summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2019-02-13 15:05:36 +0100
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2019-02-14 10:33:47 +0000
commite684a3455bcc29a6e3e66a004e352dea4e1141e7 (patch)
treed55b4003bde34d7d05f558f02cfd82b2a66a7aac /chromium/third_party/blink/renderer
parent2b94bfe47ccb6c08047959d1c26e392919550e86 (diff)
downloadqtwebengine-chromium-e684a3455bcc29a6e3e66a004e352dea4e1141e7.tar.gz
BASELINE: Update Chromium to 72.0.3626.110 and Ninja to 1.9.0
Change-Id: Ic57220b00ecc929a893c91f5cc552f5d3e99e922 Reviewed-by: Michael Brüning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/third_party/blink/renderer')
-rw-r--r--chromium/third_party/blink/renderer/DEPS6
-rw-r--r--chromium/third_party/blink/renderer/bindings/DEPS2
-rw-r--r--chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.md268
-rw-r--r--chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.txt5
-rw-r--r--chromium/third_party/blink/renderer/bindings/IDLUnionTypes.md43
-rw-r--r--chromium/third_party/blink/renderer/bindings/OWNERS2
-rw-r--r--chromium/third_party/blink/renderer/bindings/bindings.gni5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/BUILD.gn12
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/BUILD.gn26
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/activity_logger_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/binding_security.cc242
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/binding_security.h57
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.h4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_dev_tools_host_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_element_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_error_event_custom.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_event_target_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_all_collection_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_plugin_element_custom.cc36
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_channel_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_event_custom.cc17
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_pop_state_event_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_promise_rejection_event_custom.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_readable_stream_custom.cc52
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_shadow_root_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_window_custom.cc34
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_writable_stream_custom.cc52
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_xml_http_request_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/dictionary.cc11
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/dictionary_helper_for_core.cc5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/dom_wrapper_world_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h9
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/idl_types.h33
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/idl_types_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.cc91
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.h12
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.cc42
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h43
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/iterable.h6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc35
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.h8
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc28
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.h35
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.h38
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc17
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.h27
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc25
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.h6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h231
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl_test.cc269
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.cc5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.h18
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.cc74
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.h4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.h5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h35
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc23
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.h16
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_controller.cc72
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_controller.h31
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.cc110
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h65
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc101
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.h21
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc32
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_iterator.cc6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_module.cc4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_module.h2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_module_test.cc73
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_promise.cc10
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc31
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.cc23
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h31
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.cc14
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.h27
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.cc87
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.h44
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc109
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_value.cc42
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_value.h4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_marking_visitor_test.cc97
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_v8_gc_integration_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc16
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.h6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.cc8
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.h7
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc74
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h14
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_fuzzer.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/transferables.h7
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.cc68
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.h5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc99
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc325
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/use_counter_callback.cc54
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.cc83
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h4
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc62
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h41
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc29
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc68
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc1
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_controller.cc17
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.cc7
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc46
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.cc23
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h6
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_object_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc55
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.h5
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.cc10
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.h13
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/v8_wasm_response_extensions.cc197
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h16
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.cc52
-rw-r--r--chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h9
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/BUILD.gn31
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/BUILD.gn5
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/custom/v8_extendable_message_event_custom.cc13
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc31
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h2
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc36
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc61
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc56
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc62
-rw-r--r--chromium/third_party/blink/renderer/bindings/modules/v8/webgl_any.cc63
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/aggregate_generated_bindings.py3
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/code_generator.py3
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/code_generator_v8.py36
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/code_generator_web_agent_api.py5
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/compute_global_objects.py36
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py2
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py10
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/generate_global_constructors.py14
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/generate_init_partial_interfaces.py7
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py9
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py41
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py23
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/idl_compiler.py3
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/idl_definitions.py3
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/idl_types.py70
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/interface_dependency_resolver.py2
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/scripts.gni8
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/utilities.py50
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_attributes.py42
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_callback_function.py1
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py11
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_dictionary.py4
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_interface.py40
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_methods.py39
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_types.py104
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_union.py7
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/v8_utilities.py34
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/web_idl/collection.py154
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector.py18
-rwxr-xr-xchromium/third_party/blink/renderer/bindings/scripts/web_idl/collector_test.py180
-rw-r--r--chromium/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py2
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/attributes.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/attributes.cpp.tmpl)221
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/callback_function.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/callback_function.cpp.tmpl)0
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/callback_function.h.tmpl19
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/callback_interface.cpp.tmpl)15
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl27
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/callback_invoke.cc.tmpl4
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/constants.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/constants.cpp.tmpl)26
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.cpp.tmpl)8
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl15
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/dictionary_impl_common.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/dictionary_impl_common.cpp.tmpl)0
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.cpp.tmpl)63
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.h.tmpl16
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cc.tmpl122
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cpp.tmpl117
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/interface.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/interface.cpp.tmpl)601
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/interface.h.tmpl138
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/interface_base.cpp.tmpl)387
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/methods.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/methods.cpp.tmpl)237
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl8
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.h.tmpl7
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl4
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.h.tmpl7
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/partial_interface.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/partial_interface.cpp.tmpl)8
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/partial_interface.h.tmpl40
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/templates.gni28
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/union_container.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl)76
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/union_container.h.tmpl6
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/utilities.cc.tmpl (renamed from chromium/third_party/blink/renderer/bindings/templates/utilities.cpp.tmpl)2
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.cc.tmpl2
-rw-r--r--chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.h.tmpl7
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py8
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py7
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py (renamed from chromium/third_party/blink/renderer/build/scripts/make_css_primitive_value_unit_trie.py)4
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py (renamed from chromium/third_party/blink/renderer/build/scripts/make_css_property_names.py)8
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py (renamed from chromium/third_party/blink/renderer/build/scripts/make_css_tokenizer_codepoints.py)6
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py (renamed from chromium/third_party/blink/renderer/build/scripts/make_css_value_id_mappings.py)6
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py7
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py7
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_media_features.py4
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py9
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/parser/templates/at_rule_descriptors.h.tmpl2
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property.h.tmpl2
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.cc.tmpl4
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.cc.tmpl4
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.h.tmpl2
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/style_builder_functions.tmpl14
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_primitive_value_unit_trie.cc.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/css_primitive_value_unit_trie.cc.tmpl)0
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_property_names.cc.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/css_property_names.cc.tmpl)3
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_property_names.h.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/css_property_names.h.tmpl)6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_id_mappings_generated.h.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/css_value_id_mappings_generated.h.tmpl)8
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_keywords.h.tmpl11
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/cssom_types.cc.tmpl6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/media_features.h.tmpl8
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.h.tmpl10
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py (renamed from chromium/third_party/blink/renderer/build/scripts/make_computed_style_base.py)10
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.cc.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base.cc.tmpl)2
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.h.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base.h.tmpl)6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base_constants.h.tmpl (renamed from chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base_constants.h.tmpl)6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/gperf.py2
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/json5_generator.py2
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_element_lookup_trie.py6
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_element_type_helpers.py4
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_event_factory.py13
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/make_instrumenting_probes.py12
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py1
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_internal_settings.py8
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_names.py17
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_origin_trials.py1
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_qualified_names.py7
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_runtime_features.py5
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/make_settings.py1
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/media_feature_symbol.py17
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/name_utilities.py8
-rwxr-xr-xchromium/third_party/blink/renderer/build/scripts/rule_bison.py11
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/element_lookup_trie.cc.tmpl4
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/element_type_helpers.h.tmpl2
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/event_factory.cc.tmpl12
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_inl.h.tmpl6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/internal_runtime_flags.h.tmpl15
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl10
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl26
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/make_names.h.tmpl8
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl68
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.h.tmpl17
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl11
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl17
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl7
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl11
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features_test_helpers.h.tmpl8
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/settings_macros.h.tmpl6
-rw-r--r--chromium/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl4
-rw-r--r--chromium/third_party/blink/renderer/controller/blink_initializer.cc29
-rw-r--r--chromium/third_party/blink/renderer/controller/blink_leak_detector.cc4
-rw-r--r--chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.cc4
-rw-r--r--chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/controller/oom_intervention_impl.cc52
-rw-r--r--chromium/third_party/blink/renderer/controller/oom_intervention_impl.h5
-rw-r--r--chromium/third_party/blink/renderer/controller/oom_intervention_impl_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/BUILD.gn108
-rw-r--r--chromium/third_party/blink/renderer/core/DEPS6
-rw-r--r--chromium/third_party/blink/renderer/core/OWNERS2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/README.md10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation.h6
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_effect.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_effect.h8
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_effect_test.cc138
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_input_helpers.cc190
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_input_helpers.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_sim_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/color_property_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/compositor_animations.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/animation/compositor_animations.h1
-rw-r--r--chromium/third_party/blink/renderer/core/animation/compositor_animations_test.cc100
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animatable_value_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animations.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animations_test.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_transition_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_basic_shape_interpolation_type.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_font_size_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_interpolation_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_interpolation_types_map.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_length_interpolation_type.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_paint_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_transform_origin_interpolation_type.h9
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_animations.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_timeline.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_timeline.h5
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_timeline_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/effect_input.cc95
-rw-r--r--chromium/third_party/blink/renderer/core/animation/effect_model.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/effect_stack_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/animation/element_animation.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/image_list_property_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/image_slice_property_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/inert_effect.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/animation/inert_effect.h10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect.h11
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.h18
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_test.cc84
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_list_property_functions.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_property_functions.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/number_property_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/property_handle.h10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/property_handle_test.cc70
-rw-r--r--chromium/third_party/blink/renderer/core/animation/sampled_effect.h6
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc204
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline.h34
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline_test.cc172
-rw-r--r--chromium/third_party/blink/renderer/core/animation/size_list_property_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/svg_interpolation_types_map.cc178
-rw-r--r--chromium/third_party/blink/renderer/core/animation/svg_number_interpolation_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/test_data/raf-countdown.html1
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_input.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_input.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_input_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/aom/accessible_node.cc194
-rw-r--r--chromium/third_party/blink/renderer/core/aom/accessible_node.h14
-rw-r--r--chromium/third_party/blink/renderer/core/aom/computed_accessible_node.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_object.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_object.h3
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_object_item.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_object_item.h6
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_object_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer.h4
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.h4
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.h4
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/core_idl_files.gni18
-rw-r--r--chromium/third_party/blink/renderer/core/core_initializer.cc72
-rw-r--r--chromium/third_party/blink/renderer/core/core_initializer.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/BUILD.gn17
-rw-r--r--chromium/third_party/blink/renderer/core/css/OWNERS5
-rw-r--r--chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/active_style_sheets_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/affected_by_pseudo_test.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/computed_style_field_aliases.json52
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_basic_shape_values.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_basic_shape_values.h26
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_border_image_slice_value.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_calculation_value.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_calculation_value.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_color_value.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_color_value.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_computed_style_declaration_test.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_content_distribution_value.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_counter_value.h19
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_crossfade_value.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_cursor_image_value.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_custom_ident_value.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_custom_property_declaration.h37
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_default_style_sheets.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_rule.idl7
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_source.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_src_value.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_src_value.h52
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_family_value.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_family_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_feature_value.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.h52
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_selector.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_style_range_value.h27
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_variation_value.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_function_value.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_global_rule_set.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_gradient_value.h101
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_grid_auto_repeat_value.h14
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_grid_line_names_value.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_grid_template_areas_value.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_identifier_value.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_identifier_value.h26
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_set_value.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_set_value.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_value.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_value.h16
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_import_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_initial_value.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.h35
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_invalid_variable_value_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframe_rule.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframes_rule.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframes_rule.h18
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_layout_function_value.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_media_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_namespace_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_page_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_page_rule_test.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_image_generator.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_value.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_value.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_value_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_path_value.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_path_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_pending_substitution_value.h18
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value.h30
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value_mappings.h32
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value_test.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_properties.json590
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_equality.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_id_templates.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_name.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_name.h44
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_name_test.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_value.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_value_set.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_value_set.h28
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_value_set_test.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_quad_value.h28
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_ray_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_ray_value.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_reflect_value.h18
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_rule.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_rule.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_rule_list.h14
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_segmented_font_face.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_list.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_list.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_watch.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_watch.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_watch_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_shadow_value.h18
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_string_value.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_declaration.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_declaration.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_declaration.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_declaration_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_rule.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_sheet.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_sheet.h13
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_sheet_test.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_supports_rule.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_component.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_component.h68
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.cc105
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.h47
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_test_helper.cc76
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_test_helper.h69
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_test_helpers.cc73
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_test_helpers.h52
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_timing_function_value.h44
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_unicode_range_value.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_uri_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_uri_value.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_id_mappings.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_keywords.json56
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_list.h16
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_pair.h25
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_pool.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_pool.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_variable_reference_value.h28
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_viewport_rule.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.h18
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_invert.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_max.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_max.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_min.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_min.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_negate.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_product.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_product.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_array.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_perspective.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_perspective.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_position_value.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_position_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_rotate.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_rotate.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_scale.h15
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_skew.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_skew.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_style_value.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_translate.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_translate.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.h14
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.h24
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/cssom_keywords.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/cssom_types.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map.cc156
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h46
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc (renamed from chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc)59
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h59
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/document_style_sheet_collection.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/drag_update_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/element_rule_collector.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_display.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_display.h25
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face.h21
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_cache.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set.h24
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_document.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_load_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_load_event.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_worker.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_worker.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/invalidation/style_invalidator.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/keyframe_style_rule_css_style_declaration.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_feature_names.json52
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_list.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_evaluator.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_evaluator_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_exp.cc212
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_list.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_list.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_list_event.h49
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_matcher.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_matcher.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_matcher_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_type_names.json52
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_cached.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_cached.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_dynamic.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_dynamic.h13
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/offscreen_font_selector.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.h25
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_context.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_context.h51
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths_fuzzer.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.h19
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.h38
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context_test.cc89
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_selector.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_token.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_token.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc115
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h13
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc107
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.cc379
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc267
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_variable_parser.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/font_variant_east_asian_parser.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/font_variant_ligatures_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/media_query_parser.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/sizes_attribute_parser_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/README.md2
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc650
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.h39
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property_ref.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property_ref.h78
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property_ref_test.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/align_content_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/align_items_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/align_self_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/alignment_baseline_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_delay_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_duration_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/animation_timing_function_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/backdrop_filter_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/backface_visibility_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_attachment_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_blend_mode_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_clip_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_image_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_origin_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_x_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_y_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/background_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/baseline_shift_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/block_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_color_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_left_radius_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_right_radius_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_collapse_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_outset_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_repeat_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_slice_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_source_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_color_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_color_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_color_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_left_radius_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_right_radius_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/bottom_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/box_shadow_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/box_sizing_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/break_after_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/break_before_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/break_inside_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/buffered_rendering_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/caption_side_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/caret_color_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/clear_custom.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/clip_custom.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/clip_path_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/clip_rule_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/color_rendering_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_count_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_fill_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_gap_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_span_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/column_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/contain_custom.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/content_custom.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/counter_increment_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/counter_reset_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/cursor_custom.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc144
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.h65
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property_test.cc197
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/cx_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/cy_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/d_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/direction_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/display_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/dominant_baseline_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/empty_cells_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/fill_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/fill_opacity_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/fill_rule_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/filter_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flex_basis_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flex_direction_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flex_grow_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flex_shrink_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flex_wrap_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/float_custom.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flood_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/flood_opacity_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_family_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_kerning_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_adjust_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_stretch_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_style_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_caps_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_east_asian_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_ligatures_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_numeric_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/font_weight_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_columns_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_flow_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_rows_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_end_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_start_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_end_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_start_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_areas_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_columns_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_rows_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/height_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/hyphens_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/image_orientation_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/image_rendering_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/inline_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_end_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_start_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_end_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_start_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/isolation_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/justify_content_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/justify_items_custom.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/justify_self_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/left_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/letter_spacing_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/lighting_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/line_break_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_step_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_image_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_position_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_type_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_end_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_start_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_bottom_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_end_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_start_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_left_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_right_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/margin_top_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/marker_end_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/marker_mid_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/marker_start_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/mask_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/mask_source_type_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/mask_type_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/max_block_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/max_height_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/max_inline_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/max_width_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/min_block_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/min_height_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/min_inline_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/min_width_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/object_fit_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/object_position_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/offset_anchor_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/offset_distance_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/offset_path_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/offset_position_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/offset_rotate_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/opacity_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/order_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/orphans_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/outline_color_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/outline_offset_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/outline_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/outline_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_anchor_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_wrap_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_x_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_y_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_bottom_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_left_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_right_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/padding_top_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/page_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/paint_order_custom.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_origin_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/pointer_events_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/position_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/quotes_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/r_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/resize_custom.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/right_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/rotate_custom.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/row_gap_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/rx_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/ry_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scale_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_behavior_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_customization_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_bottom_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_left_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_right_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_top_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_bottom_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_left_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_right_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_top_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_align_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_type_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/shape_image_threshold_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/shape_margin_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/shape_outside_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/shape_rendering_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/size_custom.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/speak_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stop_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stop_opacity_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dasharray_custom.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dashoffset_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linecap_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_miterlimit_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_opacity_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_width_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/tab_size_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/table_layout_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_last_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_anchor_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_combine_upright_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_line_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_skip_ink_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_indent_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_justify_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_orientation_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_overflow_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_rendering_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_shadow_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_size_adjust_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_transform_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/text_underline_position_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/top_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/touch_action_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transform_box_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transform_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transform_origin_custom.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transform_style_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transition_delay_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transition_duration_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transition_property_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/transition_timing_function_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/translate_custom.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/unicode_bidi_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/user_select_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/variable.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/variable.h16
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/vector_effect_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/vertical_align_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/visibility_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_app_region_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_appearance_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_horizontal_spacing_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_image_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_align_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_decoration_break_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_flex_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_ordinal_group_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_reflect_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_size_delta_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_smoothing_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_highlight_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_hyphenate_character_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_break_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_clamp_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_locale_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_outset_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_repeat_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_slice_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_source_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_clip_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_composite_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_image_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_origin_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_x_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_y_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_size_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_x_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_y_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_tap_highlight_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_combine_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_decorations_in_effect_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_position_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_style_custom.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_fill_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_orientation_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_security_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_width_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_x_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_y_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_z_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/white_space_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/widows_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/width_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/will_change_custom.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/word_break_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/word_spacing_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/writing_mode_custom.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/x_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/y_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/z_index_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/zoom_custom.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/background_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/background_position_custom.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/background_repeat_custom.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_custom.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_style_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_bottom_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_image_custom.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_color_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_custom.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_end_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_start_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_style_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_left_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_radius_custom.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_right_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_spacing_custom.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_style_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_top_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/border_width_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/column_rule_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/columns_custom.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_custom.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_flow_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/font_custom.cc120
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/font_variant_custom.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/gap_custom.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_area_custom.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_custom.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_gap_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_custom.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_gap_custom.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_custom.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_gap_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_template_custom.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_block_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_inline_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/list_style_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_block_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_inline_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/marker_custom.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/offset_custom.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/outline_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/overflow_custom.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/overscroll_behavior_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_block_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_inline_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_after_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_before_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_inside_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/place_content_custom.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/place_items_custom.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/place_self_custom.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_block_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_inline_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_block_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_inline_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/text_decoration_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_after_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_before_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_inside_custom.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_margin_collapse_custom.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_box_image_custom.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_custom.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_position_custom.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_repeat_custom.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_emphasis_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_stroke_custom.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/style_building_utils.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registration.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registration.h15
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registry.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registry.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/remote_font_face_source.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/animated_style_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_property_priority.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_to_style_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc106
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.h28
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/font_builder.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/match_result_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h15
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder.h16
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc105
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver.cc108
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver.h17
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_feature_set.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_feature_set.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_feature_set_test.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_set.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_set.h52
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_set_test.cc252
-rw-r--r--chromium/third_party/blink/renderer/core/css/selector_checker.cc43
-rw-r--r--chromium/third_party/blink/renderer/core/css/selector_checker.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/selector_query.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/selector_query_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/shadow_tree_style_sheet_collection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_change_reason.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_change_reason.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_color.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine.cc138
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine.h36
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine_test.cc305
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_environment_variables_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_media.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule.h124
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_import.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_import.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_keyframe.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_namespace.h10
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_candidate.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_collection.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_contents.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_contents.h22
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_contents_fuzzer.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_contents_test.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_list.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_list.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_traversal_root_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/threaded/css_parser_threaded_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/threaded/css_to_length_conversion_data_threaded_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/threaded/font_object_threaded_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h2
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_context.cc429
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_context.h129
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_context.idl18
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.h34
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.idl8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/abort_signal.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/abort_signal.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/attr.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/character_data.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/character_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/child_list_mutation_scope.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/container_node.cc131
-rw-r--r--chromium/third_party/blink/renderer/core/dom/container_node.h1
-rw-r--r--chromium/third_party/blink/renderer/core/dom/context_features_client_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dataset_dom_string_map.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document.cc731
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document.h129
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_and_element_event_handlers.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_fragment.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_fragment.h3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_init.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_lifecycle.h3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_parser_timing.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_parser_timing.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_statistics_collector.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_test.cc141
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_type.h13
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_exception.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_exception.h10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_implementation.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_implementation.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_string_list.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_token_list.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element.cc911
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element.h91
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element.idl17
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_data.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_data_cache.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_rare_data.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_rare_data.h38
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_test.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_traversal.h13
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_visibility_observer_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/empty_node_list.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/README.md11
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.h14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/custom_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/custom_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event.h53
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_dispatcher.cc57
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_listener.h25
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_listener_map.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_listener_map.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_path.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_path.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_path_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_queue.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_queue.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target.cc171
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target.h104
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target_impl.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/listener_leak_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/node_event_context.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/node_event_context.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/scoped_event_queue.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.h20
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/window_event_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.cc62
-rw-r--r--chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.h51
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.h14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/global_event_handlers.h159
-rw-r--r--chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/idle_deadline.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/idle_deadline.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/idle_deadline_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/live_node_list_base.h21
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.h9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.h10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/name_node_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/name_node_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/named_node_map.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/named_node_map.h12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/names_map.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/dom/names_map_test.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node.cc381
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node.h70
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_iterator.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_iterator.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_lists_node_data.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_rare_data.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_rare_data.h30
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/nth_index_cache.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/dom/pausable_object_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/presentation_attribute_style.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/processing_instruction.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/dom/processing_instruction.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/pseudo_element.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/dom/pseudo_element.h7
-rw-r--r--chromium/third_party/blink/renderer/core/dom/pseudo_element_data.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/qualified_name.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/range.cc62
-rw-r--r--chromium/third_party/blink/renderer/core/dom/range.h19
-rw-r--r--chromium/third_party/blink/renderer/core/dom/range_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_animation_controller_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h13
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_dom_v0_test.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_root.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_root.h10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_root_v0.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/dom/sink_document.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/sink_document.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/slot_assignment.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/slot_assignment.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/slot_assignment_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/space_split_string.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/static_node_list.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/static_range.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/static_range.h26
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tag_collection.h23
-rw-r--r--chromium/third_party/blink/renderer/core/dom/template_content_document_fragment.h9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text.h7
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_ordered_map.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_ordered_map.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_scope.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_scope_adopter_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_scope_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_walker.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/v0_insertion_point.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/visited_link_state.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/visited_link_state.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/dom/whitespace_attacher_test.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/dom/xml_document.h10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/BUILD.gn3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/caret_display_item_client_test.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/apply_style_command.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/break_blockquote_command.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/delete_from_text_node_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.h13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/drag_and_drop_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/editing_commands_utilities.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/editor_command.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/format_block_command.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/format_block_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.h3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_into_text_node_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_list_command_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_node_before_command.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.h9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_text_command_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/merge_identical_elements_command.h7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/remove_css_property_command.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/remove_node_command.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/remove_node_preserving_children_command.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc101
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.h13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command.h9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/set_node_attribute_command.h9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/simplify_markup_command.h7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/split_element_command.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/split_element_command.h7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/split_text_node_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.h7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/typing_command.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/typing_command.h23
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/typing_command_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/undo_stack.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/undo_stack.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/undo_step.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/undo_step.h10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/unlink_command.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/wrap_contents_in_dummy_span_command.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/compute_layer_selection_test.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/editing/dom_selection.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/editing/dom_selection.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/drag_caret.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/drag_caret.h3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_behavior.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style.cc102
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style.h24
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style_utilities.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_utilities.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_utilities.h29
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_utilities_test.cc56
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editor.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editor.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/element_inner_text.cc417
-rw-r--r--chromium/third_party/blink/renderer/core/editing/element_inner_text_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.cc293
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.h117
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/text_finder.cc335
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/text_finder.h84
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/text_finder_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_caret.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_caret_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_selection.cc132
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_selection.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_selection_test.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/editing/granularity_strategy.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/editing/granularity_strategy_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.h5
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.h14
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc118
-rw-r--r--chromium/third_party/blink/renderer/core/editing/inline_box_traversal.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/input_mode_names.json52
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/character_iterator_test.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_iterator.cc56
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc188
-rw-r--r--chromium/third_party/blink/renderer/core/editing/layout_selection.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/editing/layout_selection.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/layout_selection_test.cc194
-rw-r--r--chromium/third_party/blink/renderer/core/editing/link_selection_test.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/editing/local_caret_rect.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/editing/local_caret_rect.h5
-rw-r--r--chromium/third_party/blink/renderer/core/editing/local_caret_rect_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller_test.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_list_impl_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/sorted_document_marker_list_editor_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_list_impl_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.h3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/unsorted_document_marker_list_editor_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_adjuster.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_controller.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_controller.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_controller_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_editor.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_editor.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_modifier.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_modifier.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc86
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/serialization.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_accumulator.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/cold_mode_spell_check_requester.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/hot_mode_spell_check_requester.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller_test.cc56
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/state_machine_util_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc108
-rw-r--r--chromium/third_party/blink/renderer/core/editing/testing/editing_test_base.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/editing/testing/selection_sample_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_offset_mapping.cc156
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_offset_mapping.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc92
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_segments.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_segments.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_position.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_position_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_selection_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units.cc149
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units.h44
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_paragraph.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_sentence.cc148
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_sentence_test.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_word.cc160
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_word_test.cc161
-rw-r--r--chromium/third_party/blink/renderer/core/editing/web_substring_util.mm2
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_playback_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_playback_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/application_cache_error_event.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/events/application_cache_error_event.h8
-rw-r--r--chromium/third_party/blink/renderer/core/events/before_text_inserted_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/events/before_unload_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/clipboard_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/events/clipboard_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/composition_event.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/events/composition_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/drag_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/drag_event.h26
-rw-r--r--chromium/third_party/blink/renderer/core/events/error_event.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/events/error_event.h34
-rw-r--r--chromium/third_party/blink/renderer/core/events/event_target_names.json565
-rw-r--r--chromium/third_party/blink/renderer/core/events/event_type_names.json53
-rw-r--r--chromium/third_party/blink/renderer/core/events/event_util.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/events/event_util.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/focus_event.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/events/focus_event.h28
-rw-r--r--chromium/third_party/blink/renderer/core/events/gesture_event.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/events/gesture_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/hash_change_event.h43
-rw-r--r--chromium/third_party/blink/renderer/core/events/input_event.cc76
-rw-r--r--chromium/third_party/blink/renderer/core/events/input_event.h8
-rw-r--r--chromium/third_party/blink/renderer/core/events/keyboard_event.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/events/keyboard_event.h15
-rw-r--r--chromium/third_party/blink/renderer/core/events/message_event.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/events/message_event.h78
-rw-r--r--chromium/third_party/blink/renderer/core/events/mouse_event.cc109
-rw-r--r--chromium/third_party/blink/renderer/core/events/mouse_event.h33
-rw-r--r--chromium/third_party/blink/renderer/core/events/mutation_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/mutation_event.h29
-rw-r--r--chromium/third_party/blink/renderer/core/events/page_transition_event.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/events/page_transition_event.h17
-rw-r--r--chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.h10
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event.cc116
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event.h33
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_factory.cc268
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_factory.h31
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_factory_test.cc83
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_init.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/events/pop_state_event.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/events/pop_state_event.h10
-rw-r--r--chromium/third_party/blink/renderer/core/events/progress_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/events/progress_event.h26
-rw-r--r--chromium/third_party/blink/renderer/core/events/promise_rejection_event.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/events/promise_rejection_event.h12
-rw-r--r--chromium/third_party/blink/renderer/core/events/resource_progress_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/resource_progress_event.h17
-rw-r--r--chromium/third_party/blink/renderer/core/events/security_policy_violation_event.cc56
-rw-r--r--chromium/third_party/blink/renderer/core/events/security_policy_violation_event.h22
-rw-r--r--chromium/third_party/blink/renderer/core/events/security_policy_violation_event.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/events/security_policy_violation_event_init.idl28
-rw-r--r--chromium/third_party/blink/renderer/core/events/text_event.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/events/text_event.h25
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event.h30
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event_context.h5
-rw-r--r--chromium/third_party/blink/renderer/core/events/transition_event.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/events/transition_event.h27
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event.h41
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.h6
-rw-r--r--chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.h6
-rw-r--r--chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.h6
-rw-r--r--chromium/third_party/blink/renderer/core/events/web_input_event_conversion.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/events/web_input_event_conversion_test.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/events/wheel_event.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/events/wheel_event.h14
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/execution_context.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/execution_context.h25
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/remote_security_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/remote_security_context.h5
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/security_context.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/security_context.h31
-rw-r--r--chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.cc128
-rw-r--r--chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.h25
-rw-r--r--chromium/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/exported/prerendering_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_blob.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc155
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h29
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.h20
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_dom_message_event.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_element_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_form_control_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_form_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_form_element_observer_impl.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_test.cc2223
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_history_item.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_hit_test_result.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_input_element.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_language_detection_details.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_layer_test.cc653
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_meaningful_layouts_test.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_node.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_node_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_performance.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.h5
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_plugin_container_test.cc229
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_range.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.h6
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_searchable_form_data.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_security_policy.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_settings_impl.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_settings_impl.h5
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.h6
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_view_impl.cc243
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_view_impl.h70
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_view_test.cc473
-rw-r--r--chromium/third_party/blink/renderer/core/exported/worker_shadow_page.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/exported/worker_shadow_page.h1
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy.cc72
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy.h12
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_test.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/iframe_policy.h4
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.h38
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/policy_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/blob_bytes_consumer.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body.h5
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.cc150
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.h24
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/bytes_consumer.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h5
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.h5
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h39
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer_test.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_data_loader.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_header_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_header_list.h4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc110
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_manager.h5
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_request_data.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_request_data.h22
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_response_data.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_response_data.h12
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_response_data_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h13
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/global_fetch.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/global_fetch.h6
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/headers.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/headers.h10
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/multipart_parser.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/multipart_parser_test.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer_test.cc268
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/request.cc267
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/request.h18
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/request_test.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/response.cc110
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/response.h14
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/response.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/response_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/blob.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/blob.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file.h77
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_error.cc70
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_error.h12
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_list.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_list.h8
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_list_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader.h19
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.h6
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_loader_client.h5
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.h6
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/public_url_manager.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/public_url_manager.h4
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/public_url_manager_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/BUILD.gn12
-rw-r--r--chromium/third_party/blink/renderer/core/frame/ad_tracker.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/frame/ad_tracker.h19
-rw-r--r--chromium/third_party/blink/renderer/core/frame/ad_tracker_test.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/frame/browser_controls.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/frame/browser_controls_test.cc603
-rw-r--r--chromium/third_party/blink/renderer/core/frame/content_settings_client.cc147
-rw-r--r--chromium/third_party/blink/renderer/core/frame/content_settings_client.h115
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.cc96
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.h4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/media_list_directive_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deferred_loading_test.cc519
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deprecation.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deprecation.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deprecation_report_body.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/device_single_window_event_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/document_loading_rendering_test.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer.h13
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.h9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_window.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_window.h15
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_window_base64.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_window_base64.h50
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_window_timers.h86
-rw-r--r--chromium/third_party/blink/renderer/core/frame/event_handler_registry.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/frame/event_handler_registry.h8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.h13
-rw-r--r--chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/frame/find_in_page.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/find_in_page.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/find_in_page_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame.h27
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_console.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_owner.h17
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_serializer.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_serializer_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_test_helpers.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_test_helpers.h18
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_view_auto_size_info.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/fullscreen_controller.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/history.cc51
-rw-r--r--chromium/third_party/blink/renderer/core/frame/history.h19
-rw-r--r--chromium/third_party/blink/renderer/core/frame/intervention.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/intervention_report_body.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/link_highlights.h8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_dom_window.cc125
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_dom_window.h37
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame.h26
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_client.h34
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_test.cc178
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc106
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h68
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc123
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_view.cc395
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_view.h45
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_view_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/location.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/mhtml_archive_test.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/frame/mhtml_loading_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.h42
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator.h9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator_concurrent_hardware.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator_user_activation.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator_user_activation.h4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/pausable_script_executor.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/frame/pausable_script_executor.h16
-rw-r--r--chromium/third_party/blink/renderer/core/frame/pausable_task.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/pausable_task.h5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/performance_monitor.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/performance_monitor_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/platform_event_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_dom_window.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame.h3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame_owner.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame_owner.h26
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame_view.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame_view.h3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/report.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/report_body.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/reporting_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/reporting_observer.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/frame/reporting_observer.h12
-rw-r--r--chromium/third_party/blink/renderer/core/frame/reporting_observer.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/root_frame_viewport.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/frame/root_frame_viewport.h9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/root_frame_viewport_test.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/frame/screen.h9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/settings.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/frame/settings.h10
-rw-r--r--chromium/third_party/blink/renderer/core/frame/settings.json58
-rw-r--r--chromium/third_party/blink/renderer/core/frame/smart_clip.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/use_counter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/use_counter_test.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/frame/user_activation.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/frame/user_activation.h3
-rw-r--r--chromium/third_party/blink/renderer/core/frame/visual_viewport.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/visual_viewport.h9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/visual_viewport_test.cc463
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.h17
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc74
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.h12
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.cc123
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.h105
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.h11
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window.idl22
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_base64.idl36
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_event_handlers.h (renamed from chromium/third_party/blink/renderer/core/frame/dom_window_event_handlers.h)49
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_event_handlers.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc (renamed from chromium/third_party/blink/renderer/core/frame/dom_window_timers.cc)147
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h116
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl (renamed from chromium/third_party/blink/renderer/core/frame/window_timers.idl)23
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h10
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h14
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/fullscreen.h6
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_matrix.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_matrix.h16
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc153
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h60
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_matrix_test.cc184
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_point.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_point.h7
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.h8
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_quad.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_quad.h24
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_rect.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_rect.h7
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_rect_list.h18
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/BUILD.gn7
-rw-r--r--chromium/third_party/blink/renderer/core/html/anchor_element_metrics.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/OWNERS2
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc160
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h39
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_image_source.h1
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.cc86
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h19
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc154
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_data.cc122
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_data.h20
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_data_color_settings.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_data_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_element_base.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_element_base.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/text_metrics.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/text_metrics.h14
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/README.md2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.h20
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_descriptor.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.h32
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_queue_test.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack_test.cc119
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.idl9
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_registry_test.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.h22
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/element_internals.cc117
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/element_internals.h60
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/element_internals.idl16
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_async_import_microtask_queue.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_run_queue.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_observer.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registry.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_scheduler.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_sync_microtask_queue.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/document_all_name_collection.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/html/document_all_name_collection.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/document_name_collection.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_button_input_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_checkable_input_type.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_text_input_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/button_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/checkbox_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/clear_button_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/color_input_type.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_input_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_field_element.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.h26
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_symbolic_field_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/email_input_type.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/email_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_popup_menu.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_chooser.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_chooser.h36
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_input_type.cc149
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_input_type.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_input_type_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_controller.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_controller.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data.h17
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data_event.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data_event.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_button_element.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_button_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.cc95
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_element.cc86
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_element.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_input_element.cc213
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_input_element.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_input_element_test.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_label_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_label_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_legend_element.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_legend_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_option_element.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_option_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_options_collection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_options_collection.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_output_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_output_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_output_element_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element.cc113
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element_test.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.cc57
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/image_input_type.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/image_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/input_type.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/input_type_names.json52
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/input_type_view.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/keyboard_clickable_input_type_view.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/labels_node_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/labels_node_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/listed_element.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/listed_element.h24
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/mock_file_chooser.h78
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/month_input_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/month_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/number_input_type.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/number_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/option_list_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/password_input_type.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/password_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/password_input_type_test.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/radio_button_group_scope.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/radio_input_type.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/radio_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/radio_node_list.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/radio_node_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/range_input_type.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/range_input_type.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/reset_input_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/reset_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.css4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.css2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.js12
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/pickerButton.css4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/validation_bubble.css2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/search_input_type.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/search_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/spin_button_element.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/spin_button_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/step_range.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/submit_input_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/submit_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_element.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_element.h1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_element_test.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.h15
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_field_input_type.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_input_type.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/time_input_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/time_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/url_input_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/url_input_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/validity_state.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/week_input_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/week_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_all_collection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_all_collection.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_anchor_element.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_anchor_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_anchor_element.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_area_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_area_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_attribute_names.json55
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_base_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_bdi_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_body_element.cc130
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_body_element.h14
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_br_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_collection.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_collection.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_content_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_content_element_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_data_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_data_element.h1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_details_element.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_details_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_dialog_element.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_directory_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_div_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_dlist_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_document.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_document.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_element.cc599
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_element.h15
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_element_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_embed_element.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_embed_element.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_embed_element_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_font_element.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_element.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_element_base.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_element_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_owner_element.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_owner_element.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_set_element.cc115
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_set_element.h14
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_head_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_hr_element.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_html_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element_test.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_element.cc122
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_element_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_loader.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_loader.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_li_element.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_link_element.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_link_element.h10
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_link_element.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_link_element_sizes_attribute_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_map_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_marquee_element.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_marquee_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_menu_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meta_element.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meter_element.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meter_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_mod_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_no_embed_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_no_script_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_object_element.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_object_element.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_object_element_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_olist_element.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_paragraph_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_param_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_picture_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_plugin_element.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_plugin_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_pre_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_progress_element.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_progress_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_quote_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_quote_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_rt_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_ruby_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_script_element.cc88
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_script_element.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_script_element.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_shadow_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_slot_element.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_slot_element.h22
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_slot_element_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_source_element.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_source_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_span_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_style_element.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_style_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_summary_element.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_summary_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_caption_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_cell_element.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_cell_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_col_element.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_col_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_element.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_part_element.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_row_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_rows_collection.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_rows_collection.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_section_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_section_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_tag_collection.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_template_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_time_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_time_element.h1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_title_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_ulist_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_unknown_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_view_source_document.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_view_source_document.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_wbr_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/image_document.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/html/image_document.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/image_document_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_import_loader.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_import_loader.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/link_import.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer_test.cc208
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_manifest.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_manifest.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_rel_attribute.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_resource.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_style.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_style.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/list_item_ordinal_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/autoplay_policy.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_audio_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_audio_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element.cc229
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element.h29
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element_event_listeners_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element.cc58
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element_persistent_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector_test.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_document.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_document.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_error.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/html/media_element_filling_viewport_test.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/background_html_parser.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_construction_site.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_document_parser.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_document_parser.h17
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_document_parser_loading_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_element_stack.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_element_stack.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_meta_charset_parser.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc279
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_fuzzer.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc246
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_stack_item.h200
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tokenizer.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tokenizer_names.json512
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.cc723
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.h28
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.cc183
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.h1
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_view_source_parser.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/preload_request.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/preload_request.h22
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/text_document_parser.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/text_document_parser.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_for_fuzzing.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/xss_auditor.cc124
-rw-r--r--chromium/third_party/blink/renderer/core/html/plugin_document.cc43
-rw-r--r--chromium/third_party/blink/renderer/core/html/plugin_document.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/document_portals.cc51
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/document_portals.h43
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/html_portal_element.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/html_portal_element.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/rel_list.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/rel_list.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/android.css (renamed from chromium/third_party/blink/renderer/core/css/themeChromiumAndroid.css)0
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/html.css (renamed from chromium/third_party/blink/renderer/core/css/html.css)173
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/input_multiple_fields.css (renamed from chromium/third_party/blink/renderer/core/css/themeInputMultipleFields.css)4
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/linux.css (renamed from chromium/third_party/blink/renderer/core/css/themeChromiumLinux.css)0
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/mac.css (renamed from chromium/third_party/blink/renderer/core/css/themeMac.css)0
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/quirks.css (renamed from chromium/third_party/blink/renderer/core/css/quirks.css)0
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/win.css (renamed from chromium/third_party/blink/renderer/core/css/themeWin.css)6
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/win_quirks.css (renamed from chromium/third_party/blink/renderer/core/css/themeWinQuirks.css)4
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/text_document.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/time_ranges.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/audio_track_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/cue_timeline.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/html_track_element.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/inband_text_track.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/inband_text_track.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/loadable_text_track.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/loadable_text_track.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track.h20
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_container.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_container.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_cue.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_cue.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_list.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_list.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/track_event.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/track_event.h21
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/track_list_base.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/video_track.h16
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/video_track_list.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/video_track_list.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h30
-rw-r--r--chromium/third_party/blink/renderer/core/html/window_name_collection.h7
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/OWNERS2
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc193
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.h116
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc105
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h49
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.idl54
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_options.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h2
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc57
-rw-r--r--chromium/third_party/blink/renderer/core/input/boundary_event_dispatcher.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handler.cc172
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handler.h19
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handler_test.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handling_util.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handling_util.h13
-rw-r--r--chromium/third_party/blink/renderer/core/input/gesture_manager.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/input/ime_on_focus_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/input/input_device_capabilities.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/input/input_device_capabilities.h12
-rw-r--r--chromium/third_party/blink/renderer/core/input/keyboard_event_manager.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/input/mouse_event_manager.cc180
-rw-r--r--chromium/third_party/blink/renderer/core/input/mouse_event_manager.h5
-rw-r--r--chromium/third_party/blink/renderer/core/input/mouse_wheel_event_manager.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/input/pointer_event_manager.cc148
-rw-r--r--chromium/third_party/blink/renderer/core/input/pointer_event_manager.h17
-rw-r--r--chromium/third_party/blink/renderer/core/input/pointer_event_manager_test.cc94
-rw-r--r--chromium/third_party/blink/renderer/core/input/scroll_manager.cc184
-rw-r--r--chromium/third_party/blink/renderer/core/input/scroll_manager.h12
-rw-r--r--chromium/third_party/blink/renderer/core/input/scroll_snap_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch.h55
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_action_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_action_util.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_action_util.h4
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_event_manager.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_event_manager.h4
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_event_manager_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_list.h13
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/BUILD.gn9
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl287
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.h3
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dev_tools_host.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dev_tools_host.h5
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc306
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_agent.h58
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_session.cc315
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_session.h (renamed from chromium/third_party/blink/renderer/core/inspector/inspector_session.h)91
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dom_editor.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dom_patch_support.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h6
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.h15
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.h16
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h7
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_io_agent.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.h6
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.h8
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.h10
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.h14
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.h5
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_protocol_config.json7
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h5
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_session.cc254
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_session_state_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.h21
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.cc235
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.h131
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.cc239
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.h99
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/main_thread_debugger.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/main_thread_debugger_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/network_resources_data.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/network_resources_data.h27
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.cc77
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.h32
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_devtools_params.h22
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc164
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.h58
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.h66
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_test.cc103
-rw-r--r--chromium/third_party/blink/renderer/core/invisible_dom/activate_invisible_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/BUILD.gn14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_block_flow.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_box.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_box_model.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_inline.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_item.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_text.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/bidi_run.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/column_balancer.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/custom_layout_constraints.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_custom.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.h22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_test.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/pending_layout_registry.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.h25
-rw-r--r--chromium/third_party/blink/renderer/core/layout/floating_objects.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/layout/floating_objects.h41
-rw-r--r--chromium/third_party/blink/renderer/core/layout/fragmentation_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_cache.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_canvas_result.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_result.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/layout/intersection_geometry.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_region.cc317
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_region.h54
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_region_test.cc122
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_tracker.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_tracker.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc43
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_analyzer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_flow.cc72
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_flow.h7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_flow_line.cc138
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box.cc243
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box.h20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_model_object.cc112
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_model_object.h23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_model_object_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_button.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_counter.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_details_marker.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_embedded_object.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_fieldset.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flexible_box.cc286
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flexible_box.h9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_frame_set.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_geometry_map.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_geometry_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_grid.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_grid.h17
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_html_canvas.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image.cc128
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image.h16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image_resource.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image_resource.h7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image_resource_style_image.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_inline.cc238
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_inline.h21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_inline_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_list_item.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_list_item.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_list_marker.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_menu_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object.cc118
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object.h145
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_child_list.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_test.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_progress_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_quote.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_replaced.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_replaced_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_ruby_base.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_scrollbar.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_scrollbar.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_scrollbar_part.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_search_field.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_slider.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_slider_container.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_cell.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_cell.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_cell_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_col.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_row.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_section.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_section_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text.cc114
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text.h15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.h3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_fragment.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_fragment.h18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_default.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_linux.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm174
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_mobile.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_video.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_view.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_view.h22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_view_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/abstract_inline_text_box.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/breaking_context_inline_headers.h24
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_box.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_iterator.h37
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/line_width.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/root_inline_box.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/trailing_objects.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/list_marker_text.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/logical_values.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/layout/logical_values.h38
-rw-r--r--chromium/third_party/blink/renderer/core/layout/map_coordinates_test.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/layout/min_max_size.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.cc145
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h55
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_line_layout_opportunity.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_shape_exclusions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_location.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h44
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_rect.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h25
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/README.md4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h32
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_fragment.h40
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h149
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline_test.cc76
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_rect.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc257
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h59
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h37
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc173
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.h9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc274
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc237
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h76
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc126
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_test.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h41
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc156
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h50
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc126
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h1
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h55
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h57
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc416
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h25
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc70
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.cc215
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.h23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc268
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h268
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.cc185
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h436
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.cc118
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h282
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h78
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc120
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc121
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h30
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc384
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h283
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc118
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.h41
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc376
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.h148
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_link.h19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc91
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h34
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc93
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h44
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h40
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc89
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h29
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc91
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.h45
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/scroll_anchor_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/layout/shapes/polygon_shape.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/shapes/shape.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h1
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.h1
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter_primitive.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_gradient.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc183
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.h61
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.h1
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.cc94
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.h23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_resources.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h48
-rw-r--r--chromium/third_party/blink/renderer/core/layout/table_layout_algorithm.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/text_autosizer.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/text_autosizer.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/text_autosizer_test.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/layout/text_decoration_offset_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/traced_layout_object.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/visual_rect_mapping_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/loader/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.h9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff_test.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache.h16
-rw-r--r--chromium/third_party/blink/renderer/core/loader/base_fetch_context.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/loader/base_fetch_context.h4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/base_fetch_context_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_loader.cc203
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_loader.h41
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_loader_test.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/loader/empty_clients.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/loader/empty_clients.h74
-rw-r--r--chromium/third_party/blink/renderer/core/loader/form_submission.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/loader/form_submission.h23
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_fetch_context.cc95
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_fetch_context.h16
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_load_request.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_loader.cc161
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_loader.h16
-rw-r--r--chromium/third_party/blink/renderer/core/loader/history_item.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/history_item.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/http_equiv.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/loader/idleness_detector.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/image_loader.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/loader/image_loader.h18
-rw-r--r--chromium/third_party/blink/renderer/core/loader/interactive_detector.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/interactive_detector.h4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/interactive_detector_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/link_loader.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/loader/link_loader.h22
-rw-r--r--chromium/third_party/blink/renderer/core/loader/link_loader_test.cc172
-rw-r--r--chromium/third_party/blink/renderer/core/loader/long_task_detector.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/long_task_detector_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/mixed_content_checker.cc92
-rw-r--r--chromium/third_party/blink/renderer/core/loader/mixed_content_checker.h12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.h43
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h27
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.h9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h7
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_test.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h15
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_registry.h7
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/worklet_module_script_fetcher.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/navigation_policy.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/loader/navigation_policy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/navigation_policy_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/loader/navigation_scheduler.cc118
-rw-r--r--chromium/third_party/blink/renderer/core/loader/navigation_scheduler.h7
-rw-r--r--chromium/third_party/blink/renderer/core/loader/ping_loader.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/loader/ping_loader_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.h28
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_test.cc94
-rw-r--r--chromium/third_party/blink/renderer/core/loader/private/prerender_handle.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/private/prerender_handle.h3
-rw-r--r--chromium/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/loader/progress_tracker.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/loader/progress_tracker.h5
-rw-r--r--chromium/third_party/blink/renderer/core/loader/progress_tracker_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h11
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/document_resource.h13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/font_resource.h7
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/font_resource_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource.h9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.h7
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/link_fetch_resource.h10
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h14
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/script_resource.cc288
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/script_resource.h129
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.h10
-rw-r--r--chromium/third_party/blink/renderer/core/loader/subresource_filter.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/subresource_filter.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/text_track_loader.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/text_track_loader.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader.cc147
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader.h12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader_client.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader_test.cc56
-rw-r--r--chromium/third_party/blink/renderer/core/loader/worker_fetch_context.cc125
-rw-r--r--chromium/third_party/blink/renderer/core/loader/worker_fetch_context.h39
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h10
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/message_channel.h6
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/message_port.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/message_port.h15
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/message_port.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/README.md2
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo.h9
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc109
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo_handle.h31
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo_watcher.h7
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.h10
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.h18
-rw-r--r--chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS3
-rw-r--r--chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h13
-rw-r--r--chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client.cc69
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client.h48
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_impl.cc85
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_impl.h21
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_impl_test.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/page/context_menu_controller.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/page/context_menu_controller_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/page/create_window.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/page/drag_controller.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/page/drag_controller.h7
-rw-r--r--chromium/third_party/blink/renderer/core/page/drag_controller_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/page/focus_controller.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/page/focus_controller.h7
-rw-r--r--chromium/third_party/blink/renderer/core/page/page.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/page/page.h3
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_animator.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_animator.h10
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_overlay_test.cc51
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_popup_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_popup_controller.h5
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_popup_supplement.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_popup_supplement.h4
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_widget_delegate.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_widget_delegate.h5
-rw-r--r--chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/page/pointer_lock_controller.h4
-rw-r--r--chromium/third_party/blink/renderer/core/page/print_context.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/page/print_context_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/page/scoped_page_pauser.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h7
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.cc172
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h13
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc1043
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.cc73
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.h16
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h20
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc62
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_metrics_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.h16
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h13
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h3
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc180
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc84
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h29
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc104
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.cc125
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h47
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.h15
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation.h1
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation_test.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/page/validation_message_client_impl.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/page/validation_message_client_impl.h3
-rw-r--r--chromium/third_party/blink/renderer/core/page/validation_message_overlay_delegate.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/page/viewport_description.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/page/viewport_description.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/viewport_test.cc337
-rw-r--r--chromium/third_party/blink/renderer/core/paint/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/README.md204
-rw-r--r--chromium/third_party/blink/renderer/core/paint/background_image_geometry.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_painter.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_painter.h4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_painter_test.cc563
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_model_object_painter.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_model_object_painter.h5
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.cc315
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.h11
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_paint_invalidator_test.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter.cc100
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter.h15
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter_base.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter_base.h3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_reflection_utils.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc152
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h18
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc481
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.cc75
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater_test.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/decoration_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/document_marker_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/embedded_content_painter.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/fieldset_painter.cc84
-rw-r--r--chromium/third_party/blink/renderer/core/paint/filter_effect_builder.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/paint/fragment_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/frame_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/frame_set_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/html_canvas_painter.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/html_canvas_painter_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_element_timing.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc317
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.h26
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc449
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_painter.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/link_highlight_impl.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/paint/list_marker_painter.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h22
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc329
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h174
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_test.cc209
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.cc133
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h28
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc101
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc534
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.h35
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.cc234
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.h42
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_info.h54
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer.cc101
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer.h39
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.h11
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_clipper_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painter.cc219
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painter.h7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painter_test.cc751
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painting_info.h16
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc241
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h33
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc282
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_test.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc287
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.h4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc248
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_result.h8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc95
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h (renamed from chromium/third_party/blink/renderer/core/paint/paint_tracker.h)19
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_tracker.cc57
-rw-r--r--chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk_test.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/paint/replaced_painter.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/paint/replaced_painter.h6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/scoped_paint_state.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/paint/scoped_paint_state.h3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/scoped_svg_paint_state.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_container_painter.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_filter_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_image_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_shape_painter.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_text_painter.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_cell_painter.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_painter.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_painter.h4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_painter_test.cc95
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_row_painter.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_section_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc152
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.h16
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc199
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_painter_test.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/paint/theme_painter.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/paint/theme_painter_default.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/video_painter.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/video_painter_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/view_painter.cc97
-rw-r--r--chromium/third_party/blink/renderer/core/paint/view_painter.h7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/view_painter_test.cc305
-rw-r--r--chromium/third_party/blink/renderer/core/probe/core_probes.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/probe/core_probes.json515
-rw-r--r--chromium/third_party/blink/renderer/core/probe/core_probes.pidl11
-rw-r--r--chromium/third_party/blink/renderer/core/resize_observer/resize_observer.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/resize_observer/resize_observer.h5
-rw-r--r--chromium/third_party/blink/renderer/core/resize_observer/resize_observer_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/scheduler/frame_throttling_test.cc135
-rw-r--r--chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_pending_script.cc205
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_pending_script.h16
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_script.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_script.h16
-rw-r--r--chromium/third_party/blink/renderer/core/script/document_modulator_impl.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/script/document_modulator_impl.h3
-rw-r--r--chromium/third_party/blink/renderer/core/script/document_write_intervention.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.cc136
-rw-r--r--chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.h8
-rw-r--r--chromium/third_party/blink/renderer/core/script/dynamic_module_resolver_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h6
-rw-r--r--chromium/third_party/blink/renderer/core/script/html_parser_script_runner.cc108
-rw-r--r--chromium/third_party/blink/renderer/core/script/html_parser_script_runner.h11
-rw-r--r--chromium/third_party/blink/renderer/core/script/layered_api.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/script/modulator.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/script/modulator.h10
-rw-r--r--chromium/third_party/blink/renderer/core/script/modulator_impl_base.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_map.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_map.h7
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_map_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_pending_script.h20
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_script.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_script.h20
-rw-r--r--chromium/third_party/blink/renderer/core/script/pending_script.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/script/pending_script.h7
-rw-r--r--chromium/third_party/blink/renderer/core/script/script.h7
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_loader.cc118
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_loader.h16
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.h11
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_module_resolver_impl_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_runner.h6
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_runner_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/script/worker_modulator_impl.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/script/worker_modulator_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.h6
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h5
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.h3
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.h2
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm10
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_customization.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_customization.h4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollable_area.h3
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar.h17
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_test_suite.h19
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h15
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm41
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/web_scrollbar_theme.mm50
-rw-r--r--chromium/third_party/blink/renderer/core/streams/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/core/streams/CommonOperations.js257
-rw-r--r--chromium/third_party/blink/renderer/core/streams/CommonStrings.js2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/ReadableStream.js175
-rw-r--r--chromium/third_party/blink/renderer/core/streams/TransformStream.js26
-rw-r--r--chromium/third_party/blink/renderer/core/streams/WritableStream.js93
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream.cc517
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream.h128
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream.idl25
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_operations.cc183
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_operations.h46
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_operations_test.cc348
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc435
-rw-r--r--chromium/third_party/blink/renderer/core/streams/test_underlying_source.h58
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream.cc130
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream.h48
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream.idl16
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream_test.cc102
-rw-r--r--chromium/third_party/blink/renderer/core/streams/underlying_source_base.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream.cc256
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream.h96
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream.idl19
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/style/BUILD.gn3
-rw-r--r--chromium/third_party/blink/renderer/core/style/ComputedStyle.md12
-rw-r--r--chromium/third_party/blink/renderer/core/style/OWNERS5
-rw-r--r--chromium/third_party/blink/renderer/core/style/basic_shapes.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/style/basic_shapes.h4
-rw-r--r--chromium/third_party/blink/renderer/core/style/border_image_length.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/border_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/style/cached_ua_style.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style.cc144
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style.h91
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_constants.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5 (renamed from chromium/third_party/blink/renderer/core/css/computed_style_diff_functions.json5)0
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 (renamed from chromium/third_party/blink/renderer/core/css/computed_style_extra_fields.json5)15
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_test.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/style/content_data.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/style/content_data.h12
-rw-r--r--chromium/third_party/blink/renderer/core/style/fill_layer.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/style/fill_layer.h64
-rw-r--r--chromium/third_party/blink/renderer/core/style/filter_operation.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/style/filter_operation.h16
-rw-r--r--chromium/third_party/blink/renderer/core/style/filter_operations.h13
-rw-r--r--chromium/third_party/blink/renderer/core/style/gap_length.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/grid_length.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/nine_piece_image.h4
-rw-r--r--chromium/third_party/blink/renderer/core/style/quad_length_value.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/shadow_data.h3
-rw-r--r--chromium/third_party/blink/renderer/core/style/shape_value.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/style/shape_value.h23
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_difference.h11
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_fetched_image.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_fetched_image.h13
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_fetched_image_set.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_fetched_image_set.h13
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_filter_data.h15
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_generated_image.h6
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_inherited_variables.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_initial_data.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_initial_data.h53
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_pending_image.h12
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_reflection.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/svg_computed_style.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/svg_computed_style_defs.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/transform_origin.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.h27
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.h5
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/linear_gradient_attributes.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/pattern_attributes.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/radial_gradient_attributes.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_a_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_angle.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_angle.h18
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_angle_tear_off.h10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_element.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_element.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_motion_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_transform_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_angle.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_angle.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.h14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_color.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_color.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.h23
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_href.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_href.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_integer.h28
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_integer_optional_integer.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_length.h21
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.h15
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_number.h28
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.h14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_number_optional_number.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_path.h9
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_point_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.h14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_rect.h14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_string.h16
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.h15
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animation_element.cc57
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animation_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animation_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_boolean.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_circle_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_clip_path_element.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_defs_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_desc_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_discard_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_discard_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_document_extensions.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_element.cc463
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_element_rare_data.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_enumeration.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_enumeration.h41
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.h63
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.cc72
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.h31
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.idl11
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_component_transfer_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_diffuse_lighting_element.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_distant_light_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_drop_shadow_element.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_flood_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_func_a_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_func_b_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_func_g_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_func_r_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_gaussian_blur_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.h1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_merge_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_merge_node_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_offset_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_point_light_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_specular_lighting_element.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_spot_light_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_tile_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_filter_element.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fit_to_view_box.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_g_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_geometry_element.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_gradient_element.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_gradient_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_graphics_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_image_element.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_image_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_image_loader.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_image_loader.h5
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_integer.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_integer.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_integer_optional_integer.h9
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length.h11
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_list_tear_off.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_line_element.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_marker_element.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_marker_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_mask_element.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_metadata_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_mpath_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_mpath_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number.h15
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number_list.h7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number_list_tear_off.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number_optional_number.h7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number_tear_off.h10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path.h9
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_parser.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_parser_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_string_source.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_string_source.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_utilities.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_pattern_element.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_point.h10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_point_list.h5
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_point_list_tear_off.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_point_tear_off.h16
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_poly_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_poly_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_polygon_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_polyline_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio_tear_off.h13
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_rect.h14
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_rect_element.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_rect_tear_off.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_resource.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_script_element.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_script_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_set_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_static_string_list.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_stop_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_string.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_string_list_tear_off.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_style_element.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_style_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_svg_element.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_svg_element.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_switch_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_symbol_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_tag_names.json523
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_tests.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_content_element.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_content_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_path_element.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_path_element.h9
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_title_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform.h21
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform_list.h7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform_list_tear_off.h11
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform_tear_off.h10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_tree_scope_resources.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_tspan_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_unit_types.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_unit_types.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_uri_reference.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_use_element.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_use_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_view_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_view_spec.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_view_spec.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_zoom_and_pan.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.h36
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/composited_selection_bounds_vertical_rl.html1
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/longpress_image_contenteditable.html2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/plugin_hidden_before_scroll.html18
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/shifted_plugin_containing_page.html19
-rw-r--r--chromium/third_party/blink/renderer/core/testing/death_aware_script_wrappable.h5
-rw-r--r--chromium/third_party/blink/renderer/core/testing/dictionary_test.cc267
-rw-r--r--chromium/third_party/blink/renderer/core/testing/dictionary_test.h24
-rw-r--r--chromium/third_party/blink/renderer/core/testing/dummy_page_holder.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/testing/fake_web_plugin.cc (renamed from chromium/third_party/blink/renderer/core/exported/fake_web_plugin.cc)2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/fake_web_plugin.h (renamed from chromium/third_party/blink/renderer/core/exported/fake_web_plugin.h)8
-rw-r--r--chromium/third_party/blink/renderer/core/testing/gc_observation.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/testing/gc_observation.h10
-rw-r--r--chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.h (renamed from chromium/third_party/blink/renderer/core/testing/layer_rect.h)51
-rw-r--r--chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.idl37
-rw-r--r--chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.cc (renamed from chromium/third_party/blink/renderer/core/testing/layer_rect_list.cc)23
-rw-r--r--chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.h (renamed from chromium/third_party/blink/renderer/core/testing/layer_rect_list.h)29
-rw-r--r--chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.idl (renamed from chromium/third_party/blink/renderer/core/testing/layer_rect_list.idl)4
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internal_settings.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internal_settings.h6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internals.cc146
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internals.h26
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internals.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/testing/layer_rect.idl43
-rw-r--r--chromium/third_party/blink/renderer/core/testing/null_execution_context.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/origin_trials_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/origin_trials_test.h17
-rw-r--r--chromium/third_party/blink/renderer/core/testing/page_test_base.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/testing/page_test_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/record_test.h6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sequence_test.h6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.h11
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_test.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_web_frame_client.h7
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.h7
-rw-r--r--chromium/third_party/blink/renderer/core/testing/static_selection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/static_selection.h4
-rw-r--r--chromium/third_party/blink/renderer/core/testing/type_conversions.h24
-rw-r--r--chromium/third_party/blink/renderer/core/testing/union_types_test.h8
-rw-r--r--chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.h8
-rw-r--r--chromium/third_party/blink/renderer/core/testing/worker_internals.h9
-rw-r--r--chromium/third_party/blink/renderer/core/timing/dom_window_performance.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/dom_window_performance.h4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/event_timing.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/memory_info.h6
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance.cc176
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance.h56
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance.idl8
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_element_timing.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_entry.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_entry_names.json52
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_event_timing.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_event_timing.h12
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_layout_jank.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.h17
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_mark.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_mark.h13
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_mark.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_measure.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_measure.h16
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_measure.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_navigation.h7
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_observer.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_observer.h9
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_observer_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_paint_timing.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_resource_timing.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_resource_timing.h20
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_server_timing.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_server_timing.h7
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_test.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_timing.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_timing.h18
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_user_timing.cc43
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_user_timing.h22
-rw-r--r--chromium/third_party/blink/renderer/core/timing/task_attribution_timing.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/task_attribution_timing.h18
-rw-r--r--chromium/third_party/blink/renderer/core/timing/time_clamper.h11
-rw-r--r--chromium/third_party/blink/renderer/core/timing/window_performance.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/timing/window_performance.h8
-rw-r--r--chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.h4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/worker_performance.h6
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_html.h6
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_script.h6
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_script_url.h6
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc77
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.h22
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h8
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl14
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc147
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util_test.cc77
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_url.h8
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h9
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.h7
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h9
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_typed_array.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h2
-rw-r--r--chromium/third_party/blink/renderer/core/url/dom_url.h8
-rw-r--r--chromium/third_party/blink/renderer/core/url/url.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/url/url_search_params.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/url/url_search_params.h5
-rw-r--r--chromium/third_party/blink/renderer/core/url/url_utils_read_only.idl45
-rw-r--r--chromium/third_party/blink/renderer/core/workers/BUILD.gn11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/abstract_worker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc134
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker.h20
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h19
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h3
-rw-r--r--chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h42
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/README.md8
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.cc478
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.h178
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc121
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h49
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc115
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h38
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h46
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc69
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h65
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h23
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h16
-rw-r--r--chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h8
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc92
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h5
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h13
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h27
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_clients.h7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc171
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.h48
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc164
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h72
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_location.h6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_location.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_navigator.h6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h44
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread.cc112
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread.h46
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet.h19
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.h3
-rw-r--r--chromium/third_party/blink/renderer/core/xml/document_xslt.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/xml/document_xslt.h3
-rw-r--r--chromium/third_party/blink/renderer/core/xml/dom_parser.h6
-rw-r--r--chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.h6
-rw-r--r--chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.h11
-rw-r--r--chromium/third_party/blink/renderer/core/xml/parser/xml_errors.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xml_attribute_names.json51
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xml_serializer.h9
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_evaluator.h9
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_expression.h9
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_functions.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_grammar.y4
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_node_set.h6
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_parser.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_predicate.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_result.h5
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_step.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_value.h19
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xsl_style_sheet.h36
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xslt_processor.h6
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc147
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h25
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_event_target.h14
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.h7
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.h6
-rw-r--r--chromium/third_party/blink/renderer/devtools/BUILD.gn5
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/Images/whatsnew.pngbin11811 -> 12114 bytes
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/Runtime.js37
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/Tests.js21
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityStrings.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/animation/animationTimeline.css2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js11
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2Panel.js5
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ProtocolService.js6
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ReportRenderer.js82
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/audits2/module.json3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/audits2_worker/Audits2Service.js2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js12
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/browser_console/BrowserConsole.js56
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/browser_console/module.json26
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/cm/README.md2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/common/ModuleExtensionInterfaces.js31
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/common/ResourceType.js13
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js9
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/components/Linkifier.js23
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js7
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js10
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js7
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js198
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js7
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console/consoleView.css5
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js10
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/coverage/coverageView.css2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/devtools_app.json1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js185
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js40
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js13
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js48
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js29
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/elementsTreeOutline.css30
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/module.json2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements/stylesSectionTree.css2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js8
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js20
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js35
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js92
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/help/ReleaseNoteText.js30
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js68
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RequestAppBannerActionDelegate.js2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/js_main/JsMain.js16
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/layer_viewer/layerDetailsView.css6
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js22
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/main/Main.js8
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js22
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js41
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js10
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js11
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/RequestHTMLView.js2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/network/networkLogView.css10
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js45
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js19
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js11
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/object_ui/module.json2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js141
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js19
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js24
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js223
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js59
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js31
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js9
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/profiler/heapProfiler.css4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js477
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js6
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js22
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js15
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js16
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js23
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js10
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/clearStorageView.css2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/module.json3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/resources/serviceWorkersView.css16
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js80
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/Connections.js187
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js8
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js16
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js8
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js18
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js23
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js7
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js6
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/Target.js117
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js50
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk/module.json18
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js126
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/search/searchResultsPane.css1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js8
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/security/mainView.css18
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/source_frame/xmlTree.css4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js71
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js65
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/breakpointEditDialog.css34
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/javaScriptBreakpointsSidebarPane.css1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/module.json22
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources/sourcesView.css29
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js12
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js43
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js5
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js58
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js19
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js3
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js210
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js21
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js40
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js29
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/ui/textPrompt.css4
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.css2
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js20
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/worker_app.json1
-rw-r--r--chromium/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js32
-rw-r--r--chromium/third_party/blink/renderer/devtools/readme.md2
-rwxr-xr-xchromium/third_party/blink/renderer/devtools/scripts/build/code_generator_frontend.py2
-rwxr-xr-xchromium/third_party/blink/renderer/devtools/scripts/build/generate_devtools_grd.py2
-rwxr-xr-xchromium/third_party/blink/renderer/devtools/scripts/build/generate_protocol_externs.py1
-rwxr-xr-xchromium/third_party/blink/renderer/devtools/scripts/compile_frontend.py2
-rw-r--r--chromium/third_party/blink/renderer/devtools/scripts/extract_module/extract_module.js6
-rw-r--r--chromium/third_party/blink/renderer/devtools/scripts/npm_test.js1
-rw-r--r--chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/README.md9
-rw-r--r--chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/index.js68
-rw-r--r--chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/package.json10
-rw-r--r--chromium/third_party/blink/renderer/modules/BUILD.gn29
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_enums.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_enums.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc608
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_list.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_list.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.cc265
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_object.cc94
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_object.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc127
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_object_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_position.cc78
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_position.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_position_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_range.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_range.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_range_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_selection.cc131
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_selection.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc386
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_slider.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_slider.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc98
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/inspector_type_builder_helper.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc273
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h38
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden-ax.txt11
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden.html12
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list-ax.txt47
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list.html20
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table-ax.txt100
-rw-r--r--chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table.html29
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/README.md2
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope_test.cc73
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.cc72
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h50
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animator.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/animator.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc212
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.h20
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation_test.cc90
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.h29
-rw-r--r--chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl9
-rw-r--r--chromium/third_party/blink/renderer/modules/app_banner/app_banner_controller.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/app_banner/dom_window_installation.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.cc36
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h44
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.h40
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.cc43
-rw-r--r--chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc32
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc22
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc42
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc113
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc119
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc80
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h39
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc86
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h41
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.idl13
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc33
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/service_worker_global_scope_sync.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/sync_event.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/sync_event.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/sync_manager.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/background_sync/sync_manager.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/badging/README.md2
-rw-r--r--chromium/third_party/blink/renderer/modules/battery/battery_manager.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/battery/battery_manager.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/battery/navigator_battery.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/battery/navigator_battery.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/README.md4
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.cc44
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/README.md2
-rw-r--r--chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py4
-rw-r--r--chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/cache.cc144
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/cache.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.cc52
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/cache_test.cc81
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc84
-rw-r--r--chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc269
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h39
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc38
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_api_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc59
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h39
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.idl3
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/clipboard/clipboard.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc1
-rw-r--r--chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/BUILD.gn16
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/DEPS4
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/OWNERS5
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/README.md3
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.cc31
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.h38
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.idl15
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.h32
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl13
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/contacts_select_options.idl12
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.cc46
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.h40
-rw-r--r--chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl12
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.cc52
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.h29
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.cc188
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.h32
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/global_cookie_store_impl.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/OWNERS4
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_inputs.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_outputs.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.cc160
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.h36
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.cc88
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.cc32
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/subtle_crypto.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/README.md2
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc23
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.h35
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.h21
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_size.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc136
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h43
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc183
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.h34
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc69
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h59
-rw-r--r--chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc58
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc44
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.h22
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc127
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.h112
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.h28
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl6
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc47
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc154
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.cc21
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.h30
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event_pump_unittest.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc46
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h22
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_motion.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_orientation.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/document_metadata/copyless_paste_extractor.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/encoding.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/encoding.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_decoder.cc26
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_decoder.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.cc28
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_encoder.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_encoder.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc175
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.cc73
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc37
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.cc73
-rw-r--r--chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/event_modules.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/event_target_modules.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/event_target_modules_names.json5124
-rw-r--r--chromium/third_party/blink/renderer/modules/eventsource/event_source.cc38
-rw-r--r--chromium/third_party/blink/renderer/modules/eventsource/event_source.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/eventsource/event_source_parser.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/eventsource/event_source_parser_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/indexed_db_key_builder.cc201
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_ax_object.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_dom_file_system.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_dom_media_stream_track.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc93
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_idb_key.cc28
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_idb_value.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_media_stream_registry.cc49
-rw-r--r--chromium/third_party/blink/renderer/modules/exported/web_testing_support.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_entry.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_entry.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_reader.cc17
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_reader.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.cc43
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/entry.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/entry_base.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_entry.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_entry_sync.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_base_handle.cc21
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h66
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_iterator.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_file_handle.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.cc31
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_writer.cc42
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_writer.h21
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/local_file_system.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/local_file_system_client.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/metadata.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/filesystem/worker_global_scope_file_system.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.h53
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.idl14
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event_init.idl11
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.cc35
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.h54
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.idl14
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event_init.idl11
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_list.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/gamepad_pose.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.h33
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/geolocation.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/geolocation.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/geolocation_error.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/geoposition.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/geolocation/position_error.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/imagecapture/README.md10
-rw-r--r--chromium/third_party/blink/renderer/modules/imagecapture/image_capture.cc384
-rw-r--r--chromium/third_party/blink/renderer/modules/imagecapture/image_capture.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/imagecapture/media_settings_range.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/BUILD.gn21
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/OWNERS5
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_any.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_any.h39
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.cc58
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.h22
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_database.cc26
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_database.h40
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_database_info.idl10
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.cc167
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.h20
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.idl15
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_factory_test.cc132
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_index.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_index.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_key.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_key.h63
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_key_path.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.cc71
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.h23
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.cc41
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h21
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_request.cc46
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_request.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_request_queue_item.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_request_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc74
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.h60
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.cc26
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h35
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink.typemap35
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.cc291
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.h187
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.cc216
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h82
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.cc23
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.cc80
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h42
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.cc49
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h55
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_names.json57
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc68
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.cc39
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h76
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_database.h32
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.h62
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc22
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h68
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.cc219
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h93
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl_unittest.cc349
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database.h154
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.cc320
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h145
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl_unittest.cc93
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory.h73
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.cc95
-rw-r--r--chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.h59
-rw-r--r--chromium/third_party/blink/renderer/modules/installation/installation_service_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/installedapp/related_application.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/keyboard/keyboard.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/lock.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/lock.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/lock.idl3
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/lock_manager.cc56
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/lock_manager.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/lock_manager.idl5
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/navigator_locks.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/navigator_locks.idl3
-rw-r--r--chromium/third_party/blink/renderer/modules/locks/worker_navigator_locks.idl3
-rw-r--r--chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.cc42
-rw-r--r--chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters_test.cc90
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/BUILD.gn6
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc234
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info.idl9
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.cc48
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.h31
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.cc37
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.h31
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.cc33
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h39
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.idl13
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_key_system_configuration.idl15
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.idl3
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/BUILD.gn3
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_fullscreen_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_enclosure_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_play_button_element.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element.cc25
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_picture_in_picture_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_play_button_element.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc38
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_scrubbing_message_element_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_slider_element.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.cc41
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element_test.cc32
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc23
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.cc39
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc43
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc292
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc142
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.cc128
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.cc43
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate_test.cc60
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.cc28
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.cc50
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/media_download_in_product_help_manager.cc1
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/resources/legacyMediaControls.css2
-rw-r--r--chromium/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css99
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.h16
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/html_media_element_capture.cc33
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/mediarecorder/README.md10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc55
-rw-r--r--chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/media_metadata.cc36
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/media_metadata.h16
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/media_metadata_sanitizer.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/media_session.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/media_session.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/media_source.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/media_source.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/media_source_registry.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/source_buffer.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/source_buffer.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/source_buffer_track_base_supplement.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/track_default.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/track_default.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/track_default_list.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/track_default_list.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/input_device_info.cc58
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/input_device_info.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.cc267
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_constraints_test.cc109
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_device_info.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_device_info.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_devices.cc35
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_devices.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_devices.idl18
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_devices_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream.cc85
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream.h43
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.cc72
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.h60
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.cc257
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.h28
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_track_settings.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.cc33
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.h31
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.idl12
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/user_media_request.cc93
-rw-r--r--chromium/third_party/blink/renderer/modules/mediastream/user_media_request.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/modules_idl_files.gni19
-rw-r--r--chromium/third_party/blink/renderer/modules/modules_initializer.cc54
-rw-r--r--chromium/third_party/blink/renderer/modules/modules_initializer.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/navigatorcontentutils/testing/navigator_content_utils_client_mock.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/netinfo/network_information.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/netinfo/network_information.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/nfc/nfc.cc152
-rw-r--r--chromium/third_party/blink/renderer/modules/nfc/nfc.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification.cc54
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification.h29
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_action.idl6
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_data.cc62
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_data.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_data_test.cc108
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_event.cc22
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_event.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_event.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_event_init.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_manager.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_manager.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/service_worker_global_scope_notifications.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.cc23
-rw-r--r--chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/abort_payment_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/abort_payment_event.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/basic_card_helper.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.cc31
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/on_payment_response_test.cc96
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_address_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_global_scope.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.cc77
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion_test.cc66
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_handler_utils.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_instruments.cc70
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_instruments.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_manager.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_manager.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request.cc404
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request.h35
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_details_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_event.cc47
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_event.h24
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc23
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_test.cc212
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.cc29
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_request_update_event_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_response.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_response.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_response.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_response_test.cc40
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_state_resolver.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_test_helper.cc115
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_test_helper.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payment_updater.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payments_validators.cc76
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payments_validators.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/payments/payments_validators_test.cc50
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/BUILD.gn9
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_host.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream.h55
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.cc122
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.h77
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_unittest.cc442
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h54
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_test.cc932
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.cc44
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.cc40
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.cc17
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.cc71
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h65
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue_test.cc127
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.cc144
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h135
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker_unittest.cc408
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc72
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h59
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.idl24
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc145
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h51
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.cc136
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc907
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h171
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl13
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.cc48
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h51
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc614
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.cc354
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h98
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl8
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_read_result.idl9
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_test.cc1172
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.cc145
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h78
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.cc109
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_encoding_parameters.idl3
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.cc48
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc255
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h32
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.cc29
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.cc158
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/permission_status.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/permission_status.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/permissions.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/document_picture_in_picture.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.cc25
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture_test.cc70
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc17
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_plugin.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_availability.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_availability.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_availability.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_availability_state.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_availability_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection.cc44
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.h34
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.h21
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_controller.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_controller.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_receiver_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_request.cc38
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_request.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/presentation/presentation_request.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_controller.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_event.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_event.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_manager.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_manager.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_manager_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/service_worker_global_scope_push.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/deprecated_storage_info.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/dom_error.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/dom_error.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/dom_window_quota.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/dom_window_quota.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/storage_estimate.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/storage_manager.cc35
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/storage_usage_details.idl13
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/remoteplayback/html_media_element_remote_playback.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/screen_orientation/screen_screen_orientation.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/README.md2
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/accelerometer.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/accelerometer.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/gyroscope.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/gyroscope.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/magnetometer.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/magnetometer.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor.cc25
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_proxy.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc5
-rw-r--r--chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/serial/serial.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/serial/serial.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/serial/serial_port.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/serial/serial_port.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/BUILD.gn6
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/client.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/extendable_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/extendable_event.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.cc78
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/fetch_event.cc59
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/fetch_event.h24
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/fetch_event.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/fetch_event_init.idl1
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/install_event.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/install_event.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.cc90
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.h67
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker.cc44
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker.idl4
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.cc182
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.h55
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.cc59
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.h67
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_test.cc115
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc91
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h49
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.cc111
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h66
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.cc135
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.cc56
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.h33
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc267
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.h102
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_script_cached_metadata_handler.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.cc132
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/barcode_detector.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/detected_face.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/detected_face.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/detected_text.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/detected_text.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/face_detector.cc26
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/face_detector.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/shape_detector.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/text_detector.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/shapedetection/text_detector.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/BUILD.gn1
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_grammar.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_grammar.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition.h26
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.cc21
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis.cc42
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/window_speech.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/speech/window_speech_synthesis.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/DEPS5
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/cached_storage_area.cc33
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/cached_storage_area_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/dom_window_storage.cc44
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/dom_window_storage.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc38
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_area.cc106
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_area.h46
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_controller.cc36
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_controller_test.cc21
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_event.cc33
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_event.h20
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_namespace.cc1
-rw-r--r--chromium/third_party/blink/renderer/modules/storage/storage_namespace_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/vibration/vibration_controller.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/PRESUBMIT.py24
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/navigator_vr.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/navigator_vr.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_display.cc91
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_display.h16
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_display_event.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_display_event.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_frame_data.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_frame_data.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/vr/vr_pose.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/analyser_node.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/analyser_node.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/async_audio_decoder.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.cc64
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.h28
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc36
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_context.cc84
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_context.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_context_autoplay_test.cc40
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_context_test.cc49
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_listener.cc38
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_listener.h20
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_node.cc63
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_node.h37
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_param.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_param_map.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.cc37
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope_test.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_messaging_proxy.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.cc54
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_object_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_thread_test.cc19
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.cc34
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/convolver_node.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/convolver_node.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/delay_node.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/delay_node.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/delay_processor.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/delay_processor.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.cc24
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/gain_node.cc20
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/gain_node.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/iir_processor.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/iir_processor.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc31
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc15
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.cc17
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.cc26
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.cc30
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/panner_node.cc82
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/panner_node.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.cc29
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.cc27
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.h23
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.cc28
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/change_version_wrapper.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database.cc96
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database.h30
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_client.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_context.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_manager.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_thread.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_thread.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/database_tracker.cc1
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_error.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.idl2
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set_row_list.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.h24
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.cc22
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc7
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.h41
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc17
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.cc16
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/PRESUBMIT.py26
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_srgb.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_srgb.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc28
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.idl24
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_active_info.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc22
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_program.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_program.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_query.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_query.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.cc9
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc86
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h12
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl18
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_shader.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_shader.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_sync.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_sync.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_texture.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_texture.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.cc17
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.h1
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/webgpu.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/webgpu.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_access.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_access.h15
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.h18
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_input.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_input.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.cc6
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.h27
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_output.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_output.h16
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_port.cc1
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_port.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/midi_port_map.h3
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.cc13
-rw-r--r--chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.h9
-rw-r--r--chromium/third_party/blink/renderer/modules/webshare/navigator_share.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/webshare/navigator_share.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/close_event.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/close_event.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/dom_websocket.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/dom_websocket.h19
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc18
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/web_pepper_socket_channel_client_proxy.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc48
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h13
-rw-r--r--chromium/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/OWNERS2
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/README.md4
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/navigator_usb.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/navigator_usb.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb.cc67
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb.h16
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc3
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_configuration.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_device.cc36
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_device.h11
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_endpoint.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_in_transfer_result.h6
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_interface.cc11
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_packet.h10
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_result.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_packet.h5
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_result.h2
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/usb_out_transfer_result.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/BUILD.gn12
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/DEPS7
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/OWNERS8
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/README.md4
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.cc120
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h65
-rw-r--r--chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread_test.cc (renamed from chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread_test.cc)126
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/PRESUBMIT.py24
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr.cc10
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr.h8
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.cc31
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.h7
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_coordinate_system.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_device.cc75
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_device.h14
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_frame.cc14
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_frame_provider.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_input_pose.cc2
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.cc12
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.cc4
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.h4
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_session.cc92
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_session.h16
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_session_event.cc8
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_session_event.h17
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.cc40
-rw-r--r--chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/BUILD.gn82
-rw-r--r--chromium/third_party/blink/renderer/platform/DEPS7
-rw-r--r--chromium/third_party/blink/renderer/platform/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/animated_layers_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_animation.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_animation.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_animation_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/animation/compositor_target_property.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_array.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_bus.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_channel.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_destination.cc58
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_destination.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_io_callback.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_processor.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_resampler.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_resampler.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_source_provider.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_source_provider_client.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_utilities.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/audio_utilities.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/biquad.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/biquad.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/arm/vector_math_neon.h42
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/mips/vector_math_msa.h38
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.h26
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h28
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.h26
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h162
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/direct_convolver.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/direct_convolver.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/dynamics_compressor.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/dynamics_compressor_kernel.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/equal_power_panner.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/equal_power_panner.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/ffmpeg/fft_frame_ffmpeg.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/fft_convolver.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/fft_convolver.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/fft_frame.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/hrtf_database_loader.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/hrtf_panner.cc20
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/hrtf_panner.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/iir_filter.cc22
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/iir_filter.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/mac/vector_math_mac.h26
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/panner.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/push_pull_fifo.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_multithread_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/resources/README2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb_accumulation_buffer.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb_convolver.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb_convolver.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/reverb_input_buffer.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/sinc_resampler.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/sinc_resampler.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/stereo_panner.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/stereo_panner.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/vector_math.cc52
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/vector_math.h22
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/vector_math_scalar.h26
-rw-r--r--chromium/third_party/blink/renderer/platform/audio/vector_math_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/DEPS4
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.cc96
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.h101
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.cc34
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h23
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/parkable_string.cc326
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/parkable_string.h73
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc209
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.h36
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/parkable_string_test.cc401
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/script_state.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/script_state.h30
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/script_wrappable.h7
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.cc15
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/string_resource.cc23
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/string_resource.h103
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/to_v8.h41
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_binding.h23
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_binding_macros.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_object_constructor.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.cc41
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h46
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider.cc15
-rw-r--r--chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/blob/blob_data.cc1
-rw-r--r--chromium/third_party/blink/renderer/platform/cross_thread_copier.h7
-rw-r--r--chromium/third_party/blink/renderer/platform/cross_thread_functional.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/data_resource_helper.cc26
-rw-r--r--chromium/third_party/blink/renderer/platform/data_resource_helper.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/platform.cc156
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_coalesced_input_event.cc35
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_cors.cc198
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_media_constraints.cc38
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_media_stream_track.cc3
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_prerender.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_runtime_features.cc98
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_service_worker_request.cc15
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_string.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_url_error.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_url_request.cc40
-rw-r--r--chromium/third_party/blink/renderer/platform/exported/web_url_response.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/DEPS3
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/alternate_font_family.h48
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android_test.cc19
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_cache.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_description.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_fallback_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_family_names.json52
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_metrics.cc22
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_metrics.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_platform_data.cc51
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_platform_data.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/font_selector.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/mac/font_cache_mac.mm16
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm2
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac_test.mm2
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm92
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support_mpl.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_types.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.cc128
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/paint_font.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/paint_text_blob.h16
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/script_run_iterator.cc26
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc44
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/case_mapping_harfbuzz_buffer_filler.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h102
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.cc121
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_font_cache.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.cc26
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper_test.cc203
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_cache.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc254
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.h59
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.cc165
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.h20
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h47
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc472
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h167
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view_test.cc366
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.cc47
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h25
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker_test.cc19
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/simple_font_data.cc20
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/simple_font_data.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc18
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.cc95
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.h45
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/utf16_text_iterator.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/web_font_render_style.cc59
-rw-r--r--chromium/third_party/blink/renderer/platform/fonts/win/font_platform_data_win.cc69
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/blend.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/calculation_value.h (renamed from chromium/third_party/blink/renderer/platform/calculation_value.h)10
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/float_box_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/float_point_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/float_rect_test.cc66
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/float_size_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/int_point.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/layout_rect.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/layout_rect_outsets.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/layout_size.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/layout_unit.cc (renamed from chromium/third_party/blink/renderer/platform/layout_unit.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/layout_unit.h (renamed from chromium/third_party/blink/renderer/platform/layout_unit.h)13
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/layout_unit_test.cc (renamed from chromium/third_party/blink/renderer/platform/layout_unit_test.cc)4
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length.cc (renamed from chromium/third_party/blink/renderer/platform/length.cc)6
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length.h (renamed from chromium/third_party/blink/renderer/platform/length.h)8
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length_box.h (renamed from chromium/third_party/blink/renderer/platform/length_box.h)10
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length_functions.cc (renamed from chromium/third_party/blink/renderer/platform/length_functions.cc)8
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length_functions.h (renamed from chromium/third_party/blink/renderer/platform/length_functions.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length_point.h (renamed from chromium/third_party/blink/renderer/platform/length_point.h)8
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/length_size.h (renamed from chromium/third_party/blink/renderer/platform/length_size.h)8
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/region.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/region.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/geometry/region_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/OWNERS4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc18
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/bitmap_image.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/bitmap_image_test.cc208
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc42
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc107
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.cc109
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.h20
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_color_params_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.cc21
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.h34
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource.cc98
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource.h7
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc158
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h21
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc408
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h83
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc248
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/canvas_resource_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/color.cc34
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/color.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/content_layer_client_impl.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc140
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h19
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc75
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc17
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.cc3
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.h38
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/contiguous_container.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/contiguous_container_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/cpu/arm/webgl_image_conversion_neon.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/cpu/mips/webgl_image_conversion_msa.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/cpu/x86/webgl_image_conversion_sse.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.cc76
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.h18
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.cc12
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.h15
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/filter.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/filter.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/filter_effect.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/image_filter_builder_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/generated_image.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/PRESUBMIT.py24
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc25
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc21
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/webgl_image_conversion.cc40
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gpu/xr_webgl_drawing_buffer.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gradient.cc62
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/gradient.h21
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/graphics_context.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/graphics_layer.cc59
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/graphics_layer.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/graphics_layer_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/high_contrast_image_classifier_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/image.cc59
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/image.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/image_frame_generator_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/image_observer.h1
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/interpolation_space.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/interpolation_space.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/logging_canvas.cc29
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/README.md204
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.cc131
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.h77
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect_test.cc429
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/display_item.cc40
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/display_item.h50
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc32
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.cc13
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc28
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc64
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h20
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc53
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc71
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.h18
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.cc40
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h42
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.cc79
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc41
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h48
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk_subset.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker_test.cc145
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc87
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.h22
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc750
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h82
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/paint_record_builder_test.cc25
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc27
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state_test.cc77
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidator_test.cc99
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.cc23
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h1
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/path.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.cc3
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/placeholder_image.cc118
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/placeholder_image.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/placeholder_image_test.cc407
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/platform_paint_worklet_input.h36
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc54
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.cc56
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc93
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.h36
-rw-r--r--chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc373
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/asm/SaveRegisters_arm64.S20
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/finalizer_traits.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/gc_info.cc25
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/gc_info.h19
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/gc_info_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/gc_task_runner.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap.h49
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_allocator.h141
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_compact.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_compact.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_compact_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_linked_stack.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_page.h154
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.h46
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_terminated_array.h71
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_terminated_array_builder.h26
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_test.cc336
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/heap_test_utilities.cc1
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/incremental_marking_test.cc150
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/marking_verifier.h11
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/marking_visitor.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/member.h262
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/page_memory.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/persistent.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/persistent_node.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/persistent_node.h1
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/process_heap.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/process_heap.h26
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/sparse_heap_bitmap.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/thread_state.cc86
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/thread_state.h11
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/trace_traits.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.cc46
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/heap/visitor.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/gif/gif_image_decoder_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/png/png_image_decoder_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/segment_stream.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/image-encoders/image_encoder_utils.cc28
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.cc50
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h72
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/lifecycle_context_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/cors/cors.cc243
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/cors/cors.h56
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.cc94
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/cors/cors_test.cc (renamed from chromium/third_party/blink/renderer/platform/exported/web_cors_test.cc)30
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/access_control_status.h17
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h34
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc40
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.json52
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.h13
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_correctness_test.cc78
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_test.cc25
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc13
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource.cc76
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource.h36
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_client.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc139
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc43
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.cc48
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler_test.cc64
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc128
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.h19
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_defer_loading_test.cc275
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.cc58
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.h57
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.cc18
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.h54
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_response_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/resource_test.cc50
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/link_header.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/link_header.h16
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/subresource_integrity.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h40
-rw-r--r--chromium/third_party/blink/renderer/platform/loader/testing/mock_resource.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/mac/theme_mac.mm2
-rw-r--r--chromium/third_party/blink/renderer/platform/media/BUILD.gn17
-rw-r--r--chromium/third_party/blink/renderer/platform/media/DEPS13
-rw-r--r--chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.cc34
-rw-r--r--chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.h30
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_center.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.cc23
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.h14
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/memory_coordinator.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc192
-rw-r--r--chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.h17
-rw-r--r--chromium/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc52
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/DEPS2
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/blink_typemaps.gni3
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.cc122
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.h90
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/referrer.typemap14
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/referrer_struct_traits.h50
-rw-r--r--chromium/third_party/blink/renderer/platform/mojo/string16_mojom_traits.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/network/content_security_policy_response_headers.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/network/encoded_form_data.cc22
-rw-r--r--chromium/third_party/blink/renderer/platform/network/encoded_form_data.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/network/encoded_form_data_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/network/form_data_encoder.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_header_map.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_header_map.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_names.json52
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_parsers.cc50
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_parsers.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_parsers_fuzzer.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/network/http_parsers_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/network/mime/content_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/network/mime/mime_type_from_url.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/network/mime/mime_type_registry.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/network/network_instrumentation.cc3
-rw-r--r--chromium/third_party/blink/renderer/platform/network/network_state_notifier.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/network/network_state_notifier.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/network/network_utils.cc13
-rw-r--r--chromium/third_party/blink/renderer/platform/network/network_utils.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/network/network_utils_test.cc116
-rw-r--r--chromium/third_party/blink/renderer/platform/network/parsed_content_header_field_parameters.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/peerconnection/OWNERS3
-rw-r--r--chromium/third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h22
-rw-r--r--chromium/third_party/blink/renderer/platform/plugins/plugin_data.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/plugins/plugin_data.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/png_fuzzer.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/prerender.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/runtime_enabled_features.json5254
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/BUILD.gn62
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/child/DEPS4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/child/OWNERS7
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/child/webthread_base.cc125
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/DEPS7
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler.cc7
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler_unittest.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/features.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/features.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/features.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/features.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper_unittest.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/post_cancellable_task.cc (renamed from chromium/third_party/blink/renderer/platform/web_task_runner.cc)39
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/post_cancellable_task_unittest.cc (renamed from chromium/third_party/blink/renderer/platform/web_task_runner_test.cc)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/post_cross_thread_task.cc41
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/process_state.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/process_state.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/process_state.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/process_state.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.cc25
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/single_thread_idle_task_runner.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h119
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread.cc119
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread_cpu_throttler.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.cc)4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker_unittest.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker_unittest.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/throttling/cpu_time_budget_pool.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.h1
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/throttling/wake_up_budget_pool.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper.cc)29
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper.h)90
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper_unittest.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper_unittest.cc)14
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc17
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.cc17
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h1
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc21
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h25
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc30
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_status.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/renderer/frame_status.cc)2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator_unittest.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.cc46
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h46
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc12
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc40
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h82
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h33
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_unittest.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler_unittest.cc)85
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/prioritize_compositing_after_input_experiment.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.cc50
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h21
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator_unittest.cc42
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/render_widget_signals.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/user_model.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/main_thread/web_scoped_virtual_time_pauser.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/renderer/web_scoped_virtual_time_pauser.cc)0
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/aggregated_metric_reporter.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/aggregated_metric_reporter.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/background_scheduler.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/frame_status.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/renderer/frame_status.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h75
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h28
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/thread.h59
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/thread_cpu_throttler.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.h)6
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/renderer/DEPS8
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.cc59
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h55
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.cc25
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.h29
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler_unittest.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc1
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc29
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc)44
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread.h (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h)31
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.cc7
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler_unittest.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc (renamed from chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler_unittest.cc)53
-rw-r--r--chromium/third_party/blink/renderer/platform/scroll/scroll_snap_data.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/scroll/web_scrollbar_theme_client.h20
-rw-r--r--chromium/third_party/blink/renderer/platform/shared_buffer.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/anim_none.gifbin0 -> 1122 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/animated-10color.gifbin0 -> 67531 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng00-ref.pngbin0 -> 428 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng00.pngbin0 -> 786 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng01-ref.pngbin0 -> 215 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng01.pngbin0 -> 859 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng02-ref.pngbin0 -> 235 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng02.pngbin0 -> 952 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng04-ref.pngbin0 -> 824 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng04.pngbin0 -> 1488 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng08-ref.pngbin0 -> 1449 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng08.pngbin0 -> 2158 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng10-ref.pngbin0 -> 445 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng10.pngbin0 -> 925 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng11-ref.pngbin0 -> 240 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng11.pngbin0 -> 893 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng12-ref.pngbin0 -> 277 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng12.pngbin0 -> 992 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng14-ref.pngbin0 -> 962 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng14.pngbin0 -> 1616 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng18-ref.pngbin0 -> 2245 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng18.pngbin0 -> 3049 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng19-ref.pngbin0 -> 2812 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/apng19.pngbin0 -> 4136 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/blue-wheel-srgb-color-profile.jpgbin0 -> 74017 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/cat.jpgbin0 -> 68826 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/crbug722072.pngbin0 -> 563 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/cropped_mandrill.jpgbin0 -> 23220 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-1-ul.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-2-ur.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-3-lr.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-4-lol.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-5-lu.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-6-ru.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-7-rl.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-8-llo.jpgbin0 -> 1948 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/gif-loop-count.gifbin0 -> 298 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/green-red-blue-yellow-animated.gifbin0 -> 353 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/green.jpgbin0 -> 764 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/green.pngbin0 -> 87 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/icc-v2-gbr.jpgbin0 -> 43834 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/lenna.bmpbin0 -> 196730 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/original-cat-420-629x473.jpgbin0 -> 17838 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/palatted-color-png-gamma-one-color-profile.pngbin0 -> 1263 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/rgb-jpeg-red.jpgbin0 -> 695 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/three-frames_loop-three-times.gifbin0 -> 14499 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/webp-color-profile-lossy.webpbin0 -> 19436 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/data/wrong-frame-dimensions.icobin0 -> 24267 bytes
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/font_test_helpers.cc11
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.cc15
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.h21
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/scoped_fake_plugin_registry.cc24
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.cc17
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h32
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/scoped_mocked_url.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.cc33
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h30
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/shaping_line_breaker_perf_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support.cc21
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support.h1
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.cc44
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h37
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h5
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.cc7
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.cc27
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.h12
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/url_test_helpers.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/url_test_helpers.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/viewport_layers_setup.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock_factory_impl.cc7
-rw-r--r--chromium/third_party/blink/renderer/platform/text/DEPS3
-rw-r--r--chromium/third_party/blink/renderer/platform/text/bidi_character_run.h18
-rw-r--r--chromium/third_party/blink/renderer/platform/text/bidi_context.cc18
-rw-r--r--chromium/third_party/blink/renderer/platform/text/bidi_context.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/text/bidi_resolver.h576
-rw-r--r--chromium/third_party/blink/renderer/platform/text/capitalize.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/text/character.cc16
-rw-r--r--chromium/third_party/blink/renderer/platform/text/character.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/text/character_property_data.h (renamed from chromium/third_party/blink/renderer/platform/text/character_property_data_generator.h)10
-rw-r--r--chromium/third_party/blink/renderer/platform/text/character_property_data_generator.cc12
-rw-r--r--chromium/third_party/blink/renderer/platform/text/locale_mac.mm4
-rw-r--r--chromium/third_party/blink/renderer/platform/text/locale_mac_test.cc43
-rw-r--r--chromium/third_party/blink/renderer/platform/text/locale_win.cc12
-rw-r--r--chromium/third_party/blink/renderer/platform/text/quoted_printable.cc163
-rw-r--r--chromium/third_party/blink/renderer/platform/text/quoted_printable.h76
-rw-r--r--chromium/third_party/blink/renderer/platform/text/segmented_string.h18
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_boundaries.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_boundaries.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_break_iterator.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_break_iterator.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc20
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_run.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_run.h20
-rw-r--r--chromium/third_party/blink/renderer/platform/text/text_run_iterator.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/theme.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/timer.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/transforms/DEPS2
-rw-r--r--chromium/third_party/blink/renderer/platform/transforms/transform_operations_test.cc53
-rw-r--r--chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.cc9
-rw-r--r--chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.h48
-rw-r--r--chromium/third_party/blink/renderer/platform/transforms/translate_transform_operation.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/web_mouse_event.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/web_pointer_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/web_task_runner.h78
-rw-r--r--chromium/third_party/blink/renderer/platform/web_test_support.cc (renamed from chromium/third_party/blink/renderer/platform/layout_test_support.cc)28
-rw-r--r--chromium/third_party/blink/renderer/platform/web_test_support.h (renamed from chromium/third_party/blink/renderer/platform/layout_test_support.h)14
-rw-r--r--chromium/third_party/blink/renderer/platform/web_thread_supporting_gc.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/web_thread_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/web_touch_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/DEPS2
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/kurl.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/referrer.h9
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/referrer_policy.h64
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/reporting_service_proxy_ptr_holder.h30
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/security_origin.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/security_origin_test.cc48
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/security_policy.cc146
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/security_policy.h29
-rw-r--r--chromium/third_party/blink/renderer/platform/weborigin/security_policy_test.cc240
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/alignment.h48
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/compiler.h10
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/date_math.cc158
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/date_math.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/decimal.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/decimal.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/decimal_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/dtoa.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/dtoa.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/hash_table.cc8
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/hash_table.h56
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/hex_number.h8
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/list_hash_set.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_arena.h18
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_arena_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_arena_test_helpers.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_free_list_arena_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_interval_tree_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_red_black_tree_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/stack_util.cc13
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/terminated_array_builder.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h7
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/character_names.h186
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_builder.cc32
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_builder.h22
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_hash.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_impl.cc42
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_impl.h36
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_impl_cf.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_impl_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/text_encoding_registry.cc10
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/unicode.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/utf8.cc4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/utf8.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.cc26
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.h15
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/threading_primitives_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/threading_win.cc5
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/type_traits.h11
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/type_traits_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h28
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.cc14
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h4
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h2
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc3
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/vector.h6
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/vector_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/vector_traits.h3
-rw-r--r--chromium/third_party/blink/renderer/platform/wtf/wtf.cc2
6186 files changed, 106834 insertions, 71540 deletions
diff --git a/chromium/third_party/blink/renderer/DEPS b/chromium/third_party/blink/renderer/DEPS
index 3d4a316b0c4..2515e2d0205 100644
--- a/chromium/third_party/blink/renderer/DEPS
+++ b/chromium/third_party/blink/renderer/DEPS
@@ -12,8 +12,10 @@ include_rules = [
"+base/macros.h",
"+base/memory/ptr_util.h",
"+base/memory/weak_ptr.h",
+ "+base/metrics/histogram_functions.h",
"+base/metrics/histogram_macros.h",
"+base/metrics/field_trial_params.h",
+ "+base/metrics/single_sample_metrics.h",
"+base/numerics/checked_math.h",
"+base/numerics/safe_conversions.h",
"+base/optional.h",
@@ -23,7 +25,7 @@ include_rules = [
"+base/single_thread_task_runner.h",
"+base/stl_util.h",
"+base/sys_byteorder.h",
- "+base/sys_info.h",
+ "+base/system/sys_info.h",
"+base/task/post_task.h",
"+base/test/metrics/histogram_tester.h",
"+base/test/scoped_feature_list.h",
@@ -31,7 +33,9 @@ include_rules = [
"+base/thread_annotations.h",
"+base/threading/thread_checker.h",
"+base/time/time.h",
+ "+base/timer/elapsed_timer.h",
"+build",
+ "+services/network/public/mojom",
"+services/service_manager/public/cpp/connector.h",
"+services/service_manager/public/cpp/interface_provider.h",
"+testing/gmock/include/gmock",
diff --git a/chromium/third_party/blink/renderer/bindings/DEPS b/chromium/third_party/blink/renderer/bindings/DEPS
index 8d675914fd6..daac63bba5e 100644
--- a/chromium/third_party/blink/renderer/bindings/DEPS
+++ b/chromium/third_party/blink/renderer/bindings/DEPS
@@ -1,8 +1,8 @@
include_rules = [
+ "+base/logging.h",
"+base/memory/scoped_refptr.h",
"+base/process/process_metrics.h",
"+gin/public",
- "+services/network/public/mojom/fetch_api.mojom-blink.h",
"+third_party/blink/renderer/bindings",
"+third_party/blink/renderer/core",
"+third_party/blink/renderer/modules",
diff --git a/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.md b/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.md
index 2e454802b62..29c3d757a9f 100644
--- a/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.md
+++ b/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.md
@@ -20,7 +20,7 @@ Blink IDL also does not support certain recent features of the Web IDL grammar:
Semantically, only certain extended attributes allow lists. Similarly, only certain extended attributes allow string literals.
Extended attributes either take no value, take a required value, or take an optional value.
-In the following explanations, _(i)_, _(m)_, _(s)_, _(a)_, _(p)_, _(c)_, _(d)_, and _(f)_ mean that a given extended attribute can be specified on interfaces, methods, special operations, attributes, parameters, constants, dictionaries, and callback functions respectively. For example, _(a,p)_ means that the IDL attribute can be specified on attributes and parameters.
+In the following explanations, _(i)_, _(m)_, _(s)_, _(a)_, _(p)_, _(c)_, _(d)_, _(f)_, and _(t)_ mean that a given extended attribute can be specified on interfaces, methods, special operations, attributes, parameters, constants, dictionaries, callback functions, and types respectively. For example, _(a,p)_ means that the IDL attribute can be specified on attributes and parameters.
*** note
These restrictions are not enforced by the parser: extended attributes used in unsupported contexts will simply be ignored.
@@ -155,23 +155,21 @@ Usage: `[CEReactions]` takes no arguments.
Note that `blink::CEReactionsScope` must be constructed after `blink::ExceptionState`.
-### [Clamp] _(a, p)_
+### [Clamp] _(t)_
Standard: [Clamp](https://heycam.github.io/webidl/#Clamp)
Summary: `[Clamp]` indicates that when an ECMAScript Number is converted to the IDL type, out of range values will be clamped to the range of valid values, rather than using the operators that use a modulo operation (ToInt32, ToUint32, etc.).
-Usage: The `[Clamp]` extended attribute MUST NOT appear on a read only attribute, or an attribute, operation argument or dictionary member that is not of an integer type.
-
-`[Clamp]` can be specified on writable attributes:
+Usage: The `[Clamp]` extended attribute MUST appear on an integer type.
```webidl
interface XXX {
- [Clamp] attribute unsigned short attributeName;
+ attribute [Clamp] unsigned short attributeName;
};
```
-`[Clamp]` can be specified on extended attributes or methods arguments:
+Annotated type with `[Clamp]` can be specified on extended attributes or methods arguments:
```webidl
interface GraphicsContext {
@@ -198,7 +196,7 @@ Usage: `[Constructor]` can be specified on interfaces:
```webidl
[
- Constructor(float x, float y, DOMString str),
+ Constructor(float x, float y, DOMString str)
]
interface XXX {
...
@@ -214,8 +212,7 @@ var x = new XXX(1.0, 2.0, "hello");
The Blink implementation must have the following method as a constructor callback:
```c++
-scoped_refptr<XXX> XXX::create(float x, float y, String str)
-{
+XXX* XXX::Create(float x, float y, const String& str) {
...;
}
```
@@ -228,23 +225,21 @@ Whether you should allow an interface to have constructor depends on the spec of
Currently `[Constructor(...)]` does not yet support optional arguments w/o defaults. It just supports optional `[Default=Undefined]`.
***
-### [EnforceRange] _(a, p)_
+### [EnforceRange] _(t)_
Standard: [EnforceRange](https://heycam.github.io/webidl/#EnforceRange)
Summary: `[EnforceRange]` indicates that when an ECMAScript Number is converted to the IDL type, out of range values will result in a TypeError exception being thrown.
-Usage: The `[EnforceRange]` extended attribute MUST NOT appear on a read only attribute, or an attribute, operation argument or dictionary member that is not of an integer type.
-
-`[EnforceRange]` can be specified on writable attributes:
+Usage: The `[EnforceRange]` extended attribute MUST appear on an integer type.
```webidl
interface XXX {
- [EnforceRange] attribute unsigned short attributeName;
+ attribute [EnforceRange] unsigned short attributeName;
};
```
-`[EnforceRange]` can be specified on extended attributes on methods arguments:
+Annotated type with `[EnforceRange]` can be specified on extended attributes on methods arguments:
```webidl
interface GraphicsContext {
@@ -261,7 +256,7 @@ Calling the `[EnforceRange]` version of `setColorEnforced()` with an out of rang
Standard: [Exposed](http://heycam.github.io/webidl/#Exposed)
-Summary: Indicates on which global object or objects (e.g., Window, WorkerGlobalScope) the interface property is generated, i.e., in which global scope or scopes an interface exists. This is primarily of interest for the constructor, i.e., the [interface object Call method](https://heycam.github.io/webidl/#es-interface-call). Global context defaults to Window (the primary global scope) if not present, overridden by standard extended attribute `[NoInterfaceObject]` (the value of the property on the global object corresponding to the interface is called the **interface object**), which results in no interface property being generated.
+Summary: Indicates on which global object or objects (e.g., Window, WorkerGlobalScope) the interface property is generated, i.e., in which global scope or scopes an interface exists. This is primarily of interest for the constructor, i.e., the [interface object Call method](https://heycam.github.io/webidl/#es-interface-call). If `[Exposed]` is not present or overridden by a standard extended attribute `[NoInterfaceObject]` (the value of the property on the global object corresponding to the interface is called the **interface object**), which results in no interface property being generated.
As with `[NoInterfaceObject]` does not affect generated code for the interface itself, only the code for the corresponding global object. A partial interface is generated at build time, containing an attribute for each interface property on that global object.
@@ -281,13 +276,13 @@ Usage: `[Exposed]` can be specified on interfaces that do not have the `[NoInter
```webidl
[
- Exposed=DedicatedWorker,
+ Exposed=DedicatedWorker
] interface XXX {
...
};
[
- Exposed=(Window,Worker),
+ Exposed=(Window,Worker)
] interface YYY {
...
};
@@ -297,15 +292,15 @@ Exposed can also be specified with a method, attribute and constant.
As a Blink-specific extension, we allow `Exposed(Arguments)` form, such as `[Exposed(Window Feature1, DedicatedWorker Feature2)]`. You can use this form to vary the exposing global scope based on runtime enabled features. For example, `[Exposed(Window Feature1, Worker Feature2)]` exposes the qualified element to Window if "Feature1" is enabled and to Worker if "Feature2" is enabled.
-### [Global] and [PrimaryGlobal] _(i)_
+### [Global] _(i)_
Standard: [Global](http://heycam.github.io/webidl/#Global)
-Summary: The `[Global]` and `[PrimaryGlobal]` extended attributes can be used to give a name to one or more global interfaces, which can then be referenced by the `[Exposed]` extended attribute.
+Summary: The `[Global]` extended attribute can be used to give a name to one or more global interfaces, which can then be referenced by the `[Exposed]` extended attribute.
-These extended attributes must either take no arguments or take an identifier list.
+This extended attribute must either take an identifier or take an identifier list.
-If the `[Global]` or `[PrimaryGlobal]` extended attribute is declared with an identifier list argument, then those identifiers are the interface’s global names; otherwise, the interface has a single global name, which is the interface's identifier.
+The identifier argument or identifier list argument the `[Global]` extended attribute is declared with define the interface's global names
### [HTMLConstructor]
@@ -385,7 +380,7 @@ Usage: `[NoInterfaceObject]` can be specified on interfaces.
```webidl
[
- NoInterfaceObject,
+ NoInterfaceObject
] interface XXX {
...
};
@@ -395,7 +390,7 @@ Note that `[NoInterfaceObject]` **MUST** be specified on testing interfaces, as
```webidl
[
- NoInterfaceObject, // testing interfaces do not appear on global objects
+ NoInterfaceObject // testing interfaces do not appear on global objects
] interface TestingInterfaceX {
...
};
@@ -442,21 +437,21 @@ Intuitively, "replaceable" means that you can set a new value to the attribute w
Specifically, a writable attribute, without `[Replaceable]`, behaves as follows:
```js
-window.screenX; // Evaluates to 0
+window.screenX; // Evaluates to 0
window.screenX = "foo";
-window.screenX; // Evaluates to "foo"
+window.screenX; // Evaluates to "foo"
delete window.screenX;
-window.screenX; // Evaluates to undefined. 0 is lost.
+window.screenX; // Evaluates to undefined. 0 is lost.
```
A read only attribute, with `[Replaceable]`, behaves as follows:
```js
-window.screenX; // Evaluates to 0
+window.screenX; // Evaluates to 0
window.screenX = "foo";
-window.screenX; // Evaluates to "foo"
+window.screenX; // Evaluates to "foo"
delete window.screenX;
-window.screenX; // Evaluates to 0. 0 remains.
+window.screenX; // Evaluates to 0. 0 remains.
```
Whether `[Replaceable]` should be specified or not depends on the spec of each attribute.
@@ -515,23 +510,21 @@ Summary: Transferable objects support being transferred across Realms with `post
This attribute has no effect on code generation and should simply be used in Blink IDL files if the specification uses it. Code to perform the transfer steps must be added to `V8ScriptValueSerializer` for types in `core/` or `V8ScriptValueDeserializerForModules` for types in `modules/`.
-### [TreatNullAs] _(a,p)_
+### [TreatNullAs] _(t)_
Standard: [TreatNullAs](https://heycam.github.io/webidl/#TreatNullAs)
Summary: `[TreatNullAs=EmptyString]` indicates that a JavaScript null is converted to `""` instead of `"null"`.
-Usage: Can be specified on DOMString attributes or DOMString parameters only:
+Usage: `[TreatNullAs=EmptyString]` must be specified on a DOMString type.
```webidl
-[TreatNullAs=EmptyString] attribute DOMString str;
+attribute [TreatNullAs=EmptyString] DOMString str;
void func([TreatNullAs=Emptytring] DOMString str);
```
Implementation: Given `[TreatNullAs=EmptyString]`, a JavaScript null is converted to a Blink empty string, for which `String::IsEmpty()` returns true, but `String::IsNull()` return false.
-**Non-standard:** Blink also supports the `NullString` identifier. Given `[TreatNullAs=NullString]`, a JavaScript null is converted to a Blink null string, for which both `String::IsEmpty()` and `String::IsNull()` return true. This is for performance reasons; see [Strings in Blink](https://docs.google.com/a/google.com/document/d/1kOCUlJdh2WJMJGDf-WoEQhmnjKLaOYRbiHz5TiGJl14/edit) for reference. Unless the spec specifies `[TreatNullAs=EmptyString]`, you should not specify `[TreatNullAs=NullString]` in Blink. Care must be taken to not treat null and empty strings differently, as they would be indistinguishable when using `[TreatNullAs=EmptyString]`.
-
### [Unforgeable] _(m,a)_
Standard: [Unforgeable](http://heycam.github.io/webidl/#Unforgeable)
@@ -569,7 +562,7 @@ Usage: `[ActiveScriptWrappable]` can be specified on interfaces, and **is inheri
```webidl
[
- ActiveScriptWrappable,
+ ActiveScriptWrappable
] interface Foo {
...
};
@@ -579,7 +572,7 @@ If an interface X has `[ActiveScriptWrappable]` and an interface Y inherits the
```webidl
[
- ActiveScriptWrappable,
+ ActiveScriptWrappable
] interface Foo {};
interface Bar : Foo {}; // inherits [ActiveScriptWrappable] from Foo
@@ -590,10 +583,9 @@ If a given DOM object needs to be kept alive as long as the DOM object has pendi
If you use `[ActiveScriptWrappable]`, the corresponding Blink class needs to inherit ActiveScriptWrappable and override hasPendingActivity(). For example, in case of XMLHttpRequest, core/xml/XMLHttpRequest.h would look like this:
```c++
-class XMLHttpRequest : public ActiveScriptWrappable<XMLHttpRequest>
-{
- // Returns true if the object needs to be kept alive.
- bool hasPendingActivity() const override { return ...; }
+class XMLHttpRequest : public ActiveScriptWrappable<XMLHttpRequest> {
+ // Returns true if the object needs to be kept alive.
+ bool HasPendingActivity() const override { return ...; }
}
```
@@ -688,12 +680,12 @@ _(rare CallWith values)_
#### [CallWith=ThisValue] _(m)_
-`[CallWith=ThisValue]` only applies to methods in callback interfaces, and is used in only one place (CSSVariablesMapForEachCallback.idl).
+`[CallWith=ThisValue]` is used in only one place (location.idl).
IDL example:
```webidl
-callback interface Example {
+interface Example {
[CallWith=ThisValue] boolean func(boolean a, boolean b);
};
```
@@ -705,7 +697,7 @@ bool Example::func(ScriptValue thisValue, bool a, bool b);
```
*** note
-`[CallWith=...]` arguments are added at the _head_ of `XXX::create(...)'s` arguments, and ` [RaisesException]`'s `ExceptionState` argument is added at the _tail_ of `XXX::create(...)`'s arguments.
+`[CallWith=...]` arguments are added at the _head_ of `XXX::Create(...)'s` arguments, and ` [RaisesException]`'s `ExceptionState` argument is added at the _tail_ of `XXX::Create(...)`'s arguments.
***
#### [ConstructorCallWith] _(i)_
@@ -717,23 +709,18 @@ If `[Constructor]` is specified on an interface, `[ConstructorCallWith]` can be
```webidl
[
Constructor(float x, float y, DOMString str),
- ConstructorCallWith=ExecutionContext,
+ ConstructorCallWith=ExecutionContext
]
interface XXX {
...
};
```
-Then XXX::create(...) can have the following signature
-
-*** note
-**FIXME:** outdated
-***
+Then XXX::Create(...) can have the following signature
```c++
-scoped_refptr<XXX> XXX::create(ExecutionContext* context, float x, float y, String str)
-{
- ...;
+XXX* XXX::Create(ExecutionContext* context, float x, float y, const String& str) {
+ ...;
}
```
@@ -756,7 +743,7 @@ Usage: `[ContextEnabled=FeatureName]`. FeatureName is an arbitrary name used to
] interface Mojo { ... };
```
-When applied to an interface, the generated code for the relevant global object will include a public `installFeatureName()` method which can be called to install the interface on the global object.
+When applied to an interface, the generated code for the relevant global object will include a public `InstallFeatureName()` method which can be called to install the interface on the global object.
Note that `[ContextEnabled]` is not mututally exclusive to `[RuntimeEnabled]`, and a feature which may be enabled by either mechanism will be enabled if the appropriate `[RuntimeEnabled]` feature is enabled; _or_ if the appropriate `[ContextEnabled]` feature is enabled; _or_ if both are enabled.
@@ -792,22 +779,20 @@ Methods:
```webidl
interface XXX {
- [Custom] void func();
- [Custom=CallEpilogue] void func2();
+ [Custom] void func();
+ [Custom=CallEpilogue] void func2();
};
```
-You can write custom bindings in Source/bindings/v8/custom/V8XXXCustom.cpp:
+You can write custom bindings in third_party/blink/renderer/bindings/{core,modules}/v8/custom/v8_xxx_custom.cc:
```c++
-void V8XXX::funcMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
-{
- ...;
+void V8XXX::FuncMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info) {
+ ...;
}
-void V8XXX::func2MethodEpilogueCustom(const v8::FunctionCallbackInfo<v8::Value>& info, V8XXX* impl)
-{
- ...;
+void V8XXX::Func2MethodEpilogueCustom(const v8::FunctionCallbackInfo<v8::Value>& info, V8XXX* impl) {
+ ...;
}
```
@@ -822,9 +807,8 @@ interface XXX {
You can write custom bindings in Source/bindings/v8/custom/V8XXXCustom.cpp:
```c++
-void V8XXX::strAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info)
-{
- ...;
+void V8XXX::StrAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info) {
+ ...;
}
```
@@ -839,9 +823,8 @@ interface XXX {
You can write custom bindings in Source/bindings/v8/custom/V8XXXCustom.cpp:
```c++
-void V8XXX::strAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info)
-{
- ...;
+void V8XXX::StrAttributeSetterCustom(v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) {
+ ...;
}
```
@@ -899,18 +882,16 @@ interface XXX {
You can write custom bindings as V8XXX::namedPropertyQuery(...) and V8XXX::namedPropertyEnumerator(...) in Source/bindings/v8/custom/V8XXXCustom.cpp:
```c++
-v8::Local<v8::Integer> V8XXX::namedPropertyQuery(v8::Local<v8::String> name, const v8::AccessorInfo& info)
-{
- ...;
+v8::Local<v8::Integer> V8XXX::NamedPropertyQuery(v8::Local<v8::String> name, const v8::AccessorInfo& info) {
+ ...;
}
-v8::Local<v8::Array> V8XXX::namedPropertyEnumerator(const v8::AccessorInfo& info)
-{
- ...;
+v8::Local<v8::Array> V8XXX::NamedPropertyEnumerator(const v8::AccessorInfo& info) {
+ ...;
}
```
-#### [Custom=LegacyCallAsFunction] _(i) _deprecated_
+#### [Custom=LegacyCallAsFunction] _(i)_ _deprecated_
Summary: `[Custom=LegacyCallAsFunction]` allows you to write custom bindings for call(...) of a given interface.
@@ -929,8 +910,7 @@ If you want to write custom bindings for XXX.call(...), you can use `[Custom=Leg
You can write custom `V8XXX::callAsFunctionCallback(...)` in Source/bindings/v8/custom/V8XXXCustom.cpp:
```c++
-v8::Local<v8::Value> V8XXX::callAsFunctionCallback(const v8::Arguments& args)
-{
+v8::Local<v8::Value> V8XXX::CallAsFunctionCallback(const v8::Arguments& args) {
...;
}
```
@@ -962,8 +942,8 @@ Usage: `[Default=Undefined]` can be specified on any optional parameter:
```webidl
interface HTMLFoo {
- void func1(int a, int b, optional int c, optional int d);
- void func2(int a, int b, [Default=Undefined] optional int c);
+ void func1(long a, long b, optional long c, optional long d);
+ void func2(long a, long b, [Default=Undefined] optional long c);
};
```
@@ -971,9 +951,9 @@ The parameters marked with the standard Web IDL `optional` qualifier are optiona
The difference between `optional` and `[Default=Undefined]` optional is whether the Blink implementation requires overloaded methods or not: without a default value, the Blink implementation must have overloaded C++ functions, while with a default value, the Blink implementation only needs a single C++ function.
-In case of func1(...), if JavaScript calls func1(100, 200), then HTMLFoo::func1(int a, int b) is called in Blink. If JavaScript calls func1(100, 200, 300), then HTMLFoo::func1(int a, int b, int c) is called in Blink. If JavaScript calls func1(100, 200, 300, 400), then HTMLFoo::func1(int a, int b, int c, int d) is called in Blink. In other words, if the Blink implementation has overloaded methods, you can use `optional`.
+In case of func1(...), if JavaScript calls func1(100, 200), then `HTMLFoo::func1(int a, int b)` is called in Blink. If JavaScript calls `func1(100, 200, 300)`, then `HTMLFoo::func1(int a, int b, int c)` is called in Blink. If JavaScript calls `func1(100, 200, 300, 400)`, then `HTMLFoo::func1(int a, int b, int c, int d)` is called in Blink. In other words, if the Blink implementation has overloaded methods, you can use `optional`.
-In case of func2(...) which adds `[Default=Undefined]`, if JavaScript calls func2(100, 200), then it behaves as if JavaScript called func2(100, 200, undefined). Consequently, HTMLFoo::func2(int a, int b, int c) is called in Blink. 100 is passed to a, 200 is passed to b, and 0 is passed to c. (A JavaScript `undefined` is converted to 0, following the value conversion rule in the Web IDL spec; if it were a DOMString parameter, it would end up as the string `"undefined"`.) In this way, Blink needs to just implement func2(int a, int b, int c) and needs not to implement both func2(int a, int b) and func2(int a, int b, int c).
+In case of func2(...) which adds `[Default=Undefined]`, if JavaScript calls `func2(100, 200)`, then it behaves as if JavaScript called `func2(100, 200, undefined)`. Consequently, `HTMLFoo::func2(int a, int b, int c)` is called in Blink. 100 is passed to `a`, 200 is passed to `b`, and 0 is passed to `c`. (A JavaScript `undefined` is converted to 0, following the value conversion rule in the Web IDL spec; if it were a DOMString parameter, it would end up as the string `"undefined"`.) In this way, Blink needs to just implement `func2(int a, int b, int c)` and needs not to implement both `func2(int a, int b)` and `func2(int a, int b, int c)`.
### [DeprecateAs] _(m, a, c)_
@@ -1026,12 +1006,6 @@ Usage: `[MeasureAs]` can be specified on interfaces, methods, attributes, and co
### [NotEnumerable] _(m, a, s)_
-*** note
-**FIXME:** docs out of date!
-***
-
-Specification: [The spec of Writable, Enumerable and Configurable (Section 8.6.1)](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) - _not standard Web IDL extended attributes._
-
Summary: Controls the enumerability of methods and attributes.
Usage: `[NotEnumerable]` can be specified on methods and attributes
@@ -1057,19 +1031,15 @@ Usage: `[OriginTrialEnabled=FeatureName]`. FeatureName must be included in [runt
When there is an active origin trial for the current execution context, the feature is enabled at runtime, and the binding would be exposed to the web. `[OriginTrialEnabled]` also includes a check for the associated runtime flag, so features can be enabled in that fashion, even without an origin trial.
-`[OriginTrialEnabled]` has similar semantics to `[RuntimeEnabled]`, and is intended as a drop-in replacement. For example, `[OriginTrialEnabled]` _cannot_ be applied to arguments, see `[RuntimeEnabled]` for reasoning. The key implementation difference is that `[OriginTrialEnabled]` wraps the generated code with `if (OriginTrials::FeatureNameEnabled(...)) { ...code... }`.
+`[OriginTrialEnabled]` has similar semantics to `[RuntimeEnabled]`, and is intended as a drop-in replacement. For example, `[OriginTrialEnabled]` _cannot_ be applied to arguments, see `[RuntimeEnabled]` for reasoning. The key implementation difference is that `[OriginTrialEnabled]` wraps the generated code with `if (origin_trials::FeatureNameEnabled(...)) { ...code... }`.
For more information, see [RuntimeEnabledFeatures](https://code.google.com/p/chromium/codesearch#chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5) and [OriginTrialContext](https://code.google.com/p/chromium/codesearch#chromium/src/third_party/blink/renderer/core/origin_trials/origin_trial_context.h).
-*** note
-**FIXME:** Currently, `[OriginTrialEnabled]` can only be applied to interfaces, attributes, and constants. Methods (including those generated by `iterable`, `setlike`, `maplike`, `serializer` and `stringifier`) are not supported. See [Bug 621641](https://crbug.com/621641).
-***
-
### [RaisesException] _(i, m, a)_
Summary: Tells the code generator to append an `ExceptionState&` argument when calling the Blink implementation.
-Implementations may use the methods on this parameter (e.g. `ExceptionState::throwDOMException`) to throw exceptions.
+Implementations may use the methods on this parameter (e.g. `ExceptionState::ThrowDOMException`) to throw exceptions.
Usage: `[RaisesException]` can be specified on methods and attributes, `[RaisesException=Getter]` and `[RaisesException=Setter]` can be specified on attributes, and `[RaisesException=Constructor]` can be specified on interfaces where `[Constructor]` is also specified. On methods and attributes, the IDL looks like:
@@ -1085,32 +1055,32 @@ interface XXX {
And the Blink implementations would look like:
```c++
-long XXX::count(ExceptionState& exceptionState) {
- if (...) {
- exceptionState.throwDOMException(TypeMismatchError, ...);
- return;
- }
- ...;
+long XXX::Count(ExceptionState& exception_state) {
+ if (...) {
+ exception_state.ThrowDOMException(TypeMismatchError, ...);
+ return;
+ }
+ ...;
}
-void XXX::setCount(long value, ExceptionState& exceptionState) {
- if (...) {
- exceptionState.throwDOMException(TypeMismatchError, ...);
- return;
- }
- ...;
+void XXX::SetCount(long value, ExceptionState& exception_state) {
+ if (...) {
+ exception_state.ThrowDOMException(TypeMismatchError, ...);
+ return;
+ }
+ ...;
}
-void XXX::foo(ExceptionState& exceptionState) {
- if (...) {
- exceptionState.throwDOMException(TypeMismatchError, ...);
- return;
- }
- ...;
+void XXX::foo(ExceptionState& exception_state) {
+ if (...) {
+ exception_state.ThrowDOMException(TypeMismatchError, ...);
+ return;
+ }
+ ...;
};
```
-If `[RaisesException=Constructor]` is specified on an interface and `[Constructor]` is also specified then an `ExceptionState&` argument is added when calling the `XXX::create(...)` constructor callback.
+If `[RaisesException=Constructor]` is specified on an interface and `[Constructor]` is also specified then an `ExceptionState&` argument is added when calling the `XXX::Create(...)` constructor callback.
```webidl
[
@@ -1125,14 +1095,13 @@ interface XXX {
Blink needs to implement the following method as a constructor callback:
```c++
-scoped_refptr<XXX> XXX::create(float x, ExceptionState& exceptionState)
-{
- ...;
- if (...) {
- exceptionState.throwDOMException(TypeMismatchError, ...);
- return nullptr;
- }
- ...;
+XXX* XXX::Create(float x, ExceptionState& exception_state) {
+ ...;
+ if (...) {
+ exception_state.ThrowDOMException(TypeMismatchError, ...);
+ return nullptr;
+ }
+ ...;
}
```
@@ -1250,14 +1219,6 @@ Usage: `[RuntimeEnabled=FeatureName]`. FeatureName must be included in [runtime\
Only when the feature is enabled at runtime (using a command line flag, for example, or when it is enabled only in certain platforms), the binding would be exposed to the web.
-`[RuntimeEnabled]` _cannot_ be applied to arguments, as this changes signatures and method resolution and is both very confusing to reason about and implement. For example, what does it mean to mark a _required_ argument as `[RuntimeEnabled]`? You probably want to apply it only to optional arguments, which are equivalent to overloads. Thus instead apply `[RuntimeEnabled]` to the _method_, generally splitting a method in two. For example, instead of:
-
-```webidl
-foo(long x, `[RuntimeEnabled=FeatureName]` optional long y); // Don't do this!
-```
-
-do:
-
```webidl
// Overload can be replaced with optional if `[RuntimeEnabled]` is removed
foo(long x);
@@ -1280,7 +1241,7 @@ These extended attributes are rarely used, generally only in one or two places.
Summary: For performance optimization, `[CachedAttribute]` indicates that a wrapped object should be cached on a DOM object. Rarely used.
-Usage: `[CachedAttribute]` can be specified on attributes, and takes a required value, generally called is*Dirty (e.g. isValueDirty):
+Usage: `[CachedAttribute]` can be specified on attributes, and takes a required value, generally called isXXXDirty (e.g. isValueDirty):
```webidl
interface HTMLFoo {
@@ -1327,23 +1288,20 @@ You should cache attributes if and only if it is really important for performanc
```c++
// Called internally to update value
-void Object::setValue(Type data)
-{
- m_data = data;
- m_attributeDirty = true;
+void Object::SetValue(Type data) {
+ data_ = data;
+ attribute_dirty_ = true;
}
// Called by generated binding code
-bool Object::isAttributeDirty() const
-{
- return m_attributeDirty;
+bool Object::IsAttributeDirty() const {
+ return attribute_dirty_;
}
-// Called by generated binding code if no value cached or isAttributeDirty() returns true
-ScriptValue Object::attribute(ExecutionContext* context)
-{
- m_attributeDirty = false;
- return convertDataToScriptValue(m_data);
+// Called by generated binding code if no value cached or IsAttributeDirty() returns true
+ScriptValue Object::attribute(ExecutionContext* context) {
+ attribute_dirty_ = false;
+ return ConvertDataToScriptValue(data_);
}
```
@@ -1365,7 +1323,7 @@ Location or Window interface.
```webidl
[
- CheckSecurity=Receiver,
+ CheckSecurity=Receiver
] interface DOMWindow {
Selection? getSelection();
};
@@ -1403,8 +1361,8 @@ allowed, but access to `window.parent.document` is not.
### [CrossOrigin] _(m, a)_
Summary: Allows cross-origin access to an attribute or method. Used for
-implementing [CrossOriginProperties] from the spec in Location.idl and
-Window.idl.
+implementing [CrossOriginProperties] from the spec in location.idl and
+window.idl.
Usage for methods:
```webidl
@@ -1461,21 +1419,22 @@ Consider the following example:
};
```
-Then you can write custom bindings in Source/bindings/v8/custom/V8XXXConstructorCustom.cpp:
+Then you can write custom bindings in third_party/blink/renderer/bindings/{core,modules}/v8/custom/v8_xxx_constructor_custom.cc:
```c++
-v8::Local<v8::Value> V8XXX::constructorCallback(const v8::Arguments& args)
-{
- ...;
+v8::Local<v8::Value> V8XXX::ConstructorCallback(const v8::Arguments& args) {
+ ...;
}
```
-### [FlexibleArrayBufferView]
+### [FlexibleArrayBufferView] _(p)_
Summary: `[FlexibleArrayBufferView]` wraps a parameter that is known to be an ArrayBufferView (or a subtype of, e.g. typed arrays) with a FlexibleArrayBufferView.
The FlexibleArrayBufferView itself can then either refer to an actual ArrayBufferView or a temporary copy (for small payloads) that may even live on the stack. The idea is that copying the payload on the stack and referring to the temporary copy saves creating global handles (resulting in weak roots) in V8. Note that `[FlexibleArrayBufferView]` will actually result in a TypedFlexibleArrayBufferView wrapper for typed arrays.
+The FlexibleArrayBufferView extended attribute always requires the AllowShared extended attribute.
+
Usage: Applies to arguments of methods. See modules/webgl/WebGLRenderingContextBase.idl for an example.
### [AllowShared] _(p)_
@@ -1576,7 +1535,7 @@ Register the required property in V8PrivateProperty.h.
To update the cached value (e.g. for HTMLFoo.bar) proceed as follows:
```c++
-V8PrivateProperty::getHTMLFooBarCachedAccessor().set(context, object, newValue);
+V8PrivateProperty::GetHTMLFooBarCachedAccessor().Set(context, object, new_value);
```
@@ -1613,7 +1572,7 @@ Usage: `[DoNotCheckConstants]` can be specified on interfaces:
```webidl
[
- DoNotCheckConstants,
+ DoNotCheckConstants
] interface XXX {
const unsigned short NOT_FOUND_ERR = 12345;
const unsigned short SYNTAX_ERR = 12346;
@@ -1636,7 +1595,7 @@ Usage: The possible usage is `[ImplementedAs=XXX]`, where XXX is a method name i
```webidl
[
- ImplementedAs=DOMPath,
+ ImplementedAs=DOMPath
] interface Path {
[ImplementedAs=classAttribute] attribute int class;
[ImplementedAs=deleteFunction] void delete();
@@ -1666,7 +1625,6 @@ Added to members of a partial interface definition (and implemented interfaces w
* `[ImmutablePrototype]`
* `[LegacyInterfaceTypeChecking]`
* `[LogAllWorlds]`
-* `[OverrideBuiltins]` :: used on named accessors
* `[PerWorldBindings]` :: interacts with `[LogActivity]`
* `[WebAgentAPI]`
diff --git a/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.txt b/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.txt
index 993ca86ca16..9a36e75ff2d 100644
--- a/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.txt
+++ b/chromium/third_party/blink/renderer/bindings/IDLExtendedAttributes.txt
@@ -57,7 +57,7 @@ EnforceRange
Exposed=*
FeaturePolicy=*
FlexibleArrayBufferView
-Global=|*
+Global=*
HTMLConstructor
ImmutablePrototype
ImplementedAs=*
@@ -79,7 +79,6 @@ OverrideBuiltins
PartialInterfaceImplementedAs=*
PermissiveDictionaryConversion
PerWorldBindings
-PrimaryGlobal=|*
PutForwards=*
RaisesException=|Getter|Setter|Constructor
Reflect=|*
@@ -101,7 +100,7 @@ Serializable
SetterCallWith=ExecutionContext|ScriptState|ScriptArguments|CurrentWindow|EnteredWindow
Transferable
TreatNonObjectAsNull
-TreatNullAs=NullString|EmptyString
+TreatNullAs=EmptyString
URL
Unforgeable
Unscopable
diff --git a/chromium/third_party/blink/renderer/bindings/IDLUnionTypes.md b/chromium/third_party/blink/renderer/bindings/IDLUnionTypes.md
index b123c9406c2..fa9558e2204 100644
--- a/chromium/third_party/blink/renderer/bindings/IDLUnionTypes.md
+++ b/chromium/third_party/blink/renderer/bindings/IDLUnionTypes.md
@@ -21,49 +21,42 @@ core/modules.
The file name for a generated class is basically the same as its class
name, but we use some aliases to avoid too-long file names
-(See http://crbug.com/611437 why we need to avoid long file names).
-Currently we use following alias(es).
-
-```
-CanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContextOrImageBitmapRenderingContextOrXRPresentationContext -> RenderingContext
-```
+(See https://crbug.com/611437 why we need to avoid long file names).
The paths for generated classes depend on the places union types are
-used. If a union type is used only by IDL files under modules/, the
-include path is `bindings/modules/v8/FooOrBar.h`. Otherwise, the
-include path is `bindings/core/v8/FooOrBar.h`. For example, given
+used. If a union type is used only in IDL files under modules/, the
+include path is `bindings/modules/v8/foo_or_bar.h`. Otherwise, the
+include path is `bindings/core/v8/foo_or_bar.h`. For example, given
following definitions:
```webidl
-// core/fileapi/FileReader.idl
+// core/fileapi/file_reader.idl
readonly attribute (DOMString or ArrayBuffer)? result;
-// dom/CommonDefinitions.idl
+// dom/common_definitions.idl
typedef (ArrayBuffer or ArrayBufferView) BufferSource;
-// modules/encoding/TextDecoder.idl
+// modules/encoding/text_decoder.idl
DOMString decode(optional BufferSource input, optional TextDecodeOptions options);
-// modules/fetch/Request.idl
+// modules/fetch/request.idl
typedef (Request or USVString) RequestInfo;
```
The include paths will be:
-- bindings/core/v8/StringOrArrayBuffer.h
-- bindings/core/v8/ArrayBufferOrArrayBufferView.h
-- bindings/modules/v8/RequestOrUSVString.h
+- bindings/core/v8/string_or_array_buffer.h
+- bindings/core/v8/array_buffer_or_array_buffer_view.h
+- bindings/modules/v8/request_or_usv_string.h
-Note that `ArrayBufferOrArrayBufferView` is located under core/ even
-it is used by `Request.idl` which is located under modules/.
+Note that `array_buffer_or_array_buffer_view.h` is located under core/ even
+it is used by `request.idl` which is located under modules/.
**Special NOTE**: If you are going to use a union type under core/ and
the union type is currently used only under modules/, you will need
to update the include path for the union type under modules/.
-## Updating GN/GYP files
-TODO(bashi): Mitigate the pain of updating GN/GYP files.
-
-Due to the requirements of GN/GYP, we need to put generated file names
-in gni/gypi files. Please update
-`bindings/core/v8/generated.{gni,gypi}` and/or
-`bindings/modules/v8/generated.{gni,gypi}` accordingly.
+## Updating GN files
+Due to the requirements of GN, we need to put generated file names
+in GN files. Please update
+`bindings/core/v8/generated.gni` and/or
+`bindings/modules/v8/generated.gni` accordingly.
diff --git a/chromium/third_party/blink/renderer/bindings/OWNERS b/chromium/third_party/blink/renderer/bindings/OWNERS
index 10235ec3e28..b0d7b28ad92 100644
--- a/chromium/third_party/blink/renderer/bindings/OWNERS
+++ b/chromium/third_party/blink/renderer/bindings/OWNERS
@@ -10,7 +10,7 @@ mkwst@chromium.org
mlippautz@chromium.org
peria@chromium.org
pfeldman@chromium.org
-vivek.vg@samsung.com
+vivekg@chromium.org
yhirano@chromium.org
yukishiino@chromium.org
diff --git a/chromium/third_party/blink/renderer/bindings/bindings.gni b/chromium/third_party/blink/renderer/bindings/bindings.gni
index d94d982b2dc..104cce2c56d 100644
--- a/chromium/third_party/blink/renderer/bindings/bindings.gni
+++ b/chromium/third_party/blink/renderer/bindings/bindings.gni
@@ -21,6 +21,8 @@ bindings_core_v8_files =
"core/v8/custom/v8_message_event_custom.cc",
"core/v8/custom/v8_pop_state_event_custom.cc",
"core/v8/custom/v8_promise_rejection_event_custom.cc",
+ "core/v8/custom/v8_readable_stream_custom.cc",
+ "core/v8/custom/v8_writable_stream_custom.cc",
"core/v8/custom/v8_shadow_root_custom.cc",
"core/v8/custom/v8_window_custom.cc",
"core/v8/custom/v8_xml_http_request_custom.cc",
@@ -68,6 +70,8 @@ bindings_core_v8_files =
"core/v8/scheduled_action.h",
"core/v8/script_controller.cc",
"core/v8/script_controller.h",
+ "core/v8/isolated_world_csp.cc",
+ "core/v8/isolated_world_csp.h",
"core/v8/script_custom_element_definition.cc",
"core/v8/script_custom_element_definition.h",
"core/v8/script_custom_element_definition_builder.cc",
@@ -80,6 +84,7 @@ bindings_core_v8_files =
"core/v8/script_iterator.h",
"core/v8/script_module.cc",
"core/v8/script_module.h",
+ "core/v8/sanitize_script_errors.h",
"core/v8/script_promise.cc",
"core/v8/script_promise.h",
"core/v8/script_promise_property.h",
diff --git a/chromium/third_party/blink/renderer/bindings/core/BUILD.gn b/chromium/third_party/blink/renderer/bindings/core/BUILD.gn
index 9c533ab9aaf..49e828ece7b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/BUILD.gn
+++ b/chromium/third_party/blink/renderer/bindings/core/BUILD.gn
@@ -41,8 +41,16 @@ generate_global_constructors("core_global_constructors_idls") {
}
generate_web_idl_collection("core_web_idl_collection") {
- sources = core_static_interface_idl_files - core_testing_definition_idl_files
- output = "WebIdlCollectionForCore.pickle"
+ # |sources| contains all IDL files under core/.
+ sources = core_static_interface_idl_files +
+ core_generated_interface_idl_files + core_all_dependency_idl_files
+ output = "web_idl_collection_for_core.pickle"
component = "core"
output_dir = bindings_core_output_dir
+ deps = [
+ "//third_party/blink/renderer/bindings/core:core_global_constructors_idls",
+ "//third_party/blink/renderer/core:generated_testing_idls",
+ "//third_party/blink/renderer/core:generated_testing_idls_internal_runtime_flags",
+ "//third_party/blink/renderer/core:generated_testing_idls_settings",
+ ]
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/BUILD.gn b/chromium/third_party/blink/renderer/bindings/core/v8/BUILD.gn
index 136cb11e63a..b37b8ca15c5 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/BUILD.gn
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/BUILD.gn
@@ -80,12 +80,12 @@ bindings_core_generated_union_type_files = [
"$bindings_core_v8_output_dir/string_or_array_buffer_or_array_buffer_view.h",
"$bindings_core_v8_output_dir/string_or_css_variable_reference_value.cc",
"$bindings_core_v8_output_dir/string_or_css_variable_reference_value.h",
- "$bindings_core_v8_output_dir/string_or_dictionary.cc",
- "$bindings_core_v8_output_dir/string_or_dictionary.h",
"$bindings_core_v8_output_dir/string_or_double.cc",
"$bindings_core_v8_output_dir/string_or_double.h",
"$bindings_core_v8_output_dir/string_or_double_or_performance_measure_options.cc",
"$bindings_core_v8_output_dir/string_or_double_or_performance_measure_options.h",
+ "$bindings_core_v8_output_dir/string_or_element_creation_options.cc",
+ "$bindings_core_v8_output_dir/string_or_element_creation_options.h",
"$bindings_core_v8_output_dir/string_or_string_sequence.cc",
"$bindings_core_v8_output_dir/string_or_string_sequence.h",
"$bindings_core_v8_output_dir/string_or_trusted_html.cc",
@@ -98,6 +98,8 @@ bindings_core_generated_union_type_files = [
"$bindings_core_v8_output_dir/string_or_trusted_script_url.h",
"$bindings_core_v8_output_dir/string_or_unrestricted_double_sequence.cc",
"$bindings_core_v8_output_dir/string_or_unrestricted_double_sequence.h",
+ "$bindings_core_v8_output_dir/string_treat_null_as_empty_string_or_trusted_script.cc",
+ "$bindings_core_v8_output_dir/string_treat_null_as_empty_string_or_trusted_script.h",
"$bindings_core_v8_output_dir/usv_string_or_trusted_url.cc",
"$bindings_core_v8_output_dir/usv_string_or_trusted_url.h",
"$bindings_core_v8_output_dir/usv_string_sequence_sequence_or_usv_string_usv_string_record_or_usv_string.cc",
@@ -130,8 +132,22 @@ generated_core_testing_callback_function_files = [
generated_core_callback_function_files = [
"$bindings_core_v8_output_dir/v8_blob_callback.cc",
"$bindings_core_v8_output_dir/v8_blob_callback.h",
+ "$bindings_core_v8_output_dir/v8_create_html_callback.cc",
+ "$bindings_core_v8_output_dir/v8_create_html_callback.h",
+ "$bindings_core_v8_output_dir/v8_create_script_callback.cc",
+ "$bindings_core_v8_output_dir/v8_create_script_callback.h",
+ "$bindings_core_v8_output_dir/v8_create_url_callback.cc",
+ "$bindings_core_v8_output_dir/v8_create_url_callback.h",
+ "$bindings_core_v8_output_dir/v8_custom_element_adopted_callback.cc",
+ "$bindings_core_v8_output_dir/v8_custom_element_adopted_callback.h",
+ "$bindings_core_v8_output_dir/v8_custom_element_attribute_changed_callback.cc",
+ "$bindings_core_v8_output_dir/v8_custom_element_attribute_changed_callback.h",
"$bindings_core_v8_output_dir/v8_custom_element_constructor.cc",
"$bindings_core_v8_output_dir/v8_custom_element_constructor.h",
+ "$bindings_core_v8_output_dir/v8_custom_element_disabled_state_changed_callback.cc",
+ "$bindings_core_v8_output_dir/v8_custom_element_disabled_state_changed_callback.h",
+ "$bindings_core_v8_output_dir/v8_custom_element_form_associated_callback.cc",
+ "$bindings_core_v8_output_dir/v8_custom_element_form_associated_callback.h",
"$bindings_core_v8_output_dir/v8_display_lock_callback.cc",
"$bindings_core_v8_output_dir/v8_display_lock_callback.h",
"$bindings_core_v8_output_dir/v8_event_handler_non_null.cc",
@@ -158,12 +174,6 @@ generated_core_callback_function_files = [
"$bindings_core_v8_output_dir/v8_resize_observer_callback.h",
"$bindings_core_v8_output_dir/v8_scroll_state_callback.cc",
"$bindings_core_v8_output_dir/v8_scroll_state_callback.h",
- "$bindings_core_v8_output_dir/v8_create_html_callback.cc",
- "$bindings_core_v8_output_dir/v8_create_html_callback.h",
- "$bindings_core_v8_output_dir/v8_create_script_callback.cc",
- "$bindings_core_v8_output_dir/v8_create_script_callback.h",
- "$bindings_core_v8_output_dir/v8_create_url_callback.cc",
- "$bindings_core_v8_output_dir/v8_create_url_callback.h",
"$bindings_core_v8_output_dir/v8_task_queue_post_callback.cc",
"$bindings_core_v8_output_dir/v8_task_queue_post_callback.h",
"$bindings_core_v8_output_dir/v8_void_function.cc",
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/activity_logger_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/activity_logger_test.cc
index a20c1a6c6dc..bd66a123f0b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/activity_logger_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/activity_logger_test.cc
@@ -17,8 +17,8 @@
namespace blink {
-using blink::FrameTestHelpers::WebViewHelper;
-using blink::FrameTestHelpers::PumpPendingRequestsForFrameToLoad;
+using blink::frame_test_helpers::WebViewHelper;
+using blink::frame_test_helpers::PumpPendingRequestsForFrameToLoad;
class TestActivityLogger : public V8DOMActivityLogger {
public:
@@ -81,8 +81,8 @@ class ActivityLoggerTest : public testing::Test {
->MainFrameImpl()
->GetFrame()
->GetScriptController();
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- "about:blank");
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank");
}
~ActivityLoggerTest() override { WebCache::Clear(); }
@@ -96,7 +96,8 @@ class ActivityLoggerTest : public testing::Test {
void ExecuteScriptInIsolatedWorld(const String& script) const {
v8::HandleScope scope(v8::Isolate::GetCurrent());
script_controller_->ExecuteScriptInIsolatedWorld(
- kIsolatedWorldId, ScriptSourceCode(script), KURL(), kOpaqueResource);
+ kIsolatedWorldId, ScriptSourceCode(script), KURL(),
+ SanitizeScriptErrors::kSanitize);
PumpPendingRequestsForFrameToLoad(web_view_helper_.LocalMainFrame());
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.cc b/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.cc
index 62c993e3500..1247b37e548 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.cc
@@ -42,13 +42,53 @@
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
+void BindingSecurity::Init() {
+ BindingSecurityForPlatform::SetShouldAllowAccessToV8ContextWithExceptionState(
+ ShouldAllowAccessToV8Context);
+ BindingSecurityForPlatform::
+ SetShouldAllowAccessToV8ContextWithErrorReportOption(
+ ShouldAllowAccessToV8Context);
+ BindingSecurityForPlatform::SetShouldAllowWrapperCreationOrThrowException(
+ ShouldAllowWrapperCreationOrThrowException);
+ BindingSecurityForPlatform::SetRethrowWrapperCreationException(
+ RethrowWrapperCreationException);
+}
+
namespace {
+void ReportOrThrowSecurityError(const LocalDOMWindow* accessing_window,
+ const DOMWindow* target_window,
+ ExceptionState& exception_state) {
+ if (target_window) {
+ exception_state.ThrowSecurityError(
+ target_window->SanitizedCrossDomainAccessErrorMessage(accessing_window),
+ target_window->CrossDomainAccessErrorMessage(accessing_window));
+ } else {
+ exception_state.ThrowSecurityError("Cross origin access was denied.");
+ }
+}
+
+void ReportOrThrowSecurityError(
+ const LocalDOMWindow* accessing_window,
+ const DOMWindow* target_window,
+ BindingSecurity::ErrorReportOption reporting_option) {
+ if (reporting_option == BindingSecurity::ErrorReportOption::kDoNotReport)
+ return;
+
+ if (accessing_window && target_window) {
+ accessing_window->PrintErrorMessage(
+ target_window->CrossDomainAccessErrorMessage(accessing_window));
+ } else if (accessing_window) {
+ accessing_window->PrintErrorMessage("Cross origin access was denied.");
+ } else {
+ // Nowhere to report the error.
+ }
+}
+
bool CanAccessWindowInternal(const LocalDOMWindow* accessing_window,
const DOMWindow* target_window) {
SECURITY_CHECK(!(target_window && target_window->GetFrame()) ||
@@ -90,39 +130,24 @@ bool CanAccessWindowInternal(const LocalDOMWindow* accessing_window,
return true;
}
+template <typename ExceptionStateOrErrorReportOption>
bool CanAccessWindow(const LocalDOMWindow* accessing_window,
const DOMWindow* target_window,
- ExceptionState& exception_state) {
- if (CanAccessWindowInternal(accessing_window, target_window))
- return true;
-
- if (target_window)
- exception_state.ThrowSecurityError(
- target_window->SanitizedCrossDomainAccessErrorMessage(accessing_window),
- target_window->CrossDomainAccessErrorMessage(accessing_window));
- return false;
-}
-
-bool CanAccessWindow(const LocalDOMWindow* accessing_window,
- const DOMWindow* target_window,
- BindingSecurity::ErrorReportOption reporting_option) {
+ ExceptionStateOrErrorReportOption& error_report) {
if (CanAccessWindowInternal(accessing_window, target_window))
return true;
- if (accessing_window && target_window &&
- reporting_option == BindingSecurity::ErrorReportOption::kReport)
- accessing_window->PrintErrorMessage(
- target_window->CrossDomainAccessErrorMessage(accessing_window));
+ ReportOrThrowSecurityError(accessing_window, target_window, error_report);
return false;
}
DOMWindow* FindWindow(v8::Isolate* isolate,
const WrapperTypeInfo* type,
v8::Local<v8::Object> holder) {
- if (V8Window::wrapperTypeInfo.Equals(type))
+ if (V8Window::wrapper_type_info.Equals(type))
return V8Window::ToImpl(holder);
- if (V8Location::wrapperTypeInfo.Equals(type))
+ if (V8Location::wrapper_type_info.Equals(type))
return V8Location::ToImpl(holder)->DomWindow();
// This function can handle only those types listed above.
@@ -285,99 +310,112 @@ bool BindingSecurity::ShouldAllowAccessToFrame(
reporting_option);
}
-bool BindingSecurity::ShouldAllowNamedAccessTo(
- const DOMWindow* accessing_window,
- const DOMWindow* target_window) {
- const Frame* accessing_frame = accessing_window->GetFrame();
- DCHECK(accessing_frame);
- DCHECK(accessing_frame->GetSecurityContext());
- const SecurityOrigin* accessing_origin =
- accessing_frame->GetSecurityContext()->GetSecurityOrigin();
+namespace {
- const Frame* target_frame = target_window->GetFrame();
- DCHECK(target_frame);
- DCHECK(target_frame->GetSecurityContext());
- const SecurityOrigin* target_origin =
- target_frame->GetSecurityContext()->GetSecurityOrigin();
- SECURITY_CHECK(!(target_window && target_window->GetFrame()) ||
- target_window == target_window->GetFrame()->DomWindow());
+template <typename ExceptionStateOrErrorReportOption>
+bool ShouldAllowAccessToV8ContextInternal(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ExceptionStateOrErrorReportOption& error_report) {
+ // Fast path for the most likely case.
+ if (accessing_context == target_context)
+ return true;
- if (!accessing_origin->CanAccess(target_origin))
+ // Workers and worklets do not support multiple contexts, so both of
+ // |accessing_context| and |target_context| must be windows at this point.
+
+ // remote_object->CreationContext() returns the empty handle. Remote contexts
+ // are unconditionally treated as cross origin.
+ if (target_context.IsEmpty()) {
+ ReportOrThrowSecurityError(ToLocalDOMWindow(accessing_context), nullptr,
+ error_report);
return false;
+ }
- // Note that there is no need to call back
- // FrameLoader::didAccessInitialDocument() because |targetWindow| must be
- // a child window inside iframe or frame and it doesn't have a URL bar,
- // so there is no need to worry about URL spoofing.
+ LocalFrame* target_frame = ToLocalFrameIfNotDetached(target_context);
+ // TODO(dcheng): Why doesn't this code just use DOMWindows throughout? Can't
+ // we just always use ToLocalDOMWindow(context)?
+ if (!target_frame) {
+ // Sandbox detached frames - they can't create cross origin objects.
+ LocalDOMWindow* accessing_window = ToLocalDOMWindow(accessing_context);
+ LocalDOMWindow* target_window = ToLocalDOMWindow(target_context);
- return true;
+ // TODO(https://crbug.com/723057): This is tricky: this intentionally uses
+ // the internal CanAccessWindow() helper rather than ShouldAllowAccessTo().
+ // ShouldAllowAccessTo() unconditionally denies access if the DOMWindow is
+ // not attached to a Frame, but this code is intended for handling the
+ // detached DOMWindow case.
+ return CanAccessWindow(accessing_window, target_window, error_report);
+ }
+
+ const DOMWrapperWorld& accessing_world =
+ DOMWrapperWorld::World(accessing_context);
+ const DOMWrapperWorld& target_world = DOMWrapperWorld::World(target_context);
+ CHECK_EQ(accessing_world.GetWorldId(), target_world.GetWorldId());
+
+ return !accessing_world.IsMainWorld() ||
+ BindingSecurity::ShouldAllowAccessToFrame(
+ ToLocalDOMWindow(accessing_context), target_frame, error_report);
}
-bool BindingSecurity::ShouldAllowAccessToCreationContext(
+} // namespace
+
+bool BindingSecurity::ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ExceptionState& exception_state) {
+ return ShouldAllowAccessToV8ContextInternal(accessing_context, target_context,
+ exception_state);
+}
+
+bool BindingSecurity::ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ErrorReportOption reporting_option) {
+ return ShouldAllowAccessToV8ContextInternal(accessing_context, target_context,
+ reporting_option);
+}
+
+bool BindingSecurity::ShouldAllowWrapperCreationOrThrowException(
+ v8::Local<v8::Context> accessing_context,
v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo* type) {
+ const WrapperTypeInfo* wrapper_type_info) {
+ // Fast path for the most likely case.
+ if (accessing_context == creation_context)
+ return true;
+
// According to
// https://html.spec.whatwg.org/multipage/browsers.html#security-location,
// cross-origin script access to a few properties of Location is allowed.
// Location already implements the necessary security checks.
- if (type->Equals(&V8Location::wrapperTypeInfo))
+ if (wrapper_type_info->Equals(&V8Location::wrapper_type_info))
return true;
- v8::Isolate* isolate = creation_context->GetIsolate();
- LocalFrame* frame = ToLocalFrameIfNotDetached(creation_context);
- ExceptionState exception_state(isolate, ExceptionState::kConstructionContext,
- type->interface_name);
- // TODO(dcheng): Why doesn't this code just use DOMWindows throughout? Can't
- // we just always use ToLocalDOMWindow(creation_context)?
- if (!frame) {
- // Sandbox detached frames - they can't create cross origin objects.
- LocalDOMWindow* calling_window = CurrentDOMWindow(isolate);
- LocalDOMWindow* target_window = ToLocalDOMWindow(creation_context);
-
- // TODO(https://crbug.com/723057): This is tricky: this intentionally uses
- // the internal CanAccessWindow() helper rather than ShouldAllowAccessTo().
- // ShouldAllowAccessTo() unconditionally denies access if the DOMWindow is
- // not attached to a Frame, but this code is intended for handling the
- // detached DOMWindow case.
- return CanAccessWindow(calling_window, target_window, exception_state);
- }
- const DOMWrapperWorld& current_world =
- DOMWrapperWorld::World(isolate->GetCurrentContext());
- CHECK_EQ(current_world.GetWorldId(),
- DOMWrapperWorld::World(creation_context).GetWorldId());
-
- return !current_world.IsMainWorld() ||
- ShouldAllowAccessToFrame(CurrentDOMWindow(isolate), frame,
- exception_state);
+ ExceptionState exception_state(accessing_context->GetIsolate(),
+ ExceptionState::kConstructionContext,
+ wrapper_type_info->interface_name);
+ return ShouldAllowAccessToV8Context(accessing_context, creation_context,
+ exception_state);
}
-void BindingSecurity::RethrowCrossContextException(
+void BindingSecurity::RethrowWrapperCreationException(
+ v8::Local<v8::Context> accessing_context,
v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo* type,
+ const WrapperTypeInfo* wrapper_type_info,
v8::Local<v8::Value> cross_context_exception) {
DCHECK(!cross_context_exception.IsEmpty());
v8::Isolate* isolate = creation_context->GetIsolate();
ExceptionState exception_state(isolate, ExceptionState::kConstructionContext,
- type->interface_name);
- if (type->Equals(&V8Location::wrapperTypeInfo)) {
- // Convert cross-context exception to security error
- LocalDOMWindow* calling_window = CurrentDOMWindow(isolate);
- LocalDOMWindow* target_window = ToLocalDOMWindow(creation_context);
- exception_state.ThrowSecurityError(
- target_window->SanitizedCrossDomainAccessErrorMessage(calling_window),
- target_window->CrossDomainAccessErrorMessage(calling_window));
+ wrapper_type_info->interface_name);
+ if (!ShouldAllowAccessToV8Context(accessing_context, creation_context,
+ exception_state)) {
+ // A cross origin exception has turned into a SecurityError.
+ CHECK(exception_state.HadException());
return;
}
exception_state.RethrowV8Exception(cross_context_exception);
}
-void BindingSecurity::InitWrapperCreationSecurityCheck() {
- WrapperCreationSecurityCheck::SetSecurityCheckFunction(
- &ShouldAllowAccessToCreationContext);
- WrapperCreationSecurityCheck::SetRethrowExceptionFunction(
- &RethrowCrossContextException);
-}
-
void BindingSecurity::FailedAccessCheckFor(v8::Isolate* isolate,
const WrapperTypeInfo* type,
v8::Local<v8::Object> holder) {
@@ -403,4 +441,32 @@ void BindingSecurity::FailedAccessCheckFor(v8::Isolate* isolate,
target->CrossDomainAccessErrorMessage(CurrentDOMWindow(isolate)));
}
+bool BindingSecurity::ShouldAllowNamedAccessTo(
+ const DOMWindow* accessing_window,
+ const DOMWindow* target_window) {
+ const Frame* accessing_frame = accessing_window->GetFrame();
+ DCHECK(accessing_frame);
+ DCHECK(accessing_frame->GetSecurityContext());
+ const SecurityOrigin* accessing_origin =
+ accessing_frame->GetSecurityContext()->GetSecurityOrigin();
+
+ const Frame* target_frame = target_window->GetFrame();
+ DCHECK(target_frame);
+ DCHECK(target_frame->GetSecurityContext());
+ const SecurityOrigin* target_origin =
+ target_frame->GetSecurityContext()->GetSecurityOrigin();
+ SECURITY_CHECK(!(target_window && target_window->GetFrame()) ||
+ target_window == target_window->GetFrame()->DomWindow());
+
+ if (!accessing_origin->CanAccess(target_origin))
+ return false;
+
+ // Note that there is no need to call back
+ // FrameLoader::didAccessInitialDocument() because |targetWindow| must be
+ // a child window inside iframe or frame and it doesn't have a URL bar,
+ // so there is no need to worry about URL spoofing.
+
+ return true;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.h b/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.h
index 9cd55701a56..115d0848b45 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/binding_security.h
@@ -32,6 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_BINDING_SECURITY_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/bindings/binding_security_for_platform.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "v8/include/v8.h"
@@ -45,16 +46,18 @@ class Location;
class Node;
struct WrapperTypeInfo;
+// BindingSecurity provides utility functions that determine access permission
+// between two realms. For example, is the current Window allowed to access the
+// target window?
class CORE_EXPORT BindingSecurity {
STATIC_ONLY(BindingSecurity);
public:
- enum class ErrorReportOption {
- kDoNotReport,
- kReport,
- };
+ using ErrorReportOption = BindingSecurityForPlatform::ErrorReportOption;
- // Check if the caller (|accessingWindow|) is allowed to access the JS
+ static void Init();
+
+ // Checks if the caller (|accessing_window|) is allowed to access the JS
// receiver object (|target|), where the receiver object is the JS object
// for which the DOM attribute or DOM operation is being invoked (in the
// form of receiver.domAttr or receiver.domOp()).
@@ -77,7 +80,7 @@ class CORE_EXPORT BindingSecurity {
const Location* target,
ErrorReportOption);
- // Check if the caller (|accessingWindow|) is allowed to access the JS
+ // Checks if the caller (|accessing_window|) is allowed to access the JS
// returned object (|target|), where the returned object is the JS object
// which is returned as a result of invoking a DOM attribute or DOM
// operation (in the form of
@@ -105,26 +108,36 @@ class CORE_EXPORT BindingSecurity {
const Frame* target,
ErrorReportOption);
- static void FailedAccessCheckFor(v8::Isolate*,
- const WrapperTypeInfo*,
- v8::Local<v8::Object> holder);
-
- // The following two functions were written to be called by
- // V8WrapperInstantiationScope before entering and after exiting an object's
- // creation context during wrapper creation.
-
- // Returns true if the current context has access to creationContext, and
- // throws a SecurityError if it doesn't have access.
- static bool ShouldAllowAccessToCreationContext(
+ // These overloads should be used only when checking a general access from
+ // one context to another context. For access to a receiver object or
+ // returned object, you should use the above overloads.
+ static bool ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ExceptionState&);
+ static bool ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ErrorReportOption);
+
+ // Checks if a wrapper creation of the given wrapper type associated with
+ // |creation_context| is allowed in |accessing_context|.
+ static bool ShouldAllowWrapperCreationOrThrowException(
+ v8::Local<v8::Context> accessing_context,
v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo*);
+ const WrapperTypeInfo* wrapper_type_info);
- static void RethrowCrossContextException(
+ // Rethrows a cross context exception, that is possibly cross origin.
+ // A SecurityError may be rethrown instead of the exception if necessary.
+ static void RethrowWrapperCreationException(
+ v8::Local<v8::Context> accessing_context,
v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo*,
+ const WrapperTypeInfo* wrapper_type_info,
v8::Local<v8::Value> cross_context_exception);
- static void InitWrapperCreationSecurityCheck();
+ static void FailedAccessCheckFor(v8::Isolate*,
+ const WrapperTypeInfo*,
+ v8::Local<v8::Object> holder);
private:
// Returns true if |accessingWindow| is allowed named access to |targetWindow|
@@ -136,7 +149,7 @@ class CORE_EXPORT BindingSecurity {
// |accessingWindow| or |targetWindow| is a RemoteDOMWindow, but remember that
// only limited operations are allowed on a RemoteDOMWindow.
//
- // This function should be only used from V8Window::namedPropertyGetterCustom.
+ // This function should be only used from V8Window::NamedPropertyGetterCustom.
friend class V8Window;
static bool ShouldAllowNamedAccessTo(const DOMWindow* accessing_window,
const DOMWindow* target_window);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.cc
index 985c052bfa9..dc98870bf5c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.cc
@@ -43,7 +43,7 @@ namespace blink {
V8CustomXPathNSResolver* V8CustomXPathNSResolver::Create(
ScriptState* script_state,
v8::Local<v8::Object> resolver) {
- return new V8CustomXPathNSResolver(script_state, resolver);
+ return MakeGarbageCollected<V8CustomXPathNSResolver>(script_state, resolver);
}
V8CustomXPathNSResolver::V8CustomXPathNSResolver(ScriptState* script_state,
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.h b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.h
index c4a90e04c30..5de4d586c2b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_custom_xpath_ns_resolver.h
@@ -47,13 +47,13 @@ class V8CustomXPathNSResolver final : public XPathNSResolver {
static V8CustomXPathNSResolver* Create(ScriptState*,
v8::Local<v8::Object> resolver);
+ V8CustomXPathNSResolver(ScriptState*, v8::Local<v8::Object> resolver);
+
AtomicString lookupNamespaceURI(const String& prefix) override;
void Trace(blink::Visitor*) override;
private:
- V8CustomXPathNSResolver(ScriptState*, v8::Local<v8::Object> resolver);
-
Member<ScriptState> script_state_;
v8::Local<v8::Object> resolver_; // Handle to resolver object.
};
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_dev_tools_host_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_dev_tools_host_custom.cc
index 2234657ffc5..d5878848ec7 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_dev_tools_host_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_dev_tools_host_custom.cc
@@ -45,7 +45,7 @@
namespace blink {
-void V8DevToolsHost::platformMethodCustom(
+void V8DevToolsHost::PlatformMethodCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
#if defined(OS_MACOSX)
V8SetReturnValue(info, V8AtomicString(info.GetIsolate(), "mac"));
@@ -124,7 +124,7 @@ static bool PopulateContextMenuItems(v8::Isolate* isolate,
return true;
}
-void V8DevToolsHost::showContextMenuAtPointMethodCustom(
+void V8DevToolsHost::ShowContextMenuAtPointMethodCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 3)
return;
@@ -154,8 +154,8 @@ void V8DevToolsHost::showContextMenuAtPointMethodCustom(
document = V8HTMLDocument::ToImplWithTypeCheck(isolate, info[3]);
} else {
v8::Local<v8::Object> window_wrapper =
- V8Window::findInstanceInPrototypeChain(
- isolate->GetEnteredContext()->Global(), isolate);
+ V8Window::FindInstanceInPrototypeChain(
+ isolate->GetEnteredOrMicrotaskContext()->Global(), isolate);
if (window_wrapper.IsEmpty())
return;
DOMWindow* window = V8Window::ToImpl(window_wrapper);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_element_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_element_custom.cc
index 6184abd88f3..081981b456c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_element_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_element_custom.cc
@@ -14,7 +14,7 @@ namespace blink {
// HTMLElement -----------------------------------------------------------------
-void V8Element::innerHTMLAttributeSetterCustom(
+void V8Element::InnerHTMLAttributeSetterCustom(
v8::Local<v8::Value> value,
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
@@ -37,7 +37,7 @@ void V8Element::innerHTMLAttributeSetterCustom(
if (value->IsNull()) {
cpp_value.SetString(String());
} else {
- V8StringOrTrustedHTML::ToImpl(info.GetIsolate(), value, cpp_value,
+ V8StringOrTrustedHTML::ToImpl(isolate, value, cpp_value,
UnionTypeConversionMode::kNotNullable,
exception_state);
}
@@ -47,7 +47,7 @@ void V8Element::innerHTMLAttributeSetterCustom(
impl->setInnerHTML(cpp_value, exception_state);
}
-void V8Element::outerHTMLAttributeSetterCustom(
+void V8Element::OuterHTMLAttributeSetterCustom(
v8::Local<v8::Value> value,
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
@@ -70,7 +70,7 @@ void V8Element::outerHTMLAttributeSetterCustom(
if (value->IsNull()) {
cpp_value.SetString(String());
} else {
- V8StringOrTrustedHTML::ToImpl(info.GetIsolate(), value, cpp_value,
+ V8StringOrTrustedHTML::ToImpl(isolate, value, cpp_value,
UnionTypeConversionMode::kNotNullable,
exception_state);
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_error_event_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_error_event_custom.cc
index 5176f91a49f..ca801c74c7d 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_error_event_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_error_event_custom.cc
@@ -34,7 +34,7 @@
namespace blink {
-void V8ErrorEvent::errorAttributeGetterCustom(
+void V8ErrorEvent::ErrorAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ErrorEvent* event = V8ErrorEvent::ToImpl(info.Holder());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_event_target_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_event_target_custom.cc
index 6281d270c37..342f622eef5 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_event_target_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_event_target_custom.cc
@@ -36,7 +36,7 @@
namespace blink {
-void V8EventTarget::addEventListenerMethodPrologueCustom(
+void V8EventTarget::AddEventListenerMethodPrologueCustom(
const v8::FunctionCallbackInfo<v8::Value>& info,
EventTarget*) {
if (info.Length() >= 3 && info[2]->IsObject()) {
@@ -49,7 +49,7 @@ void V8EventTarget::addEventListenerMethodPrologueCustom(
}
}
-void V8EventTarget::removeEventListenerMethodPrologueCustom(
+void V8EventTarget::RemoveEventListenerMethodPrologueCustom(
const v8::FunctionCallbackInfo<v8::Value>& info,
EventTarget*) {
if (info.Length() >= 3 && info[2]->IsObject()) {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_all_collection_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_all_collection_custom.cc
index 2b2193921e3..c3c3d5942ee 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_all_collection_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_all_collection_custom.cc
@@ -65,14 +65,14 @@ void GetIndexedOrNamed(const v8::FunctionCallbackInfo<v8::Value>& info) {
V8SetReturnValue(info, result);
}
-void V8HTMLAllCollection::legacyCallCustom(
+void V8HTMLAllCollection::LegacyCallCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(
info.GetIsolate(), "Blink_V8HTMLAllCollection_legacyCallCustom");
GetIndexedOrNamed(info);
}
-void V8HTMLAllCollection::itemMethodCustom(
+void V8HTMLAllCollection::ItemMethodCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(
info.GetIsolate(), "Blink_V8HTMLAllCollection_itemMethodCustom");
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_plugin_element_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_plugin_element_custom.cc
index 43bcdb3b3c4..42ee936aeef 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_plugin_element_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_html_plugin_element_custom.cc
@@ -64,13 +64,15 @@ void GetScriptableObjectProperty(
if (instance.IsEmpty())
return;
- v8::Local<v8::String> v8_name = V8String(info.GetIsolate(), name);
- if (!V8CallBoolean(instance->HasOwnProperty(state->GetContext(), v8_name)))
- return;
-
+ v8::Local<v8::String> v8_name = V8AtomicString(info.GetIsolate(), name);
+ bool has_own_property;
v8::Local<v8::Value> value;
- if (!instance->Get(state->GetContext(), v8_name).ToLocal(&value))
+ if (!instance->HasOwnProperty(state->GetContext(), v8_name)
+ .To(&has_own_property) ||
+ !has_own_property ||
+ !instance->Get(state->GetContext(), v8_name).ToLocal(&value)) {
return;
+ }
V8SetReturnValue(info, value);
}
@@ -94,9 +96,13 @@ void SetScriptableObjectProperty(
return;
// Don't intercept any of the properties of the HTMLPluginElement.
- v8::Local<v8::String> v8_name = V8String(info.GetIsolate(), name);
- if (!V8CallBoolean(instance->HasOwnProperty(state->GetContext(), v8_name)) &&
- V8CallBoolean(info.Holder()->Has(state->GetContext(), v8_name))) {
+ v8::Local<v8::String> v8_name = V8AtomicString(info.GetIsolate(), name);
+ v8::Local<v8::Context> context = state->GetContext();
+ bool instance_has_property;
+ bool holder_has_property;
+ if (!instance->HasOwnProperty(context, v8_name).To(&instance_has_property) ||
+ !info.Holder()->Has(context, v8_name).To(&holder_has_property) ||
+ (!instance_has_property && holder_has_property)) {
return;
}
@@ -109,14 +115,16 @@ void SetScriptableObjectProperty(
// DOM element will also be set. For plugin's that don't intercept the call
// (all except gTalk) this makes no difference at all. For gTalk the fact
// that the property on the DOM element also gets set is inconsequential.
- V8CallBoolean(
- instance->CreateDataProperty(state->GetContext(), v8_name, value));
+ bool created;
+ if (!instance->CreateDataProperty(context, v8_name, value).To(&created))
+ return;
+
V8SetReturnValue(info, value);
}
} // namespace
-void V8HTMLEmbedElement::namedPropertyGetterCustom(
+void V8HTMLEmbedElement::NamedPropertyGetterCustom(
const AtomicString& name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
UseCounter::Count(CurrentExecutionContext(info.GetIsolate()),
@@ -124,7 +132,7 @@ void V8HTMLEmbedElement::namedPropertyGetterCustom(
GetScriptableObjectProperty<V8HTMLEmbedElement>(name, info);
}
-void V8HTMLObjectElement::namedPropertyGetterCustom(
+void V8HTMLObjectElement::NamedPropertyGetterCustom(
const AtomicString& name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
UseCounter::Count(CurrentExecutionContext(info.GetIsolate()),
@@ -132,7 +140,7 @@ void V8HTMLObjectElement::namedPropertyGetterCustom(
GetScriptableObjectProperty<V8HTMLObjectElement>(name, info);
}
-void V8HTMLEmbedElement::namedPropertySetterCustom(
+void V8HTMLEmbedElement::NamedPropertySetterCustom(
const AtomicString& name,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
@@ -141,7 +149,7 @@ void V8HTMLEmbedElement::namedPropertySetterCustom(
SetScriptableObjectProperty<V8HTMLEmbedElement>(name, value, info);
}
-void V8HTMLObjectElement::namedPropertySetterCustom(
+void V8HTMLObjectElement::NamedPropertySetterCustom(
const AtomicString& name,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_channel_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_channel_custom.cc
index 2988f550d91..29e05ce937b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_channel_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_channel_custom.cc
@@ -39,7 +39,7 @@
namespace blink {
-void V8MessageChannel::constructorCustom(
+void V8MessageChannel::ConstructorCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
@@ -57,7 +57,7 @@ void V8MessageChannel::constructorCustom(
wrapper, ToV8(channel->port2(), wrapper, isolate));
V8SetReturnValue(info, V8DOMWrapper::AssociateObjectWithWrapper(
- isolate, channel, &wrapperTypeInfo, wrapper));
+ isolate, channel, &wrapper_type_info, wrapper));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_event_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_event_custom.cc
index ff1de20e626..864991f2a2f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_event_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_message_event_custom.cc
@@ -43,7 +43,7 @@
namespace blink {
-void V8MessageEvent::dataAttributeGetterCustom(
+void V8MessageEvent::DataAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
auto private_cached_data =
@@ -101,7 +101,7 @@ void V8MessageEvent::dataAttributeGetterCustom(
V8SetReturnValue(info, result);
}
-void V8MessageEvent::initMessageEventMethodCustom(
+void V8MessageEvent::InitMessageEventMethodCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
ExceptionState exception_state(info.GetIsolate(),
ExceptionState::kExecutionContext,
@@ -114,15 +114,8 @@ void V8MessageEvent::initMessageEventMethodCustom(
MessageEvent* event = V8MessageEvent::ToImpl(info.Holder());
TOSTRING_VOID(V8StringResource<>, type_arg, info[0]);
- bool bubbles_arg = false;
- bool cancelable_arg = false;
- if (!info[1]
- ->BooleanValue(info.GetIsolate()->GetCurrentContext())
- .To(&bubbles_arg) ||
- !info[2]
- ->BooleanValue(info.GetIsolate()->GetCurrentContext())
- .To(&cancelable_arg))
- return;
+ bool bubbles_arg = info[1]->BooleanValue(info.GetIsolate());
+ bool cancelable_arg = info[2]->BooleanValue(info.GetIsolate());
v8::Local<v8::Value> data_arg = info[3];
TOSTRING_VOID(V8StringResource<>, origin_arg, info[4]);
TOSTRING_VOID(V8StringResource<>, last_event_id_arg, info[5]);
@@ -131,7 +124,7 @@ void V8MessageEvent::initMessageEventMethodCustom(
MessagePortArray* port_array = nullptr;
const int kPortArrayIndex = 7;
if (!IsUndefinedOrNull(info[kPortArrayIndex])) {
- port_array = new MessagePortArray;
+ port_array = MakeGarbageCollected<MessagePortArray>();
*port_array = NativeValueTraits<IDLSequence<MessagePort>>::NativeValue(
info.GetIsolate(), info[kPortArrayIndex], exception_state);
if (exception_state.HadException())
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_pop_state_event_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_pop_state_event_custom.cc
index 2b6d7ec9724..28c17d96664 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_pop_state_event_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_pop_state_event_custom.cc
@@ -38,9 +38,9 @@
namespace blink {
namespace {
-// |kSymbolKey| is a key for a cached attribute for History.state.
+// |kHistoryStateSymbolKey| is a key for a cached attribute for History.state.
// TODO(peria): Do not use this cached attribute directly.
-constexpr char kSymbolKey[] = "History#State";
+constexpr char kHistoryStateSymbolKey[] = "History#State";
}
// Save the state value to a hidden attribute in the V8PopStateEvent, and return
@@ -53,7 +53,7 @@ static v8::Local<v8::Value> CacheState(ScriptState* script_state,
return state;
}
-void V8PopStateEvent::stateAttributeGetterCustom(
+void V8PopStateEvent::StateAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ScriptState* script_state = ScriptState::Current(isolate);
@@ -94,7 +94,7 @@ void V8PopStateEvent::stateAttributeGetterCustom(
bool is_same_state = history->IsSameAsCurrentState(event->SerializedState());
if (is_same_state) {
V8PrivateProperty::Symbol history_state =
- V8PrivateProperty::GetSymbol(isolate, kSymbolKey);
+ V8PrivateProperty::GetSymbol(isolate, kHistoryStateSymbolKey);
v8::Local<v8::Value> v8_history_value =
ToV8(history, info.Holder(), isolate);
if (v8_history_value.IsEmpty())
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_promise_rejection_event_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_promise_rejection_event_custom.cc
index c7900983580..0ba61950de5 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_promise_rejection_event_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_promise_rejection_event_custom.cc
@@ -14,7 +14,7 @@
namespace blink {
-void V8PromiseRejectionEvent::promiseAttributeGetterCustom(
+void V8PromiseRejectionEvent::PromiseAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_readable_stream_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_readable_stream_custom.cc
new file mode 100644
index 00000000000..829ca7a3dce
--- /dev/null
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_readable_stream_custom.cc
@@ -0,0 +1,52 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+void V8ReadableStream::ConstructorCustom(
+ const v8::FunctionCallbackInfo<v8::Value>& info) {
+ RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(
+ info.GetIsolate(), "Blink_ReadableStream_ConstructorCallback");
+
+ ExceptionState exception_state(info.GetIsolate(),
+ ExceptionState::kConstructionContext,
+ "ReadableStream");
+ ScriptState* script_state =
+ ScriptState::From(info.NewTarget().As<v8::Object>()->CreationContext());
+
+ ScriptValue underlying_source =
+ ScriptValue(ScriptState::Current(info.GetIsolate()),
+ v8::Undefined(info.GetIsolate()));
+ ScriptValue strategy = ScriptValue(ScriptState::Current(info.GetIsolate()),
+ v8::Undefined(info.GetIsolate()));
+ int num_args = info.Length();
+ auto* impl = MakeGarbageCollected<ReadableStream>();
+ v8::Local<v8::Object> wrapper = info.Holder();
+ wrapper = impl->AssociateWithWrapper(
+ info.GetIsolate(), &V8ReadableStream::wrapper_type_info, wrapper);
+
+ if (num_args >= 1) {
+ underlying_source =
+ ScriptValue(ScriptState::Current(info.GetIsolate()), info[0]);
+ }
+ if (num_args >= 2)
+ strategy = ScriptValue(ScriptState::Current(info.GetIsolate()), info[1]);
+
+ impl->Init(script_state, underlying_source, strategy, exception_state);
+ if (exception_state.HadException()) {
+ return;
+ }
+ V8SetReturnValue(info, wrapper);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_shadow_root_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_shadow_root_custom.cc
index 45240052bbf..8a89c547551 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_shadow_root_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_shadow_root_custom.cc
@@ -14,7 +14,7 @@ namespace blink {
// HTMLShadowRoot --------------------------------------------------------------
-void V8ShadowRoot::innerHTMLAttributeSetterCustom(
+void V8ShadowRoot::InnerHTMLAttributeSetterCustom(
v8::Local<v8::Value> value,
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
@@ -37,7 +37,7 @@ void V8ShadowRoot::innerHTMLAttributeSetterCustom(
if (value->IsNull()) {
cpp_value.SetString(String());
} else {
- V8StringOrTrustedHTML::ToImpl(info.GetIsolate(), value, cpp_value,
+ V8StringOrTrustedHTML::ToImpl(isolate, value, cpp_value,
UnionTypeConversionMode::kNotNullable,
exception_state);
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_window_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_window_custom.cc
index cb3a09fdedb..b87d4471fce 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_window_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_window_custom.cc
@@ -58,12 +58,11 @@
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_private_property.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
-void V8Window::locationAttributeGetterCustom(
+void V8Window::LocationAttributeGetterCustom(
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Object> holder = info.Holder();
@@ -84,15 +83,15 @@ void V8Window::locationAttributeGetterCustom(
// cross-origin status changes by changing properties like |document.domain|.
if (window->IsRemoteDOMWindow()) {
DOMWrapperWorld& world = DOMWrapperWorld::Current(isolate);
- const auto* wrapper_type_info = location->GetWrapperTypeInfo();
+ const auto* location_wrapper_type = location->GetWrapperTypeInfo();
v8::Local<v8::Object> new_wrapper =
- wrapper_type_info->domTemplate(isolate, world)
+ location_wrapper_type->DomTemplate(isolate, world)
->NewRemoteInstance()
.ToLocalChecked();
DCHECK(!DOMDataStore::ContainsWrapper(location, isolate));
wrapper = V8DOMWrapper::AssociateObjectWithWrapper(
- isolate, location, wrapper_type_info, new_wrapper);
+ isolate, location, location_wrapper_type, new_wrapper);
} else {
wrapper = ToV8(location, holder, isolate);
}
@@ -100,7 +99,7 @@ void V8Window::locationAttributeGetterCustom(
V8SetReturnValue(info, wrapper);
}
-void V8Window::eventAttributeGetterCustom(
+void V8Window::EventAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
LocalDOMWindow* impl = ToLocalDOMWindow(V8Window::ToImpl(info.Holder()));
v8::Isolate* isolate = info.GetIsolate();
@@ -136,7 +135,7 @@ void V8Window::eventAttributeGetterCustom(
V8SetReturnValue(info, js_event);
}
-void V8Window::frameElementAttributeGetterCustom(
+void V8Window::FrameElementAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
LocalDOMWindow* impl = ToLocalDOMWindow(V8Window::ToImpl(info.Holder()));
Element* frameElement = impl->frameElement();
@@ -161,7 +160,7 @@ void V8Window::frameElementAttributeGetterCustom(
V8SetReturnValue(info, wrapper);
}
-void V8Window::openerAttributeSetterCustom(
+void V8Window::OpenerAttributeSetterCustom(
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<void>& info) {
v8::Isolate* isolate = info.GetIsolate();
@@ -197,7 +196,7 @@ void V8Window::openerAttributeSetterCustom(
}
}
-void V8Window::namedPropertyGetterCustom(
+void V8Window::NamedPropertyGetterCustom(
const AtomicString& name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
DOMWindow* window = V8Window::ToImpl(info.Holder());
@@ -235,13 +234,16 @@ void V8Window::namedPropertyGetterCustom(
CurrentExecutionContext(info.GetIsolate()),
WebFeature::
kNamedAccessOnWindow_ChildBrowsingContext_CrossOriginNameMismatch);
- // In addition to the above spec'ed case, we return the child window
- // regardless of step 3 due to crbug.com/701489 for the time being.
- // TODO(yukishiino): Makes iframe.name update the browsing context name
- // appropriately and makes the new name available in the named access on
- // window. Then, removes the following two lines.
- V8SetReturnValueFast(info, child->DomWindow(), window);
- return;
+ if (!RuntimeEnabledFeatures::
+ IgnoreCrossOriginWindowWhenNamedAccessOnWindowEnabled()) {
+ // In addition to the above spec'ed case, we return the child window
+ // regardless of step 3 due to crbug.com/701489 for the time being.
+ // TODO(yukishiino): Makes iframe.name update the browsing context name
+ // appropriately and makes the new name available in the named access on
+ // window. Then, removes the following two lines.
+ V8SetReturnValueFast(info, child->DomWindow(), window);
+ return;
+ }
}
// This is a cross-origin interceptor. Check that the caller has access to the
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_writable_stream_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_writable_stream_custom.cc
new file mode 100644
index 00000000000..bdc358aff38
--- /dev/null
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_writable_stream_custom.cc
@@ -0,0 +1,52 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this sink code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+void V8WritableStream::ConstructorCustom(
+ const v8::FunctionCallbackInfo<v8::Value>& info) {
+ RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(
+ info.GetIsolate(), "Blink_WritableStream_ConstructorCallback");
+
+ ExceptionState exception_state(info.GetIsolate(),
+ ExceptionState::kConstructionContext,
+ "WritableStream");
+ ScriptState* script_state =
+ ScriptState::From(info.NewTarget().As<v8::Object>()->CreationContext());
+
+ ScriptValue underlying_sink =
+ ScriptValue(ScriptState::Current(info.GetIsolate()),
+ v8::Undefined(info.GetIsolate()));
+ ScriptValue strategy = ScriptValue(ScriptState::Current(info.GetIsolate()),
+ v8::Undefined(info.GetIsolate()));
+ int num_args = info.Length();
+ auto* impl = MakeGarbageCollected<WritableStream>();
+ v8::Local<v8::Object> wrapper = info.Holder();
+ wrapper = impl->AssociateWithWrapper(
+ info.GetIsolate(), &V8WritableStream::wrapper_type_info, wrapper);
+
+ if (num_args >= 1) {
+ underlying_sink =
+ ScriptValue(ScriptState::Current(info.GetIsolate()), info[0]);
+ }
+ if (num_args >= 2)
+ strategy = ScriptValue(ScriptState::Current(info.GetIsolate()), info[1]);
+
+ impl->Init(script_state, underlying_sink, strategy, exception_state);
+ if (exception_state.HadException()) {
+ return;
+ }
+ V8SetReturnValue(info, wrapper);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_xml_http_request_custom.cc b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_xml_http_request_custom.cc
index 76b159e2ca8..eb2b4ec267d 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_xml_http_request_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/custom/v8_xml_http_request_custom.cc
@@ -46,7 +46,7 @@
namespace blink {
-void V8XMLHttpRequest::responseTextAttributeGetterCustom(
+void V8XMLHttpRequest::ResponseTextAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
XMLHttpRequest* xml_http_request = V8XMLHttpRequest::ToImpl(info.Holder());
ExceptionState exception_state(info.GetIsolate(),
@@ -60,7 +60,7 @@ void V8XMLHttpRequest::responseTextAttributeGetterCustom(
V8SetReturnValue(info, text);
}
-void V8XMLHttpRequest::responseAttributeGetterCustom(
+void V8XMLHttpRequest::ResponseAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
XMLHttpRequest* xml_http_request = V8XMLHttpRequest::ToImpl(info.Holder());
ExceptionState exception_state(info.GetIsolate(),
@@ -70,7 +70,7 @@ void V8XMLHttpRequest::responseAttributeGetterCustom(
switch (xml_http_request->GetResponseTypeCode()) {
case XMLHttpRequest::kResponseTypeDefault:
case XMLHttpRequest::kResponseTypeText:
- responseTextAttributeGetterCustom(info);
+ ResponseTextAttributeGetterCustom(info);
return;
case XMLHttpRequest::kResponseTypeJSON: {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/dictionary.cc b/chromium/third_party/blink/renderer/bindings/core/v8/dictionary.cc
index 39d148e830c..ef5dc17bd35 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/dictionary.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/dictionary.cc
@@ -95,13 +95,16 @@ bool Dictionary::Get(v8::Local<v8::Value> key,
if (dictionary_object_.IsEmpty())
return false;
- if (!V8CallBoolean(dictionary_object_->Has(V8Context(), key)))
- return false;
-
- // Swallow a possible exception in v8::Object::Get().
+ // Swallow possible exceptions in v8::Object::Get() and Has().
// TODO(bashi,yukishiino): Should rethrow the exception.
// http://crbug.com/666661
v8::TryCatch try_catch(GetIsolate());
+
+ bool has_property;
+ if (!dictionary_object_->Has(V8Context(), key).To(&has_property) ||
+ !has_property)
+ return false;
+
return dictionary_object_->Get(V8Context(), key).ToLocal(&result);
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/dictionary_helper_for_core.cc b/chromium/third_party/blink/renderer/bindings/core/v8/dictionary_helper_for_core.cc
index 72e61ab2a13..b8812eeebee 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/dictionary_helper_for_core.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/dictionary_helper_for_core.cc
@@ -61,7 +61,8 @@ CORE_EXPORT bool DictionaryHelper::Get(const Dictionary& dictionary,
if (!dictionary.Get(key, v8_value))
return false;
- return v8_value->BooleanValue(dictionary.V8Context()).To(&value);
+ value = v8_value->BooleanValue(dictionary.GetIsolate());
+ return true;
}
template <>
@@ -205,7 +206,7 @@ bool DictionaryHelper::Get(const Dictionary& dictionary,
// FIXME: this will need to be changed so it can also return an AudioTrack
// or a VideoTrack once we add them.
- v8::Local<v8::Object> track = V8TextTrack::findInstanceInPrototypeChain(
+ v8::Local<v8::Object> track = V8TextTrack::FindInstanceInPrototypeChain(
wrapper, dictionary.GetIsolate());
if (!track.IsEmpty())
source = V8TextTrack::ToImpl(track);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/dom_wrapper_world_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/dom_wrapper_world_test.cc
index ef15fb17869..b9a08e022a5 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/dom_wrapper_world_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/dom_wrapper_world_test.cc
@@ -23,9 +23,9 @@ Vector<scoped_refptr<DOMWrapperWorld>> CreateIsolatedWorlds(
v8::Isolate* isolate) {
Vector<scoped_refptr<DOMWrapperWorld>> worlds;
worlds.push_back(DOMWrapperWorld::EnsureIsolatedWorld(
- isolate, DOMWrapperWorld::WorldId::kMainWorldId + 1));
+ isolate, DOMWrapperWorld::kMainWorldId + 1));
worlds.push_back(DOMWrapperWorld::EnsureIsolatedWorld(
- isolate, DOMWrapperWorld::WorldId::kIsolatedWorldIdLimit - 1));
+ isolate, DOMWrapperWorld::kDOMWrapperWorldEmbedderWorldIdLimit - 1));
EXPECT_TRUE(worlds[0]->IsIsolatedWorld());
EXPECT_TRUE(worlds[1]->IsIsolatedWorld());
return worlds;
@@ -116,7 +116,7 @@ TEST(DOMWrapperWorldTest, Basic) {
ThreadCreationParams(WebThreadType::kTestThread)
.SetThreadNameForTest("DOMWrapperWorld test thread"));
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner =
- Platform::Current()->CurrentThread()->GetTaskRunner();
+ Thread::Current()->GetTaskRunner();
thread->BackingThread().PostTask(
FROM_HERE,
CrossThreadBind(&WorkerThreadFunc, CrossThreadUnretained(thread.get()),
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h b/chromium/third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h
index d8e51b805d6..8d6b90acf67 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h
@@ -15,17 +15,18 @@ namespace blink {
// This class provides toV8Impl() virtual function which will be overridden
// by auto-generated IDL dictionary impl classes. toV8Impl() is used
// in ToV8.h to provide a consistent API of ToV8().
-class CORE_EXPORT IDLDictionaryBase {
- DISALLOW_NEW();
-
+class CORE_EXPORT IDLDictionaryBase
+ : public GarbageCollectedFinalized<IDLDictionaryBase> {
public:
- IDLDictionaryBase() = default;
virtual ~IDLDictionaryBase() = default;
virtual v8::Local<v8::Value> ToV8Impl(v8::Local<v8::Object> creation_context,
v8::Isolate*) const;
virtual void Trace(blink::Visitor*);
+
+ protected:
+ IDLDictionaryBase() = default;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/idl_types.h b/chromium/third_party/blink/renderer/bindings/core/v8/idl_types.h
index a1c7d0727ab..b99256da089 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/idl_types.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/idl_types.h
@@ -31,6 +31,27 @@ struct IDLUnsignedLong final : public IDLBaseHelper<uint32_t> {};
struct IDLLongLong final : public IDLBaseHelper<int64_t> {};
struct IDLUnsignedLongLong final : public IDLBaseHelper<uint64_t> {};
+// [Clamp] Integers
+struct IDLByteClamp final : public IDLBaseHelper<int8_t> {};
+struct IDLOctetClamp final : public IDLBaseHelper<uint8_t> {};
+struct IDLShortClamp final : public IDLBaseHelper<int16_t> {};
+struct IDLUnsignedShortClamp final : public IDLBaseHelper<uint16_t> {};
+struct IDLLongClamp final : public IDLBaseHelper<int32_t> {};
+struct IDLUnsignedLongClamp final : public IDLBaseHelper<uint32_t> {};
+struct IDLLongLongClamp final : public IDLBaseHelper<int64_t> {};
+struct IDLUnsignedLongLongClamp final : public IDLBaseHelper<uint64_t> {};
+
+// [EnforceRange] Integers
+struct IDLByteEnforceRange final : public IDLBaseHelper<int8_t> {};
+struct IDLOctetEnforceRange final : public IDLBaseHelper<uint8_t> {};
+struct IDLShortEnforceRange final : public IDLBaseHelper<int16_t> {};
+struct IDLUnsignedShortEnforceRange final : public IDLBaseHelper<uint16_t> {};
+struct IDLLongEnforceRange final : public IDLBaseHelper<int32_t> {};
+struct IDLUnsignedLongEnforceRange final : public IDLBaseHelper<uint32_t> {};
+struct IDLLongLongEnforceRange final : public IDLBaseHelper<int64_t> {};
+struct IDLUnsignedLongLongEnforceRange final : public IDLBaseHelper<uint64_t> {
+};
+
// Strings
// The "Base" classes are always templatized and require users to specify how JS
// null and/or undefined are supposed to be handled.
@@ -46,6 +67,18 @@ using IDLByteString = IDLByteStringBase<V8StringResourceMode::kDefaultMode>;
using IDLString = IDLStringBase<V8StringResourceMode::kDefaultMode>;
using IDLUSVString = IDLUSVStringBase<V8StringResourceMode::kDefaultMode>;
+// Nullable strings
+using IDLByteStringOrNull =
+ IDLByteStringBase<V8StringResourceMode::kTreatNullAndUndefinedAsNullString>;
+using IDLStringOrNull =
+ IDLStringBase<V8StringResourceMode::kTreatNullAndUndefinedAsNullString>;
+using IDLUSVStringOrNull =
+ IDLUSVStringBase<V8StringResourceMode::kTreatNullAndUndefinedAsNullString>;
+
+// [TreatNullAs] Strings
+using IDLStringTreatNullAsEmptyString =
+ IDLStringBase<V8StringResourceMode::kTreatNullAsEmptyString>;
+
// Double
struct IDLDouble final : public IDLBaseHelper<double> {};
struct IDLUnrestrictedDouble final : public IDLBaseHelper<double> {};
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/idl_types_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/idl_types_test.cc
index 88e85671225..2e4af559d08 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/idl_types_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/idl_types_test.cc
@@ -112,8 +112,8 @@ static_assert(std::is_same<IDLSequence<Element>::ImplType,
HeapVector<Member<Element>>>::value,
"IDLSequence<GC-type>> produces a HeapVector<Member<>>");
static_assert(std::is_same<IDLSequence<InternalDictionary>::ImplType,
- HeapVector<InternalDictionary>>::value,
- "IDLSequence<dictionary type> produces a HeapVector");
+ HeapVector<Member<InternalDictionary>>>::value,
+ "IDLSequence<dictionary type> produces a HeapVector<Member<>>");
static_assert(std::is_same<IDLSequence<StringOrStringSequence>::ImplType,
HeapVector<StringOrStringSequence>>::value,
"IDLSequence<union type> produces a HeapVector");
@@ -130,9 +130,10 @@ static_assert(
HeapVector<std::pair<String, Member<Element>>>>::value,
"IDLRecord<IDLByteString, GC-type>> produces a HeapVector with Member<>");
static_assert(
- std::is_same<IDLRecord<IDLUSVString, InternalDictionary>::ImplType,
- HeapVector<std::pair<String, InternalDictionary>>>::value,
- "IDLRecord<IDLUSVString, dictionary type> produces a HeapVector with no "
+ std::is_same<
+ IDLRecord<IDLUSVString, InternalDictionary>::ImplType,
+ HeapVector<std::pair<String, Member<InternalDictionary>>>>::value,
+ "IDLRecord<IDLUSVString, dictionary type> produces a HeapVector with "
"Member<>");
static_assert(
std::is_same<IDLRecord<IDLString, StringOrStringSequence>::ImplType,
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.cc b/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.cc
index c83cc0f5655..f261dc2d84c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.cc
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/platform/bindings/to_v8.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "v8/include/v8.h"
namespace blink {
@@ -78,16 +79,96 @@ class CountUseForBindings : public ScriptFunction {
}
};
+void AddCountUse(ScriptState* script_state, v8::Local<v8::Object> binding) {
+ v8::Local<v8::Function> fn =
+ CountUseForBindings::CreateFunction(script_state);
+ v8::Local<v8::String> name =
+ V8AtomicString(script_state->GetIsolate(), "countUse");
+ binding->Set(script_state->GetContext(), name, fn).ToChecked();
+}
+
+void AddOriginals(ScriptState* script_state, v8::Local<v8::Object> binding) {
+ // These values are only used when serialization is enabled.
+ if (!RuntimeEnabledFeatures::TransferableStreamsEnabled())
+ return;
+
+ v8::Local<v8::Object> global = script_state->GetContext()->Global();
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Isolate* isolate = script_state->GetIsolate();
+
+ const auto ObjectGet = [&context, &isolate](v8::Local<v8::Value> object,
+ const char* property) {
+ DCHECK(object->IsObject());
+ return object.As<v8::Object>()
+ ->Get(context, V8AtomicString(isolate, property))
+ .ToLocalChecked();
+ };
+
+ const auto GetPrototype = [&ObjectGet](v8::Local<v8::Value> object) {
+ return ObjectGet(object, "prototype");
+ };
+
+ const auto GetOwnPD = [&context, &isolate](v8::Local<v8::Value> object,
+ const char* property) {
+ DCHECK(object->IsObject());
+ return object.As<v8::Object>()
+ ->GetOwnPropertyDescriptor(context, V8AtomicString(isolate, property))
+ .ToLocalChecked();
+ };
+
+ const auto GetOwnPDGet = [&ObjectGet, &GetOwnPD](v8::Local<v8::Value> object,
+ const char* property) {
+ return ObjectGet(GetOwnPD(object, property), "get");
+ };
+
+ const auto Bind = [&context, &isolate, &binding](const char* name,
+ v8::Local<v8::Value> value) {
+ bool result =
+ binding
+ ->CreateDataProperty(context, V8AtomicString(isolate, name), value)
+ .ToChecked();
+ DCHECK(result);
+ };
+
+ v8::Local<v8::Value> message_port = ObjectGet(global, "MessagePort");
+
+ // Some Worklets don't have MessagePort. In this case, serialization will
+ // be disabled.
+ if (message_port->IsUndefined())
+ return;
+
+ v8::Local<v8::Value> event_target_prototype =
+ GetPrototype(ObjectGet(global, "EventTarget"));
+ Bind("EventTarget_addEventListener",
+ ObjectGet(event_target_prototype, "addEventListener"));
+
+ v8::Local<v8::Value> message_port_prototype = GetPrototype(message_port);
+ Bind("MessagePort_postMessage",
+ ObjectGet(message_port_prototype, "postMessage"));
+ Bind("MessagePort_close", ObjectGet(message_port_prototype, "close"));
+ Bind("MessagePort_start", ObjectGet(message_port_prototype, "start"));
+
+ v8::Local<v8::Value> message_event_prototype =
+ GetPrototype(ObjectGet(global, "MessageEvent"));
+
+ Bind("MessageEvent_data_get", GetOwnPDGet(message_event_prototype, "data"));
+
+ v8::Local<v8::Value> dom_exception = ObjectGet(global, "DOMException");
+ Bind("DOMException", dom_exception);
+
+ v8::Local<v8::Value> dom_exception_prototype = GetPrototype(dom_exception);
+ Bind("DOMException_message_get",
+ GetOwnPDGet(dom_exception_prototype, "message"));
+ Bind("DOMException_name_get", GetOwnPDGet(dom_exception_prototype, "name"));
+}
+
} // namespace
void InitializeV8ExtrasBinding(ScriptState* script_state) {
v8::Local<v8::Object> binding =
script_state->GetContext()->GetExtrasBindingObject();
- v8::Local<v8::Function> fn =
- CountUseForBindings::CreateFunction(script_state);
- v8::Local<v8::String> name =
- V8AtomicString(script_state->GetIsolate(), "countUse");
- binding->Set(script_state->GetContext(), name, fn).FromJust();
+ AddCountUse(script_state, binding);
+ AddOriginals(script_state, binding);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.h b/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.h
index 9d06cdd8918..a0f066de265 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/initialize_v8_extras_binding.h
@@ -11,10 +11,8 @@ namespace blink {
class ScriptState;
-// Add the Javascript function countUse() to the "binding" object that is
-// exposed to the Javascript streams implementations.
-//
-// It must be called during initialisation of the V8 context.
+// Add the JavaScript function countUse() to the "binding" object that is
+// exposed to the JavaScript streams implementations.
//
// binding.countUse() takes a string and calls UseCounter::Count() on the
// matching ID. It only does anything the first time it is called in a
@@ -23,6 +21,12 @@ class ScriptState;
// than once to avoid unnecessary overhead. Only string IDs that this code
// specifically knows about will work.
//
+// Also copy the original values of MessageChannel, MessagePort and MessageEvent
+// methods and accessors to the binding object where they can be used for
+// serialization by the streams code.
+//
+// This function must be called during initialisation of the V8 context.
+//
// countUse() is not available during snapshot creation.
void CORE_EXPORT InitializeV8ExtrasBinding(ScriptState*);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.cc b/chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.cc
new file mode 100644
index 00000000000..c82ca3efb48
--- /dev/null
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.cc
@@ -0,0 +1,42 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h"
+
+#include "base/logging.h"
+#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
+#include "third_party/blink/renderer/platform/wtf/wtf.h"
+
+namespace blink {
+
+// static
+IsolatedWorldCSP& IsolatedWorldCSP::Get() {
+ DCHECK(IsMainThread());
+ DEFINE_STATIC_LOCAL(IsolatedWorldCSP, g_isolated_world_csp, ());
+ return g_isolated_world_csp;
+}
+
+void IsolatedWorldCSP::SetContentSecurityPolicy(int world_id,
+ const String& policy) {
+ DCHECK(IsMainThread());
+ DCHECK(DOMWrapperWorld::IsIsolatedWorldId(world_id));
+
+ if (policy.IsEmpty())
+ csp_map_.erase(world_id);
+ else
+ csp_map_.Set(world_id, true);
+}
+
+bool IsolatedWorldCSP::HasContentSecurityPolicy(int world_id) const {
+ DCHECK(IsMainThread());
+ DCHECK(DOMWrapperWorld::IsIsolatedWorldId(world_id));
+
+ auto it = csp_map_.find(world_id);
+ return it != csp_map_.end() ? it->value : false;
+}
+
+IsolatedWorldCSP::IsolatedWorldCSP() = default;
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h b/chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h
new file mode 100644
index 00000000000..99c61b6fdc7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h
@@ -0,0 +1,43 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_ISOLATED_WORLD_CSP_H_
+#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_ISOLATED_WORLD_CSP_H_
+
+#include "base/macros.h"
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+// A singleton storing content security policy for each isolated world.
+class CORE_EXPORT IsolatedWorldCSP {
+ public:
+ static IsolatedWorldCSP& Get();
+
+ // Associated an isolated world with a Content Security Policy. Resources
+ // embedded into the main world's DOM from script executed in an isolated
+ // world should be restricted based on the isolated world's DOM, not the
+ // main world's.
+ //
+ // FIXME: Right now, resource injection simply bypasses the main world's
+ // DOM. More work is necessary to allow the isolated world's policy to be
+ // applied correctly.
+ void SetContentSecurityPolicy(int world_id, const String& policy);
+ bool HasContentSecurityPolicy(int world_id) const;
+
+ private:
+ IsolatedWorldCSP();
+
+ // Map from the isolated world |world_id| to a bool denoting if it has a CSP
+ // defined.
+ HashMap<int, bool> csp_map_;
+
+ DISALLOW_COPY_AND_ASSIGN(IsolatedWorldCSP);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_ISOLATED_WORLD_CSP_H_
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/iterable.h b/chromium/third_party/blink/renderer/bindings/core/v8/iterable.h
index 374baf58e0f..9898cc7620f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/iterable.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/iterable.h
@@ -25,7 +25,7 @@ class Iterable {
this->StartIteration(script_state, exception_state);
if (!source)
return nullptr;
- return new IterableIterator<KeySelector>(source);
+ return MakeGarbageCollected<IterableIterator<KeySelector>>(source);
}
Iterator* valuesForBinding(ScriptState* script_state,
@@ -34,7 +34,7 @@ class Iterable {
this->StartIteration(script_state, exception_state);
if (!source)
return nullptr;
- return new IterableIterator<ValueSelector>(source);
+ return MakeGarbageCollected<IterableIterator<ValueSelector>>(source);
}
Iterator* entriesForBinding(ScriptState* script_state,
@@ -43,7 +43,7 @@ class Iterable {
this->StartIteration(script_state, exception_state);
if (!source)
return nullptr;
- return new IterableIterator<EntrySelector>(source);
+ return MakeGarbageCollected<IterableIterator<EntrySelector>>(source);
}
void forEachForBinding(ScriptState* script_state,
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc b/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc
index 8a01fe1b3fd..d31f6da9421 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/bindings/core/v8/js_based_event_listener.h"
+#include "third_party/blink/renderer/bindings/core/v8/binding_security.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -49,17 +50,13 @@ bool JSBasedEventListener::BelongsToTheCurrentWorld(
// Implements step 2. of "inner invoke".
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
-void JSBasedEventListener::handleEvent(
+void JSBasedEventListener::Invoke(
ExecutionContext* execution_context_of_event_target,
Event* event) {
DCHECK(execution_context_of_event_target);
DCHECK(event);
-
- // TODO(crbug.com/893449): Replace this early return by
- // DCHECK(event->target()) and DCHECK(event->currentTarget) because they
- // should not be null on dispatching event.
- if (!event->target() || !event->currentTarget())
- return;
+ DCHECK(event->target());
+ DCHECK(event->currentTarget());
v8::Isolate* isolate = GetIsolate();
@@ -73,7 +70,7 @@ void JSBasedEventListener::handleEvent(
return;
{
- v8::HandleScope scope(isolate);
+ v8::HandleScope handle_scope(isolate);
// Calling |GetListenerObject()| here may cause compilation of the
// uncompiled script body in eventHandler's value earlier than standard's
@@ -92,7 +89,7 @@ void JSBasedEventListener::handleEvent(
if (!script_state_of_listener->ContextIsValid())
return;
- ScriptState::Scope scope(script_state_of_listener);
+ ScriptState::Scope listener_script_state_scope(script_state_of_listener);
// https://dom.spec.whatwg.org/#firing-events
// Step 2. of firing events: Let event be the result of creating an event
@@ -101,11 +98,23 @@ void JSBasedEventListener::handleEvent(
// |js_event|, a V8 wrapper object for |event|, must be created in the
// relevant realm of the event target. The world must match the event
// listener's world.
- v8::Local<v8::Context> v8_context =
+ v8::Local<v8::Context> v8_context_of_event_target =
ToV8Context(execution_context_of_event_target, GetWorld());
- if (v8_context.IsEmpty())
+ if (v8_context_of_event_target.IsEmpty())
+ return;
+
+ // Check if the current context, which is set to the listener's relevant
+ // context by creating |listener_script_state_scope|, has access to the
+ // event target's relevant context before creating |js_event|. SecurityError
+ // is thrown if it doesn't have access.
+ if (!BindingSecurity::ShouldAllowAccessToV8Context(
+ script_state_of_listener->GetContext(), v8_context_of_event_target,
+ BindingSecurity::ErrorReportOption::kReport)) {
return;
- v8::Local<v8::Value> js_event = ToV8(event, v8_context->Global(), isolate);
+ }
+
+ v8::Local<v8::Value> js_event =
+ ToV8(event, v8_context_of_event_target->Global(), isolate);
if (js_event.IsEmpty())
return;
@@ -140,7 +149,7 @@ void JSBasedEventListener::handleEvent(
// Step 10: Call a listener with event's currentTarget as receiver and event
// and handle errors if thrown.
- CallListenerFunction(*event->currentTarget(), *event, js_event);
+ InvokeInternal(*event->currentTarget(), *event, js_event);
if (try_catch.HasCaught()) {
// Step 10-2: Set legacyOutputDidListenersThrowFlag if given.
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.h b/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.h
index 270d5b4f219..11b430b15fc 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_based_event_listener.h
@@ -49,7 +49,7 @@ class CORE_EXPORT JSBasedEventListener : public EventListener {
bool BelongsToTheCurrentWorld(ExecutionContext*) const final;
// Implements step 2. of "inner invoke".
// See: https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
- void handleEvent(ExecutionContext*, Event*) final;
+ void Invoke(ExecutionContext*, Event*) final;
// |GetListenerObject()| and |GetEffectiveFunction()| may cause JS in the
// content attribute to get compiled, potentially unsuccessfully.
@@ -83,9 +83,9 @@ class CORE_EXPORT JSBasedEventListener : public EventListener {
// This may throw an exception on invoking the listener.
// See step 2-10:
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
- virtual void CallListenerFunction(EventTarget&,
- Event&,
- v8::Local<v8::Value> js_event) = 0;
+ virtual void InvokeInternal(EventTarget&,
+ Event&,
+ v8::Local<v8::Value> js_event) = 0;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc
index 022c4e3cbe8..39c41dc88a7 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.cc
@@ -25,6 +25,16 @@ void JSEventHandler::SetCompiledHandler(
v8::Local<v8::Function> listener,
const V8PrivateProperty::Symbol& property) {
DCHECK(!HasCompiledHandler());
+
+ // https://html.spec.whatwg.org/multipage/webappapis.html#getting-the-current-value-of-the-event-handler
+ // Step 12: Set eventHandler's value to the result of creating a Web IDL
+ // EventHandler callback function object whose object reference is function
+ // and whose callback context is settings object.
+ //
+ // Push |script_state|'s context onto the backup incumbent settings object
+ // stack because appropriate incumbent realm does not always exist when
+ // content attribute gets lazily compiled. This context is the same one of the
+ // relevant realm of |listener| and its event target.
v8::Context::BackupIncumbentScope backup_incumbent_scope(
script_state->GetContext());
event_handler_ = V8EventHandlerNonNull::Create(listener);
@@ -32,9 +42,9 @@ void JSEventHandler::SetCompiledHandler(
}
// https://html.spec.whatwg.org/C/webappapis.html#the-event-handler-processing-algorithm
-void JSEventHandler::CallListenerFunction(EventTarget& event_target,
- Event& event,
- v8::Local<v8::Value> js_event) {
+void JSEventHandler::InvokeInternal(EventTarget& event_target,
+ Event& event,
+ v8::Local<v8::Value> js_event) {
DCHECK(!js_event.IsEmpty());
// Step 1. Let callback be the result of getting the current value of the
@@ -51,7 +61,7 @@ void JSEventHandler::CallListenerFunction(EventTarget& event_target,
// WindowOrWorkerGlobalScope mixin. Otherwise, let special error event
// handling be false.
const bool special_error_event_handling =
- event.IsErrorEvent() && event.type() == EventTypeNames::error &&
+ event.IsErrorEvent() && event.type() == event_type_names::kError &&
event.currentTarget()->IsWindowOrWorkerGlobalScope();
// Step 4. Process the Event object event as follows:
@@ -81,7 +91,7 @@ void JSEventHandler::CallListenerFunction(EventTarget& event_target,
// https://html.spec.whatwg.org/C/workers.html#runtime-script-errors-2
ScriptValue error_attribute = error_event->error(script_state_of_listener);
if (error_attribute.IsEmpty() ||
- error_event->target()->InterfaceName() == EventTargetNames::Worker)
+ error_event->target()->InterfaceName() == event_target_names::kWorker)
error_attribute = ScriptValue::CreateNull(script_state_of_listener);
arguments = {
@@ -96,11 +106,11 @@ void JSEventHandler::CallListenerFunction(EventTarget& event_target,
const bool is_beforeunload_event =
event.IsBeforeUnloadEvent() &&
- event.type() == EventTypeNames::beforeunload;
+ event.type() == event_type_names::kBeforeunload;
const bool is_print_event =
// TODO(yukishiino): Should check event.Is{Before,After}PrintEvent.
- event.type() == EventTypeNames::beforeprint ||
- event.type() == EventTypeNames::afterprint;
+ event.type() == event_type_names::kBeforeprint ||
+ event.type() == event_type_names::kAfterprint;
if (!event_handler_->IsRunnableOrThrowException(
(is_beforeunload_event || is_print_event)
? V8EventHandlerNonNull::IgnorePause::kIgnore
@@ -130,7 +140,7 @@ void JSEventHandler::CallListenerFunction(EventTarget& event_target,
String result_for_beforeunload;
if (IsOnBeforeUnloadEventHandler()) {
// TODO(yukiy): use |NativeValueTraits|.
- V8StringResource<> native_result(v8_return_value);
+ V8StringResource<kTreatNullAsNullString> native_result(v8_return_value);
// |native_result.Prepare()| throws exception if it fails to convert
// |native_result| to String.
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.h b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.h
index 3aca6a5448a..65214a8cff3 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler.h
@@ -29,9 +29,23 @@ class CORE_EXPORT JSEventHandler : public JSBasedEventListener {
v8::Local<v8::Object> listener,
const V8PrivateProperty::Symbol& property,
HandlerType type) {
- return new JSEventHandler(script_state, listener, property, type);
+ return MakeGarbageCollected<JSEventHandler>(script_state, listener,
+ property, type);
}
+ JSEventHandler(ScriptState* script_state,
+ v8::Local<v8::Object> listener,
+ const V8PrivateProperty::Symbol& property,
+ HandlerType type)
+ : JSBasedEventListener(kJSEventHandlerType),
+ event_handler_(V8EventHandlerNonNull::Create(listener)),
+ type_(type) {
+ Attach(script_state, listener, property, this);
+ }
+
+ explicit JSEventHandler(HandlerType type)
+ : JSBasedEventListener(kJSEventHandlerType), type_(type) {}
+
// blink::CustomWrappable overrides:
void Trace(blink::Visitor* visitor) override;
@@ -50,19 +64,6 @@ class CORE_EXPORT JSEventHandler : public JSBasedEventListener {
v8::Local<v8::Value> GetEffectiveFunction(EventTarget&) override;
protected:
- JSEventHandler(ScriptState* script_state,
- v8::Local<v8::Object> listener,
- const V8PrivateProperty::Symbol& property,
- HandlerType type)
- : JSBasedEventListener(kJSEventHandlerType),
- event_handler_(V8EventHandlerNonNull::Create(listener)),
- type_(type) {
- Attach(script_state, listener, property, this);
- }
-
- explicit JSEventHandler(HandlerType type)
- : JSBasedEventListener(kJSEventHandlerType), type_(type) {}
-
// blink::JSBasedEventListener override:
v8::Isolate* GetIsolate() const override {
return event_handler_->GetIsolate();
@@ -94,9 +95,9 @@ class CORE_EXPORT JSEventHandler : public JSBasedEventListener {
// blink::JSBasedEventListener override:
// Performs "The event handler processing algorithm"
// https://html.spec.whatwg.org/C/webappapis.html#the-event-handler-processing-algorithm
- void CallListenerFunction(EventTarget&,
- Event&,
- v8::Local<v8::Value> js_event) override;
+ void InvokeInternal(EventTarget&,
+ Event&,
+ v8::Local<v8::Value> js_event) override;
TraceWrapperMember<V8EventHandlerNonNull> event_handler_;
const HandlerType type_;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc
index cc79a175a4d..005f2dbf0b1 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc
@@ -161,7 +161,7 @@ v8::Local<v8::Value> JSEventHandlerForContentAttribute::GetCompiledHandler(
v8::Integer::New(isolate, position_.column_.ZeroBasedInt()),
// TODO(yukiy): consider which value should be passed here.
v8::True(isolate));
- v8::ScriptCompiler::Source source(V8String(isolate, code_), origin);
+ v8::ScriptCompiler::Source source(V8String(isolate, script_body_), origin);
v8::Local<v8::Function> compiled_function;
{
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.h b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.h
index 86b6a3bfd11..bf3af88097c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.h
@@ -23,10 +23,26 @@ class JSEventHandlerForContentAttribute final : public JSEventHandler {
v8::Isolate* isolate,
DOMWrapperWorld& world,
HandlerType type = HandlerType::kEventHandler) {
- return new JSEventHandlerForContentAttribute(
+ return MakeGarbageCollected<JSEventHandlerForContentAttribute>(
isolate, world, function_name, code, source_url, position, type);
}
+ JSEventHandlerForContentAttribute(v8::Isolate* isolate,
+ DOMWrapperWorld& world,
+ const AtomicString& function_name,
+ const String& script_body,
+ const String& source_url,
+ const TextPosition& position,
+ HandlerType type)
+ : JSEventHandler(type),
+ did_compile_(false),
+ function_name_(function_name),
+ script_body_(script_body),
+ source_url_(source_url),
+ position_(position),
+ isolate_(isolate),
+ world_(&world) {}
+
// blink::EventListener overrides:
bool IsEventHandlerForContentAttribute() const override { return true; }
@@ -34,7 +50,7 @@ class JSEventHandlerForContentAttribute final : public JSEventHandler {
v8::Local<v8::Value> GetListenerObject(EventTarget&) override;
std::unique_ptr<SourceLocation> GetSourceLocation(EventTarget&) override;
- const String& Code() const override { return code_; }
+ const String& ScriptBody() const override { return script_body_; }
protected:
// blink::JSBasedEventListener override:
@@ -46,22 +62,6 @@ class JSEventHandlerForContentAttribute final : public JSEventHandler {
DOMWrapperWorld& GetWorld() const override { return *world_; }
private:
- JSEventHandlerForContentAttribute(v8::Isolate* isolate,
- DOMWrapperWorld& world,
- const AtomicString& function_name,
- const String& code,
- const String& source_url,
- const TextPosition& position,
- HandlerType type)
- : JSEventHandler(type),
- did_compile_(false),
- function_name_(function_name),
- code_(code),
- source_url_(source_url),
- position_(position),
- isolate_(isolate),
- world_(&world) {}
-
// Implements Step 3. of "get the current value of the event handler".
// The compiled v8::Function is returned and |JSEventHandler::event_handler_|
// gets initialized with it if lazy compilation succeeds.
@@ -75,7 +75,7 @@ class JSEventHandlerForContentAttribute final : public JSEventHandler {
// checking that.
bool did_compile_;
const AtomicString function_name_;
- String code_;
+ String script_body_;
String source_url_;
TextPosition position_;
v8::Isolate* isolate_;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc
index 901f6577469..ba7f69cd0fa 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -42,20 +43,22 @@ v8::Local<v8::Value> JSEventListener::GetEffectiveFunction(
}
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
-void JSEventListener::CallListenerFunction(EventTarget&,
- Event& event,
- v8::Local<v8::Value> js_event) {
+void JSEventListener::InvokeInternal(EventTarget&,
+ Event& event,
+ v8::Local<v8::Value> js_event) {
// Step 10: Call a listener with event's currentTarget as receiver and event
// and handle errors if thrown.
const bool is_beforeunload_event =
event.IsBeforeUnloadEvent() &&
- event.type() == EventTypeNames::beforeunload;
+ event.type() == event_type_names::kBeforeunload;
const bool is_print_event =
// TODO(yukishiino): Should check event.Is{Before,After}PrintEvent.
- event.type() == EventTypeNames::beforeprint ||
- event.type() == EventTypeNames::afterprint;
+ event.type() == event_type_names::kBeforeprint ||
+ event.type() == event_type_names::kAfterprint;
+ const bool is_media_query_list_event =
+ event.InterfaceName() == event_interface_names::kMediaQueryListEvent;
if (!event_listener_->IsRunnableOrThrowException(
- (is_beforeunload_event || is_print_event)
+ (is_beforeunload_event || is_print_event || is_media_query_list_event)
? V8EventListener::IgnorePause::kIgnore
: V8EventListener::IgnorePause::kDontIgnore)) {
return;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.h b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.h
index c6644678294..a31902f48ce 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/js_event_listener.h
@@ -18,7 +18,17 @@ class CORE_EXPORT JSEventListener final : public JSBasedEventListener {
static JSEventListener* Create(ScriptState* script_state,
v8::Local<v8::Object> listener,
const V8PrivateProperty::Symbol& property) {
- return new JSEventListener(script_state, listener, property);
+ return MakeGarbageCollected<JSEventListener>(script_state, listener,
+ property);
+ }
+
+ JSEventListener(ScriptState* script_state,
+ v8::Local<v8::Object> listener,
+ const V8PrivateProperty::Symbol& property)
+ : JSBasedEventListener(kJSEventListenerType),
+ event_listener_(V8EventListener::CreateOrNull(listener)) {
+ DCHECK(event_listener_);
+ Attach(script_state, listener, property, this);
}
// blink::CustomWrappable overrides:
@@ -58,19 +68,10 @@ class CORE_EXPORT JSEventListener final : public JSBasedEventListener {
}
private:
- JSEventListener(ScriptState* script_state,
- v8::Local<v8::Object> listener,
- const V8PrivateProperty::Symbol& property)
- : JSBasedEventListener(kJSEventListenerType),
- event_listener_(V8EventListener::CreateOrNull(listener)) {
- DCHECK(event_listener_);
- Attach(script_state, listener, property, this);
- }
-
// blink::JSBasedEventListener override:
- void CallListenerFunction(EventTarget&,
- Event&,
- v8::Local<v8::Value> js_event) override;
+ void InvokeInternal(EventTarget&,
+ Event&,
+ v8::Local<v8::Value> js_event) override;
const TraceWrapperMember<V8EventListener> event_listener_;
};
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc b/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc
index e148eda2960..b43ca24b259 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc
@@ -182,6 +182,9 @@ void LocalWindowProxy::Initialize() {
InstallConditionalFeatures();
+ // This needs to go after everything else since it accesses the window object.
+ InitializeV8ExtrasBinding(script_state_);
+
if (World().IsMainWorld()) {
GetFrame()->Loader().DispatchDidClearWindowObjectInMainWorld();
}
@@ -194,16 +197,8 @@ void LocalWindowProxy::CreateContext() {
// TODO(yukishiino): Remove this CHECK once crbug.com/713699 gets fixed.
CHECK(IsMainThread());
- Vector<const char*> extension_names;
- // Dynamically tell v8 about our extensions now.
- if (GetFrame()->Client()->AllowScriptExtensions()) {
- const V8Extensions& extensions = ScriptController::RegisteredExtensions();
- extension_names.ReserveInitialCapacity(extensions.size());
- for (const auto* extension : extensions)
- extension_names.push_back(extension->name());
- }
- v8::ExtensionConfiguration extension_configuration(extension_names.size(),
- extension_names.data());
+ v8::ExtensionConfiguration extension_configuration =
+ ScriptController::ExtensionsFor(GetFrame()->GetDocument());
v8::Local<v8::Context> context;
{
@@ -229,7 +224,7 @@ void LocalWindowProxy::CreateContext() {
// in some cases, e.g. loading XML files.
if (context.IsEmpty()) {
v8::Local<v8::ObjectTemplate> global_template =
- V8Window::domTemplate(isolate, World())->InstanceTemplate();
+ V8Window::DomTemplate(isolate, World())->InstanceTemplate();
CHECK(!global_template.IsEmpty());
context = v8::Context::New(isolate, &extension_configuration,
global_template, global_proxy);
@@ -244,8 +239,6 @@ void LocalWindowProxy::CreateContext() {
script_state_ = ScriptState::Create(context, world_);
- InitializeV8ExtrasBinding(script_state_);
-
DCHECK(lifecycle_ == Lifecycle::kContextIsUninitialized ||
lifecycle_ == Lifecycle::kGlobalObjectIsDetached);
lifecycle_ = Lifecycle::kContextIsInitialized;
@@ -275,7 +268,7 @@ void LocalWindowProxy::InstallConditionalFeatures() {
wrapper_type_info->InstallConditionalFeatures(
context, World(), global_proxy, unused_prototype_object,
unused_interface_object,
- wrapper_type_info->domTemplate(GetIsolate(), World()));
+ wrapper_type_info->DomTemplate(GetIsolate(), World()));
if (World().IsMainWorld()) {
// For the main world, install any remaining conditional bindings (i.e.
@@ -466,11 +459,11 @@ static v8::Local<v8::Value> GetNamedProperty(
v8::Local<v8::Object> creation_context,
v8::Isolate* isolate) {
if (!html_document->HasNamedItem(key))
- return V8Undefined();
+ return v8::Local<v8::Value>();
DocumentNameCollection* items = html_document->DocumentNamedItems(key);
if (items->IsEmpty())
- return V8Undefined();
+ return v8::Local<v8::Value>();
if (items->HasExactlyOneItem()) {
HTMLElement* element = items->Item(0);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.h b/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.h
index 90cd4564f9d..68d94c9593a 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/local_window_proxy.h
@@ -51,9 +51,11 @@ class LocalWindowProxy final : public WindowProxy {
static LocalWindowProxy* Create(v8::Isolate* isolate,
LocalFrame& frame,
scoped_refptr<DOMWrapperWorld> world) {
- return new LocalWindowProxy(isolate, frame, std::move(world));
+ return MakeGarbageCollected<LocalWindowProxy>(isolate, frame,
+ std::move(world));
}
+ LocalWindowProxy(v8::Isolate*, LocalFrame&, scoped_refptr<DOMWrapperWorld>);
void Trace(blink::Visitor*) override;
v8::Local<v8::Context> ContextIfInitialized() const {
@@ -72,8 +74,6 @@ class LocalWindowProxy final : public WindowProxy {
void UpdateSecurityOrigin(const SecurityOrigin*);
private:
- LocalWindowProxy(v8::Isolate*, LocalFrame&, scoped_refptr<DOMWrapperWorld>);
-
bool IsLocal() const override { return true; }
void Initialize() override;
void DisposeContext(Lifecycle next_status, FrameReuseStatus) override;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h b/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h
index 7edeae127f3..ca71a4f0458 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h
@@ -39,14 +39,7 @@ struct CORE_EXPORT NativeValueTraits<IDLByte>
static int8_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
- }
-
- static int8_t NativeValue(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToInt8(isolate, value, conversion_mode, exception_state);
+ return ToInt8(isolate, value, kNormalConversion, exception_state);
}
};
@@ -56,14 +49,7 @@ struct CORE_EXPORT NativeValueTraits<IDLOctet>
static uint8_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
- }
-
- static uint8_t NativeValue(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToUInt8(isolate, value, conversion_mode, exception_state);
+ return ToUInt8(isolate, value, kNormalConversion, exception_state);
}
};
@@ -73,14 +59,7 @@ struct CORE_EXPORT NativeValueTraits<IDLShort>
static int16_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
- }
-
- static int16_t NativeValue(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToInt16(isolate, value, conversion_mode, exception_state);
+ return ToInt16(isolate, value, kNormalConversion, exception_state);
}
};
@@ -90,14 +69,7 @@ struct CORE_EXPORT NativeValueTraits<IDLUnsignedShort>
static uint16_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
- }
-
- static uint16_t NativeValue(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToUInt16(isolate, value, conversion_mode, exception_state);
+ return ToUInt16(isolate, value, kNormalConversion, exception_state);
}
};
@@ -107,14 +79,7 @@ struct CORE_EXPORT NativeValueTraits<IDLLong>
static int32_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
- }
-
- static int32_t NativeValue(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToInt32(isolate, value, conversion_mode, exception_state);
+ return ToInt32(isolate, value, kNormalConversion, exception_state);
}
};
@@ -124,14 +89,7 @@ struct CORE_EXPORT NativeValueTraits<IDLUnsignedLong>
static uint32_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
- }
-
- static uint32_t NativeValue(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToUInt32(isolate, value, conversion_mode, exception_state);
+ return ToUInt32(isolate, value, kNormalConversion, exception_state);
}
};
@@ -141,31 +99,179 @@ struct CORE_EXPORT NativeValueTraits<IDLLongLong>
static int64_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
+ return ToInt64(isolate, value, kNormalConversion, exception_state);
}
+};
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedLongLong>
+ : public NativeValueTraitsBase<IDLUnsignedLongLong> {
+ static uint64_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt64(isolate, value, kNormalConversion, exception_state);
+ }
+};
+
+// [Clamp] Integers
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLByteClamp>
+ : public NativeValueTraitsBase<IDLByte> {
+ static int8_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt8(isolate, value, kClamp, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLOctetClamp>
+ : public NativeValueTraitsBase<IDLOctet> {
+ static uint8_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt8(isolate, value, kClamp, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLShortClamp>
+ : public NativeValueTraitsBase<IDLShort> {
+ static int16_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt16(isolate, value, kClamp, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedShortClamp>
+ : public NativeValueTraitsBase<IDLUnsignedShort> {
+ static uint16_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt16(isolate, value, kClamp, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLLongClamp>
+ : public NativeValueTraitsBase<IDLLong> {
+ static int32_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt32(isolate, value, kClamp, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedLongClamp>
+ : public NativeValueTraitsBase<IDLUnsignedLong> {
+ static uint32_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt32(isolate, value, kClamp, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLLongLongClamp>
+ : public NativeValueTraitsBase<IDLLongLong> {
static int64_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToInt64(isolate, value, conversion_mode, exception_state);
+ ExceptionState& exception_state) {
+ return ToInt64(isolate, value, kClamp, exception_state);
}
};
template <>
-struct CORE_EXPORT NativeValueTraits<IDLUnsignedLongLong>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedLongLongClamp>
: public NativeValueTraitsBase<IDLUnsignedLongLong> {
static uint64_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
- return NativeValue(isolate, value, exception_state, kNormalConversion);
+ return ToUInt64(isolate, value, kClamp, exception_state);
+ }
+};
+
+// [EnforceRange] Integers
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLByteEnforceRange>
+ : public NativeValueTraitsBase<IDLByte> {
+ static int8_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt8(isolate, value, kEnforceRange, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLOctetEnforceRange>
+ : public NativeValueTraitsBase<IDLOctet> {
+ static uint8_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt8(isolate, value, kEnforceRange, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLShortEnforceRange>
+ : public NativeValueTraitsBase<IDLShort> {
+ static int16_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt16(isolate, value, kEnforceRange, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedShortEnforceRange>
+ : public NativeValueTraitsBase<IDLUnsignedShort> {
+ static uint16_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt16(isolate, value, kEnforceRange, exception_state);
}
+};
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLLongEnforceRange>
+ : public NativeValueTraitsBase<IDLLong> {
+ static int32_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt32(isolate, value, kEnforceRange, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedLongEnforceRange>
+ : public NativeValueTraitsBase<IDLUnsignedLong> {
+ static uint32_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToUInt32(isolate, value, kEnforceRange, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLLongLongEnforceRange>
+ : public NativeValueTraitsBase<IDLLongLong> {
+ static int64_t NativeValue(v8::Isolate* isolate,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ return ToInt64(isolate, value, kEnforceRange, exception_state);
+ }
+};
+
+template <>
+struct CORE_EXPORT NativeValueTraits<IDLUnsignedLongLongEnforceRange>
+ : public NativeValueTraitsBase<IDLUnsignedLongLong> {
static uint64_t NativeValue(v8::Isolate* isolate,
v8::Local<v8::Value> value,
- ExceptionState& exception_state,
- IntegerConversionConfiguration conversion_mode) {
- return ToUInt64(isolate, value, conversion_mode, exception_state);
+ ExceptionState& exception_state) {
+ return ToUInt64(isolate, value, kEnforceRange, exception_state);
}
};
@@ -184,7 +290,7 @@ struct NativeValueTraits<IDLByteStringBase<Mode>>
String x = string_resource;
// 2. If the value of any element of x is greater than 255, then throw a
// TypeError.
- if (!x.ContainsOnlyLatin1()) {
+ if (!x.ContainsOnlyLatin1OrEmpty()) {
exception_state.ThrowTypeError("Value is not a valid ByteString.");
return String();
}
@@ -413,12 +519,7 @@ struct NativeValueTraits<IDLSequence<T>>
exception_state.RethrowV8Exception(block.Exception());
return;
}
- bool done_boolean;
- if (!done->BooleanValue(context).To(&done_boolean)) {
- exception_state.RethrowV8Exception(block.Exception());
- return;
- }
- if (done_boolean)
+ if (done->BooleanValue(isolate))
break;
result.emplace_back(
NativeValueTraits<T>::NativeValue(isolate, element, exception_state));
@@ -513,7 +614,7 @@ struct NativeValueTraits<IDLRecord<K, V>>
v8::Local<v8::Object>::Cast(desc)
->Get(context, V8String(isolate, "enumerable"))
.ToLocalChecked();
- if (!enumerable->BooleanValue(context).ToChecked())
+ if (!enumerable->BooleanValue(isolate))
continue;
// "4.2.1. Let typedKey be key converted to an IDL value of type K."
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl_test.cc
index a3ef60fb95f..4004a722cbe 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl_test.cc
@@ -20,6 +20,20 @@ namespace blink {
namespace {
+v8::Local<v8::Object> EvaluateScriptForObject(V8TestingScope& scope,
+ const char* source) {
+ v8::Local<v8::Script> script =
+ v8::Script::Compile(scope.GetContext(),
+ V8String(scope.GetIsolate(), source))
+ .ToLocalChecked();
+ return script->Run(scope.GetContext()).ToLocalChecked().As<v8::Object>();
+}
+
+v8::Local<v8::Array> EvaluateScriptForArray(V8TestingScope& scope,
+ const char* source) {
+ return EvaluateScriptForObject(scope, source).As<v8::Array>();
+}
+
TEST(NativeValueTraitsImplTest, IDLInterface) {
V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
@@ -43,25 +57,6 @@ TEST(NativeValueTraitsImplTest, IDLCallbackFunction) {
"");
}
-void ThrowException(v8::Local<v8::Name>,
- const v8::PropertyCallbackInfo<v8::Value>& info) {
- info.GetIsolate()->ThrowException(V8String(info.GetIsolate(), "bogus!"));
-}
-
-void ReturnBogusObjectDescriptor(
- const v8::FunctionCallbackInfo<v8::Value>& info) {
- v8::Isolate* isolate = info.GetIsolate();
- auto context = isolate->GetCurrentContext();
-
- v8::Local<v8::Object> descriptor = v8::Object::New(isolate);
- EXPECT_TRUE(
- V8CallBoolean(descriptor->Set(context, V8String(isolate, "configurable"),
- v8::Boolean::New(isolate, true))));
- EXPECT_TRUE(V8CallBoolean(descriptor->SetAccessor(
- context, V8String(isolate, "enumerable"), ThrowException)));
- info.GetReturnValue().Set(descriptor);
-}
-
TEST(NativeValueTraitsImplTest, IDLRecord) {
V8TestingScope scope;
{
@@ -73,13 +68,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
EXPECT_TRUE(record.IsEmpty());
}
{
- v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 34))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "bar"), ToV8(&scope, -1024))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 42))));
+ v8::Local<v8::Object> v8_object =
+ EvaluateScriptForObject(scope, "({ foo: 42, bar: -1024 })");
NonThrowableExceptionState exception_state;
const auto& record =
@@ -90,14 +80,13 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
EXPECT_EQ(std::make_pair(String("bar"), int32_t(-1024)), record[1]);
}
{
- v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 34))));
- EXPECT_TRUE(V8CallBoolean(v8_object->DefineOwnProperty(
- scope.GetContext(), V8String(scope.GetIsolate(), "bar"),
- ToV8(&scope, -1024), v8::PropertyAttribute::DontEnum)));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "baz"), ToV8(&scope, 42))));
+ v8::Local<v8::Object> v8_object =
+ EvaluateScriptForObject(scope,
+ "Object.defineProperties({}, {"
+ " foo: {value: 34, enumerable: true},"
+ " bar: {value: -1024, enumerable: false},"
+ " baz: {value: 42, enumerable: true},"
+ "})");
NonThrowableExceptionState exception_state;
const auto& record =
@@ -110,11 +99,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
{
// Exceptions are being thrown in this test, so we need another scope.
V8TestingScope scope;
- v8::Local<v8::Object> original_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(original_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 34))));
- EXPECT_TRUE(V8CallBoolean(original_object->Set(
- scope.GetContext(), ToV8(&scope, "bar"), ToV8(&scope, 42))));
+ v8::Local<v8::Object> original_object = EvaluateScriptForObject(
+ scope, "(self.originalObject = {foo: 34, bar: 42})");
NonThrowableExceptionState exception_state;
const auto& record =
@@ -122,14 +108,18 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
scope.GetIsolate(), original_object, exception_state);
EXPECT_EQ(2U, record.size());
- v8::Local<v8::Object> handler = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(handler->Set(
- scope.GetContext(), ToV8(&scope, "getOwnPropertyDescriptor"),
- v8::Function::New(scope.GetContext(), ReturnBogusObjectDescriptor)
- .ToLocalChecked())));
v8::Local<v8::Proxy> proxy =
- v8::Proxy::New(scope.GetContext(), original_object, handler)
- .ToLocalChecked();
+ EvaluateScriptForObject(scope,
+ "new Proxy(self.originalObject, {"
+ " getOwnPropertyDescriptor() {"
+ " return {"
+ " configurable: true,"
+ " get enumerable() { throw 'bogus!'; },"
+ " };"
+ " }"
+ "})")
+ .As<v8::Proxy>();
+
ExceptionState exception_state_from_proxy(
scope.GetIsolate(), ExceptionState::kExecutionContext,
"NativeValueTraitsImplTest", "IDLRecordTest");
@@ -150,15 +140,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
.ToChecked());
}
{
- v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 42))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "bar"), ToV8(&scope, 0))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "xx"), ToV8(&scope, true))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "abcd"), ToV8(&scope, false))));
+ v8::Local<v8::Object> v8_object = EvaluateScriptForObject(
+ scope, "({foo: 42, bar: 0, xx: true, abcd: false})");
NonThrowableExceptionState exception_state;
const auto& record =
@@ -171,14 +154,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
EXPECT_EQ(std::make_pair(String("abcd"), false), record[3]);
}
{
- v8::Local<v8::Array> v8_string_array =
- v8::Array::New(scope.GetIsolate(), 2);
- EXPECT_TRUE(V8CallBoolean(v8_string_array->Set(
- scope.GetContext(), ToV8(&scope, 0), ToV8(&scope, "Hello, World!"))));
- EXPECT_TRUE(V8CallBoolean(v8_string_array->Set(
- scope.GetContext(), ToV8(&scope, 1), ToV8(&scope, "Hi, Mom!"))));
- EXPECT_TRUE(V8CallBoolean(v8_string_array->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, "Ohai"))));
+ v8::Local<v8::Array> v8_string_array = EvaluateScriptForArray(
+ scope, "Object.assign(['Hello, World!', 'Hi, Mom!'], {foo: 'Ohai'})");
NonThrowableExceptionState exception_state;
const auto& record =
@@ -190,12 +167,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
EXPECT_EQ(std::make_pair(String("foo"), String("Ohai")), record[2]);
}
{
- v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), v8::Symbol::GetToStringTag(scope.GetIsolate()),
- ToV8(&scope, 34))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 42))));
+ v8::Local<v8::Object> v8_object =
+ EvaluateScriptForObject(scope, "({[Symbol.toStringTag]: 34, foo: 42})");
// The presence of symbols should throw a TypeError when the conversion to
// the record's key type is attempted.
@@ -208,15 +181,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
EXPECT_TRUE(exception_state.Message().IsEmpty());
}
{
- v8::Local<v8::Object> v8_parent_object =
- v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(v8_parent_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 34))));
- EXPECT_TRUE(V8CallBoolean(v8_parent_object->Set(
- scope.GetContext(), ToV8(&scope, "bar"), ToV8(&scope, 512))));
- v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(V8CallBoolean(
- v8_object->SetPrototype(scope.GetContext(), v8_parent_object)));
+ v8::Local<v8::Object> v8_object =
+ EvaluateScriptForObject(scope, "Object.create({foo: 34, bar: 512})");
NonThrowableExceptionState exception_state;
auto record =
@@ -224,10 +190,11 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
scope.GetIsolate(), v8_object, exception_state);
EXPECT_TRUE(record.IsEmpty());
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "quux"), ToV8(&scope, 42))));
- EXPECT_TRUE(V8CallBoolean(v8_object->Set(
- scope.GetContext(), ToV8(&scope, "foo"), ToV8(&scope, 1024))));
+ v8_object =
+ EvaluateScriptForObject(scope,
+ "Object.assign("
+ " Object.create({foo: 34, bar: 512}),"
+ " {quux: 42, foo: 1024})");
record =
NativeValueTraits<IDLRecord<IDLString, IDLUnsignedLong>>::NativeValue(
scope.GetIsolate(), v8_object, exception_state);
@@ -236,16 +203,8 @@ TEST(NativeValueTraitsImplTest, IDLRecord) {
EXPECT_EQ(std::make_pair(String("foo"), uint32_t(1024)), record[1]);
}
{
- v8::Local<v8::Array> v8_string_array =
- v8::Array::New(scope.GetIsolate(), 2);
- EXPECT_TRUE(V8CallBoolean(v8_string_array->Set(
- scope.GetContext(), ToV8(&scope, 0), ToV8(&scope, "Hello, World!"))));
- EXPECT_TRUE(V8CallBoolean(v8_string_array->Set(
- scope.GetContext(), ToV8(&scope, 1), ToV8(&scope, "Hi, Mom!"))));
- v8::Local<v8::Object> v8_object = v8::Object::New(scope.GetIsolate());
- EXPECT_TRUE(
- V8CallBoolean(v8_object->Set(scope.GetContext(), ToV8(&scope, "foo"),
- ToV8(&scope, v8_string_array))));
+ v8::Local<v8::Object> v8_object = EvaluateScriptForObject(
+ scope, "({foo: ['Hello, World!', 'Hi, Mom!']})");
NonThrowableExceptionState exception_state;
const auto& record =
@@ -269,11 +228,8 @@ TEST(NativeValueTraitsImplTest, IDLSequence) {
EXPECT_TRUE(sequence.IsEmpty());
}
{
- v8::Local<v8::Array> v8_array = v8::Array::New(scope.GetIsolate());
- for (int32_t i = 0; i < 5; ++i) {
- v8_array->Set(scope.GetContext(), ToV8(&scope, i), ToV8(&scope, i))
- .ToChecked();
- }
+ v8::Local<v8::Array> v8_array =
+ EvaluateScriptForArray(scope, "[0, 1, 2, 3, 4]");
NonThrowableExceptionState exception_state;
const auto& sequence = NativeValueTraits<IDLSequence<IDLLong>>::NativeValue(
scope.GetIsolate(), v8_array, exception_state);
@@ -282,10 +238,8 @@ TEST(NativeValueTraitsImplTest, IDLSequence) {
{
const double double_pi = 3.141592653589793238;
const float float_pi = double_pi;
- v8::Local<v8::Array> v8_real_array = v8::Array::New(scope.GetIsolate(), 1);
- v8_real_array
- ->Set(scope.GetContext(), ToV8(&scope, 0), ToV8(&scope, double_pi))
- .ToChecked();
+ v8::Local<v8::Array> v8_real_array =
+ EvaluateScriptForArray(scope, "[3.141592653589793238]");
NonThrowableExceptionState exception_state;
Vector<double> double_vector =
@@ -301,17 +255,8 @@ TEST(NativeValueTraitsImplTest, IDLSequence) {
EXPECT_EQ(float_pi, float_vector[0]);
}
{
- v8::Local<v8::Array> v8_array = v8::Array::New(scope.GetIsolate(), 3);
- EXPECT_TRUE(v8_array
- ->Set(scope.GetContext(), ToV8(&scope, 0),
- ToV8(&scope, "Vini, vidi, vici."))
- .ToChecked());
- EXPECT_TRUE(
- v8_array->Set(scope.GetContext(), ToV8(&scope, 1), ToV8(&scope, 65535))
- .ToChecked());
- EXPECT_TRUE(
- v8_array->Set(scope.GetContext(), ToV8(&scope, 2), ToV8(&scope, 0.125))
- .ToChecked());
+ v8::Local<v8::Array> v8_array =
+ EvaluateScriptForArray(scope, "['Vini, vidi, vici.', 65535, 0.125]");
NonThrowableExceptionState exception_state;
Vector<ScriptValue> script_value_vector =
@@ -326,38 +271,8 @@ TEST(NativeValueTraitsImplTest, IDLSequence) {
kNormalConversion, exception_state));
}
{
- v8::Local<v8::Array> v8_string_array1 =
- v8::Array::New(scope.GetIsolate(), 2);
- EXPECT_TRUE(
- v8_string_array1
- ->Set(scope.GetContext(), ToV8(&scope, 0), ToV8(&scope, "foo"))
- .ToChecked());
- EXPECT_TRUE(
- v8_string_array1
- ->Set(scope.GetContext(), ToV8(&scope, 1), ToV8(&scope, "bar"))
- .ToChecked());
- v8::Local<v8::Array> v8_string_array2 =
- v8::Array::New(scope.GetIsolate(), 3);
- EXPECT_TRUE(
- v8_string_array2
- ->Set(scope.GetContext(), ToV8(&scope, 0), ToV8(&scope, "x"))
- .ToChecked());
- EXPECT_TRUE(
- v8_string_array2
- ->Set(scope.GetContext(), ToV8(&scope, 1), ToV8(&scope, "y"))
- .ToChecked());
- EXPECT_TRUE(
- v8_string_array2
- ->Set(scope.GetContext(), ToV8(&scope, 2), ToV8(&scope, "z"))
- .ToChecked());
v8::Local<v8::Array> v8_string_array_array =
- v8::Array::New(scope.GetIsolate(), 2);
- EXPECT_TRUE(v8_string_array_array
- ->Set(scope.GetContext(), ToV8(&scope, 0), v8_string_array1)
- .ToChecked());
- EXPECT_TRUE(v8_string_array_array
- ->Set(scope.GetContext(), ToV8(&scope, 1), v8_string_array2)
- .ToChecked());
+ EvaluateScriptForArray(scope, "[['foo', 'bar'], ['x', 'y', 'z']]");
NonThrowableExceptionState exception_state;
Vector<Vector<String>> string_vector_vector =
@@ -373,27 +288,18 @@ TEST(NativeValueTraitsImplTest, IDLSequence) {
EXPECT_EQ("z", string_vector_vector[1][2]);
}
{
- v8::Local<v8::String> script_code =
- ToV8(&scope,
- "let arr = [1, 2, 3];"
- "let iterations = ["
- " {done: false, value: 8},"
- " {done: false, value: 5},"
- " {done: true}"
- "];"
- "arr[Symbol.iterator] = function() {"
- " let i = 0;"
- " return {next: () => iterations[i++]};"
- "}; arr")
- .As<v8::String>();
- v8::MicrotasksScope microtasks(scope.GetIsolate(),
- v8::MicrotasksScope::kDoNotRunMicrotasks);
- v8::Local<v8::Value> v8_array =
- v8::Script::Compile(scope.GetContext(), script_code)
- .ToLocalChecked()
- ->Run(scope.GetContext())
- .ToLocalChecked();
- EXPECT_TRUE(v8_array->IsArray());
+ v8::Local<v8::Array> v8_array =
+ EvaluateScriptForArray(scope,
+ "let arr = [1, 2, 3];"
+ "let iterations = ["
+ " {done: false, value: 8},"
+ " {done: false, value: 5},"
+ " {done: true}"
+ "];"
+ "arr[Symbol.iterator] = function() {"
+ " let i = 0;"
+ " return {next: () => iterations[i++]};"
+ "}; arr");
NonThrowableExceptionState exception_state;
const auto& sequence = NativeValueTraits<IDLSequence<IDLByte>>::NativeValue(
@@ -401,28 +307,19 @@ TEST(NativeValueTraitsImplTest, IDLSequence) {
EXPECT_EQ(Vector<int8_t>({1, 2, 3}), sequence);
}
{
- v8::Local<v8::String> script_code =
- ToV8(&scope,
- "let obj = {"
- " iterations: ["
- " {done: false, value: 55},"
- " {done: false, value: 0},"
- " {done: true, value: 99}"
- " ],"
- " [Symbol.iterator]() {"
- " let i = 0;"
- " return {next: () => this.iterations[i++]};"
- " }"
- "}; obj")
- .As<v8::String>();
- v8::MicrotasksScope microtasks(scope.GetIsolate(),
- v8::MicrotasksScope::kDoNotRunMicrotasks);
- v8::Local<v8::Value> v8_object =
- v8::Script::Compile(scope.GetContext(), script_code)
- .ToLocalChecked()
- ->Run(scope.GetContext())
- .ToLocalChecked();
- EXPECT_TRUE(v8_object->IsObject());
+ v8::Local<v8::Object> v8_object =
+ EvaluateScriptForObject(scope,
+ "let obj = {"
+ " iterations: ["
+ " {done: false, value: 55},"
+ " {done: false, value: 0},"
+ " {done: true, value: 99}"
+ " ],"
+ " [Symbol.iterator]() {"
+ " let i = 0;"
+ " return {next: () => this.iterations[i++]};"
+ " }"
+ "}; obj");
NonThrowableExceptionState exception_state;
const auto& byte_sequence =
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.cc b/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.cc
index 4768bf10179..ecc6988e2ed 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.cc
@@ -54,8 +54,9 @@ ReferrerScriptInfo ReferrerScriptInfo::FromV8HostDefinedOptions(
v8::Local<v8::Primitive> referrer_policy_value =
host_defined_options->Get(isolate, kReferrerPolicy);
- ReferrerPolicy referrer_policy = static_cast<ReferrerPolicy>(
- referrer_policy_value->IntegerValue(context).ToChecked());
+ network::mojom::ReferrerPolicy referrer_policy =
+ static_cast<network::mojom::ReferrerPolicy>(
+ referrer_policy_value->IntegerValue(context).ToChecked());
return ReferrerScriptInfo(base_url, credentials_mode, nonce, parser_state,
referrer_policy);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.h b/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.h
index ca9b68ed965..93e544b8269 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info.h
@@ -6,9 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_REFERRER_SCRIPT_INFO_H_
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "v8/include/v8.h"
@@ -25,7 +25,7 @@ class CORE_EXPORT ReferrerScriptInfo {
network::mojom::FetchCredentialsMode credentials_mode,
const String& nonce,
ParserDisposition parser_state,
- ReferrerPolicy referrer_policy)
+ network::mojom::ReferrerPolicy referrer_policy)
: base_url_(base_url),
credentials_mode_(credentials_mode),
nonce_(nonce),
@@ -49,11 +49,14 @@ class CORE_EXPORT ReferrerScriptInfo {
}
const String& Nonce() const { return nonce_; }
ParserDisposition ParserState() const { return parser_state_; }
- ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
bool IsDefaultValue() const {
return base_url_.IsNull() &&
- credentials_mode_ == network::mojom::FetchCredentialsMode::kOmit &&
+ credentials_mode_ ==
+ network::mojom::FetchCredentialsMode::kSameOrigin &&
nonce_.IsEmpty() && parser_state_ == kNotParserInserted;
}
@@ -67,10 +70,10 @@ class CORE_EXPORT ReferrerScriptInfo {
const KURL base_url_;
// Spec: "referencing script's credentials mode"
- // The default value is "omit" per:
+ // The default value is "same-origin" per:
// https://html.spec.whatwg.org/multipage/webappapis.html#default-classic-script-fetch-options
const network::mojom::FetchCredentialsMode credentials_mode_ =
- network::mojom::FetchCredentialsMode::kOmit;
+ network::mojom::FetchCredentialsMode::kSameOrigin;
// Spec: "referencing script's cryptographic nonce"
const String nonce_;
@@ -83,7 +86,8 @@ class CORE_EXPORT ReferrerScriptInfo {
// Spec: "referencing script's referrer policy"
// The default value is "the empty string" per:
// https://html.spec.whatwg.org/multipage/webappapis.html#default-classic-script-fetch-options
- const ReferrerPolicy referrer_policy_ = kReferrerPolicyDefault;
+ const network::mojom::ReferrerPolicy referrer_policy_ =
+ network::mojom::ReferrerPolicy::kDefault;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc
index 16efb5041e2..76279d4d005 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc
@@ -12,11 +12,11 @@ namespace blink {
TEST(ReferrerScriptInfo, IsDefaultValue) {
EXPECT_TRUE(ReferrerScriptInfo().IsDefaultValue());
- EXPECT_FALSE(
- ReferrerScriptInfo(KURL("http://example.com"),
- network::mojom::FetchCredentialsMode::kInclude, "",
- kNotParserInserted, kReferrerPolicyDefault)
- .IsDefaultValue());
+ EXPECT_FALSE(ReferrerScriptInfo(
+ KURL("http://example.com"),
+ network::mojom::FetchCredentialsMode::kInclude, "",
+ kNotParserInserted, network::mojom::ReferrerPolicy::kDefault)
+ .IsDefaultValue());
}
TEST(ReferrerScriptInfo, ToFromV8) {
@@ -28,7 +28,8 @@ TEST(ReferrerScriptInfo, ToFromV8) {
.IsEmpty());
ReferrerScriptInfo info(url, network::mojom::FetchCredentialsMode::kInclude,
- "foobar", kNotParserInserted, kReferrerPolicyOrigin);
+ "foobar", kNotParserInserted,
+ network::mojom::ReferrerPolicy::kOrigin);
v8::Local<v8::PrimitiveArray> v8_info =
info.ToV8HostDefinedOptions(scope.GetIsolate());
@@ -39,7 +40,8 @@ TEST(ReferrerScriptInfo, ToFromV8) {
decoded.CredentialsMode());
EXPECT_EQ("foobar", decoded.Nonce());
EXPECT_EQ(kNotParserInserted, decoded.ParserState());
- EXPECT_EQ(kReferrerPolicyOrigin, decoded.GetReferrerPolicy());
+ EXPECT_EQ(network::mojom::ReferrerPolicy::kOrigin,
+ decoded.GetReferrerPolicy());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.cc b/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.cc
index 628179002b8..d667ffac55e 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.cc
@@ -33,12 +33,28 @@ class RejectedPromises::Message final {
v8::Local<v8::Value> exception,
const String& error_message,
std::unique_ptr<SourceLocation> location,
- AccessControlStatus cors_status) {
+ SanitizeScriptErrors sanitize_script_errors) {
return base::WrapUnique(new Message(script_state, promise, exception,
error_message, std::move(location),
- cors_status));
+ sanitize_script_errors));
}
+ Message(ScriptState* script_state,
+ v8::Local<v8::Promise> promise,
+ v8::Local<v8::Value> exception,
+ const String& error_message,
+ std::unique_ptr<SourceLocation> location,
+ SanitizeScriptErrors sanitize_script_errors)
+ : script_state_(script_state),
+ promise_(script_state->GetIsolate(), promise),
+ exception_(script_state->GetIsolate(), exception),
+ error_message_(error_message),
+ location_(std::move(location)),
+ promise_rejection_id_(0),
+ collected_(false),
+ should_log_to_console_(true),
+ sanitize_script_errors_(sanitize_script_errors) {}
+
bool IsCollected() { return collected_ || !script_state_->ContextIsValid(); }
bool HasPromise(v8::Local<v8::Value> promise) {
@@ -66,14 +82,14 @@ class RejectedPromises::Message final {
DCHECK(!HasHandler());
EventTarget* target = execution_context->ErrorEventTarget();
- if (target && !execution_context->ShouldSanitizeScriptError(resource_name_,
- cors_status_)) {
- PromiseRejectionEventInit init;
- init.setPromise(ScriptPromise(script_state_, value));
- init.setReason(ScriptValue(script_state_, reason));
- init.setCancelable(true);
+ if (target &&
+ sanitize_script_errors_ == SanitizeScriptErrors::kDoNotSanitize) {
+ PromiseRejectionEventInit* init = PromiseRejectionEventInit::Create();
+ init->setPromise(ScriptPromise(script_state_, value));
+ init->setReason(ScriptValue(script_state_, reason));
+ init->setCancelable(true);
PromiseRejectionEvent* event = PromiseRejectionEvent::Create(
- script_state_, EventTypeNames::unhandledrejection, init);
+ script_state_, event_type_names::kUnhandledrejection, init);
// Log to console if event was not canceled.
should_log_to_console_ =
target->DispatchEvent(*event) == DispatchEventResult::kNotCanceled;
@@ -106,13 +122,13 @@ class RejectedPromises::Message final {
return;
EventTarget* target = execution_context->ErrorEventTarget();
- if (target && !execution_context->ShouldSanitizeScriptError(resource_name_,
- cors_status_)) {
- PromiseRejectionEventInit init;
- init.setPromise(ScriptPromise(script_state_, value));
- init.setReason(ScriptValue(script_state_, reason));
+ if (target &&
+ sanitize_script_errors_ == SanitizeScriptErrors::kDoNotSanitize) {
+ PromiseRejectionEventInit* init = PromiseRejectionEventInit::Create();
+ init->setPromise(ScriptPromise(script_state_, value));
+ init->setReason(ScriptValue(script_state_, reason));
PromiseRejectionEvent* event = PromiseRejectionEvent::Create(
- script_state_, EventTypeNames::rejectionhandled, init);
+ script_state_, event_type_names::kRejectionhandled, init);
target->DispatchEvent(*event);
}
@@ -152,23 +168,6 @@ class RejectedPromises::Message final {
}
private:
- Message(ScriptState* script_state,
- v8::Local<v8::Promise> promise,
- v8::Local<v8::Value> exception,
- const String& error_message,
- std::unique_ptr<SourceLocation> location,
- AccessControlStatus cors_status)
- : script_state_(script_state),
- promise_(script_state->GetIsolate(), promise),
- exception_(script_state->GetIsolate(), exception),
- error_message_(error_message),
- resource_name_(location->Url()),
- location_(std::move(location)),
- promise_rejection_id_(0),
- collected_(false),
- should_log_to_console_(true),
- cors_status_(cors_status) {}
-
static void DidCollectPromise(const v8::WeakCallbackInfo<Message>& data) {
data.GetParameter()->collected_ = true;
data.GetParameter()->promise_.Clear();
@@ -182,12 +181,11 @@ class RejectedPromises::Message final {
ScopedPersistent<v8::Promise> promise_;
ScopedPersistent<v8::Value> exception_;
String error_message_;
- String resource_name_;
std::unique_ptr<SourceLocation> location_;
unsigned promise_rejection_id_;
bool collected_;
bool should_log_to_console_;
- AccessControlStatus cors_status_;
+ SanitizeScriptErrors sanitize_script_errors_;
};
RejectedPromises::RejectedPromises() = default;
@@ -199,10 +197,10 @@ void RejectedPromises::RejectedWithNoHandler(
v8::PromiseRejectMessage data,
const String& error_message,
std::unique_ptr<SourceLocation> location,
- AccessControlStatus cors_status) {
- queue_.push_back(Message::Create(script_state, data.GetPromise(),
- data.GetValue(), error_message,
- std::move(location), cors_status));
+ SanitizeScriptErrors sanitize_script_errors) {
+ queue_.push_back(Message::Create(
+ script_state, data.GetPromise(), data.GetValue(), error_message,
+ std::move(location), sanitize_script_errors));
}
void RejectedPromises::HandlerAdded(v8::PromiseRejectMessage data) {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.h b/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.h
index 71821c55040..b4bb6f7b2c4 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/rejected_promises.h
@@ -6,8 +6,8 @@
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_REJECTED_PROMISES_H_
#include <memory>
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -35,7 +35,7 @@ class RejectedPromises final : public RefCounted<RejectedPromises> {
v8::PromiseRejectMessage,
const String& error_message,
std::unique_ptr<SourceLocation>,
- AccessControlStatus);
+ SanitizeScriptErrors);
void HandlerAdded(v8::PromiseRejectMessage);
void ProcessQueue();
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.cc b/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.cc
index 751aaee6d8b..dcf2acf1ce4 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.cc
@@ -96,7 +96,7 @@ void RemoteWindowProxy::CreateContext() {
// Create a new v8::Context with the window object as the global object
// (aka the inner global). Reuse the outer global proxy if it already exists.
v8::Local<v8::ObjectTemplate> global_template =
- V8Window::domTemplate(GetIsolate(), *world_)->InstanceTemplate();
+ V8Window::DomTemplate(GetIsolate(), *world_)->InstanceTemplate();
CHECK(!global_template.IsEmpty());
v8::Local<v8::Object> global_proxy =
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.h b/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.h
index 30561dc9fbd..c96623a40ef 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/remote_window_proxy.h
@@ -48,12 +48,13 @@ class RemoteWindowProxy final : public WindowProxy {
static RemoteWindowProxy* Create(v8::Isolate* isolate,
RemoteFrame& frame,
scoped_refptr<DOMWrapperWorld> world) {
- return new RemoteWindowProxy(isolate, frame, std::move(world));
+ return MakeGarbageCollected<RemoteWindowProxy>(isolate, frame,
+ std::move(world));
}
- private:
RemoteWindowProxy(v8::Isolate*, RemoteFrame&, scoped_refptr<DOMWrapperWorld>);
+ private:
void Initialize() override;
void DisposeContext(Lifecycle next_status, FrameReuseStatus) override;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h b/chromium/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h
new file mode 100644
index 00000000000..d718c74b0f8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h
@@ -0,0 +1,35 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SANITIZE_SCRIPT_ERRORS_H_
+#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SANITIZE_SCRIPT_ERRORS_H_
+
+namespace blink {
+
+// https://html.spec.whatwg.org/C/webappapis.html#muted-errors
+// "A boolean which, if true, means that error information will not be provided
+// for errors in this script. This is used to mute errors for cross-origin
+// scripts, since that can leak private information."
+//
+// For example:
+// - A classic script from a cross-origin url without a "crossorigin" attribute
+// has "kSanitize" flag.
+// - A classic script from a cross-origin url with a "crossorigin" attribute
+// has "kDoNotSanitize" flag.
+// - A classic script from a same-origin url has "kDoNotSanitize" flag.
+//
+// "Muting" here usually means hiding error content, not hiding error
+// existence. When an error is muted, a sanitized error instance is dispatched
+// instead of the original error. But in the promise unhandled rejection case,
+// error existence is hidden when kSanitize is specified.
+enum class SanitizeScriptErrors {
+ // "muted errors" is false
+ kDoNotSanitize,
+ // *muted errors" is true
+ kSanitize
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_SANITIZE_ERRORS_H_
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc b/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc
index 94b91e7e15c..1fac6f436b7 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.cc
@@ -62,10 +62,11 @@ ScheduledAction* ScheduledAction::Create(ScriptState* script_state,
To<Document>(target)->GetFrame(),
BindingSecurity::ErrorReportOption::kDoNotReport)) {
UseCounter::Count(target, WebFeature::kScheduledActionIgnored);
- return new ScheduledAction(script_state);
+ return MakeGarbageCollected<ScheduledAction>(script_state);
}
}
- return new ScheduledAction(script_state, handler, arguments);
+ return MakeGarbageCollected<ScheduledAction>(script_state, handler,
+ arguments);
}
ScheduledAction* ScheduledAction::Create(ScriptState* script_state,
@@ -77,10 +78,10 @@ ScheduledAction* ScheduledAction::Create(ScriptState* script_state,
To<Document>(target)->GetFrame(),
BindingSecurity::ErrorReportOption::kDoNotReport)) {
UseCounter::Count(target, WebFeature::kScheduledActionIgnored);
- return new ScheduledAction(script_state);
+ return MakeGarbageCollected<ScheduledAction>(script_state);
}
}
- return new ScheduledAction(script_state, handler);
+ return MakeGarbageCollected<ScheduledAction>(script_state, handler);
}
ScheduledAction::~ScheduledAction() {
@@ -123,7 +124,7 @@ void ScheduledAction::Execute(ExecutionContext* context) {
Execute(frame);
} else {
DVLOG(1) << "ScheduledAction::execute " << this << ": worker scope";
- Execute(ToWorkerGlobalScope(context));
+ Execute(To<WorkerGlobalScope>(context));
}
}
@@ -171,15 +172,15 @@ void ScheduledAction::Execute(LocalFrame* frame) {
} else {
DVLOG(1) << "ScheduledAction::execute " << this
<< ": executing from source";
- // We're using |kSharableCrossOrigin| to keep the existing behavior, but
- // this causes failures on
+ // We're using |SanitizeScriptErrors::kDoNotSanitize| to keep the existing
+ // behavior, but this causes failures on
// wpt/html/webappapis/scripting/processing-model-2/compile-error-cross-origin-setTimeout.html
// and friends.
frame->GetScriptController().ExecuteScriptAndReturnValue(
script_state_->GetContext(),
ScriptSourceCode(code_,
ScriptSourceLocationType::kEvalForScheduledAction),
- KURL(), kSharableCrossOrigin);
+ KURL(), SanitizeScriptErrors::kDoNotSanitize);
}
// The frame might be invalid at this point because JavaScript could have
@@ -211,14 +212,14 @@ void ScheduledAction::Execute(WorkerGlobalScope* worker) {
function, worker, script_state_->GetContext()->Global(), info.size(),
info.data(), script_state_->GetIsolate());
} else {
- // We're using |kSharableCrossOrigin| to keep the existing behavior, but
- // this causes failures on
+ // We're using |SanitizeScriptErrors::kDoNotSanitize| to keep the existing
+ // behavior, but this causes failures on
// wpt/html/webappapis/scripting/processing-model-2/compile-error-cross-origin-setTimeout.html
// and friends.
worker->ScriptController()->Evaluate(
ScriptSourceCode(code_,
ScriptSourceLocationType::kEvalForScheduledAction),
- kSharableCrossOrigin);
+ SanitizeScriptErrors::kDoNotSanitize);
}
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.h b/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.h
index e115da2ef77..efc73bfad1b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/scheduled_action.h
@@ -59,14 +59,6 @@ class ScheduledAction final
ExecutionContext* target,
const String& handler);
- ~ScheduledAction();
- void Dispose();
-
- void Trace(blink::Visitor*);
-
- void Execute(ExecutionContext*);
-
- private:
ScheduledAction(ScriptState*,
const ScriptValue& handler,
const Vector<ScriptValue>& arguments);
@@ -75,6 +67,14 @@ class ScheduledAction final
// Creates an empty ScheduledAction.
explicit ScheduledAction(ScriptState*);
+ ~ScheduledAction();
+ void Dispose();
+
+ void Trace(blink::Visitor*);
+
+ void Execute(ExecutionContext*);
+
+ private:
void Execute(LocalFrame*);
void Execute(WorkerGlobalScope*);
void CreateLocalHandlesForArgs(Vector<v8::Local<v8::Value>>* handles);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.cc
index 913248754c8..e9d6c322097 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.cc
@@ -43,6 +43,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/scriptable_document_parser.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -88,12 +89,12 @@ v8::Local<v8::Value> ScriptController::ExecuteScriptAndReturnValue(
v8::Local<v8::Context> context,
const ScriptSourceCode& source,
const KURL& base_url,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
const ScriptFetchOptions& fetch_options) {
TRACE_EVENT1(
"devtools.timeline", "EvaluateScript", "data",
- InspectorEvaluateScriptEvent::Data(GetFrame(), source.Url().GetString(),
- source.StartPosition()));
+ inspector_evaluate_script_event::Data(
+ GetFrame(), source.Url().GetString(), source.StartPosition()));
v8::Local<v8::Value> result;
{
V8CacheOptions v8_cache_options = kV8CacheOptionsDefault;
@@ -121,7 +122,7 @@ v8::Local<v8::Value> ScriptController::ExecuteScriptAndReturnValue(
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(v8_cache_options, source);
if (!V8ScriptRunner::CompileScript(ScriptState::From(context), source,
- access_control_status, compile_options,
+ sanitize_script_errors, compile_options,
no_cache_reason, referrer_info)
.ToLocal(&script))
return result;
@@ -141,16 +142,6 @@ v8::Local<v8::Value> ScriptController::ExecuteScriptAndReturnValue(
return result;
}
-bool ScriptController::ShouldBypassMainWorldCSP() {
- v8::HandleScope handle_scope(GetIsolate());
- v8::Local<v8::Context> context = GetIsolate()->GetCurrentContext();
- if (context.IsEmpty() || !ToLocalDOMWindow(context))
- return false;
- DOMWrapperWorld& world = DOMWrapperWorld::Current(GetIsolate());
- return world.IsIsolatedWorld() ? world.IsolatedWorldHasContentSecurityPolicy()
- : false;
-}
-
TextPosition ScriptController::EventHandlerPosition() const {
ScriptableDocumentParser* parser =
GetFrame()->GetDocument()->GetScriptableDocumentParser();
@@ -181,19 +172,31 @@ void ScriptController::DisableEval(const String& error_message) {
V8String(GetIsolate(), error_message));
}
-V8Extensions& ScriptController::RegisteredExtensions() {
- DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
- return extensions;
+namespace {
+
+Vector<const char*>& RegisteredExtensionNames() {
+ DEFINE_STATIC_LOCAL(Vector<const char*>, extension_names, ());
+ return extension_names;
}
+} // namespace
+
void ScriptController::RegisterExtensionIfNeeded(v8::Extension* extension) {
- const V8Extensions& extensions = RegisteredExtensions();
- for (wtf_size_t i = 0; i < extensions.size(); ++i) {
- if (extensions[i] == extension)
+ for (const auto* extension_name : RegisteredExtensionNames()) {
+ if (!strcmp(extension_name, extension->name()))
return;
}
+ RegisteredExtensionNames().push_back(extension->name());
v8::RegisterExtension(extension);
- RegisteredExtensions().push_back(extension);
+}
+
+v8::ExtensionConfiguration ScriptController::ExtensionsFor(
+ const ExecutionContext* context) {
+ if (context->ShouldInstallV8Extensions()) {
+ return v8::ExtensionConfiguration(RegisteredExtensionNames().size(),
+ RegisteredExtensionNames().data());
+ }
+ return v8::ExtensionConfiguration();
}
void ScriptController::ClearWindowProxy() {
@@ -251,10 +254,11 @@ bool ScriptController::ExecuteScriptIfJavaScriptURL(const KURL& url,
// Step 12.9 "Let script be result of creating a classic script given script
// source, settings, base URL, and the default classic script fetch options."
// [spec text]
- // We pass |kSharableCrossOrigin| because |muted errors| is false by default.
+ // We pass |SanitizeScriptErrors::kDoNotSanitize| because |muted errors| is
+ // false by default.
v8::Local<v8::Value> result = EvaluateScriptInMainWorld(
ScriptSourceCode(script_source, ScriptSourceLocationType::kJavascriptUrl),
- base_url, kSharableCrossOrigin, ScriptFetchOptions(),
+ base_url, SanitizeScriptErrors::kDoNotSanitize, ScriptFetchOptions(),
kDoNotExecuteScriptWhenScriptsDisabled);
// If executing script caused this frame to be removed from the page, we
@@ -286,17 +290,17 @@ void ScriptController::ExecuteScriptInMainWorld(
ExecuteScriptPolicy policy) {
v8::HandleScope handle_scope(GetIsolate());
EvaluateScriptInMainWorld(ScriptSourceCode(script, source_location_type),
- KURL(), kOpaqueResource, ScriptFetchOptions(),
- policy);
+ KURL(), SanitizeScriptErrors::kSanitize,
+ ScriptFetchOptions(), policy);
}
void ScriptController::ExecuteScriptInMainWorld(
const ScriptSourceCode& source_code,
const KURL& base_url,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
const ScriptFetchOptions& fetch_options) {
v8::HandleScope handle_scope(GetIsolate());
- EvaluateScriptInMainWorld(source_code, base_url, access_control_status,
+ EvaluateScriptInMainWorld(source_code, base_url, sanitize_script_errors,
fetch_options,
kDoNotExecuteScriptWhenScriptsDisabled);
}
@@ -304,17 +308,17 @@ void ScriptController::ExecuteScriptInMainWorld(
v8::Local<v8::Value> ScriptController::ExecuteScriptInMainWorldAndReturnValue(
const ScriptSourceCode& source_code,
const KURL& base_url,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
const ScriptFetchOptions& fetch_options,
ExecuteScriptPolicy policy) {
- return EvaluateScriptInMainWorld(source_code, base_url, access_control_status,
- fetch_options, policy);
+ return EvaluateScriptInMainWorld(
+ source_code, base_url, sanitize_script_errors, fetch_options, policy);
}
v8::Local<v8::Value> ScriptController::EvaluateScriptInMainWorld(
const ScriptSourceCode& source_code,
const KURL& base_url,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
const ScriptFetchOptions& fetch_options,
ExecuteScriptPolicy policy) {
if (policy == kDoNotExecuteScriptWhenScriptsDisabled &&
@@ -333,7 +337,7 @@ v8::Local<v8::Value> ScriptController::EvaluateScriptInMainWorld(
GetFrame()->Loader().DidAccessInitialDocument();
v8::Local<v8::Value> object = ExecuteScriptAndReturnValue(
- script_state->GetContext(), source_code, base_url, access_control_status,
+ script_state->GetContext(), source_code, base_url, sanitize_script_errors,
fetch_options);
if (object.IsEmpty())
@@ -346,7 +350,7 @@ v8::Local<v8::Value> ScriptController::ExecuteScriptInIsolatedWorld(
int world_id,
const ScriptSourceCode& source,
const KURL& base_url,
- AccessControlStatus access_control_status) {
+ SanitizeScriptErrors sanitize_script_errors) {
DCHECK_GT(world_id, 0);
scoped_refptr<DOMWrapperWorld> world =
@@ -359,7 +363,7 @@ v8::Local<v8::Value> ScriptController::ExecuteScriptInIsolatedWorld(
v8::Context::Scope scope(context);
v8::Local<v8::Value> evaluation_result = ExecuteScriptAndReturnValue(
- context, source, base_url, access_control_status);
+ context, source, base_url, sanitize_script_errors);
if (!evaluation_result.IsEmpty())
return evaluation_result;
return v8::Local<v8::Value>::New(GetIsolate(), v8::Undefined(GetIsolate()));
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.h
index 01501bfcc0a..89af1d7854b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_controller.h
@@ -31,13 +31,13 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_CONTROLLER_H_
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_CONTROLLER_H_
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_location_type.h"
#include "third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/shared_persistent.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
@@ -48,13 +48,12 @@ namespace blink {
class DOMWrapperWorld;
class Element;
+class ExecutionContext;
class KURL;
class LocalFrame;
class ScriptSourceCode;
class SecurityOrigin;
-typedef WTF::Vector<v8::Extension*> V8Extensions;
-
// This class exposes methods to run script in a frame (in the main world and
// in isolated worlds). An instance can be obtained by using
// LocalFrame::GetScriptController().
@@ -71,9 +70,12 @@ class CORE_EXPORT ScriptController final
static ScriptController* Create(
LocalFrame& frame,
LocalWindowProxyManager& window_proxy_manager) {
- return new ScriptController(frame, window_proxy_manager);
+ return MakeGarbageCollected<ScriptController>(frame, window_proxy_manager);
}
+ ScriptController(LocalFrame& frame,
+ LocalWindowProxyManager& window_proxy_manager)
+ : frame_(&frame), window_proxy_manager_(&window_proxy_manager) {}
void Trace(blink::Visitor*);
// This returns an initialized window proxy. (If the window proxy is not
@@ -90,19 +92,19 @@ class CORE_EXPORT ScriptController final
void ExecuteScriptInMainWorld(
const ScriptSourceCode&,
const KURL& base_url,
- AccessControlStatus,
+ SanitizeScriptErrors,
const ScriptFetchOptions& = ScriptFetchOptions());
v8::Local<v8::Value> ExecuteScriptInMainWorldAndReturnValue(
const ScriptSourceCode&,
const KURL& base_url,
- AccessControlStatus,
+ SanitizeScriptErrors,
const ScriptFetchOptions& = ScriptFetchOptions(),
ExecuteScriptPolicy = kDoNotExecuteScriptWhenScriptsDisabled);
v8::Local<v8::Value> ExecuteScriptAndReturnValue(
v8::Local<v8::Context>,
const ScriptSourceCode&,
const KURL& base_url,
- AccessControlStatus,
+ SanitizeScriptErrors,
const ScriptFetchOptions& = ScriptFetchOptions());
// Executes JavaScript in an isolated world. The script gets its own global
@@ -115,7 +117,7 @@ class CORE_EXPORT ScriptController final
int world_id,
const ScriptSourceCode&,
const KURL& base_url,
- AccessControlStatus access_control_status);
+ SanitizeScriptErrors sanitize_script_errors);
// Returns true if argument is a JavaScript URL.
bool ExecuteScriptIfJavaScriptURL(const KURL&, Element*);
@@ -125,11 +127,6 @@ class CORE_EXPORT ScriptController final
scoped_refptr<DOMWrapperWorld> CreateNewInspectorIsolatedWorld(
const String& world_name);
- // Returns true if the current world is isolated, and has its own Content
- // Security Policy. In this case, the policy of the main world should be
- // ignored when evaluating resources injected into the DOM.
- bool ShouldBypassMainWorldCSP();
-
void DisableEval(const String& error_message);
TextPosition EventHandlerPosition() const;
@@ -145,13 +142,9 @@ class CORE_EXPORT ScriptController final
// affect v8 contexts initialized after this call. Takes ownership of
// the v8::Extension object passed.
static void RegisterExtensionIfNeeded(v8::Extension*);
- static V8Extensions& RegisteredExtensions();
+ static v8::ExtensionConfiguration ExtensionsFor(const ExecutionContext*);
private:
- ScriptController(LocalFrame& frame,
- LocalWindowProxyManager& window_proxy_manager)
- : frame_(&frame), window_proxy_manager_(&window_proxy_manager) {}
-
LocalFrame* GetFrame() const { return frame_; }
v8::Isolate* GetIsolate() const {
return window_proxy_manager_->GetIsolate();
@@ -160,7 +153,7 @@ class CORE_EXPORT ScriptController final
v8::Local<v8::Value> EvaluateScriptInMainWorld(const ScriptSourceCode&,
const KURL& base_url,
- AccessControlStatus,
+ SanitizeScriptErrors,
const ScriptFetchOptions&,
ExecuteScriptPolicy);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.cc
index 0ed5ed957f3..db2db818149 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.cc
@@ -5,12 +5,17 @@
#include "third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_adopted_callback.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_attribute_changed_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_constructor.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_disabled_state_changed_callback.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_form_associated_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_registry.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_element.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_function.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_void_function.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/events/error_event.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
@@ -74,15 +79,23 @@ ScriptCustomElementDefinition* ScriptCustomElementDefinition::Create(
const CustomElementDescriptor& descriptor,
CustomElementDefinition::Id id,
V8CustomElementConstructor* constructor,
- V8Function* connected_callback,
- V8Function* disconnected_callback,
- V8Function* adopted_callback,
- V8Function* attribute_changed_callback,
- HashSet<AtomicString>&& observed_attributes) {
- ScriptCustomElementDefinition* definition = new ScriptCustomElementDefinition(
- script_state, descriptor, constructor, connected_callback,
- disconnected_callback, adopted_callback, attribute_changed_callback,
- std::move(observed_attributes));
+ V8VoidFunction* connected_callback,
+ V8VoidFunction* disconnected_callback,
+ V8CustomElementAdoptedCallback* adopted_callback,
+ V8CustomElementAttributeChangedCallback* attribute_changed_callback,
+ V8CustomElementFormAssociatedCallback* form_associated_callback,
+ V8CustomElementDisabledStateChangedCallback*
+ disabled_state_changed_callback,
+ HashSet<AtomicString>&& observed_attributes,
+ const Vector<String>& disabled_features,
+ FormAssociationFlag form_association_flag) {
+ ScriptCustomElementDefinition* definition =
+ MakeGarbageCollected<ScriptCustomElementDefinition>(
+ script_state, descriptor, constructor, connected_callback,
+ disconnected_callback, adopted_callback, attribute_changed_callback,
+ form_associated_callback, disabled_state_changed_callback,
+ std::move(observed_attributes), disabled_features,
+ form_association_flag);
// Tag the JavaScript constructor object with its ID.
v8::Local<v8::Value> id_value =
@@ -100,18 +113,28 @@ ScriptCustomElementDefinition::ScriptCustomElementDefinition(
ScriptState* script_state,
const CustomElementDescriptor& descriptor,
V8CustomElementConstructor* constructor,
- V8Function* connected_callback,
- V8Function* disconnected_callback,
- V8Function* adopted_callback,
- V8Function* attribute_changed_callback,
- HashSet<AtomicString>&& observed_attributes)
- : CustomElementDefinition(descriptor, std::move(observed_attributes)),
+ V8VoidFunction* connected_callback,
+ V8VoidFunction* disconnected_callback,
+ V8CustomElementAdoptedCallback* adopted_callback,
+ V8CustomElementAttributeChangedCallback* attribute_changed_callback,
+ V8CustomElementFormAssociatedCallback* form_associated_callback,
+ V8CustomElementDisabledStateChangedCallback*
+ disabled_state_changed_callback,
+ HashSet<AtomicString>&& observed_attributes,
+ const Vector<String>& disabled_features,
+ FormAssociationFlag form_association_flag)
+ : CustomElementDefinition(descriptor,
+ std::move(observed_attributes),
+ disabled_features,
+ form_association_flag),
script_state_(script_state),
constructor_(constructor),
connected_callback_(connected_callback),
disconnected_callback_(disconnected_callback),
adopted_callback_(adopted_callback),
- attribute_changed_callback_(attribute_changed_callback) {}
+ attribute_changed_callback_(attribute_changed_callback),
+ form_associated_callback_(form_associated_callback),
+ disabled_state_changed_callback_(disabled_state_changed_callback) {}
void ScriptCustomElementDefinition::Trace(Visitor* visitor) {
visitor->Trace(script_state_);
@@ -120,6 +143,8 @@ void ScriptCustomElementDefinition::Trace(Visitor* visitor) {
visitor->Trace(disconnected_callback_);
visitor->Trace(adopted_callback_);
visitor->Trace(attribute_changed_callback_);
+ visitor->Trace(form_associated_callback_);
+ visitor->Trace(disabled_state_changed_callback_);
CustomElementDefinition::Trace(visitor);
}
@@ -260,19 +285,26 @@ bool ScriptCustomElementDefinition::HasAdoptedCallback() const {
return adopted_callback_;
}
+bool ScriptCustomElementDefinition::HasFormAssociatedCallback() const {
+ return form_associated_callback_;
+}
+
+bool ScriptCustomElementDefinition::HasDisabledStateChangedCallback() const {
+ return disabled_state_changed_callback_;
+}
+
void ScriptCustomElementDefinition::RunConnectedCallback(Element* element) {
if (!connected_callback_)
return;
- connected_callback_->InvokeAndReportException(element, Vector<ScriptValue>());
+ connected_callback_->InvokeAndReportException(element);
}
void ScriptCustomElementDefinition::RunDisconnectedCallback(Element* element) {
if (!disconnected_callback_)
return;
- disconnected_callback_->InvokeAndReportException(element,
- Vector<ScriptValue>());
+ disconnected_callback_->InvokeAndReportException(element);
}
void ScriptCustomElementDefinition::RunAdoptedCallback(Element* element,
@@ -281,15 +313,7 @@ void ScriptCustomElementDefinition::RunAdoptedCallback(Element* element,
if (!adopted_callback_)
return;
- ScriptState* script_state = adopted_callback_->CallbackRelevantScriptState();
- if (!script_state->ContextIsValid())
- return;
- ScriptState::Scope scope(script_state);
- Vector<ScriptValue> args({
- ScriptValue(script_state, ToV8(old_owner, script_state)),
- ScriptValue(script_state, ToV8(new_owner, script_state)),
- });
- adopted_callback_->InvokeAndReportException(element, args);
+ adopted_callback_->InvokeAndReportException(element, old_owner, new_owner);
}
void ScriptCustomElementDefinition::RunAttributeChangedCallback(
@@ -300,19 +324,25 @@ void ScriptCustomElementDefinition::RunAttributeChangedCallback(
if (!attribute_changed_callback_)
return;
- v8::Isolate* isolate = attribute_changed_callback_->GetIsolate();
- ScriptState* script_state =
- attribute_changed_callback_->CallbackRelevantScriptState();
- if (!script_state->ContextIsValid())
+ attribute_changed_callback_->InvokeAndReportException(
+ element, name.LocalName(), old_value, new_value, name.NamespaceURI());
+}
+
+void ScriptCustomElementDefinition::RunFormAssociatedCallback(
+ Element* element,
+ HTMLFormElement* nullable_form) {
+ if (!form_associated_callback_)
+ return;
+ form_associated_callback_->InvokeAndReportException(element, nullable_form);
+}
+
+void ScriptCustomElementDefinition::RunDisabledStateChangedCallback(
+ Element* element,
+ bool is_disabled) {
+ if (!disabled_state_changed_callback_)
return;
- ScriptState::Scope scope(script_state);
- Vector<ScriptValue> args({
- ScriptValue(script_state, V8String(isolate, name.LocalName())),
- ScriptValue(script_state, V8StringOrNull(isolate, old_value)),
- ScriptValue(script_state, V8StringOrNull(isolate, new_value)),
- ScriptValue(script_state, V8StringOrNull(isolate, name.NamespaceURI())),
- });
- attribute_changed_callback_->InvokeAndReportException(element, args);
+ disabled_state_changed_callback_->InvokeAndReportException(element,
+ is_disabled);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h
index b27f7254d2c..4a1eb049dd2 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h
@@ -17,8 +17,12 @@ namespace blink {
class CustomElementDescriptor;
class CustomElementRegistry;
+class V8CustomElementAdoptedCallback;
+class V8CustomElementAttributeChangedCallback;
class V8CustomElementConstructor;
-class V8Function;
+class V8CustomElementDisabledStateChangedCallback;
+class V8CustomElementFormAssociatedCallback;
+class V8VoidFunction;
class CORE_EXPORT ScriptCustomElementDefinition final
: public CustomElementDefinition {
@@ -36,12 +40,31 @@ class CORE_EXPORT ScriptCustomElementDefinition final
const CustomElementDescriptor&,
CustomElementDefinition::Id,
V8CustomElementConstructor* constructor,
- V8Function* connected_callback,
- V8Function* disconnected_callback,
- V8Function* adopted_callback,
- V8Function* attribute_changed_callback,
- HashSet<AtomicString>&& observed_attributes);
-
+ V8VoidFunction* connected_callback,
+ V8VoidFunction* disconnected_callback,
+ V8CustomElementAdoptedCallback* adopted_callback,
+ V8CustomElementAttributeChangedCallback* attribute_changed_callback,
+ V8CustomElementFormAssociatedCallback* form_associated_callback,
+ V8CustomElementDisabledStateChangedCallback*
+ disabled_state_changed_callback,
+ HashSet<AtomicString>&& observed_attributes,
+ const Vector<String>& disabled_features,
+ FormAssociationFlag form_association_flag);
+
+ ScriptCustomElementDefinition(
+ ScriptState*,
+ const CustomElementDescriptor&,
+ V8CustomElementConstructor* constructor,
+ V8VoidFunction* connected_callback,
+ V8VoidFunction* disconnected_callback,
+ V8CustomElementAdoptedCallback* adopted_callback,
+ V8CustomElementAttributeChangedCallback* attribute_changed_callback,
+ V8CustomElementFormAssociatedCallback* form_associated_callback,
+ V8CustomElementDisabledStateChangedCallback*
+ disabled_state_changed_callback,
+ HashSet<AtomicString>&& observed_attributes,
+ const Vector<String>& disabled_features,
+ FormAssociationFlag form_association_flag);
~ScriptCustomElementDefinition() override = default;
void Trace(Visitor*) override;
@@ -54,6 +77,8 @@ class CORE_EXPORT ScriptCustomElementDefinition final
bool HasConnectedCallback() const override;
bool HasDisconnectedCallback() const override;
bool HasAdoptedCallback() const override;
+ bool HasFormAssociatedCallback() const override;
+ bool HasDisabledStateChangedCallback() const override;
void RunConnectedCallback(Element*) override;
void RunDisconnectedCallback(Element*) override;
@@ -64,17 +89,12 @@ class CORE_EXPORT ScriptCustomElementDefinition final
const QualifiedName&,
const AtomicString& old_value,
const AtomicString& new_value) override;
+ void RunFormAssociatedCallback(Element* element,
+ HTMLFormElement* nullable_form) override;
+ void RunDisabledStateChangedCallback(Element* element,
+ bool is_disabled) override;
private:
- ScriptCustomElementDefinition(ScriptState*,
- const CustomElementDescriptor&,
- V8CustomElementConstructor* constructor,
- V8Function* connected_callback,
- V8Function* disconnected_callback,
- V8Function* adopted_callback,
- V8Function* attribute_changed_callback,
- HashSet<AtomicString>&& observed_attributes);
-
// Implementations of |CustomElementDefinition|
ScriptValue GetConstructorForScript() final;
bool RunConstructor(Element*) override;
@@ -89,10 +109,15 @@ class CORE_EXPORT ScriptCustomElementDefinition final
Member<ScriptState> script_state_;
TraceWrapperMember<V8CustomElementConstructor> constructor_;
- TraceWrapperMember<V8Function> connected_callback_;
- TraceWrapperMember<V8Function> disconnected_callback_;
- TraceWrapperMember<V8Function> adopted_callback_;
- TraceWrapperMember<V8Function> attribute_changed_callback_;
+ TraceWrapperMember<V8VoidFunction> connected_callback_;
+ TraceWrapperMember<V8VoidFunction> disconnected_callback_;
+ TraceWrapperMember<V8CustomElementAdoptedCallback> adopted_callback_;
+ TraceWrapperMember<V8CustomElementAttributeChangedCallback>
+ attribute_changed_callback_;
+ TraceWrapperMember<V8CustomElementFormAssociatedCallback>
+ form_associated_callback_;
+ TraceWrapperMember<V8CustomElementDisabledStateChangedCallback>
+ disabled_state_changed_callback_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc
index e57011a1cde..79f2c83793f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc
@@ -9,8 +9,12 @@
#include "third_party/blink/renderer/bindings/core/v8/script_custom_element_definition.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_adopted_callback.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_attribute_changed_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_constructor.h"
-#include "third_party/blink/renderer/bindings/core/v8/v8_function.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_disabled_state_changed_callback.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_custom_element_form_associated_callback.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_void_function.h"
#include "third_party/blink/renderer/platform/bindings/callback_method_retriever.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -67,7 +71,7 @@ bool ScriptCustomElementDefinitionBuilder::RememberOriginalProperties() {
return false;
if (v8_connected_callback_->IsFunction()) {
connected_callback_ =
- V8Function::Create(v8_connected_callback_.As<v8::Function>());
+ V8VoidFunction::Create(v8_connected_callback_.As<v8::Function>());
}
v8_disconnected_callback_ =
retriever.GetMethodOrUndefined("disconnectedCallback", exception_state_);
@@ -75,15 +79,15 @@ bool ScriptCustomElementDefinitionBuilder::RememberOriginalProperties() {
return false;
if (v8_disconnected_callback_->IsFunction()) {
disconnected_callback_ =
- V8Function::Create(v8_disconnected_callback_.As<v8::Function>());
+ V8VoidFunction::Create(v8_disconnected_callback_.As<v8::Function>());
}
v8_adopted_callback_ =
retriever.GetMethodOrUndefined("adoptedCallback", exception_state_);
if (exception_state_.HadException())
return false;
if (v8_adopted_callback_->IsFunction()) {
- adopted_callback_ =
- V8Function::Create(v8_adopted_callback_.As<v8::Function>());
+ adopted_callback_ = V8CustomElementAdoptedCallback::Create(
+ v8_adopted_callback_.As<v8::Function>());
}
v8_attribute_changed_callback_ = retriever.GetMethodOrUndefined(
"attributeChangedCallback", exception_state_);
@@ -91,7 +95,8 @@ bool ScriptCustomElementDefinitionBuilder::RememberOriginalProperties() {
return false;
if (v8_attribute_changed_callback_->IsFunction()) {
attribute_changed_callback_ =
- V8Function::Create(v8_attribute_changed_callback_.As<v8::Function>());
+ V8CustomElementAttributeChangedCallback::Create(
+ v8_attribute_changed_callback_.As<v8::Function>());
}
// step 10.6. If the value of the entry in lifecycleCallbacks with key
@@ -110,17 +115,79 @@ bool ScriptCustomElementDefinitionBuilder::RememberOriginalProperties() {
return false;
}
- if (v8_observed_attributes->IsUndefined())
- return true;
+ if (!v8_observed_attributes->IsUndefined()) {
+ const Vector<String>& observed_attrs =
+ NativeValueTraits<IDLSequence<IDLString>>::NativeValue(
+ isolate, v8_observed_attributes, exception_state_);
+ if (exception_state_.HadException())
+ return false;
+ observed_attributes_.ReserveCapacityForSize(observed_attrs.size());
+ for (const auto& attribute : observed_attrs)
+ observed_attributes_.insert(AtomicString(attribute));
+ }
+ }
+
+ if (RuntimeEnabledFeatures::ElementInternalsEnabled()) {
+ auto* isolate = script_state_->GetIsolate();
+ v8::Local<v8::Context> current_context = isolate->GetCurrentContext();
+ v8::TryCatch try_catch(isolate);
+ v8::Local<v8::Value> v8_disabled_features;
+
+ if (!constructor_->CallbackObject()
+ ->Get(current_context, V8AtomicString(isolate, "disabledFeatures"))
+ .ToLocal(&v8_disabled_features)) {
+ exception_state_.RethrowV8Exception(try_catch.Exception());
+ return false;
+ }
+
+ if (!v8_disabled_features->IsUndefined()) {
+ disabled_features_ =
+ NativeValueTraits<IDLSequence<IDLString>>::NativeValue(
+ isolate, v8_disabled_features, exception_state_);
+ if (exception_state_.HadException())
+ return false;
+ }
+ }
+
+ if (RuntimeEnabledFeatures::FormAssociatedCustomElementsEnabled()) {
+ auto* isolate = script_state_->GetIsolate();
+ v8::Local<v8::Context> current_context = isolate->GetCurrentContext();
+ v8::TryCatch try_catch(isolate);
+ v8::Local<v8::Value> v8_form_associated;
- const Vector<String>& observed_attrs =
- NativeValueTraits<IDLSequence<IDLString>>::NativeValue(
- isolate, v8_observed_attributes, exception_state_);
+ if (!constructor_->CallbackObject()
+ ->Get(current_context, V8AtomicString(isolate, "formAssociated"))
+ .ToLocal(&v8_form_associated)) {
+ exception_state_.RethrowV8Exception(try_catch.Exception());
+ return false;
+ }
+
+ if (!v8_form_associated->IsUndefined()) {
+ is_form_associated_ = NativeValueTraits<IDLBoolean>::NativeValue(
+ isolate, v8_form_associated, exception_state_);
+ if (exception_state_.HadException())
+ return false;
+ }
+ }
+ if (is_form_associated_) {
+ v8_form_associated_callback_ = retriever.GetMethodOrUndefined(
+ "formAssociatedCallback", exception_state_);
+ if (exception_state_.HadException())
+ return false;
+ if (v8_form_associated_callback_->IsFunction()) {
+ form_associated_callback_ = V8CustomElementFormAssociatedCallback::Create(
+ v8_form_associated_callback_.As<v8::Function>());
+ }
+
+ v8_disabled_state_changed_callback_ = retriever.GetMethodOrUndefined(
+ "disabledStateChangedCallback", exception_state_);
if (exception_state_.HadException())
return false;
- observed_attributes_.ReserveCapacityForSize(observed_attrs.size());
- for (const auto& attribute : observed_attrs)
- observed_attributes_.insert(AtomicString(attribute));
+ if (v8_disabled_state_changed_callback_->IsFunction()) {
+ disabled_state_changed_callback_ =
+ V8CustomElementDisabledStateChangedCallback::Create(
+ v8_disabled_state_changed_callback_.As<v8::Function>());
+ }
}
return true;
@@ -132,7 +199,11 @@ CustomElementDefinition* ScriptCustomElementDefinitionBuilder::Build(
return ScriptCustomElementDefinition::Create(
script_state_, registry_, descriptor, id, constructor_,
connected_callback_, disconnected_callback_, adopted_callback_,
- attribute_changed_callback_, std::move(observed_attributes_));
+ attribute_changed_callback_, form_associated_callback_,
+ disabled_state_changed_callback_, std::move(observed_attributes_),
+ disabled_features_,
+ is_form_associated_ ? FormAssociationFlag::kYes
+ : FormAssociationFlag::kNo);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.h
index eeb90940474..c34319489d5 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.h
@@ -22,8 +22,12 @@ namespace blink {
class CustomElementRegistry;
class ExceptionState;
class ScriptState;
+class V8CustomElementAdoptedCallback;
+class V8CustomElementAttributeChangedCallback;
class V8CustomElementConstructor;
-class V8Function;
+class V8CustomElementDisabledStateChangedCallback;
+class V8CustomElementFormAssociatedCallback;
+class V8VoidFunction;
class CORE_EXPORT ScriptCustomElementDefinitionBuilder
: public CustomElementDefinitionBuilder {
@@ -55,11 +59,18 @@ class CORE_EXPORT ScriptCustomElementDefinitionBuilder
v8::Local<v8::Value> v8_disconnected_callback_;
v8::Local<v8::Value> v8_adopted_callback_;
v8::Local<v8::Value> v8_attribute_changed_callback_;
- Member<V8Function> connected_callback_;
- Member<V8Function> disconnected_callback_;
- Member<V8Function> adopted_callback_;
- Member<V8Function> attribute_changed_callback_;
+ v8::Local<v8::Value> v8_form_associated_callback_;
+ v8::Local<v8::Value> v8_disabled_state_changed_callback_;
+ Member<V8VoidFunction> connected_callback_;
+ Member<V8VoidFunction> disconnected_callback_;
+ Member<V8CustomElementAdoptedCallback> adopted_callback_;
+ Member<V8CustomElementAttributeChangedCallback> attribute_changed_callback_;
+ Member<V8CustomElementFormAssociatedCallback> form_associated_callback_;
+ Member<V8CustomElementDisabledStateChangedCallback>
+ disabled_state_changed_callback_;
HashSet<AtomicString> observed_attributes_;
+ Vector<String> disabled_features_;
+ bool is_form_associated_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc
index 15576be91de..1ffd0df22d2 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc
@@ -56,7 +56,6 @@ EventListener* CreateAttributeEventListener(Node* node,
String source_url;
v8::Isolate* isolate = ToIsolate(&node->GetDocument());
- v8::HandleScope scope(isolate);
if (LocalFrame* frame = node->GetDocument().GetFrame()) {
ScriptController& script_controller = frame->GetScriptController();
@@ -66,16 +65,15 @@ EventListener* CreateAttributeEventListener(Node* node,
source_url = node->GetDocument().Url().GetString();
}
- // |v8_context| can be an empty handle when this listener is added as content
- // attribute like <hoge onclick="fuga"></hoge> because there is no JS context
- // when parsing HTML. In that case we should assume the main world.
- v8::Local<v8::Context> v8_context = isolate->GetCurrentContext();
+ // An assumption here is that the content attributes are used only in the main
+ // world or the isolated world for the content scripts, they are never used in
+ // other isolated worlds nor worker/worklets.
+ // In case of the content scripts, Blink runs script in the main world instead
+ // of the isolated world for the content script by design.
+ DOMWrapperWorld& world = DOMWrapperWorld::MainWorld();
return JSEventHandlerForContentAttribute::Create(
- name.LocalName(), value, source_url, position, isolate,
- v8_context.IsEmpty() ? DOMWrapperWorld::MainWorld()
- : ScriptState::From(v8_context)->World(),
- type);
+ name.LocalName(), value, source_url, position, isolate, world, type);
}
EventListener* CreateAttributeEventListener(LocalFrame* frame,
@@ -95,18 +93,16 @@ EventListener* CreateAttributeEventListener(LocalFrame* frame,
String source_url = frame->GetDocument()->Url().GetString();
v8::Isolate* isolate = ToIsolate(frame);
- v8::HandleScope scope(isolate);
- // |v8_context| can be an empty handle when this listener is added as content
- // attribute like <hoge onclick="fuga"></hoge> because there is no JS context
- // when parsing HTML. In that case we should assume the main world.
- v8::Local<v8::Context> v8_context = isolate->GetCurrentContext();
+ // An assumption here is that the content attributes are used only in the main
+ // world or the isolated world for the content scripts, they are never used in
+ // other isolated worlds nor worker/worklets.
+ // In case of the content scripts, Blink runs script in the main world instead
+ // of the isolated world for the content script by design.
+ DOMWrapperWorld& world = DOMWrapperWorld::MainWorld();
return JSEventHandlerForContentAttribute::Create(
- name.LocalName(), value, source_url, position, isolate,
- v8_context.IsEmpty() ? DOMWrapperWorld::MainWorld()
- : ScriptState::From(v8_context)->World(),
- type);
+ name.LocalName(), value, source_url, position, isolate, world, type);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_iterator.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_iterator.cc
index 8457d7d8a7d..bc53edb5efe 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_iterator.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_iterator.cc
@@ -72,16 +72,14 @@ bool ScriptIterator::Next(ExecutionContext* execution_context,
}
v8::Local<v8::Value> done;
- v8::Local<v8::Boolean> done_boolean;
- if (!result_object->Get(context, done_key_).ToLocal(&done) ||
- !done->ToBoolean(context).ToLocal(&done_boolean)) {
+ if (!result_object->Get(context, done_key_).ToLocal(&done)) {
CHECK(!try_catch.Exception().IsEmpty());
exception_state.RethrowV8Exception(try_catch.Exception());
done_ = true;
return false;
}
- done_ = done_boolean->Value();
+ done_ = done->BooleanValue(isolate_);
return !done_;
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_module.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_module.cc
index 3fdc21bd60b..d06a23b05c4 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_module.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_module.cc
@@ -35,14 +35,12 @@ ScriptModule ScriptModule::Compile(v8::Isolate* isolate,
const KURL& source_url,
const KURL& base_url,
const ScriptFetchOptions& options,
- AccessControlStatus access_control_status,
const TextPosition& text_position,
ExceptionState& exception_state) {
v8::TryCatch try_catch(isolate);
v8::Local<v8::Module> module;
- if (!V8ScriptRunner::CompileModule(isolate, source, source_url,
- access_control_status, text_position,
+ if (!V8ScriptRunner::CompileModule(isolate, source, source_url, text_position,
ReferrerScriptInfo(base_url, options))
.ToLocal(&module)) {
DCHECK(try_catch.HasCaught());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_module.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_module.h
index 8570d790323..e956c260a42 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_module.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_module.h
@@ -7,7 +7,6 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/bindings/shared_persistent.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -38,7 +37,6 @@ class CORE_EXPORT ScriptModule final {
const KURL& source_url,
const KURL& base_url,
const ScriptFetchOptions&,
- AccessControlStatus,
const TextPosition&,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_module_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_module_test.cc
index 2390b8d8f05..3418dcf1fae 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_module_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_module_test.cc
@@ -15,7 +15,6 @@
#include "third_party/blink/renderer/core/testing/dummy_modulator.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "v8/include/v8.h"
namespace blink {
@@ -76,7 +75,7 @@ class ScriptModuleTestModulator final : public DummyModulator {
};
ScriptModuleTestModulator::ScriptModuleTestModulator()
- : resolver_(new TestScriptModuleResolver) {}
+ : resolver_(MakeGarbageCollected<TestScriptModuleResolver>()) {}
void ScriptModuleTestModulator::Trace(blink::Visitor* visitor) {
visitor->Trace(resolver_);
@@ -88,8 +87,8 @@ TEST(ScriptModuleTest, compileSuccess) {
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "export const a = 42;", js_url, js_url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module.IsNull());
}
@@ -98,8 +97,7 @@ TEST(ScriptModuleTest, compileFail) {
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "123 = 456", js_url, js_url, ScriptFetchOptions(),
- kSharableCrossOrigin, TextPosition::MinimumPosition(),
- scope.GetExceptionState());
+ TextPosition::MinimumPosition(), scope.GetExceptionState());
ASSERT_TRUE(module.IsNull());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
@@ -112,13 +110,13 @@ TEST(ScriptModuleTest, equalAndHash) {
ScriptModule module_null;
ScriptModule module_a = ScriptModule::Compile(
scope.GetIsolate(), "export const a = 'a';", js_url_a, js_url_a,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module_a.IsNull());
ScriptModule module_b = ScriptModule::Compile(
scope.GetIsolate(), "export const b = 'b';", js_url_b, js_url_b,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module_b.IsNull());
Vector<char> module_deleted_buffer(sizeof(ScriptModule));
ScriptModule& module_deleted =
@@ -159,8 +157,8 @@ TEST(ScriptModuleTest, moduleRequests) {
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "import 'a'; import 'b'; export const c = 'c';",
- js_url, js_url, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ js_url, js_url, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module.IsNull());
auto requests = module.ModuleRequests(scope.GetScriptState());
@@ -170,7 +168,7 @@ TEST(ScriptModuleTest, moduleRequests) {
TEST(ScriptModuleTest, instantiateNoDeps) {
V8TestingScope scope;
- auto* modulator = new ScriptModuleTestModulator();
+ auto* modulator = MakeGarbageCollected<ScriptModuleTestModulator>();
auto* resolver = modulator->GetTestScriptModuleResolver();
Modulator::SetModulator(scope.GetScriptState(), modulator);
@@ -178,8 +176,8 @@ TEST(ScriptModuleTest, instantiateNoDeps) {
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "export const a = 42;", js_url, js_url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(scope.GetScriptState());
ASSERT_TRUE(exception.IsEmpty());
@@ -190,7 +188,7 @@ TEST(ScriptModuleTest, instantiateNoDeps) {
TEST(ScriptModuleTest, instantiateWithDeps) {
V8TestingScope scope;
- auto* modulator = new ScriptModuleTestModulator();
+ auto* modulator = MakeGarbageCollected<ScriptModuleTestModulator>();
auto* resolver = modulator->GetTestScriptModuleResolver();
Modulator::SetModulator(scope.GetScriptState(), modulator);
@@ -198,24 +196,24 @@ TEST(ScriptModuleTest, instantiateWithDeps) {
const KURL js_url_a("https://example.com/a.js");
ScriptModule module_a = ScriptModule::Compile(
scope.GetIsolate(), "export const a = 'a';", js_url_a, js_url_a,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module_a.IsNull());
resolver->PushScriptModule(module_a);
const KURL js_url_b("https://example.com/b.js");
ScriptModule module_b = ScriptModule::Compile(
scope.GetIsolate(), "export const b = 'b';", js_url_b, js_url_b,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module_b.IsNull());
resolver->PushScriptModule(module_b);
const KURL js_url_c("https://example.com/c.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "import 'a'; import 'b'; export const c = 123;",
- js_url_c, js_url_c, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ js_url_c, js_url_c, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(scope.GetScriptState());
ASSERT_TRUE(exception.IsEmpty());
@@ -228,7 +226,7 @@ TEST(ScriptModuleTest, instantiateWithDeps) {
TEST(ScriptModuleTest, EvaluationErrrorIsRemembered) {
V8TestingScope scope;
- auto* modulator = new ScriptModuleTestModulator();
+ auto* modulator = MakeGarbageCollected<ScriptModuleTestModulator>();
auto* resolver = modulator->GetTestScriptModuleResolver();
Modulator::SetModulator(scope.GetScriptState(), modulator);
@@ -236,8 +234,8 @@ TEST(ScriptModuleTest, EvaluationErrrorIsRemembered) {
const KURL js_url_f("https://example.com/failure.js");
ScriptModule module_failure = ScriptModule::Compile(
scope.GetIsolate(), "nonexistent_function()", js_url_f, js_url_f,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module_failure.IsNull());
ASSERT_TRUE(module_failure.Instantiate(scope.GetScriptState()).IsEmpty());
ScriptValue evaluation_error =
@@ -249,8 +247,8 @@ TEST(ScriptModuleTest, EvaluationErrrorIsRemembered) {
const KURL js_url_c("https://example.com/c.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "import 'failure'; export const c = 123;", js_url_c,
- js_url_c, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), scope.GetExceptionState());
+ js_url_c, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ scope.GetExceptionState());
ASSERT_FALSE(module.IsNull());
ASSERT_TRUE(module.Instantiate(scope.GetScriptState()).IsEmpty());
ScriptValue evaluation_error2 = module.Evaluate(scope.GetScriptState());
@@ -265,24 +263,24 @@ TEST(ScriptModuleTest, EvaluationErrrorIsRemembered) {
TEST(ScriptModuleTest, Evaluate) {
V8TestingScope scope;
- auto* modulator = new ScriptModuleTestModulator();
+ auto* modulator = MakeGarbageCollected<ScriptModuleTestModulator>();
Modulator::SetModulator(scope.GetScriptState(), modulator);
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "export const a = 42; window.foo = 'bar';", js_url,
- js_url, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ js_url, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(scope.GetScriptState());
ASSERT_TRUE(exception.IsEmpty());
EXPECT_TRUE(module.Evaluate(scope.GetScriptState()).IsEmpty());
- v8::Local<v8::Value> value =
- scope.GetFrame()
- .GetScriptController()
- .ExecuteScriptInMainWorldAndReturnValue(
- ScriptSourceCode("window.foo"), KURL(), kOpaqueResource);
+ v8::Local<v8::Value> value = scope.GetFrame()
+ .GetScriptController()
+ .ExecuteScriptInMainWorldAndReturnValue(
+ ScriptSourceCode("window.foo"), KURL(),
+ SanitizeScriptErrors::kSanitize);
ASSERT_TRUE(value->IsString());
EXPECT_EQ("bar", ToCoreString(v8::Local<v8::String>::Cast(value)));
@@ -299,14 +297,13 @@ TEST(ScriptModuleTest, Evaluate) {
TEST(ScriptModuleTest, EvaluateCaptureError) {
V8TestingScope scope;
- auto* modulator = new ScriptModuleTestModulator();
+ auto* modulator = MakeGarbageCollected<ScriptModuleTestModulator>();
Modulator::SetModulator(scope.GetScriptState(), modulator);
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
scope.GetIsolate(), "throw 'bar';", js_url, js_url, ScriptFetchOptions(),
- kSharableCrossOrigin, TextPosition::MinimumPosition(),
- ASSERT_NO_EXCEPTION);
+ TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
ASSERT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(scope.GetScriptState());
ASSERT_TRUE(exception.IsEmpty());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise.cc
index d79efd16401..f7ca42d342a 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise.cc
@@ -133,14 +133,8 @@ class PromiseAllHandler final
if (--number_of_pending_promises_ > 0)
return;
- v8::Local<v8::Array> values =
- v8::Array::New(value.GetIsolate(), values_.size());
- for (wtf_size_t i = 0; i < values_.size(); ++i) {
- if (!V8CallBoolean(values->CreateDataProperty(value.GetContext(), i,
- values_[i].V8Value())))
- return;
- }
-
+ v8::Local<v8::Value> values =
+ ToV8(values_, value.GetContext()->Global(), value.GetIsolate());
MarkPromiseSettled();
resolver_.Resolve(values);
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc
index 27078675eb7..608124103c8 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc
@@ -130,7 +130,9 @@ class ScriptPromisePropertyTestBase {
}
void Gc() {
- V8GCController::CollectAllGarbageForTesting(v8::Isolate::GetCurrent());
+ V8GCController::CollectAllGarbageForTesting(
+ v8::Isolate::GetCurrent(),
+ v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
}
v8::Local<v8::Function> NotReached(ScriptState* script_state) {
@@ -168,8 +170,9 @@ class ScriptPromisePropertyGarbageCollectedTest
typedef GarbageCollectedHolder::Property Property;
ScriptPromisePropertyGarbageCollectedTest()
- : holder_(new GarbageCollectedHolder(&GetDocument())) {}
+ : holder_(MakeGarbageCollected<GarbageCollectedHolder>(&GetDocument())) {}
+ void ClearHolder() { holder_.Clear(); }
GarbageCollectedHolder* Holder() { return holder_; }
Property* GetProperty() { return holder_->GetProperty(); }
ScriptPromise Promise(DOMWrapperWorld& world) {
@@ -192,7 +195,8 @@ class ScriptPromisePropertyNonScriptWrappableResolutionTargetTest
ToV8UndefinedGenerator>
Property;
Property* property = new Property(
- &GetDocument(), new GarbageCollectedScriptWrappable("holder"),
+ &GetDocument(),
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("holder"),
Property::kReady);
size_t n_resolve_calls = 0;
ScriptValue actual_value;
@@ -264,7 +268,7 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest,
Promise_IsStableObjectAfterSettling) {
ScriptPromise v = Promise(DOMWrapperWorld::MainWorld());
GarbageCollectedScriptWrappable* value =
- new GarbageCollectedScriptWrappable("value");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("value");
GetProperty()->Resolve(value);
EXPECT_EQ(Property::kResolved, GetProperty()->GetState());
@@ -290,10 +294,9 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest,
EXPECT_FALSE(observation->wasCollected());
holder_wrapper.Clear();
+ ClearHolder();
Gc();
EXPECT_TRUE(observation->wasCollected());
-
- EXPECT_EQ(Property::kPending, GetProperty()->GetState());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
@@ -320,7 +323,7 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest,
EXPECT_NE(promise, other_promise);
GarbageCollectedScriptWrappable* value =
- new GarbageCollectedScriptWrappable("value");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("value");
GetProperty()->Resolve(value);
EXPECT_EQ(Property::kResolved, GetProperty()->GetState());
@@ -348,7 +351,7 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest,
EXPECT_NE(promise, other_promise);
GarbageCollectedScriptWrappable* value =
- new GarbageCollectedScriptWrappable("value");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("value");
GetProperty()->Resolve(value);
EXPECT_EQ(Property::kResolved, GetProperty()->GetState());
@@ -373,7 +376,7 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest,
TEST_F(ScriptPromisePropertyGarbageCollectedTest, Reject_RejectsScriptPromise) {
GarbageCollectedScriptWrappable* reason =
- new GarbageCollectedScriptWrappable("reason");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("reason");
GetProperty()->Reject(reason);
EXPECT_EQ(Property::kRejected, GetProperty()->GetState());
@@ -405,7 +408,8 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest, Reject_RejectsScriptPromise) {
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest, Promise_DeadContext) {
- GetProperty()->Resolve(new GarbageCollectedScriptWrappable("value"));
+ GetProperty()->Resolve(
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("value"));
EXPECT_EQ(Property::kResolved, GetProperty()->GetState());
DestroyContext();
@@ -426,7 +430,8 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest, Resolve_DeadContext) {
EXPECT_TRUE(!GetProperty()->GetExecutionContext() ||
GetProperty()->GetExecutionContext()->IsContextDestroyed());
- GetProperty()->Resolve(new GarbageCollectedScriptWrappable("value"));
+ GetProperty()->Resolve(
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("value"));
EXPECT_EQ(Property::kPending, GetProperty()->GetState());
v8::MicrotasksScope::PerformCheckpoint(v8::Isolate::GetCurrent());
@@ -438,9 +443,9 @@ TEST_F(ScriptPromisePropertyGarbageCollectedTest, Reset) {
ScriptPromise old_promise, new_promise;
ScriptValue old_actual, new_actual;
GarbageCollectedScriptWrappable* old_value =
- new GarbageCollectedScriptWrappable("old");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("old");
GarbageCollectedScriptWrappable* new_value =
- new GarbageCollectedScriptWrappable("new");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("new");
size_t n_old_resolve_calls = 0;
size_t n_new_reject_calls = 0;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.cc
index c9edbdb7d0c..f00ecd53742 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.cc
@@ -8,6 +8,10 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
+#if DCHECK_IS_ON()
+#include "base/debug/alias.h"
+#endif
+
namespace blink {
ScriptPromiseResolver::ScriptPromiseResolver(ScriptState* script_state)
@@ -21,6 +25,25 @@ ScriptPromiseResolver::ScriptPromiseResolver(ScriptState* script_state)
}
}
+#if DCHECK_IS_ON()
+ScriptPromiseResolver::~ScriptPromiseResolver() {
+ // This is here temporarily to make it easier to track down which promise
+ // resolvers are being abandoned.
+ // TODO(crbug.com/873980): Remove this.
+ base::debug::StackTrace create_stack_trace(create_stack_trace_);
+ base::debug::Alias(&create_stack_trace);
+
+ // This assertion fails if:
+ // - promise() is called at least once and
+ // - this resolver is destructed before it is resolved, rejected,
+ // detached, the V8 isolate is terminated or the associated
+ // ExecutionContext is stopped.
+ DCHECK(state_ == kDetached || !is_promise_called_ ||
+ !GetScriptState()->ContextIsValid() || !GetExecutionContext() ||
+ GetExecutionContext()->IsContextDestroyed());
+}
+#endif
+
void ScriptPromiseResolver::Reject(ExceptionState& exception_state) {
DCHECK(exception_state.HadException());
Reject(exception_state.GetException());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h
index 0ab94180113..f6df61365bf 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h
@@ -15,9 +15,13 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/self_keep_alive.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "v8/include/v8.h"
+#if DCHECK_IS_ON()
+#include "base/debug/stack_trace.h"
+#endif
+
namespace blink {
// This class wraps v8::Promise::Resolver and provides the following
@@ -39,26 +43,22 @@ class CORE_EXPORT ScriptPromiseResolver
public:
static ScriptPromiseResolver* Create(ScriptState* script_state) {
- ScriptPromiseResolver* resolver = new ScriptPromiseResolver(script_state);
+ ScriptPromiseResolver* resolver =
+ MakeGarbageCollected<ScriptPromiseResolver>(script_state);
resolver->PauseIfNeeded();
return resolver;
}
+ // You need to call suspendIfNeeded after the construction because
+ // this is an PausableObject.
+ explicit ScriptPromiseResolver(ScriptState*);
+
#if DCHECK_IS_ON()
// Eagerly finalized so as to ensure valid access to getExecutionContext()
// from the destructor's assert.
EAGERLY_FINALIZE();
- ~ScriptPromiseResolver() override {
- // This assertion fails if:
- // - promise() is called at least once and
- // - this resolver is destructed before it is resolved, rejected,
- // detached, the V8 isolate is terminated or the associated
- // ExecutionContext is stopped.
- DCHECK(state_ == kDetached || !is_promise_called_ ||
- !GetScriptState()->ContextIsValid() || !GetExecutionContext() ||
- GetExecutionContext()->IsContextDestroyed());
- }
+ ~ScriptPromiseResolver() override;
#endif
// Anything that can be passed to toV8 can be passed to this function.
@@ -107,11 +107,6 @@ class CORE_EXPORT ScriptPromiseResolver
void Trace(blink::Visitor*) override;
- protected:
- // You need to call suspendIfNeeded after the construction because
- // this is an PausableObject.
- explicit ScriptPromiseResolver(ScriptState*);
-
private:
typedef ScriptPromise::InternalResolver Resolver;
enum ResolutionState {
@@ -179,6 +174,8 @@ class CORE_EXPORT ScriptPromiseResolver
#if DCHECK_IS_ON()
// True if promise() is called.
bool is_promise_called_ = false;
+
+ base::debug::StackTrace create_stack_trace_{8};
#endif
};
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.cc
index 746517c5b38..312f8934487 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.cc
@@ -38,12 +38,12 @@ KURL StripFragmentIdentifier(const KURL& url) {
}
String SourceMapUrlFromResponse(const ResourceResponse& response) {
- String source_map_url = response.HttpHeaderField(HTTPNames::SourceMap);
+ String source_map_url = response.HttpHeaderField(http_names::kSourceMap);
if (!source_map_url.IsEmpty())
return source_map_url;
// Try to get deprecated header.
- return response.HttpHeaderField(HTTPNames::X_SourceMap);
+ return response.HttpHeaderField(http_names::kXSourceMap);
}
} // namespace
@@ -90,6 +90,16 @@ ScriptSourceCode::ScriptSourceCode(ScriptStreamer* streamer,
DCHECK_EQ(!streamer, reason != ScriptStreamer::NotStreamingReason::kInvalid);
}
+ScriptSourceCode::ScriptSourceCode(const String& source,
+ SingleCachedMetadataHandler* cache_handler,
+ const KURL& url)
+ : source_(TreatNullSourceAsEmpty(ParkableString(source.Impl()))),
+ cache_handler_(cache_handler),
+ not_streaming_reason_(ScriptStreamer::kWorkerTopLevelScript),
+ url_(url),
+ start_position_(TextPosition::MinimumPosition()),
+ source_location_type_(ScriptSourceLocationType::kUnknown) {}
+
ScriptSourceCode::~ScriptSourceCode() = default;
void ScriptSourceCode::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.h
index 2a3bbe32925..96042ce368f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_source_code.h
@@ -57,13 +57,6 @@ class CORE_EXPORT ScriptSourceCode final {
const KURL& = KURL(),
const TextPosition& = TextPosition::MinimumPosition());
- ScriptSourceCode(
- const ParkableString& source,
- ScriptSourceLocationType = ScriptSourceLocationType::kUnknown,
- SingleCachedMetadataHandler* cache_handler = nullptr,
- const KURL& = KURL(),
- const TextPosition& start_position = TextPosition::MinimumPosition());
-
// For external scripts.
//
// We lose the encoding information from ScriptResource.
@@ -72,6 +65,19 @@ class CORE_EXPORT ScriptSourceCode final {
ScriptResource*,
ScriptStreamer::NotStreamingReason);
+ // For (external) worker scripts. Leaves url fragment intact.
+ //
+ // If we move worker top-level script fetch to the worker thread, this could
+ // probably be merged in to the main external script constructor.
+ //
+ // NOTE: It is import to keep the url fragment in this case so that errors in
+ // worker scripts can include the fragment when reporting the location of the
+ // failure. This is enforced by several tests in
+ // external/wpt/workers/interfaces/WorkerGlobalScope/onerror/.
+ ScriptSourceCode(const String& source,
+ SingleCachedMetadataHandler*,
+ const KURL&);
+
~ScriptSourceCode();
void Trace(blink::Visitor*);
@@ -90,6 +96,13 @@ class CORE_EXPORT ScriptSourceCode final {
}
private:
+ ScriptSourceCode(
+ const ParkableString& source,
+ ScriptSourceLocationType = ScriptSourceLocationType::kUnknown,
+ SingleCachedMetadataHandler* cache_handler = nullptr,
+ const KURL& = KURL(),
+ const TextPosition& start_position = TextPosition::MinimumPosition());
+
const ParkableString source_;
Member<SingleCachedMetadataHandler> cache_handler_;
Member<ScriptStreamer> streamer_;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.cc
index 486ef2544fb..5aaee51b99b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.cc
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/parser/text_resource_decoder.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-#include "third_party/blink/renderer/core/script/classic_pending_script.h"
+#include "third_party/blink/renderer/core/loader/resource/script_resource.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
@@ -22,6 +22,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
@@ -313,8 +314,8 @@ void RunScriptStreamingTask(
ScriptStreamer* streamer) {
TRACE_EVENT1(
"v8,devtools.timeline", "v8.parseOnBackground", "data",
- InspectorParseScriptEvent::Data(streamer->ScriptResourceIdentifier(),
- streamer->ScriptURLString()));
+ inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(),
+ streamer->ScriptURLString()));
// Running the task can and will block: SourceStream::GetSomeData will get
// called and it will block and wait for data from the network.
task->Run();
@@ -343,7 +344,7 @@ bool ScriptStreamer::HasEnoughDataForStreaming(size_t resource_buffer_size) {
return resource_buffer_size >= small_script_threshold_;
}
-void ScriptStreamer::NotifyAppendData(ScriptResource* resource) {
+void ScriptStreamer::NotifyAppendData() {
DCHECK(IsMainThread());
if (streaming_suppressed_)
return;
@@ -351,8 +352,8 @@ void ScriptStreamer::NotifyAppendData(ScriptResource* resource) {
// Even if the first data chunk is small, the script can still be big
// enough - wait until the next data chunk comes before deciding whether
// to start the streaming.
- DCHECK(resource->ResourceBuffer());
- if (!HasEnoughDataForStreaming(resource->ResourceBuffer()->size()))
+ DCHECK(script_resource_->ResourceBuffer());
+ if (!HasEnoughDataForStreaming(script_resource_->ResourceBuffer()->size()))
return;
have_enough_data_for_streaming_ = true;
@@ -360,8 +361,8 @@ void ScriptStreamer::NotifyAppendData(ScriptResource* resource) {
// Check for BOM (byte order marks), because that might change our
// understanding of the data encoding.
char maybe_bom[kMaximumLengthOfBOM] = {};
- if (!resource->ResourceBuffer()->GetBytes(maybe_bom,
- kMaximumLengthOfBOM)) {
+ if (!script_resource_->ResourceBuffer()->GetBytes(maybe_bom,
+ kMaximumLengthOfBOM)) {
NOTREACHED();
return;
}
@@ -369,7 +370,7 @@ void ScriptStreamer::NotifyAppendData(ScriptResource* resource) {
std::unique_ptr<TextResourceDecoder> decoder(
TextResourceDecoder::Create(TextResourceDecoderOptions(
TextResourceDecoderOptions::kPlainTextContent,
- WTF::TextEncoding(resource->Encoding()))));
+ WTF::TextEncoding(script_resource_->Encoding()))));
decoder->CheckForBOM(maybe_bom, kMaximumLengthOfBOM);
// The encoding may change when we see the BOM. Check for BOM now
@@ -424,7 +425,7 @@ void ScriptStreamer::NotifyAppendData(ScriptResource* resource) {
// cancel the task.
//
// TODO(leszeks): Decrease the priority of these tasks where possible.
- BackgroundScheduler::PostOnBackgroundThreadWithTraits(
+ background_scheduler::PostOnBackgroundThreadWithTraits(
FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()},
CrossThreadBind(RunBlockingScriptStreamingTask,
WTF::Passed(std::move(script_streaming_task)),
@@ -441,7 +442,7 @@ void ScriptStreamer::NotifyAppendData(ScriptResource* resource) {
}
if (stream_)
- stream_->DidReceiveData(resource, this);
+ stream_->DidReceiveData(script_resource_, this);
}
void ScriptStreamer::NotifyFinished() {
@@ -463,9 +464,10 @@ void ScriptStreamer::NotifyFinished() {
// a non-blocking task, since we know now that all the data is received and
// we will no longer block.
//
- // TODO(874080): Once we have mutable task traits, simply unmark the
- // existing task as no longer MayBlock.
+ // TODO(874080): Remove this once blocking and non-blocking pools are
+ // merged.
if (RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled() &&
+ !RuntimeEnabledFeatures::MergeBlockingNonBlockingPoolsEnabled() &&
!blocking_task_started_or_cancelled_.test_and_set()) {
std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask>
script_streaming_task(
@@ -476,7 +478,7 @@ void ScriptStreamer::NotifyFinished() {
// The task creation shouldn't fail, since it didn't fail before during
// NotifyAppendData.
CHECK(script_streaming_task);
- BackgroundScheduler::PostOnBackgroundThreadWithTraits(
+ background_scheduler::PostOnBackgroundThreadWithTraits(
FROM_HERE, {base::TaskPriority::USER_BLOCKING},
CrossThreadBind(RunNonBlockingScriptStreamingTask,
WTF::Passed(std::move(script_streaming_task)),
@@ -489,10 +491,10 @@ void ScriptStreamer::NotifyFinished() {
}
ScriptStreamer::ScriptStreamer(
- ClassicPendingScript* script,
+ ScriptResource* script_resource,
v8::ScriptCompiler::CompileOptions compile_options,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner)
- : pending_script_(script),
+ : script_resource_(script_resource),
detached_(false),
stream_(nullptr),
loading_finished_(false),
@@ -501,8 +503,8 @@ ScriptStreamer::ScriptStreamer(
streaming_suppressed_(false),
suppressed_reason_(kInvalid),
compile_options_(compile_options),
- script_url_string_(script->GetResource()->Url().Copy().GetString()),
- script_resource_identifier_(script->GetResource()->Identifier()),
+ script_url_string_(script_resource->Url().Copy().GetString()),
+ script_resource_identifier_(script_resource->Identifier()),
// Unfortunately there's no dummy encoding value in the enum; let's use
// one we don't stream.
encoding_(v8::ScriptCompiler::StreamedSource::TWO_BYTE),
@@ -516,7 +518,7 @@ void ScriptStreamer::Prefinalize() {
}
void ScriptStreamer::Trace(blink::Visitor* visitor) {
- visitor->Trace(pending_script_);
+ visitor->Trace(script_resource_);
}
void ScriptStreamer::StreamingComplete() {
@@ -549,64 +551,33 @@ void ScriptStreamer::NotifyFinishedToClient() {
if (!IsFinished())
return;
- pending_script_->StreamingFinished();
+ script_resource_->StreamingFinished();
}
-void ScriptStreamer::StartStreaming(
- ClassicPendingScript* script,
+ScriptStreamer* ScriptStreamer::Create(
+ ScriptResource* resource,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
NotStreamingReason* not_streaming_reason) {
DCHECK(IsMainThread());
*not_streaming_reason = kInvalid;
- ScriptResource* resource = ToScriptResource(script->GetResource());
if (!resource->Url().ProtocolIsInHTTPFamily()) {
*not_streaming_reason = kNotHTTP;
- return;
- }
- if (resource->IsCacheValidator()) {
- // This happens e.g., during reloads. We're actually not going to load
- // the current Resource of the ClassicPendingScript but switch to another
- // Resource -> don't stream.
- *not_streaming_reason = kReload;
- return;
+ return nullptr;
}
if (resource->IsLoaded() && !resource->ResourceBuffer()) {
// This happens for already loaded resources, e.g. if resource
// validation fails. In that case, the loading subsystem will discard
// the resource buffer.
*not_streaming_reason = kNoResourceBuffer;
- return;
+ return nullptr;
}
// We cannot filter out short scripts, even if we wait for the HTTP headers
// to arrive: the Content-Length HTTP header is not sent for chunked
// downloads.
- ScriptStreamer* streamer =
- new ScriptStreamer(script, v8::ScriptCompiler::kNoCompileOptions,
- std::move(loading_task_runner));
-
- // If this script was ready when streaming began, no callbacks will be
- // received to populate the data for the ScriptStreamer, so send them now.
- // Note that this script may be processing an asynchronous cache hit, in
- // which case ScriptResource::IsLoaded() will be true, but ready_state_ will
- // not be kReadyStreaming. In that case, ScriptStreamer can listen to the
- // async callbacks generated by the cache hit.
- if (script->IsReady()) {
- DCHECK(resource->IsLoaded());
- streamer->NotifyAppendData(resource);
- if (streamer->StreamingSuppressed()) {
- *not_streaming_reason = streamer->StreamingSuppressedReason();
- return;
- }
- }
-
- // The Resource might go out of scope if the script is no longer needed.
- // This makes ClassicPendingScript notify the ScriptStreamer when it is
- // destroyed.
- script->SetStreamer(streamer);
-
- if (script->IsReady())
- streamer->NotifyFinished();
+ return MakeGarbageCollected<ScriptStreamer>(
+ resource, v8::ScriptCompiler::kNoCompileOptions,
+ std::move(loading_task_runner));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.h
index 0891268a3cf..6532cc33158 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer.h
@@ -17,12 +17,11 @@
namespace blink {
-class ClassicPendingScript;
class ScriptResource;
class SourceStream;
// ScriptStreamer streams incomplete script data to V8 so that it can be parsed
-// while it's loaded. ClassicPendingScript holds a reference to ScriptStreamer.
+// while it's loaded. ScriptResource holds a reference to ScriptStreamer.
// At the moment, ScriptStreamer is only used for parser blocking scripts; this
// means that the Document stays stable and no other scripts are executing
// while we're streaming. It is possible, though, that Document and the
@@ -40,32 +39,39 @@ class CORE_EXPORT ScriptStreamer final
enum NotStreamingReason {
kAlreadyLoaded, // DEPRECATED
kNotHTTP,
- kReload,
+ kRevalidate,
kContextNotValid, // DEPRECATED
kEncodingNotSupported,
+ // TODO(leszeks): Deprecate once scheduled streaming is on by default
kThreadBusy,
kV8CannotStream,
kScriptTooSmall,
kNoResourceBuffer,
kHasCodeCache,
- kStreamerNotReadyOnGetSource,
+ kStreamerNotReadyOnGetSource, // DEPRECATED
kInlineScript,
kDidntTryToStartStreaming,
kErrorOccurred,
+ kStreamingDisabled,
+ kSecondScriptResourceUse,
+ kWorkerTopLevelScript,
// Pseudo values that should never be seen in reported metrics
kCount,
kInvalid = -1,
};
+ ScriptStreamer(ScriptResource*,
+ v8::ScriptCompiler::CompileOptions,
+ scoped_refptr<base::SingleThreadTaskRunner>);
~ScriptStreamer();
void Trace(blink::Visitor*);
- // Launches a task (on a background thread) which will stream the given
- // ClassicPendingScript into V8 as it loads.
- static void StartStreaming(ClassicPendingScript*,
- scoped_refptr<base::SingleThreadTaskRunner>,
- NotStreamingReason* not_streaming_reason);
+ // Create a script streamer which will stream the given ScriptResource into V8
+ // as it loads.
+ static ScriptStreamer* Create(ScriptResource*,
+ scoped_refptr<base::SingleThreadTaskRunner>,
+ NotStreamingReason* not_streaming_reason);
// Returns false if we cannot stream the given encoding.
static bool ConvertEncoding(const char* encoding_name,
@@ -98,8 +104,12 @@ class CORE_EXPORT ScriptStreamer final
return suppressed_reason_;
}
- // Called by ClassicPendingScript when data arrives from the network.
- void NotifyAppendData(ScriptResource*);
+ // Called by ScriptResource when data arrives from the network.
+ void NotifyAppendData();
+ // Called by ScriptResource when loading has completed.
+ //
+ // Should not be called synchronously, as it can trigger script resource
+ // client callbacks.
void NotifyFinished();
// Called by ScriptStreamingTask when it has streamed all data to V8 and V8
@@ -122,17 +132,17 @@ class CORE_EXPORT ScriptStreamer final
// Maximum size of the BOM marker.
static constexpr size_t kMaximumLengthOfBOM = 4;
- ScriptStreamer(ClassicPendingScript*,
- v8::ScriptCompiler::CompileOptions,
- scoped_refptr<base::SingleThreadTaskRunner>);
-
void Prefinalize();
+ // Should not be called synchronously, as it can trigger script resource
+ // client callbacks.
void StreamingComplete();
+ // Should not be called synchronously, as it can trigger script resource
+ // client callbacks.
void NotifyFinishedToClient();
bool HasEnoughDataForStreaming(size_t resource_buffer_size);
- Member<ClassicPendingScript> pending_script_;
+ Member<ScriptResource> script_resource_;
// Whether ScriptStreamer is detached from the Resource. In those cases, the
// script data is not needed any more, and the client won't get notified
// when the loading and streaming are done.
@@ -147,7 +157,7 @@ class CORE_EXPORT ScriptStreamer final
// Flag used to allow atomic cancelling and reposting of the streaming task
// when the load completes without the task yet starting.
- // TODO(874080): Remove once we can mutate task traits.
+ // TODO(874080): Remove this once blocking and non-blocking pools are merged.
std::atomic_flag blocking_task_started_or_cancelled_ = ATOMIC_FLAG_INIT;
// Whether the script source code should be retrieved from the Resource
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc
index 7d033b0912c..dc00b6abda9 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc
@@ -159,10 +159,7 @@ class TestPendingScriptClient final
TEST_F(ScriptStreamingTest, CompilingStreamedScript) {
// Test that we can successfully compile a streamed script.
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -188,8 +185,9 @@ TEST_F(ScriptStreamingTest, CompilingStreamedScript) {
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(kV8CacheOptionsDefault, source_code);
EXPECT_TRUE(V8ScriptRunner::CompileScript(
- scope.GetScriptState(), source_code, kSharableCrossOrigin,
- compile_options, no_cache_reason, ReferrerScriptInfo())
+ scope.GetScriptState(), source_code,
+ SanitizeScriptErrors::kDoNotSanitize, compile_options,
+ no_cache_reason, ReferrerScriptInfo())
.ToLocal(&script));
EXPECT_FALSE(try_catch.HasCaught());
}
@@ -199,10 +197,7 @@ TEST_F(ScriptStreamingTest, CompilingStreamedScriptWithParseError) {
// the V8 side typically finished before loading finishes: make sure we
// handle it gracefully.
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
AppendData("function foo() {");
@@ -230,8 +225,9 @@ TEST_F(ScriptStreamingTest, CompilingStreamedScriptWithParseError) {
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(kV8CacheOptionsDefault, source_code);
EXPECT_FALSE(V8ScriptRunner::CompileScript(
- scope.GetScriptState(), source_code, kSharableCrossOrigin,
- compile_options, no_cache_reason, ReferrerScriptInfo())
+ scope.GetScriptState(), source_code,
+ SanitizeScriptErrors::kDoNotSanitize, compile_options,
+ no_cache_reason, ReferrerScriptInfo())
.ToLocal(&script));
EXPECT_TRUE(try_catch.HasCaught());
}
@@ -240,10 +236,7 @@ TEST_F(ScriptStreamingTest, CancellingStreaming) {
// Test that the upper layers (PendingScript and up) can be ramped down
// while streaming is ongoing, and ScriptStreamer handles it gracefully.
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
AppendData("function foo() {");
@@ -264,14 +257,11 @@ TEST_F(ScriptStreamingTest, CancellingStreaming) {
EXPECT_FALSE(client->Finished());
}
-TEST_F(ScriptStreamingTest, DataAfterCancellingStreaming) {
+TEST_F(ScriptStreamingTest, DataAfterDisposingPendingScript) {
// Test that the upper layers (PendingScript and up) can be ramped down
// before streaming is started, and ScriptStreamer handles it gracefully.
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -291,6 +281,7 @@ TEST_F(ScriptStreamingTest, DataAfterCancellingStreaming) {
// holding on to it here.
// Make sure the streaming starts.
+ AppendData(resource, "function foo() {");
AppendPadding(resource);
resource.Clear();
@@ -306,10 +297,7 @@ TEST_F(ScriptStreamingTest, SuppressingStreaming) {
// upper layer (ScriptResourceClient) should get a notification when the
// script is loaded.
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
AppendData("function foo() {");
@@ -338,10 +326,7 @@ TEST_F(ScriptStreamingTest, EmptyScripts) {
// (ScriptResourceClient) should be notified when an empty script has been
// loaded.
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -360,10 +345,7 @@ TEST_F(ScriptStreamingTest, SmallScripts) {
V8TestingScope scope;
ScriptStreamer::SetSmallScriptThresholdForTesting(100);
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -385,10 +367,7 @@ TEST_F(ScriptStreamingTest, ScriptsWithSmallFirstChunk) {
V8TestingScope scope;
ScriptStreamer::SetSmallScriptThresholdForTesting(100);
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -412,8 +391,9 @@ TEST_F(ScriptStreamingTest, ScriptsWithSmallFirstChunk) {
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(kV8CacheOptionsDefault, source_code);
EXPECT_TRUE(V8ScriptRunner::CompileScript(
- scope.GetScriptState(), source_code, kSharableCrossOrigin,
- compile_options, no_cache_reason, ReferrerScriptInfo())
+ scope.GetScriptState(), source_code,
+ SanitizeScriptErrors::kDoNotSanitize, compile_options,
+ no_cache_reason, ReferrerScriptInfo())
.ToLocal(&script));
EXPECT_FALSE(try_catch.HasCaught());
}
@@ -424,10 +404,7 @@ TEST_F(ScriptStreamingTest, EncodingChanges) {
V8TestingScope scope;
GetResource()->SetEncodingForTest("windows-1252");
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -451,8 +428,9 @@ TEST_F(ScriptStreamingTest, EncodingChanges) {
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(kV8CacheOptionsDefault, source_code);
EXPECT_TRUE(V8ScriptRunner::CompileScript(
- scope.GetScriptState(), source_code, kSharableCrossOrigin,
- compile_options, no_cache_reason, ReferrerScriptInfo())
+ scope.GetScriptState(), source_code,
+ SanitizeScriptErrors::kDoNotSanitize, compile_options,
+ no_cache_reason, ReferrerScriptInfo())
.ToLocal(&script));
EXPECT_FALSE(try_catch.HasCaught());
}
@@ -465,10 +443,7 @@ TEST_F(ScriptStreamingTest, EncodingFromBOM) {
// This encoding is wrong on purpose.
GetResource()->SetEncodingForTest("windows-1252");
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -491,8 +466,9 @@ TEST_F(ScriptStreamingTest, EncodingFromBOM) {
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(kV8CacheOptionsDefault, source_code);
EXPECT_TRUE(V8ScriptRunner::CompileScript(
- scope.GetScriptState(), source_code, kSharableCrossOrigin,
- compile_options, no_cache_reason, ReferrerScriptInfo())
+ scope.GetScriptState(), source_code,
+ SanitizeScriptErrors::kDoNotSanitize, compile_options,
+ no_cache_reason, ReferrerScriptInfo())
.ToLocal(&script));
EXPECT_FALSE(try_catch.HasCaught());
}
@@ -500,10 +476,7 @@ TEST_F(ScriptStreamingTest, EncodingFromBOM) {
// A test for crbug.com/711703. Should not crash.
TEST_F(ScriptStreamingTest, GarbageCollectDuringStreaming) {
V8TestingScope scope;
- ScriptStreamer::NotStreamingReason reason;
- ScriptStreamer::StartStreaming(GetPendingScript(), loading_task_runner_,
- &reason);
- GetPendingScript()->SetNotStreamingReasonForTest(reason);
+ GetResource()->StartStreaming(loading_task_runner_);
TestPendingScriptClient* client = new TestPendingScriptClient;
GetPendingScript()->WatchForLoad(client);
@@ -515,6 +488,32 @@ TEST_F(ScriptStreamingTest, GarbageCollectDuringStreaming) {
BlinkGC::kEagerSweeping, BlinkGC::GCReason::kForcedGC);
}
+TEST_F(ScriptStreamingTest, ResourceSetRevalidatingRequest) {
+ V8TestingScope scope;
+ GetResource()->StartStreaming(loading_task_runner_);
+
+ TestPendingScriptClient* client = new TestPendingScriptClient;
+ GetPendingScript()->WatchForLoad(client);
+
+ // Kick the streaming off.
+ AppendData("function foo() {");
+ AppendPadding();
+ AppendData("}");
+ Finish();
+ ProcessTasksUntilStreamingComplete();
+
+ // Second start streaming should fail.
+ EXPECT_FALSE(GetResource()->StartStreaming(loading_task_runner_));
+
+ ResourceRequest request(GetResource()->Url());
+ GetResource()->SetRevalidatingRequest(request);
+
+ // The next streaming should still fail, but the reason should be
+ // "kRevalidate".
+ EXPECT_FALSE(GetResource()->StartStreaming(loading_task_runner_));
+ EXPECT_EQ(GetResource()->NoStreamerReason(), ScriptStreamer::kRevalidate);
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc
index 4bd5bf7cedb..bcedd5468e2 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc
@@ -11,8 +11,8 @@
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -69,8 +69,8 @@ void ScriptStreamerThread::RunScriptStreamingTask(
DCHECK(!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled());
TRACE_EVENT1(
"v8,devtools.timeline", "v8.parseOnBackground", "data",
- InspectorParseScriptEvent::Data(streamer->ScriptResourceIdentifier(),
- streamer->ScriptURLString()));
+ inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(),
+ streamer->ScriptURLString()));
// Running the task can and will block: SourceStream::GetSomeData will get
// called and it will block and wait for data from the network.
task->Run();
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_value.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_value.cc
index 419134d6a24..291b5b6c290 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_value.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_value.cc
@@ -35,6 +35,28 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
+namespace {
+
+v8::Local<v8::Value> ToWorldSafeValue(ScriptState* target_script_state,
+ v8::Local<v8::Value> value) {
+ if (value.IsEmpty() || !value->IsObject())
+ return value;
+
+ v8::Local<v8::Context> creation_context =
+ value.As<v8::Object>()->CreationContext();
+ v8::Isolate* isolate = target_script_state->GetIsolate();
+ if (&ScriptState::From(creation_context)->World() ==
+ &target_script_state->World()) {
+ return value;
+ }
+
+ v8::Context::Scope target_context_scope(target_script_state->GetContext());
+ scoped_refptr<SerializedScriptValue> serialized =
+ SerializedScriptValue::SerializeAndSwallowExceptions(isolate, value);
+ return serialized->Deserialize(isolate);
+}
+
+} // namespace
v8::Local<v8::Value> ScriptValue::V8Value() const {
if (IsEmpty())
@@ -56,15 +78,9 @@ v8::Local<v8::Value> ScriptValue::V8ValueFor(
ScriptState* target_script_state) const {
if (IsEmpty())
return v8::Local<v8::Value>();
- v8::Isolate* isolate = target_script_state->GetIsolate();
- if (&script_state_->World() == &target_script_state->World())
- return value_->NewLocal(isolate);
- DCHECK(isolate->InContext());
- v8::Local<v8::Value> value = value_->NewLocal(isolate);
- scoped_refptr<SerializedScriptValue> serialized =
- SerializedScriptValue::SerializeAndSwallowExceptions(isolate, value);
- return serialized->Deserialize(isolate);
+ return ToWorldSafeValue(target_script_state,
+ value_->NewLocal(target_script_state->GetIsolate()));
}
bool ScriptValue::ToString(String& result) const {
@@ -83,4 +99,14 @@ ScriptValue ScriptValue::CreateNull(ScriptState* script_state) {
return ScriptValue(script_state, v8::Null(script_state->GetIsolate()));
}
+// static
+ScriptValue ScriptValue::ToWorldSafeScriptValue(
+ ScriptState* target_script_state,
+ const TraceWrapperV8Reference<v8::Value>& value) {
+ return ScriptValue(
+ target_script_state,
+ ToWorldSafeValue(target_script_state,
+ value.NewLocal(target_script_state->GetIsolate())));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_value.h b/chromium/third_party/blink/renderer/bindings/core/v8/script_value.h
index 457c56aabff..fda34f5bf06 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_value.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_value.h
@@ -169,6 +169,10 @@ class CORE_EXPORT ScriptValue final {
static ScriptValue CreateNull(ScriptState*);
+ static ScriptValue ToWorldSafeScriptValue(
+ ScriptState* target_script_state,
+ const TraceWrapperV8Reference<v8::Value>& value);
+
private:
// TODO(peria): Move ScriptValue to Oilpan heap.
GC_PLUGIN_IGNORE("813731")
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_marking_visitor_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_marking_visitor_test.cc
index 576c9f6e947..15b9fe13297 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_marking_visitor_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_marking_visitor_test.cc
@@ -30,6 +30,9 @@ class TemporaryScriptWrappableVisitorScope {
v8::Isolate* isolate,
std::unique_ptr<ScriptWrappableMarkingVisitor> controller)
: isolate_(isolate), saved_controller_(std::move(controller)) {
+ // The save and restore logic assumes that V8 is interested in the
+ // wrapper tracing controller.
+ CHECK(!RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled());
SwapWithV8PerIsolateDataVisitor();
}
~TemporaryScriptWrappableVisitorScope() { SwapWithV8PerIsolateDataVisitor(); }
@@ -76,7 +79,7 @@ class InterceptingScriptWrappableMarkingVisitor
void end() {
// Gracefully terminate tracing.
AdvanceTracing(std::numeric_limits<double>::infinity());
- AbortTracing();
+ AbortTracingForTermination();
}
private:
@@ -119,6 +122,11 @@ void PreciselyCollectGarbage() {
TEST(ScriptWrappableMarkingVisitorTest,
ScriptWrappableMarkingVisitorTracesWrappers) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
DeathAwareScriptWrappable* target = DeathAwareScriptWrappable::Create();
@@ -151,25 +159,12 @@ TEST(ScriptWrappableMarkingVisitorTest,
}
TEST(ScriptWrappableMarkingVisitorTest,
- OilpanClearsMarkingDequeWhenObjectDied) {
- V8TestingScope scope;
-
- DeathAwareScriptWrappable* object = DeathAwareScriptWrappable::Create();
- InterceptingScriptWrappableMarkingVisitorScope intercepting_scope(
- scope.GetIsolate());
- ScriptWrappableMarkingVisitor* visitor = intercepting_scope.Visitor();
-
- visitor->TraceWithWrappers(object);
-
- EXPECT_EQ(visitor->MarkingDeque()->front().RawObjectPointer(), object);
-
- PreciselyCollectGarbage();
-
- EXPECT_EQ(visitor->MarkingDeque()->front().RawObjectPointer(), nullptr);
-}
-
-TEST(ScriptWrappableMarkingVisitorTest,
MarkedObjectDoesNothingOnWriteBarrierHitWhenDependencyIsMarkedToo) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
InterceptingScriptWrappableMarkingVisitorScope intercepting_scope(
@@ -197,6 +192,11 @@ TEST(ScriptWrappableMarkingVisitorTest,
TEST(ScriptWrappableMarkingVisitorTest,
MarkedObjectMarksDependencyOnWriteBarrierHitWhenNotMarked) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
InterceptingScriptWrappableMarkingVisitorScope intercepting_scope(
@@ -246,6 +246,11 @@ class HandleContainer
} // namespace
TEST(ScriptWrappableMarkingVisitorTest, WriteBarrierOnUnmarkedContainer) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
InterceptingScriptWrappableMarkingVisitorScope visitor_scope(
scope.GetIsolate());
@@ -264,6 +269,11 @@ TEST(ScriptWrappableMarkingVisitorTest, WriteBarrierOnUnmarkedContainer) {
}
TEST(ScriptWrappableMarkingVisitorTest, WriteBarrierTriggersOnMarkedContainer) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
InterceptingScriptWrappableMarkingVisitorScope visitor_scope(
scope.GetIsolate());
@@ -294,6 +304,12 @@ TEST(ScriptWrappableMarkingVisitorTest, VtableAtObjectStart) {
TEST(ScriptWrappableMarkingVisitor, WriteBarrierForScriptWrappable) {
// Regression test for crbug.com/702490.
+
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
InterceptingScriptWrappableMarkingVisitorScope visitor_scope(
scope.GetIsolate());
@@ -318,6 +334,11 @@ TEST(ScriptWrappableMarkingVisitor, WriteBarrierForScriptWrappable) {
}
TEST(ScriptWrappableMarkingVisitorTest, WriteBarrierOnHeapVectorSwap1) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
HeapVector<DeathAwareScriptWrappable::Wrapper> vector1;
@@ -339,6 +360,11 @@ TEST(ScriptWrappableMarkingVisitorTest, WriteBarrierOnHeapVectorSwap1) {
}
TEST(ScriptWrappableMarkingVisitorTest, WriteBarrierOnHeapVectorSwap2) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
HeapVector<DeathAwareScriptWrappable::Wrapper> vector1;
@@ -411,6 +437,11 @@ class Base : public blink::GarbageCollected<Base>,
} // namespace
TEST(ScriptWrappableMarkingVisitorTest, MixinTracing) {
+ // Test depends on InterceptingScriptWrappableMarkingVisitorScope which is
+ // specialized for wrapper tracing.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
DeathAwareScriptWrappable* base_wrapper = DeathAwareScriptWrappable::Create();
@@ -448,6 +479,11 @@ TEST(ScriptWrappableMarkingVisitorTest, MixinTracing) {
}
TEST(ScriptWrappableMarkingVisitorTest, OilpanClearsHeadersWhenObjectDied) {
+ // This test depends on cleanup callbacks that are only fired when wrapper
+ // tracing is enabled.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
V8TestingScope scope;
DeathAwareScriptWrappable* object = DeathAwareScriptWrappable::Create();
@@ -463,4 +499,27 @@ TEST(ScriptWrappableMarkingVisitorTest, OilpanClearsHeadersWhenObjectDied) {
EXPECT_FALSE(visitor->headers_to_unmark_.Contains(header));
}
+TEST(ScriptWrappableMarkingVisitorTest,
+ OilpanClearsMarkingDequeWhenObjectDied) {
+ // This test depends on cleanup callbacks that are only fired when wrapper
+ // tracing is enabled.
+ if (RuntimeEnabledFeatures::HeapUnifiedGarbageCollectionEnabled())
+ return;
+
+ V8TestingScope scope;
+
+ DeathAwareScriptWrappable* object = DeathAwareScriptWrappable::Create();
+ InterceptingScriptWrappableMarkingVisitorScope intercepting_scope(
+ scope.GetIsolate());
+ ScriptWrappableMarkingVisitor* visitor = intercepting_scope.Visitor();
+
+ visitor->TraceWithWrappers(object);
+
+ EXPECT_EQ(visitor->MarkingDeque()->front().RawObjectPointer(), object);
+
+ PreciselyCollectGarbage();
+
+ EXPECT_EQ(visitor->MarkingDeque()->front().RawObjectPointer(), nullptr);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_v8_gc_integration_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_v8_gc_integration_test.cc
index dc15fa3ab23..47f89204ebe 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_v8_gc_integration_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/script_wrappable_v8_gc_integration_test.cc
@@ -27,10 +27,10 @@ void RunV8MinorGC(v8::Isolate* isolate) {
v8::Isolate::GarbageCollectionType::kMinorGarbageCollection);
}
-void RunV8FullGC(v8::Isolate* isolate) {
+void RunV8FullGCWithoutScanningOilpanStack(v8::Isolate* isolate) {
CHECK(isolate);
- isolate->RequestGarbageCollectionForTesting(
- v8::Isolate::GarbageCollectionType::kFullGarbageCollection);
+ V8GCController::CollectAllGarbageForTesting(
+ isolate, v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
}
} // namespace v8_gc_integration_test
@@ -108,7 +108,7 @@ TEST(ScriptWrappableV8GCIntegrationTest,
}
v8_gc_integration_test::RunV8MinorGC(isolate);
- v8_gc_integration_test::RunV8FullGC(isolate);
+ v8_gc_integration_test::RunV8FullGCWithoutScanningOilpanStack(isolate);
v8_gc_integration_test::PreciselyCollectGarbage();
EXPECT_FALSE(observer.WasCollected());
@@ -131,7 +131,7 @@ TEST(ScriptWrappableV8GCIntegrationTest,
}
v8_gc_integration_test::RunV8MinorGC(isolate);
- v8_gc_integration_test::RunV8FullGC(isolate);
+ v8_gc_integration_test::RunV8FullGCWithoutScanningOilpanStack(isolate);
v8_gc_integration_test::PreciselyCollectGarbage();
EXPECT_TRUE(observer.WasCollected());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc
index 278b2ec8f25..7b3cc33c75b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.cc
@@ -15,12 +15,12 @@ namespace blink {
scoped_refptr<SerializedScriptValue> PostMessageHelper::SerializeMessageByMove(
v8::Isolate* isolate,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
Transferables& transferables,
ExceptionState& exception_state) {
- if (options.hasTransfer() && !options.transfer().IsEmpty()) {
+ if (options->hasTransfer() && !options->transfer().IsEmpty()) {
if (!SerializedScriptValue::ExtractTransferables(
- isolate, options.transfer(), transferables, exception_state)) {
+ isolate, options->transfer(), transferables, exception_state)) {
return nullptr;
}
}
@@ -40,12 +40,12 @@ scoped_refptr<SerializedScriptValue> PostMessageHelper::SerializeMessageByMove(
scoped_refptr<SerializedScriptValue> PostMessageHelper::SerializeMessageByCopy(
v8::Isolate* isolate,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
Transferables& transferables,
ExceptionState& exception_state) {
- if (options.hasTransfer() && !options.transfer().IsEmpty()) {
+ if (options->hasTransfer() && !options->transfer().IsEmpty()) {
if (!SerializedScriptValue::ExtractTransferables(
- isolate, options.transfer(), transferables, exception_state)) {
+ isolate, options->transfer(), transferables, exception_state)) {
return nullptr;
}
}
@@ -87,8 +87,8 @@ scoped_refptr<SerializedScriptValue> PostMessageHelper::SerializeMessageByCopy(
mojom::blink::UserActivationSnapshotPtr
PostMessageHelper::CreateUserActivationSnapshot(
ExecutionContext* execution_context,
- const PostMessageOptions& options) {
- if (!options.includeUserActivation())
+ const PostMessageOptions* options) {
+ if (!options->includeUserActivation())
return nullptr;
if (LocalDOMWindow* dom_window = execution_context->ExecutingWindow()) {
if (LocalFrame* frame = dom_window->GetFrame()) {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.h
index 2c9a498b731..9c521c9d74a 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/post_message_helper.h
@@ -27,14 +27,14 @@ class CORE_EXPORT PostMessageHelper {
static scoped_refptr<SerializedScriptValue> SerializeMessageByMove(
v8::Isolate*,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
Transferables& transferables,
ExceptionState&);
static scoped_refptr<SerializedScriptValue> SerializeMessageByCopy(
v8::Isolate*,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
Transferables& transferables,
ExceptionState&);
@@ -42,7 +42,7 @@ class CORE_EXPORT PostMessageHelper {
// execution context is not a window.
static mojom::blink::UserActivationSnapshotPtr CreateUserActivationSnapshot(
ExecutionContext*,
- const PostMessageOptions&);
+ const PostMessageOptions*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h
index 33d2b21f40d..3cbeb15d057 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialization_tag.h
@@ -67,6 +67,8 @@ enum SerializationTag {
kOffscreenCanvasTransferTag = 'H', // index, width, height, id:uint32_t ->
// OffscreenCanvas. For OffscreenCanvas
// transfer
+ kReadableStreamTransferTag = 'r', // index:uint32_t
+ kWritableStreamTransferTag = 'w', // index:uint32_t
kDOMPointTag = 'Q', // x:Double, y:Double, z:Double, w:Double
kDOMPointReadOnlyTag = 'W', // x:Double, y:Double, z:Double, w:Double
kDOMRectTag = 'E', // x:Double, y:Double, width:Double, height:Double
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.cc
index 34130f067ab..8053c879147 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.cc
@@ -17,6 +17,9 @@ SerializedColorParams::SerializedColorParams(CanvasColorParams color_params) {
case kSRGBCanvasColorSpace:
color_space_ = SerializedColorSpace::kSRGB;
break;
+ case kLinearRGBCanvasColorSpace:
+ color_space_ = SerializedColorSpace::kLinearRGB;
+ break;
case kRec2020CanvasColorSpace:
color_space_ = SerializedColorSpace::kRec2020;
break;
@@ -27,8 +30,6 @@ SerializedColorParams::SerializedColorParams(CanvasColorParams color_params) {
switch (color_params.PixelFormat()) {
case kRGBA8CanvasPixelFormat:
- case kRGB10A2CanvasPixelFormat:
- case kRGBA12CanvasPixelFormat:
pixel_format_ = SerializedPixelFormat::kRGBA8;
break;
case kF16CanvasPixelFormat:
@@ -77,6 +78,9 @@ CanvasColorParams SerializedColorParams::GetCanvasColorParams() const {
case SerializedColorSpace::kSRGB:
color_space = kSRGBCanvasColorSpace;
break;
+ case SerializedColorSpace::kLinearRGB:
+ color_space = kLinearRGBCanvasColorSpace;
+ break;
case SerializedColorSpace::kRec2020:
color_space = kRec2020CanvasColorSpace;
break;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.h
index 8ea8f9ba0a0..3665c191363 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_color_params.h
@@ -41,15 +41,14 @@ enum class SerializedColorSpace : uint32_t {
kSRGB = 1,
kRec2020 = 2,
kP3 = 3,
- kLast = kP3,
+ kLinearRGB = 4,
+ kLast = kLinearRGB,
};
// This enumeration specifies the values used to serialize CanvasPixelFormat.
enum class SerializedPixelFormat : uint32_t {
kRGBA8 = 0,
- kRGB10A2 = 1,
- kRGBA12 = 2,
- kF16 = 3,
+ kF16 = 1,
kLast = kF16,
};
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc
index 037f145ed13..0fbf601bfe2 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.cc
@@ -47,9 +47,14 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_message_port.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mojo_handle.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_offscreen_canvas.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_shared_array_buffer.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream.h"
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h"
#include "third_party/blink/renderer/platform/bindings/dom_data_store.h"
@@ -58,6 +63,7 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/dtoa/utils.h"
@@ -65,6 +71,7 @@
#include "third_party/blink/renderer/platform/wtf/text/string_buffer.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
+#include "third_party/blink/renderer/platform/wtf/wtf_size_t.h"
namespace blink {
@@ -369,6 +376,39 @@ void SerializedScriptValue::TransferOffscreenCanvas(
}
visited.insert(offscreen_canvases[i].Get());
offscreen_canvases[i].Get()->SetNeutered();
+ offscreen_canvases[i].Get()->RecordTransfer();
+ }
+}
+
+void SerializedScriptValue::TransferReadableStreams(
+ ScriptState* script_state,
+ const ReadableStreamArray& readable_streams,
+ ExceptionState& exception_state) {
+ auto* execution_context = ExecutionContext::From(script_state);
+ for (ReadableStream* readable_stream : readable_streams) {
+ mojo::MessagePipe pipe;
+ MessagePort* local_port = MessagePort::Create(*execution_context);
+ local_port->Entangle(std::move(pipe.handle0));
+ readable_stream->Serialize(script_state, local_port, exception_state);
+ if (exception_state.HadException())
+ return;
+ stream_channels_.push_back(MessagePortChannel(std::move(pipe.handle1)));
+ }
+}
+
+void SerializedScriptValue::TransferWritableStreams(
+ ScriptState* script_state,
+ const WritableStreamArray& writable_streams,
+ ExceptionState& exception_state) {
+ auto* execution_context = ExecutionContext::From(script_state);
+ for (WritableStream* writable_stream : writable_streams) {
+ mojo::MessagePipe pipe;
+ MessagePort* local_port = MessagePort::Create(*execution_context);
+ local_port->Entangle(std::move(pipe.handle0));
+ writable_stream->Serialize(script_state, local_port, exception_state);
+ if (exception_state.HadException())
+ return;
+ stream_channels_.push_back(MessagePortChannel(std::move(pipe.handle1)));
}
}
@@ -414,7 +454,7 @@ UnpackedSerializedScriptValue* SerializedScriptValue::Unpack(
DCHECK(!value->was_unpacked_);
value->was_unpacked_ = true;
#endif
- return new UnpackedSerializedScriptValue(std::move(value));
+ return MakeGarbageCollected<UnpackedSerializedScriptValue>(std::move(value));
}
bool SerializedScriptValue::HasPackedContents() const {
@@ -460,7 +500,7 @@ bool SerializedScriptValue::ExtractTransferables(
return false;
}
// Validation of Objects implementing an interface, per WebIDL spec 4.1.15.
- if (V8MessagePort::hasInstance(transferable_object, isolate)) {
+ if (V8MessagePort::HasInstance(transferable_object, isolate)) {
MessagePort* port = V8MessagePort::ToImpl(
v8::Local<v8::Object>::Cast(transferable_object));
// Check for duplicate MessagePorts.
@@ -472,7 +512,7 @@ bool SerializedScriptValue::ExtractTransferables(
return false;
}
transferables.message_ports.push_back(port);
- } else if (V8MojoHandle::hasInstance(transferable_object, isolate)) {
+ } else if (V8MojoHandle::HasInstance(transferable_object, isolate)) {
MojoHandle* handle = V8MojoHandle::ToImpl(
v8::Local<v8::Object>::Cast(transferable_object));
// Check for duplicate MojoHandles.
@@ -506,7 +546,7 @@ bool SerializedScriptValue::ExtractTransferables(
return false;
}
transferables.array_buffers.push_back(shared_array_buffer);
- } else if (V8ImageBitmap::hasInstance(transferable_object, isolate)) {
+ } else if (V8ImageBitmap::HasInstance(transferable_object, isolate)) {
ImageBitmap* image_bitmap = V8ImageBitmap::ToImpl(
v8::Local<v8::Object>::Cast(transferable_object));
if (transferables.image_bitmaps.Contains(image_bitmap)) {
@@ -517,7 +557,7 @@ bool SerializedScriptValue::ExtractTransferables(
return false;
}
transferables.image_bitmaps.push_back(image_bitmap);
- } else if (V8OffscreenCanvas::hasInstance(transferable_object, isolate)) {
+ } else if (V8OffscreenCanvas::HasInstance(transferable_object, isolate)) {
OffscreenCanvas* offscreen_canvas = V8OffscreenCanvas::ToImpl(
v8::Local<v8::Object>::Cast(transferable_object));
if (transferables.offscreen_canvases.Contains(offscreen_canvas)) {
@@ -528,6 +568,30 @@ bool SerializedScriptValue::ExtractTransferables(
return false;
}
transferables.offscreen_canvases.push_back(offscreen_canvas);
+ } else if (RuntimeEnabledFeatures::TransferableStreamsEnabled() &&
+ V8ReadableStream::HasInstance(transferable_object, isolate)) {
+ ReadableStream* stream = V8ReadableStream::ToImpl(
+ v8::Local<v8::Object>::Cast(transferable_object));
+ if (transferables.readable_streams.Contains(stream)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kDataCloneError,
+ "ReadableStream at index " + String::Number(i) +
+ " is a duplicate of an earlier ReadableStream.");
+ return false;
+ }
+ transferables.readable_streams.push_back(stream);
+ } else if (RuntimeEnabledFeatures::TransferableStreamsEnabled() &&
+ V8WritableStream::HasInstance(transferable_object, isolate)) {
+ WritableStream* stream = V8WritableStream::ToImpl(
+ v8::Local<v8::Object>::Cast(transferable_object));
+ if (transferables.writable_streams.Contains(stream)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kDataCloneError,
+ "WritableStream at index " + String::Number(i) +
+ " is a duplicate of an earlier WritableStream.");
+ return false;
+ }
+ transferables.writable_streams.push_back(stream);
} else {
exception_state.ThrowTypeError("Value at index " + String::Number(i) +
" does not have a transferable type.");
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h
index 68ebafe597b..eea425054ed 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h
@@ -35,6 +35,7 @@
#include "base/containers/span.h"
#include "base/optional.h"
+#include "third_party/blink/public/common/messaging/message_port_channel.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/transferables.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -72,6 +73,7 @@ class CORE_EXPORT SerializedScriptValue
using ImageBitmapContentsArray = Vector<scoped_refptr<StaticBitmapImage>, 1>;
using TransferredWasmModulesArray =
WTF::Vector<v8::WasmCompiledModule::TransferrableModule>;
+ using MessagePortChannelArray = Vector<MessagePortChannel>;
// Increment this for each incompatible change to the wire format.
// Version 2: Added StringUCharTag for UChar v8 strings.
@@ -254,6 +256,8 @@ class CORE_EXPORT SerializedScriptValue
}
void SetImageBitmapContentsArray(ImageBitmapContentsArray contents);
+ MessagePortChannelArray& GetStreamChannels() { return stream_channels_; }
+
bool IsLockedToAgentCluster() const {
return !wasm_modules_.IsEmpty() ||
!shared_array_buffers_contents_.IsEmpty();
@@ -288,6 +292,12 @@ class CORE_EXPORT SerializedScriptValue
void TransferOffscreenCanvas(v8::Isolate*,
const OffscreenCanvasArray&,
ExceptionState&);
+ void TransferReadableStreams(ScriptState*,
+ const ReadableStreamArray&,
+ ExceptionState&);
+ void TransferWritableStreams(ScriptState*,
+ const WritableStreamArray&,
+ ExceptionState&);
void CloneSharedArrayBuffers(SharedArrayBufferArray&);
DataBufferPtr data_buffer_;
size_t data_buffer_size_ = 0;
@@ -297,6 +307,10 @@ class CORE_EXPORT SerializedScriptValue
ArrayBufferContentsArray array_buffer_contents_array_;
ImageBitmapContentsArray image_bitmap_contents_array_;
+ // |stream_channels_| is also single-use but is special-cased because it works
+ // with ServiceWorkers.
+ MessagePortChannelArray stream_channels_;
+
// These do not have one-use transferred contents, like the above.
TransferredWasmModulesArray wasm_modules_;
BlobDataHandleMap blob_data_handles_;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_fuzzer.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_fuzzer.cc
index a75067bffdd..adf921cd4cd 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_fuzzer.cc
@@ -69,7 +69,7 @@ int LLVMFuzzerTestOneInput(const uint8_t* data, size_t data_size) {
// If message ports are requested, make some.
if (hash & kFuzzMessagePorts) {
- MessagePortArray* message_ports = new MessagePortArray(3);
+ MessagePortArray* message_ports = MakeGarbageCollected<MessagePortArray>(3);
std::generate(message_ports->begin(), message_ports->end(), []() {
MessagePort* port = MessagePort::Create(g_page_holder->GetDocument());
port->Entangle(mojo::MessagePipe().handle0);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_test.cc
index 2448105b4ac..a9b7cf0f17b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_test.cc
@@ -114,7 +114,7 @@ TEST(SerializedScriptValueTest, WireFormatVersion0ImageData) {
serializedScriptValue->Deserialize(isolate);
ASSERT_TRUE(deserialized->IsObject());
v8::Local<v8::Object> deserializedObject = deserialized.As<v8::Object>();
- ASSERT_TRUE(V8ImageData::hasInstance(deserializedObject, isolate));
+ ASSERT_TRUE(V8ImageData::HasInstance(deserializedObject, isolate));
ImageData* imageData = V8ImageData::ToImpl(deserializedObject);
EXPECT_EQ(imageData->width(), 127);
EXPECT_EQ(imageData->height(), 1);
@@ -140,7 +140,7 @@ TEST(SerializedScriptValueTest, UserSelectedFile) {
v8::Local<v8::Value> v8_file =
serialized_script_value->Deserialize(scope.GetIsolate());
- ASSERT_TRUE(V8File::hasInstance(v8_file, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(v8_file, scope.GetIsolate()));
File* file = V8File::ToImpl(v8::Local<v8::Object>::Cast(v8_file));
EXPECT_TRUE(file->HasBackingFile());
EXPECT_EQ(File::kIsUserVisible, file->GetUserVisibility());
@@ -164,7 +164,7 @@ TEST(SerializedScriptValueTest, FileConstructorFile) {
v8::Local<v8::Value> v8_file =
serialized_script_value->Deserialize(scope.GetIsolate());
- ASSERT_TRUE(V8File::hasInstance(v8_file, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(v8_file, scope.GetIsolate()));
File* file = V8File::ToImpl(v8::Local<v8::Object>::Cast(v8_file));
EXPECT_FALSE(file->HasBackingFile());
EXPECT_EQ(File::kIsNotUserVisible, file->GetUserVisibility());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/transferables.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/transferables.h
index 736199db43a..2408ccf5276 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/transferables.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/transferables.h
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
namespace blink {
@@ -16,12 +17,16 @@ class ImageBitmap;
class OffscreenCanvas;
class MessagePort;
class MojoHandle;
+class ReadableStream;
+class WritableStream;
using ArrayBufferArray = HeapVector<Member<DOMArrayBufferBase>>;
using ImageBitmapArray = HeapVector<Member<ImageBitmap>>;
using OffscreenCanvasArray = HeapVector<Member<OffscreenCanvas>>;
using MessagePortArray = HeapVector<Member<MessagePort>>;
using MojoHandleArray = HeapVector<Member<blink::MojoHandle>>;
+using ReadableStreamArray = HeapVector<Member<ReadableStream>>;
+using WritableStreamArray = HeapVector<Member<WritableStream>>;
class CORE_EXPORT Transferables final {
STACK_ALLOCATED();
@@ -35,6 +40,8 @@ class CORE_EXPORT Transferables final {
OffscreenCanvasArray offscreen_canvases;
MessagePortArray message_ports;
MojoHandleArray mojo_handles;
+ ReadableStreamArray readable_streams;
+ WritableStreamArray writable_streams;
};
// Along with extending |Transferables| to hold a new kind of transferable
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h
index 44f4aceb6f1..6d93d2feac9 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h
@@ -38,6 +38,8 @@ class ImageBitmap;
class CORE_EXPORT UnpackedSerializedScriptValue
: public GarbageCollectedFinalized<UnpackedSerializedScriptValue> {
public:
+ // Callers should use SerializedScriptValue::Unpack.
+ explicit UnpackedSerializedScriptValue(scoped_refptr<SerializedScriptValue>);
~UnpackedSerializedScriptValue();
void Trace(blink::Visitor*);
@@ -58,9 +60,6 @@ class CORE_EXPORT UnpackedSerializedScriptValue
const DeserializeOptions& = DeserializeOptions());
private:
- // Private so that callers use SerializedScriptValue::Unpack.
- explicit UnpackedSerializedScriptValue(scoped_refptr<SerializedScriptValue>);
-
// The underlying serialized data.
scoped_refptr<SerializedScriptValue> value_;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.cc
index 298cc58efdd..bf2da93684b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.cc
@@ -25,8 +25,11 @@
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/mojo/mojo_handle.h"
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
namespace blink {
@@ -168,8 +171,17 @@ v8::Local<v8::Value> V8ScriptValueDeserializer::Deserialize() {
}
void V8ScriptValueDeserializer::Transfer() {
- // Thre's nothing to transfer if the deserializer was not given an unpacked
- // value.
+ if (RuntimeEnabledFeatures::TransferableStreamsEnabled()) {
+ // TODO(ricea): Make ExtendableMessageEvent store an
+ // UnpackedSerializedScriptValue like MessageEvent does, and then this
+ // special case won't be necessary.
+ transferred_stream_ports_ = MessagePort::EntanglePorts(
+ *ExecutionContext::From(script_state_),
+ serialized_script_value_->GetStreamChannels());
+ }
+
+ // There's nothing else to transfer if the deserializer was not given an
+ // unpacked value.
if (!unpacked_value_)
return;
@@ -206,7 +218,8 @@ bool V8ScriptValueDeserializer::ReadUTF8String(String* string) {
}
ScriptWrappable* V8ScriptValueDeserializer::ReadDOMObject(
- SerializationTag tag) {
+ SerializationTag tag,
+ ExceptionState& exception_state) {
switch (tag) {
case kBlobTag: {
if (Version() < 3)
@@ -422,19 +435,21 @@ ScriptWrappable* V8ScriptValueDeserializer::ReadDOMObject(
return ReadDOMRectReadOnly();
}
case kDOMQuadTag: {
- DOMPointInit pointInits[4];
- for (DOMPointInit& init : pointInits) {
+ DOMPointInit* point_inits[4];
+ for (int i = 0; i < 4; ++i) {
+ auto* init = DOMPointInit::Create();
double x = 0, y = 0, z = 0, w = 0;
if (!ReadDouble(&x) || !ReadDouble(&y) || !ReadDouble(&z) ||
!ReadDouble(&w))
return nullptr;
- init.setX(x);
- init.setY(y);
- init.setZ(z);
- init.setW(w);
+ init->setX(x);
+ init->setY(y);
+ init->setZ(z);
+ init->setW(w);
+ point_inits[i] = init;
}
- return DOMQuad::Create(pointInits[0], pointInits[1], pointInits[2],
- pointInits[3]);
+ return DOMQuad::Create(point_inits[0], point_inits[1], point_inits[2],
+ point_inits[3]);
}
case kDOMMatrix2DTag: {
double values[6];
@@ -497,6 +512,30 @@ ScriptWrappable* V8ScriptValueDeserializer::ReadDOMObject(
canvas->SetFrameSinkId(client_id, sink_id);
return canvas;
}
+ case kReadableStreamTransferTag: {
+ if (!RuntimeEnabledFeatures::TransferableStreamsEnabled())
+ return nullptr;
+ uint32_t index = 0;
+ if (!ReadUint32(&index) || !transferred_stream_ports_ ||
+ index >= transferred_stream_ports_->size()) {
+ return nullptr;
+ }
+ return ReadableStream::Deserialize(
+ script_state_, (*transferred_stream_ports_)[index].Get(),
+ exception_state);
+ }
+ case kWritableStreamTransferTag: {
+ if (!RuntimeEnabledFeatures::TransferableStreamsEnabled())
+ return nullptr;
+ uint32_t index = 0;
+ if (!ReadUint32(&index) || !transferred_stream_ports_ ||
+ index >= transferred_stream_ports_->size()) {
+ return nullptr;
+ }
+ return WritableStream::Deserialize(
+ script_state_, (*transferred_stream_ports_)[index].Get(),
+ exception_state);
+ }
default:
break;
}
@@ -599,8 +638,11 @@ v8::MaybeLocal<v8::Object> V8ScriptValueDeserializer::ReadHostObject(
nullptr, nullptr);
ScriptWrappable* wrappable = nullptr;
SerializationTag tag = kVersionTag;
- if (ReadTag(&tag))
- wrappable = ReadDOMObject(tag);
+ if (ReadTag(&tag)) {
+ wrappable = ReadDOMObject(tag, exception_state);
+ if (exception_state.HadException())
+ return v8::MaybeLocal<v8::Object>();
+ }
if (!wrappable) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataCloneError,
"Unable to deserialize cloned data.");
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.h b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.h
index c020791b310..665dcfe18d7 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_deserializer.h
@@ -18,6 +18,7 @@
namespace blink {
class DOMRectReadOnly;
+class ExceptionState;
class File;
class UnpackedSerializedScriptValue;
@@ -46,7 +47,7 @@ class CORE_EXPORT V8ScriptValueDeserializer
v8::Local<v8::Value> Deserialize();
protected:
- virtual ScriptWrappable* ReadDOMObject(SerializationTag);
+ virtual ScriptWrappable* ReadDOMObject(SerializationTag, ExceptionState&);
ScriptState* GetScriptState() const { return script_state_; }
@@ -113,6 +114,8 @@ class CORE_EXPORT V8ScriptValueDeserializer
// Message ports which were transferred in.
const MessagePortArray* transferred_message_ports_ = nullptr;
+ Member<MessagePortArray> transferred_stream_ports_;
+
// Blob info for blobs stored by index.
const WebBlobInfoArray* blob_info_array_ = nullptr;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc
index dd2f4e0c668..c37928dcd5c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer.cc
@@ -22,8 +22,10 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_message_port.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mojo_handle.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_offscreen_canvas.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_shared_array_buffer.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix_read_only.h"
#include "third_party/blink/renderer/core/geometry/dom_point.h"
@@ -33,8 +35,11 @@
#include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h"
#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/core/mojo/mojo_handle.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_base.h"
#include "third_party/blink/renderer/platform/file_metadata.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
@@ -163,6 +168,17 @@ void V8ScriptValueSerializer::FinalizeTransfer(
isolate, transferables_->offscreen_canvases, exception_state);
if (exception_state.HadException())
return;
+
+ if (RuntimeEnabledFeatures::TransferableStreamsEnabled()) {
+ serialized_script_value_->TransferReadableStreams(
+ script_state_, transferables_->readable_streams, exception_state);
+ if (exception_state.HadException())
+ return;
+ serialized_script_value_->TransferWritableStreams(
+ script_state_, transferables_->writable_streams, exception_state);
+ if (exception_state.HadException())
+ return;
+ }
}
}
@@ -177,7 +193,7 @@ void V8ScriptValueSerializer::WriteUTF8String(const String& string) {
bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
ExceptionState& exception_state) {
const WrapperTypeInfo* wrapper_type_info = wrappable->GetWrapperTypeInfo();
- if (wrapper_type_info == &V8Blob::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8Blob::wrapper_type_info) {
Blob* blob = wrappable->ToImpl<Blob>();
serialized_script_value_->BlobDataHandles().Set(blob->Uuid(),
blob->GetBlobDataHandle());
@@ -196,11 +212,11 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
}
return true;
}
- if (wrapper_type_info == &V8File::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8File::wrapper_type_info) {
WriteTag(blob_info_array_ ? kFileIndexTag : kFileTag);
return WriteFile(wrappable->ToImpl<File>(), exception_state);
}
- if (wrapper_type_info == &V8FileList::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8FileList::wrapper_type_info) {
// This does not presently deduplicate a File object and its entry in a
// FileList, which is non-standard behavior.
FileList* file_list = wrappable->ToImpl<FileList>();
@@ -213,7 +229,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
}
return true;
}
- if (wrapper_type_info == &V8ImageBitmap::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8ImageBitmap::wrapper_type_info) {
ImageBitmap* image_bitmap = wrappable->ToImpl<ImageBitmap>();
if (image_bitmap->IsNeutered()) {
exception_state.ThrowDOMException(
@@ -254,7 +270,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteRawBytes(pixels->Data(), pixels->length());
return true;
}
- if (wrapper_type_info == &V8ImageData::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8ImageData::wrapper_type_info) {
ImageData* image_data = wrappable->ToImpl<ImageData>();
WriteTag(kImageDataTag);
SerializedColorParams color_params(image_data->GetCanvasColorParams(),
@@ -273,7 +289,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteRawBytes(pixel_buffer->Data(), pixel_buffer_length);
return true;
}
- if (wrapper_type_info == &V8DOMPoint::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMPoint::wrapper_type_info) {
DOMPoint* point = wrappable->ToImpl<DOMPoint>();
WriteTag(kDOMPointTag);
WriteDouble(point->x());
@@ -282,7 +298,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteDouble(point->w());
return true;
}
- if (wrapper_type_info == &V8DOMPointReadOnly::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMPointReadOnly::wrapper_type_info) {
DOMPointReadOnly* point = wrappable->ToImpl<DOMPointReadOnly>();
WriteTag(kDOMPointReadOnlyTag);
WriteDouble(point->x());
@@ -291,7 +307,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteDouble(point->w());
return true;
}
- if (wrapper_type_info == &V8DOMRect::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMRect::wrapper_type_info) {
DOMRect* rect = wrappable->ToImpl<DOMRect>();
WriteTag(kDOMRectTag);
WriteDouble(rect->x());
@@ -300,7 +316,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteDouble(rect->height());
return true;
}
- if (wrapper_type_info == &V8DOMRectReadOnly::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMRectReadOnly::wrapper_type_info) {
DOMRectReadOnly* rect = wrappable->ToImpl<DOMRectReadOnly>();
WriteTag(kDOMRectReadOnlyTag);
WriteDouble(rect->x());
@@ -309,7 +325,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteDouble(rect->height());
return true;
}
- if (wrapper_type_info == &V8DOMQuad::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMQuad::wrapper_type_info) {
DOMQuad* quad = wrappable->ToImpl<DOMQuad>();
WriteTag(kDOMQuadTag);
for (const DOMPoint* point :
@@ -321,7 +337,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
}
return true;
}
- if (wrapper_type_info == &V8DOMMatrix::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMMatrix::wrapper_type_info) {
DOMMatrix* matrix = wrappable->ToImpl<DOMMatrix>();
if (matrix->is2D()) {
WriteTag(kDOMMatrix2DTag);
@@ -352,7 +368,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
}
return true;
}
- if (wrapper_type_info == &V8DOMMatrixReadOnly::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMMatrixReadOnly::wrapper_type_info) {
DOMMatrixReadOnly* matrix = wrappable->ToImpl<DOMMatrixReadOnly>();
if (matrix->is2D()) {
WriteTag(kDOMMatrix2DReadOnlyTag);
@@ -383,7 +399,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
}
return true;
}
- if (wrapper_type_info == &V8MessagePort::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8MessagePort::wrapper_type_info) {
MessagePort* message_port = wrappable->ToImpl<MessagePort>();
size_t index = kNotFound;
if (transferables_)
@@ -399,7 +415,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteUint32(static_cast<uint32_t>(index));
return true;
}
- if (wrapper_type_info == &V8MojoHandle::wrapperTypeInfo &&
+ if (wrapper_type_info == &V8MojoHandle::wrapper_type_info &&
RuntimeEnabledFeatures::MojoJSEnabled()) {
MojoHandle* mojo_handle = wrappable->ToImpl<MojoHandle>();
size_t index = kNotFound;
@@ -419,7 +435,7 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteUint32(static_cast<uint32_t>(index));
return true;
}
- if (wrapper_type_info == &V8OffscreenCanvas::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8OffscreenCanvas::wrapper_type_info) {
OffscreenCanvas* canvas = wrappable->ToImpl<OffscreenCanvas>();
size_t index = kNotFound;
if (transferables_)
@@ -452,6 +468,59 @@ bool V8ScriptValueSerializer::WriteDOMObject(ScriptWrappable* wrappable,
WriteUint32(canvas->SinkId());
return true;
}
+ if (wrapper_type_info == &V8ReadableStream::wrapper_type_info &&
+ RuntimeEnabledFeatures::TransferableStreamsEnabled()) {
+ ReadableStream* stream = wrappable->ToImpl<ReadableStream>();
+ size_t index = kNotFound;
+ if (transferables_)
+ index = transferables_->readable_streams.Find(stream);
+ if (index == kNotFound) {
+ exception_state.ThrowDOMException(DOMExceptionCode::kDataCloneError,
+ "A ReadableStream could not be cloned "
+ "because it was not transferred.");
+ return false;
+ }
+ if (stream->IsLocked(script_state_, exception_state).value_or(true)) {
+ if (exception_state.HadException())
+ return false;
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kDataCloneError,
+ "A ReadableStream could not be cloned because it was locked");
+ return false;
+ }
+ WriteTag(kReadableStreamTransferTag);
+ WriteUint32(static_cast<uint32_t>(index));
+ return true;
+ }
+ if (wrapper_type_info == &V8WritableStream::wrapper_type_info &&
+ RuntimeEnabledFeatures::TransferableStreamsEnabled()) {
+ WritableStream* stream = wrappable->ToImpl<WritableStream>();
+ size_t index = kNotFound;
+ if (transferables_)
+ index = transferables_->writable_streams.Find(stream);
+ if (index == kNotFound) {
+ exception_state.ThrowDOMException(DOMExceptionCode::kDataCloneError,
+ "A WritableStream could not be cloned "
+ "because it was not transferred.");
+ return false;
+ }
+ if (stream->IsLocked(script_state_, exception_state).value_or(true)) {
+ if (exception_state.HadException())
+ return false;
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kDataCloneError,
+ "A WritableStream could not be cloned because it was locked");
+ return false;
+ }
+ WriteTag(kWritableStreamTransferTag);
+ DCHECK(transferables_);
+ // The index calculation depends on the order that TransferReadableStreams
+ // and TransferWritableStreams are called in
+ // V8ScriptValueSerializer::FinalizeTransfer.
+ WriteUint32(
+ static_cast<uint32_t>(index + transferables_->readable_streams.size()));
+ return true;
+ }
return false;
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc
index 8e3f54805d5..861eb3a1dce 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/serialization/v8_script_value_serializer_test.cc
@@ -30,6 +30,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_message_port.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mojo_handle.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_offscreen_canvas.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_string_resource.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/fileapi/file.h"
@@ -46,6 +47,7 @@
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/mojo/mojo_handle.h"
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/file_metadata.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
@@ -106,7 +108,8 @@ v8::Local<v8::Value> RoundTrip(
v8::Local<v8::Value> Eval(const String& source, V8TestingScope& scope) {
return scope.GetFrame()
.GetScriptController()
- .ExecuteScriptInMainWorldAndReturnValue(source, KURL(), kOpaqueResource);
+ .ExecuteScriptInMainWorldAndReturnValue(source, KURL(),
+ SanitizeScriptErrors::kSanitize);
}
String ToJSON(v8::Local<v8::Object> object, const V8TestingScope& scope) {
@@ -237,7 +240,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripDOMPoint) {
v8::Local<v8::Value> wrapper =
ToV8(point, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMPoint::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMPoint::HasInstance(result, scope.GetIsolate()));
DOMPoint* new_point = V8DOMPoint::ToImpl(result.As<v8::Object>());
EXPECT_NE(point, new_point);
EXPECT_EQ(point->x(), new_point->x());
@@ -256,7 +259,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMPoint) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMPoint::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMPoint::HasInstance(result, scope.GetIsolate()));
DOMPoint* point = V8DOMPoint::ToImpl(result.As<v8::Object>());
EXPECT_EQ(1, point->x());
EXPECT_EQ(2, point->y());
@@ -271,8 +274,8 @@ TEST(V8ScriptValueSerializerTest, RoundTripDOMPointReadOnly) {
v8::Local<v8::Value> wrapper =
ToV8(point, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMPointReadOnly::hasInstance(result, scope.GetIsolate()));
- EXPECT_FALSE(V8DOMPoint::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMPointReadOnly::HasInstance(result, scope.GetIsolate()));
+ EXPECT_FALSE(V8DOMPoint::HasInstance(result, scope.GetIsolate()));
DOMPointReadOnly* new_point =
V8DOMPointReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_NE(point, new_point);
@@ -292,7 +295,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMPointReadOnly) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMPointReadOnly::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMPointReadOnly::HasInstance(result, scope.GetIsolate()));
DOMPointReadOnly* point = V8DOMPointReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_EQ(1, point->x());
EXPECT_EQ(2, point->y());
@@ -307,7 +310,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripDOMRect) {
v8::Local<v8::Value> wrapper =
ToV8(rect, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMRect::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMRect::HasInstance(result, scope.GetIsolate()));
DOMRect* new_rect = V8DOMRect::ToImpl(result.As<v8::Object>());
EXPECT_NE(rect, new_rect);
EXPECT_EQ(rect->x(), new_rect->x());
@@ -326,7 +329,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMRect) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMRect::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMRect::HasInstance(result, scope.GetIsolate()));
DOMRect* rect = V8DOMRect::ToImpl(result.As<v8::Object>());
EXPECT_EQ(1, rect->x());
EXPECT_EQ(2, rect->y());
@@ -341,8 +344,8 @@ TEST(V8ScriptValueSerializerTest, RoundTripDOMRectReadOnly) {
v8::Local<v8::Value> wrapper =
ToV8(rect, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMRectReadOnly::hasInstance(result, scope.GetIsolate()));
- EXPECT_FALSE(V8DOMRect::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMRectReadOnly::HasInstance(result, scope.GetIsolate()));
+ EXPECT_FALSE(V8DOMRect::HasInstance(result, scope.GetIsolate()));
DOMRectReadOnly* new_rect =
V8DOMRectReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_NE(rect, new_rect);
@@ -362,7 +365,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMRectReadOnly) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMRectReadOnly::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMRectReadOnly::HasInstance(result, scope.GetIsolate()));
DOMRectReadOnly* rect = V8DOMRectReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_EQ(1, rect->x());
EXPECT_EQ(2, rect->y());
@@ -373,31 +376,31 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMRectReadOnly) {
TEST(V8ScriptValueSerializerTest, RoundTripDOMQuad) {
// DOMQuad objects should serialize and deserialize correctly.
V8TestingScope scope;
- DOMPointInit pi1;
- pi1.setX(1);
- pi1.setY(5);
- pi1.setZ(9);
- pi1.setW(13);
- DOMPointInit pi2;
- pi2.setX(2);
- pi2.setY(6);
- pi2.setZ(10);
- pi2.setW(14);
- DOMPointInit pi3;
- pi3.setX(3);
- pi3.setY(7);
- pi3.setZ(11);
- pi3.setW(15);
- DOMPointInit pi4;
- pi4.setX(4);
- pi4.setY(8);
- pi4.setZ(12);
- pi4.setW(16);
+ DOMPointInit* pi1 = DOMPointInit::Create();
+ pi1->setX(1);
+ pi1->setY(5);
+ pi1->setZ(9);
+ pi1->setW(13);
+ DOMPointInit* pi2 = DOMPointInit::Create();
+ pi2->setX(2);
+ pi2->setY(6);
+ pi2->setZ(10);
+ pi2->setW(14);
+ DOMPointInit* pi3 = DOMPointInit::Create();
+ pi3->setX(3);
+ pi3->setY(7);
+ pi3->setZ(11);
+ pi3->setW(15);
+ DOMPointInit* pi4 = DOMPointInit::Create();
+ pi4->setX(4);
+ pi4->setY(8);
+ pi4->setZ(12);
+ pi4->setW(16);
DOMQuad* quad = DOMQuad::Create(pi1, pi2, pi3, pi4);
v8::Local<v8::Value> wrapper =
ToV8(quad, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMQuad::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMQuad::HasInstance(result, scope.GetIsolate()));
DOMQuad* new_quad = V8DOMQuad::ToImpl(result.As<v8::Object>());
EXPECT_NE(quad, new_quad);
EXPECT_NE(quad->p1(), new_quad->p1());
@@ -440,7 +443,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMQuad) {
0x30, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMQuad::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMQuad::HasInstance(result, scope.GetIsolate()));
DOMQuad* quad = V8DOMQuad::ToImpl(result.As<v8::Object>());
EXPECT_EQ(1, quad->p1()->x());
EXPECT_EQ(5, quad->p1()->y());
@@ -463,20 +466,20 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMQuad) {
TEST(V8ScriptValueSerializerTest, RoundTripDOMMatrix2D) {
// DOMMatrix objects should serialize and deserialize correctly.
V8TestingScope scope;
- DOMMatrixInit init;
- init.setIs2D(true);
- init.setA(1.0);
- init.setB(2.0);
- init.setC(3.0);
- init.setD(4.0);
- init.setE(5.0);
- init.setF(6.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setIs2D(true);
+ init->setA(1.0);
+ init->setB(2.0);
+ init->setC(3.0);
+ init->setD(4.0);
+ init->setE(5.0);
+ init->setF(6.0);
DOMMatrix* matrix = DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(matrix->is2D());
v8::Local<v8::Value> wrapper =
ToV8(matrix, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMMatrix::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrix::HasInstance(result, scope.GetIsolate()));
DOMMatrix* new_matrix = V8DOMMatrix::ToImpl(result.As<v8::Object>());
EXPECT_NE(matrix, new_matrix);
EXPECT_TRUE(new_matrix->is2D());
@@ -504,7 +507,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrix2D) {
});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMMatrix::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrix::HasInstance(result, scope.GetIsolate()));
DOMMatrix* matrix = V8DOMMatrix::ToImpl(result.As<v8::Object>());
EXPECT_TRUE(matrix->is2D());
EXPECT_EQ(1.0, matrix->a());
@@ -518,22 +521,22 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrix2D) {
TEST(V8ScriptValueSerializerTest, RoundTripDOMMatrixReadOnly2D) {
// DOMMatrix objects should serialize and deserialize correctly.
V8TestingScope scope;
- DOMMatrixInit init;
- init.setIs2D(true);
- init.setA(1.0);
- init.setB(2.0);
- init.setC(3.0);
- init.setD(4.0);
- init.setE(5.0);
- init.setF(6.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setIs2D(true);
+ init->setA(1.0);
+ init->setB(2.0);
+ init->setC(3.0);
+ init->setD(4.0);
+ init->setE(5.0);
+ init->setF(6.0);
DOMMatrixReadOnly* matrix =
DOMMatrixReadOnly::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(matrix->is2D());
v8::Local<v8::Value> wrapper =
ToV8(matrix, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMMatrixReadOnly::hasInstance(result, scope.GetIsolate()));
- EXPECT_FALSE(V8DOMMatrix::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrixReadOnly::HasInstance(result, scope.GetIsolate()));
+ EXPECT_FALSE(V8DOMMatrix::HasInstance(result, scope.GetIsolate()));
DOMMatrixReadOnly* new_matrix =
V8DOMMatrixReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_NE(matrix, new_matrix);
@@ -562,7 +565,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrixReadOnly2D) {
});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMMatrixReadOnly::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrixReadOnly::HasInstance(result, scope.GetIsolate()));
DOMMatrixReadOnly* matrix =
V8DOMMatrixReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_TRUE(matrix->is2D());
@@ -577,30 +580,30 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrixReadOnly2D) {
TEST(V8ScriptValueSerializerTest, RoundTripDOMMatrix) {
// DOMMatrix objects should serialize and deserialize correctly.
V8TestingScope scope;
- DOMMatrixInit init;
- init.setIs2D(false);
- init.setM11(1.1);
- init.setM12(1.2);
- init.setM13(1.3);
- init.setM14(1.4);
- init.setM21(2.1);
- init.setM22(2.2);
- init.setM23(2.3);
- init.setM24(2.4);
- init.setM31(3.1);
- init.setM32(3.2);
- init.setM33(3.3);
- init.setM34(3.4);
- init.setM41(4.1);
- init.setM42(4.2);
- init.setM43(4.3);
- init.setM44(4.4);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setIs2D(false);
+ init->setM11(1.1);
+ init->setM12(1.2);
+ init->setM13(1.3);
+ init->setM14(1.4);
+ init->setM21(2.1);
+ init->setM22(2.2);
+ init->setM23(2.3);
+ init->setM24(2.4);
+ init->setM31(3.1);
+ init->setM32(3.2);
+ init->setM33(3.3);
+ init->setM34(3.4);
+ init->setM41(4.1);
+ init->setM42(4.2);
+ init->setM43(4.3);
+ init->setM44(4.4);
DOMMatrix* matrix = DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_FALSE(matrix->is2D());
v8::Local<v8::Value> wrapper =
ToV8(matrix, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMMatrix::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrix::HasInstance(result, scope.GetIsolate()));
DOMMatrix* new_matrix = V8DOMMatrix::ToImpl(result.As<v8::Object>());
EXPECT_NE(matrix, new_matrix);
EXPECT_FALSE(new_matrix->is2D());
@@ -641,7 +644,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrix) {
});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMMatrix::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrix::HasInstance(result, scope.GetIsolate()));
DOMMatrix* matrix = V8DOMMatrix::ToImpl(result.As<v8::Object>());
EXPECT_FALSE(matrix->is2D());
EXPECT_EQ(1.1, matrix->m11());
@@ -665,32 +668,32 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrix) {
TEST(V8ScriptValueSerializerTest, RoundTripDOMMatrixReadOnly) {
// DOMMatrixReadOnly objects should serialize and deserialize correctly.
V8TestingScope scope;
- DOMMatrixInit init;
- init.setIs2D(false);
- init.setM11(1.1);
- init.setM12(1.2);
- init.setM13(1.3);
- init.setM14(1.4);
- init.setM21(2.1);
- init.setM22(2.2);
- init.setM23(2.3);
- init.setM24(2.4);
- init.setM31(3.1);
- init.setM32(3.2);
- init.setM33(3.3);
- init.setM34(3.4);
- init.setM41(4.1);
- init.setM42(4.2);
- init.setM43(4.3);
- init.setM44(4.4);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setIs2D(false);
+ init->setM11(1.1);
+ init->setM12(1.2);
+ init->setM13(1.3);
+ init->setM14(1.4);
+ init->setM21(2.1);
+ init->setM22(2.2);
+ init->setM23(2.3);
+ init->setM24(2.4);
+ init->setM31(3.1);
+ init->setM32(3.2);
+ init->setM33(3.3);
+ init->setM34(3.4);
+ init->setM41(4.1);
+ init->setM42(4.2);
+ init->setM43(4.3);
+ init->setM44(4.4);
DOMMatrixReadOnly* matrix =
DOMMatrixReadOnly::fromMatrix(init, scope.GetExceptionState());
EXPECT_FALSE(matrix->is2D());
v8::Local<v8::Value> wrapper =
ToV8(matrix, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8DOMMatrixReadOnly::hasInstance(result, scope.GetIsolate()));
- EXPECT_FALSE(V8DOMMatrix::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrixReadOnly::HasInstance(result, scope.GetIsolate()));
+ EXPECT_FALSE(V8DOMMatrix::HasInstance(result, scope.GetIsolate()));
DOMMatrixReadOnly* new_matrix =
V8DOMMatrixReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_NE(matrix, new_matrix);
@@ -733,7 +736,7 @@ TEST(V8ScriptValueSerializerTest, DecodeDOMMatrixReadOnly) {
});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMMatrixReadOnly::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMMatrixReadOnly::HasInstance(result, scope.GetIsolate()));
DOMMatrixReadOnly* matrix =
V8DOMMatrixReadOnly::ToImpl(result.As<v8::Object>());
EXPECT_FALSE(matrix->is2D());
@@ -763,7 +766,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripImageData) {
v8::Local<v8::Value> wrapper =
ToV8(image_data, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8ImageData::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageData::HasInstance(result, scope.GetIsolate()));
ImageData* new_image_data = V8ImageData::ToImpl(result.As<v8::Object>());
EXPECT_NE(image_data, new_image_data);
EXPECT_EQ(image_data->Size(), new_image_data->Size());
@@ -775,23 +778,23 @@ TEST(V8ScriptValueSerializerTest, RoundTripImageDataWithColorSpaceInfo) {
// ImageData objects with color space information should serialize and
// deserialize correctly.
V8TestingScope scope;
- ImageDataColorSettings color_settings;
- color_settings.setColorSpace("p3");
- color_settings.setStorageFormat("float32");
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
+ color_settings->setColorSpace("p3");
+ color_settings->setStorageFormat("float32");
ImageData* image_data =
ImageData::CreateImageData(2, 1, color_settings, ASSERT_NO_EXCEPTION);
static_cast<unsigned char*>(image_data->BufferBase()->Data())[0] = 200;
v8::Local<v8::Value> wrapper =
ToV8(image_data, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8ImageData::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageData::HasInstance(result, scope.GetIsolate()));
ImageData* new_image_data = V8ImageData::ToImpl(result.As<v8::Object>());
EXPECT_NE(image_data, new_image_data);
EXPECT_EQ(image_data->Size(), new_image_data->Size());
- ImageDataColorSettings new_color_settings;
- new_image_data->getColorSettings(new_color_settings);
- EXPECT_EQ("p3", new_color_settings.colorSpace());
- EXPECT_EQ("float32", new_color_settings.storageFormat());
+ ImageDataColorSettings* new_color_settings =
+ new_image_data->getColorSettings();
+ EXPECT_EQ("p3", new_color_settings->colorSpace());
+ EXPECT_EQ("float32", new_color_settings->storageFormat());
EXPECT_EQ(image_data->BufferBase()->ByteLength(),
new_image_data->BufferBase()->ByteLength());
EXPECT_EQ(200, static_cast<unsigned char*>(
@@ -809,7 +812,7 @@ TEST(V8ScriptValueSerializerTest, DecodeImageDataV9) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8ImageData::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageData::HasInstance(result, scope.GetIsolate()));
ImageData* new_image_data = V8ImageData::ToImpl(result.As<v8::Object>());
EXPECT_EQ(IntSize(2, 1), new_image_data->Size());
EXPECT_EQ(8u, new_image_data->data()->length());
@@ -824,7 +827,7 @@ TEST(V8ScriptValueSerializerTest, DecodeImageDataV16) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8ImageData::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageData::HasInstance(result, scope.GetIsolate()));
ImageData* new_image_data = V8ImageData::ToImpl(result.As<v8::Object>());
EXPECT_EQ(IntSize(2, 1), new_image_data->Size());
EXPECT_EQ(8u, new_image_data->data()->length());
@@ -841,13 +844,13 @@ TEST(V8ScriptValueSerializerTest, DecodeImageDataV18) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8ImageData::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageData::HasInstance(result, scope.GetIsolate()));
ImageData* new_image_data = V8ImageData::ToImpl(result.As<v8::Object>());
EXPECT_EQ(IntSize(2, 1), new_image_data->Size());
- ImageDataColorSettings new_color_settings;
- new_image_data->getColorSettings(new_color_settings);
- EXPECT_EQ("p3", new_color_settings.colorSpace());
- EXPECT_EQ("float32", new_color_settings.storageFormat());
+ ImageDataColorSettings* new_color_settings =
+ new_image_data->getColorSettings();
+ EXPECT_EQ("p3", new_color_settings->colorSpace());
+ EXPECT_EQ("float32", new_color_settings->storageFormat());
EXPECT_EQ(32u, new_image_data->BufferBase()->ByteLength());
EXPECT_EQ(200, static_cast<unsigned char*>(
new_image_data->BufferBase()->Data())[0]);
@@ -878,7 +881,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripMessagePort) {
v8::Local<v8::Value> result =
RoundTrip(wrapper, scope, nullptr, &transferables);
- ASSERT_TRUE(V8MessagePort::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8MessagePort::HasInstance(result, scope.GetIsolate()));
MessagePort* new_port = V8MessagePort::ToImpl(result.As<v8::Object>());
EXPECT_FALSE(port->IsEntangled());
EXPECT_TRUE(new_port->IsEntangled());
@@ -931,25 +934,25 @@ TEST(V8ScriptValueSerializerTest, OutOfRangeMessagePortIndex) {
}
{
V8ScriptValueDeserializer::Options options;
- options.message_ports = new MessagePortArray;
+ options.message_ports = MakeGarbageCollected<MessagePortArray>();
V8ScriptValueDeserializer deserializer(script_state, input, options);
ASSERT_TRUE(deserializer.Deserialize()->IsNull());
}
{
V8ScriptValueDeserializer::Options options;
- options.message_ports = new MessagePortArray;
+ options.message_ports = MakeGarbageCollected<MessagePortArray>();
options.message_ports->push_back(port1);
V8ScriptValueDeserializer deserializer(script_state, input, options);
ASSERT_TRUE(deserializer.Deserialize()->IsNull());
}
{
V8ScriptValueDeserializer::Options options;
- options.message_ports = new MessagePortArray;
+ options.message_ports = MakeGarbageCollected<MessagePortArray>();
options.message_ports->push_back(port1);
options.message_ports->push_back(port2);
V8ScriptValueDeserializer deserializer(script_state, input, options);
v8::Local<v8::Value> result = deserializer.Deserialize();
- ASSERT_TRUE(V8MessagePort::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8MessagePort::HasInstance(result, scope.GetIsolate()));
EXPECT_EQ(port2, V8MessagePort::ToImpl(result.As<v8::Object>()));
}
}
@@ -966,7 +969,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripMojoHandle) {
v8::Local<v8::Value> result =
RoundTrip(wrapper, scope, nullptr, &transferables);
- ASSERT_TRUE(V8MojoHandle::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8MojoHandle::HasInstance(result, scope.GetIsolate()));
MojoHandle* new_handle = V8MojoHandle::ToImpl(result.As<v8::Object>());
EXPECT_FALSE(handle->TakeHandle().is_valid());
EXPECT_TRUE(new_handle->TakeHandle().is_valid());
@@ -992,7 +995,7 @@ TEST(V8ScriptValueSerializerTest, UntransferredMojoHandleThrowsDataCloneError) {
// Decode tests for backward compatibility are not required for message ports
// and Mojo handles because they cannot be persisted to disk.
-// A more exhaustive set of ImageBitmap cases are covered by LayoutTests.
+// A more exhaustive set of ImageBitmap cases are covered by web tests.
TEST(V8ScriptValueSerializerTest, RoundTripImageBitmap) {
V8TestingScope scope;
@@ -1006,7 +1009,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripImageBitmap) {
// Serialize and deserialize it.
v8::Local<v8::Value> wrapper = ToV8(image_bitmap, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8ImageBitmap::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageBitmap::HasInstance(result, scope.GetIsolate()));
ImageBitmap* new_image_bitmap =
V8ImageBitmap::ToImpl(result.As<v8::Object>());
ASSERT_TRUE(new_image_bitmap->BitmapImage());
@@ -1039,7 +1042,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripImageBitmapWithColorSpaceInfo) {
// Serialize and deserialize it.
v8::Local<v8::Value> wrapper = ToV8(image_bitmap, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8ImageBitmap::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageBitmap::HasInstance(result, scope.GetIsolate()));
ImageBitmap* new_image_bitmap =
V8ImageBitmap::ToImpl(result.As<v8::Object>());
ASSERT_TRUE(new_image_bitmap->BitmapImage());
@@ -1095,7 +1098,7 @@ TEST(V8ScriptValueSerializerTest, DecodeImageBitmap) {
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8ImageBitmap::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageBitmap::HasInstance(result, scope.GetIsolate()));
ImageBitmap* new_image_bitmap =
V8ImageBitmap::ToImpl(result.As<v8::Object>());
ASSERT_EQ(IntSize(2, 1), new_image_bitmap->Size());
@@ -1115,13 +1118,13 @@ TEST(V8ScriptValueSerializerTest, DecodeImageBitmapV18) {
V8TestingScope scope;
ScriptState* script_state = scope.GetScriptState();
scoped_refptr<SerializedScriptValue> input = SerializedValue(
- {0xff, 0x12, 0xff, 0x0d, 0x5c, 0x67, 0x01, 0x03, 0x02, 0x03, 0x04, 0x01,
+ {0xff, 0x12, 0xff, 0x0d, 0x5c, 0x67, 0x01, 0x03, 0x02, 0x01, 0x04, 0x01,
0x05, 0x01, 0x00, 0x02, 0x01, 0x10, 0x94, 0x3a, 0x3f, 0x28, 0x5f, 0x24,
0x00, 0x3c, 0x94, 0x3a, 0x3f, 0x28, 0x5f, 0x24, 0x00, 0x3c});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(script_state, input).Deserialize();
- ASSERT_TRUE(V8ImageBitmap::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageBitmap::HasInstance(result, scope.GetIsolate()));
ImageBitmap* new_image_bitmap =
V8ImageBitmap::ToImpl(result.As<v8::Object>());
ASSERT_EQ(IntSize(2, 1), new_image_bitmap->Size());
@@ -1210,7 +1213,7 @@ TEST(V8ScriptValueSerializerTest, InvalidImageBitmapDecodeV18) {
{
// Nonsense for color space data.
scoped_refptr<SerializedScriptValue> input = SerializedValue(
- {0xff, 0x12, 0xff, 0x0d, 0x5c, 0x67, 0x01, 0x04, 0x02, 0x03, 0x04, 0x01,
+ {0xff, 0x12, 0xff, 0x0d, 0x5c, 0x67, 0x01, 0x05, 0x02, 0x03, 0x04, 0x01,
0x05, 0x01, 0x00, 0x02, 0x01, 0x10, 0x94, 0x3a, 0x3f, 0x28, 0x5f, 0x24,
0x00, 0x3c, 0x94, 0x3a, 0x3f, 0x28, 0x5f, 0x24, 0x00, 0x3c});
EXPECT_TRUE(
@@ -1255,7 +1258,7 @@ TEST(V8ScriptValueSerializerTest, InvalidImageBitmapDecodeV18) {
}
TEST(V8ScriptValueSerializerTest, TransferImageBitmap) {
- // More thorough tests exist in LayoutTests/.
+ // More thorough tests exist in web_tests/.
V8TestingScope scope;
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(10, 7);
@@ -1270,7 +1273,7 @@ TEST(V8ScriptValueSerializerTest, TransferImageBitmap) {
transferables.image_bitmaps.push_back(image_bitmap);
v8::Local<v8::Value> result =
RoundTrip(wrapper, scope, nullptr, &transferables);
- ASSERT_TRUE(V8ImageBitmap::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8ImageBitmap::HasInstance(result, scope.GetIsolate()));
ImageBitmap* new_image_bitmap =
V8ImageBitmap::ToImpl(result.As<v8::Object>());
ASSERT_TRUE(new_image_bitmap->BitmapImage());
@@ -1291,7 +1294,7 @@ TEST(V8ScriptValueSerializerTest, TransferImageBitmap) {
}
TEST(V8ScriptValueSerializerTest, TransferOffscreenCanvas) {
- // More exhaustive tests in LayoutTests/. This is a sanity check.
+ // More exhaustive tests in web_tests/. This is a sanity check.
V8TestingScope scope;
OffscreenCanvas* canvas = OffscreenCanvas::Create(10, 7);
canvas->SetPlaceholderCanvasId(519);
@@ -1300,7 +1303,7 @@ TEST(V8ScriptValueSerializerTest, TransferOffscreenCanvas) {
transferables.offscreen_canvases.push_back(canvas);
v8::Local<v8::Value> result =
RoundTrip(wrapper, scope, nullptr, &transferables);
- ASSERT_TRUE(V8OffscreenCanvas::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8OffscreenCanvas::HasInstance(result, scope.GetIsolate()));
OffscreenCanvas* new_canvas =
V8OffscreenCanvas::ToImpl(result.As<v8::Object>());
EXPECT_EQ(IntSize(10, 7), new_canvas->Size());
@@ -1319,7 +1322,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripBlob) {
EXPECT_FALSE(uuid.IsEmpty());
v8::Local<v8::Value> wrapper = ToV8(blob, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8Blob::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8Blob::HasInstance(result, scope.GetIsolate()));
Blob* new_blob = V8Blob::ToImpl(result.As<v8::Object>());
EXPECT_EQ("text/plain", new_blob->type());
EXPECT_EQ(sizeof(kHelloWorld), new_blob->size());
@@ -1336,7 +1339,7 @@ TEST(V8ScriptValueSerializerTest, DecodeBlob) {
0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x0c});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8Blob::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8Blob::HasInstance(result, scope.GetIsolate()));
Blob* new_blob = V8Blob::ToImpl(result.As<v8::Object>());
EXPECT_EQ("d875dfc2-4505-461b-98fe-0cf6cc5eaf44", new_blob->Uuid());
EXPECT_EQ("text/plain", new_blob->type());
@@ -1357,7 +1360,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripBlobIndex) {
RoundTrip(wrapper, scope, nullptr, nullptr, &blob_info_array);
// As before, the resulting blob should be correct.
- ASSERT_TRUE(V8Blob::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8Blob::HasInstance(result, scope.GetIsolate()));
Blob* new_blob = V8Blob::ToImpl(result.As<v8::Object>());
EXPECT_EQ("text/plain", new_blob->type());
EXPECT_EQ(sizeof(kHelloWorld), new_blob->size());
@@ -1385,7 +1388,7 @@ TEST(V8ScriptValueSerializerTest, DecodeBlobIndex) {
V8ScriptValueDeserializer deserializer(scope.GetScriptState(), input,
options);
v8::Local<v8::Value> result = deserializer.Deserialize();
- ASSERT_TRUE(V8Blob::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8Blob::HasInstance(result, scope.GetIsolate()));
Blob* new_blob = V8Blob::ToImpl(result.As<v8::Object>());
EXPECT_EQ("d875dfc2-4505-461b-98fe-0cf6cc5eaf44", new_blob->Uuid());
EXPECT_EQ("text/plain", new_blob->type());
@@ -1417,7 +1420,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileNative) {
File* file = File::Create("/native/path");
v8::Local<v8::Value> wrapper = ToV8(file, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_TRUE(new_file->HasBackingFile());
EXPECT_EQ("/native/path", new_file->GetPath());
@@ -1432,7 +1435,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileBackedByBlob) {
File::Create("/native/path", kModificationTime, blob_data_handle);
v8::Local<v8::Value> wrapper = ToV8(file, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_FALSE(new_file->HasBackingFile());
EXPECT_TRUE(file->GetPath().IsEmpty());
@@ -1447,7 +1450,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileNativeSnapshot) {
File::CreateForFileSystemFile("name", metadata, File::kIsUserVisible);
v8::Local<v8::Value> wrapper = ToV8(file, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_TRUE(new_file->HasBackingFile());
EXPECT_EQ("/native/snapshot", new_file->GetPath());
@@ -1462,7 +1465,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileNonNativeSnapshot) {
File::CreateForFileSystemFile(url, FileMetadata(), File::kIsUserVisible);
v8::Local<v8::Value> wrapper = ToV8(file, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_FALSE(new_file->HasBackingFile());
EXPECT_TRUE(file->GetPath().IsEmpty());
@@ -1494,7 +1497,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileV3) {
't', 'e', 'x', 't', '/', 'p', 'l', 'a', 'i', 'n'});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_EQ("path", new_file->GetPath());
EXPECT_EQ("f4a6edd5-65ad-4dc3-b67c-a779c02f0fa3", new_file->Uuid());
@@ -1517,7 +1520,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileV4) {
't', '/', 'p', 'l', 'a', 'i', 'n', 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_EQ("path", new_file->GetPath());
EXPECT_EQ("name", new_file->name());
@@ -1542,7 +1545,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileV4WithSnapshot) {
0x00, 0x00, 0x00, 0x00, 0xd0, 0xbf});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_EQ("path", new_file->GetPath());
EXPECT_EQ("name", new_file->name());
@@ -1568,7 +1571,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileV7) {
't', '/', 'p', 'l', 'a', 'i', 'n', 0x00, 0x00, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_EQ("path", new_file->GetPath());
EXPECT_EQ("name", new_file->name());
@@ -1593,7 +1596,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileV8WithSnapshot) {
0x00, 0x00, 0x00, 0x00, 0xd0, 0xbf, 0x01, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_EQ("path", new_file->GetPath());
EXPECT_EQ("name", new_file->name());
@@ -1617,7 +1620,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileIndex) {
RoundTrip(wrapper, scope, nullptr, nullptr, &blob_info_array);
// As above, the resulting blob should be correct.
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_TRUE(new_file->HasBackingFile());
EXPECT_EQ("/native/path", new_file->GetPath());
@@ -1645,7 +1648,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileIndex) {
V8ScriptValueDeserializer deserializer(scope.GetScriptState(), input,
options);
v8::Local<v8::Value> result = deserializer.Deserialize();
- ASSERT_TRUE(V8File::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8File::HasInstance(result, scope.GetIsolate()));
File* new_file = V8File::ToImpl(result.As<v8::Object>());
EXPECT_EQ("d875dfc2-4505-461b-98fe-0cf6cc5eaf44", new_file->Uuid());
EXPECT_EQ("text/plain", new_file->type());
@@ -1684,7 +1687,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileList) {
file_list->Append(File::Create("/native/path2"));
v8::Local<v8::Value> wrapper = ToV8(file_list, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTrip(wrapper, scope);
- ASSERT_TRUE(V8FileList::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8FileList::HasInstance(result, scope.GetIsolate()));
FileList* new_file_list = V8FileList::ToImpl(result.As<v8::Object>());
ASSERT_EQ(2u, new_file_list->length());
EXPECT_EQ("/native/path", new_file_list->item(0)->GetPath());
@@ -1697,7 +1700,7 @@ TEST(V8ScriptValueSerializerTest, DecodeEmptyFileList) {
SerializedValue({0xff, 0x09, 0x3f, 0x00, 0x6c, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8FileList::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8FileList::HasInstance(result, scope.GetIsolate()));
FileList* new_file_list = V8FileList::ToImpl(result.As<v8::Object>());
EXPECT_EQ(0u, new_file_list->length());
}
@@ -1723,7 +1726,7 @@ TEST(V8ScriptValueSerializerTest, DecodeFileListV8WithoutSnapshot) {
'x', 't', '/', 'p', 'l', 'a', 'i', 'n', 0x00, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializer(scope.GetScriptState(), input).Deserialize();
- ASSERT_TRUE(V8FileList::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8FileList::HasInstance(result, scope.GetIsolate()));
FileList* new_file_list = V8FileList::ToImpl(result.As<v8::Object>());
EXPECT_EQ(1u, new_file_list->length());
File* new_file = new_file_list->item(0);
@@ -1749,7 +1752,7 @@ TEST(V8ScriptValueSerializerTest, RoundTripFileListIndex) {
RoundTrip(wrapper, scope, nullptr, nullptr, &blob_info_array);
// FileList should be produced correctly.
- ASSERT_TRUE(V8FileList::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8FileList::HasInstance(result, scope.GetIsolate()));
FileList* new_file_list = V8FileList::ToImpl(result.As<v8::Object>());
ASSERT_EQ(2u, new_file_list->length());
EXPECT_EQ("/native/path", new_file_list->item(0)->GetPath());
@@ -1773,7 +1776,7 @@ TEST(V8ScriptValueSerializerTest, DecodeEmptyFileListIndex) {
V8ScriptValueDeserializer deserializer(scope.GetScriptState(), input,
options);
v8::Local<v8::Value> result = deserializer.Deserialize();
- ASSERT_TRUE(V8FileList::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8FileList::HasInstance(result, scope.GetIsolate()));
FileList* new_file_list = V8FileList::ToImpl(result.As<v8::Object>());
EXPECT_EQ(0u, new_file_list->length());
}
@@ -1839,5 +1842,31 @@ TEST(V8ScriptValueSerializerTest, DecodeWithInefficientVersionEnvelope) {
->IsTrue());
}
+// Sanity check for transferring ReadableStreams. This is mostly tested via
+// layout tests.
+TEST(V8ScriptValueSerializerTest, RoundTripReadableStream) {
+ ScopedTransferableStreamsForTest enable_transferable_streams(true);
+
+ V8TestingScope scope;
+ auto* isolate = scope.GetIsolate();
+ auto* script_state = scope.GetScriptState();
+
+ auto* rs = ReadableStream::Create(script_state, ASSERT_NO_EXCEPTION);
+ v8::Local<v8::Value> wrapper = ToV8(rs, script_state);
+ Vector<ScriptValue> transferable_array = {ScriptValue(script_state, wrapper)};
+ Transferables transferables;
+ ASSERT_TRUE(SerializedScriptValue::ExtractTransferables(
+ isolate, transferable_array, transferables, ASSERT_NO_EXCEPTION));
+ v8::Local<v8::Value> result =
+ RoundTrip(wrapper, scope, &ASSERT_NO_EXCEPTION, &transferables);
+ EXPECT_TRUE(result->IsObject());
+ ASSERT_TRUE(V8ReadableStream::HasInstance(result, isolate));
+ ReadableStream* transferred =
+ V8ReadableStream::ToImpl(result.As<v8::Object>());
+ EXPECT_NE(rs, transferred);
+ EXPECT_TRUE(rs->locked(script_state, ASSERT_NO_EXCEPTION));
+ EXPECT_FALSE(transferred->locked(script_state, ASSERT_NO_EXCEPTION));
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.cc b/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.cc
index fb79c05e781..51ba025d2a3 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.cc
@@ -44,7 +44,7 @@ v8::Local<v8::Value> ToV8(EventTarget* impl,
if (UNLIKELY(!impl))
return v8::Null(isolate);
- if (impl->InterfaceName() == EventTargetNames::DOMWindow)
+ if (impl->InterfaceName() == event_target_names::kWindow)
return ToV8(static_cast<DOMWindow*>(impl), creation_context, isolate);
return ToV8(static_cast<ScriptWrappable*>(impl), creation_context, isolate);
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h b/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h
index fa43f5a75ae..85869b91ad4 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h
@@ -50,10 +50,12 @@ inline v8::Local<v8::Value> ToV8(NotShared<T> value,
// Dictionary
-inline v8::Local<v8::Value> ToV8(const IDLDictionaryBase& value,
+inline v8::Local<v8::Value> ToV8(const IDLDictionaryBase* value,
v8::Local<v8::Object> creation_context,
v8::Isolate* isolate) {
- return value.ToV8Impl(creation_context, isolate);
+ if (!value)
+ return v8::Null(isolate);
+ return value->ToV8Impl(creation_context, isolate);
}
// ScriptValue
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc
index 022abeb976f..1c3037bdaac 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/to_v8_test.cc
@@ -67,7 +67,7 @@ class OffHeapGarbageCollectedHolder {
TEST(ToV8Test, garbageCollectedScriptWrappable) {
V8TestingScope scope;
GarbageCollectedScriptWrappable* object =
- new GarbageCollectedScriptWrappable("world");
+ MakeGarbageCollected<GarbageCollectedScriptWrappable>("world");
GarbageCollectedHolderForToV8Test holder(object);
OffHeapGarbageCollectedHolder off_heap_holder(object);
@@ -231,10 +231,10 @@ TEST(ToV8Test, pairHeapVector) {
V8TestingScope scope;
HeapVector<std::pair<String, Member<GarbageCollectedScriptWrappable>>>
pair_heap_vector;
- pair_heap_vector.push_back(
- std::make_pair("one", new GarbageCollectedScriptWrappable("foo")));
- pair_heap_vector.push_back(
- std::make_pair("two", new GarbageCollectedScriptWrappable("bar")));
+ pair_heap_vector.push_back(std::make_pair(
+ "one", MakeGarbageCollected<GarbageCollectedScriptWrappable>("foo")));
+ pair_heap_vector.push_back(std::make_pair(
+ "two", MakeGarbageCollected<GarbageCollectedScriptWrappable>("bar")));
TEST_TOV8("[object Object]", pair_heap_vector);
v8::Local<v8::Context> context = scope.GetScriptState()->GetContext();
v8::Local<v8::Object> result =
@@ -287,8 +287,8 @@ TEST(ToV8Test, stringVectorVector) {
TEST(ToV8Test, heapVector) {
V8TestingScope scope;
HeapVector<Member<GarbageCollectedScriptWrappable>> v;
- v.push_back(new GarbageCollectedScriptWrappable("hoge"));
- v.push_back(new GarbageCollectedScriptWrappable("fuga"));
+ v.push_back(MakeGarbageCollected<GarbageCollectedScriptWrappable>("hoge"));
+ v.push_back(MakeGarbageCollected<GarbageCollectedScriptWrappable>("fuga"));
v.push_back(nullptr);
TEST_TOV8("hoge,fuga,", v);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/use_counter_callback.cc b/chromium/third_party/blink/renderer/bindings/core/v8/use_counter_callback.cc
index e615bd3bbb9..1a433797400 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/use_counter_callback.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/use_counter_callback.cc
@@ -163,6 +163,60 @@ void UseCounterCallback(v8::Isolate* isolate,
case v8::Isolate::kAtomicsWake:
blink_feature = WebFeature::kV8AtomicsWake;
break;
+ case v8::Isolate::kCollator:
+ blink_feature = WebFeature::kCollator;
+ break;
+ case v8::Isolate::kNumberFormat:
+ blink_feature = WebFeature::kNumberFormat;
+ break;
+ case v8::Isolate::kDateTimeFormat:
+ blink_feature = WebFeature::kDateTimeFormat;
+ break;
+ case v8::Isolate::kPluralRules:
+ blink_feature = WebFeature::kPluralRules;
+ break;
+ case v8::Isolate::kRelativeTimeFormat:
+ blink_feature = WebFeature::kRelativeTimeFormat;
+ break;
+ case v8::Isolate::kLocale:
+ blink_feature = WebFeature::kLocale;
+ break;
+ case v8::Isolate::kListFormat:
+ blink_feature = WebFeature::kListFormat;
+ break;
+ case v8::Isolate::kSegmenter:
+ blink_feature = WebFeature::kSegmenter;
+ break;
+ case v8::Isolate::kStringLocaleCompare:
+ blink_feature = WebFeature::kStringLocaleCompare;
+ break;
+ case v8::Isolate::kStringToLocaleUpperCase:
+ blink_feature = WebFeature::kStringToLocaleUpperCase;
+ break;
+ case v8::Isolate::kStringToLocaleLowerCase:
+ blink_feature = WebFeature::kStringToLocaleLowerCase;
+ break;
+ case v8::Isolate::kNumberToLocaleString:
+ blink_feature = WebFeature::kNumberToLocaleString;
+ break;
+ case v8::Isolate::kDateToLocaleString:
+ blink_feature = WebFeature::kDateToLocaleString;
+ break;
+ case v8::Isolate::kDateToLocaleDateString:
+ blink_feature = WebFeature::kDateToLocaleDateString;
+ break;
+ case v8::Isolate::kDateToLocaleTimeString:
+ blink_feature = WebFeature::kDateToLocaleTimeString;
+ break;
+ case v8::Isolate::kAttemptOverrideReadOnlyOnPrototypeSloppy:
+ blink_feature = WebFeature::kV8AttemptOverrideReadOnlyOnPrototypeSloppy;
+ break;
+ case v8::Isolate::kAttemptOverrideReadOnlyOnPrototypeStrict:
+ blink_feature = WebFeature::kV8AttemptOverrideReadOnlyOnPrototypeStrict;
+ break;
+ case v8::Isolate::kOptimizedFunctionWithOneShotBytecode:
+ blink_feature = WebFeature::kV8OptimizedFunctionWithOneShotBytecode;
+ break;
default:
// This can happen if V8 has added counters that this version of Blink
// does not know about. It's harmless.
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.cc
index f61db2f9edf..6b9272e13bf 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.cc
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h"
-#include "third_party/blink/renderer/bindings/core/v8/string_or_dictionary.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_element_creation_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_document.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_html_element.h"
@@ -57,7 +57,7 @@ static void ConstructCustomElement(const v8::FunctionCallbackInfo<v8::Value>&);
V0CustomElementConstructorBuilder::V0CustomElementConstructorBuilder(
ScriptState* script_state,
- const ElementRegistrationOptions& options)
+ const ElementRegistrationOptions* options)
: script_state_(script_state), options_(options) {
DCHECK(script_state_->GetContext() ==
script_state_->GetIsolate()->GetCurrentContext());
@@ -84,31 +84,34 @@ bool V0CustomElementConstructorBuilder::ValidateOptions(
return false;
}
- if (options_.hasPrototype()) {
- DCHECK(options_.prototype().IsObject());
- prototype_ = options_.prototype().V8Value().As<v8::Object>();
+ if (options_->hasPrototype()) {
+ DCHECK(options_->prototype().IsObject());
+ prototype_ = options_->prototype().V8Value().As<v8::Object>();
} else {
prototype_ = v8::Object::New(script_state_->GetIsolate());
v8::Local<v8::Object> base_prototype =
script_state_->PerContextData()->PrototypeForType(
- &V8HTMLElement::wrapperTypeInfo);
+ &V8HTMLElement::wrapper_type_info);
if (!base_prototype.IsEmpty()) {
- if (!V8CallBoolean(prototype_->SetPrototype(script_state_->GetContext(),
- base_prototype)))
+ bool set_prototype;
+ if (!prototype_->SetPrototype(script_state_->GetContext(), base_prototype)
+ .To(&set_prototype) ||
+ !set_prototype) {
return false;
+ }
}
}
- AtomicString namespace_uri = HTMLNames::xhtmlNamespaceURI;
- if (HasValidPrototypeChainFor(&V8SVGElement::wrapperTypeInfo))
- namespace_uri = SVGNames::svgNamespaceURI;
+ AtomicString namespace_uri = html_names::xhtmlNamespaceURI;
+ if (HasValidPrototypeChainFor(&V8SVGElement::wrapper_type_info))
+ namespace_uri = svg_names::kNamespaceURI;
DCHECK(!try_catch.HasCaught());
AtomicString local_name;
- if (options_.hasExtends()) {
- local_name = AtomicString(options_.extends().DeprecatedLower());
+ if (options_->hasExtends()) {
+ local_name = AtomicString(options_->extends().DeprecatedLower());
if (!Document::IsValidName(local_name)) {
V0CustomElementException::ThrowException(
@@ -125,7 +128,7 @@ bool V0CustomElementConstructorBuilder::ValidateOptions(
return false;
}
} else {
- if (namespace_uri == SVGNames::svgNamespaceURI) {
+ if (namespace_uri == svg_names::kNamespaceURI) {
V0CustomElementException::ThrowException(
V0CustomElementException::kExtendsIsInvalidName, type,
exception_state);
@@ -216,38 +219,63 @@ bool V0CustomElementConstructorBuilder::CreateConstructor(
: v8_type.As<v8::String>());
v8::Local<v8::String> prototype_key = V8AtomicString(isolate, "prototype");
- if (!V8CallBoolean(constructor_->HasOwnProperty(context, prototype_key)))
+ bool has_own_property;
+ if (!constructor_->HasOwnProperty(context, prototype_key)
+ .To(&has_own_property) ||
+ !has_own_property) {
return false;
+ }
+
// This sets the property *value*; calling Set is safe because
// "prototype" is a non-configurable data property so there can be
// no side effects.
- if (!V8CallBoolean(constructor_->Set(context, prototype_key, prototype_)))
+ bool set_prototype_key;
+ if (!constructor_->Set(context, prototype_key, prototype_)
+ .To(&set_prototype_key) ||
+ !set_prototype_key) {
return false;
+ }
+
// This *configures* the property. DefineOwnProperty of a function's
// "prototype" does not affect the value, but can reconfigure the
// property.
- if (!V8CallBoolean(constructor_->DefineOwnProperty(
- context, prototype_key, prototype_,
- v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum | v8::DontDelete))))
+ bool configured_prototype;
+ if (!constructor_
+ ->DefineOwnProperty(
+ context, prototype_key, prototype_,
+ v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum |
+ v8::DontDelete))
+ .To(&configured_prototype) ||
+ !configured_prototype) {
return false;
+ }
v8::Local<v8::String> constructor_key =
V8AtomicString(isolate, "constructor");
v8::Local<v8::Value> constructor_prototype;
if (!prototype_->Get(context, constructor_key)
- .ToLocal(&constructor_prototype))
+ .ToLocal(&constructor_prototype)) {
return false;
+ }
- if (!V8CallBoolean(
- constructor_->SetPrototype(context, constructor_prototype)))
+ bool set_prototype;
+ if (!constructor_->SetPrototype(context, constructor_prototype)
+ .To(&set_prototype) ||
+ !set_prototype) {
return false;
+ }
V8PrivateProperty::GetCustomElementIsInterfacePrototypeObject(isolate).Set(
prototype_, v8::True(isolate));
- if (!V8CallBoolean(prototype_->DefineOwnProperty(
- context, V8AtomicString(isolate, "constructor"), constructor_,
- v8::DontEnum)))
+
+ bool configured_constructor;
+ if (!prototype_
+ ->DefineOwnProperty(context, constructor_key, constructor_,
+ v8::DontEnum)
+ .To(&configured_constructor) ||
+ !configured_constructor) {
return false;
+ }
return true;
}
@@ -356,14 +384,13 @@ static void ConstructCustomElement(
maybe_type->IsUndefined()) {
return;
}
- TOSTRING_VOID(V8StringResource<>, type, maybe_type);
+ TOSTRING_VOID(V8StringResource<kTreatNullAsNullString>, type, maybe_type);
ExceptionState exception_state(isolate, ExceptionState::kConstructionContext,
"CustomElement");
V0CustomElementProcessingStack::CallbackDeliveryScope delivery_scope;
Element* element = document->createElementNS(
- namespace_uri, tag_name,
- StringOrDictionary::FromString(maybe_type->IsNull() ? g_null_atom : type),
+ namespace_uri, tag_name, StringOrElementCreationOptions::FromString(type),
exception_state);
if (element) {
UseCounter::Count(document, WebFeature::kV0CustomElementsConstruct);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h b/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h
index 116661e2809..2bc90ce414f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h
@@ -58,7 +58,7 @@ class V0CustomElementConstructorBuilder {
public:
V0CustomElementConstructorBuilder(ScriptState*,
- const ElementRegistrationOptions&);
+ const ElementRegistrationOptions*);
// The builder accumulates state and may run script at specific
// points. These methods must be called in order. When one fails
@@ -85,7 +85,7 @@ class V0CustomElementConstructorBuilder {
v8::MaybeLocal<v8::Function> RetrieveCallback(const char* name);
Member<ScriptState> script_state_;
- const ElementRegistrationOptions& options_;
+ Member<const ElementRegistrationOptions> options_;
v8::Local<v8::Object> prototype_;
v8::Local<v8::Function> constructor_;
Member<V8V0CustomElementLifecycleCallbacks> callbacks_;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc
index 5833fe9690b..e2df2fbb1a2 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_element.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_event_target.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_html_link_element.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_window.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_worker_global_scope.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_worklet_global_scope.h"
@@ -74,15 +75,18 @@
namespace blink {
-bool ToBooleanSlow(v8::Isolate* isolate,
- v8::Local<v8::Value> value,
- ExceptionState& exception_state) {
- DCHECK(!value->IsBoolean());
- v8::TryCatch block(isolate);
- bool result = false;
- if (!value->BooleanValue(isolate->GetCurrentContext()).To(&result))
- exception_state.RethrowV8Exception(block.Exception());
- return result;
+void V8SetReturnValue(const v8::PropertyCallbackInfo<v8::Value>& info,
+ const v8::PropertyDescriptor& descriptor) {
+ DCHECK(descriptor.has_configurable());
+ DCHECK(descriptor.has_enumerable());
+ DCHECK(descriptor.has_value());
+ DCHECK(descriptor.has_writable());
+ info.GetReturnValue().Set(V8ObjectBuilder(ScriptState::ForCurrentRealm(info))
+ .Add("configurable", descriptor.configurable())
+ .Add("enumerable", descriptor.enumerable())
+ .Add("value", descriptor.value())
+ .Add("writable", descriptor.writable())
+ .V8Value());
}
const int32_t kMaxInt32 = 0x7fffffff;
@@ -603,7 +607,7 @@ String ReplaceUnmatchedSurrogates(const String& string) {
XPathNSResolver* ToXPathNSResolver(ScriptState* script_state,
v8::Local<v8::Value> value) {
XPathNSResolver* resolver = nullptr;
- if (V8XPathNSResolver::hasInstance(value, script_state->GetIsolate())) {
+ if (V8XPathNSResolver::HasInstance(value, script_state->GetIsolate())) {
resolver = V8XPathNSResolver::ToImpl(v8::Local<v8::Object>::Cast(value));
} else if (value->IsObject()) {
resolver =
@@ -616,7 +620,7 @@ DOMWindow* ToDOMWindow(v8::Isolate* isolate, v8::Local<v8::Value> value) {
if (value.IsEmpty() || !value->IsObject())
return nullptr;
- v8::Local<v8::Object> window_wrapper = V8Window::findInstanceInPrototypeChain(
+ v8::Local<v8::Object> window_wrapper = V8Window::FindInstanceInPrototypeChain(
v8::Local<v8::Object>::Cast(value), isolate);
if (!window_wrapper.IsEmpty())
return V8Window::ToImpl(window_wrapper);
@@ -656,11 +660,11 @@ ExecutionContext* ToExecutionContext(v8::Local<v8::Context> context) {
return nullptr;
const WrapperTypeInfo* wrapper_type_info = ToWrapperTypeInfo(global_proxy);
- if (wrapper_type_info->Equals(&V8Window::wrapperTypeInfo))
+ if (wrapper_type_info->Equals(&V8Window::wrapper_type_info))
return V8Window::ToImpl(global_proxy)->GetExecutionContext();
- if (wrapper_type_info->IsSubclass(&V8WorkerGlobalScope::wrapperTypeInfo))
+ if (wrapper_type_info->IsSubclass(&V8WorkerGlobalScope::wrapper_type_info))
return V8WorkerGlobalScope::ToImpl(global_proxy)->GetExecutionContext();
- if (wrapper_type_info->IsSubclass(&V8WorkletGlobalScope::wrapperTypeInfo))
+ if (wrapper_type_info->IsSubclass(&V8WorkletGlobalScope::wrapper_type_info))
return V8WorkletGlobalScope::ToImpl(global_proxy)->GetExecutionContext();
NOTREACHED();
@@ -740,6 +744,18 @@ v8::Local<v8::Context> ToV8ContextEvenIfDetached(LocalFrame* frame,
return frame->WindowProxy(world)->ContextIfInitialized();
}
+ScriptState* ToScriptState(ExecutionContext* context, DOMWrapperWorld& world) {
+ DCHECK(context);
+ if (auto* document = DynamicTo<Document>(context)) {
+ if (LocalFrame* frame = document->GetFrame())
+ return ToScriptState(frame, world);
+ } else if (auto* scope = DynamicTo<WorkerOrWorkletGlobalScope>(context)) {
+ if (WorkerOrWorkletScriptController* script = scope->ScriptController())
+ return script->GetScriptState();
+ }
+ return nullptr;
+}
+
ScriptState* ToScriptState(LocalFrame* frame, DOMWrapperWorld& world) {
v8::HandleScope handle_scope(ToIsolate(frame));
return ToScriptStateImpl(frame, world);
@@ -856,13 +872,23 @@ bool HasCallableIteratorSymbol(v8::Isolate* isolate,
return iterator_getter->IsFunction();
}
-v8::Isolate* ToIsolate(ExecutionContext* context) {
+v8::Isolate* ToIsolate(const ExecutionContext* context) {
+ if (!context)
+ return nullptr;
+
+#if DCHECK_IS_ON()
+ v8::Isolate* isolate;
if (context && context->IsDocument())
- return V8PerIsolateData::MainThreadIsolate();
- return v8::Isolate::GetCurrent();
+ isolate = V8PerIsolateData::MainThreadIsolate();
+ else
+ isolate = v8::Isolate::GetCurrent();
+ DCHECK(context->GetIsolate() == isolate);
+#endif
+
+ return context->GetIsolate();
}
-v8::Isolate* ToIsolate(LocalFrame* frame) {
+v8::Isolate* ToIsolate(const LocalFrame* frame) {
DCHECK(frame);
return frame->GetWindowProxyManager()->GetIsolate();
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h b/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h
index a3f90daa95c..8fcde3226b4 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h
@@ -180,35 +180,8 @@ inline void V8SetReturnValueFast(const CallbackInfo& callbackInfo,
// Specialized overload, used by interface indexed property handlers in their
// descriptor callbacks, which need an actual V8 Object with the properties of
// a property descriptor.
-template <typename CallbackInfo>
-inline void V8SetReturnValue(const CallbackInfo& callback_info,
- const v8::PropertyDescriptor& descriptor) {
- DCHECK(descriptor.has_configurable());
- DCHECK(descriptor.has_enumerable());
- DCHECK(descriptor.has_value());
- DCHECK(descriptor.has_writable());
- v8::Local<v8::Object> desc = v8::Object::New(callback_info.GetIsolate());
- desc->Set(callback_info.GetIsolate()->GetCurrentContext(),
- V8AtomicString(callback_info.GetIsolate(), "configurable"),
- ToV8(descriptor.configurable(), callback_info.Holder(),
- callback_info.GetIsolate()))
- .ToChecked();
- desc->Set(callback_info.GetIsolate()->GetCurrentContext(),
- V8AtomicString(callback_info.GetIsolate(), "enumerable"),
- ToV8(descriptor.enumerable(), callback_info.Holder(),
- callback_info.GetIsolate()))
- .ToChecked();
- desc->Set(callback_info.GetIsolate()->GetCurrentContext(),
- V8AtomicString(callback_info.GetIsolate(), "value"),
- descriptor.value())
- .ToChecked();
- desc->Set(callback_info.GetIsolate()->GetCurrentContext(),
- V8AtomicString(callback_info.GetIsolate(), "writable"),
- ToV8(descriptor.writable(), callback_info.Holder(),
- callback_info.GetIsolate()))
- .ToChecked();
- callback_info.GetReturnValue().Set(desc);
-}
+CORE_EXPORT void V8SetReturnValue(const v8::PropertyCallbackInfo<v8::Value>&,
+ const v8::PropertyDescriptor&);
// Conversion flags, used in toIntXX/toUIntXX.
enum IntegerConversionConfiguration {
@@ -218,15 +191,12 @@ enum IntegerConversionConfiguration {
};
// Convert a value to a boolean.
-CORE_EXPORT bool ToBooleanSlow(v8::Isolate*,
- v8::Local<v8::Value>,
- ExceptionState&);
inline bool ToBoolean(v8::Isolate* isolate,
v8::Local<v8::Value> value,
ExceptionState& exception_state) {
if (LIKELY(value->IsBoolean()))
return value.As<v8::Boolean>()->Value();
- return ToBooleanSlow(isolate, value, exception_state);
+ return value->BooleanValue(isolate);
}
// Convert a value to a 8-bit signed integer. The conversion fails if the
@@ -466,8 +436,8 @@ CORE_EXPORT bool HasCallableIteratorSymbol(v8::Isolate*,
v8::Local<v8::Value>,
ExceptionState&);
-CORE_EXPORT v8::Isolate* ToIsolate(ExecutionContext*);
-CORE_EXPORT v8::Isolate* ToIsolate(LocalFrame*);
+CORE_EXPORT v8::Isolate* ToIsolate(const ExecutionContext*);
+CORE_EXPORT v8::Isolate* ToIsolate(const LocalFrame*);
CORE_EXPORT DOMWindow* ToDOMWindow(v8::Isolate*, v8::Local<v8::Value>);
CORE_EXPORT LocalDOMWindow* ToLocalDOMWindow(v8::Local<v8::Context>);
@@ -493,6 +463,7 @@ CORE_EXPORT v8::Local<v8::Context> ToV8ContextEvenIfDetached(LocalFrame*,
// These methods can return nullptr if the context associated with the
// ScriptState has already been detached.
+CORE_EXPORT ScriptState* ToScriptState(ExecutionContext*, DOMWrapperWorld&);
CORE_EXPORT ScriptState* ToScriptState(LocalFrame*, DOMWrapperWorld&);
// Do not use this method unless you are sure you should use the main world's
// ScriptState
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc
index 727c3ee45e1..9faae3cef3f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc
@@ -223,12 +223,12 @@ void V8CodeCache::ProduceCache(
TRACE_EVENT_END1(
kTraceEventCategoryGroup, "v8.compile", "data",
- InspectorCompileScriptEvent::Data(
+ inspector_compile_script_event::Data(
source.Url().GetString(), source.StartPosition(),
- InspectorCompileScriptEvent::V8CacheResult(
- InspectorCompileScriptEvent::V8CacheResult::ProduceResult(
+ inspector_compile_script_event::V8CacheResult(
+ inspector_compile_script_event::V8CacheResult::ProduceResult(
compile_options, cached_data ? cached_data->length : 0),
- base::Optional<InspectorCompileScriptEvent::V8CacheResult::
+ base::Optional<inspector_compile_script_event::V8CacheResult::
ConsumeResult>()),
source.Streamer(), source.NotStreamingReason()));
break;
@@ -311,25 +311,26 @@ scoped_refptr<CachedMetadata> V8CodeCache::GenerateFullCodeCache(
TRACE_EVENT_END1(
kTraceEventCategoryGroup, "v8.compile", "data",
- InspectorCompileScriptEvent::Data(
+ inspector_compile_script_event::Data(
file_name, TextPosition(),
- InspectorCompileScriptEvent::V8CacheResult(
- InspectorCompileScriptEvent::V8CacheResult::ProduceResult(
+ inspector_compile_script_event::V8CacheResult(
+ inspector_compile_script_event::V8CacheResult::ProduceResult(
v8::ScriptCompiler::kEagerCompile,
cached_data ? cached_data->length : 0),
- base::Optional<
- InspectorCompileScriptEvent::V8CacheResult::ConsumeResult>()),
+ base::Optional<inspector_compile_script_event::V8CacheResult::
+ ConsumeResult>()),
false, ScriptStreamer::kHasCodeCache));
return cached_metadata;
}
-STATIC_ASSERT_ENUM(WebSettings::kV8CacheOptionsDefault, kV8CacheOptionsDefault);
-STATIC_ASSERT_ENUM(WebSettings::kV8CacheOptionsNone, kV8CacheOptionsNone);
-STATIC_ASSERT_ENUM(WebSettings::kV8CacheOptionsCode, kV8CacheOptionsCode);
-STATIC_ASSERT_ENUM(WebSettings::kV8CacheOptionsCodeWithoutHeatCheck,
+STATIC_ASSERT_ENUM(WebSettings::V8CacheOptions::kDefault,
+ kV8CacheOptionsDefault);
+STATIC_ASSERT_ENUM(WebSettings::V8CacheOptions::kNone, kV8CacheOptionsNone);
+STATIC_ASSERT_ENUM(WebSettings::V8CacheOptions::kCode, kV8CacheOptionsCode);
+STATIC_ASSERT_ENUM(WebSettings::V8CacheOptions::kCodeWithoutHeatCheck,
kV8CacheOptionsCodeWithoutHeatCheck);
-STATIC_ASSERT_ENUM(WebSettings::kV8CacheOptionsFullCodeWithoutHeatCheck,
+STATIC_ASSERT_ENUM(WebSettings::V8CacheOptions::kFullCodeWithoutHeatCheck,
kV8CacheOptionsFullCodeWithoutHeatCheck);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc
index ccaa8507ba1..6db6b620402 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc
@@ -47,7 +47,7 @@ v8::Local<v8::Object> CreatePlainWrapper(v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::Context> context,
const WrapperTypeInfo* type) {
- CHECK(V8HTMLDocument::wrapperTypeInfo.Equals(type));
+ CHECK(V8HTMLDocument::wrapper_type_info.Equals(type));
v8::Context::Scope scope(context);
v8::Local<v8::Function> interface_object =
@@ -56,10 +56,7 @@ v8::Local<v8::Object> CreatePlainWrapper(v8::Isolate* isolate,
v8::Local<v8::Object> instance_template =
V8ObjectConstructor::NewInstance(isolate, interface_object)
.ToLocalChecked();
- v8::Local<v8::Object> wrapper = instance_template->Clone();
- wrapper->SetAlignedPointerInInternalField(kV8DOMWrapperTypeIndex,
- const_cast<WrapperTypeInfo*>(type));
- return wrapper;
+ return instance_template->Clone();
}
int GetSnapshotIndexForWorld(const DOMWrapperWorld& world) {
@@ -74,14 +71,15 @@ struct SnapshotInterface {
InstallRuntimeEnabledFeaturesOnTemplateFunction install_function;
};
SnapshotInterface g_snapshot_interfaces[] = {
- {&V8Window::wrapperTypeInfo,
+ {&V8Window::wrapper_type_info,
V8Window::InstallRuntimeEnabledFeaturesOnTemplate},
- {&V8HTMLDocument::wrapperTypeInfo,
+ {&V8HTMLDocument::wrapper_type_info,
V8HTMLDocument::InstallRuntimeEnabledFeaturesOnTemplate},
- {&V8EventTarget::wrapperTypeInfo,
+ {&V8EventTarget::wrapper_type_info,
V8EventTarget::InstallRuntimeEnabledFeaturesOnTemplate},
- {&V8Node::wrapperTypeInfo, V8Node::InstallRuntimeEnabledFeaturesOnTemplate},
- {&V8Document::wrapperTypeInfo,
+ {&V8Node::wrapper_type_info,
+ V8Node::InstallRuntimeEnabledFeaturesOnTemplate},
+ {&V8Document::wrapper_type_info,
V8Document::InstallRuntimeEnabledFeaturesOnTemplate},
};
constexpr size_t kSnapshotInterfaceSize = base::size(g_snapshot_interfaces);
@@ -100,13 +98,13 @@ const WrapperTypeInfo* FieldTypeToWrapperTypeInfo(InternalFieldType type) {
NOTREACHED();
break;
case InternalFieldType::kNodeType:
- return &V8Node::wrapperTypeInfo;
+ return &V8Node::wrapper_type_info;
case InternalFieldType::kDocumentType:
- return &V8Document::wrapperTypeInfo;
+ return &V8Document::wrapper_type_info;
case InternalFieldType::kHTMLDocumentType:
- return &V8HTMLDocument::wrapperTypeInfo;
+ return &V8HTMLDocument::wrapper_type_info;
case InternalFieldType::kHTMLDocumentObject:
- return &V8HTMLDocument::wrapperTypeInfo;
+ return &V8HTMLDocument::wrapper_type_info;
}
NOTREACHED();
return nullptr;
@@ -177,7 +175,7 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
{
v8::Local<v8::Object> window_wrapper =
global_proxy->GetPrototype().As<v8::Object>();
- const WrapperTypeInfo* type = &V8Window::wrapperTypeInfo;
+ const WrapperTypeInfo* type = &V8Window::wrapper_type_info;
v8::Local<v8::Function> interface = data->ConstructorForType(type);
v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
.ToLocalChecked()
@@ -186,11 +184,11 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
prototype, interface);
type->InstallConditionalFeatures(context, world, window_wrapper, prototype,
interface,
- type->domTemplate(isolate, world));
+ type->DomTemplate(isolate, world));
InstallOriginTrialFeatures(type, script_state, prototype, interface);
}
{
- const WrapperTypeInfo* type = &V8EventTarget::wrapperTypeInfo;
+ const WrapperTypeInfo* type = &V8EventTarget::wrapper_type_info;
v8::Local<v8::Function> interface = data->ConstructorForType(type);
v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
.ToLocalChecked()
@@ -199,7 +197,7 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
isolate, world, v8::Local<v8::Object>(), prototype, interface);
type->InstallConditionalFeatures(context, world, v8::Local<v8::Object>(),
prototype, interface,
- type->domTemplate(isolate, world));
+ type->DomTemplate(isolate, world));
InstallOriginTrialFeatures(type, script_state, prototype, interface);
}
@@ -214,7 +212,7 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
CHECK(document->ContainsWrapper());
v8::Local<v8::Object> document_wrapper =
ToV8(document, global_proxy, isolate).As<v8::Object>();
- const WrapperTypeInfo* type = &V8HTMLDocument::wrapperTypeInfo;
+ const WrapperTypeInfo* type = &V8HTMLDocument::wrapper_type_info;
v8::Local<v8::Function> interface = data->ConstructorForType(type);
v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
.ToLocalChecked()
@@ -223,11 +221,11 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
isolate, world, document_wrapper, prototype, interface);
type->InstallConditionalFeatures(context, world, document_wrapper,
prototype, interface,
- type->domTemplate(isolate, world));
+ type->DomTemplate(isolate, world));
InstallOriginTrialFeatures(type, script_state, prototype, interface);
}
{
- const WrapperTypeInfo* type = &V8Document::wrapperTypeInfo;
+ const WrapperTypeInfo* type = &V8Document::wrapper_type_info;
v8::Local<v8::Function> interface = data->ConstructorForType(type);
v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
.ToLocalChecked()
@@ -236,11 +234,11 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
isolate, world, v8::Local<v8::Object>(), prototype, interface);
type->InstallConditionalFeatures(context, world, v8::Local<v8::Object>(),
prototype, interface,
- type->domTemplate(isolate, world));
+ type->DomTemplate(isolate, world));
InstallOriginTrialFeatures(type, script_state, prototype, interface);
}
{
- const WrapperTypeInfo* type = &V8Node::wrapperTypeInfo;
+ const WrapperTypeInfo* type = &V8Node::wrapper_type_info;
v8::Local<v8::Function> interface = data->ConstructorForType(type);
v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
.ToLocalChecked()
@@ -249,7 +247,7 @@ bool V8ContextSnapshot::InstallConditionalFeatures(
isolate, world, v8::Local<v8::Object>(), prototype, interface);
type->InstallConditionalFeatures(context, world, v8::Local<v8::Object>(),
prototype, interface,
- type->domTemplate(isolate, world));
+ type->DomTemplate(isolate, world));
InstallOriginTrialFeatures(type, script_state, prototype, interface);
}
@@ -266,13 +264,13 @@ void V8ContextSnapshot::EnsureInterfaceTemplates(v8::Isolate* isolate) {
// Update the install functions for V8Window and V8Document to work for their
// partial interfaces.
SnapshotInterface& snapshot_window = g_snapshot_interfaces[0];
- DCHECK(V8Window::wrapperTypeInfo.Equals(snapshot_window.wrapper_type_info));
+ DCHECK(V8Window::wrapper_type_info.Equals(snapshot_window.wrapper_type_info));
snapshot_window.install_function =
V8Window::install_runtime_enabled_features_on_template_function_;
SnapshotInterface& snapshot_document = g_snapshot_interfaces[4];
- DCHECK(
- V8Document::wrapperTypeInfo.Equals(snapshot_document.wrapper_type_info));
+ DCHECK(V8Document::wrapper_type_info.Equals(
+ snapshot_document.wrapper_type_info));
snapshot_document.install_function =
V8Document::install_runtime_enabled_features_on_template_function_;
@@ -326,17 +324,17 @@ v8::StartupData V8ContextSnapshot::SerializeInternalField(
InternalFieldType field_type = InternalFieldType::kNone;
const WrapperTypeInfo* wrapper_type = ToWrapperTypeInfo(object);
if (kV8DOMWrapperObjectIndex == index) {
- if (blink::V8HTMLDocument::wrapperTypeInfo.Equals(wrapper_type)) {
+ if (blink::V8HTMLDocument::wrapper_type_info.Equals(wrapper_type)) {
field_type = InternalFieldType::kHTMLDocumentObject;
}
DCHECK_LE(kV8DefaultWrapperInternalFieldCount,
object->InternalFieldCount());
} else if (kV8DOMWrapperTypeIndex == index) {
- if (blink::V8HTMLDocument::wrapperTypeInfo.Equals(wrapper_type)) {
+ if (blink::V8HTMLDocument::wrapper_type_info.Equals(wrapper_type)) {
field_type = InternalFieldType::kHTMLDocumentType;
- } else if (blink::V8Document::wrapperTypeInfo.Equals(wrapper_type)) {
+ } else if (blink::V8Document::wrapper_type_info.Equals(wrapper_type)) {
field_type = InternalFieldType::kDocumentType;
- } else if (blink::V8Node::wrapperTypeInfo.Equals(wrapper_type)) {
+ } else if (blink::V8Node::wrapper_type_info.Equals(wrapper_type)) {
field_type = InternalFieldType::kNodeType;
}
DCHECK_LE(kV8PrototypeInternalFieldcount, object->InternalFieldCount());
@@ -466,10 +464,10 @@ void V8ContextSnapshot::TakeSnapshotForWorld(v8::SnapshotCreator* creator,
const WrapperTypeInfo* wrapper_type_info =
g_snapshot_interfaces[i].wrapper_type_info;
v8::Local<v8::FunctionTemplate> interface_template =
- wrapper_type_info->domTemplate(isolate, world);
+ wrapper_type_info->DomTemplate(isolate, world);
CHECK(!interface_template.IsEmpty());
interface_templates[i] = interface_template;
- if (V8Window::wrapperTypeInfo.Equals(wrapper_type_info)) {
+ if (V8Window::wrapper_type_info.Equals(wrapper_type_info)) {
window_template = interface_template;
}
}
@@ -492,10 +490,10 @@ void V8ContextSnapshot::TakeSnapshotForWorld(v8::SnapshotCreator* creator,
if (world.IsMainWorld()) {
v8::Context::Scope scope(context);
v8::Local<v8::Object> document_wrapper = CreatePlainWrapper(
- isolate, world, context, &V8HTMLDocument::wrapperTypeInfo);
+ isolate, world, context, &V8HTMLDocument::wrapper_type_info);
int indices[] = {kV8DOMWrapperObjectIndex, kV8DOMWrapperTypeIndex};
void* values[] = {nullptr, const_cast<WrapperTypeInfo*>(
- &V8HTMLDocument::wrapperTypeInfo)};
+ &V8HTMLDocument::wrapper_type_info)};
document_wrapper->SetAlignedPointerInInternalFields(base::size(indices),
indices, values);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc
index 53a5417b0dd..65b479d8c92 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc
@@ -811,6 +811,7 @@ void V8DOMConfiguration::InitializeDOMInterfaceTemplate(
// This is needed since bug 110436 asks WebKit to tell native-initiated
// prototypes from pure-JS ones. This doesn't mark kinds "root" classes
// like Node, where setting this changes prototype chain structure.
+ // The value of this field is not used, only the count.
prototype_template->SetInternalFieldCount(kV8PrototypeInternalFieldcount);
}
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_controller.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_controller.cc
index d0f3e987df9..795d282271c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_controller.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_controller.cc
@@ -115,7 +115,7 @@ class MinorGCUnmodifiedWrapperVisitor : public v8::PersistentHandleVisitor {
}
if (class_id == WrapperTypeInfo::kNodeClassId) {
- DCHECK(V8Node::hasInstance(wrapper, isolate_));
+ DCHECK(V8Node::HasInstance(wrapper, isolate_));
Node* node = V8Node::ToImpl(wrapper);
if (node->HasEventListeners()) {
v8::Persistent<v8::Object>::Cast(*value).MarkActive();
@@ -147,12 +147,21 @@ void VisitWeakHandlesForMinorGC(v8::Isolate* isolate) {
isolate->VisitWeakHandles(&visitor);
}
+bool IsNestedInV8GC(ThreadState* thread_state, v8::GCType type) {
+ return thread_state && (type == v8::kGCTypeMarkSweepCompact ||
+ type == v8::kGCTypeIncrementalMarking);
+}
+
} // namespace
void V8GCController::GcPrologue(v8::Isolate* isolate,
v8::GCType type,
v8::GCCallbackFlags flags) {
RUNTIME_CALL_TIMER_SCOPE(isolate, RuntimeCallStats::CounterId::kGcPrologue);
+ ThreadHeapStatsCollector::BlinkGCInV8Scope nested_scope(
+ IsNestedInV8GC(ThreadState::Current(), type)
+ ? ThreadState::Current()->Heap().stats_collector()
+ : nullptr);
ScriptForbiddenScope::Enter();
// Attribute garbage collection to the all frames instead of a specific
@@ -264,6 +273,10 @@ void V8GCController::GcEpilogue(v8::Isolate* isolate,
v8::GCType type,
v8::GCCallbackFlags flags) {
RUNTIME_CALL_TIMER_SCOPE(isolate, RuntimeCallStats::CounterId::kGcEpilogue);
+ ThreadHeapStatsCollector::BlinkGCInV8Scope nested_scope(
+ IsNestedInV8GC(ThreadState::Current(), type)
+ ? ThreadState::Current()->Heap().stats_collector()
+ : nullptr);
UpdateCollectedPhantomHandles(isolate);
switch (type) {
case v8::kGCTypeScavenge:
@@ -309,7 +322,7 @@ void V8GCController::GcEpilogue(v8::Isolate* isolate,
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorUpdateCountersEvent::Data());
+ inspector_update_counters_event::Data());
}
void V8GCController::CollectAllGarbageForTesting(
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.cc
index c776ce8655c..741b2289b1f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.cc
@@ -59,10 +59,9 @@ static size_t GetMemoryUsage() {
namespace blink {
V8GCForContextDispose::V8GCForContextDispose()
- : pseudo_idle_timer_(
- Platform::Current()->MainThread()->Scheduler()->V8TaskRunner(),
- this,
- &V8GCForContextDispose::PseudoIdleTimerFired),
+ : pseudo_idle_timer_(ThreadScheduler::Current()->V8TaskRunner(),
+ this,
+ &V8GCForContextDispose::PseudoIdleTimerFired),
force_page_navigation_gc_(false) {
Reset();
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc
index e9b01bed52b..aa166403c83 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc
@@ -74,7 +74,7 @@ void V8HTMLConstructor::HtmlConstructor(
// Autonomous custom element
// 4.1. If the active function object is not HTMLElement, then throw a
// TypeError
- if (!V8HTMLElement::wrapperTypeInfo.Equals(&wrapper_type_info)) {
+ if (!V8HTMLElement::wrapper_type_info.Equals(&wrapper_type_info)) {
V8ThrowException::ThrowTypeError(isolate,
"Illegal constructor: autonomous custom "
"elements must extend HTMLElement");
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
index 5db87633802..0050eb07bf1 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
@@ -35,6 +35,7 @@
#include "third_party/blink/renderer/bindings/core/v8/binding_security.h"
#include "third_party/blink/renderer/bindings/core/v8/referrer_script_info.h"
#include "third_party/blink/renderer/bindings/core/v8/rejected_promises.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
@@ -64,7 +65,6 @@
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
#include "third_party/blink/renderer/platform/bindings/v8_private_property.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
@@ -198,7 +198,7 @@ static String ExtractMessageForConsole(v8::Isolate* isolate,
if (V8DOMWrapper::IsWrapper(isolate, data)) {
v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(data);
const WrapperTypeInfo* type = ToWrapperTypeInfo(obj);
- if (V8DOMException::wrapperTypeInfo.IsSubclass(type)) {
+ if (V8DOMException::wrapper_type_info.IsSubclass(type)) {
DOMException* exception = V8DOMException::ToImpl(obj);
if (exception && !exception->MessageForConsole().IsEmpty())
return exception->ToStringForConsole();
@@ -242,7 +242,7 @@ void V8Initializer::MessageHandlerInMainThread(v8::Local<v8::Message> message,
DCHECK(IsMainThread());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
- if (isolate->GetEnteredContext().IsEmpty())
+ if (isolate->GetEnteredOrMicrotaskContext().IsEmpty())
return;
// If called during context initialization, there will be no entered context.
@@ -262,8 +262,9 @@ void V8Initializer::MessageHandlerInMainThread(v8::Local<v8::Message> message,
return;
}
- AccessControlStatus access_control_status =
- message->IsSharedCrossOrigin() ? kSharableCrossOrigin : kOpaqueResource;
+ const auto sanitize_script_errors = message->IsSharedCrossOrigin()
+ ? SanitizeScriptErrors::kDoNotSanitize
+ : SanitizeScriptErrors::kSanitize;
ErrorEvent* event = ErrorEvent::Create(
ToCoreStringWithNullCheck(message->Get()), std::move(location),
@@ -273,7 +274,7 @@ void V8Initializer::MessageHandlerInMainThread(v8::Local<v8::Message> message,
if (!message_for_console.IsEmpty())
event->SetUnsanitizedMessage("Uncaught " + message_for_console);
- context->DispatchErrorEvent(event, access_control_status);
+ context->DispatchErrorEvent(event, sanitize_script_errors);
}
void V8Initializer::MessageHandlerInWorker(v8::Local<v8::Message> message,
@@ -310,14 +311,15 @@ void V8Initializer::MessageHandlerInWorker(v8::Local<v8::Message> message,
ToCoreStringWithNullCheck(message->Get()), std::move(location),
ScriptValue::From(script_state, data), &script_state->World());
- AccessControlStatus access_control_status =
- message->IsSharedCrossOrigin() ? kSharableCrossOrigin : kOpaqueResource;
+ const auto sanitize_script_errors = message->IsSharedCrossOrigin()
+ ? SanitizeScriptErrors::kDoNotSanitize
+ : SanitizeScriptErrors::kSanitize;
// If execution termination has been triggered as part of constructing
// the error event from the v8::Message, quietly leave.
if (!isolate->IsExecutionTerminating()) {
ExecutionContext::From(script_state)
- ->DispatchErrorEvent(event, access_control_status);
+ ->DispatchErrorEvent(event, sanitize_script_errors);
}
per_isolate_data->SetReportingException(false);
@@ -370,7 +372,7 @@ static void PromiseRejectHandler(v8::PromiseRejectMessage data,
}
String error_message;
- AccessControlStatus cors_status = kOpaqueResource;
+ SanitizeScriptErrors sanitize_script_errors = SanitizeScriptErrors::kSanitize;
std::unique_ptr<SourceLocation> location;
v8::Local<v8::Message> message =
@@ -380,7 +382,7 @@ static void PromiseRejectHandler(v8::PromiseRejectMessage data,
error_message = ToCoreStringWithNullCheck(message->Get());
location = SourceLocation::FromMessage(isolate, message, context);
if (message->IsSharedCrossOrigin())
- cors_status = kSharableCrossOrigin;
+ sanitize_script_errors = SanitizeScriptErrors::kDoNotSanitize;
} else {
location =
SourceLocation::Create(context->Url().GetString(), 0, 0, nullptr);
@@ -392,7 +394,8 @@ static void PromiseRejectHandler(v8::PromiseRejectMessage data,
error_message = "Uncaught " + message_for_console;
rejected_promises.RejectedWithNoHandler(script_state, data, error_message,
- std::move(location), cors_status);
+ std::move(location),
+ sanitize_script_errors);
}
static void PromiseRejectHandlerInMainThread(v8::PromiseRejectMessage data) {
@@ -429,9 +432,8 @@ static void PromiseRejectHandlerInWorker(v8::PromiseRejectMessage data) {
if (!execution_context)
return;
- DCHECK(execution_context->IsWorkerGlobalScope());
- WorkerOrWorkletScriptController* script_controller =
- ToWorkerGlobalScope(execution_context)->ScriptController();
+ auto* script_controller =
+ To<WorkerGlobalScope>(execution_context)->ScriptController();
DCHECK(script_controller);
PromiseRejectHandler(data, *script_controller->GetRejectedPromises(),
@@ -502,7 +504,7 @@ static bool WasmThreadsEnabledCallback(v8::Local<v8::Context> context) {
if (!execution_context)
return false;
- return OriginTrials::WebAssemblyThreadsEnabled(execution_context);
+ return origin_trials::WebAssemblyThreadsEnabled(execution_context);
}
v8::Local<v8::Value> NewRangeException(v8::Isolate* isolate,
@@ -696,9 +698,7 @@ void V8Initializer::InitializeMainThread(const intptr_t* reference_table) {
v8_extras_mode, &array_buffer_allocator,
reference_table);
- // NOTE: Some threads (namely utility threads) don't have a scheduler.
- ThreadScheduler* scheduler =
- Platform::Current()->CurrentThread()->Scheduler();
+ ThreadScheduler* scheduler = ThreadScheduler::Current();
#if defined(USE_V8_CONTEXT_SNAPSHOT)
V8PerIsolateData::V8ContextSnapshotMode v8_context_snapshot_mode =
@@ -716,10 +716,8 @@ void V8Initializer::InitializeMainThread(const intptr_t* reference_table) {
V8PerIsolateData::V8ContextSnapshotMode::kDontUseSnapshot;
#endif // USE_V8_CONTEXT_SNAPSHOT
- v8::Isolate* isolate = V8PerIsolateData::Initialize(
- scheduler ? scheduler->V8TaskRunner()
- : Platform::Current()->CurrentThread()->GetTaskRunner(),
- v8_context_snapshot_mode);
+ v8::Isolate* isolate = V8PerIsolateData::Initialize(scheduler->V8TaskRunner(),
+ v8_context_snapshot_mode);
// ThreadState::isolate_ needs to be set before setting the EmbedderHeapTracer
// as setting the tracer indicates that a V8 garbage collection should trace
@@ -770,8 +768,6 @@ void V8Initializer::InitializeMainThread(const intptr_t* reference_table) {
V8PerIsolateData::From(isolate)->SetThreadDebugger(
std::make_unique<MainThreadDebugger>(isolate));
-
- BindingSecurity::InitWrapperCreationSecurityCheck();
}
static void ReportFatalErrorInWorker(const char* location,
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.cc
index ac844072655..c85d9b8593f 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.cc
@@ -4,22 +4,19 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
+
namespace blink {
-v8::Local<v8::Object> V8IteratorResultValue(v8::Isolate* isolate,
+v8::Local<v8::Object> V8IteratorResultValue(ScriptState* script_state,
bool done,
v8::Local<v8::Value> value) {
- v8::Local<v8::Object> result = v8::Object::New(isolate);
if (value.IsEmpty())
- value = v8::Undefined(isolate);
- if (!V8CallBoolean(result->CreateDataProperty(
- isolate->GetCurrentContext(), V8AtomicString(isolate, "done"),
- v8::Boolean::New(isolate, done))) ||
- !V8CallBoolean(
- result->CreateDataProperty(isolate->GetCurrentContext(),
- V8AtomicString(isolate, "value"), value)))
- return v8::Local<v8::Object>();
- return result;
+ value = v8::Undefined(script_state->GetIsolate());
+ return V8ObjectBuilder(script_state)
+ .Add("done", done)
+ .Add("value", value)
+ .V8Value();
}
v8::MaybeLocal<v8::Value> V8UnpackIteratorResult(ScriptState* script_state,
@@ -34,10 +31,10 @@ v8::MaybeLocal<v8::Value> V8UnpackIteratorResult(ScriptState* script_state,
if (!result
->Get(script_state->GetContext(),
V8AtomicString(script_state->GetIsolate(), "done"))
- .ToLocal(&done_value) ||
- !done_value->BooleanValue(script_state->GetContext()).To(done)) {
+ .ToLocal(&done_value)) {
return v8::MaybeLocal<v8::Value>();
}
+ *done = done_value->BooleanValue(script_state->GetIsolate());
return maybe_value;
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h b/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h
index 0c5c246e116..6d37648968d 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h
@@ -15,7 +15,7 @@ namespace blink {
// "Iterator result" in this file is an object returned from iterator.next()
// having two members "done" and "value".
-CORE_EXPORT v8::Local<v8::Object> V8IteratorResultValue(v8::Isolate*,
+CORE_EXPORT v8::Local<v8::Object> V8IteratorResultValue(ScriptState*,
bool done,
v8::Local<v8::Value>);
@@ -28,7 +28,7 @@ template <typename T>
inline ScriptValue V8IteratorResult(ScriptState* script_state, const T& value) {
return ScriptValue(
script_state,
- V8IteratorResultValue(script_state->GetIsolate(), false,
+ V8IteratorResultValue(script_state, false,
ToV8(value, script_state->GetContext()->Global(),
script_state->GetIsolate())));
}
@@ -36,7 +36,7 @@ inline ScriptValue V8IteratorResult(ScriptState* script_state, const T& value) {
inline ScriptValue V8IteratorResultDone(ScriptState* script_state) {
return ScriptValue(
script_state,
- V8IteratorResultValue(script_state->GetIsolate(), true,
+ V8IteratorResultValue(script_state, true,
v8::Undefined(script_state->GetIsolate())));
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_object_parser.h b/chromium/third_party/blink/renderer/bindings/core/v8/v8_object_parser.h
index 4e2fcfa9616..2aa5cd1c572 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_object_parser.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_object_parser.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_OBJECT_PARSER_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "v8/include/v8.h"
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc
index 695d6b777c0..45f880934e0 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc
@@ -69,7 +69,8 @@ void ThrowScriptForbiddenException(v8::Isolate* isolate) {
V8ThrowException::ThrowError(isolate, "Script execution is forbidden.");
}
-v8::Local<v8::Value> ThrowStackOverflowExceptionIfNeeded(v8::Isolate* isolate) {
+v8::MaybeLocal<v8::Value> ThrowStackOverflowExceptionIfNeeded(
+ v8::Isolate* isolate) {
if (V8PerIsolateData::From(isolate)->IsHandlingRecursionLevelError()) {
// If we are already handling a recursion level error, we should
// not invoke v8::Function::Call.
@@ -80,12 +81,13 @@ v8::Local<v8::Value> ThrowStackOverflowExceptionIfNeeded(v8::Isolate* isolate) {
V8PerIsolateData::From(isolate)->SetIsHandlingRecursionLevelError(true);
ScriptForbiddenScope::AllowUserAgentScript allow_script;
- v8::Local<v8::Value> result =
- v8::Function::New(isolate->GetCurrentContext(),
- ThrowStackOverflowException, v8::Local<v8::Value>(), 0,
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
+ v8::MaybeLocal<v8::Value> result =
+ v8::Function::New(context, ThrowStackOverflowException,
+ v8::Local<v8::Value>(), 0,
v8::ConstructorBehavior::kThrow)
.ToLocalChecked()
- ->Call(v8::Undefined(isolate), 0, nullptr);
+ ->Call(context, v8::Undefined(isolate), 0, nullptr);
V8PerIsolateData::From(isolate)->SetIsHandlingRecursionLevelError(false);
return result;
@@ -98,7 +100,7 @@ v8::MaybeLocal<v8::Script> CompileScriptInternal(
v8::ScriptOrigin origin,
v8::ScriptCompiler::CompileOptions compile_options,
v8::ScriptCompiler::NoCacheReason no_cache_reason,
- InspectorCompileScriptEvent::V8CacheResult* cache_result) {
+ inspector_compile_script_event::V8CacheResult* cache_result) {
v8::Local<v8::String> code = V8String(isolate, source_code.Source());
if (ScriptStreamer* streamer = source_code.Streamer()) {
@@ -147,7 +149,7 @@ v8::MaybeLocal<v8::Script> CompileScriptInternal(
}
if (cache_result) {
cache_result->consume_result = base::make_optional(
- InspectorCompileScriptEvent::V8CacheResult::ConsumeResult(
+ inspector_compile_script_event::V8CacheResult::ConsumeResult(
v8::ScriptCompiler::kConsumeCodeCache, cached_data->length,
cached_data->rejected));
}
@@ -171,7 +173,7 @@ v8::MaybeLocal<v8::Script> CompileScriptInternal(
v8::MaybeLocal<v8::Script> V8ScriptRunner::CompileScript(
ScriptState* script_state,
const ScriptSourceCode& source,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
v8::ScriptCompiler::CompileOptions compile_options,
v8::ScriptCompiler::NoCacheReason no_cache_reason,
const ReferrerScriptInfo& referrer_info) {
@@ -198,9 +200,11 @@ v8::MaybeLocal<v8::Script> V8ScriptRunner::CompileScript(
V8String(isolate, file_name),
v8::Integer::New(isolate, script_start_position.line_.ZeroBasedInt()),
v8::Integer::New(isolate, script_start_position.column_.ZeroBasedInt()),
- v8::Boolean::New(isolate, access_control_status == kSharableCrossOrigin),
+ v8::Boolean::New(isolate, sanitize_script_errors ==
+ SanitizeScriptErrors::kDoNotSanitize),
v8::Local<v8::Integer>(), V8String(isolate, source.SourceMapUrl()),
- v8::Boolean::New(isolate, access_control_status == kOpaqueResource),
+ v8::Boolean::New(
+ isolate, sanitize_script_errors == SanitizeScriptErrors::kSanitize),
v8::False(isolate), // is_wasm
v8::False(isolate), // is_module
referrer_info.ToV8HostDefinedOptions(isolate));
@@ -210,12 +214,12 @@ v8::MaybeLocal<v8::Script> V8ScriptRunner::CompileScript(
compile_options, no_cache_reason, nullptr);
}
- InspectorCompileScriptEvent::V8CacheResult cache_result;
+ inspector_compile_script_event::V8CacheResult cache_result;
v8::MaybeLocal<v8::Script> script =
CompileScriptInternal(isolate, execution_context, source, origin,
compile_options, no_cache_reason, &cache_result);
TRACE_EVENT_END1(kTraceEventCategoryGroup, "v8.compile", "data",
- InspectorCompileScriptEvent::Data(
+ inspector_compile_script_event::Data(
file_name, script_start_position, cache_result,
source.Streamer(), source.NotStreamingReason()));
return script;
@@ -225,22 +229,23 @@ v8::MaybeLocal<v8::Module> V8ScriptRunner::CompileModule(
v8::Isolate* isolate,
const String& source,
const String& file_name,
- AccessControlStatus access_control_status,
const TextPosition& start_position,
const ReferrerScriptInfo& referrer_info) {
TRACE_EVENT1("v8,devtools.timeline", "v8.compileModule", "fileName",
file_name.Utf8());
+ // |resource_is_shared_cross_origin| is always true and |resource_is_opaque|
+ // is always false because CORS is enforced to module scripts.
v8::ScriptOrigin origin(
V8String(isolate, file_name),
v8::Integer::New(isolate, start_position.line_.ZeroBasedInt()),
v8::Integer::New(isolate, start_position.column_.ZeroBasedInt()),
- v8::Boolean::New(isolate, access_control_status == kSharableCrossOrigin),
- v8::Local<v8::Integer>(), // script id
- v8::String::Empty(isolate), // source_map_url
- v8::Boolean::New(isolate, access_control_status == kOpaqueResource),
- v8::False(isolate), // is_wasm
- v8::True(isolate), // is_module
+ v8::Boolean::New(isolate, true), // resource_is_shared_cross_origin
+ v8::Local<v8::Integer>(), // script id
+ v8::String::Empty(isolate), // source_map_url
+ v8::Boolean::New(isolate, false), // resource_is_opaque
+ v8::False(isolate), // is_wasm
+ v8::True(isolate), // is_module
referrer_info.ToV8HostDefinedOptions(isolate));
v8::ScriptCompiler::Source script_source(V8String(isolate, source), origin);
@@ -311,9 +316,9 @@ v8::MaybeLocal<v8::Value> V8ScriptRunner::CompileAndRunInternalScript(
// Use default ScriptReferrerInfo here:
// - nonce: empty for internal script, and
// - parser_state: always "not parser inserted" for internal scripts.
- if (!V8ScriptRunner::CompileScript(script_state, source_code,
- kSharableCrossOrigin, compile_options,
- no_cache_reason, ReferrerScriptInfo())
+ if (!V8ScriptRunner::CompileScript(
+ script_state, source_code, SanitizeScriptErrors::kDoNotSanitize,
+ compile_options, no_cache_reason, ReferrerScriptInfo())
.ToLocal(&script))
return v8::MaybeLocal<v8::Value>();
@@ -339,8 +344,7 @@ v8::MaybeLocal<v8::Value> V8ScriptRunner::CallAsConstructor(
int depth = v8::MicrotasksScope::GetCurrentDepth(isolate);
if (depth >= kMaxRecursionDepth)
- return v8::MaybeLocal<v8::Value>(
- ThrowStackOverflowExceptionIfNeeded(isolate));
+ return ThrowStackOverflowExceptionIfNeeded(isolate);
CHECK(!context->IsIteratingOverObservers());
@@ -382,8 +386,7 @@ v8::MaybeLocal<v8::Value> V8ScriptRunner::CallFunction(
int depth = v8::MicrotasksScope::GetCurrentDepth(isolate);
if (depth >= kMaxRecursionDepth)
- return v8::MaybeLocal<v8::Value>(
- ThrowStackOverflowExceptionIfNeeded(isolate));
+ return ThrowStackOverflowExceptionIfNeeded(isolate);
CHECK(!context->IsIteratingOverObservers());
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.h b/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.h
index ffa79e6ed3a..f5499a38894 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner.h
@@ -26,8 +26,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_SCRIPT_RUNNER_H_
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_SCRIPT_RUNNER_H_
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "v8/include/v8.h"
@@ -52,14 +52,13 @@ class CORE_EXPORT V8ScriptRunner final {
static v8::MaybeLocal<v8::Script> CompileScript(
ScriptState*,
const ScriptSourceCode&,
- AccessControlStatus,
+ SanitizeScriptErrors,
v8::ScriptCompiler::CompileOptions,
v8::ScriptCompiler::NoCacheReason,
const ReferrerScriptInfo&);
static v8::MaybeLocal<v8::Module> CompileModule(v8::Isolate*,
const String& source,
const String& file_name,
- AccessControlStatus,
const WTF::TextPosition&,
const ReferrerScriptInfo&);
static v8::MaybeLocal<v8::Value> RunCompiledScript(v8::Isolate*,
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc
index edbdba257e0..87d41d374a0 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc
@@ -63,8 +63,8 @@ class V8ScriptRunnerTest : public testing::Test {
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(cache_options, source_code);
v8::MaybeLocal<v8::Script> compiled_script = V8ScriptRunner::CompileScript(
- script_state, source_code, kOpaqueResource, compile_options,
- no_cache_reason, ReferrerScriptInfo());
+ script_state, source_code, SanitizeScriptErrors::kSanitize,
+ compile_options, no_cache_reason, ReferrerScriptInfo());
if (compiled_script.IsEmpty()) {
return false;
}
@@ -81,8 +81,8 @@ class V8ScriptRunnerTest : public testing::Test {
v8::ScriptCompiler::NoCacheReason no_cache_reason,
V8CodeCache::ProduceCacheOptions produce_cache_options) {
v8::MaybeLocal<v8::Script> compiled_script = V8ScriptRunner::CompileScript(
- script_state, source_code, kOpaqueResource, compile_options,
- no_cache_reason, ReferrerScriptInfo());
+ script_state, source_code, SanitizeScriptErrors::kSanitize,
+ compile_options, no_cache_reason, ReferrerScriptInfo());
if (compiled_script.IsEmpty()) {
return false;
}
@@ -93,11 +93,15 @@ class V8ScriptRunnerTest : public testing::Test {
}
ScriptResource* CreateEmptyResource() {
- return ScriptResource::CreateForTest(NullURL(), UTF8Encoding());
+ ScriptResource* resource =
+ ScriptResource::CreateForTest(NullURL(), UTF8Encoding());
+ resource->SetClientIsWaitingForFinished();
+ return resource;
}
ScriptResource* CreateResource(const WTF::TextEncoding& encoding) {
ScriptResource* resource = ScriptResource::CreateForTest(Url(), encoding);
+ resource->SetClientIsWaitingForFinished();
String code = Code();
ResourceResponse response(Url());
response.SetHTTPStatusCode(200);
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.cc
index aaff56e8050..fe0426952bc 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.cc
@@ -73,7 +73,7 @@ V8V0CustomElementLifecycleCallbacks::Create(
CALLBACK_LIST(SET_PRIVATE_PROPERTY)
#undef SET_PRIVATE_PROPERTY
- return new V8V0CustomElementLifecycleCallbacks(
+ return MakeGarbageCollected<V8V0CustomElementLifecycleCallbacks>(
script_state, prototype, created, attached, detached, attribute_changed);
}
@@ -168,10 +168,12 @@ void V8V0CustomElementLifecycleCallbacks::Created(Element* element) {
// Swizzle the prototype of the wrapper.
v8::Local<v8::Object> prototype = prototype_.NewLocal(isolate);
- if (prototype.IsEmpty())
- return;
- if (!V8CallBoolean(receiver->SetPrototype(context, prototype)))
+ bool set_prototype;
+ if (prototype.IsEmpty() ||
+ !receiver->SetPrototype(context, prototype).To(&set_prototype) ||
+ !set_prototype) {
return;
+ }
v8::Local<v8::Function> callback = created_.NewLocal(isolate);
if (callback.IsEmpty())
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.h b/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.h
index 3abeeb37b6c..c37f7880552 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_v0_custom_element_lifecycle_callbacks.h
@@ -57,13 +57,6 @@ class V8V0CustomElementLifecycleCallbacks final
v8::MaybeLocal<v8::Function> detached,
v8::MaybeLocal<v8::Function> attribute_changed);
- ~V8V0CustomElementLifecycleCallbacks() override;
-
- bool SetBinding(std::unique_ptr<V0CustomElementBinding>);
-
- void Trace(blink::Visitor*) override;
-
- private:
V8V0CustomElementLifecycleCallbacks(
ScriptState*,
v8::Local<v8::Object> prototype,
@@ -71,7 +64,13 @@ class V8V0CustomElementLifecycleCallbacks final
v8::MaybeLocal<v8::Function> attached,
v8::MaybeLocal<v8::Function> detached,
v8::MaybeLocal<v8::Function> attribute_changed);
+ ~V8V0CustomElementLifecycleCallbacks() override;
+
+ bool SetBinding(std::unique_ptr<V0CustomElementBinding>);
+ void Trace(blink::Visitor*) override;
+
+ private:
void Created(Element*) override;
void Attached(Element*) override;
void Detached(Element*) override;
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/v8_wasm_response_extensions.cc b/chromium/third_party/blink/renderer/bindings/core/v8/v8_wasm_response_extensions.cc
index 9b8c92bfff9..0511190227b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/v8_wasm_response_extensions.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/v8_wasm_response_extensions.cc
@@ -115,103 +115,6 @@ class FetchDataLoaderForWasmStreaming final : public FetchDataLoader,
const Member<ScriptState> script_state_;
};
-// TODO(ahaas): Remove |FetchDataLoaderAsWasmModule| once the
-// |SetWasmCompileStreamingCallback| API is successfully replaced by the
-// |SetWasmStreamingCallback| API.
-class FetchDataLoaderAsWasmModule final : public FetchDataLoader,
- public BytesConsumer::Client {
- USING_GARBAGE_COLLECTED_MIXIN(FetchDataLoaderAsWasmModule);
-
- public:
- explicit FetchDataLoaderAsWasmModule(ScriptState* script_state)
- : builder_(script_state->GetIsolate()), script_state_(script_state) {}
-
- void Start(BytesConsumer* consumer,
- FetchDataLoader::Client* client) override {
- DCHECK(!consumer_);
- DCHECK(!client_);
- client_ = client;
- consumer_ = consumer;
- consumer_->SetClient(this);
- OnStateChange();
- }
-
- v8::Local<v8::Promise> GetPromise() { return builder_.GetPromise(); }
-
- void OnStateChange() override {
- while (true) {
- // |buffer| is owned by |consumer_|.
- const char* buffer = nullptr;
- size_t available = 0;
- BytesConsumer::Result result = consumer_->BeginRead(&buffer, &available);
-
- if (result == BytesConsumer::Result::kShouldWait)
- return;
- if (result == BytesConsumer::Result::kOk) {
- if (available > 0) {
- DCHECK_NE(buffer, nullptr);
- builder_.OnBytesReceived(reinterpret_cast<const uint8_t*>(buffer),
- available);
- }
- result = consumer_->EndRead(available);
- }
- switch (result) {
- case BytesConsumer::Result::kShouldWait:
- NOTREACHED();
- return;
- case BytesConsumer::Result::kOk: {
- break;
- }
- case BytesConsumer::Result::kDone: {
- ScriptState::Scope scope(script_state_);
- builder_.Finish();
- client_->DidFetchDataLoadedCustomFormat();
- return;
- }
- case BytesConsumer::Result::kError: {
- return AbortCompilation();
- }
- }
- }
- }
-
- String DebugName() const override { return "FetchDataLoaderAsWasmModule"; }
-
- void Cancel() override {
- consumer_->Cancel();
- return AbortCompilation();
- }
-
- void Trace(blink::Visitor* visitor) override {
- visitor->Trace(consumer_);
- visitor->Trace(client_);
- visitor->Trace(script_state_);
- FetchDataLoader::Trace(visitor);
- BytesConsumer::Client::Trace(visitor);
- }
-
- private:
- // TODO(mtrofin): replace with spec-ed error types, once spec clarifies
- // what they are.
- void AbortCompilation() {
- if (script_state_->ContextIsValid()) {
- ScriptState::Scope scope(script_state_);
- builder_.Abort(V8ThrowException::CreateTypeError(
- script_state_->GetIsolate(), "Could not download wasm module"));
- } else {
- // We are not allowed to execute a script, which indicates that we should
- // not reject the promise of the streaming compilation. By passing no
- // abort reason, we indicate the V8 side that the promise should not get
- // rejected.
- builder_.Abort(v8::Local<v8::Value>());
- }
- }
- TraceWrapperMember<BytesConsumer> consumer_;
- Member<FetchDataLoader::Client> client_;
- v8::WasmModuleObjectBuilderStreaming builder_;
- const Member<ScriptState> script_state_;
-};
-
// TODO(mtrofin): WasmDataLoaderClient is necessary so we may provide an
// argument to BodyStreamBuffer::startLoading, however, it fulfills
// a very small role. Consider refactoring to avoid it.
@@ -324,109 +227,9 @@ void StreamFromResponseCallback(
exception_state);
}
-// This callback may be entered as a promise is resolved, or directly
-// from the overload callback.
-// See
-// https://github.com/WebAssembly/design/blob/master/Web.md#webassemblycompile
-void CompileFromResponseCallback(
- const v8::FunctionCallbackInfo<v8::Value>& args) {
- ExceptionState exception_state(args.GetIsolate(),
- ExceptionState::kExecutionContext,
- "WebAssembly", "compile");
- ExceptionToRejectPromiseScope reject_promise_scope(args, exception_state);
-
- ScriptState* script_state = ScriptState::ForCurrentRealm(args);
- if (!script_state->ContextIsValid()) {
- V8SetReturnValue(args, ScriptPromise().V8Value());
- return;
- }
-
- Response* response =
- V8Response::ToImplWithTypeCheck(args.GetIsolate(), args[0]);
- if (!response) {
- exception_state.ThrowTypeError(
- "An argument must be provided, which must be a "
- "Response or Promise<Response> object");
- return;
- }
-
- if (!response->ok()) {
- exception_state.ThrowTypeError("HTTP status code is not ok");
- return;
- }
-
- if (response->MimeType() != "application/wasm") {
- exception_state.ThrowTypeError(
- "Incorrect response MIME type. Expected 'application/wasm'.");
- return;
- }
-
- Body::BodyLocked body_locked = response->IsBodyLocked(exception_state);
- if (body_locked == Body::BodyLocked::kBroken)
- return;
-
- if (body_locked == Body::BodyLocked::kLocked ||
- response->IsBodyUsed(exception_state) == Body::BodyUsed::kUsed) {
- DCHECK(!exception_state.HadException());
- exception_state.ThrowTypeError(
- "Cannot compile WebAssembly.Module from an already read Response");
- return;
- }
-
- if (exception_state.HadException())
- return;
-
- if (!response->BodyBuffer()) {
- exception_state.ThrowTypeError("Response object has a null body.");
- return;
- }
-
- FetchDataLoaderAsWasmModule* loader =
- new FetchDataLoaderAsWasmModule(script_state);
- v8::Local<v8::Value> promise = loader->GetPromise();
- response->BodyBuffer()->StartLoading(loader, new WasmDataLoaderClient(),
- exception_state);
- if (exception_state.HadException())
- return;
-
- V8SetReturnValue(args, promise);
-}
-
-// See https://crbug.com/708238 for tracking avoiding the hand-generated code.
-void WasmCompileStreamingImpl(const v8::FunctionCallbackInfo<v8::Value>& args) {
- ScriptState* script_state = ScriptState::ForCurrentRealm(args);
- V8PerIsolateData* per_isolate_data =
- V8PerIsolateData::From(script_state->GetIsolate());
-
- // An unique key of the v8::FunctionTemplate cache in V8PerIsolateData.
- // Everyone uses address of something as a key, so the address of |unique_key|
- // is guaranteed to be unique for the function template cache.
- static const int unique_key = 0;
- v8::Local<v8::FunctionTemplate> function_template =
- per_isolate_data->FindOrCreateOperationTemplate(
- script_state->World(), &unique_key, CompileFromResponseCallback,
- v8::Local<v8::Value>(), v8::Local<v8::Signature>(), 1);
- v8::Local<v8::Function> compile_callback;
- if (!function_template->GetFunction(script_state->GetContext())
- .ToLocal(&compile_callback)) {
- return; // Throw an exception.
- }
-
- // treat either case of parameter as
- // Promise.resolve(parameter)
- // as per https://www.w3.org/2001/tag/doc/promises-guide#resolve-arguments
-
- // Ending with:
- // return Promise.resolve(parameter).then(compileCallback);
- V8SetReturnValue(args, ScriptPromise::Cast(script_state, args[0])
- .Then(compile_callback)
- .V8Value());
-}
-
} // namespace
void WasmResponseExtensions::Initialize(v8::Isolate* isolate) {
- isolate->SetWasmCompileStreamingCallback(WasmCompileStreamingImpl);
isolate->SetWasmStreamingCallback(StreamFromResponseCallback);
}
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h b/chromium/third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h
index d99a786916b..8cbe4da1d0b 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h
@@ -91,9 +91,14 @@ class LocalWindowProxyManager
: public WindowProxyManagerImplHelper<LocalFrame, LocalWindowProxy> {
public:
static LocalWindowProxyManager* Create(LocalFrame& frame) {
- return new LocalWindowProxyManager(frame);
+ return MakeGarbageCollected<LocalWindowProxyManager>(frame);
}
+ explicit LocalWindowProxyManager(LocalFrame& frame)
+ : WindowProxyManagerImplHelper<LocalFrame, LocalWindowProxy>(
+ frame,
+ FrameType::kLocal) {}
+
// TODO(yukishiino): Remove this method.
LocalWindowProxy* MainWorldProxyMaybeUninitialized() {
return static_cast<LocalWindowProxy*>(window_proxy_.Get());
@@ -102,22 +107,15 @@ class LocalWindowProxyManager
// Sets the given security origin to the main world's context. Also updates
// the security origin of the context for each isolated world.
void UpdateSecurityOrigin(const SecurityOrigin*);
-
- private:
- explicit LocalWindowProxyManager(LocalFrame& frame)
- : WindowProxyManagerImplHelper<LocalFrame, LocalWindowProxy>(
- frame,
- FrameType::kLocal) {}
};
class RemoteWindowProxyManager
: public WindowProxyManagerImplHelper<RemoteFrame, RemoteWindowProxy> {
public:
static RemoteWindowProxyManager* Create(RemoteFrame& frame) {
- return new RemoteWindowProxyManager(frame);
+ return MakeGarbageCollected<RemoteWindowProxyManager>(frame);
}
- private:
explicit RemoteWindowProxyManager(RemoteFrame& frame)
: WindowProxyManagerImplHelper<RemoteFrame, RemoteWindowProxy>(
frame,
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.cc b/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.cc
index 3746a1fe999..bf65386a40c 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.cc
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.cc
@@ -95,7 +95,8 @@ class WorkerOrWorkletScriptController::ExecutionState final {
WorkerOrWorkletScriptController* WorkerOrWorkletScriptController::Create(
WorkerOrWorkletGlobalScope* global_scope,
v8::Isolate* isolate) {
- return new WorkerOrWorkletScriptController(global_scope, isolate);
+ return MakeGarbageCollected<WorkerOrWorkletScriptController>(global_scope,
+ isolate);
}
WorkerOrWorkletScriptController::WorkerOrWorkletScriptController(
@@ -153,7 +154,7 @@ bool WorkerOrWorkletScriptController::InitializeContextIfNeeded(
const WrapperTypeInfo* wrapper_type_info =
script_wrappable->GetWrapperTypeInfo();
v8::Local<v8::FunctionTemplate> global_interface_template =
- wrapper_type_info->domTemplate(isolate_, *world_);
+ wrapper_type_info->DomTemplate(isolate_, *world_);
if (global_interface_template.IsEmpty())
return false;
v8::Local<v8::ObjectTemplate> global_template =
@@ -161,17 +162,8 @@ bool WorkerOrWorkletScriptController::InitializeContextIfNeeded(
v8::Local<v8::Context> context;
{
// Initialize V8 extensions before creating the context.
- Vector<const char*> extension_names;
- if (global_scope_->IsServiceWorkerGlobalScope() &&
- Platform::Current()->AllowScriptExtensionForServiceWorker(
- ToWorkerGlobalScope(global_scope_.Get())->Url())) {
- const V8Extensions& extensions = ScriptController::RegisteredExtensions();
- extension_names.ReserveInitialCapacity(extensions.size());
- for (const auto* extension : extensions)
- extension_names.push_back(extension->name());
- }
- v8::ExtensionConfiguration extension_configuration(extension_names.size(),
- extension_names.data());
+ v8::ExtensionConfiguration extension_configuration =
+ ScriptController::ExtensionsFor(global_scope_);
V8PerIsolateData::UseCounterDisabledScope use_counter_disabled(
V8PerIsolateData::From(isolate_));
@@ -185,8 +177,6 @@ bool WorkerOrWorkletScriptController::InitializeContextIfNeeded(
ScriptState::Scope scope(script_state_);
- InitializeV8ExtrasBinding(script_state_);
-
// Associate the global proxy object, the global object and the worker
// instance (C++ object) as follows.
//
@@ -255,18 +245,22 @@ bool WorkerOrWorkletScriptController::InitializeContextIfNeeded(
disable_eval_pending_ = String();
}
+ // This can only be called after the global object is fully initialised, as it
+ // reads values from it.
+ InitializeV8ExtrasBinding(script_state_);
+
return true;
}
ScriptValue WorkerOrWorkletScriptController::EvaluateInternal(
const ScriptSourceCode& source_code,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
V8CacheOptions v8_cache_options) {
DCHECK(IsContextInitialized());
TRACE_EVENT1("devtools.timeline", "EvaluateScript", "data",
- InspectorEvaluateScriptEvent::Data(nullptr, source_code.Url(),
- source_code.StartPosition()));
+ inspector_evaluate_script_event::Data(
+ nullptr, source_code.Url(), source_code.StartPosition()));
ScriptState::Scope scope(script_state_);
@@ -284,7 +278,7 @@ ScriptValue WorkerOrWorkletScriptController::EvaluateInternal(
std::tie(compile_options, produce_cache_options, no_cache_reason) =
V8CodeCache::GetCompileOptions(v8_cache_options, source_code);
if (V8ScriptRunner::CompileScript(script_state_, source_code,
- access_control_status, compile_options,
+ sanitize_script_errors, compile_options,
no_cache_reason, referrer_info)
.ToLocal(&compiled_script)) {
maybe_result = V8ScriptRunner::RunCompiledScript(isolate_, compiled_script,
@@ -319,14 +313,14 @@ ScriptValue WorkerOrWorkletScriptController::EvaluateInternal(
bool WorkerOrWorkletScriptController::Evaluate(
const ScriptSourceCode& source_code,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
ErrorEvent** error_event,
V8CacheOptions v8_cache_options) {
if (IsExecutionForbidden())
return false;
ExecutionState state(this);
- EvaluateInternal(source_code, access_control_status, v8_cache_options);
+ EvaluateInternal(source_code, sanitize_script_errors, v8_cache_options);
if (IsExecutionForbidden())
return false;
@@ -338,17 +332,15 @@ bool WorkerOrWorkletScriptController::Evaluate(
*error_event = state.error_event_from_imported_script_.Release();
return false;
}
- if (global_scope_->ShouldSanitizeScriptError(state.location_->Url(),
- access_control_status)) {
- *error_event = ErrorEvent::CreateSanitizedError(world_.get());
+ if (sanitize_script_errors == SanitizeScriptErrors::kSanitize) {
+ *error_event = ErrorEvent::CreateSanitizedError(script_state_);
} else {
*error_event =
ErrorEvent::Create(state.error_message, state.location_->Clone(),
state.exception, world_.get());
}
} else {
- DCHECK(!global_scope_->ShouldSanitizeScriptError(state.location_->Url(),
- access_control_status));
+ DCHECK_EQ(sanitize_script_errors, SanitizeScriptErrors::kDoNotSanitize);
ErrorEvent* event = nullptr;
if (state.error_event_from_imported_script_) {
event = state.error_event_from_imported_script_.Release();
@@ -357,7 +349,7 @@ bool WorkerOrWorkletScriptController::Evaluate(
ErrorEvent::Create(state.error_message, state.location_->Clone(),
state.exception, world_.get());
}
- global_scope_->DispatchErrorEvent(event, access_control_status);
+ global_scope_->DispatchErrorEvent(event, sanitize_script_errors);
}
return false;
}
@@ -367,7 +359,8 @@ bool WorkerOrWorkletScriptController::Evaluate(
ScriptValue WorkerOrWorkletScriptController::EvaluateAndReturnValueForTest(
const ScriptSourceCode& source_code) {
ExecutionState state(this);
- return EvaluateInternal(source_code, kOpaqueResource, kV8CacheOptionsDefault);
+ return EvaluateInternal(source_code, SanitizeScriptErrors::kSanitize,
+ kV8CacheOptionsDefault);
}
void WorkerOrWorkletScriptController::ForbidExecution() {
@@ -387,11 +380,10 @@ void WorkerOrWorkletScriptController::DisableEval(const String& error_message) {
void WorkerOrWorkletScriptController::RethrowExceptionFromImportedScript(
ErrorEvent* error_event,
ExceptionState& exception_state) {
- const String& error_message = error_event->message();
if (execution_state_)
execution_state_->error_event_from_imported_script_ = error_event;
exception_state.RethrowV8Exception(
- V8ThrowException::CreateError(isolate_, error_message));
+ error_event->error(script_state_).V8ValueFor(script_state_));
}
void WorkerOrWorkletScriptController::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h b/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h
index 0f01f1c2d02..57718e0f255 100644
--- a/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h
+++ b/chromium/third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h
@@ -32,11 +32,11 @@
#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_WORKER_OR_WORKLET_SCRIPT_CONTROLLER_H_
#include "third_party/blink/renderer/bindings/core/v8/rejected_promises.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "v8/include/v8.h"
@@ -55,6 +55,8 @@ class CORE_EXPORT WorkerOrWorkletScriptController final
public:
static WorkerOrWorkletScriptController* Create(WorkerOrWorkletGlobalScope*,
v8::Isolate*);
+
+ WorkerOrWorkletScriptController(WorkerOrWorkletGlobalScope*, v8::Isolate*);
virtual ~WorkerOrWorkletScriptController();
void Dispose();
@@ -62,7 +64,7 @@ class CORE_EXPORT WorkerOrWorkletScriptController final
// Returns true if the evaluation completed with no uncaught exception.
bool Evaluate(const ScriptSourceCode&,
- AccessControlStatus access_control_status,
+ SanitizeScriptErrors sanitize_script_errors,
ErrorEvent** = nullptr,
V8CacheOptions = kV8CacheOptionsDefault);
@@ -104,12 +106,11 @@ class CORE_EXPORT WorkerOrWorkletScriptController final
ScriptValue EvaluateAndReturnValueForTest(const ScriptSourceCode&);
private:
- WorkerOrWorkletScriptController(WorkerOrWorkletGlobalScope*, v8::Isolate*);
class ExecutionState;
// Evaluate a script file in the current execution environment.
ScriptValue EvaluateInternal(const ScriptSourceCode&,
- AccessControlStatus,
+ SanitizeScriptErrors,
V8CacheOptions);
void DisposeContextIfNeeded();
diff --git a/chromium/third_party/blink/renderer/bindings/modules/BUILD.gn b/chromium/third_party/blink/renderer/bindings/modules/BUILD.gn
index e35eaba33e3..09fafc74618 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/BUILD.gn
+++ b/chromium/third_party/blink/renderer/bindings/modules/BUILD.gn
@@ -2,9 +2,9 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import("//third_party/blink/renderer/modules/modules.gni")
import("//third_party/blink/renderer/bindings/scripts/scripts.gni")
import("//third_party/blink/renderer/build/scripts/scripts.gni")
+import("//third_party/blink/renderer/modules/modules.gni")
group("bindings_modules_generated") {
visibility = [ "//third_party/blink/*" ]
@@ -28,6 +28,8 @@ generate_event_interfaces("modules_bindings_generated_event_interfaces") {
"//third_party/blink/renderer/modules/device_orientation/device_orientation_event.idl",
"//third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.idl",
"//third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.idl",
+ "//third_party/blink/renderer/modules/gamepad/gamepad_axis_event.idl",
+ "//third_party/blink/renderer/modules/gamepad/gamepad_button_event.idl",
"//third_party/blink/renderer/modules/gamepad/gamepad_event.idl",
"//third_party/blink/renderer/modules/indexeddb/idb_version_change_event.idl",
"//third_party/blink/renderer/modules/mediarecorder/blob_event.idl",
@@ -66,28 +68,23 @@ generate_event_interfaces("modules_bindings_generated_event_interfaces") {
"//third_party/blink/renderer/modules/xr/xr_input_source_event.idl",
"//third_party/blink/renderer/modules/xr/xr_session_event.idl",
]
- output_file = "event_modules_names.json5"
+
+ output_file = "modules/event_interface_modules_names.json5"
suffix = "Modules"
}
make_event_factory("event_modules") {
visibility = [ ":*" ]
- in_files =
- [ "$root_gen_dir/third_party/blink/renderer/event_modules_names.json5" ]
+ in_files = [ "$blink_modules_output_dir/event_interface_modules_names.json5" ]
outputs = [
"$blink_modules_output_dir/event_modules_factory.cc",
]
deps = make_core_generated_deps + [ "//third_party/blink/renderer/bindings/modules:modules_bindings_generated_event_interfaces" ]
- deps += [
- "//device/gamepad/public/mojom:mojom_blink",
- "//media/midi:mojo_blink",
- ]
}
make_names("event_modules_names") {
visibility = [ ":*" ]
- in_files =
- [ "$root_gen_dir/third_party/blink/renderer/event_modules_names.json5" ]
+ in_files = [ "$blink_modules_output_dir/event_interface_modules_names.json5" ]
output_dir = blink_modules_output_dir
deps = make_core_generated_deps + [ "//third_party/blink/renderer/bindings/modules:modules_bindings_generated_event_interfaces" ]
}
@@ -197,6 +194,8 @@ source_set("generated") {
":event_modules",
":event_modules_names",
":event_target_modules_names",
+ "//media/midi:mojo_blink_headers",
+ "//third_party/blink/public/mojom:mojom_modules_blink_headers",
"//third_party/blink/renderer/core",
"//third_party/blink/renderer/platform/wtf",
"//v8",
@@ -204,8 +203,16 @@ source_set("generated") {
}
generate_web_idl_collection("modules_web_idl_collection") {
- sources = modules_definition_idl_files + modules_dependency_idl_files
- output = "WebIdlCollectionForModules.pickle"
+ # |sources| contains all IDL files under modules/.
+ sources = modules_definition_idl_files + modules_static_interface_idl_files +
+ modules_all_dependency_idl_files
+ output = "web_idl_collection_for_modules.pickle"
component = "modules"
output_dir = bindings_modules_output_dir
+
+ deps = [
+ "//third_party/blink/renderer/bindings/modules:modules_core_global_constructors_idls",
+ "//third_party/blink/renderer/bindings/modules:modules_global_constructors_idls",
+ "//third_party/blink/renderer/bindings/modules/v8:bindings_modules_origin_trial_features",
+ ]
}
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/BUILD.gn b/chromium/third_party/blink/renderer/bindings/modules/v8/BUILD.gn
index 47a5d5372d1..2ca7b7e007c 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/BUILD.gn
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/BUILD.gn
@@ -99,10 +99,15 @@ group("generate_mojo_bindings") {
"//device/usb/public/mojom:mojom_blink_headers",
"//device/vr/public/mojom:mojom_blink_headers",
"//media/capture/mojom:image_capture_blink_headers",
+ "//media/midi:mojo_blink_headers",
"//services/device/public/mojom:generic_sensor_headers",
"//services/device/public/mojom:mojom_blink_headers",
"//services/shape_detection/public/mojom:mojom_blink_headers",
"//third_party/blink/public:media_devices_mojo_bindings_blink_headers",
+
+ # IndexedDB Mojom Blink headers are provided by the mojom_modules
+ # target.
+ "//third_party/blink/public/mojom:mojom_modules_blink_headers",
]
}
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/custom/v8_extendable_message_event_custom.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/custom/v8_extendable_message_event_custom.cc
index 3f85f75499d..70ffc789015 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/custom/v8_extendable_message_event_custom.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/custom/v8_extendable_message_event_custom.cc
@@ -10,7 +10,7 @@
namespace blink {
-void V8ExtendableMessageEvent::constructorCustom(
+void V8ExtendableMessageEvent::ConstructorCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ExceptionState exception_state(isolate, ExceptionState::kConstructionContext,
@@ -25,7 +25,8 @@ void V8ExtendableMessageEvent::constructorCustom(
if (!type.Prepare())
return;
- ExtendableMessageEventInit event_init_dict;
+ ExtendableMessageEventInit* event_init_dict =
+ ExtendableMessageEventInit::Create();
if (!IsUndefinedOrNull(info[1])) {
if (!info[1]->IsObject()) {
exception_state.ThrowTypeError(
@@ -42,12 +43,12 @@ void V8ExtendableMessageEvent::constructorCustom(
ExtendableMessageEvent::Create(type, event_init_dict);
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->AssociateWithWrapper(
- isolate, &V8ExtendableMessageEvent::wrapperTypeInfo, wrapper);
+ isolate, &V8ExtendableMessageEvent::wrapper_type_info, wrapper);
// TODO(bashi): Workaround for http://crbug.com/529941. We need to store
// |data| as a private value to avoid cyclic references.
- if (event_init_dict.hasData()) {
- v8::Local<v8::Value> v8_data = event_init_dict.data().V8Value();
+ if (event_init_dict->hasData()) {
+ v8::Local<v8::Value> v8_data = event_init_dict->data().V8Value();
V8PrivateProperty::GetMessageEventCachedData(isolate).Set(wrapper, v8_data);
if (DOMWrapperWorld::Current(isolate).IsIsolatedWorld()) {
impl->SetSerializedData(
@@ -58,7 +59,7 @@ void V8ExtendableMessageEvent::constructorCustom(
V8SetReturnValue(info, wrapper);
}
-void V8ExtendableMessageEvent::dataAttributeGetterCustom(
+void V8ExtendableMessageEvent::DataAttributeGetterCustom(
const v8::FunctionCallbackInfo<v8::Value>& info) {
ExtendableMessageEvent* event =
V8ExtendableMessageEvent::ToImpl(info.Holder());
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc
index 16098233b65..88e2a40ff26 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.cc
@@ -21,11 +21,12 @@
namespace blink {
ScriptWrappable* V8ScriptValueDeserializerForModules::ReadDOMObject(
- SerializationTag tag) {
+ SerializationTag tag,
+ ExceptionState& exception_state) {
// Give the core/ implementation a chance to try first.
// If it didn't recognize the kind of wrapper, try the modules types.
if (ScriptWrappable* wrappable =
- V8ScriptValueDeserializer::ReadDOMObject(tag))
+ V8ScriptValueDeserializer::ReadDOMObject(tag, exception_state))
return wrappable;
switch (tag) {
@@ -58,7 +59,7 @@ ScriptWrappable* V8ScriptValueDeserializerForModules::ReadDOMObject(
certificate_generator->FromPEM(pem_private_key, pem_certificate);
if (!certificate)
return nullptr;
- return new RTCCertificate(std::move(certificate));
+ return MakeGarbageCollected<RTCCertificate>(std::move(certificate));
}
case kDetectedBarcodeTag: {
String raw_value;
@@ -70,10 +71,10 @@ ScriptWrappable* V8ScriptValueDeserializerForModules::ReadDOMObject(
uint32_t corner_points_length;
if (!ReadUint32(&corner_points_length))
return nullptr;
- HeapVector<Point2D> corner_points;
+ HeapVector<Member<Point2D>> corner_points;
for (uint32_t i = 0; i < corner_points_length; i++) {
- Point2D point;
- if (!ReadPoint2D(&point))
+ Point2D* point = Point2D::Create();
+ if (!ReadPoint2D(point))
return nullptr;
corner_points.push_back(point);
}
@@ -86,10 +87,10 @@ ScriptWrappable* V8ScriptValueDeserializerForModules::ReadDOMObject(
uint32_t landmarks_length;
if (!ReadUint32(&landmarks_length))
return nullptr;
- HeapVector<Landmark> landmarks;
+ HeapVector<Member<Landmark>> landmarks;
for (uint32_t i = 0; i < landmarks_length; i++) {
- Landmark landmark;
- if (!ReadLandmark(&landmark))
+ Landmark* landmark = Landmark::Create();
+ if (!ReadLandmark(landmark))
return nullptr;
landmarks.push_back(landmark);
}
@@ -105,10 +106,10 @@ ScriptWrappable* V8ScriptValueDeserializerForModules::ReadDOMObject(
uint32_t corner_points_length;
if (!ReadUint32(&corner_points_length))
return nullptr;
- HeapVector<Point2D> corner_points;
+ HeapVector<Member<Point2D>> corner_points;
for (uint32_t i = 0; i < corner_points_length; i++) {
- Point2D point;
- if (!ReadPoint2D(&point))
+ Point2D* point = Point2D::Create();
+ if (!ReadPoint2D(point))
return nullptr;
corner_points.push_back(point);
}
@@ -355,10 +356,10 @@ bool V8ScriptValueDeserializerForModules::ReadLandmark(Landmark* landmark) {
uint32_t locations_length;
if (!ReadUint32(&locations_length))
return false;
- HeapVector<Point2D> locations;
+ HeapVector<Member<Point2D>> locations;
for (uint32_t i = 0; i < locations_length; i++) {
- Point2D location;
- if (!ReadPoint2D(&location))
+ Point2D* location = Point2D::Create();
+ if (!ReadPoint2D(location))
return false;
locations.push_back(location);
}
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h
index eab1e1fce3c..fa33ae1ece7 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_deserializer_for_modules.h
@@ -33,7 +33,7 @@ class MODULES_EXPORT V8ScriptValueDeserializerForModules final
: V8ScriptValueDeserializer(script_state, std::move(value), options) {}
protected:
- ScriptWrappable* ReadDOMObject(SerializationTag) override;
+ ScriptWrappable* ReadDOMObject(SerializationTag, ExceptionState&) override;
private:
bool ReadOneByte(uint8_t* byte) {
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc
index 00efd238e56..0e3011dfbdc 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules.cc
@@ -31,11 +31,11 @@ bool V8ScriptValueSerializerForModules::WriteDOMObject(
return false;
const WrapperTypeInfo* wrapper_type_info = wrappable->GetWrapperTypeInfo();
- if (wrapper_type_info == &V8CryptoKey::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8CryptoKey::wrapper_type_info) {
return WriteCryptoKey(wrappable->ToImpl<CryptoKey>()->Key(),
exception_state);
}
- if (wrapper_type_info == &V8DOMFileSystem::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DOMFileSystem::wrapper_type_info) {
DOMFileSystem* fs = wrappable->ToImpl<DOMFileSystem>();
if (!fs->Clonable()) {
exception_state.ThrowDOMException(
@@ -50,7 +50,7 @@ bool V8ScriptValueSerializerForModules::WriteDOMObject(
WriteUTF8String(fs->RootURL().GetString());
return true;
}
- if (wrapper_type_info == &V8RTCCertificate::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8RTCCertificate::wrapper_type_info) {
RTCCertificate* certificate = wrappable->ToImpl<RTCCertificate>();
rtc::RTCCertificatePEM pem = certificate->Certificate()->ToPEM();
WriteTag(kRTCCertificateTag);
@@ -58,7 +58,7 @@ bool V8ScriptValueSerializerForModules::WriteDOMObject(
WriteUTF8String(pem.certificate().c_str());
return true;
}
- if (wrapper_type_info == &V8DetectedBarcode::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DetectedBarcode::wrapper_type_info) {
DetectedBarcode* detected_barcode = wrappable->ToImpl<DetectedBarcode>();
WriteTag(kDetectedBarcodeTag);
WriteUTF8String(detected_barcode->rawValue());
@@ -67,15 +67,16 @@ bool V8ScriptValueSerializerForModules::WriteDOMObject(
WriteDouble(bounding_box->y());
WriteDouble(bounding_box->width());
WriteDouble(bounding_box->height());
- const HeapVector<Point2D>& corner_points = detected_barcode->cornerPoints();
+ const HeapVector<Member<Point2D>>& corner_points =
+ detected_barcode->cornerPoints();
WriteUint32(static_cast<uint32_t>(corner_points.size()));
for (const auto& corner_point : corner_points) {
- WriteDouble(corner_point.x());
- WriteDouble(corner_point.y());
+ WriteDouble(corner_point->x());
+ WriteDouble(corner_point->y());
}
return true;
}
- if (wrapper_type_info == &V8DetectedFace::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DetectedFace::wrapper_type_info) {
DetectedFace* detected_face = wrappable->ToImpl<DetectedFace>();
WriteTag(kDetectedFaceTag);
DOMRectReadOnly* bounding_box = detected_face->boundingBox();
@@ -83,20 +84,20 @@ bool V8ScriptValueSerializerForModules::WriteDOMObject(
WriteDouble(bounding_box->y());
WriteDouble(bounding_box->width());
WriteDouble(bounding_box->height());
- const HeapVector<Landmark>& landmarks = detected_face->landmarks();
+ const HeapVector<Member<Landmark>>& landmarks = detected_face->landmarks();
WriteUint32(static_cast<uint32_t>(landmarks.size()));
for (const auto& landmark : landmarks) {
- WriteUTF8String(landmark.type());
- const HeapVector<Point2D>& locations = landmark.locations();
+ WriteUTF8String(landmark->type());
+ const HeapVector<Member<Point2D>>& locations = landmark->locations();
WriteUint32(static_cast<uint32_t>(locations.size()));
for (const auto& location : locations) {
- WriteDouble(location.x());
- WriteDouble(location.y());
+ WriteDouble(location->x());
+ WriteDouble(location->y());
}
}
return true;
}
- if (wrapper_type_info == &V8DetectedText::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8DetectedText::wrapper_type_info) {
DetectedText* detected_text = wrappable->ToImpl<DetectedText>();
WriteTag(kDetectedTextTag);
WriteUTF8String(detected_text->rawValue());
@@ -105,11 +106,12 @@ bool V8ScriptValueSerializerForModules::WriteDOMObject(
WriteDouble(bounding_box->y());
WriteDouble(bounding_box->width());
WriteDouble(bounding_box->height());
- const HeapVector<Point2D>& corner_points = detected_text->cornerPoints();
+ const HeapVector<Member<Point2D>>& corner_points =
+ detected_text->cornerPoints();
WriteUint32(static_cast<uint32_t>(corner_points.size()));
for (const auto& corner_point : corner_points) {
- WriteDouble(corner_point.x());
- WriteDouble(corner_point.y());
+ WriteDouble(corner_point->x());
+ WriteDouble(corner_point->y());
}
return true;
}
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc
index 8f5ffd39b55..57d8c4a59d5 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/serialization/v8_script_value_serializer_for_modules_test.cc
@@ -166,13 +166,14 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripRTCCertificate) {
WebString::FromUTF8(kEcdsaPrivateKey, sizeof(kEcdsaPrivateKey)),
WebString::FromUTF8(kEcdsaCertificate, sizeof(kEcdsaCertificate)));
ASSERT_TRUE(web_certificate);
- RTCCertificate* certificate = new RTCCertificate(std::move(web_certificate));
+ RTCCertificate* certificate =
+ MakeGarbageCollected<RTCCertificate>(std::move(web_certificate));
// Round trip test.
v8::Local<v8::Value> wrapper =
ToV8(certificate, scope.GetContext()->Global(), scope.GetIsolate());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
- ASSERT_TRUE(V8RTCCertificate::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8RTCCertificate::HasInstance(result, scope.GetIsolate()));
RTCCertificate* new_certificate =
V8RTCCertificate::ToImpl(result.As<v8::Object>());
rtc::RTCCertificatePEM pem = new_certificate->Certificate()->ToPEM();
@@ -199,7 +200,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeRTCCertificate) {
// Decode test.
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8RTCCertificate::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8RTCCertificate::HasInstance(result, scope.GetIsolate()));
RTCCertificate* new_certificate =
V8RTCCertificate::ToImpl(result.As<v8::Object>());
rtc::RTCCertificatePEM pem = new_certificate->Certificate()->ToPEM();
@@ -407,7 +408,7 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripCryptoKeyAES) {
// Round trip it and check the visible attributes.
v8::Local<v8::Value> wrapper = ToV8(key, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("secret", new_key->type());
EXPECT_TRUE(new_key->extractable());
@@ -444,7 +445,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeCryptoKeyAES) {
0x70, 0xa2, 0xae, 0x98, 0x79, 0x1b, 0xc5, 0xf7});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("secret", new_key->type());
EXPECT_FALSE(new_key->extractable());
@@ -479,7 +480,7 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripCryptoKeyHMAC) {
// Round trip it and check the visible attributes.
v8::Local<v8::Value> wrapper = ToV8(key, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("secret", new_key->type());
EXPECT_TRUE(new_key->extractable());
@@ -517,7 +518,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeCryptoKeyHMAC) {
0x85, 0xaf, 0x41, 0xc4, 0x6a, 0x2d, 0x06, 0x7a});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("secret", new_key->type());
EXPECT_FALSE(new_key->extractable());
@@ -554,7 +555,7 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripCryptoKeyRSAHashed) {
// Round trip the private key and check the visible attributes.
v8::Local<v8::Value> wrapper = ToV8(private_key, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_private_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("private", new_private_key->type());
EXPECT_TRUE(new_private_key->extractable());
@@ -600,7 +601,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeCryptoKeyRSAHashed) {
0xb1, 0x19, 0x24, 0xae, 0x8d, 0x22, 0xb5, 0x02, 0x03, 0x01, 0x00, 0x01});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_public_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("public", new_public_key->type());
EXPECT_TRUE(new_public_key->extractable());
@@ -645,7 +646,7 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripCryptoKeyEC) {
// Round trip the private key and check the visible attributes.
v8::Local<v8::Value> wrapper = ToV8(private_key, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_private_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("private", new_private_key->type());
EXPECT_TRUE(new_private_key->extractable());
@@ -686,7 +687,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeCryptoKeyEC) {
0x0e, 0x1c, 0x31, 0x5a, 0xaa, 0x2d});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_public_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("public", new_public_key->type());
EXPECT_TRUE(new_public_key->extractable());
@@ -721,7 +722,7 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripCryptoKeyNoParams) {
// Round trip the key and check the visible attributes.
v8::Local<v8::Value> wrapper = ToV8(key, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("secret", new_key->type());
EXPECT_FALSE(new_key->extractable());
@@ -751,7 +752,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeCryptoKeyNoParams) {
0x03, 0x01, 0x02, 0x03, 0x00});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8CryptoKey::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8CryptoKey::HasInstance(result, scope.GetIsolate()));
CryptoKey* new_key = V8CryptoKey::ToImpl(result.As<v8::Object>());
EXPECT_EQ("secret", new_key->type());
EXPECT_FALSE(new_key->extractable());
@@ -902,7 +903,7 @@ TEST(V8ScriptValueSerializerForModulesTest, RoundTripDOMFileSystem) {
v8::Local<v8::Value> wrapper = ToV8(fs, scope.GetScriptState());
v8::Local<v8::Value> result = RoundTripForModules(wrapper, scope);
ASSERT_FALSE(result.IsEmpty());
- ASSERT_TRUE(V8DOMFileSystem::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMFileSystem::HasInstance(result, scope.GetIsolate()));
DOMFileSystem* new_fs = V8DOMFileSystem::ToImpl(result.As<v8::Object>());
EXPECT_EQ("http_example.com_0:Persistent", new_fs->name());
EXPECT_EQ(mojom::blink::FileSystemType::kPersistent, new_fs->GetType());
@@ -945,7 +946,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeDOMFileSystem) {
// Decode test.
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8DOMFileSystem::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DOMFileSystem::HasInstance(result, scope.GetIsolate()));
DOMFileSystem* new_fs = V8DOMFileSystem::ToImpl(result.As<v8::Object>());
EXPECT_EQ("http_example.com_0:Persistent", new_fs->name());
EXPECT_EQ(mojom::blink::FileSystemType::kPersistent, new_fs->GetType());
@@ -987,7 +988,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedBarcode) {
0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8DetectedBarcode::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DetectedBarcode::HasInstance(result, scope.GetIsolate()));
DetectedBarcode* detected_barcode =
V8DetectedBarcode::ToImpl(result.As<v8::Object>());
EXPECT_EQ("text", detected_barcode->rawValue());
@@ -996,10 +997,11 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedBarcode) {
EXPECT_EQ(2, bounding_box->y());
EXPECT_EQ(3, bounding_box->width());
EXPECT_EQ(4, bounding_box->height());
- const HeapVector<Point2D>& corner_points = detected_barcode->cornerPoints();
+ const HeapVector<Member<Point2D>>& corner_points =
+ detected_barcode->cornerPoints();
EXPECT_EQ(1u, corner_points.size());
- EXPECT_EQ(1, corner_points[0].x());
- EXPECT_EQ(2, corner_points[0].y());
+ EXPECT_EQ(1, corner_points[0]->x());
+ EXPECT_EQ(2, corner_points[0]->y());
}
TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedFace) {
@@ -1013,20 +1015,20 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedFace) {
0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8DetectedFace::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DetectedFace::HasInstance(result, scope.GetIsolate()));
DetectedFace* detected_face = V8DetectedFace::ToImpl(result.As<v8::Object>());
DOMRectReadOnly* bounding_box = detected_face->boundingBox();
EXPECT_EQ(1, bounding_box->x());
EXPECT_EQ(2, bounding_box->y());
EXPECT_EQ(3, bounding_box->width());
EXPECT_EQ(4, bounding_box->height());
- const HeapVector<Landmark>& landmarks = detected_face->landmarks();
+ const HeapVector<Member<Landmark>>& landmarks = detected_face->landmarks();
EXPECT_EQ(1u, landmarks.size());
- EXPECT_EQ("eye", landmarks[0].type());
- const HeapVector<Point2D>& locations = landmarks[0].locations();
+ EXPECT_EQ("eye", landmarks[0]->type());
+ const HeapVector<Member<Point2D>>& locations = landmarks[0]->locations();
EXPECT_EQ(1u, locations.size());
- EXPECT_EQ(1, locations[0].x());
- EXPECT_EQ(2, locations[0].y());
+ EXPECT_EQ(1, locations[0]->x());
+ EXPECT_EQ(2, locations[0]->y());
}
TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedText) {
@@ -1040,7 +1042,7 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedText) {
0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40});
v8::Local<v8::Value> result =
V8ScriptValueDeserializerForModules(script_state, input).Deserialize();
- ASSERT_TRUE(V8DetectedText::hasInstance(result, scope.GetIsolate()));
+ ASSERT_TRUE(V8DetectedText::HasInstance(result, scope.GetIsolate()));
DetectedText* detected_text = V8DetectedText::ToImpl(result.As<v8::Object>());
EXPECT_EQ("text", detected_text->rawValue());
DOMRectReadOnly* bounding_box = detected_text->boundingBox();
@@ -1048,10 +1050,11 @@ TEST(V8ScriptValueSerializerForModulesTest, DecodeDetectedText) {
EXPECT_EQ(2, bounding_box->y());
EXPECT_EQ(3, bounding_box->width());
EXPECT_EQ(4, bounding_box->height());
- const HeapVector<Point2D>& corner_points = detected_text->cornerPoints();
+ const HeapVector<Member<Point2D>>& corner_points =
+ detected_text->cornerPoints();
EXPECT_EQ(1u, corner_points.size());
- EXPECT_EQ(1, corner_points[0].x());
- EXPECT_EQ(2, corner_points[0].y());
+ EXPECT_EQ(1, corner_points[0]->x());
+ EXPECT_EQ(2, corner_points[0]->y());
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc
index 11f1bcdd522..8ae7cf65e24 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc
@@ -84,7 +84,7 @@ v8::Local<v8::Value> ToV8(const IDBKey* key,
// values as undefined, rather than the more typical (for DOM) null.
// This appears on the |upper| and |lower| attributes of IDBKeyRange.
// Spec: http://www.w3.org/TR/IndexedDB/#idl-def-IDBKeyRange
- return V8Undefined();
+ return v8::Local<v8::Value>();
}
v8::Local<v8::Context> context = isolate->GetCurrentContext();
@@ -93,7 +93,7 @@ v8::Local<v8::Value> ToV8(const IDBKey* key,
case IDBKey::kInvalidType:
case IDBKey::kTypeEnumMax:
NOTREACHED();
- return V8Undefined();
+ return v8::Local<v8::Value>();
case IDBKey::kNumberType:
return v8::Number::New(isolate, key->Number());
case IDBKey::kStringType:
@@ -111,15 +111,18 @@ v8::Local<v8::Value> ToV8(const IDBKey* key,
ToV8(key->Array()[i].get(), creation_context, isolate);
if (value.IsEmpty())
value = v8::Undefined(isolate);
- if (!V8CallBoolean(array->CreateDataProperty(context, i, value)))
- return V8Undefined();
+ bool created_property;
+ if (!array->CreateDataProperty(context, i, value)
+ .To(&created_property) ||
+ !created_property)
+ return v8::Local<v8::Value>();
}
return array;
}
}
NOTREACHED();
- return V8Undefined();
+ return v8::Local<v8::Value>();
}
// IDBAny is a variant type used to hold the values produced by the |result|
@@ -219,7 +222,12 @@ static std::unique_ptr<IDBKey> CreateIDBKeyFromValue(
v8::TryCatch block(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (uint32_t i = 0; i < length; ++i) {
- if (!V8CallBoolean(array->HasOwnProperty(context, i)))
+ bool has_own_property;
+ if (!array->HasOwnProperty(context, i).To(&has_own_property)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return nullptr;
+ }
+ if (!has_own_property)
return nullptr;
v8::Local<v8::Value> item;
if (!array->Get(context, i).ToLocal(&item)) {
@@ -262,9 +270,9 @@ static bool IsImplicitProperty(v8::Isolate* isolate,
return true;
if (value->IsArray() && name == "length")
return true;
- if (V8Blob::hasInstance(value, isolate))
+ if (V8Blob::HasInstance(value, isolate))
return name == "size" || name == "type";
- if (V8File::hasInstance(value, isolate))
+ if (V8File::HasInstance(value, isolate))
return name == "name" || name == "lastModified" ||
name == "lastModifiedDate";
return false;
@@ -313,7 +321,7 @@ static std::unique_ptr<IDBKey> CreateIDBKeyFromValueAndKeyPath(
return nullptr;
v8::Local<v8::Object> object = v8_value.As<v8::Object>();
- if (V8Blob::hasInstance(object, isolate)) {
+ if (V8Blob::HasInstance(object, isolate)) {
if (element == "size") {
v8_value = v8::Number::New(isolate, V8Blob::ToImpl(object)->size());
continue;
@@ -325,7 +333,7 @@ static std::unique_ptr<IDBKey> CreateIDBKeyFromValueAndKeyPath(
// Fall through.
}
- if (V8File::hasInstance(object, isolate)) {
+ if (V8File::HasInstance(object, isolate)) {
if (element == "name") {
v8_value = V8String(isolate, V8File::ToImpl(object)->name());
continue;
@@ -345,7 +353,12 @@ static std::unique_ptr<IDBKey> CreateIDBKeyFromValueAndKeyPath(
}
v8::Local<v8::String> key = V8String(isolate, element);
- if (!V8CallBoolean(object->HasOwnProperty(context, key)))
+ bool has_own_property;
+ if (!object->HasOwnProperty(context, key).To(&has_own_property)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return nullptr;
+ }
+ if (!has_own_property)
return nullptr;
if (!object->Get(context, key).ToLocal(&v8_value)) {
exception_state.RethrowV8Exception(block.Exception());
@@ -447,8 +460,11 @@ static v8::Local<v8::Value> DeserializeIDBValueArray(
DeserializeIDBValue(isolate, creation_context, values[i].get());
if (v8_value.IsEmpty())
v8_value = v8::Undefined(isolate);
- if (!V8CallBoolean(array->CreateDataProperty(context, i, v8_value)))
- return V8Undefined();
+ bool created_property;
+ if (!array->CreateDataProperty(context, i, v8_value)
+ .To(&created_property) ||
+ !created_property)
+ return v8::Local<v8::Value>();
}
return array;
@@ -462,7 +478,7 @@ static v8::Local<v8::Value> DeserializeIDBValueArray(
// the conceptual description in the spec states that the key produced by the
// key generator is injected into the value before it is written to IndexedDB.
//
-// We cannot implementing the spec's conceptual description. We need to assign
+// We cannot implement the spec's conceptual description. We need to assign
// primary keys in the browser process, to ensure that multiple renderer
// processes talking to the same database receive sequential keys. At the same
// time, we want the value serialization code to live in the renderer process,
@@ -532,7 +548,10 @@ bool InjectV8KeyIntoV8Value(v8::Isolate* isolate,
return false;
} else {
value = v8::Object::New(isolate);
- if (!V8CallBoolean(object->CreateDataProperty(context, property, value)))
+ bool created_property;
+ if (!object->CreateDataProperty(context, property, value)
+ .To(&created_property) ||
+ !created_property)
return false;
}
}
@@ -551,10 +570,11 @@ bool InjectV8KeyIntoV8Value(v8::Isolate* isolate,
v8::Local<v8::Object> object = value.As<v8::Object>();
v8::Local<v8::String> property = V8String(isolate, key_path_elements.back());
- if (!V8CallBoolean(object->CreateDataProperty(context, property, key)))
- return false;
- return true;
+ bool created_property;
+ if (!object->CreateDataProperty(context, property, key).To(&created_property))
+ return false;
+ return created_property;
}
// Verify that an value can have an generated key inserted at the location
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc
index 6753e600735..c9194ea91c5 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules_test.cc
@@ -37,6 +37,7 @@
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
#include "third_party/blink/renderer/bindings/modules/v8/to_v8_for_modules.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_any.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key.h"
@@ -194,13 +195,9 @@ TEST(IDBKeyFromValueAndKeyPathTest, TopLevelPropertyStringValue) {
v8::Isolate* isolate = scope.GetIsolate();
// object = { foo: "zoo" }
- v8::Local<v8::Object> object = v8::Object::New(isolate);
- ASSERT_TRUE(V8CallBoolean(object->Set(scope.GetContext(),
- V8AtomicString(isolate, "foo"),
- V8AtomicString(isolate, "zoo"))));
-
- ScriptValue script_value(scope.GetScriptState(), object);
-
+ ScriptValue script_value = V8ObjectBuilder(scope.GetScriptState())
+ .Add("foo", "zoo")
+ .GetScriptValue();
CheckKeyPathStringValue(isolate, script_value, "foo", "zoo");
CheckKeyPathNullValue(isolate, script_value, "bar");
}
@@ -212,32 +209,23 @@ TEST(IDBKeyFromValueAndKeyPathTest, TopLevelPropertyNumberValue) {
v8::Isolate* isolate = scope.GetIsolate();
// object = { foo: 456 }
- v8::Local<v8::Object> object = v8::Object::New(isolate);
- ASSERT_TRUE(V8CallBoolean(object->Set(scope.GetContext(),
- V8AtomicString(isolate, "foo"),
- v8::Number::New(isolate, 456))));
-
- ScriptValue script_value(scope.GetScriptState(), object);
-
+ ScriptValue script_value = V8ObjectBuilder(scope.GetScriptState())
+ .AddNumber("foo", 456)
+ .GetScriptValue();
CheckKeyPathNumberValue(isolate, script_value, "foo", 456);
CheckKeyPathNullValue(isolate, script_value, "bar");
}
TEST(IDBKeyFromValueAndKeyPathTest, SubProperty) {
V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
// object = { foo: { bar: "zee" } }
- v8::Local<v8::Object> object = v8::Object::New(isolate);
- v8::Local<v8::Object> sub_property = v8::Object::New(isolate);
- ASSERT_TRUE(V8CallBoolean(sub_property->Set(scope.GetContext(),
- V8AtomicString(isolate, "bar"),
- V8AtomicString(isolate, "zee"))));
- ASSERT_TRUE(V8CallBoolean(object->Set(
- scope.GetContext(), V8AtomicString(isolate, "foo"), sub_property)));
-
- ScriptValue script_value(scope.GetScriptState(), object);
-
+ ScriptValue script_value =
+ V8ObjectBuilder(script_state)
+ .Add("foo", V8ObjectBuilder(script_state).Add("bar", "zee"))
+ .GetScriptValue();
CheckKeyPathStringValue(isolate, script_value, "foo.bar", "zee");
CheckKeyPathNullValue(isolate, script_value, "bar");
}
@@ -263,15 +251,11 @@ TEST(InjectIDBKeyTest, ImplicitValues) {
TEST(InjectIDBKeyTest, TopLevelPropertyStringValue) {
V8TestingScope scope;
- v8::Isolate* isolate = scope.GetIsolate();
// object = { foo: "zoo" }
- v8::Local<v8::Object> object = v8::Object::New(isolate);
- ASSERT_TRUE(V8CallBoolean(object->Set(scope.GetContext(),
- V8AtomicString(isolate, "foo"),
- V8AtomicString(isolate, "zoo"))));
-
- ScriptValue script_object(scope.GetScriptState(), object);
+ ScriptValue script_object = V8ObjectBuilder(scope.GetScriptState())
+ .Add("foo", "zoo")
+ .GetScriptValue();
std::unique_ptr<IDBKey> idb_string_key = IDBKey::CreateString("myNewKey");
CheckInjection(scope.GetScriptState(), idb_string_key.get(), script_object,
"bar");
@@ -284,18 +268,14 @@ TEST(InjectIDBKeyTest, TopLevelPropertyStringValue) {
TEST(InjectIDBKeyTest, SubProperty) {
V8TestingScope scope;
- v8::Isolate* isolate = scope.GetIsolate();
+ ScriptState* script_state = scope.GetScriptState();
// object = { foo: { bar: "zee" } }
- v8::Local<v8::Object> object = v8::Object::New(isolate);
- v8::Local<v8::Object> sub_property = v8::Object::New(isolate);
- ASSERT_TRUE(V8CallBoolean(sub_property->Set(scope.GetContext(),
- V8AtomicString(isolate, "bar"),
- V8AtomicString(isolate, "zee"))));
- ASSERT_TRUE(V8CallBoolean(object->Set(
- scope.GetContext(), V8AtomicString(isolate, "foo"), sub_property)));
-
- ScriptValue script_object(scope.GetScriptState(), object);
+ ScriptValue script_object =
+ V8ObjectBuilder(script_state)
+ .Add("foo", V8ObjectBuilder(script_state).Add("bar", "zee"))
+ .GetScriptValue();
+
std::unique_ptr<IDBKey> idb_string_key = IDBKey::CreateString("myNewKey");
CheckInjection(scope.GetScriptState(), idb_string_key.get(), script_object,
"foo.baz");
diff --git a/chromium/third_party/blink/renderer/bindings/modules/v8/webgl_any.cc b/chromium/third_party/blink/renderer/bindings/modules/v8/webgl_any.cc
index 61b74eb6f2d..2933abb7dc1 100644
--- a/chromium/third_party/blink/renderer/bindings/modules/v8/webgl_any.cc
+++ b/chromium/third_party/blink/renderer/bindings/modules/v8/webgl_any.cc
@@ -4,7 +4,9 @@
#include "third_party/blink/renderer/bindings/modules/v8/webgl_any.h"
+#include "base/containers/span.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
+#include "third_party/blink/renderer/platform/bindings/to_v8.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -17,51 +19,20 @@ ScriptValue WebGLAny(ScriptState* script_state, bool value) {
ScriptValue WebGLAny(ScriptState* script_state,
const bool* value,
uint32_t size) {
- v8::Local<v8::Array> array = v8::Array::New(script_state->GetIsolate(), size);
- for (uint32_t i = 0; i < size; ++i) {
- if (!V8CallBoolean(array->CreateDataProperty(
- script_state->GetContext(), i,
- v8::Boolean::New(script_state->GetIsolate(), value[i]))))
- return ScriptValue();
- }
- return ScriptValue(script_state, array);
+ auto span = base::make_span(value, size);
+ return ScriptValue(script_state, ToV8(span, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, const Vector<bool>& value) {
- wtf_size_t size = value.size();
- v8::Local<v8::Array> array = v8::Array::New(script_state->GetIsolate(), size);
- for (wtf_size_t i = 0; i < size; ++i) {
- if (!V8CallBoolean(array->CreateDataProperty(
- script_state->GetContext(), i,
- v8::Boolean::New(script_state->GetIsolate(), value[i]))))
- return ScriptValue();
- }
- return ScriptValue(script_state, array);
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, const Vector<unsigned>& value) {
- wtf_size_t size = value.size();
- v8::Local<v8::Array> array = v8::Array::New(script_state->GetIsolate(), size);
- for (wtf_size_t i = 0; i < size; ++i) {
- if (!V8CallBoolean(array->CreateDataProperty(
- script_state->GetContext(), i,
- v8::Integer::NewFromUnsigned(script_state->GetIsolate(),
- value[i]))))
- return ScriptValue();
- }
- return ScriptValue(script_state, array);
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, const Vector<int>& value) {
- wtf_size_t size = value.size();
- v8::Local<v8::Array> array = v8::Array::New(script_state->GetIsolate(), size);
- for (wtf_size_t i = 0; i < size; ++i) {
- if (!V8CallBoolean(array->CreateDataProperty(
- script_state->GetContext(), i,
- v8::Integer::New(script_state->GetIsolate(), value[i]))))
- return ScriptValue();
- }
- return ScriptValue(script_state, array);
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, int value) {
@@ -95,33 +66,23 @@ ScriptValue WebGLAny(ScriptState* script_state, String value) {
}
ScriptValue WebGLAny(ScriptState* script_state, WebGLObject* value) {
- return ScriptValue(script_state,
- ToV8(value, script_state->GetContext()->Global(),
- script_state->GetIsolate()));
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, DOMFloat32Array* value) {
- return ScriptValue(script_state,
- ToV8(value, script_state->GetContext()->Global(),
- script_state->GetIsolate()));
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, DOMInt32Array* value) {
- return ScriptValue(script_state,
- ToV8(value, script_state->GetContext()->Global(),
- script_state->GetIsolate()));
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, DOMUint8Array* value) {
- return ScriptValue(script_state,
- ToV8(value, script_state->GetContext()->Global(),
- script_state->GetIsolate()));
+ return ScriptValue(script_state, ToV8(value, script_state));
}
ScriptValue WebGLAny(ScriptState* script_state, DOMUint32Array* value) {
- return ScriptValue(script_state,
- ToV8(value, script_state->GetContext()->Global(),
- script_state->GetIsolate()));
+ return ScriptValue(script_state, ToV8(value, script_state));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/aggregate_generated_bindings.py b/chromium/third_party/blink/renderer/bindings/scripts/aggregate_generated_bindings.py
index c314fe6f470..ed93ca1519b 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/aggregate_generated_bindings.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/aggregate_generated_bindings.py
@@ -120,8 +120,7 @@ def write_content(content, output_file_name):
def main():
options, filenames = parse_options()
component = options.component
- idl_filenames = read_idl_files_list_from_file(filenames[0],
- is_gyp_format=False)
+ idl_filenames = read_idl_files_list_from_file(filenames[0])
basenames = [idl_filename_to_basename(file_path)
for file_path in idl_filenames]
file_contents = generate_content(component, basenames)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/code_generator.py b/chromium/third_party/blink/renderer/bindings/scripts/code_generator.py
index f66c4767692..58b9b862515 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/code_generator.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/code_generator.py
@@ -55,7 +55,7 @@ def generate_indented_conditional(code, conditional):
def exposed_if(code, exposed_test):
if not exposed_test:
return code
- return generate_indented_conditional(code, 'executionContext && (%s)' % exposed_test)
+ return generate_indented_conditional(code, 'execution_context && (%s)' % exposed_test)
# [SecureContext]
@@ -150,6 +150,7 @@ class CodeGeneratorBase(object):
IdlType.set_callback_functions(self.info_provider.callback_functions)
IdlType.set_implemented_as_interfaces(interfaces_info['implemented_as_interfaces'])
IdlType.set_garbage_collected_types(interfaces_info['garbage_collected_interfaces'])
+ IdlType.set_garbage_collected_types(interfaces_info['dictionaries'])
set_component_dirs(interfaces_info['component_dirs'])
def render_templates(self, include_paths, header_template, cpp_template,
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/code_generator_v8.py b/chromium/third_party/blink/renderer/bindings/scripts/code_generator_v8.py
index 455a76ec2aa..60d3d3a24e3 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/code_generator_v8.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/code_generator_v8.py
@@ -59,7 +59,7 @@ import v8_interface
import v8_types
import v8_union
from v8_utilities import build_basename, cpp_name
-from utilities import idl_filename_to_component, is_testing_target, shorten_union_name, to_snake_case
+from utilities import idl_filename_to_component, is_testing_target, shorten_union_name, to_header_guard, to_snake_case
# Make sure extension is .py, not .pyc or .pyo, so doesn't depend on caching
@@ -187,19 +187,19 @@ class CodeGeneratorV8(CodeGeneratorV8Base):
# Select appropriate Jinja template and contents function
if interface.is_callback:
header_template_filename = 'callback_interface.h.tmpl'
- cpp_template_filename = 'callback_interface.cpp.tmpl'
+ cpp_template_filename = 'callback_interface.cc.tmpl'
interface_context = v8_callback_interface.callback_interface_context
elif interface.is_partial:
interface_context = v8_interface.interface_context
header_template_filename = 'partial_interface.h.tmpl'
- cpp_template_filename = 'partial_interface.cpp.tmpl'
+ cpp_template_filename = 'partial_interface.cc.tmpl'
interface_name += 'Partial'
assert component == 'core'
component = 'modules'
include_paths = interface_info.get('dependencies_other_component_include_paths')
else:
header_template_filename = 'interface.h.tmpl'
- cpp_template_filename = 'interface.cpp.tmpl'
+ cpp_template_filename = 'interface.cc.tmpl'
interface_context = v8_interface.interface_context
template_context = interface_context(interface, definitions.interfaces)
@@ -217,7 +217,9 @@ class CodeGeneratorV8(CodeGeneratorV8Base):
template_context['header_includes'].update(
interface_info.get('additional_header_includes', []))
header_path, cpp_path = self.output_paths(interface_name)
- template_context['this_include_header_path'] = self.normalize_this_header_path(header_path)
+ this_include_header_path = self.normalize_this_header_path(header_path)
+ template_context['this_include_header_path'] = this_include_header_path
+ template_context['header_guard'] = to_header_guard(this_include_header_path)
header_template = self.jinja_env.get_template(header_template_filename)
cpp_template = self.jinja_env.get_template(cpp_template_filename)
header_text, cpp_text = self.render_templates(
@@ -233,7 +235,7 @@ class CodeGeneratorV8(CodeGeneratorV8Base):
# pylint: disable=unused-argument
interfaces_info = self.info_provider.interfaces_info
header_template = self.jinja_env.get_template('dictionary_v8.h.tmpl')
- cpp_template = self.jinja_env.get_template('dictionary_v8.cpp.tmpl')
+ cpp_template = self.jinja_env.get_template('dictionary_v8.cc.tmpl')
interface_info = interfaces_info[dictionary_name]
template_context = v8_dictionary.dictionary_context(
dictionary, interfaces_info)
@@ -244,7 +246,9 @@ class CodeGeneratorV8(CodeGeneratorV8Base):
template_context['header_includes'].add(self.info_provider.include_path_for_export)
template_context['exported'] = self.info_provider.specifier_for_export
header_path, cpp_path = self.output_paths(dictionary_name)
- template_context['this_include_header_path'] = self.normalize_this_header_path(header_path)
+ this_include_header_path = self.normalize_this_header_path(header_path)
+ template_context['this_include_header_path'] = this_include_header_path
+ template_context['header_guard'] = to_header_guard(this_include_header_path)
header_text, cpp_text = self.render_templates(
include_paths, header_template, cpp_template, template_context)
return (
@@ -273,7 +277,7 @@ class CodeGeneratorDictionaryImpl(CodeGeneratorV8Base):
dictionary = definitions.dictionaries[definition_name]
interface_info = interfaces_info[definition_name]
header_template = self.jinja_env.get_template('dictionary_impl.h.tmpl')
- cpp_template = self.jinja_env.get_template('dictionary_impl.cpp.tmpl')
+ cpp_template = self.jinja_env.get_template('dictionary_impl.cc.tmpl')
template_context = v8_dictionary.dictionary_impl_context(
dictionary, interfaces_info)
include_paths = interface_info.get('dependencies_include_paths')
@@ -283,7 +287,9 @@ class CodeGeneratorDictionaryImpl(CodeGeneratorV8Base):
template_context['header_includes'].update(
interface_info.get('additional_header_includes', []))
header_path, cpp_path = self.output_paths(definition_name, interface_info)
- template_context['this_include_header_path'] = self.normalize_this_header_path(header_path)
+ this_include_header_path = self.normalize_this_header_path(header_path)
+ template_context['this_include_header_path'] = this_include_header_path
+ template_context['header_guard'] = to_header_guard(this_include_header_path)
header_text, cpp_text = self.render_templates(
include_paths, header_template, cpp_template, template_context)
return (
@@ -313,7 +319,7 @@ class CodeGeneratorUnionType(CodeGeneratorBase):
includes.clear()
union_type = union_type.resolve_typedefs(self.typedefs)
header_template = self.jinja_env.get_template('union_container.h.tmpl')
- cpp_template = self.jinja_env.get_template('union_container.cpp.tmpl')
+ cpp_template = self.jinja_env.get_template('union_container.cc.tmpl')
template_context = v8_union.container_context(union_type, self.info_provider)
template_context['header_includes'].append(
self.info_provider.include_path_for_export)
@@ -321,7 +327,9 @@ class CodeGeneratorUnionType(CodeGeneratorBase):
snake_base_name = to_snake_case(shorten_union_name(union_type))
header_path = posixpath.join(self.output_dir, '%s.h' % snake_base_name)
cpp_path = posixpath.join(self.output_dir, '%s.cc' % snake_base_name)
- template_context['this_include_header_path'] = self.normalize_this_header_path(header_path)
+ this_include_header_path = self.normalize_this_header_path(header_path)
+ template_context['this_include_header_path'] = this_include_header_path
+ template_context['header_guard'] = to_header_guard(this_include_header_path)
header_text, cpp_text = self.render_templates(
[], header_template, cpp_template, template_context)
return (
@@ -365,7 +373,7 @@ class CodeGeneratorCallbackFunction(CodeGeneratorBase):
def generate_code_internal(self, callback_function, path):
self.typedef_resolver.resolve(callback_function, callback_function.name)
header_template = self.jinja_env.get_template('callback_function.h.tmpl')
- cpp_template = self.jinja_env.get_template('callback_function.cpp.tmpl')
+ cpp_template = self.jinja_env.get_template('callback_function.cc.tmpl')
template_context = v8_callback_function.callback_function_context(
callback_function)
if not is_testing_target(path):
@@ -383,7 +391,9 @@ class CodeGeneratorCallbackFunction(CodeGeneratorBase):
snake_base_name = to_snake_case('V8%s' % callback_function.name)
header_path = posixpath.join(self.output_dir, '%s.h' % snake_base_name)
cpp_path = posixpath.join(self.output_dir, '%s.cc' % snake_base_name)
- template_context['this_include_header_path'] = self.normalize_this_header_path(header_path)
+ this_include_header_path = self.normalize_this_header_path(header_path)
+ template_context['this_include_header_path'] = this_include_header_path
+ template_context['header_guard'] = to_header_guard(this_include_header_path)
header_text, cpp_text = self.render_templates(
[], header_template, cpp_template, template_context)
return (
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/code_generator_web_agent_api.py b/chromium/third_party/blink/renderer/bindings/scripts/code_generator_web_agent_api.py
index cad68172bc9..9a4171e386a 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/code_generator_web_agent_api.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/code_generator_web_agent_api.py
@@ -26,6 +26,7 @@ import sys
from code_generator import CodeGeneratorBase, render_template, normalize_and_sort_includes
# TODO(dglazkov): Move TypedefResolver to code_generator.py
from code_generator_v8 import TypedefResolver
+from utilities import to_header_guard
sys.path.append(os.path.join(os.path.dirname(__file__),
'..', '..', 'build', 'scripts'))
@@ -259,6 +260,10 @@ class CodeGeneratorWebAgentAPI(CodeGeneratorBase):
self.output_dir,
'%s.%s' % (template_context['class_name']['snake_case'],
file_extension))
+ if file_extension == 'h':
+ this_include_header_path = self.normalize_this_header_path(path)
+ template_context['header_guard'] = to_header_guard(this_include_header_path)
+
text = render_template(template, template_context)
return (path, text)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/compute_global_objects.py b/chromium/third_party/blink/renderer/bindings/scripts/compute_global_objects.py
index ececf61132d..78d74f825be 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/compute_global_objects.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/compute_global_objects.py
@@ -6,7 +6,7 @@
"""Compute global objects.
-Global objects are defined by interfaces with [Global] or [PrimaryGlobal] on
+Global objects are defined by interfaces with [Global] on
their definition: http://heycam.github.io/webidl/#Global
Design document: http://www.chromium.org/developers/design-documents/idl-build
@@ -25,11 +25,6 @@ from utilities import read_file_to_list
from utilities import read_pickle_files
from utilities import write_pickle_file
-GLOBAL_EXTENDED_ATTRIBUTES = frozenset([
- 'Global',
- 'PrimaryGlobal',
-])
-
def parse_options():
usage = 'Usage: %prog [options] [GlobalObjects.pickle]'
@@ -57,29 +52,22 @@ def dict_union(dicts):
def idl_file_to_global_names(idl_filename):
"""Returns global names, if any, for an IDL file.
- If the [Global] or [PrimaryGlobal] extended attribute is declared with an
- identifier list argument, then those identifiers are the interface's global
- names; otherwise, the interface has a single global name, which is the
- interface's identifier (http://heycam.github.io/webidl/#Global).
+ The identifier argument or identifier list argument the [Global] extended
+ attribute is declared with define the interface's global names
+ (http://heycam.github.io/webidl/#Global).
"""
full_path = os.path.realpath(idl_filename)
idl_file_contents = get_file_contents(full_path)
extended_attributes = get_interface_extended_attributes_from_idl(idl_file_contents)
interface_name = get_first_interface_name_from_idl(idl_file_contents)
- global_keys = GLOBAL_EXTENDED_ATTRIBUTES.intersection(
- extended_attributes.iterkeys())
- if not global_keys:
+ if 'Global' not in extended_attributes:
return
- if len(global_keys) > 1:
- raise ValueError('The [Global] and [PrimaryGlobal] extended attributes '
- 'MUST NOT be declared on the same interface.')
- global_key = next(iter(global_keys))
-
- global_value = extended_attributes[global_key]
- if global_value:
- return global_value.strip('()').split(',')
- return [interface_name]
+ global_value = extended_attributes['Global']
+ if not global_value:
+ raise ValueError('[Global] must take an indentifier or an identifier list.\n' +
+ full_path)
+ return map(str.strip, global_value.strip('()').split(','))
def idl_files_to_interface_name_global_names(idl_files):
@@ -101,8 +89,8 @@ def main():
for existing_interface_name_global_names
in read_pickle_files(options.global_objects_component_files))
- # Input IDL files are passed in a file, due to OS command line length
- # limits. This is generated at GYP time, which is ok b/c files are static.
+ # File paths of input IDL files are passed in a file, which is generated at
+ # GN time. It is OK because the target IDL files themselves are static.
idl_files = read_file_to_list(options.idl_files_list)
interface_name_global_names.update(
idl_files_to_interface_name_global_names(idl_files))
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py b/chromium/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py
index 931b1d01fd1..992d4dba805 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/compute_interfaces_info_individual.py
@@ -347,7 +347,7 @@ def main():
options, _ = parse_options()
# IDL files are passed in a file, due to OS command line length limits
- idl_files = read_idl_files_list_from_file(options.idl_files_list, is_gyp_format=False)
+ idl_files = read_idl_files_list_from_file(options.idl_files_list)
# Compute information for individual files
# Information is stored in global variables interfaces_info and
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py b/chromium/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py
index 3ea1063d7ce..62cee43cf39 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py
@@ -87,13 +87,12 @@ def write_event_interfaces_file(event_idl_files, destination_filename, suffix):
for name in EXPORTED_EXTENDED_ATTRIBUTES
if name in extended_attributes]
- return (posixpath.join(relative_dir_posix, interface_name),
- extended_attributes_list)
+ return (relative_dir_posix, interface_name, extended_attributes_list)
lines = [
'{',
'metadata: {',
- ' namespace: "Event",'
+ ' namespace: "event_interface_names",'
]
if suffix:
lines.append(' suffix: "' + suffix + '",')
@@ -107,10 +106,11 @@ def write_event_interfaces_file(event_idl_files, destination_filename, suffix):
interface_lines = [interface_line(event_idl_file)
for event_idl_file in event_idl_files]
interface_lines.sort()
- for name, attributes in interface_lines:
+ for relative_dir, name, attributes in interface_lines:
lines.extend([
' {',
- ' name: "%s",' % name
+ ' name: "%s",' % name,
+ ' interfaceHeaderDir: "%s",' % relative_dir
])
for param, value in attributes:
if param == 'RuntimeEnabled':
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/generate_global_constructors.py b/chromium/third_party/blink/renderer/bindings/scripts/generate_global_constructors.py
index c068fbddbdb..d7568a07aa3 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/generate_global_constructors.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/generate_global_constructors.py
@@ -97,7 +97,8 @@ def record_global_constructors(idl_filename):
global_name_to_constructors[argument['exposed']].extend(new_constructors_list)
else:
# Exposed=env or Exposed=(env1,...) case
- exposed_global_names = extended_attributes.get('Exposed', 'Window').strip('()').split(',')
+ exposed_value = extended_attributes.get('Exposed', 'Window')
+ exposed_global_names = map(str.strip, exposed_value.strip('()').split(','))
new_constructors_list = generate_global_constructors_list(interface_name, extended_attributes)
for name in exposed_global_names:
global_name_to_constructors[name].extend(new_constructors_list)
@@ -153,14 +154,14 @@ def write_global_constructors_partial_interface(interface_name, idl_filename, co
def main():
options, args = parse_options()
- # Input IDL files are passed in a file, due to OS command line length
- # limits. This is generated at GYP time, which is ok b/c files are static.
+ # File paths of input IDL files are passed in a file, which is generated at
+ # GN time. It is OK because the target IDL files are static.
idl_files = read_file_to_list(options.idl_files_list)
# Output IDL files (to generate) are passed at the command line, since
# these are in the build directory, which is determined at build time, not
- # GYP time.
- # These are passed as pairs of GlobalObjectName, GlobalObject.idl
+ # GN time.
+ # These are passed as pairs of GlobalObjectName, global_object.idl
interface_name_idl_filename = [(args[i], args[i + 1])
for i in range(0, len(args), 2)]
@@ -175,8 +176,7 @@ def main():
if not exposed_global_names.issubset(known_global_names):
unknown_global_names = exposed_global_names.difference(known_global_names)
raise ValueError('The following global names were used in '
- '[Exposed=xxx] but do not match any [Global] / '
- '[PrimaryGlobal] interface: %s'
+ '[Exposed=xxx] but do not match any global names: %s'
% list(unknown_global_names))
# Write partial interfaces containing constructor attributes for each
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/generate_init_partial_interfaces.py b/chromium/third_party/blink/renderer/bindings/scripts/generate_init_partial_interfaces.py
index dd1b8541d7b..0e44fe91b66 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/generate_init_partial_interfaces.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/generate_init_partial_interfaces.py
@@ -43,9 +43,6 @@ def parse_options():
parser = OptionParser(usage=usage)
parser.add_option('--idl-files-list',
help='a text file containing the IDL file paths, so the command line doesn\'t exceed OS length limits.')
- parser.add_option('--gyp-format-list', default=False, action='store_true',
- help='if specified, idl-files-list is newline separated. ' +
- 'When unspecified, it\'s formatted as a Posix command line.')
parser.add_option('--output')
options, args = parser.parse_args()
@@ -86,7 +83,7 @@ def extract_meta_data(file_paths):
def main():
options = parse_options()
- idl_file_names = read_idl_files_list_from_file(options.idl_files_list, is_gyp_format=options.gyp_format_list)
+ idl_file_names = read_idl_files_list_from_file(options.idl_files_list)
meta_data_list = extract_meta_data(idl_file_names)
interface_names = ['V8%sPartial' % meta_data['basename']
@@ -96,7 +93,7 @@ def main():
includes = ['#include "third_party/blink/renderer/bindings/modules/v8/%s.h"' %
build_basename(interface_name)
for interface_name in interface_names]
- initialize_calls = [' %s::initialize();' % interface_name
+ initialize_calls = [' %s::Initialize();' % interface_name
for interface_name in interface_names]
content = _INIT_PARTIAL_INTERFACE % (
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py b/chromium/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py
index 16b0f8d58d9..af1ae5c051e 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py
@@ -39,9 +39,9 @@ def get_install_functions(interfaces, feature_names):
be installed on those interfaces.
"""
return [
- {'condition': 'OriginTrials::%sEnabled' % feature_name,
+ {'condition': 'origin_trials::%sEnabled' % feature_name,
'name': feature_name,
- 'install_method': 'install%s' % feature_name,
+ 'install_method': 'Install%s' % feature_name,
'interface_is_global': interface_info.is_global,
'v8_class': interface_info.v8_class,
'v8_class_or_partial': interface_info.v8_class_or_partial}
@@ -75,8 +75,7 @@ def read_idl_file(reader, idl_filename):
def interface_is_global(interface):
- return ('Global' in interface.extended_attributes or
- 'PrimaryGlobal' in interface.extended_attributes)
+ return 'Global' in interface.extended_attributes
def origin_trial_features_info(info_provider, reader, idl_filenames, target_component):
@@ -183,7 +182,7 @@ def origin_trial_features_context(generator_name, feature_info):
# functions to call, organized by interface.
context['installers_by_feature'] = [
{'name': feature_name,
- 'name_constant': 'OriginTrials::k%sTrialName' % feature_name,
+ 'name_constant': 'origin_trials::k%sTrialName' % feature_name,
'installers': get_install_functions(interfaces, [feature_name])}
for feature_name, interfaces in types_for_feature.items()]
context['installers_by_feature'].sort(key=lambda x: x['name'])
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py b/chromium/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py
index 5eaa5245a10..58dd824e9e7 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/generate_v8_context_snapshot_external_references.py
@@ -23,17 +23,10 @@ INCLUDES = frozenset([
'third_party/blink/renderer/bindings/core/v8/v8_html_document.h',
'third_party/blink/renderer/bindings/core/v8/v8_initializer.h',
'third_party/blink/renderer/bindings/core/v8/v8_window.h',
- 'third_party/blink/renderer/platform/bindings/dom_wrapper_world.h',
'third_party/blink/renderer/platform/bindings/v8_object_constructor.h',
- 'third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h',
- 'third_party/blink/renderer/platform/bindings/v8_private_property.h',
'v8/include/v8.h'])
-TEMPLATE_FILE = 'external_reference_table.cpp.tmpl'
-
-WHITE_LIST_INTERFACES = frozenset([
- 'DOMMatrix', # crbug.com/733481
-])
+TEMPLATE_FILE = 'external_reference_table.cc.tmpl'
SNAPSHOTTED_INTERFACES = frozenset([
'Window',
@@ -66,9 +59,11 @@ class InterfaceTemplateContextBuilder(object):
self._opts = opts
self._info_provider = info_provider
- def create_interface_context(self, interface, interfaces):
+ def create_interface_context(self, interface, component, interfaces):
'''Creates a Jinja context which is based on an interface.'''
+ assert component in ['core', 'modules']
+
name = '%s%s' % (v8_utilities.cpp_name(interface), 'Partial' if interface.is_partial else '')
# Constructors
@@ -94,8 +89,7 @@ class InterfaceTemplateContextBuilder(object):
attributes = [v8_attributes.attribute_context(interface, attribute, interfaces)
for attribute in interface.attributes]
methods = v8_interface.methods_context(interface)['methods']
- is_global = ('PrimaryGlobal' in interface.extended_attributes or
- 'Global' in interface.extended_attributes)
+ is_global = 'Global' in interface.extended_attributes
named_property_getter = v8_interface.property_getter(
interface.named_property_getter, ['name'])
@@ -118,6 +112,7 @@ class InterfaceTemplateContextBuilder(object):
return {
'attributes': attributes,
+ 'component': component,
'has_origin_safe_method_setter': has_origin_safe_method_setter,
'has_constructor_callback': has_constructor_callback,
'has_cross_origin_named_getter': has_cross_origin_named_getter,
@@ -128,17 +123,15 @@ class InterfaceTemplateContextBuilder(object):
'indexed_property_getter': indexed_property_getter,
'indexed_property_setter': v8_interface.property_setter(interface.indexed_property_setter, interface),
'indexed_property_deleter': v8_interface.property_deleter(interface.indexed_property_deleter),
- 'is_array_buffer_or_view': interface.idl_type.is_array_buffer_or_view,
- 'is_callback': interface.is_callback,
+ 'internal_namespace': v8_interface.internal_namespace(interface),
'is_partial': interface.is_partial,
- 'is_snapshotted': interface in SNAPSHOTTED_INTERFACES,
'methods': methods,
'name': name,
'named_constructor': v8_interface.named_constructor_context(interface),
'named_property_getter': named_property_getter,
'named_property_setter': v8_interface.property_setter(interface.named_property_setter, interface),
'named_property_deleter': v8_interface.property_deleter(interface.named_property_deleter),
- 'v8_name': v8_utilities.v8_class_name_or_partial(interface),
+ 'v8_class': v8_utilities.v8_class_name_or_partial(interface),
}
@@ -168,24 +161,30 @@ class ExternalReferenceTableGenerator(object):
# in V8 context snapshot, so we can skip them.
def _process_interface(self, interface, component, interfaces):
def has_impl(interface):
- if interface.name in WHITE_LIST_INTERFACES:
- return True
# Non legacy callback interface does not provide V8 callbacks.
if interface.is_callback:
return len(interface.constants) > 0
if 'RuntimeEnabled' in interface.extended_attributes:
return False
- return True
+ if 'Exposed' not in interface.extended_attributes:
+ return True
+ return any(exposure.exposed == 'Window' and exposure.runtime_enabled is None
+ for exposure in interface.extended_attributes['Exposed'])
if not has_impl(interface):
return
context_builder = InterfaceTemplateContextBuilder(self._opts, self._info_provider)
- context = context_builder.create_interface_context(interface, interfaces)
+ context = context_builder.create_interface_context(interface, component, interfaces)
name = '%s%s' % (interface.name, 'Partial' if interface.is_partial else '')
self._interface_contexts[name] = context
+
+ # Do not include unnecessary header files.
+ if not context['attributes'] and not context['named_property_setter']:
+ return
+
include_file = 'third_party/blink/renderer/bindings/%s/v8/%s.h' % (
- component, utilities.to_snake_case(context['v8_name']))
+ component, utilities.to_snake_case(context['v8_class']))
self._include_files.add(include_file)
# Gathers all interface-dependent information and returns as a Jinja template context.
@@ -220,7 +219,7 @@ def main():
opts.info_dir, opts.target_component)
generator = ExternalReferenceTableGenerator(opts, info_provider)
- idl_files = utilities.read_idl_files_list_from_file(opts.idl_files_list, False)
+ idl_files = utilities.read_idl_files_list_from_file(opts.idl_files_list)
for idl_file in idl_files:
generator.process_idl_file(idl_file)
output_code = generator.generate()
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py b/chromium/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py
index 4cd03f41e6e..323d0f9c9fc 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/generate_web_idl_collection.py
@@ -3,36 +3,41 @@
# found in the LICENSE file.
"""Generates a data collection of IDL information per component.
-In this data collection, we use identifier strings to point IDL definitions
-(i.e. interface, dictionary, namespace, etc.) instead of references, because
-some referred definitions can be in other components.
+This scripts parses IDL files and stores the result ASTs in a pickle file.
+The output file may contain information about component, too.
"""
-
import blink_idl_parser
import optparse
import utilities
from web_idl.collector import Collector
+_VALID_COMPONENTS = ("core", "modules")
+
def parse_options():
parser = optparse.OptionParser()
- parser.add_option('--idl-list-file', help='a file path which lists IDL file paths to process')
- parser.add_option('--component', help='decide which component to collect IDLs', default=None)
- parser.add_option('--output', help='pickle file of IDL definition')
+ parser.add_option('--idl-list-file', type='string',
+ help='a file path which lists IDL file paths to process')
+ parser.add_option('--component', type='choice', choices=_VALID_COMPONENTS,
+ help='specify a component name where IDLs belong')
+ parser.add_option('--output', type='string',
+ help='pickle file to write down')
options, args = parser.parse_args()
if options.idl_list_file is None:
- parser.error('Must specify a file listing IDL files using --idl-files-list.')
+ parser.error('Must specify a file listing IDL files using --idl-list-file.')
if options.output is None:
parser.error('Must specify a pickle file to output using --output.')
+ if options.component is None:
+ parser.error('Must specify a component using --component.')
return options, args
def main():
options, _ = parse_options()
- idl_file_names = utilities.read_idl_files_list_from_file(options.idl_list_file, False)
+ idl_file_names = utilities.read_idl_files_list_from_file(options.idl_list_file)
parser = blink_idl_parser.BlinkIDLParser()
collector = Collector(component=options.component, parser=parser)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/idl_compiler.py b/chromium/third_party/blink/renderer/bindings/scripts/idl_compiler.py
index 278954a157d..eef89351649 100755
--- a/chromium/third_party/blink/renderer/bindings/scripts/idl_compiler.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/idl_compiler.py
@@ -178,8 +178,7 @@ def main():
if options.generate_impl or options.read_idl_list_from_file:
# |input_filename| should be a file which contains a list of IDL
# dictionary paths.
- input_filenames = read_idl_files_list_from_file(input_filename,
- is_gyp_format=True)
+ input_filenames = read_idl_files_list_from_file(input_filename)
else:
input_filenames = [input_filename]
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/idl_definitions.py b/chromium/third_party/blink/renderer/bindings/scripts/idl_definitions.py
index 8d9b00f3dcf..b7980d186d5 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/idl_definitions.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/idl_definitions.py
@@ -64,6 +64,7 @@ Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
import abc
+from idl_types import IdlAnnotatedType
from idl_types import IdlFrozenArrayType
from idl_types import IdlNullableType
from idl_types import IdlRecordType
@@ -951,7 +952,7 @@ def type_node_to_type(node):
base_type = type_node_inner_to_type(children[0])
if len(children) == 2:
extended_attributes = ext_attributes_node_to_extended_attributes(children[1])
- base_type.set_extended_attributes(extended_attributes)
+ base_type = IdlAnnotatedType(base_type, extended_attributes)
if node.GetProperty('NULLABLE'):
base_type = IdlNullableType(base_type)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/idl_types.py b/chromium/third_party/blink/renderer/bindings/scripts/idl_types.py
index cf202b3ec0a..068c33d912f 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/idl_types.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/idl_types.py
@@ -11,6 +11,7 @@ IdlTypeBase
IdlSequenceType
IdlFrozenArrayType
IdlNullableType
+ IdlAnnotatedType
IdlTypes are picklable because we store them in interfaces_info.
"""
@@ -91,6 +92,11 @@ NON_STANDARD_CALLBACK_FUNCTIONS = frozenset([
'CallbackFunctionTreatedAsScriptValue',
])
+EXTENDED_ATTRIBUTES_APPLICABLE_TO_TYPES = frozenset([
+ 'Clamp',
+ 'EnforceRange',
+ 'TreatNullAs',
+])
################################################################################
# Inheritance
@@ -143,13 +149,12 @@ class IdlType(IdlTypeBase):
dictionaries = set()
enums = {} # name -> values
- def __init__(self, base_type, is_unrestricted=False, extended_attributes=None):
+ def __init__(self, base_type, is_unrestricted=False):
super(IdlType, self).__init__()
if is_unrestricted:
self.base_type = 'unrestricted %s' % base_type
else:
self.base_type = base_type
- self.extended_attributes = extended_attributes
def __str__(self):
return self.base_type
@@ -157,15 +162,10 @@ class IdlType(IdlTypeBase):
def __getstate__(self):
return {
'base_type': self.base_type,
- 'extended_attributes': self.extended_attributes,
}
def __setstate__(self, state):
self.base_type = state['base_type']
- self.extended_attributes = state['extended_attributes']
-
- def set_extended_attributes(self, extended_attributes):
- self.extended_attributes = extended_attributes
@property
def is_basic_type(self):
@@ -581,3 +581,59 @@ class IdlNullableType(IdlTypeBase):
yield self
for idl_type in self.inner_type.idl_types():
yield idl_type
+
+
+################################################################################
+# IdlAnnotatedType
+################################################################################
+
+class IdlAnnotatedType(IdlTypeBase):
+ """IdlAnnoatedType represents an IDL type with extended attributes.
+ [Clamp], [EnforceRange], and [TreatNullAs] are applicable to types.
+ https://heycam.github.io/webidl/#idl-annotated-types
+ """
+
+ def __init__(self, inner_type, extended_attributes):
+ super(IdlAnnotatedType, self).__init__()
+ self.inner_type = inner_type
+ self.extended_attributes = extended_attributes
+
+ if any(key not in EXTENDED_ATTRIBUTES_APPLICABLE_TO_TYPES
+ for key in extended_attributes):
+ raise ValueError('Extended attributes not applicable to types: %s' % self)
+
+ def __str__(self):
+ annotation = ', '.join((key + ('' if val is None else '=' + val))
+ for key, val in self.extended_attributes.iteritems())
+ return '[%s] %s' % (annotation, str(self.inner_type))
+
+ def __getattr__(self, name):
+ return getattr(self.inner_type, name)
+
+ def __getstate__(self):
+ return {
+ 'inner_type': self.inner_type,
+ 'extended_attributes': self.extended_attributes,
+ }
+
+ def __setstate__(self, state):
+ self.inner_type = state['inner_type']
+ self.extended_attributes = state['extended_attributes']
+
+ @property
+ def is_annotated_type(self):
+ return True
+
+ @property
+ def name(self):
+ annotation = ''.join((key + ('' if val is None else val))
+ for key, val in sorted(self.extended_attributes.iteritems()))
+ return self.inner_type.name + annotation
+
+ def resolve_typedefs(self, typedefs):
+ self.inner_type = self.inner_type.resolve_typedefs(typedefs)
+ return self
+
+ def idl_types(self):
+ yield self
+ yield self.inner_type
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/interface_dependency_resolver.py b/chromium/third_party/blink/renderer/bindings/scripts/interface_dependency_resolver.py
index 239f11ec530..a27af0773e9 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/interface_dependency_resolver.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/interface_dependency_resolver.py
@@ -203,7 +203,7 @@ def merge_interface_dependencies(definitions, component, target_interface, depen
# cpp class to obtain partial interface's cpp class.
# e.g.. V8WindowPartial.cpp:
# DOMWindow* impl = V8Window::ToImpl(holder);
- # DOMWindowQuota* cppValue(DOMWindowQuota::webkitStorageInfo(impl));
+ # DOMWindowQuota* cpp_value(DOMWindowQuota::webkitStorageInfo(impl));
# TODO(tasak): remove ImplementedAs extended attributes
# from all partial interfaces. Instead, rename all cpp/header
# files correctly. ImplementedAs should not be allowed in
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/scripts.gni b/chromium/third_party/blink/renderer/bindings/scripts/scripts.gni
index c6867747c08..4e5f888fbc3 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/scripts.gni
+++ b/chromium/third_party/blink/renderer/bindings/scripts/scripts.gni
@@ -62,8 +62,6 @@ web_idl_scripts = get_path_info([
"web_idl/argument.py",
"web_idl/attribute.py",
"web_idl/callback_function.py",
- "web_idl/collection.py",
- "web_idl/collector.py",
"web_idl/constant.py",
"web_idl/dictionary.py",
"web_idl/ecma_script_types.py",
@@ -500,11 +498,13 @@ template("generate_web_idl_collection") {
output_path = "${output_dir}/${output_file_name}"
inputs = [
script,
- "${bindings_scripts_dir}/utilities.py",
- ] + web_idl_scripts + invoker.sources
+ "${bindings_scripts_dir}/web_idl/collection.py",
+ "${bindings_scripts_dir}/web_idl/collector.py",
+ ] + idl_lexer_parser_files + invoker.sources
outputs = [
output_path,
]
+ deps = invoker.deps
# List input file names in a temporary file.
response_file_contents = rebase_path(invoker.sources, root_build_dir)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/utilities.py b/chromium/third_party/blink/renderer/bindings/scripts/utilities.py
index 9d9725fd90a..4b9573fa72e 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/utilities.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/utilities.py
@@ -281,19 +281,10 @@ def resolve_cygpath(cygdrive_names):
return idl_file_names
-def read_idl_files_list_from_file(filename, is_gyp_format):
- """Similar to read_file_to_list, but also resolves cygpath.
-
- If is_gyp_format is True, the file is treated as a newline-separated list
- with no quoting or escaping. When False, the file is interpreted as a
- Posix-style quoted and space-separated list."""
+def read_idl_files_list_from_file(filename):
+ """Similar to read_file_to_list, but also resolves cygpath."""
with open(filename) as input_file:
- if is_gyp_format:
- file_names = sorted([os.path.realpath(line.rstrip('\n'))
- for line in input_file])
- else:
- file_names = sorted(shlex.split(input_file))
-
+ file_names = sorted(shlex.split(input_file))
idl_file_names = [file_name for file_name in file_names
if not file_name.startswith('/cygdrive')]
cygdrive_names = [file_name for file_name in file_names
@@ -374,7 +365,7 @@ def match_interface_extended_attributes_and_name_from_idl(file_contents):
file_contents = re.sub(block_comment_re, '', file_contents)
match = re.search(
- r'(?:\[([^[]*)\]\s*)?'
+ r'(?:\[([^{};]*)\]\s*)?'
r'(interface|callback\s+interface|partial\s+interface|dictionary)\s+'
r'(\w+)\s*'
r'(:\s*\w+\s*)?'
@@ -382,22 +373,34 @@ def match_interface_extended_attributes_and_name_from_idl(file_contents):
file_contents, flags=re.DOTALL)
return match
+
def get_interface_extended_attributes_from_idl(file_contents):
match = match_interface_extended_attributes_and_name_from_idl(file_contents)
if not match or not match.group(1):
return {}
- extended_attributes_string = match.group(1)
- extended_attributes = {}
- # FIXME: this splitting is WRONG: it fails on extended attributes where lists of
- # multiple values are used, which are seperated by a comma and a space.
+ extended_attributes_string = match.group(1).strip()
parts = [extended_attribute.strip()
- for extended_attribute in re.split(',\s+', extended_attributes_string)
+ for extended_attribute in re.split(',', extended_attributes_string)
# Discard empty parts, which may exist due to trailing comma
if extended_attribute.strip()]
+
+ # Joins |parts| with commas as far as the parences are not balanced,
+ # and then converts a (joined) term to a dict entry.
+ # ex. ['ab=c', 'ab(cd', 'ef', 'gh)', 'f=(a', 'b)']
+ # => {'ab': 'c', 'ab(cd,ef,gh)': '', 'f': '(a,b)'}
+ extended_attributes = {}
+ concatenated = None
for part in parts:
- name, _, value = map(string.strip, part.partition('='))
- extended_attributes[name] = value
+ concatenated = (concatenated + ', ' + part) if concatenated else part
+ parences = concatenated.count('(') - concatenated.count(')')
+ square_brackets = concatenated.count('[') - concatenated.count(']')
+ if parences < 0 or square_brackets < 0:
+ raise ValueError('You have more close braces than open braces.')
+ if parences == 0 and square_brackets == 0:
+ name, _, value = map(string.strip, concatenated.partition('='))
+ extended_attributes[name] = value
+ concatenated = None
return extended_attributes
@@ -419,6 +422,7 @@ def get_interface_exposed_arguments(file_contents):
def get_first_interface_name_from_idl(file_contents):
+ # TODO(peria): This function returns 'mixin' for interface mixins.
match = match_interface_extended_attributes_and_name_from_idl(file_contents)
if match:
return match.group(3)
@@ -437,7 +441,7 @@ def shorten_union_name(union_type):
'CanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContextOrImageBitmapRenderingContextOrXRPresentationContext': 'RenderingContext',
# modules/canvas/htmlcanvas/html_canvas_element_module.idl
'CanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrImageBitmapRenderingContextOrXRPresentationContext': 'RenderingContext',
- # core/imagebitmap/ImageBitmapFactories.idl
+ # core/frame/window_or_worker_global_scope.idl
'HTMLImageElementOrSVGImageElementOrHTMLVideoElementOrHTMLCanvasElementOrBlobOrImageDataOrImageBitmapOrOffscreenCanvas': 'ImageBitmapSource',
# bindings/tests/idls/core/TestTypedefs.idl
'NodeOrLongSequenceOrEventOrXMLHttpRequestOrStringOrStringByteStringOrNodeListRecord': 'NestedUnionType',
@@ -465,6 +469,10 @@ def to_snake_case(name):
return NameStyleConverter(name).to_snake_case()
+def to_header_guard(path):
+ return NameStyleConverter(path).to_header_guard()
+
+
def format_remove_duplicates(text, patterns):
"""Removes duplicated line-basis patterns.
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_attributes.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_attributes.py
index d58a5d96e71..f06d6dfc206 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_attributes.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_attributes.py
@@ -35,6 +35,12 @@ Extends IdlType with property |constructor_type_name|.
Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
"""
+import os
+import sys
+
+sys.path.append(os.path.join(os.path.dirname(__file__),
+ '..', '..', 'build', 'scripts'))
+from blinkbuild.name_style_converter import NameStyleConverter
import idl_types
from idl_types import inherits_interface
from v8_globals import includes
@@ -132,6 +138,7 @@ def attribute_context(interface, attribute, interfaces):
'activity_logging_world_list_for_setter': v8_utilities.activity_logging_world_list(attribute, 'Setter'), # [ActivityLogging]
'activity_logging_world_check': v8_utilities.activity_logging_world_check(attribute), # [ActivityLogging]
'cached_attribute_validation_method': cached_attribute_validation_method,
+ 'camel_case_name': NameStyleConverter(attribute.name).to_upper_camel_case(),
'constructor_type': constructor_type,
'context_enabled_feature_name': v8_utilities.context_enabled_feature_name(attribute),
'cpp_name': cpp_name(attribute),
@@ -306,11 +313,11 @@ def getter_context(interface, attribute, context):
context['is_keep_alive_for_gc'] or
context['is_getter_raises_exception']):
context['cpp_value_original'] = cpp_value
- cpp_value = 'cppValue'
+ cpp_value = 'cpp_value'
def v8_set_return_value_statement(for_main_world=False):
if context['is_keep_alive_for_gc'] or 'CachedAttribute' in extended_attributes:
- return 'V8SetReturnValue(info, v8Value)'
+ return 'V8SetReturnValue(info, v8_value)'
return idl_type.v8_set_return_value(
cpp_value, extended_attributes=extended_attributes, script_wrappable='impl',
for_main_world=for_main_world, is_static=attribute.is_static)
@@ -343,9 +350,9 @@ def getter_expression(interface, attribute, context):
not attribute.is_static):
arguments.append('*impl')
if attribute.idl_type.is_explicit_nullable:
- arguments.append('isNull')
+ arguments.append('is_null')
if context['is_getter_raises_exception']:
- arguments.append('exceptionState')
+ arguments.append('exception_state')
if attribute.idl_type.use_output_parameter_for_result:
arguments.append('result')
@@ -434,9 +441,13 @@ def setter_context(interface, attribute, interfaces, context):
return
if ('Replaceable' in attribute.extended_attributes):
+ # Create the property, and early-return if an exception is thrown.
+ # Subsequent cleanup code may not be prepared to handle a pending
+ # exception.
context['cpp_setter'] = (
- 'V8CallBoolean(info.Holder()->CreateDataProperty(' +
- 'info.GetIsolate()->GetCurrentContext(), propertyName, v8Value))')
+ 'if (info.Holder()->CreateDataProperty(' +
+ 'info.GetIsolate()->GetCurrentContext(), property_name, v8_value).IsNothing())' +
+ '\n return')
return
extended_attributes = attribute.extended_attributes
@@ -462,7 +473,7 @@ def setter_context(interface, attribute, interfaces, context):
attribute, 'SetterCallWith', 'ScriptState'),
'is_setter_raises_exception': is_setter_raises_exception,
'v8_value_to_local_cpp_value': idl_type.v8_value_to_local_cpp_value(
- extended_attributes, 'v8Value', 'cppValue'),
+ extended_attributes, 'v8_value', 'cpp_value'),
})
# setter_expression() depends on context values we set above.
@@ -496,17 +507,17 @@ def setter_expression(interface, attribute, context):
handler_type = 'kOnBeforeUnloadEventHandler'
arguments.append(
'V8EventListenerHelper::GetEventHandler(' +
- 'ScriptState::ForRelevantRealm(info), v8Value, ' +
+ 'ScriptState::ForRelevantRealm(info), v8_value, ' +
'JSEventHandler::HandlerType::' + handler_type +
', kListenerFindOrCreate)')
elif idl_type.base_type == 'SerializedScriptValue':
- arguments.append('std::move(cppValue)')
+ arguments.append('std::move(cpp_value)')
else:
- arguments.append('cppValue')
+ arguments.append('cpp_value')
if idl_type.is_explicit_nullable:
- arguments.append('isNull')
+ arguments.append('is_null')
if context['is_setter_raises_exception']:
- arguments.append('exceptionState')
+ arguments.append('exception_state')
return '%s(%s)' % (setter_name, ', '.join(arguments))
@@ -531,13 +542,14 @@ def setter_base_name(interface, attribute, arguments):
def scoped_content_attribute_name(interface, attribute):
content_attribute_name = attribute.extended_attributes['Reflect'] or attribute.name.lower()
+ symbol_name = 'k' + NameStyleConverter(content_attribute_name).to_upper_camel_case()
if interface.name.startswith('SVG'):
- namespace = 'SVGNames'
+ namespace = 'svg_names'
includes.add('core/svg_names.h')
else:
- namespace = 'HTMLNames'
+ namespace = 'html_names'
includes.add('core/html_names.h')
- return '%s::%sAttr' % (namespace, content_attribute_name)
+ return '%s::%sAttr' % (namespace, symbol_name)
################################################################################
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_function.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_function.py
index 8ca9fb63be8..515ab774b42 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_function.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_function.py
@@ -12,6 +12,7 @@ import v8_types
CALLBACK_FUNCTION_H_INCLUDES = frozenset([
'platform/bindings/callback_function_base.h',
+ 'platform/wtf/forward.h',
])
CALLBACK_FUNCTION_CPP_INCLUDES = frozenset([
'base/stl_util.h',
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py
index 025650ce08a..66ebc6767d9 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_callback_interface.py
@@ -57,13 +57,12 @@ LEGACY_CALLBACK_INTERFACE_CPP_INCLUDES = frozenset([
])
-def cpp_type(idl_type):
+def _cpp_type(idl_type):
# FIXME: remove this function by making callback types consistent
# (always use usual v8_types.cpp_type)
- idl_type_name = idl_type.name
- if idl_type_name == 'String' or idl_type.is_enum:
+ if idl_type.is_string_type or idl_type.is_enum:
return 'const String&'
- if idl_type_name == 'void':
+ if idl_type.name == 'void':
return 'void'
# Callbacks use raw pointers, so raw_type=True
raw_cpp_type = idl_type.cpp_type_args(raw_type=True)
@@ -72,7 +71,7 @@ def cpp_type(idl_type):
return 'const %s&' % raw_cpp_type
return raw_cpp_type
-IdlTypeBase.callback_cpp_type = property(cpp_type)
+IdlTypeBase.callback_cpp_type = property(_cpp_type)
def callback_interface_context(callback_interface, _):
@@ -123,6 +122,8 @@ def forward_declarations(callback_interface):
return idl_type.implemented_as
elif idl_type.is_array_or_sequence_type:
return find_forward_declaration(idl_type.element_type)
+ elif idl_type.is_nullable:
+ return find_forward_declaration(idl_type.inner_type)
return None
declarations = set()
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_dictionary.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_dictionary.py
index 16854564550..7b5227a2de2 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_dictionary.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_dictionary.py
@@ -93,7 +93,6 @@ def dictionary_context(dictionary, interfaces_info):
if member.is_required]),
'use_permissive_dictionary_conversion': 'PermissiveDictionaryConversion' in dictionary.extended_attributes,
'v8_class': v8_types.v8_type(cpp_class),
- 'v8_original_class': v8_types.v8_type(dictionary.name),
}
if dictionary.parent:
IdlType(dictionary.parent).add_includes_for_type()
@@ -129,6 +128,7 @@ def member_context(dictionary, member):
return None, None
if member.default_value.is_null:
return None, 'v8::Null(isolate)'
+
cpp_default_value = unwrapped_idl_type.literal_cpp_value(
member.default_value)
v8_default_value = unwrapped_idl_type.cpp_value_to_v8_value(
@@ -149,7 +149,7 @@ def member_context(dictionary, member):
'cpp_type': unwrapped_idl_type.cpp_type,
'cpp_value': cpp_value,
'cpp_value_to_v8_value': unwrapped_idl_type.cpp_value_to_v8_value(
- cpp_value='impl.%s()' % getter_name, isolate='isolate',
+ cpp_value='impl->%s()' % getter_name, isolate='isolate',
creation_context='creationContext',
extended_attributes=extended_attributes),
'deprecate_as': v8_utilities.deprecate_as(member),
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_interface.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_interface.py
index a57122c0e74..3468250813a 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_interface.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_interface.py
@@ -33,8 +33,13 @@
Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
"""
+import os
+import sys
from operator import or_
+sys.path.append(os.path.join(os.path.dirname(__file__),
+ '..', '..', 'build', 'scripts'))
+from blinkbuild.name_style_converter import NameStyleConverter
from idl_definitions import IdlAttribute, IdlOperation, IdlArgument
from idl_types import IdlType, inherits_interface
from overload_set_algorithm import effective_overload_set_by_length
@@ -248,9 +253,8 @@ def interface_context(interface, interfaces):
includes.add('bindings/core/v8/binding_security.h')
includes.add('core/frame/local_dom_window.h')
- # [PrimaryGlobal] and [Global]
- is_global = ('PrimaryGlobal' in extended_attributes or
- 'Global' in extended_attributes)
+ # [Global]
+ is_global = 'Global' in extended_attributes
# [ImmutablePrototype]
# TODO(littledan): Is it possible to deduce this based on inheritance,
@@ -287,6 +291,7 @@ def interface_context(interface, interfaces):
'has_partial_interface': len(interface.partial_interfaces) > 0,
'header_includes': header_includes,
'interface_name': interface.name,
+ 'internal_namespace': internal_namespace(interface),
'is_array_buffer_or_view': is_array_buffer_or_view,
'is_check_security': is_check_security,
'is_event_target': is_event_target,
@@ -302,6 +307,7 @@ def interface_context(interface, interfaces):
'pass_cpp_type': cpp_name(interface) + '*',
'runtime_call_stats': runtime_call_stats_context(interface),
'runtime_enabled_feature_name': runtime_enabled_feature_name(interface), # [RuntimeEnabled]
+ 'snake_case_v8_class': NameStyleConverter(v8_class_name).to_snake_case(),
'v8_class': v8_class_name,
'v8_class_or_partial': v8_class_name_or_partial,
'wrapper_class_id': wrapper_class_id,
@@ -829,6 +835,7 @@ def constant_context(constant, interface):
extended_attributes = constant.extended_attributes
return {
+ 'camel_case_name': NameStyleConverter(constant.name).to_upper_camel_case(),
'cpp_class': extended_attributes.get('PartialInterfaceImplementedAs'),
'cpp_type': constant.idl_type.cpp_type,
'deprecate_as': v8_utilities.deprecate_as(constant), # [DeprecateAs]
@@ -873,8 +880,7 @@ def compute_method_overloads_context_by_type(interface, methods):
# package necessary information into |method.overloads| for that method.
overloads[-1]['overloads'] = overloads_context(interface, overloads)
overloads[-1]['overloads']['name'] = name
-
-
+ overloads[-1]['overloads']['camel_case_name'] = NameStyleConverter(name).to_upper_camel_case()
def overloads_context(interface, overloads):
@@ -897,6 +903,7 @@ def overloads_context(interface, overloads):
effective_overloads_by_length = effective_overload_set_by_length(overloads)
lengths = [length for length, _ in effective_overloads_by_length]
name = overloads[0].get('name', '<constructor>')
+ camel_case_name = NameStyleConverter(name).to_upper_camel_case()
runtime_determined_lengths = None
function_length = lengths[0]
@@ -924,8 +931,8 @@ def overloads_context(interface, overloads):
break
runtime_determined_lengths.append(
(length, sorted(runtime_enabled_feature_names)))
- function_length = ('%sV8Internal::%sMethodLength()'
- % (cpp_name_or_partial(interface), name))
+ function_length = ('%s::%sMethodLength()'
+ % (internal_namespace(interface), camel_case_name))
# Check if all overloads with the longest required arguments list are
# runtime enabled, in which case we need to have a runtime determined
@@ -947,8 +954,8 @@ def overloads_context(interface, overloads):
break
runtime_determined_maxargs.append(
(length, sorted(runtime_enabled_feature_names)))
- maxarg = ('%sV8Internal::%sMethodMaxArg()'
- % (cpp_name_or_partial(interface), name))
+ maxarg = ('%s::%sMethodMaxArg()' %
+ (internal_namespace(interface), camel_case_name))
# Check and fail if overloads disagree about whether the return type
# is a Promise or not.
@@ -1171,7 +1178,7 @@ def resolution_tests_methods(effective_overloads):
# ...
for idl_type, method in idl_types_methods:
if idl_type.is_wrapper_type and not idl_type.is_array_buffer_or_view:
- test = 'V8{idl_type}::hasInstance({cpp_value}, info.GetIsolate())'.format(
+ test = 'V8{idl_type}::HasInstance({cpp_value}, info.GetIsolate())'.format(
idl_type=idl_type.base_type, cpp_value=cpp_value)
yield test, method
@@ -1241,7 +1248,7 @@ def resolution_tests_methods(effective_overloads):
# Either condition should be fulfilled to call this |method|.
test = '%s->IsArray()' % cpp_value
yield test, method
- test = 'HasCallableIteratorSymbol(info.GetIsolate(), %s, exceptionState)' % cpp_value
+ test = 'HasCallableIteratorSymbol(info.GetIsolate(), %s, exception_state)' % cpp_value
yield test, method
except StopIteration:
pass
@@ -1355,6 +1362,11 @@ def common_value(dicts, key):
return common(dicts, lambda d: d.get(key))
+def internal_namespace(interface):
+ return (v8_utilities.to_snake_case(cpp_name_or_partial(interface)) +
+ '_v8_internal')
+
+
################################################################################
# Constructors
################################################################################
@@ -1464,9 +1476,9 @@ def property_getter(getter, cpp_arguments):
cpp_method_name = 'impl->%s' % cpp_name(getter)
if is_call_with_script_state:
- cpp_arguments.insert(0, 'scriptState')
+ cpp_arguments.insert(0, 'script_state')
if is_raises_exception:
- cpp_arguments.append('exceptionState')
+ cpp_arguments.append('exception_state')
if use_output_parameter_for_result:
cpp_arguments.append('result')
@@ -1525,7 +1537,7 @@ def property_setter(setter, interface):
'is_raises_exception': is_raises_exception,
'name': cpp_name(setter),
'v8_value_to_local_cpp_value': idl_type.v8_value_to_local_cpp_value(
- extended_attributes, 'v8Value', 'propertyValue'),
+ extended_attributes, 'v8_value', 'property_value'),
}
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_methods.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_methods.py
index 14e785d10cd..11dbd99db4d 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_methods.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_methods.py
@@ -34,6 +34,12 @@ Extends IdlTypeBase and IdlUnionType with property |union_arguments|.
Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
"""
+import os
+import sys
+
+sys.path.append(os.path.join(os.path.dirname(__file__),
+ '..', '..', 'build', 'scripts'))
+from blinkbuild.name_style_converter import NameStyleConverter
from idl_definitions import IdlArgument, IdlOperation
from idl_types import IdlTypeBase, IdlUnionType, inherits_interface
from v8_globals import includes
@@ -106,6 +112,7 @@ def use_local_result(method):
'NewObject' in extended_attributes or
'RaisesException' in extended_attributes or
idl_type.is_union_type or
+ idl_type.is_dictionary or
idl_type.is_explicit_nullable)
@@ -183,6 +190,7 @@ def method_context(interface, method, is_visible=True):
return {
'activity_logging_world_list': v8_utilities.activity_logging_world_list(method), # [ActivityLogging]
'arguments': argument_contexts,
+ 'camel_case_name': NameStyleConverter(name).to_upper_camel_case(),
'cpp_type': (v8_types.cpp_template_type('base::Optional', idl_type.cpp_type)
if idl_type.is_explicit_nullable else idl_type.cpp_type),
'cpp_value': this_cpp_value,
@@ -241,6 +249,7 @@ def method_context(interface, method, is_visible=True):
'runtime_enabled_feature_name': v8_utilities.runtime_enabled_feature_name(method), # [RuntimeEnabled]
'secure_context_test': v8_utilities.secure_context(method, interface), # [SecureContext]
'side_effect_type': side_effect_type, # [Affects]
+ 'snake_case_name': NameStyleConverter(name).to_snake_case(),
'use_output_parameter_for_result': idl_type.use_output_parameter_for_result,
'use_local_result': use_local_result(method),
'v8_set_return_value': v8_set_return_value(interface.name, method, this_cpp_value),
@@ -267,6 +276,7 @@ def argument_context(interface, method, argument, index, is_visible=True):
this_cpp_type = idl_type.cpp_type_args(extended_attributes=extended_attributes,
raw_type=True,
used_as_variadic_argument=argument.is_variadic)
+ snake_case_name = NameStyleConverter(argument.name).to_snake_case()
context = {
'cpp_type': (
v8_types.cpp_template_type('base::Optional', this_cpp_type)
@@ -274,10 +284,9 @@ def argument_context(interface, method, argument, index, is_visible=True):
else this_cpp_type),
'cpp_value': this_cpp_value,
# FIXME: check that the default value's type is compatible with the argument's
- 'set_default_value': set_default_value,
'enum_type': idl_type.enum_type,
'enum_values': idl_type.enum_values,
- 'handle': '%sHandle' % argument.name,
+ 'handle': '%s_handle' % snake_case_name,
# FIXME: remove once [Default] removed and just use argument.default_value
'has_default': 'Default' in extended_attributes or set_default_value,
'has_type_checking_interface': has_type_checking_interface,
@@ -295,7 +304,9 @@ def argument_context(interface, method, argument, index, is_visible=True):
'is_variadic': argument.is_variadic,
'is_variadic_wrapper_type': is_variadic_wrapper_type,
'is_wrapper_type': idl_type.is_wrapper_type,
+ 'local_cpp_variable': snake_case_name,
'name': argument.name,
+ 'set_default_value': set_default_value,
'use_permissive_dictionary_conversion': 'PermissiveDictionaryConversion' in extended_attributes,
'v8_set_return_value': v8_set_return_value(interface.name, method, this_cpp_value),
'v8_set_return_value_for_main_world': v8_set_return_value(interface.name, method, this_cpp_value, for_main_world=True),
@@ -333,15 +344,16 @@ def cpp_value(interface, method, number_of_arguments):
not method.is_static):
cpp_arguments.append('*impl')
for argument in arguments:
+ variable_name = NameStyleConverter(argument.name).to_snake_case()
if argument.idl_type.base_type == 'SerializedScriptValue':
- cpp_arguments.append('std::move(%s)' % argument.name)
+ cpp_arguments.append('std::move(%s)' % variable_name)
else:
- cpp_arguments.append(argument.name)
+ cpp_arguments.append(variable_name)
if ('RaisesException' in method.extended_attributes or
(method.is_constructor and
has_extended_attribute_value(interface, 'RaisesException', 'Constructor'))):
- cpp_arguments.append('exceptionState')
+ cpp_arguments.append('exception_state')
# If a method returns an IDL dictionary or union type, the return value is
# passed as an argument to impl classes.
@@ -385,9 +397,9 @@ def v8_value_to_local_cpp_variadic_value(argument, index):
argument.extended_attributes, True)
return {
- 'assign_expression': 'ToImplArguments<%s>(info, %s, exceptionState)' % (idl_type, index),
- 'check_expression': 'exceptionState.HadException()',
- 'cpp_name': argument.name,
+ 'assign_expression': 'ToImplArguments<%s>(info, %s, exception_state)' % (idl_type, index),
+ 'check_expression': 'exception_state.HadException()',
+ 'cpp_name': NameStyleConverter(argument.name).to_snake_case(),
'declare_variable': False,
}
@@ -400,7 +412,7 @@ def v8_value_to_local_cpp_ssv_value(extended_attributes, idl_type, v8_value, var
'info.GetIsolate()',
v8_value,
'{ssv}::SerializeOptions({ssv}::{storage_policy})',
- 'exceptionState'
+ 'exception_state'
])
cpp_expression_format = 'NativeValueTraits<{ssv}>::NativeValue(%s)' % arguments
this_cpp_value = cpp_expression_format.format(
@@ -410,7 +422,7 @@ def v8_value_to_local_cpp_ssv_value(extended_attributes, idl_type, v8_value, var
return {
'assign_expression': this_cpp_value,
- 'check_expression': 'exceptionState.HadException()',
+ 'check_expression': 'exception_state.HadException()',
'cpp_type': this_cpp_type,
'cpp_name': variable_name,
'declare_variable': False,
@@ -420,7 +432,7 @@ def v8_value_to_local_cpp_ssv_value(extended_attributes, idl_type, v8_value, var
def v8_value_to_local_cpp_value(interface_name, method, argument, index):
extended_attributes = argument.extended_attributes
idl_type = argument.idl_type
- name = argument.name
+ name = NameStyleConverter(argument.name).to_snake_case()
v8_value = 'info[{index}]'.format(index=index)
# History.pushState and History.replaceState are explicitly specified as
@@ -459,6 +471,7 @@ def property_attributes(interface, method):
def argument_set_default_value(argument):
idl_type = argument.idl_type
default_value = argument.default_value
+ variable_name = NameStyleConverter(argument.name).to_snake_case()
if not default_value:
return None
if idl_type.is_dictionary:
@@ -493,9 +506,9 @@ def argument_set_default_value(argument):
member_type_name = (member_type.inner_type.name
if member_type.is_nullable else
member_type.name)
- return '%s.Set%s(%s)' % (argument.name, member_type_name,
+ return '%s.Set%s(%s)' % (variable_name, member_type_name,
member_type.literal_cpp_value(default_value))
- return '%s = %s' % (argument.name,
+ return '%s = %s' % (variable_name,
idl_type.literal_cpp_value(default_value))
IdlArgument.set_default_value = property(argument_set_default_value)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_types.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_types.py
index 033ac59aafe..7bb7a2fc29a 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_types.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_types.py
@@ -141,32 +141,20 @@ CPP_SPECIAL_CONVERSION_RULES = {
}
-def string_resource_mode(idl_type, extended_attributes=None):
+def string_resource_mode(idl_type):
"""Returns a V8StringResourceMode value corresponding to the IDL type.
Args:
idl_type:
A string IdlType.
- extended_attributes:
- A mapping type with extended attribute names and values.
"""
- extended_attributes = extended_attributes or {}
-
if idl_type.is_nullable:
return 'kTreatNullAndUndefinedAsNullString'
- # TODO(lisabelle): Remove these 4 lines when we have fully supported
- # annoteted types. (crbug.com/714866)
- # It is because at that time 'TreatNullAs' will only appear in
- # type_extended_attributes, not in extended_attributes.
- if extended_attributes.get('TreatNullAs') == 'EmptyString':
- return 'kTreatNullAsEmptyString'
- if extended_attributes.get('TreatNullAs') == 'NullString':
- return 'kTreatNullAsNullString'
- type_extended_attributes = idl_type.extended_attributes or {}
- if type_extended_attributes.get('TreatNullAs') == 'EmptyString':
- return 'kTreatNullAsEmptyString'
- if type_extended_attributes.get('TreatNullAs') == 'NullString':
- return 'kTreatNullAsNullString'
+ if idl_type.is_annotated_type:
+ treat_null_as = idl_type.extended_attributes.get('TreatNullAs')
+ if treat_null_as == 'EmptyString':
+ return 'kTreatNullAsEmptyString'
+ raise ValueError('Unknown value for [TreatNullAs]: %s' % treat_null_as)
return ''
@@ -251,7 +239,7 @@ def cpp_type(idl_type, extended_attributes=None, raw_type=False, used_as_rvalue_
if idl_type.is_string_type:
if not raw_type:
return 'const String&' if used_as_rvalue_type else 'String'
- return 'V8StringResource<%s>' % string_resource_mode(idl_type, extended_attributes)
+ return 'V8StringResource<%s>' % string_resource_mode(idl_type)
if base_idl_type == 'ArrayBufferView' and 'FlexibleArrayBufferView' in extended_attributes:
return 'FlexibleArrayBufferView'
@@ -263,17 +251,15 @@ def cpp_type(idl_type, extended_attributes=None, raw_type=False, used_as_rvalue_
return cpp_template_type('MaybeShared', idl_type.implemented_as)
else:
return cpp_template_type('NotShared', idl_type.implemented_as)
- if idl_type.is_interface_type:
+ if idl_type.is_interface_type or idl_type.is_dictionary:
implemented_as_class = idl_type.implemented_as
- if raw_type or (used_as_rvalue_type and idl_type.is_garbage_collected) or not used_in_cpp_sequence:
+ if raw_type or not used_in_cpp_sequence:
return implemented_as_class + '*'
if not used_in_cpp_sequence:
return implemented_as_class + '*'
+ if used_as_rvalue_type and idl_type.is_garbage_collected:
+ return 'const %s*' % implemented_as_class
return cpp_template_type('Member', implemented_as_class)
- if idl_type.is_dictionary:
- if used_as_rvalue_type:
- return 'const %s&' % idl_type.implemented_as
- return idl_type.implemented_as
if idl_type.is_union_type:
# Avoid "AOrNullOrB" for cpp type of (A? or B) because we generate
# V8AOrBOrNull to handle nulle for (A? or B), (A or B?) and (A or B)?
@@ -388,14 +374,14 @@ IdlType.set_garbage_collected_types = classmethod(
def is_gc_type(idl_type):
- return idl_type.is_garbage_collected or idl_type.is_dictionary or idl_type.is_union_type
+ return idl_type.is_garbage_collected or idl_type.is_union_type
IdlTypeBase.is_gc_type = property(is_gc_type)
def is_traceable(idl_type):
- return idl_type.is_garbage_collected or idl_type.is_dictionary or idl_type.is_callback_function
+ return idl_type.is_garbage_collected or idl_type.is_callback_function
IdlTypeBase.is_traceable = property(is_traceable)
IdlUnionType.is_traceable = property(lambda self: True)
@@ -630,11 +616,8 @@ def native_value_traits_type_name(idl_type, extended_attributes, in_sequence_or_
if idl_type.is_string_type:
# Strings are handled separately because null and/or undefined are
# processed by V8StringResource due to the [TreatNullAs] extended
- # attribute (it also handles nullable string types).
- name = 'IDL%s' % (idl_type.inner_type.name if idl_type.is_nullable else idl_type.name)
- resource_mode = string_resource_mode(idl_type, extended_attributes)
- if resource_mode:
- name = cpp_template_type('%sBase' % name, resource_mode)
+ # attribute and nullable string types.
+ name = 'IDL%s' % idl_type.name
elif idl_type.is_nullable:
inner_type = native_value_traits_type_name(idl_type.inner_type, extended_attributes)
# IDLNullable is only required for sequences and such.
@@ -669,38 +652,26 @@ def v8_value_to_cpp_value(idl_type, extended_attributes, v8_value, variable_name
# Simple types
idl_type = idl_type.preprocessed_type
base_idl_type = idl_type.as_union_type.name if idl_type.is_union_type else idl_type.base_type
- type_extended_attributes = idl_type.extended_attributes or {}
if 'FlexibleArrayBufferView' in extended_attributes:
if base_idl_type not in ARRAY_BUFFER_VIEW_AND_TYPED_ARRAY_TYPES:
raise ValueError('Unrecognized base type for extended attribute "FlexibleArrayBufferView": %s' % (idl_type.base_type))
+ if 'AllowShared' not in extended_attributes:
+ raise ValueError('"FlexibleArrayBufferView" extended attribute requires "AllowShared" on %s' % (idl_type.base_type))
base_idl_type = 'FlexibleArrayBufferView'
if 'AllowShared' in extended_attributes and not idl_type.is_array_buffer_view_or_typed_array:
raise ValueError('Unrecognized base type for extended attribute "AllowShared": %s' % (idl_type.base_type))
if idl_type.is_integer_type:
- configuration = 'kNormalConversion'
- # TODO(lisabelle): Remove these 4 lines when we have fully supported
- # annoteted types.
- # It is because at that time 'Clamp' and 'EnforceRange' will only
- # appear in type_extended_attributes, not in extended_attributes.
- if 'EnforceRange' in extended_attributes:
- configuration = 'kEnforceRange'
- elif 'Clamp' in extended_attributes:
- configuration = 'kClamp'
- if 'EnforceRange' in type_extended_attributes:
- configuration = 'kEnforceRange'
- elif 'Clamp' in type_extended_attributes:
- configuration = 'kClamp'
- arguments = ', '.join([v8_value, 'exceptionState', configuration])
+ arguments = ', '.join([v8_value, 'exception_state'])
elif base_idl_type == 'SerializedScriptValue':
arguments = ', '.join([
v8_value,
'SerializedScriptValue::SerializeOptions(SerializedScriptValue::kNotForStorage)',
- 'exceptionState'])
+ 'exception_state'])
elif idl_type.v8_conversion_needs_exception_state:
- arguments = ', '.join([v8_value, 'exceptionState'])
+ arguments = ', '.join([v8_value, 'exception_state'])
else:
arguments = v8_value
@@ -713,9 +684,9 @@ def v8_value_to_cpp_value(idl_type, extended_attributes, v8_value, variable_name
elif idl_type.is_array_buffer_view_or_typed_array:
this_cpp_type = idl_type.cpp_type_args(extended_attributes=extended_attributes)
if 'AllowShared' in extended_attributes:
- cpp_expression_format = ('ToMaybeShared<%s>({isolate}, {v8_value}, exceptionState)' % this_cpp_type)
+ cpp_expression_format = ('ToMaybeShared<%s>({isolate}, {v8_value}, exception_state)' % this_cpp_type)
else:
- cpp_expression_format = ('ToNotShared<%s>({isolate}, {v8_value}, exceptionState)' % this_cpp_type)
+ cpp_expression_format = ('ToNotShared<%s>({isolate}, {v8_value}, exception_state)' % this_cpp_type)
elif idl_type.is_union_type:
nullable = 'UnionTypeConversionMode::kNullable' if idl_type.includes_nullable_type \
@@ -723,10 +694,10 @@ def v8_value_to_cpp_value(idl_type, extended_attributes, v8_value, variable_name
# We need to consider the moving of the null through the union in order
# to generate the correct V8* class name.
this_cpp_type = idl_type.cpp_type_args(extended_attributes=extended_attributes)
- cpp_expression_format = '%s::ToImpl({isolate}, {v8_value}, {variable_name}, %s, exceptionState)' % \
+ cpp_expression_format = '%s::ToImpl({isolate}, {v8_value}, {variable_name}, %s, exception_state)' % \
(v8_type(this_cpp_type), nullable)
elif idl_type.use_output_parameter_for_result:
- cpp_expression_format = 'V8{idl_type}::ToImpl({isolate}, {v8_value}, {variable_name}, exceptionState)'
+ cpp_expression_format = 'V8{idl_type}::ToImpl({isolate}, {v8_value}, {variable_name}, exception_state)'
elif idl_type.is_callback_function:
cpp_expression_format = 'V8{idl_type}::Create({v8_value}.As<v8::Function>())'
elif idl_type.v8_conversion_needs_exception_state:
@@ -769,9 +740,9 @@ def v8_value_to_local_cpp_value(idl_type, extended_attributes, v8_value, variabl
elif idl_type.is_string_type or idl_type.v8_conversion_needs_exception_state:
# Types for which conversion can fail and that need error handling.
- check_expression = 'exceptionState.HadException()'
+ check_expression = 'exception_state.HadException()'
- if idl_type.is_dictionary or idl_type.is_union_type:
+ if idl_type.is_union_type:
set_expression = cpp_value
else:
assign_expression = cpp_value
@@ -781,7 +752,7 @@ def v8_value_to_local_cpp_value(idl_type, extended_attributes, v8_value, variabl
# as the condition here would be wrong.
if not idl_type.v8_conversion_needs_exception_state:
if use_exception_state:
- check_expression = '!%s.Prepare(exceptionState)' % variable_name
+ check_expression = '!%s.Prepare(exception_state)' % variable_name
else:
check_expression = '!%s.Prepare()' % variable_name
elif not idl_type.v8_conversion_is_trivial and not idl_type.is_callback_function:
@@ -812,7 +783,7 @@ def use_output_parameter_for_result(idl_type):
"""True when methods/getters which return the given idl_type should
take the output argument.
"""
- return idl_type.is_dictionary or idl_type.is_union_type
+ return idl_type.is_union_type
IdlTypeBase.use_output_parameter_for_result = property(use_output_parameter_for_result)
@@ -822,14 +793,13 @@ IdlTypeBase.use_output_parameter_for_result = property(use_output_parameter_for_
################################################################################
def preprocess_idl_type(idl_type):
- extended_attributes = idl_type.extended_attributes
if idl_type.is_nullable:
return IdlNullableType(idl_type.inner_type.preprocessed_type)
if idl_type.is_enum:
# Enumerations are internally DOMStrings
- return IdlType('DOMString', extended_attributes)
+ return IdlType('DOMString')
if idl_type.base_type in ['any', 'object'] or idl_type.is_custom_callback_function:
- return IdlType('ScriptValue', extended_attributes)
+ return IdlType('ScriptValue')
if idl_type.is_callback_function:
return idl_type
return idl_type
@@ -973,8 +943,8 @@ V8_SET_RETURN_VALUE = {
'Dictionary': 'V8SetReturnValue(info, {cpp_value})',
'DictionaryStatic': '#error not implemented yet',
# Nullable dictionaries
- 'NullableDictionary': 'V8SetReturnValue(info, result.value())',
- 'NullableDictionaryStatic': 'V8SetReturnValue(info, result.value(), info.GetIsolate()->GetCurrentContext()->Global())',
+ 'NullableDictionary': 'V8SetReturnValue(info, result)',
+ 'NullableDictionaryStatic': 'V8SetReturnValue(info, result, info.GetIsolate()->GetCurrentContext()->Global())',
# Union types or dictionaries
'DictionaryOrUnion': 'V8SetReturnValue(info, result)',
'DictionaryOrUnionStatic': 'V8SetReturnValue(info, result, info.GetIsolate()->GetCurrentContext()->Global())',
@@ -1020,7 +990,7 @@ IdlTypeBase.v8_set_return_value = v8_set_return_value
CPP_VALUE_TO_V8_VALUE = {
# Built-in types
- 'Date': 'V8DateOrNaN({isolate}, {cpp_value})',
+ 'Date': 'v8::Date::New({isolate}->GetCurrentContext(), {cpp_value})',
'DOMString': 'V8String({isolate}, {cpp_value})',
'ByteString': 'V8String({isolate}, {cpp_value})',
'USVString': 'V8String({isolate}, {cpp_value})',
@@ -1038,8 +1008,9 @@ CPP_VALUE_TO_V8_VALUE = {
'unrestricted float': 'v8::Number::New({isolate}, {cpp_value})',
'double': 'v8::Number::New({isolate}, {cpp_value})',
'unrestricted double': 'v8::Number::New({isolate}, {cpp_value})',
- 'void': 'v8Undefined()',
- 'StringOrNull': '{cpp_value}.IsNull() ? v8::Local<v8::Value>(v8::Null({isolate})) : V8String({isolate}, {cpp_value})',
+ 'StringOrNull': ('({cpp_value}.IsNull() ? ' +
+ 'v8::Null({isolate}).As<v8::Value>() : ' +
+ 'V8String({isolate}, {cpp_value}).As<v8::Value>())'),
# Special cases
'Dictionary': '{cpp_value}.V8Value()',
'EventHandler':
@@ -1148,7 +1119,7 @@ def cpp_type_has_null_value(idl_type):
# - String types (String/AtomicString) represent null as a null string,
# i.e. one for which String::IsNull() returns true.
# - Enum types, as they are implemented as Strings.
- # - Interface types (raw pointer) represent null as a null pointer.
+ # - Interface types and Dictionary types represent null as a null pointer.
# - Union types, as thier container classes can represent null value.
# - 'Object' and 'any' type. We use ScriptValue for object type.
return (idl_type.is_string_type
@@ -1157,6 +1128,7 @@ def cpp_type_has_null_value(idl_type):
or idl_type.is_callback_interface
or idl_type.is_callback_function
or idl_type.is_custom_callback_function
+ or idl_type.is_dictionary
or idl_type.is_union_type
or idl_type.base_type == 'object' or idl_type.base_type == 'any')
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_union.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_union.py
index 686310b529f..fc2a8638a18 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_union.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_union.py
@@ -145,12 +145,13 @@ def member_context(member, info_provider):
_update_includes_and_forward_decls(member, info_provider)
if member.is_nullable:
member = member.inner_type
+ type_name = (member.inner_type if member.is_annotated_type else member).name
return {
'cpp_name': to_snake_case(v8_utilities.cpp_name(member)),
'cpp_type': member.cpp_type_args(used_in_cpp_sequence=True),
'cpp_local_type': member.cpp_type,
'cpp_value_to_v8_value': member.cpp_value_to_v8_value(
- cpp_value='impl.GetAs%s()' % member.name, isolate='isolate',
+ cpp_value='impl.GetAs%s()' % type_name, isolate='isolate',
creation_context='creationContext'),
'enum_type': member.enum_type,
'enum_values': member.enum_values,
@@ -159,8 +160,8 @@ def member_context(member, info_provider):
'is_traceable': member.is_traceable,
'rvalue_cpp_type': member.cpp_type_args(used_as_rvalue_type=True),
'specific_type_enum': 'k' + member.name,
- 'type_name': member.name,
+ 'type_name': type_name,
'v8_value_to_local_cpp_value': member.v8_value_to_local_cpp_value(
- {}, 'v8Value', 'cppValue', isolate='isolate',
+ {}, 'v8_value', 'cpp_value', isolate='isolate',
use_exception_state=True)
}
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/v8_utilities.py b/chromium/third_party/blink/renderer/bindings/scripts/v8_utilities.py
index cc1a95418c5..0d523207b43 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/v8_utilities.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/v8_utilities.py
@@ -206,13 +206,13 @@ def activity_logging_world_check(member):
# [CallWith]
CALL_WITH_ARGUMENTS = {
- 'ScriptState': 'scriptState',
- 'ExecutionContext': 'executionContext',
- 'ScriptArguments': 'scriptArguments',
+ 'ScriptState': 'script_state',
+ 'ExecutionContext': 'execution_context',
+ 'ScriptArguments': 'script_arguments',
'CurrentWindow': 'CurrentDOMWindow(info.GetIsolate())',
'EnteredWindow': 'EnteredDOMWindow(info.GetIsolate())',
'Document': 'document',
- 'ThisValue': 'ScriptValue(scriptState, info.Holder())',
+ 'ThisValue': 'ScriptValue(script_state, info.Holder())',
}
# List because key order matters, as we want arguments in deterministic order
CALL_WITH_VALUES = [
@@ -304,12 +304,12 @@ class ExposureSet:
@staticmethod
def _code(exposure):
- exposed = ('executionContext->%s()' %
+ condition = ('execution_context->%s()' %
EXPOSED_EXECUTION_CONTEXT_METHOD[exposure.exposed])
if exposure.runtime_enabled is not None:
runtime_enabled = (runtime_enabled_function(exposure.runtime_enabled))
- return '({0} && {1})'.format(exposed, runtime_enabled)
- return exposed
+ return '({0} && {1})'.format(condition, runtime_enabled)
+ return condition
def code(self):
if len(self.exposures) == 0:
@@ -350,10 +350,10 @@ def exposed(member, interface):
# [SecureContext]
def secure_context(member, interface):
"""Returns C++ code that checks whether an interface/method/attribute/etc. is exposed
- to the current context. Requires that the surrounding code defines an 'isSecureContext'
+ to the current context. Requires that the surrounding code defines an |is_secure_context|
variable prior to this check."""
if 'SecureContext' in member.extended_attributes or 'SecureContext' in interface.extended_attributes:
- conditions = ['isSecureContext']
+ conditions = ['is_secure_context']
if 'SecureContext' in member.extended_attributes and member.extended_attributes['SecureContext'] is not None:
conditions.append('!%s' % runtime_enabled_function(member.extended_attributes['SecureContext']))
if 'SecureContext' in interface.extended_attributes and interface.extended_attributes['SecureContext'] is not None:
@@ -426,7 +426,7 @@ def origin_trial_feature_name(definition_or_member):
def origin_trial_function_call(feature_name, execution_context=None):
"""Returns a function call to determine if an origin trial is enabled."""
- return 'OriginTrials::{feature_name}Enabled({context})'.format(
+ return 'origin_trials::{feature_name}Enabled({context})'.format(
feature_name=feature_name,
context=execution_context if execution_context else "execution_context")
@@ -466,14 +466,14 @@ def is_legacy_interface_type_checking(interface, member):
'LegacyInterfaceTypeChecking' in member.extended_attributes)
-# [Unforgeable], [Global], [PrimaryGlobal]
+# [Unforgeable], [Global]
def on_instance(interface, member):
"""Returns True if the interface's member needs to be defined on every
instance object.
The following members must be defined on an instance object.
- [Unforgeable] members
- - regular members of [Global] or [PrimaryGlobal] interfaces
+ - regular members of [Global] interfaces
"""
if member.is_static:
return False
@@ -488,8 +488,7 @@ def on_instance(interface, member):
if is_constructor_attribute(member):
return True
- if ('PrimaryGlobal' in interface.extended_attributes or
- 'Global' in interface.extended_attributes or
+ if ('Global' in interface.extended_attributes or
'Unforgeable' in member.extended_attributes):
return True
return False
@@ -503,8 +502,8 @@ def on_prototype(interface, member):
follows.
- static members (optional)
- [Unforgeable] members
- - members of [Global] or [PrimaryGlobal] interfaces
- - named properties of [Global] or [PrimaryGlobal] interfaces
+ - members of [Global] interfaces
+ - named properties of [Global] interfaces
"""
if member.is_static:
return False
@@ -519,8 +518,7 @@ def on_prototype(interface, member):
if is_constructor_attribute(member):
return False
- if ('PrimaryGlobal' in interface.extended_attributes or
- 'Global' in interface.extended_attributes or
+ if ('Global' in interface.extended_attributes or
'Unforgeable' in member.extended_attributes):
return False
return True
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collection.py b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collection.py
index a206cc800ec..751e6308527 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collection.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collection.py
@@ -2,162 +2,26 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-from .callback_function import CallbackFunction
-from .callback_interface import CallbackInterface
-from .dictionary import Dictionary
-from .enumeration import Enumeration
-from .implements import Implements
-from .interface import Interface
-from .namespace import Namespace
-from .typedef import Typedef
-
class Collection(object):
"""
- Collection class stores Web IDL definitions and some meta information.
+ Collection class stores ASTs of Web IDL files and meta information
+ like component.
"""
def __init__(self, component=None):
- self._interfaces = {}
- self._callback_interfaces = {}
- self._namespaces = {}
- self._dictionaries = {}
- self._enumerations = {}
- self._callback_functions = {}
- self._typedefs = {}
- # In spec, different partial definitions can have same identifiers.
- # So they are stored in a list, which is indexed by the identifier.
- # i.e. {'identifer': [definition, definition, ...]}
- self._partial_interfaces = {}
- self._partial_namespaces = {}
- self._partial_dictionaries = {}
- # Implements statements are not named definitions.
- self._implements = []
- # These members are not in spec., but they are necessary for code generators.
- self._metadata_store = []
+ self._asts = []
self._component = component
- def find_non_partial_definition(self, identifier):
- """Returns a non-partial named definition, if it is defined. Otherwise returns None."""
- if identifier in self._interfaces:
- return self._interfaces[identifier]
- if identifier in self._callback_interfaces:
- return self._callback_interfaces[identifier]
- if identifier in self._namespaces:
- return self._namespaces[identifier]
- if identifier in self._dictionaries:
- return self._dictionaries[identifier]
- if identifier in self._enumerations:
- return self._enumerations[identifier]
- if identifier in self._callback_functions:
- return self._callback_functions[identifier]
- if identifier in self._typedefs:
- return self._typedefs[identifier]
- return None
-
- def find_partial_definition(self, identifier):
- if identifier in self._partial_interfaces:
- return self._partial_interfaces[identifier]
- if identifier in self._partial_namespaces:
- return self._partial_namespaces[identifier]
- if identifier in self._partial_dictionaries:
- return self._partial_dictionaries[identifier]
- return []
-
- def find_filepath(self, definition):
- for metadata in self._metadata_store:
- if metadata.definition == definition:
- return metadata.filepath
- return None
-
- def register_definition(self, definition, filepath):
- if type(definition) == Interface:
- if definition.is_partial:
- self._register_partial_definition(self._partial_interfaces, definition)
- else:
- self._register_definition(self._interfaces, definition)
- elif type(definition) == Namespace:
- if definition.is_partial:
- self._register_partial_definition(self._partial_namespaces, definition)
- else:
- self._register_definition(self._namespaces, definition)
- elif type(definition) == Dictionary:
- if definition.is_partial:
- self._register_partial_definition(self._partial_dictionaries, definition)
- else:
- self._register_definition(self._dictionaries, definition)
- elif type(definition) == CallbackInterface:
- self._register_definition(self._callback_interfaces, definition)
- elif type(definition) == Enumeration:
- self._register_definition(self._enumerations, definition)
- elif type(definition) == Typedef:
- self._register_definition(self._typedefs, definition)
- elif type(definition) == CallbackFunction:
- self._register_definition(self._callback_functions, definition)
- elif type(definition) == Implements:
- self._implements.append(definition)
- else:
- raise ValueError('Unrecognized class definition %s in %s' % (str(type(definition)), filepath))
-
- metadata = _Metadata(definition, filepath)
- self._metadata_store.append(metadata)
-
- @property
- def interface_identifiers(self):
- return self._interfaces.keys()
-
- @property
- def callback_interface_identifiers(self):
- return self._callback_interfaces.keys()
-
- @property
- def namespace_identifiers(self):
- return self._namespaces.keys()
-
- @property
- def dictionary_identifiers(self):
- return self._dictionaries.keys()
-
- @property
- def enumeration_identifiers(self):
- return self._enumerations.keys()
-
- @property
- def callback_function_identifiers(self):
- return self._callback_functions.keys()
-
- @property
- def typedef_identifiers(self):
- return self._typedefs.keys()
+ def add_ast(self, ast):
+ assert ast.GetClass() == 'File', (
+ 'Root node of an AST must be a File node., but is %s.' % ast.GetClass())
+ self._asts.append(ast)
@property
- def implements(self):
- return self._implements
+ def asts(self):
+ return self._asts
@property
def component(self):
return self._component
-
- def _register_definition(self, definitions, definition):
- identifier = definition.identifier
- previous_definition = self.find_non_partial_definition(identifier)
- if previous_definition and previous_definition == definition:
- raise ValueError('Conflict: %s is defined in %s and %s' %
- (identifier, self.find_filepath(previous_definition),
- self.find_filepath(definition)))
- definitions[identifier] = definition
-
- def _register_partial_definition(self, definitions, definition):
- identifier = definition.identifier
- if identifier not in definitions:
- definitions[identifier] = []
- definitions[identifier].append(definition)
-
-
-class _Metadata(object):
- """Metadata holds information of a definition which is not in spec.
- - |filepath| shows the .idl file name where the definition is described.
- """
- def __init__(self, definition, filepath):
- self._definition = definition
- self._filepath = filepath
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector.py b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector.py
index 180ea47579f..07c31340ce6 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector.py
@@ -2,19 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import os
-import sys
-
-from .idl_definition_builder import IdlDefinitionBuilder
-from .collection import Collection
-
-
-# TODO(peria): Merge bindings/scripts/blink_idl_parser.py with tools/idl_parser,
-# and put in this directory. Then we can remove this sys.path update.
-_SCRIPTS_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)
-sys.path.append(_SCRIPTS_PATH)
-
import blink_idl_parser
+from .collection import Collection
class Collector(object):
@@ -25,7 +14,7 @@ class Collector(object):
self._parser = parser
def collect_from_idl_files(self, filepaths):
- if type(filepaths) == str:
+ if isinstance(filepaths, str):
filepaths = [filepaths]
for filepath in filepaths:
try:
@@ -39,8 +28,7 @@ class Collector(object):
self.collect_from_ast(ast)
def collect_from_ast(self, node):
- for definition, filepath in IdlDefinitionBuilder.idl_definitions(node):
- self._collection.register_definition(definition, filepath)
+ self._collection.add_ast(node)
def get_collection(self):
return self._collection
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector_test.py b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector_test.py
deleted file mode 100755
index 0678b0347cf..00000000000
--- a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/collector_test.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/python
-# Copyright 2017 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import unittest
-
-from .collector import Collector
-
-
-class CollectorTest(unittest.TestCase):
-
- def setUp(self):
- self._collector = Collector(component='test')
-
- def collect_from_idl_text(self, idl_text):
- self._collector.collect_from_idl_text(idl_text)
- return self._collector.get_collection()
-
- def test_definition_filters(self):
- idl_text = """
- interface MyInterface {};
- partial interface MyInterface {};
- dictionary MyDictionary {};
- dictionary MyDictionary2 {};
- partial dictionary MyPartialDictionary {};
- namespace MyNamespace {};
- partial namespace MyNamespace {};
- partial namespace MyNamespace2 {};
- partial namespace MyNamespace2 {};
- enum MyEnum { "FOO" };
- callback MyCallbackFunction = void (DOMString arg);
- typedef sequence<Point> Points;
- Foo implements Bar;
- """
- collection = self.collect_from_idl_text(idl_text)
- self.assertEqual(1, len(collection.callback_function_identifiers))
- self.assertEqual(1, len(collection.enumeration_identifiers))
- self.assertEqual(1, len(collection.interface_identifiers))
- self.assertEqual(1, len(collection.namespace_identifiers))
- self.assertEqual(1, len(collection.typedef_identifiers))
- self.assertEqual(2, len(collection.dictionary_identifiers))
- self.assertEqual(1, len(collection.implements))
- self.assertEqual(2, len(collection.find_partial_definition('MyNamespace2')))
-
- def test_interface(self):
- idl_text = """
- interface InterfaceSimpleMembers {
- void operation1(DOMString arg);
- attribute long longMember;
- };
- interface InheritInterface : InheritedInterface {};
- partial interface PartialInterface {
- attribute long longMember;
- };
- partial interface PartialInterface {
- attribute long long longlongMember;
- };
- """
- collection = self.collect_from_idl_text(idl_text)
-
- interface = collection.find_non_partial_definition('InterfaceSimpleMembers')
- self.assertEqual('InterfaceSimpleMembers', interface.identifier)
- self.assertEqual(1, len(interface.attributes))
- self.assertEqual(1, len(interface.operations))
- self.assertEqual('operation1', interface.operations[0].identifier)
- self.assertEqual('longMember', interface.attributes[0].identifier)
-
- interface = collection.find_non_partial_definition('InheritInterface')
- self.assertEqual('InheritInterface', interface.identifier)
- self.assertEqual('InheritedInterface', interface.inherited_interface_name)
-
- partial_interfaces = collection.find_partial_definition('PartialInterface')
- self.assertTrue(partial_interfaces[0].is_partial)
- self.assertTrue(partial_interfaces[1].is_partial)
- attribute = partial_interfaces[0].attributes[0]
- self.assertEqual('longMember', attribute.identifier)
- attribute = partial_interfaces[1].attributes[0]
- self.assertEqual('longlongMember', attribute.identifier)
-
- idl_text = """
- interface InterfaceAttributes {
- attribute long longAttr;
- readonly attribute octet readonlyAttr;
- static attribute DOMString staticStringAttr;
- attribute [TreatNullAs=EmptyString] DOMString annotatedTypeAttr;
- [Unforgeable] attribute DOMString? extendedAttributeAttr;
- };
- """
- collection = self.collect_from_idl_text(idl_text)
- interface = collection.find_non_partial_definition('InterfaceAttributes')
- attributes = interface.attributes
- self.assertEqual(5, len(attributes))
- attribute = attributes[0]
- self.assertEqual('longAttr', attribute.identifier)
- self.assertEqual('Long', attribute.type.type_name)
-
- attribute = attributes[1]
- self.assertEqual('readonlyAttr', attribute.identifier)
- self.assertEqual('Octet', attribute.type.type_name)
- self.assertTrue(attribute.is_readonly)
-
- attribute = attributes[2]
- self.assertEqual('staticStringAttr', attribute.identifier)
- self.assertEqual('String', attribute.type.type_name)
- self.assertTrue(attribute.is_static)
-
- attribute = attributes[3]
- self.assertEqual('annotatedTypeAttr', attribute.identifier)
- self.assertEqual('String', attribute.type.type_name)
- self.assertEqual('EmptyString', attribute.type.treat_null_as)
-
- attribute = attributes[4]
- self.assertEqual('extendedAttributeAttr', attribute.identifier)
- self.assertEqual('String', attribute.type.type_name)
- self.assertTrue(attribute.type.is_nullable)
- self.assertTrue(attribute.extended_attribute_list.has('Unforgeable'))
-
- def test_extended_attributes(self):
- idl_text = """
- [
- NoInterfaceObject,
- OriginTrialEnabled=FooBar
- ] interface ExtendedAttributeInterface {};
- """
- collection = self.collect_from_idl_text(idl_text)
-
- interface = collection.find_non_partial_definition('ExtendedAttributeInterface')
- extended_attribute_list = interface.extended_attribute_list
- self.assertTrue(extended_attribute_list.has('OriginTrialEnabled'))
- self.assertTrue(extended_attribute_list.has('NoInterfaceObject'))
- self.assertEqual('FooBar', extended_attribute_list.get('OriginTrialEnabled'))
-
- idl_text = """
- [
- Constructor,
- Constructor(DOMString arg),
- CustomConstructor,
- CustomConstructor(long arg),
- NamedConstructor=Audio,
- NamedConstructor=Audio(DOMString src)
- ] interface ConstructorInterface {};
- """
- collection = self.collect_from_idl_text(idl_text)
-
- interface = collection.find_non_partial_definition('ConstructorInterface')
- constructors = interface.constructors
- self.assertEqual(4, len(constructors))
- self.assertFalse(constructors[0].is_custom)
- self.assertFalse(constructors[1].is_custom)
- self.assertTrue(constructors[2].is_custom)
- self.assertTrue(constructors[3].is_custom)
- named_constructors = interface.named_constructors
- self.assertEqual('Audio', named_constructors[0].identifier)
- self.assertEqual('Audio', named_constructors[1].identifier)
- self.assertEqual('arg', constructors[1].arguments[0].identifier)
- self.assertEqual('arg', constructors[3].arguments[0].identifier)
- self.assertEqual('src', named_constructors[1].arguments[0].identifier)
-
- idl_text = """
- [
- Exposed=(Window, Worker),
- Exposed(Window Feature1, Worker Feature2)
- ] interface ExposedInterface {};
- """
- collection = self.collect_from_idl_text(idl_text)
-
- interface = collection.find_non_partial_definition('ExposedInterface')
- exposures = interface.exposures
- self.assertEqual(4, len(exposures))
- self.assertEqual('Window', exposures[0].global_interface)
- self.assertEqual('Worker', exposures[1].global_interface)
- self.assertEqual('Window', exposures[2].global_interface)
- self.assertEqual('Worker', exposures[3].global_interface)
- self.assertEqual('Feature1', exposures[2].runtime_enabled_feature)
- self.assertEqual('Feature2', exposures[3].runtime_enabled_feature)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py
index d1884ec79c7..ab1ead19435 100644
--- a/chromium/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py
+++ b/chromium/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py
@@ -95,7 +95,7 @@ class StringType(TypeBase):
@param StringType.TreatNullAs treat_null_as : argument of an extended attribute [TreatNullAs] (optional)
"""
STRING_TYPES = ('DOMString', 'ByteString', 'USVString')
- TREAT_NULL_AS = ('EmptyString', 'NullString')
+ TREAT_NULL_AS = ('EmptyString',)
def __init__(self, **kwargs):
self._string_type = kwargs.pop('string_type')
diff --git a/chromium/third_party/blink/renderer/bindings/templates/attributes.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/attributes.cc.tmpl
index f569e78a6dd..3f3d94dcd9f 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/attributes.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/attributes.cc.tmpl
@@ -1,36 +1,38 @@
-{% from 'utilities.cpp.tmpl' import declare_enum_validation_variable, v8_value_to_local_cpp_value %}
-{% from 'methods.cpp.tmpl' import runtime_timer_scope, runtime_timer_scope_disabled_by_default %}
+{% from 'utilities.cc.tmpl' import declare_enum_validation_variable, v8_value_to_local_cpp_value %}
+{% from 'methods.cc.tmpl' import runtime_timer_scope, runtime_timer_scope_disabled_by_default %}
{##############################################################################}
{% macro attribute_getter(attribute, world_suffix) %}
-static void {{attribute.name}}AttributeGetter{{world_suffix}}(
+static void {{attribute.camel_case_name}}AttributeGetter{{world_suffix}}(
{%- if attribute.is_data_type_property %}
const v8::PropertyCallbackInfo<v8::Value>& info
{%- else %}
const v8::FunctionCallbackInfo<v8::Value>& info
{%- endif %}) {
- {% filter format_remove_duplicates(['ExceptionState exceptionState']) %}
+ {% filter format_remove_duplicates(['ExceptionState exception_state']) %}
{% set define_exception_state -%}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kGetterContext, "{{interface_name}}", "{{attribute.name}}");
+ ExceptionState exception_state(
+ info.GetIsolate(), ExceptionState::kGetterContext,
+ "{{interface_name}}", "{{attribute.name}}");
{%- endset %}
{% if attribute.is_lenient_this %}
// [LenientThis]
// Make sure that info.Holder() really points to an instance if [LenientThis].
- if (!{{v8_class}}::hasInstance(info.Holder(), info.GetIsolate()))
+ if (!{{v8_class}}::HasInstance(info.Holder(), info.GetIsolate()))
return; // Return silently because of [LenientThis].
{% elif attribute.has_promise_type %}
// This attribute returns a Promise.
// Per https://heycam.github.io/webidl/#dfn-attribute-getter, all exceptions
// must be turned into a Promise rejection.
{{define_exception_state}}
- ExceptionToRejectPromiseScope rejectPromiseScope(info, exceptionState);
+ ExceptionToRejectPromiseScope reject_promise_scope(info, exception_state);
// Returning a Promise type requires us to disable some of V8's type checks,
// so we have to manually check that info.Holder() really points to an
// instance of the type.
- if (!{{v8_class}}::hasInstance(info.Holder(), info.GetIsolate())) {
- exceptionState.ThrowTypeError("Illegal invocation");
+ if (!{{v8_class}}::HasInstance(info.Holder(), info.GetIsolate())) {
+ exception_state.ThrowTypeError("Illegal invocation");
return;
}
{% endif %}
@@ -41,7 +43,7 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% if attribute.is_save_same_object %}
// [SaveSameObject]
- {% set same_object_private_key = interface_name + attribute.name[0]|capitalize + attribute.name[1:] %}
+ {% set same_object_private_key = interface_name + attribute.camel_case_name %}
// If you see a compile error that
// V8PrivateProperty::GetSameObject{{same_object_private_key}}
// is not defined, then you need to register your attribute at
@@ -49,9 +51,9 @@ const v8::FunctionCallbackInfo<v8::Value>& info
// X(SameObject, {{same_object_private_key}})
auto privateSameObject = V8PrivateProperty::GetSameObject{{same_object_private_key}}(info.GetIsolate());
{
- v8::Local<v8::Value> v8Value;
- if (privateSameObject.GetOrUndefined(holder).ToLocal(&v8Value) && !v8Value->IsUndefined()) {
- V8SetReturnValue(info, v8Value);
+ v8::Local<v8::Value> v8_value;
+ if (privateSameObject.GetOrUndefined(holder).ToLocal(&v8_value) && !v8_value->IsUndefined()) {
+ V8SetReturnValue(info, v8_value);
return;
}
}
@@ -61,7 +63,7 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% set local_dom_window_only = interface_name == 'Window' and not attribute.has_cross_origin_getter %}
{% if local_dom_window_only %}
{% if attribute.is_check_security_for_receiver %}
- {{cpp_class}}* uncheckedImpl = {{v8_class}}::ToImpl(holder);
+ {{cpp_class}}* unchecked_impl = {{v8_class}}::ToImpl(holder);
{% else %}
// Same-origin attribute getters are never exposed via the cross-origin
// interceptors. Since same-origin access requires a LocalDOMWindow, it is
@@ -75,13 +77,13 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% if attribute.cached_attribute_validation_method %}
// [CachedAttribute]
- V8PrivateProperty::Symbol propertySymbol =
+ V8PrivateProperty::Symbol property_symbol =
V8PrivateProperty::GetSymbol(info.GetIsolate(),
- "{{cpp_class}}#{{attribute.name.capitalize()}}");
+ "{{cpp_class}}#{{attribute.camel_case_name}}");
if (!static_cast<const {{cpp_class}}*>(impl)->{{attribute.cached_attribute_validation_method}}()) {
- v8::Local<v8::Value> v8Value;
- if (propertySymbol.GetOrUndefined(holder).ToLocal(&v8Value) && !v8Value->IsUndefined()) {
- V8SetReturnValue(info, v8Value);
+ v8::Local<v8::Value> v8_value;
+ if (property_symbol.GetOrUndefined(holder).ToLocal(&v8_value) && !v8_value->IsUndefined()) {
+ V8SetReturnValue(info, v8_value);
return;
}
}
@@ -91,15 +93,15 @@ const v8::FunctionCallbackInfo<v8::Value>& info
// Perform a security check for the receiver object.
{{define_exception_state}}
{% if local_dom_window_only %}
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), uncheckedImpl, exceptionState)) {
+ if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), unchecked_impl, exception_state)) {
{% else %}
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), impl, exceptionState)) {
+ if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), impl, exception_state)) {
{% endif %}{# local_dom_window_only #}
V8SetReturnValueNull(info);
return;
}
{% if local_dom_window_only %}
- LocalDOMWindow* impl = ToLocalDOMWindow(uncheckedImpl);
+ LocalDOMWindow* impl = ToLocalDOMWindow(unchecked_impl);
{% endif %}{# local_dom_window_only #}
{% endif %}
@@ -108,7 +110,7 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{{define_exception_state}}
if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), {{attribute.cpp_value}}, BindingSecurity::ErrorReportOption::kDoNotReport)) {
UseCounter::Count(CurrentExecutionContext(info.GetIsolate()),
- WebFeature::kCrossOrigin{{interface_name}}{{attribute.name|blink_capitalize}});
+ WebFeature::kCrossOrigin{{interface_name}}{{attribute.camel_case_name}});
V8SetReturnValueNull(info);
return;
}
@@ -116,17 +118,17 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% if attribute.is_call_with_execution_context %}
{% if attribute.is_static %}
- ExecutionContext* executionContext = ExecutionContext::ForCurrentRealm(info);
+ ExecutionContext* execution_context = ExecutionContext::ForCurrentRealm(info);
{% else %}
- ExecutionContext* executionContext = ExecutionContext::ForRelevantRealm(info);
+ ExecutionContext* execution_context = ExecutionContext::ForRelevantRealm(info);
{% endif %}
{% endif %}
{% if attribute.is_call_with_script_state %}
{% if attribute.is_static %}
- ScriptState* scriptState = ScriptState::ForCurrentRealm(info);
+ ScriptState* script_state = ScriptState::ForCurrentRealm(info);
{% else %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{% endif %}
@@ -134,7 +136,7 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{{define_exception_state}}
{% endif %}
{% if attribute.is_explicit_nullable %}
- bool isNull = false;
+ bool is_null = false;
{% endif %}
{% if attribute.cpp_value_original %}
@@ -147,7 +149,7 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% endif %}
{% if attribute.is_getter_raises_exception %}
- if (UNLIKELY(exceptionState.HadException()))
+ if (UNLIKELY(exception_state.HadException()))
return;
{% endif %}
@@ -160,12 +162,12 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% if attribute.cached_attribute_validation_method %}
// [CachedAttribute]
- v8::Local<v8::Value> v8Value({{attribute.cpp_value_to_v8_value}});
- propertySymbol.Set(holder, v8Value);
+ v8::Local<v8::Value> v8_value({{attribute.cpp_value_to_v8_value}});
+ property_symbol.Set(holder, v8_value);
{% endif %}
{% if attribute.is_explicit_nullable %}
- if (isNull) {
+ if (is_null) {
V8SetReturnValueNull(info);
return;
}
@@ -176,10 +178,10 @@ const v8::FunctionCallbackInfo<v8::Value>& info
// object is alive in order to save creation time of the wrapper object.
if ({{attribute.cpp_value}} && DOMDataStore::SetReturnValue{{world_suffix}}(info.GetReturnValue(), {{attribute.cpp_value_to_script_wrappable}}))
return;
- v8::Local<v8::Value> v8Value(ToV8({{attribute.cpp_value_to_script_wrappable}}, holder, info.GetIsolate()));
+ v8::Local<v8::Value> v8_value(ToV8({{attribute.cpp_value_to_script_wrappable}}, holder, info.GetIsolate()));
V8PrivateProperty::GetSymbol(
info.GetIsolate(), "KeepAlive#{{interface_name}}#{{attribute.name}}")
- .Set(holder, v8Value);
+ .Set(holder, v8_value);
{% endif %}
{% if world_suffix %}
@@ -233,7 +235,7 @@ if ({{cpp_value}}.IsEmpty()) {
{##############################################################################}
{% macro attribute_getter_callback(attribute, world_suffix) %}
-void {{v8_class_or_partial}}::{{attribute.name}}AttributeGetterCallback{{world_suffix}}(
+void {{v8_class_or_partial}}::{{attribute.camel_case_name}}AttributeGetterCallback{{world_suffix}}(
{%- if attribute.is_data_type_property %}
v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info
{%- else %}
@@ -255,24 +257,24 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% if world_suffix in attribute.activity_logging_world_list_for_getter %}
{% if attribute.is_static %}
- ScriptState* scriptState = ScriptState::ForCurrentRealm(info);
+ ScriptState* script_state = ScriptState::ForCurrentRealm(info);
{% else %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
- V8PerContextData* contextData = scriptState->PerContextData();
+ V8PerContextData* context_data = script_state->PerContextData();
if (
{%- if attribute.activity_logging_world_check -%}
- scriptState->World().IsIsolatedWorld() && {# one space at the end #}
+ script_state->World().IsIsolatedWorld() && {# one space at the end #}
{%- endif -%}
- contextData && contextData->ActivityLogger()) {
- contextData->ActivityLogger()->LogGetter("{{interface_name}}.{{attribute.name}}");
+ context_data && context_data->ActivityLogger()) {
+ context_data->ActivityLogger()->LogGetter("{{interface_name}}.{{attribute.name}}");
}
{% endif %}
{% if attribute.has_custom_getter %}
- {{v8_class}}::{{attribute.name}}AttributeGetterCustom(info);
+ {{v8_class}}::{{attribute.camel_case_name}}AttributeGetterCustom(info);
{% else %}
- {{cpp_class_or_partial}}V8Internal::{{attribute.name}}AttributeGetter{{world_suffix}}(info);
+ {{internal_namespace}}::{{attribute.camel_case_name}}AttributeGetter{{world_suffix}}(info);
{% endif %}
}
{% endmacro %}
@@ -280,7 +282,8 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{##############################################################################}
{% macro constructor_getter_callback(attribute, world_suffix) %}
-void {{v8_class_or_partial}}::{{attribute.name}}ConstructorGetterCallback{{world_suffix}}(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::{{attribute.camel_case_name}}ConstructorGetterCallback{{world_suffix}}(
+ v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(attribute.runtime_call_stats.constructor_getter_callback_counter) }}
{% if attribute.deprecate_as %}
Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), WebFeature::k{{attribute.deprecate_as}});
@@ -293,7 +296,7 @@ void {{v8_class_or_partial}}::{{attribute.name}}ConstructorGetterCallback{{world
{% if attribute.is_named_constructor %}
V8{{attribute.constructor_type}}::NamedConstructorAttributeGetter(property, info);
{% else %}
- V8ConstructorAttributeGetter(property, info, &V8{{attribute.constructor_type}}::wrapperTypeInfo);
+ V8ConstructorAttributeGetter(property, info, &V8{{attribute.constructor_type}}::wrapper_type_info);
{% endif %}
}
{% endmacro %}
@@ -301,15 +304,15 @@ void {{v8_class_or_partial}}::{{attribute.name}}ConstructorGetterCallback{{world
{##############################################################################}
{% macro attribute_setter(attribute, world_suffix) %}
-static void {{attribute.name}}AttributeSetter{{world_suffix}}(
-{%- if attribute.has_cross_origin_setter %}
-v8::Local<v8::Value> v8Value, const V8CrossOriginSetterInfo& info
-{%- elif attribute.is_data_type_property %}
-v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info
-{%- else %}
-v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
-{%- endif %}) {
- {% filter format_remove_duplicates(['ExceptionState exceptionState']) %}
+static void {{attribute.camel_case_name}}AttributeSetter{{world_suffix}}(
+ {% if attribute.has_cross_origin_setter %}
+ v8::Local<v8::Value> v8_value, const V8CrossOriginSetterInfo& info
+ {% elif attribute.is_data_type_property %}
+ v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<void>& info
+ {% else %}
+ v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info
+ {%- endif %}) {
+ {% filter format_remove_duplicates(['ExceptionState exception_state']) %}
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
@@ -317,13 +320,13 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
ALLOW_UNUSED_LOCAL(holder);
{% set define_exception_state -%}
- ExceptionState exceptionState(isolate, ExceptionState::kSetterContext, "{{interface_name}}", "{{attribute.name}}");
+ ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "{{interface_name}}", "{{attribute.name}}");
{%- endset %}
{% if attribute.is_lenient_this %}
// [LenientThis]
// Make sure that info.Holder() really points to an instance if [LenientThis].
- if (!{{v8_class}}::hasInstance(holder, isolate))
+ if (!{{v8_class}}::HasInstance(holder, isolate))
return; // Return silently because of [LenientThis].
{% endif %}
@@ -331,7 +334,7 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
{% set local_dom_window_only = interface_name == 'Window' and not attribute.has_cross_origin_setter %}
{% if local_dom_window_only %}
{% if attribute.is_check_security_for_receiver %}
- {{cpp_class}}* uncheckedImpl = {{v8_class}}::ToImpl(holder);
+ {{cpp_class}}* unchecked_impl = {{v8_class}}::ToImpl(holder);
{% else %}
// Same-origin attributes setters are never exposed via the cross-origin
// interceptors. Since same-origin access requires a LocalDOMWindow, it is
@@ -347,15 +350,15 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
// Perform a security check for the receiver object.
{{define_exception_state}}
{% if local_dom_window_only %}
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(isolate), uncheckedImpl, exceptionState)) {
+ if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(isolate), unchecked_impl, exception_state)) {
{% else %}
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(isolate), impl, exceptionState)) {
+ if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(isolate), impl, exception_state)) {
{% endif %}{# local_dom_window_only #}
- V8SetReturnValue(info, v8Value);
+ V8SetReturnValue(info, v8_value);
return;
}
{% if local_dom_window_only %}
- LocalDOMWindow* impl = ToLocalDOMWindow(uncheckedImpl);
+ LocalDOMWindow* impl = ToLocalDOMWindow(unchecked_impl);
{% endif %}{# local_dom_window_only #}
{% endif %}
@@ -367,20 +370,26 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
// [PutForwards] => {{attribute.name}}.{{attribute.target_attribute_name}}
{{define_exception_state}}
v8::Local<v8::Value> target;
- if (!holder->Get(isolate->GetCurrentContext(), V8AtomicString(isolate, "{{attribute.name}}")).ToLocal(&target))
+ if (!holder->Get(isolate->GetCurrentContext(), V8AtomicString(isolate, "{{attribute.name}}"))
+ .ToLocal(&target)) {
return;
+ }
if (!target->IsObject()) {
- exceptionState.ThrowTypeError("The attribute value is not an object");
+ exception_state.ThrowTypeError("The attribute value is not an object");
return;
}
bool result;
- if (!target.As<v8::Object>()->Set(isolate->GetCurrentContext(), V8AtomicString(isolate, "{{attribute.target_attribute_name}}"), v8Value).To(&result))
+ if (!target.As<v8::Object>()->Set(
+ isolate->GetCurrentContext(),
+ V8AtomicString(isolate, "{{attribute.target_attribute_name}}"),
+ v8_value).To(&result)) {
return;
+ }
if (!result)
return;
{% else %}{# attribute.is_put_forwards #}
{% if attribute.is_custom_element_callbacks or attribute.is_reflect %}
- V0CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
+ V0CustomElementProcessingStack::CallbackDeliveryScope delivery_scope;
{% endif %}
{% if attribute.has_setter_exception_state %}
@@ -397,8 +406,8 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
{% if attribute.has_type_checking_interface %}
// Type check per: http://heycam.github.io/webidl/#es-interface
- if (!cppValue{% if attribute.is_nullable %} && !IsUndefinedOrNull(v8Value){% endif %}) {
- exceptionState.ThrowTypeError("The provided value is not of type '{{attribute.idl_type}}'.");
+ if (!cpp_value{% if attribute.is_nullable %} && !IsUndefinedOrNull(v8_value){% endif %}) {
+ exception_state.ThrowTypeError("The provided value is not of type '{{attribute.idl_type}}'.");
return;
}
{% endif %}
@@ -406,47 +415,50 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
{% if attribute.enum_values %}
// Type check per: http://heycam.github.io/webidl/#dfn-attribute-setter
// Returns undefined without setting the value if the value is invalid.
- DummyExceptionStateForTesting dummyExceptionState;
- {{declare_enum_validation_variable(attribute.enum_values) | trim | indent(2)}}
- if (!IsValidEnum(cppValue, validValues, base::size(validValues), "{{attribute.enum_type}}", dummyExceptionState)) {
- ExecutionContext::ForCurrentRealm(info)->AddConsoleMessage(
- ConsoleMessage::Create(kJSMessageSource, kWarningMessageLevel,
- dummyExceptionState.Message()));
- return;
+ DummyExceptionStateForTesting dummy_exception_state;
+ {
+ {{declare_enum_validation_variable(attribute.enum_values) | trim | indent(2)}}
+ if (!IsValidEnum(cpp_value, kValidValues, base::size(kValidValues),
+ "{{attribute.enum_type}}", dummy_exception_state)) {
+ ExecutionContext::ForCurrentRealm(info)->AddConsoleMessage(
+ ConsoleMessage::Create(kJSMessageSource, kWarningMessageLevel,
+ dummy_exception_state.Message()));
+ return;
+ }
}
{% endif %}
{% if attribute.is_call_with_execution_context or
attribute.is_setter_call_with_execution_context %}
{% if attribute.is_static %}
- ExecutionContext* executionContext = ExecutionContext::ForCurrentRealm(info);
+ ExecutionContext* execution_context = ExecutionContext::ForCurrentRealm(info);
{% else %}
- ExecutionContext* executionContext = ExecutionContext::ForRelevantRealm(info);
+ ExecutionContext* execution_context = ExecutionContext::ForRelevantRealm(info);
{% endif %}
{% endif %}
{% if attribute.is_call_with_script_state or
attribute.is_setter_call_with_script_state %}
{% if attribute.is_static %}
- ScriptState* scriptState = ScriptState::ForCurrentRealm(info);
+ ScriptState* script_state = ScriptState::ForCurrentRealm(info);
{% else %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{% endif %}
{% if attribute.is_replaceable %}
- v8::Local<v8::String> propertyName = V8AtomicString(isolate, "{{attribute.name}}");
+ v8::Local<v8::String> property_name = V8AtomicString(isolate, "{{attribute.name}}");
{% endif %}
{% if attribute.is_explicit_nullable %}
- bool isNull = IsUndefinedOrNull(v8Value);
+ bool is_null = IsUndefinedOrNull(v8_value);
{% endif %}
- {{attribute.cpp_setter}};
+ {{attribute.cpp_setter | indent(2)}};
{% if attribute.cached_attribute_validation_method %}
// [CachedAttribute]
// Invalidate the cached value.
V8PrivateProperty::GetSymbol(
- isolate, "{{cpp_class}}#{{attribute.name.capitalize()}}")
+ isolate, "{{cpp_class}}#{{attribute.camel_case_name}}")
.DeleteProperty(holder, v8::Undefined(isolate));
{% endif %}
{% endif %}{# attribute.is_put_forwards #}
@@ -457,12 +469,12 @@ v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info
{##############################################################################}
{% macro attribute_setter_callback(attribute, world_suffix) %}
-void {{v8_class_or_partial}}::{{attribute.name}}AttributeSetterCallback{{world_suffix}}(
-{%- if attribute.is_data_type_property %}
-v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info
-{%- else %}
-const v8::FunctionCallbackInfo<v8::Value>& info
-{%- endif %}) {
+void {{v8_class_or_partial}}::{{attribute.camel_case_name}}AttributeSetterCallback{{world_suffix}}(
+ {% if attribute.is_data_type_property %}
+ v8::Local<v8::Name>, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<void>& info
+ {% else %}
+ const v8::FunctionCallbackInfo<v8::Value>& info
+ {%- endif %}) {
{% if attribute.is_lenient_setter %}
// Setter for {{attribute.name}} is no-op because [LenientSetter] is specified.
{% else %}
@@ -473,7 +485,7 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% endif %}
{% if not attribute.is_data_type_property %}
- v8::Local<v8::Value> v8Value = info[0];
+ v8::Local<v8::Value> v8_value = info[0];
{% endif %}
{% if attribute.deprecate_as %}
@@ -486,26 +498,27 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{% if world_suffix in attribute.activity_logging_world_list_for_setter %}
{% if attribute.is_static %}
- ScriptState* scriptState = ScriptState::ForCurrentRealm(info);
+ ScriptState* script_state = ScriptState::ForCurrentRealm(info);
{% else %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
- V8PerContextData* contextData = scriptState->PerContextData();
+ V8PerContextData* context_data = script_state->PerContextData();
if (
{%- if attribute.activity_logging_world_check -%}
- scriptState->World().IsIsolatedWorld() && {# one space at the end #}
+ script_state->World().IsIsolatedWorld() && {# one space at the end #}
{%- endif -%}
- contextData && contextData->ActivityLogger()) {
- contextData->ActivityLogger()->LogSetter("{{interface_name}}.{{attribute.name}}", v8Value);
+ context_data && context_data->ActivityLogger()) {
+ context_data->ActivityLogger()->LogSetter("{{interface_name}}.{{attribute.name}}", v8_value);
}
{% endif %}
{% if attribute.has_custom_setter %}
- {{v8_class}}::{{attribute.name}}AttributeSetterCustom(v8Value, info);
+ {{v8_class}}::{{attribute.camel_case_name}}AttributeSetterCustom(v8_value, info);
{% elif attribute.has_cross_origin_setter %}
- {{cpp_class_or_partial}}V8Internal::{{attribute.name}}AttributeSetter(v8Value, V8CrossOriginSetterInfo(info.GetIsolate(), info.Holder()));
+ {{internal_namespace}}::{{attribute.camel_case_name}}AttributeSetter(
+ v8_value, V8CrossOriginSetterInfo(info.GetIsolate(), info.Holder()));
{% else %}
- {{cpp_class_or_partial}}V8Internal::{{attribute.name}}AttributeSetter{{world_suffix}}(v8Value, info);
+ {{internal_namespace}}::{{attribute.camel_case_name}}AttributeSetter{{world_suffix}}(v8_value, info);
{% endif %}
{% endif %}{# attribute.is_lenient_setter #}
}
@@ -514,13 +527,13 @@ const v8::FunctionCallbackInfo<v8::Value>& info
{##############################################################################}
{% macro build_attribute_or_accessor_configuration(attribute, config_type) %}
-{% from 'utilities.cpp.tmpl' import property_location %}
+{% from 'utilities.cc.tmpl' import property_location %}
{% if attribute.constructor_type %}
- {% set getter_callback = '%s::%sConstructorGetterCallback' % (v8_class_or_partial, attribute.name) %}
+ {% set getter_callback = '%s::%sConstructorGetterCallback' % (v8_class_or_partial, attribute.camel_case_name) %}
{% set setter_callback = 'nullptr' %}
{% else %}{# regular attributes #}
- {% set getter_callback = '%s::%sAttributeGetterCallback' % (v8_class_or_partial, attribute.name) %}
- {% set setter_callback = '%s::%sAttributeSetterCallback' % (v8_class_or_partial, attribute.name)
+ {% set getter_callback = '%s::%sAttributeGetterCallback' % (v8_class_or_partial, attribute.camel_case_name) %}
+ {% set setter_callback = '%s::%sAttributeSetterCallback' % (v8_class_or_partial, attribute.camel_case_name)
if attribute.has_setter else 'nullptr' %}
{% endif %}
@@ -606,7 +619,7 @@ static const V8DOMConfiguration::AccessorConfiguration accessor_configurations[]
{% endfor %}
};
V8DOMConfiguration::InstallAccessors(
- isolate, world, instanceObject, prototypeObject, interfaceObject,
+ isolate, world, instance_object, prototype_object, interface_object,
signature, accessor_configurations,
base::size(accessor_configurations));
{% endfilter %}{# runtime_enabled #}
@@ -632,7 +645,7 @@ static const V8DOMConfiguration::AttributeConfiguration attribute_configurations
{% endfor %}
};
V8DOMConfiguration::InstallAttributes(
- isolate, world, instanceObject, prototypeObject,
+ isolate, world, instance_object, prototype_object,
attribute_configurations, base::size(attribute_configurations));
{% endfilter %}{# runtime_enabled #}
{% endfor %}{# secure_context_attribute_list grouped by runtime_enabled #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/callback_function.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/callback_function.cc.tmpl
index 9331774ef04..9331774ef04 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/callback_function.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/callback_function.cc.tmpl
diff --git a/chromium/third_party/blink/renderer/bindings/templates/callback_function.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/callback_function.h.tmpl
index 832a7216061..bb739787bd1 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/callback_function.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/callback_function.h.tmpl
@@ -1,9 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-
-#ifndef {{cpp_class}}_h
-#define {{cpp_class}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -20,9 +19,13 @@ class {{exported}}{{cpp_class}} final : public CallbackFunctionBase {
static {{cpp_class}}* Create(
{%- if is_treat_non_object_as_null %}v8::Local<v8::Object>
{%- else %}v8::Local<v8::Function>{% endif %} callback_function) {
- return new {{cpp_class}}(callback_function);
+ return MakeGarbageCollected<{{cpp_class}}>(callback_function);
}
+ explicit {{cpp_class}}(
+ {%- if is_treat_non_object_as_null %}v8::Local<v8::Object>
+ {%- else %}v8::Local<v8::Function>{% endif %} callback_function)
+ : CallbackFunctionBase(callback_function) {}
~{{cpp_class}}() override = default;
// NameClient overrides:
@@ -62,12 +65,6 @@ class {{exported}}{{cpp_class}} final : public CallbackFunctionBase {
// This function may throw unlike InvokeAndReportException.
v8::Maybe<{{return_cpp_type}}> InvokeWithoutRunnabilityCheck({{argument_declarations | join(', ')}}) WARN_UNUSED_RESULT;
{% endif %}
-
- private:
- explicit {{cpp_class}}(
- {%- if is_treat_non_object_as_null %}v8::Local<v8::Object>
- {%- else %}v8::Local<v8::Function>{% endif %} callback_function)
- : CallbackFunctionBase(callback_function) {}
};
template <>
@@ -107,6 +104,6 @@ Persistent<{{cpp_class}}> WrapPersistent({{cpp_class}}*) = delete;
} // namespace blink
-#endif // {{cpp_class}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/callback_interface.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl
index 9dd81941727..527221ba342 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/callback_interface.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl
@@ -20,7 +20,7 @@ namespace blink {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
-const WrapperTypeInfo {{v8_class}}::wrapperTypeInfo = {
+const WrapperTypeInfo {{v8_class}}::wrapper_type_info = {
gin::kEmbedderBlink,
{{v8_class}}::DomTemplate,
nullptr,
@@ -34,7 +34,7 @@ const WrapperTypeInfo {{v8_class}}::wrapperTypeInfo = {
#pragma clang diagnostic pop
#endif
-{% from 'constants.cpp.tmpl' import install_constants with context %}
+{% from 'constants.cc.tmpl' import install_constants with context %}
static void Install{{v8_class}}Template(v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) {
// Legacy callback interface must not have a prototype object.
interface_template->RemovePrototype();
@@ -42,15 +42,14 @@ static void Install{{v8_class}}Template(v8::Isolate* isolate, const DOMWrapperWo
// Initialize the interface object's template.
V8DOMConfiguration::InitializeDOMInterfaceTemplate(
isolate, interface_template,
- {{v8_class}}::wrapperTypeInfo.interface_name,
+ {{v8_class}}::wrapper_type_info.interface_name,
v8::Local<v8::FunctionTemplate>(),
kV8DefaultWrapperInternalFieldCount);
interface_template->SetLength(0);
// Register IDL constants.
- {# |install_constants| requires |interfaceTemplate| and |prototypeTemplate|. #}
- v8::Local<v8::FunctionTemplate> interfaceTemplate = interface_template;
- v8::Local<v8::ObjectTemplate> prototypeTemplate =
+ {# |install_constants| requires |interface_template| and |prototype_template|. #}
+ v8::Local<v8::ObjectTemplate> prototype_template =
interface_template->PrototypeTemplate();
{{install_constants() | trim | indent(2)}}
}
@@ -60,7 +59,7 @@ v8::Local<v8::FunctionTemplate> {{v8_class}}::DomTemplate(v8::Isolate* isolate,
return V8DOMConfiguration::DomClassTemplate(
isolate,
world,
- const_cast<WrapperTypeInfo*>(&wrapperTypeInfo),
+ const_cast<WrapperTypeInfo*>(&wrapper_type_info),
Install{{v8_class}}Template);
}
{% endif %}{# is_legacy_callback_interface #}
@@ -79,7 +78,7 @@ const char* {{v8_class}}::NameInHeapSnapshot() const {
if (creation_context.IsEmpty())
return nullptr;
- return new {{v8_class}}(callback_object, creation_context);
+ return MakeGarbageCollected<{{v8_class}}>(callback_object, creation_context);
}
{% for method in methods %}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl
index 50c2951dd58..2fdb7be87fb 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl
@@ -1,9 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-
-#ifndef {{v8_class}}_h
-#define {{v8_class}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -20,7 +19,7 @@ class {{exported}}{{v8_class}} final : public CallbackInterfaceBase {
{% if is_legacy_callback_interface %}
// Support of "legacy callback interface"
static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&);
- static const WrapperTypeInfo wrapperTypeInfo;
+ static const WrapperTypeInfo wrapper_type_info;
// Constants
{% for constant in constants %}
static constexpr {{constant.cpp_type}} {{constant.name}} = {{constant.value}};
@@ -33,6 +32,14 @@ class {{exported}}{{v8_class}} final : public CallbackInterfaceBase {
// See also crbug.com/886588
static {{v8_class}}* CreateOrNull(v8::Local<v8::Object> callback_object);
+{% set single_operation_enum_value =
+ 'kSingleOperation' if is_single_operation_callback_interface else
+ 'kNotSingleOperation' %}
+ explicit {{v8_class}}(
+ v8::Local<v8::Object> callback_object,
+ v8::Local<v8::Context> callback_object_creation_context)
+ : CallbackInterfaceBase(callback_object, callback_object_creation_context,
+ {{single_operation_enum_value}}) {}
~{{v8_class}}() override = default;
// NameClient overrides:
@@ -65,16 +72,6 @@ class {{exported}}{{v8_class}} final : public CallbackInterfaceBase {
// This function may throw unlike InvokeAndReportException.
v8::Maybe<{{methods[0].cpp_type}}> InvokeWithoutRunnabilityCheck({{methods[0].argument_declarations | join(', ')}}) WARN_UNUSED_RESULT;
{% endif %}
-
- private:
-{% set single_operation_enum_value =
- 'kSingleOperation' if is_single_operation_callback_interface else
- 'kNotSingleOperation' %}
- explicit {{v8_class}}(
- v8::Local<v8::Object> callback_object,
- v8::Local<v8::Context> callback_object_creation_context)
- : CallbackInterfaceBase(callback_object, callback_object_creation_context,
- {{single_operation_enum_value}}) {}
};
template <>
@@ -113,6 +110,6 @@ Persistent<{{v8_class}}> WrapPersistent({{v8_class}}*) = delete;
} // namespace blink
-#endif // {{v8_class}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/callback_invoke.cc.tmpl b/chromium/third_party/blink/renderer/bindings/templates/callback_invoke.cc.tmpl
index d6631cb6191..647fd8ae4d7 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/callback_invoke.cc.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/callback_invoke.cc.tmpl
@@ -1,4 +1,4 @@
-{% from 'utilities.cpp.tmpl' import declare_enum_validation_variable %}
+{% from 'utilities.cc.tmpl' import declare_enum_validation_variable %}
{# Implements callback interface\'s "call a user object's operation", or
callback function\'s "invoke" and/or "construct".
@@ -154,7 +154,7 @@
// Enum values provided by Blink must be valid, otherwise typo.
#if DCHECK_IS_ON()
{
- {% set valid_enum_variables = 'valid_' + argument.name + '_values' %}
+ {% set valid_enum_variables = 'kValid' + argument.name[0].upper() + argument.name[1:] + 'Values' %}
{{declare_enum_validation_variable(argument.enum_values, valid_enum_variables) | trim | indent(4)}}
ExceptionState exception_state(GetIsolate(),
ExceptionState::kExecutionContext,
diff --git a/chromium/third_party/blink/renderer/bindings/templates/constants.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/constants.cc.tmpl
index 1b8d27c0335..a9fba5a4017 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/constants.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/constants.cc.tmpl
@@ -1,8 +1,8 @@
-{% from 'methods.cpp.tmpl' import runtime_timer_scope_disabled_by_default %}
+{% from 'methods.cc.tmpl' import runtime_timer_scope_disabled_by_default %}
{##############################################################################}
{% macro constant_getter_callback(constant) %}
-void {{v8_class_or_partial}}::{{constant.name}}ConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::{{constant.camel_case_name}}ConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(constant.rcs_counter) }}
{% if constant.deprecate_as %}
Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), WebFeature::k{{constant.deprecate_as}});
@@ -25,20 +25,22 @@ void {{v8_class_or_partial}}::{{constant.name}}ConstantGetterCallback(v8::Local<
{% macro install_constants() %}
{% if constants | has_constant_configuration %}
{# Normal constants #}
-static constexpr V8DOMConfiguration::ConstantConfiguration {{v8_class}}Constants[] = {
- {% for constant in constants | has_constant_configuration %}
- {{constant_configuration(constant)}},
- {% endfor %}
-};
-V8DOMConfiguration::InstallConstants(
- isolate, interfaceTemplate, prototypeTemplate,
- {{v8_class}}Constants, base::size({{v8_class}}Constants));
+{
+ static constexpr V8DOMConfiguration::ConstantConfiguration kConstants[] = {
+ {% for constant in constants | has_constant_configuration %}
+ {{constant_configuration(constant)}},
+ {% endfor %}
+ };
+ V8DOMConfiguration::InstallConstants(
+ isolate, interface_template, prototype_template,
+ kConstants, base::size(kConstants));
+}
{% endif %}
{# Constants with [DeprecateAs] or [MeasureAs] #}
{% for constant in constants | has_special_getter %}
V8DOMConfiguration::InstallConstantWithGetter(
- isolate, interfaceTemplate, prototypeTemplate,
- "{{constant.name}}", {{v8_class_or_partial}}::{{constant.name}}ConstantGetterCallback);
+ isolate, interface_template, prototype_template,
+ "{{constant.name}}", {{v8_class_or_partial}}::{{constant.camel_case_name}}ConstantGetterCallback);
{% endfor %}
{# Check constants #}
{% if not do_not_check_constants %}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.cc.tmpl
index a08c3adb996..7af94dccb47 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.cc.tmpl
@@ -1,4 +1,4 @@
-{% from 'dictionary_impl_common.cpp.tmpl' import dictionary_setter_impl with context %}
+{% from 'dictionary_impl_common.cc.tmpl' import dictionary_setter_impl with context %}
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
@@ -21,11 +21,7 @@ namespace blink {
{% endfor %}
}
-{{cpp_class}}::~{{cpp_class}}() {}
-
-{{cpp_class}}::{{cpp_class}}(const {{cpp_class}}&) = default;
-
-{{cpp_class}}& {{cpp_class}}::operator=(const {{cpp_class}}&) = default;
+{{cpp_class}}::~{{cpp_class}}() = default;
{% for member in members if not member.setter_inline %}
{{dictionary_setter_impl(member)}}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl
index 8e485d33cc8..c4a5c7a23c0 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl
@@ -1,9 +1,9 @@
-{% from 'dictionary_impl_common.cpp.tmpl' import dictionary_setter_impl with context %}
+{% from 'dictionary_impl_common.cc.tmpl' import dictionary_setter_impl with context %}
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-#ifndef {{cpp_class}}_h
-#define {{cpp_class}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -16,13 +16,12 @@ class {{decl}};
{% endfor %}
{# FIXME: Add "final" if this class doesn\'t have subclasses #}
-class {{exported}}{{cpp_class}}{% if parent_cpp_class %} : public {{parent_cpp_class}}{% endif %} {
- DISALLOW_NEW();
+class {{exported}}{{cpp_class}} : public {{parent_cpp_class}} {
public:
+ static {{cpp_class}}* Create() { return MakeGarbageCollected<{{cpp_class}}>(); }
+
{{cpp_class}}();
virtual ~{{cpp_class}}();
- {{cpp_class}}(const {{cpp_class}}&);
- {{cpp_class}}& operator=(const {{cpp_class}}&);
{% for member in members %}
bool {{member.has_method_name}}() const { return {{member.has_method_expression}}; }
@@ -59,6 +58,6 @@ class {{exported}}{{cpp_class}}{% if parent_cpp_class %} : public {{parent_cpp_c
} // namespace blink
-#endif // {{cpp_class}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl_common.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl_common.cc.tmpl
index d4cf49b6baf..d4cf49b6baf 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl_common.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/dictionary_impl_common.cc.tmpl
diff --git a/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.cc.tmpl
index 1573a02795f..5562da43f2d 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.cc.tmpl
@@ -1,6 +1,6 @@
{% filter format_blink_cpp_source_code %}
-{% from 'utilities.cpp.tmpl' import declare_enum_validation_variable %}
+{% from 'utilities.cc.tmpl' import declare_enum_validation_variable %}
{% include 'copyright_block.txt' %}
#include "{{this_include_header_path}}"
@@ -22,32 +22,33 @@ static const v8::Eternal<v8::Name>* eternal{{v8_class}}Keys(v8::Isolate* isolate
}
{% endif %}
-{% from 'utilities.cpp.tmpl' import v8_value_to_local_cpp_value %}
-void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{cpp_class}}& impl, ExceptionState& exceptionState) {
- if (IsUndefinedOrNull(v8Value)) {
+{% from 'utilities.cc.tmpl' import v8_value_to_local_cpp_value %}
+void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8_value, {{cpp_class}}* impl, ExceptionState& exception_state) {
+ if (IsUndefinedOrNull(v8_value)) {
{% if required_member_names %}
- exceptionState.ThrowTypeError("Missing required member(s): {{required_member_names|join(', ')}}.");
+ exception_state.ThrowTypeError("Missing required member(s): {{required_member_names|join(', ')}}.");
{% endif %}
return;
}
- if (!v8Value->IsObject()) {
+ if (!v8_value->IsObject()) {
{% if use_permissive_dictionary_conversion %}
// Do nothing.
return;
{% else %}
- exceptionState.ThrowTypeError("cannot convert to dictionary.");
+ exception_state.ThrowTypeError("cannot convert to dictionary.");
return;
{% endif %}
}
- v8::Local<v8::Object> v8Object = v8Value.As<v8::Object>();
+ v8::Local<v8::Object> v8Object = v8_value.As<v8::Object>();
ALLOW_UNUSED_LOCAL(v8Object);
{% if parent_v8_class %}
- {{parent_v8_class}}::ToImpl(isolate, v8Value, impl, exceptionState);
- if (exceptionState.HadException())
+ {{parent_v8_class}}::ToImpl(isolate, v8_value, impl, exception_state);
+ if (exception_state.HadException())
return;
{% endif %}
+
{# Declare local variables only when the dictionary has members to avoid unused variable warnings. #}
{% if members %}
const v8::Eternal<v8::Name>* keys = eternal{{v8_class}}Keys(isolate);
@@ -65,19 +66,19 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
{% for member in member_list %}
v8::Local<v8::Value> {{member.v8_value}};
if (!v8Object->Get(context, keys[{{members.index(member)}}].Get(isolate)).ToLocal(&{{member.v8_value}})) {
- exceptionState.RethrowV8Exception(block.Exception());
+ exception_state.RethrowV8Exception(block.Exception());
return;
}
if ({{member.v8_value}}.IsEmpty() || {{member.v8_value}}->IsUndefined()) {
{% if member.is_required %}
- exceptionState.ThrowTypeError("required member {{member.name}} is undefined.");
+ exception_state.ThrowTypeError("required member {{member.name}} is undefined.");
return;
{% else %}
// Do nothing.
{% endif %}
{% if member.is_nullable and not member.is_string_type %}{# String types handle null via V8StringResource #}
} else if ({{member.v8_value}}->IsNull()) {
- impl.{{member.null_setter_name}}();
+ impl->{{member.null_setter_name}}();
{% endif %}
} else {
{% if member.deprecate_as %}
@@ -86,21 +87,21 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
{{v8_value_to_local_cpp_value(member) | trim | indent}}
{% if member.is_interface_type %}
if (!{{member.cpp_value}}) {
- exceptionState.ThrowTypeError("member {{member.name}} is not of type {{member.idl_type}}.");
+ exception_state.ThrowTypeError("member {{member.name}} is not of type {{member.idl_type}}.");
return;
}
{% endif %}
{% if member.enum_values %}
{{declare_enum_validation_variable(member.enum_values) | trim | indent}}
- if (!IsValidEnum({{member.cpp_value}}, validValues, base::size(validValues), "{{member.enum_type}}", exceptionState))
+ if (!IsValidEnum({{member.cpp_value}}, kValidValues, base::size(kValidValues), "{{member.enum_type}}", exception_state))
return;
{% elif member.is_object %}
if (!{{member.cpp_value}}.IsObject()) {
- exceptionState.ThrowTypeError("member {{member.name}} is not an object.");
+ exception_state.ThrowTypeError("member {{member.name}} is not an object.");
return;
}
{% endif %}
- impl.{{member.setter_name}}({{member.cpp_value}});
+ impl->{{member.setter_name}}({{member.cpp_value}});
}
{% endfor %}
@@ -114,12 +115,12 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
v8::Local<v8::Value> {{cpp_class}}::ToV8Impl(v8::Local<v8::Object> creationContext, v8::Isolate* isolate) const {
v8::Local<v8::Object> v8Object = v8::Object::New(isolate);
- if (!toV8{{cpp_class}}(*this, v8Object, creationContext, isolate))
+ if (!toV8{{cpp_class}}(this, v8Object, creationContext, isolate))
return v8::Undefined(isolate);
return v8Object;
}
-bool toV8{{cpp_class}}(const {{cpp_class}}& impl, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
+bool toV8{{cpp_class}}(const {{cpp_class}}* impl, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
{% if parent_v8_class %}
if (!toV8{{parent_cpp_class}}(impl, dictionary, creationContext, isolate))
return false;
@@ -128,6 +129,18 @@ bool toV8{{cpp_class}}(const {{cpp_class}}& impl, v8::Local<v8::Object> dictiona
{% if members %}
const v8::Eternal<v8::Name>* keys = eternal{{v8_class}}Keys(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
+
+ auto create_property = [dictionary, context, keys, isolate](
+ size_t key_index, v8::Local<v8::Value> value) {
+ bool added_property;
+ v8::Local<v8::Name> key = keys[key_index].Get(isolate);
+ if (!dictionary->CreateDataProperty(context, key, value)
+ .To(&added_property)) {
+ return false;
+ }
+ return added_property;
+ };
+
{% if has_origin_trial_members %}
ExecutionContext* executionContext = ToExecutionContext(context);
DCHECK(executionContext);
@@ -140,9 +153,9 @@ bool toV8{{cpp_class}}(const {{cpp_class}}& impl, v8::Local<v8::Object> dictiona
{% for member in member_list %}
v8::Local<v8::Value> {{member.v8_value}};
bool {{member.has_value_or_default}} = false;
- if (impl.{{member.has_method_name}}()) {
+ if (impl->{{member.has_method_name}}()) {
{% if member.is_object %}
- DCHECK(impl.{{member.getter_name}}().IsObject());
+ DCHECK(impl->{{member.getter_name}}().IsObject());
{% endif %}
{{member.v8_value}} = {{member.cpp_value_to_v8_value}};
{{member.has_value_or_default}} = true;
@@ -164,7 +177,7 @@ bool toV8{{cpp_class}}(const {{cpp_class}}& impl, v8::Local<v8::Object> dictiona
If there is not, then the compiler will inline this call into the only branch that sets it to true.
Either way, the code is efficient and the variable is completely elided. #}
if ({{member.has_value_or_default}} &&
- !V8CallBoolean(dictionary->CreateDataProperty(context, keys[{{members.index(member)}}].Get(isolate), {{member.v8_value}}))) {
+ !create_property({{members.index(member)}}, {{member.v8_value}})) {
return false;
}
@@ -178,9 +191,9 @@ bool toV8{{cpp_class}}(const {{cpp_class}}& impl, v8::Local<v8::Object> dictiona
return true;
}
-{{cpp_class}} NativeValueTraits<{{cpp_class}}>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
- {{cpp_class}} impl;
- {{v8_class}}::ToImpl(isolate, value, impl, exceptionState);
+{{cpp_class}}* NativeValueTraits<{{cpp_class}}>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) {
+ {{cpp_class}}* impl = {{cpp_class}}::Create();
+ {{v8_class}}::ToImpl(isolate, value, impl, exception_state);
return impl;
}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.h.tmpl
index e04f7dc2ba2..0a0cfa748c1 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/dictionary_v8.h.tmpl
@@ -1,8 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-#ifndef {{v8_original_class}}_h
-#define {{v8_original_class}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -14,24 +14,24 @@ class ExceptionState;
class {{v8_class}} {
public:
- {{exported}}static void ToImpl(v8::Isolate*, v8::Local<v8::Value>, {{cpp_class}}&, ExceptionState&);
+ {{exported}}static void ToImpl(v8::Isolate*, v8::Local<v8::Value>, {{cpp_class}}* impl, ExceptionState&);
};
-{{exported}}bool toV8{{cpp_class}}(const {{cpp_class}}&, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate*);
+{{exported}}bool toV8{{cpp_class}}(const {{cpp_class}}*, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate*);
template <class CallbackInfo>
-inline void V8SetReturnValue(const CallbackInfo& callbackInfo, {{cpp_class}}& impl) {
+inline void V8SetReturnValue(const CallbackInfo& callbackInfo, {{cpp_class}}* impl) {
V8SetReturnValue(callbackInfo, ToV8(impl, callbackInfo.Holder(), callbackInfo.GetIsolate()));
}
template <class CallbackInfo>
-inline void V8SetReturnValue(const CallbackInfo& callbackInfo, {{cpp_class}}& impl, v8::Local<v8::Object> creationContext) {
+inline void V8SetReturnValue(const CallbackInfo& callbackInfo, {{cpp_class}}* impl, v8::Local<v8::Object> creationContext) {
V8SetReturnValue(callbackInfo, ToV8(impl, creationContext, callbackInfo.GetIsolate()));
}
template <>
struct NativeValueTraits<{{cpp_class}}> : public NativeValueTraitsBase<{{cpp_class}}> {
- {{exported}}static {{cpp_class}} NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&);
+ {{exported}}static {{cpp_class}}* NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&);
};
template <>
@@ -41,6 +41,6 @@ struct V8TypeOf<{{cpp_class}}> {
} // namespace blink
-#endif // {{v8_original_class}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cc.tmpl b/chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cc.tmpl
new file mode 100644
index 00000000000..dcd1bee8fa4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cc.tmpl
@@ -0,0 +1,122 @@
+{% filter format_blink_cpp_source_code %}
+
+{% include 'copyright_block.txt' %}
+
+#include "{{this_include_header_path}}"
+
+#include <cstdint>
+
+{% for include_file in include_files %}
+#include "{{include_file}}"
+{% endfor %}
+
+namespace blink {
+
+// We use forward declaration instead of include for faster compile time here.
+{% for interface in interfaces %}
+{% if interface.has_constructor_callback %}
+namespace {{interface.internal_namespace}} {
+{{interface.component|upper}}_EXPORT void ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>&);
+} // namespace {{interface.internal_namespace}}
+
+{% endif %}
+{% endfor %}
+
+const intptr_t* {{class}}::GetTable() {
+ static const intptr_t kReferenceTable[] = {
+#if defined(USE_V8_CONTEXT_SNAPSHOT)
+ // Android is sensitive on its APK size, and this table improves it.
+ // So we drop the table entries until the V8 context snapshot feature
+ // is released on Android.
+ {% for interface in interfaces %}
+ {% set v8_class = interface.v8_class %}
+ {# Attributes #}
+ {%- for attribute in interface.attributes %}
+ {%- for world_suffix in attribute.world_suffixes %}
+ {% if not attribute.constructor_type %}
+ reinterpret_cast<intptr_t>({{v8_class}}::{{attribute.camel_case_name}}AttributeGetterCallback{{world_suffix}}),
+ {% else %}
+ reinterpret_cast<intptr_t>({{v8_class}}::{{attribute.camel_case_name}}ConstructorGetterCallback{{world_suffix}}),
+ {% endif %}
+ {% if attribute.has_setter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::{{attribute.camel_case_name}}AttributeSetterCallback{{world_suffix}}),
+ {% endif %}
+ {%- endfor %}{# world_suffix #}
+ {%- endfor %}{# attributes #}
+ {# Methods / Operations #}
+ {% for method in interface.methods %}
+ {%- for world_suffix in method.world_suffixes %}
+ {% if not method.overload_index or method.overloads %}
+ {% if (method.overloads and method.overloads.visible and
+ (not method.overloads.has_partial_overloads or not interface.is_partial)) or
+ (not method.overloads and method.visible) %}
+ reinterpret_cast<intptr_t>({{v8_class}}::{{method.camel_case_name}}MethodCallback{{world_suffix}}),
+ {% endif %}
+ {% endif %}
+ {% if method.is_cross_origin and method.visible and not method.overloads %}
+ reinterpret_cast<intptr_t>({{v8_class}}::{{method.camel_case_name}}OriginSafeMethodGetterCallback{{world_suffix}}),
+ {% endif%}
+ {% endfor %}
+ {% endfor %}{# method #}
+ {% if interface.has_origin_safe_method_setter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::{{interface.name}}OriginSafeMethodSetterCallback),
+ {% endif %}
+ {% if interface.has_cross_origin_named_getter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::CrossOriginNamedGetter),
+ {% endif %}
+ {% if interface.has_cross_origin_named_setter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::CrossOriginNamedSetter),
+ {% endif %}
+ {% if interface.has_cross_origin_named_enumerator %}
+ reinterpret_cast<intptr_t>({{v8_class}}::CrossOriginNamedEnumerator),
+ {% endif %}
+ {% if interface.has_cross_origin_indexed_getter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::CrossOriginIndexedGetter),
+ {% endif %}
+ {% if interface.has_security_check %}
+ reinterpret_cast<intptr_t>({{v8_class}}::SecurityCheck),
+ reinterpret_cast<intptr_t>(&{{v8_class}}::wrapper_type_info),
+ {% endif %}
+ {# Other properties #}
+ {% if interface.has_constructor_callback %}
+ reinterpret_cast<intptr_t>({{interface.internal_namespace}}::ConstructorCallback),
+ {% endif %}
+ {% if interface.named_property_getter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::NamedPropertyGetterCallback),
+ {% endif %}
+ {% if interface.named_property_setter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::NamedPropertySetterCallback),
+ {% endif %}
+ {% if interface.named_property_deleter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::NamedPropertyDeleterCallback),
+ {% endif %}
+ {% if interface.named_property_getter and interface.named_property_getter.is_enumerable %}
+ reinterpret_cast<intptr_t>({{v8_class}}::NamedPropertyQueryCallback),
+ reinterpret_cast<intptr_t>({{v8_class}}::NamedPropertyEnumeratorCallback),
+ {% endif %}
+ {% if interface.indexed_property_getter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::IndexedPropertyGetterCallback),
+ reinterpret_cast<intptr_t>({{v8_class}}::IndexedPropertyDefinerCallback),
+ reinterpret_cast<intptr_t>({{v8_class}}::IndexedPropertyDescriptorCallback),
+ {% endif %}
+ {% if interface.indexed_property_getter or interface.named_property_setter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::IndexedPropertySetterCallback),
+ {% endif %}
+ {% if interface.indexed_property_deleter %}
+ reinterpret_cast<intptr_t>({{v8_class}}::IndexedPropertyDeleterCallback),
+ {% endif %}
+ {% if interface.has_security_check_function %}
+ reinterpret_cast<intptr_t>({{v8_class}}::SecurityCheck),
+ {% endif %}
+ {% endfor %}{# interfaces #}
+ reinterpret_cast<intptr_t>(V8ObjectConstructor::IsValidConstructorMode),
+#endif // USE_V8_CONTEXT_SNAPSHOT
+ 0 // terminate with a null
+ };
+
+ return kReferenceTable;
+}
+
+} // namespace blink
+
+{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cpp.tmpl
deleted file mode 100644
index af3f6e74c56..00000000000
--- a/chromium/third_party/blink/renderer/bindings/templates/external_reference_table.cpp.tmpl
+++ /dev/null
@@ -1,117 +0,0 @@
-{% filter format_blink_cpp_source_code %}
-
-{% include 'copyright_block.txt' %}
-
-#include "{{this_include_header_path}}"
-
-#include <cstdint>
-
-{% for include_file in include_files %}
-#include "{{include_file}}"
-{% endfor %}
-
-namespace blink {
-
-const intptr_t* {{class}}::GetTable() {
- static const intptr_t reference_table[] = {
-#if defined(USE_V8_CONTEXT_SNAPSHOT)
- // Android is sensitive on its APK size, and this table improves it.
- // So we drop the table entries until the V8 context snapshot feature
- // is released on Android.
- {% for interface in interfaces %}
- {% if not interface.is_array_buffer_or_view %}
- {% set v8_class = interface.v8_name %}
- {# Attributes #}
- {%- for attribute in interface.attributes %}
- {%- for world_suffix in attribute.world_suffixes %}
- {% if not attribute.constructor_type %}
- reinterpret_cast<intptr_t>({{v8_class}}::{{attribute.name}}AttributeGetterCallback{{world_suffix}}),
- {% else %}
- reinterpret_cast<intptr_t>({{v8_class}}::{{attribute.name}}ConstructorGetterCallback{{world_suffix}}),
- {% endif %}
- {% if attribute.has_setter %}
- reinterpret_cast<intptr_t>({{v8_class}}::{{attribute.name}}AttributeSetterCallback{{world_suffix}}),
- {% endif %}
- {%- endfor %}{# world_suffix #}
- {%- endfor %}{# attributes #}
- {# Methods / Operations #}
- {% for method in interface.methods %}
- {%- for world_suffix in method.world_suffixes %}
- {% if not method.overload_index or method.overloads %}
- {% if (method.overloads and method.overloads.visible and
- (not method.overloads.has_partial_overloads or not interface.is_partial)) or
- (not method.overloads and method.visible) %}
- {# TODO(bashi): Remove this 'if' condition when crbug.com/630986 is fixed. #}
- {% if not interface.is_callback %}
- reinterpret_cast<intptr_t>({{v8_class}}::{{method.name}}MethodCallback{{world_suffix}}),
- {% endif %}
- {% endif %}
- {% endif %}{# overload(_index) #}
- {% if method.is_cross_origin and method.visible %}
- reinterpret_cast<intptr_t>({{v8_class}}::{{method.name}}OriginSafeMethodGetterCallback{{world_suffix}}),
- {% endif%}
- {% endfor %}
- {% endfor %}{# method #}
- {% if interface.has_origin_safe_method_setter %}
- reinterpret_cast<intptr_t>({{v8_class}}::{{interface.name}}OriginSafeMethodSetterCallback),
- {% endif %}
- {% if interface.has_cross_origin_named_getter %}
- reinterpret_cast<intptr_t>({{v8_class}}::crossOriginNamedGetter),
- {% endif %}
- {% if interface.has_cross_origin_named_setter %}
- reinterpret_cast<intptr_t>({{v8_class}}::crossOriginNamedSetter),
- {% endif %}
- {% if interface.has_cross_origin_named_enumerator %}
- reinterpret_cast<intptr_t>({{v8_class}}::crossOriginNamedEnumerator),
- {% endif %}
- {% if interface.has_cross_origin_indexed_getter %}
- reinterpret_cast<intptr_t>({{v8_class}}::crossOriginIndexedGetter),
- {% endif %}
- {% if interface.has_security_check %}
- reinterpret_cast<intptr_t>({{v8_class}}::securityCheck),
- reinterpret_cast<intptr_t>(&{{v8_class}}::wrapperTypeInfo),
- {% endif %}
- {# Other properties #}
- {% if interface.has_constructor_callback %}
- reinterpret_cast<intptr_t>({{v8_class}}::constructorCallback),
- {% endif %}
- {% if interface.named_property_getter %}
- reinterpret_cast<intptr_t>({{v8_class}}::namedPropertyGetterCallback),
- {% endif %}
- {%- if interface.named_property_setter %}
- reinterpret_cast<intptr_t>({{v8_class}}::namedPropertySetterCallback),
- {% endif %}
- {%- if interface.named_property_deleter %}
- reinterpret_cast<intptr_t>({{v8_class}}::namedPropertyDeleterCallback),
- {% endif %}
- {%- if interface.named_property_getter and interface.named_property_getter.is_enumerable %}
- reinterpret_cast<intptr_t>({{v8_class}}::namedPropertyQueryCallback),
- reinterpret_cast<intptr_t>({{v8_class}}::namedPropertyEnumeratorCallback),
- {% endif %}
- {%- if interface.indexed_property_getter %}
- reinterpret_cast<intptr_t>({{v8_class}}::indexedPropertyGetterCallback),
- reinterpret_cast<intptr_t>({{v8_class}}::indexedPropertyDefinerCallback),
- reinterpret_cast<intptr_t>({{v8_class}}::indexedPropertyDescriptorCallback),
- {% endif %}
- {%- if interface.indexed_property_getter or interface.named_property_setter %}
- reinterpret_cast<intptr_t>({{v8_class}}::indexedPropertySetterCallback),
- {% endif %}
- {%- if interface.indexed_property_deleter %}
- reinterpret_cast<intptr_t>({{v8_class}}::indexedPropertyDeleterCallback),
- {% endif %}
- {% if interface.has_security_check_function %}
- reinterpret_cast<intptr_t>({{v8_class}}::securityCheck),
- {%- endif %}
- {% endif %}{# not is_array_buffer_or_view #}
- {% endfor %}{# interfaces #}
- reinterpret_cast<intptr_t>(V8ObjectConstructor::IsValidConstructorMode),
-#endif // USE_V8_CONTEXT_SNAPSHOT
- 0 // terminate with a null
- };
-
- return reference_table;
-}
-
-} // namespace blink
-
-{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/interface.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/interface.cc.tmpl
index 1d7c57a480a..06dc821d117 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/interface.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/interface.cc.tmpl
@@ -1,14 +1,16 @@
-{% extends 'interface_base.cpp.tmpl' %}
+{% extends 'interface_base.cc.tmpl' %}
-{% from 'methods.cpp.tmpl' import runtime_timer_scope, runtime_timer_scope_disabled_by_default %}
+{% from 'methods.cc.tmpl' import runtime_timer_scope, runtime_timer_scope_disabled_by_default %}
{##############################################################################}
{% block indexed_property_getter %}
{% if indexed_property_getter and not indexed_property_getter.is_custom %}
{% set getter = indexed_property_getter %}
-static void indexedPropertyGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
+static void IndexedPropertyGetter(
+ uint32_t index,
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if getter.is_raises_exception %}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kIndexedGetterContext, "{{interface_name}}");
+ ExceptionState exception_state(info.GetIsolate(), ExceptionState::kIndexedGetterContext, "{{interface_name}}");
{% endif %}
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
@@ -23,11 +25,11 @@ static void indexedPropertyGetter(uint32_t index, const v8::PropertyCallbackInfo
{% set getter_name = getter.name or 'AnonymousIndexedGetter' %}
{% set getter_arguments = ['index'] %}
{% if getter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
- {% set getter_arguments = ['scriptState'] + getter_arguments %}
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
+ {% set getter_arguments = ['script_state'] + getter_arguments %}
{% endif %}
{% if getter.is_raises_exception %}
- {% set getter_arguments = getter_arguments + ['exceptionState'] %}
+ {% set getter_arguments = getter_arguments + ['exception_state'] %}
{% endif %}
{{getter.cpp_type}} result = impl->{{getter_name}}({{getter_arguments | join(', ')}});
{{getter.v8_set_return_value}};
@@ -41,24 +43,25 @@ static void indexedPropertyGetter(uint32_t index, const v8::PropertyCallbackInfo
{% block indexed_property_getter_callback %}
{% if indexed_property_getter or named_property_getter %}
{% set getter = indexed_property_getter or named_property_getter %}
-void {{v8_class_or_partial}}::indexedPropertyGetterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::IndexedPropertyGetterCallback(
+ uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.indexed_property_getter_counter) }}
{% if indexed_property_getter %}
{% if getter.is_custom %}
- {{v8_class}}::indexedPropertyGetterCustom(index, info);
+ {{v8_class}}::IndexedPropertyGetterCustom(index, info);
{% else %}
- {{cpp_class}}V8Internal::indexedPropertyGetter(index, info);
+ {{internal_namespace}}::IndexedPropertyGetter(index, info);
{% endif %}
{% else %}{# otherwise, named property #}
- const AtomicString& propertyName = AtomicString::Number(index);
+ const AtomicString& property_name = AtomicString::Number(index);
{% if getter.is_custom %}
- {{v8_class}}::namedPropertyGetterCustom(propertyName, info);
+ {{v8_class}}::NamedPropertyGetterCustom(property_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyGetter(propertyName, info);
+ {{internal_namespace}}::NamedPropertyGetter(property_name, info);
{% endif %}
{% endif %}{# indexed_property_getter #}
@@ -70,12 +73,18 @@ void {{v8_class_or_partial}}::indexedPropertyGetterCallback(uint32_t index, cons
{##############################################################################}
{% block indexed_property_setter %}
-{% from 'utilities.cpp.tmpl' import v8_value_to_local_cpp_value %}
+{% from 'utilities.cc.tmpl' import v8_value_to_local_cpp_value %}
{% if indexed_property_setter and not indexed_property_setter.is_custom %}
{% set setter = indexed_property_setter %}
-static void indexedPropertySetter(uint32_t index, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info) {
+static void IndexedPropertySetter(
+ uint32_t index,
+ v8::Local<v8::Value> v8_value,
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if setter.has_exception_state %}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kIndexedSetterContext, "{{interface_name}}");
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kIndexedSetterContext,
+ "{{interface_name}}");
{% endif %}
{% if setter.is_ce_reactions %}
CEReactionsScope ce_reactions_scope;
@@ -86,29 +95,29 @@ static void indexedPropertySetter(uint32_t index, v8::Local<v8::Value> v8Value,
{% if setter.has_type_checking_interface %}
{# Type checking for interface types (if interface not implemented, throw
TypeError), per http://www.w3.org/TR/WebIDL/#es-interface #}
- if (!propertyValue{% if setter.is_nullable %} && !IsUndefinedOrNull(v8Value){% endif %}) {
- exceptionState.ThrowTypeError("The provided value is not of type '{{setter.idl_type}}'.");
+ if (!property_value{% if setter.is_nullable %} && !IsUndefinedOrNull(v8_value){% endif %}) {
+ exception_state.ThrowTypeError("The provided value is not of type '{{setter.idl_type}}'.");
return;
}
{% endif %}
{% set setter_name = setter.name or 'AnonymousIndexedSetter' %}
- {% set setter_arguments = ['index', 'propertyValue'] %}
+ {% set setter_arguments = ['index', 'property_value'] %}
{% if setter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
- {% set setter_arguments = ['scriptState'] + setter_arguments %}
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
+ {% set setter_arguments = ['script_state'] + setter_arguments %}
{% endif %}
{% if setter.is_raises_exception %}
- {% set setter_arguments = setter_arguments + ['exceptionState'] %}
+ {% set setter_arguments = setter_arguments + ['exception_state'] %}
{% endif %}
bool result = impl->{{setter_name}}({{setter_arguments | join(', ')}});
{% if setter.is_raises_exception %}
- if (exceptionState.HadException())
+ if (exception_state.HadException())
return;
{% endif %}
if (!result)
return;
- V8SetReturnValue(info, v8Value);
+ V8SetReturnValue(info, v8_value);
}
{% endif %}
@@ -119,23 +128,26 @@ static void indexedPropertySetter(uint32_t index, v8::Local<v8::Value> v8Value,
{% block indexed_property_setter_callback %}
{% if indexed_property_getter or named_property_setter %}
{% set setter = indexed_property_setter or named_property_setter %}
-void {{v8_class_or_partial}}::indexedPropertySetterCallback(uint32_t index, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::IndexedPropertySetterCallback(
+ uint32_t index,
+ v8::Local<v8::Value> v8_value,
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if indexed_property_setter %}
{% if setter.is_custom %}
- {{v8_class}}::indexedPropertySetterCustom(index, v8Value, info);
+ {{v8_class}}::IndexedPropertySetterCustom(index, v8_value, info);
{% else %}
- {{cpp_class}}V8Internal::indexedPropertySetter(index, v8Value, info);
+ {{internal_namespace}}::IndexedPropertySetter(index, v8_value, info);
{% endif %}
{% elif named_property_setter %}
- const AtomicString& propertyName = AtomicString::Number(index);
+ const AtomicString& property_name = AtomicString::Number(index);
{% if setter.is_custom %}
- {{v8_class}}::namedPropertySetterCustom(propertyName, v8Value, info);
+ {{v8_class}}::NamedPropertySetterCustom(property_name, v8_value, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertySetter(propertyName, v8Value, info);
+ {{internal_namespace}}::NamedPropertySetter(property_name, v8_value, info);
{% endif %}
{% else %}{# neither of indexed_property_setter nor named_property_setter #}
@@ -144,13 +156,13 @@ void {{v8_class_or_partial}}::indexedPropertySetterCallback(uint32_t index, v8::
// setter.
V8SetReturnValue(info, v8::Null(info.GetIsolate()));
if (info.ShouldThrowOnError()) {
- ExceptionState exceptionState(info.GetIsolate(),
- ExceptionState::kIndexedSetterContext,
- "{{interface_name}}");
+ ExceptionState exception_state(info.GetIsolate(),
+ ExceptionState::kIndexedSetterContext,
+ "{{interface_name}}");
{% if setter.is_ce_reactions %}
CEReactionsScope ce_reactions_scope;
{% endif %}
- exceptionState.ThrowTypeError("Index property setter is not supported.");
+ exception_state.ThrowTypeError("Index property setter is not supported.");
}
{% endif %}{# indexed/named_property_setter #}
@@ -163,21 +175,22 @@ void {{v8_class_or_partial}}::indexedPropertySetterCallback(uint32_t index, v8::
{##############################################################################}
{% block indexed_property_descriptor %}
{% if indexed_property_getter %}
-static void indexedPropertyDescriptor(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
+static void IndexedPropertyDescriptor(
+ uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
// https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty
// Steps 1.1 to 1.2.4 are covered here: we rely on indexedPropertyGetter() to
// call the getter function and check that |index| is a valid property index,
// in which case it will have set info.GetReturnValue() to something other
// than undefined.
- {{v8_class_or_partial}}::indexedPropertyGetterCallback(index, info);
- v8::Local<v8::Value> getterValue = info.GetReturnValue().Get();
- if (!getterValue->IsUndefined()) {
+ {{v8_class_or_partial}}::IndexedPropertyGetterCallback(index, info);
+ v8::Local<v8::Value> getter_value = info.GetReturnValue().Get();
+ if (!getter_value->IsUndefined()) {
// 1.2.5. Let |desc| be a newly created Property Descriptor with no fields.
// 1.2.6. Set desc.[[Value]] to the result of converting value to an
// ECMAScript value.
// 1.2.7. If O implements an interface with an indexed property setter,
// then set desc.[[Writable]] to true, otherwise set it to false.
- v8::PropertyDescriptor desc(getterValue, {% if indexed_property_setter %}true{% else %}false{% endif %});
+ v8::PropertyDescriptor desc(getter_value, {% if indexed_property_setter %}true{% else %}false{% endif %});
// 1.2.8. Set desc.[[Enumerable]] and desc.[[Configurable]] to true.
desc.set_enumerable(true);
desc.set_configurable(true);
@@ -193,7 +206,8 @@ static void indexedPropertyDescriptor(uint32_t index, const v8::PropertyCallback
{##############################################################################}
{% block named_property_descriptor %}
{% if not indexed_property_getter and named_property_getter %}
-static void namedPropertyDescriptor(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
+static void NamedPropertyDescriptor(
+ uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
// This function is called when an IDL interface supports named properties
// but not indexed properties. When a numeric property is queried, V8 calls
// indexedPropertyDescriptorCallback(), which calls this function.
@@ -206,20 +220,20 @@ static void namedPropertyDescriptor(uint32_t index, const v8::PropertyCallbackIn
// expected by a descriptor callback.
// TODO(rakuco): remove this hack once we switch named property handlers to
// using descriptor and definer callbacks (bug 764633).
- const AtomicString& indexAsName = AtomicString::Number(index);
+ const AtomicString& index_as_name = AtomicString::Number(index);
{% if named_property_getter.is_custom_property_query %}
- {{v8_class}}::namedPropertyQueryCustom(indexAsName, info);
+ {{v8_class}}::NamedPropertyQueryCustom(index_as_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyQuery(indexAsName, info);
+ {{internal_namespace}}::NamedPropertyQuery(index_as_name, info);
{% endif %}
- v8::Local<v8::Value> getterValue = info.GetReturnValue().Get();
- if (!getterValue->IsUndefined()) {
- DCHECK(getterValue->IsInt32());
+ v8::Local<v8::Value> getter_value = info.GetReturnValue().Get();
+ if (!getter_value->IsUndefined()) {
+ DCHECK(getter_value->IsInt32());
const int32_t props =
- getterValue->ToInt32(info.GetIsolate()->GetCurrentContext())
+ getter_value->ToInt32(info.GetIsolate()->GetCurrentContext())
.ToLocalChecked()
->Value();
- v8::PropertyDescriptor desc(V8String(info.GetIsolate(), indexAsName),
+ v8::PropertyDescriptor desc(V8String(info.GetIsolate(), index_as_name),
!(props & v8::ReadOnly));
desc.set_enumerable(!(props & v8::DontEnum));
desc.set_configurable(!(props & v8::DontDelete));
@@ -231,10 +245,10 @@ static void namedPropertyDescriptor(uint32_t index, const v8::PropertyCallbackIn
// indexedPropertyGetterCallback, let it end up calling the named property
// getter and, if all goes well, we create a v8::PropertyDescriptor with the
// right values.
- {{v8_class_or_partial}}::indexedPropertyGetterCallback(index, info);
- v8::Local<v8::Value> getterValue = info.GetReturnValue().Get();
- if (!getterValue->IsUndefined()) {
- v8::PropertyDescriptor desc(getterValue, {% if named_property_setter %}true{% else %}false{% endif %});
+ {{v8_class_or_partial}}::IndexedPropertyGetterCallback(index, info);
+ v8::Local<v8::Value> getter_value = info.GetReturnValue().Get();
+ if (!getter_value->IsUndefined()) {
+ v8::PropertyDescriptor desc(getter_value, {% if named_property_setter %}true{% else %}false{% endif %});
desc.set_enumerable(false);
desc.set_configurable(true);
V8SetReturnValue(info, desc);
@@ -249,11 +263,12 @@ static void namedPropertyDescriptor(uint32_t index, const v8::PropertyCallbackIn
{##############################################################################}
{% block indexed_property_descriptor_callback %}
{% if indexed_property_getter or named_property_getter %}
-void {{v8_class_or_partial}}::indexedPropertyDescriptorCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::IndexedPropertyDescriptorCallback(
+ uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if indexed_property_getter %}
- {{cpp_class}}V8Internal::indexedPropertyDescriptor(index, info);
+ {{internal_namespace}}::IndexedPropertyDescriptor(index, info);
{% else %}{# The interface only supports named properties. #}
- {{cpp_class}}V8Internal::namedPropertyDescriptor(index, info);
+ {{internal_namespace}}::NamedPropertyDescriptor(index, info);
{% endif %}{# indexed_property_getter #}
}
@@ -265,9 +280,13 @@ void {{v8_class_or_partial}}::indexedPropertyDescriptorCallback(uint32_t index,
{% block indexed_property_deleter %}
{% if indexed_property_deleter and not indexed_property_deleter.is_custom %}
{% set deleter = indexed_property_deleter %}
-static void indexedPropertyDeleter(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
+static void IndexedPropertyDeleter(
+ uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
{% if deleter.is_raises_exception %}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kIndexedDeletionContext, "{{interface_name}}");
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kIndexedDeletionContext,
+ "{{interface_name}}");
{% endif %}
{% if deleter.is_ce_reactions %}
CEReactionsScope ce_reactions_scope;
@@ -278,15 +297,15 @@ static void indexedPropertyDeleter(uint32_t index, const v8::PropertyCallbackInf
{% set deleter_name = deleter.name or 'AnonymousIndexedDeleter' %}
{% set deleter_arguments = ['index'] %}
{% if deleter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
- {% set deleter_arguments = ['scriptState'] + deleter_arguments %}
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
+ {% set deleter_arguments = ['script_state'] + deleter_arguments %}
{% endif %}
{% if deleter.is_raises_exception %}
- {% set deleter_arguments = deleter_arguments + ['exceptionState'] %}
+ {% set deleter_arguments = deleter_arguments + ['exception_state'] %}
{% endif %}
DeleteResult result = impl->{{deleter_name}}({{deleter_arguments | join(', ')}});
{% if deleter.is_raises_exception %}
- if (exceptionState.HadException())
+ if (exception_state.HadException())
return;
{% endif %}
if (result == kDeleteUnknownProperty)
@@ -302,23 +321,24 @@ static void indexedPropertyDeleter(uint32_t index, const v8::PropertyCallbackInf
{% block indexed_property_deleter_callback %}
{% if indexed_property_deleter or named_property_deleter %}
{% set deleter = indexed_property_deleter or named_property_deleter %}
-void {{v8_class_or_partial}}::indexedPropertyDeleterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
+void {{v8_class_or_partial}}::IndexedPropertyDeleterCallback(
+ uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
{% if indexed_property_deleter %}
{% if deleter.is_custom %}
- {{v8_class}}::indexedPropertyDeleterCustom(index, info);
+ {{v8_class}}::IndexedPropertyDeleterCustom(index, info);
{% else %}
- {{cpp_class}}V8Internal::indexedPropertyDeleter(index, info);
+ {{internal_namespace}}::IndexedPropertyDeleter(index, info);
{% endif %}
{% else %}{# otherwise, named property #}
- const AtomicString& propertyName = AtomicString::Number(index);
+ const AtomicString& property_name = AtomicString::Number(index);
{% if deleter.is_custom %}
- {{v8_class}}::namedPropertyDeleterCustom(propertyName, info);
+ {{v8_class}}::NamedPropertyDeleterCustom(property_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyDeleter(propertyName, info);
+ {{internal_namespace}}::NamedPropertyDeleter(property_name, info);
{% endif %}
{% endif %}{# indexed_property_deleter #}
@@ -331,7 +351,7 @@ void {{v8_class_or_partial}}::indexedPropertyDeleterCallback(uint32_t index, con
{##############################################################################}
{% block indexed_property_definer_callback %}
{% if indexed_property_getter %}
-void {{v8_class_or_partial}}::indexedPropertyDefinerCallback(
+void {{v8_class_or_partial}}::IndexedPropertyDefinerCallback(
uint32_t index,
const v8::PropertyDescriptor& desc,
const v8::PropertyCallbackInfo<v8::Value>& info) {
@@ -343,10 +363,10 @@ void {{v8_class_or_partial}}::indexedPropertyDefinerCallback(
if (desc.has_get() || desc.has_set()) {
V8SetReturnValue(info, v8::Null(info.GetIsolate()));
if (info.ShouldThrowOnError()) {
- ExceptionState exceptionState(info.GetIsolate(),
- ExceptionState::kIndexedSetterContext,
- "{{interface_name}}");
- exceptionState.ThrowTypeError("Accessor properties are not allowed.");
+ ExceptionState exception_state(info.GetIsolate(),
+ ExceptionState::kIndexedSetterContext,
+ "{{interface_name}}");
+ exception_state.ThrowTypeError("Accessor properties are not allowed.");
}
return;
}
@@ -363,10 +383,10 @@ void {{v8_class_or_partial}}::indexedPropertyDefinerCallback(
// step 2.1. If P is an array index property name, return false.
V8SetReturnValue(info, v8::Null(info.GetIsolate()));
if (info.ShouldThrowOnError()) {
- ExceptionState exceptionState(info.GetIsolate(),
- ExceptionState::kIndexedSetterContext,
- "{{interface_name}}");
- exceptionState.ThrowTypeError("Index property setter is not supported.");
+ ExceptionState exception_state(info.GetIsolate(),
+ ExceptionState::kIndexedSetterContext,
+ "{{interface_name}}");
+ exception_state.ThrowTypeError("Index property setter is not supported.");
}
{% endif %}{# indexed_property_setter #}
}
@@ -379,13 +399,18 @@ void {{v8_class_or_partial}}::indexedPropertyDefinerCallback(
{% block named_property_getter %}
{% if named_property_getter and not named_property_getter.is_custom %}
{% set getter = named_property_getter %}
-static void namedPropertyGetter(const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) {
+static void NamedPropertyGetter(const AtomicString& name,
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if getter.is_raises_exception %}
- const CString& nameInUtf8 = name.Utf8();
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kGetterContext, "{{interface_name}}", nameInUtf8.data());
+ const CString& name_in_utf8 = name.Utf8();
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kGetterContext,
+ "{{interface_name}}",
+ name_in_utf8.data());
{% endif %}
{% if getter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
@@ -408,16 +433,17 @@ static void namedPropertyGetter(const AtomicString& name, const v8::PropertyCall
{% block named_property_getter_callback %}
{% if named_property_getter %}
{% set getter = named_property_getter %}
-void {{v8_class_or_partial}}::namedPropertyGetterCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::NamedPropertyGetterCallback(
+ v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.named_property_getter_counter) }}
if (!name->IsString())
return;
- const AtomicString& propertyName = ToCoreAtomicString(name.As<v8::String>());
+ const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
{% if getter.is_custom %}
- {{v8_class}}::namedPropertyGetterCustom(propertyName, info);
+ {{v8_class}}::NamedPropertyGetterCustom(property_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyGetter(propertyName, info);
+ {{internal_namespace}}::NamedPropertyGetter(property_name, info);
{% endif %}
}
@@ -427,19 +453,26 @@ void {{v8_class_or_partial}}::namedPropertyGetterCallback(v8::Local<v8::Name> na
{##############################################################################}
{% block named_property_setter %}
-{% from 'utilities.cpp.tmpl' import v8_value_to_local_cpp_value %}
+{% from 'utilities.cc.tmpl' import v8_value_to_local_cpp_value %}
{% if named_property_setter and not named_property_setter.is_custom %}
{% set setter = named_property_setter %}
-static void namedPropertySetter(const AtomicString& name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info) {
+static void NamedPropertySetter(
+ const AtomicString& name,
+ v8::Local<v8::Value> v8_value,
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if setter.has_exception_state %}
- const CString& nameInUtf8 = name.Utf8();
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kSetterContext, "{{interface_name}}", nameInUtf8.data());
+ const CString& name_in_utf8 = name.Utf8();
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kSetterContext,
+ "{{interface_name}}",
+ name_in_utf8.data());
{% endif %}
{% if setter.is_ce_reactions %}
CEReactionsScope ce_reactions_scope;
{% endif %}
{% if setter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
@@ -447,28 +480,28 @@ static void namedPropertySetter(const AtomicString& name, v8::Local<v8::Value> v
{% if setter.has_type_checking_interface %}
{# Type checking for interface types (if interface not implemented, throw
TypeError), per http://www.w3.org/TR/WebIDL/#es-interface #}
- if (!propertyValue{% if setter.is_nullable %} && !IsUndefinedOrNull(v8Value){% endif %}) {
- exceptionState.ThrowTypeError("The provided value is not of type '{{setter.idl_type}}'.");
+ if (!property_value{% if setter.is_nullable %} && !IsUndefinedOrNull(v8_value){% endif %}) {
+ exception_state.ThrowTypeError("The provided value is not of type '{{setter.idl_type}}'.");
return;
}
{% endif %}
{% set setter_name = setter.name or 'AnonymousNamedSetter' %}
- {% set setter_arguments = ['name', 'propertyValue'] %}
+ {% set setter_arguments = ['name', 'property_value'] %}
{% if setter.is_call_with_script_state %}
- {% set setter_arguments = ['scriptState'] + setter_arguments %}
+ {% set setter_arguments = ['script_state'] + setter_arguments %}
{% endif %}
{% if setter.is_raises_exception %}
- {% set setter_arguments = setter_arguments + ['exceptionState'] %}
+ {% set setter_arguments = setter_arguments + ['exception_state'] %}
{% endif %}
bool result = impl->{{setter_name}}({{setter_arguments | join(', ')}});
{% if setter.is_raises_exception %}
- if (exceptionState.HadException())
+ if (exception_state.HadException())
return;
{% endif %}
if (!result)
return;
- V8SetReturnValue(info, v8Value);
+ V8SetReturnValue(info, v8_value);
}
{% endif %}
@@ -479,16 +512,19 @@ static void namedPropertySetter(const AtomicString& name, v8::Local<v8::Value> v
{% block named_property_setter_callback %}
{% if named_property_setter %}
{% set setter = named_property_setter %}
-void {{v8_class_or_partial}}::namedPropertySetterCallback(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::NamedPropertySetterCallback(
+ v8::Local<v8::Name> name,
+ v8::Local<v8::Value> v8_value,
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.named_property_setter_counter) }}
if (!name->IsString())
return;
- const AtomicString& propertyName = ToCoreAtomicString(name.As<v8::String>());
+ const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
{% if setter.is_custom %}
- {{v8_class}}::namedPropertySetterCustom(propertyName, v8Value, info);
+ {{v8_class}}::NamedPropertySetterCustom(property_name, v8_value, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertySetter(propertyName, v8Value, info);
+ {{internal_namespace}}::NamedPropertySetter(property_name, v8_value, info);
{% endif %}
}
@@ -500,16 +536,21 @@ void {{v8_class_or_partial}}::namedPropertySetterCallback(v8::Local<v8::Name> na
{% block named_property_deleter %}
{% if named_property_deleter and not named_property_deleter.is_custom %}
{% set deleter = named_property_deleter %}
-static void namedPropertyDeleter(const AtomicString& name, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
+static void NamedPropertyDeleter(
+ const AtomicString& name, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
{% if deleter.is_raises_exception %}
- const CString& nameInUtf8 = name.Utf8();
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kDeletionContext, "{{interface_name}}", nameInUtf8.data());
+ const CString& name_in_utf8 = name.Utf8();
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kDeletionContext,
+ "{{interface_name}}",
+ name_in_utf8.data());
{% endif %}
{% if deleter.is_ce_reactions %}
CEReactionsScope ce_reactions_scope;
{% endif %}
{% if deleter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
@@ -517,14 +558,14 @@ static void namedPropertyDeleter(const AtomicString& name, const v8::PropertyCal
{% set deleter_name = deleter.name or 'AnonymousNamedDeleter' %}
{% set deleter_arguments = ['name'] %}
{% if deleter.is_call_with_script_state %}
- {% set deleter_arguments = ['scriptState'] + deleter_arguments %}
+ {% set deleter_arguments = ['script_state'] + deleter_arguments %}
{% endif %}
{% if deleter.is_raises_exception %}
- {% set deleter_arguments = deleter_arguments + ['exceptionState'] %}
+ {% set deleter_arguments = deleter_arguments + ['exception_state'] %}
{% endif %}
DeleteResult result = impl->{{deleter_name}}({{deleter_arguments | join(', ')}});
{% if deleter.is_raises_exception %}
- if (exceptionState.HadException())
+ if (exception_state.HadException())
return;
{% endif %}
if (result == kDeleteUnknownProperty)
@@ -540,15 +581,16 @@ static void namedPropertyDeleter(const AtomicString& name, const v8::PropertyCal
{% block named_property_deleter_callback %}
{% if named_property_deleter %}
{% set deleter = named_property_deleter %}
-void {{v8_class_or_partial}}::namedPropertyDeleterCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
+void {{v8_class_or_partial}}::NamedPropertyDeleterCallback(
+ v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Boolean>& info) {
if (!name->IsString())
return;
- const AtomicString& propertyName = ToCoreAtomicString(name.As<v8::String>());
+ const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
{% if deleter.is_custom %}
- {{v8_class}}::namedPropertyDeleterCustom(propertyName, info);
+ {{v8_class}}::NamedPropertyDeleterCustom(property_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyDeleter(propertyName, info);
+ {{internal_namespace}}::NamedPropertyDeleter(property_name, info);
{% endif %}
}
@@ -564,7 +606,8 @@ void {{v8_class_or_partial}}::namedPropertyDeleterCallback(v8::Local<v8::Name> n
{# If there is an enumerator, there MUST be a query method to properly
communicate property attributes. #}
{% if indexed_property_getter %}
-static void namedPropertyQuery(const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) {
+static void NamedPropertyQuery(
+ const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) {
{% else %}
{# If we do not have an indexed property getter, this function is called #}
{# from namedPropertyDescriptor(), whose v8::PropertyCallbackInfo has a #}
@@ -573,19 +616,24 @@ static void namedPropertyQuery(const AtomicString& name, const v8::PropertyCallb
{# TODO(rakuco): remove this hack once we switch named property handlers to #}
{# using descriptor and definer callbacks (bug 764633). #}
template <typename T>
-static void namedPropertyQuery(const AtomicString& name, const v8::PropertyCallbackInfo<T>& info) {
+static void NamedPropertyQuery(
+ const AtomicString& name, const v8::PropertyCallbackInfo<T>& info) {
{% endif %}
- const CString& nameInUtf8 = name.Utf8();
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kGetterContext, "{{interface_name}}", nameInUtf8.data());
+ const CString& name_in_utf8 = name.Utf8();
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kGetterContext,
+ "{{interface_name}}",
+ name_in_utf8.data());
{% if getter.is_call_with_script_state %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
- {% set getter_arguments = ['name', 'exceptionState'] %}
+ {% set getter_arguments = ['name', 'exception_state'] %}
{% if getter.is_call_with_script_state %}
- {% set getter_arguments = ['scriptState'] + getter_arguments %}
+ {% set getter_arguments = ['script_state'] + getter_arguments %}
{% endif %}
bool result = impl->NamedPropertyQuery({{getter_arguments | join(', ')}});
if (!result)
@@ -615,16 +663,17 @@ static void namedPropertyQuery(const AtomicString& name, const v8::PropertyCallb
{% block named_property_query_callback %}
{% if named_property_getter and named_property_getter.is_enumerable %}
{% set getter = named_property_getter %}
-void {{v8_class_or_partial}}::namedPropertyQueryCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Integer>& info) {
+void {{v8_class_or_partial}}::NamedPropertyQueryCallback(
+ v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Integer>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.named_property_query_counter) }}
if (!name->IsString())
return;
- const AtomicString& propertyName = ToCoreAtomicString(name.As<v8::String>());
+ const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
{% if getter.is_custom_property_query %}
- {{v8_class}}::namedPropertyQueryCustom(propertyName, info);
+ {{v8_class}}::NamedPropertyQueryCustom(property_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyQuery(propertyName, info);
+ {{internal_namespace}}::NamedPropertyQuery(property_name, info);
{% endif %}
}
@@ -636,14 +685,17 @@ void {{v8_class_or_partial}}::namedPropertyQueryCallback(v8::Local<v8::Name> nam
{% block named_property_enumerator %}
{% if named_property_getter and named_property_getter.is_enumerable and
not named_property_getter.is_custom_property_enumerator %}
-static void namedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kEnumerationContext, "{{interface_name}}");
+static void NamedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kEnumerationContext,
+ "{{interface_name}}");
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
Vector<String> names;
- impl->NamedPropertyEnumerator(names, exceptionState);
- if (exceptionState.HadException())
+ impl->NamedPropertyEnumerator(names, exception_state);
+ if (exception_state.HadException())
return;
V8SetReturnValue(info, ToV8(names, info.Holder(), info.GetIsolate()).As<v8::Array>());
}
@@ -656,11 +708,12 @@ static void namedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& i
{% block named_property_enumerator_callback %}
{% if named_property_getter and named_property_getter.is_enumerable %}
{% set getter = named_property_getter %}
-void {{v8_class_or_partial}}::namedPropertyEnumeratorCallback(const v8::PropertyCallbackInfo<v8::Array>& info) {
+void {{v8_class_or_partial}}::NamedPropertyEnumeratorCallback(
+ const v8::PropertyCallbackInfo<v8::Array>& info) {
{% if getter.is_custom_property_enumerator %}
- {{v8_class}}::namedPropertyEnumeratorCustom(info);
+ {{v8_class}}::NamedPropertyEnumeratorCustom(info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyEnumerator(info);
+ {{internal_namespace}}::NamedPropertyEnumerator(info);
{% endif %}
}
@@ -674,16 +727,25 @@ void {{v8_class_or_partial}}::namedPropertyEnumeratorCallback(const v8::Property
properly supports the incumbent realm. #}
{% block origin_safe_method_setter %}
{% if has_origin_safe_method_setter %}
-static void {{cpp_class}}OriginSafeMethodSetter(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) {
+static void {{cpp_class}}OriginSafeMethodSetter(
+ v8::Local<v8::Name> name,
+ v8::Local<v8::Value> v8_value,
+ const v8::PropertyCallbackInfo<void>& info) {
if (!name->IsString())
return;
- v8::Local<v8::Object> holder = {{v8_class}}::findInstanceInPrototypeChain(info.Holder(), info.GetIsolate());
+ v8::Local<v8::Object> holder =
+ {{v8_class}}::FindInstanceInPrototypeChain(info.Holder(), info.GetIsolate());
if (holder.IsEmpty())
return;
{{cpp_class}}* impl = {{v8_class}}::ToImpl(holder);
- v8::String::Utf8Value methodName(info.GetIsolate(), name);
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kSetterContext, "{{interface_name}}", *methodName);
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), impl, exceptionState)) {
+ v8::String::Utf8Value name_in_utf8(info.GetIsolate(), name);
+ ExceptionState exception_state(
+ info.GetIsolate(),
+ ExceptionState::kSetterContext,
+ "{{interface_name}}",
+ *name_in_utf8);
+ if (!BindingSecurity::ShouldAllowAccessTo(
+ CurrentDOMWindow(info.GetIsolate()), impl, exception_state)) {
return;
}
@@ -691,18 +753,21 @@ static void {{cpp_class}}OriginSafeMethodSetter(v8::Local<v8::Name> name, v8::Lo
{% raw %}
// |methodName| must be same with {{method.name}} in
// {{method.name}}OriginSafeMethodGetter{{world_suffix}} defined in
- // methods.cpp.tmpl
+ // methods.cc.tmpl
{% endraw %}
- V8PrivateProperty::GetSymbol(info.GetIsolate(), *methodName)
- .Set(v8::Local<v8::Object>::Cast(info.Holder()), v8Value);
+ V8PrivateProperty::GetSymbol(info.GetIsolate(), *name_in_utf8)
+ .Set(v8::Local<v8::Object>::Cast(info.Holder()), v8_value);
}
{% endif %}
{% endblock %}
{% block origin_safe_method_setter_callback %}
{% if has_origin_safe_method_setter %}
-void {{v8_class_or_partial}}::{{cpp_class}}OriginSafeMethodSetterCallback(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) {
- {{cpp_class}}V8Internal::{{cpp_class}}OriginSafeMethodSetter(name, v8Value, info);
+void {{v8_class_or_partial}}::{{cpp_class}}OriginSafeMethodSetterCallback(
+ v8::Local<v8::Name> name,
+ v8::Local<v8::Value> v8_value,
+ const v8::PropertyCallbackInfo<void>& info) {
+ {{internal_namespace}}::{{cpp_class}}OriginSafeMethodSetter(name, v8_value, info);
}
{% endif %}
{% endblock %}
@@ -710,7 +775,7 @@ void {{v8_class_or_partial}}::{{cpp_class}}OriginSafeMethodSetterCallback(v8::Lo
{##############################################################################}
{% block named_constructor %}
-{% from 'methods.cpp.tmpl' import generate_constructor with context %}
+{% from 'methods.cc.tmpl' import generate_constructor with context %}
{% if named_constructor %}
{% set active_scriptwrappable_inheritance =
'kInheritFromActiveScriptWrappable'
@@ -722,9 +787,9 @@ void {{v8_class_or_partial}}::{{cpp_class}}OriginSafeMethodSetterCallback(v8::Lo
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
-const WrapperTypeInfo {{v8_class}}Constructor::wrapperTypeInfo = {
+const WrapperTypeInfo {{v8_class}}Constructor::wrapper_type_info = {
gin::kEmbedderBlink,
- {{v8_class}}Constructor::domTemplate,
+ {{v8_class}}Constructor::DomTemplate,
{{install_conditional_features_func or 'nullptr'}},
"{{interface_name}}",
nullptr,
@@ -737,49 +802,59 @@ const WrapperTypeInfo {{v8_class}}Constructor::wrapperTypeInfo = {
#endif
{{generate_constructor(named_constructor)}}
-v8::Local<v8::FunctionTemplate> {{v8_class}}Constructor::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world) {
- static int domTemplateKey; // This address is used for a key to look up the dom template.
+v8::Local<v8::FunctionTemplate> {{v8_class}}Constructor::DomTemplate(
+ v8::Isolate* isolate, const DOMWrapperWorld& world) {
+ static int dom_template_key; // This address is used for a key to look up the dom template.
V8PerIsolateData* data = V8PerIsolateData::From(isolate);
- v8::Local<v8::FunctionTemplate> result = data->FindInterfaceTemplate(world, &domTemplateKey);
+ v8::Local<v8::FunctionTemplate> result =
+ data->FindInterfaceTemplate(world, &dom_template_key);
if (!result.IsEmpty())
return result;
result = v8::FunctionTemplate::New(isolate, {{v8_class}}ConstructorCallback);
- v8::Local<v8::ObjectTemplate> instanceTemplate = result->InstanceTemplate();
- instanceTemplate->SetInternalFieldCount({{v8_class}}::internalFieldCount);
+ v8::Local<v8::ObjectTemplate> instance_template = result->InstanceTemplate();
+ instance_template->SetInternalFieldCount({{v8_class}}::kInternalFieldCount);
result->SetClassName(V8AtomicString(isolate, "{{named_constructor.name}}"));
- result->Inherit({{v8_class}}::domTemplate(isolate, world));
- data->SetInterfaceTemplate(world, &domTemplateKey, result);
+ result->Inherit({{v8_class}}::DomTemplate(isolate, world));
+ data->SetInterfaceTemplate(world, &dom_template_key, result);
return result;
}
void {{v8_class}}Constructor::NamedConstructorAttributeGetter(
- v8::Local<v8::Name> propertyName,
+ v8::Local<v8::Name> property_name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Local<v8::Context> creationContext = info.Holder()->CreationContext();
- V8PerContextData* perContextData = V8PerContextData::From(creationContext);
- if (!perContextData) {
+ V8PerContextData* per_context_data = V8PerContextData::From(creationContext);
+ if (!per_context_data) {
// TODO(yukishiino): Return a valid named constructor even after the context is detached
return;
}
- v8::Local<v8::Function> namedConstructor = perContextData->ConstructorForType(&{{v8_class}}Constructor::wrapperTypeInfo);
+ v8::Local<v8::Function> named_constructor =
+ per_context_data->ConstructorForType(&{{v8_class}}Constructor::wrapper_type_info);
// Set the prototype of named constructors to the regular constructor.
- auto privateProperty = V8PrivateProperty::GetNamedConstructorInitialized(info.GetIsolate());
- v8::Local<v8::Context> currentContext = info.GetIsolate()->GetCurrentContext();
- v8::Local<v8::Value> privateValue;
-
- if (!privateProperty.GetOrUndefined(namedConstructor).ToLocal(&privateValue) || privateValue->IsUndefined()) {
- v8::Local<v8::Function> interface = perContextData->ConstructorForType(&{{v8_class}}::wrapperTypeInfo);
- v8::Local<v8::Value> interfacePrototype = interface->Get(currentContext, V8AtomicString(info.GetIsolate(), "prototype")).ToLocalChecked();
- bool result = namedConstructor->Set(currentContext, V8AtomicString(info.GetIsolate(), "prototype"), interfacePrototype).ToChecked();
+ auto private_property =
+ V8PrivateProperty::GetNamedConstructorInitialized(info.GetIsolate());
+ v8::Local<v8::Context> current_context = info.GetIsolate()->GetCurrentContext();
+ v8::Local<v8::Value> private_value;
+
+ if (!private_property.GetOrUndefined(named_constructor).ToLocal(&private_value) ||
+ private_value->IsUndefined()) {
+ v8::Local<v8::Function> interface =
+ per_context_data->ConstructorForType(&{{v8_class}}::wrapper_type_info);
+ v8::Local<v8::Value> interfacePrototype =
+ interface->Get(current_context, V8AtomicString(info.GetIsolate(), "prototype"))
+ .ToLocalChecked();
+ bool result = named_constructor->Set(
+ current_context, V8AtomicString(info.GetIsolate(), "prototype"),
+ interfacePrototype).ToChecked();
if (!result)
return;
- privateProperty.Set(namedConstructor, v8::True(info.GetIsolate()));
+ private_property.Set(named_constructor, v8::True(info.GetIsolate()));
}
- V8SetReturnValue(info, namedConstructor);
+ V8SetReturnValue(info, named_constructor);
}
{% endif %}
@@ -788,8 +863,8 @@ void {{v8_class}}Constructor::NamedConstructorAttributeGetter(
{##############################################################################}
{% block overloaded_constructor %}
{% if constructor_overloads %}
-static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) {
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kConstructionContext, "{{interface_name}}");
+static void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info) {
+ ExceptionState exception_state(info.GetIsolate(), ExceptionState::kConstructionContext, "{{interface_name}}");
{# This follows the overload resolution algorithm. #}
{# https://heycam.github.io/webidl/#dfn-overload-resolution-algorithm #}
{# 3. Initialize argcount to be min(maxarg, n). #}
@@ -801,12 +876,12 @@ static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) {
{# Then resolve by testing argument #}
{% for test, constructor in tests_constructors %}
if ({{test}}) {
- {{cpp_class}}V8Internal::constructor{{constructor.overload_index}}(info);
+ {{internal_namespace}}::Constructor{{constructor.overload_index}}(info);
return;
}
- {% if "exceptionState" in test %}
- if (exceptionState.HadException()) {
- exceptionState.RethrowV8Exception(exceptionState.GetException());
+ {% if "exception_state" in test %}
+ if (exception_state.HadException()) {
+ exception_state.RethrowV8Exception(exception_state.GetException());
return;
}
{% endif %}
@@ -818,16 +893,16 @@ static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) {
{# Report full list of valid arities if gaps and above minimum #}
{% if constructor_overloads.valid_arities %}
if (info.Length() >= {{constructor_overloads.length}}) {
- exceptionState.ThrowTypeError(ExceptionMessages::InvalidArity("{{constructor_overloads.valid_arities}}", info.Length()));
+ exception_state.ThrowTypeError(ExceptionMessages::InvalidArity("{{constructor_overloads.valid_arities}}", info.Length()));
return;
}
{% endif %}
{# Otherwise just report "not enough arguments" #}
- exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments({{constructor_overloads.length}}, info.Length()));
+ exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments({{constructor_overloads.length}}, info.Length()));
return;
}
{# No match, throw error #}
- exceptionState.ThrowTypeError("No matching constructor signature.");
+ exception_state.ThrowTypeError("No matching constructor signature.");
}
{% endif %}
@@ -837,13 +912,15 @@ static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) {
{##############################################################################}
{% block constructor_callback %}
{% if constructors or has_custom_constructor or has_html_constructor %}
-void {{v8_class}}::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
+{{exported}}void ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.constructor_counter) }}
{% if measure_as %}
UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::k{{measure_as('Constructor')}});
{% endif %}
if (!info.IsConstructCall()) {
- V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::ConstructorNotCallableAsFunction("{{interface_name}}"));
+ V8ThrowException::ThrowTypeError(
+ info.GetIsolate(),
+ ExceptionMessages::ConstructorNotCallableAsFunction("{{interface_name}}"));
return;
}
@@ -853,11 +930,12 @@ void {{v8_class}}::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>
}
{% if has_custom_constructor %}
- {{v8_class}}::constructorCustom(info);
+ {{v8_class}}::ConstructorCustom(info);
{% elif has_html_constructor %}
- V8HTMLConstructor::HtmlConstructor(info, {{v8_class}}::wrapperTypeInfo, HTMLElementType::k{{interface_name}});
+ V8HTMLConstructor::HtmlConstructor(
+ info, {{v8_class}}::wrapper_type_info, HTMLElementType::k{{interface_name}});
{% else %}
- {{cpp_class}}V8Internal::constructor(info);
+ {{internal_namespace}}::Constructor(info);
{% endif %}
}
@@ -867,13 +945,13 @@ void {{v8_class}}::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>
{##############################################################################}
{% macro install_origin_safe_method(method, instance_template, prototype_template) %}
-{% from 'utilities.cpp.tmpl' import property_location %}
+{% from 'utilities.cc.tmpl' import property_location %}
{# TODO(dcheng): Currently, bindings must create a function object for each
realm as a hack to support the incumbent realm. Clean this up when Blink
properly supports the incumbent realm. #}
{% set getter_callback =
'%s::%sOriginSafeMethodGetterCallback' %
- (v8_class_or_partial, method.name) %}
+ (v8_class_or_partial, method.camel_case_name) %}
{% set setter_callback =
'%s::%sOriginSafeMethodSetterCallback' % (v8_class_or_partial, cpp_class)
if not method.is_unforgeable else 'nullptr' %}
@@ -892,7 +970,7 @@ static const V8DOMConfiguration::AttributeConfiguration {{method.name}}OriginSaf
{"{{method.name}}", {{getter_callback}}, {{setter_callback}}, {{property_attribute}}, {{property_location(method)}}, {{holder_check}}, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds}
{% endif %}
};
-for (const auto& attributeConfig : {{method.name}}OriginSafeAttributeConfiguration)
+ for (const auto& attributeConfig : {{method.name}}OriginSafeAttributeConfiguration)
V8DOMConfiguration::InstallAttribute(isolate, world, {{instance_template}}, {{prototype_template}}, attributeConfig);
{%- endmacro %}
@@ -900,21 +978,21 @@ for (const auto& attributeConfig : {{method.name}}OriginSafeAttributeConfigurati
{##############################################################################}
{% macro install_indexed_property_handler(target) %}
{% set indexed_property_getter_callback =
- '%s::indexedPropertyGetterCallback' % v8_class_or_partial %}
+ '%s::IndexedPropertyGetterCallback' % v8_class_or_partial %}
{% set indexed_property_setter_callback =
- '%s::indexedPropertySetterCallback' % v8_class_or_partial
+ '%s::IndexedPropertySetterCallback' % v8_class_or_partial
if indexed_property_getter or named_property_setter else 'nullptr' %}
{% set indexed_property_descriptor_callback =
- '%s::indexedPropertyDescriptorCallback' % v8_class_or_partial
+ '%s::IndexedPropertyDescriptorCallback' % v8_class_or_partial
if indexed_property_getter or named_property_getter else 'nullptr' %}
{% set indexed_property_deleter_callback =
- '%s::indexedPropertyDeleterCallback' % v8_class_or_partial
+ '%s::IndexedPropertyDeleterCallback' % v8_class_or_partial
if indexed_property_deleter or named_property_deleter else 'nullptr' %}
{% set indexed_property_enumerator_callback =
'IndexedPropertyEnumerator<%s>' % cpp_class
if indexed_property_getter.is_enumerable else 'nullptr' %}
{% set indexed_property_definer_callback =
- '%s::indexedPropertyDefinerCallback' % v8_class_or_partial
+ '%s::IndexedPropertyDefinerCallback' % v8_class_or_partial
if indexed_property_getter else 'nullptr' %}
{% set property_handler_flags =
'v8::PropertyHandlerFlags::kHasNoSideEffect'
@@ -935,18 +1013,18 @@ v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(
{##############################################################################}
{% macro install_named_property_handler(target) %}
{% set named_property_getter_callback =
- '%s::namedPropertyGetterCallback' % v8_class_or_partial %}
+ '%s::NamedPropertyGetterCallback' % v8_class_or_partial %}
{% set named_property_setter_callback =
- '%s::namedPropertySetterCallback' % v8_class_or_partial
+ '%s::NamedPropertySetterCallback' % v8_class_or_partial
if named_property_setter else 'nullptr' %}
{% set named_property_query_callback =
- '%s::namedPropertyQueryCallback' % v8_class_or_partial
+ '%s::NamedPropertyQueryCallback' % v8_class_or_partial
if named_property_getter.is_enumerable else 'nullptr' %}
{% set named_property_deleter_callback =
- '%s::namedPropertyDeleterCallback' % v8_class_or_partial
+ '%s::NamedPropertyDeleterCallback' % v8_class_or_partial
if named_property_deleter else 'nullptr' %}
{% set named_property_enumerator_callback =
- '%s::namedPropertyEnumeratorCallback' % v8_class_or_partial
+ '%s::NamedPropertyEnumeratorCallback' % v8_class_or_partial
if named_property_getter.is_enumerable else 'nullptr' %}
{% set property_handler_flags_list =
['int(v8::PropertyHandlerFlags::kOnlyInterceptStrings)'] %}
@@ -969,9 +1047,12 @@ v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig({{named_propert
{##############################################################################}
{% block get_dom_template %}
{% if not is_array_buffer_or_view %}
-v8::Local<v8::FunctionTemplate> {{v8_class}}::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world) {
- {% set installTemplateFunction = '%s::install%sTemplateFunction' % (v8_class, v8_class) if has_partial_interface else 'install%sTemplate' % v8_class %}
- return V8DOMConfiguration::DomClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), {{installTemplateFunction}});
+v8::Local<v8::FunctionTemplate> {{v8_class}}::DomTemplate(
+ v8::Isolate* isolate, const DOMWrapperWorld& world) {
+ {% set install_template_function = '%s::install_%s_template_function_' % (v8_class, snake_case_v8_class) if has_partial_interface else 'Install%sTemplate' % v8_class %}
+ return V8DOMConfiguration::DomClassTemplate(
+ isolate, world, const_cast<WrapperTypeInfo*>(&wrapper_type_info),
+ {{install_template_function}});
}
{% endif %}
@@ -981,21 +1062,30 @@ v8::Local<v8::FunctionTemplate> {{v8_class}}::domTemplate(v8::Isolate* isolate,
{##############################################################################}
{% block get_dom_template_for_named_properties_object %}
{% if has_named_properties_object %}
-v8::Local<v8::FunctionTemplate> {{v8_class}}::domTemplateForNamedPropertiesObject(v8::Isolate* isolate, const DOMWrapperWorld& world) {
- v8::Local<v8::FunctionTemplate> parentTemplate = V8{{parent_interface}}::domTemplate(isolate, world);
-
- v8::Local<v8::FunctionTemplate> namedPropertiesObjectFunctionTemplate = v8::FunctionTemplate::New(isolate, V8ObjectConstructor::IsValidConstructorMode);
- namedPropertiesObjectFunctionTemplate->SetClassName(V8AtomicString(isolate, "{{interface_name}}Properties"));
- namedPropertiesObjectFunctionTemplate->Inherit(parentTemplate);
-
- v8::Local<v8::ObjectTemplate> namedPropertiesObjectTemplate = namedPropertiesObjectFunctionTemplate->PrototypeTemplate();
- namedPropertiesObjectTemplate->SetInternalFieldCount({{v8_class}}::internalFieldCount);
+v8::Local<v8::FunctionTemplate>
+{{v8_class}}::DomTemplateForNamedPropertiesObject(
+ v8::Isolate* isolate, const DOMWrapperWorld& world) {
+ v8::Local<v8::FunctionTemplate> parentTemplate =
+ V8{{parent_interface}}::DomTemplate(isolate, world);
+
+ v8::Local<v8::FunctionTemplate> named_properties_function_template =
+ v8::FunctionTemplate::New(isolate,
+ V8ObjectConstructor::IsValidConstructorMode);
+ named_properties_function_template->SetClassName(
+ V8AtomicString(isolate, "{{interface_name}}Properties"));
+ named_properties_function_template->Inherit(parentTemplate);
+
+ v8::Local<v8::ObjectTemplate> named_properties_object_template =
+ named_properties_function_template->PrototypeTemplate();
+ named_properties_object_template->SetInternalFieldCount(
+ {{v8_class}}::kInternalFieldCount);
// Named Properties object has SetPrototype method of Immutable Prototype Exotic Objects
- namedPropertiesObjectTemplate->SetImmutableProto();
- V8DOMConfiguration::SetClassString(isolate, namedPropertiesObjectTemplate, "{{interface_name}}Properties");
- {{install_named_property_handler('namedPropertiesObjectTemplate') | trim | indent(2)}}
+ named_properties_object_template->SetImmutableProto();
+ V8DOMConfiguration::SetClassString(
+ isolate, named_properties_object_template, "{{interface_name}}Properties");
+ {{install_named_property_handler('named_properties_object_template') | trim | indent(2)}}
- return namedPropertiesObjectFunctionTemplate;
+ return named_properties_function_template;
}
{% endif %}
@@ -1006,12 +1096,14 @@ v8::Local<v8::FunctionTemplate> {{v8_class}}::domTemplateForNamedPropertiesObjec
{% block has_instance %}
{% if not is_array_buffer_or_view %}
-bool {{v8_class}}::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) {
- return V8PerIsolateData::From(isolate)->HasInstance(&wrapperTypeInfo, v8Value);
+bool {{v8_class}}::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
+ return V8PerIsolateData::From(isolate)->HasInstance(&wrapper_type_info, v8_value);
}
-v8::Local<v8::Object> {{v8_class}}::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) {
- return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
+v8::Local<v8::Object> {{v8_class}}::FindInstanceInPrototypeChain(
+ v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
+ return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(
+ &wrapper_type_info, v8_value);
}
{% endif %}
@@ -1025,19 +1117,19 @@ v8::Local<v8::Object> {{v8_class}}::findInstanceInPrototypeChain(v8::Local<v8::V
DCHECK(object->Is{{interface_name}}());
v8::Local<v8::{{interface_name}}> v8buffer = object.As<v8::{{interface_name}}>();
if (v8buffer->IsExternal()) {
- const WrapperTypeInfo* wrapperTypeInfo = ToWrapperTypeInfo(object);
- CHECK(wrapperTypeInfo);
- CHECK_EQ(wrapperTypeInfo->gin_embedder, gin::kEmbedderBlink);
+ const WrapperTypeInfo* wrapper_type = ToWrapperTypeInfo(object);
+ CHECK(wrapper_type);
+ CHECK_EQ(wrapper_type->gin_embedder, gin::kEmbedderBlink);
return ToScriptWrappable(object)->ToImpl<{{cpp_class}}>();
}
// Transfer the ownership of the allocated memory to an {{interface_name}} without
// copying.
- v8::{{interface_name}}::Contents v8Contents = v8buffer->Externalize();
- WTF::ArrayBufferContents::DataHandle data(v8Contents.Data(),
- v8Contents.ByteLength(),
- v8Contents.Deleter(),
- v8Contents.DeleterData());
+ v8::{{interface_name}}::Contents v8_contents = v8buffer->Externalize();
+ WTF::ArrayBufferContents::DataHandle data(v8_contents.Data(),
+ v8_contents.ByteLength(),
+ v8_contents.Deleter(),
+ v8_contents.DeleterData());
WTF::ArrayBufferContents contents(std::move(data), WTF::ArrayBufferContents::k{% if interface_name == 'ArrayBuffer' %}Not{% endif %}Shared);
{{cpp_class}}* buffer = {{cpp_class}}::Create(contents);
v8::Local<v8::Object> associatedWrapper = buffer->AssociateWithWrapper(v8::Isolate::GetCurrent(), buffer->GetWrapperTypeInfo(), object);
@@ -1049,9 +1141,9 @@ v8::Local<v8::Object> {{v8_class}}::findInstanceInPrototypeChain(v8::Local<v8::V
{% elif interface_name == 'ArrayBufferView' %}
{{cpp_class}}* V8ArrayBufferView::ToImpl(v8::Local<v8::Object> object) {
DCHECK(object->IsArrayBufferView());
- ScriptWrappable* scriptWrappable = ToScriptWrappable(object);
- if (scriptWrappable)
- return scriptWrappable->ToImpl<{{cpp_class}}>();
+ ScriptWrappable* script_wrappable = ToScriptWrappable(object);
+ if (script_wrappable)
+ return script_wrappable->ToImpl<{{cpp_class}}>();
if (object->IsInt8Array())
return V8Int8Array::ToImpl(object);
@@ -1079,30 +1171,38 @@ v8::Local<v8::Object> {{v8_class}}::findInstanceInPrototypeChain(v8::Local<v8::V
return V8DataView::ToImpl(object);
NOTREACHED();
- return 0;
+ return nullptr;
}
{% elif is_array_buffer_or_view %}
{{cpp_class}}* {{v8_class}}::ToImpl(v8::Local<v8::Object> object) {
DCHECK(object->Is{{interface_name}}());
- ScriptWrappable* scriptWrappable = ToScriptWrappable(object);
- if (scriptWrappable)
- return scriptWrappable->ToImpl<{{cpp_class}}>();
-
- v8::Local<v8::{{interface_name}}> v8View = object.As<v8::{{interface_name}}>();
- v8::Local<v8::Object> arrayBuffer = v8View->Buffer();
- {{cpp_class}}* typedArray = nullptr;
- if (arrayBuffer->IsArrayBuffer()) {
- typedArray = {{cpp_class}}::Create(V8ArrayBuffer::ToImpl(arrayBuffer), v8View->ByteOffset(), v8View->{% if interface_name == 'DataView' %}Byte{% endif %}Length());
- } else if (arrayBuffer->IsSharedArrayBuffer()) {
- typedArray = {{cpp_class}}::Create(V8SharedArrayBuffer::ToImpl(arrayBuffer), v8View->ByteOffset(), v8View->{% if interface_name == 'DataView' %}Byte{% endif %}Length());
+ ScriptWrappable* script_wrappable = ToScriptWrappable(object);
+ if (script_wrappable)
+ return script_wrappable->ToImpl<{{cpp_class}}>();
+
+ v8::Local<v8::{{interface_name}}> v8_view = object.As<v8::{{interface_name}}>();
+ v8::Local<v8::Object> array_buffer = v8_view->Buffer();
+ {{cpp_class}}* typed_array = nullptr;
+ if (array_buffer->IsArrayBuffer()) {
+ typed_array = {{cpp_class}}::Create(
+ V8ArrayBuffer::ToImpl(array_buffer),
+ v8_view->ByteOffset(),
+ v8_view->{% if interface_name == 'DataView' %}Byte{% endif %}Length());
+ } else if (array_buffer->IsSharedArrayBuffer()) {
+ typed_array = {{cpp_class}}::Create(
+ V8SharedArrayBuffer::ToImpl(array_buffer),
+ v8_view->ByteOffset(),
+ v8_view->{% if interface_name == 'DataView' %}Byte{% endif %}Length());
} else {
NOTREACHED();
}
- v8::Local<v8::Object> associatedWrapper = typedArray->AssociateWithWrapper(v8::Isolate::GetCurrent(), typedArray->GetWrapperTypeInfo(), object);
- DCHECK(associatedWrapper == object);
+ v8::Local<v8::Object> associated_wrapper =
+ typed_array->AssociateWithWrapper(
+ v8::Isolate::GetCurrent(), typed_array->GetWrapperTypeInfo(), object);
+ DCHECK(associated_wrapper == object);
- return typedArray->ToImpl<{{cpp_class}}>();
+ return typed_array->ToImpl<{{cpp_class}}>();
}
{% endif %}
@@ -1111,11 +1211,12 @@ v8::Local<v8::Object> {{v8_class}}::findInstanceInPrototypeChain(v8::Local<v8::V
{##############################################################################}
{% block to_impl_with_type_check %}
-{{cpp_class}}* {{v8_class}}::ToImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) {
+{{cpp_class}}* {{v8_class}}::ToImplWithTypeCheck(
+ v8::Isolate* isolate, v8::Local<v8::Value> value) {
{% if is_array_buffer_or_view %}
return value->Is{{interface_name}}() ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
{% else %}
- return hasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
+ return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
{% endif %}
}
@@ -1124,13 +1225,14 @@ v8::Local<v8::Object> {{v8_class}}::findInstanceInPrototypeChain(v8::Local<v8::V
{##############################################################################}
{% block native_value_traits %}
-{{cpp_class}}* NativeValueTraits<{{cpp_class}}>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
- {{cpp_class}}* nativeValue = {{v8_class}}::ToImplWithTypeCheck(isolate, value);
- if (!nativeValue) {
- exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue(
+{{cpp_class}}* NativeValueTraits<{{cpp_class}}>::NativeValue(
+ v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) {
+ {{cpp_class}}* native_value = {{v8_class}}::ToImplWithTypeCheck(isolate, value);
+ if (!native_value) {
+ exception_state.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue(
"{{interface_name}}"));
}
- return nativeValue;
+ return native_value;
}
{% endblock %}
@@ -1150,15 +1252,16 @@ InstallRuntimeEnabledFeaturesOnTemplateFunction
&{{v8_class}}::InstallRuntimeEnabledFeaturesOnTemplate;
{% endif %}
-InstallTemplateFunction {{v8_class}}::install{{v8_class}}TemplateFunction =
- &{{v8_class}}::install{{v8_class}}Template;
+InstallTemplateFunction
+{{v8_class}}::install_{{snake_case_v8_class}}_template_function_ =
+ &{{v8_class}}::Install{{v8_class}}Template;
void {{v8_class}}::UpdateWrapperTypeInfo(
InstallTemplateFunction install_template_function,
InstallRuntimeEnabledFeaturesFunction install_runtime_enabled_features_function,
InstallRuntimeEnabledFeaturesOnTemplateFunction install_runtime_enabled_features_on_template_function,
InstallConditionalFeaturesFunction install_conditional_features_function) {
- {{v8_class}}::install{{v8_class}}TemplateFunction =
+ {{v8_class}}::install_{{snake_case_v8_class}}_template_function_ =
install_template_function;
{% if needs_runtime_enabled_installer %}
@@ -1174,14 +1277,14 @@ void {{v8_class}}::UpdateWrapperTypeInfo(
{% endif %}
if (install_conditional_features_function) {
- {{v8_class}}::wrapperTypeInfo.install_conditional_features_function =
+ {{v8_class}}::wrapper_type_info.install_conditional_features_function =
install_conditional_features_function;
}
}
{% for method in methods if method.overloads and method.overloads.has_partial_overloads %}
-void {{v8_class}}::register{{method.name | blink_capitalize}}MethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&)) {
- {{cpp_class}}V8Internal::{{method.name}}MethodForPartialInterface = method;
+void {{v8_class}}::Register{{method.camel_case_name}}MethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&)) {
+ {{internal_namespace}}::{{method.name}}MethodForPartialInterface = method;
}
{% endfor %}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/interface.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/interface.h.tmpl
index ddac35416b1..240114540c7 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/interface.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/interface.h.tmpl
@@ -1,8 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-#ifndef {{v8_class}}_h
-#define {{v8_class}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -17,9 +17,9 @@ class ScriptState;
class {{v8_class}}Constructor {
STATIC_ONLY({{v8_class}}Constructor);
public:
- static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*, const DOMWrapperWorld&);
- static void NamedConstructorAttributeGetter(v8::Local<v8::Name> propertyName, const v8::PropertyCallbackInfo<v8::Value>& info);
- static const WrapperTypeInfo wrapperTypeInfo;
+ static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&);
+ static void NamedConstructorAttributeGetter(v8::Local<v8::Name> property_name, const v8::PropertyCallbackInfo<v8::Value>& info);
+ static const WrapperTypeInfo wrapper_type_info;
};
{% endif %}
@@ -29,11 +29,11 @@ class {{v8_class}} {
{% if is_array_buffer_or_view %}
{{exported}}static {{cpp_class}}* ToImpl(v8::Local<v8::Object> object);
{% else %}
- {{exported}}static bool hasInstance(v8::Local<v8::Value>, v8::Isolate*);
- static v8::Local<v8::Object> findInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
- {{exported}}static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*, const DOMWrapperWorld&);
+ {{exported}}static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*);
+ static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
+ {{exported}}static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&);
{% if has_named_properties_object %}
- {{exported}}static v8::Local<v8::FunctionTemplate> domTemplateForNamedPropertiesObject(v8::Isolate*, const DOMWrapperWorld&);
+ {{exported}}static v8::Local<v8::FunctionTemplate> DomTemplateForNamedPropertiesObject(v8::Isolate*, const DOMWrapperWorld&);
{% endif %}
static {{cpp_class}}* ToImpl(v8::Local<v8::Object> object) {
return ToScriptWrappable(object)->ToImpl<{{cpp_class}}>();
@@ -41,68 +41,68 @@ class {{v8_class}} {
{% endif %}
{{exported}}static {{cpp_class}}* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>);
{% if has_partial_interface %}
- {{exported}}static WrapperTypeInfo wrapperTypeInfo;
+ {{exported}}static WrapperTypeInfo wrapper_type_info;
{% else %}
- {{exported}}static const WrapperTypeInfo wrapperTypeInfo;
+ {{exported}}static const WrapperTypeInfo wrapper_type_info;
{% endif %}
{% for method in methods %}
{% if method.is_custom %}
- static void {{method.name}}MethodCustom(const v8::FunctionCallbackInfo<v8::Value>&);
+ static void {{method.camel_case_name}}MethodCustom(const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{% if method.is_custom_call_prologue %}
- static void {{method.name}}MethodPrologueCustom(const v8::FunctionCallbackInfo<v8::Value>&, {{cpp_class}}*);
+ static void {{method.camel_case_name}}MethodPrologueCustom(const v8::FunctionCallbackInfo<v8::Value>&, {{cpp_class}}*);
{% endif %}
{% if method.is_custom_call_epilogue %}
- static void {{method.name}}MethodEpilogueCustom(const v8::FunctionCallbackInfo<v8::Value>&, {{cpp_class}}*);
+ static void {{method.camel_case_name}}MethodEpilogueCustom(const v8::FunctionCallbackInfo<v8::Value>&, {{cpp_class}}*);
{% endif %}
{% endfor %}
{% if has_custom_constructor %}
- static void constructorCustom(const v8::FunctionCallbackInfo<v8::Value>&);
+ static void ConstructorCustom(const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{% for attribute in attributes %}
{% if attribute.has_custom_getter %}{# FIXME: and not attribute.implemented_by #}
{% if attribute.is_data_type_property %}
- static void {{attribute.name}}AttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>&);
+ static void {{attribute.camel_case_name}}AttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>&);
{% else %}
- static void {{attribute.name}}AttributeGetterCustom(const v8::FunctionCallbackInfo<v8::Value>&);
+ static void {{attribute.camel_case_name}}AttributeGetterCustom(const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{% endif %}
{% if attribute.has_custom_setter %}{# FIXME: and not attribute.implemented_by #}
{% if attribute.is_data_type_property %}
- static void {{attribute.name}}AttributeSetterCustom(v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&);
+ static void {{attribute.camel_case_name}}AttributeSetterCustom(v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&);
{% else %}
- static void {{attribute.name}}AttributeSetterCustom(v8::Local<v8::Value>, const v8::FunctionCallbackInfo<v8::Value>&);
+ static void {{attribute.camel_case_name}}AttributeSetterCustom(v8::Local<v8::Value>, const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{% endif %}
{% endfor %}
{# Custom special operations #}
{% if indexed_property_getter and indexed_property_getter.is_custom %}
- static void indexedPropertyGetterCustom(uint32_t, const v8::PropertyCallbackInfo<v8::Value>&);
+ static void IndexedPropertyGetterCustom(uint32_t, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if indexed_property_setter and indexed_property_setter.is_custom %}
- static void indexedPropertySetterCustom(uint32_t, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
+ static void IndexedPropertySetterCustom(uint32_t, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if indexed_property_deleter and indexed_property_deleter.is_custom %}
- static void indexedPropertyDeleterCustom(uint32_t, const v8::PropertyCallbackInfo<v8::Boolean>&);
+ static void IndexedPropertyDeleterCustom(uint32_t, const v8::PropertyCallbackInfo<v8::Boolean>&);
{% endif %}
{% if named_property_getter and named_property_getter.is_custom %}
- static void namedPropertyGetterCustom(const AtomicString&, const v8::PropertyCallbackInfo<v8::Value>&);
+ static void NamedPropertyGetterCustom(const AtomicString&, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if named_property_setter and named_property_setter.is_custom %}
- static void namedPropertySetterCustom(const AtomicString&, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
+ static void NamedPropertySetterCustom(const AtomicString&, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if named_property_getter and named_property_getter.is_custom_property_query %}
- static void namedPropertyQueryCustom(const AtomicString&, const v8::PropertyCallbackInfo<v8::Integer>&);
+ static void NamedPropertyQueryCustom(const AtomicString&, const v8::PropertyCallbackInfo<v8::Integer>&);
{% endif %}
{% if named_property_deleter and named_property_deleter.is_custom %}
- static void namedPropertyDeleterCustom(const AtomicString&, const v8::PropertyCallbackInfo<v8::Boolean>&);
+ static void NamedPropertyDeleterCustom(const AtomicString&, const v8::PropertyCallbackInfo<v8::Boolean>&);
{% endif %}
{% if named_property_getter and named_property_getter.is_custom_property_enumerator %}
- static void namedPropertyEnumeratorCustom(const v8::PropertyCallbackInfo<v8::Array>&);
+ static void NamedPropertyEnumeratorCustom(const v8::PropertyCallbackInfo<v8::Array>&);
{% endif %}
{# END custom special operations #}
{% if has_custom_legacy_call_as_function %}
- static void legacyCallCustom(const v8::FunctionCallbackInfo<v8::Value>&);
+ static void LegacyCallCustom(const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{# Custom internal fields #}
{# persistentHandleIndex must be the last field, if it is present.
@@ -110,25 +110,25 @@ class {{v8_class}} {
FIXME: Remove this internal field, and share one field for either:
* a persistent handle (if the object is in oilpan) or
* a C++ pointer to the DOM object (if the object is not in oilpan) #}
- static const int internalFieldCount = kV8DefaultWrapperInternalFieldCount;
+ static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount;
{# End custom internal fields #}
{% if install_conditional_features_func %}
{{exported}}static void InstallConditionalFeatures(
v8::Local<v8::Context>,
const DOMWrapperWorld&,
- v8::Local<v8::Object> instanceObject,
- v8::Local<v8::Object> prototypeObject,
- v8::Local<v8::Function> interfaceObject,
- v8::Local<v8::FunctionTemplate> interfaceTemplate);
+ v8::Local<v8::Object> instance_object,
+ v8::Local<v8::Object> prototype_object,
+ v8::Local<v8::Function> interface_object,
+ v8::Local<v8::FunctionTemplate> interface_template);
{% elif has_partial_interface %}
{{exported}}static void InstallConditionalFeatures(
v8::Local<v8::Context>,
const DOMWrapperWorld&,
- v8::Local<v8::Object> instanceObject,
- v8::Local<v8::Object> prototypeObject,
- v8::Local<v8::Function> interfaceObject,
- v8::Local<v8::FunctionTemplate> interfaceTemplate) {}
+ v8::Local<v8::Object> instance_object,
+ v8::Local<v8::Object> prototype_object,
+ v8::Local<v8::Function> interface_object,
+ v8::Local<v8::FunctionTemplate> interface_template) {}
{% endif %}
{% if has_partial_interface %}
@@ -137,47 +137,43 @@ class {{v8_class}} {
InstallRuntimeEnabledFeaturesFunction,
InstallRuntimeEnabledFeaturesOnTemplateFunction,
InstallConditionalFeaturesFunction);
- {{exported}}static void install{{v8_class}}Template(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interfaceTemplate);
+ {{exported}}static void Install{{v8_class}}Template(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template);
{% for method in methods if method.overloads and method.overloads.has_partial_overloads %}
- {{exported}}static void register{{method.name | blink_capitalize}}MethodForPartialInterface(void (*)(const v8::FunctionCallbackInfo<v8::Value>&));
+ {{exported}}static void Register{{method.camel_case_name}}MethodForPartialInterface(void (*)(const v8::FunctionCallbackInfo<v8::Value>&));
{% endfor %}
{% endif %}
{% for feature in optional_features %}
- static void install{{feature.name}}(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface);
- static void install{{feature.name}}(ScriptState*, v8::Local<v8::Object> instance);
+ static void Install{{feature.name}}(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface);
+ static void Install{{feature.name}}(ScriptState*, v8::Local<v8::Object> instance);
{% if not feature.needs_instance %}
- static void install{{feature.name}}(ScriptState*);
+ static void Install{{feature.name}}(ScriptState*);
{% endif %}
{% endfor %}
// Callback functions
- {% if constructors or has_custom_constructor or has_html_constructor %}
- {{exported}}static void constructorCallback(const v8::FunctionCallbackInfo<v8::Value>&);
-
- {% endif %}
{% for constant in constants | has_special_getter %}
- {{exported}}static void {{constant.name}}ConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void {{constant.camel_case_name}}ConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endfor %}
{% for attribute in attributes %}
{% if attribute.is_cached_accessor %}
- {{exported}}static v8::Local<v8::Private> {{attribute.name}}CachedPropertyKey(v8::Isolate*);
+ {{exported}}static v8::Local<v8::Private> {{attribute.camel_case_name}}CachedPropertyKey(v8::Isolate*);
{% endif %}
{% for world_suffix in attribute.world_suffixes %}
{% if not attribute.constructor_type %}
- {{exported}}static void {{attribute.name}}AttributeGetterCallback{{world_suffix}}(
+ {{exported}}static void {{attribute.camel_case_name}}AttributeGetterCallback{{world_suffix}}(
{%- if attribute.is_data_type_property -%}
v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&
{%- else -%}
const v8::FunctionCallbackInfo<v8::Value>&
{%- endif -%});
{% else %}
- {{exported}}static void {{attribute.name}}ConstructorGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void {{attribute.camel_case_name}}ConstructorGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if attribute.has_setter %}
- {{exported}}static void {{attribute.name}}AttributeSetterCallback{{world_suffix}}(
+ {{exported}}static void {{attribute.camel_case_name}}AttributeSetterCallback{{world_suffix}}(
{%- if attribute.is_data_type_property -%}
v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&
{%- else -%}
@@ -197,66 +193,66 @@ class {{v8_class}} {
(not method.overloads and method.visible) %}
{# A single callback is generated for overloaded methods #}
{# with considering partial overloads #}
- {{exported}}static void {{method.name}}MethodCallback{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>&);
+ {{exported}}static void {{method.camel_case_name}}MethodCallback{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{% if method.is_cross_origin and method.visible %}
- {{exported}}static void {{method.name}}OriginSafeMethodGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void {{method.camel_case_name}}OriginSafeMethodGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
{% if iterator_method %}
- {{exported}}static void {{iterator_method.name}}MethodCallback(const v8::FunctionCallbackInfo<v8::Value>&);
+ {{exported}}static void {{iterator_method.camel_case_name}}MethodCallback(const v8::FunctionCallbackInfo<v8::Value>&);
{% endif %}
{% if has_origin_safe_method_setter %}
{{exported}}static void {{cpp_class}}OriginSafeMethodSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&);
{% endif %}
{% if has_access_check_callbacks and not is_partial %}
- {{exported}}static bool securityCheck(v8::Local<v8::Context>, v8::Local<v8::Object>, v8::Local<v8::Value>);
+ {{exported}}static bool SecurityCheck(v8::Local<v8::Context>, v8::Local<v8::Object>, v8::Local<v8::Value>);
{% if has_cross_origin_named_getter %}
- {{exported}}static void crossOriginNamedGetter(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void CrossOriginNamedGetter(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if has_cross_origin_named_setter %}
- {{exported}}static void crossOriginNamedSetter(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void CrossOriginNamedSetter(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if has_cross_origin_named_enumerator %}
- {{exported}}static void crossOriginNamedEnumerator(const v8::PropertyCallbackInfo<v8::Array>&);
+ {{exported}}static void CrossOriginNamedEnumerator(const v8::PropertyCallbackInfo<v8::Array>&);
{% endif %}
{% if has_cross_origin_indexed_getter %}
- {{exported}}static void crossOriginIndexedGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void CrossOriginIndexedGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% endif %}
{% if named_property_getter %}
- {{exported}}static void namedPropertyGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void NamedPropertyGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if named_property_setter %}
- {{exported}}static void namedPropertySetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void NamedPropertySetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if named_property_deleter %}
- {{exported}}static void namedPropertyDeleterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean>&);
+ {{exported}}static void NamedPropertyDeleterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean>&);
{% endif %}
{% if named_property_getter and named_property_getter.is_enumerable %}
- {{exported}}static void namedPropertyQueryCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer>&);
+ {{exported}}static void NamedPropertyQueryCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer>&);
{% endif %}
{% if named_property_getter and named_property_getter.is_enumerable %}
- {{exported}}static void namedPropertyEnumeratorCallback(const v8::PropertyCallbackInfo<v8::Array>&);
+ {{exported}}static void NamedPropertyEnumeratorCallback(const v8::PropertyCallbackInfo<v8::Array>&);
{% endif %}
{% if indexed_property_getter or named_property_getter %}
- {{exported}}static void indexedPropertyGetterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void IndexedPropertyGetterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if indexed_property_getter or named_property_setter %}
- {{exported}}static void indexedPropertySetterCallback(uint32_t index, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void IndexedPropertySetterCallback(uint32_t index, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if indexed_property_getter or named_property_getter %}
- {{exported}}static void indexedPropertyDescriptorCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void IndexedPropertyDescriptorCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if indexed_property_deleter or named_property_deleter %}
- {{exported}}static void indexedPropertyDeleterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>&);
+ {{exported}}static void IndexedPropertyDeleterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>&);
{% endif %}
{% if indexed_property_getter %}
- {{exported}}static void indexedPropertyDefinerCallback(uint32_t index, const v8::PropertyDescriptor&, const v8::PropertyCallbackInfo<v8::Value>&);
+ {{exported}}static void IndexedPropertyDefinerCallback(uint32_t index, const v8::PropertyDescriptor&, const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if needs_runtime_enabled_installer %}
@@ -290,7 +286,7 @@ class {{v8_class}} {
v8::Local<v8::Function> interface);
{% endif %}{# needs_runtime_enabled_installer #}
{% if has_partial_interface %}
- static InstallTemplateFunction install{{v8_class}}TemplateFunction;
+ static InstallTemplateFunction install_{{snake_case_v8_class}}_template_function_;
{% if needs_runtime_enabled_installer %}
static InstallRuntimeEnabledFeaturesFunction
install_runtime_enabled_features_function_;
@@ -312,6 +308,6 @@ struct V8TypeOf<{{cpp_class}}> {
} // namespace blink
-#endif // {{v8_class}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/interface_base.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl
index f78737d467f..1f41c62eb8a 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/interface_base.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl
@@ -8,8 +8,8 @@
{% endfor %}
namespace blink {
-{% set dom_template = '%s::domTemplate' % v8_class if not is_array_buffer_or_view else 'nullptr' %}
-{% set parent_wrapper_type_info = '&V8%s::wrapperTypeInfo' % parent_interface
+{% set dom_template = '%s::DomTemplate' % v8_class if not is_array_buffer_or_view else 'nullptr' %}
+{% set parent_wrapper_type_info = '&V8%s::wrapper_type_info' % parent_interface
if parent_interface else 'nullptr' %}
{% set active_scriptwrappable_inheritance =
'kInheritFromActiveScriptWrappable'
@@ -24,7 +24,7 @@ namespace blink {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
-{{wrapper_type_info_const}}WrapperTypeInfo {{v8_class}}::wrapperTypeInfo = {
+{{wrapper_type_info_const}}WrapperTypeInfo {{v8_class}}::wrapper_type_info = {
gin::kEmbedderBlink,
{{dom_template}},
{{install_conditional_features_func or 'nullptr'}},
@@ -42,7 +42,7 @@ namespace blink {
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in {{cpp_class}}.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// platform/bindings/ScriptWrappable.h.
-const WrapperTypeInfo& {{cpp_class}}::wrapper_type_info_ = {{v8_class}}::wrapperTypeInfo;
+const WrapperTypeInfo& {{cpp_class}}::wrapper_type_info_ = {{v8_class}}::wrapper_type_info;
{% endif %}
{% if active_scriptwrappable %}
@@ -75,7 +75,7 @@ static_assert(
{% endif %}{# not is_partial #}
{% if not is_array_buffer_or_view %}
-namespace {{cpp_class_or_partial}}V8Internal {
+namespace {{internal_namespace}} {
{% if has_partial_interface %}
{% for method in methods if method.overloads and method.overloads.has_partial_overloads %}
static void (*{{method.name}}MethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
@@ -84,7 +84,7 @@ static void (*{{method.name}}MethodForPartialInterface)(const v8::FunctionCallba
{##############################################################################}
{# Attributes #}
-{% from 'attributes.cpp.tmpl' import attribute_getter,
+{% from 'attributes.cc.tmpl' import attribute_getter,
attribute_setter,
with context %}
{% for attribute in attributes %}
@@ -99,7 +99,7 @@ static void (*{{method.name}}MethodForPartialInterface)(const v8::FunctionCallba
{% endfor %}
{##############################################################################}
{# Methods #}
-{% from 'methods.cpp.tmpl' import generate_method, overload_resolution_method,
+{% from 'methods.cc.tmpl' import generate_method, overload_resolution_method,
origin_safe_method_getter, generate_constructor,
runtime_determined_length_method, runtime_determined_maxarg_method
with context %}
@@ -132,6 +132,7 @@ static void (*{{method.name}}MethodForPartialInterface)(const v8::FunctionCallba
{{generate_constructor(constructor)}}
{% endfor %}
{% block overloaded_constructor %}{% endblock %}
+{% block constructor_callback %}{% endblock %}
{# Special operations (methods) #}
{% block named_property_getter %}{% endblock %}
{% block named_property_setter %}{% endblock %}
@@ -159,34 +160,34 @@ static const struct {
"{{attribute.name}}",
{% if attribute.has_cross_origin_getter %}
{% if attribute.has_custom_getter %}
- {{v8_class}}::{{attribute.name}}AttributeGetterCustom,
+ {{v8_class}}::{{attribute.camel_case_name}}AttributeGetterCustom,
{% else %}
- &{{cpp_class}}V8Internal::{{attribute.name}}AttributeGetter,
+ {{internal_namespace}}::{{attribute.camel_case_name}}AttributeGetter,
{% endif %}
{% else %}
nullptr,
{% endif %}
- {%+ if attribute.has_cross_origin_setter %}&{{cpp_class}}V8Internal::{{attribute.name}}AttributeSetter{% else %}nullptr{% endif %},
+ {%+ if attribute.has_cross_origin_setter %}&{{internal_namespace}}::{{attribute.camel_case_name}}AttributeSetter{% else %}nullptr{% endif %},
},
{% endfor %}
{##### Cross-origin methods #####}
{% for method in methods if method.is_cross_origin and
(not method.overload_index or method.overloads) %}
- {"{{method.name}}", &{{cpp_class}}V8Internal::{{method.name}}OriginSafeMethodGetter, nullptr},
+ {"{{method.name}}", &{{internal_namespace}}::{{method.camel_case_name}}OriginSafeMethodGetter, nullptr},
{% endfor %}
};
{% endif %}
{##############################################################################}
-} // namespace {{cpp_class_or_partial}}V8Internal
+} // namespace {{internal_namespace}}
{# Constants #}
-{% from 'constants.cpp.tmpl' import constant_getter_callback with context %}
+{% from 'constants.cc.tmpl' import constant_getter_callback with context %}
{% for constant in constants | has_special_getter %}
{{constant_getter_callback(constant)}}
{% endfor %}
{# Attributes #}
-{% from 'attributes.cpp.tmpl' import constructor_getter_callback,
+{% from 'attributes.cc.tmpl' import constructor_getter_callback,
attribute_getter_callback, attribute_setter_callback with context %}
{% for attribute in attributes %}
{% for world_suffix in attribute.world_suffixes %}
@@ -202,7 +203,7 @@ static const struct {
{% endfor %}
{# Methods #}
-{% from 'methods.cpp.tmpl' import origin_safe_method_getter_callback,
+{% from 'methods.cc.tmpl' import origin_safe_method_getter_callback,
method_callback with context %}
{% for method in methods %}
{% for world_suffix in method.world_suffixes %}
@@ -240,32 +241,32 @@ static const struct {
{% block indexed_property_definer_callback %}{% endblock %}
{% if has_access_check_callbacks and not is_partial %}
-bool {{v8_class_or_partial}}::securityCheck(v8::Local<v8::Context> accessingContext, v8::Local<v8::Object> accessedObject, v8::Local<v8::Value> data) {
+bool {{v8_class_or_partial}}::SecurityCheck(v8::Local<v8::Context> accessing_context, v8::Local<v8::Object> accessed_object, v8::Local<v8::Value> data) {
{% if interface_name == 'Window' %}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
- v8::Local<v8::Object> window = V8Window::findInstanceInPrototypeChain(accessedObject, isolate);
+ v8::Local<v8::Object> window = V8Window::FindInstanceInPrototypeChain(accessed_object, isolate);
if (window.IsEmpty())
return false; // the frame is gone.
- const DOMWindow* targetWindow = V8Window::ToImpl(window);
- return BindingSecurity::ShouldAllowAccessTo(ToLocalDOMWindow(accessingContext), targetWindow, BindingSecurity::ErrorReportOption::kDoNotReport);
+ const DOMWindow* target_window = V8Window::ToImpl(window);
+ return BindingSecurity::ShouldAllowAccessTo(ToLocalDOMWindow(accessing_context), target_window, BindingSecurity::ErrorReportOption::kDoNotReport);
{% elif interface_name == 'Location' %}
- {{cpp_class}}* impl = {{v8_class}}::ToImpl(accessedObject);
- return BindingSecurity::ShouldAllowAccessTo(ToLocalDOMWindow(accessingContext), impl, BindingSecurity::ErrorReportOption::kDoNotReport);
+ {{cpp_class}}* impl = {{v8_class}}::ToImpl(accessed_object);
+ return BindingSecurity::ShouldAllowAccessTo(ToLocalDOMWindow(accessing_context), impl, BindingSecurity::ErrorReportOption::kDoNotReport);
{% else %}
#error "Unexpected security check for interface {{interface_name}}"
{% endif %}
}
{% if has_cross_origin_named_getter %}
-void {{v8_class_or_partial}}::crossOriginNamedGetter(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::CrossOriginNamedGetter(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.cross_origin_named_getter_counter) }}
if (!name->IsString())
return;
- const AtomicString& propertyName = ToCoreAtomicString(name.As<v8::String>());
+ const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
- for (const auto& attribute : {{cpp_class_or_partial}}V8Internal::kCrossOriginAttributeTable) {
- if (propertyName == attribute.name && attribute.getter) {
+ for (const auto& attribute : {{internal_namespace}}::kCrossOriginAttributeTable) {
+ if (property_name == attribute.name && attribute.getter) {
attribute.getter(info);
return;
}
@@ -273,9 +274,9 @@ void {{v8_class_or_partial}}::crossOriginNamedGetter(v8::Local<v8::Name> name, c
{% if named_property_getter and named_property_getter.is_cross_origin %}
{% if named_property_getter.is_custom %}
- {{v8_class}}::namedPropertyGetterCustom(propertyName, info);
+ {{v8_class}}::NamedPropertyGetterCustom(property_name, info);
{% else %}
- {{cpp_class}}V8Internal::namedPropertyGetter(propertyName, info);
+ {{internal_namespace}}::NamedPropertyGetter(property_name, info);
{% endif %}
{% else %}
// HTML 7.2.3.3 CrossOriginGetOwnPropertyHelper ( O, P )
@@ -284,28 +285,28 @@ void {{v8_class_or_partial}}::crossOriginNamedGetter(v8::Local<v8::Name> name, c
// @@isConcatSpreadable, then return PropertyDescriptor{ [[Value]]:
// undefined, [[Writable]]: false, [[Enumerable]]: false,
// [[Configurable]]: true }.
- if (propertyName == "then") {
+ if (property_name == "then") {
V8SetReturnValue(info, v8::Undefined(info.GetIsolate()));
return;
}
BindingSecurity::FailedAccessCheckFor(
info.GetIsolate(),
- &{{v8_class}}::wrapperTypeInfo,
+ &{{v8_class}}::wrapper_type_info,
info.Holder());
{% endif %}
}
{% endif %}
{% if has_cross_origin_named_setter %}
-void {{v8_class_or_partial}}::crossOriginNamedSetter(v8::Local<v8::Name> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::CrossOriginNamedSetter(v8::Local<v8::Name> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(runtime_call_stats.cross_origin_named_setter_counter) }}
if (!name->IsString())
return;
- const AtomicString& propertyName = ToCoreAtomicString(name.As<v8::String>());
+ const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
- for (const auto& attribute : {{cpp_class_or_partial}}V8Internal::kCrossOriginAttributeTable) {
- if (propertyName == attribute.name && attribute.setter) {
+ for (const auto& attribute : {{internal_namespace}}::kCrossOriginAttributeTable) {
+ if (property_name == attribute.name && attribute.setter) {
attribute.setter(value, V8CrossOriginSetterInfo(info.GetIsolate(), info.Holder()));
return;
}
@@ -317,15 +318,15 @@ void {{v8_class_or_partial}}::crossOriginNamedSetter(v8::Local<v8::Name> name, v
BindingSecurity::FailedAccessCheckFor(
info.GetIsolate(),
- &{{v8_class}}::wrapperTypeInfo,
+ &{{v8_class}}::wrapper_type_info,
info.Holder());
}
{% endif %}
{% if has_cross_origin_named_enumerator %}
-void {{v8_class_or_partial}}::crossOriginNamedEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
+void {{v8_class_or_partial}}::CrossOriginNamedEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
Vector<String> names;
- for (const auto& attribute : {{cpp_class_or_partial}}V8Internal::kCrossOriginAttributeTable)
+ for (const auto& attribute : {{internal_namespace}}::kCrossOriginAttributeTable)
names.push_back(attribute.name);
// Use the current context as the creation context, as a cross-origin access
@@ -337,11 +338,11 @@ void {{v8_class_or_partial}}::crossOriginNamedEnumerator(const v8::PropertyCallb
{% endif %}
{% if has_cross_origin_indexed_getter %}
-void {{v8_class_or_partial}}::crossOriginIndexedGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::CrossOriginIndexedGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
{% if indexed_property_getter.is_custom %}
- {{v8_class}}::indexedPropertyGetterCustom(index, info);
+ {{v8_class}}::IndexedPropertyGetterCustom(index, info);
{% else %}
- {{cpp_class}}V8Internal::indexedPropertyGetter(index, info);
+ {{internal_namespace}}::IndexedPropertyGetter(index, info);
{% endif %}
}
{% endif %}
@@ -350,7 +351,7 @@ void {{v8_class_or_partial}}::crossOriginIndexedGetter(uint32_t index, const v8:
{% block visit_dom_wrapper %}{% endblock %}
{##############################################################################}
{% block install_attributes %}
-{% from 'attributes.cpp.tmpl' import attribute_configuration with context %}
+{% from 'attributes.cc.tmpl' import attribute_configuration with context %}
{% if data_attributes %}
// Suppress warning: global constructors, because AttributeConfiguration is trivial
// and does not depend on another global objects.
@@ -358,7 +359,7 @@ void {{v8_class_or_partial}}::crossOriginIndexedGetter(uint32_t index, const v8:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
-static const V8DOMConfiguration::AttributeConfiguration {{v8_class}}Attributes[] = {
+static constexpr V8DOMConfiguration::AttributeConfiguration k{{v8_class}}Attributes[] = {
{% for data_attribute in data_attributes %}
{{attribute_configuration(data_attribute) | trim | indent(4)}},
{% endfor %}
@@ -371,9 +372,9 @@ static const V8DOMConfiguration::AttributeConfiguration {{v8_class}}Attributes[]
{% endblock %}
{##############################################################################}
{% block install_accessors %}
-{% from 'attributes.cpp.tmpl' import accessor_configuration with context %}
+{% from 'attributes.cc.tmpl' import accessor_configuration with context %}
{% if accessors %}
-static const V8DOMConfiguration::AccessorConfiguration {{v8_class}}Accessors[] = {
+static constexpr V8DOMConfiguration::AccessorConfiguration k{{v8_class}}Accessors[] = {
{% for accessor in accessors %}
{{accessor_configuration(accessor) | trim | indent(4)}},
{% endfor %}
@@ -383,9 +384,9 @@ static const V8DOMConfiguration::AccessorConfiguration {{v8_class}}Accessors[] =
{% endblock %}
{##############################################################################}
{% block install_methods %}
-{% from 'methods.cpp.tmpl' import method_configuration with context %}
+{% from 'methods.cc.tmpl' import method_configuration with context %}
{% if methods | has_method_configuration(is_partial) %}
-static const V8DOMConfiguration::MethodConfiguration {{v8_class}}Methods[] = {
+static constexpr V8DOMConfiguration::MethodConfiguration k{{v8_class}}Methods[] = {
{% for method in methods | has_method_configuration(is_partial) %}
{{method_configuration(method) | trim | indent(4)}},
{% endfor %}
@@ -396,42 +397,41 @@ static const V8DOMConfiguration::MethodConfiguration {{v8_class}}Methods[] = {
{% endif %}{# not is_array_buffer_or_view #}
{##############################################################################}
{% block named_constructor %}{% endblock %}
-{% block constructor_callback %}{% endblock %}
{##############################################################################}
{% block install_dom_template %}
{% if not is_array_buffer_or_view %}
-{% from 'methods.cpp.tmpl' import install_custom_signature,
+{% from 'methods.cc.tmpl' import install_custom_signature,
method_configuration with context %}
-{% from 'attributes.cpp.tmpl' import accessor_configuration,
+{% from 'attributes.cc.tmpl' import accessor_configuration,
attribute_configuration,
with context %}
-{% from 'constants.cpp.tmpl' import install_constants,
+{% from 'constants.cc.tmpl' import install_constants,
constant_configuration with context %}
{% if has_partial_interface or is_partial %}
-void {{v8_class_or_partial}}::install{{v8_class}}Template(
+void {{v8_class_or_partial}}::Install{{v8_class}}Template(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
- v8::Local<v8::FunctionTemplate> interfaceTemplate) {
+ v8::Local<v8::FunctionTemplate> interface_template) {
{% else %}
-static void install{{v8_class}}Template(
+static void Install{{v8_class}}Template(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
- v8::Local<v8::FunctionTemplate> interfaceTemplate) {
+ v8::Local<v8::FunctionTemplate> interface_template) {
{% endif %}
// Initialize the interface object's template.
{% if is_partial %}
- {{v8_class}}::install{{v8_class}}Template(isolate, world, interfaceTemplate);
+ {{v8_class}}::Install{{v8_class}}Template(isolate, world, interface_template);
{% else %}
{% set parent_interface_template =
- '%s::domTemplateForNamedPropertiesObject(isolate, world)' % v8_class
+ '%s::DomTemplateForNamedPropertiesObject(isolate, world)' % v8_class
if has_named_properties_object else
- 'V8%s::domTemplate(isolate, world)' % parent_interface
+ 'V8%s::DomTemplate(isolate, world)' % parent_interface
if parent_interface else
'v8::Local<v8::FunctionTemplate>()' %}
- V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interfaceTemplate, {{v8_class}}::wrapperTypeInfo.interface_name, {{parent_interface_template}}, {{v8_class}}::internalFieldCount);
+ V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, {{v8_class}}::wrapper_type_info.interface_name, {{parent_interface_template}}, {{v8_class}}::kInternalFieldCount);
{% if constructors or has_custom_constructor or has_html_constructor %}
- interfaceTemplate->SetCallHandler({{v8_class}}::constructorCallback);
- interfaceTemplate->SetLength({{interface_length}});
+ interface_template->SetCallHandler({{internal_namespace}}::ConstructorCallback);
+ interface_template->SetLength({{interface_length}});
{% endif %}
{% endif %}{# is_partial #}
@@ -441,25 +441,25 @@ static void install{{v8_class}}Template(
}
{% endif %}
- v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
+ v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
- v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate();
- ALLOW_UNUSED_LOCAL(instanceTemplate);
- v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate();
- ALLOW_UNUSED_LOCAL(prototypeTemplate);
+ v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
+ ALLOW_UNUSED_LOCAL(instance_template);
+ v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
+ ALLOW_UNUSED_LOCAL(prototype_template);
{% if interface_name == 'Window' and not is_partial %}
- prototypeTemplate->SetInternalFieldCount(V8Window::internalFieldCount);
+ prototype_template->SetInternalFieldCount(V8Window::kInternalFieldCount);
{% endif %}
{% if is_immutable_prototype %}
// Global object prototype chain consists of Immutable Prototype Exotic Objects
- prototypeTemplate->SetImmutableProto();
+ prototype_template->SetImmutableProto();
{% endif %}
{% if is_global %}
// Global objects are Immutable Prototype Exotic Objects
- instanceTemplate->SetImmutableProto();
+ instance_template->SetImmutableProto();
{% endif %}
// Register IDL constants, attributes and operations.
@@ -468,28 +468,28 @@ static void install{{v8_class}}Template(
{% endif %}
{% if data_attributes %}
V8DOMConfiguration::InstallAttributes(
- isolate, world, instanceTemplate, prototypeTemplate,
- {{'%sAttributes' % v8_class}}, {{'base::size(%sAttributes)' % v8_class}});
+ isolate, world, instance_template, prototype_template,
+ k{{v8_class}}Attributes, base::size(k{{v8_class}}Attributes));
{% endif %}
{% if accessors %}
V8DOMConfiguration::InstallAccessors(
- isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate,
- signature, {{'%sAccessors' % v8_class}}, {{'base::size(%sAccessors)' % v8_class}});
+ isolate, world, instance_template, prototype_template, interface_template,
+ signature, k{{v8_class}}Accessors, base::size(k{{v8_class}}Accessors));
{% endif %}
{% if methods | has_method_configuration(is_partial) %}
V8DOMConfiguration::InstallMethods(
- isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate,
- signature, {{'%sMethods' % v8_class}}, {{'base::size(%sMethods)' % v8_class}});
+ isolate, world, instance_template, prototype_template, interface_template,
+ signature, k{{v8_class}}Methods, base::size(k{{v8_class}}Methods));
{% endif %}
{% if has_access_check_callbacks and not is_partial %}
// Cross-origin access check
- {% set cross_origin_named_getter = '%s::crossOriginNamedGetter' % v8_class_or_partial if has_cross_origin_named_getter else 'nullptr' %}
- {% set cross_origin_named_setter = '%s::crossOriginNamedSetter' % v8_class_or_partial if has_cross_origin_named_setter else 'nullptr' %}
- {% set cross_origin_named_enumerator = '%s::crossOriginNamedEnumerator' % v8_class_or_partial if has_cross_origin_named_enumerator else 'nullptr' %}
- {% set cross_origin_indexed_getter = '%s::crossOriginIndexedGetter' % v8_class_or_partial if has_cross_origin_indexed_getter else 'nullptr' %}
- instanceTemplate->SetAccessCheckCallbackAndHandler(
- {{v8_class_or_partial}}::securityCheck,
+ {% set cross_origin_named_getter = '%s::CrossOriginNamedGetter' % v8_class_or_partial if has_cross_origin_named_getter else 'nullptr' %}
+ {% set cross_origin_named_setter = '%s::CrossOriginNamedSetter' % v8_class_or_partial if has_cross_origin_named_setter else 'nullptr' %}
+ {% set cross_origin_named_enumerator = '%s::CrossOriginNamedEnumerator' % v8_class_or_partial if has_cross_origin_named_enumerator else 'nullptr' %}
+ {% set cross_origin_indexed_getter = '%s::CrossOriginIndexedGetter' % v8_class_or_partial if has_cross_origin_indexed_getter else 'nullptr' %}
+ instance_template->SetAccessCheckCallbackAndHandler(
+ {{v8_class_or_partial}}::SecurityCheck,
v8::NamedPropertyHandlerConfiguration(
{{cross_origin_named_getter}},
{{cross_origin_named_setter}},
@@ -497,31 +497,31 @@ static void install{{v8_class}}Template(
nullptr,
{{cross_origin_named_enumerator}}),
v8::IndexedPropertyHandlerConfiguration({{cross_origin_indexed_getter}}),
- v8::External::New(isolate, const_cast<WrapperTypeInfo*>(&{{v8_class}}::wrapperTypeInfo)));
+ v8::External::New(isolate, const_cast<WrapperTypeInfo*>(&{{v8_class}}::wrapper_type_info)));
{% endif %}
{% if (indexed_property_getter or named_property_getter) and not is_partial %}
// Indexed properties
- {{install_indexed_property_handler('instanceTemplate') | trim | indent(2)}}
+ {{install_indexed_property_handler('instance_template') | trim | indent(2)}}
{% endif %}
{% if named_property_getter and not is_partial and not has_named_properties_object %}
// Named properties
- {{install_named_property_handler('instanceTemplate') | trim | indent(2)}}
+ {{install_named_property_handler('instance_template') | trim | indent(2)}}
{% endif %}
{% if has_array_iterator and not is_partial %}
// Array iterator (@@iterator)
- {%+ if is_global %}instanceTemplate{% else %}prototypeTemplate{% endif %}->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum);
+ {%+ if is_global %}instance_template{% else %}prototype_template{% endif %}->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum);
{% if iterable %}
{% if is_global %}
-#error "iterable<V> on [Global] and [PrimaryGlobal] is currently unsupported."
+#error "iterable<V> on [Global] is currently unsupported."
{% endif %}
// For value iterators, the properties below must originally be set to the corresponding ones in %ArrayPrototype%.
// See https://heycam.github.io/webidl/#es-iterators.
- prototypeTemplate->SetIntrinsicDataProperty(V8AtomicString(isolate, "entries"), v8::kArrayProto_entries);
- prototypeTemplate->SetIntrinsicDataProperty(V8AtomicString(isolate, "forEach"), v8::kArrayProto_forEach);
- prototypeTemplate->SetIntrinsicDataProperty(V8AtomicString(isolate, "keys"), v8::kArrayProto_keys);
- prototypeTemplate->SetIntrinsicDataProperty(V8AtomicString(isolate, "values"), v8::kArrayProto_values);
+ prototype_template->SetIntrinsicDataProperty(V8AtomicString(isolate, "entries"), v8::kArrayProto_entries);
+ prototype_template->SetIntrinsicDataProperty(V8AtomicString(isolate, "forEach"), v8::kArrayProto_forEach);
+ prototype_template->SetIntrinsicDataProperty(V8AtomicString(isolate, "keys"), v8::kArrayProto_keys);
+ prototype_template->SetIntrinsicDataProperty(V8AtomicString(isolate, "values"), v8::kArrayProto_values);
{% endif %}
{% endif %}
@@ -531,10 +531,10 @@ static void install{{v8_class}}Template(
if iterator_method_alias else 'nullptr' %}
// Iterator (@@iterator)
static const V8DOMConfiguration::SymbolKeyedMethodConfiguration
- symbolKeyedIteratorConfiguration = {
+ kSymbolKeyedIteratorConfiguration = {
v8::Symbol::GetIterator,
{{symbol_alias}},
- {{v8_class_or_partial}}::iteratorMethodCallback,
+ {{v8_class_or_partial}}::IteratorMethodCallback,
0,
v8::DontEnum,
V8DOMConfiguration::kOnPrototype,
@@ -542,7 +542,9 @@ static void install{{v8_class}}Template(
V8DOMConfiguration::kDoNotCheckAccess,
V8DOMConfiguration::kHasSideEffect
};
- V8DOMConfiguration::InstallMethod(isolate, world, prototypeTemplate, signature, symbolKeyedIteratorConfiguration);
+ V8DOMConfiguration::InstallMethod(
+ isolate, world, prototype_template, signature,
+ kSymbolKeyedIteratorConfiguration);
{% endfilter %}
{% endif %}
@@ -563,24 +565,24 @@ static void install{{v8_class}}Template(
// - Making the prototype object inherit from %IteratorPrototype% with the
// hack below, which creates another function template with no prototype
// and sets the "prototype" property of its function object.
- // When |interfaceTemplate|'s function object is created, its
+ // When |interface_template|'s function object is created, its
// prototype.__proto__ will point to the value of the "prototype" property
- // of |intrinsicIteratorPrototypeInterfaceTemplate|, which is exactly what
- // we want.
+ // of |intrinsic_iterator_prototype_interface_template|, which is exactly
+ // what we want.
//
// Finally, creating a FunctionTemplate here might look expensive since they
// have the same lifetime as their context, but:
- // - |interfaceTemplate| is cached in V8PerIsolateData, so we create only one
+ // - |interface_template| is cached in V8PerIsolateData, so we create only one
// FunctionTemplate per interface.
// - There is only one Iterator interface that creates this FunctionTemplate,
// so there is no need to reuse this FunctionTemplate and register it in
// V8PerIsolateData.
- v8::Local<v8::FunctionTemplate> intrinsicIteratorPrototypeInterfaceTemplate =
+ v8::Local<v8::FunctionTemplate> intrinsic_iterator_prototype_interface_template =
v8::FunctionTemplate::New(isolate);
- intrinsicIteratorPrototypeInterfaceTemplate->RemovePrototype();
- intrinsicIteratorPrototypeInterfaceTemplate->SetIntrinsicDataProperty(
+ intrinsic_iterator_prototype_interface_template->RemovePrototype();
+ intrinsic_iterator_prototype_interface_template->SetIntrinsicDataProperty(
V8AtomicString(isolate, "prototype"), v8::kIteratorPrototype);
- interfaceTemplate->Inherit(intrinsicIteratorPrototypeInterfaceTemplate);
+ interface_template->Inherit(intrinsic_iterator_prototype_interface_template);
{% endif %}
{% if interface_name == 'DOMException' %}
@@ -596,15 +598,15 @@ static void install{{v8_class}}Template(
//
// We achieve this with the same hack we use for Iterators: create a new
// function template with no prototype, set its "prototype" property to
- // %ErrorPrototype% and make |interfaceTemplate| inherit from it. When
- // |interfaceTemplate| is instantiated, its prototype.__proto__ will point to
- // |intrinsicErrorPrototypeInterfaceTemplate|'s "prototype" property.
- v8::Local<v8::FunctionTemplate> intrinsicErrorPrototypeInterfaceTemplate =
+ // %ErrorPrototype% and make |interface_template| inherit from it. When
+ // |interface_template| is instantiated, its prototype.__proto__ will point to
+ // |intrinsic_error_prototype_interface_template|'s "prototype" property.
+ v8::Local<v8::FunctionTemplate> intrinsic_error_prototype_interface_template =
v8::FunctionTemplate::New(isolate);
- intrinsicErrorPrototypeInterfaceTemplate->RemovePrototype();
- intrinsicErrorPrototypeInterfaceTemplate->SetIntrinsicDataProperty(
+ intrinsic_error_prototype_interface_template->RemovePrototype();
+ intrinsic_error_prototype_interface_template->SetIntrinsicDataProperty(
V8AtomicString(isolate, "prototype"), v8::kErrorPrototype);
- interfaceTemplate->Inherit(intrinsicErrorPrototypeInterfaceTemplate);
+ interface_template->Inherit(intrinsic_error_prototype_interface_template);
{% endif %}
{% if interface_name == 'Location' %}
@@ -612,19 +614,19 @@ static void install{{v8_class}}Template(
// Prevent author scripts to inject Symbol.toPrimitive property into location
// objects, also prevent the look-up of Symbol.toPrimitive through the
// prototype chain.
- instanceTemplate->Set(v8::Symbol::GetToPrimitive(isolate),
+ instance_template->Set(v8::Symbol::GetToPrimitive(isolate),
v8::Undefined(isolate),
static_cast<v8::PropertyAttribute>(
v8::ReadOnly | v8::DontEnum | v8::DontDelete));
{% endif %}
{% if has_custom_legacy_call_as_function and not is_partial %}
- instanceTemplate->SetCallAsFunctionHandler({{v8_class}}::legacyCallCustom);
+ instance_template->SetCallAsFunctionHandler({{v8_class}}::LegacyCallCustom);
{% endif %}
{% if interface_name == 'HTMLAllCollection' and not is_partial %}
// Needed for legacy support of document.all
- instanceTemplate->MarkAsUndetectable();
+ instance_template->MarkAsUndetectable();
{% endif %}
// Custom signature
@@ -635,9 +637,9 @@ static void install{{v8_class}}Template(
if method.overloads else method.runtime_enabled_feature_name %}
{% if not feature_name %}
{% if method.is_cross_origin %}
- {{install_origin_safe_method(method, 'instanceTemplate', 'prototypeTemplate') | trim | indent(2)}}
+ {{install_origin_safe_method(method, 'instance_template', 'prototype_template') | trim | indent(2)}}
{% else %}
- {{install_custom_signature(method, 'instanceTemplate', 'prototypeTemplate', 'interfaceTemplate', 'signature') | trim | indent(2)}}
+ {{install_custom_signature(method, 'instance_template', 'prototype_template', 'interface_template', 'signature') | trim | indent(2)}}
{% endif %}
{% endif %}
{% endfilter %}
@@ -645,7 +647,7 @@ static void install{{v8_class}}Template(
{% if not has_partial_interface %}
{{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesOnTemplate(
- isolate, world, interfaceTemplate);
+ isolate, world, interface_template);
{% endif %}
}
@@ -673,41 +675,40 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesOnTemplate(
// Register IDL constants, attributes and operations.
{% for feature_name, constants_list in constants | selectattr('runtime_enabled_feature_name') | groupby('runtime_enabled_feature_name') %}
{% filter runtime_enabled(feature_name) %}
- static const V8DOMConfiguration::ConstantConfiguration constant_configurations[] = {
+ static constexpr V8DOMConfiguration::ConstantConfiguration kConfigurations[] = {
{% for constant in constants_list %}
{{constant_configuration(constant) | trim | indent(6)}},
{% endfor %}
};
V8DOMConfiguration::InstallConstants(
isolate, interface_template, prototype_template,
- constant_configurations, base::size(constant_configurations));
+ kConfigurations, base::size(kConfigurations));
{% endfilter %}
{% endfor %}
{% for feature_name, attribute_list in runtime_enabled_attributes | selectattr('is_data_type_property') | groupby('runtime_enabled_feature_name') %}
{% filter runtime_enabled(feature_name) %}
- static const V8DOMConfiguration::AttributeConfiguration attribute_configurations[] = {
+ static constexpr V8DOMConfiguration::AttributeConfiguration kConfigurations[] = {
{% for attribute in attribute_list | sort %}
{{attribute_configuration(attribute) | trim | indent(6)}},
{% endfor %}
};
V8DOMConfiguration::InstallAttributes(
isolate, world, instance_template, prototype_template,
- attribute_configurations, base::size(attribute_configurations));
+ kConfigurations, base::size(kConfigurations));
{% endfilter %}
{% endfor %}
{% for feature_name, attribute_list in runtime_enabled_attributes | selectattr('is_data_type_property', 'equalto', False) | groupby('runtime_enabled_feature_name') %}
{% filter runtime_enabled(feature_name) %}
- static const V8DOMConfiguration::AccessorConfiguration accessor_configurations[] = {
+ static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = {
{% for attribute in attribute_list | sort %}
{{accessor_configuration(attribute) | trim | indent(6)}},
{% endfor %}
};
V8DOMConfiguration::InstallAccessors(
isolate, world, instance_template, prototype_template, interface_template,
- signature, accessor_configurations,
- base::size(accessor_configurations));
+ signature, kConfigurations, base::size(kConfigurations));
{% endfilter %}
{% endfor %}
@@ -717,11 +718,11 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesOnTemplate(
{% set symbol_alias = '"%s"' % iterator_method_alias
if iterator_method_alias else 'nullptr' %}
// Iterator (@@iterator)
- static const V8DOMConfiguration::SymbolKeyedMethodConfiguration
- symbol_keyed_iterator_configuration = {
+ static constexpr V8DOMConfiguration::SymbolKeyedMethodConfiguration
+ kSymbolKeyedIteratorConfiguration = {
v8::Symbol::GetIterator,
{{symbol_alias}},
- {{v8_class_or_partial}}::iteratorMethodCallback,
+ {{v8_class_or_partial}}::IteratorMethodCallback,
0,
v8::DontEnum,
V8DOMConfiguration::kOnPrototype,
@@ -731,7 +732,7 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesOnTemplate(
};
V8DOMConfiguration::InstallMethod(
isolate, world, prototype_template, signature,
- symbol_keyed_iterator_configuration);
+ kSymbolKeyedIteratorConfiguration);
{% endfilter %}
{% endfilter %}
{% endif %}
@@ -760,8 +761,8 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesOnTemplate(
{##############################################################################}
{% block install_runtime_enabled %}
{% if needs_runtime_enabled_installer %}
-{% from 'attributes.cpp.tmpl' import accessor_configuration, attribute_configuration with context %}
-{% from 'methods.cpp.tmpl' import install_custom_signature with context %}
+{% from 'attributes.cc.tmpl' import accessor_configuration, attribute_configuration with context %}
+{% from 'methods.cc.tmpl' import install_custom_signature with context %}
{% if not is_partial %}
void {{v8_class}}::InstallRuntimeEnabledFeatures(
v8::Isolate* isolate,
@@ -792,7 +793,7 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesImpl(
#error "We don't expect a runtime enabled interface {{v8_class_or_partial}} to have InstallRuntimeEnabledFeatures()."
{% endif %}
- v8::Local<v8::FunctionTemplate> interface_template = {{v8_class}}::wrapperTypeInfo.domTemplate(isolate, world);
+ v8::Local<v8::FunctionTemplate> interface_template = {{v8_class}}::wrapper_type_info.DomTemplate(isolate, world);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
@@ -800,26 +801,25 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesImpl(
{% for feature_name, attrs in runtime_enabled_attributes | selectattr('is_data_type_property') | groupby('runtime_enabled_feature_name') %}
{% filter runtime_enabled(feature_name) %}
- static const V8DOMConfiguration::AttributeConfiguration attribute_configurations[] = {
+ static constexpr V8DOMConfiguration::AttributeConfiguration kConfigurations[] = {
{% for attribute in attrs | sort %}
{{attribute_configuration(attribute) | trim | indent(6)}},
{% endfor %}
};
V8DOMConfiguration::InstallAttributes(isolate, world, instance, prototype,
- attribute_configurations, base::size(attribute_configurations));
+ kConfigurations, base::size(kConfigurations));
{% endfilter %}
{% endfor %}
{% for feature_name, attrs in runtime_enabled_attributes | selectattr('is_data_type_property', 'equalto', False) | groupby('runtime_enabled_feature_name') %}
{% filter runtime_enabled(feature_name) %}
- static const V8DOMConfiguration::AccessorConfiguration accessor_configurations[] = {
+ static constexpr V8DOMConfiguration::AccessorConfiguration kConfigurations[] = {
{% for attribute in attrs | sort %}
{{accessor_configuration(attribute) | trim | indent(6)}},
{% endfor %}
};
V8DOMConfiguration::InstallAccessors(isolate, world, instance, prototype,
- interface, signature, accessor_configurations,
- base::size(accessor_configurations));
+ interface, signature, kConfigurations, base::size(kConfigurations));
{% endfilter %}
{% endfor %}
@@ -851,70 +851,88 @@ void {{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesImpl(
{% endblock %}
{##############################################################################}
{% block origin_trials %}
-{% from 'attributes.cpp.tmpl' import accessor_configuration,
+{% from 'attributes.cc.tmpl' import accessor_configuration,
attribute_configuration,
with context %}
-{% from 'constants.cpp.tmpl' import constant_configuration with context %}
-{% from 'methods.cpp.tmpl' import method_configuration with context %}
+{% from 'constants.cc.tmpl' import constant_configuration with context %}
+{% from 'methods.cc.tmpl' import method_configuration with context %}
{% for feature in optional_features %}
-void {{v8_class_or_partial}}::install{{feature.name}}(v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface) {
+void {{v8_class_or_partial}}::Install{{feature.name}}(
+ v8::Isolate* isolate,
+ const DOMWrapperWorld& world,
+ v8::Local<v8::Object> instance,
+ v8::Local<v8::Object> prototype,
+ v8::Local<v8::Function> interface) {
{% if feature.attributes or feature.methods %}
- v8::Local<v8::FunctionTemplate> interfaceTemplate = {{v8_class}}::wrapperTypeInfo.domTemplate(isolate, world);
- v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
+ v8::Local<v8::FunctionTemplate> interface_template =
+ {{v8_class}}::wrapper_type_info.DomTemplate(isolate, world);
+ v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
{% endif %}
{% if feature.needs_secure_context %}
- ExecutionContext* executionContext = ToExecutionContext(isolate->GetCurrentContext());
- bool isSecureContext = (executionContext && executionContext->IsSecureContext());
+ ExecutionContext* execution_context = ToExecutionContext(isolate->GetCurrentContext());
+ bool is_secure_context = (execution_context && execution_context->IsSecureContext());
{% endif %}{# needs secure context #}
{# Origin-Trial-enabled attributes #}
{% for attribute in feature.attributes %}
{% filter secure_context(attribute.secure_context_test) %}
{% if attribute.is_data_type_property %}
- static const V8DOMConfiguration::AttributeConfiguration attribute{{attribute.name}}Configuration[] = {
- {{attribute_configuration(attribute) | trim | indent(2)}}
+ static constexpr V8DOMConfiguration::AttributeConfiguration
+ k{{attribute.name}}Configurations[] = {
+ {{attribute_configuration(attribute) | trim | indent(4)}}
};
- for (const auto& attributeConfig : attribute{{attribute.name}}Configuration)
- V8DOMConfiguration::InstallAttribute(isolate, world, instance, prototype, attributeConfig);
+ for (const auto& config : k{{attribute.name}}Configurations)
+ V8DOMConfiguration::InstallAttribute(isolate, world, instance, prototype, config);
{% else %}
- static const V8DOMConfiguration::AccessorConfiguration accessor{{attribute.name}}Configuration[] = {
- {{accessor_configuration(attribute) | trim | indent(2)}}
+ static constexpr V8DOMConfiguration::AccessorConfiguration
+ k{{attribute.name}}Configurations[] = {
+ {{accessor_configuration(attribute) | trim | indent(4)}}
};
- for (const auto& accessorConfig : accessor{{attribute.name}}Configuration)
- V8DOMConfiguration::InstallAccessor(isolate, world, instance, prototype, interface, signature, accessorConfig);
+ for (const auto& config : k{{attribute.name}}Configurations) {
+ V8DOMConfiguration::InstallAccessor(isolate, world, instance, prototype,
+ interface, signature, config);
+ }
{% endif %}
{% endfilter %}{# secure_context #}
{% endfor %}
{# Origin-Trial-enabled constants #}
{% for constant in feature.constants %}
- {% set constant_name = constant.name.title().replace('_', '') %}
- const V8DOMConfiguration::ConstantConfiguration constant{{constant_name}}Configuration = {{constant_configuration(constant)}};
- V8DOMConfiguration::InstallConstant(isolate, interface, prototype, constant{{constant_name}}Configuration);
+ {% set constant_name = constant.camel_case_name %}
+ static constexpr V8DOMConfiguration::ConstantConfiguration
+ k{{constant_name}}Configuration = {{constant_configuration(constant)}};
+ V8DOMConfiguration::InstallConstant(
+ isolate, interface, prototype, k{{constant_name}}Configuration);
{% endfor %}
{# Origin-Trial-enabled methods (no overloads) #}
{% for method in feature.methods %}
{% filter secure_context(method.secure_context_test) %}
- {% set method_name = method.name.title().replace('_', '') %}
- static const V8DOMConfiguration::MethodConfiguration method{{method_name}}Configuration[] = {
- {{method_configuration(method) | trim | indent(2)}}
+ static constexpr V8DOMConfiguration::MethodConfiguration
+ k{{method.camel_case_name}}Configurations[] = {
+ {{method_configuration(method) | trim | indent(4)}}
};
- for (const auto& methodConfig : method{{method_name}}Configuration)
- V8DOMConfiguration::InstallMethod(isolate, world, instance, prototype, interface, signature, methodConfig);
+ for (const auto& config : k{{method.camel_case_name}}Configurations) {
+ V8DOMConfiguration::InstallMethod(
+ isolate, world, instance, prototype,
+ interface, signature, config);
+ }
{% endfilter %}{# secure_context #}
{% endfor %}
}
-void {{v8_class_or_partial}}::install{{feature.name}}(ScriptState* scriptState, v8::Local<v8::Object> instance) {
- V8PerContextData* perContextData = scriptState->PerContextData();
- v8::Local<v8::Object> prototype = perContextData->PrototypeForType(&{{v8_class}}::wrapperTypeInfo);
- v8::Local<v8::Function> interface = perContextData->ConstructorForType(&{{v8_class}}::wrapperTypeInfo);
+void {{v8_class_or_partial}}::Install{{feature.name}}(
+ ScriptState* script_state, v8::Local<v8::Object> instance) {
+ V8PerContextData* per_context_data = script_state->PerContextData();
+ v8::Local<v8::Object> prototype = per_context_data->PrototypeForType(
+ &{{v8_class}}::wrapper_type_info);
+ v8::Local<v8::Function> interface = per_context_data->ConstructorForType(
+ &{{v8_class}}::wrapper_type_info);
ALLOW_UNUSED_LOCAL(interface);
- install{{feature.name}}(scriptState->GetIsolate(), scriptState->World(), instance, prototype, interface);
+ Install{{feature.name}}(script_state->GetIsolate(), script_state->World(), instance, prototype, interface);
}
{% if not feature.needs_instance %}
-void {{v8_class_or_partial}}::install{{feature.name}}(ScriptState* scriptState) {
- install{{feature.name}}(scriptState, v8::Local<v8::Object>());
+void {{v8_class_or_partial}}::Install{{feature.name}}(ScriptState* script_state) {
+ Install{{feature.name}}(script_state, v8::Local<v8::Object>());
}
{% endif %}
@@ -929,34 +947,36 @@ void {{v8_class_or_partial}}::install{{feature.name}}(ScriptState* scriptState)
{% block native_value_traits %}{% endblock %}
{##############################################################################}
{% block install_conditional_features %}
-{% from 'attributes.cpp.tmpl' import install_conditional_attributes,
+{% from 'attributes.cc.tmpl' import install_conditional_attributes,
install_conditional_interface_objects with context %}
-{% from 'methods.cpp.tmpl' import install_conditional_methods with context %}
+{% from 'methods.cc.tmpl' import install_conditional_methods with context %}
{% if install_conditional_features_func %}
void {{v8_class_or_partial}}::InstallConditionalFeatures(
v8::Local<v8::Context> context,
const DOMWrapperWorld& world,
- v8::Local<v8::Object> instanceObject,
- v8::Local<v8::Object> prototypeObject,
- v8::Local<v8::Function> interfaceObject,
- v8::Local<v8::FunctionTemplate> interfaceTemplate) {
- CHECK(!interfaceTemplate.IsEmpty());
- DCHECK((!prototypeObject.IsEmpty() && !interfaceObject.IsEmpty()) ||
- !instanceObject.IsEmpty());
+ v8::Local<v8::Object> instance_object,
+ v8::Local<v8::Object> prototype_object,
+ v8::Local<v8::Function> interface_object,
+ v8::Local<v8::FunctionTemplate> interface_template) {
+ CHECK(!interface_template.IsEmpty());
+ DCHECK((!prototype_object.IsEmpty() && !interface_object.IsEmpty()) ||
+ !instance_object.IsEmpty());
{% if is_partial %}
{{v8_class}}::InstallConditionalFeatures(
- context, world, instanceObject, prototypeObject, interfaceObject, interfaceTemplate);
+ context, world, instance_object, prototype_object, interface_object, interface_template);
{% endif %}
v8::Isolate* isolate = context->GetIsolate();
{% if unscopables %}
- if (!prototypeObject.IsEmpty()) {
- v8::Local<v8::Name> unscopablesSymbol(v8::Symbol::GetUnscopables(isolate));
+ if (!prototype_object.IsEmpty()) {
+ v8::Local<v8::Name> unscopables_symbol(v8::Symbol::GetUnscopables(isolate));
v8::Local<v8::Object> unscopables;
bool has_unscopables;
- if (prototypeObject->HasOwnProperty(context, unscopablesSymbol).To(&has_unscopables) && has_unscopables) {
- unscopables = prototypeObject->Get(context, unscopablesSymbol).ToLocalChecked().As<v8::Object>();
+ if (prototype_object->HasOwnProperty(context, unscopables_symbol)
+ .To(&has_unscopables) && has_unscopables) {
+ unscopables = prototype_object->Get(context, unscopables_symbol)
+ .ToLocalChecked().As<v8::Object>();
} else {
// Web IDL 3.6.3. Interface prototype object
// https://heycam.github.io/webidl/#create-an-interface-prototype-object
@@ -972,24 +992,25 @@ void {{v8_class_or_partial}}::InstallConditionalFeatures(
.FromJust();
{% endfilter %}
{% endfor %}
- prototypeObject->CreateDataProperty(context, unscopablesSymbol, unscopables).FromJust();
+ prototype_object->CreateDataProperty(
+ context, unscopables_symbol, unscopables).FromJust();
}
{% endif %}{# unscopables #}
{% if conditional_attributes or conditional_methods %}
- v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
+ v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
{% endif %}
{% if conditional_attributes or conditional_methods or conditional_interface_objects %}
- ExecutionContext* executionContext = ToExecutionContext(context);
- DCHECK(executionContext);
+ ExecutionContext* execution_context = ToExecutionContext(context);
+ DCHECK(execution_context);
{% if has_conditional_secure_attributes or has_conditional_secure_methods %}
- bool isSecureContext = (executionContext && executionContext->IsSecureContext());
+ bool is_secure_context = (execution_context && execution_context->IsSecureContext());
{% endif %}
{% set attributes_on_instance = conditional_attributes | selectattr('on_instance') | list %}
{% set methods_on_instance = conditional_methods | selectattr('on_instance') | list %}
{% if attributes_on_instance or conditional_interface_objects or methods_on_instance %}
- if (!instanceObject.IsEmpty()) {
+ if (!instance_object.IsEmpty()) {
{{install_conditional_attributes(attributes_on_instance) | trim | indent(4)}}
{{install_conditional_interface_objects(conditional_interface_objects) | trim | indent(4)}}
{{install_conditional_methods(methods_on_instance) | trim | indent(4)}}
@@ -1001,7 +1022,7 @@ void {{v8_class_or_partial}}::InstallConditionalFeatures(
{% set methods_on_prototype = conditional_methods | selectattr('on_prototype') | list %}
{% set methods_on_interface = conditional_methods | selectattr('on_interface') | list %}
{% if attributes_on_prototype or attributes_on_interface or methods_on_prototype or methods_on_interface %}
- if (!prototypeObject.IsEmpty() || !interfaceObject.IsEmpty()) {
+ if (!prototype_object.IsEmpty() || !interface_object.IsEmpty()) {
{{install_conditional_attributes(attributes_on_prototype + attributes_on_interface) | trim | indent(4)}}
{{install_conditional_methods(methods_on_prototype + methods_on_interface) | trim | indent(4)}}
}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/methods.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/methods.cc.tmpl
index b0e5543c154..f524655e74d 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/methods.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/methods.cc.tmpl
@@ -1,4 +1,4 @@
-{% from 'utilities.cpp.tmpl' import declare_enum_validation_variable, v8_value_to_local_cpp_value %}
+{% from 'utilities.cc.tmpl' import declare_enum_validation_variable, v8_value_to_local_cpp_value %}
{##############################################################################}
{% macro runtime_timer_scope(counter) %}
@@ -10,21 +10,21 @@ RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "{{counter}}");
{% endmacro %}
{% macro generate_method(method, world_suffix) %}
-static void {{method.name}}{{method.overload_index}}Method{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
+static void {{method.camel_case_name}}{{method.overload_index}}Method{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
{% filter format_remove_duplicates([
- 'ExceptionState exceptionState',
- 'ScriptState* scriptState = ']) %}
+ 'ExceptionState exception_state',
+ 'ScriptState* script_state = ']) %}
{% set define_exception_state -%}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "{{interface_name}}", "{{method.name}}");
+ ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "{{interface_name}}", "{{method.name}}");
{%- endset %}
{% set function_call = func_call_with_prep_of_args(method, world_suffix) %}
- {% if 'exceptionState' in function_call or
+ {% if 'exception_state' in function_call or
(method.returns_promise and not method.is_static) %}
{{define_exception_state}}
{% if method.returns_promise %}
- ExceptionToRejectPromiseScope rejectPromiseScope(info, exceptionState);
+ ExceptionToRejectPromiseScope reject_promise_scope(info, exception_state);
{% endif %}
{% endif %}
{% if method.is_ce_reactions %}
@@ -35,7 +35,7 @@ static void {{method.name}}{{method.overload_index}}Method{{world_suffix}}(const
{% if method.returns_promise %}
// V8DOMConfiguration::kDoNotCheckHolder
// Make sure that info.Holder() really points to an instance of the type.
- if (!{{v8_class}}::hasInstance(info.Holder(), info.GetIsolate())) {
+ if (!{{v8_class}}::HasInstance(info.Holder(), info.GetIsolate())) {
{{throw_type_error(method, '"Illegal invocation"')}}
return;
}
@@ -53,24 +53,26 @@ static void {{method.name}}{{method.overload_index}}Method{{world_suffix}}(const
{# Security checks #}
{% if method.is_check_security_for_return_value %}
{{define_exception_state}}
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), {{method.cpp_value}}, BindingSecurity::ErrorReportOption::kDoNotReport)) {
+ if (!BindingSecurity::ShouldAllowAccessTo(
+ CurrentDOMWindow(info.GetIsolate()), {{method.cpp_value}},
+ BindingSecurity::ErrorReportOption::kDoNotReport)) {
UseCounter::Count(CurrentExecutionContext(info.GetIsolate()),
- WebFeature::kCrossOrigin{{interface_name}}{{method.name|blink_capitalize}});
+ WebFeature::kCrossOrigin{{interface_name}}{{method.camel_case_name}});
V8SetReturnValueNull(info);
return;
}
{% endif %}
- {% if 'scriptState' in function_call %}
+ {% if 'script_state' in function_call %}
{% if method.is_static %}
- ScriptState* scriptState = ScriptState::ForCurrentRealm(info);
+ ScriptState* script_state = ScriptState::ForCurrentRealm(info);
{% else %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
{% endif %}
{% if method.is_custom_element_callbacks %}
- V0CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
+ V0CustomElementProcessingStack::CallbackDeliveryScope delivery_scope;
{% endif %}
{{function_call | trim | indent(2)}}
@@ -105,17 +107,17 @@ if (UNLIKELY(info.Length() < {{method.number_of_required_arguments}})) {
{% endif %}
{% for argument in method.arguments %}
-{{argument.cpp_type}} {{argument.name}};
+{{argument.cpp_type}} {{argument.local_cpp_variable}};
{% endfor %}
{% if method.has_optional_argument_without_default_value %}
{# Count the effective number of arguments. (arg1, arg2, undefined) is
interpreted as two arguments are passed and (arg1, undefined, arg3) is
interpreted as three arguments are passed. #}
-int numArgsPassed = info.Length();
-while (numArgsPassed > 0) {
- if (!info[numArgsPassed - 1]->IsUndefined())
+int num_args_passed = info.Length();
+while (num_args_passed > 0) {
+ if (!info[num_args_passed - 1]->IsUndefined())
break;
- --numArgsPassed;
+ --num_args_passed;
}
{% endif %}
{% for argument in method.arguments %}
@@ -140,7 +142,7 @@ if (!info[{{argument.index}}]->IsUndefined()) {
{# Optional arguments without a default value generate an early call with
fewer arguments if they are omitted.
Optional Dictionary arguments default to empty dictionary. #}
-if (UNLIKELY(numArgsPassed <= {{argument.index}})) {
+if (UNLIKELY(num_args_passed <= {{argument.index}})) {
{% if world_suffix %}
{{cpp_method_call(method, argument.v8_set_return_value_for_main_world, argument.cpp_value) | trim | indent(2)}}
{% else %}
@@ -158,7 +160,7 @@ if (info[{{argument.index}}]->IsNullOrUndefined()) {
// TODO(crbug.com/886588): Remove the following special casing.
if (info[{{argument.index}}].As<v8::Object>()->CreationContext().IsEmpty()) {
{{define_exception_state}}
- exceptionState.ThrowSecurityError("The callback provided as parameter {{argument.index + 1}} is a cross origin object.");
+ exception_state.ThrowSecurityError("The callback provided as parameter {{argument.index + 1}} is a cross origin object.");
return;
}
} else {
@@ -166,24 +168,24 @@ if (info[{{argument.index}}]->IsNullOrUndefined()) {
return;
}
{% if method.name == 'removeEventListener' or method.name == 'removeListener' %}
-{{argument.name}} = V8EventListenerHelper::GetEventListener(ScriptState::Current(info.GetIsolate()), info[{{argument.index}}], kListenerFindOnly);
+{{argument.local_cpp_variable}} = V8EventListenerHelper::GetEventListener(ScriptState::Current(info.GetIsolate()), info[{{argument.index}}], kListenerFindOnly);
{% else %}{# method.name == 'AddEventListener' #}
-{{argument.name}} = V8EventListenerHelper::GetEventListener(ScriptState::Current(info.GetIsolate()), info[{{argument.index}}], kListenerFindOrCreate);
+{{argument.local_cpp_variable}} = V8EventListenerHelper::GetEventListener(ScriptState::Current(info.GetIsolate()), info[{{argument.index}}], kListenerFindOrCreate);
{% endif %}{# method.name #}
{% else %}{# argument.idl_type == 'EventListener' #}
if (info[{{argument.index}}]->IsObject()) {
- {{argument.name}} = V8{{argument.idl_type}}::CreateOrNull(info[{{argument.index}}].As<v8::Object>());
- if (!{{argument.name}}) {
+ {{argument.local_cpp_variable}} = V8{{argument.idl_type}}::CreateOrNull(info[{{argument.index}}].As<v8::Object>());
+ if (!{{argument.local_cpp_variable}}) {
{{define_exception_state}}
- exceptionState.ThrowSecurityError("The callback provided as parameter {{argument.index + 1}} is a cross origin object.");
+ exception_state.ThrowSecurityError("The callback provided as parameter {{argument.index + 1}} is a cross origin object.");
return;
}
{% if argument.is_nullable %}
} else if (info[{{argument.index}}]->IsNullOrUndefined()) {
- {{argument.name}} = nullptr;
+ {{argument.local_cpp_variable}} = nullptr;
{% elif argument.is_optional %}
} else if (info[{{argument.index}}]->IsUndefined()) {
- {{argument.name}} = nullptr;
+ {{argument.local_cpp_variable}} = nullptr;
{% endif %}
} else {
{{throw_argument_error(method, argument, "The callback provided as parameter %(index)d is not an object.")}}
@@ -195,10 +197,10 @@ if (info[{{argument.index}}]->IsFunction()) {
{{v8_value_to_local_cpp_value(argument)}}
{% if argument.is_nullable %}
} else if (info[{{argument.index}}]->IsNullOrUndefined()) {
- {{argument.name}} = nullptr;
+ {{argument.local_cpp_variable}} = nullptr;
{% elif argument.is_optional %}
} else if (info[{{argument.index}}]->IsUndefined()) {
- {{argument.name}} = nullptr;
+ {{argument.local_cpp_variable}} = nullptr;
{% endif %}
} else {
{{throw_argument_error(method, argument, "The callback provided as parameter %(index)d is not a function.")}}
@@ -206,11 +208,11 @@ if (info[{{argument.index}}]->IsFunction()) {
}
{% elif argument.is_variadic_wrapper_type %}
for (int i = {{argument.index}}; i < info.Length(); ++i) {
- if (!V8{{argument.idl_type}}::hasInstance(info[i], info.GetIsolate())) {
+ if (!V8{{argument.idl_type}}::HasInstance(info[i], info.GetIsolate())) {
{{throw_argument_error(method, argument, "parameter %(index)d is not of type '%(type)s'.")}}
return;
}
- {{argument.name}}.push_back(V8{{argument.idl_type}}::ToImpl(v8::Local<v8::Object>::Cast(info[i])));
+ {{argument.local_cpp_variable}}.push_back(V8{{argument.idl_type}}::ToImpl(v8::Local<v8::Object>::Cast(info[i])));
}
{% elif argument.is_dictionary %}
{% if not argument.use_permissive_dictionary_conversion %}
@@ -231,10 +233,10 @@ if (info[{{argument.index}}]->IsObject()) {
{{v8_value_to_local_cpp_value(argument)}}
{% if argument.is_nullable %}
} else if (info[{{argument.index}}]->IsNullOrUndefined()) {
- {{argument.name}} = ScriptValue(ScriptState::Current(info.GetIsolate()), v8::Null(info.GetIsolate()));
+ {{argument.local_cpp_variable}} = ScriptValue(ScriptState::Current(info.GetIsolate()), v8::Null(info.GetIsolate()));
{% elif argument.is_optional %}
} else if (info[{{argument.index}}]->IsUndefined()) {
- {{argument.name}} = ScriptValue(ScriptState::Current(info.GetIsolate()), v8::Undefined(info.GetIsolate()));
+ {{argument.local_cpp_variable}} = ScriptValue(ScriptState::Current(info.GetIsolate()), v8::Undefined(info.GetIsolate()));
{% endif %}
} else {
{{throw_argument_error(method, argument, "parameter %(index)d ('%(name)s') is not an object.")}}
@@ -250,21 +252,21 @@ if (info[{{argument.index}}]->IsObject()) {
throw a TypeError), per http://www.w3.org/TR/WebIDL/#es-interface
Note: for variadic arguments, the type checking is done for each matched
argument instead; see argument.is_variadic_wrapper_type code-path above. #}
-if (!{{argument.name}}{% if argument.is_nullable %} && !IsUndefinedOrNull(info[{{argument.index}}]){% endif %}) {
+if (!{{argument.local_cpp_variable}}{% if argument.is_nullable %} && !IsUndefinedOrNull(info[{{argument.index}}]){% endif %}) {
{{throw_argument_error(method, argument, "parameter %(index)d is not of type '%(type)s'.")}}
return;
}
{% elif argument.enum_values %}
{# Invalid enum values: http://www.w3.org/TR/WebIDL/#idl-enums #}
-{% set enum_variable = 'valid' + argument.name[0].upper() + argument.name[1:] + 'Values' %}
+{% set enum_variable = 'kValid' + argument.name[0].upper() + argument.name[1:] + 'Values' %}
{{declare_enum_validation_variable(argument.enum_values, enum_variable)}}
-if (!IsValidEnum({{argument.name}}, {{enum_variable}}, base::size({{enum_variable}}), "{{argument.enum_type}}", exceptionState)) {
+if (!IsValidEnum({{argument.local_cpp_variable}}, {{enum_variable}}, base::size({{enum_variable}}), "{{argument.enum_type}}", exception_state)) {
return;
}
{% elif argument.idl_type == 'Promise' %}
{# We require this for our implementation of promises, though not in spec:
http://heycam.github.io/webidl/#es-promise #}
-if (!{{argument.name}}.IsUndefinedOrNull() && !{{argument.name}}.IsObject()) {
+if (!{{argument.local_cpp_variable}}.IsUndefinedOrNull() && !{{argument.local_cpp_variable}}.IsObject()) {
{{throw_argument_error(method, argument, "parameter %(index)d ('%(name)s') is not an object.")}}
return;
}
@@ -275,23 +277,23 @@ if (!{{argument.name}}.IsUndefinedOrNull() && !{{argument.name}}.IsObject()) {
{######################################}
{% macro cpp_method_call(method, v8_set_return_value, cpp_value) %}
{% if method.is_custom_call_prologue %}
-{{v8_class}}::{{method.name}}MethodPrologueCustom(info, impl);
+{{v8_class}}::{{method.camel_case_name}}MethodPrologueCustom(info, impl);
{% endif %}
{# Local variables #}
{% if method.is_call_with_execution_context %}
{# [ConstructorCallWith=ExecutionContext] or [CallWith=ExecutionContext] #}
{% if method.is_constructor %}
-ExecutionContext* executionContext = ToExecutionContext(
+ExecutionContext* execution_context = ToExecutionContext(
info.NewTarget().As<v8::Object>()->CreationContext());
{% elif method.is_static %}
-ExecutionContext* executionContext = ExecutionContext::ForCurrentRealm(info);
+ExecutionContext* execution_context = ExecutionContext::ForCurrentRealm(info);
{% else %}
-ExecutionContext* executionContext = ExecutionContext::ForRelevantRealm(info);
+ExecutionContext* execution_context = ExecutionContext::ForRelevantRealm(info);
{% endif %}
{% endif %}
{% if method.is_call_with_script_arguments %}
{# [CallWith=ScriptArguments] #}
-ScriptArguments* scriptArguments(ScriptArguments::Create(scriptState, info, {{method.number_of_arguments}}));
+ScriptArguments* scriptArguments(ScriptArguments::Create(script_state, info, {{method.number_of_arguments}}));
{% endif %}
{% if method.is_call_with_document %}
{# [ConstructorCallWith=Document] #}
@@ -311,7 +313,7 @@ Document& document = *To<Document>(ToExecutionContext(
{% endif %}
{# Post-call #}
{% if method.is_raises_exception %}
-if (exceptionState.HadException()) {
+if (exception_state.HadException()) {
return;
}
{% endif %}
@@ -339,7 +341,7 @@ else
{% endif %}
{%- endif %}{# None for void #}
{% if method.is_custom_call_epilogue %}
-{{v8_class}}::{{method.name}}MethodEpilogueCustom(info, impl);
+{{v8_class}}::{{method.camel_case_name}}MethodEpilogueCustom(info, impl);
{% endif %}
{% endmacro %}
@@ -347,7 +349,7 @@ else
{##############################################################################}
{% macro throw_type_error(method, error_message) %}
{% if method.has_exception_state or method.returns_promise %}
-exceptionState.ThrowTypeError({{error_message}});
+exception_state.ThrowTypeError({{error_message}});
{%- elif method.is_constructor %}
V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToConstruct("{{interface_name}}", {{error_message}}));
{%- else %}
@@ -365,7 +367,7 @@ V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToE
{##############################################################################}
{% macro runtime_determined_length_method(overloads) %}
-static int {{overloads.name}}MethodLength() {
+static int {{overloads.camel_case_name}}MethodLength() {
{% for length, runtime_enabled_features in overloads.runtime_determined_lengths %}
{% for runtime_enabled_feature in runtime_enabled_features %}
{% filter runtime_enabled(runtime_enabled_feature) %}
@@ -379,7 +381,7 @@ static int {{overloads.name}}MethodLength() {
{##############################################################################}
{% macro runtime_determined_maxarg_method(overloads) %}
-static int {{overloads.name}}MethodMaxArg() {
+static int {{overloads.camel_case_name}}MethodMaxArg() {
{% for length, runtime_enabled_features in overloads.runtime_determined_maxargs %}
{% for name in runtime_enabled_features %}
{% filter runtime_enabled(name) %}
@@ -393,7 +395,7 @@ static int {{overloads.name}}MethodMaxArg() {
{##############################################################################}
{% macro overload_resolution_method(overloads, world_suffix) %}
-static void {{overloads.name}}Method{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
+static void {{overloads.camel_case_name}}Method{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
{% set fall_through_to_partial_overloads = not is_partial and overloads.has_partial_overloads %}
{% if overloads.measure_all_as %}
@@ -405,7 +407,7 @@ static void {{overloads.name}}Method{{world_suffix}}(const v8::FunctionCallbackI
{# First resolve by length #}
{% if not fall_through_to_partial_overloads %}
- bool isArityError = false;
+ bool is_arity_error = false;
{% endif %}
{# This follows the overload resolution algorithm. #}
@@ -420,19 +422,19 @@ static void {{overloads.name}}Method{{world_suffix}}(const v8::FunctionCallbackI
{% for test, method in tests_methods %}
{% if method.visible %}
{% filter runtime_enabled(not overloads.runtime_enabled_all and method.runtime_enabled_feature_name) %}
- {% if "exceptionState" in test %}
+ {% if "exception_state" in test %}
{
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext,
+ ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext,
"{{interface_name}}", "{{overloads.name}}");
{{ test_and_call_overloaded_method(test, method, overloads, world_suffix) | trim | indent(8) }}
- if (exceptionState.HadException()) {
- exceptionState.RethrowV8Exception(exceptionState.GetException());
+ if (exception_state.HadException()) {
+ exception_state.RethrowV8Exception(exception_state.GetException());
return;
}
}
- {% else %}{# exceptionState #}
+ {% else %}{# exception_state #}
{{ test_and_call_overloaded_method(test, method, overloads, world_suffix) | trim | indent(6) }}
- {% endif %}{# exceptionState #}
+ {% endif %}{# exception_state #}
{% endfilter %}
{% endif %}
{% endfor %}
@@ -441,7 +443,7 @@ static void {{overloads.name}}Method{{world_suffix}}(const v8::FunctionCallbackI
{% if not fall_through_to_partial_overloads %}
default:
{# 12.19. Otherwise: throw a TypeError. #}
- isArityError = true;
+ is_arity_error = true;
{% endif %}
}
@@ -449,25 +451,25 @@ static void {{overloads.name}}Method{{world_suffix}}(const v8::FunctionCallbackI
DCHECK({{overloads.name}}MethodForPartialInterface);
({{overloads.name}}MethodForPartialInterface)(info);
{% else %}{# fall_through_to_partial_overloads #}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "{{interface_name}}", "{{overloads.name}}");
+ ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "{{interface_name}}", "{{overloads.name}}");
{% if overloads.returns_promise_all %}
- ExceptionToRejectPromiseScope rejectPromiseScope(info, exceptionState);
+ ExceptionToRejectPromiseScope reject_promise_scope(info, exception_state);
{% endif %}
- if (isArityError) {
+ if (is_arity_error) {
{% if overloads.length != 0 %}
if (info.Length() < {{overloads.length}}) {
- exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments({{overloads.length}}, info.Length()));
+ exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments({{overloads.length}}, info.Length()));
return;
}
{% endif %}
{% if overloads.valid_arities %}
if (info.Length() >= {{overloads.length}}) {
- exceptionState.ThrowTypeError(ExceptionMessages::InvalidArity("{{overloads.valid_arities}}", info.Length()));
+ exception_state.ThrowTypeError(ExceptionMessages::InvalidArity("{{overloads.valid_arities}}", info.Length()));
return;
}
{% endif %}
}
- exceptionState.ThrowTypeError("No function was found that matched the signature provided.");
+ exception_state.ThrowTypeError("No function was found that matched the signature provided.");
{% endif %}{# fall_through_to_partial_overloads #}
}
{% endmacro %}
@@ -480,7 +482,7 @@ if ({{test}}) {
{% if method.deprecate_as and not overloads.deprecate_all_as %}
Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), WebFeature::k{{method.deprecate_as}});
{% endif %}
- {{method.name}}{{method.overload_index}}Method{{world_suffix}}(info);
+ {{method.camel_case_name}}{{method.overload_index}}Method{{world_suffix}}(info);
return;
}
{% endmacro %}
@@ -489,7 +491,7 @@ if ({{test}}) {
{##############################################################################}
{% macro method_callback(method, world_suffix) %}
-void {{v8_class_or_partial}}::{{method.name}}MethodCallback{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::{{method.camel_case_name}}MethodCallback{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
{% if method.runtime_call_stats.extended_attribute_defined %}
{{ runtime_timer_scope(method.runtime_call_stats.method_counter) | trim | indent(2) }}
{% else %}
@@ -505,19 +507,19 @@ void {{v8_class_or_partial}}::{{method.name}}MethodCallback{{world_suffix}}(cons
{% endif %}{# not method.overloads #}
{% if world_suffix in method.activity_logging_world_list %}
{% if method.is_static %}
- ScriptState* scriptState = ScriptState::ForCurrentRealm(info);
+ ScriptState* script_state = ScriptState::ForCurrentRealm(info);
{% else %}
- ScriptState* scriptState = ScriptState::ForRelevantRealm(info);
+ ScriptState* script_state = ScriptState::ForRelevantRealm(info);
{% endif %}
- V8PerContextData* contextData = scriptState->PerContextData();
- if (contextData && contextData->ActivityLogger()) {
- contextData->ActivityLogger()->LogMethod("{{interface_name}}.{{method.name}}", info);
+ V8PerContextData* context_data = script_state->PerContextData();
+ if (context_data && context_data->ActivityLogger()) {
+ context_data->ActivityLogger()->LogMethod("{{interface_name}}.{{method.name}}", info);
}
{% endif %}
{% if method.is_custom %}
- {{v8_class}}::{{method.name}}MethodCustom(info);
+ {{v8_class}}::{{method.camel_case_name}}MethodCustom(info);
{% else %}
- {{cpp_class_or_partial}}V8Internal::{{method.name}}Method{{world_suffix}}(info);
+ {{internal_namespace}}::{{method.camel_case_name}}Method{{world_suffix}}(info);
{% endif %}
}
{% endmacro %}
@@ -528,39 +530,50 @@ void {{v8_class_or_partial}}::{{method.name}}MethodCallback{{world_suffix}}(cons
{# TODO(dcheng): Currently, bindings must create a function object for each
realm as a hack to support the incumbent realm. Clean this up when Blink
properly supports the incumbent realm. #}
-static void {{method.name}}OriginSafeMethodGetter{{world_suffix}}(const v8::PropertyCallbackInfo<v8::Value>& info) {
- static int domTemplateKey; // This address is used for a key to look up the dom template.
+static void {{method.camel_case_name}}OriginSafeMethodGetter{{world_suffix}}(const v8::PropertyCallbackInfo<v8::Value>& info) {
+ static int dom_template_key; // This address is used for a key to look up the dom template.
V8PerIsolateData* data = V8PerIsolateData::From(info.GetIsolate());
const DOMWrapperWorld& world = DOMWrapperWorld::World(info.GetIsolate()->GetCurrentContext());
- v8::Local<v8::FunctionTemplate> interfaceTemplate = data->FindInterfaceTemplate(world, &{{v8_class}}::wrapperTypeInfo);
- v8::Local<v8::Signature> signature = v8::Signature::New(info.GetIsolate(), interfaceTemplate);
-
- v8::Local<v8::FunctionTemplate> methodTemplate = data->FindOrCreateOperationTemplate(world, &domTemplateKey, {{v8_class_or_partial}}::{{method.name}}MethodCallback{{world_suffix}}, V8Undefined(), signature, {{method.length}});
+ v8::Local<v8::FunctionTemplate> interface_template =
+ data->FindInterfaceTemplate(world, &{{v8_class}}::wrapper_type_info);
+ v8::Local<v8::Signature> signature = v8::Signature::New(info.GetIsolate(), interface_template);
+
+ v8::Local<v8::FunctionTemplate> method_template =
+ data->FindOrCreateOperationTemplate(
+ world,
+ &dom_template_key,
+ {{v8_class_or_partial}}::{{method.camel_case_name}}MethodCallback{{world_suffix}},
+ v8::Local<v8::Value>(),
+ signature,
+ {{method.length}});
// Return the function by default, unless the user script has overwritten it.
- V8SetReturnValue(info, methodTemplate->GetFunction(info.GetIsolate()->GetCurrentContext()).ToLocalChecked());
+ V8SetReturnValue(info, method_template->GetFunction(info.GetIsolate()->GetCurrentContext())
+ .ToLocalChecked());
{{cpp_class}}* impl = {{v8_class}}::ToImpl(info.Holder());
- if (!BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(info.GetIsolate()), impl, BindingSecurity::ErrorReportOption::kDoNotReport)) {
+ if (!BindingSecurity::ShouldAllowAccessTo(
+ CurrentDOMWindow(info.GetIsolate()), impl,
+ BindingSecurity::ErrorReportOption::kDoNotReport)) {
return;
}
{% raw %}
// {{method.name}} must be same with |methodName| (=name) in
- // {{cpp_class}}OriginSafeMethodSetter defined in interface.cpp.tmpl.
+ // {{cpp_class}}OriginSafeMethodSetter defined in interface.cc.tmpl.
{% endraw %}
- V8PrivateProperty::Symbol propertySymbol =
+ V8PrivateProperty::Symbol property_symbol =
V8PrivateProperty::GetSymbol(info.GetIsolate(), "{{method.name}}");
v8::Local<v8::Object> holder = v8::Local<v8::Object>::Cast(info.Holder());
- if (propertySymbol.HasValue(holder)) {
- V8SetReturnValue(info, propertySymbol.GetOrUndefined(holder));
+ if (property_symbol.HasValue(holder)) {
+ V8SetReturnValue(info, property_symbol.GetOrUndefined(holder));
}
}
{% endmacro %}
{% macro origin_safe_method_getter_callback(method, world_suffix) %}
-void {{v8_class_or_partial}}::{{method.name}}OriginSafeMethodGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) {
+void {{v8_class_or_partial}}::{{method.camel_case_name}}OriginSafeMethodGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(method.runtime_call_stats.origin_safe_method_getter_counter) }}
- {{cpp_class}}V8Internal::{{method.name}}OriginSafeMethodGetter{{world_suffix}}(info);
+ {{internal_namespace}}::{{method.camel_case_name}}OriginSafeMethodGetter{{world_suffix}}(info);
}
{% endmacro %}
@@ -569,7 +582,7 @@ void {{v8_class_or_partial}}::{{method.name}}OriginSafeMethodGetterCallback{{wor
{% macro generate_constructor(constructor) %}
{% set name = '%sConstructorCallback' % v8_class
if constructor.is_named_constructor else
- 'constructor%s' % (constructor.overload_index or '') %}
+ 'Constructor%s' % (constructor.overload_index or '') %}
static void {{name}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
{{ runtime_timer_scope_disabled_by_default(constructor.rcs_counter) }}
{% set function_call = func_call_with_prep_of_args(constructor) %}
@@ -586,11 +599,11 @@ static void {{name}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
}
{% endif %}
- {% if 'exceptionState' in function_call %}
- ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kConstructionContext, "{{interface_name}}");
+ {% if 'exception_state' in function_call %}
+ ExceptionState exception_state(info.GetIsolate(), ExceptionState::kConstructionContext, "{{interface_name}}");
{% endif %}
- {% if 'scriptState' in function_call %}
- ScriptState* scriptState = ScriptState::From(
+ {% if 'script_state' in function_call %}
+ ScriptState* script_state = ScriptState::From(
info.NewTarget().As<v8::Object>()->CreationContext());
{% endif %}
@@ -605,18 +618,18 @@ static void {{name}}(const v8::FunctionCallbackInfo<v8::Value>& info) {
if constructor.is_named_constructor else
'') %}
v8::Local<v8::Object> wrapper = info.Holder();
-wrapper = impl->AssociateWithWrapper(info.GetIsolate(), &{{constructor_class}}::wrapperTypeInfo, wrapper);
+wrapper = impl->AssociateWithWrapper(info.GetIsolate(), &{{constructor_class}}::wrapper_type_info, wrapper);
V8SetReturnValue(info, wrapper);
{% endmacro %}
{##############################################################################}
{% macro method_configuration(method) %}
-{% from 'utilities.cpp.tmpl' import property_location %}
+{% from 'utilities.cc.tmpl' import property_location %}
{% set method_callback =
- '%s::%sMethodCallback' % (v8_class_or_partial, method.name) %}
+ '%s::%sMethodCallback' % (v8_class_or_partial, method.camel_case_name) %}
{% set method_callback_for_main_world =
- '%s::%sMethodCallbackForMainWorld' % (v8_class_or_partial, method.name)
+ '%s::%sMethodCallbackForMainWorld' % (v8_class_or_partial, method.camel_case_name)
if method.is_per_world_bindings else 'nullptr' %}
{% set property_attribute =
'static_cast<v8::PropertyAttribute>(%s)' % ' | '.join(method.property_attributes)
@@ -627,7 +640,7 @@ V8SetReturnValue(info, wrapper);
if method.is_check_security_for_receiver else 'V8DOMConfiguration::kDoNotCheckAccess' %}
{% if method.is_per_world_bindings %}
{% set method_callback_for_main_world =
- '%s::%sMethodCallbackForMainWorld' % (v8_class_or_partial, method.name) %}
+ '%s::%sMethodCallbackForMainWorld' % (v8_class_or_partial, method.camel_case_name) %}
{"{{method.name}}", {{method_callback_for_main_world}}, {{method.length}}, {{property_attribute}}, {{property_location(method)}}, {{holder_check}}, {{access_check}}, {{method.side_effect_type}}, V8DOMConfiguration::kMainWorld},
{"{{method.name}}", {{method_callback}}, {{method.length}}, {{property_attribute}}, {{property_location(method)}}, {{holder_check}}, {{access_check}}, {{method.side_effect_type}}, V8DOMConfiguration::kNonMainWorlds}
{%- else %}
@@ -638,11 +651,17 @@ V8SetReturnValue(info, wrapper);
{######################################}
{% macro install_custom_signature(method, instance_template, prototype_template, interface_template, signature) %}
-const V8DOMConfiguration::MethodConfiguration {{method.name}}MethodConfiguration[] = {
- {{method_configuration(method) | trim | indent(2)}}
-};
-for (const auto& methodConfig : {{method.name}}MethodConfiguration)
- V8DOMConfiguration::InstallMethod(isolate, world, {{instance_template}}, {{prototype_template}}, {{interface_template}}, {{signature}}, methodConfig);
+{
+ // Install {{method.name}} configuration
+ constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
+ {{method_configuration(method) | trim | indent(4)}}
+ };
+ for (const auto& config : kConfigurations) {
+ V8DOMConfiguration::InstallMethod(
+ isolate, world, {{instance_template}}, {{prototype_template}},
+ {{interface_template}}, {{signature}}, config);
+ }
+}
{%- endmacro %}
@@ -658,11 +677,17 @@ for (const auto& methodConfig : {{method.name}}MethodConfiguration)
{% filter runtime_enabled(method.overloads.runtime_enabled_all
if method.overloads else
method.runtime_enabled_feature_name) %}
-const V8DOMConfiguration::MethodConfiguration {{method.name}}MethodConfiguration[] = {
- {{method_configuration(method) | trim | indent(2)}}
-};
-for (const auto& methodConfig : {{method.name}}MethodConfiguration)
- V8DOMConfiguration::InstallMethod(isolate, world, instanceObject, prototypeObject, interfaceObject, signature, methodConfig);
+{
+ // Install {{method.name}} configuration
+ const V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
+ {{method_configuration(method) | trim | indent(4)}}
+ };
+ for (const auto& config : kConfigurations) {
+ V8DOMConfiguration::InstallMethod(
+ isolate, world, instance_object, prototype_object,
+ interface_object, signature, config);
+ }
+}
{% endfilter %}{# runtime_enabled() #}
{% endfilter %}{# exposed() #}
{% endfilter %}{# secure_context() #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl
index b4f19116fd0..8646c398535 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl
@@ -31,21 +31,21 @@ void InstallOriginTrialFeaturesForCore(
const DOMWrapperWorld& world = script_state->World();
// TODO(iclelland): Unify ContextFeatureSettings with the rest of the
// conditional features.
- if (wrapper_type_info == &V8Window::wrapperTypeInfo) {
+ if (wrapper_type_info == &V8Window::wrapper_type_info) {
auto* settings = ContextFeatureSettings::From(
execution_context,
ContextFeatureSettings::CreationMode::kDontCreateIfNotExists);
if (settings && settings->isMojoJSEnabled()) {
v8::Local<v8::Object> instance_object =
script_state->GetContext()->Global();
- V8Window::installMojoJS(isolate, world, instance_object, prototype_object,
+ V8Window::InstallMojoJS(isolate, world, instance_object, prototype_object,
interface_object);
}
}
// TODO(iclelland): Extract this common code out of OriginTrialFeaturesForCore
// and OriginTrialFeaturesForModules into a block.
{% for interface in installers_by_interface %}
- if (wrapper_type_info == &{{interface.v8_class}}::wrapperTypeInfo) {
+ if (wrapper_type_info == &{{interface.v8_class}}::wrapper_type_info) {
{% if interface.is_global %}
v8::Local<v8::Object> instance_object =
script_state->GetContext()->Global();
@@ -81,7 +81,7 @@ void InstallPendingOriginTrialFeatureForCore(const String& feature,
v8::Local<v8::Object>(), v8::Local<v8::Function>());
{% else %}
if (context_data->GetExistingConstructorAndPrototypeForType(
- &{{installer.v8_class}}::wrapperTypeInfo, &prototype_object, &interface_object)) {
+ &{{installer.v8_class}}::wrapper_type_info, &prototype_object, &interface_object)) {
{{installer.v8_class_or_partial}}::{{installer.install_method}}(
isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object);
}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.h.tmpl
index 6aad7fe0aaf..a4963503470 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.h.tmpl
@@ -1,9 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-
-#ifndef BLINK_BINDINGS_CORE_V8_ORIGIN_TRIAL_FEATURES_FOR_CORE_H_
-#define BLINK_BINDINGS_CORE_V8_ORIGIN_TRIAL_FEATURES_FOR_CORE_H_
+#ifndef THIRD_PARTY_BLINK_BINDINGS_CORE_V8_ORIGIN_TRIAL_FEATURES_FOR_CORE_H_
+#define THIRD_PARTY_BLINK_BINDINGS_CORE_V8_ORIGIN_TRIAL_FEATURES_FOR_CORE_H_
#include "third_party/blink/renderer/core/core_export.h"
@@ -13,6 +12,6 @@ CORE_EXPORT void RegisterInstallOriginTrialFeaturesForCore();
} // namespace blink
-#endif // BLINK_BINDINGS_CORE_V8_ORIGIN_TRIAL_FEATURES_FOR_CORE_H_
+#endif // THIRD_PARTY_BLINK_BINDINGS_CORE_V8_ORIGIN_TRIAL_FEATURES_FOR_CORE_H_
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl
index e3b216c16c5..8ad8c353989 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl
@@ -34,7 +34,7 @@ void InstallOriginTrialFeaturesForModules(
// TODO(iclelland): Extract this common code out of OriginTrialFeaturesForCore
// and OriginTrialFeaturesForModules into a block.
{% for interface in installers_by_interface %}
- if (wrapper_type_info == &{{interface.v8_class}}::wrapperTypeInfo) {
+ if (wrapper_type_info == &{{interface.v8_class}}::wrapper_type_info) {
{% if interface.is_global %}
v8::Local<v8::Object> instance_object =
script_state->GetContext()->Global();
@@ -73,7 +73,7 @@ void InstallPendingOriginTrialFeatureForModules(
v8::Local<v8::Object>(), v8::Local<v8::Function>());
{% else %}
if (context_data->GetExistingConstructorAndPrototypeForType(
- &{{installer.v8_class}}::wrapperTypeInfo, &prototype_object, &interface_object)) {
+ &{{installer.v8_class}}::wrapper_type_info, &prototype_object, &interface_object)) {
{{installer.v8_class_or_partial}}::{{installer.install_method}}(
isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object);
}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.h.tmpl
index 538eb3d30aa..bac0cf176ed 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.h.tmpl
@@ -1,9 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-
-#ifndef BLINK_BINDINGS_MODULES_V8_ORIGIN_TRIAL_FEATURES_FOR_MODULES_H_
-#define BLINK_BINDINGS_MODULES_V8_ORIGIN_TRIAL_FEATURES_FOR_MODULES_H_
+#ifndef THIRD_PARTY_BLINK_BINDINGS_MODULES_V8_ORIGIN_TRIAL_FEATURES_FOR_MODULES_H_
+#define THIRD_PARTY_BLINK_BINDINGS_MODULES_V8_ORIGIN_TRIAL_FEATURES_FOR_MODULES_H_
namespace blink {
@@ -11,6 +10,6 @@ void RegisterInstallOriginTrialFeaturesForModules();
} // namespace blink
-#endif // BLINK_BINDINGS_MODULES_V8_ORIGIN_TRIAL_FEATURES_FOR_MODULES_H_
+#endif // THIRD_PARTY_BLINK_BINDINGS_MODULES_V8_ORIGIN_TRIAL_FEATURES_FOR_MODULES_H_
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/partial_interface.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/partial_interface.cc.tmpl
index e318f6120b2..3ca4e951b75 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/partial_interface.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/partial_interface.cc.tmpl
@@ -1,11 +1,11 @@
-{% extends 'interface_base.cpp.tmpl' %}
+{% extends 'interface_base.cc.tmpl' %}
{##############################################################################}
{% block partial_interface %}
-void {{v8_class_or_partial}}::initialize() {
+void {{v8_class_or_partial}}::Initialize() {
// Should be invoked from ModulesInitializer.
{{v8_class}}::UpdateWrapperTypeInfo(
- &{{v8_class_or_partial}}::install{{v8_class}}Template,
+ &{{v8_class_or_partial}}::Install{{v8_class}}Template,
{% if needs_runtime_enabled_installer %}
&{{v8_class_or_partial}}::InstallRuntimeEnabledFeaturesImpl,
{% else %}
@@ -15,7 +15,7 @@ void {{v8_class_or_partial}}::initialize() {
{{install_conditional_features_func or 'nullptr'}});
{% for method in methods %}
{% if method.overloads and method.overloads.has_partial_overloads %}
- {{v8_class}}::register{{method.name | blink_capitalize}}MethodForPartialInterface(&{{cpp_class_or_partial}}V8Internal::{{method.name}}Method);
+ {{v8_class}}::Register{{method.camel_case_name}}MethodForPartialInterface(&{{internal_namespace}}::{{method.camel_case_name}}Method);
{% endif %}
{% endfor %}
}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/partial_interface.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/partial_interface.h.tmpl
index e8b0055ef66..9a3e8cd882e 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/partial_interface.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/partial_interface.h.tmpl
@@ -1,8 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-#ifndef {{v8_class_or_partial}}_h
-#define {{v8_class_or_partial}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -17,16 +17,16 @@ class ScriptState;
class {{v8_class_or_partial}} {
STATIC_ONLY({{v8_class_or_partial}});
public:
- static void initialize();
+ static void Initialize();
{% for method in methods if method.is_custom %}
- static void {{method.name}}MethodCustom(const v8::FunctionCallbackInfo<v8::Value>&);
+ static void {{method.camel_case_name}}MethodCustom(const v8::FunctionCallbackInfo<v8::Value>&);
{% endfor %}
{% for attribute in attributes %}
{% if attribute.has_custom_getter %}{# FIXME: and not attribute.implemented_by #}
- static void {{attribute.name}}AttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>&);
+ static void {{attribute.camel_case_name}}AttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>&);
{% endif %}
{% if attribute.has_custom_setter %}{# FIXME: and not attribute.implemented_by #}
- static void {{attribute.name}}AttributeSetterCustom(v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&);
+ static void {{attribute.camel_case_name}}AttributeSetterCustom(v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&);
{% endif %}
{% endfor %}
{% if install_conditional_features_func %}
@@ -40,10 +40,10 @@ class {{v8_class_or_partial}} {
{% endif %}
{% for feature in optional_features %}
- static void install{{feature.name}}(ScriptState*, v8::Local<v8::Object> instance);
- static void install{{feature.name}}(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface);
+ static void Install{{feature.name}}(ScriptState*, v8::Local<v8::Object> instance);
+ static void Install{{feature.name}}(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, v8::Local<v8::Function> interface);
{% if not feature.needs_instance %}
- static void install{{feature.name}}(ScriptState*);
+ static void Install{{feature.name}}(ScriptState*);
{% endif %}
{% endfor %}
@@ -55,23 +55,23 @@ class {{v8_class_or_partial}} {
// Callback functions
{% for attribute in attributes %}
{% if attribute.is_cached_accessor %}
- {{exported}}static v8::Local<v8::Private> {{attribute.name}}CachedPropertyKey(v8::Isolate* isolate);
+ {{exported}}static v8::Local<v8::Private> {{attribute.camel_case_name}}CachedPropertyKey(v8::Isolate* isolate);
{% endif %}
{% for world_suffix in attribute.world_suffixes %}
{% if not attribute.constructor_type %}
- {{exported}}static void {{attribute.name}}AttributeGetterCallback{{world_suffix}}(
+ {{exported}}static void {{attribute.camel_case_name}}AttributeGetterCallback{{world_suffix}}(
{%- if attribute.is_data_type_property %}
v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info
{%- else %}
const v8::FunctionCallbackInfo<v8::Value>& info
{%- endif %});
{% else %}
- {{exported}}static void {{attribute.name}}ConstructorGetterCallback{{world_suffix}}(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info);
+ {{exported}}static void {{attribute.camel_case_name}}ConstructorGetterCallback{{world_suffix}}(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info);
{% endif %}
{% if attribute.has_setter %}
- {{exported}}static void {{attribute.name}}AttributeSetterCallback{{world_suffix}}(
+ {{exported}}static void {{attribute.camel_case_name}}AttributeSetterCallback{{world_suffix}}(
{%- if attribute.is_data_type_property %}
- v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info
+ v8::Local<v8::Name>, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<void>& info
{%- else %}
const v8::FunctionCallbackInfo<v8::Value>& info
{%- endif %});
@@ -89,19 +89,19 @@ class {{v8_class_or_partial}} {
(not method.overloads and method.visible) %}
{# A single callback is generated for overloaded methods #}
{# with considering partial overloads #}
- {{exported}}static void {{method.name}}MethodCallback{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info);
+ {{exported}}static void {{method.camel_case_name}}MethodCallback{{world_suffix}}(const v8::FunctionCallbackInfo<v8::Value>& info);
{% endif %}
{% endif %}
{% if method.is_cross_origin and method.visible %}
- {{exported}}static void {{method.name}}OriginSafeMethodGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info);
+ {{exported}}static void {{method.camel_case_name}}OriginSafeMethodGetterCallback{{world_suffix}}(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info);
{% endif %}
{% endfor %}
{% endfor %}
{% if iterator_method %}
- {{exported}}static void {{iterator_method.name}}MethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
+ {{exported}}static void {{iterator_method.camel_case_name}}MethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
{% endif %}
{% if has_origin_safe_method_setter %}
- {{exported}}static void {{cpp_class}}OriginSafeMethodSetterCallback(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info);
+ {{exported}}static void {{cpp_class}}OriginSafeMethodSetterCallback(v8::Local<v8::Name> name, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<void>& info);
{% endif %}
private:
@@ -114,11 +114,11 @@ class {{v8_class_or_partial}} {
v8::Local<v8::Function> interface);
{% endif %}
- static void install{{v8_class}}Template(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interfaceTemplate);
+ static void Install{{v8_class}}Template(v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template);
};
} // namespace blink
-#endif // {{v8_class_or_partial}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/templates.gni b/chromium/third_party/blink/renderer/bindings/templates/templates.gni
index b6c270e5e03..585a300e043 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/templates.gni
+++ b/chromium/third_party/blink/renderer/bindings/templates/templates.gni
@@ -5,29 +5,29 @@
# Paths should be absolute so this file can be imported from anywhere.
code_generator_template_files =
get_path_info([
- "attributes.cpp.tmpl",
- "callback_function.cpp.tmpl",
+ "attributes.cc.tmpl",
+ "callback_function.cc.tmpl",
"callback_function.h.tmpl",
- "callback_interface.cpp.tmpl",
+ "callback_interface.cc.tmpl",
"callback_interface.h.tmpl",
"callback_invoke.cc.tmpl",
- "constants.cpp.tmpl",
+ "constants.cc.tmpl",
"copyright_block.txt",
- "dictionary_impl.cpp.tmpl",
+ "dictionary_impl.cc.tmpl",
"dictionary_impl.h.tmpl",
- "dictionary_impl_common.cpp.tmpl",
- "dictionary_v8.cpp.tmpl",
+ "dictionary_impl_common.cc.tmpl",
+ "dictionary_v8.cc.tmpl",
"dictionary_v8.h.tmpl",
- "external_reference_table.cpp.tmpl",
- "interface.cpp.tmpl",
+ "external_reference_table.cc.tmpl",
+ "interface.cc.tmpl",
"interface.h.tmpl",
- "interface_base.cpp.tmpl",
- "methods.cpp.tmpl",
- "partial_interface.cpp.tmpl",
+ "interface_base.cc.tmpl",
+ "methods.cc.tmpl",
+ "partial_interface.cc.tmpl",
"partial_interface.h.tmpl",
- "union_container.cpp.tmpl",
+ "union_container.cc.tmpl",
"union_container.h.tmpl",
- "utilities.cpp.tmpl",
+ "utilities.cc.tmpl",
"web_agent_api_interface.cc.tmpl",
"web_agent_api_interface.h.tmpl",
],
diff --git a/chromium/third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/union_container.cc.tmpl
index 2b6b64ce60e..4287064a64b 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/union_container.cc.tmpl
@@ -1,20 +1,20 @@
-{% from 'utilities.cpp.tmpl' import declare_enum_validation_variable %}
-{% from 'utilities.cpp.tmpl' import v8_value_to_local_cpp_value %}
+{% from 'utilities.cc.tmpl' import declare_enum_validation_variable %}
+{% from 'utilities.cc.tmpl' import v8_value_to_local_cpp_value %}
{#############################################################################}
{% macro assign_and_return_if_hasinstance(member) %}
{% if member.is_array_buffer_or_view_type %}
-if (v8Value->Is{{member.type_name}}()) {
+if (v8_value->Is{{member.type_name}}()) {
{% else %}
-if (V8{{member.type_name}}::hasInstance(v8Value, isolate)) {
+if (V8{{member.type_name}}::HasInstance(v8_value, isolate)) {
{% endif %}
{% if member.is_array_buffer_view_or_typed_array %}
- {{member.cpp_local_type}} cppValue = ToNotShared<{{member.cpp_local_type}}>(isolate, v8Value, exceptionState);
- if (exceptionState.HadException())
+ {{member.cpp_local_type}} cpp_value = ToNotShared<{{member.cpp_local_type}}>(isolate, v8_value, exception_state);
+ if (exception_state.HadException())
return;
{% else %}
- {{member.cpp_local_type}} cppValue = V8{{member.type_name}}::ToImpl(v8::Local<v8::Object>::Cast(v8Value));
+ {{member.cpp_local_type}} cpp_value = V8{{member.type_name}}::ToImpl(v8::Local<v8::Object>::Cast(v8_value));
{% endif %}
- impl.Set{{member.type_name}}(cppValue);
+ impl.Set{{member.type_name}}(cpp_value);
return;
}
{% endmacro %}
@@ -40,9 +40,9 @@ namespace blink {
void {{cpp_class}}::Set{{member.type_name}}({{member.rvalue_cpp_type}} value) {
DCHECK(IsNull());
{% if member.enum_values %}
- NonThrowableExceptionState exceptionState;
+ NonThrowableExceptionState exception_state;
{{declare_enum_validation_variable(member.enum_values) | trim | indent(2)}}
- if (!IsValidEnum(value, validValues, base::size(validValues), "{{member.enum_type}}", exceptionState)) {
+ if (!IsValidEnum(value, kValidValues, base::size(kValidValues), "{{member.enum_type}}", exception_state)) {
NOTREACHED();
return;
}
@@ -72,21 +72,26 @@ void {{cpp_class}}::Trace(blink::Visitor* visitor) {
{% endfor %}
}
-void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{cpp_class}}& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) {
- if (v8Value.IsEmpty())
+void {{v8_class}}::ToImpl(
+ v8::Isolate* isolate,
+ v8::Local<v8::Value> v8_value,
+ {{cpp_class}}& impl,
+ UnionTypeConversionMode conversion_mode,
+ ExceptionState& exception_state) {
+ if (v8_value.IsEmpty())
return;
{# The numbers in the following comments refer to the steps described in
http://heycam.github.io/webidl/#es-union #}
{# 1. null or undefined #}
- if (conversionMode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8Value))
+ if (conversion_mode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8_value))
return;
{% if dictionary_type %}
{# 3. Dictionaries for null or undefined #}
- if (IsUndefinedOrNull(v8Value)) {
+ if (IsUndefinedOrNull(v8_value)) {
{{v8_value_to_local_cpp_value(dictionary_type) | trim | indent}}
- impl.Set{{dictionary_type.type_name}}(cppValue);
+ impl.Set{{dictionary_type.type_name}}(cpp_value);
return;
}
@@ -109,32 +114,32 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
{% endif %}
{% if array_or_sequence_type %}
{# 11.1, 11.2. Sequences and frozen arrays #}
- if (HasCallableIteratorSymbol(isolate, v8Value, exceptionState)) {
+ if (HasCallableIteratorSymbol(isolate, v8_value, exception_state)) {
{{v8_value_to_local_cpp_value(array_or_sequence_type) | trim | indent}}
{% if array_or_sequence_type.enum_values %}
{{declare_enum_validation_variable(array_or_sequence_type.enum_values) | trim | indent(4)}}
- if (!IsValidEnum(cppValue, validValues, base::size(validValues), "{{array_or_sequence_type.enum_type}}", exceptionState))
+ if (!IsValidEnum(cpp_value, kValidValues, base::size(kValidValues), "{{array_or_sequence_type.enum_type}}", exception_state))
return;
{% endif %}
- impl.Set{{array_or_sequence_type.type_name}}(cppValue);
+ impl.Set{{array_or_sequence_type.type_name}}(cpp_value);
return;
}
{% endif %}
{% if dictionary_type %}
{# 11.3. Dictionaries #}
- if (v8Value->IsObject()) {
+ if (v8_value->IsObject()) {
{{v8_value_to_local_cpp_value(dictionary_type) | trim | indent}}
- impl.Set{{dictionary_type.type_name}}(cppValue);
+ impl.Set{{dictionary_type.type_name}}(cpp_value);
return;
}
{% endif %}
{# 11.4. Records #}
{% if record_type %}
- if (v8Value->IsObject()) {
+ if (v8_value->IsObject()) {
{{v8_value_to_local_cpp_value(record_type) | trim | indent}}
- impl.Set{{record_type.type_name}}(cppValue);
+ impl.Set{{record_type.type_name}}(cpp_value);
return;
}
@@ -142,9 +147,9 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
{# TODO(bashi): Support 11.5 Callback interface when we need it #}
{# 11.6. Objects #}
{% if object_type %}
- if (IsUndefinedOrNull(v8Value) || v8Value->IsObject()) {
+ if (IsUndefinedOrNull(v8_value) || v8_value->IsObject()) {
{{v8_value_to_local_cpp_value(object_type) | trim | indent}}
- impl.Set{{object_type.type_name}}(cppValue);
+ impl.Set{{object_type.type_name}}(cpp_value);
return;
}
@@ -153,17 +158,17 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
we have fallback conversions. (step 16 and 17) #}
{% if boolean_type %}
{# 12. Boolean #}
- if (v8Value->IsBoolean()) {
- impl.SetBoolean(v8Value.As<v8::Boolean>()->Value());
+ if (v8_value->IsBoolean()) {
+ impl.SetBoolean(v8_value.As<v8::Boolean>()->Value());
return;
}
{% endif %}
{% if numeric_type %}
{# 13. Number #}
- if (v8Value->IsNumber()) {
+ if (v8_value->IsNumber()) {
{{v8_value_to_local_cpp_value(numeric_type) | trim | indent}}
- impl.Set{{numeric_type.type_name}}(cppValue);
+ impl.Set{{numeric_type.type_name}}(cpp_value);
return;
}
@@ -174,10 +179,10 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
{{v8_value_to_local_cpp_value(string_type) | trim | indent}}
{% if string_type.enum_values %}
{{declare_enum_validation_variable(string_type.enum_values) | trim | indent}}
- if (!IsValidEnum(cppValue, validValues, base::size(validValues), "{{string_type.enum_type}}", exceptionState))
+ if (!IsValidEnum(cpp_value, kValidValues, base::size(kValidValues), "{{string_type.enum_type}}", exception_state))
return;
{% endif %}
- impl.Set{{string_type.type_name}}(cppValue);
+ impl.Set{{string_type.type_name}}(cpp_value);
return;
}
@@ -185,20 +190,20 @@ void {{v8_class}}::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, {{
{% elif numeric_type %}
{
{{v8_value_to_local_cpp_value(numeric_type) | trim | indent}}
- impl.Set{{numeric_type.type_name}}(cppValue);
+ impl.Set{{numeric_type.type_name}}(cpp_value);
return;
}
{# 16. Boolean (fallback) #}
{% elif boolean_type %}
{
- impl.SetBoolean(v8Value->BooleanValue(isolate->GetCurrentContext()).ToChecked());
+ impl.SetBoolean(v8_value->BooleanValue(isolate));
return;
}
{% else %}
{# 17. TypeError #}
- exceptionState.ThrowTypeError("The provided value is not of type '{{type_string}}'");
+ exception_state.ThrowTypeError("The provided value is not of type '{{type_string}}'");
{% endif %}
}
@@ -217,9 +222,10 @@ v8::Local<v8::Value> ToV8(const {{cpp_class}}& impl, v8::Local<v8::Object> creat
return v8::Local<v8::Value>();
}
-{{cpp_class}} NativeValueTraits<{{cpp_class}}>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
+{{cpp_class}} NativeValueTraits<{{cpp_class}}>::NativeValue(
+ v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) {
{{cpp_class}} impl;
- {{v8_class}}::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exceptionState);
+ {{v8_class}}::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exception_state);
return impl;
}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/union_container.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/union_container.h.tmpl
index 177ae92d3b0..e264980ce99 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/union_container.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/union_container.h.tmpl
@@ -1,8 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-#ifndef {{cpp_class}}_h
-#define {{cpp_class}}_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for filename in header_includes %}
#include "{{filename}}"
@@ -84,6 +84,6 @@ struct V8TypeOf<{{cpp_class}}> {
// See https://codereview.chromium.org/1118993002/#msg5 for more details.
WTF_ALLOW_MOVE_AND_INIT_WITH_MEM_FUNCTIONS(blink::{{cpp_class}});
-#endif // {{cpp_class}}_h
+#endif // {{header_guard}}
{% endfilter %}{# format_blink_cpp_source_code #}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/utilities.cpp.tmpl b/chromium/third_party/blink/renderer/bindings/templates/utilities.cc.tmpl
index b5ae1c892cc..b4cdea716f3 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/utilities.cpp.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/utilities.cc.tmpl
@@ -31,7 +31,7 @@ if ({{item.check_expression}})
{% endmacro %}
-{% macro declare_enum_validation_variable(enum_values, enum_variable='validValues') %}
+{% macro declare_enum_validation_variable(enum_values, enum_variable='kValidValues') %}
const char* {{enum_variable}}[] = {
{% for enum_value in enum_values %}
{% if enum_value is none %}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.cc.tmpl b/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.cc.tmpl
index f4d27d49fb5..076348dc433 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.cc.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.cc.tmpl
@@ -12,7 +12,7 @@
namespace web {
{{class_name.upper_camel_case}}* {{class_name.upper_camel_case}}::Create(blink::{{class_name.upper_camel_case}}* {{class_name.snake_case}}) {
- return {{class_name.snake_case}} ? new {{class_name.upper_camel_case}}({{class_name.snake_case}}) : nullptr;
+ return {{class_name.snake_case}} ? MakeGarbageCollected<{{class_name.upper_camel_case}}>({{class_name.snake_case}}) : nullptr;
}
{% if not base_class %}
diff --git a/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.h.tmpl b/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.h.tmpl
index 86d0537049c..923d12bdb66 100644
--- a/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.h.tmpl
+++ b/chromium/third_party/blink/renderer/bindings/templates/web_agent_api_interface.h.tmpl
@@ -1,9 +1,8 @@
{% filter format_blink_cpp_source_code %}
{% include 'copyright_block.txt' %}
-
-#ifndef WEB_API_{{class_name.macro_case}}_H
-#define WEB_API_{{class_name.macro_case}}_H
+#ifndef {{header_guard}}
+#define {{header_guard}}
{% for include_file in header_includes %}
#include "{{include_file}}"
@@ -41,6 +40,6 @@ class {{class_name.upper_camel_case}} : public {% if not base_class -%}
} // namespace web
-#endif // WEB_API_{{class_name.macro_case}}_H
+#endif // {{header_guard}}
{% endfilter %}
diff --git a/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py b/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py
index a989def3854..9c44e535b22 100644
--- a/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py
+++ b/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter.py
@@ -60,6 +60,7 @@ SPECIAL_TOKENS = [
'FE',
'V0',
'V8',
+ 'v8',
]
_SPECIAL_TOKENS_WITH_NUMBERS = [token for token in SPECIAL_TOKENS if re.search(r'[0-9]', token)]
@@ -226,3 +227,10 @@ class NameStyleConverter(object):
i.e. kUpperCamelCase
"""
return 'k' + self.to_upper_camel_case()
+
+ def to_header_guard(self):
+ """Represents this name as a header guard style in Chromium C++ style.
+
+ i.e. THIRD_PARTY_BLINK_RENDERER_MODULES_MODULES_EXPORT_H_
+ """
+ return re.sub(r'[-/.]', '_', self.to_macro_case()) + '_'
diff --git a/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py b/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py
index d3d5944b674..09daf14a4d1 100644
--- a/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py
+++ b/chromium/third_party/blink/renderer/build/scripts/blinkbuild/name_style_converter_test.py
@@ -191,3 +191,10 @@ class NameStyleConverterTest(unittest.TestCase):
'upper_camel_case': 'SVGScriptElement',
'macro_case': 'SVG_SCRIPT_ELEMENT',
})
+
+ def test_to_header_guard(self):
+ converter = NameStyleConverter('third_party/blink/renderer/bindings/modules/v8/v8_path_2d.h')
+ self.assertEqual(converter.to_header_guard(), 'THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_PATH_2D_H_')
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_css_primitive_value_unit_trie.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py
index b6c0cfb6164..316284c0cbf 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_css_primitive_value_unit_trie.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_primitive_value_unit_trie.py
@@ -3,7 +3,9 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import os
import sys
+sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
import json5_generator
import trie_builder
@@ -20,7 +22,7 @@ class UnitTrieWriter(json5_generator.Writer):
'css_primitive_value_unit_trie.cc': self.generate_implementation
}
- @template_expander.use_jinja('templates/css_primitive_value_unit_trie.cc.tmpl')
+ @template_expander.use_jinja('core/css/templates/css_primitive_value_unit_trie.cc.tmpl')
def generate_implementation(self):
return {
'input_files': self._input_files,
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_css_property_names.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py
index 4a9c81cff33..5cb3e205fff 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_css_property_names.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_property_names.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python
+import os
+import sys
+sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
+
from core.css import css_properties
import gperf
import json5_generator
@@ -25,7 +29,7 @@ class CSSPropertyNamesWriter(json5_generator.Writer):
return " static_cast<CSSPropertyID>(%(enum_value)s), " \
"// %(property_id)s" % property_
- @template_expander.use_jinja('templates/css_property_names.h.tmpl')
+ @template_expander.use_jinja('core/css/templates/css_property_names.h.tmpl')
def generate_header(self):
return {
'alias_offset': self._css_properties.alias_offset,
@@ -45,7 +49,7 @@ class CSSPropertyNamesWriter(json5_generator.Writer):
max(map(len, self._css_properties.properties_by_id)),
}
- @gperf.use_jinja_gperf_template('templates/css_property_names.cc.tmpl',
+ @gperf.use_jinja_gperf_template('core/css/templates/css_property_names.cc.tmpl',
['-Q', 'CSSPropStringPool'])
def generate_implementation(self):
enum_value_to_name = {}
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_css_tokenizer_codepoints.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py
index 54d4a374606..c48d23ae703 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_css_tokenizer_codepoints.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_tokenizer_codepoints.py
@@ -4,9 +4,11 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-import in_generator
-import sys
import os
+import sys
+sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
+
+import in_generator
module_basename = os.path.basename(__file__)
module_pyname = os.path.splitext(module_basename)[0] + '.py'
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_css_value_id_mappings.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py
index 907821095d1..b0cdb892012 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_css_value_id_mappings.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_id_mappings.py
@@ -3,6 +3,10 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import os
+import sys
+sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
+
from blinkbuild.name_style_converter import NameStyleConverter
import json5_generator
import template_expander
@@ -115,7 +119,7 @@ class CSSValueIDMappingsWriter(make_style_builder.StyleBuilderWriter):
css_properties = keyword_utils.sort_keyword_properties_by_canonical_order(
css_properties, json5_file_paths[2], self.default_parameters)
- @template_expander.use_jinja('templates/css_value_id_mappings_generated.h.tmpl')
+ @template_expander.use_jinja('core/css/templates/css_value_id_mappings_generated.h.tmpl')
def generate_css_value_mappings(self):
mappings = {}
include_paths = set()
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py
index c9ea5d05b8f..7c08560cfcf 100755
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_css_value_keywords.py
@@ -14,11 +14,13 @@ import gperf
class CSSValueKeywordsWriter(json5_generator.Writer):
+ _FILE_BASENAME = 'css_value_keywords'
+
def __init__(self, file_paths, output_dir):
json5_generator.Writer.__init__(self, file_paths, output_dir)
self._outputs = {
- "css_value_keywords.h": self.generate_header,
- "css_value_keywords.cc": self.generate_implementation
+ (self._FILE_BASENAME + '.h'): self.generate_header,
+ (self._FILE_BASENAME + '.cc'): self.generate_implementation,
}
self._value_keywords = self.json5_file.name_dictionaries
@@ -43,6 +45,7 @@ class CSSValueKeywordsWriter(json5_generator.Writer):
'value_keywords_count': self._keyword_count,
'max_value_keyword_length':
max(len(keyword['name'].original) for keyword in self._value_keywords),
+ 'header_guard': self.make_header_guard(self._relative_output_dir + self._FILE_BASENAME + '.h')
}
def _value_keywords_with_mode(self, mode):
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py
index 273aaba6a3c..5f1ad9cbf88 100755
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_feature_names.py
@@ -14,9 +14,12 @@ import media_feature_symbol
class MakeMediaFeatureNamesWriter(make_names.MakeNamesWriter):
- pass
-MakeMediaFeatureNamesWriter.filters['symbol'] = media_feature_symbol.getMediaFeatureSymbolWithSuffix('MediaFeature')
+ def __init__(self, json5_file_path, output_dir):
+ super(MakeMediaFeatureNamesWriter, self).__init__(json5_file_path, output_dir)
+ MakeMediaFeatureNamesWriter.filters['symbol'] = (
+ media_feature_symbol.getMediaFeatureSymbolWithSuffix('MediaFeature'))
+
if __name__ == "__main__":
json5_generator.Maker(MakeMediaFeatureNamesWriter).main()
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_features.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_features.py
index 487e6b3f732..fcf89d7d4f2 100755
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_features.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_media_features.py
@@ -21,7 +21,8 @@ class MakeMediaFeaturesWriter(json5_generator.Writer):
}
filters = {
'symbol': media_feature_symbol.getMediaFeatureSymbolWithSuffix(''),
- 'to_function_name': lambda symbol: NameStyleConverter(symbol).to_function_name(),
+ # symbol[1:] removes the leading 'k' produced by the above function.
+ 'to_function_name': lambda symbol: NameStyleConverter(symbol[1:]).to_function_name(),
}
def __init__(self, json5_file_path, output_dir):
@@ -33,6 +34,7 @@ class MakeMediaFeaturesWriter(json5_generator.Writer):
self._template_context = {
'entries': self.json5_file.name_dictionaries,
'input_files': self._input_files,
+ 'header_guard': self.make_header_guard(self._relative_output_dir + 'media_festures.h')
}
@template_expander.use_jinja('core/css/templates/media_features.h.tmpl', filters=filters)
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py b/chromium/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py
index 11e80e2c5c9..060d2f32a5a 100755
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/make_style_shorthands.py
@@ -40,15 +40,17 @@ import template_expander
class StylePropertyShorthandWriter(json5_generator.Writer):
class_name = 'StylePropertyShorthand'
+ _FILE_BASENAME = 'style_property_shorthand'
def __init__(self, json5_file_paths, output_dir):
super(StylePropertyShorthandWriter, self).__init__([], output_dir)
self._input_files = json5_file_paths
self._outputs = {
- 'style_property_shorthand.cc':
+ (self._FILE_BASENAME + '.cc'):
self.generate_style_property_shorthand_cpp,
- 'style_property_shorthand.h':
- self.generate_style_property_shorthand_h}
+ (self._FILE_BASENAME + '.h'):
+ self.generate_style_property_shorthand_h
+ }
json5_properties = css_properties.CSSProperties(json5_file_paths)
self._shorthands = json5_properties.shorthands
@@ -83,6 +85,7 @@ class StylePropertyShorthandWriter(json5_generator.Writer):
return {
'input_files': self._input_files,
'properties': self._shorthands,
+ 'header_guard': self.make_header_guard(self._relative_output_dir + self._FILE_BASENAME + '.h')
}
if __name__ == '__main__':
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/parser/templates/at_rule_descriptors.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/parser/templates/at_rule_descriptors.h.tmpl
index 0e41a3e1031..900fa592198 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/parser/templates/at_rule_descriptors.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/parser/templates/at_rule_descriptors.h.tmpl
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_AT_RULE_DESCRIPTORS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_AT_RULE_DESCRIPTORS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include <string.h>
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property.h.tmpl
index 1947b2ffc35..becfce1a85b 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property.h.tmpl
@@ -9,7 +9,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTY_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/properties/css_unresolved_property.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.cc.tmpl
index 3647ca60c02..838dccaf48d 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.cc.tmpl
@@ -13,9 +13,9 @@
{% endfor %}
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
{{style_builder_functions(property, false)}}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl
index 91a0efed320..94e9ee344bb 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl
@@ -14,14 +14,14 @@
{% endfor %}
namespace blink {
-namespace CSS{{property.namespace_group}} {
+namespace css_{{property.namespace_group.lower()}} {
{% if property.is_property %}
// Implements the '{{property.name}}' CSS property
{% else %}
// Implements the '{{property.name}}' CSS descriptor
{% endif %}
-// See src/third_party/WebKit/Source/core/css/properties/README.md
+// See src/third_party/blink/renderer/core/css/properties/README.md
{% if property.alias_for != None%}
class {{property_classname}} final : public CSSUnresolvedProperty {
public:
@@ -130,7 +130,7 @@ class {{property_classname}} final : public {{property.namespace_group}} {
{% endif %}
};
-} // namespace CSS{{property.namespace_group}}
+} // namespace css_{{property.namespace_group.lower()}}
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_{{property.namespace_group.upper()}}_{{property_filename|upper}}_H_
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.cc.tmpl
index 78721960a97..56c9eb7c292 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.cc.tmpl
@@ -23,10 +23,10 @@ namespace {
static constexpr Variable property_csspropertyvariable;
{% for _, property_id, classname, namespace_group, _ in property_classes_by_property_id %}
-static constexpr CSS{{namespace_group}}::{{classname}} property_{{property_id.lower()}};
+static constexpr css_{{namespace_group.lower()}}::{{classname}} property_{{property_id.lower()}};
{% endfor %}
{% for _, property_id, classname, namespace_group, _ in alias_classes_by_property_id %}
-static constexpr CSS{{namespace_group}}::{{classname}} property_{{property_id.lower()}};
+static constexpr css_{{namespace_group.lower()}}::{{classname}} property_{{property_id.lower()}};
{% endfor %}
} // namespace
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.h.tmpl
index 440453d6c10..ea360d624a9 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_unresolved_property.h.tmpl
@@ -9,7 +9,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_UNRESOLVED_PROPERTY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_UNRESOLVED_PROPERTY_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/style_builder_functions.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/style_builder_functions.tmpl
index e10f98b0b49..5ff29d8618a 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/style_builder_functions.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/properties/templates/style_builder_functions.tmpl
@@ -161,7 +161,7 @@ ToLonghand(resolved_property).{{apply_call}};
const NinePieceImage& current_image = state.Style()->{{getter}}();
{# Check for equality in case we can bail out before creating a new NinePieceImage. #}
{% if modifier_type == 'Outset' %}
- if (StyleBuildingUtils::BorderImageLengthMatchesAllSides(current_image.Outset(),
+ if (style_building_utils::BorderImageLengthMatchesAllSides(current_image.Outset(),
BorderImageLength(Length(0, kFixed))))
return;
{% elif modifier_type == 'Repeat' %}
@@ -172,20 +172,20 @@ ToLonghand(resolved_property).{{apply_call}};
// Masks have a different initial value for slices. Preserve the value of 0
// for backwards compatibility.
if (current_image.Fill() == true &&
- StyleBuildingUtils::LengthMatchesAllSides(current_image.ImageSlices(), Length(0, kFixed)))
+ style_building_utils::LengthMatchesAllSides(current_image.ImageSlices(), Length(0, kFixed)))
return;
{% elif modifier_type == 'Slice' and not is_mask_box %}
if (current_image.Fill() == false &&
- StyleBuildingUtils::LengthMatchesAllSides(current_image.ImageSlices(), Length(100, kPercent)))
+ style_building_utils::LengthMatchesAllSides(current_image.ImageSlices(), Length(100, kPercent)))
return;
{% elif modifier_type == 'Width' and is_mask_box %}
// Masks have a different initial value for widths. Preserve the value of
// 'auto' for backwards compatibility.
- if (StyleBuildingUtils::BorderImageLengthMatchesAllSides(current_image.BorderSlices(),
+ if (style_building_utils::BorderImageLengthMatchesAllSides(current_image.BorderSlices(),
BorderImageLength(Length(kAuto))))
return;
{% elif modifier_type == 'Width' and not is_mask_box %}
- if (StyleBuildingUtils::BorderImageLengthMatchesAllSides(current_image.BorderSlices(),
+ if (style_building_utils::BorderImageLengthMatchesAllSides(current_image.BorderSlices(),
BorderImageLength(1.0)))
return;
{% endif %}
@@ -407,8 +407,8 @@ ToLonghand(resolved_property).{{apply_call}};
const CSSValueList& list = ToCSSValueList(value);
- for (size_t i = 0; i < list.length(); ++i) {
- const CSSValuePair& pair = ToCSSValuePair(list.Item(i));
+ for (const CSSValue* item : list) {
+ const CSSValuePair& pair = ToCSSValuePair(*item);
AtomicString identifier(ToCSSCustomIdentValue(pair.First()).Value());
int counter_value = ToCSSPrimitiveValue(pair.Second()).GetIntValue();
CounterDirectives& directives =
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/css_primitive_value_unit_trie.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_primitive_value_unit_trie.cc.tmpl
index 84c3a5b6bfb..84c3a5b6bfb 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/css_primitive_value_unit_trie.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_primitive_value_unit_trie.cc.tmpl
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/css_property_names.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_property_names.cc.tmpl
index 54c9f645a8c..25e3e6bab05 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/css_property_names.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_property_names.cc.tmpl
@@ -3,7 +3,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/core/{{file_basename}}.h"
+#include "third_party/blink/renderer/core/css/{{file_basename}}.h"
#include <string.h>
#include "third_party/blink/renderer/core/css/hash_tools.h"
@@ -25,7 +25,6 @@ struct Property;
%omit-struct-type
%language=C++
%readonly-tables
-%global-table
%compare-strncmp
%define class-name {{class_name}}Hash
%define lookup-function-name findPropertyImpl
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/css_property_names.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_property_names.h.tmpl
index b20372d39c1..3b8186fa027 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/css_property_names.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_property_names.h.tmpl
@@ -1,8 +1,8 @@
{% from 'templates/macros.tmpl' import license %}
{{license()}}
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTY_NAMES_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTY_NAMES_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_NAMES_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_NAMES_H_
#include <stddef.h>
#include "third_party/blink/renderer/core/core_export.h"
@@ -62,4 +62,4 @@ CSSPropertyID CORE_EXPORT cssPropertyID(const WTF::String&);
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTY_NAMES_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_NAMES_H_
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/css_value_id_mappings_generated.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_id_mappings_generated.h.tmpl
index 8e371e71baa..66d484f7f3c 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/css_value_id_mappings_generated.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_id_mappings_generated.h.tmpl
@@ -3,12 +3,12 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_VALUE_ID_MAPPINGS_GENERATED_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_VALUE_ID_MAPPINGS_GENERATED_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_VALUE_ID_MAPPINGS_GENERATED_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_VALUE_ID_MAPPINGS_GENERATED_H_
#include "base/logging.h"
-#include "third_party/blink/renderer/core/computed_style_base_constants.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
+#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
{% for path in include_paths %}
#include "{{path}}"
{% endfor %}
@@ -100,4 +100,4 @@ inline CSSValueID platformEnumToCSSValueIDGenerated({{enum_name}} v) {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_VALUE_ID_MAPPINGS_GENERATED_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_VALUE_ID_MAPPINGS_GENERATED_H_
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_keywords.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_keywords.h.tmpl
index ae17728ee96..e91f3222d47 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_keywords.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/css_value_keywords.h.tmpl
@@ -2,12 +2,13 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef BLINK_CORE_CSS_VALUE_KEYWORDS_H_
-#define BLINK_CORE_CSS_VALUE_KEYWORDS_H_
+#ifndef {{header_guard}}
+#define {{header_guard}}
-#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
#include <string.h>
+#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
+
namespace blink {
enum CSSValueID {
@@ -23,6 +24,6 @@ const size_t maxCSSValueKeywordLength = {{max_value_keyword_length}};
const char* getValueName(CSSValueID);
bool isValueAllowedInMode(unsigned short id, CSSParserMode mode);
-} // namespace blink
+} // namespace blink
-#endif // BLINK_CORE_CSS_VALUE_KEYWORDS_H_
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/cssom_types.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/cssom_types.cc.tmpl
index f479b87b811..4b7dc54bb91 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/cssom_types.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/cssom_types.cc.tmpl
@@ -93,7 +93,8 @@ bool CSSOMTypes::IsPropertySupported(CSSPropertyID id) {
bool CSSOMTypes::PropertyCanTake(CSSPropertyID id,
const AtomicString& custom_property_name,
const PropertyRegistration* registration,
- const CSSStyleValue& value) {
+ const CSSStyleValue& value,
+ const CSSSyntaxComponent*& match) {
DCHECK_EQ(id == CSSPropertyVariable, !custom_property_name.IsNull());
if (id == CSSPropertyVariable && registration) {
@@ -101,7 +102,8 @@ bool CSSOMTypes::PropertyCanTake(CSSPropertyID id,
return ToCSSUnsupportedStyleValue(value).GetCustomPropertyName() ==
custom_property_name;
}
- return registration->Syntax().CanTake(value);
+ match = registration->Syntax().Match(value);
+ return match != nullptr;
}
if (value.GetType() == CSSStyleValue::kKeywordType) {
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/media_features.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/media_features.h.tmpl
index 4f7fe5d43f3..4b8de52e195 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/media_features.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/media_features.h.tmpl
@@ -1,10 +1,10 @@
{% from "templates/macros.tmpl" import license, source_files_for_generated_file %}
-{{ license() }}
+{{license()}}
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef BLINK_CORE_CSS_MEDIA_FEATURES_H_
-#define BLINK_CORE_CSS_MEDIA_FEATURES_H_
+#ifndef {{header_guard}}
+#define {{header_guard}}
#define CSS_MEDIAQUERY_NAMES_FOR_EACH_MEDIAFEATURE(macro) \
{% for entry in entries %}
@@ -14,4 +14,4 @@
{% endif %}
{% endfor %}
-#endif // BLINK_CORE_CSS_MEDIA_FEATURES_H_
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.h.tmpl
index 20ae092e477..49cc3b86342 100644
--- a/chromium/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.h.tmpl
@@ -22,10 +22,10 @@
{% from 'templates/macros.tmpl' import source_files_for_generated_file %}
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef BLINK_CORE_STYLE_PROPERTY_SHORTHAND_H_
-#define BLINK_CORE_STYLE_PROPERTY_SHORTHAND_H_
+#ifndef {{header_guard}}
+#define {{header_guard}}
-#include "css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -74,6 +74,6 @@ void getMatchingShorthandsForLonghand(
unsigned indexOfShorthandForLonghand(CSSPropertyID,
const Vector<StylePropertyShorthand, 4>&);
-} // namespace blink
+} // namespace blink
-#endif // BLINK_CORE_STYLE_PROPERTY_SHORTHAND_H_
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_computed_style_base.py b/chromium/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py
index a15ae5e8794..21dbfa4cae8 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_computed_style_base.py
+++ b/chromium/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py
@@ -3,6 +3,10 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import os
+import sys
+sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
+
import math
import json5_generator
@@ -556,7 +560,7 @@ class ComputedStyleBaseWriter(json5_generator.Writer):
}
@template_expander.use_jinja(
- 'templates/computed_style_base.h.tmpl', tests={'in': lambda a, b: a in b})
+ 'core/style/templates/computed_style_base.h.tmpl', tests={'in': lambda a, b: a in b})
def generate_base_computed_style_h(self):
return {
'input_files': self._input_files,
@@ -568,7 +572,7 @@ class ComputedStyleBaseWriter(json5_generator.Writer):
}
@template_expander.use_jinja(
- 'templates/computed_style_base.cc.tmpl',
+ 'core/style/templates/computed_style_base.cc.tmpl',
tests={'in': lambda a, b: a in b})
def generate_base_computed_style_cpp(self):
return {
@@ -580,7 +584,7 @@ class ComputedStyleBaseWriter(json5_generator.Writer):
'diff_functions_map': self._diff_functions_map,
}
- @template_expander.use_jinja('templates/computed_style_base_constants.h.tmpl')
+ @template_expander.use_jinja('core/style/templates/computed_style_base_constants.h.tmpl')
def generate_base_computed_style_constants(self):
return {
'input_files': self._input_files,
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.cc.tmpl
index b640e745205..5697ad5a947 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.cc.tmpl
@@ -5,8 +5,8 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#include "third_party/blink/renderer/core/computed_style_base.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/core/style/computed_style_base.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.h.tmpl
index fdcf46c9442..eeaaa0586e5 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.h.tmpl
@@ -5,8 +5,8 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_COMPUTED_STYLE_BASE_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_COMPUTED_STYLE_BASE_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_BASE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_BASE_H_
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
@@ -185,4 +185,4 @@ class ComputedStyleBase {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_COMPUTED_STYLE_BASE_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_BASE_H_
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base_constants.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base_constants.h.tmpl
index ef98612f9f5..aee3668af2f 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/computed_style_base_constants.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base_constants.h.tmpl
@@ -3,8 +3,8 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_COMPUTED_STYLE_BASE_CONSTANTS_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_COMPUTED_STYLE_BASE_CONSTANTS_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_BASE_CONSTANTS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_BASE_CONSTANTS_H_
namespace blink {
@@ -36,4 +36,4 @@ inline {{enum.type_name}}& operator{{op}}=({{enum.type_name}}& a, {{enum.type_na
{% endfor %}
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_COMPUTED_STYLE_BASE_CONSTANTS_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_BASE_CONSTANTS_H_
diff --git a/chromium/third_party/blink/renderer/build/scripts/gperf.py b/chromium/third_party/blink/renderer/build/scripts/gperf.py
index 057796677c4..df7b713a8a2 100644
--- a/chromium/third_party/blink/renderer/build/scripts/gperf.py
+++ b/chromium/third_party/blink/renderer/build/scripts/gperf.py
@@ -38,7 +38,7 @@ def generate_gperf(gperf_path, gperf_input, gperf_args):
# so replace gperf's /*FALLTHROUGH*/ comment with the statement.
# https://savannah.gnu.org/bugs/index.php?53029
gperf_output = gperf_output.replace('/*FALLTHROUGH*/', ' FALLTHROUGH;')
- script = 'third_party/WebKit/Source/build/scripts/gperf.py'
+ script = 'third_party/blink/renderer/build/scripts/gperf.py'
return '// Generated by %s\n' % script + gperf_output
except OSError:
raise subprocess.CalledProcessError(
diff --git a/chromium/third_party/blink/renderer/build/scripts/json5_generator.py b/chromium/third_party/blink/renderer/build/scripts/json5_generator.py
index 2a4ed7db2a5..2b8cd7520e4 100644
--- a/chromium/third_party/blink/renderer/build/scripts/json5_generator.py
+++ b/chromium/third_party/blink/renderer/build/scripts/json5_generator.py
@@ -252,7 +252,7 @@ class Writer(object):
return NameStyleConverter(name).to_snake_case()
def make_header_guard(self, path):
- return re.sub(r'[-/.]', '_', path).upper() + '_'
+ return NameStyleConverter(path).to_header_guard()
class Maker(object):
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_element_lookup_trie.py b/chromium/third_party/blink/renderer/build/scripts/make_element_lookup_trie.py
index d0fce32f3c1..f370fd553de 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_element_lookup_trie.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_element_lookup_trie.py
@@ -29,6 +29,7 @@
import sys
+from blinkbuild.name_style_converter import NameStyleConverter
import json5_generator
import trie_builder
import template_expander
@@ -53,6 +54,9 @@ class ElementLookupTrieWriter(json5_generator.Writer):
'namespacePrefix': '',
'namespaceURI': '',
}
+ filters = {
+ 'symbol': lambda symbol: 'k' + NameStyleConverter(symbol).to_upper_camel_case()
+ }
def __init__(self, json5_file_paths, output_dir):
super(ElementLookupTrieWriter, self).__init__(json5_file_paths, output_dir)
@@ -73,7 +77,7 @@ class ElementLookupTrieWriter(json5_generator.Writer):
'namespace': self._namespace,
}
- @template_expander.use_jinja('templates/element_lookup_trie.cc.tmpl')
+ @template_expander.use_jinja('templates/element_lookup_trie.cc.tmpl', filters=filters)
def generate_implementation(self):
return {
'input_files': self._input_files,
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_element_type_helpers.py b/chromium/third_party/blink/renderer/build/scripts/make_element_type_helpers.py
index 0c8561e0d5f..210e5c26fd8 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_element_type_helpers.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_element_type_helpers.py
@@ -8,12 +8,11 @@ from collections import defaultdict
import hasher
import json5_generator
-import name_utilities
import template_expander
def _symbol(tag):
- return name_utilities.cpp_name(tag).replace('-', '_')
+ return 'k' + tag['name'].to_upper_camel_case()
class MakeElementTypeHelpersWriter(json5_generator.Writer):
@@ -60,6 +59,7 @@ class MakeElementTypeHelpersWriter(json5_generator.Writer):
'{0}/{0}_element.h'.format(self.namespace.lower())
self._template_context = {
'base_element_header': base_element_header,
+ 'cpp_namespace': self.namespace.lower() + '_names',
'input_files': self._input_files,
'namespace': self.namespace,
'tags': self.json5_file.name_dictionaries,
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_event_factory.py b/chromium/third_party/blink/renderer/build/scripts/make_event_factory.py
index d509a3e8d42..a941cc0a793 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_event_factory.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_event_factory.py
@@ -91,6 +91,7 @@ def measure_name(name):
class EventFactoryWriter(json5_generator.Writer):
default_parameters = {
'ImplementedAs': {},
+ 'interfaceHeaderDir': {},
'RuntimeEnabled': {},
}
default_metadata = {
@@ -100,7 +101,7 @@ class EventFactoryWriter(json5_generator.Writer):
}
filters = {
'cpp_name': name_utilities.cpp_name,
- 'script_name': name_utilities.script_name,
+ 'name': lambda entry: entry['name'].original,
'create_event_whitelist': create_event_whitelist,
'create_event_measure_whitelist': create_event_measure_whitelist,
'measure_name': measure_name,
@@ -109,7 +110,7 @@ class EventFactoryWriter(json5_generator.Writer):
def __init__(self, json5_file_path, output_dir):
super(EventFactoryWriter, self).__init__(json5_file_path, output_dir)
self.namespace = self.json5_file.metadata['namespace'].strip('"')
- assert self.namespace == 'Event', 'namespace field should be "Event".'
+ assert self.namespace == 'event_interface_names', 'namespace field should be "event_interface_names".'
self.suffix = self.json5_file.metadata['suffix'].strip('"')
snake_suffix = (self.suffix.lower() + '_') if self.suffix else ''
self._outputs = {
@@ -121,14 +122,10 @@ class EventFactoryWriter(json5_generator.Writer):
exit(1)
def _headers_header_include_path(self, entry):
- path = os.path.dirname(entry['name'].original)
+ path = entry['interfaceHeaderDir']
if len(path):
path += '/'
- if entry['ImplementedAs']:
- path += self.get_file_basename(entry['ImplementedAs'])
- else:
- path += self.get_file_basename(os.path.basename(entry['name'].original))
- return path + '.h'
+ return path + self.get_file_basename(name_utilities.cpp_name(entry)) + '.h'
def _headers_header_includes(self, entries):
includes = dict()
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_instrumenting_probes.py b/chromium/third_party/blink/renderer/build/scripts/make_instrumenting_probes.py
index 64d6e7d533a..514a0dcfc1f 100644
--- a/chromium/third_party/blink/renderer/build/scripts/make_instrumenting_probes.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_instrumenting_probes.py
@@ -60,7 +60,8 @@ def agent_name_to_class(config, agent_name):
def agent_name_to_include(config, agent_name):
include_path = agent_config(config, agent_name, "include_path") or config["settings"]["include_path"]
agent_class = agent_name_to_class(config, agent_name)
- return os.path.join(include_path, NameStyleConverter(agent_class).to_snake_case() + ".h")
+ include_file = os.path.join(include_path, NameStyleConverter(agent_class).to_snake_case() + ".h")
+ return include_file.replace("dev_tools", "devtools")
def initialize_jinja_env(config, cache_dir):
@@ -106,7 +107,7 @@ def load_model_from_idl(source):
class File(object):
def __init__(self, name, source):
self.name = NameStyleConverter(name).to_snake_case()
- self.header_name = self.name + "_inl"
+ self.header_name = self.name + "_inl.h"
self.forward_declarations = []
self.declarations = []
for line in map(str.strip, source.split("\n")):
@@ -263,15 +264,18 @@ def main():
template_context["template_file"] = "/probe_sink.h.tmpl"
sink_h_template = jinja_env.get_template(template_context["template_file"])
- sink_h_file = open(output_dirpath + "/" + to_singular(base_name) + "_sink.h", "w")
+ sink_h_file_name = to_singular(base_name) + "_sink.h"
+ sink_h_file = open(output_dirpath + "/" + sink_h_file_name, "w")
+ template_context["header_guard"] = NameStyleConverter(output_path_in_gen_dir + "/" + sink_h_file_name).to_header_guard()
sink_h_file.write(sink_h_template.render(template_context))
sink_h_file.close()
for f in files:
template_context["file"] = f
template_context["template_file"] = "/instrumenting_probes_inl.h.tmpl"
+ template_context["header_guard"] = NameStyleConverter(output_path_in_gen_dir + "/" + f.header_name).to_header_guard()
h_template = jinja_env.get_template(template_context["template_file"])
- h_file = open(output_dirpath + "/" + f.header_name + ".h", "w")
+ h_file = open(output_dirpath + "/" + f.header_name, "w")
h_file.write(h_template.render(template_context))
h_file.close()
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py b/chromium/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py
index d8e2fa99bfc..b0fd5dd2b3e 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_internal_runtime_flags.py
@@ -62,6 +62,7 @@ class InternalRuntimeFlagsWriter(make_runtime_features.RuntimeFeatureWriter):
'feature_sets': self._feature_sets(),
'input_files': self._input_files,
'standard_features': self._standard_features,
+ 'header_guard': self._header_guard,
}
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_internal_settings.py b/chromium/third_party/blink/renderer/build/scripts/make_internal_settings.py
index 8827eea5e63..8d12f653635 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_internal_settings.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_internal_settings.py
@@ -40,6 +40,7 @@ class MakeInternalSettingsWriter(json5_generator.Writer):
'to_passing_type': to_passing_type,
'to_idl_type': to_idl_type,
}
+ _FILE_BASENAME = 'internal_settings_generated'
def __init__(self, json5_file_path, output_dir):
super(MakeInternalSettingsWriter, self).__init__(json5_file_path, output_dir)
@@ -47,14 +48,15 @@ class MakeInternalSettingsWriter(json5_generator.Writer):
self.json5_file.name_dictionaries.sort(key=lambda entry: entry['name'].original)
self._outputs = {
- 'internal_settings_generated.h': self.generate_header,
- 'internal_settings_generated.cc': self.generate_implementation,
- 'internal_settings_generated.idl': self.generate_idl,
+ (self._FILE_BASENAME + '.h'): self.generate_header,
+ (self._FILE_BASENAME + '.cc'): self.generate_implementation,
+ (self._FILE_BASENAME + '.idl'): self.generate_idl,
}
self._template_context = {
'input_files': self._input_files,
'primary_header_name': 'internal_settings_generated.h',
'settings': self.json5_file.name_dictionaries,
+ 'header_guard': self.make_header_guard(self._relative_output_dir + self._FILE_BASENAME + '.h')
}
@template_expander.use_jinja('templates/internal_settings_generated.h.tmpl', filters=filters)
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_names.py b/chromium/third_party/blink/renderer/build/scripts/make_names.py
index 99f8a8f2586..dba17c66a1d 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_names.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_names.py
@@ -35,19 +35,19 @@ import json5_generator
import template_expander
import name_utilities
+
def _symbol(entry):
if entry['Symbol'] is not None:
return entry['Symbol']
- # FIXME: Remove this special case for the ugly x-webkit-foo attributes.
- if entry['name'].original.startswith('-webkit-'):
- return entry['name'].original.replace('-', '_')[1:]
- return name_utilities.cpp_name(entry).replace('-', '_').replace(' ', '_')
+ return 'k' + entry['name'].to_upper_camel_case()
class MakeNamesWriter(json5_generator.Writer):
default_parameters = {
'Conditional': {}, # FIXME: Add support for Conditional.
'ImplementedAs': {},
+ # This is not used in make_names,py, but used in make_event_factory.py.
+ 'interfaceHeaderDir': {},
'RuntimeEnabled': {}, # What should we do for runtime-enabled features?
'Symbol': {},
}
@@ -59,7 +59,6 @@ class MakeNamesWriter(json5_generator.Writer):
filters = {
'cpp_name': name_utilities.cpp_name,
'hash': hasher.hash,
- 'script_name': name_utilities.script_name,
'symbol': _symbol,
}
@@ -70,7 +69,13 @@ class MakeNamesWriter(json5_generator.Writer):
suffix = self.json5_file.metadata['suffix'].strip('"')
export = self.json5_file.metadata['export'].strip('"')
- assert namespace, 'A namespace is required.'
+ if not namespace:
+ raise ValueError('A namespace is required.')
+ # https://google.github.io/styleguide/cppguide.html#Namespace_Names
+ if namespace.lower() != namespace:
+ raise ValueError('The namespace field should be lower-cased. ' +
+ '"%s" is specified in %s.' %
+ (namespace, json5_file_path))
basename, _ = os.path.splitext(os.path.basename(json5_file_path[0]))
self._outputs = {
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_origin_trials.py b/chromium/third_party/blink/renderer/build/scripts/make_origin_trials.py
index 5a72aa3169c..465636c03f6 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_origin_trials.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_origin_trials.py
@@ -89,6 +89,7 @@ class OriginTrialsWriter(make_runtime_features.RuntimeFeatureWriter):
'origin_trial_features': self._origin_trial_features,
'implied_origin_trial_features': self._implied_mappings,
'input_files': self._input_files,
+ 'header_guard': self._header_guard,
}
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_qualified_names.py b/chromium/third_party/blink/renderer/build/scripts/make_qualified_names.py
index 9957831019f..1b3bdaa039b 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_qualified_names.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_qualified_names.py
@@ -40,7 +40,7 @@ from json5_generator import Json5File
def _symbol(entry):
- return entry['name'].original.replace('-', '_')
+ return 'k' + entry['name'].to_upper_camel_case()
class MakeQualifiedNamesWriter(json5_generator.Writer):
@@ -85,10 +85,10 @@ class MakeQualifiedNamesWriter(json5_generator.Writer):
self.attrs_json5_file.merge_from(self.aria_reader.attributes_list())
self.namespace = self._metadata('namespace')
+ cpp_namespace = self.namespace.lower() + '_names'
+ namespace_prefix = self._metadata('namespacePrefix') or 'k'
- namespace_prefix = self._metadata('namespacePrefix') or self.namespace.lower()
namespace_uri = self._metadata('namespaceURI')
-
use_namespace_for_attrs = self.attrs_json5_file.metadata['attrsNullNamespace'] is None
self._outputs = {
@@ -98,6 +98,7 @@ class MakeQualifiedNamesWriter(json5_generator.Writer):
qualified_header = self._relative_output_dir + self.namespace.lower() + '_names.h'
self._template_context = {
'attrs': self.attrs_json5_file.name_dictionaries,
+ 'cpp_namespace': cpp_namespace,
'export': self._metadata('export'),
'header_guard': self.make_header_guard(qualified_header),
'input_files': self._input_files,
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_runtime_features.py b/chromium/third_party/blink/renderer/build/scripts/make_runtime_features.py
index f9efefe7a5c..a17e488f0b4 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_runtime_features.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_runtime_features.py
@@ -59,6 +59,7 @@ class RuntimeFeatureWriter(json5_generator.Writer):
feature['enabled_condition'] = enabled_condition
self._standard_features = [feature for feature in self._features if not feature['custom']]
self._origin_trial_features = [feature for feature in self._features if feature['origin_trial_feature_name']]
+ self._header_guard = self.make_header_guard(self._relative_output_dir + self.file_basename + '.h')
@staticmethod
def _data_member_name(str_or_converter):
@@ -77,6 +78,7 @@ class RuntimeFeatureWriter(json5_generator.Writer):
'input_files': self._input_files,
'standard_features': self._standard_features,
'origin_trial_controlled_features': self._origin_trial_features,
+ 'header_guard': self._header_guard,
}
@template_expander.use_jinja('templates/' + file_basename + '.h.tmpl')
@@ -95,13 +97,14 @@ class RuntimeFeatureTestHelpersWriter(json5_generator.Writer):
def __init__(self, json5_file_path, output_dir):
super(RuntimeFeatureTestHelpersWriter, self).__init__(json5_file_path, output_dir)
self._outputs = {('testing/' + self.file_basename + '.h'): self.generate_header}
-
self._features = self.json5_file.name_dictionaries
+ self._header_guard = self.make_header_guard(self._relative_output_dir + self.file_basename + '.h')
def _template_inputs(self):
return {
'features': self._features,
'input_files': self._input_files,
+ 'header_guard': self._header_guard,
}
@template_expander.use_jinja('templates/' + file_basename + '.h.tmpl')
diff --git a/chromium/third_party/blink/renderer/build/scripts/make_settings.py b/chromium/third_party/blink/renderer/build/scripts/make_settings.py
index 4f2752ad33f..b463bee6e48 100755
--- a/chromium/third_party/blink/renderer/build/scripts/make_settings.py
+++ b/chromium/third_party/blink/renderer/build/scripts/make_settings.py
@@ -73,6 +73,7 @@ class MakeSettingsWriter(json5_generator.Writer):
self._template_context = {
'input_files': self._input_files,
'settings': self.json5_file.name_dictionaries,
+ 'header_guard': self.make_header_guard(self._relative_output_dir + 'settings_macros.h')
}
@template_expander.use_jinja('templates/settings_macros.h.tmpl', filters=filters)
diff --git a/chromium/third_party/blink/renderer/build/scripts/media_feature_symbol.py b/chromium/third_party/blink/renderer/build/scripts/media_feature_symbol.py
index f9d51e96a7a..10d8a10f354 100644
--- a/chromium/third_party/blink/renderer/build/scripts/media_feature_symbol.py
+++ b/chromium/third_party/blink/renderer/build/scripts/media_feature_symbol.py
@@ -3,23 +3,14 @@
# found in the LICENSE file.
+from blinkbuild.name_style_converter import NameStyleConverter
+
+
def mediaFeatureSymbol(entry, suffix):
name = entry['name'].original
if name.startswith('-webkit-'):
name = name[8:]
-
- foundDash = False
- newName = ""
- for chr in name:
- if chr == '-':
- foundDash = True
- continue
- if foundDash:
- chr = chr.upper()
- foundDash = False
- newName = newName + chr
- newName = newName + suffix
- return newName
+ return 'k' + NameStyleConverter(name).to_upper_camel_case() + suffix
def getMediaFeatureSymbolWithSuffix(suffix):
diff --git a/chromium/third_party/blink/renderer/build/scripts/name_utilities.py b/chromium/third_party/blink/renderer/build/scripts/name_utilities.py
index d6afcc029e7..2ef88dad080 100644
--- a/chromium/third_party/blink/renderer/build/scripts/name_utilities.py
+++ b/chromium/third_party/blink/renderer/build/scripts/name_utilities.py
@@ -26,15 +26,9 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-import os.path
-
from blinkbuild.name_style_converter import NameStyleConverter
-def script_name(entry):
- return os.path.basename(entry['name'].original)
-
-
def cpp_bool(value):
if value is True:
return 'true'
@@ -46,7 +40,7 @@ def cpp_bool(value):
def cpp_name(entry):
- return entry['ImplementedAs'] or script_name(entry)
+ return entry['ImplementedAs'] or entry['name'].original
def enum_for_css_keyword(keyword):
diff --git a/chromium/third_party/blink/renderer/build/scripts/rule_bison.py b/chromium/third_party/blink/renderer/build/scripts/rule_bison.py
index 7f17e0f22d5..9e88f1c3915 100755
--- a/chromium/third_party/blink/renderer/build/scripts/rule_bison.py
+++ b/chromium/third_party/blink/renderer/build/scripts/rule_bison.py
@@ -42,6 +42,8 @@ import os.path
import subprocess
import sys
+from blinkbuild.name_style_converter import NameStyleConverter
+
assert len(sys.argv) == 4 or len(sys.argv) == 5
inputFile = sys.argv[1]
@@ -105,9 +107,12 @@ os.unlink(outputHTmp)
# Rewrite the generated header with #include guards.
outputH = os.path.join(outputDir, inputRoot + '.h')
+outputHInGen = outputH.replace('gen/', '')
+headerGuard = NameStyleConverter(outputHInGen).to_header_guard()
+
outputHFile = open(outputH, 'w')
-print >>outputHFile, '#ifndef %sH' % inputRoot
-print >>outputHFile, '#define %sH' % inputRoot
+print >>outputHFile, '#ifndef %s' % headerGuard
+print >>outputHFile, '#define %s' % headerGuard
print >>outputHFile, outputHContents
-print >>outputHFile, '#endif'
+print >>outputHFile, '#endif // %s' % headerGuard
outputHFile.close()
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl
index 96d8303736e..96ede7f9df0 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/element_factory.cc.tmpl
@@ -31,10 +31,10 @@ static {{namespace}}Element* {{namespace}}{{tag|symbol}}Constructor(
const CreateElementFlags flags) {
{% if tag.runtimeEnabled %}
if (!RuntimeEnabledFeatures::{{tag.runtimeEnabled}}Enabled())
- return {{fallback_interface}}::Create({{namespace}}Names::{{tag|symbol}}Tag, document);
+ return {{fallback_interface}}::Create({{cpp_namespace}}::{{tag|symbol}}Tag, document);
{% endif %}
return {{tag.interface}}::Create(
- {%- if tag.multipleTagNames %}{{namespace}}Names::{{tag|symbol}}Tag, {% endif -%}
+ {%- if tag.multipleTagNames %}{{cpp_namespace}}::{{tag|symbol}}Tag, {% endif -%}
document
{%- if tag.constructorNeedsCreateElementFlags %}, flags{% endif -%}
);
@@ -53,7 +53,7 @@ static void create{{namespace}}FunctionMap() {
// compile in MSVC. If tags list is empty, add check to skip this.
static const Create{{namespace}}FunctionMapData data[] = {
{% for tag in tags|sort if not tag.noConstructor %}
- { {{namespace}}Names::{{tag|symbol}}Tag, {{namespace}}{{tag|symbol}}Constructor },
+ { {{cpp_namespace}}::{{tag|symbol}}Tag, {{namespace}}{{tag|symbol}}Constructor },
{% endfor %}
};
for (size_t i = 0; i < arraysize(data); i++)
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/element_lookup_trie.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/element_lookup_trie.cc.tmpl
index 8c5096044e0..2eab64f679e 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/element_lookup_trie.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/element_lookup_trie.cc.tmpl
@@ -11,12 +11,12 @@
namespace blink {
-using namespace {{namespace}}Names;
+using namespace {{namespace|lower}}_names;
const AtomicString& lookup{{namespace}}Tag(const UChar* data, unsigned length) {
DCHECK(data);
DCHECK(length);
- {% macro trie_return_statement(tag) %}{{tag}}Tag.LocalName(){% endmacro %}
+ {% macro trie_return_statement(tag) %}{{tag|symbol}}Tag.LocalName(){% endmacro %}
{{ trie_length_switch(length_tries, trie_return_statement, false) | indent(4) }}
return g_null_atom;
}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/element_type_helpers.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/element_type_helpers.h.tmpl
index d0f65a3f7ba..7b4a4578b6a 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/element_type_helpers.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/element_type_helpers.h.tmpl
@@ -23,7 +23,7 @@ inline bool Is{{tag.interface}}(const {{namespace}}Element& element) {
if (!RuntimeEnabledFeatures::{{tag.runtimeEnabled}}Enabled())
return false;
{% endif %}
- return element.HasTagName({{namespace}}Names::{{tag|symbol}}Tag);
+ return element.HasTagName({{cpp_namespace}}::{{tag|symbol}}Tag);
}
inline bool Is{{tag.interface}}(const {{namespace}}Element* element) {
return element && Is{{tag.interface}}(*element);
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/event_factory.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/event_factory.cc.tmpl
index 1fe511bb71c..498baf402ef 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/event_factory.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/event_factory.cc.tmpl
@@ -18,14 +18,14 @@
namespace blink {
Event* Event{{suffix}}Factory::Create(ExecutionContext* executionContext, const String& type) {
- {% for event in events if event|script_name|create_event_whitelist or event|script_name|create_event_measure_whitelist %}
- {% if event|script_name|create_event_whitelist or event|script_name|create_event_measure_whitelist %}
- if (DeprecatedEqualIgnoringCase(type, "{{event|script_name}}"){% if event.RuntimeEnabled %} && RuntimeEnabledFeatures::{{event.RuntimeEnabled}}(){% endif %}) {
+ {% for event in events if event|name|create_event_whitelist or event|name|create_event_measure_whitelist %}
+ {% if event|name|create_event_whitelist or event|name|create_event_measure_whitelist %}
+ if (DeprecatedEqualIgnoringCase(type, "{{event|name}}"){% if event.RuntimeEnabled %} && RuntimeEnabledFeatures::{{event.RuntimeEnabled}}(){% endif %}) {
{% else %}
- if (type == "{{event|script_name}}"{% if event.RuntimeEnabled %} && RuntimeEnabledFeatures::{{event.RuntimeEnabled}}(){% endif %}) {
+ if (type == "{{event|name}}"{% if event.RuntimeEnabled %} && RuntimeEnabledFeatures::{{event.RuntimeEnabled}}(){% endif %}) {
{% endif %}
- {% if not event|script_name|create_event_whitelist %}
- UseCounter::Count(executionContext, WebFeature::k{{event|script_name|measure_name}});
+ {% if not event|name|create_event_whitelist %}
+ UseCounter::Count(executionContext, WebFeature::k{{event|name|measure_name}});
{% endif %}
return {{event|cpp_name}}::Create();
}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_inl.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_inl.h.tmpl
index 92f0d113554..86d48b872e9 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_inl.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_inl.h.tmpl
@@ -5,8 +5,8 @@
{% from 'macros.tmpl' import source_files_for_generated_file %}
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef {{file.header_name.upper()}}_H
-#define {{file.header_name.upper()}}_H
+#ifndef {{header_guard}}
+#define {{header_guard}}
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
@@ -80,4 +80,4 @@ inline void {{probe.name}}({{params_list(probe)}}) {
} // namespace probe
} // namespace blink
-#endif // !defined({{file.header_name.upper()}}_H)
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/internal_runtime_flags.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/internal_runtime_flags.h.tmpl
index 8f4a96e3fb5..bcc131bfc92 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/internal_runtime_flags.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/internal_runtime_flags.h.tmpl
@@ -3,8 +3,8 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef InternalRuntimeFlags_h
-#define InternalRuntimeFlags_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -18,9 +18,11 @@ class InternalRuntimeFlags : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
static InternalRuntimeFlags* create() {
- return new InternalRuntimeFlags;
+ return MakeGarbageCollected<InternalRuntimeFlags>();
}
+ InternalRuntimeFlags() {}
+
// These are reset between layout tests from Internals::resetToConsistentState
// using RuntimeEnabledFeatures::Backup.
{% for feature in standard_features if feature.settable_from_internals %}
@@ -38,11 +40,8 @@ class InternalRuntimeFlags : public ScriptWrappable {
{% endif %}
}
{% endfor %}
-
- private:
- InternalRuntimeFlags() {}
};
-} // namespace blink
+} // namespace blink
-#endif // InternalRuntimeFlags_h
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl
index 50a86395612..7933bd1896f 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/internal_settings_generated.h.tmpl
@@ -3,13 +3,13 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef InternalSettingsGenerated_h
-#define InternalSettingsGenerated_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
+#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
-#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -37,6 +37,6 @@ class InternalSettingsGenerated : public ScriptWrappable {
{% endfor %}
};
-} // namespace blink
+} // namespace blink
-#endif // InternalSettingsGenerated_h
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl
index 8be40d6920a..9d0a3104de7 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/make_names.cc.tmpl
@@ -8,18 +8,18 @@
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
-namespace {{namespace}}Names {
+namespace {{namespace}} {
-void* {{suffix}}NamesStorage[{{namespace}}{{suffix}}NamesCount * ((sizeof(AtomicString) + sizeof(void *) - 1) / sizeof(void *))];
+void* {{suffix|lower}}names_storage[k{{suffix}}NamesCount * ((sizeof(AtomicString) + sizeof(void *) - 1) / sizeof(void *))];
{% for entry in entries|sort(attribute='name', case_sensitive=True) %}
-const AtomicString& {{entry|symbol}} = reinterpret_cast<AtomicString*>(&{{suffix}}NamesStorage)[{{loop.index0}}];
+const AtomicString& {{entry|symbol}} = reinterpret_cast<AtomicString*>(&{{suffix|lower}}names_storage)[{{loop.index0}}];
{% endfor %}
-void init{{suffix}}() {
- static bool isLoaded = false;
- if (isLoaded) return;
- isLoaded = true;
+void Init{{suffix}}() {
+ static bool is_loaded = false;
+ if (is_loaded) return;
+ is_loaded = true;
struct NameEntry {
const char* name;
@@ -33,12 +33,12 @@ void init{{suffix}}() {
{% endfor %}
};
- for (size_t i = 0; i < arraysize(kNames); i++) {
- StringImpl* stringImpl = StringImpl::CreateStatic(kNames[i].name, kNames[i].length, kNames[i].hash);
- void* address = reinterpret_cast<AtomicString*>(&{{suffix}}NamesStorage) + i;
- new (address) AtomicString(stringImpl);
+ for (size_t i = 0; i < arraysize(kNames); ++i) {
+ StringImpl* impl = StringImpl::CreateStatic(kNames[i].name, kNames[i].length, kNames[i].hash);
+ void* address = reinterpret_cast<AtomicString*>(&{{suffix|lower}}names_storage) + i;
+ new (address) AtomicString(impl);
}
}
-} // {{namespace}}Names
-} // namespace blink
+} // namespace {{namespace}}
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/make_names.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/make_names.h.tmpl
index 621c966d6ee..6b624979d16 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/make_names.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/make_names.h.tmpl
@@ -17,17 +17,17 @@
{% endif %}
namespace blink {
-namespace {{namespace}}Names {
+namespace {{namespace}} {
{% for entry in entries|sort %}
{{symbol_export}}extern const WTF::AtomicString& {{entry|symbol}};
{% endfor %}
-const unsigned {{namespace}}{{suffix}}NamesCount = {{entries|length}};
+constexpr unsigned k{{suffix}}NamesCount = {{entries|length}};
-{{symbol_export}}void init{{suffix}}();
+{{symbol_export}}void Init{{suffix}}();
-} // {{namespace}}Names
+} // namespace {{namespace}}
} // namespace blink
#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl
index 7bf6eeb8d7c..eacbbd47517 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.cc.tmpl
@@ -11,61 +11,59 @@
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
-namespace {{namespace}}Names {
-
-using namespace blink;
+namespace {{cpp_namespace}} {
DEFINE_GLOBAL(AtomicString, {{namespace_prefix}}NamespaceURI);
{% if tags %}
// Tags
-void* {{suffix}}TagStorage[{{namespace}}TagsCount * ((sizeof({{namespace}}QualifiedName) + sizeof(void *) - 1) / sizeof(void *))];
+void* tag_storage[kTagsCount * ((sizeof({{namespace}}QualifiedName) + sizeof(void *) - 1) / sizeof(void *))];
{% for tag in tags|sort(attribute='name', case_sensitive=True) %}
-const {{namespace}}QualifiedName& {{tag|symbol}}Tag = reinterpret_cast<{{namespace}}QualifiedName*>(&{{suffix}}TagStorage)[{{loop.index0}}];
+const {{namespace}}QualifiedName& {{tag|symbol}}Tag = reinterpret_cast<{{namespace}}QualifiedName*>(&tag_storage)[{{loop.index0}}];
{% endfor %}
-std::unique_ptr<const {{namespace}}QualifiedName*[]> get{{namespace}}Tags() {
- auto tags = std::make_unique<const {{namespace}}QualifiedName*[]>({{namespace}}TagsCount);
- for (size_t i = 0; i < {{namespace}}TagsCount; i++)
- tags[i] = reinterpret_cast<{{namespace}}QualifiedName*>(&{{suffix}}TagStorage) + i;
+std::unique_ptr<const {{namespace}}QualifiedName*[]> GetTags() {
+ auto tags = std::make_unique<const {{namespace}}QualifiedName*[]>(kTagsCount);
+ for (size_t i = 0; i < kTagsCount; ++i)
+ tags[i] = reinterpret_cast<{{namespace}}QualifiedName*>(&tag_storage) + i;
return tags;
}
{% endif %}
// Attributes
-void* {{suffix}}AttrStorage[{{namespace}}AttrsCount * ((sizeof(QualifiedName) + sizeof(void *) - 1) / sizeof(void *))];
+void* attr_storage[kAttrsCount * ((sizeof(QualifiedName) + sizeof(void *) - 1) / sizeof(void *))];
{% for attr in attrs|sort(attribute='name', case_sensitive=True) %}
-const QualifiedName& {{attr|symbol}}Attr = reinterpret_cast<QualifiedName*>(&{{suffix}}AttrStorage)[{{loop.index0}}];
+const QualifiedName& {{attr|symbol}}Attr = reinterpret_cast<QualifiedName*>(&attr_storage)[{{loop.index0}}];
{% endfor %}
{% if namespace != 'HTML' %}
-std::unique_ptr<const QualifiedName*[]> get{{namespace}}Attrs() {
- auto attrs = std::make_unique<const QualifiedName*[]>({{namespace}}AttrsCount);
- for (size_t i = 0; i < {{namespace}}AttrsCount; i++)
- attrs[i] = reinterpret_cast<QualifiedName*>(&{{suffix}}AttrStorage) + i;
+std::unique_ptr<const QualifiedName*[]> GetAttrs() {
+ auto attrs = std::make_unique<const QualifiedName*[]>(kAttrsCount);
+ for (size_t i = 0; i < kAttrsCount; ++i)
+ attrs[i] = reinterpret_cast<QualifiedName*>(&attr_storage) + i;
return attrs;
}
{% endif %}
-void init() {
+void Init() {
struct NameEntry {
const char* name;
unsigned hash;
unsigned char length;
- unsigned char isTag;
- unsigned char isAttr;
+ unsigned char is_tag;
+ unsigned char is_attr;
};
+ // Namespace
// Use placement new to initialize the globals.
- AtomicString {{namespace_prefix}}NS("{{namespace_uri}}");
+ AtomicString ns_uri("{{namespace_uri}}");
+ new ((void*)&{{namespace_prefix}}NamespaceURI) AtomicString(ns_uri);
- // Namespace
- new ((void*)&{{namespace_prefix}}NamespaceURI) AtomicString({{namespace_prefix}}NS);
{% set tagnames = tags|map(attribute='name')|list() %}
{% set attrnames = attrs|map(attribute='name')|list() %}
static const NameEntry kNames[] = {
@@ -78,31 +76,31 @@ void init() {
size_t tag_i = 0;
{% endif %}
size_t attr_i = 0;
- for (size_t i = 0; i < arraysize(kNames); i++) {
- StringImpl* stringImpl = StringImpl::CreateStatic(kNames[i].name, kNames[i].length, kNames[i].hash);
+ for (size_t i = 0; i < arraysize(kNames); ++i) {
+ StringImpl* impl = StringImpl::CreateStatic(kNames[i].name, kNames[i].length, kNames[i].hash);
{% if tags %}
- if (kNames[i].isTag) {
- void* address = reinterpret_cast<{{namespace}}QualifiedName*>(&{{suffix}}TagStorage) + tag_i;
- QualifiedName::CreateStatic(address, stringImpl, {{namespace_prefix}}NS);
- tag_i++;
+ if (kNames[i].is_tag) {
+ void* address = reinterpret_cast<{{namespace}}QualifiedName*>(&tag_storage) + tag_i;
+ QualifiedName::CreateStatic(address, impl, ns_uri);
+ ++tag_i;
}
- if (!kNames[i].isAttr)
+ if (!kNames[i].is_attr)
continue;
{% endif %}
- void* address = reinterpret_cast<QualifiedName*>(&{{suffix}}AttrStorage) + attr_i;
+ void* address = reinterpret_cast<QualifiedName*>(&attr_storage) + attr_i;
{% if use_namespace_for_attrs %}
- QualifiedName::CreateStatic(address, stringImpl, {{namespace_prefix}}NS);
+ QualifiedName::CreateStatic(address, impl, ns_uri);
{% else %}
- QualifiedName::CreateStatic(address, stringImpl);
+ QualifiedName::CreateStatic(address, impl);
{% endif %}
- attr_i++;
+ ++attr_i;
}
{% if tags %}
- DCHECK_EQ(tag_i, {{namespace}}TagsCount);
+ DCHECK_EQ(tag_i, kTagsCount);
{% endif %}
- DCHECK_EQ(attr_i, {{namespace}}AttrsCount);
+ DCHECK_EQ(attr_i, kAttrsCount);
}
-} // namespace {{namespace}}Names
+} // namespace {{cpp_namespace}}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.h.tmpl
index b4c5c86d63a..cb05c6c4315 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/make_qualified_names.h.tmpl
@@ -6,17 +6,18 @@
#ifndef {{header_guard}}
#define {{header_guard}}
+#include <memory>
+
{% if export == 'CORE_EXPORT' %}
#include "third_party/blink/renderer/core/core_export.h"
{% endif %}
#include "third_party/blink/renderer/core/dom/qualified_name.h"
-#include <memory>
namespace blink {
class {{namespace}}QualifiedName : public QualifiedName { };
-namespace {{namespace}}Names {
+namespace {{cpp_namespace}} {
{% set symbol_export = '%s ' % export if export else '' %}
// Namespace
@@ -33,18 +34,18 @@ namespace {{namespace}}Names {
{% endfor %}
{% if tags %}
-const unsigned {{namespace}}TagsCount = {{tags|count}};
-{{symbol_export}}std::unique_ptr<const {{namespace}}QualifiedName*[]> get{{namespace}}Tags();
+constexpr unsigned kTagsCount = {{tags|count}};
+{{symbol_export}}std::unique_ptr<const {{namespace}}QualifiedName*[]> GetTags();
{% endif %}
-const unsigned {{namespace}}AttrsCount = {{attrs|count}};
+constexpr unsigned kAttrsCount = {{attrs|count}};
{% if namespace != 'HTML' %}
-std::unique_ptr<const QualifiedName*[]> get{{namespace}}Attrs();
+std::unique_ptr<const QualifiedName*[]> GetAttrs();
{% endif %}
-void init();
+void Init();
-} // namespace {{namespace}}Names
+} // namespace {{cpp_namespace}}
} // namespace blink
#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl
index 7c2e355dd9b..7aa623dd1a7 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl
@@ -12,14 +12,14 @@ namespace blink {
{% for feature in features %}
{% if feature.origin_trial_feature_name %}
-const char OriginTrials::k{{feature.name}}TrialName[] = "{{feature.origin_trial_feature_name}}";
+const char origin_trials::k{{feature.name}}TrialName[] = "{{feature.origin_trial_feature_name}}";
{% endif %}
{% endfor %}
{% for feature in features %}
{% if feature.origin_trial_feature_name %}
-bool OriginTrials::{{feature.name}}Enabled(const ExecutionContext* executionContext) {
+bool origin_trials::{{feature.name}}Enabled(const ExecutionContext* executionContext) {
if (RuntimeEnabledFeatures::{{feature.name}}EnabledByRuntimeFlag())
return true;
{% if feature.origin_trial_os %}
@@ -30,6 +30,11 @@ bool OriginTrials::{{feature.name}}Enabled(const ExecutionContext* executionCont
{%- endfor %}
{% endif %}
+{%- for depends_on in feature.depends_on %}
+ if (!RuntimeEnabledFeatures::{{depends_on}}Enabled())
+ return false;
+{%- endfor %}
+
const OriginTrialContext* context = OriginTrialContext::From(executionContext);
if (!context) return false;
if (context->IsTrialEnabled(k{{feature.name}}TrialName))
@@ -52,7 +57,7 @@ bool OriginTrials::{{feature.name}}Enabled(const ExecutionContext* executionCont
{% endif %}
{% endfor %}
-Vector<AtomicString> OriginTrials::GetImpliedTrials(const String& trial_name) {
+Vector<AtomicString> origin_trials::GetImpliedTrials(const String& trial_name) {
{% for implied_by_name, implied_list in implied_origin_trial_features.items() %}
if (trial_name == k{{implied_by_name}}TrialName) {
Vector<AtomicString> implied_trials = {
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl
index ed530591361..7f4ff3ba4de 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl
@@ -3,21 +3,26 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef BLINK_CORE_ORIGIN_TRIALS_ORIGIN_TRIALS_H_
-#define BLINK_CORE_ORIGIN_TRIALS_ORIGIN_TRIALS_H_
+#ifndef {{header_guard}}
+#define {{header_guard}}
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
+#define ASSERT_ORIGIN_TRIAL(feature) \
+static_assert(std::is_same<decltype(::blink::origin_trials::feature##Enabled(\
+ nullptr)), bool>(), \
+ #feature " must be part of an origin trial");
+
namespace blink {
class ExecutionContext;
// A namespace with dynamic tests for experimental features which can be
// enabled by the origin trials framework via origin trial tokens.
-namespace OriginTrials {
+namespace origin_trials {
{% for feature in features %}
{% if feature.origin_trial_feature_name %}
@@ -33,8 +38,8 @@ CORE_EXPORT bool {{feature.name}}Enabled(const ExecutionContext*);
CORE_EXPORT Vector<AtomicString> GetImpliedTrials(const String& trial_name);
-} // namespace OriginTrials
+} // namespace origin_trials
-} // namespace blink
+} // namespace blink
-#endif // BLINK_CORE_ORIGIN_TRIALS_ORIGIN_TRIALS_H_
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl
index 09d869fad19..e3cff077041 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl
@@ -6,12 +6,11 @@
{{source_files_for_generated_file(template_file, input_files)}}
{% set sink_class = (name | to_singular) + "Sink" %}
-{% set sink_class_header = (header | to_singular) + "_sink" %}
{% set export_header = config["settings"]["export_header"] %}
{% set export_symbol = config["settings"]["export_symbol"] %}
-#ifndef {{sink_class_header.upper()}}_H
-#define {{sink_class_header.upper()}}_H
+#ifndef {{header_guard}}
+#define {{header_guard}}
#include <atomic>
@@ -75,4 +74,4 @@ class {{export_symbol}} {{sink_class}} : public GarbageCollectedFinalized<{{sink
} // namespace blink
-#endif // !defined({{sink_class_header.upper()}}_H)
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl
index 77be3bb3cda..b74af567130 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl
@@ -3,14 +3,13 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef RuntimeEnabledFeatures_h
-#define RuntimeEnabledFeatures_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
#include <string>
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -56,7 +55,7 @@ class PLATFORM_EXPORT RuntimeEnabledFeatures {
// to test whether the feature is unconditionally enabled (for example, by
// starting the browser with the appropriate command-line flag). However,
// that is almost always the incorrect check. Most renderer code should
- // be calling OriginTrials::<feature>Enabled() instead, to test if the
+ // be calling origin_trials::<feature>Enabled() instead, to test if the
// feature is enabled in a given context.
{% for feature in features %}
@@ -77,6 +76,6 @@ class PLATFORM_EXPORT RuntimeEnabledFeatures {
{% endfor %}
};
-} // namespace blink
+} // namespace blink
-#endif // RuntimeEnabledFeatures_h
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features_test_helpers.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features_test_helpers.h.tmpl
index a26579b3b3b..ba7399c844f 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features_test_helpers.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features_test_helpers.h.tmpl
@@ -3,8 +3,8 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef BLINK_PLATFORM_TESTING_RUNTIME_ENABLED_FEATURES_TEST_HELPERS_H_
-#define BLINK_PLATFORM_TESTING_RUNTIME_ENABLED_FEATURES_TEST_HELPERS_H_
+#ifndef {{header_guard}}
+#define {{header_guard}}
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -39,6 +39,6 @@ typedef ScopedRuntimeEnabledFeatureForTest<
RuntimeEnabledFeatures::Set{{feature.name}}Enabled>
Scoped{{feature.name}}ForTest;
{% endfor %}
-} // namespace blink
+} // namespace blink
-#endif // BLINK_PLATFORM_TESTING_RUNTIME_ENABLED_FEATURES_TEST_HELPERS_H_
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/settings_macros.h.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/settings_macros.h.tmpl
index 33c2220baa9..0ed1f533f06 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/settings_macros.h.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/settings_macros.h.tmpl
@@ -3,8 +3,8 @@
{{source_files_for_generated_file(template_file, input_files)}}
-#ifndef SettingsMacros_h
-#define SettingsMacros_h
+#ifndef {{header_guard}}
+#define {{header_guard}}
#define SETTINGS_GETTERS_AND_SETTERS \
{% for setting in settings %}
@@ -67,4 +67,4 @@ void Settings::SetFromStrings(const String& name, const String& value) { \
}
// End of SETTINGS_SETTER_BODIES.
-#endif // SettingsMacros_h
+#endif // {{header_guard}}
diff --git a/chromium/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl b/chromium/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl
index 657c373b880..6e234f3937a 100644
--- a/chromium/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl
+++ b/chromium/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl
@@ -16,8 +16,8 @@ bool WebOriginTrials::isTrialEnabled(const WebDocument* web_document, const WebS
if (!web_document) return false;
{% for feature in features %}
{% if feature.origin_trial_feature_name %}
- if (trial == OriginTrials::k{{feature.name}}TrialName)
- return OriginTrials::{{feature.name}}Enabled(*web_document);
+ if (trial == origin_trials::k{{feature.name}}TrialName)
+ return origin_trials::{{feature.name}}Enabled(*web_document);
{% endif %}
{% endfor %}
return false;
diff --git a/chromium/third_party/blink/renderer/controller/blink_initializer.cc b/chromium/third_party/blink/renderer/controller/blink_initializer.cc
index 90ff5526461..78dcd897a19 100644
--- a/chromium/third_party/blink/renderer/controller/blink_initializer.cc
+++ b/chromium/third_party/blink/renderer/controller/blink_initializer.cc
@@ -67,8 +67,10 @@ namespace {
class EndOfTaskRunner : public Thread::TaskObserver {
public:
- void WillProcessTask() override { AnimationClock::NotifyTaskStart(); }
- void DidProcessTask() override {
+ void WillProcessTask(const base::PendingTask&) override {
+ AnimationClock::NotifyTaskStart();
+ }
+ void DidProcessTask(const base::PendingTask&) override {
Microtask::PerformCheckpoint(V8PerIsolateData::MainThreadIsolate());
V8Initializer::ReportRejectedPromisesOnMainThread();
}
@@ -121,19 +123,14 @@ void InitializeCommon(Platform* platform,
GetBlinkInitializer().RegisterInterfaces(*registry);
- // currentThread is null if we are running on a thread without a message loop.
- if (Thread* current_thread = platform->CurrentThread()) {
- DCHECK(!g_end_of_task_runner);
- g_end_of_task_runner = new EndOfTaskRunner;
- current_thread->AddTaskObserver(g_end_of_task_runner);
- }
+ DCHECK(!g_end_of_task_runner);
+ g_end_of_task_runner = new EndOfTaskRunner;
+ Thread::Current()->AddTaskObserver(g_end_of_task_runner);
- if (Thread* main_thread = Platform::Current()->MainThread()) {
- scoped_refptr<base::SequencedTaskRunner> task_runner =
- main_thread->GetTaskRunner();
- if (task_runner)
- MemoryAblationExperiment::MaybeStartForRenderer(task_runner);
- }
+ scoped_refptr<base::SequencedTaskRunner> task_runner =
+ Thread::MainThread()->GetTaskRunner();
+ if (task_runner)
+ MemoryAblationExperiment::MaybeStartForRenderer(task_runner);
#if defined(OS_ANDROID)
// Initialize CrashMemoryMetricsReporterImpl in order to assure that memory
@@ -162,10 +159,10 @@ void CreateMainThreadAndInitialize(Platform* platform,
void BlinkInitializer::RegisterInterfaces(
service_manager::BinderRegistry& registry) {
ModulesInitializer::RegisterInterfaces(registry);
- Thread* main_thread = Platform::Current()->MainThread();
+ Thread* main_thread = Thread::MainThread();
// GetSingleThreadTaskRunner() uses GetTaskRunner() internally.
// crbug.com/781664
- if (!main_thread || !main_thread->GetTaskRunner())
+ if (!main_thread->GetTaskRunner())
return;
#if defined(OS_ANDROID)
diff --git a/chromium/third_party/blink/renderer/controller/blink_leak_detector.cc b/chromium/third_party/blink/renderer/controller/blink_leak_detector.cc
index 90554994c7a..d332220b6cf 100644
--- a/chromium/third_party/blink/renderer/controller/blink_leak_detector.cc
+++ b/chromium/third_party/blink/renderer/controller/blink_leak_detector.cc
@@ -25,7 +25,7 @@
namespace blink {
BlinkLeakDetector::BlinkLeakDetector()
- : delayed_gc_timer_(Platform::Current()->CurrentThread()->GetTaskRunner(),
+ : delayed_gc_timer_(Thread::Current()->GetTaskRunner(),
this,
&BlinkLeakDetector::TimerFiredGC) {}
@@ -98,7 +98,7 @@ void BlinkLeakDetector::TimerFiredGC(TimerBase*) {
V8GCController::CollectAllGarbageForTesting(
V8PerIsolateData::MainThreadIsolate(),
v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
- CoreInitializer::GetInstance().CollectAllGarbageForAnimationWorklet();
+ CoreInitializer::GetInstance().CollectAllGarbageForAnimationAndPaintWorklet();
// Note: Oilpan precise GC is scheduled at the end of the event loop.
// Inspect counters on the next event loop.
diff --git a/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.cc b/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.cc
index 8ac719293f8..c1d68eb9aa4 100644
--- a/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.cc
+++ b/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.cc
@@ -47,8 +47,8 @@ void DevToolsFrontendImpl::BindMojoRequest(
mojom::blink::DevToolsFrontendAssociatedRequest request) {
if (!local_frame)
return;
- local_frame->ProvideSupplement(
- new DevToolsFrontendImpl(*local_frame, std::move(request)));
+ local_frame->ProvideSupplement(MakeGarbageCollected<DevToolsFrontendImpl>(
+ *local_frame, std::move(request)));
}
// static
diff --git a/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.h b/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.h
index a2db8e68ce1..b5777f2a0ae 100644
--- a/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.h
+++ b/chromium/third_party/blink/renderer/controller/dev_tools_frontend_impl.h
@@ -61,13 +61,13 @@ class DevToolsFrontendImpl final
mojom::blink::DevToolsFrontendAssociatedRequest);
static DevToolsFrontendImpl* From(LocalFrame*);
+ DevToolsFrontendImpl(LocalFrame&,
+ mojom::blink::DevToolsFrontendAssociatedRequest);
~DevToolsFrontendImpl() override;
void DidClearWindowObject();
void Trace(blink::Visitor*) override;
private:
- DevToolsFrontendImpl(LocalFrame&,
- mojom::blink::DevToolsFrontendAssociatedRequest);
void DestroyOnHostGone();
// mojom::blink::DevToolsFrontend implementation.
diff --git a/chromium/third_party/blink/renderer/controller/oom_intervention_impl.cc b/chromium/third_party/blink/renderer/controller/oom_intervention_impl.cc
index 4bf6e8d8365..24b601ff70b 100644
--- a/chromium/third_party/blink/renderer/controller/oom_intervention_impl.cc
+++ b/chromium/third_party/blink/renderer/controller/oom_intervention_impl.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/controller/oom_intervention_impl.h"
+#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "third_party/blink/public/platform/platform.h"
@@ -11,7 +12,6 @@
#include "third_party/blink/renderer/controller/crash_memory_metrics_reporter_impl.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"
namespace blink {
@@ -23,9 +23,12 @@ void OomInterventionImpl::Create(mojom::blink::OomInterventionRequest request) {
}
OomInterventionImpl::OomInterventionImpl()
- : timer_(Platform::Current()->MainThread()->GetTaskRunner(),
+ : timer_(Thread::MainThread()->GetTaskRunner(),
this,
- &OomInterventionImpl::Check) {}
+ &OomInterventionImpl::Check),
+ delayed_report_timer_(Thread::MainThread()->GetTaskRunner(),
+ this,
+ &OomInterventionImpl::TimerFiredUMAReport) {}
OomInterventionImpl::~OomInterventionImpl() {}
@@ -53,7 +56,6 @@ OomInterventionMetrics OomInterventionImpl::GetCurrentMemoryMetrics() {
void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
- DCHECK(renderer_pause_enabled_ || navigate_ads_enabled_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
@@ -95,6 +97,11 @@ void OomInterventionImpl::Check(TimerBase*) {
// Notify V8GCForContextDispose that page navigation gc is needed when
// intervention runs, as it indicates that memory usage is high.
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
+
+ // Report the memory impact of intervention after 10, 20, 30 seconds.
+ metrics_at_intervention_ = current_memory;
+ number_of_report_needed_ = 3;
+ delayed_report_timer_.StartRepeating(TimeDelta::FromSeconds(10), FROM_HERE);
}
}
@@ -118,4 +125,41 @@ void OomInterventionImpl::ReportMemoryStats(
current_memory);
}
+void OomInterventionImpl::TimerFiredUMAReport(TimerBase*) {
+ OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
+ switch (number_of_report_needed_--) {
+ case 3:
+ base::UmaHistogramSparse(
+ "Memory.Experimental.OomIntervention.ReducedBlinkUsageAfter10secs",
+ current_memory.current_blink_usage_kb / 1024 -
+ metrics_at_intervention_.current_blink_usage_kb / 1024);
+ base::UmaHistogramSparse(
+ "Memory.Experimental.OomIntervention.ReducedRendererPMFAfter10secs",
+ current_memory.current_private_footprint_kb / 1024 -
+ metrics_at_intervention_.current_private_footprint_kb / 1024);
+ break;
+ case 2:
+ base::UmaHistogramSparse(
+ "Memory.Experimental.OomIntervention.ReducedBlinkUsageAfter20secs",
+ current_memory.current_blink_usage_kb / 1024 -
+ metrics_at_intervention_.current_blink_usage_kb / 1024);
+ base::UmaHistogramSparse(
+ "Memory.Experimental.OomIntervention.ReducedRendererPMFAfter20secs",
+ current_memory.current_private_footprint_kb / 1024 -
+ metrics_at_intervention_.current_private_footprint_kb / 1024);
+ break;
+ case 1:
+ base::UmaHistogramSparse(
+ "Memory.Experimental.OomIntervention.ReducedBlinkUsageAfter30secs",
+ current_memory.current_blink_usage_kb / 1024 -
+ metrics_at_intervention_.current_blink_usage_kb / 1024);
+ base::UmaHistogramSparse(
+ "Memory.Experimental.OomIntervention.ReducedRendererPMFAfter30secs",
+ current_memory.current_private_footprint_kb / 1024 -
+ metrics_at_intervention_.current_private_footprint_kb / 1024);
+ delayed_report_timer_.Stop();
+ break;
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/controller/oom_intervention_impl.h b/chromium/third_party/blink/renderer/controller/oom_intervention_impl.h
index 9fb26d818d0..1b23b81270e 100644
--- a/chromium/third_party/blink/renderer/controller/oom_intervention_impl.h
+++ b/chromium/third_party/blink/renderer/controller/oom_intervention_impl.h
@@ -47,6 +47,8 @@ class CONTROLLER_EXPORT OomInterventionImpl
void ReportMemoryStats(OomInterventionMetrics& current_memory);
+ void TimerFiredUMAReport(TimerBase*);
+
mojom::blink::DetectionArgsPtr detection_args_;
mojom::blink::OomInterventionHostPtr host_;
@@ -54,6 +56,9 @@ class CONTROLLER_EXPORT OomInterventionImpl
bool navigate_ads_enabled_ = false;
TaskRunnerTimer<OomInterventionImpl> timer_;
std::unique_ptr<ScopedPagePauser> pauser_;
+ OomInterventionMetrics metrics_at_intervention_;
+ int number_of_report_needed_ = 0;
+ TaskRunnerTimer<OomInterventionImpl> delayed_report_timer_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/controller/oom_intervention_impl_test.cc b/chromium/third_party/blink/renderer/controller/oom_intervention_impl_test.cc
index aeb5f8945cc..be703563197 100644
--- a/chromium/third_party/blink/renderer/controller/oom_intervention_impl_test.cc
+++ b/chromium/third_party/blink/renderer/controller/oom_intervention_impl_test.cc
@@ -101,7 +101,7 @@ class OomInterventionImplTest : public testing::Test {
protected:
std::unique_ptr<MockOomInterventionImpl> intervention_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
std::unique_ptr<SimRequest> main_resource_;
};
diff --git a/chromium/third_party/blink/renderer/core/BUILD.gn b/chromium/third_party/blink/renderer/core/BUILD.gn
index 5111a0aa6e4..0eacbb576ae 100644
--- a/chromium/third_party/blink/renderer/core/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/BUILD.gn
@@ -4,16 +4,16 @@
import("//build/config/chromecast_build.gni")
import("//build/config/compiler/compiler.gni")
-import("//build/toolchain/toolchain.gni")
import("//build/config/ui.gni")
import("//build/split_static_library.gni")
+import("//build/toolchain/toolchain.gni")
import("//testing/libfuzzer/fuzzer_test.gni")
import("//third_party/blink/renderer/bindings/bindings.gni")
import("//third_party/blink/renderer/bindings/modules/v8/generated.gni")
import("//third_party/blink/renderer/bindings/scripts/scripts.gni")
+import("//third_party/blink/renderer/build/scripts/scripts.gni")
import("//third_party/blink/renderer/config.gni")
import("//third_party/blink/renderer/core/core.gni")
-import("//third_party/blink/renderer/build/scripts/scripts.gni")
import("//third_party/blink/renderer/modules/modules_idl_files.gni")
import("//third_party/blink/renderer/platform/platform_generated.gni")
import("//third_party/protobuf/proto_library.gni")
@@ -267,6 +267,7 @@ jumbo_source_set("testing") {
"fetch/testing/internals_fetch.h",
"fetch/testing/worker_internals_fetch.cc",
"fetch/testing/worker_internals_fetch.h",
+ "html/forms/mock_file_chooser.h",
"testing/callback_function_test.cc",
"testing/callback_function_test.h",
"testing/death_aware_script_wrappable.cc",
@@ -282,13 +283,13 @@ jumbo_source_set("testing") {
"testing/gc_object_liveness_observer.h",
"testing/gc_observation.cc",
"testing/gc_observation.h",
+ "testing/hit_test_layer_rect.h",
+ "testing/hit_test_layer_rect_list.cc",
+ "testing/hit_test_layer_rect_list.h",
"testing/internal_settings.cc",
"testing/internal_settings.h",
"testing/internals.cc",
"testing/internals.h",
- "testing/layer_rect.h",
- "testing/layer_rect_list.cc",
- "testing/layer_rect_list.h",
"testing/mock_hyphenation.cc",
"testing/mock_hyphenation.h",
"testing/null_execution_context.cc",
@@ -367,7 +368,8 @@ generate_event_interfaces("core_event_interfaces") {
"invisible_dom/activate_invisible_event.idl",
"mojo/test/mojo_interface_request_event.idl",
]
- output_file = "core/event_names.json5"
+
+ output_file = "core/event_interface_names.json5"
}
# generated_testing_idls -------------------------------------------------------
@@ -447,7 +449,7 @@ action("generated_testing_idls_internal_runtime_flags") {
css_properties("make_core_generated_computed_style_initial_values") {
script = "../build/scripts/core/style/make_computed_style_initial_values.py"
- in_files = [ "css/computed_style_extra_fields.json5" ]
+ in_files = [ "style/computed_style_extra_fields.json5" ]
other_inputs = [ "../build/scripts/core/style/templates/computed_style_initial_values.h.tmpl" ]
outputs = [
"$blink_core_output_dir/style/computed_style_initial_values.h",
@@ -455,15 +457,18 @@ css_properties("make_core_generated_computed_style_initial_values") {
}
css_properties("make_core_generated_computed_style_base") {
- script = "../build/scripts/make_computed_style_base.py"
+ script = "../build/scripts/core/style/make_computed_style_base.py"
in_files = [
- "css/computed_style_extra_fields.json5",
- "css/computed_style_diff_functions.json5",
+ "style/computed_style_extra_fields.json5",
+ "style/computed_style_diff_functions.json5",
"css/css_value_keywords.json5",
"css/css_properties_ranking.json5",
"css/css_group_config.json5",
]
other_inputs = [
+ "../build/scripts/core/style/templates/computed_style_base.cc.tmpl",
+ "../build/scripts/core/style/templates/computed_style_base.h.tmpl",
+ "../build/scripts/core/style/templates/computed_style_base_constants.h.tmpl",
"../build/scripts/templates/fields/field.tmpl",
"../build/scripts/templates/fields/group.tmpl",
"../build/scripts/templates/fields/base.tmpl",
@@ -472,27 +477,24 @@ css_properties("make_core_generated_computed_style_base") {
"../build/scripts/templates/fields/primitive.tmpl",
"../build/scripts/templates/fields/monotonic_flag.tmpl",
"../build/scripts/templates/fields/external.tmpl",
- "../build/scripts/templates/computed_style_base.h.tmpl",
- "../build/scripts/templates/computed_style_base.cc.tmpl",
- "../build/scripts/templates/computed_style_base_constants.h.tmpl",
"../build/scripts/keyword_utils.py",
]
outputs = [
- "$blink_core_output_dir/computed_style_base.h",
- "$blink_core_output_dir/computed_style_base.cc",
- "$blink_core_output_dir/computed_style_base_constants.h",
+ "$blink_core_output_dir/style/computed_style_base.cc",
+ "$blink_core_output_dir/style/computed_style_base.h",
+ "$blink_core_output_dir/style/computed_style_base_constants.h",
]
}
css_properties("make_core_generated_css_value_id_mappings") {
- script = "../build/scripts/make_css_value_id_mappings.py"
+ script = "../build/scripts/core/css/make_css_value_id_mappings.py"
in_files = [ "css/css_value_keywords.json5" ]
other_inputs = [
- "../build/scripts/templates/css_value_id_mappings_generated.h.tmpl",
+ "../build/scripts/core/css/templates/css_value_id_mappings_generated.h.tmpl",
"../build/scripts/keyword_utils.py",
]
outputs = [
- "$blink_core_output_dir/css_value_id_mappings_generated.h",
+ "$blink_core_output_dir/css/css_value_id_mappings_generated.h",
]
}
@@ -826,6 +828,7 @@ css_properties("make_core_generated_css_longhand_property_classes") {
"$blink_core_output_dir/css/properties/longhands/text_decoration_color.h",
"$blink_core_output_dir/css/properties/longhands/text_decoration_color.cc",
"$blink_core_output_dir/css/properties/longhands/text_decoration_line.h",
+ "$blink_core_output_dir/css/properties/longhands/text_decoration_skip_ink.h",
"$blink_core_output_dir/css/properties/longhands/text_decoration_style.h",
"$blink_core_output_dir/css/properties/longhands/text_indent.h",
"$blink_core_output_dir/css/properties/longhands/text_justify.h",
@@ -1127,15 +1130,15 @@ css_properties("make_core_generated_css_shorthand_property_classes") {
}
css_properties("make_core_generated_css_property_names") {
- script = "../build/scripts/make_css_property_names.py"
+ script = "../build/scripts/core/css/make_css_property_names.py"
other_inputs = [
"../build/scripts/gperf.py",
- "../build/scripts/templates/css_property_names.cc.tmpl",
- "../build/scripts/templates/css_property_names.h.tmpl",
+ "../build/scripts/core/css/templates/css_property_names.cc.tmpl",
+ "../build/scripts/core/css/templates/css_property_names.h.tmpl",
]
outputs = [
- "$blink_core_output_dir/css_property_names.cc",
- "$blink_core_output_dir/css_property_names.h",
+ "$blink_core_output_dir/css/css_property_names.cc",
+ "$blink_core_output_dir/css/css_property_names.h",
]
}
@@ -1160,6 +1163,8 @@ code_generator("make_core_generated_atrule_names") {
code_generator("make_core_generated_media_features") {
script = "../build/scripts/core/css/make_media_features.py"
json_inputs = [ "css/media_feature_names.json5" ]
+ other_inputs =
+ scripts_for_json5_files + [ "../build/scripts/media_feature_symbol.py" ]
templates = [ "../build/scripts/core/css/templates/media_features.h.tmpl" ]
outputs = [
"$blink_core_output_dir/css/media_features.h",
@@ -1269,7 +1274,7 @@ process_json5_files("make_core_generated_svg_element_type_helpers") {
make_event_factory("make_core_generated_event_factory") {
in_files = [
- "$blink_core_output_dir/event_names.json5",
+ "$blink_core_output_dir/event_interface_names.json5",
"events/event_interface_aliases.json5",
]
outputs = [
@@ -1286,7 +1291,8 @@ code_generator("make_core_generated_media_feature_names") {
"../build/scripts/templates/make_names.cc.tmpl",
"../build/scripts/templates/make_names.h.tmpl",
]
- other_inputs = make_names_files
+ other_inputs =
+ make_names_files + [ "../build/scripts/media_feature_symbol.py" ]
outputs = [
"$blink_core_output_dir/css/media_feature_names.cc",
"$blink_core_output_dir/css/media_feature_names.h",
@@ -1299,7 +1305,7 @@ make_names("make_core_generated_media_type_names") {
}
make_names("make_core_generated_event_names") {
- in_files = [ "$blink_core_output_dir/event_names.json5" ]
+ in_files = [ "$blink_core_output_dir/event_interface_names.json5" ]
output_dir = blink_core_output_dir
}
@@ -1376,7 +1382,7 @@ action("make_minimized_css") {
script = "../build/scripts/minimize_css.py"
inputs = [
- "css/html.css",
+ "html/resources/html.css",
]
outputs = [
"$blink_core_output_dir/html.css",
@@ -1412,15 +1418,15 @@ action("make_core_generated_html_entity_table") {
action("make_core_generated_css_tokenizer_codepoints") {
visibility = [] # Allow re-assignment of list.
visibility = [ ":*" ]
- script = "../build/scripts/make_css_tokenizer_codepoints.py"
+ script = "../build/scripts/core/css/make_css_tokenizer_codepoints.py"
outputs = [
- "$blink_core_output_dir/css_tokenizer_codepoints.cc",
+ "$blink_core_output_dir/css/css_tokenizer_codepoints.cc",
]
args = [
"--output_dir",
- rel_blink_core_gen_dir,
+ "$rel_blink_core_gen_dir/css",
]
if (is_mac && !use_system_xcode) {
args += [
@@ -1435,21 +1441,21 @@ action("make_core_generated_css_tokenizer_codepoints") {
action("make_core_generated_css_primitive_value_unit_trie") {
visibility = [] # Allow re-assignment of list.
visibility = [ ":*" ]
- script = "../build/scripts/make_css_primitive_value_unit_trie.py"
+ script = "../build/scripts/core/css/make_css_primitive_value_unit_trie.py"
input_file = "css/css_primitive_value_units.json5"
inputs = make_trie_helpers_files + [
input_file,
- "../build/scripts/templates/css_primitive_value_unit_trie.cc.tmpl",
+ "../build/scripts/core/css/templates/css_primitive_value_unit_trie.cc.tmpl",
]
outputs = [
- "$blink_core_output_dir/css_primitive_value_unit_trie.cc",
+ "$blink_core_output_dir/css/css_primitive_value_unit_trie.cc",
]
args = [
rebase_path(input_file, root_build_dir),
"--output_dir",
- rel_blink_core_gen_dir,
+ "$rel_blink_core_gen_dir/css",
]
if (is_mac && !use_system_xcode) {
args += [
@@ -1573,11 +1579,10 @@ targets_generating_sources = [
":make_core_generated_css_primitive_value_unit_trie",
":make_core_generated_computed_style_initial_values",
":make_core_generated_computed_style_base",
- ":make_core_generated_css_value_id_mappings",
- ":make_core_generated_css_property_baseclass",
":make_core_generated_css_longhand_property_classes",
- ":make_core_generated_css_shorthand_property_classes",
+ ":make_core_generated_css_property_baseclass",
":make_core_generated_css_property_names",
+ ":make_core_generated_css_shorthand_property_classes",
":make_core_generated_css_value_id_mappings",
":make_core_generated_cssom_types",
":make_core_generated_event_factory",
@@ -1724,14 +1729,18 @@ jumbo_source_set("unit_tests") {
"css/css_computed_style_declaration_test.cc",
"css/css_font_face_source_test.cc",
"css/css_gradient_value_test.cc",
+ "css/css_invalid_variable_value_test.cc",
"css/css_page_rule_test.cc",
"css/css_paint_value_test.cc",
+ "css/css_primitive_value_test.cc",
+ "css/css_property_name_test.cc",
+ "css/css_property_value_set_test.cc",
"css/css_selector_test.cc",
"css/css_selector_watch_test.cc",
"css/css_style_declaration_test.cc",
"css/css_style_sheet_test.cc",
- "css/css_test_helper.cc",
- "css/css_test_helper.h",
+ "css/css_test_helpers.cc",
+ "css/css_test_helpers.h",
"css/css_value_test_helper.h",
"css/cssom/css_math_invert_test.cc",
"css/cssom/css_math_negate_test.cc",
@@ -1753,6 +1762,7 @@ jumbo_source_set("unit_tests") {
"css/media_values_test.cc",
"css/parser/css_lazy_parsing_test.cc",
"css/parser/css_parser_fast_paths_test.cc",
+ "css/parser/css_parser_local_context_test.cc",
"css/parser/css_parser_token_stream_test.cc",
"css/parser/css_parser_token_test.cc",
"css/parser/css_property_parser_test.cc",
@@ -1762,6 +1772,8 @@ jumbo_source_set("unit_tests") {
"css/parser/sizes_attribute_parser_test.cc",
"css/parser/sizes_calc_parser_test.cc",
"css/properties/css_parsing_utils_test.cc",
+ "css/properties/css_property_ref_test.cc",
+ "css/properties/longhands/custom_property_test.cc",
"css/resolver/css_variable_data_test.cc",
"css/resolver/css_variable_resolver_test.cc",
"css/resolver/font_builder_test.cc",
@@ -1820,8 +1832,6 @@ jumbo_source_set("unit_tests") {
"events/pointer_event_factory_test.cc",
"events/touch_event_test.cc",
"events/web_input_event_conversion_test.cc",
- "exported/fake_web_plugin.cc",
- "exported/fake_web_plugin.h",
"exported/local_frame_client_impl_test.cc",
"exported/prerendering_test.cc",
"exported/web_associated_url_loader_impl_test.cc",
@@ -1832,6 +1842,7 @@ jumbo_source_set("unit_tests") {
"exported/web_frame_serializer_sanitization_test.cc",
"exported/web_frame_serializer_test.cc",
"exported/web_frame_test.cc",
+ "exported/web_layer_test.cc",
"exported/web_meaningful_layouts_test.cc",
"exported/web_node_test.cc",
"exported/web_plugin_container_test.cc",
@@ -1868,7 +1879,6 @@ jumbo_source_set("unit_tests") {
"frame/csp/csp_source_test.cc",
"frame/csp/media_list_directive_test.cc",
"frame/csp/source_list_directive_test.cc",
- "frame/deferred_loading_test.cc",
"frame/document_loading_rendering_test.cc",
"frame/dom_timer_test.cc",
"frame/find_in_page_test.cc",
@@ -1975,11 +1985,13 @@ jumbo_source_set("unit_tests") {
"inspector/inspector_session_state_test.cc",
"inspector/main_thread_debugger_test.cc",
"inspector/protocol_parser_test.cc",
+ "inspector/protocol_unittest.cc",
"intersection_observer/intersection_observer_test.cc",
"layout/api/selection_state_test.cc",
"layout/collapsed_border_value_test.cc",
"layout/custom/layout_worklet_test.cc",
"layout/grid_test.cc",
+ "layout/jank_region_test.cc",
"layout/jank_tracker_test.cc",
"layout/layout_block_test.cc",
"layout/layout_box_model_object_test.cc",
@@ -2017,6 +2029,7 @@ jumbo_source_set("unit_tests") {
"layout/ng/geometry/ng_physical_offset_rect_test.cc",
"layout/ng/geometry/ng_physical_offset_test.cc",
"layout/ng/geometry/ng_physical_rect_test.cc",
+ "layout/ng/inline/ng_baseline_test.cc",
"layout/ng/inline/ng_caret_position_test.cc",
"layout/ng/inline/ng_inline_fragment_traversal_test.cc",
"layout/ng/inline/ng_inline_items_builder_test.cc",
@@ -2159,7 +2172,10 @@ jumbo_source_set("unit_tests") {
"scroll/scrollable_area_test.cc",
"scroll/scrollbar_theme_overlay_test.cc",
"streams/readable_stream_operations_test.cc",
+ "streams/readable_stream_test.cc",
+ "streams/test_underlying_source.h",
"streams/transform_stream_test.cc",
+ "streams/writable_stream_test.cc",
"style/border_value_test.cc",
"style/computed_style_test.cc",
"style/filter_operations_test.cc",
@@ -2169,6 +2185,8 @@ jumbo_source_set("unit_tests") {
"svg/svg_path_parser_test.cc",
"svg/svg_text_content_element_test.cc",
"svg/unsafe_svg_attribute_sanitization_test.cc",
+ "testing/fake_web_plugin.cc",
+ "testing/fake_web_plugin.h",
"testing/sim/sim_canvas.cc",
"testing/sim/sim_canvas.h",
"testing/sim/sim_compositor.cc",
@@ -2294,7 +2312,7 @@ fuzzer_test("stylesheet_contents_fuzzer") {
"../platform:blink_fuzzer_test_support",
]
dict = "//third_party/blink/renderer/core/css/css.dict"
- seed_corpus = "//third_party/WebKit/LayoutTests/fast/css/resources"
+ seed_corpus = "//third_party/blink/web_tests/fast/css/resources"
libfuzzer_options = [ "max_len=1024" ]
}
@@ -2317,7 +2335,7 @@ fuzzer_test("html_preload_scanner_fuzzer") {
"html/parser/html_preload_scanner_fuzzer.cc",
"html/parser/text_resource_decoder_for_fuzzing.h",
]
- seed_corpus = "//third_party/WebKit/LayoutTests/fast/parser"
+ seed_corpus = "//third_party/blink/web_tests/fast/parser"
deps = [
":core",
"../platform:blink_fuzzer_test_support",
diff --git a/chromium/third_party/blink/renderer/core/DEPS b/chromium/third_party/blink/renderer/core/DEPS
index 33d83b3055d..a6c68014db6 100644
--- a/chromium/third_party/blink/renderer/core/DEPS
+++ b/chromium/third_party/blink/renderer/core/DEPS
@@ -38,7 +38,6 @@ include_rules = [
"+services/network/public/cpp/cors/cors_error_status.h",
"+services/network/public/cpp/features.h",
"+services/network/public/cpp/shared_url_loader_factory.h",
- "+services/network/public/mojom",
"+services/resource_coordinator/public/cpp/resource_coordinator_features.h",
"+services/service_manager/public",
"+services/ws/public/mojom/ime/ime.mojom-shared.h",
@@ -71,6 +70,7 @@ specific_include_rules = {
"+base/message_loop/message_loop.h",
# Test harness may use cc directly instead of going through WebViewImpl etc.
"+cc",
+ "+components/ukm/test_ukm_recorder.h",
# TODO(crbug.com/838693): Test harnesses use LayerTreeView
# from content instead of a fake WebLayerTreeView implementation, so
# that the Web abstraction can go away.
@@ -85,7 +85,7 @@ specific_include_rules = {
"find_in_page.cc" : [
"+third_party/blink/renderer/core/frame/web_local_frame_impl.h",
],
- "local_frame_ukm_aggregator_test.cc" : [
- "+components/ukm/test_ukm_recorder.h"
+ "find_task_controller.cc" : [
+ "+third_party/blink/renderer/core/frame/web_local_frame_impl.h",
],
}
diff --git a/chromium/third_party/blink/renderer/core/OWNERS b/chromium/third_party/blink/renderer/core/OWNERS
index 995cd607f52..50bd98e64c5 100644
--- a/chromium/third_party/blink/renderer/core/OWNERS
+++ b/chromium/third_party/blink/renderer/core/OWNERS
@@ -26,6 +26,7 @@ fmalita@chromium.org
# foolip reviews <video>, <track>, WebVTT and Fullscreen.
foolip@chromium.org
fs@opera.com
+fserb@chromium.org
futhark@chromium.org
haraken@chromium.org
hayato@chromium.org
@@ -37,7 +38,6 @@ jbroman@chromium.org
jfernandez@igalia.com
jianli@chromium.org
jochen@chromium.org
-junov@chromium.org
kbr@chromium.org
keishi@chromium.org
kenneth.r.christiansen@intel.com
diff --git a/chromium/third_party/blink/renderer/core/animation/README.md b/chromium/third_party/blink/renderer/core/animation/README.md
index 7fb2b0e266e..e6ffefb1335 100644
--- a/chromium/third_party/blink/renderer/core/animation/README.md
+++ b/chromium/third_party/blink/renderer/core/animation/README.md
@@ -331,7 +331,7 @@ to an animated element's [ComputedStyle][].
Test new animation features using end to end web-platform-tests to ensure
cross-browser interoperability. Use unit testing when access to chrome internals
is required. Test chrome specific features such as compositing of animation
-using LayoutTests or unit tests.
+using web tests or unit tests.
### End to end testing
@@ -341,15 +341,15 @@ pointers for how to get started. If Chrome does not correctly implement the
spec, add a corresponding -expected.txt file with your test listing the expected
failure in Chrome.
-[Layout tests](../../../../../docs/testing/writing_layout_tests.md) are located
-in [third_party/WebKit/LayoutTests][]. These should be written when needing end
+[Web tests](../../../../../docs/testing/writing_web_tests.md) are located
+in [third_party/blink/web_tests][]. These should be written when needing end
to end testing but either when testing chrome specific features (i.e.
non-standardized) such as compositing or when the test requires access to chrome
internal features not easily tested by web-platform-tests.
-[web-animations-tests]: https://cs.chromium.org/chromium/src/third_party/WebKit/LayoutTests/external/wpt/web-animations/
+[web-animations-tests]: https://cs.chromium.org/chromium/src/third_party/blink/web_tests/external/wpt/web-animations/
[Writing web platform tests]: ../../../../../docs/testing/web_platform_tests.md#Writing-tests
-[third_party/WebKit/LayoutTests]: https://cs.chromium.org/chromium/src/third_party/WebKit/LayoutTests/animations/
+[third_party/blink/web_tests]: https://cs.chromium.org/chromium/src/third_party/blink/web_tests/animations/
### Unit testing
diff --git a/chromium/third_party/blink/renderer/core/animation/animation.cc b/chromium/third_party/blink/renderer/core/animation/animation.cc
index 94bdffa9ee8..bab13cab062 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation.cc
@@ -705,7 +705,7 @@ ScriptPromise Animation::ready(ScriptState* script_state) {
}
const AtomicString& Animation::InterfaceName() const {
- return EventTargetNames::Animation;
+ return event_target_names::kAnimation;
}
ExecutionContext* Animation::GetExecutionContext() const {
@@ -718,7 +718,7 @@ bool Animation::HasPendingActivity() const {
finished_promise_->GetState() == ScriptPromisePropertyBase::kPending;
return pending_finished_event_ || has_pending_promise ||
- (!finished_ && HasEventListeners(EventTypeNames::finish));
+ (!finished_ && HasEventListeners(event_type_names::kFinish));
}
void Animation::ContextDestroyed(ExecutionContext*) {
@@ -971,7 +971,7 @@ bool Animation::Update(TimingUpdateReason reason) {
if ((idle || Limited()) && !finished_) {
if (reason == kTimingUpdateForAnimationFrame && (idle || start_time_)) {
if (idle) {
- const AtomicString& event_type = EventTypeNames::cancel;
+ const AtomicString& event_type = event_type_names::kCancel;
if (GetExecutionContext() && HasEventListeners(event_type)) {
double event_current_time = NullValue();
pending_cancelled_event_ =
@@ -983,7 +983,7 @@ bool Animation::Update(TimingUpdateReason reason) {
pending_cancelled_event_);
}
} else {
- const AtomicString& event_type = EventTypeNames::finish;
+ const AtomicString& event_type = event_type_names::kFinish;
if (GetExecutionContext() && HasEventListeners(event_type)) {
double event_current_time = CurrentTimeInternal() * 1000;
pending_finished_event_ =
@@ -1142,19 +1142,21 @@ Animation::PlayStateUpdateScope::~PlayStateUpdateScope() {
if (old_play_state != new_play_state) {
bool was_active = old_play_state == kPending || old_play_state == kRunning;
bool is_active = new_play_state == kPending || new_play_state == kRunning;
- if (!was_active && is_active)
+ if (!was_active && is_active) {
TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(
"blink.animations,devtools.timeline,benchmark,rail", "Animation",
- animation_, "data", InspectorAnimationEvent::Data(*animation_));
- else if (was_active && !is_active)
+ animation_, "data", inspector_animation_event::Data(*animation_));
+ } else if (was_active && !is_active) {
TRACE_EVENT_NESTABLE_ASYNC_END1(
"blink.animations,devtools.timeline,benchmark,rail", "Animation",
animation_, "endData",
- InspectorAnimationStateEvent::Data(*animation_));
- else
+ inspector_animation_state_event::Data(*animation_));
+ } else {
TRACE_EVENT_NESTABLE_ASYNC_INSTANT1(
"blink.animations,devtools.timeline,benchmark,rail", "Animation",
- animation_, "data", InspectorAnimationStateEvent::Data(*animation_));
+ animation_, "data",
+ inspector_animation_state_event::Data(*animation_));
+ }
}
// Ordering is important, the ready promise should resolve/reject before
@@ -1231,7 +1233,7 @@ void Animation::AddedEventListener(
RegisteredEventListener& registered_listener) {
EventTargetWithInlineData::AddedEventListener(event_type,
registered_listener);
- if (event_type == EventTypeNames::finish)
+ if (event_type == event_type_names::kFinish)
UseCounter::Count(GetExecutionContext(), WebFeature::kAnimationFinishEvent);
}
@@ -1269,7 +1271,7 @@ void Animation::InvalidateKeyframeEffect(const TreeScope& tree_scope) {
CSSAnimations::IsAffectedByKeyframesFromScope(*target, tree_scope)) {
target->SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleSheetChange));
+ style_change_reason::kStyleSheetChange));
}
}
diff --git a/chromium/third_party/blink/renderer/core/animation/animation.h b/chromium/third_party/blink/renderer/core/animation/animation.h
index 8aa2047cd1a..de4b82499fc 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation.h
@@ -44,7 +44,7 @@
#include "third_party/blink/renderer/core/animation/compositor_animations.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
@@ -144,8 +144,8 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
bool Limited() const { return Limited(CurrentTimeInternal()); }
bool FinishedInternal() const { return finished_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(finish);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(cancel);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(finish, kFinish);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(cancel, kCancel);
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_effect.cc b/chromium/third_party/blink/renderer/core/animation/animation_effect.cc
index 94ff9301fd1..5adbdf56aa9 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_effect.cc
@@ -91,12 +91,14 @@ void AnimationEffect::UpdateSpecifiedTiming(const Timing& timing) {
InvalidateAndNotifyOwner();
}
-void AnimationEffect::getTiming(EffectTiming& effect_timing) const {
- effect_timing.setDelay(SpecifiedTiming().start_delay * 1000);
- effect_timing.setEndDelay(SpecifiedTiming().end_delay * 1000);
- effect_timing.setFill(Timing::FillModeString(SpecifiedTiming().fill_mode));
- effect_timing.setIterationStart(SpecifiedTiming().iteration_start);
- effect_timing.setIterations(SpecifiedTiming().iteration_count);
+EffectTiming* AnimationEffect::getTiming() const {
+ EffectTiming* effect_timing = EffectTiming::Create();
+
+ effect_timing->setDelay(SpecifiedTiming().start_delay * 1000);
+ effect_timing->setEndDelay(SpecifiedTiming().end_delay * 1000);
+ effect_timing->setFill(Timing::FillModeString(SpecifiedTiming().fill_mode));
+ effect_timing->setIterationStart(SpecifiedTiming().iteration_start);
+ effect_timing->setIterations(SpecifiedTiming().iteration_count);
UnrestrictedDoubleOrString duration;
if (SpecifiedTiming().iteration_duration) {
duration.SetUnrestrictedDouble(
@@ -104,65 +106,58 @@ void AnimationEffect::getTiming(EffectTiming& effect_timing) const {
} else {
duration.SetString("auto");
}
- effect_timing.setDuration(duration);
- effect_timing.setDirection(
+ effect_timing->setDuration(duration);
+ effect_timing->setDirection(
Timing::PlaybackDirectionString(SpecifiedTiming().direction));
- effect_timing.setEasing(SpecifiedTiming().timing_function->ToString());
-}
+ effect_timing->setEasing(SpecifiedTiming().timing_function->ToString());
-EffectTiming AnimationEffect::getTiming() const {
- EffectTiming result;
- getTiming(result);
- return result;
+ return effect_timing;
}
-void AnimationEffect::getComputedTiming(
- ComputedEffectTiming& computed_timing) const {
+ComputedEffectTiming* AnimationEffect::getComputedTiming() const {
+ ComputedEffectTiming* computed_timing = ComputedEffectTiming::Create();
+
// ComputedEffectTiming members.
- computed_timing.setEndTime(EndTimeInternal() * 1000);
- computed_timing.setActiveDuration(RepeatedDuration() * 1000);
+ computed_timing->setEndTime(EndTimeInternal() * 1000);
+ computed_timing->setActiveDuration(RepeatedDuration() * 1000);
if (IsNull(EnsureCalculated().local_time)) {
- computed_timing.setLocalTimeToNull();
+ computed_timing->setLocalTimeToNull();
} else {
- computed_timing.setLocalTime(EnsureCalculated().local_time * 1000);
+ computed_timing->setLocalTime(EnsureCalculated().local_time * 1000);
}
if (EnsureCalculated().is_in_effect) {
- computed_timing.setProgress(EnsureCalculated().progress.value());
- computed_timing.setCurrentIteration(EnsureCalculated().current_iteration);
+ computed_timing->setProgress(EnsureCalculated().progress.value());
+ computed_timing->setCurrentIteration(EnsureCalculated().current_iteration);
} else {
- computed_timing.setProgressToNull();
- computed_timing.setCurrentIterationToNull();
+ computed_timing->setProgressToNull();
+ computed_timing->setCurrentIterationToNull();
}
// For the EffectTiming members, getComputedTiming is equivalent to getTiming
// except that the fill and duration must be resolved.
//
// https://drafts.csswg.org/web-animations-1/#dom-animationeffect-getcomputedtiming
- computed_timing.setDelay(SpecifiedTiming().start_delay * 1000);
- computed_timing.setEndDelay(SpecifiedTiming().end_delay * 1000);
- computed_timing.setFill(Timing::FillModeString(
+ computed_timing->setDelay(SpecifiedTiming().start_delay * 1000);
+ computed_timing->setEndDelay(SpecifiedTiming().end_delay * 1000);
+ computed_timing->setFill(Timing::FillModeString(
ResolvedFillMode(SpecifiedTiming().fill_mode, IsKeyframeEffect())));
- computed_timing.setIterationStart(SpecifiedTiming().iteration_start);
- computed_timing.setIterations(SpecifiedTiming().iteration_count);
+ computed_timing->setIterationStart(SpecifiedTiming().iteration_start);
+ computed_timing->setIterations(SpecifiedTiming().iteration_count);
UnrestrictedDoubleOrString duration;
duration.SetUnrestrictedDouble(IterationDuration().InMillisecondsF());
- computed_timing.setDuration(duration);
+ computed_timing->setDuration(duration);
- computed_timing.setDirection(
+ computed_timing->setDirection(
Timing::PlaybackDirectionString(SpecifiedTiming().direction));
- computed_timing.setEasing(SpecifiedTiming().timing_function->ToString());
-}
+ computed_timing->setEasing(SpecifiedTiming().timing_function->ToString());
-ComputedEffectTiming AnimationEffect::getComputedTiming() const {
- ComputedEffectTiming result;
- getComputedTiming(result);
- return result;
+ return computed_timing;
}
-void AnimationEffect::updateTiming(OptionalEffectTiming& optional_timing,
+void AnimationEffect::updateTiming(OptionalEffectTiming* optional_timing,
ExceptionState& exception_state) {
// TODO(crbug.com/827178): Determine whether we should pass a Document in here
// (and which) to resolve the CSS secure/insecure context against.
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_effect.h b/chromium/third_party/blink/renderer/core/animation/animation_effect.h
index 695789b3bd2..502a8d4f7a3 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation_effect.h
@@ -121,11 +121,9 @@ class CORE_EXPORT AnimationEffect : public ScriptWrappable {
void UpdateSpecifiedTiming(const Timing&);
EventDelegate* GetEventDelegate() { return event_delegate_; }
- void getTiming(EffectTiming&) const;
- EffectTiming getTiming() const;
- void getComputedTiming(ComputedEffectTiming&) const;
- ComputedEffectTiming getComputedTiming() const;
- void updateTiming(OptionalEffectTiming&,
+ EffectTiming* getTiming() const;
+ ComputedEffectTiming* getComputedTiming() const;
+ void updateTiming(OptionalEffectTiming*,
ExceptionState& = ASSERT_NO_EXCEPTION);
// Attach/Detach the AnimationEffect from its owning animation.
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_effect_test.cc b/chromium/third_party/blink/renderer/core/animation/animation_effect_test.cc
index c5faba741a5..60805f61f30 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_effect_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_effect_test.cc
@@ -71,10 +71,15 @@ class TestAnimationEffectEventDelegate : public AnimationEffect::EventDelegate {
class TestAnimationEffect : public AnimationEffect {
public:
static TestAnimationEffect* Create(const Timing& specified) {
- return new TestAnimationEffect(specified,
- new TestAnimationEffectEventDelegate());
+ return MakeGarbageCollected<TestAnimationEffect>(
+ specified, MakeGarbageCollected<TestAnimationEffectEventDelegate>());
}
+ TestAnimationEffect(const Timing& specified,
+ TestAnimationEffectEventDelegate* event_delegate)
+ : AnimationEffect(specified, event_delegate),
+ event_delegate_(event_delegate) {}
+
void UpdateInheritedTime(double time) {
UpdateInheritedTime(time, kTimingUpdateForAnimationFrame);
}
@@ -115,11 +120,6 @@ class TestAnimationEffect : public AnimationEffect {
}
private:
- TestAnimationEffect(const Timing& specified,
- TestAnimationEffectEventDelegate* event_delegate)
- : AnimationEffect(specified, event_delegate),
- event_delegate_(event_delegate) {}
-
Member<TestAnimationEffectEventDelegate> event_delegate_;
mutable double local_time_;
mutable double time_to_next_iteration_;
@@ -726,54 +726,54 @@ TEST(AnimationAnimationEffectTest, UpdateTiming) {
Timing timing;
TestAnimationEffect* effect = TestAnimationEffect::Create(timing);
- EXPECT_EQ(0, effect->getTiming().delay());
- OptionalEffectTiming effect_timing;
- effect_timing.setDelay(2);
+ EXPECT_EQ(0, effect->getTiming()->delay());
+ OptionalEffectTiming* effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDelay(2);
effect->updateTiming(effect_timing);
- EXPECT_EQ(2, effect->getTiming().delay());
+ EXPECT_EQ(2, effect->getTiming()->delay());
- EXPECT_EQ(0, effect->getTiming().endDelay());
- effect_timing = OptionalEffectTiming();
- effect_timing.setEndDelay(0.5);
+ EXPECT_EQ(0, effect->getTiming()->endDelay());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setEndDelay(0.5);
effect->updateTiming(effect_timing);
- EXPECT_EQ(0.5, effect->getTiming().endDelay());
+ EXPECT_EQ(0.5, effect->getTiming()->endDelay());
- EXPECT_EQ("auto", effect->getTiming().fill());
- effect_timing = OptionalEffectTiming();
- effect_timing.setFill("backwards");
+ EXPECT_EQ("auto", effect->getTiming()->fill());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setFill("backwards");
effect->updateTiming(effect_timing);
- EXPECT_EQ("backwards", effect->getTiming().fill());
+ EXPECT_EQ("backwards", effect->getTiming()->fill());
- EXPECT_EQ(0, effect->getTiming().iterationStart());
- effect_timing = OptionalEffectTiming();
- effect_timing.setIterationStart(2);
+ EXPECT_EQ(0, effect->getTiming()->iterationStart());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setIterationStart(2);
effect->updateTiming(effect_timing);
- EXPECT_EQ(2, effect->getTiming().iterationStart());
+ EXPECT_EQ(2, effect->getTiming()->iterationStart());
- EXPECT_EQ(1, effect->getTiming().iterations());
- effect_timing = OptionalEffectTiming();
- effect_timing.setIterations(10);
+ EXPECT_EQ(1, effect->getTiming()->iterations());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setIterations(10);
effect->updateTiming(effect_timing);
- EXPECT_EQ(10, effect->getTiming().iterations());
+ EXPECT_EQ(10, effect->getTiming()->iterations());
- EXPECT_EQ("normal", effect->getTiming().direction());
- effect_timing = OptionalEffectTiming();
- effect_timing.setDirection("reverse");
+ EXPECT_EQ("normal", effect->getTiming()->direction());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDirection("reverse");
effect->updateTiming(effect_timing);
- EXPECT_EQ("reverse", effect->getTiming().direction());
+ EXPECT_EQ("reverse", effect->getTiming()->direction());
- EXPECT_EQ("linear", effect->getTiming().easing());
- effect_timing = OptionalEffectTiming();
- effect_timing.setEasing("ease-in-out");
+ EXPECT_EQ("linear", effect->getTiming()->easing());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setEasing("ease-in-out");
effect->updateTiming(effect_timing);
- EXPECT_EQ("ease-in-out", effect->getTiming().easing());
+ EXPECT_EQ("ease-in-out", effect->getTiming()->easing());
- EXPECT_EQ("auto", effect->getTiming().duration().GetAsString());
- effect_timing = OptionalEffectTiming();
- effect_timing.setDuration(
+ EXPECT_EQ("auto", effect->getTiming()->duration().GetAsString());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDuration(
UnrestrictedDoubleOrString::FromUnrestrictedDouble(2.5));
effect->updateTiming(effect_timing);
- EXPECT_EQ(2.5, effect->getTiming().duration().GetAsUnrestrictedDouble());
+ EXPECT_EQ(2.5, effect->getTiming()->duration().GetAsUnrestrictedDouble());
}
TEST(AnimationAnimationEffectTest, UpdateTimingThrowsWhenExpected) {
@@ -783,43 +783,43 @@ TEST(AnimationAnimationEffectTest, UpdateTimingThrowsWhenExpected) {
DummyExceptionStateForTesting exception_state;
// iterationStart must be non-negative
- OptionalEffectTiming effect_timing;
- effect_timing.setIterationStart(-10);
+ OptionalEffectTiming* effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setIterationStart(-10);
effect->updateTiming(effect_timing, exception_state);
EXPECT_TRUE(exception_state.HadException());
// iterations must be non-negative and non-null.
exception_state.ClearException();
- effect_timing = OptionalEffectTiming();
- effect_timing.setIterations(-2);
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setIterations(-2);
effect->updateTiming(effect_timing, exception_state);
EXPECT_TRUE(exception_state.HadException());
exception_state.ClearException();
- effect_timing = OptionalEffectTiming();
- effect_timing.setIterations(std::numeric_limits<double>::quiet_NaN());
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setIterations(std::numeric_limits<double>::quiet_NaN());
effect->updateTiming(effect_timing, exception_state);
EXPECT_TRUE(exception_state.HadException());
// If it is a number, duration must be non-negative and non-null.
exception_state.ClearException();
- effect_timing = OptionalEffectTiming();
- effect_timing.setDuration(
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDuration(
UnrestrictedDoubleOrString::FromUnrestrictedDouble(-100));
effect->updateTiming(effect_timing, exception_state);
EXPECT_TRUE(exception_state.HadException());
exception_state.ClearException();
- effect_timing = OptionalEffectTiming();
- effect_timing.setDuration(UnrestrictedDoubleOrString::FromUnrestrictedDouble(
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDuration(UnrestrictedDoubleOrString::FromUnrestrictedDouble(
std::numeric_limits<double>::quiet_NaN()));
effect->updateTiming(effect_timing, exception_state);
EXPECT_TRUE(exception_state.HadException());
// easing must be a valid timing function
exception_state.ClearException();
- effect_timing = OptionalEffectTiming();
- effect_timing.setEasing("my-custom-timing-function");
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setEasing("my-custom-timing-function");
effect->updateTiming(effect_timing, exception_state);
EXPECT_TRUE(exception_state.HadException());
}
@@ -828,13 +828,14 @@ TEST(AnimationAnimationEffectTest, UpdateTimingInformsOwnerOnChange) {
Timing timing;
TestAnimationEffect* effect = TestAnimationEffect::Create(timing);
- MockAnimationEffectOwner* owner = new MockAnimationEffectOwner();
+ MockAnimationEffectOwner* owner =
+ MakeGarbageCollected<MockAnimationEffectOwner>();
effect->Attach(owner);
EXPECT_CALL(*owner, EffectInvalidated()).Times(1);
- OptionalEffectTiming effect_timing;
- effect_timing.setDelay(5);
+ OptionalEffectTiming* effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDelay(5);
effect->updateTiming(effect_timing);
}
@@ -850,35 +851,36 @@ TEST(AnimationAnimationEffectTest, UpdateTimingNoChange) {
timing.timing_function = CubicBezierTimingFunction::Create(1, 1, 0.3, 0.3);
TestAnimationEffect* effect = TestAnimationEffect::Create(timing);
- MockAnimationEffectOwner* owner = new MockAnimationEffectOwner();
+ MockAnimationEffectOwner* owner =
+ MakeGarbageCollected<MockAnimationEffectOwner>();
effect->Attach(owner);
// None of the below calls to updateTime should cause the AnimationEffect to
// update, as they all match the existing timing information.
EXPECT_CALL(*owner, EffectInvalidated()).Times(0);
- OptionalEffectTiming effect_timing;
+ OptionalEffectTiming* effect_timing = OptionalEffectTiming::Create();
effect->updateTiming(effect_timing);
- effect_timing = OptionalEffectTiming();
- effect_timing.setDelay(0);
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setDelay(0);
effect->updateTiming(effect_timing);
- effect_timing = OptionalEffectTiming();
- effect_timing.setEndDelay(5000);
- effect_timing.setFill("both");
- effect_timing.setIterationStart(0.1);
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setEndDelay(5000);
+ effect_timing->setFill("both");
+ effect_timing->setIterationStart(0.1);
effect->updateTiming(effect_timing);
- effect_timing = OptionalEffectTiming();
- effect_timing.setIterations(3);
- effect_timing.setDuration(
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setIterations(3);
+ effect_timing->setDuration(
UnrestrictedDoubleOrString::FromUnrestrictedDouble(2000));
- effect_timing.setDirection("alternate-reverse");
+ effect_timing->setDirection("alternate-reverse");
effect->updateTiming(effect_timing);
- effect_timing = OptionalEffectTiming();
- effect_timing.setEasing("cubic-bezier(1, 1, 0.3, 0.3)");
+ effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setEasing("cubic-bezier(1, 1, 0.3, 0.3)");
effect->updateTiming(effect_timing);
}
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.cc b/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.cc
index 1aa84f65f77..3e215ff26c2 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.cc
@@ -104,101 +104,101 @@ const AttributeNameMap& GetSupportedAttributes() {
// Fill the set for the first use.
// Animatable attributes from http://www.w3.org/TR/SVG/attindex.html
const QualifiedName* attributes[] = {
- &HTMLNames::classAttr,
- &SVGNames::amplitudeAttr,
- &SVGNames::azimuthAttr,
- &SVGNames::baseFrequencyAttr,
- &SVGNames::biasAttr,
- &SVGNames::clipPathUnitsAttr,
- &SVGNames::cxAttr,
- &SVGNames::cyAttr,
- &SVGNames::dAttr,
- &SVGNames::diffuseConstantAttr,
- &SVGNames::divisorAttr,
- &SVGNames::dxAttr,
- &SVGNames::dyAttr,
- &SVGNames::edgeModeAttr,
- &SVGNames::elevationAttr,
- &SVGNames::exponentAttr,
- &SVGNames::filterUnitsAttr,
- &SVGNames::fxAttr,
- &SVGNames::fyAttr,
- &SVGNames::gradientTransformAttr,
- &SVGNames::gradientUnitsAttr,
- &SVGNames::heightAttr,
- &SVGNames::hrefAttr,
- &SVGNames::in2Attr,
- &SVGNames::inAttr,
- &SVGNames::interceptAttr,
- &SVGNames::k1Attr,
- &SVGNames::k2Attr,
- &SVGNames::k3Attr,
- &SVGNames::k4Attr,
- &SVGNames::kernelMatrixAttr,
- &SVGNames::kernelUnitLengthAttr,
- &SVGNames::lengthAdjustAttr,
- &SVGNames::limitingConeAngleAttr,
- &SVGNames::markerHeightAttr,
- &SVGNames::markerUnitsAttr,
- &SVGNames::markerWidthAttr,
- &SVGNames::maskContentUnitsAttr,
- &SVGNames::maskUnitsAttr,
- &SVGNames::methodAttr,
- &SVGNames::modeAttr,
- &SVGNames::numOctavesAttr,
- &SVGNames::offsetAttr,
- &SVGNames::operatorAttr,
- &SVGNames::orderAttr,
- &SVGNames::orientAttr,
- &SVGNames::pathLengthAttr,
- &SVGNames::patternContentUnitsAttr,
- &SVGNames::patternTransformAttr,
- &SVGNames::patternUnitsAttr,
- &SVGNames::pointsAtXAttr,
- &SVGNames::pointsAtYAttr,
- &SVGNames::pointsAtZAttr,
- &SVGNames::pointsAttr,
- &SVGNames::preserveAlphaAttr,
- &SVGNames::preserveAspectRatioAttr,
- &SVGNames::primitiveUnitsAttr,
- &SVGNames::rAttr,
- &SVGNames::radiusAttr,
- &SVGNames::refXAttr,
- &SVGNames::refYAttr,
- &SVGNames::resultAttr,
- &SVGNames::rotateAttr,
- &SVGNames::rxAttr,
- &SVGNames::ryAttr,
- &SVGNames::scaleAttr,
- &SVGNames::seedAttr,
- &SVGNames::slopeAttr,
- &SVGNames::spacingAttr,
- &SVGNames::specularConstantAttr,
- &SVGNames::specularExponentAttr,
- &SVGNames::spreadMethodAttr,
- &SVGNames::startOffsetAttr,
- &SVGNames::stdDeviationAttr,
- &SVGNames::stitchTilesAttr,
- &SVGNames::surfaceScaleAttr,
- &SVGNames::tableValuesAttr,
- &SVGNames::targetAttr,
- &SVGNames::targetXAttr,
- &SVGNames::targetYAttr,
- &SVGNames::textLengthAttr,
- &SVGNames::transformAttr,
- &SVGNames::typeAttr,
- &SVGNames::valuesAttr,
- &SVGNames::viewBoxAttr,
- &SVGNames::widthAttr,
- &SVGNames::x1Attr,
- &SVGNames::x2Attr,
- &SVGNames::xAttr,
- &SVGNames::xChannelSelectorAttr,
- &SVGNames::y1Attr,
- &SVGNames::y2Attr,
- &SVGNames::yAttr,
- &SVGNames::yChannelSelectorAttr,
- &SVGNames::zAttr,
+ &html_names::kClassAttr,
+ &svg_names::kAmplitudeAttr,
+ &svg_names::kAzimuthAttr,
+ &svg_names::kBaseFrequencyAttr,
+ &svg_names::kBiasAttr,
+ &svg_names::kClipPathUnitsAttr,
+ &svg_names::kCxAttr,
+ &svg_names::kCyAttr,
+ &svg_names::kDAttr,
+ &svg_names::kDiffuseConstantAttr,
+ &svg_names::kDivisorAttr,
+ &svg_names::kDxAttr,
+ &svg_names::kDyAttr,
+ &svg_names::kEdgeModeAttr,
+ &svg_names::kElevationAttr,
+ &svg_names::kExponentAttr,
+ &svg_names::kFilterUnitsAttr,
+ &svg_names::kFxAttr,
+ &svg_names::kFyAttr,
+ &svg_names::kGradientTransformAttr,
+ &svg_names::kGradientUnitsAttr,
+ &svg_names::kHeightAttr,
+ &svg_names::kHrefAttr,
+ &svg_names::kIn2Attr,
+ &svg_names::kInAttr,
+ &svg_names::kInterceptAttr,
+ &svg_names::kK1Attr,
+ &svg_names::kK2Attr,
+ &svg_names::kK3Attr,
+ &svg_names::kK4Attr,
+ &svg_names::kKernelMatrixAttr,
+ &svg_names::kKernelUnitLengthAttr,
+ &svg_names::kLengthAdjustAttr,
+ &svg_names::kLimitingConeAngleAttr,
+ &svg_names::kMarkerHeightAttr,
+ &svg_names::kMarkerUnitsAttr,
+ &svg_names::kMarkerWidthAttr,
+ &svg_names::kMaskContentUnitsAttr,
+ &svg_names::kMaskUnitsAttr,
+ &svg_names::kMethodAttr,
+ &svg_names::kModeAttr,
+ &svg_names::kNumOctavesAttr,
+ &svg_names::kOffsetAttr,
+ &svg_names::kOperatorAttr,
+ &svg_names::kOrderAttr,
+ &svg_names::kOrientAttr,
+ &svg_names::kPathLengthAttr,
+ &svg_names::kPatternContentUnitsAttr,
+ &svg_names::kPatternTransformAttr,
+ &svg_names::kPatternUnitsAttr,
+ &svg_names::kPointsAtXAttr,
+ &svg_names::kPointsAtYAttr,
+ &svg_names::kPointsAtZAttr,
+ &svg_names::kPointsAttr,
+ &svg_names::kPreserveAlphaAttr,
+ &svg_names::kPreserveAspectRatioAttr,
+ &svg_names::kPrimitiveUnitsAttr,
+ &svg_names::kRAttr,
+ &svg_names::kRadiusAttr,
+ &svg_names::kRefXAttr,
+ &svg_names::kRefYAttr,
+ &svg_names::kResultAttr,
+ &svg_names::kRotateAttr,
+ &svg_names::kRxAttr,
+ &svg_names::kRyAttr,
+ &svg_names::kScaleAttr,
+ &svg_names::kSeedAttr,
+ &svg_names::kSlopeAttr,
+ &svg_names::kSpacingAttr,
+ &svg_names::kSpecularConstantAttr,
+ &svg_names::kSpecularExponentAttr,
+ &svg_names::kSpreadMethodAttr,
+ &svg_names::kStartOffsetAttr,
+ &svg_names::kStdDeviationAttr,
+ &svg_names::kStitchTilesAttr,
+ &svg_names::kSurfaceScaleAttr,
+ &svg_names::kTableValuesAttr,
+ &svg_names::kTargetAttr,
+ &svg_names::kTargetXAttr,
+ &svg_names::kTargetYAttr,
+ &svg_names::kTextLengthAttr,
+ &svg_names::kTransformAttr,
+ &svg_names::kTypeAttr,
+ &svg_names::kValuesAttr,
+ &svg_names::kViewBoxAttr,
+ &svg_names::kWidthAttr,
+ &svg_names::kX1Attr,
+ &svg_names::kX2Attr,
+ &svg_names::kXAttr,
+ &svg_names::kXChannelSelectorAttr,
+ &svg_names::kY1Attr,
+ &svg_names::kY2Attr,
+ &svg_names::kYAttr,
+ &svg_names::kYChannelSelectorAttr,
+ &svg_names::kZAttr,
};
for (size_t i = 0; i < arraysize(attributes); i++) {
DCHECK(!SVGElement::IsAnimatableCSSProperty(*attributes[i]));
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.h b/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.h
index 1dc56ae8c41..1ea358cf30d 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation_input_helpers.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ANIMATION_INPUT_HELPERS_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_sim_test.cc b/chromium/third_party/blink/renderer/core/animation/animation_sim_test.cc
index 1c6de23e023..80aa614b621 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_sim_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_sim_test.cc
@@ -51,11 +51,11 @@ TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
// inherits: false
// })
DummyExceptionStateForTesting exception_state;
- PropertyDescriptor property_descriptor;
- property_descriptor.setName("--x");
- property_descriptor.setSyntax("<percentage>");
- property_descriptor.setInitialValue("0%");
- property_descriptor.setInherits(false);
+ PropertyDescriptor* property_descriptor = PropertyDescriptor::Create();
+ property_descriptor->setName("--x");
+ property_descriptor->setSyntax("<percentage>");
+ property_descriptor->setInitialValue("0%");
+ property_descriptor->setInherits(false);
PropertyRegistration::registerProperty(&GetDocument(), property_descriptor,
exception_state);
EXPECT_FALSE(exception_state.HadException());
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_test.cc b/chromium/third_party/blink/renderer/core/animation/animation_test.cc
index 73a6fd5c9fb..ef9d2620489 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_test.cc
@@ -135,7 +135,7 @@ class AnimationAnimationTest : public RenderingTest {
// After creating the animation we need to clean the lifecycle so that the
// animation can be pushed to the compositor.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
document->GetAnimationClock().UpdateTime(base::TimeTicks());
document->GetPendingAnimations().Update(base::nullopt, true);
@@ -883,7 +883,7 @@ TEST_F(AnimationAnimationTest, NoCompositeWithoutCompositedElementId) {
CompositorElementId expected_compositor_element_id =
CompositorElementIdFromUniqueObjectId(
ToLayoutBoxModelObject(object_composited)->UniqueId(),
- CompositorElementIdNamespace::kPrimary);
+ CompositorElementIdNamespace::kPrimaryEffect);
composited_element_ids->insert(expected_compositor_element_id);
Timing timing;
diff --git a/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc b/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc
index 5e7a1cb7202..8a077911c48 100644
--- a/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc
+++ b/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.cc
@@ -164,7 +164,7 @@ LengthSize CreateBorderRadius(
height, nullptr, conversion_data, kValueRangeNonNegative));
}
-namespace CircleFunctions {
+namespace circle_functions {
enum CircleComponentIndex : unsigned {
kCircleCenterXIndex,
@@ -230,9 +230,9 @@ scoped_refptr<BasicShape> CreateBasicShape(
return circle;
}
-} // namespace CircleFunctions
+} // namespace circle_functions
-namespace EllipseFunctions {
+namespace ellipse_functions {
enum EllipseComponentIndex : unsigned {
kEllipseCenterXIndex,
@@ -308,9 +308,9 @@ scoped_refptr<BasicShape> CreateBasicShape(
return ellipse;
}
-} // namespace EllipseFunctions
+} // namespace ellipse_functions
-namespace InsetFunctions {
+namespace inset_functions {
enum InsetComponentIndex : unsigned {
kInsetTopIndex,
@@ -448,9 +448,9 @@ scoped_refptr<BasicShape> CreateBasicShape(
return inset;
}
-} // namespace InsetFunctions
+} // namespace inset_functions
-namespace PolygonFunctions {
+namespace polygon_functions {
InterpolationValue ConvertCSSValue(
const cssvalue::CSSBasicShapePolygonValue& polygon) {
@@ -504,48 +504,49 @@ scoped_refptr<BasicShape> CreateBasicShape(
return polygon;
}
-} // namespace PolygonFunctions
+} // namespace polygon_functions
} // namespace
-InterpolationValue BasicShapeInterpolationFunctions::MaybeConvertCSSValue(
+InterpolationValue basic_shape_interpolation_functions::MaybeConvertCSSValue(
const CSSValue& value) {
if (value.IsBasicShapeCircleValue()) {
- return CircleFunctions::ConvertCSSValue(
+ return circle_functions::ConvertCSSValue(
cssvalue::ToCSSBasicShapeCircleValue(value));
}
if (value.IsBasicShapeEllipseValue()) {
- return EllipseFunctions::ConvertCSSValue(
+ return ellipse_functions::ConvertCSSValue(
cssvalue::ToCSSBasicShapeEllipseValue(value));
}
if (value.IsBasicShapeInsetValue()) {
- return InsetFunctions::ConvertCSSValue(
+ return inset_functions::ConvertCSSValue(
cssvalue::ToCSSBasicShapeInsetValue(value));
}
if (value.IsBasicShapePolygonValue()) {
- return PolygonFunctions::ConvertCSSValue(
+ return polygon_functions::ConvertCSSValue(
cssvalue::ToCSSBasicShapePolygonValue(value));
}
return nullptr;
}
-InterpolationValue BasicShapeInterpolationFunctions::MaybeConvertBasicShape(
+InterpolationValue basic_shape_interpolation_functions::MaybeConvertBasicShape(
const BasicShape* shape,
double zoom) {
if (!shape)
return nullptr;
switch (shape->GetType()) {
case BasicShape::kBasicShapeCircleType:
- return CircleFunctions::ConvertBasicShape(ToBasicShapeCircle(*shape),
- zoom);
- case BasicShape::kBasicShapeEllipseType:
- return EllipseFunctions::ConvertBasicShape(ToBasicShapeEllipse(*shape),
+ return circle_functions::ConvertBasicShape(ToBasicShapeCircle(*shape),
zoom);
+ case BasicShape::kBasicShapeEllipseType:
+ return ellipse_functions::ConvertBasicShape(ToBasicShapeEllipse(*shape),
+ zoom);
case BasicShape::kBasicShapeInsetType:
- return InsetFunctions::ConvertBasicShape(ToBasicShapeInset(*shape), zoom);
+ return inset_functions::ConvertBasicShape(ToBasicShapeInset(*shape),
+ zoom);
case BasicShape::kBasicShapePolygonType:
- return PolygonFunctions::ConvertBasicShape(ToBasicShapePolygon(*shape),
- zoom);
+ return polygon_functions::ConvertBasicShape(ToBasicShapePolygon(*shape),
+ zoom);
default:
NOTREACHED();
return nullptr;
@@ -553,33 +554,33 @@ InterpolationValue BasicShapeInterpolationFunctions::MaybeConvertBasicShape(
}
std::unique_ptr<InterpolableValue>
-BasicShapeInterpolationFunctions::CreateNeutralValue(
+basic_shape_interpolation_functions::CreateNeutralValue(
const NonInterpolableValue& untyped_non_interpolable_value) {
const BasicShapeNonInterpolableValue& non_interpolable_value =
ToBasicShapeNonInterpolableValue(untyped_non_interpolable_value);
switch (non_interpolable_value.GetShapeType()) {
case BasicShape::kBasicShapeCircleType:
- return CircleFunctions::CreateNeutralValue();
+ return circle_functions::CreateNeutralValue();
case BasicShape::kBasicShapeEllipseType:
- return EllipseFunctions::CreateNeutralValue();
+ return ellipse_functions::CreateNeutralValue();
case BasicShape::kBasicShapeInsetType:
- return InsetFunctions::CreateNeutralValue();
+ return inset_functions::CreateNeutralValue();
case BasicShape::kBasicShapePolygonType:
- return PolygonFunctions::CreateNeutralValue(non_interpolable_value);
+ return polygon_functions::CreateNeutralValue(non_interpolable_value);
default:
NOTREACHED();
return nullptr;
}
}
-bool BasicShapeInterpolationFunctions::ShapesAreCompatible(
+bool basic_shape_interpolation_functions::ShapesAreCompatible(
const NonInterpolableValue& a,
const NonInterpolableValue& b) {
return ToBasicShapeNonInterpolableValue(a).IsCompatibleWith(
ToBasicShapeNonInterpolableValue(b));
}
-scoped_refptr<BasicShape> BasicShapeInterpolationFunctions::CreateBasicShape(
+scoped_refptr<BasicShape> basic_shape_interpolation_functions::CreateBasicShape(
const InterpolableValue& interpolable_value,
const NonInterpolableValue& untyped_non_interpolable_value,
const CSSToLengthConversionData& conversion_data) {
@@ -587,16 +588,16 @@ scoped_refptr<BasicShape> BasicShapeInterpolationFunctions::CreateBasicShape(
ToBasicShapeNonInterpolableValue(untyped_non_interpolable_value);
switch (non_interpolable_value.GetShapeType()) {
case BasicShape::kBasicShapeCircleType:
- return CircleFunctions::CreateBasicShape(interpolable_value,
- conversion_data);
- case BasicShape::kBasicShapeEllipseType:
- return EllipseFunctions::CreateBasicShape(interpolable_value,
+ return circle_functions::CreateBasicShape(interpolable_value,
conversion_data);
+ case BasicShape::kBasicShapeEllipseType:
+ return ellipse_functions::CreateBasicShape(interpolable_value,
+ conversion_data);
case BasicShape::kBasicShapeInsetType:
- return InsetFunctions::CreateBasicShape(interpolable_value,
- conversion_data);
+ return inset_functions::CreateBasicShape(interpolable_value,
+ conversion_data);
case BasicShape::kBasicShapePolygonType:
- return PolygonFunctions::CreateBasicShape(
+ return polygon_functions::CreateBasicShape(
interpolable_value, non_interpolable_value, conversion_data);
default:
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.h b/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.h
index 0e74742f475..43f50619b0c 100644
--- a/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.h
@@ -14,7 +14,7 @@ class BasicShape;
class CSSValue;
class CSSToLengthConversionData;
-namespace BasicShapeInterpolationFunctions {
+namespace basic_shape_interpolation_functions {
InterpolationValue MaybeConvertCSSValue(const CSSValue&);
InterpolationValue MaybeConvertBasicShape(const BasicShape*, double zoom);
@@ -26,7 +26,7 @@ scoped_refptr<BasicShape> CreateBasicShape(const InterpolableValue&,
const NonInterpolableValue&,
const CSSToLengthConversionData&);
-} // namespace BasicShapeInterpolationFunctions
+} // namespace basic_shape_interpolation_functions
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/color_property_functions.h b/chromium/third_party/blink/renderer/core/animation/color_property_functions.h
index 21191f11a38..208e344cc97 100644
--- a/chromium/third_party/blink/renderer/core/animation/color_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/color_property_functions.h
@@ -5,8 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_COLOR_PROPERTY_FUNCTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_COLOR_PROPERTY_FUNCTIONS_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_color.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/compositor_animations.cc b/chromium/third_party/blink/renderer/core/animation/compositor_animations.cc
index 5b5669d239c..1cc872bd6af 100644
--- a/chromium/third_party/blink/renderer/core/animation/compositor_animations.cc
+++ b/chromium/third_party/blink/renderer/core/animation/compositor_animations.cc
@@ -143,6 +143,34 @@ bool HasIncompatibleAnimations(const Element& target_element,
return false;
}
+CompositorElementIdNamespace CompositorElementNamespaceForProperty(
+ CSSPropertyID property) {
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // Pre-BlinkGenPropertyTrees, all animations affect the primary
+ // ElementId namespace.
+ return CompositorElementIdNamespace::kPrimary;
+ }
+ switch (property) {
+ case CSSPropertyOpacity:
+ return CompositorElementIdNamespace::kPrimaryEffect;
+ case CSSPropertyRotate:
+ case CSSPropertyScale:
+ case CSSPropertyTranslate:
+ case CSSPropertyTransform:
+ return CompositorElementIdNamespace::kPrimaryTransform;
+ case CSSPropertyFilter:
+ case CSSPropertyBackdropFilter: {
+ return CompositorElementIdNamespace::kEffectFilter;
+ case CSSPropertyVariable:
+ return CompositorElementIdNamespace::kPrimary;
+ default:
+ NOTREACHED();
+ }
+ return CompositorElementIdNamespace::kPrimary;
+ }
+}
+
} // namespace
CompositorAnimations::FailureCode
@@ -204,8 +232,6 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
"Accelerated keyframe value could not be computed");
}
- CompositorElementIdNamespace property_namespace =
- CompositorElementIdNamespace::kPrimary;
// FIXME: Determine candidacy based on the CSSValue instead of a snapshot
// AnimatableValue.
switch (property.GetCSSProperty().PropertyID()) {
@@ -232,7 +258,6 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
return FailureCode::Actionable(
"Filter-related property may affect surrounding pixels");
}
- property_namespace = CompositorElementIdNamespace::kEffectFilter;
break;
}
case CSSPropertyVariable: {
@@ -260,9 +285,10 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
CompositorElementId target_element_id =
CompositorElementIdFromUniqueObjectId(
target_element.GetLayoutObject()->UniqueId(),
- property_namespace);
+ CompositorElementNamespaceForProperty(
+ property.GetCSSProperty().PropertyID()));
DCHECK(target_element_id);
- if (!composited_element_ids->Contains(target_element_id)) {
+ if (!composited_element_ids->count(target_element_id)) {
return FailureCode::NonActionable(
"Target element does not have its own compositing layer");
}
@@ -419,7 +445,7 @@ void CompositorAnimations::StartAnimationOnCompositor(
ToKeyframeEffectModelBase(effect);
Vector<std::unique_ptr<CompositorKeyframeModel>> keyframe_models;
- GetAnimationOnCompositor(timing, group, start_time, time_offset,
+ GetAnimationOnCompositor(element, timing, group, start_time, time_offset,
keyframe_effect, keyframe_models,
animation_playback_rate);
DCHECK(!keyframe_models.IsEmpty());
@@ -489,9 +515,20 @@ void CompositorAnimations::AttachCompositedLayers(
return;
}
+ CompositorElementIdNamespace element_id_namespace =
+ CompositorElementIdNamespace::kPrimary;
+ // With BlinkGenPropertyTrees we create an animation namespace element id
+ // when an element has created all property tree nodes which may be required
+ // by the keyframe effects. The animation affects multiple element ids, and
+ // one is pushed each KeyframeModel. See |GetAnimationOnCompositor|.
+ // Currently we use the kPrimaryEffect node to know if nodes have been
+ // created for animations.
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
+ RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ element_id_namespace = CompositorElementIdNamespace::kPrimaryEffect;
+ }
compositor_animation->AttachElement(CompositorElementIdFromUniqueObjectId(
- element.GetLayoutObject()->UniqueId(),
- CompositorElementIdNamespace::kPrimary));
+ element.GetLayoutObject()->UniqueId(), element_id_namespace));
}
bool CompositorAnimations::ConvertTimingForCompositor(
@@ -590,6 +627,7 @@ void AddKeyframesToCurve(PlatformAnimationCurveType& curve,
} // namespace
void CompositorAnimations::GetAnimationOnCompositor(
+ const Element& target_element,
const Timing& timing,
int group,
base::Optional<double> start_time,
@@ -616,12 +654,12 @@ void CompositorAnimations::GetAnimationOnCompositor(
const PropertySpecificKeyframeVector& values =
effect.GetPropertySpecificKeyframes(property);
- CompositorTargetProperty::Type target_property;
+ compositor_target_property::Type target_property;
std::unique_ptr<CompositorAnimationCurve> curve;
DCHECK(timing.timing_function);
switch (property.GetCSSProperty().PropertyID()) {
case CSSPropertyOpacity: {
- target_property = CompositorTargetProperty::OPACITY;
+ target_property = compositor_target_property::OPACITY;
std::unique_ptr<CompositorFloatAnimationCurve> float_curve =
CompositorFloatAnimationCurve::Create();
AddKeyframesToCurve(*float_curve, values);
@@ -632,7 +670,7 @@ void CompositorAnimations::GetAnimationOnCompositor(
}
case CSSPropertyFilter:
case CSSPropertyBackdropFilter: {
- target_property = CompositorTargetProperty::FILTER;
+ target_property = compositor_target_property::FILTER;
std::unique_ptr<CompositorFilterAnimationCurve> filter_curve =
CompositorFilterAnimationCurve::Create();
AddKeyframesToCurve(*filter_curve, values);
@@ -645,7 +683,7 @@ void CompositorAnimations::GetAnimationOnCompositor(
case CSSPropertyScale:
case CSSPropertyTranslate:
case CSSPropertyTransform: {
- target_property = CompositorTargetProperty::TRANSFORM;
+ target_property = compositor_target_property::TRANSFORM;
std::unique_ptr<CompositorTransformAnimationCurve> transform_curve =
CompositorTransformAnimationCurve::Create();
AddKeyframesToCurve(*transform_curve, values);
@@ -656,7 +694,7 @@ void CompositorAnimations::GetAnimationOnCompositor(
}
case CSSPropertyVariable: {
DCHECK(RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled());
- target_property = CompositorTargetProperty::CSS_CUSTOM_PROPERTY;
+ target_property = compositor_target_property::CSS_CUSTOM_PROPERTY;
// TODO(kevers): Extend support to non-float types.
std::unique_ptr<CompositorFloatAnimationCurve> float_curve =
CompositorFloatAnimationCurve::Create();
@@ -678,6 +716,10 @@ void CompositorAnimations::GetAnimationOnCompositor(
if (start_time)
keyframe_model->SetStartTime(start_time.value());
+ keyframe_model->SetElementId(CompositorElementIdFromUniqueObjectId(
+ target_element.GetLayoutObject()->UniqueId(),
+ CompositorElementNamespaceForProperty(
+ property.GetCSSProperty().PropertyID())));
keyframe_model->SetIterations(compositor_timing.adjusted_iteration_count);
keyframe_model->SetIterationStart(compositor_timing.iteration_start);
keyframe_model->SetTimeOffset(compositor_timing.scaled_time_offset);
diff --git a/chromium/third_party/blink/renderer/core/animation/compositor_animations.h b/chromium/third_party/blink/renderer/core/animation/compositor_animations.h
index 393ace9b945..30d53abb1b7 100644
--- a/chromium/third_party/blink/renderer/core/animation/compositor_animations.h
+++ b/chromium/third_party/blink/renderer/core/animation/compositor_animations.h
@@ -128,6 +128,7 @@ class CORE_EXPORT CompositorAnimations {
double animation_playback_rate);
static void GetAnimationOnCompositor(
+ const Element&,
const Timing&,
int group,
base::Optional<double> start_time,
diff --git a/chromium/third_party/blink/renderer/core/animation/compositor_animations_test.cc b/chromium/third_party/blink/renderer/core/animation/compositor_animations_test.cc
index 7e3db3746c4..a8154a61f89 100644
--- a/chromium/third_party/blink/renderer/core/animation/compositor_animations_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/compositor_animations_test.cc
@@ -46,9 +46,7 @@
#include "third_party/blink/renderer/core/animation/element_animations.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect.h"
#include "third_party/blink/renderer/core/animation/pending_animations.h"
-#include "third_party/blink/renderer/core/css/property_descriptor.h"
-#include "third_party/blink/renderer/core/css/property_registration.h"
-#include "third_party/blink/renderer/core/css/property_registry.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
@@ -76,6 +74,8 @@
namespace blink {
+using namespace css_test_helpers;
+
class AnimationCompositorAnimationsTest : public RenderingTest {
protected:
scoped_refptr<TimingFunction> linear_timing_function_;
@@ -124,7 +124,14 @@ class AnimationCompositorAnimationsTest : public RenderingTest {
timeline_ = DocumentTimeline::Create(&GetDocument());
timeline_->ResetForTesting();
- element_ = GetDocument().CreateElementForBinding("test");
+
+ // Using will-change ensures that this object will need paint properties.
+ // Having an animation would normally ensure this but these tests don't
+ // explicitly construct a full animation on the element.
+ SetBodyInnerHTML(R"HTML(
+ <div id='test' style='will-change: opacity,filter,transform;'></div>
+ )HTML");
+ element_ = GetDocument().getElementById("test");
helper_.Initialize(nullptr, nullptr, nullptr);
base_url_ = "http://www.test.com/";
@@ -171,9 +178,9 @@ class AnimationCompositorAnimationsTest : public RenderingTest {
StringKeyframeEffectModel& effect,
Vector<std::unique_ptr<CompositorKeyframeModel>>& keyframe_models,
double animation_playback_rate) {
- CompositorAnimations::GetAnimationOnCompositor(timing, 0, base::nullopt, 0,
- effect, keyframe_models,
- animation_playback_rate);
+ CompositorAnimations::GetAnimationOnCompositor(
+ *element_, timing, 0, base::nullopt, 0, effect, keyframe_models,
+ animation_playback_rate);
}
bool DuplicateSingleKeyframeAndTestIsCandidateOnResult(
@@ -254,7 +261,7 @@ class AnimationCompositorAnimationsTest : public RenderingTest {
HeapVector<Member<StringKeyframe>>* CreateCompositableFloatKeyframeVector(
Vector<double>& values) {
HeapVector<Member<StringKeyframe>>* frames =
- new HeapVector<Member<StringKeyframe>>();
+ MakeGarbageCollected<HeapVector<Member<StringKeyframe>>>();
for (wtf_size_t i = 0; i < values.size(); i++) {
double offset = 1.0 / (values.size() - 1) * i;
String value = String::Number(values[i]);
@@ -264,21 +271,6 @@ class AnimationCompositorAnimationsTest : public RenderingTest {
return frames;
}
- void RegisterProperty(const String& name,
- const String& syntax,
- const String& initial_value,
- bool is_inherited) {
- DummyExceptionStateForTesting exception_state;
- PropertyDescriptor property_descriptor;
- property_descriptor.setName(name);
- property_descriptor.setSyntax(syntax);
- property_descriptor.setInitialValue(initial_value);
- property_descriptor.setInherits(is_inherited);
- PropertyRegistration::registerProperty(&GetDocument(), property_descriptor,
- exception_state);
- EXPECT_FALSE(exception_state.HadException());
- }
-
void SetCustomProperty(const String& name, const String& value) {
DummyExceptionStateForTesting exception_state;
element_->style()->setProperty(&GetDocument(), name, value, g_empty_string,
@@ -457,13 +449,13 @@ class AnimationCompositorAnimationsTest : public RenderingTest {
void LoadTestData(const std::string& file_name) {
String testing_path = test::BlinkRootDir();
testing_path.append("/renderer/core/animation/test_data/");
- WebURL url = URLTestHelpers::RegisterMockedURLLoadFromBase(
+ WebURL url = url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), testing_path,
WebString::FromUTF8(file_name));
- FrameTestHelpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
- base_url_ + file_name);
+ frame_test_helpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
+ base_url_ + file_name);
ForceFullCompositingUpdate();
- URLTestHelpers::RegisterMockedURLUnregister(url);
+ url_test_helpers::RegisterMockedURLUnregister(url);
}
LocalFrame* GetFrame() const { return helper_.LocalMainFrame()->GetFrame(); }
@@ -473,11 +465,12 @@ class AnimationCompositorAnimationsTest : public RenderingTest {
}
void ForceFullCompositingUpdate() {
- helper_.GetWebView()->UpdateAllLifecyclePhases();
+ helper_.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
private:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
std::string base_url_;
};
@@ -580,8 +573,8 @@ TEST_F(AnimationCompositorAnimationsTest,
TEST_F(AnimationCompositorAnimationsTest,
CanStartEffectOnCompositorCustomCssProperty) {
ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
- RegisterProperty("--foo", "<number>", "0", false);
- RegisterProperty("--bar", "<length>", "10px", false);
+ RegisterProperty(GetDocument(), "--foo", "<number>", "0", false);
+ RegisterProperty(GetDocument(), "--bar", "<length>", "10px", false);
SetCustomProperty("--foo", "10");
SetCustomProperty("--bar", "10px");
@@ -595,10 +588,15 @@ TEST_F(AnimationCompositorAnimationsTest,
StringKeyframe* keyframe = CreateReplaceOpKeyframe("--foo", "10");
EXPECT_TRUE(DuplicateSingleKeyframeAndTestIsCandidateOnResult(keyframe));
+ // Length-valued properties are not compositable.
StringKeyframe* non_animatable_keyframe =
CreateReplaceOpKeyframe("--bar", "10px");
EXPECT_FALSE(DuplicateSingleKeyframeAndTestIsCandidateOnResult(
non_animatable_keyframe));
+
+ // Cannot composite due to side effect.
+ SetCustomProperty("opacity", "var(--foo)");
+ EXPECT_FALSE(DuplicateSingleKeyframeAndTestIsCandidateOnResult(keyframe));
}
TEST_F(AnimationCompositorAnimationsTest,
@@ -807,6 +805,7 @@ TEST_F(AnimationCompositorAnimationsTest,
TEST_F(AnimationCompositorAnimationsTest,
CanStartElementOnCompositorEffectOpacity) {
+ ScopedBlinkGenPropertyTreesForTest blink_gen_property_trees(true);
Persistent<Element> element = GetDocument().CreateElementForBinding("shared");
LayoutObjectProxy* layout_object = LayoutObjectProxy::Create(element.Get());
@@ -815,13 +814,13 @@ TEST_F(AnimationCompositorAnimationsTest,
CompositorElementIdSet compositor_ids;
compositor_ids.insert(CompositorElementIdFromUniqueObjectId(
- layout_object->UniqueId(), CompositorElementIdNamespace::kPrimary));
+ layout_object->UniqueId(), CompositorElementIdNamespace::kPrimaryEffect));
// We need an ID to be in the set, but not the same.
CompositorElementId different_id = CompositorElementIdFromUniqueObjectId(
layout_object->UniqueId(), CompositorElementIdNamespace::kEffectClipPath);
// Check that we got something effectively different.
- EXPECT_FALSE(compositor_ids.Contains(different_id));
+ EXPECT_FALSE(compositor_ids.count(different_id));
CompositorElementIdSet disjoint_ids;
compositor_ids.insert(different_id);
@@ -880,7 +879,8 @@ TEST_F(AnimationCompositorAnimationsTest,
// Timings have to be convertible for compositor.
compositor_ids.insert(CompositorElementIdFromUniqueObjectId(
- new_layout_object->UniqueId(), CompositorElementIdNamespace::kPrimary));
+ new_layout_object->UniqueId(),
+ CompositorElementIdNamespace::kPrimaryEffect));
EXPECT_TRUE(CheckCanStartEffectOnCompositor(
timing, *element.Get(), animation, *animation_effect, compositor_ids));
timing.end_delay = 1.0;
@@ -905,7 +905,7 @@ TEST_F(AnimationCompositorAnimationsTest,
CompositorElementIdSet compositor_ids;
compositor_ids.insert(CompositorElementIdFromUniqueObjectId(
- layout_object->UniqueId(), CompositorElementIdNamespace::kPrimary));
+ layout_object->UniqueId(), CompositorElementIdNamespace::kPrimaryEffect));
// Check that we notice the value is not animatable correctly.
const CSSProperty& target_property1(GetCSSPropertyOutlineStyle());
@@ -998,7 +998,7 @@ TEST_F(AnimationCompositorAnimationsTest,
CompositorElementId different_id = CompositorElementIdFromUniqueObjectId(
layout_object->UniqueId(), CompositorElementIdNamespace::kPrimary);
// Check that we got something effectively different.
- EXPECT_FALSE(compositor_ids.Contains(different_id));
+ EXPECT_FALSE(compositor_ids.count(different_id));
CompositorElementIdSet disjoint_ids;
compositor_ids.insert(different_id);
@@ -1048,6 +1048,7 @@ TEST_F(AnimationCompositorAnimationsTest,
TEST_F(AnimationCompositorAnimationsTest,
CanStartElementOnCompositorEffectTransform) {
+ ScopedBlinkGenPropertyTreesForTest blink_gen_property_trees(true);
Persistent<Element> element = GetDocument().CreateElementForBinding("shared");
LayoutObjectProxy* layout_object = LayoutObjectProxy::Create(element.Get());
@@ -1056,12 +1057,15 @@ TEST_F(AnimationCompositorAnimationsTest,
CompositorElementIdSet compositor_ids;
compositor_ids.insert(CompositorElementIdFromUniqueObjectId(
- layout_object->UniqueId(), CompositorElementIdNamespace::kPrimary));
+ layout_object->UniqueId(),
+ CompositorElementIdNamespace::kPrimaryTransform));
+ compositor_ids.insert(CompositorElementIdFromUniqueObjectId(
+ layout_object->UniqueId(), CompositorElementIdNamespace::kPrimaryEffect));
CompositorElementId different_id = CompositorElementIdFromUniqueObjectId(
layout_object->UniqueId(), CompositorElementIdNamespace::kEffectFilter);
// Check that we got something effectively different.
- EXPECT_FALSE(compositor_ids.Contains(different_id));
+ EXPECT_FALSE(compositor_ids.count(different_id));
CompositorElementIdSet disjoint_ids;
compositor_ids.insert(different_id);
@@ -1267,7 +1271,7 @@ TEST_F(AnimationCompositorAnimationsTest, CreateSimpleOpacityAnimation) {
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(1.0, keyframe_model->Iterations());
EXPECT_EQ(0, keyframe_model->TimeOffset());
@@ -1329,7 +1333,7 @@ TEST_F(AnimationCompositorAnimationsTest,
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect, 2.0);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(5.0, keyframe_model->Iterations());
EXPECT_EQ(0, keyframe_model->TimeOffset());
@@ -1381,7 +1385,7 @@ TEST_F(AnimationCompositorAnimationsTest,
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(5.0, keyframe_model->Iterations());
EXPECT_EQ(-kStartDelay, keyframe_model->TimeOffset());
@@ -1418,7 +1422,7 @@ TEST_F(AnimationCompositorAnimationsTest,
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(10.0, keyframe_model->Iterations());
EXPECT_EQ(0, keyframe_model->TimeOffset());
@@ -1479,7 +1483,7 @@ TEST_F(AnimationCompositorAnimationsTest, CreateReversedOpacityAnimation) {
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(10.0, keyframe_model->Iterations());
EXPECT_EQ(0, keyframe_model->TimeOffset());
@@ -1534,7 +1538,7 @@ TEST_F(AnimationCompositorAnimationsTest,
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(5.0, keyframe_model->Iterations());
EXPECT_EQ(-kNegativeStartDelay, keyframe_model->TimeOffset());
@@ -1576,7 +1580,7 @@ TEST_F(AnimationCompositorAnimationsTest,
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::OPACITY,
+ EXPECT_EQ(compositor_target_property::OPACITY,
keyframe_model->TargetProperty());
EXPECT_EQ(1.0, keyframe_model->Iterations());
EXPECT_EQ(0, keyframe_model->TimeOffset());
@@ -1634,7 +1638,7 @@ TEST_F(AnimationCompositorAnimationsTest,
CreateSimpleCustomFloatPropertyAnimation) {
ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
- RegisterProperty("--foo", "<number>", "0", false);
+ RegisterProperty(GetDocument(), "--foo", "<number>", "0", false);
SetCustomProperty("--foo", "10");
StringKeyframeEffectModel* effect =
@@ -1643,7 +1647,7 @@ TEST_F(AnimationCompositorAnimationsTest,
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
ConvertToCompositorAnimation(*effect);
- EXPECT_EQ(CompositorTargetProperty::CSS_CUSTOM_PROPERTY,
+ EXPECT_EQ(compositor_target_property::CSS_CUSTOM_PROPERTY,
keyframe_model->TargetProperty());
std::unique_ptr<CompositorFloatAnimationCurve> keyframed_float_curve =
@@ -1674,7 +1678,7 @@ TEST_F(AnimationCompositorAnimationsTest,
element->SetLayoutObject(layout_object);
Persistent<HeapVector<Member<StringKeyframe>>> key_frames =
- new HeapVector<Member<StringKeyframe>>;
+ MakeGarbageCollected<HeapVector<Member<StringKeyframe>>>();
key_frames->push_back(CreateDefaultKeyframe(
CSSPropertyOpacity, EffectModel::kCompositeReplace, 0.0));
key_frames->push_back(CreateDefaultKeyframe(
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_animatable_value_factory.h b/chromium/third_party/blink/renderer/core/animation/css/css_animatable_value_factory.h
index 30243107539..a4e34d54e83 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_animatable_value_factory.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_animatable_value_factory.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_CSS_ANIMATABLE_VALUE_FACTORY_H_
#include "third_party/blink/renderer/core/animation/animatable/animatable_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_animations.cc b/chromium/third_party/blink/renderer/core/animation/css/css_animations.cc
index 220aafd9171..a8bdb4b5871 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_animations.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_animations.cc
@@ -528,7 +528,7 @@ void CSSAnimations::MaybeApplyPendingUpdate(Element* element) {
for (const auto& entry : pending_update_.NewAnimations()) {
const InertEffect* inert_animation = entry.effect.Get();
AnimationEventDelegate* event_delegate =
- new AnimationEventDelegate(element, entry.name);
+ MakeGarbageCollected<AnimationEventDelegate>(element, entry.name);
KeyframeEffect* effect = KeyframeEffect::Create(
element, inert_animation->Model(), inert_animation->SpecifiedTiming(),
KeyframeEffect::kDefaultPriority, event_delegate);
@@ -538,7 +538,8 @@ void CSSAnimations::MaybeApplyPendingUpdate(Element* element) {
animation->pause();
animation->Update(kTimingUpdateOnDemand);
- running_animations_.push_back(new RunningAnimation(animation, entry));
+ running_animations_.push_back(
+ MakeGarbageCollected<RunningAnimation>(animation, entry));
}
// Transitions that are run on the compositor only update main-thread state
@@ -592,7 +593,7 @@ void CSSAnimations::MaybeApplyPendingUpdate(Element* element) {
const PropertyHandle& property = new_transition.property;
const InertEffect* inert_animation = new_transition.effect.Get();
TransitionEventDelegate* event_delegate =
- new TransitionEventDelegate(element, property);
+ MakeGarbageCollected<TransitionEventDelegate>(element, property);
KeyframeEffectModelBase* model = inert_animation->Model();
@@ -1119,7 +1120,7 @@ void CSSAnimations::CalculateTransitionActiveInterpolations(
}
EventTarget* CSSAnimations::AnimationEventDelegate::GetEventTarget() const {
- return EventPath::EventTargetRespectingTargetRules(*animation_target_);
+ return &EventPath::EventTargetRespectingTargetRules(*animation_target_);
}
void CSSAnimations::AnimationEventDelegate::MaybeDispatch(
@@ -1154,7 +1155,7 @@ void CSSAnimations::AnimationEventDelegate::OnEventCondition(
const double start_delay = animation_node.SpecifiedTiming().start_delay;
const double elapsed_time = start_delay < 0 ? -start_delay : 0;
MaybeDispatch(Document::kAnimationStartListener,
- EventTypeNames::animationstart, elapsed_time);
+ event_type_names::kAnimationstart, elapsed_time);
}
if (current_phase == AnimationEffect::kPhaseActive &&
@@ -1168,13 +1169,14 @@ void CSSAnimations::AnimationEventDelegate::OnEventCondition(
animation_node.SpecifiedTiming().iteration_duration.value() *
(previous_iteration_ + 1);
MaybeDispatch(Document::kAnimationIterationListener,
- EventTypeNames::animationiteration,
+ event_type_names::kAnimationiteration,
elapsed_time.InSecondsF());
}
if (current_phase == AnimationEffect::kPhaseAfter &&
previous_phase_ != AnimationEffect::kPhaseAfter) {
- MaybeDispatch(Document::kAnimationEndListener, EventTypeNames::animationend,
+ MaybeDispatch(Document::kAnimationEndListener,
+ event_type_names::kAnimationend,
animation_node.RepeatedDuration());
}
@@ -1188,7 +1190,7 @@ void CSSAnimations::AnimationEventDelegate::Trace(blink::Visitor* visitor) {
}
EventTarget* CSSAnimations::TransitionEventDelegate::GetEventTarget() const {
- return EventPath::EventTargetRespectingTargetRules(*transition_target_);
+ return &EventPath::EventTargetRespectingTargetRules(*transition_target_);
}
void CSSAnimations::TransitionEventDelegate::OnEventCondition(
@@ -1203,7 +1205,7 @@ void CSSAnimations::TransitionEventDelegate::OnEventCondition(
: property_.GetCSSProperty().GetPropertyNameString();
const Timing& timing = animation_node.SpecifiedTiming();
double elapsed_time = timing.iteration_duration->InSecondsF();
- const AtomicString& event_type = EventTypeNames::transitionend;
+ const AtomicString& event_type = event_type_names::kTransitionend;
String pseudo_element =
PseudoElement::PseudoElementNameForEvents(GetPseudoId());
TransitionEvent* event = TransitionEvent::Create(
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_animations_test.cc b/chromium/third_party/blink/renderer/core/animation/css/css_animations_test.cc
index ceaa7b74b0b..529e50a61c6 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_animations_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_animations_test.cc
@@ -15,7 +15,8 @@ namespace blink {
class CSSAnimationsTest : public RenderingTest {
public:
- CSSAnimationsTest() : chrome_client_(new StubChromeClientForSPv2()) {
+ CSSAnimationsTest()
+ : chrome_client_(MakeGarbageCollected<StubChromeClientForSPv2>()) {
EnablePlatform();
platform()->SetThreadedAnimationEnabled(true);
}
@@ -72,8 +73,8 @@ TEST_F(CSSAnimationsTest, RetargetedTransition) {
<div id='test'></div>
)HTML");
Element* element = GetDocument().getElementById("test");
- element->setAttribute(HTMLNames::classAttr, "contrast1");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ element->setAttribute(html_names::kClassAttr, "contrast1");
+ UpdateAllLifecyclePhasesForTest();
ElementAnimations* animations = element->GetElementAnimations();
EXPECT_EQ(1u, animations->Animations().size());
Animation* animation = (*animations->Animations().begin()).key;
@@ -83,15 +84,15 @@ TEST_F(CSSAnimationsTest, RetargetedTransition) {
AdvanceClockSeconds(0.8);
// Starting the second transition should retarget the active transition.
- element->setAttribute(HTMLNames::classAttr, "contrast2");
+ element->setAttribute(html_names::kClassAttr, "contrast2");
GetPage().Animator().ServiceScriptedAnimations(CurrentTimeTicks());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_DOUBLE_EQ(0.6, GetContrastFilterAmount(element));
// As it has been retargeted, advancing halfway should go to 0.3.
AdvanceClockSeconds(0.5);
GetPage().Animator().ServiceScriptedAnimations(CurrentTimeTicks());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_DOUBLE_EQ(0.3, GetContrastFilterAmount(element));
}
@@ -108,8 +109,8 @@ TEST_F(CSSAnimationsTest, IncompatibleRetargetedTransition) {
<div id='test'></div>
)HTML");
Element* element = GetDocument().getElementById("test");
- element->setAttribute(HTMLNames::classAttr, "saturate");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ element->setAttribute(html_names::kClassAttr, "saturate");
+ UpdateAllLifecyclePhasesForTest();
ElementAnimations* animations = element->GetElementAnimations();
EXPECT_EQ(1u, animations->Animations().size());
Animation* animation = (*animations->Animations().begin()).key;
@@ -125,9 +126,9 @@ TEST_F(CSSAnimationsTest, IncompatibleRetargetedTransition) {
// Now we start a contrast filter. Since it will try to combine with
// the in progress saturate filter, and be incompatible, there should
// be no transition and it should immediately apply on the next frame.
- element->setAttribute(HTMLNames::classAttr, "contrast");
+ element->setAttribute(html_names::kClassAttr, "contrast");
EXPECT_TRUE(element->GetComputedStyle()->Filter().IsEmpty());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(0.2, GetContrastFilterAmount(element));
}
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_transition_data.h b/chromium/third_party/blink/renderer/core/animation/css/css_transition_data.h
index 95801b65188..24bec6abe87 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_transition_data.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_transition_data.h
@@ -9,7 +9,7 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/css/css_timing_data.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_basic_shape_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_basic_shape_interpolation_type.cc
index 5848ec5c177..1b9fb29863c 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_basic_shape_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_basic_shape_interpolation_type.cc
@@ -9,9 +9,9 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/basic_shape_interpolation_functions.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/basic_shapes.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/data_equivalency.h"
@@ -61,7 +61,7 @@ class UnderlyingCompatibilityChecker
bool IsValid(const StyleResolverState&,
const InterpolationValue& underlying) const final {
- return BasicShapeInterpolationFunctions::ShapesAreCompatible(
+ return basic_shape_interpolation_functions::ShapesAreCompatible(
*underlying_non_interpolable_value_,
*underlying.non_interpolable_value);
}
@@ -106,7 +106,7 @@ InterpolationValue CSSBasicShapeInterpolationType::MaybeConvertNeutral(
conversion_checkers.push_back(
UnderlyingCompatibilityChecker::Create(non_interpolable_value));
return InterpolationValue(
- BasicShapeInterpolationFunctions::CreateNeutralValue(
+ basic_shape_interpolation_functions::CreateNeutralValue(
*underlying.non_interpolable_value),
non_interpolable_value);
}
@@ -114,7 +114,7 @@ InterpolationValue CSSBasicShapeInterpolationType::MaybeConvertNeutral(
InterpolationValue CSSBasicShapeInterpolationType::MaybeConvertInitial(
const StyleResolverState&,
ConversionCheckers&) const {
- return BasicShapeInterpolationFunctions::MaybeConvertBasicShape(
+ return basic_shape_interpolation_functions::MaybeConvertBasicShape(
GetBasicShape(CssProperty(), ComputedStyle::InitialStyle()), 1);
}
@@ -125,7 +125,7 @@ InterpolationValue CSSBasicShapeInterpolationType::MaybeConvertInherit(
// const_cast to take a ref.
conversion_checkers.push_back(InheritedShapeChecker::Create(
CssProperty(), const_cast<BasicShape*>(shape)));
- return BasicShapeInterpolationFunctions::MaybeConvertBasicShape(
+ return basic_shape_interpolation_functions::MaybeConvertBasicShape(
shape, state.ParentStyle()->EffectiveZoom());
}
@@ -134,18 +134,19 @@ InterpolationValue CSSBasicShapeInterpolationType::MaybeConvertValue(
const StyleResolverState*,
ConversionCheckers&) const {
if (!value.IsBaseValueList())
- return BasicShapeInterpolationFunctions::MaybeConvertCSSValue(value);
+ return basic_shape_interpolation_functions::MaybeConvertCSSValue(value);
const CSSValueList& list = ToCSSValueList(value);
if (list.length() != 1)
return nullptr;
- return BasicShapeInterpolationFunctions::MaybeConvertCSSValue(list.Item(0));
+ return basic_shape_interpolation_functions::MaybeConvertCSSValue(
+ list.Item(0));
}
PairwiseInterpolationValue CSSBasicShapeInterpolationType::MaybeMergeSingles(
InterpolationValue&& start,
InterpolationValue&& end) const {
- if (!BasicShapeInterpolationFunctions::ShapesAreCompatible(
+ if (!basic_shape_interpolation_functions::ShapesAreCompatible(
*start.non_interpolable_value, *end.non_interpolable_value))
return nullptr;
return PairwiseInterpolationValue(std::move(start.interpolable_value),
@@ -156,7 +157,7 @@ PairwiseInterpolationValue CSSBasicShapeInterpolationType::MaybeMergeSingles(
InterpolationValue
CSSBasicShapeInterpolationType::MaybeConvertStandardPropertyUnderlyingValue(
const ComputedStyle& style) const {
- return BasicShapeInterpolationFunctions::MaybeConvertBasicShape(
+ return basic_shape_interpolation_functions::MaybeConvertBasicShape(
GetBasicShape(CssProperty(), style), style.EffectiveZoom());
}
@@ -165,7 +166,7 @@ void CSSBasicShapeInterpolationType::Composite(
double underlying_fraction,
const InterpolationValue& value,
double interpolation_fraction) const {
- if (!BasicShapeInterpolationFunctions::ShapesAreCompatible(
+ if (!basic_shape_interpolation_functions::ShapesAreCompatible(
*underlying_value_owner.Value().non_interpolable_value,
*value.non_interpolable_value)) {
underlying_value_owner.Set(*this, value);
@@ -181,7 +182,7 @@ void CSSBasicShapeInterpolationType::ApplyStandardPropertyValue(
const NonInterpolableValue* non_interpolable_value,
StyleResolverState& state) const {
scoped_refptr<BasicShape> shape =
- BasicShapeInterpolationFunctions::CreateBasicShape(
+ basic_shape_interpolation_functions::CreateBasicShape(
interpolable_value, *non_interpolable_value,
state.CssToLengthConversionData());
switch (CssProperty().PropertyID()) {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
index 17b39503b9f..02b0d0062a4 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.cc
@@ -11,9 +11,9 @@
#include "third_party/blink/renderer/core/animation/length_interpolation_functions.h"
#include "third_party/blink/renderer/core/animation/side_index.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_quad_value.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc
index e21c49bd11a..924a3ab7893 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_color_interpolation_type.cc
@@ -159,8 +159,10 @@ Color CSSColorInterpolationType::ResolveInterpolableColor(
if (alpha == 0)
return Color::kTransparent;
- return MakeRGBA(round(red / alpha), round(green / alpha), round(blue / alpha),
- round(alpha));
+ return MakeRGBA(static_cast<int>(round(red / alpha)),
+ static_cast<int>(round(green / alpha)),
+ static_cast<int>(round(blue / alpha)),
+ static_cast<int>(round(alpha)));
}
class InheritedColorChecker
diff --git a/chromium/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc
index 62e27c37882..7cb1a882fe3 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc
@@ -39,7 +39,7 @@ void CSSDefaultInterpolationType::Apply(
InterpolationEnvironment& environment) const {
DCHECK(ToCSSDefaultNonInterpolableValue(non_interpolable_value)->CssValue());
StyleBuilder::ApplyProperty(
- GetProperty().GetCSSProperty(),
+ GetProperty().GetCSSPropertyName(),
ToCSSInterpolationEnvironment(environment).GetState(),
*ToCSSDefaultNonInterpolableValue(non_interpolable_value)->CssValue());
}
diff --git a/chromium/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc
index f32881e4b83..eea3067d4c7 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc
@@ -11,9 +11,9 @@
#include "third_party/blink/renderer/core/animation/filter_interpolation_functions.h"
#include "third_party/blink/renderer/core/animation/list_interpolation_functions.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
@@ -66,7 +66,7 @@ class UnderlyingFilterListChecker
underlying_non_interpolable_list.length())
return false;
for (wtf_size_t i = 0; i < non_interpolable_list_->length(); i++) {
- if (!FilterInterpolationFunctions::FiltersAreCompatible(
+ if (!filter_interpolation_functions::FiltersAreCompatible(
*non_interpolable_list_->Get(i),
*underlying_non_interpolable_list.Get(i)))
return false;
@@ -118,7 +118,7 @@ InterpolationValue ConvertFilterList(const FilterOperations& filter_operations,
Vector<scoped_refptr<NonInterpolableValue>> non_interpolable_values(length);
for (wtf_size_t i = 0; i < length; i++) {
InterpolationValue filter_result =
- FilterInterpolationFunctions::MaybeConvertFilter(
+ filter_interpolation_functions::MaybeConvertFilter(
*filter_operations.Operations()[i], zoom);
if (!filter_result)
return nullptr;
@@ -182,7 +182,7 @@ InterpolationValue CSSFilterListInterpolationType::MaybeConvertValue(
Vector<scoped_refptr<NonInterpolableValue>> non_interpolable_values(length);
for (wtf_size_t i = 0; i < length; i++) {
InterpolationValue item_result =
- FilterInterpolationFunctions::MaybeConvertCSSFilter(list.Item(i));
+ filter_interpolation_functions::MaybeConvertCSSFilter(list.Item(i));
if (!item_result)
return nullptr;
interpolable_list->Set(i, std::move(item_result.interpolable_value));
@@ -211,7 +211,7 @@ PairwiseInterpolationValue CSSFilterListInterpolationType::MaybeMergeSingles(
wtf_size_t end_length = end_non_interpolable_list.length();
for (wtf_size_t i = 0; i < start_length && i < end_length; i++) {
- if (!FilterInterpolationFunctions::FiltersAreCompatible(
+ if (!filter_interpolation_functions::FiltersAreCompatible(
*start_non_interpolable_list.Get(i),
*end_non_interpolable_list.Get(i)))
return nullptr;
@@ -243,7 +243,7 @@ PairwiseInterpolationValue CSSFilterListInterpolationType::MaybeMergeSingles(
i, std::move(shorter_interpolable_list.GetMutable(i)));
else
extended_interpolable_list->Set(
- i, FilterInterpolationFunctions::CreateNoneValue(
+ i, filter_interpolation_functions::CreateNoneValue(
*longer_non_interpolable_list.Get(i)));
}
shorter.interpolable_value = std::move(extended_interpolable_list);
@@ -267,7 +267,7 @@ void CSSFilterListInterpolationType::Composite(
wtf_size_t length = non_interpolable_list.length();
for (wtf_size_t i = 0; i < underlying_length && i < length; i++) {
- if (!FilterInterpolationFunctions::FiltersAreCompatible(
+ if (!filter_interpolation_functions::FiltersAreCompatible(
*underlying_non_interpolable_list.Get(i),
*non_interpolable_list.Get(i))) {
underlying_value_owner.Set(*this, value);
@@ -320,7 +320,7 @@ void CSSFilterListInterpolationType::ApplyStandardPropertyValue(
filter_operations.Operations().ReserveCapacity(length);
for (wtf_size_t i = 0; i < length; i++) {
filter_operations.Operations().push_back(
- FilterInterpolationFunctions::CreateFilter(
+ filter_interpolation_functions::CreateFilter(
*interpolable_list.Get(i), *non_interpolable_list.Get(i), state));
}
SetFilterList(CssProperty(), *state.Style(), std::move(filter_operations));
diff --git a/chromium/third_party/blink/renderer/core/animation/css_font_size_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_font_size_interpolation_type.cc
index 981eff3bbdb..0bd5d9c40fd 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_font_size_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_font_size_interpolation_type.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc
index 7e2a933520f..a363e1f7bbc 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_font_variation_settings_interpolation_type.cc
@@ -212,7 +212,8 @@ void CSSFontVariationSettingsInterpolationType::ApplyStandardPropertyValue(
wtf_size_t length = numbers.length();
for (wtf_size_t i = 0; i < length; ++i) {
settings->Append(FontVariationAxis(
- tags[i], ToInterpolableNumber(numbers.Get(i))->Value()));
+ tags[i],
+ static_cast<float>(ToInterpolableNumber(numbers.Get(i))->Value())));
}
state.GetFontBuilder().SetVariationSettings(settings);
}
diff --git a/chromium/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc
index 5231eb71a77..067f9b6425b 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc
@@ -9,8 +9,8 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/css/css_crossfade_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/style_image.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc
index 22f11ffd12b..504e59f143d 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_image_list_interpolation_type.cc
@@ -51,7 +51,7 @@ InterpolationValue CSSImageListInterpolationType::MaybeConvertNeutral(
InterpolationValue CSSImageListInterpolationType::MaybeConvertInitial(
const StyleResolverState&,
ConversionCheckers& conversion_checkers) const {
- StyleImageList* initial_image_list = new StyleImageList;
+ StyleImageList* initial_image_list = MakeGarbageCollected<StyleImageList>();
ImageListPropertyFunctions::GetInitialImageList(CssProperty(),
initial_image_list);
return MaybeConvertStyleImageList(initial_image_list);
@@ -88,7 +88,8 @@ class InheritedImageListChecker
bool IsValid(const StyleResolverState& state,
const InterpolationValue& underlying) const final {
- StyleImageList* inherited_image_list = new StyleImageList;
+ StyleImageList* inherited_image_list =
+ MakeGarbageCollected<StyleImageList>();
ImageListPropertyFunctions::GetImageList(property_, *state.ParentStyle(),
inherited_image_list);
return inherited_image_list_ == inherited_image_list;
@@ -104,7 +105,7 @@ InterpolationValue CSSImageListInterpolationType::MaybeConvertInherit(
if (!state.ParentStyle())
return nullptr;
- StyleImageList* inherited_image_list = new StyleImageList();
+ StyleImageList* inherited_image_list = MakeGarbageCollected<StyleImageList>();
ImageListPropertyFunctions::GetImageList(CssProperty(), *state.ParentStyle(),
inherited_image_list);
conversion_checkers.push_back(
@@ -159,7 +160,8 @@ PairwiseInterpolationValue CSSImageListInterpolationType::MaybeMergeSingles(
InterpolationValue
CSSImageListInterpolationType::MaybeConvertStandardPropertyUnderlyingValue(
const ComputedStyle& style) const {
- StyleImageList* underlying_image_list = new StyleImageList();
+ StyleImageList* underlying_image_list =
+ MakeGarbageCollected<StyleImageList>();
ImageListPropertyFunctions::GetImageList(CssProperty(), style,
underlying_image_list);
return MaybeConvertStyleImageList(underlying_image_list);
@@ -184,7 +186,7 @@ void CSSImageListInterpolationType::ApplyStandardPropertyValue(
const NonInterpolableList& non_interpolable_list =
ToNonInterpolableList(*non_interpolable_value);
DCHECK_EQ(non_interpolable_list.length(), length);
- StyleImageList* image_list = new StyleImageList(length);
+ StyleImageList* image_list = MakeGarbageCollected<StyleImageList>(length);
for (wtf_size_t i = 0; i < length; i++) {
image_list->at(i) = CSSImageInterpolationType::ResolveStyleImage(
CssProperty(), *interpolable_list.Get(i), non_interpolable_list.Get(i),
diff --git a/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.cc
index c1613129a6c..101252cb947 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.cc
@@ -120,7 +120,7 @@ class ResolvedRegisteredCustomPropertyChecker
bool IsValid(const InterpolationEnvironment& environment,
const InterpolationValue&) const final {
DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver());
- bool cycle_detected;
+ bool cycle_detected = false;
scoped_refptr<CSSVariableData> resolved_tokens =
ToCSSInterpolationEnvironment(environment)
.VariableResolver()
@@ -233,7 +233,7 @@ InterpolationValue CSSInterpolationType::MaybeConvertCustomPropertyDeclaration(
scoped_refptr<CSSVariableData> resolved_tokens;
if (declaration.Value()->NeedsVariableResolution()) {
- bool cycle_detected;
+ bool cycle_detected = false;
resolved_tokens = variable_resolver.ResolveCustomPropertyAnimationKeyframe(
declaration, cycle_detected);
DCHECK(!cycle_detected);
@@ -266,12 +266,8 @@ InterpolationValue CSSInterpolationType::MaybeConvertUnderlyingValue(
const AtomicString& name = property.CustomPropertyName();
const CSSValue* underlying_value =
style.GetRegisteredVariable(name, Registration().Inherits());
- if (!underlying_value) {
- underlying_value = Registration().Initial();
- }
- if (!underlying_value) {
+ if (!underlying_value)
return nullptr;
- }
// TODO(alancutter): Remove the need for passing in conversion checkers.
ConversionCheckers dummy_conversion_checkers;
return MaybeConvertValue(*underlying_value, nullptr,
diff --git a/chromium/third_party/blink/renderer/core/animation/css_interpolation_types_map.cc b/chromium/third_party/blink/renderer/core/animation/css_interpolation_types_map.cc
index 4252f4a60f5..602dd12cacf 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_interpolation_types_map.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_interpolation_types_map.cc
@@ -46,6 +46,7 @@
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
+#include "third_party/blink/renderer/core/feature_policy/layout_animations_policy.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
namespace blink {
@@ -55,7 +56,7 @@ CSSInterpolationTypesMap::CSSInterpolationTypesMap(
const Document& document)
: registry_(registry) {
allow_all_animations_ = document.IsFeatureEnabled(
- blink::mojom::FeaturePolicyFeature::kAnimations);
+ blink::mojom::FeaturePolicyFeature::kLayoutAnimations);
}
static const PropertyRegistration* GetRegistration(
@@ -112,14 +113,9 @@ const InterpolationTypes& CSSInterpolationTypesMap::Get(
property.IsCSSProperty() ? property : PropertyHandle(css_property);
// TODO(crbug.com/838263): Support site-defined list of acceptable properties
// through feature policy declarations.
- bool is_compositor_animatable_property =
- (css_property.IDEquals(CSSPropertyFilter) ||
- css_property.IDEquals(CSSPropertyOpacity) ||
- css_property.IDEquals(CSSPropertyRotate) ||
- css_property.IDEquals(CSSPropertyScale) ||
- css_property.IDEquals(CSSPropertyTransform) ||
- css_property.IDEquals(CSSPropertyTranslate));
- if (allow_all_animations_ || is_compositor_animatable_property) {
+ bool property_maybe_blocked_by_feature_policy =
+ LayoutAnimationsPolicy::AffectedCSSProperties().Contains(&css_property);
+ if (allow_all_animations_ || !property_maybe_blocked_by_feature_policy) {
switch (css_property.PropertyID()) {
case CSSPropertyBaselineShift:
case CSSPropertyBorderBottomWidth:
@@ -436,7 +432,7 @@ CSSInterpolationTypesMap::CreateInterpolationTypesForCSSSyntax(
for (const CSSSyntaxComponent& component : descriptor.Components()) {
std::unique_ptr<CSSInterpolationType> interpolation_type =
- CreateInterpolationTypeForCSSSyntax(component.type_, property,
+ CreateInterpolationTypeForCSSSyntax(component.GetType(), property,
registration);
if (!interpolation_type)
@@ -445,7 +441,7 @@ CSSInterpolationTypesMap::CreateInterpolationTypesForCSSSyntax(
if (component.IsRepeatable()) {
interpolation_type = std::make_unique<CSSCustomListInterpolationType>(
property, &registration, std::move(interpolation_type),
- component.repeat_);
+ component.GetRepeat());
}
result.push_back(std::move(interpolation_type));
diff --git a/chromium/third_party/blink/renderer/core/animation/css_length_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_length_interpolation_type.cc
index 87b110f4769..26c93224804 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_length_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_length_interpolation_type.cc
@@ -16,7 +16,7 @@
#include "third_party/blink/renderer/core/css/resolver/style_builder.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -154,9 +154,11 @@ void CSSLengthInterpolationType::ApplyStandardPropertyValue(
StyleResolverState& state) const {
ComputedStyle& style = *state.Style();
float zoom = EffectiveZoom(style);
+ CSSToLengthConversionData conversion_data = state.CssToLengthConversionData();
+ conversion_data.SetZoom(zoom);
Length length = LengthInterpolationFunctions::CreateLength(
- interpolable_value, non_interpolable_value,
- state.CssToLengthConversionData(), value_range_);
+ interpolable_value, non_interpolable_value, conversion_data,
+ value_range_);
if (LengthPropertyFunctions::SetLength(CssProperty(), style, length)) {
#if DCHECK_IS_ON()
// Assert that setting the length on ComputedStyle directly is identical to
diff --git a/chromium/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.h
index b000e5e5170..f844ab40451 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.h
+++ b/chromium/third_party/blink/renderer/core/animation/css_length_list_interpolation_type.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/animation/css_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_length_interpolation_type.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_paint_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_paint_interpolation_type.cc
index 052bfa81fa9..b3e637382fd 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_paint_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_paint_interpolation_type.cc
@@ -9,9 +9,9 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/css_color_interpolation_type.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
#include "third_party/blink/renderer/core/css/style_color.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc
index 7b0321163c3..0071b81ef8d 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_shadow_list_interpolation_type.cc
@@ -11,10 +11,10 @@
#include "third_party/blink/renderer/core/animation/list_interpolation_functions.h"
#include "third_party/blink/renderer/core/animation/shadow_interpolation_functions.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/shadow_list.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/css_transform_origin_interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/css_transform_origin_interpolation_type.h
index 0ab0b229c16..98779ab5359 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_transform_origin_interpolation_type.h
+++ b/chromium/third_party/blink/renderer/core/animation/css_transform_origin_interpolation_type.h
@@ -24,9 +24,14 @@ class CSSTransformOriginInterpolationType
const StyleResolverState*,
ConversionCheckers&) const final {
const CSSValueList& list = ToCSSValueList(value);
- DCHECK_EQ(list.length(), 3U);
+ DCHECK_GE(list.length(), 2u);
return ListInterpolationFunctions::CreateList(
- list.length(), [&list](wtf_size_t index) {
+ 3, [&list](wtf_size_t index) {
+ if (index == list.length()) {
+ return LengthInterpolationFunctions::MaybeConvertCSSValue(
+ *CSSPrimitiveValue::Create(
+ 0, CSSPrimitiveValue::UnitType::kPixels));
+ }
const CSSValue& item = list.Item(index);
if (index < 2)
return CSSPositionAxisListInterpolationType::
diff --git a/chromium/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc
index 34056ff4bda..5ade91cdd13 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc
@@ -125,7 +125,7 @@ void CSSVarCycleInterpolationType::Apply(
const NonInterpolableValue*,
InterpolationEnvironment& environment) const {
StyleBuilder::ApplyProperty(
- GetProperty().GetCSSProperty(),
+ GetProperty().GetCSSPropertyName(),
ToCSSInterpolationEnvironment(environment).GetState(),
*CSSCustomPropertyDeclaration::Create(GetProperty().CustomPropertyName(),
CSSValueUnset));
diff --git a/chromium/third_party/blink/renderer/core/animation/document_animations.h b/chromium/third_party/blink/renderer/core/animation/document_animations.h
index a0da056eb37..024c5c4404a 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_animations.h
+++ b/chromium/third_party/blink/renderer/core/animation/document_animations.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_DOCUMENT_ANIMATIONS_H_
#include "base/optional.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document_lifecycle.h"
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/document_timeline.cc b/chromium/third_party/blink/renderer/core/animation/document_timeline.cc
index 0b766a630ad..f83a0fe1c0e 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_timeline.cc
+++ b/chromium/third_party/blink/renderer/core/animation/document_timeline.cc
@@ -62,15 +62,15 @@ const double DocumentTimeline::kMinimumDelay = 0.04;
DocumentTimeline* DocumentTimeline::Create(Document* document,
TimeDelta origin_time,
PlatformTiming* timing) {
- return new DocumentTimeline(document, origin_time, timing);
+ return MakeGarbageCollected<DocumentTimeline>(document, origin_time, timing);
}
DocumentTimeline* DocumentTimeline::Create(
ExecutionContext* execution_context,
- const DocumentTimelineOptions& options) {
+ const DocumentTimelineOptions* options) {
Document* document = To<Document>(execution_context);
- return new DocumentTimeline(
- document, TimeDelta::FromMillisecondsD(options.originTime()), nullptr);
+ return MakeGarbageCollected<DocumentTimeline>(
+ document, TimeDelta::FromMillisecondsD(options->originTime()), nullptr);
}
DocumentTimeline::DocumentTimeline(Document* document,
@@ -84,7 +84,7 @@ DocumentTimeline::DocumentTimeline(Document* document,
playback_rate_(1),
last_current_time_internal_(0) {
if (!timing)
- timing_ = new DocumentTimelineTiming(this);
+ timing_ = MakeGarbageCollected<DocumentTimelineTiming>(this);
else
timing_ = timing;
diff --git a/chromium/third_party/blink/renderer/core/animation/document_timeline.h b/chromium/third_party/blink/renderer/core/animation/document_timeline.h
index 853446ecb79..5b46323014e 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_timeline.h
+++ b/chromium/third_party/blink/renderer/core/animation/document_timeline.h
@@ -74,8 +74,9 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
// Web Animations API IDL constructor
static DocumentTimeline* Create(ExecutionContext*,
- const DocumentTimelineOptions&);
+ const DocumentTimelineOptions*);
+ DocumentTimeline(Document*, TimeDelta origin_time, PlatformTiming*);
~DocumentTimeline() override = default;
bool IsDocumentTimeline() const final { return true; }
@@ -125,8 +126,6 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
void Trace(blink::Visitor*) override;
private:
- DocumentTimeline(Document*, TimeDelta origin_time, PlatformTiming*);
-
Member<Document> document_;
// Origin time for the timeline relative to the time origin of the document.
// Provided when the timeline is constructed. See
diff --git a/chromium/third_party/blink/renderer/core/animation/document_timeline_test.cc b/chromium/third_party/blink/renderer/core/animation/document_timeline_test.cc
index 43fc0a941b4..2d8daa7ce8a 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_timeline_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/document_timeline_test.cc
@@ -63,7 +63,7 @@ class AnimationDocumentTimelineTest : public PageTestBase {
document = &GetDocument();
GetAnimationClock().ResetTimeForTesting();
element = Element::Create(QualifiedName::Null(), document.Get());
- platform_timing = new MockPlatformTiming;
+ platform_timing = MakeGarbageCollected<MockPlatformTiming>();
timeline =
DocumentTimeline::Create(document.Get(), TimeDelta(), platform_timing);
timeline->ResetForTesting();
diff --git a/chromium/third_party/blink/renderer/core/animation/effect_input.cc b/chromium/third_party/blink/renderer/core/animation/effect_input.cc
index 2bcbbc93f11..c2e3d0c7247 100644
--- a/chromium/third_party/blink/renderer/core/animation/effect_input.cc
+++ b/chromium/third_party/blink/renderer/core/animation/effect_input.cc
@@ -63,9 +63,9 @@ namespace {
// Converts the composite property of a BasePropertyIndexedKeyframe into a
// vector of base::Optional<EffectModel::CompositeOperation> enums.
Vector<base::Optional<EffectModel::CompositeOperation>> ParseCompositeProperty(
- const BasePropertyIndexedKeyframe& keyframe) {
+ const BasePropertyIndexedKeyframe* keyframe) {
const CompositeOperationOrAutoOrCompositeOperationOrAutoSequence& composite =
- keyframe.composite();
+ keyframe->composite();
if (composite.IsCompositeOperationOrAuto()) {
return {EffectModel::StringToCompositeOperation(
@@ -205,12 +205,6 @@ bool IsAnimatableKeyframeAttribute(const String& property,
element);
}
-// Temporary storage struct used when converting array-form keyframes.
-struct KeyframeOutput {
- BaseKeyframe base_keyframe;
- Vector<std::pair<String, String>> property_value_pairs;
-};
-
void AddPropertyValuePairsForKeyframe(
v8::Isolate* isolate,
v8::Local<v8::Object> keyframe_obj,
@@ -273,7 +267,8 @@ StringKeyframeVector ConvertArrayForm(Element* element,
// This loop captures step 5 of the procedure to process a keyframes argument,
// in the case where the argument is iterable.
- Vector<KeyframeOutput> processed_keyframes;
+ HeapVector<Member<const BaseKeyframe>> processed_base_keyframes;
+ Vector<Vector<std::pair<String, String>>> processed_properties;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
while (iterator.Next(execution_context, exception_state)) {
if (exception_state.HadException())
@@ -289,22 +284,22 @@ StringKeyframeVector ConvertArrayForm(Element* element,
return {};
}
- KeyframeOutput keyframe_output;
- keyframe_output.base_keyframe =
- NativeValueTraits<BaseKeyframe>::NativeValue(isolate, keyframe,
- exception_state);
+ BaseKeyframe* base_keyframe = NativeValueTraits<BaseKeyframe>::NativeValue(
+ isolate, keyframe, exception_state);
+ Vector<std::pair<String, String>> property_value_pairs;
if (exception_state.HadException())
return {};
if (!keyframe->IsNullOrUndefined()) {
AddPropertyValuePairsForKeyframe(
isolate, v8::Local<v8::Object>::Cast(keyframe), element, document,
- keyframe_output.property_value_pairs, exception_state);
+ property_value_pairs, exception_state);
if (exception_state.HadException())
return {};
}
- processed_keyframes.push_back(keyframe_output);
+ processed_base_keyframes.push_back(base_keyframe);
+ processed_properties.push_back(property_value_pairs);
}
// If the very first call to next() throws the above loop will never be
// entered, so we have to catch that here.
@@ -314,53 +309,56 @@ StringKeyframeVector ConvertArrayForm(Element* element,
// 6. If processed keyframes is not loosely sorted by offset, throw a
// TypeError and abort these steps.
double previous_offset = -std::numeric_limits<double>::infinity();
- for (const auto& processed_keyframe : processed_keyframes) {
- if (processed_keyframe.base_keyframe.hasOffset()) {
- double offset = processed_keyframe.base_keyframe.offset();
- if (offset < previous_offset) {
- exception_state.ThrowTypeError(
- "Offsets must be montonically non-decreasing.");
- return {};
- }
- previous_offset = offset;
+ const wtf_size_t num_processed_keyframes = processed_base_keyframes.size();
+ for (wtf_size_t i = 0; i < num_processed_keyframes; ++i) {
+ if (!processed_base_keyframes[i]->hasOffset())
+ continue;
+
+ double offset = processed_base_keyframes[i]->offset();
+ if (offset < previous_offset) {
+ exception_state.ThrowTypeError(
+ "Offsets must be montonically non-decreasing.");
+ return {};
}
+ previous_offset = offset;
}
// 7. If there exist any keyframe in processed keyframes whose keyframe
// offset is non-null and less than zero or greater than one, throw a
// TypeError and abort these steps.
- for (const auto& processed_keyframe : processed_keyframes) {
- if (processed_keyframe.base_keyframe.hasOffset()) {
- double offset = processed_keyframe.base_keyframe.offset();
- if (offset < 0 || offset > 1) {
- exception_state.ThrowTypeError(
- "Offsets must be null or in the range [0,1].");
- return {};
- }
+ for (wtf_size_t i = 0; i < num_processed_keyframes; ++i) {
+ if (!processed_base_keyframes[i]->hasOffset())
+ continue;
+
+ double offset = processed_base_keyframes[i]->offset();
+ if (offset < 0 || offset > 1) {
+ exception_state.ThrowTypeError(
+ "Offsets must be null or in the range [0,1].");
+ return {};
}
}
StringKeyframeVector keyframes;
- for (const KeyframeOutput& processed_keyframe : processed_keyframes) {
+ for (wtf_size_t i = 0; i < num_processed_keyframes; ++i) {
// Now we create the actual Keyframe object. We start by assigning the
// offset and composite values; conceptually these were actually added in
// step 5 above but we didn't have a keyframe object then.
+ const BaseKeyframe* base_keyframe = processed_base_keyframes[i];
StringKeyframe* keyframe = StringKeyframe::Create();
- if (processed_keyframe.base_keyframe.hasOffset()) {
- keyframe->SetOffset(processed_keyframe.base_keyframe.offset());
+ if (base_keyframe->hasOffset()) {
+ keyframe->SetOffset(base_keyframe->offset());
}
// 8.1. For each property-value pair in frame, parse the property value
// using the syntax specified for that property.
- for (const auto& pair : processed_keyframe.property_value_pairs) {
+ for (const auto& pair : processed_properties[i]) {
// TODO(crbug.com/777971): Make parsing of property values spec-compliant.
SetKeyframeValue(element, document, *keyframe, pair.first, pair.second,
execution_context);
}
base::Optional<EffectModel::CompositeOperation> composite =
- EffectModel::StringToCompositeOperation(
- processed_keyframe.base_keyframe.composite());
+ EffectModel::StringToCompositeOperation(base_keyframe->composite());
if (composite) {
keyframe->SetComposite(
ResolveCompositeOperationForKeyframe(composite.value(), keyframe));
@@ -373,9 +371,8 @@ StringKeyframeVector ConvertArrayForm(Element* element,
// If parsing the “easing” property fails, throw a TypeError and abort this
// procedure.
scoped_refptr<TimingFunction> timing_function =
- AnimationInputHelpers::ParseTimingFunction(
- processed_keyframe.base_keyframe.easing(), &document,
- exception_state);
+ AnimationInputHelpers::ParseTimingFunction(base_keyframe->easing(),
+ &document, exception_state);
if (!timing_function)
return {};
keyframe->SetEasing(timing_function);
@@ -438,27 +435,27 @@ StringKeyframeVector ConvertObjectForm(Element* element,
// Extract the offset, easing, and composite as per step 1 of the 'procedure
// to process a keyframe-like object'.
- BasePropertyIndexedKeyframe property_indexed_keyframe =
+ BasePropertyIndexedKeyframe* property_indexed_keyframe =
NativeValueTraits<BasePropertyIndexedKeyframe>::NativeValue(
script_state->GetIsolate(), keyframe, exception_state);
if (exception_state.HadException())
return {};
Vector<base::Optional<double>> offsets;
- if (property_indexed_keyframe.offset().IsNull())
+ if (property_indexed_keyframe->offset().IsNull())
offsets.push_back(base::nullopt);
- else if (property_indexed_keyframe.offset().IsDouble())
- offsets.push_back(property_indexed_keyframe.offset().GetAsDouble());
+ else if (property_indexed_keyframe->offset().IsDouble())
+ offsets.push_back(property_indexed_keyframe->offset().GetAsDouble());
else
- offsets = property_indexed_keyframe.offset().GetAsDoubleOrNullSequence();
+ offsets = property_indexed_keyframe->offset().GetAsDoubleOrNullSequence();
// The web-animations spec explicitly states that easings should be kept as
// DOMStrings here and not parsed into timing functions until later.
Vector<String> easings;
- if (property_indexed_keyframe.easing().IsString())
- easings.push_back(property_indexed_keyframe.easing().GetAsString());
+ if (property_indexed_keyframe->easing().IsString())
+ easings.push_back(property_indexed_keyframe->easing().GetAsString());
else
- easings = property_indexed_keyframe.easing().GetAsStringSequence();
+ easings = property_indexed_keyframe->easing().GetAsStringSequence();
Vector<base::Optional<EffectModel::CompositeOperation>> composite_operations =
ParseCompositeProperty(property_indexed_keyframe);
diff --git a/chromium/third_party/blink/renderer/core/animation/effect_model.h b/chromium/third_party/blink/renderer/core/animation/effect_model.h
index 688e3b19680..bec992ba60e 100644
--- a/chromium/third_party/blink/renderer/core/animation/effect_model.h
+++ b/chromium/third_party/blink/renderer/core/animation/effect_model.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/animation/animation_time_delta.h"
#include "third_party/blink/renderer/core/animation/property_handle.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/effect_stack_test.cc b/chromium/third_party/blink/renderer/core/animation/effect_stack_test.cc
index 0ccd06844b5..9cf45e94c32 100644
--- a/chromium/third_party/blink/renderer/core/animation/effect_stack_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/effect_stack_test.cc
@@ -180,8 +180,8 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
UpdateTimeline(TimeDelta::FromSeconds(11));
ThreadState::Current()->CollectAllGarbage();
- interpolations =
- new ActiveInterpolationsMap(EffectStack::ActiveInterpolations(
+ interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
+ EffectStack::ActiveInterpolations(
&element->GetElementAnimations()->GetEffectStack(), nullptr, nullptr,
KeyframeEffect::kDefaultPriority));
EXPECT_EQ(1u, interpolations->size());
@@ -190,8 +190,8 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
UpdateTimeline(TimeDelta::FromSeconds(13));
ThreadState::Current()->CollectAllGarbage();
- interpolations =
- new ActiveInterpolationsMap(EffectStack::ActiveInterpolations(
+ interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
+ EffectStack::ActiveInterpolations(
&element->GetElementAnimations()->GetEffectStack(), nullptr, nullptr,
KeyframeEffect::kDefaultPriority));
EXPECT_EQ(1u, interpolations->size());
@@ -200,8 +200,8 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
UpdateTimeline(TimeDelta::FromSeconds(15));
ThreadState::Current()->CollectAllGarbage();
- interpolations =
- new ActiveInterpolationsMap(EffectStack::ActiveInterpolations(
+ interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
+ EffectStack::ActiveInterpolations(
&element->GetElementAnimations()->GetEffectStack(), nullptr, nullptr,
KeyframeEffect::kDefaultPriority));
EXPECT_EQ(1u, interpolations->size());
@@ -210,8 +210,8 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
UpdateTimeline(TimeDelta::FromSeconds(17));
ThreadState::Current()->CollectAllGarbage();
- interpolations =
- new ActiveInterpolationsMap(EffectStack::ActiveInterpolations(
+ interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
+ EffectStack::ActiveInterpolations(
&element->GetElementAnimations()->GetEffectStack(), nullptr, nullptr,
KeyframeEffect::kDefaultPriority));
EXPECT_EQ(1u, interpolations->size());
diff --git a/chromium/third_party/blink/renderer/core/animation/element_animation.cc b/chromium/third_party/blink/renderer/core/animation/element_animation.cc
index 112c286fb8a..0999d0082b5 100644
--- a/chromium/third_party/blink/renderer/core/animation/element_animation.cc
+++ b/chromium/third_party/blink/renderer/core/animation/element_animation.cc
@@ -14,10 +14,30 @@
#include "third_party/blink/renderer/core/animation/timing_input.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/feature_policy/feature_policy.h"
+#include "third_party/blink/renderer/core/feature_policy/layout_animations_policy.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
+namespace {
+
+// A helper method which is used to trigger a violation report for cases where
+// the |element.animate| API is used to animate a CSS property which is blocked
+// by the feature policy 'layout-animations'.
+void ReportFeaturePolicyViolationsIfNecessary(
+ const Document& document,
+ const KeyframeEffectModelBase& effect) {
+ if (document.IsFeatureEnabled(mojom::FeaturePolicyFeature::kLayoutAnimations))
+ return;
+ for (const auto* blocked_property :
+ LayoutAnimationsPolicy::AffectedCSSProperties()) {
+ if (effect.Affects(PropertyHandle(*blocked_property)))
+ LayoutAnimationsPolicy::ReportViolation(*blocked_property, document);
+ }
+}
+
+} // namespace
Animation* ElementAnimation::animate(
ScriptState* script_state,
@@ -28,7 +48,7 @@ Animation* ElementAnimation::animate(
EffectModel::CompositeOperation composite = EffectModel::kCompositeReplace;
if (options.IsKeyframeAnimationOptions()) {
composite = EffectModel::StringToCompositeOperation(
- options.GetAsKeyframeAnimationOptions().composite())
+ options.GetAsKeyframeAnimationOptions()->composite())
.value();
}
@@ -44,7 +64,7 @@ Animation* ElementAnimation::animate(
Animation* animation = animateInternal(element, effect, timing);
if (options.IsKeyframeAnimationOptions())
- animation->setId(options.GetAsKeyframeAnimationOptions().id());
+ animation->setId(options.GetAsKeyframeAnimationOptions()->id());
return animation;
}
@@ -81,6 +101,7 @@ HeapVector<Member<Animation>> ElementAnimation::getAnimations(
Animation* ElementAnimation::animateInternal(Element& element,
KeyframeEffectModelBase* effect,
const Timing& timing) {
+ ReportFeaturePolicyViolationsIfNecessary(element.GetDocument(), *effect);
KeyframeEffect* keyframe_effect =
KeyframeEffect::Create(&element, effect, timing);
return element.GetDocument().Timeline().Play(keyframe_effect);
diff --git a/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.cc b/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.cc
index 7b3278abf61..1e21c15e1c5 100644
--- a/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.cc
+++ b/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.cc
@@ -92,7 +92,7 @@ double ClampParameter(double value, FilterOperation::OperationType type) {
} // namespace
-InterpolationValue FilterInterpolationFunctions::MaybeConvertCSSFilter(
+InterpolationValue filter_interpolation_functions::MaybeConvertCSSFilter(
const CSSValue& value) {
if (value.IsURIValue())
return nullptr;
@@ -160,7 +160,7 @@ InterpolationValue FilterInterpolationFunctions::MaybeConvertCSSFilter(
return result;
}
-InterpolationValue FilterInterpolationFunctions::MaybeConvertFilter(
+InterpolationValue filter_interpolation_functions::MaybeConvertFilter(
const FilterOperation& filter,
double zoom) {
InterpolationValue result = nullptr;
@@ -210,7 +210,7 @@ InterpolationValue FilterInterpolationFunctions::MaybeConvertFilter(
}
std::unique_ptr<InterpolableValue>
-FilterInterpolationFunctions::CreateNoneValue(
+filter_interpolation_functions::CreateNoneValue(
const NonInterpolableValue& untyped_value) {
switch (ToFilterNonInterpolableValue(untyped_value).GetOperationType()) {
case FilterOperation::GRAYSCALE:
@@ -237,14 +237,14 @@ FilterInterpolationFunctions::CreateNoneValue(
}
}
-bool FilterInterpolationFunctions::FiltersAreCompatible(
+bool filter_interpolation_functions::FiltersAreCompatible(
const NonInterpolableValue& a,
const NonInterpolableValue& b) {
return ToFilterNonInterpolableValue(a).GetOperationType() ==
ToFilterNonInterpolableValue(b).GetOperationType();
}
-FilterOperation* FilterInterpolationFunctions::CreateFilter(
+FilterOperation* filter_interpolation_functions::CreateFilter(
const InterpolableValue& interpolable_value,
const NonInterpolableValue& untyped_non_interpolable_value,
const StyleResolverState& state) {
diff --git a/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.h b/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.h
index 44d13ffbc7a..799a8bd49e1 100644
--- a/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.h
@@ -15,7 +15,7 @@ class FilterOperation;
class CSSValue;
class StyleResolverState;
-namespace FilterInterpolationFunctions {
+namespace filter_interpolation_functions {
InterpolationValue MaybeConvertCSSFilter(const CSSValue&);
InterpolationValue MaybeConvertFilter(const FilterOperation&, double zoom);
@@ -26,7 +26,7 @@ FilterOperation* CreateFilter(const InterpolableValue&,
const NonInterpolableValue&,
const StyleResolverState&);
-} // namespace FilterInterpolationFunctions
+} // namespace filter_interpolation_functions
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/image_list_property_functions.h b/chromium/third_party/blink/renderer/core/animation/image_list_property_functions.h
index 3437057085f..39071e66c74 100644
--- a/chromium/third_party/blink/renderer/core/animation/image_list_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/image_list_property_functions.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_IMAGE_LIST_PROPERTY_FUNCTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_IMAGE_LIST_PROPERTY_FUNCTIONS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/image_slice_property_functions.h b/chromium/third_party/blink/renderer/core/animation/image_slice_property_functions.h
index 84c6390308f..ca090999a94 100644
--- a/chromium/third_party/blink/renderer/core/animation/image_slice_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/image_slice_property_functions.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_IMAGE_SLICE_PROPERTY_FUNCTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_IMAGE_SLICE_PROPERTY_FUNCTIONS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/inert_effect.cc b/chromium/third_party/blink/renderer/core/animation/inert_effect.cc
index 7d82f71e8ab..d8d601b8c9c 100644
--- a/chromium/third_party/blink/renderer/core/animation/inert_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/inert_effect.cc
@@ -38,7 +38,8 @@ InertEffect* InertEffect::Create(KeyframeEffectModelBase* effect,
const Timing& timing,
bool paused,
double inherited_time) {
- return new InertEffect(effect, timing, paused, inherited_time);
+ return MakeGarbageCollected<InertEffect>(effect, timing, paused,
+ inherited_time);
}
InertEffect::InertEffect(KeyframeEffectModelBase* model,
diff --git a/chromium/third_party/blink/renderer/core/animation/inert_effect.h b/chromium/third_party/blink/renderer/core/animation/inert_effect.h
index c5d52dcc365..b622198f5aa 100644
--- a/chromium/third_party/blink/renderer/core/animation/inert_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/inert_effect.h
@@ -46,6 +46,12 @@ class CORE_EXPORT InertEffect final : public AnimationEffect {
const Timing&,
bool paused,
double inherited_time);
+
+ InertEffect(KeyframeEffectModelBase*,
+ const Timing&,
+ bool paused,
+ double inherited_time);
+
void Sample(HeapVector<Member<Interpolation>>&) const;
KeyframeEffectModelBase* Model() const { return model_.Get(); }
bool Paused() const { return paused_; }
@@ -62,10 +68,6 @@ class CORE_EXPORT InertEffect final : public AnimationEffect {
double time_to_next_iteration) const override;
private:
- InertEffect(KeyframeEffectModelBase*,
- const Timing&,
- bool paused,
- double inherited_time);
Member<KeyframeEffectModelBase> model_;
bool paused_;
double inherited_time_;
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc b/chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc
index b62eb6c9ddc..3a4339b1024 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc
@@ -53,7 +53,8 @@ KeyframeEffect* KeyframeEffect::Create(Element* target,
const Timing& timing,
Priority priority,
EventDelegate* event_delegate) {
- return new KeyframeEffect(target, model, timing, priority, event_delegate);
+ return MakeGarbageCollected<KeyframeEffect>(target, model, timing, priority,
+ event_delegate);
}
KeyframeEffect* KeyframeEffect::Create(
@@ -76,7 +77,7 @@ KeyframeEffect* KeyframeEffect::Create(
EffectModel::CompositeOperation composite = EffectModel::kCompositeReplace;
if (options.IsKeyframeEffectOptions()) {
composite = EffectModel::StringToCompositeOperation(
- options.GetAsKeyframeEffectOptions().composite())
+ options.GetAsKeyframeEffectOptions()->composite())
.value();
}
@@ -110,8 +111,9 @@ KeyframeEffect* KeyframeEffect::Create(ScriptState* script_state,
ExceptionState& exception_state) {
Timing new_timing = source->SpecifiedTiming();
KeyframeEffectModelBase* model = source->Model()->Clone();
- return new KeyframeEffect(source->target(), model, new_timing,
- source->GetPriority(), source->GetEventDelegate());
+ return MakeGarbageCollected<KeyframeEffect>(source->target(), model,
+ new_timing, source->GetPriority(),
+ source->GetEventDelegate());
}
KeyframeEffect::KeyframeEffect(Element* target,
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe_effect.h b/chromium/third_party/blink/renderer/core/animation/keyframe_effect.h
index d36560a4b65..0c5861f9904 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect.h
@@ -71,6 +71,11 @@ class CORE_EXPORT KeyframeEffect final : public AnimationEffect {
ExceptionState&);
static KeyframeEffect* Create(ScriptState*, KeyframeEffect*, ExceptionState&);
+ KeyframeEffect(Element*,
+ KeyframeEffectModelBase*,
+ const Timing&,
+ Priority,
+ EventDelegate*);
~KeyframeEffect() override;
bool IsKeyframeEffect() const override { return true; }
@@ -128,12 +133,6 @@ class CORE_EXPORT KeyframeEffect final : public AnimationEffect {
void Trace(blink::Visitor*) override;
private:
- KeyframeEffect(Element*,
- KeyframeEffectModelBase*,
- const Timing&,
- Priority,
- EventDelegate*);
-
EffectModel::CompositeOperation CompositeInternal() const;
void ApplyEffects();
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.cc b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.cc
index f590afa86c3..2c4e8d31b26 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.cc
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.cc
@@ -173,11 +173,25 @@ bool KeyframeEffectModelBase::SnapshotCompositableProperties(
parent_style, should_snapshot_property_callback,
should_snapshot_keyframe_callback);
}
+
// Custom properties need to be handled separately, since not all values
// can be animated. Need to resolve the value of each custom property to
// ensure that it can be animated.
+ const PropertyRegistry* property_registry =
+ element.GetDocument().GetPropertyRegistry();
+ if (!property_registry) {
+ // TODO(kevers): Change to DCHECK once CSSVariables2Enabled flag is removed.
+ return updated;
+ }
+
if (auto* inherited_variables = computed_style.InheritedVariables()) {
for (const auto& name : inherited_variables->GetCustomPropertyNames()) {
+ if (property_registry->WasReferenced(name)) {
+ // This variable has been referenced as a property value at least once
+ // during style resolution in the document. Animating this property on
+ // the compositor could introduce misalignment in frame synchronization.
+ continue;
+ }
updated |= SnapshotCompositorKeyFrames(
PropertyHandle(name), element, computed_style, parent_style,
should_snapshot_property_callback, should_snapshot_keyframe_callback);
@@ -185,6 +199,12 @@ bool KeyframeEffectModelBase::SnapshotCompositableProperties(
}
if (auto* non_inherited_variables = computed_style.NonInheritedVariables()) {
for (const auto& name : non_inherited_variables->GetCustomPropertyNames()) {
+ // TODO(kevers): Check if referenced in computed style. References
+ // elsewhere in the document should not prevent compositing.
+ if (property_registry->WasReferenced(name)) {
+ // Avoid potential side-effect of animating on compositor.
+ continue;
+ }
updated |= SnapshotCompositorKeyFrames(
PropertyHandle(name), element, computed_style, parent_style,
should_snapshot_property_callback, should_snapshot_keyframe_callback);
@@ -290,7 +310,7 @@ void KeyframeEffectModelBase::EnsureKeyframeGroups() const {
if (keyframe_groups_)
return;
- keyframe_groups_ = new KeyframeGroupMap;
+ keyframe_groups_ = MakeGarbageCollected<KeyframeGroupMap>();
scoped_refptr<TimingFunction> zero_offset_easing = default_keyframe_easing_;
Vector<double> computed_offsets = GetComputedOffsets(keyframes_);
DCHECK_EQ(computed_offsets.size(), keyframes_.size());
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.h b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.h
index 7b52cc81261..3fe078e32a4 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.h
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.h
@@ -213,8 +213,15 @@ class KeyframeEffectModel final : public KeyframeEffectModelBase {
const KeyframeVector& keyframes,
CompositeOperation composite = kCompositeReplace,
scoped_refptr<TimingFunction> default_keyframe_easing = nullptr) {
- return new KeyframeEffectModel(keyframes, composite,
- std::move(default_keyframe_easing));
+ return MakeGarbageCollected<KeyframeEffectModel<K>>(
+ keyframes, composite, std::move(default_keyframe_easing));
+ }
+
+ KeyframeEffectModel(const KeyframeVector& keyframes,
+ CompositeOperation composite,
+ scoped_refptr<TimingFunction> default_keyframe_easing)
+ : KeyframeEffectModelBase(composite, std::move(default_keyframe_easing)) {
+ keyframes_.AppendVector(keyframes);
}
KeyframeEffectModelBase* Clone() override {
@@ -227,13 +234,6 @@ class KeyframeEffectModel final : public KeyframeEffectModelBase {
}
private:
- KeyframeEffectModel(const KeyframeVector& keyframes,
- CompositeOperation composite,
- scoped_refptr<TimingFunction> default_keyframe_easing)
- : KeyframeEffectModelBase(composite, std::move(default_keyframe_easing)) {
- keyframes_.AppendVector(keyframes);
- }
-
bool IsStringKeyframeEffectModel() const override { return false; }
bool IsTransitionKeyframeEffectModel() const override { return false; }
};
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc
index 5feb9537f80..324be2c4071 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc
@@ -678,11 +678,11 @@ TEST_F(AnimationKeyframeEffectModel,
TEST_F(AnimationKeyframeEffectModel, CompositorSnapshotUpdateCustomProperty) {
ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
DummyExceptionStateForTesting exception_state;
- PropertyDescriptor property_descriptor;
- property_descriptor.setName("--foo");
- property_descriptor.setSyntax("<number>");
- property_descriptor.setInitialValue("0");
- property_descriptor.setInherits(false);
+ PropertyDescriptor* property_descriptor = PropertyDescriptor::Create();
+ property_descriptor->setName("--foo");
+ property_descriptor->setSyntax("<number>");
+ property_descriptor->setInitialValue("0");
+ property_descriptor->setInherits(false);
PropertyRegistration::registerProperty(&GetDocument(), property_descriptor,
exception_state);
EXPECT_FALSE(exception_state.HadException());
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_test.cc b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_test.cc
index 6b92b69c4e7..2c342de5dbe 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect_test.cc
@@ -43,10 +43,11 @@ class KeyframeEffectTest : public PageTestBase {
class AnimationKeyframeEffectV8Test : public KeyframeEffectTest {
protected:
- static KeyframeEffect* CreateAnimation(ScriptState* script_state,
- Element* element,
- const ScriptValue& keyframe_object,
- double timing_input) {
+ static KeyframeEffect* CreateAnimationFromTiming(
+ ScriptState* script_state,
+ Element* element,
+ const ScriptValue& keyframe_object,
+ double timing_input) {
NonThrowableExceptionState exception_state;
return KeyframeEffect::Create(
script_state, element, keyframe_object,
@@ -54,16 +55,16 @@ class AnimationKeyframeEffectV8Test : public KeyframeEffectTest {
timing_input),
exception_state);
}
- static KeyframeEffect* CreateAnimation(
+ static KeyframeEffect* CreateAnimationFromOption(
ScriptState* script_state,
Element* element,
const ScriptValue& keyframe_object,
- const KeyframeEffectOptions& timing_input) {
+ const KeyframeEffectOptions* timing_input) {
NonThrowableExceptionState exception_state;
return KeyframeEffect::Create(
script_state, element, keyframe_object,
UnrestrictedDoubleOrKeyframeEffectOptions::FromKeyframeEffectOptions(
- timing_input),
+ const_cast<KeyframeEffectOptions*>(timing_input)),
exception_state);
}
static KeyframeEffect* CreateAnimation(ScriptState* script_state,
@@ -97,7 +98,7 @@ TEST_F(AnimationKeyframeEffectV8Test, CanCreateAnAnimation) {
ToV8(blink_keyframes, scope.GetContext()->Global(), scope.GetIsolate()));
KeyframeEffect* animation =
- CreateAnimation(script_state, element.Get(), js_keyframes, 0);
+ CreateAnimationFromTiming(script_state, element.Get(), js_keyframes, 0);
Element* target = animation->target();
EXPECT_EQ(*element.Get(), *target);
@@ -132,13 +133,14 @@ TEST_F(AnimationKeyframeEffectV8Test, SetAndRetrieveEffectComposite) {
v8::Local<v8::Object> effect_options = v8::Object::New(scope.GetIsolate());
SetV8ObjectPropertyAsString(scope.GetIsolate(), effect_options, "composite",
"add");
- KeyframeEffectOptions effect_options_dictionary;
+ KeyframeEffectOptions* effect_options_dictionary =
+ KeyframeEffectOptions::Create();
V8KeyframeEffectOptions::ToImpl(scope.GetIsolate(), effect_options,
effect_options_dictionary, exception_state);
EXPECT_FALSE(exception_state.HadException());
ScriptValue js_keyframes = ScriptValue::CreateNull(script_state);
- KeyframeEffect* effect = CreateAnimation(
+ KeyframeEffect* effect = CreateAnimationFromOption(
script_state, element.Get(), js_keyframes, effect_options_dictionary);
EXPECT_EQ("add", effect->composite());
@@ -159,7 +161,8 @@ TEST_F(AnimationKeyframeEffectV8Test, KeyframeCompositeOverridesEffect) {
v8::Local<v8::Object> effect_options = v8::Object::New(scope.GetIsolate());
SetV8ObjectPropertyAsString(scope.GetIsolate(), effect_options, "composite",
"add");
- KeyframeEffectOptions effect_options_dictionary;
+ KeyframeEffectOptions* effect_options_dictionary =
+ KeyframeEffectOptions::Create();
V8KeyframeEffectOptions::ToImpl(scope.GetIsolate(), effect_options,
effect_options_dictionary, exception_state);
EXPECT_FALSE(exception_state.HadException());
@@ -175,7 +178,7 @@ TEST_F(AnimationKeyframeEffectV8Test, KeyframeCompositeOverridesEffect) {
script_state,
ToV8(blink_keyframes, scope.GetContext()->Global(), scope.GetIsolate()));
- KeyframeEffect* effect = CreateAnimation(
+ KeyframeEffect* effect = CreateAnimationFromOption(
script_state, element.Get(), js_keyframes, effect_options_dictionary);
EXPECT_EQ("add", effect->composite());
@@ -193,8 +196,8 @@ TEST_F(AnimationKeyframeEffectV8Test, CanSetDuration) {
ScriptValue js_keyframes = ScriptValue::CreateNull(script_state);
double duration = 2000;
- KeyframeEffect* animation =
- CreateAnimation(script_state, element.Get(), js_keyframes, duration);
+ KeyframeEffect* animation = CreateAnimationFromTiming(
+ script_state, element.Get(), js_keyframes, duration);
EXPECT_EQ(duration / 1000,
animation->SpecifiedTiming().iteration_duration->InSecondsF());
@@ -228,24 +231,24 @@ TEST_F(AnimationKeyframeEffectV8Test, SpecifiedGetters) {
"reverse");
SetV8ObjectPropertyAsString(scope.GetIsolate(), timing_input, "easing",
"ease-in-out");
- KeyframeEffectOptions timing_input_dictionary;
+ KeyframeEffectOptions* timing_input_dictionary =
+ KeyframeEffectOptions::Create();
DummyExceptionStateForTesting exception_state;
V8KeyframeEffectOptions::ToImpl(scope.GetIsolate(), timing_input,
timing_input_dictionary, exception_state);
EXPECT_FALSE(exception_state.HadException());
- KeyframeEffect* animation = CreateAnimation(
+ KeyframeEffect* animation = CreateAnimationFromOption(
script_state, element.Get(), js_keyframes, timing_input_dictionary);
- EffectTiming timing;
- animation->getTiming(timing);
- EXPECT_EQ(2, timing.delay());
- EXPECT_EQ(0.5, timing.endDelay());
- EXPECT_EQ("backwards", timing.fill());
- EXPECT_EQ(2, timing.iterationStart());
- EXPECT_EQ(10, timing.iterations());
- EXPECT_EQ("reverse", timing.direction());
- EXPECT_EQ("ease-in-out", timing.easing());
+ EffectTiming* timing = animation->getTiming();
+ EXPECT_EQ(2, timing->delay());
+ EXPECT_EQ(0.5, timing->endDelay());
+ EXPECT_EQ("backwards", timing->fill());
+ EXPECT_EQ(2, timing->iterationStart());
+ EXPECT_EQ(10, timing->iterations());
+ EXPECT_EQ("reverse", timing->direction());
+ EXPECT_EQ("ease-in-out", timing->easing());
}
TEST_F(AnimationKeyframeEffectV8Test, SpecifiedDurationGetter) {
@@ -257,7 +260,8 @@ TEST_F(AnimationKeyframeEffectV8Test, SpecifiedDurationGetter) {
v8::Object::New(scope.GetIsolate());
SetV8ObjectPropertyAsNumber(scope.GetIsolate(), timing_input_with_duration,
"duration", 2.5);
- KeyframeEffectOptions timing_input_dictionary_with_duration;
+ KeyframeEffectOptions* timing_input_dictionary_with_duration =
+ KeyframeEffectOptions::Create();
DummyExceptionStateForTesting exception_state;
V8KeyframeEffectOptions::ToImpl(
scope.GetIsolate(), timing_input_with_duration,
@@ -265,31 +269,30 @@ TEST_F(AnimationKeyframeEffectV8Test, SpecifiedDurationGetter) {
EXPECT_FALSE(exception_state.HadException());
KeyframeEffect* animation_with_duration =
- CreateAnimation(script_state, element.Get(), js_keyframes,
- timing_input_dictionary_with_duration);
+ CreateAnimationFromOption(script_state, element.Get(), js_keyframes,
+ timing_input_dictionary_with_duration);
- EffectTiming specified_with_duration;
- animation_with_duration->getTiming(specified_with_duration);
- UnrestrictedDoubleOrString duration = specified_with_duration.duration();
+ EffectTiming* specified_with_duration = animation_with_duration->getTiming();
+ UnrestrictedDoubleOrString duration = specified_with_duration->duration();
EXPECT_TRUE(duration.IsUnrestrictedDouble());
EXPECT_EQ(2.5, duration.GetAsUnrestrictedDouble());
EXPECT_FALSE(duration.IsString());
v8::Local<v8::Object> timing_input_no_duration =
v8::Object::New(scope.GetIsolate());
- KeyframeEffectOptions timing_input_dictionary_no_duration;
+ KeyframeEffectOptions* timing_input_dictionary_no_duration =
+ KeyframeEffectOptions::Create();
V8KeyframeEffectOptions::ToImpl(scope.GetIsolate(), timing_input_no_duration,
timing_input_dictionary_no_duration,
exception_state);
EXPECT_FALSE(exception_state.HadException());
KeyframeEffect* animation_no_duration =
- CreateAnimation(script_state, element.Get(), js_keyframes,
- timing_input_dictionary_no_duration);
+ CreateAnimationFromOption(script_state, element.Get(), js_keyframes,
+ timing_input_dictionary_no_duration);
- EffectTiming specified_no_duration;
- animation_no_duration->getTiming(specified_no_duration);
- UnrestrictedDoubleOrString duration2 = specified_no_duration.duration();
+ EffectTiming* specified_no_duration = animation_no_duration->getTiming();
+ UnrestrictedDoubleOrString duration2 = specified_no_duration->duration();
EXPECT_FALSE(duration2.IsUnrestrictedDouble());
EXPECT_TRUE(duration2.IsString());
EXPECT_EQ("auto", duration2.GetAsString());
@@ -301,7 +304,8 @@ TEST_F(AnimationKeyframeEffectV8Test, SetKeyframesAdditiveCompositeOperation) {
ScriptState* script_state = scope.GetScriptState();
ScriptValue js_keyframes = ScriptValue::CreateNull(script_state);
v8::Local<v8::Object> timing_input = v8::Object::New(scope.GetIsolate());
- KeyframeEffectOptions timing_input_dictionary;
+ KeyframeEffectOptions* timing_input_dictionary =
+ KeyframeEffectOptions::Create();
DummyExceptionStateForTesting exception_state;
V8KeyframeEffectOptions::ToImpl(scope.GetIsolate(), timing_input,
timing_input_dictionary, exception_state);
@@ -309,8 +313,8 @@ TEST_F(AnimationKeyframeEffectV8Test, SetKeyframesAdditiveCompositeOperation) {
// Since there are no CSS-targeting keyframes, we can create a KeyframeEffect
// with composite = 'add'.
- timing_input_dictionary.setComposite("add");
- KeyframeEffect* effect = CreateAnimation(
+ timing_input_dictionary->setComposite("add");
+ KeyframeEffect* effect = CreateAnimationFromOption(
script_state, element.Get(), js_keyframes, timing_input_dictionary);
EXPECT_EQ(effect->Model()->Composite(), EffectModel::kCompositeAdd);
diff --git a/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.cc b/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.cc
index 0f53dc87d90..b1cd14d943c 100644
--- a/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.cc
+++ b/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
-#include "third_party/blink/renderer/platform/calculation_value.h"
+#include "third_party/blink/renderer/platform/geometry/calculation_value.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.h b/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.h
index 1a87760a5b5..a75221a8231 100644
--- a/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.h
@@ -8,7 +8,7 @@
#include <memory>
#include "third_party/blink/renderer/core/animation/interpolation_value.h"
#include "third_party/blink/renderer/core/animation/pairwise_interpolation_value.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/length_list_property_functions.h b/chromium/third_party/blink/renderer/core/animation/length_list_property_functions.h
index bf5f15d9902..95b962c45f5 100644
--- a/chromium/third_party/blink/renderer/core/animation/length_list_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/length_list_property_functions.h
@@ -5,8 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_LENGTH_LIST_PROPERTY_FUNCTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_LENGTH_LIST_PROPERTY_FUNCTIONS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/length_property_functions.h b/chromium/third_party/blink/renderer/core/animation/length_property_functions.h
index 9138744df11..43e2f83d4b4 100644
--- a/chromium/third_party/blink/renderer/core/animation/length_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/length_property_functions.h
@@ -5,9 +5,9 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_LENGTH_PROPERTY_FUNCTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_LENGTH_PROPERTY_FUNCTIONS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/number_property_functions.h b/chromium/third_party/blink/renderer/core/animation/number_property_functions.h
index c4457954ff2..4b32e30745e 100644
--- a/chromium/third_party/blink/renderer/core/animation/number_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/number_property_functions.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_NUMBER_PROPERTY_FUNCTIONS_H_
#include "base/optional.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.cc b/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.cc
index 1b8bacee719..1a7007837ba 100644
--- a/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.cc
+++ b/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.cc
@@ -203,7 +203,7 @@ std::unique_ptr<SVGPathByteStream> PathInterpolationFunctions::AppliedValue(
*ToInterpolableList(interpolable_value).Get(kPathArgsIndex)),
ToSVGPathNonInterpolableValue(non_interpolable_value)->PathSegTypes());
SVGPathByteStreamBuilder builder(*path_byte_stream);
- SVGPathParser::ParsePath(source, builder);
+ svg_path_parser::ParsePath(source, builder);
return path_byte_stream;
}
diff --git a/chromium/third_party/blink/renderer/core/animation/property_handle.h b/chromium/third_party/blink/renderer/core/animation/property_handle.h
index 98b57045edb..eeca4b7bf7b 100644
--- a/chromium/third_party/blink/renderer/core/animation/property_handle.h
+++ b/chromium/third_party/blink/renderer/core/animation/property_handle.h
@@ -6,8 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_PROPERTY_HANDLE_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/qualified_name.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -71,6 +72,13 @@ class CORE_EXPORT PropertyHandle {
return *svg_attribute_;
}
+ CSSPropertyName GetCSSPropertyName() const {
+ if (handle_type_ == kHandleCSSCustomProperty)
+ return CSSPropertyName(property_name_);
+ DCHECK(IsCSSProperty() || IsPresentationAttribute());
+ return CSSPropertyName(css_property_->PropertyID());
+ }
+
private:
enum HandleType {
kHandleEmptyValueForHashTraits,
diff --git a/chromium/third_party/blink/renderer/core/animation/property_handle_test.cc b/chromium/third_party/blink/renderer/core/animation/property_handle_test.cc
index f30eb0865bb..7d2187eaae7 100644
--- a/chromium/third_party/blink/renderer/core/animation/property_handle_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/property_handle_test.cc
@@ -9,8 +9,8 @@
namespace blink {
-using SVGNames::amplitudeAttr;
-using SVGNames::exponentAttr;
+using svg_names::kAmplitudeAttr;
+using svg_names::kExponentAttr;
class PropertyHandleTest : public testing::Test {};
@@ -31,9 +31,9 @@ TEST_F(PropertyHandleTest, Equality) {
EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()) !=
PropertyHandle(name_a));
EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()) ==
- PropertyHandle(amplitudeAttr));
+ PropertyHandle(kAmplitudeAttr));
EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()) !=
- PropertyHandle(amplitudeAttr));
+ PropertyHandle(kAmplitudeAttr));
EXPECT_FALSE(PropertyHandle(name_a) ==
PropertyHandle(GetCSSPropertyOpacity()));
@@ -47,19 +47,20 @@ TEST_F(PropertyHandleTest, Equality) {
EXPECT_FALSE(PropertyHandle(name_a) != PropertyHandle(name_a));
EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(name_b));
EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(name_b));
- EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(amplitudeAttr));
- EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(amplitudeAttr));
+ EXPECT_FALSE(PropertyHandle(name_a) == PropertyHandle(kAmplitudeAttr));
+ EXPECT_TRUE(PropertyHandle(name_a) != PropertyHandle(kAmplitudeAttr));
- EXPECT_FALSE(PropertyHandle(amplitudeAttr) ==
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) ==
PropertyHandle(GetCSSPropertyOpacity()));
- EXPECT_TRUE(PropertyHandle(amplitudeAttr) !=
+ EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) !=
PropertyHandle(GetCSSPropertyOpacity()));
- EXPECT_FALSE(PropertyHandle(amplitudeAttr) == PropertyHandle(name_a));
- EXPECT_TRUE(PropertyHandle(amplitudeAttr) != PropertyHandle(name_a));
- EXPECT_TRUE(PropertyHandle(amplitudeAttr) == PropertyHandle(amplitudeAttr));
- EXPECT_FALSE(PropertyHandle(amplitudeAttr) != PropertyHandle(amplitudeAttr));
- EXPECT_FALSE(PropertyHandle(amplitudeAttr) == PropertyHandle(exponentAttr));
- EXPECT_TRUE(PropertyHandle(amplitudeAttr) != PropertyHandle(exponentAttr));
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(name_a));
+ EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) != PropertyHandle(name_a));
+ EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(kAmplitudeAttr));
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) !=
+ PropertyHandle(kAmplitudeAttr));
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr) == PropertyHandle(kExponentAttr));
+ EXPECT_TRUE(PropertyHandle(kAmplitudeAttr) != PropertyHandle(kExponentAttr));
}
TEST_F(PropertyHandleTest, Hash) {
@@ -73,7 +74,7 @@ TEST_F(PropertyHandleTest, Hash) {
EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).GetHash() ==
PropertyHandle(GetCSSPropertyTransform()).GetHash());
EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).GetHash() ==
- PropertyHandle(amplitudeAttr).GetHash());
+ PropertyHandle(kAmplitudeAttr).GetHash());
EXPECT_FALSE(PropertyHandle(name_a).GetHash() ==
PropertyHandle(GetCSSPropertyOpacity()).GetHash());
@@ -82,16 +83,16 @@ TEST_F(PropertyHandleTest, Hash) {
EXPECT_FALSE(PropertyHandle(name_a).GetHash() ==
PropertyHandle(name_b).GetHash());
EXPECT_FALSE(PropertyHandle(name_a).GetHash() ==
- PropertyHandle(exponentAttr).GetHash());
+ PropertyHandle(kExponentAttr).GetHash());
- EXPECT_FALSE(PropertyHandle(amplitudeAttr).GetHash() ==
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).GetHash() ==
PropertyHandle(GetCSSPropertyOpacity()).GetHash());
- EXPECT_FALSE(PropertyHandle(amplitudeAttr).GetHash() ==
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).GetHash() ==
PropertyHandle(name_a).GetHash());
- EXPECT_TRUE(PropertyHandle(amplitudeAttr).GetHash() ==
- PropertyHandle(amplitudeAttr).GetHash());
- EXPECT_FALSE(PropertyHandle(amplitudeAttr).GetHash() ==
- PropertyHandle(exponentAttr).GetHash());
+ EXPECT_TRUE(PropertyHandle(kAmplitudeAttr).GetHash() ==
+ PropertyHandle(kAmplitudeAttr).GetHash());
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).GetHash() ==
+ PropertyHandle(kExponentAttr).GetHash());
}
TEST_F(PropertyHandleTest, Accessors) {
@@ -99,23 +100,30 @@ TEST_F(PropertyHandleTest, Accessors) {
EXPECT_TRUE(PropertyHandle(GetCSSPropertyOpacity()).IsCSSProperty());
EXPECT_TRUE(PropertyHandle(name).IsCSSProperty());
- EXPECT_FALSE(PropertyHandle(amplitudeAttr).IsCSSProperty());
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).IsCSSProperty());
EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).IsSVGAttribute());
EXPECT_FALSE(PropertyHandle(name).IsSVGAttribute());
- EXPECT_TRUE(PropertyHandle(amplitudeAttr).IsSVGAttribute());
+ EXPECT_TRUE(PropertyHandle(kAmplitudeAttr).IsSVGAttribute());
EXPECT_FALSE(PropertyHandle(GetCSSPropertyOpacity()).IsCSSCustomProperty());
EXPECT_TRUE(PropertyHandle(name).IsCSSCustomProperty());
- EXPECT_FALSE(PropertyHandle(amplitudeAttr).IsCSSCustomProperty());
+ EXPECT_FALSE(PropertyHandle(kAmplitudeAttr).IsCSSCustomProperty());
EXPECT_EQ(
- PropertyHandle(GetCSSPropertyOpacity()).GetCSSProperty().PropertyID(),
- CSSPropertyOpacity);
- EXPECT_EQ(PropertyHandle(name).GetCSSProperty().PropertyID(),
- CSSPropertyVariable);
- EXPECT_EQ(PropertyHandle(name).CustomPropertyName(), name);
- EXPECT_EQ(PropertyHandle(amplitudeAttr).SvgAttribute(), amplitudeAttr);
+ CSSPropertyOpacity,
+ PropertyHandle(GetCSSPropertyOpacity()).GetCSSProperty().PropertyID());
+ EXPECT_EQ(CSSPropertyVariable,
+ PropertyHandle(name).GetCSSProperty().PropertyID());
+ EXPECT_EQ(name, PropertyHandle(name).CustomPropertyName());
+ EXPECT_EQ(kAmplitudeAttr, PropertyHandle(kAmplitudeAttr).SvgAttribute());
+
+ EXPECT_EQ(name, PropertyHandle(name).GetCSSPropertyName().ToAtomicString());
+ EXPECT_EQ(CSSPropertyOpacity,
+ PropertyHandle(GetCSSPropertyOpacity()).GetCSSPropertyName().Id());
+ EXPECT_EQ(
+ CSSPropertyColor,
+ PropertyHandle(GetCSSPropertyColor(), true).GetCSSPropertyName().Id());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/sampled_effect.h b/chromium/third_party/blink/renderer/core/animation/sampled_effect.h
index db153c4c39a..057d96d461c 100644
--- a/chromium/third_party/blink/renderer/core/animation/sampled_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/sampled_effect.h
@@ -20,9 +20,11 @@ class SampledEffect : public GarbageCollectedFinalized<SampledEffect> {
public:
static SampledEffect* Create(KeyframeEffect* effect,
unsigned sequence_number) {
- return new SampledEffect(effect, sequence_number);
+ return MakeGarbageCollected<SampledEffect>(effect, sequence_number);
}
+ SampledEffect(KeyframeEffect*, unsigned sequence_number);
+
void Clear();
const HeapVector<Member<Interpolation>>& Interpolations() const {
@@ -42,8 +44,6 @@ class SampledEffect : public GarbageCollectedFinalized<SampledEffect> {
void Trace(blink::Visitor*);
private:
- SampledEffect(KeyframeEffect*, unsigned sequence_number);
-
WeakMember<KeyframeEffect> effect_;
HeapVector<Member<Interpolation>> interpolations_;
const unsigned sequence_number_;
diff --git a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc
index 04e2128fa44..394c242f7f2 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -28,7 +28,6 @@ ActiveScrollTimelineSet& GetActiveScrollTimelineSet() {
bool StringToScrollDirection(String scroll_direction,
ScrollTimeline::ScrollDirection& result) {
- // TODO(smcgruer): Support 'auto' value.
if (scroll_direction == "block") {
result = ScrollTimeline::Block;
return true;
@@ -52,7 +51,7 @@ bool StringToScrollOffset(String scroll_offset, CSSPrimitiveValue** result) {
CSSTokenizer tokenizer(scroll_offset);
const auto tokens = tokenizer.TokenizeToEOF();
CSSParserTokenRange range(tokens);
- CSSValue* value = CSSParsingUtils::ConsumeScrollOffset(range);
+ CSSValue* value = css_parsing_utils::ConsumeScrollOffset(range);
if (!value)
return false;
@@ -60,45 +59,56 @@ bool StringToScrollOffset(String scroll_offset, CSSPrimitiveValue** result) {
*result = value->IsIdentifierValue() ? nullptr : ToCSSPrimitiveValue(value);
return true;
}
+
+// Note that the resolution process may trigger document lifecycle to clean
+// style and layout.
+Node* ResolveScrollSource(Element* scroll_source) {
+ // When in quirks mode we need the style to be clean, so we don't use
+ // |ScrollingElementNoLayout|.
+ if (scroll_source == scroll_source->GetDocument().scrollingElement())
+ return &scroll_source->GetDocument();
+ return scroll_source;
+}
} // namespace
ScrollTimeline* ScrollTimeline::Create(Document& document,
- ScrollTimelineOptions options,
+ ScrollTimelineOptions* options,
ExceptionState& exception_state) {
- Element* scroll_source = options.scrollSource() ? options.scrollSource()
- : document.scrollingElement();
+ Element* scroll_source = options->scrollSource()
+ ? options->scrollSource()
+ : document.scrollingElement();
ScrollDirection orientation;
- if (!StringToScrollDirection(options.orientation(), orientation)) {
+ if (!StringToScrollDirection(options->orientation(), orientation)) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
"Invalid orientation");
return nullptr;
}
CSSPrimitiveValue* start_scroll_offset = nullptr;
- if (!StringToScrollOffset(options.startScrollOffset(),
+ if (!StringToScrollOffset(options->startScrollOffset(),
&start_scroll_offset)) {
exception_state.ThrowTypeError("Invalid startScrollOffset");
return nullptr;
}
CSSPrimitiveValue* end_scroll_offset = nullptr;
- if (!StringToScrollOffset(options.endScrollOffset(), &end_scroll_offset)) {
+ if (!StringToScrollOffset(options->endScrollOffset(), &end_scroll_offset)) {
exception_state.ThrowTypeError("Invalid endScrollOffset");
return nullptr;
}
// TODO(smcgruer): Support 'auto' value.
- if (options.timeRange().IsScrollTimelineAutoKeyword()) {
+ if (options->timeRange().IsScrollTimelineAutoKeyword()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"'auto' value for timeRange not yet supported");
return nullptr;
}
- return new ScrollTimeline(scroll_source, orientation, start_scroll_offset,
- end_scroll_offset,
- options.timeRange().GetAsDouble());
+ return MakeGarbageCollected<ScrollTimeline>(
+ scroll_source, orientation, start_scroll_offset, end_scroll_offset,
+ options->timeRange().GetAsDouble());
}
ScrollTimeline::ScrollTimeline(Element* scroll_source,
@@ -107,6 +117,7 @@ ScrollTimeline::ScrollTimeline(Element* scroll_source,
CSSPrimitiveValue* end_scroll_offset,
double time_range)
: scroll_source_(scroll_source),
+ resolved_scroll_source_(ResolveScrollSource(scroll_source_)),
orientation_(orientation),
start_scroll_offset_(start_scroll_offset),
end_scroll_offset_(end_scroll_offset),
@@ -115,59 +126,20 @@ ScrollTimeline::ScrollTimeline(Element* scroll_source,
}
double ScrollTimeline::currentTime(bool& is_null) {
+ is_null = true;
// 1. If scrollSource does not currently have a CSS layout box, or if its
// layout box is not a scroll container, return an unresolved time value.
- LayoutBox* layout_box = ResolvedScrollSource()->GetLayoutBox();
+ LayoutBox* layout_box = resolved_scroll_source_->GetLayoutBox();
if (!layout_box || !layout_box->HasOverflowClip()) {
- is_null = false;
return std::numeric_limits<double>::quiet_NaN();
}
// 2. Otherwise, let current scroll offset be the current scroll offset of
// scrollSource in the direction specified by orientation.
- // Depending on the writing-mode and direction, the scroll origin shifts and
- // the scroll offset may be negative. The easiest way to deal with this is to
- // use only the magnitude of the scroll offset, and compare it to (max-offset
- // - min_offset).
- PaintLayerScrollableArea* scrollable_area = layout_box->GetScrollableArea();
- // Using the absolute value of the scroll offset only makes sense if either
- // the max or min scroll offset for a given axis is 0. This should be
- // guaranteed by the scroll origin code, but these DCHECKs ensure that.
- DCHECK(scrollable_area->MaximumScrollOffset().Height() == 0 ||
- scrollable_area->MinimumScrollOffset().Height() == 0);
- DCHECK(scrollable_area->MaximumScrollOffset().Width() == 0 ||
- scrollable_area->MinimumScrollOffset().Width() == 0);
- ScrollOffset scroll_offset = scrollable_area->GetScrollOffset();
- ScrollOffset scroll_dimensions = scrollable_area->MaximumScrollOffset() -
- scrollable_area->MinimumScrollOffset();
-
double current_offset;
double max_offset;
- bool is_horizontal = layout_box->IsHorizontalWritingMode();
- if (orientation_ == Block) {
- current_offset =
- is_horizontal ? scroll_offset.Height() : scroll_offset.Width();
- max_offset =
- is_horizontal ? scroll_dimensions.Height() : scroll_dimensions.Width();
- } else if (orientation_ == Inline) {
- current_offset =
- is_horizontal ? scroll_offset.Width() : scroll_offset.Height();
- max_offset =
- is_horizontal ? scroll_dimensions.Width() : scroll_dimensions.Height();
- } else if (orientation_ == Horizontal) {
- current_offset = scroll_offset.Width();
- max_offset = scroll_dimensions.Width();
- } else {
- DCHECK(orientation_ == Vertical);
- current_offset = scroll_offset.Height();
- max_offset = scroll_dimensions.Height();
- }
- // When using a rtl direction, current_offset grows correctly from 0 to
- // max_offset, but is negative. Since our offsets are all just deltas along
- // the orientation direction, we can just take the absolute current_offset and
- // use that everywhere.
- current_offset = std::abs(current_offset);
+ GetCurrentAndMaxOffset(layout_box, current_offset, max_offset);
double resolved_start_scroll_offset = 0;
double resolved_end_scroll_offset = max_offset;
@@ -211,30 +183,6 @@ double ScrollTimeline::currentTime(bool& is_null) {
time_range_;
}
-void ScrollTimeline::ResolveScrollStartAndEnd(
- const LayoutBox* layout_box,
- double max_offset,
- double& resolved_start_scroll_offset,
- double& resolved_end_scroll_offset) {
- const ComputedStyle& computed_style = layout_box->StyleRef();
- Document& document = layout_box->GetDocument();
- const ComputedStyle* root_style =
- document.documentElement()
- ? document.documentElement()->GetComputedStyle()
- : document.GetComputedStyle();
- CSSToLengthConversionData conversion_data = CSSToLengthConversionData(
- &computed_style, root_style, document.GetLayoutView(),
- computed_style.EffectiveZoom());
- if (start_scroll_offset_) {
- resolved_start_scroll_offset = FloatValueForLength(
- start_scroll_offset_->ConvertToLength(conversion_data), max_offset);
- }
- if (end_scroll_offset_) {
- resolved_end_scroll_offset = FloatValueForLength(
- end_scroll_offset_->ConvertToLength(conversion_data), max_offset);
- }
-}
-
Element* ScrollTimeline::scrollSource() {
return scroll_source_.Get();
}
@@ -267,20 +215,86 @@ void ScrollTimeline::timeRange(DoubleOrScrollTimelineAutoKeyword& result) {
result.SetDouble(time_range_);
}
-Node* ScrollTimeline::ResolvedScrollSource() const {
- // When in quirks mode we need the style to be clean, so we don't use
- // |ScrollingElementNoLayout|.
- if (scroll_source_ == scroll_source_->GetDocument().scrollingElement())
- return &scroll_source_->GetDocument();
- return scroll_source_;
+
+void ScrollTimeline::GetCurrentAndMaxOffset(const LayoutBox* layout_box,
+ double& current_offset,
+ double& max_offset) const {
+ DCHECK(layout_box);
+
+ // Depending on the writing-mode and direction, the scroll origin shifts and
+ // the scroll offset may be negative. The easiest way to deal with this is to
+ // use only the magnitude of the scroll offset, and compare it to (max_offset
+ // - min_offset).
+ PaintLayerScrollableArea* scrollable_area = layout_box->GetScrollableArea();
+ if (!scrollable_area)
+ return;
+ // Using the absolute value of the scroll offset only makes sense if either
+ // the max or min scroll offset for a given axis is 0. This should be
+ // guaranteed by the scroll origin code, but these DCHECKs ensure that.
+ DCHECK(scrollable_area->MaximumScrollOffset().Height() == 0 ||
+ scrollable_area->MinimumScrollOffset().Height() == 0);
+ DCHECK(scrollable_area->MaximumScrollOffset().Width() == 0 ||
+ scrollable_area->MinimumScrollOffset().Width() == 0);
+ ScrollOffset scroll_offset = scrollable_area->GetScrollOffset();
+ ScrollOffset scroll_dimensions = scrollable_area->MaximumScrollOffset() -
+ scrollable_area->MinimumScrollOffset();
+
+ bool is_horizontal = layout_box->IsHorizontalWritingMode();
+ if (orientation_ == Block) {
+ current_offset =
+ is_horizontal ? scroll_offset.Height() : scroll_offset.Width();
+ max_offset =
+ is_horizontal ? scroll_dimensions.Height() : scroll_dimensions.Width();
+ } else if (orientation_ == Inline) {
+ current_offset =
+ is_horizontal ? scroll_offset.Width() : scroll_offset.Height();
+ max_offset =
+ is_horizontal ? scroll_dimensions.Width() : scroll_dimensions.Height();
+ } else if (orientation_ == Horizontal) {
+ current_offset = scroll_offset.Width();
+ max_offset = scroll_dimensions.Width();
+ } else {
+ DCHECK(orientation_ == Vertical);
+ current_offset = scroll_offset.Height();
+ max_offset = scroll_dimensions.Height();
+ }
+ // When using a rtl direction, current_offset grows correctly from 0 to
+ // max_offset, but is negative. Since our offsets are all just deltas along
+ // the orientation direction, we can just take the absolute current_offset and
+ // use that everywhere.
+ current_offset = std::abs(current_offset);
+}
+
+void ScrollTimeline::ResolveScrollStartAndEnd(
+ const LayoutBox* layout_box,
+ double max_offset,
+ double& resolved_start_scroll_offset,
+ double& resolved_end_scroll_offset) const {
+ DCHECK(layout_box);
+ const ComputedStyle& computed_style = layout_box->StyleRef();
+ Document& document = layout_box->GetDocument();
+ const ComputedStyle* root_style =
+ document.documentElement()
+ ? document.documentElement()->GetComputedStyle()
+ : document.GetComputedStyle();
+ CSSToLengthConversionData conversion_data = CSSToLengthConversionData(
+ &computed_style, root_style, document.GetLayoutView(),
+ computed_style.EffectiveZoom());
+ if (start_scroll_offset_) {
+ resolved_start_scroll_offset = FloatValueForLength(
+ start_scroll_offset_->ConvertToLength(conversion_data), max_offset);
+ }
+ if (end_scroll_offset_) {
+ resolved_end_scroll_offset = FloatValueForLength(
+ end_scroll_offset_->ConvertToLength(conversion_data), max_offset);
+ }
}
void ScrollTimeline::AttachAnimation() {
- Node* resolved_scroll_source = ResolvedScrollSource();
- GetActiveScrollTimelineSet().insert(resolved_scroll_source);
- if (resolved_scroll_source->IsElementNode())
- ToElement(resolved_scroll_source)->SetNeedsCompositingUpdate();
- resolved_scroll_source->GetDocument()
+ GetActiveScrollTimelineSet().insert(resolved_scroll_source_);
+ if (resolved_scroll_source_->IsElementNode())
+ ToElement(resolved_scroll_source_)->SetNeedsCompositingUpdate();
+ resolved_scroll_source_->GetDocument()
.GetLayoutView()
->Compositor()
->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
@@ -292,11 +306,10 @@ void ScrollTimeline::AttachAnimation() {
}
void ScrollTimeline::DetachAnimation() {
- Node* resolved_scroll_source = ResolvedScrollSource();
- GetActiveScrollTimelineSet().erase(resolved_scroll_source);
- if (resolved_scroll_source->IsElementNode())
- ToElement(resolved_scroll_source)->SetNeedsCompositingUpdate();
- auto* layout_view = resolved_scroll_source->GetDocument().GetLayoutView();
+ GetActiveScrollTimelineSet().erase(resolved_scroll_source_);
+ if (resolved_scroll_source_->IsElementNode())
+ ToElement(resolved_scroll_source_)->SetNeedsCompositingUpdate();
+ auto* layout_view = resolved_scroll_source_->GetDocument().GetLayoutView();
if (layout_view && layout_view->Compositor()) {
layout_view->Compositor()->SetNeedsCompositingUpdate(
kCompositingUpdateRebuildTree);
@@ -311,6 +324,7 @@ void ScrollTimeline::DetachAnimation() {
void ScrollTimeline::Trace(blink::Visitor* visitor) {
visitor->Trace(scroll_source_);
+ visitor->Trace(resolved_scroll_source_);
visitor->Trace(start_scroll_offset_);
visitor->Trace(end_scroll_offset_);
AnimationTimeline::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.h b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.h
index 173af1af703..ee43c4539c9 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.h
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.h
@@ -36,9 +36,15 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
};
static ScrollTimeline* Create(Document&,
- ScrollTimelineOptions,
+ ScrollTimelineOptions*,
ExceptionState&);
+ ScrollTimeline(Element*,
+ ScrollDirection,
+ CSSPrimitiveValue*,
+ CSSPrimitiveValue*,
+ double);
+
// AnimationTimeline implementation.
double currentTime(bool& is_null) final;
bool IsScrollTimeline() const override { return true; }
@@ -53,10 +59,17 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
// Returns the Node that should actually have the ScrollableArea (if one
// exists). This can differ from |scrollSource| when |scroll_source_| is the
// Document's scrollingElement.
- Node* ResolvedScrollSource() const;
-
+ Node* ResolvedScrollSource() const { return resolved_scroll_source_; }
ScrollDirection GetOrientation() const { return orientation_; }
+ void GetCurrentAndMaxOffset(const LayoutBox*,
+ double& current_offset,
+ double& max_offset) const;
+ void ResolveScrollStartAndEnd(const LayoutBox*,
+ double max_offset,
+ double& resolved_start_scroll_offset,
+ double& resolved_end_scroll_offset) const;
+
// Must be called when this ScrollTimeline is attached/detached from an
// animation.
void AttachAnimation();
@@ -72,18 +85,11 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
static bool HasActiveScrollTimeline(Node* node);
private:
- ScrollTimeline(Element*,
- ScrollDirection,
- CSSPrimitiveValue*,
- CSSPrimitiveValue*,
- double);
-
- void ResolveScrollStartAndEnd(const LayoutBox*,
- double max_offset,
- double& resolved_start_scroll_offset,
- double& resolved_end_scroll_offset);
-
+ // Use |scroll_source_| only to implement the web-exposed API but use
+ // resolved_scroll_source_ to actually access the scroll related properties.
Member<Element> scroll_source_;
+ Member<Node> resolved_scroll_source_;
+
ScrollDirection orientation_;
Member<CSSPrimitiveValue> start_scroll_offset_;
Member<CSSPrimitiveValue> end_scroll_offset_;
diff --git a/chromium/third_party/blink/renderer/core/animation/scroll_timeline_test.cc b/chromium/third_party/blink/renderer/core/animation/scroll_timeline_test.cc
index 802289072db..5de8c38bf37 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline_test.cc
@@ -6,6 +6,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -34,11 +35,11 @@ TEST_F(ScrollTimelineTest,
// Create the ScrollTimeline. This shouldn't cause the scrollSource to need
// compositing, as it isn't attached to any animation yet.
- ScrollTimelineOptions options;
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
DoubleOrScrollTimelineAutoKeyword time_range =
DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
- options.setTimeRange(time_range);
- options.setScrollSource(GetElementById("scroller"));
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetElementById("scroller"));
ScrollTimeline* scroll_timeline =
ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
EXPECT_EQ(DocumentLifecycle::kPaintClean,
@@ -48,14 +49,175 @@ TEST_F(ScrollTimelineTest,
// Now attach an animation. This should require a compositing update.
scroll_timeline->AttachAnimation();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(scroller->Layer()->GetCompositingState(), kNotComposited);
// Now detach an animation. This should again require a compositing update.
scroll_timeline->DetachAnimation();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(scroller->Layer()->GetCompositingState(), kNotComposited);
}
+TEST_F(ScrollTimelineTest, CurrentTimeIsNullIfScrollSourceIsNotScrollable) {
+ SetBodyInnerHTML(R"HTML(
+ <style>#scroller { width: 100px; height: 100px; }</style>
+ <div id='scroller'></div>
+ )HTML");
+
+ LayoutBoxModelObject* scroller =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"));
+ ASSERT_TRUE(scroller);
+
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
+ DoubleOrScrollTimelineAutoKeyword time_range =
+ DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetElementById("scroller"));
+ ScrollTimeline* scroll_timeline =
+ ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+
+ bool current_time_is_null = false;
+ scroll_timeline->currentTime(current_time_is_null);
+ EXPECT_TRUE(current_time_is_null);
+}
+
+TEST_F(ScrollTimelineTest,
+ CurrentTimeIsNullIfScrollOffsetIsBeyondStartAndEndScrollOffset) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #scroller { overflow: scroll; width: 100px; height: 100px; }
+ #spacer { height: 1000px; }
+ </style>
+ <div id='scroller'>
+ <div id ='spacer'></div>
+ </div>
+ )HTML");
+
+ LayoutBoxModelObject* scroller =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"));
+ ASSERT_TRUE(scroller);
+ ASSERT_TRUE(scroller->HasOverflowClip());
+ PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea();
+ ASSERT_TRUE(scrollable_area);
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
+ DoubleOrScrollTimelineAutoKeyword time_range =
+ DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetElementById("scroller"));
+ options->setStartScrollOffset("10px");
+ options->setEndScrollOffset("90px");
+ ScrollTimeline* scroll_timeline =
+ ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+
+ bool current_time_is_null = false;
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 5), kProgrammaticScroll);
+ scroll_timeline->currentTime(current_time_is_null);
+ EXPECT_TRUE(current_time_is_null);
+
+ current_time_is_null = true;
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 50), kProgrammaticScroll);
+ scroll_timeline->currentTime(current_time_is_null);
+ EXPECT_FALSE(current_time_is_null);
+
+ current_time_is_null = false;
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 100), kProgrammaticScroll);
+ scroll_timeline->currentTime(current_time_is_null);
+ EXPECT_TRUE(current_time_is_null);
+}
+
+TEST_F(ScrollTimelineTest,
+ CurrentTimeIsNullIfEndScrollOffsetIsLessThanStartScrollOffset) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #scroller { overflow: scroll; width: 100px; height: 100px; }
+ #spacer { height: 1000px; }
+ </style>
+ <div id='scroller'>
+ <div id ='spacer'></div>
+ </div>
+ )HTML");
+
+ LayoutBoxModelObject* scroller =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"));
+ ASSERT_TRUE(scroller);
+ ASSERT_TRUE(scroller->HasOverflowClip());
+ PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea();
+ ASSERT_TRUE(scrollable_area);
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
+ DoubleOrScrollTimelineAutoKeyword time_range =
+ DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetElementById("scroller"));
+ options->setStartScrollOffset("80px");
+ options->setEndScrollOffset("40px");
+ ScrollTimeline* scroll_timeline =
+ ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+
+ bool current_time_is_null = false;
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 50), kProgrammaticScroll);
+ scroll_timeline->currentTime(current_time_is_null);
+ EXPECT_TRUE(current_time_is_null);
+}
+
+TEST_F(ScrollTimelineTest,
+ UsingDocumentScrollingElementShouldCorrectlyResolveToDocument) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #content { width: 10000px; height: 10000px; }
+ </style>
+ <div id='content'></div>
+ )HTML");
+
+ EXPECT_EQ(GetDocument().documentElement(), GetDocument().scrollingElement());
+ // Create the ScrollTimeline with Document.scrollingElement() as source. The
+ // resolved scroll source should be the Document.
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
+ DoubleOrScrollTimelineAutoKeyword time_range =
+ DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetDocument().scrollingElement());
+ ScrollTimeline* scroll_timeline =
+ ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(&GetDocument(), scroll_timeline->ResolvedScrollSource());
+}
+
+TEST_F(ScrollTimelineTest,
+ ChangingDocumentScrollingElementShouldNotImpactScrollTimeline) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #body { overflow: scroll; width: 100px; height: 100px; }
+ #content { width: 10000px; height: 10000px; }
+ </style>
+ <div id='content'></div>
+ )HTML");
+
+ // In QuirksMode, the body is the scrolling element
+ GetDocument().SetCompatibilityMode(Document::kQuirksMode);
+ EXPECT_EQ(GetDocument().body(), GetDocument().scrollingElement());
+
+ // Create the ScrollTimeline with Document.scrollingElement() as source. The
+ // resolved scroll source should be the Document.
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
+ DoubleOrScrollTimelineAutoKeyword time_range =
+ DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetDocument().scrollingElement());
+ ScrollTimeline* scroll_timeline =
+ ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(&GetDocument(), scroll_timeline->ResolvedScrollSource());
+
+ // Now change the Document.scrollingElement(). In NoQuirksMode, the
+ // documentElement is the scrolling element and not the body.
+ GetDocument().SetCompatibilityMode(Document::kNoQuirksMode);
+ EXPECT_NE(GetDocument().documentElement(), GetDocument().body());
+ EXPECT_EQ(GetDocument().documentElement(), GetDocument().scrollingElement());
+
+ // Changing the scrollingElement should not impact the previously resolved
+ // scroll source. Note that at this point the scroll timeline's scroll source
+ // is still body element which is no longer the scrolling element. So if we
+ // were to re-resolve the scroll source, it would not map to Document.
+ EXPECT_EQ(&GetDocument(), scroll_timeline->ResolvedScrollSource());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/size_list_property_functions.h b/chromium/third_party/blink/renderer/core/animation/size_list_property_functions.h
index 2f22c58cca1..cf3c147839c 100644
--- a/chromium/third_party/blink/renderer/core/animation/size_list_property_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/size_list_property_functions.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_SIZE_LIST_PROPERTY_FUNCTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_SIZE_LIST_PROPERTY_FUNCTIONS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/style/fill_layer.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/svg_interpolation_types_map.cc b/chromium/third_party/blink/renderer/core/animation/svg_interpolation_types_map.cc
index 9e3b73d7138..4b5afe57c6c 100644
--- a/chromium/third_party/blink/renderer/core/animation/svg_interpolation_types_map.cc
+++ b/chromium/third_party/blink/renderer/core/animation/svg_interpolation_types_map.cc
@@ -37,121 +37,131 @@ const InterpolationTypes& SVGInterpolationTypesMap::Get(
std::make_unique<InterpolationTypes>();
const QualifiedName& attribute = property.SvgAttribute();
- if (attribute == SVGNames::orientAttr) {
+ if (attribute == svg_names::kOrientAttr) {
applicable_types->push_back(
std::make_unique<SVGAngleInterpolationType>(attribute));
- } else if (attribute == SVGNames::numOctavesAttr ||
- attribute == SVGNames::targetXAttr ||
- attribute == SVGNames::targetYAttr) {
+ } else if (attribute == svg_names::kNumOctavesAttr ||
+ attribute == svg_names::kTargetXAttr ||
+ attribute == svg_names::kTargetYAttr) {
applicable_types->push_back(
std::make_unique<SVGIntegerInterpolationType>(attribute));
- } else if (attribute == SVGNames::orderAttr) {
+ } else if (attribute == svg_names::kOrderAttr) {
applicable_types->push_back(
std::make_unique<SVGIntegerOptionalIntegerInterpolationType>(
attribute));
- } else if (attribute == SVGNames::cxAttr || attribute == SVGNames::cyAttr ||
- attribute == SVGNames::fxAttr || attribute == SVGNames::fyAttr ||
- attribute == SVGNames::heightAttr ||
- attribute == SVGNames::markerHeightAttr ||
- attribute == SVGNames::markerWidthAttr ||
- attribute == SVGNames::rAttr || attribute == SVGNames::refXAttr ||
- attribute == SVGNames::refYAttr || attribute == SVGNames::rxAttr ||
- attribute == SVGNames::ryAttr ||
- attribute == SVGNames::startOffsetAttr ||
- attribute == SVGNames::textLengthAttr ||
- attribute == SVGNames::widthAttr ||
- attribute == SVGNames::x1Attr || attribute == SVGNames::x2Attr ||
- attribute == SVGNames::y1Attr || attribute == SVGNames::y2Attr) {
+ } else if (attribute == svg_names::kCxAttr ||
+ attribute == svg_names::kCyAttr ||
+ attribute == svg_names::kFxAttr ||
+ attribute == svg_names::kFyAttr ||
+ attribute == svg_names::kHeightAttr ||
+ attribute == svg_names::kMarkerHeightAttr ||
+ attribute == svg_names::kMarkerWidthAttr ||
+ attribute == svg_names::kRAttr ||
+ attribute == svg_names::kRefXAttr ||
+ attribute == svg_names::kRefYAttr ||
+ attribute == svg_names::kRxAttr ||
+ attribute == svg_names::kRyAttr ||
+ attribute == svg_names::kStartOffsetAttr ||
+ attribute == svg_names::kTextLengthAttr ||
+ attribute == svg_names::kWidthAttr ||
+ attribute == svg_names::kX1Attr ||
+ attribute == svg_names::kX2Attr ||
+ attribute == svg_names::kY1Attr ||
+ attribute == svg_names::kY2Attr) {
applicable_types->push_back(
std::make_unique<SVGLengthInterpolationType>(attribute));
- } else if (attribute == SVGNames::dxAttr || attribute == SVGNames::dyAttr) {
+ } else if (attribute == svg_names::kDxAttr ||
+ attribute == svg_names::kDyAttr) {
applicable_types->push_back(
std::make_unique<SVGNumberInterpolationType>(attribute));
applicable_types->push_back(
std::make_unique<SVGLengthListInterpolationType>(attribute));
- } else if (attribute == SVGNames::xAttr || attribute == SVGNames::yAttr) {
+ } else if (attribute == svg_names::kXAttr || attribute == svg_names::kYAttr) {
applicable_types->push_back(
std::make_unique<SVGLengthInterpolationType>(attribute));
applicable_types->push_back(
std::make_unique<SVGLengthListInterpolationType>(attribute));
- } else if (attribute == SVGNames::amplitudeAttr ||
- attribute == SVGNames::azimuthAttr ||
- attribute == SVGNames::biasAttr ||
- attribute == SVGNames::diffuseConstantAttr ||
- attribute == SVGNames::divisorAttr ||
- attribute == SVGNames::elevationAttr ||
- attribute == SVGNames::exponentAttr ||
- attribute == SVGNames::interceptAttr ||
- attribute == SVGNames::k1Attr || attribute == SVGNames::k2Attr ||
- attribute == SVGNames::k3Attr || attribute == SVGNames::k4Attr ||
- attribute == SVGNames::limitingConeAngleAttr ||
- attribute == SVGNames::offsetAttr ||
- attribute == SVGNames::pathLengthAttr ||
- attribute == SVGNames::pointsAtXAttr ||
- attribute == SVGNames::pointsAtYAttr ||
- attribute == SVGNames::pointsAtZAttr ||
- attribute == SVGNames::scaleAttr ||
- attribute == SVGNames::seedAttr ||
- attribute == SVGNames::slopeAttr ||
- attribute == SVGNames::specularConstantAttr ||
- attribute == SVGNames::specularExponentAttr ||
- attribute == SVGNames::surfaceScaleAttr ||
- attribute == SVGNames::zAttr) {
+ } else if (attribute == svg_names::kAmplitudeAttr ||
+ attribute == svg_names::kAzimuthAttr ||
+ attribute == svg_names::kBiasAttr ||
+ attribute == svg_names::kDiffuseConstantAttr ||
+ attribute == svg_names::kDivisorAttr ||
+ attribute == svg_names::kElevationAttr ||
+ attribute == svg_names::kExponentAttr ||
+ attribute == svg_names::kInterceptAttr ||
+ attribute == svg_names::kK1Attr ||
+ attribute == svg_names::kK2Attr ||
+ attribute == svg_names::kK3Attr ||
+ attribute == svg_names::kK4Attr ||
+ attribute == svg_names::kLimitingConeAngleAttr ||
+ attribute == svg_names::kOffsetAttr ||
+ attribute == svg_names::kPathLengthAttr ||
+ attribute == svg_names::kPointsAtXAttr ||
+ attribute == svg_names::kPointsAtYAttr ||
+ attribute == svg_names::kPointsAtZAttr ||
+ attribute == svg_names::kScaleAttr ||
+ attribute == svg_names::kSeedAttr ||
+ attribute == svg_names::kSlopeAttr ||
+ attribute == svg_names::kSpecularConstantAttr ||
+ attribute == svg_names::kSpecularExponentAttr ||
+ attribute == svg_names::kSurfaceScaleAttr ||
+ attribute == svg_names::kZAttr) {
applicable_types->push_back(
std::make_unique<SVGNumberInterpolationType>(attribute));
- } else if (attribute == SVGNames::kernelMatrixAttr ||
- attribute == SVGNames::rotateAttr ||
- attribute == SVGNames::tableValuesAttr ||
- attribute == SVGNames::valuesAttr) {
+ } else if (attribute == svg_names::kKernelMatrixAttr ||
+ attribute == svg_names::kRotateAttr ||
+ attribute == svg_names::kTableValuesAttr ||
+ attribute == svg_names::kValuesAttr) {
applicable_types->push_back(
std::make_unique<SVGNumberListInterpolationType>(attribute));
- } else if (attribute == SVGNames::baseFrequencyAttr ||
- attribute == SVGNames::kernelUnitLengthAttr ||
- attribute == SVGNames::radiusAttr ||
- attribute == SVGNames::stdDeviationAttr) {
+ } else if (attribute == svg_names::kBaseFrequencyAttr ||
+ attribute == svg_names::kKernelUnitLengthAttr ||
+ attribute == svg_names::kRadiusAttr ||
+ attribute == svg_names::kStdDeviationAttr) {
applicable_types->push_back(
std::make_unique<SVGNumberOptionalNumberInterpolationType>(attribute));
- } else if (attribute == SVGNames::dAttr) {
+ } else if (attribute == svg_names::kDAttr) {
applicable_types->push_back(
std::make_unique<SVGPathInterpolationType>(attribute));
- } else if (attribute == SVGNames::pointsAttr) {
+ } else if (attribute == svg_names::kPointsAttr) {
applicable_types->push_back(
std::make_unique<SVGPointListInterpolationType>(attribute));
- } else if (attribute == SVGNames::viewBoxAttr) {
+ } else if (attribute == svg_names::kViewBoxAttr) {
applicable_types->push_back(
std::make_unique<SVGRectInterpolationType>(attribute));
- } else if (attribute == SVGNames::gradientTransformAttr ||
- attribute == SVGNames::patternTransformAttr ||
- attribute == SVGNames::transformAttr) {
+ } else if (attribute == svg_names::kGradientTransformAttr ||
+ attribute == svg_names::kPatternTransformAttr ||
+ attribute == svg_names::kTransformAttr) {
applicable_types->push_back(
std::make_unique<SVGTransformListInterpolationType>(attribute));
- } else if (attribute == HTMLNames::classAttr ||
- attribute == SVGNames::clipPathUnitsAttr ||
- attribute == SVGNames::edgeModeAttr ||
- attribute == SVGNames::filterUnitsAttr ||
- attribute == SVGNames::gradientUnitsAttr ||
- attribute == SVGNames::hrefAttr || attribute == SVGNames::inAttr ||
- attribute == SVGNames::in2Attr ||
- attribute == SVGNames::lengthAdjustAttr ||
- attribute == SVGNames::markerUnitsAttr ||
- attribute == SVGNames::maskContentUnitsAttr ||
- attribute == SVGNames::maskUnitsAttr ||
- attribute == SVGNames::methodAttr ||
- attribute == SVGNames::modeAttr ||
- attribute == SVGNames::operatorAttr ||
- attribute == SVGNames::patternContentUnitsAttr ||
- attribute == SVGNames::patternUnitsAttr ||
- attribute == SVGNames::preserveAlphaAttr ||
- attribute == SVGNames::preserveAspectRatioAttr ||
- attribute == SVGNames::primitiveUnitsAttr ||
- attribute == SVGNames::resultAttr ||
- attribute == SVGNames::spacingAttr ||
- attribute == SVGNames::spreadMethodAttr ||
- attribute == SVGNames::stitchTilesAttr ||
- attribute == SVGNames::targetAttr ||
- attribute == SVGNames::typeAttr ||
- attribute == SVGNames::xChannelSelectorAttr ||
- attribute == SVGNames::yChannelSelectorAttr) {
+ } else if (attribute == html_names::kClassAttr ||
+ attribute == svg_names::kClipPathUnitsAttr ||
+ attribute == svg_names::kEdgeModeAttr ||
+ attribute == svg_names::kFilterUnitsAttr ||
+ attribute == svg_names::kGradientUnitsAttr ||
+ attribute == svg_names::kHrefAttr ||
+ attribute == svg_names::kInAttr ||
+ attribute == svg_names::kIn2Attr ||
+ attribute == svg_names::kLengthAdjustAttr ||
+ attribute == svg_names::kMarkerUnitsAttr ||
+ attribute == svg_names::kMaskContentUnitsAttr ||
+ attribute == svg_names::kMaskUnitsAttr ||
+ attribute == svg_names::kMethodAttr ||
+ attribute == svg_names::kModeAttr ||
+ attribute == svg_names::kOperatorAttr ||
+ attribute == svg_names::kPatternContentUnitsAttr ||
+ attribute == svg_names::kPatternUnitsAttr ||
+ attribute == svg_names::kPreserveAlphaAttr ||
+ attribute == svg_names::kPreserveAspectRatioAttr ||
+ attribute == svg_names::kPrimitiveUnitsAttr ||
+ attribute == svg_names::kResultAttr ||
+ attribute == svg_names::kSpacingAttr ||
+ attribute == svg_names::kSpreadMethodAttr ||
+ attribute == svg_names::kStitchTilesAttr ||
+ attribute == svg_names::kTargetAttr ||
+ attribute == svg_names::kTypeAttr ||
+ attribute == svg_names::kXChannelSelectorAttr ||
+ attribute == svg_names::kYChannelSelectorAttr) {
// Use default SVGValueInterpolationType.
} else {
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/animation/svg_number_interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/svg_number_interpolation_type.h
index 02a01fb6b9f..9afe9be7a8f 100644
--- a/chromium/third_party/blink/renderer/core/animation/svg_number_interpolation_type.h
+++ b/chromium/third_party/blink/renderer/core/animation/svg_number_interpolation_type.h
@@ -14,7 +14,7 @@ class SVGNumberInterpolationType : public SVGInterpolationType {
public:
SVGNumberInterpolationType(const QualifiedName& attribute)
: SVGInterpolationType(attribute),
- is_non_negative_(attribute == SVGNames::pathLengthAttr) {}
+ is_non_negative_(attribute == svg_names::kPathLengthAttr) {}
private:
InterpolationValue MaybeConvertNeutral(const InterpolationValue& underlying,
diff --git a/chromium/third_party/blink/renderer/core/animation/test_data/raf-countdown.html b/chromium/third_party/blink/renderer/core/animation/test_data/raf-countdown.html
index dfe149953a4..05b3a824adc 100644
--- a/chromium/third_party/blink/renderer/core/animation/test_data/raf-countdown.html
+++ b/chromium/third_party/blink/renderer/core/animation/test_data/raf-countdown.html
@@ -1,7 +1,6 @@
<!DOCTYPE html>
<script>
function runRaf(countdown) {
- console.log(countdown);
countdown--;
if (countdown > 0)
requestAnimationFrame(function() { runRaf(countdown); });
diff --git a/chromium/third_party/blink/renderer/core/animation/timing_input.cc b/chromium/third_party/blink/renderer/core/animation/timing_input.cc
index 3482e109603..da804826fef 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_input.cc
+++ b/chromium/third_party/blink/renderer/core/animation/timing_input.cc
@@ -48,7 +48,7 @@ base::Optional<AnimationTimeDelta> ConvertIterationDuration(
return base::nullopt;
}
-Timing ConvertEffectTiming(const EffectTiming& timing_input,
+Timing ConvertEffectTiming(const EffectTiming* timing_input,
Document* document,
ExceptionState& exception_state) {
Timing timing_output;
@@ -89,8 +89,8 @@ Timing TimingInput::Convert(
// If options is a double,
// Let timing input be a new EffectTiming object with all members set to
// their default values and duration set to options.
- EffectTiming timing_input;
- timing_input.setDuration(UnrestrictedDoubleOrString::FromUnrestrictedDouble(
+ EffectTiming* timing_input = EffectTiming::Create();
+ timing_input->setDuration(UnrestrictedDoubleOrString::FromUnrestrictedDouble(
options.GetAsUnrestrictedDouble()));
return ConvertEffectTiming(timing_input, document, exception_state);
}
@@ -114,28 +114,28 @@ Timing TimingInput::Convert(
// If options is a double,
// Let timing input be a new EffectTiming object with all members set to
// their default values and duration set to options.
- EffectTiming timing_input;
- timing_input.setDuration(UnrestrictedDoubleOrString::FromUnrestrictedDouble(
+ EffectTiming* timing_input = EffectTiming::Create();
+ timing_input->setDuration(UnrestrictedDoubleOrString::FromUnrestrictedDouble(
options.GetAsUnrestrictedDouble()));
return ConvertEffectTiming(timing_input, document, exception_state);
}
template <class InputTiming>
bool TimingInput::Update(Timing& timing,
- const InputTiming& input,
+ const InputTiming* input,
Document* document,
ExceptionState& exception_state) {
// 1. If the iterationStart member of input is present and less than zero,
// throw a TypeError and abort this procedure.
- if (input.hasIterationStart() && input.iterationStart() < 0) {
+ if (input->hasIterationStart() && input->iterationStart() < 0) {
exception_state.ThrowTypeError("iterationStart must be non-negative");
return false;
}
// 2. If the iterations member of input is present, and less than zero or is
// the value NaN, throw a TypeError and abort this procedure.
- if (input.hasIterations() &&
- (std::isnan(input.iterations()) || input.iterations() < 0)) {
+ if (input->hasIterations() &&
+ (std::isnan(input->iterations()) || input->iterations() < 0)) {
exception_state.ThrowTypeError("iterationCount must be non-negative");
return false;
}
@@ -145,15 +145,15 @@ bool TimingInput::Update(Timing& timing,
//
// We also throw if the value is a string but not 'auto', as per
// https://github.com/w3c/csswg-drafts/issues/247 .
- if (input.hasDuration()) {
+ if (input->hasDuration()) {
const char* error_message = "duration must be non-negative or auto";
- if (input.duration().IsUnrestrictedDouble()) {
- double duration = input.duration().GetAsUnrestrictedDouble();
+ if (input->duration().IsUnrestrictedDouble()) {
+ double duration = input->duration().GetAsUnrestrictedDouble();
if (std::isnan(duration) || duration < 0) {
exception_state.ThrowTypeError(error_message);
return false;
}
- } else if (input.duration().GetAsString() != "auto") {
+ } else if (input->duration().GetAsString() != "auto") {
exception_state.ThrowTypeError(error_message);
return false;
}
@@ -163,9 +163,9 @@ bool TimingInput::Update(Timing& timing,
// <timing-function> production [CSS-TIMING-1], throw a TypeError and abort
// this procedure.
scoped_refptr<TimingFunction> timing_function;
- if (input.hasEasing()) {
+ if (input->hasEasing()) {
timing_function = AnimationInputHelpers::ParseTimingFunction(
- input.easing(), document, exception_state);
+ input->easing(), document, exception_state);
if (!timing_function) {
DCHECK(exception_state.HadException());
return false;
@@ -175,32 +175,33 @@ bool TimingInput::Update(Timing& timing,
// 5. Assign each member present in input to the corresponding timing property
// of effect as follows:
bool changed = false;
- if (input.hasDelay()) {
- DCHECK(std::isfinite(input.delay()));
- changed |= UpdateValueIfChanged(timing.start_delay, input.delay() / 1000);
+ if (input->hasDelay()) {
+ DCHECK(std::isfinite(input->delay()));
+ changed |= UpdateValueIfChanged(timing.start_delay, input->delay() / 1000);
}
- if (input.hasEndDelay()) {
- DCHECK(std::isfinite(input.endDelay()));
- changed |= UpdateValueIfChanged(timing.end_delay, input.endDelay() / 1000);
+ if (input->hasEndDelay()) {
+ DCHECK(std::isfinite(input->endDelay()));
+ changed |= UpdateValueIfChanged(timing.end_delay, input->endDelay() / 1000);
}
- if (input.hasFill()) {
+ if (input->hasFill()) {
changed |=
- UpdateValueIfChanged(timing.fill_mode, ConvertFillMode(input.fill()));
+ UpdateValueIfChanged(timing.fill_mode, ConvertFillMode(input->fill()));
}
- if (input.hasIterationStart()) {
+ if (input->hasIterationStart()) {
changed |=
- UpdateValueIfChanged(timing.iteration_start, input.iterationStart());
+ UpdateValueIfChanged(timing.iteration_start, input->iterationStart());
}
- if (input.hasIterations()) {
- changed |= UpdateValueIfChanged(timing.iteration_count, input.iterations());
+ if (input->hasIterations()) {
+ changed |=
+ UpdateValueIfChanged(timing.iteration_count, input->iterations());
}
- if (input.hasDuration()) {
- changed |= UpdateValueIfChanged(timing.iteration_duration,
- ConvertIterationDuration(input.duration()));
+ if (input->hasDuration()) {
+ changed |= UpdateValueIfChanged(
+ timing.iteration_duration, ConvertIterationDuration(input->duration()));
}
- if (input.hasDirection()) {
+ if (input->hasDirection()) {
changed |= UpdateValueIfChanged(
- timing.direction, ConvertPlaybackDirection(input.direction()));
+ timing.direction, ConvertPlaybackDirection(input->direction()));
}
if (timing_function) {
// We need to compare the timing functions by underlying value to see if
@@ -215,7 +216,7 @@ bool TimingInput::Update(Timing& timing,
// Export the OptionalEffectTiming version for AnimationEffect::updateTiming.
template CORE_EXPORT bool TimingInput::Update(Timing&,
- const OptionalEffectTiming&,
+ const OptionalEffectTiming*,
Document*,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/core/animation/timing_input.h b/chromium/third_party/blink/renderer/core/animation/timing_input.h
index 19e3240c4da..b9a6a329d7f 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_input.h
+++ b/chromium/third_party/blink/renderer/core/animation/timing_input.h
@@ -44,7 +44,7 @@ class CORE_EXPORT TimingInput {
//
// https://drafts.csswg.org/web-animations-1/#update-the-timing-properties-of-an-animation-effect
template <class TimingInput>
- static bool Update(Timing&, const TimingInput&, Document*, ExceptionState&);
+ static bool Update(Timing&, const TimingInput*, Document*, ExceptionState&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/timing_input_test.cc b/chromium/third_party/blink/renderer/core/animation/timing_input_test.cc
index c64636d7393..de45cbe72be 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_input_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/timing_input_test.cc
@@ -49,7 +49,8 @@ Timing AnimationTimingInputTest::ApplyTimingInputNumber(
DummyExceptionStateForTesting exception_state;
Timing result;
if (is_keyframeeffectoptions) {
- KeyframeEffectOptions timing_input_dictionary;
+ KeyframeEffectOptions* timing_input_dictionary =
+ KeyframeEffectOptions::Create();
V8KeyframeEffectOptions::ToImpl(isolate, timing_input,
timing_input_dictionary, exception_state);
UnrestrictedDoubleOrKeyframeEffectOptions timing_input =
@@ -57,7 +58,8 @@ Timing AnimationTimingInputTest::ApplyTimingInputNumber(
timing_input_dictionary);
result = TimingInput::Convert(timing_input, GetDocument(), exception_state);
} else {
- KeyframeAnimationOptions timing_input_dictionary;
+ KeyframeAnimationOptions* timing_input_dictionary =
+ KeyframeAnimationOptions::Create();
V8KeyframeAnimationOptions::ToImpl(
isolate, timing_input, timing_input_dictionary, exception_state);
UnrestrictedDoubleOrKeyframeAnimationOptions timing_input =
@@ -82,7 +84,8 @@ Timing AnimationTimingInputTest::ApplyTimingInputString(
DummyExceptionStateForTesting exception_state;
Timing result;
if (is_keyframeeffectoptions) {
- KeyframeEffectOptions timing_input_dictionary;
+ KeyframeEffectOptions* timing_input_dictionary =
+ KeyframeEffectOptions::Create();
V8KeyframeEffectOptions::ToImpl(isolate, timing_input,
timing_input_dictionary, exception_state);
UnrestrictedDoubleOrKeyframeEffectOptions timing_input =
@@ -90,7 +93,8 @@ Timing AnimationTimingInputTest::ApplyTimingInputString(
timing_input_dictionary);
result = TimingInput::Convert(timing_input, GetDocument(), exception_state);
} else {
- KeyframeAnimationOptions timing_input_dictionary;
+ KeyframeAnimationOptions* timing_input_dictionary =
+ KeyframeAnimationOptions::Create();
V8KeyframeAnimationOptions::ToImpl(
isolate, timing_input, timing_input_dictionary, exception_state);
UnrestrictedDoubleOrKeyframeAnimationOptions timing_input =
@@ -441,7 +445,7 @@ TEST_F(AnimationTimingInputTest, TimingInputEmpty) {
Timing control_timing;
UnrestrictedDoubleOrKeyframeEffectOptions timing_input =
UnrestrictedDoubleOrKeyframeEffectOptions::FromKeyframeEffectOptions(
- KeyframeEffectOptions());
+ KeyframeEffectOptions::Create());
Timing updated_timing =
TimingInput::Convert(timing_input, nullptr, exception_state);
EXPECT_FALSE(exception_state.HadException());
@@ -460,7 +464,7 @@ TEST_F(AnimationTimingInputTest, TimingInputEmptyKeyframeAnimationOptions) {
Timing control_timing;
UnrestrictedDoubleOrKeyframeAnimationOptions input_timing =
UnrestrictedDoubleOrKeyframeAnimationOptions::
- FromKeyframeAnimationOptions(KeyframeAnimationOptions());
+ FromKeyframeAnimationOptions(KeyframeAnimationOptions::Create());
Timing updated_timing =
TimingInput::Convert(input_timing, nullptr, exception_state);
EXPECT_FALSE(exception_state.HadException());
diff --git a/chromium/third_party/blink/renderer/core/aom/accessible_node.cc b/chromium/third_party/blink/renderer/core/aom/accessible_node.cc
index a1bdd6bf906..b90ae774577 100644
--- a/chromium/third_party/blink/renderer/core/aom/accessible_node.cc
+++ b/chromium/third_party/blink/renderer/core/aom/accessible_node.cc
@@ -14,44 +14,44 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
QualifiedName GetCorrespondingARIAAttribute(AOMStringProperty property) {
switch (property) {
case AOMStringProperty::kAutocomplete:
- return aria_autocompleteAttr;
+ return kAriaAutocompleteAttr;
case AOMStringProperty::kChecked:
- return aria_checkedAttr;
+ return kAriaCheckedAttr;
case AOMStringProperty::kCurrent:
- return aria_currentAttr;
+ return kAriaCurrentAttr;
case AOMStringProperty::kHasPopUp:
- return aria_haspopupAttr;
+ return kAriaHaspopupAttr;
case AOMStringProperty::kInvalid:
- return aria_invalidAttr;
+ return kAriaInvalidAttr;
case AOMStringProperty::kKeyShortcuts:
- return aria_keyshortcutsAttr;
+ return kAriaKeyshortcutsAttr;
case AOMStringProperty::kLabel:
- return aria_labelAttr;
+ return kAriaLabelAttr;
case AOMStringProperty::kLive:
- return aria_liveAttr;
+ return kAriaLiveAttr;
case AOMStringProperty::kOrientation:
- return aria_orientationAttr;
+ return kAriaOrientationAttr;
case AOMStringProperty::kPlaceholder:
- return aria_placeholderAttr;
+ return kAriaPlaceholderAttr;
case AOMStringProperty::kPressed:
- return aria_pressedAttr;
+ return kAriaPressedAttr;
case AOMStringProperty::kRelevant:
- return aria_relevantAttr;
+ return kAriaRelevantAttr;
case AOMStringProperty::kRole:
- return roleAttr;
+ return kRoleAttr;
case AOMStringProperty::kRoleDescription:
- return aria_roledescriptionAttr;
+ return kAriaRoledescriptionAttr;
case AOMStringProperty::kSort:
- return aria_sortAttr;
+ return kAriaSortAttr;
case AOMStringProperty::kValueText:
- return aria_valuetextAttr;
+ return kAriaValuetextAttr;
}
NOTREACHED();
@@ -61,13 +61,13 @@ QualifiedName GetCorrespondingARIAAttribute(AOMStringProperty property) {
QualifiedName GetCorrespondingARIAAttribute(AOMRelationProperty property) {
switch (property) {
case AOMRelationProperty::kActiveDescendant:
- return aria_activedescendantAttr;
+ return kAriaActivedescendantAttr;
break;
case AOMRelationProperty::kDetails:
- return aria_detailsAttr;
+ return kAriaDetailsAttr;
break;
case AOMRelationProperty::kErrorMessage:
- return aria_errormessageAttr;
+ return kAriaErrormessageAttr;
break;
}
@@ -78,21 +78,21 @@ QualifiedName GetCorrespondingARIAAttribute(AOMRelationProperty property) {
QualifiedName GetCorrespondingARIAAttribute(AOMRelationListProperty property) {
switch (property) {
case AOMRelationListProperty::kDescribedBy:
- return aria_describedbyAttr;
+ return kAriaDescribedbyAttr;
break;
case AOMRelationListProperty::kControls:
- return aria_controlsAttr;
+ return kAriaControlsAttr;
break;
case AOMRelationListProperty::kFlowTo:
- return aria_flowtoAttr;
+ return kAriaFlowtoAttr;
break;
case AOMRelationListProperty::kLabeledBy:
// Note that there are two allowed spellings of this attribute.
// Callers should check both.
- return aria_labelledbyAttr;
+ return kAriaLabelledbyAttr;
break;
case AOMRelationListProperty::kOwns:
- return aria_ownsAttr;
+ return kAriaOwnsAttr;
break;
}
@@ -103,37 +103,37 @@ QualifiedName GetCorrespondingARIAAttribute(AOMRelationListProperty property) {
QualifiedName GetCorrespondingARIAAttribute(AOMBooleanProperty property) {
switch (property) {
case AOMBooleanProperty::kAtomic:
- return aria_atomicAttr;
+ return kAriaAtomicAttr;
break;
case AOMBooleanProperty::kBusy:
- return aria_busyAttr;
+ return kAriaBusyAttr;
break;
case AOMBooleanProperty::kDisabled:
- return aria_disabledAttr;
+ return kAriaDisabledAttr;
break;
case AOMBooleanProperty::kExpanded:
- return aria_expandedAttr;
+ return kAriaExpandedAttr;
break;
case AOMBooleanProperty::kHidden:
- return aria_hiddenAttr;
+ return kAriaHiddenAttr;
break;
case AOMBooleanProperty::kModal:
- return aria_modalAttr;
+ return kAriaModalAttr;
break;
case AOMBooleanProperty::kMultiline:
- return aria_multilineAttr;
+ return kAriaMultilineAttr;
break;
case AOMBooleanProperty::kMultiselectable:
- return aria_multiselectableAttr;
+ return kAriaMultiselectableAttr;
break;
case AOMBooleanProperty::kReadOnly:
- return aria_readonlyAttr;
+ return kAriaReadonlyAttr;
break;
case AOMBooleanProperty::kRequired:
- return aria_requiredAttr;
+ return kAriaRequiredAttr;
break;
case AOMBooleanProperty::kSelected:
- return aria_selectedAttr;
+ return kAriaSelectedAttr;
break;
}
@@ -145,13 +145,13 @@ QualifiedName GetCorrespondingARIAAttribute(AOMFloatProperty property) {
AtomicString attr_value;
switch (property) {
case AOMFloatProperty::kValueMax:
- return aria_valuemaxAttr;
+ return kAriaValuemaxAttr;
break;
case AOMFloatProperty::kValueMin:
- return aria_valueminAttr;
+ return kAriaValueminAttr;
break;
case AOMFloatProperty::kValueNow:
- return aria_valuenowAttr;
+ return kAriaValuenowAttr;
break;
}
@@ -162,22 +162,22 @@ QualifiedName GetCorrespondingARIAAttribute(AOMFloatProperty property) {
QualifiedName GetCorrespondingARIAAttribute(AOMUIntProperty property) {
switch (property) {
case AOMUIntProperty::kColIndex:
- return aria_colindexAttr;
+ return kAriaColindexAttr;
break;
case AOMUIntProperty::kColSpan:
- return aria_colspanAttr;
+ return kAriaColspanAttr;
break;
case AOMUIntProperty::kLevel:
- return aria_levelAttr;
+ return kAriaLevelAttr;
break;
case AOMUIntProperty::kPosInSet:
- return aria_posinsetAttr;
+ return kAriaPosinsetAttr;
break;
case AOMUIntProperty::kRowIndex:
- return aria_rowindexAttr;
+ return kAriaRowindexAttr;
break;
case AOMUIntProperty::kRowSpan:
- return aria_rowspanAttr;
+ return kAriaRowspanAttr;
break;
}
@@ -188,13 +188,13 @@ QualifiedName GetCorrespondingARIAAttribute(AOMUIntProperty property) {
QualifiedName GetCorrespondingARIAAttribute(AOMIntProperty property) {
switch (property) {
case AOMIntProperty::kColCount:
- return aria_colcountAttr;
+ return kAriaColcountAttr;
break;
case AOMIntProperty::kRowCount:
- return aria_rowcountAttr;
+ return kAriaRowcountAttr;
break;
case AOMIntProperty::kSetSize:
- return aria_setsizeAttr;
+ return kAriaSetsizeAttr;
break;
}
@@ -422,7 +422,7 @@ bool AccessibleNode::GetPropertyOrARIAAttribute(
QualifiedName attribute = GetCorrespondingARIAAttribute(property);
String value = element->FastGetAttribute(attribute).GetString();
if (value.IsEmpty() && property == AOMRelationListProperty::kLabeledBy)
- value = element->FastGetAttribute(aria_labeledbyAttr).GetString();
+ value = element->FastGetAttribute(kAriaLabeledbyAttr).GetString();
if (value.IsEmpty())
return false;
@@ -563,7 +563,7 @@ AccessibleNode* AccessibleNode::activeDescendant() const {
void AccessibleNode::setActiveDescendant(AccessibleNode* active_descendant) {
SetRelationProperty(AOMRelationProperty::kActiveDescendant,
active_descendant);
- NotifyAttributeChanged(aria_activedescendantAttr);
+ NotifyAttributeChanged(kAriaActivedescendantAttr);
}
bool AccessibleNode::atomic(bool& is_null) const {
@@ -572,7 +572,7 @@ bool AccessibleNode::atomic(bool& is_null) const {
void AccessibleNode::setAtomic(bool atomic, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kAtomic, atomic, is_null);
- NotifyAttributeChanged(aria_atomicAttr);
+ NotifyAttributeChanged(kAriaAtomicAttr);
}
AtomicString AccessibleNode::autocomplete() const {
@@ -581,7 +581,7 @@ AtomicString AccessibleNode::autocomplete() const {
void AccessibleNode::setAutocomplete(const AtomicString& autocomplete) {
SetStringProperty(AOMStringProperty::kAutocomplete, autocomplete);
- NotifyAttributeChanged(aria_autocompleteAttr);
+ NotifyAttributeChanged(kAriaAutocompleteAttr);
}
bool AccessibleNode::busy(bool& is_null) const {
@@ -590,7 +590,7 @@ bool AccessibleNode::busy(bool& is_null) const {
void AccessibleNode::setBusy(bool busy, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kBusy, busy, is_null);
- NotifyAttributeChanged(aria_busyAttr);
+ NotifyAttributeChanged(kAriaBusyAttr);
}
AtomicString AccessibleNode::checked() const {
@@ -599,7 +599,7 @@ AtomicString AccessibleNode::checked() const {
void AccessibleNode::setChecked(const AtomicString& checked) {
SetStringProperty(AOMStringProperty::kChecked, checked);
- NotifyAttributeChanged(aria_checkedAttr);
+ NotifyAttributeChanged(kAriaCheckedAttr);
}
int32_t AccessibleNode::colCount(bool& is_null) const {
@@ -608,7 +608,7 @@ int32_t AccessibleNode::colCount(bool& is_null) const {
void AccessibleNode::setColCount(int32_t col_count, bool is_null) {
SetIntProperty(AOMIntProperty::kColCount, col_count, is_null);
- NotifyAttributeChanged(aria_colcountAttr);
+ NotifyAttributeChanged(kAriaColcountAttr);
}
uint32_t AccessibleNode::colIndex(bool& is_null) const {
@@ -617,7 +617,7 @@ uint32_t AccessibleNode::colIndex(bool& is_null) const {
void AccessibleNode::setColIndex(uint32_t col_index, bool is_null) {
SetUIntProperty(AOMUIntProperty::kColIndex, col_index, is_null);
- NotifyAttributeChanged(aria_colindexAttr);
+ NotifyAttributeChanged(kAriaColindexAttr);
}
uint32_t AccessibleNode::colSpan(bool& is_null) const {
@@ -626,7 +626,7 @@ uint32_t AccessibleNode::colSpan(bool& is_null) const {
void AccessibleNode::setColSpan(uint32_t col_span, bool is_null) {
SetUIntProperty(AOMUIntProperty::kColSpan, col_span, is_null);
- NotifyAttributeChanged(aria_colspanAttr);
+ NotifyAttributeChanged(kAriaColspanAttr);
}
AccessibleNodeList* AccessibleNode::controls() const {
@@ -635,7 +635,7 @@ AccessibleNodeList* AccessibleNode::controls() const {
void AccessibleNode::setControls(AccessibleNodeList* controls) {
SetRelationListProperty(AOMRelationListProperty::kControls, controls);
- NotifyAttributeChanged(aria_controlsAttr);
+ NotifyAttributeChanged(kAriaControlsAttr);
}
AtomicString AccessibleNode::current() const {
@@ -644,7 +644,7 @@ AtomicString AccessibleNode::current() const {
void AccessibleNode::setCurrent(const AtomicString& current) {
SetStringProperty(AOMStringProperty::kCurrent, current);
- NotifyAttributeChanged(aria_currentAttr);
+ NotifyAttributeChanged(kAriaCurrentAttr);
}
AccessibleNodeList* AccessibleNode::describedBy() {
@@ -653,7 +653,7 @@ AccessibleNodeList* AccessibleNode::describedBy() {
void AccessibleNode::setDescribedBy(AccessibleNodeList* described_by) {
SetRelationListProperty(AOMRelationListProperty::kDescribedBy, described_by);
- NotifyAttributeChanged(aria_describedbyAttr);
+ NotifyAttributeChanged(kAriaDescribedbyAttr);
}
AccessibleNode* AccessibleNode::details() const {
@@ -662,7 +662,7 @@ AccessibleNode* AccessibleNode::details() const {
void AccessibleNode::setDetails(AccessibleNode* details) {
SetRelationProperty(AOMRelationProperty::kDetails, details);
- NotifyAttributeChanged(aria_detailsAttr);
+ NotifyAttributeChanged(kAriaDetailsAttr);
}
bool AccessibleNode::disabled(bool& is_null) const {
@@ -671,7 +671,7 @@ bool AccessibleNode::disabled(bool& is_null) const {
void AccessibleNode::setDisabled(bool disabled, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kDisabled, disabled, is_null);
- NotifyAttributeChanged(aria_disabledAttr);
+ NotifyAttributeChanged(kAriaDisabledAttr);
}
AccessibleNode* AccessibleNode::errorMessage() const {
@@ -680,7 +680,7 @@ AccessibleNode* AccessibleNode::errorMessage() const {
void AccessibleNode::setErrorMessage(AccessibleNode* error_message) {
SetRelationProperty(AOMRelationProperty::kErrorMessage, error_message);
- NotifyAttributeChanged(aria_errormessageAttr);
+ NotifyAttributeChanged(kAriaErrormessageAttr);
}
bool AccessibleNode::expanded(bool& is_null) const {
@@ -689,7 +689,7 @@ bool AccessibleNode::expanded(bool& is_null) const {
void AccessibleNode::setExpanded(bool expanded, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kExpanded, expanded, is_null);
- NotifyAttributeChanged(aria_expandedAttr);
+ NotifyAttributeChanged(kAriaExpandedAttr);
}
AccessibleNodeList* AccessibleNode::flowTo() const {
@@ -698,7 +698,7 @@ AccessibleNodeList* AccessibleNode::flowTo() const {
void AccessibleNode::setFlowTo(AccessibleNodeList* flow_to) {
SetRelationListProperty(AOMRelationListProperty::kFlowTo, flow_to);
- NotifyAttributeChanged(aria_flowtoAttr);
+ NotifyAttributeChanged(kAriaFlowtoAttr);
}
AtomicString AccessibleNode::hasPopUp() const {
@@ -707,7 +707,7 @@ AtomicString AccessibleNode::hasPopUp() const {
void AccessibleNode::setHasPopUp(const AtomicString& has_popup) {
SetStringProperty(AOMStringProperty::kHasPopUp, has_popup);
- NotifyAttributeChanged(aria_haspopupAttr);
+ NotifyAttributeChanged(kAriaHaspopupAttr);
}
bool AccessibleNode::hidden(bool& is_null) const {
@@ -716,7 +716,7 @@ bool AccessibleNode::hidden(bool& is_null) const {
void AccessibleNode::setHidden(bool hidden, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kHidden, hidden, is_null);
- NotifyAttributeChanged(aria_hiddenAttr);
+ NotifyAttributeChanged(kAriaHiddenAttr);
}
AtomicString AccessibleNode::invalid() const {
@@ -725,7 +725,7 @@ AtomicString AccessibleNode::invalid() const {
void AccessibleNode::setInvalid(const AtomicString& invalid) {
SetStringProperty(AOMStringProperty::kInvalid, invalid);
- NotifyAttributeChanged(aria_invalidAttr);
+ NotifyAttributeChanged(kAriaInvalidAttr);
}
AtomicString AccessibleNode::keyShortcuts() const {
@@ -734,7 +734,7 @@ AtomicString AccessibleNode::keyShortcuts() const {
void AccessibleNode::setKeyShortcuts(const AtomicString& key_shortcuts) {
SetStringProperty(AOMStringProperty::kKeyShortcuts, key_shortcuts);
- NotifyAttributeChanged(aria_keyshortcutsAttr);
+ NotifyAttributeChanged(kAriaKeyshortcutsAttr);
}
AtomicString AccessibleNode::label() const {
@@ -743,7 +743,7 @@ AtomicString AccessibleNode::label() const {
void AccessibleNode::setLabel(const AtomicString& label) {
SetStringProperty(AOMStringProperty::kLabel, label);
- NotifyAttributeChanged(aria_labelAttr);
+ NotifyAttributeChanged(kAriaLabelAttr);
}
AccessibleNodeList* AccessibleNode::labeledBy() {
@@ -752,7 +752,7 @@ AccessibleNodeList* AccessibleNode::labeledBy() {
void AccessibleNode::setLabeledBy(AccessibleNodeList* labeled_by) {
SetRelationListProperty(AOMRelationListProperty::kLabeledBy, labeled_by);
- NotifyAttributeChanged(aria_labelledbyAttr);
+ NotifyAttributeChanged(kAriaLabelledbyAttr);
}
uint32_t AccessibleNode::level(bool& is_null) const {
@@ -761,7 +761,7 @@ uint32_t AccessibleNode::level(bool& is_null) const {
void AccessibleNode::setLevel(uint32_t level, bool is_null) {
SetUIntProperty(AOMUIntProperty::kLevel, level, is_null);
- NotifyAttributeChanged(aria_levelAttr);
+ NotifyAttributeChanged(kAriaLevelAttr);
}
AtomicString AccessibleNode::live() const {
@@ -770,7 +770,7 @@ AtomicString AccessibleNode::live() const {
void AccessibleNode::setLive(const AtomicString& live) {
SetStringProperty(AOMStringProperty::kLive, live);
- NotifyAttributeChanged(aria_liveAttr);
+ NotifyAttributeChanged(kAriaLiveAttr);
}
bool AccessibleNode::modal(bool& is_null) const {
@@ -779,7 +779,7 @@ bool AccessibleNode::modal(bool& is_null) const {
void AccessibleNode::setModal(bool modal, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kModal, modal, is_null);
- NotifyAttributeChanged(aria_modalAttr);
+ NotifyAttributeChanged(kAriaModalAttr);
}
bool AccessibleNode::multiline(bool& is_null) const {
@@ -788,7 +788,7 @@ bool AccessibleNode::multiline(bool& is_null) const {
void AccessibleNode::setMultiline(bool multiline, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kMultiline, multiline, is_null);
- NotifyAttributeChanged(aria_multilineAttr);
+ NotifyAttributeChanged(kAriaMultilineAttr);
}
bool AccessibleNode::multiselectable(bool& is_null) const {
@@ -798,7 +798,7 @@ bool AccessibleNode::multiselectable(bool& is_null) const {
void AccessibleNode::setMultiselectable(bool multiselectable, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kMultiselectable, multiselectable,
is_null);
- NotifyAttributeChanged(aria_multiselectableAttr);
+ NotifyAttributeChanged(kAriaMultiselectableAttr);
}
AtomicString AccessibleNode::orientation() const {
@@ -807,7 +807,7 @@ AtomicString AccessibleNode::orientation() const {
void AccessibleNode::setOrientation(const AtomicString& orientation) {
SetStringProperty(AOMStringProperty::kOrientation, orientation);
- NotifyAttributeChanged(aria_orientationAttr);
+ NotifyAttributeChanged(kAriaOrientationAttr);
}
AccessibleNodeList* AccessibleNode::owns() const {
@@ -816,7 +816,7 @@ AccessibleNodeList* AccessibleNode::owns() const {
void AccessibleNode::setOwns(AccessibleNodeList* owns) {
SetRelationListProperty(AOMRelationListProperty::kOwns, owns);
- NotifyAttributeChanged(aria_ownsAttr);
+ NotifyAttributeChanged(kAriaOwnsAttr);
}
AtomicString AccessibleNode::placeholder() const {
@@ -825,7 +825,7 @@ AtomicString AccessibleNode::placeholder() const {
void AccessibleNode::setPlaceholder(const AtomicString& placeholder) {
SetStringProperty(AOMStringProperty::kPlaceholder, placeholder);
- NotifyAttributeChanged(aria_placeholderAttr);
+ NotifyAttributeChanged(kAriaPlaceholderAttr);
}
uint32_t AccessibleNode::posInSet(bool& is_null) const {
@@ -834,7 +834,7 @@ uint32_t AccessibleNode::posInSet(bool& is_null) const {
void AccessibleNode::setPosInSet(uint32_t pos_in_set, bool is_null) {
SetUIntProperty(AOMUIntProperty::kPosInSet, pos_in_set, is_null);
- NotifyAttributeChanged(aria_posinsetAttr);
+ NotifyAttributeChanged(kAriaPosinsetAttr);
}
AtomicString AccessibleNode::pressed() const {
@@ -843,7 +843,7 @@ AtomicString AccessibleNode::pressed() const {
void AccessibleNode::setPressed(const AtomicString& pressed) {
SetStringProperty(AOMStringProperty::kPressed, pressed);
- NotifyAttributeChanged(aria_pressedAttr);
+ NotifyAttributeChanged(kAriaPressedAttr);
}
bool AccessibleNode::readOnly(bool& is_null) const {
@@ -852,7 +852,7 @@ bool AccessibleNode::readOnly(bool& is_null) const {
void AccessibleNode::setReadOnly(bool read_only, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kReadOnly, read_only, is_null);
- NotifyAttributeChanged(aria_readonlyAttr);
+ NotifyAttributeChanged(kAriaReadonlyAttr);
}
AtomicString AccessibleNode::relevant() const {
@@ -861,7 +861,7 @@ AtomicString AccessibleNode::relevant() const {
void AccessibleNode::setRelevant(const AtomicString& relevant) {
SetStringProperty(AOMStringProperty::kRelevant, relevant);
- NotifyAttributeChanged(aria_relevantAttr);
+ NotifyAttributeChanged(kAriaRelevantAttr);
}
bool AccessibleNode::required(bool& is_null) const {
@@ -870,7 +870,7 @@ bool AccessibleNode::required(bool& is_null) const {
void AccessibleNode::setRequired(bool required, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kRequired, required, is_null);
- NotifyAttributeChanged(aria_requiredAttr);
+ NotifyAttributeChanged(kAriaRequiredAttr);
}
AtomicString AccessibleNode::role() const {
@@ -879,7 +879,7 @@ AtomicString AccessibleNode::role() const {
void AccessibleNode::setRole(const AtomicString& role) {
SetStringProperty(AOMStringProperty::kRole, role);
- NotifyAttributeChanged(roleAttr);
+ NotifyAttributeChanged(kRoleAttr);
}
AtomicString AccessibleNode::roleDescription() const {
@@ -888,7 +888,7 @@ AtomicString AccessibleNode::roleDescription() const {
void AccessibleNode::setRoleDescription(const AtomicString& role_description) {
SetStringProperty(AOMStringProperty::kRoleDescription, role_description);
- NotifyAttributeChanged(aria_roledescriptionAttr);
+ NotifyAttributeChanged(kAriaRoledescriptionAttr);
}
int32_t AccessibleNode::rowCount(bool& is_null) const {
@@ -897,7 +897,7 @@ int32_t AccessibleNode::rowCount(bool& is_null) const {
void AccessibleNode::setRowCount(int32_t row_count, bool is_null) {
SetIntProperty(AOMIntProperty::kRowCount, row_count, is_null);
- NotifyAttributeChanged(aria_rowcountAttr);
+ NotifyAttributeChanged(kAriaRowcountAttr);
}
uint32_t AccessibleNode::rowIndex(bool& is_null) const {
@@ -906,7 +906,7 @@ uint32_t AccessibleNode::rowIndex(bool& is_null) const {
void AccessibleNode::setRowIndex(uint32_t row_index, bool is_null) {
SetUIntProperty(AOMUIntProperty::kRowIndex, row_index, is_null);
- NotifyAttributeChanged(aria_rowindexAttr);
+ NotifyAttributeChanged(kAriaRowindexAttr);
}
uint32_t AccessibleNode::rowSpan(bool& is_null) const {
@@ -915,7 +915,7 @@ uint32_t AccessibleNode::rowSpan(bool& is_null) const {
void AccessibleNode::setRowSpan(uint32_t row_span, bool is_null) {
SetUIntProperty(AOMUIntProperty::kRowSpan, row_span, is_null);
- NotifyAttributeChanged(aria_rowspanAttr);
+ NotifyAttributeChanged(kAriaRowspanAttr);
}
bool AccessibleNode::selected(bool& is_null) const {
@@ -924,7 +924,7 @@ bool AccessibleNode::selected(bool& is_null) const {
void AccessibleNode::setSelected(bool selected, bool is_null) {
SetBooleanProperty(AOMBooleanProperty::kSelected, selected, is_null);
- NotifyAttributeChanged(aria_selectedAttr);
+ NotifyAttributeChanged(kAriaSelectedAttr);
}
int32_t AccessibleNode::setSize(bool& is_null) const {
@@ -933,7 +933,7 @@ int32_t AccessibleNode::setSize(bool& is_null) const {
void AccessibleNode::setSetSize(int32_t set_size, bool is_null) {
SetIntProperty(AOMIntProperty::kSetSize, set_size, is_null);
- NotifyAttributeChanged(aria_setsizeAttr);
+ NotifyAttributeChanged(kAriaSetsizeAttr);
}
AtomicString AccessibleNode::sort() const {
@@ -942,7 +942,7 @@ AtomicString AccessibleNode::sort() const {
void AccessibleNode::setSort(const AtomicString& sort) {
SetStringProperty(AOMStringProperty::kSort, sort);
- NotifyAttributeChanged(aria_sortAttr);
+ NotifyAttributeChanged(kAriaSortAttr);
}
float AccessibleNode::valueMax(bool& is_null) const {
@@ -951,7 +951,7 @@ float AccessibleNode::valueMax(bool& is_null) const {
void AccessibleNode::setValueMax(float value_max, bool is_null) {
SetFloatProperty(AOMFloatProperty::kValueMax, value_max, is_null);
- NotifyAttributeChanged(aria_valuemaxAttr);
+ NotifyAttributeChanged(kAriaValuemaxAttr);
}
float AccessibleNode::valueMin(bool& is_null) const {
@@ -960,7 +960,7 @@ float AccessibleNode::valueMin(bool& is_null) const {
void AccessibleNode::setValueMin(float value_min, bool is_null) {
SetFloatProperty(AOMFloatProperty::kValueMin, value_min, is_null);
- NotifyAttributeChanged(aria_valueminAttr);
+ NotifyAttributeChanged(kAriaValueminAttr);
}
float AccessibleNode::valueNow(bool& is_null) const {
@@ -969,7 +969,7 @@ float AccessibleNode::valueNow(bool& is_null) const {
void AccessibleNode::setValueNow(float value_now, bool is_null) {
SetFloatProperty(AOMFloatProperty::kValueNow, value_now, is_null);
- NotifyAttributeChanged(aria_valuenowAttr);
+ NotifyAttributeChanged(kAriaValuenowAttr);
}
AtomicString AccessibleNode::valueText() const {
@@ -978,7 +978,7 @@ AtomicString AccessibleNode::valueText() const {
void AccessibleNode::setValueText(const AtomicString& value_text) {
SetStringProperty(AOMStringProperty::kValueText, value_text);
- NotifyAttributeChanged(aria_valuetextAttr);
+ NotifyAttributeChanged(kAriaValuetextAttr);
}
AccessibleNodeList* AccessibleNode::childNodes() {
@@ -1067,7 +1067,7 @@ bool AccessibleNode::IsStringTokenProperty(AOMStringProperty property) {
}
const AtomicString& AccessibleNode::InterfaceName() const {
- return EventTargetNames::AccessibleNode;
+ return event_target_names::kAccessibleNode;
}
ExecutionContext* AccessibleNode::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/core/aom/accessible_node.h b/chromium/third_party/blink/renderer/core/aom/accessible_node.h
index d6161002118..1115c51d634 100644
--- a/chromium/third_party/blink/renderer/core/aom/accessible_node.h
+++ b/chromium/third_party/blink/renderer/core/aom/accessible_node.h
@@ -347,12 +347,14 @@ class CORE_EXPORT AccessibleNode : public EventTargetWithInlineData {
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(accessibleclick);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(accessiblecontextmenu);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(accessibledecrement);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(accessiblefocus);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(accessibleincrement);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(accessiblescrollintoview);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(accessibleclick, kAccessibleclick);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(accessiblecontextmenu,
+ kAccessiblecontextmenu);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(accessibledecrement, kAccessibledecrement);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(accessiblefocus, kAccessiblefocus);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(accessibleincrement, kAccessibleincrement);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(accessiblescrollintoview,
+ kAccessiblescrollintoview);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/aom/computed_accessible_node.cc b/chromium/third_party/blink/renderer/core/aom/computed_accessible_node.cc
index 6c4a97c9f3e..fa71c7ed576 100644
--- a/chromium/third_party/blink/renderer/core/aom/computed_accessible_node.cc
+++ b/chromium/third_party/blink/renderer/core/aom/computed_accessible_node.cc
@@ -77,7 +77,7 @@ void ComputedAccessibleNodePromiseResolver::EnsureUpToDate() {
return;
// TODO(aboxhall): Trigger a call when lifecycle is next at kPrePaintClean.
RequestAnimationFrameCallback* callback =
- new RequestAnimationFrameCallback(this);
+ MakeGarbageCollected<RequestAnimationFrameCallback>(this);
continue_callback_request_id_ =
element_->GetDocument().RequestAnimationFrame(callback);
}
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_object.cc b/chromium/third_party/blink/renderer/core/clipboard/data_object.cc
index 1a096dad2bb..7ee02a7ff66 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_object.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_object.cc
@@ -68,7 +68,7 @@ DataObject* DataObject::CreateFromString(const String& data) {
}
DataObject* DataObject::Create() {
- return new DataObject;
+ return MakeGarbageCollected<DataObject>();
}
DataObject::~DataObject() = default;
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_object.h b/chromium/third_party/blink/renderer/core/clipboard/data_object.h
index 63549f6671a..bcef9644ca4 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_object.h
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_object.h
@@ -68,6 +68,7 @@ class CORE_EXPORT DataObject : public GarbageCollectedFinalized<DataObject>,
static DataObject* Create();
static DataObject* Create(WebDragData);
+ DataObject();
virtual ~DataObject();
// DataTransferItemList support.
@@ -128,8 +129,6 @@ class CORE_EXPORT DataObject : public GarbageCollectedFinalized<DataObject>,
WebDragData ToWebDragData();
private:
- DataObject();
-
DataObjectItem* FindStringItem(const String& type) const;
bool InternalAddStringItem(DataObjectItem*);
void InternalAddFileItem(DataObjectItem*);
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_object_item.cc b/chromium/third_party/blink/renderer/core/clipboard/data_object_item.cc
index aa2ab78e254..9f1bfedbc6f 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_object_item.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_object_item.cc
@@ -41,13 +41,15 @@ namespace blink {
DataObjectItem* DataObjectItem::CreateFromString(const String& type,
const String& data) {
- DataObjectItem* item = new DataObjectItem(kStringKind, type);
+ DataObjectItem* item =
+ MakeGarbageCollected<DataObjectItem>(kStringKind, type);
item->data_ = data;
return item;
}
DataObjectItem* DataObjectItem::CreateFromFile(File* file) {
- DataObjectItem* item = new DataObjectItem(kFileKind, file->type());
+ DataObjectItem* item =
+ MakeGarbageCollected<DataObjectItem>(kFileKind, file->type());
item->file_ = file;
return item;
}
@@ -55,7 +57,8 @@ DataObjectItem* DataObjectItem::CreateFromFile(File* file) {
DataObjectItem* DataObjectItem::CreateFromFileWithFileSystemId(
File* file,
const String& file_system_id) {
- DataObjectItem* item = new DataObjectItem(kFileKind, file->type());
+ DataObjectItem* item =
+ MakeGarbageCollected<DataObjectItem>(kFileKind, file->type());
item->file_ = file;
item->file_system_id_ = file_system_id;
return item;
@@ -63,7 +66,8 @@ DataObjectItem* DataObjectItem::CreateFromFileWithFileSystemId(
DataObjectItem* DataObjectItem::CreateFromURL(const String& url,
const String& title) {
- DataObjectItem* item = new DataObjectItem(kStringKind, kMimeTypeTextURIList);
+ DataObjectItem* item =
+ MakeGarbageCollected<DataObjectItem>(kStringKind, kMimeTypeTextURIList);
item->data_ = url;
item->title_ = title;
return item;
@@ -71,7 +75,8 @@ DataObjectItem* DataObjectItem::CreateFromURL(const String& url,
DataObjectItem* DataObjectItem::CreateFromHTML(const String& html,
const KURL& base_url) {
- DataObjectItem* item = new DataObjectItem(kStringKind, kMimeTypeTextHTML);
+ DataObjectItem* item =
+ MakeGarbageCollected<DataObjectItem>(kStringKind, kMimeTypeTextHTML);
item->data_ = html;
item->base_url_ = base_url;
return item;
@@ -82,7 +87,7 @@ DataObjectItem* DataObjectItem::CreateFromSharedBuffer(
const KURL& source_url,
const String& filename_extension,
const AtomicString& content_disposition) {
- DataObjectItem* item = new DataObjectItem(
+ DataObjectItem* item = MakeGarbageCollected<DataObjectItem>(
kFileKind,
MIMETypeRegistry::GetWellKnownMIMETypeForExtension(filename_extension));
item->shared_buffer_ = std::move(buffer);
@@ -95,9 +100,12 @@ DataObjectItem* DataObjectItem::CreateFromSharedBuffer(
DataObjectItem* DataObjectItem::CreateFromClipboard(const String& type,
uint64_t sequence_number) {
- if (type == kMimeTypeImagePng)
- return new DataObjectItem(kFileKind, type, sequence_number);
- return new DataObjectItem(kStringKind, type, sequence_number);
+ if (type == kMimeTypeImagePng) {
+ return MakeGarbageCollected<DataObjectItem>(kFileKind, type,
+ sequence_number);
+ }
+ return MakeGarbageCollected<DataObjectItem>(kStringKind, type,
+ sequence_number);
}
DataObjectItem::DataObjectItem(ItemKind kind, const String& type)
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_object_item.h b/chromium/third_party/blink/renderer/core/clipboard/data_object_item.h
index 2aab3a232c8..fa2cd048c42 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_object_item.h
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_object_item.h
@@ -64,6 +64,9 @@ class CORE_EXPORT DataObjectItem
static DataObjectItem* CreateFromClipboard(const String& type,
uint64_t sequence_number);
+ DataObjectItem(ItemKind, const String& type);
+ DataObjectItem(ItemKind, const String& type, uint64_t sequence_number);
+
ItemKind Kind() const { return kind_; }
String GetType() const { return type_; }
String GetAsString() const;
@@ -88,9 +91,6 @@ class CORE_EXPORT DataObjectItem
kInternalSource,
};
- DataObjectItem(ItemKind, const String& type);
- DataObjectItem(ItemKind, const String& type, uint64_t sequence_number);
-
DataSource source_;
ItemKind kind_;
String type_;
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_object_test.cc b/chromium/third_party/blink/renderer/core/clipboard/data_object_test.cc
index 64f75a72633..929af5bd607 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_object_test.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_object_test.cc
@@ -33,7 +33,7 @@ class DataObjectObserver : public GarbageCollected<DataObjectObserver>,
};
TEST_F(DataObjectTest, DataObjectObserver) {
- DataObjectObserver* observer = new DataObjectObserver;
+ DataObjectObserver* observer = MakeGarbageCollected<DataObjectObserver>();
data_object_->AddObserver(observer);
data_object_->ClearAll();
@@ -62,7 +62,7 @@ TEST_F(DataObjectTest, DataObjectObserver) {
EXPECT_EQ(1U, data_object_->length());
EXPECT_EQ(3U, observer->call_count());
- DataObjectObserver* observer2 = new DataObjectObserver;
+ DataObjectObserver* observer2 = MakeGarbageCollected<DataObjectObserver>();
data_object_->AddObserver(observer2);
String file_path = test::BlinkRootDir();
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc
index f1e09d62f6e..d020720ebb9 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc
@@ -122,9 +122,9 @@ class DraggedNodeImageBuilder {
.AbsoluteToLocalQuad(FloatQuad(absolute_bounding_box),
kUseTransforms)
.BoundingBox();
- PaintLayerPaintingInfo painting_info(layer, LayoutRect(bounding_box),
- kGlobalPaintFlattenCompositingLayers,
- LayoutSize());
+ PaintLayerPaintingInfo painting_info(
+ layer, CullRect(EnclosingIntRect(bounding_box)),
+ kGlobalPaintFlattenCompositingLayers, LayoutSize());
PaintLayerFlags flags = kPaintLayerHaveTransparency |
kPaintLayerUncachedClipRects;
PaintRecordBuilder builder;
@@ -232,7 +232,7 @@ DataTransfer* DataTransfer::Create() {
DataTransfer* DataTransfer::Create(DataTransferType type,
DataTransferAccessPolicy policy,
DataObject* data_object) {
- return new DataTransfer(type, policy, data_object);
+ return MakeGarbageCollected<DataTransfer>(type, policy, data_object);
}
DataTransfer::~DataTransfer() = default;
@@ -481,7 +481,7 @@ static void WriteImageToDataObject(DataObject* data_object,
data_object->AddSharedBuffer(
image_buffer, image_url, image->FilenameExtension(),
cached_image->GetResponse().HttpHeaderFields().Get(
- HTTPNames::Content_Disposition));
+ http_names::kContentDisposition));
}
void DataTransfer::DeclareAndWriteDragImage(Element* element,
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.h b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.h
index 466f7576653..6cfbb54bc84 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.h
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.h
@@ -71,6 +71,8 @@ class CORE_EXPORT DataTransfer final : public ScriptWrappable,
static DataTransfer* Create(DataTransferType,
DataTransferAccessPolicy,
DataObject*);
+
+ DataTransfer(DataTransferType, DataTransferAccessPolicy, DataObject*);
~DataTransfer() override;
bool IsForCopyAndPaste() const { return transfer_type_ == kCopyAndPaste; }
@@ -157,8 +159,6 @@ class CORE_EXPORT DataTransfer final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
private:
- DataTransfer(DataTransferType, DataTransferAccessPolicy, DataObject*);
-
void setDragImage(ImageResourceContent*, Node*, const IntPoint&);
bool HasFileOfType(const String&) const;
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.cc b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.cc
index 312ef2d9b4d..cd501a02bf5 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.cc
@@ -44,7 +44,7 @@ namespace blink {
DataTransferItem* DataTransferItem::Create(DataTransfer* data_transfer,
DataObjectItem* item) {
- return new DataTransferItem(data_transfer, item);
+ return MakeGarbageCollected<DataTransferItem>(data_transfer, item);
}
String DataTransferItem::kind() const {
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.h b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.h
index 1ed59ecaca2..8bea370632e 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.h
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.h
@@ -52,6 +52,8 @@ class CORE_EXPORT DataTransferItem final : public ScriptWrappable {
public:
static DataTransferItem* Create(DataTransfer*, DataObjectItem*);
+ DataTransferItem(DataTransfer*, DataObjectItem*);
+
String kind() const;
String type() const;
@@ -64,8 +66,6 @@ class CORE_EXPORT DataTransferItem final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- DataTransferItem(DataTransfer*, DataObjectItem*);
-
void RunGetAsStringTask(
ExecutionContext*,
V8PersistentCallbackFunction<V8FunctionStringCallback>*,
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.cc b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.cc
index 6984e0c6f36..601b9fca5e7 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.cc
@@ -35,7 +35,7 @@ namespace blink {
DataTransferItemList* DataTransferItemList::Create(DataTransfer* data_transfer,
DataObject* list) {
- return new DataTransferItemList(data_transfer, list);
+ return MakeGarbageCollected<DataTransferItemList>(data_transfer, list);
}
uint32_t DataTransferItemList::length() const {
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.h b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.h
index 971b9c1fe68..c6e824233ce 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.h
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.h
@@ -51,6 +51,8 @@ class CORE_EXPORT DataTransferItemList final : public ScriptWrappable {
public:
static DataTransferItemList* Create(DataTransfer*, DataObject*);
+ DataTransferItemList(DataTransfer*, DataObject*);
+
uint32_t length() const;
DataTransferItem* item(uint32_t index);
void deleteItem(uint32_t index, ExceptionState&);
@@ -63,8 +65,6 @@ class CORE_EXPORT DataTransferItemList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- DataTransferItemList(DataTransfer*, DataObject*);
-
Member<DataTransfer> data_transfer_;
Member<DataObject> data_object_;
};
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_test.cc b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_test.cc
index d4680cd67d3..70f5749f768 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_test.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_test.cc
@@ -20,9 +20,6 @@ class DataTransferTest : public RenderingTest {
protected:
Page& GetPage() const { return *GetDocument().GetPage(); }
LocalFrame& GetFrame() const { return *GetDocument().GetFrame(); }
- void UpdateAllLifecyclePhases() {
- GetDocument().View()->UpdateAllLifecyclePhases();
- }
};
TEST_F(DataTransferTest, NodeImage) {
@@ -93,7 +90,7 @@ TEST_F(DataTransferTest, NodeImageWithChangingLayoutObject) {
<span id=sample>foo</span>
)HTML");
Element* sample = GetDocument().getElementById("sample");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject* before_layout_object = sample->GetLayoutObject();
const std::unique_ptr<DragImage> image =
DataTransfer::NodeImage(GetFrame(), *sample);
@@ -105,7 +102,7 @@ TEST_F(DataTransferTest, NodeImageWithChangingLayoutObject) {
<< "#sample has :-webkit-drag.";
// Layout w/o :-webkit-drag
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(Color(0, 0, 255),
sample->GetLayoutObject()->ResolveColor(GetCSSPropertyColor()))
diff --git a/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc b/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc
index ac7e91263d3..a39e7856299 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc
@@ -172,18 +172,21 @@ void SystemClipboard::WriteImage(Image* image,
if (bitmap.isNull())
return;
- // Only 32-bit bitmaps are supported.
- DCHECK_EQ(bitmap.colorType(), kN32_SkColorType);
- void* pixels = bitmap.getPixels();
// TODO(piman): this should not be NULL, but it is. crbug.com/369621
- if (!pixels)
+ if (!bitmap.getPixels())
return;
clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap);
if (url.IsValid() && !url.IsEmpty()) {
+#if !defined(OS_MACOSX)
+ // See http://crbug.com/838808: Not writing text/plain on Mac for
+ // consistency between platforms, and to help fix errors in applications
+ // which prefer text/plain content over image content for compatibility with
+ // Microsoft Word.
clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard,
url.GetString(), NonNullString(title));
+#endif
// When writing the image, we also write the image markup so that pasting
// into rich text editors, such as Gmail, reveals the image. We also don't
diff --git a/chromium/third_party/blink/renderer/core/core_idl_files.gni b/chromium/third_party/blink/renderer/core/core_idl_files.gni
index 651f2b07c5f..228aa27c1e6 100644
--- a/chromium/third_party/blink/renderer/core/core_idl_files.gni
+++ b/chromium/third_party/blink/renderer/core/core_idl_files.gni
@@ -49,6 +49,7 @@ core_idl_files =
"clipboard/data_transfer_item_list.idl",
"css/css_condition_rule.idl",
"css/css_font_face_rule.idl",
+ "css/css_font_feature_values_rule.idl",
"css/css_grouping_rule.idl",
"css/css_import_rule.idl",
"css/css_keyframe_rule.idl",
@@ -101,6 +102,7 @@ core_idl_files =
"css/cssom/style_property_map.idl",
"css/cssom/style_property_map_read_only.idl",
"display_lock/display_lock_context.idl",
+ "display_lock/display_lock_suspended_handle.idl",
"dom/abort_controller.idl",
"dom/abort_signal.idl",
"dom/attr.idl",
@@ -265,6 +267,7 @@ core_idl_files =
"html/canvas/image_data.idl",
"html/canvas/text_metrics.idl",
"html/custom/custom_element_registry.idl",
+ "html/custom/element_internals.idl",
"html/forms/form_data.idl",
"html/forms/form_data_event.idl",
"html/forms/html_button_element.idl",
@@ -320,6 +323,9 @@ core_idl_files =
"page/scrolling/scroll_state.idl",
"resize_observer/resize_observer.idl",
"resize_observer/resize_observer_entry.idl",
+ "streams/readable_stream.idl",
+ "streams/transform_stream.idl",
+ "streams/writable_stream.idl",
"streams/underlying_source_base.idl",
"svg/svg_a_element.idl",
"svg/svg_angle.idl",
@@ -454,6 +460,8 @@ core_idl_files =
"typed_arrays/uint8_clamped_array.idl",
"url/url_search_params.idl",
"workers/experimental/task.idl",
+ "workers/experimental/task_worklet.idl",
+ "workers/experimental/task_worklet_global_scope.idl",
"workers/experimental/worker_task_queue.idl",
"workers/shared_worker.idl",
"workers/worker.idl",
@@ -532,13 +540,11 @@ core_dependency_idl_files =
"frame/navigator_language.idl",
"frame/navigator_on_line.idl",
"frame/navigator_user_activation.idl",
- "frame/window_base64.idl",
"frame/window_event_handlers.idl",
- "frame/window_timers.idl",
+ "frame/window_or_worker_global_scope.idl",
"fullscreen/document_fullscreen.idl",
"fullscreen/element_fullscreen.idl",
"html/html_hyperlink_element_utils.idl",
- "imagebitmap/image_bitmap_factories.idl",
"layout/custom/css_layout_worklet.idl",
"svg/svg_document.idl",
"svg/svg_filter_primitive_standard_attributes.idl",
@@ -548,8 +554,8 @@ core_dependency_idl_files =
"svg/svg_zoom_and_pan.idl",
"timing/window_performance.idl",
"timing/worker_global_scope_performance.idl",
- "url/url_utils_read_only.idl",
"workers/abstract_worker.idl",
+ "workers/experimental/window_task_worklet.idl",
"xml/document_xpath_evaluator.idl",
],
"abspath")
@@ -697,9 +703,9 @@ webcore_testing_idl_files =
"testing/dictionary_test.idl",
"testing/gc_observation.idl",
"testing/garbage_collected_script_wrappable.idl",
+ "testing/hit_test_layer_rect.idl",
+ "testing/hit_test_layer_rect_list.idl",
"testing/internal_settings.idl",
- "testing/layer_rect.idl",
- "testing/layer_rect_list.idl",
"testing/origin_trials_test.idl",
"testing/record_test.idl",
"testing/sequence_test.idl",
diff --git a/chromium/third_party/blink/renderer/core/core_initializer.cc b/chromium/third_party/blink/renderer/core/core_initializer.cc
index f2d0f9d597c..4b2cc246b5a 100644
--- a/chromium/third_party/blink/renderer/core/core_initializer.cc
+++ b/chromium/third_party/blink/renderer/core/core_initializer.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/core_initializer.h"
#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/renderer/bindings/core/v8/binding_security.h"
#include "third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h"
#include "third_party/blink/renderer/core/css/media_feature_names.h"
@@ -38,7 +39,7 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/event_target_names.h"
#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/core/events/event_factory.h"
@@ -89,24 +90,20 @@ void CoreInitializer::Initialize() {
// TODO(mikhail.pozdnyakov@intel.com): We should generate static strings
// initialization code.
const unsigned kQualifiedNamesCount =
- HTMLNames::HTMLTagsCount + HTMLNames::HTMLAttrsCount +
- MathMLNames::MathMLTagsCount + MathMLNames::MathMLAttrsCount +
- SVGNames::SVGTagsCount + SVGNames::SVGAttrsCount +
- XLinkNames::XLinkAttrsCount + XMLNSNames::XMLNSAttrsCount +
- XMLNames::XMLAttrsCount;
+ html_names::kTagsCount + html_names::kAttrsCount +
+ mathml_names::kTagsCount + mathml_names::kAttrsCount +
+ svg_names::kTagsCount + svg_names::kAttrsCount +
+ xlink_names::kAttrsCount + xml_names::kAttrsCount +
+ xmlns_names::kAttrsCount;
const unsigned kCoreStaticStringsCount =
- kQualifiedNamesCount + EventNames::EventNamesCount +
- EventTargetNames::EventTargetNamesCount +
- EventTypeNames::EventTypeNamesCount +
- FetchInitiatorTypeNames::FetchInitiatorTypeNamesCount +
- FontFamilyNames::FontFamilyNamesCount +
- HTMLTokenizerNames::HTMLTokenizerNamesCount + HTTPNames::HTTPNamesCount +
- InputModeNames::InputModeNamesCount +
- InputTypeNames::InputTypeNamesCount +
- MediaFeatureNames::MediaFeatureNamesCount +
- MediaTypeNames::MediaTypeNamesCount +
- PerformanceEntryNames::PerformanceEntryNamesCount;
+ kQualifiedNamesCount + event_interface_names::kNamesCount +
+ event_target_names::kNamesCount + event_type_names::kNamesCount +
+ fetch_initiator_type_names::kNamesCount + font_family_names::kNamesCount +
+ html_tokenizer_names::kNamesCount + http_names::kNamesCount +
+ input_mode_names::kNamesCount + input_type_names::kNamesCount +
+ media_feature_names::kNamesCount + media_type_names::kNamesCount +
+ performance_entry_names::kNamesCount;
StringImpl::ReserveStaticStringsCapacityForSize(
kCoreStaticStringsCount + StringImpl::AllStaticStrings().size());
@@ -114,30 +111,30 @@ void CoreInitializer::Initialize() {
AtomicStringTable::Instance().ReserveCapacity(kCoreStaticStringsCount);
- HTMLNames::init();
- SVGNames::init();
- XLinkNames::init();
- MathMLNames::init();
- XMLNSNames::init();
- XMLNames::init();
-
- EventNames::init();
- EventTargetNames::init();
- EventTypeNames::init();
- FetchInitiatorTypeNames::init();
- FontFamilyNames::init();
- HTMLTokenizerNames::init();
- HTTPNames::init();
- InputModeNames::init();
- InputTypeNames::init();
- MediaFeatureNames::init();
- MediaTypeNames::init();
- PerformanceEntryNames::init();
+ html_names::Init();
+ mathml_names::Init();
+ svg_names::Init();
+ xlink_names::Init();
+ xml_names::Init();
+ xmlns_names::Init();
+
+ event_interface_names::Init();
+ event_target_names::Init();
+ event_type_names::Init();
+ fetch_initiator_type_names::Init();
+ font_family_names::Init();
+ html_tokenizer_names::Init();
+ http_names::Init();
+ input_mode_names::Init();
+ input_type_names::Init();
+ media_feature_names::Init();
+ media_type_names::Init();
+ performance_entry_names::Init();
MediaQueryEvaluator::Init();
CSSParserTokenRange::InitStaticEOFToken();
- StyleChangeExtraData::Init();
+ style_change_extra_data::Init();
KURL::Initialize();
SchemeRegistry::Initialize();
@@ -149,6 +146,7 @@ void CoreInitializer::Initialize() {
V8ThrowDOMException::Init();
+ BindingSecurity::Init();
ScriptStreamerThread::Init();
}
diff --git a/chromium/third_party/blink/renderer/core/core_initializer.h b/chromium/third_party/blink/renderer/core/core_initializer.h
index 2737b6bd957..467bb2b2b44 100644
--- a/chromium/third_party/blink/renderer/core/core_initializer.h
+++ b/chromium/third_party/blink/renderer/core/core_initializer.h
@@ -33,16 +33,17 @@
#include "base/macros.h"
#include "services/service_manager/public/cpp/binder_registry.h"
+#include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
+class DevToolsSession;
class Document;
class HTMLMediaElement;
class InspectedFrames;
class InspectorDOMAgent;
-class InspectorSession;
class LocalFrame;
class MediaControls;
class Page;
@@ -93,7 +94,7 @@ class CORE_EXPORT CoreInitializer {
// These methods typically create agents and append them to a session.
// TODO(nverne): remove this and restore to WebDevToolsAgentImpl once that
// class is a controller/ crbug:731490
- virtual void InitInspectorAgentSession(InspectorSession*,
+ virtual void InitInspectorAgentSession(DevToolsSession*,
bool,
InspectorDOMAgent*,
InspectedFrames*,
@@ -115,7 +116,11 @@ class CORE_EXPORT CoreInitializer {
virtual void ProvideModulesToPage(Page&, WebViewClient*) const = 0;
virtual void ForceNextWebGLContextCreationToFail() const = 0;
- virtual void CollectAllGarbageForAnimationWorklet() const = 0;
+ virtual void CollectAllGarbageForAnimationAndPaintWorklet() const = 0;
+
+ virtual void CloneSessionStorage(
+ Page* clone_from_page,
+ const SessionStorageNamespaceId& clone_to_namespace) = 0;
protected:
// CoreInitializer is only instantiated by subclass ModulesInitializer.
diff --git a/chromium/third_party/blink/renderer/core/css/BUILD.gn b/chromium/third_party/blink/renderer/core/css/BUILD.gn
index f67c3131428..fe7c36aa421 100644
--- a/chromium/third_party/blink/renderer/core/css/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/css/BUILD.gn
@@ -58,6 +58,8 @@ blink_core_sources("css") {
"css_font_family_value.h",
"css_font_feature_value.cc",
"css_font_feature_value.h",
+ "css_font_feature_values_rule.cc",
+ "css_font_feature_values_rule.h",
"css_font_selector.cc",
"css_font_selector.h",
"css_font_style_range_value.cc",
@@ -92,6 +94,8 @@ blink_core_sources("css") {
"css_inherited_value.h",
"css_initial_value.cc",
"css_initial_value.h",
+ "css_invalid_variable_value.cc",
+ "css_invalid_variable_value.h",
"css_keyframe_rule.cc",
"css_keyframe_rule.h",
"css_keyframes_rule.cc",
@@ -120,6 +124,8 @@ blink_core_sources("css") {
"css_property_equality.cc",
"css_property_equality.h",
"css_property_id_templates.h",
+ "css_property_name.cc",
+ "css_property_name.h",
"css_property_source_data.cc",
"css_property_source_data.h",
"css_property_value.cc",
@@ -158,6 +164,8 @@ blink_core_sources("css") {
"css_style_sheet.h",
"css_supports_rule.cc",
"css_supports_rule.h",
+ "css_syntax_component.cc",
+ "css_syntax_component.h",
"css_syntax_descriptor.cc",
"css_syntax_descriptor.h",
"css_timing_function_value.cc",
@@ -256,8 +264,9 @@ blink_core_sources("css") {
"cssom/prepopulated_computed_style_property_map.h",
"cssom/style_property_map.cc",
"cssom/style_property_map.h",
- "cssom/style_property_map_read_only.cc",
"cssom/style_property_map_read_only.h",
+ "cssom/style_property_map_read_only_main_thread.cc",
+ "cssom/style_property_map_read_only_main_thread.h",
"cssom/style_value_factory.cc",
"cssom/style_value_factory.h",
"document_style_environment_variables.cc",
@@ -270,6 +279,8 @@ blink_core_sources("css") {
"dom_window_css.h",
"element_rule_collector.cc",
"element_rule_collector.h",
+ "font_display.cc",
+ "font_display.h",
"font_face.cc",
"font_face.h",
"font_face_cache.cc",
@@ -392,6 +403,8 @@ blink_core_sources("css") {
"properties/css_parsing_utils.cc",
"properties/css_parsing_utils.h",
"properties/css_property_base_custom.cc",
+ "properties/css_property_ref.cc",
+ "properties/css_property_ref.h",
"properties/longhand.h",
"properties/longhands/align_content_custom.cc",
"properties/longhands/align_items_custom.cc",
@@ -478,6 +491,8 @@ blink_core_sources("css") {
"properties/longhands/counter_increment_custom.cc",
"properties/longhands/counter_reset_custom.cc",
"properties/longhands/cursor_custom.cc",
+ "properties/longhands/custom_property.cc",
+ "properties/longhands/custom_property.h",
"properties/longhands/cx_custom.cc",
"properties/longhands/cy_custom.cc",
"properties/longhands/d_custom.cc",
diff --git a/chromium/third_party/blink/renderer/core/css/OWNERS b/chromium/third_party/blink/renderer/core/css/OWNERS
index 7d528afeb3b..070536afc22 100644
--- a/chromium/third_party/blink/renderer/core/css/OWNERS
+++ b/chromium/third_party/blink/renderer/core/css/OWNERS
@@ -1,9 +1,6 @@
+alancutter@chromium.org
andruud@chromium.org
ericwilligers@chromium.org
-shend@chromium.org
-
-# Also core owners
-alancutter@chromium.org
futhark@chromium.org
# COMPONENT: Blink>CSS
diff --git a/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.cc b/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.cc
index bae87db1759..2ddf7ae7e00 100644
--- a/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.cc
+++ b/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.cc
@@ -213,7 +213,7 @@ void AbstractPropertySetCSSStyleDeclaration::SetPropertyInternal(
Element* parent = ParentElement();
if (parent) {
parent->GetDocument().GetStyleEngine().AttributeChangedForElement(
- HTMLNames::styleAttr, *parent);
+ html_names::kStyleAttr, *parent);
}
mutation_scope.EnqueueMutationRecord();
}
diff --git a/chromium/third_party/blink/renderer/core/css/active_style_sheets_test.cc b/chromium/third_party/blink/renderer/core/css/active_style_sheets_test.cc
index ce80993fe51..a319ce84d97 100644
--- a/chromium/third_party/blink/renderer/core/css/active_style_sheets_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/active_style_sheets_test.cc
@@ -419,7 +419,7 @@ TEST_F(ActiveStyleSheetsTest, CompareActiveStyleSheets_AddRemoveNonMatchingMQ) {
}
TEST_F(ApplyRulesetsTest, AddUniversalRuleToDocument) {
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
CSSStyleSheet* sheet = CreateSheet("body * { color:red }");
@@ -440,7 +440,7 @@ TEST_F(ApplyRulesetsTest, AddUniversalRuleToShadowTree) {
ShadowRoot& shadow_root =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
CSSStyleSheet* sheet = CreateSheet("body * { color:red }");
@@ -456,7 +456,7 @@ TEST_F(ApplyRulesetsTest, AddUniversalRuleToShadowTree) {
}
TEST_F(ApplyRulesetsTest, AddFontFaceRuleToDocument) {
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
CSSStyleSheet* sheet =
CreateSheet("@font-face { font-family: ahum; src: url(ahum.ttf) }");
@@ -478,7 +478,7 @@ TEST_F(ApplyRulesetsTest, AddFontFaceRuleToShadowTree) {
ShadowRoot& shadow_root =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
CSSStyleSheet* sheet =
CreateSheet("@font-face { font-family: ahum; src: url(ahum.ttf) }");
@@ -505,7 +505,7 @@ TEST_F(ApplyRulesetsTest, RemoveSheetFromShadowTree) {
host->AttachShadowRootInternal(ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString(
"<style>::slotted(#dummy){color:pink}</style>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(GetStyleEngine().TreeBoundaryCrossingScopes().IsEmpty());
ASSERT_EQ(1u, shadow_root.StyleSheets().length());
diff --git a/chromium/third_party/blink/renderer/core/css/affected_by_pseudo_test.cc b/chromium/third_party/blink/renderer/core/css/affected_by_pseudo_test.cc
index 980fec89761..0884a530c0d 100644
--- a/chromium/third_party/blink/renderer/core/css/affected_by_pseudo_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/affected_by_pseudo_test.cc
@@ -16,7 +16,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class AffectedByPseudoTest : public PageTestBase {
protected:
@@ -33,7 +33,7 @@ class AffectedByPseudoTest : public PageTestBase {
void AffectedByPseudoTest::SetHtmlInnerHTML(const char* html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content));
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
void AffectedByPseudoTest::CheckElementsForFocus(
@@ -57,11 +57,11 @@ void AffectedByPseudoTest::CheckElementsForFocus(
// ":focus div" will mark ascendants of all divs with
// childrenOrSiblingsAffectedByFocus.
TEST_F(AffectedByPseudoTest, FocusedAscendant) {
- ElementResult expected[] = {{bodyTag, true},
- {divTag, true},
- {divTag, false},
- {divTag, false},
- {spanTag, false}};
+ ElementResult expected[] = {{kBodyTag, true},
+ {kDivTag, true},
+ {kDivTag, false},
+ {kDivTag, false},
+ {kSpanTag, false}};
SetHtmlInnerHTML(R"HTML(
<head>
@@ -79,11 +79,11 @@ TEST_F(AffectedByPseudoTest, FocusedAscendant) {
// "body:focus div" will mark the body element with
// childrenOrSiblingsAffectedByFocus.
TEST_F(AffectedByPseudoTest, FocusedAscendantWithType) {
- ElementResult expected[] = {{bodyTag, true},
- {divTag, false},
- {divTag, false},
- {divTag, false},
- {spanTag, false}};
+ ElementResult expected[] = {{kBodyTag, true},
+ {kDivTag, false},
+ {kDivTag, false},
+ {kDivTag, false},
+ {kSpanTag, false}};
SetHtmlInnerHTML(R"HTML(
<head>
@@ -104,11 +104,11 @@ TEST_F(AffectedByPseudoTest, FocusedAscendantWithType) {
// is checked and the childrenOrSiblingsAffectedByFocus flag set before the
// negated type selector is found.
TEST_F(AffectedByPseudoTest, FocusedAscendantWithNegatedType) {
- ElementResult expected[] = {{bodyTag, false},
- {divTag, true},
- {divTag, false},
- {divTag, false},
- {spanTag, false}};
+ ElementResult expected[] = {{kBodyTag, false},
+ {kDivTag, true},
+ {kDivTag, false},
+ {kDivTag, false},
+ {kSpanTag, false}};
SetHtmlInnerHTML(R"HTML(
<head>
@@ -131,7 +131,7 @@ TEST_F(AffectedByPseudoTest, FocusedAscendantWithNegatedType) {
// makes sure the sibling also gets its styles recalculated.
TEST_F(AffectedByPseudoTest, FocusedSibling) {
ElementResult expected[] = {
- {bodyTag, false}, {divTag, true}, {spanTag, false}, {divTag, false}};
+ {kBodyTag, false}, {kDivTag, true}, {kSpanTag, false}, {kDivTag, false}};
SetHtmlInnerHTML(R"HTML(
<head>
@@ -168,12 +168,12 @@ TEST_F(AffectedByPseudoTest, AffectedByFocusUpdate) {
</div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned start_count = GetStyleEngine().StyleForElementCount();
GetElementById("d")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned element_count =
GetStyleEngine().StyleForElementCount() - start_count;
@@ -201,12 +201,12 @@ TEST_F(AffectedByPseudoTest, ChildrenOrSiblingsAffectedByFocusUpdate) {
</div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned start_count = GetStyleEngine().StyleForElementCount();
GetElementById("d")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned element_count =
GetStyleEngine().StyleForElementCount() - start_count;
@@ -234,12 +234,12 @@ TEST_F(AffectedByPseudoTest, InvalidationSetFocusUpdate) {
</div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned start_count = GetStyleEngine().StyleForElementCount();
GetElementById("d")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned element_count =
GetStyleEngine().StyleForElementCount() - start_count;
@@ -269,12 +269,12 @@ TEST_F(AffectedByPseudoTest, NoInvalidationSetFocusUpdate) {
</div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned start_count = GetStyleEngine().StyleForElementCount();
GetElementById("d")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned element_count =
GetStyleEngine().StyleForElementCount() - start_count;
@@ -296,12 +296,12 @@ TEST_F(AffectedByPseudoTest, FocusWithinCommonAncestor) {
</div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned start_count = GetStyleEngine().StyleForElementCount();
GetElementById("focusme1")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned element_count =
GetStyleEngine().StyleForElementCount() - start_count;
@@ -311,7 +311,7 @@ TEST_F(AffectedByPseudoTest, FocusWithinCommonAncestor) {
start_count += element_count;
GetElementById("focusme2")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
element_count = GetStyleEngine().StyleForElementCount() - start_count;
@@ -325,7 +325,7 @@ TEST_F(AffectedByPseudoTest, HoverScrollbar) {
"<style>div::-webkit-scrollbar:hover { color: pink; }</style>"
"<div id=div1></div>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetElementById("div1")->GetComputedStyle()->AffectedByHover());
}
diff --git a/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.cc b/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.cc
index 4df98db90f6..58c4a150e98 100644
--- a/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.cc
+++ b/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.cc
@@ -27,6 +27,7 @@
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
#include "third_party/blink/renderer/core/css/css_value.h"
+#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
@@ -36,25 +37,10 @@ const CSSValue* ComputedStyleCSSValueMapping::Get(
const AtomicString custom_property_name,
const ComputedStyle& style,
const PropertyRegistry* registry) {
- if (registry) {
- const PropertyRegistration* registration =
- registry->Registration(custom_property_name);
- if (registration) {
- const CSSValue* result = style.GetRegisteredVariable(
- custom_property_name, registration->Inherits());
- if (result)
- return result;
- return registration->Initial();
- }
- }
-
- bool is_inherited_property = true;
- CSSVariableData* data =
- style.GetVariable(custom_property_name, is_inherited_property);
- if (!data)
- return nullptr;
-
- return CSSCustomPropertyDeclaration::Create(custom_property_name, data);
+ CustomProperty custom_property(custom_property_name, registry);
+ return custom_property.CSSValueFromComputedStyle(
+ style, nullptr /* layout_object */, nullptr /* styled_node */,
+ false /* allow_visited_style */);
}
HeapHashMap<AtomicString, Member<const CSSValue>>
diff --git a/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.h b/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.h
index 5d3d03bcbd6..29103fc597a 100644
--- a/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.h
+++ b/chromium/third_party/blink/renderer/core/css/computed_style_css_value_mapping.h
@@ -17,12 +17,14 @@ class ComputedStyleCSSValueMapping {
STATIC_ONLY(ComputedStyleCSSValueMapping);
public:
- static const CSSValue* Get(const AtomicString custom_property_name,
- const ComputedStyle&,
- const PropertyRegistry*);
static HeapHashMap<AtomicString, Member<const CSSValue>> GetVariables(
const ComputedStyle& style,
const PropertyRegistry*);
+
+ private:
+ static const CSSValue* Get(const AtomicString custom_property_name,
+ const ComputedStyle&,
+ const PropertyRegistry*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/computed_style_field_aliases.json5 b/chromium/third_party/blink/renderer/core/css/computed_style_field_aliases.json5
index cce3321d5a6..cef592a33e0 100644
--- a/chromium/third_party/blink/renderer/core/css/computed_style_field_aliases.json5
+++ b/chromium/third_party/blink/renderer/core/css/computed_style_field_aliases.json5
@@ -8,7 +8,7 @@
"name": "<length>",
"field_template": "external",
"type_name": "Length",
- "include_paths": ["third_party/blink/renderer/platform/length.h"]
+ "include_paths": ["third_party/blink/renderer/platform/geometry/length.h"]
},
{
"name": "<color>",
diff --git a/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.cc b/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.cc
index 28776fe111a..289cd8db99c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.cc
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.h b/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.h
index 4e1e047db77..037514d3f61 100644
--- a/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.h
+++ b/chromium/third_party/blink/renderer/core/css/css_basic_shape_values.h
@@ -44,9 +44,11 @@ namespace cssvalue {
class CSSBasicShapeCircleValue final : public CSSValue {
public:
static CSSBasicShapeCircleValue* Create() {
- return new CSSBasicShapeCircleValue;
+ return MakeGarbageCollected<CSSBasicShapeCircleValue>();
}
+ CSSBasicShapeCircleValue() : CSSValue(kBasicShapeCircleClass) {}
+
String CustomCSSText() const;
bool Equals(const CSSBasicShapeCircleValue&) const;
@@ -62,8 +64,6 @@ class CSSBasicShapeCircleValue final : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSBasicShapeCircleValue() : CSSValue(kBasicShapeCircleClass) {}
-
Member<CSSValue> center_x_;
Member<CSSValue> center_y_;
Member<CSSValue> radius_;
@@ -72,9 +72,11 @@ class CSSBasicShapeCircleValue final : public CSSValue {
class CSSBasicShapeEllipseValue final : public CSSValue {
public:
static CSSBasicShapeEllipseValue* Create() {
- return new CSSBasicShapeEllipseValue;
+ return MakeGarbageCollected<CSSBasicShapeEllipseValue>();
}
+ CSSBasicShapeEllipseValue() : CSSValue(kBasicShapeEllipseClass) {}
+
String CustomCSSText() const;
bool Equals(const CSSBasicShapeEllipseValue&) const;
@@ -92,8 +94,6 @@ class CSSBasicShapeEllipseValue final : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSBasicShapeEllipseValue() : CSSValue(kBasicShapeEllipseClass) {}
-
Member<CSSValue> center_x_;
Member<CSSValue> center_y_;
Member<CSSValue> radius_x_;
@@ -103,9 +103,12 @@ class CSSBasicShapeEllipseValue final : public CSSValue {
class CSSBasicShapePolygonValue final : public CSSValue {
public:
static CSSBasicShapePolygonValue* Create() {
- return new CSSBasicShapePolygonValue;
+ return MakeGarbageCollected<CSSBasicShapePolygonValue>();
}
+ CSSBasicShapePolygonValue()
+ : CSSValue(kBasicShapePolygonClass), wind_rule_(RULE_NONZERO) {}
+
void AppendPoint(CSSPrimitiveValue* x, CSSPrimitiveValue* y) {
values_.push_back(x);
values_.push_back(y);
@@ -127,9 +130,6 @@ class CSSBasicShapePolygonValue final : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSBasicShapePolygonValue()
- : CSSValue(kBasicShapePolygonClass), wind_rule_(RULE_NONZERO) {}
-
HeapVector<Member<CSSPrimitiveValue>> values_;
WindRule wind_rule_;
};
@@ -137,9 +137,11 @@ class CSSBasicShapePolygonValue final : public CSSValue {
class CSSBasicShapeInsetValue final : public CSSValue {
public:
static CSSBasicShapeInsetValue* Create() {
- return new CSSBasicShapeInsetValue;
+ return MakeGarbageCollected<CSSBasicShapeInsetValue>();
}
+ CSSBasicShapeInsetValue() : CSSValue(kBasicShapeInsetClass) {}
+
CSSPrimitiveValue* Top() const { return top_.Get(); }
CSSPrimitiveValue* Right() const { return right_.Get(); }
CSSPrimitiveValue* Bottom() const { return bottom_.Get(); }
@@ -196,8 +198,6 @@ class CSSBasicShapeInsetValue final : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSBasicShapeInsetValue() : CSSValue(kBasicShapeInsetClass) {}
-
Member<CSSPrimitiveValue> top_;
Member<CSSPrimitiveValue> right_;
Member<CSSPrimitiveValue> bottom_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_border_image_slice_value.h b/chromium/third_party/blink/renderer/core/css/css_border_image_slice_value.h
index 2f3f0bae087..c19bb059311 100644
--- a/chromium/third_party/blink/renderer/core/css/css_border_image_slice_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_border_image_slice_value.h
@@ -35,9 +35,11 @@ namespace cssvalue {
class CSSBorderImageSliceValue : public CSSValue {
public:
static CSSBorderImageSliceValue* Create(CSSQuadValue* slices, bool fill) {
- return new CSSBorderImageSliceValue(slices, fill);
+ return MakeGarbageCollected<CSSBorderImageSliceValue>(slices, fill);
}
+ CSSBorderImageSliceValue(CSSQuadValue* slices, bool fill);
+
String CustomCSSText() const;
// TODO(sashab): Change this to a quad of CSSPrimitiveValues, or add separate
@@ -50,8 +52,6 @@ class CSSBorderImageSliceValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSBorderImageSliceValue(CSSQuadValue* slices, bool fill);
-
// These four values are used to make "cuts" in the border image. They can be
// numbers or percentages.
Member<CSSQuadValue> slices_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_calculation_value.cc b/chromium/third_party/blink/renderer/core/css/css_calculation_value.cc
index e785bd05a2b..cac6c210359 100644
--- a/chromium/third_party/blink/renderer/core/css/css_calculation_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_calculation_value.cc
@@ -165,7 +165,7 @@ class CSSCalcPrimitiveValue final : public CSSCalcExpressionNode {
public:
static CSSCalcPrimitiveValue* Create(CSSPrimitiveValue* value,
bool is_integer) {
- return new CSSCalcPrimitiveValue(value, is_integer);
+ return MakeGarbageCollected<CSSCalcPrimitiveValue>(value, is_integer);
}
static CSSCalcPrimitiveValue* Create(double value,
@@ -173,10 +173,15 @@ class CSSCalcPrimitiveValue final : public CSSCalcExpressionNode {
bool is_integer) {
if (std::isnan(value) || std::isinf(value))
return nullptr;
- return new CSSCalcPrimitiveValue(CSSPrimitiveValue::Create(value, type),
- is_integer);
+ return MakeGarbageCollected<CSSCalcPrimitiveValue>(
+ CSSPrimitiveValue::Create(value, type), is_integer);
}
+ CSSCalcPrimitiveValue(CSSPrimitiveValue* value, bool is_integer)
+ : CSSCalcExpressionNode(UnitCategory(value->TypeWithCalcResolved()),
+ is_integer),
+ value_(value) {}
+
bool IsZero() const override { return !value_->GetDoubleValue(); }
String CustomCSSText() const override { return value_->CssText(); }
@@ -278,11 +283,6 @@ class CSSCalcPrimitiveValue final : public CSSCalcExpressionNode {
}
private:
- CSSCalcPrimitiveValue(CSSPrimitiveValue* value, bool is_integer)
- : CSSCalcExpressionNode(UnitCategory(value->TypeWithCalcResolved()),
- is_integer),
- value_(value) {}
-
Member<CSSPrimitiveValue> value_;
};
@@ -375,7 +375,8 @@ class CSSCalcBinaryOperation final : public CSSCalcExpressionNode {
if (new_category == kCalcOther)
return nullptr;
- return new CSSCalcBinaryOperation(left_side, right_side, op, new_category);
+ return MakeGarbageCollected<CSSCalcBinaryOperation>(left_side, right_side,
+ op, new_category);
}
static CSSCalcExpressionNode* CreateSimplified(
@@ -462,6 +463,16 @@ class CSSCalcBinaryOperation final : public CSSCalcExpressionNode {
return Create(left_side, right_side, op);
}
+ CSSCalcBinaryOperation(CSSCalcExpressionNode* left_side,
+ CSSCalcExpressionNode* right_side,
+ CalcOperator op,
+ CalculationCategory category)
+ : CSSCalcExpressionNode(category,
+ IsIntegerResult(left_side, right_side, op)),
+ left_side_(left_side),
+ right_side_(right_side),
+ operator_(op) {}
+
bool IsZero() const override { return !DoubleValue(); }
void AccumulatePixelsAndPercent(
@@ -627,16 +638,6 @@ class CSSCalcBinaryOperation final : public CSSCalcExpressionNode {
}
private:
- CSSCalcBinaryOperation(CSSCalcExpressionNode* left_side,
- CSSCalcExpressionNode* right_side,
- CalcOperator op,
- CalculationCategory category)
- : CSSCalcExpressionNode(category,
- IsIntegerResult(left_side, right_side, op)),
- left_side_(left_side),
- right_side_(right_side),
- operator_(op) {}
-
static CSSCalcExpressionNode* GetNumberSide(
CSSCalcExpressionNode* left_side,
CSSCalcExpressionNode* right_side) {
@@ -837,13 +838,13 @@ CSSCalcExpressionNode* CSSCalcValue::CreateExpressionNode(
CSSCalcExpressionNode* CSSCalcValue::CreateExpressionNode(double pixels,
double percent) {
return CreateExpressionNode(
- CreateExpressionNode(CSSPrimitiveValue::Create(
- pixels, CSSPrimitiveValue::UnitType::kPixels),
- pixels == trunc(pixels)),
CreateExpressionNode(
CSSPrimitiveValue::Create(percent,
CSSPrimitiveValue::UnitType::kPercentage),
percent == trunc(percent)),
+ CreateExpressionNode(CSSPrimitiveValue::Create(
+ pixels, CSSPrimitiveValue::UnitType::kPixels),
+ pixels == trunc(pixels)),
kCalcAdd);
}
@@ -852,12 +853,13 @@ CSSCalcValue* CSSCalcValue::Create(const CSSParserTokenRange& tokens,
CSSCalcExpressionNodeParser parser;
CSSCalcExpressionNode* expression = parser.ParseCalc(tokens);
- return expression ? new CSSCalcValue(expression, range) : nullptr;
+ return expression ? MakeGarbageCollected<CSSCalcValue>(expression, range)
+ : nullptr;
}
CSSCalcValue* CSSCalcValue::Create(CSSCalcExpressionNode* expression,
ValueRange range) {
- return new CSSCalcValue(expression, range);
+ return MakeGarbageCollected<CSSCalcValue>(expression, range);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_calculation_value.h b/chromium/third_party/blink/renderer/core/css/css_calculation_value.h
index 3f53cb637d6..609924e4964 100644
--- a/chromium/third_party/blink/renderer/core/css/css_calculation_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_calculation_value.h
@@ -35,7 +35,7 @@
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
-#include "third_party/blink/renderer/platform/calculation_value.h"
+#include "third_party/blink/renderer/platform/geometry/calculation_value.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -120,6 +120,10 @@ class CORE_EXPORT CSSCalcValue : public GarbageCollected<CSSCalcValue> {
static CSSCalcExpressionNode* CreateExpressionNode(double pixels,
double percent);
+ CSSCalcValue(CSSCalcExpressionNode* expression, ValueRange range)
+ : expression_(expression),
+ non_negative_(range == kValueRangeNonNegative) {}
+
scoped_refptr<CalculationValue> ToCalcValue(
const CSSToLengthConversionData& conversion_data) const {
PixelsAndPercent value(0, 0);
@@ -147,10 +151,6 @@ class CORE_EXPORT CSSCalcValue : public GarbageCollected<CSSCalcValue> {
void Trace(blink::Visitor* visitor) { visitor->Trace(expression_); }
private:
- CSSCalcValue(CSSCalcExpressionNode* expression, ValueRange range)
- : expression_(expression),
- non_negative_(range == kValueRangeNonNegative) {}
-
double ClampToPermittedRange(double) const;
const Member<CSSCalcExpressionNode> expression_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_color_value.cc b/chromium/third_party/blink/renderer/core/css/css_color_value.cc
index 9066791175f..85d833278c4 100644
--- a/chromium/third_party/blink/renderer/core/css/css_color_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_color_value.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/css_value_pool.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
namespace cssvalue {
@@ -22,9 +23,43 @@ CSSColorValue* CSSColorValue::Create(RGBA32 color) {
CSSValuePool::ColorValueCache::AddResult entry =
CssValuePool().GetColorCacheEntry(color);
if (entry.is_new_entry)
- entry.stored_value->value = new CSSColorValue(color);
+ entry.stored_value->value = MakeGarbageCollected<CSSColorValue>(color);
return entry.stored_value->value;
}
+String CSSColorValue::SerializeAsCSSComponentValue(Color color) {
+ StringBuilder result;
+ result.ReserveCapacity(32);
+ bool color_has_alpha = color.HasAlpha();
+ if (color_has_alpha)
+ result.Append("rgba(");
+ else
+ result.Append("rgb(");
+
+ result.AppendNumber(static_cast<unsigned char>(color.Red()));
+ result.Append(", ");
+
+ result.AppendNumber(static_cast<unsigned char>(color.Green()));
+ result.Append(", ");
+
+ result.AppendNumber(static_cast<unsigned char>(color.Blue()));
+ if (color_has_alpha) {
+ result.Append(", ");
+ // See <alphavalue> section in
+ // https://drafts.csswg.org/cssom/#serializing-css-values
+ int alphavalue = color.Alpha();
+ float rounded = round(alphavalue * 100 / 255.0f) / 100;
+ if (round(rounded * 255) == alphavalue) {
+ result.AppendNumber(rounded, 2);
+ } else {
+ rounded = round(alphavalue * 1000 / 255.0f) / 1000;
+ result.AppendNumber(rounded, 3);
+ }
+ }
+
+ result.Append(')');
+ return result.ToString();
+}
+
} // namespace cssvalue
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_color_value.h b/chromium/third_party/blink/renderer/core/css/css_color_value.h
index 56007897b09..a63b22ab3ec 100644
--- a/chromium/third_party/blink/renderer/core/css/css_color_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_color_value.h
@@ -21,9 +21,9 @@ class CSSColorValue : public CSSValue {
// TODO(sashab): Make this create() method take a Color instead.
static CSSColorValue* Create(RGBA32 color);
- String CustomCSSText() const {
- return color_.SerializedAsCSSComponentValue();
- }
+ CSSColorValue(Color color) : CSSValue(kColorClass), color_(color) {}
+
+ String CustomCSSText() const { return SerializeAsCSSComponentValue(color_); }
Color Value() const { return color_; }
@@ -35,11 +35,13 @@ class CSSColorValue : public CSSValue {
CSSValue::TraceAfterDispatch(visitor);
}
+ // Returns the color serialized according to CSSOM:
+ // https://drafts.csswg.org/cssom/#serialize-a-css-component-value
+ static String SerializeAsCSSComponentValue(Color color);
+
private:
friend class ::blink::CSSValuePool;
- CSSColorValue(Color color) : CSSValue(kColorClass), color_(color) {}
-
Color color_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.cc b/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.cc
index 5af1c199552..163d827584a 100644
--- a/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.cc
@@ -29,12 +29,13 @@
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/core/css/css_property_id_templates.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_selector.h"
#include "third_party/blink/renderer/core/css/css_variable_data.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
@@ -182,6 +183,8 @@ CSSValueID CssIdentifierForFontSizeKeyword(int keyword_size) {
void LogUnimplementedPropertyID(const CSSProperty& property) {
DEFINE_STATIC_LOCAL(HashSet<CSSPropertyID>, property_id_set, ());
+ if (property.PropertyID() == CSSPropertyVariable)
+ return;
if (!property_id_set.insert(property.PropertyID()).is_new_entry)
return;
@@ -304,16 +307,8 @@ const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue(
if (!styled_node)
return nullptr;
- styled_node->GetDocument().UpdateStyleAndLayoutTreeForNode(styled_node);
-
- const ComputedStyle* style = ComputeComputedStyle();
- if (!style)
- return nullptr;
- // Don't use styled_node in case it was discarded or replaced in
- // UpdateStyleAndLayoutTreeForNode.
- return ComputedStyleCSSValueMapping::Get(
- custom_property_name, *style,
- StyledNode()->GetDocument().GetPropertyRegistry());
+ CSSPropertyRef ref(custom_property_name, styled_node->GetDocument());
+ return GetPropertyCSSValue(ref.GetProperty());
}
HeapHashMap<AtomicString, Member<const CSSValue>>
diff --git a/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.h b/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.h
index 9e9a46a9611..bc7cfa45f7f 100644
--- a/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.h
@@ -46,11 +46,13 @@ class CORE_EXPORT CSSComputedStyleDeclaration final
Node* node,
bool allow_visited_style = false,
const String& pseudo_element_name = String()) {
- return new CSSComputedStyleDeclaration(node, allow_visited_style,
- pseudo_element_name);
+ return MakeGarbageCollected<CSSComputedStyleDeclaration>(
+ node, allow_visited_style, pseudo_element_name);
}
static const Vector<const CSSProperty*>& ComputableProperties();
+
+ CSSComputedStyleDeclaration(Node*, bool allow_visited_style, const String&);
~CSSComputedStyleDeclaration() override;
String GetPropertyValue(CSSPropertyID) const;
@@ -75,8 +77,6 @@ class CORE_EXPORT CSSComputedStyleDeclaration final
void Trace(blink::Visitor*) override;
private:
- CSSComputedStyleDeclaration(Node*, bool allow_visited_style, const String&);
-
// The styled node is either the node passed into getComputedStyle, or the
// PseudoElement for :before and :after if they exist.
// FIXME: This should be styledElement since in JS getComputedStyle only works
diff --git a/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration_test.cc b/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration_test.cc
index 9b9a9917de4..60651762c50 100644
--- a/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_computed_style_declaration_test.cc
@@ -19,7 +19,7 @@ TEST_F(CSSComputedStyleDeclarationTest, CleanAncestorsNoRecalc) {
<div id=target style='color:green'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetDocument().NeedsLayoutTreeUpdate());
GetDocument().getElementById("dirty")->setAttribute("style", "color:pink");
@@ -48,7 +48,7 @@ TEST_F(CSSComputedStyleDeclarationTest, CleanShadowAncestorsNoRecalc) {
<div id=target style='color:green'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetDocument().NeedsLayoutTreeUpdate());
GetDocument().getElementById("dirty")->setAttribute("style", "color:pink");
@@ -63,4 +63,46 @@ TEST_F(CSSComputedStyleDeclarationTest, CleanShadowAncestorsNoRecalc) {
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
}
+TEST_F(CSSComputedStyleDeclarationTest, NeedsAdjacentStyleRecalc) {
+ GetDocument().body()->SetInnerHTMLFromString(R"HTML(
+ <style>
+ #a + #b { color: green }
+ </style>
+ <div id="container" style="display:none">
+ <span id="a"></span>
+ <span id="b">
+ <span id="c"></span>
+ <span id="d"></span>
+ </span>
+ </div>
+ )HTML");
+
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_FALSE(GetDocument().NeedsLayoutTreeUpdate());
+
+ Element* container = GetDocument().getElementById("container");
+ Element* c_span = GetDocument().getElementById("c");
+ Element* d_span = GetDocument().getElementById("d");
+ d_span->setAttribute("style", "color:pink");
+
+ EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
+ EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdateForNode(*d_span));
+ EXPECT_FALSE(GetDocument().NeedsLayoutTreeUpdateForNode(*c_span));
+ EXPECT_FALSE(GetDocument().NeedsLayoutTreeUpdateForNode(*c_span, true));
+ EXPECT_FALSE(container->NeedsAdjacentStyleRecalc());
+
+ CSSComputedStyleDeclaration* computed =
+ CSSComputedStyleDeclaration::Create(c_span);
+
+ EXPECT_STREQ("rgb(0, 128, 0)",
+ computed->GetPropertyValue(CSSPropertyColor).Utf8().data());
+
+ EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
+ EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdateForNode(*d_span));
+ EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdateForNode(*c_span));
+ EXPECT_FALSE(GetDocument().NeedsLayoutTreeUpdateForNode(*c_span, true));
+ EXPECT_TRUE(container->NeedsAdjacentStyleRecalc());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_content_distribution_value.h b/chromium/third_party/blink/renderer/core/css/css_content_distribution_value.h
index 88165080352..a9da14f1c3c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_content_distribution_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_content_distribution_value.h
@@ -18,8 +18,13 @@ class CSSContentDistributionValue : public CSSValue {
static CSSContentDistributionValue* Create(CSSValueID distribution,
CSSValueID position,
CSSValueID overflow) {
- return new CSSContentDistributionValue(distribution, position, overflow);
+ return MakeGarbageCollected<CSSContentDistributionValue>(
+ distribution, position, overflow);
}
+
+ CSSContentDistributionValue(CSSValueID distribution,
+ CSSValueID position,
+ CSSValueID overflow);
~CSSContentDistributionValue();
CSSValueID Distribution() const { return distribution_; }
@@ -37,10 +42,6 @@ class CSSContentDistributionValue : public CSSValue {
}
private:
- CSSContentDistributionValue(CSSValueID distribution,
- CSSValueID position,
- CSSValueID overflow);
-
CSSValueID distribution_;
CSSValueID position_;
CSSValueID overflow_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_counter_value.h b/chromium/third_party/blink/renderer/core/css/css_counter_value.h
index f7754bdd8df..1cc4f25f232 100644
--- a/chromium/third_party/blink/renderer/core/css/css_counter_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_counter_value.h
@@ -35,9 +35,18 @@ class CSSCounterValue : public CSSValue {
static CSSCounterValue* Create(CSSCustomIdentValue* identifier,
CSSIdentifierValue* list_style,
CSSStringValue* separator) {
- return new CSSCounterValue(identifier, list_style, separator);
+ return MakeGarbageCollected<CSSCounterValue>(identifier, list_style,
+ separator);
}
+ CSSCounterValue(CSSCustomIdentValue* identifier,
+ CSSIdentifierValue* list_style,
+ CSSStringValue* separator)
+ : CSSValue(kCounterClass),
+ identifier_(identifier),
+ list_style_(list_style),
+ separator_(separator) {}
+
String Identifier() const { return identifier_->Value(); }
CSSValueID ListStyle() const { return list_style_->GetValueID(); }
String Separator() const { return separator_->Value(); }
@@ -52,14 +61,6 @@ class CSSCounterValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSCounterValue(CSSCustomIdentValue* identifier,
- CSSIdentifierValue* list_style,
- CSSStringValue* separator)
- : CSSValue(kCounterClass),
- identifier_(identifier),
- list_style_(list_style),
- separator_(separator) {}
-
Member<CSSCustomIdentValue> identifier_; // string
Member<CSSIdentifierValue> list_style_; // ident
Member<CSSStringValue> separator_; // string
diff --git a/chromium/third_party/blink/renderer/core/css/css_crossfade_value.h b/chromium/third_party/blink/renderer/core/css/css_crossfade_value.h
index 1a12acea169..f5d5df37369 100644
--- a/chromium/third_party/blink/renderer/core/css/css_crossfade_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_crossfade_value.h
@@ -47,9 +47,13 @@ class CORE_EXPORT CSSCrossfadeValue final : public CSSImageGeneratorValue {
static CSSCrossfadeValue* Create(CSSValue* from_value,
CSSValue* to_value,
CSSPrimitiveValue* percentage_value) {
- return new CSSCrossfadeValue(from_value, to_value, percentage_value);
+ return MakeGarbageCollected<CSSCrossfadeValue>(from_value, to_value,
+ percentage_value);
}
+ CSSCrossfadeValue(CSSValue* from_value,
+ CSSValue* to_value,
+ CSSPrimitiveValue* percentage_value);
~CSSCrossfadeValue();
String CustomCSSText() const;
@@ -75,10 +79,6 @@ class CORE_EXPORT CSSCrossfadeValue final : public CSSImageGeneratorValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSCrossfadeValue(CSSValue* from_value,
- CSSValue* to_value,
- CSSPrimitiveValue* percentage_value);
-
void Dispose();
class CrossfadeSubimageObserverProxy final : public ImageResourceObserver {
diff --git a/chromium/third_party/blink/renderer/core/css/css_cursor_image_value.h b/chromium/third_party/blink/renderer/core/css/css_cursor_image_value.h
index ea7e0ccb820..affb948e2dc 100644
--- a/chromium/third_party/blink/renderer/core/css/css_cursor_image_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_cursor_image_value.h
@@ -33,9 +33,13 @@ class CSSCursorImageValue : public CSSValue {
static const CSSCursorImageValue* Create(const CSSValue& image_value,
bool hot_spot_specified,
const IntPoint& hot_spot) {
- return new CSSCursorImageValue(image_value, hot_spot_specified, hot_spot);
+ return MakeGarbageCollected<CSSCursorImageValue>(
+ image_value, hot_spot_specified, hot_spot);
}
+ CSSCursorImageValue(const CSSValue& image_value,
+ bool hot_spot_specified,
+ const IntPoint& hot_spot);
~CSSCursorImageValue();
bool HotSpotSpecified() const { return hot_spot_specified_; }
@@ -49,10 +53,6 @@ class CSSCursorImageValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSCursorImageValue(const CSSValue& image_value,
- bool hot_spot_specified,
- const IntPoint& hot_spot);
-
Member<const CSSValue> image_value_;
IntPoint hot_spot_;
bool hot_spot_specified_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_custom_ident_value.h b/chromium/third_party/blink/renderer/core/css/css_custom_ident_value.h
index dd2cef19419..12800f70824 100644
--- a/chromium/third_party/blink/renderer/core/css/css_custom_ident_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_custom_ident_value.h
@@ -5,8 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_CUSTOM_IDENT_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_CUSTOM_IDENT_VALUE_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
@@ -14,15 +14,18 @@ namespace blink {
class CORE_EXPORT CSSCustomIdentValue : public CSSValue {
public:
static CSSCustomIdentValue* Create(const AtomicString& str) {
- return new CSSCustomIdentValue(str);
+ return MakeGarbageCollected<CSSCustomIdentValue>(str);
}
// TODO(sashab, timloh): Remove this and lazily parse the CSSPropertyID in
// isKnownPropertyID().
static CSSCustomIdentValue* Create(CSSPropertyID id) {
- return new CSSCustomIdentValue(id);
+ return MakeGarbageCollected<CSSCustomIdentValue>(id);
}
+ explicit CSSCustomIdentValue(const AtomicString&);
+ explicit CSSCustomIdentValue(CSSPropertyID);
+
AtomicString Value() const {
DCHECK(!IsKnownPropertyID());
return string_;
@@ -43,9 +46,6 @@ class CORE_EXPORT CSSCustomIdentValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- explicit CSSCustomIdentValue(const AtomicString&);
- explicit CSSCustomIdentValue(CSSPropertyID);
-
AtomicString string_;
CSSPropertyID property_id_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_custom_property_declaration.h b/chromium/third_party/blink/renderer/core/css/css_custom_property_declaration.h
index 32d5722cc46..c81b2d1ddd0 100644
--- a/chromium/third_party/blink/renderer/core/css/css_custom_property_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/css_custom_property_declaration.h
@@ -17,14 +17,31 @@ class CORE_EXPORT CSSCustomPropertyDeclaration : public CSSValue {
static CSSCustomPropertyDeclaration* Create(
const AtomicString& name,
scoped_refptr<CSSVariableData> value) {
- return new CSSCustomPropertyDeclaration(name, std::move(value));
+ return MakeGarbageCollected<CSSCustomPropertyDeclaration>(name,
+ std::move(value));
}
static CSSCustomPropertyDeclaration* Create(const AtomicString& name,
CSSValueID id) {
- return new CSSCustomPropertyDeclaration(name, id);
+ return MakeGarbageCollected<CSSCustomPropertyDeclaration>(name, id);
}
+ CSSCustomPropertyDeclaration(const AtomicString& name, CSSValueID id)
+ : CSSValue(kCustomPropertyDeclarationClass),
+ name_(name),
+ value_(nullptr),
+ value_id_(id) {
+ DCHECK(id == CSSValueInherit || id == CSSValueInitial ||
+ id == CSSValueUnset);
+ }
+
+ CSSCustomPropertyDeclaration(const AtomicString& name,
+ scoped_refptr<CSSVariableData> value)
+ : CSSValue(kCustomPropertyDeclarationClass),
+ name_(name),
+ value_(std::move(value)),
+ value_id_(CSSValueInvalid) {}
+
const AtomicString& GetName() const { return name_; }
CSSVariableData* Value() const { return value_.get(); }
@@ -46,22 +63,6 @@ class CORE_EXPORT CSSCustomPropertyDeclaration : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSCustomPropertyDeclaration(const AtomicString& name, CSSValueID id)
- : CSSValue(kCustomPropertyDeclarationClass),
- name_(name),
- value_(nullptr),
- value_id_(id) {
- DCHECK(id == CSSValueInherit || id == CSSValueInitial ||
- id == CSSValueUnset);
- }
-
- CSSCustomPropertyDeclaration(const AtomicString& name,
- scoped_refptr<CSSVariableData> value)
- : CSSValue(kCustomPropertyDeclarationClass),
- name_(name),
- value_(std::move(value)),
- value_id_(CSSValueInvalid) {}
-
const AtomicString name_;
scoped_refptr<CSSVariableData> value_;
CSSValueID value_id_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.cc b/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.cc
index 8e34a4c54e6..07a7419077b 100644
--- a/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.cc
@@ -43,8 +43,6 @@
namespace blink {
-using namespace HTMLNames;
-
CSSDefaultStyleSheets& CSSDefaultStyleSheets::Instance() {
DEFINE_STATIC_LOCAL(Persistent<CSSDefaultStyleSheets>,
css_default_style_sheets, (new CSSDefaultStyleSheets));
@@ -53,13 +51,13 @@ CSSDefaultStyleSheets& CSSDefaultStyleSheets::Instance() {
static const MediaQueryEvaluator& ScreenEval() {
DEFINE_STATIC_LOCAL(Persistent<MediaQueryEvaluator>, static_screen_eval,
- (new MediaQueryEvaluator("screen")));
+ (MakeGarbageCollected<MediaQueryEvaluator>("screen")));
return *static_screen_eval;
}
static const MediaQueryEvaluator& PrintEval() {
DEFINE_STATIC_LOCAL(Persistent<MediaQueryEvaluator>, static_print_eval,
- (new MediaQueryEvaluator("print")));
+ (MakeGarbageCollected<MediaQueryEvaluator>("print")));
return *static_print_eval;
}
@@ -173,7 +171,7 @@ bool CSSDefaultStyleSheets::EnsureDefaultStyleSheetsForElement(
}
// FIXME: We should assert that the sheet only styles MathML elements.
- if (element.namespaceURI() == MathMLNames::mathmlNamespaceURI &&
+ if (element.namespaceURI() == mathml_names::kNamespaceURI &&
!mathml_style_sheet_) {
mathml_style_sheet_ =
ParseUASheet(GetDataResourceAsASCIIString("mathml.css"));
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face.cc b/chromium/third_party/blink/renderer/core/css/css_font_face.cc
index 9ef4032fcf4..397dfeb7d69 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face.cc
@@ -205,14 +205,11 @@ void CSSFontFace::SetLoadStatus(FontFace::LoadStatusType new_status) {
if (!segmented_font_face_ || !font_face_->GetExecutionContext())
return;
- if (Document* document =
- DynamicTo<Document>(font_face_->GetExecutionContext())) {
+ if (auto* document = DynamicTo<Document>(font_face_->GetExecutionContext())) {
if (new_status == FontFace::kLoading)
FontFaceSetDocument::From(*document)->BeginFontLoading(font_face_);
- }
- if (font_face_->GetExecutionContext()->IsWorkerGlobalScope()) {
- WorkerGlobalScope* scope =
- ToWorkerGlobalScope(font_face_->GetExecutionContext());
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(
+ font_face_->GetExecutionContext())) {
if (new_status == FontFace::kLoading)
FontFaceSetWorker::From(*scope)->BeginFontLoading(font_face_);
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face_rule.h b/chromium/third_party/blink/renderer/core/css/css_font_face_rule.h
index 3e37da4ac89..f7412603f14 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face_rule.h
@@ -37,9 +37,10 @@ class CSSFontFaceRule final : public CSSRule {
public:
static CSSFontFaceRule* Create(StyleRuleFontFace* rule,
CSSStyleSheet* sheet) {
- return new CSSFontFaceRule(rule, sheet);
+ return MakeGarbageCollected<CSSFontFaceRule>(rule, sheet);
}
+ CSSFontFaceRule(StyleRuleFontFace*, CSSStyleSheet* parent);
~CSSFontFaceRule() override;
String cssText() const override;
@@ -52,8 +53,6 @@ class CSSFontFaceRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSFontFaceRule(StyleRuleFontFace*, CSSStyleSheet* parent);
-
CSSRule::Type type() const override { return kFontFaceRule; }
Member<StyleRuleFontFace> font_face_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face_rule.idl b/chromium/third_party/blink/renderer/core/css/css_font_face_rule.idl
index 5b9cddb7502..2e2a7530a30 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face_rule.idl
@@ -18,14 +18,7 @@
* Boston, MA 02110-1301, USA.
*/
-// The CSSFontFaceRule interface was introduced in DOM Level 2 Style, but has
-// been replaced by an entirely different interface in CSS Fonts:
-// https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSFontFaceRule
// https://drafts.csswg.org/css-fonts/#om-fontface
-//
-// TODO(foolip): Make CSSFontFaceRule match new spec and/or change spec to match
-// what's implemented. https://crbug.com/709013
-// https://github.com/w3c/csswg-drafts/issues/825
interface CSSFontFaceRule : CSSRule {
[Measure] readonly attribute CSSStyleDeclaration style;
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face_source.h b/chromium/third_party/blink/renderer/core/css/css_font_face_source.h
index 683b223fc32..cfb07ee67df 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face_source.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face_source.h
@@ -28,6 +28,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/font_display.h"
#include "third_party/blink/renderer/platform/fonts/font_cache_key.h"
#include "third_party/blink/renderer/platform/fonts/font_selection_types.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -40,15 +41,6 @@ namespace blink {
class FontDescription;
class SimpleFontData;
-enum FontDisplay {
- kFontDisplayAuto,
- kFontDisplayBlock,
- kFontDisplaySwap,
- kFontDisplayFallback,
- kFontDisplayOptional,
- kFontDisplayEnumMax
-};
-
class CORE_EXPORT CSSFontFaceSource
: public GarbageCollectedFinalized<CSSFontFaceSource> {
public:
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.cc b/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.cc
index c8b5f4fd0fe..c1843a36109 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.cc
@@ -86,7 +86,7 @@ FontResource& CSSFontFaceSrcValue::Fetch(ExecutionContext* context,
resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer(
referrer_.referrer_policy, resource_request.Url(), referrer_.referrer));
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::css;
+ options.initiator_info.name = fetch_initiator_type_names::kCSS;
FetchParameters params(resource_request, options);
if (RuntimeEnabledFeatures::WebFontsCacheAwareTimeoutAdaptationEnabled())
params.SetCacheAwareLoadingEnabled(kIsCacheAwareLoadingEnabled);
@@ -101,8 +101,8 @@ FontResource& CSSFontFaceSrcValue::Fetch(ExecutionContext* context,
}
// For Workers, Fetcher is lazily loaded, so we must ensure it's available
// here.
- if (context->IsWorkerGlobalScope()) {
- ToWorkerGlobalScope(context)->EnsureFetcher();
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(context)) {
+ scope->EnsureFetcher();
}
fetched_ = FontResourceHelper::Create(
FontResource::Fetch(params, context->Fetcher(), client),
@@ -131,7 +131,7 @@ void CSSFontFaceSrcValue::RestoreCachedResourceIfNeeded(
fetched_->GetResource()->Options().content_security_policy_option);
context->Fetcher()->EmulateLoadStartedForInspector(
fetched_->GetResource(), KURL(resource_url),
- mojom::RequestContextType::FONT, FetchInitiatorTypeNames::css);
+ mojom::RequestContextType::FONT, fetch_initiator_type_names::kCSS);
}
bool CSSFontFaceSrcValue::Equals(const CSSFontFaceSrcValue& other) const {
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.h b/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.h
index 6b36900d575..e850ea379f1 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face_src_value.h
@@ -43,18 +43,32 @@ class CORE_EXPORT CSSFontFaceSrcValue : public CSSValue {
const String& absolute_resource,
const Referrer& referrer,
ContentSecurityPolicyDisposition should_check_content_security_policy) {
- return new CSSFontFaceSrcValue(specified_resource, absolute_resource,
- referrer, false,
- should_check_content_security_policy);
+ return MakeGarbageCollected<CSSFontFaceSrcValue>(
+ specified_resource, absolute_resource, referrer, false,
+ should_check_content_security_policy);
}
static CSSFontFaceSrcValue* CreateLocal(
const String& absolute_resource,
ContentSecurityPolicyDisposition should_check_content_security_policy) {
- return new CSSFontFaceSrcValue(g_empty_string, absolute_resource,
- Referrer(), true,
- should_check_content_security_policy);
+ return MakeGarbageCollected<CSSFontFaceSrcValue>(
+ g_empty_string, absolute_resource, Referrer(), true,
+ should_check_content_security_policy);
}
+ CSSFontFaceSrcValue(
+ const String& specified_resource,
+ const String& absolute_resource,
+ const Referrer& referrer,
+ bool local,
+ ContentSecurityPolicyDisposition should_check_content_security_policy)
+ : CSSValue(kFontFaceSrcClass),
+ absolute_resource_(absolute_resource),
+ specified_resource_(specified_resource),
+ referrer_(referrer),
+ is_local_(local),
+ should_check_content_security_policy_(
+ should_check_content_security_policy) {}
+
const String& GetResource() const { return absolute_resource_; }
const String& Format() const { return format_; }
bool IsLocal() const { return is_local_; }
@@ -77,20 +91,6 @@ class CORE_EXPORT CSSFontFaceSrcValue : public CSSValue {
}
private:
- CSSFontFaceSrcValue(
- const String& specified_resource,
- const String& absolute_resource,
- const Referrer& referrer,
- bool local,
- ContentSecurityPolicyDisposition should_check_content_security_policy)
- : CSSValue(kFontFaceSrcClass),
- absolute_resource_(absolute_resource),
- specified_resource_(specified_resource),
- referrer_(referrer),
- is_local_(local),
- should_check_content_security_policy_(
- should_check_content_security_policy) {}
-
void RestoreCachedResourceIfNeeded(ExecutionContext*) const;
String absolute_resource_;
@@ -109,19 +109,19 @@ class CORE_EXPORT CSSFontFaceSrcValue : public CSSValue {
static FontResourceHelper* Create(
FontResource* resource,
base::SingleThreadTaskRunner* task_runner) {
- return new FontResourceHelper(resource, task_runner);
+ return MakeGarbageCollected<FontResourceHelper>(resource, task_runner);
}
- void Trace(blink::Visitor* visitor) override {
- FontResourceClient::Trace(visitor);
- }
-
- private:
FontResourceHelper(FontResource* resource,
base::SingleThreadTaskRunner* task_runner) {
SetResource(resource, task_runner);
}
+ void Trace(blink::Visitor* visitor) override {
+ FontResourceClient::Trace(visitor);
+ }
+
+ private:
String DebugName() const override {
return "CSSFontFaceSrcValue::FontResourceHelper";
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_family_value.cc b/chromium/third_party/blink/renderer/core/css/css_font_family_value.cc
index 9420fbe6733..99e4f96e486 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_family_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_font_family_value.cc
@@ -12,11 +12,13 @@ namespace blink {
CSSFontFamilyValue* CSSFontFamilyValue::Create(const String& family_name) {
if (family_name.IsNull())
- return new CSSFontFamilyValue(family_name);
+ return MakeGarbageCollected<CSSFontFamilyValue>(family_name);
CSSValuePool::FontFamilyValueCache::AddResult entry =
CssValuePool().GetFontFamilyCacheEntry(family_name);
- if (!entry.stored_value->value)
- entry.stored_value->value = new CSSFontFamilyValue(family_name);
+ if (!entry.stored_value->value) {
+ entry.stored_value->value =
+ MakeGarbageCollected<CSSFontFamilyValue>(family_name);
+ }
return entry.stored_value->value;
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_family_value.h b/chromium/third_party/blink/renderer/core/css/css_font_family_value.h
index ffe15d414df..4ed587dba2a 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_family_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_family_value.h
@@ -14,6 +14,8 @@ class CORE_EXPORT CSSFontFamilyValue : public CSSValue {
public:
static CSSFontFamilyValue* Create(const String& family_name);
+ CSSFontFamilyValue(const String&);
+
String Value() const { return string_; }
String CustomCSSText() const;
@@ -27,8 +29,6 @@ class CORE_EXPORT CSSFontFamilyValue : public CSSValue {
private:
friend class CSSValuePool;
- CSSFontFamilyValue(const String&);
-
// TODO(sashab): Change this to an AtomicString.
String string_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_feature_value.h b/chromium/third_party/blink/renderer/core/css/css_font_feature_value.h
index c9138b5c1c7..e9c07bd60e0 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_feature_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_feature_value.h
@@ -34,9 +34,11 @@ namespace cssvalue {
class CSSFontFeatureValue : public CSSValue {
public:
static CSSFontFeatureValue* Create(const AtomicString& tag, int value) {
- return new CSSFontFeatureValue(tag, value);
+ return MakeGarbageCollected<CSSFontFeatureValue>(tag, value);
}
+ CSSFontFeatureValue(const AtomicString& tag, int value);
+
const AtomicString& Tag() const { return tag_; }
int Value() const { return value_; }
String CustomCSSText() const;
@@ -48,8 +50,6 @@ class CSSFontFeatureValue : public CSSValue {
}
private:
- CSSFontFeatureValue(const AtomicString& tag, int value);
-
AtomicString tag_;
const int value_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc b/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc
new file mode 100644
index 00000000000..629a9dc3ba4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc
@@ -0,0 +1,61 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_font_feature_values_rule.h"
+
+#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_value_list.h"
+#include "third_party/blink/renderer/core/css/style_rule.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+namespace blink {
+
+CSSFontFeatureValuesRule::CSSFontFeatureValuesRule(
+ StyleRuleFontFeatureValues* font_feature_values_rule,
+ CSSStyleSheet* parent)
+ : CSSRule(parent), font_feature_values_rule_(font_feature_values_rule) {}
+
+CSSFontFeatureValuesRule::~CSSFontFeatureValuesRule() = default;
+
+void CSSFontFeatureValuesRule::setFontFamily(const String& font_family) {}
+
+String CSSFontFeatureValuesRule::fontFamily() {
+ return font_feature_values_rule_->FontFamily().CssText();
+}
+
+void CSSFontFeatureValuesRule::setFontDisplay(const String& font_display) {}
+
+String CSSFontFeatureValuesRule::fontDisplay() {
+ if (font_feature_values_rule_->FontDisplay())
+ return font_feature_values_rule_->FontDisplay()->CssText();
+ return "";
+}
+
+String CSSFontFeatureValuesRule::cssText() const {
+ StringBuilder result;
+ result.Append("@font-feature-values ");
+ DCHECK(font_feature_values_rule_);
+ result.Append(font_feature_values_rule_->FontFamily().CssText());
+ result.Append(" { ");
+ if (const CSSIdentifierValue* display =
+ font_feature_values_rule_->FontDisplay()) {
+ result.Append("{ font-display: ");
+ result.Append(display->CssText());
+ result.Append("; } ");
+ }
+ result.Append("}");
+ return result.ToString();
+}
+
+void CSSFontFeatureValuesRule::Reattach(StyleRuleBase* rule) {
+ DCHECK(rule);
+ font_feature_values_rule_ = ToStyleRuleFontFeatureValues(rule);
+}
+
+void CSSFontFeatureValuesRule::Trace(blink::Visitor* visitor) {
+ visitor->Trace(font_feature_values_rule_);
+ CSSRule::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.h b/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.h
new file mode 100644
index 00000000000..a70caec1ee7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.h
@@ -0,0 +1,52 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FEATURE_VALUES_RULE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FEATURE_VALUES_RULE_H_
+
+#include "third_party/blink/renderer/core/css/css_rule.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+
+namespace blink {
+
+class StyleRuleFontFeatureValues;
+
+class CSSFontFeatureValuesRule final : public CSSRule {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ static CSSFontFeatureValuesRule* Create(StyleRuleFontFeatureValues* rule,
+ CSSStyleSheet* sheet) {
+ return new CSSFontFeatureValuesRule(rule, sheet);
+ }
+
+ ~CSSFontFeatureValuesRule() override;
+
+ void setFontFamily(const String& font_family);
+ String fontFamily();
+ void setFontDisplay(const String& font_display);
+ String fontDisplay();
+
+ String cssText() const override;
+ void Reattach(StyleRuleBase*) override;
+
+ StyleRuleFontFeatureValues* StyleRule() const {
+ return font_feature_values_rule_.Get();
+ }
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ CSSFontFeatureValuesRule(StyleRuleFontFeatureValues*, CSSStyleSheet* parent);
+
+ CSSRule::Type type() const override { return kFontFeatureValuesRule; }
+
+ Member<StyleRuleFontFeatureValues> font_feature_values_rule_;
+};
+
+DEFINE_CSS_RULE_TYPE_CASTS(CSSFontFeatureValuesRule, kFontFeatureValuesRule);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FEATURE_VALUES_RULE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl b/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl
new file mode 100644
index 00000000000..e65dd40ea22
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl
@@ -0,0 +1,12 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=CSSFontFeatureValues
+] interface CSSFontFeatureValuesRule : CSSRule {
+ attribute CSSOMString fontFamily;
+
+ // fontDisplay is not reflected in CSSOM according to the current draft.
+ attribute CSSOMString fontDisplay;
+};
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_selector.h b/chromium/third_party/blink/renderer/core/css/css_font_selector.h
index e15f782aac2..b39f1389c30 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_selector.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_selector.h
@@ -43,8 +43,10 @@ class FontDescription;
class CORE_EXPORT CSSFontSelector : public FontSelector {
public:
static CSSFontSelector* Create(Document* document) {
- return new CSSFontSelector(document);
+ return MakeGarbageCollected<CSSFontSelector>(document);
}
+
+ explicit CSSFontSelector(Document*);
~CSSFontSelector() override;
unsigned Version() const override { return font_face_cache_.Version(); }
@@ -81,8 +83,6 @@ class CORE_EXPORT CSSFontSelector : public FontSelector {
void Trace(blink::Visitor*) override;
protected:
- explicit CSSFontSelector(Document*);
-
void DispatchInvalidationCallbacks();
private:
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_style_range_value.h b/chromium/third_party/blink/renderer/core/css/css_font_style_range_value.h
index 6e64b2724eb..7330a1bf490 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_style_range_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_style_range_value.h
@@ -36,14 +36,26 @@ class CSSFontStyleRangeValue final : public CSSValue {
public:
static CSSFontStyleRangeValue* Create(
const CSSIdentifierValue& font_style_value) {
- return new CSSFontStyleRangeValue(font_style_value);
+ return MakeGarbageCollected<CSSFontStyleRangeValue>(font_style_value);
}
static CSSFontStyleRangeValue* Create(
const CSSIdentifierValue& font_style_value,
const CSSValueList& oblique_values) {
- return new CSSFontStyleRangeValue(font_style_value, oblique_values);
+ return MakeGarbageCollected<CSSFontStyleRangeValue>(font_style_value,
+ oblique_values);
}
+ CSSFontStyleRangeValue(const CSSIdentifierValue& font_style_value,
+ const CSSValueList& oblique_values)
+ : CSSValue(kFontStyleRangeClass),
+ font_style_value_(&font_style_value),
+ oblique_values_(&oblique_values) {}
+
+ CSSFontStyleRangeValue(const CSSIdentifierValue& font_style_value)
+ : CSSValue(kFontStyleRangeClass),
+ font_style_value_(&font_style_value),
+ oblique_values_(nullptr) {}
+
const CSSIdentifierValue* GetFontStyleValue() const {
return font_style_value_.Get();
}
@@ -56,17 +68,6 @@ class CSSFontStyleRangeValue final : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSFontStyleRangeValue(const CSSIdentifierValue& font_style_value,
- const CSSValueList& oblique_values)
- : CSSValue(kFontStyleRangeClass),
- font_style_value_(&font_style_value),
- oblique_values_(&oblique_values) {}
-
- CSSFontStyleRangeValue(const CSSIdentifierValue& font_style_value)
- : CSSValue(kFontStyleRangeClass),
- font_style_value_(&font_style_value),
- oblique_values_(nullptr) {}
-
Member<const CSSIdentifierValue> font_style_value_;
Member<const CSSValueList> oblique_values_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_variation_value.h b/chromium/third_party/blink/renderer/core/css/css_font_variation_value.h
index 4a2afd76c1f..6f08ebc5df6 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_variation_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_font_variation_value.h
@@ -14,9 +14,11 @@ namespace cssvalue {
class CSSFontVariationValue : public CSSValue {
public:
static CSSFontVariationValue* Create(const AtomicString& tag, float value) {
- return new CSSFontVariationValue(tag, value);
+ return MakeGarbageCollected<CSSFontVariationValue>(tag, value);
}
+ CSSFontVariationValue(const AtomicString& tag, float value);
+
const AtomicString& Tag() const { return tag_; }
float Value() const { return value_; }
String CustomCSSText() const;
@@ -28,8 +30,6 @@ class CSSFontVariationValue : public CSSValue {
}
private:
- CSSFontVariationValue(const AtomicString& tag, float value);
-
AtomicString tag_;
const float value_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_function_value.h b/chromium/third_party/blink/renderer/core/css/css_function_value.h
index 14fde898b0e..ffc0cbbd8d2 100644
--- a/chromium/third_party/blink/renderer/core/css/css_function_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_function_value.h
@@ -13,9 +13,12 @@ namespace blink {
class CSSFunctionValue : public CSSValueList {
public:
static CSSFunctionValue* Create(CSSValueID id) {
- return new CSSFunctionValue(id);
+ return MakeGarbageCollected<CSSFunctionValue>(id);
}
+ CSSFunctionValue(CSSValueID id)
+ : CSSValueList(kFunctionClass, kCommaSeparator), value_id_(id) {}
+
String CustomCSSText() const;
bool Equals(const CSSFunctionValue& other) const {
@@ -28,9 +31,6 @@ class CSSFunctionValue : public CSSValueList {
}
private:
- CSSFunctionValue(CSSValueID id)
- : CSSValueList(kFunctionClass, kCommaSeparator), value_id_(id) {}
-
const CSSValueID value_id_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_global_rule_set.h b/chromium/third_party/blink/renderer/core/css/css_global_rule_set.h
index d0f2e160c86..61d5dc8ddfe 100644
--- a/chromium/third_party/blink/renderer/core/css/css_global_rule_set.h
+++ b/chromium/third_party/blink/renderer/core/css/css_global_rule_set.h
@@ -24,7 +24,11 @@ class RuleSet;
class CSSGlobalRuleSet : public GarbageCollectedFinalized<CSSGlobalRuleSet> {
public:
- static CSSGlobalRuleSet* Create() { return new CSSGlobalRuleSet(); }
+ static CSSGlobalRuleSet* Create() {
+ return MakeGarbageCollected<CSSGlobalRuleSet>();
+ }
+
+ CSSGlobalRuleSet() = default;
void Dispose();
void InitWatchedSelectorsRuleSet(Document&);
@@ -44,7 +48,6 @@ class CSSGlobalRuleSet : public GarbageCollectedFinalized<CSSGlobalRuleSet> {
void Trace(blink::Visitor*);
private:
- CSSGlobalRuleSet() = default;
// Constructed from rules in all TreeScopes including UA style and style
// injected from extensions.
RuleFeatureSet features_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_gradient_value.h b/chromium/third_party/blink/renderer/core/css/css_gradient_value.h
index b110024bfa5..76807dd7dc3 100644
--- a/chromium/third_party/blink/renderer/core/css/css_gradient_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_gradient_value.h
@@ -162,23 +162,10 @@ class CSSLinearGradientValue final : public CSSGradientValue {
const CSSPrimitiveValue* angle,
CSSGradientRepeat repeat,
CSSGradientType gradient_type = kCSSLinearGradient) {
- return new CSSLinearGradientValue(first_x, first_y, second_x, second_y,
- angle, repeat, gradient_type);
+ return MakeGarbageCollected<CSSLinearGradientValue>(
+ first_x, first_y, second_x, second_y, angle, repeat, gradient_type);
}
- String CustomCSSText() const;
-
- // Create the gradient for a given size.
- scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
- const FloatSize&,
- const Document&,
- const ComputedStyle&) const;
-
- bool Equals(const CSSLinearGradientValue&) const;
-
- void TraceAfterDispatch(blink::Visitor*);
-
- private:
CSSLinearGradientValue(const CSSValue* first_x,
const CSSValue* first_y,
const CSSValue* second_x,
@@ -193,6 +180,19 @@ class CSSLinearGradientValue final : public CSSGradientValue {
second_y_(second_y),
angle_(angle) {}
+ String CustomCSSText() const;
+
+ // Create the gradient for a given size.
+ scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
+ const FloatSize&,
+ const Document&,
+ const ComputedStyle&) const;
+
+ bool Equals(const CSSLinearGradientValue&) const;
+
+ void TraceAfterDispatch(blink::Visitor*);
+
+ private:
// Any of these may be null.
Member<const CSSValue> first_x_;
Member<const CSSValue> first_y_;
@@ -214,9 +214,9 @@ class CSSRadialGradientValue final : public CSSGradientValue {
const CSSPrimitiveValue* second_radius,
CSSGradientRepeat repeat,
CSSGradientType gradient_type = kCSSRadialGradient) {
- return new CSSRadialGradientValue(first_x, first_y, first_radius, second_x,
- second_y, second_radius, nullptr, nullptr,
- nullptr, nullptr, repeat, gradient_type);
+ return MakeGarbageCollected<CSSRadialGradientValue>(
+ first_x, first_y, first_radius, second_x, second_y, second_radius,
+ nullptr, nullptr, nullptr, nullptr, repeat, gradient_type);
}
static CSSGradientValue* Create(const CSSValue* center_x,
@@ -227,32 +227,11 @@ class CSSRadialGradientValue final : public CSSGradientValue {
const CSSPrimitiveValue* vertical_size,
CSSGradientRepeat repeat,
CSSGradientType gradient_type) {
- return new CSSRadialGradientValue(
+ return MakeGarbageCollected<CSSRadialGradientValue>(
center_x, center_y, nullptr, center_x, center_y, nullptr, shape,
sizing_behavior, horizontal_size, vertical_size, repeat, gradient_type);
}
- String CustomCSSText() const;
-
- void SetShape(CSSIdentifierValue* val) { shape_ = val; }
- void SetSizingBehavior(CSSIdentifierValue* val) { sizing_behavior_ = val; }
-
- void SetEndHorizontalSize(CSSPrimitiveValue* val) {
- end_horizontal_size_ = val;
- }
- void SetEndVerticalSize(CSSPrimitiveValue* val) { end_vertical_size_ = val; }
-
- // Create the gradient for a given size.
- scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
- const FloatSize&,
- const Document&,
- const ComputedStyle&) const;
-
- bool Equals(const CSSRadialGradientValue&) const;
-
- void TraceAfterDispatch(blink::Visitor*);
-
- private:
CSSRadialGradientValue(const CSSValue* first_x,
const CSSValue* first_y,
const CSSPrimitiveValue* first_radius,
@@ -277,6 +256,27 @@ class CSSRadialGradientValue final : public CSSGradientValue {
end_horizontal_size_(horizontal_size),
end_vertical_size_(vertical_size) {}
+ String CustomCSSText() const;
+
+ void SetShape(CSSIdentifierValue* val) { shape_ = val; }
+ void SetSizingBehavior(CSSIdentifierValue* val) { sizing_behavior_ = val; }
+
+ void SetEndHorizontalSize(CSSPrimitiveValue* val) {
+ end_horizontal_size_ = val;
+ }
+ void SetEndVerticalSize(CSSPrimitiveValue* val) { end_vertical_size_ = val; }
+
+ // Create the gradient for a given size.
+ scoped_refptr<Gradient> CreateGradient(const CSSToLengthConversionData&,
+ const FloatSize&,
+ const Document&,
+ const ComputedStyle&) const;
+
+ bool Equals(const CSSRadialGradientValue&) const;
+
+ void TraceAfterDispatch(blink::Visitor*);
+
+ private:
// Any of these may be null.
Member<const CSSValue> first_x_;
Member<const CSSValue> first_y_;
@@ -304,9 +304,19 @@ class CSSConicGradientValue final : public CSSGradientValue {
const CSSValue* y,
const CSSPrimitiveValue* from_angle,
CSSGradientRepeat repeat) {
- return new CSSConicGradientValue(x, y, from_angle, repeat);
+ return MakeGarbageCollected<CSSConicGradientValue>(x, y, from_angle,
+ repeat);
}
+ CSSConicGradientValue(const CSSValue* x,
+ const CSSValue* y,
+ const CSSPrimitiveValue* from_angle,
+ CSSGradientRepeat repeat)
+ : CSSGradientValue(kConicGradientClass, repeat, kCSSConicGradient),
+ x_(x),
+ y_(y),
+ from_angle_(from_angle) {}
+
String CustomCSSText() const;
// Create the gradient for a given size.
@@ -320,15 +330,6 @@ class CSSConicGradientValue final : public CSSGradientValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSConicGradientValue(const CSSValue* x,
- const CSSValue* y,
- const CSSPrimitiveValue* from_angle,
- CSSGradientRepeat repeat)
- : CSSGradientValue(kConicGradientClass, repeat, kCSSConicGradient),
- x_(x),
- y_(y),
- from_angle_(from_angle) {}
-
// Any of these may be null.
Member<const CSSValue> x_;
Member<const CSSValue> y_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_grid_auto_repeat_value.h b/chromium/third_party/blink/renderer/core/css/css_grid_auto_repeat_value.h
index ba728b91487..bfb629bb4ea 100644
--- a/chromium/third_party/blink/renderer/core/css/css_grid_auto_repeat_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_grid_auto_repeat_value.h
@@ -26,7 +26,13 @@ namespace blink {
class CSSGridAutoRepeatValue : public CSSValueList {
public:
static CSSGridAutoRepeatValue* Create(CSSValueID id) {
- return new CSSGridAutoRepeatValue(id);
+ return MakeGarbageCollected<CSSGridAutoRepeatValue>(id);
+ }
+
+ CSSGridAutoRepeatValue(CSSValueID id)
+ : CSSValueList(kGridAutoRepeatClass, kSpaceSeparator),
+ auto_repeat_id_(id) {
+ DCHECK(id == CSSValueAutoFill || id == CSSValueAutoFit);
}
String CustomCSSText() const;
@@ -37,12 +43,6 @@ class CSSGridAutoRepeatValue : public CSSValueList {
}
private:
- CSSGridAutoRepeatValue(CSSValueID id)
- : CSSValueList(kGridAutoRepeatClass, kSpaceSeparator),
- auto_repeat_id_(id) {
- DCHECK(id == CSSValueAutoFill || id == CSSValueAutoFit);
- }
-
const CSSValueID auto_repeat_id_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_grid_line_names_value.h b/chromium/third_party/blink/renderer/core/css/css_grid_line_names_value.h
index 18cb9c8ffba..dec5c986ecb 100644
--- a/chromium/third_party/blink/renderer/core/css/css_grid_line_names_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_grid_line_names_value.h
@@ -37,16 +37,17 @@ namespace blink {
class CSSGridLineNamesValue : public CSSValueList {
public:
- static CSSGridLineNamesValue* Create() { return new CSSGridLineNamesValue(); }
+ static CSSGridLineNamesValue* Create() {
+ return MakeGarbageCollected<CSSGridLineNamesValue>();
+ }
+
+ CSSGridLineNamesValue();
String CustomCSSText() const;
void TraceAfterDispatch(blink::Visitor* visitor) {
CSSValueList::TraceAfterDispatch(visitor);
}
-
- private:
- CSSGridLineNamesValue();
};
DEFINE_CSS_VALUE_TYPE_CASTS(CSSGridLineNamesValue, IsGridLineNamesValue());
diff --git a/chromium/third_party/blink/renderer/core/css/css_grid_template_areas_value.h b/chromium/third_party/blink/renderer/core/css/css_grid_template_areas_value.h
index 027dde5a858..c2cba1c92f8 100644
--- a/chromium/third_party/blink/renderer/core/css/css_grid_template_areas_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_grid_template_areas_value.h
@@ -43,9 +43,13 @@ class CSSGridTemplateAreasValue : public CSSValue {
const NamedGridAreaMap& grid_area_map,
size_t row_count,
size_t column_count) {
- return new CSSGridTemplateAreasValue(grid_area_map, row_count,
- column_count);
+ return MakeGarbageCollected<CSSGridTemplateAreasValue>(
+ grid_area_map, row_count, column_count);
}
+
+ CSSGridTemplateAreasValue(const NamedGridAreaMap&,
+ size_t row_count,
+ size_t column_count);
~CSSGridTemplateAreasValue() = default;
String CustomCSSText() const;
@@ -61,10 +65,6 @@ class CSSGridTemplateAreasValue : public CSSValue {
}
private:
- CSSGridTemplateAreasValue(const NamedGridAreaMap&,
- size_t row_count,
- size_t column_count);
-
NamedGridAreaMap grid_area_map_;
size_t row_count_;
size_t column_count_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_identifier_value.cc b/chromium/third_party/blink/renderer/core/css/css_identifier_value.cc
index b8e722f01bf..63f0c70c009 100644
--- a/chromium/third_party/blink/renderer/core/css/css_identifier_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_identifier_value.cc
@@ -6,7 +6,7 @@
#include "third_party/blink/renderer/core/css/css_markup.h"
#include "third_party/blink/renderer/core/css/css_value_pool.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -16,7 +16,7 @@ CSSIdentifierValue* CSSIdentifierValue::Create(CSSValueID value_id) {
CSSIdentifierValue* css_value = CssValuePool().IdentifierCacheValue(value_id);
if (!css_value) {
css_value = CssValuePool().SetIdentifierCacheValue(
- value_id, new CSSIdentifierValue(value_id));
+ value_id, MakeGarbageCollected<CSSIdentifierValue>(value_id));
}
return css_value;
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_identifier_value.h b/chromium/third_party/blink/renderer/core/css/css_identifier_value.h
index 8829909b1cb..3ca9441b4f4 100644
--- a/chromium/third_party/blink/renderer/core/css/css_identifier_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_identifier_value.h
@@ -26,13 +26,24 @@ class CORE_EXPORT CSSIdentifierValue : public CSSValue {
static_assert(!std::is_same<T, CSSValueID>::value,
"Do not call create() with a CSSValueID; call "
"createIdentifier() instead");
- return new CSSIdentifierValue(value);
+ return MakeGarbageCollected<CSSIdentifierValue>(value);
}
static CSSIdentifierValue* Create(const Length& value) {
- return new CSSIdentifierValue(value);
+ return MakeGarbageCollected<CSSIdentifierValue>(value);
}
+ explicit CSSIdentifierValue(CSSValueID);
+
+ // TODO(sashab): Remove this function, and update mapping methods to
+ // specialize the create() method instead.
+ template <typename T>
+ CSSIdentifierValue(
+ T t) // Overriden for special cases in CSSPrimitiveValueMappings.h
+ : CSSValue(kIdentifierClass), value_id_(PlatformEnumToCSSValueID(t)) {}
+
+ CSSIdentifierValue(const Length&);
+
CSSValueID GetValueID() const { return value_id_; }
String CustomCSSText() const;
@@ -50,17 +61,6 @@ class CORE_EXPORT CSSIdentifierValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- explicit CSSIdentifierValue(CSSValueID);
-
- // TODO(sashab): Remove this function, and update mapping methods to
- // specialize the create() method instead.
- template <typename T>
- CSSIdentifierValue(
- T t) // Overriden for special cases in CSSPrimitiveValueMappings.h
- : CSSValue(kIdentifierClass), value_id_(PlatformEnumToCSSValueID(t)) {}
-
- CSSIdentifierValue(const Length&);
-
CSSValueID value_id_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_image_set_value.cc b/chromium/third_party/blink/renderer/core/css/css_image_set_value.cc
index 879635ba386..597ea7685b3 100644
--- a/chromium/third_party/blink/renderer/core/css/css_image_set_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_image_set_value.cc
@@ -117,8 +117,8 @@ StyleImage* CSSImageSetValue::CacheImage(
resource_request.SetHTTPReferrer(image.referrer);
ResourceLoaderOptions options;
options.initiator_info.name = parser_mode_ == kUASheetMode
- ? FetchInitiatorTypeNames::uacss
- : FetchInitiatorTypeNames::css;
+ ? fetch_initiator_type_names::kUacss
+ : fetch_initiator_type_names::kCSS;
FetchParameters params(resource_request, options);
if (cross_origin != kCrossOriginAttributeNotSet) {
diff --git a/chromium/third_party/blink/renderer/core/css/css_image_set_value.h b/chromium/third_party/blink/renderer/core/css/css_image_set_value.h
index 2841c7367b4..43b9db23886 100644
--- a/chromium/third_party/blink/renderer/core/css/css_image_set_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_image_set_value.h
@@ -41,8 +41,10 @@ class StyleImage;
class CSSImageSetValue : public CSSValueList {
public:
static CSSImageSetValue* Create(CSSParserMode parser_mode) {
- return new CSSImageSetValue(parser_mode);
+ return MakeGarbageCollected<CSSImageSetValue>(parser_mode);
}
+
+ explicit CSSImageSetValue(CSSParserMode);
~CSSImageSetValue();
bool IsCachePending(float device_scale_factor) const;
@@ -72,8 +74,6 @@ class CSSImageSetValue : public CSSValueList {
ImageWithScale BestImageForScaleFactor(float scale_factor);
private:
- explicit CSSImageSetValue(CSSParserMode);
-
void FillImageSet();
static inline bool CompareByScaleFactor(ImageWithScale first,
ImageWithScale second) {
diff --git a/chromium/third_party/blink/renderer/core/css/css_image_value.cc b/chromium/third_party/blink/renderer/core/css/css_image_value.cc
index 8cafaa9575a..ac9305000c7 100644
--- a/chromium/third_party/blink/renderer/core/css/css_image_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_image_value.cc
@@ -64,7 +64,7 @@ StyleImage* CSSImageValue::CacheImage(
referrer_.referrer_policy, resource_request.Url(), referrer_.referrer));
ResourceLoaderOptions options;
options.initiator_info.name = initiator_name_.IsEmpty()
- ? FetchInitiatorTypeNames::css
+ ? fetch_initiator_type_names::kCSS
: initiator_name_;
FetchParameters params(resource_request, options);
@@ -97,7 +97,7 @@ void CSSImageValue::RestoreCachedResourceIfNeeded(
resource->EmulateLoadStartedForInspector(
document.Fetcher(), KURL(absolute_url_),
- initiator_name_.IsEmpty() ? FetchInitiatorTypeNames::css
+ initiator_name_.IsEmpty() ? fetch_initiator_type_names::kCSS
: initiator_name_);
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_image_value.h b/chromium/third_party/blink/renderer/core/css/css_image_value.h
index 6124f79d61f..ec7e0cfe1c3 100644
--- a/chromium/third_party/blink/renderer/core/css/css_image_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_image_value.h
@@ -55,11 +55,17 @@ class CORE_EXPORT CSSImageValue : public CSSValue {
const KURL& url,
const Referrer& referrer,
StyleImage* image = nullptr) {
- return new CSSImageValue(raw_value, url, referrer, image);
+ return MakeGarbageCollected<CSSImageValue>(raw_value, url, referrer, image);
}
static CSSImageValue* Create(const AtomicString& absolute_url) {
- return new CSSImageValue(absolute_url);
+ return MakeGarbageCollected<CSSImageValue>(absolute_url);
}
+
+ CSSImageValue(const AtomicString& raw_value,
+ const KURL&,
+ const Referrer&,
+ StyleImage*);
+ CSSImageValue(const AtomicString& absolute_url);
~CSSImageValue();
bool IsCachePending() const { return !cached_image_; }
@@ -101,12 +107,6 @@ class CORE_EXPORT CSSImageValue : public CSSValue {
void RestoreCachedResourceIfNeeded(const Document&) const;
private:
- CSSImageValue(const AtomicString& raw_value,
- const KURL&,
- const Referrer&,
- StyleImage*);
- CSSImageValue(const AtomicString& absolute_url);
-
AtomicString relative_url_;
Referrer referrer_;
AtomicString initiator_name_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_import_rule.h b/chromium/third_party/blink/renderer/core/css/css_import_rule.h
index 546eb5da4a6..d9be4fdcdfd 100644
--- a/chromium/third_party/blink/renderer/core/css/css_import_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_import_rule.h
@@ -35,9 +35,10 @@ class CSSImportRule final : public CSSRule {
public:
static CSSImportRule* Create(StyleRuleImport* rule, CSSStyleSheet* sheet) {
- return new CSSImportRule(rule, sheet);
+ return MakeGarbageCollected<CSSImportRule>(rule, sheet);
}
+ CSSImportRule(StyleRuleImport*, CSSStyleSheet*);
~CSSImportRule() override;
String cssText() const override;
@@ -50,8 +51,6 @@ class CSSImportRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSImportRule(StyleRuleImport*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kImportRule; }
Member<StyleRuleImport> import_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_initial_value.h b/chromium/third_party/blink/renderer/core/css/css_initial_value.h
index 7f127949f05..7cbecaf0dfb 100644
--- a/chromium/third_party/blink/renderer/core/css/css_initial_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_initial_value.h
@@ -22,14 +22,17 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_INITIAL_VALUE_H_
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_value.h"
namespace blink {
-class CSSInitialValue : public CSSValue {
+class CORE_EXPORT CSSInitialValue : public CSSValue {
public:
static CSSInitialValue* Create();
+ CSSInitialValue() : CSSValue(kInitialClass) {}
+
String CustomCSSText() const;
bool Equals(const CSSInitialValue&) const { return true; }
@@ -40,8 +43,6 @@ class CSSInitialValue : public CSSValue {
private:
friend class CSSValuePool;
-
- CSSInitialValue() : CSSValue(kInitialClass) {}
};
DEFINE_CSS_VALUE_TYPE_CASTS(CSSInitialValue, IsInitialValue());
diff --git a/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.cc b/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.cc
new file mode 100644
index 00000000000..7d191c2276a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.cc
@@ -0,0 +1,20 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h"
+
+#include "third_party/blink/renderer/core/css/css_value_pool.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+CSSInvalidVariableValue* CSSInvalidVariableValue::Create() {
+ return CssValuePool().InvalidVariableValue();
+}
+
+String CSSInvalidVariableValue::CustomCSSText() const {
+ return "";
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.h b/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.h
new file mode 100644
index 00000000000..090ca837b2c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value.h
@@ -0,0 +1,35 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_INVALID_VARIABLE_VALUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_INVALID_VARIABLE_VALUE_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_value.h"
+
+namespace blink {
+
+class CORE_EXPORT CSSInvalidVariableValue : public CSSValue {
+ public:
+ static CSSInvalidVariableValue* Create();
+
+ String CustomCSSText() const;
+
+ bool Equals(const CSSInvalidVariableValue&) const { return true; }
+
+ void TraceAfterDispatch(blink::Visitor* visitor) {
+ CSSValue::TraceAfterDispatch(visitor);
+ }
+
+ private:
+ friend class CSSValuePool;
+
+ CSSInvalidVariableValue() : CSSValue(kInvalidVariableValueClass) {}
+};
+
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSInvalidVariableValue, IsInvalidVariableValue());
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_INVALID_VARIABLE_VALUE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value_test.cc b/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value_test.cc
new file mode 100644
index 00000000000..dcedc4f0fad
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_invalid_variable_value_test.cc
@@ -0,0 +1,34 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+namespace {
+
+TEST(CSSInvalidVariableValueTest, Create) {
+ EXPECT_TRUE(CSSInvalidVariableValue::Create());
+}
+
+TEST(CSSInvalidVariableValueTest, Pool) {
+ const CSSInvalidVariableValue* value1 = CSSInvalidVariableValue::Create();
+ const CSSInvalidVariableValue* value2 = CSSInvalidVariableValue::Create();
+ EXPECT_EQ(value1, value2);
+}
+
+TEST(CSSInvalidVariableValueTest, Equals) {
+ const CSSInvalidVariableValue* value1 = CSSInvalidVariableValue::Create();
+ const CSSInvalidVariableValue* value2 = CSSInvalidVariableValue::Create();
+ EXPECT_TRUE(value1->Equals(*value2));
+}
+
+TEST(CSSInvalidVariableValueTest, CustomCSSText) {
+ EXPECT_EQ("", CSSInvalidVariableValue::Create()->CustomCSSText());
+}
+
+} // namespace
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.h b/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.h
index e4172f50071..df8f03f392f 100644
--- a/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.h
@@ -40,6 +40,7 @@ class CSSKeyframeRule final : public CSSRule {
DEFINE_WRAPPERTYPEINFO();
public:
+ CSSKeyframeRule(StyleRuleKeyframe*, CSSKeyframesRule* parent);
~CSSKeyframeRule() override;
String cssText() const override { return keyframe_->CssText(); }
@@ -53,8 +54,6 @@ class CSSKeyframeRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSKeyframeRule(StyleRuleKeyframe*, CSSKeyframesRule* parent);
-
CSSRule::Type type() const override { return kKeyframeRule; }
Member<StyleRuleKeyframe> keyframe_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.cc b/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.cc
index 4a7b8e2e294..93650f7a901 100644
--- a/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.cc
@@ -162,9 +162,11 @@ CSSKeyframeRule* CSSKeyframesRule::Item(unsigned index) const {
DCHECK_EQ(child_rule_cssom_wrappers_.size(),
keyframes_rule_->Keyframes().size());
Member<CSSKeyframeRule>& rule = child_rule_cssom_wrappers_[index];
- if (!rule)
- rule = new CSSKeyframeRule(keyframes_rule_->Keyframes()[index].Get(),
- const_cast<CSSKeyframesRule*>(this));
+ if (!rule) {
+ rule = MakeGarbageCollected<CSSKeyframeRule>(
+ keyframes_rule_->Keyframes()[index].Get(),
+ const_cast<CSSKeyframesRule*>(this));
+ }
return rule.Get();
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.h b/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.h
index 032d1ce4eb1..e9db4179268 100644
--- a/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.h
@@ -39,8 +39,12 @@ class StyleRuleKeyframe;
class StyleRuleKeyframes final : public StyleRuleBase {
public:
- static StyleRuleKeyframes* Create() { return new StyleRuleKeyframes(); }
+ static StyleRuleKeyframes* Create() {
+ return MakeGarbageCollected<StyleRuleKeyframes>();
+ }
+ StyleRuleKeyframes();
+ explicit StyleRuleKeyframes(const StyleRuleKeyframes&);
~StyleRuleKeyframes();
const HeapVector<Member<StyleRuleKeyframe>>& Keyframes() const {
@@ -59,7 +63,9 @@ class StyleRuleKeyframes final : public StyleRuleBase {
int FindKeyframeIndex(const String& key) const;
- StyleRuleKeyframes* Copy() const { return new StyleRuleKeyframes(*this); }
+ StyleRuleKeyframes* Copy() const {
+ return MakeGarbageCollected<StyleRuleKeyframes>(*this);
+ }
void TraceAfterDispatch(blink::Visitor*);
@@ -67,9 +73,6 @@ class StyleRuleKeyframes final : public StyleRuleBase {
unsigned Version() const { return version_; }
private:
- StyleRuleKeyframes();
- explicit StyleRuleKeyframes(const StyleRuleKeyframes&);
-
HeapVector<Member<StyleRuleKeyframe>> keyframes_;
AtomicString name_;
unsigned version_ : 31;
@@ -84,9 +87,10 @@ class CSSKeyframesRule final : public CSSRule {
public:
static CSSKeyframesRule* Create(StyleRuleKeyframes* rule,
CSSStyleSheet* sheet) {
- return new CSSKeyframesRule(rule, sheet);
+ return MakeGarbageCollected<CSSKeyframesRule>(rule, sheet);
}
+ CSSKeyframesRule(StyleRuleKeyframes*, CSSStyleSheet* parent);
~CSSKeyframesRule() override;
StyleRuleKeyframes* Keyframes() { return keyframes_rule_.Get(); }
@@ -116,8 +120,6 @@ class CSSKeyframesRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSKeyframesRule(StyleRuleKeyframes*, CSSStyleSheet* parent);
-
CSSRule::Type type() const override { return kKeyframesRule; }
Member<StyleRuleKeyframes> keyframes_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_layout_function_value.h b/chromium/third_party/blink/renderer/core/css/css_layout_function_value.h
index 6ca76cacea4..e85c02cc38b 100644
--- a/chromium/third_party/blink/renderer/core/css/css_layout_function_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_layout_function_value.h
@@ -19,8 +19,10 @@ class CSSLayoutFunctionValue : public CSSValue {
public:
static CSSLayoutFunctionValue* Create(CSSCustomIdentValue* name,
bool is_inline) {
- return new CSSLayoutFunctionValue(name, is_inline);
+ return MakeGarbageCollected<CSSLayoutFunctionValue>(name, is_inline);
}
+
+ CSSLayoutFunctionValue(CSSCustomIdentValue* name, bool is_inline);
~CSSLayoutFunctionValue();
String CustomCSSText() const;
@@ -31,8 +33,6 @@ class CSSLayoutFunctionValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSLayoutFunctionValue(CSSCustomIdentValue* name, bool is_inline);
-
Member<CSSCustomIdentValue> name_;
bool is_inline_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_media_rule.h b/chromium/third_party/blink/renderer/core/css/css_media_rule.h
index fb6b752f910..1991686d906 100644
--- a/chromium/third_party/blink/renderer/core/css/css_media_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_media_rule.h
@@ -35,9 +35,10 @@ class CSSMediaRule final : public CSSConditionRule {
public:
static CSSMediaRule* Create(StyleRuleMedia* rule, CSSStyleSheet* sheet) {
- return new CSSMediaRule(rule, sheet);
+ return MakeGarbageCollected<CSSMediaRule>(rule, sheet);
}
+ CSSMediaRule(StyleRuleMedia*, CSSStyleSheet*);
~CSSMediaRule() override;
void Reattach(StyleRuleBase*) override;
@@ -49,8 +50,6 @@ class CSSMediaRule final : public CSSConditionRule {
void Trace(blink::Visitor*) override;
private:
- CSSMediaRule(StyleRuleMedia*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kMediaRule; }
scoped_refptr<MediaQuerySet> MediaQueries() const;
diff --git a/chromium/third_party/blink/renderer/core/css/css_namespace_rule.h b/chromium/third_party/blink/renderer/core/css/css_namespace_rule.h
index ad2f2f2bd3e..448891b6a16 100644
--- a/chromium/third_party/blink/renderer/core/css/css_namespace_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_namespace_rule.h
@@ -17,9 +17,10 @@ class CSSNamespaceRule final : public CSSRule {
public:
static CSSNamespaceRule* Create(StyleRuleNamespace* rule,
CSSStyleSheet* sheet) {
- return new CSSNamespaceRule(rule, sheet);
+ return MakeGarbageCollected<CSSNamespaceRule>(rule, sheet);
}
+ CSSNamespaceRule(StyleRuleNamespace*, CSSStyleSheet*);
~CSSNamespaceRule() override;
String cssText() const override;
@@ -31,8 +32,6 @@ class CSSNamespaceRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSNamespaceRule(StyleRuleNamespace*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kNamespaceRule; }
Member<StyleRuleNamespace> namespace_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_page_rule.h b/chromium/third_party/blink/renderer/core/css/css_page_rule.h
index 9e839663776..c5f756cbb7c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_page_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_page_rule.h
@@ -38,9 +38,10 @@ class CORE_EXPORT CSSPageRule final : public CSSRule {
public:
static CSSPageRule* Create(StyleRulePage* rule, CSSStyleSheet* sheet) {
- return new CSSPageRule(rule, sheet);
+ return MakeGarbageCollected<CSSPageRule>(rule, sheet);
}
+ CSSPageRule(StyleRulePage*, CSSStyleSheet*);
~CSSPageRule() override;
String cssText() const override;
@@ -54,8 +55,6 @@ class CORE_EXPORT CSSPageRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSPageRule(StyleRulePage*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kPageRule; }
Member<StyleRulePage> page_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_page_rule_test.cc b/chromium/third_party/blink/renderer/core/css/css_page_rule_test.cc
index 7ad3b52d9d9..e6b7c0c0a8f 100644
--- a/chromium/third_party/blink/renderer/core/css/css_page_rule_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_page_rule_test.cc
@@ -5,52 +5,54 @@
#include "third_party/blink/renderer/core/css/css_page_rule.h"
#include "third_party/blink/renderer/core/css/css_rule_list.h"
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
+using namespace css_test_helpers;
+
TEST(CSSPageRule, Serializing) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
const char* css_rule = "@page :left { size: auto; }";
- helper.AddCSSRules(css_rule);
- if (helper.CssRules()) {
- EXPECT_EQ(1u, helper.CssRules()->length());
- EXPECT_EQ(String(css_rule), helper.CssRules()->item(0)->cssText());
- EXPECT_EQ(CSSRule::kPageRule, helper.CssRules()->item(0)->type());
- if (CSSPageRule* page_rule = ToCSSPageRule(helper.CssRules()->item(0)))
+ sheet.AddCSSRules(css_rule);
+ if (sheet.CssRules()) {
+ EXPECT_EQ(1u, sheet.CssRules()->length());
+ EXPECT_EQ(String(css_rule), sheet.CssRules()->item(0)->cssText());
+ EXPECT_EQ(CSSRule::kPageRule, sheet.CssRules()->item(0)->type());
+ if (CSSPageRule* page_rule = ToCSSPageRule(sheet.CssRules()->item(0)))
EXPECT_EQ(":left", page_rule->selectorText());
}
}
TEST(CSSPageRule, selectorText) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
const char* css_rule = "@page :left { size: auto; }";
- helper.AddCSSRules(css_rule);
- DCHECK(helper.CssRules());
- EXPECT_EQ(1u, helper.CssRules()->length());
+ sheet.AddCSSRules(css_rule);
+ DCHECK(sheet.CssRules());
+ EXPECT_EQ(1u, sheet.CssRules()->length());
- CSSPageRule* page_rule = ToCSSPageRule(helper.CssRules()->item(0));
+ CSSPageRule* page_rule = ToCSSPageRule(sheet.CssRules()->item(0));
EXPECT_EQ(":left", page_rule->selectorText());
// set invalid page selector.
- page_rule->setSelectorText(&helper.GetDocument(), ":hover");
+ page_rule->setSelectorText(&sheet.GetDocument(), ":hover");
EXPECT_EQ(":left", page_rule->selectorText());
// set invalid page selector.
- page_rule->setSelectorText(&helper.GetDocument(), "right { bla");
+ page_rule->setSelectorText(&sheet.GetDocument(), "right { bla");
EXPECT_EQ(":left", page_rule->selectorText());
// set page pseudo class selector.
- page_rule->setSelectorText(&helper.GetDocument(), ":right");
+ page_rule->setSelectorText(&sheet.GetDocument(), ":right");
EXPECT_EQ(":right", page_rule->selectorText());
// set page type selector.
- page_rule->setSelectorText(&helper.GetDocument(), "namedpage");
+ page_rule->setSelectorText(&sheet.GetDocument(), "namedpage");
EXPECT_EQ("namedpage", page_rule->selectorText());
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_paint_image_generator.h b/chromium/third_party/blink/renderer/core/css/css_paint_image_generator.h
index 7998542b4ec..ccecc1e9be9 100644
--- a/chromium/third_party/blink/renderer/core/css/css_paint_image_generator.h
+++ b/chromium/third_party/blink/renderer/core/css/css_paint_image_generator.h
@@ -6,9 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PAINT_IMAGE_GENERATOR_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
-#include "third_party/blink/renderer/platform/geometry/int_size.h"
+#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
@@ -50,7 +50,7 @@ class CORE_EXPORT CSSPaintImageGenerator
// representing an invalid image if an error occurred.
// The |container_size| is the container size with subpixel snapping.
virtual scoped_refptr<Image> Paint(const ImageResourceObserver&,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector*) = 0;
virtual const Vector<CSSPropertyID>& NativeInvalidationProperties() const = 0;
diff --git a/chromium/third_party/blink/renderer/core/css/css_paint_value.cc b/chromium/third_party/blink/renderer/core/css/css_paint_value.cc
index d97f41b6b6b..0069f562e35 100644
--- a/chromium/third_party/blink/renderer/core/css/css_paint_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_paint_value.cc
@@ -16,7 +16,7 @@ namespace blink {
CSSPaintValue::CSSPaintValue(CSSCustomIdentValue* name)
: CSSImageGeneratorValue(kPaintClass),
name_(name),
- paint_image_generator_observer_(new Observer(this)) {}
+ paint_image_generator_observer_(MakeGarbageCollected<Observer>(this)) {}
CSSPaintValue::CSSPaintValue(
CSSCustomIdentValue* name,
@@ -61,8 +61,7 @@ scoped_refptr<Image> CSSPaintValue::GetImage(
if (!ParseInputArguments(document))
return nullptr;
- return generator_->Paint(client, RoundedIntSize(target_size),
- parsed_input_arguments_);
+ return generator_->Paint(client, target_size, parsed_input_arguments_);
}
bool CSSPaintValue::ParseInputArguments(const Document& document) {
@@ -83,7 +82,7 @@ bool CSSPaintValue::ParseInputArguments(const Document& document) {
return false;
}
- parsed_input_arguments_ = new CSSStyleValueVector();
+ parsed_input_arguments_ = MakeGarbageCollected<CSSStyleValueVector>();
for (wtf_size_t i = 0; i < argument_variable_data_.size(); ++i) {
// If we are parsing a paint() function, we must be a secure context.
diff --git a/chromium/third_party/blink/renderer/core/css/css_paint_value.h b/chromium/third_party/blink/renderer/core/css/css_paint_value.h
index fc879596b9b..32953d12af0 100644
--- a/chromium/third_party/blink/renderer/core/css/css_paint_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_paint_value.h
@@ -18,15 +18,18 @@ namespace blink {
class CORE_EXPORT CSSPaintValue : public CSSImageGeneratorValue {
public:
static CSSPaintValue* Create(CSSCustomIdentValue* name) {
- return new CSSPaintValue(name);
+ return MakeGarbageCollected<CSSPaintValue>(name);
}
static CSSPaintValue* Create(
CSSCustomIdentValue* name,
Vector<scoped_refptr<CSSVariableData>>& variable_data) {
- return new CSSPaintValue(name, variable_data);
+ return MakeGarbageCollected<CSSPaintValue>(name, variable_data);
}
+ explicit CSSPaintValue(CSSCustomIdentValue* name);
+ CSSPaintValue(CSSCustomIdentValue* name,
+ Vector<scoped_refptr<CSSVariableData>>&);
~CSSPaintValue();
String CustomCSSText() const;
@@ -59,11 +62,6 @@ class CORE_EXPORT CSSPaintValue : public CSSImageGeneratorValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- explicit CSSPaintValue(CSSCustomIdentValue* name);
-
- CSSPaintValue(CSSCustomIdentValue* name,
- Vector<scoped_refptr<CSSVariableData>>&);
-
class Observer final : public CSSPaintImageGenerator::Observer {
public:
explicit Observer(CSSPaintValue* owner_value) : owner_value_(owner_value) {}
diff --git a/chromium/third_party/blink/renderer/core/css/css_paint_value_test.cc b/chromium/third_party/blink/renderer/core/css/css_paint_value_test.cc
index 923faeaf823..bca3c182049 100644
--- a/chromium/third_party/blink/renderer/core/css/css_paint_value_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_paint_value_test.cc
@@ -23,17 +23,18 @@ class CSSPaintValueTest : public RenderingTest {
void LoadTestData(const std::string& file_name) {
String testing_path = test::BlinkRootDir();
testing_path.append("/renderer/core/css/test_data/");
- WebURL url = URLTestHelpers::RegisterMockedURLLoadFromBase(
+ WebURL url = url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), testing_path,
WebString::FromUTF8(file_name));
- FrameTestHelpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
- base_url_ + file_name);
+ frame_test_helpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
+ base_url_ + file_name);
ForceFullCompositingUpdate();
- URLTestHelpers::RegisterMockedURLUnregister(url);
+ url_test_helpers::RegisterMockedURLUnregister(url);
}
void ForceFullCompositingUpdate() {
- helper_.GetWebView()->UpdateAllLifecyclePhases();
+ helper_.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
LocalFrame* GetFrame() const { return helper_.LocalMainFrame()->GetFrame(); }
@@ -45,7 +46,7 @@ class CSSPaintValueTest : public RenderingTest {
helper_.Initialize(nullptr, nullptr, nullptr);
base_url_ = "https://www.test.com/";
}
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
std::string base_url_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_path_value.cc b/chromium/third_party/blink/renderer/core/css/css_path_value.cc
index 5382bad7a65..573f1e8f2f5 100644
--- a/chromium/third_party/blink/renderer/core/css/css_path_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_path_value.cc
@@ -16,7 +16,8 @@ namespace cssvalue {
CSSPathValue* CSSPathValue::Create(
scoped_refptr<StylePath> style_path,
PathSerializationFormat serialization_format) {
- return new CSSPathValue(std::move(style_path), serialization_format);
+ return MakeGarbageCollected<CSSPathValue>(std::move(style_path),
+ serialization_format);
}
CSSPathValue* CSSPathValue::Create(
diff --git a/chromium/third_party/blink/renderer/core/css/css_path_value.h b/chromium/third_party/blink/renderer/core/css/css_path_value.h
index 9352a74d9b5..5366847b20b 100644
--- a/chromium/third_party/blink/renderer/core/css/css_path_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_path_value.h
@@ -27,6 +27,8 @@ class CSSPathValue : public CSSValue {
static CSSPathValue& EmptyPathValue();
+ CSSPathValue(scoped_refptr<StylePath>, PathSerializationFormat);
+
StylePath* GetStylePath() const { return style_path_.get(); }
String CustomCSSText() const;
@@ -39,8 +41,6 @@ class CSSPathValue : public CSSValue {
}
private:
- CSSPathValue(scoped_refptr<StylePath>, PathSerializationFormat);
-
scoped_refptr<StylePath> style_path_;
const PathSerializationFormat serialization_format_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_pending_substitution_value.h b/chromium/third_party/blink/renderer/core/css/css_pending_substitution_value.h
index 8533f6f4999..c26dcb6d16d 100644
--- a/chromium/third_party/blink/renderer/core/css/css_pending_substitution_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_pending_substitution_value.h
@@ -5,9 +5,9 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_SUBSTITUTION_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_SUBSTITUTION_VALUE_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
namespace blink {
@@ -16,10 +16,16 @@ class CSSPendingSubstitutionValue : public CSSValue {
static CSSPendingSubstitutionValue* Create(
CSSPropertyID shorthand_property_id,
CSSVariableReferenceValue* shorthand_value) {
- return new CSSPendingSubstitutionValue(shorthand_property_id,
- shorthand_value);
+ return MakeGarbageCollected<CSSPendingSubstitutionValue>(
+ shorthand_property_id, shorthand_value);
}
+ CSSPendingSubstitutionValue(CSSPropertyID shorthand_property_id,
+ CSSVariableReferenceValue* shorthand_value)
+ : CSSValue(kPendingSubstitutionValueClass),
+ shorthand_property_id_(shorthand_property_id),
+ shorthand_value_(shorthand_value) {}
+
CSSVariableReferenceValue* ShorthandValue() const {
return shorthand_value_.Get();
}
@@ -34,12 +40,6 @@ class CSSPendingSubstitutionValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSPendingSubstitutionValue(CSSPropertyID shorthand_property_id,
- CSSVariableReferenceValue* shorthand_value)
- : CSSValue(kPendingSubstitutionValueClass),
- shorthand_property_id_(shorthand_property_id),
- shorthand_value_(shorthand_value) {}
-
CSSPropertyID shorthand_property_id_;
Member<CSSVariableReferenceValue> shorthand_value_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_primitive_value.cc b/chromium/third_party/blink/renderer/core/css/css_primitive_value.cc
index f0357072aa5..11e9d167736 100644
--- a/chromium/third_party/blink/renderer/core/css/css_primitive_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_primitive_value.cc
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/css/css_resolution_units.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
#include "third_party/blink/renderer/core/css/css_value_pool.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -95,37 +95,39 @@ CSSPrimitiveValue* CSSPrimitiveValue::Create(double value, UnitType type) {
value = 0;
if (value < 0 || value > CSSValuePool::kMaximumCacheableIntegerValue)
- return new CSSPrimitiveValue(value, type);
+ return MakeGarbageCollected<CSSPrimitiveValue>(value, type);
- int int_value = static_cast<int>(value);
+ int int_value = clampTo<int>(value);
if (value != int_value)
- return new CSSPrimitiveValue(value, type);
+ return MakeGarbageCollected<CSSPrimitiveValue>(value, type);
CSSValuePool& pool = CssValuePool();
CSSPrimitiveValue* result = nullptr;
switch (type) {
case CSSPrimitiveValue::UnitType::kPixels:
result = pool.PixelCacheValue(int_value);
- if (!result)
- result = pool.SetPixelCacheValue(int_value,
- new CSSPrimitiveValue(value, type));
+ if (!result) {
+ result = pool.SetPixelCacheValue(
+ int_value, MakeGarbageCollected<CSSPrimitiveValue>(value, type));
+ }
return result;
case CSSPrimitiveValue::UnitType::kPercentage:
result = pool.PercentCacheValue(int_value);
- if (!result)
- result = pool.SetPercentCacheValue(int_value,
- new CSSPrimitiveValue(value, type));
+ if (!result) {
+ result = pool.SetPercentCacheValue(
+ int_value, MakeGarbageCollected<CSSPrimitiveValue>(value, type));
+ }
return result;
case CSSPrimitiveValue::UnitType::kNumber:
case CSSPrimitiveValue::UnitType::kInteger:
result = pool.NumberCacheValue(int_value);
if (!result)
result = pool.SetNumberCacheValue(
- int_value, new CSSPrimitiveValue(
+ int_value, MakeGarbageCollected<CSSPrimitiveValue>(
value, CSSPrimitiveValue::UnitType::kInteger));
return result;
default:
- return new CSSPrimitiveValue(value, type);
+ return MakeGarbageCollected<CSSPrimitiveValue>(value, type);
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_primitive_value.h b/chromium/third_party/blink/renderer/core/css/css_primitive_value.h
index a4b4f3a30ca..467bbb18c5b 100644
--- a/chromium/third_party/blink/renderer/core/css/css_primitive_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_primitive_value.h
@@ -23,8 +23,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PRIMITIVE_VALUE_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/platform/wtf/bit_vector.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
@@ -199,7 +199,7 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
static bool IsTime(UnitType unit) {
return unit == UnitType::kSeconds || unit == UnitType::kMilliseconds;
}
- bool IsTime() const { return IsTime(GetType()); }
+ bool IsTime() const { return IsTime(TypeWithCalcResolved()); }
static bool IsFrequency(UnitType unit) {
return unit == UnitType::kHertz || unit == UnitType::kKilohertz;
}
@@ -214,20 +214,29 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
return type >= UnitType::kDotsPerPixel &&
type <= UnitType::kDotsPerCentimeter;
}
+ bool IsResolution() const { return IsResolution(GetType()); }
static bool IsFlex(UnitType unit) { return unit == UnitType::kFraction; }
bool IsFlex() const { return IsFlex(GetType()); }
static CSSPrimitiveValue* Create(double value, UnitType);
static CSSPrimitiveValue* Create(const Length& value, float zoom) {
- return new CSSPrimitiveValue(value, zoom);
+ return MakeGarbageCollected<CSSPrimitiveValue>(value, zoom);
}
// TODO(sashab): Remove this.
template <typename T>
static CSSPrimitiveValue* Create(T value) {
- return new CSSPrimitiveValue(value);
+ return MakeGarbageCollected<CSSPrimitiveValue>(value);
}
+ CSSPrimitiveValue(const Length&, float zoom);
+ CSSPrimitiveValue(double, UnitType);
+ template <typename T>
+ CSSPrimitiveValue(T); // Defined in CSSPrimitiveValueMappings.h
+ template <typename T>
+ CSSPrimitiveValue(T* val) : CSSValue(kPrimitiveClass) {
+ Init(val);
+ }
~CSSPrimitiveValue();
UnitType TypeWithCalcResolved() const;
@@ -281,23 +290,12 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
static UnitType LengthUnitTypeToUnitType(LengthUnitType);
private:
- CSSPrimitiveValue(const Length&, float zoom);
- CSSPrimitiveValue(double, UnitType);
-
- template <typename T>
- CSSPrimitiveValue(T); // Defined in CSSPrimitiveValueMappings.h
-
- template <typename T>
- CSSPrimitiveValue(T* val) : CSSValue(kPrimitiveClass) {
- Init(val);
- }
-
static void Create(int); // compile-time guard
static void Create(unsigned); // compile-time guard
template <typename T>
operator T*(); // compile-time guard
- // Code generated by CSSPrimitiveValueUnitTrie.cpp.tmpl
+ // Code generated by css_primitive_value_unit_trie.cc.tmpl
static UnitType StringToUnitType(const LChar*, unsigned length);
static UnitType StringToUnitType(const UChar*, unsigned length);
diff --git a/chromium/third_party/blink/renderer/core/css/css_primitive_value_mappings.h b/chromium/third_party/blink/renderer/core/css/css_primitive_value_mappings.h
index fd8d8b9466b..9b8165cb58c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_primitive_value_mappings.h
+++ b/chromium/third_party/blink/renderer/core/css/css_primitive_value_mappings.h
@@ -44,9 +44,9 @@
#include "third_party/blink/renderer/platform/fonts/font_description.h"
#include "third_party/blink/renderer/platform/fonts/font_smoothing_mode.h"
#include "third_party/blink/renderer/platform/fonts/text_rendering_mode.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
#include "third_party/blink/renderer/platform/theme_types.h"
@@ -549,6 +549,12 @@ inline CSSIdentifierValue::CSSIdentifierValue(EFloat e)
case EFloat::kRight:
value_id_ = CSSValueRight;
break;
+ case EFloat::kInlineStart:
+ value_id_ = CSSValueInlineStart;
+ break;
+ case EFloat::kInlineEnd:
+ value_id_ = CSSValueInlineEnd;
+ break;
}
}
@@ -559,6 +565,10 @@ inline EFloat CSSIdentifierValue::ConvertTo() const {
return EFloat::kLeft;
case CSSValueRight:
return EFloat::kRight;
+ case CSSValueInlineStart:
+ return EFloat::kInlineStart;
+ case CSSValueInlineEnd:
+ return EFloat::kInlineEnd;
case CSSValueNone:
return EFloat::kNone;
default:
@@ -1491,31 +1501,31 @@ inline TouchAction CSSIdentifierValue::ConvertTo() const {
}
template <>
-inline ScrollCustomization::ScrollDirection CSSIdentifierValue::ConvertTo()
+inline scroll_customization::ScrollDirection CSSIdentifierValue::ConvertTo()
const {
switch (value_id_) {
case CSSValueNone:
- return ScrollCustomization::kScrollDirectionNone;
+ return scroll_customization::kScrollDirectionNone;
case CSSValueAuto:
- return ScrollCustomization::kScrollDirectionAuto;
+ return scroll_customization::kScrollDirectionAuto;
case CSSValuePanLeft:
- return ScrollCustomization::kScrollDirectionPanLeft;
+ return scroll_customization::kScrollDirectionPanLeft;
case CSSValuePanRight:
- return ScrollCustomization::kScrollDirectionPanRight;
+ return scroll_customization::kScrollDirectionPanRight;
case CSSValuePanX:
- return ScrollCustomization::kScrollDirectionPanX;
+ return scroll_customization::kScrollDirectionPanX;
case CSSValuePanUp:
- return ScrollCustomization::kScrollDirectionPanUp;
+ return scroll_customization::kScrollDirectionPanUp;
case CSSValuePanDown:
- return ScrollCustomization::kScrollDirectionPanDown;
+ return scroll_customization::kScrollDirectionPanDown;
case CSSValuePanY:
- return ScrollCustomization::kScrollDirectionPanY;
+ return scroll_customization::kScrollDirectionPanY;
default:
break;
}
NOTREACHED();
- return ScrollCustomization::kScrollDirectionNone;
+ return scroll_customization::kScrollDirectionNone;
}
template <>
diff --git a/chromium/third_party/blink/renderer/core/css/css_primitive_value_test.cc b/chromium/third_party/blink/renderer/core/css/css_primitive_value_test.cc
new file mode 100644
index 00000000000..b1c55ffec75
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_primitive_value_test.cc
@@ -0,0 +1,59 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+
+namespace blink {
+namespace {
+
+using UnitType = CSSPrimitiveValue::UnitType;
+
+struct UnitValue {
+ double value;
+ UnitType unit_type;
+};
+
+CSSPrimitiveValue* Create(UnitValue v) {
+ return CSSPrimitiveValue::Create(v.value, v.unit_type);
+}
+
+CSSPrimitiveValue* CreateAddition(UnitValue a, UnitValue b) {
+ return CSSPrimitiveValue::Create(
+ CSSCalcValue::Create(CSSCalcValue::CreateExpressionNode(
+ CSSCalcValue::CreateExpressionNode(Create(a)),
+ CSSCalcValue::CreateExpressionNode(Create(b)), kCalcAdd)));
+}
+
+TEST(CSSPrimitiveValueTest, IsTime) {
+ EXPECT_FALSE(Create({5.0, UnitType::kNumber})->IsTime());
+ EXPECT_FALSE(Create({5.0, UnitType::kDegrees})->IsTime());
+ EXPECT_TRUE(Create({5.0, UnitType::kSeconds})->IsTime());
+ EXPECT_TRUE(Create({5.0, UnitType::kMilliseconds})->IsTime());
+}
+
+TEST(CSSPrimitiveValueTest, IsTimeCalc) {
+ {
+ UnitValue a = {1.0, UnitType::kSeconds};
+ UnitValue b = {1000.0, UnitType::kMilliseconds};
+ EXPECT_TRUE(CreateAddition(a, b)->IsTime());
+ }
+ {
+ UnitValue a = {1.0, UnitType::kDegrees};
+ UnitValue b = {1000.0, UnitType::kGradians};
+ EXPECT_FALSE(CreateAddition(a, b)->IsTime());
+ }
+}
+
+TEST(CSSPrimitiveValueTest, IsResolution) {
+ EXPECT_FALSE(Create({5.0, UnitType::kNumber})->IsResolution());
+ EXPECT_FALSE(Create({5.0, UnitType::kDegrees})->IsResolution());
+ EXPECT_TRUE(Create({5.0, UnitType::kDotsPerPixel})->IsResolution());
+ EXPECT_TRUE(Create({5.0, UnitType::kDotsPerCentimeter})->IsResolution());
+}
+
+} // namespace
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_properties.json5 b/chromium/third_party/blink/renderer/core/css/css_properties.json5
index cee6cb0c474..9a6fcd2c5f5 100644
--- a/chromium/third_party/blink/renderer/core/css/css_properties.json5
+++ b/chromium/third_party/blink/renderer/core/css/css_properties.json5
@@ -1025,7 +1025,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_size.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_size.h"],
default_value: "LengthSize(Length(0, kFixed), Length(0, kFixed))",
type_name: "LengthSize",
converter: "ConvertRadius",
@@ -1037,7 +1037,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_size.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_size.h"],
default_value: "LengthSize(Length(0, kFixed), Length(0, kFixed))",
type_name: "LengthSize",
converter: "ConvertRadius",
@@ -1062,7 +1062,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/layout_unit.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/layout_unit.h"],
keywords: ["thin", "medium", "thick"],
default_value: "LayoutUnit(3)",
typedom_types: ["Keyword", "Length"],
@@ -1164,7 +1164,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/layout_unit.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/layout_unit.h"],
keywords: ["thin", "medium", "thick"],
default_value: "LayoutUnit(3)",
typedom_types: ["Keyword", "Length"],
@@ -1207,7 +1207,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/layout_unit.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/layout_unit.h"],
keywords: ["thin", "medium", "thick"],
default_value: "LayoutUnit(3)",
typedom_types: ["Keyword", "Length"],
@@ -1237,7 +1237,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_size.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_size.h"],
default_value: "LengthSize(Length(0, kFixed), Length(0, kFixed))",
type_name: "LengthSize",
converter: "ConvertRadius",
@@ -1249,7 +1249,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_size.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_size.h"],
default_value: "LengthSize(Length(0, kFixed), Length(0, kFixed))",
type_name: "LengthSize",
converter: "ConvertRadius",
@@ -1274,7 +1274,7 @@
interpolable: true,
field_group: "surround",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/layout_unit.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/layout_unit.h"],
keywords: ["thin", "medium", "thick"],
default_value: "LayoutUnit(3)",
typedom_types: ["Keyword", "Length"],
@@ -1390,10 +1390,9 @@
name: "clear",
property_methods: ["CSSValueFromComputedStyleInternal"],
field_template: "keyword",
- keywords: ["none", "left", "right", "both"],
+ keywords: ["none", "left", "right", "both", "inline-start", "inline-end"],
typedom_types: ["Keyword"],
default_value: "none",
- style_builder_custom_functions: ["value"],
},
{
name: "clip",
@@ -1401,7 +1400,7 @@
interpolable: true,
field_group: "visual",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_box.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_box.h"],
default_value: "LengthBox()",
type_name: "LengthBox",
computed_style_custom_functions: ["setter"],
@@ -1606,7 +1605,7 @@
interpolable: true,
inherited: true,
svg: true,
- converter: "ConvertNumberOrPercentage",
+ converter: "ConvertAlpha",
typedom_types: ["Number"],
},
{
@@ -1687,12 +1686,11 @@
name: "float",
property_methods: ["CSSValueFromComputedStyleInternal"],
field_template: "keyword",
- keywords: ["none", "left", "right"],
+ keywords: ["none", "left", "right", "inline-start", "inline-end"],
typedom_types: ["Keyword"],
default_value: "none",
name_for_methods: "Floating",
type_name: "EFloat",
- style_builder_custom_functions: ["value"],
},
{
name: "flood-color",
@@ -1708,7 +1706,7 @@
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
interpolable: true,
svg: true,
- converter: "ConvertNumberOrPercentage",
+ converter: "ConvertAlpha",
typedom_types: ["Number"]
},
{
@@ -2212,7 +2210,7 @@
interpolable: true,
field_group: "*",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_point.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_point.h"],
default_value: "LengthPoint(Length(50.0, kPercent), Length(50.0, kPercent))",
type_name: "LengthPoint",
converter: "ConvertPosition",
@@ -2225,7 +2223,7 @@
runtime_flag: "CSSOffsetPositionAnchor",
field_group: "*",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_point.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_point.h"],
default_value: "LengthPoint(Length(kAuto), Length(kAuto))",
type_name: "LengthPoint",
converter: "ConvertPositionOrAuto",
@@ -2263,7 +2261,7 @@
runtime_flag: "CSSOffsetPositionAnchor",
field_group: "*",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_point.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_point.h"],
default_value: "LengthPoint(Length(kAuto), Length(kAuto))",
type_name: "LengthPoint",
converter: "ConvertPositionOrAuto",
@@ -2366,7 +2364,7 @@
interpolable: true,
field_group: "*",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/layout_unit.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/layout_unit.h"],
default_value: "LayoutUnit(3)",
type_name: "LayoutUnit",
computed_style_custom_functions: ["initial", "getter", "setter"],
@@ -2509,7 +2507,7 @@
layout_dependent: true,
field_group: "*",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/length_point.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length_point.h"],
default_value: "LengthPoint(Length(50.0, kPercent), Length(50.0, kPercent))",
type_name: "LengthPoint",
converter: "ConvertPosition",
@@ -2522,8 +2520,8 @@
inherited: true,
field_template: "keyword",
keywords: [
- "none", "auto", "stroke", "fill", "painted", "visible", "visibleStroke",
- "visibleFill", "visiblePainted", "bounding-box", "all"
+ "none", "auto", "stroke", "fill", "painted", "visible", "visiblestroke",
+ "visiblefill", "visiblepainted", "bounding-box", "all"
],
typedom_types: ["Keyword"],
default_value: "auto",
@@ -2559,7 +2557,7 @@
property_methods: ["CSSValueFromComputedStyleInternal"],
field_group: "*",
field_template: "keyword",
- keywords: ["none", "both", "horizontal", "vertical"],
+ keywords: ["none", "both", "horizontal", "vertical", "block", "inline"],
typedom_types: ["Keyword"],
default_value: "none",
style_builder_custom_functions: ["value"],
@@ -2605,7 +2603,6 @@
{
name: "scroll-behavior",
property_methods: ["CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSOMSmoothScroll",
field_group: "*",
field_size: 2, // FIXME: Convert this to a keyword field
field_template: "primitive",
@@ -2617,7 +2614,6 @@
{
name: "scroll-margin-block-end",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
direction_aware_options: {
logical_side: "after",
shorthand_for_physical_side: "scrollMarginShorthand",
@@ -2627,19 +2623,18 @@
{
name: "scroll-customization",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- converter: "ConvertFlags<blink::ScrollCustomization::ScrollDirection>",
- type_name: "ScrollCustomization::ScrollDirection",
+ converter: "ConvertFlags<blink::scroll_customization::ScrollDirection>",
+ type_name: "scroll_customization::ScrollDirection",
field_group: "*",
field_size: 4,
field_template: "primitive",
- default_value: "ScrollCustomization::kScrollDirectionNone",
+ default_value: "scroll_customization::kScrollDirectionNone",
include_paths: ["third_party/blink/renderer/core/scroll/scroll_customization.h"],
runtime_flag: "ScrollCustomization",
},
{
name: "scroll-margin-block-start",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
direction_aware_options: {
logical_side: "before",
shorthand_for_physical_side: "scrollMarginShorthand",
@@ -2649,7 +2644,6 @@
{
name: "scroll-margin-bottom",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "primitive",
default_value: "0.0f",
@@ -2660,7 +2654,6 @@
{
name: "scroll-margin-inline-end",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
direction_aware_options: {
logical_side: "end",
shorthand_for_physical_side: "scrollMarginShorthand",
@@ -2670,7 +2663,6 @@
{
name: "scroll-margin-inline-start",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
direction_aware_options: {
logical_side: "start",
shorthand_for_physical_side: "scrollMarginShorthand",
@@ -2680,7 +2672,6 @@
{
name: "scroll-margin-left",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "primitive",
default_value: "0.0f",
@@ -2691,7 +2682,6 @@
{
name: "scroll-margin-right",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "primitive",
default_value: "0.0f",
@@ -2702,7 +2692,6 @@
{
name: "scroll-margin-top",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "primitive",
default_value: "0.0f",
@@ -2713,8 +2702,7 @@
{
name: "scroll-padding-block-end",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
- include_paths: ["third_party/blink/renderer/platform/length.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length.h"],
typedom_types: ["Keyword", "Length", "Percentage"],
type_name: "Length",
converter: "ConvertLength",
@@ -2726,8 +2714,7 @@
{
name: "scroll-padding-block-start",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
- include_paths: ["third_party/blink/renderer/platform/length.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length.h"],
typedom_types: ["Keyword", "Length", "Percentage"],
type_name: "Length",
converter: "ConvertLength",
@@ -2739,7 +2726,6 @@
{
name: "scroll-padding-bottom",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "<length>",
default_value: "Length()",
@@ -2749,8 +2735,7 @@
{
name: "scroll-padding-inline-end",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
- include_paths: ["third_party/blink/renderer/platform/length.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length.h"],
typedom_types: ["Keyword", "Length", "Percentage"],
type_name: "Length",
converter: "ConvertLength",
@@ -2762,8 +2747,7 @@
{
name: "scroll-padding-inline-start",
property_methods: ["ParseSingleValue"],
- runtime_flag: "CSSScrollSnapPoints",
- include_paths: ["third_party/blink/renderer/platform/length.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length.h"],
typedom_types: ["Keyword", "Length", "Percentage"],
type_name: "Length",
converter: "ConvertLength",
@@ -2775,7 +2759,6 @@
{
name: "scroll-padding-left",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "<length>",
default_value: "Length()",
@@ -2785,7 +2768,6 @@
{
name: "scroll-padding-right",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "<length>",
default_value: "Length()",
@@ -2795,7 +2777,6 @@
{
name: "scroll-padding-top",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "<length>",
default_value: "Length()",
@@ -2805,7 +2786,6 @@
{
name: "scroll-snap-align",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "external",
include_paths: ["third_party/blink/renderer/platform/scroll/scroll_snap_data.h"],
@@ -2819,7 +2799,6 @@
{
name: "scroll-snap-stop",
property_methods: ["CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_template: "keyword",
keywords: ["normal", "always"],
default_value: "normal",
@@ -2828,7 +2807,6 @@
{
name: "scroll-snap-type",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
field_group: "*",
field_template: "external",
include_paths: ["third_party/blink/renderer/platform/scroll/scroll_snap_data.h"],
@@ -2915,7 +2893,7 @@
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
interpolable: true,
svg: true,
- converter: "ConvertNumberOrPercentage",
+ converter: "ConvertAlpha",
typedom_types: ["Number"]
},
{
@@ -2989,7 +2967,7 @@
interpolable: true,
inherited: true,
svg: true,
- converter: "ConvertNumberOrPercentage",
+ converter: "ConvertAlpha",
typedom_types: ["Number"]
},
{
@@ -3567,7 +3545,7 @@
interpolable: true,
field_group: "*",
field_template: "external",
- include_paths: ["third_party/blink/renderer/platform/layout_unit.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/layout_unit.h"],
default_value: "LayoutUnit(3)",
type_name: "LayoutUnit",
computed_style_custom_functions: ["initial", "getter", "setter"],
@@ -4918,19 +4896,16 @@
name: "scroll-margin",
longhands: ["scroll-margin-top", "scroll-margin-right", "scroll-margin-bottom", "scroll-margin-left"],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
},
{
name: "scroll-margin-block",
longhands: ["scroll-margin-block-start", "scroll-margin-block-end"],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
},
{
name: "scroll-margin-inline",
longhands: ["scroll-margin-inline-start", "scroll-margin-inline-end"],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
},
{
name: "scroll-padding",
@@ -4939,19 +4914,16 @@
"scroll-padding-left"
],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
},
{
name: "scroll-padding-block",
longhands: ["scroll-padding-block-start", "scroll-padding-block-end"],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
},
{
name: "scroll-padding-inline",
longhands: ["scroll-padding-inline-start", "scroll-padding-inline-end"],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
- runtime_flag: "CSSScrollSnapPoints",
},
{
name: "text-decoration",
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_equality.h b/chromium/third_party/blink/renderer/core/css/css_property_equality.h
index 0e48b7c4f07..33fe623e74f 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_equality.h
+++ b/chromium/third_party/blink/renderer/core/css/css_property_equality.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_EQUALITY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_EQUALITY_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_id_templates.h b/chromium/third_party/blink/renderer/core/css/css_property_id_templates.h
index 8f326764079..ac0f2f50be1 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_id_templates.h
+++ b/chromium/third_party/blink/renderer/core/css/css_property_id_templates.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_ID_TEMPLATES_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_ID_TEMPLATES_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_name.cc b/chromium/third_party/blink/renderer/core/css/css_property_name.cc
new file mode 100644
index 00000000000..a268c6772e3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_name.cc
@@ -0,0 +1,30 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+
+#include "third_party/blink/renderer/core/css/properties/css_property.h"
+
+namespace blink {
+
+namespace {
+
+// TODO(andruud): Reduce this to sizeof(void*).
+struct SameSizeAsCSSPropertyName {
+ CSSPropertyID property_id_;
+ AtomicString custom_property_name_;
+};
+
+static_assert(sizeof(CSSPropertyName) == sizeof(SameSizeAsCSSPropertyName),
+ "CSSPropertyName should stay small");
+
+} // namespace
+
+AtomicString CSSPropertyName::ToAtomicString() const {
+ if (IsCustomProperty())
+ return custom_property_name_;
+ return CSSProperty::Get(property_id_).GetPropertyNameAtomicString();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_name.h b/chromium/third_party/blink/renderer/core/css/css_property_name.h
new file mode 100644
index 00000000000..517dd73599d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_name.h
@@ -0,0 +1,44 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_NAME_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_NAME_H_
+
+#include "third_party/blink/renderer/core/css/css_property_names.h"
+#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
+
+namespace blink {
+
+// This class may be used to represent the name of any valid CSS property,
+// including custom properties.
+class CORE_EXPORT CSSPropertyName {
+ DISALLOW_NEW();
+
+ public:
+ explicit CSSPropertyName(CSSPropertyID property_id)
+ : property_id_(property_id) {
+ DCHECK_NE(property_id, CSSPropertyInvalid);
+ DCHECK_NE(property_id, CSSPropertyVariable);
+ }
+
+ explicit CSSPropertyName(const AtomicString& custom_property_name)
+ : property_id_(CSSPropertyVariable),
+ custom_property_name_(custom_property_name) {
+ DCHECK(!custom_property_name.IsNull());
+ }
+
+ CSSPropertyID Id() const { return property_id_; }
+
+ bool IsCustomProperty() const { return property_id_ == CSSPropertyVariable; }
+
+ AtomicString ToAtomicString() const;
+
+ private:
+ CSSPropertyID property_id_;
+ AtomicString custom_property_name_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_NAME_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_name_test.cc b/chromium/third_party/blink/renderer/core/css/css_property_name_test.cc
new file mode 100644
index 00000000000..7dd12abe1dc
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_name_test.cc
@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace blink {
+
+TEST(CSSPropertyNameTest, IdStandardProperty) {
+ CSSPropertyName name(CSSPropertyFontSize);
+ EXPECT_EQ(CSSPropertyFontSize, name.Id());
+}
+
+TEST(CSSPropertyNameTest, IdCustomProperty) {
+ CSSPropertyName name(AtomicString("--x"));
+ EXPECT_EQ(CSSPropertyVariable, name.Id());
+ EXPECT_TRUE(name.IsCustomProperty());
+}
+
+TEST(CSSPropertyNameTest, GetNameStandardProperty) {
+ CSSPropertyName name(CSSPropertyFontSize);
+ EXPECT_EQ(AtomicString("font-size"), name.ToAtomicString());
+}
+
+TEST(CSSPropertyNameTest, GetNameCustomProperty) {
+ CSSPropertyName name(AtomicString("--x"));
+ EXPECT_EQ(AtomicString("--x"), name.ToAtomicString());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_value.cc b/chromium/third_party/blink/renderer/core/css/css_property_value.cc
index 8d7ee819a7e..8d9162ecd74 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_property_value.cc
@@ -20,6 +20,8 @@
#include "third_party/blink/renderer/core/css/css_property_value.h"
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
@@ -46,6 +48,12 @@ CSSPropertyID CSSPropertyValueMetadata::ShorthandID() const {
return shorthands.at(index_in_shorthands_vector_).id();
}
+CSSPropertyName CSSPropertyValue::Name() const {
+ if (Id() != CSSPropertyVariable)
+ return CSSPropertyName(Id());
+ return CSSPropertyName(ToCSSCustomPropertyDeclaration(value_)->GetName());
+}
+
bool CSSPropertyValue::operator==(const CSSPropertyValue& other) const {
return DataEquivalent(value_, other.value_) &&
IsImportant() == other.IsImportant();
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_value.h b/chromium/third_party/blink/renderer/core/css/css_property_value.h
index 431b1bcbf2f..d956eb9dbd2 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_property_value.h
@@ -21,9 +21,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_VALUE_H_
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -86,6 +87,7 @@ class CSSPropertyValue {
bool IsSetFromShorthand() const { return metadata_.is_set_from_shorthand_; }
CSSPropertyID ShorthandID() const { return metadata_.ShorthandID(); }
bool IsImportant() const { return metadata_.important_; }
+ CSSPropertyName Name() const;
const CSSValue* Value() const { return value_.Get(); }
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_value_set.cc b/chromium/third_party/blink/renderer/core/css/css_property_value_set.cc
index 25f487820f2..97ca29e6f06 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_value_set.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_property_value_set.cc
@@ -59,6 +59,12 @@ ImmutableCSSPropertyValueSet* ImmutableCSSPropertyValueSet::Create(
ImmutableCSSPropertyValueSet(properties, count, css_parser_mode);
}
+CSSPropertyName CSSPropertyValueSet::PropertyReference::Name() const {
+ if (Id() != CSSPropertyVariable)
+ return CSSPropertyName(Id());
+ return CSSPropertyName(ToCSSCustomPropertyDeclaration(Value()).GetName());
+}
+
ImmutableCSSPropertyValueSet* CSSPropertyValueSet::ImmutableCopyIfNeeded()
const {
if (!IsMutable()) {
@@ -410,12 +416,8 @@ void MutableCSSPropertyValueSet::SetProperty(CSSPropertyID property_id,
bool MutableCSSPropertyValueSet::SetProperty(const CSSPropertyValue& property,
CSSPropertyValue* slot) {
- const AtomicString& name =
- (property.Id() == CSSPropertyVariable)
- ? ToCSSCustomPropertyDeclaration(property.Value())->GetName()
- : g_null_atom;
CSSPropertyValue* to_replace =
- slot ? slot : FindCSSPropertyWithID(property.Id(), name);
+ slot ? slot : FindCSSPropertyWithName(property.Name());
if (to_replace && *to_replace == property)
return false;
if (to_replace) {
@@ -479,8 +481,7 @@ void MutableCSSPropertyValueSet::MergeAndOverrideOnConflict(
unsigned size = other->PropertyCount();
for (unsigned n = 0; n < size; ++n) {
PropertyReference to_merge = other->PropertyAt(n);
- // TODO(leviw): This probably doesn't work correctly with Custom Properties
- CSSPropertyValue* old = FindCSSPropertyWithID(to_merge.Id());
+ CSSPropertyValue* old = FindCSSPropertyWithName(to_merge.Name());
if (old) {
SetProperty(
CSSPropertyValue(to_merge.PropertyMetadata(), to_merge.Value()), old);
@@ -537,18 +538,11 @@ bool MutableCSSPropertyValueSet::RemovePropertiesInSet(const CSSProperty** set,
return false;
}
-CSSPropertyValue* MutableCSSPropertyValueSet::FindCSSPropertyWithID(
- CSSPropertyID property_id,
- const AtomicString& custom_property_name) {
- int found_property_index = -1;
- if (property_id == CSSPropertyVariable && !custom_property_name.IsNull()) {
- // TODO(shanestephens): fix call sites so we always have a
- // customPropertyName here.
- found_property_index = FindPropertyIndex(custom_property_name);
- } else {
- DCHECK(custom_property_name.IsNull());
- found_property_index = FindPropertyIndex(property_id);
- }
+CSSPropertyValue* MutableCSSPropertyValueSet::FindCSSPropertyWithName(
+ const CSSPropertyName& name) {
+ int found_property_index = name.IsCustomProperty()
+ ? FindPropertyIndex(name.ToAtomicString())
+ : FindPropertyIndex(name.Id());
if (found_property_index == -1)
return nullptr;
return &property_vector_.at(found_property_index);
@@ -592,7 +586,7 @@ void MutableCSSPropertyValueSet::RemoveEquivalentProperties(
}
MutableCSSPropertyValueSet* CSSPropertyValueSet::MutableCopy() const {
- return new MutableCSSPropertyValueSet(*this);
+ return MakeGarbageCollected<MutableCSSPropertyValueSet>(*this);
}
MutableCSSPropertyValueSet* CSSPropertyValueSet::CopyPropertiesInSet(
@@ -617,7 +611,7 @@ CSSStyleDeclaration* MutableCSSPropertyValueSet::EnsureCSSStyleDeclaration() {
DCHECK(!cssom_wrapper_->ParentElement());
return cssom_wrapper_.Get();
}
- cssom_wrapper_ = new PropertySetCSSStyleDeclaration(*this);
+ cssom_wrapper_ = MakeGarbageCollected<PropertySetCSSStyleDeclaration>(*this);
return cssom_wrapper_.Get();
}
@@ -670,13 +664,13 @@ void CSSPropertyValueSet::ShowStyle() {
MutableCSSPropertyValueSet* MutableCSSPropertyValueSet::Create(
CSSParserMode css_parser_mode) {
- return new MutableCSSPropertyValueSet(css_parser_mode);
+ return MakeGarbageCollected<MutableCSSPropertyValueSet>(css_parser_mode);
}
MutableCSSPropertyValueSet* MutableCSSPropertyValueSet::Create(
const CSSPropertyValue* properties,
unsigned count) {
- return new MutableCSSPropertyValueSet(properties, count);
+ return MakeGarbageCollected<MutableCSSPropertyValueSet>(properties, count);
}
void CSSLazyPropertyParser::Trace(blink::Visitor* visitor) {}
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_value_set.h b/chromium/third_party/blink/renderer/core/css/css_property_value_set.h
index 80f1a4ca7bf..dc8810152ea 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_value_set.h
+++ b/chromium/third_party/blink/renderer/core/css/css_property_value_set.h
@@ -24,10 +24,11 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
#include "third_party/blink/renderer/core/css/property_set_css_style_declaration.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -67,6 +68,8 @@ class CORE_EXPORT CSSPropertyValueSet
return PropertyMetadata().ShorthandID();
}
+ CSSPropertyName Name() const;
+
bool IsImportant() const { return PropertyMetadata().important_; }
bool IsInherited() const { return PropertyMetadata().inherited_; }
bool IsImplicit() const { return PropertyMetadata().implicit_; }
@@ -175,7 +178,11 @@ class CSSLazyPropertyParser
class CORE_EXPORT ImmutableCSSPropertyValueSet : public CSSPropertyValueSet {
public:
+ ImmutableCSSPropertyValueSet(const CSSPropertyValue*,
+ unsigned count,
+ CSSParserMode);
~ImmutableCSSPropertyValueSet();
+
static ImmutableCSSPropertyValueSet*
Create(const CSSPropertyValue* properties, unsigned count, CSSParserMode);
@@ -192,11 +199,6 @@ class CORE_EXPORT ImmutableCSSPropertyValueSet : public CSSPropertyValueSet {
void* operator new(std::size_t, void* location) { return location; }
void* storage_;
-
- private:
- ImmutableCSSPropertyValueSet(const CSSPropertyValue*,
- unsigned count,
- CSSParserMode);
};
inline const Member<const CSSValue>* ImmutableCSSPropertyValueSet::ValueArray()
@@ -220,7 +222,12 @@ DEFINE_TYPE_CASTS(ImmutableCSSPropertyValueSet,
class CORE_EXPORT MutableCSSPropertyValueSet : public CSSPropertyValueSet {
public:
+ explicit MutableCSSPropertyValueSet(CSSParserMode);
+ explicit MutableCSSPropertyValueSet(const CSSPropertyValueSet&);
+ MutableCSSPropertyValueSet(const CSSPropertyValue* properties,
+ unsigned count);
~MutableCSSPropertyValueSet() = default;
+
static MutableCSSPropertyValueSet* Create(CSSParserMode);
static MutableCSSPropertyValueSet* Create(const CSSPropertyValue* properties,
unsigned count);
@@ -277,20 +284,13 @@ class CORE_EXPORT MutableCSSPropertyValueSet : public CSSPropertyValueSet {
void TraceAfterDispatch(blink::Visitor*);
private:
- explicit MutableCSSPropertyValueSet(CSSParserMode);
- explicit MutableCSSPropertyValueSet(const CSSPropertyValueSet&);
- MutableCSSPropertyValueSet(const CSSPropertyValue* properties,
- unsigned count);
-
bool RemovePropertyAtIndex(int, String* return_text);
bool RemoveShorthandProperty(CSSPropertyID);
bool RemoveShorthandProperty(const AtomicString& custom_property_name) {
return false;
}
- CSSPropertyValue* FindCSSPropertyWithID(
- CSSPropertyID,
- const AtomicString& custom_property_name = g_null_atom);
+ CSSPropertyValue* FindCSSPropertyWithName(const CSSPropertyName&);
Member<PropertySetCSSStyleDeclaration> cssom_wrapper_;
friend class CSSPropertyValueSet;
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_value_set_test.cc b/chromium/third_party/blink/renderer/core/css/css_property_value_set_test.cc
new file mode 100644
index 00000000000..5c8e384b1f7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_value_set_test.cc
@@ -0,0 +1,67 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_property_value_set.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
+#include "third_party/blink/renderer/core/css/style_rule.h"
+#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+
+namespace blink {
+
+class CSSPropertyValueSetTest : public PageTestBase {
+ public:
+ StyleRule* RuleAt(StyleSheetContents* sheet, wtf_size_t index) {
+ return ToStyleRule(sheet->ChildRules()[index]);
+ }
+};
+
+TEST_F(CSSPropertyValueSetTest, MergeAndOverrideOnConflictCustomProperty) {
+ CSSParserContext* context = CSSParserContext::Create(GetDocument());
+ StyleSheetContents* style_sheet = StyleSheetContents::Create(context);
+
+ String sheet_text = R"CSS(
+ #first {
+ color: red;
+ --x:foo;
+ --y:foo;
+ }
+ #second {
+ color: green;
+ --x:bar;
+ --y:bar;
+ }
+ )CSS";
+
+ CSSParser::ParseSheet(context, style_sheet, sheet_text,
+ CSSDeferPropertyParsing::kNo);
+ StyleRule* rule0 = RuleAt(style_sheet, 0);
+ StyleRule* rule1 = RuleAt(style_sheet, 1);
+ MutableCSSPropertyValueSet& set0 = rule0->MutableProperties();
+ MutableCSSPropertyValueSet& set1 = rule1->MutableProperties();
+
+ EXPECT_EQ(3u, set0.PropertyCount());
+ EXPECT_EQ("red", set0.GetPropertyValue(CSSPropertyColor));
+ EXPECT_EQ("foo", set0.GetPropertyValue(AtomicString("--x")));
+ EXPECT_EQ("foo", set0.GetPropertyValue(AtomicString("--y")));
+ EXPECT_EQ(3u, set1.PropertyCount());
+ EXPECT_EQ("green", set1.GetPropertyValue(CSSPropertyColor));
+ EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--x")));
+ EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--y")));
+
+ set0.MergeAndOverrideOnConflict(&set1);
+
+ EXPECT_EQ(3u, set0.PropertyCount());
+ EXPECT_EQ("green", set0.GetPropertyValue(CSSPropertyColor));
+ EXPECT_EQ("bar", set0.GetPropertyValue(AtomicString("--x")));
+ EXPECT_EQ("bar", set0.GetPropertyValue(AtomicString("--y")));
+ EXPECT_EQ(3u, set1.PropertyCount());
+ EXPECT_EQ("green", set1.GetPropertyValue(CSSPropertyColor));
+ EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--x")));
+ EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--y")));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_quad_value.h b/chromium/third_party/blink/renderer/core/css/css_quad_value.h
index dffd9412bcb..dc6718c1f88 100644
--- a/chromium/third_party/blink/renderer/core/css/css_quad_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_quad_value.h
@@ -36,9 +36,22 @@ class CORE_EXPORT CSSQuadValue : public CSSValue {
CSSValue* bottom,
CSSValue* left,
TypeForSerialization serialization_type) {
- return new CSSQuadValue(top, right, bottom, left, serialization_type);
+ return MakeGarbageCollected<CSSQuadValue>(top, right, bottom, left,
+ serialization_type);
}
+ CSSQuadValue(CSSValue* top,
+ CSSValue* right,
+ CSSValue* bottom,
+ CSSValue* left,
+ TypeForSerialization serialization_type)
+ : CSSValue(kQuadClass),
+ serialization_type_(serialization_type),
+ top_(top),
+ right_(right),
+ bottom_(bottom),
+ left_(left) {}
+
CSSValue* Top() const { return top_.Get(); }
CSSValue* Right() const { return right_.Get(); }
CSSValue* Bottom() const { return bottom_.Get(); }
@@ -57,19 +70,6 @@ class CORE_EXPORT CSSQuadValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
- protected:
- CSSQuadValue(CSSValue* top,
- CSSValue* right,
- CSSValue* bottom,
- CSSValue* left,
- TypeForSerialization serialization_type)
- : CSSValue(kQuadClass),
- serialization_type_(serialization_type),
- top_(top),
- right_(right),
- bottom_(bottom),
- left_(left) {}
-
private:
TypeForSerialization serialization_type_;
Member<CSSValue> top_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_ray_value.cc b/chromium/third_party/blink/renderer/core/css/css_ray_value.cc
index 9fc1f9289ad..01f870cc6c3 100644
--- a/chromium/third_party/blink/renderer/core/css/css_ray_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_ray_value.cc
@@ -14,7 +14,7 @@ namespace cssvalue {
CSSRayValue* CSSRayValue::Create(const CSSPrimitiveValue& angle,
const CSSIdentifierValue& size,
const CSSIdentifierValue* contain) {
- return new CSSRayValue(angle, size, contain);
+ return MakeGarbageCollected<CSSRayValue>(angle, size, contain);
}
CSSRayValue::CSSRayValue(const CSSPrimitiveValue& angle,
diff --git a/chromium/third_party/blink/renderer/core/css/css_ray_value.h b/chromium/third_party/blink/renderer/core/css/css_ray_value.h
index 0abb78c7dd8..261abf9a81c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_ray_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_ray_value.h
@@ -20,6 +20,10 @@ class CSSRayValue : public CSSValue {
const CSSIdentifierValue& size,
const CSSIdentifierValue* contain);
+ CSSRayValue(const CSSPrimitiveValue& angle,
+ const CSSIdentifierValue& size,
+ const CSSIdentifierValue* contain);
+
const CSSPrimitiveValue& Angle() const { return *angle_; }
const CSSIdentifierValue& Size() const { return *size_; }
const CSSIdentifierValue* Contain() const { return contain_.Get(); }
@@ -31,10 +35,6 @@ class CSSRayValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSRayValue(const CSSPrimitiveValue& angle,
- const CSSIdentifierValue& size,
- const CSSIdentifierValue* contain);
-
Member<const CSSPrimitiveValue> angle_;
Member<const CSSIdentifierValue> size_;
Member<const CSSIdentifierValue> contain_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_reflect_value.h b/chromium/third_party/blink/renderer/core/css/css_reflect_value.h
index 4df6bf54b7f..f299357094a 100644
--- a/chromium/third_party/blink/renderer/core/css/css_reflect_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_reflect_value.h
@@ -41,9 +41,17 @@ class CSSReflectValue : public CSSValue {
static CSSReflectValue* Create(CSSIdentifierValue* direction,
CSSPrimitiveValue* offset,
CSSValue* mask) {
- return new CSSReflectValue(direction, offset, mask);
+ return MakeGarbageCollected<CSSReflectValue>(direction, offset, mask);
}
+ CSSReflectValue(CSSIdentifierValue* direction,
+ CSSPrimitiveValue* offset,
+ CSSValue* mask)
+ : CSSValue(kReflectClass),
+ direction_(direction),
+ offset_(offset),
+ mask_(mask) {}
+
CSSIdentifierValue* Direction() const { return direction_.Get(); }
CSSPrimitiveValue* Offset() const { return offset_.Get(); }
CSSValue* Mask() const { return mask_.Get(); }
@@ -55,14 +63,6 @@ class CSSReflectValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSReflectValue(CSSIdentifierValue* direction,
- CSSPrimitiveValue* offset,
- CSSValue* mask)
- : CSSValue(kReflectClass),
- direction_(direction),
- offset_(offset),
- mask_(mask) {}
-
Member<CSSIdentifierValue> direction_;
Member<CSSPrimitiveValue> offset_;
Member<CSSValue> mask_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_rule.h b/chromium/third_party/blink/renderer/core/css/css_rule.h
index 5e733cbffe7..917dadf01fd 100644
--- a/chromium/third_party/blink/renderer/core/css/css_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_rule.h
@@ -53,6 +53,7 @@ class CORE_EXPORT CSSRule : public ScriptWrappable {
kKeyframeRule = 8,
kNamespaceRule = 10,
kSupportsRule = 12,
+ kFontFeatureValuesRule = 14,
kViewportRule = 15,
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_rule.idl b/chromium/third_party/blink/renderer/core/css/css_rule.idl
index 6de5c973d76..49e771e6df0 100644
--- a/chromium/third_party/blink/renderer/core/css/css_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_rule.idl
@@ -46,6 +46,10 @@
// https://drafts.csswg.org/css-conditional/#extentions-to-cssrule-interface
const unsigned short SUPPORTS_RULE = 12;
+ // CSS Fonts Level 4
+ // https://drafts.csswg.org/css-fonts-4/#font-feature-values
+ [RuntimeEnabled=CSSFontFeatureValues] const unsigned short FONT_FEATURE_VALUES_RULE = 14;
+
// CSS Device Adaptation
// https://drafts.csswg.org/css-device-adapt/#css-rule-interface
[RuntimeEnabled=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
diff --git a/chromium/third_party/blink/renderer/core/css/css_rule_list.h b/chromium/third_party/blink/renderer/core/css/css_rule_list.h
index dd02709d921..8f208c9d77e 100644
--- a/chromium/third_party/blink/renderer/core/css/css_rule_list.h
+++ b/chromium/third_party/blink/renderer/core/css/css_rule_list.h
@@ -51,7 +51,11 @@ class CSSRuleList : public ScriptWrappable {
class StaticCSSRuleList final : public CSSRuleList {
public:
- static StaticCSSRuleList* Create() { return new StaticCSSRuleList(); }
+ static StaticCSSRuleList* Create() {
+ return MakeGarbageCollected<StaticCSSRuleList>();
+ }
+
+ StaticCSSRuleList();
HeapVector<Member<CSSRule>>& Rules() { return rules_; }
@@ -60,8 +64,6 @@ class StaticCSSRuleList final : public CSSRuleList {
void Trace(blink::Visitor*) override;
private:
- StaticCSSRuleList();
-
unsigned length() const override { return rules_.size(); }
CSSRule* item(unsigned index) const override {
return index < rules_.size() ? rules_[index].Get() : nullptr;
@@ -74,17 +76,17 @@ template <class Rule>
class LiveCSSRuleList final : public CSSRuleList {
public:
static LiveCSSRuleList* Create(Rule* rule) {
- return new LiveCSSRuleList(rule);
+ return MakeGarbageCollected<LiveCSSRuleList>(rule);
}
+ LiveCSSRuleList(Rule* rule) : rule_(rule) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(rule_);
CSSRuleList::Trace(visitor);
}
private:
- LiveCSSRuleList(Rule* rule) : rule_(rule) {}
-
unsigned length() const override { return rule_->length(); }
CSSRule* item(unsigned index) const override { return rule_->Item(index); }
CSSStyleSheet* GetStyleSheet() const override {
diff --git a/chromium/third_party/blink/renderer/core/css/css_segmented_font_face.h b/chromium/third_party/blink/renderer/core/css/css_segmented_font_face.h
index f521100cade..ff69a70a037 100644
--- a/chromium/third_party/blink/renderer/core/css/css_segmented_font_face.h
+++ b/chromium/third_party/blink/renderer/core/css/css_segmented_font_face.h
@@ -47,8 +47,11 @@ class CSSSegmentedFontFace final
public:
static CSSSegmentedFontFace* Create(
FontSelectionCapabilities font_selection_capabilities) {
- return new CSSSegmentedFontFace(font_selection_capabilities);
+ return MakeGarbageCollected<CSSSegmentedFontFace>(
+ font_selection_capabilities);
}
+
+ CSSSegmentedFontFace(FontSelectionCapabilities);
~CSSSegmentedFontFace();
FontSelectionCapabilities GetFontSelectionCapabilities() const {
@@ -76,8 +79,6 @@ class CSSSegmentedFontFace final
void Trace(blink::Visitor*);
private:
- CSSSegmentedFontFace(FontSelectionCapabilities);
-
void PruneTable();
bool IsValid() const;
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector.cc b/chromium/third_party/blink/renderer/core/css/css_selector.cc
index 58b9234b3a3..8b651b9b6d0 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_selector.cc
@@ -44,8 +44,6 @@
namespace blink {
-using namespace HTMLNames;
-
struct SameSizeAsCSSSelector {
unsigned bitfields;
void* pointers[1];
@@ -118,7 +116,7 @@ inline unsigned CSSSelector::SpecificityForOneSelector() const {
// FIXME: PseudoAny should base the specificity on the sub-selectors.
// See http://lists.w3.org/Archives/Public/www-style/2010Sep/0530.html
case kPseudoAny:
- case kPseudoMatches:
+ case kPseudoIs:
default:
break;
}
@@ -217,8 +215,8 @@ PseudoId CSSSelector::GetPseudoId(PseudoType type) {
case kPseudoLink:
case kPseudoVisited:
case kPseudoAny:
- case kPseudoMatches:
- case kPseudoIS:
+ case kPseudoIs:
+ case kPseudoWhere:
case kPseudoAnyLink:
case kPseudoWebkitAnyLink:
case kPseudoAutofill:
@@ -399,9 +397,8 @@ const static NameToPseudoStruct kPseudoTypeWithArgumentsMap[] = {
{"cue", CSSSelector::kPseudoCue},
{"host", CSSSelector::kPseudoHost},
{"host-context", CSSSelector::kPseudoHostContext},
- {"is", CSSSelector::kPseudoIS},
+ {"is", CSSSelector::kPseudoIs},
{"lang", CSSSelector::kPseudoLang},
- {"matches", CSSSelector::kPseudoMatches},
{"not", CSSSelector::kPseudoNot},
{"nth-child", CSSSelector::kPseudoNthChild},
{"nth-last-child", CSSSelector::kPseudoNthLastChild},
@@ -409,24 +406,7 @@ const static NameToPseudoStruct kPseudoTypeWithArgumentsMap[] = {
{"nth-of-type", CSSSelector::kPseudoNthOfType},
{"part", CSSSelector::kPseudoPart},
{"slotted", CSSSelector::kPseudoSlotted},
-};
-
-class NameToPseudoCompare {
- public:
- NameToPseudoCompare(const AtomicString& key) : key_(key) {
- DCHECK(key_.Is8Bit());
- }
-
- bool operator()(const NameToPseudoStruct& entry, const NameToPseudoStruct&) {
- DCHECK(entry.string);
- const char* key = reinterpret_cast<const char*>(key_.Characters8());
- // If strncmp returns 0, then either the keys are equal, or |key_| sorts
- // before |entry|.
- return strncmp(entry.string, key, key_.length()) < 0;
- }
-
- private:
- const AtomicString& key_;
+ {"where", CSSSelector::kPseudoWhere},
};
static CSSSelector::PseudoType NameToPseudoType(const AtomicString& name,
@@ -445,10 +425,17 @@ static CSSSelector::PseudoType NameToPseudoType(const AtomicString& name,
pseudo_type_map_end = kPseudoTypeWithoutArgumentsMap +
arraysize(kPseudoTypeWithoutArgumentsMap);
}
- NameToPseudoStruct dummy_key = {nullptr, CSSSelector::kPseudoUnknown};
- const NameToPseudoStruct* match =
- std::lower_bound(pseudo_type_map, pseudo_type_map_end, dummy_key,
- NameToPseudoCompare(name));
+ const NameToPseudoStruct* match = std::lower_bound(
+ pseudo_type_map, pseudo_type_map_end, name,
+ [](const NameToPseudoStruct& entry, const AtomicString& name) -> bool {
+ DCHECK(name.Is8Bit());
+ DCHECK(entry.string);
+ // If strncmp returns 0, then either the keys are equal, or |name| sorts
+ // before |entry|.
+ return strncmp(entry.string,
+ reinterpret_cast<const char*>(name.Characters8()),
+ name.length()) < 0;
+ });
if (match == pseudo_type_map_end || match->string != name.GetString())
return CSSSelector::kPseudoUnknown;
@@ -619,12 +606,12 @@ void CSSSelector::UpdatePseudoType(const AtomicString& value,
case kPseudoIncrement:
case kPseudoIndeterminate:
case kPseudoInvalid:
- case kPseudoIS:
+ case kPseudoWhere:
case kPseudoLang:
case kPseudoLastChild:
case kPseudoLastOfType:
case kPseudoLink:
- case kPseudoMatches:
+ case kPseudoIs:
case kPseudoNoButton:
case kPseudoNot:
case kPseudoNthChild:
@@ -770,8 +757,8 @@ const CSSSelector* CSSSelector::SerializeCompound(
case kPseudoHost:
case kPseudoHostContext:
case kPseudoAny:
- case kPseudoMatches:
- case kPseudoIS:
+ case kPseudoIs:
+ case kPseudoWhere:
break;
default:
break;
@@ -1049,6 +1036,12 @@ bool CSSSelector::MatchesPseudoElement() const {
return false;
}
+bool CSSSelector::IsTreeAbidingPseudoElement() const {
+ return Match() == CSSSelector::kPseudoElement &&
+ (GetPseudoType() == kPseudoBefore || GetPseudoType() == kPseudoAfter ||
+ GetPseudoType() == kPseudoPlaceholder);
+}
+
template <typename Functor>
static bool ForAnyInTagHistory(const Functor& functor,
const CSSSelector& selector) {
@@ -1102,17 +1095,17 @@ bool CSSSelector::NeedsUpdatedDistribution() const {
*this);
}
-bool CSSSelector::HasPseudoMatches() const {
+bool CSSSelector::HasPseudoIs() const {
for (const CSSSelector* s = this; s; s = s->TagHistory()) {
- if (s->GetPseudoType() == CSSSelector::kPseudoMatches)
+ if (s->GetPseudoType() == CSSSelector::kPseudoIs)
return true;
}
return false;
}
-bool CSSSelector::HasPseudoIS() const {
+bool CSSSelector::HasPseudoWhere() const {
for (const CSSSelector* s = this; s; s = s->TagHistory()) {
- if (s->GetPseudoType() == CSSSelector::kPseudoIS)
+ if (s->GetPseudoType() == CSSSelector::kPseudoWhere)
return true;
}
return false;
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector.h b/chromium/third_party/blink/renderer/core/css/css_selector.h
index b32eb9ed14d..72f1d831db9 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector.h
+++ b/chromium/third_party/blink/renderer/core/css/css_selector.h
@@ -163,8 +163,8 @@ class CORE_EXPORT CSSSelector {
kPseudoLink,
kPseudoVisited,
kPseudoAny,
- kPseudoMatches,
- kPseudoIS,
+ kPseudoIs,
+ kPseudoWhere,
kPseudoAnyLink,
kPseudoWebkitAnyLink,
kPseudoAutofill,
@@ -380,13 +380,14 @@ class CORE_EXPORT CSSSelector {
}
bool MatchesPseudoElement() const;
+ bool IsTreeAbidingPseudoElement() const;
bool HasContentPseudo() const;
bool HasSlottedPseudo() const;
bool HasDeepCombinatorOrShadowPseudo() const;
bool NeedsUpdatedDistribution() const;
- bool HasPseudoMatches() const;
- bool HasPseudoIS() const;
+ bool HasPseudoIs() const;
+ bool HasPseudoWhere() const;
private:
unsigned relation_ : 4; // enum RelationType
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector_list.cc b/chromium/third_party/blink/renderer/core/css/css_selector_list.cc
index ac9ac12e768..5a4542f40d1 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector_list.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_selector_list.cc
@@ -122,7 +122,7 @@ void AddToList(CSSSelector*& destination,
if (!selector_to_expand->IsLastInTagHistory())
destination->SetLastInTagHistory(false);
}
- if (selector_to_expand->GetPseudoType() == CSSSelector::kPseudoIS ||
+ if (selector_to_expand->GetPseudoType() == CSSSelector::kPseudoWhere ||
selector_to_expand->IgnoreSpecificity())
destination->SetIgnoreSpecificity(true);
destination->SetLastInSelectorList(false);
@@ -139,8 +139,8 @@ CSSSelectorList CSSSelectorList::ExpandedFirstPseudoClass() const {
size_t i = 0;
CSSSelectorList transformed = this->Copy();
- while (!selector_boundaries[i]->HasPseudoMatches() &&
- !selector_boundaries[i]->HasPseudoIS())
+ while (!selector_boundaries[i]->HasPseudoIs() &&
+ !selector_boundaries[i]->HasPseudoWhere())
++i;
const CSSSelector* selector_to_expand_begin = selector_boundaries[i];
@@ -149,8 +149,8 @@ CSSSelectorList CSSSelectorList::ExpandedFirstPseudoClass() const {
static_cast<unsigned>(selector_to_expand_end - selector_to_expand_begin);
const CSSSelector* simple_selector = selector_to_expand_begin;
- while (simple_selector->GetPseudoType() != CSSSelector::kPseudoMatches &&
- simple_selector->GetPseudoType() != CSSSelector::kPseudoIS) {
+ while (simple_selector->GetPseudoType() != CSSSelector::kPseudoIs &&
+ simple_selector->GetPseudoType() != CSSSelector::kPseudoWhere) {
simple_selector = simple_selector->TagHistory();
}
@@ -217,17 +217,17 @@ CSSSelectorList CSSSelectorList::TransformForListExpansion() {
return CSSSelectorList::ConcatenateListExpansion(transformed, *this);
}
-bool CSSSelectorList::HasPseudoMatches() const {
+bool CSSSelectorList::HasPseudoIs() const {
for (const CSSSelector* s = FirstForCSSOM(); s; s = Next(*s)) {
- if (s->HasPseudoMatches())
+ if (s->HasPseudoIs())
return true;
}
return false;
}
-bool CSSSelectorList::HasPseudoIS() const {
+bool CSSSelectorList::HasPseudoWhere() const {
for (const CSSSelector* s = FirstForCSSOM(); s; s = Next(*s)) {
- if (s->HasPseudoIS())
+ if (s->HasPseudoWhere())
return true;
}
return false;
@@ -235,7 +235,7 @@ bool CSSSelectorList::HasPseudoIS() const {
bool CSSSelectorList::RequiresExpansion() const {
for (const CSSSelector* s = FirstForCSSOM(); s; s = Next(*s)) {
- if (s->HasPseudoMatches() || s->HasPseudoIS())
+ if (s->HasPseudoIs() || s->HasPseudoWhere())
return true;
}
return false;
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector_list.h b/chromium/third_party/blink/renderer/core/css/css_selector_list.h
index db3b8b87daf..51f354b6bf4 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector_list.h
+++ b/chromium/third_party/blink/renderer/core/css/css_selector_list.h
@@ -77,8 +77,8 @@ class CORE_EXPORT CSSSelectorList {
CSSSelectorList ExpandedFirstPseudoClass() const;
CSSSelectorList TransformForListExpansion();
- bool HasPseudoMatches() const;
- bool HasPseudoIS() const;
+ bool HasPseudoIs() const;
+ bool HasPseudoWhere() const;
bool RequiresExpansion() const;
CSSSelectorList& operator=(CSSSelectorList&& o) {
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector_test.cc b/chromium/third_party/blink/renderer/core/css/css_selector_test.cc
index 16017e47215..694d59f6568 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_selector_test.cc
@@ -2,15 +2,17 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/core/css/rule_set.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
+using namespace css_test_helpers;
+
TEST(CSSSelector, Representations) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
const char* css_rules =
"summary::-webkit-details-marker { }"
@@ -46,11 +48,11 @@ TEST(CSSSelector, Representations) {
".a.b .c {}";
- helper.AddCSSRules(css_rules);
+ sheet.AddCSSRules(css_rules);
EXPECT_EQ(30u,
- helper.GetRuleSet().RuleCount()); // .a, .b counts as two rules.
+ sheet.GetRuleSet().RuleCount()); // .a, .b counts as two rules.
#ifndef NDEBUG
- helper.GetRuleSet().Show();
+ sheet.GetRuleSet().Show();
#endif
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector_watch.cc b/chromium/third_party/blink/renderer/core/css/css_selector_watch.cc
index cb416216e27..0c6ad72e1a9 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector_watch.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_selector_watch.cc
@@ -55,7 +55,7 @@ CSSSelectorWatch::CSSSelectorWatch(Document& document)
CSSSelectorWatch& CSSSelectorWatch::From(Document& document) {
CSSSelectorWatch* watch = FromIfExists(document);
if (!watch) {
- watch = new CSSSelectorWatch(document);
+ watch = MakeGarbageCollected<CSSSelectorWatch>(document);
ProvideTo(document, watch);
}
return *watch;
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector_watch.h b/chromium/third_party/blink/renderer/core/css/css_selector_watch.h
index fcc7e9537a8..1f8f1677498 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector_watch.h
+++ b/chromium/third_party/blink/renderer/core/css/css_selector_watch.h
@@ -50,6 +50,7 @@ class CORE_EXPORT CSSSelectorWatch final
public:
static const char kSupplementName[];
+ explicit CSSSelectorWatch(Document&);
virtual ~CSSSelectorWatch() = default;
static CSSSelectorWatch& From(Document&);
@@ -66,7 +67,6 @@ class CORE_EXPORT CSSSelectorWatch final
void Trace(blink::Visitor*) override;
private:
- explicit CSSSelectorWatch(Document&);
void CallbackSelectorChangeTimerFired(TimerBase*);
HeapVector<Member<StyleRule>> watched_callback_selectors_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_selector_watch_test.cc b/chromium/third_party/blink/renderer/core/css/css_selector_watch_test.cc
index 4bb106de70f..55351d77d3e 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector_watch_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_selector_watch_test.cc
@@ -47,7 +47,7 @@ TEST_F(CSSSelectorWatchTest, RecalcOnDocumentChange) {
selectors.push_back(".a");
watch.WatchCSSSelectors(selectors);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
selectors.clear();
selectors.push_back(".b");
@@ -55,7 +55,7 @@ TEST_F(CSSSelectorWatchTest, RecalcOnDocumentChange) {
selectors.push_back("#nomatch");
watch.WatchCSSSelectors(selectors);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* x = GetDocument().getElementById("x");
Element* y = GetDocument().getElementById("y");
@@ -64,14 +64,14 @@ TEST_F(CSSSelectorWatchTest, RecalcOnDocumentChange) {
ASSERT_TRUE(y);
ASSERT_TRUE(z);
- x->removeAttribute(HTMLNames::classAttr);
- y->removeAttribute(HTMLNames::classAttr);
- z->setAttribute(HTMLNames::classAttr, "c");
+ x->removeAttribute(html_names::kClassAttr);
+ y->removeAttribute(html_names::kClassAttr);
+ z->setAttribute(html_names::kClassAttr, "c");
ClearAddedRemoved(watch);
unsigned before_count = GetStyleEngine().StyleForElementCount();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(2u, after_count - before_count);
diff --git a/chromium/third_party/blink/renderer/core/css/css_shadow_value.h b/chromium/third_party/blink/renderer/core/css/css_shadow_value.h
index d42c673e3fe..0783d72ce63 100644
--- a/chromium/third_party/blink/renderer/core/css/css_shadow_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_shadow_value.h
@@ -39,9 +39,17 @@ class CORE_EXPORT CSSShadowValue : public CSSValue {
CSSPrimitiveValue* spread,
CSSIdentifierValue* style,
CSSValue* color) {
- return new CSSShadowValue(x, y, blur, spread, style, color);
+ return MakeGarbageCollected<CSSShadowValue>(x, y, blur, spread, style,
+ color);
}
+ CSSShadowValue(CSSPrimitiveValue* x,
+ CSSPrimitiveValue* y,
+ CSSPrimitiveValue* blur,
+ CSSPrimitiveValue* spread,
+ CSSIdentifierValue* style,
+ CSSValue* color);
+
String CustomCSSText() const;
bool Equals(const CSSShadowValue&) const;
@@ -54,14 +62,6 @@ class CORE_EXPORT CSSShadowValue : public CSSValue {
Member<CSSValue> color;
void TraceAfterDispatch(blink::Visitor*);
-
- private:
- CSSShadowValue(CSSPrimitiveValue* x,
- CSSPrimitiveValue* y,
- CSSPrimitiveValue* blur,
- CSSPrimitiveValue* spread,
- CSSIdentifierValue* style,
- CSSValue* color);
};
DEFINE_CSS_VALUE_TYPE_CASTS(CSSShadowValue, IsShadowValue());
diff --git a/chromium/third_party/blink/renderer/core/css/css_string_value.h b/chromium/third_party/blink/renderer/core/css/css_string_value.h
index c5ef637f9db..6c0ed697237 100644
--- a/chromium/third_party/blink/renderer/core/css/css_string_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_string_value.h
@@ -13,9 +13,11 @@ namespace blink {
class CSSStringValue : public CSSValue {
public:
static CSSStringValue* Create(const String& str) {
- return new CSSStringValue(str);
+ return MakeGarbageCollected<CSSStringValue>(str);
}
+ CSSStringValue(const String&);
+
String Value() const { return string_; }
String CustomCSSText() const;
@@ -27,8 +29,6 @@ class CSSStringValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSStringValue(const String&);
-
String string_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_declaration.cc b/chromium/third_party/blink/renderer/core/css/css_style_declaration.cc
index 4032f2f8586..d4c61489d99 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_declaration.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_style_declaration.cc
@@ -34,11 +34,11 @@
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_id_templates.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_style_declaration.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_declaration.h b/chromium/third_party/blink/renderer/core/css/css_style_declaration.h
index e2ce951b3fd..6dae92035d8 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/css_style_declaration.h
@@ -23,7 +23,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_declaration.idl b/chromium/third_party/blink/renderer/core/css/css_style_declaration.idl
index 03e8b072200..934c1c95401 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_declaration.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_style_declaration.idl
@@ -28,12 +28,12 @@
[Affects=Nothing] getter DOMString item(unsigned long index);
DOMString getPropertyValue(DOMString property);
DOMString getPropertyPriority(DOMString property);
- [CEReactions, RaisesException, CallWith=ExecutionContext] void setProperty(DOMString property, [TreatNullAs=EmptyString] DOMString value, [TreatNullAs=EmptyString] optional DOMString priority = "");
+ [CEReactions, RaisesException, CallWith=ExecutionContext] void setProperty(DOMString property, [TreatNullAs=EmptyString] DOMString value, optional [TreatNullAs=EmptyString] DOMString priority = "");
// void setPropertyValue(DOMString property, [TreatNullAs=EmptyString] DOMString value);
// void setPropertyPriority(DOMString property, [TreatNullAs=EmptyString] DOMString priority);
[CEReactions, RaisesException] DOMString removeProperty(DOMString property);
readonly attribute CSSRule? parentRule;
- [CEReactions, SetterCallWith=ExecutionContext, RaisesException=Setter, TreatNullAs=EmptyString] attribute DOMString cssFloat;
+ [CEReactions, SetterCallWith=ExecutionContext, RaisesException=Setter] attribute [TreatNullAs=EmptyString] DOMString cssFloat;
// The camel-cased and dashed attribute getters have custom bindings.
// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-camel-cased-attribute
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_declaration_test.cc b/chromium/third_party/blink/renderer/core/css/css_style_declaration_test.cc
index 217943bb028..93d258add61 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_declaration_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_style_declaration_test.cc
@@ -6,20 +6,22 @@
#include "third_party/blink/renderer/core/css/css_rule_list.h"
#include "third_party/blink/renderer/core/css/css_style_rule.h"
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
+using namespace css_test_helpers;
+
TEST(CSSStyleDeclarationTest, getPropertyShorthand) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("div { padding: var(--p); }");
- ASSERT_TRUE(helper.CssRules());
- ASSERT_EQ(1u, helper.CssRules()->length());
- ASSERT_EQ(CSSRule::kStyleRule, helper.CssRules()->item(0)->type());
- CSSStyleRule* style_rule = ToCSSStyleRule(helper.CssRules()->item(0));
+ sheet.AddCSSRules("div { padding: var(--p); }");
+ ASSERT_TRUE(sheet.CssRules());
+ ASSERT_EQ(1u, sheet.CssRules()->length());
+ ASSERT_EQ(CSSRule::kStyleRule, sheet.CssRules()->item(0)->type());
+ CSSStyleRule* style_rule = ToCSSStyleRule(sheet.CssRules()->item(0));
CSSStyleDeclaration* style = style_rule->style();
ASSERT_TRUE(style);
EXPECT_EQ(AtomicString(), style->GetPropertyShorthand("padding"));
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_rule.cc b/chromium/third_party/blink/renderer/core/css/css_style_rule.cc
index c2e6d1b4b98..1818ed6394a 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_rule.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_style_rule.cc
@@ -37,14 +37,14 @@ using SelectorTextCache = HeapHashMap<WeakMember<const CSSStyleRule>, String>;
static SelectorTextCache& GetSelectorTextCache() {
DEFINE_STATIC_LOCAL(Persistent<SelectorTextCache>, cache,
- (new SelectorTextCache));
+ (MakeGarbageCollected<SelectorTextCache>()));
return *cache;
}
CSSStyleRule::CSSStyleRule(StyleRule* style_rule, CSSStyleSheet* parent)
: CSSRule(parent),
style_rule_(style_rule),
- style_map_(new DeclaredStylePropertyMap(this)) {}
+ style_map_(MakeGarbageCollected<DeclaredStylePropertyMap>(this)) {}
CSSStyleRule::~CSSStyleRule() = default;
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_rule.h b/chromium/third_party/blink/renderer/core/css/css_style_rule.h
index c8e8a3e3538..bde00b92ecf 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_style_rule.h
@@ -38,9 +38,10 @@ class CORE_EXPORT CSSStyleRule final : public CSSRule {
public:
static CSSStyleRule* Create(StyleRule* rule, CSSStyleSheet* sheet) {
- return new CSSStyleRule(rule, sheet);
+ return MakeGarbageCollected<CSSStyleRule>(rule, sheet);
}
+ CSSStyleRule(StyleRule*, CSSStyleSheet*);
~CSSStyleRule() override;
String cssText() const override;
@@ -59,8 +60,6 @@ class CORE_EXPORT CSSStyleRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSStyleRule(StyleRule*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kStyleRule; }
Member<StyleRule> style_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_sheet.cc b/chromium/third_party/blink/renderer/core/css/css_style_sheet.cc
index b564ea18dce..eba408502a8 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_sheet.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_style_sheet.cc
@@ -47,22 +47,22 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class StyleSheetCSSRuleList final : public CSSRuleList {
public:
static StyleSheetCSSRuleList* Create(CSSStyleSheet* sheet) {
- return new StyleSheetCSSRuleList(sheet);
+ return MakeGarbageCollected<StyleSheetCSSRuleList>(sheet);
}
+ StyleSheetCSSRuleList(CSSStyleSheet* sheet) : style_sheet_(sheet) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(style_sheet_);
CSSRuleList::Trace(visitor);
}
private:
- StyleSheetCSSRuleList(CSSStyleSheet* sheet) : style_sheet_(sheet) {}
-
unsigned length() const override { return style_sheet_->length(); }
CSSRule* item(unsigned index) const override {
return style_sheet_->item(index);
@@ -93,7 +93,7 @@ const Document* CSSStyleSheet::SingleOwnerDocument(
}
CSSStyleSheet* CSSStyleSheet::Create(Document& document,
- const CSSStyleSheetInit& options,
+ const CSSStyleSheetInit* options,
ExceptionState& exception_state) {
if (!RuntimeEnabledFeatures::ConstructableStylesheetsEnabled()) {
exception_state.ThrowTypeError("Illegal constructor");
@@ -103,41 +103,42 @@ CSSStyleSheet* CSSStyleSheet::Create(Document& document,
// https://wicg.github.io/construct-stylesheets/#dom-cssstylesheet-cssstylesheet
CSSParserContext* parser_context = CSSParserContext::Create(document);
StyleSheetContents* contents = StyleSheetContents::Create(parser_context);
- CSSStyleSheet* sheet = new CSSStyleSheet(contents, nullptr);
- sheet->SetTitle(options.title());
+ CSSStyleSheet* sheet = MakeGarbageCollected<CSSStyleSheet>(contents, nullptr);
+ sheet->SetTitle(options->title());
sheet->ClearOwnerNode();
sheet->ClearOwnerRule();
scoped_refptr<MediaQuerySet> media_query_set;
- if (options.media().IsString())
- media_query_set = MediaQuerySet::Create(options.media().GetAsString());
+ if (options->media().IsString())
+ media_query_set = MediaQuerySet::Create(options->media().GetAsString());
else
- media_query_set = options.media().GetAsMediaList()->Queries()->Copy();
+ media_query_set = options->media().GetAsMediaList()->Queries()->Copy();
MediaList* media_list =
MediaList::Create(media_query_set, const_cast<CSSStyleSheet*>(sheet));
sheet->SetMedia(media_list);
- if (options.alternate())
+ if (options->alternate())
sheet->SetAlternateFromConstructor(true);
- if (options.disabled())
+ if (options->disabled())
sheet->setDisabled(true);
return sheet;
}
CSSStyleSheet* CSSStyleSheet::Create(StyleSheetContents* sheet,
CSSImportRule* owner_rule) {
- return new CSSStyleSheet(sheet, owner_rule);
+ return MakeGarbageCollected<CSSStyleSheet>(sheet, owner_rule);
}
CSSStyleSheet* CSSStyleSheet::Create(StyleSheetContents* sheet,
Node& owner_node) {
- return new CSSStyleSheet(sheet, owner_node, false,
- TextPosition::MinimumPosition());
+ return MakeGarbageCollected<CSSStyleSheet>(sheet, owner_node, false,
+ TextPosition::MinimumPosition());
}
CSSStyleSheet* CSSStyleSheet::CreateInline(StyleSheetContents* sheet,
Node& owner_node,
const TextPosition& start_position) {
DCHECK(sheet);
- return new CSSStyleSheet(sheet, owner_node, true, start_position);
+ return MakeGarbageCollected<CSSStyleSheet>(sheet, owner_node, true,
+ start_position);
}
CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node,
@@ -150,7 +151,8 @@ CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node,
owner_node.GetDocument().GetReferrerPolicy(), encoding);
StyleSheetContents* sheet =
StyleSheetContents::Create(base_url.GetString(), parser_context);
- return new CSSStyleSheet(sheet, owner_node, true, start_position);
+ return MakeGarbageCollected<CSSStyleSheet>(sheet, owner_node, true,
+ start_position);
}
CSSStyleSheet::CSSStyleSheet(StyleSheetContents* contents,
@@ -551,7 +553,7 @@ void CSSStyleSheet::SetAlternateFromConstructor(
bool CSSStyleSheet::IsAlternate() const {
if (owner_node_) {
return owner_node_->IsElementNode() &&
- ToElement(owner_node_)->getAttribute(relAttr).Contains("alternate");
+ ToElement(owner_node_)->getAttribute(kRelAttr).Contains("alternate");
}
return alternate_from_constructor_;
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_sheet.h b/chromium/third_party/blink/renderer/core/css/css_style_sheet.h
index dcafec0c17f..51d77f9a018 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_sheet.h
+++ b/chromium/third_party/blink/renderer/core/css/css_style_sheet.h
@@ -54,7 +54,7 @@ class CORE_EXPORT CSSStyleSheet final : public StyleSheet {
static const Document* SingleOwnerDocument(const CSSStyleSheet*);
static CSSStyleSheet* Create(Document&,
- const CSSStyleSheetInit&,
+ const CSSStyleSheetInit*,
ExceptionState&);
static CSSStyleSheet* Create(StyleSheetContents*,
@@ -70,6 +70,11 @@ class CORE_EXPORT CSSStyleSheet final : public StyleSheet {
Node& owner_node,
const TextPosition& start_position = TextPosition::MinimumPosition());
+ CSSStyleSheet(StyleSheetContents*, CSSImportRule* owner_rule);
+ CSSStyleSheet(StyleSheetContents*,
+ Node& owner_node,
+ bool is_inline_stylesheet,
+ const TextPosition& start_position);
~CSSStyleSheet() override;
CSSStyleSheet* parentStyleSheet() const override;
@@ -193,12 +198,6 @@ class CORE_EXPORT CSSStyleSheet final : public StyleSheet {
void Trace(blink::Visitor*) override;
private:
- CSSStyleSheet(StyleSheetContents*, CSSImportRule* owner_rule);
- CSSStyleSheet(StyleSheetContents*,
- Node& owner_node,
- bool is_inline_stylesheet,
- const TextPosition& start_position);
-
bool IsCSSStyleSheet() const override { return true; }
String type() const override { return "text/css"; }
diff --git a/chromium/third_party/blink/renderer/core/css/css_style_sheet_test.cc b/chromium/third_party/blink/renderer/core/css/css_style_sheet_test.cc
index 234c6883238..3cdf716f661 100644
--- a/chromium/third_party/blink/renderer/core/css/css_style_sheet_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_style_sheet_test.cc
@@ -28,14 +28,15 @@ class CSSStyleSheetTest : public PageTestBase {
public:
static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
ScriptValue* output) {
- FunctionForTest* self = new FunctionForTest(script_state, output);
+ FunctionForTest* self =
+ MakeGarbageCollected<FunctionForTest>(script_state, output);
return self->BindToV8Function();
}
- private:
FunctionForTest(ScriptState* script_state, ScriptValue* output)
: ScriptFunction(script_state), output_(output) {}
+ private:
ScriptValue Call(ScriptValue value) override {
DCHECK(!value.IsEmpty());
*output_ = value;
@@ -49,7 +50,7 @@ class CSSStyleSheetTest : public PageTestBase {
TEST_F(CSSStyleSheetTest, ConstructorWithoutRuntimeFlagThrowsException) {
DummyExceptionStateForTesting exception_state;
RuntimeEnabledFeatures::SetConstructableStylesheetsEnabled(false);
- EXPECT_EQ(CSSStyleSheet::Create(GetDocument(), CSSStyleSheetInit(),
+ EXPECT_EQ(CSSStyleSheet::Create(GetDocument(), CSSStyleSheetInit::Create(),
exception_state),
nullptr);
ASSERT_TRUE(exception_state.HadException());
@@ -58,11 +59,11 @@ TEST_F(CSSStyleSheetTest, ConstructorWithoutRuntimeFlagThrowsException) {
TEST_F(CSSStyleSheetTest,
CSSStyleSheetConstructionWithNonEmptyCSSStyleSheetInit) {
DummyExceptionStateForTesting exception_state;
- CSSStyleSheetInit init;
- init.setMedia(MediaListOrString::FromString("screen, print"));
- init.setTitle("test");
- init.setAlternate(true);
- init.setDisabled(true);
+ CSSStyleSheetInit* init = CSSStyleSheetInit::Create();
+ init->setMedia(MediaListOrString::FromString("screen, print"));
+ init->setTitle("test");
+ init->setAlternate(true);
+ init->setDisabled(true);
CSSStyleSheet* sheet =
CSSStyleSheet::Create(GetDocument(), init, exception_state);
ASSERT_FALSE(exception_state.HadException());
@@ -71,8 +72,8 @@ TEST_F(CSSStyleSheetTest,
EXPECT_EQ(sheet->ownerNode(), nullptr);
EXPECT_EQ(sheet->ownerRule(), nullptr);
EXPECT_EQ(sheet->media()->length(), 2U);
- EXPECT_EQ(sheet->media()->mediaText(), init.media().GetAsString());
- EXPECT_EQ(sheet->title(), init.title());
+ EXPECT_EQ(sheet->media()->mediaText(), init->media().GetAsString());
+ EXPECT_EQ(sheet->title(), init->title());
EXPECT_TRUE(sheet->AlternateFromConstructor());
EXPECT_TRUE(sheet->disabled());
EXPECT_EQ(sheet->cssRules(exception_state)->length(), 0U);
@@ -83,7 +84,7 @@ TEST_F(CSSStyleSheetTest, CreateEmptyCSSStyleSheetWithEmptyCSSStyleSheetInit) {
V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
CSSStyleSheet* sheet = GetDocument().createEmptyCSSStyleSheet(
- scope.GetScriptState(), CSSStyleSheetInit(), exception_state);
+ scope.GetScriptState(), CSSStyleSheetInit::Create(), exception_state);
ASSERT_FALSE(exception_state.HadException());
EXPECT_TRUE(sheet->href().IsNull());
EXPECT_EQ(sheet->parentStyleSheet(), nullptr);
@@ -99,11 +100,11 @@ TEST_F(CSSStyleSheetTest, CreateEmptyCSSStyleSheetWithEmptyCSSStyleSheetInit) {
TEST_F(CSSStyleSheetTest,
CreateEmptyCSSStyleSheetWithNonEmptyCSSStyleSheetInit) {
- CSSStyleSheetInit init;
- init.setMedia(MediaListOrString::FromString("screen, print"));
- init.setTitle("test");
- init.setAlternate(true);
- init.setDisabled(true);
+ CSSStyleSheetInit* init = CSSStyleSheetInit::Create();
+ init->setMedia(MediaListOrString::FromString("screen, print"));
+ init->setTitle("test");
+ init->setAlternate(true);
+ init->setDisabled(true);
V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
CSSStyleSheet* sheet = GetDocument().createEmptyCSSStyleSheet(
@@ -114,8 +115,8 @@ TEST_F(CSSStyleSheetTest,
EXPECT_EQ(sheet->ownerNode(), nullptr);
EXPECT_EQ(sheet->ownerRule(), nullptr);
EXPECT_EQ(sheet->media()->length(), 2U);
- EXPECT_EQ(sheet->media()->mediaText(), init.media().GetAsString());
- EXPECT_EQ(sheet->title(), init.title());
+ EXPECT_EQ(sheet->media()->mediaText(), init->media().GetAsString());
+ EXPECT_EQ(sheet->title(), init->title());
EXPECT_TRUE(sheet->AlternateFromConstructor());
EXPECT_TRUE(sheet->disabled());
ASSERT_FALSE(exception_state.HadException());
@@ -126,7 +127,7 @@ TEST_F(CSSStyleSheetTest,
V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
ScriptPromise promise = GetDocument().createCSSStyleSheet(
- scope.GetScriptState(), "", CSSStyleSheetInit(), exception_state);
+ scope.GetScriptState(), "", CSSStyleSheetInit::Create(), exception_state);
EXPECT_FALSE(promise.IsEmpty());
ASSERT_FALSE(exception_state.HadException());
ScriptValue on_fulfilled, on_rejected;
@@ -153,11 +154,11 @@ TEST_F(CSSStyleSheetTest,
CreateCSSStyleSheetWithNonEmptyCSSStyleSheetInitAndText) {
String styleText[2] = {".red { color: red; }",
".red + span + span { color: red; }"};
- CSSStyleSheetInit init;
- init.setMedia(MediaListOrString::FromString("screen, print"));
- init.setTitle("test");
- init.setAlternate(true);
- init.setDisabled(true);
+ CSSStyleSheetInit* init = CSSStyleSheetInit::Create();
+ init->setMedia(MediaListOrString::FromString("screen, print"));
+ init->setTitle("test");
+ init->setAlternate(true);
+ init->setDisabled(true);
V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
ScriptPromise promise = GetDocument().createCSSStyleSheet(
@@ -179,8 +180,8 @@ TEST_F(CSSStyleSheetTest,
EXPECT_EQ(sheet->ownerNode(), nullptr);
EXPECT_EQ(sheet->ownerRule(), nullptr);
EXPECT_EQ(sheet->media()->length(), 2U);
- EXPECT_EQ(sheet->media()->mediaText(), init.media().GetAsString());
- EXPECT_EQ(sheet->title(), init.title());
+ EXPECT_EQ(sheet->media()->mediaText(), init->media().GetAsString());
+ EXPECT_EQ(sheet->title(), init->title());
EXPECT_TRUE(sheet->AlternateFromConstructor());
EXPECT_TRUE(sheet->disabled());
EXPECT_EQ(sheet->cssRules(exception_state)->length(), 2U);
diff --git a/chromium/third_party/blink/renderer/core/css/css_supports_rule.h b/chromium/third_party/blink/renderer/core/css/css_supports_rule.h
index 75088cf78e6..2ff67c34347 100644
--- a/chromium/third_party/blink/renderer/core/css/css_supports_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_supports_rule.h
@@ -41,16 +41,15 @@ class CSSSupportsRule final : public CSSConditionRule {
public:
static CSSSupportsRule* Create(StyleRuleSupports* rule,
CSSStyleSheet* sheet) {
- return new CSSSupportsRule(rule, sheet);
+ return MakeGarbageCollected<CSSSupportsRule>(rule, sheet);
}
+ CSSSupportsRule(StyleRuleSupports*, CSSStyleSheet*);
~CSSSupportsRule() override = default;
String cssText() const override;
private:
- CSSSupportsRule(StyleRuleSupports*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kSupportsRule; }
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_syntax_component.cc b/chromium/third_party/blink/renderer/core/css/css_syntax_component.cc
new file mode 100644
index 00000000000..926d064fa8f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_syntax_component.cc
@@ -0,0 +1,63 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_syntax_component.h"
+
+#include "third_party/blink/renderer/core/css/cssom/css_keyword_value.h"
+#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
+#include "third_party/blink/renderer/core/css/cssom/cssom_types.h"
+
+namespace blink {
+
+bool CSSSyntaxComponent::CanTake(const CSSStyleValue& value) const {
+ switch (type_) {
+ case CSSSyntaxType::kTokenStream:
+ return value.GetType() == CSSStyleValue::kUnparsedType;
+ case CSSSyntaxType::kIdent:
+ return value.GetType() == CSSStyleValue::kKeywordType &&
+ static_cast<const CSSKeywordValue&>(value).value() == string_;
+ case CSSSyntaxType::kLength:
+ return CSSOMTypes::IsCSSStyleValueLength(value);
+ case CSSSyntaxType::kInteger:
+ // TODO(andruud): Support rounding.
+ // https://drafts.css-houdini.org/css-typed-om-1/#numeric-objects
+ FALLTHROUGH;
+ case CSSSyntaxType::kNumber:
+ return CSSOMTypes::IsCSSStyleValueNumber(value);
+ case CSSSyntaxType::kPercentage:
+ return CSSOMTypes::IsCSSStyleValuePercentage(value);
+ case CSSSyntaxType::kLengthPercentage:
+ // TODO(andruud): Support calc(X% + Ypx).
+ return CSSOMTypes::IsCSSStyleValueLength(value) ||
+ CSSOMTypes::IsCSSStyleValuePercentage(value);
+ case CSSSyntaxType::kColor:
+ // TODO(andruud): Support custom properties in CSSUnsupportedStyleValue.
+ return false;
+ case CSSSyntaxType::kImage:
+ case CSSSyntaxType::kUrl:
+ return value.GetType() == CSSStyleValue::kURLImageType;
+ case CSSSyntaxType::kAngle:
+ return CSSOMTypes::IsCSSStyleValueAngle(value);
+ case CSSSyntaxType::kTime:
+ return CSSOMTypes::IsCSSStyleValueTime(value);
+ case CSSSyntaxType::kResolution:
+ return CSSOMTypes::IsCSSStyleValueResolution(value);
+ case CSSSyntaxType::kTransformFunction:
+ // TODO(andruud): Currently not supported by Typed OM.
+ // https://github.com/w3c/css-houdini-drafts/issues/290
+ // For now, this should accept a CSSUnsupportedStyleValue, such that
+ // <transform-function> values can be moved from one registered property
+ // to another.
+ // TODO(andruud): Support custom properties in CSSUnsupportedStyleValue.
+ return false;
+ case CSSSyntaxType::kTransformList:
+ return value.GetType() == CSSStyleValue::kTransformType;
+ case CSSSyntaxType::kCustomIdent:
+ return value.GetType() == CSSStyleValue::kKeywordType;
+ default:
+ return false;
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_syntax_component.h b/chromium/third_party/blink/renderer/core/css/css_syntax_component.h
new file mode 100644
index 00000000000..a828a13909d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_syntax_component.h
@@ -0,0 +1,68 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SYNTAX_COMPONENT_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SYNTAX_COMPONENT_H_
+
+#include "base/macros.h"
+#include "third_party/blink/renderer/core/css/css_value.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+class CSSStyleValue;
+
+enum class CSSSyntaxType {
+ kTokenStream,
+ kIdent,
+ kLength,
+ kNumber,
+ kPercentage,
+ kLengthPercentage,
+ kColor,
+ kImage,
+ kUrl,
+ kInteger,
+ kAngle,
+ kTime,
+ kResolution,
+ kTransformFunction,
+ kTransformList,
+ kCustomIdent,
+};
+
+enum class CSSSyntaxRepeat { kNone, kSpaceSeparated, kCommaSeparated };
+
+class CSSSyntaxComponent {
+ public:
+ CSSSyntaxComponent(CSSSyntaxType type,
+ const String& string,
+ CSSSyntaxRepeat repeat)
+ : type_(type), string_(string), repeat_(repeat) {}
+
+ bool operator==(const CSSSyntaxComponent& a) const {
+ return type_ == a.type_ && string_ == a.string_ && repeat_ == a.repeat_;
+ }
+
+ CSSSyntaxType GetType() const { return type_; }
+ const String& GetString() const { return string_; }
+ CSSSyntaxRepeat GetRepeat() const { return repeat_; }
+ bool IsRepeatable() const { return repeat_ != CSSSyntaxRepeat::kNone; }
+ bool IsInteger() const { return type_ == CSSSyntaxType::kInteger; }
+ char Separator() const {
+ DCHECK(IsRepeatable());
+ return repeat_ == CSSSyntaxRepeat::kSpaceSeparated ? ' ' : ',';
+ }
+
+ bool CanTake(const CSSStyleValue&) const;
+
+ private:
+ CSSSyntaxType type_;
+ String string_; // Only used when type_ is CSSSyntaxType::kIdent
+ CSSSyntaxRepeat repeat_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SYNTAX_COMPONENT_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.cc b/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.cc
index a60e132796c..0f252c37254 100644
--- a/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.cc
@@ -5,16 +5,15 @@
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_syntax_component.h"
#include "third_party/blink/renderer/core/css/css_uri_value.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
-#include "third_party/blink/renderer/core/css/cssom/css_keyword_value.h"
-#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css/cssom/cssom_types.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_idioms.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -45,8 +44,10 @@ CSSSyntaxType ParseSyntaxType(String type) {
return CSSSyntaxType::kLengthPercentage;
if (type == "color")
return CSSSyntaxType::kColor;
- if (type == "image")
- return CSSSyntaxType::kImage;
+ if (RuntimeEnabledFeatures::CSSVariables2ImageValuesEnabled()) {
+ if (type == "image")
+ return CSSSyntaxType::kImage;
+ }
if (type == "url")
return CSSSyntaxType::kUrl;
if (type == "integer")
@@ -57,10 +58,12 @@ CSSSyntaxType ParseSyntaxType(String type) {
return CSSSyntaxType::kTime;
if (type == "resolution")
return CSSSyntaxType::kResolution;
- if (type == "transform-function")
- return CSSSyntaxType::kTransformFunction;
- if (type == "transform-list")
- return CSSSyntaxType::kTransformList;
+ if (RuntimeEnabledFeatures::CSSVariables2TransformValuesEnabled()) {
+ if (type == "transform-function")
+ return CSSSyntaxType::kTransformFunction;
+ if (type == "transform-list")
+ return CSSSyntaxType::kTransformList;
+ }
if (type == "custom-ident")
return CSSSyntaxType::kCustomIdent;
// Not an Ident, just used to indicate failure
@@ -93,7 +96,7 @@ bool ConsumeSyntaxIdent(const String& input,
if (offset == ident_start)
return false;
ident = input.Substring(ident_start, offset - ident_start);
- return !CSSPropertyParserHelpers::IsCSSWideKeyword(ident);
+ return !css_property_parser_helpers::IsCSSWideKeyword(ident);
}
CSSSyntaxDescriptor::CSSSyntaxDescriptor(const String& input) {
@@ -152,14 +155,14 @@ CSSSyntaxDescriptor::CSSSyntaxDescriptor(const String& input) {
const CSSValue* ConsumeSingleType(const CSSSyntaxComponent& syntax,
CSSParserTokenRange& range,
const CSSParserContext* context) {
- using namespace CSSPropertyParserHelpers;
+ using namespace css_property_parser_helpers;
- switch (syntax.type_) {
+ switch (syntax.GetType()) {
case CSSSyntaxType::kIdent:
if (range.Peek().GetType() == kIdentToken &&
- range.Peek().Value() == syntax.string_) {
+ range.Peek().Value() == syntax.GetString()) {
range.ConsumeIncludingWhitespace();
- return CSSCustomIdentValue::Create(AtomicString(syntax.string_));
+ return CSSCustomIdentValue::Create(AtomicString(syntax.GetString()));
}
return nullptr;
case CSSSyntaxType::kLength:
@@ -179,7 +182,7 @@ const CSSValue* ConsumeSingleType(const CSSSyntaxComponent& syntax,
case CSSSyntaxType::kUrl:
return ConsumeUrl(range, context);
case CSSSyntaxType::kInteger:
- return ConsumeInteger(range);
+ return ConsumeIntegerOrNumberCalc(range);
case CSSSyntaxType::kAngle:
return ConsumeAngle(range, context, base::Optional<WebFeature>());
case CSSSyntaxType::kTime:
@@ -191,7 +194,7 @@ const CSSValue* ConsumeSingleType(const CSSSyntaxComponent& syntax,
case CSSSyntaxType::kTransformList:
return ConsumeTransformList(range, *context);
case CSSSyntaxType::kCustomIdent:
- return ConsumeCustomIdent(range);
+ return ConsumeCustomIdent(range, *context);
default:
NOTREACHED();
return nullptr;
@@ -202,7 +205,7 @@ const CSSValue* ConsumeSyntaxComponent(const CSSSyntaxComponent& syntax,
CSSParserTokenRange range,
const CSSParserContext* context) {
// CSS-wide keywords are already handled by the CSSPropertyParser
- if (syntax.repeat_ == CSSSyntaxRepeat::kSpaceSeparated) {
+ if (syntax.GetRepeat() == CSSSyntaxRepeat::kSpaceSeparated) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
while (!range.AtEnd()) {
const CSSValue* value = ConsumeSingleType(syntax, range, context);
@@ -210,17 +213,18 @@ const CSSValue* ConsumeSyntaxComponent(const CSSSyntaxComponent& syntax,
return nullptr;
list->Append(*value);
}
- return list;
+ return list->length() ? list : nullptr;
}
- if (syntax.repeat_ == CSSSyntaxRepeat::kCommaSeparated) {
+ if (syntax.GetRepeat() == CSSSyntaxRepeat::kCommaSeparated) {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
do {
const CSSValue* value = ConsumeSingleType(syntax, range, context);
if (!value)
return nullptr;
list->Append(*value);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
- return list;
+ } while (
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
+ return list->length() ? list : nullptr;
}
const CSSValue* result = ConsumeSingleType(syntax, range, context);
if (!range.AtEnd())
@@ -228,62 +232,17 @@ const CSSValue* ConsumeSyntaxComponent(const CSSSyntaxComponent& syntax,
return result;
}
-bool CSSSyntaxComponent::CanTake(const CSSStyleValue& value) const {
- switch (type_) {
- case CSSSyntaxType::kTokenStream:
- return value.GetType() == CSSStyleValue::kUnparsedType;
- case CSSSyntaxType::kIdent:
- return value.GetType() == CSSStyleValue::kKeywordType &&
- static_cast<const CSSKeywordValue&>(value).value() == string_;
- case CSSSyntaxType::kLength:
- return CSSOMTypes::IsCSSStyleValueLength(value);
- case CSSSyntaxType::kInteger:
- // TODO(andruud): Support rounding.
- // https://drafts.css-houdini.org/css-typed-om-1/#numeric-objects
- FALLTHROUGH;
- case CSSSyntaxType::kNumber:
- return CSSOMTypes::IsCSSStyleValueNumber(value);
- case CSSSyntaxType::kPercentage:
- return CSSOMTypes::IsCSSStyleValuePercentage(value);
- case CSSSyntaxType::kLengthPercentage:
- // TODO(andruud): Support calc(X% + Ypx).
- return CSSOMTypes::IsCSSStyleValueLength(value) ||
- CSSOMTypes::IsCSSStyleValuePercentage(value);
- case CSSSyntaxType::kColor:
- // TODO(andruud): Support custom properties in CSSUnsupportedStyleValue.
- return false;
- case CSSSyntaxType::kImage:
- case CSSSyntaxType::kUrl:
- return value.GetType() == CSSStyleValue::kURLImageType;
- case CSSSyntaxType::kAngle:
- return CSSOMTypes::IsCSSStyleValueAngle(value);
- case CSSSyntaxType::kTime:
- return CSSOMTypes::IsCSSStyleValueTime(value);
- case CSSSyntaxType::kResolution:
- return CSSOMTypes::IsCSSStyleValueResolution(value);
- case CSSSyntaxType::kTransformFunction:
- // TODO(andruud): Currently not supported by Typed OM.
- // https://github.com/w3c/css-houdini-drafts/issues/290
- // For now, this should accept a CSSUnsupportedStyleValue, such that
- // <transform-function> values can be moved from one registered property
- // to another.
- // TODO(andruud): Support custom properties in CSSUnsupportedStyleValue.
- return false;
- case CSSSyntaxType::kTransformList:
- return value.GetType() == CSSStyleValue::kTransformType;
- case CSSSyntaxType::kCustomIdent:
- return value.GetType() == CSSStyleValue::kKeywordType;
- default:
- return false;
+const CSSSyntaxComponent* CSSSyntaxDescriptor::Match(
+ const CSSStyleValue& value) const {
+ for (const CSSSyntaxComponent& component : syntax_components_) {
+ if (component.CanTake(value))
+ return &component;
}
+ return nullptr;
}
bool CSSSyntaxDescriptor::CanTake(const CSSStyleValue& value) const {
- for (const CSSSyntaxComponent& component : syntax_components_) {
- if (component.CanTake(value))
- return true;
- }
- return false;
+ return Match(value);
}
const CSSValue* CSSSyntaxDescriptor::Parse(CSSParserTokenRange range,
diff --git a/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.h b/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.h
index ec88ced9391..e08b46ee86a 100644
--- a/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.h
+++ b/chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.h
@@ -5,54 +5,14 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SYNTAX_DESCRIPTOR_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SYNTAX_DESCRIPTOR_H_
+#include "third_party/blink/renderer/core/css/css_syntax_component.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
namespace blink {
class CSSParserContext;
-class CSSStyleValue;
class CSSValue;
-enum class CSSSyntaxType {
- kTokenStream,
- kIdent,
- kLength,
- kNumber,
- kPercentage,
- kLengthPercentage,
- kColor,
- kImage,
- kUrl,
- kInteger,
- kAngle,
- kTime,
- kResolution,
- kTransformFunction,
- kTransformList,
- kCustomIdent,
-};
-
-enum class CSSSyntaxRepeat { kNone, kSpaceSeparated, kCommaSeparated };
-
-struct CSSSyntaxComponent {
- CSSSyntaxComponent(CSSSyntaxType type,
- const String& string,
- CSSSyntaxRepeat repeat)
- : type_(type), string_(string), repeat_(repeat) {}
-
- bool operator==(const CSSSyntaxComponent& a) const {
- return type_ == a.type_ && string_ == a.string_ && repeat_ == a.repeat_;
- }
-
- bool IsRepeatable() const { return repeat_ != CSSSyntaxRepeat::kNone; }
-
- bool CanTake(const CSSStyleValue&) const;
-
- CSSSyntaxType type_;
- String string_; // Only used when type_ is CSSSyntaxType::kIdent
- CSSSyntaxRepeat repeat_;
-};
-
class CORE_EXPORT CSSSyntaxDescriptor {
public:
explicit CSSSyntaxDescriptor(const String& syntax);
@@ -60,15 +20,16 @@ class CORE_EXPORT CSSSyntaxDescriptor {
const CSSValue* Parse(CSSParserTokenRange,
const CSSParserContext*,
bool is_animation_tainted) const;
+ const CSSSyntaxComponent* Match(const CSSStyleValue&) const;
bool CanTake(const CSSStyleValue&) const;
bool IsValid() const { return !syntax_components_.IsEmpty(); }
bool IsTokenStream() const {
return syntax_components_.size() == 1 &&
- syntax_components_[0].type_ == CSSSyntaxType::kTokenStream;
+ syntax_components_[0].GetType() == CSSSyntaxType::kTokenStream;
}
bool HasUrlSyntax() const {
for (const CSSSyntaxComponent& component : syntax_components_) {
- if (component.type_ == CSSSyntaxType::kUrl)
+ if (component.GetType() == CSSSyntaxType::kUrl)
return true;
}
return false;
diff --git a/chromium/third_party/blink/renderer/core/css/css_test_helper.cc b/chromium/third_party/blink/renderer/core/css/css_test_helper.cc
deleted file mode 100644
index 7a5acf84252..00000000000
--- a/chromium/third_party/blink/renderer/core/css/css_test_helper.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2014, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Opera Software ASA nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
-
-#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/core/css/css_rule_list.h"
-#include "third_party/blink/renderer/core/css/css_style_sheet.h"
-#include "third_party/blink/renderer/core/css/rule_set.h"
-#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
-
-namespace blink {
-
-CSSTestHelper::~CSSTestHelper() = default;
-
-CSSTestHelper::CSSTestHelper() {
- document_ = Document::CreateForTest();
- TextPosition position;
- style_sheet_ = CSSStyleSheet::CreateInline(*document_, NullURL(), position,
- UTF8Encoding());
-}
-
-CSSRuleList* CSSTestHelper::CssRules() {
- DummyExceptionStateForTesting exception_state;
- CSSRuleList* result = style_sheet_->cssRules(exception_state);
- EXPECT_FALSE(exception_state.HadException());
- return result;
-}
-
-RuleSet& CSSTestHelper::GetRuleSet() {
- RuleSet& rule_set = style_sheet_->Contents()->EnsureRuleSet(
- MediaQueryEvaluator(), kRuleHasNoSpecialState);
- rule_set.CompactRulesIfNeeded();
- return rule_set;
-}
-
-void CSSTestHelper::AddCSSRules(const char* css_text, bool is_empty_sheet) {
- TextPosition position;
- unsigned sheet_length = style_sheet_->length();
- style_sheet_->Contents()->ParseStringAtPosition(css_text, position);
- if (!is_empty_sheet)
- ASSERT_GT(style_sheet_->length(), sheet_length);
- else
- ASSERT_EQ(style_sheet_->length(), sheet_length);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_test_helper.h b/chromium/third_party/blink/renderer/core/css/css_test_helper.h
deleted file mode 100644
index b64d3469b68..00000000000
--- a/chromium/third_party/blink/renderer/core/css/css_test_helper.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2014, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Opera Software ASA nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_TEST_HELPER_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_TEST_HELPER_H_
-
-#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/core/css/rule_set.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-
-namespace blink {
-
-class Document;
-class CSSStyleSheet;
-
-// A helper class for writing tests of CSS rules. Example usage:
-//
-// CSSTestHelper helper;
-// helper.addCSSRule("body { color: red} #a { position: absolute }");
-// RuleSet& ruleSet = helper.ruleSet();
-// ... examine RuleSet to find the rule and test properties on it.
-
-class CSSTestHelper {
- STACK_ALLOCATED();
-
- public:
- CSSTestHelper();
- ~CSSTestHelper();
-
- const Document& GetDocument() { return *document_; };
-
- void AddCSSRules(const char* rule_text, bool is_empty_sheet = false);
- RuleSet& GetRuleSet();
- CSSRuleList* CssRules();
-
- private:
- Persistent<Document> document_;
- Persistent<CSSStyleSheet> style_sheet_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_TEST_HELPER_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_test_helpers.cc b/chromium/third_party/blink/renderer/core/css/css_test_helpers.cc
new file mode 100644
index 00000000000..9b1fac6b088
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_test_helpers.cc
@@ -0,0 +1,73 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_rule_list.h"
+#include "third_party/blink/renderer/core/css/css_style_sheet.h"
+#include "third_party/blink/renderer/core/css/property_descriptor.h"
+#include "third_party/blink/renderer/core/css/property_registration.h"
+#include "third_party/blink/renderer/core/css/property_registry.h"
+#include "third_party/blink/renderer/core/css/rule_set.h"
+#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
+
+namespace blink {
+namespace css_test_helpers {
+
+TestStyleSheet::~TestStyleSheet() = default;
+
+TestStyleSheet::TestStyleSheet() {
+ document_ = Document::CreateForTest();
+ TextPosition position;
+ style_sheet_ = CSSStyleSheet::CreateInline(*document_, NullURL(), position,
+ UTF8Encoding());
+}
+
+CSSRuleList* TestStyleSheet::CssRules() {
+ DummyExceptionStateForTesting exception_state;
+ CSSRuleList* result = style_sheet_->cssRules(exception_state);
+ EXPECT_FALSE(exception_state.HadException());
+ return result;
+}
+
+RuleSet& TestStyleSheet::GetRuleSet() {
+ RuleSet& rule_set = style_sheet_->Contents()->EnsureRuleSet(
+ MediaQueryEvaluator(), kRuleHasNoSpecialState);
+ rule_set.CompactRulesIfNeeded();
+ return rule_set;
+}
+
+void TestStyleSheet::AddCSSRules(const char* css_text, bool is_empty_sheet) {
+ TextPosition position;
+ unsigned sheet_length = style_sheet_->length();
+ style_sheet_->Contents()->ParseStringAtPosition(css_text, position);
+ if (!is_empty_sheet)
+ ASSERT_GT(style_sheet_->length(), sheet_length);
+ else
+ ASSERT_EQ(style_sheet_->length(), sheet_length);
+}
+
+void RegisterProperty(Document& document,
+ const String& name,
+ const String& syntax,
+ const String& initial_value,
+ bool is_inherited) {
+ DummyExceptionStateForTesting exception_state;
+ PropertyDescriptor* property_descriptor = PropertyDescriptor::Create();
+ property_descriptor->setName(name);
+ property_descriptor->setSyntax(syntax);
+ property_descriptor->setInitialValue(initial_value);
+ property_descriptor->setInherits(is_inherited);
+ PropertyRegistration::registerProperty(&document, property_descriptor,
+ exception_state);
+ ASSERT_FALSE(exception_state.HadException());
+}
+
+} // namespace css_test_helpers
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_test_helpers.h b/chromium/third_party/blink/renderer/core/css/css_test_helpers.h
new file mode 100644
index 00000000000..8d4e5b9bcee
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_test_helpers.h
@@ -0,0 +1,52 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_TEST_HELPERS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_TEST_HELPERS_H_
+
+#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/core/css/rule_set.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
+
+namespace blink {
+
+class Document;
+class CSSStyleSheet;
+
+namespace css_test_helpers {
+
+// Example usage:
+//
+// css_test_helpers::TestStyleSheet sheet;
+// sheet.addCSSRule("body { color: red} #a { position: absolute }");
+// RuleSet& ruleSet = sheet.ruleSet();
+// ... examine RuleSet to find the rule and test properties on it.
+class TestStyleSheet {
+ STACK_ALLOCATED();
+
+ public:
+ TestStyleSheet();
+ ~TestStyleSheet();
+
+ const Document& GetDocument() { return *document_; };
+
+ void AddCSSRules(const char* rule_text, bool is_empty_sheet = false);
+ RuleSet& GetRuleSet();
+ CSSRuleList* CssRules();
+
+ private:
+ Persistent<Document> document_;
+ Persistent<CSSStyleSheet> style_sheet_;
+};
+
+void RegisterProperty(Document& document,
+ const String& name,
+ const String& syntax,
+ const String& initial_value,
+ bool is_inherited);
+
+} // namespace css_test_helpers
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_TEST_HELPERS_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_timing_function_value.h b/chromium/third_party/blink/renderer/core/css/css_timing_function_value.h
index 3aa915fdd5c..3ded042f157 100644
--- a/chromium/third_party/blink/renderer/core/css/css_timing_function_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_timing_function_value.h
@@ -40,9 +40,17 @@ class CSSCubicBezierTimingFunctionValue : public CSSValue {
double y1,
double x2,
double y2) {
- return new CSSCubicBezierTimingFunctionValue(x1, y1, x2, y2);
+ return MakeGarbageCollected<CSSCubicBezierTimingFunctionValue>(x1, y1, x2,
+ y2);
}
+ CSSCubicBezierTimingFunctionValue(double x1, double y1, double x2, double y2)
+ : CSSValue(kCubicBezierTimingFunctionClass),
+ x1_(x1),
+ y1_(y1),
+ x2_(x2),
+ y2_(y2) {}
+
String CustomCSSText() const;
double X1() const { return x1_; }
@@ -57,13 +65,6 @@ class CSSCubicBezierTimingFunctionValue : public CSSValue {
}
private:
- CSSCubicBezierTimingFunctionValue(double x1, double y1, double x2, double y2)
- : CSSValue(kCubicBezierTimingFunctionClass),
- x1_(x1),
- y1_(y1),
- x2_(x2),
- y2_(y2) {}
-
double x1_;
double y1_;
double x2_;
@@ -78,9 +79,16 @@ class CSSStepsTimingFunctionValue : public CSSValue {
static CSSStepsTimingFunctionValue* Create(
int steps,
StepsTimingFunction::StepPosition step_position) {
- return new CSSStepsTimingFunctionValue(steps, step_position);
+ return MakeGarbageCollected<CSSStepsTimingFunctionValue>(steps,
+ step_position);
}
+ CSSStepsTimingFunctionValue(int steps,
+ StepsTimingFunction::StepPosition step_position)
+ : CSSValue(kStepsTimingFunctionClass),
+ steps_(steps),
+ step_position_(step_position) {}
+
int NumberOfSteps() const { return steps_; }
StepsTimingFunction::StepPosition GetStepPosition() const {
return step_position_;
@@ -95,12 +103,6 @@ class CSSStepsTimingFunctionValue : public CSSValue {
}
private:
- CSSStepsTimingFunctionValue(int steps,
- StepsTimingFunction::StepPosition step_position)
- : CSSValue(kStepsTimingFunctionClass),
- steps_(steps),
- step_position_(step_position) {}
-
int steps_;
StepsTimingFunction::StepPosition step_position_;
};
@@ -111,7 +113,12 @@ DEFINE_CSS_VALUE_TYPE_CASTS(CSSStepsTimingFunctionValue,
class CSSFramesTimingFunctionValue : public CSSValue {
public:
static CSSFramesTimingFunctionValue* Create(int frames) {
- return new CSSFramesTimingFunctionValue(frames);
+ return MakeGarbageCollected<CSSFramesTimingFunctionValue>(frames);
+ }
+
+ CSSFramesTimingFunctionValue(int frames)
+ : CSSValue(kFramesTimingFunctionClass), frames_(frames) {
+ DCHECK(RuntimeEnabledFeatures::FramesTimingFunctionEnabled());
}
int NumberOfFrames() const { return frames_; }
@@ -125,11 +132,6 @@ class CSSFramesTimingFunctionValue : public CSSValue {
}
private:
- CSSFramesTimingFunctionValue(int frames)
- : CSSValue(kFramesTimingFunctionClass), frames_(frames) {
- DCHECK(RuntimeEnabledFeatures::FramesTimingFunctionEnabled());
- }
-
int frames_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_unicode_range_value.h b/chromium/third_party/blink/renderer/core/css/css_unicode_range_value.h
index 7562110314c..7057845a785 100644
--- a/chromium/third_party/blink/renderer/core/css/css_unicode_range_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_unicode_range_value.h
@@ -34,9 +34,12 @@ namespace blink {
class CSSUnicodeRangeValue : public CSSValue {
public:
static CSSUnicodeRangeValue* Create(UChar32 from, UChar32 to) {
- return new CSSUnicodeRangeValue(from, to);
+ return MakeGarbageCollected<CSSUnicodeRangeValue>(from, to);
}
+ CSSUnicodeRangeValue(UChar32 from, UChar32 to)
+ : CSSValue(kUnicodeRangeClass), from_(from), to_(to) {}
+
UChar32 From() const { return from_; }
UChar32 To() const { return to_; }
@@ -49,9 +52,6 @@ class CSSUnicodeRangeValue : public CSSValue {
}
private:
- CSSUnicodeRangeValue(UChar32 from, UChar32 to)
- : CSSValue(kUnicodeRangeClass), from_(from), to_(to) {}
-
UChar32 from_;
UChar32 to_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_uri_value.cc b/chromium/third_party/blink/renderer/core/css/css_uri_value.cc
index be594ae52e3..ef22d478644 100644
--- a/chromium/third_party/blink/renderer/core/css/css_uri_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_uri_value.cc
@@ -25,7 +25,7 @@ CSSURIValue::~CSSURIValue() = default;
SVGResource* CSSURIValue::EnsureResourceReference() const {
if (!resource_)
- resource_ = new ExternalSVGResource(AbsoluteUrl());
+ resource_ = MakeGarbageCollected<ExternalSVGResource>(AbsoluteUrl());
return resource_;
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_uri_value.h b/chromium/third_party/blink/renderer/core/css/css_uri_value.h
index 57b4519d0bb..2f0ea52240d 100644
--- a/chromium/third_party/blink/renderer/core/css/css_uri_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_uri_value.h
@@ -17,11 +17,15 @@ class SVGResource;
class CSSURIValue : public CSSValue {
public:
static CSSURIValue* Create(const String& relative_url, const KURL& url) {
- return new CSSURIValue(AtomicString(relative_url), url);
+ return MakeGarbageCollected<CSSURIValue>(AtomicString(relative_url), url);
}
static CSSURIValue* Create(const AtomicString& absolute_url) {
- return new CSSURIValue(absolute_url, absolute_url);
+ return MakeGarbageCollected<CSSURIValue>(absolute_url, absolute_url);
}
+
+ CSSURIValue(const AtomicString&, const KURL&);
+ CSSURIValue(const AtomicString& relative_url,
+ const AtomicString& absolute_url);
~CSSURIValue();
SVGResource* EnsureResourceReference() const;
@@ -41,10 +45,6 @@ class CSSURIValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSURIValue(const AtomicString&, const KURL&);
- CSSURIValue(const AtomicString& relative_url,
- const AtomicString& absolute_url);
-
KURL AbsoluteUrl() const;
AtomicString relative_url_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_value.cc b/chromium/third_party/blink/renderer/core/css/css_value.cc
index d7a9cc8b282..e00e74ec82f 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_value.cc
@@ -50,6 +50,7 @@
#include "third_party/blink/renderer/core/css/css_image_value.h"
#include "third_party/blink/renderer/core/css/css_inherited_value.h"
#include "third_party/blink/renderer/core/css/css_initial_value.h"
+#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h"
#include "third_party/blink/renderer/core/css/css_layout_function_value.h"
#include "third_party/blink/renderer/core/css/css_paint_value.h"
#include "third_party/blink/renderer/core/css/css_path_value.h"
@@ -67,7 +68,7 @@
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
namespace blink {
@@ -246,6 +247,8 @@ bool CSSValue::operator==(const CSSValue& other) const {
return CompareCSSValues<CSSVariableReferenceValue>(*this, other);
case kPendingSubstitutionValueClass:
return CompareCSSValues<CSSPendingSubstitutionValue>(*this, other);
+ case kInvalidVariableValueClass:
+ return CompareCSSValues<CSSInvalidVariableValue>(*this, other);
}
NOTREACHED();
return false;
@@ -351,6 +354,8 @@ String CSSValue::CssText() const {
return ToCSSCustomPropertyDeclaration(this)->CustomCSSText();
case kPendingSubstitutionValueClass:
return ToCSSPendingSubstitutionValue(this)->CustomCSSText();
+ case kInvalidVariableValueClass:
+ return ToCSSInvalidVariableValue(this)->CustomCSSText();
}
NOTREACHED();
return String();
@@ -503,6 +508,9 @@ void CSSValue::FinalizeGarbageCollectedObject() {
case kPendingSubstitutionValueClass:
ToCSSPendingSubstitutionValue(this)->~CSSPendingSubstitutionValue();
return;
+ case kInvalidVariableValueClass:
+ ToCSSInvalidVariableValue(this)->~CSSInvalidVariableValue();
+ return;
}
NOTREACHED();
}
@@ -653,6 +661,9 @@ void CSSValue::Trace(blink::Visitor* visitor) {
case kPendingSubstitutionValueClass:
ToCSSPendingSubstitutionValue(this)->TraceAfterDispatch(visitor);
return;
+ case kInvalidVariableValueClass:
+ ToCSSInvalidVariableValue(this)->TraceAfterDispatch(visitor);
+ return;
}
NOTREACHED();
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_value.h b/chromium/third_party/blink/renderer/core/css/css_value.h
index 84b6e122740..e1bd04894f7 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_value.h
@@ -161,6 +161,9 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
bool IsPendingSubstitutionValue() const {
return class_type_ == kPendingSubstitutionValueClass;
}
+ bool IsInvalidVariableValue() const {
+ return class_type_ == kInvalidVariableValueClass;
+ }
bool HasFailedOrCanceledSubresources() const;
bool MayContainUrl() const;
@@ -235,6 +238,7 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
kVariableReferenceClass,
kCustomPropertyDeclarationClass,
kPendingSubstitutionValueClass,
+ kInvalidVariableValueClass,
kLayoutFunctionClass,
kCSSContentDistributionClass,
diff --git a/chromium/third_party/blink/renderer/core/css/css_value_id_mappings.h b/chromium/third_party/blink/renderer/core/css/css_value_id_mappings.h
index 6185d2ff0bb..e4008a50463 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value_id_mappings.h
+++ b/chromium/third_party/blink/renderer/core/css/css_value_id_mappings.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_VALUE_ID_MAPPINGS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_VALUE_ID_MAPPINGS_H_
-#include "third_party/blink/renderer/core/css_value_id_mappings_generated.h"
+#include "third_party/blink/renderer/core/css/css_value_id_mappings_generated.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/css_value_keywords.json5 b/chromium/third_party/blink/renderer/core/css/css_value_keywords.json5
index b944b4c8ef4..6967328735d 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value_keywords.json5
+++ b/chromium/third_party/blink/renderer/core/css/css_value_keywords.json5
@@ -797,9 +797,9 @@
//
// pointer-events
//
- "visiblePainted",
- "visibleFill",
- "visibleStroke",
+ "visiblepainted",
+ "visiblefill",
+ "visiblestroke",
//visible
"painted",
"fill",
diff --git a/chromium/third_party/blink/renderer/core/css/css_value_list.h b/chromium/third_party/blink/renderer/core/css/css_value_list.h
index 085c2021f45..090786ffa73 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value_list.h
+++ b/chromium/third_party/blink/renderer/core/css/css_value_list.h
@@ -36,19 +36,22 @@ class CORE_EXPORT CSSValueList : public CSSValue {
using const_iterator = HeapVector<Member<const CSSValue>, 4>::const_iterator;
static CSSValueList* CreateCommaSeparated() {
- return new CSSValueList(kCommaSeparator);
+ return MakeGarbageCollected<CSSValueList>(kCommaSeparator);
}
static CSSValueList* CreateSpaceSeparated() {
- return new CSSValueList(kSpaceSeparator);
+ return MakeGarbageCollected<CSSValueList>(kSpaceSeparator);
}
static CSSValueList* CreateSlashSeparated() {
- return new CSSValueList(kSlashSeparator);
+ return MakeGarbageCollected<CSSValueList>(kSlashSeparator);
}
static CSSValueList* CreateWithSeparatorFrom(const CSSValueList& list) {
- return new CSSValueList(
+ return MakeGarbageCollected<CSSValueList>(
static_cast<ValueListSeparator>(list.value_list_separator_));
}
+ CSSValueList(ClassType, ValueListSeparator);
+ explicit CSSValueList(ValueListSeparator);
+
iterator begin() { return values_.begin(); }
iterator end() { return values_.end(); }
const_iterator begin() const { return values_.begin(); }
@@ -72,12 +75,7 @@ class CORE_EXPORT CSSValueList : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
- protected:
- CSSValueList(ClassType, ValueListSeparator);
-
private:
- explicit CSSValueList(ValueListSeparator);
-
HeapVector<Member<const CSSValue>, 4> values_;
DISALLOW_COPY_AND_ASSIGN(CSSValueList);
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_value_pair.h b/chromium/third_party/blink/renderer/core/css/css_value_pair.h
index 211ec99feb6..92312f72ffb 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value_pair.h
+++ b/chromium/third_party/blink/renderer/core/css/css_value_pair.h
@@ -34,7 +34,19 @@ class CORE_EXPORT CSSValuePair : public CSSValue {
static CSSValuePair* Create(const CSSValue* first,
const CSSValue* second,
IdenticalValuesPolicy identical_values_policy) {
- return new CSSValuePair(first, second, identical_values_policy);
+ return MakeGarbageCollected<CSSValuePair>(first, second,
+ identical_values_policy);
+ }
+
+ CSSValuePair(const CSSValue* first,
+ const CSSValue* second,
+ IdenticalValuesPolicy identical_values_policy)
+ : CSSValue(kValuePairClass),
+ first_(first),
+ second_(second),
+ identical_values_policy_(identical_values_policy) {
+ DCHECK(first_);
+ DCHECK(second_);
}
const CSSValue& First() const { return *first_; }
@@ -61,17 +73,6 @@ class CORE_EXPORT CSSValuePair : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSValuePair(const CSSValue* first,
- const CSSValue* second,
- IdenticalValuesPolicy identical_values_policy)
- : CSSValue(kValuePairClass),
- first_(first),
- second_(second),
- identical_values_policy_(identical_values_policy) {
- DCHECK(first_);
- DCHECK(second_);
- }
-
Member<const CSSValue> first_;
Member<const CSSValue> second_;
IdenticalValuesPolicy identical_values_policy_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_value_pool.cc b/chromium/third_party/blink/renderer/core/css/css_value_pool.cc
index 147ed0eb85d..7d8e1ecde74 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value_pool.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_value_pool.cc
@@ -37,7 +37,7 @@ CSSValuePool& CssValuePool() {
thread_specific_pool, ());
Persistent<CSSValuePool>& pool_handle = *thread_specific_pool;
if (!pool_handle) {
- pool_handle = new CSSValuePool;
+ pool_handle = MakeGarbageCollected<CSSValuePool>();
pool_handle.RegisterAsStaticReference();
}
return *pool_handle;
@@ -45,11 +45,13 @@ CSSValuePool& CssValuePool() {
CSSValuePool::CSSValuePool()
: inherited_value_(new CSSInheritedValue),
- initial_value_(new CSSInitialValue()),
+ initial_value_(MakeGarbageCollected<CSSInitialValue>()),
unset_value_(new CSSUnsetValue),
- color_transparent_(new CSSColorValue(Color::kTransparent)),
- color_white_(new CSSColorValue(Color::kWhite)),
- color_black_(new CSSColorValue(Color::kBlack)) {
+ invalid_variable_value_(new CSSInvalidVariableValue),
+ color_transparent_(
+ MakeGarbageCollected<CSSColorValue>(Color::kTransparent)),
+ color_white_(MakeGarbageCollected<CSSColorValue>(Color::kWhite)),
+ color_black_(MakeGarbageCollected<CSSColorValue>(Color::kBlack)) {
identifier_value_cache_.resize(numCSSValueKeywords);
pixel_value_cache_.resize(kMaximumCacheableIntegerValue + 1);
percent_value_cache_.resize(kMaximumCacheableIntegerValue + 1);
@@ -60,6 +62,7 @@ void CSSValuePool::Trace(blink::Visitor* visitor) {
visitor->Trace(inherited_value_);
visitor->Trace(initial_value_);
visitor->Trace(unset_value_);
+ visitor->Trace(invalid_variable_value_);
visitor->Trace(color_transparent_);
visitor->Trace(color_white_);
visitor->Trace(color_black_);
diff --git a/chromium/third_party/blink/renderer/core/css/css_value_pool.h b/chromium/third_party/blink/renderer/core/css/css_value_pool.h
index ecfe36cddba..b0ad715acf8 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value_pool.h
+++ b/chromium/third_party/blink/renderer/core/css/css_value_pool.h
@@ -35,10 +35,11 @@
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_inherited_value.h"
#include "third_party/blink/renderer/core/css/css_initial_value.h"
+#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_unset_value.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string_hash.h"
@@ -60,6 +61,8 @@ class CORE_EXPORT CSSValuePool
static const unsigned kMaximumFontFaceCacheSize = 128;
using FontFamilyValueCache = HeapHashMap<String, Member<CSSFontFamilyValue>>;
+ CSSValuePool();
+
// Cached individual values.
CSSColorValue* TransparentColor() { return color_transparent_; }
CSSColorValue* WhiteColor() { return color_white_; }
@@ -67,6 +70,9 @@ class CORE_EXPORT CSSValuePool
CSSInheritedValue* InheritedValue() { return inherited_value_; }
CSSInitialValue* InitialValue() { return initial_value_; }
CSSUnsetValue* UnsetValue() { return unset_value_; }
+ CSSInvalidVariableValue* InvalidVariableValue() {
+ return invalid_variable_value_;
+ }
// Vector caches.
CSSIdentifierValue* IdentifierCacheValue(CSSValueID ident) {
@@ -120,12 +126,11 @@ class CORE_EXPORT CSSValuePool
void Trace(blink::Visitor*);
private:
- CSSValuePool();
-
// Cached individual values.
Member<CSSInheritedValue> inherited_value_;
Member<CSSInitialValue> initial_value_;
Member<CSSUnsetValue> unset_value_;
+ Member<CSSInvalidVariableValue> invalid_variable_value_;
Member<CSSColorValue> color_transparent_;
Member<CSSColorValue> color_white_;
Member<CSSColorValue> color_black_;
diff --git a/chromium/third_party/blink/renderer/core/css/css_variable_reference_value.h b/chromium/third_party/blink/renderer/core/css/css_variable_reference_value.h
index b79c7e4e4e4..278f07d6f65 100644
--- a/chromium/third_party/blink/renderer/core/css/css_variable_reference_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_variable_reference_value.h
@@ -16,13 +16,25 @@ class CSSVariableReferenceValue : public CSSValue {
public:
static CSSVariableReferenceValue* Create(
scoped_refptr<CSSVariableData> data) {
- return new CSSVariableReferenceValue(std::move(data));
+ return MakeGarbageCollected<CSSVariableReferenceValue>(std::move(data));
}
static CSSVariableReferenceValue* Create(scoped_refptr<CSSVariableData> data,
const CSSParserContext& context) {
- return new CSSVariableReferenceValue(std::move(data), context);
+ return MakeGarbageCollected<CSSVariableReferenceValue>(std::move(data),
+ context);
}
+ CSSVariableReferenceValue(scoped_refptr<CSSVariableData> data)
+ : CSSValue(kVariableReferenceClass),
+ data_(std::move(data)),
+ parser_context_(nullptr) {}
+
+ CSSVariableReferenceValue(scoped_refptr<CSSVariableData> data,
+ const CSSParserContext& context)
+ : CSSValue(kVariableReferenceClass),
+ data_(std::move(data)),
+ parser_context_(context) {}
+
CSSVariableData* VariableDataValue() const { return data_.get(); }
const CSSParserContext* ParserContext() const {
DCHECK(parser_context_);
@@ -37,18 +49,6 @@ class CSSVariableReferenceValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor*);
private:
- CSSVariableReferenceValue(scoped_refptr<CSSVariableData> data)
- : CSSValue(kVariableReferenceClass),
- data_(std::move(data)),
- parser_context_(nullptr) {}
-
- CSSVariableReferenceValue(scoped_refptr<CSSVariableData> data,
- const CSSParserContext& context)
- : CSSValue(kVariableReferenceClass),
- data_(std::move(data)),
- parser_context_(context) {
- }
-
scoped_refptr<CSSVariableData> data_;
Member<const CSSParserContext> parser_context_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_viewport_rule.h b/chromium/third_party/blink/renderer/core/css/css_viewport_rule.h
index ec49f61f634..4ed4ce89d57 100644
--- a/chromium/third_party/blink/renderer/core/css/css_viewport_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_viewport_rule.h
@@ -46,8 +46,10 @@ class CSSViewportRule final : public CSSRule {
public:
static CSSViewportRule* Create(StyleRuleViewport* viewport_rule,
CSSStyleSheet* sheet) {
- return new CSSViewportRule(viewport_rule, sheet);
+ return MakeGarbageCollected<CSSViewportRule>(viewport_rule, sheet);
}
+
+ CSSViewportRule(StyleRuleViewport*, CSSStyleSheet*);
~CSSViewportRule() override;
String cssText() const override;
@@ -58,8 +60,6 @@ class CSSViewportRule final : public CSSRule {
void Trace(blink::Visitor*) override;
private:
- CSSViewportRule(StyleRuleViewport*, CSSStyleSheet*);
-
CSSRule::Type type() const override { return kViewportRule; }
Member<StyleRuleViewport> viewport_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.cc b/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.cc
index 16d58911f2d..e7c767f2c26 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/css/css_function_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_variable_data.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
@@ -234,7 +235,8 @@ const CSSValue* ComputedStylePropertyMap::GetProperty(
default:
return CSSProperty::Get(property_id)
.CSSValueFromComputedStyle(*style, nullptr /* layout_object */,
- StyledNode(), false);
+ StyledNode(),
+ false /* allow_visited_style */);
}
}
@@ -243,8 +245,10 @@ const CSSValue* ComputedStylePropertyMap::GetCustomProperty(
const ComputedStyle* style = UpdateStyle();
if (!style)
return nullptr;
- return ComputedStyleCSSValueMapping::Get(
- property_name, *style, node_->GetDocument().GetPropertyRegistry());
+ CSSPropertyRef ref(property_name, node_->GetDocument());
+ return ref.GetProperty().CSSValueFromComputedStyle(
+ *style, nullptr /* layout_object */, StyledNode(),
+ false /* allow_visited_style */);
}
void ComputedStylePropertyMap::ForEachProperty(
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.h b/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.h
index 4c517e14fbb..9fa239bacc2 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h"
#include "third_party/blink/renderer/core/css/css_selector.h"
-#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h"
+#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h"
#include "third_party/blink/renderer/core/dom/node.h"
namespace blink {
@@ -17,11 +17,13 @@ namespace blink {
// API. The specification is here:
// https://drafts.css-houdini.org/css-typed-om/#computed-StylePropertyMapReadOnly-objects
//
-// The computed StylePropertyMapReadOnly retrieves computed styles and returns
-// them as CSSStyleValues. The IDL for this class is in StylePropertyMap.idl.
-// The computed StylePropertyMapReadOnly for an element is accessed via
-// element.computedStyleMap() (see ElementComputedStyleMap.idl/h)
-class CORE_EXPORT ComputedStylePropertyMap : public StylePropertyMapReadOnly {
+// The computed StylePropertyMapReadOnlyMainThread retrieves computed styles and
+// returns them as CSSStyleValues. The IDL for this class is in
+// StylePropertyMap.idl. The computed StylePropertyMapReadOnlyMainThread for an
+// element is accessed via element.computedStyleMap() (see
+// ElementComputedStyleMap.idl/h)
+class CORE_EXPORT ComputedStylePropertyMap
+ : public StylePropertyMapReadOnlyMainThread {
public:
static ComputedStylePropertyMap* Create(Node* node) {
return new ComputedStylePropertyMap(node);
@@ -29,7 +31,7 @@ class CORE_EXPORT ComputedStylePropertyMap : public StylePropertyMapReadOnly {
void Trace(blink::Visitor* visitor) override {
visitor->Trace(node_);
- StylePropertyMapReadOnly::Trace(visitor);
+ StylePropertyMapReadOnlyMainThread::Trace(visitor);
}
unsigned int size() override;
@@ -41,7 +43,7 @@ class CORE_EXPORT ComputedStylePropertyMap : public StylePropertyMapReadOnly {
protected:
ComputedStylePropertyMap(Node* node, const String& pseudo_element = String())
- : StylePropertyMapReadOnly(),
+ : StylePropertyMapReadOnlyMainThread(),
pseudo_id_(CSSSelector::ParsePseudoId(pseudo_element)),
node_(node) {}
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.cc
index b23b9d6e813..a1de447a133 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.cc
@@ -22,18 +22,18 @@ CSSKeywordValue* CSSKeywordValue::Create(const String& keyword,
"CSSKeywordValue does not support empty strings");
return nullptr;
}
- return new CSSKeywordValue(keyword);
+ return MakeGarbageCollected<CSSKeywordValue>(keyword);
}
CSSKeywordValue* CSSKeywordValue::FromCSSValue(const CSSValue& value) {
if (value.IsInheritedValue())
- return new CSSKeywordValue(getValueName(CSSValueInherit));
+ return MakeGarbageCollected<CSSKeywordValue>(getValueName(CSSValueInherit));
if (value.IsInitialValue())
- return new CSSKeywordValue(getValueName(CSSValueInitial));
+ return MakeGarbageCollected<CSSKeywordValue>(getValueName(CSSValueInitial));
if (value.IsUnsetValue())
- return new CSSKeywordValue(getValueName(CSSValueUnset));
+ return MakeGarbageCollected<CSSKeywordValue>(getValueName(CSSValueUnset));
if (value.IsIdentifierValue()) {
- return new CSSKeywordValue(
+ return MakeGarbageCollected<CSSKeywordValue>(
getValueName(ToCSSIdentifierValue(value).GetValueID()));
}
if (value.IsCustomIdentValue()) {
@@ -43,7 +43,7 @@ CSSKeywordValue* CSSKeywordValue::FromCSSValue(const CSSValue& value) {
// CSSKeywordValue represents a RHS.
return nullptr;
}
- return new CSSKeywordValue(ident_value.Value());
+ return MakeGarbageCollected<CSSKeywordValue>(ident_value.Value());
}
NOTREACHED();
return nullptr;
@@ -51,7 +51,7 @@ CSSKeywordValue* CSSKeywordValue::FromCSSValue(const CSSValue& value) {
CSSKeywordValue* CSSKeywordValue::Create(const String& keyword) {
DCHECK(!keyword.IsEmpty());
- return new CSSKeywordValue(keyword);
+ return MakeGarbageCollected<CSSKeywordValue>(keyword);
}
const String& CSSKeywordValue::value() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.h
index 8ecb9824756..77acd90166e 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_keyword_value.h
@@ -22,6 +22,8 @@ class CORE_EXPORT CSSKeywordValue final : public CSSStyleValue {
static CSSKeywordValue* Create(const String& keyword, ExceptionState&);
static CSSKeywordValue* FromCSSValue(const CSSValue&);
+ explicit CSSKeywordValue(const String& keyword) : keyword_value_(keyword) {}
+
StyleValueType GetType() const override { return kKeywordType; }
const String& value() const;
@@ -31,8 +33,6 @@ class CORE_EXPORT CSSKeywordValue final : public CSSStyleValue {
const CSSValue* ToCSSValue() const override;
private:
- explicit CSSKeywordValue(const String& keyword) : keyword_value_(keyword) {}
-
String keyword_value_;
DISALLOW_COPY_AND_ASSIGN(CSSKeywordValue);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_invert.h b/chromium/third_party/blink/renderer/core/css/cssom/css_math_invert.h
index 2d164c6d2e1..134df106c0d 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_invert.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_invert.h
@@ -22,10 +22,13 @@ class CORE_EXPORT CSSMathInvert : public CSSMathValue {
}
// Blink-internal constructor
static CSSMathInvert* Create(CSSNumericValue* value) {
- return new CSSMathInvert(
+ return MakeGarbageCollected<CSSMathInvert>(
value, CSSNumericValueType::NegateExponents(value->Type()));
}
+ CSSMathInvert(CSSNumericValue* value, const CSSNumericValueType& type)
+ : CSSMathValue(type), value_(value) {}
+
String getOperator() const final { return "invert"; }
void value(CSSNumberish& value) { value.SetCSSNumericValue(value_); }
@@ -56,9 +59,6 @@ class CORE_EXPORT CSSMathInvert : public CSSMathValue {
}
private:
- CSSMathInvert(CSSNumericValue* value, const CSSNumericValueType& type)
- : CSSMathValue(type), value_(value) {}
-
// From CSSNumericValue
CSSNumericValue* Invert() final { return value_.Get(); }
base::Optional<CSSNumericSumValue> SumValue() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.cc
index afad8017ee3..07986816d82 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.cc
@@ -31,8 +31,8 @@ CSSMathMax* CSSMathMax::Create(CSSNumericValueVector values) {
CSSNumericValueType final_type =
CSSMathVariadic::TypeCheck(values, CSSNumericValueType::Add, error);
return error ? nullptr
- : new CSSMathMax(CSSNumericArray::Create(std::move(values)),
- final_type);
+ : MakeGarbageCollected<CSSMathMax>(
+ CSSNumericArray::Create(std::move(values)), final_type);
}
base::Optional<CSSNumericSumValue> CSSMathMax::SumValue() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.h b/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.h
index 7643359418e..c307520d1ee 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_max.h
@@ -22,6 +22,9 @@ class CORE_EXPORT CSSMathMax final : public CSSMathVariadic {
// Blink-internal constructor.
static CSSMathMax* Create(CSSNumericValueVector);
+ CSSMathMax(CSSNumericArray* values, const CSSNumericValueType& type)
+ : CSSMathVariadic(values, type) {}
+
String getOperator() const final { return "max"; }
// From CSSStyleValue.
@@ -33,9 +36,6 @@ class CORE_EXPORT CSSMathMax final : public CSSMathVariadic {
}
private:
- CSSMathMax(CSSNumericArray* values, const CSSNumericValueType& type)
- : CSSMathVariadic(values, type) {}
-
void BuildCSSText(Nested, ParenLess, StringBuilder&) const final;
base::Optional<CSSNumericSumValue> SumValue() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.cc
index 49afba461d3..93cf2c90e64 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.cc
@@ -31,8 +31,8 @@ CSSMathMin* CSSMathMin::Create(CSSNumericValueVector values) {
CSSNumericValueType final_type =
CSSMathVariadic::TypeCheck(values, CSSNumericValueType::Add, error);
return error ? nullptr
- : new CSSMathMin(CSSNumericArray::Create(std::move(values)),
- final_type);
+ : MakeGarbageCollected<CSSMathMin>(
+ CSSNumericArray::Create(std::move(values)), final_type);
}
base::Optional<CSSNumericSumValue> CSSMathMin::SumValue() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.h b/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.h
index 7edde5b0f85..6f7dbdb6b6e 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_min.h
@@ -24,6 +24,9 @@ class CORE_EXPORT CSSMathMin final : public CSSMathVariadic {
// Blink-internal constructor.
static CSSMathMin* Create(CSSNumericValueVector);
+ CSSMathMin(CSSNumericArray* values, const CSSNumericValueType& type)
+ : CSSMathVariadic(values, type) {}
+
String getOperator() const final { return "min"; }
// From CSSStyleValue.
@@ -35,9 +38,6 @@ class CORE_EXPORT CSSMathMin final : public CSSMathVariadic {
}
private:
- CSSMathMin(CSSNumericArray* values, const CSSNumericValueType& type)
- : CSSMathVariadic(values, type) {}
-
void BuildCSSText(Nested, ParenLess, StringBuilder&) const final;
base::Optional<CSSNumericSumValue> SumValue() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_negate.h b/chromium/third_party/blink/renderer/core/css/cssom/css_math_negate.h
index 56201d2614f..b80022290f5 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_negate.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_negate.h
@@ -22,9 +22,12 @@ class CORE_EXPORT CSSMathNegate : public CSSMathValue {
}
// Blink-internal constructor
static CSSMathNegate* Create(CSSNumericValue* value) {
- return new CSSMathNegate(value, value->Type());
+ return MakeGarbageCollected<CSSMathNegate>(value, value->Type());
}
+ CSSMathNegate(CSSNumericValue* value, const CSSNumericValueType& type)
+ : CSSMathValue(type), value_(value) {}
+
String getOperator() const final { return "negate"; }
void value(CSSNumberish& value) { value.SetCSSNumericValue(value_); }
@@ -55,9 +58,6 @@ class CORE_EXPORT CSSMathNegate : public CSSMathValue {
}
private:
- CSSMathNegate(CSSNumericValue* value, const CSSNumericValueType& type)
- : CSSMathValue(type), value_(value) {}
-
// From CSSNumericValue
CSSNumericValue* Negate() final { return value_.Get(); }
base::Optional<CSSNumericSumValue> SumValue() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.cc
index 88a6435c7dd..f38e313c93d 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.cc
@@ -53,8 +53,8 @@ CSSMathProduct* CSSMathProduct::Create(CSSNumericValueVector values) {
CSSNumericValueType final_type =
CSSMathVariadic::TypeCheck(values, CSSNumericValueType::Multiply, error);
return error ? nullptr
- : new CSSMathProduct(CSSNumericArray::Create(std::move(values)),
- final_type);
+ : MakeGarbageCollected<CSSMathProduct>(
+ CSSNumericArray::Create(std::move(values)), final_type);
}
base::Optional<CSSNumericSumValue> CSSMathProduct::SumValue() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.h b/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.h
index 3fa5ced14b4..f0b32102198 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_product.h
@@ -22,6 +22,9 @@ class CORE_EXPORT CSSMathProduct final : public CSSMathVariadic {
// Blink internal-constructor.
static CSSMathProduct* Create(CSSNumericValueVector);
+ CSSMathProduct(CSSNumericArray* values, const CSSNumericValueType& type)
+ : CSSMathVariadic(values, type) {}
+
String getOperator() const final { return "product"; }
// From CSSStyleValue.
@@ -30,9 +33,6 @@ class CORE_EXPORT CSSMathProduct final : public CSSMathVariadic {
CSSCalcExpressionNode* ToCalcExpressionNode() const final;
private:
- CSSMathProduct(CSSNumericArray* values, const CSSNumericValueType& type)
- : CSSMathVariadic(values, type) {}
-
void BuildCSSText(Nested, ParenLess, StringBuilder&) const final;
base::Optional<CSSNumericSumValue> SumValue() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.cc
index b468e1d776f..a69b0904610 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.cc
@@ -71,8 +71,8 @@ CSSMathSum* CSSMathSum::Create(CSSNumericValueVector values) {
CSSNumericValueType final_type =
CSSMathVariadic::TypeCheck(values, CSSNumericValueType::Add, error);
return error ? nullptr
- : new CSSMathSum(CSSNumericArray::Create(std::move(values)),
- final_type);
+ : MakeGarbageCollected<CSSMathSum>(
+ CSSNumericArray::Create(std::move(values)), final_type);
}
base::Optional<CSSNumericSumValue> CSSMathSum::SumValue() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.h b/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.h
index 69398350506..0ff1d04455b 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.h
@@ -22,6 +22,9 @@ class CORE_EXPORT CSSMathSum final : public CSSMathVariadic {
// Blink-internal constructor.
static CSSMathSum* Create(CSSNumericValueVector);
+ CSSMathSum(CSSNumericArray* values, const CSSNumericValueType& type)
+ : CSSMathVariadic(values, type) {}
+
String getOperator() const final { return "sum"; }
// From CSSStyleValue.
@@ -30,9 +33,6 @@ class CORE_EXPORT CSSMathSum final : public CSSMathVariadic {
CSSCalcExpressionNode* ToCalcExpressionNode() const final;
private:
- CSSMathSum(CSSNumericArray* values, const CSSNumericValueType& type)
- : CSSMathVariadic(values, type) {}
-
void BuildCSSText(Nested, ParenLess, StringBuilder&) const final;
base::Optional<CSSNumericSumValue> SumValue() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.cc
index 29b3b6b6eff..568cfb74e25 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.cc
@@ -28,9 +28,9 @@ DOMMatrix* To2DMatrix(DOMMatrixReadOnly* matrix) {
CSSMatrixComponent* CSSMatrixComponent::Create(
DOMMatrixReadOnly* matrix,
- const CSSMatrixComponentOptions& options) {
- return new CSSMatrixComponent(
- matrix, options.hasIs2D() ? options.is2D() : matrix->is2D());
+ const CSSMatrixComponentOptions* options) {
+ return MakeGarbageCollected<CSSMatrixComponent>(
+ matrix, options->hasIs2D() ? options->is2D() : matrix->is2D());
}
DOMMatrix* CSSMatrixComponent::toMatrix(ExceptionState&) const {
@@ -47,7 +47,7 @@ CSSMatrixComponent* CSSMatrixComponent::FromCSSValue(
return CSSMatrixComponent::Create(
DOMMatrixReadOnly::CreateForSerialization(entries.data(), entries.size()),
- CSSMatrixComponentOptions());
+ CSSMatrixComponentOptions::Create());
}
const CSSFunctionValue* CSSMatrixComponent::ToCSSValue() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.h b/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.h
index 2f3537272e1..e60ebefee2c 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.h
@@ -23,11 +23,14 @@ class CORE_EXPORT CSSMatrixComponent final : public CSSTransformComponent {
public:
// Constructors defined in the IDL.
static CSSMatrixComponent* Create(DOMMatrixReadOnly*,
- const CSSMatrixComponentOptions&);
+ const CSSMatrixComponentOptions*);
// Blink-internal ways of creating CSSMatrixComponents.
static CSSMatrixComponent* FromCSSValue(const CSSFunctionValue&);
+ CSSMatrixComponent(DOMMatrixReadOnly* matrix, bool is2D)
+ : CSSTransformComponent(is2D), matrix_(DOMMatrix::Create(matrix)) {}
+
// Getters and setters for attributes defined in the IDL.
DOMMatrix* matrix() { return matrix_.Get(); }
void setMatrix(DOMMatrix* matrix) { matrix_ = matrix; }
@@ -44,9 +47,6 @@ class CORE_EXPORT CSSMatrixComponent final : public CSSTransformComponent {
}
private:
- CSSMatrixComponent(DOMMatrixReadOnly* matrix, bool is2D)
- : CSSTransformComponent(is2D), matrix_(DOMMatrix::Create(matrix)) {}
-
Member<DOMMatrix> matrix_;
DISALLOW_COPY_AND_ASSIGN(CSSMatrixComponent);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_array.h b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_array.h
index fbd9c5ea161..529f6a463ba 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_array.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_array.h
@@ -17,13 +17,17 @@ class CORE_EXPORT CSSNumericArray final : public ScriptWrappable {
public:
// blink internal
static CSSNumericArray* Create(CSSNumericValueVector values) {
- return new CSSNumericArray(std::move(values));
+ return MakeGarbageCollected<CSSNumericArray>(std::move(values));
}
static CSSNumericArray* FromNumberishes(
const HeapVector<CSSNumberish>& values) {
- return new CSSNumericArray(CSSNumberishesToNumericValues(values));
+ return MakeGarbageCollected<CSSNumericArray>(
+ CSSNumberishesToNumericValues(values));
}
+ explicit CSSNumericArray(CSSNumericValueVector values)
+ : values_(std::move(values)) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(values_);
ScriptWrappable::Trace(visitor);
@@ -39,9 +43,6 @@ class CORE_EXPORT CSSNumericArray final : public ScriptWrappable {
const CSSNumericValueVector& Values() const { return values_; }
private:
- explicit CSSNumericArray(CSSNumericValueVector values)
- : values_(std::move(values)) {}
-
CSSNumericValueVector values_;
DISALLOW_COPY_AND_ASSIGN(CSSNumericArray);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc
index 14b9576b6bd..34e865b98bb 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc
@@ -364,27 +364,29 @@ CSSMathSum* CSSNumericValue::toSum(const Vector<String>& unit_strings,
return value;
}
-void CSSNumericValue::type(CSSNumericType& type) const {
+CSSNumericType* CSSNumericValue::type() const {
+ CSSNumericType* type = CSSNumericType::Create();
using BaseType = CSSNumericValueType::BaseType;
if (int exponent = type_.Exponent(BaseType::kLength))
- type.setLength(exponent);
+ type->setLength(exponent);
if (int exponent = type_.Exponent(BaseType::kAngle))
- type.setAngle(exponent);
+ type->setAngle(exponent);
if (int exponent = type_.Exponent(BaseType::kTime))
- type.setTime(exponent);
+ type->setTime(exponent);
if (int exponent = type_.Exponent(BaseType::kFrequency))
- type.setFrequency(exponent);
+ type->setFrequency(exponent);
if (int exponent = type_.Exponent(BaseType::kResolution))
- type.setResolution(exponent);
+ type->setResolution(exponent);
if (int exponent = type_.Exponent(BaseType::kFlex))
- type.setFlex(exponent);
+ type->setFlex(exponent);
if (int exponent = type_.Exponent(BaseType::kPercent))
- type.setPercent(exponent);
+ type->setPercent(exponent);
if (type_.HasPercentHint()) {
- type.setPercentHint(
+ type->setPercentHint(
CSSNumericValueType::BaseTypeToString(type_.PercentHint()));
}
+ return type;
}
CSSNumericValue* CSSNumericValue::add(
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.h
index 89937e7a8c1..ecdd7bfd4e9 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.h
@@ -50,7 +50,7 @@ class CORE_EXPORT CSSNumericValue : public CSSStyleValue {
CSSUnitValue* to(const String&, ExceptionState&);
CSSMathSum* toSum(const Vector<String>&, ExceptionState&);
- void type(CSSNumericType&) const;
+ CSSNumericType* type() const;
String toString() const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.cc
index e6969ce5359..e992b7f3a45 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.cc
@@ -26,7 +26,7 @@ CSSPerspective* CSSPerspective::Create(CSSNumericValue* length,
exception_state.ThrowTypeError("Must pass length to CSSPerspective");
return nullptr;
}
- return new CSSPerspective(length);
+ return MakeGarbageCollected<CSSPerspective>(length);
}
void CSSPerspective::setLength(CSSNumericValue* length,
@@ -43,7 +43,7 @@ CSSPerspective* CSSPerspective::FromCSSValue(const CSSFunctionValue& value) {
DCHECK_EQ(value.length(), 1U);
CSSNumericValue* length =
CSSNumericValue::FromCSSValue(ToCSSPrimitiveValue(value.Item(0)));
- return new CSSPerspective(length);
+ return MakeGarbageCollected<CSSPerspective>(length);
}
DOMMatrix* CSSPerspective::toMatrix(ExceptionState& exception_state) const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.h b/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.h
index 3e78565edf8..ff15be0e46a 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_perspective.h
@@ -28,6 +28,8 @@ class CORE_EXPORT CSSPerspective final : public CSSTransformComponent {
// Blink-internal ways of creating CSSPerspectives.
static CSSPerspective* FromCSSValue(const CSSFunctionValue&);
+ CSSPerspective(CSSNumericValue* length);
+
// Getters and setters for attributes defined in the IDL.
CSSNumericValue* length() { return length_.Get(); }
void setLength(CSSNumericValue*, ExceptionState&);
@@ -49,8 +51,6 @@ class CORE_EXPORT CSSPerspective final : public CSSTransformComponent {
}
private:
- CSSPerspective(CSSNumericValue* length);
-
Member<CSSNumericValue> length_;
DISALLOW_COPY_AND_ASSIGN(CSSPerspective);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.cc
index 81c2b3cc8ca..1ed55ac309b 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.cc
@@ -86,14 +86,14 @@ CSSPositionValue* CSSPositionValue::Create(CSSNumericValue* x,
"Must pass length or percentage to y in CSSPositionValue");
return nullptr;
}
- return new CSSPositionValue(x, y);
+ return MakeGarbageCollected<CSSPositionValue>(x, y);
}
CSSPositionValue* CSSPositionValue::Create(CSSNumericValue* x,
CSSNumericValue* y) {
if (!IsValidPositionCoord(x) || !IsValidPositionCoord(y))
return nullptr;
- return new CSSPositionValue(x, y);
+ return MakeGarbageCollected<CSSPositionValue>(x, y);
}
CSSPositionValue* CSSPositionValue::FromCSSValue(const CSSValue& value) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.h
index 4b720156427..4d9d1ac5d93 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_position_value.h
@@ -29,6 +29,8 @@ class CORE_EXPORT CSSPositionValue final : public CSSStyleValue {
static CSSPositionValue* FromCSSValue(const CSSValue&);
+ CSSPositionValue(CSSNumericValue* x, CSSNumericValue* y) : x_(x), y_(y) {}
+
// Getters and setters defined in the IDL.
CSSNumericValue* x() { return x_.Get(); }
CSSNumericValue* y() { return y_.Get(); }
@@ -50,8 +52,6 @@ class CORE_EXPORT CSSPositionValue final : public CSSStyleValue {
static bool IsValidCoordinate(CSSNumericValue* coord);
protected:
- CSSPositionValue(CSSNumericValue* x, CSSNumericValue* y) : x_(x), y_(y) {}
-
Member<CSSNumericValue> x_;
Member<CSSNumericValue> y_;
DISALLOW_COPY_AND_ASSIGN(CSSPositionValue);
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.cc
index 51bd5f8503d..f746471b546 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.cc
@@ -75,8 +75,9 @@ CSSRotate* CSSRotate::Create(CSSNumericValue* angle,
exception_state.ThrowTypeError("Must pass an angle to CSSRotate");
return nullptr;
}
- return new CSSRotate(CSSUnitValue::Create(0), CSSUnitValue::Create(0),
- CSSUnitValue::Create(1), angle, true /* is2D */);
+ return MakeGarbageCollected<CSSRotate>(
+ CSSUnitValue::Create(0), CSSUnitValue::Create(0), CSSUnitValue::Create(1),
+ angle, true /* is2D */);
}
CSSRotate* CSSRotate::Create(const CSSNumberish& x,
@@ -97,19 +98,21 @@ CSSRotate* CSSRotate::Create(const CSSNumberish& x,
exception_state.ThrowTypeError("Must pass an angle to CSSRotate");
return nullptr;
}
- return new CSSRotate(x_value, y_value, z_value, angle, false /* is2D */);
+ return MakeGarbageCollected<CSSRotate>(x_value, y_value, z_value, angle,
+ false /* is2D */);
}
CSSRotate* CSSRotate::Create(CSSNumericValue* angle) {
- return new CSSRotate(CSSUnitValue::Create(0), CSSUnitValue::Create(0),
- CSSUnitValue::Create(1), angle, true /* is2D */);
+ return MakeGarbageCollected<CSSRotate>(
+ CSSUnitValue::Create(0), CSSUnitValue::Create(0), CSSUnitValue::Create(1),
+ angle, true /* is2D */);
}
CSSRotate* CSSRotate::Create(CSSNumericValue* x,
CSSNumericValue* y,
CSSNumericValue* z,
CSSNumericValue* angle) {
- return new CSSRotate(x, y, z, angle, false /* is2D */);
+ return MakeGarbageCollected<CSSRotate>(x, y, z, angle, false /* is2D */);
}
CSSRotate* CSSRotate::FromCSSValue(const CSSFunctionValue& value) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.h b/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.h
index 7b3659aa052..f0a5f04a575 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_rotate.h
@@ -38,6 +38,12 @@ class CORE_EXPORT CSSRotate final : public CSSTransformComponent {
CSSNumericValue* angle);
static CSSRotate* FromCSSValue(const CSSFunctionValue&);
+ CSSRotate(CSSNumericValue* x,
+ CSSNumericValue* y,
+ CSSNumericValue* z,
+ CSSNumericValue* angle,
+ bool is2D);
+
// Getters and setters for attributes defined in the IDL.
CSSNumericValue* angle() { return angle_.Get(); }
void setAngle(CSSNumericValue* angle, ExceptionState&);
@@ -63,12 +69,6 @@ class CORE_EXPORT CSSRotate final : public CSSTransformComponent {
}
private:
- CSSRotate(CSSNumericValue* x,
- CSSNumericValue* y,
- CSSNumericValue* z,
- CSSNumericValue* angle,
- bool is2D);
-
Member<CSSNumericValue> angle_;
Member<CSSNumericValue> x_;
Member<CSSNumericValue> y_;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_scale.h b/chromium/third_party/blink/renderer/core/css/cssom/css_scale.h
index 76bcf7736e6..e564e330d76 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_scale.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_scale.h
@@ -33,15 +33,21 @@ class CORE_EXPORT CSSScale final : public CSSTransformComponent {
// Blink-internal ways of creating CSSScales.
static CSSScale* Create(CSSNumericValue* x, CSSNumericValue* y) {
- return new CSSScale(x, y, CSSUnitValue::Create(1), true /* is2D */);
+ return MakeGarbageCollected<CSSScale>(x, y, CSSUnitValue::Create(1),
+ true /* is2D */);
}
static CSSScale* Create(CSSNumericValue* x,
CSSNumericValue* y,
CSSNumericValue* z) {
- return new CSSScale(x, y, z, false /* is2D */);
+ return MakeGarbageCollected<CSSScale>(x, y, z, false /* is2D */);
}
static CSSScale* FromCSSValue(const CSSFunctionValue&);
+ CSSScale(CSSNumericValue* x,
+ CSSNumericValue* y,
+ CSSNumericValue* z,
+ bool is2D);
+
// Getters and setters for attributes defined in the IDL.
void x(CSSNumberish& x) { x.SetCSSNumericValue(x_); }
void y(CSSNumberish& y) { y.SetCSSNumericValue(y_); }
@@ -64,11 +70,6 @@ class CORE_EXPORT CSSScale final : public CSSTransformComponent {
}
private:
- CSSScale(CSSNumericValue* x,
- CSSNumericValue* y,
- CSSNumericValue* z,
- bool is2D);
-
Member<CSSNumericValue> x_;
Member<CSSNumericValue> y_;
Member<CSSNumericValue> z_;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_skew.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_skew.cc
index 9bf1634eff4..22584e4eff8 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_skew.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_skew.cc
@@ -30,7 +30,7 @@ CSSSkew* CSSSkew::Create(CSSNumericValue* ax,
exception_state.ThrowTypeError("CSSSkew does not support non-angles");
return nullptr;
}
- return new CSSSkew(ax, ay);
+ return MakeGarbageCollected<CSSSkew>(ax, ay);
}
void CSSSkew::setAx(CSSNumericValue* value, ExceptionState& exception_state) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_skew.h b/chromium/third_party/blink/renderer/core/css/cssom/css_skew.h
index 6b4d7d711f0..9fddbe91471 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_skew.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_skew.h
@@ -24,12 +24,14 @@ class CORE_EXPORT CSSSkew final : public CSSTransformComponent {
// Constructor defined in the IDL.
static CSSSkew* Create(CSSNumericValue*, CSSNumericValue*, ExceptionState&);
static CSSSkew* Create(CSSNumericValue* ax, CSSNumericValue* ay) {
- return new CSSSkew(ax, ay);
+ return MakeGarbageCollected<CSSSkew>(ax, ay);
}
// Internal ways of creating CSSSkew.
static CSSSkew* FromCSSValue(const CSSFunctionValue&);
+ CSSSkew(CSSNumericValue* ax, CSSNumericValue* ay);
+
// Getters and setters for the ax and ay attributes defined in the IDL.
CSSNumericValue* ax() { return ax_.Get(); }
CSSNumericValue* ay() { return ay_.Get(); }
@@ -54,8 +56,6 @@ class CORE_EXPORT CSSSkew final : public CSSTransformComponent {
}
private:
- CSSSkew(CSSNumericValue* ax, CSSNumericValue* ay);
-
Member<CSSNumericValue> ax_;
Member<CSSNumericValue> ay_;
DISALLOW_COPY_AND_ASSIGN(CSSSkew);
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.cc
index 424665d8524..cfaa123f171 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.cc
@@ -29,7 +29,7 @@ CSSSkewX* CSSSkewX::Create(CSSNumericValue* ax,
exception_state.ThrowTypeError("CSSSkewX does not support non-angles");
return nullptr;
}
- return new CSSSkewX(ax);
+ return MakeGarbageCollected<CSSSkewX>(ax);
}
void CSSSkewX::setAx(CSSNumericValue* value, ExceptionState& exception_state) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.h b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.h
index ce9aec9ae8c..7e16aac2c3e 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_x.h
@@ -23,11 +23,15 @@ class CORE_EXPORT CSSSkewX final : public CSSTransformComponent {
public:
// Constructor defined in the IDL.
static CSSSkewX* Create(CSSNumericValue*, ExceptionState&);
- static CSSSkewX* Create(CSSNumericValue* ax) { return new CSSSkewX(ax); }
+ static CSSSkewX* Create(CSSNumericValue* ax) {
+ return MakeGarbageCollected<CSSSkewX>(ax);
+ }
// Internal ways of creating CSSSkewX.
static CSSSkewX* FromCSSValue(const CSSFunctionValue&);
+ CSSSkewX(CSSNumericValue* ax);
+
// Getters and setters for the ax attributes defined in the IDL.
CSSNumericValue* ax() { return ax_.Get(); }
void setAx(CSSNumericValue*, ExceptionState&);
@@ -49,8 +53,6 @@ class CORE_EXPORT CSSSkewX final : public CSSTransformComponent {
}
private:
- CSSSkewX(CSSNumericValue* ax);
-
Member<CSSNumericValue> ax_;
DISALLOW_COPY_AND_ASSIGN(CSSSkewX);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.cc
index f064f891e0e..d491642b3df 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.cc
@@ -29,7 +29,7 @@ CSSSkewY* CSSSkewY::Create(CSSNumericValue* ay,
exception_state.ThrowTypeError("CSSSkewY does not support non-angles");
return nullptr;
}
- return new CSSSkewY(ay);
+ return MakeGarbageCollected<CSSSkewY>(ay);
}
void CSSSkewY::setAy(CSSNumericValue* value, ExceptionState& exception_state) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.h b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.h
index cb133668085..10378a73b9a 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_skew_y.h
@@ -23,11 +23,15 @@ class CORE_EXPORT CSSSkewY final : public CSSTransformComponent {
public:
// Constructor defined in the IDL.
static CSSSkewY* Create(CSSNumericValue*, ExceptionState&);
- static CSSSkewY* Create(CSSNumericValue* ay) { return new CSSSkewY(ay); }
+ static CSSSkewY* Create(CSSNumericValue* ay) {
+ return MakeGarbageCollected<CSSSkewY>(ay);
+ }
// Internal ways of creating CSSSkewY.
static CSSSkewY* FromCSSValue(const CSSFunctionValue&);
+ CSSSkewY(CSSNumericValue* ay);
+
// Getters and setters for the ay attributes defined in the IDL.
CSSNumericValue* ay() { return ay_.Get(); }
void setAy(CSSNumericValue*, ExceptionState&);
@@ -49,8 +53,6 @@ class CORE_EXPORT CSSSkewY final : public CSSTransformComponent {
}
private:
- CSSSkewY(CSSNumericValue* ay);
-
Member<CSSNumericValue> ay_;
DISALLOW_COPY_AND_ASSIGN(CSSSkewY);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.h
index 2e6a16201b5..2d1f43bf1a3 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.h
@@ -8,13 +8,14 @@
#include "base/macros.h"
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
+class CSSSyntaxComponent;
class ExceptionState;
class ExecutionContext;
enum class SecureContextMode;
@@ -66,7 +67,9 @@ class CORE_EXPORT CSSStyleValue : public ScriptWrappable {
virtual const CSSValue* ToCSSValue() const = 0;
// FIXME: We should make this a method on CSSProperty instead.
- virtual const CSSValue* ToCSSValueWithProperty(CSSPropertyID) const {
+ virtual const CSSValue* ToCSSValueWithProperty(
+ CSSPropertyID,
+ const CSSSyntaxComponent*) const {
return ToCSSValue();
}
virtual String toString() const;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.cc
index 444ce68626b..9a5859364d4 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.cc
@@ -30,7 +30,8 @@ CSSStyleVariableReferenceValue* CSSStyleVariableReferenceValue::Create(
CSSUnparsedValue* fallback) {
if (!variable.StartsWith("--"))
return nullptr;
- return new CSSStyleVariableReferenceValue(variable, fallback);
+ return MakeGarbageCollected<CSSStyleVariableReferenceValue>(variable,
+ fallback);
}
void CSSStyleVariableReferenceValue::setVariable(
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.h
index 87fd19e0dc8..2173b0cef9a 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_style_variable_reference_value.h
@@ -32,6 +32,10 @@ class CORE_EXPORT CSSStyleVariableReferenceValue final
const String& variable,
CSSUnparsedValue* fallback = nullptr);
+ CSSStyleVariableReferenceValue(const String& variable,
+ CSSUnparsedValue* fallback)
+ : variable_(variable), fallback_(fallback) {}
+
const String& variable() const { return variable_; }
void setVariable(const String&, ExceptionState&);
@@ -44,10 +48,6 @@ class CORE_EXPORT CSSStyleVariableReferenceValue final
}
protected:
- CSSStyleVariableReferenceValue(const String& variable,
- CSSUnparsedValue* fallback)
- : variable_(variable), fallback_(fallback) {}
-
String variable_;
Member<CSSUnparsedValue> fallback_;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.cc
index 3a85ef3a30a..3247963c4c9 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.cc
@@ -28,7 +28,7 @@ CSSTransformValue* CSSTransformValue::Create(
const HeapVector<Member<CSSTransformComponent>>& transform_components) {
if (transform_components.IsEmpty())
return nullptr;
- return new CSSTransformValue(transform_components);
+ return MakeGarbageCollected<CSSTransformValue>(transform_components);
}
CSSTransformValue* CSSTransformValue::FromCSSValue(const CSSValue& css_value) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.h
index 8a6dc7a5236..c7bcc5a4103 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_transform_value.h
@@ -30,6 +30,10 @@ class CORE_EXPORT CSSTransformValue final : public CSSStyleValue {
static CSSTransformValue* FromCSSValue(const CSSValue&);
+ CSSTransformValue(
+ const HeapVector<Member<CSSTransformComponent>>& transform_components)
+ : CSSStyleValue(), transform_components_(transform_components) {}
+
bool is2D() const;
DOMMatrix* toMatrix(ExceptionState&) const;
@@ -53,10 +57,6 @@ class CORE_EXPORT CSSTransformValue final : public CSSStyleValue {
}
private:
- CSSTransformValue(
- const HeapVector<Member<CSSTransformComponent>>& transform_components)
- : CSSStyleValue(), transform_components_(transform_components) {}
-
HeapVector<Member<CSSTransformComponent>> transform_components_;
DISALLOW_COPY_AND_ASSIGN(CSSTransformValue);
};
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_translate.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_translate.cc
index f571a1e4758..3a40305704d 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_translate.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_translate.cc
@@ -92,7 +92,7 @@ CSSTranslate* CSSTranslate::Create(CSSNumericValue* x,
"Must pass length or percentage to X and Y of CSSTranslate");
return nullptr;
}
- return new CSSTranslate(
+ return MakeGarbageCollected<CSSTranslate>(
x, y, CSSUnitValue::Create(0, CSSPrimitiveValue::UnitType::kPixels),
true /* is2D */);
}
@@ -107,11 +107,11 @@ CSSTranslate* CSSTranslate::Create(CSSNumericValue* x,
"Must pass length or percentage to X, Y and Z of CSSTranslate");
return nullptr;
}
- return new CSSTranslate(x, y, z, false /* is2D */);
+ return MakeGarbageCollected<CSSTranslate>(x, y, z, false /* is2D */);
}
CSSTranslate* CSSTranslate::Create(CSSNumericValue* x, CSSNumericValue* y) {
- return new CSSTranslate(
+ return MakeGarbageCollected<CSSTranslate>(
x, y, CSSUnitValue::Create(0, CSSPrimitiveValue::UnitType::kPixels),
true /* is2D */);
}
@@ -119,7 +119,7 @@ CSSTranslate* CSSTranslate::Create(CSSNumericValue* x, CSSNumericValue* y) {
CSSTranslate* CSSTranslate::Create(CSSNumericValue* x,
CSSNumericValue* y,
CSSNumericValue* z) {
- return new CSSTranslate(x, y, z, false /* is2D */);
+ return MakeGarbageCollected<CSSTranslate>(x, y, z, false /* is2D */);
}
CSSTranslate* CSSTranslate::FromCSSValue(const CSSFunctionValue& value) {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_translate.h b/chromium/third_party/blink/renderer/core/css/cssom/css_translate.h
index 34ff0ba7015..e28fa08ee1c 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_translate.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_translate.h
@@ -40,6 +40,11 @@ class CORE_EXPORT CSSTranslate final : public CSSTransformComponent {
CSSNumericValue* z);
static CSSTranslate* FromCSSValue(const CSSFunctionValue&);
+ CSSTranslate(CSSNumericValue* x,
+ CSSNumericValue* y,
+ CSSNumericValue* z,
+ bool is2D);
+
// Getters and setters for attributes defined in the IDL.
CSSNumericValue* x() { return x_; }
CSSNumericValue* y() { return y_; }
@@ -62,11 +67,6 @@ class CORE_EXPORT CSSTranslate final : public CSSTransformComponent {
}
private:
- CSSTranslate(CSSNumericValue* x,
- CSSNumericValue* y,
- CSSNumericValue* z,
- bool is2D);
-
Member<CSSNumericValue> x_;
Member<CSSNumericValue> y_;
Member<CSSNumericValue> z_;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.cc
index 22b3c060978..5af88ff840d 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/core/animation/length_property_functions.h"
#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_resolution_units.h"
+#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/cssom/css_math_invert.h"
#include "third_party/blink/renderer/core/css/cssom/css_math_max.h"
#include "third_party/blink/renderer/core/css/cssom/css_math_min.h"
@@ -37,7 +38,8 @@ CSSPrimitiveValue::UnitType ToCanonicalUnitIfPossible(
bool IsValueOutOfRangeForProperty(CSSPropertyID property_id,
double value,
- CSSPrimitiveValue::UnitType unit) {
+ CSSPrimitiveValue::UnitType unit,
+ const CSSSyntaxComponent* match) {
// FIXME: Avoid this CSSProperty::Get call as it can be costly.
// The caller often has a CSSProperty already, so we can just pass it here.
if (LengthPropertyFunctions::GetValueRange(CSSProperty::Get(property_id)) ==
@@ -47,6 +49,10 @@ bool IsValueOutOfRangeForProperty(CSSPropertyID property_id,
// For non-length properties and special cases.
switch (property_id) {
+ case CSSPropertyVariable:
+ if (match && match->IsInteger())
+ return round(value) != value;
+ return false;
case CSSPropertyOrder:
case CSSPropertyZIndex:
return round(value) != value;
@@ -91,13 +97,13 @@ CSSUnitValue* CSSUnitValue::Create(double value,
exception_state.ThrowTypeError("Invalid unit: " + unit_name);
return nullptr;
}
- return new CSSUnitValue(value, unit);
+ return MakeGarbageCollected<CSSUnitValue>(value, unit);
}
CSSUnitValue* CSSUnitValue::Create(double value,
CSSPrimitiveValue::UnitType unit) {
DCHECK(IsValidUnit(unit));
- return new CSSUnitValue(value, unit);
+ return MakeGarbageCollected<CSSUnitValue>(value, unit);
}
CSSUnitValue* CSSUnitValue::FromCSSValue(const CSSPrimitiveValue& value) {
@@ -107,7 +113,7 @@ CSSUnitValue* CSSUnitValue::FromCSSValue(const CSSPrimitiveValue& value) {
if (!IsValidUnit(unit))
return nullptr;
- return new CSSUnitValue(value.GetDoubleValue(), unit);
+ return MakeGarbageCollected<CSSUnitValue>(value.GetDoubleValue(), unit);
}
String CSSUnitValue::unit() const {
@@ -167,8 +173,9 @@ const CSSPrimitiveValue* CSSUnitValue::ToCSSValue() const {
}
const CSSPrimitiveValue* CSSUnitValue::ToCSSValueWithProperty(
- CSSPropertyID property_id) const {
- if (IsValueOutOfRangeForProperty(property_id, value_, unit_)) {
+ CSSPropertyID property_id,
+ const CSSSyntaxComponent* match) const {
+ if (IsValueOutOfRangeForProperty(property_id, value_, unit_, match)) {
// Wrap out of range values with a calc.
CSSCalcExpressionNode* node = ToCalcExpressionNode();
node->SetIsNestedCalc();
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.h
index 127d3a8605c..3d5b8ddfbb5 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.h
@@ -28,6 +28,11 @@ class CORE_EXPORT CSSUnitValue final : public CSSNumericValue {
CSSPrimitiveValue::UnitType = CSSPrimitiveValue::UnitType::kNumber);
static CSSUnitValue* FromCSSValue(const CSSPrimitiveValue&);
+ CSSUnitValue(double value, CSSPrimitiveValue::UnitType unit)
+ : CSSNumericValue(CSSNumericValueType(unit)),
+ value_(value),
+ unit_(unit) {}
+
// Setters and getters for attributes defined in the IDL.
void setValue(double new_value) { value_ = new_value; }
double value() const { return value_; }
@@ -46,15 +51,12 @@ class CORE_EXPORT CSSUnitValue final : public CSSNumericValue {
// From CSSStyleValue.
StyleValueType GetType() const final;
const CSSPrimitiveValue* ToCSSValue() const final;
- const CSSPrimitiveValue* ToCSSValueWithProperty(CSSPropertyID) const final;
+ const CSSPrimitiveValue* ToCSSValueWithProperty(
+ CSSPropertyID,
+ const CSSSyntaxComponent*) const final;
CSSCalcExpressionNode* ToCalcExpressionNode() const final;
private:
- CSSUnitValue(double value, CSSPrimitiveValue::UnitType unit)
- : CSSNumericValue(CSSNumericValueType(unit)),
- value_(value),
- unit_(unit) {}
-
double ConvertFixedLength(CSSPrimitiveValue::UnitType) const;
double ConvertAngle(CSSPrimitiveValue::UnitType) const;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h
index a8b7d2268f4..dc29d1e65d7 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h
@@ -23,7 +23,7 @@ class CORE_EXPORT CSSUnparsedValue final : public CSSStyleValue {
public:
static CSSUnparsedValue* Create(
const HeapVector<CSSUnparsedSegment>& tokens) {
- return new CSSUnparsedValue(tokens);
+ return MakeGarbageCollected<CSSUnparsedValue>(tokens);
}
// Blink-internal constructor
@@ -34,6 +34,9 @@ class CORE_EXPORT CSSUnparsedValue final : public CSSStyleValue {
static CSSUnparsedValue* FromCSSValue(const CSSCustomPropertyDeclaration&);
static CSSUnparsedValue* FromCSSVariableData(const CSSVariableData&);
+ CSSUnparsedValue(const HeapVector<CSSUnparsedSegment>& tokens)
+ : CSSStyleValue(), tokens_(tokens) {}
+
const CSSValue* ToCSSValue() const override;
StyleValueType GetType() const override { return kUnparsedType; }
@@ -50,10 +53,6 @@ class CORE_EXPORT CSSUnparsedValue final : public CSSStyleValue {
CSSStyleValue::Trace(visitor);
}
- protected:
- CSSUnparsedValue(const HeapVector<CSSUnparsedSegment>& tokens)
- : CSSStyleValue(), tokens_(tokens) {}
-
private:
static CSSUnparsedValue* FromString(const String& string) {
HeapVector<CSSUnparsedSegment> tokens;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.cc
index 894e4747c90..3da34b07a9a 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.cc
@@ -4,8 +4,8 @@
#include "third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.h
index 5a384a11df7..ce971b49259 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_unsupported_style_value.h
@@ -20,15 +20,23 @@ class CORE_EXPORT CSSUnsupportedStyleValue final : public CSSStyleValue {
CSSPropertyID property,
const AtomicString& custom_property_name,
const String& css_text) {
- return new CSSUnsupportedStyleValue(property, custom_property_name,
- css_text);
+ return MakeGarbageCollected<CSSUnsupportedStyleValue>(
+ property, custom_property_name, css_text);
}
static CSSUnsupportedStyleValue* Create(
CSSPropertyID property,
const AtomicString& custom_property_name,
const CSSValue& value) {
- return new CSSUnsupportedStyleValue(property, custom_property_name,
- value.CssText());
+ return MakeGarbageCollected<CSSUnsupportedStyleValue>(
+ property, custom_property_name, value.CssText());
+ }
+
+ CSSUnsupportedStyleValue(CSSPropertyID property,
+ const AtomicString& custom_property_name,
+ const String& css_text)
+ : property_(property), custom_property_name_(custom_property_name) {
+ SetCSSText(css_text);
+ DCHECK_EQ(property == CSSPropertyVariable, !custom_property_name.IsNull());
}
StyleValueType GetType() const override {
@@ -46,14 +54,6 @@ class CORE_EXPORT CSSUnsupportedStyleValue final : public CSSStyleValue {
String toString() const final { return CSSText(); }
private:
- CSSUnsupportedStyleValue(CSSPropertyID property,
- const AtomicString& custom_property_name,
- const String& css_text)
- : property_(property), custom_property_name_(custom_property_name) {
- SetCSSText(css_text);
- DCHECK_EQ(property == CSSPropertyVariable, !custom_property_name.IsNull());
- }
-
const CSSPropertyID property_;
// Name is set when property_ is CSSPropertyVariable, otherwise it's
// g_null_atom.
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.cc
index d0bb96c66fe..97005aba840 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.cc
@@ -25,12 +25,12 @@ CSSURLImageValue* CSSURLImageValue::Create(ScriptState* script_state,
}
// Use absolute URL for CSSImageValue but keep relative URL for
// getter and serialization.
- return new CSSURLImageValue(
+ return MakeGarbageCollected<CSSURLImageValue>(
*CSSImageValue::Create(url, parsed_url, Referrer()));
}
CSSURLImageValue* CSSURLImageValue::FromCSSValue(const CSSImageValue& value) {
- return new CSSURLImageValue(value);
+ return MakeGarbageCollected<CSSURLImageValue>(value);
}
const String& CSSURLImageValue::url() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.h b/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.h
index 81ce5e2e6db..9635cb30954 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.h
@@ -21,6 +21,8 @@ class CORE_EXPORT CSSURLImageValue final : public CSSStyleImageValue {
static CSSURLImageValue* FromCSSValue(const CSSImageValue&);
+ explicit CSSURLImageValue(const CSSImageValue& value) : value_(value) {}
+
const String& url() const;
// CSSStyleImageValue
@@ -40,8 +42,6 @@ class CORE_EXPORT CSSURLImageValue final : public CSSStyleImageValue {
void Trace(blink::Visitor*) override;
private:
- explicit CSSURLImageValue(const CSSImageValue& value) : value_(value) {}
-
scoped_refptr<Image> GetImage() const;
Member<const CSSImageValue> value_;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/cssom_keywords.h b/chromium/third_party/blink/renderer/core/css/cssom/cssom_keywords.h
index 3e5388eb8b3..86bd5e28f91 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/cssom_keywords.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/cssom_keywords.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSSOM_KEYWORDS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSSOM_KEYWORDS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/cssom_types.h b/chromium/third_party/blink/renderer/core/css/cssom/cssom_types.h
index e96cf7a5709..d43ebea52f2 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/cssom_types.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/cssom_types.h
@@ -5,8 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSSOM_TYPES_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSSOM_TYPES_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -33,10 +33,15 @@ class CSSOMTypes {
static bool IsCSSStyleValuePosition(const CSSStyleValue&);
static bool IsPropertySupported(CSSPropertyID);
+ // For registered custom properties, if the CSSStyleValue is accepted
+ // because it matches the registered grammar (and not because it is
+ // a CSSUnsupportedStyleValue with matching name), 'match' will be set
+ // to the component that was matched.
static bool PropertyCanTake(CSSPropertyID,
const AtomicString& custom_property_name,
const PropertyRegistration*,
- const CSSStyleValue&);
+ const CSSStyleValue&,
+ const CSSSyntaxComponent*& match);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.cc b/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.cc
index d7beaf9eae8..310444d9973 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/css/css_variable_data.h"
#include "third_party/blink/renderer/core/css/cssom/computed_style_property_map.h"
#include "third_party/blink/renderer/core/css/cssom/css_unparsed_value.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
@@ -20,7 +21,7 @@ PrepopulatedComputedStylePropertyMap::PrepopulatedComputedStylePropertyMap(
Node* styled_node,
const Vector<CSSPropertyID>& native_properties,
const Vector<AtomicString>& custom_properties)
- : StylePropertyMapReadOnly(), styled_node_(styled_node) {
+ : StylePropertyMapReadOnlyMainThread(), styled_node_(styled_node) {
// NOTE: This may over-reserve as shorthand properties will get dropped from
// being in the map.
native_values_.ReserveCapacityForSize(native_properties.size());
@@ -71,8 +72,10 @@ void PrepopulatedComputedStylePropertyMap::UpdateCustomProperty(
const Document& document,
const ComputedStyle& style,
const AtomicString& property_name) {
- const CSSValue* value = ComputedStyleCSSValueMapping::Get(
- property_name, style, document.GetPropertyRegistry());
+ CSSPropertyRef ref(property_name, document);
+ const CSSValue* value = ref.GetProperty().CSSValueFromComputedStyle(
+ style, /* layout_object */ nullptr, styled_node_,
+ /* allow_visited_style */ false);
if (!value)
value = CSSUnparsedValue::Create()->ToCSSValue();
@@ -125,7 +128,7 @@ void PrepopulatedComputedStylePropertyMap::Trace(blink::Visitor* visitor) {
visitor->Trace(styled_node_);
visitor->Trace(native_values_);
visitor->Trace(custom_values_);
- StylePropertyMapReadOnly::Trace(visitor);
+ StylePropertyMapReadOnlyMainThread::Trace(visitor);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.h b/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.h
index f691eafe73f..7d346e5f2ad 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/css/css_property_id_templates.h"
-#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h"
+#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h"
namespace blink {
@@ -24,7 +24,7 @@ class ComputedStyle;
// result when the ComputedStyle changes UpdateStyle needs to be called to
// re-populate the internal maps.
class CORE_EXPORT PrepopulatedComputedStylePropertyMap
- : public StylePropertyMapReadOnly {
+ : public StylePropertyMapReadOnlyMainThread {
public:
// NOTE: styled_node may be null, in the case where this map is for an
// anonymous box.
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map_test.cc b/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map_test.cc
index 4fec89eb08f..30e93f2bee1 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map_test.cc
@@ -39,11 +39,11 @@ TEST_F(PrepopulatedComputedStylePropertyMapTest, NativePropertyAccessors) {
{CSSPropertyColor, CSSPropertyAlignItems});
Vector<AtomicString> empty_custom_properties;
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* node = PageNode();
PrepopulatedComputedStylePropertyMap* map =
- new PrepopulatedComputedStylePropertyMap(
+ MakeGarbageCollected<PrepopulatedComputedStylePropertyMap>(
GetDocument(), node->ComputedStyleRef(), node, native_properties,
empty_custom_properties);
@@ -75,11 +75,11 @@ TEST_F(PrepopulatedComputedStylePropertyMapTest, CustomPropertyAccessors) {
Vector<CSSPropertyID> empty_native_properties;
Vector<AtomicString> custom_properties({"--foo", "--bar"});
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* node = PageNode();
PrepopulatedComputedStylePropertyMap* map =
- new PrepopulatedComputedStylePropertyMap(
+ MakeGarbageCollected<PrepopulatedComputedStylePropertyMap>(
GetDocument(), node->ComputedStyleRef(), node,
empty_native_properties, custom_properties);
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.cc b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.cc
index adc08f09890..3994c6abc7e 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.cc
@@ -22,6 +22,21 @@ namespace blink {
namespace {
+bool IsListValuedProperty(const CSSProperty& property,
+ const PropertyRegistration* registration) {
+ if (property.IsRepeated())
+ return true;
+ // TODO(andruud): The concept of "list-valued properties" doesn't fully work
+ // in all cases. See https://github.com/w3c/css-houdini-drafts/issues/823
+ // For now we only consider a custom property list-valued if it has a single
+ // syntax component that is repeatable (e.g. <length>+).
+ if (property.IDEquals(CSSPropertyVariable) && registration) {
+ const auto& components = registration->Syntax().Components();
+ return components.size() == 1 && components[0].IsRepeatable();
+ }
+ return false;
+}
+
CSSValueList* CssValueListForPropertyID(CSSPropertyID property_id) {
DCHECK(CSSProperty::Get(property_id).IsRepeated());
char separator = CSSProperty::Get(property_id).RepetitionSeparator();
@@ -38,6 +53,56 @@ CSSValueList* CssValueListForPropertyID(CSSPropertyID property_id) {
}
}
+String StyleValueToString(const CSSProperty& property,
+ const CSSStyleValue& style_value,
+ const CSSSyntaxComponent* syntax_component) {
+ if (style_value.GetType() == CSSStyleValue::kUnknownType)
+ return style_value.toString();
+ return style_value
+ .ToCSSValueWithProperty(property.PropertyID(), syntax_component)
+ ->CssText();
+}
+
+const CSSVariableReferenceValue* CreateVariableReferenceValue(
+ const String& value,
+ const CSSParserContext& context) {
+ CSSTokenizer tokenizer(value);
+ const auto tokens = tokenizer.TokenizeToEOF();
+ CSSParserTokenRange range(tokens);
+ scoped_refptr<CSSVariableData> variable_data = CSSVariableData::Create(
+ range, false, false, context.BaseURL(), context.Charset());
+ return CSSVariableReferenceValue::Create(variable_data, context);
+}
+
+const CSSVariableReferenceValue* CreateVariableReferenceValue(
+ const CSSProperty& property,
+ const AtomicString& custom_property_name,
+ const PropertyRegistration& registration,
+ const CSSStyleValueVector& values,
+ const CSSParserContext& context) {
+ DCHECK(IsListValuedProperty(property, &registration));
+ DCHECK_EQ(registration.Syntax().Components().size(), 1U);
+
+ char separator = registration.Syntax().Components()[0].Separator();
+
+ StringBuilder builder;
+
+ for (const auto& value : values) {
+ const CSSSyntaxComponent* syntax_component = nullptr;
+
+ if (!CSSOMTypes::PropertyCanTake(property.PropertyID(),
+ custom_property_name, &registration,
+ *value, syntax_component)) {
+ return nullptr;
+ }
+ if (!builder.IsEmpty())
+ builder.Append(separator);
+ builder.Append(StyleValueToString(property, *value, syntax_component));
+ }
+
+ return CreateVariableReferenceValue(builder.ToString(), context);
+}
+
const CSSValue* StyleValueToCSSValue(
const CSSProperty& property,
const AtomicString& custom_property_name,
@@ -47,9 +112,12 @@ const CSSValue* StyleValueToCSSValue(
DCHECK_EQ(property.IDEquals(CSSPropertyVariable),
!custom_property_name.IsNull());
+ const CSSSyntaxComponent* syntax_component = nullptr;
+
const CSSPropertyID property_id = property.PropertyID();
if (!CSSOMTypes::PropertyCanTake(property_id, custom_property_name,
- registration, style_value)) {
+ registration, style_value,
+ syntax_component)) {
return nullptr;
}
@@ -69,13 +137,10 @@ const CSSValue* StyleValueToCSSValue(
case CSSPropertyVariable:
if (registration &&
style_value.GetType() != CSSStyleValue::kUnparsedType) {
- CSSTokenizer tokenizer(style_value.toString());
- const auto tokens = tokenizer.TokenizeToEOF();
- CSSParserTokenRange range(tokens);
CSSParserContext* context = CSSParserContext::Create(execution_context);
- scoped_refptr<CSSVariableData> variable_data = CSSVariableData::Create(
- range, false, false, context->BaseURL(), context->Charset());
- return CSSVariableReferenceValue::Create(variable_data, *context);
+ String string =
+ StyleValueToString(property, style_value, syntax_component);
+ return CreateVariableReferenceValue(string, *context);
}
break;
case CSSPropertyBorderBottomLeftRadius:
@@ -198,7 +263,7 @@ const CSSValue* StyleValueToCSSValue(
break;
}
- return style_value.ToCSSValueWithProperty(property_id);
+ return style_value.ToCSSValueWithProperty(property_id, syntax_component);
}
const CSSValue* CoerceStyleValueOrString(
@@ -207,7 +272,7 @@ const CSSValue* CoerceStyleValueOrString(
const PropertyRegistration* registration,
const CSSStyleValueOrString& value,
const ExecutionContext& execution_context) {
- DCHECK(!property.IsRepeated());
+ DCHECK(!IsListValuedProperty(property, registration));
DCHECK_EQ(property.IDEquals(CSSPropertyVariable),
!custom_property_name.IsNull());
@@ -233,9 +298,10 @@ const CSSValue* CoerceStyleValueOrString(
const CSSValue* CoerceStyleValuesOrStrings(
const CSSProperty& property,
const AtomicString& custom_property_name,
+ const PropertyRegistration* registration,
const HeapVector<CSSStyleValueOrString>& values,
const ExecutionContext& execution_context) {
- DCHECK(property.IsRepeated());
+ DCHECK(IsListValuedProperty(property, registration));
DCHECK_EQ(property.IDEquals(CSSPropertyVariable),
!custom_property_name.IsNull());
if (values.IsEmpty())
@@ -243,11 +309,18 @@ const CSSValue* CoerceStyleValuesOrStrings(
CSSStyleValueVector style_values =
StyleValueFactory::CoerceStyleValuesOrStrings(
- property, custom_property_name, nullptr, values, execution_context);
+ property, custom_property_name, registration, values,
+ execution_context);
if (style_values.IsEmpty())
return nullptr;
+ if (property.IDEquals(CSSPropertyVariable) && registration) {
+ CSSParserContext* context = CSSParserContext::Create(execution_context);
+ return CreateVariableReferenceValue(property, custom_property_name,
+ *registration, style_values, *context);
+ }
+
CSSValueList* result = CssValueListForPropertyID(property.PropertyID());
for (const auto& style_value : style_values) {
const CSSValue* css_value =
@@ -286,8 +359,10 @@ void StylePropertyMap::set(const ExecutionContext* execution_context,
String css_text;
if (values[0].IsCSSStyleValue()) {
CSSStyleValue* style_value = values[0].GetAsCSSStyleValue();
- if (style_value && CSSOMTypes::PropertyCanTake(property_id, g_null_atom,
- nullptr, *style_value)) {
+ const CSSSyntaxComponent* syntax_component = nullptr;
+ if (style_value &&
+ CSSOMTypes::PropertyCanTake(property_id, g_null_atom, nullptr,
+ *style_value, syntax_component)) {
css_text = style_value->toString();
}
} else {
@@ -317,9 +392,10 @@ void StylePropertyMap::set(const ExecutionContext* execution_context,
}
const CSSValue* result = nullptr;
- if (property.IsRepeated()) {
- result = CoerceStyleValuesOrStrings(property, custom_property_name, values,
- *execution_context);
+ if (IsListValuedProperty(property, registration)) {
+ result =
+ CoerceStyleValuesOrStrings(property, custom_property_name, registration,
+ values, *execution_context);
} else if (values.size() == 1U) {
result =
CoerceStyleValueOrString(property, custom_property_name, registration,
@@ -351,13 +427,55 @@ void StylePropertyMap::append(const ExecutionContext* execution_context,
return;
}
+ const CSSProperty& property = CSSProperty::Get(property_id);
+
if (property_id == CSSPropertyVariable) {
+ AtomicString custom_property_name(property_name);
+
+ const PropertyRegistration* registration =
+ PropertyRegistration::From(execution_context, custom_property_name);
+
+ if (registration && IsListValuedProperty(property, registration)) {
+ CSSStyleValueVector style_values;
+
+ // Add existing CSSStyleValues:
+ if (const CSSValue* css_value =
+ GetCustomProperty(*execution_context, custom_property_name)) {
+ DCHECK(css_value->IsValueList());
+ style_values = StyleValueFactory::CssValueToStyleValueVector(
+ property_id, custom_property_name, *css_value);
+ }
+
+ // Append incoming CSSStyleValues:
+ CSSStyleValueVector incoming_style_values =
+ StyleValueFactory::CoerceStyleValuesOrStrings(
+ property, custom_property_name, registration, values,
+ *execution_context);
+
+ const CSSValue* result = nullptr;
+
+ if (!incoming_style_values.IsEmpty()) {
+ style_values.AppendVector(incoming_style_values);
+ CSSParserContext* context =
+ CSSParserContext::Create(*execution_context);
+ result =
+ CreateVariableReferenceValue(property, custom_property_name,
+ *registration, style_values, *context);
+ }
+
+ if (!result) {
+ exception_state.ThrowTypeError("Invalid type for property");
+ return;
+ }
+
+ SetCustomProperty(custom_property_name, *result);
+ return;
+ }
exception_state.ThrowTypeError(
"Appending to custom properties is not supported");
return;
}
- const CSSProperty& property = CSSProperty::Get(property_id);
if (!property.IsRepeated()) {
exception_state.ThrowTypeError("Property does not support multiple values");
return;
@@ -371,10 +489,8 @@ void StylePropertyMap::append(const ExecutionContext* execution_context,
current_value = CssValueListForPropertyID(property_id);
}
- // TODO(andruud): Don't pass g_null_atom as custom property name
- // once appending to custom properties is supported.
const CSSValue* result = CoerceStyleValuesOrStrings(
- property, g_null_atom, values, *execution_context);
+ property, g_null_atom, nullptr, values, *execution_context);
if (!result || !result->IsValueList()) {
exception_state.ThrowTypeError("Invalid type for property");
return;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.h b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.h
index 37b32d505c5..6bbc19bb0f2 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/bindings/core/v8/css_style_value_or_string.h"
-#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h"
+#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
namespace blink {
@@ -15,7 +15,7 @@ namespace blink {
class ExceptionState;
class ExecutionContext;
-class CORE_EXPORT StylePropertyMap : public StylePropertyMapReadOnly {
+class CORE_EXPORT StylePropertyMap : public StylePropertyMapReadOnlyMainThread {
DEFINE_WRAPPERTYPEINFO();
public:
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h
index 49415543ac8..bdb84457ec6 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h
@@ -8,57 +8,29 @@
#include "base/macros.h"
#include "third_party/blink/renderer/bindings/core/v8/iterable.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
namespace blink {
-class CSSProperty;
-
class CORE_EXPORT StylePropertyMapReadOnly
: public ScriptWrappable,
public PairIterable<String, CSSStyleValueVector> {
DEFINE_WRAPPERTYPEINFO();
public:
- using StylePropertyMapEntry = std::pair<String, CSSStyleValueVector>;
-
- ~StylePropertyMapReadOnly() override = default;
-
- CSSStyleValue* get(const ExecutionContext*,
- const String& property_name,
- ExceptionState&);
- CSSStyleValueVector getAll(const ExecutionContext*,
+ virtual CSSStyleValue* get(const ExecutionContext*,
const String& property_name,
- ExceptionState&);
- bool has(const ExecutionContext*,
- const String& property_name,
- ExceptionState&);
+ ExceptionState&) = 0;
+ virtual CSSStyleValueVector getAll(const ExecutionContext*,
+ const String& property_name,
+ ExceptionState&) = 0;
+ virtual bool has(const ExecutionContext*,
+ const String& property_name,
+ ExceptionState&) = 0;
virtual unsigned int size() = 0;
-
- protected:
- StylePropertyMapReadOnly() = default;
-
- virtual const CSSValue* GetProperty(CSSPropertyID) = 0;
- virtual const CSSValue* GetCustomProperty(AtomicString) = 0;
-
- using IterationCallback =
- std::function<void(const AtomicString&, const CSSValue&)>;
- virtual void ForEachProperty(const IterationCallback&) = 0;
-
- virtual String SerializationForShorthand(const CSSProperty&) = 0;
-
- private:
- IterationSource* StartIteration(ScriptState*, ExceptionState&) override;
-
- CSSStyleValue* GetShorthandProperty(const CSSProperty&);
- const CSSValue* GetCustomProperty(const ExecutionContext&,
- const AtomicString&);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(StylePropertyMapReadOnly);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc
index 2a8d4804dae..3adb7f95625 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc
@@ -1,10 +1,11 @@
-// Copyright 2016 the chromium authors. All rights reserved.
+// Copyright 2018 the chromium authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h"
+#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h"
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
@@ -14,7 +15,6 @@
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/property_registration.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -26,7 +26,8 @@ class StylePropertyMapIterationSource final
: public PairIterable<String, CSSStyleValueVector>::IterationSource {
public:
explicit StylePropertyMapIterationSource(
- HeapVector<StylePropertyMapReadOnly::StylePropertyMapEntry> values)
+ HeapVector<StylePropertyMapReadOnlyMainThread::StylePropertyMapEntry>
+ values)
: index_(0), values_(values) {}
bool Next(ScriptState*,
@@ -36,7 +37,7 @@ class StylePropertyMapIterationSource final
if (index_ >= values_.size())
return false;
- const StylePropertyMapReadOnly::StylePropertyMapEntry& pair =
+ const StylePropertyMapReadOnlyMainThread::StylePropertyMapEntry& pair =
values_.at(index_++);
key = pair.first;
value = pair.second;
@@ -50,12 +51,13 @@ class StylePropertyMapIterationSource final
private:
wtf_size_t index_;
- const HeapVector<StylePropertyMapReadOnly::StylePropertyMapEntry> values_;
+ const HeapVector<StylePropertyMapReadOnlyMainThread::StylePropertyMapEntry>
+ values_;
};
} // namespace
-CSSStyleValue* StylePropertyMapReadOnly::get(
+CSSStyleValue* StylePropertyMapReadOnlyMainThread::get(
const ExecutionContext* execution_context,
const String& property_name,
ExceptionState& exception_state) {
@@ -93,7 +95,7 @@ CSSStyleValue* StylePropertyMapReadOnly::get(
custom_property_name, *value);
}
-CSSStyleValueVector StylePropertyMapReadOnly::getAll(
+CSSStyleValueVector StylePropertyMapReadOnlyMainThread::getAll(
const ExecutionContext* execution_context,
const String& property_name,
ExceptionState& exception_state) {
@@ -127,16 +129,29 @@ CSSStyleValueVector StylePropertyMapReadOnly::getAll(
property_id, custom_property_name, *value);
}
-bool StylePropertyMapReadOnly::has(const ExecutionContext* execution_context,
- const String& property_name,
- ExceptionState& exception_state) {
+bool StylePropertyMapReadOnlyMainThread::has(
+ const ExecutionContext* execution_context,
+ const String& property_name,
+ ExceptionState& exception_state) {
return !getAll(execution_context, property_name, exception_state).IsEmpty();
}
-StylePropertyMapReadOnly::IterationSource*
-StylePropertyMapReadOnly::StartIteration(ScriptState* script_state,
- ExceptionState&) {
- HeapVector<StylePropertyMapReadOnly::StylePropertyMapEntry> result;
+const CSSValue* StylePropertyMapReadOnlyMainThread::GetCustomProperty(
+ const ExecutionContext& execution_context,
+ const AtomicString& property_name) {
+ const CSSValue* value = GetCustomProperty(property_name);
+
+ const auto* document = DynamicTo<Document>(execution_context);
+ if (!document)
+ return value;
+
+ return PropertyRegistry::ParseIfRegistered(*document, property_name, value);
+}
+
+StylePropertyMapReadOnlyMainThread::IterationSource*
+StylePropertyMapReadOnlyMainThread::StartIteration(ScriptState* script_state,
+ ExceptionState&) {
+ HeapVector<StylePropertyMapReadOnlyMainThread::StylePropertyMapEntry> result;
const ExecutionContext& execution_context =
*ExecutionContext::From(script_state);
@@ -166,7 +181,7 @@ StylePropertyMapReadOnly::StartIteration(ScriptState* script_state,
return new StylePropertyMapIterationSource(result);
}
-CSSStyleValue* StylePropertyMapReadOnly::GetShorthandProperty(
+CSSStyleValue* StylePropertyMapReadOnlyMainThread::GetShorthandProperty(
const CSSProperty& property) {
DCHECK(property.IsShorthand());
const auto serialization = SerializationForShorthand(property);
@@ -176,16 +191,4 @@ CSSStyleValue* StylePropertyMapReadOnly::GetShorthandProperty(
serialization);
}
-const CSSValue* StylePropertyMapReadOnly::GetCustomProperty(
- const ExecutionContext& execution_context,
- const AtomicString& property_name) {
- const CSSValue* value = GetCustomProperty(property_name);
-
- const auto* document = DynamicTo<Document>(execution_context);
- if (!document)
- return value;
-
- return PropertyRegistry::ParseIfRegistered(*document, property_name, value);
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h
new file mode 100644
index 00000000000..dab11e66550
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h
@@ -0,0 +1,59 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_STYLE_PROPERTY_MAP_READ_ONLY_MAIN_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_STYLE_PROPERTY_MAP_READ_ONLY_MAIN_THREAD_H_
+
+#include "third_party/blink/renderer/core/css/cssom/style_property_map_read_only.h"
+
+namespace blink {
+
+class CSSProperty;
+
+class CORE_EXPORT StylePropertyMapReadOnlyMainThread
+ : public StylePropertyMapReadOnly {
+ public:
+ using StylePropertyMapEntry = std::pair<String, CSSStyleValueVector>;
+
+ ~StylePropertyMapReadOnlyMainThread() override = default;
+
+ CSSStyleValue* get(const ExecutionContext*,
+ const String& property_name,
+ ExceptionState&) override;
+ CSSStyleValueVector getAll(const ExecutionContext*,
+ const String& property_name,
+ ExceptionState&) override;
+ bool has(const ExecutionContext*,
+ const String& property_name,
+ ExceptionState&) override;
+
+ unsigned int size() override = 0;
+
+ protected:
+ StylePropertyMapReadOnlyMainThread() = default;
+
+ virtual const CSSValue* GetProperty(CSSPropertyID) = 0;
+ virtual const CSSValue* GetCustomProperty(AtomicString) = 0;
+
+ using IterationCallback =
+ std::function<void(const AtomicString&, const CSSValue&)>;
+ virtual void ForEachProperty(const IterationCallback&) = 0;
+
+ virtual String SerializationForShorthand(const CSSProperty&) = 0;
+
+ const CSSValue* GetCustomProperty(const ExecutionContext&,
+ const AtomicString&);
+
+ private:
+ IterationSource* StartIteration(ScriptState*, ExceptionState&) override;
+
+ CSSStyleValue* GetShorthandProperty(const CSSProperty&);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(StylePropertyMapReadOnlyMainThread);
+};
+
+} // namespace blink
+
+#endif
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.h b/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.h
index 603aa2f6a9e..094c4635dc1 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.h
@@ -6,8 +6,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_STYLE_VALUE_FACTORY_H_
#include "third_party/blink/renderer/bindings/core/v8/css_style_value_or_string.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/document_style_sheet_collection.h b/chromium/third_party/blink/renderer/core/css/document_style_sheet_collection.h
index ad4361b3bc7..f99ced9a805 100644
--- a/chromium/third_party/blink/renderer/core/css/document_style_sheet_collection.h
+++ b/chromium/third_party/blink/renderer/core/css/document_style_sheet_collection.h
@@ -44,9 +44,11 @@ class DocumentStyleSheetCollection final
: public TreeScopeStyleSheetCollection {
public:
static DocumentStyleSheetCollection* Create(TreeScope& tree_scope) {
- return new DocumentStyleSheetCollection(tree_scope);
+ return MakeGarbageCollected<DocumentStyleSheetCollection>(tree_scope);
}
+ explicit DocumentStyleSheetCollection(TreeScope&);
+
void UpdateActiveStyleSheets(StyleEngine& master_engine);
void CollectStyleSheets(StyleEngine& master_engine,
DocumentStyleSheetCollector&);
@@ -57,8 +59,6 @@ class DocumentStyleSheetCollection final
}
private:
- explicit DocumentStyleSheetCollection(TreeScope&);
-
void CollectStyleSheetsFromCandidates(StyleEngine& master_engine,
DocumentStyleSheetCollector&);
DISALLOW_COPY_AND_ASSIGN(DocumentStyleSheetCollection);
diff --git a/chromium/third_party/blink/renderer/core/css/drag_update_test.cc b/chromium/third_party/blink/renderer/core/css/drag_update_test.cc
index b34d15fd9fd..54682f3e691 100644
--- a/chromium/third_party/blink/renderer/core/css/drag_update_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/drag_update_test.cc
@@ -30,11 +30,13 @@ TEST(DragUpdateTest, AffectedByDragUpdate) {
</div>
)HTML");
- document.View()->UpdateAllLifecyclePhases();
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
unsigned start_count = document.GetStyleEngine().StyleForElementCount();
document.getElementById("div")->SetDragged(true);
- document.View()->UpdateAllLifecyclePhases();
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
unsigned element_count =
document.GetStyleEngine().StyleForElementCount() - start_count;
diff --git a/chromium/third_party/blink/renderer/core/css/element_rule_collector.cc b/chromium/third_party/blink/renderer/core/css/element_rule_collector.cc
index 73d56c10a62..59008329f55 100644
--- a/chromium/third_party/blink/renderer/core/css/element_rule_collector.cc
+++ b/chromium/third_party/blink/renderer/core/css/element_rule_collector.cc
@@ -84,7 +84,7 @@ void ElementRuleCollector::ClearMatchedRules() {
inline StyleRuleList* ElementRuleCollector::EnsureStyleRuleList() {
if (!style_rule_list_)
- style_rule_list_ = new StyleRuleList();
+ style_rule_list_ = MakeGarbageCollected<StyleRuleList>();
return style_rule_list_;
}
@@ -235,9 +235,16 @@ void ElementRuleCollector::CollectMatchingRules(
if (SelectorChecker::MatchesFocusPseudoClass(element))
CollectMatchingRulesForList(match_request.rule_set->FocusPseudoClassRules(),
cascade_order, match_request);
- CollectMatchingRulesForList(
- match_request.rule_set->TagRules(element.LocalNameForSelectorMatching()),
- cascade_order, match_request);
+ if (SelectorChecker::MatchesSpatialNavigationFocusPseudoClass(element)) {
+ CollectMatchingRulesForList(
+ match_request.rule_set->SpatialNavigationFocusPseudoClassRules(),
+ cascade_order, match_request);
+ }
+ AtomicString element_name = matching_ua_rules_
+ ? element.localName()
+ : element.LocalNameForSelectorMatching();
+ CollectMatchingRulesForList(match_request.rule_set->TagRules(element_name),
+ cascade_order, match_request);
CollectMatchingRulesForList(match_request.rule_set->UniversalRules(),
cascade_order, match_request);
}
diff --git a/chromium/third_party/blink/renderer/core/css/font_display.cc b/chromium/third_party/blink/renderer/core/css/font_display.cc
new file mode 100644
index 00000000000..c30ea41239d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/font_display.cc
@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/font_display.h"
+
+#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+
+namespace blink {
+
+FontDisplay CSSValueToFontDisplay(const CSSValue* value) {
+ if (value && value->IsIdentifierValue()) {
+ switch (ToCSSIdentifierValue(value)->GetValueID()) {
+ case CSSValueAuto:
+ return kFontDisplayAuto;
+ case CSSValueBlock:
+ return kFontDisplayBlock;
+ case CSSValueSwap:
+ return kFontDisplaySwap;
+ case CSSValueFallback:
+ return kFontDisplayFallback;
+ case CSSValueOptional:
+ return kFontDisplayOptional;
+ default:
+ break;
+ }
+ }
+ return kFontDisplayAuto;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/font_display.h b/chromium/third_party/blink/renderer/core/css/font_display.h
new file mode 100644
index 00000000000..ede328708df
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/font_display.h
@@ -0,0 +1,25 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_FONT_DISPLAY_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_FONT_DISPLAY_H_
+
+namespace blink {
+
+class CSSValue;
+
+enum FontDisplay {
+ kFontDisplayAuto,
+ kFontDisplayBlock,
+ kFontDisplaySwap,
+ kFontDisplayFallback,
+ kFontDisplayOptional,
+ kFontDisplayEnumMax,
+};
+
+FontDisplay CSSValueToFontDisplay(const CSSValue*);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_FONT_DISPLAY_H_
diff --git a/chromium/third_party/blink/renderer/core/css/font_face.cc b/chromium/third_party/blink/renderer/core/css/font_face.cc
index 88a4b9b9a73..85cb342aa95 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face.cc
@@ -81,26 +81,6 @@ const CSSValue* ParseCSSValue(const ExecutionContext* context,
*parser_context);
}
-FontDisplay CSSValueToFontDisplay(const CSSValue* value) {
- if (value && value->IsIdentifierValue()) {
- switch (ToCSSIdentifierValue(value)->GetValueID()) {
- case CSSValueAuto:
- return kFontDisplayAuto;
- case CSSValueBlock:
- return kFontDisplayBlock;
- case CSSValueSwap:
- return kFontDisplaySwap;
- case CSSValueFallback:
- return kFontDisplayFallback;
- case CSSValueOptional:
- return kFontDisplayOptional;
- default:
- break;
- }
- }
- return kFontDisplayAuto;
-}
-
CSSFontFace* CreateCSSFontFace(FontFace* font_face,
const CSSValue* unicode_range) {
Vector<UnicodeRange> ranges;
@@ -113,7 +93,7 @@ CSSFontFace* CreateCSSFontFace(FontFace* font_face,
}
}
- return new CSSFontFace(font_face, ranges);
+ return MakeGarbageCollected<CSSFontFace>(font_face, ranges);
}
} // namespace
@@ -121,7 +101,7 @@ CSSFontFace* CreateCSSFontFace(FontFace* font_face,
FontFace* FontFace::Create(ExecutionContext* context,
const AtomicString& family,
StringOrArrayBufferOrArrayBufferView& source,
- const FontFaceDescriptors& descriptors) {
+ const FontFaceDescriptors* descriptors) {
if (source.IsString())
return Create(context, family, source.GetAsString(), descriptors);
if (source.IsArrayBuffer())
@@ -137,8 +117,9 @@ FontFace* FontFace::Create(ExecutionContext* context,
FontFace* FontFace::Create(ExecutionContext* context,
const AtomicString& family,
const String& source,
- const FontFaceDescriptors& descriptors) {
- FontFace* font_face = new FontFace(context, family, descriptors);
+ const FontFaceDescriptors* descriptors) {
+ FontFace* font_face =
+ MakeGarbageCollected<FontFace>(context, family, descriptors);
const CSSValue* src = ParseCSSValue(context, source, AtRuleDescriptorID::Src);
if (!src || !src->IsValueList()) {
@@ -155,8 +136,9 @@ FontFace* FontFace::Create(ExecutionContext* context,
FontFace* FontFace::Create(ExecutionContext* context,
const AtomicString& family,
DOMArrayBuffer* source,
- const FontFaceDescriptors& descriptors) {
- FontFace* font_face = new FontFace(context, family, descriptors);
+ const FontFaceDescriptors* descriptors) {
+ FontFace* font_face =
+ MakeGarbageCollected<FontFace>(context, family, descriptors);
font_face->InitCSSFontFace(static_cast<const unsigned char*>(source->Data()),
source->ByteLength());
return font_face;
@@ -165,8 +147,9 @@ FontFace* FontFace::Create(ExecutionContext* context,
FontFace* FontFace::Create(ExecutionContext* context,
const AtomicString& family,
DOMArrayBufferView* source,
- const FontFaceDescriptors& descriptors) {
- FontFace* font_face = new FontFace(context, family, descriptors);
+ const FontFaceDescriptors* descriptors) {
+ FontFace* font_face =
+ MakeGarbageCollected<FontFace>(context, family, descriptors);
font_face->InitCSSFontFace(
static_cast<const unsigned char*>(source->BaseAddress()),
source->byteLength());
@@ -186,7 +169,7 @@ FontFace* FontFace::Create(Document* document,
if (!src || !src->IsValueList())
return nullptr;
- FontFace* font_face = new FontFace(document);
+ FontFace* font_face = MakeGarbageCollected<FontFace>(document);
if (font_face->SetFamilyValue(*family) &&
font_face->SetPropertyFromStyle(properties,
@@ -216,21 +199,21 @@ FontFace::FontFace(ExecutionContext* context)
FontFace::FontFace(ExecutionContext* context,
const AtomicString& family,
- const FontFaceDescriptors& descriptors)
+ const FontFaceDescriptors* descriptors)
: ContextClient(context), family_(family), status_(kUnloaded) {
- SetPropertyFromString(context, descriptors.style(),
+ SetPropertyFromString(context, descriptors->style(),
AtRuleDescriptorID::FontStyle);
- SetPropertyFromString(context, descriptors.weight(),
+ SetPropertyFromString(context, descriptors->weight(),
AtRuleDescriptorID::FontWeight);
- SetPropertyFromString(context, descriptors.stretch(),
+ SetPropertyFromString(context, descriptors->stretch(),
AtRuleDescriptorID::FontStretch);
- SetPropertyFromString(context, descriptors.unicodeRange(),
+ SetPropertyFromString(context, descriptors->unicodeRange(),
AtRuleDescriptorID::UnicodeRange);
- SetPropertyFromString(context, descriptors.variant(),
+ SetPropertyFromString(context, descriptors->variant(),
AtRuleDescriptorID::FontVariant);
- SetPropertyFromString(context, descriptors.featureSettings(),
+ SetPropertyFromString(context, descriptors->featureSettings(),
AtRuleDescriptorID::FontFeatureSettings);
- SetPropertyFromString(context, descriptors.display(),
+ SetPropertyFromString(context, descriptors->display(),
AtRuleDescriptorID::FontDisplay);
}
@@ -379,22 +362,22 @@ bool FontFace::SetFamilyValue(const CSSValue& family_value) {
// types.
switch (ToCSSIdentifierValue(family_value).GetValueID()) {
case CSSValueSerif:
- family = FontFamilyNames::webkit_serif;
+ family = font_family_names::kWebkitSerif;
break;
case CSSValueSansSerif:
- family = FontFamilyNames::webkit_sans_serif;
+ family = font_family_names::kWebkitSansSerif;
break;
case CSSValueCursive:
- family = FontFamilyNames::webkit_cursive;
+ family = font_family_names::kWebkitCursive;
break;
case CSSValueFantasy:
- family = FontFamilyNames::webkit_fantasy;
+ family = font_family_names::kWebkitFantasy;
break;
case CSSValueMonospace:
- family = FontFamilyNames::webkit_monospace;
+ family = font_family_names::kWebkitMonospace;
break;
case CSSValueWebkitPictograph:
- family = FontFamilyNames::webkit_pictograph;
+ family = font_family_names::kWebkitPictograph;
break;
default:
return false;
@@ -725,19 +708,21 @@ void FontFace::InitCSSFontFace(ExecutionContext* context, const CSSValue& src) {
FontSelector* font_selector = nullptr;
if (auto* document = DynamicTo<Document>(context)) {
font_selector = document->GetStyleEngine().GetFontSelector();
- } else if (context->IsWorkerGlobalScope()) {
- font_selector = ToWorkerGlobalScope(context)->GetFontSelector();
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(context)) {
+ font_selector = scope->GetFontSelector();
} else {
NOTREACHED();
}
RemoteFontFaceSource* source =
- new RemoteFontFaceSource(css_font_face_, font_selector,
- CSSValueToFontDisplay(display_.Get()));
+ MakeGarbageCollected<RemoteFontFaceSource>(
+ css_font_face_, font_selector,
+ CSSValueToFontDisplay(display_.Get()));
item.Fetch(context, source);
css_font_face_->AddSource(source);
}
} else {
- css_font_face_->AddSource(new LocalFontFaceSource(item.GetResource()));
+ css_font_face_->AddSource(
+ MakeGarbageCollected<LocalFontFaceSource>(item.GetResource()));
}
}
@@ -789,4 +774,13 @@ bool FontFace::HasPendingActivity() const {
return status_ == kLoading && GetExecutionContext();
}
+FontDisplay FontFace::GetFontDisplayWithFallback() const {
+ if (display_)
+ return CSSValueToFontDisplay(display_.Get());
+ ExecutionContext* context = GetExecutionContext();
+ if (!context || !context->IsDocument())
+ return kFontDisplayAuto;
+ return To<Document>(context)->GetStyleEngine().GetDefaultFontDisplay(family_);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/font_face.h b/chromium/third_party/blink/renderer/core/css/font_face.h
index 05ec831413d..6669a2e5d40 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face.h
+++ b/chromium/third_party/blink/renderer/core/css/font_face.h
@@ -36,6 +36,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_property.h"
#include "third_party/blink/renderer/core/css/css_value.h"
+#include "third_party/blink/renderer/core/css/font_display.h"
#include "third_party/blink/renderer/core/css/parser/at_rule_descriptors.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
@@ -68,9 +69,13 @@ class CORE_EXPORT FontFace : public ScriptWrappable,
static FontFace* Create(ExecutionContext*,
const AtomicString& family,
StringOrArrayBufferOrArrayBufferView&,
- const FontFaceDescriptors&);
+ const FontFaceDescriptors*);
static FontFace* Create(Document*, const StyleRuleFontFace*);
+ explicit FontFace(ExecutionContext*);
+ FontFace(ExecutionContext*,
+ const AtomicString& family,
+ const FontFaceDescriptors*);
~FontFace() override;
const AtomicString& family() const { return family_; }
@@ -108,6 +113,9 @@ class CORE_EXPORT FontFace : public ScriptWrappable,
FontSelectionCapabilities GetFontSelectionCapabilities() const;
CSSFontFace* CssFontFace() { return css_font_face_.Get(); }
size_t ApproximateBlankCharacterCount() const;
+ // Return FontDisplay using the default from @font-feature-values if not
+ // specified on this FontFace.
+ FontDisplay GetFontDisplayWithFallback() const;
void Trace(blink::Visitor*) override;
@@ -130,20 +138,15 @@ class CORE_EXPORT FontFace : public ScriptWrappable,
static FontFace* Create(ExecutionContext*,
const AtomicString& family,
DOMArrayBuffer* source,
- const FontFaceDescriptors&);
+ const FontFaceDescriptors*);
static FontFace* Create(ExecutionContext*,
const AtomicString& family,
DOMArrayBufferView*,
- const FontFaceDescriptors&);
+ const FontFaceDescriptors*);
static FontFace* Create(ExecutionContext*,
const AtomicString& family,
const String& source,
- const FontFaceDescriptors&);
-
- explicit FontFace(ExecutionContext*);
- FontFace(ExecutionContext*,
- const AtomicString& family,
- const FontFaceDescriptors&);
+ const FontFaceDescriptors*);
void InitCSSFontFace(ExecutionContext*, const CSSValue& src);
void InitCSSFontFace(const unsigned char* data, size_t);
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_cache.cc b/chromium/third_party/blink/renderer/core/css/font_face_cache.cc
index 68c4e3cb9aa..0e434aba849 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_cache.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face_cache.cc
@@ -51,8 +51,10 @@ void FontFaceCache::AddFontFace(FontFace* font_face, bool css_connected) {
SegmentedFacesByFamily::AddResult capabilities_result =
segmented_faces_.insert(font_face->family(), nullptr);
- if (capabilities_result.is_new_entry)
- capabilities_result.stored_value->value = new CapabilitiesSet();
+ if (capabilities_result.is_new_entry) {
+ capabilities_result.stored_value->value =
+ MakeGarbageCollected<CapabilitiesSet>();
+ }
DCHECK(font_face->GetFontSelectionCapabilities().IsValid() &&
!font_face->GetFontSelectionCapabilities().IsHashTableDeletedValue());
@@ -156,8 +158,8 @@ CSSSegmentedFontFace* FontFaceCache::Get(
// Either add or retrieve a cache entry in the selection query cache for the
// specified family.
FontSelectionQueryCache::AddResult cache_entry_for_family_add =
- font_selection_query_cache_.insert(family,
- new FontSelectionQueryResult());
+ font_selection_query_cache_.insert(
+ family, MakeGarbageCollected<FontSelectionQueryResult>());
auto cache_entry_for_family = cache_entry_for_family_add.stored_value->value;
const FontSelectionRequest& request =
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set.cc b/chromium/third_party/blink/renderer/core/css/font_face_set.cc
index 2c3ab8ebdc6..d67753bbdfa 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set.cc
@@ -39,7 +39,7 @@ void FontFaceSet::FireLoadingEvent() {
if (should_fire_loading_event_) {
should_fire_loading_event_ = false;
DispatchEvent(
- *FontFaceSetLoadEvent::CreateForFontFaces(EventTypeNames::loading));
+ *FontFaceSetLoadEvent::CreateForFontFaces(event_type_names::kLoading));
}
}
@@ -236,11 +236,11 @@ void FontFaceSet::FireDoneEvent() {
FontFaceSetLoadEvent* done_event = nullptr;
FontFaceSetLoadEvent* error_event = nullptr;
done_event = FontFaceSetLoadEvent::CreateForFontFaces(
- EventTypeNames::loadingdone, loaded_fonts_);
+ event_type_names::kLoadingdone, loaded_fonts_);
loaded_fonts_.clear();
if (!failed_fonts_.IsEmpty()) {
error_event = FontFaceSetLoadEvent::CreateForFontFaces(
- EventTypeNames::loadingerror, failed_fonts_);
+ event_type_names::kLoadingerror, failed_fonts_);
failed_fonts_.clear();
}
is_loading_ = false;
@@ -308,7 +308,7 @@ FontFaceSetIterable::IterationSource* FontFaceSet::StartIteration(
for (const auto& font_face : non_css_connected_faces_)
font_faces.push_back(font_face);
}
- return new IterationSource(font_faces);
+ return MakeGarbageCollected<IterationSource>(font_faces);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set.h b/chromium/third_party/blink/renderer/core/css/font_face_set.h
index 5568339a66c..b56e097baf1 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set.h
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set.h
@@ -51,9 +51,9 @@ class CORE_EXPORT FontFaceSet : public EventTargetWithInlineData,
context.GetTaskRunner(TaskType::kInternalDefault))) {}
~FontFaceSet() override = default;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loading);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingdone);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loading, kLoading);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingdone, kLoadingdone);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingerror, kLoadingerror);
bool check(const String& font, const String& text, ExceptionState&);
ScriptPromise load(ScriptState*, const String& font, const String& text);
@@ -64,7 +64,7 @@ class CORE_EXPORT FontFaceSet : public EventTargetWithInlineData,
}
const AtomicString& InterfaceName() const override {
- return EventTargetNames::FontFaceSet;
+ return event_target_names::kFontFaceSet;
}
FontFaceSet* addForBinding(ScriptState*, FontFace*, ExceptionState&);
@@ -146,7 +146,14 @@ class CORE_EXPORT FontFaceSet : public EventTargetWithInlineData,
public:
static LoadFontPromiseResolver* Create(FontFaceArray faces,
ScriptState* script_state) {
- return new LoadFontPromiseResolver(faces, script_state);
+ return MakeGarbageCollected<LoadFontPromiseResolver>(faces, script_state);
+ }
+
+ LoadFontPromiseResolver(FontFaceArray faces, ScriptState* script_state)
+ : num_loading_(faces.size()),
+ error_occured_(false),
+ resolver_(ScriptPromiseResolver::Create(script_state)) {
+ font_faces_.swap(faces);
}
void LoadFonts();
@@ -158,13 +165,6 @@ class CORE_EXPORT FontFaceSet : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- LoadFontPromiseResolver(FontFaceArray faces, ScriptState* script_state)
- : num_loading_(faces.size()),
- error_occured_(false),
- resolver_(ScriptPromiseResolver::Create(script_state)) {
- font_faces_.swap(faces);
- }
-
HeapVector<Member<FontFace>> font_faces_;
int num_loading_;
bool error_occured_;
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set_document.h b/chromium/third_party/blink/renderer/core/css/font_face_set_document.h
index b1ff2d832bd..0ced9aaa9fc 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set_document.h
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set_document.h
@@ -52,6 +52,7 @@ class CORE_EXPORT FontFaceSetDocument final : public FontFaceSet,
public:
static const char kSupplementName[];
+ explicit FontFaceSetDocument(Document&);
~FontFaceSetDocument() override;
ScriptPromise ready(ScriptState*) override;
@@ -85,11 +86,9 @@ class CORE_EXPORT FontFaceSetDocument final : public FontFaceSet,
private:
static FontFaceSetDocument* Create(Document& document) {
- return new FontFaceSetDocument(document);
+ return MakeGarbageCollected<FontFaceSetDocument>(document);
}
- explicit FontFaceSetDocument(Document&);
-
void FireDoneEventIfPossible() override;
const HeapLinkedHashSet<Member<FontFace>>& CSSConnectedFontFaceList()
const override;
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.cc b/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.cc
index 5fcb64bf46b..7ecec065917 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.cc
@@ -30,6 +30,8 @@
#include "third_party/blink/renderer/core/css/font_face_set_load_event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
+
namespace blink {
FontFaceSetLoadEvent::FontFaceSetLoadEvent(const AtomicString& type,
@@ -38,13 +40,13 @@ FontFaceSetLoadEvent::FontFaceSetLoadEvent(const AtomicString& type,
FontFaceSetLoadEvent::FontFaceSetLoadEvent(
const AtomicString& type,
- const FontFaceSetLoadEventInit& initializer)
- : Event(type, initializer), fontfaces_(initializer.fontfaces()) {}
+ const FontFaceSetLoadEventInit* initializer)
+ : Event(type, initializer), fontfaces_(initializer->fontfaces()) {}
FontFaceSetLoadEvent::~FontFaceSetLoadEvent() = default;
const AtomicString& FontFaceSetLoadEvent::InterfaceName() const {
- return EventNames::FontFaceSetLoadEvent;
+ return event_interface_names::kFontFaceSetLoadEvent;
}
void FontFaceSetLoadEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.h b/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.h
index b1c302791bb..ca012ca0c24 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.h
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set_load_event.h
@@ -44,16 +44,18 @@ class FontFaceSetLoadEvent final : public Event {
public:
static FontFaceSetLoadEvent* Create(
const AtomicString& type,
- const FontFaceSetLoadEventInit& initializer) {
- return new FontFaceSetLoadEvent(type, initializer);
+ const FontFaceSetLoadEventInit* initializer) {
+ return MakeGarbageCollected<FontFaceSetLoadEvent>(type, initializer);
}
static FontFaceSetLoadEvent* CreateForFontFaces(
const AtomicString& type,
const FontFaceArray& fontfaces = FontFaceArray()) {
- return new FontFaceSetLoadEvent(type, fontfaces);
+ return MakeGarbageCollected<FontFaceSetLoadEvent>(type, fontfaces);
}
+ FontFaceSetLoadEvent(const AtomicString&, const FontFaceArray&);
+ FontFaceSetLoadEvent(const AtomicString&, const FontFaceSetLoadEventInit*);
~FontFaceSetLoadEvent() override;
FontFaceArray fontfaces() const { return fontfaces_; }
@@ -63,9 +65,6 @@ class FontFaceSetLoadEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- FontFaceSetLoadEvent(const AtomicString&, const FontFaceArray&);
- FontFaceSetLoadEvent(const AtomicString&, const FontFaceSetLoadEventInit&);
-
FontFaceArray fontfaces_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set_worker.cc b/chromium/third_party/blink/renderer/core/css/font_face_set_worker.cc
index c65f6ab466b..5e7ee27f0fb 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set_worker.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set_worker.cc
@@ -32,7 +32,7 @@ FontFaceSetWorker::FontFaceSetWorker(WorkerGlobalScope& worker)
FontFaceSetWorker::~FontFaceSetWorker() = default;
WorkerGlobalScope* FontFaceSetWorker::GetWorker() const {
- return ToWorkerGlobalScope(GetExecutionContext());
+ return To<WorkerGlobalScope>(GetExecutionContext());
}
AtomicString FontFaceSetWorker::status() const {
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set_worker.h b/chromium/third_party/blink/renderer/core/css/font_face_set_worker.h
index 63c8734a29b..f56d7f2903a 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set_worker.h
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set_worker.h
@@ -29,6 +29,7 @@ class CORE_EXPORT FontFaceSetWorker final
public:
static const char kSupplementName[];
+ explicit FontFaceSetWorker(WorkerGlobalScope&);
~FontFaceSetWorker() override;
ScriptPromise ready(ScriptState*) override;
@@ -65,11 +66,9 @@ class CORE_EXPORT FontFaceSetWorker final
private:
static FontFaceSetWorker* Create(WorkerGlobalScope& worker) {
- return new FontFaceSetWorker(worker);
+ return MakeGarbageCollected<FontFaceSetWorker>(worker);
}
- explicit FontFaceSetWorker(WorkerGlobalScope&);
-
void FireDoneEventIfPossible() override;
DISALLOW_COPY_AND_ASSIGN(FontFaceSetWorker);
};
diff --git a/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.cc b/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.cc
index 3e7201ed8cf..bbb0eb61bd3 100644
--- a/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.cc
+++ b/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.cc
@@ -43,7 +43,7 @@ void InlineCSSStyleDeclaration::DidMutate(MutationType type) {
parent_element_->ClearMutableInlineStyleIfEmpty();
parent_element_->SetNeedsStyleRecalc(
kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kInlineCSSStyleMutated));
+ style_change_reason::kInlineCSSStyleMutated));
parent_element_->InvalidateStyleAttribute();
StyleAttributeMutationScope(this).DidInvalidateStyleAttr();
}
diff --git a/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc b/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc
index 1e115ca278b..c8192681129 100644
--- a/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc
+++ b/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc
@@ -106,7 +106,7 @@ bool InvalidationSet::InvalidatesElement(Element& element) const {
}
}
- if (element.HasPartName() && invalidation_flags_.InvalidatesParts()) {
+ if (element.HasPart() && invalidation_flags_.InvalidatesParts()) {
TRACE_STYLE_INVALIDATOR_INVALIDATION_SELECTORPART_IF_ENABLED(
element, kInvalidationSetMatchedPart, *this, "");
return true;
diff --git a/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations.cc b/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations.cc
index 585ecd48017..224fc759863 100644
--- a/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations.cc
+++ b/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations.cc
@@ -32,7 +32,7 @@ void PendingInvalidations::ScheduleInvalidationSetsForNode(
if (invalidation_set->WholeSubtreeInvalid()) {
node.SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
requires_descendant_invalidation = false;
break;
}
@@ -40,7 +40,7 @@ void PendingInvalidations::ScheduleInvalidationSetsForNode(
if (invalidation_set->InvalidatesSelf()) {
node.SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
}
if (!invalidation_set->IsEmpty())
@@ -94,7 +94,7 @@ void PendingInvalidations::ScheduleSiblingInvalidationsAsDescendants(
if (invalidation_set->WholeSubtreeInvalid()) {
scheduling_parent.SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
return;
}
if (invalidation_set->InvalidatesSelf() &&
@@ -106,7 +106,7 @@ void PendingInvalidations::ScheduleSiblingInvalidationsAsDescendants(
if (descendants->WholeSubtreeInvalid()) {
scheduling_parent.SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
return;
}
if (!pending_invalidations.Descendants().Contains(descendants))
diff --git a/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations_test.cc b/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations_test.cc
index afd1968ad1c..d67db7ccf42 100644
--- a/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/invalidation/pending_invalidations_test.cc
@@ -33,7 +33,8 @@ void PendingInvalidationsTest::SetUp() {
TEST_F(PendingInvalidationsTest, ScheduleOnDocumentNode) {
GetDocument().body()->SetInnerHTMLFromString(
"<div id='d'></div><i id='i'></i><span></span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
unsigned before_count = GetStyleEngine().StyleForElementCount();
@@ -57,7 +58,8 @@ TEST_F(PendingInvalidationsTest, ScheduleOnDocumentNode) {
EXPECT_FALSE(GetDocument().NeedsStyleRecalc());
EXPECT_TRUE(GetDocument().ChildNeedsStyleRecalc());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(2u, after_count - before_count);
}
diff --git a/chromium/third_party/blink/renderer/core/css/invalidation/style_invalidator.cc b/chromium/third_party/blink/renderer/core/css/invalidation/style_invalidator.cc
index 68e6fb95f51..40f2db6256c 100644
--- a/chromium/third_party/blink/renderer/core/css/invalidation/style_invalidator.cc
+++ b/chromium/third_party/blink/renderer/core/css/invalidation/style_invalidator.cc
@@ -169,9 +169,9 @@ bool StyleInvalidator::SiblingData::MatchCurrentInvalidationSets(
if (const DescendantInvalidationSet* descendants =
invalidation_set.SiblingDescendants()) {
if (descendants->WholeSubtreeInvalid()) {
- element.SetNeedsStyleRecalc(kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ element.SetNeedsStyleRecalc(
+ kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
+ style_change_reason::kStyleInvalidator));
return true;
}
@@ -209,7 +209,7 @@ void StyleInvalidator::PushInvalidationSetsForContainerNode(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"StyleInvalidatorInvalidationTracking", TRACE_EVENT_SCOPE_THREAD,
"data",
- InspectorStyleInvalidatorInvalidateEvent::InvalidationList(
+ inspector_style_invalidator_invalidate_event::InvalidationList(
node, pending_invalidations.Descendants()));
}
}
@@ -276,7 +276,7 @@ void StyleInvalidator::Invalidate(Element& element, SiblingData& sibling_data) {
} else if (CheckInvalidationSetsAgainstElement(element, sibling_data)) {
element.SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
}
if (UNLIKELY(element.NeedsStyleInvalidation()))
PushInvalidationSetsForContainerNode(element, sibling_data);
@@ -295,7 +295,7 @@ void StyleInvalidator::Invalidate(Element& element, SiblingData& sibling_data) {
if (InsertionPointCrossing() && element.IsV0InsertionPoint()) {
element.SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
}
}
@@ -320,10 +320,11 @@ void StyleInvalidator::InvalidateSlotDistributedElements(
continue;
if (!distributed_node->IsElementNode())
continue;
- if (MatchesCurrentInvalidationSetsAsSlotted(ToElement(*distributed_node)))
+ if (MatchesCurrentInvalidationSetsAsSlotted(ToElement(*distributed_node))) {
distributed_node->SetNeedsStyleRecalc(
kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleInvalidator));
+ style_change_reason::kStyleInvalidator));
+ }
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/keyframe_style_rule_css_style_declaration.h b/chromium/third_party/blink/renderer/core/css/keyframe_style_rule_css_style_declaration.h
index 40a95e38ff2..7c57d95552c 100644
--- a/chromium/third_party/blink/renderer/core/css/keyframe_style_rule_css_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/keyframe_style_rule_css_style_declaration.h
@@ -17,13 +17,14 @@ class KeyframeStyleRuleCSSStyleDeclaration final
static KeyframeStyleRuleCSSStyleDeclaration* Create(
MutableCSSPropertyValueSet& property_set,
CSSKeyframeRule* parent_rule) {
- return new KeyframeStyleRuleCSSStyleDeclaration(property_set, parent_rule);
+ return MakeGarbageCollected<KeyframeStyleRuleCSSStyleDeclaration>(
+ property_set, parent_rule);
}
- private:
KeyframeStyleRuleCSSStyleDeclaration(MutableCSSPropertyValueSet&,
CSSKeyframeRule*);
+ private:
void DidMutate(MutationType) override;
bool IsKeyframeStyle() const final { return true; }
};
diff --git a/chromium/third_party/blink/renderer/core/css/media_feature_names.json5 b/chromium/third_party/blink/renderer/core/css/media_feature_names.json5
index c36a0f83f81..4640d1a8340 100644
--- a/chromium/third_party/blink/renderer/core/css/media_feature_names.json5
+++ b/chromium/third_party/blink/renderer/core/css/media_feature_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "MediaFeature",
+ namespace: "media_feature_names",
export: "",
},
diff --git a/chromium/third_party/blink/renderer/core/css/media_list.h b/chromium/third_party/blink/renderer/core/css/media_list.h
index 5018623ccb4..4019995841b 100644
--- a/chromium/third_party/blink/renderer/core/css/media_list.h
+++ b/chromium/third_party/blink/renderer/core/css/media_list.h
@@ -74,14 +74,19 @@ class MediaList final : public ScriptWrappable {
public:
static MediaList* Create(scoped_refptr<MediaQuerySet> media_queries,
CSSStyleSheet* parent_sheet) {
- return new MediaList(std::move(media_queries), parent_sheet);
+ return MakeGarbageCollected<MediaList>(std::move(media_queries),
+ parent_sheet);
}
static MediaList* Create(scoped_refptr<MediaQuerySet> media_queries,
CSSRule* parent_rule) {
- return new MediaList(std::move(media_queries), parent_rule);
+ return MakeGarbageCollected<MediaList>(std::move(media_queries),
+ parent_rule);
}
+ MediaList(scoped_refptr<MediaQuerySet>, CSSStyleSheet* parent_sheet);
+ MediaList(scoped_refptr<MediaQuerySet>, CSSRule* parent_rule);
+
unsigned length() const { return media_queries_->QueryVector().size(); }
String item(unsigned index) const;
void deleteMedium(const String& old_medium, ExceptionState&);
@@ -101,9 +106,6 @@ class MediaList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- MediaList(scoped_refptr<MediaQuerySet>, CSSStyleSheet* parent_sheet);
- MediaList(scoped_refptr<MediaQuerySet>, CSSRule* parent_rule);
-
scoped_refptr<MediaQuerySet> media_queries_;
Member<CSSStyleSheet> parent_style_sheet_;
Member<CSSRule> parent_rule_;
diff --git a/chromium/third_party/blink/renderer/core/css/media_query.cc b/chromium/third_party/blink/renderer/core/css/media_query.cc
index 2a002db3ef1..2748773e071 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query.cc
@@ -56,7 +56,7 @@ String MediaQuery::Serialize() const {
return result.ToString();
}
- if (media_type_ != MediaTypeNames::all || restrictor_ != kNone) {
+ if (media_type_ != media_type_names::kAll || restrictor_ != kNone) {
result.Append(media_type_);
result.Append(" and ");
}
@@ -74,7 +74,7 @@ static bool ExpressionCompare(const MediaQueryExp& a, const MediaQueryExp& b) {
}
std::unique_ptr<MediaQuery> MediaQuery::CreateNotAll() {
- return std::make_unique<MediaQuery>(MediaQuery::kNot, MediaTypeNames::all,
+ return std::make_unique<MediaQuery>(MediaQuery::kNot, media_type_names::kAll,
ExpressionHeapVector());
}
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_evaluator.cc b/chromium/third_party/blink/renderer/core/css/media_query_evaluator.cc
index 5c6aa02a23b..e0e5ca28faa 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_evaluator.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_evaluator.cc
@@ -55,7 +55,7 @@
namespace blink {
-using namespace MediaFeatureNames;
+using namespace media_feature_names;
enum MediaFeaturePrefix { kMinPrefix, kMaxPrefix, kNoPrefix };
@@ -100,7 +100,7 @@ bool MediaQueryEvaluator::MediaTypeMatch(
const String& media_type_to_match) const {
return media_type_to_match.IsEmpty() ||
DeprecatedEqualIgnoringCase(media_type_to_match,
- MediaTypeNames::all) ||
+ media_type_names::kAll) ||
DeprecatedEqualIgnoringCase(media_type_to_match, MediaType());
}
@@ -322,10 +322,10 @@ static bool EvalResolution(const MediaQueryExpValue& value,
// in the query. Thus, if if the document's media type is "print", the
// media type of the query will either be "print" or "all".
if (DeprecatedEqualIgnoringCase(media_values.MediaType(),
- MediaTypeNames::screen)) {
+ media_type_names::kScreen)) {
actual_resolution = clampTo<float>(media_values.DevicePixelRatio());
} else if (DeprecatedEqualIgnoringCase(media_values.MediaType(),
- MediaTypeNames::print)) {
+ media_type_names::kPrint)) {
// The resolution of images while printing should not depend on the DPI
// of the screen. Until we support proper ways of querying this info
// we use 300px which is considered minimum for current printers.
@@ -752,7 +752,7 @@ static bool ScanMediaFeatureEval(const MediaQueryExpValue& value,
const MediaValues& media_values) {
// Scan only applies to 'tv' media.
if (!DeprecatedEqualIgnoringCase(media_values.MediaType(),
- MediaTypeNames::tv))
+ media_type_names::kTv))
return false;
if (!value.IsValid())
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_evaluator_test.cc b/chromium/third_party/blink/renderer/core/css/media_query_evaluator_test.cc
index b8eecf98174..e2de522ff15 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_evaluator_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_evaluator_test.cc
@@ -209,7 +209,7 @@ TEST(MediaQueryEvaluatorTest, Cached) {
data.primary_hover_type = kHoverTypeHover;
data.default_font_size = 16;
data.three_d_enabled = true;
- data.media_type = MediaTypeNames::screen;
+ data.media_type = media_type_names::kScreen;
data.strict_mode = true;
data.display_mode = kWebDisplayModeBrowser;
data.display_shape = kDisplayShapeRect;
@@ -228,11 +228,11 @@ TEST(MediaQueryEvaluatorTest, Cached) {
// Print values.
{
- data.media_type = MediaTypeNames::print;
+ data.media_type = media_type_names::kPrint;
MediaValues* media_values = MediaValuesCached::Create(data);
MediaQueryEvaluator media_query_evaluator(*media_values);
TestMQEvaluator(g_print_test_cases, media_query_evaluator);
- data.media_type = MediaTypeNames::screen;
+ data.media_type = media_type_names::kScreen;
}
// Monochrome values.
@@ -261,11 +261,11 @@ TEST(MediaQueryEvaluatorTest, Cached) {
TEST(MediaQueryEvaluatorTest, Dynamic) {
std::unique_ptr<DummyPageHolder> page_holder =
DummyPageHolder::Create(IntSize(500, 500));
- page_holder->GetFrameView().SetMediaType(MediaTypeNames::screen);
+ page_holder->GetFrameView().SetMediaType(media_type_names::kScreen);
MediaQueryEvaluator media_query_evaluator(&page_holder->GetFrame());
TestMQEvaluator(g_viewport_test_cases, media_query_evaluator);
- page_holder->GetFrameView().SetMediaType(MediaTypeNames::print);
+ page_holder->GetFrameView().SetMediaType(media_type_names::kPrint);
TestMQEvaluator(g_print_test_cases, media_query_evaluator);
}
@@ -304,7 +304,7 @@ TEST(MediaQueryEvaluatorTest, CachedFloatViewportNonFloatFriendly) {
TEST(MediaQueryEvaluatorTest, InitialViewport) {
std::unique_ptr<DummyPageHolder> page_holder =
DummyPageHolder::Create(IntSize(500, 500));
- page_holder->GetFrameView().SetMediaType(MediaTypeNames::screen);
+ page_holder->GetFrameView().SetMediaType(media_type_names::kScreen);
page_holder->GetFrameView().SetLayoutSizeFixedToFrameSize(false);
page_holder->GetFrameView().SetInitialViewportSize(IntSize(500, 500));
page_holder->GetFrameView().SetLayoutSize(IntSize(800, 800));
@@ -318,7 +318,7 @@ TEST(MediaQueryEvaluatorTest, InitialViewport) {
TEST(MediaQueryEvaluatorTest, DynamicImmersive) {
std::unique_ptr<DummyPageHolder> page_holder =
DummyPageHolder::Create(IntSize(500, 500));
- page_holder->GetFrameView().SetMediaType(MediaTypeNames::screen);
+ page_holder->GetFrameView().SetMediaType(media_type_names::kScreen);
MediaQueryEvaluator media_query_evaluator(&page_holder->GetFrame());
page_holder->GetDocument().GetSettings()->SetImmersiveModeEnabled(false);
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_exp.cc b/chromium/third_party/blink/renderer/core/css/media_query_exp.cc
index b61a883d3cc..8719608cb98 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_exp.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_exp.cc
@@ -39,35 +39,35 @@
namespace blink {
-using namespace MediaFeatureNames;
+using namespace media_feature_names;
static inline bool FeatureWithValidIdent(const String& media_feature,
CSSValueID ident) {
- if (media_feature == displayModeMediaFeature)
+ if (media_feature == kDisplayModeMediaFeature)
return ident == CSSValueFullscreen || ident == CSSValueStandalone ||
ident == CSSValueMinimalUi || ident == CSSValueBrowser;
- if (media_feature == orientationMediaFeature)
+ if (media_feature == kOrientationMediaFeature)
return ident == CSSValuePortrait || ident == CSSValueLandscape;
- if (media_feature == pointerMediaFeature ||
- media_feature == anyPointerMediaFeature)
+ if (media_feature == kPointerMediaFeature ||
+ media_feature == kAnyPointerMediaFeature)
return ident == CSSValueNone || ident == CSSValueCoarse ||
ident == CSSValueFine;
- if (media_feature == hoverMediaFeature ||
- media_feature == anyHoverMediaFeature)
+ if (media_feature == kHoverMediaFeature ||
+ media_feature == kAnyHoverMediaFeature)
return ident == CSSValueNone || ident == CSSValueHover;
- if (media_feature == scanMediaFeature)
+ if (media_feature == kScanMediaFeature)
return ident == CSSValueInterlace || ident == CSSValueProgressive;
if (RuntimeEnabledFeatures::MediaQueryShapeEnabled()) {
- if (media_feature == shapeMediaFeature)
+ if (media_feature == kShapeMediaFeature)
return ident == CSSValueRect || ident == CSSValueRound;
}
- if (media_feature == colorGamutMediaFeature) {
+ if (media_feature == kColorGamutMediaFeature) {
return ident == CSSValueSRGB || ident == CSSValueP3 ||
ident == CSSValueRec2020;
}
@@ -82,18 +82,18 @@ static inline bool FeatureWithValidPositiveLength(
(value->IsNumber() && value->GetDoubleValue() == 0)))
return false;
- return media_feature == heightMediaFeature ||
- media_feature == maxHeightMediaFeature ||
- media_feature == minHeightMediaFeature ||
- media_feature == widthMediaFeature ||
- media_feature == maxWidthMediaFeature ||
- media_feature == minWidthMediaFeature ||
- media_feature == deviceHeightMediaFeature ||
- media_feature == maxDeviceHeightMediaFeature ||
- media_feature == minDeviceHeightMediaFeature ||
- media_feature == deviceWidthMediaFeature ||
- media_feature == minDeviceWidthMediaFeature ||
- media_feature == maxDeviceWidthMediaFeature;
+ return media_feature == kHeightMediaFeature ||
+ media_feature == kMaxHeightMediaFeature ||
+ media_feature == kMinHeightMediaFeature ||
+ media_feature == kWidthMediaFeature ||
+ media_feature == kMaxWidthMediaFeature ||
+ media_feature == kMinWidthMediaFeature ||
+ media_feature == kDeviceHeightMediaFeature ||
+ media_feature == kMaxDeviceHeightMediaFeature ||
+ media_feature == kMinDeviceHeightMediaFeature ||
+ media_feature == kDeviceWidthMediaFeature ||
+ media_feature == kMinDeviceWidthMediaFeature ||
+ media_feature == kMaxDeviceWidthMediaFeature;
}
static inline bool FeatureWithValidDensity(const String& media_feature,
@@ -107,23 +107,23 @@ static inline bool FeatureWithValidDensity(const String& media_feature,
value->GetDoubleValue() <= 0)
return false;
- return media_feature == resolutionMediaFeature ||
- media_feature == minResolutionMediaFeature ||
- media_feature == maxResolutionMediaFeature;
+ return media_feature == kResolutionMediaFeature ||
+ media_feature == kMinResolutionMediaFeature ||
+ media_feature == kMaxResolutionMediaFeature;
}
static inline bool FeatureExpectingPositiveInteger(
const String& media_feature) {
- return media_feature == colorMediaFeature ||
- media_feature == maxColorMediaFeature ||
- media_feature == minColorMediaFeature ||
- media_feature == colorIndexMediaFeature ||
- media_feature == maxColorIndexMediaFeature ||
- media_feature == minColorIndexMediaFeature ||
- media_feature == monochromeMediaFeature ||
- media_feature == maxMonochromeMediaFeature ||
- media_feature == minMonochromeMediaFeature ||
- media_feature == immersiveMediaFeature;
+ return media_feature == kColorMediaFeature ||
+ media_feature == kMaxColorMediaFeature ||
+ media_feature == kMinColorMediaFeature ||
+ media_feature == kColorIndexMediaFeature ||
+ media_feature == kMaxColorIndexMediaFeature ||
+ media_feature == kMinColorIndexMediaFeature ||
+ media_feature == kMonochromeMediaFeature ||
+ media_feature == kMaxMonochromeMediaFeature ||
+ media_feature == kMinMonochromeMediaFeature ||
+ media_feature == kImmersiveMediaFeature;
}
static inline bool FeatureWithPositiveInteger(const String& media_feature,
@@ -138,10 +138,10 @@ static inline bool FeatureWithPositiveNumber(const String& media_feature,
if (!value->IsNumber())
return false;
- return media_feature == transform3dMediaFeature ||
- media_feature == devicePixelRatioMediaFeature ||
- media_feature == maxDevicePixelRatioMediaFeature ||
- media_feature == minDevicePixelRatioMediaFeature;
+ return media_feature == kTransform3dMediaFeature ||
+ media_feature == kDevicePixelRatioMediaFeature ||
+ media_feature == kMaxDevicePixelRatioMediaFeature ||
+ media_feature == kMinDevicePixelRatioMediaFeature;
}
static inline bool FeatureWithZeroOrOne(const String& media_feature,
@@ -150,73 +150,73 @@ static inline bool FeatureWithZeroOrOne(const String& media_feature,
!(value->GetDoubleValue() == 1 || !value->GetDoubleValue()))
return false;
- return media_feature == gridMediaFeature;
+ return media_feature == kGridMediaFeature;
}
static inline bool FeatureWithAspectRatio(const String& media_feature) {
- return media_feature == aspectRatioMediaFeature ||
- media_feature == deviceAspectRatioMediaFeature ||
- media_feature == minAspectRatioMediaFeature ||
- media_feature == maxAspectRatioMediaFeature ||
- media_feature == minDeviceAspectRatioMediaFeature ||
- media_feature == maxDeviceAspectRatioMediaFeature;
+ return media_feature == kAspectRatioMediaFeature ||
+ media_feature == kDeviceAspectRatioMediaFeature ||
+ media_feature == kMinAspectRatioMediaFeature ||
+ media_feature == kMaxAspectRatioMediaFeature ||
+ media_feature == kMinDeviceAspectRatioMediaFeature ||
+ media_feature == kMaxDeviceAspectRatioMediaFeature;
}
static inline bool FeatureWithoutValue(const String& media_feature) {
// Media features that are prefixed by min/max cannot be used without a value.
- return media_feature == monochromeMediaFeature ||
- media_feature == colorMediaFeature ||
- media_feature == colorIndexMediaFeature ||
- media_feature == gridMediaFeature ||
- media_feature == heightMediaFeature ||
- media_feature == widthMediaFeature ||
- media_feature == deviceHeightMediaFeature ||
- media_feature == deviceWidthMediaFeature ||
- media_feature == orientationMediaFeature ||
- media_feature == aspectRatioMediaFeature ||
- media_feature == deviceAspectRatioMediaFeature ||
- media_feature == hoverMediaFeature ||
- media_feature == anyHoverMediaFeature ||
- media_feature == transform3dMediaFeature ||
- media_feature == pointerMediaFeature ||
- media_feature == anyPointerMediaFeature ||
- media_feature == devicePixelRatioMediaFeature ||
- media_feature == resolutionMediaFeature ||
- media_feature == displayModeMediaFeature ||
- media_feature == scanMediaFeature ||
- media_feature == shapeMediaFeature ||
- media_feature == colorGamutMediaFeature ||
- media_feature == immersiveMediaFeature;
+ return media_feature == kMonochromeMediaFeature ||
+ media_feature == kColorMediaFeature ||
+ media_feature == kColorIndexMediaFeature ||
+ media_feature == kGridMediaFeature ||
+ media_feature == kHeightMediaFeature ||
+ media_feature == kWidthMediaFeature ||
+ media_feature == kDeviceHeightMediaFeature ||
+ media_feature == kDeviceWidthMediaFeature ||
+ media_feature == kOrientationMediaFeature ||
+ media_feature == kAspectRatioMediaFeature ||
+ media_feature == kDeviceAspectRatioMediaFeature ||
+ media_feature == kHoverMediaFeature ||
+ media_feature == kAnyHoverMediaFeature ||
+ media_feature == kTransform3dMediaFeature ||
+ media_feature == kPointerMediaFeature ||
+ media_feature == kAnyPointerMediaFeature ||
+ media_feature == kDevicePixelRatioMediaFeature ||
+ media_feature == kResolutionMediaFeature ||
+ media_feature == kDisplayModeMediaFeature ||
+ media_feature == kScanMediaFeature ||
+ media_feature == kShapeMediaFeature ||
+ media_feature == kColorGamutMediaFeature ||
+ media_feature == kImmersiveMediaFeature;
}
bool MediaQueryExp::IsViewportDependent() const {
- return media_feature_ == widthMediaFeature ||
- media_feature_ == heightMediaFeature ||
- media_feature_ == minWidthMediaFeature ||
- media_feature_ == minHeightMediaFeature ||
- media_feature_ == maxWidthMediaFeature ||
- media_feature_ == maxHeightMediaFeature ||
- media_feature_ == orientationMediaFeature ||
- media_feature_ == aspectRatioMediaFeature ||
- media_feature_ == minAspectRatioMediaFeature ||
- media_feature_ == devicePixelRatioMediaFeature ||
- media_feature_ == resolutionMediaFeature ||
- media_feature_ == maxAspectRatioMediaFeature ||
- media_feature_ == maxDevicePixelRatioMediaFeature ||
- media_feature_ == minDevicePixelRatioMediaFeature;
+ return media_feature_ == kWidthMediaFeature ||
+ media_feature_ == kHeightMediaFeature ||
+ media_feature_ == kMinWidthMediaFeature ||
+ media_feature_ == kMinHeightMediaFeature ||
+ media_feature_ == kMaxWidthMediaFeature ||
+ media_feature_ == kMaxHeightMediaFeature ||
+ media_feature_ == kOrientationMediaFeature ||
+ media_feature_ == kAspectRatioMediaFeature ||
+ media_feature_ == kMinAspectRatioMediaFeature ||
+ media_feature_ == kDevicePixelRatioMediaFeature ||
+ media_feature_ == kResolutionMediaFeature ||
+ media_feature_ == kMaxAspectRatioMediaFeature ||
+ media_feature_ == kMaxDevicePixelRatioMediaFeature ||
+ media_feature_ == kMinDevicePixelRatioMediaFeature;
}
bool MediaQueryExp::IsDeviceDependent() const {
- return media_feature_ == deviceAspectRatioMediaFeature ||
- media_feature_ == deviceWidthMediaFeature ||
- media_feature_ == deviceHeightMediaFeature ||
- media_feature_ == minDeviceAspectRatioMediaFeature ||
- media_feature_ == minDeviceWidthMediaFeature ||
- media_feature_ == minDeviceHeightMediaFeature ||
- media_feature_ == maxDeviceAspectRatioMediaFeature ||
- media_feature_ == maxDeviceWidthMediaFeature ||
- media_feature_ == maxDeviceHeightMediaFeature ||
- media_feature_ == shapeMediaFeature;
+ return media_feature_ == kDeviceAspectRatioMediaFeature ||
+ media_feature_ == kDeviceWidthMediaFeature ||
+ media_feature_ == kDeviceHeightMediaFeature ||
+ media_feature_ == kMinDeviceAspectRatioMediaFeature ||
+ media_feature_ == kMinDeviceWidthMediaFeature ||
+ media_feature_ == kMinDeviceHeightMediaFeature ||
+ media_feature_ == kMaxDeviceAspectRatioMediaFeature ||
+ media_feature_ == kMaxDeviceWidthMediaFeature ||
+ media_feature_ == kMaxDeviceHeightMediaFeature ||
+ media_feature_ == kShapeMediaFeature;
}
MediaQueryExp::MediaQueryExp(const MediaQueryExp& other)
@@ -234,16 +234,19 @@ MediaQueryExp MediaQueryExp::Create(const String& media_feature,
String lower_media_feature =
AttemptStaticStringCreation(media_feature.LowerASCII());
- CSSPrimitiveValue* value = CSSPropertyParserHelpers::ConsumeInteger(range, 0);
+ CSSPrimitiveValue* value =
+ css_property_parser_helpers::ConsumeInteger(range, 0);
if (!value && !FeatureExpectingPositiveInteger(lower_media_feature) &&
- !FeatureWithAspectRatio(lower_media_feature))
- value =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
- if (!value)
- value = CSSPropertyParserHelpers::ConsumeLength(range, kHTMLStandardMode,
- kValueRangeNonNegative);
+ !FeatureWithAspectRatio(lower_media_feature)) {
+ value = css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
+ }
+ if (!value) {
+ value = css_property_parser_helpers::ConsumeLength(range, kHTMLStandardMode,
+ kValueRangeNonNegative);
+ }
if (!value)
- value = CSSPropertyParserHelpers::ConsumeResolution(range);
+ value = css_property_parser_helpers::ConsumeResolution(range);
// Create value for media query expression that must have 1 or more values.
if (value) {
if (FeatureWithAspectRatio(lower_media_feature)) {
@@ -251,10 +254,10 @@ MediaQueryExp MediaQueryExp::Create(const String& media_feature,
CSSPrimitiveValue::UnitType::kInteger ||
value->GetDoubleValue() == 0)
return Invalid();
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
return Invalid();
CSSPrimitiveValue* denominator =
- CSSPropertyParserHelpers::ConsumePositiveInteger(range);
+ css_property_parser_helpers::ConsumePositiveInteger(range);
if (!denominator)
return Invalid();
@@ -275,7 +278,8 @@ MediaQueryExp MediaQueryExp::Create(const String& media_feature,
} else {
return Invalid();
}
- } else if (CSSIdentifierValue* ident = CSSPropertyParserHelpers::ConsumeIdent(range)) {
+ } else if (CSSIdentifierValue* ident =
+ css_property_parser_helpers::ConsumeIdent(range)) {
CSSValueID ident_id = ident->GetValueID();
if (!FeatureWithValidIdent(lower_media_feature, ident_id))
return Invalid();
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_list.cc b/chromium/third_party/blink/renderer/core/css/media_query_list.cc
index f8efddac98c..51ebc837cb4 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_list.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_list.cc
@@ -30,8 +30,8 @@ namespace blink {
MediaQueryList* MediaQueryList::Create(ExecutionContext* context,
MediaQueryMatcher* matcher,
scoped_refptr<MediaQuerySet> media) {
- return new MediaQueryList(context, matcher,
- scoped_refptr<MediaQuerySet>(media));
+ return MakeGarbageCollected<MediaQueryList>(
+ context, matcher, scoped_refptr<MediaQuerySet>(media));
}
MediaQueryList::MediaQueryList(ExecutionContext* context,
@@ -56,14 +56,14 @@ void MediaQueryList::addDeprecatedListener(EventListener* listener) {
if (!listener)
return;
- addEventListener(EventTypeNames::change, listener, false);
+ addEventListener(event_type_names::kChange, listener, false);
}
void MediaQueryList::removeDeprecatedListener(EventListener* listener) {
if (!listener)
return;
- removeEventListener(EventTypeNames::change, listener, false);
+ removeEventListener(event_type_names::kChange, listener, false);
}
void MediaQueryList::AddListener(MediaQueryListListener* listener) {
@@ -82,7 +82,7 @@ void MediaQueryList::RemoveListener(MediaQueryListListener* listener) {
bool MediaQueryList::HasPendingActivity() const {
return GetExecutionContext() &&
- (listeners_.size() || HasEventListeners(EventTypeNames::change));
+ (listeners_.size() || HasEventListeners(event_type_names::kChange));
}
void MediaQueryList::ContextDestroyed(ExecutionContext*) {
@@ -98,7 +98,7 @@ bool MediaQueryList::MediaFeaturesChanged(
for (const auto& listener : listeners_) {
listeners_to_notify->push_back(listener);
}
- return HasEventListeners(EventTypeNames::change);
+ return HasEventListeners(event_type_names::kChange);
}
bool MediaQueryList::UpdateMatches() {
@@ -123,7 +123,7 @@ void MediaQueryList::Trace(blink::Visitor* visitor) {
}
const AtomicString& MediaQueryList::InterfaceName() const {
- return EventTargetNames::MediaQueryList;
+ return event_target_names::kMediaQueryList;
}
ExecutionContext* MediaQueryList::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_list.h b/chromium/third_party/blink/renderer/core/css/media_query_list.h
index 615b8e9cdd5..4ca8fd6b741 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_list.h
+++ b/chromium/third_party/blink/renderer/core/css/media_query_list.h
@@ -53,12 +53,16 @@ class CORE_EXPORT MediaQueryList final
static MediaQueryList* Create(ExecutionContext*,
MediaQueryMatcher*,
scoped_refptr<MediaQuerySet>);
+
+ MediaQueryList(ExecutionContext*,
+ MediaQueryMatcher*,
+ scoped_refptr<MediaQuerySet>);
~MediaQueryList() override;
String media() const;
bool matches();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
// These two functions are provided for compatibility with JS code
// written before the change listener became a DOM event.
@@ -86,10 +90,6 @@ class CORE_EXPORT MediaQueryList final
ExecutionContext* GetExecutionContext() const override;
private:
- MediaQueryList(ExecutionContext*,
- MediaQueryMatcher*,
- scoped_refptr<MediaQuerySet>);
-
bool UpdateMatches();
Member<MediaQueryMatcher> matcher_;
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_list_event.h b/chromium/third_party/blink/renderer/core/css/media_query_list_event.h
index 7307703fd7e..c150a53a640 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_list_event.h
+++ b/chromium/third_party/blink/renderer/core/css/media_query_list_event.h
@@ -8,6 +8,7 @@
#include "third_party/blink/renderer/core/css/media_query_list.h"
#include "third_party/blink/renderer/core/css/media_query_list_event_init.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -16,17 +17,36 @@ class MediaQueryListEvent final : public Event {
public:
static MediaQueryListEvent* Create(MediaQueryList* list) {
- return new MediaQueryListEvent(list);
+ return MakeGarbageCollected<MediaQueryListEvent>(list);
}
static MediaQueryListEvent* Create(const String& media, bool matches) {
- return new MediaQueryListEvent(media, matches);
+ return MakeGarbageCollected<MediaQueryListEvent>(media, matches);
}
static MediaQueryListEvent* Create(
const AtomicString& event_type,
- const MediaQueryListEventInit& initializer) {
- return new MediaQueryListEvent(event_type, initializer);
+ const MediaQueryListEventInit* initializer) {
+ return MakeGarbageCollected<MediaQueryListEvent>(event_type, initializer);
+ }
+
+ MediaQueryListEvent(const String& media, bool matches)
+ : Event(event_type_names::kChange, Bubbles::kNo, Cancelable::kNo),
+ media_(media),
+ matches_(matches) {}
+
+ explicit MediaQueryListEvent(MediaQueryList* list)
+ : Event(event_type_names::kChange, Bubbles::kNo, Cancelable::kNo),
+ media_query_list_(list),
+ matches_(false) {}
+
+ MediaQueryListEvent(const AtomicString& event_type,
+ const MediaQueryListEventInit* initializer)
+ : Event(event_type, initializer), matches_(false) {
+ if (initializer->hasMedia())
+ media_ = initializer->media();
+ if (initializer->hasMatches())
+ matches_ = initializer->matches();
}
String media() const {
@@ -37,7 +57,7 @@ class MediaQueryListEvent final : public Event {
}
const AtomicString& InterfaceName() const override {
- return EventNames::MediaQueryListEvent;
+ return event_interface_names::kMediaQueryListEvent;
}
void Trace(blink::Visitor* visitor) override {
@@ -46,25 +66,6 @@ class MediaQueryListEvent final : public Event {
}
private:
- MediaQueryListEvent(const String& media, bool matches)
- : Event(EventTypeNames::change, Bubbles::kNo, Cancelable::kNo),
- media_(media),
- matches_(matches) {}
-
- explicit MediaQueryListEvent(MediaQueryList* list)
- : Event(EventTypeNames::change, Bubbles::kNo, Cancelable::kNo),
- media_query_list_(list),
- matches_(false) {}
-
- MediaQueryListEvent(const AtomicString& event_type,
- const MediaQueryListEventInit& initializer)
- : Event(event_type, initializer), matches_(false) {
- if (initializer.hasMedia())
- media_ = initializer.media();
- if (initializer.hasMatches())
- matches_ = initializer.matches();
- }
-
// We have media_/matches_ for JS-created events; we use media_query_list_
// for events that blink generates.
Member<MediaQueryList> media_query_list_;
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_matcher.cc b/chromium/third_party/blink/renderer/core/css/media_query_matcher.cc
index 6465d6afa34..d478c870953 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_matcher.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_matcher.cc
@@ -33,7 +33,7 @@
namespace blink {
MediaQueryMatcher* MediaQueryMatcher::Create(Document& document) {
- return new MediaQueryMatcher(document);
+ return MakeGarbageCollected<MediaQueryMatcher>(document);
}
MediaQueryMatcher::MediaQueryMatcher(Document& document)
@@ -52,7 +52,7 @@ MediaQueryEvaluator* MediaQueryMatcher::CreateEvaluator() const {
if (!document_ || !document_->GetFrame())
return nullptr;
- return new MediaQueryEvaluator(document_->GetFrame());
+ return MakeGarbageCollected<MediaQueryEvaluator>(document_->GetFrame());
}
bool MediaQueryMatcher::Evaluate(const MediaQuerySet* media) {
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_matcher.h b/chromium/third_party/blink/renderer/core/css/media_query_matcher.h
index 4b02434e602..6a2b90ff3ca 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_matcher.h
+++ b/chromium/third_party/blink/renderer/core/css/media_query_matcher.h
@@ -44,6 +44,8 @@ class CORE_EXPORT MediaQueryMatcher final
public:
static MediaQueryMatcher* Create(Document&);
+
+ explicit MediaQueryMatcher(Document&);
~MediaQueryMatcher();
void DocumentDetached();
@@ -63,8 +65,6 @@ class CORE_EXPORT MediaQueryMatcher final
void Trace(blink::Visitor*);
private:
- explicit MediaQueryMatcher(Document&);
-
MediaQueryEvaluator* CreateEvaluator() const;
Member<Document> document_;
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_matcher_test.cc b/chromium/third_party/blink/renderer/core/css/media_query_matcher_test.cc
index 8505778fcc3..5c9b1d8615a 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_matcher_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_matcher_test.cc
@@ -18,7 +18,7 @@ TEST(MediaQueryMatcherTest, LostFrame) {
MediaQueryMatcher* matcher =
MediaQueryMatcher::Create(page_holder->GetDocument());
scoped_refptr<MediaQuerySet> query_set =
- MediaQuerySet::Create(MediaTypeNames::all);
+ MediaQuerySet::Create(media_type_names::kAll);
ASSERT_TRUE(matcher->Evaluate(query_set.get()));
matcher->DocumentDetached();
diff --git a/chromium/third_party/blink/renderer/core/css/media_type_names.json5 b/chromium/third_party/blink/renderer/core/css/media_type_names.json5
index 8e638e10bb5..64cee27c01a 100644
--- a/chromium/third_party/blink/renderer/core/css/media_type_names.json5
+++ b/chromium/third_party/blink/renderer/core/css/media_type_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "MediaType",
+ namespace: "media_type_names",
export: "CORE_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/core/css/media_values_cached.cc b/chromium/third_party/blink/renderer/core/css/media_values_cached.cc
index 57bf67ec453..5d8f675d030 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values_cached.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_values_cached.cc
@@ -73,12 +73,12 @@ MediaValuesCached::MediaValuesCachedData::MediaValuesCachedData(
}
MediaValuesCached* MediaValuesCached::Create() {
- return new MediaValuesCached();
+ return MakeGarbageCollected<MediaValuesCached>();
}
MediaValuesCached* MediaValuesCached::Create(
const MediaValuesCachedData& data) {
- return new MediaValuesCached(data);
+ return MakeGarbageCollected<MediaValuesCached>(data);
}
MediaValuesCached::MediaValuesCached() = default;
@@ -87,7 +87,7 @@ MediaValuesCached::MediaValuesCached(const MediaValuesCachedData& data)
: data_(data) {}
MediaValues* MediaValuesCached::Copy() const {
- return new MediaValuesCached(data_);
+ return MakeGarbageCollected<MediaValuesCached>(data_);
}
bool MediaValuesCached::ComputeLength(double value,
diff --git a/chromium/third_party/blink/renderer/core/css/media_values_cached.h b/chromium/third_party/blink/renderer/core/css/media_values_cached.h
index 0a5c22a2740..dfa427f7c38 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values_cached.h
+++ b/chromium/third_party/blink/renderer/core/css/media_values_cached.h
@@ -67,6 +67,11 @@ class CORE_EXPORT MediaValuesCached final : public MediaValues {
static MediaValuesCached* Create();
static MediaValuesCached* Create(const MediaValuesCachedData&);
+
+ MediaValuesCached();
+ MediaValuesCached(LocalFrame*);
+ MediaValuesCached(const MediaValuesCachedData&);
+
MediaValues* Copy() const override;
bool ComputeLength(double value,
CSSPrimitiveValue::UnitType,
@@ -99,10 +104,6 @@ class CORE_EXPORT MediaValuesCached final : public MediaValues {
void OverrideViewportDimensions(double width, double height) override;
protected:
- MediaValuesCached();
- MediaValuesCached(LocalFrame*);
- MediaValuesCached(const MediaValuesCachedData&);
-
MediaValuesCachedData data_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/media_values_dynamic.cc b/chromium/third_party/blink/renderer/core/css/media_values_dynamic.cc
index ee785dd3980..6d8ad635a0c 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values_dynamic.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_values_dynamic.cc
@@ -21,7 +21,7 @@ MediaValues* MediaValuesDynamic::Create(LocalFrame* frame) {
if (!frame || !frame->View() || !frame->GetDocument() ||
!frame->GetDocument()->GetLayoutView())
return MediaValuesCached::Create();
- return new MediaValuesDynamic(frame);
+ return MakeGarbageCollected<MediaValuesDynamic>(frame);
}
MediaValuesDynamic::MediaValuesDynamic(LocalFrame* frame)
@@ -44,9 +44,9 @@ MediaValuesDynamic::MediaValuesDynamic(LocalFrame* frame,
}
MediaValues* MediaValuesDynamic::Copy() const {
- return new MediaValuesDynamic(frame_, viewport_dimensions_overridden_,
- viewport_width_override_,
- viewport_height_override_);
+ return MakeGarbageCollected<MediaValuesDynamic>(
+ frame_, viewport_dimensions_overridden_, viewport_width_override_,
+ viewport_height_override_);
}
bool MediaValuesDynamic::ComputeLength(double value,
diff --git a/chromium/third_party/blink/renderer/core/css/media_values_dynamic.h b/chromium/third_party/blink/renderer/core/css/media_values_dynamic.h
index d4c346fd082..0d522475059 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values_dynamic.h
+++ b/chromium/third_party/blink/renderer/core/css/media_values_dynamic.h
@@ -15,6 +15,13 @@ class CORE_EXPORT MediaValuesDynamic : public MediaValues {
public:
static MediaValues* Create(Document&);
static MediaValues* Create(LocalFrame*);
+
+ MediaValuesDynamic(LocalFrame*);
+ MediaValuesDynamic(LocalFrame*,
+ bool overridden_viewport_dimensions,
+ double viewport_width,
+ double viewport_height);
+
MediaValues* Copy() const override;
bool ComputeLength(double value,
CSSPrimitiveValue::UnitType,
@@ -48,12 +55,6 @@ class CORE_EXPORT MediaValuesDynamic : public MediaValues {
void Trace(blink::Visitor*) override;
protected:
- MediaValuesDynamic(LocalFrame*);
- MediaValuesDynamic(LocalFrame*,
- bool overridden_viewport_dimensions,
- double viewport_width,
- double viewport_height);
-
Member<LocalFrame> frame_;
bool viewport_dimensions_overridden_;
double viewport_width_override_;
diff --git a/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.cc b/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.cc
index 8333e597584..876b2531e93 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.cc
@@ -12,7 +12,7 @@ namespace blink {
MediaValuesInitialViewport* MediaValuesInitialViewport::Create(
LocalFrame& frame) {
- return new MediaValuesInitialViewport(frame);
+ return MakeGarbageCollected<MediaValuesInitialViewport>(frame);
}
MediaValuesInitialViewport::MediaValuesInitialViewport(LocalFrame& frame)
diff --git a/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.h b/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.h
index 741c4d6b7b4..2956252dfe9 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.h
+++ b/chromium/third_party/blink/renderer/core/css/media_values_initial_viewport.h
@@ -13,11 +13,10 @@ class CORE_EXPORT MediaValuesInitialViewport final : public MediaValuesDynamic {
public:
static MediaValuesInitialViewport* Create(LocalFrame&);
+ MediaValuesInitialViewport(LocalFrame&);
+
double ViewportWidth() const override;
double ViewportHeight() const override;
-
- private:
- MediaValuesInitialViewport(LocalFrame&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.h b/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.h
index 88fd83136bc..79c2a1d077f 100644
--- a/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.h
+++ b/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.h
@@ -22,8 +22,10 @@ class FontDescription;
class CORE_EXPORT OffscreenFontSelector : public FontSelector {
public:
static OffscreenFontSelector* Create(ExecutionContext* context) {
- return new OffscreenFontSelector(context);
+ return MakeGarbageCollected<OffscreenFontSelector>(context);
}
+
+ explicit OffscreenFontSelector(ExecutionContext*);
~OffscreenFontSelector() override;
unsigned Version() const override { return 1; }
@@ -64,8 +66,6 @@ class CORE_EXPORT OffscreenFontSelector : public FontSelector {
void Trace(blink::Visitor*) override;
protected:
- explicit OffscreenFontSelector(ExecutionContext*);
-
void DispatchInvalidationCallbacks();
private:
diff --git a/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.cc
index f67b97c821d..d64c6986e16 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.cc
@@ -28,13 +28,13 @@ CSSValue* ConsumeFontVariantList(CSSParserTokenRange& range) {
// 'all' is only allowed in @font-face and with no other values.
if (values->length())
return nullptr;
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
}
CSSIdentifierValue* font_variant =
- CSSParsingUtils::ConsumeFontVariantCSS21(range);
+ css_parsing_utils::ConsumeFontVariantCSS21(range);
if (font_variant)
values->Append(*font_variant);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
if (values->length())
return values;
@@ -43,9 +43,9 @@ CSSValue* ConsumeFontVariantList(CSSParserTokenRange& range) {
}
CSSIdentifierValue* ConsumeFontDisplay(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueAuto, CSSValueBlock,
- CSSValueSwap, CSSValueFallback,
- CSSValueOptional>(range);
+ return css_property_parser_helpers::ConsumeIdent<
+ CSSValueAuto, CSSValueBlock, CSSValueSwap, CSSValueFallback,
+ CSSValueOptional>(range);
}
CSSValueList* ConsumeFontFaceUnicodeRange(CSSParserTokenRange& range) {
@@ -61,7 +61,7 @@ CSSValueList* ConsumeFontFaceUnicodeRange(CSSParserTokenRange& range) {
if (start > end)
return nullptr;
values->Append(*CSSUnicodeRangeValue::Create(start, end));
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return values;
}
@@ -69,7 +69,7 @@ CSSValueList* ConsumeFontFaceUnicodeRange(CSSParserTokenRange& range) {
CSSValue* ConsumeFontFaceSrcURI(CSSParserTokenRange& range,
const CSSParserContext& context) {
String url =
- CSSPropertyParserHelpers::ConsumeUrlAsStringView(range).ToString();
+ css_property_parser_helpers::ConsumeUrlAsStringView(range).ToString();
if (url.IsNull())
return nullptr;
CSSFontFaceSrcValue* uri_value(CSSFontFaceSrcValue::Create(
@@ -82,7 +82,8 @@ CSSValue* ConsumeFontFaceSrcURI(CSSParserTokenRange& range,
// FIXME: https://drafts.csswg.org/css-fonts says that format() contains a
// comma-separated list of strings, but CSSFontFaceSrcValue stores only one
// format. Allowing one format for now.
- CSSParserTokenRange args = CSSPropertyParserHelpers::ConsumeFunction(range);
+ CSSParserTokenRange args =
+ css_property_parser_helpers::ConsumeFunction(range);
const CSSParserToken& arg = args.ConsumeIncludingWhitespace();
if ((arg.GetType() != kStringToken) || !args.AtEnd())
return nullptr;
@@ -92,7 +93,8 @@ CSSValue* ConsumeFontFaceSrcURI(CSSParserTokenRange& range,
CSSValue* ConsumeFontFaceSrcLocal(CSSParserTokenRange& range,
const CSSParserContext& context) {
- CSSParserTokenRange args = CSSPropertyParserHelpers::ConsumeFunction(range);
+ CSSParserTokenRange args =
+ css_property_parser_helpers::ConsumeFunction(range);
ContentSecurityPolicyDisposition should_check_content_security_policy =
context.ShouldCheckContentSecurityPolicy();
if (args.Peek().GetType() == kStringToken) {
@@ -103,7 +105,7 @@ CSSValue* ConsumeFontFaceSrcLocal(CSSParserTokenRange& range,
arg.Value().ToString(), should_check_content_security_policy);
}
if (args.Peek().GetType() == kIdentToken) {
- String family_name = CSSParsingUtils::ConcatenateFamilyName(args);
+ String family_name = css_parsing_utils::ConcatenateFamilyName(args);
if (!args.AtEnd())
return nullptr;
return CSSFontFaceSrcValue::CreateLocal(
@@ -127,7 +129,7 @@ CSSValueList* ConsumeFontFaceSrc(CSSParserTokenRange& range,
if (!parsed_value)
return nullptr;
values->Append(*parsed_value);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return values;
}
@@ -141,9 +143,9 @@ CSSValue* AtRuleDescriptorParser::ParseFontFaceDescriptor(
range.ConsumeWhitespace();
switch (id) {
case AtRuleDescriptorID::FontFamily:
- if (CSSParsingUtils::ConsumeGenericFamily(range))
+ if (css_parsing_utils::ConsumeGenericFamily(range))
return nullptr;
- parsed_value = CSSParsingUtils::ConsumeFamilyName(range);
+ parsed_value = css_parsing_utils::ConsumeFamilyName(range);
break;
case AtRuleDescriptorID::Src: // This is a list of urls or local
// references.
@@ -157,21 +159,21 @@ CSSValue* AtRuleDescriptorParser::ParseFontFaceDescriptor(
break;
case AtRuleDescriptorID::FontStretch:
parsed_value =
- CSSParsingUtils::ConsumeFontStretch(range, kCSSFontFaceRuleMode);
+ css_parsing_utils::ConsumeFontStretch(range, kCSSFontFaceRuleMode);
break;
case AtRuleDescriptorID::FontStyle:
parsed_value =
- CSSParsingUtils::ConsumeFontStyle(range, kCSSFontFaceRuleMode);
+ css_parsing_utils::ConsumeFontStyle(range, kCSSFontFaceRuleMode);
break;
case AtRuleDescriptorID::FontVariant:
parsed_value = ConsumeFontVariantList(range);
break;
case AtRuleDescriptorID::FontWeight:
parsed_value =
- CSSParsingUtils::ConsumeFontWeight(range, kCSSFontFaceRuleMode);
+ css_parsing_utils::ConsumeFontWeight(range, kCSSFontFaceRuleMode);
break;
case AtRuleDescriptorID::FontFeatureSettings:
- parsed_value = CSSParsingUtils::ConsumeFontFeatureSettings(range);
+ parsed_value = css_parsing_utils::ConsumeFontFeatureSettings(range);
break;
default:
break;
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc b/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc
index ca147bf985e..d9850ed87ce 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc
@@ -14,6 +14,8 @@ CSSAtRuleID CssAtRuleID(StringView name) {
return kCSSAtRuleCharset;
if (EqualIgnoringASCIICase(name, "font-face"))
return kCSSAtRuleFontFace;
+ if (EqualIgnoringASCIICase(name, "font-feature-values"))
+ return kCSSAtRuleFontFeatureValues;
if (EqualIgnoringASCIICase(name, "import"))
return kCSSAtRuleImport;
if (EqualIgnoringASCIICase(name, "keyframes"))
@@ -43,6 +45,9 @@ void CountAtRule(const CSSParserContext* context, CSSAtRuleID rule_id) {
case kCSSAtRuleFontFace:
feature = WebFeature::kCSSAtRuleFontFace;
break;
+ case kCSSAtRuleFontFeatureValues:
+ feature = WebFeature::kCSSAtRuleFontFeatureValues;
+ break;
case kCSSAtRuleImport:
feature = WebFeature::kCSSAtRuleImport;
break;
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.h b/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.h
index 60bed62c078..89404368c14 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.h
@@ -12,19 +12,18 @@ namespace blink {
class CSSParserContext;
enum CSSAtRuleID {
- kCSSAtRuleInvalid = 0,
-
- kCSSAtRuleCharset = 1,
- kCSSAtRuleFontFace = 2,
- kCSSAtRuleImport = 3,
- kCSSAtRuleKeyframes = 4,
- kCSSAtRuleMedia = 5,
- kCSSAtRuleNamespace = 6,
- kCSSAtRulePage = 7,
- kCSSAtRuleSupports = 8,
- kCSSAtRuleViewport = 9,
-
- kCSSAtRuleWebkitKeyframes = 10,
+ kCSSAtRuleInvalid,
+ kCSSAtRuleCharset,
+ kCSSAtRuleFontFace,
+ kCSSAtRuleFontFeatureValues,
+ kCSSAtRuleImport,
+ kCSSAtRuleKeyframes,
+ kCSSAtRuleMedia,
+ kCSSAtRuleNamespace,
+ kCSSAtRulePage,
+ kCSSAtRuleSupports,
+ kCSSAtRuleViewport,
+ kCSSAtRuleWebkitKeyframes,
};
CSSAtRuleID CssAtRuleID(StringView name);
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.cc b/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.cc
index 1051232f6a7..9188af0af1f 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.cc
@@ -35,27 +35,6 @@ const CSSParserContext* CSSLazyParsingState::Context() {
return context_;
}
-bool CSSLazyParsingState::ShouldLazilyParseProperties(
- const CSSSelectorList& selectors) const {
- // Disallow lazy parsing for blocks which have before/after in their selector
- // list. This ensures we don't cause a collectFeatures() when we trigger
- // parsing for attr() functions which would trigger expensive invalidation
- // propagation.
- for (const auto* s = selectors.FirstForCSSOM(); s;
- s = CSSSelectorList::Next(*s)) {
- for (const CSSSelector* current = s; current;
- current = current->TagHistory()) {
- const CSSSelector::PseudoType type(current->GetPseudoType());
- if (type == CSSSelector::kPseudoBefore ||
- type == CSSSelector::kPseudoAfter)
- return false;
- if (current->Relation() != CSSSelector::kSubSelector)
- break;
- }
- }
- return true;
-}
-
void CSSLazyParsingState::Trace(blink::Visitor* visitor) {
visitor->Trace(owning_contents_);
visitor->Trace(document_);
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.h b/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.h
index 1e50644f8ea..6b7ad897bc1 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.h
@@ -30,7 +30,6 @@ class CSSLazyParsingState
const CSSParserContext* Context();
const String& SheetText() const { return sheet_text_; }
- bool ShouldLazilyParseProperties(const CSSSelectorList&) const;
void Trace(blink::Visitor*);
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc b/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc
index 961cfad7598..394a65d1f91 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc
@@ -45,9 +45,7 @@ TEST_F(CSSLazyParsingTest, Simple) {
EXPECT_TRUE(HasParsedProperties(rule));
}
-// Avoid parsing rules with ::before or ::after to avoid causing
-// collectFeatures() when we trigger parsing for attr();
-TEST_F(CSSLazyParsingTest, DontLazyParseBeforeAfter) {
+TEST_F(CSSLazyParsingTest, LazyParseBeforeAfter) {
CSSParserContext* context = CSSParserContext::Create(
kHTMLStandardMode, SecureContextMode::kInsecureContext);
StyleSheetContents* style_sheet = StyleSheetContents::Create(context);
@@ -57,8 +55,8 @@ TEST_F(CSSLazyParsingTest, DontLazyParseBeforeAfter) {
CSSParser::ParseSheet(context, style_sheet, sheet_text,
CSSDeferPropertyParsing::kYes);
- EXPECT_TRUE(HasParsedProperties(RuleAt(style_sheet, 0)));
- EXPECT_TRUE(HasParsedProperties(RuleAt(style_sheet, 1)));
+ EXPECT_FALSE(HasParsedProperties(RuleAt(style_sheet, 0)));
+ EXPECT_FALSE(HasParsedProperties(RuleAt(style_sheet, 1)));
}
// Test for crbug.com/664115 where |shouldConsiderForMatchingRules| would flip
@@ -88,8 +86,8 @@ TEST_F(CSSLazyParsingTest, ShouldConsiderForMatchingRulesDoesntChange1) {
rule->ShouldConsiderForMatchingRules(false /* includeEmptyRules */));
}
-// Test the same thing as above, with a property that does not get lazy parsed,
-// to ensure that we perform the optimization where possible.
+// Test the same thing as above with lazy parsing off to ensure that we perform
+// the optimization where possible.
TEST_F(CSSLazyParsingTest, ShouldConsiderForMatchingRulesSimple) {
CSSParserContext* context = CSSParserContext::Create(
kHTMLStandardMode, SecureContextMode::kInsecureContext);
@@ -97,7 +95,7 @@ TEST_F(CSSLazyParsingTest, ShouldConsiderForMatchingRulesSimple) {
String sheet_text = "p::before { ,badness, } ";
CSSParser::ParseSheet(context, style_sheet, sheet_text,
- CSSDeferPropertyParsing::kYes);
+ CSSDeferPropertyParsing::kNo);
StyleRule* rule = RuleAt(style_sheet, 0);
EXPECT_TRUE(HasParsedProperties(rule));
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser.cc
index 9f354dd04ec..35d92911d1d 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser.cc
@@ -186,6 +186,14 @@ ImmutableCSSPropertyValueSet* CSSParser::ParseInlineStyleDeclaration(
return CSSParserImpl::ParseInlineStyleDeclaration(style_string, element);
}
+ImmutableCSSPropertyValueSet* CSSParser::ParseInlineStyleDeclaration(
+ const String& style_string,
+ CSSParserMode parser_mode,
+ SecureContextMode secure_context_mode) {
+ return CSSParserImpl::ParseInlineStyleDeclaration(style_string, parser_mode,
+ secure_context_mode);
+}
+
std::unique_ptr<Vector<double>> CSSParser::ParseKeyframeKeyList(
const String& key_list) {
return CSSParserImpl::ParseKeyframeKeyList(key_list);
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser.h
index 118bb97223f..e13bb6c4f01 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser.h
@@ -7,9 +7,9 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
namespace blink {
@@ -88,6 +88,8 @@ class CORE_EXPORT CSSParser {
static ImmutableCSSPropertyValueSet* ParseInlineStyleDeclaration(
const String&,
Element*);
+ static ImmutableCSSPropertyValueSet*
+ ParseInlineStyleDeclaration(const String&, CSSParserMode, SecureContextMode);
static std::unique_ptr<Vector<double>> ParseKeyframeKeyList(const String&);
static StyleRuleKeyframe* ParseKeyframeRule(const CSSParserContext*,
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.cc
index b02890d02ff..fa214682792 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.cc
@@ -4,9 +4,14 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
+#include "third_party/blink/renderer/core/css/css_custom_ident_value.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
+#include "third_party/blink/renderer/core/css/css_value_list.h"
+#include "third_party/blink/renderer/core/css/style_rule_keyframe.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/feature_policy/feature_policy.h"
+#include "third_party/blink/renderer/core/feature_policy/layout_animations_policy.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/settings.h"
@@ -27,7 +32,7 @@ CSSParserContext* CSSParserContext::Create(const ExecutionContext& context) {
else
policy_disposition = kCheckContentSecurityPolicy;
- return new CSSParserContext(
+ return MakeGarbageCollected<CSSParserContext>(
context.Url(), false /* is_opaque_response_from_service_worker */,
WTF::TextEncoding(), kHTMLStandardMode, kHTMLStandardMode, kLiveProfile,
referrer, true, false, context.GetSecureContextMode(), policy_disposition,
@@ -54,7 +59,7 @@ CSSParserContext* CSSParserContext::CreateWithStyleSheetContents(
CSSParserContext* CSSParserContext::Create(
const CSSParserContext* other,
const Document* use_counter_document) {
- return new CSSParserContext(
+ return MakeGarbageCollected<CSSParserContext>(
other->base_url_, other->is_opaque_response_from_service_worker_,
other->charset_, other->mode_, other->match_mode_, other->profile_,
other->referrer_, other->is_html_document_,
@@ -68,10 +73,10 @@ CSSParserContext* CSSParserContext::Create(
const CSSParserContext* other,
const KURL& base_url,
bool is_opaque_response_from_service_worker,
- ReferrerPolicy referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const WTF::TextEncoding& charset,
const Document* use_counter_document) {
- return new CSSParserContext(
+ return MakeGarbageCollected<CSSParserContext>(
base_url, is_opaque_response_from_service_worker, charset, other->mode_,
other->match_mode_, other->profile_,
Referrer(base_url.StrippedForUseAsReferrer(), referrer_policy),
@@ -87,7 +92,7 @@ CSSParserContext* CSSParserContext::Create(
SecureContextMode secure_context_mode,
SelectorProfile profile,
const Document* use_counter_document) {
- return new CSSParserContext(
+ return MakeGarbageCollected<CSSParserContext>(
KURL(), false /* is_opaque_response_from_service_worker */,
WTF::TextEncoding(), mode, mode, profile, Referrer(), false, false,
secure_context_mode, kDoNotCheckContentSecurityPolicy,
@@ -107,7 +112,7 @@ CSSParserContext* CSSParserContext::Create(
const Document& document,
const KURL& base_url_override,
bool is_opaque_response_from_service_worker,
- ReferrerPolicy referrer_policy_override,
+ network::mojom::ReferrerPolicy referrer_policy_override,
const WTF::TextEncoding& charset,
SelectorProfile profile) {
CSSParserMode mode =
@@ -137,7 +142,7 @@ CSSParserContext* CSSParserContext::Create(
else
policy_disposition = kCheckContentSecurityPolicy;
- return new CSSParserContext(
+ return MakeGarbageCollected<CSSParserContext>(
base_url_override, is_opaque_response_from_service_worker, charset, mode,
match_mode, profile, referrer, document.IsHTMLDocument(),
use_legacy_background_size_shorthand_behavior,
@@ -239,6 +244,22 @@ bool CSSParserContext::IsDocumentHandleEqual(const Document* other) const {
return document_.Get() == other;
}
+bool CSSParserContext::IsLayoutAnimationsPolicyEnforced() const {
+ return document_ && !document_->IsFeatureEnabled(
+ mojom::FeaturePolicyFeature::kLayoutAnimations);
+}
+
+void CSSParserContext::ReportLayoutAnimationsViolationIfNeeded(
+ const StyleRuleKeyframe& rule) const {
+ DCHECK(IsLayoutAnimationsPolicyEnforced());
+ for (size_t i = 0; i < rule.Properties().PropertyCount(); ++i) {
+ const CSSProperty& property = rule.Properties().PropertyAt(i).Property();
+ if (!LayoutAnimationsPolicy::AffectedCSSProperties().Contains(&property))
+ continue;
+ LayoutAnimationsPolicy::ReportViolation(property, *document_);
+ }
+}
+
void CSSParserContext::Trace(blink::Visitor* visitor) {
visitor->Trace(document_);
}
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.h
index 851e068e373..c14c66fda31 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_context.h
@@ -6,8 +6,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_CONTEXT_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/web_feature_forward.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -20,6 +20,7 @@ namespace blink {
class CSSStyleSheet;
class Document;
+class StyleRuleKeyframe;
class StyleSheetContents;
class CORE_EXPORT CSSParserContext
@@ -41,12 +42,13 @@ class CORE_EXPORT CSSParserContext
static CSSParserContext* Create(const CSSParserContext* other,
const Document* use_counter_document);
- static CSSParserContext* Create(const CSSParserContext* other,
- const KURL& base_url_override,
- bool is_opaque_response_from_service_worker,
- ReferrerPolicy referrer_policy_override,
- const WTF::TextEncoding& charset_override,
- const Document* use_counter_document);
+ static CSSParserContext* Create(
+ const CSSParserContext* other,
+ const KURL& base_url_override,
+ bool is_opaque_response_from_service_worker,
+ network::mojom::ReferrerPolicy referrer_policy_override,
+ const WTF::TextEncoding& charset_override,
+ const Document* use_counter_document);
static CSSParserContext* Create(
CSSParserMode,
@@ -58,12 +60,25 @@ class CORE_EXPORT CSSParserContext
const Document&,
const KURL& base_url_override,
bool is_opaque_response_from_service_worker,
- ReferrerPolicy referrer_policy_override,
+ network::mojom::ReferrerPolicy referrer_policy_override,
const WTF::TextEncoding& charset = WTF::TextEncoding(),
SelectorProfile = kLiveProfile);
// This is used for workers, where we don't have a document.
static CSSParserContext* Create(const ExecutionContext&);
+ CSSParserContext(const KURL& base_url,
+ bool is_opaque_response_from_service_worker,
+ const WTF::TextEncoding& charset,
+ CSSParserMode,
+ CSSParserMode match_mode,
+ SelectorProfile,
+ const Referrer&,
+ bool is_html_document,
+ bool use_legacy_background_size_shorthand_behavior,
+ SecureContextMode,
+ ContentSecurityPolicyDisposition,
+ const Document* use_counter_document);
+
bool operator==(const CSSParserContext&) const;
bool operator!=(const CSSParserContext& other) const {
return !(*this == other);
@@ -110,22 +125,16 @@ class CORE_EXPORT CSSParserContext
return should_check_content_security_policy_;
}
+ // TODO(ekaramad): We currently only report @keyframes violations. We need to
+ // report CSS transitions as well (https://crbug.com/906147).
+ // TODO(ekaramad): We should provide a source location in the violation
+ // report (https://crbug.com/906150, ).
+ bool IsLayoutAnimationsPolicyEnforced() const;
+ void ReportLayoutAnimationsViolationIfNeeded(const StyleRuleKeyframe&) const;
+
void Trace(blink::Visitor*);
private:
- CSSParserContext(const KURL& base_url,
- bool is_opaque_response_from_service_worker,
- const WTF::TextEncoding& charset,
- CSSParserMode,
- CSSParserMode match_mode,
- SelectorProfile,
- const Referrer&,
- bool is_html_document,
- bool use_legacy_background_size_shorthand_behavior,
- SecureContextMode,
- ContentSecurityPolicyDisposition,
- const Document* use_counter_document);
-
KURL base_url_;
const bool is_opaque_response_from_service_worker_;
WTF::TextEncoding charset_;
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc
index 19be54166b1..07d25b3c6f3 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc
@@ -665,7 +665,7 @@ bool CSSParserFastPaths::IsValidKeywordPropertyAndValue(
case CSSPropertyPointerEvents:
return value_id == CSSValueVisible || value_id == CSSValueNone ||
value_id == CSSValueAll || value_id == CSSValueAuto ||
- (value_id >= CSSValueVisiblePainted &&
+ (value_id >= CSSValueVisiblepainted &&
value_id <= CSSValueBoundingBox);
case CSSPropertyPosition:
return value_id == CSSValueStatic || value_id == CSSValueRelative ||
@@ -678,7 +678,6 @@ bool CSSParserFastPaths::IsValidKeywordPropertyAndValue(
(value_id == CSSValueBlock || value_id == CSSValueInline)) ||
value_id == CSSValueAuto;
case CSSPropertyScrollBehavior:
- DCHECK(RuntimeEnabledFeatures::CSSOMSmoothScrollEnabled());
return value_id == CSSValueAuto || value_id == CSSValueSmooth;
case CSSPropertyShapeRendering:
return value_id == CSSValueAuto || value_id == CSSValueOptimizespeed ||
@@ -883,7 +882,6 @@ bool CSSParserFastPaths::IsValidKeywordPropertyAndValue(
return value_id == CSSValueNormal || value_id == CSSValueBreakAll ||
value_id == CSSValueKeepAll || value_id == CSSValueBreakWord;
case CSSPropertyScrollSnapStop:
- DCHECK(RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled());
return value_id == CSSValueNormal || value_id == CSSValueAlways;
case CSSPropertyOverscrollBehaviorX:
return value_id == CSSValueAuto || value_id == CSSValueContain ||
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.h
index 4d491dc3e65..17109539d67 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_FAST_PATHS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_FAST_PATHS_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths_fuzzer.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths_fuzzer.cc
index 193e767d8ae..7d1c0e37830 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths_fuzzer.cc
@@ -18,7 +18,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
blink::FuzzedDataProvider provider(data, size);
const auto property_id =
- blink::convertToCSSPropertyID(provider.ConsumeInt32InRange(
+ blink::convertToCSSPropertyID(provider.ConsumeIntegralInRange<int>(
blink::firstCSSProperty, blink::lastCSSProperty));
const auto data_string = provider.ConsumeRemainingBytes();
@@ -31,12 +31,5 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
static_cast<blink::CSSParserMode>(parser_mode));
}
-#if defined(ADDRESS_SANITIZER)
- // LSAN needs unreachable objects to be released to avoid reporting them
- // incorrectly as a memory leak.
- blink::ThreadState* currentThreadState = blink::ThreadState::Current();
- currentThreadState->CollectAllGarbage();
-#endif
-
return 0;
}
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
index a38daa0943c..1f1d7f8c47e 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
@@ -25,6 +25,7 @@
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h"
#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h"
#include "third_party/blink/renderer/core/css/parser/media_query_parser.h"
+#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
#include "third_party/blink/renderer/core/css/style_rule_import.h"
#include "third_party/blink/renderer/core/css/style_rule_keyframe.h"
@@ -192,6 +193,19 @@ ImmutableCSSPropertyValueSet* CSSParserImpl::ParseInlineStyleDeclaration(
return CreateCSSPropertyValueSet(parser.parsed_properties_, mode);
}
+ImmutableCSSPropertyValueSet* CSSParserImpl::ParseInlineStyleDeclaration(
+ const String& string,
+ CSSParserMode parser_mode,
+ SecureContextMode secure_context_mode) {
+ CSSParserContext* context =
+ CSSParserContext::Create(parser_mode, secure_context_mode);
+ CSSParserImpl parser(context);
+ CSSTokenizer tokenizer(string);
+ CSSParserTokenStream stream(tokenizer);
+ parser.ConsumeDeclarationList(stream, StyleRule::kStyle);
+ return CreateCSSPropertyValueSet(parser.parsed_properties_, parser_mode);
+}
+
bool CSSParserImpl::ParseDeclarationList(
MutableCSSPropertyValueSet* declaration,
const String& string,
@@ -258,8 +272,8 @@ ParseSheetResult CSSParserImpl::ParseStyleSheet(
CSSParserTokenStream stream(tokenizer);
CSSParserImpl parser(context, style_sheet);
if (defer_property_parsing == CSSDeferPropertyParsing::kYes) {
- parser.lazy_state_ =
- new CSSLazyParsingState(context, string, parser.style_sheet_);
+ parser.lazy_state_ = MakeGarbageCollected<CSSLazyParsingState>(
+ context, string, parser.style_sheet_);
}
ParseSheetResult result = ParseSheetResult::kSucceeded;
bool first_rule_valid = parser.ConsumeRuleList(
@@ -397,6 +411,7 @@ static CSSParserImpl::AllowedRulesType ComputeNewAllowedRules(
CSSParserImpl::AllowedRulesType allowed_rules,
StyleRuleBase* rule) {
if (!rule || allowed_rules == CSSParserImpl::kKeyframeRules ||
+ allowed_rules == CSSParserImpl::kFontFeatureRules ||
allowed_rules == CSSParserImpl::kNoRules)
return allowed_rules;
DCHECK_LE(allowed_rules, CSSParserImpl::kRegularRules);
@@ -422,6 +437,9 @@ bool CSSParserImpl::ConsumeRuleList(CSSParserTokenStream& stream,
case kKeyframesRuleList:
allowed_rules = kKeyframeRules;
break;
+ case kFontFeatureRuleList:
+ allowed_rules = kFontFeatureRules;
+ break;
default:
NOTREACHED();
}
@@ -502,6 +520,9 @@ StyleRuleBase* CSSParserImpl::ConsumeAtRule(CSSParserTokenStream& stream,
if (allowed_rules == kKeyframeRules)
return nullptr; // Parse error, no at-rules supported inside @keyframes
+ // Parse error, no at-rules currently supported inside @font-feature-values
+ if (allowed_rules == kFontFeatureRules)
+ return nullptr;
if (allowed_rules == kNoRules)
return nullptr; // Parse error, no at-rules with blocks supported inside
// declaration lists
@@ -517,6 +538,8 @@ StyleRuleBase* CSSParserImpl::ConsumeAtRule(CSSParserTokenStream& stream,
return ConsumeViewportRule(prelude, prelude_offset, stream);
case kCSSAtRuleFontFace:
return ConsumeFontFaceRule(prelude, prelude_offset, stream);
+ case kCSSAtRuleFontFeatureValues:
+ return ConsumeFontFeatureValuesRule(prelude, prelude_offset, stream);
case kCSSAtRuleWebkitKeyframes:
return ConsumeKeyframesRule(true, prelude, prelude_offset, stream);
case kCSSAtRuleKeyframes:
@@ -547,7 +570,34 @@ StyleRuleBase* CSSParserImpl::ConsumeQualifiedRule(
return nullptr; // Parse error, EOF instead of qualified rule block
CSSParserTokenStream::BlockGuard guard(stream);
- return ConsumeKeyframeStyleRule(prelude, prelude_offset, stream);
+ StyleRuleKeyframe* keyframe_style_rule =
+ ConsumeKeyframeStyleRule(prelude, prelude_offset, stream);
+ if (context_->IsLayoutAnimationsPolicyEnforced()) {
+ context_->ReportLayoutAnimationsViolationIfNeeded(*keyframe_style_rule);
+ }
+ return keyframe_style_rule;
+ }
+ if (allowed_rules == kFontFeatureRules) {
+ stream.ConsumeWhitespace();
+ if (stream.AtEnd())
+ return nullptr; // Parse error, EOF instead of qualified rule block
+ bool prelude_invalid = false;
+ stream.EnsureLookAhead();
+ if (stream.UncheckedPeek().GetType() != kLeftBraceToken) {
+ prelude_invalid = true;
+ while (!stream.AtEnd() &&
+ stream.UncheckedPeek().GetType() != kLeftBraceToken)
+ stream.UncheckedConsumeComponentValue();
+ if (stream.AtEnd())
+ return nullptr;
+ }
+
+ CSSParserTokenStream::BlockGuard guard(stream);
+ if (prelude_invalid)
+ return nullptr;
+ ConsumeDeclarationList(stream, StyleRule::kFontFace);
+ return StyleRuleFontFace::Create(
+ CreateCSSPropertyValueSet(parsed_properties_, kCSSFontFaceRuleMode));
}
NOTREACHED();
@@ -716,6 +766,43 @@ StyleRuleFontFace* CSSParserImpl::ConsumeFontFaceRule(
CreateCSSPropertyValueSet(parsed_properties_, kCSSFontFaceRuleMode));
}
+StyleRuleFontFeatureValues* CSSParserImpl::ConsumeFontFeatureValuesRule(
+ CSSParserTokenRange prelude,
+ const RangeOffset& prelude_offset,
+ CSSParserTokenStream& block) {
+ if (!RuntimeEnabledFeatures::CSSFontFeatureValuesEnabled())
+ return nullptr;
+
+ const CSSValueList* font_family =
+ css_parsing_utils::ConsumeFontFamily(prelude);
+ if (!font_family || !prelude.AtEnd())
+ return nullptr;
+
+ if (observer_) {
+ observer_->StartRuleHeader(StyleRule::kFontFeatureValues,
+ prelude_offset.start);
+ observer_->EndRuleHeader(prelude_offset.end);
+ observer_->StartRuleBody(block.Offset());
+ }
+
+ const CSSIdentifierValue* font_display = nullptr;
+ ConsumeRuleList(
+ block, kFontFeatureRuleList, [&font_display](StyleRuleBase* rule) {
+ const CSSValue* value =
+ ToStyleRuleFontFace(rule)->Properties().GetPropertyCSSValue(
+ CSSPropertyFontDisplay);
+ if (value)
+ font_display = ToCSSIdentifierValue(value);
+ });
+
+ if (observer_)
+ observer_->EndRuleBody(block.Offset());
+
+ if (!block.AtEnd())
+ return nullptr;
+ return StyleRuleFontFeatureValues::Create(font_family, font_display);
+}
+
StyleRuleKeyframes* CSSParserImpl::ConsumeKeyframesRule(
bool webkit_prefixed,
CSSParserTokenRange prelude,
@@ -824,12 +911,12 @@ StyleRule* CSSParserImpl::ConsumeStyleRule(CSSParserTokenStream& stream) {
return nullptr; // Parse error, invalid selector list
// TODO(csharrison): How should we lazily parse css that needs the observer?
- if (!observer_ && lazy_state_ &&
- lazy_state_->ShouldLazilyParseProperties(selector_list)) {
+ if (!observer_ && lazy_state_) {
DCHECK(style_sheet_);
return StyleRule::CreateLazy(
std::move(selector_list),
- new CSSLazyPropertyParserImpl(stream.Offset() - 1, lazy_state_));
+ MakeGarbageCollected<CSSLazyPropertyParserImpl>(stream.Offset() - 1,
+ lazy_state_));
}
ConsumeDeclarationList(stream, StyleRule::kStyle);
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.h
index 37bf28a0b98..58c53ab8ebf 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.h
@@ -8,11 +8,11 @@
#include <memory>
#include "base/macros.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_source_data.h"
#include "third_party/blink/renderer/core/css/css_property_value.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -26,6 +26,7 @@ class CSSParserTokenStream;
class StyleRule;
class StyleRuleBase;
class StyleRuleCharset;
+class StyleRuleFontFeatureValues;
class StyleRuleFontFace;
class StyleRuleImport;
class StyleRuleKeyframe;
@@ -60,7 +61,8 @@ class CSSParserImpl {
kAllowNamespaceRules,
kRegularRules,
kKeyframeRules,
- kNoRules, // For parsing at-rules inside declaration lists
+ kFontFeatureRules,
+ kNoRules, // For parsing at-rules inside declaration lists
};
// Represents the start and end offsets of a CSSParserTokenRange.
@@ -93,6 +95,8 @@ class CSSParserImpl {
static ImmutableCSSPropertyValueSet* ParseInlineStyleDeclaration(
const String&,
Element*);
+ static ImmutableCSSPropertyValueSet*
+ ParseInlineStyleDeclaration(const String&, CSSParserMode, SecureContextMode);
static bool ParseDeclarationList(MutableCSSPropertyValueSet*,
const String&,
const CSSParserContext*);
@@ -127,7 +131,12 @@ class CSSParserImpl {
const CSSParserContext*);
private:
- enum RuleListType { kTopLevelRuleList, kRegularRuleList, kKeyframesRuleList };
+ enum RuleListType {
+ kTopLevelRuleList,
+ kRegularRuleList,
+ kKeyframesRuleList,
+ kFontFeatureRuleList,
+ };
// Returns whether the first encountered rule was valid
template <typename T>
@@ -154,6 +163,10 @@ class CSSParserImpl {
StyleRuleFontFace* ConsumeFontFaceRule(CSSParserTokenRange prelude,
const RangeOffset& prelude_offset,
CSSParserTokenStream& block);
+ StyleRuleFontFeatureValues* ConsumeFontFeatureValuesRule(
+ CSSParserTokenRange prelude,
+ const RangeOffset& prelude_offset,
+ CSSParserTokenStream& block);
StyleRuleKeyframes* ConsumeKeyframesRule(bool webkit_prefixed,
CSSParserTokenRange prelude,
const RangeOffset& prelude_offset,
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.cc
index bb8cefa4425..6ac76945e1a 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.cc
@@ -7,19 +7,54 @@
namespace blink {
CSSParserLocalContext::CSSParserLocalContext()
- : use_alias_parsing_(false), current_shorthand_(CSSPropertyInvalid) {}
+ : use_alias_parsing_(false),
+ is_animation_tainted_(false),
+ current_shorthand_(CSSPropertyInvalid),
+ variable_mode_(VariableMode::kTyped) {}
-CSSParserLocalContext::CSSParserLocalContext(bool use_alias_parsing,
- CSSPropertyID current_shorthand)
- : use_alias_parsing_(use_alias_parsing),
- current_shorthand_(current_shorthand) {}
+CSSParserLocalContext CSSParserLocalContext::WithAliasParsing(
+ bool use_alias_parsing) const {
+ CSSParserLocalContext context = *this;
+ context.use_alias_parsing_ = use_alias_parsing;
+ return context;
+}
+
+CSSParserLocalContext CSSParserLocalContext::WithAnimationTainted(
+ bool is_animation_tainted) const {
+ CSSParserLocalContext context = *this;
+ context.is_animation_tainted_ = is_animation_tainted;
+ return context;
+}
+
+CSSParserLocalContext CSSParserLocalContext::WithCurrentShorthand(
+ CSSPropertyID current_shorthand) const {
+ CSSParserLocalContext context = *this;
+ context.current_shorthand_ = current_shorthand;
+ return context;
+}
+
+CSSParserLocalContext CSSParserLocalContext::WithVariableMode(
+ VariableMode variable_mode) const {
+ CSSParserLocalContext context = *this;
+ context.variable_mode_ = variable_mode;
+ return context;
+}
bool CSSParserLocalContext::UseAliasParsing() const {
return use_alias_parsing_;
}
+bool CSSParserLocalContext::IsAnimationTainted() const {
+ return is_animation_tainted_;
+}
+
CSSPropertyID CSSParserLocalContext::CurrentShorthand() const {
return current_shorthand_;
}
+CSSParserLocalContext::VariableMode CSSParserLocalContext::GetVariableMode()
+ const {
+ return variable_mode_;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.h
index 2f1fbf3a20d..d5de80e82ed 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.h
@@ -5,26 +5,56 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_LOCAL_CONTEXT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_LOCAL_CONTEXT_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
// A wrapper class containing all local context when parsing a property.
-class CSSParserLocalContext {
+class CORE_EXPORT CSSParserLocalContext {
STACK_ALLOCATED();
public:
CSSParserLocalContext();
- CSSParserLocalContext(bool use_alias_parsing,
- CSSPropertyID current_shorthand);
+
+ // When parsing registered custom properties, a different result is required
+ // depending on the context.
+ enum class VariableMode {
+ // The custom property is parsed according to the registered syntax (if
+ // available).
+ kTyped,
+ // The registration of the custom property (if any) is ignored; the custom
+ // property will parse as if unregistered.
+ kUntyped,
+ // The custom property will be parsed as if unregistered (that is,
+ // a CSSCustomPropertyDeclaration will be returned), but the tokens must
+ // also match the registered syntax (if any). This is useful for CSSOM,
+ // where incoming values must validate against the registered syntax, but
+ // are otherwise treated as unregistered.
+ kValidatedUntyped
+ };
+
+ CSSParserLocalContext WithAliasParsing(bool) const;
+ CSSParserLocalContext WithAnimationTainted(bool) const;
+ CSSParserLocalContext WithCurrentShorthand(CSSPropertyID) const;
+ CSSParserLocalContext WithVariableMode(VariableMode) const;
+
bool UseAliasParsing() const;
+ // Any custom property used in a @keyframes rule becomes animation-tainted,
+ // which prevents the custom property from being substituted into the
+ // 'animation' property, or one of its longhands.
+ //
+ // https://drafts.csswg.org/css-variables/#animation-tainted
+ bool IsAnimationTainted() const;
CSSPropertyID CurrentShorthand() const;
+ VariableMode GetVariableMode() const;
private:
bool use_alias_parsing_;
+ bool is_animation_tainted_;
CSSPropertyID current_shorthand_;
+ VariableMode variable_mode_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context_test.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context_test.cc
new file mode 100644
index 00000000000..4fbcac6d178
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context_test.cc
@@ -0,0 +1,89 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace blink {
+
+using VariableMode = CSSParserLocalContext::VariableMode;
+
+TEST(CSSParserLocalContextTest, Constructor) {
+ EXPECT_FALSE(CSSParserLocalContext().UseAliasParsing());
+ EXPECT_FALSE(CSSParserLocalContext().IsAnimationTainted());
+ EXPECT_EQ(CSSPropertyInvalid, CSSParserLocalContext().CurrentShorthand());
+ EXPECT_EQ(VariableMode::kTyped, CSSParserLocalContext().GetVariableMode());
+}
+
+TEST(CSSParserLocalContextTest, WithAliasParsing) {
+ const CSSParserLocalContext context;
+ EXPECT_FALSE(context.WithAliasParsing(false).UseAliasParsing());
+ EXPECT_TRUE(context.WithAliasParsing(true).UseAliasParsing());
+}
+
+TEST(CSSParserLocalContextTest, WithAnimationTainted) {
+ const CSSParserLocalContext context;
+ EXPECT_FALSE(context.WithAnimationTainted(false).IsAnimationTainted());
+ EXPECT_TRUE(context.WithAnimationTainted(true).IsAnimationTainted());
+}
+
+TEST(CSSParserLocalContextTest, WithCurrentShorthand) {
+ const CSSParserLocalContext context;
+ const CSSPropertyID shorthand = CSSPropertyBackground;
+ EXPECT_EQ(shorthand,
+ context.WithCurrentShorthand(shorthand).CurrentShorthand());
+}
+
+TEST(CSSParserLocalContextTest, WithVariableMode) {
+ auto mode = VariableMode::kUntyped;
+ auto context = CSSParserLocalContext().WithVariableMode(mode);
+ EXPECT_EQ(mode, context.GetVariableMode());
+}
+
+TEST(CSSParserLocalContextTest, LocalMutation) {
+ CSSParserLocalContext context;
+ context = context.WithAliasParsing(true);
+ context = context.WithAnimationTainted(true);
+ context = context.WithCurrentShorthand(CSSPropertyBackground);
+ context = context.WithVariableMode(VariableMode::kUntyped);
+
+ // WithAliasParsing only changes that member.
+ {
+ auto local_context = context.WithAliasParsing(false);
+ EXPECT_FALSE(local_context.UseAliasParsing());
+ EXPECT_EQ(CSSPropertyBackground, local_context.CurrentShorthand());
+ EXPECT_TRUE(local_context.IsAnimationTainted());
+ EXPECT_EQ(VariableMode::kUntyped, local_context.GetVariableMode());
+ }
+
+ // WithAnimationTainted only changes that member.
+ {
+ auto local_context = context.WithAnimationTainted(false);
+ EXPECT_TRUE(local_context.UseAliasParsing());
+ EXPECT_EQ(CSSPropertyBackground, local_context.CurrentShorthand());
+ EXPECT_FALSE(local_context.IsAnimationTainted());
+ EXPECT_EQ(VariableMode::kUntyped, local_context.GetVariableMode());
+ }
+
+ // WithCurrentShorthand only changes that member.
+ {
+ auto local_context = context.WithCurrentShorthand(CSSPropertyPadding);
+ EXPECT_TRUE(local_context.UseAliasParsing());
+ EXPECT_EQ(CSSPropertyPadding, local_context.CurrentShorthand());
+ EXPECT_TRUE(local_context.IsAnimationTainted());
+ EXPECT_EQ(VariableMode::kUntyped, local_context.GetVariableMode());
+ }
+
+ // WithVariableMode only changes that member.
+ {
+ auto local_context = context.WithVariableMode(VariableMode::kTyped);
+ EXPECT_TRUE(local_context.UseAliasParsing());
+ EXPECT_EQ(CSSPropertyBackground, local_context.CurrentShorthand());
+ EXPECT_TRUE(local_context.IsAnimationTainted());
+ EXPECT_EQ(VariableMode::kTyped, local_context.GetVariableMode());
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_selector.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_selector.h
index cf602a8948d..b55eda0e968 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_selector.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_selector.h
@@ -96,6 +96,9 @@ class CORE_EXPORT CSSParserSelector {
CSSSelector::PseudoType GetPseudoType() const {
return selector_->GetPseudoType();
}
+ bool IsTreeAbidingPseudoElement() const {
+ return selector_->IsTreeAbidingPseudoElement();
+ }
const CSSSelectorList* SelectorList() const {
return selector_->SelectorList();
}
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.cc b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.cc
index aa43d67d9a8..be1580b43da 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.cc
@@ -131,11 +131,11 @@ bool CSSParserToken::ValueDataCharRawEqual(const CSSParserToken& other) const {
return false;
if (value_data_char_raw_ == other.value_data_char_raw_ &&
- value_is8_bit_ == other.value_is8_bit_)
+ value_is_8bit_ == other.value_is_8bit_)
return true;
- if (value_is8_bit_) {
- return other.value_is8_bit_
+ if (value_is_8bit_) {
+ return other.value_is_8bit_
? Equal(static_cast<const LChar*>(value_data_char_raw_),
static_cast<const LChar*>(other.value_data_char_raw_),
value_length_)
@@ -143,7 +143,7 @@ bool CSSParserToken::ValueDataCharRawEqual(const CSSParserToken& other) const {
static_cast<const UChar*>(other.value_data_char_raw_),
value_length_);
} else {
- return other.value_is8_bit_
+ return other.value_is_8bit_
? Equal(static_cast<const UChar*>(value_data_char_raw_),
static_cast<const LChar*>(other.value_data_char_raw_),
value_length_)
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.h
index 240d2e7297f..9feebcf15a5 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token.h
@@ -111,7 +111,7 @@ class CORE_EXPORT CSSParserToken {
return static_cast<CSSParserTokenType>(type_);
}
StringView Value() const {
- if (value_is8_bit_)
+ if (value_is_8bit_)
return StringView(reinterpret_cast<const LChar*>(value_data_char_raw_),
value_length_);
return StringView(reinterpret_cast<const UChar*>(value_data_char_raw_),
@@ -155,7 +155,7 @@ class CORE_EXPORT CSSParserToken {
private:
void InitValueFromStringView(StringView string) {
value_length_ = string.length();
- value_is8_bit_ = string.Is8Bit();
+ value_is_8bit_ = string.Is8Bit();
value_data_char_raw_ = string.Bytes();
}
bool ValueDataCharRawEqual(const CSSParserToken& other) const;
@@ -167,7 +167,7 @@ class CORE_EXPORT CSSParserToken {
unsigned unit_ : 7; // CSSPrimitiveValue::UnitType
// value_... is an unpacked StringView so that we can pack it
// tightly with the rest of this object for a smaller object size.
- bool value_is8_bit_ : 1;
+ bool value_is_8bit_ : 1;
unsigned value_length_;
const void* value_data_char_raw_; // Either LChar* or UChar*.
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.cc
index 1f44e2df51b..33bfdf16fe7 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.cc
@@ -23,7 +23,7 @@
namespace blink {
-using namespace CSSPropertyParserHelpers;
+using namespace css_property_parser_helpers;
class CSSIdentifierValue;
@@ -96,13 +96,14 @@ bool CSSPropertyParser::ParseValueStart(CSSPropertyID unresolved_property,
bool is_shorthand = property.IsShorthand();
DCHECK(context_);
if (is_shorthand) {
+ const auto local_context =
+ CSSParserLocalContext()
+ .WithAliasParsing(isPropertyAlias(unresolved_property))
+ .WithCurrentShorthand(property_id);
// Variable references will fail to parse here and will fall out to the
// variable ref parser below.
if (ToShorthand(property).ParseShorthand(
- important, range_, *context_,
- CSSParserLocalContext(isPropertyAlias(unresolved_property),
- property_id),
- *parsed_properties_))
+ important, range_, *context_, local_context, *parsed_properties_))
return true;
} else {
if (const CSSValue* parsed_value = ParseLonghand(
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc
index 497d1a5fade..7e7a1d43cac 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc
@@ -33,7 +33,7 @@ namespace blink {
using namespace cssvalue;
-namespace CSSPropertyParserHelpers {
+namespace css_property_parser_helpers {
namespace {
@@ -85,13 +85,14 @@ CSSFunctionValue* ConsumeFilterFunction(CSSParserTokenRange& range,
CSSValueID filter_type = range.Peek().FunctionId();
if (filter_type < CSSValueInvert || filter_type > CSSValueDropShadow)
return nullptr;
- CSSParserTokenRange args = CSSPropertyParserHelpers::ConsumeFunction(range);
+ CSSParserTokenRange args =
+ css_property_parser_helpers::ConsumeFunction(range);
CSSFunctionValue* filter_value = CSSFunctionValue::Create(filter_type);
CSSValue* parsed_value = nullptr;
if (filter_type == CSSValueDropShadow) {
- parsed_value = CSSParsingUtils::ParseSingleShadow(
- args, context.Mode(), CSSParsingUtils::AllowInsetAndSpread::kForbid);
+ parsed_value = css_parsing_utils::ParseSingleShadow(
+ args, context.Mode(), css_parsing_utils::AllowInsetAndSpread::kForbid);
} else {
if (args.AtEnd()) {
context.Count(WebFeature::kCSSFilterFunctionNoArguments);
@@ -100,23 +101,23 @@ CSSFunctionValue* ConsumeFilterFunction(CSSParserTokenRange& range,
if (filter_type == CSSValueBrightness) {
// FIXME (crbug.com/397061): Support calc expressions like calc(10% + 0.5)
parsed_value =
- CSSPropertyParserHelpers::ConsumePercent(args, kValueRangeAll);
+ css_property_parser_helpers::ConsumePercent(args, kValueRangeAll);
if (!parsed_value) {
- parsed_value = CSSPropertyParserHelpers::ConsumeNumber(
+ parsed_value = css_property_parser_helpers::ConsumeNumber(
args, kValueRangeNonNegative);
}
} else if (filter_type == CSSValueHueRotate) {
- parsed_value = CSSPropertyParserHelpers::ConsumeAngle(
+ parsed_value = css_property_parser_helpers::ConsumeAngle(
args, &context, WebFeature::kUnitlessZeroAngleFilter);
} else if (filter_type == CSSValueBlur) {
- parsed_value = CSSPropertyParserHelpers::ConsumeLength(
+ parsed_value = css_property_parser_helpers::ConsumeLength(
args, kHTMLStandardMode, kValueRangeNonNegative);
} else {
// FIXME (crbug.com/397061): Support calc expressions like calc(10% + 0.5)
- parsed_value = CSSPropertyParserHelpers::ConsumePercent(
+ parsed_value = css_property_parser_helpers::ConsumePercent(
args, kValueRangeNonNegative);
if (!parsed_value) {
- parsed_value = CSSPropertyParserHelpers::ConsumeNumber(
+ parsed_value = css_property_parser_helpers::ConsumeNumber(
args, kValueRangeNonNegative);
}
if (parsed_value && filter_type != CSSValueSaturate &&
@@ -245,6 +246,30 @@ CSSPrimitiveValue* ConsumeInteger(CSSParserTokenRange& range,
return nullptr;
}
+// This implements the behavior defined in [1], where calc() expressions
+// are valid when <integer> is expected, even if the calc()-expression does
+// not result in an integral value.
+//
+// TODO(andruud): Eventually this behavior should just be part of
+// ConsumeInteger, and this function can be removed. For now, having a separate
+// function with this behavior allows us to implement [1] gradually.
+//
+// [1] https://drafts.csswg.org/css-values-4/#calc-type-checking
+CSSPrimitiveValue* ConsumeIntegerOrNumberCalc(CSSParserTokenRange& range) {
+ CSSParserTokenRange int_range(range);
+ if (CSSPrimitiveValue* value = ConsumeInteger(int_range)) {
+ range = int_range;
+ return value;
+ }
+ CalcParser calc_parser(range);
+ if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (calculation->Category() != kCalcNumber)
+ return nullptr;
+ return calc_parser.ConsumeValue();
+ }
+ return nullptr;
+}
+
CSSPrimitiveValue* ConsumePositiveInteger(CSSParserTokenRange& range) {
return ConsumeInteger(range, 1);
}
@@ -395,6 +420,28 @@ CSSPrimitiveValue* ConsumeLengthOrPercent(CSSParserTokenRange& range,
return nullptr;
}
+namespace {
+
+bool IsNonZeroUserUnitsValue(const CSSPrimitiveValue* value) {
+ return value &&
+ value->TypeWithCalcResolved() ==
+ CSSPrimitiveValue::UnitType::kUserUnits &&
+ value->GetDoubleValue() != 0;
+}
+
+} // namespace
+
+CSSPrimitiveValue* ConsumeSVGGeometryPropertyLength(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ ValueRange value_range) {
+ CSSPrimitiveValue* value = ConsumeLengthOrPercent(
+ range, kSVGAttributeMode, value_range, UnitlessQuirk::kForbid);
+ if (IsNonZeroUserUnitsValue(value))
+ context.Count(WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue);
+ return value;
+}
+
CSSPrimitiveValue* ConsumeGradientLengthOrPercent(
CSSParserTokenRange& range,
const CSSParserContext& context,
@@ -489,17 +536,26 @@ CSSIdentifierValue* ConsumeIdentRange(CSSParserTokenRange& range,
return ConsumeIdent(range);
}
-CSSCustomIdentValue* ConsumeCustomIdentWithToken(const CSSParserToken& token) {
+CSSCustomIdentValue* ConsumeCustomIdentWithToken(
+ const CSSParserToken& token,
+ const CSSParserContext& context) {
if (token.GetType() != kIdentToken || IsCSSWideKeyword(token.Value()))
return nullptr;
+
+ if (EqualIgnoringASCIICase(token.Value(), "default"))
+ context.Count(WebFeature::kDefaultInCustomIdent);
+
return CSSCustomIdentValue::Create(token.Value().ToAtomicString());
}
-CSSCustomIdentValue* ConsumeCustomIdent(CSSParserTokenRange& range) {
+CSSCustomIdentValue* ConsumeCustomIdent(CSSParserTokenRange& range,
+ const CSSParserContext& context) {
if (range.Peek().GetType() != kIdentToken ||
IsCSSWideKeyword(range.Peek().Value()))
return nullptr;
- return ConsumeCustomIdentWithToken(range.ConsumeIncludingWhitespace());
+
+ return ConsumeCustomIdentWithToken(range.ConsumeIncludingWhitespace(),
+ context);
}
CSSStringValue* ConsumeString(CSSParserTokenRange& range) {
@@ -962,21 +1018,21 @@ bool ConsumeBorderShorthand(CSSParserTokenRange& range,
const CSSValue*& result_color) {
while (!result_width || !result_style || !result_color) {
if (!result_width) {
- result_width = CSSPropertyParserHelpers::ConsumeLineWidth(
+ result_width = css_property_parser_helpers::ConsumeLineWidth(
range, context.Mode(),
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
if (result_width)
continue;
}
if (!result_style) {
- result_style = CSSPropertyParserHelpers::ParseLonghand(
+ result_style = css_property_parser_helpers::ParseLonghand(
CSSPropertyBorderLeftStyle, CSSPropertyBorder, context, range);
if (result_style)
continue;
}
if (!result_color) {
result_color =
- CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ css_property_parser_helpers::ConsumeColor(range, context.Mode());
if (result_color)
continue;
}
@@ -1428,7 +1484,7 @@ static CSSValue* ConsumeCrossFade(CSSParserTokenRange& args,
static CSSValue* ConsumePaint(CSSParserTokenRange& args,
const CSSParserContext* context) {
const CSSParserToken& name_token = args.ConsumeIncludingWhitespace();
- CSSCustomIdentValue* name = ConsumeCustomIdentWithToken(name_token);
+ CSSCustomIdentValue* name = ConsumeCustomIdentWithToken(name_token, *context);
if (!name)
return nullptr;
@@ -1638,14 +1694,14 @@ void AddProperty(CSSPropertyID resolved_property,
CSSValue* ConsumeTransformValue(CSSParserTokenRange& range,
const CSSParserContext& context) {
bool use_legacy_parsing = false;
- return CSSParsingUtils::ConsumeTransformValue(range, context,
- use_legacy_parsing);
+ return css_parsing_utils::ConsumeTransformValue(range, context,
+ use_legacy_parsing);
}
CSSValue* ConsumeTransformList(CSSParserTokenRange& range,
const CSSParserContext& context) {
- return CSSParsingUtils::ConsumeTransformList(range, context,
- CSSParserLocalContext());
+ return css_parsing_utils::ConsumeTransformList(range, context,
+ CSSParserLocalContext());
}
CSSValue* ConsumeFilterFunctionList(CSSParserTokenRange& range,
@@ -1746,12 +1802,13 @@ const CSSValue* ParseLonghand(CSSPropertyID unresolved_property,
return nullptr;
}
- const CSSValue* result =
- ToLonghand(CSSProperty::Get(property_id))
- .ParseSingleValue(
- range, context,
- CSSParserLocalContext(isPropertyAlias(unresolved_property),
- current_shorthand));
+ const auto local_context =
+ CSSParserLocalContext()
+ .WithAliasParsing(isPropertyAlias(unresolved_property))
+ .WithCurrentShorthand(current_shorthand);
+
+ const CSSValue* result = ToLonghand(CSSProperty::Get(property_id))
+ .ParseSingleValue(range, context, local_context);
return result;
}
@@ -1885,6 +1942,6 @@ void AddExpandedPropertyForValue(
}
}
-} // namespace CSSPropertyParserHelpers
+} // namespace css_property_parser_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h
index c8cc6856851..dc58c66aafc 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h
@@ -14,8 +14,8 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
#include "third_party/blink/renderer/core/frame/web_feature_forward.h"
+#include "third_party/blink/renderer/platform/geometry/length.h" // For ValueRange
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/length.h" // For ValueRange
namespace blink {
@@ -30,7 +30,7 @@ class StylePropertyShorthand;
// tokens from the range and also consume any whitespace which follows. When
// the start of the range doesn't match the type we're looking for, the range
// will not be modified.
-namespace CSSPropertyParserHelpers {
+namespace css_property_parser_helpers {
void Complete4Sides(CSSValue* side[4]);
@@ -45,6 +45,7 @@ enum class UnitlessQuirk { kAllow, kForbid };
CSSPrimitiveValue* ConsumeInteger(
CSSParserTokenRange&,
double minimum_value = -std::numeric_limits<double>::max());
+CSSPrimitiveValue* ConsumeIntegerOrNumberCalc(CSSParserTokenRange&);
CSSPrimitiveValue* ConsumePositiveInteger(CSSParserTokenRange&);
bool ConsumeNumberRaw(CSSParserTokenRange&, double& result);
CSSPrimitiveValue* ConsumeNumber(CSSParserTokenRange&, ValueRange);
@@ -58,6 +59,9 @@ CSSPrimitiveValue* ConsumeLengthOrPercent(
CSSParserMode,
ValueRange,
UnitlessQuirk = UnitlessQuirk::kForbid);
+CSSPrimitiveValue* ConsumeSVGGeometryPropertyLength(CSSParserTokenRange&,
+ const CSSParserContext&,
+ ValueRange);
CSSPrimitiveValue* ConsumeAngle(
CSSParserTokenRange&,
@@ -75,7 +79,8 @@ inline bool IdentMatches(CSSValueID id);
template <CSSValueID... allowedIdents>
CSSIdentifierValue* ConsumeIdent(CSSParserTokenRange&);
-CSSCustomIdentValue* ConsumeCustomIdent(CSSParserTokenRange&);
+CSSCustomIdentValue* ConsumeCustomIdent(CSSParserTokenRange&,
+ const CSSParserContext&);
CSSStringValue* ConsumeString(CSSParserTokenRange&);
StringView ConsumeUrlAsStringView(CSSParserTokenRange&);
CSSURIValue* ConsumeUrl(CSSParserTokenRange&, const CSSParserContext*);
@@ -205,7 +210,7 @@ CSSValue* ConsumeTransformList(CSSParserTokenRange&, const CSSParserContext&);
CSSValue* ConsumeFilterFunctionList(CSSParserTokenRange&,
const CSSParserContext&);
-} // namespace CSSPropertyParserHelpers
+} // namespace css_property_parser_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc
index 89b0b1bdea6..34d072e00f6 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc
@@ -457,4 +457,111 @@ TEST(CSSPropertyParserTest, DropFontfaceDescriptor) {
IsValidPropertyValueForStyleRule(CSSPropertySrc, "var(--dummy)"));
}
+class CSSPropertyUseCounterTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ dummy_page_holder_ = DummyPageHolder::Create(IntSize(800, 600));
+ Page::InsertOrdinaryPageForTesting(&dummy_page_holder_->GetPage());
+ // Use strict mode.
+ GetDocument().SetCompatibilityMode(Document::kNoQuirksMode);
+ }
+ void TearDown() override { dummy_page_holder_ = nullptr; }
+
+ void ParseProperty(CSSPropertyID property, const char* value_string) {
+ const CSSValue* value =
+ CSSParser::ParseSingleValue(property, String(value_string),
+ CSSParserContext::Create(GetDocument()));
+ DCHECK(value);
+ }
+
+ bool IsCounted(WebFeature feature) {
+ return UseCounter::IsCounted(GetDocument(), feature);
+ }
+
+ private:
+ Document& GetDocument() { return dummy_page_holder_->GetDocument(); }
+
+ std::unique_ptr<DummyPageHolder> dummy_page_holder_;
+};
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyXUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyX, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyX, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyYUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyY, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyY, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyRUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyR, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyR, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyRxUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyRx, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyRx, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyRyUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyRy, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyRy, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyCxUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyCx, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyCx, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyCyUnitlessUseCount) {
+ WebFeature feature = WebFeature::kSVGGeometryPropertyHasNonZeroUnitlessValue;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyCy, "0");
+ // Unitless zero should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyCy, "42");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyAnimationNameCustomIdentUseCount) {
+ WebFeature feature = WebFeature::kDefaultInCustomIdent;
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyAnimationName, "initial");
+ // css-wide keywords in custom ident other than default should not register.
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyAnimationName, "default");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.cc
index 5431ec0ad88..2918f7a99ee 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/core/css/parser/css_selector_parser.h"
#include <memory>
+#include "base/numerics/safe_conversions.h"
#include "third_party/blink/renderer/core/css/css_selector_list.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_observer.h"
@@ -266,12 +267,8 @@ bool IsSimpleSelectorValidAfterPseudoElement(
return true;
if (compound_pseudo_element == CSSSelector::kPseudoContent)
return simple_selector.Match() != CSSSelector::kPseudoElement;
- if (compound_pseudo_element == CSSSelector::kPseudoSlotted) {
- return simple_selector.Match() == CSSSelector::kPseudoElement &&
- (simple_selector.GetPseudoType() == CSSSelector::kPseudoBefore ||
- simple_selector.GetPseudoType() == CSSSelector::kPseudoAfter);
- }
-
+ if (compound_pseudo_element == CSSSelector::kPseudoSlotted)
+ return simple_selector.IsTreeAbidingPseudoElement();
if (simple_selector.Match() != CSSSelector::kPseudoClass)
return false;
CSSSelector::PseudoType pseudo = simple_selector.GetPseudoType();
@@ -328,6 +325,7 @@ std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumeCompoundSelector(
if (!compound_selector) {
AtomicString namespace_uri = DetermineNamespace(namespace_prefix);
if (namespace_uri.IsNull()) {
+ context_->Count(WebFeature::kCSSUnknownNamespacePrefixInSelector);
failed_parsing_ = true;
return nullptr;
}
@@ -489,6 +487,44 @@ std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumeAttribute(
return selector;
}
+void CSSSelectorParser::CountRejectedNot(CSSParserTokenRange& range) {
+ bool exists_valid = false;
+ bool exists_invalid = false;
+
+ do {
+ if (exists_valid || exists_invalid) {
+ DCHECK(range.Peek().GetType() == kCommaToken);
+ range.ConsumeIncludingWhitespace();
+ }
+ // else we are parsing the first complex selector
+
+ failed_parsing_ = false;
+ bool consumed_invalid = !ConsumeComplexSelector(range) || failed_parsing_;
+ range.ConsumeWhitespace();
+ while (!range.AtEnd() && range.Peek().GetType() != kCommaToken) {
+ consumed_invalid = true;
+ range.ConsumeIncludingWhitespace();
+ }
+
+ if (consumed_invalid)
+ exists_invalid = true;
+ else
+ exists_valid = true;
+ } while (!range.AtEnd());
+
+ WebFeature feature;
+ if (exists_valid) {
+ if (exists_invalid)
+ feature = WebFeature::kCSSSelectorNotWithPartiallyValidList;
+ else
+ feature = WebFeature::kCSSSelectorNotWithValidList;
+ } else {
+ feature = WebFeature::kCSSSelectorNotWithInvalidList;
+ }
+ context_->Count(feature);
+ failed_parsing_ = true;
+}
+
std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumePseudo(
CSSParserTokenRange& range) {
DCHECK_EQ(range.Peek().GetType(), kColonToken);
@@ -535,8 +571,8 @@ std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumePseudo(
return nullptr;
switch (selector->GetPseudoType()) {
- case CSSSelector::kPseudoMatches: {
- if (!RuntimeEnabledFeatures::CSSMatchesEnabled())
+ case CSSSelector::kPseudoIs: {
+ if (!RuntimeEnabledFeatures::CSSPseudoIsEnabled())
break;
DisallowPseudoElementsScope scope(this);
@@ -549,8 +585,8 @@ std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumePseudo(
selector->SetSelectorList(std::move(selector_list));
return selector;
}
- case CSSSelector::kPseudoIS: {
- if (!RuntimeEnabledFeatures::CSSPseudoISEnabled())
+ case CSSSelector::kPseudoWhere: {
+ if (!RuntimeEnabledFeatures::CSSPseudoWhereEnabled())
break;
DisallowPseudoElementsScope scope(this);
@@ -573,17 +609,23 @@ std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumePseudo(
std::make_unique<CSSSelectorList>();
*selector_list = ConsumeCompoundSelectorList(block);
if (!selector_list->IsValid() || !block.AtEnd() ||
- selector_list->HasPseudoMatches() || selector_list->HasPseudoIS())
+ selector_list->HasPseudoIs() || selector_list->HasPseudoWhere())
return nullptr;
selector->SetSelectorList(std::move(selector_list));
return selector;
}
case CSSSelector::kPseudoNot: {
+ CSSParserTokenRange fallback_block = block;
+
std::unique_ptr<CSSParserSelector> inner_selector =
ConsumeCompoundSelector(block);
block.ConsumeWhitespace();
- if (!inner_selector || !inner_selector->IsSimple() || !block.AtEnd())
+ if (!inner_selector || !inner_selector->IsSimple() ||
+ inner_selector->Relation() != CSSSelector::kSubSelector ||
+ !block.AtEnd()) {
+ CountRejectedNot(fallback_block);
return nullptr;
+ }
Vector<std::unique_ptr<CSSParserSelector>> selector_vector;
selector_vector.push_back(std::move(inner_selector));
selector->AdoptSelectorVector(selector_vector);
@@ -605,8 +647,8 @@ std::unique_ptr<CSSParserSelector> CSSSelectorParser::ConsumePseudo(
ConsumeCompoundSelector(block);
block.ConsumeWhitespace();
if (!inner_selector || !block.AtEnd() ||
- inner_selector->GetPseudoType() == CSSSelector::kPseudoMatches ||
- inner_selector->GetPseudoType() == CSSSelector::kPseudoIS)
+ inner_selector->GetPseudoType() == CSSSelector::kPseudoIs ||
+ inner_selector->GetPseudoType() == CSSSelector::kPseudoWhere)
return nullptr;
Vector<std::unique_ptr<CSSParserSelector>> selector_vector;
selector_vector.push_back(std::move(inner_selector));
@@ -917,14 +959,149 @@ CSSSelectorParser::SplitCompoundAtImplicitShadowCrossingCombinator(
if (!split_after || !split_after->TagHistory())
return compound_selector;
- std::unique_ptr<CSSParserSelector> second_compound =
+ std::unique_ptr<CSSParserSelector> remaining =
split_after->ReleaseTagHistory();
- second_compound->AppendTagHistory(
- second_compound->GetImplicitShadowCombinatorForMatching(),
- std::move(compound_selector));
- return second_compound;
+ CSSSelector::RelationType relation =
+ remaining->GetImplicitShadowCombinatorForMatching();
+ // We might need to split the compound twice since ::placeholder is allowed
+ // after ::slotted and they both need an implicit combinator for matching.
+ remaining =
+ SplitCompoundAtImplicitShadowCrossingCombinator(std::move(remaining));
+ remaining->AppendTagHistory(relation, std::move(compound_selector));
+ return remaining;
+}
+
+namespace {
+
+struct PseudoElementFeatureMapEntry {
+ template <unsigned key_length>
+ PseudoElementFeatureMapEntry(const char (&key)[key_length],
+ WebFeature feature)
+ : key(key),
+ key_length(base::checked_cast<uint16_t>(key_length - 1)),
+ feature(base::checked_cast<uint16_t>(feature)) {}
+ const char* const key;
+ const uint16_t key_length;
+ const uint16_t feature;
+};
+
+WebFeature FeatureForWebKitCustomPseudoElement(const AtomicString& name) {
+ static const PseudoElementFeatureMapEntry feature_table[] = {
+ {"cue", WebFeature::kCSSSelectorCue},
+ {"-internal-media-controls-overlay-cast-button",
+ WebFeature::kCSSSelectorInternalMediaControlsOverlayCastButton},
+ {"-webkit-calendar-picker-indicator",
+ WebFeature::kCSSSelectorWebkitCalendarPickerIndicator},
+ {"-webkit-clear-button", WebFeature::kCSSSelectorWebkitClearButton},
+ {"-webkit-color-swatch", WebFeature::kCSSSelectorWebkitColorSwatch},
+ {"-webkit-color-swatch-wrapper",
+ WebFeature::kCSSSelectorWebkitColorSwatchWrapper},
+ {"-webkit-date-and-time-value",
+ WebFeature::kCSSSelectorWebkitDateAndTimeValue},
+ {"-webkit-datetime-edit", WebFeature::kCSSSelectorWebkitDatetimeEdit},
+ {"-webkit-datetime-edit-ampm-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditAmpmField},
+ {"-webkit-datetime-edit-day-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditDayField},
+ {"-webkit-datetime-edit-fields-wrapper",
+ WebFeature::kCSSSelectorWebkitDatetimeEditFieldsWrapper},
+ {"-webkit-datetime-edit-hour-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditHourField},
+ {"-webkit-datetime-edit-millisecond-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditMillisecondField},
+ {"-webkit-datetime-edit-minute-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditMinuteField},
+ {"-webkit-datetime-edit-month-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditMonthField},
+ {"-webkit-datetime-edit-second-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditSecondField},
+ {"-webkit-datetime-edit-text",
+ WebFeature::kCSSSelectorWebkitDatetimeEditText},
+ {"-webkit-datetime-edit-week-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditWeekField},
+ {"-webkit-datetime-edit-year-field",
+ WebFeature::kCSSSelectorWebkitDatetimeEditYearField},
+ {"-webkit-details-marker", WebFeature::kCSSSelectorWebkitDetailsMarker},
+ {"-webkit-file-upload-button",
+ WebFeature::kCSSSelectorWebkitFileUploadButton},
+ {"-webkit-inner-spin-button",
+ WebFeature::kCSSSelectorWebkitInnerSpinButton},
+ {"-webkit-input-placeholder",
+ WebFeature::kCSSSelectorWebkitInputPlaceholder},
+ {"-webkit-media-controls", WebFeature::kCSSSelectorWebkitMediaControls},
+ {"-webkit-media-controls-current-time-display",
+ WebFeature::kCSSSelectorWebkitMediaControlsCurrentTimeDisplay},
+ {"-webkit-media-controls-enclosure",
+ WebFeature::kCSSSelectorWebkitMediaControlsEnclosure},
+ {"-webkit-media-controls-fullscreen-button",
+ WebFeature::kCSSSelectorWebkitMediaControlsFullscreenButton},
+ {"-webkit-media-controls-mute-button",
+ WebFeature::kCSSSelectorWebkitMediaControlsMuteButton},
+ {"-webkit-media-controls-overlay-enclosure",
+ WebFeature::kCSSSelectorWebkitMediaControlsOverlayEnclosure},
+ {"-webkit-media-controls-overlay-play-button",
+ WebFeature::kCSSSelectorWebkitMediaControlsOverlayPlayButton},
+ {"-webkit-media-controls-panel",
+ WebFeature::kCSSSelectorWebkitMediaControlsPanel},
+ {"-webkit-media-controls-play-button",
+ WebFeature::kCSSSelectorWebkitMediaControlsPlayButton},
+ {"-webkit-media-controls-timeline",
+ WebFeature::kCSSSelectorWebkitMediaControlsTimeline},
+ // Note: This feature is no longer implemented in Blink.
+ {"-webkit-media-controls-timeline-container",
+ WebFeature::kCSSSelectorWebkitMediaControlsTimelineContainer},
+ {"-webkit-media-controls-time-remaining-display",
+ WebFeature::kCSSSelectorWebkitMediaControlsTimeRemainingDisplay},
+ {"-webkit-media-controls-toggle-closed-captions-button",
+ WebFeature::kCSSSelectorWebkitMediaControlsToggleClosedCaptionsButton},
+ {"-webkit-media-controls-volume-slider",
+ WebFeature::kCSSSelectorWebkitMediaControlsVolumeSlider},
+ {"-webkit-media-slider-container",
+ WebFeature::kCSSSelectorWebkitMediaSliderContainer},
+ {"-webkit-media-slider-thumb",
+ WebFeature::kCSSSelectorWebkitMediaSliderThumb},
+ {"-webkit-media-text-track-container",
+ WebFeature::kCSSSelectorWebkitMediaTextTrackContainer},
+ {"-webkit-media-text-track-display",
+ WebFeature::kCSSSelectorWebkitMediaTextTrackDisplay},
+ {"-webkit-media-text-track-region",
+ WebFeature::kCSSSelectorWebkitMediaTextTrackRegion},
+ {"-webkit-media-text-track-region-container",
+ WebFeature::kCSSSelectorWebkitMediaTextTrackRegionContainer},
+ {"-webkit-meter-bar", WebFeature::kCSSSelectorWebkitMeterBar},
+ {"-webkit-meter-even-less-good-value",
+ WebFeature::kCSSSelectorWebkitMeterEvenLessGoodValue},
+ {"-webkit-meter-inner-element",
+ WebFeature::kCSSSelectorWebkitMeterInnerElement},
+ {"-webkit-meter-optimum-value",
+ WebFeature::kCSSSelectorWebkitMeterOptimumValue},
+ {"-webkit-meter-suboptimum-value",
+ WebFeature::kCSSSelectorWebkitMeterSuboptimumValue},
+ {"-webkit-progress-bar", WebFeature::kCSSSelectorWebkitProgressBar},
+ {"-webkit-progress-inner-element",
+ WebFeature::kCSSSelectorWebkitProgressInnerElement},
+ {"-webkit-progress-value", WebFeature::kCSSSelectorWebkitProgressValue},
+ {"-webkit-search-cancel-button",
+ WebFeature::kCSSSelectorWebkitSearchCancelButton},
+ {"-webkit-slider-container",
+ WebFeature::kCSSSelectorWebkitSliderContainer},
+ {"-webkit-slider-runnable-track",
+ WebFeature::kCSSSelectorWebkitSliderRunnableTrack},
+ {"-webkit-slider-thumb", WebFeature::kCSSSelectorWebkitSliderThumb},
+ {"-webkit-textfield-decoration-container",
+ WebFeature::kCSSSelectorWebkitTextfieldDecorationContainer},
+ };
+ // TODO(fs): Could use binary search once there's a less finicky way to
+ // compare (order) String and StringView/non-String.
+ for (const auto& entry : feature_table) {
+ if (name == StringView(entry.key, entry.key_length))
+ return static_cast<WebFeature>(entry.feature);
+ }
+ return WebFeature::kCSSSelectorWebkitUnknownPseudo;
}
+} // namespace
+
void CSSSelectorParser::RecordUsageAndDeprecations(
const CSSSelectorList& selector_list) {
if (!context_->IsUseCounterRecordingEnabled())
@@ -939,9 +1116,9 @@ void CSSSelectorParser::RecordUsageAndDeprecations(
case CSSSelector::kPseudoAny:
feature = WebFeature::kCSSSelectorPseudoAny;
break;
- case CSSSelector::kPseudoMatches:
- DCHECK(RuntimeEnabledFeatures::CSSMatchesEnabled());
- feature = WebFeature::kCSSSelectorPseudoMatches;
+ case CSSSelector::kPseudoIs:
+ DCHECK(RuntimeEnabledFeatures::CSSPseudoIsEnabled());
+ feature = WebFeature::kCSSSelectorPseudoIs;
break;
case CSSSelector::kPseudoFocusVisible:
DCHECK(RuntimeEnabledFeatures::CSSFocusVisibleEnabled());
@@ -958,9 +1135,9 @@ void CSSSelectorParser::RecordUsageAndDeprecations(
case CSSSelector::kPseudoWebkitAnyLink:
feature = WebFeature::kCSSSelectorPseudoWebkitAnyLink;
break;
- case CSSSelector::kPseudoIS:
- DCHECK(RuntimeEnabledFeatures::CSSPseudoISEnabled());
- feature = WebFeature::kCSSSelectorPseudoIS;
+ case CSSSelector::kPseudoWhere:
+ DCHECK(RuntimeEnabledFeatures::CSSPseudoWhereEnabled());
+ feature = WebFeature::kCSSSelectorPseudoWhere;
break;
case CSSSelector::kPseudoUnresolved:
feature = WebFeature::kCSSSelectorPseudoUnresolved;
@@ -991,156 +1168,8 @@ void CSSSelectorParser::RecordUsageAndDeprecations(
feature = WebFeature::kCSSSelectorInternalPseudoListBox;
break;
case CSSSelector::kPseudoWebKitCustomElement:
- if (context_->Mode() != kUASheetMode) {
- if (current->Value() == "cue") {
- feature = WebFeature::kCSSSelectorCue;
- } else if (current->Value() ==
- "-internal-media-controls-overlay-cast-button") {
- feature = WebFeature::
- kCSSSelectorInternalMediaControlsOverlayCastButton;
- } else if (current->Value() ==
- "-webkit-calendar-picker-indicator") {
- feature = WebFeature::kCSSSelectorWebkitCalendarPickerIndicator;
- } else if (current->Value() == "-webkit-clear-button") {
- feature = WebFeature::kCSSSelectorWebkitClearButton;
- } else if (current->Value() == "-webkit-color-swatch") {
- feature = WebFeature::kCSSSelectorWebkitColorSwatch;
- } else if (current->Value() == "-webkit-color-swatch-wrapper") {
- feature = WebFeature::kCSSSelectorWebkitColorSwatchWrapper;
- } else if (current->Value() == "-webkit-date-and-time-value") {
- feature = WebFeature::kCSSSelectorWebkitDateAndTimeValue;
- } else if (current->Value() == "-webkit-datetime-edit") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEdit;
- } else if (current->Value() == "-webkit-datetime-edit-ampm-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditAmpmField;
- } else if (current->Value() == "-webkit-datetime-edit-day-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditDayField;
- } else if (current->Value() ==
- "-webkit-datetime-edit-fields-wrapper") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditFieldsWrapper;
- } else if (current->Value() == "-webkit-datetime-edit-hour-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditHourField;
- } else if (current->Value() ==
- "-webkit-datetime-edit-millisecond-field") {
- feature =
- WebFeature::kCSSSelectorWebkitDatetimeEditMillisecondField;
- } else if (current->Value() ==
- "-webkit-datetime-edit-minute-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditMinuteField;
- } else if (current->Value() ==
- "-webkit-datetime-edit-month-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditMonthField;
- } else if (current->Value() ==
- "-webkit-datetime-edit-second-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditSecondField;
- } else if (current->Value() == "-webkit-datetime-edit-text") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditText;
- } else if (current->Value() == "-webkit-datetime-edit-week-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditWeekField;
- } else if (current->Value() == "-webkit-datetime-edit-year-field") {
- feature = WebFeature::kCSSSelectorWebkitDatetimeEditYearField;
- } else if (current->Value() == "-webkit-details-marker") {
- feature = WebFeature::kCSSSelectorWebkitDetailsMarker;
- } else if (current->Value() == "-webkit-file-upload-button") {
- feature = WebFeature::kCSSSelectorWebkitFileUploadButton;
- } else if (current->Value() == "-webkit-inner-spin-button") {
- feature = WebFeature::kCSSSelectorWebkitInnerSpinButton;
- } else if (current->Value() == "-webkit-input-placeholder") {
- feature = WebFeature::kCSSSelectorWebkitInputPlaceholder;
- } else if (current->Value() == "-webkit-media-controls") {
- feature = WebFeature::kCSSSelectorWebkitMediaControls;
- } else if (current->Value() ==
- "-webkit-media-controls-current-time-display") {
- feature =
- WebFeature::kCSSSelectorWebkitMediaControlsCurrentTimeDisplay;
- } else if (current->Value() == "-webkit-media-controls-enclosure") {
- feature = WebFeature::kCSSSelectorWebkitMediaControlsEnclosure;
- } else if (current->Value() ==
- "-webkit-media-controls-fullscreen-button") {
- feature =
- WebFeature::kCSSSelectorWebkitMediaControlsFullscreenButton;
- } else if (current->Value() ==
- "-webkit-media-controls-mute-button") {
- feature = WebFeature::kCSSSelectorWebkitMediaControlsMuteButton;
- } else if (current->Value() ==
- "-webkit-media-controls-overlay-enclosure") {
- feature =
- WebFeature::kCSSSelectorWebkitMediaControlsOverlayEnclosure;
- } else if (current->Value() ==
- "-webkit-media-controls-overlay-play-button") {
- feature =
- WebFeature::kCSSSelectorWebkitMediaControlsOverlayPlayButton;
- } else if (current->Value() == "-webkit-media-controls-panel") {
- feature = WebFeature::kCSSSelectorWebkitMediaControlsPanel;
- } else if (current->Value() ==
- "-webkit-media-controls-play-button") {
- feature = WebFeature::kCSSSelectorWebkitMediaControlsPlayButton;
- } else if (current->Value() == "-webkit-media-controls-timeline") {
- feature = WebFeature::kCSSSelectorWebkitMediaControlsTimeline;
- } else if (current->Value() ==
- "-webkit-media-controls-timeline-container") {
- // Note: This feature is no longer implemented in Blink.
- feature =
- WebFeature::kCSSSelectorWebkitMediaControlsTimelineContainer;
- } else if (current->Value() ==
- "-webkit-media-controls-time-remaining-display") {
- feature = WebFeature::
- kCSSSelectorWebkitMediaControlsTimeRemainingDisplay;
- } else if (current->Value() ==
- "-webkit-media-controls-toggle-closed-captions-button") {
- feature = WebFeature::
- kCSSSelectorWebkitMediaControlsToggleClosedCaptionsButton;
- } else if (current->Value() ==
- "-webkit-media-controls-volume-slider") {
- feature = WebFeature::kCSSSelectorWebkitMediaControlsVolumeSlider;
- } else if (current->Value() == "-webkit-media-slider-container") {
- feature = WebFeature::kCSSSelectorWebkitMediaSliderContainer;
- } else if (current->Value() == "-webkit-media-slider-thumb") {
- feature = WebFeature::kCSSSelectorWebkitMediaSliderThumb;
- } else if (current->Value() ==
- "-webkit-media-text-track-container") {
- feature = WebFeature::kCSSSelectorWebkitMediaTextTrackContainer;
- } else if (current->Value() == "-webkit-media-text-track-display") {
- feature = WebFeature::kCSSSelectorWebkitMediaTextTrackDisplay;
- } else if (current->Value() == "-webkit-media-text-track-region") {
- feature = WebFeature::kCSSSelectorWebkitMediaTextTrackRegion;
- } else if (current->Value() ==
- "-webkit-media-text-track-region-container") {
- feature =
- WebFeature::kCSSSelectorWebkitMediaTextTrackRegionContainer;
- } else if (current->Value() == "-webkit-meter-bar") {
- feature = WebFeature::kCSSSelectorWebkitMeterBar;
- } else if (current->Value() ==
- "-webkit-meter-even-less-good-value") {
- feature = WebFeature::kCSSSelectorWebkitMeterEvenLessGoodValue;
- } else if (current->Value() == "-webkit-meter-inner-element") {
- feature = WebFeature::kCSSSelectorWebkitMeterInnerElement;
- } else if (current->Value() == "-webkit-meter-optimum-value") {
- feature = WebFeature::kCSSSelectorWebkitMeterOptimumValue;
- } else if (current->Value() == "-webkit-meter-suboptimum-value") {
- feature = WebFeature::kCSSSelectorWebkitMeterSuboptimumValue;
- } else if (current->Value() == "-webkit-progress-bar") {
- feature = WebFeature::kCSSSelectorWebkitProgressBar;
- } else if (current->Value() == "-webkit-progress-inner-element") {
- feature = WebFeature::kCSSSelectorWebkitProgressInnerElement;
- } else if (current->Value() == "-webkit-progress-value") {
- feature = WebFeature::kCSSSelectorWebkitProgressValue;
- } else if (current->Value() == "-webkit-search-cancel-button") {
- feature = WebFeature::kCSSSelectorWebkitSearchCancelButton;
- } else if (current->Value() == "-webkit-slider-container") {
- feature = WebFeature::kCSSSelectorWebkitSliderContainer;
- } else if (current->Value() == "-webkit-slider-runnable-track") {
- feature = WebFeature::kCSSSelectorWebkitSliderRunnableTrack;
- } else if (current->Value() == "-webkit-slider-thumb") {
- feature = WebFeature::kCSSSelectorWebkitSliderThumb;
- } else if (current->Value() ==
- "-webkit-textfield-decoration-container") {
- feature =
- WebFeature::kCSSSelectorWebkitTextfieldDecorationContainer;
- } else {
- feature = WebFeature::kCSSSelectorWebkitUnknownPseudo;
- }
- }
+ if (context_->Mode() != kUASheetMode)
+ feature = FeatureForWebKitCustomPseudoElement(current->Value());
break;
case CSSSelector::kPseudoSpatialNavigationFocus:
if (context_->Mode() != kUASheetMode) {
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.h b/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.h
index b1a8442a5ab..f75374c742c 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.h
@@ -80,6 +80,7 @@ class CORE_EXPORT CSSSelectorParser {
SplitCompoundAtImplicitShadowCrossingCombinator(
std::unique_ptr<CSSParserSelector> compound_selector);
void RecordUsageAndDeprecations(const CSSSelectorList&);
+ void CountRejectedNot(CSSParserTokenRange&);
Member<const CSSParserContext> context_;
Member<const StyleSheetContents> style_sheet_;
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc b/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc
index c67ee0f9a91..a795cba47fa 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc
@@ -364,24 +364,24 @@ TEST(CSSSelectorParserTest, InternalPseudo) {
}
}
-TEST(CSSSelectorParserTest, InvalidNestingPseudoMatches) {
- // :matches() is currently not supported within these pseudo classes as they
- // currently do not support complex selector arguments (:matches() does
- // support this and the expansion of :matches() may provide complex selector
+TEST(CSSSelectorParserTest, InvalidNestingPseudoIs) {
+ // :is() is currently not supported within these pseudo classes as they
+ // currently do not support complex selector arguments (:is() does
+ // support this and the expansion of :is() may provide complex selector
// arguments to these pseudo classes). Most of these test cases should
// eventually be removed once they support complex selector arguments.
- const char* test_cases[] = {":-webkit-any(:matches(.a))",
- "::cue(:matches(.a))",
- ":cue(:matches(.a))",
- ":host(:matches(.a))",
- ":host-context(:matches(.a))",
- ":lang(:matches(.a))",
- ":not(:matches(.a))",
- ":nth-child(:matches(.a))",
- ":nth-last-child(:matches(.a))",
- ":nth-last-of-type(:matches(.a))",
- ":nth-of-type(:matches(.a))",
- "::slotted(:matches(.a))"};
+ const char* test_cases[] = {":-webkit-any(:is(.a))",
+ "::cue(:is(.a))",
+ ":cue(:is(.a))",
+ ":host(:is(.a))",
+ ":host-context(:is(.a))",
+ ":lang(:is(.a))",
+ ":not(:is(.a))",
+ ":nth-child(:is(.a))",
+ ":nth-last-child(:is(.a))",
+ ":nth-last-of-type(:is(.a))",
+ ":nth-of-type(:is(.a))",
+ "::slotted(:is(.a))"};
CSSParserContext* context = CSSParserContext::Create(
kHTMLStandardMode, SecureContextMode::kInsecureContext);
@@ -398,30 +398,30 @@ TEST(CSSSelectorParserTest, InvalidNestingPseudoMatches) {
}
}
-TEST(CSSSelectorParserTest, InvalidPseudoMatchesArguments) {
- // Pseudo-elements are not valid within :matches() as per the spec:
+TEST(CSSSelectorParserTest, InvalidPseudoIsArguments) {
+ // Pseudo-elements are not valid within :is() as per the spec:
// https://drafts.csswg.org/selectors-4/#matches
- const char* test_cases[] = {":matches(::-webkit-progress-bar)",
- ":matches(::-webkit-progress-value)",
- ":matches(::-webkit-slider-runnable-track)",
- ":matches(::-webkit-slider-thumb)",
- ":matches(::after)",
- ":matches(::backdrop)",
- ":matches(::before)",
- ":matches(::cue)",
- ":matches(::first-letter)",
- ":matches(::first-line)",
- ":matches(::grammar-error)",
- ":matches(::marker)",
- ":matches(::placeholder)",
- ":matches(::selection)",
- ":matches(::slotted)",
- ":matches(::spelling-error)",
- ":matches(:after)",
- ":matches(:before)",
- ":matches(:cue)",
- ":matches(:first-letter)",
- ":matches(:first-line)"};
+ const char* test_cases[] = {":is(::-webkit-progress-bar)",
+ ":is(::-webkit-progress-value)",
+ ":is(::-webkit-slider-runnable-track)",
+ ":is(::-webkit-slider-thumb)",
+ ":is(::after)",
+ ":is(::backdrop)",
+ ":is(::before)",
+ ":is(::cue)",
+ ":is(::first-letter)",
+ ":is(::first-line)",
+ ":is(::grammar-error)",
+ ":is(::marker)",
+ ":is(::placeholder)",
+ ":is(::selection)",
+ ":is(::slotted)",
+ ":is(::spelling-error)",
+ ":is(:after)",
+ ":is(:before)",
+ ":is(:cue)",
+ ":is(:first-letter)",
+ ":is(:first-line)"};
CSSParserContext* context = CSSParserContext::Create(
kHTMLStandardMode, SecureContextMode::kInsecureContext);
@@ -438,24 +438,24 @@ TEST(CSSSelectorParserTest, InvalidPseudoMatchesArguments) {
}
}
-TEST(CSSSelectorParserTest, InvalidNestingPseudoIS) {
- // :is() is currently not supported within these pseudo classes as they
- // currently do not support complex selector arguments (:is() does support
- // this and the expansion of :is() may provide complex selector arguments to
- // these pseudo classes). Most of these test cases should eventually be
+TEST(CSSSelectorParserTest, InvalidNestingPseudoWhere) {
+ // :where() is currently not supported within these pseudo classes as they
+ // currently do not support complex selector arguments (:where() does support
+ // this and the expansion of :where() may provide complex selector arguments
+ // to these pseudo classes). Most of these test cases should eventually be
// removed once they support complex selector arguments.
- const char* test_cases[] = {":-webkit-any(:is(.a))",
- "::cue(:is(.a))",
- ":cue(:is(.a))",
- ":host(:is(.a))",
- ":host-context(:is(.a))",
- ":lang(:is(.a))",
- ":not(:is(.a))",
- ":nth-child(:is(.a))",
- ":nth-last-child(:is(.a))",
- ":nth-last-of-type(:is(.a))",
- ":nth-of-type(:is(.a))",
- "::slotted(:is(.a))"};
+ const char* test_cases[] = {":-webkit-any(:where(.a))",
+ "::cue(:where(.a))",
+ ":cue(:where(.a))",
+ ":host(:where(.a))",
+ ":host-context(:where(.a))",
+ ":lang(:where(.a))",
+ ":not(:where(.a))",
+ ":nth-child(:where(.a))",
+ ":nth-last-child(:where(.a))",
+ ":nth-last-of-type(:where(.a))",
+ ":nth-of-type(:where(.a))",
+ "::slotted(:where(.a))"};
CSSParserContext* context = CSSParserContext::Create(
kHTMLStandardMode, SecureContextMode::kInsecureContext);
@@ -700,4 +700,159 @@ TEST(CSSSelectorParserTest, UseCountShadowPseudo) {
WebFeature::kCSSSelectorWebkitUnknownPseudo);
}
+TEST(CSSSelectorParserTest, ImplicitShadowCrossingCombinators) {
+ struct ShadowCombinatorTest {
+ const char* input;
+ std::vector<std::pair<AtomicString, CSSSelector::RelationType>> expectation;
+ };
+
+ const ShadowCombinatorTest test_cases[] = {
+ {
+ "*::placeholder",
+ {
+ {"placeholder", CSSSelector::kShadowPseudo},
+ {g_null_atom, CSSSelector::kSubSelector},
+ },
+ },
+ {
+ "div::slotted(*)",
+ {
+ {"slotted", CSSSelector::kShadowSlot},
+ {"div", CSSSelector::kSubSelector},
+ },
+ },
+ {
+ "::slotted(*)::placeholder",
+ {
+ {"placeholder", CSSSelector::kShadowPseudo},
+ {"slotted", CSSSelector::kShadowSlot},
+ {g_null_atom, CSSSelector::kSubSelector},
+ },
+ },
+ {
+ "span::part(my-part)",
+ {
+ {"part", CSSSelector::kShadowPart},
+ {"span", CSSSelector::kSubSelector},
+ },
+ },
+ {
+ "video::-webkit-media-controls",
+ {
+ {"-webkit-media-controls", CSSSelector::kShadowPseudo},
+ {"video", CSSSelector::kSubSelector},
+ },
+ },
+ };
+
+ CSSParserContext* context = CSSParserContext::Create(
+ kHTMLStandardMode, SecureContextMode::kInsecureContext);
+ StyleSheetContents* sheet = StyleSheetContents::Create(context);
+
+ for (auto test_case : test_cases) {
+ SCOPED_TRACE(test_case.input);
+ CSSTokenizer tokenizer(test_case.input);
+ const auto tokens = tokenizer.TokenizeToEOF();
+ CSSParserTokenRange range(tokens);
+ CSSSelectorList list =
+ CSSSelectorParser::ParseSelector(range, context, sheet);
+ EXPECT_TRUE(list.IsValid());
+ const CSSSelector* selector = list.First();
+ for (auto sub_expectation : test_case.expectation) {
+ ASSERT_TRUE(selector);
+ AtomicString selector_value = selector->Match() == CSSSelector::kTag
+ ? selector->TagQName().LocalName()
+ : selector->Value();
+ EXPECT_EQ(sub_expectation.first, selector_value);
+ EXPECT_EQ(sub_expectation.second, selector->Relation());
+ selector = selector->TagHistory();
+ }
+ EXPECT_FALSE(selector);
+ }
+}
+
+TEST(CSSSelectorParserTest, UseCountRejectedNot) {
+ auto ExpectCount = [](const char* selector, WebFeature feature) {
+ std::unique_ptr<DummyPageHolder> dummy_holder =
+ DummyPageHolder::Create(IntSize(500, 500));
+ Document* doc = &dummy_holder->GetDocument();
+ Page::InsertOrdinaryPageForTesting(&dummy_holder->GetPage());
+ CSSParserContext* context = CSSParserContext::Create(
+ kHTMLStandardMode, SecureContextMode::kSecureContext,
+ CSSParserContext::kLiveProfile, doc);
+ StyleSheetContents* sheet = StyleSheetContents::Create(context);
+ EXPECT_FALSE(UseCounter::IsCounted(*doc, feature));
+
+ CSSTokenizer tokenizer(selector);
+ const auto tokens = tokenizer.TokenizeToEOF();
+ CSSParserTokenRange range(tokens);
+ CSSSelectorParser::ParseSelector(range, context, sheet);
+
+ bool result = UseCounter::IsCounted(*doc, feature);
+ EXPECT_TRUE(result);
+ };
+
+ ExpectCount(":not(:nonsense :gibberish)",
+ WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(:nonsense :gibberish, .a)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not()", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(,)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(,,)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(* .a)", WebFeature::kCSSSelectorNotWithValidList);
+ ExpectCount(":not(:nonsense)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(* * .previouslyFailed)",
+ WebFeature::kCSSSelectorNotWithValidList);
+ ExpectCount(":not(* :nonsense)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(:nonsense *)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(*,)", WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(*,,)", WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(:nonsense ,)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(:nonsense,,)", WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(*, *)", WebFeature::kCSSSelectorNotWithValidList);
+ ExpectCount(":not(*, :nonsense)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(* , * *)", WebFeature::kCSSSelectorNotWithValidList);
+ ExpectCount(":not(*, * :nonsense)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(:nonsense,*)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(:nonsense , :nonsense)",
+ WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(:nonsense, * *)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(:nonsense, * :nonsense )",
+ WebFeature::kCSSSelectorNotWithInvalidList);
+ ExpectCount(":not(*, :not(* * :nonsense))",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(:not(* * :nonsense) , *)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+ ExpectCount(":not(.a || :nonsense, *)",
+ WebFeature::kCSSSelectorNotWithPartiallyValidList);
+}
+
+TEST(CSSSelectorParserTest, SimpleNotNeverCounted) {
+ // :not with a simple selector from CSS Selectors 3 is not counted.
+ std::unique_ptr<DummyPageHolder> dummy_holder =
+ DummyPageHolder::Create(IntSize(500, 500));
+ Document* doc = &dummy_holder->GetDocument();
+ Page::InsertOrdinaryPageForTesting(&dummy_holder->GetPage());
+ CSSParserContext* context = CSSParserContext::Create(
+ kHTMLStandardMode, SecureContextMode::kSecureContext,
+ CSSParserContext::kLiveProfile, doc);
+ StyleSheetContents* sheet = StyleSheetContents::Create(context);
+
+ CSSTokenizer tokenizer(":not(*)");
+ const auto tokens = tokenizer.TokenizeToEOF();
+ CSSParserTokenRange range(tokens);
+ CSSSelectorParser::ParseSelector(range, context, sheet);
+
+ EXPECT_FALSE(
+ UseCounter::IsCounted(*doc, WebFeature::kCSSSelectorNotWithValidList));
+ EXPECT_FALSE(
+ UseCounter::IsCounted(*doc, WebFeature::kCSSSelectorNotWithInvalidList));
+ EXPECT_FALSE(UseCounter::IsCounted(
+ *doc, WebFeature::kCSSSelectorNotWithPartiallyValidList));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.cc b/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.cc
index 94e41a16dfb..0ae81f1bf23 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h"
namespace blink {
-#include "third_party/blink/renderer/core/css_tokenizer_codepoints.cc"
+#include "third_party/blink/renderer/core/css/css_tokenizer_codepoints.cc"
}
#include "third_party/blink/renderer/core/css/parser/css_parser_idioms.h"
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_variable_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/css_variable_parser.cc
index 3c931168a48..0ebe89db420 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_variable_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_variable_parser.cc
@@ -36,8 +36,6 @@ bool ClassifyBlock(CSSParserTokenRange range,
has_references = true;
continue;
case CSSValueEnv:
- if (!RuntimeEnabledFeatures::CSSEnvironmentVariablesEnabled())
- return false;
if (!IsValidEnvVariableReference(range.ConsumeBlock(),
skip_variables))
return false; // Invalid reference.
diff --git a/chromium/third_party/blink/renderer/core/css/parser/font_variant_east_asian_parser.h b/chromium/third_party/blink/renderer/core/css/parser/font_variant_east_asian_parser.h
index 4877ca89196..bc06cea9d18 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/font_variant_east_asian_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/font_variant_east_asian_parser.h
@@ -33,18 +33,20 @@ class FontVariantEastAsianParser {
case CSSValueTraditional:
if (east_asian_form_value_)
return ParseResult::kDisallowedValue;
- east_asian_form_value_ = CSSPropertyParserHelpers::ConsumeIdent(range);
+ east_asian_form_value_ =
+ css_property_parser_helpers::ConsumeIdent(range);
return ParseResult::kConsumedValue;
case CSSValueFullWidth:
case CSSValueProportionalWidth:
if (east_asian_width_value_)
return ParseResult::kDisallowedValue;
- east_asian_width_value_ = CSSPropertyParserHelpers::ConsumeIdent(range);
+ east_asian_width_value_ =
+ css_property_parser_helpers::ConsumeIdent(range);
return ParseResult::kConsumedValue;
case CSSValueRuby:
if (ruby_value_)
return ParseResult::kDisallowedValue;
- ruby_value_ = CSSPropertyParserHelpers::ConsumeIdent(range);
+ ruby_value_ = css_property_parser_helpers::ConsumeIdent(range);
return ParseResult::kConsumedValue;
default:
return ParseResult::kUnknownValue;
diff --git a/chromium/third_party/blink/renderer/core/css/parser/font_variant_ligatures_parser.h b/chromium/third_party/blink/renderer/core/css/parser/font_variant_ligatures_parser.h
index 14495b685bb..71baf46c3df 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/font_variant_ligatures_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/font_variant_ligatures_parser.h
@@ -55,7 +55,7 @@ class FontVariantLigaturesParser {
default:
return ParseResult::kUnknownValue;
}
- result_->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ result_->Append(*css_property_parser_helpers::ConsumeIdent(range));
return ParseResult::kConsumedValue;
}
diff --git a/chromium/third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h b/chromium/third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h
index 3b39eb0f7ec..f0721c58af6 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h
@@ -59,7 +59,7 @@ class FontVariantNumericParser {
default:
return ParseResult::kUnknownValue;
}
- result_->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ result_->Append(*css_property_parser_helpers::ConsumeIdent(range));
return ParseResult::kConsumedValue;
}
diff --git a/chromium/third_party/blink/renderer/core/css/parser/media_query_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/media_query_parser.cc
index 9539cc29415..0dcf599e730 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/media_query_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/media_query_parser.cc
@@ -283,17 +283,17 @@ scoped_refptr<MediaQuerySet> MediaQueryParser::ParseImpl(
bool MediaQueryParser::IsMediaFeatureAllowedInMode(
const String& media_feature) const {
return mode_ == kUASheetMode ||
- media_feature != MediaFeatureNames::immersiveMediaFeature;
+ media_feature != media_feature_names::kImmersiveMediaFeature;
}
MediaQueryData::MediaQueryData()
: restrictor_(MediaQuery::kNone),
- media_type_(MediaTypeNames::all),
+ media_type_(media_type_names::kAll),
media_type_set_(false) {}
void MediaQueryData::Clear() {
restrictor_ = MediaQuery::kNone;
- media_type_ = MediaTypeNames::all;
+ media_type_ = media_type_names::kAll;
media_type_set_ = false;
media_feature_ = String();
expressions_.clear();
diff --git a/chromium/third_party/blink/renderer/core/css/parser/sizes_attribute_parser_test.cc b/chromium/third_party/blink/renderer/core/css/parser/sizes_attribute_parser_test.cc
index d35078dc288..ef509ed1119 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/sizes_attribute_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/sizes_attribute_parser_test.cc
@@ -85,7 +85,7 @@ TEST(SizesAttributeParserTest, Basic) {
data.primary_pointer_type = kPointerTypeFine;
data.default_font_size = 16;
data.three_d_enabled = true;
- data.media_type = MediaTypeNames::screen;
+ data.media_type = media_type_names::kScreen;
data.strict_mode = true;
data.display_mode = kWebDisplayModeBrowser;
MediaValues* media_values = MediaValuesCached::Create(data);
@@ -166,7 +166,7 @@ TEST(SizesAttributeParserTest, FloatViewportWidth) {
data.primary_pointer_type = kPointerTypeFine;
data.default_font_size = 16;
data.three_d_enabled = true;
- data.media_type = MediaTypeNames::screen;
+ data.media_type = media_type_names::kScreen;
data.strict_mode = true;
data.display_mode = kWebDisplayModeBrowser;
MediaValues* media_values = MediaValuesCached::Create(data);
diff --git a/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser_test.cc b/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser_test.cc
index 240981082f4..56b3d919b0d 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser_test.cc
@@ -119,7 +119,7 @@ TEST(SizesCalcParserTest, Basic) {
data.primary_pointer_type = kPointerTypeFine;
data.default_font_size = 16;
data.three_d_enabled = true;
- data.media_type = MediaTypeNames::screen;
+ data.media_type = media_type_names::kScreen;
data.strict_mode = true;
data.display_mode = kWebDisplayModeBrowser;
MediaValues* media_values = MediaValuesCached::Create(data);
diff --git a/chromium/third_party/blink/renderer/core/css/properties/README.md b/chromium/third_party/blink/renderer/core/css/properties/README.md
index c2e56dd4eb4..4083ed4a7ef 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/README.md
+++ b/chromium/third_party/blink/renderer/core/css/properties/README.md
@@ -89,7 +89,7 @@ headers are in this directory.
2. Implement the required methods on the property class.
3. If logic is required by multiple property classes you may need to create a
new Utils file. These utils methods are grouped by pipeline function (e.g.
- [CSSParsingUtils](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/css/properties/css_parsing_utils.h)).
+ [css_parsing_utils](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/css/properties/css_parsing_utils.h)).
4. Add the new property to `core/css/css_properties.json5`. Ensure that you
include all the methods implemented on the property in the
'property_methods' flag so that the header file is generated correctly (see
diff --git a/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.cc b/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.cc
index 566b70cc563..73b8a08f7a3 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.cc
@@ -709,17 +709,17 @@ CSSValue* ComputedStyleUtils::ValueForLineHeight(const ComputedStyle& style) {
}
CSSValueID IdentifierForFamily(const AtomicString& family) {
- if (family == FontFamilyNames::webkit_cursive)
+ if (family == font_family_names::kWebkitCursive)
return CSSValueCursive;
- if (family == FontFamilyNames::webkit_fantasy)
+ if (family == font_family_names::kWebkitFantasy)
return CSSValueFantasy;
- if (family == FontFamilyNames::webkit_monospace)
+ if (family == font_family_names::kWebkitMonospace)
return CSSValueMonospace;
- if (family == FontFamilyNames::webkit_pictograph)
+ if (family == font_family_names::kWebkitPictograph)
return CSSValueWebkitPictograph;
- if (family == FontFamilyNames::webkit_sans_serif)
+ if (family == font_family_names::kWebkitSansSerif)
return CSSValueSansSerif;
- if (family == FontFamilyNames::webkit_serif)
+ if (family == font_family_names::kWebkitSerif)
return CSSValueSerif;
return CSSValueInvalid;
}
@@ -1856,27 +1856,6 @@ CSSValue* ComputedStyleUtils::StrokeDashArrayToCSSValueList(
return list;
}
-CSSValue* ComputedStyleUtils::PaintOrderToCSSValueList(
- const SVGComputedStyle& svg_style) {
- CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- for (int i = 0; i < 3; i++) {
- EPaintOrderType paint_order_type = svg_style.PaintOrderType(i);
- switch (paint_order_type) {
- case PT_FILL:
- case PT_STROKE:
- case PT_MARKERS:
- list->Append(*CSSIdentifierValue::Create(paint_order_type));
- break;
- case PT_NONE:
- default:
- NOTREACHED();
- break;
- }
- }
-
- return list;
-}
-
CSSValue* ComputedStyleUtils::AdjustSVGPaintForCurrentColor(
const SVGPaint& paint,
const Color& current_color) {
@@ -2309,30 +2288,30 @@ CSSValue* ComputedStyleUtils::ValuesForFontVariantProperty(
// Returns up to two values for 'scroll-customization' property. The values
// correspond to the customization values for 'x' and 'y' axes.
CSSValue* ComputedStyleUtils::ScrollCustomizationFlagsToCSSValue(
- ScrollCustomization::ScrollDirection scroll_customization) {
+ scroll_customization::ScrollDirection scroll_customization) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- if (scroll_customization == ScrollCustomization::kScrollDirectionAuto) {
+ if (scroll_customization == scroll_customization::kScrollDirectionAuto) {
list->Append(*CSSIdentifierValue::Create(CSSValueAuto));
} else if (scroll_customization ==
- ScrollCustomization::kScrollDirectionNone) {
+ scroll_customization::kScrollDirectionNone) {
list->Append(*CSSIdentifierValue::Create(CSSValueNone));
} else {
- if ((scroll_customization & ScrollCustomization::kScrollDirectionPanX) ==
- ScrollCustomization::kScrollDirectionPanX)
+ if ((scroll_customization & scroll_customization::kScrollDirectionPanX) ==
+ scroll_customization::kScrollDirectionPanX)
list->Append(*CSSIdentifierValue::Create(CSSValuePanX));
else if (scroll_customization &
- ScrollCustomization::kScrollDirectionPanLeft)
+ scroll_customization::kScrollDirectionPanLeft)
list->Append(*CSSIdentifierValue::Create(CSSValuePanLeft));
else if (scroll_customization &
- ScrollCustomization::kScrollDirectionPanRight)
+ scroll_customization::kScrollDirectionPanRight)
list->Append(*CSSIdentifierValue::Create(CSSValuePanRight));
- if ((scroll_customization & ScrollCustomization::kScrollDirectionPanY) ==
- ScrollCustomization::kScrollDirectionPanY)
+ if ((scroll_customization & scroll_customization::kScrollDirectionPanY) ==
+ scroll_customization::kScrollDirectionPanY)
list->Append(*CSSIdentifierValue::Create(CSSValuePanY));
- else if (scroll_customization & ScrollCustomization::kScrollDirectionPanUp)
+ else if (scroll_customization & scroll_customization::kScrollDirectionPanUp)
list->Append(*CSSIdentifierValue::Create(CSSValuePanUp));
else if (scroll_customization &
- ScrollCustomization::kScrollDirectionPanDown)
+ scroll_customization::kScrollDirectionPanDown)
list->Append(*CSSIdentifierValue::Create(CSSValuePanDown));
}
diff --git a/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.h b/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.h
index 2ec83b6ae44..b4133eeac32 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.h
@@ -143,7 +143,6 @@ class ComputedStyleUtils {
static CSSValueList* ValueForBorderRadiusShorthand(const ComputedStyle&);
static CSSValue* StrokeDashArrayToCSSValueList(const SVGDashArray&,
const ComputedStyle&);
- static CSSValue* PaintOrderToCSSValueList(const SVGComputedStyle&);
static CSSValue* AdjustSVGPaintForCurrentColor(const SVGPaint&, const Color&);
static CSSValue* ValueForSVGResource(const StyleSVGResource*);
static CSSValue* ValueForShadowData(const ShadowData&,
@@ -189,7 +188,7 @@ class ComputedStyleUtils {
Node*,
bool allow_visited_style);
static CSSValue* ScrollCustomizationFlagsToCSSValue(
- ScrollCustomization::ScrollDirection);
+ scroll_customization::ScrollDirection);
static CSSValue* ValueForGapLength(const GapLength&, const ComputedStyle&);
};
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc b/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
index b686b57582a..b7c96bbf4ae 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/core/css/css_initial_value.h"
#include "third_party/blink/renderer/core/css/css_path_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_ray_value.h"
#include "third_party/blink/renderer/core/css/css_shadow_value.h"
#include "third_party/blink/renderer/core/css/css_timing_function_value.h"
@@ -34,7 +35,6 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/properties/longhand.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
@@ -42,7 +42,7 @@
#include "third_party/blink/renderer/core/svg/svg_parsing_error.h"
#include "third_party/blink/renderer/core/svg/svg_path_utilities.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -50,43 +50,43 @@ namespace blink {
using namespace cssvalue;
-namespace CSSParsingUtils {
+namespace css_parsing_utils {
namespace {
bool IsLeftOrRightKeyword(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<CSSValueLeft, CSSValueRight>(
+ return css_property_parser_helpers::IdentMatches<CSSValueLeft, CSSValueRight>(
id);
}
bool IsAuto(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<CSSValueAuto>(id);
+ return css_property_parser_helpers::IdentMatches<CSSValueAuto>(id);
}
bool IsNormalOrStretch(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<CSSValueNormal,
- CSSValueStretch>(id);
+ return css_property_parser_helpers::IdentMatches<CSSValueNormal,
+ CSSValueStretch>(id);
}
bool IsContentDistributionKeyword(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<
+ return css_property_parser_helpers::IdentMatches<
CSSValueSpaceBetween, CSSValueSpaceAround, CSSValueSpaceEvenly,
CSSValueStretch>(id);
}
bool IsOverflowKeyword(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<CSSValueUnsafe, CSSValueSafe>(
- id);
+ return css_property_parser_helpers::IdentMatches<CSSValueUnsafe,
+ CSSValueSafe>(id);
}
CSSIdentifierValue* ConsumeOverflowPositionKeyword(CSSParserTokenRange& range) {
return IsOverflowKeyword(range.Peek().Id())
- ? CSSPropertyParserHelpers::ConsumeIdent(range)
+ ? css_property_parser_helpers::ConsumeIdent(range)
: nullptr;
}
bool IsBaselineKeyword(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<CSSValueFirst, CSSValueLast,
- CSSValueBaseline>(id);
+ return css_property_parser_helpers::IdentMatches<CSSValueFirst, CSSValueLast,
+ CSSValueBaseline>(id);
}
CSSValueID GetBaselineKeyword(CSSValue& value) {
@@ -104,10 +104,10 @@ CSSValueID GetBaselineKeyword(CSSValue& value) {
CSSValue* ConsumeBaselineKeyword(CSSParserTokenRange& range) {
CSSIdentifierValue* preference =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueFirst, CSSValueLast>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueFirst, CSSValueLast>(
range);
CSSIdentifierValue* baseline =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueBaseline>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueBaseline>(range);
if (!baseline)
return nullptr;
if (preference && preference->GetValueID() == CSSValueLast) {
@@ -121,16 +121,16 @@ CSSValue* ConsumeSteps(CSSParserTokenRange& range) {
DCHECK_EQ(range.Peek().FunctionId(), CSSValueSteps);
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
CSSPrimitiveValue* steps =
- CSSPropertyParserHelpers::ConsumePositiveInteger(args);
+ css_property_parser_helpers::ConsumePositiveInteger(args);
if (!steps)
return nullptr;
StepsTimingFunction::StepPosition position =
StepsTimingFunction::StepPosition::END;
- if (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ if (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
switch (args.ConsumeIncludingWhitespace().Id()) {
case CSSValueMiddle:
if (!RuntimeEnabledFeatures::WebAnimationsAPIEnabled())
@@ -159,10 +159,10 @@ CSSValue* ConsumeFrames(CSSParserTokenRange& range) {
DCHECK_EQ(range.Peek().FunctionId(), CSSValueFrames);
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
CSSPrimitiveValue* frames =
- CSSPropertyParserHelpers::ConsumePositiveInteger(args);
+ css_property_parser_helpers::ConsumePositiveInteger(args);
if (!frames)
return nullptr;
@@ -181,18 +181,18 @@ CSSValue* ConsumeCubicBezier(CSSParserTokenRange& range) {
DCHECK_EQ(range.Peek().FunctionId(), CSSValueCubicBezier);
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
double x1, y1, x2, y2;
- if (CSSPropertyParserHelpers::ConsumeNumberRaw(args, x1) && x1 >= 0 &&
+ if (css_property_parser_helpers::ConsumeNumberRaw(args, x1) && x1 >= 0 &&
x1 <= 1 &&
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) &&
- CSSPropertyParserHelpers::ConsumeNumberRaw(args, y1) &&
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) &&
- CSSPropertyParserHelpers::ConsumeNumberRaw(args, x2) && x2 >= 0 &&
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args) &&
+ css_property_parser_helpers::ConsumeNumberRaw(args, y1) &&
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args) &&
+ css_property_parser_helpers::ConsumeNumberRaw(args, x2) && x2 >= 0 &&
x2 <= 1 &&
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) &&
- CSSPropertyParserHelpers::ConsumeNumberRaw(args, y2) && args.AtEnd()) {
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args) &&
+ css_property_parser_helpers::ConsumeNumberRaw(args, y2) && args.AtEnd()) {
range = range_copy;
return CSSCubicBezierTimingFunctionValue::Create(x1, y1, x2, y2);
}
@@ -202,13 +202,13 @@ CSSValue* ConsumeCubicBezier(CSSParserTokenRange& range) {
CSSIdentifierValue* ConsumeBorderImageRepeatKeyword(
CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueStretch, CSSValueRepeat,
- CSSValueSpace, CSSValueRound>(
- range);
+ return css_property_parser_helpers::ConsumeIdent<
+ CSSValueStretch, CSSValueRepeat, CSSValueSpace, CSSValueRound>(range);
}
bool ConsumeCSSValueId(CSSParserTokenRange& range, CSSValueID& value) {
- CSSIdentifierValue* keyword = CSSPropertyParserHelpers::ConsumeIdent(range);
+ CSSIdentifierValue* keyword =
+ css_property_parser_helpers::ConsumeIdent(range);
if (!keyword || !range.AtEnd())
return false;
value = keyword->GetValueID();
@@ -217,11 +217,11 @@ bool ConsumeCSSValueId(CSSParserTokenRange& range, CSSValueID& value) {
CSSValue* ConsumeShapeRadius(CSSParserTokenRange& args,
CSSParserMode css_parser_mode) {
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueClosestSide,
- CSSValueFarthestSide>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueClosestSide,
+ CSSValueFarthestSide>(
args.Peek().Id()))
- return CSSPropertyParserHelpers::ConsumeIdent(args);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(args);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
args, css_parser_mode, kValueRangeNonNegative);
}
@@ -233,11 +233,11 @@ CSSBasicShapeCircleValue* ConsumeBasicShapeCircle(
CSSBasicShapeCircleValue* shape = CSSBasicShapeCircleValue::Create();
if (CSSValue* radius = ConsumeShapeRadius(args, context.Mode()))
shape->SetRadius(radius);
- if (CSSPropertyParserHelpers::ConsumeIdent<CSSValueAt>(args)) {
+ if (css_property_parser_helpers::ConsumeIdent<CSSValueAt>(args)) {
CSSValue* center_x = nullptr;
CSSValue* center_y = nullptr;
if (!ConsumePosition(args, context,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid,
+ css_property_parser_helpers::UnitlessQuirk::kForbid,
base::Optional<WebFeature>(), center_x, center_y))
return nullptr;
shape->SetCenterX(center_x);
@@ -261,11 +261,11 @@ CSSBasicShapeEllipseValue* ConsumeBasicShapeEllipse(
feature = WebFeature::kBasicShapeEllipseTwoRadius;
}
}
- if (CSSPropertyParserHelpers::ConsumeIdent<CSSValueAt>(args)) {
+ if (css_property_parser_helpers::ConsumeIdent<CSSValueAt>(args)) {
CSSValue* center_x = nullptr;
CSSValue* center_y = nullptr;
if (!ConsumePosition(args, context,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid,
+ css_property_parser_helpers::UnitlessQuirk::kForbid,
base::Optional<WebFeature>(), center_x, center_y))
return nullptr;
shape->SetCenterX(center_x);
@@ -279,28 +279,29 @@ CSSBasicShapePolygonValue* ConsumeBasicShapePolygon(
CSSParserTokenRange& args,
const CSSParserContext& context) {
CSSBasicShapePolygonValue* shape = CSSBasicShapePolygonValue::Create();
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueEvenodd, CSSValueNonzero>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueEvenodd,
+ CSSValueNonzero>(
args.Peek().Id())) {
shape->SetWindRule(args.ConsumeIncludingWhitespace().Id() == CSSValueEvenodd
? RULE_EVENODD
: RULE_NONZERO);
- if (!CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args))
+ if (!css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args))
return nullptr;
}
do {
CSSPrimitiveValue* x_length =
- CSSPropertyParserHelpers::ConsumeLengthOrPercent(args, context.Mode(),
- kValueRangeAll);
+ css_property_parser_helpers::ConsumeLengthOrPercent(
+ args, context.Mode(), kValueRangeAll);
if (!x_length)
return nullptr;
CSSPrimitiveValue* y_length =
- CSSPropertyParserHelpers::ConsumeLengthOrPercent(args, context.Mode(),
- kValueRangeAll);
+ css_property_parser_helpers::ConsumeLengthOrPercent(
+ args, context.Mode(), kValueRangeAll);
if (!y_length)
return nullptr;
shape->AppendPoint(x_length, y_length);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args));
return shape;
}
@@ -308,19 +309,20 @@ CSSBasicShapeInsetValue* ConsumeBasicShapeInset(
CSSParserTokenRange& args,
const CSSParserContext& context) {
CSSBasicShapeInsetValue* shape = CSSBasicShapeInsetValue::Create();
- CSSPrimitiveValue* top = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ CSSPrimitiveValue* top = css_property_parser_helpers::ConsumeLengthOrPercent(
args, context.Mode(), kValueRangeAll);
if (!top)
return nullptr;
- CSSPrimitiveValue* right = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- args, context.Mode(), kValueRangeAll);
+ CSSPrimitiveValue* right =
+ css_property_parser_helpers::ConsumeLengthOrPercent(args, context.Mode(),
+ kValueRangeAll);
CSSPrimitiveValue* bottom = nullptr;
CSSPrimitiveValue* left = nullptr;
if (right) {
- bottom = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ bottom = css_property_parser_helpers::ConsumeLengthOrPercent(
args, context.Mode(), kValueRangeAll);
if (bottom) {
- left = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ left = css_property_parser_helpers::ConsumeLengthOrPercent(
args, context.Mode(), kValueRangeAll);
}
}
@@ -333,7 +335,7 @@ CSSBasicShapeInsetValue* ConsumeBasicShapeInset(
else
shape->UpdateShapeSize1Value(top);
- if (CSSPropertyParserHelpers::ConsumeIdent<CSSValueRound>(args)) {
+ if (css_property_parser_helpers::ConsumeIdent<CSSValueRound>(args)) {
CSSValue* horizontal_radii[4] = {nullptr};
CSSValue* vertical_radii[4] = {nullptr};
if (!ConsumeRadii(horizontal_radii, vertical_radii, args, context.Mode(),
@@ -360,12 +362,12 @@ bool ConsumeNumbers(CSSParserTokenRange& args,
unsigned number_of_arguments) {
do {
CSSValue* parsed_value =
- CSSPropertyParserHelpers::ConsumeNumber(args, kValueRangeAll);
+ css_property_parser_helpers::ConsumeNumber(args, kValueRangeAll);
if (!parsed_value)
return false;
transform_value->Append(*parsed_value);
if (--number_of_arguments &&
- !CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ !css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
return false;
}
} while (number_of_arguments);
@@ -376,11 +378,11 @@ bool ConsumePerspective(CSSParserTokenRange& args,
const CSSParserContext& context,
CSSFunctionValue*& transform_value,
bool use_legacy_parsing) {
- CSSPrimitiveValue* parsed_value = CSSPropertyParserHelpers::ConsumeLength(
+ CSSPrimitiveValue* parsed_value = css_property_parser_helpers::ConsumeLength(
args, context.Mode(), kValueRangeNonNegative);
if (!parsed_value && use_legacy_parsing) {
double perspective;
- if (!CSSPropertyParserHelpers::ConsumeNumberRaw(args, perspective) ||
+ if (!css_property_parser_helpers::ConsumeNumberRaw(args, perspective) ||
perspective < 0) {
return false;
}
@@ -400,16 +402,16 @@ bool ConsumeTranslate3d(CSSParserTokenRange& args,
unsigned number_of_arguments = 2;
CSSValue* parsed_value = nullptr;
do {
- parsed_value = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ parsed_value = css_property_parser_helpers::ConsumeLengthOrPercent(
args, css_parser_mode, kValueRangeAll);
if (!parsed_value)
return false;
transform_value->Append(*parsed_value);
- if (!CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args))
+ if (!css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args))
return false;
} while (--number_of_arguments);
- parsed_value = CSSPropertyParserHelpers::ConsumeLength(args, css_parser_mode,
- kValueRangeAll);
+ parsed_value = css_property_parser_helpers::ConsumeLength(
+ args, css_parser_mode, kValueRangeAll);
if (!parsed_value)
return false;
transform_value->Append(*parsed_value);
@@ -419,7 +421,7 @@ bool ConsumeTranslate3d(CSSParserTokenRange& args,
} // namespace
bool IsSelfPositionKeyword(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<
+ return css_property_parser_helpers::IdentMatches<
CSSValueStart, CSSValueEnd, CSSValueCenter, CSSValueSelfStart,
CSSValueSelfEnd, CSSValueFlexStart, CSSValueFlexEnd>(id);
}
@@ -429,7 +431,7 @@ bool IsSelfPositionOrLeftOrRightKeyword(CSSValueID id) {
}
bool IsContentPositionKeyword(CSSValueID id) {
- return CSSPropertyParserHelpers::IdentMatches<
+ return css_property_parser_helpers::IdentMatches<
CSSValueStart, CSSValueEnd, CSSValueCenter, CSSValueFlexStart,
CSSValueFlexEnd>(id);
}
@@ -440,9 +442,10 @@ bool IsContentPositionOrLeftOrRightKeyword(CSSValueID id) {
CSSValue* ConsumeScrollOffset(CSSParserTokenRange& range) {
range.ConsumeWhitespace();
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueAuto>(range.Peek().Id()))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- CSSValue* value = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ if (css_property_parser_helpers::IdentMatches<CSSValueAuto>(
+ range.Peek().Id()))
+ return css_property_parser_helpers::ConsumeIdent(range);
+ CSSValue* value = css_property_parser_helpers::ConsumeLengthOrPercent(
range, kHTMLStandardMode, kValueRangeNonNegative);
if (!range.AtEnd())
return nullptr;
@@ -455,7 +458,7 @@ CSSValue* ConsumeSelfPositionOverflowPosition(
DCHECK(is_position_keyword);
CSSValueID id = range.Peek().Id();
if (IsAuto(id) || IsNormalOrStretch(id))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (IsBaselineKeyword(id))
return ConsumeBaselineKeyword(range);
@@ -464,7 +467,7 @@ CSSValue* ConsumeSelfPositionOverflowPosition(
if (!is_position_keyword(range.Peek().Id()))
return nullptr;
CSSIdentifierValue* self_position =
- CSSPropertyParserHelpers::ConsumeIdent(range);
+ css_property_parser_helpers::ConsumeIdent(range);
if (overflow_position) {
return CSSValuePair::Create(overflow_position, self_position,
CSSValuePair::kDropIdenticalValues);
@@ -477,7 +480,7 @@ CSSValue* ConsumeContentDistributionOverflowPosition(
IsPositionKeyword is_position_keyword) {
DCHECK(is_position_keyword);
CSSValueID id = range.Peek().Id();
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueNormal>(id)) {
+ if (css_property_parser_helpers::IdentMatches<CSSValueNormal>(id)) {
return CSSContentDistributionValue::Create(
CSSValueInvalid, range.ConsumeIncludingWhitespace().Id(),
CSSValueInvalid);
@@ -510,15 +513,16 @@ CSSValue* ConsumeContentDistributionOverflowPosition(
CSSValue* ConsumeAnimationIterationCount(CSSParserTokenRange& range) {
if (range.Peek().Id() == CSSValueInfinite)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
}
CSSValue* ConsumeAnimationName(CSSParserTokenRange& range,
const CSSParserContext& context,
bool allow_quoted_name) {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (allow_quoted_name && range.Peek().GetType() == kStringToken) {
// Legacy support for strings in prefixed animations.
@@ -530,7 +534,7 @@ CSSValue* ConsumeAnimationName(CSSParserTokenRange& range,
return CSSCustomIdentValue::Create(token.Value().ToAtomicString());
}
- return CSSPropertyParserHelpers::ConsumeCustomIdent(range);
+ return css_property_parser_helpers::ConsumeCustomIdent(range, context);
}
CSSValue* ConsumeAnimationTimingFunction(CSSParserTokenRange& range) {
@@ -539,7 +543,7 @@ CSSValue* ConsumeAnimationTimingFunction(CSSParserTokenRange& range) {
id == CSSValueEaseOut || id == CSSValueEaseInOut ||
id == CSSValueStepStart || id == CSSValueStepEnd ||
id == CSSValueStepMiddle)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueID function = range.Peek().FunctionId();
if (function == CSSValueSteps)
@@ -596,7 +600,7 @@ bool ConsumeAnimationShorthand(
}
parsed_longhand[i] = false;
}
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return true;
}
@@ -616,41 +620,41 @@ void AddBackgroundValue(CSSValue*& list, CSSValue* value) {
}
CSSValue* ConsumeBackgroundAttachment(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueScroll, CSSValueFixed,
- CSSValueLocal>(range);
+ return css_property_parser_helpers::ConsumeIdent<
+ CSSValueScroll, CSSValueFixed, CSSValueLocal>(range);
}
CSSValue* ConsumeBackgroundBlendMode(CSSParserTokenRange& range) {
CSSValueID id = range.Peek().Id();
if (id == CSSValueNormal || id == CSSValueOverlay ||
(id >= CSSValueMultiply && id <= CSSValueLuminosity))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
return nullptr;
}
CSSValue* ConsumeBackgroundBox(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdent<
+ return css_property_parser_helpers::ConsumeIdent<
CSSValueBorderBox, CSSValuePaddingBox, CSSValueContentBox>(range);
}
CSSValue* ConsumeBackgroundComposite(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdentRange(range, CSSValueClear,
- CSSValuePlusLighter);
+ return css_property_parser_helpers::ConsumeIdentRange(range, CSSValueClear,
+ CSSValuePlusLighter);
}
CSSValue* ConsumeMaskSourceType(CSSParserTokenRange& range) {
DCHECK(RuntimeEnabledFeatures::CSSMaskSourceTypeEnabled());
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueAuto, CSSValueAlpha,
- CSSValueLuminance>(range);
+ return css_property_parser_helpers::ConsumeIdent<CSSValueAuto, CSSValueAlpha,
+ CSSValueLuminance>(range);
}
CSSPrimitiveValue* ConsumeLengthOrPercentCountNegative(
CSSParserTokenRange& range,
const CSSParserContext& context,
base::Optional<WebFeature> negative_size) {
- CSSPrimitiveValue* result =
- ConsumeLengthOrPercent(range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ CSSPrimitiveValue* result = ConsumeLengthOrPercent(
+ range, context.Mode(), kValueRangeNonNegative,
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
if (!result && negative_size)
context.Count(*negative_size);
return result;
@@ -660,13 +664,13 @@ CSSValue* ConsumeBackgroundSize(CSSParserTokenRange& range,
const CSSParserContext& context,
base::Optional<WebFeature> negative_size,
ParsingStyle parsing_style) {
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueContain, CSSValueCover>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueContain, CSSValueCover>(
range.Peek().Id())) {
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
}
CSSValue* horizontal =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueAuto>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueAuto>(range);
if (!horizontal) {
horizontal =
ConsumeLengthOrPercentCountNegative(range, context, negative_size);
@@ -693,21 +697,22 @@ CSSValue* ConsumeBackgroundSize(CSSParserTokenRange& range,
CSSValuePair::kKeepIdenticalValues);
}
-bool ConsumeBackgroundPosition(CSSParserTokenRange& range,
- const CSSParserContext& context,
- CSSPropertyParserHelpers::UnitlessQuirk unitless,
- CSSValue*& result_x,
- CSSValue*& result_y) {
+bool ConsumeBackgroundPosition(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ css_property_parser_helpers::UnitlessQuirk unitless,
+ CSSValue*& result_x,
+ CSSValue*& result_y) {
do {
CSSValue* position_x = nullptr;
CSSValue* position_y = nullptr;
- if (!CSSPropertyParserHelpers::ConsumePosition(
+ if (!css_property_parser_helpers::ConsumePosition(
range, context, unitless,
WebFeature::kThreeValuedPositionBackground, position_x, position_y))
return false;
AddBackgroundValue(result_x, position_x);
AddBackgroundValue(result_y, position_y);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return true;
}
@@ -715,12 +720,12 @@ CSSValue* ConsumePrefixedBackgroundBox(CSSParserTokenRange& range,
AllowTextValue allow_text_value) {
// The values 'border', 'padding' and 'content' are deprecated and do not
// apply to the version of the property that has the -webkit- prefix removed.
- if (CSSValue* value = CSSPropertyParserHelpers::ConsumeIdentRange(
+ if (CSSValue* value = css_property_parser_helpers::ConsumeIdentRange(
range, CSSValueBorder, CSSValuePaddingBox))
return value;
if (allow_text_value == AllowTextValue::kAllow &&
range.Peek().Id() == CSSValueText)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
return nullptr;
}
@@ -729,10 +734,10 @@ CSSValue* ParseBackgroundBox(CSSParserTokenRange& range,
AllowTextValue alias_allow_text_value) {
// This is legacy behavior that does not match spec, see crbug.com/604023
if (local_context.UseAliasParsing()) {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
ConsumePrefixedBackgroundBox, range, alias_allow_text_value);
}
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
ConsumeBackgroundBox, range);
}
@@ -740,7 +745,7 @@ CSSValue* ParseBackgroundOrMaskSize(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context,
base::Optional<WebFeature> negative_size) {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
ConsumeBackgroundSize, range, context, negative_size,
local_context.UseAliasParsing() ? ParsingStyle::kLegacy
: ParsingStyle::kNotLegacy);
@@ -760,7 +765,7 @@ CSSValue* ConsumeBackgroundComponent(CSSPropertyID resolved_property,
return ConsumeBackgroundBox(range);
case CSSPropertyBackgroundImage:
case CSSPropertyWebkitMaskImage:
- return CSSPropertyParserHelpers::ConsumeImageOrNone(range, &context);
+ return css_property_parser_helpers::ConsumeImageOrNone(range, &context);
case CSSPropertyBackgroundPositionX:
case CSSPropertyWebkitMaskPositionX:
return ConsumePositionLonghand<CSSValueLeft, CSSValueRight>(
@@ -778,7 +783,7 @@ CSSValue* ConsumeBackgroundComponent(CSSPropertyID resolved_property,
WebFeature::kNegativeMaskSize,
ParsingStyle::kNotLegacy);
case CSSPropertyBackgroundColor:
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
case CSSPropertyWebkitMaskClip:
return ConsumePrefixedBackgroundBox(range, AllowTextValue::kAllow);
case CSSPropertyWebkitMaskOrigin:
@@ -833,14 +838,15 @@ bool ParseBackgroundOrMask(bool important,
ConsumeRepeatStyleComponent(range, value, value_y, implicit);
} else if (property.IDEquals(CSSPropertyBackgroundPositionX) ||
property.IDEquals(CSSPropertyWebkitMaskPositionX)) {
- if (!CSSPropertyParserHelpers::ConsumePosition(
+ if (!css_property_parser_helpers::ConsumePosition(
range, context,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid,
+ css_property_parser_helpers::UnitlessQuirk::kForbid,
WebFeature::kThreeValuedPositionBackground, value, value_y))
continue;
} else if (property.IDEquals(CSSPropertyBackgroundSize) ||
property.IDEquals(CSSPropertyWebkitMaskSize)) {
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(
+ range))
continue;
value =
ConsumeBackgroundSize(range, context,
@@ -899,7 +905,7 @@ bool ParseBackgroundOrMask(bool important,
AddBackgroundValue(longhands[i], CSSInitialValue::Create());
}
}
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
if (!range.AtEnd())
return false;
@@ -908,10 +914,11 @@ bool ParseBackgroundOrMask(bool important,
if (property.IDEquals(CSSPropertyBackgroundSize) && longhands[i] &&
context.UseLegacyBackgroundSizeShorthandBehavior())
continue;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
property.PropertyID(), shorthand.id(), *longhands[i], important,
- implicit ? CSSPropertyParserHelpers::IsImplicitProperty::kImplicit
- : CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ implicit
+ ? css_property_parser_helpers::IsImplicitProperty::kImplicit
+ : css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
}
return true;
@@ -921,24 +928,24 @@ bool ConsumeRepeatStyleComponent(CSSParserTokenRange& range,
CSSValue*& value1,
CSSValue*& value2,
bool& implicit) {
- if (CSSPropertyParserHelpers::ConsumeIdent<CSSValueRepeatX>(range)) {
+ if (css_property_parser_helpers::ConsumeIdent<CSSValueRepeatX>(range)) {
value1 = CSSIdentifierValue::Create(CSSValueRepeat);
value2 = CSSIdentifierValue::Create(CSSValueNoRepeat);
implicit = true;
return true;
}
- if (CSSPropertyParserHelpers::ConsumeIdent<CSSValueRepeatY>(range)) {
+ if (css_property_parser_helpers::ConsumeIdent<CSSValueRepeatY>(range)) {
value1 = CSSIdentifierValue::Create(CSSValueNoRepeat);
value2 = CSSIdentifierValue::Create(CSSValueRepeat);
implicit = true;
return true;
}
- value1 = CSSPropertyParserHelpers::ConsumeIdent<
+ value1 = css_property_parser_helpers::ConsumeIdent<
CSSValueRepeat, CSSValueNoRepeat, CSSValueRound, CSSValueSpace>(range);
if (!value1)
return false;
- value2 = CSSPropertyParserHelpers::ConsumeIdent<
+ value2 = css_property_parser_helpers::ConsumeIdent<
CSSValueRepeat, CSSValueNoRepeat, CSSValueRound, CSSValueSpace>(range);
if (!value2) {
value2 = value1;
@@ -958,7 +965,7 @@ bool ConsumeRepeatStyle(CSSParserTokenRange& range,
return false;
AddBackgroundValue(result_x, repeat_x);
AddBackgroundValue(result_y, repeat_y);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return true;
}
@@ -985,7 +992,7 @@ bool ConsumeBorderImageComponents(CSSParserTokenRange& range,
DefaultFill default_fill) {
do {
if (!source) {
- source = CSSPropertyParserHelpers::ConsumeImageOrNone(range, &context);
+ source = css_property_parser_helpers::ConsumeImageOrNone(range, &context);
if (source)
continue;
}
@@ -999,9 +1006,10 @@ bool ConsumeBorderImageComponents(CSSParserTokenRange& range,
if (slice) {
DCHECK(!width);
DCHECK(!outset);
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(
+ range)) {
width = ConsumeBorderImageWidth(range);
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(
range)) {
outset = ConsumeBorderImageOutset(range);
if (!outset)
@@ -1033,15 +1041,15 @@ CSSValue* ConsumeBorderImageRepeat(CSSParserTokenRange& range) {
CSSValue* ConsumeBorderImageSlice(CSSParserTokenRange& range,
DefaultFill default_fill) {
- bool fill = CSSPropertyParserHelpers::ConsumeIdent<CSSValueFill>(range);
+ bool fill = css_property_parser_helpers::ConsumeIdent<CSSValueFill>(range);
CSSValue* slices[4] = {nullptr};
for (size_t index = 0; index < 4; ++index) {
- CSSPrimitiveValue* value =
- CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
+ CSSPrimitiveValue* value = css_property_parser_helpers::ConsumePercent(
+ range, kValueRangeNonNegative);
if (!value) {
- value = CSSPropertyParserHelpers::ConsumeNumber(range,
- kValueRangeNonNegative);
+ value = css_property_parser_helpers::ConsumeNumber(
+ range, kValueRangeNonNegative);
}
if (!value)
break;
@@ -1049,12 +1057,12 @@ CSSValue* ConsumeBorderImageSlice(CSSParserTokenRange& range,
}
if (!slices[0])
return nullptr;
- if (CSSPropertyParserHelpers::ConsumeIdent<CSSValueFill>(range)) {
+ if (css_property_parser_helpers::ConsumeIdent<CSSValueFill>(range)) {
if (fill)
return nullptr;
fill = true;
}
- CSSPropertyParserHelpers::Complete4Sides(slices);
+ css_property_parser_helpers::Complete4Sides(slices);
if (default_fill == DefaultFill::kFill)
fill = true;
return CSSBorderImageSliceValue::Create(
@@ -1068,22 +1076,22 @@ CSSValue* ConsumeBorderImageWidth(CSSParserTokenRange& range) {
CSSValue* value = nullptr;
for (size_t index = 0; index < 4; ++index) {
- value =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ value = css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
if (!value) {
- value = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ value = css_property_parser_helpers::ConsumeLengthOrPercent(
range, kHTMLStandardMode, kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
if (!value)
- value = CSSPropertyParserHelpers::ConsumeIdent<CSSValueAuto>(range);
+ value = css_property_parser_helpers::ConsumeIdent<CSSValueAuto>(range);
if (!value)
break;
widths[index] = value;
}
if (!widths[0])
return nullptr;
- CSSPropertyParserHelpers::Complete4Sides(widths);
+ css_property_parser_helpers::Complete4Sides(widths);
return CSSQuadValue::Create(widths[0], widths[1], widths[2], widths[3],
CSSQuadValue::kSerializeAsQuad);
}
@@ -1093,11 +1101,11 @@ CSSValue* ConsumeBorderImageOutset(CSSParserTokenRange& range) {
CSSValue* value = nullptr;
for (size_t index = 0; index < 4; ++index) {
- value =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ value = css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
if (!value) {
- value = CSSPropertyParserHelpers::ConsumeLength(range, kHTMLStandardMode,
- kValueRangeNonNegative);
+ value = css_property_parser_helpers::ConsumeLength(
+ range, kHTMLStandardMode, kValueRangeNonNegative);
}
if (!value)
break;
@@ -1105,18 +1113,18 @@ CSSValue* ConsumeBorderImageOutset(CSSParserTokenRange& range) {
}
if (!outsets[0])
return nullptr;
- CSSPropertyParserHelpers::Complete4Sides(outsets);
+ css_property_parser_helpers::Complete4Sides(outsets);
return CSSQuadValue::Create(outsets[0], outsets[1], outsets[2], outsets[3],
CSSQuadValue::kSerializeAsQuad);
}
CSSValue* ParseBorderRadiusCorner(CSSParserTokenRange& range,
const CSSParserContext& context) {
- CSSValue* parsed_value1 = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ CSSValue* parsed_value1 = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative);
if (!parsed_value1)
return nullptr;
- CSSValue* parsed_value2 = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ CSSValue* parsed_value2 = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative);
if (!parsed_value2)
parsed_value2 = parsed_value1;
@@ -1131,9 +1139,10 @@ CSSValue* ParseBorderWidthSide(CSSParserTokenRange& range,
bool allow_quirky_lengths =
IsQuirksModeBehavior(context.Mode()) &&
(shorthand == CSSPropertyInvalid || shorthand == CSSPropertyBorderWidth);
- CSSPropertyParserHelpers::UnitlessQuirk unitless =
- allow_quirky_lengths ? CSSPropertyParserHelpers::UnitlessQuirk::kAllow
- : CSSPropertyParserHelpers::UnitlessQuirk::kForbid;
+ css_property_parser_helpers::UnitlessQuirk unitless =
+ allow_quirky_lengths
+ ? css_property_parser_helpers::UnitlessQuirk::kAllow
+ : css_property_parser_helpers::UnitlessQuirk::kForbid;
return ConsumeBorderWidth(range, context.Mode(), unitless);
}
@@ -1141,8 +1150,8 @@ CSSValue* ConsumeShadow(CSSParserTokenRange& range,
CSSParserMode css_parser_mode,
AllowInsetAndSpread inset_and_spread) {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
ParseSingleShadow, range, css_parser_mode, inset_and_spread);
}
@@ -1155,27 +1164,28 @@ CSSShadowValue* ParseSingleShadow(CSSParserTokenRange& range,
if (range.AtEnd())
return nullptr;
- color = CSSPropertyParserHelpers::ConsumeColor(range, css_parser_mode);
+ color = css_property_parser_helpers::ConsumeColor(range, css_parser_mode);
if (range.Peek().Id() == CSSValueInset) {
if (inset_and_spread != AllowInsetAndSpread::kAllow)
return nullptr;
- style = CSSPropertyParserHelpers::ConsumeIdent(range);
+ style = css_property_parser_helpers::ConsumeIdent(range);
if (!color)
- color = CSSPropertyParserHelpers::ConsumeColor(range, css_parser_mode);
+ color = css_property_parser_helpers::ConsumeColor(range, css_parser_mode);
}
CSSPrimitiveValue* horizontal_offset =
- CSSPropertyParserHelpers::ConsumeLength(range, css_parser_mode,
- kValueRangeAll);
+ css_property_parser_helpers::ConsumeLength(range, css_parser_mode,
+ kValueRangeAll);
if (!horizontal_offset)
return nullptr;
- CSSPrimitiveValue* vertical_offset = CSSPropertyParserHelpers::ConsumeLength(
- range, css_parser_mode, kValueRangeAll);
+ CSSPrimitiveValue* vertical_offset =
+ css_property_parser_helpers::ConsumeLength(range, css_parser_mode,
+ kValueRangeAll);
if (!vertical_offset)
return nullptr;
- CSSPrimitiveValue* blur_radius = CSSPropertyParserHelpers::ConsumeLength(
+ CSSPrimitiveValue* blur_radius = css_property_parser_helpers::ConsumeLength(
range, css_parser_mode, kValueRangeAll);
CSSPrimitiveValue* spread_distance = nullptr;
if (blur_radius) {
@@ -1183,20 +1193,22 @@ CSSShadowValue* ParseSingleShadow(CSSParserTokenRange& range,
if (blur_radius->GetDoubleValue() < 0)
return nullptr;
if (inset_and_spread == AllowInsetAndSpread::kAllow) {
- spread_distance = CSSPropertyParserHelpers::ConsumeLength(
+ spread_distance = css_property_parser_helpers::ConsumeLength(
range, css_parser_mode, kValueRangeAll);
}
}
if (!range.AtEnd()) {
if (!color)
- color = CSSPropertyParserHelpers::ConsumeColor(range, css_parser_mode);
+ color = css_property_parser_helpers::ConsumeColor(range, css_parser_mode);
if (range.Peek().Id() == CSSValueInset) {
if (inset_and_spread != AllowInsetAndSpread::kAllow || style)
return nullptr;
- style = CSSPropertyParserHelpers::ConsumeIdent(range);
- if (!color)
- color = CSSPropertyParserHelpers::ConsumeColor(range, css_parser_mode);
+ style = css_property_parser_helpers::ConsumeIdent(range);
+ if (!color) {
+ color =
+ css_property_parser_helpers::ConsumeColor(range, css_parser_mode);
+ }
}
}
return CSSShadowValue::Create(horizontal_offset, vertical_offset, blur_radius,
@@ -1205,16 +1217,16 @@ CSSShadowValue* ParseSingleShadow(CSSParserTokenRange& range,
CSSValue* ConsumeColumnCount(CSSParserTokenRange& range) {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumePositiveInteger(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumePositiveInteger(range);
}
CSSValue* ConsumeColumnWidth(CSSParserTokenRange& range) {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
// Always parse lengths in strict mode here, since it would be ambiguous
// otherwise when used in the 'columns' shorthand property.
- CSSPrimitiveValue* column_width = CSSPropertyParserHelpers::ConsumeLength(
+ CSSPrimitiveValue* column_width = css_property_parser_helpers::ConsumeLength(
range, kHTMLStandardMode, kValueRangeNonNegative);
if (!column_width)
return nullptr;
@@ -1225,7 +1237,7 @@ bool ConsumeColumnWidthOrCount(CSSParserTokenRange& range,
CSSValue*& column_width,
CSSValue*& column_count) {
if (range.Peek().Id() == CSSValueAuto) {
- CSSPropertyParserHelpers::ConsumeIdent(range);
+ css_property_parser_helpers::ConsumeIdent(range);
return true;
}
if (!column_width) {
@@ -1241,24 +1253,26 @@ bool ConsumeColumnWidthOrCount(CSSParserTokenRange& range,
CSSValue* ConsumeGapLength(CSSParserTokenRange& range,
const CSSParserContext& context) {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative);
}
-CSSValue* ConsumeCounter(CSSParserTokenRange& range, int default_value) {
+CSSValue* ConsumeCounter(CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ int default_value) {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
do {
CSSCustomIdentValue* counter_name =
- CSSPropertyParserHelpers::ConsumeCustomIdent(range);
+ css_property_parser_helpers::ConsumeCustomIdent(range, context);
if (!counter_name)
return nullptr;
int value = default_value;
if (CSSPrimitiveValue* counter_value =
- CSSPropertyParserHelpers::ConsumeInteger(range))
+ css_property_parser_helpers::ConsumeInteger(range))
value = clampTo<int>(counter_value->GetDoubleValue());
list->Append(*CSSValuePair::Create(
counter_name,
@@ -1270,24 +1284,24 @@ CSSValue* ConsumeCounter(CSSParserTokenRange& range, int default_value) {
CSSValue* ConsumeFontSize(CSSParserTokenRange& range,
CSSParserMode css_parser_mode,
- CSSPropertyParserHelpers::UnitlessQuirk unitless) {
+ css_property_parser_helpers::UnitlessQuirk unitless) {
if (range.Peek().Id() >= CSSValueXxSmall &&
range.Peek().Id() <= CSSValueLarger)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative, unitless);
}
CSSValue* ConsumeLineHeight(CSSParserTokenRange& range,
CSSParserMode css_parser_mode) {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSPrimitiveValue* line_height =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeNonNegative);
if (line_height)
return line_height;
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative);
}
@@ -1305,13 +1319,13 @@ CSSValueList* ConsumeFontFamily(CSSParserTokenRange& range) {
return nullptr;
}
}
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return list;
}
CSSValue* ConsumeGenericFamily(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdentRange(range, CSSValueSerif,
- CSSValueWebkitBody);
+ return css_property_parser_helpers::ConsumeIdentRange(range, CSSValueSerif,
+ CSSValueWebkitBody);
}
CSSValue* ConsumeFamilyName(CSSParserTokenRange& range) {
@@ -1339,7 +1353,7 @@ String ConcatenateFamilyName(CSSParserTokenRange& range) {
builder.Append(range.ConsumeIncludingWhitespace().Value());
}
if (!added_space &&
- (CSSPropertyParserHelpers::IsCSSWideKeyword(first_token.Value()) ||
+ (css_property_parser_helpers::IsCSSWideKeyword(first_token.Value()) ||
EqualIgnoringASCIICase(first_token.Value(), "default"))) {
return String();
}
@@ -1368,16 +1382,16 @@ CSSValue* ConsumeFontStyle(CSSParserTokenRange& range,
const CSSParserMode& parser_mode) {
if (range.Peek().Id() == CSSValueNormal ||
range.Peek().Id() == CSSValueItalic)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (range.Peek().Id() != CSSValueOblique)
return nullptr;
CSSIdentifierValue* oblique_identifier =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueOblique>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueOblique>(range);
CSSPrimitiveValue* start_angle =
- CSSPropertyParserHelpers::ConsumeAngle(range, nullptr, base::nullopt);
+ css_property_parser_helpers::ConsumeAngle(range, nullptr, base::nullopt);
if (!start_angle)
return oblique_identifier;
if (!IsAngleWithinLimits(start_angle))
@@ -1390,7 +1404,7 @@ CSSValue* ConsumeFontStyle(CSSParserTokenRange& range,
}
CSSPrimitiveValue* end_angle =
- CSSPropertyParserHelpers::ConsumeAngle(range, nullptr, base::nullopt);
+ css_property_parser_helpers::ConsumeAngle(range, nullptr, base::nullopt);
if (!end_angle || !IsAngleWithinLimits(end_angle))
return nullptr;
@@ -1404,7 +1418,7 @@ CSSIdentifierValue* ConsumeFontStretchKeywordOnly(CSSParserTokenRange& range) {
const CSSParserToken& token = range.Peek();
if (token.Id() == CSSValueNormal || (token.Id() >= CSSValueUltraCondensed &&
token.Id() <= CSSValueUltraExpanded))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
return nullptr;
}
@@ -1415,7 +1429,8 @@ CSSValue* ConsumeFontStretch(CSSParserTokenRange& range,
return parsed_keyword;
CSSPrimitiveValue* start_percent =
- CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
+ css_property_parser_helpers::ConsumePercent(range,
+ kValueRangeNonNegative);
if (!start_percent)
return nullptr;
@@ -1423,8 +1438,8 @@ CSSValue* ConsumeFontStretch(CSSParserTokenRange& range,
if (parser_mode != kCSSFontFaceRuleMode || range.AtEnd())
return start_percent;
- CSSPrimitiveValue* end_percent =
- CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
+ CSSPrimitiveValue* end_percent = css_property_parser_helpers::ConsumePercent(
+ range, kValueRangeNonNegative);
if (!end_percent)
return nullptr;
@@ -1435,7 +1450,7 @@ CSSValue* ConsumeFontWeight(CSSParserTokenRange& range,
const CSSParserMode& parser_mode) {
const CSSParserToken& token = range.Peek();
if (token.Id() >= CSSValueNormal && token.Id() <= CSSValueLighter)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
// Avoid consuming the first zero of font: 0/0; e.g. in the Acid3 test. In
// font:0/0; the first zero is the font size, the second is the line height.
@@ -1449,7 +1464,7 @@ CSSValue* ConsumeFontWeight(CSSParserTokenRange& range,
return nullptr;
CSSPrimitiveValue* start_weight =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeNonNegative);
if (!start_weight || start_weight->GetFloatValue() < 1 ||
start_weight->GetFloatValue() > 1000)
return nullptr;
@@ -1461,7 +1476,7 @@ CSSValue* ConsumeFontWeight(CSSParserTokenRange& range,
return start_weight;
CSSPrimitiveValue* end_weight =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeNonNegative);
if (!end_weight || end_weight->GetFloatValue() < 1 ||
end_weight->GetFloatValue() > 1000)
return nullptr;
@@ -1471,14 +1486,14 @@ CSSValue* ConsumeFontWeight(CSSParserTokenRange& range,
CSSValue* ConsumeFontFeatureSettings(CSSParserTokenRange& range) {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* settings = CSSValueList::CreateCommaSeparated();
do {
CSSFontFeatureValue* font_feature_value = ConsumeFontFeatureTag(range);
if (!font_feature_value)
return nullptr;
settings->Append(*font_feature_value);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return settings;
}
@@ -1504,7 +1519,7 @@ CSSFontFeatureValue* ConsumeFontFeatureTag(CSSParserTokenRange& range) {
int tag_value = 1;
// Feature tag values could follow: <integer> | on | off
if (CSSPrimitiveValue* value =
- CSSPropertyParserHelpers::ConsumeInteger(range, 0)) {
+ css_property_parser_helpers::ConsumeInteger(range, 0)) {
tag_value = clampTo<int>(value->GetDoubleValue());
} else if (range.Peek().Id() == CSSValueOn ||
range.Peek().Id() == CSSValueOff) {
@@ -1514,8 +1529,8 @@ CSSFontFeatureValue* ConsumeFontFeatureTag(CSSParserTokenRange& range) {
}
CSSIdentifierValue* ConsumeFontVariantCSS21(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueNormal,
- CSSValueSmallCaps>(range);
+ return css_property_parser_helpers::ConsumeIdent<CSSValueNormal,
+ CSSValueSmallCaps>(range);
}
Vector<String> ParseGridTemplateAreasColumnNames(const String& grid_row_names) {
@@ -1562,10 +1577,9 @@ Vector<String> ParseGridTemplateAreasColumnNames(const String& grid_row_names) {
CSSValue* ConsumeGridBreadth(CSSParserTokenRange& range,
CSSParserMode css_parser_mode) {
const CSSParserToken& token = range.Peek();
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueMinContent,
- CSSValueMaxContent, CSSValueAuto>(
- token.Id()))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ if (css_property_parser_helpers::IdentMatches<
+ CSSValueMinContent, CSSValueMaxContent, CSSValueAuto>(token.Id()))
+ return css_property_parser_helpers::ConsumeIdent(range);
if (token.GetType() == kDimensionToken &&
token.GetUnitType() == CSSPrimitiveValue::UnitType::kFraction) {
if (range.Peek().NumericValue() < 0)
@@ -1574,19 +1588,20 @@ CSSValue* ConsumeGridBreadth(CSSParserTokenRange& range,
range.ConsumeIncludingWhitespace().NumericValue(),
CSSPrimitiveValue::UnitType::kFraction);
}
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
CSSValue* ConsumeFitContent(CSSParserTokenRange& range,
CSSParserMode css_parser_mode) {
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
- CSSPrimitiveValue* length = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- args, css_parser_mode, kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
+ CSSPrimitiveValue* length =
+ css_property_parser_helpers::ConsumeLengthOrPercent(
+ args, css_parser_mode, kValueRangeNonNegative,
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
if (!length || !args.AtEnd())
return nullptr;
range = range_copy;
@@ -1628,18 +1643,18 @@ bool IsGridTrackFixedSized(const CSSValue& value) {
CSSValue* ConsumeGridTrackSize(CSSParserTokenRange& range,
CSSParserMode css_parser_mode) {
const CSSParserToken& token = range.Peek();
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueAuto>(token.Id()))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ if (css_property_parser_helpers::IdentMatches<CSSValueAuto>(token.Id()))
+ return css_property_parser_helpers::ConsumeIdent(range);
if (token.FunctionId() == CSSValueMinmax) {
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
CSSValue* min_track_breadth = ConsumeGridBreadth(args, css_parser_mode);
if (!min_track_breadth ||
(min_track_breadth->IsPrimitiveValue() &&
ToCSSPrimitiveValue(min_track_breadth)->IsFlex()) ||
- !CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args))
+ !css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args))
return nullptr;
CSSValue* max_track_breadth = ConsumeGridBreadth(args, css_parser_mode);
if (!max_track_breadth || !args.AtEnd())
@@ -1657,17 +1672,20 @@ CSSValue* ConsumeGridTrackSize(CSSParserTokenRange& range,
return ConsumeGridBreadth(range, css_parser_mode);
}
-CSSCustomIdentValue* ConsumeCustomIdentForGridLine(CSSParserTokenRange& range) {
+CSSCustomIdentValue* ConsumeCustomIdentForGridLine(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context) {
if (range.Peek().Id() == CSSValueAuto || range.Peek().Id() == CSSValueSpan ||
range.Peek().Id() == CSSValueDefault)
return nullptr;
- return CSSPropertyParserHelpers::ConsumeCustomIdent(range);
+ return css_property_parser_helpers::ConsumeCustomIdent(range, context);
}
// Appends to the passed in CSSGridLineNamesValue if any, otherwise creates a
// new one.
CSSGridLineNamesValue* ConsumeGridLineNames(
CSSParserTokenRange& range,
+ const CSSParserContext& context,
CSSGridLineNamesValue* line_names = nullptr) {
CSSParserTokenRange range_copy = range;
if (range_copy.ConsumeIncludingWhitespace().GetType() != kLeftBracketToken)
@@ -1675,7 +1693,7 @@ CSSGridLineNamesValue* ConsumeGridLineNames(
if (!line_names)
line_names = CSSGridLineNamesValue::Create();
while (CSSCustomIdentValue* line_name =
- ConsumeCustomIdentForGridLine(range_copy))
+ ConsumeCustomIdentForGridLine(range_copy, context))
line_names->Append(*line_name);
if (range_copy.ConsumeIncludingWhitespace().GetType() != kRightBracketToken)
return nullptr;
@@ -1684,17 +1702,19 @@ CSSGridLineNamesValue* ConsumeGridLineNames(
}
bool ConsumeGridTrackRepeatFunction(CSSParserTokenRange& range,
+ const CSSParserContext& context,
CSSParserMode css_parser_mode,
CSSValueList& list,
bool& is_auto_repeat,
bool& all_tracks_are_fixed_sized) {
- CSSParserTokenRange args = CSSPropertyParserHelpers::ConsumeFunction(range);
+ CSSParserTokenRange args =
+ css_property_parser_helpers::ConsumeFunction(range);
// The number of repetitions for <auto-repeat> is not important at parsing
// level because it will be computed later, let's set it to 1.
size_t repetitions = 1;
- is_auto_repeat =
- CSSPropertyParserHelpers::IdentMatches<CSSValueAutoFill, CSSValueAutoFit>(
- args.Peek().Id());
+ is_auto_repeat = css_property_parser_helpers::IdentMatches<CSSValueAutoFill,
+ CSSValueAutoFit>(
+ args.Peek().Id());
CSSValueList* repeated_values;
if (is_auto_repeat) {
repeated_values =
@@ -1702,16 +1722,16 @@ bool ConsumeGridTrackRepeatFunction(CSSParserTokenRange& range,
} else {
// TODO(rob.buis): a consumeIntegerRaw would be more efficient here.
CSSPrimitiveValue* repetition =
- CSSPropertyParserHelpers::ConsumePositiveInteger(args);
+ css_property_parser_helpers::ConsumePositiveInteger(args);
if (!repetition)
return false;
repetitions =
clampTo<size_t>(repetition->GetDoubleValue(), 0, kGridMaxTracks);
repeated_values = CSSValueList::CreateSpaceSeparated();
}
- if (!CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args))
+ if (!css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args))
return false;
- CSSGridLineNamesValue* line_names = ConsumeGridLineNames(args);
+ CSSGridLineNamesValue* line_names = ConsumeGridLineNames(args, context);
if (line_names)
repeated_values->Append(*line_names);
@@ -1724,7 +1744,7 @@ bool ConsumeGridTrackRepeatFunction(CSSParserTokenRange& range,
all_tracks_are_fixed_sized = IsGridTrackFixedSized(*track_size);
repeated_values->Append(*track_size);
++number_of_tracks;
- line_names = ConsumeGridLineNames(args);
+ line_names = ConsumeGridLineNames(args, context);
if (line_names)
repeated_values->Append(*line_names);
}
@@ -1769,7 +1789,7 @@ bool ConsumeGridTemplateRowsAndAreasAndColumns(bool important,
do {
// Handle leading <custom-ident>*.
bool has_previous_line_names = line_names;
- line_names = ConsumeGridLineNames(range, line_names);
+ line_names = ConsumeGridLineNames(range, context, line_names);
if (line_names && !has_previous_line_names)
template_rows_value_list->Append(*line_names);
@@ -1788,17 +1808,17 @@ bool ConsumeGridTemplateRowsAndAreasAndColumns(bool important,
template_rows_value_list->Append(*value);
// This will handle the trailing/leading <custom-ident>* in the grammar.
- line_names = ConsumeGridLineNames(range);
+ line_names = ConsumeGridLineNames(range, context);
if (line_names)
template_rows_value_list->Append(*line_names);
} while (!range.AtEnd() && !(range.Peek().GetType() == kDelimiterToken &&
range.Peek().Delimiter() == '/'));
if (!range.AtEnd()) {
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
return false;
template_columns = ConsumeGridTrackList(
- range, context.Mode(), TrackListType::kGridTemplateNoRepeat);
+ range, context, context.Mode(), TrackListType::kGridTemplateNoRepeat);
if (!template_columns || !range.AtEnd())
return false;
} else {
@@ -1811,30 +1831,31 @@ bool ConsumeGridTemplateRowsAndAreasAndColumns(bool important,
return true;
}
-CSSValue* ConsumeGridLine(CSSParserTokenRange& range) {
+CSSValue* ConsumeGridLine(CSSParserTokenRange& range,
+ const CSSParserContext& context) {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSIdentifierValue* span_value = nullptr;
CSSCustomIdentValue* grid_line_name = nullptr;
CSSPrimitiveValue* numeric_value =
- CSSPropertyParserHelpers::ConsumeInteger(range);
+ css_property_parser_helpers::ConsumeInteger(range);
if (numeric_value) {
- grid_line_name = ConsumeCustomIdentForGridLine(range);
- span_value = CSSPropertyParserHelpers::ConsumeIdent<CSSValueSpan>(range);
+ grid_line_name = ConsumeCustomIdentForGridLine(range, context);
+ span_value = css_property_parser_helpers::ConsumeIdent<CSSValueSpan>(range);
} else {
- span_value = CSSPropertyParserHelpers::ConsumeIdent<CSSValueSpan>(range);
+ span_value = css_property_parser_helpers::ConsumeIdent<CSSValueSpan>(range);
if (span_value) {
- numeric_value = CSSPropertyParserHelpers::ConsumeInteger(range);
- grid_line_name = ConsumeCustomIdentForGridLine(range);
+ numeric_value = css_property_parser_helpers::ConsumeInteger(range);
+ grid_line_name = ConsumeCustomIdentForGridLine(range, context);
if (!numeric_value)
- numeric_value = CSSPropertyParserHelpers::ConsumeInteger(range);
+ numeric_value = css_property_parser_helpers::ConsumeInteger(range);
} else {
- grid_line_name = ConsumeCustomIdentForGridLine(range);
+ grid_line_name = ConsumeCustomIdentForGridLine(range, context);
if (grid_line_name) {
- numeric_value = CSSPropertyParserHelpers::ConsumeInteger(range);
+ numeric_value = css_property_parser_helpers::ConsumeInteger(range);
span_value =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueSpan>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueSpan>(range);
if (!span_value && !numeric_value)
return grid_line_name;
} else {
@@ -1869,11 +1890,12 @@ CSSValue* ConsumeGridLine(CSSParserTokenRange& range) {
}
CSSValue* ConsumeGridTrackList(CSSParserTokenRange& range,
+ const CSSParserContext& context,
CSSParserMode css_parser_mode,
TrackListType track_list_type) {
bool allow_grid_line_names = track_list_type != TrackListType::kGridAuto;
CSSValueList* values = CSSValueList::CreateSpaceSeparated();
- CSSGridLineNamesValue* line_names = ConsumeGridLineNames(range);
+ CSSGridLineNamesValue* line_names = ConsumeGridLineNames(range, context);
if (line_names) {
if (!allow_grid_line_names)
return nullptr;
@@ -1888,8 +1910,8 @@ CSSValue* ConsumeGridTrackList(CSSParserTokenRange& range,
if (range.Peek().FunctionId() == CSSValueRepeat) {
if (!allow_repeat)
return nullptr;
- if (!ConsumeGridTrackRepeatFunction(range, css_parser_mode, *values,
- is_auto_repeat,
+ if (!ConsumeGridTrackRepeatFunction(range, context, css_parser_mode,
+ *values, is_auto_repeat,
all_tracks_are_fixed_sized))
return nullptr;
if (is_auto_repeat && seen_auto_repeat)
@@ -1904,7 +1926,7 @@ CSSValue* ConsumeGridTrackList(CSSParserTokenRange& range,
}
if (seen_auto_repeat && !all_tracks_are_fixed_sized)
return nullptr;
- line_names = ConsumeGridLineNames(range);
+ line_names = ConsumeGridLineNames(range, context);
if (line_names) {
if (!allow_grid_line_names)
return nullptr;
@@ -1918,7 +1940,7 @@ bool ParseGridTemplateAreasRow(const String& grid_row_names,
NamedGridAreaMap& grid_area_map,
const size_t row_count,
size_t& column_count) {
- if (grid_row_names.IsEmpty() || grid_row_names.ContainsOnlyWhitespace())
+ if (grid_row_names.ContainsOnlyWhitespaceOrEmpty())
return false;
Vector<String> column_names =
@@ -1983,27 +2005,29 @@ bool ParseGridTemplateAreasRow(const String& grid_row_names,
}
CSSValue* ConsumeGridTemplatesRowsOrColumns(CSSParserTokenRange& range,
+ const CSSParserContext& context,
CSSParserMode css_parser_mode) {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return ConsumeGridTrackList(range, css_parser_mode,
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return ConsumeGridTrackList(range, context, css_parser_mode,
TrackListType::kGridTemplate);
}
bool ConsumeGridItemPositionShorthand(bool important,
CSSParserTokenRange& range,
+ const CSSParserContext& context,
CSSValue*& start_value,
CSSValue*& end_value) {
// Input should be nullptrs.
DCHECK(!start_value);
DCHECK(!end_value);
- start_value = ConsumeGridLine(range);
+ start_value = ConsumeGridLine(range, context);
if (!start_value)
return false;
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
- end_value = ConsumeGridLine(range);
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
+ end_value = ConsumeGridLine(range, context);
if (!end_value)
return false;
} else {
@@ -2028,7 +2052,8 @@ bool ConsumeGridTemplateShorthand(bool important,
DCHECK_EQ(gridTemplateShorthand().length(), 3u);
CSSParserTokenRange range_copy = range;
- template_rows = CSSPropertyParserHelpers::ConsumeIdent<CSSValueNone>(range);
+ template_rows =
+ css_property_parser_helpers::ConsumeIdent<CSSValueNone>(range);
// 1- 'none' case.
if (template_rows && range.AtEnd()) {
@@ -2040,14 +2065,15 @@ bool ConsumeGridTemplateShorthand(bool important,
// 2- <grid-template-rows> / <grid-template-columns>
if (!template_rows) {
- template_rows = ConsumeGridTrackList(range, context.Mode(),
+ template_rows = ConsumeGridTrackList(range, context, context.Mode(),
TrackListType::kGridTemplate);
}
if (template_rows) {
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
return false;
- template_columns = ConsumeGridTemplatesRowsOrColumns(range, context.Mode());
+ template_columns =
+ ConsumeGridTemplatesRowsOrColumns(range, context, context.Mode());
if (!template_columns || !range.AtEnd())
return false;
@@ -2131,7 +2157,7 @@ CSSValue* ConsumePath(CSSParserTokenRange& range) {
CSSParserTokenRange function_range = range;
CSSParserTokenRange function_args =
- CSSPropertyParserHelpers::ConsumeFunction(function_range);
+ css_property_parser_helpers::ConsumeFunction(function_range);
if (function_args.Peek().GetType() != kStringToken)
return nullptr;
@@ -2156,27 +2182,27 @@ CSSValue* ConsumeRay(CSSParserTokenRange& range,
DCHECK_EQ(range.Peek().FunctionId(), CSSValueRay);
CSSParserTokenRange function_range = range;
CSSParserTokenRange function_args =
- CSSPropertyParserHelpers::ConsumeFunction(function_range);
+ css_property_parser_helpers::ConsumeFunction(function_range);
CSSPrimitiveValue* angle = nullptr;
CSSIdentifierValue* size = nullptr;
CSSIdentifierValue* contain = nullptr;
while (!function_args.AtEnd()) {
if (!angle) {
- angle = CSSPropertyParserHelpers::ConsumeAngle(
+ angle = css_property_parser_helpers::ConsumeAngle(
function_args, &context, base::Optional<WebFeature>());
if (angle)
continue;
}
if (!size) {
- size = CSSPropertyParserHelpers::ConsumeIdent<
+ size = css_property_parser_helpers::ConsumeIdent<
CSSValueClosestSide, CSSValueClosestCorner, CSSValueFarthestSide,
CSSValueFarthestCorner, CSSValueSides>(function_args);
if (size)
continue;
}
if (RuntimeEnabledFeatures::CSSOffsetPathRayContainEnabled() && !contain) {
- contain = CSSPropertyParserHelpers::ConsumeIdent<CSSValueContain>(
+ contain = css_property_parser_helpers::ConsumeIdent<CSSValueContain>(
function_args);
if (contain)
continue;
@@ -2192,32 +2218,32 @@ CSSValue* ConsumeRay(CSSParserTokenRange& range,
CSSValue* ConsumeMaxWidthOrHeight(
CSSParserTokenRange& range,
const CSSParserContext& context,
- CSSPropertyParserHelpers::UnitlessQuirk unitless) {
+ css_property_parser_helpers::UnitlessQuirk unitless) {
if (range.Peek().Id() == CSSValueNone ||
ValidWidthOrHeightKeyword(range.Peek().Id(), context))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative, unitless);
}
CSSValue* ConsumeWidthOrHeight(
CSSParserTokenRange& range,
const CSSParserContext& context,
- CSSPropertyParserHelpers::UnitlessQuirk unitless) {
+ css_property_parser_helpers::UnitlessQuirk unitless) {
if (range.Peek().Id() == CSSValueAuto ||
ValidWidthOrHeightKeyword(range.Peek().Id(), context))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative, unitless);
}
CSSValue* ConsumeMarginOrOffset(
CSSParserTokenRange& range,
CSSParserMode css_parser_mode,
- CSSPropertyParserHelpers::UnitlessQuirk unitless) {
+ css_property_parser_helpers::UnitlessQuirk unitless) {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeAll, unitless);
}
@@ -2239,23 +2265,23 @@ CSSValue* ConsumeOffsetPath(CSSParserTokenRange& range,
CSSValue* ConsumePathOrNone(CSSParserTokenRange& range) {
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
return ConsumePath(range);
}
CSSValue* ConsumeOffsetRotate(CSSParserTokenRange& range,
const CSSParserContext& context) {
- CSSValue* angle = CSSPropertyParserHelpers::ConsumeAngle(
+ CSSValue* angle = css_property_parser_helpers::ConsumeAngle(
range, &context, base::Optional<WebFeature>());
CSSValue* keyword =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueAuto, CSSValueReverse>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueAuto, CSSValueReverse>(
range);
if (!angle && !keyword)
return nullptr;
if (!angle) {
- angle = CSSPropertyParserHelpers::ConsumeAngle(
+ angle = css_property_parser_helpers::ConsumeAngle(
range, &context, base::Optional<WebFeature>());
}
@@ -2275,7 +2301,7 @@ bool ConsumeRadii(CSSValue* horizontal_radii[4],
unsigned i = 0;
for (; i < 4 && !range.AtEnd() && range.Peek().GetType() != kDelimiterToken;
++i) {
- horizontal_radii[i] = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ horizontal_radii[i] = css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative);
if (!horizontal_radii[i])
return false;
@@ -2289,16 +2315,16 @@ bool ConsumeRadii(CSSValue* horizontal_radii[4],
vertical_radii[0] = horizontal_radii[1];
horizontal_radii[1] = nullptr;
} else {
- CSSPropertyParserHelpers::Complete4Sides(horizontal_radii);
+ css_property_parser_helpers::Complete4Sides(horizontal_radii);
for (unsigned i = 0; i < 4; ++i)
vertical_radii[i] = horizontal_radii[i];
return true;
}
} else {
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
return false;
for (i = 0; i < 4 && !range.AtEnd(); ++i) {
- vertical_radii[i] = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ vertical_radii[i] = css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeNonNegative);
if (!vertical_radii[i])
return false;
@@ -2306,8 +2332,8 @@ bool ConsumeRadii(CSSValue* horizontal_radii[4],
if (!vertical_radii[0] || !range.AtEnd())
return false;
}
- CSSPropertyParserHelpers::Complete4Sides(horizontal_radii);
- CSSPropertyParserHelpers::Complete4Sides(vertical_radii);
+ css_property_parser_helpers::Complete4Sides(horizontal_radii);
+ css_property_parser_helpers::Complete4Sides(vertical_radii);
return true;
}
@@ -2319,7 +2345,7 @@ CSSValue* ConsumeBasicShape(CSSParserTokenRange& range,
CSSValueID id = range.Peek().FunctionId();
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
if (id == CSSValueCircle)
shape = ConsumeBasicShapeCircle(args, context);
else if (id == CSSValueEllipse)
@@ -2339,14 +2365,13 @@ CSSValue* ConsumeBasicShape(CSSParserTokenRange& range,
CSSValue* ConsumeTextDecorationLine(CSSParserTokenRange& range) {
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
while (true) {
- CSSIdentifierValue* ident =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueBlink, CSSValueUnderline,
- CSSValueOverline,
- CSSValueLineThrough>(range);
+ CSSIdentifierValue* ident = css_property_parser_helpers::ConsumeIdent<
+ CSSValueBlink, CSSValueUnderline, CSSValueOverline,
+ CSSValueLineThrough>(range);
if (!ident)
break;
if (list->HasValue(*ident))
@@ -2365,7 +2390,8 @@ CSSValue* ConsumeTransformValue(CSSParserTokenRange& range,
CSSValueID function_id = range.Peek().FunctionId();
if (function_id == CSSValueInvalid)
return nullptr;
- CSSParserTokenRange args = CSSPropertyParserHelpers::ConsumeFunction(range);
+ CSSParserTokenRange args =
+ css_property_parser_helpers::ConsumeFunction(range);
if (args.AtEnd())
return nullptr;
CSSFunctionValue* transform_value = CSSFunctionValue::Create(function_id);
@@ -2378,14 +2404,14 @@ CSSValue* ConsumeTransformValue(CSSParserTokenRange& range,
case CSSValueSkewX:
case CSSValueSkewY:
case CSSValueSkew:
- parsed_value = CSSPropertyParserHelpers::ConsumeAngle(
+ parsed_value = css_property_parser_helpers::ConsumeAngle(
args, &context, WebFeature::kUnitlessZeroAngleTransform);
if (!parsed_value)
return nullptr;
if (function_id == CSSValueSkew &&
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
transform_value->Append(*parsed_value);
- parsed_value = CSSPropertyParserHelpers::ConsumeAngle(
+ parsed_value = css_property_parser_helpers::ConsumeAngle(
args, &context, WebFeature::kUnitlessZeroAngleTransform);
if (!parsed_value)
return nullptr;
@@ -2396,14 +2422,14 @@ CSSValue* ConsumeTransformValue(CSSParserTokenRange& range,
case CSSValueScaleZ:
case CSSValueScale:
parsed_value =
- CSSPropertyParserHelpers::ConsumeNumber(args, kValueRangeAll);
+ css_property_parser_helpers::ConsumeNumber(args, kValueRangeAll);
if (!parsed_value)
return nullptr;
if (function_id == CSSValueScale &&
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
transform_value->Append(*parsed_value);
parsed_value =
- CSSPropertyParserHelpers::ConsumeNumber(args, kValueRangeAll);
+ css_property_parser_helpers::ConsumeNumber(args, kValueRangeAll);
if (!parsed_value)
return nullptr;
}
@@ -2417,21 +2443,21 @@ CSSValue* ConsumeTransformValue(CSSParserTokenRange& range,
case CSSValueTranslateX:
case CSSValueTranslateY:
case CSSValueTranslate:
- parsed_value = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ parsed_value = css_property_parser_helpers::ConsumeLengthOrPercent(
args, context.Mode(), kValueRangeAll);
if (!parsed_value)
return nullptr;
if (function_id == CSSValueTranslate &&
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
transform_value->Append(*parsed_value);
- parsed_value = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ parsed_value = css_property_parser_helpers::ConsumeLengthOrPercent(
args, context.Mode(), kValueRangeAll);
if (!parsed_value)
return nullptr;
}
break;
case CSSValueTranslateZ:
- parsed_value = CSSPropertyParserHelpers::ConsumeLength(
+ parsed_value = css_property_parser_helpers::ConsumeLength(
args, context.Mode(), kValueRangeAll);
break;
case CSSValueMatrix:
@@ -2447,10 +2473,10 @@ CSSValue* ConsumeTransformValue(CSSParserTokenRange& range,
break;
case CSSValueRotate3d:
if (!ConsumeNumbers(args, transform_value, 3) ||
- !CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ !css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
return nullptr;
}
- parsed_value = CSSPropertyParserHelpers::ConsumeAngle(
+ parsed_value = css_property_parser_helpers::ConsumeAngle(
args, &context, WebFeature::kUnitlessZeroAngleTransform);
if (!parsed_value)
return nullptr;
@@ -2473,7 +2499,7 @@ CSSValue* ConsumeTransformList(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
do {
@@ -2487,12 +2513,13 @@ CSSValue* ConsumeTransformList(CSSParserTokenRange& range,
return list;
}
-CSSValue* ConsumeTransitionProperty(CSSParserTokenRange& range) {
+CSSValue* ConsumeTransitionProperty(CSSParserTokenRange& range,
+ const CSSParserContext& context) {
const CSSParserToken& token = range.Peek();
if (token.GetType() != kIdentToken)
return nullptr;
if (token.Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSPropertyID unresolved_property = token.ParseAsUnresolvedCSSPropertyID();
if (unresolved_property != CSSPropertyInvalid &&
unresolved_property != CSSPropertyVariable) {
@@ -2503,7 +2530,7 @@ CSSValue* ConsumeTransitionProperty(CSSParserTokenRange& range) {
range.ConsumeIncludingWhitespace();
return CSSCustomIdentValue::Create(unresolved_property);
}
- return CSSPropertyParserHelpers::ConsumeCustomIdent(range);
+ return css_property_parser_helpers::ConsumeCustomIdent(range, context);
}
bool IsValidPropertyList(const CSSValueList& value_list) {
@@ -2524,39 +2551,40 @@ CSSValue* ConsumeBorderColorSide(CSSParserTokenRange& range,
bool allow_quirky_colors =
IsQuirksModeBehavior(context.Mode()) &&
(shorthand == CSSPropertyInvalid || shorthand == CSSPropertyBorderColor);
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode(),
- allow_quirky_colors);
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode(),
+ allow_quirky_colors);
}
-CSSValue* ConsumeBorderWidth(CSSParserTokenRange& range,
- CSSParserMode css_parser_mode,
- CSSPropertyParserHelpers::UnitlessQuirk unitless) {
- return CSSPropertyParserHelpers::ConsumeLineWidth(range, css_parser_mode,
- unitless);
+CSSValue* ConsumeBorderWidth(
+ CSSParserTokenRange& range,
+ CSSParserMode css_parser_mode,
+ css_property_parser_helpers::UnitlessQuirk unitless) {
+ return css_property_parser_helpers::ConsumeLineWidth(range, css_parser_mode,
+ unitless);
}
CSSValue* ParseSpacing(CSSParserTokenRange& range,
const CSSParserContext& context) {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
// TODO(timloh): allow <percentage>s in word-spacing.
- return CSSPropertyParserHelpers::ConsumeLength(
+ return css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
CSSValue* ParsePaintStroke(CSSParserTokenRange& range,
const CSSParserContext& context) {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- CSSURIValue* url = CSSPropertyParserHelpers::ConsumeUrl(range, &context);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ CSSURIValue* url = css_property_parser_helpers::ConsumeUrl(range, &context);
if (url) {
CSSValue* parsed_value = nullptr;
if (range.Peek().Id() == CSSValueNone) {
- parsed_value = CSSPropertyParserHelpers::ConsumeIdent(range);
+ parsed_value = css_property_parser_helpers::ConsumeIdent(range);
} else {
parsed_value =
- CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
if (parsed_value) {
CSSValueList* values = CSSValueList::CreateSpaceSeparated();
@@ -2566,8 +2594,8 @@ CSSValue* ParsePaintStroke(CSSParserTokenRange& range,
}
return url;
}
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
-} // namespace CSSParsingUtils
+} // namespace css_parsing_utils
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.h b/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.h
index 44358b05e8e..c7cbb4c5316 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.h
@@ -24,7 +24,7 @@ class CSSValue;
class CSSValueList;
class StylePropertyShorthand;
-namespace CSSParsingUtils {
+namespace css_parsing_utils {
enum class AllowInsetAndSpread { kAllow, kForbid };
enum class AllowTextValue { kAllow, kForbid };
@@ -78,7 +78,7 @@ CSSValue* ConsumeBackgroundComposite(CSSParserTokenRange&);
CSSValue* ConsumeMaskSourceType(CSSParserTokenRange&);
bool ConsumeBackgroundPosition(CSSParserTokenRange&,
const CSSParserContext&,
- CSSPropertyParserHelpers::UnitlessQuirk,
+ css_property_parser_helpers::UnitlessQuirk,
CSSValue*& result_x,
CSSValue*& result_y);
CSSValue* ConsumePrefixedBackgroundBox(CSSParserTokenRange&, AllowTextValue);
@@ -137,12 +137,13 @@ CSSValue* ConsumeColumnWidth(CSSParserTokenRange&);
bool ConsumeColumnWidthOrCount(CSSParserTokenRange&, CSSValue*&, CSSValue*&);
CSSValue* ConsumeGapLength(CSSParserTokenRange&, const CSSParserContext&);
-CSSValue* ConsumeCounter(CSSParserTokenRange&, int);
+CSSValue* ConsumeCounter(CSSParserTokenRange&, const CSSParserContext&, int);
-CSSValue* ConsumeFontSize(CSSParserTokenRange&,
- CSSParserMode,
- CSSPropertyParserHelpers::UnitlessQuirk =
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+CSSValue* ConsumeFontSize(
+ CSSParserTokenRange&,
+ CSSParserMode,
+ css_property_parser_helpers::UnitlessQuirk =
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
CSSValue* ConsumeLineHeight(CSSParserTokenRange&, CSSParserMode);
@@ -158,8 +159,9 @@ CSSValue* ConsumeFontFeatureSettings(CSSParserTokenRange&);
cssvalue::CSSFontFeatureValue* ConsumeFontFeatureTag(CSSParserTokenRange&);
CSSIdentifierValue* ConsumeFontVariantCSS21(CSSParserTokenRange&);
-CSSValue* ConsumeGridLine(CSSParserTokenRange&);
+CSSValue* ConsumeGridLine(CSSParserTokenRange&, const CSSParserContext&);
CSSValue* ConsumeGridTrackList(CSSParserTokenRange&,
+ const CSSParserContext&,
CSSParserMode,
TrackListType);
bool ParseGridTemplateAreasRow(const WTF::String& grid_row_names,
@@ -167,9 +169,11 @@ bool ParseGridTemplateAreasRow(const WTF::String& grid_row_names,
const size_t row_count,
size_t& column_count);
CSSValue* ConsumeGridTemplatesRowsOrColumns(CSSParserTokenRange&,
+ const CSSParserContext&,
CSSParserMode);
bool ConsumeGridItemPositionShorthand(bool important,
CSSParserTokenRange&,
+ const CSSParserContext&,
CSSValue*& start_value,
CSSValue*& end_value);
bool ConsumeGridTemplateShorthand(bool important,
@@ -190,17 +194,17 @@ bool ConsumeFromColumnOrPageBreakInside(CSSParserTokenRange&, CSSValueID&);
CSSValue* ConsumeMaxWidthOrHeight(
CSSParserTokenRange&,
const CSSParserContext&,
- CSSPropertyParserHelpers::UnitlessQuirk =
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk =
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
CSSValue* ConsumeWidthOrHeight(
CSSParserTokenRange&,
const CSSParserContext&,
- CSSPropertyParserHelpers::UnitlessQuirk =
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk =
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
CSSValue* ConsumeMarginOrOffset(CSSParserTokenRange&,
CSSParserMode,
- CSSPropertyParserHelpers::UnitlessQuirk);
+ css_property_parser_helpers::UnitlessQuirk);
CSSValue* ConsumeOffsetPath(CSSParserTokenRange&, const CSSParserContext&);
CSSValue* ConsumePathOrNone(CSSParserTokenRange&);
CSSValue* ConsumeOffsetRotate(CSSParserTokenRange&, const CSSParserContext&);
@@ -220,7 +224,8 @@ CSSValue* ConsumeTransformValue(CSSParserTokenRange&,
CSSValue* ConsumeTransformList(CSSParserTokenRange&,
const CSSParserContext&,
const CSSParserLocalContext&);
-CSSValue* ConsumeTransitionProperty(CSSParserTokenRange&);
+CSSValue* ConsumeTransitionProperty(CSSParserTokenRange&,
+ const CSSParserContext&);
bool IsValidPropertyList(const CSSValueList&);
CSSValue* ConsumeBorderColorSide(CSSParserTokenRange&,
@@ -228,7 +233,7 @@ CSSValue* ConsumeBorderColorSide(CSSParserTokenRange&,
const CSSParserLocalContext&);
CSSValue* ConsumeBorderWidth(CSSParserTokenRange&,
CSSParserMode,
- CSSPropertyParserHelpers::UnitlessQuirk);
+ css_property_parser_helpers::UnitlessQuirk);
CSSValue* ParsePaintStroke(CSSParserTokenRange&, const CSSParserContext&);
CSSValue* ParseSpacing(CSSParserTokenRange&, const CSSParserContext&);
@@ -250,11 +255,11 @@ CSSValue* ConsumePositionLonghand(CSSParserTokenRange& range,
return CSSPrimitiveValue::Create(percent,
CSSPrimitiveValue::UnitType::kPercentage);
}
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeAll);
}
-} // namespace CSSParsingUtils
+} // namespace css_parsing_utils
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_PARSING_UTILS_H_
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property_ref.cc b/chromium/third_party/blink/renderer/core/css/properties/css_property_ref.cc
new file mode 100644
index 00000000000..ebe0cc4859f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property_ref.cc
@@ -0,0 +1,35 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
+
+#include "third_party/blink/renderer/core/dom/document.h"
+
+namespace blink {
+
+CSSPropertyRef::CSSPropertyRef(const String& name, const Document& document)
+ : property_id_(unresolvedCSSPropertyID(name)) {
+ if (property_id_ == CSSPropertyVariable)
+ custom_property_ = CustomProperty(AtomicString(name), document);
+}
+
+CSSPropertyRef::CSSPropertyRef(const CSSPropertyName& name,
+ const Document& document)
+ : property_id_(name.Id()) {
+ DCHECK_NE(name.Id(), CSSPropertyInvalid);
+ if (property_id_ == CSSPropertyVariable)
+ custom_property_ = CustomProperty(name.ToAtomicString(), document);
+}
+
+CSSPropertyRef::CSSPropertyRef(const CSSProperty& property)
+ : property_id_(property.PropertyID()) {
+ if (property.PropertyID() == CSSPropertyVariable) {
+ if (!Variable::IsStaticInstance(property))
+ custom_property_ = static_cast<const CustomProperty&>(property);
+ else
+ property_id_ = CSSPropertyInvalid;
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property_ref.h b/chromium/third_party/blink/renderer/core/css/properties/css_property_ref.h
new file mode 100644
index 00000000000..557414d776f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property_ref.h
@@ -0,0 +1,78 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_PROPERTY_REF_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_PROPERTY_REF_H_
+
+#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h"
+
+namespace blink {
+
+class CSSPropertyName;
+class Document;
+
+// Use this class to acquire a reference to a CSSProperty instance. The
+// reference returned by GetProperty() may point to the embedded CustomProperty
+// object, hence this reference is only valid for the lifetime of the
+// CSSPropertyRef object.
+//
+// Usage:
+//
+// CSSPropertyRef ref(some_string, document);
+//
+// if (ref.IsValid()) {
+// LOG(INFO) << ref.GetProperty().GetName();
+// }
+//
+// Note that any CSSPropertyRef constructor may produce an invalid
+// CSSPropertyRef (e.g. if a non-existent property name is provided), so be
+// sure to always check IsValid() before calling GetProperty().
+class CORE_EXPORT CSSPropertyRef {
+ DISALLOW_NEW();
+
+ public:
+ // Look up (or create) a CSSProperty.
+ //
+ // If the incoming 'name' is not a CSS property, the CSSPropertyRef is
+ // invalid.
+ CSSPropertyRef(const String& name, const Document&);
+
+ // Like above, but will never produce an invalid CSSPropertyRef.
+ CSSPropertyRef(const CSSPropertyName&, const Document&);
+
+ // If you already have a CSSProperty& object, you may use it to get
+ // a CSSPropertyRef again.
+ //
+ // Note that the CSSProperty& returned by GetProperty() may be different
+ // than the incoming CSSProperty&.
+ //
+ // Note also that this CSSPropertyRef is invalid if the incoming CSSProperty&
+ // is the static Variable instance.
+ CSSPropertyRef(const CSSProperty&);
+
+ bool IsValid() const { return property_id_ != CSSPropertyInvalid; }
+
+ const CSSProperty& GetProperty() const {
+ DCHECK(IsValid());
+ if (property_id_ == CSSPropertyVariable)
+ return custom_property_;
+ return CSSProperty::Get(resolveCSSPropertyID(property_id_));
+ }
+
+ const CSSUnresolvedProperty& GetUnresolvedProperty() const {
+ if (isPropertyAlias(property_id_))
+ return *CSSUnresolvedProperty::GetAliasProperty(property_id_);
+ return GetProperty();
+ }
+
+ void Trace(blink::Visitor* visitor) { visitor->Trace(custom_property_); }
+
+ private:
+ CSSPropertyID property_id_;
+ CustomProperty custom_property_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_PROPERTY_REF_H_
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property_ref_test.cc b/chromium/third_party/blink/renderer/core/css/properties/css_property_ref_test.cc
new file mode 100644
index 00000000000..42c03ced91e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property_ref_test.cc
@@ -0,0 +1,99 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+
+namespace blink {
+
+using namespace css_test_helpers;
+
+namespace {
+
+class CSSPropertyRefTest : public PageTestBase {};
+
+} // namespace
+
+TEST_F(CSSPropertyRefTest, LookupUnregistred) {
+ CSSPropertyRef ref("--x", GetDocument());
+ EXPECT_TRUE(ref.IsValid());
+ EXPECT_EQ(CSSPropertyVariable, ref.GetProperty().PropertyID());
+}
+
+TEST_F(CSSPropertyRefTest, LookupRegistered) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "42px", false);
+ CSSPropertyRef ref("--x", GetDocument());
+ EXPECT_TRUE(ref.IsValid());
+ EXPECT_EQ(CSSPropertyVariable, ref.GetProperty().PropertyID());
+}
+
+TEST_F(CSSPropertyRefTest, LookupStandard) {
+ CSSPropertyRef ref("font-size", GetDocument());
+ EXPECT_TRUE(ref.IsValid());
+ EXPECT_EQ(CSSPropertyFontSize, ref.GetProperty().PropertyID());
+}
+
+TEST_F(CSSPropertyRefTest, IsValid) {
+ CSSPropertyRef ref("nosuchproperty", GetDocument());
+ EXPECT_FALSE(ref.IsValid());
+}
+
+TEST_F(CSSPropertyRefTest, FromCustomProperty) {
+ CustomProperty custom(AtomicString("--x"), GetDocument());
+ CSSPropertyRef ref(custom);
+ EXPECT_TRUE(ref.IsValid());
+ EXPECT_EQ(CSSPropertyVariable, ref.GetProperty().PropertyID());
+}
+
+TEST_F(CSSPropertyRefTest, FromStandardProperty) {
+ CSSPropertyRef ref(GetCSSPropertyFontSize());
+ EXPECT_TRUE(ref.IsValid());
+ EXPECT_EQ(CSSPropertyFontSize, ref.GetProperty().PropertyID());
+}
+
+TEST_F(CSSPropertyRefTest, FromStaticVariableInstance) {
+ CSSPropertyRef ref(GetCSSPropertyVariable());
+ EXPECT_FALSE(ref.IsValid());
+}
+
+TEST_F(CSSPropertyRefTest, GetUnresolvedPropertyStandard) {
+ CSSPropertyRef ref("font-size", GetDocument());
+ EXPECT_TRUE(ref.GetUnresolvedProperty().IsResolvedProperty());
+}
+
+TEST_F(CSSPropertyRefTest, GetUnresolvedPropertyCustom) {
+ CSSPropertyRef ref("--x", GetDocument());
+ EXPECT_TRUE(ref.GetUnresolvedProperty().IsResolvedProperty());
+}
+
+TEST_F(CSSPropertyRefTest, GetUnresolvedPropertyAlias) {
+ // -webkit-transform is an arbitrarily chosen alias.
+ CSSPropertyRef ref("-webkit-transform", GetDocument());
+ const auto& unresolved = ref.GetUnresolvedProperty();
+ EXPECT_FALSE(unresolved.IsResolvedProperty());
+ EXPECT_EQ("-webkit-transform", unresolved.GetPropertyNameString());
+}
+
+TEST_F(CSSPropertyRefTest, GetResolvedPropertyAlias) {
+ // -webkit-transform is an arbitrarily chosen alias.
+ CSSPropertyRef ref("-webkit-transform", GetDocument());
+ EXPECT_TRUE(ref.GetProperty().IsResolvedProperty());
+ EXPECT_EQ("transform", ref.GetProperty().GetPropertyNameString());
+}
+
+TEST_F(CSSPropertyRefTest, FromCSSPropertyNameCustom) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "42px", false);
+ CSSPropertyRef ref(CSSPropertyName("--x"), GetDocument());
+ EXPECT_EQ(CSSPropertyVariable, ref.GetProperty().PropertyID());
+}
+
+TEST_F(CSSPropertyRefTest, FromCSSPropertyNameStandard) {
+ CSSPropertyRef ref(CSSPropertyName(CSSPropertyFontSize), GetDocument());
+ EXPECT_EQ(CSSPropertyFontSize, ref.GetProperty().PropertyID());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/align_content_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/align_content_custom.cc
index 2c2215420c2..3ffafa147fc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/align_content_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/align_content_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AlignContent::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeContentDistributionOverflowPosition(
- range, CSSParsingUtils::IsContentPositionKeyword);
+ return css_parsing_utils::ConsumeContentDistributionOverflowPosition(
+ range, css_parsing_utils::IsContentPositionKeyword);
}
const CSSValue* AlignContent::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* AlignContent::CSSValueFromComputedStyleInternal(
style.AlignContent());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/align_items_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/align_items_custom.cc
index fe5538132b2..e77d25d8739 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/align_items_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/align_items_custom.cc
@@ -10,17 +10,18 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AlignItems::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
// align-items property does not allow the 'auto' value.
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueAuto>(range.Peek().Id()))
+ if (css_property_parser_helpers::IdentMatches<CSSValueAuto>(
+ range.Peek().Id()))
return nullptr;
- return CSSParsingUtils::ConsumeSelfPositionOverflowPosition(
- range, CSSParsingUtils::IsSelfPositionKeyword);
+ return css_parsing_utils::ConsumeSelfPositionOverflowPosition(
+ range, css_parsing_utils::IsSelfPositionKeyword);
}
const CSSValue* AlignItems::CSSValueFromComputedStyleInternal(
@@ -33,5 +34,5 @@ const CSSValue* AlignItems::CSSValueFromComputedStyleInternal(
style.AlignItems());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/align_self_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/align_self_custom.cc
index 9fc2ec591a4..9565047cd11 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/align_self_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/align_self_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AlignSelf::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeSelfPositionOverflowPosition(
- range, CSSParsingUtils::IsSelfPositionKeyword);
+ return css_parsing_utils::ConsumeSelfPositionOverflowPosition(
+ range, css_parsing_utils::IsSelfPositionKeyword);
}
const CSSValue* AlignSelf::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* AlignSelf::CSSValueFromComputedStyleInternal(
style.AlignSelf());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/alignment_baseline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/alignment_baseline_custom.cc
index f725b6c3ada..6ee34f480ea 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/alignment_baseline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/alignment_baseline_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/alignment_baseline.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AlignmentBaseline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* AlignmentBaseline::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.AlignmentBaseline());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_delay_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_delay_custom.cc
index 3bfcd9ac19a..06dfd297b21 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_delay_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_delay_custom.cc
@@ -7,17 +7,17 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationDelay::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeTime, range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeTime, range, kValueRangeAll);
}
const CSSValue* AnimationDelay::CSSValueFromComputedStyleInternal(
@@ -37,5 +37,5 @@ const CSSValue* AnimationDelay::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc
index 8572a3a924f..4deae2d747a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc
@@ -10,16 +10,16 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationDirection::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueNormal, CSSValueAlternate,
- CSSValueReverse,
- CSSValueAlternateReverse>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeIdent<
+ CSSValueNormal, CSSValueAlternate, CSSValueReverse,
+ CSSValueAlternateReverse>,
range);
}
@@ -48,5 +48,5 @@ const CSSValue* AnimationDirection::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_duration_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_duration_custom.cc
index b4fba58f73f..5158fb343bf 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_duration_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_duration_custom.cc
@@ -7,17 +7,17 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationDuration::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeTime, range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeTime, range, kValueRangeNonNegative);
}
const CSSValue* AnimationDuration::CSSValueFromComputedStyleInternal(
@@ -37,5 +37,5 @@ const CSSValue* AnimationDuration::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc
index fa1c4ab13a8..e1fb8603598 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationFillMode::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueNone, CSSValueForwards,
- CSSValueBackwards, CSSValueBoth>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeIdent<
+ CSSValueNone, CSSValueForwards, CSSValueBackwards, CSSValueBoth>,
range);
}
@@ -47,5 +47,5 @@ const CSSValue* AnimationFillMode::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc
index e8c25fd0dea..b0eaa447849 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationIterationCount::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeAnimationIterationCount, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeAnimationIterationCount, range);
}
const CSSValue* AnimationIterationCount::CSSValueFromComputedStyleInternal(
@@ -49,5 +49,5 @@ const CSSValue* AnimationIterationCount::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc
index 4b708e88d16..8603f6ab954 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationName::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
// Allow quoted name if this is an alias property.
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeAnimationName, range, context,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeAnimationName, range, context,
local_context.UseAliasParsing());
}
@@ -45,5 +45,5 @@ const CSSValue* AnimationName::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc
index 418090b3b6e..16e02578f9a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc
@@ -10,14 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationPlayState::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueRunning, CSSValuePaused>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeIdent<CSSValueRunning,
+ CSSValuePaused>,
range);
}
@@ -46,5 +47,5 @@ const CSSValue* AnimationPlayState::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_timing_function_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_timing_function_custom.cc
index 19983ebe080..205f3331a94 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_timing_function_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/animation_timing_function_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* AnimationTimingFunction::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeAnimationTimingFunction, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeAnimationTimingFunction, range);
}
const CSSValue* AnimationTimingFunction::CSSValueFromComputedStyleInternal(
@@ -36,5 +36,5 @@ const CSSValue* AnimationTimingFunction::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/backdrop_filter_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/backdrop_filter_custom.cc
index 41eb3346fbd..50302fdfc3d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/backdrop_filter_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/backdrop_filter_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackdropFilter::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeFilterFunctionList(range, context);
+ return css_property_parser_helpers::ConsumeFilterFunctionList(range, context);
}
const CSSValue* BackdropFilter::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* BackdropFilter::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFilter(style, style.BackdropFilter());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/backface_visibility_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/backface_visibility_custom.cc
index aa12196f7cc..7ef04f62c53 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/backface_visibility_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/backface_visibility_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/backface_visibility.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackfaceVisibility::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -19,5 +19,5 @@ const CSSValue* BackfaceVisibility::CSSValueFromComputedStyleInternal(
: CSSValueVisible);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_attachment_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_attachment_custom.cc
index 2bff0de99d4..e0591339c82 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_attachment_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_attachment_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundAttachment::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeBackgroundAttachment, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeBackgroundAttachment, range);
}
const CSSValue* BackgroundAttachment::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* BackgroundAttachment::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_blend_mode_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_blend_mode_custom.cc
index 4a89a5f37b6..08417ec6c78 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_blend_mode_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_blend_mode_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundBlendMode::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeBackgroundBlendMode, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeBackgroundBlendMode, range);
}
const CSSValue* BackgroundBlendMode::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* BackgroundBlendMode::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_clip_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_clip_custom.cc
index 0941b8fc1d4..a2e80e5c9fe 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_clip_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_clip_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundClip::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBackgroundBox(
- range, local_context, CSSParsingUtils::AllowTextValue::kAllow);
+ return css_parsing_utils::ParseBackgroundBox(
+ range, local_context, css_parsing_utils::AllowTextValue::kAllow);
}
const CSSValue* BackgroundClip::CSSValueFromComputedStyleInternal(
@@ -33,5 +33,5 @@ const CSSValue* BackgroundClip::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_color_custom.cc
index 78dafacc84d..1fb8f509d1a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_color_custom.cc
@@ -12,13 +12,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(
+ return css_property_parser_helpers::ConsumeColor(
range, context.Mode(), IsQuirksModeBehavior(context.Mode()));
}
@@ -57,5 +57,5 @@ const CSSValue* BackgroundColor::CSSValueFromComputedStyleInternal(
style, style.BackgroundColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_image_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_image_custom.cc
index 9e47d1b0a45..bc8afb10d05 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_image_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_image_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundImage::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeImageOrNone, range, &context);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeImageOrNone, range, &context);
}
const CSSValue* BackgroundImage::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* BackgroundImage::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::BackgroundImageOrWebkitMaskImage(fill_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_origin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_origin_custom.cc
index 0224310c538..3b076d97db1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_origin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_origin_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundOrigin::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBackgroundBox(
- range, local_context, CSSParsingUtils::AllowTextValue::kForbid);
+ return css_parsing_utils::ParseBackgroundBox(
+ range, local_context, css_parsing_utils::AllowTextValue::kForbid);
}
const CSSValue* BackgroundOrigin::CSSValueFromComputedStyleInternal(
@@ -33,5 +33,5 @@ const CSSValue* BackgroundOrigin::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_x_custom.cc
index 00322791db5..de6066de717 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_x_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundPositionX::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumePositionLonghand<CSSValueLeft, CSSValueRight>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumePositionLonghand<CSSValueLeft, CSSValueRight>,
range, context.Mode());
}
@@ -33,5 +33,5 @@ const CSSValue* BackgroundPositionX::CSSValueFromComputedStyleInternal(
style, curr_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_y_custom.cc
index a1f096894b4..f5a453c9b17 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_position_y_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundPositionY::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>,
range, context.Mode());
}
@@ -33,5 +33,5 @@ const CSSValue* BackgroundPositionY::CSSValueFromComputedStyleInternal(
style, curr_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_size_custom.cc
index 8663381d549..c426a54df67 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/background_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/background_size_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BackgroundSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBackgroundOrMaskSize(
+ return css_parsing_utils::ParseBackgroundOrMaskSize(
range, context, local_context, WebFeature::kNegativeBackgroundSize);
}
@@ -30,5 +30,5 @@ const CSSValue* BackgroundSize::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::BackgroundImageOrWebkitMaskSize(style, fill_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/baseline_shift_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/baseline_shift_custom.cc
index 26734d4bc0d..a16199c840a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/baseline_shift_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/baseline_shift_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BaselineShift::ParseSingleValue(
CSSParserTokenRange& range,
@@ -19,8 +19,8 @@ const CSSValue* BaselineShift::ParseSingleValue(
const CSSParserLocalContext&) const {
CSSValueID id = range.Peek().Id();
if (id == CSSValueBaseline || id == CSSValueSub || id == CSSValueSuper)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, kSVGAttributeMode, kValueRangeAll);
}
@@ -77,5 +77,5 @@ void BaselineShift::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/block_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/block_size_custom.cc
index 0bf6c111c7a..56bba6cf32d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/block_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/block_size_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BlockSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(range, context);
+ return css_parsing_utils::ConsumeWidthOrHeight(range, context);
}
bool BlockSize::IsLayoutDependent(const ComputedStyle* style,
@@ -23,5 +23,5 @@ bool BlockSize::IsLayoutDependent(const ComputedStyle* style,
return layout_object && layout_object->IsBox();
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_color_custom.cc
index 584cd2e7b9b..f66392706e2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_color_custom.cc
@@ -12,14 +12,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBlockEndColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_width_custom.cc
index b51c04782ef..e57415d7891 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_end_width_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBlockEndWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeBorderWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_color_custom.cc
index 30d384981f3..ea96b89508e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_color_custom.cc
@@ -12,14 +12,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBlockStartColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_width_custom.cc
index a4bc114343b..8a15fcbc2ab 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_block_start_width_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBlockStartWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeBorderWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_color_custom.cc
index 14681dc3162..1935e6a27a6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_color_custom.cc
@@ -15,13 +15,14 @@ class CSSParserContext;
class CSSParserLocalContext;
class CSSParserTokenRange;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBottomColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ConsumeBorderColorSide(range, context, local_context);
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
}
const blink::Color BorderBottomColor::ColorIncludingFallback(
@@ -46,5 +47,5 @@ const CSSValue* BorderBottomColor::CSSValueFromComputedStyleInternal(
style, style.BorderBottomColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_left_radius_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_left_radius_custom.cc
index 7ef63ec14cd..791b4cdc3fc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_left_radius_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_left_radius_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBottomLeftRadius::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParseBorderRadiusCorner(range, context);
+ return css_parsing_utils::ParseBorderRadiusCorner(range, context);
}
const CSSValue* BorderBottomLeftRadius::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* BorderBottomLeftRadius::CSSValueFromComputedStyleInternal(
style.BorderBottomLeftRadius(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_right_radius_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_right_radius_custom.cc
index fa10ed696b7..1eb8d4ec7f3 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_right_radius_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_right_radius_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBottomRightRadius::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParseBorderRadiusCorner(range, context);
+ return css_parsing_utils::ParseBorderRadiusCorner(range, context);
}
const CSSValue* BorderBottomRightRadius::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* BorderBottomRightRadius::CSSValueFromComputedStyleInternal(
style.BorderBottomRightRadius(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_style_custom.cc
index fbdec89087b..5b1894cf293 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_style_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/border_bottom_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBottomStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BorderBottomStyle::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BorderBottomStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_width_custom.cc
index 90240194ace..253c9b0792c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_bottom_width_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderBottomWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBorderWidthSide(range, context, local_context);
+ return css_parsing_utils::ParseBorderWidthSide(range, context, local_context);
}
const CSSValue* BorderBottomWidth::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* BorderBottomWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.BorderBottomWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_collapse_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_collapse_custom.cc
index d815b21921a..d6a4bfdffa9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_collapse_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_collapse_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* BorderCollapse::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueSeparate);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_outset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_outset_custom.cc
index 43fcc5ef118..7f0185f3c27 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_outset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_outset_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderImageOutset::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageOutset(range);
+ return css_parsing_utils::ConsumeBorderImageOutset(range);
}
const CSSValue* BorderImageOutset::CSSValueFromComputedStyleInternal(
@@ -39,5 +39,5 @@ const CSSValue* BorderImageOutset::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_repeat_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_repeat_custom.cc
index 4a9bcb09ad8..96d735818ae 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_repeat_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_repeat_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderImageRepeat::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageRepeat(range);
+ return css_parsing_utils::ConsumeBorderImageRepeat(range);
}
const CSSValue* BorderImageRepeat::CSSValueFromComputedStyleInternal(
@@ -33,5 +33,5 @@ const CSSValue* BorderImageRepeat::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_slice_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_slice_custom.cc
index 3376506b45e..62888d64f9e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_slice_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_slice_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderImageSlice::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageSlice(
- range, CSSParsingUtils::DefaultFill::kNoFill);
+ return css_parsing_utils::ConsumeBorderImageSlice(
+ range, css_parsing_utils::DefaultFill::kNoFill);
}
const CSSValue* BorderImageSlice::CSSValueFromComputedStyleInternal(
@@ -35,5 +35,5 @@ const CSSValue* BorderImageSlice::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_source_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_source_custom.cc
index 8f5375a87c3..17622ae42f7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_source_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_source_custom.cc
@@ -12,13 +12,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderImageSource::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeImageOrNone(range, &context);
+ return css_property_parser_helpers::ConsumeImageOrNone(range, &context);
}
const CSSValue* BorderImageSource::CSSValueFromComputedStyleInternal(
@@ -44,5 +44,5 @@ void BorderImageSource::ApplyValue(StyleResolverState& state,
state.GetStyleImage(CSSPropertyBorderImageSource, value));
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_width_custom.cc
index d981f2bbd9f..6b3bd3bd6a1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_image_width_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderImageWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageWidth(range);
+ return css_parsing_utils::ConsumeBorderImageWidth(range);
}
const CSSValue* BorderImageWidth::CSSValueFromComputedStyleInternal(
@@ -39,5 +39,5 @@ const CSSValue* BorderImageWidth::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_color_custom.cc
index 250d1d60b90..4a76f43041a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_color_custom.cc
@@ -12,14 +12,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderInlineEndColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_width_custom.cc
index 9b239eac685..ce62e09ee46 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_end_width_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderInlineEndWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeBorderWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_color_custom.cc
index 927a86240e3..35c90842baa 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_color_custom.cc
@@ -12,14 +12,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderInlineStartColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_width_custom.cc
index 803070f0843..a9cdb5f1e44 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_inline_start_width_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderInlineStartWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeBorderWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_color_custom.cc
index 1b243bd0284..899c48f5284 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_color_custom.cc
@@ -15,13 +15,14 @@ class CSSParserContext;
class CSSParserLocalContext;
class CSSParserTokenRange;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderLeftColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ConsumeBorderColorSide(range, context, local_context);
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
}
const blink::Color BorderLeftColor::ColorIncludingFallback(
@@ -46,5 +47,5 @@ const CSSValue* BorderLeftColor::CSSValueFromComputedStyleInternal(
style, style.BorderLeftColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_style_custom.cc
index 5789b084c24..eca1f56a9da 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_style_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/border_left_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderLeftStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BorderLeftStyle::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BorderLeftStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_width_custom.cc
index 6bfccb3ede8..cccc045086e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_left_width_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderLeftWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBorderWidthSide(range, context, local_context);
+ return css_parsing_utils::ParseBorderWidthSide(range, context, local_context);
}
const CSSValue* BorderLeftWidth::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* BorderLeftWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.BorderLeftWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_color_custom.cc
index da1f4d3ff38..5adefc67e86 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_color_custom.cc
@@ -15,13 +15,14 @@ class CSSParserContext;
class CSSParserLocalContext;
class CSSParserTokenRange;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderRightColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ConsumeBorderColorSide(range, context, local_context);
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
}
const blink::Color BorderRightColor::ColorIncludingFallback(
@@ -46,5 +47,5 @@ const CSSValue* BorderRightColor::CSSValueFromComputedStyleInternal(
style, style.BorderRightColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_style_custom.cc
index eb04928a72b..bb8bcde223e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_style_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/border_right_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderRightStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BorderRightStyle::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BorderRightStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_width_custom.cc
index 0c1fca8c791..9850f28e996 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_right_width_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderRightWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBorderWidthSide(range, context, local_context);
+ return css_parsing_utils::ParseBorderWidthSide(range, context, local_context);
}
const CSSValue* BorderRightWidth::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* BorderRightWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.BorderRightWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_color_custom.cc
index c7793559a67..10319b5022f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_color_custom.cc
@@ -15,13 +15,14 @@ class CSSParserContext;
class CSSParserLocalContext;
class CSSParserTokenRange;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderTopColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ConsumeBorderColorSide(range, context, local_context);
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
}
const blink::Color BorderTopColor::ColorIncludingFallback(
@@ -47,5 +48,5 @@ const CSSValue* BorderTopColor::CSSValueFromComputedStyleInternal(
style, style.BorderTopColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_left_radius_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_left_radius_custom.cc
index 7b4b65ad323..7c01a8a4091 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_left_radius_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_left_radius_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderTopLeftRadius::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParseBorderRadiusCorner(range, context);
+ return css_parsing_utils::ParseBorderRadiusCorner(range, context);
}
const CSSValue* BorderTopLeftRadius::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* BorderTopLeftRadius::CSSValueFromComputedStyleInternal(
style.BorderTopLeftRadius(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_right_radius_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_right_radius_custom.cc
index 297749b001f..723f4005d0a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_right_radius_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_right_radius_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderTopRightRadius::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParseBorderRadiusCorner(range, context);
+ return css_parsing_utils::ParseBorderRadiusCorner(range, context);
}
const CSSValue* BorderTopRightRadius::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* BorderTopRightRadius::CSSValueFromComputedStyleInternal(
style.BorderTopRightRadius(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_style_custom.cc
index 7b524a901e3..e00e4d0acb5 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_style_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/border_top_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderTopStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BorderTopStyle::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BorderTopStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_width_custom.cc
index ee94b04b747..864199510b4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/border_top_width_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BorderTopWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBorderWidthSide(range, context, local_context);
+ return css_parsing_utils::ParseBorderWidthSide(range, context, local_context);
}
const CSSValue* BorderTopWidth::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* BorderTopWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.BorderTopWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/bottom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/bottom_custom.cc
index 68606e85b46..7f22bfd645a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/bottom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/bottom_custom.cc
@@ -15,13 +15,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Bottom::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool Bottom::IsLayoutDependent(const ComputedStyle* style,
@@ -39,5 +40,5 @@ const CSSValue* Bottom::CSSValueFromComputedStyleInternal(
layout_object);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/box_shadow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/box_shadow_custom.cc
index 615e14d8391..0004a5d3b4e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/box_shadow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/box_shadow_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BoxShadow::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeShadow(
- range, context.Mode(), CSSParsingUtils::AllowInsetAndSpread::kAllow);
+ return css_parsing_utils::ConsumeShadow(
+ range, context.Mode(), css_parsing_utils::AllowInsetAndSpread::kAllow);
}
const CSSValue* BoxShadow::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* BoxShadow::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForShadowList(style.BoxShadow(), style, true);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/box_sizing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/box_sizing_custom.cc
index 2ece767f398..560b580eb18 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/box_sizing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/box_sizing_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BoxSizing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* BoxSizing::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueBorderBox);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/break_after_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/break_after_custom.cc
index cc54c807b06..fdf5814187a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/break_after_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/break_after_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/break_after.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BreakAfter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BreakAfter::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BreakAfter());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/break_before_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/break_before_custom.cc
index 131cd9e6cfb..7626cb72834 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/break_before_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/break_before_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/break_before.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BreakBefore::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BreakBefore::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BreakBefore());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/break_inside_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/break_inside_custom.cc
index 118eb08012e..36c675bcc0c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/break_inside_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/break_inside_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/break_inside.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BreakInside::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BreakInside::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BreakInside());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/buffered_rendering_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/buffered_rendering_custom.cc
index 8fb703f5e35..a65e2fb894c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/buffered_rendering_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/buffered_rendering_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/buffered_rendering.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* BufferedRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* BufferedRendering::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.BufferedRendering());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/caption_side_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/caption_side_custom.cc
index 68b07a20bc0..26175888763 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/caption_side_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/caption_side_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/caption_side.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* CaptionSide::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* CaptionSide::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.CaptionSide());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/caret_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/caret_color_custom.cc
index bd1010e20f8..48d4150244d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/caret_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/caret_color_custom.cc
@@ -11,15 +11,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* CaretColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color CaretColor::ColorIncludingFallback(
@@ -80,5 +80,5 @@ void CaretColor::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/clear_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/clear_custom.cc
index 0fa6c74e360..23784392b93 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/clear_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/clear_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/clear.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Clear::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,27 +16,5 @@ const CSSValue* Clear::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.Clear());
}
-void Clear::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
- const CSSIdentifierValue& identifier_value = ToCSSIdentifierValue(value);
-
- EClear c;
- CSSValueID id = identifier_value.GetValueID();
- switch (id) {
- case CSSValueInlineStart:
- case CSSValueInlineEnd:
- if ((id == CSSValueInlineStart) ==
- (state.Style()->Direction() == TextDirection::kLtr)) {
- c = EClear::kLeft;
- } else {
- c = EClear::kRight;
- }
- break;
- default:
- c = identifier_value.ConvertTo<EClear>();
- break;
- }
- state.Style()->SetClear(c);
-}
-
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_custom.cc
index 1a703b112ff..968d00af06d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_custom.cc
@@ -16,40 +16,41 @@ namespace {
CSSValue* ConsumeClipComponent(CSSParserTokenRange& range,
CSSParserMode css_parser_mode) {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLength(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLength(
range, css_parser_mode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
} // namespace
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Clip::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (range.Peek().FunctionId() != CSSValueRect)
return nullptr;
- CSSParserTokenRange args = CSSPropertyParserHelpers::ConsumeFunction(range);
+ CSSParserTokenRange args =
+ css_property_parser_helpers::ConsumeFunction(range);
// rect(t, r, b, l) || rect(t r b l)
CSSValue* top = ConsumeClipComponent(args, context.Mode());
if (!top)
return nullptr;
bool needs_comma =
- CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args);
+ css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args);
CSSValue* right = ConsumeClipComponent(args, context.Mode());
if (!right ||
(needs_comma &&
- !CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)))
+ !css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)))
return nullptr;
CSSValue* bottom = ConsumeClipComponent(args, context.Mode());
if (!bottom ||
(needs_comma &&
- !CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)))
+ !css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)))
return nullptr;
CSSValue* left = ConsumeClipComponent(args, context.Mode());
if (!left || !args.AtEnd())
@@ -78,5 +79,5 @@ const CSSValue* Clip::CSSValueFromComputedStyleInternal(
CSSQuadValue::kSerializeAsRect);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_path_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_path_custom.cc
index 5b9ff89b12e..c12fa9f5789 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_path_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_path_custom.cc
@@ -13,16 +13,17 @@
#include "third_party/blink/renderer/core/style/shape_clip_path_operation.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ClipPath::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- if (CSSURIValue* url = CSSPropertyParserHelpers::ConsumeUrl(range, &context))
+ return css_property_parser_helpers::ConsumeIdent(range);
+ if (CSSURIValue* url =
+ css_property_parser_helpers::ConsumeUrl(range, &context))
return url;
- return CSSParsingUtils::ConsumeBasicShape(range, context);
+ return css_parsing_utils::ConsumeBasicShape(range, context);
}
const CSSValue* ClipPath::CSSValueFromComputedStyleInternal(
@@ -44,5 +45,5 @@ const CSSValue* ClipPath::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueNone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_rule_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_rule_custom.cc
index 355a6a2cca9..dbdb9899612 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_rule_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/clip_rule_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/clip_rule.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ClipRule::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ClipRule::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.ClipRule());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_custom.cc
index 8061da94d70..75fb0a421c9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_custom.cc
@@ -12,12 +12,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Color::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(
+ return css_property_parser_helpers::ConsumeColor(
range, context.Mode(), IsQuirksModeBehavior(context.Mode()));
}
@@ -73,5 +73,5 @@ void Color::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_custom.cc
index 73f1c308162..473436ee526 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/color_interpolation.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColorInterpolation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ColorInterpolation::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.ColorInterpolation());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters_custom.cc
index 586a813ac1b..edbc6013164 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColorInterpolationFilters::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ColorInterpolationFilters::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.ColorInterpolationFilters());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_rendering_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_rendering_custom.cc
index 0fa6eec6581..9c76a140b16 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/color_rendering_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/color_rendering_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/color_rendering.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColorRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ColorRendering::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.ColorRendering());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_count_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_count_custom.cc
index d7e0ab5359a..629c19f687a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_count_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_count_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnCount::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeColumnCount(range);
+ return css_parsing_utils::ConsumeColumnCount(range);
}
const CSSValue* ColumnCount::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ColumnCount::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_fill_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_fill_custom.cc
index 5e5ac8851d2..01b60be1d6f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_fill_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_fill_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/column_fill.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnFill::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ColumnFill::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetColumnFill());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_gap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_gap_custom.cc
index 58f45a2aede..e84fc9dd077 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_gap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_gap_custom.cc
@@ -11,13 +11,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnGap::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGapLength(range, context);
+ return css_parsing_utils::ConsumeGapLength(range, context);
}
const CSSValue* ColumnGap::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ColumnGap::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGapLength(style.ColumnGap(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_color_custom.cc
index e9294e47db1..95f128af7e2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_color_custom.cc
@@ -11,13 +11,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnRuleColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color ColumnRuleColor::ColorIncludingFallback(
@@ -42,5 +42,5 @@ const CSSValue* ColumnRuleColor::CSSValueFromComputedStyleInternal(
style, style.ColumnRuleColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_style_custom.cc
index 0813b5d596a..bace7dd7dbf 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_style_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/column_rule_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnRuleStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ColumnRuleStyle::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.ColumnRuleStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_width_custom.cc
index 2c4ac28f911..1dce9d4295c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_rule_width_custom.cc
@@ -9,14 +9,15 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnRuleWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLineWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeLineWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ColumnRuleWidth::CSSValueFromComputedStyleInternal(
@@ -28,5 +29,5 @@ const CSSValue* ColumnRuleWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.ColumnRuleWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_span_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_span_custom.cc
index be13a3ac7ef..030e7a86fff 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_span_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_span_custom.cc
@@ -7,13 +7,13 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnSpan::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueAll, CSSValueNone>(
+ return css_property_parser_helpers::ConsumeIdent<CSSValueAll, CSSValueNone>(
range);
}
@@ -28,5 +28,5 @@ const CSSValue* ColumnSpan::CSSValueFromComputedStyleInternal(
: CSSValueNone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_width_custom.cc
index e06bf3c3bec..d8f23451c5c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/column_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/column_width_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ColumnWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeColumnWidth(range);
+ return css_parsing_utils::ConsumeColumnWidth(range);
}
const CSSValue* ColumnWidth::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ColumnWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.ColumnWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/contain_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/contain_custom.cc
index effdab99b06..b6fab7d6254 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/contain_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/contain_custom.cc
@@ -10,31 +10,47 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
-// none | strict | content | [ layout || style || paint || size ]
+// none | strict | content | [ size || layout || style || paint ]
const CSSValue* Contain::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (id == CSSValueStrict || id == CSSValueContent) {
- list->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ list->Append(*css_property_parser_helpers::ConsumeIdent(range));
return list;
}
+
+ CSSIdentifierValue* size = nullptr;
+ CSSIdentifierValue* layout = nullptr;
+ CSSIdentifierValue* style = nullptr;
+ CSSIdentifierValue* paint = nullptr;
while (true) {
- CSSIdentifierValue* ident = CSSPropertyParserHelpers::ConsumeIdent<
- CSSValuePaint, CSSValueLayout, CSSValueStyle, CSSValueSize>(range);
- if (!ident)
+ CSSValueID id = range.Peek().Id();
+ if (id == CSSValueSize && !size)
+ size = css_property_parser_helpers::ConsumeIdent(range);
+ else if (id == CSSValueLayout && !layout)
+ layout = css_property_parser_helpers::ConsumeIdent(range);
+ else if (id == CSSValueStyle && !style)
+ style = css_property_parser_helpers::ConsumeIdent(range);
+ else if (id == CSSValuePaint && !paint)
+ paint = css_property_parser_helpers::ConsumeIdent(range);
+ else
break;
- if (list->HasValue(*ident))
- return nullptr;
- list->Append(*ident);
}
-
+ if (size)
+ list->Append(*size);
+ if (layout)
+ list->Append(*layout);
+ if (style)
+ list->Append(*style);
+ if (paint)
+ list->Append(*paint);
if (!list->length())
return nullptr;
return list;
@@ -54,17 +70,17 @@ const CSSValue* Contain::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueContent);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- if (style.ContainsStyle())
- list->Append(*CSSIdentifierValue::Create(CSSValueStyle));
+ if (style.ContainsSize())
+ list->Append(*CSSIdentifierValue::Create(CSSValueSize));
if (style.Contain() & kContainsLayout)
list->Append(*CSSIdentifierValue::Create(CSSValueLayout));
+ if (style.ContainsStyle())
+ list->Append(*CSSIdentifierValue::Create(CSSValueStyle));
if (style.ContainsPaint())
list->Append(*CSSIdentifierValue::Create(CSSValuePaint));
- if (style.ContainsSize())
- list->Append(*CSSIdentifierValue::Create(CSSValueSize));
DCHECK(list->length());
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/content_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/content_custom.cc
index 63916ae2e6e..ee8e477a028 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/content_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/content_custom.cc
@@ -35,9 +35,11 @@ CSSValue* ConsumeAttr(CSSParserTokenRange args,
return attr_value;
}
-CSSValue* ConsumeCounterContent(CSSParserTokenRange args, bool counters) {
+CSSValue* ConsumeCounterContent(CSSParserTokenRange args,
+ const CSSParserContext& context,
+ bool counters) {
CSSCustomIdentValue* identifier =
- CSSPropertyParserHelpers::ConsumeCustomIdent(args);
+ css_property_parser_helpers::ConsumeCustomIdent(args, context);
if (!identifier)
return nullptr;
@@ -45,7 +47,7 @@ CSSValue* ConsumeCounterContent(CSSParserTokenRange args, bool counters) {
if (!counters) {
separator = CSSStringValue::Create(String());
} else {
- if (!CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) ||
+ if (!css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args) ||
args.Peek().GetType() != kStringToken)
return nullptr;
separator = CSSStringValue::Create(
@@ -53,12 +55,12 @@ CSSValue* ConsumeCounterContent(CSSParserTokenRange args, bool counters) {
}
CSSIdentifierValue* list_style = nullptr;
- if (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) {
+ if (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(args)) {
CSSValueID id = args.Peek().Id();
if ((id != CSSValueNone &&
(id < CSSValueDisc || id > CSSValueKatakanaIroha)))
return nullptr;
- list_style = CSSPropertyParserHelpers::ConsumeIdent(args);
+ list_style = css_property_parser_helpers::ConsumeIdent(args);
} else {
list_style = CSSIdentifierValue::Create(CSSValueDecimal);
}
@@ -69,37 +71,38 @@ CSSValue* ConsumeCounterContent(CSSParserTokenRange args, bool counters) {
}
} // namespace
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Content::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueNone, CSSValueNormal>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueNone, CSSValueNormal>(
range.Peek().Id()))
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* values = CSSValueList::CreateSpaceSeparated();
do {
CSSValue* parsed_value =
- CSSPropertyParserHelpers::ConsumeImage(range, &context);
+ css_property_parser_helpers::ConsumeImage(range, &context);
if (!parsed_value) {
- parsed_value = CSSPropertyParserHelpers::ConsumeIdent<
+ parsed_value = css_property_parser_helpers::ConsumeIdent<
CSSValueOpenQuote, CSSValueCloseQuote, CSSValueNoOpenQuote,
CSSValueNoCloseQuote>(range);
}
if (!parsed_value)
- parsed_value = CSSPropertyParserHelpers::ConsumeString(range);
+ parsed_value = css_property_parser_helpers::ConsumeString(range);
if (!parsed_value) {
if (range.Peek().FunctionId() == CSSValueAttr) {
parsed_value = ConsumeAttr(
- CSSPropertyParserHelpers::ConsumeFunction(range), context);
+ css_property_parser_helpers::ConsumeFunction(range), context);
} else if (range.Peek().FunctionId() == CSSValueCounter) {
parsed_value = ConsumeCounterContent(
- CSSPropertyParserHelpers::ConsumeFunction(range), false);
+ css_property_parser_helpers::ConsumeFunction(range), context,
+ false);
} else if (range.Peek().FunctionId() == CSSValueCounters) {
parsed_value = ConsumeCounterContent(
- CSSPropertyParserHelpers::ConsumeFunction(range), true);
+ css_property_parser_helpers::ConsumeFunction(range), context, true);
}
if (!parsed_value)
return nullptr;
@@ -209,5 +212,5 @@ void Content::ApplyValue(StyleResolverState& state,
state.Style()->SetContent(first_content);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_increment_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_increment_custom.cc
index 7d28408aa67..d93128e1cc1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_increment_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_increment_custom.cc
@@ -9,15 +9,16 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const int kCounterIncrementDefaultValue = 1;
const CSSValue* CounterIncrement::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeCounter(range, kCounterIncrementDefaultValue);
+ return css_parsing_utils::ConsumeCounter(range, context,
+ kCounterIncrementDefaultValue);
}
const CSSValue* CounterIncrement::CSSValueFromComputedStyleInternal(
@@ -29,5 +30,5 @@ const CSSValue* CounterIncrement::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForCounterDirectives(style, true);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_reset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_reset_custom.cc
index 5784e093cf4..04a48a00e80 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_reset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/counter_reset_custom.cc
@@ -9,15 +9,16 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const int kCounterResetDefaultValue = 0;
const CSSValue* CounterReset::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeCounter(range, kCounterResetDefaultValue);
+ return css_parsing_utils::ConsumeCounter(range, context,
+ kCounterResetDefaultValue);
}
const CSSValue* CounterReset::CSSValueFromComputedStyleInternal(
@@ -29,5 +30,5 @@ const CSSValue* CounterReset::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForCounterDirectives(style, false);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/cursor_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/cursor_custom.cc
index ae8607ec0ff..4b93b78aa24 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/cursor_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/cursor_custom.cc
@@ -13,22 +13,23 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Cursor::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
bool in_quirks_mode = IsQuirksModeBehavior(context.Mode());
CSSValueList* list = nullptr;
- while (CSSValue* image = CSSPropertyParserHelpers::ConsumeImage(
- range, &context,
- CSSPropertyParserHelpers::ConsumeGeneratedImagePolicy::kForbid)) {
+ while (
+ CSSValue* image = css_property_parser_helpers::ConsumeImage(
+ range, &context,
+ css_property_parser_helpers::ConsumeGeneratedImagePolicy::kForbid)) {
double num;
IntPoint hot_spot(-1, -1);
bool hot_spot_specified = false;
- if (CSSPropertyParserHelpers::ConsumeNumberRaw(range, num)) {
+ if (css_property_parser_helpers::ConsumeNumberRaw(range, num)) {
hot_spot.SetX(clampTo<int>(num));
- if (!CSSPropertyParserHelpers::ConsumeNumberRaw(range, num))
+ if (!css_property_parser_helpers::ConsumeNumberRaw(range, num))
return nullptr;
hot_spot.SetY(clampTo<int>(num));
hot_spot_specified = true;
@@ -39,7 +40,7 @@ const CSSValue* Cursor::ParseSingleValue(CSSParserTokenRange& range,
list->Append(*cssvalue::CSSCursorImageValue::Create(
*image, hot_spot_specified, hot_spot));
- if (!CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range))
return nullptr;
}
@@ -62,7 +63,7 @@ const CSSValue* Cursor::ParseSingleValue(CSSParserTokenRange& range,
range.ConsumeIncludingWhitespace();
} else if ((id >= CSSValueAuto && id <= CSSValueWebkitZoomOut) ||
id == CSSValueCopy || id == CSSValueNone) {
- cursor_type = CSSPropertyParserHelpers::ConsumeIdent(range);
+ cursor_type = css_property_parser_helpers::ConsumeIdent(range);
} else {
return nullptr;
}
@@ -131,5 +132,5 @@ void Cursor::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc
new file mode 100644
index 00000000000..f139d170b76
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc
@@ -0,0 +1,144 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h"
+
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h"
+#include "third_party/blink/renderer/core/css/property_registration.h"
+#include "third_party/blink/renderer/core/css/property_registry.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
+
+namespace blink {
+
+CustomProperty::CustomProperty(const AtomicString& name,
+ const Document& document)
+ : name_(name), registration_(PropertyRegistration::From(&document, name)) {}
+
+CustomProperty::CustomProperty(const AtomicString& name,
+ const PropertyRegistry* registry)
+ : name_(name),
+ registration_(registry ? registry->Registration(name) : nullptr) {}
+
+bool CustomProperty::IsInherited() const {
+ return !registration_ || registration_->Inherits();
+}
+
+const AtomicString& CustomProperty::GetPropertyNameAtomicString() const {
+ return name_;
+}
+
+void CustomProperty::ApplyInitial(StyleResolverState& state) const {
+ state.Style()->RemoveVariable(name_, IsInherited());
+}
+
+void CustomProperty::ApplyInherit(StyleResolverState& state) const {
+ bool is_inherited_property = IsInherited();
+ state.Style()->RemoveVariable(name_, is_inherited_property);
+
+ CSSVariableData* parent_value =
+ state.ParentStyle()->GetVariable(name_, is_inherited_property);
+
+ if (!parent_value)
+ return;
+
+ state.Style()->SetVariable(name_, parent_value, is_inherited_property);
+
+ if (registration_) {
+ const CSSValue* parent_css_value =
+ parent_value ? state.ParentStyle()->GetNonInitialRegisteredVariable(
+ name_, is_inherited_property)
+ : nullptr;
+ state.Style()->SetRegisteredVariable(name_, parent_css_value,
+ is_inherited_property);
+ }
+}
+
+void CustomProperty::ApplyValue(StyleResolverState& state,
+ const CSSValue& value) const {
+ const CSSCustomPropertyDeclaration& declaration =
+ ToCSSCustomPropertyDeclaration(value);
+
+ bool is_inherited_property = IsInherited();
+ bool initial = declaration.IsInitial(is_inherited_property);
+ bool inherit = declaration.IsInherit(is_inherited_property);
+ DCHECK(!(initial && inherit));
+
+ // TODO(andruud): Use regular initial/inherit dispatch in StyleBuilder
+ // once custom properties are Ribbonized.
+ if (initial) {
+ ApplyInitial(state);
+ } else if (inherit) {
+ ApplyInherit(state);
+ } else {
+ state.Style()->SetVariable(name_, declaration.Value(),
+ is_inherited_property);
+ if (registration_) {
+ state.Style()->SetRegisteredVariable(name_, nullptr,
+ is_inherited_property);
+ }
+ }
+}
+
+const CSSValue* CustomProperty::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ using VariableMode = CSSParserLocalContext::VariableMode;
+
+ switch (local_context.GetVariableMode()) {
+ case VariableMode::kTyped:
+ return ParseTyped(range, context, local_context);
+ case VariableMode::kUntyped:
+ return ParseUntyped(range, context, local_context);
+ case VariableMode::kValidatedUntyped:
+ if (registration_ && !ParseTyped(range, context, local_context))
+ return nullptr;
+ return ParseUntyped(range, context, local_context);
+ }
+}
+
+const CSSValue* CustomProperty::CSSValueFromComputedStyleInternal(
+ const ComputedStyle& style,
+ const SVGComputedStyle&,
+ const LayoutObject*,
+ Node* styled_node,
+ bool allow_visited_style) const {
+ if (registration_) {
+ const CSSValue* value = style.GetRegisteredVariable(name_, IsInherited());
+ if (value)
+ return value;
+ // If we don't have CSSValue for this registered property, it means that
+ // that the property was not registered at the time |style| was calculated,
+ // hence we proceed with unregistered behavior.
+ }
+
+ CSSVariableData* data = style.GetVariable(name_, IsInherited());
+
+ if (!data)
+ return nullptr;
+
+ return CSSCustomPropertyDeclaration::Create(name_, data);
+}
+
+const CSSValue* CustomProperty::ParseUntyped(
+ CSSParserTokenRange range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return CSSVariableParser::ParseDeclarationValue(
+ name_, range, local_context.IsAnimationTainted(), context);
+}
+
+const CSSValue* CustomProperty::ParseTyped(
+ CSSParserTokenRange range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ if (!registration_)
+ return ParseUntyped(range, context, local_context);
+ return registration_->Syntax().Parse(range, &context,
+ local_context.IsAnimationTainted());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.h b/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.h
new file mode 100644
index 00000000000..57a2f0fb393
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.h
@@ -0,0 +1,65 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHANDS_CUSTOM_PROPERTY_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHANDS_CUSTOM_PROPERTY_H_
+
+#include "third_party/blink/renderer/core/css/properties/longhands/variable.h"
+
+#include "third_party/blink/renderer/core/css/property_registration.h"
+
+namespace blink {
+
+class PropertyRegistry;
+
+// Represents a custom property (both registered and unregistered).
+//
+// Unlike all other CSSProperty instances, instances of this class are
+// allocated dynamically on demand. (See CSSPropertyRef).
+//
+// TODO(andruud): Move functionality from Variable to here, and eventually
+// remove Variable.
+class CORE_EXPORT CustomProperty : public Variable {
+ DISALLOW_NEW();
+
+ public:
+ CustomProperty() = default;
+ CustomProperty(const AtomicString& name, const Document&);
+ CustomProperty(const AtomicString& name, const PropertyRegistry*);
+
+ bool IsInherited() const override;
+ const AtomicString& GetPropertyNameAtomicString() const override;
+
+ void ApplyInitial(StyleResolverState&) const override;
+ void ApplyInherit(StyleResolverState&) const override;
+ void ApplyValue(StyleResolverState&, const CSSValue&) const override;
+
+ const CSSValue* ParseSingleValue(CSSParserTokenRange&,
+ const CSSParserContext&,
+ const CSSParserLocalContext&) const override;
+
+ const CSSValue* CSSValueFromComputedStyleInternal(
+ const ComputedStyle&,
+ const SVGComputedStyle&,
+ const LayoutObject*,
+ Node* styled_node,
+ bool allow_visited_style) const override;
+
+ void Trace(blink::Visitor* visitor) { visitor->Trace(registration_); }
+
+ private:
+ const CSSValue* ParseUntyped(CSSParserTokenRange,
+ const CSSParserContext&,
+ const CSSParserLocalContext&) const;
+ const CSSValue* ParseTyped(CSSParserTokenRange,
+ const CSSParserContext&,
+ const CSSParserLocalContext&) const;
+
+ AtomicString name_;
+ Member<const PropertyRegistration> registration_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_LONGHANDS_CUSTOM_PROPERTY_H_
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property_test.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property_test.cc
new file mode 100644
index 00000000000..9224db4b406
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property_test.cc
@@ -0,0 +1,197 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
+#include "third_party/blink/renderer/core/html/html_element.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+
+namespace blink {
+
+using namespace css_test_helpers;
+using VariableMode = CSSParserLocalContext::VariableMode;
+
+namespace {
+
+class CustomPropertyTest : public PageTestBase {
+ public:
+ void SetElementWithStyle(const String& value) {
+ GetDocument().body()->SetInnerHTMLFromString("<div id='target' style='" +
+ value + "'></div>");
+ UpdateAllLifecyclePhasesForTest();
+ }
+
+ const CSSValue* GetComputedValue(const CustomProperty& property) {
+ Element* node = GetDocument().getElementById("target");
+ return property.CSSValueFromComputedStyle(node->ComputedStyleRef(),
+ nullptr /* layout_object*/, node,
+ false /* allow_visisted_style */);
+ }
+
+ const CSSValue* ParseValue(const Longhand& property,
+ const String& value,
+ const CSSParserLocalContext& local_context) {
+ CSSTokenizer tokenizer(value);
+ const auto tokens = tokenizer.TokenizeToEOF();
+ CSSParserTokenRange range(tokens);
+ CSSParserContext* context = CSSParserContext::Create(GetDocument());
+ return property.ParseSingleValue(range, *context, local_context);
+ }
+};
+
+} // namespace
+
+TEST_F(CustomPropertyTest, UnregisteredPropertyIsInherited) {
+ CustomProperty property("--x", GetDocument());
+ EXPECT_TRUE(property.IsInherited());
+}
+
+TEST_F(CustomPropertyTest, RegisteredNonInheritedPropertyIsNotInherited) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "42px", false);
+ CustomProperty property("--x", GetDocument());
+ EXPECT_FALSE(property.IsInherited());
+}
+
+TEST_F(CustomPropertyTest, RegisteredInheritedPropertyIsInherited) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "42px", true);
+ CustomProperty property("--x", GetDocument());
+ EXPECT_TRUE(property.IsInherited());
+}
+
+TEST_F(CustomPropertyTest, StaticVariableInstance) {
+ CustomProperty property("--x", GetDocument());
+ EXPECT_FALSE(Variable::IsStaticInstance(property));
+ EXPECT_TRUE(Variable::IsStaticInstance(GetCSSPropertyVariable()));
+}
+
+TEST_F(CustomPropertyTest, PropertyID) {
+ CustomProperty property("--x", GetDocument());
+ EXPECT_EQ(CSSPropertyVariable, property.PropertyID());
+}
+
+TEST_F(CustomPropertyTest, GetPropertyNameAtomicString) {
+ CustomProperty property("--x", GetDocument());
+ EXPECT_EQ(AtomicString("--x"), property.GetPropertyNameAtomicString());
+}
+
+TEST_F(CustomPropertyTest, ComputedCSSValueUnregistered) {
+ CustomProperty property("--x", GetDocument());
+ SetElementWithStyle("--x:foo");
+ const CSSValue* value = GetComputedValue(property);
+ EXPECT_TRUE(value->IsCustomPropertyDeclaration());
+ EXPECT_EQ("foo", value->CssText());
+}
+
+TEST_F(CustomPropertyTest, ComputedCSSValueInherited) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", true);
+ CustomProperty property("--x", GetDocument());
+ SetElementWithStyle("--x:100px");
+ const CSSValue* value = GetComputedValue(property);
+ ASSERT_TRUE(value->IsPrimitiveValue());
+ const CSSPrimitiveValue* primitive_value = ToCSSPrimitiveValue(value);
+ EXPECT_EQ(100, primitive_value->GetIntValue());
+}
+
+TEST_F(CustomPropertyTest, ComputedCSSValueNonInherited) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ CustomProperty property("--x", GetDocument());
+ SetElementWithStyle("--x:100px");
+ const CSSValue* value = GetComputedValue(property);
+ ASSERT_TRUE(value->IsPrimitiveValue());
+ const CSSPrimitiveValue* primitive_value = ToCSSPrimitiveValue(value);
+ EXPECT_EQ(100, primitive_value->GetIntValue());
+}
+
+TEST_F(CustomPropertyTest, ComputedCSSValueInitial) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "100px", false);
+ CustomProperty property("--x", GetDocument());
+ SetElementWithStyle(""); // Do not apply --x.
+ const CSSValue* value = GetComputedValue(property);
+ ASSERT_TRUE(value->IsPrimitiveValue());
+ const CSSPrimitiveValue* primitive_value = ToCSSPrimitiveValue(value);
+ EXPECT_EQ(100, primitive_value->GetIntValue());
+}
+
+TEST_F(CustomPropertyTest, ComputedCSSValueEmptyInitial) {
+ CustomProperty property("--x", GetDocument());
+ SetElementWithStyle(""); // Do not apply --x.
+ const CSSValue* value = GetComputedValue(property);
+ EXPECT_FALSE(value);
+}
+
+TEST_F(CustomPropertyTest, ComputedCSSValueLateRegistration) {
+ CustomProperty property("--x", GetDocument());
+ SetElementWithStyle("--x:100px");
+ RegisterProperty(GetDocument(), "--x", "<length>", "100px", false);
+ // The property was not registered when the style was computed, hence the
+ // computed value should be what we expect for an unregistered property.
+ const CSSValue* value = GetComputedValue(property);
+ EXPECT_TRUE(value->IsCustomPropertyDeclaration());
+ EXPECT_EQ("100px", value->CssText());
+}
+
+TEST_F(CustomPropertyTest, ParseSingleValueUnregistered) {
+ CustomProperty property("--x", GetDocument());
+ const CSSValue* value =
+ ParseValue(property, "100px", CSSParserLocalContext());
+ ASSERT_TRUE(value->IsCustomPropertyDeclaration());
+ EXPECT_EQ("100px", value->CssText());
+}
+
+TEST_F(CustomPropertyTest, ParseSingleValueAnimationTainted) {
+ CustomProperty property("--x", GetDocument());
+ const CSSValue* value1 = ParseValue(
+ property, "100px", CSSParserLocalContext().WithAnimationTainted(true));
+ const CSSValue* value2 = ParseValue(
+ property, "100px", CSSParserLocalContext().WithAnimationTainted(false));
+
+ EXPECT_TRUE(
+ ToCSSCustomPropertyDeclaration(value1)->Value()->IsAnimationTainted());
+ EXPECT_FALSE(
+ ToCSSCustomPropertyDeclaration(value2)->Value()->IsAnimationTainted());
+}
+
+TEST_F(CustomPropertyTest, ParseSingleValueTyped) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ CustomProperty property("--x", GetDocument());
+ const CSSValue* value1 =
+ ParseValue(property, "100px", CSSParserLocalContext());
+ EXPECT_TRUE(value1->IsPrimitiveValue());
+ EXPECT_EQ(100, ToCSSPrimitiveValue(value1)->GetIntValue());
+
+ const CSSValue* value2 =
+ ParseValue(property, "maroon", CSSParserLocalContext());
+ EXPECT_FALSE(value2);
+}
+
+TEST_F(CustomPropertyTest, ParseSingleValueUntyped) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ CustomProperty property("--x", GetDocument());
+ const CSSValue* value = ParseValue(
+ property, "maroon",
+ CSSParserLocalContext().WithVariableMode(VariableMode::kUntyped));
+ ASSERT_TRUE(value->IsCustomPropertyDeclaration());
+ EXPECT_EQ("maroon", value->CssText());
+}
+
+TEST_F(CustomPropertyTest, ParseSingleValueValidatedUntyped) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ CustomProperty property("--x", GetDocument());
+ auto local_context =
+ CSSParserLocalContext().WithVariableMode(VariableMode::kValidatedUntyped);
+ const CSSValue* value1 = ParseValue(property, "100px", local_context);
+ ASSERT_TRUE(value1->IsCustomPropertyDeclaration());
+ EXPECT_EQ("100px", value1->CssText());
+
+ const CSSValue* value2 = ParseValue(property, "maroon", local_context);
+ EXPECT_FALSE(value2);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/cx_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/cx_custom.cc
index 2acdba943a3..517c04ccd01 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/cx_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/cx_custom.cc
@@ -8,14 +8,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Cx::ParseSingleValue(CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeAll);
}
const CSSValue* Cx::CSSValueFromComputedStyleInternal(
@@ -28,5 +27,5 @@ const CSSValue* Cx::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/cy_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/cy_custom.cc
index e3bc5b1dfab..97b5a99fba0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/cy_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/cy_custom.cc
@@ -8,14 +8,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Cy::ParseSingleValue(CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeAll);
}
const CSSValue* Cy::CSSValueFromComputedStyleInternal(
@@ -28,5 +27,5 @@ const CSSValue* Cy::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/d_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/d_custom.cc
index 0b56e58d910..c24d8c19491 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/d_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/d_custom.cc
@@ -8,12 +8,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* D::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumePathOrNone(range);
+ return css_parsing_utils::ConsumePathOrNone(range);
}
const CSSValue* D::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* D::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueNone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/direction_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/direction_custom.cc
index 7cd95e7323f..13c848354db 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/direction_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/direction_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/direction.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Direction::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -22,5 +22,5 @@ void Direction::ApplyValue(StyleResolverState& state,
ToCSSIdentifierValue(value).ConvertTo<TextDirection>());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/display_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/display_custom.cc
index 4d8e2fc6825..123540f454d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/display_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/display_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Display::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
@@ -30,9 +30,9 @@ const CSSValue* Display::ParseSingleValue(CSSParserTokenRange& range,
CSSParserTokenRange range_copy = range;
CSSParserTokenRange args =
- CSSPropertyParserHelpers::ConsumeFunction(range_copy);
+ css_property_parser_helpers::ConsumeFunction(range_copy);
CSSCustomIdentValue* name =
- CSSPropertyParserHelpers::ConsumeCustomIdent(args);
+ css_property_parser_helpers::ConsumeCustomIdent(args, context);
// If we didn't get a custom-ident or didn't exhaust the function arguments
// return nothing.
@@ -92,5 +92,5 @@ void Display::ApplyValue(StyleResolverState& state,
state.Style()->SetDisplayLayoutCustomName(layout_function_value.GetName());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/dominant_baseline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/dominant_baseline_custom.cc
index 85123ec2db7..cb4b4550253 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/dominant_baseline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/dominant_baseline_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/dominant_baseline.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* DominantBaseline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* DominantBaseline::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.DominantBaseline());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/empty_cells_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/empty_cells_custom.cc
index d12909378d7..cefac2dbff9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/empty_cells_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/empty_cells_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/empty_cells.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* EmptyCells::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* EmptyCells::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.EmptyCells());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_custom.cc
index 4f3bff29011..f266db3dd5a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_custom.cc
@@ -9,12 +9,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Fill::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParsePaintStroke(range, context);
+ return css_parsing_utils::ParsePaintStroke(range, context);
}
const CSSValue* Fill::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* Fill::CSSValueFromComputedStyleInternal(
svg_style.FillPaint(), style.GetColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_opacity_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_opacity_custom.cc
index 50809fc6b35..4ff579ef5aa 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_opacity_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_opacity_custom.cc
@@ -11,13 +11,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FillOpacity::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* FillOpacity::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* FillOpacity::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_rule_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_rule_custom.cc
index c496cdf7b7b..90e993eef6d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_rule_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/fill_rule_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/fill_rule.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FillRule::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* FillRule::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.FillRule());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/filter_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/filter_custom.cc
index 8ceee228f32..74313572334 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/filter_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/filter_custom.cc
@@ -10,12 +10,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Filter::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeFilterFunctionList(range, context);
+ return css_property_parser_helpers::ConsumeFilterFunctionList(range, context);
}
const CSSValue* Filter::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* Filter::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFilter(style, style.Filter());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_basis_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_basis_custom.cc
index fecc16d65ef..f186c4087b1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_basis_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_basis_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FlexBasis::ParseSingleValue(
CSSParserTokenRange& range,
@@ -17,8 +17,8 @@ const CSSValue* FlexBasis::ParseSingleValue(
const CSSParserLocalContext&) const {
// FIXME: Support intrinsic dimensions too.
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative);
}
@@ -32,5 +32,5 @@ const CSSValue* FlexBasis::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_direction_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_direction_custom.cc
index 47f5aa587e3..50bd0037b7e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_direction_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_direction_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/flex_direction.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FlexDirection::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* FlexDirection::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.FlexDirection());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_grow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_grow_custom.cc
index 144a0ec1bd5..7636c88f28c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_grow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_grow_custom.cc
@@ -6,15 +6,16 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FlexGrow::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
}
const CSSValue* FlexGrow::CSSValueFromComputedStyleInternal(
@@ -27,5 +28,5 @@ const CSSValue* FlexGrow::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_shrink_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_shrink_custom.cc
index f98dba4ab7c..6268696a385 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_shrink_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_shrink_custom.cc
@@ -6,16 +6,17 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FlexShrink::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
}
const CSSValue* FlexShrink::CSSValueFromComputedStyleInternal(
@@ -28,5 +29,5 @@ const CSSValue* FlexShrink::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_wrap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_wrap_custom.cc
index 2c604c97966..4ecb245a842 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_wrap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flex_wrap_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/flex_wrap.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FlexWrap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* FlexWrap::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.FlexWrap());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/float_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/float_custom.cc
index 37c2bd54e46..3eacdda8eee 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/float_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/float_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Float::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,27 +20,5 @@ const CSSValue* Float::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.Floating());
}
-void Float::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
- const CSSIdentifierValue& identifier_value = ToCSSIdentifierValue(value);
-
- EFloat f;
- CSSValueID id = identifier_value.GetValueID();
- switch (id) {
- case CSSValueInlineStart:
- case CSSValueInlineEnd:
- if ((id == CSSValueInlineStart) ==
- (state.Style()->Direction() == TextDirection::kLtr)) {
- f = EFloat::kLeft;
- } else {
- f = EFloat::kRight;
- }
- break;
- default:
- f = identifier_value.ConvertTo<EFloat>();
- break;
- }
- state.Style()->SetFloating(f);
-}
-
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_color_custom.cc
index a72ef4f7a08..6885c49ee22 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_color_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FloodColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color FloodColor::ColorIncludingFallback(
@@ -37,5 +37,5 @@ const CSSValue* FloodColor::CSSValueFromComputedStyleInternal(
style.FloodColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_opacity_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_opacity_custom.cc
index 07130aeb339..768b47fc2ab 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_opacity_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/flood_opacity_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FloodOpacity::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* FloodOpacity::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* FloodOpacity::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_family_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_family_custom.cc
index 6b4097039ca..e417f758528 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_family_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_family_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontFamily::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeFontFamily(range);
+ return css_parsing_utils::ConsumeFontFamily(range);
}
const CSSValue* FontFamily::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* FontFamily::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontFamily(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc
index 41f0a944f37..68ddb3d10c0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontFeatureSettings::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeFontFeatureSettings(range);
+ return css_parsing_utils::ConsumeFontFeatureSettings(range);
}
const CSSValue* FontFeatureSettings::CSSValueFromComputedStyleInternal(
@@ -38,5 +38,5 @@ const CSSValue* FontFeatureSettings::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_kerning_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_kerning_custom.cc
index 56d651114fa..3d7d64c6a41 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_kerning_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_kerning_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontKerning::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -18,5 +18,5 @@ const CSSValue* FontKerning::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetFontDescription().GetKerning());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_adjust_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_adjust_custom.cc
index 6c66e137f1b..182ee12b354 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_adjust_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_adjust_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontSizeAdjust::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,9 @@ const CSSValue* FontSizeAdjust::ParseSingleValue(
const CSSParserLocalContext&) const {
DCHECK(RuntimeEnabledFeatures::CSSFontSizeAdjustEnabled());
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
}
const CSSValue* FontSizeAdjust::CSSValueFromComputedStyleInternal(
@@ -35,5 +36,5 @@ const CSSValue* FontSizeAdjust::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueNone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_custom.cc
index 70387fa1cb3..c7949a255a0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_size_custom.cc
@@ -11,13 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontSize::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeFontSize(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeFontSize(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
const CSSValue* FontSize::CSSValueFromComputedStyleInternal(
@@ -29,5 +30,5 @@ const CSSValue* FontSize::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontSize(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_stretch_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_stretch_custom.cc
index 8de80b777fd..e84ab2b5de8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_stretch_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_stretch_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontStretch::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeFontStretch(range, context.Mode());
+ return css_parsing_utils::ConsumeFontStretch(range, context.Mode());
}
const CSSValue* FontStretch::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* FontStretch::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontStretch(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_style_custom.cc
index f4239d0f68b..0fece06ceda 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_style_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontStyle::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeFontStyle(range, context.Mode());
+ return css_parsing_utils::ConsumeFontStyle(range, context.Mode());
}
const CSSValue* FontStyle::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* FontStyle::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontStyle(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_caps_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_caps_custom.cc
index a1784986c48..d129401f182 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_caps_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_caps_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontVariantCaps::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeIdent<
+ return css_property_parser_helpers::ConsumeIdent<
CSSValueNormal, CSSValueSmallCaps, CSSValueAllSmallCaps,
CSSValuePetiteCaps, CSSValueAllPetiteCaps, CSSValueUnicase,
CSSValueTitlingCaps>(range);
@@ -31,5 +31,5 @@ const CSSValue* FontVariantCaps::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontVariantCaps(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_east_asian_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_east_asian_custom.cc
index ada95bfb47e..4fad3ff66eb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_east_asian_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_east_asian_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontVariantEastAsian::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
FontVariantEastAsianParser east_asian_parser;
do {
@@ -38,5 +38,5 @@ const CSSValue* FontVariantEastAsian::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontVariantEastAsian(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_ligatures_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_ligatures_custom.cc
index 533510c52d8..3d0f7921443 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_ligatures_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_ligatures_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontVariantLigatures::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNormal || range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
FontVariantLigaturesParser ligatures_parser;
do {
@@ -38,5 +38,5 @@ const CSSValue* FontVariantLigatures::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontVariantLigatures(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_numeric_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_numeric_custom.cc
index 4f781142443..999082a7215 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_numeric_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variant_numeric_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontVariantNumeric::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
FontVariantNumericParser numeric_parser;
do {
@@ -38,5 +38,5 @@ const CSSValue* FontVariantNumeric::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontVariantNumeric(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc
index 6c71543ecad..96c5224f019 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc
@@ -35,21 +35,21 @@ cssvalue::CSSFontVariationValue* ConsumeFontVariationTag(
}
double tag_value = 0;
- if (!CSSPropertyParserHelpers::ConsumeNumberRaw(range, tag_value))
+ if (!css_property_parser_helpers::ConsumeNumberRaw(range, tag_value))
return nullptr;
return cssvalue::CSSFontVariationValue::Create(tag,
clampTo<float>(tag_value));
}
} // namespace
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontVariationSettings::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* variation_settings = CSSValueList::CreateCommaSeparated();
do {
cssvalue::CSSFontVariationValue* font_variation_value =
@@ -57,7 +57,7 @@ const CSSValue* FontVariationSettings::ParseSingleValue(
if (!font_variation_value)
return nullptr;
variation_settings->Append(*font_variation_value);
- } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range));
+ } while (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range));
return variation_settings;
}
@@ -82,5 +82,5 @@ const CSSValue* FontVariationSettings::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_weight_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_weight_custom.cc
index fd211a3cabf..45f37e6d6e5 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/font_weight_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/font_weight_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* FontWeight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeFontWeight(range, context.Mode());
+ return css_parsing_utils::ConsumeFontWeight(range, context.Mode());
}
const CSSValue* FontWeight::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* FontWeight::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFontWeight(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_columns_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_columns_custom.cc
index c165ed1ab18..b1cf05a1232 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_columns_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_columns_custom.cc
@@ -10,14 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridAutoColumns::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridTrackList(
- range, context.Mode(), CSSParsingUtils::TrackListType::kGridAuto);
+ return css_parsing_utils::ConsumeGridTrackList(
+ range, context, context.Mode(),
+ css_parsing_utils::TrackListType::kGridAuto);
}
// Specs mention that getComputedStyle() should return the used value of the
@@ -36,5 +37,5 @@ const CSSValue* GridAutoColumns::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGridTrackSizeList(kForColumns, style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_flow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_flow_custom.cc
index d45027906c4..5120a20c50a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_flow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_flow_custom.cc
@@ -10,20 +10,20 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridAutoFlow::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
CSSIdentifierValue* row_or_column_value =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueRow, CSSValueColumn>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueRow, CSSValueColumn>(
range);
CSSIdentifierValue* dense_algorithm =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueDense>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueDense>(range);
if (!row_or_column_value) {
row_or_column_value =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueRow, CSSValueColumn>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueRow, CSSValueColumn>(
range);
if (!row_or_column_value && !dense_algorithm)
return nullptr;
@@ -69,5 +69,5 @@ const CSSValue* GridAutoFlow::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_rows_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_rows_custom.cc
index 455be520703..cb690bf9bc9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_rows_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_auto_rows_custom.cc
@@ -10,14 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridAutoRows::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridTrackList(
- range, context.Mode(), CSSParsingUtils::TrackListType::kGridAuto);
+ return css_parsing_utils::ConsumeGridTrackList(
+ range, context, context.Mode(),
+ css_parsing_utils::TrackListType::kGridAuto);
}
const CSSValue* GridAutoRows::CSSValueFromComputedStyleInternal(
@@ -29,5 +30,5 @@ const CSSValue* GridAutoRows::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGridTrackSizeList(kForRows, style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_end_custom.cc
index 69c716ba34d..7ac7e9760b5 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_end_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridColumnEnd::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridLine(range);
+ return css_parsing_utils::ConsumeGridLine(range, context);
}
const CSSValue* GridColumnEnd::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* GridColumnEnd::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGridPosition(style.GridColumnEnd());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_start_custom.cc
index db39b83b1c9..d1a36822ad6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_column_start_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridColumnStart::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridLine(range);
+ return css_parsing_utils::ConsumeGridLine(range, context);
}
const CSSValue* GridColumnStart::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* GridColumnStart::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGridPosition(style.GridColumnStart());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_end_custom.cc
index 84515376ca8..df82567cdeb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_end_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridRowEnd::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridLine(range);
+ return css_parsing_utils::ConsumeGridLine(range, context);
}
const CSSValue* GridRowEnd::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* GridRowEnd::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGridPosition(style.GridRowEnd());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_start_custom.cc
index c104b9502ab..c7263362aff 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_row_start_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridRowStart::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridLine(range);
+ return css_parsing_utils::ConsumeGridLine(range, context);
}
const CSSValue* GridRowStart::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* GridRowStart::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGridPosition(style.GridRowStart());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_areas_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_areas_custom.cc
index 67153f84505..17aee7d456b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_areas_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_areas_custom.cc
@@ -16,21 +16,21 @@
#include "third_party/blink/renderer/core/style/grid_area.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridTemplateAreas::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
NamedGridAreaMap grid_area_map;
size_t row_count = 0;
size_t column_count = 0;
while (range.Peek().GetType() == kStringToken) {
- if (!CSSParsingUtils::ParseGridTemplateAreasRow(
+ if (!css_parsing_utils::ParseGridTemplateAreasRow(
range.ConsumeIncludingWhitespace().Value().ToString(),
grid_area_map, row_count, column_count))
return nullptr;
@@ -109,5 +109,5 @@ void GridTemplateAreas::ApplyValue(StyleResolverState& state,
grid_template_areas_value.ColumnCount());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_columns_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_columns_custom.cc
index d928c37f805..629599b8c55 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_columns_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_columns_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridTemplateColumns::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridTemplatesRowsOrColumns(range,
- context.Mode());
+ return css_parsing_utils::ConsumeGridTemplatesRowsOrColumns(range, context,
+ context.Mode());
}
bool GridTemplateColumns::IsLayoutDependent(const ComputedStyle* style,
@@ -36,5 +36,5 @@ const CSSValue* GridTemplateColumns::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_rows_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_rows_custom.cc
index 9902a4c4384..5fff8e567b4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_rows_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/grid_template_rows_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* GridTemplateRows::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGridTemplatesRowsOrColumns(range,
- context.Mode());
+ return css_parsing_utils::ConsumeGridTemplatesRowsOrColumns(range, context,
+ context.Mode());
}
bool GridTemplateRows::IsLayoutDependent(const ComputedStyle* style,
@@ -36,5 +36,5 @@ const CSSValue* GridTemplateRows::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/height_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/height_custom.cc
index e2e707a71d9..4c843c38f23 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/height_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/height_custom.cc
@@ -11,13 +11,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Height::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeWidthOrHeight(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool Height::IsLayoutDependent(const ComputedStyle* style,
@@ -39,5 +39,5 @@ const CSSValue* Height::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/hyphens_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/hyphens_custom.cc
index d38676b1815..126d04077d9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/hyphens_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/hyphens_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/hyphens.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Hyphens::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* Hyphens::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetHyphens());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/image_orientation_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/image_orientation_custom.cc
index 0c21d6cd7f2..839465070f7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/image_orientation_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/image_orientation_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ImageOrientation::ParseSingleValue(
CSSParserTokenRange& range,
@@ -19,9 +19,9 @@ const CSSValue* ImageOrientation::ParseSingleValue(
const CSSParserLocalContext&) const {
DCHECK(RuntimeEnabledFeatures::ImageOrientationEnabled());
if (range.Peek().Id() == CSSValueFromImage)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (range.Peek().GetType() != kNumberToken) {
- CSSPrimitiveValue* angle = CSSPropertyParserHelpers::ConsumeAngle(
+ CSSPrimitiveValue* angle = css_property_parser_helpers::ConsumeAngle(
range, &context, base::Optional<WebFeature>());
if (angle && angle->GetDoubleValue() == 0)
return angle;
@@ -40,5 +40,5 @@ const CSSValue* ImageOrientation::CSSValueFromComputedStyleInternal(
return CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kDegrees);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/image_rendering_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/image_rendering_custom.cc
index 2afb6b3902d..75bd3729492 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/image_rendering_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/image_rendering_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/image_rendering.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ImageRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ImageRendering::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.ImageRendering());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/inline_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/inline_size_custom.cc
index 5b7d8f892d8..0352962c3ad 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/inline_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/inline_size_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* InlineSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(range, context);
+ return css_parsing_utils::ConsumeWidthOrHeight(range, context);
}
bool InlineSize::IsLayoutDependent(const ComputedStyle* style,
@@ -23,5 +23,5 @@ bool InlineSize::IsLayoutDependent(const ComputedStyle* style,
return layout_object && layout_object->IsBox();
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_end_custom.cc
index 631aa57ae9e..fa897cfdc13 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_end_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* InsetBlockEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_start_custom.cc
index 27cbd329d83..0e86d55187a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_block_start_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* InsetBlockStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_end_custom.cc
index 6b1113d3795..fb265c3584d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_end_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* InsetInlineEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_start_custom.cc
index 2a394eba3d0..dd4b9b0b486 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/inset_inline_start_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* InsetInlineStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/isolation_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/isolation_custom.cc
index 7e3a5078bad..4e27da49414 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/isolation_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/isolation_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/isolation.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Isolation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* Isolation::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.Isolation());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_content_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_content_custom.cc
index 20bb4725139..0bada6ec34c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_content_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_content_custom.cc
@@ -9,19 +9,19 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* JustifyContent::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
// justify-content property does not allow the <baseline-position> values.
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueFirst, CSSValueLast,
- CSSValueBaseline>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueFirst, CSSValueLast,
+ CSSValueBaseline>(
range.Peek().Id()))
return nullptr;
- return CSSParsingUtils::ConsumeContentDistributionOverflowPosition(
- range, CSSParsingUtils::IsContentPositionOrLeftOrRightKeyword);
+ return css_parsing_utils::ConsumeContentDistributionOverflowPosition(
+ range, css_parsing_utils::IsContentPositionOrLeftOrRightKeyword);
}
const CSSValue* JustifyContent::CSSValueFromComputedStyleInternal(
@@ -35,5 +35,5 @@ const CSSValue* JustifyContent::CSSValueFromComputedStyleInternal(
style.JustifyContent());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_items_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_items_custom.cc
index 43e958f4ee8..327401ed601 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_items_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_items_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* JustifyItems::ParseSingleValue(
CSSParserTokenRange& range,
@@ -20,15 +20,18 @@ const CSSValue* JustifyItems::ParseSingleValue(
const CSSParserLocalContext&) const {
CSSParserTokenRange range_copy = range;
// justify-items property does not allow the 'auto' value.
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueAuto>(range.Peek().Id()))
+ if (css_property_parser_helpers::IdentMatches<CSSValueAuto>(
+ range.Peek().Id()))
return nullptr;
CSSIdentifierValue* legacy =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueLegacy>(range_copy);
+ css_property_parser_helpers::ConsumeIdent<CSSValueLegacy>(range_copy);
CSSIdentifierValue* position_keyword =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueCenter, CSSValueLeft,
- CSSValueRight>(range_copy);
- if (!legacy)
- legacy = CSSPropertyParserHelpers::ConsumeIdent<CSSValueLegacy>(range_copy);
+ css_property_parser_helpers::ConsumeIdent<CSSValueCenter, CSSValueLeft,
+ CSSValueRight>(range_copy);
+ if (!legacy) {
+ legacy =
+ css_property_parser_helpers::ConsumeIdent<CSSValueLegacy>(range_copy);
+ }
if (legacy) {
range = range_copy;
if (position_keyword) {
@@ -39,8 +42,8 @@ const CSSValue* JustifyItems::ParseSingleValue(
return legacy;
}
- return CSSParsingUtils::ConsumeSelfPositionOverflowPosition(
- range, CSSParsingUtils::IsSelfPositionOrLeftOrRightKeyword);
+ return css_parsing_utils::ConsumeSelfPositionOverflowPosition(
+ range, css_parsing_utils::IsSelfPositionOrLeftOrRightKeyword);
}
const CSSValue* JustifyItems::CSSValueFromComputedStyleInternal(
@@ -55,5 +58,5 @@ const CSSValue* JustifyItems::CSSValueFromComputedStyleInternal(
: style.JustifyItems());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_self_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_self_custom.cc
index 0cd0d27b556..68e13866043 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_self_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/justify_self_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* JustifySelf::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeSelfPositionOverflowPosition(
- range, CSSParsingUtils::IsSelfPositionOrLeftOrRightKeyword);
+ return css_parsing_utils::ConsumeSelfPositionOverflowPosition(
+ range, css_parsing_utils::IsSelfPositionOrLeftOrRightKeyword);
}
const CSSValue* JustifySelf::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* JustifySelf::CSSValueFromComputedStyleInternal(
style.JustifySelf());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/left_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/left_custom.cc
index 322894322db..e9f4074e5e4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/left_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/left_custom.cc
@@ -15,13 +15,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Left::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool Left::IsLayoutDependent(const ComputedStyle* style,
@@ -39,5 +40,5 @@ const CSSValue* Left::CSSValueFromComputedStyleInternal(
layout_object);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/letter_spacing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/letter_spacing_custom.cc
index 27c26b5c2df..612ec5b4c73 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/letter_spacing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/letter_spacing_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* LetterSpacing::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParseSpacing(range, context);
+ return css_parsing_utils::ParseSpacing(range, context);
}
const CSSValue* LetterSpacing::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* LetterSpacing::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.LetterSpacing(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/lighting_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/lighting_color_custom.cc
index 45ae29982d0..761f4f8b93c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/lighting_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/lighting_color_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* LightingColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color LightingColor::ColorIncludingFallback(
@@ -37,5 +37,5 @@ const CSSValue* LightingColor::CSSValueFromComputedStyleInternal(
style.LightingColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/line_break_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/line_break_custom.cc
index 010d62acc5d..c980562989a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/line_break_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/line_break_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/line_break.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* LineBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* LineBreak::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetLineBreak());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_custom.cc
index 0f6b4a24ad7..585a3f2b92a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* LineHeight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeLineHeight(range, context.Mode());
+ return css_parsing_utils::ConsumeLineHeight(range, context.Mode());
}
const CSSValue* LineHeight::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* LineHeight::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForLineHeight(style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_step_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_step_custom.cc
index 0f94c53db55..68f5ca47b7a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_step_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/line_height_step_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* LineHeightStep::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
+ kValueRangeNonNegative);
}
const CSSValue* LineHeightStep::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* LineHeightStep::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.LineHeightStep(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_image_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_image_custom.cc
index 8563f505af3..597e9890cfd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_image_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_image_custom.cc
@@ -11,13 +11,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ListStyleImage::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeImageOrNone(range, &context);
+ return css_property_parser_helpers::ConsumeImageOrNone(range, &context);
}
const CSSValue* ListStyleImage::CSSValueFromComputedStyleInternal(
@@ -37,5 +37,5 @@ void ListStyleImage::ApplyValue(StyleResolverState& state,
state.GetStyleImage(CSSPropertyListStyleImage, value));
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_position_custom.cc
index 984c1346f02..f723f944ba4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_position_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/list_style_position.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ListStylePosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ListStylePosition::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.ListStylePosition());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_type_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_type_custom.cc
index 766f0ec3fe4..1e76b7a130d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_type_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/list_style_type_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/list_style_type.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ListStyleType::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ListStyleType::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.ListStyleType());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_end_custom.cc
index 1472ef90e71..75e8af0220f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_end_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginBlockEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_start_custom.cc
index 1cea46eee03..92934df9ce3 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_block_start_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginBlockStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_bottom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_bottom_custom.cc
index 01dfd4de9c7..ed9228046e3 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_bottom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_bottom_custom.cc
@@ -13,14 +13,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginBottom::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool MarginBottom::IsLayoutDependent(const ComputedStyle* style,
@@ -44,5 +45,5 @@ const CSSValue* MarginBottom::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_end_custom.cc
index 5dd6bdcbf1a..ac895c4dd89 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_end_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginInlineEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_start_custom.cc
index c4134551d94..058c5030209 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_inline_start_custom.cc
@@ -10,15 +10,16 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginInlineStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_left_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_left_custom.cc
index c040712a2a3..24e7d794ac2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_left_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_left_custom.cc
@@ -13,14 +13,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginLeft::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool MarginLeft::IsLayoutDependent(const ComputedStyle* style,
@@ -44,5 +45,5 @@ const CSSValue* MarginLeft::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_right_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_right_custom.cc
index 2bc750d4e3f..6740f711fff 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_right_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_right_custom.cc
@@ -13,14 +13,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginRight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool MarginRight::IsLayoutDependent(const ComputedStyle* style,
@@ -58,5 +59,5 @@ const CSSValue* MarginRight::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(value, style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_top_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_top_custom.cc
index 6dc19f53f6d..7cac20e2153 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_top_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/margin_top_custom.cc
@@ -13,14 +13,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarginTop::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool MarginTop::IsLayoutDependent(const ComputedStyle* style,
@@ -43,5 +44,5 @@ const CSSValue* MarginTop::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(ToLayoutBox(layout_object)->MarginTop(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_end_custom.cc
index b8813a24559..092e27b984a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_end_custom.cc
@@ -11,15 +11,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarkerEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeUrl(range, &context);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeUrl(range, &context);
}
const CSSValue* MarkerEnd::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* MarkerEnd::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForSVGResource(svg_style.MarkerEndResource());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_mid_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_mid_custom.cc
index 4f886cf502a..e6f75ae0833 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_mid_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_mid_custom.cc
@@ -11,15 +11,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarkerMid::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeUrl(range, &context);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeUrl(range, &context);
}
const CSSValue* MarkerMid::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* MarkerMid::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForSVGResource(svg_style.MarkerMidResource());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_start_custom.cc
index fc475fbf8bc..8fcf23a05b0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/marker_start_custom.cc
@@ -11,15 +11,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MarkerStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeUrl(range, &context);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeUrl(range, &context);
}
const CSSValue* MarkerStart::CSSValueFromComputedStyleInternal(
@@ -32,5 +32,5 @@ const CSSValue* MarkerStart::CSSValueFromComputedStyleInternal(
svg_style.MarkerStartResource());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_custom.cc
index 4f7ca4ffce8..c891a09a861 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Mask::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeUrl(range, &context);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeUrl(range, &context);
}
const CSSValue* Mask::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* Mask::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForSVGResource(svg_style.MaskerResource());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_source_type_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_source_type_custom.cc
index 0490eb0f0b5..70c72ab01cc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_source_type_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_source_type_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MaskSourceType::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeMaskSourceType, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeMaskSourceType, range);
}
static CSSValue* ValueForFillSourceType(EMaskSourceType type) {
@@ -42,5 +42,5 @@ const CSSValue* MaskSourceType::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_type_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_type_custom.cc
index bde23dfb9ac..ce1c69bc9b2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_type_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/mask_type_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/mask_type.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MaskType::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* MaskType::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.MaskType());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_block_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_block_size_custom.cc
index acf81e5b40f..caaad31ad77 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_block_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_block_size_custom.cc
@@ -7,14 +7,14 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MaxBlockSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMaxWidthOrHeight(range, context);
+ return css_parsing_utils::ConsumeMaxWidthOrHeight(range, context);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_height_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_height_custom.cc
index efc599c165e..76456f5d08e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_height_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_height_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MaxHeight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMaxWidthOrHeight(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMaxWidthOrHeight(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
const CSSValue* MaxHeight::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* MaxHeight::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(max_height, style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_inline_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_inline_size_custom.cc
index 91e63e07405..b0a8c1d0cb7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_inline_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_inline_size_custom.cc
@@ -7,14 +7,14 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MaxInlineSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMaxWidthOrHeight(range, context);
+ return css_parsing_utils::ConsumeMaxWidthOrHeight(range, context);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_width_custom.cc
index 711c944a35d..5dd083dbbfc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/max_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/max_width_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MaxWidth::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMaxWidthOrHeight(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMaxWidthOrHeight(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
const CSSValue* MaxWidth::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* MaxWidth::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(max_width, style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_block_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_block_size_custom.cc
index 7e82be7a46f..b5b6278ca7d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_block_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_block_size_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MinBlockSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(range, context);
+ return css_parsing_utils::ConsumeWidthOrHeight(range, context);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_height_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_height_custom.cc
index 6ea9dec83cd..0f91093df1a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_height_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_height_custom.cc
@@ -13,14 +13,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MinHeight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeWidthOrHeight(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
const CSSValue* MinHeight::CSSValueFromComputedStyleInternal(
@@ -35,5 +35,5 @@ const CSSValue* MinHeight::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_inline_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_inline_size_custom.cc
index 93a7aaa4f38..3f207f0a026 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_inline_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_inline_size_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MinInlineSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(range, context);
+ return css_parsing_utils::ConsumeWidthOrHeight(range, context);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_width_custom.cc
index 92f488b6ea8..a332e0a8cbb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/min_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/min_width_custom.cc
@@ -13,13 +13,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MinWidth::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeWidthOrHeight(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
const CSSValue* MinWidth::CSSValueFromComputedStyleInternal(
@@ -34,5 +34,5 @@ const CSSValue* MinWidth::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode_custom.cc
index e6453fd8693..601297a1b71 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* MixBlendMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* MixBlendMode::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetBlendMode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/object_fit_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/object_fit_custom.cc
index fe43af9f307..13856d7b963 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/object_fit_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/object_fit_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/object_fit.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ObjectFit::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ObjectFit::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetObjectFit());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/object_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/object_position_custom.cc
index 29e04cdabb0..52edd499b33 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/object_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/object_position_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ObjectPosition::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumePosition(range, context,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid,
+ css_property_parser_helpers::UnitlessQuirk::kForbid,
base::Optional<WebFeature>());
}
@@ -36,5 +36,5 @@ const CSSValue* ObjectPosition::CSSValueFromComputedStyleInternal(
CSSValuePair::kKeepIdenticalValues);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_anchor_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_anchor_custom.cc
index 47d0c45799e..f1d20ee301c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_anchor_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_anchor_custom.cc
@@ -12,9 +12,9 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
-using namespace CSSPropertyParserHelpers;
+using namespace css_property_parser_helpers;
const CSSValue* OffsetAnchor::ParseSingleValue(
CSSParserTokenRange& range,
@@ -36,5 +36,5 @@ const CSSValue* OffsetAnchor::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForPosition(style.OffsetAnchor(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_distance_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_distance_custom.cc
index a68f4e163eb..fe0f5b0ff8e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_distance_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_distance_custom.cc
@@ -7,17 +7,17 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OffsetDistance::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(range, context.Mode(),
- kValueRangeAll);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
+ range, context.Mode(), kValueRangeAll);
}
const CSSValue* OffsetDistance::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* OffsetDistance::CSSValueFromComputedStyleInternal(
style.OffsetDistance(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_path_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_path_custom.cc
index e222f236ed6..31463258b2b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_path_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_path_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OffsetPath::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeOffsetPath(range, context);
+ return css_parsing_utils::ConsumeOffsetPath(range, context);
}
const CSSValue* OffsetPath::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* OffsetPath::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueNone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_position_custom.cc
index dc022d7129e..f7fa82fc16a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_position_custom.cc
@@ -12,9 +12,9 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
-using namespace CSSPropertyParserHelpers;
+using namespace css_property_parser_helpers;
const CSSValue* OffsetPosition::ParseSingleValue(
CSSParserTokenRange& range,
@@ -41,5 +41,5 @@ const CSSValue* OffsetPosition::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForPosition(style.OffsetPosition(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_rotate_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_rotate_custom.cc
index 7fe1a2bfcd0..de1a31d2bd8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_rotate_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/offset_rotate_custom.cc
@@ -7,13 +7,13 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OffsetRotate::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeOffsetRotate(range, context);
+ return css_parsing_utils::ConsumeOffsetRotate(range, context);
}
const CSSValue* OffsetRotate::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -29,5 +29,5 @@ const CSSValue* OffsetRotate::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/opacity_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/opacity_custom.cc
index 8d2d656efde..39e52b64fac 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/opacity_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/opacity_custom.cc
@@ -8,12 +8,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Opacity::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* Opacity::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* Opacity::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/order_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/order_custom.cc
index 93d607766d2..b8e95bf557f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/order_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/order_custom.cc
@@ -8,12 +8,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Order::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeInteger(range);
+ return css_property_parser_helpers::ConsumeInteger(range);
}
const CSSValue* Order::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* Order::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/orphans_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/orphans_custom.cc
index 30efcefe46f..468c68c14d0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/orphans_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/orphans_custom.cc
@@ -8,12 +8,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Orphans::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumePositiveInteger(range);
+ return css_property_parser_helpers::ConsumePositiveInteger(range);
}
const CSSValue* Orphans::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* Orphans::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_color_custom.cc
index d3e3582da3d..aebb8f06d83 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_color_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OutlineColor::ParseSingleValue(
CSSParserTokenRange& range,
@@ -19,8 +19,8 @@ const CSSValue* OutlineColor::ParseSingleValue(
const CSSParserLocalContext&) const {
// Allow the special focus color even in HTML Standard parsing mode.
if (range.Peek().Id() == CSSValueWebkitFocusRingColor)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color OutlineColor::ColorIncludingFallback(
@@ -45,5 +45,5 @@ const CSSValue* OutlineColor::CSSValueFromComputedStyleInternal(
style, style.OutlineColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_offset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_offset_custom.cc
index a0dcf6fcd62..a83f5a13983 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_offset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_offset_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OutlineOffset::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeAll);
+ return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
+ kValueRangeAll);
}
const CSSValue* OutlineOffset::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* OutlineOffset::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.OutlineOffset(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_style_custom.cc
index 85ebb2889bf..dabcba11d61 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_style_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OutlineStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -41,5 +41,5 @@ void OutlineStyle::ApplyValue(StyleResolverState& state,
state.Style()->SetOutlineStyle(identifier_value.ConvertTo<EBorderStyle>());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_width_custom.cc
index d34a69a3fed..ce38ee02276 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/outline_width_custom.cc
@@ -9,14 +9,15 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OutlineWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLineWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeLineWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* OutlineWidth::CSSValueFromComputedStyleInternal(
@@ -28,5 +29,5 @@ const CSSValue* OutlineWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.OutlineWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_anchor_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_anchor_custom.cc
index 44c9069cd49..7bd0665462d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_anchor_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_anchor_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/overflow_anchor.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OverflowAnchor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* OverflowAnchor::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.OverflowAnchor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_wrap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_wrap_custom.cc
index dc9adb59529..9bf7fe542f8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_wrap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_wrap_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/overflow_wrap.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OverflowWrap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* OverflowWrap::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.OverflowWrap());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_x_custom.cc
index bc9b1e08011..46213f16eb4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_x_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/overflow_x.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OverflowX::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* OverflowX::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.OverflowX());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_y_custom.cc
index 267cf121759..f006aee57c1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/overflow_y_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/overflow_y.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OverflowY::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* OverflowY::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.OverflowY());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x_custom.cc
index b175e01ebe9..257dd525840 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OverscrollBehaviorX::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* OverscrollBehaviorX::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.OverscrollBehaviorX());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y_custom.cc
index ce62081c754..69800afadf4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* OverscrollBehaviorY::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* OverscrollBehaviorY::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.OverscrollBehaviorY());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_end_custom.cc
index d0764c3e0bb..499c6eacabb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_end_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingBlockEnd::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* PaddingBlockEnd::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_start_custom.cc
index b431bcda79e..ebfbe2bc833 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_block_start_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingBlockStart::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* PaddingBlockStart::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_bottom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_bottom_custom.cc
index c483b3c766e..9154c40885d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_bottom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_bottom_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingBottom::ParseSingleValue(
CSSParserTokenRange& range,
@@ -20,7 +20,7 @@ const CSSValue* PaddingBottom::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool PaddingBottom::IsLayoutDependent(const ComputedStyle* style,
@@ -44,5 +44,5 @@ const CSSValue* PaddingBottom::CSSValueFromComputedStyleInternal(
ToLayoutBox(layout_object)->ComputedCSSPaddingBottom(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_end_custom.cc
index 371658bd81d..714efdb955b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_end_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingInlineEnd::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* PaddingInlineEnd::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_start_custom.cc
index f5224eeb1d5..5e9e128306c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_inline_start_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingInlineStart::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* PaddingInlineStart::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_left_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_left_custom.cc
index 762006e8499..9620b075c17 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_left_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_left_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingLeft::ParseSingleValue(
CSSParserTokenRange& range,
@@ -20,7 +20,7 @@ const CSSValue* PaddingLeft::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool PaddingLeft::IsLayoutDependent(const ComputedStyle* style,
@@ -44,5 +44,5 @@ const CSSValue* PaddingLeft::CSSValueFromComputedStyleInternal(
ToLayoutBox(layout_object)->ComputedCSSPaddingLeft(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_right_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_right_custom.cc
index c057367746e..848f041118e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_right_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_right_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingRight::ParseSingleValue(
CSSParserTokenRange& range,
@@ -20,7 +20,7 @@ const CSSValue* PaddingRight::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool PaddingRight::IsLayoutDependent(const ComputedStyle* style,
@@ -44,5 +44,5 @@ const CSSValue* PaddingRight::CSSValueFromComputedStyleInternal(
ToLayoutBox(layout_object)->ComputedCSSPaddingRight(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_top_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_top_custom.cc
index 636ccb58bf1..4624004ab53 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_top_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/padding_top_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaddingTop::ParseSingleValue(
CSSParserTokenRange& range,
@@ -20,7 +20,7 @@ const CSSValue* PaddingTop::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool PaddingTop::IsLayoutDependent(const ComputedStyle* style,
@@ -44,5 +44,5 @@ const CSSValue* PaddingTop::CSSValueFromComputedStyleInternal(
ToLayoutBox(layout_object)->ComputedCSSPaddingTop(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/page_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/page_custom.cc
index 64b140d3bdd..68be30e287a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/page_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/page_custom.cc
@@ -7,15 +7,15 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Page::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeCustomIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeCustomIdent(range, context);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/paint_order_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/paint_order_custom.cc
index 05a9a44ebe0..6a0e2fdf0cb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/paint_order_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/paint_order_custom.cc
@@ -6,18 +6,17 @@
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
-#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PaintOrder::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNormal)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
Vector<CSSValueID, 3> paint_type_list;
CSSIdentifierValue* fill = nullptr;
@@ -26,11 +25,11 @@ const CSSValue* PaintOrder::ParseSingleValue(
do {
CSSValueID id = range.Peek().Id();
if (id == CSSValueFill && !fill)
- fill = CSSPropertyParserHelpers::ConsumeIdent(range);
+ fill = css_property_parser_helpers::ConsumeIdent(range);
else if (id == CSSValueStroke && !stroke)
- stroke = CSSPropertyParserHelpers::ConsumeIdent(range);
+ stroke = css_property_parser_helpers::ConsumeIdent(range);
else if (id == CSSValueMarkers && !markers)
- markers = CSSPropertyParserHelpers::ConsumeIdent(range);
+ markers = css_property_parser_helpers::ConsumeIdent(range);
else
return nullptr;
paint_type_list.push_back(id);
@@ -69,10 +68,39 @@ const CSSValue* PaintOrder::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ Node*,
bool allow_visited_style) const {
- return ComputedStyleUtils::PaintOrderToCSSValueList(svg_style);
+ const EPaintOrder paint_order = svg_style.PaintOrder();
+ if (paint_order == kPaintOrderNormal)
+ return CSSIdentifierValue::Create(CSSValueNormal);
+
+ // Table mapping to the shortest (canonical) form of the property.
+ //
+ // Per spec, if any keyword is omitted it will be added last using
+ // the standard ordering. So "stroke" implies an order "stroke fill
+ // markers" etc. From a serialization PoV this means we never need
+ // to emit the last keyword.
+ //
+ // https://svgwg.org/svg2-draft/painting.html#PaintOrder
+ static const uint8_t canonical_form[][2] = {
+ // kPaintOrderNormal is handled above.
+ {PT_FILL, PT_NONE}, // kPaintOrderFillStrokeMarkers
+ {PT_FILL, PT_MARKERS}, // kPaintOrderFillMarkersStroke
+ {PT_STROKE, PT_NONE}, // kPaintOrderStrokeFillMarkers
+ {PT_STROKE, PT_MARKERS}, // kPaintOrderStrokeMarkersFill
+ {PT_MARKERS, PT_NONE}, // kPaintOrderMarkersFillStroke
+ {PT_MARKERS, PT_STROKE}, // kPaintOrderMarkersStrokeFill
+ };
+ DCHECK_LT(static_cast<size_t>(paint_order) - 1, base::size(canonical_form));
+ CSSValueList* list = CSSValueList::CreateSpaceSeparated();
+ for (const auto& keyword : canonical_form[paint_order - 1]) {
+ const auto paint_order_type = static_cast<EPaintOrderType>(keyword);
+ if (paint_order_type == PT_NONE)
+ break;
+ list->Append(*CSSIdentifierValue::Create(paint_order_type));
+ }
+ return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_custom.cc
index a781987d300..19f423c38b4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_custom.cc
@@ -12,20 +12,20 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Perspective::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& localContext) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- CSSPrimitiveValue* parsed_value = CSSPropertyParserHelpers::ConsumeLength(
+ return css_property_parser_helpers::ConsumeIdent(range);
+ CSSPrimitiveValue* parsed_value = css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeAll);
bool use_legacy_parsing = localContext.UseAliasParsing();
if (!parsed_value && use_legacy_parsing) {
double perspective;
- if (!CSSPropertyParserHelpers::ConsumeNumberRaw(range, perspective))
+ if (!css_property_parser_helpers::ConsumeNumberRaw(range, perspective))
return nullptr;
context.Count(WebFeature::kUnitlessPerspectiveInPerspectiveProperty);
parsed_value = CSSPrimitiveValue::Create(
@@ -48,5 +48,5 @@ const CSSValue* Perspective::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.Perspective(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_origin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_origin_custom.cc
index e6a7c62ba1f..dc142e7e941 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_origin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/perspective_origin_custom.cc
@@ -13,14 +13,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PerspectiveOrigin::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumePosition(range, context,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid,
+ css_property_parser_helpers::UnitlessQuirk::kForbid,
base::Optional<WebFeature>());
}
@@ -58,5 +58,5 @@ const CSSValue* PerspectiveOrigin::CSSValueFromComputedStyleInternal(
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/pointer_events_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/pointer_events_custom.cc
index c501f1aaf2c..f7b562480dd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/pointer_events_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/pointer_events_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/pointer_events.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* PointerEvents::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* PointerEvents::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.PointerEvents());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/position_custom.cc
index 1b4c438e4dd..68fc098ae5f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/position_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/position.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Position::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -21,5 +21,5 @@ void Position::ApplyInherit(StyleResolverState& state) const {
state.Style()->SetPosition(state.ParentStyle()->GetPosition());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/quotes_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/quotes_custom.cc
index 56874b3fb94..9524d5e9c8e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/quotes_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/quotes_custom.cc
@@ -11,17 +11,17 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Quotes::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* values = CSSValueList::CreateSpaceSeparated();
while (!range.AtEnd()) {
CSSStringValue* parsed_value =
- CSSPropertyParserHelpers::ConsumeString(range);
+ css_property_parser_helpers::ConsumeString(range);
if (!parsed_value)
return nullptr;
values->Append(*parsed_value);
@@ -53,5 +53,5 @@ const CSSValue* Quotes::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueNone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/r_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/r_custom.cc
index fb272fcc38a..7f3111ad37e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/r_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/r_custom.cc
@@ -8,14 +8,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* R::ParseSingleValue(CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeNonNegative);
}
const CSSValue* R::CSSValueFromComputedStyleInternal(
@@ -28,5 +27,5 @@ const CSSValue* R::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/resize_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/resize_custom.cc
index 9068e5b207f..f2cefd9e40b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/resize_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/resize_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/frame/web_feature.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Resize::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -25,30 +25,17 @@ void Resize::ApplyValue(StyleResolverState& state,
const CSSIdentifierValue& identifier_value = ToCSSIdentifierValue(value);
EResize r = EResize::kNone;
- CSSValueID id = identifier_value.GetValueID();
- switch (id) {
- case CSSValueAuto:
- if (Settings* settings = state.GetDocument().GetSettings()) {
- r = settings->GetTextAreasAreResizable() ? EResize::kBoth
- : EResize::kNone;
- }
- UseCounter::Count(state.GetDocument(), WebFeature::kCSSResizeAuto);
- break;
- case CSSValueBlock:
- case CSSValueInline:
- if ((id == CSSValueBlock) ==
- IsHorizontalWritingMode(state.Style()->GetWritingMode())) {
- r = EResize::kVertical;
- } else {
- r = EResize::kHorizontal;
- }
- break;
- default:
- r = identifier_value.ConvertTo<EResize>();
- break;
+ if (identifier_value.GetValueID() == CSSValueAuto) {
+ if (Settings* settings = state.GetDocument().GetSettings()) {
+ r = settings->GetTextAreasAreResizable() ? EResize::kBoth
+ : EResize::kNone;
+ }
+ UseCounter::Count(state.GetDocument(), WebFeature::kCSSResizeAuto);
+ } else {
+ r = identifier_value.ConvertTo<EResize>();
}
state.Style()->SetResize(r);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/right_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/right_custom.cc
index 3d7218df1c2..3ea427901af 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/right_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/right_custom.cc
@@ -15,13 +15,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Right::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool Right::IsLayoutDependent(const ComputedStyle* style,
@@ -39,5 +40,5 @@ const CSSValue* Right::CSSValueFromComputedStyleInternal(
layout_object);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/rotate_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/rotate_custom.cc
index b68f3b8fb77..69367f266a4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/rotate_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/rotate_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Rotate::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
@@ -20,16 +20,16 @@ const CSSValue* Rotate::ParseSingleValue(CSSParserTokenRange& range,
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- CSSValue* rotation = CSSPropertyParserHelpers::ConsumeAngle(
+ CSSValue* rotation = css_property_parser_helpers::ConsumeAngle(
range, &context, base::Optional<WebFeature>());
CSSValueID axis_id = range.Peek().Id();
if (axis_id == CSSValueX) {
- CSSPropertyParserHelpers::ConsumeIdent(range);
+ css_property_parser_helpers::ConsumeIdent(range);
list->Append(
*CSSPrimitiveValue::Create(1, CSSPrimitiveValue::UnitType::kNumber));
list->Append(
@@ -37,7 +37,7 @@ const CSSValue* Rotate::ParseSingleValue(CSSParserTokenRange& range,
list->Append(
*CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kNumber));
} else if (axis_id == CSSValueY) {
- CSSPropertyParserHelpers::ConsumeIdent(range);
+ css_property_parser_helpers::ConsumeIdent(range);
list->Append(
*CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kNumber));
list->Append(
@@ -45,7 +45,7 @@ const CSSValue* Rotate::ParseSingleValue(CSSParserTokenRange& range,
list->Append(
*CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kNumber));
} else if (axis_id == CSSValueZ) {
- CSSPropertyParserHelpers::ConsumeIdent(range);
+ css_property_parser_helpers::ConsumeIdent(range);
list->Append(
*CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kNumber));
list->Append(
@@ -55,7 +55,7 @@ const CSSValue* Rotate::ParseSingleValue(CSSParserTokenRange& range,
} else {
for (unsigned i = 0; i < 3; i++) { // 3 dimensions of rotation
CSSValue* dimension =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
if (!dimension) {
if (i == 0)
break;
@@ -66,7 +66,7 @@ const CSSValue* Rotate::ParseSingleValue(CSSParserTokenRange& range,
}
if (!rotation) {
- rotation = CSSPropertyParserHelpers::ConsumeAngle(
+ rotation = css_property_parser_helpers::ConsumeAngle(
range, &context, base::Optional<WebFeature>());
if (!rotation)
return nullptr;
@@ -100,5 +100,5 @@ const CSSValue* Rotate::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/row_gap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/row_gap_custom.cc
index c320f6f763b..5b5c1df1601 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/row_gap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/row_gap_custom.cc
@@ -11,12 +11,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* RowGap::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeGapLength(range, context);
+ return css_parsing_utils::ConsumeGapLength(range, context);
}
const CSSValue* RowGap::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* RowGap::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForGapLength(style.RowGap(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/rx_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/rx_custom.cc
index 1df2543f1f3..231414c6601 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/rx_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/rx_custom.cc
@@ -8,16 +8,15 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Rx::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeNonNegative);
}
const CSSValue* Rx::CSSValueFromComputedStyleInternal(
@@ -30,5 +29,5 @@ const CSSValue* Rx::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/ry_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/ry_custom.cc
index 88d773f1aa2..d8f95008385 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/ry_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/ry_custom.cc
@@ -8,16 +8,15 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Ry::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeNonNegative);
}
const CSSValue* Ry::CSSValueFromComputedStyleInternal(
@@ -30,5 +29,5 @@ const CSSValue* Ry::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scale_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scale_custom.cc
index e2c747d37a9..461a180942a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scale_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scale_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Scale::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
@@ -19,18 +19,18 @@ const CSSValue* Scale::ParseSingleValue(CSSParserTokenRange& range,
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValue* scale =
- CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
if (!scale)
return nullptr;
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*scale);
- scale = CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ scale = css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
if (scale) {
list->Append(*scale);
- scale = CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ scale = css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
if (scale)
list->Append(*scale);
}
@@ -58,5 +58,5 @@ const CSSValue* Scale::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_behavior_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_behavior_custom.cc
index 16f81194168..ece75e07a8f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_behavior_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_behavior_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/scroll_behavior.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollBehavior::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ScrollBehavior::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetScrollBehavior());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_customization_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_customization_custom.cc
index 69dc5af8b40..8f1e4e47e8d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_customization_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_customization_custom.cc
@@ -20,11 +20,11 @@ static bool ConsumePan(CSSParserTokenRange& range,
CSSValueID id = range.Peek().Id();
if ((id == CSSValuePanX || id == CSSValuePanRight || id == CSSValuePanLeft) &&
!*pan_x) {
- *pan_x = CSSPropertyParserHelpers::ConsumeIdent(range);
+ *pan_x = css_property_parser_helpers::ConsumeIdent(range);
} else if ((id == CSSValuePanY || id == CSSValuePanDown ||
id == CSSValuePanUp) &&
!*pan_y) {
- *pan_y = CSSPropertyParserHelpers::ConsumeIdent(range);
+ *pan_y = css_property_parser_helpers::ConsumeIdent(range);
} else {
return false;
}
@@ -32,7 +32,7 @@ static bool ConsumePan(CSSParserTokenRange& range,
}
} // namespace
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollCustomization::ParseSingleValue(
CSSParserTokenRange& range,
@@ -41,7 +41,7 @@ const CSSValue* ScrollCustomization::ParseSingleValue(
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
CSSValueID id = range.Peek().Id();
if (id == CSSValueAuto || id == CSSValueNone) {
- list->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ list->Append(*css_property_parser_helpers::ConsumeIdent(range));
return list;
}
@@ -69,5 +69,5 @@ const CSSValue* ScrollCustomization::CSSValueFromComputedStyleInternal(
style.ScrollCustomization());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_end_custom.cc
index 29fbe3c76c6..a835df34dcd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_end_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginBlockEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_start_custom.cc
index e6ba6321476..472e5b76052 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_start_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginBlockStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_bottom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_bottom_custom.cc
index 5583fdc311e..978ebde3936 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_bottom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_bottom_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginBottom::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollMarginBottom::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ScrollMarginBottom::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.ScrollMarginBottom(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_end_custom.cc
index bb8b8236c77..7f17fd30c3c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_end_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginInlineEnd::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_start_custom.cc
index 0a2668ca02c..cab85ffb07a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_start_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginInlineStart::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_left_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_left_custom.cc
index 362208441c8..a7fe021568e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_left_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_left_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginLeft::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollMarginLeft::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ScrollMarginLeft::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.ScrollMarginLeft(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_right_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_right_custom.cc
index 2ce02b1564d..9769d15ddc7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_right_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_right_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginRight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollMarginRight::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ScrollMarginRight::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.ScrollMarginRight(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_top_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_top_custom.cc
index e6ce2a2b4b9..5a9a4d42572 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_top_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_margin_top_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollMarginTop::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return ConsumeLength(range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollMarginTop::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* ScrollMarginTop::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.ScrollMarginTop(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_end_custom.cc
index 1f66c7e803b..d4d9484710f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_end_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingBlockEnd::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* ScrollPaddingBlockEnd::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_start_custom.cc
index 3c93e003db6..1a2ae5d04f0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_start_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingBlockStart::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* ScrollPaddingBlockStart::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_bottom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_bottom_custom.cc
index 862abd5a324..fbce2ba039b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_bottom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_bottom_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingBottom::ParseSingleValue(
CSSParserTokenRange& range,
@@ -17,7 +17,7 @@ const CSSValue* ScrollPaddingBottom::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollPaddingBottom::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* ScrollPaddingBottom::CSSValueFromComputedStyleInternal(
style.ScrollPaddingBottom(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_end_custom.cc
index adaadd255d2..9bb8dd65868 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_end_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingInlineEnd::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* ScrollPaddingInlineEnd::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_start_custom.cc
index 7a98a9b3f96..ee82bf526a8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_start_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingInlineStart::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,8 +18,8 @@ const CSSValue* ScrollPaddingInlineStart::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_left_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_left_custom.cc
index ee232f22c70..d0a38ccfdf9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_left_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_left_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingLeft::ParseSingleValue(
CSSParserTokenRange& range,
@@ -17,7 +17,7 @@ const CSSValue* ScrollPaddingLeft::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollPaddingLeft::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* ScrollPaddingLeft::CSSValueFromComputedStyleInternal(
style.ScrollPaddingLeft(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_right_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_right_custom.cc
index 089a2302b7a..987d1dcae86 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_right_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_right_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingRight::ParseSingleValue(
CSSParserTokenRange& range,
@@ -17,7 +17,7 @@ const CSSValue* ScrollPaddingRight::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollPaddingRight::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* ScrollPaddingRight::CSSValueFromComputedStyleInternal(
style.ScrollPaddingRight(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_top_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_top_custom.cc
index 80886a1b94c..6636efca5e0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_top_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_padding_top_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollPaddingTop::ParseSingleValue(
CSSParserTokenRange& range,
@@ -17,7 +17,7 @@ const CSSValue* ScrollPaddingTop::ParseSingleValue(
const CSSParserLocalContext&) const {
return ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* ScrollPaddingTop::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* ScrollPaddingTop::CSSValueFromComputedStyleInternal(
style.ScrollPaddingTop(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_align_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_align_custom.cc
index 889016363c7..3fc3e664eb7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_align_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_align_custom.cc
@@ -10,20 +10,20 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollSnapAlign::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- CSSValue* block_value = CSSPropertyParserHelpers::ConsumeIdent<
+ CSSValue* block_value = css_property_parser_helpers::ConsumeIdent<
CSSValueNone, CSSValueStart, CSSValueEnd, CSSValueCenter>(range);
if (!block_value)
return nullptr;
if (range.AtEnd())
return block_value;
- CSSValue* inline_value = CSSPropertyParserHelpers::ConsumeIdent<
+ CSSValue* inline_value = css_property_parser_helpers::ConsumeIdent<
CSSValueNone, CSSValueStart, CSSValueEnd, CSSValueCenter>(range);
if (!inline_value)
return block_value;
@@ -42,5 +42,5 @@ const CSSValue* ScrollSnapAlign::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop_custom.cc
index 072376f4b23..38b79555e14 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollSnapStop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ScrollSnapStop::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.ScrollSnapStop());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_type_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_type_custom.cc
index 84d979ec0ab..edc61c33045 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_type_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/scroll_snap_type_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ScrollSnapType::ParseSingleValue(
CSSParserTokenRange& range,
@@ -21,14 +21,14 @@ const CSSValue* ScrollSnapType::ParseSingleValue(
axis_id != CSSValueBlock && axis_id != CSSValueInline &&
axis_id != CSSValueBoth)
return nullptr;
- CSSValue* axis_value = CSSPropertyParserHelpers::ConsumeIdent(range);
+ CSSValue* axis_value = css_property_parser_helpers::ConsumeIdent(range);
if (range.AtEnd() || axis_id == CSSValueNone)
return axis_value;
CSSValueID strictness_id = range.Peek().Id();
if (strictness_id != CSSValueProximity && strictness_id != CSSValueMandatory)
return axis_value;
- CSSValue* strictness_value = CSSPropertyParserHelpers::ConsumeIdent(range);
+ CSSValue* strictness_value = css_property_parser_helpers::ConsumeIdent(range);
CSSValuePair* pair = CSSValuePair::Create(axis_value, strictness_value,
CSSValuePair::kDropIdenticalValues);
return pair;
@@ -44,5 +44,5 @@ const CSSValue* ScrollSnapType::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_image_threshold_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_image_threshold_custom.cc
index 3a297190611..b9a90b43fce 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_image_threshold_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_image_threshold_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ShapeImageThreshold::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* ShapeImageThreshold::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* ShapeImageThreshold::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_margin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_margin_custom.cc
index b7fafb30899..a541cd5c29a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_margin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_margin_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ShapeMargin::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative);
}
@@ -28,5 +28,5 @@ const CSSValue* ShapeMargin::CSSValueFromComputedStyleInternal(
return CSSValue::Create(style.ShapeMargin(), style.EffectiveZoom());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_outside_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_outside_custom.cc
index 7ee480ac605..27434eaab75 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_outside_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_outside_custom.cc
@@ -12,9 +12,9 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
-using namespace CSSPropertyParserHelpers;
+using namespace css_property_parser_helpers;
const CSSValue* ShapeOutside::ParseSingleValue(
CSSParserTokenRange& range,
@@ -26,7 +26,7 @@ const CSSValue* ShapeOutside::ParseSingleValue(
if (CSSValue* box_value = ConsumeShapeBox(range))
list->Append(*box_value);
if (CSSValue* shape_value =
- CSSParsingUtils::ConsumeBasicShape(range, context)) {
+ css_parsing_utils::ConsumeBasicShape(range, context)) {
list->Append(*shape_value);
if (list->length() < 2) {
if (CSSValue* box_value = ConsumeShapeBox(range))
@@ -47,5 +47,5 @@ const CSSValue* ShapeOutside::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForShape(style, style.ShapeOutside());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_rendering_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_rendering_custom.cc
index 901f7de5509..707fc51e844 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_rendering_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/shape_rendering_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/shape_rendering.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ShapeRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* ShapeRendering::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.ShapeRendering());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/size_custom.cc
index 5ed6ab5d3c8..1c6af681b8d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/size_custom.cc
@@ -10,10 +10,10 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
static CSSValue* ConsumePageSize(CSSParserTokenRange& range) {
- return CSSPropertyParserHelpers::ConsumeIdent<
+ return css_property_parser_helpers::ConsumeIdent<
CSSValueA3, CSSValueA4, CSSValueA5, CSSValueB4, CSSValueB5,
CSSValueLedger, CSSValueLegal, CSSValueLetter>(range);
}
@@ -54,13 +54,13 @@ const CSSValue* Size::ParseSingleValue(CSSParserTokenRange& range,
CSSValueList* result = CSSValueList::CreateSpaceSeparated();
if (range.Peek().Id() == CSSValueAuto) {
- result->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ result->Append(*css_property_parser_helpers::ConsumeIdent(range));
return result;
}
- if (CSSValue* width = CSSPropertyParserHelpers::ConsumeLength(
+ if (CSSValue* width = css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeNonNegative)) {
- CSSValue* height = CSSPropertyParserHelpers::ConsumeLength(
+ CSSValue* height = css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeNonNegative);
result->Append(*width);
if (height)
@@ -70,8 +70,8 @@ const CSSValue* Size::ParseSingleValue(CSSParserTokenRange& range,
CSSValue* page_size = ConsumePageSize(range);
CSSValue* orientation =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValuePortrait,
- CSSValueLandscape>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValuePortrait,
+ CSSValueLandscape>(range);
if (!page_size)
page_size = ConsumePageSize(range);
@@ -147,5 +147,5 @@ void Size::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
state.Style()->SetPageSize(size);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/speak_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/speak_custom.cc
index 74983d0f8b2..46db889f029 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/speak_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/speak_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/speak.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Speak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* Speak::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.Speak());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_color_custom.cc
index 0d0cac293b7..ff92bf917b1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_color_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StopColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color StopColor::ColorIncludingFallback(
@@ -36,5 +36,5 @@ const CSSValue* StopColor::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::CurrentColorOrValidColor(style, style.StopColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_opacity_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_opacity_custom.cc
index 551df8fe22e..8c34280915c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_opacity_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stop_opacity_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StopOpacity::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* StopOpacity::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* StopOpacity::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_custom.cc
index 99b51e88341..2a48ffc5a96 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_custom.cc
@@ -9,12 +9,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Stroke::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParsePaintStroke(range, context);
+ return css_parsing_utils::ParsePaintStroke(range, context);
}
const CSSValue* Stroke::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* Stroke::CSSValueFromComputedStyleInternal(
svg_style.StrokePaint(), style.GetColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dasharray_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dasharray_custom.cc
index b9b25b1eb11..214fb673c7f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dasharray_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dasharray_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeDasharray::ParseSingleValue(
CSSParserTokenRange& range,
@@ -18,14 +18,15 @@ const CSSValue* StrokeDasharray::ParseSingleValue(
const CSSParserLocalContext&) const {
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* dashes = CSSValueList::CreateCommaSeparated();
do {
- CSSPrimitiveValue* dash = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeNonNegative);
+ CSSPrimitiveValue* dash =
+ css_property_parser_helpers::ConsumeLengthOrPercent(
+ range, kSVGAttributeMode, kValueRangeNonNegative);
if (!dash ||
- (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range) &&
+ (css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range) &&
range.AtEnd()))
return nullptr;
dashes->Append(*dash);
@@ -43,5 +44,5 @@ const CSSValue* StrokeDasharray::CSSValueFromComputedStyleInternal(
*svg_style.StrokeDashArray(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dashoffset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dashoffset_custom.cc
index a6f3ab8d349..c0e1406ceb4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dashoffset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_dashoffset_custom.cc
@@ -8,15 +8,15 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeDashoffset::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* StrokeDashoffset::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* StrokeDashoffset::CSSValueFromComputedStyleInternal(
style.StrokeDashOffset(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linecap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linecap_custom.cc
index 72f69396608..97d000ab119 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linecap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linecap_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/stroke_linecap.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeLinecap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* StrokeLinecap::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.CapStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin_custom.cc
index 1ee5aa3994a..74dc509c00c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeLinejoin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* StrokeLinejoin::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.JoinStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_miterlimit_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_miterlimit_custom.cc
index 61a3fe4bd10..ba2f77bf4a7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_miterlimit_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_miterlimit_custom.cc
@@ -8,13 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeMiterlimit::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
}
const CSSValue* StrokeMiterlimit::CSSValueFromComputedStyleInternal(
@@ -27,5 +28,5 @@ const CSSValue* StrokeMiterlimit::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_opacity_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_opacity_custom.cc
index 726c74a5112..0f4f7ffe448 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_opacity_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_opacity_custom.cc
@@ -11,13 +11,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeOpacity::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* StrokeOpacity::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* StrokeOpacity::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_width_custom.cc
index 705680040fe..7c90d530e8e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/stroke_width_custom.cc
@@ -8,15 +8,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* StrokeWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeLengthOrPercent(
+ range, kSVGAttributeMode, kValueRangeNonNegative,
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* StrokeWidth::CSSValueFromComputedStyleInternal(
@@ -33,5 +33,5 @@ const CSSValue* StrokeWidth::CSSValueFromComputedStyleInternal(
return CSSValue::Create(length, style.EffectiveZoom());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/tab_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/tab_size_custom.cc
index 60a76b70e7e..6ff737c2e17 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/tab_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/tab_size_custom.cc
@@ -9,17 +9,17 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TabSize::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
CSSPrimitiveValue* parsed_value =
- CSSPropertyParserHelpers::ConsumeInteger(range, 0);
+ css_property_parser_helpers::ConsumeInteger(range, 0);
if (parsed_value)
return parsed_value;
- return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
+ kValueRangeNonNegative);
}
const CSSValue* TabSize::CSSValueFromComputedStyleInternal(
@@ -34,5 +34,5 @@ const CSSValue* TabSize::CSSValueFromComputedStyleInternal(
: CSSPrimitiveValue::UnitType::kPixels);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/table_layout_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/table_layout_custom.cc
index 33527a3bdd7..028428c4433 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/table_layout_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/table_layout_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/table_layout.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TableLayout::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TableLayout::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TableLayout());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_custom.cc
index 4b614bd4faf..4377366d66d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_align.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextAlign::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -43,5 +43,5 @@ void TextAlign::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_last_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_last_custom.cc
index ff841754c43..37a2dafc678 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_last_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_align_last_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_align_last.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextAlignLast::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TextAlignLast::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TextAlignLast());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_anchor_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_anchor_custom.cc
index 4ab7953083d..b6fe998ce43 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_anchor_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_anchor_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_anchor.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextAnchor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TextAnchor::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.TextAnchor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_combine_upright_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_combine_upright_custom.cc
index f219d0d4fcf..36087bf36a6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_combine_upright_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_combine_upright_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_combine_upright.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextCombineUpright::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TextCombineUpright::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TextCombine());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_color_custom.cc
index 9215dd483ec..e7d5215360c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_color_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextDecorationColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color TextDecorationColor::ColorIncludingFallback(
@@ -38,5 +38,5 @@ const CSSValue* TextDecorationColor::CSSValueFromComputedStyleInternal(
style, style.TextDecorationColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_line_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_line_custom.cc
index 7a20bb815a7..c6b25d15e29 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_line_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_line_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextDecorationLine::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeTextDecorationLine(range);
+ return css_parsing_utils::ConsumeTextDecorationLine(range);
}
const CSSValue* TextDecorationLine::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* TextDecorationLine::CSSValueFromComputedStyleInternal(
style.GetTextDecoration());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_skip_ink_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_skip_ink_custom.cc
index ff991853cce..b7786fcf102 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_skip_ink_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_skip_ink_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextDecorationSkipInk::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* TextDecorationSkipInk::CSSValueFromComputedStyleInternal(
style.TextDecorationSkipInk());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_style_custom.cc
index 19bd6b59362..b5afc9a0731 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_decoration_style_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextDecorationStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* TextDecorationStyle::CSSValueFromComputedStyleInternal(
style.TextDecorationStyle());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_indent_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_indent_custom.cc
index 2b3e126b407..a581d1e6da1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_indent_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_indent_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextIndent::ParseSingleValue(
CSSParserTokenRange& range,
@@ -25,9 +25,9 @@ const CSSValue* TextIndent::ParseSingleValue(
CSSValue* each_line = nullptr;
do {
if (!length_percentage) {
- length_percentage = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ length_percentage = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
if (length_percentage) {
continue;
}
@@ -36,11 +36,11 @@ const CSSValue* TextIndent::ParseSingleValue(
if (RuntimeEnabledFeatures::CSS3TextEnabled()) {
CSSValueID id = range.Peek().Id();
if (!hanging && id == CSSValueHanging) {
- hanging = CSSPropertyParserHelpers::ConsumeIdent(range);
+ hanging = css_property_parser_helpers::ConsumeIdent(range);
continue;
}
if (!each_line && id == CSSValueEachLine) {
- each_line = CSSPropertyParserHelpers::ConsumeIdent(range);
+ each_line = css_property_parser_helpers::ConsumeIdent(range);
continue;
}
}
@@ -122,5 +122,5 @@ void TextIndent::ApplyValue(StyleResolverState& state,
state.Style()->SetTextIndentType(text_indent_type_value);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_justify_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_justify_custom.cc
index 3d90c41da2b..14ea4675b6b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_justify_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_justify_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_justify.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextJustify::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TextJustify::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetTextJustify());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_orientation_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_orientation_custom.cc
index 80680e04cf4..e07fff1d0e9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_orientation_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_orientation_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_orientation.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextOrientation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -22,5 +22,5 @@ void TextOrientation::ApplyValue(StyleResolverState& state,
ToCSSIdentifierValue(value).ConvertTo<ETextOrientation>());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_overflow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_overflow_custom.cc
index 3a2b259c3ed..7d8863c63e1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_overflow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_overflow_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextOverflow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* TextOverflow::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueClip);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_rendering_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_rendering_custom.cc
index e06ef3615bb..7dba68991f1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_rendering_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_rendering_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -18,5 +18,5 @@ const CSSValue* TextRendering::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetFontDescription().TextRendering());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_shadow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_shadow_custom.cc
index b6961ebf2e3..2c4a85746e2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_shadow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_shadow_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextShadow::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeShadow(
- range, context.Mode(), CSSParsingUtils::AllowInsetAndSpread::kForbid);
+ return css_parsing_utils::ConsumeShadow(
+ range, context.Mode(), css_parsing_utils::AllowInsetAndSpread::kForbid);
}
const CSSValue* TextShadow::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* TextShadow::CSSValueFromComputedStyleInternal(
false);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_size_adjust_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_size_adjust_custom.cc
index 9179c1dc0b9..865b9276310 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_size_adjust_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_size_adjust_custom.cc
@@ -9,18 +9,18 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextSizeAdjust::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumePercent(range,
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumePercent(range,
+ kValueRangeNonNegative);
}
const CSSValue* TextSizeAdjust::CSSValueFromComputedStyleInternal(
@@ -35,5 +35,5 @@ const CSSValue* TextSizeAdjust::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kPercentage);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_transform_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_transform_custom.cc
index 84332fa3c28..2a2a0f7df9b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_transform_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_transform_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/text_transform.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TextTransform::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TextTransform::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TextTransform());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_underline_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_underline_position_custom.cc
index 882eb40ca80..912e2606b86 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/text_underline_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/text_underline_position_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
// auto | [ under || [ left | right ] ]
const CSSValue* TextUnderlinePosition::ParseSingleValue(
@@ -18,18 +18,18 @@ const CSSValue* TextUnderlinePosition::ParseSingleValue(
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSIdentifierValue* under_value =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueUnder>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueUnder>(range);
CSSIdentifierValue* left_or_right_value = nullptr;
if (RuntimeEnabledFeatures::TextUnderlinePositionLeftRightEnabled()) {
left_or_right_value =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueLeft, CSSValueRight>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueLeft, CSSValueRight>(
range);
if (left_or_right_value && !under_value) {
under_value =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueUnder>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueUnder>(range);
}
}
if (!under_value && !left_or_right_value) {
@@ -70,5 +70,5 @@ const CSSValue* TextUnderlinePosition::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/top_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/top_custom.cc
index 8804de29e32..34328499657 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/top_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/top_custom.cc
@@ -15,13 +15,14 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Top::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeMarginOrOffset(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeMarginOrOffset(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool Top::IsLayoutDependent(const ComputedStyle* style,
@@ -39,5 +40,5 @@ const CSSValue* Top::CSSValueFromComputedStyleInternal(
layout_object);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/touch_action_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/touch_action_custom.cc
index 3905ac916a6..57897d6290c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/touch_action_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/touch_action_custom.cc
@@ -19,13 +19,13 @@ static bool ConsumePan(CSSParserTokenRange& range,
CSSValueID id = range.Peek().Id();
if ((id == CSSValuePanX || id == CSSValuePanRight || id == CSSValuePanLeft) &&
!pan_x) {
- pan_x = CSSPropertyParserHelpers::ConsumeIdent(range);
+ pan_x = css_property_parser_helpers::ConsumeIdent(range);
} else if ((id == CSSValuePanY || id == CSSValuePanDown ||
id == CSSValuePanUp) &&
!pan_y) {
- pan_y = CSSPropertyParserHelpers::ConsumeIdent(range);
+ pan_y = css_property_parser_helpers::ConsumeIdent(range);
} else if (id == CSSValuePinchZoom && !pinch_zoom) {
- pinch_zoom = CSSPropertyParserHelpers::ConsumeIdent(range);
+ pinch_zoom = css_property_parser_helpers::ConsumeIdent(range);
} else {
return false;
}
@@ -33,7 +33,7 @@ static bool ConsumePan(CSSParserTokenRange& range,
}
} // namespace
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TouchAction::ParseSingleValue(
CSSParserTokenRange& range,
@@ -42,7 +42,7 @@ const CSSValue* TouchAction::ParseSingleValue(
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
CSSValueID id = range.Peek().Id();
if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueManipulation) {
- list->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ list->Append(*css_property_parser_helpers::ConsumeIdent(range));
return list;
}
@@ -74,5 +74,5 @@ const CSSValue* TouchAction::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::TouchActionFlagsToCSSValue(style.GetTouchAction());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_box_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_box_custom.cc
index 137c2b0dab7..50dfff861b5 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_box_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_box_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/transform_box.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransformBox::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* TransformBox::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TransformBox());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_custom.cc
index 133bedb6965..e419eb86f4c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_custom.cc
@@ -14,13 +14,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Transform::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ConsumeTransformList(range, context, local_context);
+ return css_parsing_utils::ConsumeTransformList(range, context, local_context);
}
bool Transform::IsLayoutDependent(const ComputedStyle* style,
@@ -37,5 +37,5 @@ const CSSValue* Transform::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ComputedTransform(layout_object, style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_origin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_origin_custom.cc
index 1b17685c5d6..e5fd8d94be9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_origin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_origin_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransformOrigin::ParseSingleValue(
CSSParserTokenRange& range,
@@ -21,20 +21,17 @@ const CSSValue* TransformOrigin::ParseSingleValue(
const CSSParserLocalContext&) const {
CSSValue* result_x = nullptr;
CSSValue* result_y = nullptr;
- if (CSSPropertyParserHelpers::ConsumeOneOrTwoValuedPosition(
+ if (css_property_parser_helpers::ConsumeOneOrTwoValuedPosition(
range, context.Mode(),
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid, result_x,
+ css_property_parser_helpers::UnitlessQuirk::kForbid, result_x,
result_y)) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*result_x);
list->Append(*result_y);
- CSSValue* result_z = CSSPropertyParserHelpers::ConsumeLength(
+ CSSValue* result_z = css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeAll);
- if (!result_z) {
- result_z =
- CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kPixels);
- }
- list->Append(*result_z);
+ if (result_z)
+ list->Append(*result_z);
return list;
}
return nullptr;
@@ -74,5 +71,5 @@ const CSSValue* TransformOrigin::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_style_custom.cc
index e167986a014..60712b2ab6f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transform_style_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/transform_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransformStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -19,5 +19,5 @@ const CSSValue* TransformStyle::CSSValueFromComputedStyleInternal(
: CSSValueFlat);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_delay_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_delay_custom.cc
index 5fb5fc382c5..55a077efa5a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_delay_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_delay_custom.cc
@@ -7,17 +7,17 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransitionDelay::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeTime, range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeTime, range, kValueRangeAll);
}
const CSSValue* TransitionDelay::CSSValueFromComputedStyleInternal(
@@ -37,5 +37,5 @@ const CSSValue* TransitionDelay::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_duration_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_duration_custom.cc
index 4055c9891b1..dadf1e03d0f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_duration_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_duration_custom.cc
@@ -7,17 +7,17 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransitionDuration::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeTime, range, kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeTime, range, kValueRangeNonNegative);
}
const CSSValue* TransitionDuration::CSSValueFromComputedStyleInternal(
@@ -37,5 +37,5 @@ const CSSValue* TransitionDuration::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_property_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_property_custom.cc
index 2d5db6a1dec..407674c7647 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_property_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_property_custom.cc
@@ -11,15 +11,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransitionProperty::ParseSingleValue(
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- CSSValueList* list = CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeTransitionProperty, range);
- if (!list || !CSSParsingUtils::IsValidPropertyList(*list))
+ CSSValueList* list = css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeTransitionProperty, range, context);
+ if (!list || !css_parsing_utils::IsValidPropertyList(*list))
return nullptr;
return list;
}
@@ -39,5 +39,5 @@ const CSSValue* TransitionProperty::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_timing_function_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_timing_function_custom.cc
index fe475045bfa..50b2a1d5e3f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_timing_function_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/transition_timing_function_custom.cc
@@ -10,14 +10,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* TransitionTimingFunction::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeAnimationTimingFunction, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeAnimationTimingFunction, range);
}
const CSSValue* TransitionTimingFunction::CSSValueFromComputedStyleInternal(
@@ -36,5 +36,5 @@ const CSSValue* TransitionTimingFunction::InitialValue() const {
return value;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/translate_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/translate_custom.cc
index d924ca40c22..e513d0ee54a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/translate_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/translate_custom.cc
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Translate::ParseSingleValue(
CSSParserTokenRange& range,
@@ -23,22 +23,27 @@ const CSSValue* Translate::ParseSingleValue(
DCHECK(RuntimeEnabledFeatures::CSSIndependentTransformPropertiesEnabled());
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
- CSSValue* translate = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ CSSValue* translate_x = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll);
- if (!translate)
+ if (!translate_x)
return nullptr;
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- list->Append(*translate);
- translate = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, context.Mode(), kValueRangeAll);
- if (translate) {
- list->Append(*translate);
- translate = CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeAll);
- if (translate)
- list->Append(*translate);
+ list->Append(*translate_x);
+ CSSPrimitiveValue* translate_y =
+ css_property_parser_helpers::ConsumeLengthOrPercent(range, context.Mode(),
+ kValueRangeAll);
+ if (translate_y) {
+ CSSValue* translate_z = css_property_parser_helpers::ConsumeLength(
+ range, context.Mode(), kValueRangeAll);
+ if (translate_y->GetIntValue() == 0 && !translate_z)
+ return list;
+
+ list->Append(*translate_y);
+ if (translate_z) {
+ list->Append(*translate_z);
+ }
}
return list;
@@ -73,5 +78,5 @@ const CSSValue* Translate::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/unicode_bidi_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/unicode_bidi_custom.cc
index 847227cff15..8680d3ec356 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/unicode_bidi_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/unicode_bidi_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/unicode_bidi.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* UnicodeBidi::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* UnicodeBidi::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetUnicodeBidi());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/user_select_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/user_select_custom.cc
index 2c72d4e6ca0..5fca6fed2b0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/user_select_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/user_select_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/user_select.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* UserSelect::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* UserSelect::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.UserSelect());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.cc
index 398f185b0c5..4c21de56427 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.cc
@@ -4,77 +4,12 @@
#include "third_party/blink/renderer/core/css/properties/longhands/variable.h"
-#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
-#include "third_party/blink/renderer/core/css/property_registration.h"
-#include "third_party/blink/renderer/core/css/property_registry.h"
-#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/core/css/properties/css_property.h"
namespace blink {
-namespace {
-
-void ApplyInitialValue(StyleResolverState& state,
- const AtomicString& name,
- const PropertyRegistration* registration) {
- bool is_inherited_property = !registration || registration->Inherits();
- state.Style()->RemoveVariable(name, is_inherited_property);
-}
-
-void ApplyInheritValue(StyleResolverState& state,
- const AtomicString& name,
- const PropertyRegistration* registration) {
- bool is_inherited_property = !registration || registration->Inherits();
- state.Style()->RemoveVariable(name, is_inherited_property);
-
- CSSVariableData* parent_value =
- state.ParentStyle()->GetVariable(name, is_inherited_property);
-
- if (!parent_value)
- return;
-
- state.Style()->SetVariable(name, parent_value, is_inherited_property);
-
- if (registration) {
- const CSSValue* parent_css_value =
- parent_value ? state.ParentStyle()->GetRegisteredVariable(
- name, is_inherited_property)
- : nullptr;
- state.Style()->SetRegisteredVariable(name, parent_css_value,
- is_inherited_property);
- }
-}
-
-} // namespace
-
-void Variable::ApplyValue(StyleResolverState& state,
- const CSSValue& value) const {
- const CSSCustomPropertyDeclaration& declaration =
- ToCSSCustomPropertyDeclaration(value);
- const AtomicString& name = declaration.GetName();
- const PropertyRegistration* registration = nullptr;
- const PropertyRegistry* registry = state.GetDocument().GetPropertyRegistry();
- if (registry)
- registration = registry->Registration(name);
-
- bool is_inherited_property = !registration || registration->Inherits();
- bool initial = declaration.IsInitial(is_inherited_property);
- bool inherit = declaration.IsInherit(is_inherited_property);
- DCHECK(!(initial && inherit));
-
- // TODO(andruud): Use regular initial/inherit dispatch in StyleBuilder
- // once custom properties are Ribbonized.
- if (initial) {
- ApplyInitialValue(state, name, registration);
- } else if (inherit) {
- ApplyInheritValue(state, name, registration);
- } else {
- state.Style()->SetVariable(name, declaration.Value(),
- is_inherited_property);
- if (registration) {
- state.Style()->SetRegisteredVariable(name, nullptr,
- is_inherited_property);
- }
- }
+bool Variable::IsStaticInstance(const CSSProperty& property) {
+ return &property == &GetCSSPropertyVariable();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.h b/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.h
index 6faf1e60701..cb0137e5c2b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/variable.h
@@ -13,7 +13,9 @@
namespace blink {
-class Variable final : public Longhand {
+// TODO(andruud): Remove this class when the static Variable instance
+// (as returned by GetCSSPropertyVariable()) has been removed.
+class CORE_EXPORT Variable : public Longhand {
public:
constexpr Variable() : Longhand() {}
@@ -25,18 +27,8 @@ class Variable final : public Longhand {
DEFINE_STATIC_LOCAL(const AtomicString, name, ("variable"));
return name;
}
- const CSSValue* CSSValueFromComputedStyleInternal(
- const ComputedStyle&,
- const SVGComputedStyle&,
- const LayoutObject*,
- Node*,
- bool allow_visited_style) const override {
- NOTREACHED();
- return nullptr;
- }
- void ApplyValue(StyleResolverState& state,
- const CSSValue& value) const override;
+ static bool IsStaticInstance(const CSSProperty&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/vector_effect_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/vector_effect_custom.cc
index 245092978a8..2c65fd53465 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/vector_effect_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/vector_effect_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/vector_effect.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* VectorEffect::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* VectorEffect::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(svg_style.VectorEffect());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/vertical_align_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/vertical_align_custom.cc
index faebb54554b..33acfa75f5c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/vertical_align_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/vertical_align_custom.cc
@@ -10,18 +10,18 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* VerticalAlign::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- CSSValue* parsed_value = CSSPropertyParserHelpers::ConsumeIdentRange(
+ CSSValue* parsed_value = css_property_parser_helpers::ConsumeIdentRange(
range, CSSValueBaseline, CSSValueWebkitBaselineMiddle);
if (!parsed_value) {
- parsed_value = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ parsed_value = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
return parsed_value;
}
@@ -80,5 +80,5 @@ void VerticalAlign::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/visibility_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/visibility_custom.cc
index 674c338796f..bf661350510 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/visibility_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/visibility_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/visibility.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Visibility::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* Visibility::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.Visibility());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_app_region_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_app_region_custom.cc
index acf27dac60f..b14f67f6250 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_app_region_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_app_region_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitAppRegion::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -38,5 +38,5 @@ void WebkitAppRegion::ApplyValue(StyleResolverState& state,
state.GetDocument().SetHasAnnotatedRegions(true);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_appearance_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_appearance_custom.cc
index 15407fff637..e548064bca0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_appearance_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_appearance_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitAppearance::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -18,5 +18,5 @@ const CSSValue* WebkitAppearance::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.Appearance());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_horizontal_spacing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_horizontal_spacing_custom.cc
index 26d334c183b..965ce1c4f71 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_horizontal_spacing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_horizontal_spacing_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBorderHorizontalSpacing::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
+ kValueRangeNonNegative);
}
const CSSValue*
@@ -29,5 +29,5 @@ WebkitBorderHorizontalSpacing::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.HorizontalBorderSpacing(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_image_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_image_custom.cc
index 700e42d5a6c..ae40d8937e0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_image_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_image_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBorderImage::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWebkitBorderImage(range, context);
+ return css_parsing_utils::ConsumeWebkitBorderImage(range, context);
}
const CSSValue* WebkitBorderImage::CSSValueFromComputedStyleInternal(
@@ -35,5 +35,5 @@ void WebkitBorderImage::ApplyValue(StyleResolverState& state,
state.Style()->SetBorderImage(image);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing_custom.cc
index 113f14447fc..b0fd820cb86 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBorderVerticalSpacing::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
+ kValueRangeNonNegative);
}
const CSSValue* WebkitBorderVerticalSpacing::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* WebkitBorderVerticalSpacing::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.VerticalBorderSpacing(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_align_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_align_custom.cc
index faeb97de4dd..5541d46614d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_align_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_align_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_align.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxAlign::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitBoxAlign::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BoxAlign());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_decoration_break_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_decoration_break_custom.cc
index f2e3bfc460a..25bc591dc1b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_decoration_break_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_decoration_break_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxDecorationBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* WebkitBoxDecorationBreak::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(CSSValueClone);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction_custom.cc
index 9b65e12dd84..9c27821b884 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxDirection::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitBoxDirection::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BoxDirection());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_flex_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_flex_custom.cc
index 1fde2e2fed8..5504909e0bd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_flex_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_flex_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxFlex::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* WebkitBoxFlex::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* WebkitBoxFlex::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_ordinal_group_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_ordinal_group_custom.cc
index 7ef8905eda4..502aaef4d83 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_ordinal_group_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_ordinal_group_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxOrdinalGroup::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumePositiveInteger(range);
+ return css_property_parser_helpers::ConsumePositiveInteger(range);
}
const CSSValue* WebkitBoxOrdinalGroup::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* WebkitBoxOrdinalGroup::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient_custom.cc
index 82dd04f19b8..ec1ace9bdd7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxOrient::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitBoxOrient::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BoxOrient());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack_custom.cc
index 9d8c74f6ed1..834b6e36dfd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxPack::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitBoxPack::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.BoxPack());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_reflect_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_reflect_custom.cc
index a370a0ee5bc..187e7478023 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_reflect_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_box_reflect_custom.cc
@@ -17,7 +17,7 @@ namespace {
CSSValue* ConsumeReflect(CSSParserTokenRange& range,
const CSSParserContext& context) {
- CSSIdentifierValue* direction = CSSPropertyParserHelpers::ConsumeIdent<
+ CSSIdentifierValue* direction = css_property_parser_helpers::ConsumeIdent<
CSSValueAbove, CSSValueBelow, CSSValueLeft, CSSValueRight>(range);
if (!direction)
return nullptr;
@@ -28,14 +28,14 @@ CSSValue* ConsumeReflect(CSSParserTokenRange& range,
} else {
offset = ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
if (!offset)
return nullptr;
}
CSSValue* mask = nullptr;
if (!range.AtEnd()) {
- mask = CSSParsingUtils::ConsumeWebkitBorderImage(range, context);
+ mask = css_parsing_utils::ConsumeWebkitBorderImage(range, context);
if (!mask)
return nullptr;
}
@@ -43,7 +43,7 @@ CSSValue* ConsumeReflect(CSSParserTokenRange& range,
}
} // namespace
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitBoxReflect::ParseSingleValue(
CSSParserTokenRange& range,
@@ -61,5 +61,5 @@ const CSSValue* WebkitBoxReflect::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForReflection(style.BoxReflect(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_size_delta_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_size_delta_custom.cc
index 3a91866211e..ed33b92f2ff 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_size_delta_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_size_delta_custom.cc
@@ -8,16 +8,16 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitFontSizeDelta::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLength(
+ return css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_smoothing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_smoothing_custom.cc
index c6239aa39d0..7efe52b5b7d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_smoothing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_font_smoothing_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitFontSmoothing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -18,5 +18,5 @@ const CSSValue* WebkitFontSmoothing::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetFontDescription().FontSmoothing());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_highlight_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_highlight_custom.cc
index a464f6fbf49..04f5bc26246 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_highlight_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_highlight_custom.cc
@@ -9,15 +9,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitHighlight::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeString(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeString(range);
}
const CSSValue* WebkitHighlight::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* WebkitHighlight::CSSValueFromComputedStyleInternal(
return CSSStringValue::Create(style.Highlight());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_hyphenate_character_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_hyphenate_character_custom.cc
index fca12033eaa..8009063c998 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_hyphenate_character_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_hyphenate_character_custom.cc
@@ -9,15 +9,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitHyphenateCharacter::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeString(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeString(range);
}
const CSSValue* WebkitHyphenateCharacter::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* WebkitHyphenateCharacter::CSSValueFromComputedStyleInternal(
return CSSStringValue::Create(style.HyphenationString());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_break_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_break_custom.cc
index e2940892c2d..3e56971b4b9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_break_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_break_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_line_break.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitLineBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitLineBreak::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetLineBreak());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_clamp_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_clamp_custom.cc
index 23a30d3d7f6..6bb0bb1bc73 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_clamp_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_line_clamp_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitLineClamp::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
// When specifying number of lines, don't allow 0 as a valid value.
- return CSSPropertyParserHelpers::ConsumePositiveInteger(range);
+ return css_property_parser_helpers::ConsumePositiveInteger(range);
}
const CSSValue* WebkitLineClamp::CSSValueFromComputedStyleInternal(
@@ -30,5 +30,5 @@ const CSSValue* WebkitLineClamp::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_locale_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_locale_custom.cc
index 96b3e203bb8..e603549ff25 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_locale_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_locale_custom.cc
@@ -9,15 +9,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitLocale::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeString(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeString(range);
}
const CSSValue* WebkitLocale::CSSValueFromComputedStyleInternal(
@@ -42,5 +42,5 @@ void WebkitLocale::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse_custom.cc
index 985fbc80880..cc9a58395ee 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMarginAfterCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitMarginAfterCollapse::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.MarginAfterCollapse());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse_custom.cc
index 10fb47023eb..d5aed0b912f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMarginBeforeCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitMarginBeforeCollapse::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.MarginBeforeCollapse());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse_custom.cc
index 3965797b787..096a6a59c13 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMarginBottomCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitMarginBottomCollapse::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.MarginAfterCollapse());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse_custom.cc
index c2b5350e1b9..b249f9a086b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMarginTopCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitMarginTopCollapse::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.MarginBeforeCollapse());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_outset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_outset_custom.cc
index 4e276e20827..f06733d65a2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_outset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_outset_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskBoxImageOutset::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageOutset(range);
+ return css_parsing_utils::ConsumeBorderImageOutset(range);
}
const CSSValue* WebkitMaskBoxImageOutset::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* WebkitMaskBoxImageOutset::CSSValueFromComputedStyleInternal(
style.MaskBoxImage().Outset(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_repeat_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_repeat_custom.cc
index ed21f3f8800..814a43b04bb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_repeat_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_repeat_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskBoxImageRepeat::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageRepeat(range);
+ return css_parsing_utils::ConsumeBorderImageRepeat(range);
}
const CSSValue* WebkitMaskBoxImageRepeat::CSSValueFromComputedStyleInternal(
@@ -27,5 +27,5 @@ const CSSValue* WebkitMaskBoxImageRepeat::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForNinePieceImageRepeat(style.MaskBoxImage());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_slice_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_slice_custom.cc
index de6bd72960c..93383d22e55 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_slice_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_slice_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskBoxImageSlice::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageSlice(
- range, CSSParsingUtils::DefaultFill::kNoFill);
+ return css_parsing_utils::ConsumeBorderImageSlice(
+ range, css_parsing_utils::DefaultFill::kNoFill);
}
const CSSValue* WebkitMaskBoxImageSlice::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* WebkitMaskBoxImageSlice::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForNinePieceImageSlice(style.MaskBoxImage());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_source_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_source_custom.cc
index 7390074dd9a..dae0afee1c2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_source_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_source_custom.cc
@@ -11,13 +11,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskBoxImageSource::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeImageOrNone(range, &context);
+ return css_property_parser_helpers::ConsumeImageOrNone(range, &context);
}
const CSSValue* WebkitMaskBoxImageSource::CSSValueFromComputedStyleInternal(
@@ -37,5 +37,5 @@ void WebkitMaskBoxImageSource::ApplyValue(StyleResolverState& state,
state.GetStyleImage(CSSPropertyWebkitMaskBoxImageSource, value));
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_width_custom.cc
index 497407b6a3a..5480dac2b7f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_width_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskBoxImageWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeBorderImageWidth(range);
+ return css_parsing_utils::ConsumeBorderImageWidth(range);
}
const CSSValue* WebkitMaskBoxImageWidth::CSSValueFromComputedStyleInternal(
@@ -28,5 +28,5 @@ const CSSValue* WebkitMaskBoxImageWidth::CSSValueFromComputedStyleInternal(
style.MaskBoxImage().BorderSlices(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_clip_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_clip_custom.cc
index d42ed11f491..6b4721c41d9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_clip_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_clip_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskClip::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumePrefixedBackgroundBox, range,
- CSSParsingUtils::AllowTextValue::kAllow);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumePrefixedBackgroundBox, range,
+ css_parsing_utils::AllowTextValue::kAllow);
}
const CSSValue* WebkitMaskClip::CSSValueFromComputedStyleInternal(
@@ -36,5 +36,5 @@ const CSSValue* WebkitMaskClip::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_composite_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_composite_custom.cc
index 36a82ce4b75..65aa267478a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_composite_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_composite_custom.cc
@@ -8,14 +8,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskComposite::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumeBackgroundComposite, range);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumeBackgroundComposite, range);
}
const CSSValue* WebkitMaskComposite::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* WebkitMaskComposite::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_image_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_image_custom.cc
index cd7007c2e93..07f34cb7a3f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_image_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_image_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskImage::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSPropertyParserHelpers::ConsumeImageOrNone, range, &context);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_property_parser_helpers::ConsumeImageOrNone, range, &context);
}
const CSSValue* WebkitMaskImage::CSSValueFromComputedStyleInternal(
@@ -29,5 +29,5 @@ const CSSValue* WebkitMaskImage::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::BackgroundImageOrWebkitMaskImage(fill_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_origin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_origin_custom.cc
index ecfc25b2308..1ef8a4bd92a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_origin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_origin_custom.cc
@@ -10,15 +10,15 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskOrigin::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumePrefixedBackgroundBox, range,
- CSSParsingUtils::AllowTextValue::kForbid);
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumePrefixedBackgroundBox, range,
+ css_parsing_utils::AllowTextValue::kForbid);
}
const CSSValue* WebkitMaskOrigin::CSSValueFromComputedStyleInternal(
@@ -36,5 +36,5 @@ const CSSValue* WebkitMaskOrigin::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_x_custom.cc
index 442bfafa946..5de6d2e0d79 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_x_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskPositionX::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumePositionLonghand<CSSValueLeft, CSSValueRight>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumePositionLonghand<CSSValueLeft, CSSValueRight>,
range, context.Mode());
}
@@ -33,5 +33,5 @@ const CSSValue* WebkitMaskPositionX::CSSValueFromComputedStyleInternal(
style, curr_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_y_custom.cc
index c61426e6e31..1327489a9ca 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_y_custom.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskPositionY::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeCommaSeparatedList(
- CSSParsingUtils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>,
+ return css_property_parser_helpers::ConsumeCommaSeparatedList(
+ css_parsing_utils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>,
range, context.Mode());
}
@@ -33,5 +33,5 @@ const CSSValue* WebkitMaskPositionY::CSSValueFromComputedStyleInternal(
style, curr_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_size_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_size_custom.cc
index 5a179bc208d..2f6565b60c4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_size_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_mask_size_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitMaskSize::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext& local_context) const {
- return CSSParsingUtils::ParseBackgroundOrMaskSize(
+ return css_parsing_utils::ParseBackgroundOrMaskSize(
range, context, local_context, WebFeature::kNegativeMaskSize);
}
@@ -30,5 +30,5 @@ const CSSValue* WebkitMaskSize::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::BackgroundImageOrWebkitMaskSize(style, fill_layer);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_x_custom.cc
index 1320f1a9035..8b2599d0cc7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_x_custom.cc
@@ -9,15 +9,16 @@
#include "third_party/blink/renderer/core/css_value_keywords.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitPerspectiveOriginX::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumePositionLonghand<CSSValueLeft, CSSValueRight>(
+ return css_parsing_utils::ConsumePositionLonghand<CSSValueLeft,
+ CSSValueRight>(
range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_y_custom.cc
index dde58f0021f..3b4020f3c1a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_y_custom.cc
@@ -9,15 +9,16 @@
#include "third_party/blink/renderer/core/css_value_keywords.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitPerspectiveOriginY::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>(
+ return css_parsing_utils::ConsumePositionLonghand<CSSValueTop,
+ CSSValueBottom>(
range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust_custom.cc
index fd9a805f78b..6f2f4def100 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitPrintColorAdjust::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitPrintColorAdjust::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.PrintColorAdjust());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering_custom.cc
index 7b951869cec..7419992f18e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitRtlOrdering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -18,5 +18,5 @@ const CSSValue* WebkitRtlOrdering::CSSValueFromComputedStyleInternal(
: CSSValueLogical);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position_custom.cc
index 79cfda5c7a3..27992bae1c8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitRubyPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitRubyPosition::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.GetRubyPosition());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_tap_highlight_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_tap_highlight_color_custom.cc
index 6294875e7af..f438a4bc1ab 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_tap_highlight_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_tap_highlight_color_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTapHighlightColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color WebkitTapHighlightColor::ColorIncludingFallback(
@@ -37,5 +37,5 @@ const CSSValue* WebkitTapHighlightColor::CSSValueFromComputedStyleInternal(
style, style.TapHighlightColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_combine_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_combine_custom.cc
index d4c3ec458f8..ba24bd2364e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_combine_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_combine_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextCombine::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -20,5 +20,5 @@ const CSSValue* WebkitTextCombine::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TextCombine());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_decorations_in_effect_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_decorations_in_effect_custom.cc
index b849101df4c..af03a24e751 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_decorations_in_effect_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_decorations_in_effect_custom.cc
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextDecorationsInEffect::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext&,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeTextDecorationLine(range);
+ return css_parsing_utils::ConsumeTextDecorationLine(range);
}
const CSSValue*
@@ -29,5 +29,5 @@ WebkitTextDecorationsInEffect::CSSValueFromComputedStyleInternal(
style.TextDecorationsInEffect());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_color_custom.cc
index 5b748146760..fa8356403d6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_color_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextEmphasisColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color WebkitTextEmphasisColor::ColorIncludingFallback(
@@ -39,5 +39,5 @@ const CSSValue* WebkitTextEmphasisColor::CSSValueFromComputedStyleInternal(
style, style.TextEmphasisColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_position_custom.cc
index 074b51f337c..68079e5a9eb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_position_custom.cc
@@ -13,7 +13,7 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
// [ over | under ] && [ right | left ]?
// If [ right | left ] is omitted, it defaults to right.
@@ -22,13 +22,13 @@ const CSSValue* WebkitTextEmphasisPosition::ParseSingleValue(
const CSSParserContext& context,
const CSSParserLocalContext&) const {
CSSIdentifierValue* values[2] = {
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueOver, CSSValueUnder,
- CSSValueRight, CSSValueLeft>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueOver, CSSValueUnder,
+ CSSValueRight, CSSValueLeft>(
range),
nullptr};
if (!values[0])
return nullptr;
- values[1] = CSSPropertyParserHelpers::ConsumeIdent<
+ values[1] = css_property_parser_helpers::ConsumeIdent<
CSSValueOver, CSSValueUnder, CSSValueRight, CSSValueLeft>(range);
CSSIdentifierValue* over_under = nullptr;
CSSIdentifierValue* left_right = nullptr;
@@ -92,5 +92,5 @@ const CSSValue* WebkitTextEmphasisPosition::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_style_custom.cc
index cbc33535993..6468e778391 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_style_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextEmphasisStyle::ParseSingleValue(
CSSParserTokenRange& range,
@@ -19,23 +19,22 @@ const CSSValue* WebkitTextEmphasisStyle::ParseSingleValue(
const CSSParserLocalContext&) const {
CSSValueID id = range.Peek().Id();
if (id == CSSValueNone)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
if (CSSValue* text_emphasis_style =
- CSSPropertyParserHelpers::ConsumeString(range))
+ css_property_parser_helpers::ConsumeString(range))
return text_emphasis_style;
CSSIdentifierValue* fill =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueFilled, CSSValueOpen>(
- range);
- CSSIdentifierValue* shape =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueDot, CSSValueCircle,
- CSSValueDoubleCircle,
- CSSValueTriangle, CSSValueSesame>(
+ css_property_parser_helpers::ConsumeIdent<CSSValueFilled, CSSValueOpen>(
range);
+ CSSIdentifierValue* shape = css_property_parser_helpers::ConsumeIdent<
+ CSSValueDot, CSSValueCircle, CSSValueDoubleCircle, CSSValueTriangle,
+ CSSValueSesame>(range);
if (!fill) {
- fill = CSSPropertyParserHelpers::ConsumeIdent<CSSValueFilled, CSSValueOpen>(
- range);
+ fill =
+ css_property_parser_helpers::ConsumeIdent<CSSValueFilled, CSSValueOpen>(
+ range);
}
if (fill && shape) {
CSSValueList* parsed_values = CSSValueList::CreateSpaceSeparated();
@@ -138,5 +137,5 @@ void WebkitTextEmphasisStyle::ApplyValue(StyleResolverState& state,
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_fill_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_fill_color_custom.cc
index 3aeeb2de6dd..bb214a61028 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_fill_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_fill_color_custom.cc
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextFillColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color WebkitTextFillColor::ColorIncludingFallback(
@@ -39,5 +39,5 @@ const CSSValue* WebkitTextFillColor::CSSValueFromComputedStyleInternal(
style.TextFillColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_orientation_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_orientation_custom.cc
index fa32fe3a0e2..354ead7741f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_orientation_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_orientation_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextOrientation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -26,5 +26,5 @@ void WebkitTextOrientation::ApplyValue(StyleResolverState& state,
ToCSSIdentifierValue(value).ConvertTo<ETextOrientation>());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_security_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_security_custom.cc
index 4388ee02c57..4fc247e1ac5 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_security_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_security_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_security.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextSecurity::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitTextSecurity::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.TextSecurity());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_color_custom.cc
index 0fe2bf8d629..1da797d6a34 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_color_custom.cc
@@ -13,13 +13,13 @@ namespace blink {
class CSSParserLocalContext;
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextStrokeColor::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode());
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
}
const blink::Color WebkitTextStrokeColor::ColorIncludingFallback(
@@ -42,5 +42,5 @@ const CSSValue* WebkitTextStrokeColor::CSSValueFromComputedStyleInternal(
style.TextStrokeColor());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_width_custom.cc
index 48a0e1f98c9..5623d1b274b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_width_custom.cc
@@ -9,14 +9,15 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTextStrokeWidth::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLineWidth(
- range, context.Mode(), CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeLineWidth(
+ range, context.Mode(),
+ css_property_parser_helpers::UnitlessQuirk::kForbid);
}
const CSSValue* WebkitTextStrokeWidth::CSSValueFromComputedStyleInternal(
@@ -28,5 +29,5 @@ const CSSValue* WebkitTextStrokeWidth::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.TextStrokeWidth(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_x_custom.cc
index 62ac87f860b..5b3f9696467 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_x_custom.cc
@@ -9,15 +9,16 @@
#include "third_party/blink/renderer/core/css_value_keywords.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTransformOriginX::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumePositionLonghand<CSSValueLeft, CSSValueRight>(
+ return css_parsing_utils::ConsumePositionLonghand<CSSValueLeft,
+ CSSValueRight>(
range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_y_custom.cc
index cf89929fa15..0d0d1f3f51d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_y_custom.cc
@@ -9,15 +9,16 @@
#include "third_party/blink/renderer/core/css_value_keywords.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTransformOriginY::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>(
+ return css_parsing_utils::ConsumePositionLonghand<CSSValueTop,
+ CSSValueBottom>(
range, context.Mode());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_z_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_z_custom.cc
index be88496d3e1..d417dd43f9d 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_z_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_z_custom.cc
@@ -8,15 +8,15 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitTransformOriginZ::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLength(range, context.Mode(),
- kValueRangeAll);
+ return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
+ kValueRangeAll);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag_custom.cc
index 0ddc3d4b847..284a76c64ea 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitUserDrag::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitUserDrag::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.UserDrag());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify_custom.cc
index 27ea95382df..f0ee863bba4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitUserModify::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WebkitUserModify::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.UserModify());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode_custom.cc
index 1aa5e106d86..bfa124478fc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WebkitWritingMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -22,5 +22,5 @@ void WebkitWritingMode::ApplyValue(StyleResolverState& state,
ToCSSIdentifierValue(value).ConvertTo<blink::WritingMode>());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/white_space_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/white_space_custom.cc
index 5ee78020bf6..d35361227ba 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/white_space_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/white_space_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/white_space.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WhiteSpace::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WhiteSpace::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.WhiteSpace());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/widows_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/widows_custom.cc
index ab2a9a90936..cded0238bc6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/widows_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/widows_custom.cc
@@ -8,12 +8,12 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Widows::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumePositiveInteger(range);
+ return css_property_parser_helpers::ConsumePositiveInteger(range);
}
const CSSValue* Widows::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* Widows::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kNumber);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/width_custom.cc
index 875578372a1..e48fb203761 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/width_custom.cc
@@ -11,13 +11,13 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Width::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ConsumeWidthOrHeight(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ return css_parsing_utils::ConsumeWidthOrHeight(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
bool Width::IsLayoutDependent(const ComputedStyle* style,
@@ -39,5 +39,5 @@ const CSSValue* Width::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/will_change_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/will_change_custom.cc
index 8caadeae027..aefee07e956 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/will_change_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/will_change_custom.cc
@@ -12,14 +12,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WillChange::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
CSSValueList* values = CSSValueList::CreateCommaSeparated();
// Every comma-separated list of identifiers is a valid will-change value,
@@ -53,7 +53,7 @@ const CSSValue* WillChange::ParseSingleValue(
return nullptr;
case CSSValueContents:
case CSSValueScrollPosition:
- values->Append(*CSSPropertyParserHelpers::ConsumeIdent(range));
+ values->Append(*css_property_parser_helpers::ConsumeIdent(range));
break;
default:
range.ConsumeIncludingWhitespace();
@@ -63,7 +63,7 @@ const CSSValue* WillChange::ParseSingleValue(
if (range.AtEnd())
break;
- if (!CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeCommaIncludingWhitespace(range))
return nullptr;
}
@@ -132,5 +132,5 @@ void WillChange::ApplyValue(StyleResolverState& state,
will_change_contents || state.ParentStyle()->SubtreeWillChangeContents());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/word_break_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/word_break_custom.cc
index 90d0875bf7c..e1ebe16edcb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/word_break_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/word_break_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/word_break.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WordBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -16,5 +16,5 @@ const CSSValue* WordBreak::CSSValueFromComputedStyleInternal(
return CSSIdentifierValue::Create(style.WordBreak());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/word_spacing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/word_spacing_custom.cc
index 12f0d3f79aa..8c0b30674d5 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/word_spacing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/word_spacing_custom.cc
@@ -8,13 +8,13 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WordSpacing::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSParsingUtils::ParseSpacing(range, context);
+ return css_parsing_utils::ParseSpacing(range, context);
}
const CSSValue* WordSpacing::CSSValueFromComputedStyleInternal(
@@ -26,5 +26,5 @@ const CSSValue* WordSpacing::CSSValueFromComputedStyleInternal(
return ZoomAdjustedPixelValue(style.WordSpacing(), style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/writing_mode_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/writing_mode_custom.cc
index 36b2dd68322..7c73effe1a3 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/writing_mode_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/writing_mode_custom.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/properties/longhands/writing_mode.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* WritingMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
@@ -22,5 +22,5 @@ void WritingMode::ApplyValue(StyleResolverState& state,
ToCSSIdentifierValue(value).ConvertTo<blink::WritingMode>());
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/x_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/x_custom.cc
index 1d40a1a1603..27166019a09 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/x_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/x_custom.cc
@@ -8,14 +8,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* X::ParseSingleValue(CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeAll);
}
const CSSValue* X::CSSValueFromComputedStyleInternal(
@@ -28,5 +27,5 @@ const CSSValue* X::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/y_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/y_custom.cc
index 3f11b322eac..eaa456c3308 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/y_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/y_custom.cc
@@ -8,14 +8,13 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Y::ParseSingleValue(CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&) const {
- return CSSPropertyParserHelpers::ConsumeLengthOrPercent(
- range, kSVGAttributeMode, kValueRangeAll,
- CSSPropertyParserHelpers::UnitlessQuirk::kForbid);
+ return css_property_parser_helpers::ConsumeSVGGeometryPropertyLength(
+ range, context, kValueRangeAll);
}
const CSSValue* Y::CSSValueFromComputedStyleInternal(
@@ -28,5 +27,5 @@ const CSSValue* Y::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/z_index_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/z_index_custom.cc
index f807bef3d45..966179c2cae 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/z_index_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/z_index_custom.cc
@@ -9,14 +9,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* ZIndex::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
if (range.Peek().Id() == CSSValueAuto)
- return CSSPropertyParserHelpers::ConsumeIdent(range);
- return CSSPropertyParserHelpers::ConsumeInteger(range);
+ return css_property_parser_helpers::ConsumeIdent(range);
+ return css_property_parser_helpers::ConsumeInteger(range);
}
const CSSValue* ZIndex::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* ZIndex::CSSValueFromComputedStyleInternal(
CSSPrimitiveValue::UnitType::kInteger);
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/longhands/zoom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/zoom_custom.cc
index 150dc75aefa..269a6107887 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/zoom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/zoom_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSLonghand {
+namespace css_longhand {
const CSSValue* Zoom::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
@@ -18,13 +18,13 @@ const CSSValue* Zoom::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserToken& token = range.Peek();
CSSValue* zoom = nullptr;
if (token.GetType() == kIdentToken) {
- zoom = CSSPropertyParserHelpers::ConsumeIdent<CSSValueNormal>(range);
+ zoom = css_property_parser_helpers::ConsumeIdent<CSSValueNormal>(range);
} else {
- zoom =
- CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
+ zoom = css_property_parser_helpers::ConsumePercent(range,
+ kValueRangeNonNegative);
if (!zoom) {
- zoom = CSSPropertyParserHelpers::ConsumeNumber(range,
- kValueRangeNonNegative);
+ zoom = css_property_parser_helpers::ConsumeNumber(range,
+ kValueRangeNonNegative);
}
}
if (zoom) {
@@ -80,5 +80,5 @@ void Zoom::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
}
}
-} // namespace CSSLonghand
+} // namespace css_longhand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc
index 29e35a17f76..eb60bd55abb 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc
@@ -23,28 +23,28 @@ CSSValue* ConsumeAnimationValue(CSSPropertyID property,
bool use_legacy_parsing) {
switch (property) {
case CSSPropertyAnimationDelay:
- return CSSPropertyParserHelpers::ConsumeTime(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeTime(range, kValueRangeAll);
case CSSPropertyAnimationDirection:
- return CSSPropertyParserHelpers::ConsumeIdent<
+ return css_property_parser_helpers::ConsumeIdent<
CSSValueNormal, CSSValueAlternate, CSSValueReverse,
CSSValueAlternateReverse>(range);
case CSSPropertyAnimationDuration:
- return CSSPropertyParserHelpers::ConsumeTime(range,
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeTime(range,
+ kValueRangeNonNegative);
case CSSPropertyAnimationFillMode:
- return CSSPropertyParserHelpers::ConsumeIdent<
+ return css_property_parser_helpers::ConsumeIdent<
CSSValueNone, CSSValueForwards, CSSValueBackwards, CSSValueBoth>(
range);
case CSSPropertyAnimationIterationCount:
- return CSSParsingUtils::ConsumeAnimationIterationCount(range);
+ return css_parsing_utils::ConsumeAnimationIterationCount(range);
case CSSPropertyAnimationName:
- return CSSParsingUtils::ConsumeAnimationName(range, context,
- use_legacy_parsing);
+ return css_parsing_utils::ConsumeAnimationName(range, context,
+ use_legacy_parsing);
case CSSPropertyAnimationPlayState:
- return CSSPropertyParserHelpers::ConsumeIdent<CSSValueRunning,
- CSSValuePaused>(range);
+ return css_property_parser_helpers::ConsumeIdent<CSSValueRunning,
+ CSSValuePaused>(range);
case CSSPropertyAnimationTimingFunction:
- return CSSParsingUtils::ConsumeAnimationTimingFunction(range);
+ return css_parsing_utils::ConsumeAnimationTimingFunction(range);
default:
NOTREACHED();
return nullptr;
@@ -52,7 +52,7 @@ CSSValue* ConsumeAnimationValue(CSSPropertyID property,
}
} // namespace
-namespace CSSShorthand {
+namespace css_shorthand {
bool Animation::ParseShorthand(
bool important,
@@ -63,18 +63,19 @@ bool Animation::ParseShorthand(
const StylePropertyShorthand shorthand = animationShorthandForParsing();
const unsigned longhand_count = shorthand.length();
- HeapVector<Member<CSSValueList>, CSSParsingUtils::kMaxNumAnimationLonghands>
+ HeapVector<Member<CSSValueList>, css_parsing_utils::kMaxNumAnimationLonghands>
longhands(longhand_count);
- if (!CSSParsingUtils::ConsumeAnimationShorthand(
+ if (!css_parsing_utils::ConsumeAnimationShorthand(
shorthand, longhands, ConsumeAnimationValue, range, context,
local_context.UseAliasParsing())) {
return false;
}
for (unsigned i = 0; i < longhand_count; ++i) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
shorthand.properties()[i]->PropertyID(), shorthand.id(), *longhands[i],
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
}
return range.AtEnd();
@@ -136,5 +137,5 @@ const CSSValue* Animation::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_custom.cc
index f410e160208..a0cd224bd3b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Background::ParseShorthand(
bool important,
@@ -17,8 +17,8 @@ bool Background::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext& local_context,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSParsingUtils::ParseBackgroundOrMask(important, range, context,
- local_context, properties);
+ return css_parsing_utils::ParseBackgroundOrMask(important, range, context,
+ local_context, properties);
}
const CSSValue* Background::CSSValueFromComputedStyleInternal(
@@ -31,5 +31,5 @@ const CSSValue* Background::CSSValueFromComputedStyleInternal(
style, layout_object, styled_node, allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_position_custom.cc
index 3ec724e5cfb..cef5bc7fed9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_position_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BackgroundPosition::ParseShorthand(
bool important,
@@ -22,20 +22,20 @@ bool BackgroundPosition::ParseShorthand(
CSSValue* result_x = nullptr;
CSSValue* result_y = nullptr;
- if (!CSSParsingUtils::ConsumeBackgroundPosition(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow,
+ if (!css_parsing_utils::ConsumeBackgroundPosition(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow,
result_x, result_y) ||
!range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBackgroundPositionX, CSSPropertyBackgroundPosition, *result_x,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBackgroundPositionY, CSSPropertyBackgroundPosition, *result_y,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
}
@@ -50,5 +50,5 @@ const CSSValue* BackgroundPosition::CSSValueFromComputedStyleInternal(
*this, style, &style.BackgroundLayers());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_repeat_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_repeat_custom.cc
index c99c683f3d4..61a9742e99b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_repeat_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/background_repeat_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BackgroundRepeat::ParseShorthand(
bool important,
@@ -24,22 +24,22 @@ bool BackgroundRepeat::ParseShorthand(
CSSValue* result_x = nullptr;
CSSValue* result_y = nullptr;
bool implicit = false;
- if (!CSSParsingUtils::ConsumeRepeatStyle(range, result_x, result_y,
- implicit) ||
+ if (!css_parsing_utils::ConsumeRepeatStyle(range, result_x, result_y,
+ implicit) ||
!range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBackgroundRepeatX, CSSPropertyBackgroundRepeat, *result_x,
important,
- implicit ? CSSPropertyParserHelpers::IsImplicitProperty::kImplicit
- : CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ implicit ? css_property_parser_helpers::IsImplicitProperty::kImplicit
+ : css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBackgroundRepeatY, CSSPropertyBackgroundRepeat, *result_y,
important,
- implicit ? CSSPropertyParserHelpers::IsImplicitProperty::kImplicit
- : CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ implicit ? css_property_parser_helpers::IsImplicitProperty::kImplicit
+ : css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -55,5 +55,5 @@ const CSSValue* BackgroundRepeat::CSSValueFromComputedStyleInternal(
&style.BackgroundLayers());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_color_custom.cc
index c1ab6852b74..1304f373293 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_color_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBlockColor::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderBlockColor::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
borderBlockColorShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderBlockColor::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_custom.cc
index d18442f8e88..92797531d4e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBlock::ParseShorthand(
bool important,
@@ -20,16 +20,16 @@ bool BorderBlock::ParseShorthand(
const CSSValue* style = nullptr;
const CSSValue* color = nullptr;
- if (!CSSPropertyParserHelpers::ConsumeBorderShorthand(range, context, width,
- style, color)) {
+ if (!css_property_parser_helpers::ConsumeBorderShorthand(
+ range, context, width, style, color)) {
return false;
};
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderBlockWidth, *width, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderBlockStyle, *style, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderBlockColor, *color, important, properties);
return range.AtEnd();
@@ -53,5 +53,5 @@ const CSSValue* BorderBlock::CSSValueFromComputedStyleInternal(
return value_start;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_end_custom.cc
index 8e9665afe4e..78b27a6f287 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_end_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBlockEnd::ParseShorthand(
bool important,
@@ -16,9 +16,9 @@ bool BorderBlockEnd::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderBlockEndShorthand(), important, context, range, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_start_custom.cc
index 22f27305992..0b725a37d14 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_start_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBlockStart::ParseShorthand(
bool important,
@@ -16,9 +16,9 @@ bool BorderBlockStart::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderBlockStartShorthand(), important, context, range, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_style_custom.cc
index d873dee0a73..66ad0ee5dc7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_style_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBlockStyle::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderBlockStyle::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
borderBlockStyleShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderBlockStyle::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_width_custom.cc
index 7d3523291bf..bde08ce83a6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_block_width_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBlockWidth::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderBlockWidth::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
borderBlockWidthShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderBlockWidth::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_bottom_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_bottom_custom.cc
index 55b4aac34bc..1c27bc33a4a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_bottom_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_bottom_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderBottom::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderBottom::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderBottomShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderBottom::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_color_custom.cc
index 509f2e38a9c..92abd043d7f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_color_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderColor::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderColor::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
borderColorShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderColor::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc
index 7dff25ea3ef..9ac731d078b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Border::ParseShorthand(
bool important,
@@ -23,18 +23,18 @@ bool Border::ParseShorthand(
const CSSValue* style = nullptr;
const CSSValue* color = nullptr;
- if (!CSSPropertyParserHelpers::ConsumeBorderShorthand(range, context, width,
- style, color)) {
+ if (!css_property_parser_helpers::ConsumeBorderShorthand(
+ range, context, width, style, color)) {
return false;
};
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderWidth, *width, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderStyle, *style, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderColor, *color, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderImage, *CSSInitialValue::Create(), important,
properties);
@@ -62,5 +62,5 @@ const CSSValue* Border::CSSValueFromComputedStyleInternal(
return value;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_image_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_image_custom.cc
index 679d657ce1f..7928f6994b9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_image_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_image_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderImage::ParseShorthand(
bool important,
@@ -27,41 +27,41 @@ bool BorderImage::ParseShorthand(
CSSValue* outset = nullptr;
CSSValue* repeat = nullptr;
- if (!CSSParsingUtils::ConsumeBorderImageComponents(
+ if (!css_parsing_utils::ConsumeBorderImageComponents(
range, context, source, slice, width, outset, repeat,
- CSSParsingUtils::DefaultFill::kNoFill)) {
+ css_parsing_utils::DefaultFill::kNoFill)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderImageSource, CSSPropertyBorderImage,
source ? *source
: *ToLonghand(&GetCSSPropertyBorderImageSource())->InitialValue(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderImageSlice, CSSPropertyBorderImage,
slice ? *slice
: *ToLonghand(&GetCSSPropertyBorderImageSlice())->InitialValue(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderImageWidth, CSSPropertyBorderImage,
width ? *width
: *ToLonghand(&GetCSSPropertyBorderImageWidth())->InitialValue(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderImageOutset, CSSPropertyBorderImage,
outset ? *outset
: *ToLonghand(&GetCSSPropertyBorderImageOutset())->InitialValue(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderImageRepeat, CSSPropertyBorderImage,
repeat ? *repeat
: *ToLonghand(&GetCSSPropertyBorderImageRepeat())->InitialValue(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -76,5 +76,5 @@ const CSSValue* BorderImage::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForNinePieceImage(style.BorderImage(), style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_color_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_color_custom.cc
index 15ebaa985e9..675514b42ed 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_color_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_color_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderInlineColor::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderInlineColor::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
borderInlineColorShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderInlineColor::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_custom.cc
index b08fe2e7f51..3d8d79109dd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderInline::ParseShorthand(
bool important,
@@ -20,16 +20,16 @@ bool BorderInline::ParseShorthand(
const CSSValue* style = nullptr;
const CSSValue* color = nullptr;
- if (!CSSPropertyParserHelpers::ConsumeBorderShorthand(range, context, width,
- style, color)) {
+ if (!css_property_parser_helpers::ConsumeBorderShorthand(
+ range, context, width, style, color)) {
return false;
};
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderInlineWidth, *width, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderInlineStyle, *style, important, properties);
- CSSPropertyParserHelpers::AddExpandedPropertyForValue(
+ css_property_parser_helpers::AddExpandedPropertyForValue(
CSSPropertyBorderInlineColor, *color, important, properties);
return range.AtEnd();
@@ -53,5 +53,5 @@ const CSSValue* BorderInline::CSSValueFromComputedStyleInternal(
return value_start;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_end_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_end_custom.cc
index 53c9c7d72d8..bac89861d35 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_end_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_end_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderInlineEnd::ParseShorthand(
bool important,
@@ -16,9 +16,9 @@ bool BorderInlineEnd::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderInlineEndShorthand(), important, context, range, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_start_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_start_custom.cc
index 7440a220bc1..28a36350300 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_start_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_start_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderInlineStart::ParseShorthand(
bool important,
@@ -16,9 +16,9 @@ bool BorderInlineStart::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderInlineStartShorthand(), important, context, range, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_style_custom.cc
index b30e9c2047d..c559d957b94 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_style_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderInlineStyle::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderInlineStyle::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
borderInlineStyleShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderInlineStyle::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_width_custom.cc
index a0e10839891..76577f274dc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_inline_width_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderInlineWidth::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderInlineWidth::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
borderInlineWidthShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderInlineWidth::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_left_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_left_custom.cc
index 0a26d4b4d0f..af9b336c80e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_left_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_left_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderLeft::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderLeft::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderLeftShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderLeft::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_radius_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_radius_custom.cc
index 22b397760aa..5f0b7591578 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_radius_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_radius_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderRadius::ParseShorthand(
bool important,
@@ -24,34 +24,34 @@ bool BorderRadius::ParseShorthand(
CSSValue* horizontal_radii[4] = {nullptr};
CSSValue* vertical_radii[4] = {nullptr};
- if (!CSSParsingUtils::ConsumeRadii(horizontal_radii, vertical_radii, range,
- context.Mode(),
- local_context.UseAliasParsing()))
+ if (!css_parsing_utils::ConsumeRadii(horizontal_radii, vertical_radii, range,
+ context.Mode(),
+ local_context.UseAliasParsing()))
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderTopLeftRadius, CSSPropertyBorderRadius,
*CSSValuePair::Create(horizontal_radii[0], vertical_radii[0],
CSSValuePair::kDropIdenticalValues),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderTopRightRadius, CSSPropertyBorderRadius,
*CSSValuePair::Create(horizontal_radii[1], vertical_radii[1],
CSSValuePair::kDropIdenticalValues),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderBottomRightRadius, CSSPropertyBorderRadius,
*CSSValuePair::Create(horizontal_radii[2], vertical_radii[2],
CSSValuePair::kDropIdenticalValues),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBorderBottomLeftRadius, CSSPropertyBorderRadius,
*CSSValuePair::Create(horizontal_radii[3], vertical_radii[3],
CSSValuePair::kDropIdenticalValues),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
}
@@ -65,5 +65,5 @@ const CSSValue* BorderRadius::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForBorderRadiusShorthand(style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_right_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_right_custom.cc
index 0a573903858..0075cff9bd8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_right_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_right_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderRight::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderRight::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderRightShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderRight::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_spacing_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_spacing_custom.cc
index ea06cdb8fdb..73ed905d19c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_spacing_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_spacing_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderSpacing::ParseShorthand(
bool important,
@@ -20,25 +20,27 @@ bool BorderSpacing::ParseShorthand(
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValue* horizontal_spacing =
ConsumeLength(range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
if (!horizontal_spacing)
return false;
CSSValue* vertical_spacing = horizontal_spacing;
if (!range.AtEnd()) {
vertical_spacing =
ConsumeLength(range, context.Mode(), kValueRangeNonNegative,
- CSSPropertyParserHelpers::UnitlessQuirk::kAllow);
+ css_property_parser_helpers::UnitlessQuirk::kAllow);
}
if (!vertical_spacing || !range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitBorderHorizontalSpacing, CSSPropertyBorderSpacing,
*horizontal_spacing, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitBorderVerticalSpacing, CSSPropertyBorderSpacing,
*vertical_spacing, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -54,5 +56,5 @@ const CSSValue* BorderSpacing::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_style_custom.cc
index bfea74affd3..bbbd07c6d96 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_style_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderStyle::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderStyle::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
borderStyleShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderStyle::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_top_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_top_custom.cc
index 158fcbb8f67..1dd99d0a058 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_top_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_top_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderTop::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderTop::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
borderTopShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderTop::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_width_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_width_custom.cc
index 22b31b1f9a0..7d8b7b302e0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_width_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/border_width_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool BorderWidth::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool BorderWidth::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
borderWidthShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* BorderWidth::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/column_rule_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/column_rule_custom.cc
index 639d8725a3f..7f05677e429 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/column_rule_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/column_rule_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ColumnRule::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ColumnRule::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
columnRuleShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ColumnRule::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/columns_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/columns_custom.cc
index d5f2371db0e..5968080e518 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/columns_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/columns_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Columns::ParseShorthand(
bool important,
@@ -23,22 +23,25 @@ bool Columns::ParseShorthand(
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValue* column_width = nullptr;
CSSValue* column_count = nullptr;
- if (!CSSParsingUtils::ConsumeColumnWidthOrCount(range, column_width,
- column_count))
+ if (!css_parsing_utils::ConsumeColumnWidthOrCount(range, column_width,
+ column_count))
return false;
- CSSParsingUtils::ConsumeColumnWidthOrCount(range, column_width, column_count);
+ css_parsing_utils::ConsumeColumnWidthOrCount(range, column_width,
+ column_count);
if (!range.AtEnd())
return false;
if (!column_width)
column_width = CSSIdentifierValue::Create(CSSValueAuto);
if (!column_count)
column_count = CSSIdentifierValue::Create(CSSValueAuto);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyColumnWidth, CSSPropertyInvalid, *column_width, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyColumnCount, CSSPropertyInvalid, *column_count, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -53,5 +56,5 @@ const CSSValue* Columns::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_custom.cc
index 0ed2a6b08b0..443787e8764 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Flex::ParseShorthand(bool important,
CSSParserTokenRange& range,
@@ -34,7 +34,7 @@ bool Flex::ParseShorthand(bool important,
unsigned index = 0;
while (!range.AtEnd() && index++ < 3) {
double num;
- if (CSSPropertyParserHelpers::ConsumeNumberRaw(range, num)) {
+ if (css_property_parser_helpers::ConsumeNumberRaw(range, num)) {
if (num < 0)
return false;
if (flex_grow == kUnsetValue) {
@@ -52,9 +52,9 @@ bool Flex::ParseShorthand(bool important,
}
} else if (!flex_basis) {
if (range.Peek().Id() == CSSValueAuto)
- flex_basis = CSSPropertyParserHelpers::ConsumeIdent(range);
+ flex_basis = css_property_parser_helpers::ConsumeIdent(range);
if (!flex_basis) {
- flex_basis = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ flex_basis = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeNonNegative);
}
if (index == 2 && !range.AtEnd())
@@ -75,22 +75,23 @@ bool Flex::ParseShorthand(bool important,
if (!range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFlexGrow, CSSPropertyFlex,
*CSSPrimitiveValue::Create(clampTo<float>(flex_grow),
CSSPrimitiveValue::UnitType::kNumber),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFlexShrink, CSSPropertyFlex,
*CSSPrimitiveValue::Create(clampTo<float>(flex_shrink),
CSSPrimitiveValue::UnitType::kNumber),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFlexBasis, CSSPropertyFlex, *flex_basis, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -105,5 +106,5 @@ const CSSValue* Flex::CSSValueFromComputedStyleInternal(
flexShorthand(), style, layout_object, styled_node, allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_flow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_flow_custom.cc
index 8310114b8fe..4289d1d7d68 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_flow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/flex_flow_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool FlexFlow::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool FlexFlow::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
flexFlowShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* FlexFlow::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_custom.cc
index 321d19f3aaf..1150e5dec38 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_custom.cc
@@ -35,55 +35,62 @@ bool ConsumeSystemFont(bool important,
LayoutTheme::GetTheme().SystemFont(system_font_id, font_style, font_weight,
font_size, font_family);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontStyle, CSSPropertyFont,
*CSSIdentifierValue::Create(
font_style == ItalicSlopeValue() ? CSSValueItalic : CSSValueNormal),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontWeight, CSSPropertyFont,
*CSSPrimitiveValue::Create(font_weight,
CSSPrimitiveValue::UnitType::kNumber),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontSize, CSSPropertyFont,
*CSSPrimitiveValue::Create(font_size,
CSSPrimitiveValue::UnitType::kPixels),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
CSSValueList* font_family_list = CSSValueList::CreateCommaSeparated();
font_family_list->Append(*CSSFontFamilyValue::Create(font_family));
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontFamily, CSSPropertyFont, *font_family_list, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontStretch, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantCaps, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantLigatures, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantNumeric, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantEastAsian, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyLineHeight, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -100,7 +107,7 @@ bool ConsumeFont(bool important,
CSSValueID id = range.Peek().Id();
if (!font_style && (id == CSSValueNormal || id == CSSValueItalic ||
id == CSSValueOblique)) {
- font_style = CSSParsingUtils::ConsumeFontStyle(range, context.Mode());
+ font_style = css_parsing_utils::ConsumeFontStyle(range, context.Mode());
continue;
}
if (!font_variant_caps &&
@@ -108,12 +115,12 @@ bool ConsumeFont(bool important,
// Font variant in the shorthand is particular, it only accepts normal or
// small-caps.
// See https://drafts.csswg.org/css-fonts/#propdef-font
- font_variant_caps = CSSParsingUtils::ConsumeFontVariantCSS21(range);
+ font_variant_caps = css_parsing_utils::ConsumeFontVariantCSS21(range);
if (font_variant_caps)
continue;
}
if (!font_weight) {
- font_weight = CSSParsingUtils::ConsumeFontWeight(range, context.Mode());
+ font_weight = css_parsing_utils::ConsumeFontWeight(range, context.Mode());
if (font_weight)
continue;
}
@@ -125,81 +132,90 @@ bool ConsumeFont(bool important,
// shorthand, compare: [ [ <‘font-style’> || <font-variant-css21> ||
// <‘font-weight’> || <font-stretch-css3> ]?
if (font_stretch ||
- !(font_stretch = CSSParsingUtils::ConsumeFontStretchKeywordOnly(range)))
+ !(font_stretch =
+ css_parsing_utils::ConsumeFontStretchKeywordOnly(range)))
break;
}
if (range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontStyle, CSSPropertyFont,
font_style ? *font_style : *CSSIdentifierValue::Create(CSSValueNormal),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantCaps, CSSPropertyFont,
font_variant_caps ? *font_variant_caps
: *CSSIdentifierValue::Create(CSSValueNormal),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantLigatures, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantNumeric, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantEastAsian, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontWeight, CSSPropertyFont,
font_weight ? *font_weight : *CSSIdentifierValue::Create(CSSValueNormal),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontStretch, CSSPropertyFont,
font_stretch ? *font_stretch
: *CSSIdentifierValue::Create(CSSValueNormal),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
// Now a font size _must_ come.
- CSSValue* font_size = CSSParsingUtils::ConsumeFontSize(range, context.Mode());
+ CSSValue* font_size =
+ css_parsing_utils::ConsumeFontSize(range, context.Mode());
if (!font_size || range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontSize, CSSPropertyFont, *font_size, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
CSSValue* line_height =
- CSSParsingUtils::ConsumeLineHeight(range, context.Mode());
+ css_parsing_utils::ConsumeLineHeight(range, context.Mode());
if (!line_height)
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyLineHeight, CSSPropertyFont, *line_height, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
} else {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyLineHeight, CSSPropertyFont,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
}
// Font family must come now.
- CSSValue* parsed_family_value = CSSParsingUtils::ConsumeFontFamily(range);
+ CSSValue* parsed_family_value = css_parsing_utils::ConsumeFontFamily(range);
if (!parsed_family_value)
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontFamily, CSSPropertyFont, *parsed_family_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
// FIXME: http://www.w3.org/TR/2011/WD-css3-fonts-20110324/#font-prop requires
// that "font-stretch", "font-size-adjust", and "font-kerning" be reset to
@@ -209,7 +225,7 @@ bool ConsumeFont(bool important,
}
} // namespace
-namespace CSSShorthand {
+namespace css_shorthand {
bool Font::ParseShorthand(bool important,
CSSParserTokenRange& range,
@@ -231,5 +247,5 @@ const CSSValue* Font::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForFont(style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_variant_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_variant_custom.cc
index 503bcca3c64..e4fab73c675 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_variant_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/font_variant_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool FontVariant::ParseShorthand(
bool important,
@@ -21,24 +21,28 @@ bool FontVariant::ParseShorthand(
const CSSParserContext&,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueNormal, CSSValueNone>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueNormal, CSSValueNone>(
range.Peek().Id())) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantLigatures, CSSPropertyFontVariant,
- *CSSPropertyParserHelpers::ConsumeIdent(range), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ *css_property_parser_helpers::ConsumeIdent(range), important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantCaps, CSSPropertyFontVariant,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantNumeric, CSSPropertyFontVariant,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantEastAsian, CSSPropertyFontVariant,
*CSSIdentifierValue::Create(CSSValueNormal), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return range.AtEnd();
}
@@ -80,29 +84,32 @@ bool FontVariant::ParseShorthand(
// Only one caps value permitted in font-variant grammar.
if (caps_value)
return false;
- caps_value = CSSPropertyParserHelpers::ConsumeIdent(range);
+ caps_value = css_property_parser_helpers::ConsumeIdent(range);
break;
default:
return false;
}
} while (!range.AtEnd());
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantLigatures, CSSPropertyFontVariant,
*ligatures_parser.FinalizeValue(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantNumeric, CSSPropertyFontVariant,
*numeric_parser.FinalizeValue(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantEastAsian, CSSPropertyFontVariant,
*east_asian_parser.FinalizeValue(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyFontVariantCaps, CSSPropertyFontVariant,
caps_value ? *caps_value : *CSSIdentifierValue::Create(CSSValueNormal),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
}
@@ -117,5 +124,5 @@ const CSSValue* FontVariant::CSSValueFromComputedStyleInternal(
style, layout_object, styled_node, allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/gap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/gap_custom.cc
index d55424277da..47016d25a2a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/gap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/gap_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Gap::ParseShorthand(bool important,
CSSParserTokenRange& range,
@@ -19,18 +19,20 @@ bool Gap::ParseShorthand(bool important,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
DCHECK_EQ(shorthandForProperty(CSSPropertyGap).length(), 2u);
- CSSValue* row_gap = CSSParsingUtils::ConsumeGapLength(range, context);
- CSSValue* column_gap = CSSParsingUtils::ConsumeGapLength(range, context);
+ CSSValue* row_gap = css_parsing_utils::ConsumeGapLength(range, context);
+ CSSValue* column_gap = css_parsing_utils::ConsumeGapLength(range, context);
if (!row_gap || !range.AtEnd())
return false;
if (!column_gap)
column_gap = row_gap;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyRowGap, CSSPropertyGap, *row_gap, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyColumnGap, CSSPropertyGap, *column_gap, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -44,5 +46,5 @@ const CSSValue* Gap::CSSValueFromComputedStyleInternal(
gapShorthand(), style, layout_object, styled_node, allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_area_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_area_custom.cc
index ce88adcc16d..493bc85c0cf 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_area_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_area_custom.cc
@@ -11,32 +11,33 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridArea::ParseShorthand(
bool important,
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
DCHECK_EQ(gridAreaShorthand().length(), 4u);
- CSSValue* row_start_value = CSSParsingUtils::ConsumeGridLine(range);
+ CSSValue* row_start_value =
+ css_parsing_utils::ConsumeGridLine(range, context);
if (!row_start_value)
return false;
CSSValue* column_start_value = nullptr;
CSSValue* row_end_value = nullptr;
CSSValue* column_end_value = nullptr;
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
- column_start_value = CSSParsingUtils::ConsumeGridLine(range);
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
+ column_start_value = css_parsing_utils::ConsumeGridLine(range, context);
if (!column_start_value)
return false;
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
- row_end_value = CSSParsingUtils::ConsumeGridLine(range);
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
+ row_end_value = css_parsing_utils::ConsumeGridLine(range, context);
if (!row_end_value)
return false;
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
- column_end_value = CSSParsingUtils::ConsumeGridLine(range);
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
+ column_end_value = css_parsing_utils::ConsumeGridLine(range, context);
if (!column_end_value)
return false;
}
@@ -60,19 +61,21 @@ bool GridArea::ParseShorthand(
: CSSIdentifierValue::Create(CSSValueAuto);
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridRowStart, CSSPropertyGridArea, *row_start_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridColumnStart, CSSPropertyGridArea, *column_start_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridRowEnd, CSSPropertyGridArea, *row_end_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridColumnEnd, CSSPropertyGridArea, *column_end_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
}
@@ -88,5 +91,5 @@ const CSSValue* GridArea::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_custom.cc
index 5fb067c9745..94884442f74 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_custom.cc
@@ -12,12 +12,12 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridColumn::ParseShorthand(
bool important,
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
const StylePropertyShorthand& shorthand =
@@ -26,19 +26,21 @@ bool GridColumn::ParseShorthand(
CSSValue* start_value = nullptr;
CSSValue* end_value = nullptr;
- if (!CSSParsingUtils::ConsumeGridItemPositionShorthand(
- important, range, start_value, end_value)) {
+ if (!css_parsing_utils::ConsumeGridItemPositionShorthand(
+ important, range, context, start_value, end_value)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
shorthand.properties()[0]->PropertyID(), CSSPropertyGridColumn,
*start_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
shorthand.properties()[1]->PropertyID(), CSSPropertyGridColumn,
*end_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -54,5 +56,5 @@ const CSSValue* GridColumn::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_gap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_gap_custom.cc
index 8ba54bc9575..e40ef508d61 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_gap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_column_gap_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridColumnGap::ParseShorthand(
bool important,
@@ -18,13 +18,14 @@ bool GridColumnGap::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- CSSValue* gap_length = CSSParsingUtils::ConsumeGapLength(range, context);
+ CSSValue* gap_length = css_parsing_utils::ConsumeGapLength(range, context);
if (!gap_length || !range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyColumnGap, CSSPropertyGridColumnGap, *gap_length, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -39,5 +40,5 @@ const CSSValue* GridColumnGap::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_custom.cc
index 0a30b7b7a0a..ac57385e3bd 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_custom.cc
@@ -20,15 +20,15 @@ CSSValueList* ConsumeImplicitAutoFlow(CSSParserTokenRange& range,
const CSSValue& flow_direction) {
// [ auto-flow && dense? ]
CSSValue* dense_algorithm = nullptr;
- if ((CSSPropertyParserHelpers::ConsumeIdent<CSSValueAutoFlow>(range))) {
+ if ((css_property_parser_helpers::ConsumeIdent<CSSValueAutoFlow>(range))) {
dense_algorithm =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueDense>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueDense>(range);
} else {
dense_algorithm =
- CSSPropertyParserHelpers::ConsumeIdent<CSSValueDense>(range);
+ css_property_parser_helpers::ConsumeIdent<CSSValueDense>(range);
if (!dense_algorithm)
return nullptr;
- if (!CSSPropertyParserHelpers::ConsumeIdent<CSSValueAutoFlow>(range))
+ if (!css_property_parser_helpers::ConsumeIdent<CSSValueAutoFlow>(range))
return nullptr;
}
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
@@ -39,7 +39,7 @@ CSSValueList* ConsumeImplicitAutoFlow(CSSParserTokenRange& range,
}
} // namespace
-namespace CSSShorthand {
+namespace css_shorthand {
bool Grid::ParseShorthand(bool important,
CSSParserTokenRange& range,
@@ -54,39 +54,45 @@ bool Grid::ParseShorthand(bool important,
CSSValue* template_columns = nullptr;
CSSValue* template_areas = nullptr;
- if (CSSParsingUtils::ConsumeGridTemplateShorthand(
+ if (css_parsing_utils::ConsumeGridTemplateShorthand(
important, range, context, template_rows, template_columns,
template_areas)) {
DCHECK(template_rows);
DCHECK(template_columns);
DCHECK(template_areas);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateRows, CSSPropertyGrid, *template_rows, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateColumns, CSSPropertyGrid, *template_columns,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateAreas, CSSPropertyGrid, *template_areas,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
// It can only be specified the explicit or the implicit grid properties in
// a single grid declaration. The sub-properties not specified are set to
// their initial value, as normal for shorthands.
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridAutoFlow, CSSPropertyGrid, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridAutoColumns, CSSPropertyGrid, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridAutoRows, CSSPropertyGrid, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
}
@@ -99,35 +105,38 @@ bool Grid::ParseShorthand(bool important,
template_rows = nullptr;
template_columns = nullptr;
- if (CSSPropertyParserHelpers::IdentMatches<CSSValueDense, CSSValueAutoFlow>(
+ if (css_property_parser_helpers::IdentMatches<CSSValueDense,
+ CSSValueAutoFlow>(
range.Peek().Id())) {
// 2- [ auto-flow && dense? ] <grid-auto-rows>? / <grid-template-columns>
grid_auto_flow = ConsumeImplicitAutoFlow(
range, *CSSIdentifierValue::Create(CSSValueRow));
if (!grid_auto_flow)
return false;
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
auto_rows_value = CSSInitialValue::Create();
} else {
- auto_rows_value = CSSParsingUtils::ConsumeGridTrackList(
- range, context.Mode(), CSSParsingUtils::TrackListType::kGridAuto);
+ auto_rows_value = css_parsing_utils::ConsumeGridTrackList(
+ range, context, context.Mode(),
+ css_parsing_utils::TrackListType::kGridAuto);
if (!auto_rows_value)
return false;
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
return false;
}
- if (!(template_columns = CSSParsingUtils::ConsumeGridTemplatesRowsOrColumns(
- range, context.Mode())))
+ if (!(template_columns =
+ css_parsing_utils::ConsumeGridTemplatesRowsOrColumns(
+ range, context, context.Mode())))
return false;
template_rows = CSSInitialValue::Create();
auto_columns_value = CSSInitialValue::Create();
} else {
// 3- <grid-template-rows> / [ auto-flow && dense? ] <grid-auto-columns>?
- template_rows = CSSParsingUtils::ConsumeGridTemplatesRowsOrColumns(
- range, context.Mode());
+ template_rows = css_parsing_utils::ConsumeGridTemplatesRowsOrColumns(
+ range, context, context.Mode());
if (!template_rows)
return false;
- if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
return false;
grid_auto_flow = ConsumeImplicitAutoFlow(
range, *CSSIdentifierValue::Create(CSSValueColumn));
@@ -136,8 +145,9 @@ bool Grid::ParseShorthand(bool important,
if (range.AtEnd()) {
auto_columns_value = CSSInitialValue::Create();
} else {
- auto_columns_value = CSSParsingUtils::ConsumeGridTrackList(
- range, context.Mode(), CSSParsingUtils::TrackListType::kGridAuto);
+ auto_columns_value = css_parsing_utils::ConsumeGridTrackList(
+ range, context, context.Mode(),
+ css_parsing_utils::TrackListType::kGridAuto);
if (!auto_columns_value)
return false;
}
@@ -151,27 +161,30 @@ bool Grid::ParseShorthand(bool important,
// It can only be specified the explicit or the implicit grid properties in a
// single grid declaration. The sub-properties not specified are set to their
// initial value, as normal for shorthands.
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateColumns, CSSPropertyGrid, *template_columns,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateRows, CSSPropertyGrid, *template_rows, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateAreas, CSSPropertyGrid, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridAutoFlow, CSSPropertyGrid, *grid_auto_flow, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridAutoColumns, CSSPropertyGrid, *auto_columns_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridAutoRows, CSSPropertyGrid, *auto_rows_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -190,5 +203,5 @@ const CSSValue* Grid::CSSValueFromComputedStyleInternal(
gridShorthand(), style, layout_object, styled_node, allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_gap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_gap_custom.cc
index 745d12a4772..a78285a531f 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_gap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_gap_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridGap::ParseShorthand(
bool important,
@@ -21,18 +21,20 @@ bool GridGap::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
DCHECK_EQ(shorthandForProperty(CSSPropertyGridGap).length(), 2u);
- CSSValue* row_gap = CSSParsingUtils::ConsumeGapLength(range, context);
- CSSValue* column_gap = CSSParsingUtils::ConsumeGapLength(range, context);
+ CSSValue* row_gap = css_parsing_utils::ConsumeGapLength(range, context);
+ CSSValue* column_gap = css_parsing_utils::ConsumeGapLength(range, context);
if (!row_gap || !range.AtEnd())
return false;
if (!column_gap)
column_gap = row_gap;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyRowGap, CSSPropertyGap, *row_gap, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyColumnGap, CSSPropertyGap, *column_gap, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -47,5 +49,5 @@ const CSSValue* GridGap::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_custom.cc
index 01c3a4833e8..11877a4f8d0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_custom.cc
@@ -12,12 +12,12 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridRow::ParseShorthand(
bool important,
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
const StylePropertyShorthand& shorthand =
@@ -26,18 +26,18 @@ bool GridRow::ParseShorthand(
CSSValue* start_value = nullptr;
CSSValue* end_value = nullptr;
- if (!CSSParsingUtils::ConsumeGridItemPositionShorthand(
- important, range, start_value, end_value)) {
+ if (!css_parsing_utils::ConsumeGridItemPositionShorthand(
+ important, range, context, start_value, end_value)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
shorthand.properties()[0]->PropertyID(), CSSPropertyGridRow, *start_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
shorthand.properties()[1]->PropertyID(), CSSPropertyGridRow, *end_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -54,5 +54,5 @@ const CSSValue* GridRow::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_gap_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_gap_custom.cc
index 6150d68f0b6..3a35691a678 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_gap_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_row_gap_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridRowGap::ParseShorthand(
bool important,
@@ -18,13 +18,14 @@ bool GridRowGap::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- CSSValue* gap_length = CSSParsingUtils::ConsumeGapLength(range, context);
+ CSSValue* gap_length = css_parsing_utils::ConsumeGapLength(range, context);
if (!gap_length || !range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyRowGap, CSSPropertyGridRowGap, *gap_length, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -39,5 +40,5 @@ const CSSValue* GridRowGap::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_template_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_template_custom.cc
index d4a921bdcf2..514539f0c34 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_template_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/grid_template_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool GridTemplate::ParseShorthand(
bool important,
@@ -24,7 +24,7 @@ bool GridTemplate::ParseShorthand(
CSSValue* template_rows = nullptr;
CSSValue* template_columns = nullptr;
CSSValue* template_areas = nullptr;
- if (!CSSParsingUtils::ConsumeGridTemplateShorthand(
+ if (!css_parsing_utils::ConsumeGridTemplateShorthand(
important, range, context, template_rows, template_columns,
template_areas))
return false;
@@ -33,17 +33,18 @@ bool GridTemplate::ParseShorthand(
DCHECK(template_columns);
DCHECK(template_areas);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateRows, CSSPropertyGridTemplate, *template_rows,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateColumns, CSSPropertyGridTemplate,
*template_columns, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyGridTemplateAreas, CSSPropertyGridTemplate, *template_areas,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -65,5 +66,5 @@ const CSSValue* GridTemplate::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_block_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_block_custom.cc
index c60122b98b7..078558ede26 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_block_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_block_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool InsetBlock::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool InsetBlock::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
insetBlockShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* InsetBlock::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_custom.cc
index e76065f6e0b..d7cf29c2a70 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Inset::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool Inset::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
insetShorthand(), important, context, range, properties);
}
@@ -32,5 +32,5 @@ const CSSValue* Inset::CSSValueFromComputedStyleInternal(
insetShorthand(), style, layout_object, styled_node, allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_inline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_inline_custom.cc
index 7a6e6d27ec0..7d04665f6d4 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_inline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/inset_inline_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool InsetInline::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool InsetInline::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
insetInlineShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* InsetInline::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/list_style_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/list_style_custom.cc
index 28332ec69ec..0c99adbfbb2 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/list_style_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/list_style_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ListStyle::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ListStyle::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
listStyleShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ListStyle::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_block_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_block_custom.cc
index aa8384ab05c..ffb1a795592 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_block_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_block_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool MarginBlock::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool MarginBlock::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
marginBlockShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* MarginBlock::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_custom.cc
index 7d3493eeb65..03334831065 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Margin::ParseShorthand(
bool important,
@@ -19,7 +19,7 @@ bool Margin::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
marginShorthand(), important, context, range, properties);
}
@@ -42,5 +42,5 @@ const CSSValue* Margin::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_inline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_inline_custom.cc
index f6ad3c6ff84..deb0ef952d9 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_inline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/margin_inline_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool MarginInline::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool MarginInline::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
marginInlineShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* MarginInline::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/marker_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/marker_custom.cc
index 5ecb12677af..5f304bfbe31 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/marker_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/marker_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Marker::ParseShorthand(
bool important,
@@ -15,22 +15,25 @@ bool Marker::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- const CSSValue* marker = CSSPropertyParserHelpers::ParseLonghand(
+ const CSSValue* marker = css_property_parser_helpers::ParseLonghand(
CSSPropertyMarkerStart, CSSPropertyMarker, context, range);
if (!marker || !range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyMarkerStart, CSSPropertyMarker, *marker, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyMarkerMid, CSSPropertyMarker, *marker, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyMarkerEnd, CSSPropertyMarker, *marker, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/offset_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/offset_custom.cc
index bfdc1cab2e0..81169ef4b7c 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/offset_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/offset_custom.cc
@@ -15,7 +15,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Offset::ParseShorthand(
bool important,
@@ -31,20 +31,20 @@ bool Offset::ParseShorthand(
ToLonghand(GetCSSPropertyOffsetPosition())
.ParseSingleValue(range, context, CSSParserLocalContext());
const CSSValue* offset_path =
- CSSParsingUtils::ConsumeOffsetPath(range, context);
+ css_parsing_utils::ConsumeOffsetPath(range, context);
const CSSValue* offset_distance = nullptr;
const CSSValue* offset_rotate = nullptr;
if (offset_path) {
- offset_distance = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ offset_distance = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll);
- offset_rotate = CSSParsingUtils::ConsumeOffsetRotate(range, context);
+ offset_rotate = css_parsing_utils::ConsumeOffsetRotate(range, context);
if (offset_rotate && !offset_distance) {
- offset_distance = CSSPropertyParserHelpers::ConsumeLengthOrPercent(
+ offset_distance = css_property_parser_helpers::ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll);
}
}
const CSSValue* offset_anchor = nullptr;
- if (CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) {
+ if (css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range)) {
offset_anchor =
ToLonghand(GetCSSPropertyOffsetAnchor())
.ParseSingleValue(range, context, CSSParserLocalContext());
@@ -59,59 +59,69 @@ bool Offset::ParseShorthand(
return false;
if (offset_position) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetPosition, CSSPropertyOffset, *offset_position,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
} else if (RuntimeEnabledFeatures::CSSOffsetPositionAnchorEnabled()) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetPosition, CSSPropertyOffset,
*CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
}
if (offset_path) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetPath, CSSPropertyOffset, *offset_path, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
} else {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetPath, CSSPropertyOffset, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
}
if (offset_distance) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetDistance, CSSPropertyOffset, *offset_distance,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
} else {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetDistance, CSSPropertyOffset,
*CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
}
if (offset_rotate) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetRotate, CSSPropertyOffset, *offset_rotate, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
} else {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetRotate, CSSPropertyOffset, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
}
if (offset_anchor) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetAnchor, CSSPropertyOffset, *offset_anchor, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
} else if (RuntimeEnabledFeatures::CSSOffsetPositionAnchorEnabled()) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOffsetAnchor, CSSPropertyOffset, *CSSInitialValue::Create(),
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
}
@@ -128,5 +138,5 @@ const CSSValue* Offset::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/outline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/outline_custom.cc
index a387e6bd181..48fc568b9ed 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/outline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/outline_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Outline::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool Outline::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
outlineShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* Outline::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/overflow_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/overflow_custom.cc
index fac920462eb..47d279acc4b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/overflow_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/overflow_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Overflow::ParseShorthand(
bool important,
@@ -51,12 +51,14 @@ bool Overflow::ParseShorthand(
overflow_x_value = CSSIdentifierValue::Create(CSSValueAuto);
else
overflow_x_value = overflow_y_value;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyOverflowX, CSSPropertyOverflow, *overflow_x_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyOverflowY, CSSPropertyOverflow, *overflow_y_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -74,5 +76,5 @@ const CSSValue* Overflow::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/overscroll_behavior_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/overscroll_behavior_custom.cc
index c43ba762fcd..92e2ceaae74 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/overscroll_behavior_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/overscroll_behavior_custom.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool OverscrollBehavior::ParseShorthand(
bool important,
@@ -17,7 +17,7 @@ bool OverscrollBehavior::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
overscrollBehaviorShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* OverscrollBehavior::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_block_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_block_custom.cc
index 036c17e0815..580b8a03278 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_block_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_block_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PaddingBlock::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool PaddingBlock::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
paddingBlockShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* PaddingBlock::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_custom.cc
index 808e45efc9d..c44429896ba 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool Padding::ParseShorthand(
bool important,
@@ -19,7 +19,7 @@ bool Padding::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
paddingShorthand(), important, context, range, properties);
}
@@ -42,5 +42,5 @@ const CSSValue* Padding::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_inline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_inline_custom.cc
index 73c747b6a4d..b60986b8822 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_inline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/padding_inline_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PaddingInline::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool PaddingInline::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
paddingInlineShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* PaddingInline::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_after_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_after_custom.cc
index 3960363453e..44e8dd93372 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_after_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_after_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PageBreakAfter::ParseShorthand(
bool important,
@@ -19,15 +19,16 @@ bool PageBreakAfter::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValueID value;
- if (!CSSParsingUtils::ConsumeFromPageBreakBetween(range, value)) {
+ if (!css_parsing_utils::ConsumeFromPageBreakBetween(range, value)) {
return false;
}
DCHECK_NE(value, CSSValueInvalid);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBreakAfter, CSSPropertyPageBreakAfter,
*CSSIdentifierValue::Create(value), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -40,5 +41,5 @@ const CSSValue* PageBreakAfter::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForPageBreakBetween(style.BreakAfter());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_before_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_before_custom.cc
index 44c0fbd0844..a9958fb23d1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_before_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_before_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PageBreakBefore::ParseShorthand(
bool important,
@@ -19,15 +19,16 @@ bool PageBreakBefore::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValueID value;
- if (!CSSParsingUtils::ConsumeFromPageBreakBetween(range, value)) {
+ if (!css_parsing_utils::ConsumeFromPageBreakBetween(range, value)) {
return false;
}
DCHECK_NE(value, CSSValueInvalid);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBreakBefore, CSSPropertyPageBreakBefore,
*CSSIdentifierValue::Create(value), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -40,5 +41,5 @@ const CSSValue* PageBreakBefore::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForPageBreakBetween(style.BreakBefore());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_inside_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_inside_custom.cc
index f038750ebbf..0860022c8fa 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_inside_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/page_break_inside_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PageBreakInside::ParseShorthand(
bool important,
@@ -19,14 +19,15 @@ bool PageBreakInside::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValueID value;
- if (!CSSParsingUtils::ConsumeFromColumnOrPageBreakInside(range, value)) {
+ if (!css_parsing_utils::ConsumeFromColumnOrPageBreakInside(range, value)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBreakInside, CSSPropertyPageBreakInside,
*CSSIdentifierValue::Create(value), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -39,5 +40,5 @@ const CSSValue* PageBreakInside::CSSValueFromComputedStyleInternal(
return ComputedStyleUtils::ValueForPageBreakInside(style.BreakInside());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_content_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_content_custom.cc
index 3114d6601d8..99c29aac3fc 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_content_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_content_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PlaceContent::ParseShorthand(
bool important,
@@ -41,14 +41,15 @@ bool PlaceContent::ParseShorthand(
DCHECK(align_content_value);
DCHECK(justify_content_value);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyAlignContent, CSSPropertyPlaceContent, *align_content_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyJustifyContent, CSSPropertyPlaceContent,
*justify_content_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -66,5 +67,5 @@ const CSSValue* PlaceContent::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_items_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_items_custom.cc
index 7870df724d7..c7b6c2fbc6b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_items_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_items_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PlaceItems::ParseShorthand(
bool important,
@@ -41,13 +41,13 @@ bool PlaceItems::ParseShorthand(
DCHECK(align_items_value);
DCHECK(justify_items_value);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyAlignItems, CSSPropertyPlaceItems, *align_items_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyJustifyItems, CSSPropertyPlaceItems, *justify_items_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -66,5 +66,5 @@ const CSSValue* PlaceItems::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_self_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_self_custom.cc
index c41c353b28c..c4683c941f8 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_self_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/place_self_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool PlaceSelf::ParseShorthand(
bool important,
@@ -41,12 +41,13 @@ bool PlaceSelf::ParseShorthand(
DCHECK(align_self_value);
DCHECK(justify_self_value);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyAlignSelf, CSSPropertyPlaceSelf, *align_self_value, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyJustifySelf, CSSPropertyPlaceSelf, *justify_self_value,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -65,5 +66,5 @@ const CSSValue* PlaceSelf::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_block_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_block_custom.cc
index 9da1785091e..9b2f504b6f7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_block_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_block_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ScrollMarginBlock::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ScrollMarginBlock::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
scrollMarginBlockShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ScrollMarginBlock::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_custom.cc
index 57a56333f85..3cf8b9c7386 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ScrollMargin::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ScrollMargin::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
scrollMarginShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ScrollMargin::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_inline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_inline_custom.cc
index 0ea529f1a03..1c8b2b737ca 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_inline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_inline_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ScrollMarginInline::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ScrollMarginInline::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
scrollMarginInlineShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ScrollMarginInline::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_block_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_block_custom.cc
index 404d7b7f5b4..f3c70674a02 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_block_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_block_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ScrollPaddingBlock::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ScrollPaddingBlock::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
scrollPaddingBlockShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ScrollPaddingBlock::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_custom.cc
index 28330aab1a7..2075592e5c0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ScrollPadding::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ScrollPadding::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia4Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia4Longhands(
scrollPaddingShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ScrollPadding::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_inline_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_inline_custom.cc
index a46a074d0bb..414a5825aa6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_inline_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_inline_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool ScrollPaddingInline::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool ScrollPaddingInline::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandVia2Longhands(
+ return css_property_parser_helpers::ConsumeShorthandVia2Longhands(
scrollPaddingInlineShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* ScrollPaddingInline::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/text_decoration_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/text_decoration_custom.cc
index c321e20999c..9aefde62344 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/text_decoration_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/text_decoration_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool TextDecoration::ParseShorthand(
bool important,
@@ -18,7 +18,7 @@ bool TextDecoration::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
textDecorationShorthand(), important, context, range, properties);
}
@@ -33,5 +33,5 @@ const CSSValue* TextDecoration::CSSValueFromComputedStyleInternal(
allow_visited_style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc
index ddce931bfb5..e68f627cfb3 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc
@@ -18,18 +18,18 @@ namespace {
CSSValue* ConsumeTransitionValue(CSSPropertyID property,
CSSParserTokenRange& range,
- const CSSParserContext&,
+ const CSSParserContext& context,
bool use_legacy_parsing) {
switch (property) {
case CSSPropertyTransitionDelay:
- return CSSPropertyParserHelpers::ConsumeTime(range, kValueRangeAll);
+ return css_property_parser_helpers::ConsumeTime(range, kValueRangeAll);
case CSSPropertyTransitionDuration:
- return CSSPropertyParserHelpers::ConsumeTime(range,
- kValueRangeNonNegative);
+ return css_property_parser_helpers::ConsumeTime(range,
+ kValueRangeNonNegative);
case CSSPropertyTransitionProperty:
- return CSSParsingUtils::ConsumeTransitionProperty(range);
+ return css_parsing_utils::ConsumeTransitionProperty(range, context);
case CSSPropertyTransitionTimingFunction:
- return CSSParsingUtils::ConsumeAnimationTimingFunction(range);
+ return css_parsing_utils::ConsumeAnimationTimingFunction(range);
default:
NOTREACHED();
return nullptr;
@@ -37,7 +37,7 @@ CSSValue* ConsumeTransitionValue(CSSPropertyID property,
}
} // namespace
-namespace CSSShorthand {
+namespace css_shorthand {
bool Transition::ParseShorthand(
bool important,
@@ -48,9 +48,9 @@ bool Transition::ParseShorthand(
const StylePropertyShorthand shorthand = transitionShorthandForParsing();
const unsigned longhand_count = shorthand.length();
- HeapVector<Member<CSSValueList>, CSSParsingUtils::kMaxNumAnimationLonghands>
+ HeapVector<Member<CSSValueList>, css_parsing_utils::kMaxNumAnimationLonghands>
longhands(longhand_count);
- if (!CSSParsingUtils::ConsumeAnimationShorthand(
+ if (!css_parsing_utils::ConsumeAnimationShorthand(
shorthand, longhands, ConsumeTransitionValue, range, context,
local_context.UseAliasParsing())) {
return false;
@@ -58,14 +58,15 @@ bool Transition::ParseShorthand(
for (unsigned i = 0; i < longhand_count; ++i) {
if (shorthand.properties()[i]->IDEquals(CSSPropertyTransitionProperty) &&
- !CSSParsingUtils::IsValidPropertyList(*longhands[i]))
+ !css_parsing_utils::IsValidPropertyList(*longhands[i]))
return false;
}
for (unsigned i = 0; i < longhand_count; ++i) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
shorthand.properties()[i]->PropertyID(), shorthand.id(), *longhands[i],
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
}
@@ -113,5 +114,5 @@ const CSSValue* Transition::CSSValueFromComputedStyleInternal(
return list;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_after_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_after_custom.cc
index cddb2ff5e65..bd9fad47841 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_after_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_after_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitColumnBreakAfter::ParseShorthand(
bool important,
@@ -19,14 +19,15 @@ bool WebkitColumnBreakAfter::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValueID value;
- if (!CSSParsingUtils::ConsumeFromColumnBreakBetween(range, value)) {
+ if (!css_parsing_utils::ConsumeFromColumnBreakBetween(range, value)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBreakAfter, CSSPropertyWebkitColumnBreakAfter,
*CSSIdentifierValue::Create(value), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -40,5 +41,5 @@ const CSSValue* WebkitColumnBreakAfter::CSSValueFromComputedStyleInternal(
style.BreakAfter());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_before_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_before_custom.cc
index 724002b33f8..cd9807b5d5e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_before_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_before_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitColumnBreakBefore::ParseShorthand(
bool important,
@@ -19,14 +19,15 @@ bool WebkitColumnBreakBefore::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValueID value;
- if (!CSSParsingUtils::ConsumeFromColumnBreakBetween(range, value)) {
+ if (!css_parsing_utils::ConsumeFromColumnBreakBetween(range, value)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBreakBefore, CSSPropertyWebkitColumnBreakBefore,
*CSSIdentifierValue::Create(value), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -40,5 +41,5 @@ const CSSValue* WebkitColumnBreakBefore::CSSValueFromComputedStyleInternal(
style.BreakBefore());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_inside_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_inside_custom.cc
index b703c990c22..8265c9485c0 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_inside_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_inside_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitColumnBreakInside::ParseShorthand(
bool important,
@@ -19,14 +19,15 @@ bool WebkitColumnBreakInside::ParseShorthand(
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
CSSValueID value;
- if (!CSSParsingUtils::ConsumeFromColumnOrPageBreakInside(range, value)) {
+ if (!css_parsing_utils::ConsumeFromColumnOrPageBreakInside(range, value)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyBreakInside, CSSPropertyWebkitColumnBreakInside,
*CSSIdentifierValue::Create(value), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -40,5 +41,5 @@ const CSSValue* WebkitColumnBreakInside::CSSValueFromComputedStyleInternal(
style.BreakInside());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_margin_collapse_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_margin_collapse_custom.cc
index 985f3eb7a4e..abb474f6aa1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_margin_collapse_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_margin_collapse_custom.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitMarginCollapse::ParseShorthand(
bool important,
@@ -24,16 +24,18 @@ bool WebkitMarginCollapse::ParseShorthand(
return false;
CSSValue* before_collapse = CSSIdentifierValue::Create(id);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMarginBeforeCollapse, CSSPropertyWebkitMarginCollapse,
*before_collapse, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
if (range.AtEnd()) {
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMarginAfterCollapse, CSSPropertyWebkitMarginCollapse,
*before_collapse, important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -41,12 +43,13 @@ bool WebkitMarginCollapse::ParseShorthand(
if (!CSSParserFastPaths::IsValidKeywordPropertyAndValue(
CSSPropertyWebkitMarginAfterCollapse, id, context.Mode()))
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMarginAfterCollapse, CSSPropertyWebkitMarginCollapse,
*CSSIdentifierValue::Create(id), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_box_image_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_box_image_custom.cc
index 3fa1f752e36..5bc3049e018 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_box_image_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_box_image_custom.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitMaskBoxImage::ParseShorthand(
bool important,
@@ -26,32 +26,37 @@ bool WebkitMaskBoxImage::ParseShorthand(
CSSValue* outset = nullptr;
CSSValue* repeat = nullptr;
- if (!CSSParsingUtils::ConsumeBorderImageComponents(
+ if (!css_parsing_utils::ConsumeBorderImageComponents(
range, context, source, slice, width, outset, repeat,
- CSSParsingUtils::DefaultFill::kFill)) {
+ css_parsing_utils::DefaultFill::kFill)) {
return false;
}
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskBoxImageSource, CSSPropertyWebkitMaskBoxImage,
source ? *source : *CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskBoxImageSlice, CSSPropertyWebkitMaskBoxImage,
slice ? *slice : *CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskBoxImageWidth, CSSPropertyWebkitMaskBoxImage,
width ? *width : *CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskBoxImageOutset, CSSPropertyWebkitMaskBoxImage,
outset ? *outset : *CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskBoxImageRepeat, CSSPropertyWebkitMaskBoxImage,
repeat ? *repeat : *CSSInitialValue::Create(), important,
- CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
return true;
}
@@ -66,5 +71,5 @@ const CSSValue* WebkitMaskBoxImage::CSSValueFromComputedStyleInternal(
style);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_custom.cc
index 36461420a20..5656c80725b 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_custom.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitMask::ParseShorthand(
bool important,
@@ -15,9 +15,9 @@ bool WebkitMask::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext& local_context,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSParsingUtils::ParseBackgroundOrMask(important, range, context,
- local_context, properties);
+ return css_parsing_utils::ParseBackgroundOrMask(important, range, context,
+ local_context, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_position_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_position_custom.cc
index 7cdd0fa4405..d0746642917 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_position_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_position_custom.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitMaskPosition::ParseShorthand(
bool important,
@@ -22,20 +22,20 @@ bool WebkitMaskPosition::ParseShorthand(
CSSValue* result_x = nullptr;
CSSValue* result_y = nullptr;
- if (!CSSParsingUtils::ConsumeBackgroundPosition(
- range, context, CSSPropertyParserHelpers::UnitlessQuirk::kAllow,
+ if (!css_parsing_utils::ConsumeBackgroundPosition(
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow,
result_x, result_y) ||
!range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskPositionX, CSSPropertyWebkitMaskPosition, *result_x,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskPositionY, CSSPropertyWebkitMaskPosition, *result_y,
- important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
}
@@ -50,5 +50,5 @@ const CSSValue* WebkitMaskPosition::CSSValueFromComputedStyleInternal(
*this, style, &style.MaskLayers());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_repeat_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_repeat_custom.cc
index 8d070634fbb..585000554b6 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_repeat_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_repeat_custom.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitMaskRepeat::ParseShorthand(
bool important,
@@ -24,22 +24,22 @@ bool WebkitMaskRepeat::ParseShorthand(
CSSValue* result_x = nullptr;
CSSValue* result_y = nullptr;
bool implicit = false;
- if (!CSSParsingUtils::ConsumeRepeatStyle(range, result_x, result_y,
- implicit) ||
+ if (!css_parsing_utils::ConsumeRepeatStyle(range, result_x, result_y,
+ implicit) ||
!range.AtEnd())
return false;
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskRepeatX, CSSPropertyWebkitMaskRepeat, *result_x,
important,
- implicit ? CSSPropertyParserHelpers::IsImplicitProperty::kImplicit
- : CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ implicit ? css_property_parser_helpers::IsImplicitProperty::kImplicit
+ : css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
- CSSPropertyParserHelpers::AddProperty(
+ css_property_parser_helpers::AddProperty(
CSSPropertyWebkitMaskRepeatY, CSSPropertyWebkitMaskRepeat, *result_y,
important,
- implicit ? CSSPropertyParserHelpers::IsImplicitProperty::kImplicit
- : CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit,
+ implicit ? css_property_parser_helpers::IsImplicitProperty::kImplicit
+ : css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
return true;
@@ -55,5 +55,5 @@ const CSSValue* WebkitMaskRepeat::CSSValueFromComputedStyleInternal(
&style.MaskLayers());
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_emphasis_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_emphasis_custom.cc
index 55b0f8e237d..ad5322714ea 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_emphasis_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_emphasis_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitTextEmphasis::ParseShorthand(
bool important,
@@ -16,9 +16,9 @@ bool WebkitTextEmphasis::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
webkitTextEmphasisShorthand(), important, context, range, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_stroke_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_stroke_custom.cc
index df10d4b3b7a..3ed0b964f1e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_stroke_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/webkit_text_stroke_custom.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/style_property_shorthand.h"
namespace blink {
-namespace CSSShorthand {
+namespace css_shorthand {
bool WebkitTextStroke::ParseShorthand(
bool important,
@@ -16,9 +16,9 @@ bool WebkitTextStroke::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return CSSPropertyParserHelpers::ConsumeShorthandGreedilyViaLonghands(
+ return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
webkitTextStrokeShorthand(), important, context, range, properties);
}
-} // namespace CSSShorthand
+} // namespace css_shorthand
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/style_building_utils.h b/chromium/third_party/blink/renderer/core/css/properties/style_building_utils.h
index 1fba8a59397..730c294698e 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/style_building_utils.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/style_building_utils.h
@@ -7,11 +7,11 @@
#include "third_party/blink/renderer/core/style/border_image_length.h"
#include "third_party/blink/renderer/core/style/border_image_length_box.h"
-#include "third_party/blink/renderer/platform/length.h"
-#include "third_party/blink/renderer/platform/length_box.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/geometry/length_box.h"
namespace blink {
-namespace StyleBuildingUtils {
+namespace style_building_utils {
inline bool BorderImageLengthMatchesAllSides(
const BorderImageLengthBox& border_image_length_box,
@@ -27,7 +27,7 @@ inline bool LengthMatchesAllSides(const LengthBox& length_box,
length_box.Top() == length && length_box.Bottom() == length);
}
-} // namespace StyleBuildingUtils
+} // namespace style_building_utils
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_STYLE_BUILDING_UTILS_H_
diff --git a/chromium/third_party/blink/renderer/core/css/property_registration.cc b/chromium/third_party/blink/renderer/core/css/property_registration.cc
index d5d49d7a862..883f87f96ec 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registration.cc
+++ b/chromium/third_party/blink/renderer/core/css/property_registration.cc
@@ -46,7 +46,8 @@ PropertyRegistration::PropertyRegistration(
CSSInterpolationTypesMap::CreateInterpolationTypesForCSSSyntax(
name,
syntax,
- *this)) {
+ *this)),
+ referenced_(false) {
DCHECK(RuntimeEnabledFeatures::CSSVariables2Enabled());
}
@@ -90,14 +91,14 @@ static bool ComputationallyIndependent(const CSSValue& value) {
void PropertyRegistration::registerProperty(
ExecutionContext* execution_context,
- const PropertyDescriptor& descriptor,
+ const PropertyDescriptor* descriptor,
ExceptionState& exception_state) {
// Bindings code ensures these are set.
- DCHECK(descriptor.hasName());
- DCHECK(descriptor.hasInherits());
- DCHECK(descriptor.hasSyntax());
+ DCHECK(descriptor->hasName());
+ DCHECK(descriptor->hasInherits());
+ DCHECK(descriptor->hasSyntax());
- String name = descriptor.name();
+ String name = descriptor->name();
if (!CSSVariableParser::IsValidVariableName(name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
@@ -114,7 +115,7 @@ void PropertyRegistration::registerProperty(
return;
}
- CSSSyntaxDescriptor syntax_descriptor(descriptor.syntax());
+ CSSSyntaxDescriptor syntax_descriptor(descriptor->syntax());
if (!syntax_descriptor.IsValid()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
@@ -127,8 +128,8 @@ void PropertyRegistration::registerProperty(
const CSSValue* initial = nullptr;
scoped_refptr<CSSVariableData> initial_variable_data;
- if (descriptor.hasInitialValue()) {
- CSSTokenizer tokenizer(descriptor.initialValue());
+ if (descriptor->hasInitialValue()) {
+ CSSTokenizer tokenizer(descriptor->initialValue());
const auto tokens = tokenizer.TokenizeToEOF();
bool is_animation_tainted = false;
initial = syntax_descriptor.Parse(CSSParserTokenRange(tokens),
@@ -145,8 +146,8 @@ void PropertyRegistration::registerProperty(
"The initial value provided is not computationally independent.");
return;
}
- initial =
- &StyleBuilderConverter::ConvertRegisteredPropertyInitialValue(*initial);
+ initial = &StyleBuilderConverter::ConvertRegisteredPropertyInitialValue(
+ *document, *initial);
initial_variable_data = CSSVariableData::Create(
CSSParserTokenRange(tokens), is_animation_tainted, false,
parser_context->BaseURL(), parser_context->Charset());
@@ -159,9 +160,9 @@ void PropertyRegistration::registerProperty(
}
}
registry.RegisterProperty(
- atomic_name, *new PropertyRegistration(atomic_name, syntax_descriptor,
- descriptor.inherits(), initial,
- std::move(initial_variable_data)));
+ atomic_name, *MakeGarbageCollected<PropertyRegistration>(
+ atomic_name, syntax_descriptor, descriptor->inherits(),
+ initial, std::move(initial_variable_data)));
document->GetStyleEngine().CustomPropertyRegistered();
}
diff --git a/chromium/third_party/blink/renderer/core/css/property_registration.h b/chromium/third_party/blink/renderer/core/css/property_registration.h
index 68639ad494b..2986ee03c42 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registration.h
+++ b/chromium/third_party/blink/renderer/core/css/property_registration.h
@@ -26,12 +26,18 @@ class CORE_EXPORT PropertyRegistration
: public GarbageCollectedFinalized<PropertyRegistration> {
public:
static void registerProperty(ExecutionContext*,
- const PropertyDescriptor&,
+ const PropertyDescriptor*,
ExceptionState&);
static const PropertyRegistration* From(const ExecutionContext*,
const AtomicString& property_name);
+ PropertyRegistration(const AtomicString& name,
+ const CSSSyntaxDescriptor&,
+ bool inherits,
+ const CSSValue* initial,
+ scoped_refptr<CSSVariableData> initial_variable_data);
+
const CSSSyntaxDescriptor& Syntax() const { return syntax_; }
bool Inherits() const { return inherits_; }
const CSSValue* Initial() const { return initial_; }
@@ -45,17 +51,14 @@ class CORE_EXPORT PropertyRegistration
void Trace(blink::Visitor* visitor) { visitor->Trace(initial_); }
private:
- PropertyRegistration(const AtomicString& name,
- const CSSSyntaxDescriptor&,
- bool inherits,
- const CSSValue* initial,
- scoped_refptr<CSSVariableData> initial_variable_data);
+ friend class ::blink::PropertyRegistry;
const CSSSyntaxDescriptor syntax_;
const bool inherits_;
const Member<const CSSValue> initial_;
const scoped_refptr<CSSVariableData> initial_variable_data_;
const InterpolationTypes interpolation_types_;
+ mutable bool referenced_;
FRIEND_TEST_ALL_PREFIXES(CSSVariableResolverTest,
NeedsResolutionClearedByResolver);
diff --git a/chromium/third_party/blink/renderer/core/css/property_registry.cc b/chromium/third_party/blink/renderer/core/css/property_registry.cc
index 28ff581082c..8bc06920796 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registry.cc
+++ b/chromium/third_party/blink/renderer/core/css/property_registry.cc
@@ -57,4 +57,19 @@ const CSSValue* PropertyRegistry::ParseIfRegistered(
return parsed_value ? parsed_value : value;
}
+void PropertyRegistry::MarkReferenced(const AtomicString& property_name) const {
+ const PropertyRegistration* registration = Registration(property_name);
+ if (registration) {
+ registration->referenced_ = true;
+ }
+}
+
+bool PropertyRegistry::WasReferenced(const AtomicString& property_name) const {
+ const PropertyRegistration* registration = Registration(property_name);
+ if (!registration) {
+ return false;
+ }
+ return registration->referenced_;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/property_registry.h b/chromium/third_party/blink/renderer/core/css/property_registry.h
index b9dc7a10ef4..6f7f0503db4 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registry.h
+++ b/chromium/third_party/blink/renderer/core/css/property_registry.h
@@ -16,7 +16,9 @@ class CORE_EXPORT PropertyRegistry : public GarbageCollected<PropertyRegistry> {
using RegistrationMap =
HeapHashMap<AtomicString, Member<PropertyRegistration>>;
- static PropertyRegistry* Create() { return new PropertyRegistry(); }
+ static PropertyRegistry* Create() {
+ return MakeGarbageCollected<PropertyRegistry>();
+ }
void RegisterProperty(const AtomicString&, PropertyRegistration&);
const PropertyRegistration* Registration(const AtomicString&) const;
@@ -36,6 +38,9 @@ class CORE_EXPORT PropertyRegistry : public GarbageCollected<PropertyRegistry> {
const AtomicString& property_name,
const CSSValue*);
+ void MarkReferenced(const AtomicString&) const;
+ bool WasReferenced(const AtomicString&) const;
+
private:
RegistrationMap registrations_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/remote_font_face_source.cc b/chromium/third_party/blink/renderer/core/css/remote_font_face_source.cc
index 9eff7047b0d..2f758c5d349 100644
--- a/chromium/third_party/blink/renderer/core/css/remote_font_face_source.cc
+++ b/chromium/third_party/blink/renderer/core/css/remote_font_face_source.cc
@@ -235,9 +235,9 @@ RemoteFontFaceSource::CreateLoadingFallbackFontData(
const FontDescription& font_description) {
// This temporary font is not retained and should not be returned.
FontCachePurgePreventer font_cache_purge_preventer;
- SimpleFontData* temporary_font =
- FontCache::GetFontCache()->GetNonRetainedLastResortFallbackFont(
- font_description);
+ scoped_refptr<SimpleFontData> temporary_font =
+ FontCache::GetFontCache()->GetLastResortFallbackFont(font_description,
+ kDoNotRetain);
if (!temporary_font) {
NOTREACHED();
return nullptr;
@@ -253,6 +253,8 @@ void RemoteFontFaceSource::BeginLoadIfNeeded() {
return;
DCHECK(GetResource());
+ SetDisplay(face_->GetFontFace()->GetFontDisplayWithFallback());
+
FontResource* font = ToFontResource(GetResource());
if (font->StillNeedsLoad()) {
if (font->IsLowPriorityLoadingAllowedForRemoteFont()) {
@@ -330,11 +332,11 @@ void RemoteFontFaceSource::FontLoadHistograms::RecordRemoteFont(
int duration = static_cast<int>(CurrentTimeMS() - load_start_time_);
RecordLoadTimeHistogram(font, duration);
- enum { kCORSFail, kCORSSuccess, kCORSEnumMax };
+ enum { kCorsFail, kCorsSuccess, kCorsEnumMax };
int cors_value =
- font->GetResponse().IsCORSSameOrigin() ? kCORSSuccess : kCORSFail;
+ font->GetResponse().IsCorsSameOrigin() ? kCorsSuccess : kCorsFail;
DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram, cors_histogram,
- ("WebFont.CORSSuccess", kCORSEnumMax));
+ ("WebFont.CORSSuccess", kCorsEnumMax));
cors_histogram.Count(cors_value);
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/animated_style_builder.h b/chromium/third_party/blink/renderer/core/css/resolver/animated_style_builder.h
index bfe5802f203..196c1b68426 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/animated_style_builder.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/animated_style_builder.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_ANIMATED_STYLE_BUILDER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_ANIMATED_STYLE_BUILDER_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/css_property_priority.h b/chromium/third_party/blink/renderer/core/css/resolver/css_property_priority.h
index 74a835ca3de..0d90ca3fe4f 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/css_property_priority.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/css_property_priority.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_CSS_PROPERTY_PRIORITY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_CSS_PROPERTY_PRIORITY_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/css_to_style_map.h b/chromium/third_party/blink/renderer/core/css/resolver/css_to_style_map.h
index 827b91cde84..a50c47a51d8 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/css_to_style_map.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/css_to_style_map.h
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/animation/css/css_transition_data.h"
#include "third_party/blink/renderer/core/animation/timing.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc b/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc
index 57172354634..48160c189ca 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.cc
@@ -5,7 +5,9 @@
#include "third_party/blink/renderer/core/css/resolver/css_variable_resolver.h"
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h"
#include "third_party/blink/renderer/core/css/css_pending_substitution_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_unset_value.h"
#include "third_party/blink/renderer/core/css/css_variable_data.h"
#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
@@ -20,7 +22,6 @@
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_stats.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
@@ -85,14 +86,28 @@ scoped_refptr<CSSVariableData> ComputedVariableData(
} // namespace
-bool CSSVariableResolver::ResolveFallback(CSSParserTokenRange range,
- const Options& options,
- Result& result) {
+CSSVariableResolver::Fallback CSSVariableResolver::ResolveFallback(
+ CSSParserTokenRange range,
+ const Options& options,
+ const PropertyRegistration* registration,
+ Result& result) {
if (range.AtEnd())
- return false;
+ return Fallback::kNone;
DCHECK_EQ(range.Peek().GetType(), kCommaToken);
range.Consume();
- return ResolveTokenRange(range, options, result);
+ size_t first_fallback_token = result.tokens.size();
+ if (!ResolveTokenRange(range, options, result))
+ return Fallback::kFail;
+ if (registration) {
+ CSSParserTokenRange range(result.tokens);
+ range = range.MakeSubRange(&range.Peek(first_fallback_token), range.end());
+ const CSSParserContext* context =
+ StrictCSSParserContext(state_.GetDocument().GetSecureContextMode());
+ const bool is_animation_tainted = false;
+ if (!registration->Syntax().Parse(range, context, is_animation_tainted))
+ return Fallback::kFail;
+ }
+ return Fallback::kSuccess;
}
scoped_refptr<CSSVariableData> CSSVariableResolver::ValueForCustomProperty(
@@ -109,11 +124,31 @@ scoped_refptr<CSSVariableData> CSSVariableResolver::ValueForCustomProperty(
CSSVariableData* variable_data = GetVariable(name, registration);
- if (!variable_data)
- return registration ? registration->InitialVariableData() : nullptr;
+ if (!variable_data) {
+ // For unregistered properties, not having a CSSVariableData here means
+ // that it either never existed, or we have resolved it earlier, but
+ // resolution failed. Either way, we return nullptr to signify that this is
+ // an invalid variable.
+ if (!registration)
+ return nullptr;
+ // For registered properties, it's more complicated. Here too, it can mean
+ // that it never existed, or that resolution failed earlier, but now we need
+ // to know which; in the former case we must provide the initial value, and
+ // in the latter case the variable is invalid.
+ return IsRegisteredVariableInvalid(name, *registration)
+ ? nullptr
+ : registration->InitialVariableData();
+ }
- scoped_refptr<CSSVariableData> resolved_data =
- ResolveCustomPropertyIfNeeded(name, variable_data, options);
+ bool cycle_detected = false;
+ scoped_refptr<CSSVariableData> resolved_data = ResolveCustomPropertyIfNeeded(
+ name, variable_data, options, cycle_detected);
+
+ if (!resolved_data && cycle_detected) {
+ if (options.absolutize)
+ SetInvalidVariable(name, registration);
+ return nullptr;
+ }
if (resolved_data) {
if (IsVariableDisallowed(*resolved_data, options, registration))
@@ -146,7 +181,8 @@ scoped_refptr<CSSVariableData> CSSVariableResolver::ValueForCustomProperty(
// take inherited values instead of falling back on initial.
if (registration->Inherits() && !resolved_data) {
resolved_data = state_.ParentStyle()->GetVariable(name, true);
- resolved_value = state_.ParentStyle()->GetRegisteredVariable(name, true);
+ resolved_value =
+ state_.ParentStyle()->GetNonInitialRegisteredVariable(name, true);
}
DCHECK(!!resolved_data == !!resolved_value);
@@ -197,9 +233,10 @@ scoped_refptr<CSSVariableData> CSSVariableResolver::ResolveCustomProperty(
bool success = ResolveTokenRange(variable_data.Tokens(), options, result);
variables_seen_.erase(name);
- if (!success || !cycle_start_points_.IsEmpty()) {
- cycle_start_points_.erase(name);
+ if (!cycle_start_points_.IsEmpty())
cycle_detected = true;
+ if (!success || cycle_detected) {
+ cycle_start_points_.erase(name);
return nullptr;
}
cycle_detected = false;
@@ -219,14 +256,14 @@ scoped_refptr<CSSVariableData>
CSSVariableResolver::ResolveCustomPropertyIfNeeded(
AtomicString name,
CSSVariableData* variable_data,
- const Options& options) {
+ const Options& options,
+ bool& cycle_detected) {
DCHECK(variable_data);
bool resolve_urls = ShouldResolveRelativeUrls(name, *variable_data);
if (!variable_data->NeedsVariableResolution() && !resolve_urls)
return variable_data;
- bool unused_cycle_detected;
return ResolveCustomProperty(name, *variable_data, options, resolve_urls,
- unused_cycle_detected);
+ cycle_detected);
}
void CSSVariableResolver::ResolveRelativeUrls(
@@ -319,6 +356,25 @@ void CSSVariableResolver::SetRegisteredVariable(
}
}
+void CSSVariableResolver::SetInvalidVariable(
+ const AtomicString& name,
+ const PropertyRegistration* registration) {
+ // TODO(andruud): Use RemoveVariable instead, but currently it also does
+ // a lookup in the registered map, which seems wasteful.
+ SetVariable(name, registration, nullptr);
+ if (registration) {
+ const CSSValue* value = CSSInvalidVariableValue::Create();
+ SetRegisteredVariable(name, *registration, value);
+ }
+}
+
+bool CSSVariableResolver::IsRegisteredVariableInvalid(
+ const AtomicString& name,
+ const PropertyRegistration& registration) {
+ const CSSValue* value = GetRegisteredVariable(name, registration);
+ return value && value->IsInvalidVariableValue();
+}
+
bool CSSVariableResolver::ResolveVariableReference(CSSParserTokenRange range,
const Options& options,
bool is_env_variable,
@@ -337,6 +393,13 @@ bool CSSVariableResolver::ResolveVariableReference(CSSParserTokenRange range,
non_inherited_variables_ = state_.Style()->NonInheritedVariables();
}
+ const PropertyRegistration* registration = nullptr;
+ if (registry_) {
+ registration = registry_->Registration(variable_name);
+ if (!is_env_variable)
+ registry_->MarkReferenced(variable_name);
+ }
+
scoped_refptr<CSSVariableData> variable_data =
is_env_variable ? ValueForEnvironmentVariable(variable_name)
: ValueForCustomProperty(variable_name, options);
@@ -344,7 +407,8 @@ bool CSSVariableResolver::ResolveVariableReference(CSSParserTokenRange range,
if (!variable_data) {
// TODO(alancutter): Append the registered initial custom property value if
// we are disallowing an animation tainted value.
- return ResolveFallback(range, options, result);
+ return ResolveFallback(range, options, registration, result) ==
+ Fallback::kSuccess;
}
result.tokens.AppendVector(variable_data->Tokens());
@@ -356,7 +420,13 @@ bool CSSVariableResolver::ResolveVariableReference(CSSParserTokenRange range,
result.absolutized &= variable_data->IsAbsolutized();
Result trash;
- ResolveFallback(range, options, trash);
+ Fallback fallback = ResolveFallback(range, options, registration, trash);
+
+ // For registered properties, the fallback (if present) must be valid, even
+ // if it's not used.
+ if (registration && fallback == Fallback::kFail)
+ return false;
+
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.h b/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.h
index d7481380a68..a68e4265adc 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.h
@@ -5,8 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_CSS_VARIABLE_RESOLVER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_CSS_VARIABLE_RESOLVER_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string_hash.h"
@@ -134,9 +134,26 @@ class CORE_EXPORT CSSVariableResolver {
// Resolves a range which may contain var() or env() references.
bool ResolveTokenRange(CSSParserTokenRange, const Options&, Result&);
+
+ // Return value for ResolveFallback.
+ enum class Fallback {
+ // Fallback not present.
+ kNone,
+ // Fallback present, but resolution failed (i.e. invalid variables
+ // referenced), or the result did not match the syntax registered for
+ // the referenced variable (if applicable).
+ kFail,
+ // Fallback present, resolution succeeded, and syntax matched (if
+ // applicable).
+ kSuccess
+ };
+
// Resolves the fallback (if present) of a var() or env() reference, starting
// from the comma.
- bool ResolveFallback(CSSParserTokenRange, const Options&, Result&);
+ Fallback ResolveFallback(CSSParserTokenRange,
+ const Options&,
+ const PropertyRegistration*,
+ Result&);
// Resolves the contents of a var() or env() reference.
bool ResolveVariableReference(CSSParserTokenRange,
const Options&,
@@ -163,7 +180,8 @@ class CORE_EXPORT CSSVariableResolver {
scoped_refptr<CSSVariableData> ResolveCustomPropertyIfNeeded(
AtomicString name,
CSSVariableData*,
- const Options&);
+ const Options&,
+ bool& cycle_detected);
// Rewrites (in-place) kUrlTokens and kFunctionToken/CSSValueUrls to contain
// absolute URLs.
void ResolveRelativeUrls(Vector<CSSParserToken>& tokens,
@@ -191,6 +209,10 @@ class CORE_EXPORT CSSVariableResolver {
void SetRegisteredVariable(const AtomicString& name,
const PropertyRegistration&,
const CSSValue*);
+ void SetInvalidVariable(const AtomicString& name,
+ const PropertyRegistration*);
+ bool IsRegisteredVariableInvalid(const AtomicString& name,
+ const PropertyRegistration&);
const StyleResolverState& state_;
StyleInheritedVariables* inherited_variables_;
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc b/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc
index aea966ed443..bd5d4b631c7 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/properties/longhand.h"
+#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h"
#include "third_party/blink/renderer/core/css/property_registration.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
@@ -40,7 +41,6 @@ class CSSVariableResolverTest : public PageTestBase {
void SetUp() override {
PageTestBase::SetUp();
- RuntimeEnabledFeatures::SetCSSEnvironmentVariablesEnabled(true);
GetStyleEngine().EnsureEnvironmentVariables().SetVariable("test", "red");
}
@@ -57,7 +57,7 @@ class CSSVariableResolverTest : public PageTestBase {
"<div>"
" <div id=target></div>"
"</div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
const CSSCustomPropertyDeclaration* CreateCustomProperty(
@@ -261,16 +261,17 @@ TEST_F(CSSVariableResolverTest, NeedsResolutionClearedByResolver) {
token_syntax.Parse(CSSParserTokenRange(tokens), context, false);
ASSERT_TRUE(initial_value);
ASSERT_TRUE(initial_value->IsVariableReferenceValue());
- PropertyRegistration* registration = new PropertyRegistration(
- "--prop3", token_syntax, false, initial_value,
- ToCSSVariableReferenceValue(*initial_value).VariableDataValue());
+ PropertyRegistration* registration =
+ MakeGarbageCollected<PropertyRegistration>(
+ "--prop3", token_syntax, false, initial_value,
+ ToCSSVariableReferenceValue(*initial_value).VariableDataValue());
ASSERT_TRUE(GetDocument().GetPropertyRegistry());
GetDocument().GetPropertyRegistry()->RegisterProperty("--prop3",
*registration);
- ToLonghand(GetCSSPropertyVariable()).ApplyValue(state, *prop1);
- ToLonghand(GetCSSPropertyVariable()).ApplyValue(state, *prop2);
- ToLonghand(GetCSSPropertyVariable()).ApplyValue(state, *prop3);
+ CustomProperty("--prop1", GetDocument()).ApplyValue(state, *prop1);
+ CustomProperty("--prop2", GetDocument()).ApplyValue(state, *prop2);
+ CustomProperty("--prop3", GetDocument()).ApplyValue(state, *prop3);
EXPECT_TRUE(state.Style()->InheritedVariables()->NeedsResolution());
EXPECT_TRUE(state.Style()->NonInheritedVariables()->NeedsResolution());
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.h b/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.h
index 49bb15d112a..9bcf1581af9 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.h
@@ -24,6 +24,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_ELEMENT_RESOLVE_CONTEXT_H_
#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.cc b/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.cc
index c1ea3013309..8cf83d116c4 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.cc
@@ -25,12 +25,13 @@
#include "third_party/blink/renderer/core/css/css_gradient_value.h"
#include "third_party/blink/renderer/core/css/css_image_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_uri_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/tree_scope.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/lazy_load_image_observer.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/content_data.h"
@@ -44,7 +45,7 @@
#include "third_party/blink/renderer/core/style/style_pending_image.h"
#include "third_party/blink/renderer/core/svg/svg_resource.h"
#include "third_party/blink/renderer/core/svg/svg_tree_scope_resources.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
@@ -203,7 +204,9 @@ void ElementStyleResources::LoadPendingImages(ComputedStyle* style) {
FetchParameters::ImageRequestOptimization
image_request_optimization = FetchParameters::kNone;
if (!BackgroundLayerMayBeSprite(*background_layer)) {
- if (element_->GetDocument()
+ if (element_->GetDocument().GetSettings() &&
+ element_->GetDocument().GetSettings()->GetLazyLoadEnabled() &&
+ element_->GetDocument()
.GetFrame()
->IsLazyLoadingImageAllowed()) {
image_request_optimization = FetchParameters::kDeferImageLoad;
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.h b/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.h
index 08ebe761f06..f90ebdba843 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.h
@@ -26,7 +26,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/css/css_property_id_templates.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.cc b/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.cc
index 4e6c08de9ec..8b147e0bb58 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.cc
@@ -120,6 +120,38 @@ static void CountFilterUse(FilterOperation::OperationType operation_type,
UseCounter::Count(document, feature);
}
+static double ResolveFirstArgumentForFunction(const CSSFunctionValue& filter,
+ const CSSPrimitiveValue* value) {
+ switch (filter.FunctionType()) {
+ case CSSValueGrayscale:
+ case CSSValueSepia:
+ case CSSValueSaturate:
+ case CSSValueInvert:
+ case CSSValueBrightness:
+ case CSSValueContrast:
+ case CSSValueOpacity: {
+ double amount = (filter.FunctionType() == CSSValueBrightness ||
+ filter.FunctionType() == CSSValueInvert)
+ ? 0
+ : 1;
+ if (filter.length() == 1) {
+ amount = value->GetDoubleValue();
+ if (value->IsPercentage())
+ amount /= 100;
+ }
+ return amount;
+ }
+ case CSSValueHueRotate: {
+ double angle = 0;
+ if (filter.length() == 1)
+ angle = value->ComputeDegrees();
+ return angle;
+ }
+ default:
+ return 0;
+ }
+}
+
FilterOperations FilterOperationResolver::CreateFilterOperations(
StyleResolverState& state,
const CSSValue& in_value) {
@@ -158,7 +190,7 @@ FilterOperations FilterOperationResolver::CreateFilterOperations(
? &ToCSSPrimitiveValue(filter_value->Item(0))
: nullptr;
double first_number =
- StyleBuilderConverter::ConvertValueToNumber(filter_value, first_value);
+ ResolveFirstArgumentForFunction(*filter_value, first_value);
switch (filter_value->FunctionType()) {
case CSSValueGrayscale:
@@ -242,7 +274,7 @@ FilterOperations FilterOperationResolver::CreateOffscreenFilterOperations(
? &ToCSSPrimitiveValue(filter_value->Item(0))
: nullptr;
double first_number =
- StyleBuilderConverter::ConvertValueToNumber(filter_value, first_value);
+ ResolveFirstArgumentForFunction(*filter_value, first_value);
switch (filter_value->FunctionType()) {
case CSSValueGrayscale:
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/font_builder.cc b/chromium/third_party/blink/renderer/core/css/resolver/font_builder.cc
index c5302a92614..e46dfec3c15 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/font_builder.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/font_builder.cc
@@ -86,17 +86,17 @@ AtomicString FontBuilder::GenericFontFamilyName(
case FontDescription::kStandardFamily:
return StandardFontFamilyName();
case FontDescription::kSerifFamily:
- return FontFamilyNames::webkit_serif;
+ return font_family_names::kWebkitSerif;
case FontDescription::kSansSerifFamily:
- return FontFamilyNames::webkit_sans_serif;
+ return font_family_names::kWebkitSansSerif;
case FontDescription::kMonospaceFamily:
- return FontFamilyNames::webkit_monospace;
+ return font_family_names::kWebkitMonospace;
case FontDescription::kCursiveFamily:
- return FontFamilyNames::webkit_cursive;
+ return font_family_names::kWebkitCursive;
case FontDescription::kFantasyFamily:
- return FontFamilyNames::webkit_fantasy;
+ return font_family_names::kWebkitFantasy;
case FontDescription::kPictographFamily:
- return FontFamilyNames::webkit_pictograph;
+ return font_family_names::kWebkitPictograph;
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/match_result_test.cc b/chromium/third_party/blink/renderer/core/css/resolver/match_result_test.cc
index 1b2775e4062..027bf590582 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/match_result_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/match_result_test.cc
@@ -22,7 +22,8 @@ class MatchResultTest : public testing::Test {
};
void MatchResultTest::SetUp() {
- property_sets = new HeapVector<Member<MutableCSSPropertyValueSet>, 8>();
+ property_sets =
+ MakeGarbageCollected<HeapVector<Member<MutableCSSPropertyValueSet>, 8>>();
for (unsigned i = 0; i < 8; i++) {
property_sets->push_back(
MutableCSSPropertyValueSet::Create(kHTMLQuirksMode));
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc b/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc
index b60eabca74e..9f4f7482a19 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc
@@ -81,6 +81,9 @@ void ScopedStyleResolver::AddFontFaceRules(const RuleSet& rule_set) {
}
if (font_face_rules.size() && document.GetStyleResolver())
document.GetStyleResolver()->InvalidateMatchedPropertiesCache();
+
+ for (const auto& rule : rule_set.FontFeatureValuesRules())
+ document.GetStyleEngine().AddDefaultFontDisplay(rule);
}
void ScopedStyleResolver::AppendActiveStyleSheets(
@@ -206,7 +209,7 @@ void ScopedStyleResolver::KeyframesRulesAdded(const TreeScope& tree_scope) {
InvalidationRootForTreeScope(tree_scope)
.SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleSheetChange));
+ style_change_reason::kStyleSheetChange));
return;
}
@@ -326,7 +329,8 @@ void ScopedStyleResolver::AddTreeBoundaryCrossingRules(
AddRules(rule_set_for_scope, author_rules.ContentPseudoElementRules());
if (!tree_boundary_crossing_rule_set_) {
- tree_boundary_crossing_rule_set_ = new CSSStyleSheetRuleSubSet();
+ tree_boundary_crossing_rule_set_ =
+ MakeGarbageCollected<CSSStyleSheetRuleSubSet>();
GetTreeScope().GetDocument().GetStyleEngine().AddTreeBoundaryCrossingScope(
GetTreeScope());
}
@@ -341,7 +345,8 @@ void ScopedStyleResolver::V0ShadowAddedOnV1Document() {
return;
if (!tree_boundary_crossing_rule_set_) {
- tree_boundary_crossing_rule_set_ = new CSSStyleSheetRuleSubSet();
+ tree_boundary_crossing_rule_set_ =
+ MakeGarbageCollected<CSSStyleSheetRuleSubSet>();
GetTreeScope().GetDocument().GetStyleEngine().AddTreeBoundaryCrossingScope(
GetTreeScope());
}
@@ -369,7 +374,8 @@ void ScopedStyleResolver::AddSlottedRules(const RuleSet& author_rules,
// rule sets. See V0ShadowAddedOnV1Document().
if (GetTreeScope().GetDocument().MayContainV0Shadow()) {
if (!tree_boundary_crossing_rule_set_) {
- tree_boundary_crossing_rule_set_ = new CSSStyleSheetRuleSubSet();
+ tree_boundary_crossing_rule_set_ =
+ MakeGarbageCollected<CSSStyleSheetRuleSubSet>();
GetTreeScope()
.GetDocument()
.GetStyleEngine()
@@ -380,7 +386,7 @@ void ScopedStyleResolver::AddSlottedRules(const RuleSet& author_rules,
return;
}
if (!slotted_rule_set_)
- slotted_rule_set_ = new CSSStyleSheetRuleSubSet();
+ slotted_rule_set_ = MakeGarbageCollected<CSSStyleSheetRuleSubSet>();
slotted_rule_set_->push_back(
RuleSubSet::Create(parent_style_sheet, sheet_index, slotted_rule_set));
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h b/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h
index acda21dc2e5..1504e045932 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h
@@ -52,9 +52,11 @@ class ScopedStyleResolver final
public:
static ScopedStyleResolver* Create(TreeScope& scope) {
- return new ScopedStyleResolver(scope);
+ return MakeGarbageCollected<ScopedStyleResolver>(scope);
}
+ explicit ScopedStyleResolver(TreeScope& scope) : scope_(scope) {}
+
const TreeScope& GetTreeScope() const { return *scope_; }
ScopedStyleResolver* Parent() const;
@@ -94,8 +96,6 @@ class ScopedStyleResolver final
void Trace(blink::Visitor*);
private:
- explicit ScopedStyleResolver(TreeScope& scope) : scope_(scope) {}
-
void AddTreeBoundaryCrossingRules(const RuleSet&,
CSSStyleSheet*,
unsigned sheet_index);
@@ -119,18 +119,17 @@ class ScopedStyleResolver final
static RuleSubSet* Create(CSSStyleSheet* sheet,
unsigned index,
RuleSet* rules) {
- return new RuleSubSet(sheet, index, rules);
+ return MakeGarbageCollected<RuleSubSet>(sheet, index, rules);
}
+ RuleSubSet(CSSStyleSheet* sheet, unsigned index, RuleSet* rules)
+ : parent_style_sheet_(sheet), parent_index_(index), rule_set_(rules) {}
+
Member<CSSStyleSheet> parent_style_sheet_;
unsigned parent_index_;
Member<RuleSet> rule_set_;
void Trace(blink::Visitor*);
-
- private:
- RuleSubSet(CSSStyleSheet* sheet, unsigned index, RuleSet* rules)
- : parent_style_sheet_(sheet), parent_index_(index), rule_set_(rules) {}
};
using CSSStyleSheetRuleSubSet = HeapVector<Member<RuleSubSet>>;
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope_test.cc b/chromium/third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope_test.cc
index 9382d366d46..efcf3dfbc03 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope_test.cc
@@ -26,7 +26,7 @@ class SelectorFilterParentScopeTest : public testing::Test {
};
TEST_F(SelectorFilterParentScopeTest, ParentScope) {
- GetDocument().body()->setAttribute(HTMLNames::classAttr, "match");
+ GetDocument().body()->setAttribute(html_names::kClassAttr, "match");
GetDocument().documentElement()->SetIdAttribute("myId");
SelectorFilter& filter =
GetDocument().EnsureStyleResolver().GetSelectorFilter();
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.cc
index 530c91882cc..0b552a69d2b 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.cc
@@ -56,15 +56,13 @@
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
#include "third_party/blink/renderer/core/svg_names.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/transforms/transform_operations.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
-using namespace HTMLNames;
-
namespace {
TouchAction AdjustTouchActionForElement(TouchAction touch_action,
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc
index 6521f2f00db..0d79e06aebc 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster_test.cc
@@ -27,15 +27,15 @@ TEST_F(StyleAdjusterTest, TouchActionPropagatedAcrossIframes) {
</style>
<div id='target' style='touch-action: pinch-zoom'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = ChildDocument().getElementById("target");
EXPECT_EQ(TouchAction::kTouchActionNone,
target->GetComputedStyle()->GetEffectiveTouchAction());
Element* owner = GetDocument().getElementById("owner");
- owner->setAttribute(HTMLNames::styleAttr, "touch-action: auto");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ owner->setAttribute(html_names::kStyleAttr, "touch-action: auto");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TouchAction::kTouchActionPinchZoom,
target->GetComputedStyle()->GetEffectiveTouchAction());
}
@@ -49,7 +49,7 @@ TEST_F(StyleAdjusterTest, TouchActionPanningReEnabledByScrollers) {
<div id='ancestor'><div id='scroller'><div id='target'>
</div></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = GetDocument().getElementById("target");
EXPECT_EQ(TouchAction::kTouchActionManipulation,
@@ -65,22 +65,22 @@ TEST_F(StyleAdjusterTest, TouchActionPropagatedWhenAncestorStyleChanges) {
<div id='ancestor'><div id='potential-scroller'><div id='target'>
</div></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = GetDocument().getElementById("target");
EXPECT_EQ(TouchAction::kTouchActionPanX,
target->GetComputedStyle()->GetEffectiveTouchAction());
Element* ancestor = GetDocument().getElementById("ancestor");
- ancestor->setAttribute(HTMLNames::styleAttr, "touch-action: pan-y");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "touch-action: pan-y");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TouchAction::kTouchActionPanY,
target->GetComputedStyle()->GetEffectiveTouchAction());
Element* potential_scroller =
GetDocument().getElementById("potential-scroller");
- potential_scroller->setAttribute(HTMLNames::styleAttr, "overflow: scroll");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ potential_scroller->setAttribute(html_names::kStyleAttr, "overflow: scroll");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TouchAction::kTouchActionPan,
target->GetComputedStyle()->GetEffectiveTouchAction());
}
@@ -93,15 +93,15 @@ TEST_F(StyleAdjusterTest, TouchActionRestrictedByLowerAncestor) {
<div id='target' style='touch-action: pan-x'>
</div></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = GetDocument().getElementById("target");
EXPECT_EQ(TouchAction::kTouchActionPanRight,
target->GetComputedStyle()->GetEffectiveTouchAction());
Element* parent = GetDocument().getElementById("parent");
- parent->setAttribute(HTMLNames::styleAttr, "touch-action: auto");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "touch-action: auto");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TouchAction::kTouchActionPanX,
target->GetComputedStyle()->GetEffectiveTouchAction());
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_builder.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_builder.cc
index 056f19c56af..78c281e59d1 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_builder.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_builder.cc
@@ -42,7 +42,10 @@
#include <utility>
#include "third_party/blink/renderer/core/animation/css/css_animations.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
#include "third_party/blink/renderer/core/css/properties/longhand.h"
+#include "third_party/blink/renderer/core/css/properties/longhands/variable.h"
#include "third_party/blink/renderer/core/css/resolver/css_variable_resolver.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
@@ -50,9 +53,21 @@
namespace blink {
+void StyleBuilder::ApplyProperty(const CSSPropertyName& name,
+ StyleResolverState& state,
+ const CSSValue& value) {
+ CSSPropertyRef ref(name, state.GetDocument());
+ DCHECK(ref.IsValid());
+
+ ApplyProperty(ref.GetProperty(), state, value);
+}
+
void StyleBuilder::ApplyProperty(const CSSProperty& property,
StyleResolverState& state,
const CSSValue& value) {
+ DCHECK(!Variable::IsStaticInstance(property))
+ << "Please use a CustomProperty instance to apply custom properties";
+
CSSPropertyID id = property.PropertyID();
bool is_inherited = property.IsInherited();
if (id != CSSPropertyVariable && (value.IsVariableReferenceValue() ||
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_builder.h b/chromium/third_party/blink/renderer/core/css/resolver/style_builder.h
index 1693a7498db..455e2f8994c 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_builder.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_builder.h
@@ -32,12 +32,13 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_BUILDER_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
+class CSSPropertyName;
class CSSValue;
class StyleResolverState;
@@ -45,6 +46,19 @@ class CORE_EXPORT StyleBuilder {
STATIC_ONLY(StyleBuilder);
public:
+ // Apply a property/value pair to the ComputedStyle.
+ //
+ // If the incoming CSSPropertyName is a custom property, a temporary
+ // CustomProperty instance is created to carry out the application.
+ static void ApplyProperty(const CSSPropertyName&,
+ StyleResolverState&,
+ const CSSValue&);
+
+ // Apply a property/value pair to the ComputedStyle.
+ //
+ // If you are applying a custom property, please ensure that the incoming
+ // CSSProperty is an instance of CustomProperty, and not the static Variable
+ // instance. See Variable::IsStaticInstance.
static void ApplyProperty(const CSSProperty&,
StyleResolverState&,
const CSSValue&);
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc
index 750b9f99e83..559595ebb78 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc
@@ -198,7 +198,7 @@ static bool ConvertFontFamilyName(
#if defined(OS_MACOSX)
if (family_name == FontCache::LegacySystemFontFamily()) {
UseCounter::Count(*document_for_count, WebFeature::kBlinkMacSystemFont);
- family_name = FontFamilyNames::system_ui;
+ family_name = font_family_names::kSystemUi;
}
#endif
} else if (font_builder) {
@@ -356,39 +356,6 @@ float StyleBuilderConverter::ConvertFontSizeAdjust(StyleResolverState& state,
return primitive_value.GetFloatValue();
}
-double StyleBuilderConverter::ConvertValueToNumber(
- const CSSFunctionValue* filter,
- const CSSPrimitiveValue* value) {
- switch (filter->FunctionType()) {
- case CSSValueGrayscale:
- case CSSValueSepia:
- case CSSValueSaturate:
- case CSSValueInvert:
- case CSSValueBrightness:
- case CSSValueContrast:
- case CSSValueOpacity: {
- double amount = (filter->FunctionType() == CSSValueBrightness ||
- filter->FunctionType() == CSSValueInvert)
- ? 0
- : 1;
- if (filter->length() == 1) {
- amount = value->GetDoubleValue();
- if (value->IsPercentage())
- amount /= 100;
- }
- return amount;
- }
- case CSSValueHueRotate: {
- double angle = 0;
- if (filter->length() == 1)
- angle = value->ComputeDegrees();
- return angle;
- }
- default:
- return 0;
- }
-}
-
FontSelectionValue StyleBuilderConverterBase::ConvertFontStretch(
const blink::CSSValue& value) {
if (value.IsPrimitiveValue()) {
@@ -1135,6 +1102,11 @@ float StyleBuilderConverter::ConvertNumberOrPercentage(
return primitive_value.GetFloatValue() / 100.0f;
}
+float StyleBuilderConverter::ConvertAlpha(StyleResolverState& state,
+ const CSSValue& value) {
+ return clampTo<float>(ConvertNumberOrPercentage(state, value), 0, 1);
+}
+
StyleOffsetRotation StyleBuilderConverter::ConvertOffsetRotate(
StyleResolverState&,
const CSSValue& value) {
@@ -1510,15 +1482,20 @@ TransformOrigin StyleBuilderConverter::ConvertTransformOrigin(
StyleResolverState& state,
const CSSValue& value) {
const CSSValueList& list = ToCSSValueList(value);
- DCHECK_EQ(list.length(), 3U);
+ DCHECK_GE(list.length(), 2u);
DCHECK(list.Item(0).IsPrimitiveValue() || list.Item(0).IsIdentifierValue());
DCHECK(list.Item(1).IsPrimitiveValue() || list.Item(1).IsIdentifierValue());
- DCHECK(list.Item(2).IsPrimitiveValue());
+ float z = 0;
+ if (list.length() == 3) {
+ DCHECK(list.Item(2).IsPrimitiveValue());
+ z = StyleBuilderConverter::ConvertComputedLength<float>(state,
+ list.Item(2));
+ }
return TransformOrigin(
ConvertPositionLength<CSSValueLeft, CSSValueRight>(state, list.Item(0)),
ConvertPositionLength<CSSValueTop, CSSValueBottom>(state, list.Item(1)),
- StyleBuilderConverter::ConvertComputedLength<float>(state, list.Item(2)));
+ z);
}
ScrollSnapType StyleBuilderConverter::ConvertSnapType(StyleResolverState&,
@@ -1665,6 +1642,7 @@ scoped_refptr<BasicShape> StyleBuilderConverter::ConvertOffsetPath(
}
static const CSSValue& ComputeRegisteredPropertyValue(
+ const Document& document,
const CSSToLengthConversionData& css_to_length_conversion_data,
const CSSValue& value) {
// TODO(timloh): Images values can also contain lengths.
@@ -1674,7 +1652,7 @@ static const CSSValue& ComputeRegisteredPropertyValue(
CSSFunctionValue::Create(function_value.FunctionType());
for (const CSSValue* inner_value : ToCSSValueList(value)) {
new_function->Append(ComputeRegisteredPropertyValue(
- css_to_length_conversion_data, *inner_value));
+ document, css_to_length_conversion_data, *inner_value));
}
return *new_function;
}
@@ -1684,7 +1662,7 @@ static const CSSValue& ComputeRegisteredPropertyValue(
CSSValueList* new_list = CSSValueList::CreateWithSeparatorFrom(old_list);
for (const CSSValue* inner_value : old_list) {
new_list->Append(ComputeRegisteredPropertyValue(
- css_to_length_conversion_data, *inner_value));
+ document, css_to_length_conversion_data, *inner_value));
}
return *new_list;
}
@@ -1701,20 +1679,63 @@ static const CSSValue& ComputeRegisteredPropertyValue(
css_to_length_conversion_data.CopyWithAdjustedZoom(1));
return *CSSPrimitiveValue::Create(length, 1);
}
+ // If we encounter a calculated number that was not resolved during
+ // parsing, it means that a calc()-expression was allowed in place of
+ // an integer. Such calc()-for-integers must be rounded at computed value
+ // time.
+ // https://drafts.csswg.org/css-values-4/#calc-type-checking
+ if (primitive_value.IsCalculated() &&
+ (primitive_value.TypeWithCalcResolved() ==
+ CSSPrimitiveValue::UnitType::kNumber)) {
+ double double_value = primitive_value.CssCalcValue()->DoubleValue();
+ auto unit_type = CSSPrimitiveValue::UnitType::kInteger;
+ return *CSSPrimitiveValue::Create(std::round(double_value), unit_type);
+ }
+
+ if (primitive_value.IsAngle()) {
+ return *CSSPrimitiveValue::Create(primitive_value.ComputeDegrees(),
+ CSSPrimitiveValue::UnitType::kDegrees);
+ }
+
+ if (primitive_value.IsTime()) {
+ return *CSSPrimitiveValue::Create(primitive_value.ComputeSeconds(),
+ CSSPrimitiveValue::UnitType::kSeconds);
+ }
+
+ if (primitive_value.IsResolution()) {
+ return *CSSPrimitiveValue::Create(
+ primitive_value.ComputeDotsPerPixel(),
+ CSSPrimitiveValue::UnitType::kDotsPerPixel);
+ }
}
+
+ if (value.IsIdentifierValue()) {
+ const CSSIdentifierValue& identifier_value = ToCSSIdentifierValue(value);
+ CSSValueID value_id = identifier_value.GetValueID();
+ if (value_id == CSSValueCurrentcolor)
+ return value;
+ if (StyleColor::IsColorKeyword(value_id)) {
+ Color color =
+ document.GetTextLinkColors().ColorFromCSSValue(value, Color(), false);
+ return *CSSColorValue::Create(color.Rgb());
+ }
+ }
+
return value;
}
const CSSValue& StyleBuilderConverter::ConvertRegisteredPropertyInitialValue(
+ const Document& document,
const CSSValue& value) {
- return ComputeRegisteredPropertyValue(CSSToLengthConversionData(), value);
+ return ComputeRegisteredPropertyValue(document, CSSToLengthConversionData(),
+ value);
}
const CSSValue& StyleBuilderConverter::ConvertRegisteredPropertyValue(
const StyleResolverState& state,
const CSSValue& value) {
- return ComputeRegisteredPropertyValue(state.CssToLengthConversionData(),
- value);
+ return ComputeRegisteredPropertyValue(
+ state.GetDocument(), state.CssToLengthConversionData(), value);
}
const CSSToLengthConversionData&
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.h b/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.h
index 90e63408249..933d95edeea 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.h
@@ -45,8 +45,8 @@
#include "third_party/blink/renderer/core/style/svg_computed_style_defs.h"
#include "third_party/blink/renderer/core/style/transform_origin.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
#include "third_party/blink/renderer/platform/graphics/image_orientation.h"
-#include "third_party/blink/renderer/platform/length_size.h"
#include "third_party/blink/renderer/platform/text/tab_size.h"
#include "third_party/blink/renderer/platform/transforms/rotation.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -167,6 +167,8 @@ class StyleBuilderConverter {
static TabSize ConvertLengthOrTabSpaces(StyleResolverState&, const CSSValue&);
static Length ConvertLineHeight(StyleResolverState&, const CSSValue&);
static float ConvertNumberOrPercentage(StyleResolverState&, const CSSValue&);
+ static float ConvertAlpha(StyleResolverState&,
+ const CSSValue&); // clamps to [0,1]
static StyleOffsetRotation ConvertOffsetRotate(StyleResolverState&,
const CSSValue&);
static LengthPoint ConvertPosition(StyleResolverState&, const CSSValue&);
@@ -181,8 +183,6 @@ class StyleBuilderConverter {
static ShadowData ConvertShadow(const CSSToLengthConversionData&,
StyleResolverState*,
const CSSValue&);
- static double ConvertValueToNumber(const CSSFunctionValue*,
- const CSSPrimitiveValue*);
static scoped_refptr<ShadowList> ConvertShadowList(StyleResolverState&,
const CSSValue&);
static ShapeValue* ConvertShapeValue(StyleResolverState&, const CSSValue&);
@@ -254,7 +254,8 @@ class StyleBuilderConverter {
static Length ConvertPositionLength(StyleResolverState&, const CSSValue&);
static Rotation ConvertRotation(const CSSValue&);
- static const CSSValue& ConvertRegisteredPropertyInitialValue(const CSSValue&);
+ static const CSSValue& ConvertRegisteredPropertyInitialValue(const Document&,
+ const CSSValue&);
static const CSSValue& ConvertRegisteredPropertyValue(
const StyleResolverState&,
const CSSValue&);
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.cc
index a8ed17a4fe4..b492c41928e 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.cc
@@ -46,6 +46,7 @@
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_keyframe_rule.h"
#include "third_party/blink/renderer/core/css/css_keyframes_rule.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_reflect_value.h"
#include "third_party/blink/renderer/core/css/css_rule_list.h"
@@ -60,6 +61,7 @@
#include "third_party/blink/renderer/core/css/page_rule_collector.h"
#include "third_party/blink/renderer/core/css/part_names.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
#include "third_party/blink/renderer/core/css/resolver/animated_style_builder.h"
#include "third_party/blink/renderer/core/css/resolver/css_variable_animator.h"
#include "third_party/blink/renderer/core/css/resolver/css_variable_resolver.h"
@@ -74,7 +76,6 @@
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/css/style_rule_import.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/first_letter_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
@@ -91,6 +92,7 @@
#include "third_party/blink/renderer/core/media_type_names.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/style/style_inherited_variables.h"
+#include "third_party/blink/renderer/core/style/style_initial_data.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -114,9 +116,7 @@ void SetAnimationUpdateIfNeeded(StyleResolverState& state, Element& element) {
} // namespace
-using namespace HTMLNames;
-
-ComputedStyle* StyleResolver::style_not_yet_available_;
+using namespace html_names;
static CSSPropertyValueSet* LeftToRightDeclaration() {
DEFINE_STATIC_LOCAL(Persistent<MutableCSSPropertyValueSet>,
@@ -215,8 +215,12 @@ static void MatchCustomElementRules(const Element& element,
element.GetCustomElementDefinition()) {
if (definition->HasDefaultStyleSheets()) {
for (CSSStyleSheet* style : definition->DefaultStyleSheets()) {
- collector.CollectMatchingRules(MatchRequest(
- element.GetDocument().GetStyleEngine().RuleSetForSheet(*style)));
+ if (!style)
+ continue;
+ RuleSet* rule_set =
+ element.GetDocument().GetStyleEngine().RuleSetForSheet(*style);
+ if (rule_set)
+ collector.CollectMatchingRules(MatchRequest(rule_set));
}
}
}
@@ -238,12 +242,44 @@ static void MatchHostAndCustomElementRules(const Element& element,
collector.FinishAddingAuthorRulesForTreeScope();
}
+static void MatchSlottedRules(const Element&, ElementRuleCollector&);
+static void MatchSlottedRulesForUAHost(const Element& element,
+ ElementRuleCollector& collector) {
+ if (element.ShadowPseudoId() != "-webkit-input-placeholder")
+ return;
+
+ // We allow ::placeholder pseudo element after ::slotted(). Since we are
+ // matching such pseudo elements starting from inside the UA shadow DOM of
+ // the element having the placeholder, we need to match ::slotted rules from
+ // the scopes to which the placeholder's host element may be slotted.
+ //
+ // Example:
+ //
+ // <div id=host>
+ // <:shadow-root>
+ // <style>::slotted(input)::placeholder { color: green }</style>
+ // <slot />
+ // </:shadow-root>
+ // <input placeholder="PLACEHOLDER-TEXT">
+ // <:ua-shadow-root>
+ // ... <placeholder>PLACEHOLDER-TEXT</placeholder> ...
+ // </:ua-shadow-root>
+ // </input>
+ // </div>
+ //
+ // Here we need to match the ::slotted rule from the #host shadow tree where
+ // the input is slotted on the placeholder element.
+ DCHECK(element.OwnerShadowHost());
+ MatchSlottedRules(*element.OwnerShadowHost(), collector);
+}
+
// Matches `::slotted` selectors. It matches rules in the element's slot's
// scope. If that slot is itself slotted it will match rules in the slot's
// slot's scope and so on. The result is that it considers a chain of scopes
// descending from the element's own scope.
static void MatchSlottedRules(const Element& element,
ElementRuleCollector& collector) {
+ MatchSlottedRulesForUAHost(element, collector);
HTMLSlotElement* slot = element.AssignedSlot();
if (!slot)
return;
@@ -290,11 +326,11 @@ void StyleResolver::MatchPseudoPartRules(const Element& element,
if (!RuntimeEnabledFeatures::CSSPartPseudoElementEnabled())
return;
- const SpaceSplitString* part_names = element.PartNames();
- if (!part_names)
+ DOMTokenList* part = element.GetPart();
+ if (!part)
return;
- PartNames current_names(*part_names);
+ PartNames current_names(part->TokenSet());
// ::part selectors in the shadow host's scope and above can match this
// element.
@@ -416,7 +452,6 @@ void StyleResolver::MatchAuthorRules(const Element& element,
MatchAuthorRulesV0(element, collector);
return;
}
-
MatchHostAndCustomElementRules(element, collector);
ScopedStyleResolver* element_scope_resolver = ScopedResolverFor(element);
@@ -654,24 +689,6 @@ scoped_refptr<ComputedStyle> StyleResolver::StyleForElement(
DCHECK(GetDocument().GetFrame());
DCHECK(GetDocument().GetSettings());
- // Once an element has a layout object or non-layout style, we don't try to
- // destroy it, since that means it could be rendering already and we cannot
- // arbitrarily change its style during loading.
- if (!GetDocument().IsRenderingReady() && !element->GetLayoutObject() &&
- !element->NonLayoutObjectComputedStyle()) {
- if (!style_not_yet_available_) {
- auto style = ComputedStyle::Create();
- style->AddRef();
- style_not_yet_available_ = style.get();
- style_not_yet_available_->SetDisplay(EDisplay::kNone);
- style_not_yet_available_->GetFont().Update(
- GetDocument().GetStyleEngine().GetFontSelector());
- }
-
- GetDocument().SetHasNodesWithPlaceholderStyle();
- return style_not_yet_available_;
- }
-
GetDocument().GetStyleEngine().IncStyleForElementCount();
INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(), elements_styled,
1);
@@ -741,7 +758,7 @@ scoped_refptr<ComputedStyle> StyleResolver::StyleForElement(
matching_behavior != kMatchAllRulesExcludingSMIL);
// TODO(dominicc): Remove this counter when Issue 590014 is fixed.
- if (element->HasTagName(HTMLNames::summaryTag)) {
+ if (element->HasTagName(html_names::kSummaryTag)) {
MatchedPropertiesRange matched_range =
collector.MatchedResult().AuthorRules();
for (const auto& matched : matched_range) {
@@ -827,7 +844,7 @@ AnimatableValue* StyleResolver::CreateAnimatableValueSnapshot(
parent_style);
state.SetStyle(ComputedStyle::Clone(base_style));
if (value) {
- StyleBuilder::ApplyProperty(property.GetCSSProperty(), state, *value);
+ StyleBuilder::ApplyProperty(property.GetCSSPropertyName(), state, *value);
state.GetFontBuilder().CreateFont(
state.GetDocument().GetStyleEngine().GetFontSelector(),
state.StyleRef());
@@ -1008,6 +1025,12 @@ scoped_refptr<ComputedStyle> StyleResolver::InitialStyleForElement(
? EUserModify::kReadWrite
: EUserModify::kReadOnly);
document.SetupFontBuilder(*initial_style);
+
+ scoped_refptr<StyleInitialData> initial_data =
+ document.GetStyleEngine().MaybeCreateAndGetInitialData();
+ if (initial_data)
+ initial_style->SetInitialData(std::move(initial_data));
+
return initial_style;
}
@@ -1452,6 +1475,25 @@ void StyleResolver::ApplyAllProperty(
}
}
+template <CSSPropertyPriority priority>
+static inline void ApplyProperty(
+ const CSSPropertyValueSet::PropertyReference& reference,
+ StyleResolverState& state) {
+ static_assert(
+ priority != kResolveVariables,
+ "Application of custom properties must use specialized template");
+ DCHECK_NE(reference.Id(), CSSPropertyVariable);
+ StyleBuilder::ApplyProperty(reference.Property(), state, reference.Value());
+}
+
+template <>
+inline void ApplyProperty<kResolveVariables>(
+ const CSSPropertyValueSet::PropertyReference& reference,
+ StyleResolverState& state) {
+ CSSPropertyRef ref(reference.Name(), state.GetDocument());
+ StyleBuilder::ApplyProperty(ref.GetProperty(), state, reference.Value());
+}
+
template <CSSPropertyPriority priority,
StyleResolver::ShouldUpdateNeedsApplyPass shouldUpdateNeedsApplyPass>
void StyleResolver::ApplyProperties(
@@ -1504,7 +1546,7 @@ void StyleResolver::ApplyProperties(
if (!CSSPropertyPriorityData<priority>::PropertyHasPriority(property_id))
continue;
- StyleBuilder::ApplyProperty(current.Property(), state, current.Value());
+ ApplyProperty<priority>(current, state);
}
}
@@ -1929,8 +1971,8 @@ void StyleResolver::ComputeFont(ComputedStyle* style,
void StyleResolver::UpdateMediaType() {
if (LocalFrameView* view = GetDocument().View()) {
bool was_print = print_media_type_;
- print_media_type_ =
- DeprecatedEqualIgnoringCase(view->MediaType(), MediaTypeNames::print);
+ print_media_type_ = DeprecatedEqualIgnoringCase(view->MediaType(),
+ media_type_names::kPrint);
if (was_print != print_media_type_)
matched_properties_cache_.ClearViewportDependent();
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.h b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.h
index a84ffa57094..fe4ae0d29fc 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver.h
@@ -64,8 +64,10 @@ class CORE_EXPORT StyleResolver final
public:
static StyleResolver* Create(Document& document) {
- return new StyleResolver(document);
+ return MakeGarbageCollected<StyleResolver>(document);
}
+
+ explicit StyleResolver(Document&);
~StyleResolver();
void Dispose();
@@ -75,6 +77,8 @@ class CORE_EXPORT StyleResolver final
const ComputedStyle* layout_parent_style = nullptr,
RuleMatchingBehavior = kMatchAllRules);
+ static scoped_refptr<ComputedStyle> InitialStyleForElement(Document&);
+
static AnimatableValue* CreateAnimatableValueSnapshot(
Element&,
const ComputedStyle& base_style,
@@ -128,11 +132,6 @@ class CORE_EXPORT StyleResolver final
void SetResizedForViewportUnits();
void ClearResizedForViewportUnits();
- // Exposed for ComputedStyle::IsStyleAvailable().
- static ComputedStyle* StyleNotYetAvailable() {
- return style_not_yet_available_;
- }
-
void SetRuleUsageTracker(StyleRuleUsageTracker*);
void UpdateMediaType();
@@ -141,10 +140,6 @@ class CORE_EXPORT StyleResolver final
void Trace(blink::Visitor*);
private:
- explicit StyleResolver(Document&);
-
- static scoped_refptr<ComputedStyle> InitialStyleForElement(Document&);
-
// FIXME: This should probably go away, folded into FontBuilder.
void UpdateFont(StyleResolverState&);
@@ -282,8 +277,6 @@ class CORE_EXPORT StyleResolver final
Document& GetDocument() const { return *document_; }
bool WasViewportResized() const { return was_viewport_resized_; }
- static ComputedStyle* style_not_yet_available_;
-
MatchedPropertiesCache matched_properties_cache_;
Member<Document> document_;
SelectorFilter selector_filter_;
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.cc
index 27faa263a84..9f64fd7ffd7 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.cc
@@ -169,7 +169,8 @@ StyleResolverState::ParsedPropertiesForPendingSubstitutionCache(
HeapHashMap<CSSPropertyID, Member<const CSSValue>>* map =
parsed_properties_for_pending_substitution_cache_.at(&value);
if (!map) {
- map = new HeapHashMap<CSSPropertyID, Member<const CSSValue>>;
+ map = MakeGarbageCollected<
+ HeapHashMap<CSSPropertyID, Member<const CSSValue>>>();
parsed_properties_for_pending_substitution_cache_.Set(&value, map);
}
return *map;
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.h b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.h
index fc9664a418c..b50afc5490c 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.h
@@ -28,12 +28,12 @@
#include "third_party/blink/renderer/core/animation/css/css_animation_update.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_pending_substitution_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
#include "third_party/blink/renderer/core/css/resolver/css_to_style_map.h"
#include "third_party/blink/renderer/core/css/resolver/element_resolve_context.h"
#include "third_party/blink/renderer/core/css/resolver/element_style_resources.h"
#include "third_party/blink/renderer/core/css/resolver/font_builder.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/style/cached_ua_style.h"
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.cc b/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.cc
index 2957bc5bd55..c4cb3ec71a8 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.cc
@@ -66,7 +66,7 @@ bool HasViewportFitProperty(const CSSPropertyValueSet* property_set) {
ViewportStyleResolver::ViewportStyleResolver(Document& document)
: document_(document) {
DCHECK(document.GetFrame());
- initial_viewport_medium_ = new MediaQueryEvaluator(
+ initial_viewport_medium_ = MakeGarbageCollected<MediaQueryEvaluator>(
MediaValuesInitialViewport::Create(*document.GetFrame()));
}
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.h b/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.h
index 541f3b6a2fc..6b70c9c902b 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/viewport_style_resolver.h
@@ -31,10 +31,10 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_VIEWPORT_STYLE_RESOLVER_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/rule_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/page/viewport_description.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
@@ -48,9 +48,11 @@ class CORE_EXPORT ViewportStyleResolver
: public GarbageCollectedFinalized<ViewportStyleResolver> {
public:
static ViewportStyleResolver* Create(Document& document) {
- return new ViewportStyleResolver(document);
+ return MakeGarbageCollected<ViewportStyleResolver>(document);
}
+ explicit ViewportStyleResolver(Document&);
+
void InitialStyleChanged();
void InitialViewportChanged();
void SetNeedsCollectRules();
@@ -62,8 +64,6 @@ class CORE_EXPORT ViewportStyleResolver
void Trace(blink::Visitor*);
private:
- explicit ViewportStyleResolver(Document&);
-
void Reset();
void Resolve();
diff --git a/chromium/third_party/blink/renderer/core/css/rule_feature_set.cc b/chromium/third_party/blink/renderer/core/css/rule_feature_set.cc
index f9426163d7d..91ad65c8d0c 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_feature_set.cc
+++ b/chromium/third_party/blink/renderer/core/css/rule_feature_set.cc
@@ -167,8 +167,8 @@ bool SupportsInvalidation(CSSSelector::PseudoType type) {
case CSSSelector::kPseudoVideoPersistent:
case CSSSelector::kPseudoVideoPersistentAncestor:
return true;
- case CSSSelector::kPseudoMatches:
- case CSSSelector::kPseudoIS:
+ case CSSSelector::kPseudoIs:
+ case CSSSelector::kPseudoWhere:
case CSSSelector::kPseudoUnknown:
case CSSSelector::kPseudoLeftPage:
case CSSSelector::kPseudoRightPage:
@@ -415,10 +415,6 @@ void RuleFeatureSet::ExtractInvalidationSetFeaturesFromSimpleSelector(
case CSSSelector::kPseudoBlinkInternalElement:
features.invalidation_flags.SetInvalidateCustomPseudo(true);
return;
- case CSSSelector::kPseudoBefore:
- case CSSSelector::kPseudoAfter:
- features.has_before_or_after = true;
- return;
case CSSSelector::kPseudoSlotted:
features.invalidation_flags.SetInvalidatesSlotted(true);
return;
@@ -485,6 +481,7 @@ InvalidationSet* RuleFeatureSet::InvalidationSetForSimpleSelector(
case CSSSelector::kPseudoDefined:
case CSSSelector::kPseudoVideoPersistent:
case CSSSelector::kPseudoVideoPersistentAncestor:
+ case CSSSelector::kPseudoSpatialNavigationFocus:
return &EnsurePseudoInvalidationSet(selector.GetPseudoType(), type,
position);
case CSSSelector::kPseudoFirstOfType:
@@ -526,8 +523,6 @@ void RuleFeatureSet::UpdateInvalidationSets(const RuleData* rule_data) {
features.invalidation_flags.SetWholeSubtreeInvalid(true);
if (features.has_nth_pseudo)
AddFeaturesToInvalidationSet(EnsureNthInvalidationSet(), features);
- if (features.has_before_or_after)
- UpdateInvalidationSetsForContentAttribute(rule_data);
const CSSSelector* next_compound = last_in_compound
? last_in_compound->TagHistory()
@@ -567,39 +562,6 @@ void RuleFeatureSet::UpdateRuleSetInvalidation(
type_rule_invalidation_set_->AddTagName(tag_name);
}
-void RuleFeatureSet::UpdateInvalidationSetsForContentAttribute(
- const RuleData* rule_data) {
- // If any ::before and ::after rules specify 'content: attr(...)', we
- // need to create invalidation sets for those attributes to have content
- // changes applied through style recalc.
-
- const CSSPropertyValueSet& property_set = rule_data->Rule()->Properties();
-
- int property_index = property_set.FindPropertyIndex(CSSPropertyContent);
-
- if (property_index == -1)
- return;
-
- CSSPropertyValueSet::PropertyReference content_property =
- property_set.PropertyAt(property_index);
- const CSSValue& content_value = content_property.Value();
-
- if (!content_value.IsValueList())
- return;
-
- for (auto& item : ToCSSValueList(content_value)) {
- if (!item->IsFunctionValue())
- continue;
- const CSSFunctionValue* function_value = ToCSSFunctionValue(item.Get());
- if (function_value->FunctionType() != CSSValueAttr)
- continue;
- EnsureAttributeInvalidationSet(
- AtomicString(ToCSSCustomIdentValue(function_value->Item(0)).Value()),
- kInvalidateDescendants, kSubject)
- .SetInvalidatesSelf();
- }
-}
-
RuleFeatureSet::FeatureInvalidationType
RuleFeatureSet::ExtractInvalidationSetFeaturesFromSelectorList(
const CSSSelector& simple_selector,
@@ -1260,7 +1222,6 @@ void RuleFeatureSet::InvalidationSetFeatures::Add(
max_direct_adjacent_selectors = std::max(max_direct_adjacent_selectors,
other.max_direct_adjacent_selectors);
invalidation_flags.Merge(other.invalidation_flags);
- has_before_or_after |= other.has_before_or_after;
content_pseudo_crossing |= other.content_pseudo_crossing;
has_nth_pseudo |= other.has_nth_pseudo;
}
diff --git a/chromium/third_party/blink/renderer/core/css/rule_feature_set.h b/chromium/third_party/blink/renderer/core/css/rule_feature_set.h
index 9e4ecbc3b60..b81bfba81b2 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_feature_set.h
+++ b/chromium/third_party/blink/renderer/core/css/rule_feature_set.h
@@ -194,7 +194,6 @@ class CORE_EXPORT RuleFeatureSet {
DescendantInvalidationSet& EnsurePartInvalidationSet();
void UpdateInvalidationSets(const RuleData*);
- void UpdateInvalidationSetsForContentAttribute(const RuleData*);
struct InvalidationSetFeatures {
DISALLOW_NEW();
@@ -209,7 +208,6 @@ class CORE_EXPORT RuleFeatureSet {
Vector<AtomicString> tag_names;
unsigned max_direct_adjacent_selectors = 0;
InvalidationFlags invalidation_flags;
- bool has_before_or_after = false;
bool content_pseudo_crossing = false;
bool has_nth_pseudo = false;
bool has_features_for_rule_set_invalidation = false;
diff --git a/chromium/third_party/blink/renderer/core/css/rule_feature_set_test.cc b/chromium/third_party/blink/renderer/core/css/rule_feature_set_test.cc
index b3e32f3142e..b70ba8a458f 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_feature_set_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/rule_feature_set_test.cc
@@ -51,8 +51,9 @@ class RuleFeatureSetTest : public testing::Test {
RuleFeatureSet::SelectorPreMatch result =
RuleFeatureSet::SelectorPreMatch::kSelectorNeverMatches;
for (unsigned i = 0; i < indices.size(); ++i) {
- RuleData* rule_data =
- new RuleData(style_rule, indices[i], 0, kRuleHasNoSpecialState);
+ RuleData* rule_data = RuleData::MaybeCreate(style_rule, indices[i], 0,
+ kRuleHasNoSpecialState);
+ DCHECK(rule_data);
if (rule_feature_set_.CollectFeaturesFromRuleData(rule_data))
result = RuleFeatureSet::SelectorPreMatch::kSelectorMayMatch;
}
@@ -986,9 +987,9 @@ TEST_F(RuleFeatureSetTest, ReplaceSelfInvalidationSet) {
ExpectNotSelfInvalidationSet(invalidation_lists.descendants);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesSibling) {
+TEST_F(RuleFeatureSetTest, pseudoIsSibling) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(":matches(.q, .r) ~ .s .t"));
+ CollectFeatures(":is(.q, .r) ~ .s .t"));
{
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "q");
@@ -1005,9 +1006,8 @@ TEST_F(RuleFeatureSetTest, pseudoMatchesSibling) {
}
}
-TEST_F(RuleFeatureSetTest, pseudoMatches) {
- EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(":matches(.w, .x)"));
+TEST_F(RuleFeatureSetTest, pseudoIs) {
+ EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch, CollectFeatures(":is(.w, .x)"));
{
InvalidationLists invalidation_lists;
@@ -1023,27 +1023,27 @@ TEST_F(RuleFeatureSetTest, pseudoMatches) {
}
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesIdDescendant) {
+TEST_F(RuleFeatureSetTest, pseudoIsIdDescendant) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :matches(#b, #c)"));
+ CollectFeatures(".a :is(#b, #c)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
ExpectIdInvalidation("b", "c", invalidation_lists.descendants);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesTagDescendant) {
+TEST_F(RuleFeatureSetTest, pseudoIsTagDescendant) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :matches(span, div)"));
+ CollectFeatures(".a :is(span, div)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
ExpectTagNameInvalidation("span", "div", invalidation_lists.descendants);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesAnySibling) {
+TEST_F(RuleFeatureSetTest, pseudoIsAnySibling) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".v ~ :matches(.w, .x)"));
+ CollectFeatures(".v ~ :is(.w, .x)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "v");
@@ -1051,9 +1051,9 @@ TEST_F(RuleFeatureSetTest, pseudoMatchesAnySibling) {
ExpectClassInvalidation("w", "x", invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesDescendantSibling) {
+TEST_F(RuleFeatureSetTest, pseudoIsDescendantSibling) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".u .v ~ :matches(.w, .x)"));
+ CollectFeatures(".u .v ~ :is(.w, .x)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "u");
@@ -1061,9 +1061,9 @@ TEST_F(RuleFeatureSetTest, pseudoMatchesDescendantSibling) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesWithComplexSelectors) {
+TEST_F(RuleFeatureSetTest, pseudoIsWithComplexSelectors) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :matches(.w+.b, .x>#c)"));
+ CollectFeatures(".a :is(.w+.b, .x>#c)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
@@ -1072,9 +1072,9 @@ TEST_F(RuleFeatureSetTest, pseudoMatchesWithComplexSelectors) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesNested) {
+TEST_F(RuleFeatureSetTest, pseudoIsNested) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :matches(.w+.b, .e+:matches(.c, #d))"));
+ CollectFeatures(".a :is(.w+.b, .e+:is(.c, #d))"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
@@ -1083,16 +1083,16 @@ TEST_F(RuleFeatureSetTest, pseudoMatchesNested) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoMatchesTooLarge) {
+TEST_F(RuleFeatureSetTest, pseudoIsTooLarge) {
// RuleData cannot support selectors at index 8192 or beyond so the expansion
// is limited to this size
EXPECT_EQ(RuleFeatureSet::kSelectorNeverMatches,
- CollectFeatures(":matches(.a#a, .b#b, .c#c, .d#d) + "
- ":matches(.e#e, .f#f, .g#g, .h#h) + "
- ":matches(.i#i, .j#j, .k#k, .l#l) + "
- ":matches(.m#m, .n#n, .o#o, .p#p) + "
- ":matches(.q#q, .r#r, .s#s, .t#t) + "
- ":matches(.u#u, .v#v, .w#w, .x#x)"));
+ CollectFeatures(":is(.a#a, .b#b, .c#c, .d#d) + "
+ ":is(.e#e, .f#f, .g#g, .h#h) + "
+ ":is(.i#i, .j#j, .k#k, .l#l) + "
+ ":is(.m#m, .n#n, .o#o, .p#p) + "
+ ":is(.q#q, .r#r, .s#s, .t#t) + "
+ ":is(.u#u, .v#v, .w#w, .x#x)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
@@ -1100,8 +1100,9 @@ TEST_F(RuleFeatureSetTest, pseudoMatchesTooLarge) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoIS) {
- EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch, CollectFeatures(":is(.w, .x)"));
+TEST_F(RuleFeatureSetTest, pseudoWhere) {
+ EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
+ CollectFeatures(":where(.w, .x)"));
{
InvalidationLists invalidation_lists;
@@ -1117,9 +1118,9 @@ TEST_F(RuleFeatureSetTest, pseudoIS) {
}
}
-TEST_F(RuleFeatureSetTest, pseudoISSibling) {
+TEST_F(RuleFeatureSetTest, pseudoWhereSibling) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(":is(.q, .r) ~ .s .t"));
+ CollectFeatures(":where(.q, .r) ~ .s .t"));
{
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "q");
@@ -1136,27 +1137,27 @@ TEST_F(RuleFeatureSetTest, pseudoISSibling) {
}
}
-TEST_F(RuleFeatureSetTest, pseudoISIdDescendant) {
+TEST_F(RuleFeatureSetTest, pseudoWhereIdDescendant) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :is(#b, #c)"));
+ CollectFeatures(".a :where(#b, #c)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
ExpectIdInvalidation("b", "c", invalidation_lists.descendants);
}
-TEST_F(RuleFeatureSetTest, pseudoISTagDescendant) {
+TEST_F(RuleFeatureSetTest, pseudoWhereTagDescendant) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :is(span, div)"));
+ CollectFeatures(".a :where(span, div)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
ExpectTagNameInvalidation("span", "div", invalidation_lists.descendants);
}
-TEST_F(RuleFeatureSetTest, pseudoISAnySibling) {
+TEST_F(RuleFeatureSetTest, pseudoWhereAnySibling) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".v ~ :is(.w, .x)"));
+ CollectFeatures(".v ~ :where(.w, .x)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "v");
@@ -1164,9 +1165,9 @@ TEST_F(RuleFeatureSetTest, pseudoISAnySibling) {
ExpectClassInvalidation("w", "x", invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoISDescendantSibling) {
+TEST_F(RuleFeatureSetTest, pseudoWhereDescendantSibling) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".u .v ~ :is(.w, .x)"));
+ CollectFeatures(".u .v ~ :where(.w, .x)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "u");
@@ -1174,9 +1175,9 @@ TEST_F(RuleFeatureSetTest, pseudoISDescendantSibling) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoISWithComplexSelectors) {
+TEST_F(RuleFeatureSetTest, pseudoWhereWithComplexSelectors) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :is(.w+.b, .x>#c)"));
+ CollectFeatures(".a :where(.w+.b, .x>#c)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
@@ -1185,9 +1186,9 @@ TEST_F(RuleFeatureSetTest, pseudoISWithComplexSelectors) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoISNested) {
+TEST_F(RuleFeatureSetTest, pseudoWhereNested) {
EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch,
- CollectFeatures(".a :is(.w+.b, .e+:is(.c, #d))"));
+ CollectFeatures(".a :where(.w+.b, .e+:where(.c, #d))"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
@@ -1196,16 +1197,16 @@ TEST_F(RuleFeatureSetTest, pseudoISNested) {
ExpectNoInvalidation(invalidation_lists.siblings);
}
-TEST_F(RuleFeatureSetTest, pseudoISTooLarge) {
+TEST_F(RuleFeatureSetTest, pseudoWhereTooLarge) {
// RuleData cannot support selectors at index 8192 or beyond so the expansion
// is limited to this size
EXPECT_EQ(RuleFeatureSet::kSelectorNeverMatches,
- CollectFeatures(":is(.a#a, .b#b, .c#c, .d#d) + "
- ":is(.e#e, .f#f, .g#g, .h#h) + "
- ":is(.i#i, .j#j, .k#k, .l#l) + "
- ":is(.m#m, .n#n, .o#o, .p#p) + "
- ":is(.q#q, .r#r, .s#s, .t#t) + "
- ":is(.u#u, .v#v, .w#w, .x#x)"));
+ CollectFeatures(":where(.a#a, .b#b, .c#c, .d#d) + "
+ ":where(.e#e, .f#f, .g#g, .h#h) + "
+ ":where(.i#i, .j#j, .k#k, .l#l) + "
+ ":where(.m#m, .n#n, .o#o, .p#p) + "
+ ":where(.q#q, .r#r, .s#s, .t#t) + "
+ ":where(.u#u, .v#v, .w#w, .x#x)"));
InvalidationLists invalidation_lists;
CollectInvalidationSetsForClass(invalidation_lists, "a");
diff --git a/chromium/third_party/blink/renderer/core/css/rule_set.cc b/chromium/third_party/blink/renderer/core/css/rule_set.cc
index 0233c8ab397..5dd78121577 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_set.cc
+++ b/chromium/third_party/blink/renderer/core/css/rule_set.cc
@@ -38,7 +38,6 @@
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/html/track/text_track_cue.h"
#include "third_party/blink/renderer/core/html_names.h"
-#include "third_party/blink/renderer/platform/heap/heap_terminated_array_builder.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
@@ -46,8 +45,6 @@
namespace blink {
-using namespace HTMLNames;
-
static inline PropertyWhitelistType DeterminePropertyWhitelistType(
const AddRuleFlags add_rule_flags,
const CSSSelector& selector) {
@@ -63,6 +60,20 @@ static inline PropertyWhitelistType DeterminePropertyWhitelistType(
return kPropertyWhitelistNone;
}
+RuleData* RuleData::MaybeCreate(StyleRule* rule,
+ unsigned selector_index,
+ unsigned position,
+ AddRuleFlags add_rule_flags) {
+ // The selector index field in RuleData is only 13 bits so we can't support
+ // selectors at index 8192 or beyond.
+ // See https://crbug.com/804179
+ if (selector_index >= (1 << RuleData::kSelectorIndexBits))
+ return nullptr;
+ if (position >= (1 << RuleData::kPositionBits))
+ return nullptr;
+ return new RuleData(rule, selector_index, position, add_rule_flags);
+}
+
RuleData::RuleData(StyleRule* rule,
unsigned selector_index,
unsigned position,
@@ -125,6 +136,7 @@ static void ExtractSelectorValues(const CSSSelector* selector,
case CSSSelector::kPseudoPart:
case CSSSelector::kPseudoHost:
case CSSSelector::kPseudoHostContext:
+ case CSSSelector::kPseudoSpatialNavigationFocus:
pseudo_type = selector->GetPseudoType();
break;
case CSSSelector::kPseudoWebKitCustomElement:
@@ -196,6 +208,9 @@ bool RuleSet::FindBestRuleSetAndAdd(const CSSSelector& component,
case CSSSelector::kPseudoWebkitAnyLink:
link_pseudo_class_rules_.push_back(rule_data);
return true;
+ case CSSSelector::kPseudoSpatialNavigationFocus:
+ spatial_navigation_focus_class_rules_.push_back(rule_data);
+ return true;
case CSSSelector::kPseudoFocus:
focus_pseudo_class_rules_.push_back(rule_data);
return true;
@@ -228,13 +243,13 @@ bool RuleSet::FindBestRuleSetAndAdd(const CSSSelector& component,
void RuleSet::AddRule(StyleRule* rule,
unsigned selector_index,
AddRuleFlags add_rule_flags) {
- // The selector index field in RuleData is only 13 bits so we can't support
- // selectors at index 8192 or beyond.
- // See https://crbug.com/804179
- if (selector_index >= 8192)
- return;
RuleData* rule_data =
- new RuleData(rule, selector_index, rule_count_++, add_rule_flags);
+ RuleData::MaybeCreate(rule, selector_index, rule_count_, add_rule_flags);
+ if (!rule_data) {
+ // This can happen if selector_index or position is out of range.
+ return;
+ }
+ ++rule_count_;
if (features_.CollectFeaturesFromRuleData(rule_data) ==
RuleFeatureSet::kSelectorNeverMatches)
return;
@@ -256,6 +271,11 @@ void RuleSet::AddFontFaceRule(StyleRuleFontFace* rule) {
font_face_rules_.push_back(rule);
}
+void RuleSet::AddFontFeatureValuesRule(StyleRuleFontFeatureValues* rule) {
+ EnsurePendingRules();
+ font_feature_values_rules_.push_back(rule);
+}
+
void RuleSet::AddKeyframesRule(StyleRuleKeyframes* rule) {
EnsurePendingRules(); // So that keyframes_rules_.ShrinkToFit() gets called.
keyframes_rules_.push_back(rule);
@@ -298,6 +318,8 @@ void RuleSet::AddChildRules(const HeapVector<Member<StyleRuleBase>>& rules,
AddChildRules(media_rule->ChildRules(), medium, add_rule_flags);
} else if (rule->IsFontFaceRule()) {
AddFontFaceRule(ToStyleRuleFontFace(rule));
+ } else if (rule->IsFontFeatureValuesRule()) {
+ AddFontFeatureValuesRule(ToStyleRuleFontFeatureValues(rule));
} else if (rule->IsKeyframesRule()) {
AddKeyframesRule(ToStyleRuleKeyframes(rule));
} else if (rule->IsSupportsRule() &&
@@ -347,7 +369,7 @@ void RuleSet::CompactPendingRules(PendingRuleMap& pending_map,
Member<HeapVector<Member<const RuleData>>>& rules =
compact_map.insert(item.key, nullptr).stored_value->value;
if (!rules) {
- rules = new HeapVector<Member<const RuleData>>();
+ rules = MakeGarbageCollected<HeapVector<Member<const RuleData>>>();
rules->ReserveInitialCapacity(pending_rules->size());
} else {
rules->ReserveCapacity(pending_rules->size());
@@ -370,10 +392,12 @@ void RuleSet::CompactRules() {
link_pseudo_class_rules_.ShrinkToFit();
cue_pseudo_rules_.ShrinkToFit();
focus_pseudo_class_rules_.ShrinkToFit();
+ spatial_navigation_focus_class_rules_.ShrinkToFit();
universal_rules_.ShrinkToFit();
shadow_host_rules_.ShrinkToFit();
page_rules_.ShrinkToFit();
font_face_rules_.ShrinkToFit();
+ font_feature_values_rules_.ShrinkToFit();
keyframes_rules_.ShrinkToFit();
deep_combinator_or_shadow_pseudo_rules_.ShrinkToFit();
part_pseudo_rules_.ShrinkToFit();
@@ -404,10 +428,12 @@ void RuleSet::Trace(blink::Visitor* visitor) {
visitor->Trace(link_pseudo_class_rules_);
visitor->Trace(cue_pseudo_rules_);
visitor->Trace(focus_pseudo_class_rules_);
+ visitor->Trace(spatial_navigation_focus_class_rules_);
visitor->Trace(universal_rules_);
visitor->Trace(shadow_host_rules_);
visitor->Trace(page_rules_);
visitor->Trace(font_face_rules_);
+ visitor->Trace(font_feature_values_rules_);
visitor->Trace(keyframes_rules_);
visitor->Trace(deep_combinator_or_shadow_pseudo_rules_);
visitor->Trace(part_pseudo_rules_);
diff --git a/chromium/third_party/blink/renderer/core/css/rule_set.h b/chromium/third_party/blink/renderer/core/css/rule_set.h
index 44d4da9d233..6f57a02f8b5 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_set.h
+++ b/chromium/third_party/blink/renderer/core/css/rule_set.h
@@ -79,10 +79,10 @@ namespace blink {
// and makes it accessible cheaply.
class CORE_EXPORT RuleData : public GarbageCollected<RuleData> {
public:
- RuleData(StyleRule*,
- unsigned selector_index,
- unsigned position,
- AddRuleFlags);
+ static RuleData* MaybeCreate(StyleRule*,
+ unsigned selector_index,
+ unsigned position,
+ AddRuleFlags);
unsigned GetPosition() const { return position_; }
StyleRule* Rule() const { return rule_; }
@@ -114,16 +114,25 @@ class CORE_EXPORT RuleData : public GarbageCollected<RuleData> {
void Trace(blink::Visitor*);
- private:
- Member<StyleRule> rule_;
// This number is picked fairly arbitrary. If lowered, be aware that there
// might be sites and extensions using style rules with selector lists
// exceeding the number of simple selectors to fit in this bitfield.
// See https://crbug.com/312913 and https://crbug.com/704562
- unsigned selector_index_ : 13;
+ static constexpr size_t kSelectorIndexBits = 13;
+
// This number was picked fairly arbitrarily. We can probably lower it if we
// need to. Some simple testing showed <100,000 RuleData's on large sites.
- unsigned position_ : 18;
+ static constexpr size_t kPositionBits = 18;
+
+ private:
+ RuleData(StyleRule*,
+ unsigned selector_index,
+ unsigned position,
+ AddRuleFlags);
+
+ Member<StyleRule> rule_;
+ unsigned selector_index_ : kSelectorIndexBits;
+ unsigned position_ : kPositionBits;
unsigned contains_uncommon_attribute_selector_ : 1;
// 32 bits above
unsigned specificity_ : 24;
@@ -161,7 +170,9 @@ static_assert(sizeof(RuleData) == sizeof(SameSizeAsRuleData),
// ElementRuleCollector::CollectMatchingRules.
class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
public:
- static RuleSet* Create() { return new RuleSet; }
+ static RuleSet* Create() { return MakeGarbageCollected<RuleSet>(); }
+
+ RuleSet() : rule_count_(0) {}
void AddRulesFromSheet(StyleSheetContents*,
const MediaQueryEvaluator&,
@@ -203,6 +214,11 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
DCHECK(!pending_rules_);
return &focus_pseudo_class_rules_;
}
+ const HeapVector<Member<const RuleData>>*
+ SpatialNavigationFocusPseudoClassRules() const {
+ DCHECK(!pending_rules_);
+ return &spatial_navigation_focus_class_rules_;
+ }
const HeapVector<Member<const RuleData>>* UniversalRules() const {
DCHECK(!pending_rules_);
return &universal_rules_;
@@ -222,6 +238,10 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
const HeapVector<Member<StyleRuleFontFace>>& FontFaceRules() const {
return font_face_rules_;
}
+ const HeapVector<Member<StyleRuleFontFeatureValues>>& FontFeatureValuesRules()
+ const {
+ return font_feature_values_rules_;
+ }
const HeapVector<Member<StyleRuleKeyframes>>& KeyframesRules() const {
return keyframes_rules_;
}
@@ -270,12 +290,11 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
using CompactRuleMap =
HeapHashMap<AtomicString, Member<HeapVector<Member<const RuleData>>>>;
- RuleSet() : rule_count_(0) {}
-
void AddToRuleSet(const AtomicString& key, PendingRuleMap&, const RuleData*);
void AddPageRule(StyleRulePage*);
void AddViewportRule(StyleRuleViewport*);
void AddFontFaceRule(StyleRuleFontFace*);
+ void AddFontFeatureValuesRule(StyleRuleFontFeatureValues*);
void AddKeyframesRule(StyleRuleKeyframes*);
void AddChildRules(const HeapVector<Member<StyleRuleBase>>&,
@@ -288,7 +307,11 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
class PendingRuleMaps : public GarbageCollected<PendingRuleMaps> {
public:
- static PendingRuleMaps* Create() { return new PendingRuleMaps; }
+ static PendingRuleMaps* Create() {
+ return MakeGarbageCollected<PendingRuleMaps>();
+ }
+
+ PendingRuleMaps() = default;
PendingRuleMap id_rules;
PendingRuleMap class_rules;
@@ -296,9 +319,6 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
PendingRuleMap shadow_pseudo_element_rules;
void Trace(blink::Visitor*);
-
- private:
- PendingRuleMaps() = default;
};
PendingRuleMaps* EnsurePendingRules() {
@@ -314,12 +334,14 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
HeapVector<Member<const RuleData>> link_pseudo_class_rules_;
HeapVector<Member<const RuleData>> cue_pseudo_rules_;
HeapVector<Member<const RuleData>> focus_pseudo_class_rules_;
+ HeapVector<Member<const RuleData>> spatial_navigation_focus_class_rules_;
HeapVector<Member<const RuleData>> universal_rules_;
HeapVector<Member<const RuleData>> shadow_host_rules_;
HeapVector<Member<const RuleData>> part_pseudo_rules_;
RuleFeatureSet features_;
HeapVector<Member<StyleRulePage>> page_rules_;
HeapVector<Member<StyleRuleFontFace>> font_face_rules_;
+ HeapVector<Member<StyleRuleFontFeatureValues>> font_feature_values_rules_;
HeapVector<Member<StyleRuleKeyframes>> keyframes_rules_;
HeapVector<MinimalRuleData> deep_combinator_or_shadow_pseudo_rules_;
HeapVector<MinimalRuleData> content_pseudo_element_rules_;
diff --git a/chromium/third_party/blink/renderer/core/css/rule_set_test.cc b/chromium/third_party/blink/renderer/core/css/rule_set_test.cc
index 720857871ee..8eaaf158b90 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_set_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/rule_set_test.cc
@@ -30,16 +30,31 @@
#include "third_party/blink/renderer/core/css/rule_set.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
+using namespace css_test_helpers;
+
+namespace {
+
+StyleRule* CreateDummyStyleRule() {
+ TestStyleSheet sheet;
+ sheet.AddCSSRules("#id { color: tomato; }");
+ const RuleSet& rule_set = sheet.GetRuleSet();
+ const HeapVector<Member<const RuleData>>* rules = rule_set.IdRules("id");
+ DCHECK_EQ(1u, rules->size());
+ return rules->at(0)->Rule();
+}
+
+} // namespace
+
TEST(RuleSetTest, findBestRuleSetAndAdd_CustomPseudoElements) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("summary::-webkit-details-marker { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("summary::-webkit-details-marker { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("-webkit-details-marker");
const HeapVector<Member<const RuleData>>* rules =
rule_set.ShadowPseudoElementRules(str);
@@ -48,10 +63,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_CustomPseudoElements) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_Id) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("#id { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("#id { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("id");
const HeapVector<Member<const RuleData>>* rules = rule_set.IdRules(str);
ASSERT_EQ(1u, rules->size());
@@ -59,10 +74,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_Id) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_NthChild) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("div:nth-child(2) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("div:nth-child(2) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("div");
const HeapVector<Member<const RuleData>>* rules = rule_set.TagRules(str);
ASSERT_EQ(1u, rules->size());
@@ -70,10 +85,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_NthChild) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_ClassThenId) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(".class#id { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(".class#id { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("id");
// id is prefered over class even if class preceeds it in the selector.
const HeapVector<Member<const RuleData>>* rules = rule_set.IdRules(str);
@@ -83,10 +98,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_ClassThenId) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_IdThenClass) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("#id.class { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("#id.class { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("id");
const HeapVector<Member<const RuleData>>* rules = rule_set.IdRules(str);
ASSERT_EQ(1u, rules->size());
@@ -94,10 +109,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_IdThenClass) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_AttrThenId) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("[attr]#id { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("[attr]#id { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("id");
const HeapVector<Member<const RuleData>>* rules = rule_set.IdRules(str);
ASSERT_EQ(1u, rules->size());
@@ -106,10 +121,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_AttrThenId) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_TagThenAttrThenId) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("div[attr]#id { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("div[attr]#id { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("id");
const HeapVector<Member<const RuleData>>* rules = rule_set.IdRules(str);
ASSERT_EQ(1u, rules->size());
@@ -118,10 +133,10 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_TagThenAttrThenId) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_DivWithContent) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("div::content { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("div::content { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
AtomicString str("div");
const HeapVector<Member<const RuleData>>* rules = rule_set.TagRules(str);
ASSERT_EQ(1u, rules->size());
@@ -130,46 +145,46 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_DivWithContent) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_Host) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(":host { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(":host { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.ShadowHostRules();
ASSERT_EQ(1u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_HostWithId) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(":host(#x) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(":host(#x) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.ShadowHostRules();
ASSERT_EQ(1u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_HostContext) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(":host-context(*) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(":host-context(*) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.ShadowHostRules();
ASSERT_EQ(1u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_HostContextWithId) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(":host-context(#x) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(":host-context(#x) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.ShadowHostRules();
ASSERT_EQ(1u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_HostAndHostContextNotInRightmost) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(":host-context(#x) .y, :host(.a) > #b { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(":host-context(#x) .y, :host(.a) > #b { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* shadow_rules =
rule_set.ShadowHostRules();
const HeapVector<Member<const RuleData>>* id_rules = rule_set.IdRules("b");
@@ -181,74 +196,74 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_HostAndHostContextNotInRightmost) {
}
TEST(RuleSetTest, findBestRuleSetAndAdd_HostAndClass) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(".foo:host { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(".foo:host { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.ShadowHostRules();
ASSERT_EQ(0u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_HostContextAndClass) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(".foo:host-context(*) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(".foo:host-context(*) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.ShadowHostRules();
ASSERT_EQ(0u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_Focus) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(":focus { }");
- helper.AddCSSRules("[attr]:focus { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(":focus { }");
+ sheet.AddCSSRules("[attr]:focus { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules =
rule_set.FocusPseudoClassRules();
ASSERT_EQ(2u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_LinkVisited) {
- CSSTestHelper helper;
-
- helper.AddCSSRules(":link { }");
- helper.AddCSSRules("[attr]:link { }");
- helper.AddCSSRules(":visited { }");
- helper.AddCSSRules("[attr]:visited { }");
- helper.AddCSSRules(":-webkit-any-link { }");
- helper.AddCSSRules("[attr]:-webkit-any-link { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ TestStyleSheet sheet;
+
+ sheet.AddCSSRules(":link { }");
+ sheet.AddCSSRules("[attr]:link { }");
+ sheet.AddCSSRules(":visited { }");
+ sheet.AddCSSRules("[attr]:visited { }");
+ sheet.AddCSSRules(":-webkit-any-link { }");
+ sheet.AddCSSRules("[attr]:-webkit-any-link { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules =
rule_set.LinkPseudoClassRules();
ASSERT_EQ(6u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_Cue) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("::cue(b) { }");
- helper.AddCSSRules("video::cue(u) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("::cue(b) { }");
+ sheet.AddCSSRules("video::cue(u) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.CuePseudoRules();
ASSERT_EQ(2u, rules->size());
}
TEST(RuleSetTest, findBestRuleSetAndAdd_PlaceholderPseudo) {
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules("::placeholder { }");
- helper.AddCSSRules("input::placeholder { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules("::placeholder { }");
+ sheet.AddCSSRules("input::placeholder { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
auto* rules = rule_set.ShadowPseudoElementRules("-webkit-input-placeholder");
ASSERT_EQ(2u, rules->size());
}
-TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoMatches) {
- CSSTestHelper helper;
+TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoIs) {
+ TestStyleSheet sheet;
- helper.AddCSSRules(".a :matches(.b+.c, .d>:matches(.e, .f)) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(".a :is(.b+.c, .d>:is(.e, .f)) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
{
AtomicString str("c");
const HeapVector<Member<const RuleData>>* rules = rule_set.ClassRules(str);
@@ -269,11 +284,11 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoMatches) {
}
}
-TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoIS) {
- CSSTestHelper helper;
+TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoWhere) {
+ TestStyleSheet sheet;
- helper.AddCSSRules(".a :is(.b+.c, .d>:is(.e, .f)) { }");
- RuleSet& rule_set = helper.GetRuleSet();
+ sheet.AddCSSRules(".a :where(.b+.c, .d>:where(.e, .f)) { }");
+ RuleSet& rule_set = sheet.GetRuleSet();
{
AtomicString str("c");
const HeapVector<Member<const RuleData>>* rules = rule_set.ClassRules(str);
@@ -294,40 +309,47 @@ TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoIS) {
}
}
-TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoMatchesTooLarge) {
+TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoIsTooLarge) {
// RuleData cannot support selectors at index 8192 or beyond so the expansion
// is limited to this size
- CSSTestHelper helper;
-
- helper.AddCSSRules(
- ":matches(.a#a, .b#b, .c#c, .d#d) + "
- ":matches(.e#e, .f#f, .g#g, .h#h) + "
- ":matches(.i#i, .j#j, .k#k, .l#l) + "
- ":matches(.m#m, .n#n, .o#o, .p#p) + "
- ":matches(.q#q, .r#r, .s#s, .t#t) + "
- ":matches(.u#u, .v#v, .w#w, .x#x) { }",
+ TestStyleSheet sheet;
+
+ sheet.AddCSSRules(
+ ":is(.a#a, .b#b, .c#c, .d#d) + "
+ ":is(.e#e, .f#f, .g#g, .h#h) + "
+ ":is(.i#i, .j#j, .k#k, .l#l) + "
+ ":is(.m#m, .n#n, .o#o, .p#p) + "
+ ":is(.q#q, .r#r, .s#s, .t#t) + "
+ ":is(.u#u, .v#v, .w#w, .x#x) { }",
true);
- RuleSet& rule_set = helper.GetRuleSet();
+ RuleSet& rule_set = sheet.GetRuleSet();
ASSERT_EQ(0u, rule_set.RuleCount());
}
-TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoISTooLarge) {
+TEST(RuleSetTest, findBestRuleSetAndAdd_PseudoWhereTooLarge) {
// RuleData cannot support selectors at index 8192 or beyond so the expansion
// is limited to this size
- CSSTestHelper helper;
+ TestStyleSheet sheet;
- helper.AddCSSRules(
- ":is(.a#a, .b#b, .c#c, .d#d) + :is(.e#e, .f#f, .g#g, .h#h) + "
- ":is(.i#i, .j#j, .k#k, .l#l) + :is(.m#m, .n#n, .o#o, .p#p) + "
- ":is(.q#q, .r#r, .s#s, .t#t) + :is(.u#u, .v#v, .w#w, .x#x) { }",
+ sheet.AddCSSRules(
+ ":where(.a#a, .b#b, .c#c, .d#d) + :where(.e#e, .f#f, .g#g, .h#h) + "
+ ":where(.i#i, .j#j, .k#k, .l#l) + :where(.m#m, .n#n, .o#o, .p#p) + "
+ ":where(.q#q, .r#r, .s#s, .t#t) + :where(.u#u, .v#v, .w#w, .x#x) { }",
true);
- RuleSet& rule_set = helper.GetRuleSet();
+ RuleSet& rule_set = sheet.GetRuleSet();
ASSERT_EQ(0u, rule_set.RuleCount());
}
TEST(RuleSetTest, SelectorIndexLimit) {
+ // It's not feasible to run this test for a large number of bits. If the
+ // number of bits have increased to a large number, consider removing this
+ // test and making do with RuleSetTest.RuleDataSelectorIndexLimit.
+ static_assert(
+ RuleData::kSelectorIndexBits == 13,
+ "Please manually consider whether this test should be removed.");
+
StringBuilder builder;
// We use 13 bits to storing the selector start index in RuleData. This is a
@@ -338,13 +360,51 @@ TEST(RuleSetTest, SelectorIndexLimit) {
builder.Append("b,span {}");
- CSSTestHelper helper;
- helper.AddCSSRules(builder.ToString().Ascii().data());
- const RuleSet& rule_set = helper.GetRuleSet();
+ TestStyleSheet sheet;
+ sheet.AddCSSRules(builder.ToString().Ascii().data());
+ const RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.TagRules("b");
ASSERT_EQ(1u, rules->size());
EXPECT_EQ("b", rules->at(0)->Selector().TagQName().LocalName());
EXPECT_FALSE(rule_set.TagRules("span"));
}
+TEST(RuleSetTest, RuleDataSelectorIndexLimit) {
+ StyleRule* rule = CreateDummyStyleRule();
+ AddRuleFlags flags = kRuleHasNoSpecialState;
+ const unsigned position = 0;
+ EXPECT_TRUE(RuleData::MaybeCreate(rule, 0, position, flags));
+ EXPECT_FALSE(RuleData::MaybeCreate(rule, (1 << RuleData::kSelectorIndexBits),
+ position, flags));
+ EXPECT_FALSE(RuleData::MaybeCreate(
+ rule, (1 << RuleData::kSelectorIndexBits) + 1, position, flags));
+}
+
+TEST(RuleSetTest, RuleDataPositionLimit) {
+ StyleRule* rule = CreateDummyStyleRule();
+ AddRuleFlags flags = kRuleHasNoSpecialState;
+ const unsigned selector_index = 0;
+ EXPECT_TRUE(RuleData::MaybeCreate(rule, selector_index, 0, flags));
+ EXPECT_FALSE(RuleData::MaybeCreate(rule, selector_index,
+ (1 << RuleData::kPositionBits), flags));
+ EXPECT_FALSE(RuleData::MaybeCreate(
+ rule, selector_index, (1 << RuleData::kPositionBits) + 1, flags));
+}
+
+TEST(RuleSetTest, RuleCountNotIncreasedByInvalidRuleData) {
+ RuleSet* rule_set = RuleSet::Create();
+ EXPECT_EQ(0u, rule_set->RuleCount());
+
+ AddRuleFlags flags = kRuleHasNoSpecialState;
+ StyleRule* rule = CreateDummyStyleRule();
+
+ // Add with valid selector_index=0.
+ rule_set->AddRule(rule, 0, flags);
+ EXPECT_EQ(1u, rule_set->RuleCount());
+
+ // Adding with invalid selector_index should not lead to a change in count.
+ rule_set->AddRule(rule, 1 << RuleData::kSelectorIndexBits, flags);
+ EXPECT_EQ(1u, rule_set->RuleCount());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/selector_checker.cc b/chromium/third_party/blink/renderer/core/css/selector_checker.cc
index 5e0b242e194..971c5659c92 100644
--- a/chromium/third_party/blink/renderer/core/css/selector_checker.cc
+++ b/chromium/third_party/blink/renderer/core/css/selector_checker.cc
@@ -58,6 +58,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
+#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
@@ -66,8 +67,6 @@
namespace blink {
-using namespace HTMLNames;
-
static bool IsFrameFocused(const Element& element) {
return element.GetDocument().GetFrame() && element.GetDocument()
.GetFrame()
@@ -75,12 +74,6 @@ static bool IsFrameFocused(const Element& element) {
.FrameIsFocusedAndActive();
}
-static bool MatchesSpatialNavigationFocusPseudoClass(const Element& element) {
- return IsHTMLOptionElement(element) &&
- ToHTMLOptionElement(element).SpatialNavigationFocused() &&
- IsFrameFocused(element);
-}
-
static bool MatchesListBoxPseudoClass(const Element& element) {
return IsHTMLSelectElement(element) &&
!ToHTMLSelectElement(element).UsesMenuList();
@@ -763,6 +756,7 @@ bool SelectorChecker::CheckPseudoClass(const SelectorCheckingContext& context,
return CheckPseudoNot(context, result);
case CSSSelector::kPseudoEmpty: {
bool result = true;
+ bool has_whitespace = false;
for (Node* n = element.firstChild(); n; n = n->nextSibling()) {
if (n->IsElementNode()) {
result = false;
@@ -771,11 +765,20 @@ bool SelectorChecker::CheckPseudoClass(const SelectorCheckingContext& context,
if (n->IsTextNode()) {
Text* text_node = ToText(n);
if (!text_node->data().IsEmpty()) {
- result = false;
- break;
+ if (text_node->ContainsOnlyWhitespaceOrEmpty()) {
+ has_whitespace = true;
+ } else {
+ result = false;
+ break;
+ }
}
}
}
+ if (result && has_whitespace) {
+ UseCounter::Count(context.element->GetDocument(),
+ WebFeature::kCSSSelectorEmptyWhitespaceOnlyFail);
+ result = false;
+ }
if (mode_ == kResolvingStyle)
element.SetStyleAffectedByEmpty();
return result;
@@ -1099,8 +1102,8 @@ bool SelectorChecker::CheckPseudoClass(const SelectorCheckingContext& context,
case CSSSelector::kPseudoCornerPresent:
return false;
case CSSSelector::kPseudoUnknown:
- case CSSSelector::kPseudoMatches:
- case CSSSelector::kPseudoIS:
+ case CSSSelector::kPseudoIs:
+ case CSSSelector::kPseudoWhere:
default:
NOTREACHED();
break;
@@ -1390,4 +1393,20 @@ bool SelectorChecker::MatchesFocusVisiblePseudoClass(const Element& element) {
always_show_focus_ring);
}
+// static
+bool SelectorChecker::MatchesSpatialNavigationFocusPseudoClass(
+ const Element& element) {
+ if (!IsSpatialNavigationEnabled(element.GetDocument().GetFrame()))
+ return false;
+ if (RuntimeEnabledFeatures::SpatialNavigationForcesOutlineEnabled()) {
+ // TODO(mthiesse): Decouple spatial navigation target from focus, so that
+ // if spat nav is enabled, but not used, we don't override focus ring
+ // behavior on that element.
+ return element.IsFocused() && IsFrameFocused(element);
+ }
+ return IsHTMLOptionElement(element) &&
+ ToHTMLOptionElement(element).SpatialNavigationFocused() &&
+ IsFrameFocused(element);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/selector_checker.h b/chromium/third_party/blink/renderer/core/css/selector_checker.h
index 014dd143ebf..c657a9ea06f 100644
--- a/chromium/third_party/blink/renderer/core/css/selector_checker.h
+++ b/chromium/third_party/blink/renderer/core/css/selector_checker.h
@@ -153,6 +153,7 @@ class SelectorChecker {
static bool MatchesFocusPseudoClass(const Element&);
static bool MatchesFocusVisiblePseudoClass(const Element&);
+ static bool MatchesSpatialNavigationFocusPseudoClass(const Element&);
private:
// Does the work of checking whether the simple selector and element pointed
diff --git a/chromium/third_party/blink/renderer/core/css/selector_query.cc b/chromium/third_party/blink/renderer/core/css/selector_query.cc
index fa10f0df333..642f0b61a1b 100644
--- a/chromium/third_party/blink/renderer/core/css/selector_query.cc
+++ b/chromium/third_party/blink/renderer/core/css/selector_query.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
#if DCHECK_IS_ON() || defined(RELEASE_QUERY_STATS)
static SelectorQuery::QueryStats& CurrentQueryStats() {
@@ -503,7 +503,7 @@ SelectorQuery::SelectorQuery(CSSSelectorList selector_list)
// We only use the fast path when in standards mode where #id selectors
// are case sensitive, so we need the same behavior for [id=value].
if (current->Match() == CSSSelector::kAttributeExact &&
- current->Attribute() == idAttr &&
+ current->Attribute() == kIdAttr &&
current->AttributeMatch() == CSSSelector::kCaseSensitive) {
selector_id_ = current->Value();
break;
diff --git a/chromium/third_party/blink/renderer/core/css/selector_query_test.cc b/chromium/third_party/blink/renderer/core/css/selector_query_test.cc
index 9ad67cb14c0..b677facb58f 100644
--- a/chromium/third_party/blink/renderer/core/css/selector_query_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/selector_query_test.cc
@@ -71,7 +71,7 @@ TEST(SelectorQueryTest, NotMatchingPseudoElement) {
CSSParserContext::Create(
*document, NullURL(),
false /* is_opaque_response_from_service_worker */,
- kReferrerPolicyDefault, WTF::TextEncoding(),
+ network::mojom::ReferrerPolicy::kDefault, WTF::TextEncoding(),
CSSParserContext::kSnapshotProfile),
nullptr, "span::before");
std::unique_ptr<SelectorQuery> query =
@@ -83,7 +83,7 @@ TEST(SelectorQueryTest, NotMatchingPseudoElement) {
CSSParserContext::Create(
*document, NullURL(),
false /* is_opaque_response_from_service_worker */,
- kReferrerPolicyDefault, WTF::TextEncoding(),
+ network::mojom::ReferrerPolicy::kDefault, WTF::TextEncoding(),
CSSParserContext::kSnapshotProfile),
nullptr, "span");
query = SelectorQuery::Adopt(std::move(selector_list));
@@ -104,7 +104,7 @@ TEST(SelectorQueryTest, LastOfTypeNotFinishedParsing) {
CSSParserContext::Create(
*document, NullURL(),
false /* is_opaque_response_from_service_worker */,
- kReferrerPolicyDefault, WTF::TextEncoding(),
+ network::mojom::ReferrerPolicy::kDefault, WTF::TextEncoding(),
CSSParserContext::kSnapshotProfile),
nullptr, "p:last-of-type");
std::unique_ptr<SelectorQuery> query =
@@ -330,7 +330,7 @@ TEST(SelectorQueryTest, QuirksModeSlowPath) {
TEST(SelectorQueryTest, DisconnectedSubtree) {
Document* document = HTMLDocument::CreateForTest();
- Element* scope = document->CreateRawElement(HTMLNames::divTag);
+ Element* scope = document->CreateRawElement(html_names::kDivTag);
scope->SetInnerHTMLFromString(R"HTML(
<section>
<span id=first>
@@ -357,7 +357,7 @@ TEST(SelectorQueryTest, DisconnectedSubtree) {
TEST(SelectorQueryTest, DisconnectedTreeScope) {
Document* document = HTMLDocument::CreateForTest();
- Element* host = document->CreateRawElement(HTMLNames::divTag);
+ Element* host = document->CreateRawElement(html_names::kDivTag);
ShadowRoot& shadowRoot =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
shadowRoot.SetInnerHTMLFromString(R"HTML(
diff --git a/chromium/third_party/blink/renderer/core/css/shadow_tree_style_sheet_collection.cc b/chromium/third_party/blink/renderer/core/css/shadow_tree_style_sheet_collection.cc
index 4c8a15752cc..8a8867ac811 100644
--- a/chromium/third_party/blink/renderer/core/css/shadow_tree_style_sheet_collection.cc
+++ b/chromium/third_party/blink/renderer/core/css/shadow_tree_style_sheet_collection.cc
@@ -40,8 +40,6 @@
namespace blink {
-using namespace HTMLNames;
-
ShadowTreeStyleSheetCollection::ShadowTreeStyleSheetCollection(
ShadowRoot& shadow_root)
: TreeScopeStyleSheetCollection(shadow_root) {}
diff --git a/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.cc b/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.cc
index d9050cb824f..58ff83ce080 100644
--- a/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.cc
@@ -68,21 +68,21 @@ StyleAttributeMutationScope::StyleAttributeMutationScope(
mutation_recipients_ =
MutationObserverInterestGroup::CreateForAttributesMutation(
- *current_decl_->ParentElement(), HTMLNames::styleAttr);
+ *current_decl_->ParentElement(), html_names::kStyleAttr);
bool should_read_old_value =
(mutation_recipients_ && mutation_recipients_->IsOldValueRequested()) ||
DefinitionIfStyleChangedCallback(current_decl_->ParentElement());
if (should_read_old_value) {
old_value_ =
- current_decl_->ParentElement()->getAttribute(HTMLNames::styleAttr);
+ current_decl_->ParentElement()->getAttribute(html_names::kStyleAttr);
}
if (mutation_recipients_) {
AtomicString requested_old_value =
mutation_recipients_->IsOldValueRequested() ? old_value_ : g_null_atom;
mutation_ = MutationRecord::CreateAttributes(current_decl_->ParentElement(),
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
requested_old_value);
}
}
@@ -101,8 +101,8 @@ StyleAttributeMutationScope::~StyleAttributeMutationScope() {
if (CustomElementDefinition* definition =
DefinitionIfStyleChangedCallback(element)) {
definition->EnqueueAttributeChangedCallback(
- element, HTMLNames::styleAttr, old_value_,
- element->getAttribute(HTMLNames::styleAttr));
+ element, html_names::kStyleAttr, old_value_,
+ element->getAttribute(html_names::kStyleAttr));
}
should_deliver_ = false;
diff --git a/chromium/third_party/blink/renderer/core/css/style_change_reason.cc b/chromium/third_party/blink/renderer/core/css/style_change_reason.cc
index a8ff0fa0fa8..7fed20e4839 100644
--- a/chromium/third_party/blink/renderer/core/css/style_change_reason.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_change_reason.cc
@@ -10,7 +10,7 @@
namespace blink {
-namespace StyleChangeReason {
+namespace style_change_reason {
const char kActiveStylesheetsUpdate[] = "ActiveStylesheetsUpdate";
const char kAnimation[] = "Animation";
const char kAttribute[] = "Attribute";
@@ -50,9 +50,9 @@ const char kVisitedLink[] = "VisitedLink";
const char kVisuallyOrdered[] = "VisuallyOrdered";
const char kWritingModeChange[] = "WritingModeChange";
const char kZoom[] = "Zoom";
-} // namespace StyleChangeReason
+} // namespace style_change_reason
-namespace StyleChangeExtraData {
+namespace style_change_extra_data {
DEFINE_GLOBAL(AtomicString, g_active);
DEFINE_GLOBAL(AtomicString, g_disabled);
DEFINE_GLOBAL(AtomicString, g_drag);
@@ -77,6 +77,6 @@ void Init() {
new (NotNull, (void*)&g_unresolved) AtomicString(":unresolved");
}
-} // namespace StyleChangeExtraData
+} // namespace style_change_extra_data
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/style_change_reason.h b/chromium/third_party/blink/renderer/core/css/style_change_reason.h
index 06d03249ab5..7d21ac935b0 100644
--- a/chromium/third_party/blink/renderer/core/css/style_change_reason.h
+++ b/chromium/third_party/blink/renderer/core/css/style_change_reason.h
@@ -13,7 +13,7 @@ namespace blink {
class QualifiedName;
-namespace StyleChangeReason {
+namespace style_change_reason {
extern const char kActiveStylesheetsUpdate[];
extern const char kAnimation[];
extern const char kAttribute[];
@@ -50,10 +50,10 @@ extern const char kVisitedLink[];
extern const char kVisuallyOrdered[];
extern const char kWritingModeChange[];
extern const char kZoom[];
-} // namespace StyleChangeReason
+} // namespace style_change_reason
typedef const char StyleChangeReasonString[];
-namespace StyleChangeExtraData {
+namespace style_change_extra_data {
extern const AtomicString& g_active;
extern const AtomicString& g_disabled;
extern const AtomicString& g_drag;
@@ -65,7 +65,7 @@ extern const AtomicString& g_past;
extern const AtomicString& g_unresolved;
void Init();
-} // namespace StyleChangeExtraData
+} // namespace style_change_extra_data
// |StyleChangeReasonForTracing| is used to trace the reason a
// |Node::setNeedsStyleRecalc| call was made to show it in DevTools or in
@@ -89,7 +89,7 @@ class StyleChangeReasonForTracing {
static StyleChangeReasonForTracing FromAttribute(
const QualifiedName& attribute_name) {
- return StyleChangeReasonForTracing(StyleChangeReason::kAttribute,
+ return StyleChangeReasonForTracing(style_change_reason::kAttribute,
attribute_name.LocalName());
}
diff --git a/chromium/third_party/blink/renderer/core/css/style_color.h b/chromium/third_party/blink/renderer/core/css/style_color.h
index f3ebcf21c6a..b43684bf76f 100644
--- a/chromium/third_party/blink/renderer/core/css/style_color.h
+++ b/chromium/third_party/blink/renderer/core/css/style_color.h
@@ -55,6 +55,8 @@ class StyleColor {
return current_color_ ? current_color : color_;
}
+ bool HasAlpha() const { return !current_color_ && color_.HasAlpha(); }
+
static Color ColorFromKeyword(CSSValueID);
static bool IsColorKeyword(CSSValueID);
static bool IsSystemColor(CSSValueID);
diff --git a/chromium/third_party/blink/renderer/core/css/style_element.cc b/chromium/third_party/blink/renderer/core/css/style_element.cc
index 5edb773c8f0..7c5da2dc8f5 100644
--- a/chromium/third_party/blink/renderer/core/css/style_element.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_element.cc
@@ -123,8 +123,7 @@ void StyleElement::ClearSheet(Element& owner_element) {
static bool ShouldBypassMainWorldCSP(const Element& element) {
// Main world CSP is bypassed within an isolated world.
- LocalFrame* frame = element.GetDocument().GetFrame();
- if (frame && frame->GetScriptController().ShouldBypassMainWorldCSP())
+ if (ContentSecurityPolicy::ShouldBypassMainWorld(&element.GetDocument()))
return true;
// Main world CSP is bypassed for style elements in user agent shadow DOM.
diff --git a/chromium/third_party/blink/renderer/core/css/style_engine.cc b/chromium/third_party/blink/renderer/core/css/style_engine.cc
index d941f6606e1..2fd4861f44b 100644
--- a/chromium/third_party/blink/renderer/core/css/style_engine.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_engine.cc
@@ -30,12 +30,16 @@
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/css/css_default_style_sheets.h"
+#include "third_party/blink/renderer/core/css/css_font_family_value.h"
#include "third_party/blink/renderer/core/css/css_font_selector.h"
+#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
+#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/document_style_environment_variables.h"
#include "third_party/blink/renderer/core/css/document_style_sheet_collector.h"
#include "third_party/blink/renderer/core/css/font_face_cache.h"
#include "third_party/blink/renderer/core/css/invalidation/invalidation_set.h"
+#include "third_party/blink/renderer/core/css/property_registry.h"
#include "third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h"
#include "third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope.h"
#include "third_party/blink/renderer/core/css/resolver/style_rule_usage_tracker.h"
@@ -47,6 +51,7 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/processing_instruction.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/text.h"
@@ -60,6 +65,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/core/style/style_initial_data.h"
#include "third_party/blink/renderer/core/svg/svg_style_element.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_selector.h"
@@ -67,8 +73,6 @@
namespace blink {
-using namespace HTMLNames;
-
StyleEngine::StyleEngine(Document& document)
: document_(&document),
is_master_(!document.IsHTMLImport()),
@@ -110,7 +114,8 @@ TreeScopeStyleSheetCollection& StyleEngine::EnsureStyleSheetCollectionFor(
style_sheet_collection_map_.insert(&tree_scope, nullptr);
if (result.is_new_entry) {
result.stored_value->value =
- new ShadowTreeStyleSheetCollection(ToShadowRoot(tree_scope));
+ MakeGarbageCollected<ShadowTreeStyleSheetCollection>(
+ ToShadowRoot(tree_scope));
}
return *result.stored_value->value.Get();
}
@@ -341,7 +346,7 @@ void StyleEngine::WatchedSelectorsChanged() {
// TODO(futhark@chromium.org): Should be able to use RuleSetInvalidation here.
GetDocument().SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kDeclarativeContent));
+ style_change_reason::kDeclarativeContent));
}
bool StyleEngine::ShouldUpdateDocumentStyleSheetCollection() const {
@@ -599,13 +604,39 @@ void StyleEngine::ClearFontCacheAndAddUserFonts() {
resolver_->InvalidateMatchedPropertiesCache();
}
+ default_font_display_map_.clear();
// Rebuild the font cache with @font-face rules from user style sheets.
for (unsigned i = 0; i < active_user_style_sheets_.size(); ++i) {
DCHECK(active_user_style_sheets_[i].second);
- AddFontFaceRules(*active_user_style_sheets_[i].second);
+ AddUserFontFaceRules(*active_user_style_sheets_[i].second);
+ for (const auto& rule :
+ active_user_style_sheets_[i].second->FontFeatureValuesRules()) {
+ AddDefaultFontDisplay(rule);
+ }
+ }
+}
+
+void StyleEngine::AddDefaultFontDisplay(
+ const StyleRuleFontFeatureValues* rule) {
+ if (!rule->FontDisplay())
+ return;
+ for (const auto& family_value : rule->FontFamily()) {
+ if (family_value->IsFontFamilyValue()) {
+ default_font_display_map_.Set(
+ AtomicString(ToCSSFontFamilyValue(family_value)->Value()),
+ CSSValueToFontDisplay(rule->FontDisplay()));
+ }
}
}
+FontDisplay StyleEngine::GetDefaultFontDisplay(
+ const AtomicString& family) const {
+ auto it = default_font_display_map_.find(family);
+ if (it == default_font_display_map_.end())
+ return kFontDisplayAuto;
+ return it->value;
+}
+
void StyleEngine::UpdateGenericFontFamilySettings() {
// FIXME: we should not update generic font family settings when
// document is inactive.
@@ -747,7 +778,7 @@ void StyleEngine::FontsNeedUpdate(FontSelector*) {
resolver_->InvalidateMatchedPropertiesCache();
GetDocument().SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kFonts));
+ StyleChangeReasonForTracing::Create(style_change_reason::kFonts));
probe::fontsUpdated(document_, nullptr, String(), nullptr);
}
@@ -764,7 +795,7 @@ void StyleEngine::PlatformColorsChanged() {
resolver_->InvalidateMatchedPropertiesCache();
GetDocument().SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kPlatformColorChange));
+ style_change_reason::kPlatformColorChange));
}
bool StyleEngine::ShouldSkipInvalidationFor(const Element& element) const {
@@ -842,6 +873,24 @@ void StyleEngine::ClassChangedForElement(const SpaceSplitString& old_classes,
element);
}
+namespace {
+
+bool HasAttributeDependentGeneratedContent(const Element& element) {
+ if (PseudoElement* before = element.GetPseudoElement(kPseudoIdBefore)) {
+ const ComputedStyle* style = before->GetComputedStyle();
+ if (style && style->HasAttrContent())
+ return true;
+ }
+ if (PseudoElement* after = element.GetPseudoElement(kPseudoIdAfter)) {
+ const ComputedStyle* style = after->GetComputedStyle();
+ if (style && style->HasAttrContent())
+ return true;
+ }
+ return false;
+}
+
+} // namespace
+
void StyleEngine::AttributeChangedForElement(
const QualifiedName& attribute_name,
Element& element) {
@@ -853,6 +902,13 @@ void StyleEngine::AttributeChangedForElement(
invalidation_lists, element, attribute_name);
pending_invalidations_.ScheduleInvalidationSetsForNode(invalidation_lists,
element);
+
+ if (!element.NeedsStyleRecalc() &&
+ HasAttributeDependentGeneratedContent(element)) {
+ element.SetNeedsStyleRecalc(
+ kLocalStyleChange,
+ StyleChangeReasonForTracing::FromAttribute(attribute_name));
+ }
}
void StyleEngine::IdChangedForElement(const AtomicString& old_id,
@@ -893,10 +949,10 @@ void StyleEngine::PartChangedForElement(Element& element) {
return;
element.SetNeedsStyleRecalc(
kLocalStyleChange,
- StyleChangeReasonForTracing::FromAttribute(HTMLNames::partAttr));
+ StyleChangeReasonForTracing::FromAttribute(html_names::kPartAttr));
}
-void StyleEngine::PartmapChangedForElement(Element& element) {
+void StyleEngine::ExportpartsChangedForElement(Element& element) {
if (ShouldSkipInvalidationFor(element))
return;
if (!element.GetShadowRoot())
@@ -1055,7 +1111,7 @@ void StyleEngine::ScheduleTypeRuleSetInvalidations(
if (invalidation_set->InvalidatesTagName(host)) {
host.SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleSheetChange));
+ style_change_reason::kStyleSheetChange));
return;
}
}
@@ -1088,7 +1144,7 @@ void StyleEngine::InvalidateSlottedElements(HTMLSlotElement& slot) {
if (node->IsElementNode()) {
node->SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleSheetChange));
+ style_change_reason::kStyleSheetChange));
}
}
}
@@ -1204,7 +1260,7 @@ void StyleEngine::InitialStyleChanged() {
GetDocument().SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kSettings));
+ StyleChangeReasonForTracing::Create(style_change_reason::kSettings));
}
void StyleEngine::InitialViewportChanged() {
@@ -1238,8 +1294,9 @@ void StyleEngine::HtmlImportAddedOrRemoved() {
MarkDocumentDirty();
resolver->SetNeedsAppendAllSheets();
GetDocument().SetNeedsStyleRecalc(
- kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kActiveStylesheetsUpdate));
+ kSubtreeStyleChange,
+ StyleChangeReasonForTracing::Create(
+ style_change_reason::kActiveStylesheetsUpdate));
}
}
@@ -1257,7 +1314,9 @@ namespace {
enum RuleSetFlags {
kFontFaceRules = 1 << 0,
kKeyframesRules = 1 << 1,
- kFullRecalcRules = 1 << 2
+ kFullRecalcRules = 1 << 2,
+ kFontFeatureValuesRules = 1 << 3,
+ kFontRules = kFontFaceRules | kFontFeatureValuesRules,
};
unsigned GetRuleSetFlags(const HeapHashSet<Member<RuleSet>> rule_sets) {
@@ -1270,6 +1329,8 @@ unsigned GetRuleSetFlags(const HeapHashSet<Member<RuleSet>> rule_sets) {
flags |= kFontFaceRules;
if (rule_set->NeedsFullRecalcForRuleSetInvalidation())
flags |= kFullRecalcRules;
+ if (!rule_set->FontFeatureValuesRules().IsEmpty())
+ flags |= kFontFeatureValuesRules;
}
return flags;
}
@@ -1287,8 +1348,9 @@ void StyleEngine::InvalidateForRuleSetChanges(
if (!tree_scope.GetDocument().body() ||
tree_scope.GetDocument().HasNodesWithPlaceholderStyle()) {
tree_scope.GetDocument().SetNeedsStyleRecalc(
- kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kCleanupPlaceholderStyles));
+ kSubtreeStyleChange,
+ StyleChangeReasonForTracing::Create(
+ style_change_reason::kCleanupPlaceholderStyles));
return;
}
@@ -1304,8 +1366,9 @@ void StyleEngine::InvalidateForRuleSetChanges(
((changed_rule_flags & kFontFaceRules) &&
tree_scope.RootNode().IsDocumentNode())) {
invalidation_root.SetNeedsStyleRecalc(
- kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kActiveStylesheetsUpdate));
+ kSubtreeStyleChange,
+ StyleChangeReasonForTracing::Create(
+ style_change_reason::kActiveStylesheetsUpdate));
return;
}
@@ -1313,6 +1376,10 @@ void StyleEngine::InvalidateForRuleSetChanges(
invalidation_scope);
}
+void StyleEngine::InvalidateInitialData() {
+ initial_data_ = nullptr;
+}
+
void StyleEngine::ApplyUserRuleSetChanges(
const ActiveStyleSheetVector& old_style_sheets,
const ActiveStyleSheetVector& new_style_sheets) {
@@ -1330,7 +1397,7 @@ void StyleEngine::ApplyUserRuleSetChanges(
global_rule_set_->MarkDirty();
unsigned changed_rule_flags = GetRuleSetFlags(changed_rule_sets);
- if (changed_rule_flags & kFontFaceRules) {
+ if (changed_rule_flags & kFontRules) {
if (ScopedStyleResolver* scoped_resolver =
GetDocument().GetScopedStyleResolver()) {
// User style and document scope author style shares the font cache. If
@@ -1351,7 +1418,7 @@ void StyleEngine::ApplyUserRuleSetChanges(
for (auto* it = new_style_sheets.begin(); it != new_style_sheets.end();
it++) {
DCHECK(it->second);
- AddKeyframeRules(*it->second);
+ AddUserKeyframeRules(*it->second);
}
ScopedStyleResolver::KeyframesRulesAdded(GetDocument());
}
@@ -1374,7 +1441,7 @@ void StyleEngine::ApplyRuleSetChanges(
unsigned changed_rule_flags = GetRuleSetFlags(changed_rule_sets);
bool rebuild_font_cache = change == kActiveSheetsChanged &&
- (changed_rule_flags & kFontFaceRules) &&
+ (changed_rule_flags & kFontRules) &&
tree_scope.RootNode().IsDocumentNode();
ScopedStyleResolver* scoped_resolver = tree_scope.GetScopedStyleResolver();
if (scoped_resolver && scoped_resolver->NeedsAppendAllSheets()) {
@@ -1422,9 +1489,9 @@ const MediaQueryEvaluator& StyleEngine::EnsureMediaQueryEvaluator() {
if (!media_query_evaluator_) {
if (GetDocument().GetFrame()) {
media_query_evaluator_ =
- new MediaQueryEvaluator(GetDocument().GetFrame());
+ MakeGarbageCollected<MediaQueryEvaluator>(GetDocument().GetFrame());
} else {
- media_query_evaluator_ = new MediaQueryEvaluator("all");
+ media_query_evaluator_ = MakeGarbageCollected<MediaQueryEvaluator>("all");
}
}
return *media_query_evaluator_;
@@ -1476,15 +1543,16 @@ void StyleEngine::CustomPropertyRegistered() {
// TODO(timloh): Invalidate only elements with this custom property set
GetDocument().SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kPropertyRegistration));
+ style_change_reason::kPropertyRegistration));
if (resolver_)
resolver_->InvalidateMatchedPropertiesCache();
+ InvalidateInitialData();
}
void StyleEngine::EnvironmentVariableChanged() {
GetDocument().SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kPropertyRegistration));
+ style_change_reason::kPropertyRegistration));
if (resolver_)
resolver_->InvalidateMatchedPropertiesCache();
}
@@ -1555,7 +1623,7 @@ void StyleEngine::CollectMatchingUserRules(
}
}
-void StyleEngine::AddFontFaceRules(const RuleSet& rule_set) {
+void StyleEngine::AddUserFontFaceRules(const RuleSet& rule_set) {
if (!font_selector_)
return;
@@ -1569,14 +1637,14 @@ void StyleEngine::AddFontFaceRules(const RuleSet& rule_set) {
resolver_->InvalidateMatchedPropertiesCache();
}
-void StyleEngine::AddKeyframeRules(const RuleSet& rule_set) {
+void StyleEngine::AddUserKeyframeRules(const RuleSet& rule_set) {
const HeapVector<Member<StyleRuleKeyframes>> keyframes_rules =
rule_set.KeyframesRules();
for (unsigned i = 0; i < keyframes_rules.size(); ++i)
- AddKeyframeStyle(keyframes_rules[i]);
+ AddUserKeyframeStyle(keyframes_rules[i]);
}
-void StyleEngine::AddKeyframeStyle(StyleRuleKeyframes* rule) {
+void StyleEngine::AddUserKeyframeStyle(StyleRuleKeyframes* rule) {
AtomicString animation_name(rule->GetName());
if (rule->IsVendorPrefixed()) {
@@ -1610,6 +1678,16 @@ DocumentStyleEnvironmentVariables& StyleEngine::EnsureEnvironmentVariables() {
return *environment_variables_.get();
}
+scoped_refptr<StyleInitialData> StyleEngine::MaybeCreateAndGetInitialData() {
+ if (initial_data_)
+ return initial_data_;
+ if (PropertyRegistry* registry = document_->GetPropertyRegistry()) {
+ if (registry->RegistrationCount())
+ initial_data_ = StyleInitialData::Create(*registry);
+ }
+ return initial_data_;
+}
+
void StyleEngine::RecalcStyle(StyleRecalcChange change) {
DCHECK(GetDocument().documentElement());
DCHECK(GetDocument().ChildNeedsStyleRecalc() || change == kForce);
diff --git a/chromium/third_party/blink/renderer/core/css/style_engine.h b/chromium/third_party/blink/renderer/core/css/style_engine.h
index 0f8f464f23d..354d1c7cb62 100644
--- a/chromium/third_party/blink/renderer/core/css/style_engine.h
+++ b/chromium/third_party/blink/renderer/core/css/style_engine.h
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/core/css/active_style_sheets.h"
#include "third_party/blink/renderer/core/css/css_global_rule_set.h"
#include "third_party/blink/renderer/core/css/document_style_sheet_collection.h"
+#include "third_party/blink/renderer/core/css/font_display.h"
#include "third_party/blink/renderer/core/css/invalidation/pending_invalidations.h"
#include "third_party/blink/renderer/core/css/invalidation/style_invalidator.h"
#include "third_party/blink/renderer/core/css/layout_tree_rebuild_root.h"
@@ -69,6 +70,7 @@ class DocumentStyleEnvironmentVariables;
class StyleRuleFontFace;
class StyleRuleUsageTracker;
class StyleSheetContents;
+class StyleInitialData;
class ViewportStyleResolver;
enum InvalidationScope { kInvalidateCurrentScope, kInvalidateAllScopes };
@@ -90,7 +92,10 @@ class CORE_EXPORT StyleEngine final
public:
IgnoringPendingStylesheet(StyleEngine& engine)
- : scope_(&engine.ignore_pending_stylesheets_, true) {}
+ : scope_(&engine.ignore_pending_stylesheets_,
+ !RuntimeEnabledFeatures::CSSInBodyDoesNotBlockPaintEnabled()) {
+ }
+
private:
base::AutoReset<bool> scope_;
};
@@ -107,9 +112,10 @@ class CORE_EXPORT StyleEngine final
};
static StyleEngine* Create(Document& document) {
- return new StyleEngine(document);
+ return MakeGarbageCollected<StyleEngine>(document);
}
+ StyleEngine(Document&);
~StyleEngine() override;
const HeapVector<TraceWrapperMember<StyleSheet>>&
@@ -268,8 +274,10 @@ class CORE_EXPORT StyleEngine final
CollectUserStyleFeaturesTo(features);
CollectScopedStyleFeaturesTo(features);
for (CSSStyleSheet* sheet : custom_element_default_style_sheets_) {
- if (sheet)
- features.Add(RuleSetForSheet(*sheet)->Features());
+ if (!sheet)
+ continue;
+ if (RuleSet* rule_set = RuleSetForSheet(*sheet))
+ features.Add(rule_set->Features());
}
}
@@ -291,7 +299,7 @@ class CORE_EXPORT StyleEngine final
Element&);
void PseudoStateChangedForElement(CSSSelector::PseudoType, Element&);
void PartChangedForElement(Element&);
- void PartmapChangedForElement(Element&);
+ void ExportpartsChangedForElement(Element&);
void ScheduleSiblingInvalidationsForElement(Element&,
ContainerNode& scheduling_parent,
@@ -342,6 +350,10 @@ class CORE_EXPORT StyleEngine final
const AtomicString& animation_name);
DocumentStyleEnvironmentVariables& EnsureEnvironmentVariables();
+ void AddDefaultFontDisplay(const StyleRuleFontFeatureValues*);
+ FontDisplay GetDefaultFontDisplay(const AtomicString& family) const;
+
+ scoped_refptr<StyleInitialData> MaybeCreateAndGetInitialData();
void RecalcStyle(StyleRecalcChange change);
void RebuildLayoutTree();
@@ -355,7 +367,6 @@ class CORE_EXPORT StyleEngine final
void FontsNeedUpdate(FontSelector*) override;
private:
- StyleEngine(Document&);
bool NeedsActiveStyleSheetUpdate() const {
return all_tree_scopes_dirty_ || tree_scopes_removed_ ||
document_scope_dirty_ || dirty_tree_scopes_.size() ||
@@ -420,6 +431,7 @@ class CORE_EXPORT StyleEngine final
const HeapHashSet<Member<RuleSet>>& changed_rule_sets,
unsigned changed_rule_flags,
InvalidationScope invalidation_scope);
+ void InvalidateInitialData();
void UpdateViewport();
void UpdateActiveUserStyleSheets();
@@ -435,9 +447,9 @@ class CORE_EXPORT StyleEngine final
void ClearFontCacheAndAddUserFonts();
void ClearKeyframeRules() { keyframes_rule_map_.clear(); }
- void AddFontFaceRules(const RuleSet&);
- void AddKeyframeRules(const RuleSet&);
- void AddKeyframeStyle(StyleRuleKeyframes*);
+ void AddUserFontFaceRules(const RuleSet&);
+ void AddUserKeyframeRules(const RuleSet&);
+ void AddUserKeyframeStyle(StyleRuleKeyframes*);
Member<Document> document_;
bool is_master_;
@@ -518,6 +530,12 @@ class CORE_EXPORT StyleEngine final
scoped_refptr<DocumentStyleEnvironmentVariables> environment_variables_;
+ scoped_refptr<StyleInitialData> initial_data_;
+
+ // Default font-display collected from @font-feature-values rules. The key is
+ // font-family.
+ HashMap<AtomicString, FontDisplay> default_font_display_map_;
+
friend class StyleEngineTest;
};
diff --git a/chromium/third_party/blink/renderer/core/css/style_engine_test.cc b/chromium/third_party/blink/renderer/core/css/style_engine_test.cc
index 2e11be19c9a..26cd17b201c 100644
--- a/chromium/third_party/blink/renderer/core/css/style_engine_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_engine_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/css/css_rule_list.h"
#include "third_party/blink/renderer/core/css/css_style_rule.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -23,6 +24,7 @@
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/viewport_data.h"
+#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_span_element.h"
#include "third_party/blink/renderer/core/html/html_style_element.h"
@@ -34,6 +36,8 @@
namespace blink {
+using namespace css_test_helpers;
+
class StyleEngineTest : public testing::Test {
protected:
void SetUp() override;
@@ -52,6 +56,12 @@ class StyleEngineTest : public testing::Test {
RuleSetInvalidation ScheduleInvalidationsForRules(TreeScope&,
const String& css_text);
+ // A wrapper to add a reason for UpdateAllLifecyclePhases
+ void UpdateAllLifecyclePhases() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
private:
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
};
@@ -84,7 +94,7 @@ TEST_F(StyleEngineTest, DocumentDirtyAfterInject) {
parsed_sheet->ParseString("div {}");
GetStyleEngine().InjectSheet("", parsed_sheet);
EXPECT_FALSE(IsDocumentStyleSheetCollectionClean());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_TRUE(IsDocumentStyleSheetCollectionClean());
}
@@ -122,7 +132,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
<div id='t11'>White</div>
<div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
Element* t2 = GetDocument().getElementById("t2");
@@ -151,7 +161,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
StyleSheetKey green_key("green");
GetStyleEngine().InjectSheet(green_key, green_parsed_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(3u, GetStyleEngine().StyleForElementCount() - initial_count);
@@ -177,7 +187,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
StyleSheetKey blue_key("blue");
GetStyleEngine().InjectSheet(blue_key, blue_parsed_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(6u, GetStyleEngine().StyleForElementCount() - initial_count);
@@ -197,7 +207,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
t3->GetComputedStyle()->VisitedDependentColor(GetCSSPropertyColor()));
GetStyleEngine().RemoveInjectedSheet(green_key, WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(9u, GetStyleEngine().StyleForElementCount() - initial_count);
ASSERT_TRUE(t1->GetComputedStyle());
ASSERT_TRUE(t2->GetComputedStyle());
@@ -213,7 +223,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
t3->GetComputedStyle()->VisitedDependentColor(GetCSSPropertyColor()));
GetStyleEngine().RemoveInjectedSheet(blue_key, WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(12u, GetStyleEngine().StyleForElementCount() - initial_count);
ASSERT_TRUE(t1->GetComputedStyle());
ASSERT_TRUE(t2->GetComputedStyle());
@@ -258,7 +268,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
StyleSheetKey font_face_key("font_face");
GetStyleEngine().InjectSheet(font_face_key, font_face_parsed_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// After injecting a more specific font, now there are two and the
// bold-italic one is selected.
@@ -284,7 +294,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
" font-style: italic;"
"}");
GetDocument().body()->AppendChild(style_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Now there are three fonts, but the newest one does not override the older,
// better matching one.
@@ -301,7 +311,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
FontSelectionRange({ItalicSlopeValue(), ItalicSlopeValue()}));
GetStyleEngine().RemoveInjectedSheet(font_face_key, WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// After removing the injected style sheet we're left with a bold-normal and
// a normal-italic font, and the latter is selected by the matching algorithm
@@ -333,7 +343,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
StyleSheetKey keyframes_key("keyframes");
GetStyleEngine().InjectSheet(keyframes_key, keyframes_parsed_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// After injecting the style sheet, a @keyframes rule named dummy-animation
// is found with one keyframe.
@@ -347,7 +357,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
style_element->SetInnerHTMLFromString(
"@keyframes dummy-animation { from {} to {} }");
GetDocument().body()->AppendChild(style_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Author @keyframes rules take precedence; now there are two keyframes (from
// and to).
@@ -357,7 +367,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
EXPECT_EQ(2u, keyframes->Keyframes().size());
GetDocument().body()->RemoveChild(style_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
keyframes = GetStyleEngine().Resolver()->FindKeyframesRule(
t5, AtomicString("dummy-animation"));
@@ -365,7 +375,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
EXPECT_EQ(1u, keyframes->Keyframes().size());
GetStyleEngine().RemoveInjectedSheet(keyframes_key, WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Injected @keyframes rules are no longer available once removed.
ASSERT_FALSE(GetStyleEngine().Resolver()->FindKeyframesRule(
@@ -396,7 +406,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().InjectSheet(custom_properties_key,
custom_properties_parsed_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t6->GetComputedStyle());
ASSERT_TRUE(t7->GetComputedStyle());
EXPECT_EQ(MakeRGB(255, 0, 0), t6->GetComputedStyle()->VisitedDependentColor(
@@ -407,7 +417,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(custom_properties_key,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t6->GetComputedStyle());
ASSERT_TRUE(t7->GetComputedStyle());
EXPECT_EQ(MakeRGB(0, 0, 0), t6->GetComputedStyle()->VisitedDependentColor(
@@ -442,7 +452,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().InjectSheet(media_queries_sheet_key,
media_queries_parsed_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t8->GetComputedStyle());
EXPECT_EQ(MakeRGB(255, 0, 0), t8->GetComputedStyle()->VisitedDependentColor(
GetCSSPropertyColor()));
@@ -460,7 +470,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(media_queries_sheet_key,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t8->GetComputedStyle());
EXPECT_EQ(
MakeRGB(255, 255, 255),
@@ -491,7 +501,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
StyleSheetKey author_sheet_key("author_sheet");
GetStyleEngine().InjectSheet(author_sheet_key, parsed_author_sheet,
WebDocument::kAuthorOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t9->GetComputedStyle());
ASSERT_TRUE(t10->GetComputedStyle());
@@ -504,7 +514,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(author_sheet_key,
WebDocument::kAuthorOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t9->GetComputedStyle());
ASSERT_TRUE(t10->GetComputedStyle());
EXPECT_EQ(MakeRGB(255, 0, 0), t9->GetComputedStyle()->VisitedDependentColor(
@@ -528,7 +538,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().InjectSheet(removable_red_sheet_key,
parsed_removable_red_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
EXPECT_EQ(MakeRGB(255, 0, 0), t11->GetComputedStyle()->VisitedDependentColor(
@@ -542,7 +552,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().InjectSheet(removable_green_sheet_key,
parsed_removable_green_sheet,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
EXPECT_EQ(MakeRGB(0, 128, 0), t11->GetComputedStyle()->VisitedDependentColor(
@@ -554,7 +564,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().InjectSheet(removable_red_sheet_key,
parsed_removable_red_sheet2,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
EXPECT_EQ(MakeRGB(255, 0, 0), t11->GetComputedStyle()->VisitedDependentColor(
@@ -562,7 +572,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(removable_red_sheet_key,
WebDocument::kAuthorOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
// Removal works only within the same origin.
@@ -571,7 +581,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(removable_red_sheet_key,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
// The last sheet with the given key is removed.
@@ -580,7 +590,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(removable_green_sheet_key,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
// Only the last sheet with the given key is removed.
@@ -589,7 +599,7 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
GetStyleEngine().RemoveInjectedSheet(removable_red_sheet_key,
WebDocument::kUserOrigin);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t11->GetComputedStyle());
EXPECT_EQ(
@@ -597,11 +607,44 @@ TEST_F(StyleEngineTest, AnalyzedInject) {
t11->GetComputedStyle()->VisitedDependentColor(GetCSSPropertyColor()));
}
+TEST_F(StyleEngineTest, InjectedFontFace) {
+ GetDocument().body()->SetInnerHTMLFromString(R"HTML(
+ <style>
+ @font-face {
+ font-family: 'Author';
+ src: url(user);
+ }
+ </style>
+ )HTML");
+ UpdateAllLifecyclePhases();
+
+ FontDescription font_description;
+ FontFaceCache* cache = GetStyleEngine().GetFontSelector()->GetFontFaceCache();
+ EXPECT_TRUE(cache->Get(font_description, "Author"));
+ EXPECT_FALSE(cache->Get(font_description, "User"));
+
+ StyleSheetContents* user_sheet =
+ StyleSheetContents::Create(CSSParserContext::Create(GetDocument()));
+ user_sheet->ParseString(
+ "@font-face {"
+ " font-family: 'User';"
+ " src: url(author);"
+ "}");
+
+ StyleSheetKey user_key("user");
+ GetStyleEngine().InjectSheet(user_key, user_sheet, WebDocument::kUserOrigin);
+
+ UpdateAllLifecyclePhases();
+
+ EXPECT_TRUE(cache->Get(font_description, "Author"));
+ EXPECT_TRUE(cache->Get(font_description, "User"));
+}
+
TEST_F(StyleEngineTest, IgnoreInvalidPropertyValue) {
GetDocument().body()->SetInnerHTMLFromString(
"<section><div id='t1'>Red</div></section>"
"<style id='s1'>div { color: red; } section div#t1 { color:rgb(0");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
ASSERT_TRUE(t1);
@@ -661,13 +704,13 @@ TEST_F(StyleEngineTest, RuleSetInvalidationTypeSelectors) {
</i>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned before_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(kRuleSetInvalidationsScheduled,
ScheduleInvalidationsForRules(GetDocument(),
"span { background: green}"));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(1u, after_count - before_count);
@@ -675,20 +718,20 @@ TEST_F(StyleEngineTest, RuleSetInvalidationTypeSelectors) {
EXPECT_EQ(kRuleSetInvalidationsScheduled,
ScheduleInvalidationsForRules(GetDocument(),
"body div { background: green}"));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(2u, after_count - before_count);
EXPECT_EQ(kRuleSetInvalidationFullRecalc,
ScheduleInvalidationsForRules(GetDocument(),
"div * { background: green}"));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
before_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(kRuleSetInvalidationsScheduled,
ScheduleInvalidationsForRules(GetDocument(),
"#i b { background: green}"));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(1u, after_count - before_count);
}
@@ -700,13 +743,13 @@ TEST_F(StyleEngineTest, RuleSetInvalidationCustomPseudo) {
<div></div><div></div><div></div><div></div><div></div><div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned before_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(ScheduleInvalidationsForRules(
GetDocument(), "::-webkit-progress-bar { background: green }"),
kRuleSetInvalidationsScheduled);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(3u, after_count - before_count);
}
@@ -721,13 +764,13 @@ TEST_F(StyleEngineTest, RuleSetInvalidationHost) {
host->AttachShadowRootInternal(ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString("<div></div><div></div><div></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned before_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(ScheduleInvalidationsForRules(
shadow_root, ":host(#nohost), #nohost { background: green}"),
kRuleSetInvalidationsScheduled);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(0u, after_count - before_count);
@@ -735,7 +778,7 @@ TEST_F(StyleEngineTest, RuleSetInvalidationHost) {
EXPECT_EQ(ScheduleInvalidationsForRules(shadow_root,
":host(#host) { background: green}"),
kRuleSetInvalidationsScheduled);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(1u, after_count - before_count);
EXPECT_EQ(ScheduleInvalidationsForRules(shadow_root,
@@ -767,13 +810,13 @@ TEST_F(StyleEngineTest, RuleSetInvalidationSlotted) {
host->AttachShadowRootInternal(ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString("<slot name=other></slot><slot></slot>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned before_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(ScheduleInvalidationsForRules(
shadow_root, "::slotted(.s1) { background: green}"),
kRuleSetInvalidationsScheduled);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(4u, after_count - before_count);
@@ -781,7 +824,7 @@ TEST_F(StyleEngineTest, RuleSetInvalidationSlotted) {
EXPECT_EQ(ScheduleInvalidationsForRules(shadow_root,
"::slotted(*) { background: green}"),
kRuleSetInvalidationsScheduled);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(4u, after_count - before_count);
}
@@ -796,13 +839,13 @@ TEST_F(StyleEngineTest, RuleSetInvalidationHostContext) {
shadow_root.SetInnerHTMLFromString(
"<div></div><div class=a></div><div></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned before_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(ScheduleInvalidationsForRules(
shadow_root, ":host-context(.nomatch) .a { background: green}"),
kRuleSetInvalidationsScheduled);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(1u, after_count - before_count);
@@ -824,7 +867,7 @@ TEST_F(StyleEngineTest, RuleSetInvalidationV0BoundaryCrossing) {
shadow_root.SetInnerHTMLFromString(
"<div></div><div class=a></div><div></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(ScheduleInvalidationsForRules(
shadow_root, ".a ::content span { background: green}"),
@@ -843,15 +886,15 @@ TEST_F(StyleEngineTest, HasViewportDependentMediaQueries) {
for (unsigned i = 0; i < 10; i++) {
GetDocument().body()->RemoveChild(style_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetDocument().body()->AppendChild(style_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
EXPECT_TRUE(GetStyleEngine().HasViewportDependentMediaQueries());
GetDocument().body()->RemoveChild(style_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_FALSE(GetStyleEngine().HasViewportDependentMediaQueries());
}
@@ -860,7 +903,7 @@ TEST_F(StyleEngineTest, StyleMediaAttributeStyleChange) {
GetDocument().body()->SetInnerHTMLFromString(
"<style id='s1' media='(max-width: 1px)'>#t1 { color: green }</style>"
"<div id='t1'>Green</div><div></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
ASSERT_TRUE(t1);
@@ -871,8 +914,8 @@ TEST_F(StyleEngineTest, StyleMediaAttributeStyleChange) {
unsigned before_count = GetStyleEngine().StyleForElementCount();
Element* s1 = GetDocument().getElementById("s1");
- s1->setAttribute(blink::HTMLNames::mediaAttr, "(max-width: 2000px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ s1->setAttribute(blink::html_names::kMediaAttr, "(max-width: 2000px)");
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(1u, after_count - before_count);
@@ -886,7 +929,7 @@ TEST_F(StyleEngineTest, StyleMediaAttributeNoStyleChange) {
GetDocument().body()->SetInnerHTMLFromString(
"<style id='s1' media='(max-width: 1000px)'>#t1 { color: green }</style>"
"<div id='t1'>Green</div><div></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
ASSERT_TRUE(t1);
@@ -897,8 +940,8 @@ TEST_F(StyleEngineTest, StyleMediaAttributeNoStyleChange) {
unsigned before_count = GetStyleEngine().StyleForElementCount();
Element* s1 = GetDocument().getElementById("s1");
- s1->setAttribute(blink::HTMLNames::mediaAttr, "(max-width: 2000px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ s1->setAttribute(blink::html_names::kMediaAttr, "(max-width: 2000px)");
+ UpdateAllLifecyclePhases();
unsigned after_count = GetStyleEngine().StyleForElementCount();
EXPECT_EQ(0u, after_count - before_count);
@@ -917,7 +960,7 @@ TEST_F(StyleEngineTest, ModifyStyleRuleMatchedPropertiesCache) {
GetDocument().body()->SetInnerHTMLFromString(
"<style id='s1'>#t1 { color: blue }</style>"
"<div id='t1'>Green</div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
ASSERT_TRUE(t1);
@@ -940,7 +983,7 @@ TEST_F(StyleEngineTest, ModifyStyleRuleMatchedPropertiesCache) {
// hash value will be the same.
style_rule->style()->setProperty(&GetDocument(), "color", "red", "",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t1->GetComputedStyle());
EXPECT_EQ(MakeRGB(255, 0, 0), t1->GetComputedStyle()->VisitedDependentColor(
@@ -948,7 +991,7 @@ TEST_F(StyleEngineTest, ModifyStyleRuleMatchedPropertiesCache) {
style_rule->style()->setProperty(&GetDocument(), "color", "green", "",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_TRUE(t1->GetComputedStyle());
EXPECT_EQ(MakeRGB(0, 128, 0), t1->GetComputedStyle()->VisitedDependentColor(
@@ -962,7 +1005,7 @@ TEST_F(StyleEngineTest, VisitedExplicitInheritanceMatchedPropertiesCache) {
</style>
<span id="span"><a href></a></span>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* span = GetDocument().getElementById("span");
const ComputedStyle* style = span->GetComputedStyle();
@@ -974,7 +1017,7 @@ TEST_F(StyleEngineTest, VisitedExplicitInheritanceMatchedPropertiesCache) {
span->SetInlineStyleProperty(CSSPropertyColor, "blue");
// Should not DCHECK on applying overflow:inherit on cached matched properties
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
TEST_F(StyleEngineTest, ScheduleInvalidationAfterSubtreeRecalc) {
@@ -987,7 +1030,7 @@ TEST_F(StyleEngineTest, ScheduleInvalidationAfterSubtreeRecalc) {
<div id='t1'></div>
<div id='t2'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
Element* t2 = GetDocument().getElementById("t2");
@@ -995,12 +1038,12 @@ TEST_F(StyleEngineTest, ScheduleInvalidationAfterSubtreeRecalc) {
ASSERT_TRUE(t2);
// Sanity test.
- t1->setAttribute(blink::HTMLNames::classAttr, "t1");
+ t1->setAttribute(blink::html_names::kClassAttr, "t1");
EXPECT_FALSE(GetDocument().NeedsStyleInvalidation());
EXPECT_TRUE(GetDocument().ChildNeedsStyleInvalidation());
EXPECT_TRUE(t1->NeedsStyleInvalidation());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// platformColorsChanged() triggers SubtreeStyleChange on document(). If that
// for some reason should change, this test will start failing and the
@@ -1011,11 +1054,11 @@ TEST_F(StyleEngineTest, ScheduleInvalidationAfterSubtreeRecalc) {
// Check that no invalidations sets are scheduled when the document node is
// already SubtreeStyleChange.
- t2->setAttribute(blink::HTMLNames::classAttr, "t2");
+ t2->setAttribute(blink::html_names::kClassAttr, "t2");
EXPECT_FALSE(GetDocument().NeedsStyleInvalidation());
EXPECT_FALSE(GetDocument().ChildNeedsStyleInvalidation());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
HTMLStyleElement* s2 = ToHTMLStyleElement(GetDocument().getElementById("s2"));
ASSERT_TRUE(s2);
s2->setDisabled(true);
@@ -1023,14 +1066,14 @@ TEST_F(StyleEngineTest, ScheduleInvalidationAfterSubtreeRecalc) {
EXPECT_FALSE(GetDocument().ChildNeedsStyleInvalidation());
EXPECT_TRUE(GetDocument().NeedsStyleInvalidation());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().PlatformColorsChanged();
s2->setDisabled(false);
GetStyleEngine().UpdateActiveStyle();
EXPECT_FALSE(GetDocument().ChildNeedsStyleInvalidation());
EXPECT_FALSE(GetDocument().NeedsStyleInvalidation());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
HTMLStyleElement* s1 = ToHTMLStyleElement(GetDocument().getElementById("s1"));
ASSERT_TRUE(s1);
s1->setDisabled(true);
@@ -1040,7 +1083,7 @@ TEST_F(StyleEngineTest, ScheduleInvalidationAfterSubtreeRecalc) {
EXPECT_TRUE(t1->NeedsStyleInvalidation());
EXPECT_TRUE(t2->NeedsStyleInvalidation());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().PlatformColorsChanged();
s1->setDisabled(false);
GetStyleEngine().UpdateActiveStyle();
@@ -1055,7 +1098,7 @@ TEST_F(StyleEngineTest, NoScheduledRuleSetInvalidationsOnNewShadow) {
Element* host = GetDocument().getElementById("host");
ASSERT_TRUE(host);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ShadowRoot& shadow_root =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
@@ -1076,7 +1119,7 @@ TEST_F(StyleEngineTest, NoScheduledRuleSetInvalidationsOnNewShadow) {
TEST_F(StyleEngineTest, EmptyHttpEquivDefaultStyle) {
GetDocument().body()->SetInnerHTMLFromString(
"<style>div { color:pink }</style><div id=container></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_FALSE(GetStyleEngine().NeedsActiveStyleUpdate());
@@ -1120,7 +1163,7 @@ TEST_F(StyleEngineTest, StyleSheetsForStyleSheetList_ShadowRoot) {
Element* host = GetDocument().getElementById("host");
ASSERT_TRUE(host);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ShadowRoot& shadow_root =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
@@ -1146,7 +1189,7 @@ TEST_F(StyleEngineTest, StyleSheetsForStyleSheetList_ShadowRoot) {
EXPECT_FALSE(GetStyleEngine().NeedsActiveStyleUpdate());
}
-class StyleEngineClient : public FrameTestHelpers::TestWebViewClient {
+class StyleEngineClient : public frame_test_helpers::TestWebViewClient {
public:
StyleEngineClient() : device_scale_factor_(1.f) {}
void ConvertWindowToViewport(WebFloatRect* rect) override {
@@ -1167,10 +1210,11 @@ TEST_F(StyleEngineTest, ViewportDescriptionForZoomDSF) {
StyleEngineClient client;
client.set_device_scale_factor(1.f);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.Initialize(nullptr, &client, nullptr, nullptr);
- web_view_impl->UpdateAllLifecyclePhases();
+ web_view_impl->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
Document* document =
ToLocalFrame(web_view_impl->GetPage()->MainFrame())->GetDocument();
@@ -1183,7 +1227,8 @@ TEST_F(StyleEngineTest, ViewportDescriptionForZoomDSF) {
const float device_scale = 3.5f;
client.set_device_scale_factor(device_scale);
- web_view_impl->UpdateAllLifecyclePhases();
+ web_view_impl->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
desc = document->GetViewportData().GetViewportDescription();
EXPECT_FLOAT_EQ(device_scale * min_width, desc.min_width.GetFloatValue());
@@ -1195,7 +1240,7 @@ TEST_F(StyleEngineTest, ViewportDescriptionForZoomDSF) {
TEST_F(StyleEngineTest, MediaQueryAffectingValueChanged_StyleElementNoMedia) {
GetDocument().body()->SetInnerHTMLFromString(
"<style>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_FALSE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1204,7 +1249,7 @@ TEST_F(StyleEngineTest,
MediaQueryAffectingValueChanged_StyleElementMediaNoValue) {
GetDocument().body()->SetInnerHTMLFromString(
"<style media>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_FALSE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1213,7 +1258,7 @@ TEST_F(StyleEngineTest,
MediaQueryAffectingValueChanged_StyleElementMediaEmpty) {
GetDocument().body()->SetInnerHTMLFromString(
"<style media=''>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_FALSE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1226,7 +1271,7 @@ TEST_F(StyleEngineTest,
MediaQueryAffectingValueChanged_StyleElementMediaNoValid) {
GetDocument().body()->SetInnerHTMLFromString(
"<style media=',,'>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_TRUE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1234,7 +1279,7 @@ TEST_F(StyleEngineTest,
TEST_F(StyleEngineTest, MediaQueryAffectingValueChanged_StyleElementMediaAll) {
GetDocument().body()->SetInnerHTMLFromString(
"<style media='all'>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_TRUE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1243,7 +1288,7 @@ TEST_F(StyleEngineTest,
MediaQueryAffectingValueChanged_StyleElementMediaNotAll) {
GetDocument().body()->SetInnerHTMLFromString(
"<style media='not all'>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_TRUE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1251,7 +1296,7 @@ TEST_F(StyleEngineTest,
TEST_F(StyleEngineTest, MediaQueryAffectingValueChanged_StyleElementMediaType) {
GetDocument().body()->SetInnerHTMLFromString(
"<style media='print'>div{color:pink}</style>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetStyleEngine().MediaQueryAffectingValueChanged();
EXPECT_TRUE(GetStyleEngine().NeedsActiveStyleUpdate());
}
@@ -1267,7 +1312,7 @@ TEST_F(StyleEngineTest, EmptyPseudo_RemoveLast) {
<span></span>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
t1->firstChild()->remove();
@@ -1289,7 +1334,7 @@ TEST_F(StyleEngineTest, EmptyPseudo_RemoveNotLast) {
<span></span>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
t1->firstChild()->remove();
@@ -1311,7 +1356,7 @@ TEST_F(StyleEngineTest, EmptyPseudo_InsertFirst) {
<span></span>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
t1->appendChild(Text::Create(GetDocument(), "Text"));
@@ -1333,7 +1378,7 @@ TEST_F(StyleEngineTest, EmptyPseudo_InsertNotFirst) {
<span></span>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* t1 = GetDocument().getElementById("t1");
t1->appendChild(Text::Create(GetDocument(), "Text"));
@@ -1363,7 +1408,7 @@ TEST_F(StyleEngineTest, EmptyPseudo_ModifyTextData_SingleNode) {
t2->appendChild(Text::Create(GetDocument(), ""));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ToText(t1->firstChild())->setData("");
EXPECT_TRUE(t1->NeedsStyleInvalidation());
@@ -1396,7 +1441,7 @@ TEST_F(StyleEngineTest, EmptyPseudo_ModifyTextData_HasSiblings) {
t2->appendChild(Text::Create(GetDocument(), ""));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ToText(t1->firstChild())->setData("");
EXPECT_FALSE(t1->NeedsStyleInvalidation());
@@ -1419,13 +1464,13 @@ TEST_F(StyleEngineTest, MediaQueriesChangeDefaultFontSize) {
<body></body>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(MakeRGB(255, 0, 0),
GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
GetCSSPropertyColor()));
GetDocument().GetSettings()->SetDefaultFontSize(40);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(MakeRGB(0, 128, 0),
GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
GetCSSPropertyColor()));
@@ -1445,12 +1490,12 @@ TEST_F(StyleEngineTest, ShadowRootStyleRecalcCrash) {
:nth-child(odd) { color: green }
</style>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// This should not cause DCHECK errors on style recalc flags.
shadow_root.getElementById("span")->remove();
host->SetInlineStyleProperty(CSSPropertyDisplay, "inline");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
TEST_F(StyleEngineTest, GetComputedStyleOutsideFlatTreeCrash) {
@@ -1463,11 +1508,11 @@ TEST_F(StyleEngineTest, GetComputedStyleOutsideFlatTreeCrash) {
)HTML");
GetDocument().documentElement()->CreateV0ShadowRootForTesting();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetDocument().body()->EnsureComputedStyle();
GetDocument().getElementById("inner")->SetInlineStyleProperty(
CSSPropertyColor, "blue");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
TEST_F(StyleEngineTest, RejectSelectorForPseudoElement) {
@@ -1478,7 +1523,7 @@ TEST_F(StyleEngineTest, RejectSelectorForPseudoElement) {
</style>
<div class='not-in-filter'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
StyleEngine& engine = GetStyleEngine();
engine.SetStatsEnabled(true);
@@ -1509,7 +1554,7 @@ TEST_F(StyleEngineTest, MarkForWhitespaceReattachment) {
Element* d2 = GetDocument().getElementById("d2");
Element* d3 = GetDocument().getElementById("d3");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
d1->firstChild()->remove();
EXPECT_TRUE(GetStyleEngine().NeedsWhitespaceReattachment(d1));
@@ -1520,7 +1565,7 @@ TEST_F(StyleEngineTest, MarkForWhitespaceReattachment) {
GetStyleEngine().MarkForWhitespaceReattachment();
EXPECT_FALSE(GetDocument().ChildNeedsReattachLayoutTree());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
d2->firstChild()->remove();
d2->firstChild()->remove();
@@ -1532,7 +1577,7 @@ TEST_F(StyleEngineTest, MarkForWhitespaceReattachment) {
GetStyleEngine().MarkForWhitespaceReattachment();
EXPECT_FALSE(GetDocument().ChildNeedsReattachLayoutTree());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
d3->firstChild()->remove();
EXPECT_TRUE(GetStyleEngine().NeedsWhitespaceReattachment(d3));
@@ -1551,7 +1596,7 @@ TEST_F(StyleEngineTest, FirstLetterRemoved) {
<div class=fl id=d2><div><span id=f2>BB</span></div></div>
<div class=fl id=d3><div><span id=f3>C<!---->C</span></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* d1 = GetDocument().getElementById("d1");
Element* d2 = GetDocument().getElementById("d2");
@@ -1569,7 +1614,7 @@ TEST_F(StyleEngineTest, FirstLetterRemoved) {
EXPECT_TRUE(d1->ChildNeedsStyleRecalc());
EXPECT_TRUE(fl1->NeedsStyleRecalc());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_FALSE(
ToFirstLetterPseudoElement(d1->GetPseudoElement(kPseudoIdFirstLetter)));
@@ -1585,7 +1630,7 @@ TEST_F(StyleEngineTest, FirstLetterRemoved) {
EXPECT_TRUE(d2->ChildNeedsStyleRecalc());
EXPECT_TRUE(fl2->NeedsStyleRecalc());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_FALSE(
ToFirstLetterPseudoElement(d2->GetPseudoElement(kPseudoIdFirstLetter)));
@@ -1602,11 +1647,73 @@ TEST_F(StyleEngineTest, FirstLetterRemoved) {
EXPECT_TRUE(d3->ChildNeedsStyleRecalc());
EXPECT_TRUE(fl3->NeedsStyleRecalc());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
fl3 = ToFirstLetterPseudoElement(d3->GetPseudoElement(kPseudoIdFirstLetter));
EXPECT_TRUE(fl3);
EXPECT_EQ(f3->lastChild()->GetLayoutObject(),
fl3->RemainingTextLayoutObject());
}
+TEST_F(StyleEngineTest, InitialDataCreation) {
+ UpdateAllLifecyclePhases();
+
+ // There should be no initial data if nothing is registered.
+ EXPECT_FALSE(GetStyleEngine().MaybeCreateAndGetInitialData());
+
+ // After registering, there should be initial data.
+ RegisterProperty(GetDocument(), "--x", "<length>", "10px", false);
+ auto data1 = GetStyleEngine().MaybeCreateAndGetInitialData();
+ EXPECT_TRUE(data1);
+
+ // After a full recalc, we should have the same initial data.
+ GetDocument().body()->SetInnerHTMLFromString(
+ "<style>* { font-size: 1px; } </style>");
+ EXPECT_TRUE(GetDocument().NeedsStyleRecalc());
+ EXPECT_TRUE(GetDocument().ChildNeedsStyleRecalc());
+ UpdateAllLifecyclePhases();
+ auto data2 = GetStyleEngine().MaybeCreateAndGetInitialData();
+ EXPECT_TRUE(data2);
+ EXPECT_EQ(data1, data2);
+
+ // After registering a new property, initial data should be invalidated,
+ // such that the new initial data is different.
+ RegisterProperty(GetDocument(), "--y", "<color>", "black", false);
+ EXPECT_NE(data1, GetStyleEngine().MaybeCreateAndGetInitialData());
+}
+
+TEST_F(StyleEngineTest, CSSSelectorEmptyWhitespaceOnlyFail) {
+ GetDocument().body()->SetInnerHTMLFromString(R"HTML(
+ <style>.match:empty { background-color: red }</style>
+ <div></div>
+ <div> <span></span></div>
+ <div> <!-- -->X</div>
+ <div></div>
+ <div> <!-- --></div>
+ )HTML");
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+
+ EXPECT_FALSE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kCSSSelectorEmptyWhitespaceOnlyFail));
+
+ auto* div_elements = GetDocument().getElementsByTagName("div");
+ ASSERT_TRUE(div_elements);
+ ASSERT_EQ(5u, div_elements->length());
+
+ auto is_counted = [](Element* element) {
+ element->setAttribute(blink::html_names::kClassAttr, "match");
+ element->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ return UseCounter::IsCounted(
+ element->GetDocument(),
+ WebFeature::kCSSSelectorEmptyWhitespaceOnlyFail);
+ };
+
+ EXPECT_FALSE(is_counted(div_elements->item(0)));
+ EXPECT_FALSE(is_counted(div_elements->item(1)));
+ EXPECT_FALSE(is_counted(div_elements->item(2)));
+ EXPECT_FALSE(is_counted(div_elements->item(3)));
+ EXPECT_TRUE(is_counted(div_elements->item(4)));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/style_environment_variables_test.cc b/chromium/third_party/blink/renderer/core/css/style_environment_variables_test.cc
index 455df4b9044..1979b42a684 100644
--- a/chromium/third_party/blink/renderer/core/css/style_environment_variables_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_environment_variables_test.cc
@@ -41,8 +41,6 @@ class StyleEnvironmentVariablesTest : public PageTestBase {
void SetUp() override {
PageTestBase::SetUp();
- RuntimeEnabledFeatures::SetCSSEnvironmentVariablesEnabled(true);
-
// Needed for RecordUseCounter_IgnoreMediaControls.
RuntimeEnabledFeatures::SetModernMediaControlsEnabled(true);
}
@@ -58,7 +56,8 @@ class StyleEnvironmentVariablesTest : public PageTestBase {
void InitializeWithHTML(LocalFrame& frame, const String& html_content) {
// Sets the inner html and runs the document lifecycle.
frame.GetDocument()->body()->SetInnerHTMLFromString(html_content);
- frame.GetDocument()->View()->UpdateAllLifecyclePhases();
+ frame.GetDocument()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
void InitializeTestPageWithVariableNamed(LocalFrame& frame,
@@ -105,7 +104,7 @@ TEST_F(StyleEnvironmentVariablesTest, DocumentVariable_AfterLoad) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the variable.
Element* target = GetDocument().getElementById("target");
@@ -122,7 +121,7 @@ TEST_F(StyleEnvironmentVariablesTest, DocumentVariable_Change) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the variable.
Element* target = GetDocument().getElementById("target");
@@ -148,7 +147,7 @@ TEST_F(StyleEnvironmentVariablesTest,
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the document
// variable.
@@ -160,7 +159,7 @@ TEST_F(StyleEnvironmentVariablesTest,
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the global
// variable.
@@ -185,7 +184,7 @@ TEST_F(StyleEnvironmentVariablesTest, DocumentVariable_Override_RemoveGlobal) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the document
// variable.
@@ -223,7 +222,7 @@ TEST_F(StyleEnvironmentVariablesTest, DocumentVariable_Remove) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element does not have the background color any more.
EXPECT_NE(kTestColorRed, target->ComputedStyleRef().VisitedDependentColor(
@@ -241,7 +240,8 @@ TEST_F(StyleEnvironmentVariablesTest, MultiDocumentInvalidation_FromRoot) {
// Create an empty page that does not use the variable.
std::unique_ptr<DummyPageHolder> empty_page =
DummyPageHolder::Create(IntSize(800, 600));
- empty_page->GetDocument().View()->UpdateAllLifecyclePhases();
+ empty_page->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
StyleEnvironmentVariables::GetRootInstance().SetVariable(kVariableName,
kVariableTestColor);
@@ -287,7 +287,7 @@ TEST_F(StyleEnvironmentVariablesTest, GlobalVariable_AfterLoad) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the variable.
Element* target = GetDocument().getElementById("target");
@@ -306,7 +306,7 @@ TEST_F(StyleEnvironmentVariablesTest, GlobalVariable_Change) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element has the background color provided by the variable.
Element* target = GetDocument().getElementById("target");
@@ -355,7 +355,7 @@ TEST_F(StyleEnvironmentVariablesTest, GlobalVariable_Remove) {
// Ensure that the document has been invalidated.
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the element does not have the background color any more.
EXPECT_NE(kTestColorRed, target->ComputedStyleRef().VisitedDependentColor(
diff --git a/chromium/third_party/blink/renderer/core/css/style_media.h b/chromium/third_party/blink/renderer/core/css/style_media.h
index f5385febe4b..546e6897053 100644
--- a/chromium/third_party/blink/renderer/core/css/style_media.h
+++ b/chromium/third_party/blink/renderer/core/css/style_media.h
@@ -41,15 +41,16 @@ class StyleMedia final : public ScriptWrappable, public ContextClient {
USING_GARBAGE_COLLECTED_MIXIN(StyleMedia);
public:
- static StyleMedia* Create(LocalFrame* frame) { return new StyleMedia(frame); }
+ static StyleMedia* Create(LocalFrame* frame) {
+ return MakeGarbageCollected<StyleMedia>(frame);
+ }
+
+ explicit StyleMedia(LocalFrame*);
AtomicString type() const;
bool matchMedium(const String&) const;
void Trace(blink::Visitor*) override;
-
- private:
- explicit StyleMedia(LocalFrame*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule.cc b/chromium/third_party/blink/renderer/core/css/style_rule.cc
index 4235e4dabd6..6ca909b749e 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_rule.cc
@@ -22,6 +22,8 @@
#include "third_party/blink/renderer/core/css/style_rule.h"
#include "third_party/blink/renderer/core/css/css_font_face_rule.h"
+#include "third_party/blink/renderer/core/css/css_font_feature_values_rule.h"
+#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_import_rule.h"
#include "third_party/blink/renderer/core/css/css_keyframes_rule.h"
#include "third_party/blink/renderer/core/css/css_media_rule.h"
@@ -29,6 +31,7 @@
#include "third_party/blink/renderer/core/css/css_page_rule.h"
#include "third_party/blink/renderer/core/css/css_style_rule.h"
#include "third_party/blink/renderer/core/css/css_supports_rule.h"
+#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/css_viewport_rule.h"
#include "third_party/blink/renderer/core/css/style_rule_import.h"
#include "third_party/blink/renderer/core/css/style_rule_keyframe.h"
@@ -87,6 +90,9 @@ void StyleRuleBase::Trace(blink::Visitor* visitor) {
case kViewport:
ToStyleRuleViewport(this)->TraceAfterDispatch(visitor);
return;
+ case kFontFeatureValues:
+ ToStyleRuleFontFeatureValues(this)->TraceAfterDispatch(visitor);
+ return;
}
NOTREACHED();
}
@@ -126,6 +132,9 @@ void StyleRuleBase::FinalizeGarbageCollectedObject() {
case kViewport:
ToStyleRuleViewport(this)->~StyleRuleViewport();
return;
+ case kFontFeatureValues:
+ ToStyleRuleFontFeatureValues(this)->~StyleRuleFontFeatureValues();
+ return;
}
NOTREACHED();
}
@@ -152,6 +161,8 @@ StyleRuleBase* StyleRuleBase::Copy() const {
return ToStyleRuleViewport(this)->Copy();
case kNamespace:
return ToStyleRuleNamespace(this)->Copy();
+ case kFontFeatureValues:
+ return ToStyleRuleFontFeatureValues(this)->Copy();
case kCharset:
case kKeyframe:
NOTREACHED();
@@ -193,6 +204,10 @@ CSSRule* StyleRuleBase::CreateCSSOMWrapper(CSSStyleSheet* parent_sheet,
case kViewport:
rule = CSSViewportRule::Create(ToStyleRuleViewport(self), parent_sheet);
break;
+ case kFontFeatureValues:
+ rule = CSSFontFeatureValuesRule::Create(
+ ToStyleRuleFontFeatureValues(self), parent_sheet);
+ break;
case kKeyframe:
case kCharset:
NOTREACHED();
@@ -397,4 +412,17 @@ void StyleRuleViewport::TraceAfterDispatch(blink::Visitor* visitor) {
StyleRuleBase::TraceAfterDispatch(visitor);
}
+StyleRuleFontFeatureValues::StyleRuleFontFeatureValues(
+ const CSSValueList* font_family,
+ const CSSIdentifierValue* font_display)
+ : StyleRuleBase(kFontFeatureValues),
+ font_family_(font_family),
+ font_display_(font_display) {}
+
+void StyleRuleFontFeatureValues::TraceAfterDispatch(blink::Visitor* visitor) {
+ visitor->Trace(font_family_);
+ visitor->Trace(font_display_);
+ StyleRuleBase::TraceAfterDispatch(visitor);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule.h b/chromium/third_party/blink/renderer/core/css/style_rule.h
index 7a06d7b72b1..a6488356465 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/style_rule.h
@@ -31,8 +31,10 @@
namespace blink {
+class CSSIdentifierValue;
class CSSRule;
class CSSStyleSheet;
+class CSSValueList;
class CORE_EXPORT StyleRuleBase
: public GarbageCollectedFinalized<StyleRuleBase> {
@@ -49,6 +51,7 @@ class CORE_EXPORT StyleRuleBase
kNamespace,
kSupports,
kViewport,
+ kFontFeatureValues,
};
RuleType GetType() const { return static_cast<RuleType>(type_); }
@@ -64,6 +67,9 @@ class CORE_EXPORT StyleRuleBase
bool IsSupportsRule() const { return GetType() == kSupports; }
bool IsViewportRule() const { return GetType() == kViewport; }
bool IsImportRule() const { return GetType() == kImport; }
+ bool IsFontFeatureValuesRule() const {
+ return GetType() == kFontFeatureValues;
+ }
StyleRuleBase* Copy() const;
@@ -100,13 +106,18 @@ class CORE_EXPORT StyleRule : public StyleRuleBase {
// Adopts the selector list
static StyleRule* Create(CSSSelectorList selector_list,
CSSPropertyValueSet* properties) {
- return new StyleRule(std::move(selector_list), properties);
+ return MakeGarbageCollected<StyleRule>(std::move(selector_list),
+ properties);
}
static StyleRule* CreateLazy(CSSSelectorList selector_list,
CSSLazyPropertyParser* lazy_property_parser) {
- return new StyleRule(std::move(selector_list), lazy_property_parser);
+ return MakeGarbageCollected<StyleRule>(std::move(selector_list),
+ lazy_property_parser);
}
+ StyleRule(CSSSelectorList, CSSPropertyValueSet*);
+ StyleRule(CSSSelectorList, CSSLazyPropertyParser*);
+ StyleRule(const StyleRule&);
~StyleRule();
const CSSSelectorList& SelectorList() const { return selector_list_; }
@@ -117,7 +128,7 @@ class CORE_EXPORT StyleRule : public StyleRuleBase {
selector_list_ = std::move(selectors);
}
- StyleRule* Copy() const { return new StyleRule(*this); }
+ StyleRule* Copy() const { return MakeGarbageCollected<StyleRule>(*this); }
static unsigned AverageSizeInBytes();
@@ -131,10 +142,6 @@ class CORE_EXPORT StyleRule : public StyleRuleBase {
friend class CSSLazyParsingTest;
bool HasParsedProperties() const;
- StyleRule(CSSSelectorList, CSSPropertyValueSet*);
- StyleRule(CSSSelectorList, CSSLazyPropertyParser*);
- StyleRule(const StyleRule&);
-
// Whether or not we should consider this for matching rules. Usually we try
// to avoid considering empty property sets, as an optimization. This is
// not possible for lazy properties, which always need to be considered. The
@@ -154,22 +161,23 @@ class CORE_EXPORT StyleRule : public StyleRuleBase {
class CORE_EXPORT StyleRuleFontFace : public StyleRuleBase {
public:
static StyleRuleFontFace* Create(CSSPropertyValueSet* properties) {
- return new StyleRuleFontFace(properties);
+ return MakeGarbageCollected<StyleRuleFontFace>(properties);
}
+ StyleRuleFontFace(CSSPropertyValueSet*);
+ StyleRuleFontFace(const StyleRuleFontFace&);
~StyleRuleFontFace();
const CSSPropertyValueSet& Properties() const { return *properties_; }
MutableCSSPropertyValueSet& MutableProperties();
- StyleRuleFontFace* Copy() const { return new StyleRuleFontFace(*this); }
+ StyleRuleFontFace* Copy() const {
+ return MakeGarbageCollected<StyleRuleFontFace>(*this);
+ }
void TraceAfterDispatch(blink::Visitor*);
private:
- StyleRuleFontFace(CSSPropertyValueSet*);
- StyleRuleFontFace(const StyleRuleFontFace&);
-
Member<CSSPropertyValueSet> properties_; // Cannot be null.
};
@@ -178,9 +186,12 @@ class StyleRulePage : public StyleRuleBase {
// Adopts the selector list
static StyleRulePage* Create(CSSSelectorList selector_list,
CSSPropertyValueSet* properties) {
- return new StyleRulePage(std::move(selector_list), properties);
+ return MakeGarbageCollected<StyleRulePage>(std::move(selector_list),
+ properties);
}
+ StyleRulePage(CSSSelectorList, CSSPropertyValueSet*);
+ StyleRulePage(const StyleRulePage&);
~StyleRulePage();
const CSSSelector* Selector() const { return selector_list_.First(); }
@@ -191,14 +202,13 @@ class StyleRulePage : public StyleRuleBase {
selector_list_ = std::move(selectors);
}
- StyleRulePage* Copy() const { return new StyleRulePage(*this); }
+ StyleRulePage* Copy() const {
+ return MakeGarbageCollected<StyleRulePage>(*this);
+ }
void TraceAfterDispatch(blink::Visitor*);
private:
- StyleRulePage(CSSSelectorList, CSSPropertyValueSet*);
- StyleRulePage(const StyleRulePage&);
-
Member<CSSPropertyValueSet> properties_; // Cannot be null.
CSSSelectorList selector_list_;
};
@@ -244,20 +254,22 @@ class CORE_EXPORT StyleRuleMedia : public StyleRuleCondition {
static StyleRuleMedia* Create(
scoped_refptr<MediaQuerySet> media,
HeapVector<Member<StyleRuleBase>>& adopt_rules) {
- return new StyleRuleMedia(media, adopt_rules);
+ return MakeGarbageCollected<StyleRuleMedia>(media, adopt_rules);
}
+ StyleRuleMedia(scoped_refptr<MediaQuerySet>,
+ HeapVector<Member<StyleRuleBase>>& adopt_rules);
+ StyleRuleMedia(const StyleRuleMedia&);
+
MediaQuerySet* MediaQueries() const { return media_queries_.get(); }
- StyleRuleMedia* Copy() const { return new StyleRuleMedia(*this); }
+ StyleRuleMedia* Copy() const {
+ return MakeGarbageCollected<StyleRuleMedia>(*this);
+ }
void TraceAfterDispatch(blink::Visitor*);
private:
- StyleRuleMedia(scoped_refptr<MediaQuerySet>,
- HeapVector<Member<StyleRuleBase>>& adopt_rules);
- StyleRuleMedia(const StyleRuleMedia&);
-
scoped_refptr<MediaQuerySet> media_queries_;
};
@@ -267,23 +279,25 @@ class StyleRuleSupports : public StyleRuleCondition {
const String& condition_text,
bool condition_is_supported,
HeapVector<Member<StyleRuleBase>>& adopt_rules) {
- return new StyleRuleSupports(condition_text, condition_is_supported,
- adopt_rules);
+ return MakeGarbageCollected<StyleRuleSupports>(
+ condition_text, condition_is_supported, adopt_rules);
}
+ StyleRuleSupports(const String& condition_text,
+ bool condition_is_supported,
+ HeapVector<Member<StyleRuleBase>>& adopt_rules);
+ StyleRuleSupports(const StyleRuleSupports&);
+
bool ConditionIsSupported() const { return condition_is_supported_; }
- StyleRuleSupports* Copy() const { return new StyleRuleSupports(*this); }
+ StyleRuleSupports* Copy() const {
+ return MakeGarbageCollected<StyleRuleSupports>(*this);
+ }
void TraceAfterDispatch(blink::Visitor* visitor) {
StyleRuleCondition::TraceAfterDispatch(visitor);
}
private:
- StyleRuleSupports(const String& condition_text,
- bool condition_is_supported,
- HeapVector<Member<StyleRuleBase>>& adopt_rules);
- StyleRuleSupports(const StyleRuleSupports&);
-
String condition_text_;
bool condition_is_supported_;
};
@@ -291,35 +305,68 @@ class StyleRuleSupports : public StyleRuleCondition {
class StyleRuleViewport : public StyleRuleBase {
public:
static StyleRuleViewport* Create(CSSPropertyValueSet* properties) {
- return new StyleRuleViewport(properties);
+ return MakeGarbageCollected<StyleRuleViewport>(properties);
}
+ StyleRuleViewport(CSSPropertyValueSet*);
+ StyleRuleViewport(const StyleRuleViewport&);
~StyleRuleViewport();
const CSSPropertyValueSet& Properties() const { return *properties_; }
MutableCSSPropertyValueSet& MutableProperties();
- StyleRuleViewport* Copy() const { return new StyleRuleViewport(*this); }
+ StyleRuleViewport* Copy() const {
+ return MakeGarbageCollected<StyleRuleViewport>(*this);
+ }
void TraceAfterDispatch(blink::Visitor*);
private:
- StyleRuleViewport(CSSPropertyValueSet*);
- StyleRuleViewport(const StyleRuleViewport&);
-
Member<CSSPropertyValueSet> properties_; // Cannot be null
};
// This should only be used within the CSS Parser
class StyleRuleCharset : public StyleRuleBase {
public:
- static StyleRuleCharset* Create() { return new StyleRuleCharset(); }
+ static StyleRuleCharset* Create() {
+ return MakeGarbageCollected<StyleRuleCharset>();
+ }
+
+ StyleRuleCharset() : StyleRuleBase(kCharset) {}
void TraceAfterDispatch(blink::Visitor* visitor) {
StyleRuleBase::TraceAfterDispatch(visitor);
}
private:
- StyleRuleCharset() : StyleRuleBase(kCharset) {}
+};
+
+class CORE_EXPORT StyleRuleFontFeatureValues : public StyleRuleBase {
+ public:
+ static StyleRuleFontFeatureValues* Create(
+ const CSSValueList* font_family,
+ const CSSIdentifierValue* font_display) {
+ return new StyleRuleFontFeatureValues(font_family, font_display);
+ }
+
+ StyleRuleFontFeatureValues* Copy() const {
+ return new StyleRuleFontFeatureValues(*this);
+ }
+
+ const CSSValueList& FontFamily() const {
+ DCHECK(font_family_);
+ return *font_family_;
+ }
+ const CSSIdentifierValue* FontDisplay() const { return font_display_; }
+
+ void TraceAfterDispatch(blink::Visitor*);
+
+ private:
+ StyleRuleFontFeatureValues(const CSSValueList* font_family,
+ const CSSIdentifierValue* font_display);
+ StyleRuleFontFeatureValues(const StyleRuleFontFeatureValues&) = default;
+
+ Member<const CSSValueList> font_family_;
+ Member<const CSSIdentifierValue> font_display_;
};
#define DEFINE_STYLE_RULE_TYPE_CASTS(Type) \
@@ -337,6 +384,7 @@ DEFINE_STYLE_RULE_TYPE_CASTS(Media);
DEFINE_STYLE_RULE_TYPE_CASTS(Supports);
DEFINE_STYLE_RULE_TYPE_CASTS(Viewport);
DEFINE_STYLE_RULE_TYPE_CASTS(Charset);
+DEFINE_STYLE_RULE_TYPE_CASTS(FontFeatureValues);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.h b/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.h
index 618b296f702..255798dea7f 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.h
@@ -39,17 +39,18 @@ class StyleRuleCSSStyleDeclaration : public PropertySetCSSStyleDeclaration {
static StyleRuleCSSStyleDeclaration* Create(
MutableCSSPropertyValueSet& property_set,
CSSRule* parent_rule) {
- return new StyleRuleCSSStyleDeclaration(property_set, parent_rule);
+ return MakeGarbageCollected<StyleRuleCSSStyleDeclaration>(property_set,
+ parent_rule);
}
+ StyleRuleCSSStyleDeclaration(MutableCSSPropertyValueSet&, CSSRule*);
+ ~StyleRuleCSSStyleDeclaration() override;
+
void Reattach(MutableCSSPropertyValueSet&);
void Trace(blink::Visitor*) override;
protected:
- StyleRuleCSSStyleDeclaration(MutableCSSPropertyValueSet&, CSSRule*);
- ~StyleRuleCSSStyleDeclaration() override;
-
CSSStyleSheet* ParentStyleSheet() const override;
CSSRule* parentRule() const override { return parent_rule_; }
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule_import.cc b/chromium/third_party/blink/renderer/core/css/style_rule_import.cc
index 05e833ba58e..c53f60348eb 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule_import.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_rule_import.cc
@@ -34,14 +34,14 @@ namespace blink {
StyleRuleImport* StyleRuleImport::Create(const String& href,
scoped_refptr<MediaQuerySet> media) {
- return new StyleRuleImport(href, media);
+ return MakeGarbageCollected<StyleRuleImport>(href, media);
}
StyleRuleImport::StyleRuleImport(const String& href,
scoped_refptr<MediaQuerySet> media)
: StyleRuleBase(kImport),
parent_style_sheet_(nullptr),
- style_sheet_client_(new ImportedStyleSheetClient(this)),
+ style_sheet_client_(MakeGarbageCollected<ImportedStyleSheetClient>(this)),
str_href_(href),
media_queries_(media),
loading_(false) {
@@ -134,7 +134,7 @@ void StyleRuleImport::RequestStyleSheet() {
}
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::css;
+ options.initiator_info.name = fetch_initiator_type_names::kCSS;
FetchParameters params(ResourceRequest(abs_url), options);
params.SetCharset(parent_style_sheet_->Charset());
loading_ = true;
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule_import.h b/chromium/third_party/blink/renderer/core/css/style_rule_import.h
index 4e90a9cf5ef..0e2189468ff 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule_import.h
+++ b/chromium/third_party/blink/renderer/core/css/style_rule_import.h
@@ -38,6 +38,7 @@ class StyleRuleImport : public StyleRuleBase {
static StyleRuleImport* Create(const String& href,
scoped_refptr<MediaQuerySet>);
+ StyleRuleImport(const String& href, scoped_refptr<MediaQuerySet>);
~StyleRuleImport();
StyleSheetContents* ParentStyleSheet() const { return parent_style_sheet_; }
@@ -89,8 +90,6 @@ class StyleRuleImport : public StyleRuleBase {
void NotifyFinished(Resource*);
- StyleRuleImport(const String& href, scoped_refptr<MediaQuerySet>);
-
void Dispose();
Member<StyleSheetContents> parent_style_sheet_;
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule_keyframe.h b/chromium/third_party/blink/renderer/core/css/style_rule_keyframe.h
index 0f33b88069c..bf0ac2f383b 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule_keyframe.h
+++ b/chromium/third_party/blink/renderer/core/css/style_rule_keyframe.h
@@ -17,9 +17,11 @@ class StyleRuleKeyframe final : public StyleRuleBase {
public:
static StyleRuleKeyframe* Create(std::unique_ptr<Vector<double>> keys,
CSSPropertyValueSet* properties) {
- return new StyleRuleKeyframe(std::move(keys), properties);
+ return MakeGarbageCollected<StyleRuleKeyframe>(std::move(keys), properties);
}
+ StyleRuleKeyframe(std::unique_ptr<Vector<double>>, CSSPropertyValueSet*);
+
// Exposed to JavaScript.
String KeyText() const;
bool SetKeyText(const String&);
@@ -35,8 +37,6 @@ class StyleRuleKeyframe final : public StyleRuleBase {
void TraceAfterDispatch(blink::Visitor*);
private:
- StyleRuleKeyframe(std::unique_ptr<Vector<double>>, CSSPropertyValueSet*);
-
Member<CSSPropertyValueSet> properties_;
Vector<double> keys_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule_namespace.h b/chromium/third_party/blink/renderer/core/css/style_rule_namespace.h
index 8a0208b7965..bebb5e0148d 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule_namespace.h
+++ b/chromium/third_party/blink/renderer/core/css/style_rule_namespace.h
@@ -14,11 +14,14 @@ namespace blink {
class StyleRuleNamespace final : public StyleRuleBase {
public:
static StyleRuleNamespace* Create(AtomicString prefix, AtomicString uri) {
- return new StyleRuleNamespace(prefix, uri);
+ return MakeGarbageCollected<StyleRuleNamespace>(prefix, uri);
}
+ StyleRuleNamespace(AtomicString prefix, AtomicString uri)
+ : StyleRuleBase(kNamespace), prefix_(prefix), uri_(uri) {}
+
StyleRuleNamespace* Copy() const {
- return new StyleRuleNamespace(prefix_, uri_);
+ return MakeGarbageCollected<StyleRuleNamespace>(prefix_, uri_);
}
AtomicString Prefix() const { return prefix_; }
@@ -29,9 +32,6 @@ class StyleRuleNamespace final : public StyleRuleBase {
}
private:
- StyleRuleNamespace(AtomicString prefix, AtomicString uri)
- : StyleRuleBase(kNamespace), prefix_(prefix), uri_(uri) {}
-
AtomicString prefix_;
AtomicString uri_;
};
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_candidate.cc b/chromium/third_party/blink/renderer/core/css/style_sheet_candidate.cc
index 5bd16a9accb..321f00c166e 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_candidate.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_candidate.cc
@@ -37,10 +37,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
AtomicString StyleSheetCandidate::Title() const {
- return IsElement() ? ToElement(GetNode()).FastGetAttribute(titleAttr)
+ return IsElement() ? ToElement(GetNode()).FastGetAttribute(kTitleAttr)
: g_null_atom;
}
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_collection.h b/chromium/third_party/blink/renderer/core/css/style_sheet_collection.h
index b8fd00326a9..bc47cfb4f84 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_collection.h
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_collection.h
@@ -50,7 +50,11 @@ class CORE_EXPORT StyleSheetCollection
friend class ActiveDocumentStyleSheetCollector;
friend class ImportedDocumentStyleSheetCollector;
- static StyleSheetCollection* Create() { return new StyleSheetCollection; }
+ static StyleSheetCollection* Create() {
+ return MakeGarbageCollected<StyleSheetCollection>();
+ }
+
+ StyleSheetCollection();
const ActiveStyleSheetVector& ActiveAuthorStyleSheets() const {
return active_author_style_sheets_;
@@ -74,8 +78,6 @@ class CORE_EXPORT StyleSheetCollection
void Dispose();
protected:
- StyleSheetCollection();
-
HeapVector<TraceWrapperMember<StyleSheet>> style_sheets_for_style_sheet_list_;
ActiveStyleSheetVector active_author_style_sheets_;
bool sheet_list_dirty_ = true;
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_contents.cc b/chromium/third_party/blink/renderer/core/css/style_sheet_contents.cc
index 0725d4d71d7..2338cc7a86b 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_contents.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_contents.cc
@@ -332,8 +332,9 @@ const AtomicString& StyleSheetContents::NamespaceURIFromPrefix(
void StyleSheetContents::ParseAuthorStyleSheet(
const CSSStyleSheetResource* cached_style_sheet,
const SecurityOrigin* security_origin) {
- TRACE_EVENT1("blink,devtools.timeline", "ParseAuthorStyleSheet", "data",
- InspectorParseAuthorStyleSheetEvent::Data(cached_style_sheet));
+ TRACE_EVENT1(
+ "blink,devtools.timeline", "ParseAuthorStyleSheet", "data",
+ inspector_parse_author_style_sheet_event::Data(cached_style_sheet));
TimeTicks start_time = CurrentTimeTicks();
bool is_same_origin_request =
@@ -360,10 +361,10 @@ void StyleSheetContents::ParseAuthorStyleSheet(
cached_style_sheet->SheetText(parser_context_, mime_type_check);
const ResourceResponse& response = cached_style_sheet->GetResponse();
- source_map_url_ = response.HttpHeaderField(HTTPNames::SourceMap);
+ source_map_url_ = response.HttpHeaderField(http_names::kSourceMap);
if (source_map_url_.IsEmpty()) {
// Try to get deprecated header.
- source_map_url_ = response.HttpHeaderField(HTTPNames::X_SourceMap);
+ source_map_url_ = response.HttpHeaderField(http_names::kXSourceMap);
}
const CSSParserContext* context =
@@ -535,6 +536,7 @@ static bool ChildRulesHaveFailedOrCanceledSubresources(
case StyleRuleBase::kKeyframe:
case StyleRuleBase::kSupports:
case StyleRuleBase::kViewport:
+ case StyleRuleBase::kFontFeatureValues:
break;
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_contents.h b/chromium/third_party/blink/renderer/core/css/style_sheet_contents.h
index acf61566509..81e515579dd 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_contents.h
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_contents.h
@@ -50,20 +50,27 @@ class CORE_EXPORT StyleSheetContents
: public GarbageCollectedFinalized<StyleSheetContents> {
public:
static StyleSheetContents* Create(const CSSParserContext* context) {
- return new StyleSheetContents(nullptr, String(), context);
+ return MakeGarbageCollected<StyleSheetContents>(nullptr, String(), context);
}
static StyleSheetContents* Create(const String& original_url,
const CSSParserContext* context) {
- return new StyleSheetContents(nullptr, original_url, context);
+ return MakeGarbageCollected<StyleSheetContents>(nullptr, original_url,
+ context);
}
static StyleSheetContents* Create(StyleRuleImport* owner_rule,
const String& original_url,
const CSSParserContext* context) {
- return new StyleSheetContents(owner_rule, original_url, context);
+ return MakeGarbageCollected<StyleSheetContents>(owner_rule, original_url,
+ context);
}
static const Document* SingleOwnerDocument(const StyleSheetContents*);
+ StyleSheetContents(StyleRuleImport* owner_rule,
+ const String& original_url,
+ const CSSParserContext*);
+ StyleSheetContents(const StyleSheetContents&);
+ StyleSheetContents() = delete;
~StyleSheetContents();
const CSSParserContext* ParserContext() const { return parser_context_; }
@@ -174,7 +181,9 @@ class CORE_EXPORT StyleSheetContents
bool WrapperInsertRule(StyleRuleBase*, unsigned index);
bool WrapperDeleteRule(unsigned index);
- StyleSheetContents* Copy() const { return new StyleSheetContents(*this); }
+ StyleSheetContents* Copy() const {
+ return MakeGarbageCollected<StyleSheetContents>(*this);
+ }
void RegisterClient(CSSStyleSheet*);
void UnregisterClient(CSSStyleSheet*);
@@ -214,11 +223,6 @@ class CORE_EXPORT StyleSheetContents
void Trace(blink::Visitor*);
private:
- StyleSheetContents(StyleRuleImport* owner_rule,
- const String& original_url,
- const CSSParserContext*);
- StyleSheetContents(const StyleSheetContents&);
- StyleSheetContents() = delete;
StyleSheetContents& operator=(const StyleSheetContents&) = delete;
void NotifyRemoveFontFaceRule(const StyleRuleFontFace*);
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_contents_fuzzer.cc b/chromium/third_party/blink/renderer/core/css/style_sheet_contents_fuzzer.cc
index 1921cf6c6bc..374f2aa783d 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_contents_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_contents_fuzzer.cc
@@ -27,13 +27,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
styleSheet->ParseString(String::FromUTF8WithLatin1Fallback(
reinterpret_cast<const char*>(data), size));
-#if defined(ADDRESS_SANITIZER)
- // LSAN needs unreachable objects to be released to avoid reporting them
- // incorrectly as a memory leak.
- blink::ThreadState* currentThreadState = blink::ThreadState::Current();
- currentThreadState->CollectAllGarbage();
-#endif
-
return 0;
}
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_contents_test.cc b/chromium/third_party/blink/renderer/core/css/style_sheet_contents_test.cc
index e884bbdab91..4bbf05458f8 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_contents_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_contents_test.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_list.cc b/chromium/third_party/blink/renderer/core/css/style_sheet_list.cc
index 3045da40df5..2990d6a88b3 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_list.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_list.cc
@@ -29,11 +29,9 @@
namespace blink {
-using namespace HTMLNames;
-
StyleSheetList* StyleSheetList::Create() {
DCHECK(RuntimeEnabledFeatures::ConstructableStylesheetsEnabled());
- return new StyleSheetList();
+ return MakeGarbageCollected<StyleSheetList>();
}
StyleSheetList* StyleSheetList::Create(
@@ -43,7 +41,7 @@ StyleSheetList* StyleSheetList::Create(
exception_state.ThrowTypeError("Illegal constructor");
return nullptr;
}
- return new StyleSheetList(style_sheet_vector);
+ return MakeGarbageCollected<StyleSheetList>(style_sheet_vector);
}
StyleSheetList::StyleSheetList(
diff --git a/chromium/third_party/blink/renderer/core/css/style_sheet_list.h b/chromium/third_party/blink/renderer/core/css/style_sheet_list.h
index 3ec4f37a496..4533e7cda07 100644
--- a/chromium/third_party/blink/renderer/core/css/style_sheet_list.h
+++ b/chromium/third_party/blink/renderer/core/css/style_sheet_list.h
@@ -42,9 +42,13 @@ class CORE_EXPORT StyleSheetList final : public ScriptWrappable {
ExceptionState&);
static StyleSheetList* Create(TreeScope* tree_scope) {
- return new StyleSheetList(tree_scope);
+ return MakeGarbageCollected<StyleSheetList>(tree_scope);
}
+ explicit StyleSheetList(const HeapVector<Member<CSSStyleSheet>>&);
+ explicit StyleSheetList(TreeScope*);
+ StyleSheetList() {}
+
unsigned length();
StyleSheet* item(unsigned index);
@@ -59,9 +63,6 @@ class CORE_EXPORT StyleSheetList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit StyleSheetList(const HeapVector<Member<CSSStyleSheet>>&);
- explicit StyleSheetList(TreeScope*);
- StyleSheetList() {}
const HeapVector<TraceWrapperMember<StyleSheet>>& StyleSheets() const;
Member<TreeScope> tree_scope_;
diff --git a/chromium/third_party/blink/renderer/core/css/style_traversal_root_test.cc b/chromium/third_party/blink/renderer/core/css/style_traversal_root_test.cc
index d74387881c5..ca8c7277e56 100644
--- a/chromium/third_party/blink/renderer/core/css/style_traversal_root_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_traversal_root_test.cc
@@ -49,9 +49,9 @@ class StyleTraversalRootTest : public testing::Test {
enum ElementIndex { kA, kB, kC, kD, kE, kF, kG, kElementCount };
void SetUp() final {
document_ = Document::CreateForTest();
- elements_ = new HeapVector<Member<Element>, 7>;
+ elements_ = MakeGarbageCollected<HeapVector<Member<Element>, 7>>();
for (size_t i = 0; i < kElementCount; i++) {
- elements_->push_back(GetDocument().CreateRawElement(HTMLNames::divTag));
+ elements_->push_back(GetDocument().CreateRawElement(html_names::kDivTag));
}
GetDocument().appendChild(DivElement(kA));
DivElement(kA)->appendChild(DivElement(kB));
diff --git a/chromium/third_party/blink/renderer/core/css/threaded/css_parser_threaded_test.cc b/chromium/third_party/blink/renderer/core/css/threaded/css_parser_threaded_test.cc
index 679d1af4a87..83e290f8064 100644
--- a/chromium/third_party/blink/renderer/core/css/threaded/css_parser_threaded_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/threaded/css_parser_threaded_test.cc
@@ -6,9 +6,9 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/threaded/css_to_length_conversion_data_threaded_test.cc b/chromium/third_party/blink/renderer/core/css/threaded/css_to_length_conversion_data_threaded_test.cc
index 916e7e79fde..afa544e0650 100644
--- a/chromium/third_party/blink/renderer/core/css/threaded/css_to_length_conversion_data_threaded_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/threaded/css_to_length_conversion_data_threaded_test.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/threaded/font_object_threaded_test.cc b/chromium/third_party/blink/renderer/core/css/threaded/font_object_threaded_test.cc
index c3351970cce..a22eac0d5db 100644
--- a/chromium/third_party/blink/renderer/core/css/threaded/font_object_threaded_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/threaded/font_object_threaded_test.cc
@@ -130,16 +130,16 @@ TSAN_TEST(FontObjectThreadedTest, WordShaperTest) {
CachingWordShapeIterator iter(&cache, text_run, &font);
ASSERT_TRUE(iter.Next(&result));
- EXPECT_EQ(0u, result->StartIndexForResult());
- EXPECT_EQ(3u, result->EndIndexForResult());
+ EXPECT_EQ(0u, result->StartIndex());
+ EXPECT_EQ(3u, result->EndIndex());
ASSERT_TRUE(iter.Next(&result));
- EXPECT_EQ(0u, result->StartIndexForResult());
- EXPECT_EQ(1u, result->EndIndexForResult());
+ EXPECT_EQ(0u, result->StartIndex());
+ EXPECT_EQ(1u, result->EndIndex());
ASSERT_TRUE(iter.Next(&result));
- EXPECT_EQ(0u, result->StartIndexForResult());
- EXPECT_EQ(4u, result->EndIndexForResult());
+ EXPECT_EQ(0u, result->StartIndex());
+ EXPECT_EQ(4u, result->EndIndex());
ASSERT_FALSE(iter.Next(&result));
});
diff --git a/chromium/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h b/chromium/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h
index c97cdc47cfd..b0e022ff97c 100644
--- a/chromium/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h
+++ b/chromium/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h
@@ -12,10 +12,10 @@
#include "base/single_thread_task_runner.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
diff --git a/chromium/third_party/blink/renderer/core/display_lock/BUILD.gn b/chromium/third_party/blink/renderer/core/display_lock/BUILD.gn
index 85c2a605643..d6cce9bb2ba 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/display_lock/BUILD.gn
@@ -8,6 +8,8 @@ blink_core_sources("display_lock") {
sources = [
"display_lock_context.cc",
"display_lock_context.h",
+ "display_lock_suspended_handle.cc",
+ "display_lock_suspended_handle.h",
]
public_deps = [
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.cc
index fd35164e8dd..386b85b0106 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.cc
@@ -3,16 +3,439 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
+
#include "third_party/blink/renderer/bindings/core/v8/v8_display_lock_callback.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
+#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "third_party/blink/renderer/core/page/page.h"
+#include "third_party/blink/renderer/platform/bindings/microtask.h"
namespace blink {
-DisplayLockContext::~DisplayLockContext() {}
+// Change this to 1 to enable each function stderr logging.
+// TODO(vmpstr): Remove this after debugging is all done.
+#if 0
+class CORE_EXPORT DisplayLockScopedLogger {
+ public:
+ DisplayLockScopedLogger(const char* function,
+ const DisplayLockContext::State* state,
+ const DisplayLockContext::LifecycleUpdateState* lifecycle_update_state)
+ : function_(function), state_(state), lifecycle_update_state_(lifecycle_update_state) {
+ for (int i = 0; i < s_indent_; ++i)
+ fprintf(stderr, " ");
+ fprintf(stderr, "entering %s: state %s lifecycle_update_state %s\n",
+ function, StateToString(*state),
+ LifecycleUpdateStateToString(*lifecycle_update_state));
+ ++s_indent_;
+ }
+
+ ~DisplayLockScopedLogger() {
+ --s_indent_;
+ for (int i = 0; i < s_indent_; ++i)
+ fprintf(stderr, " ");
+ fprintf(stderr, "exiting %s: state %s lifecycle_update_state %s\n",
+ function_, StateToString(*state_),
+ LifecycleUpdateStateToString(*lifecycle_update_state_));
+ }
+
+ private:
+ const char* StateToString(DisplayLockContext::State state) {
+ switch (state) {
+ case DisplayLockContext::kUninitialized:
+ return "kUninitialized";
+ case DisplayLockContext::kSuspended:
+ return "kSuspended";
+ case DisplayLockContext::kCallbacksPending:
+ return "kCallbacksPending";
+ case DisplayLockContext::kDisconnected:
+ return "kDisconnected";
+ case DisplayLockContext::kCommitting:
+ return "kCommitting";
+ case DisplayLockContext::kResolving:
+ return "kResolving";
+ case DisplayLockContext::kResolved:
+ return "kResolved";
+ }
+ return "<unknown>";
+ };
+
+ const char* LifecycleUpdateStateToString(
+ DisplayLockContext::LifecycleUpdateState state) {
+ switch (state) {
+ case DisplayLockContext::kNeedsStyle:
+ return "kNeedsStyle";
+ case DisplayLockContext::kNeedsLayout:
+ return "kNeedsLayout";
+ case DisplayLockContext::kNeedsPrePaint:
+ return "kNeedsPrePaint";
+ case DisplayLockContext::kNeedsPaint:
+ return "kNeedsPaint";
+ case DisplayLockContext::kDone:
+ return "kDone";
+ }
+ return "<unknown>";
+ }
+
+ const char* function_;
+ const DisplayLockContext::State* state_;
+ const DisplayLockContext::LifecycleUpdateState* lifecycle_update_state_;
+ static int s_indent_;
+};
+
+int DisplayLockScopedLogger::s_indent_ = 0;
+
+#define SCOPED_LOGGER(func) \
+ DisplayLockScopedLogger logger(func, &state_, &lifecycle_update_state_)
+#else
+#define SCOPED_LOGGER(func)
+#endif // #if 0
+
+DisplayLockContext::DisplayLockContext(Element* element,
+ ExecutionContext* context)
+ : ContextLifecycleObserver(context), element_(element) {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+}
+
+DisplayLockContext::~DisplayLockContext() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ DCHECK(state_ == kResolved || state_ == kSuspended) << state_;
+ DCHECK(callbacks_.IsEmpty());
+}
+
+void DisplayLockContext::Trace(blink::Visitor* visitor) {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ visitor->Trace(callbacks_);
+ visitor->Trace(resolver_);
+ visitor->Trace(element_);
+ ScriptWrappable::Trace(visitor);
+ ActiveScriptWrappable::Trace(visitor);
+ ContextLifecycleObserver::Trace(visitor);
+}
+
+void DisplayLockContext::Dispose() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ RejectAndCleanUp();
+}
+
+void DisplayLockContext::ContextDestroyed(ExecutionContext*) {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ RejectAndCleanUp();
+}
-void DisplayLockContext::Dispose() {}
+bool DisplayLockContext::HasPendingActivity() const {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ // If we haven't resolved it, we should stick around.
+ return !IsResolved();
+}
+
+void DisplayLockContext::ScheduleCallback(V8DisplayLockCallback* callback) {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ callbacks_.push_back(callback);
+
+ // Suspended state supercedes any new lock requests.
+ if (state_ == kSuspended)
+ return;
+ state_ = kCallbacksPending;
+
+ ScheduleTaskIfNeeded();
+}
+
+void DisplayLockContext::RequestLock(V8DisplayLockCallback* callback,
+ ScriptState* script_state) {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (!resolver_) {
+ DCHECK(script_state);
+ resolver_ = ScriptPromiseResolver::Create(script_state);
+ }
+ ScheduleCallback(callback);
+}
void DisplayLockContext::schedule(V8DisplayLockCallback* callback) {
- callback->InvokeAndReportException(nullptr, this);
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ DCHECK(state_ == kSuspended || state_ == kCallbacksPending);
+
+ ScheduleCallback(callback);
+}
+
+DisplayLockSuspendedHandle* DisplayLockContext::suspend() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ ++suspended_count_;
+ state_ = kSuspended;
+ return new DisplayLockSuspendedHandle(this);
+}
+
+Element* DisplayLockContext::lockedElement() const {
+ return element_;
+}
+
+void DisplayLockContext::ProcessQueue() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ // It's important to clear this before running the tasks, since the tasks can
+ // call ScheduleCallback() which will re-schedule a PostTask() for us to
+ // continue the work.
+ process_queue_task_scheduled_ = false;
+
+ // If we're not in callbacks pending, then we shouldn't run anything at the
+ // moment.
+ if (state_ != kCallbacksPending)
+ return;
+
+ // Get a local copy of all the tasks we will run.
+ // TODO(vmpstr): This should possibly be subject to a budget instead.
+ HeapVector<Member<V8DisplayLockCallback>> callbacks;
+ callbacks.swap(callbacks_);
+
+ for (auto& callback : callbacks) {
+ DCHECK(callback);
+ {
+ // A re-implementation of InvokeAndReportException, in order for us to
+ // be able to query |try_catch| to determine whether or not we need to
+ // reject our promise.
+ v8::TryCatch try_catch(callback->GetIsolate());
+ try_catch.SetVerbose(true);
+
+ auto result = callback->Invoke(nullptr, this);
+ ALLOW_UNUSED_LOCAL(result);
+ if (try_catch.HasCaught()) {
+ RejectAndCleanUp();
+ // We should run the checkpoint here, since the rejection callback (for
+ // the promise rejected in RejectAndCleanUp()) may modify DOM which
+ // should happen here, as opposed to after a potential lifecycle update
+ // (or whenever the next microtask checkpoint is going to happen).
+ Microtask::PerformCheckpoint(callback->GetIsolate());
+ return;
+ }
+ }
+ }
+
+ if (callbacks_.IsEmpty() && state_ != kSuspended) {
+ if (element_->isConnected()) {
+ StartCommit();
+ } else {
+ state_ = kDisconnected;
+ }
+ }
+}
+
+void DisplayLockContext::RejectAndCleanUp() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (resolver_) {
+ state_ = kResolved;
+ resolver_->Reject();
+ resolver_ = nullptr;
+ }
+ callbacks_.clear();
+
+ // We may have a dirty subtree and have not propagated the dirty bit up the
+ // ancestor tree. Since we're now rejecting the promise and unlocking the
+ // element, ensure that we can reach both style and layout subtrees if they
+ // are dirty by propagating the bit.
+ MarkAncestorsForStyleRecalcIfNeeded();
+ MarkAncestorsForLayoutIfNeeded();
+}
+
+void DisplayLockContext::Resume() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ DCHECK_GT(suspended_count_, 0u);
+ DCHECK_EQ(state_, kSuspended);
+ if (--suspended_count_ == 0) {
+ // When becoming unsuspended here are the possible transitions:
+ // - If there are callbacks to run, then pending callbacks
+ // - If we're not connected, then we're soft suspended, ie disconnected.
+ // - Otherwise, we can start committing.
+ if (!callbacks_.IsEmpty()) {
+ state_ = kCallbacksPending;
+ } else if (element_->isConnected()) {
+ StartCommit();
+ } else {
+ state_ = kDisconnected;
+ }
+ }
+ ScheduleTaskIfNeeded();
+}
+
+void DisplayLockContext::NotifyWillNotResume() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ DCHECK_GT(suspended_count_, 0u);
+ // The promise will never reject or resolve since we're now indefinitely
+ // suspended.
+ // TODO(vmpstr): We should probably issue a console warning.
+ // We keep the state as suspended.
+ DCHECK_EQ(state_, kSuspended);
+ resolver_->Detach();
+ resolver_ = nullptr;
+}
+
+void DisplayLockContext::ScheduleTaskIfNeeded() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (state_ != kCallbacksPending || process_queue_task_scheduled_)
+ return;
+
+ DCHECK(GetExecutionContext());
+ DCHECK(GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI));
+ GetExecutionContext()
+ ->GetTaskRunner(TaskType::kMiscPlatformAPI)
+ ->PostTask(FROM_HERE, WTF::Bind(&DisplayLockContext::ProcessQueue,
+ WrapWeakPersistent(this)));
+ process_queue_task_scheduled_ = true;
+}
+
+void DisplayLockContext::NotifyConnectedMayHaveChanged() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (element_->isConnected()) {
+ if (state_ == kDisconnected)
+ StartCommit();
+ return;
+ }
+ // All other states should remain as they are. Specifically, if we're
+ // acquiring the lock then we should finish doing so; if we're resolving, then
+ // we should finish that as well.
+ if (state_ == kCommitting)
+ state_ = kDisconnected;
+}
+
+bool DisplayLockContext::ShouldStyle() const {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ return state_ >= kCommitting;
+}
+
+void DisplayLockContext::DidStyle() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (state_ != kCommitting)
+ return;
+
+ // We must have contain: content for display locking.
+ auto* style = element_->GetComputedStyle();
+ if (!style || !style->ContainsContent()) {
+ RejectAndCleanUp();
+ return;
+ }
+
+ if (lifecycle_update_state_ <= kNeedsStyle) {
+ // Normally we need to do layout next, but if it's not dirty then we can
+ // skip ahead to pre-paint.
+ if (MarkAncestorsForLayoutIfNeeded())
+ lifecycle_update_state_ = kNeedsLayout;
+ else
+ lifecycle_update_state_ = kNeedsPrePaint;
+ }
+}
+
+bool DisplayLockContext::ShouldLayout() const {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ return std::tie(state_, lifecycle_update_state_) >=
+ std::tuple<State, LifecycleUpdateState>{kCommitting, kNeedsLayout};
+}
+
+void DisplayLockContext::DidLayout() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (state_ != kCommitting)
+ return;
+
+ if (lifecycle_update_state_ <= kNeedsLayout)
+ lifecycle_update_state_ = kNeedsPrePaint;
+}
+
+bool DisplayLockContext::ShouldPrePaint() const {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ return std::tie(state_, lifecycle_update_state_) >=
+ std::tuple<State, LifecycleUpdateState>{kCommitting, kNeedsPrePaint};
+}
+
+void DisplayLockContext::DidPrePaint() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (state_ != kCommitting)
+ return;
+
+ // Since we should be under containment, we should have a layer. If we don't,
+ // then paint might not happen and we'll never resolve.
+ DCHECK(element_->GetLayoutObject()->HasLayer());
+ if (lifecycle_update_state_ <= kNeedsPrePaint)
+ lifecycle_update_state_ = kNeedsPaint;
+}
+
+bool DisplayLockContext::ShouldPaint() const {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ return std::tie(state_, lifecycle_update_state_) >=
+ std::tuple<State, LifecycleUpdateState>{kCommitting, kNeedsPaint};
+}
+
+void DisplayLockContext::DidPaint() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (state_ != kCommitting)
+ return;
+
+ if (lifecycle_update_state_ <= kNeedsPaint)
+ lifecycle_update_state_ = kDone;
+
+ DCHECK(resolver_);
+ state_ = kResolving;
+ resolver_->Resolve();
+ resolver_ = nullptr;
+
+ // After the above resolution callback runs (in a microtask), we should
+ // finish resolving if the lock was not re-acquired.
+ Microtask::EnqueueMicrotask(WTF::Bind(&DisplayLockContext::FinishResolution,
+ WrapWeakPersistent(this)));
+}
+
+void DisplayLockContext::DidAttachLayoutTree() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+
+ // Note that although we checked at style recalc time that the element has
+ // "contain: content", it might not actually apply the containment (e.g. see
+ // ShouldApplyContentContainment()). This confirms that containment should
+ // apply.
+ auto* layout_object = element_->GetLayoutObject();
+ if (!layout_object || !layout_object->ShouldApplyContentContainment())
+ RejectAndCleanUp();
+}
+
+void DisplayLockContext::FinishResolution() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ if (state_ == kResolving)
+ state_ = kResolved;
+}
+
+void DisplayLockContext::StartCommit() {
+ SCOPED_LOGGER(__PRETTY_FUNCTION__);
+ state_ = kCommitting;
+ lifecycle_update_state_ = kNeedsStyle;
+
+ if (!MarkAncestorsForStyleRecalcIfNeeded())
+ DidStyle();
+
+ // The above DidStyle() may reject the promise since it checks that we have
+ // containment before proceeding.
+ if (state_ != kCommitting)
+ return;
+
+ // Schedule an animation to perform the lifecycle phases.
+ element_->GetDocument().GetPage()->Animator().ScheduleVisualUpdate(
+ element_->GetDocument().GetFrame());
+}
+
+bool DisplayLockContext::MarkAncestorsForStyleRecalcIfNeeded() {
+ if (element_->NeedsStyleRecalc() || element_->ChildNeedsStyleRecalc()) {
+ element_->MarkAncestorsWithChildNeedsStyleRecalc();
+ return true;
+ }
+ return false;
+}
+
+bool DisplayLockContext::MarkAncestorsForLayoutIfNeeded() {
+ if (auto* layout_object = element_->GetLayoutObject()) {
+ if (layout_object->NeedsLayout()) {
+ layout_object->MarkContainerChainForLayout();
+ return true;
+ }
+ }
+ return false;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.h b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.h
index 0d4087bf4b1..64019e8e0cd 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.h
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.h
@@ -5,22 +5,147 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_CONTEXT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_CONTEXT_H_
+#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
namespace blink {
+class DisplayLockSuspendedHandle;
+class Element;
class V8DisplayLockCallback;
-class CORE_EXPORT DisplayLockContext final : public ScriptWrappable {
+class DisplayLockScopedLogger;
+class CORE_EXPORT DisplayLockContext final
+ : public ScriptWrappable,
+ public ActiveScriptWrappable<DisplayLockContext>,
+ public ContextLifecycleObserver {
DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(DisplayLockContext);
public:
- DisplayLockContext() = default;
+ // Conceptually the states are private, but made public for debugging /
+ // logging.
+ enum State {
+ kUninitialized,
+ kSuspended,
+ kCallbacksPending,
+ kDisconnected,
+ kCommitting,
+ kResolving,
+ kResolved
+ };
+
+ enum LifecycleUpdateState {
+ kNeedsStyle,
+ kNeedsLayout,
+ kNeedsPrePaint,
+ kNeedsPaint,
+ kDone
+ };
+
+ DisplayLockContext(Element*, ExecutionContext*);
~DisplayLockContext() override;
+ // GC functions.
+ void Trace(blink::Visitor*) override;
void Dispose();
+ // ContextLifecycleObserver overrides.
+ void ContextDestroyed(ExecutionContext*) override;
+ // ActiveScriptWrappable overrides. If there is an outstanding task scheduled
+ // to process the callback queue, then this return true.
+ // TODO(vmpstr): In the future this would also be true while we're doing
+ // co-operative work.
+ bool HasPendingActivity() const final;
+
+ // Notify that the lock was requested. Note that for a new context, this has
+ // to be called first. For an existing lock, this will either extend the
+ // lifetime of the current lock, or start acquiring a new lock (depending on
+ // whether this lock is active or passive).
+ void RequestLock(V8DisplayLockCallback*, ScriptState*);
+
+ // Returns true if the promise associated with this context was already
+ // resolved (or rejected).
+ bool IsResolved() const { return state_ == kResolved; }
+
+ // Returns a ScriptPromise associated with this context.
+ ScriptPromise Promise() const {
+ DCHECK(resolver_);
+ return resolver_->Promise();
+ }
+
+ // Called when the connected state may have changed.
+ void NotifyConnectedMayHaveChanged();
+
+ // Rejects the associated promise if one exists, and clears the current queue.
+ // This effectively makes the context finalized.
+ void RejectAndCleanUp();
+
+ // JavaScript interface implementation.
void schedule(V8DisplayLockCallback*);
+ DisplayLockSuspendedHandle* suspend();
+ Element* lockedElement() const;
+
+ // Lifecycle observation / state functions.
+ bool ShouldStyle() const;
+ void DidStyle();
+ bool ShouldLayout() const;
+ void DidLayout();
+ bool ShouldPrePaint() const;
+ void DidPrePaint();
+ bool ShouldPaint() const;
+ void DidPaint();
+
+ void DidAttachLayoutTree();
+
+ private:
+ friend class DisplayLockSuspendedHandle;
+
+ // Schedules a new callback. If this is the first callback to be scheduled,
+ // then a valid ScriptState must be provided, which will be used to create a
+ // new ScriptPromiseResolver. In other cases, the ScriptState is ignored.
+ void ScheduleCallback(V8DisplayLockCallback*);
+
+ // Processes the current queue of callbacks.
+ void ProcessQueue();
+
+ // Called by the suspended handle in order to resume context operations.
+ void Resume();
+
+ // Called by the suspended handle informing us that it was disposed without
+ // resuming, meaning it will never resume.
+ void NotifyWillNotResume();
+
+ // Schedule a task if one is required. Specifically, this would schedule a
+ // task if one was not already scheduled and if we need to either process
+ // callbacks or to resolve the associated promise.
+ void ScheduleTaskIfNeeded();
+
+ // A function that finishes resolving the promise by establishing a microtask
+ // checkpoint. Note that this should be scheduled after entering the
+ // kResolving state. If the state is still kResolving after the microtask
+ // checkpoint finishes (ie, the lock was not re-acquired), we enter the final
+ // kResolved state.
+ void FinishResolution();
+
+ // Initiate a commit.
+ void StartCommit();
+
+ // The following functions propagate dirty bits from the locked element up to
+ // the ancestors in order to be reached. They return true if the element or
+ // its subtree were dirty, and false otherwise.
+ bool MarkAncestorsForStyleRecalcIfNeeded();
+ bool MarkAncestorsForLayoutIfNeeded();
+
+ HeapVector<Member<V8DisplayLockCallback>> callbacks_;
+ Member<ScriptPromiseResolver> resolver_;
+ Member<Element> element_;
+
+ bool process_queue_task_scheduled_ = false;
+ unsigned suspended_count_ = 0;
+ State state_ = kUninitialized;
+ LifecycleUpdateState lifecycle_update_state_ = kNeedsStyle;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.idl b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.idl
index 67171c7e782..40cd8b5ea01 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.idl
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context.idl
@@ -2,8 +2,20 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-[RuntimeEnabled=DisplayLocking] callback DisplayLockCallback = void(DisplayLockContext context);
-[RuntimeEnabled=DisplayLocking] interface DisplayLockContext {
+[RuntimeEnabled=DisplayLocking]
+callback DisplayLockCallback = void(DisplayLockContext context);
+
+[RuntimeEnabled=DisplayLocking, ActiveScriptWrappable]
+interface DisplayLockContext {
+ // Schedule continuation work for this context. Multiple calls are allowed and
+ // will run in the order scheduled.
void schedule(DisplayLockCallback callback);
-};
+ // Suspend the context, preventing the lock from being released. Multiple
+ // calls to suspend are allowed: in order to resume the context, resume() must
+ // be called on each of the returned DisplayLockSuspendedHandles.
+ DisplayLockSuspendedHandle suspend();
+
+ // Represents the element on which this locked has been acquired.
+ [SameObject, Affects=Nothing] readonly attribute Element lockedElement;
+};
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.cc
new file mode 100644
index 00000000000..85a36b8ac86
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.cc
@@ -0,0 +1,40 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
+
+namespace blink {
+
+DisplayLockSuspendedHandle::DisplayLockSuspendedHandle(
+ DisplayLockContext* context)
+ : context_(context) {}
+
+DisplayLockSuspendedHandle::~DisplayLockSuspendedHandle() {}
+
+void DisplayLockSuspendedHandle::Trace(blink::Visitor* visitor) {
+ ScriptWrappable::Trace(visitor);
+ visitor->Trace(context_);
+}
+
+void DisplayLockSuspendedHandle::Dispose() {
+ // If we're disposing the handle and we still have a valid reference to the
+ // context, it means that this handle was never resumed. In turn, this means
+ // that we will never resume the context. We should inform the context of
+ // this.
+ // TODO(vmpstr): It is possible that we want to resume the context on dispose,
+ // making gc observable from script. If that's the case, this should be
+ // changed to instead resume the context.
+ if (context_)
+ context_->NotifyWillNotResume();
+ context_ = nullptr;
+}
+
+void DisplayLockSuspendedHandle::resume() {
+ if (context_)
+ context_->Resume();
+ context_ = nullptr;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.h b/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.h
new file mode 100644
index 00000000000..9e96daba140
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.h
@@ -0,0 +1,34 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_SUSPENDED_HANDLE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_SUSPENDED_HANDLE_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+
+namespace blink {
+
+class DisplayLockContext;
+class CORE_EXPORT DisplayLockSuspendedHandle final : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ DisplayLockSuspendedHandle(DisplayLockContext* context);
+ ~DisplayLockSuspendedHandle() override;
+
+ // GC functions.
+ void Trace(blink::Visitor*) override;
+ void Dispose();
+
+ // JavaScript interface implementation.
+ void resume();
+
+ private:
+ WeakMember<DisplayLockContext> context_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_SUSPENDED_HANDLE_H_
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.idl b/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.idl
new file mode 100644
index 00000000000..0b4dc90e6d2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_suspended_handle.idl
@@ -0,0 +1,8 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[RuntimeEnabled=DisplayLocking] interface DisplayLockSuspendedHandle {
+ void resume();
+};
+
diff --git a/chromium/third_party/blink/renderer/core/dom/BUILD.gn b/chromium/third_party/blink/renderer/core/dom/BUILD.gn
index a2dbb33214b..b9b40b4a345 100644
--- a/chromium/third_party/blink/renderer/core/dom/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/dom/BUILD.gn
@@ -139,6 +139,8 @@ blink_core_sources("dom") {
"events/window_event_context.h",
"first_letter_pseudo_element.cc",
"first_letter_pseudo_element.h",
+ "flat_tree_node_data.cc",
+ "flat_tree_node_data.h",
"flat_tree_traversal.cc",
"flat_tree_traversal.h",
"frame_request_callback_collection.cc",
diff --git a/chromium/third_party/blink/renderer/core/dom/abort_signal.cc b/chromium/third_party/blink/renderer/core/dom/abort_signal.cc
index 49b7a502ce7..b1774cbaf12 100644
--- a/chromium/third_party/blink/renderer/core/dom/abort_signal.cc
+++ b/chromium/third_party/blink/renderer/core/dom/abort_signal.cc
@@ -23,7 +23,7 @@ AbortSignal::AbortSignal(ExecutionContext* execution_context)
AbortSignal::~AbortSignal() = default;
const AtomicString& AbortSignal::InterfaceName() const {
- return EventTargetNames::AbortSignal;
+ return event_target_names::kAbortSignal;
}
ExecutionContext* AbortSignal::GetExecutionContext() const {
@@ -44,7 +44,7 @@ void AbortSignal::SignalAbort() {
std::move(closure).Run();
}
abort_algorithms_.clear();
- DispatchEvent(*Event::Create(EventTypeNames::abort));
+ DispatchEvent(*Event::Create(event_type_names::kAbort));
}
void AbortSignal::Follow(AbortSignal* parentSignal) {
diff --git a/chromium/third_party/blink/renderer/core/dom/abort_signal.h b/chromium/third_party/blink/renderer/core/dom/abort_signal.h
index 23cadde9933..65b7563ab06 100644
--- a/chromium/third_party/blink/renderer/core/dom/abort_signal.h
+++ b/chromium/third_party/blink/renderer/core/dom/abort_signal.h
@@ -26,7 +26,7 @@ class CORE_EXPORT AbortSignal final : public EventTargetWithInlineData {
// abort_signal.idl
bool aborted() const { return aborted_flag_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
diff --git a/chromium/third_party/blink/renderer/core/dom/attr.cc b/chromium/third_party/blink/renderer/core/dom/attr.cc
index 25afd5d818b..392a07f3fbc 100644
--- a/chromium/third_party/blink/renderer/core/dom/attr.cc
+++ b/chromium/third_party/blink/renderer/core/dom/attr.cc
@@ -34,8 +34,6 @@
namespace blink {
-using namespace HTMLNames;
-
Attr::Attr(Element& element, const QualifiedName& name)
: Node(&element.GetDocument(), kCreateOther),
element_(&element),
diff --git a/chromium/third_party/blink/renderer/core/dom/character_data.cc b/chromium/third_party/blink/renderer/core/dom/character_data.cc
index 8530b0e823e..aef50d33ebc 100644
--- a/chromium/third_party/blink/renderer/core/dom/character_data.cc
+++ b/chromium/third_party/blink/renderer/core/dom/character_data.cc
@@ -164,8 +164,8 @@ String CharacterData::nodeValue() const {
return data_;
}
-bool CharacterData::ContainsOnlyWhitespace() const {
- return data_.ContainsOnlyWhitespace();
+bool CharacterData::ContainsOnlyWhitespaceOrEmpty() const {
+ return data_.ContainsOnlyWhitespaceOrEmpty();
}
void CharacterData::setNodeValue(const String& node_value) {
@@ -216,7 +216,7 @@ void CharacterData::DidModifyData(const String& old_data, UpdateSource source) {
if (GetDocument().HasListenerType(
Document::kDOMCharacterDataModifiedListener)) {
DispatchScopedEvent(*MutationEvent::Create(
- EventTypeNames::DOMCharacterDataModified, Event::Bubbles::kYes,
+ event_type_names::kDOMCharacterDataModified, Event::Bubbles::kYes,
nullptr, old_data, data_));
}
DispatchSubtreeModifiedEvent();
diff --git a/chromium/third_party/blink/renderer/core/dom/character_data.h b/chromium/third_party/blink/renderer/core/dom/character_data.h
index 745f963895a..456e8409798 100644
--- a/chromium/third_party/blink/renderer/core/dom/character_data.h
+++ b/chromium/third_party/blink/renderer/core/dom/character_data.h
@@ -50,7 +50,7 @@ class CORE_EXPORT CharacterData : public Node {
void insertData(unsigned offset, const String&, ExceptionState&);
void deleteData(unsigned offset, unsigned count, ExceptionState&);
- bool ContainsOnlyWhitespace() const;
+ bool ContainsOnlyWhitespaceOrEmpty() const;
StringImpl* DataImpl() { return data_.Impl(); }
diff --git a/chromium/third_party/blink/renderer/core/dom/child_list_mutation_scope.cc b/chromium/third_party/blink/renderer/core/dom/child_list_mutation_scope.cc
index 5413c5ee09a..f377fc47895 100644
--- a/chromium/third_party/blink/renderer/core/dom/child_list_mutation_scope.cc
+++ b/chromium/third_party/blink/renderer/core/dom/child_list_mutation_scope.cc
@@ -46,7 +46,8 @@ typedef HeapHashMap<Member<Node>, Member<ChildListMutationAccumulator>>
AccumulatorMap;
static AccumulatorMap& GetAccumulatorMap() {
- DEFINE_STATIC_LOCAL(Persistent<AccumulatorMap>, map, (new AccumulatorMap));
+ DEFINE_STATIC_LOCAL(Persistent<AccumulatorMap>, map,
+ (MakeGarbageCollected<AccumulatorMap>()));
return *map;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/container_node.cc b/chromium/third_party/blink/renderer/core/dom/container_node.cc
index f94b4d22d1e..cce4bc210c6 100644
--- a/chromium/third_party/blink/renderer/core/dom/container_node.cc
+++ b/chromium/third_party/blink/renderer/core/dom/container_node.cc
@@ -63,8 +63,6 @@
namespace blink {
-using namespace HTMLNames;
-
static void DispatchChildInsertionEvents(Node&);
static void DispatchChildRemovalEvents(Node&);
@@ -282,7 +280,8 @@ bool ContainerNode::EnsurePreInsertionValidity(
}
// We need this extra structural check because prior DOM mutation operations
-// dispatched synchronous events, and their handlers might modified DOM trees.
+// dispatched synchronous events, so their handlers may have modified DOM
+// trees.
bool ContainerNode::RecheckNodeInsertionStructuralPrereq(
const NodeVector& new_children,
const Node* next,
@@ -622,13 +621,13 @@ void ContainerNode::WillRemoveChild(Node& child) {
DispatchChildRemovalEvents(child);
ChildFrameDisconnector(child).Disconnect();
if (GetDocument() != child.GetDocument()) {
- // |child| was moved another document by DOM mutation event handler.
+ // |child| was moved to another document by the DOM mutation event handler.
return;
}
// |nodeWillBeRemoved()| must be run after |ChildFrameDisconnector|, because
- // |ChildFrameDisconnector| can run script which may cause state that is to
- // be invalidated by removing the node.
+ // |ChildFrameDisconnector| may remove the node, resulting in an invalid
+ // state.
ScriptForbiddenScope script_forbidden_scope;
EventDispatchForbiddenScope assert_no_event_dispatch;
// e.g. mutation event listener can create a new range.
@@ -728,11 +727,8 @@ void ContainerNode::RemoveBetween(Node* previous_child,
DCHECK_EQ(old_child.parentNode(), this);
- if (!old_child.NeedsAttach()) {
- AttachContext context;
- context.clear_invalidation = true;
- old_child.DetachLayoutTree(context);
- }
+ if (!old_child.NeedsAttach())
+ old_child.DetachLayoutTree();
if (next_child)
next_child->SetPreviousSibling(previous_child);
@@ -955,6 +951,20 @@ void ContainerNode::NotifyNodeRemoved(Node& root) {
}
}
+void ContainerNode::RemovedFrom(ContainerNode& insertion_point) {
+ if (isConnected()) {
+ if (NeedsStyleInvalidation()) {
+ GetDocument()
+ .GetStyleEngine()
+ .GetPendingNodeInvalidations()
+ .ClearInvalidation(*this);
+ ClearNeedsStyleInvalidation();
+ }
+ ClearChildNeedsStyleInvalidation();
+ }
+ Node::RemovedFrom(insertion_point);
+}
+
#if DCHECK_IS_ON()
namespace {
@@ -995,11 +1005,8 @@ void ContainerNode::AttachLayoutTree(AttachContext& context) {
}
void ContainerNode::DetachLayoutTree(const AttachContext& context) {
- AttachContext children_context(context);
- children_context.clear_invalidation = true;
-
for (Node* child = firstChild(); child; child = child->nextSibling())
- child->DetachLayoutTree(children_context);
+ child->DetachLayoutTree(context);
SetChildNeedsStyleRecalc();
Node::DetachLayoutTree(context);
@@ -1043,7 +1050,7 @@ void ContainerNode::FocusStateChanged() {
SetNeedsStyleRecalc(
change_type,
StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_focus));
+ style_change_reason::kPseudoClass, style_change_extra_data::g_focus));
if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByFocus())
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoFocus);
@@ -1062,8 +1069,8 @@ void ContainerNode::FocusVisibleStateChanged() {
: kLocalStyleChange;
SetNeedsStyleRecalc(change_type,
StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass,
- StyleChangeExtraData::g_focus_visible));
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_focus_visible));
if (IsElementNode() &&
ToElement(this)->ChildrenOrSiblingsAffectedByFocusVisible())
@@ -1078,8 +1085,8 @@ void ContainerNode::FocusWithinStateChanged() {
: kLocalStyleChange;
SetNeedsStyleRecalc(change_type,
StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass,
- StyleChangeExtraData::g_focus_within));
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_focus_within));
}
if (IsElementNode() &&
ToElement(this)->ChildrenOrSiblingsAffectedByFocusWithin())
@@ -1116,13 +1123,14 @@ void ContainerNode::SetFocused(bool received, WebFocusType focus_type) {
// If :focus sets display: none, we lose focus but still need to recalc our
// style.
- if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByFocus())
+ if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByFocus()) {
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoFocus);
- else
- SetNeedsStyleRecalc(
- kLocalStyleChange,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_focus));
+ } else {
+ SetNeedsStyleRecalc(kLocalStyleChange,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_focus));
+ }
if (RuntimeEnabledFeatures::CSSFocusVisibleEnabled()) {
if (IsElementNode() &&
@@ -1131,8 +1139,8 @@ void ContainerNode::SetFocused(bool received, WebFocusType focus_type) {
} else {
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass,
- StyleChangeExtraData::g_focus_visible));
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_focus_visible));
}
}
@@ -1142,8 +1150,8 @@ void ContainerNode::SetFocused(bool received, WebFocusType focus_type) {
} else {
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass,
- StyleChangeExtraData::g_focus_within));
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_focus_within));
}
}
@@ -1163,13 +1171,14 @@ void ContainerNode::SetActive(bool down) {
if (!GetLayoutObject()) {
if (IsElementNode() &&
- ToElement(this)->ChildrenOrSiblingsAffectedByActive())
+ ToElement(this)->ChildrenOrSiblingsAffectedByActive()) {
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoActive);
- else
- SetNeedsStyleRecalc(
- kLocalStyleChange,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_active));
+ } else {
+ SetNeedsStyleRecalc(kLocalStyleChange,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_active));
+ }
return;
}
@@ -1178,10 +1187,10 @@ void ContainerNode::SetActive(bool down) {
GetComputedStyle()->HasPseudoStyle(kPseudoIdFirstLetter)
? kSubtreeStyleChange
: kLocalStyleChange;
- SetNeedsStyleRecalc(
- change_type,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_active));
+ SetNeedsStyleRecalc(change_type,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_active));
}
if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByActive())
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoActive);
@@ -1200,13 +1209,16 @@ void ContainerNode::SetDragged(bool new_value) {
if (!GetLayoutObject()) {
if (new_value)
return;
- if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByDrag())
+ if (IsElementNode() &&
+ ToElement(this)->ChildrenOrSiblingsAffectedByDrag()) {
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoDrag);
- else
- SetNeedsStyleRecalc(
- kLocalStyleChange,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_drag));
+
+ } else {
+ SetNeedsStyleRecalc(kLocalStyleChange,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_drag));
+ }
return;
}
@@ -1215,10 +1227,10 @@ void ContainerNode::SetDragged(bool new_value) {
GetComputedStyle()->HasPseudoStyle(kPseudoIdFirstLetter)
? kSubtreeStyleChange
: kLocalStyleChange;
- SetNeedsStyleRecalc(
- change_type,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_drag));
+ SetNeedsStyleRecalc(change_type,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_drag));
}
if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByDrag())
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoDrag);
@@ -1235,10 +1247,10 @@ void ContainerNode::SetHovered(bool over) {
StyleChangeType change_type = kLocalStyleChange;
if (style && style->HasPseudoStyle(kPseudoIdFirstLetter))
change_type = kSubtreeStyleChange;
- SetNeedsStyleRecalc(
- change_type,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_hover));
+ SetNeedsStyleRecalc(change_type,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_hover));
}
if (IsElementNode() && ToElement(this)->ChildrenOrSiblingsAffectedByHover())
ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoHover);
@@ -1305,7 +1317,7 @@ static void DispatchChildInsertionEvents(Node& child) {
if (c->parentNode() &&
document->HasListenerType(Document::kDOMNodeInsertedListener)) {
c->DispatchScopedEvent(
- *MutationEvent::Create(EventTypeNames::DOMNodeInserted,
+ *MutationEvent::Create(event_type_names::kDOMNodeInserted,
Event::Bubbles::kYes, c->parentNode()));
}
@@ -1314,7 +1326,7 @@ static void DispatchChildInsertionEvents(Node& child) {
Document::kDOMNodeInsertedIntoDocumentListener)) {
for (; c; c = NodeTraversal::Next(*c, &child)) {
c->DispatchScopedEvent(*MutationEvent::Create(
- EventTypeNames::DOMNodeInsertedIntoDocument, Event::Bubbles::kNo));
+ event_type_names::kDOMNodeInsertedIntoDocument, Event::Bubbles::kNo));
}
}
}
@@ -1347,8 +1359,9 @@ static void DispatchChildRemovalEvents(Node& child) {
Document::InDOMNodeRemovedHandlerState::kDOMNodeRemoved);
}
NodeChildRemovalTracker scope(child);
- c->DispatchScopedEvent(*MutationEvent::Create(
- EventTypeNames::DOMNodeRemoved, Event::Bubbles::kYes, c->parentNode()));
+ c->DispatchScopedEvent(
+ *MutationEvent::Create(event_type_names::kDOMNodeRemoved,
+ Event::Bubbles::kYes, c->parentNode()));
document.SetInDOMNodeRemovedHandlerState(original_document_state);
c->SetInDOMNodeRemovedHandler(original_node_flag);
}
@@ -1369,7 +1382,7 @@ static void DispatchChildRemovalEvents(Node& child) {
NodeChildRemovalTracker scope(child);
for (; c; c = NodeTraversal::Next(*c, &child)) {
c->DispatchScopedEvent(*MutationEvent::Create(
- EventTypeNames::DOMNodeRemovedFromDocument, Event::Bubbles::kNo));
+ event_type_names::kDOMNodeRemovedFromDocument, Event::Bubbles::kNo));
}
document.SetInDOMNodeRemovedHandlerState(original_document_state);
child.SetInDOMNodeRemovedHandler(original_node_flag);
diff --git a/chromium/third_party/blink/renderer/core/dom/container_node.h b/chromium/third_party/blink/renderer/core/dom/container_node.h
index ebb81ac43ea..afb12644d32 100644
--- a/chromium/third_party/blink/renderer/core/dom/container_node.h
+++ b/chromium/third_party/blink/renderer/core/dom/container_node.h
@@ -158,6 +158,7 @@ class CORE_EXPORT ContainerNode : public Node {
void SetActive(bool = true) override;
void SetDragged(bool) override;
void SetHovered(bool = true) override;
+ void RemovedFrom(ContainerNode& insertion_point) override;
bool ChildrenOrSiblingsAffectedByFocus() const {
return HasRestyleFlag(
diff --git a/chromium/third_party/blink/renderer/core/dom/context_features_client_impl.cc b/chromium/third_party/blink/renderer/core/dom/context_features_client_impl.cc
index bde295e4d08..69f26b6058b 100644
--- a/chromium/third_party/blink/renderer/core/dom/context_features_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/dom/context_features_client_impl.cc
@@ -30,8 +30,8 @@
#include "third_party/blink/renderer/core/dom/context_features_client_impl.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
diff --git a/chromium/third_party/blink/renderer/core/dom/dataset_dom_string_map.h b/chromium/third_party/blink/renderer/core/dom/dataset_dom_string_map.h
index bb1c800a842..998d8f7a1bb 100644
--- a/chromium/third_party/blink/renderer/core/dom/dataset_dom_string_map.h
+++ b/chromium/third_party/blink/renderer/core/dom/dataset_dom_string_map.h
@@ -36,9 +36,11 @@ class ExceptionState;
class DatasetDOMStringMap final : public DOMStringMap {
public:
static DatasetDOMStringMap* Create(Element* element) {
- return new DatasetDOMStringMap(element);
+ return MakeGarbageCollected<DatasetDOMStringMap>(element);
}
+ explicit DatasetDOMStringMap(Element* element) : element_(element) {}
+
void GetNames(Vector<String>&) override;
String item(const String& name) override;
bool Contains(const String& name) override;
@@ -50,8 +52,6 @@ class DatasetDOMStringMap final : public DOMStringMap {
void Trace(blink::Visitor*) override;
private:
- explicit DatasetDOMStringMap(Element* element) : element_(element) {}
-
Member<Element> element_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/document.cc b/chromium/third_party/blink/renderer/core/dom/document.cc
index 7ba01ff026e..ca5e41dc1be 100644
--- a/chromium/third_party/blink/renderer/core/dom/document.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document.cc
@@ -46,13 +46,14 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/ukm.mojom-blink.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_prerendering_support.h"
#include "third_party/blink/renderer/bindings/core/v8/html_script_element_or_svg_script_element.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
-#include "third_party/blink/renderer/bindings/core/v8/string_or_dictionary.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_element_creation_options.h"
#include "third_party/blink/renderer/bindings/core/v8/usv_string_or_trusted_url.h"
#include "third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_element_creation_options.h"
@@ -119,6 +120,7 @@
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/slot_assignment.h"
#include "third_party/blink/renderer/core/dom/slot_assignment_engine.h"
+#include "third_party/blink/renderer/core/dom/slot_assignment_recalc_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/static_node_list.h"
#include "third_party/blink/renderer/core/dom/transform_source.h"
#include "third_party/blink/renderer/core/dom/tree_walker.h"
@@ -136,7 +138,6 @@
#include "third_party/blink/renderer/core/events/visual_viewport_resize_event.h"
#include "third_party/blink/renderer/core/events/visual_viewport_scroll_event.h"
#include "third_party/blink/renderer/core/feature_policy/document_policy.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/dom_timer.h"
#include "third_party/blink/renderer/core/frame/dom_visual_viewport.h"
@@ -265,11 +266,11 @@
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/date_components.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/language.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
@@ -277,6 +278,7 @@
#include "third_party/blink/renderer/platform/plugins/plugin_script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_or_worker_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/weborigin/origin_access_entry.h"
@@ -298,7 +300,7 @@ static WeakDocumentSet& liveDocumentSet();
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class DocumentOutliveTimeReporter : public BlinkGCObserver {
public:
@@ -411,10 +413,10 @@ static inline bool IsValidNameStart(UChar32 c) {
// rules (a) and (f) above
const uint32_t kNameStartMask =
- WTF::Unicode::kLetter_Lowercase | WTF::Unicode::kLetter_Uppercase |
- WTF::Unicode::kLetter_Other | WTF::Unicode::kLetter_Titlecase |
- WTF::Unicode::kNumber_Letter;
- if (!(WTF::Unicode::Category(c) & kNameStartMask))
+ WTF::unicode::kLetter_Lowercase | WTF::unicode::kLetter_Uppercase |
+ WTF::unicode::kLetter_Other | WTF::unicode::kLetter_Titlecase |
+ WTF::unicode::kNumber_Letter;
+ if (!(WTF::unicode::Category(c) & kNameStartMask))
return false;
// rule (c) above
@@ -422,10 +424,10 @@ static inline bool IsValidNameStart(UChar32 c) {
return false;
// rule (d) above
- WTF::Unicode::CharDecompositionType decomp_type =
- WTF::Unicode::DecompositionType(c);
- if (decomp_type == WTF::Unicode::kDecompositionFont ||
- decomp_type == WTF::Unicode::kDecompositionCompat)
+ WTF::unicode::CharDecompositionType decomp_type =
+ WTF::unicode::DecompositionType(c);
+ if (decomp_type == WTF::unicode::kDecompositionFont ||
+ decomp_type == WTF::unicode::kDecompositionCompat)
return false;
return true;
@@ -446,10 +448,10 @@ static inline bool IsValidNamePart(UChar32 c) {
// rules (b) and (f) above
const uint32_t kOtherNamePartMask =
- WTF::Unicode::kMark_NonSpacing | WTF::Unicode::kMark_Enclosing |
- WTF::Unicode::kMark_SpacingCombining | WTF::Unicode::kLetter_Modifier |
- WTF::Unicode::kNumber_DecimalDigit;
- if (!(WTF::Unicode::Category(c) & kOtherNamePartMask))
+ WTF::unicode::kMark_NonSpacing | WTF::unicode::kMark_Enclosing |
+ WTF::unicode::kMark_SpacingCombining | WTF::unicode::kLetter_Modifier |
+ WTF::unicode::kNumber_DecimalDigit;
+ if (!(WTF::unicode::Category(c) & kOtherNamePartMask))
return false;
// rule (c) above
@@ -457,10 +459,10 @@ static inline bool IsValidNamePart(UChar32 c) {
return false;
// rule (d) above
- WTF::Unicode::CharDecompositionType decomp_type =
- WTF::Unicode::DecompositionType(c);
- if (decomp_type == WTF::Unicode::kDecompositionFont ||
- decomp_type == WTF::Unicode::kDecompositionCompat)
+ WTF::unicode::CharDecompositionType decomp_type =
+ WTF::unicode::DecompositionType(c);
+ if (decomp_type == WTF::unicode::kDecompositionFont ||
+ decomp_type == WTF::unicode::kDecompositionCompat)
return false;
return true;
@@ -539,14 +541,6 @@ static void RunAutofocusTask(ExecutionContext* context) {
}
}
-static void RecordLoadReasonToHistogram(WouldLoadReason reason) {
- // TODO(dcheng): Make EnumerationHistogram work with scoped enums.
- DEFINE_STATIC_LOCAL(EnumerationHistogram, unseen_frame_histogram,
- ("Navigation.DeferredDocumentLoading.StatesV4",
- static_cast<int>(WouldLoadReason::kCount)));
- unseen_frame_histogram.Count(static_cast<int>(reason));
-}
-
class Document::NetworkStateObserver final
: public GarbageCollectedFinalized<Document::NetworkStateObserver>,
public NetworkStateNotifier::NetworkStateObserver,
@@ -562,7 +556,7 @@ class Document::NetworkStateObserver final
void OnLineStateChange(bool on_line) override {
AtomicString event_name =
- on_line ? EventTypeNames::online : EventTypeNames::offline;
+ on_line ? event_type_names::kOnline : event_type_names::kOffline;
Document* document = To<Document>(GetExecutionContext());
if (!document->domWindow())
return;
@@ -589,11 +583,11 @@ class Document::NetworkStateObserver final
};
Document* Document::CreateForTest() {
- return new Document(DocumentInit::Create());
+ return MakeGarbageCollected<Document>(DocumentInit::Create());
}
Document* Document::Create(Document& document) {
- Document* new_document = new Document(
+ Document* new_document = MakeGarbageCollected<Document>(
DocumentInit::Create().WithContextDocument(&document).WithURL(
BlankURL()));
new_document->SetSecurityOrigin(document.GetMutableSecurityOrigin());
@@ -605,6 +599,7 @@ Document::Document(const DocumentInit& initializer,
DocumentClassFlags document_classes)
: ContainerNode(nullptr, kCreateDocument),
TreeScope(*this),
+ ExecutionContext(V8PerIsolateData::MainThreadIsolate()),
has_nodes_with_placeholder_style_(false),
evaluate_media_queries_on_style_recalc_(false),
pending_sheet_layout_(kNoLayoutWithPendingSheets),
@@ -639,7 +634,7 @@ Document::Document(const DocumentInit& initializer,
ignore_destructive_write_count_(0),
throw_on_dynamic_markup_insertion_count_(0),
ignore_opens_during_unload_count_(0),
- markers_(new DocumentMarkerController(*this)),
+ markers_(MakeGarbageCollected<DocumentMarkerController>(*this)),
update_focus_appearance_timer_(
GetTaskRunner(TaskType::kInternalUserInteraction),
this,
@@ -680,8 +675,9 @@ Document::Document(const DocumentInit& initializer,
this,
&Document::ElementDataCacheClearTimerFired),
timeline_(DocumentTimeline::Create(this)),
- pending_animations_(new PendingAnimations(*this)),
- worklet_animation_controller_(new WorkletAnimationController(this)),
+ pending_animations_(MakeGarbageCollected<PendingAnimations>(*this)),
+ worklet_animation_controller_(
+ MakeGarbageCollected<WorkletAnimationController>(this)),
template_document_host_(nullptr),
did_associate_form_controls_timer_(
GetTaskRunner(TaskType::kInternalLoading),
@@ -691,7 +687,6 @@ Document::Document(const DocumentInit& initializer,
has_viewport_units_(false),
parser_sync_policy_(kAllowAsynchronousParsing),
node_count_(0),
- would_load_reason_(WouldLoadReason::kInvalid),
password_count_(0),
logged_field_edit_(false),
secure_context_state_(SecureContextState::kUnknown),
@@ -700,8 +695,10 @@ Document::Document(const DocumentInit& initializer,
slot_assignment_recalc_forbidden_recursion_depth_(0),
#endif
needs_to_record_ukm_outlive_time_(false),
- viewport_data_(new ViewportData(*this)),
- agent_cluster_id_(base::UnguessableToken::Create()) {
+ viewport_data_(MakeGarbageCollected<ViewportData>(*this)),
+ agent_cluster_id_(base::UnguessableToken::Create()),
+ parsed_feature_policies_(
+ static_cast<int>(mojom::FeaturePolicyFeature::kMaxValue) + 1) {
if (frame_) {
DCHECK(frame_->GetPage());
ProvideContextFeaturesToDocumentFrom(*this, *frame_->GetPage());
@@ -852,6 +849,10 @@ Location* Document::location() const {
return domWindow()->location();
}
+bool Document::ShouldInstallV8Extensions() const {
+ return frame_->Client()->AllowScriptExtensions();
+}
+
void Document::ChildrenChanged(const ChildrenChange& change) {
ContainerNode::ChildrenChanged(change);
document_element_ = ElementTraversal::FirstWithin(*this);
@@ -890,7 +891,7 @@ AtomicString Document::ConvertLocalName(const AtomicString& name) {
Element* Document::CreateRawElement(const QualifiedName& qname,
CreateElementFlags flags) {
Element* element = nullptr;
- if (qname.NamespaceURI() == HTMLNames::xhtmlNamespaceURI) {
+ if (qname.NamespaceURI() == html_names::xhtmlNamespaceURI) {
// https://html.spec.whatwg.org/multipage/dom.html#elements-in-the-dom:element-interface
element = HTMLElementFactory::Create(qname.LocalName(), *this, flags);
if (!element) {
@@ -903,7 +904,7 @@ Element* Document::CreateRawElement(const QualifiedName& qname,
element = HTMLUnknownElement::Create(qname, *this);
}
saw_elements_in_known_namespaces_ = true;
- } else if (qname.NamespaceURI() == SVGNames::svgNamespaceURI) {
+ } else if (qname.NamespaceURI() == svg_names::kNamespaceURI) {
element = SVGElementFactory::Create(qname.LocalName(), *this, flags);
if (!element)
element = SVGUnknownElement::Create(qname, *this);
@@ -936,13 +937,14 @@ Element* Document::CreateElementForBinding(const AtomicString& name,
if (CustomElement::ShouldCreateCustomElement(local_name)) {
return CustomElement::CreateCustomElement(
*this,
- QualifiedName(g_null_atom, local_name, HTMLNames::xhtmlNamespaceURI),
+ QualifiedName(g_null_atom, local_name, html_names::xhtmlNamespaceURI),
CreateElementFlags::ByCreateElement());
}
if (auto* element = HTMLElementFactory::Create(
local_name, *this, CreateElementFlags::ByCreateElement()))
return element;
- QualifiedName q_name(g_null_atom, local_name, HTMLNames::xhtmlNamespaceURI);
+ QualifiedName q_name(g_null_atom, local_name,
+ html_names::xhtmlNamespaceURI);
if (RegistrationContext() && V0CustomElement::IsValidName(local_name))
return RegistrationContext()->CreateCustomTagElement(*this, q_name);
return HTMLUnknownElement::Create(q_name, *this);
@@ -950,37 +952,32 @@ Element* Document::CreateElementForBinding(const AtomicString& name,
return Element::Create(QualifiedName(g_null_atom, name, g_null_atom), this);
}
-String GetTypeExtension(Document* document,
- const StringOrDictionary& string_or_options,
- ExceptionState& exception_state) {
+AtomicString GetTypeExtension(
+ Document* document,
+ const StringOrElementCreationOptions& string_or_options) {
if (string_or_options.IsNull())
- return String();
+ return AtomicString();
if (string_or_options.IsString()) {
UseCounter::Count(document,
WebFeature::kDocumentCreateElement2ndArgStringHandling);
- return string_or_options.GetAsString();
+ return AtomicString(string_or_options.GetAsString());
}
- if (string_or_options.IsDictionary()) {
- Dictionary dict = string_or_options.GetAsDictionary();
- ElementCreationOptions impl;
- V8ElementCreationOptions::ToImpl(dict.GetIsolate(), dict.V8Value(), impl,
- exception_state);
- if (exception_state.HadException())
- return String();
-
- if (impl.hasIs())
- return impl.is();
+ if (string_or_options.IsElementCreationOptions()) {
+ const ElementCreationOptions& options =
+ *string_or_options.GetAsElementCreationOptions();
+ if (options.hasIs())
+ return AtomicString(options.is());
}
- return String();
+ return AtomicString();
}
// https://dom.spec.whatwg.org/#dom-document-createelement
Element* Document::CreateElementForBinding(
const AtomicString& local_name,
- const StringOrDictionary& string_or_options,
+ const StringOrElementCreationOptions& string_or_options,
ExceptionState& exception_state) {
if (string_or_options.IsNull()) {
return CreateElementForBinding(local_name, exception_state);
@@ -998,17 +995,17 @@ Element* Document::CreateElementForBinding(
const AtomicString& converted_local_name = ConvertLocalName(local_name);
QualifiedName q_name(g_null_atom, converted_local_name,
IsXHTMLDocument() || IsHTMLDocument()
- ? HTMLNames::xhtmlNamespaceURI
+ ? html_names::xhtmlNamespaceURI
: g_null_atom);
- bool is_v1 = string_or_options.IsDictionary() || !RegistrationContext();
- bool create_v1_builtin = string_or_options.IsDictionary();
+ bool is_v1 =
+ string_or_options.IsElementCreationOptions() || !RegistrationContext();
+ bool create_v1_builtin = string_or_options.IsElementCreationOptions();
bool should_create_builtin =
create_v1_builtin || string_or_options.IsString();
// 3.
- const AtomicString& is =
- AtomicString(GetTypeExtension(this, string_or_options, exception_state));
+ const AtomicString& is = GetTypeExtension(this, string_or_options);
// 5. Let element be the result of creating an element given ...
Element* element =
@@ -1019,7 +1016,7 @@ Element* Document::CreateElementForBinding(
// 8. If 'is' is non-null, set 'is' attribute
if (!is_v1 && !is.IsEmpty())
- element->setAttribute(HTMLNames::isAttr, is);
+ element->setAttribute(html_names::kIsAttr, is);
return element;
}
@@ -1063,10 +1060,11 @@ Element* Document::createElementNS(const AtomicString& namespace_uri,
}
// https://dom.spec.whatwg.org/#internal-createelementns-steps
-Element* Document::createElementNS(const AtomicString& namespace_uri,
- const AtomicString& qualified_name,
- const StringOrDictionary& string_or_options,
- ExceptionState& exception_state) {
+Element* Document::createElementNS(
+ const AtomicString& namespace_uri,
+ const AtomicString& qualified_name,
+ const StringOrElementCreationOptions& string_or_options,
+ ExceptionState& exception_state) {
if (string_or_options.IsNull())
return createElementNS(namespace_uri, qualified_name, exception_state);
@@ -1076,14 +1074,14 @@ Element* Document::createElementNS(const AtomicString& namespace_uri,
if (q_name == QualifiedName::Null())
return nullptr;
- bool is_v1 = string_or_options.IsDictionary() || !RegistrationContext();
- bool create_v1_builtin = string_or_options.IsDictionary();
+ bool is_v1 =
+ string_or_options.IsElementCreationOptions() || !RegistrationContext();
+ bool create_v1_builtin = string_or_options.IsElementCreationOptions();
bool should_create_builtin =
create_v1_builtin || string_or_options.IsString();
// 2.
- const AtomicString& is =
- AtomicString(GetTypeExtension(this, string_or_options, exception_state));
+ const AtomicString& is = GetTypeExtension(this, string_or_options);
if (!IsValidElementName(this, qualified_name)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidCharacterError,
@@ -1102,7 +1100,7 @@ Element* Document::createElementNS(const AtomicString& namespace_uri,
// 4. If 'is' is non-null, set 'is' attribute
if (!is_v1 && !is.IsEmpty())
- element->setAttribute(HTMLNames::isAttr, is);
+ element->setAttribute(html_names::kIsAttr, is);
return element;
}
@@ -1114,7 +1112,7 @@ Element* Document::CreateElement(const QualifiedName& q_name,
const AtomicString& is) {
CustomElementDefinition* definition = nullptr;
if (flags.IsCustomElementsV1() &&
- q_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI) {
+ q_name.NamespaceURI() == html_names::xhtmlNamespaceURI) {
const CustomElementDescriptor desc(is.IsNull() ? q_name.LocalName() : is,
q_name.LocalName());
if (CustomElementRegistry* registry = CustomElement::Registry(*this))
@@ -1131,13 +1129,13 @@ Element* Document::CreateElement(const QualifiedName& q_name,
ScriptPromise Document::createCSSStyleSheet(ScriptState* script_state,
const String& text,
ExceptionState& exception_state) {
- return Document::createCSSStyleSheet(script_state, text, CSSStyleSheetInit(),
- exception_state);
+ return Document::createCSSStyleSheet(
+ script_state, text, CSSStyleSheetInit::Create(), exception_state);
}
ScriptPromise Document::createCSSStyleSheet(ScriptState* script_state,
const String& text,
- const CSSStyleSheetInit& options,
+ const CSSStyleSheetInit* options,
ExceptionState& exception_state) {
// Even though this function returns a Promise, it actually does all the work
// at once here because CSS parsing is done synchronously on the main thread.
@@ -1145,8 +1143,7 @@ ScriptPromise Document::createCSSStyleSheet(ScriptState* script_state,
CSSStyleSheet* sheet = CSSStyleSheet::Create(*this, options, exception_state);
sheet->SetText(text, true /* allow_import_rules */, exception_state);
sheet->SetAssociatedDocument(this);
- return ScriptPromise::Cast(script_state,
- ScriptValue::From(script_state, sheet));
+ return ScriptPromise::Cast(script_state, ToV8(sheet, script_state));
}
CSSStyleSheet* Document::createCSSStyleSheetSync(
@@ -1154,13 +1151,13 @@ CSSStyleSheet* Document::createCSSStyleSheetSync(
const String& text,
ExceptionState& exception_state) {
return Document::createCSSStyleSheetSync(
- script_state, text, CSSStyleSheetInit(), exception_state);
+ script_state, text, CSSStyleSheetInit::Create(), exception_state);
}
CSSStyleSheet* Document::createCSSStyleSheetSync(
ScriptState* script_state,
const String& text,
- const CSSStyleSheetInit& options,
+ const CSSStyleSheetInit* options,
ExceptionState& exception_state) {
CSSStyleSheet* sheet = CSSStyleSheet::Create(*this, options, exception_state);
sheet->SetText(text, false /* allow_import_rules */, exception_state);
@@ -1172,7 +1169,7 @@ CSSStyleSheet* Document::createCSSStyleSheetSync(
CSSStyleSheet* Document::createEmptyCSSStyleSheet(
ScriptState* script_state,
- const CSSStyleSheetInit& options,
+ const CSSStyleSheetInit* options,
ExceptionState& exception_state) {
CSSStyleSheet* sheet = CSSStyleSheet::Create(*this, options, exception_state);
sheet->SetAssociatedDocument(this);
@@ -1182,13 +1179,13 @@ CSSStyleSheet* Document::createEmptyCSSStyleSheet(
CSSStyleSheet* Document::createEmptyCSSStyleSheet(
ScriptState* script_state,
ExceptionState& exception_state) {
- return Document::createEmptyCSSStyleSheet(script_state, CSSStyleSheetInit(),
- exception_state);
+ return Document::createEmptyCSSStyleSheet(
+ script_state, CSSStyleSheetInit::Create(), exception_state);
}
ScriptValue Document::registerElement(ScriptState* script_state,
const AtomicString& name,
- const ElementRegistrationOptions& options,
+ const ElementRegistrationOptions* options,
ExceptionState& exception_state) {
if (!RegistrationContext()) {
exception_state.ThrowDOMException(
@@ -1423,7 +1420,7 @@ bool Document::HasValidNamespaceForElements(const QualifiedName& q_name) {
return false;
// createElementNS("http://www.example.com", "xml:lang")
if (q_name.Prefix() == g_xml_atom &&
- q_name.NamespaceURI() != XMLNames::xmlNamespaceURI)
+ q_name.NamespaceURI() != xml_names::kNamespaceURI)
return false;
// Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
@@ -1432,8 +1429,8 @@ bool Document::HasValidNamespaceForElements(const QualifiedName& q_name) {
// createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
if (q_name.Prefix() == g_xmlns_atom ||
(q_name.Prefix().IsEmpty() && q_name.LocalName() == g_xmlns_atom))
- return q_name.NamespaceURI() == XMLNSNames::xmlnsNamespaceURI;
- return q_name.NamespaceURI() != XMLNSNames::xmlnsNamespaceURI;
+ return q_name.NamespaceURI() == xmlns_names::kNamespaceURI;
+ return q_name.NamespaceURI() != xmlns_names::kNamespaceURI;
}
bool Document::HasValidNamespaceForAttributes(const QualifiedName& q_name) {
@@ -1479,7 +1476,7 @@ void Document::SetReadyState(DocumentReadyState ready_state) {
}
ready_state_ = ready_state;
- DispatchEvent(*Event::Create(EventTypeNames::readystatechange));
+ DispatchEvent(*Event::Create(event_type_names::kReadystatechange));
}
bool Document::IsLoadCompleted() const {
@@ -1500,7 +1497,7 @@ void Document::SetContentLanguage(const AtomicString& language) {
// Document's style depends on the content language.
SetNeedsStyleRecalc(kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kLanguage));
+ style_change_reason::kLanguage));
}
void Document::setXMLVersion(const String& version,
@@ -1642,9 +1639,9 @@ static inline String CanonicalizedTitle(Document* document,
bool pending_whitespace = false;
for (unsigned i = 0; i < length; ++i) {
UChar32 c = characters[i];
- if ((c <= WTF::Unicode::kSpaceCharacter &&
- c != WTF::Unicode::kLineTabulationCharacter) ||
- c == WTF::Unicode::kDeleteCharacter) {
+ if ((c <= WTF::unicode::kSpaceCharacter &&
+ c != WTF::unicode::kLineTabulationCharacter) ||
+ c == WTF::unicode::kDeleteCharacter) {
if (builder_index != 0)
pending_whitespace = true;
} else {
@@ -1688,31 +1685,25 @@ void Document::DispatchDidReceiveTitle() {
void Document::setTitle(const String& title) {
// Title set by JavaScript -- overrides any title elements.
- if (!title_element_) {
- if (IsHTMLDocument() || IsXHTMLDocument()) {
+ Element* element = documentElement();
+ if (IsSVGSVGElement(element)) {
+ if (!title_element_) {
+ title_element_ = SVGTitleElement::Create(*this);
+ element->InsertBefore(title_element_.Get(), element->firstChild());
+ }
+ if (auto* svg_title = ToSVGTitleElementOrNull(title_element_))
+ svg_title->SetText(title);
+ } else if (element && element->IsHTMLElement()) {
+ if (!title_element_) {
HTMLElement* head_element = head();
if (!head_element)
return;
title_element_ = HTMLTitleElement::Create(*this);
head_element->AppendChild(title_element_.Get());
- } else if (IsSVGDocument()) {
- Element* element = documentElement();
- if (!IsSVGSVGElement(element))
- return;
- title_element_ = SVGTitleElement::Create(*this);
- element->InsertBefore(title_element_.Get(), element->firstChild());
}
- } else {
- if (!IsHTMLDocument() && !IsXHTMLDocument() && !IsSVGDocument())
- title_element_ = nullptr;
+ if (auto* html_title = ToHTMLTitleElementOrNull(title_element_))
+ html_title->setText(title);
}
-
- if (auto* html_title = ToHTMLTitleElementOrNull(title_element_))
- html_title->setText(title);
- else if (auto* svg_title = ToSVGTitleElementOrNull(title_element_))
- svg_title->SetText(title);
- else
- UpdateTitle(title);
}
void Document::SetTitleElement(Element* title_element) {
@@ -1815,9 +1806,10 @@ void Document::SetWasDiscarded(bool was_discarded) {
}
void Document::DidChangeVisibilityState() {
- DispatchEvent(*Event::CreateBubble(EventTypeNames::visibilitychange));
+ DispatchEvent(*Event::CreateBubble(event_type_names::kVisibilitychange));
// Also send out the deprecated version until it can be removed.
- DispatchEvent(*Event::CreateBubble(EventTypeNames::webkitvisibilitychange));
+ DispatchEvent(
+ *Event::CreateBubble(event_type_names::kWebkitvisibilitychange));
if (GetPageVisibilityState() == mojom::PageVisibilityState::kVisible)
Timeline().SetAllCompositorPending();
@@ -1930,9 +1922,7 @@ bool Document::NeedsFullLayoutTreeUpdate() const {
return true;
if (NeedsStyleInvalidation())
return true;
- // FIXME: The childNeedsDistributionRecalc bit means either self or children,
- // we should fix that.
- if (ChildNeedsDistributionRecalc())
+ if (IsSlotAssignmentOrLegacyDistributionDirty())
return true;
if (DocumentAnimations::NeedsAnimationTimingUpdate(*this))
return true;
@@ -1965,7 +1955,7 @@ void Document::ScheduleLayoutTreeUpdate() {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"ScheduleStyleRecalculation", TRACE_EVENT_SCOPE_THREAD,
"data",
- InspectorRecalculateStylesEvent::Data(GetFrame()));
+ inspector_recalculate_styles_event::Data(GetFrame()));
++style_version_;
}
@@ -1993,7 +1983,8 @@ void Document::SetupFontBuilder(ComputedStyle& document_style) {
void Document::PropagateStyleToViewport() {
DCHECK(InStyleRecalc());
- DCHECK(documentElement());
+ if (!documentElement())
+ return;
HTMLElement* body = this->body();
@@ -2015,67 +2006,70 @@ void Document::PropagateStyleToViewport() {
// http://www.w3.org/TR/css3-background/#body-background
// <html> root element with no background steals background from its first
// <body> child.
- // Also see LayoutBoxModelObject::backgroundStolenForBeingBody()
- if (IsHTMLHtmlElement(documentElement()) && IsHTMLBodyElement(body) &&
- !background_style->HasBackground())
+ // Also see LayoutBoxModelObject::BackgroundTransfersToView()
+ if (IsHTMLHtmlElement(documentElement()) &&
+ document_element_style->Display() != EDisplay::kNone &&
+ IsHTMLBodyElement(body) && !background_style->HasBackground()) {
background_style = body_style;
-
- Color background_color =
- background_style->VisitedDependentColor(GetCSSPropertyBackgroundColor());
- FillLayer background_layers = background_style->BackgroundLayers();
- for (auto* current_layer = &background_layers; current_layer;
- current_layer = current_layer->Next()) {
- // http://www.w3.org/TR/css3-background/#root-background
- // The root element background always have painting area of the whole
- // canvas.
- current_layer->SetClip(EFillBox::kBorder);
-
- // The root element doesn't scroll. It always propagates its layout overflow
- // to the viewport. Positioning background against either box is equivalent
- // to positioning against the scrolled box of the viewport.
- if (current_layer->Attachment() == EFillAttachment::kScroll)
- current_layer->SetAttachment(EFillAttachment::kLocal);
}
- EImageRendering image_rendering = background_style->ImageRendering();
- const ComputedStyle* overflow_style = nullptr;
- if (Element* element = ViewportDefiningElement(document_element_style)) {
- if (element == body) {
- overflow_style = body_style;
- } else {
- DCHECK_EQ(element, documentElement());
- overflow_style = document_element_style;
-
- // The body element has its own scrolling box, independent from the
- // viewport. This is a bit of a weird edge case in the CSS spec that we
- // might want to try to eliminate some day (eg. for ScrollTopLeftInterop -
- // see http://crbug.com/157855).
- if (body_style && !body_style->IsOverflowVisible())
- UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport);
+ Color background_color = Color::kTransparent;
+ FillLayer background_layers(EFillLayerType::kBackground, true);
+ EImageRendering image_rendering = EImageRendering::kAuto;
+
+ if (background_style->Display() != EDisplay::kNone) {
+ background_color = background_style->VisitedDependentColor(
+ GetCSSPropertyBackgroundColor());
+ background_layers = background_style->BackgroundLayers();
+ for (auto* current_layer = &background_layers; current_layer;
+ current_layer = current_layer->Next()) {
+ // http://www.w3.org/TR/css3-background/#root-background
+ // The root element background always have painting area of the whole
+ // canvas.
+ current_layer->SetClip(EFillBox::kBorder);
+
+ // The root element doesn't scroll. It always propagates its layout
+ // overflow to the viewport. Positioning background against either box is
+ // equivalent to positioning against the scrolled box of the viewport.
+ if (current_layer->Attachment() == EFillAttachment::kScroll)
+ current_layer->SetAttachment(EFillAttachment::kLocal);
}
+ image_rendering = background_style->ImageRendering();
}
- EOverflowAnchor overflow_anchor = EOverflowAnchor::kAuto;
- EOverflow overflow_x = EOverflow::kAuto;
- EOverflow overflow_y = EOverflow::kAuto;
- GapLength column_gap;
- if (overflow_style) {
- overflow_anchor = overflow_style->OverflowAnchor();
- overflow_x = overflow_style->OverflowX();
- overflow_y = overflow_style->OverflowY();
- // Visible overflow on the viewport is meaningless, and the spec says to
- // treat it as 'auto':
- if (overflow_x == EOverflow::kVisible)
- overflow_x = EOverflow::kAuto;
- if (overflow_y == EOverflow::kVisible)
- overflow_y = EOverflow::kAuto;
- if (overflow_anchor == EOverflowAnchor::kVisible)
- overflow_anchor = EOverflowAnchor::kAuto;
- // Column-gap is (ab)used by the current paged overflow implementation (in
- // lack of other ways to specify gaps between pages), so we have to
- // propagate it too.
- column_gap = overflow_style->ColumnGap();
- }
+ const ComputedStyle* overflow_style = nullptr;
+ Element* viewport_element = ViewportDefiningElement();
+ DCHECK(viewport_element);
+ if (viewport_element == body) {
+ overflow_style = body_style;
+ } else {
+ DCHECK_EQ(viewport_element, documentElement());
+ overflow_style = document_element_style;
+
+ // The body element has its own scrolling box, independent from the
+ // viewport. This is a bit of a weird edge case in the CSS spec that we
+ // might want to try to eliminate some day (eg. for ScrollTopLeftInterop -
+ // see http://crbug.com/157855).
+ if (body_style && !body_style->IsOverflowVisible())
+ UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport);
+ }
+ DCHECK(overflow_style);
+
+ EOverflowAnchor overflow_anchor = overflow_style->OverflowAnchor();
+ EOverflow overflow_x = overflow_style->OverflowX();
+ EOverflow overflow_y = overflow_style->OverflowY();
+ // Visible overflow on the viewport is meaningless, and the spec says to
+ // treat it as 'auto':
+ if (overflow_x == EOverflow::kVisible)
+ overflow_x = EOverflow::kAuto;
+ if (overflow_y == EOverflow::kVisible)
+ overflow_y = EOverflow::kAuto;
+ if (overflow_anchor == EOverflowAnchor::kVisible)
+ overflow_anchor = EOverflowAnchor::kAuto;
+ // Column-gap is (ab)used by the current paged overflow implementation (in
+ // lack of other ways to specify gaps between pages), so we have to
+ // propagate it too.
+ GapLength column_gap = overflow_style->ColumnGap();
ScrollSnapType snap_type = overflow_style->GetScrollSnapType();
ScrollBehavior scroll_behavior = document_element_style->GetScrollBehavior();
@@ -2155,23 +2149,33 @@ void Document::PropagateStyleToViewport() {
#if DCHECK_IS_ON()
static void AssertLayoutTreeUpdated(Node& root) {
- for (Node& node : NodeTraversal::InclusiveDescendantsOf(root)) {
- DCHECK(!node.NeedsStyleRecalc());
- DCHECK(!node.ChildNeedsStyleRecalc());
- DCHECK(!node.NeedsReattachLayoutTree());
- DCHECK(!node.ChildNeedsReattachLayoutTree());
- DCHECK(!node.ChildNeedsDistributionRecalc());
- DCHECK(!node.NeedsStyleInvalidation());
- DCHECK(!node.ChildNeedsStyleInvalidation());
+ Node* node = &root;
+ while (node) {
+ if (RuntimeEnabledFeatures::DisplayLockingEnabled() &&
+ node->IsElementNode() &&
+ ToElement(node)->StyleRecalcBlockedByDisplayLock()) {
+ node = NodeTraversal::NextSkippingChildren(*node);
+ continue;
+ }
+
+ DCHECK(!node->NeedsStyleRecalc());
+ DCHECK(!node->ChildNeedsStyleRecalc());
+ DCHECK(!node->NeedsReattachLayoutTree());
+ DCHECK(!node->ChildNeedsReattachLayoutTree());
+ DCHECK(!node->ChildNeedsDistributionRecalc());
+ DCHECK(!node->NeedsStyleInvalidation());
+ DCHECK(!node->ChildNeedsStyleInvalidation());
+ DCHECK(!node->GetForceReattachLayoutTree());
// Make sure there is no node which has a LayoutObject, but doesn't have a
// parent in a flat tree. If there is such a node, we forgot to detach the
// node. DocumentNode is only an exception.
- DCHECK((node.IsDocumentNode() || !node.GetLayoutObject() ||
- FlatTreeTraversal::Parent(node)))
- << node;
+ DCHECK((node->IsDocumentNode() || !node->GetLayoutObject() ||
+ FlatTreeTraversal::Parent(*node)))
+ << *node;
- if (ShadowRoot* shadow_root = node.GetShadowRoot())
+ if (ShadowRoot* shadow_root = node->GetShadowRoot())
AssertLayoutTreeUpdated(*shadow_root);
+ node = NodeTraversal::Next(*node);
}
}
#endif
@@ -2198,10 +2202,7 @@ void Document::UpdateStyleAndLayoutTree() {
// NeedsLayoutTreeUpdate().
GetSlotAssignmentEngine().RecalcSlotAssignments();
-#if DCHECK_IS_ON()
- NestingLevelIncrementer slot_assignment_recalc_forbidden_scope(
- slot_assignment_recalc_forbidden_recursion_depth_);
-#endif
+ SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(*this);
if (!NeedsLayoutTreeUpdate()) {
if (Lifecycle().GetState() < DocumentLifecycle::kStyleClean) {
@@ -2225,7 +2226,7 @@ void Document::UpdateStyleAndLayoutTree() {
CHECK(Lifecycle().StateAllowsTreeMutations());
TRACE_EVENT_BEGIN1("blink,devtools.timeline", "UpdateLayoutTree", "beginData",
- InspectorRecalculateStylesEvent::Data(GetFrame()));
+ inspector_recalculate_styles_event::Data(GetFrame()));
unsigned start_element_count = GetStyleEngine().StyleForElementCount();
@@ -2339,7 +2340,6 @@ void Document::UpdateStyle() {
ViewportDefiningElementDidChange();
}
GetStyleEngine().MarkForWhitespaceReattachment();
- PropagateStyleToViewport();
if (document_element->NeedsReattachLayoutTree() ||
document_element->ChildNeedsReattachLayoutTree()) {
TRACE_EVENT0("blink,blink_style", "Document::rebuildLayoutTree");
@@ -2350,13 +2350,13 @@ void Document::UpdateStyle() {
}
}
GetStyleEngine().ClearWhitespaceReattachSet();
+ ClearChildNeedsStyleRecalc();
+ ClearChildNeedsReattachLayoutTree();
+ PropagateStyleToViewport();
View()->UpdateCountersAfterStyleChange();
GetLayoutView()->RecalcOverflow();
- ClearChildNeedsStyleRecalc();
- ClearChildNeedsReattachLayoutTree();
-
DCHECK(!NeedsStyleRecalc());
DCHECK(!ChildNeedsStyleRecalc());
DCHECK(!NeedsReattachLayoutTree());
@@ -2414,7 +2414,8 @@ void Document::NotifyLayoutTreeOfSubtreeChanges() {
lifecycle_.AdvanceTo(DocumentLifecycle::kLayoutSubtreeChangeClean);
}
-bool Document::NeedsLayoutTreeUpdateForNode(const Node& node) const {
+bool Document::NeedsLayoutTreeUpdateForNode(const Node& node,
+ bool ignore_adjacent_style) const {
if (!node.CanParticipateInFlatTree())
return false;
if (!NeedsLayoutTreeUpdate())
@@ -2434,7 +2435,7 @@ bool Document::NeedsLayoutTreeUpdateForNode(const Node& node) const {
}
}
if (ancestor->NeedsStyleRecalc() || ancestor->NeedsStyleInvalidation() ||
- ancestor->NeedsAdjacentStyleRecalc()) {
+ (ancestor->NeedsAdjacentStyleRecalc() && !ignore_adjacent_style)) {
return true;
}
}
@@ -2543,6 +2544,10 @@ void Document::ClearFocusedElementTimerFired(TimerBase*) {
// lets us get reasonable answers. The long term solution to this problem is
// to instead suspend JavaScript execution.
void Document::UpdateStyleAndLayoutTreeIgnorePendingStylesheets() {
+ if (RuntimeEnabledFeatures::CSSInBodyDoesNotBlockPaintEnabled()) {
+ UpdateStyleAndLayoutTree();
+ return;
+ }
if (Lifecycle().LifecyclePostponed())
return;
// See comment for equivalent CHECK in Document::UpdateStyleAndLayoutTree.
@@ -2573,7 +2578,7 @@ void Document::UpdateStyleAndLayoutTreeIgnorePendingStylesheets() {
// but here we need up-to-date style immediately.
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kCleanupPlaceholderStyles));
+ style_change_reason::kCleanupPlaceholderStyles));
}
}
UpdateStyleAndLayoutTree();
@@ -2584,7 +2589,8 @@ void Document::UpdateStyleAndLayoutIgnorePendingStylesheets(
LocalFrameView* local_view = View();
if (local_view)
local_view->WillStartForcedLayout();
- UpdateStyleAndLayoutTreeIgnorePendingStylesheets();
+ if (!RuntimeEnabledFeatures::CSSInBodyDoesNotBlockPaintEnabled())
+ UpdateStyleAndLayoutTreeIgnorePendingStylesheets();
UpdateStyleAndLayout();
if (local_view) {
@@ -2761,7 +2767,7 @@ void Document::Initialize() {
if (TextAutosizer* autosizer = GetTextAutosizer())
autosizer->UpdatePageInfo();
- frame_->DocumentAttached();
+ frame_->DidAttachDocument();
lifecycle_.AdvanceTo(DocumentLifecycle::kStyleClean);
if (View())
@@ -2770,10 +2776,12 @@ void Document::Initialize() {
// Observer(s) should not be initialized until the document is initialized /
// attached to a frame. Otherwise ContextLifecycleObserver::contextDestroyed
// wouldn't be fired.
- network_state_observer_ = new NetworkStateObserver(*this);
+ network_state_observer_ = MakeGarbageCollected<NetworkStateObserver>(*this);
}
void Document::Shutdown() {
+ if (num_canvases_ > 0)
+ UMA_HISTOGRAM_COUNTS_100("Blink.Canvas.NumCanvasesPerPage", num_canvases_);
TRACE_EVENT0("blink", "Document::shutdown");
CHECK(!frame_ || frame_->Tree().ChildCount() == 0);
if (!IsActive())
@@ -3325,8 +3333,7 @@ HTMLHeadElement* Document::head() const {
return Traversal<HTMLHeadElement>::FirstChild(*de);
}
-Element* Document::ViewportDefiningElement(
- const ComputedStyle* root_style) const {
+Element* Document::ViewportDefiningElement() const {
// If a BODY element sets non-visible overflow, it is to be propagated to the
// viewport, as long as the following conditions are all met:
// (1) The root element is HTML.
@@ -3338,11 +3345,9 @@ Element* Document::ViewportDefiningElement(
Element* body_element = body();
if (!root_element)
return nullptr;
- if (!root_style) {
- root_style = root_element->GetComputedStyle();
- if (!root_style)
- return nullptr;
- }
+ const ComputedStyle* root_style = root_element->GetComputedStyle();
+ if (!root_style)
+ return nullptr;
if (body_element && root_style->IsOverflowVisible() &&
IsHTMLHtmlElement(*root_element))
return body_element;
@@ -3588,6 +3593,15 @@ bool Document::CheckCompletedInternal() {
}
AnchorElementMetrics::MaybeReportViewportMetricsOnLoad(*this);
+
+ // If this is a document associated with a resource loading hints based
+ // preview, then record the resource loading hints UKM now that the load is
+ // finished.
+ PreviewsResourceLoadingHints* hints =
+ Loader()->GetPreviewsResourceLoadingHints();
+ if (hints) {
+ hints->RecordUKM(UkmRecorder());
+ }
}
return true;
@@ -3607,7 +3621,7 @@ bool Document::DispatchBeforeUnloadEvent(ChromeClient& chrome_client,
return false;
BeforeUnloadEvent& before_unload_event = *BeforeUnloadEvent::Create();
- before_unload_event.initEvent(EventTypeNames::beforeunload, false, true);
+ before_unload_event.initEvent(event_type_names::kBeforeunload, false, true);
load_event_progress_ = kBeforeUnloadEventInProgress;
const TimeTicks beforeunload_event_start = CurrentTimeTicks();
dom_window_->DispatchEvent(before_unload_event, this);
@@ -3701,7 +3715,7 @@ void Document::DispatchUnloadEvents() {
if (LocalDOMWindow* window = domWindow()) {
const TimeTicks pagehide_event_start = CurrentTimeTicks();
window->DispatchEvent(
- *PageTransitionEvent::Create(EventTypeNames::pagehide, false),
+ *PageTransitionEvent::Create(event_type_names::kPagehide, false),
this);
const TimeTicks pagehide_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
@@ -3719,7 +3733,8 @@ void Document::DispatchUnloadEvents() {
// Dispatch visibilitychange event, but don't bother doing
// other notifications as we're about to be unloaded.
const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks();
- DispatchEvent(*Event::CreateBubble(EventTypeNames::visibilitychange));
+ DispatchEvent(
+ *Event::CreateBubble(event_type_names::kVisibilitychange));
const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram,
("DocumentEventTiming.PageVibilityHiddenDuration",
@@ -3728,7 +3743,7 @@ void Document::DispatchUnloadEvents() {
pagevisibility_hidden_event_end -
pagevisibility_hidden_event_start);
DispatchEvent(
- *Event::CreateBubble(EventTypeNames::webkitvisibilitychange));
+ *Event::CreateBubble(event_type_names::kWebkitvisibilitychange));
}
if (!frame_)
return;
@@ -3738,7 +3753,7 @@ void Document::DispatchUnloadEvents() {
DocumentLoader* document_loader =
frame_->Loader().GetProvisionalDocumentLoader();
load_event_progress_ = kUnloadEventInProgress;
- Event& unload_event = *Event::Create(EventTypeNames::unload);
+ Event& unload_event = *Event::Create(event_type_names::kUnload);
if (document_loader &&
document_loader->GetTiming().UnloadEventStart().is_null() &&
document_loader->GetTiming().UnloadEventEnd().is_null()) {
@@ -3781,12 +3796,13 @@ void Document::DispatchFreezeEvent() {
DCHECK(RuntimeEnabledFeatures::PageLifecycleEnabled());
const TimeTicks freeze_event_start = CurrentTimeTicks();
SetFreezingInProgress(true);
- DispatchEvent(*Event::Create(EventTypeNames::freeze));
+ DispatchEvent(*Event::Create(event_type_names::kFreeze));
SetFreezingInProgress(false);
const TimeTicks freeze_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(CustomCountHistogram, freeze_histogram,
("DocumentEventTiming.FreezeDuration", 0, 10000000, 50));
freeze_histogram.CountMicroseconds(freeze_event_end - freeze_event_start);
+ UseCounter::Count(*this, WebFeature::kPageLifeCycleFreeze);
}
Document::PageDismissalType Document::PageDismissalEventBeingDispatched()
@@ -3922,7 +3938,8 @@ void Document::write(const String& text,
DCHECK(parser_);
PerformanceMonitor::ReportGenericViolation(
this, PerformanceMonitor::kDiscouragedAPIUse,
- "Avoid using document.write().", base::TimeDelta(), nullptr);
+ "Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write",
+ base::TimeDelta(), nullptr);
probe::breakableLocation(this, "Document.write");
parser_->insert(text);
}
@@ -4109,12 +4126,12 @@ void Document::ProcessBaseElement() {
base && (!href || !target);
base = Traversal<HTMLBaseElement>::Next(*base)) {
if (!href) {
- const AtomicString& value = base->FastGetAttribute(hrefAttr);
+ const AtomicString& value = base->FastGetAttribute(kHrefAttr);
if (!value.IsNull())
href = &value;
}
if (!target) {
- const AtomicString& value = base->FastGetAttribute(targetAttr);
+ const AtomicString& value = base->FastGetAttribute(kTargetAttr);
if (!value.IsNull())
target = &value;
}
@@ -4303,13 +4320,14 @@ String Document::OutgoingReferrer() const {
return referrer_document->url_.StrippedForUseAsReferrer();
}
-ReferrerPolicy Document::GetReferrerPolicy() const {
- ReferrerPolicy policy = ExecutionContext::GetReferrerPolicy();
+network::mojom::ReferrerPolicy Document::GetReferrerPolicy() const {
+ network::mojom::ReferrerPolicy policy = ExecutionContext::GetReferrerPolicy();
// For srcdoc documents without their own policy, walk up the frame
// tree to find the document that is either not a srcdoc or doesn't
// have its own policy. This algorithm is defined in
// https://html.spec.whatwg.org/multipage/window-object.html#set-up-a-window-environment-settings-object.
- if (!frame_ || policy != kReferrerPolicyDefault || !IsSrcdocDocument()) {
+ if (!frame_ || policy != network::mojom::ReferrerPolicy::kDefault ||
+ !IsSrcdocDocument()) {
return policy;
}
LocalFrame* frame = ToLocalFrame(frame_->Tree().Parent());
@@ -4593,7 +4611,7 @@ void Document::StyleResolverMayHaveChanged() {
if (HasNodesWithPlaceholderStyle()) {
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kCleanupPlaceholderStyles));
+ style_change_reason::kCleanupPlaceholderStyles));
}
if (DidLayoutWithPendingStylesheets() &&
@@ -4732,14 +4750,14 @@ bool Document::SetFocusedElement(Element* new_focused_element,
}
// 'focusout' is a DOM level 3 name for the bubbling blur event.
- old_focused_element->DispatchFocusOutEvent(EventTypeNames::focusout,
+ old_focused_element->DispatchFocusOutEvent(event_type_names::kFocusout,
new_focused_element,
params.source_capabilities);
// 'DOMFocusOut' is a DOM level 2 name for compatibility.
// FIXME: We should remove firing DOMFocusOutEvent event when we are sure
// no content depends on it, probably when <rdar://problem/8503958> is
// resolved.
- old_focused_element->DispatchFocusOutEvent(EventTypeNames::DOMFocusOut,
+ old_focused_element->DispatchFocusOutEvent(event_type_names::kDOMFocusOut,
new_focused_element,
params.source_capabilities);
@@ -4802,7 +4820,7 @@ bool Document::SetFocusedElement(Element* new_focused_element,
goto SetFocusedElementDone;
}
// DOM level 3 bubbling focus event.
- focused_element_->DispatchFocusInEvent(EventTypeNames::focusin,
+ focused_element_->DispatchFocusInEvent(event_type_names::kFocusin,
old_focused_element, params.type,
params.source_capabilities);
@@ -4815,7 +4833,7 @@ bool Document::SetFocusedElement(Element* new_focused_element,
// For DOM level 2 compatibility.
// FIXME: We should remove firing DOMFocusInEvent event when we are sure
// no content depends on it, probably when <rdar://problem/8503958> is m.
- focused_element_->DispatchFocusInEvent(EventTypeNames::DOMFocusIn,
+ focused_element_->DispatchFocusInEvent(event_type_names::kDOMFocusIn,
old_focused_element, params.type,
params.source_capabilities);
@@ -4873,6 +4891,7 @@ Element* Document::SequentialFocusNavigationStartingPoint(
return focused_element_.Get();
if (!sequential_focus_navigation_starting_point_)
return nullptr;
+ DCHECK(sequential_focus_navigation_starting_point_->IsConnected());
if (!sequential_focus_navigation_starting_point_->collapsed()) {
Node* node = sequential_focus_navigation_starting_point_->startContainer();
DCHECK_EQ(node,
@@ -4900,11 +4919,25 @@ Element* Document::SequentialFocusNavigationStartingPoint(
// document tree.
if (Node* next_node =
sequential_focus_navigation_starting_point_->FirstNode()) {
- if (type == kWebFocusTypeForward)
- return ElementTraversal::Previous(*next_node);
+ if (next_node->IsShadowRoot())
+ return next_node->OwnerShadowHost();
+ // TODO(tkent): Using FlatTreeTraversal is inconsistent with
+ // FocusController. Ideally we should find backward/forward focusable
+ // elements before the starting point is disconnected. crbug.com/606582
+ if (type == kWebFocusTypeForward) {
+ Node* previous = next_node;
+ do {
+ previous = FlatTreeTraversal::Previous(*previous);
+ } while (previous && !previous->IsElementNode());
+ return ToElement(previous);
+ }
if (next_node->IsElementNode())
return ToElement(next_node);
- return ElementTraversal::Next(*next_node);
+ Node* next = next_node;
+ do {
+ next = FlatTreeTraversal::Next(*next);
+ } while (next && !next->IsElementNode());
+ return ToElement(next);
}
return nullptr;
}
@@ -4985,8 +5018,11 @@ void Document::DidMoveTreeToNewDocument(const Node& root) {
void Document::NodeChildrenWillBeRemoved(ContainerNode& container) {
EventDispatchForbiddenScope assert_no_event_dispatch;
- for (Range* range : ranges_)
+ for (Range* range : ranges_) {
range->NodeChildrenWillBeRemoved(container);
+ if (range == sequential_focus_navigation_starting_point_)
+ range->FixupRemovedChildrenAcrossShadowBoundary(container);
+ }
for (NodeIterator* ni : node_iterators_) {
for (Node& n : NodeTraversal::ChildrenOf(container))
@@ -5005,8 +5041,11 @@ void Document::NodeWillBeRemoved(Node& n) {
for (NodeIterator* ni : node_iterators_)
ni->NodeWillBeRemoved(n);
- for (Range* range : ranges_)
+ for (Range* range : ranges_) {
range->NodeWillBeRemoved(n);
+ if (range == sequential_focus_navigation_starting_point_)
+ range->FixupRemovedNodeAcrossShadowBoundary(n);
+ }
NotifyNodeWillBeRemoved(n);
@@ -5087,14 +5126,14 @@ void Document::EnqueueScrollEventForNode(Node* target) {
// Per the W3C CSSOM View Module only scroll events fired at the document
// should bubble.
Event* scroll_event = target->IsDocumentNode()
- ? Event::CreateBubble(EventTypeNames::scroll)
- : Event::Create(EventTypeNames::scroll);
+ ? Event::CreateBubble(event_type_names::kScroll)
+ : Event::Create(event_type_names::kScroll);
scroll_event->SetTarget(target);
EnsureScriptedAnimationController().EnqueuePerFrameEvent(scroll_event);
}
void Document::EnqueueResizeEvent() {
- Event* event = Event::Create(EventTypeNames::resize);
+ Event* event = Event::Create(event_type_names::kResize);
event->SetTarget(domWindow());
EnsureScriptedAnimationController().EnqueuePerFrameEvent(event);
}
@@ -5132,7 +5171,7 @@ const OriginAccessEntry& Document::AccessEntryFromURL() {
if (!access_entry_from_url_) {
access_entry_from_url_ = std::make_unique<OriginAccessEntry>(
Url().Protocol(), Url().Host(),
- network::cors::OriginAccessEntry::kAllowRegisterableDomains);
+ network::mojom::CorsOriginAccessMatchMode::kAllowRegisterableDomains);
}
return *access_entry_from_url_;
}
@@ -5189,7 +5228,7 @@ Event* Document::createEvent(ScriptState* script_state,
// createEvent for TouchEvent should throw DOM exception if touch event
// feature detection is not enabled. See crbug.com/392584#c22
if (DeprecatedEqualIgnoringCase(event_type, "TouchEvent") &&
- !OriginTrials::TouchEventFeatureDetectionEnabled(execution_context))
+ !origin_trials::TouchEventFeatureDetectionEnabled(execution_context))
break;
return event;
}
@@ -5208,43 +5247,43 @@ void Document::AddMutationEventListenerTypeIfEnabled(
void Document::AddListenerTypeIfNeeded(const AtomicString& event_type,
EventTarget& event_target) {
- if (event_type == EventTypeNames::DOMSubtreeModified) {
+ if (event_type == event_type_names::kDOMSubtreeModified) {
UseCounter::Count(*this, WebFeature::kDOMSubtreeModifiedEvent);
AddMutationEventListenerTypeIfEnabled(kDOMSubtreeModifiedListener);
- } else if (event_type == EventTypeNames::DOMNodeInserted) {
+ } else if (event_type == event_type_names::kDOMNodeInserted) {
UseCounter::Count(*this, WebFeature::kDOMNodeInsertedEvent);
AddMutationEventListenerTypeIfEnabled(kDOMNodeInsertedListener);
- } else if (event_type == EventTypeNames::DOMNodeRemoved) {
+ } else if (event_type == event_type_names::kDOMNodeRemoved) {
UseCounter::Count(*this, WebFeature::kDOMNodeRemovedEvent);
AddMutationEventListenerTypeIfEnabled(kDOMNodeRemovedListener);
- } else if (event_type == EventTypeNames::DOMNodeRemovedFromDocument) {
+ } else if (event_type == event_type_names::kDOMNodeRemovedFromDocument) {
UseCounter::Count(*this, WebFeature::kDOMNodeRemovedFromDocumentEvent);
AddMutationEventListenerTypeIfEnabled(kDOMNodeRemovedFromDocumentListener);
- } else if (event_type == EventTypeNames::DOMNodeInsertedIntoDocument) {
+ } else if (event_type == event_type_names::kDOMNodeInsertedIntoDocument) {
UseCounter::Count(*this, WebFeature::kDOMNodeInsertedIntoDocumentEvent);
AddMutationEventListenerTypeIfEnabled(kDOMNodeInsertedIntoDocumentListener);
- } else if (event_type == EventTypeNames::DOMCharacterDataModified) {
+ } else if (event_type == event_type_names::kDOMCharacterDataModified) {
UseCounter::Count(*this, WebFeature::kDOMCharacterDataModifiedEvent);
AddMutationEventListenerTypeIfEnabled(kDOMCharacterDataModifiedListener);
- } else if (event_type == EventTypeNames::webkitAnimationStart ||
- event_type == EventTypeNames::animationstart) {
+ } else if (event_type == event_type_names::kWebkitAnimationStart ||
+ event_type == event_type_names::kAnimationstart) {
AddListenerType(kAnimationStartListener);
- } else if (event_type == EventTypeNames::webkitAnimationEnd ||
- event_type == EventTypeNames::animationend) {
+ } else if (event_type == event_type_names::kWebkitAnimationEnd ||
+ event_type == event_type_names::kAnimationend) {
AddListenerType(kAnimationEndListener);
- } else if (event_type == EventTypeNames::webkitAnimationIteration ||
- event_type == EventTypeNames::animationiteration) {
+ } else if (event_type == event_type_names::kWebkitAnimationIteration ||
+ event_type == event_type_names::kAnimationiteration) {
AddListenerType(kAnimationIterationListener);
if (View()) {
// Need to re-evaluate time-to-effect-change for any running animations.
View()->ScheduleAnimation();
}
- } else if (event_type == EventTypeNames::webkitTransitionEnd ||
- event_type == EventTypeNames::transitionend) {
+ } else if (event_type == event_type_names::kWebkitTransitionEnd ||
+ event_type == event_type_names::kTransitionend) {
AddListenerType(kTransitionEndListener);
- } else if (event_type == EventTypeNames::scroll) {
+ } else if (event_type == event_type_names::kScroll) {
AddListenerType(kScrollListener);
- } else if (event_type == EventTypeNames::load) {
+ } else if (event_type == event_type_names::kLoad) {
if (Node* node = event_target.ToNode()) {
if (IsHTMLStyleElement(*node)) {
AddListenerType(kLoadListenerAtCapturePhaseOrAtStyleElement);
@@ -5271,23 +5310,21 @@ void Document::WillChangeFrameOwnerProperties(int margin_width,
DCHECK(GetFrame() && GetFrame()->Owner());
FrameOwner* owner = GetFrame()->Owner();
- if (RuntimeEnabledFeatures::DisplayNoneIFrameCreatesNoLayoutObjectEnabled()) {
- if (documentElement()) {
- if (is_display_none != owner->IsDisplayNone())
- documentElement()->LazyReattachIfAttached();
- }
+ if (documentElement()) {
+ if (is_display_none != owner->IsDisplayNone())
+ documentElement()->LazyReattachIfAttached();
}
// body() may become null as a result of modification event listeners, so we
// check before each call.
if (margin_width != owner->MarginWidth()) {
if (auto* body_element = body()) {
- body_element->SetIntegralAttribute(marginwidthAttr, margin_width);
+ body_element->SetIntegralAttribute(kMarginwidthAttr, margin_width);
}
}
if (margin_height != owner->MarginHeight()) {
if (auto* body_element = body()) {
- body_element->SetIntegralAttribute(marginheightAttr, margin_height);
+ body_element->SetIntegralAttribute(kMarginheightAttr, margin_height);
}
}
if (scrolling_mode != owner->ScrollingMode() && View()) {
@@ -5380,6 +5417,15 @@ void Document::setDomain(const String& raw_domain,
ExceptionState& exception_state) {
UseCounter::Count(*this, WebFeature::kDocumentSetDomain);
+ const String feature_policy_error =
+ "Setting `document.domain` is disabled by Feature Policy.";
+ if (!IsFeatureEnabled(mojom::FeaturePolicyFeature::kDocumentDomain,
+ ReportOptions::kReportOnFailure,
+ feature_policy_error)) {
+ exception_state.ThrowSecurityError(feature_policy_error);
+ return;
+ }
+
if (!frame_) {
exception_state.ThrowSecurityError(
"A browsing context is required to set a domain.");
@@ -5422,7 +5468,7 @@ void Document::setDomain(const String& raw_domain,
new_domain != "null") {
OriginAccessEntry access_entry(
GetSecurityOrigin()->Protocol(), new_domain,
- network::cors::OriginAccessEntry::kAllowSubdomains);
+ network::mojom::CorsOriginAccessMatchMode::kAllowSubdomains);
network::cors::OriginAccessEntry::MatchResult result =
access_entry.MatchesOrigin(*GetSecurityOrigin());
if (result == network::cors::OriginAccessEntry::kDoesNotMatchOrigin) {
@@ -5457,19 +5503,18 @@ void Document::setDomain(const String& raw_domain,
String Document::lastModified() const {
DateComponents date;
bool found_date = false;
- if (frame_) {
+ AtomicString http_last_modified = override_last_modified_;
+ if (http_last_modified.IsEmpty() && frame_) {
if (DocumentLoader* document_loader = Loader()) {
- const AtomicString& http_last_modified =
- document_loader->GetResponse().HttpHeaderField(
- HTTPNames::Last_Modified);
- if (!http_last_modified.IsEmpty()) {
- double date_value = ParseDate(http_last_modified);
- if (!std::isnan(date_value)) {
- date.SetMillisecondsSinceEpochForDateTime(
- ConvertToLocalTime(date_value));
- found_date = true;
- }
- }
+ http_last_modified = document_loader->GetResponse().HttpHeaderField(
+ http_names::kLastModified);
+ }
+ }
+ if (!http_last_modified.IsEmpty()) {
+ double date_value = ParseDate(http_last_modified);
+ if (!std::isnan(date_value)) {
+ date.SetMillisecondsSinceEpochForDateTime(ConvertToLocalTime(date_value));
+ found_date = true;
}
}
// FIXME: If this document came from the file system, the HTML5
@@ -5521,7 +5566,7 @@ const KURL Document::SiteForCookies() const {
if (!top.IsLocalFrame()) {
remote_entry.emplace(
top_document_url.Protocol(), top_document_url.Host(),
- network::cors::OriginAccessEntry::kAllowRegisterableDomains);
+ network::mojom::CorsOriginAccessMatchMode::kAllowRegisterableDomains);
}
const OriginAccessEntry& access_entry =
remote_entry ? *remote_entry
@@ -5740,7 +5785,7 @@ void Document::SetEncodingData(const DocumentEncodingData& new_data) {
if (title_element_ && Encoding() != new_data.Encoding() &&
!ElementTraversal::FirstWithin(*title_element_) &&
Encoding() == Latin1Encoding() &&
- title_element_->textContent().ContainsOnlyLatin1()) {
+ title_element_->textContent().ContainsOnlyLatin1OrEmpty()) {
CString original_bytes = title_element_->textContent().Latin1();
std::unique_ptr<TextCodec> codec = NewTextCodec(new_data.Encoding());
String correctly_decoded_title =
@@ -5760,7 +5805,7 @@ void Document::SetEncodingData(const DocumentEncodingData& new_data) {
visually_ordered_ = should_use_visual_ordering;
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kVisuallyOrdered));
+ style_change_reason::kVisuallyOrdered));
}
}
@@ -5881,11 +5926,9 @@ void Document::setDesignMode(const String& value) {
if (new_value == design_mode_)
return;
design_mode_ = new_value;
- StyleChangeType type = RuntimeEnabledFeatures::LayoutNGEnabled()
- ? kNeedsReattachStyleChange
- : kSubtreeStyleChange;
- SetNeedsStyleRecalc(type, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kDesignMode));
+ SetNeedsStyleRecalc(
+ kSubtreeStyleChange,
+ StyleChangeReasonForTracing::Create(style_change_reason::kDesignMode));
}
Document* Document::ParentDocument() const {
@@ -5952,7 +5995,7 @@ const SVGDocumentExtensions* Document::SvgExtensions() {
SVGDocumentExtensions& Document::AccessSVGExtensions() {
if (!svg_extensions_)
- svg_extensions_ = new SVGDocumentExtensions(this);
+ svg_extensions_ = MakeGarbageCollected<SVGDocumentExtensions>(this);
return *svg_extensions_;
}
@@ -6023,7 +6066,7 @@ void Document::FinishedParsing() {
// dispatched in a queued task, see https://crbug.com/425790
if (document_timing_.DomContentLoadedEventStart().is_null())
document_timing_.MarkDomContentLoadedEventStart();
- DispatchEvent(*Event::CreateBubble(EventTypeNames::DOMContentLoaded));
+ DispatchEvent(*Event::CreateBubble(event_type_names::kDOMContentLoaded));
if (document_timing_.DomContentLoadedEventEnd().is_null())
document_timing_.MarkDomContentLoadedEventEnd();
SetParsingState(kFinishedParsing);
@@ -6067,7 +6110,7 @@ void Document::FinishedParsing() {
TRACE_EVENT_INSTANT1("devtools.timeline", "MarkDOMContent",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorMarkLoadEvent::Data(frame));
+ inspector_mark_load_event::Data(frame));
probe::domContentLoadedEventFired(frame);
frame->GetIdlenessDetector()->DomContentLoadedEventFired();
}
@@ -6514,7 +6557,7 @@ bool Document::CanExecuteScripts(ReasonForCallingCanExecuteScripts reason) {
// main world's CSP (such as for privileged isolated worlds). See
// https://crbug.com/811528.
if (IsSandboxed(kSandboxScripts) &&
- !GetFrame()->GetScriptController().ShouldBypassMainWorldCSP()) {
+ !ContentSecurityPolicy::ShouldBypassMainWorld(this)) {
// FIXME: This message should be moved off the console once a solution to
// https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
if (reason == kAboutToExecuteScript) {
@@ -6527,20 +6570,20 @@ bool Document::CanExecuteScripts(ReasonForCallingCanExecuteScripts reason) {
return false;
}
- ContentSettingsClient* settings_client =
- GetFrame()->GetContentSettingsClient();
- if (!settings_client)
+ // No scripting on a detached frame.
+ if (!GetFrame()->Client())
return false;
- Settings* settings = GetFrame()->GetSettings();
- if (!settings_client->AllowScript(settings && settings->GetScriptEnabled())) {
- if (reason == kAboutToExecuteScript)
- settings_client->DidNotAllowScript();
-
- return false;
- }
+ WebContentSettingsClient* settings_client =
+ GetFrame()->GetContentSettingsClient();
- return true;
+ Settings* settings = GetFrame()->GetSettings();
+ bool script_enabled = settings && settings->GetScriptEnabled();
+ if (settings_client)
+ script_enabled = settings_client->AllowScript(script_enabled);
+ if (!script_enabled && reason == kAboutToExecuteScript && settings_client)
+ settings_client->DidNotAllowScript();
+ return script_enabled;
}
bool Document::IsRenderingReady() const {
@@ -6555,7 +6598,7 @@ bool Document::AllowInlineEventHandler(Node* node,
Element* element = node && node->IsElementNode() ? ToElement(node) : nullptr;
if (!ContentSecurityPolicy::ShouldBypassMainWorld(this) &&
!GetContentSecurityPolicy()->AllowInlineEventHandler(
- element, listener->Code(), context_url, context_line))
+ element, listener->ScriptBody(), context_url, context_line))
return false;
// HTML says that inline script needs browsing context to create its execution
@@ -6667,8 +6710,10 @@ Document::EnsureIntersectionObserverController() {
}
ResizeObserverController& Document::EnsureResizeObserverController() {
- if (!resize_observer_controller_)
- resize_observer_controller_ = new ResizeObserverController();
+ if (!resize_observer_controller_) {
+ resize_observer_controller_ =
+ MakeGarbageCollected<ResizeObserverController>();
+ }
return *resize_observer_controller_;
}
@@ -6886,7 +6931,7 @@ ScriptedIdleTaskController& Document::EnsureScriptedIdleTaskController() {
int Document::RequestIdleCallback(
ScriptedIdleTaskController::IdleTask* idle_task,
- const IdleRequestOptions& options) {
+ const IdleRequestOptions* options) {
return EnsureScriptedIdleTaskController().RegisterCallback(idle_task,
options);
}
@@ -6951,8 +6996,7 @@ bool Document::ThreadedParsingEnabledForTesting() {
}
SnapCoordinator* Document::GetSnapCoordinator() {
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled() &&
- !snap_coordinator_)
+ if (!snap_coordinator_)
snap_coordinator_ = SnapCoordinator::Create();
return snap_coordinator_.Get();
@@ -7223,48 +7267,48 @@ void Document::SetBodyAttribute(const QualifiedName& name,
}
const AtomicString& Document::bgColor() const {
- return BodyAttributeValue(bgcolorAttr);
+ return BodyAttributeValue(kBgcolorAttr);
}
void Document::setBgColor(const AtomicString& value) {
if (!IsFrameSet())
- SetBodyAttribute(bgcolorAttr, value);
+ SetBodyAttribute(kBgcolorAttr, value);
}
const AtomicString& Document::fgColor() const {
- return BodyAttributeValue(textAttr);
+ return BodyAttributeValue(kTextAttr);
}
void Document::setFgColor(const AtomicString& value) {
if (!IsFrameSet())
- SetBodyAttribute(textAttr, value);
+ SetBodyAttribute(kTextAttr, value);
}
const AtomicString& Document::alinkColor() const {
- return BodyAttributeValue(alinkAttr);
+ return BodyAttributeValue(kAlinkAttr);
}
void Document::setAlinkColor(const AtomicString& value) {
if (!IsFrameSet())
- SetBodyAttribute(alinkAttr, value);
+ SetBodyAttribute(kAlinkAttr, value);
}
const AtomicString& Document::linkColor() const {
- return BodyAttributeValue(linkAttr);
+ return BodyAttributeValue(kLinkAttr);
}
void Document::setLinkColor(const AtomicString& value) {
if (!IsFrameSet())
- SetBodyAttribute(linkAttr, value);
+ SetBodyAttribute(kLinkAttr, value);
}
const AtomicString& Document::vlinkColor() const {
- return BodyAttributeValue(vlinkAttr);
+ return BodyAttributeValue(kVlinkAttr);
}
void Document::setVlinkColor(const AtomicString& value) {
if (!IsFrameSet())
- SetBodyAttribute(vlinkAttr, value);
+ SetBodyAttribute(kVlinkAttr, value);
}
template <unsigned type>
@@ -7376,7 +7420,7 @@ void Document::SetShadowCascadeOrder(ShadowCascadeOrder order) {
order == ShadowCascadeOrder::kShadowCascadeV1) {
SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kShadow));
+ StyleChangeReasonForTracing::Create(style_change_reason::kShadow));
UseCounter::Count(*this, WebFeature::kMixedShadowRootV0AndV1);
}
@@ -7474,12 +7518,12 @@ scoped_refptr<base::SingleThreadTaskRunner> Document::GetTaskRunner(
// cases, though, there isn't a good candidate (most commonly when either the
// passed-in document or ContextDocument() used to be attached to a Frame but
// has since been detached).
- return Platform::Current()->CurrentThread()->GetTaskRunner();
+ return Thread::Current()->GetTaskRunner();
}
Policy* Document::policy() {
if (!policy_)
- policy_ = new DocumentPolicy(this);
+ policy_ = MakeGarbageCollected<DocumentPolicy>(this);
return policy_.Get();
}
@@ -7579,21 +7623,6 @@ void Document::Trace(blink::Visitor* visitor) {
SynchronousMutationNotifier::Trace(visitor);
}
-void Document::RecordDeferredLoadReason(WouldLoadReason reason) {
- DCHECK(would_load_reason_ == WouldLoadReason::kInvalid ||
- reason != WouldLoadReason::kCreated);
- DCHECK(reason != WouldLoadReason::kInvalid);
- DCHECK(GetFrame());
- DCHECK(GetFrame()->IsCrossOriginSubframe());
- if (reason <= would_load_reason_ ||
- !GetFrame()->Loader().StateMachine()->CommittedFirstRealDocumentLoad())
- return;
- for (int i = static_cast<int>(would_load_reason_) + 1;
- i <= static_cast<int>(reason); ++i)
- RecordLoadReasonToHistogram(static_cast<WouldLoadReason>(i));
- would_load_reason_ = reason;
-}
-
void Document::RecordUkmOutliveTimeAfterShutdown(int outlive_time_count) {
if (!needs_to_record_ukm_outlive_time_)
return;
@@ -7639,10 +7668,11 @@ SlotAssignmentEngine& Document::GetSlotAssignmentEngine() {
return *slot_assignment_engine_;
}
-bool Document::IsSlotAssignmentOrLegacyDistributionDirty() {
+bool Document::IsSlotAssignmentOrLegacyDistributionDirty() const {
if (ChildNeedsDistributionRecalc())
return true;
- if (GetSlotAssignmentEngine().HasPendingSlotAssignmentRecalc()) {
+ if (slot_assignment_engine_ &&
+ slot_assignment_engine_->HasPendingSlotAssignmentRecalc()) {
return true;
}
return false;
@@ -7656,20 +7686,28 @@ bool Document::IsLazyLoadPolicyEnforced() const {
LazyLoadImageObserver& Document::EnsureLazyLoadImageObserver() {
if (!lazy_load_image_observer_)
- lazy_load_image_observer_ = new LazyLoadImageObserver();
+ lazy_load_image_observer_ = MakeGarbageCollected<LazyLoadImageObserver>();
return *lazy_load_image_observer_;
}
void Document::ReportFeaturePolicyViolation(
- mojom::FeaturePolicyFeature feature) const {
+ mojom::FeaturePolicyFeature feature,
+ mojom::FeaturePolicyDisposition disposition,
+ const String& message) const {
if (!RuntimeEnabledFeatures::FeaturePolicyReportingEnabled())
return;
- if (!GetFrame())
+ LocalFrame* frame = GetFrame();
+ if (!frame)
return;
const String& feature_name = GetNameForFeature(feature);
- FeaturePolicyViolationReportBody* body = new FeaturePolicyViolationReportBody(
- feature_name, "Feature policy violation", SourceLocation::Capture());
- Report* report = new Report("feature-policy", Url().GetString(), body);
+ FeaturePolicyViolationReportBody* body =
+ MakeGarbageCollected<FeaturePolicyViolationReportBody>(
+ feature_name, "Feature policy violation",
+ (disposition == mojom::FeaturePolicyDisposition::kReport ? "report"
+ : "enforce"),
+ SourceLocation::Capture());
+ Report* report = MakeGarbageCollected<Report>("feature-policy-violation",
+ Url().GetString(), body);
ReportingContext::From(this)->QueueReport(report);
bool is_null;
@@ -7679,9 +7717,24 @@ void Document::ReportFeaturePolicyViolation(
column_number = is_null ? 0 : column_number;
// Send the feature policy violation report to the Reporting API.
- GetFrame()->GetReportingService()->QueueFeaturePolicyViolationReport(
- Url(), feature_name, "Feature policy violation", body->sourceFile(),
- line_number, column_number);
+ frame->GetReportingService()->QueueFeaturePolicyViolationReport(
+ Url(), feature_name,
+ (disposition == mojom::FeaturePolicyDisposition::kReport ? "report"
+ : "enforce"),
+ "Feature policy violation", body->sourceFile(), line_number,
+ column_number);
+ // TODO(iclelland): Report something different in report-only mode
+ if (disposition == mojom::FeaturePolicyDisposition::kEnforce) {
+ frame->Console().AddMessage(ConsoleMessage::Create(
+ kViolationMessageSource, kErrorMessageLevel,
+ (message.IsEmpty() ? ("Feature policy violation: " + feature_name +
+ " is not allowed in this document.")
+ : message)));
+ }
+}
+
+void Document::IncrementNumberOfCanvases() {
+ num_canvases_++;
}
void Document::SendViolationReport(
@@ -7721,7 +7774,7 @@ template class CORE_TEMPLATE_EXPORT Supplement<Document>;
#ifndef NDEBUG
static WeakDocumentSet& liveDocumentSet() {
DEFINE_STATIC_LOCAL(blink::Persistent<WeakDocumentSet>, set,
- (new WeakDocumentSet));
+ (blink::MakeGarbageCollected<WeakDocumentSet>()));
return *set;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/document.h b/chromium/third_party/blink/renderer/core/dom/document.h
index e5e57044bbf..18de74e9ce7 100644
--- a/chromium/third_party/blink/renderer/core/dom/document.h
+++ b/chromium/third_party/blink/renderer/core/dom/document.h
@@ -35,6 +35,7 @@
#include "base/memory/scoped_refptr.h"
#include "mojo/public/cpp/bindings/binding_set.h"
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/navigation_initiator.mojom-blink.h"
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
@@ -61,12 +62,14 @@
#include "third_party/blink/renderer/core/frame/hosts_using_features.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element.h"
#include "third_party/blink/renderer/core/html/parser/parser_synchronization_policy.h"
+#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/bit_vector.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -177,7 +180,7 @@ class SerializedScriptValue;
class Settings;
class SlotAssignmentEngine;
class SnapCoordinator;
-class StringOrDictionary;
+class StringOrElementCreationOptions;
class StyleEngine;
class StyleResolver;
class StylePropertyMapReadOnly;
@@ -226,26 +229,6 @@ enum ShadowCascadeOrder {
kShadowCascadeV1
};
-// Collect data about deferred loading of offscreen cross-origin documents. All
-// cross-origin documents log Created. Only those that would load log a reason.
-// We can then see the % of cross-origin documents that never have to load.
-// See https://crbug.com/635105.
-// Logged to UMA, don't re-arrange entries without creating a new histogram.
-enum class WouldLoadReason {
- kInvalid,
- kCreated,
- k3ScreensAway,
- k2ScreensAway,
- k1ScreenAway,
- kVisible,
- // If outer and inner frames aren't in the same process we can't determine
- // if the inner frame is visible, so just load it.
- // TODO(dgrogan): Revisit after https://crbug.com/650433 is fixed.
- kNoParent,
-
- kCount,
-};
-
enum class SecureContextState { kUnknown, kNonSecure, kSecure };
using DocumentClassFlags = unsigned char;
@@ -267,7 +250,7 @@ class CORE_EXPORT Document : public ContainerNode,
public:
static Document* Create(const DocumentInit& init) {
- return new Document(init);
+ return MakeGarbageCollected<Document>(init);
}
static Document* CreateForTest();
// Factory for web-exposed Document constructor. The argument document must be
@@ -275,7 +258,10 @@ class CORE_EXPORT Document : public ContainerNode,
// source of ExecutionContext and security origin of the new document.
// https://dom.spec.whatwg.org/#dom-document-document
static Document* Create(Document&);
+
+ Document(const DocumentInit&, DocumentClassFlags = kDefaultDocumentClass);
~Document() override;
+
static Range* CreateRangeAdjustedToTreeScope(const TreeScope&,
const Position&);
@@ -291,6 +277,10 @@ class CORE_EXPORT Document : public ContainerNode,
using SecurityContext::GetContentSecurityPolicy;
using TreeScope::getElementById;
+ // ExecutionContext overrides:
+ bool IsDocument() const final { return true; }
+ bool ShouldInstallV8Extensions() const final;
+
bool CanContainRangeEndPoint() const override { return true; }
SelectorQueryCache& GetSelectorQueryCache();
@@ -301,22 +291,23 @@ class CORE_EXPORT Document : public ContainerNode,
// DOM methods & attributes for Document
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(freeze);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockerror);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resume);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(visibilitychange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy, kBeforecopy);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut, kBeforecut);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste, kBeforepaste);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(freeze, kFreeze);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockchange, kPointerlockchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockerror, kPointerlockerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange, kReadystatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resume, kResume);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(search, kSearch);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation,
+ kSecuritypolicyviolation);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(visibilitychange, kVisibilitychange);
ViewportData& GetViewportData() const { return *viewport_data_; }
String OutgoingReferrer() const override;
- ReferrerPolicy GetReferrerPolicy() const override;
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const override;
void SetDoctype(DocumentType*);
DocumentType* doctype() const { return doc_type_.Get(); }
@@ -330,14 +321,14 @@ class CORE_EXPORT Document : public ContainerNode,
Element* CreateElementForBinding(const AtomicString& local_name,
ExceptionState& = ASSERT_NO_EXCEPTION);
Element* CreateElementForBinding(const AtomicString& local_name,
- const StringOrDictionary&,
+ const StringOrElementCreationOptions&,
ExceptionState&);
Element* createElementNS(const AtomicString& namespace_uri,
const AtomicString& qualified_name,
ExceptionState&);
Element* createElementNS(const AtomicString& namespace_uri,
const AtomicString& qualified_name,
- const StringOrDictionary&,
+ const StringOrElementCreationOptions&,
ExceptionState&);
DocumentFragment* createDocumentFragment();
Text* createTextNode(const String& data);
@@ -363,7 +354,7 @@ class CORE_EXPORT Document : public ContainerNode,
const CreateElementFlags = CreateElementFlags());
CSSStyleSheet* createEmptyCSSStyleSheet(ScriptState*,
- const CSSStyleSheetInit&,
+ const CSSStyleSheetInit*,
ExceptionState&);
CSSStyleSheet* createEmptyCSSStyleSheet(ScriptState*, ExceptionState&);
@@ -374,12 +365,12 @@ class CORE_EXPORT Document : public ContainerNode,
ScriptPromise createCSSStyleSheet(ScriptState*,
const String&,
- const CSSStyleSheetInit&,
+ const CSSStyleSheetInit*,
ExceptionState&);
CSSStyleSheet* createCSSStyleSheetSync(ScriptState*,
const String&,
- const CSSStyleSheetInit&,
+ const CSSStyleSheetInit*,
ExceptionState&);
CSSStyleSheet* createCSSStyleSheetSync(ScriptState*,
@@ -540,7 +531,9 @@ class CORE_EXPORT Document : public ContainerNode,
void SetupFontBuilder(ComputedStyle& document_style);
bool NeedsLayoutTreeUpdate() const;
- bool NeedsLayoutTreeUpdateForNode(const Node&) const;
+ bool NeedsLayoutTreeUpdateForNode(const Node&,
+ bool ignore_adjacent_style = false) const;
+
// Update ComputedStyles and attach LayoutObjects if necessary, but don't
// lay out.
void UpdateStyleAndLayoutTree();
@@ -594,7 +587,7 @@ class CORE_EXPORT Document : public ContainerNode,
NOTREACHED();
}
- // If you have a Document, use layoutView() instead which is faster.
+ // If you have a Document, use GetLayoutView() instead which is faster.
void GetLayoutObject() const = delete;
LayoutView* GetLayoutView() const { return layout_view_; }
@@ -954,6 +947,9 @@ class CORE_EXPORT Document : public ContainerNode,
String domain() const;
void setDomain(const String& new_domain, ExceptionState&);
+ void OverrideLastModified(const AtomicString& modified) {
+ override_last_modified_ = modified;
+ }
String lastModified() const;
// The cookieURL is used to query the cookie database for this document's
@@ -1003,14 +999,8 @@ class CORE_EXPORT Document : public ContainerNode,
HTMLHeadElement* head() const;
- // Decide which element is to define the viewport's overflow policy. If
- // |rootStyle| is set, use that as the style for the root element, rather than
- // obtaining it on our own. The reason for this is that style may not have
- // been associated with the elements yet - in which case it may have been
- // calculated on the fly (without associating it with the actual element)
- // somewhere.
- Element* ViewportDefiningElement(
- const ComputedStyle* root_style = nullptr) const;
+ // Decide which element is to define the viewport's overflow policy.
+ Element* ViewportDefiningElement() const;
DocumentMarkerController& Markers() const { return *markers_; }
@@ -1220,7 +1210,7 @@ class CORE_EXPORT Document : public ContainerNode,
base::TimeTicks monotonic_animation_start_time);
int RequestIdleCallback(ScriptedIdleTaskController::IdleTask*,
- const IdleRequestOptions&);
+ const IdleRequestOptions*);
void CancelIdleCallback(int id);
EventTarget* ErrorEventTarget() final;
@@ -1234,7 +1224,7 @@ class CORE_EXPORT Document : public ContainerNode,
ScriptValue registerElement(ScriptState*,
const AtomicString& name,
- const ElementRegistrationOptions&,
+ const ElementRegistrationOptions*,
ExceptionState&);
V0CustomElementRegistrationContext* RegistrationContext() const {
return registration_context_.Get();
@@ -1403,9 +1393,6 @@ class CORE_EXPORT Document : public ContainerNode,
bool IsInMainFrame() const;
- void RecordDeferredLoadReason(WouldLoadReason);
- WouldLoadReason DeferredLoadReason() { return would_load_reason_; }
-
const PropertyRegistry* GetPropertyRegistry() const;
PropertyRegistry* GetPropertyRegistry();
@@ -1467,7 +1454,7 @@ class CORE_EXPORT Document : public ContainerNode,
SlotAssignmentEngine& GetSlotAssignmentEngine();
- bool IsSlotAssignmentOrLegacyDistributionDirty();
+ bool IsSlotAssignmentOrLegacyDistributionDirty() const;
#if DCHECK_IS_ON()
unsigned& SlotAssignmentRecalcForbiddenRecursionDepth() {
@@ -1504,11 +1491,22 @@ class CORE_EXPORT Document : public ContainerNode,
return agent_cluster_id_;
}
- void ReportFeaturePolicyViolation(mojom::FeaturePolicyFeature) const override;
+ void ReportFeaturePolicyViolation(
+ mojom::FeaturePolicyFeature,
+ mojom::FeaturePolicyDisposition,
+ const String& message = g_empty_string) const override;
- protected:
- Document(const DocumentInit&, DocumentClassFlags = kDefaultDocumentClass);
+ bool IsParsedFeaturePolicy(mojom::FeaturePolicyFeature feature) const {
+ return parsed_feature_policies_.QuickGet(static_cast<int>(feature));
+ }
+
+ void SetParsedFeaturePolicy(mojom::FeaturePolicyFeature feature) {
+ parsed_feature_policies_.QuickSet(static_cast<int>(feature));
+ }
+ void IncrementNumberOfCanvases();
+
+ protected:
void DidUpdateSecurityOrigin() final;
void ClearXMLVersion() { xml_version_ = String(); }
@@ -1577,8 +1575,6 @@ class CORE_EXPORT Document : public ContainerNode,
void BeginLifecycleUpdatesIfRenderingReady();
- bool IsDocument() const final { return true; }
-
void ChildrenChanged(const ChildrenChange&) override;
String nodeName() const final;
@@ -1894,8 +1890,6 @@ class CORE_EXPORT Document : public ContainerNode,
Member<SnapCoordinator> snap_coordinator_;
- WouldLoadReason would_load_reason_;
-
Member<PropertyRegistry> property_registry_;
unsigned password_count_;
@@ -1939,6 +1933,9 @@ class CORE_EXPORT Document : public ContainerNode,
// This is set through feature policy 'vertical-scroll'.
bool is_vertical_scroll_enforced_ = false;
+ // The number of canvas elements on the document
+ int num_canvases_ = 0;
+
// A list of all the navigation_initiator bindings owned by this document.
// Used to report CSP violations that result from CSP blocking
// navigation requests that were initiated by this document.
@@ -1949,6 +1946,12 @@ class CORE_EXPORT Document : public ContainerNode,
// https://tc39.github.io/ecma262/#sec-agent-clusters
const base::UnguessableToken agent_cluster_id_;
+
+ // Tracks which feature policies have already been parsed, so as not to count
+ // them multiple times.
+ BitVector parsed_feature_policies_;
+
+ AtomicString override_last_modified_;
};
extern template class CORE_EXTERN_TEMPLATE_EXPORT Supplement<Document>;
diff --git a/chromium/third_party/blink/renderer/core/dom/document.idl b/chromium/third_party/blink/renderer/core/dom/document.idl
index 83d8beb183b..0477c21d353 100644
--- a/chromium/third_party/blink/renderer/core/dom/document.idl
+++ b/chromium/third_party/blink/renderer/core/dom/document.idl
@@ -176,9 +176,8 @@ typedef (HTMLScriptElement or SVGScriptElement) HTMLOrSVGScriptElement;
// FIXME: The registerElement return type should be Function.
[RuntimeEnabled=CustomElementsV0, CallWith=ScriptState, CustomElementCallbacks, RaisesException, DeprecateAs=DocumentRegisterElement] any registerElement(DOMString type, optional ElementRegistrationOptions options);
// https://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-instantiate
- // FIXME: The typeExtension arguments should not be nullable.
- [CustomElementCallbacks, PerWorldBindings, RaisesException, ImplementedAs=CreateElementForBinding] Element createElement(DOMString localName, (DOMString or Dictionary)? options);
- [CustomElementCallbacks, RaisesException] Element createElementNS(DOMString? namespaceURI, DOMString qualifiedName, (DOMString or Dictionary)? options);
+ [CustomElementCallbacks, PerWorldBindings, RaisesException, ImplementedAs=CreateElementForBinding] Element createElement(DOMString localName, (DOMString or ElementCreationOptions) options);
+ [CustomElementCallbacks, RaisesException] Element createElementNS(DOMString? namespaceURI, DOMString qualifiedName, (DOMString or ElementCreationOptions) options);
// Page Visibility
// https://w3c.github.io/page-visibility/#extensions-to-the-document-interface
diff --git a/chromium/third_party/blink/renderer/core/dom/document_and_element_event_handlers.h b/chromium/third_party/blink/renderer/core/dom/document_and_element_event_handlers.h
index e09780ba578..84cad84b563 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_and_element_event_handlers.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_and_element_event_handlers.h
@@ -14,9 +14,9 @@ class DocumentAndElementEventHandlers {
STATIC_ONLY(DocumentAndElementEventHandlers);
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(copy);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cut);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(paste);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(copy, kCopy);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cut, kCut);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(paste, kPaste);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/document_fragment.cc b/chromium/third_party/blink/renderer/core/dom/document_fragment.cc
index 1e836ce4a3a..b32f0044c32 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_fragment.cc
@@ -35,7 +35,8 @@ DocumentFragment::DocumentFragment(Document* document,
: ContainerNode(document, construction_type) {}
DocumentFragment* DocumentFragment::Create(Document& document) {
- return new DocumentFragment(&document, Node::kCreateDocumentFragment);
+ return MakeGarbageCollected<DocumentFragment>(&document,
+ Node::kCreateDocumentFragment);
}
String DocumentFragment::nodeName() const {
diff --git a/chromium/third_party/blink/renderer/core/dom/document_fragment.h b/chromium/third_party/blink/renderer/core/dom/document_fragment.h
index cb87be03206..fd362515738 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_fragment.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_fragment.h
@@ -36,6 +36,8 @@ class CORE_EXPORT DocumentFragment : public ContainerNode {
public:
static DocumentFragment* Create(Document&);
+ DocumentFragment(Document*, ConstructionType = kCreateContainer);
+
void ParseHTML(const String&,
Element* context_element,
ParserContentPolicy = kAllowScriptingContent);
@@ -47,7 +49,6 @@ class CORE_EXPORT DocumentFragment : public ContainerNode {
virtual bool IsTemplateContent() const { return false; }
protected:
- DocumentFragment(Document*, ConstructionType = kCreateContainer);
String nodeName() const final;
private:
diff --git a/chromium/third_party/blink/renderer/core/dom/document_init.cc b/chromium/third_party/blink/renderer/core/dom/document_init.cc
index f8dc05ee14f..a1db021d271 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_init.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_init.cc
@@ -129,7 +129,7 @@ DocumentInit::InsecureNavigationsToUpgrade() const {
bool DocumentInit::IsHostedInReservedIPRange() const {
if (DocumentLoader* loader = MasterDocumentLoader()) {
if (!loader->GetResponse().RemoteIPAddress().IsEmpty()) {
- return NetworkUtils::IsReservedIPAddress(
+ return network_utils::IsReservedIPAddress(
loader->GetResponse().RemoteIPAddress());
}
}
diff --git a/chromium/third_party/blink/renderer/core/dom/document_lifecycle.h b/chromium/third_party/blink/renderer/core/dom/document_lifecycle.h
index 2cb5634b39b..5d02b2874ec 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_lifecycle.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_lifecycle.h
@@ -87,6 +87,9 @@ class CORE_EXPORT DocumentLifecycle {
kStopped,
};
+ // This must be kept coordinated with WebWidget::LifecycleUpdateReason
+ enum LifecycleUpdateReason { kBeginMainFrame, kTest, kOther };
+
class Scope {
STACK_ALLOCATED();
diff --git a/chromium/third_party/blink/renderer/core/dom/document_parser_timing.cc b/chromium/third_party/blink/renderer/core/dom/document_parser_timing.cc
index a9c99cd4980..d184e49935d 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_parser_timing.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_parser_timing.cc
@@ -17,7 +17,7 @@ DocumentParserTiming& DocumentParserTiming::From(Document& document) {
DocumentParserTiming* timing =
Supplement<Document>::From<DocumentParserTiming>(document);
if (!timing) {
- timing = new DocumentParserTiming(document);
+ timing = MakeGarbageCollected<DocumentParserTiming>(document);
ProvideTo(document, timing);
}
return *timing;
diff --git a/chromium/third_party/blink/renderer/core/dom/document_parser_timing.h b/chromium/third_party/blink/renderer/core/dom/document_parser_timing.h
index 4cea8dc7f16..8cd533d7092 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_parser_timing.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_parser_timing.h
@@ -22,6 +22,7 @@ class DocumentParserTiming final
public:
static const char kSupplementName[];
+ explicit DocumentParserTiming(Document&);
virtual ~DocumentParserTiming() = default;
static DocumentParserTiming& From(Document&);
@@ -99,7 +100,6 @@ class DocumentParserTiming final
void Trace(blink::Visitor*) override;
private:
- explicit DocumentParserTiming(Document&);
void NotifyDocumentParserTimingChanged();
TimeTicks parser_start_;
diff --git a/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.cc b/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.cc
index de59cff236a..6be49cd3556 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.cc
@@ -21,7 +21,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -124,19 +124,19 @@ void CollectFeatures(Element& root,
features.element_count++;
Element& element = ToElement(node);
- if (element.HasTagName(aTag)) {
+ if (element.HasTagName(kATag)) {
features.anchor_count++;
- } else if (element.HasTagName(formTag)) {
+ } else if (element.HasTagName(kFormTag)) {
features.form_count++;
- } else if (element.HasTagName(inputTag)) {
+ } else if (element.HasTagName(kInputTag)) {
const HTMLInputElement& input = ToHTMLInputElement(element);
- if (input.type() == InputTypeNames::text) {
+ if (input.type() == input_type_names::kText) {
features.text_input_count++;
- } else if (input.type() == InputTypeNames::password) {
+ } else if (input.type() == input_type_names::kPassword) {
features.password_input_count++;
}
- } else if (element.HasTagName(pTag) || element.HasTagName(preTag)) {
- if (element.HasTagName(pTag)) {
+ } else if (element.HasTagName(kPTag) || element.HasTagName(kPreTag)) {
+ if (element.HasTagName(kPTag)) {
features.p_count++;
} else {
features.pre_count++;
@@ -156,7 +156,7 @@ void CollectFeatures(Element& root,
features.moz_score_all_linear = std::min(features.moz_score_all_linear,
kMozScoreAllLinearSaturation);
}
- } else if (element.HasTagName(liTag)) {
+ } else if (element.HasTagName(kLiTag)) {
is_list_item = true;
}
CollectFeatures(element, features, under_list_item || is_list_item);
diff --git a/chromium/third_party/blink/renderer/core/dom/document_test.cc b/chromium/third_party/blink/renderer/core/dom/document_test.cc
index 45b22787b3b..f20a13bac88 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_test.cc
@@ -33,9 +33,11 @@
#include <memory>
#include "build/build_config.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/web_application_cache_host.h"
+#include "third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
@@ -56,7 +58,6 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -73,7 +74,7 @@ class DocumentTest : public PageTestBase {
void DocumentTest::SetHtmlInnerHTML(const char* html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
namespace {
@@ -357,8 +358,8 @@ TEST_F(DocumentTest, DomTreeVersionForRemoval) {
Document& doc = GetDocument();
{
DocumentFragment* fragment = DocumentFragment::Create(doc);
- fragment->appendChild(Element::Create(HTMLNames::divTag, &doc));
- fragment->appendChild(Element::Create(HTMLNames::spanTag, &doc));
+ fragment->appendChild(Element::Create(html_names::kDivTag, &doc));
+ fragment->appendChild(Element::Create(html_names::kSpanTag, &doc));
uint64_t original_version = doc.DomTreeVersion();
fragment->RemoveChildren();
EXPECT_EQ(original_version + 1, doc.DomTreeVersion())
@@ -367,8 +368,8 @@ TEST_F(DocumentTest, DomTreeVersionForRemoval) {
{
DocumentFragment* fragment = DocumentFragment::Create(doc);
- Node* child = Element::Create(HTMLNames::divTag, &doc);
- child->appendChild(Element::Create(HTMLNames::spanTag, &doc));
+ Node* child = Element::Create(html_names::kDivTag, &doc);
+ child->appendChild(Element::Create(html_names::kSpanTag, &doc));
fragment->appendChild(child);
uint64_t original_version = doc.DomTreeVersion();
fragment->removeChild(child);
@@ -417,50 +418,50 @@ TEST_F(DocumentTest, LinkManifest) {
// Check that we use the first manifest with <link rel=manifest>
auto* link = HTMLLinkElement::Create(GetDocument(), CreateElementFlags());
- link->setAttribute(blink::HTMLNames::relAttr, "manifest");
- link->setAttribute(blink::HTMLNames::hrefAttr, "foo.json");
+ link->setAttribute(blink::html_names::kRelAttr, "manifest");
+ link->setAttribute(blink::html_names::kHrefAttr, "foo.json");
GetDocument().head()->AppendChild(link);
EXPECT_EQ(link, GetDocument().LinkManifest());
auto* link2 = HTMLLinkElement::Create(GetDocument(), CreateElementFlags());
- link2->setAttribute(blink::HTMLNames::relAttr, "manifest");
- link2->setAttribute(blink::HTMLNames::hrefAttr, "bar.json");
+ link2->setAttribute(blink::html_names::kRelAttr, "manifest");
+ link2->setAttribute(blink::html_names::kHrefAttr, "bar.json");
GetDocument().head()->InsertBefore(link2, link);
EXPECT_EQ(link2, GetDocument().LinkManifest());
GetDocument().head()->AppendChild(link2);
EXPECT_EQ(link, GetDocument().LinkManifest());
// Check that crazy URLs are accepted.
- link->setAttribute(blink::HTMLNames::hrefAttr, "http:foo.json");
+ link->setAttribute(blink::html_names::kHrefAttr, "http:foo.json");
EXPECT_EQ(link, GetDocument().LinkManifest());
// Check that empty URLs are accepted.
- link->setAttribute(blink::HTMLNames::hrefAttr, "");
+ link->setAttribute(blink::html_names::kHrefAttr, "");
EXPECT_EQ(link, GetDocument().LinkManifest());
// Check that URLs from different origins are accepted.
- link->setAttribute(blink::HTMLNames::hrefAttr,
+ link->setAttribute(blink::html_names::kHrefAttr,
"http://example.org/manifest.json");
EXPECT_EQ(link, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::hrefAttr,
+ link->setAttribute(blink::html_names::kHrefAttr,
"http://foo.example.org/manifest.json");
EXPECT_EQ(link, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::hrefAttr,
+ link->setAttribute(blink::html_names::kHrefAttr,
"http://foo.bar/manifest.json");
EXPECT_EQ(link, GetDocument().LinkManifest());
// More than one token in @rel is accepted.
- link->setAttribute(blink::HTMLNames::relAttr, "foo bar manifest");
+ link->setAttribute(blink::html_names::kRelAttr, "foo bar manifest");
EXPECT_EQ(link, GetDocument().LinkManifest());
// Such as spaces around the token.
- link->setAttribute(blink::HTMLNames::relAttr, " manifest ");
+ link->setAttribute(blink::html_names::kRelAttr, " manifest ");
EXPECT_EQ(link, GetDocument().LinkManifest());
// Check that rel=manifest actually matters.
- link->setAttribute(blink::HTMLNames::relAttr, "");
+ link->setAttribute(blink::html_names::kRelAttr, "");
EXPECT_EQ(link2, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::relAttr, "manifest");
+ link->setAttribute(blink::html_names::kRelAttr, "manifest");
// Check that link outside of the <head> are ignored.
GetDocument().head()->RemoveChild(link);
@@ -472,58 +473,68 @@ TEST_F(DocumentTest, LinkManifest) {
GetDocument().head()->AppendChild(link2);
// Check that some attribute values do not have an effect.
- link->setAttribute(blink::HTMLNames::crossoriginAttr, "use-credentials");
+ link->setAttribute(blink::html_names::kCrossoriginAttr, "use-credentials");
EXPECT_EQ(link, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::hreflangAttr, "klingon");
+ link->setAttribute(blink::html_names::kHreflangAttr, "klingon");
EXPECT_EQ(link, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::typeAttr, "image/gif");
+ link->setAttribute(blink::html_names::kTypeAttr, "image/gif");
EXPECT_EQ(link, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::sizesAttr, "16x16");
+ link->setAttribute(blink::html_names::kSizesAttr, "16x16");
EXPECT_EQ(link, GetDocument().LinkManifest());
- link->setAttribute(blink::HTMLNames::mediaAttr, "print");
+ link->setAttribute(blink::html_names::kMediaAttr, "print");
EXPECT_EQ(link, GetDocument().LinkManifest());
}
TEST_F(DocumentTest, referrerPolicyParsing) {
- EXPECT_EQ(kReferrerPolicyDefault, GetDocument().GetReferrerPolicy());
+ EXPECT_EQ(network::mojom::ReferrerPolicy::kDefault,
+ GetDocument().GetReferrerPolicy());
struct TestCase {
const char* policy;
- ReferrerPolicy expected;
+ network::mojom::ReferrerPolicy expected;
bool is_legacy;
} tests[] = {
- {"", kReferrerPolicyDefault, false},
+ {"", network::mojom::ReferrerPolicy::kDefault, false},
// Test that invalid policy values are ignored.
- {"not-a-real-policy", kReferrerPolicyDefault, false},
- {"not-a-real-policy,also-not-a-real-policy", kReferrerPolicyDefault,
+ {"not-a-real-policy", network::mojom::ReferrerPolicy::kDefault, false},
+ {"not-a-real-policy,also-not-a-real-policy",
+ network::mojom::ReferrerPolicy::kDefault, false},
+ {"not-a-real-policy,unsafe-url", network::mojom::ReferrerPolicy::kAlways,
false},
- {"not-a-real-policy,unsafe-url", kReferrerPolicyAlways, false},
- {"unsafe-url,not-a-real-policy", kReferrerPolicyAlways, false},
- // Test parsing each of the policy values.
- {"always", kReferrerPolicyAlways, true},
- {"default", kReferrerPolicyNoReferrerWhenDowngrade, true},
- {"never", kReferrerPolicyNever, true},
- {"no-referrer", kReferrerPolicyNever, false},
- {"default", kReferrerPolicyNoReferrerWhenDowngrade, true},
- {"no-referrer-when-downgrade", kReferrerPolicyNoReferrerWhenDowngrade,
+ {"unsafe-url,not-a-real-policy", network::mojom::ReferrerPolicy::kAlways,
false},
- {"origin", kReferrerPolicyOrigin, false},
- {"origin-when-crossorigin", kReferrerPolicyOriginWhenCrossOrigin, true},
- {"origin-when-cross-origin", kReferrerPolicyOriginWhenCrossOrigin, false},
- {"same-origin", kReferrerPolicySameOrigin, false},
- {"strict-origin", kReferrerPolicyStrictOrigin, false},
+ // Test parsing each of the policy values.
+ {"always", network::mojom::ReferrerPolicy::kAlways, true},
+ {"default", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade,
+ true},
+ {"never", network::mojom::ReferrerPolicy::kNever, true},
+ {"no-referrer", network::mojom::ReferrerPolicy::kNever, false},
+ {"default", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade,
+ true},
+ {"no-referrer-when-downgrade",
+ network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, false},
+ {"origin", network::mojom::ReferrerPolicy::kOrigin, false},
+ {"origin-when-crossorigin",
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, true},
+ {"origin-when-cross-origin",
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, false},
+ {"same-origin", network::mojom::ReferrerPolicy::kSameOrigin, false},
+ {"strict-origin", network::mojom::ReferrerPolicy::kStrictOrigin, false},
{"strict-origin-when-cross-origin",
- kReferrerPolicyStrictOriginWhenCrossOrigin, false},
- {"unsafe-url", kReferrerPolicyAlways},
+ network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ false},
+ {"unsafe-url", network::mojom::ReferrerPolicy::kAlways},
};
for (auto test : tests) {
- GetDocument().SetReferrerPolicy(kReferrerPolicyDefault);
+ GetDocument().SetReferrerPolicy(network::mojom::ReferrerPolicy::kDefault);
if (test.is_legacy) {
// Legacy keyword support must be explicitly enabled for the policy to
// parse successfully.
GetDocument().ParseAndSetReferrerPolicy(test.policy);
- EXPECT_EQ(kReferrerPolicyDefault, GetDocument().GetReferrerPolicy());
+ EXPECT_EQ(network::mojom::ReferrerPolicy::kDefault,
+ GetDocument().GetReferrerPolicy());
GetDocument().ParseAndSetReferrerPolicy(test.policy, true);
} else {
GetDocument().ParseAndSetReferrerPolicy(test.policy);
@@ -558,19 +569,19 @@ TEST_F(DocumentTest, StyleVersion) {
EXPECT_TRUE(element);
uint64_t previous_style_version = GetDocument().StyleVersion();
- element->setAttribute(blink::HTMLNames::classAttr, "notfound");
+ element->setAttribute(blink::html_names::kClassAttr, "notfound");
EXPECT_EQ(previous_style_version, GetDocument().StyleVersion());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
previous_style_version = GetDocument().StyleVersion();
- element->setAttribute(blink::HTMLNames::classAttr, "a");
+ element->setAttribute(blink::html_names::kClassAttr, "a");
EXPECT_NE(previous_style_version, GetDocument().StyleVersion());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
previous_style_version = GetDocument().StyleVersion();
- element->setAttribute(blink::HTMLNames::classAttr, "a b");
+ element->setAttribute(blink::html_names::kClassAttr, "a b");
EXPECT_NE(previous_style_version, GetDocument().StyleVersion());
}
@@ -620,13 +631,13 @@ TEST_F(DocumentTest, SynchronousMutationNotifier) {
EXPECT_EQ(GetDocument(), observer.LifecycleContext());
EXPECT_EQ(0, observer.CountContextDestroyedCalled());
- Element* div_node = GetDocument().CreateRawElement(HTMLNames::divTag);
+ Element* div_node = GetDocument().CreateRawElement(html_names::kDivTag);
GetDocument().body()->AppendChild(div_node);
- Element* bold_node = GetDocument().CreateRawElement(HTMLNames::bTag);
+ Element* bold_node = GetDocument().CreateRawElement(html_names::kBTag);
div_node->AppendChild(bold_node);
- Element* italic_node = GetDocument().CreateRawElement(HTMLNames::iTag);
+ Element* italic_node = GetDocument().CreateRawElement(html_names::kITag);
div_node->AppendChild(italic_node);
Node* text_node = GetDocument().createTextNode("0123456789");
@@ -686,7 +697,7 @@ TEST_F(DocumentTest, SynchronousMutationNotifierMergeTextNodes) {
TEST_F(DocumentTest, SynchronousMutationNotifierMoveTreeToNewDocument) {
auto& observer = *new TestSynchronousMutationObserver(GetDocument());
- Node* move_sample = GetDocument().CreateRawElement(HTMLNames::divTag);
+ Node* move_sample = GetDocument().CreateRawElement(html_names::kDivTag);
move_sample->appendChild(GetDocument().createTextNode("a123"));
move_sample->appendChild(GetDocument().createTextNode("b456"));
GetDocument().body()->AppendChild(move_sample);
@@ -710,7 +721,8 @@ TEST_F(DocumentTest, SynchronousMutationNotifieReplaceChild) {
auto& observer = *new TestSynchronousMutationObserver(GetDocument());
Element* const replaced_node = GetDocument().body();
GetDocument().documentElement()->ReplaceChild(
- GetDocument().CreateRawElement(HTMLNames::divTag), GetDocument().body());
+ GetDocument().CreateRawElement(html_names::kDivTag),
+ GetDocument().body());
ASSERT_EQ(2u, observer.ChildrenChangedNodes().size());
EXPECT_EQ(GetDocument().documentElement(),
observer.ChildrenChangedNodes()[0]);
@@ -820,9 +832,10 @@ TEST_F(DocumentTest, ValidationMessageCleanup) {
// true. It's necessary to kick unload process.
GetDocument().ImplicitOpen(kForceSynchronousParsing);
GetDocument().CancelParsing();
- GetDocument().AppendChild(GetDocument().CreateRawElement(HTMLNames::htmlTag));
+ GetDocument().AppendChild(
+ GetDocument().CreateRawElement(html_names::kHTMLTag));
SetHtmlInnerHTML("<body><input required></body>");
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->setTextContent(
"window.onunload = function() {"
"document.querySelector('input').reportValidity(); };");
@@ -968,17 +981,19 @@ TEST_F(DocumentTest, CanExecuteScriptsWithSandboxAndIsolatedWorld) {
ScriptState* isolated_world_without_csp_script_state =
ToScriptState(frame, *world_without_csp);
ASSERT_TRUE(world_without_csp->IsIsolatedWorld());
- EXPECT_FALSE(world_without_csp->IsolatedWorldHasContentSecurityPolicy());
+ EXPECT_FALSE(IsolatedWorldCSP::Get().HasContentSecurityPolicy(
+ kIsolatedWorldWithoutCSPId));
constexpr int kIsolatedWorldWithCSPId = 2;
scoped_refptr<DOMWrapperWorld> world_with_csp =
DOMWrapperWorld::EnsureIsolatedWorld(isolate, kIsolatedWorldWithCSPId);
- DOMWrapperWorld::SetIsolatedWorldContentSecurityPolicy(
+ IsolatedWorldCSP::Get().SetContentSecurityPolicy(
kIsolatedWorldWithCSPId, String::FromUTF8("script-src *"));
ScriptState* isolated_world_with_csp_script_state =
ToScriptState(frame, *world_with_csp);
ASSERT_TRUE(world_with_csp->IsIsolatedWorld());
- EXPECT_TRUE(world_with_csp->IsolatedWorldHasContentSecurityPolicy());
+ EXPECT_TRUE(IsolatedWorldCSP::Get().HasContentSecurityPolicy(
+ kIsolatedWorldWithCSPId));
{
// Since the page is sandboxed, main world script execution shouldn't be
@@ -1143,7 +1158,7 @@ class ParameterizedViewportFitDocumentTest
}
GetDocument().documentElement()->SetInnerHTMLFromString(html.ToString());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
};
diff --git a/chromium/third_party/blink/renderer/core/dom/document_type.h b/chromium/third_party/blink/renderer/core/dom/document_type.h
index 2a3648cf904..fa4bf122c21 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_type.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_type.h
@@ -36,19 +36,20 @@ class DocumentType final : public Node {
const String& name,
const String& public_id,
const String& system_id) {
- return new DocumentType(document, name, public_id, system_id);
+ return MakeGarbageCollected<DocumentType>(document, name, public_id,
+ system_id);
}
- const String& name() const { return name_; }
- const String& publicId() const { return public_id_; }
- const String& systemId() const { return system_id_; }
-
- private:
DocumentType(Document*,
const String& name,
const String& public_id,
const String& system_id);
+ const String& name() const { return name_; }
+ const String& publicId() const { return public_id_; }
+ const String& systemId() const { return system_id_; }
+
+ private:
String nodeName() const override;
NodeType getNodeType() const override;
Node* Clone(Document&, CloneChildrenFlag) const override;
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_exception.cc b/chromium/third_party/blink/renderer/core/dom/dom_exception.cc
index 1676d597178..85e29a72e65 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_exception.cc
+++ b/chromium/third_party/blink/renderer/core/dom/dom_exception.cc
@@ -174,7 +174,7 @@ DOMException* DOMException::Create(DOMExceptionCode exception_code,
const String& sanitized_message,
const String& unsanitized_message) {
const DOMExceptionEntry* entry = FindErrorEntry(exception_code);
- return new DOMException(
+ return MakeGarbageCollected<DOMException>(
ToLegacyErrorCode(entry->code), entry->name ? entry->name : "Error",
sanitized_message.IsNull() ? String(entry->message) : sanitized_message,
unsanitized_message);
@@ -182,7 +182,8 @@ DOMException* DOMException::Create(DOMExceptionCode exception_code,
// static
DOMException* DOMException::Create(const String& message, const String& name) {
- return new DOMException(FindLegacyErrorCode(name), name, message, String());
+ return MakeGarbageCollected<DOMException>(FindLegacyErrorCode(name), name,
+ message, String());
}
// static
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_exception.h b/chromium/third_party/blink/renderer/core/dom/dom_exception.h
index e96e5e8abbf..acc876f0db7 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_exception.h
+++ b/chromium/third_party/blink/renderer/core/dom/dom_exception.h
@@ -49,6 +49,11 @@ class CORE_EXPORT DOMException final : public ScriptWrappable {
// Constructor exposed to script.
static DOMException* Create(const String& message, const String& name);
+ DOMException(unsigned short legacy_code,
+ const String& name,
+ const String& sanitized_message,
+ const String& unsanitized_message);
+
static String GetErrorName(DOMExceptionCode);
static String GetErrorMessage(DOMExceptionCode);
@@ -68,11 +73,6 @@ class CORE_EXPORT DOMException final : public ScriptWrappable {
String ToStringForConsole() const;
private:
- DOMException(unsigned short legacy_code,
- const String& name,
- const String& sanitized_message,
- const String& unsanitized_message);
-
unsigned short legacy_code_;
String name_;
String sanitized_message_;
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_implementation.cc b/chromium/third_party/blink/renderer/core/dom/dom_implementation.cc
index c360933eb10..3dac1a5a6f6 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_implementation.cc
+++ b/chromium/third_party/blink/renderer/core/dom/dom_implementation.cc
@@ -84,9 +84,9 @@ XMLDocument* DOMImplementation::createDocument(
XMLDocument* doc = nullptr;
DocumentInit init =
DocumentInit::Create().WithContextDocument(document_->ContextDocument());
- if (namespace_uri == SVGNames::svgNamespaceURI) {
+ if (namespace_uri == svg_names::kNamespaceURI) {
doc = XMLDocument::CreateSVG(init);
- } else if (namespace_uri == HTMLNames::xhtmlNamespaceURI) {
+ } else if (namespace_uri == html_names::xhtmlNamespaceURI) {
doc = XMLDocument::CreateXHTML(
init.WithRegistrationContext(document_->RegistrationContext()));
} else {
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_implementation.h b/chromium/third_party/blink/renderer/core/dom/dom_implementation.h
index 36016c3cce8..b30c6f1b66d 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_implementation.h
+++ b/chromium/third_party/blink/renderer/core/dom/dom_implementation.h
@@ -40,9 +40,11 @@ class CORE_EXPORT DOMImplementation final : public ScriptWrappable {
public:
static DOMImplementation* Create(Document& document) {
- return new DOMImplementation(document);
+ return MakeGarbageCollected<DOMImplementation>(document);
}
+ explicit DOMImplementation(Document&);
+
// DOM methods & attributes for DOMImplementation
bool hasFeature() { return true; }
DocumentType* createDocumentType(const AtomicString& qualified_name,
@@ -69,8 +71,6 @@ class CORE_EXPORT DOMImplementation final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit DOMImplementation(Document&);
-
Member<Document> document_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_string_list.h b/chromium/third_party/blink/renderer/core/dom/dom_string_list.h
index adb66dfa73f..529413a20ce 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_string_list.h
+++ b/chromium/third_party/blink/renderer/core/dom/dom_string_list.h
@@ -40,7 +40,11 @@ class CORE_EXPORT DOMStringList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DOMStringList* Create() { return new DOMStringList(); }
+ static DOMStringList* Create() {
+ return MakeGarbageCollected<DOMStringList>();
+ }
+
+ explicit DOMStringList() = default;
bool IsEmpty() const { return strings_.IsEmpty(); }
void clear() { strings_.clear(); }
@@ -56,8 +60,6 @@ class CORE_EXPORT DOMStringList final : public ScriptWrappable {
operator const Vector<String>&() const { return strings_; }
private:
- explicit DOMStringList() = default;
-
Vector<String> strings_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_token_list.h b/chromium/third_party/blink/renderer/core/dom/dom_token_list.h
index 5c50df16f1d..00c1f1f2319 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_token_list.h
+++ b/chromium/third_party/blink/renderer/core/dom/dom_token_list.h
@@ -44,8 +44,10 @@ class CORE_EXPORT DOMTokenList : public ScriptWrappable {
public:
static DOMTokenList* Create(Element& element, const QualifiedName& attr) {
- return new DOMTokenList(element, attr);
+ return MakeGarbageCollected<DOMTokenList>(element, attr);
}
+ DOMTokenList(Element& element, const QualifiedName& attr)
+ : element_(element), attribute_name_(attr) {}
~DOMTokenList() override = default;
void Trace(blink::Visitor*) override;
@@ -75,8 +77,6 @@ class CORE_EXPORT DOMTokenList : public ScriptWrappable {
void Remove(const AtomicString&);
protected:
- DOMTokenList(Element& element, const QualifiedName& attr)
- : element_(element), attribute_name_(attr) {}
Element& GetElement() const { return *element_; }
virtual bool ValidateTokenValue(const AtomicString&, ExceptionState&) const;
diff --git a/chromium/third_party/blink/renderer/core/dom/element.cc b/chromium/third_party/blink/renderer/core/dom/element.cc
index 20396498651..c0561e2fc14 100644
--- a/chromium/third_party/blink/renderer/core/dom/element.cc
+++ b/chromium/third_party/blink/renderer/core/dom/element.cc
@@ -86,7 +86,6 @@
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
-#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/editing/set_selection_options.h"
@@ -134,12 +133,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/pointer_lock_controller.h"
#include "third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h"
-#include "third_party/blink/renderer/core/page/scrolling/root_scroller_util.h"
-#include "third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h"
-#include "third_party/blink/renderer/core/page/scrolling/scroll_state.h"
-#include "third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h"
#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h"
-#include "third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
@@ -167,31 +161,61 @@
namespace blink {
+using namespace html_names;
+
+enum class ClassStringContent { kEmpty, kWhiteSpaceOnly, kHasClasses };
+
namespace {
-// We need to retain the scroll customization callbacks until the element
-// they're associated with is destroyed. It would be simplest if the callbacks
-// could be stored in ElementRareData, but we can't afford the space increase.
-// Instead, keep the scroll customization callbacks here. The other option would
-// be to store these callbacks on the Page or document, but that necessitates a
-// bunch more logic for transferring the callbacks between Pages when elements
-// are moved around.
-ScrollCustomizationCallbacks& GetScrollCustomizationCallbacks() {
- DEFINE_STATIC_LOCAL(Persistent<ScrollCustomizationCallbacks>,
- scroll_customization_callbacks,
- (new ScrollCustomizationCallbacks));
- return *scroll_customization_callbacks;
+bool IsRootEditableElementWithCounting(const Element& element) {
+ bool is_editable = IsRootEditableElement(element);
+ Document& doc = element.GetDocument();
+ if (!doc.IsActive())
+ return is_editable;
+ // -webkit-user-modify doesn't affect text control elements.
+ if (element.IsTextControl())
+ return is_editable;
+ const auto* style = element.GetComputedStyle();
+ if (!style)
+ return is_editable;
+ auto user_modify = style->UserModify();
+ const AtomicString& ce_value = element.FastGetAttribute(kContenteditableAttr);
+ if (ce_value.IsNull() || DeprecatedEqualIgnoringCase(ce_value, "false")) {
+ if (user_modify == EUserModify::kReadWritePlaintextOnly) {
+ UseCounter::Count(doc, WebFeature::kPlainTextEditingEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyPlainTextEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyEffective);
+ } else if (user_modify == EUserModify::kReadWrite) {
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyReadWriteEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyEffective);
+ }
+ } else if (ce_value.IsEmpty() ||
+ DeprecatedEqualIgnoringCase(ce_value, "true")) {
+ if (user_modify == EUserModify::kReadWritePlaintextOnly) {
+ UseCounter::Count(doc, WebFeature::kPlainTextEditingEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyPlainTextEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyEffective);
+ } else if (user_modify == EUserModify::kReadOnly) {
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyReadOnlyEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyEffective);
+ }
+ } else if (DeprecatedEqualIgnoringCase(ce_value, "plaintext-only")) {
+ UseCounter::Count(doc, WebFeature::kPlainTextEditingEffective);
+ if (user_modify == EUserModify::kReadWrite) {
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyReadWriteEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyEffective);
+ } else if (user_modify == EUserModify::kReadOnly) {
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyReadOnlyEffective);
+ UseCounter::Count(doc, WebFeature::kWebKitUserModifyEffective);
+ }
+ }
+ return is_editable;
}
} // namespace
-using namespace HTMLNames;
-using namespace XMLNames;
-
-enum class ClassStringContent { kEmpty, kWhiteSpaceOnly, kHasClasses };
-
Element* Element::Create(const QualifiedName& tag_name, Document* document) {
- return new Element(tag_name, document, kCreateElement);
+ return MakeGarbageCollected<Element>(tag_name, document, kCreateElement);
}
Element::Element(const QualifiedName& tag_name,
@@ -238,12 +262,12 @@ void Element::SetTabIndexExplicitly() {
}
void Element::setTabIndex(int value) {
- SetIntegralAttribute(tabindexAttr, value);
+ SetIntegralAttribute(kTabindexAttr, value);
}
int Element::tabIndex() const {
return HasElementFlag(ElementFlags::kTabIndexWasSetExplicitly)
- ? GetIntegralAttribute(tabindexAttr)
+ ? GetIntegralAttribute(kTabindexAttr)
: 0;
}
@@ -374,7 +398,7 @@ ElementAnimations* Element::GetElementAnimations() const {
ElementAnimations& Element::EnsureElementAnimations() {
ElementRareData& rare_data = EnsureElementRareData();
if (!rare_data.GetElementAnimations())
- rare_data.SetElementAnimations(new ElementAnimations());
+ rare_data.SetElementAnimations(MakeGarbageCollected<ElementAnimations>());
return *rare_data.GetElementAnimations();
}
@@ -412,7 +436,7 @@ void Element::SynchronizeAllAttributes() const {
inline void Element::SynchronizeAttribute(const QualifiedName& name) const {
if (!GetElementData())
return;
- if (UNLIKELY(name == styleAttr &&
+ if (UNLIKELY(name == kStyleAttr &&
GetElementData()->style_attribute_is_dirty_)) {
DCHECK(IsStyledElement());
SynchronizeStyleAttributeInternal();
@@ -431,7 +455,7 @@ void Element::SynchronizeAttribute(const AtomicString& local_name) const {
if (!GetElementData())
return;
if (GetElementData()->style_attribute_is_dirty_ &&
- LowercaseIfNecessary(local_name) == styleAttr.LocalName()) {
+ LowercaseIfNecessary(local_name) == kStyleAttr.LocalName()) {
DCHECK(IsStyledElement());
SynchronizeStyleAttributeInternal();
return;
@@ -477,19 +501,15 @@ void Element::setNonce(const AtomicString& nonce) {
}
void Element::scrollIntoView(ScrollIntoViewOptionsOrBoolean arg) {
- ScrollIntoViewOptions options;
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
if (arg.IsBoolean()) {
if (arg.GetAsBoolean())
- options.setBlock("start");
+ options->setBlock("start");
else
- options.setBlock("end");
- options.setInlinePosition("nearest");
+ options->setBlock("end");
+ options->setInlinePosition("nearest");
} else if (arg.IsScrollIntoViewOptions()) {
options = arg.GetAsScrollIntoViewOptions();
- if (!RuntimeEnabledFeatures::CSSOMSmoothScrollEnabled() &&
- options.behavior() == "smooth") {
- options.setBehavior("instant");
- }
}
scrollIntoViewWithOptions(options);
}
@@ -500,15 +520,15 @@ void Element::scrollIntoView(bool align_to_top) {
scrollIntoView(arg);
}
-static ScrollAlignment ToPhysicalAlignment(const ScrollIntoViewOptions& options,
+static ScrollAlignment ToPhysicalAlignment(const ScrollIntoViewOptions* options,
ScrollOrientation axis,
bool is_horizontal_writing_mode,
bool is_flipped_blocks_mode) {
String alignment =
((axis == kHorizontalScroll && is_horizontal_writing_mode) ||
(axis == kVerticalScroll && !is_horizontal_writing_mode))
- ? options.inlinePosition()
- : options.block();
+ ? options->inlinePosition()
+ : options->block();
if (alignment == "center")
return ScrollAlignment::kAlignCenterAlways;
@@ -536,17 +556,17 @@ static ScrollAlignment ToPhysicalAlignment(const ScrollIntoViewOptions& options,
: ScrollAlignment::kAlignToEdgeIfNeeded;
}
-void Element::scrollIntoViewWithOptions(const ScrollIntoViewOptions& options) {
+void Element::scrollIntoViewWithOptions(const ScrollIntoViewOptions* options) {
GetDocument().EnsurePaintLocationDataValidForNode(this);
ScrollIntoViewNoVisualUpdate(options);
}
void Element::ScrollIntoViewNoVisualUpdate(
- const ScrollIntoViewOptions& options) {
+ const ScrollIntoViewOptions* options) {
if (!GetLayoutObject() || !GetDocument().GetPage())
return;
- ScrollBehavior behavior = (options.behavior() == "smooth")
+ ScrollBehavior behavior = (options->behavior() == "smooth")
? kScrollBehaviorSmooth
: kScrollBehaviorAuto;
@@ -588,182 +608,6 @@ void Element::scrollIntoViewIfNeeded(bool center_if_needed) {
}
}
-void Element::setDistributeScroll(V8ScrollStateCallback* scroll_state_callback,
- const String& native_scroll_behavior) {
- GetScrollCustomizationCallbacks().SetDistributeScroll(
- this, ScrollStateCallbackV8Impl::Create(scroll_state_callback,
- native_scroll_behavior));
-}
-
-void Element::setApplyScroll(V8ScrollStateCallback* scroll_state_callback,
- const String& native_scroll_behavior) {
- SetApplyScroll(ScrollStateCallbackV8Impl::Create(scroll_state_callback,
- native_scroll_behavior));
-}
-
-void Element::SetApplyScroll(ScrollStateCallback* scroll_state_callback) {
- GetScrollCustomizationCallbacks().SetApplyScroll(this, scroll_state_callback);
-}
-
-void Element::RemoveApplyScroll() {
- GetScrollCustomizationCallbacks().RemoveApplyScroll(this);
-}
-
-ScrollStateCallback* Element::GetApplyScroll() {
- return GetScrollCustomizationCallbacks().GetApplyScroll(this);
-}
-
-void Element::NativeDistributeScroll(ScrollState& scroll_state) {
- if (scroll_state.FullyConsumed())
- return;
-
- scroll_state.distributeToScrollChainDescendant();
-
- // The scroll doesn't propagate, and we're currently scrolling an element
- // other than this one, prevent the scroll from propagating to this element.
- if (scroll_state.DeltaConsumedForScrollSequence() &&
- scroll_state.CurrentNativeScrollingElement() != this) {
- return;
- }
-
- const double delta_x = scroll_state.deltaX();
- const double delta_y = scroll_state.deltaY();
-
- CallApplyScroll(scroll_state);
-
- if (delta_x != scroll_state.deltaX() || delta_y != scroll_state.deltaY())
- scroll_state.SetCurrentNativeScrollingElement(this);
-}
-
-void Element::CallDistributeScroll(ScrollState& scroll_state) {
- TRACE_EVENT0("input", "Element::CallDistributeScroll");
- ScrollStateCallback* callback =
- GetScrollCustomizationCallbacks().GetDistributeScroll(this);
-
- // TODO(bokan): Need to add tests before we allow calling custom callbacks
- // for non-touch modalities. For now, just call into the native callback but
- // allow the viewport scroll callback so we don't disable overscroll.
- // crbug.com/623079.
- bool disable_custom_callbacks = !scroll_state.isDirectManipulation() &&
- !GetDocument()
- .GetPage()
- ->GlobalRootScrollerController()
- .IsViewportScrollCallback(callback);
-
- disable_custom_callbacks |=
- !RootScrollerUtil::IsGlobal(this) &&
- RuntimeEnabledFeatures::ScrollCustomizationEnabled() &&
- !GetScrollCustomizationCallbacks().InScrollPhase(this);
-
- if (!callback || disable_custom_callbacks) {
- NativeDistributeScroll(scroll_state);
- return;
- }
- if (callback->NativeScrollBehavior() !=
- WebNativeScrollBehavior::kPerformAfterNativeScroll)
- callback->Invoke(&scroll_state);
- if (callback->NativeScrollBehavior() !=
- WebNativeScrollBehavior::kDisableNativeScroll)
- NativeDistributeScroll(scroll_state);
- if (callback->NativeScrollBehavior() ==
- WebNativeScrollBehavior::kPerformAfterNativeScroll)
- callback->Invoke(&scroll_state);
-}
-
-void Element::NativeApplyScroll(ScrollState& scroll_state) {
- // All elements in the scroll chain should be boxes.
- DCHECK(!GetLayoutObject() || GetLayoutObject()->IsBox());
-
- if (scroll_state.FullyConsumed())
- return;
-
- FloatSize delta(scroll_state.deltaX(), scroll_state.deltaY());
-
- if (delta.IsZero())
- return;
-
- // TODO(esprehn): This should use
- // updateStyleAndLayoutIgnorePendingStylesheetsForNode.
- GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
-
- LayoutBox* box_to_scroll = nullptr;
-
- if (this == GetDocument().documentElement())
- box_to_scroll = GetDocument().GetLayoutView();
- else if (GetLayoutObject())
- box_to_scroll = ToLayoutBox(GetLayoutObject());
-
- if (!box_to_scroll)
- return;
-
- ScrollableArea* scrollable_area =
- box_to_scroll->EnclosingBox()->GetScrollableArea();
-
- if (!scrollable_area)
- return;
-
- ScrollResult result = scrollable_area->UserScroll(
- ScrollGranularity(static_cast<int>(scroll_state.deltaGranularity())),
- delta);
-
- if (!result.DidScroll())
- return;
-
- // FIXME: Native scrollers should only consume the scroll they
- // apply. See crbug.com/457765.
- scroll_state.ConsumeDeltaNative(delta.Width(), delta.Height());
-
- // We need to setCurrentNativeScrollingElement in both the
- // distributeScroll and applyScroll default implementations so
- // that if JS overrides one of these methods, but not the
- // other, this bookkeeping remains accurate.
- scroll_state.SetCurrentNativeScrollingElement(this);
-};
-
-void Element::CallApplyScroll(ScrollState& scroll_state) {
- TRACE_EVENT0("input", "Element::CallApplyScroll");
- // Hits ASSERTs when trying to determine whether we need to scroll on main
- // or CC. http://crbug.com/625676.
- DisableCompositingQueryAsserts disabler;
-
- if (!GetDocument().GetPage()) {
- // We should always have a Page if we're scrolling. See
- // crbug.com/689074 for details.
- return;
- }
-
- ScrollStateCallback* callback =
- GetScrollCustomizationCallbacks().GetApplyScroll(this);
-
- // TODO(bokan): Need to add tests before we allow calling custom callbacks
- // for non-touch modalities. For now, just call into the native callback but
- // allow the viewport scroll callback so we don't disable overscroll.
- // crbug.com/623079.
- bool disable_custom_callbacks = !scroll_state.isDirectManipulation() &&
- !GetDocument()
- .GetPage()
- ->GlobalRootScrollerController()
- .IsViewportScrollCallback(callback);
- disable_custom_callbacks |=
- !RootScrollerUtil::IsGlobal(this) &&
- RuntimeEnabledFeatures::ScrollCustomizationEnabled() &&
- !GetScrollCustomizationCallbacks().InScrollPhase(this);
-
- if (!callback || disable_custom_callbacks) {
- NativeApplyScroll(scroll_state);
- return;
- }
- if (callback->NativeScrollBehavior() !=
- WebNativeScrollBehavior::kPerformAfterNativeScroll)
- callback->Invoke(&scroll_state);
- if (callback->NativeScrollBehavior() !=
- WebNativeScrollBehavior::kDisableNativeScroll)
- NativeApplyScroll(scroll_state);
- if (callback->NativeScrollBehavior() ==
- WebNativeScrollBehavior::kPerformAfterNativeScroll)
- callback->Invoke(&scroll_state);
-}
-
int Element::OffsetLeft() {
GetDocument().EnsurePaintLocationDataValidForNode(this);
if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject())
@@ -953,8 +797,8 @@ void Element::setScrollLeft(double new_left) {
if (GetDocument().ScrollingElementNoLayout() == this) {
if (LocalDOMWindow* window = GetDocument().domWindow()) {
- ScrollToOptions options;
- options.setLeft(new_left);
+ ScrollToOptions* options = ScrollToOptions::Create();
+ options->setLeft(new_left);
window->scrollTo(options);
}
} else {
@@ -964,12 +808,13 @@ void Element::setScrollLeft(double new_left) {
FloatPoint end_point(new_left * box->Style()->EffectiveZoom(),
box->ScrollTop().ToFloat());
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- end_point = GetDocument()
- .GetSnapCoordinator()
- ->GetSnapPositionForPoint(*box, end_point, true, false)
- .value_or(end_point);
- }
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(
+ gfx::ScrollOffset(end_point), true, false);
+ end_point = GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*box, *strategy)
+ .value_or(end_point);
box->SetScrollLeft(LayoutUnit::FromFloatRound(end_point.X()));
}
}
@@ -984,8 +829,8 @@ void Element::setScrollTop(double new_top) {
if (GetDocument().ScrollingElementNoLayout() == this) {
if (LocalDOMWindow* window = GetDocument().domWindow()) {
- ScrollToOptions options;
- options.setTop(new_top);
+ ScrollToOptions* options = ScrollToOptions::Create();
+ options->setTop(new_top);
window->scrollTo(options);
}
} else {
@@ -995,12 +840,13 @@ void Element::setScrollTop(double new_top) {
FloatPoint end_point(box->ScrollLeft().ToFloat(),
new_top * box->Style()->EffectiveZoom());
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- end_point = GetDocument()
- .GetSnapCoordinator()
- ->GetSnapPositionForPoint(*box, end_point, false, true)
- .value_or(end_point);
- }
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(
+ gfx::ScrollOffset(end_point), false, true);
+ end_point = GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*box, *strategy)
+ .value_or(end_point);
box->SetScrollTop(LayoutUnit::FromFloatRound(end_point.Y()));
}
}
@@ -1050,13 +896,13 @@ int Element::scrollHeight() {
}
void Element::scrollBy(double x, double y) {
- ScrollToOptions scroll_to_options;
- scroll_to_options.setLeft(x);
- scroll_to_options.setTop(y);
+ ScrollToOptions* scroll_to_options = ScrollToOptions::Create();
+ scroll_to_options->setLeft(x);
+ scroll_to_options->setTop(y);
scrollBy(scroll_to_options);
}
-void Element::scrollBy(const ScrollToOptions& scroll_to_options) {
+void Element::scrollBy(const ScrollToOptions* scroll_to_options) {
if (!InActiveDocument())
return;
@@ -1072,13 +918,13 @@ void Element::scrollBy(const ScrollToOptions& scroll_to_options) {
}
void Element::scrollTo(double x, double y) {
- ScrollToOptions scroll_to_options;
- scroll_to_options.setLeft(x);
- scroll_to_options.setTop(y);
+ ScrollToOptions* scroll_to_options = ScrollToOptions::Create();
+ scroll_to_options->setLeft(x);
+ scroll_to_options->setTop(y);
scrollTo(scroll_to_options);
}
-void Element::scrollTo(const ScrollToOptions& scroll_to_options) {
+void Element::scrollTo(const ScrollToOptions* scroll_to_options) {
if (!InActiveDocument())
return;
@@ -1093,86 +939,84 @@ void Element::scrollTo(const ScrollToOptions& scroll_to_options) {
}
}
-void Element::ScrollLayoutBoxBy(const ScrollToOptions& scroll_to_options) {
- double left =
- scroll_to_options.hasLeft()
- ? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left())
- : 0.0;
- double top =
- scroll_to_options.hasTop()
- ? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top())
- : 0.0;
+void Element::ScrollLayoutBoxBy(const ScrollToOptions* scroll_to_options) {
+ gfx::ScrollOffset displacement;
+ if (scroll_to_options->hasLeft()) {
+ displacement.set_x(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left()));
+ }
+ if (scroll_to_options->hasTop()) {
+ displacement.set_y(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top()));
+ }
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
- ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
+ ScrollableArea::ScrollBehaviorFromString(scroll_to_options->behavior(),
scroll_behavior);
LayoutBox* box = GetLayoutBox();
if (box) {
- float current_scaled_left = box->ScrollLeft().ToFloat();
- float current_scaled_top = box->ScrollTop().ToFloat();
- float new_scaled_left =
- left * box->Style()->EffectiveZoom() + current_scaled_left;
- float new_scaled_top =
- top * box->Style()->EffectiveZoom() + current_scaled_top;
-
- FloatPoint new_scaled_position(new_scaled_left, new_scaled_top);
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- new_scaled_position =
- GetDocument()
- .GetSnapCoordinator()
- ->GetSnapPositionForPoint(*box, new_scaled_position,
- scroll_to_options.hasLeft(),
- scroll_to_options.hasTop())
- .value_or(new_scaled_position);
- }
- box->ScrollToPosition(new_scaled_position, scroll_behavior);
+ gfx::ScrollOffset current_position(box->ScrollLeft().ToFloat(),
+ box->ScrollTop().ToFloat());
+ displacement.Scale(box->Style()->EffectiveZoom());
+ gfx::ScrollOffset new_offset(current_position + displacement);
+ FloatPoint new_position(new_offset.x(), new_offset.y());
+
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndAndDirection(current_position,
+ displacement);
+ new_position = GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*box, *strategy)
+ .value_or(new_position);
+ box->ScrollToPosition(new_position, scroll_behavior);
}
}
-void Element::ScrollLayoutBoxTo(const ScrollToOptions& scroll_to_options) {
+void Element::ScrollLayoutBoxTo(const ScrollToOptions* scroll_to_options) {
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
- ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
+ ScrollableArea::ScrollBehaviorFromString(scroll_to_options->behavior(),
scroll_behavior);
LayoutBox* box = GetLayoutBox();
if (box) {
- float scaled_left = box->ScrollLeft().ToFloat();
- float scaled_top = box->ScrollTop().ToFloat();
- if (scroll_to_options.hasLeft())
- scaled_left =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left()) *
- box->Style()->EffectiveZoom();
- if (scroll_to_options.hasTop())
- scaled_top =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top()) *
- box->Style()->EffectiveZoom();
-
- FloatPoint new_scaled_position(scaled_left, scaled_top);
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- new_scaled_position =
- GetDocument()
- .GetSnapCoordinator()
- ->GetSnapPositionForPoint(*box, new_scaled_position,
- scroll_to_options.hasLeft(),
- scroll_to_options.hasTop())
- .value_or(new_scaled_position);
+ FloatPoint new_position(box->ScrollLeft().ToFloat(),
+ box->ScrollTop().ToFloat());
+ if (scroll_to_options->hasLeft()) {
+ new_position.SetX(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left()) *
+ box->Style()->EffectiveZoom());
+ }
+ if (scroll_to_options->hasTop()) {
+ new_position.SetY(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top()) *
+ box->Style()->EffectiveZoom());
}
- box->ScrollToPosition(new_scaled_position, scroll_behavior);
+
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(
+ gfx::ScrollOffset(new_position), scroll_to_options->hasLeft(),
+ scroll_to_options->hasTop());
+ new_position = GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*box, *strategy)
+ .value_or(new_position);
+ box->ScrollToPosition(new_position, scroll_behavior);
}
}
-void Element::ScrollFrameBy(const ScrollToOptions& scroll_to_options) {
- double left =
- scroll_to_options.hasLeft()
- ? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left())
- : 0.0;
- double top =
- scroll_to_options.hasTop()
- ? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top())
- : 0.0;
+void Element::ScrollFrameBy(const ScrollToOptions* scroll_to_options) {
+ gfx::ScrollOffset displacement;
+ if (scroll_to_options->hasLeft()) {
+ displacement.set_x(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left()));
+ }
+ if (scroll_to_options->hasTop()) {
+ displacement.set_y(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top()));
+ }
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
- ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
+ ScrollableArea::ScrollBehaviorFromString(scroll_to_options->behavior(),
scroll_behavior);
LocalFrame* frame = GetDocument().GetFrame();
if (!frame || !frame->View() || !GetDocument().GetPage())
@@ -1182,30 +1026,26 @@ void Element::ScrollFrameBy(const ScrollToOptions& scroll_to_options) {
if (!viewport)
return;
- float new_scaled_left =
- left * frame->PageZoomFactor() + viewport->GetScrollOffset().Width();
- float new_scaled_top =
- top * frame->PageZoomFactor() + viewport->GetScrollOffset().Height();
+ displacement.Scale(frame->PageZoomFactor());
+ FloatPoint new_position = viewport->ScrollPosition() +
+ FloatPoint(displacement.x(), displacement.y());
- FloatPoint new_scaled_position = viewport->ScrollOffsetToPosition(
- ScrollOffset(new_scaled_left, new_scaled_top));
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- new_scaled_position =
- GetDocument()
- .GetSnapCoordinator()
- ->GetSnapPositionForPoint(
- *GetDocument().GetLayoutView(), new_scaled_position,
- scroll_to_options.hasLeft(), scroll_to_options.hasTop())
- .value_or(new_scaled_position);
- }
- viewport->SetScrollOffset(
- viewport->ScrollPositionToOffset(new_scaled_position),
- kProgrammaticScroll, scroll_behavior);
+ gfx::ScrollOffset current_position(viewport->ScrollPosition());
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndAndDirection(current_position,
+ displacement);
+ new_position =
+ GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*GetDocument().GetLayoutView(), *strategy)
+ .value_or(new_position);
+ viewport->SetScrollOffset(viewport->ScrollPositionToOffset(new_position),
+ kProgrammaticScroll, scroll_behavior);
}
-void Element::ScrollFrameTo(const ScrollToOptions& scroll_to_options) {
+void Element::ScrollFrameTo(const ScrollToOptions* scroll_to_options) {
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
- ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
+ ScrollableArea::ScrollBehaviorFromString(scroll_to_options->behavior(),
scroll_behavior);
LocalFrame* frame = GetDocument().GetFrame();
if (!frame || !frame->View() || !GetDocument().GetPage())
@@ -1215,31 +1055,30 @@ void Element::ScrollFrameTo(const ScrollToOptions& scroll_to_options) {
if (!viewport)
return;
- float scaled_left = viewport->GetScrollOffset().Width();
- float scaled_top = viewport->GetScrollOffset().Height();
- if (scroll_to_options.hasLeft())
- scaled_left =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left()) *
- frame->PageZoomFactor();
- if (scroll_to_options.hasTop())
- scaled_top =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top()) *
- frame->PageZoomFactor();
-
- FloatPoint new_scaled_position =
- viewport->ScrollOffsetToPosition(ScrollOffset(scaled_left, scaled_top));
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- new_scaled_position =
- GetDocument()
- .GetSnapCoordinator()
- ->GetSnapPositionForPoint(
- *GetDocument().GetLayoutView(), new_scaled_position,
- scroll_to_options.hasLeft(), scroll_to_options.hasTop())
- .value_or(new_scaled_position);
- }
- viewport->SetScrollOffset(
- viewport->ScrollPositionToOffset(new_scaled_position),
- kProgrammaticScroll, scroll_behavior);
+ ScrollOffset new_offset = viewport->GetScrollOffset();
+ if (scroll_to_options->hasLeft()) {
+ new_offset.SetWidth(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left()) *
+ frame->PageZoomFactor());
+ }
+ if (scroll_to_options->hasTop()) {
+ new_offset.SetHeight(
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top()) *
+ frame->PageZoomFactor());
+ }
+
+ FloatPoint new_position = viewport->ScrollOffsetToPosition(new_offset);
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(
+ gfx::ScrollOffset(new_position), scroll_to_options->hasLeft(),
+ scroll_to_options->hasTop());
+ new_position =
+ GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*GetDocument().GetLayoutView(), *strategy)
+ .value_or(new_position);
+ new_offset = viewport->ScrollPositionToOffset(new_position);
+ viewport->SetScrollOffset(new_offset, kProgrammaticScroll, scroll_behavior);
}
bool Element::HasNonEmptyLayoutSize() const {
@@ -1420,7 +1259,7 @@ AccessibleNode* Element::accessibleNode() {
}
InvisibleState Element::Invisible() const {
- const AtomicString& value = FastGetAttribute(invisibleAttr);
+ const AtomicString& value = FastGetAttribute(kInvisibleAttr);
if (value.IsNull())
return InvisibleState::kMissing;
if (EqualIgnoringASCIICase(value, "static"))
@@ -1469,7 +1308,7 @@ void Element::InvisibleAttributeChanged(const AtomicString& old_value,
if (old_value.IsNull() != new_value.IsNull()) {
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kInvisibleChange));
+ style_change_reason::kInvisibleChange));
}
if (EqualIgnoringASCIICase(old_value, "static") &&
!IsInsideInvisibleStaticSubtree()) {
@@ -1481,9 +1320,9 @@ void Element::InvisibleAttributeChanged(const AtomicString& old_value,
void Element::DefaultEventHandler(Event& event) {
if (RuntimeEnabledFeatures::InvisibleDOMEnabled() &&
- event.type() == EventTypeNames::activateinvisible &&
+ event.type() == event_type_names::kActivateinvisible &&
event.target() == this) {
- removeAttribute(invisibleAttr);
+ removeAttribute(kInvisibleAttr);
event.SetDefaultHandled();
return;
}
@@ -1746,7 +1585,7 @@ void Element::AttributeChanged(const AttributeModificationParams& params) {
*parent_shadow_root, name, params.new_value))
parent_shadow_root->SetNeedsDistributionRecalc();
}
- if (name == HTMLNames::slotAttr && params.old_value != params.new_value) {
+ if (name == html_names::kSlotAttr && params.old_value != params.new_value) {
if (ShadowRoot* root = V1ShadowRootOfParent())
root->DidChangeHostChildSlotName(params.old_value, params.new_value);
}
@@ -1755,7 +1594,7 @@ void Element::AttributeChanged(const AttributeModificationParams& params) {
GetDocument().IncDOMTreeVersion();
- if (name == HTMLNames::idAttr) {
+ if (name == html_names::kIdAttr) {
AtomicString old_id = GetElementData()->IdForStyleResolution();
AtomicString new_id = MakeIdForStyleResolution(
params.new_value, GetDocument().InQuirksMode());
@@ -1763,33 +1602,33 @@ void Element::AttributeChanged(const AttributeModificationParams& params) {
GetElementData()->SetIdForStyleResolution(new_id);
GetDocument().GetStyleEngine().IdChangedForElement(old_id, new_id, *this);
}
- } else if (name == classAttr) {
+ } else if (name == kClassAttr) {
ClassAttributeChanged(params.new_value);
if (HasRareData() && GetElementRareData()->GetClassList()) {
GetElementRareData()->GetClassList()->DidUpdateAttributeValue(
params.old_value, params.new_value);
}
- } else if (name == HTMLNames::nameAttr) {
+ } else if (name == html_names::kNameAttr) {
SetHasName(!params.new_value.IsNull());
- } else if (name == HTMLNames::partAttr) {
+ } else if (name == html_names::kPartAttr) {
if (RuntimeEnabledFeatures::CSSPartPseudoElementEnabled()) {
- EnsureElementRareData().SetPart(params.new_value);
+ part().DidUpdateAttributeValue(params.old_value, params.new_value);
GetDocument().GetStyleEngine().PartChangedForElement(*this);
}
- } else if (name == HTMLNames::partmapAttr) {
+ } else if (name == html_names::kExportpartsAttr) {
if (RuntimeEnabledFeatures::CSSPartPseudoElementEnabled()) {
EnsureElementRareData().SetPartNamesMap(params.new_value);
- GetDocument().GetStyleEngine().PartmapChangedForElement(*this);
+ GetDocument().GetStyleEngine().ExportpartsChangedForElement(*this);
}
} else if (IsStyledElement()) {
- if (name == styleAttr) {
+ if (name == kStyleAttr) {
StyleAttributeChanged(params.new_value, params.reason);
} else if (IsPresentationAttribute(name)) {
GetElementData()->presentation_attribute_style_is_dirty_ = true;
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::FromAttribute(name));
} else if (RuntimeEnabledFeatures::InvisibleDOMEnabled() &&
- name == HTMLNames::invisibleAttr &&
+ name == html_names::kInvisibleAttr &&
params.old_value != params.new_value) {
InvisibleAttributeChanged(params.old_value, params.new_value);
}
@@ -1805,7 +1644,7 @@ void Element::AttributeChanged(const AttributeModificationParams& params) {
}
if (params.reason == AttributeModificationReason::kDirectly &&
- name == tabindexAttr && AdjustedFocusedElementInTreeScope() == this) {
+ name == kTabindexAttr && AdjustedFocusedElementInTreeScope() == this) {
// The attribute change may cause supportsFocus() to return false
// for the element which had focus.
//
@@ -1886,7 +1725,7 @@ bool Element::ShouldInvalidateDistributionWhenAttributeChanged(
const SelectRuleFeatureSet& feature_set =
shadow_root.V0().EnsureSelectFeatureSet();
- if (name == HTMLNames::idAttr) {
+ if (name == html_names::kIdAttr) {
AtomicString old_id = GetElementData()->IdForStyleResolution();
AtomicString new_id =
MakeIdForStyleResolution(new_value, GetDocument().InQuirksMode());
@@ -1898,7 +1737,7 @@ bool Element::ShouldInvalidateDistributionWhenAttributeChanged(
}
}
- if (name == HTMLNames::classAttr) {
+ if (name == html_names::kClassAttr) {
const AtomicString& new_class_string = new_value;
if (ClassStringHasClassName(new_class_string) ==
ClassStringContent::kHasClasses) {
@@ -2026,7 +1865,7 @@ const AtomicString& Element::LocateNamespacePrefix(
}
const AtomicString Element::ImageSourceURL() const {
- return getAttribute(srcAttr);
+ return getAttribute(kSrcAttr);
}
bool Element::LayoutObjectIsNeeded(const ComputedStyle& style) const {
@@ -2058,6 +1897,8 @@ Node::InsertionNotificationRequest Element::InsertedInto(
if (LocalFrameView* frame_view = GetDocument().View())
frame_view->SetIntersectionObservationState(LocalFrameView::kRequired);
}
+ if (rare_data->GetDisplayLockContext())
+ rare_data->GetDisplayLockContext()->NotifyConnectedMayHaveChanged();
}
if (isConnected()) {
@@ -2095,7 +1936,10 @@ void Element::RemovedFrom(ContainerNode& insertion_point) {
// AttachLayoutTree again. We don't clear pseudo elements on
// DetachLayoutTree() if we intend to attach again to avoid recreating the
// pseudo elements.
- GetElementRareData()->ClearPseudoElements();
+ ElementRareData* rare_data = GetElementRareData();
+ rare_data->ClearPseudoElements();
+ if (rare_data->GetDisplayLockContext())
+ rare_data->GetDisplayLockContext()->NotifyConnectedMayHaveChanged();
}
if (Fullscreen::IsFullscreenElement(*this)) {
@@ -2132,13 +1976,6 @@ void Element::RemovedFrom(ContainerNode& insertion_point) {
CustomElement::EnqueueDisconnectedCallback(this);
else if (IsUpgradedV0CustomElement())
V0CustomElement::DidDetach(this, insertion_point.GetDocument());
-
- if (NeedsStyleInvalidation()) {
- GetDocument()
- .GetStyleEngine()
- .GetPendingNodeInvalidations()
- .ClearInvalidation(*this);
- }
}
GetDocument().GetRootScrollerController().ElementRemoved(*this);
@@ -2187,14 +2024,13 @@ void Element::AttachLayoutTree(AttachContext& context) {
data->ClearComputedStyle();
}
- if (CanParticipateInFlatTree()) {
- LayoutTreeBuilderForElement builder(*this, GetNonAttachedStyle());
+ ComputedStyle* style = GetNonAttachedStyle();
+ if (style && CanParticipateInFlatTree()) {
+ LayoutTreeBuilderForElement builder(*this, style);
builder.CreateLayoutObjectIfNeeded();
- if (ComputedStyle* style = builder.ResolvedStyle()) {
- if (!GetLayoutObject() && ShouldStoreNonLayoutObjectComputedStyle(*style))
- StoreNonLayoutObjectComputedStyle(style);
- }
+ if (!GetLayoutObject() && ShouldStoreNonLayoutObjectComputedStyle(*style))
+ StoreNonLayoutObjectComputedStyle(style);
}
if (HasRareData() && !GetLayoutObject() &&
@@ -2240,6 +2076,9 @@ void Element::AttachLayoutTree(AttachContext& context) {
} else {
context.previous_in_flow = children_context.previous_in_flow;
}
+
+ if (auto* display_lock_context = GetDisplayLockContext())
+ display_lock_context->DidAttachLayoutTree();
}
void Element::DetachLayoutTree(const AttachContext& context) {
@@ -2293,13 +2132,6 @@ void Element::DetachLayoutTree(const AttachContext& context) {
GetDocument().UserActionElements().DidDetach(*this);
}
- if (context.clear_invalidation) {
- GetDocument()
- .GetStyleEngine()
- .GetPendingNodeInvalidations()
- .ClearInvalidation(*this);
- }
-
SetNeedsResizeObserverUpdate();
DCHECK(NeedsAttach());
@@ -2315,8 +2147,9 @@ scoped_refptr<ComputedStyle> Element::StyleForLayoutObject() {
element_animations->CssAnimations().ClearPendingUpdate();
if (RuntimeEnabledFeatures::InvisibleDOMEnabled() &&
- hasAttribute(HTMLNames::invisibleAttr)) {
- auto style = ComputedStyle::Create();
+ hasAttribute(html_names::kInvisibleAttr)) {
+ auto style =
+ GetDocument().GetStyleResolver()->InitialStyleForElement(GetDocument());
style->SetDisplay(EDisplay::kNone);
return style;
}
@@ -2379,6 +2212,10 @@ void Element::RecalcStyleForTraversalRootAncestor() {
void Element::RecalcStyle(StyleRecalcChange change) {
DCHECK(GetDocument().InStyleRecalc());
DCHECK(!GetDocument().Lifecycle().InDetach());
+
+ if (StyleRecalcBlockedByDisplayLock())
+ return;
+
// If we are re-attaching in a Shadow DOM v0 tree, we recalc down to the
// distributed nodes to propagate kReattach down the flat tree (See
// V0InsertionPoint::DidRecalcStyle). That means we may have a shadow-
@@ -2456,7 +2293,6 @@ void Element::RecalcStyle(StyleRecalcChange change) {
}
if (ShouldCallRecalcStyleForChildren(change)) {
-
UpdatePseudoElement(kPseudoIdBefore, change);
if (change > kUpdatePseudoElements || ChildNeedsStyleRecalc()) {
@@ -2481,6 +2317,7 @@ void Element::RecalcStyle(StyleRecalcChange change) {
if (HasCustomStyleCallbacks())
DidRecalcStyle(change);
+ NotifyDisplayLockDidRecalcStyle();
}
scoped_refptr<ComputedStyle> Element::PropagateInheritedProperties(
@@ -2546,6 +2383,9 @@ StyleRecalcChange Element::RecalcOwnStyle(StyleRecalcChange change) {
}
}
+ if (GetForceReattachLayoutTree())
+ local_change = kReattach;
+
if (change == kReattach || local_change == kReattach) {
SetNonAttachedStyle(new_style);
SetNeedsReattachLayoutTree();
@@ -2733,7 +2573,7 @@ ShadowRoot& Element::CreateAndAttachShadowRoot(ShadowRootType type) {
shadow_root->InsertedInto(*this);
SetChildNeedsStyleRecalc();
SetNeedsStyleRecalc(kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kShadow));
+ style_change_reason::kShadow));
probe::didPushShadowRoot(this, shadow_root);
@@ -2773,11 +2613,13 @@ void Element::ClearAnimationStyleChange() {
}
void Element::SetNeedsAnimationStyleRecalc() {
+ if (GetDocument().InStyleRecalc())
+ return;
if (GetStyleChangeType() != kNoStyleChange)
return;
SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kAnimation));
+ style_change_reason::kAnimation));
SetAnimationStyleChange(true);
}
@@ -2833,6 +2675,18 @@ const AtomicString& Element::IsValue() const {
return g_null_atom;
}
+void Element::SetDidAttachInternals() {
+ EnsureElementRareData().SetDidAttachInternals();
+}
+
+bool Element::DidAttachInternals() const {
+ return HasRareData() && GetElementRareData()->DidAttachInternals();
+}
+
+ElementInternals& Element::EnsureElementInternals() {
+ return EnsureElementRareData().EnsureElementInternals(ToHTMLElement(*this));
+}
+
ShadowRoot* Element::createShadowRoot(ExceptionState& exception_state) {
if (ShadowRoot* root = GetShadowRoot()) {
if (root->IsUserAgent()) {
@@ -2873,21 +2727,22 @@ bool Element::CanAttachShadowRoot() const {
// because IsValidName is not cheap.
return (IsCustomElement() && CustomElement::IsValidName(tag_name)) ||
(IsV0CustomElement() && V0CustomElement::IsValidName(tag_name)) ||
- tag_name == HTMLNames::articleTag || tag_name == HTMLNames::asideTag ||
- tag_name == HTMLNames::blockquoteTag ||
- tag_name == HTMLNames::bodyTag || tag_name == HTMLNames::divTag ||
- tag_name == HTMLNames::footerTag || tag_name == HTMLNames::h1Tag ||
- tag_name == HTMLNames::h2Tag || tag_name == HTMLNames::h3Tag ||
- tag_name == HTMLNames::h4Tag || tag_name == HTMLNames::h5Tag ||
- tag_name == HTMLNames::h6Tag || tag_name == HTMLNames::headerTag ||
- tag_name == HTMLNames::navTag || tag_name == HTMLNames::mainTag ||
- tag_name == HTMLNames::pTag || tag_name == HTMLNames::sectionTag ||
- tag_name == HTMLNames::spanTag;
-}
-
-ShadowRoot* Element::attachShadow(const ShadowRootInit& shadow_root_init_dict,
+ tag_name == html_names::kArticleTag ||
+ tag_name == html_names::kAsideTag ||
+ tag_name == html_names::kBlockquoteTag ||
+ tag_name == html_names::kBodyTag || tag_name == html_names::kDivTag ||
+ tag_name == html_names::kFooterTag || tag_name == html_names::kH1Tag ||
+ tag_name == html_names::kH2Tag || tag_name == html_names::kH3Tag ||
+ tag_name == html_names::kH4Tag || tag_name == html_names::kH5Tag ||
+ tag_name == html_names::kH6Tag || tag_name == html_names::kHeaderTag ||
+ tag_name == html_names::kNavTag || tag_name == html_names::kMainTag ||
+ tag_name == html_names::kPTag || tag_name == html_names::kSectionTag ||
+ tag_name == html_names::kSpanTag;
+}
+
+ShadowRoot* Element::attachShadow(const ShadowRootInit* shadow_root_init_dict,
ExceptionState& exception_state) {
- DCHECK(shadow_root_init_dict.hasMode());
+ DCHECK(shadow_root_init_dict->hasMode());
if (!CanAttachShadowRoot()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
@@ -2902,7 +2757,7 @@ ShadowRoot* Element::attachShadow(const ShadowRootInit& shadow_root_init_dict,
return nullptr;
}
- ShadowRootType type = shadow_root_init_dict.mode() == "open"
+ ShadowRootType type = shadow_root_init_dict->mode() == "open"
? ShadowRootType::kOpen
: ShadowRootType::kClosed;
@@ -2911,10 +2766,10 @@ ShadowRoot* Element::attachShadow(const ShadowRootInit& shadow_root_init_dict,
else
UseCounter::Count(GetDocument(), WebFeature::kElementAttachShadowClosed);
- DCHECK(!shadow_root_init_dict.hasMode() || !GetShadowRoot());
- bool delegates_focus = shadow_root_init_dict.hasDelegatesFocus() &&
- shadow_root_init_dict.delegatesFocus();
- bool manual_slotting = shadow_root_init_dict.slotting() == "manual";
+ DCHECK(!shadow_root_init_dict->hasMode() || !GetShadowRoot());
+ bool delegates_focus = shadow_root_init_dict->hasDelegatesFocus() &&
+ shadow_root_init_dict->delegatesFocus();
+ bool manual_slotting = shadow_root_init_dict->slotting() == "manual";
return &AttachShadowRootInternal(type, delegates_focus, manual_slotting);
}
@@ -3160,7 +3015,7 @@ Attr* Element::removeAttributeNode(Attr* attr,
}
void Element::ParseAttribute(const AttributeModificationParams& params) {
- if (params.name == tabindexAttr) {
+ if (params.name == kTabindexAttr) {
int tabindex = 0;
if (params.new_value.IsEmpty() ||
!ParseHTMLInteger(params.new_value, tabindex)) {
@@ -3169,7 +3024,7 @@ void Element::ParseAttribute(const AttributeModificationParams& params) {
// We only set when value is in integer range.
SetTabIndexExplicitly();
}
- } else if (params.name == XMLNames::langAttr) {
+ } else if (params.name == xml_names::kLangAttr) {
PseudoStateChanged(CSSSelector::kPseudoLang);
}
}
@@ -3261,7 +3116,7 @@ void Element::removeAttribute(const AtomicString& name) {
AtomicString local_name = LowercaseIfNecessary(name);
wtf_size_t index = GetElementData()->Attributes().FindIndex(local_name);
if (index == kNotFound) {
- if (UNLIKELY(local_name == styleAttr) &&
+ if (UNLIKELY(local_name == kStyleAttr) &&
GetElementData()->style_attribute_is_dirty_ && IsStyledElement())
RemoveAllInlineStyleProperties();
return;
@@ -3315,7 +3170,7 @@ bool Element::hasAttributeNS(const AtomicString& namespace_uri,
return GetElementData()->Attributes().Find(q_name);
}
-void Element::focus(FocusOptions options) {
+void Element::focus(const FocusOptions* options) {
focus(FocusParams(SelectionBehaviorOnFocus::kRestore, kWebFocusTypeNone,
nullptr, options));
}
@@ -3374,12 +3229,12 @@ void Element::focus(const FocusParams& params) {
void Element::UpdateFocusAppearance(
SelectionBehaviorOnFocus selection_behavior) {
- UpdateFocusAppearanceWithOptions(selection_behavior, FocusOptions());
+ UpdateFocusAppearanceWithOptions(selection_behavior, FocusOptions::Create());
}
void Element::UpdateFocusAppearanceWithOptions(
SelectionBehaviorOnFocus selection_behavior,
- const FocusOptions& options) {
+ const FocusOptions* options) {
if (selection_behavior == SelectionBehaviorOnFocus::kNone)
return;
if (IsRootEditableElement(*this)) {
@@ -3407,11 +3262,11 @@ void Element::UpdateFocusAppearanceWithOptions(
.SetShouldClearTypingStyle(true)
.SetDoNotSetFocus(true)
.Build());
- if (!options.preventScroll())
+ if (!options->preventScroll())
frame->Selection().RevealSelection();
} else if (GetLayoutObject() &&
!GetLayoutObject()->IsLayoutEmbeddedContent()) {
- if (!options.preventScroll()) {
+ if (!options->preventScroll()) {
GetLayoutObject()->ScrollRectToVisible(BoundingBoxForScrollIntoView(),
WebScrollIntoViewParams());
}
@@ -3439,7 +3294,7 @@ bool Element::SupportsFocus() const {
// it won't be focusable. Furthermore, supportsFocus cannot just return true
// always or else tabIndex() will change for all HTML elements.
return HasElementFlag(ElementFlags::kTabIndexWasSetExplicitly) ||
- IsRootEditableElement(*this) ||
+ IsRootEditableElementWithCounting(*this) ||
(IsShadowHost(this) && AuthorShadowRoot() &&
AuthorShadowRoot()->delegatesFocus()) ||
SupportsSpatialNavigationFocus();
@@ -3455,33 +3310,40 @@ bool Element::SupportsSpatialNavigationFocus() const {
if (!IsSpatialNavigationEnabled(GetDocument().GetFrame()) ||
SpatialNavigationIgnoresEventHandlers(GetDocument().GetFrame()))
return false;
- if (HasEventListeners(EventTypeNames::click) ||
- HasEventListeners(EventTypeNames::keydown) ||
- HasEventListeners(EventTypeNames::keypress) ||
- HasEventListeners(EventTypeNames::keyup))
+ if (HasEventListeners(event_type_names::kClick) ||
+ HasEventListeners(event_type_names::kKeydown) ||
+ HasEventListeners(event_type_names::kKeypress) ||
+ HasEventListeners(event_type_names::kKeyup))
return true;
if (!IsSVGElement())
return false;
- return (HasEventListeners(EventTypeNames::focus) ||
- HasEventListeners(EventTypeNames::blur) ||
- HasEventListeners(EventTypeNames::focusin) ||
- HasEventListeners(EventTypeNames::focusout));
+ return (HasEventListeners(event_type_names::kFocus) ||
+ HasEventListeners(event_type_names::kBlur) ||
+ HasEventListeners(event_type_names::kFocusin) ||
+ HasEventListeners(event_type_names::kFocusout));
}
bool Element::IsFocusable() const {
- // Style cannot be cleared out for non-active documents, so in that case the
- // needsLayoutTreeUpdateForNode check is invalid.
- DCHECK(!GetDocument().IsActive() ||
- !GetDocument().NeedsLayoutTreeUpdateForNode(*this));
- return isConnected() && SupportsFocus() && !IsInert() && IsFocusableStyle();
+ return Element::IsMouseFocusable() || Element::IsKeyboardFocusable();
}
bool Element::IsKeyboardFocusable() const {
- return IsFocusable() && tabIndex() >= 0;
+ // No point in checking NeedsLayoutTreeUpdateForNode when the document
+ // isn't active (style can't be invalidated in a non-active document).
+ DCHECK(!GetDocument().IsActive() ||
+ !GetDocument().NeedsLayoutTreeUpdateForNode(*this));
+ return isConnected() && !IsInert() && IsFocusableStyle() &&
+ ((SupportsFocus() && tabIndex() >= 0) ||
+ (RuntimeEnabledFeatures::KeyboardFocusableScrollersEnabled() &&
+ IsScrollableNode(this)));
}
bool Element::IsMouseFocusable() const {
- return IsFocusable();
+ // No point in checking NeedsLayoutTreeUpdateForNode when the document
+ // isn't active (style can't be invalidated in a non-active document).
+ DCHECK(!GetDocument().IsActive() ||
+ !GetDocument().NeedsLayoutTreeUpdateForNode(*this));
+ return isConnected() && !IsInert() && IsFocusableStyle() && SupportsFocus();
}
bool Element::IsFocusedElementInDocument() const {
@@ -3496,17 +3358,17 @@ Element* Element::AdjustedFocusedElementInTreeScope() const {
void Element::DispatchFocusEvent(Element* old_focused_element,
WebFocusType type,
InputDeviceCapabilities* source_capabilities) {
- DispatchEvent(*FocusEvent::Create(EventTypeNames::focus, Event::Bubbles::kNo,
- GetDocument().domWindow(), 0,
- old_focused_element, source_capabilities));
+ DispatchEvent(*FocusEvent::Create(
+ event_type_names::kFocus, Event::Bubbles::kNo, GetDocument().domWindow(),
+ 0, old_focused_element, source_capabilities));
}
void Element::DispatchBlurEvent(Element* new_focused_element,
WebFocusType type,
InputDeviceCapabilities* source_capabilities) {
- DispatchEvent(*FocusEvent::Create(EventTypeNames::blur, Event::Bubbles::kNo,
- GetDocument().domWindow(), 0,
- new_focused_element, source_capabilities));
+ DispatchEvent(*FocusEvent::Create(
+ event_type_names::kBlur, Event::Bubbles::kNo, GetDocument().domWindow(),
+ 0, new_focused_element, source_capabilities));
}
void Element::DispatchFocusInEvent(
@@ -3517,8 +3379,8 @@ void Element::DispatchFocusInEvent(
#if DCHECK_IS_ON()
DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
- DCHECK(event_type == EventTypeNames::focusin ||
- event_type == EventTypeNames::DOMFocusIn);
+ DCHECK(event_type == event_type_names::kFocusin ||
+ event_type == event_type_names::kDOMFocusIn);
DispatchScopedEvent(*FocusEvent::Create(
event_type, Event::Bubbles::kYes, GetDocument().domWindow(), 0,
old_focused_element, source_capabilities));
@@ -3531,8 +3393,8 @@ void Element::DispatchFocusOutEvent(
#if DCHECK_IS_ON()
DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
- DCHECK(event_type == EventTypeNames::focusout ||
- event_type == EventTypeNames::DOMFocusOut);
+ DCHECK(event_type == event_type_names::kFocusout ||
+ event_type == event_type_names::kDOMFocusOut);
DispatchScopedEvent(*FocusEvent::Create(
event_type, Event::Bubbles::kYes, GetDocument().domWindow(), 0,
new_focused_element, source_capabilities));
@@ -3704,34 +3566,28 @@ void Element::SetNeedsResizeObserverUpdate() {
}
}
-void Element::WillBeginCustomizedScrollPhase(
- ScrollCustomization::ScrollDirection direction) {
- DCHECK(!GetScrollCustomizationCallbacks().InScrollPhase(this));
- LayoutBox* box = GetLayoutBox();
- if (!box)
- return;
-
- ScrollCustomization::ScrollDirection scroll_customization =
- box->Style()->ScrollCustomization();
+ScriptPromise Element::acquireDisplayLock(ScriptState* script_state,
+ V8DisplayLockCallback* callback) {
+ auto* context = EnsureElementRareData().EnsureDisplayLockContext(
+ this, GetExecutionContext());
+ context->RequestLock(callback, script_state);
+ auto lock_promise = context->Promise();
- GetScrollCustomizationCallbacks().SetInScrollPhase(
- this, direction & scroll_customization);
-}
+ // Only support "mode 2" display locking, which requires that the lock is
+ // acquired before the element is connected. Note that we need to call this
+ // after actually getting the promise to avoid ScriptPromiseResolver asserts.
+ // TODO(vmpstr): Implement mode 1.
+ if (isConnected())
+ context->RejectAndCleanUp();
-void Element::DidEndCustomizedScrollPhase() {
- GetScrollCustomizationCallbacks().SetInScrollPhase(this, false);
+ return lock_promise;
}
-ScriptPromise Element::acquireDisplayLock(ScriptState* script_state,
- V8DisplayLockCallback* callback) {
- // For now, just invoke the callback, and resolve the promise immediately.
- // TODO(vmpstr): Finish implementation.
- callback->InvokeAndReportException(nullptr, new DisplayLockContext);
-
- auto* resolver = ScriptPromiseResolver::Create(script_state);
- const auto& promise = resolver->Promise();
- resolver->Resolve();
- return promise;
+DisplayLockContext* Element::GetDisplayLockContext() const {
+ if (!RuntimeEnabledFeatures::DisplayLockingEnabled())
+ return nullptr;
+ return HasRareData() ? GetElementRareData()->GetDisplayLockContext()
+ : nullptr;
}
// Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
@@ -3848,19 +3704,6 @@ bool Element::HasProcessedPointerCapture(int pointer_id) const {
pointer_id, this);
}
-String Element::innerText() {
- // We need to update layout, since plainText uses line boxes in the layout
- // tree.
- GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
-
- if (!GetLayoutObject() && !HasDisplayContentsStyle())
- return textContent(true);
-
- return PlainText(
- EphemeralRange::RangeOfContents(*this),
- TextIteratorBehavior::Builder().SetForInnerText(true).Build());
-}
-
String Element::outerText() {
// Getting outerText is the same as getting innerText, only
// setting is different. You would think this should get the plain
@@ -3912,7 +3755,7 @@ String Element::TextFromChildren() {
const AtomicString& Element::ShadowPseudoId() const {
if (ShadowRoot* root = ContainingShadowRoot()) {
if (root->IsUserAgent())
- return FastGetAttribute(pseudoAttr);
+ return FastGetAttribute(kPseudoAttr);
}
return g_null_atom;
}
@@ -3922,7 +3765,7 @@ void Element::SetShadowPseudoId(const AtomicString& id) {
CSSSelector::kPseudoWebKitCustomElement ||
CSSSelector::ParsePseudoType(id, false) ==
CSSSelector::kPseudoBlinkInternalElement);
- setAttribute(pseudoAttr, id);
+ setAttribute(kPseudoAttr, id);
}
bool Element::IsInDescendantTreeOf(const Element* shadow_host) const {
@@ -3950,6 +3793,23 @@ const ComputedStyle* Element::EnsureComputedStyle(
return nullptr;
}
+ // EnsureComputedStyle is expected to be called to forcibly compute style for
+ // elements in display:none subtrees on otherwise style-clean documents. If
+ // you hit this DCHECK, consider if you really need ComputedStyle for
+ // display:none elements. If not, use GetComputedStyle() instead.
+ // Regardlessly, you need to UpdateStyleAndLayoutTree() before calling
+ // EnsureComputedStyle. In some cases you might be fine using GetComputedStyle
+ // without updating the style, but in most cases you want a clean tree for
+ // that as well.
+ //
+ // Adjacent styling bits may be set and affect NeedsLayoutTreeUpdateForNode as
+ // part of EnsureComputedStyle in an ancestor chain.
+ // (see CSSComputedStyleDeclarationTest::NeedsAdjacentStyleRecalc). It is OK
+ // that it happens, but we need to ignore the effect on
+ // NeedsLayoutTreeUpdateForNode here.
+ DCHECK(!GetDocument().NeedsLayoutTreeUpdateForNode(
+ *this, true /* ignore_adjacent_style */));
+
// FIXME: Find and use the layoutObject from the pseudo element instead of the
// actual element so that the 'length' properties, which are only known by the
// layoutObject because it did the layout, will be correct and so that the
@@ -4041,10 +3901,10 @@ AtomicString Element::ComputeInheritedLanguage() const {
if (const ElementData* element_data = ToElement(n)->GetElementData()) {
AttributeCollection attributes = element_data->Attributes();
// Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
- if (const Attribute* attribute = attributes.Find(XMLNames::langAttr))
+ if (const Attribute* attribute = attributes.Find(xml_names::kLangAttr))
value = attribute->Value();
else if (const Attribute* attribute =
- attributes.Find(HTMLNames::langAttr))
+ attributes.Find(html_names::kLangAttr))
value = attribute->Value();
}
} else if (auto* document = DynamicTo<Document>(n)) {
@@ -4329,8 +4189,8 @@ Element* Element::closest(const AtomicString& selectors) {
DOMTokenList& Element::classList() {
ElementRareData& rare_data = EnsureElementRareData();
if (!rare_data.GetClassList()) {
- DOMTokenList* class_list = DOMTokenList::Create(*this, classAttr);
- class_list->DidUpdateAttributeValue(g_null_atom, getAttribute(classAttr));
+ DOMTokenList* class_list = DOMTokenList::Create(*this, kClassAttr);
+ class_list->DidUpdateAttributeValue(g_null_atom, getAttribute(kClassAttr));
rare_data.SetClassList(class_list);
}
return *rare_data.GetClassList();
@@ -4348,7 +4208,7 @@ KURL Element::HrefURL() const {
// doesn't <link> implement URLUtils?
if (IsHTMLAnchorElement(*this) || IsHTMLAreaElement(*this) ||
IsHTMLLinkElement(*this))
- return GetURLAttribute(hrefAttr);
+ return GetURLAttribute(kHrefAttr);
if (auto* svg_a = ToSVGAElementOrNull(*this))
return svg_a->LegacyHrefURL(GetDocument());
return KURL();
@@ -4432,7 +4292,8 @@ double Element::GetFloatingPointAttribute(const QualifiedName& attribute_name,
void Element::SetFloatingPointAttribute(const QualifiedName& attribute_name,
double value) {
- setAttribute(attribute_name, AtomicString::Number(value));
+ String serialized_value = SerializeForNumberType(value);
+ setAttribute(attribute_name, AtomicString(serialized_value));
}
void Element::SetContainsFullScreenElement(bool flag) {
@@ -4497,11 +4358,11 @@ void Element::SetIsInTopLayer(bool in_top_layer) {
if (IsInTopLayer() == in_top_layer)
return;
SetElementFlag(ElementFlags::kIsInTopLayer, in_top_layer);
-
- // We must ensure a reattach occurs so the layoutObject is inserted in the
- // correct sibling order under LayoutView according to its top layer position,
- // or in its usual place if not in the top layer.
- LazyReattachIfAttached();
+ if (!isConnected())
+ return;
+ SetForceReattachLayoutTree();
+ SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
+ style_change_reason::kFullscreen));
}
void Element::requestPointerLock() {
@@ -4511,7 +4372,7 @@ void Element::requestPointerLock() {
}
SpellcheckAttributeState Element::GetSpellcheckAttributeState() const {
- const AtomicString& value = FastGetAttribute(spellcheckAttr);
+ const AtomicString& value = FastGetAttribute(kSpellcheckAttr);
if (value == g_null_atom)
return kSpellcheckAttributeDefault;
if (DeprecatedEqualIgnoringCase(value, "true") ||
@@ -4544,7 +4405,7 @@ bool Element::IsSpellCheckingEnabled() const {
#if DCHECK_IS_ON()
bool Element::FastAttributeLookupAllowed(const QualifiedName& name) const {
- if (name == HTMLNames::styleAttr)
+ if (name == html_names::kStyleAttr)
return false;
if (IsSVGElement())
@@ -4604,7 +4465,7 @@ inline void Element::UpdateId(TreeScope& scope,
void Element::WillModifyAttribute(const QualifiedName& name,
const AtomicString& old_value,
const AtomicString& new_value) {
- if (name == HTMLNames::nameAttr) {
+ if (name == html_names::kNameAttr) {
UpdateName(old_value, new_value);
}
@@ -4633,7 +4494,7 @@ void Element::WillModifyAttribute(const QualifiedName& name,
DISABLE_CFI_PERF
void Element::DidAddAttribute(const QualifiedName& name,
const AtomicString& value) {
- if (name == HTMLNames::idAttr)
+ if (name == html_names::kIdAttr)
UpdateId(g_null_atom, value);
AttributeChanged(AttributeModificationParams(
name, g_null_atom, value, AttributeModificationReason::kDirectly));
@@ -4644,7 +4505,7 @@ void Element::DidAddAttribute(const QualifiedName& name,
void Element::DidModifyAttribute(const QualifiedName& name,
const AtomicString& old_value,
const AtomicString& new_value) {
- if (name == HTMLNames::idAttr)
+ if (name == html_names::kIdAttr)
UpdateId(old_value, new_value);
AttributeChanged(AttributeModificationParams(
name, old_value, new_value, AttributeModificationReason::kDirectly));
@@ -4654,7 +4515,7 @@ void Element::DidModifyAttribute(const QualifiedName& name,
void Element::DidRemoveAttribute(const QualifiedName& name,
const AtomicString& old_value) {
- if (name == HTMLNames::idAttr)
+ if (name == html_names::kIdAttr)
UpdateId(old_value, g_null_atom);
AttributeChanged(AttributeModificationParams(
name, old_value, g_null_atom, AttributeModificationReason::kDirectly));
@@ -4703,7 +4564,7 @@ void Element::DidMoveToNewDocument(Document& old_document) {
if (HasID())
SetIdAttribute(GetIdAttribute());
if (HasClass())
- setAttribute(HTMLNames::classAttr, GetClassAttribute());
+ setAttribute(html_names::kClassAttr, GetClassAttribute());
}
// TODO(tkent): Even if Documents' modes are same, keeping
// ShareableElementData owned by old_document isn't right.
@@ -4932,7 +4793,7 @@ void Element::SynchronizeStyleAttributeInternal() const {
GetElementData()->style_attribute_is_dirty_ = false;
const CSSPropertyValueSet* inline_style = InlineStyle();
const_cast<Element*>(this)->SetSynchronizedLazyAttribute(
- styleAttr,
+ kStyleAttr,
inline_style ? AtomicString(inline_style->AsText()) : g_empty_atom);
}
@@ -5027,32 +4888,32 @@ void Element::StyleAttributeChanged(
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleSheetChange));
+ style_change_reason::kStyleSheetChange));
probe::didInvalidateStyleAttr(this);
}
void Element::InlineStyleChanged() {
DCHECK(IsStyledElement());
SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kInline));
+ style_change_reason::kInline));
DCHECK(GetElementData());
GetElementData()->style_attribute_is_dirty_ = true;
probe::didInvalidateStyleAttr(this);
if (MutationObserverInterestGroup* recipients =
MutationObserverInterestGroup::CreateForAttributesMutation(
- *this, styleAttr)) {
+ *this, kStyleAttr)) {
// We don't use getAttribute() here to get a style attribute value
// before the change.
AtomicString old_value;
if (const Attribute* attribute =
- GetElementData()->Attributes().Find(styleAttr))
+ GetElementData()->Attributes().Find(kStyleAttr))
old_value = attribute->Value();
recipients->EnqueueMutationRecord(
- MutationRecord::CreateAttributes(this, styleAttr, old_value));
+ MutationRecord::CreateAttributes(this, kStyleAttr, old_value));
// Need to synchronize every time so that following MutationRecords will
// have correct oldValues.
- SynchronizeAttribute(styleAttr);
+ SynchronizeAttribute(kStyleAttr);
}
}
@@ -5241,23 +5102,33 @@ void Element::Trace(blink::Visitor* visitor) {
ContainerNode::Trace(visitor);
}
-bool Element::HasPartName() const {
+bool Element::HasPart() const {
if (!RuntimeEnabledFeatures::CSSPartPseudoElementEnabled())
return false;
if (HasRareData()) {
- if (auto* part_names = GetElementRareData()->PartNames()) {
- return part_names->size() > 0;
+ if (auto* part = GetElementRareData()->GetPart()) {
+ return part->length() > 0;
}
}
return false;
}
-const SpaceSplitString* Element::PartNames() const {
+DOMTokenList* Element::GetPart() const {
return RuntimeEnabledFeatures::CSSPartPseudoElementEnabled() && HasRareData()
- ? GetElementRareData()->PartNames()
+ ? GetElementRareData()->GetPart()
: nullptr;
}
+DOMTokenList& Element::part() {
+ ElementRareData& rare_data = EnsureElementRareData();
+ DOMTokenList* part = rare_data.GetPart();
+ if (!part) {
+ part = DOMTokenList::Create(*this, kPartAttr);
+ rare_data.SetPart(part);
+ }
+ return *part;
+}
+
bool Element::HasPartNamesMap() const {
const NamesMap* names_map = PartNamesMap();
return names_map && names_map->size() > 0;
@@ -5269,4 +5140,14 @@ const NamesMap* Element::PartNamesMap() const {
: nullptr;
}
+bool Element::StyleRecalcBlockedByDisplayLock() const {
+ auto* context = GetDisplayLockContext();
+ return context && !context->ShouldStyle();
+}
+
+void Element::NotifyDisplayLockDidRecalcStyle() {
+ if (auto* context = GetDisplayLockContext())
+ context->DidStyle();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/element.h b/chromium/third_party/blink/renderer/core/dom/element.h
index 36d8ccd308e..430fd713515 100644
--- a/chromium/third_party/blink/renderer/core/dom/element.h
+++ b/chromium/third_party/blink/renderer/core/dom/element.h
@@ -38,7 +38,6 @@
#include "third_party/blink/renderer/core/html/focus_options.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer.h"
-#include "third_party/blink/renderer/core/scroll/scroll_customization.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
@@ -58,7 +57,9 @@ class DOMRectList;
class DOMStringMap;
class DOMTokenList;
class Document;
+class DisplayLockContext;
class ElementAnimations;
+class ElementInternals;
class ElementIntersectionObserverData;
class ElementRareData;
class ExceptionState;
@@ -74,8 +75,6 @@ class PseudoStyleRequest;
class ResizeObservation;
class ScrollIntoViewOptions;
class ScrollIntoViewOptionsOrBoolean;
-class ScrollState;
-class ScrollStateCallback;
class ScrollToOptions;
class ShadowRoot;
class ShadowRootInit;
@@ -89,7 +88,6 @@ class StylePropertyMapReadOnly;
class USVStringOrTrustedURL;
class V0CustomElementDefinition;
class V8DisplayLockCallback;
-class V8ScrollStateCallback;
enum SpellcheckAttributeState {
kSpellcheckAttributeTrue,
@@ -134,11 +132,11 @@ struct FocusParams {
STACK_ALLOCATED();
public:
- FocusParams() = default;
+ FocusParams() : options(FocusOptions::Create()) {}
FocusParams(SelectionBehaviorOnFocus selection,
WebFocusType focus_type,
InputDeviceCapabilities* capabilities,
- FocusOptions focus_options = FocusOptions())
+ const FocusOptions* focus_options = FocusOptions::Create())
: selection_behavior(selection),
type(focus_type),
source_capabilities(capabilities),
@@ -148,7 +146,7 @@ struct FocusParams {
SelectionBehaviorOnFocus::kRestore;
WebFocusType type = kWebFocusTypeNone;
Member<InputDeviceCapabilities> source_capabilities = nullptr;
- FocusOptions options = FocusOptions();
+ Member<const FocusOptions> options;
};
typedef HeapVector<TraceWrapperMember<Attr>> AttrNodeList;
@@ -158,12 +156,14 @@ class CORE_EXPORT Element : public ContainerNode {
public:
static Element* Create(const QualifiedName&, Document*);
+
+ Element(const QualifiedName& tag_name, Document*, ConstructionType);
~Element() override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy, kBeforecopy);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut, kBeforecut);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste, kBeforepaste);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(search, kSearch);
bool hasAttribute(const QualifiedName&) const;
const AtomicString& getAttribute(const QualifiedName&) const;
@@ -291,8 +291,8 @@ class CORE_EXPORT Element : public ContainerNode {
void scrollIntoView(ScrollIntoViewOptionsOrBoolean);
void scrollIntoView(bool align_to_top = true);
- void scrollIntoViewWithOptions(const ScrollIntoViewOptions&);
- void ScrollIntoViewNoVisualUpdate(const ScrollIntoViewOptions&);
+ void scrollIntoViewWithOptions(const ScrollIntoViewOptions*);
+ void ScrollIntoViewNoVisualUpdate(const ScrollIntoViewOptions*);
void scrollIntoViewIfNeeded(bool center_if_needed = true);
int OffsetLeft();
@@ -313,9 +313,9 @@ class CORE_EXPORT Element : public ContainerNode {
int scrollHeight();
void scrollBy(double x, double y);
- virtual void scrollBy(const ScrollToOptions&);
+ virtual void scrollBy(const ScrollToOptions*);
void scrollTo(double x, double y);
- virtual void scrollTo(const ScrollToOptions&);
+ virtual void scrollTo(const ScrollToOptions*);
IntRect BoundsInViewport() const;
// Returns an intersection rectangle of the bounds rectangle and the visual
@@ -534,8 +534,7 @@ class CORE_EXPORT Element : public ContainerNode {
// throws an exception. Multiple shadow roots are allowed only when
// createShadowRoot() is used without any parameters from JavaScript.
ShadowRoot* createShadowRoot(ExceptionState&);
- ShadowRoot* attachShadow(const ShadowRootInit&,
- ExceptionState&);
+ ShadowRoot* attachShadow(const ShadowRootInit*, ExceptionState&);
ShadowRoot& CreateV0ShadowRootForTesting() {
return CreateShadowRootInternal();
@@ -631,27 +630,13 @@ class CORE_EXPORT Element : public ContainerNode {
virtual Image* ImageContents() { return nullptr; }
virtual void focus(const FocusParams& = FocusParams());
- void focus(FocusOptions);
+ void focus(const FocusOptions*);
void UpdateFocusAppearance(SelectionBehaviorOnFocus);
virtual void UpdateFocusAppearanceWithOptions(SelectionBehaviorOnFocus,
- const FocusOptions&);
+ const FocusOptions*);
virtual void blur();
- void setDistributeScroll(V8ScrollStateCallback*,
- const String& native_scroll_behavior);
- void NativeDistributeScroll(ScrollState&);
- void setApplyScroll(V8ScrollStateCallback*,
- const String& native_scroll_behavior);
- void SetApplyScroll(ScrollStateCallback*);
- void RemoveApplyScroll();
- void NativeApplyScroll(ScrollState&);
-
- void CallDistributeScroll(ScrollState&);
- void CallApplyScroll(ScrollState&);
-
- ScrollStateCallback* GetApplyScroll();
-
// Whether this element can receive focus at all. Most elements are not
// focusable but some elements, such as form controls and links, are. Unlike
// layoutObjectIsFocusable(), this method may be called when layout is not up
@@ -826,6 +811,9 @@ class CORE_EXPORT Element : public ContainerNode {
// https://dom.spec.whatwg.org/#concept-element-is-value
void SetIsValue(const AtomicString&);
const AtomicString& IsValue() const;
+ void SetDidAttachInternals();
+ bool DidAttachInternals() const;
+ ElementInternals& EnsureElementInternals();
bool ContainsFullScreenElement() const {
return HasElementFlag(ElementFlags::kContainsFullScreenElement);
@@ -855,8 +843,13 @@ class CORE_EXPORT Element : public ContainerNode {
const SpaceSplitString& ClassNames() const;
bool HasClassName(const AtomicString& class_name) const;
- bool HasPartName() const;
- const SpaceSplitString* PartNames() const;
+ // Returns true if the element has 1 or more part names.
+ bool HasPart() const;
+ // Returns the list of part names if it has ever been created.
+ DOMTokenList* GetPart() const;
+ // IDL method.
+ // Returns the list of part names, creating it if it doesn't exist.
+ DOMTokenList& part();
bool HasPartNamesMap() const;
const NamesMap* PartNamesMap() const;
@@ -905,14 +898,12 @@ class CORE_EXPORT Element : public ContainerNode {
EnsureResizeObserverData();
void SetNeedsResizeObserverUpdate();
- void WillBeginCustomizedScrollPhase(ScrollCustomization::ScrollDirection);
- void DidEndCustomizedScrollPhase();
-
ScriptPromise acquireDisplayLock(ScriptState*, V8DisplayLockCallback*);
+ DisplayLockContext* GetDisplayLockContext() const;
- protected:
- Element(const QualifiedName& tag_name, Document*, ConstructionType);
+ bool StyleRecalcBlockedByDisplayLock() const;
+ protected:
const ElementData* GetElementData() const { return element_data_.Get(); }
UniqueElementData& EnsureUniqueElementData();
@@ -970,10 +961,10 @@ class CORE_EXPORT Element : public ContainerNode {
virtual void ParserDidSetAttributes() {}
private:
- void ScrollLayoutBoxBy(const ScrollToOptions&);
- void ScrollLayoutBoxTo(const ScrollToOptions&);
- void ScrollFrameBy(const ScrollToOptions&);
- void ScrollFrameTo(const ScrollToOptions&);
+ void ScrollLayoutBoxBy(const ScrollToOptions*);
+ void ScrollLayoutBoxTo(const ScrollToOptions*);
+ void ScrollFrameBy(const ScrollToOptions*);
+ void ScrollFrameTo(const ScrollToOptions*);
bool HasElementFlag(ElementFlags mask) const {
return HasRareData() && HasElementFlagInternal(mask);
@@ -1120,6 +1111,8 @@ class CORE_EXPORT Element : public ContainerNode {
void DetachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);
void DetachAttrNodeAtIndex(Attr*, wtf_size_t index);
+ void NotifyDisplayLockDidRecalcStyle();
+
Member<ElementData> element_data_;
};
@@ -1254,23 +1247,23 @@ inline const AtomicString& Element::IdForStyleResolution() const {
}
inline const AtomicString& Element::GetIdAttribute() const {
- return HasID() ? FastGetAttribute(HTMLNames::idAttr) : g_null_atom;
+ return HasID() ? FastGetAttribute(html_names::kIdAttr) : g_null_atom;
}
inline const AtomicString& Element::GetNameAttribute() const {
- return HasName() ? FastGetAttribute(HTMLNames::nameAttr) : g_null_atom;
+ return HasName() ? FastGetAttribute(html_names::kNameAttr) : g_null_atom;
}
inline const AtomicString& Element::GetClassAttribute() const {
if (!HasClass())
return g_null_atom;
if (IsSVGElement())
- return getAttribute(HTMLNames::classAttr);
- return FastGetAttribute(HTMLNames::classAttr);
+ return getAttribute(html_names::kClassAttr);
+ return FastGetAttribute(html_names::kClassAttr);
}
inline void Element::SetIdAttribute(const AtomicString& value) {
- setAttribute(HTMLNames::idAttr, value);
+ setAttribute(html_names::kIdAttr, value);
}
inline const SpaceSplitString& Element::ClassNames() const {
diff --git a/chromium/third_party/blink/renderer/core/dom/element.idl b/chromium/third_party/blink/renderer/core/dom/element.idl
index a1e311a7651..6c6e91778ca 100644
--- a/chromium/third_party/blink/renderer/core/dom/element.idl
+++ b/chromium/third_party/blink/renderer/core/dom/element.idl
@@ -36,6 +36,7 @@ interface Element : Node {
[Affects=Nothing, CEReactions, Reflect=class] attribute DOMString className;
[Affects=Nothing, SameObject, PerWorldBindings, PutForwards=value] readonly attribute DOMTokenList classList;
[Unscopable, CEReactions, Reflect] attribute DOMString slot;
+ [RuntimeEnabled=CSSPartPseudoElement, Affects=Nothing, SameObject, PerWorldBindings, PutForwards=value] readonly attribute DOMTokenList part;
// Pointer Events
// https://w3c.github.io/pointerevents/#extensions-to-the-element-interface
@@ -100,12 +101,12 @@ interface Element : Node {
// TODO(sunyunjia): Add default value for scrollIntoView() once
// crbug.com/734599 is fixed.
void scrollIntoView(optional (ScrollIntoViewOptions or boolean) arg);
- [RuntimeEnabled=CSSOMSmoothScroll, ImplementedAs=scrollTo] void scroll(optional ScrollToOptions options);
- [RuntimeEnabled=CSSOMSmoothScroll, ImplementedAs=scrollTo] void scroll(unrestricted double x, unrestricted double y);
- [RuntimeEnabled=CSSOMSmoothScroll] void scrollTo(optional ScrollToOptions options);
- [RuntimeEnabled=CSSOMSmoothScroll] void scrollTo(unrestricted double x, unrestricted double y);
- [RuntimeEnabled=CSSOMSmoothScroll] void scrollBy(optional ScrollToOptions options);
- [RuntimeEnabled=CSSOMSmoothScroll] void scrollBy(unrestricted double x, unrestricted double y);
+ [ImplementedAs=scrollTo] void scroll(optional ScrollToOptions options);
+ [ImplementedAs=scrollTo] void scroll(unrestricted double x, unrestricted double y);
+ void scrollTo(optional ScrollToOptions options);
+ void scrollTo(unrestricted double x, unrestricted double y);
+ void scrollBy(optional ScrollToOptions options);
+ void scrollBy(unrestricted double x, unrestricted double y);
[Affects=Nothing] attribute unrestricted double scrollTop;
[Affects=Nothing] attribute unrestricted double scrollLeft;
[Affects=Nothing] readonly attribute long scrollWidth;
@@ -115,10 +116,6 @@ interface Element : Node {
[Affects=Nothing] readonly attribute long clientWidth;
[Affects=Nothing] readonly attribute long clientHeight;
- // Scroll Customization API. See crbug.com/410974 for details.
- [RuntimeEnabled=ScrollCustomization] void setApplyScroll(ScrollStateCallback scrollStateCallback, NativeScrollBehavior nativeScrollBehavior);
- [RuntimeEnabled=ScrollCustomization] void setDistributeScroll(ScrollStateCallback scrollStateCallback, NativeScrollBehavior nativeScrollBehavior);
-
// Typed OM
// https://drafts.css-houdini.org/css-typed-om/#inline-stylepropertymap-objects
[SameObject, MeasureAs=CSSTypedOMStylePropertyMap] readonly attribute StylePropertyMap attributeStyleMap;
diff --git a/chromium/third_party/blink/renderer/core/dom/element_data.cc b/chromium/third_party/blink/renderer/core/dom/element_data.cc
index 2275ad72e34..a772eead2ba 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_data.cc
+++ b/chromium/third_party/blink/renderer/core/dom/element_data.cc
@@ -87,8 +87,8 @@ void ElementData::FinalizeGarbageCollectedObject() {
UniqueElementData* ElementData::MakeUniqueCopy() const {
if (IsUnique())
- return new UniqueElementData(ToUniqueElementData(*this));
- return new UniqueElementData(ToShareableElementData(*this));
+ return MakeGarbageCollected<UniqueElementData>(ToUniqueElementData(*this));
+ return MakeGarbageCollected<UniqueElementData>(ToShareableElementData(*this));
}
bool ElementData::IsEquivalent(const ElementData* other) const {
@@ -173,7 +173,7 @@ UniqueElementData::UniqueElementData(const ShareableElementData& other)
}
UniqueElementData* UniqueElementData::Create() {
- return new UniqueElementData;
+ return MakeGarbageCollected<UniqueElementData>();
}
ShareableElementData* UniqueElementData::MakeShareableCopy() const {
diff --git a/chromium/third_party/blink/renderer/core/dom/element_data_cache.h b/chromium/third_party/blink/renderer/core/dom/element_data_cache.h
index 4c915fb6441..9e115429704 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_data_cache.h
+++ b/chromium/third_party/blink/renderer/core/dom/element_data_cache.h
@@ -39,7 +39,11 @@ class ShareableElementData;
class ElementDataCache final : public GarbageCollected<ElementDataCache> {
public:
- static ElementDataCache* Create() { return new ElementDataCache; }
+ static ElementDataCache* Create() {
+ return MakeGarbageCollected<ElementDataCache>();
+ }
+
+ ElementDataCache();
ShareableElementData* CachedShareableElementDataWithAttributes(
const Vector<Attribute>&);
@@ -47,8 +51,6 @@ class ElementDataCache final : public GarbageCollected<ElementDataCache> {
void Trace(blink::Visitor*);
private:
- ElementDataCache();
-
typedef HeapHashMap<unsigned, Member<ShareableElementData>, AlreadyHashed>
ShareableElementDataCache;
ShareableElementDataCache shareable_element_data_cache_;
diff --git a/chromium/third_party/blink/renderer/core/dom/element_rare_data.cc b/chromium/third_party/blink/renderer/core/dom/element_rare_data.cc
index eb67c03c2db..4846d42dbc1 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_rare_data.cc
+++ b/chromium/third_party/blink/renderer/core/dom/element_rare_data.cc
@@ -32,6 +32,7 @@
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/css/cssom/inline_style_property_map.h"
+#include "third_party/blink/renderer/core/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observation.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
@@ -40,8 +41,9 @@ namespace blink {
struct SameSizeAsElementRareData : NodeRareData {
IntSize scroll_offset;
- void* pointers_or_strings[5];
- Member<void*> members[14];
+ void* pointers_or_strings[4];
+ Member<void*> members[17];
+ bool flags[1];
};
ElementRareData::ElementRareData(NodeRenderingData* node_layout_data)
@@ -55,15 +57,18 @@ ElementRareData::~ElementRareData() {
CSSStyleDeclaration& ElementRareData::EnsureInlineCSSStyleDeclaration(
Element* owner_element) {
- if (!cssom_wrapper_)
- cssom_wrapper_ = new InlineCSSStyleDeclaration(owner_element);
+ if (!cssom_wrapper_) {
+ cssom_wrapper_ =
+ MakeGarbageCollected<InlineCSSStyleDeclaration>(owner_element);
+ }
return *cssom_wrapper_;
}
InlineStylePropertyMap& ElementRareData::EnsureInlineStylePropertyMap(
Element* owner_element) {
if (!cssom_map_wrapper_) {
- cssom_map_wrapper_ = new InlineStylePropertyMap(owner_element);
+ cssom_map_wrapper_ =
+ MakeGarbageCollected<InlineStylePropertyMap>(owner_element);
}
return *cssom_map_wrapper_;
}
@@ -79,21 +84,31 @@ void ElementRareData::ClearComputedStyle() {
AttrNodeList& ElementRareData::EnsureAttrNodeList() {
if (!attr_node_list_)
- attr_node_list_ = new AttrNodeList;
+ attr_node_list_ = MakeGarbageCollected<AttrNodeList>();
return *attr_node_list_;
}
ElementRareData::ResizeObserverDataMap&
ElementRareData::EnsureResizeObserverData() {
- if (!resize_observer_data_)
- resize_observer_data_ = new HeapHashMap<TraceWrapperMember<ResizeObserver>,
- Member<ResizeObservation>>();
+ if (!resize_observer_data_) {
+ resize_observer_data_ =
+ MakeGarbageCollected<HeapHashMap<TraceWrapperMember<ResizeObserver>,
+ Member<ResizeObservation>>>();
+ }
return *resize_observer_data_;
}
+ElementInternals& ElementRareData::EnsureElementInternals(HTMLElement& target) {
+ if (element_internals_)
+ return *element_internals_;
+ element_internals_ = MakeGarbageCollected<ElementInternals>(target);
+ return *element_internals_;
+}
+
void ElementRareData::TraceAfterDispatch(blink::Visitor* visitor) {
visitor->Trace(dataset_);
visitor->Trace(class_list_);
+ visitor->Trace(part_);
visitor->Trace(shadow_root_);
visitor->Trace(attribute_map_);
visitor->Trace(attr_node_list_);
@@ -102,8 +117,10 @@ void ElementRareData::TraceAfterDispatch(blink::Visitor* visitor) {
visitor->Trace(cssom_map_wrapper_);
visitor->Trace(pseudo_element_data_);
visitor->Trace(accessible_node_);
+ visitor->Trace(display_lock_context_);
visitor->Trace(v0_custom_element_definition_);
visitor->Trace(custom_element_definition_);
+ visitor->Trace(element_internals_);
visitor->Trace(intersection_observer_data_);
visitor->Trace(resize_observer_data_);
NodeRareData::TraceAfterDispatch(visitor);
diff --git a/chromium/third_party/blink/renderer/core/dom/element_rare_data.h b/chromium/third_party/blink/renderer/core/dom/element_rare_data.h
index b73961b318c..6f8d1dbc904 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_rare_data.h
+++ b/chromium/third_party/blink/renderer/core/dom/element_rare_data.h
@@ -27,6 +27,7 @@
#include "third_party/blink/renderer/core/aom/accessible_node.h"
#include "third_party/blink/renderer/core/css/cssom/inline_style_property_map.h"
#include "third_party/blink/renderer/core/css/inline_css_style_declaration.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
#include "third_party/blink/renderer/core/dom/attr.h"
#include "third_party/blink/renderer/core/dom/dataset_dom_string_map.h"
#include "third_party/blink/renderer/core/dom/dom_token_list.h"
@@ -47,15 +48,18 @@
namespace blink {
+class Element;
+class HTMLElement;
class ResizeObservation;
class ResizeObserver;
class ElementRareData : public NodeRareData {
public:
static ElementRareData* Create(NodeRenderingData* node_layout_data) {
- return new ElementRareData(node_layout_data);
+ return MakeGarbageCollected<ElementRareData>(node_layout_data);
}
+ explicit ElementRareData(NodeRenderingData*);
~ElementRareData();
void SetPseudoElement(PseudoId, PseudoElement*);
@@ -96,15 +100,12 @@ class ElementRareData : public NodeRareData {
class_list_ = class_list;
}
- void SetPart(const AtomicString part_names) {
+ void SetPart(DOMTokenList* part) {
if (!RuntimeEnabledFeatures::CSSPartPseudoElementEnabled())
return;
- if (!part_names_) {
- part_names_.reset(new SpaceSplitString());
- }
- part_names_->Set(part_names);
+ part_ = part;
}
- const SpaceSplitString* PartNames() const { return part_names_.get(); }
+ DOMTokenList* GetPart() const { return part_.Get(); }
void SetPartNamesMap(const AtomicString part_names) {
if (!RuntimeEnabledFeatures::CSSPartPseudoElementEnabled())
@@ -153,6 +154,9 @@ class ElementRareData : public NodeRareData {
}
void SetIsValue(const AtomicString& is_value) { is_value_ = is_value; }
const AtomicString& IsValue() const { return is_value_; }
+ void SetDidAttachInternals() { did_attach_internals_ = true; }
+ bool DidAttachInternals() const { return did_attach_internals_; }
+ ElementInternals& EnsureElementInternals(HTMLElement& target);
AccessibleNode* GetAccessibleNode() const { return accessible_node_.Get(); }
AccessibleNode* EnsureAccessibleNode(Element* owner_element) {
@@ -174,7 +178,8 @@ class ElementRareData : public NodeRareData {
}
ElementIntersectionObserverData& EnsureIntersectionObserverData() {
if (!intersection_observer_data_) {
- intersection_observer_data_ = new ElementIntersectionObserverData();
+ intersection_observer_data_ =
+ MakeGarbageCollected<ElementIntersectionObserverData>();
}
return *intersection_observer_data_;
}
@@ -187,6 +192,17 @@ class ElementRareData : public NodeRareData {
}
ResizeObserverDataMap& EnsureResizeObserverData();
+ DisplayLockContext* EnsureDisplayLockContext(Element* element,
+ ExecutionContext* context) {
+ if (!display_lock_context_ || display_lock_context_->IsResolved()) {
+ display_lock_context_ = new DisplayLockContext(element, context);
+ }
+ return display_lock_context_.Get();
+ }
+ DisplayLockContext* GetDisplayLockContext() const {
+ return display_lock_context_;
+ }
+
const AtomicString& GetNonce() const { return nonce_; }
void SetNonce(const AtomicString& nonce) { nonce_ = nonce; }
@@ -199,7 +215,7 @@ class ElementRareData : public NodeRareData {
TraceWrapperMember<DatasetDOMStringMap> dataset_;
TraceWrapperMember<ShadowRoot> shadow_root_;
TraceWrapperMember<DOMTokenList> class_list_;
- std::unique_ptr<SpaceSplitString> part_names_;
+ TraceWrapperMember<DOMTokenList> part_;
std::unique_ptr<NamesMap> part_names_map_;
TraceWrapperMember<NamedNodeMap> attribute_map_;
TraceWrapperMember<AttrNodeList> attr_node_list_;
@@ -216,12 +232,14 @@ class ElementRareData : public NodeRareData {
Member<V0CustomElementDefinition> v0_custom_element_definition_;
Member<CustomElementDefinition> custom_element_definition_;
AtomicString is_value_;
+ TraceWrapperMember<ElementInternals> element_internals_;
Member<PseudoElementData> pseudo_element_data_;
TraceWrapperMember<AccessibleNode> accessible_node_;
- explicit ElementRareData(NodeRenderingData*);
+ WeakMember<DisplayLockContext> display_lock_context_;
+ bool did_attach_internals_ = false;
};
inline LayoutSize DefaultMinimumSizeForResizing() {
diff --git a/chromium/third_party/blink/renderer/core/dom/element_test.cc b/chromium/third_party/blink/renderer/core/dom/element_test.cc
index 74d0347e52a..db52ab4c9c8 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/element_test.cc
@@ -7,6 +7,7 @@
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/dom_token_list.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/editing/testing/editing_test_base.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
@@ -24,7 +25,8 @@ TEST_F(ElementTest, SupportsFocus) {
Document& document = GetDocument();
DCHECK(IsHTMLHtmlElement(document.documentElement()));
document.setDesignMode("on");
- document.View()->UpdateAllLifecyclePhases();
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_TRUE(document.documentElement()->SupportsFocus())
<< "<html> with designMode=on should be focusable.";
}
@@ -217,7 +219,8 @@ TEST_F(ElementTest, StickySubtreesAreTrackedCorrectly) {
// ensure that the sticky subtree update behavior survives forking.
document.getElementById("child")->SetInlineStyleProperty(
CSSPropertyWebkitRubyPosition, CSSValueAfter);
- document.View()->UpdateAllLifecyclePhases();
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_EQ(DocumentLifecycle::kPaintClean, document.Lifecycle().GetState());
EXPECT_EQ(RubyPosition::kBefore, outer_sticky->StyleRef().GetRubyPosition());
@@ -239,7 +242,8 @@ TEST_F(ElementTest, StickySubtreesAreTrackedCorrectly) {
// fork it's StyleRareInheritedData to maintain the sticky subtree bit.
document.getElementById("outerSticky")
->SetInlineStyleProperty(CSSPropertyPosition, CSSValueStatic);
- document.View()->UpdateAllLifecyclePhases();
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_EQ(DocumentLifecycle::kPaintClean, document.Lifecycle().GetState());
EXPECT_FALSE(outer_sticky->StyleRef().SubtreeIsSticky());
@@ -362,40 +366,42 @@ TEST_F(ElementTest, PartAttribute) {
ASSERT_TRUE(has_two_parts);
{
- EXPECT_TRUE(has_one_part->HasPartName());
- const SpaceSplitString* part_names = has_one_part->PartNames();
- ASSERT_TRUE(part_names);
- ASSERT_EQ(1UL, part_names->size());
- ASSERT_EQ("partname", (*part_names)[0].Ascii());
+ EXPECT_TRUE(has_one_part->HasPart());
+ const DOMTokenList* part = has_one_part->GetPart();
+ ASSERT_TRUE(part);
+ ASSERT_EQ(1UL, part->length());
+ ASSERT_EQ("partname", part->value());
}
{
- EXPECT_TRUE(has_two_parts->HasPartName());
- const SpaceSplitString* part_names = has_two_parts->PartNames();
- ASSERT_TRUE(part_names);
- ASSERT_EQ(2UL, part_names->size());
- ASSERT_EQ("partname1", (*part_names)[0].Ascii());
- ASSERT_EQ("partname2", (*part_names)[1].Ascii());
+ EXPECT_TRUE(has_two_parts->HasPart());
+ const DOMTokenList* part = has_two_parts->GetPart();
+ ASSERT_TRUE(part);
+ ASSERT_EQ(2UL, part->length());
+ ASSERT_EQ("partname1 partname2", part->value());
}
{
- EXPECT_FALSE(has_no_part->HasPartName());
- EXPECT_FALSE(has_no_part->PartNames());
+ EXPECT_FALSE(has_no_part->HasPart());
+ EXPECT_FALSE(has_no_part->GetPart());
+
+ // Calling the DOM API should force creation of an empty DOMTokenList.
+ const DOMTokenList& part = has_no_part->part();
+ EXPECT_FALSE(has_no_part->HasPart());
+ EXPECT_EQ(&part, has_no_part->GetPart());
// Now update the attribute value and make sure it's reflected.
has_no_part->setAttribute("part", "partname");
- const SpaceSplitString* part_names = has_no_part->PartNames();
- ASSERT_TRUE(part_names);
- ASSERT_EQ(1UL, part_names->size());
- ASSERT_EQ("partname", (*part_names)[0].Ascii());
+ ASSERT_EQ(1UL, part.length());
+ ASSERT_EQ("partname", part.value());
}
}
-TEST_F(ElementTest, PartmapAttribute) {
+TEST_F(ElementTest, ExportpartsAttribute) {
Document& document = GetDocument();
SetBodyContent(R"HTML(
- <span id='has_one_mapping' partmap='partname1 partname2'></span>
- <span id='has_two_mappings' partmap='partname1 partname2, partname3 partname4'></span>
+ <span id='has_one_mapping' exportparts='partname1: partname2'></span>
+ <span id='has_two_mappings' exportparts='partname1: partname2, partname3: partname4'></span>
<span id='has_no_mapping'></span>
)HTML");
@@ -432,7 +438,7 @@ TEST_F(ElementTest, PartmapAttribute) {
EXPECT_FALSE(has_no_mapping->PartNamesMap());
// Now update the attribute value and make sure it's reflected.
- has_no_mapping->setAttribute("partmap", "partname1 partname2");
+ has_no_mapping->setAttribute("exportparts", "partname1: partname2");
const NamesMap* part_names_map = has_no_mapping->PartNamesMap();
ASSERT_TRUE(part_names_map);
ASSERT_EQ(1UL, part_names_map->size());
diff --git a/chromium/third_party/blink/renderer/core/dom/element_traversal.h b/chromium/third_party/blink/renderer/core/dom/element_traversal.h
index 0a9e5933b50..19098838323 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_traversal.h
+++ b/chromium/third_party/blink/renderer/core/dom/element_traversal.h
@@ -56,13 +56,14 @@ class HasTagName {
// that defines operator(). HasTagName above is an example of a matcher.
//
// For example, a caller could do this:
-// Traversal<Element>::firstChild(someNode, HasTagName(HTMLNames::titleTag));
+// Traversal<Element>::firstChild(some_node,
+// HasTagName(html_names::kTitleTag));
//
-// This invocation would return the first child of |someNode| (which has to be a
-// ContainerNode) for which HasTagName(HTMLNames::titleTag) returned true, so it
-// would return the first child of |someNode| which is a <title> element. If the
-// caller needs to traverse a Node this way, it's necessary to first check
-// Node::isContainerNode() and then use toContainerNode().
+// This invocation would return the first child of |some_node| (which has to be
+// a ContainerNode) for which HasTagName(html_names::kTitleTag) returned true,
+// so it would return the first child of |someNode| which is a <title> element.
+// If the caller needs to traverse a Node this way, it's necessary to first
+// check Node::IsContainerNode() and then use ToContainerNode().
//
// When looking for a specific element type, it is more efficient to do this:
// Traversal<HTMLTitleElement>::firstChild(someNode);
diff --git a/chromium/third_party/blink/renderer/core/dom/element_visibility_observer_test.cc b/chromium/third_party/blink/renderer/core/dom/element_visibility_observer_test.cc
index 5cc0d1a8953..f629fe863d5 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_visibility_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/element_visibility_observer_test.cc
@@ -20,7 +20,7 @@ namespace {
class ElementVisibilityObserverTest : public ::testing::Test {
protected:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
};
TEST_F(ElementVisibilityObserverTest, ObserveElementWithoutDocumentFrame) {
@@ -28,8 +28,9 @@ TEST_F(ElementVisibilityObserverTest, ObserveElementWithoutDocumentFrame) {
Document& document = *helper_.LocalMainFrame()->GetFrame()->GetDocument();
HTMLElement* element = HTMLDivElement::Create(
*DOMImplementation::Create(document)->createHTMLDocument("test"));
- ElementVisibilityObserver* observer = new ElementVisibilityObserver(
- element, ElementVisibilityObserver::VisibilityCallback());
+ ElementVisibilityObserver* observer =
+ MakeGarbageCollected<ElementVisibilityObserver>(
+ element, ElementVisibilityObserver::VisibilityCallback());
observer->Start();
observer->Stop();
// It should not crash.
@@ -39,12 +40,13 @@ TEST_F(ElementVisibilityObserverTest, ObserveElementWithRemoteFrameParent) {
helper_.InitializeRemote();
WebLocalFrameImpl* child_frame =
- FrameTestHelpers::CreateLocalChild(*helper_.RemoteMainFrame());
+ frame_test_helpers::CreateLocalChild(*helper_.RemoteMainFrame());
Document& document = *child_frame->GetFrame()->GetDocument();
Persistent<HTMLElement> element = HTMLDivElement::Create(document);
ElementVisibilityObserver* observer =
- new ElementVisibilityObserver(element, WTF::BindRepeating([](bool) {}));
+ MakeGarbageCollected<ElementVisibilityObserver>(
+ element, WTF::BindRepeating([](bool) {}));
observer->Start();
observer->DeliverObservationsForTesting();
observer->Stop();
diff --git a/chromium/third_party/blink/renderer/core/dom/empty_node_list.h b/chromium/third_party/blink/renderer/core/dom/empty_node_list.h
index be910c0d6bf..85b73df2943 100644
--- a/chromium/third_party/blink/renderer/core/dom/empty_node_list.h
+++ b/chromium/third_party/blink/renderer/core/dom/empty_node_list.h
@@ -39,8 +39,10 @@ namespace blink {
class EmptyNodeList final : public NodeList {
public:
static EmptyNodeList* Create(Node& root_node) {
- return new EmptyNodeList(root_node);
+ return MakeGarbageCollected<EmptyNodeList>(root_node);
}
+
+ explicit EmptyNodeList(Node& root_node) : owner_(root_node) {}
~EmptyNodeList() override;
Node& OwnerNode() const { return *owner_; }
@@ -48,8 +50,6 @@ class EmptyNodeList final : public NodeList {
void Trace(blink::Visitor*) override;
private:
- explicit EmptyNodeList(Node& root_node) : owner_(root_node) {}
-
unsigned length() const override { return 0; }
Node* item(unsigned) const override { return nullptr; }
diff --git a/chromium/third_party/blink/renderer/core/dom/events/README.md b/chromium/third_party/blink/renderer/core/dom/events/README.md
new file mode 100644
index 00000000000..5b371c17e2e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/dom/events/README.md
@@ -0,0 +1,11 @@
+# DOM Events
+
+[Rendered](https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/core/dom/events/README.md)
+
+The `renderer/core/dom/events` directory contains the implementation of [DOM Events].
+
+[DOM Events]: https://dom.spec.whatwg.org/#events
+
+Please avoid to put any kind of specific event's implementation in this directory, such as [UI Events].
+
+[UI Events]: https://w3c.github.io/uievents/
diff --git a/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.cc b/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.cc
index 15e459ae093..746d8e4d995 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.cc
@@ -10,10 +10,18 @@ AddEventListenerOptionsResolved::AddEventListenerOptionsResolved()
: passive_forced_for_document_target_(false), passive_specified_(false) {}
AddEventListenerOptionsResolved::AddEventListenerOptionsResolved(
- const AddEventListenerOptions& options)
- : AddEventListenerOptions(options),
- passive_forced_for_document_target_(false),
- passive_specified_(false) {}
+ const AddEventListenerOptions* options)
+ : passive_forced_for_document_target_(false), passive_specified_(false) {
+ DCHECK(options);
+ // AddEventListenerOptions
+ if (options->hasPassive())
+ setPassive(options->passive());
+ if (options->hasOnce())
+ setOnce(options->once());
+ // EventListenerOptions
+ if (options->hasCapture())
+ setCapture(options->capture());
+}
AddEventListenerOptionsResolved::~AddEventListenerOptionsResolved() = default;
diff --git a/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.h b/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.h
index 533519827e3..fcb23b68aa8 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.h
@@ -15,11 +15,14 @@ namespace blink {
// and the result and the reasons why changes occurred are stored in this class.
class CORE_EXPORT AddEventListenerOptionsResolved
: public AddEventListenerOptions {
- DISALLOW_NEW();
-
public:
- AddEventListenerOptionsResolved();
- AddEventListenerOptionsResolved(const AddEventListenerOptions&);
+ static AddEventListenerOptionsResolved* Create() {
+ return new AddEventListenerOptionsResolved();
+ }
+ static AddEventListenerOptionsResolved* Create(
+ const AddEventListenerOptions* options) {
+ return new AddEventListenerOptionsResolved(options);
+ }
~AddEventListenerOptionsResolved() override;
void SetPassiveForcedForDocumentTarget(bool forced) {
@@ -37,6 +40,9 @@ class CORE_EXPORT AddEventListenerOptionsResolved
void Trace(blink::Visitor*) override;
private:
+ AddEventListenerOptionsResolved();
+ AddEventListenerOptionsResolved(const AddEventListenerOptions*);
+
bool passive_forced_for_document_target_;
bool passive_specified_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/events/custom_event.cc b/chromium/third_party/blink/renderer/core/dom/events/custom_event.cc
index 902d22a3f91..a5ae410abad 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/custom_event.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/custom_event.cc
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -35,12 +35,12 @@ CustomEvent::CustomEvent() = default;
CustomEvent::CustomEvent(ScriptState* script_state,
const AtomicString& type,
- const CustomEventInit& initializer)
+ const CustomEventInit* initializer)
: Event(type, initializer) {
world_ = WrapRefCounted(&script_state->World());
- if (initializer.hasDetail()) {
- detail_.Set(initializer.detail().GetIsolate(),
- initializer.detail().V8Value());
+ if (initializer->hasDetail()) {
+ detail_.Set(initializer->detail().GetIsolate(),
+ initializer->detail().V8Value());
}
}
@@ -72,7 +72,7 @@ ScriptValue CustomEvent::detail(ScriptState* script_state) const {
}
const AtomicString& CustomEvent::InterfaceName() const {
- return EventNames::CustomEvent;
+ return event_interface_names::kCustomEvent;
}
void CustomEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/dom/events/custom_event.h b/chromium/third_party/blink/renderer/core/dom/events/custom_event.h
index 72c81b2cbe2..9d2f33faac0 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/custom_event.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/custom_event.h
@@ -44,7 +44,7 @@ class CORE_EXPORT CustomEvent final : public Event {
static CustomEvent* Create(ScriptState* script_state,
const AtomicString& type,
- const CustomEventInit& initializer) {
+ const CustomEventInit* initializer) {
return new CustomEvent(script_state, type, initializer);
}
@@ -64,7 +64,7 @@ class CORE_EXPORT CustomEvent final : public Event {
CustomEvent();
CustomEvent(ScriptState*,
const AtomicString& type,
- const CustomEventInit& initializer);
+ const CustomEventInit* initializer);
scoped_refptr<DOMWrapperWorld> world_;
TraceWrapperV8Reference<v8::Value> detail_;
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event.cc b/chromium/third_party/blink/renderer/core/dom/events/event.cc
index 0239dfb8d4c..7b3b0bf7f99 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event.cc
@@ -27,6 +27,7 @@
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/dom/events/window_event_context.h"
#include "third_party/blink/renderer/core/dom/static_node_list.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/focus_event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/events/pointer_event.h"
@@ -45,16 +46,16 @@ static bool IsEventTypeScopedInV0(const AtomicString& event_type) {
// WebKit never allowed selectstart event to cross the the shadow DOM
// boundary. Changing this breaks existing sites.
// See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
- return event_type == EventTypeNames::abort ||
- event_type == EventTypeNames::change ||
- event_type == EventTypeNames::error ||
- event_type == EventTypeNames::load ||
- event_type == EventTypeNames::reset ||
- event_type == EventTypeNames::resize ||
- event_type == EventTypeNames::scroll ||
- event_type == EventTypeNames::select ||
- event_type == EventTypeNames::selectstart ||
- event_type == EventTypeNames::slotchange;
+ return event_type == event_type_names::kAbort ||
+ event_type == event_type_names::kChange ||
+ event_type == event_type_names::kError ||
+ event_type == event_type_names::kLoad ||
+ event_type == event_type_names::kReset ||
+ event_type == event_type_names::kResize ||
+ event_type == event_type_names::kScroll ||
+ event_type == event_type_names::kSelect ||
+ event_type == event_type_names::kSelectstart ||
+ event_type == event_type_names::kSlotchange;
}
Event::Event() : Event("", Bubbles::kNo, Cancelable::kNo) {
@@ -108,13 +109,13 @@ Event::Event(const AtomicString& event_type,
platform_time_stamp_(platform_time_stamp) {}
Event::Event(const AtomicString& event_type,
- const EventInit& initializer,
+ const EventInit* initializer,
TimeTicks platform_time_stamp)
: Event(event_type,
- initializer.bubbles() ? Bubbles::kYes : Bubbles::kNo,
- initializer.cancelable() ? Cancelable::kYes : Cancelable::kNo,
- initializer.composed() ? ComposedMode::kComposed
- : ComposedMode::kScoped,
+ initializer->bubbles() ? Bubbles::kYes : Bubbles::kNo,
+ initializer->cancelable() ? Cancelable::kYes : Cancelable::kNo,
+ initializer->composed() ? ComposedMode::kComposed
+ : ComposedMode::kScoped,
platform_time_stamp) {}
Event::~Event() = default;
@@ -172,7 +173,7 @@ void Event::setLegacyReturnValue(ScriptState* script_state, bool return_value) {
}
const AtomicString& Event::InterfaceName() const {
- return EventNames::Event;
+ return event_interface_names::kEvent;
}
bool Event::HasInterface(const AtomicString& name) const {
@@ -298,7 +299,7 @@ void Event::SetUnderlyingEvent(Event* ue) {
void Event::InitEventPath(Node& node) {
if (!event_path_) {
- event_path_ = new EventPath(node, this);
+ event_path_ = MakeGarbageCollected<EventPath>(node, this);
} else {
event_path_->InitializeWith(node, this);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event.h b/chromium/third_party/blink/renderer/core/dom/events/event.h
index b1229004af9..654b6faaaa0 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event.h
@@ -87,25 +87,44 @@ class CORE_EXPORT Event : public ScriptWrappable {
kPassiveDefault,
};
- static Event* Create() { return new Event; }
+ static Event* Create() { return MakeGarbageCollected<Event>(); }
static Event* Create(const AtomicString& type) {
- return new Event(type, Bubbles::kNo, Cancelable::kNo);
+ return MakeGarbageCollected<Event>(type, Bubbles::kNo, Cancelable::kNo);
}
static Event* CreateCancelable(const AtomicString& type) {
- return new Event(type, Bubbles::kNo, Cancelable::kYes);
+ return MakeGarbageCollected<Event>(type, Bubbles::kNo, Cancelable::kYes);
}
static Event* CreateBubble(const AtomicString& type) {
- return new Event(type, Bubbles::kYes, Cancelable::kNo);
+ return MakeGarbageCollected<Event>(type, Bubbles::kYes, Cancelable::kNo);
}
static Event* CreateCancelableBubble(const AtomicString& type) {
- return new Event(type, Bubbles::kYes, Cancelable::kYes);
+ return MakeGarbageCollected<Event>(type, Bubbles::kYes, Cancelable::kYes);
}
- static Event* Create(const AtomicString& type, const EventInit& initializer) {
- return new Event(type, initializer);
+ static Event* Create(const AtomicString& type, const EventInit* initializer) {
+ return MakeGarbageCollected<Event>(type, initializer);
}
+ Event();
+ Event(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ ComposedMode,
+ TimeTicks platform_time_stamp);
+ Event(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ TimeTicks platform_time_stamp);
+ Event(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ ComposedMode = ComposedMode::kScoped);
+ Event(const AtomicString& type,
+ const EventInit*,
+ TimeTicks platform_time_stamp);
+ Event(const AtomicString& type, const EventInit* init)
+ : Event(type, init, CurrentTimeTicks()) {}
~Event() override;
void initEvent(const AtomicString& type, bool bubbles, bool cancelable);
@@ -294,26 +313,6 @@ class CORE_EXPORT Event : public ScriptWrappable {
void Trace(blink::Visitor*) override;
protected:
- Event();
- Event(const AtomicString& type,
- Bubbles,
- Cancelable,
- ComposedMode,
- TimeTicks platform_time_stamp);
- Event(const AtomicString& type,
- Bubbles,
- Cancelable,
- TimeTicks platform_time_stamp);
- Event(const AtomicString& type,
- Bubbles,
- Cancelable,
- ComposedMode = ComposedMode::kScoped);
- Event(const AtomicString& type,
- const EventInit&,
- TimeTicks platform_time_stamp);
- Event(const AtomicString& type, const EventInit& init)
- : Event(type, init, CurrentTimeTicks()) {}
-
virtual void ReceivedTarget();
void SetBubbles(bool bubble) { bubbles_ = bubble; }
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_dispatcher.cc b/chromium/third_party/blink/renderer/core/dom/events/event_dispatcher.cc
index a6710b309ec..e217aa91d2d 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_dispatcher.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_dispatcher.cc
@@ -37,6 +37,7 @@
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/dom/events/window_event_context.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
+#include "third_party/blink/renderer/core/frame/ad_tracker.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
@@ -69,7 +70,7 @@ EventDispatcher::EventDispatcher(Node& node, Event& event)
void EventDispatcher::DispatchScopedEvent(Node& node, Event& event) {
// We need to set the target here because it can go away by the time we
// actually fire the event.
- event.SetTarget(EventPath::EventTargetRespectingTargetRules(node));
+ event.SetTarget(&EventPath::EventTargetRespectingTargetRules(node));
ScopedEventQueue::Instance()->EnqueueEvent(event);
}
@@ -84,7 +85,7 @@ void EventDispatcher::DispatchSimulatedClick(
// dispatchSimulatedClick().
DEFINE_STATIC_LOCAL(Persistent<HeapHashSet<Member<Node>>>,
nodes_dispatching_simulated_clicks,
- (new HeapHashSet<Member<Node>>));
+ (MakeGarbageCollected<HeapHashSet<Member<Node>>>()));
if (IsDisabledFormControl(&node))
return;
@@ -95,18 +96,18 @@ void EventDispatcher::DispatchSimulatedClick(
nodes_dispatching_simulated_clicks->insert(&node);
if (mouse_event_options == kSendMouseOverUpDownEvents)
- EventDispatcher(node, *MouseEvent::Create(EventTypeNames::mouseover,
+ EventDispatcher(node, *MouseEvent::Create(event_type_names::kMouseover,
node.GetDocument().domWindow(),
underlying_event, creation_scope))
.Dispatch();
if (mouse_event_options != kSendNoEvents) {
- EventDispatcher(node, *MouseEvent::Create(EventTypeNames::mousedown,
+ EventDispatcher(node, *MouseEvent::Create(event_type_names::kMousedown,
node.GetDocument().domWindow(),
underlying_event, creation_scope))
.Dispatch();
node.SetActive(true);
- EventDispatcher(node, *MouseEvent::Create(EventTypeNames::mouseup,
+ EventDispatcher(node, *MouseEvent::Create(event_type_names::kMouseup,
node.GetDocument().domWindow(),
underlying_event, creation_scope))
.Dispatch();
@@ -116,7 +117,7 @@ void EventDispatcher::DispatchSimulatedClick(
node.SetActive(false);
// always send click
- EventDispatcher(node, *MouseEvent::Create(EventTypeNames::click,
+ EventDispatcher(node, *MouseEvent::Create(event_type_names::kClick,
node.GetDocument().domWindow(),
underlying_event, creation_scope))
.Dispatch();
@@ -139,7 +140,7 @@ DispatchEventResult EventDispatcher::Dispatch() {
return DispatchEventResult::kNotCanceled;
}
std::unique_ptr<EventTiming> eventTiming;
- if (OriginTrials::EventTimingEnabled(&node_->GetDocument())) {
+ if (origin_trials::EventTimingEnabled(&node_->GetDocument())) {
LocalFrame* frame = node_->GetDocument().GetFrame();
if (frame && frame->DomWindow()) {
UseCounter::Count(node_->GetDocument(),
@@ -150,13 +151,29 @@ DispatchEventResult EventDispatcher::Dispatch() {
}
event_->GetEventPath().EnsureWindowEventContext();
+ const bool is_click =
+ event_->IsMouseEvent() && event_->type() == event_type_names::kClick;
+
+ if (is_click && event_->isTrusted()) {
+ Document& document = node_->GetDocument();
+ LocalFrame* frame = document.GetFrame();
+ if (frame) {
+ // A genuine mouse click cannot be triggered by script so we don't expect
+ // there are any script in the stack.
+ DCHECK(!frame->GetAdTracker() ||
+ !frame->GetAdTracker()->IsAdScriptInStack());
+ if (frame->IsAdSubframe()) {
+ UseCounter::Count(document, WebFeature::kAdClick);
+ }
+ }
+ }
+
// 6. Let isActivationEvent be true, if event is a MouseEvent object and
// event's type attribute is "click", and false otherwise.
//
// We need to include non-standard textInput event for HTMLInputElement.
const bool is_activation_event =
- (event_->IsMouseEvent() && event_->type() == EventTypeNames::click) ||
- event_->type() == EventTypeNames::textInput;
+ is_click || event_->type() == event_type_names::kTextInput;
// 7. Let activationTarget be target, if isActivationEvent is true and target
// has activation behavior, and null otherwise.
@@ -167,21 +184,21 @@ DispatchEventResult EventDispatcher::Dispatch() {
if (is_activation_event && !activation_target && event_->bubbles()) {
wtf_size_t size = event_->GetEventPath().size();
for (wtf_size_t i = 1; i < size; ++i) {
- Node* target = event_->GetEventPath()[i].GetNode();
- if (target->HasActivationBehavior()) {
- activation_target = target;
+ Node& target = event_->GetEventPath()[i].GetNode();
+ if (target.HasActivationBehavior()) {
+ activation_target = &target;
break;
}
}
}
- event_->SetTarget(EventPath::EventTargetRespectingTargetRules(*node_));
+ event_->SetTarget(&EventPath::EventTargetRespectingTargetRules(*node_));
#if DCHECK_IS_ON()
DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
DCHECK(event_->target());
TRACE_EVENT1("devtools.timeline", "EventDispatch", "data",
- InspectorEventDispatchEvent::Data(*event_));
+ inspector_event_dispatch_event::Data(*event_));
EventDispatchHandlingState* pre_dispatch_event_handler_result = nullptr;
if (DispatchEventPreProcess(activation_target,
pre_dispatch_event_handler_result) ==
@@ -289,7 +306,7 @@ inline void EventDispatcher::DispatchEventAtBubbling() {
inline void EventDispatcher::DispatchEventPostProcess(
Node* activation_target,
EventDispatchHandlingState* pre_dispatch_event_handler_result) {
- event_->SetTarget(EventPath::EventTargetRespectingTargetRules(*node_));
+ event_->SetTarget(&EventPath::EventTargetRespectingTargetRules(*node_));
// https://dom.spec.whatwg.org/#concept-event-dispatch
// 14. Unset event’s dispatch flag, stop propagation flag, and stop immediate
// propagation flag.
@@ -302,7 +319,7 @@ inline void EventDispatcher::DispatchEventPostProcess(
event_->SetCurrentTarget(nullptr);
bool is_click = event_->IsMouseEvent() &&
- ToMouseEvent(*event_).type() == EventTypeNames::click;
+ ToMouseEvent(*event_).type() == event_type_names::kClick;
if (is_click) {
// Fire an accessibility event indicating a node was clicked on. This is
// safe if event_->target()->ToNode() returns null.
@@ -331,7 +348,7 @@ inline void EventDispatcher::DispatchEventPostProcess(
// fastclick.js seems to generate these. crbug.com/642698
// TODO(dtapuska): Change this to a target SDK quirk crbug.com/643705
if (!is_trusted_or_click && event_->IsMouseEvent() &&
- event_->type() == EventTypeNames::mousedown &&
+ event_->type() == event_type_names::kMousedown &&
IsHTMLSelectElement(*node_)) {
if (Settings* settings = node_->GetDocument().GetSettings()) {
is_trusted_or_click = settings->GetWideViewportQuirkEnabled();
@@ -353,9 +370,9 @@ inline void EventDispatcher::DispatchEventPostProcess(
if (!event_->DefaultHandled() && event_->bubbles()) {
wtf_size_t size = event_->GetEventPath().size();
for (wtf_size_t i = 1; i < size; ++i) {
- event_->GetEventPath()[i].GetNode()->WillCallDefaultEventHandler(
+ event_->GetEventPath()[i].GetNode().WillCallDefaultEventHandler(
*event_);
- event_->GetEventPath()[i].GetNode()->DefaultEventHandler(*event_);
+ event_->GetEventPath()[i].GetNode().DefaultEventHandler(*event_);
DCHECK(!event_->defaultPrevented());
if (event_->DefaultHandled())
break;
@@ -367,7 +384,7 @@ inline void EventDispatcher::DispatchEventPostProcess(
// it to open. This measures a possible breakage of not allowing untrusted
// events to open select boxes.
if (!event_->isTrusted() && event_->IsMouseEvent() &&
- event_->type() == EventTypeNames::mousedown &&
+ event_->type() == event_type_names::kMousedown &&
IsHTMLSelectElement(*node_)) {
UseCounter::Count(node_->GetDocument(),
WebFeature::kUntrustedMouseDownEventDispatchedToSelect);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_listener.h b/chromium/third_party/blink/renderer/core/dom/events/event_listener.h
index d658c3c82b4..b5b2e7449db 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_listener.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_listener.h
@@ -47,15 +47,29 @@ class CORE_EXPORT EventListener : public CustomWrappableAdapter {
kConditionEventListenerType,
};
+ explicit EventListener(ListenerType type) : type_(type) {}
~EventListener() override = default;
- virtual bool operator==(const EventListener&) const = 0;
- virtual void handleEvent(ExecutionContext*, Event*) = 0;
- virtual const String& Code() const { return g_empty_string; }
+
+ // Invokes this event listener.
+ virtual void Invoke(ExecutionContext*, Event*) = 0;
+
+ // Returns true if this implements IDL EventHandler family.
+ virtual bool IsEventHandler() const { return false; }
+
+ // Returns true if this implements IDL EventHandler family and the value is
+ // a content attribute (or compiled from a content attribute).
virtual bool IsEventHandlerForContentAttribute() const { return false; }
+
+ // Returns an uncompiled script body.
+ // https://html.spec.whatwg.org/C/webappapis.html#internal-raw-uncompiled-handler
+ virtual const String& ScriptBody() const { return g_empty_string; }
+
+ // Returns true if this event listener was created in the current world.
virtual bool BelongsToTheCurrentWorld(ExecutionContext*) const {
return false;
}
- virtual bool IsEventHandler() const { return false; }
+
+ virtual bool operator==(const EventListener&) const = 0;
ListenerType GetType() const { return type_; }
@@ -69,9 +83,6 @@ class CORE_EXPORT EventListener : public CustomWrappableAdapter {
const char* NameInHeapSnapshot() const override { return "EventListener"; }
- protected:
- explicit EventListener(ListenerType type) : type_(type) {}
-
private:
ListenerType type_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.cc b/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.cc
index de300766682..f508802ea06 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.cc
@@ -97,7 +97,7 @@ Vector<AtomicString> EventListenerMap::EventTypes() const {
static bool AddListenerToVector(EventListenerVector* vector,
EventListener* listener,
- const AddEventListenerOptionsResolved& options,
+ const AddEventListenerOptionsResolved* options,
RegisteredEventListener* registered_listener) {
*registered_listener = RegisteredEventListener(listener, options);
@@ -110,7 +110,7 @@ static bool AddListenerToVector(EventListenerVector* vector,
bool EventListenerMap::Add(const AtomicString& event_type,
EventListener* listener,
- const AddEventListenerOptionsResolved& options,
+ const AddEventListenerOptionsResolved* options,
RegisteredEventListener* registered_listener) {
CheckNoActiveIterators();
@@ -120,7 +120,8 @@ bool EventListenerMap::Add(const AtomicString& event_type,
registered_listener);
}
- entries_.push_back(std::make_pair(event_type, new EventListenerVector));
+ entries_.push_back(
+ std::make_pair(event_type, MakeGarbageCollected<EventListenerVector>()));
return AddListenerToVector(entries_.back().second.Get(), listener, options,
registered_listener);
}
@@ -128,7 +129,7 @@ bool EventListenerMap::Add(const AtomicString& event_type,
static bool RemoveListenerFromVector(
EventListenerVector* listener_vector,
const EventListener* listener,
- const EventListenerOptions& options,
+ const EventListenerOptions* options,
wtf_size_t* index_of_removed_listener,
RegisteredEventListener* registered_listener) {
auto* const begin = listener_vector->data();
@@ -154,7 +155,7 @@ static bool RemoveListenerFromVector(
bool EventListenerMap::Remove(const AtomicString& event_type,
const EventListener* listener,
- const EventListenerOptions& options,
+ const EventListenerOptions* options,
wtf_size_t* index_of_removed_listener,
RegisteredEventListener* registered_listener) {
CheckNoActiveIterators();
@@ -191,7 +192,7 @@ static void CopyListenersNotCreatedFromMarkupToTarget(
for (auto& event_listener : *listener_vector) {
if (event_listener.Callback()->IsEventHandlerForContentAttribute())
continue;
- AddEventListenerOptionsResolved options = event_listener.Options();
+ AddEventListenerOptionsResolved* options = event_listener.Options();
target->addEventListener(event_type, event_listener.Callback(), options);
}
}
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.h b/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.h
index d2ee92dac25..57da2d12a25 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_listener_map.h
@@ -60,11 +60,11 @@ class CORE_EXPORT EventListenerMap final {
void Clear();
bool Add(const AtomicString& event_type,
EventListener*,
- const AddEventListenerOptionsResolved&,
+ const AddEventListenerOptionsResolved*,
RegisteredEventListener* registered_listener);
bool Remove(const AtomicString& event_type,
const EventListener*,
- const EventListenerOptions&,
+ const EventListenerOptions*,
wtf_size_t* index_of_removed_listener,
RegisteredEventListener* registered_listener);
EventListenerVector* Find(const AtomicString& event_type);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_path.cc b/chromium/third_party/blink/renderer/core/dom/events/event_path.cc
index b5f52b1b952..a353eb91562 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_path.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_path.cc
@@ -30,7 +30,6 @@
#include "third_party/blink/renderer/core/dom/events/window_event_context.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/v0_insertion_point.h"
-#include "third_party/blink/renderer/core/event_names.h"
#include "third_party/blink/renderer/core/events/touch_event.h"
#include "third_party/blink/renderer/core/events/touch_event_context.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
@@ -39,13 +38,13 @@
namespace blink {
-EventTarget* EventPath::EventTargetRespectingTargetRules(Node& reference_node) {
+EventTarget& EventPath::EventTargetRespectingTargetRules(Node& reference_node) {
if (reference_node.IsPseudoElement()) {
DCHECK(reference_node.parentNode());
- return reference_node.parentNode();
+ return *reference_node.parentNode();
}
- return &reference_node;
+ return reference_node;
}
static inline bool ShouldStopAtShadowRoot(Event& event,
@@ -134,8 +133,9 @@ void EventPath::CalculatePath() {
node_event_contexts_.ReserveCapacity(nodes_in_path.size());
for (Node* node_in_path : nodes_in_path) {
+ DCHECK(node_in_path);
node_event_contexts_.push_back(NodeEventContext(
- node_in_path, EventTargetRespectingTargetRules(*node_in_path)));
+ *node_in_path, EventTargetRespectingTargetRules(*node_in_path)));
}
}
@@ -154,7 +154,7 @@ void EventPath::CalculateTreeOrderAndSetNearestAncestorClosedTree() {
continue;
}
TreeScopeEventContext* parent_tree_scope_event_context =
- GetTreeScopeEventContext(parent);
+ GetTreeScopeEventContext(*parent);
DCHECK(parent_tree_scope_event_context);
parent_tree_scope_event_context->AddChild(*tree_scope_event_context.Get());
}
@@ -163,8 +163,7 @@ void EventPath::CalculateTreeOrderAndSetNearestAncestorClosedTree() {
}
TreeScopeEventContext* EventPath::GetTreeScopeEventContext(
- TreeScope* tree_scope) {
- DCHECK(tree_scope);
+ TreeScope& tree_scope) {
for (TreeScopeEventContext* tree_scope_event_context :
tree_scope_event_contexts_) {
if (tree_scope_event_context->GetTreeScope() == tree_scope) {
@@ -180,7 +179,7 @@ TreeScopeEventContext* EventPath::EnsureTreeScopeEventContext(
if (!tree_scope)
return nullptr;
TreeScopeEventContext* tree_scope_event_context =
- GetTreeScopeEventContext(tree_scope);
+ GetTreeScopeEventContext(*tree_scope);
if (!tree_scope_event_context) {
tree_scope_event_context = TreeScopeEventContext::Create(*tree_scope);
tree_scope_event_contexts_.push_back(tree_scope_event_context);
@@ -190,7 +189,7 @@ TreeScopeEventContext* EventPath::EnsureTreeScopeEventContext(
if (parent_tree_scope_event_context &&
parent_tree_scope_event_context->Target()) {
tree_scope_event_context->SetTarget(
- parent_tree_scope_event_context->Target());
+ *parent_tree_scope_event_context->Target());
} else if (current_target) {
tree_scope_event_context->SetTarget(
EventTargetRespectingTargetRules(*current_target));
@@ -207,11 +206,11 @@ void EventPath::CalculateAdjustedTargets() {
TreeScopeEventContext* last_tree_scope_event_context = nullptr;
for (auto& context : node_event_contexts_) {
- Node* current_node = context.GetNode();
- TreeScope& current_tree_scope = current_node->GetTreeScope();
+ Node& current_node = context.GetNode();
+ TreeScope& current_tree_scope = current_node.GetTreeScope();
if (last_tree_scope != &current_tree_scope) {
last_tree_scope_event_context =
- EnsureTreeScopeEventContext(current_node, &current_tree_scope);
+ EnsureTreeScopeEventContext(&current_node, &current_tree_scope);
}
DCHECK(last_tree_scope_event_context);
context.SetTreeScopeEventContext(last_tree_scope_event_context);
@@ -222,7 +221,7 @@ void EventPath::CalculateAdjustedTargets() {
void EventPath::BuildRelatedNodeMap(const Node& related_node,
RelatedTargetMap& related_target_map) {
EventPath* related_target_event_path =
- new EventPath(const_cast<Node&>(related_node));
+ MakeGarbageCollected<EventPath>(const_cast<Node&>(related_node));
for (const auto& tree_scope_event_context :
related_target_event_path->tree_scope_event_contexts_) {
related_target_map.insert(&tree_scope_event_context->GetTreeScope(),
@@ -274,7 +273,7 @@ void EventPath::RetargetRelatedTarget(const Node& related_target_node) {
EventTarget* adjusted_related_target = FindRelatedNode(
tree_scope_event_context->GetTreeScope(), related_node_map);
DCHECK(adjusted_related_target);
- tree_scope_event_context.Get()->SetRelatedTarget(adjusted_related_target);
+ tree_scope_event_context.Get()->SetRelatedTarget(*adjusted_related_target);
}
}
@@ -307,7 +306,7 @@ bool ShouldStopEventPath(EventTarget& adjusted_target,
void EventPath::ShrinkForRelatedTarget(const Node& event_target_node,
const Node& event_related_target_node) {
for (wtf_size_t i = 0; i < size(); ++i) {
- if (ShouldStopEventPath(*at(i).Target(), *at(i).RelatedTarget(),
+ if (ShouldStopEventPath(*(*this)[i].Target(), *(*this)[i].RelatedTarget(),
event_target_node, event_related_target_node)) {
Shrink(i);
break;
@@ -323,11 +322,11 @@ void EventPath::AdjustForTouchEvent(const TouchEvent& touch_event) {
HeapVector<Member<TreeScope>> tree_scopes;
for (const auto& tree_scope_event_context : tree_scope_event_contexts_) {
- TouchEventContext* touch_event_context =
+ TouchEventContext& touch_event_context =
tree_scope_event_context->EnsureTouchEventContext();
- adjusted_touches.push_back(&touch_event_context->Touches());
- adjusted_target_touches.push_back(&touch_event_context->TargetTouches());
- adjusted_changed_touches.push_back(&touch_event_context->ChangedTouches());
+ adjusted_touches.push_back(&touch_event_context.Touches());
+ adjusted_target_touches.push_back(&touch_event_context.TargetTouches());
+ adjusted_changed_touches.push_back(&touch_event_context.ChangedTouches());
tree_scopes.push_back(&tree_scope_event_context->GetTreeScope());
}
@@ -378,8 +377,7 @@ void EventPath::AdjustTouchList(
bool EventPath::DisabledFormControlExistsInPath() const {
for (const auto& context : node_event_contexts_) {
- const Node* target_node = context.GetNode();
- if (target_node && IsDisabledFormControl(target_node))
+ if (IsDisabledFormControl(&context.GetNode()))
return true;
}
return false;
@@ -387,8 +385,7 @@ bool EventPath::DisabledFormControlExistsInPath() const {
bool EventPath::HasEventListenersInPath(const AtomicString& event_type) const {
for (const auto& context : node_event_contexts_) {
- const Node* target_node = context.GetNode();
- if (target_node && target_node->HasEventListeners(event_type))
+ if (context.GetNode().HasEventListeners(event_type))
return true;
}
return false;
@@ -401,9 +398,10 @@ NodeEventContext& EventPath::TopNodeEventContext() {
void EventPath::EnsureWindowEventContext() {
DCHECK(event_);
- if (!window_event_context_)
- window_event_context_ =
- new WindowEventContext(*event_, TopNodeEventContext());
+ if (!window_event_context_) {
+ window_event_context_ = MakeGarbageCollected<WindowEventContext>(
+ *event_, TopNodeEventContext());
+ }
}
#if DCHECK_IS_ON()
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_path.h b/chromium/third_party/blink/renderer/core/dom/events/event_path.h
index 8dc3a5a0459..be0d71d2c43 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_path.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_path.h
@@ -62,7 +62,6 @@ class CORE_EXPORT EventPath final
const NodeEventContext& operator[](wtf_size_t index) const {
return node_event_contexts_[index];
}
- NodeEventContext& at(wtf_size_t index) { return node_event_contexts_[index]; }
NodeEventContext& Last() { return node_event_contexts_[size() - 1]; }
WindowEventContext& GetWindowEventContext() {
@@ -82,7 +81,7 @@ class CORE_EXPORT EventPath final
NodeEventContext& TopNodeEventContext();
- static EventTarget* EventTargetRespectingTargetRules(Node&);
+ static EventTarget& EventTargetRespectingTargetRules(Node&);
void Trace(blink::Visitor*);
void Clear() {
@@ -112,7 +111,7 @@ class CORE_EXPORT EventPath final
HeapVector<Member<TouchList>> adjusted_touch_list,
const HeapVector<Member<TreeScope>>& tree_scopes);
- TreeScopeEventContext* GetTreeScopeEventContext(TreeScope*);
+ TreeScopeEventContext* GetTreeScopeEventContext(TreeScope&);
TreeScopeEventContext* EnsureTreeScopeEventContext(Node* current_target,
TreeScope*);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_path_test.cc b/chromium/third_party/blink/renderer/core/dom/events/event_path_test.cc
index a405a3a1ff7..6f3b6dc0300 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_path_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_path_test.cc
@@ -18,7 +18,7 @@ class EventPathTest : public PageTestBase {};
TEST_F(EventPathTest, ShouldBeEmptyForPseudoElementWithoutParentElement) {
Element* div = GetDocument().CreateRawElement(
- HTMLNames::divTag, CreateElementFlags::ByCreateElement());
+ html_names::kDivTag, CreateElementFlags::ByCreateElement());
PseudoElement* pseudo = PseudoElement::Create(div, kPseudoIdFirstLetter);
pseudo->Dispose();
EventPath event_path(*pseudo);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_queue.cc b/chromium/third_party/blink/renderer/core/dom/events/event_queue.cc
index 78bea34c911..55abadf355f 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_queue.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_queue.cc
@@ -35,7 +35,7 @@
namespace blink {
EventQueue* EventQueue::Create(ExecutionContext* context, TaskType task_type) {
- return new EventQueue(context, task_type);
+ return MakeGarbageCollected<EventQueue>(context, task_type);
}
EventQueue::EventQueue(ExecutionContext* context, TaskType task_type)
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_queue.h b/chromium/third_party/blink/renderer/core/dom/events/event_queue.h
index 1906634e688..a1ecfb3d427 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_queue.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_queue.h
@@ -43,6 +43,8 @@ class CORE_EXPORT EventQueue final
public:
static EventQueue* Create(ExecutionContext*, TaskType);
+
+ EventQueue(ExecutionContext*, TaskType);
~EventQueue();
void Trace(blink::Visitor*) override;
@@ -51,8 +53,6 @@ class CORE_EXPORT EventQueue final
bool HasPendingEvents() const;
private:
- EventQueue(ExecutionContext*, TaskType);
-
bool RemoveEvent(Event&);
void DispatchEvent(Event*);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_target.cc b/chromium/third_party/blink/renderer/core/dom/events/event_target.cc
index a8f3eb98f6a..42faeb2a461 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_target.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_target.cc
@@ -93,13 +93,13 @@ Settings* WindowSettings(LocalDOMWindow* executing_window) {
}
bool IsTouchScrollBlockingEvent(const AtomicString& event_type) {
- return event_type == EventTypeNames::touchstart ||
- event_type == EventTypeNames::touchmove;
+ return event_type == event_type_names::kTouchstart ||
+ event_type == event_type_names::kTouchmove;
}
bool IsWheelScrollBlockingEvent(const AtomicString& event_type) {
- return event_type == EventTypeNames::mousewheel ||
- event_type == EventTypeNames::wheel;
+ return event_type == event_type_names::kMousewheel ||
+ event_type == event_type_names::kWheel;
}
bool IsScrollBlockingEvent(const AtomicString& event_type) {
@@ -108,8 +108,8 @@ bool IsScrollBlockingEvent(const AtomicString& event_type) {
}
bool IsInstrumentedForAsyncStack(const AtomicString& event_type) {
- return event_type == EventTypeNames::load ||
- event_type == EventTypeNames::error;
+ return event_type == event_type_names::kLoad ||
+ event_type == event_type_names::kError;
}
base::TimeDelta BlockedEventsWarningThreshold(ExecutionContext* context,
@@ -231,20 +231,20 @@ bool EventTarget::IsTopLevelNode() {
void EventTarget::SetDefaultAddEventListenerOptions(
const AtomicString& event_type,
EventListener* event_listener,
- AddEventListenerOptionsResolved& options) {
- options.SetPassiveSpecified(options.hasPassive());
+ AddEventListenerOptionsResolved* options) {
+ options->SetPassiveSpecified(options->hasPassive());
if (!IsScrollBlockingEvent(event_type)) {
- if (!options.hasPassive())
- options.setPassive(false);
+ if (!options->hasPassive())
+ options->setPassive(false);
return;
}
LocalDOMWindow* executing_window = ExecutingWindow();
if (executing_window) {
- if (options.hasPassive()) {
+ if (options->hasPassive()) {
UseCounter::Count(executing_window->document(),
- options.passive()
+ options->passive()
? WebFeature::kAddEventListenerPassiveTrue
: WebFeature::kAddEventListenerPassiveFalse);
}
@@ -252,31 +252,31 @@ void EventTarget::SetDefaultAddEventListenerOptions(
if (RuntimeEnabledFeatures::PassiveDocumentEventListenersEnabled() &&
IsTouchScrollBlockingEvent(event_type)) {
- if (!options.hasPassive() && IsTopLevelNode()) {
- options.setPassive(true);
- options.SetPassiveForcedForDocumentTarget(true);
+ if (!options->hasPassive() && IsTopLevelNode()) {
+ options->setPassive(true);
+ options->SetPassiveForcedForDocumentTarget(true);
return;
}
}
if (IsWheelScrollBlockingEvent(event_type) && IsTopLevelNode()) {
- if (options.hasPassive()) {
+ if (options->hasPassive()) {
if (executing_window) {
UseCounter::Count(
executing_window->document(),
- options.passive()
+ options->passive()
? WebFeature::kAddDocumentLevelPassiveTrueWheelEventListener
: WebFeature::kAddDocumentLevelPassiveFalseWheelEventListener);
}
- } else { // !options.hasPassive()
+ } else { // !options->hasPassive()
if (executing_window) {
UseCounter::Count(
executing_window->document(),
WebFeature::kAddDocumentLevelPassiveDefaultWheelEventListener);
}
if (RuntimeEnabledFeatures::PassiveDocumentWheelEventListenersEnabled()) {
- options.setPassive(true);
- options.SetPassiveForcedForDocumentTarget(true);
+ options->setPassive(true);
+ options->SetPassiveForcedForDocumentTarget(true);
return;
}
}
@@ -286,8 +286,8 @@ void EventTarget::SetDefaultAddEventListenerOptions(
// a bound function name of "ssc_wheel" treat and no passive value default
// passive to true. See crbug.com/501568.
if (RuntimeEnabledFeatures::SmoothScrollJSInterventionEnabled() &&
- event_type == EventTypeNames::mousewheel && ToLocalDOMWindow() &&
- event_listener && !options.hasPassive()) {
+ event_type == event_type_names::kMousewheel && ToLocalDOMWindow() &&
+ event_listener && !options->hasPassive()) {
JSBasedEventListener* v8_listener =
JSBasedEventListener::Cast(event_listener);
if (!v8_listener)
@@ -301,7 +301,7 @@ void EventTarget::SetDefaultAddEventListenerOptions(
v8::Isolate::GetCurrent(),
v8::Local<v8::Function>::Cast(callback_object)->GetName())) ==
0) {
- options.setPassive(true);
+ options->setPassive(true);
if (executing_window) {
UseCounter::Count(executing_window->document(),
WebFeature::kSmoothScrollJSInterventionActivated);
@@ -321,23 +321,23 @@ void EventTarget::SetDefaultAddEventListenerOptions(
if (Settings* settings = WindowSettings(ExecutingWindow())) {
switch (settings->GetPassiveListenerDefault()) {
case PassiveListenerDefault::kFalse:
- if (!options.hasPassive())
- options.setPassive(false);
+ if (!options->hasPassive())
+ options->setPassive(false);
break;
case PassiveListenerDefault::kTrue:
- if (!options.hasPassive())
- options.setPassive(true);
+ if (!options->hasPassive())
+ options->setPassive(true);
break;
case PassiveListenerDefault::kForceAllTrue:
- options.setPassive(true);
+ options->setPassive(true);
break;
}
} else {
- if (!options.hasPassive())
- options.setPassive(false);
+ if (!options->hasPassive())
+ options->setPassive(false);
}
- if (!options.passive() && !options.PassiveSpecified()) {
+ if (!options->passive() && !options->PassiveSpecified()) {
String message_text = String::Format(
"Added non-passive event listener to a scroll-blocking '%s' event. "
"Consider marking event handler as 'passive' to make the page more "
@@ -354,8 +354,9 @@ void EventTarget::SetDefaultAddEventListenerOptions(
bool EventTarget::addEventListener(const AtomicString& event_type,
EventListener* listener,
bool use_capture) {
- AddEventListenerOptionsResolved options;
- options.setCapture(use_capture);
+ AddEventListenerOptionsResolved* options =
+ AddEventListenerOptionsResolved::Create();
+ options->setCapture(use_capture);
SetDefaultAddEventListenerOptions(event_type, listener, options);
return AddEventListenerInternal(event_type, listener, options);
}
@@ -367,16 +368,24 @@ bool EventTarget::addEventListener(
if (options_union.IsBoolean())
return addEventListener(event_type, listener, options_union.GetAsBoolean());
if (options_union.IsAddEventListenerOptions()) {
- AddEventListenerOptionsResolved options =
+ AddEventListenerOptionsResolved* resolved_options =
+ AddEventListenerOptionsResolved::Create();
+ AddEventListenerOptions* options =
options_union.GetAsAddEventListenerOptions();
- return addEventListener(event_type, listener, options);
+ if (options->hasPassive())
+ resolved_options->setPassive(options->passive());
+ if (options->hasOnce())
+ resolved_options->setOnce(options->once());
+ if (options->hasCapture())
+ resolved_options->setCapture(options->capture());
+ return addEventListener(event_type, listener, resolved_options);
}
return addEventListener(event_type, listener);
}
bool EventTarget::addEventListener(const AtomicString& event_type,
EventListener* listener,
- AddEventListenerOptionsResolved& options) {
+ AddEventListenerOptionsResolved* options) {
SetDefaultAddEventListenerOptions(event_type, listener, options);
return AddEventListenerInternal(event_type, listener, options);
}
@@ -384,7 +393,7 @@ bool EventTarget::addEventListener(const AtomicString& event_type,
bool EventTarget::AddEventListenerInternal(
const AtomicString& event_type,
EventListener* listener,
- const AddEventListenerOptionsResolved& options) {
+ const AddEventListenerOptionsResolved* options) {
if (!listener)
return false;
@@ -415,17 +424,17 @@ void EventTarget::AddedEventListener(
RegisteredEventListener& registered_listener) {
if (const LocalDOMWindow* executing_window = ExecutingWindow()) {
if (const Document* document = executing_window->document()) {
- if (event_type == EventTypeNames::auxclick)
+ if (event_type == event_type_names::kAuxclick)
UseCounter::Count(*document, WebFeature::kAuxclickAddListenerCount);
- else if (event_type == EventTypeNames::appinstalled)
+ else if (event_type == event_type_names::kAppinstalled)
UseCounter::Count(*document, WebFeature::kAppInstalledEventAddListener);
- else if (EventUtil::IsPointerEventType(event_type))
+ else if (event_util::IsPointerEventType(event_type))
UseCounter::Count(*document, WebFeature::kPointerEventAddListenerCount);
- else if (event_type == EventTypeNames::slotchange)
+ else if (event_type == event_type_names::kSlotchange)
UseCounter::Count(*document, WebFeature::kSlotChangeEventAddListener);
}
}
- if (EventUtil::IsDOMMutationEventType(event_type)) {
+ if (event_util::IsDOMMutationEventType(event_type)) {
if (ExecutionContext* context = GetExecutionContext()) {
String message_text = String::Format(
"Added synchronous DOM mutation listener to a '%s' event. "
@@ -441,8 +450,8 @@ void EventTarget::AddedEventListener(
bool EventTarget::removeEventListener(const AtomicString& event_type,
const EventListener* listener,
bool use_capture) {
- EventListenerOptions options;
- options.setCapture(use_capture);
+ EventListenerOptions* options = EventListenerOptions::Create();
+ options->setCapture(use_capture);
return RemoveEventListenerInternal(event_type, listener, options);
}
@@ -455,7 +464,7 @@ bool EventTarget::removeEventListener(
options_union.GetAsBoolean());
}
if (options_union.IsEventListenerOptions()) {
- EventListenerOptions options = options_union.GetAsEventListenerOptions();
+ EventListenerOptions* options = options_union.GetAsEventListenerOptions();
return removeEventListener(event_type, listener, options);
}
return removeEventListener(event_type, listener);
@@ -463,14 +472,14 @@ bool EventTarget::removeEventListener(
bool EventTarget::removeEventListener(const AtomicString& event_type,
const EventListener* listener,
- EventListenerOptions& options) {
+ EventListenerOptions* options) {
return RemoveEventListenerInternal(event_type, listener, options);
}
bool EventTarget::RemoveEventListenerInternal(
const AtomicString& event_type,
const EventListener* listener,
- const EventListenerOptions& options) {
+ const EventListenerOptions* options) {
if (!listener)
return false;
@@ -596,20 +605,20 @@ DispatchEventResult EventTarget::DispatchEventInternal(Event& event) {
}
static const AtomicString& LegacyType(const Event& event) {
- if (event.type() == EventTypeNames::transitionend)
- return EventTypeNames::webkitTransitionEnd;
+ if (event.type() == event_type_names::kTransitionend)
+ return event_type_names::kWebkitTransitionEnd;
- if (event.type() == EventTypeNames::animationstart)
- return EventTypeNames::webkitAnimationStart;
+ if (event.type() == event_type_names::kAnimationstart)
+ return event_type_names::kWebkitAnimationStart;
- if (event.type() == EventTypeNames::animationend)
- return EventTypeNames::webkitAnimationEnd;
+ if (event.type() == event_type_names::kAnimationend)
+ return event_type_names::kWebkitAnimationEnd;
- if (event.type() == EventTypeNames::animationiteration)
- return EventTypeNames::webkitAnimationIteration;
+ if (event.type() == event_type_names::kAnimationiteration)
+ return event_type_names::kWebkitAnimationIteration;
- if (event.type() == EventTypeNames::wheel)
- return EventTypeNames::mousewheel;
+ if (event.type() == event_type_names::kWheel)
+ return event_type_names::kMousewheel;
return g_empty_atom;
}
@@ -621,27 +630,27 @@ void EventTarget::CountLegacyEvents(
WebFeature unprefixed_feature;
WebFeature prefixed_feature;
WebFeature prefixed_and_unprefixed_feature;
- if (legacy_type_name == EventTypeNames::webkitTransitionEnd) {
+ if (legacy_type_name == event_type_names::kWebkitTransitionEnd) {
prefixed_feature = WebFeature::kPrefixedTransitionEndEvent;
unprefixed_feature = WebFeature::kUnprefixedTransitionEndEvent;
prefixed_and_unprefixed_feature =
WebFeature::kPrefixedAndUnprefixedTransitionEndEvent;
- } else if (legacy_type_name == EventTypeNames::webkitAnimationEnd) {
+ } else if (legacy_type_name == event_type_names::kWebkitAnimationEnd) {
prefixed_feature = WebFeature::kPrefixedAnimationEndEvent;
unprefixed_feature = WebFeature::kUnprefixedAnimationEndEvent;
prefixed_and_unprefixed_feature =
WebFeature::kPrefixedAndUnprefixedAnimationEndEvent;
- } else if (legacy_type_name == EventTypeNames::webkitAnimationStart) {
+ } else if (legacy_type_name == event_type_names::kWebkitAnimationStart) {
prefixed_feature = WebFeature::kPrefixedAnimationStartEvent;
unprefixed_feature = WebFeature::kUnprefixedAnimationStartEvent;
prefixed_and_unprefixed_feature =
WebFeature::kPrefixedAndUnprefixedAnimationStartEvent;
- } else if (legacy_type_name == EventTypeNames::webkitAnimationIteration) {
+ } else if (legacy_type_name == event_type_names::kWebkitAnimationIteration) {
prefixed_feature = WebFeature::kPrefixedAnimationIterationEvent;
unprefixed_feature = WebFeature::kUnprefixedAnimationIterationEvent;
prefixed_and_unprefixed_feature =
WebFeature::kPrefixedAndUnprefixedAnimationIterationEvent;
- } else if (legacy_type_name == EventTypeNames::mousewheel) {
+ } else if (legacy_type_name == event_type_names::kMousewheel) {
prefixed_feature = WebFeature::kMouseWheelEvent;
unprefixed_feature = WebFeature::kWheelEvent;
prefixed_and_unprefixed_feature = WebFeature::kMouseWheelAndWheelEvent;
@@ -715,66 +724,66 @@ bool EventTarget::FireEventListeners(Event& event,
// excludes new event listeners.
if (const LocalDOMWindow* executing_window = ExecutingWindow()) {
if (const Document* document = executing_window->document()) {
- if (CheckTypeThenUseCount(event, EventTypeNames::beforeunload,
+ if (CheckTypeThenUseCount(event, event_type_names::kBeforeunload,
WebFeature::kDocumentBeforeUnloadFired,
document)) {
if (executing_window != executing_window->top())
UseCounter::Count(*document, WebFeature::kSubFrameBeforeUnloadFired);
- } else if (CheckTypeThenUseCount(event, EventTypeNames::unload,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kUnload,
WebFeature::kDocumentUnloadFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pagehide,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPagehide,
WebFeature::kDocumentPageHideFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pageshow,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPageshow,
WebFeature::kDocumentPageShowFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::DOMFocusIn,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kDOMFocusIn,
WebFeature::kDOMFocusInOutEvent,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::DOMFocusOut,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kDOMFocusOut,
WebFeature::kDOMFocusInOutEvent,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::focusin,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kFocusin,
WebFeature::kFocusInOutEvent,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::focusout,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kFocusout,
WebFeature::kFocusInOutEvent,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::textInput,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kTextInput,
WebFeature::kTextInputFired, document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::touchstart,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kTouchstart,
WebFeature::kTouchStartFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::mousedown,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kMousedown,
WebFeature::kMouseDownFired, document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerdown,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPointerdown,
WebFeature::kPointerDownFired,
document)) {
if (event.IsPointerEvent() &&
static_cast<PointerEvent&>(event).pointerType() == "touch") {
UseCounter::Count(*document, WebFeature::kPointerDownFiredForTouch);
}
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerenter,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPointerenter,
WebFeature::kPointerEnterLeaveFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerleave,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPointerleave,
WebFeature::kPointerEnterLeaveFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerover,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPointerover,
WebFeature::kPointerOverOutFired,
document)) {
- } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerout,
+ } else if (CheckTypeThenUseCount(event, event_type_names::kPointerout,
WebFeature::kPointerOverOutFired,
document)) {
} else if (event.eventPhase() == Event::kCapturingPhase ||
event.eventPhase() == Event::kBubblingPhase) {
if (CheckTypeThenUseCount(
- event, EventTypeNames::DOMNodeRemoved,
+ event, event_type_names::kDOMNodeRemoved,
WebFeature::kDOMNodeRemovedEventListenedAtNonTarget,
document)) {
} else if (CheckTypeThenUseCount(
- event, EventTypeNames::DOMNodeRemovedFromDocument,
+ event, event_type_names::kDOMNodeRemovedFromDocument,
WebFeature::
kDOMNodeRemovedFromDocumentEventListenedAtNonTarget,
document)) {
@@ -838,7 +847,7 @@ bool EventTarget::FireEventListeners(Event& event,
// To match Mozilla, the AT_TARGET phase fires both capturing and bubbling
// event listeners, even though that violates some versions of the DOM spec.
- listener->handleEvent(context, &event);
+ listener->Invoke(context, &event);
fired_listener = true;
// If we're about to report this event listener as blocking, make sure it
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_target.h b/chromium/third_party/blink/renderer/core/dom/events/event_target.h
index f9e4fc6c8f4..69d0db56ec5 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_target.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_target.h
@@ -40,7 +40,6 @@
#include "third_party/blink/renderer/core/dom/events/add_event_listener_options_resolved.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_result.h"
#include "third_party/blink/renderer/core/dom/events/event_listener_map.h"
-#include "third_party/blink/renderer/core/event_names.h"
#include "third_party/blink/renderer/core/event_target_names.h"
#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
@@ -141,7 +140,7 @@ class CORE_EXPORT EventTarget : public ScriptWrappable {
const AddEventListenerOptionsOrBoolean&);
bool addEventListener(const AtomicString& event_type,
EventListener*,
- AddEventListenerOptionsResolved&);
+ AddEventListenerOptionsResolved*);
bool removeEventListener(const AtomicString& event_type,
const EventListener*,
@@ -151,7 +150,7 @@ class CORE_EXPORT EventTarget : public ScriptWrappable {
const EventListenerOptionsOrBoolean&);
bool removeEventListener(const AtomicString& event_type,
const EventListener*,
- EventListenerOptions&);
+ EventListenerOptions*);
virtual void RemoveAllEventListeners();
DispatchEventResult DispatchEvent(Event&);
@@ -191,10 +190,10 @@ class CORE_EXPORT EventTarget : public ScriptWrappable {
virtual bool AddEventListenerInternal(const AtomicString& event_type,
EventListener*,
- const AddEventListenerOptionsResolved&);
+ const AddEventListenerOptionsResolved*);
virtual bool RemoveEventListenerInternal(const AtomicString& event_type,
const EventListener*,
- const EventListenerOptions&);
+ const EventListenerOptions*);
// Called when an event listener has been successfully added.
virtual void AddedEventListener(const AtomicString& event_type,
@@ -216,7 +215,7 @@ class CORE_EXPORT EventTarget : public ScriptWrappable {
LocalDOMWindow* ExecutingWindow();
void SetDefaultAddEventListenerOptions(const AtomicString& event_type,
EventListener*,
- AddEventListenerOptionsResolved&);
+ AddEventListenerOptionsResolved*);
RegisteredEventListener* GetAttributeRegisteredEventListener(
const AtomicString& event_type);
@@ -252,62 +251,61 @@ class CORE_EXPORT EventTargetWithInlineData : public EventTarget {
GC_PLUGIN_IGNORE("513199") EventTargetData event_target_data_;
};
+// Macros to define an attribute event listener.
+// |lower_name| - Lower-cased event type name. e.g. |focus|
+// |symbol_name| - C++ symbol name in event_type_names namespace. e.g. |kFocus|
// FIXME: These macros should be split into separate DEFINE and DECLARE
// macros to avoid causing so many header includes.
-#define DEFINE_ATTRIBUTE_EVENT_LISTENER(attribute) \
- EventListener* on##attribute() { \
- return GetAttributeEventListener(EventTypeNames::attribute); \
- } \
- void setOn##attribute(EventListener* listener) { \
- SetAttributeEventListener(EventTypeNames::attribute, listener); \
- }
-#define DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(attribute) \
- static EventListener* on##attribute(EventTarget& eventTarget) { \
- return eventTarget.GetAttributeEventListener(EventTypeNames::attribute); \
- } \
- static void setOn##attribute(EventTarget& eventTarget, \
- EventListener* listener) { \
- eventTarget.SetAttributeEventListener(EventTypeNames::attribute, \
- listener); \
+#define DEFINE_ATTRIBUTE_EVENT_LISTENER(lower_name, symbol_name) \
+ EventListener* on##lower_name() { \
+ return GetAttributeEventListener(event_type_names::symbol_name); \
+ } \
+ void setOn##lower_name(EventListener* listener) { \
+ SetAttributeEventListener(event_type_names::symbol_name, listener); \
}
-#define DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
- EventListener* on##attribute() { \
- return GetDocument().GetWindowAttributeEventListener( \
- EventTypeNames::attribute); \
- } \
- void setOn##attribute(EventListener* listener) { \
- GetDocument().SetWindowAttributeEventListener(EventTypeNames::attribute, \
- listener); \
+#define DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(lower_name, symbol_name) \
+ static EventListener* on##lower_name(EventTarget& eventTarget) { \
+ return eventTarget.GetAttributeEventListener( \
+ event_type_names::symbol_name); \
+ } \
+ static void setOn##lower_name(EventTarget& eventTarget, \
+ EventListener* listener) { \
+ eventTarget.SetAttributeEventListener(event_type_names::symbol_name, \
+ listener); \
}
-#define DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
- static EventListener* on##attribute(EventTarget& eventTarget) { \
- if (Node* node = eventTarget.ToNode()) \
- return node->GetDocument().GetWindowAttributeEventListener( \
- EventTypeNames::attribute); \
- DCHECK(eventTarget.ToLocalDOMWindow()); \
- return eventTarget.GetAttributeEventListener(EventTypeNames::attribute); \
- } \
- static void setOn##attribute(EventTarget& eventTarget, \
- EventListener* listener) { \
- if (Node* node = eventTarget.ToNode()) \
- node->GetDocument().SetWindowAttributeEventListener( \
- EventTypeNames::attribute, listener); \
- else { \
- DCHECK(eventTarget.ToLocalDOMWindow()); \
- eventTarget.SetAttributeEventListener(EventTypeNames::attribute, \
- listener); \
- } \
+#define DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(lower_name, symbol_name) \
+ EventListener* on##lower_name() { \
+ return GetDocument().GetWindowAttributeEventListener( \
+ event_type_names::symbol_name); \
+ } \
+ void setOn##lower_name(EventListener* listener) { \
+ GetDocument().SetWindowAttributeEventListener( \
+ event_type_names::symbol_name, listener); \
}
-#define DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(attribute, eventName) \
- EventListener* on##attribute() { \
- return GetAttributeEventListener(EventTypeNames::eventName); \
- } \
- void setOn##attribute(EventListener* listener) { \
- SetAttributeEventListener(EventTypeNames::eventName, listener); \
+#define DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(lower_name, symbol_name) \
+ static EventListener* on##lower_name(EventTarget& eventTarget) { \
+ if (Node* node = eventTarget.ToNode()) { \
+ return node->GetDocument().GetWindowAttributeEventListener( \
+ event_type_names::symbol_name); \
+ } \
+ DCHECK(eventTarget.ToLocalDOMWindow()); \
+ return eventTarget.GetAttributeEventListener( \
+ event_type_names::symbol_name); \
+ } \
+ static void setOn##lower_name(EventTarget& eventTarget, \
+ EventListener* listener) { \
+ if (Node* node = eventTarget.ToNode()) { \
+ node->GetDocument().SetWindowAttributeEventListener( \
+ event_type_names::symbol_name, listener); \
+ } else { \
+ DCHECK(eventTarget.ToLocalDOMWindow()); \
+ eventTarget.SetAttributeEventListener(event_type_names::symbol_name, \
+ listener); \
+ } \
}
DISABLE_CFI_PERF
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.cc b/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.cc
index 08bf850212e..91a841a8799 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.cc
@@ -7,11 +7,11 @@
namespace blink {
EventTargetImpl* EventTargetImpl::Create(ScriptState* script_state) {
- return new EventTargetImpl(script_state);
+ return MakeGarbageCollected<EventTargetImpl>(script_state);
}
const AtomicString& EventTargetImpl::InterfaceName() const {
- return EventTargetNames::EventTargetImpl;
+ return event_target_names::kEventTargetImpl;
}
ExecutionContext* EventTargetImpl::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.h b/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.h
index 943d6fdc62a..77fe99923fe 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_target_impl.h
@@ -27,14 +27,12 @@ class CORE_EXPORT EventTargetImpl final : public EventTargetWithInlineData,
public:
static EventTargetImpl* Create(ScriptState*);
+ EventTargetImpl(ScriptState*);
~EventTargetImpl() override = default;
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
void Trace(blink::Visitor*) override;
-
- private:
- EventTargetImpl(ScriptState*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_target_test.cc b/chromium/third_party/blink/renderer/core/dom/events/event_target_test.cc
index 9eb3ca70d0c..c1d92286196 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_target_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_target_test.cc
@@ -24,7 +24,8 @@ TEST_F(EventTargetTest, PreventDefaultNotCalled) {
HistogramTester histogram_tester;
GetDocument().GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
"window.addEventListener('touchstart', function(e) {}, {});"
- "window.dispatchEvent(new TouchEvent('touchstart', {cancelable: "
+ "window.dispatchEvent(new TouchEvent('touchstart', "
+ "{cancelable: "
"false}));");
histogram_tester.ExpectTotalCount("Event.PassiveForcedEventDispatchCancelled",
@@ -39,7 +40,8 @@ TEST_F(EventTargetTest, PreventDefaultCalled) {
GetDocument().GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
"window.addEventListener('touchstart', function(e) "
"{e.preventDefault();}, {});"
- "window.dispatchEvent(new TouchEvent('touchstart', {cancelable: "
+ "window.dispatchEvent(new TouchEvent('touchstart', "
+ "{cancelable: "
"false}));");
histogram_tester.ExpectTotalCount("Event.PassiveForcedEventDispatchCancelled",
diff --git a/chromium/third_party/blink/renderer/core/dom/events/listener_leak_test.cc b/chromium/third_party/blink/renderer/core/dom/events/listener_leak_test.cc
index 6b178219e10..bf97de00785 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/listener_leak_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/listener_leak_test.cc
@@ -27,12 +27,13 @@
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "v8/include/v8-profiler.h"
@@ -40,6 +41,8 @@
namespace blink {
+namespace {
+
const v8::HeapGraphNode* GetProperty(v8::Isolate* isolate,
const v8::HeapGraphNode* node,
v8::HeapGraphEdge::Type type,
@@ -55,8 +58,7 @@ const v8::HeapGraphNode* GetProperty(v8::Isolate* isolate,
return nullptr;
}
-int GetNumObjects(const char* constructor) {
- v8::Isolate* isolate = v8::Isolate::GetCurrent();
+int GetNumObjects(v8::Isolate* isolate, const char* constructor) {
v8::HandleScope scope(isolate);
v8::HeapProfiler* profiler = isolate->GetHeapProfiler();
const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot();
@@ -84,15 +86,23 @@ int GetNumObjects(const char* constructor) {
return count;
}
+} // namespace
+
class ListenerLeakTest : public testing::Test {
public:
- void RunTest(const std::string& filename) {
+ void RunTestAndGC(const std::string& filename) {
std::string base_url("http://www.example.com/");
std::string file_name(filename);
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url), blink::test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
web_view_helper.InitializeAndLoad(base_url + file_name);
+ V8GCController::CollectAllGarbageForTesting(
+ isolate(), v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
+ }
+
+ v8::Isolate* isolate() const {
+ return ToIsolate(web_view_helper.LocalMainFrame()->GetFrame());
}
void TearDown() override {
@@ -102,21 +112,21 @@ class ListenerLeakTest : public testing::Test {
}
protected:
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
};
// This test tries to create a reference cycle between node and its listener.
// See http://crbug/17400.
TEST_F(ListenerLeakTest, ReferenceCycle) {
- RunTest("listener/listener_leak1.html");
- ASSERT_EQ(0, GetNumObjects("EventListenerLeakTestObject1"));
+ RunTestAndGC("listener/listener_leak1.html");
+ ASSERT_EQ(0, GetNumObjects(isolate(), "EventListenerLeakTestObject1"));
}
// This test sets node onclick many times to expose a possible memory
// leak where all listeners get referenced by the node.
TEST_F(ListenerLeakTest, HiddenReferences) {
- RunTest("listener/listener_leak2.html");
- ASSERT_EQ(1, GetNumObjects("EventListenerLeakTestObject2"));
+ RunTestAndGC("listener/listener_leak2.html");
+ ASSERT_EQ(1, GetNumObjects(isolate(), "EventListenerLeakTestObject2"));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/events/node_event_context.cc b/chromium/third_party/blink/renderer/core/dom/events/node_event_context.cc
index 48d5de7df4b..16d26106b99 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/node_event_context.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/node_event_context.cc
@@ -35,10 +35,8 @@
namespace blink {
-NodeEventContext::NodeEventContext(Node* node, EventTarget* current_target)
- : node_(node), current_target_(current_target) {
- DCHECK(node_);
-}
+NodeEventContext::NodeEventContext(Node& node, EventTarget& current_target)
+ : node_(node), current_target_(current_target) {}
void NodeEventContext::Trace(blink::Visitor* visitor) {
visitor->Trace(node_);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/node_event_context.h b/chromium/third_party/blink/renderer/core/dom/events/node_event_context.h
index 4bbb99b7e7f..21c2ca244f5 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/node_event_context.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/node_event_context.h
@@ -42,10 +42,10 @@ class CORE_EXPORT NodeEventContext {
public:
// FIXME: Use ContainerNode instead of Node.
- NodeEventContext(Node*, EventTarget* current_target);
+ NodeEventContext(Node&, EventTarget& current_target);
void Trace(blink::Visitor*);
- Node* GetNode() const { return node_.Get(); }
+ Node& GetNode() const { return *node_; }
void SetTreeScopeEventContext(
TreeScopeEventContext* tree_scope_event_context) {
diff --git a/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.cc b/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.cc
index 91efc198321..93685d95475 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.cc
@@ -41,15 +41,15 @@ RegisteredEventListener::RegisteredEventListener()
RegisteredEventListener::RegisteredEventListener(
EventListener* listener,
- const AddEventListenerOptionsResolved& options)
+ const AddEventListenerOptionsResolved* options)
: callback_(listener),
- use_capture_(options.capture()),
- passive_(options.passive()),
- once_(options.once()),
+ use_capture_(options->capture()),
+ passive_(options->passive()),
+ once_(options->once()),
blocked_event_warning_emitted_(false),
passive_forced_for_document_target_(
- options.PassiveForcedForDocumentTarget()),
- passive_specified_(options.PassiveSpecified()) {}
+ options->PassiveForcedForDocumentTarget()),
+ passive_specified_(options->PassiveSpecified()) {}
RegisteredEventListener& RegisteredEventListener::operator=(
const RegisteredEventListener& that) = default;
@@ -58,13 +58,15 @@ void RegisteredEventListener::Trace(Visitor* visitor) {
visitor->Trace(callback_);
}
-AddEventListenerOptionsResolved RegisteredEventListener::Options() const {
- AddEventListenerOptionsResolved result;
- result.setCapture(use_capture_);
- result.setPassive(passive_);
- result.SetPassiveForcedForDocumentTarget(passive_forced_for_document_target_);
- result.setOnce(once_);
- result.SetPassiveSpecified(passive_specified_);
+AddEventListenerOptionsResolved* RegisteredEventListener::Options() const {
+ AddEventListenerOptionsResolved* result =
+ AddEventListenerOptionsResolved::Create();
+ result->setCapture(use_capture_);
+ result->setPassive(passive_);
+ result->SetPassiveForcedForDocumentTarget(
+ passive_forced_for_document_target_);
+ result->setOnce(once_);
+ result->SetPassiveSpecified(passive_specified_);
return result;
}
@@ -74,12 +76,12 @@ void RegisteredEventListener::SetCallback(EventListener* listener) {
bool RegisteredEventListener::Matches(
const EventListener* listener,
- const EventListenerOptions& options) const {
+ const EventListenerOptions* options) const {
// Equality is soley based on the listener and useCapture flags.
DCHECK(callback_);
DCHECK(listener);
return *callback_ == *listener &&
- static_cast<bool>(use_capture_) == options.capture();
+ static_cast<bool>(use_capture_) == options->capture();
}
bool RegisteredEventListener::ShouldFire(const Event& event) const {
diff --git a/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.h b/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.h
index ac6bb8ca70c..248e143f347 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/registered_event_listener.h
@@ -44,12 +44,12 @@ class RegisteredEventListener final {
public:
RegisteredEventListener();
RegisteredEventListener(EventListener* listener,
- const AddEventListenerOptionsResolved& options);
+ const AddEventListenerOptionsResolved* options);
RegisteredEventListener& operator=(const RegisteredEventListener& that);
void Trace(Visitor* visitor);
- AddEventListenerOptionsResolved Options() const;
+ AddEventListenerOptionsResolved* Options() const;
const EventListener* Callback() const { return callback_; }
@@ -78,7 +78,7 @@ class RegisteredEventListener final {
}
bool Matches(const EventListener* listener,
- const EventListenerOptions& options) const;
+ const EventListenerOptions* options) const;
bool ShouldFire(const Event&) const;
diff --git a/chromium/third_party/blink/renderer/core/dom/events/scoped_event_queue.cc b/chromium/third_party/blink/renderer/core/dom/events/scoped_event_queue.cc
index c45ab23c18c..3409af0dc7e 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/scoped_event_queue.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/scoped_event_queue.cc
@@ -42,7 +42,8 @@ namespace blink {
ScopedEventQueue* ScopedEventQueue::instance_ = nullptr;
ScopedEventQueue::ScopedEventQueue()
- : queued_events_(new HeapVector<Member<Event>>()), scoping_level_(0) {}
+ : queued_events_(MakeGarbageCollected<HeapVector<Member<Event>>>()),
+ scoping_level_(0) {}
ScopedEventQueue::~ScopedEventQueue() {
DCHECK(!scoping_level_);
diff --git a/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc b/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc
index 866c2a6d20d..2133bac406e 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.cc
@@ -67,7 +67,7 @@ HeapVector<Member<EventTarget>>& TreeScopeEventContext::EnsureEventPath(
if (event_path_)
return *event_path_;
- event_path_ = new HeapVector<Member<EventTarget>>();
+ event_path_ = MakeGarbageCollected<HeapVector<Member<EventTarget>>>();
LocalDOMWindow* window = path.GetWindowEventContext().Window();
event_path_->ReserveCapacity(path.size() + (window ? 1 : 0));
@@ -80,14 +80,14 @@ HeapVector<Member<EventTarget>>& TreeScopeEventContext::EnsureEventPath(
return *event_path_;
}
-TouchEventContext* TreeScopeEventContext::EnsureTouchEventContext() {
+TouchEventContext& TreeScopeEventContext::EnsureTouchEventContext() {
if (!touch_event_context_)
touch_event_context_ = TouchEventContext::Create();
- return touch_event_context_.Get();
+ return *touch_event_context_;
}
TreeScopeEventContext* TreeScopeEventContext::Create(TreeScope& tree_scope) {
- return new TreeScopeEventContext(tree_scope);
+ return MakeGarbageCollected<TreeScopeEventContext>(tree_scope);
}
TreeScopeEventContext::TreeScopeEventContext(TreeScope& tree_scope)
diff --git a/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.h b/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.h
index d167c660640..eac6b4a0d04 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/tree_scope_event_context.h
@@ -48,21 +48,23 @@ class CORE_EXPORT TreeScopeEventContext final
: public GarbageCollected<TreeScopeEventContext> {
public:
static TreeScopeEventContext* Create(TreeScope&);
+
+ TreeScopeEventContext(TreeScope&);
void Trace(blink::Visitor*);
TreeScope& GetTreeScope() const { return *tree_scope_; }
ContainerNode& RootNode() const { return tree_scope_->RootNode(); }
EventTarget* Target() const { return target_.Get(); }
- void SetTarget(EventTarget*);
+ void SetTarget(EventTarget&);
EventTarget* RelatedTarget() const { return related_target_.Get(); }
- void SetRelatedTarget(EventTarget*);
+ void SetRelatedTarget(EventTarget&);
TouchEventContext* GetTouchEventContext() const {
return touch_event_context_.Get();
}
- TouchEventContext* EnsureTouchEventContext();
+ TouchEventContext& EnsureTouchEventContext();
HeapVector<Member<EventTarget>>& EnsureEventPath(EventPath&);
@@ -84,8 +86,6 @@ class CORE_EXPORT TreeScopeEventContext final
}
private:
- TreeScopeEventContext(TreeScope&);
-
void CheckReachableNode(EventTarget&);
bool IsUnclosedTreeOf(const TreeScopeEventContext& other);
@@ -118,16 +118,14 @@ inline void TreeScopeEventContext::CheckReachableNode(EventTarget& target) {
inline void TreeScopeEventContext::CheckReachableNode(EventTarget&) {}
#endif
-inline void TreeScopeEventContext::SetTarget(EventTarget* target) {
- DCHECK(target);
- CheckReachableNode(*target);
+inline void TreeScopeEventContext::SetTarget(EventTarget& target) {
+ CheckReachableNode(target);
target_ = target;
}
inline void TreeScopeEventContext::SetRelatedTarget(
- EventTarget* related_target) {
- DCHECK(related_target);
- CheckReachableNode(*related_target);
+ EventTarget& related_target) {
+ CheckReachableNode(related_target);
related_target_ = related_target;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/events/window_event_context.cc b/chromium/third_party/blink/renderer/core/dom/events/window_event_context.cc
index 3e00f04ccd8..3e3de47918c 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/window_event_context.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/window_event_context.cc
@@ -39,7 +39,7 @@ WindowEventContext::WindowEventContext(
const NodeEventContext& top_node_event_context) {
// We don't dispatch load events to the window. This quirk was originally
// added because Mozilla doesn't propagate load events to the window object.
- if (event.type() == EventTypeNames::load)
+ if (event.type() == event_type_names::kLoad)
return;
auto* document = DynamicTo<Document>(top_node_event_context.GetNode());
if (!document)
diff --git a/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.cc b/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.cc
index 4693d518554..a689ec3a7aa 100644
--- a/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.cc
+++ b/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.cc
@@ -44,16 +44,16 @@ namespace blink {
// (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes),
// that precedes or follows the first letter should be included"
static inline bool IsPunctuationForFirstLetter(UChar32 c) {
- WTF::Unicode::CharCategory char_category = WTF::Unicode::Category(c);
- return char_category == WTF::Unicode::kPunctuation_Open ||
- char_category == WTF::Unicode::kPunctuation_Close ||
- char_category == WTF::Unicode::kPunctuation_InitialQuote ||
- char_category == WTF::Unicode::kPunctuation_FinalQuote ||
- char_category == WTF::Unicode::kPunctuation_Other;
+ WTF::unicode::CharCategory char_category = WTF::unicode::Category(c);
+ return char_category == WTF::unicode::kPunctuation_Open ||
+ char_category == WTF::unicode::kPunctuation_Close ||
+ char_category == WTF::unicode::kPunctuation_InitialQuote ||
+ char_category == WTF::unicode::kPunctuation_FinalQuote ||
+ char_category == WTF::unicode::kPunctuation_Other;
}
static inline bool IsSpaceForFirstLetter(UChar c) {
- return IsSpaceOrNewline(c) || c == WTF::Unicode::kNoBreakSpaceCharacter;
+ return IsSpaceOrNewline(c) || c == WTF::unicode::kNoBreakSpaceCharacter;
}
unsigned FirstLetterPseudoElement::FirstLetterLength(const String& text) {
@@ -231,7 +231,7 @@ void FirstLetterPseudoElement::UpdateTextFragments() {
// needs to re-create the line boxes. The remaining text layoutObject
// will be marked by the LayoutText::setText.
child_fragment->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kTextChanged);
+ layout_invalidation_reason::kTextChanged);
break;
}
}
@@ -252,8 +252,9 @@ void FirstLetterPseudoElement::ClearRemainingTextLayoutObject() {
// first letter, we need to UpdateFirstLetter to render the new first letter
// or remove the ::first-letter pseudo if there is no text left. Do that as
// part of a style recalc for this ::first-letter.
- SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kPseudoClass));
+ SetNeedsStyleRecalc(
+ kLocalStyleChange,
+ StyleChangeReasonForTracing::Create(style_change_reason::kPseudoClass));
}
void FirstLetterPseudoElement::AttachLayoutTree(AttachContext& context) {
@@ -310,12 +311,13 @@ void FirstLetterPseudoElement::AttachFirstLetterTextLayoutObjects(LayoutText* fi
LayoutTextFragment* remaining_text;
if (first_letter_text->GetNode()) {
- remaining_text =
- new LayoutTextFragment(first_letter_text->GetNode(), old_text.Impl(),
- length, remaining_length);
+ remaining_text = LayoutTextFragment::Create(
+ *first_letter_text->Style(), first_letter_text->GetNode(),
+ old_text.Impl(), length, remaining_length);
} else {
remaining_text = LayoutTextFragment::CreateAnonymous(
- *this, old_text.Impl(), length, remaining_length);
+ *first_letter_text->Style(), *this, old_text.Impl(), length,
+ remaining_length);
}
remaining_text->SetFirstLetterPseudoElement(this);
@@ -331,40 +333,16 @@ void FirstLetterPseudoElement::AttachFirstLetterTextLayoutObjects(LayoutText* fi
GetLayoutObject()->Parent()->AddChild(remaining_text, next_sibling);
// Construct text fragment for the first letter.
- LayoutTextFragment* letter =
- LayoutTextFragment::CreateAnonymous(*this, old_text.Impl(), 0, length);
+ ComputedStyle* const letter_style = MutableComputedStyle();
+ LayoutTextFragment* letter = LayoutTextFragment::CreateAnonymous(
+ *letter_style, *this, old_text.Impl(), 0, length);
letter->SetFirstLetterPseudoElement(this);
- letter->SetStyle(MutableComputedStyle());
+ letter->SetStyle(letter_style);
GetLayoutObject()->AddChild(letter);
first_letter_text->Destroy();
}
-void FirstLetterPseudoElement::DidRecalcStyle(StyleRecalcChange) {
- LayoutObject* layout_object = GetLayoutObject();
- if (!layout_object)
- return;
-
- // The layout objects inside pseudo elements are anonymous so they don't get
- // notified of RecalcStyle and must have the style propagated downward
- // manually similar to LayoutObject::PropagateStyleToAnonymousChildren.
- for (LayoutObject* child = layout_object->NextInPreOrder(layout_object);
- child; child = child->NextInPreOrder(layout_object)) {
- // We need to re-calculate the correct style for the first letter element
- // and then apply that to the container and the text fragment inside.
- if (child->Style()->StyleType() == kPseudoIdFirstLetter) {
- child->SetPseudoStyle(layout_object->MutableStyle());
- continue;
- }
-
- // We only manage the style for the generated content items.
- if (!child->IsText() && !child->IsQuote() && !child->IsImage())
- continue;
-
- child->SetPseudoStyle(layout_object->MutableStyle());
- }
-}
-
Node* FirstLetterPseudoElement::InnerNodeForHitTesting() const {
// When we hit a first letter during hit testing, hover state and events
// should be triggered on the parent of the real text node where the first
diff --git a/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.h b/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.h
index 192dc999bfc..1c5235c9e49 100644
--- a/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.h
+++ b/chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.h
@@ -39,9 +39,10 @@ class LayoutTextFragment;
class CORE_EXPORT FirstLetterPseudoElement final : public PseudoElement {
public:
static FirstLetterPseudoElement* Create(Element* parent) {
- return new FirstLetterPseudoElement(parent);
+ return MakeGarbageCollected<FirstLetterPseudoElement>(parent);
}
+ explicit FirstLetterPseudoElement(Element*);
~FirstLetterPseudoElement() override;
static LayoutText* FirstLetterTextLayoutObject(const Element&);
@@ -59,10 +60,7 @@ class CORE_EXPORT FirstLetterPseudoElement final : public PseudoElement {
Node* InnerNodeForHitTesting() const override;
private:
- explicit FirstLetterPseudoElement(Element*);
-
scoped_refptr<ComputedStyle> CustomStyleForLayoutObject() override;
- void DidRecalcStyle(StyleRecalcChange) override;
void AttachFirstLetterTextLayoutObjects(LayoutText* first_letter_text);
diff --git a/chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.cc b/chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.cc
new file mode 100644
index 00000000000..163ec4338a1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.cc
@@ -0,0 +1,17 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/dom/flat_tree_node_data.h"
+
+#include "third_party/blink/renderer/core/html/html_slot_element.h"
+
+namespace blink {
+
+void FlatTreeNodeData::Trace(Visitor* visitor) {
+ visitor->Trace(assigned_slot_);
+ visitor->Trace(previous_in_assigned_nodes_);
+ visitor->Trace(next_in_assigned_nodes_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.h b/chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.h
new file mode 100644
index 00000000000..96d98836eb3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/dom/flat_tree_node_data.h
@@ -0,0 +1,51 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_FLAT_TREE_NODE_DATA_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_FLAT_TREE_NODE_DATA_H_
+
+#include "base/macros.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+
+namespace blink {
+
+class Node;
+class HTMLSlotElement;
+
+class FlatTreeNodeData final : public GarbageCollected<FlatTreeNodeData> {
+ public:
+ FlatTreeNodeData() {}
+ void Clear() {
+ assigned_slot_ = nullptr;
+ previous_in_assigned_nodes_ = nullptr;
+ next_in_assigned_nodes_ = nullptr;
+ }
+ void Trace(Visitor*);
+
+ private:
+ void SetAssignedSlot(HTMLSlotElement* assigned_slot) {
+ assigned_slot_ = assigned_slot;
+ }
+
+ void SetPreviousInAssignedNodes(Node* previous) {
+ previous_in_assigned_nodes_ = previous;
+ }
+ void SetNextInAssignedNodes(Node* next) { next_in_assigned_nodes_ = next; }
+
+ HTMLSlotElement* AssignedSlot() { return assigned_slot_; }
+ Node* PreviousInAssignedNodes() { return previous_in_assigned_nodes_; }
+ Node* NextInAssignedNodes() { return next_in_assigned_nodes_; }
+
+ friend class FlatTreeTraversal;
+ friend class HTMLSlotElement;
+
+ WeakMember<HTMLSlotElement> assigned_slot_;
+ WeakMember<Node> previous_in_assigned_nodes_;
+ WeakMember<Node> next_in_assigned_nodes_;
+ DISALLOW_COPY_AND_ASSIGN(FlatTreeNodeData);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_FLAT_TREE_NODE_DATA_H_
diff --git a/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.cc b/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.cc
index f98a8b5775a..92e6ec38f32 100644
--- a/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.cc
+++ b/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.cc
@@ -27,6 +27,8 @@
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/dom/flat_tree_node_data.h"
+#include "third_party/blink/renderer/core/dom/slot_assignment.h"
#include "third_party/blink/renderer/core/html/html_shadow_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
@@ -114,12 +116,28 @@ Node* FlatTreeTraversal::TraverseSiblings(const Node& node,
Node* FlatTreeTraversal::TraverseSiblingsForV1HostChild(
const Node& node,
TraversalDirection direction) {
- HTMLSlotElement* slot = node.AssignedSlot();
- if (!slot)
+ ShadowRoot* shadow_root = node.ParentElementShadowRoot();
+ DCHECK(shadow_root);
+ if (!shadow_root->HasSlotAssignment()) {
+ // The shadow root doesn't have any slot.
return nullptr;
- return direction == kTraversalDirectionForward
- ? slot->AssignedNodeNextTo(node)
- : slot->AssignedNodePreviousTo(node);
+ }
+ shadow_root->GetSlotAssignment().RecalcAssignment();
+
+ FlatTreeNodeData* flat_tree_node_data = node.GetFlatTreeNodeData();
+ if (!flat_tree_node_data) {
+ // This node has never been assigned to any slot.
+ return nullptr;
+ }
+ if (flat_tree_node_data->AssignedSlot()) {
+ return direction == kTraversalDirectionForward
+ ? flat_tree_node_data->NextInAssignedNodes()
+ : flat_tree_node_data->PreviousInAssignedNodes();
+ }
+ // This node is not assigned to any slot.
+ DCHECK(!flat_tree_node_data->NextInAssignedNodes());
+ DCHECK(!flat_tree_node_data->PreviousInAssignedNodes());
+ return nullptr;
}
Node* FlatTreeTraversal::TraverseSiblingsForV0Distribution(
diff --git a/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.h b/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.h
index f12b457cdcc..da283a34310 100644
--- a/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.h
+++ b/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.h
@@ -60,6 +60,9 @@ class CORE_EXPORT FlatTreeTraversal {
static Node* Next(const Node&);
static Node* Next(const Node&, const Node* stay_within);
static Node* Previous(const Node&);
+ // Returns the previous of |node| in preorder. When |stay_within| is given,
+ // returns nullptr if the previous is not a descendant of |stay_within|.
+ static Node* Previous(const Node& node, const Node* stay_within);
static Node* FirstChild(const Node&);
static Node* LastChild(const Node&);
@@ -282,6 +285,17 @@ inline Node* FlatTreeTraversal::TraversePrevious(const Node& node) {
return TraverseParent(node);
}
+inline Node* FlatTreeTraversal::Previous(const Node& node,
+ const Node* stay_within) {
+ if (!stay_within)
+ return Previous(node);
+ DCHECK(IsDescendantOf(node, *stay_within));
+ Node* previous = Previous(node);
+ if (previous == stay_within)
+ return nullptr;
+ return previous;
+}
+
inline Node* FlatTreeTraversal::FirstChild(const Node& node) {
AssertPrecondition(node);
Node* result = TraverseChild(node, kTraversalDirectionForward);
diff --git a/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.cc b/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.cc
index d5f54e1149c..02b71b6619e 100644
--- a/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.cc
+++ b/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.cc
@@ -22,7 +22,7 @@ FrameRequestCallbackCollection::RegisterCallback(FrameCallback* callback) {
TRACE_EVENT_INSTANT1("devtools.timeline", "RequestAnimationFrame",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorAnimationFrameEvent::Data(context_, id));
+ inspector_animation_frame_event::Data(context_, id));
probe::AsyncTaskScheduledBreakable(context_, "requestAnimationFrame",
callback);
return id;
@@ -36,7 +36,7 @@ void FrameRequestCallbackCollection::CancelCallback(CallbackId id) {
callbacks_.EraseAt(i);
TRACE_EVENT_INSTANT1("devtools.timeline", "CancelAnimationFrame",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorAnimationFrameEvent::Data(context_, id));
+ inspector_animation_frame_event::Data(context_, id));
return;
}
}
@@ -46,7 +46,7 @@ void FrameRequestCallbackCollection::CancelCallback(CallbackId id) {
callback);
TRACE_EVENT_INSTANT1("devtools.timeline", "CancelAnimationFrame",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorAnimationFrameEvent::Data(context_, id));
+ inspector_animation_frame_event::Data(context_, id));
callback->SetIsCancelled(true);
// will be removed at the end of executeCallbacks()
return;
@@ -74,7 +74,7 @@ void FrameRequestCallbackCollection::ExecuteCallbacks(
if (!callback->IsCancelled()) {
TRACE_EVENT1(
"devtools.timeline", "FireAnimationFrame", "data",
- InspectorAnimationFrameEvent::Data(context_, callback->Id()));
+ inspector_animation_frame_event::Data(context_, callback->Id()));
probe::AsyncTask async_task(context_, callback);
probe::UserCallback probe(context_, "requestAnimationFrame",
AtomicString(), true);
diff --git a/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.h b/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.h
index 0aca9b30f38..3d69e24d821 100644
--- a/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.h
+++ b/chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.h
@@ -59,17 +59,19 @@ class GC_PLUGIN_IGNORE("crbug.com/841830")
class CORE_EXPORT V8FrameCallback : public FrameCallback {
public:
static V8FrameCallback* Create(V8FrameRequestCallback* callback) {
- return new V8FrameCallback(callback);
+ return MakeGarbageCollected<V8FrameCallback>(callback);
}
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override {
return "V8FrameCallback";
}
+
+ explicit V8FrameCallback(V8FrameRequestCallback*);
~V8FrameCallback() override = default;
+
void Invoke(double) override;
private:
- explicit V8FrameCallback(V8FrameRequestCallback*);
TraceWrapperMember<V8FrameRequestCallback> callback_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/global_event_handlers.h b/chromium/third_party/blink/renderer/core/dom/global_event_handlers.h
index e01c6ca6dbd..36f277a1940 100644
--- a/chromium/third_party/blink/renderer/core/dom/global_event_handlers.h
+++ b/chromium/third_party/blink/renderer/core/dom/global_event_handlers.h
@@ -39,85 +39,86 @@ class GlobalEventHandlers {
STATIC_ONLY(GlobalEventHandlers);
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(activateinvisible);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(auxclick);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(blur);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cancel);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplay);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(click);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(close);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(contextmenu);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cuechange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dblclick);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drag);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragend);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragenter);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragleave);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragover);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragstart);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drop);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(durationchange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(emptied);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ended);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(focus);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(formdata);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(gotpointercapture);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(input);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(invalid);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keydown);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keypress);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keyup);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadeddata);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadstart);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(lostpointercapture);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousedown);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseenter);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseleave);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousemove);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseout);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseover);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseup);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousewheel);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pause);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(play);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(playing);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointercancel);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerdown);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerenter);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerleave);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointermove);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerout);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerover);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerrawmove);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerup);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(progress);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ratechange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(reset);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeked);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeking);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(select);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(selectionchange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(selectstart);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(stalled);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(submit);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(suspend);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(timeupdate);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(toggle);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchcancel);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchend);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchmove);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchstart);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(volumechange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(waiting);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(wheel);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(activateinvisible, kActivateinvisible);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(auxclick, kAuxclick);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(blur, kBlur);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cancel, kCancel);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplay, kCanplay);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplaythrough, kCanplaythrough);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(change, kChange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(click, kClick);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(close, kClose);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(contextmenu, kContextmenu);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cuechange, kCuechange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dblclick, kDblclick);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drag, kDrag);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragend, kDragend);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragenter, kDragenter);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragleave, kDragleave);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragover, kDragover);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragstart, kDragstart);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drop, kDrop);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(durationchange, kDurationchange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(emptied, kEmptied);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ended, kEnded);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(focus, kFocus);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(formdata, kFormdata);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(gotpointercapture, kGotpointercapture);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(input, kInput);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(invalid, kInvalid);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keydown, kKeydown);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keypress, kKeypress);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keyup, kKeyup);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(load, kLoad);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadeddata, kLoadeddata);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadedmetadata, kLoadedmetadata);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadstart, kLoadstart);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(lostpointercapture,
+ kLostpointercapture);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousedown, kMousedown);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseenter, kMouseenter);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseleave, kMouseleave);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousemove, kMousemove);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseout, kMouseout);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseover, kMouseover);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseup, kMouseup);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousewheel, kMousewheel);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pause, kPause);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(play, kPlay);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(playing, kPlaying);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointercancel, kPointercancel);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerdown, kPointerdown);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerenter, kPointerenter);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerleave, kPointerleave);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointermove, kPointermove);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerout, kPointerout);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerover, kPointerover);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerrawmove, kPointerrawmove);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pointerup, kPointerup);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(progress, kProgress);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ratechange, kRatechange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(reset, kReset);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(resize, kResize);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(scroll, kScroll);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeked, kSeeked);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeking, kSeeking);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(select, kSelect);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(selectionchange, kSelectionchange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(selectstart, kSelectstart);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(stalled, kStalled);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(submit, kSubmit);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(suspend, kSuspend);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(timeupdate, kTimeupdate);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(toggle, kToggle);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchcancel, kTouchcancel);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchend, kTouchend);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchmove, kTouchmove);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(touchstart, kTouchstart);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(volumechange, kVolumechange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(waiting, kWaiting);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(wheel, kWheel);
};
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.cc b/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.cc
index 044076bfbcb..7c73ad21e8a 100644
--- a/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.cc
+++ b/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.cc
@@ -30,7 +30,7 @@
namespace blink {
IdTargetObserverRegistry* IdTargetObserverRegistry::Create() {
- return new IdTargetObserverRegistry();
+ return MakeGarbageCollected<IdTargetObserverRegistry>();
}
void IdTargetObserverRegistry::Trace(blink::Visitor* visitor) {
@@ -45,7 +45,7 @@ void IdTargetObserverRegistry::AddObserver(const AtomicString& id,
IdToObserverSetMap::AddResult result = registry_.insert(id.Impl(), nullptr);
if (result.is_new_entry)
- result.stored_value->value = new ObserverSet();
+ result.stored_value->value = MakeGarbageCollected<ObserverSet>();
result.stored_value->value->insert(observer);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.h b/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.h
index 5c94327cc2e..fd7d78960a3 100644
--- a/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.h
+++ b/chromium/third_party/blink/renderer/core/dom/id_target_observer_registry.h
@@ -43,12 +43,14 @@ class IdTargetObserverRegistry final
public:
static IdTargetObserverRegistry* Create();
+
+ IdTargetObserverRegistry() : notifying_observers_in_set_(nullptr) {}
+
void Trace(blink::Visitor*);
void NotifyObservers(const AtomicString& id);
bool HasObservers(const AtomicString& id) const;
private:
- IdTargetObserverRegistry() : notifying_observers_in_set_(nullptr) {}
void AddObserver(const AtomicString& id, IdTargetObserver*);
void RemoveObserver(const AtomicString& id, IdTargetObserver*);
void NotifyObserversInternal(const AtomicString& id);
diff --git a/chromium/third_party/blink/renderer/core/dom/idle_deadline.cc b/chromium/third_party/blink/renderer/core/dom/idle_deadline.cc
index a30fe7c2767..f59ec80c193 100644
--- a/chromium/third_party/blink/renderer/core/dom/idle_deadline.cc
+++ b/chromium/third_party/blink/renderer/core/dom/idle_deadline.cc
@@ -16,10 +16,8 @@ IdleDeadline::IdleDeadline(TimeTicks deadline, CallbackType callback_type)
double IdleDeadline::timeRemaining() const {
TimeDelta time_remaining = deadline_ - CurrentTimeTicks();
- if (time_remaining < TimeDelta() || Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->ShouldYieldForHighPriorityWork()) {
+ if (time_remaining < TimeDelta() ||
+ ThreadScheduler::Current()->ShouldYieldForHighPriorityWork()) {
return 0;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/idle_deadline.h b/chromium/third_party/blink/renderer/core/dom/idle_deadline.h
index 59c37cd7593..471935fd748 100644
--- a/chromium/third_party/blink/renderer/core/dom/idle_deadline.h
+++ b/chromium/third_party/blink/renderer/core/dom/idle_deadline.h
@@ -19,9 +19,11 @@ class CORE_EXPORT IdleDeadline : public ScriptWrappable {
enum class CallbackType { kCalledWhenIdle, kCalledByTimeout };
static IdleDeadline* Create(TimeTicks deadline, CallbackType callback_type) {
- return new IdleDeadline(deadline, callback_type);
+ return MakeGarbageCollected<IdleDeadline>(deadline, callback_type);
}
+ IdleDeadline(TimeTicks deadline, CallbackType);
+
double timeRemaining() const;
bool didTimeout() const {
@@ -29,8 +31,6 @@ class CORE_EXPORT IdleDeadline : public ScriptWrappable {
}
private:
- IdleDeadline(TimeTicks deadline, CallbackType);
-
TimeTicks deadline_;
CallbackType callback_type_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/idle_deadline_test.cc b/chromium/third_party/blink/renderer/core/dom/idle_deadline_test.cc
index aebde6e91d8..5c04f0f4e0f 100644
--- a/chromium/third_party/blink/renderer/core/dom/idle_deadline_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/idle_deadline_test.cc
@@ -8,7 +8,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h"
+#include "third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h"
#include "third_party/blink/renderer/platform/testing/wtf/scoped_mock_clock.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -48,11 +48,9 @@ class MockIdleDeadlineScheduler final : public ThreadScheduler {
return base::TimeTicks();
}
- void AddTaskObserver(
- base::MessageLoop::TaskObserver* task_observer) override {}
+ void AddTaskObserver(Thread::TaskObserver* task_observer) override {}
- void RemoveTaskObserver(
- base::MessageLoop::TaskObserver* task_observer) override {}
+ void RemoveTaskObserver(Thread::TaskObserver* task_observer) override {}
void AddRAILModeObserver(scheduler::WebRAILModeObserver*) override {}
@@ -74,7 +72,7 @@ class IdleDeadlineTest : public testing::Test {
WTF::ScopedMockClock clock_;
};
-TEST_F(IdleDeadlineTest, deadlineInFuture) {
+TEST_F(IdleDeadlineTest, DeadlineInFuture) {
IdleDeadline* deadline =
IdleDeadline::Create(TimeTicks() + TimeDelta::FromSecondsD(1.25),
IdleDeadline::CallbackType::kCalledWhenIdle);
@@ -82,18 +80,16 @@ TEST_F(IdleDeadlineTest, deadlineInFuture) {
EXPECT_FLOAT_EQ(250.0, deadline->timeRemaining());
}
-TEST_F(IdleDeadlineTest, deadlineInPast) {
+TEST_F(IdleDeadlineTest, DeadlineInPast) {
IdleDeadline* deadline =
IdleDeadline::Create(TimeTicks() + TimeDelta::FromSecondsD(0.75),
IdleDeadline::CallbackType::kCalledWhenIdle);
EXPECT_FLOAT_EQ(0, deadline->timeRemaining());
}
-TEST_F(IdleDeadlineTest, yieldForHighPriorityWork) {
+TEST_F(IdleDeadlineTest, YieldForHighPriorityWork) {
MockIdleDeadlineScheduler scheduler;
- ScopedTestingPlatformSupport<TestingPlatformSupportWithCustomScheduler,
- ThreadScheduler*>
- platform(&scheduler);
+ ScopedSchedulerOverrider scheduler_overrider(&scheduler);
IdleDeadline* deadline =
IdleDeadline::Create(TimeTicks() + TimeDelta::FromSecondsD(1.25),
diff --git a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.cc b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.cc
index ba586f17e2b..24f2266c427 100644
--- a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.cc
+++ b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.cc
@@ -76,6 +76,7 @@ LayoutTreeBuilderForElement::LayoutTreeBuilderForElement(Element& element,
ComputedStyle* style)
: LayoutTreeBuilder(element, nullptr), style_(style) {
DCHECK(element.CanParticipateInFlatTree());
+ DCHECK(style_);
// TODO(ecobos): Move the first-letter logic inside ParentLayoutObject too?
// It's an extra (unnecessary) check for text nodes, though.
if (element.IsFirstLetterPseudoElement()) {
@@ -127,36 +128,24 @@ bool LayoutTreeBuilderForElement::ShouldCreateLayoutObject() const {
!CanHaveGeneratedChildren(*parent_layout_object)) {
return false;
}
- return node_->LayoutObjectIsNeeded(Style());
-}
-
-ComputedStyle& LayoutTreeBuilderForElement::Style() const {
- if (!style_) {
- // TODO(futhark@chromium.org): this should never happen, but we currently
- // have crashes in the wild because of this (https://crbug.com/875796).
- // Please report if you ever end up here.
- NOTREACHED();
- style_ = node_->StyleForLayoutObject();
- }
- return *style_;
+ return node_->LayoutObjectIsNeeded(*style_);
}
DISABLE_CFI_PERF
void LayoutTreeBuilderForElement::CreateLayoutObject() {
- ComputedStyle& style = Style();
ReattachLegacyLayoutObjectList& legacy_layout_objects =
node_->GetDocument().GetReattachLegacyLayoutObjectList();
if (legacy_layout_objects.IsForcingLegacyLayout()) {
DCHECK(!node_->GetLayoutObject());
- style.SetForceLegacyLayout(true);
+ style_->SetForceLegacyLayout(true);
}
- LayoutObject* new_layout_object = node_->CreateLayoutObject(style);
+ LayoutObject* new_layout_object = node_->CreateLayoutObject(*style_);
if (!new_layout_object)
return;
LayoutObject* parent_layout_object = ParentLayoutObject();
- if (!parent_layout_object->IsChildAllowed(new_layout_object, style)) {
+ if (!parent_layout_object->IsChildAllowed(new_layout_object, *style_)) {
new_layout_object->Destroy();
return;
}
@@ -171,7 +160,7 @@ void LayoutTreeBuilderForElement::CreateLayoutObject() {
LayoutObject* next_layout_object = NextLayoutObject();
node_->SetLayoutObject(new_layout_object);
new_layout_object->SetStyle(
- &style); // SetStyle() can depend on LayoutObject() already being set.
+ style_); // SetStyle() can depend on LayoutObject() already being set.
// Note: Adding new_layout_object instead of LayoutObject(). LayoutObject()
// may be a child of new_layout_object.
diff --git a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.h b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.h
index 0f53a0781a8..f71adc0d85b 100644
--- a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.h
+++ b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder.h
@@ -105,16 +105,13 @@ class LayoutTreeBuilderForElement : public LayoutTreeBuilder<Element> {
CreateLayoutObject();
}
- ComputedStyle* ResolvedStyle() const { return style_.get(); }
-
private:
LayoutObject* ParentLayoutObject() const;
LayoutObject* NextLayoutObject() const;
bool ShouldCreateLayoutObject() const;
- ComputedStyle& Style() const;
void CreateLayoutObject();
- mutable scoped_refptr<ComputedStyle> style_;
+ scoped_refptr<ComputedStyle> style_;
};
class LayoutTreeBuilderForText : public LayoutTreeBuilder<Text> {
diff --git a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.cc b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.cc
index 11da8b7a25b..9c02d00533a 100644
--- a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.cc
+++ b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.cc
@@ -304,6 +304,16 @@ LayoutObject* LayoutTreeBuilderTraversal::NextInTopLayer(
wtf_size_t position = top_layer_elements.Find(&element);
DCHECK_NE(position, kNotFound);
for (wtf_size_t i = position + 1; i < top_layer_elements.size(); ++i) {
+ if (top_layer_elements[i]->NeedsReattachLayoutTree()) {
+ // top_layer_elements[i] is either about to have its LayoutObject removed
+ // from the LayoutView or it has just been moved to the top layer and the
+ // current LayoutObject is not in LayoutView and should not be considered
+ // as a LayoutObject sibling. For the former case we could use it as a
+ // sibling, but for the latter using it as a sibling will confuse the
+ // AddChild code as it will not have a common non-anonymous layout tree
+ // ancestor.
+ continue;
+ }
if (LayoutObject* layout_object = top_layer_elements[i]->GetLayoutObject())
return layout_object;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/live_node_list_base.h b/chromium/third_party/blink/renderer/core/dom/live_node_list_base.h
index 04699837f5e..2a1d02984e0 100644
--- a/chromium/third_party/blink/renderer/core/dom/live_node_list_base.h
+++ b/chromium/third_party/blink/renderer/core/dom/live_node_list_base.h
@@ -113,21 +113,22 @@ ALWAYS_INLINE bool LiveNodeListBase::ShouldInvalidateTypeOnAttributeChange(
const QualifiedName& attr_name) {
switch (type) {
case kInvalidateOnClassAttrChange:
- return attr_name == HTMLNames::classAttr;
+ return attr_name == html_names::kClassAttr;
case kInvalidateOnNameAttrChange:
- return attr_name == HTMLNames::nameAttr;
+ return attr_name == html_names::kNameAttr;
case kInvalidateOnIdNameAttrChange:
- return attr_name == HTMLNames::idAttr || attr_name == HTMLNames::nameAttr;
+ return attr_name == html_names::kIdAttr ||
+ attr_name == html_names::kNameAttr;
case kInvalidateOnForAttrChange:
- return attr_name == HTMLNames::forAttr;
+ return attr_name == html_names::kForAttr;
case kInvalidateForFormControls:
- return attr_name == HTMLNames::nameAttr ||
- attr_name == HTMLNames::idAttr ||
- attr_name == HTMLNames::forAttr ||
- attr_name == HTMLNames::formAttr ||
- attr_name == HTMLNames::typeAttr;
+ return attr_name == html_names::kNameAttr ||
+ attr_name == html_names::kIdAttr ||
+ attr_name == html_names::kForAttr ||
+ attr_name == html_names::kFormAttr ||
+ attr_name == html_names::kTypeAttr;
case kInvalidateOnHRefAttrChange:
- return attr_name == HTMLNames::hrefAttr;
+ return attr_name == html_names::kHrefAttr;
case kDoNotInvalidateOnAttributeChanges:
return false;
case kInvalidateOnAnyAttrChange:
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer.cc b/chromium/third_party/blink/renderer/core/dom/mutation_observer.cc
index ac2ea2359e9..34227f76acd 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer.cc
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer.cc
@@ -55,9 +55,13 @@ class MutationObserver::V8DelegateImpl final
public:
static V8DelegateImpl* Create(V8MutationCallback* callback,
ExecutionContext* execution_context) {
- return new V8DelegateImpl(callback, execution_context);
+ return MakeGarbageCollected<V8DelegateImpl>(callback, execution_context);
}
+ V8DelegateImpl(V8MutationCallback* callback,
+ ExecutionContext* execution_context)
+ : ContextClient(execution_context), callback_(callback) {}
+
ExecutionContext* GetExecutionContext() const override {
return ContextClient::GetExecutionContext();
}
@@ -76,10 +80,6 @@ class MutationObserver::V8DelegateImpl final
}
private:
- V8DelegateImpl(V8MutationCallback* callback,
- ExecutionContext* execution_context)
- : ContextClient(execution_context), callback_(callback) {}
-
TraceWrapperMember<V8MutationCallback> callback_;
};
@@ -94,14 +94,15 @@ struct MutationObserver::ObserverLessThan {
MutationObserver* MutationObserver::Create(Delegate* delegate) {
DCHECK(IsMainThread());
- return new MutationObserver(delegate->GetExecutionContext(), delegate);
+ return MakeGarbageCollected<MutationObserver>(delegate->GetExecutionContext(),
+ delegate);
}
MutationObserver* MutationObserver::Create(ScriptState* script_state,
V8MutationCallback* callback) {
DCHECK(IsMainThread());
ExecutionContext* execution_context = ExecutionContext::From(script_state);
- return new MutationObserver(
+ return MakeGarbageCollected<MutationObserver>(
execution_context, V8DelegateImpl::Create(callback, execution_context));
}
@@ -116,42 +117,44 @@ MutationObserver::~MutationObserver() {
}
void MutationObserver::observe(Node* node,
- const MutationObserverInit& observer_init,
+ const MutationObserverInit* observer_init,
ExceptionState& exception_state) {
DCHECK(node);
MutationObserverOptions options = 0;
- if (observer_init.hasAttributeOldValue() && observer_init.attributeOldValue())
+ if (observer_init->hasAttributeOldValue() &&
+ observer_init->attributeOldValue())
options |= kAttributeOldValue;
HashSet<AtomicString> attribute_filter;
- if (observer_init.hasAttributeFilter()) {
- for (const auto& name : observer_init.attributeFilter())
+ if (observer_init->hasAttributeFilter()) {
+ for (const auto& name : observer_init->attributeFilter())
attribute_filter.insert(AtomicString(name));
options |= kAttributeFilter;
}
- bool attributes = observer_init.hasAttributes() && observer_init.attributes();
- if (attributes || (!observer_init.hasAttributes() &&
- (observer_init.hasAttributeOldValue() ||
- observer_init.hasAttributeFilter())))
+ bool attributes =
+ observer_init->hasAttributes() && observer_init->attributes();
+ if (attributes || (!observer_init->hasAttributes() &&
+ (observer_init->hasAttributeOldValue() ||
+ observer_init->hasAttributeFilter())))
options |= kMutationTypeAttributes;
- if (observer_init.hasCharacterDataOldValue() &&
- observer_init.characterDataOldValue())
+ if (observer_init->hasCharacterDataOldValue() &&
+ observer_init->characterDataOldValue())
options |= kCharacterDataOldValue;
bool character_data =
- observer_init.hasCharacterData() && observer_init.characterData();
- if (character_data || (!observer_init.hasCharacterData() &&
- observer_init.hasCharacterDataOldValue()))
+ observer_init->hasCharacterData() && observer_init->characterData();
+ if (character_data || (!observer_init->hasCharacterData() &&
+ observer_init->hasCharacterDataOldValue()))
options |= kMutationTypeCharacterData;
- if (observer_init.childList())
+ if (observer_init->childList())
options |= kMutationTypeChildList;
- if (observer_init.subtree())
+ if (observer_init->subtree())
options |= kSubtree;
if (!(options & kMutationTypeAttributes)) {
@@ -220,7 +223,7 @@ void MutationObserver::ObservationEnded(
static MutationObserverSet& ActiveMutationObservers() {
DEFINE_STATIC_LOCAL(Persistent<MutationObserverSet>, active_observers,
- (new MutationObserverSet));
+ (MakeGarbageCollected<MutationObserverSet>()));
return *active_observers;
}
@@ -231,13 +234,13 @@ using SlotChangeList = HeapVector<Member<HTMLSlotElement>>;
// https://html.spec.whatwg.org/multipage/browsers.html#unit-of-related-similar-origin-browsing-contexts
static SlotChangeList& ActiveSlotChangeList() {
DEFINE_STATIC_LOCAL(Persistent<SlotChangeList>, slot_change_list,
- (new SlotChangeList));
+ (MakeGarbageCollected<SlotChangeList>()));
return *slot_change_list;
}
static MutationObserverSet& SuspendedMutationObservers() {
DEFINE_STATIC_LOCAL(Persistent<MutationObserverSet>, suspended_observers,
- (new MutationObserverSet));
+ (MakeGarbageCollected<MutationObserverSet>()));
return *suspended_observers;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer.h b/chromium/third_party/blink/renderer/core/dom/mutation_observer.h
index 6b2c8ca210d..5013393edca 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer.h
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer.h
@@ -100,9 +100,10 @@ class CORE_EXPORT MutationObserver final
static void EnqueueSlotChange(HTMLSlotElement&);
static void CleanSlotChangeList(Document&);
+ MutationObserver(ExecutionContext*, Delegate*);
~MutationObserver() override;
- void observe(Node*, const MutationObserverInit&, ExceptionState&);
+ void observe(Node*, const MutationObserverInit*, ExceptionState&);
MutationRecordVector takeRecords();
void disconnect();
void ObservationStarted(MutationObserverRegistration*);
@@ -121,7 +122,6 @@ class CORE_EXPORT MutationObserver final
private:
struct ObserverLessThan;
- MutationObserver(ExecutionContext*, Delegate*);
void Deliver();
bool ShouldBeSuspended() const;
void CancelInspectorAsyncTasks();
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.cc b/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.cc
index 49d85ba1c20..e6c553ecf22 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.cc
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.cc
@@ -47,7 +47,8 @@ MutationObserverInterestGroup* MutationObserverInterestGroup::CreateIfNeeded(
if (observers.IsEmpty())
return nullptr;
- return new MutationObserverInterestGroup(observers, old_value_flag);
+ return MakeGarbageCollected<MutationObserverInterestGroup>(observers,
+ old_value_flag);
}
MutationObserverInterestGroup::MutationObserverInterestGroup(
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.h b/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.h
index bdf9c03bf95..341a5cbda19 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.h
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_interest_group.h
@@ -75,6 +75,11 @@ class MutationObserverInterestGroup final
&attribute_name);
}
+ MutationObserverInterestGroup(
+ HeapHashMap<Member<MutationObserver>, MutationRecordDeliveryOptions>&
+ observers,
+ MutationRecordDeliveryOptions old_value_flag);
+
bool IsOldValueRequested();
void EnqueueMutationRecord(MutationRecord*);
@@ -86,10 +91,6 @@ class MutationObserverInterestGroup final
MutationType,
MutationRecordDeliveryOptions old_value_flag,
const QualifiedName* attribute_name = nullptr);
- MutationObserverInterestGroup(
- HeapHashMap<Member<MutationObserver>, MutationRecordDeliveryOptions>&
- observers,
- MutationRecordDeliveryOptions old_value_flag);
bool HasOldValue(MutationRecordDeliveryOptions options) {
return options & old_value_flag_;
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.cc b/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.cc
index 8f4cc214102..156a106ee30 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.cc
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.cc
@@ -40,8 +40,8 @@ MutationObserverRegistration* MutationObserverRegistration::Create(
Node* registration_node,
MutationObserverOptions options,
const HashSet<AtomicString>& attribute_filter) {
- return new MutationObserverRegistration(observer, registration_node, options,
- attribute_filter);
+ return MakeGarbageCollected<MutationObserverRegistration>(
+ observer, registration_node, options, attribute_filter);
}
MutationObserverRegistration::MutationObserverRegistration(
@@ -80,7 +80,7 @@ void MutationObserverRegistration::ObservedSubtreeNodeWillDetach(Node& node) {
observer_->SetHasTransientRegistration();
if (!transient_registration_nodes_) {
- transient_registration_nodes_ = new NodeHashSet;
+ transient_registration_nodes_ = MakeGarbageCollected<NodeHashSet>();
DCHECK(registration_node_);
DCHECK(!registration_node_keep_alive_);
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.h b/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.h
index ff5af8ec2f9..bfcff43fb48 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.h
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_registration.h
@@ -53,6 +53,11 @@ class CORE_EXPORT MutationObserverRegistration final
Node*,
MutationObserverOptions,
const HashSet<AtomicString>& attribute_filter);
+
+ MutationObserverRegistration(MutationObserver&,
+ Node*,
+ MutationObserverOptions,
+ const HashSet<AtomicString>& attribute_filter);
~MutationObserverRegistration();
void ResetObservation(MutationObserverOptions,
@@ -89,11 +94,6 @@ class CORE_EXPORT MutationObserverRegistration final
}
private:
- MutationObserverRegistration(MutationObserver&,
- Node*,
- MutationObserverOptions,
- const HashSet<AtomicString>& attribute_filter);
-
TraceWrapperMember<MutationObserver> observer_;
WeakMember<Node> registration_node_;
Member<Node> registration_node_keep_alive_;
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_test.cc b/chromium/third_party/blink/renderer/core/dom/mutation_observer_test.cc
index b4f620ca95b..4f8b0290f53 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_test.cc
@@ -35,15 +35,15 @@ class EmptyMutationCallback : public MutationObserver::Delegate {
TEST(MutationObserverTest, DisconnectCrash) {
Persistent<Document> document = HTMLDocument::CreateForTest();
- auto* root = ToHTMLElement(document->CreateRawElement(HTMLNames::htmlTag));
+ auto* root = ToHTMLElement(document->CreateRawElement(html_names::kHTMLTag));
document->AppendChild(root);
root->SetInnerHTMLFromString("<head><title>\n</title></head><body></body>");
Node* head = root->firstChild()->firstChild();
DCHECK(head);
Persistent<MutationObserver> observer =
MutationObserver::Create(new EmptyMutationCallback(*document));
- MutationObserverInit init;
- init.setCharacterDataOldValue(false);
+ MutationObserverInit* init = MutationObserverInit::Create();
+ init->setCharacterDataOldValue(false);
observer->observe(head, init, ASSERT_NO_EXCEPTION);
head->remove();
diff --git a/chromium/third_party/blink/renderer/core/dom/name_node_list.cc b/chromium/third_party/blink/renderer/core/dom/name_node_list.cc
index 946c27b2910..eb473a200ff 100644
--- a/chromium/third_party/blink/renderer/core/dom/name_node_list.cc
+++ b/chromium/third_party/blink/renderer/core/dom/name_node_list.cc
@@ -28,8 +28,6 @@
namespace blink {
-using namespace HTMLNames;
-
NameNodeList::NameNodeList(ContainerNode& root_node, const AtomicString& name)
: LiveNodeList(root_node, kNameNodeListType, kInvalidateOnNameAttrChange),
name_(name) {}
diff --git a/chromium/third_party/blink/renderer/core/dom/name_node_list.h b/chromium/third_party/blink/renderer/core/dom/name_node_list.h
index f290cb49cfe..f496bf736d4 100644
--- a/chromium/third_party/blink/renderer/core/dom/name_node_list.h
+++ b/chromium/third_party/blink/renderer/core/dom/name_node_list.h
@@ -37,14 +37,13 @@ class CORE_EXPORT NameNodeList final : public LiveNodeList {
CollectionType type,
const AtomicString& name) {
DCHECK_EQ(type, kNameNodeListType);
- return new NameNodeList(root_node, name);
+ return MakeGarbageCollected<NameNodeList>(root_node, name);
}
+ NameNodeList(ContainerNode& root_node, const AtomicString& name);
~NameNodeList() override;
private:
- NameNodeList(ContainerNode& root_node, const AtomicString& name);
-
bool ElementMatches(const Element&) const override;
AtomicString name_;
diff --git a/chromium/third_party/blink/renderer/core/dom/named_node_map.cc b/chromium/third_party/blink/renderer/core/dom/named_node_map.cc
index 691c73b8c28..f0b19a3c7f9 100644
--- a/chromium/third_party/blink/renderer/core/dom/named_node_map.cc
+++ b/chromium/third_party/blink/renderer/core/dom/named_node_map.cc
@@ -33,8 +33,6 @@
namespace blink {
-using namespace HTMLNames;
-
Attr* NamedNodeMap::getNamedItem(const AtomicString& name) const {
return element_->getAttributeNode(name);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/named_node_map.h b/chromium/third_party/blink/renderer/core/dom/named_node_map.h
index 905c349b782..a8209b6c484 100644
--- a/chromium/third_party/blink/renderer/core/dom/named_node_map.h
+++ b/chromium/third_party/blink/renderer/core/dom/named_node_map.h
@@ -41,7 +41,12 @@ class NamedNodeMap final : public ScriptWrappable {
public:
static NamedNodeMap* Create(Element* element) {
- return new NamedNodeMap(element);
+ return MakeGarbageCollected<NamedNodeMap>(element);
+ }
+
+ explicit NamedNodeMap(Element* element) : element_(element) {
+ // Only supports NamedNodeMaps with Element associated.
+ DCHECK(element_);
}
// Public DOM interface.
@@ -67,11 +72,6 @@ class NamedNodeMap final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit NamedNodeMap(Element* element) : element_(element) {
- // Only supports NamedNodeMaps with Element associated.
- DCHECK(element_);
- }
-
Member<Element> element_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/names_map.cc b/chromium/third_party/blink/renderer/core/dom/names_map.cc
index 8acb1e5af77..ad7dbc30b11 100644
--- a/chromium/third_party/blink/renderer/core/dom/names_map.cc
+++ b/chromium/third_party/blink/renderer/core/dom/names_map.cc
@@ -45,15 +45,34 @@ void NamesMap::Add(const AtomicString& key, const AtomicString& value) {
// second and => is not used to separate key and value. It also allows an ident
// token on its own as a short-hand for forwarding with the same name.
-// The states that can occur while parsing the part map. {...} denotes the new
-// states that can be reached from this state.
+// The states that can occur while parsing the part map and their transitions.
+// A "+" indicates that this transition should consume the current character.
+// A "*" indicates that this is invalid input, usually the decision here is
+// to just do our best and recover gracefully.
enum State {
- kPreKey, // Searching for the start of a key. {kPreKey, kKey}
- kKey, // Searching for the end of a key. {kKey, kPreValue}
- kPreValue, // Searching for the start of a value. {kPreValue, kPreKey,
- // kValue}
- kValue, // Searching for the end of a value. {kValue, kPreKey, kPostValue}
- kPostValue, // Searching for the comma after the value. {kPostValue, kPreKey}
+ kPreKey, // Searching for the start of a key:
+ // space, comma, colon* -> kPreKey+
+ // else -> kKey
+ kKey, // Searching for the end of a key:
+ // comma -> kPreKey+
+ // colon -> kPreValue+
+ // space -> kPostKey+
+ // else -> kKey+
+ kPostKey, // Searching for a delimiter:
+ // comma -> kPreKey+
+ // colon -> kPreValue+
+ // space, else* -> kPostKey+
+ kPreValue, // Searching for the start of a value:
+ // comma -> kPreKey+
+ // colon*, space -> kPreValue+
+ // else -> kValue+
+ kValue, // Searching for the end of a value:
+ // comma -> kPreKey+
+ // colon*, space -> kPostValue+
+ // else -> kValue+
+ kPostValue, // Searching for the comma after the value:
+ // comma -> kPreKey+
+ // colon*, else -> kPostValue+
};
template <typename CharacterType>
@@ -69,24 +88,55 @@ void NamesMap::Set(const AtomicString& source,
State state = kPreKey;
AtomicString key;
while (cur < length) {
+ // Almost all cases break, ensuring that some input is consumed and we avoid
+ // an infinite loop. For the few transitions which should happen without
+ // consuming input we fall through into the new state's case. This makes it
+ // easy to see the cases which don't consume input and check that they lead
+ // to a case which does.
+ //
+ // The only state which should set a value for key is kKey, as we leave the
+ // state.
switch (state) {
case kPreKey:
- // Skip any number of spaces and commas. When we find something else, it
- // is the start of a key.
- if (!IsHTMLSpaceOrComma<CharacterType>(characters[cur])) {
- start = cur;
- state = kKey;
+ // Skip any number of spaces, commas and colons. When we find something
+ // else, it is the start of a key.
+ if ((IsHTMLSpaceOrComma<CharacterType>(characters[cur]) ||
+ IsColon<CharacterType>(characters[cur]))) {
+ break;
}
- break;
+ start = cur;
+ state = kKey;
+ FALLTHROUGH;
case kKey:
- // At a space or comma, we have found the end of the key.
- if (IsHTMLSpaceOrComma<CharacterType>(characters[cur])) {
+ // At a comma this was a key without a value, the implicit value is the
+ // same as the key.
+ if (IsComma<CharacterType>(characters[cur])) {
+ key = AtomicString(characters + start, cur - start);
+ Add(key, key);
+ state = kPreKey;
+ // At a colon, we have found the end of the key and we expect a value.
+ } else if (IsColon<CharacterType>(characters[cur])) {
key = AtomicString(characters + start, cur - start);
state = kPreValue;
- } else {
- break;
+ // At a space, we have found the end of the key.
+ } else if (IsHTMLSpace<CharacterType>(characters[cur])) {
+ key = AtomicString(characters + start, cur - start);
+ state = kPostKey;
}
- FALLTHROUGH;
+ break;
+ case kPostKey:
+ // At a comma this was a key without a value, the implicit value is the
+ // same as the key.
+ if (IsComma<CharacterType>(characters[cur])) {
+ Add(key, key);
+ state = kPreKey;
+ // At a colon this was a key with a value, we expect a value.
+ } else if (IsColon<CharacterType>(characters[cur])) {
+ state = kPreValue;
+ }
+ // Spaces should be consumed. We consume other characters too
+ // although the input is invalid
+ break;
case kPreValue:
// At a comma this was a key without a value, the implicit value is the
// same as the key.
@@ -95,20 +145,26 @@ void NamesMap::Set(const AtomicString& source,
state = kPreKey;
// If we reach a non-space character, we have found the start of the
// value.
- } else if (IsNotHTMLSpace<CharacterType>(characters[cur])) {
+ } else if (IsColon<CharacterType>(characters[cur]) ||
+ IsHTMLSpace<CharacterType>(characters[cur])) {
+ break;
+ } else {
start = cur;
state = kValue;
}
break;
case kValue:
- // At a comma or space, we have found the end of the value.
- if (IsHTMLSpaceOrComma<CharacterType>(characters[cur])) {
+ // At a comma, we have found the end of the value and expect
+ // the next key.
+ if (IsComma<CharacterType>(characters[cur])) {
+ Add(key, AtomicString(characters + start, cur - start));
+ state = kPreKey;
+ // At a space or colon, we have found the end of the value,
+ // although a colon is invalid here.
+ } else if (IsHTMLSpace<CharacterType>(characters[cur]) ||
+ IsColon<CharacterType>(characters[cur])) {
Add(key, AtomicString(characters + start, cur - start));
- if (IsComma<CharacterType>(characters[cur])) {
- state = kPreKey;
- } else {
- state = kPostValue;
- }
+ state = kPostValue;
}
break;
case kPostValue:
@@ -130,6 +186,7 @@ void NamesMap::Set(const AtomicString& source,
// The string ends with a key.
key = AtomicString(characters + start, cur - start);
FALLTHROUGH;
+ case kPostKey:
case kPreValue:
// The string ends after a key but with nothing else useful.
Add(key, key);
diff --git a/chromium/third_party/blink/renderer/core/dom/names_map_test.cc b/chromium/third_party/blink/renderer/core/dom/names_map_test.cc
index db30cc82447..995fade172d 100644
--- a/chromium/third_party/blink/renderer/core/dom/names_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/names_map_test.cc
@@ -29,26 +29,38 @@ TEST(NamesMapTest, Set) {
Vector<std::pair<String, ExpectedMap>> test_cases({
// Various valid values.
{"foo", {{"foo", "foo"}}},
- {"foo bar", {{"foo", "bar"}}},
- {"foo bar, foo buz", {{"foo", "bar buz"}}},
- {"foo bar, buz", {{"foo", "bar"}, {"buz", "buz"}}},
- {"foo bar, buz bar", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo, buz bar", {{"foo", "foo"}, {"buz", "bar"}}},
+ {"foo: bar", {{"foo", "bar"}}},
+ {"foo : bar", {{"foo", "bar"}}},
+ {"foo: bar, foo: buz", {{"foo", "bar buz"}}},
+ {"foo: bar, buz", {{"foo", "bar"}, {"buz", "buz"}}},
+ {"foo: bar, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo, buz: bar", {{"foo", "foo"}, {"buz", "bar"}}},
// This is an error but qux should be ignored.
- {"foo bar qux, buz bar", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo bar, buz bar qux", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar qux, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar qux", {{"foo", "bar"}, {"buz", "bar"}}},
- // This is an error but the extra comma should be ignored.
- {",foo bar, buz bar", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo bar,, buz bar", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo bar, buz bar,", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo bar, buz bar,,", {{"foo", "bar"}, {"buz", "bar"}}},
+ // This is an error but the extra commas and colons should be ignored.
+ {"foo:", {{"foo", "foo"}}},
+ {"foo:,", {{"foo", "foo"}}},
+ {"foo :", {{"foo", "foo"}}},
+ {"foo :,", {{"foo", "foo"}}},
+ {"foo: bar, buz:", {{"foo", "bar"}, {"buz", "buz"}}},
+ {"foo: bar, buz :", {{"foo", "bar"}, {"buz", "buz"}}},
+ {",foo: bar, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar,, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar,", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar,,", {{"foo", "bar"}, {"buz", "bar"}}},
+ {":foo: bar, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar:, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: :bar, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar:", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar::", {{"foo", "bar"}, {"buz", "bar"}}},
// Spaces in odd places.
- {" foo bar, buz bar", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo bar, buz bar", {{"foo", "bar"}, {"buz", "bar"}}},
- {"foo bar, buz bar ", {{"foo", "bar"}, {"buz", "bar"}}},
+ {" foo: bar, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar", {{"foo", "bar"}, {"buz", "bar"}}},
+ {"foo: bar, buz: bar ", {{"foo", "bar"}, {"buz", "bar"}}},
});
NamesMap map;
diff --git a/chromium/third_party/blink/renderer/core/dom/node.cc b/chromium/third_party/blink/renderer/core/dom/node.cc
index 600d9c401b4..89e4681f15a 100644
--- a/chromium/third_party/blink/renderer/core/dom/node.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node.cc
@@ -27,6 +27,7 @@
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/bindings/core/v8/node_or_string.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/css/css_selector.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
@@ -47,6 +48,7 @@
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
+#include "third_party/blink/renderer/core/dom/flat_tree_node_data.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/get_root_node_options.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
@@ -95,11 +97,20 @@
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
+#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/mathml_names.h"
#include "third_party/blink/renderer/core/page/context_menu_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
+#include "third_party/blink/renderer/core/page/scrolling/root_scroller_util.h"
+#include "third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h"
+#include "third_party/blink/renderer/core/page/scrolling/scroll_state.h"
+#include "third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h"
+#include "third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
+#include "third_party/blink/renderer/core/trustedtypes/trusted_script.h"
#include "third_party/blink/renderer/platform/bindings/dom_data_store.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
@@ -119,6 +130,20 @@ namespace blink {
namespace {
+// We need to retain the scroll customization callbacks until the element
+// they're associated with is destroyed. It would be simplest if the callbacks
+// could be stored in ElementRareData, but we can't afford the space increase.
+// Instead, keep the scroll customization callbacks here. The other option would
+// be to store these callbacks on the Page or document, but that necessitates a
+// bunch more logic for transferring the callbacks between Pages when elements
+// are moved around.
+ScrollCustomizationCallbacks& GetScrollCustomizationCallbacks() {
+ DEFINE_STATIC_LOCAL(Persistent<ScrollCustomizationCallbacks>,
+ scroll_customization_callbacks,
+ (new ScrollCustomizationCallbacks));
+ return *scroll_customization_callbacks;
+}
+
// TODO(crbug.com/545926): Unsafe hack to avoid triggering the
// ThreadRestrictionVerifier on StringImpl. This should be fixed completely, and
// we should always avoid accessing these strings from the impl thread.
@@ -135,7 +160,7 @@ void AppendUnsafe(StringBuilder& builder, const String& off_thread_string) {
} // namespace
-using namespace HTMLNames;
+using namespace html_names;
struct SameSizeAsNode : EventTarget {
uint32_t node_flags_;
@@ -436,9 +461,206 @@ Node& Node::TreeRoot() const {
return const_cast<Node&>(*node);
}
-Node* Node::getRootNode(const GetRootNodeOptions& options) const {
- return (options.hasComposed() && options.composed()) ? &ShadowIncludingRoot()
- : &TreeRoot();
+Node* Node::getRootNode(const GetRootNodeOptions* options) const {
+ return (options->hasComposed() && options->composed())
+ ? &ShadowIncludingRoot()
+ : &TreeRoot();
+}
+
+void Node::setDistributeScroll(V8ScrollStateCallback* scroll_state_callback,
+ const String& native_scroll_behavior) {
+ GetScrollCustomizationCallbacks().SetDistributeScroll(
+ this, ScrollStateCallbackV8Impl::Create(scroll_state_callback,
+ native_scroll_behavior));
+}
+
+void Node::setApplyScroll(V8ScrollStateCallback* scroll_state_callback,
+ const String& native_scroll_behavior) {
+ SetApplyScroll(ScrollStateCallbackV8Impl::Create(scroll_state_callback,
+ native_scroll_behavior));
+}
+
+void Node::SetApplyScroll(ScrollStateCallback* scroll_state_callback) {
+ GetScrollCustomizationCallbacks().SetApplyScroll(this, scroll_state_callback);
+}
+
+void Node::RemoveApplyScroll() {
+ GetScrollCustomizationCallbacks().RemoveApplyScroll(this);
+}
+
+ScrollStateCallback* Node::GetApplyScroll() {
+ return GetScrollCustomizationCallbacks().GetApplyScroll(this);
+}
+
+void Node::NativeDistributeScroll(ScrollState& scroll_state) {
+ if (scroll_state.FullyConsumed())
+ return;
+
+ scroll_state.distributeToScrollChainDescendant();
+
+ // The scroll doesn't propagate, and we're currently scrolling an element
+ // other than this one, prevent the scroll from propagating to this element.
+ if (scroll_state.DeltaConsumedForScrollSequence() &&
+ scroll_state.CurrentNativeScrollingNode() != this) {
+ return;
+ }
+
+ const double delta_x = scroll_state.deltaX();
+ const double delta_y = scroll_state.deltaY();
+
+ CallApplyScroll(scroll_state);
+
+ if (delta_x != scroll_state.deltaX() || delta_y != scroll_state.deltaY())
+ scroll_state.SetCurrentNativeScrollingNode(this);
+}
+
+void Node::NativeApplyScroll(ScrollState& scroll_state) {
+ if (!GetLayoutObject())
+ return;
+
+ // All elements in the scroll chain should be boxes.
+ DCHECK(GetLayoutObject()->IsBox());
+
+ if (scroll_state.FullyConsumed())
+ return;
+
+ FloatSize delta(scroll_state.deltaX(), scroll_state.deltaY());
+
+ if (delta.IsZero())
+ return;
+
+ // TODO(esprehn): This should use
+ // updateStyleAndLayoutIgnorePendingStylesheetsForNode.
+ GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
+
+ LayoutBox* box_to_scroll = ToLayoutBox(GetLayoutObject());
+
+ ScrollableArea* scrollable_area =
+ box_to_scroll->EnclosingBox()->GetScrollableArea();
+
+ if (!scrollable_area)
+ return;
+
+ ScrollResult result = scrollable_area->UserScroll(
+ ScrollGranularity(static_cast<int>(scroll_state.deltaGranularity())),
+ delta);
+
+ if (!result.DidScroll())
+ return;
+
+ // FIXME: Native scrollers should only consume the scroll they
+ // apply. See crbug.com/457765.
+ scroll_state.ConsumeDeltaNative(delta.Width(), delta.Height());
+
+ // We need to setCurrentNativeScrollingElement in both the
+ // distributeScroll and applyScroll default implementations so
+ // that if JS overrides one of these methods, but not the
+ // other, this bookkeeping remains accurate.
+ scroll_state.SetCurrentNativeScrollingNode(this);
+}
+
+void Node::CallDistributeScroll(ScrollState& scroll_state) {
+ TRACE_EVENT0("input", "Node::CallDistributeScroll");
+ ScrollStateCallback* callback =
+ GetScrollCustomizationCallbacks().GetDistributeScroll(this);
+
+ // TODO(bokan): Need to add tests before we allow calling custom callbacks
+ // for non-touch modalities. For now, just call into the native callback but
+ // allow the viewport scroll callback so we don't disable overscroll.
+ // crbug.com/623079.
+ bool disable_custom_callbacks = !scroll_state.isDirectManipulation() &&
+ !GetDocument()
+ .GetPage()
+ ->GlobalRootScrollerController()
+ .IsViewportScrollCallback(callback);
+
+ bool is_global_root_scroller =
+ GetLayoutObject() && GetLayoutObject()->IsGlobalRootScroller();
+
+ disable_custom_callbacks |=
+ !is_global_root_scroller &&
+ RuntimeEnabledFeatures::ScrollCustomizationEnabled() &&
+ !GetScrollCustomizationCallbacks().InScrollPhase(this);
+
+ if (!callback || disable_custom_callbacks) {
+ NativeDistributeScroll(scroll_state);
+ return;
+ }
+ if (callback->NativeScrollBehavior() !=
+ WebNativeScrollBehavior::kPerformAfterNativeScroll)
+ callback->Invoke(&scroll_state);
+ if (callback->NativeScrollBehavior() !=
+ WebNativeScrollBehavior::kDisableNativeScroll)
+ NativeDistributeScroll(scroll_state);
+ if (callback->NativeScrollBehavior() ==
+ WebNativeScrollBehavior::kPerformAfterNativeScroll)
+ callback->Invoke(&scroll_state);
+}
+
+void Node::CallApplyScroll(ScrollState& scroll_state) {
+ TRACE_EVENT0("input", "Node::CallApplyScroll");
+ // Hits ASSERTs when trying to determine whether we need to scroll on main
+ // or CC. http://crbug.com/625676.
+ DisableCompositingQueryAsserts disabler;
+
+ if (!GetDocument().GetPage()) {
+ // We should always have a Page if we're scrolling. See
+ // crbug.com/689074 for details.
+ return;
+ }
+
+ ScrollStateCallback* callback =
+ GetScrollCustomizationCallbacks().GetApplyScroll(this);
+
+ // TODO(bokan): Need to add tests before we allow calling custom callbacks
+ // for non-touch modalities. For now, just call into the native callback but
+ // allow the viewport scroll callback so we don't disable overscroll.
+ // crbug.com/623079.
+ bool disable_custom_callbacks = !scroll_state.isDirectManipulation() &&
+ !GetDocument()
+ .GetPage()
+ ->GlobalRootScrollerController()
+ .IsViewportScrollCallback(callback);
+
+ bool is_global_root_scroller =
+ GetLayoutObject() && GetLayoutObject()->IsGlobalRootScroller();
+
+ disable_custom_callbacks |=
+ !is_global_root_scroller &&
+ RuntimeEnabledFeatures::ScrollCustomizationEnabled() &&
+ !GetScrollCustomizationCallbacks().InScrollPhase(this);
+
+ if (!callback || disable_custom_callbacks) {
+ NativeApplyScroll(scroll_state);
+ return;
+ }
+ if (callback->NativeScrollBehavior() !=
+ WebNativeScrollBehavior::kPerformAfterNativeScroll)
+ callback->Invoke(&scroll_state);
+ if (callback->NativeScrollBehavior() !=
+ WebNativeScrollBehavior::kDisableNativeScroll)
+ NativeApplyScroll(scroll_state);
+ if (callback->NativeScrollBehavior() ==
+ WebNativeScrollBehavior::kPerformAfterNativeScroll)
+ callback->Invoke(&scroll_state);
+}
+
+void Node::WillBeginCustomizedScrollPhase(
+ scroll_customization::ScrollDirection direction) {
+ DCHECK(!GetScrollCustomizationCallbacks().InScrollPhase(this));
+ LayoutBox* box = GetLayoutBox();
+ if (!box)
+ return;
+
+ scroll_customization::ScrollDirection scroll_customization =
+ box->Style()->ScrollCustomization();
+
+ GetScrollCustomizationCallbacks().SetInScrollPhase(
+ this, direction & scroll_customization);
+}
+
+void Node::DidEndCustomizedScrollPhase() {
+ GetScrollCustomizationCallbacks().SetInScrollPhase(this, false);
}
Node* Node::insertBefore(Node* new_child,
@@ -882,6 +1104,14 @@ void Node::MarkAncestorsWithChildNeedsStyleRecalc() {
ancestor->SetChildNeedsStyleRecalc();
if (ancestor->NeedsStyleRecalc())
break;
+ // If we reach a locked ancestor, we should abort since the ancestor marking
+ // will be done when the lock is committed.
+ if (RuntimeEnabledFeatures::DisplayLockingEnabled()) {
+ if (ancestor->IsElementNode() &&
+ ToElement(ancestor)->StyleRecalcBlockedByDisplayLock()) {
+ break;
+ }
+ }
}
if (!isConnected())
return;
@@ -889,6 +1119,23 @@ void Node::MarkAncestorsWithChildNeedsStyleRecalc() {
// early return here is a performance optimization.
if (parent_dirty)
return;
+
+ // If we're in a locked subtree, then we should not update the style recalc
+ // roots. These would be updated when we commit the lock.
+ // TODO(vmpstr): There's currently no easy way to determine whether we're in a
+ // locked subtree other than navigating up the ancestor chain. We can probably
+ // do better and only do this walk if there is in fact a lock somewhere in the
+ // document.
+ if (RuntimeEnabledFeatures::DisplayLockingEnabled()) {
+ for (auto* ancestor_copy = ancestor; ancestor_copy;
+ ancestor_copy = ancestor_copy->ParentOrShadowHostNode()) {
+ if (ancestor_copy->IsElementNode() &&
+ ToElement(ancestor_copy)->StyleRecalcBlockedByDisplayLock()) {
+ return;
+ }
+ }
+ }
+
GetDocument().GetStyleEngine().UpdateStyleRecalcRoot(ancestor, this);
GetDocument().ScheduleLayoutTreeUpdateIfNeeded();
}
@@ -947,7 +1194,7 @@ void Node::SetNeedsStyleRecalc(StyleChangeType change_type,
TRACE_EVENT_INSTANT1(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"StyleRecalcInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorStyleRecalcInvalidationTrackingEvent::Data(this, reason));
+ inspector_style_recalc_invalidation_tracking_event::Data(this, reason));
StyleChangeType existing_change_type = GetStyleChangeType();
if (change_type > existing_change_type)
@@ -965,6 +1212,7 @@ void Node::SetNeedsStyleRecalc(StyleChangeType change_type,
void Node::ClearNeedsStyleRecalc() {
node_flags_ &= ~kStyleChangeMask;
+ ClearFlag(kForceReattachLayoutTree);
if (IsElementNode() && HasRareData())
ToElement(*this).SetAnimationStyleChange(false);
@@ -1004,7 +1252,7 @@ bool Node::IsInert() const {
? ToElement(this)
: FlatTreeTraversal::ParentElement(*this);
while (element) {
- if (element->hasAttribute(HTMLNames::inertAttr))
+ if (element->hasAttribute(html_names::kInertAttr))
return true;
element = FlatTreeTraversal::ParentElement(*element);
}
@@ -1028,6 +1276,21 @@ void Node::ClearNodeLists() {
RareData()->ClearNodeLists();
}
+FlatTreeNodeData& Node::EnsureFlatTreeNodeData() {
+ return EnsureRareData().EnsureFlatTreeNodeData();
+}
+
+FlatTreeNodeData* Node::GetFlatTreeNodeData() const {
+ if (!HasRareData())
+ return nullptr;
+ return RareData()->GetFlatTreeNodeData();
+}
+
+void Node::ClearFlatTreeNodeData() {
+ if (FlatTreeNodeData* data = GetFlatTreeNodeData())
+ data->Clear();
+}
+
bool Node::IsDescendantOf(const Node* other) const {
// Return true if other is an ancestor of this, otherwise false
if (!other || !other->hasChildren() || isConnected() != other->isConnected())
@@ -1164,7 +1427,6 @@ void Node::DetachLayoutTree(const AttachContext& context) {
GetLayoutObject()->DestroyAndCleanupAnonymousWrappers();
SetLayoutObject(nullptr);
SetStyleChange(kNeedsReattachStyleChange);
- ClearChildNeedsStyleInvalidation();
}
const ComputedStyle* Node::VirtualEnsureComputedStyle(
@@ -1208,7 +1470,7 @@ bool Node::CanStartSelection() const {
bool Node::IsStyledElement() const {
return IsHTMLElement() || IsSVGElement() ||
(IsElementNode() &&
- ToElement(this)->namespaceURI() == MathMLNames::mathmlNamespaceURI);
+ ToElement(this)->namespaceURI() == mathml_names::kNamespaceURI);
}
bool Node::CanParticipateInFlatTree() const {
@@ -1223,9 +1485,10 @@ bool Node::IsActiveSlotOrActiveV0InsertionPoint() const {
AtomicString Node::SlotName() const {
DCHECK(IsSlotable());
- if (IsElementNode())
+ if (IsElementNode()) {
return HTMLSlotElement::NormalizeSlotName(
- ToElement(*this).FastGetAttribute(HTMLNames::slotAttr));
+ ToElement(*this).FastGetAttribute(html_names::kSlotAttr));
+ }
DCHECK(IsTextNode());
return g_empty_atom;
}
@@ -1524,6 +1787,23 @@ String Node::textContent(bool convert_brs_to_newlines) const {
return content.ToString();
}
+void Node::setTextContent(const StringOrTrustedScript& string_or_trusted_script,
+ ExceptionState& exception_state) {
+ String value =
+ string_or_trusted_script.IsString()
+ ? string_or_trusted_script.GetAsString()
+ : string_or_trusted_script.IsTrustedScript()
+ ? string_or_trusted_script.GetAsTrustedScript()->toString()
+ : g_empty_string;
+ setTextContent(value);
+}
+
+void Node::textContent(StringOrTrustedScript& result) {
+ String value = textContent();
+ if (!value.IsNull())
+ result.SetString(value);
+}
+
void Node::setTextContent(const String& text) {
switch (getNodeType()) {
case kAttributeNode:
@@ -1776,9 +2056,9 @@ String Node::ToString() const {
builder.Append(nodeValue().EncodeForDebugging());
return builder.ToString();
}
- DumpAttributeDesc(*this, HTMLNames::idAttr, builder);
- DumpAttributeDesc(*this, HTMLNames::classAttr, builder);
- DumpAttributeDesc(*this, HTMLNames::styleAttr, builder);
+ DumpAttributeDesc(*this, html_names::kIdAttr, builder);
+ DumpAttributeDesc(*this, html_names::kClassAttr, builder);
+ DumpAttributeDesc(*this, html_names::kStyleAttr, builder);
if (HasEditableStyle(*this))
builder.Append(" (editable)");
if (GetDocument().FocusedElement() == this)
@@ -1991,7 +2271,9 @@ void Node::ShowTreeForThisAcrossFrame() const {
// --------
Element* Node::EnclosingLinkEventParentOrSelf() const {
- const Node* result = nullptr;
+ // https://crbug.com/784492
+ DCHECK(this);
+
for (const Node* node = this; node; node = FlatTreeTraversal::Parent(*node)) {
// For imagemaps, the enclosing link node is the associated area element not
// the image itself. So we don't let images be the enclosingLinkNode, even
@@ -1999,16 +2281,15 @@ Element* Node::EnclosingLinkEventParentOrSelf() const {
if (node->IsLink() && !IsHTMLImageElement(*node)) {
// Casting to Element is safe because only HTMLAnchorElement,
// HTMLImageElement and SVGAElement can return true for isLink().
- result = node;
- break;
+ return ToElement(const_cast<Node*>(node));
}
}
- return ToElement(const_cast<Node*>(result));
+ return nullptr;
}
const AtomicString& Node::InterfaceName() const {
- return EventTargetNames::Node;
+ return event_target_names::kNode;
}
ExecutionContext* Node::GetExecutionContext() const {
@@ -2110,7 +2391,7 @@ using EventTargetDataMap =
HeapHashMap<WeakMember<Node>, TraceWrapperMember<EventTargetData>>;
static EventTargetDataMap& GetEventTargetDataMap() {
DEFINE_STATIC_LOCAL(Persistent<EventTargetDataMap>, map,
- (new EventTargetDataMap));
+ (MakeGarbageCollected<EventTargetDataMap>()));
return *map;
}
@@ -2123,7 +2404,7 @@ EventTargetData& Node::EnsureEventTargetData() {
return *GetEventTargetDataMap().at(this);
DCHECK(!GetEventTargetDataMap().Contains(this));
SetHasEventTargetData(true);
- EventTargetData* data = new EventTargetData;
+ EventTargetData* data = MakeGarbageCollected<EventTargetData>();
GetEventTargetDataMap().Set(this, data);
return *data;
}
@@ -2280,8 +2561,8 @@ void Node::HandleLocalEvents(Event& event) {
if (HasEventListeners(event.type())) {
UseCounter::Count(GetDocument(),
WebFeature::kDispatchMouseEventOnDisabledFormControl);
- if (event.type() == EventTypeNames::mousedown ||
- event.type() == EventTypeNames::mouseup) {
+ if (event.type() == event_type_names::kMousedown ||
+ event.type() == event_type_names::kMouseup) {
UseCounter::Count(
GetDocument(),
WebFeature::kDispatchMouseUpDownEventOnDisabledFormControl);
@@ -2313,8 +2594,8 @@ void Node::DispatchSubtreeModifiedEvent() {
if (!GetDocument().HasListenerType(Document::kDOMSubtreeModifiedListener))
return;
- DispatchScopedEvent(*MutationEvent::Create(EventTypeNames::DOMSubtreeModified,
- Event::Bubbles::kYes));
+ DispatchScopedEvent(*MutationEvent::Create(
+ event_type_names::kDOMSubtreeModified, Event::Bubbles::kYes));
}
DispatchEventResult Node::DispatchDOMActivateEvent(int detail,
@@ -2323,7 +2604,7 @@ DispatchEventResult Node::DispatchDOMActivateEvent(int detail,
DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
UIEvent& event = *UIEvent::Create();
- event.initUIEvent(EventTypeNames::DOMActivate, true, true,
+ event.initUIEvent(event_type_names::kDOMActivate, true, true,
GetDocument().domWindow(), detail);
event.SetUnderlyingEvent(&underlying_event);
event.SetComposed(underlying_event.composed());
@@ -2343,41 +2624,44 @@ void Node::DispatchSimulatedClick(Event* underlying_event,
void Node::DispatchInputEvent() {
// Legacy 'input' event for forms set value and checked.
- DispatchScopedEvent(*Event::CreateBubble(EventTypeNames::input));
+ Event* event = Event::CreateBubble(event_type_names::kInput);
+ event->SetComposed(true);
+ DispatchScopedEvent(*event);
}
void Node::DefaultEventHandler(Event& event) {
if (event.target() != this)
return;
const AtomicString& event_type = event.type();
- if (event_type == EventTypeNames::keydown ||
- event_type == EventTypeNames::keypress) {
+ if (event_type == event_type_names::kKeydown ||
+ event_type == event_type_names::kKeypress) {
if (event.IsKeyboardEvent()) {
if (LocalFrame* frame = GetDocument().GetFrame()) {
frame->GetEventHandler().DefaultKeyboardEventHandler(
ToKeyboardEvent(&event));
}
}
- } else if (event_type == EventTypeNames::click) {
+ } else if (event_type == event_type_names::kClick) {
int detail = event.IsUIEvent() ? ToUIEvent(event).detail() : 0;
if (DispatchDOMActivateEvent(detail, event) !=
DispatchEventResult::kNotCanceled)
event.SetDefaultHandled();
- } else if (event_type == EventTypeNames::contextmenu &&
+ } else if (event_type == event_type_names::kContextmenu &&
event.IsMouseEvent()) {
if (Page* page = GetDocument().GetPage()) {
page->GetContextMenuController().HandleContextMenuEvent(
ToMouseEvent(&event));
}
- } else if (event_type == EventTypeNames::textInput) {
- if (event.HasInterface(EventNames::TextEvent)) {
+ } else if (event_type == event_type_names::kTextInput) {
+ if (event.HasInterface(event_interface_names::kTextEvent)) {
if (LocalFrame* frame = GetDocument().GetFrame()) {
frame->GetEventHandler().DefaultTextInputEventHandler(
ToTextEvent(&event));
}
}
} else if (RuntimeEnabledFeatures::MiddleClickAutoscrollEnabled() &&
- event_type == EventTypeNames::mousedown && event.IsMouseEvent()) {
+ event_type == event_type_names::kMousedown &&
+ event.IsMouseEvent()) {
auto& mouse_event = ToMouseEvent(event);
if (mouse_event.button() ==
static_cast<short>(WebPointerProperties::Button::kMiddle)) {
@@ -2407,7 +2691,7 @@ void Node::DefaultEventHandler(Event& event) {
frame->GetEventHandler().StartMiddleClickAutoscroll(layout_object);
}
}
- } else if (event_type == EventTypeNames::mouseup && event.IsMouseEvent()) {
+ } else if (event_type == event_type_names::kMouseup && event.IsMouseEvent()) {
auto& mouse_event = ToMouseEvent(event);
if (mouse_event.button() ==
static_cast<short>(WebPointerProperties::Button::kBack)) {
@@ -2432,7 +2716,7 @@ void Node::WillCallDefaultEventHandler(const Event& event) {
if (!IsFocused() || GetDocument().LastFocusType() != kWebFocusTypeMouse)
return;
- if (event.type() != EventTypeNames::keydown ||
+ if (event.type() != event_type_names::kKeydown ||
GetDocument().HadKeyboardEvent())
return;
@@ -2456,9 +2740,9 @@ bool Node::HasActivationBehavior() const {
bool Node::WillRespondToMouseMoveEvents() {
if (IsDisabledFormControl(this))
return false;
- return HasEventListeners(EventTypeNames::mousemove) ||
- HasEventListeners(EventTypeNames::mouseover) ||
- HasEventListeners(EventTypeNames::mouseout);
+ return HasEventListeners(event_type_names::kMousemove) ||
+ HasEventListeners(event_type_names::kMouseover) ||
+ HasEventListeners(event_type_names::kMouseout);
}
bool Node::WillRespondToMouseClickEvents() {
@@ -2466,19 +2750,19 @@ bool Node::WillRespondToMouseClickEvents() {
return false;
GetDocument().UpdateStyleAndLayoutTree();
return HasEditableStyle(*this) ||
- HasEventListeners(EventTypeNames::mouseup) ||
- HasEventListeners(EventTypeNames::mousedown) ||
- HasEventListeners(EventTypeNames::click) ||
- HasEventListeners(EventTypeNames::DOMActivate);
+ HasEventListeners(event_type_names::kMouseup) ||
+ HasEventListeners(event_type_names::kMousedown) ||
+ HasEventListeners(event_type_names::kClick) ||
+ HasEventListeners(event_type_names::kDOMActivate);
}
bool Node::WillRespondToTouchEvents() {
if (IsDisabledFormControl(this))
return false;
- return HasEventListeners(EventTypeNames::touchstart) ||
- HasEventListeners(EventTypeNames::touchmove) ||
- HasEventListeners(EventTypeNames::touchcancel) ||
- HasEventListeners(EventTypeNames::touchend);
+ return HasEventListeners(event_type_names::kTouchstart) ||
+ HasEventListeners(event_type_names::kTouchmove) ||
+ HasEventListeners(event_type_names::kTouchcancel) ||
+ HasEventListeners(event_type_names::kTouchend);
}
unsigned Node::ConnectedSubframeCount() const {
@@ -2690,6 +2974,11 @@ void Node::CheckSlotChange(SlotChangeType slot_change_type) {
}
}
+bool Node::IsEffectiveRootScroller() const {
+ return GetLayoutObject() ? GetLayoutObject()->IsEffectiveRootScroller()
+ : false;
+}
+
WebPluginContainerImpl* Node::GetWebPluginContainer() const {
if (!IsHTMLObjectElement(this) && !IsHTMLEmbedElement(this)) {
return nullptr;
diff --git a/chromium/third_party/blink/renderer/core/dom/node.h b/chromium/third_party/blink/renderer/core/dom/node.h
index 20acc9cae2a..32e30eb5b52 100644
--- a/chromium/third_party/blink/renderer/core/dom/node.h
+++ b/chromium/third_party/blink/renderer/core/dom/node.h
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/dom/mutation_observer_options.h"
#include "third_party/blink/renderer/core/dom/node_rare_data.h"
#include "third_party/blink/renderer/core/dom/tree_scope.h"
+#include "third_party/blink/renderer/core/scroll/scroll_customization.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
@@ -50,6 +51,7 @@ class Element;
class Event;
class EventDispatchHandlingState;
class ExceptionState;
+class FlatTreeNodeData;
class GetRootNodeOptions;
class HTMLQualifiedName;
class HTMLSlotElement;
@@ -67,11 +69,15 @@ class NodeRareData;
class QualifiedName;
class RegisteredEventListener;
class SVGQualifiedName;
+class ScrollState;
+class ScrollStateCallback;
class ShadowRoot;
template <typename NodeType>
class StaticNodeTypeList;
using StaticNodeList = StaticNodeTypeList<Node>;
+class StringOrTrustedScript;
class StyleChangeReasonForTracing;
+class V8ScrollStateCallback;
class WebPluginContainerImpl;
const int kNodeStyleChangeShift = 18;
@@ -189,7 +195,23 @@ class CORE_EXPORT Node : public EventTarget {
NodeList* childNodes();
Node* firstChild() const;
Node* lastChild() const;
- Node* getRootNode(const GetRootNodeOptions&) const;
+ Node* getRootNode(const GetRootNodeOptions*) const;
+
+ // Scroll Customization API. See crbug.com/410974 for details.
+ void setDistributeScroll(V8ScrollStateCallback*,
+ const String& native_scroll_behavior);
+ void setApplyScroll(V8ScrollStateCallback*,
+ const String& native_scroll_behavior);
+ void SetApplyScroll(ScrollStateCallback*);
+ void RemoveApplyScroll();
+ ScrollStateCallback* GetApplyScroll();
+ void NativeDistributeScroll(ScrollState&);
+ void NativeApplyScroll(ScrollState&);
+ void CallDistributeScroll(ScrollState&);
+ void CallApplyScroll(ScrollState&);
+ void WillBeginCustomizedScrollPhase(scroll_customization::ScrollDirection);
+ void DidEndCustomizedScrollPhase();
+
Node& TreeRoot() const;
Node& ShadowIncludingRoot() const;
// closed-shadow-hidden is defined at
@@ -236,6 +258,8 @@ class CORE_EXPORT Node : public EventTarget {
String textContent(bool convert_brs_to_newlines = false) const;
void setTextContent(const String&);
+ void textContent(StringOrTrustedScript& result);
+ virtual void setTextContent(const StringOrTrustedScript&, ExceptionState&);
bool SupportsAltText();
@@ -442,6 +466,9 @@ class CORE_EXPORT Node : public EventTarget {
void SetNeedsStyleRecalc(StyleChangeType, const StyleChangeReasonForTracing&);
void ClearNeedsStyleRecalc();
+ // Propagates a dirty bit breadcrumb for this element up the ancestor chain.
+ void MarkAncestorsWithChildNeedsStyleRecalc();
+
bool NeedsReattachLayoutTree() const {
return GetFlag(kNeedsReattachLayoutTree);
}
@@ -461,6 +488,11 @@ class CORE_EXPORT Node : public EventTarget {
void MarkAncestorsWithChildNeedsReattachLayoutTree();
+ void SetForceReattachLayoutTree() { SetFlag(kForceReattachLayoutTree); }
+ bool GetForceReattachLayoutTree() {
+ return GetFlag(kForceReattachLayoutTree);
+ }
+
bool NeedsDistributionRecalc() const;
bool ChildNeedsDistributionRecalc() const {
@@ -512,7 +544,7 @@ class CORE_EXPORT Node : public EventTarget {
// Please don't use this function.
// Background: When we investigated the usage of (old) UpdateDistribution,
- // some caller's intents were unclear. Thus, we had to introduce this funtion
+ // some caller's intents were unclear. Thus, we had to introduce this function
// for the sake of safety. If we can figure out the intent of each caller, we
// can replace that with calling UpdateDistributionForFlatTreeTraversal (or
// just RecalcSlotAssignments()) on a case-by-case basis.
@@ -611,7 +643,7 @@ class CORE_EXPORT Node : public EventTarget {
// Whether or not a selection can be started in this object
virtual bool CanStartSelection() const;
- // -----------------------------------------------------------------------------
+ // ---------------------------------------------------------------------------
// Integration with layout tree
// As layoutObject() includes a branch you should avoid calling it repeatedly
@@ -637,7 +669,6 @@ class CORE_EXPORT Node : public EventTarget {
// objects when we need to do whitespace re-attachment.
LayoutObject* previous_in_flow = nullptr;
bool performing_reattach = false;
- bool clear_invalidation = false;
// True if the previous_in_flow member is up-to-date, even if it is nullptr.
bool use_previous_in_flow = false;
@@ -666,20 +697,26 @@ class CORE_EXPORT Node : public EventTarget {
// such a method (on Document and Element).
bool ShouldCallRecalcStyle(StyleRecalcChange);
+ // ---------------------------------------------------------------------------
+ // Inline ComputedStyle accessors
+ //
+ // Note that the following 'inline' functions are not defined in this header,
+ // but in node_computed_style.h. Please include that file if you want to use
+ // these functions.
+
// Wrapper for nodes that don't have a layoutObject, but still cache the style
// (like HTMLOptionElement).
- ComputedStyle* MutableComputedStyle() const;
- const ComputedStyle* GetComputedStyle() const;
- const ComputedStyle* ParentComputedStyle() const;
-
- const ComputedStyle& ComputedStyleRef() const;
+ inline ComputedStyle* MutableComputedStyle() const;
+ inline const ComputedStyle* GetComputedStyle() const;
+ inline const ComputedStyle* ParentComputedStyle() const;
+ inline const ComputedStyle& ComputedStyleRef() const;
const ComputedStyle* EnsureComputedStyle(
PseudoId pseudo_element_specifier = kPseudoIdNone) {
return VirtualEnsureComputedStyle(pseudo_element_specifier);
}
- // -----------------------------------------------------------------------------
+ // ---------------------------------------------------------------------------
// Notification of document structure changes (see container_node.h for more
// notification methods)
//
@@ -743,6 +780,10 @@ class CORE_EXPORT Node : public EventTarget {
NodeListsNodeData* NodeLists();
void ClearNodeLists();
+ FlatTreeNodeData* GetFlatTreeNodeData() const;
+ FlatTreeNodeData& EnsureFlatTreeNodeData();
+ void ClearFlatTreeNodeData();
+
virtual bool WillRespondToMouseMoveEvents();
virtual bool WillRespondToMouseClickEvents();
virtual bool WillRespondToTouchEvents();
@@ -842,6 +883,8 @@ class CORE_EXPORT Node : public EventTarget {
return GetFlag(kInDOMNodeRemovedHandler);
}
+ bool IsEffectiveRootScroller() const;
+
// If the node is a plugin, then this returns its WebPluginContainer.
WebPluginContainerImpl* GetWebPluginContainer() const;
@@ -900,11 +943,13 @@ class CORE_EXPORT Node : public EventTarget {
// Temporary flag for some UseCounter items. crbug.com/859391.
kInDOMNodeRemovedHandler = 1 << 29,
+ kForceReattachLayoutTree = 1 << 30,
+
kDefaultNodeFlags =
kIsFinishedParsingChildrenFlag | kNeedsReattachStyleChange
};
- // 3 bits remaining.
+ // 1 bit remaining.
bool GetFlag(NodeFlags mask) const { return node_flags_ & mask; }
void SetFlag(bool f, NodeFlags mask) {
@@ -928,8 +973,6 @@ class CORE_EXPORT Node : public EventTarget {
kCreateDocument = kCreateContainer | kIsConnectedFlag,
kCreateV0InsertionPoint = kCreateHTMLElement | kIsV0InsertionPointFlag,
kCreateEditingText = kCreateText | kHasNameOrIsEditingTextFlag,
- kCreatePseudoElement = kDefaultNodeFlags | kIsContainerFlag |
- kIsElementFlag | kNeedsReattachLayoutTree,
};
Node(TreeScope*, ConstructionType);
@@ -963,7 +1006,6 @@ class CORE_EXPORT Node : public EventTarget {
void SetTreeScope(TreeScope* scope) { tree_scope_ = scope; }
- void MarkAncestorsWithChildNeedsStyleRecalc();
static void MarkAncestorsWithChildNeedsStyleRecalc(Node* child) {
child->MarkAncestorsWithChildNeedsStyleRecalc();
}
diff --git a/chromium/third_party/blink/renderer/core/dom/node.idl b/chromium/third_party/blink/renderer/core/dom/node.idl
index bc3277043de..73f5989dc29 100644
--- a/chromium/third_party/blink/renderer/core/dom/node.idl
+++ b/chromium/third_party/blink/renderer/core/dom/node.idl
@@ -38,6 +38,10 @@ interface Node : EventTarget {
readonly attribute USVString baseURI;
+ // Scroll Customization API. See crbug.com/410974 for details.
+ [RuntimeEnabled=ScrollCustomization] void setApplyScroll(ScrollStateCallback scrollStateCallback, NativeScrollBehavior nativeScrollBehavior);
+ [RuntimeEnabled=ScrollCustomization] void setDistributeScroll(ScrollStateCallback scrollStateCallback, NativeScrollBehavior nativeScrollBehavior);
+
[Affects=Nothing, Measure] readonly attribute boolean isConnected;
[Affects=Nothing, PerWorldBindings] readonly attribute Document? ownerDocument;
[Affects=Nothing, PerWorldBindings, ImplementedAs=ParentNodeWithCounting] readonly attribute Node? parentNode;
@@ -52,7 +56,7 @@ interface Node : EventTarget {
[Affects=Nothing, CEReactions, CustomElementCallbacks] attribute DOMString? nodeValue;
- [Affects=Nothing, CEReactions, CustomElementCallbacks] attribute DOMString? textContent;
+ [Affects=Nothing, CEReactions, CustomElementCallbacks, RaisesException=Setter] attribute ScriptString? textContent;
[CEReactions, CustomElementCallbacks] void normalize();
[NewObject, DoNotTestNewObject, CEReactions, CustomElementCallbacks, RaisesException] Node cloneNode(optional boolean deep = false);
diff --git a/chromium/third_party/blink/renderer/core/dom/node_iterator.cc b/chromium/third_party/blink/renderer/core/dom/node_iterator.cc
index eae9578a213..7c514b0bee0 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_iterator.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node_iterator.cc
@@ -185,7 +185,7 @@ void NodeIterator::UpdateForNodeRemoval(Node& removed_node,
if (node)
reference_node.node = node;
} else {
- // FIXME: This branch doesn't appear to have any LayoutTests.
+ // FIXME: This branch doesn't appear to have any web tests.
node = NodeTraversal::Next(removed_node, root());
// Move out from under the node being removed if the reference node is
// a descendant of the node being removed.
diff --git a/chromium/third_party/blink/renderer/core/dom/node_iterator.h b/chromium/third_party/blink/renderer/core/dom/node_iterator.h
index 8fb47a744d7..b3707560da9 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_iterator.h
+++ b/chromium/third_party/blink/renderer/core/dom/node_iterator.h
@@ -41,9 +41,11 @@ class NodeIterator final : public ScriptWrappable, public NodeIteratorBase {
static NodeIterator* Create(Node* root_node,
unsigned what_to_show,
V8NodeFilter* filter) {
- return new NodeIterator(root_node, what_to_show, filter);
+ return MakeGarbageCollected<NodeIterator>(root_node, what_to_show, filter);
}
+ NodeIterator(Node*, unsigned what_to_show, V8NodeFilter*);
+
Node* nextNode(ExceptionState&);
Node* previousNode(ExceptionState&);
void detach();
@@ -59,8 +61,6 @@ class NodeIterator final : public ScriptWrappable, public NodeIteratorBase {
void Trace(blink::Visitor*) override;
private:
- NodeIterator(Node*, unsigned what_to_show, V8NodeFilter*);
-
class NodePointer {
DISALLOW_NEW();
diff --git a/chromium/third_party/blink/renderer/core/dom/node_lists_node_data.h b/chromium/third_party/blink/renderer/core/dom/node_lists_node_data.h
index 74ee59eb2e7..e562e8badda 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_lists_node_data.h
+++ b/chromium/third_party/blink/renderer/core/dom/node_lists_node_data.h
@@ -136,7 +136,11 @@ class NodeListsNodeData final : public GarbageCollected<NodeListsNodeData> {
return list;
}
- static NodeListsNodeData* Create() { return new NodeListsNodeData; }
+ static NodeListsNodeData* Create() {
+ return MakeGarbageCollected<NodeListsNodeData>();
+ }
+
+ NodeListsNodeData() : child_node_list_(nullptr) {}
void InvalidateCaches(const QualifiedName* attr_name = nullptr);
@@ -173,8 +177,6 @@ class NodeListsNodeData final : public GarbageCollected<NodeListsNodeData> {
void Trace(blink::Visitor*);
private:
- NodeListsNodeData() : child_node_list_(nullptr) {}
-
// Can be a ChildNodeList or an EmptyNodeList.
TraceWrapperMember<NodeList> child_node_list_;
NodeListAtomicNameCacheMap atomic_name_caches_;
diff --git a/chromium/third_party/blink/renderer/core/dom/node_rare_data.cc b/chromium/third_party/blink/renderer/core/dom/node_rare_data.cc
index f340e29198f..89c6f58e7d3 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_rare_data.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node_rare_data.cc
@@ -33,6 +33,7 @@
#include "third_party/blink/renderer/core/dom/container_node.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/element_rare_data.h"
+#include "third_party/blink/renderer/core/dom/flat_tree_node_data.h"
#include "third_party/blink/renderer/core/dom/mutation_observer_registration.h"
#include "third_party/blink/renderer/core/dom/node_lists_node_data.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -43,12 +44,12 @@ namespace blink {
struct SameSizeAsNodeRareData {
void* pointer_;
- Member<void*> willbe_member_[2];
+ Member<void*> willbe_member_[3];
unsigned bitfields_;
};
NodeMutationObserverData* NodeMutationObserverData::Create() {
- return new NodeMutationObserverData;
+ return MakeGarbageCollected<NodeMutationObserverData>();
}
static_assert(sizeof(NodeRareData) == sizeof(SameSizeAsNodeRareData),
@@ -83,6 +84,7 @@ void NodeMutationObserverData::RemoveRegistration(
void NodeRareData::TraceAfterDispatch(blink::Visitor* visitor) {
visitor->Trace(mutation_observer_data_);
+ visitor->Trace(flat_tree_node_data_);
// Do not keep empty NodeListsNodeData objects around.
if (node_lists_ && node_lists_->IsEmpty())
node_lists_.Clear();
@@ -114,6 +116,12 @@ NodeListsNodeData& NodeRareData::CreateNodeLists() {
return *node_lists_;
}
+FlatTreeNodeData& NodeRareData::EnsureFlatTreeNodeData() {
+ if (!flat_tree_node_data_)
+ flat_tree_node_data_ = MakeGarbageCollected<FlatTreeNodeData>();
+ return *flat_tree_node_data_;
+}
+
// Ensure the 10 bits reserved for the connected_frame_count_ cannot overflow.
static_assert(Page::kMaxNumberOfFrames <
(1 << NodeRareData::kConnectedFrameCountBits),
diff --git a/chromium/third_party/blink/renderer/core/dom/node_rare_data.h b/chromium/third_party/blink/renderer/core/dom/node_rare_data.h
index 394632d899b..2e4ec9c7c6a 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_rare_data.h
+++ b/chromium/third_party/blink/renderer/core/dom/node_rare_data.h
@@ -32,6 +32,7 @@ namespace blink {
class ComputedStyle;
enum class DynamicRestyleFlags;
enum class ElementFlags;
+class FlatTreeNodeData;
class LayoutObject;
class MutationObserverRegistration;
class NodeListsNodeData;
@@ -41,6 +42,8 @@ class NodeMutationObserverData final
public:
static NodeMutationObserverData* Create();
+ NodeMutationObserverData() = default;
+
const HeapVector<TraceWrapperMember<MutationObserverRegistration>>&
Registry() {
return registry_;
@@ -59,8 +62,6 @@ class NodeMutationObserverData final
void Trace(blink::Visitor* visitor);
private:
- NodeMutationObserverData() = default;
-
HeapVector<TraceWrapperMember<MutationObserverRegistration>> registry_;
HeapHashSet<TraceWrapperMember<MutationObserverRegistration>>
transient_registry_;
@@ -119,7 +120,16 @@ class NodeRareData : public GarbageCollectedFinalized<NodeRareData>,
public NodeRareDataBase {
public:
static NodeRareData* Create(NodeRenderingData* node_layout_data) {
- return new NodeRareData(node_layout_data);
+ return MakeGarbageCollected<NodeRareData>(node_layout_data);
+ }
+
+ explicit NodeRareData(NodeRenderingData* node_layout_data)
+ : NodeRareDataBase(node_layout_data),
+ connected_frame_count_(0),
+ element_flags_(0),
+ restyle_flags_(0),
+ is_element_rare_data_(false) {
+ CHECK_NE(node_layout_data, nullptr);
}
void ClearNodeLists() { node_lists_.Clear(); }
@@ -134,6 +144,9 @@ class NodeRareData : public GarbageCollectedFinalized<NodeRareData>,
return *node_lists_;
}
+ FlatTreeNodeData* GetFlatTreeNodeData() const { return flat_tree_node_data_; }
+ FlatTreeNodeData& EnsureFlatTreeNodeData();
+
NodeMutationObserverData* MutationObserverData() {
return mutation_observer_data_.Get();
}
@@ -182,21 +195,12 @@ class NodeRareData : public GarbageCollectedFinalized<NodeRareData>,
void TraceAfterDispatch(blink::Visitor*);
void FinalizeGarbageCollectedObject();
- protected:
- explicit NodeRareData(NodeRenderingData* node_layout_data)
- : NodeRareDataBase(node_layout_data),
- connected_frame_count_(0),
- element_flags_(0),
- restyle_flags_(0),
- is_element_rare_data_(false) {
- CHECK_NE(node_layout_data, nullptr);
- }
-
private:
NodeListsNodeData& CreateNodeLists();
TraceWrapperMember<NodeListsNodeData> node_lists_;
TraceWrapperMember<NodeMutationObserverData> mutation_observer_data_;
+ Member<FlatTreeNodeData> flat_tree_node_data_;
unsigned connected_frame_count_ : kConnectedFrameCountBits;
unsigned element_flags_ : kNumberOfElementFlags;
diff --git a/chromium/third_party/blink/renderer/core/dom/node_test.cc b/chromium/third_party/blink/renderer/core/dom/node_test.cc
index 6f0641ce0b5..56563b04feb 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node_test.cc
@@ -267,7 +267,7 @@ TEST_F(NodeTest, AttachContext_PreviousInFlow_Slotted) {
ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString(
"<div id=root style='display:contents'><span></span><slot></slot></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* root = shadow_root.getElementById("root");
Element* span = GetDocument().getElementById("inline");
@@ -297,19 +297,21 @@ TEST_F(NodeTest, HasMediaControlAncestor_Fail) {
}
TEST_F(NodeTest, HasMediaControlAncestor_MediaControlElement) {
- FakeMediaControlElement* node = new FakeMediaControlElement(GetDocument());
+ FakeMediaControlElement* node =
+ MakeGarbageCollected<FakeMediaControlElement>(GetDocument());
EXPECT_TRUE(node->HasMediaControlAncestor());
EXPECT_TRUE(InitializeUserAgentShadowTree(node)->HasMediaControlAncestor());
}
TEST_F(NodeTest, HasMediaControlAncestor_MediaControls) {
- FakeMediaControls* node = new FakeMediaControls(GetDocument());
+ FakeMediaControls* node =
+ MakeGarbageCollected<FakeMediaControls>(GetDocument());
EXPECT_TRUE(node->HasMediaControlAncestor());
EXPECT_TRUE(InitializeUserAgentShadowTree(node)->HasMediaControlAncestor());
}
TEST_F(NodeTest, appendChildProcessingInstructionNoStyleRecalc) {
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetDocument().ChildNeedsStyleRecalc());
ProcessingInstruction* pi =
ProcessingInstruction::Create(GetDocument(), "A", "B");
@@ -318,7 +320,7 @@ TEST_F(NodeTest, appendChildProcessingInstructionNoStyleRecalc) {
}
TEST_F(NodeTest, appendChildCommentNoStyleRecalc) {
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetDocument().ChildNeedsStyleRecalc());
Comment* comment = Comment::Create(GetDocument(), "comment");
GetDocument().body()->appendChild(comment, ASSERT_NO_EXCEPTION);
@@ -331,7 +333,7 @@ TEST_F(NodeTest, LazyReattachCommentAndPI) {
ProcessingInstruction* pi =
ProcessingInstruction::Create(GetDocument(), "A", "B");
body->appendChild(pi, ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* comment = body->firstChild();
EXPECT_EQ(Node::kCommentNode, comment->getNodeType());
diff --git a/chromium/third_party/blink/renderer/core/dom/nth_index_cache.cc b/chromium/third_party/blink/renderer/core/dom/nth_index_cache.cc
index 988c02cdaf3..8c31f852a2c 100644
--- a/chromium/third_party/blink/renderer/core/dom/nth_index_cache.cc
+++ b/chromium/third_party/blink/renderer/core/dom/nth_index_cache.cc
@@ -152,23 +152,24 @@ unsigned NthIndexCache::NthLastOfTypeIndex(Element& element) {
void NthIndexCache::CacheNthIndexDataForParent(Element& element) {
DCHECK(element.parentNode());
if (!parent_map_)
- parent_map_ = new ParentMap();
+ parent_map_ = MakeGarbageCollected<ParentMap>();
ParentMap::AddResult add_result =
parent_map_->insert(element.parentNode(), nullptr);
DCHECK(add_result.is_new_entry);
- add_result.stored_value->value = new NthIndexData(*element.parentNode());
+ add_result.stored_value->value =
+ MakeGarbageCollected<NthIndexData>(*element.parentNode());
}
NthIndexCache::IndexByType& NthIndexCache::EnsureTypeIndexMap(
ContainerNode& parent) {
if (!parent_map_for_type_)
- parent_map_for_type_ = new ParentMapForType();
+ parent_map_for_type_ = MakeGarbageCollected<ParentMapForType>();
ParentMapForType::AddResult add_result =
parent_map_for_type_->insert(&parent, nullptr);
if (add_result.is_new_entry)
- add_result.stored_value->value = new IndexByType();
+ add_result.stored_value->value = MakeGarbageCollected<IndexByType>();
DCHECK(add_result.stored_value->value);
return *add_result.stored_value->value;
@@ -179,8 +180,8 @@ void NthIndexCache::CacheNthOfTypeIndexDataForParent(Element& element) {
IndexByType::AddResult add_result = EnsureTypeIndexMap(*element.parentNode())
.insert(element.tagName(), nullptr);
DCHECK(add_result.is_new_entry);
- add_result.stored_value->value =
- new NthIndexData(*element.parentNode(), element.TagQName());
+ add_result.stored_value->value = MakeGarbageCollected<NthIndexData>(
+ *element.parentNode(), element.TagQName());
}
unsigned NthIndexData::NthIndex(Element& element) const {
diff --git a/chromium/third_party/blink/renderer/core/dom/pausable_object_test.cc b/chromium/third_party/blink/renderer/core/dom/pausable_object_test.cc
index 3d4081bd4c3..c43ea1e1457 100644
--- a/chromium/third_party/blink/renderer/core/dom/pausable_object_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/pausable_object_test.cc
@@ -73,8 +73,8 @@ class PausableObjectTest : public testing::Test {
PausableObjectTest::PausableObjectTest()
: src_page_holder_(DummyPageHolder::Create(IntSize(800, 600))),
dest_page_holder_(DummyPageHolder::Create(IntSize(800, 600))),
- pausable_object_(
- new MockPausableObject(&src_page_holder_->GetDocument())) {
+ pausable_object_(MakeGarbageCollected<MockPausableObject>(
+ &src_page_holder_->GetDocument())) {
pausable_object_->PauseIfNeeded();
}
diff --git a/chromium/third_party/blink/renderer/core/dom/presentation_attribute_style.cc b/chromium/third_party/blink/renderer/core/dom/presentation_attribute_style.cc
index 6fd4deabd8a..78e52699a7d 100644
--- a/chromium/third_party/blink/renderer/core/dom/presentation_attribute_style.cc
+++ b/chromium/third_party/blink/renderer/core/dom/presentation_attribute_style.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
struct PresentationAttributeCacheKey {
PresentationAttributeCacheKey() : tag_name(nullptr) {}
@@ -76,7 +76,7 @@ using PresentationAttributeCache =
AlreadyHashed>;
static PresentationAttributeCache& GetPresentationAttributeCache() {
DEFINE_STATIC_LOCAL(Persistent<PresentationAttributeCache>, cache,
- (new PresentationAttributeCache));
+ (MakeGarbageCollected<PresentationAttributeCache>()));
return *cache;
}
@@ -105,7 +105,7 @@ static void MakePresentationAttributeCacheKey(
return;
// FIXME: Background URL may depend on the base URL and can't be shared.
// Disallow caching.
- if (attr.GetName() == backgroundAttr)
+ if (attr.GetName() == kBackgroundAttr)
return;
result.attributes_and_values.push_back(
std::make_pair(attr.LocalName().Impl(), attr.Value()));
@@ -182,7 +182,7 @@ CSSPropertyValueSet* ComputePresentationAttributeStyle(Element& element) {
return style;
PresentationAttributeCacheEntry* new_entry =
- new PresentationAttributeCacheEntry;
+ MakeGarbageCollected<PresentationAttributeCacheEntry>();
new_entry->key = cache_key;
new_entry->value = style;
diff --git a/chromium/third_party/blink/renderer/core/dom/processing_instruction.cc b/chromium/third_party/blink/renderer/core/dom/processing_instruction.cc
index bfe8e343948..8178485b71f 100644
--- a/chromium/third_party/blink/renderer/core/dom/processing_instruction.cc
+++ b/chromium/third_party/blink/renderer/core/dom/processing_instruction.cc
@@ -53,7 +53,7 @@ inline ProcessingInstruction::ProcessingInstruction(Document& document,
ProcessingInstruction* ProcessingInstruction::Create(Document& document,
const String& target,
const String& data) {
- return new ProcessingInstruction(document, target, data);
+ return MakeGarbageCollected<ProcessingInstruction>(document, target, data);
}
ProcessingInstruction::~ProcessingInstruction() = default;
@@ -87,8 +87,11 @@ Node* ProcessingInstruction::Clone(Document& factory, CloneChildrenFlag) const {
}
void ProcessingInstruction::DidAttributeChanged() {
- if (sheet_)
+ if (sheet_) {
+ if (sheet_->IsLoading())
+ RemovePendingSheet();
ClearSheet();
+ }
String href;
String charset;
@@ -151,7 +154,8 @@ void ProcessingInstruction::Process(const String& href, const String& charset) {
return;
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::processinginstruction;
+ options.initiator_info.name =
+ fetch_initiator_type_names::kProcessinginstruction;
FetchParameters params(ResourceRequest(GetDocument().CompleteURL(href)),
options);
loading_ = true;
@@ -179,8 +183,7 @@ bool ProcessingInstruction::IsLoading() const {
bool ProcessingInstruction::SheetLoaded() {
if (!IsLoading()) {
if (!DocumentXSLT::SheetLoaded(GetDocument(), this))
- GetDocument().GetStyleEngine().RemovePendingSheet(*this,
- style_engine_context_);
+ RemovePendingSheet();
return true;
}
return false;
@@ -264,6 +267,9 @@ void ProcessingInstruction::RemovedFrom(ContainerNode& insertion_point) {
*this, insertion_point);
}
+ if (IsLoading())
+ RemovePendingSheet();
+
if (sheet_) {
DCHECK_EQ(sheet_->ownerNode(), this);
ClearSheet();
@@ -275,12 +281,14 @@ void ProcessingInstruction::RemovedFrom(ContainerNode& insertion_point) {
void ProcessingInstruction::ClearSheet() {
DCHECK(sheet_);
- if (sheet_->IsLoading())
- GetDocument().GetStyleEngine().RemovePendingSheet(*this,
- style_engine_context_);
sheet_.Release()->ClearOwnerNode();
}
+void ProcessingInstruction::RemovePendingSheet() {
+ GetDocument().GetStyleEngine().RemovePendingSheet(*this,
+ style_engine_context_);
+}
+
void ProcessingInstruction::Trace(blink::Visitor* visitor) {
visitor->Trace(sheet_);
visitor->Trace(listener_for_xslt_);
diff --git a/chromium/third_party/blink/renderer/core/dom/processing_instruction.h b/chromium/third_party/blink/renderer/core/dom/processing_instruction.h
index 66e8683eb92..8341102cbd7 100644
--- a/chromium/third_party/blink/renderer/core/dom/processing_instruction.h
+++ b/chromium/third_party/blink/renderer/core/dom/processing_instruction.h
@@ -41,6 +41,8 @@ class CORE_EXPORT ProcessingInstruction final : public CharacterData,
static ProcessingInstruction* Create(Document&,
const String& target,
const String& data);
+
+ ProcessingInstruction(Document&, const String& target, const String& data);
~ProcessingInstruction() override;
void Trace(blink::Visitor*) override;
@@ -72,8 +74,6 @@ class CORE_EXPORT ProcessingInstruction final : public CharacterData,
void ClearEventListenerForXSLT();
private:
- ProcessingInstruction(Document&, const String& target, const String& data);
-
String nodeName() const override;
NodeType getNodeType() const override;
Node* Clone(Document&, CloneChildrenFlag) const override;
@@ -91,6 +91,7 @@ class CORE_EXPORT ProcessingInstruction final : public CharacterData,
void ParseStyleSheet(const String& sheet);
void ClearSheet();
+ void RemovePendingSheet();
String DebugName() const override { return "ProcessingInstruction"; }
diff --git a/chromium/third_party/blink/renderer/core/dom/pseudo_element.cc b/chromium/third_party/blink/renderer/core/dom/pseudo_element.cc
index a2a656c9639..805af538212 100644
--- a/chromium/third_party/blink/renderer/core/dom/pseudo_element.cc
+++ b/chromium/third_party/blink/renderer/core/dom/pseudo_element.cc
@@ -41,7 +41,7 @@ namespace blink {
PseudoElement* PseudoElement::Create(Element* parent, PseudoId pseudo_id) {
if (pseudo_id == kPseudoIdFirstLetter)
return FirstLetterPseudoElement::Create(parent);
- return new PseudoElement(parent, pseudo_id);
+ return MakeGarbageCollected<PseudoElement>(parent, pseudo_id);
}
const QualifiedName& PseudoElementTagName(PseudoId pseudo_id) {
@@ -90,14 +90,14 @@ String PseudoElement::PseudoElementNameForEvents(PseudoId pseudo_id) {
PseudoElement::PseudoElement(Element* parent, PseudoId pseudo_id)
: Element(PseudoElementTagName(pseudo_id),
&parent->GetDocument(),
- kCreatePseudoElement),
+ kCreateElement),
pseudo_id_(pseudo_id) {
DCHECK_NE(pseudo_id, kPseudoIdNone);
parent->GetTreeScope().AdoptIfNeeded(*this);
SetParentOrShadowHostNode(parent);
SetHasCustomStyleCallbacks();
if ((pseudo_id == kPseudoIdBefore || pseudo_id == kPseudoIdAfter) &&
- parent->HasTagName(HTMLNames::inputTag)) {
+ parent->HasTagName(html_names::kInputTag)) {
UseCounter::Count(parent->GetDocument(),
WebFeature::kPseudoBeforeAfterForInputElement);
}
@@ -184,29 +184,6 @@ bool PseudoElement::LayoutObjectIsNeeded(const ComputedStyle& style) const {
return PseudoElementLayoutObjectIsNeeded(&style);
}
-void PseudoElement::DidRecalcStyle(StyleRecalcChange change) {
- // If the pseudo element is being re-attached, its anonymous LayoutObjects for
- // generated content will be destroyed and possibly recreated during layout
- // tree rebuild. Thus, propagating style to generated content now is futile.
- if (change == kReattach)
- return;
- if (!GetLayoutObject())
- return;
-
- // The layoutObjects inside pseudo elements are anonymous so they don't get
- // notified of recalcStyle and must have the style propagated downward
- // manually similar to LayoutObject::PropagateStyleToAnonymousChildren.
- LayoutObject* layout_object = GetLayoutObject();
- for (LayoutObject* child = layout_object->NextInPreOrder(layout_object);
- child; child = child->NextInPreOrder(layout_object)) {
- // We only manage the style for the generated content items.
- if (!child->IsText() && !child->IsQuote() && !child->IsImage())
- continue;
-
- child->SetPseudoStyle(layout_object->MutableStyle());
- }
-}
-
Node* PseudoElement::InnerNodeForHitTesting() const {
return ParentOrShadowHostNode();
}
diff --git a/chromium/third_party/blink/renderer/core/dom/pseudo_element.h b/chromium/third_party/blink/renderer/core/dom/pseudo_element.h
index df0e5571928..d3da1693511 100644
--- a/chromium/third_party/blink/renderer/core/dom/pseudo_element.h
+++ b/chromium/third_party/blink/renderer/core/dom/pseudo_element.h
@@ -38,6 +38,8 @@ class CORE_EXPORT PseudoElement : public Element {
public:
static PseudoElement* Create(Element* parent, PseudoId);
+ PseudoElement(Element*, PseudoId);
+
scoped_refptr<ComputedStyle> CustomStyleForLayoutObject() override;
void AttachLayoutTree(AttachContext&) override;
bool LayoutObjectIsNeeded(const ComputedStyle&) const override;
@@ -58,12 +60,7 @@ class CORE_EXPORT PseudoElement : public Element {
virtual void Dispose();
- protected:
- PseudoElement(Element*, PseudoId);
-
private:
- void DidRecalcStyle(StyleRecalcChange) override;
-
PseudoId pseudo_id_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/pseudo_element_data.h b/chromium/third_party/blink/renderer/core/dom/pseudo_element_data.h
index 2ab87d442b5..76db5ac2b0d 100644
--- a/chromium/third_party/blink/renderer/core/dom/pseudo_element_data.h
+++ b/chromium/third_party/blink/renderer/core/dom/pseudo_element_data.h
@@ -14,6 +14,9 @@ namespace blink {
class PseudoElementData final : public GarbageCollected<PseudoElementData> {
public:
static PseudoElementData* Create();
+
+ PseudoElementData() = default;
+
void SetPseudoElement(PseudoId, PseudoElement*);
PseudoElement* GetPseudoElement(PseudoId) const;
bool HasPseudoElements() const;
@@ -26,7 +29,6 @@ class PseudoElementData final : public GarbageCollected<PseudoElementData> {
}
private:
- PseudoElementData() = default;
Member<PseudoElement> generated_before_;
Member<PseudoElement> generated_after_;
Member<PseudoElement> generated_first_letter_;
@@ -35,7 +37,7 @@ class PseudoElementData final : public GarbageCollected<PseudoElementData> {
};
inline PseudoElementData* PseudoElementData::Create() {
- return new PseudoElementData();
+ return MakeGarbageCollected<PseudoElementData>();
}
inline bool PseudoElementData::HasPseudoElements() const {
diff --git a/chromium/third_party/blink/renderer/core/dom/qualified_name.h b/chromium/third_party/blink/renderer/core/dom/qualified_name.h
index ea0348d47cc..48ff2473771 100644
--- a/chromium/third_party/blink/renderer/core/dom/qualified_name.h
+++ b/chromium/third_party/blink/renderer/core/dom/qualified_name.h
@@ -52,7 +52,7 @@ class CORE_EXPORT QualifiedName {
USING_FAST_MALLOC(QualifiedName);
public:
- class QualifiedNameImpl : public RefCounted<QualifiedNameImpl> {
+ class CORE_EXPORT QualifiedNameImpl : public RefCounted<QualifiedNameImpl> {
public:
static scoped_refptr<QualifiedNameImpl> Create(
const AtomicString& prefix,
@@ -223,6 +223,8 @@ CORE_EXPORT std::ostream& operator<<(std::ostream&, const QualifiedName&);
} // namespace blink
+WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::QualifiedName);
+
namespace WTF {
template <>
diff --git a/chromium/third_party/blink/renderer/core/dom/range.cc b/chromium/third_party/blink/renderer/core/dom/range.cc
index 7832ffd3a74..2a626e82804 100644
--- a/chromium/third_party/blink/renderer/core/dom/range.cc
+++ b/chromium/third_party/blink/renderer/core/dom/range.cc
@@ -129,7 +129,7 @@ inline Range::Range(Document& owner_document)
}
Range* Range::Create(Document& owner_document) {
- return new Range(owner_document);
+ return MakeGarbageCollected<Range>(owner_document);
}
inline Range::Range(Document& owner_document,
@@ -153,17 +153,17 @@ Range* Range::Create(Document& owner_document,
unsigned start_offset,
Node* end_container,
unsigned end_offset) {
- return new Range(owner_document, start_container, start_offset, end_container,
- end_offset);
+ return MakeGarbageCollected<Range>(owner_document, start_container,
+ start_offset, end_container, end_offset);
}
Range* Range::Create(Document& owner_document,
const Position& start,
const Position& end) {
- return new Range(owner_document, start.ComputeContainerNode(),
- start.ComputeOffsetInContainerNode(),
- end.ComputeContainerNode(),
- end.ComputeOffsetInContainerNode());
+ return MakeGarbageCollected<Range>(
+ owner_document, start.ComputeContainerNode(),
+ start.ComputeOffsetInContainerNode(), end.ComputeContainerNode(),
+ end.ComputeOffsetInContainerNode());
}
void Range::Dispose() {
@@ -1435,12 +1435,33 @@ static inline void BoundaryNodeChildrenWillBeRemoved(
}
}
+static void BoundaryShadowNodeChildrenWillBeRemoved(
+ RangeBoundaryPoint& boundary,
+ ContainerNode& container) {
+ for (Node* node_to_be_removed = container.firstChild(); node_to_be_removed;
+ node_to_be_removed = node_to_be_removed->nextSibling()) {
+ for (Node* n = &boundary.Container(); n;
+ n = n->ParentOrShadowHostElement()) {
+ if (n == node_to_be_removed) {
+ boundary.SetToStartOfNode(container);
+ return;
+ }
+ }
+ }
+}
+
void Range::NodeChildrenWillBeRemoved(ContainerNode& container) {
DCHECK_EQ(container.GetDocument(), owner_document_);
BoundaryNodeChildrenWillBeRemoved(start_, container);
BoundaryNodeChildrenWillBeRemoved(end_, container);
}
+void Range::FixupRemovedChildrenAcrossShadowBoundary(ContainerNode& container) {
+ DCHECK_EQ(container.GetDocument(), owner_document_);
+ BoundaryShadowNodeChildrenWillBeRemoved(start_, container);
+ BoundaryShadowNodeChildrenWillBeRemoved(end_, container);
+}
+
static inline void BoundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary,
Node& node_to_be_removed) {
if (boundary.ChildBefore() == node_to_be_removed) {
@@ -1456,6 +1477,19 @@ static inline void BoundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary,
}
}
+static inline void BoundaryShadowNodeWillBeRemoved(RangeBoundaryPoint& boundary,
+ Node& node_to_be_removed) {
+ DCHECK_NE(boundary.ChildBefore(), node_to_be_removed);
+
+ for (Node* node = &boundary.Container(); node;
+ node = node->ParentOrShadowHostElement()) {
+ if (node == node_to_be_removed) {
+ boundary.SetToBeforeChild(node_to_be_removed);
+ return;
+ }
+ }
+}
+
void Range::NodeWillBeRemoved(Node& node) {
DCHECK_EQ(node.GetDocument(), owner_document_);
DCHECK_NE(node, owner_document_.Get());
@@ -1468,6 +1502,11 @@ void Range::NodeWillBeRemoved(Node& node) {
BoundaryNodeWillBeRemoved(end_, node);
}
+void Range::FixupRemovedNodeAcrossShadowBoundary(Node& node) {
+ BoundaryShadowNodeWillBeRemoved(start_, node);
+ BoundaryShadowNodeWillBeRemoved(end_, node);
+}
+
static inline void BoundaryTextInserted(RangeBoundaryPoint& boundary,
const CharacterData& text,
unsigned offset,
@@ -1579,11 +1618,12 @@ void Range::expand(const String& unit, ExceptionState& exception_state) {
VisiblePosition start = CreateVisiblePosition(StartPosition());
VisiblePosition end = CreateVisiblePosition(EndPosition());
if (unit == "word") {
- start = StartOfWord(start);
- end = EndOfWord(end);
+ start = CreateVisiblePosition(StartOfWordPosition(start.DeepEquivalent()));
+ end = CreateVisiblePosition(EndOfWordPosition(end.DeepEquivalent()));
} else if (unit == "sentence") {
- start = StartOfSentence(start);
- end = EndOfSentence(end);
+ start =
+ CreateVisiblePosition(StartOfSentencePosition(start.DeepEquivalent()));
+ end = CreateVisiblePosition(EndOfSentence(end.DeepEquivalent()));
} else if (unit == "block") {
start = StartOfParagraph(start);
end = EndOfParagraph(end);
diff --git a/chromium/third_party/blink/renderer/core/dom/range.h b/chromium/third_party/blink/renderer/core/dom/range.h
index 66f75b09717..ec46883ee63 100644
--- a/chromium/third_party/blink/renderer/core/dom/range.h
+++ b/chromium/third_party/blink/renderer/core/dom/range.h
@@ -61,6 +61,13 @@ class CORE_EXPORT Range final : public ScriptWrappable {
unsigned end_offset);
static Range* Create(Document&, const Position&, const Position&);
+ explicit Range(Document&);
+ Range(Document&,
+ Node* start_container,
+ unsigned start_offset,
+ Node* end_container,
+ unsigned end_offset);
+
void Dispose();
Document& OwnerDocument() const {
@@ -148,6 +155,11 @@ class CORE_EXPORT Range final : public ScriptWrappable {
void NodeChildrenWillBeRemoved(ContainerNode&);
void NodeWillBeRemoved(Node&);
+ // They are special fixups only for sequential focus navigation
+ // starting point.
+ void FixupRemovedChildrenAcrossShadowBoundary(ContainerNode& container);
+ void FixupRemovedNodeAcrossShadowBoundary(Node& node);
+
void DidInsertText(const CharacterData&, unsigned offset, unsigned length);
void DidRemoveText(const CharacterData&, unsigned offset, unsigned length);
void DidMergeTextNodes(const NodeWithIndex& old_node, unsigned offset);
@@ -167,13 +179,6 @@ class CORE_EXPORT Range final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit Range(Document&);
- Range(Document&,
- Node* start_container,
- unsigned start_offset,
- Node* end_container,
- unsigned end_offset);
-
void SetDocument(Document&);
void CheckNodeBA(Node*, ExceptionState&) const;
diff --git a/chromium/third_party/blink/renderer/core/dom/range_test.cc b/chromium/third_party/blink/renderer/core/dom/range_test.cc
index 2855792021d..187b7735f5e 100644
--- a/chromium/third_party/blink/renderer/core/dom/range_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/range_test.cc
@@ -40,7 +40,7 @@ TEST_F(RangeTest, extractContentsWithDOMMutationEvent) {
GetDocument().body()->SetInnerHTMLFromString("<span><b>abc</b>def</span>");
GetDocument().GetSettings()->SetScriptEnabled(true);
Element* const script_element =
- GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ GetDocument().CreateRawElement(html_names::kScriptTag);
script_element->setTextContent(
"let count = 0;"
"const span = document.querySelector('span');"
@@ -54,7 +54,7 @@ TEST_F(RangeTest, extractContentsWithDOMMutationEvent) {
Element* const span_element = GetDocument().QuerySelector("span");
Range* const range =
Range::Create(GetDocument(), span_element, 0, span_element, 1);
- Element* const result = GetDocument().CreateRawElement(HTMLNames::divTag);
+ Element* const result = GetDocument().CreateRawElement(html_names::kDivTag);
result->AppendChild(range->extractContents(ASSERT_NO_EXCEPTION));
EXPECT_EQ("<b>abc</b>", result->InnerHTMLAsString())
@@ -302,7 +302,7 @@ TEST_F(RangeTest, BoundingRectMustIndependentFromSelection) {
SelectionInDOMTree::Builder()
.SetBaseAndExtent(EphemeralRange(range))
.Build());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(Selection().SelectedText(), "x x");
const FloatRect rect_after = range->BoundingRect();
EXPECT_EQ(rect_before, rect_after);
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.cc b/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.cc
index 685a7871c3e..0bcedc826eb 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.cc
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.cc
@@ -28,6 +28,7 @@
#include "third_party/blink/renderer/core/css/media_query_list_listener.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
@@ -66,7 +67,7 @@ void ScriptedAnimationController::Unpause() {
}
void ScriptedAnimationController::DispatchEventsAndCallbacksForPrinting() {
- DispatchEvents(EventNames::MediaQueryListEvent);
+ DispatchEvents(event_interface_names::kMediaQueryListEvent);
CallMediaQueryListListeners();
}
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.h b/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.h
index 6c8855f65b4..a1ca3e62ab0 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.h
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller.h
@@ -47,8 +47,10 @@ class CORE_EXPORT ScriptedAnimationController
public NameClient {
public:
static ScriptedAnimationController* Create(Document* document) {
- return new ScriptedAnimationController(document);
+ return MakeGarbageCollected<ScriptedAnimationController>(document);
}
+
+ explicit ScriptedAnimationController(Document*);
virtual ~ScriptedAnimationController() = default;
void Trace(blink::Visitor*);
@@ -88,8 +90,6 @@ class CORE_EXPORT ScriptedAnimationController
bool NextFrameHasPendingRAF() const { return next_frame_has_pending_raf_; }
private:
- explicit ScriptedAnimationController(Document*);
-
void ScheduleAnimationIfNeeded();
void RunTasks();
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller_test.cc b/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller_test.cc
index 9afaa953e7d..8be822368a7 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_animation_controller_test.cc
@@ -121,7 +121,7 @@ class RunTaskEventListener final : public EventListener {
public:
RunTaskEventListener(base::RepeatingClosure task)
: EventListener(kCPPEventListenerType), task_(std::move(task)) {}
- void handleEvent(ExecutionContext*, Event*) override { task_.Run(); }
+ void Invoke(ExecutionContext*, Event*) override { task_.Run(); }
bool operator==(const EventListener& other) const override {
return this == &other;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc b/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc
index f38852efb04..d9bb0cbdd94 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc
@@ -38,10 +38,7 @@ class IdleRequestCallbackWrapper
callback_wrapper->Controller()) {
// If we are going to yield immediately, reschedule the callback for
// later.
- if (Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->ShouldYieldForHighPriorityWork()) {
+ if (ThreadScheduler::Current()->ShouldYieldForHighPriorityWork()) {
controller->ScheduleCallback(std::move(callback_wrapper),
/* timeout_millis */ 0);
return;
@@ -94,7 +91,7 @@ void ScriptedIdleTaskController::V8IdleTask::invoke(IdleDeadline* deadline) {
ScriptedIdleTaskController::ScriptedIdleTaskController(
ExecutionContext* context)
: PausableObject(context),
- scheduler_(Platform::Current()->CurrentThread()->Scheduler()),
+ scheduler_(ThreadScheduler::Current()),
next_callback_id_(0),
paused_(false) {
PauseIfNeeded();
@@ -122,12 +119,12 @@ int ScriptedIdleTaskController::NextCallbackId() {
ScriptedIdleTaskController::CallbackId
ScriptedIdleTaskController::RegisterCallback(
IdleTask* idle_task,
- const IdleRequestOptions& options) {
+ const IdleRequestOptions* options) {
DCHECK(idle_task);
CallbackId id = NextCallbackId();
idle_tasks_.Set(id, idle_task);
- long long timeout_millis = options.timeout();
+ long long timeout_millis = options->timeout();
probe::AsyncTaskScheduled(GetExecutionContext(), "requestIdleCallback",
idle_task);
@@ -137,7 +134,7 @@ ScriptedIdleTaskController::RegisterCallback(
ScheduleCallback(std::move(callback_wrapper), timeout_millis);
TRACE_EVENT_INSTANT1("devtools.timeline", "RequestIdleCallback",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorIdleCallbackRequestEvent::Data(
+ inspector_idle_callback_request_event::Data(
GetExecutionContext(), id, timeout_millis));
return id;
}
@@ -163,7 +160,7 @@ void ScriptedIdleTaskController::CancelCallback(CallbackId id) {
TRACE_EVENT_INSTANT1(
"devtools.timeline", "CancelIdleCallback", TRACE_EVENT_SCOPE_THREAD,
"data",
- InspectorIdleCallbackCancelEvent::Data(GetExecutionContext(), id));
+ inspector_idle_callback_cancel_event::Data(GetExecutionContext(), id));
if (!IsValidCallbackId(id))
return;
@@ -214,7 +211,7 @@ void ScriptedIdleTaskController::RunCallback(
TRACE_EVENT1(
"devtools.timeline", "FireIdleCallback", "data",
- InspectorIdleCallbackFireEvent::Data(
+ inspector_idle_callback_fire_event::Data(
GetExecutionContext(), id, allotted_time.InMillisecondsF(),
callback_type == IdleDeadline::CallbackType::kCalledByTimeout));
idle_task->invoke(IdleDeadline::Create(deadline, callback_type));
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h b/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h
index 55adb1fe191..c734b7cef99 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h
@@ -31,8 +31,10 @@ class CORE_EXPORT ScriptedIdleTaskController
public:
static ScriptedIdleTaskController* Create(ExecutionContext* context) {
- return new ScriptedIdleTaskController(context);
+ return MakeGarbageCollected<ScriptedIdleTaskController>(context);
}
+
+ explicit ScriptedIdleTaskController(ExecutionContext*);
~ScriptedIdleTaskController() override;
void Trace(blink::Visitor*) override;
@@ -58,18 +60,20 @@ class CORE_EXPORT ScriptedIdleTaskController
class V8IdleTask : public IdleTask {
public:
static V8IdleTask* Create(V8IdleRequestCallback* callback) {
- return new V8IdleTask(callback);
+ return MakeGarbageCollected<V8IdleTask>(callback);
}
+
+ explicit V8IdleTask(V8IdleRequestCallback*);
~V8IdleTask() override = default;
+
void invoke(IdleDeadline*) override;
void Trace(blink::Visitor*) override;
private:
- explicit V8IdleTask(V8IdleRequestCallback*);
TraceWrapperMember<V8IdleRequestCallback> callback_;
};
- int RegisterCallback(IdleTask*, const IdleRequestOptions&);
+ int RegisterCallback(IdleTask*, const IdleRequestOptions*);
void CancelCallback(CallbackId);
// PausableObject interface.
@@ -83,7 +87,6 @@ class CORE_EXPORT ScriptedIdleTaskController
private:
friend class internal::IdleRequestCallbackWrapper;
- explicit ScriptedIdleTaskController(ExecutionContext*);
void ScheduleCallback(scoped_refptr<internal::IdleRequestCallbackWrapper>,
long long timeout_millis);
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc b/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc
index 3da0c695f5e..b17a00e9b99 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc
@@ -6,12 +6,11 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_idle_request_callback.h"
#include "third_party/blink/renderer/core/dom/idle_request_options.h"
#include "third_party/blink/renderer/core/testing/null_execution_context.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h"
+#include "third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -56,11 +55,9 @@ class MockScriptedIdleTaskControllerScheduler final : public ThreadScheduler {
return base::TimeTicks();
}
- void AddTaskObserver(
- base::MessageLoop::TaskObserver* task_observer) override {}
+ void AddTaskObserver(Thread::TaskObserver* task_observer) override {}
- void RemoveTaskObserver(
- base::MessageLoop::TaskObserver* task_observer) override {}
+ void RemoveTaskObserver(Thread::TaskObserver* task_observer) override {}
void AddRAILModeObserver(scheduler::WebRAILModeObserver*) override {}
@@ -86,7 +83,9 @@ class MockIdleTask : public ScriptedIdleTaskController::IdleTask {
class ScriptedIdleTaskControllerTest : public testing::Test {
public:
- void SetUp() override { execution_context_ = new NullExecutionContext(); }
+ void SetUp() override {
+ execution_context_ = MakeGarbageCollected<NullExecutionContext>();
+ }
protected:
Persistent<ExecutionContext> execution_context_;
@@ -94,16 +93,14 @@ class ScriptedIdleTaskControllerTest : public testing::Test {
TEST_F(ScriptedIdleTaskControllerTest, RunCallback) {
MockScriptedIdleTaskControllerScheduler scheduler(ShouldYield::DONT_YIELD);
- ScopedTestingPlatformSupport<TestingPlatformSupportWithCustomScheduler,
- ThreadScheduler*>
- platform(&scheduler);
+ ScopedSchedulerOverrider scheduler_overrider(&scheduler);
NullExecutionContext execution_context;
ScriptedIdleTaskController* controller =
ScriptedIdleTaskController::Create(execution_context_);
Persistent<MockIdleTask> idle_task(new MockIdleTask());
- IdleRequestOptions options;
+ IdleRequestOptions* options = IdleRequestOptions::Create();
EXPECT_FALSE(scheduler.HasIdleTask());
int id = controller->RegisterCallback(idle_task, options);
EXPECT_TRUE(scheduler.HasIdleTask());
@@ -117,16 +114,14 @@ TEST_F(ScriptedIdleTaskControllerTest, RunCallback) {
TEST_F(ScriptedIdleTaskControllerTest, DontRunCallbackWhenAskedToYield) {
MockScriptedIdleTaskControllerScheduler scheduler(ShouldYield::YIELD);
- ScopedTestingPlatformSupport<TestingPlatformSupportWithCustomScheduler,
- ThreadScheduler*>
- platform(&scheduler);
+ ScopedSchedulerOverrider scheduler_overrider(&scheduler);
NullExecutionContext execution_context;
ScriptedIdleTaskController* controller =
ScriptedIdleTaskController::Create(execution_context_);
Persistent<MockIdleTask> idle_task(new MockIdleTask());
- IdleRequestOptions options;
+ IdleRequestOptions* options = IdleRequestOptions::Create();
int id = controller->RegisterCallback(idle_task, options);
EXPECT_NE(0, id);
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc
index ce70145f354..0b3319f95b5 100644
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc
+++ b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_task_queue_post_callback.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/shadow_dom_v0_test.cc b/chromium/third_party/blink/renderer/core/dom/shadow_dom_v0_test.cc
index e2bb4c07f16..b555a8709c7 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_dom_v0_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_dom_v0_test.cc
@@ -40,8 +40,8 @@ class ShadowDOMVTest : public SimTest {};
TEST_F(ShadowDOMVTest, FeatureSetId) {
LoadURL("about:blank");
- auto* host = GetDocument().CreateRawElement(HTMLNames::divTag);
- auto* content = GetDocument().CreateRawElement(HTMLNames::contentTag);
+ auto* host = GetDocument().CreateRawElement(html_names::kDivTag);
+ auto* content = GetDocument().CreateRawElement(html_names::kContentTag);
content->setAttribute("select", "#foo");
host->CreateV0ShadowRootForTesting().AppendChild(content);
EXPECT_TRUE(HasSelectorForIdInShadow(host, "foo"));
@@ -57,8 +57,8 @@ TEST_F(ShadowDOMVTest, FeatureSetId) {
TEST_F(ShadowDOMVTest, FeatureSetClassName) {
LoadURL("about:blank");
- auto* host = GetDocument().CreateRawElement(HTMLNames::divTag);
- auto* content = GetDocument().CreateRawElement(HTMLNames::contentTag);
+ auto* host = GetDocument().CreateRawElement(html_names::kDivTag);
+ auto* content = GetDocument().CreateRawElement(html_names::kContentTag);
content->setAttribute("select", ".foo");
host->CreateV0ShadowRootForTesting().AppendChild(content);
EXPECT_TRUE(HasSelectorForClassInShadow(host, "foo"));
@@ -74,8 +74,8 @@ TEST_F(ShadowDOMVTest, FeatureSetClassName) {
TEST_F(ShadowDOMVTest, FeatureSetAttributeName) {
LoadURL("about:blank");
- auto* host = GetDocument().CreateRawElement(HTMLNames::divTag);
- auto* content = GetDocument().CreateRawElement(HTMLNames::contentTag);
+ auto* host = GetDocument().CreateRawElement(html_names::kDivTag);
+ auto* content = GetDocument().CreateRawElement(html_names::kContentTag);
content->setAttribute("select", "div[foo]");
host->CreateV0ShadowRootForTesting().AppendChild(content);
EXPECT_TRUE(HasSelectorForAttributeInShadow(host, "foo"));
@@ -91,8 +91,8 @@ TEST_F(ShadowDOMVTest, FeatureSetAttributeName) {
TEST_F(ShadowDOMVTest, FeatureSetMultipleSelectors) {
LoadURL("about:blank");
- auto* host = GetDocument().CreateRawElement(HTMLNames::divTag);
- auto* content = GetDocument().CreateRawElement(HTMLNames::contentTag);
+ auto* host = GetDocument().CreateRawElement(html_names::kDivTag);
+ auto* content = GetDocument().CreateRawElement(html_names::kContentTag);
content->setAttribute("select", "#foo,.bar,div[baz]");
host->CreateV0ShadowRootForTesting().AppendChild(content);
EXPECT_TRUE(HasSelectorForIdInShadow(host, "foo"));
@@ -108,7 +108,7 @@ TEST_F(ShadowDOMVTest, FeatureSetMultipleSelectors) {
TEST_F(ShadowDOMVTest, FeatureSetSubtree) {
LoadURL("about:blank");
- auto* host = GetDocument().CreateRawElement(HTMLNames::divTag);
+ auto* host = GetDocument().CreateRawElement(html_names::kDivTag);
host->CreateV0ShadowRootForTesting().SetInnerHTMLFromString(R"HTML(
<div>
<div></div>
@@ -126,12 +126,12 @@ TEST_F(ShadowDOMVTest, FeatureSetSubtree) {
TEST_F(ShadowDOMVTest, FeatureSetMultipleShadowRoots) {
LoadURL("about:blank");
- auto* host = GetDocument().CreateRawElement(HTMLNames::divTag);
+ auto* host = GetDocument().CreateRawElement(html_names::kDivTag);
auto& host_shadow = host->CreateV0ShadowRootForTesting();
host_shadow.SetInnerHTMLFromString("<content select='#foo'></content>");
- auto* child = GetDocument().CreateRawElement(HTMLNames::divTag);
+ auto* child = GetDocument().CreateRawElement(html_names::kDivTag);
auto& child_root = child->CreateV0ShadowRootForTesting();
- auto* child_content = GetDocument().CreateRawElement(HTMLNames::contentTag);
+ auto* child_content = GetDocument().CreateRawElement(html_names::kContentTag);
child_content->setAttribute("select", "#bar");
child_root.AppendChild(child_content);
host_shadow.AppendChild(child);
diff --git a/chromium/third_party/blink/renderer/core/dom/shadow_root.cc b/chromium/third_party/blink/renderer/core/dom/shadow_root.cc
index f2d520004ab..04bd6ddae57 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_root.cc
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_root.cc
@@ -76,7 +76,7 @@ ShadowRoot::ShadowRoot(Document& document, ShadowRootType type)
needs_distribution_recalc_(false),
unused_(0) {
if (IsV0())
- shadow_root_v0_ = new ShadowRootV0(*this);
+ shadow_root_v0_ = MakeGarbageCollected<ShadowRootV0>(*this);
}
ShadowRoot::~ShadowRoot() = default;
@@ -164,21 +164,6 @@ void ShadowRoot::RebuildLayoutTree(WhitespaceAttacher& whitespace_attacher) {
ClearChildNeedsReattachLayoutTree();
}
-void ShadowRoot::AttachLayoutTree(AttachContext& context) {
- Node::AttachContext children_context(context);
- DocumentFragment::AttachLayoutTree(children_context);
-}
-
-void ShadowRoot::DetachLayoutTree(const AttachContext& context) {
- Node::AttachContext children_context(context);
- children_context.clear_invalidation = true;
- GetDocument()
- .GetStyleEngine()
- .GetPendingNodeInvalidations()
- .ClearInvalidation(*this);
- DocumentFragment::DetachLayoutTree(children_context);
-}
-
Node::InsertionNotificationRequest ShadowRoot::InsertedInto(
ContainerNode& insertion_point) {
DocumentFragment::InsertedInto(insertion_point);
@@ -217,12 +202,6 @@ void ShadowRoot::RemovedFrom(ContainerNode& insertion_point) {
root->RemoveChildShadowRoot();
registered_with_parent_shadow_root_ = false;
}
- if (NeedsStyleInvalidation()) {
- GetDocument()
- .GetStyleEngine()
- .GetPendingNodeInvalidations()
- .ClearInvalidation(*this);
- }
}
DocumentFragment::RemovedFrom(insertion_point);
diff --git a/chromium/third_party/blink/renderer/core/dom/shadow_root.h b/chromium/third_party/blink/renderer/core/dom/shadow_root.h
index 5abe0c54124..2f981ad6eaa 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_root.h
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_root.h
@@ -56,9 +56,11 @@ class CORE_EXPORT ShadowRoot final : public DocumentFragment, public TreeScope {
public:
static ShadowRoot* Create(Document& document, ShadowRootType type) {
- return new ShadowRoot(document, type);
+ return MakeGarbageCollected<ShadowRoot>(document, type);
}
+ ShadowRoot(Document&, ShadowRootType);
+
// Disambiguate between Node and TreeScope hierarchies; TreeScope's
// implementation is simpler.
using TreeScope::GetDocument;
@@ -105,9 +107,6 @@ class CORE_EXPORT ShadowRoot final : public DocumentFragment, public TreeScope {
}
bool IsUserAgent() const { return GetType() == ShadowRootType::kUserAgent; }
- void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
-
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
@@ -130,6 +129,8 @@ class CORE_EXPORT ShadowRoot final : public DocumentFragment, public TreeScope {
return *slot_assignment_;
}
+ bool HasSlotAssignment() { return slot_assignment_; }
+
HTMLSlotElement* AssignedSlotFor(const Node&);
void DidAddSlot(HTMLSlotElement&);
void DidChangeHostChildSlotName(const AtomicString& old_value,
@@ -173,7 +174,6 @@ class CORE_EXPORT ShadowRoot final : public DocumentFragment, public TreeScope {
void Trace(blink::Visitor*) override;
private:
- ShadowRoot(Document&, ShadowRootType);
~ShadowRoot() override;
void ChildrenChanged(const ChildrenChange&) override;
diff --git a/chromium/third_party/blink/renderer/core/dom/shadow_root_v0.cc b/chromium/third_party/blink/renderer/core/dom/shadow_root_v0.cc
index 41971edecbb..64c9cc4a80b 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_root_v0.cc
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_root_v0.cc
@@ -125,8 +125,9 @@ inline void DistributionPool::DetachNonDistributedNodes() {
const HeapVector<Member<V0InsertionPoint>>&
ShadowRootV0::DescendantInsertionPoints() {
- DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<V0InsertionPoint>>>,
- empty_list, (new HeapVector<Member<V0InsertionPoint>>));
+ DEFINE_STATIC_LOCAL(
+ Persistent<HeapVector<Member<V0InsertionPoint>>>, empty_list,
+ (MakeGarbageCollected<HeapVector<Member<V0InsertionPoint>>>()));
if (descendant_insertion_points_is_valid_)
return descendant_insertion_points_;
@@ -195,8 +196,10 @@ void ShadowRootV0::DidDistributeNode(const Node* node,
V0InsertionPoint* insertion_point) {
NodeToDestinationInsertionPoints::AddResult result =
node_to_insertion_points_.insert(node, nullptr);
- if (result.is_new_entry)
- result.stored_value->value = new DestinationInsertionPoints;
+ if (result.is_new_entry) {
+ result.stored_value->value =
+ MakeGarbageCollected<DestinationInsertionPoints>();
+ }
result.stored_value->value->push_back(insertion_point);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/sink_document.cc b/chromium/third_party/blink/renderer/core/dom/sink_document.cc
index 05cf16aca90..609caf3ea93 100644
--- a/chromium/third_party/blink/renderer/core/dom/sink_document.cc
+++ b/chromium/third_party/blink/renderer/core/dom/sink_document.cc
@@ -33,13 +33,13 @@ namespace blink {
class SinkDocumentParser : public RawDataDocumentParser {
public:
static SinkDocumentParser* Create(SinkDocument* document) {
- return new SinkDocumentParser(document);
+ return MakeGarbageCollected<SinkDocumentParser>(document);
}
- private:
explicit SinkDocumentParser(SinkDocument* document)
: RawDataDocumentParser(document) {}
+ private:
// Ignore all data.
void AppendBytes(const char*, size_t) override {}
};
diff --git a/chromium/third_party/blink/renderer/core/dom/sink_document.h b/chromium/third_party/blink/renderer/core/dom/sink_document.h
index ef4f353d2a3..7a5f3f0f57d 100644
--- a/chromium/third_party/blink/renderer/core/dom/sink_document.h
+++ b/chromium/third_party/blink/renderer/core/dom/sink_document.h
@@ -33,12 +33,12 @@ namespace blink {
class SinkDocument final : public HTMLDocument {
public:
static SinkDocument* Create(const DocumentInit& initializer) {
- return new SinkDocument(initializer);
+ return MakeGarbageCollected<SinkDocument>(initializer);
}
- private:
explicit SinkDocument(const DocumentInit&);
+ private:
DocumentParser* CreateParser() override;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/slot_assignment.cc b/chromium/third_party/blink/renderer/core/dom/slot_assignment.cc
index fd2164fd0e8..bd70c6e1626 100644
--- a/chromium/third_party/blink/renderer/core/dom/slot_assignment.cc
+++ b/chromium/third_party/blink/renderer/core/dom/slot_assignment.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/slot_assignment_engine.h"
+#include "third_party/blink/renderer/core/dom/slot_assignment_recalc_forbidden_scope.h"
#include "third_party/blink/renderer/core/html/forms/html_opt_group_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/html_details_element.h"
@@ -226,10 +227,13 @@ void SlotAssignment::RecalcAssignment() {
#if DCHECK_IS_ON()
DCHECK(!owner_->GetDocument().IsSlotAssignmentRecalcForbidden());
#endif
+ // To detect recursive RecalcAssignment, which shouldn't happen.
+ SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(owner_->GetDocument());
+
needs_assignment_recalc_ = false;
for (Member<HTMLSlotElement> slot : Slots())
- slot->ClearAssignedNodes();
+ slot->WillRecalcAssignedNodes();
const bool is_user_agent = owner_->IsUserAgent();
@@ -266,10 +270,12 @@ void SlotAssignment::RecalcAssignment() {
}
}
- if (slot)
+ if (slot) {
slot->AppendAssignedNode(child);
- else
+ } else {
+ child.ClearFlatTreeNodeData();
child.LazyReattachIfAttached();
+ }
}
if (owner_->isConnected()) {
@@ -279,7 +285,7 @@ void SlotAssignment::RecalcAssignment() {
}
for (auto& slot : Slots())
- slot->RecalcFlatTreeChildren();
+ slot->DidRecalcAssignedNodes();
}
const HeapVector<Member<HTMLSlotElement>>& SlotAssignment::Slots() {
diff --git a/chromium/third_party/blink/renderer/core/dom/slot_assignment.h b/chromium/third_party/blink/renderer/core/dom/slot_assignment.h
index 47bb170f96e..36230f6404e 100644
--- a/chromium/third_party/blink/renderer/core/dom/slot_assignment.h
+++ b/chromium/third_party/blink/renderer/core/dom/slot_assignment.h
@@ -18,9 +18,11 @@ class ShadowRoot;
class SlotAssignment final : public GarbageCollected<SlotAssignment> {
public:
static SlotAssignment* Create(ShadowRoot& owner) {
- return new SlotAssignment(owner);
+ return MakeGarbageCollected<SlotAssignment>(owner);
}
+ explicit SlotAssignment(ShadowRoot& owner);
+
// Relevant DOM Standard: https://dom.spec.whatwg.org/#find-a-slot
HTMLSlotElement* FindSlot(const Node&);
HTMLSlotElement* FindSlotByName(const AtomicString& slot_name) const;
@@ -60,8 +62,6 @@ class SlotAssignment final : public GarbageCollected<SlotAssignment> {
void RecalcAssignment();
private:
- explicit SlotAssignment(ShadowRoot& owner);
-
enum class SlotMutationType {
kRemoved,
kRenamed,
diff --git a/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.h b/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.h
index a0c6bf2e5db..ae8a0f6a20d 100644
--- a/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.h
+++ b/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.h
@@ -14,7 +14,11 @@ class ShadowRoot;
class SlotAssignmentEngine final
: public GarbageCollected<SlotAssignmentEngine> {
public:
- static SlotAssignmentEngine* Create() { return new SlotAssignmentEngine(); }
+ static SlotAssignmentEngine* Create() {
+ return MakeGarbageCollected<SlotAssignmentEngine>();
+ }
+
+ explicit SlotAssignmentEngine();
void AddShadowRootNeedingRecalc(ShadowRoot&);
void RemoveShadowRootNeedingRecalc(ShadowRoot&);
@@ -31,8 +35,6 @@ class SlotAssignmentEngine final
void Trace(blink::Visitor*);
private:
- explicit SlotAssignmentEngine();
-
HeapHashSet<WeakMember<ShadowRoot>> shadow_roots_needing_recalc_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/slot_assignment_test.cc b/chromium/third_party/blink/renderer/core/dom/slot_assignment_test.cc
index 86a27fcef74..65eb6550d7f 100644
--- a/chromium/third_party/blink/renderer/core/dom/slot_assignment_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/slot_assignment_test.cc
@@ -69,7 +69,7 @@ void RemoveWhiteSpaceOnlyTextNode(ContainerNode& container) {
for (Node* descendant :
CollectFromIterable(NodeTraversal::InclusiveDescendantsOf(container))) {
if (Text* text = ToTextOrNull(descendant)) {
- if (text->ContainsOnlyWhitespace())
+ if (text->ContainsOnlyWhitespaceOrEmpty())
text->remove();
} else if (Element* element = ToElementOrNull(descendant)) {
if (ShadowRoot* shadow_root = element->OpenShadowRoot())
diff --git a/chromium/third_party/blink/renderer/core/dom/space_split_string.h b/chromium/third_party/blink/renderer/core/dom/space_split_string.h
index 1e1afbf4508..6589128b19c 100644
--- a/chromium/third_party/blink/renderer/core/dom/space_split_string.h
+++ b/chromium/third_party/blink/renderer/core/dom/space_split_string.h
@@ -65,7 +65,7 @@ class CORE_EXPORT SpaceSplitString {
const AtomicString& operator[](wtf_size_t i) const { return (*data_)[i]; }
private:
- class Data : public RefCounted<Data> {
+ class CORE_EXPORT Data : public RefCounted<Data> {
public:
static scoped_refptr<Data> Create(const AtomicString&);
static scoped_refptr<Data> CreateUnique(const Data&);
diff --git a/chromium/third_party/blink/renderer/core/dom/static_node_list.h b/chromium/third_party/blink/renderer/core/dom/static_node_list.h
index 884b32ad17d..9e911b1e163 100644
--- a/chromium/third_party/blink/renderer/core/dom/static_node_list.h
+++ b/chromium/third_party/blink/renderer/core/dom/static_node_list.h
@@ -44,7 +44,9 @@ class StaticNodeTypeList final : public NodeList {
public:
static StaticNodeTypeList* Adopt(HeapVector<Member<NodeType>>& nodes);
- static StaticNodeTypeList* CreateEmpty() { return new StaticNodeTypeList; }
+ static StaticNodeTypeList* CreateEmpty() {
+ return MakeGarbageCollected<StaticNodeTypeList>();
+ }
~StaticNodeTypeList() override;
diff --git a/chromium/third_party/blink/renderer/core/dom/static_range.cc b/chromium/third_party/blink/renderer/core/dom/static_range.cc
index 99fd39618a1..c5d3f6cb54e 100644
--- a/chromium/third_party/blink/renderer/core/dom/static_range.cc
+++ b/chromium/third_party/blink/renderer/core/dom/static_range.cc
@@ -33,11 +33,11 @@ StaticRange::StaticRange(Document& document,
// static
StaticRange* StaticRange::Create(const EphemeralRange& range) {
DCHECK(!range.IsNull());
- return new StaticRange(range.GetDocument(),
- range.StartPosition().ComputeContainerNode(),
- range.StartPosition().ComputeOffsetInContainerNode(),
- range.EndPosition().ComputeContainerNode(),
- range.EndPosition().ComputeOffsetInContainerNode());
+ return MakeGarbageCollected<StaticRange>(
+ range.GetDocument(), range.StartPosition().ComputeContainerNode(),
+ range.StartPosition().ComputeOffsetInContainerNode(),
+ range.EndPosition().ComputeContainerNode(),
+ range.EndPosition().ComputeOffsetInContainerNode());
}
void StaticRange::setStart(Node* container, unsigned offset) {
diff --git a/chromium/third_party/blink/renderer/core/dom/static_range.h b/chromium/third_party/blink/renderer/core/dom/static_range.h
index 728016d595e..8989453af29 100644
--- a/chromium/third_party/blink/renderer/core/dom/static_range.h
+++ b/chromium/third_party/blink/renderer/core/dom/static_range.h
@@ -21,23 +21,30 @@ class CORE_EXPORT StaticRange final : public ScriptWrappable {
public:
static StaticRange* Create(Document& document) {
- return new StaticRange(document);
+ return MakeGarbageCollected<StaticRange>(document);
}
static StaticRange* Create(Document& document,
Node* start_container,
unsigned start_offset,
Node* end_container,
unsigned end_offset) {
- return new StaticRange(document, start_container, start_offset,
- end_container, end_offset);
+ return MakeGarbageCollected<StaticRange>(
+ document, start_container, start_offset, end_container, end_offset);
}
static StaticRange* Create(const Range* range) {
- return new StaticRange(range->OwnerDocument(), range->startContainer(),
- range->startOffset(), range->endContainer(),
- range->endOffset());
+ return MakeGarbageCollected<StaticRange>(
+ range->OwnerDocument(), range->startContainer(), range->startOffset(),
+ range->endContainer(), range->endOffset());
}
static StaticRange* Create(const EphemeralRange&);
+ explicit StaticRange(Document&);
+ StaticRange(Document&,
+ Node* start_container,
+ unsigned start_offset,
+ Node* end_container,
+ unsigned end_offset);
+
Node* startContainer() const { return start_container_.Get(); }
void setStartContainer(Node* start_container) {
start_container_ = start_container;
@@ -64,13 +71,6 @@ class CORE_EXPORT StaticRange final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit StaticRange(Document&);
- StaticRange(Document&,
- Node* start_container,
- unsigned start_offset,
- Node* end_container,
- unsigned end_offset);
-
Member<Document> owner_document_; // Required by |toRange()|.
Member<Node> start_container_;
unsigned start_offset_;
diff --git a/chromium/third_party/blink/renderer/core/dom/tag_collection.h b/chromium/third_party/blink/renderer/core/dom/tag_collection.h
index 8358b1ab64c..d9842209221 100644
--- a/chromium/third_party/blink/renderer/core/dom/tag_collection.h
+++ b/chromium/third_party/blink/renderer/core/dom/tag_collection.h
@@ -36,18 +36,18 @@ class TagCollection : public HTMLCollection {
CollectionType type,
const AtomicString& qualified_name) {
DCHECK_EQ(type, kTagCollectionType);
- return new TagCollection(root_node, kTagCollectionType, qualified_name);
+ return MakeGarbageCollected<TagCollection>(root_node, kTagCollectionType,
+ qualified_name);
}
+ TagCollection(ContainerNode& root_node,
+ CollectionType,
+ const AtomicString& qualified_name);
~TagCollection() override;
bool ElementMatches(const Element&) const;
protected:
- TagCollection(ContainerNode& root_node,
- CollectionType,
- const AtomicString& qualified_name);
-
AtomicString qualified_name_;
};
@@ -56,20 +56,19 @@ class TagCollectionNS : public HTMLCollection {
static TagCollectionNS* Create(ContainerNode& root_node,
const AtomicString& namespace_uri,
const AtomicString& local_name) {
- return new TagCollectionNS(root_node, kTagCollectionNSType, namespace_uri,
- local_name);
+ return MakeGarbageCollected<TagCollectionNS>(
+ root_node, kTagCollectionNSType, namespace_uri, local_name);
}
- ~TagCollectionNS() override;
-
- bool ElementMatches(const Element&) const;
-
- private:
TagCollectionNS(ContainerNode& root_node,
CollectionType,
const AtomicString& namespace_uri,
const AtomicString& local_name);
+ ~TagCollectionNS() override;
+
+ bool ElementMatches(const Element&) const;
+ private:
AtomicString namespace_uri_;
AtomicString local_name_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/template_content_document_fragment.h b/chromium/third_party/blink/renderer/core/dom/template_content_document_fragment.h
index f7432c1cbfc..a68faf52563 100644
--- a/chromium/third_party/blink/renderer/core/dom/template_content_document_fragment.h
+++ b/chromium/third_party/blink/renderer/core/dom/template_content_document_fragment.h
@@ -35,9 +35,13 @@ class TemplateContentDocumentFragment final : public DocumentFragment {
public:
static TemplateContentDocumentFragment* Create(Document& document,
Element* host) {
- return new TemplateContentDocumentFragment(document, host);
+ return MakeGarbageCollected<TemplateContentDocumentFragment>(document,
+ host);
}
+ TemplateContentDocumentFragment(Document& document, Element* host)
+ : DocumentFragment(&document, kCreateDocumentFragment), host_(host) {}
+
Element* Host() const { return host_; }
void Trace(blink::Visitor* visitor) override {
@@ -46,9 +50,6 @@ class TemplateContentDocumentFragment final : public DocumentFragment {
}
private:
- TemplateContentDocumentFragment(Document& document, Element* host)
- : DocumentFragment(&document, kCreateDocumentFragment), host_(host) {}
-
bool IsTemplateContent() const override { return true; }
Member<Element> host_;
diff --git a/chromium/third_party/blink/renderer/core/dom/text.cc b/chromium/third_party/blink/renderer/core/dom/text.cc
index 8ea980ab00e..6a91669ed26 100644
--- a/chromium/third_party/blink/renderer/core/dom/text.cc
+++ b/chromium/third_party/blink/renderer/core/dom/text.cc
@@ -46,11 +46,11 @@
namespace blink {
Text* Text::Create(Document& document, const String& data) {
- return new Text(document, data, kCreateText);
+ return MakeGarbageCollected<Text>(document, data, kCreateText);
}
Text* Text::CreateEditingText(Document& document, const String& data) {
- return new Text(document, data, kCreateEditingText);
+ return MakeGarbageCollected<Text>(document, data, kCreateEditingText);
}
Node* Text::MergeNextSiblingNodesIfPossible() {
@@ -288,7 +288,7 @@ bool Text::TextLayoutObjectIsNeeded(const AttachContext& context,
if (style.Display() == EDisplay::kNone)
return false;
- if (!ContainsOnlyWhitespace())
+ if (!ContainsOnlyWhitespaceOrEmpty())
return true;
if (!CanHaveWhitespaceChildren(parent, style, context))
diff --git a/chromium/third_party/blink/renderer/core/dom/text.h b/chromium/third_party/blink/renderer/core/dom/text.h
index 8e78c674c25..e44317ab67a 100644
--- a/chromium/third_party/blink/renderer/core/dom/text.h
+++ b/chromium/third_party/blink/renderer/core/dom/text.h
@@ -42,6 +42,9 @@ class CORE_EXPORT Text : public CharacterData {
static Text* Create(Document&, const String&);
static Text* CreateEditingText(Document&, const String&);
+ Text(TreeScope& tree_scope, const String& data, ConstructionType type)
+ : CharacterData(tree_scope, data, type) {}
+
LayoutText* GetLayoutObject() const;
// mergeNextSiblingNodesIfPossible() merges next sibling nodes if possible
@@ -71,10 +74,6 @@ class CORE_EXPORT Text : public CharacterData {
void Trace(blink::Visitor*) override;
- protected:
- Text(TreeScope& tree_scope, const String& data, ConstructionType type)
- : CharacterData(tree_scope, data, type) {}
-
private:
String nodeName() const override;
Node* Clone(Document&, CloneChildrenFlag) const override;
diff --git a/chromium/third_party/blink/renderer/core/dom/text_test.cc b/chromium/third_party/blink/renderer/core/dom/text_test.cc
index 5813957432a..ed16d8cd5f4 100644
--- a/chromium/third_party/blink/renderer/core/dom/text_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/text_test.cc
@@ -21,7 +21,7 @@ TEST_F(TextTest, SetDataToChangeFirstLetterTextNode) {
Node* sample = GetDocument().getElementById("sample");
Text* text = ToText(sample->firstChild());
text->setData(" ");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(text->GetLayoutObject()->IsTextFragment());
}
@@ -34,14 +34,14 @@ TEST_F(TextTest, RemoveFirstLetterPseudoElementWhenNoLetter) {
Range* range = Range::Create(GetDocument(), text, 0, text, 2);
range->deleteContents(ASSERT_NO_EXCEPTION);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(text->GetLayoutObject()->IsTextFragment());
}
TEST_F(TextTest, TextLayoutObjectIsNeeded_CannotHaveChildren) {
SetBodyContent("<img id=image>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* img = GetDocument().getElementById("image");
ASSERT_TRUE(img);
@@ -61,7 +61,7 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_CannotHaveChildren) {
TEST_F(TextTest, TextLayoutObjectIsNeeded_EditingText) {
SetBodyContent("<span id=parent></span>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* parent = GetDocument().getElementById("parent");
ASSERT_TRUE(parent);
@@ -91,7 +91,7 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_EditingText) {
TEST_F(TextTest, TextLayoutObjectIsNeeded_Empty) {
SetBodyContent("<span id=parent></span>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* parent = GetDocument().getElementById("parent");
ASSERT_TRUE(parent);
@@ -112,7 +112,7 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_Whitespace) {
SetBodyContent(
"<div id=block></div>Ends with whitespace "
"<span id=inline></span>Nospace<br id=br>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject* block =
GetDocument().getElementById("block")->GetLayoutObject();
@@ -180,7 +180,7 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_PreserveNewLine) {
<div id=pre-line style='white-space:pre-line'></div>
<div id=pre-wrap style='white-space:pre-wrap'></div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Text* text = Text::Create(GetDocument(), " ");
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.cc b/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.cc
index b02ac81a903..4d70591c129 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.cc
+++ b/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.cc
@@ -41,10 +41,8 @@
namespace blink {
-using namespace HTMLNames;
-
TreeOrderedMap* TreeOrderedMap::Create() {
- return new TreeOrderedMap;
+ return MakeGarbageCollected<TreeOrderedMap>();
}
TreeOrderedMap::TreeOrderedMap() = default;
@@ -80,7 +78,8 @@ inline bool KeyMatchesSlotName(const AtomicString& key,
void TreeOrderedMap::Add(const AtomicString& key, Element& element) {
DCHECK(key);
- Map::AddResult add_result = map_.insert(key, new MapEntry(element));
+ Map::AddResult add_result =
+ map_.insert(key, MakeGarbageCollected<MapEntry>(element));
if (add_result.is_new_entry)
return;
@@ -156,7 +155,7 @@ const HeapVector<Member<Element>>& TreeOrderedMap::GetAllElementsById(
const TreeScope& scope) const {
DCHECK(key);
DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<Element>>>, empty_vector,
- (new HeapVector<Member<Element>>));
+ (MakeGarbageCollected<HeapVector<Member<Element>>>()));
Map::iterator it = map_.find(key);
if (it == map_.end())
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.h b/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.h
index 8a5eba0d681..5ca8d4fbbe9 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.h
+++ b/chromium/third_party/blink/renderer/core/dom/tree_ordered_map.h
@@ -50,6 +50,8 @@ class TreeOrderedMap : public GarbageCollected<TreeOrderedMap> {
public:
static TreeOrderedMap* Create();
+ TreeOrderedMap();
+
void Add(const AtomicString&, Element&);
void Remove(const AtomicString&, Element&);
@@ -91,8 +93,6 @@ class TreeOrderedMap : public GarbageCollected<TreeOrderedMap> {
#endif
private:
- TreeOrderedMap();
-
template <bool keyMatches(const AtomicString&, const Element&)>
Element* Get(const AtomicString&, const TreeScope&) const;
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_scope.cc b/chromium/third_party/blink/renderer/core/dom/tree_scope.cc
index 70fe641e338..1c645585bff 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_scope.cc
+++ b/chromium/third_party/blink/renderer/core/dom/tree_scope.cc
@@ -57,7 +57,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
TreeScope::TreeScope(ContainerNode& root_node, Document& document)
: root_node_(&root_node),
@@ -128,7 +128,7 @@ Element* TreeScope::getElementById(const AtomicString& element_id) const {
const HeapVector<Member<Element>>& TreeScope::GetAllElementsById(
const AtomicString& element_id) const {
DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<Element>>>, empty_vector,
- (new HeapVector<Member<Element>>));
+ (MakeGarbageCollected<HeapVector<Member<Element>>>()));
if (element_id.IsEmpty())
return *empty_vector;
if (!elements_by_id_)
@@ -189,7 +189,9 @@ HTMLMapElement* TreeScope::GetImageMap(const String& url) const {
if (!image_maps_by_name_)
return nullptr;
wtf_size_t hash_pos = url.find('#');
- String name = hash_pos == kNotFound ? url : url.Substring(hash_pos + 1);
+ if (hash_pos == kNotFound)
+ return nullptr;
+ String name = url.Substring(hash_pos + 1);
return ToHTMLMapElement(
image_maps_by_name_->GetElementByMapName(AtomicString(name), *this));
}
@@ -329,8 +331,10 @@ HeapVector<Member<Element>> TreeScope::ElementsFromPoint(double x,
}
SVGTreeScopeResources& TreeScope::EnsureSVGTreeScopedResources() {
- if (!svg_tree_scoped_resources_)
- svg_tree_scoped_resources_ = new SVGTreeScopeResources(this);
+ if (!svg_tree_scoped_resources_) {
+ svg_tree_scoped_resources_ =
+ MakeGarbageCollected<SVGTreeScopeResources>(this);
+ }
return *svg_tree_scoped_resources_;
}
@@ -485,7 +489,7 @@ Element* TreeScope::AdjustedFocusedElement() const {
return nullptr;
}
- EventPath* event_path = new EventPath(*element);
+ EventPath* event_path = MakeGarbageCollected<EventPath>(*element);
for (const auto& context : event_path->NodeEventContexts()) {
if (context.GetNode() == RootNode()) {
// context.target() is one of the followings:
@@ -598,7 +602,7 @@ Element* TreeScope::GetElementByAccessKey(const String& key) const {
Element* result = nullptr;
Node& root = RootNode();
for (Element& element : ElementTraversal::DescendantsOf(root)) {
- if (DeprecatedEqualIgnoringCase(element.FastGetAttribute(accesskeyAttr),
+ if (DeprecatedEqualIgnoringCase(element.FastGetAttribute(kAccesskeyAttr),
key))
result = &element;
if (ShadowRoot* shadow_root = element.GetShadowRoot()) {
@@ -615,10 +619,11 @@ void TreeScope::SetNeedsStyleRecalcForViewportUnits() {
if (ShadowRoot* root = element->GetShadowRoot())
root->SetNeedsStyleRecalcForViewportUnits();
const ComputedStyle* style = element->GetComputedStyle();
- if (style && style->HasViewportUnits())
+ if (style && style->HasViewportUnits()) {
element->SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kViewportUnits));
+ style_change_reason::kViewportUnits));
+ }
}
}
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter_test.cc b/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter_test.cc
index 0a795edaa1e..cc574e3c7e3 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter_test.cc
@@ -17,14 +17,14 @@ TEST(TreeScopeAdopterTest, SimpleMove) {
Document* doc1 = Document::CreateForTest();
Document* doc2 = Document::CreateForTest();
- Element* html1 = doc1->CreateRawElement(HTMLNames::htmlTag);
+ Element* html1 = doc1->CreateRawElement(html_names::kHTMLTag);
doc1->AppendChild(html1);
- Element* div1 = doc1->CreateRawElement(HTMLNames::divTag);
+ Element* div1 = doc1->CreateRawElement(html_names::kDivTag);
html1->AppendChild(div1);
- Element* html2 = doc2->CreateRawElement(HTMLNames::htmlTag);
+ Element* html2 = doc2->CreateRawElement(html_names::kHTMLTag);
doc2->AppendChild(html2);
- Element* div2 = doc1->CreateRawElement(HTMLNames::divTag);
+ Element* div2 = doc1->CreateRawElement(html_names::kDivTag);
html2->AppendChild(div2);
EXPECT_EQ(div1->ownerDocument(), doc1);
@@ -45,9 +45,9 @@ TEST(TreeScopeAdopterTest, AdoptV1ShadowRootToV0Document) {
Document* doc1 = Document::CreateForTest();
Document* doc2 = Document::CreateForTest();
- Element* html1 = doc1->CreateRawElement(HTMLNames::htmlTag);
+ Element* html1 = doc1->CreateRawElement(html_names::kHTMLTag);
doc1->AppendChild(html1);
- Element* div1 = doc1->CreateRawElement(HTMLNames::divTag);
+ Element* div1 = doc1->CreateRawElement(html_names::kDivTag);
html1->AppendChild(div1);
EXPECT_EQ(doc1->GetShadowCascadeOrder(),
ShadowCascadeOrder::kShadowCascadeNone);
@@ -56,9 +56,9 @@ TEST(TreeScopeAdopterTest, AdoptV1ShadowRootToV0Document) {
ShadowCascadeOrder::kShadowCascadeV0);
EXPECT_TRUE(doc1->MayContainV0Shadow());
- Element* html2 = doc2->CreateRawElement(HTMLNames::htmlTag);
+ Element* html2 = doc2->CreateRawElement(html_names::kHTMLTag);
doc2->AppendChild(html2);
- Element* div2 = doc1->CreateRawElement(HTMLNames::divTag);
+ Element* div2 = doc1->CreateRawElement(html_names::kDivTag);
html2->AppendChild(div2);
div2->AttachShadowRootInternal(ShadowRootType::kOpen);
@@ -81,9 +81,9 @@ TEST(TreeScopeAdopterTest, AdoptV0ShadowRootToV1Document) {
Document* doc1 = Document::CreateForTest();
Document* doc2 = Document::CreateForTest();
- Element* html1 = doc1->CreateRawElement(HTMLNames::htmlTag);
+ Element* html1 = doc1->CreateRawElement(html_names::kHTMLTag);
doc1->AppendChild(html1);
- Element* div1 = doc1->CreateRawElement(HTMLNames::divTag);
+ Element* div1 = doc1->CreateRawElement(html_names::kDivTag);
html1->AppendChild(div1);
EXPECT_EQ(doc1->GetShadowCascadeOrder(),
ShadowCascadeOrder::kShadowCascadeNone);
@@ -92,9 +92,9 @@ TEST(TreeScopeAdopterTest, AdoptV0ShadowRootToV1Document) {
ShadowCascadeOrder::kShadowCascadeV1);
EXPECT_FALSE(doc1->MayContainV0Shadow());
- Element* html2 = doc2->CreateRawElement(HTMLNames::htmlTag);
+ Element* html2 = doc2->CreateRawElement(html_names::kHTMLTag);
doc2->AppendChild(html2);
- Element* div2 = doc1->CreateRawElement(HTMLNames::divTag);
+ Element* div2 = doc1->CreateRawElement(html_names::kDivTag);
html2->AppendChild(div2);
div2->CreateV0ShadowRootForTesting();
@@ -115,13 +115,13 @@ TEST(TreeScopeAdopterTest, AdoptV0ShadowRootToV1Document) {
TEST(TreeScopeAdopterTest, AdoptV0InV1ToNewDocument) {
Document* old_doc = Document::CreateForTest();
- Element* html = old_doc->CreateRawElement(HTMLNames::htmlTag);
+ Element* html = old_doc->CreateRawElement(html_names::kHTMLTag);
old_doc->AppendChild(html);
- Element* host1 = old_doc->CreateRawElement(HTMLNames::divTag);
+ Element* host1 = old_doc->CreateRawElement(html_names::kDivTag);
html->AppendChild(host1);
ShadowRoot& shadow_root_v1 =
host1->AttachShadowRootInternal(ShadowRootType::kOpen);
- Element* host2 = old_doc->CreateRawElement(HTMLNames::divTag);
+ Element* host2 = old_doc->CreateRawElement(html_names::kDivTag);
shadow_root_v1.AppendChild(host2);
host2->CreateV0ShadowRootForTesting();
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_scope_test.cc b/chromium/third_party/blink/renderer/core/dom/tree_scope_test.cc
index 62334700cb9..67aa3e2191a 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_scope_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/tree_scope_test.cc
@@ -15,7 +15,7 @@ TEST(TreeScopeTest, CommonAncestorOfSameTrees) {
Document* document = Document::CreateForTest();
EXPECT_EQ(document, document->CommonAncestorTreeScope(*document));
- Element* html = document->CreateRawElement(HTMLNames::htmlTag);
+ Element* html = document->CreateRawElement(html_names::kHTMLTag);
document->AppendChild(html);
ShadowRoot& shadow_root = html->CreateV0ShadowRootForTesting();
EXPECT_EQ(shadow_root, shadow_root.CommonAncestorTreeScope(shadow_root));
@@ -27,7 +27,7 @@ TEST(TreeScopeTest, CommonAncestorOfInclusiveTrees) {
// shadowRoot
Document* document = Document::CreateForTest();
- Element* html = document->CreateRawElement(HTMLNames::htmlTag);
+ Element* html = document->CreateRawElement(html_names::kHTMLTag);
document->AppendChild(html);
ShadowRoot& shadow_root = html->CreateV0ShadowRootForTesting();
@@ -41,11 +41,11 @@ TEST(TreeScopeTest, CommonAncestorOfSiblingTrees) {
// A B
Document* document = Document::CreateForTest();
- Element* html = document->CreateRawElement(HTMLNames::htmlTag);
+ Element* html = document->CreateRawElement(html_names::kHTMLTag);
document->AppendChild(html);
- Element* head = document->CreateRawElement(HTMLNames::headTag);
+ Element* head = document->CreateRawElement(html_names::kHeadTag);
html->AppendChild(head);
- Element* body = document->CreateRawElement(HTMLNames::bodyTag);
+ Element* body = document->CreateRawElement(html_names::kBodyTag);
html->AppendChild(body);
ShadowRoot& shadow_root_a = head->CreateV0ShadowRootForTesting();
@@ -63,17 +63,17 @@ TEST(TreeScopeTest, CommonAncestorOfTreesAtDifferentDepths) {
// A
Document* document = Document::CreateForTest();
- Element* html = document->CreateRawElement(HTMLNames::htmlTag);
+ Element* html = document->CreateRawElement(html_names::kHTMLTag);
document->AppendChild(html);
- Element* head = document->CreateRawElement(HTMLNames::headTag);
+ Element* head = document->CreateRawElement(html_names::kHeadTag);
html->AppendChild(head);
- Element* body = document->CreateRawElement(HTMLNames::bodyTag);
+ Element* body = document->CreateRawElement(html_names::kBodyTag);
html->AppendChild(body);
ShadowRoot& shadow_root_y = head->CreateV0ShadowRootForTesting();
ShadowRoot& shadow_root_b = body->CreateV0ShadowRootForTesting();
- Element* div_in_y = document->CreateRawElement(HTMLNames::divTag);
+ Element* div_in_y = document->CreateRawElement(html_names::kDivTag);
shadow_root_y.AppendChild(div_in_y);
ShadowRoot& shadow_root_a = div_in_y->CreateV0ShadowRootForTesting();
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_walker.h b/chromium/third_party/blink/renderer/core/dom/tree_walker.h
index 97d51f00efa..43f338bde1d 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_walker.h
+++ b/chromium/third_party/blink/renderer/core/dom/tree_walker.h
@@ -41,9 +41,11 @@ class TreeWalker final : public ScriptWrappable, public NodeIteratorBase {
static TreeWalker* Create(Node* root_node,
unsigned what_to_show,
V8NodeFilter* filter) {
- return new TreeWalker(root_node, what_to_show, filter);
+ return MakeGarbageCollected<TreeWalker>(root_node, what_to_show, filter);
}
+ TreeWalker(Node*, unsigned what_to_show, V8NodeFilter*);
+
Node* currentNode() const { return current_.Get(); }
void setCurrentNode(Node*);
@@ -58,8 +60,6 @@ class TreeWalker final : public ScriptWrappable, public NodeIteratorBase {
void Trace(blink::Visitor*) override;
private:
- TreeWalker(Node*, unsigned what_to_show, V8NodeFilter*);
-
Node* SetCurrent(Node*);
template <typename Strategy>
Node* TraverseSiblings(ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.cc b/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.cc
index f086e03482c..930d432559c 100644
--- a/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.cc
+++ b/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.cc
@@ -41,8 +41,6 @@
namespace blink {
-using namespace HTMLNames;
-
V0InsertionPoint::V0InsertionPoint(const QualifiedName& tag_name,
Document& document)
: HTMLElement(tag_name, document, kCreateV0InsertionPoint),
@@ -159,7 +157,7 @@ void V0InsertionPoint::DidRecalcStyle(StyleRecalcChange change) {
node->SetNeedsStyleRecalc(
style_change_type,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kPropagateInheritChangeToDistributedNodes));
+ style_change_reason::kPropagateInheritChangeToDistributedNodes));
}
}
diff --git a/chromium/third_party/blink/renderer/core/dom/visited_link_state.cc b/chromium/third_party/blink/renderer/core/dom/visited_link_state.cc
index 5cedf79b315..9541ae52fa7 100644
--- a/chromium/third_party/blink/renderer/core/dom/visited_link_state.cc
+++ b/chromium/third_party/blink/renderer/core/dom/visited_link_state.cc
@@ -43,7 +43,7 @@ namespace blink {
static inline const AtomicString& LinkAttribute(const Element& element) {
DCHECK(element.IsLink());
if (element.IsHTMLElement())
- return element.FastGetAttribute(HTMLNames::hrefAttr);
+ return element.FastGetAttribute(html_names::kHrefAttr);
DCHECK(element.IsSVGElement());
return SVGURIReference::LegacyHrefString(ToSVGElement(element));
}
diff --git a/chromium/third_party/blink/renderer/core/dom/visited_link_state.h b/chromium/third_party/blink/renderer/core/dom/visited_link_state.h
index 4c4a310cd99..7b663e99667 100644
--- a/chromium/third_party/blink/renderer/core/dom/visited_link_state.h
+++ b/chromium/third_party/blink/renderer/core/dom/visited_link_state.h
@@ -43,9 +43,11 @@ class Document;
class VisitedLinkState : public GarbageCollectedFinalized<VisitedLinkState> {
public:
static VisitedLinkState* Create(const Document& document) {
- return new VisitedLinkState(document);
+ return MakeGarbageCollected<VisitedLinkState>(document);
}
+ explicit VisitedLinkState(const Document&);
+
void InvalidateStyleForAllLinks(bool invalidate_visited_link_hashes);
void InvalidateStyleForLink(LinkHash);
@@ -58,7 +60,6 @@ class VisitedLinkState : public GarbageCollectedFinalized<VisitedLinkState> {
void Trace(blink::Visitor*);
private:
- explicit VisitedLinkState(const Document&);
const Document& GetDocument() const { return *document_; }
EInsideLink DetermineLinkStateSlowCase(const Element&);
diff --git a/chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc b/chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc
index f1c7ea9c996..df1a7ede828 100644
--- a/chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc
+++ b/chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc
@@ -40,6 +40,8 @@ void WhitespaceAttacher::DidReattach(Node* node, LayoutObject* prev_in_flow) {
void WhitespaceAttacher::DidReattachText(Text* text) {
DCHECK(text);
+ if (text->data().IsEmpty())
+ return;
DidReattach(text, text->GetLayoutObject());
SetLastTextNode(text);
if (!text->GetLayoutObject())
@@ -54,11 +56,11 @@ void WhitespaceAttacher::DidReattachElement(Element* element,
void WhitespaceAttacher::DidVisitText(Text* text) {
DCHECK(text);
+ if (text->data().IsEmpty())
+ return;
if (!last_text_node_ || !last_text_node_needs_reattach_) {
- if (text->data().IsEmpty())
- return;
SetLastTextNode(text);
- if (reattach_all_whitespace_nodes_ && text->ContainsOnlyWhitespace())
+ if (reattach_all_whitespace_nodes_ && text->ContainsOnlyWhitespaceOrEmpty())
last_text_node_needs_reattach_ = true;
return;
}
@@ -73,11 +75,11 @@ void WhitespaceAttacher::DidVisitText(Text* text) {
if (LayoutObject* text_layout_object = text->GetLayoutObject()) {
ReattachWhitespaceSiblings(text_layout_object);
} else {
- if (last_text_node_->ContainsOnlyWhitespace())
+ if (last_text_node_->ContainsOnlyWhitespaceOrEmpty())
last_text_node_->ReattachLayoutTreeIfNeeded(Node::AttachContext());
}
SetLastTextNode(text);
- if (reattach_all_whitespace_nodes_ && text->ContainsOnlyWhitespace())
+ if (reattach_all_whitespace_nodes_ && text->ContainsOnlyWhitespaceOrEmpty())
last_text_node_needs_reattach_ = true;
}
@@ -116,7 +118,8 @@ void WhitespaceAttacher::ReattachWhitespaceSiblings(
for (Node* sibling = last_text_node_; sibling;
sibling = LayoutTreeBuilderTraversal::NextLayoutSibling(*sibling)) {
LayoutObject* sibling_layout_object = sibling->GetLayoutObject();
- if (sibling->IsTextNode() && ToText(sibling)->ContainsOnlyWhitespace()) {
+ if (sibling->IsTextNode() &&
+ ToText(sibling)->ContainsOnlyWhitespaceOrEmpty()) {
bool had_layout_object = !!sibling_layout_object;
ToText(sibling)->ReattachLayoutTreeIfNeeded(context);
sibling_layout_object = sibling->GetLayoutObject();
@@ -170,7 +173,7 @@ void WhitespaceAttacher::UpdateLastTextNodeFromDisplayContents() {
LayoutObject* layout_object = sibling->GetLayoutObject();
if (sibling->IsTextNode()) {
Text* text = ToText(sibling);
- if (text->ContainsOnlyWhitespace()) {
+ if (text->ContainsOnlyWhitespaceOrEmpty()) {
last_text_node_ = text;
return;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/whitespace_attacher_test.cc b/chromium/third_party/blink/renderer/core/dom/whitespace_attacher_test.cc
index 34f52617063..b1bc4f58bb0 100644
--- a/chromium/third_party/blink/renderer/core/dom/whitespace_attacher_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/whitespace_attacher_test.cc
@@ -18,7 +18,7 @@ class WhitespaceAttacherTest : public PageTestBase {};
TEST_F(WhitespaceAttacherTest, WhitespaceAfterReattachedBlock) {
GetDocument().body()->SetInnerHTMLFromString("<div id=block></div> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
Text* text = ToText(div->nextSibling());
@@ -38,7 +38,7 @@ TEST_F(WhitespaceAttacherTest, WhitespaceAfterReattachedBlock) {
TEST_F(WhitespaceAttacherTest, WhitespaceAfterReattachedInline) {
GetDocument().body()->SetInnerHTMLFromString("<span id=inline></span> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Text* text = ToText(span->nextSibling());
@@ -58,7 +58,7 @@ TEST_F(WhitespaceAttacherTest, WhitespaceAfterReattachedInline) {
TEST_F(WhitespaceAttacherTest, WhitespaceAfterReattachedWhitespace) {
GetDocument().body()->SetInnerHTMLFromString(
"<span id=inline></span> <!-- --> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Text* first_whitespace = ToText(span->nextSibling());
@@ -84,7 +84,7 @@ TEST_F(WhitespaceAttacherTest, WhitespaceAfterReattachedWhitespace) {
TEST_F(WhitespaceAttacherTest, VisitBlockAfterReattachedWhitespace) {
GetDocument().body()->SetInnerHTMLFromString("<div id=block></div> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
Text* text = ToText(div->nextSibling());
@@ -102,7 +102,7 @@ TEST_F(WhitespaceAttacherTest, VisitBlockAfterReattachedWhitespace) {
TEST_F(WhitespaceAttacherTest, VisitInlineAfterReattachedWhitespace) {
GetDocument().body()->SetInnerHTMLFromString("<span id=inline></span> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Text* text = ToText(span->nextSibling());
@@ -123,7 +123,7 @@ TEST_F(WhitespaceAttacherTest, VisitInlineAfterReattachedWhitespace) {
TEST_F(WhitespaceAttacherTest, VisitTextAfterReattachedWhitespace) {
GetDocument().body()->SetInnerHTMLFromString("Text<!-- --> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Text* text = ToText(GetDocument().body()->firstChild());
Text* whitespace = ToText(text->nextSibling()->nextSibling());
@@ -146,7 +146,7 @@ TEST_F(WhitespaceAttacherTest, VisitTextAfterReattachedWhitespace) {
TEST_F(WhitespaceAttacherTest, ReattachWhitespaceInsideBlockExitingScope) {
GetDocument().body()->SetInnerHTMLFromString("<div id=block> </div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
Text* text = ToText(div->firstChild());
@@ -168,7 +168,7 @@ TEST_F(WhitespaceAttacherTest, ReattachWhitespaceInsideBlockExitingScope) {
TEST_F(WhitespaceAttacherTest, ReattachWhitespaceInsideInlineExitingScope) {
GetDocument().body()->SetInnerHTMLFromString("<span id=inline> </span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Text* text = ToText(span->firstChild());
@@ -195,7 +195,7 @@ TEST_F(WhitespaceAttacherTest, SlottedWhitespaceAfterReattachedBlock) {
ShadowRoot& shadow_root =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString("<div id=block></div><slot></slot>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = shadow_root.getElementById("block");
Text* text = ToText(host->firstChild());
@@ -222,7 +222,7 @@ TEST_F(WhitespaceAttacherTest, SlottedWhitespaceAfterReattachedInline) {
ShadowRoot& shadow_root =
host->AttachShadowRootInternal(ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString("<span id=inline></span><slot></slot>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = shadow_root.getElementById("inline");
Text* text = ToText(host->firstChild());
@@ -245,7 +245,7 @@ TEST_F(WhitespaceAttacherTest,
WhitespaceInDisplayContentsAfterReattachedBlock) {
GetDocument().body()->SetInnerHTMLFromString(
"<div id=block></div><span style='display:contents'> </span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
Element* contents = ToElement(div->nextSibling());
@@ -271,7 +271,7 @@ TEST_F(WhitespaceAttacherTest,
WhitespaceInDisplayContentsAfterReattachedInline) {
GetDocument().body()->SetInnerHTMLFromString(
"<span id=inline></span><span style='display:contents'> </span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Element* contents = ToElement(span->nextSibling());
@@ -296,7 +296,7 @@ TEST_F(WhitespaceAttacherTest,
WhitespaceAfterEmptyDisplayContentsAfterReattachedBlock) {
GetDocument().body()->SetInnerHTMLFromString(
"<div id=block></div><span style='display:contents'></span> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
Element* contents = ToElement(div->nextSibling());
@@ -324,7 +324,7 @@ TEST_F(WhitespaceAttacherTest,
GetDocument().body()->SetInnerHTMLFromString(
"<div id=block></div><span style='display:contents'>"
"<span style='display:none'></span></span> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
Element* contents = ToElement(div->nextSibling());
@@ -352,7 +352,7 @@ TEST_F(WhitespaceAttacherTest, WhitespaceDeepInsideDisplayContents) {
"<span id=inline></span><span style='display:contents'>"
"<span style='display:none'></span>"
"<span id=inner style='display:contents'> </span></span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Element* contents = ToElement(span->nextSibling());
@@ -378,7 +378,7 @@ TEST_F(WhitespaceAttacherTest, MultipleDisplayContents) {
"<span style='display:contents'></span>"
"<span style='display:contents'></span>"
"<span style='display:contents'> </span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
Element* first_contents = ToElement(span->nextSibling());
@@ -412,7 +412,7 @@ TEST_F(WhitespaceAttacherTest, SlottedWhitespaceInsideDisplayContents) {
shadow_root.SetInnerHTMLFromString(
"<span id=inline></span>"
"<div style='display:contents'><slot></slot></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = shadow_root.getElementById("inline");
Element* contents = ToElement(span->nextSibling());
@@ -434,7 +434,7 @@ TEST_F(WhitespaceAttacherTest, SlottedWhitespaceInsideDisplayContents) {
TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeSpace) {
GetDocument().body()->SetInnerHTMLFromString("<span id=inline></span> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
ASSERT_TRUE(span);
@@ -446,7 +446,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeSpace) {
EXPECT_TRUE(text->GetLayoutObject());
span->remove();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(text->previousSibling());
EXPECT_TRUE(text->IsTextNode());
@@ -457,7 +457,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeSpace) {
TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeOutOfFlowBeforeSpace) {
GetDocument().body()->SetInnerHTMLFromString(
"<span id=inline></span><div id=float style='float:right'></div> ");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
ASSERT_TRUE(span);
@@ -473,7 +473,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeOutOfFlowBeforeSpace) {
EXPECT_TRUE(text->GetLayoutObject());
span->remove();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(text->IsTextNode());
EXPECT_FALSE(text->nextSibling());
@@ -482,7 +482,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeOutOfFlowBeforeSpace) {
TEST_F(WhitespaceAttacherTest, RemoveSpaceBeforeSpace) {
GetDocument().body()->SetInnerHTMLFromString("<span> <!-- --> </span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* span = GetDocument().body()->firstChild();
ASSERT_TRUE(span);
@@ -498,7 +498,7 @@ TEST_F(WhitespaceAttacherTest, RemoveSpaceBeforeSpace) {
EXPECT_FALSE(space2->GetLayoutObject());
space1->remove();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(space2->GetLayoutObject());
}
@@ -508,7 +508,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeDisplayContentsWithSpace) {
"<style>div { display: contents }</style>"
"<div><span id=inline></span></div>"
"<div><div><div id=innerdiv> </div></div></div>text");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* span = GetDocument().getElementById("inline");
ASSERT_TRUE(span);
@@ -519,7 +519,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeDisplayContentsWithSpace) {
EXPECT_TRUE(space->GetLayoutObject());
span->remove();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(space->GetLayoutObject());
}
@@ -527,7 +527,7 @@ TEST_F(WhitespaceAttacherTest, RemoveInlineBeforeDisplayContentsWithSpace) {
TEST_F(WhitespaceAttacherTest, RemoveBlockBeforeSpace) {
GetDocument().body()->SetInnerHTMLFromString(
"A<div id=block></div> <span>B</span>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* div = GetDocument().getElementById("block");
ASSERT_TRUE(div);
@@ -538,7 +538,7 @@ TEST_F(WhitespaceAttacherTest, RemoveBlockBeforeSpace) {
EXPECT_FALSE(space->GetLayoutObject());
div->remove();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(space->GetLayoutObject());
}
diff --git a/chromium/third_party/blink/renderer/core/dom/xml_document.h b/chromium/third_party/blink/renderer/core/dom/xml_document.h
index 6496f1bfd49..ae6bfc66009 100644
--- a/chromium/third_party/blink/renderer/core/dom/xml_document.h
+++ b/chromium/third_party/blink/renderer/core/dom/xml_document.h
@@ -36,19 +36,19 @@ class XMLDocument final : public Document {
public:
static XMLDocument* Create(const DocumentInit& initializer) {
- return new XMLDocument(initializer, kXMLDocumentClass);
+ return MakeGarbageCollected<XMLDocument>(initializer, kXMLDocumentClass);
}
static XMLDocument* CreateXHTML(const DocumentInit& initializer) {
- return new XMLDocument(initializer,
- kXMLDocumentClass | kXHTMLDocumentClass);
+ return MakeGarbageCollected<XMLDocument>(
+ initializer, kXMLDocumentClass | kXHTMLDocumentClass);
}
static XMLDocument* CreateSVG(const DocumentInit& initializer) {
- return new XMLDocument(initializer, kXMLDocumentClass | kSVGDocumentClass);
+ return MakeGarbageCollected<XMLDocument>(
+ initializer, kXMLDocumentClass | kSVGDocumentClass);
}
- protected:
XMLDocument(const DocumentInit&, DocumentClassFlags document_classes);
};
diff --git a/chromium/third_party/blink/renderer/core/editing/BUILD.gn b/chromium/third_party/blink/renderer/core/editing/BUILD.gn
index 2e167369198..878a31410c7 100644
--- a/chromium/third_party/blink/renderer/core/editing/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/editing/BUILD.gn
@@ -127,10 +127,13 @@ blink_core_sources("editing") {
"editor.cc",
"editor.h",
"editor_key_bindings.cc",
+ "element_inner_text.cc",
"ephemeral_range.cc",
"ephemeral_range.h",
"finder/find_in_page_coordinates.cc",
"finder/find_in_page_coordinates.h",
+ "finder/find_task_controller.cc",
+ "finder/find_task_controller.h",
"finder/text_finder.cc",
"finder/text_finder.h",
"forward.h",
diff --git a/chromium/third_party/blink/renderer/core/editing/caret_display_item_client_test.cc b/chromium/third_party/blink/renderer/core/editing/caret_display_item_client_test.cc
index 000806dcda6..016d26c9732 100644
--- a/chromium/third_party/blink/renderer/core/editing/caret_display_item_client_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/caret_display_item_client_test.cc
@@ -56,17 +56,17 @@ class CaretDisplayItemClientTest : public PaintAndRasterInvalidationTest {
}
Element* AppendBlock(const String& data) {
- Element* block = GetDocument().CreateRawElement(HTMLNames::divTag);
+ Element* block = GetDocument().CreateRawElement(html_names::kDivTag);
Text* text = GetDocument().createTextNode(data);
block->AppendChild(text);
GetDocument().body()->AppendChild(block);
return block;
}
- void UpdateAllLifecyclePhases() {
+ void UpdateAllLifecyclePhasesForCaretTest() {
// Partial lifecycle updates should not affect caret paint invalidation.
GetDocument().View()->UpdateLifecycleToLayoutClean();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Partial lifecycle updates should not affect caret paint invalidation.
GetDocument().View()->UpdateLifecycleToLayoutClean();
}
@@ -80,13 +80,13 @@ TEST_P(CaretDisplayItemClientTest, CaretPaintInvalidation) {
GetDocument().GetPage()->GetFocusController().SetFocused(true);
Text* text = AppendTextNode("Hello, World!");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
const auto* block = ToLayoutBlock(GetDocument().body()->GetLayoutObject());
// Focus the body. Should invalidate the new caret.
GetDocument().View()->SetTracksPaintInvalidations(true);
GetDocument().body()->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
EXPECT_TRUE(block->ShouldPaintCursorCaret());
LayoutRect caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
@@ -108,7 +108,7 @@ TEST_P(CaretDisplayItemClientTest, CaretPaintInvalidation) {
GetDocument().View()->SetTracksPaintInvalidations(true);
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder().Collapse(Position(text, 5)).Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(block->ShouldPaintCursorCaret());
LayoutRect new_caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
@@ -134,7 +134,7 @@ TEST_P(CaretDisplayItemClientTest, CaretPaintInvalidation) {
LayoutRect old_caret_visual_rect = new_caret_visual_rect;
GetDocument().View()->SetTracksPaintInvalidations(true);
Selection().SetSelectionAndEndTyping(SelectionInDOMTree());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
EXPECT_FALSE(block->ShouldPaintCursorCaret());
EXPECT_EQ(LayoutRect(), GetCaretDisplayItemClient().VisualRect());
@@ -155,13 +155,13 @@ TEST_P(CaretDisplayItemClientTest, CaretMovesBetweenBlocks) {
GetDocument().GetPage()->GetFocusController().SetFocused(true);
auto* block_element1 = AppendBlock("Block1");
auto* block_element2 = AppendBlock("Block2");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* block1 = ToLayoutBlockFlow(block_element1->GetLayoutObject());
auto* block2 = ToLayoutBlockFlow(block_element2->GetLayoutObject());
// Focus the body.
GetDocument().body()->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
LayoutRect caret_visual_rect1 = GetCaretDisplayItemClient().VisualRect();
EXPECT_EQ(1, caret_visual_rect1.Width());
EXPECT_EQ(block1->FirstFragment().VisualRect().Location(),
@@ -175,7 +175,7 @@ TEST_P(CaretDisplayItemClientTest, CaretMovesBetweenBlocks) {
SelectionInDOMTree::Builder()
.Collapse(Position(block_element2, 0))
.Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutRect caret_visual_rect2 = GetCaretDisplayItemClient().VisualRect();
EXPECT_EQ(1, caret_visual_rect2.Width());
@@ -204,7 +204,7 @@ TEST_P(CaretDisplayItemClientTest, CaretMovesBetweenBlocks) {
SelectionInDOMTree::Builder()
.Collapse(Position(block_element1, 0))
.Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
EXPECT_EQ(caret_visual_rect1, GetCaretDisplayItemClient().VisualRect());
EXPECT_TRUE(block1->ShouldPaintCursorCaret());
@@ -231,7 +231,7 @@ TEST_P(CaretDisplayItemClientTest, UpdatePreviousLayoutBlock) {
GetDocument().GetPage()->GetFocusController().SetFocused(true);
auto* block_element1 = AppendBlock("Block1");
auto* block_element2 = AppendBlock("Block2");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
auto* block1 = ToLayoutBlock(block_element1->GetLayoutObject());
auto* block2 = ToLayoutBlock(block_element2->GetLayoutObject());
@@ -280,7 +280,7 @@ TEST_P(CaretDisplayItemClientTest, UpdatePreviousLayoutBlock) {
SelectionInDOMTree::Builder()
.Collapse(Position(block_element1, 0))
.Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
// Remove selection.
Selection().SetSelectionAndEndTyping(SelectionInDOMTree());
GetDocument().View()->UpdateLifecycleToLayoutClean();
@@ -294,7 +294,7 @@ TEST_P(CaretDisplayItemClientTest, CaretHideMoveAndShow) {
Text* text = AppendTextNode("Hello, World!");
GetDocument().body()->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
const auto* block = ToLayoutBlock(GetDocument().body()->GetLayoutObject());
LayoutRect caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
@@ -309,7 +309,7 @@ TEST_P(CaretDisplayItemClientTest, CaretHideMoveAndShow) {
SelectionInDOMTree::Builder().Collapse(Position(text, 5)).Build());
// Simulate that the cursor blinking is restarted.
Selection().SetCaretVisible(true);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
LayoutRect new_caret_visual_rect = GetCaretDisplayItemClient().VisualRect();
EXPECT_EQ(caret_visual_rect.Size(), new_caret_visual_rect.Size());
@@ -348,7 +348,7 @@ TEST_P(CaretDisplayItemClientTest, CompositingChange) {
auto* editor_block = ToLayoutBlock(editor->GetLayoutObject());
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder().Collapse(Position(editor, 0)).Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForCaretTest();
EXPECT_TRUE(editor_block->ShouldPaintCursorCaret());
EXPECT_EQ(editor_block, CaretLayoutBlock());
@@ -356,8 +356,8 @@ TEST_P(CaretDisplayItemClientTest, CompositingChange) {
GetCaretDisplayItemClient().VisualRect());
// Composite container.
- container->setAttribute(HTMLNames::styleAttr, "will-change: transform");
- UpdateAllLifecyclePhases();
+ container->setAttribute(html_names::kStyleAttr, "will-change: transform");
+ UpdateAllLifecyclePhasesForCaretTest();
// TODO(wangxianzhu): Why will-change:transform doens't trigger compositing
// in SPv2?
if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
@@ -366,8 +366,8 @@ TEST_P(CaretDisplayItemClientTest, CompositingChange) {
}
// Uncomposite container.
- container->setAttribute(HTMLNames::styleAttr, "");
- UpdateAllLifecyclePhases();
+ container->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhasesForCaretTest();
EXPECT_EQ(LayoutRect(116, 105, 1, 1),
GetCaretDisplayItemClient().VisualRect());
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc
index 507972f33e0..0f7d9165e34 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc
@@ -42,7 +42,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
ApplyBlockElementCommand::ApplyBlockElementCommand(
Document& document,
@@ -418,7 +418,7 @@ ApplyBlockElementCommand::EndOfNextParagrahSplittingTextNodesIfNeeded(
HTMLElement* ApplyBlockElementCommand::CreateBlockElement() const {
HTMLElement* element = CreateHTMLElement(GetDocument(), tag_name_);
if (inline_style_.length())
- element->setAttribute(styleAttr, inline_style_);
+ element->setAttribute(kStyleAttr, inline_style_);
return element;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command_test.cc
index 8ad2938083f..930b54b2eb5 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/apply_block_element_command_test.cc
@@ -46,7 +46,7 @@ TEST_F(ApplyBlockElementCommandTest, selectionCrossingOverBody) {
SetSelectionOptions());
FormatBlockCommand* command =
- FormatBlockCommand::Create(GetDocument(), HTMLNames::footerTag);
+ FormatBlockCommand::Create(GetDocument(), html_names::kFooterTag);
command->Apply();
EXPECT_EQ(
@@ -63,7 +63,7 @@ TEST_F(ApplyBlockElementCommandTest, visibilityChangeDuringCommand) {
SetBodyContent("<ul style='visibility:hidden'><li>xyz</li></ul>");
GetDocument().setDesignMode("on");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Selection().SetSelection(
SelectionInDOMTree::Builder()
.Collapse(Position(GetDocument().QuerySelector("li"), 0))
@@ -121,7 +121,7 @@ TEST_F(ApplyBlockElementCommandTest, InsertPlaceHolderAtDisconnectedPosition) {
"^<input><input class=\"input\" style=\"position:absolute\">|"),
SetSelectionOptions());
FormatBlockCommand* command =
- FormatBlockCommand::Create(GetDocument(), HTMLNames::preTag);
+ FormatBlockCommand::Create(GetDocument(), html_names::kPreTag);
// Crash happens here.
EXPECT_FALSE(command->Apply());
EXPECT_EQ(
@@ -137,7 +137,7 @@ TEST_F(ApplyBlockElementCommandTest, FormatBlockCrossingUserModifyBoundary) {
"^<b style=\"-webkit-user-modify:read-only\"><button></button></b>|"),
SetSelectionOptions());
FormatBlockCommand* command =
- FormatBlockCommand::Create(GetDocument(), HTMLNames::preTag);
+ FormatBlockCommand::Create(GetDocument(), html_names::kPreTag);
// Shouldn't crash here.
EXPECT_FALSE(command->Apply());
EXPECT_EQ(
@@ -156,7 +156,7 @@ TEST_F(ApplyBlockElementCommandTest,
"/button></kbd>|"),
SetSelectionOptions());
FormatBlockCommand* command =
- FormatBlockCommand::Create(GetDocument(), HTMLNames::preTag);
+ FormatBlockCommand::Create(GetDocument(), html_names::kPreTag);
// Shouldn't crash here.
EXPECT_FALSE(command->Apply());
EXPECT_EQ(
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command.cc
index e3f5775c4ec..e31fc21483e 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command.cc
@@ -27,8 +27,8 @@
#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node_list.h"
@@ -60,7 +60,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool HasNoAttributeOrOnlyStyleAttribute(
const HTMLElement* element,
@@ -70,7 +70,7 @@ static bool HasNoAttributeOrOnlyStyleAttribute(
return true;
unsigned matched_attributes = 0;
- if (element->hasAttribute(styleAttr) &&
+ if (element->hasAttribute(kStyleAttr) &&
(should_style_attribute_be_empty == kAllowNonEmptyStyleAttribute ||
!element->InlineStyle() || element->InlineStyle()->IsEmpty()))
matched_attributes++;
@@ -512,11 +512,11 @@ void ApplyStyleCommand::ApplyRelativeFontStyleChange(
*CSSPrimitiveValue::Create(desired_font_size,
CSSPrimitiveValue::UnitType::kPixels),
false);
- SetNodeAttribute(element, styleAttr,
+ SetNodeAttribute(element, kStyleAttr,
AtomicString(inline_style->AsText()));
}
if (inline_style->IsEmpty()) {
- RemoveElementAttribute(element, styleAttr);
+ RemoveElementAttribute(element, kStyleAttr);
if (IsSpanWithoutAttributesOrUnstyledStyleSpan(element))
unstyled_spans.push_back(element);
}
@@ -646,16 +646,16 @@ void ApplyStyleCommand::RemoveEmbeddingUpToEnclosingBlock(
// it assumes that if the 'dir' attribute is present, then removing it will
// suffice, and otherwise it sets the property in the inline style
// declaration.
- if (element->hasAttribute(dirAttr)) {
+ if (element->hasAttribute(kDirAttr)) {
// FIXME: If this is a BDO element, we should probably just remove it if
// it has no other attributes, like we (should) do with B and I elements.
- RemoveElementAttribute(element, dirAttr);
+ RemoveElementAttribute(element, kDirAttr);
} else {
MutableCSSPropertyValueSet* inline_style =
CopyStyleOrCreateEmpty(element->InlineStyle());
inline_style->SetProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
inline_style->RemoveProperty(CSSPropertyDirection);
- SetNodeAttribute(element, styleAttr,
+ SetNodeAttribute(element, kStyleAttr,
AtomicString(inline_style->AsText()));
if (IsSpanWithoutAttributesOrUnstyledStyleSpan(element)) {
RemoveNodePreservingChildren(element, editing_state);
@@ -998,7 +998,7 @@ void ApplyStyleCommand::ApplyInlineStyleToNodeRange(
MutableCSSPropertyValueSet* inline_style =
CopyStyleOrCreateEmpty(element->InlineStyle());
inline_style->MergeAndOverrideOnConflict(style->Style());
- SetNodeAttribute(element, styleAttr,
+ SetNodeAttribute(element, kStyleAttr,
AtomicString(inline_style->AsText()));
continue;
}
@@ -1327,7 +1327,7 @@ void ApplyStyleCommand::ApplyInlineStyleToPushDown(
// FIXME: applyInlineStyleToRange should be used here instead.
if ((node->GetLayoutObject()->IsLayoutBlockFlow() || node->hasChildren()) &&
node->IsHTMLElement()) {
- SetNodeAttribute(ToHTMLElement(node), styleAttr,
+ SetNodeAttribute(ToHTMLElement(node), kStyleAttr,
AtomicString(new_inline_style->Style()->AsText()));
return;
}
@@ -1389,12 +1389,12 @@ void ApplyStyleCommand::PushDownInlineStyleAroundNode(
if (!child->contains(target_node) && elements_to_push_down.size()) {
for (const auto& element : elements_to_push_down) {
Element* wrapper = element->CloneWithoutChildren();
- wrapper->removeAttribute(styleAttr);
+ wrapper->removeAttribute(kStyleAttr);
// Delete id attribute from the second element because the same id
// cannot be used for more than one element
- element->removeAttribute(HTMLNames::idAttr);
+ element->removeAttribute(html_names::kIdAttr);
if (IsHTMLAnchorElement(element))
- element->removeAttribute(HTMLNames::nameAttr);
+ element->removeAttribute(html_names::kNameAttr);
SurroundNodeRangeWithElement(child, child, wrapper, editing_state);
if (editing_state->IsAborted())
return;
@@ -1826,7 +1826,7 @@ void ApplyStyleCommand::AddBlockStyle(const StyleChange& style_change,
css_text.Append(' ');
css_text.Append(decl->AsText());
}
- SetNodeAttribute(block, styleAttr, css_text.ToAtomicString());
+ SetNodeAttribute(block, kStyleAttr, css_text.ToAtomicString());
}
void ApplyStyleCommand::AddInlineStyleIfNeeded(EditingStyle* style,
@@ -1910,24 +1910,24 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
style_change.ApplyFontSize()) {
if (font_container) {
if (style_change.ApplyFontColor())
- SetNodeAttribute(font_container, colorAttr,
+ SetNodeAttribute(font_container, kColorAttr,
AtomicString(style_change.FontColor()));
if (style_change.ApplyFontFace())
- SetNodeAttribute(font_container, faceAttr,
+ SetNodeAttribute(font_container, kFaceAttr,
AtomicString(style_change.FontFace()));
if (style_change.ApplyFontSize())
- SetNodeAttribute(font_container, sizeAttr,
+ SetNodeAttribute(font_container, kSizeAttr,
AtomicString(style_change.FontSize()));
} else {
HTMLFontElement* font_element = HTMLFontElement::Create(GetDocument());
if (style_change.ApplyFontColor())
- font_element->setAttribute(colorAttr,
+ font_element->setAttribute(kColorAttr,
AtomicString(style_change.FontColor()));
if (style_change.ApplyFontFace())
- font_element->setAttribute(faceAttr,
+ font_element->setAttribute(kFaceAttr,
AtomicString(style_change.FontFace()));
if (style_change.ApplyFontSize())
- font_element->setAttribute(sizeAttr,
+ font_element->setAttribute(kSizeAttr,
AtomicString(style_change.FontSize()));
SurroundNodeRangeWithElement(start_node, end_node, font_element,
editing_state);
@@ -1946,14 +1946,15 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
if (!existing_text.IsEmpty())
css_text.Append(' ');
css_text.Append(style_change.CssStyle());
- SetNodeAttribute(style_container, styleAttr, css_text.ToAtomicString());
+ SetNodeAttribute(style_container, kStyleAttr,
+ css_text.ToAtomicString());
} else {
- SetNodeAttribute(style_container, styleAttr,
+ SetNodeAttribute(style_container, kStyleAttr,
AtomicString(style_change.CssStyle()));
}
} else {
HTMLSpanElement* style_element = HTMLSpanElement::Create(GetDocument());
- style_element->setAttribute(styleAttr,
+ style_element->setAttribute(kStyleAttr,
AtomicString(style_change.CssStyle()));
SurroundNodeRangeWithElement(start_node, end_node, style_element,
editing_state);
@@ -1964,7 +1965,7 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
if (style_change.ApplyBold()) {
SurroundNodeRangeWithElement(start_node, end_node,
- HTMLElement::Create(bTag, GetDocument()),
+ HTMLElement::Create(kBTag, GetDocument()),
editing_state);
if (editing_state->IsAborted())
return;
@@ -1972,7 +1973,7 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
if (style_change.ApplyItalic()) {
SurroundNodeRangeWithElement(start_node, end_node,
- HTMLElement::Create(iTag, GetDocument()),
+ HTMLElement::Create(kITag, GetDocument()),
editing_state);
if (editing_state->IsAborted())
return;
@@ -1980,7 +1981,7 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
if (style_change.ApplyUnderline()) {
SurroundNodeRangeWithElement(start_node, end_node,
- HTMLElement::Create(uTag, GetDocument()),
+ HTMLElement::Create(kUTag, GetDocument()),
editing_state);
if (editing_state->IsAborted())
return;
@@ -1988,7 +1989,7 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
if (style_change.ApplyLineThrough()) {
SurroundNodeRangeWithElement(start_node, end_node,
- HTMLElement::Create(strikeTag, GetDocument()),
+ HTMLElement::Create(kStrikeTag, GetDocument()),
editing_state);
if (editing_state->IsAborted())
return;
@@ -1996,13 +1997,13 @@ void ApplyStyleCommand::ApplyInlineStyleChange(
if (style_change.ApplySubscript()) {
SurroundNodeRangeWithElement(start_node, end_node,
- HTMLElement::Create(subTag, GetDocument()),
+ HTMLElement::Create(kSubTag, GetDocument()),
editing_state);
if (editing_state->IsAborted())
return;
} else if (style_change.ApplySuperscript()) {
SurroundNodeRangeWithElement(start_node, end_node,
- HTMLElement::Create(supTag, GetDocument()),
+ HTMLElement::Create(kSupTag, GetDocument()),
editing_state);
if (editing_state->IsAborted())
return;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc
index edbe6e4ad38..fc6480c5538 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/apply_style_command_test.cc
@@ -66,7 +66,7 @@ TEST_F(ApplyStyleCommandTest, JustifyRightDetachesDestination) {
"</ruby");
Element* body = GetDocument().body();
// The bug does't reproduce with a contenteditable <div> as container.
- body->setAttribute(HTMLNames::contenteditableAttr, "true");
+ body->setAttribute(html_names::kContenteditableAttr, "true");
GetDocument().UpdateStyleAndLayout();
Selection().SelectAll();
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/break_blockquote_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/break_blockquote_command.cc
index 8371c099e11..7a477b5b827 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/break_blockquote_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/break_blockquote_command.cc
@@ -42,7 +42,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -238,7 +238,7 @@ void BreakBlockquoteCommand::DoApply(EditingState* editing_state) {
list_child_node = list_child_node->nextSibling();
if (IsListItem(list_child_node))
SetNodeAttribute(
- cloned_child, startAttr,
+ cloned_child, kStartAttr,
AtomicString::Number(
ToLayoutListItem(list_child_node->GetLayoutObject())->Value()));
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc b/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
index ea1691d9626..a2540da593b 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/editing/commands/clipboard_commands.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/clipboard/data_transfer_access_policy.h"
#include "third_party/blink/renderer/core/clipboard/paste_mode.h"
#include "third_party/blink/renderer/core/clipboard/system_clipboard.h"
@@ -43,7 +44,6 @@
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/events/clipboard_event.h"
#include "third_party/blink/renderer/core/events/text_event.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
@@ -147,7 +147,7 @@ bool ClipboardCommands::DispatchCopyOrCutEvent(LocalFrame& frame,
bool ClipboardCommands::DispatchPasteEvent(LocalFrame& frame,
PasteMode paste_mode,
EditorCommandSource source) {
- return DispatchClipboardEvent(frame, EventTypeNames::paste,
+ return DispatchClipboardEvent(frame, event_type_names::kPaste,
DataTransferAccessPolicy::kReadable, source,
paste_mode);
}
@@ -163,7 +163,8 @@ bool ClipboardCommands::EnabledCopy(LocalFrame& frame,
EditorCommandSource source) {
if (!CanWriteClipboard(frame, source))
return false;
- return !DispatchCopyOrCutEvent(frame, source, EventTypeNames::beforecopy) ||
+ return !DispatchCopyOrCutEvent(frame, source,
+ event_type_names::kBeforecopy) ||
frame.GetEditor().CanCopy();
}
@@ -175,7 +176,7 @@ bool ClipboardCommands::EnabledCut(LocalFrame& frame,
if (source == EditorCommandSource::kMenuOrKeyBinding &&
!frame.Selection().SelectionHasFocus())
return false;
- return !DispatchCopyOrCutEvent(frame, source, EventTypeNames::beforecut) ||
+ return !DispatchCopyOrCutEvent(frame, source, event_type_names::kBeforecut) ||
frame.GetEditor().CanCut();
}
@@ -221,7 +222,7 @@ bool ClipboardCommands::ExecuteCopy(LocalFrame& frame,
Event*,
EditorCommandSource source,
const String&) {
- if (!DispatchCopyOrCutEvent(frame, source, EventTypeNames::copy))
+ if (!DispatchCopyOrCutEvent(frame, source, event_type_names::kCopy))
return true;
if (!frame.GetEditor().CanCopy())
return true;
@@ -279,7 +280,7 @@ bool ClipboardCommands::ExecuteCut(LocalFrame& frame,
Event*,
EditorCommandSource source,
const String&) {
- if (!DispatchCopyOrCutEvent(frame, source, EventTypeNames::cut))
+ if (!DispatchCopyOrCutEvent(frame, source, event_type_names::kCut))
return true;
if (!frame.GetEditor().CanCut())
return true;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc
index e6f337e7076..fb860ab0c14 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc
@@ -84,7 +84,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
CompositeEditCommand::CompositeEditCommand(Document& document)
: EditCommand(document) {
@@ -363,9 +363,9 @@ void CompositeEditCommand::AppendNode(Node* node,
// TODO(yosin): We should get rid of |canHaveChildrenForEditing()|, since
// |cloneParagraphUnderNewElement()| attempt to clone non-well-formed HTML,
// produced by JavaScript.
- ABORT_EDITING_COMMAND_IF(
- !CanHaveChildrenForEditing(parent) &&
- !(parent->IsElementNode() && ToElement(parent)->TagQName() == objectTag));
+ ABORT_EDITING_COMMAND_IF(!CanHaveChildrenForEditing(parent) &&
+ !(parent->IsElementNode() &&
+ ToElement(parent)->TagQName() == kObjectTag));
ABORT_EDITING_COMMAND_IF(!HasEditableStyle(*parent) &&
parent->InActiveDocument());
ApplyCommandToComposite(AppendNodeCommand::Create(parent, node),
@@ -1644,8 +1644,10 @@ bool CompositeEditCommand::BreakOutOfEmptyListItem(
if (ContainerNode* block_enclosing_list = list_node->parentNode()) {
if (IsHTMLLIElement(
*block_enclosing_list)) { // listNode is inside another list item
- if (VisiblePositionAfterNode(*block_enclosing_list).DeepEquivalent() ==
- VisiblePositionAfterNode(*list_node).DeepEquivalent()) {
+ if (CreateVisiblePosition(PositionAfterNode(*block_enclosing_list))
+ .DeepEquivalent() ==
+ CreateVisiblePosition(PositionAfterNode(*list_node))
+ .DeepEquivalent()) {
// If listNode appears at the end of the outer list item, then move
// listNode outside of this list item, e.g.
// <ul><li>hello <ul><li><br></li></ul> </li></ul>
@@ -1981,7 +1983,7 @@ bool CompositeEditCommand::IsNodeVisiblyContainedWithin(
return true;
bool start_is_visually_same =
- VisiblePositionBeforeNode(node).DeepEquivalent() ==
+ CreateVisiblePosition(PositionBeforeNode(node)).DeepEquivalent() ==
CreateVisiblePosition(selected_range.StartPosition()).DeepEquivalent();
if (start_is_visually_same &&
ComparePositions(Position::InParentAfterNode(node),
@@ -1989,7 +1991,7 @@ bool CompositeEditCommand::IsNodeVisiblyContainedWithin(
return true;
bool end_is_visually_same =
- VisiblePositionAfterNode(node).DeepEquivalent() ==
+ CreateVisiblePosition(PositionAfterNode(node)).DeepEquivalent() ==
CreateVisiblePosition(selected_range.EndPosition()).DeepEquivalent();
if (end_is_visually_same &&
ComparePositions(selected_range.StartPosition(),
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.h b/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.h
index 4a791b36376..635d59a94cb 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_COMPOSITE_EDIT_COMMAND_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/editing/commands/edit_command.h"
#include "third_party/blink/renderer/core/editing/commands/editing_state.h"
#include "third_party/blink/renderer/core/editing/commands/undo_step.h"
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command_test.cc
index 00ce0d5b6ef..1e898abeb71 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command_test.cc
@@ -112,7 +112,7 @@ TEST_F(CompositeEditCommandTest, insertNodeBeforeWithDirtyLayoutTree) {
Node* insert_child = GetDocument().createTextNode("foo");
Element* ref_child = GetDocument().QuerySelector("b");
Element* div = GetDocument().QuerySelector("div");
- div->setAttribute(HTMLNames::contenteditableAttr, "true");
+ div->setAttribute(html_names::kContenteditableAttr, "true");
EditingState editing_state;
sample.InsertNodeBefore(insert_child, ref_child, &editing_state);
@@ -128,7 +128,7 @@ TEST_F(CompositeEditCommandTest,
SampleCommand& sample = *new SampleCommand(GetDocument());
Element* body = GetDocument().body();
Node* text = body->lastChild();
- body->setAttribute(HTMLNames::contenteditableAttr, "true");
+ body->setAttribute(html_names::kContenteditableAttr, "true");
GetDocument().UpdateStyleAndLayout();
EditingState editing_state;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/delete_from_text_node_command.h b/chromium/third_party/blink/renderer/core/editing/commands/delete_from_text_node_command.h
index 9ceb5b96d69..f361a8d3011 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/delete_from_text_node_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/delete_from_text_node_command.h
@@ -37,14 +37,14 @@ class DeleteFromTextNodeCommand final : public SimpleEditCommand {
static DeleteFromTextNodeCommand* Create(Text* node,
unsigned offset,
unsigned count) {
- return new DeleteFromTextNodeCommand(node, offset, count);
+ return MakeGarbageCollected<DeleteFromTextNodeCommand>(node, offset, count);
}
+ DeleteFromTextNodeCommand(Text*, unsigned offset, unsigned count);
+
void Trace(blink::Visitor*) override;
private:
- DeleteFromTextNodeCommand(Text*, unsigned offset, unsigned count);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.cc
index be930264970..fa0d084413c 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.cc
@@ -49,8 +49,6 @@
namespace blink {
-using namespace HTMLNames;
-
static bool IsTableCellEmpty(Node* cell) {
DCHECK(cell);
DCHECK(IsTableCell(cell)) << cell;
@@ -903,8 +901,10 @@ void DeleteSelectionCommand::MergeParagraphs(EditingState* editing_state) {
// the right.
// FIXME: Consider RTL.
if (!starts_at_empty_line_ && IsStartOfParagraph(merge_destination) &&
- AbsoluteCaretBoundsOf(start_of_paragraph_to_move).X() >
- AbsoluteCaretBoundsOf(merge_destination).X()) {
+ AbsoluteCaretBoundsOf(start_of_paragraph_to_move.ToPositionWithAffinity())
+ .X() >
+ AbsoluteCaretBoundsOf(merge_destination.ToPositionWithAffinity())
+ .X()) {
if (IsHTMLBRElement(
*MostForwardCaretPosition(merge_destination.DeepEquivalent())
.AnchorNode())) {
@@ -1189,7 +1189,7 @@ void DeleteSelectionCommand::DoApply(EditingState* editing_state) {
}
// HandleGeneralDelete cause DOM mutation events so |ending_position_|
// can be out of document.
- if (ending_position_.IsConnected()) {
+ if (ending_position_.IsValidFor(GetDocument())) {
InsertNodeAt(placeholder, ending_position_, editing_state);
if (editing_state->IsAborted())
return;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.h b/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.h
index 81d8edea1e0..ca382fd8d0e 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_command.h
@@ -42,19 +42,17 @@ class CORE_EXPORT DeleteSelectionCommand final : public CompositeEditCommand {
const DeleteSelectionOptions& options,
InputEvent::InputType input_type = InputEvent::InputType::kNone,
const Position& reference_move_position = Position()) {
- return new DeleteSelectionCommand(document, options, input_type,
- reference_move_position);
+ return MakeGarbageCollected<DeleteSelectionCommand>(
+ document, options, input_type, reference_move_position);
}
static DeleteSelectionCommand* Create(
const VisibleSelection& selection,
const DeleteSelectionOptions& options,
InputEvent::InputType input_type = InputEvent::InputType::kNone) {
- return new DeleteSelectionCommand(selection, options, input_type);
+ return MakeGarbageCollected<DeleteSelectionCommand>(selection, options,
+ input_type);
}
- void Trace(blink::Visitor*) override;
-
- private:
DeleteSelectionCommand(Document&,
const DeleteSelectionOptions&,
InputEvent::InputType,
@@ -63,6 +61,9 @@ class CORE_EXPORT DeleteSelectionCommand final : public CompositeEditCommand {
const DeleteSelectionOptions&,
InputEvent::InputType);
+ void Trace(blink::Visitor*) override;
+
+ private:
void DoApply(EditingState*) override;
InputEvent::InputType GetInputType() const override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/drag_and_drop_command.h b/chromium/third_party/blink/renderer/core/editing/commands/drag_and_drop_command.h
index baa7a83c80f..36f25d196a9 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/drag_and_drop_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/drag_and_drop_command.h
@@ -17,15 +17,15 @@ namespace blink {
class DragAndDropCommand final : public CompositeEditCommand {
public:
static DragAndDropCommand* Create(Document& document) {
- return new DragAndDropCommand(document);
+ return MakeGarbageCollected<DragAndDropCommand>(document);
}
+ explicit DragAndDropCommand(Document&);
+
bool IsCommandGroupWrapper() const override;
bool IsDragAndDropCommand() const override;
private:
- explicit DragAndDropCommand(Document&);
-
void DoApply(EditingState*) override;
InputEvent::InputType GetInputType() const override;
};
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/editing_commands_utilities.cc b/chromium/third_party/blink/renderer/core/editing/commands/editing_commands_utilities.cc
index 2ad4f9f9560..d866658dc1d 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/editing_commands_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/editing_commands_utilities.cc
@@ -351,7 +351,7 @@ bool LineBreakExistsAtVisiblePosition(const VisiblePosition& visible_position) {
}
HTMLElement* CreateHTMLElement(Document& document, const QualifiedName& name) {
- DCHECK_EQ(name.NamespaceURI(), HTMLNames::xhtmlNamespaceURI)
+ DCHECK_EQ(name.NamespaceURI(), html_names::xhtmlNamespaceURI)
<< "Unexpected namespace: " << name;
return ToHTMLElement(document.CreateElement(
name, CreateElementFlags::ByCloneNode(), g_null_atom));
@@ -581,11 +581,11 @@ void DispatchEditableContentChangedEvents(Element* start_root,
Element* end_root) {
if (start_root) {
start_root->DispatchEvent(
- *Event::Create(EventTypeNames::webkitEditableContentChanged));
+ *Event::Create(event_type_names::kWebkitEditableContentChanged));
}
if (end_root && end_root != start_root) {
end_root->DispatchEvent(
- *Event::Create(EventTypeNames::webkitEditableContentChanged));
+ *Event::Create(event_type_names::kWebkitEditableContentChanged));
}
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/editor_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/editor_command.cc
index da47c6e9914..2e631eeb321 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/editor_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/editor_command.cc
@@ -29,8 +29,8 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_editing_command_type.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/tag_collection.h"
@@ -73,7 +73,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -202,7 +202,7 @@ StaticRangeVector* RangesFromCurrentSelectionOrExtendCaret(
if (selection_modifier.Selection().IsCaret())
selection_modifier.Modify(SelectionModifyAlteration::kExtend, direction,
granularity);
- StaticRangeVector* ranges = new StaticRangeVector;
+ StaticRangeVector* ranges = MakeGarbageCollected<StaticRangeVector>();
// We only supports single selections.
if (selection_modifier.Selection().IsNone())
return ranges;
@@ -312,7 +312,8 @@ static EditingTriState SelectionListState(const FrameSelection& selection,
// If the selected list has the different type of list as child, return
// |FalseTriState|.
// See http://crbug.com/385374
- if (HasChildTags(*start_element, tag_name.Matches(ulTag) ? olTag : ulTag))
+ if (HasChildTags(*start_element,
+ tag_name.Matches(kUlTag) ? kOlTag : kUlTag))
return EditingTriState::kFalse;
return EditingTriState::kTrue;
}
@@ -898,10 +899,11 @@ static bool ExecuteTranspose(LocalFrame& frame,
return false;
const String& transposed = text.Right(1) + text.Left(1);
- if (DispatchBeforeInputInsertText(
- EventTargetNodeForDocument(document), transposed,
- InputEvent::InputType::kInsertTranspose,
- new StaticRangeVector(1, StaticRange::Create(range))) !=
+ if (DispatchBeforeInputInsertText(EventTargetNodeForDocument(document),
+ transposed,
+ InputEvent::InputType::kInsertTranspose,
+ MakeGarbageCollected<StaticRangeVector>(
+ 1, StaticRange::Create(range))) !=
DispatchEventResult::kNotCanceled)
return false;
@@ -1196,11 +1198,11 @@ static EditingTriState StateNone(LocalFrame&, Event*) {
}
EditingTriState StateOrderedList(LocalFrame& frame, Event*) {
- return SelectionListState(frame.Selection(), olTag);
+ return SelectionListState(frame.Selection(), kOlTag);
}
static EditingTriState StateUnorderedList(LocalFrame& frame, Event*) {
- return SelectionListState(frame.Selection(), ulTag);
+ return SelectionListState(frame.Selection(), kUlTag);
}
static EditingTriState StateJustifyCenter(LocalFrame& frame, Event*) {
@@ -1243,9 +1245,9 @@ static String ValueDefaultParagraphSeparator(const EditorInternalCommand&,
Event*) {
switch (frame.GetEditor().DefaultParagraphSeparator()) {
case EditorParagraphSeparator::kIsDiv:
- return divTag.LocalName();
+ return kDivTag.LocalName();
case EditorParagraphSeparator::kIsP:
- return pTag.LocalName();
+ return kPTag.LocalName();
}
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.cc
index 1e7a98ff4ab..603737507bc 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.cc
@@ -40,7 +40,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static Node* EnclosingBlockToSplitTreeTo(Node* start_node);
static bool IsElementForFormatBlock(const QualifiedName& tag_name);
@@ -141,10 +141,11 @@ void FormatBlockCommand::FormatRange(const Position& start,
// Copy the inline style of the original block element to the newly created
// block-style element.
if (outer_block != node_after_insertion_position &&
- ToHTMLElement(node_after_insertion_position)->hasAttribute(styleAttr))
+ ToHTMLElement(node_after_insertion_position)->hasAttribute(kStyleAttr)) {
block_element->setAttribute(
- styleAttr,
- ToHTMLElement(node_after_insertion_position)->getAttribute(styleAttr));
+ kStyleAttr,
+ ToHTMLElement(node_after_insertion_position)->getAttribute(kStyleAttr));
+ }
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
@@ -176,10 +177,11 @@ bool IsElementForFormatBlock(const QualifiedName& tag_name) {
DEFINE_STATIC_LOCAL(
HashSet<QualifiedName>, block_tags,
({
- addressTag, articleTag, asideTag, blockquoteTag, ddTag, divTag,
- dlTag, dtTag, footerTag, h1Tag, h2Tag, h3Tag,
- h4Tag, h5Tag, h6Tag, headerTag, hgroupTag, mainTag,
- navTag, pTag, preTag, sectionTag,
+ kAddressTag, kArticleTag, kAsideTag, kBlockquoteTag, kDdTag,
+ kDivTag, kDlTag, kDtTag, kFooterTag, kH1Tag,
+ kH2Tag, kH3Tag, kH4Tag, kH5Tag, kH6Tag,
+ kHeaderTag, kHgroupTag, kMainTag, kNavTag, kPTag,
+ kPreTag, kSectionTag,
}));
return block_tags.Contains(tag_name);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.h b/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.h
index e4c50dc8016..63b54f24d7d 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/format_block_command.h
@@ -39,17 +39,17 @@ class CORE_EXPORT FormatBlockCommand final : public ApplyBlockElementCommand {
public:
static FormatBlockCommand* Create(Document& document,
const QualifiedName& tag_name) {
- return new FormatBlockCommand(document, tag_name);
+ return MakeGarbageCollected<FormatBlockCommand>(document, tag_name);
}
+ FormatBlockCommand(Document&, const QualifiedName& tag_name);
+
bool PreservesTypingStyle() const override { return true; }
static Element* ElementForFormatBlockCommand(const EphemeralRange&);
bool DidApply() const { return did_apply_; }
private:
- FormatBlockCommand(Document&, const QualifiedName& tag_name);
-
void FormatSelection(const VisiblePosition& start_of_selection,
const VisiblePosition& end_of_selection,
EditingState*) override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.cc
index 2f50ae0fe65..b464b652939 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.cc
@@ -41,7 +41,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// Returns true if |node| is UL, OL, or BLOCKQUOTE with "display:block".
// "Outdent" command considers <BLOCKQUOTE style="display:inline"> makes
@@ -55,14 +55,14 @@ static bool IsHTMLListOrBlockquoteElement(const Node* node) {
// TODO(yosin): We should check OL/UL element has "list-style-type" CSS
// property to make sure they layout contents as list.
return IsHTMLUListElement(element) || IsHTMLOListElement(element) ||
- element.HasTagName(blockquoteTag);
+ element.HasTagName(kBlockquoteTag);
}
IndentOutdentCommand::IndentOutdentCommand(Document& document,
EIndentType type_of_action)
: ApplyBlockElementCommand(
document,
- blockquoteTag,
+ kBlockquoteTag,
"margin: 0 0 0 40px; border: none; padding: 0px;"),
type_of_action_(type_of_action) {}
@@ -184,7 +184,7 @@ void IndentOutdentCommand::IndentIntoBlockquote(const Position& start,
if (outer_block == start.ComputeContainerNode()) {
// When we apply indent to an empty <blockquote>, we should call
// insertNodeAfter(). See http://crbug.com/625802 for more details.
- if (outer_block->HasTagName(blockquoteTag))
+ if (outer_block->HasTagName(kBlockquoteTag))
InsertNodeAfter(target_blockquote, outer_block, editing_state);
else
InsertNodeAt(target_blockquote, start, editing_state);
@@ -262,8 +262,8 @@ void IndentOutdentCommand::OutdentParagraph(EditingState* editing_state) {
if (split_point) {
if (Element* split_point_parent = split_point->parentElement()) {
// We can't outdent if there is no place to go!
- if (split_point_parent->HasTagName(blockquoteTag) &&
- !split_point->HasTagName(blockquoteTag) &&
+ if (split_point_parent->HasTagName(kBlockquoteTag) &&
+ !split_point->HasTagName(kBlockquoteTag) &&
HasEditableStyle(*split_point_parent->parentNode()))
SplitElement(split_point_parent, split_point);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.h b/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.h
index 302ea868a11..ebf84dbac38 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.h
@@ -34,14 +34,14 @@ class CORE_EXPORT IndentOutdentCommand final : public ApplyBlockElementCommand {
public:
enum EIndentType { kIndent, kOutdent };
static IndentOutdentCommand* Create(Document& document, EIndentType type) {
- return new IndentOutdentCommand(document, type);
+ return MakeGarbageCollected<IndentOutdentCommand>(document, type);
}
+ IndentOutdentCommand(Document&, EIndentType);
+
bool PreservesTypingStyle() const override { return true; }
private:
- IndentOutdentCommand(Document&, EIndentType);
-
InputEvent::InputType GetInputType() const override;
void OutdentRegion(const VisiblePosition&,
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.cc
index 887759002bb..9df720b50ed 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.cc
@@ -122,7 +122,8 @@ InsertIncrementalTextCommand* InsertIncrementalTextCommand::Create(
Document& document,
const String& text,
RebalanceType rebalance_type) {
- return new InsertIncrementalTextCommand(document, text, rebalance_type);
+ return MakeGarbageCollected<InsertIncrementalTextCommand>(document, text,
+ rebalance_type);
}
InsertIncrementalTextCommand::InsertIncrementalTextCommand(
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.h
index 7c0778c4ea6..165a04a8be1 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_incremental_text_command.h
@@ -17,10 +17,11 @@ class CORE_EXPORT InsertIncrementalTextCommand final
const String&,
RebalanceType = kRebalanceLeadingAndTrailingWhitespaces);
- private:
InsertIncrementalTextCommand(Document&,
const String& text,
RebalanceType);
+
+ private:
void DoApply(EditingState*) override;
};
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_into_text_node_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_into_text_node_command.h
index bd651d46ee0..94bae27d4a6 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_into_text_node_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_into_text_node_command.h
@@ -37,14 +37,14 @@ class InsertIntoTextNodeCommand final : public SimpleEditCommand {
static InsertIntoTextNodeCommand* Create(Text* node,
unsigned offset,
const String& text) {
- return new InsertIntoTextNodeCommand(node, offset, text);
+ return MakeGarbageCollected<InsertIntoTextNodeCommand>(node, offset, text);
}
+ InsertIntoTextNodeCommand(Text* node, unsigned offset, const String& text);
+
void Trace(blink::Visitor*) override;
private:
- InsertIntoTextNodeCommand(Text* node, unsigned offset, const String& text);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.cc
index c7d8e41ac04..e04983098ef 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.cc
@@ -45,8 +45,6 @@
namespace blink {
-using namespace HTMLNames;
-
InsertLineBreakCommand::InsertLineBreakCommand(Document& document)
: CompositeEditCommand(document) {}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.h
index bc8f1447906..793d2981dd2 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_line_break_command.h
@@ -33,12 +33,12 @@ namespace blink {
class InsertLineBreakCommand final : public CompositeEditCommand {
public:
static InsertLineBreakCommand* Create(Document& document) {
- return new InsertLineBreakCommand(document);
+ return MakeGarbageCollected<InsertLineBreakCommand>(document);
}
- private:
explicit InsertLineBreakCommand(Document&);
+ private:
void DoApply(EditingState*) override;
bool PreservesTypingStyle() const override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.cc
index 625716e5c03..bf649a92f24 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.cc
@@ -45,7 +45,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static Node* EnclosingListChild(Node* node, Node* list_node) {
Node* list_child = EnclosingListChild(node);
@@ -177,7 +177,7 @@ void InsertListCommand::DoApply(EditingState* editing_state) {
return;
}
- const HTMLQualifiedName& list_tag = (type_ == kOrderedList) ? olTag : ulTag;
+ const HTMLQualifiedName& list_tag = (type_ == kOrderedList) ? kOlTag : kUlTag;
if (EndingSelection().IsRange()) {
bool force_list_creation = false;
VisibleSelection selection =
@@ -378,11 +378,13 @@ bool InsertListCommand::DoApplyForSingleParagraph(
IsNodeVisiblyContainedWithin(*list_element,
EphemeralRange(&current_selection))) {
bool range_start_is_in_list =
- VisiblePositionBeforeNode(*list_element).DeepEquivalent() ==
+ CreateVisiblePosition(PositionBeforeNode(*list_element))
+ .DeepEquivalent() ==
CreateVisiblePosition(current_selection.StartPosition())
.DeepEquivalent();
bool range_end_is_in_list =
- VisiblePositionAfterNode(*list_element).DeepEquivalent() ==
+ CreateVisiblePosition(PositionAfterNode(*list_element))
+ .DeepEquivalent() ==
CreateVisiblePosition(current_selection.EndPosition())
.DeepEquivalent();
@@ -699,8 +701,35 @@ void InsertListCommand::MoveParagraphOverPositionIntoEmptyListItem(
const VisiblePosition& end =
EndOfParagraph(valid_pos, kCanSkipOverEditingBoundary);
ABORT_EDITING_COMMAND_IF(end.IsNull());
- MoveParagraph(start, end, VisiblePosition::BeforeNode(*placeholder),
- editing_state, kPreserveSelection);
+ Node* const outer_block = HighestEnclosingNodeOfType(
+ start.DeepEquivalent(), &IsInline, kCannotCrossEditingBoundary, nullptr);
+ MoveParagraphWithClones(
+ start, end, list_item_element,
+ outer_block ? outer_block : start.DeepEquivalent().AnchorNode(),
+ editing_state);
+ if (editing_state->IsAborted())
+ return;
+
+ RemoveNode(placeholder, editing_state);
+ if (editing_state->IsAborted())
+ return;
+
+ // Manually remove block_element because moveParagraphWithClones sometimes
+ // leaves it behind in the document. See the bug 33668 and
+ // editing/execCommand/insert-list-orphaned-item-with-nested-lists.html.
+ // FIXME: This might be a bug in moveParagraphWithClones or
+ // deleteSelection.
+ Node* const start_of_paragaph = start.DeepEquivalent().AnchorNode();
+ if (start_of_paragaph && start_of_paragaph->isConnected()) {
+ RemoveNode(start_of_paragaph, editing_state);
+ if (editing_state->IsAborted())
+ return;
+ }
+
+ SetEndingSelection(SelectionForUndoStep::From(
+ SelectionInDOMTree::Builder()
+ .Collapse(Position::FirstPositionInNode(*list_item_element))
+ .Build()));
}
void InsertListCommand::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.h
index aaadb8d20b5..8913ee9fd23 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.h
@@ -38,16 +38,16 @@ class CORE_EXPORT InsertListCommand final : public CompositeEditCommand {
enum Type { kOrderedList, kUnorderedList };
static InsertListCommand* Create(Document& document, Type list_type) {
- return new InsertListCommand(document, list_type);
+ return MakeGarbageCollected<InsertListCommand>(document, list_type);
}
+ InsertListCommand(Document&, Type);
+
bool PreservesTypingStyle() const override { return true; }
void Trace(blink::Visitor*) override;
private:
- InsertListCommand(Document&, Type);
-
void DoApply(EditingState*) override;
InputEvent::InputType GetInputType() const override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command_test.cc
index e7a61e4a5dd..021506ccbf8 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_list_command_test.cc
@@ -35,7 +35,7 @@ TEST_F(InsertListCommandTest, ShouldCleanlyRemoveSpuriousTextNode) {
Text* empty_text = GetDocument().createTextNode("");
GetDocument().body()->InsertBefore(empty_text,
GetDocument().body()->firstChild());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().GetFrame()->Selection().SetSelection(
SelectionInDOMTree::Builder()
.Collapse(Position(GetDocument().body(), 0))
@@ -48,7 +48,8 @@ TEST_F(InsertListCommandTest, ShouldCleanlyRemoveSpuriousTextNode) {
// This should not DCHECK.
EXPECT_TRUE(command->Apply())
<< "The insert ordered list command should have succeeded";
- EXPECT_EQ("<ol><li>d</li></ol>", GetDocument().body()->InnerHTMLAsString());
+ EXPECT_EQ("<ol><li>\nd\n</li></ol>",
+ GetDocument().body()->InnerHTMLAsString());
}
// Refer https://crbug.com/794356
@@ -80,19 +81,14 @@ TEST_F(InsertListCommandTest, CleanupNodeSameAsDestinationNode) {
Selection().SetSelection(SetSelectionTextToBody("^<table><col></table>"
"<button></button>|"),
SetSelectionOptions());
-
InsertListCommand* command = InsertListCommand::Create(
GetDocument(), InsertListCommand::kUnorderedList);
-
// Crash happens here.
- EXPECT_FALSE(command->Apply());
+ EXPECT_TRUE(command->Apply());
EXPECT_EQ(
- "<ul><li><br></li></ul>"
- "<br>"
- "<table>|<colgroup><col>"
- "<ul><li><br></li></ul>"
- "</col></colgroup></table>"
- "<button></button>",
+ "<ul><li><table><colgroup><col>"
+ "</colgroup></table></li>"
+ "<li><button>|</button></li></ul><br>",
GetSelectionTextFromBody());
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_node_before_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_node_before_command.h
index 15138b6ae79..8fafa29d52e 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_node_before_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_node_before_command.h
@@ -37,18 +37,18 @@ class InsertNodeBeforeCommand final : public SimpleEditCommand {
Node* child_to_insert_before,
ShouldAssumeContentIsAlwaysEditable
should_assume_content_is_always_editable) {
- return new InsertNodeBeforeCommand(
+ return MakeGarbageCollected<InsertNodeBeforeCommand>(
child_to_insert, child_to_insert_before,
should_assume_content_is_always_editable);
}
- void Trace(blink::Visitor*) override;
-
- private:
InsertNodeBeforeCommand(Node* child_to_insert,
Node* child_to_insert_before,
ShouldAssumeContentIsAlwaysEditable);
+ void Trace(blink::Visitor*) override;
+
+ private:
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.cc
index 7d36a48e51e..bfc599a35cc 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// When inserting a new line, we want to avoid nesting empty divs if we can.
// Otherwise, when pasting, it's easy to have each new line be a div deeper than
@@ -111,11 +111,11 @@ void InsertParagraphSeparatorCommand::ApplyStyleAfterInsertion(
EditingState* editing_state) {
// Not only do we break out of header tags, but we also do not preserve the
// typing style, in order to match other browsers.
- if (original_enclosing_block->HasTagName(h1Tag) ||
- original_enclosing_block->HasTagName(h2Tag) ||
- original_enclosing_block->HasTagName(h3Tag) ||
- original_enclosing_block->HasTagName(h4Tag) ||
- original_enclosing_block->HasTagName(h5Tag)) {
+ if (original_enclosing_block->HasTagName(kH1Tag) ||
+ original_enclosing_block->HasTagName(kH2Tag) ||
+ original_enclosing_block->HasTagName(kH3Tag) ||
+ original_enclosing_block->HasTagName(kH4Tag) ||
+ original_enclosing_block->HasTagName(kH5Tag)) {
return;
}
@@ -138,11 +138,11 @@ bool InsertParagraphSeparatorCommand::ShouldUseDefaultParagraphElement(
if (!IsEndOfBlock(EndingVisibleSelection().VisibleStart()))
return false;
- return enclosing_block->HasTagName(h1Tag) ||
- enclosing_block->HasTagName(h2Tag) ||
- enclosing_block->HasTagName(h3Tag) ||
- enclosing_block->HasTagName(h4Tag) ||
- enclosing_block->HasTagName(h5Tag);
+ return enclosing_block->HasTagName(kH1Tag) ||
+ enclosing_block->HasTagName(kH2Tag) ||
+ enclosing_block->HasTagName(kH3Tag) ||
+ enclosing_block->HasTagName(kH4Tag) ||
+ enclosing_block->HasTagName(kH5Tag);
}
void InsertParagraphSeparatorCommand::GetAncestorsInsideBlock(
@@ -170,7 +170,7 @@ Element* InsertParagraphSeparatorCommand::CloneHierarchyUnderNewBlock(
Element* child = ancestors[i - 1]->CloneWithoutChildren();
// It should always be okay to remove id from the cloned elements, since the
// originals are not deleted.
- child->removeAttribute(idAttr);
+ child->removeAttribute(kIdAttr);
AppendNode(child, parent, editing_state);
if (editing_state->IsAborted())
return nullptr;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h
index 0386f608ad2..761b40947d0 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h
@@ -39,18 +39,18 @@ class CORE_EXPORT InsertParagraphSeparatorCommand final
Document& document,
bool use_default_paragraph_element = false,
bool paste_blockquote_into_unquoted_area = false) {
- return new InsertParagraphSeparatorCommand(
+ return MakeGarbageCollected<InsertParagraphSeparatorCommand>(
document, use_default_paragraph_element,
paste_blockquote_into_unquoted_area);
}
- void Trace(blink::Visitor*) override;
-
- private:
InsertParagraphSeparatorCommand(Document&,
bool use_default_paragraph_element,
bool paste_blockquote_into_unquoted_area);
+ void Trace(blink::Visitor*) override;
+
+ private:
void DoApply(EditingState*) override;
void CalculateStyleBeforeInsertion(const Position&);
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.cc
index c843bc3b875..73d5250b7d3 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.cc
@@ -270,7 +270,7 @@ void InsertTextCommand::DoApply(EditingState* editing_state) {
RebalanceWhitespaceAt(end_position);
// Rebalancing on both sides isn't necessary if we've inserted only
// spaces.
- if (!text_.ContainsOnlyWhitespace())
+ if (!text_.ContainsOnlyWhitespaceOrEmpty())
RebalanceWhitespaceAt(start_position);
} else {
DCHECK_EQ(rebalance_type_, kRebalanceAllWhitespaces);
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.h
index c839cedd3b1..23505255cfd 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command.h
@@ -41,16 +41,17 @@ class CORE_EXPORT InsertTextCommand : public CompositeEditCommand {
Document& document,
const String& text,
RebalanceType rebalance_type = kRebalanceLeadingAndTrailingWhitespaces) {
- return new InsertTextCommand(document, text, rebalance_type);
+ return MakeGarbageCollected<InsertTextCommand>(document, text,
+ rebalance_type);
}
- String TextDataForInputEvent() const final;
-
- protected:
InsertTextCommand(Document&,
const String& text,
RebalanceType);
+ String TextDataForInputEvent() const final;
+
+ protected:
void DoApply(EditingState*) override;
Position PositionInsideTextNode(const Position&, EditingState*);
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command_test.cc
index abfe0844040..b4718d1df84 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_text_command_test.cc
@@ -278,8 +278,8 @@ TEST_F(InsertTextCommandTest, AnchorElementWithBlockCrash) {
// Since the HTML parser rejects it as there are nested <a> elements.
// We are contructing the remaining DOM manually.
Element* const anchor = GetDocument().QuerySelector("a");
- Element* nested_anchor = GetDocument().CreateRawElement(HTMLNames::aTag);
- Element* iElement = GetDocument().CreateRawElement(HTMLNames::iTag);
+ Element* nested_anchor = GetDocument().CreateRawElement(html_names::kATag);
+ Element* iElement = GetDocument().CreateRawElement(html_names::kITag);
nested_anchor->setAttribute("href", "www");
iElement->SetInnerHTMLFromString("home");
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/merge_identical_elements_command.h b/chromium/third_party/blink/renderer/core/editing/commands/merge_identical_elements_command.h
index 49c4eda113d..db230f412a3 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/merge_identical_elements_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/merge_identical_elements_command.h
@@ -34,14 +34,15 @@ class MergeIdenticalElementsCommand final : public SimpleEditCommand {
public:
static MergeIdenticalElementsCommand* Create(Element* element1,
Element* element2) {
- return new MergeIdenticalElementsCommand(element1, element2);
+ return MakeGarbageCollected<MergeIdenticalElementsCommand>(element1,
+ element2);
}
+ MergeIdenticalElementsCommand(Element*, Element*);
+
void Trace(blink::Visitor*) override;
private:
- MergeIdenticalElementsCommand(Element*, Element*);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/remove_css_property_command.h b/chromium/third_party/blink/renderer/core/editing/commands/remove_css_property_command.h
index c5402b87e33..056f77c947f 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/remove_css_property_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/remove_css_property_command.h
@@ -26,7 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_REMOVE_CSS_PROPERTY_COMMAND_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_REMOVE_CSS_PROPERTY_COMMAND_H_
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/editing/commands/edit_command.h"
namespace blink {
@@ -38,13 +38,15 @@ class RemoveCSSPropertyCommand final : public SimpleEditCommand {
static RemoveCSSPropertyCommand* Create(Document& document,
Element* element,
CSSPropertyID property) {
- return new RemoveCSSPropertyCommand(document, element, property);
+ return MakeGarbageCollected<RemoveCSSPropertyCommand>(document, element,
+ property);
}
+ RemoveCSSPropertyCommand(Document&, Element*, CSSPropertyID);
+
void Trace(blink::Visitor*) override;
private:
- RemoveCSSPropertyCommand(Document&, Element*, CSSPropertyID);
~RemoveCSSPropertyCommand() override;
void DoApply(EditingState*) override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.cc
index 115c8a9b37a..3e94ba14cc8 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.cc
@@ -39,7 +39,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
RemoveFormatCommand::RemoveFormatCommand(Document& document)
: CompositeEditCommand(document) {}
@@ -48,10 +48,10 @@ static bool IsElementForRemoveFormatCommand(const Element* element) {
DEFINE_STATIC_LOCAL(
HashSet<QualifiedName>, elements,
({
- acronymTag, bTag, bdoTag, bigTag, citeTag, codeTag,
- dfnTag, emTag, fontTag, iTag, insTag, kbdTag,
- nobrTag, qTag, sTag, sampTag, smallTag, strikeTag,
- strongTag, subTag, supTag, ttTag, uTag, varTag,
+ kAcronymTag, kBTag, kBdoTag, kBigTag, kCiteTag, kCodeTag,
+ kDfnTag, kEmTag, kFontTag, kITag, kInsTag, kKbdTag,
+ kNobrTag, kQTag, kSTag, kSampTag, kSmallTag, kStrikeTag,
+ kStrongTag, kSubTag, kSupTag, kTtTag, kUTag, kVarTag,
}));
return elements.Contains(element->TagQName());
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.h b/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.h
index 31a9e05f5d3..fcf1265603e 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/remove_format_command.h
@@ -33,12 +33,12 @@ namespace blink {
class RemoveFormatCommand final : public CompositeEditCommand {
public:
static RemoveFormatCommand* Create(Document& document) {
- return new RemoveFormatCommand(document);
+ return MakeGarbageCollected<RemoveFormatCommand>(document);
}
- private:
explicit RemoveFormatCommand(Document&);
+ private:
void DoApply(EditingState*) override;
InputEvent::InputType GetInputType() const override;
};
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/remove_node_command.h b/chromium/third_party/blink/renderer/core/editing/commands/remove_node_command.h
index 0cd1114695f..f4435cd636b 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/remove_node_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/remove_node_command.h
@@ -36,15 +36,15 @@ class RemoveNodeCommand final : public SimpleEditCommand {
Node* node,
ShouldAssumeContentIsAlwaysEditable
should_assume_content_is_always_editable) {
- return new RemoveNodeCommand(node,
- should_assume_content_is_always_editable);
+ return MakeGarbageCollected<RemoveNodeCommand>(
+ node, should_assume_content_is_always_editable);
}
+ explicit RemoveNodeCommand(Node*, ShouldAssumeContentIsAlwaysEditable);
+
void Trace(blink::Visitor*) override;
private:
- explicit RemoveNodeCommand(Node*, ShouldAssumeContentIsAlwaysEditable);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/remove_node_preserving_children_command.h b/chromium/third_party/blink/renderer/core/editing/commands/remove_node_preserving_children_command.h
index 99aaadc33f6..06fc18230b6 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/remove_node_preserving_children_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/remove_node_preserving_children_command.h
@@ -36,16 +36,16 @@ class RemoveNodePreservingChildrenCommand final : public CompositeEditCommand {
Node* node,
ShouldAssumeContentIsAlwaysEditable
should_assume_content_is_always_editable) {
- return new RemoveNodePreservingChildrenCommand(
+ return MakeGarbageCollected<RemoveNodePreservingChildrenCommand>(
node, should_assume_content_is_always_editable);
}
- void Trace(blink::Visitor*) override;
-
- private:
RemoveNodePreservingChildrenCommand(Node*,
ShouldAssumeContentIsAlwaysEditable);
+ void Trace(blink::Visitor*) override;
+
+ private:
void DoApply(EditingState*) override;
Member<Node> node_;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.cc
index 99b746df851..a464a4a5b39 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.cc
@@ -39,8 +39,6 @@
namespace blink {
-using namespace HTMLNames;
-
ReplaceNodeWithSpanCommand::ReplaceNodeWithSpanCommand(HTMLElement* element)
: SimpleEditCommand(element->GetDocument()), element_to_replace_(element) {
DCHECK(element_to_replace_);
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.h b/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.h
index 61168d6d47b..3a07c1748c4 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.h
@@ -43,16 +43,16 @@ class HTMLSpanElement;
class ReplaceNodeWithSpanCommand final : public SimpleEditCommand {
public:
static ReplaceNodeWithSpanCommand* Create(HTMLElement* element) {
- return new ReplaceNodeWithSpanCommand(element);
+ return MakeGarbageCollected<ReplaceNodeWithSpanCommand>(element);
}
+ explicit ReplaceNodeWithSpanCommand(HTMLElement*);
+
HTMLSpanElement* SpanElement() { return span_element_.Get(); }
void Trace(blink::Visitor*) override;
private:
- explicit ReplaceNodeWithSpanCommand(HTMLElement*);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc
index c4a86e3d4d6..8b9ecd3f836 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc
@@ -27,9 +27,9 @@
#include "third_party/blink/renderer/core/editing/commands/replace_selection_command.h"
#include "base/macros.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_style_declaration.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -71,7 +71,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
enum EFragmentType { kEmptyFragment, kSingleTextNodeFragment, kTreeFragment };
@@ -118,7 +118,7 @@ static bool IsInterchangeHTMLBRElement(const Node* node) {
DEFINE_STATIC_LOCAL(String, interchange_newline_class_string,
(AppleInterchangeNewline));
if (!IsHTMLBRElement(node) ||
- ToHTMLBRElement(node)->getAttribute(classAttr) !=
+ ToHTMLBRElement(node)->getAttribute(kClassAttr) !=
interchange_newline_class_string)
return false;
UseCounter::Count(node->GetDocument(),
@@ -184,7 +184,7 @@ ReplacementFragment::ReplacementFragment(Document* document,
shadow_ancestor_element = editable_root;
if (!editable_root->GetAttributeEventListener(
- EventTypeNames::webkitBeforeTextInserted)
+ event_type_names::kWebkitBeforeTextInserted)
// FIXME: Remove these checks once textareas and textfields actually
// register an event handler.
&&
@@ -508,9 +508,9 @@ static bool IsHTMLHeaderElement(const Node* a) {
return false;
const HTMLElement& element = ToHTMLElement(*a);
- return element.HasTagName(h1Tag) || element.HasTagName(h2Tag) ||
- element.HasTagName(h3Tag) || element.HasTagName(h4Tag) ||
- element.HasTagName(h5Tag) || element.HasTagName(h6Tag);
+ return element.HasTagName(kH1Tag) || element.HasTagName(kH2Tag) ||
+ element.HasTagName(kH3Tag) || element.HasTagName(kH4Tag) ||
+ element.HasTagName(kH5Tag) || element.HasTagName(kH6Tag);
}
static bool HaveSameTagName(Element* a, Element* b) {
@@ -527,7 +527,7 @@ bool ReplaceSelectionCommand::ShouldMerge(const VisiblePosition& source,
Element* source_block = EnclosingBlock(source_node);
Element* destination_block = EnclosingBlock(destination_node);
return source_block &&
- (!source_block->HasTagName(blockquoteTag) ||
+ (!source_block->HasTagName(kBlockquoteTag) ||
IsMailHTMLBlockquoteElement(source_block)) &&
EnclosingListChild(source_block) ==
EnclosingListChild(destination_node) &&
@@ -624,10 +624,10 @@ void ReplaceSelectionCommand::RemoveRedundantStylesAndKeepStyleSpanInline(
return;
continue;
}
- RemoveElementAttribute(element, styleAttr);
+ RemoveElementAttribute(element, kStyleAttr);
} else if (new_inline_style->Style()->PropertyCount() !=
inline_style->PropertyCount()) {
- SetNodeAttribute(element, styleAttr,
+ SetNodeAttribute(element, kStyleAttr,
AtomicString(new_inline_style->Style()->AsText()));
}
@@ -652,41 +652,42 @@ void ReplaceSelectionCommand::RemoveRedundantStylesAndKeepStyleSpanInline(
if (element->parentNode() &&
HasRichlyEditableStyle(*element->parentNode()) &&
HasRichlyEditableStyle(*element)) {
- RemoveElementAttribute(element, contenteditableAttr);
+ RemoveElementAttribute(element, kContenteditableAttr);
}
}
}
static bool IsProhibitedParagraphChild(const AtomicString& name) {
// https://dvcs.w3.org/hg/editing/raw-file/57abe6d3cb60/editing.html#prohibited-paragraph-child
- DEFINE_STATIC_LOCAL(HashSet<AtomicString>, elements,
- ({
- addressTag.LocalName(), articleTag.LocalName(),
- asideTag.LocalName(), blockquoteTag.LocalName(),
- captionTag.LocalName(), centerTag.LocalName(),
- colTag.LocalName(), colgroupTag.LocalName(),
- ddTag.LocalName(), detailsTag.LocalName(),
- dirTag.LocalName(), divTag.LocalName(),
- dlTag.LocalName(), dtTag.LocalName(),
- fieldsetTag.LocalName(), figcaptionTag.LocalName(),
- figureTag.LocalName(), footerTag.LocalName(),
- formTag.LocalName(), h1Tag.LocalName(),
- h2Tag.LocalName(), h3Tag.LocalName(),
- h4Tag.LocalName(), h5Tag.LocalName(),
- h6Tag.LocalName(), headerTag.LocalName(),
- hgroupTag.LocalName(), hrTag.LocalName(),
- liTag.LocalName(), listingTag.LocalName(),
- mainTag.LocalName(), // Missing in the specification.
- menuTag.LocalName(), navTag.LocalName(),
- olTag.LocalName(), pTag.LocalName(),
- plaintextTag.LocalName(), preTag.LocalName(),
- sectionTag.LocalName(), summaryTag.LocalName(),
- tableTag.LocalName(), tbodyTag.LocalName(),
- tdTag.LocalName(), tfootTag.LocalName(),
- thTag.LocalName(), theadTag.LocalName(),
- trTag.LocalName(), ulTag.LocalName(),
- xmpTag.LocalName(),
- }));
+ DEFINE_STATIC_LOCAL(
+ HashSet<AtomicString>, elements,
+ ({
+ kAddressTag.LocalName(), kArticleTag.LocalName(),
+ kAsideTag.LocalName(), kBlockquoteTag.LocalName(),
+ kCaptionTag.LocalName(), kCenterTag.LocalName(),
+ kColTag.LocalName(), kColgroupTag.LocalName(),
+ kDdTag.LocalName(), kDetailsTag.LocalName(),
+ kDirTag.LocalName(), kDivTag.LocalName(),
+ kDlTag.LocalName(), kDtTag.LocalName(),
+ kFieldsetTag.LocalName(), kFigcaptionTag.LocalName(),
+ kFigureTag.LocalName(), kFooterTag.LocalName(),
+ kFormTag.LocalName(), kH1Tag.LocalName(),
+ kH2Tag.LocalName(), kH3Tag.LocalName(),
+ kH4Tag.LocalName(), kH5Tag.LocalName(),
+ kH6Tag.LocalName(), kHeaderTag.LocalName(),
+ kHgroupTag.LocalName(), kHrTag.LocalName(),
+ kLiTag.LocalName(), kListingTag.LocalName(),
+ kMainTag.LocalName(), // Missing in the specification.
+ kMenuTag.LocalName(), kNavTag.LocalName(),
+ kOlTag.LocalName(), kPTag.LocalName(),
+ kPlaintextTag.LocalName(), kPreTag.LocalName(),
+ kSectionTag.LocalName(), kSummaryTag.LocalName(),
+ kTableTag.LocalName(), kTbodyTag.LocalName(),
+ kTdTag.LocalName(), kTfootTag.LocalName(),
+ kThTag.LocalName(), kTheadTag.LocalName(),
+ kTrTag.LocalName(), kUlTag.LocalName(),
+ kXmpTag.LocalName(),
+ }));
return elements.Contains(name);
}
@@ -711,7 +712,7 @@ void ReplaceSelectionCommand::
if (IsProhibitedParagraphChild(element.localName())) {
if (HTMLElement* paragraph_element =
ToHTMLElement(EnclosingElementWithTag(
- Position::InParentBeforeNode(element), pTag))) {
+ Position::InParentBeforeNode(element), kPTag))) {
MoveElementOutOfAncestor(&element, paragraph_element, editing_state);
if (editing_state->IsAborted())
return;
@@ -780,9 +781,9 @@ void ReplaceSelectionCommand::RemoveUnrenderedTextNodesAtEnds(
if (last_leaf_inserted && last_leaf_inserted->IsTextNode() &&
!NodeHasVisibleLayoutText(ToText(*last_leaf_inserted)) &&
!EnclosingElementWithTag(FirstPositionInOrBeforeNode(*last_leaf_inserted),
- selectTag) &&
+ kSelectTag) &&
!EnclosingElementWithTag(FirstPositionInOrBeforeNode(*last_leaf_inserted),
- scriptTag)) {
+ kScriptTag)) {
inserted_nodes.WillRemoveNode(*last_leaf_inserted);
// Removing a Text node won't dispatch synchronous events.
RemoveNode(last_leaf_inserted, ASSERT_NO_EDITING_ABORT);
@@ -808,7 +809,7 @@ VisiblePosition ReplaceSelectionCommand::PositionAtEndOfInsertedContent()
// element, since contents of SELECT elements, e.g. OPTION, OPTGROUP, are
// not editable, or SELECT element is an atomic on editing.
HTMLSelectElement* enclosing_select = ToHTMLSelectElement(
- EnclosingElementWithTag(end_of_inserted_content_, selectTag));
+ EnclosingElementWithTag(end_of_inserted_content_, kSelectTag));
if (enclosing_select) {
return CreateVisiblePosition(LastPositionInOrAfterNode(*enclosing_select));
}
@@ -844,10 +845,10 @@ static bool FollowBlockElementStyle(const Node* node) {
return false;
const HTMLElement& element = ToHTMLElement(*node);
- return IsListItem(node) || IsTableCell(node) || element.HasTagName(preTag) ||
- element.HasTagName(h1Tag) || element.HasTagName(h2Tag) ||
- element.HasTagName(h3Tag) || element.HasTagName(h4Tag) ||
- element.HasTagName(h5Tag) || element.HasTagName(h6Tag);
+ return IsListItem(node) || IsTableCell(node) || element.HasTagName(kPreTag) ||
+ element.HasTagName(kH1Tag) || element.HasTagName(kH2Tag) ||
+ element.HasTagName(kH3Tag) || element.HasTagName(kH4Tag) ||
+ element.HasTagName(kH5Tag) || element.HasTagName(kH6Tag);
}
// Remove style spans before insertion if they are unnecessary. It's faster
@@ -891,7 +892,7 @@ static void HandleStyleSpansBeforeInsertion(ReplacementFragment& fragment,
// FIXME: This string comparison is a naive way of comparing two styles.
// We should be taking the diff and check that the diff is empty.
- if (style_text != wrapping_style_span->getAttribute(styleAttr))
+ if (style_text != wrapping_style_span->getAttribute(kStyleAttr))
return;
fragment.RemoveNodePreservingChildren(wrapping_style_span);
@@ -1441,7 +1442,7 @@ void ReplaceSelectionCommand::DoApply(EditingState* editing_state) {
{
// TODO(dominicc): refNode may not be connected, for example in
- // LayoutTests/editing/inserting/insert-table-in-paragraph-crash.html .
+ // web_tests/editing/inserting/insert-table-in-paragraph-crash.html .
// Refactor this so there's a relationship between the conditions
// where refNode is dereferenced and refNode is connected.
bool ref_node_was_connected = inserted_nodes.RefNode()->isConnected();
@@ -1676,7 +1677,7 @@ bool ReplaceSelectionCommand::ShouldPerformSmartReplace() const {
TextControlElement* text_control =
EnclosingTextControl(PositionAtStartOfInsertedContent().DeepEquivalent());
if (IsHTMLInputElement(text_control) &&
- ToHTMLInputElement(text_control)->type() == InputTypeNames::password)
+ ToHTMLInputElement(text_control)->type() == input_type_names::kPassword)
return false; // Disable smart replace for password fields.
return true;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.h b/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.h
index f5b9a7ff6ac..b6f17899d72 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.h
@@ -53,19 +53,20 @@ class CORE_EXPORT ReplaceSelectionCommand final : public CompositeEditCommand {
DocumentFragment* fragment,
CommandOptions options,
InputEvent::InputType input_type = InputEvent::InputType::kNone) {
- return new ReplaceSelectionCommand(document, fragment, options, input_type);
+ return MakeGarbageCollected<ReplaceSelectionCommand>(document, fragment,
+ options, input_type);
}
- EphemeralRange InsertedRange() const;
-
- void Trace(blink::Visitor*) override;
-
- private:
ReplaceSelectionCommand(Document&,
DocumentFragment*,
CommandOptions,
InputEvent::InputType);
+ EphemeralRange InsertedRange() const;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
void DoApply(EditingState*) override;
InputEvent::InputType GetInputType() const override;
bool IsReplaceSelectionCommand() const override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command_test.cc
index 7a716b1ecd5..197eb35a2b9 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command_test.cc
@@ -40,7 +40,7 @@ TEST_F(ReplaceSelectionCommandTest, pastingEmptySpan) {
SetSelectionOptions());
DocumentFragment* fragment = GetDocument().createDocumentFragment();
- fragment->AppendChild(GetDocument().CreateRawElement(HTMLNames::spanTag));
+ fragment->AppendChild(GetDocument().CreateRawElement(html_names::kSpanTag));
// |options| are taken from |Editor::replaceSelectionWithFragment()| with
// |selectReplacement| and |smartReplace|.
@@ -86,7 +86,7 @@ TEST_F(ReplaceSelectionCommandTest, pasteSpanInText) {
// This is a regression test for https://crbug.com/121163
TEST_F(ReplaceSelectionCommandTest, styleTagsInPastedHeadIncludedInContent) {
GetDocument().setDesignMode("on");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDummyPageHolder().GetFrame().Selection().SetSelection(
SelectionInDOMTree::Builder()
.Collapse(Position(GetDocument().body(), 0))
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command.h b/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command.h
index d90f8bfa1b5..74346c5c43c 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command.h
@@ -15,17 +15,18 @@ class CORE_EXPORT SetCharacterDataCommand final : public SimpleEditCommand {
unsigned offset,
unsigned count,
const String& text) {
- return new SetCharacterDataCommand(node, offset, count, text);
+ return MakeGarbageCollected<SetCharacterDataCommand>(node, offset, count,
+ text);
}
- void Trace(blink::Visitor*) override;
-
- private:
SetCharacterDataCommand(Text* node,
unsigned offset,
unsigned count,
const String& text);
+ void Trace(blink::Visitor*) override;
+
+ private:
// EditCommand implementation
void DoApply(EditingState*) final;
void DoUnapply() final;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command_test.cc
index 24564ba0c11..147f70f7972 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/set_character_data_command_test.cc
@@ -125,7 +125,7 @@ TEST_F(SetCharacterDataCommandTest, CombinedText) {
Text* text_node = ToText(GetDocument().body()->firstChild()->appendChild(
GetDocument().CreateEditingTextNode("")));
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(text_node->GetLayoutObject());
ASSERT_TRUE(text_node->GetLayoutObject()->IsCombineText());
@@ -134,14 +134,14 @@ TEST_F(SetCharacterDataCommandTest, CombinedText) {
SimpleEditCommand* command =
SetCharacterDataCommand::Create(text_node, 0, 0, "text");
command->DoReapply();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(text_node->GetLayoutObject());
ASSERT_TRUE(text_node->GetLayoutObject()->IsCombineText());
EXPECT_TRUE(ToLayoutTextCombine(text_node->GetLayoutObject())->IsCombined());
command->DoUnapply();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(text_node->GetLayoutObject());
ASSERT_TRUE(text_node->GetLayoutObject()->IsCombineText());
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/set_node_attribute_command.h b/chromium/third_party/blink/renderer/core/editing/commands/set_node_attribute_command.h
index 3b08824dd33..3bebe7a8e1f 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/set_node_attribute_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/set_node_attribute_command.h
@@ -36,16 +36,17 @@ class SetNodeAttributeCommand final : public SimpleEditCommand {
static SetNodeAttributeCommand* Create(Element* element,
const QualifiedName& attribute,
const AtomicString& value) {
- return new SetNodeAttributeCommand(element, attribute, value);
+ return MakeGarbageCollected<SetNodeAttributeCommand>(element, attribute,
+ value);
}
- void Trace(blink::Visitor*) override;
-
- private:
SetNodeAttributeCommand(Element*,
const QualifiedName& attribute,
const AtomicString& value);
+ void Trace(blink::Visitor*) override;
+
+ private:
void DoApply(EditingState*) override;
void DoUnapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/simplify_markup_command.h b/chromium/third_party/blink/renderer/core/editing/commands/simplify_markup_command.h
index f767784584a..59b1f25ec3e 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/simplify_markup_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/simplify_markup_command.h
@@ -35,14 +35,15 @@ class SimplifyMarkupCommand final : public CompositeEditCommand {
static SimplifyMarkupCommand* Create(Document& document,
Node* first_node,
Node* node_after_last) {
- return new SimplifyMarkupCommand(document, first_node, node_after_last);
+ return MakeGarbageCollected<SimplifyMarkupCommand>(document, first_node,
+ node_after_last);
}
+ SimplifyMarkupCommand(Document&, Node* first_node, Node* node_after_last);
+
void Trace(blink::Visitor*) override;
private:
- SimplifyMarkupCommand(Document&, Node* first_node, Node* node_after_last);
-
void DoApply(EditingState*) override;
int PruneSubsequentAncestorsToRemove(
HeapVector<Member<ContainerNode>>& nodes_to_remove,
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.cc
index 4b239aa96b9..08ad760fa2a 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.cc
@@ -62,7 +62,7 @@ void SplitElementCommand::ExecuteApply() {
// Delete id attribute from the second element because the same id cannot be
// used for more than one element
- element2_->removeAttribute(HTMLNames::idAttr);
+ element2_->removeAttribute(html_names::kIdAttr);
for (const auto& child : children)
element1_->AppendChild(child, exception_state);
@@ -88,9 +88,9 @@ void SplitElementCommand::DoUnapply() {
element2_->InsertBefore(child, ref_child, IGNORE_EXCEPTION_FOR_TESTING);
// Recover the id attribute of the original element.
- const AtomicString& id = element1_->getAttribute(HTMLNames::idAttr);
+ const AtomicString& id = element1_->getAttribute(html_names::kIdAttr);
if (!id.IsNull())
- element2_->setAttribute(HTMLNames::idAttr, id);
+ element2_->setAttribute(html_names::kIdAttr, id);
element1_->remove(IGNORE_EXCEPTION_FOR_TESTING);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.h b/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.h
index b9bcd70b2ca..3c4fed054c1 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/split_element_command.h
@@ -34,14 +34,15 @@ class SplitElementCommand final : public SimpleEditCommand {
public:
static SplitElementCommand* Create(Element* element,
Node* split_point_child) {
- return new SplitElementCommand(element, split_point_child);
+ return MakeGarbageCollected<SplitElementCommand>(element,
+ split_point_child);
}
+ SplitElementCommand(Element*, Node* split_point_child);
+
void Trace(blink::Visitor*) override;
private:
- SplitElementCommand(Element*, Node* split_point_child);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
void DoReapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_command.h b/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_command.h
index ce2489a57e6..100cc8ab816 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_command.h
@@ -35,14 +35,14 @@ class Text;
class CORE_EXPORT SplitTextNodeCommand final : public SimpleEditCommand {
public:
static SplitTextNodeCommand* Create(Text* node, int offset) {
- return new SplitTextNodeCommand(node, offset);
+ return MakeGarbageCollected<SplitTextNodeCommand>(node, offset);
}
+ SplitTextNodeCommand(Text*, int offset);
+
void Trace(blink::Visitor*) override;
private:
- SplitTextNodeCommand(Text*, int offset);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
void DoReapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.h b/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.h
index 52315083120..78f5964ec65 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.h
@@ -34,14 +34,15 @@ class SplitTextNodeContainingElementCommand final
: public CompositeEditCommand {
public:
static SplitTextNodeContainingElementCommand* Create(Text* node, int offset) {
- return new SplitTextNodeContainingElementCommand(node, offset);
+ return MakeGarbageCollected<SplitTextNodeContainingElementCommand>(node,
+ offset);
}
+ SplitTextNodeContainingElementCommand(Text*, int offset);
+
void Trace(blink::Visitor*) override;
private:
- SplitTextNodeContainingElementCommand(Text*, int offset);
-
void DoApply(EditingState*) override;
Member<Text> text_;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/typing_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/typing_command.cc
index 10f999eaa27..63581c552dc 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/typing_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/typing_command.cc
@@ -162,8 +162,6 @@ bool CanAppendNewLineFeedToSelection(const VisibleSelection& selection,
} // anonymous namespace
-using namespace HTMLNames;
-
TypingCommand::TypingCommand(Document& document,
ETypingCommand command_type,
const String& text_to_insert,
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/typing_command.h b/chromium/third_party/blink/renderer/core/editing/commands/typing_command.h
index 6814dd0ea90..f5ac187fd74 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/typing_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/typing_command.h
@@ -89,6 +89,13 @@ class CORE_EXPORT TypingCommand final : public CompositeEditCommand {
static void UpdateSelectionIfDifferentFromCurrentSelection(TypingCommand*,
LocalFrame*);
+ TypingCommand(Document&,
+ ETypingCommand,
+ const String& text,
+ Options,
+ TextGranularity,
+ TextCompositionType);
+
void InsertTextRunWithoutNewlines(const String& text,
EditingState*);
void InsertLineBreak(EditingState*);
@@ -119,8 +126,8 @@ class CORE_EXPORT TypingCommand final : public CompositeEditCommand {
const String& text = "",
Options options = 0,
TextGranularity granularity = TextGranularity::kCharacter) {
- return new TypingCommand(document, command, text, options, granularity,
- kTextCompositionNone);
+ return MakeGarbageCollected<TypingCommand>(
+ document, command, text, options, granularity, kTextCompositionNone);
}
static TypingCommand* Create(Document& document,
@@ -128,17 +135,11 @@ class CORE_EXPORT TypingCommand final : public CompositeEditCommand {
const String& text,
Options options,
TextCompositionType composition_type) {
- return new TypingCommand(document, command, text, options,
- TextGranularity::kCharacter, composition_type);
+ return MakeGarbageCollected<TypingCommand>(document, command, text, options,
+ TextGranularity::kCharacter,
+ composition_type);
}
- TypingCommand(Document&,
- ETypingCommand,
- const String& text,
- Options,
- TextGranularity,
- TextCompositionType);
-
void SetSmartDelete(bool smart_delete) { smart_delete_ = smart_delete; }
bool IsOpenForMoreTyping() const { return open_for_more_typing_; }
void CloseTyping() { open_for_more_typing_ = false; }
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/typing_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/typing_command_test.cc
index a020f988eae..c3a6062cd4d 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/typing_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/typing_command_test.cc
@@ -27,14 +27,14 @@ TEST_F(TypingCommandTest, insertLineBreakWithIllFormedHTML) {
SetBodyContent("<div contenteditable></div>");
// <input><form></form></input>
- Element* input1 = GetDocument().CreateRawElement(HTMLNames::inputTag);
- Element* form = GetDocument().CreateRawElement(HTMLNames::formTag);
+ Element* input1 = GetDocument().CreateRawElement(html_names::kInputTag);
+ Element* form = GetDocument().CreateRawElement(html_names::kFormTag);
input1->AppendChild(form);
// <tr><input><header></header></input><rbc></rbc></tr>
- Element* tr = GetDocument().CreateRawElement(HTMLNames::trTag);
- Element* input2 = GetDocument().CreateRawElement(HTMLNames::inputTag);
- Element* header = GetDocument().CreateRawElement(HTMLNames::headerTag);
+ Element* tr = GetDocument().CreateRawElement(html_names::kTrTag);
+ Element* input2 = GetDocument().CreateRawElement(html_names::kInputTag);
+ Element* header = GetDocument().CreateRawElement(html_names::kHeaderTag);
Element* rbc = GetDocument().CreateElementForBinding("rbc");
input2->AppendChild(header);
tr->AppendChild(input2);
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.cc b/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.cc
index 55dafef39a0..f7828665b40 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.cc
@@ -41,7 +41,7 @@ static const size_t kMaximumUndoStackDepth = 1000;
UndoStack::UndoStack() : in_redo_(false) {}
UndoStack* UndoStack::Create() {
- return new UndoStack();
+ return MakeGarbageCollected<UndoStack>();
}
void UndoStack::RegisterUndoStep(UndoStep* step) {
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.h b/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.h
index 9adcb905bd7..49dcbc7319e 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/undo_stack.h
@@ -49,6 +49,8 @@ class UndoStack final : public GarbageCollected<UndoStack> {
public:
static UndoStack* Create();
+ UndoStack();
+
void RegisterUndoStep(UndoStep*);
void RegisterRedoStep(UndoStep*);
bool CanUndo() const;
@@ -76,8 +78,6 @@ class UndoStack final : public GarbageCollected<UndoStack> {
void Trace(blink::Visitor*);
private:
- UndoStack();
-
bool in_redo_;
UndoStepStack undo_stack_;
UndoStepStack redo_stack_;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/undo_step.cc b/chromium/third_party/blink/renderer/core/editing/commands/undo_step.cc
index f70d1d4083a..b75896345b6 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/undo_step.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/undo_step.cc
@@ -24,8 +24,8 @@ UndoStep* UndoStep::Create(Document* document,
const SelectionForUndoStep& starting_selection,
const SelectionForUndoStep& ending_selection,
InputEvent::InputType input_type) {
- return new UndoStep(document, starting_selection, ending_selection,
- input_type);
+ return MakeGarbageCollected<UndoStep>(document, starting_selection,
+ ending_selection, input_type);
}
UndoStep::UndoStep(Document* document,
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/undo_step.h b/chromium/third_party/blink/renderer/core/editing/commands/undo_step.h
index 9e0f27ed525..a754a2d16fd 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/undo_step.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/undo_step.h
@@ -46,6 +46,11 @@ class UndoStep : public GarbageCollectedFinalized<UndoStep> {
const SelectionForUndoStep&,
InputEvent::InputType);
+ UndoStep(Document*,
+ const SelectionForUndoStep& starting_selection,
+ const SelectionForUndoStep& ending_selection,
+ InputEvent::InputType);
+
void Unapply();
void Reapply();
InputEvent::InputType GetInputType() const;
@@ -76,11 +81,6 @@ class UndoStep : public GarbageCollectedFinalized<UndoStep> {
void Trace(blink::Visitor*);
private:
- UndoStep(Document*,
- const SelectionForUndoStep& starting_selection,
- const SelectionForUndoStep& ending_selection,
- InputEvent::InputType);
-
Member<Document> document_;
SelectionForUndoStep starting_selection_;
SelectionForUndoStep ending_selection_;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/unlink_command.h b/chromium/third_party/blink/renderer/core/editing/commands/unlink_command.h
index 67d2e1bb8a4..572565a021d 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/unlink_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/unlink_command.h
@@ -33,12 +33,12 @@ namespace blink {
class UnlinkCommand final : public CompositeEditCommand {
public:
static UnlinkCommand* Create(Document& document) {
- return new UnlinkCommand(document);
+ return MakeGarbageCollected<UnlinkCommand>(document);
}
- private:
explicit UnlinkCommand(Document&);
+ private:
void DoApply(EditingState*) override;
};
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/wrap_contents_in_dummy_span_command.h b/chromium/third_party/blink/renderer/core/editing/commands/wrap_contents_in_dummy_span_command.h
index 60079335b3b..e94e10d0321 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/wrap_contents_in_dummy_span_command.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/wrap_contents_in_dummy_span_command.h
@@ -35,14 +35,14 @@ class HTMLSpanElement;
class WrapContentsInDummySpanCommand final : public SimpleEditCommand {
public:
static WrapContentsInDummySpanCommand* Create(Element* element) {
- return new WrapContentsInDummySpanCommand(element);
+ return MakeGarbageCollected<WrapContentsInDummySpanCommand>(element);
}
+ explicit WrapContentsInDummySpanCommand(Element*);
+
void Trace(blink::Visitor*) override;
private:
- explicit WrapContentsInDummySpanCommand(Element*);
-
void DoApply(EditingState*) override;
void DoUnapply() override;
void DoReapply() override;
diff --git a/chromium/third_party/blink/renderer/core/editing/compute_layer_selection_test.cc b/chromium/third_party/blink/renderer/core/editing/compute_layer_selection_test.cc
index 59bc1a1fd51..f299a7e443d 100644
--- a/chromium/third_party/blink/renderer/core/editing/compute_layer_selection_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/compute_layer_selection_test.cc
@@ -22,6 +22,8 @@ class ComputeLayerSelectionTest : public EditingTestBase {
public:
void SetUp() override {
EditingTestBase::SetUp();
+ // This Page is not actually being shown by a compositor, but we act like it
+ // will in order to test behaviour.
GetPage().GetSettings().SetAcceleratedCompositingEnabled(true);
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
@@ -34,7 +36,7 @@ class ComputeLayerSelectionTest : public EditingTestBase {
Selection().SetSelection(
SelectionInDOMTree::Builder().SelectAllChildren(select).Build(),
SetSelectionOptions::Builder().SetShouldShowHandle(true).Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
void FocusAndSelectAll(TextControlElement* target) {
@@ -94,7 +96,7 @@ TEST_F(ComputeLayerSelectionTest, PositionInScrollableRoot) {
root_scroller->SetScrollOffset(ScrollOffset(800, 500), kProgrammaticScroll);
ASSERT_EQ(ScrollOffset(800, 500), root_scroller->GetScrollOffset());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const cc::LayerSelection& composited_selection =
ComputeLayerSelection(Selection());
@@ -157,7 +159,7 @@ TEST_F(ComputeLayerSelectionTest, PositionInScroller) {
scroller->SetScrollOffset(ScrollOffset(900, 800), kProgrammaticScroll);
ASSERT_EQ(ScrollOffset(900, 800), scroller->GetScrollOffset());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const cc::LayerSelection& composited_selection =
ComputeLayerSelection(Selection());
@@ -213,7 +215,7 @@ TEST_F(ComputeLayerSelectionTest, CaretBeforeSoftWrap) {
PositionWithAffinity({text_foo, 2}, TextAffinity::kUpstream))
.Build(),
SetSelectionOptions::Builder().SetShouldShowHandle(true).Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const cc::LayerSelection& composited_selection =
ComputeLayerSelection(Selection());
EXPECT_EQ(composited_selection.start.edge_top, gfx::Point(27, 8));
@@ -235,7 +237,7 @@ TEST_F(ComputeLayerSelectionTest, CaretAfterSoftWrap) {
PositionWithAffinity({text_foo, 2}, TextAffinity::kDownstream))
.Build(),
SetSelectionOptions::Builder().SetShouldShowHandle(true).Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const cc::LayerSelection& composited_selection =
ComputeLayerSelection(Selection());
EXPECT_EQ(composited_selection.start.edge_top, gfx::Point(8, 18));
@@ -254,7 +256,7 @@ TEST_F(ComputeLayerSelectionTest, RangeBeginAtBlockEnd) {
SetSelectionOptions::Builder().SetShouldShowHandle(true).Build());
Element* target = GetDocument().QuerySelector("div");
target->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const cc::LayerSelection& composited_selection =
ComputeLayerSelection(Selection());
EXPECT_EQ(composited_selection.start.edge_top, gfx::Point(38, 8));
@@ -339,4 +341,43 @@ TEST_F(ComputeLayerSelectionTest, SamplePointOnBoundary) {
EXPECT_FALSE(composited_selection.end.hidden);
}
+// https://crbug.com/892584.
+TEST_F(ComputeLayerSelectionTest, CrossingBlock1) {
+ // TODO(yoichio): To support this case with ComputeLayoutSelection,
+ // we may need to fix LocalCaretRectOfPosition(<after first br>).
+ Selection().SetSelection(
+ SetSelectionTextToBody("<div style='font: 10px/10px Ahem;'>"
+ "<div>^<br></div>"
+ "<div>|<br></div>"
+ "</div>"),
+ SetSelectionOptions::Builder().SetShouldShowHandle(true).Build());
+ Selection().CommitAppearanceIfNeeded();
+ const cc::LayerSelection& layer_selection =
+ ComputeLayerSelection(Selection());
+ EXPECT_EQ(layer_selection.start.edge_top, gfx::Point(8, 8));
+ EXPECT_EQ(layer_selection.start.edge_bottom, gfx::Point(8, 18));
+ EXPECT_EQ(layer_selection.end.edge_top, gfx::Point(8, 18));
+ EXPECT_EQ(layer_selection.end.edge_bottom, gfx::Point(8, 28));
+}
+
+// https://crbug.com/892584.
+TEST_F(ComputeLayerSelectionTest, CrossingBlock2) {
+ // TODO(yoichio): To support this case with ComputeLayoutSelection,
+ // we may need to fix LocalCaretRectOfPosition(<after first br>).
+ Selection().SetSelection(
+ SetSelectionTextToBody(
+ "<div contenteditable style='font: 10px/10px Ahem;'>"
+ "<div>^<br></div>"
+ "<div>|<br></div>"
+ "</div>"),
+ SetSelectionOptions::Builder().SetShouldShowHandle(true).Build());
+ Selection().CommitAppearanceIfNeeded();
+ const cc::LayerSelection& layer_selection =
+ ComputeLayerSelection(Selection());
+ EXPECT_EQ(layer_selection.start.edge_top, gfx::Point(8, 8));
+ EXPECT_EQ(layer_selection.start.edge_bottom, gfx::Point(8, 18));
+ EXPECT_EQ(layer_selection.end.edge_top, gfx::Point(8, 18));
+ EXPECT_EQ(layer_selection.end.edge_bottom, gfx::Point(8, 28));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/dom_selection.cc b/chromium/third_party/blink/renderer/core/editing/dom_selection.cc
index f79220c775f..c71b4bfa4aa 100644
--- a/chromium/third_party/blink/renderer/core/editing/dom_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/dom_selection.cc
@@ -624,7 +624,7 @@ void DOMSelection::addRange(Range* new_range) {
return;
if (!new_range->IsConnected()) {
- AddConsoleError("The given range isn't in document.");
+ AddConsoleWarning("addRange(): The given range isn't in document.");
return;
}
@@ -832,10 +832,11 @@ bool DOMSelection::IsValidForPosition(Node* node) const {
node->isConnected();
}
-void DOMSelection::AddConsoleError(const String& message) {
- if (tree_scope_)
- tree_scope_->GetDocument().AddConsoleMessage(
- ConsoleMessage::Create(kJSMessageSource, kErrorMessageLevel, message));
+void DOMSelection::AddConsoleWarning(const String& message) {
+ if (tree_scope_) {
+ tree_scope_->GetDocument().AddConsoleMessage(ConsoleMessage::Create(
+ kJSMessageSource, kWarningMessageLevel, message));
+ }
}
void DOMSelection::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/editing/dom_selection.h b/chromium/third_party/blink/renderer/core/editing/dom_selection.h
index 430adb05674..f056d2a6921 100644
--- a/chromium/third_party/blink/renderer/core/editing/dom_selection.h
+++ b/chromium/third_party/blink/renderer/core/editing/dom_selection.h
@@ -52,9 +52,11 @@ class CORE_EXPORT DOMSelection final : public ScriptWrappable,
public:
static DOMSelection* Create(const TreeScope* tree_scope) {
- return new DOMSelection(tree_scope);
+ return MakeGarbageCollected<DOMSelection>(tree_scope);
}
+ explicit DOMSelection(const TreeScope*);
+
void ClearTreeScope();
// Safari Selection Object API
@@ -105,8 +107,6 @@ class CORE_EXPORT DOMSelection final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
private:
- explicit DOMSelection(const TreeScope*);
-
bool IsAvailable() const;
void UpdateFrameSelection(const SelectionInDOMTree&,
@@ -122,7 +122,7 @@ class CORE_EXPORT DOMSelection final : public ScriptWrappable,
bool IsValidForPosition(Node*) const;
- void AddConsoleError(const String& message);
+ void AddConsoleWarning(const String& message);
Range* PrimaryRangeOrNull() const;
EphemeralRange CreateRangeFromSelectionEditor() const;
diff --git a/chromium/third_party/blink/renderer/core/editing/drag_caret.cc b/chromium/third_party/blink/renderer/core/editing/drag_caret.cc
index 7860c2ec1cb..135a4f75d52 100644
--- a/chromium/third_party/blink/renderer/core/editing/drag_caret.cc
+++ b/chromium/third_party/blink/renderer/core/editing/drag_caret.cc
@@ -39,7 +39,7 @@ DragCaret::DragCaret() : display_item_client_(new CaretDisplayItemClient()) {}
DragCaret::~DragCaret() = default;
DragCaret* DragCaret::Create() {
- return new DragCaret;
+ return MakeGarbageCollected<DragCaret>();
}
void DragCaret::ClearPreviousVisualRect(const LayoutBlock& block) {
@@ -66,7 +66,7 @@ bool DragCaret::IsContentRichlyEditable() const {
}
void DragCaret::SetCaretPosition(const PositionWithAffinity& position) {
- position_ = CreateVisiblePosition(position).ToPositionWithAffinity();
+ position_ = position;
Document* document = nullptr;
if (Node* node = position_.AnchorNode()) {
document = &node->GetDocument();
diff --git a/chromium/third_party/blink/renderer/core/editing/drag_caret.h b/chromium/third_party/blink/renderer/core/editing/drag_caret.h
index 74c57e546fc..734a6a5a99d 100644
--- a/chromium/third_party/blink/renderer/core/editing/drag_caret.h
+++ b/chromium/third_party/blink/renderer/core/editing/drag_caret.h
@@ -47,6 +47,7 @@ class DragCaret final : public GarbageCollectedFinalized<DragCaret>,
public:
static DragCaret* Create();
+ DragCaret();
virtual ~DragCaret();
// Paint invalidation methods delegating to CaretDisplayItemClient.
@@ -70,8 +71,6 @@ class DragCaret final : public GarbageCollectedFinalized<DragCaret>,
void Trace(blink::Visitor*) override;
private:
- DragCaret();
-
// Implementations of |SynchronousMutationObserver|
void NodeChildrenWillBeRemoved(ContainerNode&) final;
void NodeWillBeRemoved(Node&) final;
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_behavior.cc b/chromium/third_party/blink/renderer/core/editing/editing_behavior.cc
index dc9f9a15216..e47785874e6 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_behavior.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_behavior.cc
@@ -292,10 +292,10 @@ bool EditingBehavior::ShouldInsertCharacter(const KeyboardEvent& event) const {
return true;
}
-STATIC_ASSERT_ENUM(WebSettings::kEditingBehaviorMac, kEditingMacBehavior);
-STATIC_ASSERT_ENUM(WebSettings::kEditingBehaviorWin, kEditingWindowsBehavior);
-STATIC_ASSERT_ENUM(WebSettings::kEditingBehaviorUnix, kEditingUnixBehavior);
-STATIC_ASSERT_ENUM(WebSettings::kEditingBehaviorAndroid,
+STATIC_ASSERT_ENUM(WebSettings::EditingBehavior::kMac, kEditingMacBehavior);
+STATIC_ASSERT_ENUM(WebSettings::EditingBehavior::kWin, kEditingWindowsBehavior);
+STATIC_ASSERT_ENUM(WebSettings::EditingBehavior::kUnix, kEditingUnixBehavior);
+STATIC_ASSERT_ENUM(WebSettings::EditingBehavior::kAndroid,
kEditingAndroidBehavior);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_style.cc b/chromium/third_party/blink/renderer/core/editing/editing_style.cc
index 44dfbd75723..14f3e079cda 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style.cc
@@ -171,9 +171,16 @@ class HTMLElementEquivalent : public GarbageCollected<HTMLElementEquivalent> {
static HTMLElementEquivalent* Create(CSSPropertyID property_id,
CSSValueID primitive_value,
const HTMLQualifiedName& tag_name) {
- return new HTMLElementEquivalent(property_id, primitive_value, tag_name);
+ return MakeGarbageCollected<HTMLElementEquivalent>(
+ property_id, primitive_value, tag_name);
}
+ HTMLElementEquivalent(CSSPropertyID);
+ HTMLElementEquivalent(CSSPropertyID, const HTMLQualifiedName& tag_name);
+ HTMLElementEquivalent(CSSPropertyID,
+ CSSValueID primitive_value,
+ const HTMLQualifiedName& tag_name);
+
virtual bool Matches(const Element* element) const {
return !tag_name_ || element->HasTagName(*tag_name_);
}
@@ -189,11 +196,6 @@ class HTMLElementEquivalent : public GarbageCollected<HTMLElementEquivalent> {
}
protected:
- HTMLElementEquivalent(CSSPropertyID);
- HTMLElementEquivalent(CSSPropertyID, const HTMLQualifiedName& tag_name);
- HTMLElementEquivalent(CSSPropertyID,
- CSSValueID primitive_value,
- const HTMLQualifiedName& tag_name);
const CSSPropertyID property_id_;
const Member<CSSIdentifierValue> identifier_value_;
// We can store a pointer because HTML tag names are const global.
@@ -251,18 +253,19 @@ class HTMLTextDecorationEquivalent final : public HTMLElementEquivalent {
public:
static HTMLElementEquivalent* Create(CSSValueID primitive_value,
const HTMLQualifiedName& tag_name) {
- return new HTMLTextDecorationEquivalent(primitive_value, tag_name);
+ return MakeGarbageCollected<HTMLTextDecorationEquivalent>(primitive_value,
+ tag_name);
}
+
+ HTMLTextDecorationEquivalent(CSSValueID primitive_value,
+ const HTMLQualifiedName& tag_name);
+
bool PropertyExistsInStyle(const CSSPropertyValueSet*) const override;
bool ValueIsPresentInStyle(HTMLElement*, CSSPropertyValueSet*) const override;
void Trace(blink::Visitor* visitor) override {
HTMLElementEquivalent::Trace(visitor);
}
-
- private:
- HTMLTextDecorationEquivalent(CSSValueID primitive_value,
- const HTMLQualifiedName& tag_name);
};
HTMLTextDecorationEquivalent::HTMLTextDecorationEquivalent(
@@ -296,13 +299,20 @@ class HTMLAttributeEquivalent : public HTMLElementEquivalent {
static HTMLAttributeEquivalent* Create(CSSPropertyID property_id,
const HTMLQualifiedName& tag_name,
const QualifiedName& attr_name) {
- return new HTMLAttributeEquivalent(property_id, tag_name, attr_name);
+ return MakeGarbageCollected<HTMLAttributeEquivalent>(property_id, tag_name,
+ attr_name);
}
static HTMLAttributeEquivalent* Create(CSSPropertyID property_id,
const QualifiedName& attr_name) {
- return new HTMLAttributeEquivalent(property_id, attr_name);
+ return MakeGarbageCollected<HTMLAttributeEquivalent>(property_id,
+ attr_name);
}
+ HTMLAttributeEquivalent(CSSPropertyID,
+ const HTMLQualifiedName& tag_name,
+ const QualifiedName& attr_name);
+ HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& attr_name);
+
bool Matches(const Element* element) const override {
return HTMLElementEquivalent::Matches(element) &&
element->hasAttribute(attr_name_);
@@ -318,10 +328,6 @@ class HTMLAttributeEquivalent : public HTMLElementEquivalent {
}
protected:
- HTMLAttributeEquivalent(CSSPropertyID,
- const HTMLQualifiedName& tag_name,
- const QualifiedName& attr_name);
- HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& attr_name);
// We can store a reference because HTML attribute names are const global.
const QualifiedName& attr_name_;
};
@@ -370,22 +376,22 @@ const CSSValue* HTMLAttributeEquivalent::AttributeValueAsCSSValue(
class HTMLFontSizeEquivalent final : public HTMLAttributeEquivalent {
public:
static HTMLFontSizeEquivalent* Create() {
- return new HTMLFontSizeEquivalent();
+ return MakeGarbageCollected<HTMLFontSizeEquivalent>();
}
+
+ HTMLFontSizeEquivalent();
+
const CSSValue* AttributeValueAsCSSValue(Element*) const override;
void Trace(blink::Visitor* visitor) override {
HTMLAttributeEquivalent::Trace(visitor);
}
-
- private:
- HTMLFontSizeEquivalent();
};
HTMLFontSizeEquivalent::HTMLFontSizeEquivalent()
: HTMLAttributeEquivalent(CSSPropertyFontSize,
- HTMLNames::fontTag,
- HTMLNames::sizeAttr) {}
+ html_names::kFontTag,
+ html_names::kSizeAttr) {}
const CSSValue* HTMLFontSizeEquivalent::AttributeValueAsCSSValue(
Element* element) const {
@@ -970,29 +976,30 @@ bool EditingStyle::ConflictsWithInlineStyleOfElement(
static const HeapVector<Member<HTMLElementEquivalent>>&
HtmlElementEquivalents() {
- DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<HTMLElementEquivalent>>>,
- html_element_equivalents,
- (new HeapVector<Member<HTMLElementEquivalent>>));
+ DEFINE_STATIC_LOCAL(
+ Persistent<HeapVector<Member<HTMLElementEquivalent>>>,
+ html_element_equivalents,
+ (MakeGarbageCollected<HeapVector<Member<HTMLElementEquivalent>>>()));
if (!html_element_equivalents->size()) {
html_element_equivalents->push_back(HTMLElementEquivalent::Create(
- CSSPropertyFontWeight, CSSValueBold, HTMLNames::bTag));
+ CSSPropertyFontWeight, CSSValueBold, html_names::kBTag));
html_element_equivalents->push_back(HTMLElementEquivalent::Create(
- CSSPropertyFontWeight, CSSValueBold, HTMLNames::strongTag));
+ CSSPropertyFontWeight, CSSValueBold, html_names::kStrongTag));
html_element_equivalents->push_back(HTMLElementEquivalent::Create(
- CSSPropertyVerticalAlign, CSSValueSub, HTMLNames::subTag));
+ CSSPropertyVerticalAlign, CSSValueSub, html_names::kSubTag));
html_element_equivalents->push_back(HTMLElementEquivalent::Create(
- CSSPropertyVerticalAlign, CSSValueSuper, HTMLNames::supTag));
+ CSSPropertyVerticalAlign, CSSValueSuper, html_names::kSupTag));
html_element_equivalents->push_back(HTMLElementEquivalent::Create(
- CSSPropertyFontStyle, CSSValueItalic, HTMLNames::iTag));
+ CSSPropertyFontStyle, CSSValueItalic, html_names::kITag));
html_element_equivalents->push_back(HTMLElementEquivalent::Create(
- CSSPropertyFontStyle, CSSValueItalic, HTMLNames::emTag));
+ CSSPropertyFontStyle, CSSValueItalic, html_names::kEmTag));
html_element_equivalents->push_back(HTMLTextDecorationEquivalent::Create(
- CSSValueUnderline, HTMLNames::uTag));
+ CSSValueUnderline, html_names::kUTag));
html_element_equivalents->push_back(HTMLTextDecorationEquivalent::Create(
- CSSValueLineThrough, HTMLNames::sTag));
+ CSSValueLineThrough, html_names::kSTag));
html_element_equivalents->push_back(HTMLTextDecorationEquivalent::Create(
- CSSValueLineThrough, HTMLNames::strikeTag));
+ CSSValueLineThrough, html_names::kStrikeTag));
}
return *html_element_equivalents;
@@ -1023,23 +1030,24 @@ bool EditingStyle::ConflictsWithImplicitStyleOfElement(
static const HeapVector<Member<HTMLAttributeEquivalent>>&
HtmlAttributeEquivalents() {
- DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<HTMLAttributeEquivalent>>>,
- html_attribute_equivalents,
- (new HeapVector<Member<HTMLAttributeEquivalent>>));
+ DEFINE_STATIC_LOCAL(
+ Persistent<HeapVector<Member<HTMLAttributeEquivalent>>>,
+ html_attribute_equivalents,
+ (MakeGarbageCollected<HeapVector<Member<HTMLAttributeEquivalent>>>()));
if (!html_attribute_equivalents->size()) {
// elementIsStyledSpanOrHTMLEquivalent depends on the fact each
// HTMLAttriuteEquivalent matches exactly one attribute of exactly one
// element except dirAttr.
html_attribute_equivalents->push_back(HTMLAttributeEquivalent::Create(
- CSSPropertyColor, HTMLNames::fontTag, HTMLNames::colorAttr));
+ CSSPropertyColor, html_names::kFontTag, html_names::kColorAttr));
html_attribute_equivalents->push_back(HTMLAttributeEquivalent::Create(
- CSSPropertyFontFamily, HTMLNames::fontTag, HTMLNames::faceAttr));
+ CSSPropertyFontFamily, html_names::kFontTag, html_names::kFaceAttr));
html_attribute_equivalents->push_back(HTMLFontSizeEquivalent::Create());
html_attribute_equivalents->push_back(HTMLAttributeEquivalent::Create(
- CSSPropertyDirection, HTMLNames::dirAttr));
+ CSSPropertyDirection, html_names::kDirAttr));
html_attribute_equivalents->push_back(HTMLAttributeEquivalent::Create(
- CSSPropertyUnicodeBidi, HTMLNames::dirAttr));
+ CSSPropertyUnicodeBidi, html_names::kDirAttr));
}
return *html_attribute_equivalents;
@@ -1086,7 +1094,7 @@ bool EditingStyle::ExtractConflictingImplicitStyleOfAttributes(
// unicode-bidi and direction are pushed down separately so don't push down
// with other styles.
if (should_preserve_writing_direction == kPreserveWritingDirection &&
- equivalent->AttributeName() == HTMLNames::dirAttr)
+ equivalent->AttributeName() == html_names::kDirAttr)
continue;
if (!equivalent->Matches(element) ||
@@ -1141,7 +1149,7 @@ bool EditingStyle::ElementIsStyledSpanOrHTMLEquivalent(
html_attribute_equivalents = HtmlAttributeEquivalents();
for (const auto& equivalent : html_attribute_equivalents) {
if (equivalent->Matches(element) &&
- equivalent->AttributeName() != HTMLNames::dirAttr)
+ equivalent->AttributeName() != html_names::kDirAttr)
matched_attributes++;
}
@@ -1150,7 +1158,7 @@ bool EditingStyle::ElementIsStyledSpanOrHTMLEquivalent(
return false;
}
- if (element->hasAttribute(HTMLNames::styleAttr)) {
+ if (element->hasAttribute(html_names::kStyleAttr)) {
if (const CSSPropertyValueSet* style = element->InlineStyle()) {
unsigned property_count = style->PropertyCount();
for (unsigned i = 0; i < property_count; ++i) {
@@ -1306,7 +1314,7 @@ void EditingStyle::MergeInlineAndImplicitStyleOfElement(
const HeapVector<Member<HTMLAttributeEquivalent>>& attribute_equivalents =
HtmlAttributeEquivalents();
for (const auto& attribute : attribute_equivalents) {
- if (attribute->AttributeName() == HTMLNames::dirAttr)
+ if (attribute->AttributeName() == html_names::kDirAttr)
continue; // We don't want to include directionality
if (ElementMatchesAndPropertyIsNotInInlineStyleDecl(
attribute.Get(), element, mode, mutable_style_.Get()))
@@ -1540,7 +1548,7 @@ static void ReconcileTextDecorationProperties(
style->GetPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
const CSSValue* text_decoration =
style->GetPropertyCSSValue(CSSPropertyTextDecorationLine);
- // "LayoutTests/editing/execCommand/insert-list-and-strikethrough.html" makes
+ // "web_tests/editing/execCommand/insert-list-and-strikethrough.html" makes
// both |textDecorationsInEffect| and |textDecoration| non-null.
if (text_decorations_in_effect) {
style->SetProperty(CSSPropertyTextDecorationLine,
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_style.h b/chromium/third_party/blink/renderer/core/editing/editing_style.h
index f777be5b3a6..627b5b6c47e 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style.h
@@ -33,7 +33,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_EDITING_STYLE_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -76,30 +76,37 @@ class CORE_EXPORT EditingStyle final : public GarbageCollected<EditingStyle> {
};
static float no_font_delta_;
- static EditingStyle* Create() { return new EditingStyle(); }
+ static EditingStyle* Create() { return MakeGarbageCollected<EditingStyle>(); }
static EditingStyle* Create(ContainerNode* node,
PropertiesToInclude properties_to_include =
kOnlyEditingInheritableProperties) {
- return new EditingStyle(node, properties_to_include);
+ return MakeGarbageCollected<EditingStyle>(node, properties_to_include);
}
static EditingStyle* Create(const Position& position,
PropertiesToInclude properties_to_include =
kOnlyEditingInheritableProperties) {
- return new EditingStyle(position, properties_to_include);
+ return MakeGarbageCollected<EditingStyle>(position, properties_to_include);
}
static EditingStyle* Create(const CSSPropertyValueSet* style) {
- return new EditingStyle(style);
+ return MakeGarbageCollected<EditingStyle>(style);
}
static EditingStyle* Create(CSSPropertyID property_id,
const String& value,
SecureContextMode secure_context_mode) {
- return new EditingStyle(property_id, value, secure_context_mode);
+ return MakeGarbageCollected<EditingStyle>(property_id, value,
+ secure_context_mode);
}
+ EditingStyle() = default;
+ EditingStyle(ContainerNode*, PropertiesToInclude);
+ EditingStyle(const Position&, PropertiesToInclude);
+ explicit EditingStyle(const CSSPropertyValueSet*);
+ EditingStyle(CSSPropertyID, const String& value, SecureContextMode);
+
MutableCSSPropertyValueSet* Style() { return mutable_style_.Get(); }
bool GetTextDirection(WritingDirection&) const;
bool IsEmpty() const;
@@ -176,11 +183,6 @@ class CORE_EXPORT EditingStyle final : public GarbageCollected<EditingStyle> {
const String& value);
private:
- EditingStyle() = default;
- EditingStyle(ContainerNode*, PropertiesToInclude);
- EditingStyle(const Position&, PropertiesToInclude);
- explicit EditingStyle(const CSSPropertyValueSet*);
- EditingStyle(CSSPropertyID, const String& value, SecureContextMode);
void Init(Node*, PropertiesToInclude);
void RemoveInheritedColorsIfNeeded(const ComputedStyle*);
void ReplaceFontSizeByKeywordIfPossible(const ComputedStyle*,
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_style_test.cc b/chromium/third_party/blink/renderer/core/editing/editing_style_test.cc
index ad191d2f546..432db0f6078 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style_test.cc
@@ -20,7 +20,7 @@ TEST_F(EditingStyleTest, mergeInlineStyleOfElement) {
SetBodyContent(
"<span id=s1 style='--A:var(---B)'>1</span>"
"<span id=s2 style='float:var(--C)'>2</span>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EditingStyle* editing_style =
EditingStyle::Create(ToHTMLElement(GetDocument().getElementById("s2")));
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.cc b/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.cc
index 14692dc4624..84676040708 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.cc
@@ -29,9 +29,9 @@
#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/editing/editing_style.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_utilities.cc b/chromium/third_party/blink/renderer/core/editing/editing_utilities.cc
index 2e9b384b6d9..312d2bb7448 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_utilities.cc
@@ -80,7 +80,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -637,22 +637,6 @@ PositionInFlatTree PreviousVisuallyDistinctCandidate(
position);
}
-VisiblePosition FirstEditableVisiblePositionAfterPositionInRoot(
- const Position& position,
- ContainerNode& highest_root) {
- DCHECK(!NeedsLayoutTreeUpdate(position));
- return CreateVisiblePosition(
- FirstEditablePositionAfterPositionInRoot(position, highest_root));
-}
-
-VisiblePositionInFlatTree FirstEditableVisiblePositionAfterPositionInRoot(
- const PositionInFlatTree& position,
- ContainerNode& highest_root) {
- DCHECK(!NeedsLayoutTreeUpdate(position));
- return CreateVisiblePosition(
- FirstEditablePositionAfterPositionInRoot(position, highest_root));
-}
-
template <typename Strategy>
PositionTemplate<Strategy> FirstEditablePositionAfterPositionInRootAlgorithm(
const PositionTemplate<Strategy>& position,
@@ -714,22 +698,6 @@ PositionInFlatTree FirstEditablePositionAfterPositionInRoot(
EditingInFlatTreeStrategy>(position, highest_root);
}
-VisiblePosition LastEditableVisiblePositionBeforePositionInRoot(
- const Position& position,
- ContainerNode& highest_root) {
- DCHECK(!NeedsLayoutTreeUpdate(position));
- return CreateVisiblePosition(
- LastEditablePositionBeforePositionInRoot(position, highest_root));
-}
-
-VisiblePositionInFlatTree LastEditableVisiblePositionBeforePositionInRoot(
- const PositionInFlatTree& position,
- ContainerNode& highest_root) {
- DCHECK(!NeedsLayoutTreeUpdate(position));
- return CreateVisiblePosition(
- LastEditablePositionBeforePositionInRoot(position, highest_root));
-}
-
template <typename Strategy>
PositionTemplate<Strategy> LastEditablePositionBeforePositionInRootAlgorithm(
const PositionTemplate<Strategy>& position,
@@ -1118,24 +1086,24 @@ Element* TableElementJustAfter(const VisiblePosition& visible_position) {
return nullptr;
}
-// Returns the visible position at the beginning of a node
-VisiblePosition VisiblePositionBeforeNode(const Node& node) {
+// Returns the position at the beginning of a node
+Position PositionBeforeNode(const Node& node) {
DCHECK(!NeedsLayoutTreeUpdate(node));
if (node.hasChildren())
- return CreateVisiblePosition(FirstPositionInOrBeforeNode(node));
+ return FirstPositionInOrBeforeNode(node);
DCHECK(node.parentNode()) << node;
DCHECK(!node.parentNode()->IsShadowRoot()) << node.parentNode();
- return VisiblePosition::InParentBeforeNode(node);
+ return Position::InParentBeforeNode(node);
}
-// Returns the visible position at the ending of a node
-VisiblePosition VisiblePositionAfterNode(const Node& node) {
+// Returns the position at the ending of a node
+Position PositionAfterNode(const Node& node) {
DCHECK(!NeedsLayoutTreeUpdate(node));
if (node.hasChildren())
- return CreateVisiblePosition(LastPositionInOrAfterNode(node));
+ return LastPositionInOrAfterNode(node);
DCHECK(node.parentNode()) << node.parentNode();
DCHECK(!node.parentNode()->IsShadowRoot()) << node.parentNode();
- return VisiblePosition::InParentAfterNode(node);
+ return Position::InParentAfterNode(node);
}
bool IsHTMLListElement(const Node* n) {
@@ -1152,10 +1120,10 @@ bool IsPresentationalHTMLElement(const Node* node) {
return false;
const HTMLElement& element = ToHTMLElement(*node);
- return element.HasTagName(uTag) || element.HasTagName(sTag) ||
- element.HasTagName(strikeTag) || element.HasTagName(iTag) ||
- element.HasTagName(emTag) || element.HasTagName(bTag) ||
- element.HasTagName(strongTag);
+ return element.HasTagName(kUTag) || element.HasTagName(kSTag) ||
+ element.HasTagName(kStrikeTag) || element.HasTagName(kITag) ||
+ element.HasTagName(kEmTag) || element.HasTagName(kBTag) ||
+ element.HasTagName(kStrongTag);
}
Element* AssociatedElementOf(const Position& position) {
@@ -1314,7 +1282,7 @@ static HTMLSpanElement* CreateTabSpanElement(Document& document,
Text* tab_text_node) {
// Make the span to hold the tab.
HTMLSpanElement* span_element = HTMLSpanElement::Create(document);
- span_element->setAttribute(styleAttr, "white-space:pre");
+ span_element->setAttribute(kStyleAttr, "white-space:pre");
// Add tab text to that span.
if (!tab_text_node)
@@ -1405,7 +1373,7 @@ bool IsMailHTMLBlockquoteElement(const Node* node) {
return false;
const HTMLElement& element = ToHTMLElement(*node);
- return element.HasTagName(blockquoteTag) &&
+ return element.HasTagName(kBlockquoteTag) &&
element.getAttribute("type") == "cite";
}
@@ -1529,12 +1497,12 @@ bool IsNonTableCellHTMLBlockElement(const Node* node) {
return false;
const HTMLElement& element = ToHTMLElement(*node);
- return element.HasTagName(listingTag) || element.HasTagName(olTag) ||
- element.HasTagName(preTag) || element.HasTagName(tableTag) ||
- element.HasTagName(ulTag) || element.HasTagName(xmpTag) ||
- element.HasTagName(h1Tag) || element.HasTagName(h2Tag) ||
- element.HasTagName(h3Tag) || element.HasTagName(h4Tag) ||
- element.HasTagName(h5Tag);
+ return element.HasTagName(kListingTag) || element.HasTagName(kOlTag) ||
+ element.HasTagName(kPreTag) || element.HasTagName(kTableTag) ||
+ element.HasTagName(kUlTag) || element.HasTagName(kXmpTag) ||
+ element.HasTagName(kH1Tag) || element.HasTagName(kH2Tag) ||
+ element.HasTagName(kH3Tag) || element.HasTagName(kH4Tag) ||
+ element.HasTagName(kH5Tag);
}
bool IsBlockFlowElement(const Node& node) {
@@ -1546,7 +1514,8 @@ bool IsBlockFlowElement(const Node& node) {
bool IsInPasswordField(const Position& position) {
TextControlElement* text_control = EnclosingTextControl(position);
return IsHTMLInputElement(text_control) &&
- ToHTMLInputElement(text_control)->type() == InputTypeNames::password;
+ ToHTMLInputElement(text_control)->type() ==
+ input_type_names::kPassword;
}
// If current position is at grapheme boundary, return 0; otherwise, return the
@@ -1595,7 +1564,7 @@ const StaticRangeVector* TargetRangesForInputEvent(const Node& node) {
.ComputeVisibleSelectionInDOMTree());
if (range.IsNull())
return nullptr;
- return new StaticRangeVector(1, StaticRange::Create(range));
+ return MakeGarbageCollected<StaticRangeVector>(1, StaticRange::Create(range));
}
DispatchEventResult DispatchBeforeInputInsertText(
@@ -1721,7 +1690,7 @@ AtomicString GetUrlStringFromNode(const Node& node) {
// TODO(editing-dev): This should probably be reconciled with
// HitTestResult::absoluteImageURL.
if (IsHTMLImageElement(node) || IsHTMLInputElement(node))
- return ToHTMLElement(node).getAttribute(srcAttr);
+ return ToHTMLElement(node).getAttribute(kSrcAttr);
if (IsSVGImageElement(node))
return ToSVGElement(node).ImageSourceURL();
if (IsHTMLEmbedElement(node) || IsHTMLObjectElement(node) ||
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_utilities.h b/chromium/third_party/blink/renderer/core/editing/editing_utilities.h
index f4fea2acf77..1095e4a04ff 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_utilities.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_utilities.h
@@ -260,35 +260,14 @@ PositionWithAffinity PositionRespectingEditingBoundary(
Node* target_node);
Position ComputePositionForNodeRemoval(const Position&, const Node&);
+// TODO(editing-dev): These two functions should be eliminated.
+CORE_EXPORT Position PositionBeforeNode(const Node&);
+Position PositionAfterNode(const Node&);
+
// -------------------------------------------------------------------------
// VisiblePosition
// -------------------------------------------------------------------------
-// Functions returning VisiblePosition
-
-// TODO(yosin) We should rename
-// |firstEditableVisiblePositionAfterPositionInRoot()| to a better name which
-// describes what this function returns, since it returns a position before
-// specified position due by canonicalization.
-CORE_EXPORT VisiblePosition
-FirstEditableVisiblePositionAfterPositionInRoot(const Position&,
- ContainerNode&);
-CORE_EXPORT VisiblePositionInFlatTree
-FirstEditableVisiblePositionAfterPositionInRoot(const PositionInFlatTree&,
- ContainerNode&);
-// TODO(yosin) We should rename
-// |lastEditableVisiblePositionBeforePositionInRoot()| to a better name which
-// describes what this function returns, since it returns a position after
-// specified position due by canonicalization.
-CORE_EXPORT VisiblePosition
-LastEditableVisiblePositionBeforePositionInRoot(const Position&,
- ContainerNode&);
-CORE_EXPORT VisiblePositionInFlatTree
-LastEditableVisiblePositionBeforePositionInRoot(const PositionInFlatTree&,
- ContainerNode&);
-CORE_EXPORT VisiblePosition VisiblePositionBeforeNode(const Node&);
-VisiblePosition VisiblePositionAfterNode(const Node&);
-
int ComparePositions(const VisiblePosition&, const VisiblePosition&);
CORE_EXPORT int IndexForVisiblePosition(const VisiblePosition&,
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_utilities_test.cc b/chromium/third_party/blink/renderer/core/editing/editing_utilities_test.cc
index 6e7fc9e8b16..de55c5bf706 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_utilities_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_utilities_test.cc
@@ -42,32 +42,32 @@ TEST_F(EditingUtilitiesTest, firstEditablePositionAfterPositionInRoot) {
EXPECT_EQ(Position(one, 0),
FirstEditablePositionAfterPositionInRoot(Position(one, 0), *host));
- EXPECT_EQ(
- Position(one->firstChild(), 0),
- FirstEditableVisiblePositionAfterPositionInRoot(Position(one, 0), *host)
- .DeepEquivalent());
+ EXPECT_EQ(Position(one->firstChild(), 0),
+ CreateVisiblePosition(FirstEditablePositionAfterPositionInRoot(
+ Position(one, 0), *host))
+ .DeepEquivalent());
EXPECT_EQ(PositionInFlatTree(one, 0),
FirstEditablePositionAfterPositionInRoot(PositionInFlatTree(one, 0),
*host));
EXPECT_EQ(PositionInFlatTree(two->firstChild(), 2),
- FirstEditableVisiblePositionAfterPositionInRoot(
- PositionInFlatTree(one, 0), *host)
+ CreateVisiblePosition(FirstEditablePositionAfterPositionInRoot(
+ PositionInFlatTree(one, 0), *host))
.DeepEquivalent());
EXPECT_EQ(
Position::FirstPositionInNode(*host),
FirstEditablePositionAfterPositionInRoot(Position(three, 0), *host));
- EXPECT_EQ(
- Position(one->firstChild(), 0),
- FirstEditableVisiblePositionAfterPositionInRoot(Position(three, 0), *host)
- .DeepEquivalent());
+ EXPECT_EQ(Position(one->firstChild(), 0),
+ CreateVisiblePosition(FirstEditablePositionAfterPositionInRoot(
+ Position(three, 0), *host))
+ .DeepEquivalent());
EXPECT_EQ(PositionInFlatTree::AfterNode(*host),
FirstEditablePositionAfterPositionInRoot(
PositionInFlatTree(three, 0), *host));
EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*host),
- FirstEditableVisiblePositionAfterPositionInRoot(
- PositionInFlatTree(three, 0), *host)
+ CreateVisiblePosition(FirstEditablePositionAfterPositionInRoot(
+ PositionInFlatTree(three, 0), *host))
.DeepEquivalent());
}
@@ -126,13 +126,13 @@ TEST_F(EditingUtilitiesTest, isEditablePositionWithTable) {
// However, |setBodyContent()| automatically creates HTML, HEAD and BODY
// element. So, we build DOM tree manually.
// Note: This is unusual HTML taken from http://crbug.com/574230
- Element* table = GetDocument().CreateRawElement(HTMLNames::tableTag);
+ Element* table = GetDocument().CreateRawElement(html_names::kTableTag);
table->SetInnerHTMLFromString("<caption>foo</caption>");
while (GetDocument().firstChild())
GetDocument().firstChild()->remove();
GetDocument().AppendChild(table);
GetDocument().setDesignMode("on");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(IsEditablePosition(Position(table, 0)));
}
@@ -194,32 +194,32 @@ TEST_F(EditingUtilitiesTest, lastEditablePositionBeforePositionInRoot) {
EXPECT_EQ(Position(one, 0),
LastEditablePositionBeforePositionInRoot(Position(one, 0), *host));
- EXPECT_EQ(
- Position(one->firstChild(), 0),
- LastEditableVisiblePositionBeforePositionInRoot(Position(one, 0), *host)
- .DeepEquivalent());
+ EXPECT_EQ(Position(one->firstChild(), 0),
+ CreateVisiblePosition(LastEditablePositionBeforePositionInRoot(
+ Position(one, 0), *host))
+ .DeepEquivalent());
EXPECT_EQ(PositionInFlatTree(one, 0),
LastEditablePositionBeforePositionInRoot(PositionInFlatTree(one, 0),
*host));
EXPECT_EQ(PositionInFlatTree(two->firstChild(), 2),
- LastEditableVisiblePositionBeforePositionInRoot(
- PositionInFlatTree(one, 0), *host)
+ CreateVisiblePosition(LastEditablePositionBeforePositionInRoot(
+ PositionInFlatTree(one, 0), *host))
.DeepEquivalent());
EXPECT_EQ(
Position::FirstPositionInNode(*host),
LastEditablePositionBeforePositionInRoot(Position(three, 0), *host));
- EXPECT_EQ(
- Position(one->firstChild(), 0),
- LastEditableVisiblePositionBeforePositionInRoot(Position(three, 0), *host)
- .DeepEquivalent());
+ EXPECT_EQ(Position(one->firstChild(), 0),
+ CreateVisiblePosition(LastEditablePositionBeforePositionInRoot(
+ Position(three, 0), *host))
+ .DeepEquivalent());
EXPECT_EQ(PositionInFlatTree::FirstPositionInNode(*host),
LastEditablePositionBeforePositionInRoot(
PositionInFlatTree(three, 0), *host));
EXPECT_EQ(PositionInFlatTree(two->firstChild(), 0),
- LastEditableVisiblePositionBeforePositionInRoot(
- PositionInFlatTree(three, 0), *host)
+ CreateVisiblePosition(LastEditablePositionBeforePositionInRoot(
+ PositionInFlatTree(three, 0), *host))
.DeepEquivalent());
}
@@ -271,7 +271,7 @@ TEST_F(EditingUtilitiesTest, uncheckedPreviousNextOffset_FirstLetter) {
EXPECT_EQ(2, NextGraphemeBoundaryOf(node, 1));
EXPECT_EQ(3, NextGraphemeBoundaryOf(node, 2));
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(nullptr, node.GetLayoutObject());
EXPECT_EQ(2, PreviousGraphemeBoundaryOf(node, 3));
EXPECT_EQ(1, PreviousGraphemeBoundaryOf(node, 2));
@@ -292,7 +292,7 @@ TEST_F(EditingUtilitiesTest, uncheckedPreviousNextOffset_textTransform) {
EXPECT_EQ(2, NextGraphemeBoundaryOf(node, 1));
EXPECT_EQ(3, NextGraphemeBoundaryOf(node, 2));
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(nullptr, node.GetLayoutObject());
EXPECT_EQ(2, PreviousGraphemeBoundaryOf(node, 3));
EXPECT_EQ(1, PreviousGraphemeBoundaryOf(node, 2));
diff --git a/chromium/third_party/blink/renderer/core/editing/editor.cc b/chromium/third_party/blink/renderer/core/editing/editor.cc
index 5357dc0ac19..6ee491087d9 100644
--- a/chromium/third_party/blink/renderer/core/editing/editor.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editor.cc
@@ -33,8 +33,8 @@
#include "third_party/blink/renderer/core/clipboard/data_transfer_access_policy.h"
#include "third_party/blink/renderer/core/clipboard/system_clipboard.h"
#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
@@ -67,7 +67,6 @@
#include "third_party/blink/renderer/core/editing/visible_position.h"
#include "third_party/blink/renderer/core/editing/visible_units.h"
#include "third_party/blink/renderer/core/editing/writing_direction.h"
-#include "third_party/blink/renderer/core/event_names.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/events/text_event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -94,13 +93,13 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
bool IsInPasswordFieldWithUnrevealedPassword(const Position& position) {
if (auto* input = ToHTMLInputElementOrNull(EnclosingTextControl(position))) {
- return (input->type() == InputTypeNames::password) &&
+ return (input->type() == input_type_names::kPassword) &&
!input->ShouldRevealPassword();
}
return false;
@@ -448,7 +447,7 @@ void Editor::ApplyParagraphStyleToSelection(CSSPropertyValueSet* style,
}
Editor* Editor::Create(LocalFrame& frame) {
- return new Editor(frame);
+ return MakeGarbageCollected<Editor>(frame);
}
Editor::Editor(LocalFrame& frame)
@@ -594,7 +593,7 @@ void Editor::CountEvent(ExecutionContext* execution_context,
if (!execution_context)
return;
- if (event.type() == EventTypeNames::textInput) {
+ if (event.type() == event_type_names::kTextInput) {
CountEditingEvent(execution_context, event,
WebFeature::kTextInputEventOnInput,
WebFeature::kTextInputEventOnTextArea,
@@ -603,7 +602,7 @@ void Editor::CountEvent(ExecutionContext* execution_context,
return;
}
- if (event.type() == EventTypeNames::webkitBeforeTextInserted) {
+ if (event.type() == event_type_names::kWebkitBeforeTextInserted) {
CountEditingEvent(execution_context, event,
WebFeature::kWebkitBeforeTextInsertedOnInput,
WebFeature::kWebkitBeforeTextInsertedOnTextArea,
@@ -612,7 +611,7 @@ void Editor::CountEvent(ExecutionContext* execution_context,
return;
}
- if (event.type() == EventTypeNames::webkitEditableContentChanged) {
+ if (event.type() == event_type_names::kWebkitEditableContentChanged) {
CountEditingEvent(
execution_context, event,
WebFeature::kWebkitEditableContentChangedOnInput,
@@ -649,7 +648,7 @@ void Editor::SetBaseWritingDirection(WritingDirection direction) {
if (direction == WritingDirection::kNatural)
return;
focused_element->setAttribute(
- dirAttr, direction == WritingDirection::kLeftToRight ? "ltr" : "rtl");
+ kDirAttr, direction == WritingDirection::kLeftToRight ? "ltr" : "rtl");
focused_element->DispatchInputEvent();
return;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/editor.h b/chromium/third_party/blink/renderer/core/editing/editor.h
index b98e652e261..b6f3c97fabd 100644
--- a/chromium/third_party/blink/renderer/core/editing/editor.h
+++ b/chromium/third_party/blink/renderer/core/editing/editor.h
@@ -64,6 +64,8 @@ enum class WritingDirection;
class CORE_EXPORT Editor final : public GarbageCollectedFinalized<Editor> {
public:
static Editor* Create(LocalFrame&);
+
+ explicit Editor(LocalFrame&);
~Editor();
CompositeEditCommand* LastEditCommand() { return last_edit_command_.Get(); }
@@ -245,8 +247,6 @@ class CORE_EXPORT Editor final : public GarbageCollectedFinalized<Editor> {
Member<EditingStyle> typing_style_;
bool mark_is_directional_ = false;
- explicit Editor(LocalFrame&);
-
LocalFrame& GetFrame() const {
DCHECK(frame_);
return *frame_;
diff --git a/chromium/third_party/blink/renderer/core/editing/element_inner_text.cc b/chromium/third_party/blink/renderer/core/editing/element_inner_text.cc
index b70dac6b176..e96d4a71387 100644
--- a/chromium/third_party/blink/renderer/core/editing/element_inner_text.cc
+++ b/chromium/third_party/blink/renderer/core/editing/element_inner_text.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
+#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/html/forms/html_opt_group_element.h"
#include "third_party/blink/renderer/core/html/forms/html_option_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
@@ -21,9 +22,9 @@
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
-#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
-#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -47,22 +48,12 @@ class ElementInnerTextCollector final {
public:
Result() = default;
- void EmitBeginBlock();
void EmitChar16(UChar code_point);
- void EmitCollapsibleSpace();
- void EmitEndBlock();
void EmitNewline();
void EmitRequiredLineBreak(int count);
void EmitTab();
void EmitText(const StringView& text);
String Finish();
- void FlushCollapsibleSpace();
-
- bool HasCollapsibleSpace() const { return has_collapsible_space_; }
-
- void SetShouldCollapseWhitespace(bool value) {
- should_collapse_white_space_ = value;
- }
private:
void FlushRequiredLineBreak();
@@ -70,59 +61,36 @@ class ElementInnerTextCollector final {
StringBuilder builder_;
int required_line_break_count_ = 0;
- // |should_collapse_white_space_| is used for collapsing white spaces around
- // block, e.g. leading white space at start of block and leading white
- // spaces after inline-block.
- bool should_collapse_white_space_ = false;
- bool has_collapsible_space_ = false;
-
DISALLOW_COPY_AND_ASSIGN(Result);
};
- // Minimal CSS text box representation for collecting character.
- struct TextBox {
- StringView text;
- // An offset in |LayoutText::GetText()| or |NGInlineItemsData.text_content|.
- unsigned start = 0;
-
- TextBox(StringView passed_text, unsigned passed_start)
- : text(passed_text), start(passed_start) {
- DCHECK_GT(text.length(), 0u);
- }
- };
-
- static bool EndsWithWhiteSpace(const InlineTextBox& text_box);
- static bool EndsWithWhiteSpace(const LayoutText& layout_text);
- static bool EndsWithWhiteSpace(const NGPhysicalTextFragment& fragment);
static bool HasDisplayContentsStyle(const Node& node);
- static bool IsAfterWhiteSpace(const InlineTextBox& text_box);
- static bool IsAfterWhiteSpace(const LayoutText& layout_text);
- static bool IsAfterWhiteSpace(const NGPhysicalTextFragment& fragment);
static bool IsBeingRendered(const Node& node);
- static bool IsCollapsibleSpace(UChar code_point);
// Returns true if used value of "display" is block-level.
static bool IsDisplayBlockLevel(const Node&);
static LayoutObject* PreviousLeafOf(const LayoutObject& layout_object);
static bool ShouldEmitNewlineForTableRow(const LayoutTableRow& table_row);
- static bool StartsWithWhiteSpace(const LayoutText& layout_text);
+ const NGOffsetMapping* GetOffsetMapping(const LayoutText& layout_text);
void ProcessChildren(const Node& node);
void ProcessChildrenWithRequiredLineBreaks(const Node& node,
int required_line_break_count);
- void ProcessLayoutText(const LayoutText& layout_text);
+ void ProcessLayoutText(const LayoutText& layout_text, const Text& text_node);
void ProcessLayoutTextEmpty(const LayoutText& layout_text);
- void ProcessLayoutTextForNG(const NGPaintFragment::FragmentRange& fragments);
void ProcessNode(const Node& node);
void ProcessOptionElement(const HTMLOptionElement& element);
void ProcessSelectElement(const HTMLSelectElement& element);
- void ProcessText(StringView text, EWhiteSpace white_space);
- void ProcessTextBoxes(const LayoutText& layout_text,
- const Vector<TextBox>& text_boxes);
void ProcessTextNode(const Text& node);
// Result character buffer.
Result result_;
+ // Remember last |NGOffsetMapping| to avoid repeated offset mapping
+ // computation.
+ const LayoutBlockFlow* last_offset_mapping_block_flow_ = nullptr;
+ const NGOffsetMapping* last_offset_mapping_ = nullptr;
+ std::unique_ptr<NGOffsetMapping> offset_mapping_storage_;
+
DISALLOW_COPY_AND_ASSIGN(ElementInnerTextCollector);
};
@@ -141,37 +109,25 @@ String ElementInnerTextCollector::RunOn(const Element& element) {
return element.textContent(convert_brs_to_newlines);
}
- // 2. Let results be the list resulting in running the inner text collection
- // steps with this element. Each item in results will either be a JavaScript
- // string or a positive integer (a required line break count).
- ProcessNode(element);
+ // 2. Let results be a new empty list.
+ // 3. For each child node node of this element:
+ // 1. Let current be the list resulting in running the inner text collection
+ // steps with node. Each item in results will either be a JavaScript
+ // string or a positive integer (a required line break count).
+ // 2. For each item item in current, append item to results.
+ // Note: Handles <select> and <option> here since they are implemented as
+ // UA shadow DOM, e.g. Text nodes in <option> don't have layout object.
+ // See also: https://github.com/whatwg/html/issues/3797
+ if (IsHTMLSelectElement(element))
+ ProcessSelectElement(ToHTMLSelectElement(element));
+ else if (IsHTMLOptionElement(element))
+ ProcessOptionElement(ToHTMLOptionElement(element));
+ else
+ ProcessChildren(element);
return result_.Finish();
}
// static
-bool ElementInnerTextCollector::EndsWithWhiteSpace(
- const InlineTextBox& text_box) {
- const unsigned length = text_box.Len();
- if (length == 0)
- return false;
- const String text = text_box.GetLineLayoutItem().GetText();
- return IsCollapsibleSpace(text[text_box.Start() + length - 1]);
-}
-
-// static
-bool ElementInnerTextCollector::EndsWithWhiteSpace(
- const LayoutText& layout_text) {
- const unsigned length = layout_text.TextLength();
- return length > 0 && layout_text.ContainsOnlyWhitespace(length - 1, 1);
-}
-
-// static
-bool ElementInnerTextCollector::EndsWithWhiteSpace(
- const NGPhysicalTextFragment& fragment) {
- return IsCollapsibleSpace(fragment.Text()[fragment.Length() - 1]);
-}
-
-// static
bool ElementInnerTextCollector::HasDisplayContentsStyle(const Node& node) {
return node.IsElementNode() && ToElement(node).HasDisplayContentsStyle();
}
@@ -188,71 +144,24 @@ bool ElementInnerTextCollector::IsBeingRendered(const Node& node) {
}
// static
-bool ElementInnerTextCollector::IsAfterWhiteSpace(
- const InlineTextBox& text_box) {
- const unsigned start = text_box.Start();
- if (start == 0)
- return false;
- const String text = text_box.GetLineLayoutItem().GetText();
- return IsCollapsibleSpace(text[start - 1]);
-}
-
-// static
-bool ElementInnerTextCollector::IsAfterWhiteSpace(
- const LayoutText& layout_text) {
- if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
- const auto fragments = NGPaintFragment::InlineFragmentsFor(&layout_text);
- if (!fragments.IsEmpty() &&
- fragments.IsInLayoutNGInlineFormattingContext()) {
- NGPaintFragmentTraversalContext previous =
- NGPaintFragmentTraversal::PreviousInlineLeafOfIgnoringLineBreak(
- NGPaintFragmentTraversalContext::Create(&fragments.front()));
- if (previous.IsNull())
- return false;
- const NGPhysicalFragment& previous_fragment =
- previous.GetFragment()->PhysicalFragment();
- if (!previous_fragment.IsText())
- return false;
- return EndsWithWhiteSpace(ToNGPhysicalTextFragment(previous_fragment));
- }
- }
- if (InlineTextBox* text_box = layout_text.FirstTextBox()) {
- const InlineBox* previous = text_box->PrevLeafChild();
- if (!previous || !previous->IsInlineTextBox())
- return false;
- return EndsWithWhiteSpace(ToInlineTextBox(*previous));
- }
- const LayoutObject* previous_leaf = PreviousLeafOf(layout_text);
- if (!previous_leaf || !previous_leaf->IsText())
- return false;
- const LayoutText& previous_text = ToLayoutText(*previous_leaf);
- const unsigned length = previous_text.TextLength();
- if (length == 0)
- return false;
- return previous_text.ContainsOnlyWhitespace(length - 1, 1);
-}
-
-bool ElementInnerTextCollector::IsAfterWhiteSpace(
- const NGPhysicalTextFragment& text_box) {
- const unsigned start = text_box.StartOffset();
- if (start == 0)
- return false;
- const String text = text_box.TextContent();
- return IsCollapsibleSpace(text[start - 1]);
-}
-
-// See https://drafts.csswg.org/css-text-3/#white-space-phase-2
-bool ElementInnerTextCollector::IsCollapsibleSpace(UChar code_point) {
- return code_point == kSpaceCharacter || code_point == kNewlineCharacter ||
- code_point == kTabulationCharacter ||
- code_point == kCarriageReturnCharacter;
-}
-
-// static
bool ElementInnerTextCollector::IsDisplayBlockLevel(const Node& node) {
const LayoutObject* const layout_object = node.GetLayoutObject();
- if (!layout_object || !layout_object->IsLayoutBlock())
+ if (!layout_object)
return false;
+ if (!layout_object->IsLayoutBlock()) {
+ if (layout_object->IsTableSection()) {
+ // Note: |LayoutTableSeleciton::IsInline()| returns false, but it is not
+ // block-level.
+ return false;
+ }
+ // Note: Block-level replaced elements, e.g. <img style=display:block>,
+ // reach here. Unlike |LayoutBlockFlow::AddChild()|, innerText considers
+ // floats and absolutely-positioned elements as block-level node.
+ return !layout_object->IsInline();
+ }
+ // TODO(crbug.com/567964): Due by the issue, |IsAtomicInlineLevel()| is always
+ // true for replaced elements event if it has display:block, once it is fixed
+ // we should check at first.
if (layout_object->IsAtomicInlineLevel())
return false;
if (layout_object->IsRubyText()) {
@@ -303,11 +212,36 @@ bool ElementInnerTextCollector::ShouldEmitNewlineForTableRow(
return false;
}
-// static
-bool ElementInnerTextCollector::StartsWithWhiteSpace(
+// Note: LayoutFlowThread, used for multicol, can't provide offset mapping.
+bool CanUseOffsetMapping(const LayoutObject& object) {
+ return object.IsLayoutBlockFlow() && !object.IsLayoutFlowThread();
+}
+
+LayoutBlockFlow* ContainingBlockFlowFor(const LayoutText& object) {
+ for (LayoutObject* runner = object.Parent(); runner;
+ runner = runner->Parent()) {
+ if (!CanUseOffsetMapping(*runner))
+ continue;
+ return ToLayoutBlockFlow(runner);
+ }
+ return nullptr;
+}
+
+const NGOffsetMapping* ElementInnerTextCollector::GetOffsetMapping(
const LayoutText& layout_text) {
- const unsigned length = layout_text.TextLength();
- return length > 0 && layout_text.ContainsOnlyWhitespace(0, 1);
+ // TODO(editing-dev): We should handle "text-transform" in "::first-line".
+ // In legacy layout, |InlineTextBox| holds original text and text box
+ // paint does text transform.
+ LayoutBlockFlow* const block_flow = ContainingBlockFlowFor(layout_text);
+ DCHECK(block_flow) << layout_text;
+ if (block_flow == last_offset_mapping_block_flow_)
+ return last_offset_mapping_;
+ const NGOffsetMapping* const mapping =
+ NGInlineNode::GetOffsetMapping(block_flow, &offset_mapping_storage_);
+ DCHECK(mapping) << layout_text;
+ last_offset_mapping_block_flow_ = block_flow;
+ last_offset_mapping_ = mapping;
+ return mapping;
}
void ElementInnerTextCollector::ProcessChildren(const Node& container) {
@@ -318,17 +252,15 @@ void ElementInnerTextCollector::ProcessChildren(const Node& container) {
void ElementInnerTextCollector::ProcessChildrenWithRequiredLineBreaks(
const Node& node,
int required_line_break_count) {
- DCHECK_GE(required_line_break_count, 0);
+ DCHECK_GE(required_line_break_count, 1);
DCHECK_LE(required_line_break_count, 2);
- result_.EmitBeginBlock();
result_.EmitRequiredLineBreak(required_line_break_count);
ProcessChildren(node);
result_.EmitRequiredLineBreak(required_line_break_count);
- result_.EmitEndBlock();
}
-void ElementInnerTextCollector::ProcessLayoutText(
- const LayoutText& layout_text) {
+void ElementInnerTextCollector::ProcessLayoutText(const LayoutText& layout_text,
+ const Text& text_node) {
if (layout_text.TextLength() == 0)
return;
if (layout_text.Style()->Visibility() != EVisibility::kVisible) {
@@ -336,94 +268,14 @@ void ElementInnerTextCollector::ProcessLayoutText(
// we should get rid of this if-statement. http://crbug.com/866744
return;
}
- if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
- const auto fragments = NGPaintFragment::InlineFragmentsFor(&layout_text);
- if (!fragments.IsEmpty() &&
- fragments.IsInLayoutNGInlineFormattingContext()) {
- ProcessLayoutTextForNG(fragments);
- return;
- }
- }
-
- if (!layout_text.FirstTextBox()) {
- if (!layout_text.ContainsOnlyWhitespace(0, layout_text.TextLength()))
- return;
- if (IsAfterWhiteSpace(layout_text))
- return;
- // <div style="width:0">abc<span> <span>def</span></div> reaches here for
- // a space between SPAN.
- result_.EmitCollapsibleSpace();
- return;
- }
-
- // TODO(editing-dev): We should handle "text-transform" in "::first-line".
- // In legacy layout, |InlineTextBox| holds original text and text box
- // paint does text transform.
- const String text = layout_text.GetText();
- const bool collapse_white_space = layout_text.Style()->CollapseWhiteSpace();
- bool may_have_leading_space = collapse_white_space &&
- StartsWithWhiteSpace(layout_text) &&
- !IsAfterWhiteSpace(layout_text);
- Vector<TextBox> text_boxes;
- for (InlineTextBox* text_box : layout_text.TextBoxes()) {
- const unsigned start =
- may_have_leading_space && IsAfterWhiteSpace(*text_box)
- ? text_box->Start() - 1
- : text_box->Start();
- const unsigned end = text_box->Start() + text_box->Len();
- may_have_leading_space =
- collapse_white_space && !IsCollapsibleSpace(text[end - 1]);
- text_boxes.emplace_back(StringView(text, start, end - start), start);
- }
- ProcessTextBoxes(layout_text, text_boxes);
- if (!collapse_white_space || !EndsWithWhiteSpace(layout_text))
- return;
- result_.EmitCollapsibleSpace();
-}
-void ElementInnerTextCollector::ProcessLayoutTextForNG(
- const NGPaintFragment::FragmentRange& paint_fragments) {
- DCHECK(!paint_fragments.IsEmpty());
- const LayoutText& layout_text =
- ToLayoutText(*paint_fragments.front().GetLayoutObject());
- const bool collapse_white_space = layout_text.Style()->CollapseWhiteSpace();
- bool may_have_leading_space = collapse_white_space &&
- StartsWithWhiteSpace(layout_text) &&
- !IsAfterWhiteSpace(layout_text);
- // TODO(editing-dev): We should include overflow text to result of CSS
- // "text-overflow". See http://crbug.com/873957
- Vector<TextBox> text_boxes;
- const StringImpl* last_text_content = nullptr;
- for (const NGPaintFragment* paint_fragment : paint_fragments) {
- const NGPhysicalTextFragment& text_fragment =
- ToNGPhysicalTextFragment(paint_fragment->PhysicalFragment());
- if (text_fragment.IsGeneratedText())
- continue;
- // Symbol marker should be appeared in pseudo-element only.
- DCHECK_NE(text_fragment.TextType(), NGPhysicalTextFragment::kSymbolMarker);
- if (last_text_content != text_fragment.TextContent().Impl()) {
- if (!text_boxes.IsEmpty()) {
- ProcessTextBoxes(layout_text, text_boxes);
- text_boxes.clear();
- }
- last_text_content = text_fragment.TextContent().Impl();
- }
- const unsigned start =
- may_have_leading_space && IsAfterWhiteSpace(text_fragment)
- ? text_fragment.StartOffset() - 1
- : text_fragment.StartOffset();
- const unsigned end = text_fragment.EndOffset();
- may_have_leading_space =
- collapse_white_space &&
- !IsCollapsibleSpace(text_fragment.TextContent()[end - 1]);
- text_boxes.emplace_back(
- StringView(text_fragment.TextContent(), start, end - start), start);
+ const NGOffsetMapping* const mapping = GetOffsetMapping(layout_text);
+ const NGMappingUnitRange range = mapping->GetMappingUnitsForNode(text_node);
+ for (const NGOffsetMappingUnit& unit : range) {
+ result_.EmitText(
+ StringView(mapping->GetText(), unit.TextContentStart(),
+ unit.TextContentEnd() - unit.TextContentStart()));
}
- if (!text_boxes.IsEmpty())
- ProcessTextBoxes(layout_text, text_boxes);
- if (!collapse_white_space || !EndsWithWhiteSpace(layout_text))
- return;
- result_.EmitCollapsibleSpace();
}
// The "inner text collection steps".
@@ -471,7 +323,6 @@ void ElementInnerTextCollector::ProcessNode(const Node& node) {
if (IsHTMLBRElement(node)) {
ProcessChildren(node);
result_.EmitNewline();
- result_.SetShouldCollapseWhitespace(true);
return;
}
@@ -481,8 +332,7 @@ void ElementInnerTextCollector::ProcessNode(const Node& node) {
// character to items.
const LayoutObject& layout_object = *node.GetLayoutObject();
if (style->Display() == EDisplay::kTableCell) {
- ProcessChildrenWithRequiredLineBreaks(node, 0);
- result_.EmitEndBlock();
+ ProcessChildren(node);
if (layout_object.IsTableCell() &&
ToLayoutTableCell(layout_object).NextCell())
result_.EmitTab();
@@ -494,7 +344,7 @@ void ElementInnerTextCollector::ProcessNode(const Node& node) {
// append a string containing a single U+000A LINE FEED (LF) character to
// items.
if (style->Display() == EDisplay::kTableRow) {
- ProcessChildrenWithRequiredLineBreaks(node, 0);
+ ProcessChildren(node);
if (layout_object.IsTableRow() &&
ShouldEmitNewlineForTableRow(ToLayoutTableRow(layout_object)))
result_.EmitNewline();
@@ -516,15 +366,6 @@ void ElementInnerTextCollector::ProcessNode(const Node& node) {
if (IsDisplayBlockLevel(node))
return ProcessChildrenWithRequiredLineBreaks(node, 1);
- if (layout_object.IsLayoutBlock()) {
- result_.FlushCollapsibleSpace();
- ProcessChildrenWithRequiredLineBreaks(node, 0);
- // We should not collapse white space after inline-block.
- // e.g. abc <span style="display:inline-block"></span> def => "abc def".
- // See http://crbug.com/890020
- result_.SetShouldCollapseWhitespace(false);
- return;
- }
ProcessChildren(node);
}
@@ -555,81 +396,31 @@ void ElementInnerTextCollector::ProcessSelectElement(
}
}
-void ElementInnerTextCollector::ProcessTextBoxes(
- const LayoutText& layout_text,
- const Vector<TextBox>& passed_text_boxes) {
- DCHECK(!passed_text_boxes.IsEmpty());
- Vector<TextBox> text_boxes = passed_text_boxes;
- // TODO(editing-dev): We may want to check |ContainsReversedText()| in
- // |LayoutText|. See http://crbug.com/873949
- std::sort(text_boxes.begin(), text_boxes.end(),
- [](const TextBox& text_box1, const TextBox& text_box2) {
- return text_box1.start < text_box2.start;
- });
- const EWhiteSpace white_space = layout_text.Style()->WhiteSpace();
- for (const TextBox& text_box : text_boxes)
- ProcessText(text_box.text, white_space);
-}
-
-void ElementInnerTextCollector::ProcessText(StringView text,
- EWhiteSpace white_space) {
- if (!ComputedStyle::CollapseWhiteSpace(white_space))
- return result_.EmitText(text);
- for (unsigned index = 0; index < text.length(); ++index) {
- if (white_space == EWhiteSpace::kPreLine &&
- text[index] == kNewlineCharacter) {
- result_.EmitNewline();
- continue;
- }
- if (IsCollapsibleSpace(text[index])) {
- result_.EmitCollapsibleSpace();
- continue;
- }
- result_.EmitChar16(text[index]);
- }
-}
-
void ElementInnerTextCollector::ProcessTextNode(const Text& node) {
if (!node.GetLayoutObject())
return;
const LayoutText& layout_text = *node.GetLayoutObject();
- if (LayoutText* first_letter_part = layout_text.GetFirstLetterPart())
- ProcessLayoutText(*first_letter_part);
- ProcessLayoutText(layout_text);
+ if (LayoutText* first_letter_part = layout_text.GetFirstLetterPart()) {
+ if (layout_text.TextLength() == 0 ||
+ ContainingBlockFlowFor(layout_text) !=
+ ContainingBlockFlowFor(*first_letter_part)) {
+ // "::first-letter" with "float" reach here.
+ ProcessLayoutText(*first_letter_part, node);
+ }
+ }
+ ProcessLayoutText(layout_text, node);
}
// ----
-void ElementInnerTextCollector::Result::EmitBeginBlock() {
- should_collapse_white_space_ = true;
-}
-
void ElementInnerTextCollector::Result::EmitChar16(UChar code_point) {
- if (required_line_break_count_ > 0)
- FlushRequiredLineBreak();
- else
- FlushCollapsibleSpace();
+ FlushRequiredLineBreak();
DCHECK_EQ(required_line_break_count_, 0);
- DCHECK(!has_collapsible_space_);
builder_.Append(code_point);
- should_collapse_white_space_ = false;
-}
-
-void ElementInnerTextCollector::Result::EmitCollapsibleSpace() {
- if (should_collapse_white_space_)
- return;
- FlushRequiredLineBreak();
- has_collapsible_space_ = true;
-}
-
-void ElementInnerTextCollector::Result::EmitEndBlock() {
- // Discard tailing collapsible spaces from last child of the block.
- has_collapsible_space_ = false;
}
void ElementInnerTextCollector::Result::EmitNewline() {
FlushRequiredLineBreak();
- has_collapsible_space_ = false;
builder_.Append(kNewlineCharacter);
}
@@ -640,8 +431,6 @@ void ElementInnerTextCollector::Result::EmitRequiredLineBreak(int count) {
return;
// 4. Remove any runs of consecutive required line break count items at the
// start or end of results.
- should_collapse_white_space_ = true;
- has_collapsible_space_ = false;
if (builder_.IsEmpty()) {
DCHECK_EQ(required_line_break_count_, 0);
return;
@@ -653,45 +442,27 @@ void ElementInnerTextCollector::Result::EmitRequiredLineBreak(int count) {
}
void ElementInnerTextCollector::Result::EmitTab() {
- if (required_line_break_count_ > 0)
- FlushRequiredLineBreak();
- has_collapsible_space_ = false;
- should_collapse_white_space_ = false;
+ FlushRequiredLineBreak();
builder_.Append(kTabulationCharacter);
}
void ElementInnerTextCollector::Result::EmitText(const StringView& text) {
if (text.IsEmpty())
return;
- should_collapse_white_space_ = false;
- if (required_line_break_count_ > 0)
- FlushRequiredLineBreak();
- else
- FlushCollapsibleSpace();
+ FlushRequiredLineBreak();
DCHECK_EQ(required_line_break_count_, 0);
- DCHECK(!has_collapsible_space_);
builder_.Append(text);
}
String ElementInnerTextCollector::Result::Finish() {
- if (required_line_break_count_ == 0)
- FlushCollapsibleSpace();
return builder_.ToString();
}
-void ElementInnerTextCollector::Result::FlushCollapsibleSpace() {
- if (!has_collapsible_space_)
- return;
- has_collapsible_space_ = false;
- builder_.Append(kSpaceCharacter);
-}
-
void ElementInnerTextCollector::Result::FlushRequiredLineBreak() {
DCHECK_GE(required_line_break_count_, 0);
DCHECK_LE(required_line_break_count_, 2);
builder_.Append("\n\n", required_line_break_count_);
required_line_break_count_ = 0;
- has_collapsible_space_ = false;
}
} // anonymous namespace
diff --git a/chromium/third_party/blink/renderer/core/editing/element_inner_text_test.cc b/chromium/third_party/blink/renderer/core/editing/element_inner_text_test.cc
index 9a29659c447..b1b58a03e37 100644
--- a/chromium/third_party/blink/renderer/core/editing/element_inner_text_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/element_inner_text_test.cc
@@ -5,20 +5,35 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/editing/testing/editing_test_base.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
-class ElementInnerTest : public EditingTestBase {};
+class ElementInnerTest : public testing::WithParamInterface<bool>,
+ private ScopedLayoutNGForTest,
+ public EditingTestBase {
+ protected:
+ ElementInnerTest() : ScopedLayoutNGForTest(GetParam()) {}
+
+ bool LayoutNGEnabled() const { return GetParam(); }
+};
+
+INSTANTIATE_TEST_CASE_P(All, ElementInnerTest, testing::Bool());
// http://crbug.com/877498
-TEST_F(ElementInnerTest, ListItemWithLeadingWhiteSpace) {
+TEST_P(ElementInnerTest, ListItemWithLeadingWhiteSpace) {
SetBodyContent("<li id=target> abc</li>");
Element& target = *GetDocument().getElementById("target");
+ if (!LayoutNGEnabled()) {
+ // TODO(crbug.com/908339) Actual result should be "abc", no leading space.
+ EXPECT_EQ(" abc", target.innerText());
+ return;
+ }
EXPECT_EQ("abc", target.innerText());
}
// http://crbug.com/877470
-TEST_F(ElementInnerTest, SVGElementAsTableCell) {
+TEST_P(ElementInnerTest, SVGElementAsTableCell) {
SetBodyContent(
"<div id=target>abc"
"<svg><rect style='display:table-cell'></rect></svg>"
@@ -28,7 +43,7 @@ TEST_F(ElementInnerTest, SVGElementAsTableCell) {
}
// http://crbug.com/878725
-TEST_F(ElementInnerTest, SVGElementAsTableRow) {
+TEST_P(ElementInnerTest, SVGElementAsTableRow) {
SetBodyContent(
"<div id=target>abc"
"<svg><rect style='display:table-row'></rect></svg>"
diff --git a/chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.cc b/chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.cc
new file mode 100644
index 00000000000..b78d4974944
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.cc
@@ -0,0 +1,293 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/editing/finder/find_task_controller.h"
+
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/idle_request_options.h"
+#include "third_party/blink/renderer/core/dom/range.h"
+#include "third_party/blink/renderer/core/dom/scripted_idle_task_controller.h"
+#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
+#include "third_party/blink/renderer/core/editing/finder/find_options.h"
+#include "third_party/blink/renderer/core/editing/finder/text_finder.h"
+#include "third_party/blink/renderer/core/editing/iterators/search_buffer.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/wtf/time.h"
+
+namespace blink {
+
+namespace {
+const int kFindingTimeoutMS = 100;
+constexpr TimeDelta kFindTaskTestTimeout = TimeDelta::FromSeconds(10);
+} // namespace
+
+class FindTaskController::IdleFindTask
+ : public ScriptedIdleTaskController::IdleTask {
+ public:
+ static IdleFindTask* Create(FindTaskController* controller,
+ Document* document,
+ int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options) {
+ return new IdleFindTask(controller, document, identifier, search_text,
+ options);
+ }
+
+ void Dispose() {
+ DCHECK_GT(callback_handle_, 0);
+ document_->CancelIdleCallback(callback_handle_);
+ }
+
+ void ForceInvocationForTesting() {
+ invoke(IdleDeadline::Create(CurrentTimeTicks() + kFindTaskTestTimeout,
+ IdleDeadline::CallbackType::kCalledWhenIdle));
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(controller_);
+ visitor->Trace(document_);
+ ScriptedIdleTaskController::IdleTask::Trace(visitor);
+ }
+
+ private:
+ IdleFindTask(FindTaskController* controller,
+ Document* document,
+ int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options)
+ : document_(document),
+ controller_(controller),
+ identifier_(identifier),
+ search_text_(search_text),
+ options_(options.Clone()) {
+ DCHECK(document_);
+ // We need to add deadline because some webpages might have frames
+ // that are always busy, resulting in bad experience in find-in-page
+ // because the scoping tasks are not run.
+ // See crbug.com/893465.
+ IdleRequestOptions* request_options = IdleRequestOptions::Create();
+ request_options->setTimeout(kFindingTimeoutMS);
+ callback_handle_ = document_->RequestIdleCallback(this, request_options);
+ }
+
+ void invoke(IdleDeadline* deadline) override {
+ if (!controller_->ShouldFindMatches(search_text_, *options_)) {
+ controller_->DidFinishTask(identifier_, search_text_, *options_,
+ true /* finished_whole_request */,
+ PositionInFlatTree(), 0 /* match_count */);
+ }
+
+ const TimeDelta time_available =
+ TimeDelta::FromMillisecondsD(deadline->timeRemaining());
+ const TimeTicks start_time = CurrentTimeTicks();
+
+ PositionInFlatTree search_start = PositionInFlatTree::FirstPositionInNode(
+ *controller_->GetLocalFrame()->GetDocument());
+ PositionInFlatTree search_end = PositionInFlatTree::LastPositionInNode(
+ *controller_->GetLocalFrame()->GetDocument());
+ DCHECK_EQ(search_start.GetDocument(), search_end.GetDocument());
+
+ if (Range* resume_from_range = controller_->ResumeFindingFromRange()) {
+ // This is a continuation of a finding operation that timed out and didn't
+ // complete last time around, so we should start from where we left off.
+ DCHECK(resume_from_range->collapsed());
+ search_start = FromPositionInDOMTree<EditingInFlatTreeStrategy>(
+ resume_from_range->EndPosition());
+ if (search_start.GetDocument() != search_end.GetDocument())
+ return;
+ }
+
+ // TODO(editing-dev): Use of updateStyleAndLayoutIgnorePendingStylesheets
+ // needs to be audited. see http://crbug.com/590369 for more details.
+ search_start.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
+
+ int match_count = 0;
+ bool full_range_searched = false;
+ PositionInFlatTree next_scoping_start;
+ do {
+ // Find next occurrence of the search string.
+ // FIXME: (http://crbug.com/6818) This WebKit operation may run for longer
+ // than the timeout value, and is not interruptible as it is currently
+ // written. We may need to rewrite it with interruptibility in mind, or
+ // find an alternative.
+ const EphemeralRangeInFlatTree result = FindPlainText(
+ EphemeralRangeInFlatTree(search_start, search_end), search_text_,
+ options_->match_case ? 0 : kCaseInsensitive);
+ if (result.IsCollapsed()) {
+ // Not found.
+ full_range_searched = true;
+ break;
+ }
+ Range* result_range = Range::Create(
+ result.GetDocument(), ToPositionInDOMTree(result.StartPosition()),
+ ToPositionInDOMTree(result.EndPosition()));
+ if (result_range->collapsed()) {
+ // resultRange will be collapsed if the matched text spans over multiple
+ // TreeScopes. FIXME: Show such matches to users.
+ search_start = result.EndPosition();
+ if (deadline->timeRemaining() > 0)
+ continue;
+ break;
+ }
+ ++match_count;
+ controller_->DidFindMatch(identifier_, result_range);
+
+ // Set the new start for the search range to be the end of the previous
+ // result range. There is no need to use a VisiblePosition here,
+ // since findPlainText will use a TextIterator to go over the visible
+ // text nodes.
+ search_start = result.EndPosition();
+ next_scoping_start = search_start;
+ } while (deadline->timeRemaining() > 0);
+
+ const TimeDelta time_spent = CurrentTimeTicks() - start_time;
+ UMA_HISTOGRAM_TIMES("WebCore.FindInPage.ScopingTime",
+ time_spent - time_available);
+
+ controller_->DidFinishTask(identifier_, search_text_, *options_,
+ full_range_searched, next_scoping_start,
+ match_count);
+ }
+
+ Member<Document> document_;
+ Member<FindTaskController> controller_;
+ int callback_handle_ = 0;
+ const int identifier_;
+ const WebString search_text_;
+ mojom::blink::FindOptionsPtr options_;
+};
+
+FindTaskController::FindTaskController(WebLocalFrameImpl& owner_frame,
+ TextFinder& text_finder)
+ : owner_frame_(owner_frame),
+ text_finder_(text_finder),
+ resume_finding_from_range_(nullptr) {}
+
+void FindTaskController::StartRequest(
+ int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options) {
+ // This is a brand new search, so we need to reset everything.
+ finding_in_progress_ = true;
+ current_match_count_ = 0;
+ RequestIdleFindTask(identifier, search_text, options);
+}
+
+void FindTaskController::CancelPendingRequest() {
+ if (idle_find_task_) {
+ idle_find_task_->Dispose();
+ idle_find_task_.Clear();
+ }
+ if (finding_in_progress_)
+ last_find_request_completed_with_no_matches_ = false;
+ finding_in_progress_ = false;
+ resume_finding_from_range_ = nullptr;
+}
+
+void FindTaskController::RequestIdleFindTask(
+ int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options) {
+ DCHECK_EQ(idle_find_task_, nullptr);
+ idle_find_task_ = IdleFindTask::Create(this, GetLocalFrame()->GetDocument(),
+ identifier, search_text, options);
+ // If it's for testing, run the task immediately.
+ // TODO(rakina): Change to use general solution when it's available.
+ // https://crbug.com/875203
+ if (options.run_synchronously_for_testing)
+ idle_find_task_->ForceInvocationForTesting();
+}
+
+void FindTaskController::DidFinishTask(
+ int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options,
+ bool finished_whole_request,
+ PositionInFlatTree next_starting_position,
+ int match_count) {
+ if (idle_find_task_) {
+ idle_find_task_->Dispose();
+ idle_find_task_.Clear();
+ }
+ // Remember what we search for last time, so we can skip searching if more
+ // letters are added to the search string (and last outcome was 0).
+ last_search_string_ = search_text;
+
+ if (next_starting_position.IsNotNull()) {
+ resume_finding_from_range_ =
+ Range::Create(*next_starting_position.GetDocument(),
+ ToPositionInDOMTree(next_starting_position),
+ ToPositionInDOMTree(next_starting_position));
+ }
+
+ if (match_count > 0) {
+ text_finder_->UpdateMatches(identifier, match_count,
+ finished_whole_request);
+ }
+
+ if (!finished_whole_request) {
+ // Idle task ran out of time, request for another one.
+ RequestIdleFindTask(identifier, search_text, options);
+ return; // Done for now, resume work later.
+ }
+
+ text_finder_->FinishCurrentScopingEffort(identifier);
+
+ last_find_request_completed_with_no_matches_ = !current_match_count_;
+ finding_in_progress_ = false;
+}
+
+LocalFrame* FindTaskController::GetLocalFrame() const {
+ return OwnerFrame().GetFrame();
+}
+
+bool FindTaskController::ShouldFindMatches(
+ const String& search_text,
+ const mojom::blink::FindOptions& options) {
+ // Don't scope if we can't find a frame or a view.
+ // The user may have closed the tab/application, so abort.
+ LocalFrame* frame = GetLocalFrame();
+ if (!frame || !frame->View() || !frame->GetPage())
+ return false;
+
+ DCHECK(frame->GetDocument());
+ DCHECK(frame->View());
+
+ if (options.force)
+ return true;
+
+ if (!OwnerFrame().HasVisibleContent())
+ return false;
+
+ // If the frame completed the scoping operation and found 0 matches the last
+ // time it was searched, then we don't have to search it again if the user is
+ // just adding to the search string or sending the same search string again.
+ if (last_find_request_completed_with_no_matches_ &&
+ !last_search_string_.IsEmpty()) {
+ // Check to see if the search string prefixes match.
+ String previous_search_prefix =
+ search_text.Substring(0, last_search_string_.length());
+
+ if (previous_search_prefix == last_search_string_)
+ return false; // Don't search this frame, it will be fruitless.
+ }
+
+ return true;
+}
+
+void FindTaskController::DidFindMatch(int identifier, Range* result_range) {
+ current_match_count_++;
+ text_finder_->DidFindMatch(identifier, current_match_count_, result_range);
+}
+
+void FindTaskController::Trace(Visitor* visitor) {
+ visitor->Trace(owner_frame_);
+ visitor->Trace(text_finder_);
+ visitor->Trace(idle_find_task_);
+ visitor->Trace(resume_finding_from_range_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.h b/chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.h
new file mode 100644
index 00000000000..99f0b3c4e53
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.h
@@ -0,0 +1,117 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_FINDER_FIND_TASK_CONTROLLER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_FINDER_FIND_TASK_CONTROLLER_H_
+
+#include "third_party/blink/public/mojom/frame/find_in_page.mojom-blink.h"
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/editing/position.h"
+#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+class LocalFrame;
+class Range;
+class TextFinder;
+class WebString;
+class WebLocalFrameImpl;
+
+class CORE_EXPORT FindTaskController final
+ : public GarbageCollectedFinalized<FindTaskController> {
+ public:
+ static FindTaskController* Create(WebLocalFrameImpl& owner_frame,
+ TextFinder& text_finder) {
+ return new FindTaskController(owner_frame, text_finder);
+ }
+
+ // Starts an effort of finding |search_text| in |owner_frame|,
+ // which will be done asynchronously with idle tasks.
+ void StartRequest(int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options);
+
+ // Cancels the current effort, canceling the idle task request
+ // and resets variables related to the current state.
+ void CancelPendingRequest();
+
+ LocalFrame* GetLocalFrame() const;
+
+ WebLocalFrameImpl& OwnerFrame() const {
+ DCHECK(owner_frame_);
+ return *owner_frame_;
+ }
+
+ // Determines whether the finding effort is required for a particular frame.
+ // It is not necessary if the frame is invisible, for example, or if this
+ // is a repeat search that already returned nothing last time the same prefix
+ // was searched.
+ bool ShouldFindMatches(const String& search_text,
+ const mojom::blink::FindOptions& options);
+
+ // During a run of |idle_find_task|, we found a match.
+ // Updates |current_match_count_| and notifies |text_finder_|.
+ void DidFindMatch(int identifier, Range* result_range);
+
+ // One run of idle task finishes, so we need to update our state and
+ // notify |text_finder_| accordingly. Also schedules next task if needed.
+ void DidFinishTask(int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options,
+ bool finished_whole_request,
+ PositionInFlatTree next_starting_position,
+ int match_count);
+
+ Range* ResumeFindingFromRange() const { return resume_finding_from_range_; }
+ int CurrentMatchCount() const { return current_match_count_; }
+
+ // Idle task, when invoked will search for a given text and notify us
+ // whenever a match is found or when it finishes, through FoundMatch and
+ // DidFinishTask.
+ class IdleFindTask;
+
+ void Trace(Visitor* visitor);
+
+ private:
+ FindTaskController(WebLocalFrameImpl& owner_frame, TextFinder& text_finder);
+
+ void RequestIdleFindTask(int identifier,
+ const WebString& search_text,
+ const mojom::blink::FindOptions& options);
+
+ Member<WebLocalFrameImpl> owner_frame_;
+
+ Member<TextFinder> text_finder_;
+
+ Member<IdleFindTask> idle_find_task_;
+
+ // Keeps track if there is any ongoing find effort or not.
+ bool finding_in_progress_;
+
+ // Keeps track of how many matches the current finding effort has
+ // found so far.
+ int current_match_count_;
+
+ // The finding effort can time out and we need to keep track of where we
+ // ended our last search so we can continue from where we left of.
+ //
+ // This range is collapsed to the end position of the last successful
+ // search; the new search should start from this position.
+ Member<Range> resume_finding_from_range_;
+
+ // Keeps track of whether the last find request completed its finding effort
+ // without finding any matches in this frame.
+ bool last_find_request_completed_with_no_matches_;
+
+ // Keeps track of the last string this frame searched for. This is used for
+ // short-circuiting searches in the following scenarios: When a frame has
+ // been searched and returned 0 results, we don't need to search that frame
+ // again if the user is just adding to the search (making it more specific).
+ WTF::String last_search_string_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_FINDER_FIND_TASK_CONTROLLER_H_
diff --git a/chromium/third_party/blink/renderer/core/editing/finder/text_finder.cc b/chromium/third_party/blink/renderer/core/editing/finder/text_finder.cc
index a75f4be88d8..7398b74c230 100644
--- a/chromium/third_party/blink/renderer/core/editing/finder/text_finder.cc
+++ b/chromium/third_party/blink/renderer/core/editing/finder/text_finder.cc
@@ -30,21 +30,19 @@
#include "third_party/blink/renderer/core/editing/finder/text_finder.h"
-#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_float_rect.h"
#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
#include "third_party/blink/public/web/web_view_client.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache_base.h"
-#include "third_party/blink/renderer/core/dom/idle_request_options.h"
#include "third_party/blink/renderer/core/dom/range.h"
-#include "third_party/blink/renderer/core/dom/scripted_idle_task_controller.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/finder/find_in_page_coordinates.h"
#include "third_party/blink/renderer/core/editing/finder/find_options.h"
+#include "third_party/blink/renderer/core/editing/finder/find_task_controller.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/iterators/search_buffer.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
@@ -66,11 +64,6 @@
namespace blink {
-namespace {
-const int kScopingTimeoutMS = 100;
-constexpr TimeDelta kTextFinderTestTimeout = TimeDelta::FromSeconds(10);
-}
-
TextFinder::FindMatch::FindMatch(Range* range, int ordinal)
: range_(range), ordinal_(ordinal) {}
@@ -78,65 +71,6 @@ void TextFinder::FindMatch::Trace(blink::Visitor* visitor) {
visitor->Trace(range_);
}
-class TextFinder::IdleScopeStringMatchesCallback
- : public ScriptedIdleTaskController::IdleTask {
- public:
- static IdleScopeStringMatchesCallback* Create(
- TextFinder* text_finder,
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions& options) {
- return new IdleScopeStringMatchesCallback(text_finder, identifier,
- search_text, options);
- }
-
- void Dispose() {
- DCHECK_GT(callback_handle_, 0);
- if (!text_finder_->GetFrame())
- return;
- Document* document = text_finder_->GetFrame()->GetDocument();
- if (!document)
- return;
- document->CancelIdleCallback(callback_handle_);
- }
-
- void Trace(blink::Visitor* visitor) override {
- visitor->Trace(text_finder_);
- ScriptedIdleTaskController::IdleTask::Trace(visitor);
- }
-
- private:
- IdleScopeStringMatchesCallback(TextFinder* text_finder,
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions& options)
- : text_finder_(text_finder),
- identifier_(identifier),
- search_text_(search_text),
- options_(options.Clone()) {
- // We need to add deadline because some webpages might have frames
- // that are always busy, resulting in bad experience in find-in-page
- // because the scoping tasks are not run.
- // See crbug.com/893465.
- IdleRequestOptions request_options;
- request_options.setTimeout(kScopingTimeoutMS);
- callback_handle_ =
- text_finder->GetFrame()->GetDocument()->RequestIdleCallback(
- this, request_options);
- }
-
- void invoke(IdleDeadline* deadline) override {
- text_finder_->ResumeScopingStringMatches(deadline, identifier_,
- search_text_, *options_);
- }
-
- Member<TextFinder> text_finder_;
- int callback_handle_ = 0;
- const int identifier_;
- const WebString search_text_;
- mojom::blink::FindOptionsPtr options_;
-};
-
static void ScrollToVisible(Range* match) {
const Node& first_node = *match->FirstNode();
Settings* settings = first_node.GetDocument().GetSettings();
@@ -200,6 +134,8 @@ bool TextFinder::Find(int identifier,
EphemeralRangeInFlatTree(active_match_.Get()), find_options);
if (!active_match_) {
+ if (current_active_match_frame_ && !options.find_next)
+ should_locate_active_rect_ = true;
// If we're finding next the next active match might not be in the current
// frame. In this case we don't want to clear the matches cache.
if (!options.find_next)
@@ -249,17 +185,17 @@ bool TextFinder::Find(int identifier,
if (options.forward)
active_match_index_ = 0;
else
- active_match_index_ = last_match_count_ - 1;
+ active_match_index_ = find_task_controller_->CurrentMatchCount() - 1;
} else {
if (options.forward)
++active_match_index_;
else
--active_match_index_;
- if (active_match_index_ + 1 > last_match_count_)
+ if (active_match_index_ + 1 > find_task_controller_->CurrentMatchCount())
active_match_index_ = 0;
else if (active_match_index_ < 0)
- active_match_index_ = last_match_count_ - 1;
+ active_match_index_ = find_task_controller_->CurrentMatchCount() - 1;
}
WebRect selection_rect = OwnerFrame().GetFrameView()->ConvertToRootFrame(
active_match_->BoundingBox());
@@ -424,8 +360,7 @@ void TextFinder::StartScopingStringMatches(
// Clear the total match count and increment markers version.
ResetMatchCount();
- // Clear the counters from last operation.
- last_match_count_ = 0;
+ // Clear the counter from last operation.
next_invalidate_after_ = 0;
// The view might be null on detached frames.
@@ -433,93 +368,39 @@ void TextFinder::StartScopingStringMatches(
if (frame && frame->GetPage())
frame_scoping_ = true;
- // Now, defer scoping until later to allow find operation to finish quickly.
- ScopeStringMatchesSoon(identifier, search_text, options);
+ find_task_controller_->StartRequest(identifier, search_text, options);
}
-void TextFinder::ScopeStringMatches(IdleDeadline* deadline,
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions& options) {
- if (!ShouldScopeMatches(search_text, options)) {
- FinishCurrentScopingEffort(identifier);
+void TextFinder::FlushCurrentScopingEffort(int identifier) {
+ if (!OwnerFrame().GetFrame() || !OwnerFrame().GetFrame()->GetPage())
return;
- }
- const TimeDelta time_available =
- TimeDelta::FromMillisecondsD(deadline->timeRemaining());
- const TimeTicks start_time = CurrentTimeTicks();
- PositionInFlatTree search_start = PositionInFlatTree::FirstPositionInNode(
- *OwnerFrame().GetFrame()->GetDocument());
- PositionInFlatTree search_end = PositionInFlatTree::LastPositionInNode(
- *OwnerFrame().GetFrame()->GetDocument());
- DCHECK_EQ(search_start.GetDocument(), search_end.GetDocument());
-
- if (resume_scoping_from_range_) {
- // This is a continuation of a scoping operation that timed out and didn't
- // complete last time around, so we should start from where we left off.
- DCHECK(resume_scoping_from_range_->collapsed());
- search_start = FromPositionInDOMTree<EditingInFlatTreeStrategy>(
- resume_scoping_from_range_->EndPosition());
- if (search_start.GetDocument() != search_end.GetDocument())
- return;
- }
-
- // TODO(editing-dev): Use of updateStyleAndLayoutIgnorePendingStylesheets
- // needs to be audited. see http://crbug.com/590369 for more details.
- search_start.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
-
- int match_count = 0;
- bool full_range_searched = false;
- PositionInFlatTree next_scoping_start;
- do {
- // Find next occurrence of the search string.
- // FIXME: (http://crbug.com/6818) This WebKit operation may run for longer
- // than the timeout value, and is not interruptible as it is currently
- // written. We may need to rewrite it with interruptibility in mind, or
- // find an alternative.
- const EphemeralRangeInFlatTree result =
- FindPlainText(EphemeralRangeInFlatTree(search_start, search_end),
- search_text, options.match_case ? 0 : kCaseInsensitive);
- if (result.IsCollapsed()) {
- // Not found.
- full_range_searched = true;
- break;
- }
- Range* result_range = Range::Create(
- result.GetDocument(), ToPositionInDOMTree(result.StartPosition()),
- ToPositionInDOMTree(result.EndPosition()));
- if (result_range->collapsed()) {
- // resultRange will be collapsed if the matched text spans over multiple
- // TreeScopes. FIXME: Show such matches to users.
- search_start = result.EndPosition();
- if (deadline->timeRemaining() > 0)
- continue;
- break;
- }
- ++match_count;
+ frame_scoping_ = false;
+ IncreaseMatchCount(identifier, 0);
+}
- // Catch a special case where Find found something but doesn't know what
- // the bounding box for it is. In this case we set the first match we find
- // as the active rect.
+void TextFinder::DidFindMatch(int identifier,
+ int current_total_matches,
+ Range* result_range) {
+ // Catch a special case where Find found something but doesn't know what
+ // the bounding box for it is. In this case we set the first match we find
+ // as the active rect.
+ bool found_active_match = false;
+ if (should_locate_active_rect_) {
IntRect result_bounds = result_range->BoundingBox();
- IntRect active_selection_rect;
- if (should_locate_active_rect_) {
- active_selection_rect =
- active_match_.Get() ? active_match_->BoundingBox() : result_bounds;
- }
+ IntRect active_selection_rect =
+ active_match_.Get() ? active_match_->BoundingBox() : result_bounds;
// If the Find function found a match it will have stored where the
// match was found in active_selection_rect_ on the current frame. If we
// find this rect during scoping it means we have found the active
// tickmark.
- bool found_active_match = false;
- if (should_locate_active_rect_ && active_selection_rect == result_bounds) {
+ if (active_selection_rect == result_bounds) {
// We have found the active tickmark frame.
current_active_match_frame_ = true;
found_active_match = true;
// We also know which tickmark is active now.
- active_match_index_ = total_match_count_ + match_count - 1;
+ active_match_index_ = current_total_matches - 1;
// To stop looking for the active tickmark, we set this flag.
should_locate_active_rect_ = false;
@@ -528,70 +409,28 @@ void TextFinder::ScopeStringMatches(IdleDeadline* deadline,
OwnerFrame().GetFrameView()->ConvertToRootFrame(result_bounds),
active_match_index_ + 1, identifier);
}
-
- OwnerFrame().GetFrame()->GetDocument()->Markers().AddTextMatchMarker(
- EphemeralRange(result_range),
- found_active_match ? TextMatchMarker::MatchStatus::kActive
- : TextMatchMarker::MatchStatus::kInactive);
-
- find_matches_cache_.push_back(
- FindMatch(result_range, last_match_count_ + match_count));
-
- // Set the new start for the search range to be the end of the previous
- // result range. There is no need to use a VisiblePosition here,
- // since findPlainText will use a TextIterator to go over the visible
- // text nodes.
- search_start = result.EndPosition();
-
- next_scoping_start = search_start;
- } while (deadline->timeRemaining() > 0);
-
- const TimeDelta time_spent = CurrentTimeTicks() - start_time;
- UMA_HISTOGRAM_TIMES("WebCore.FindInPage.ScopingTime",
- time_spent - time_available);
-
- if (next_scoping_start.IsNotNull()) {
- resume_scoping_from_range_ =
- Range::Create(*next_scoping_start.GetDocument(),
- ToPositionInDOMTree(next_scoping_start),
- ToPositionInDOMTree(next_scoping_start));
- }
-
- // Remember what we search for last time, so we can skip searching if more
- // letters are added to the search string (and last outcome was 0).
- last_search_string_ = search_text;
-
- if (match_count > 0) {
- OwnerFrame().GetFrame()->GetEditor().SetMarkedTextMatchesAreHighlighted(
- true);
-
- last_match_count_ += match_count;
-
- // Let the frame know how many matches we found during this pass.
- IncreaseMatchCount(identifier, match_count);
}
+ OwnerFrame().GetFrame()->GetDocument()->Markers().AddTextMatchMarker(
+ EphemeralRange(result_range),
+ found_active_match ? TextMatchMarker::MatchStatus::kActive
+ : TextMatchMarker::MatchStatus::kInactive);
- if (!full_range_searched) {
- // If we found anything during this pass, we should redraw. However, we
- // don't want to spam too much if the page is extremely long, so if we
- // reach a certain point we start throttling the redraw requests.
- if (match_count > 0)
- InvalidateIfNecessary();
-
- // Scoping effort ran out of time, lets ask for another time-slice.
- ScopeStringMatchesSoon(identifier, search_text, options);
- return; // Done for now, resume work later.
- }
-
- FinishCurrentScopingEffort(identifier);
+ find_matches_cache_.push_back(FindMatch(result_range, current_total_matches));
}
-void TextFinder::FlushCurrentScopingEffort(int identifier) {
- if (!OwnerFrame().GetFrame() || !OwnerFrame().GetFrame()->GetPage())
- return;
+void TextFinder::UpdateMatches(int identifier,
+ int found_match_count,
+ bool finished_whole_request) {
+ GetFrame()->GetEditor().SetMarkedTextMatchesAreHighlighted(true);
- frame_scoping_ = false;
- IncreaseMatchCount(identifier, 0);
+ // Let the frame know how many matches we found during this pass.
+ IncreaseMatchCount(identifier, found_match_count);
+
+ // If we found anything during this pass, we should redraw. However, we
+ // don't want to spam too much if the page is extremely long, so if we
+ // reach a certain point we start throttling the redraw requests.
+ if (!finished_whole_request)
+ InvalidateIfNecessary();
}
void TextFinder::FinishCurrentScopingEffort(int identifier) {
@@ -599,29 +438,15 @@ void TextFinder::FinishCurrentScopingEffort(int identifier) {
OwnerFrame().GetFrame()->Selection().Clear();
FlushCurrentScopingEffort(identifier);
-
scoping_in_progress_ = false;
- last_find_request_completed_with_no_matches_ = !last_match_count_;
-
// This frame is done, so show any scrollbar tickmarks we haven't drawn yet.
InvalidatePaintForTickmarks();
}
void TextFinder::CancelPendingScopingEffort() {
- if (idle_scoping_callback_) {
- idle_scoping_callback_->Dispose();
- idle_scoping_callback_.Clear();
- }
-
active_match_index_ = -1;
-
- // Last request didn't complete.
- if (scoping_in_progress_)
- last_find_request_completed_with_no_matches_ = false;
-
scoping_in_progress_ = false;
-
- resume_scoping_from_range_ = nullptr;
+ find_task_controller_->CancelPendingRequest();
}
void TextFinder::IncreaseMatchCount(int identifier, int count) {
@@ -820,15 +645,14 @@ int TextFinder::SelectFindMatch(unsigned index, WebRect* selection_rect) {
}
TextFinder* TextFinder::Create(WebLocalFrameImpl& owner_frame) {
- return new TextFinder(owner_frame);
+ return MakeGarbageCollected<TextFinder>(owner_frame);
}
TextFinder::TextFinder(WebLocalFrameImpl& owner_frame)
: owner_frame_(&owner_frame),
+ find_task_controller_(FindTaskController::Create(owner_frame, *this)),
current_active_match_frame_(false),
active_match_index_(-1),
- resume_scoping_from_range_(nullptr),
- last_match_count_(-1),
total_match_count_(-1),
frame_scoping_(false),
find_request_identifier_(-1),
@@ -860,70 +684,8 @@ void TextFinder::UnmarkAllTextMatches() {
}
}
-bool TextFinder::ShouldScopeMatches(const String& search_text,
- const mojom::blink::FindOptions& options) {
- // Don't scope if we can't find a frame or a view.
- // The user may have closed the tab/application, so abort.
- LocalFrame* frame = OwnerFrame().GetFrame();
- if (!frame || !frame->View() || !frame->GetPage())
- return false;
-
- DCHECK(frame->GetDocument());
- DCHECK(frame->View());
-
- if (options.force)
- return true;
-
- if (!OwnerFrame().HasVisibleContent())
- return false;
-
- // If the frame completed the scoping operation and found 0 matches the last
- // time it was searched, then we don't have to search it again if the user is
- // just adding to the search string or sending the same search string again.
- if (last_find_request_completed_with_no_matches_ &&
- !last_search_string_.IsEmpty()) {
- // Check to see if the search string prefixes match.
- String previous_search_prefix =
- search_text.Substring(0, last_search_string_.length());
-
- if (previous_search_prefix == last_search_string_)
- return false; // Don't search this frame, it will be fruitless.
- }
-
- return true;
-}
-
-void TextFinder::ScopeStringMatchesSoon(
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions& options) {
- DCHECK_EQ(idle_scoping_callback_, nullptr);
- // If it's for testing, run the scoping immediately.
- // TODO(rakina): Change to use general solution when it's available.
- // https://crbug.com/875203
- if (options.run_synchronously_for_testing) {
- ScopeStringMatches(
- IdleDeadline::Create(CurrentTimeTicks() + kTextFinderTestTimeout,
- IdleDeadline::CallbackType::kCalledWhenIdle),
- identifier, search_text, options);
- } else {
- idle_scoping_callback_ = IdleScopeStringMatchesCallback::Create(
- this, identifier, search_text, options);
- }
-}
-
-void TextFinder::ResumeScopingStringMatches(
- IdleDeadline* deadline,
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions& options) {
- idle_scoping_callback_.Clear();
-
- ScopeStringMatches(deadline, identifier, search_text, options);
-}
-
void TextFinder::InvalidateIfNecessary() {
- if (last_match_count_ <= next_invalidate_after_)
+ if (find_task_controller_->CurrentMatchCount() <= next_invalidate_after_)
return;
// FIXME: (http://crbug.com/6819) Optimize the drawing of the tickmarks and
@@ -936,7 +698,7 @@ void TextFinder::InvalidateIfNecessary() {
static const int kStartSlowingDownAfter = 500;
static const int kSlowdown = 750;
- int i = last_match_count_ / kStartSlowingDownAfter;
+ int i = find_task_controller_->CurrentMatchCount() / kStartSlowingDownAfter;
next_invalidate_after_ += i * kSlowdown;
InvalidatePaintForTickmarks();
}
@@ -951,9 +713,8 @@ void TextFinder::InvalidatePaintForTickmarks() {
void TextFinder::Trace(blink::Visitor* visitor) {
visitor->Trace(owner_frame_);
+ visitor->Trace(find_task_controller_);
visitor->Trace(active_match_);
- visitor->Trace(resume_scoping_from_range_);
- visitor->Trace(idle_scoping_callback_);
visitor->Trace(find_matches_cache_);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/finder/text_finder.h b/chromium/third_party/blink/renderer/core/editing/finder/text_finder.h
index ee13bee792e..3c3b9ab0001 100644
--- a/chromium/third_party/blink/renderer/core/editing/finder/text_finder.h
+++ b/chromium/third_party/blink/renderer/core/editing/finder/text_finder.h
@@ -42,7 +42,7 @@
namespace blink {
-class IdleDeadline;
+class FindTaskController;
class LocalFrame;
class Range;
class WebLocalFrameImpl;
@@ -98,6 +98,12 @@ class CORE_EXPORT TextFinder final
void FlushCurrentScoping();
+ // A match has been found by the current finding effort, so we should
+ // update the marker for that match and push it to our cache.
+ void DidFindMatch(int identifier,
+ int current_total_matches,
+ Range* result_range);
+
void ResetActiveMatch() { active_match_ = nullptr; }
bool FrameScoping() const { return frame_scoping_; }
@@ -105,6 +111,17 @@ class CORE_EXPORT TextFinder final
bool ScopingInProgress() const { return scoping_in_progress_; }
void IncreaseMarkerVersion() { ++find_match_markers_version_; }
+ // Finishes the current scoping effort and triggers any updates if
+ // appropriate.
+ void FinishCurrentScopingEffort(int identifier);
+
+ // A finding effort finished one run of scoping and found some matches,
+ // so we should update markers, match count, etc.
+ void UpdateMatches(int identifier,
+ int found_match_count,
+ bool finished_whole_request);
+
+ explicit TextFinder(WebLocalFrameImpl& owner_frame);
~TextFinder();
class FindMatch {
@@ -128,11 +145,6 @@ class CORE_EXPORT TextFinder final
void Trace(blink::Visitor*);
private:
- class IdleScopeStringMatchesCallback;
- friend class IdleScopeStringMatchesCallback;
-
- explicit TextFinder(WebLocalFrameImpl& owner_frame);
-
// Notifies the delegate about a new selection rect.
void ReportFindInPageSelection(const WebRect& selection_rect,
int active_match_ordinal,
@@ -161,47 +173,11 @@ class CORE_EXPORT TextFinder final
// Removes all markers.
void UnmarkAllTextMatches();
- // Determines whether the scoping effort is required for a particular frame.
- // It is not necessary if the frame is invisible, for example, or if this
- // is a repeat search that already returned nothing last time the same prefix
- // was searched.
- bool ShouldScopeMatches(const WTF::String& search_text,
- const mojom::blink::FindOptions&);
-
// Removes the current frame from the global scoping effort and triggers any
// updates if appropriate. This method does not mark the scoping operation
// as finished.
void FlushCurrentScopingEffort(int identifier);
- // Finishes the current scoping effort and triggers any updates if
- // appropriate.
- void FinishCurrentScopingEffort(int identifier);
-
- // Counts how many times a particular string occurs within the frame. It
- // also retrieves the location of the string and updates a vector in the
- // frame so that tick-marks and highlighting can be drawn. This function
- // does its work asynchronously, by running for a certain time-slice and
- // then scheduling itself (co-operative multitasking) to be invoked later
- // (repeating the process until all matches have been found). This allows
- // multiple frames to be searched at the same time and provides a way to
- // cancel at any time (see cancelPendingScopingEffort). The parameter
- // searchText specifies what to look for.
- void ScopeStringMatches(IdleDeadline* deadline,
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions&);
-
- // Queue up a deferred call to scopeStringMatches.
- void ScopeStringMatchesSoon(int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions&);
-
- // Called by an IdleScopeStringMatchesCallback instance.
- void ResumeScopingStringMatches(IdleDeadline* deadline,
- int identifier,
- const WebString& search_text,
- const mojom::blink::FindOptions&);
-
// Determines whether to invalidate the content area and scrollbar.
void InvalidateIfNecessary();
@@ -218,6 +194,8 @@ class CORE_EXPORT TextFinder final
Member<WebLocalFrameImpl> owner_frame_;
+ Member<FindTaskController> find_task_controller_;
+
// Indicates whether this frame currently has the active match.
bool current_active_match_frame_;
@@ -227,25 +205,6 @@ class CORE_EXPORT TextFinder final
// The index of the active match for the current frame.
int active_match_index_;
- // The scoping effort can time out and we need to keep track of where we
- // ended our last search so we can continue from where we left of.
- //
- // This range is collapsed to the end position of the last successful
- // search; the new search should start from this position.
- Member<Range> resume_scoping_from_range_;
-
- // Keeps track of the last string this frame searched for. This is used for
- // short-circuiting searches in the following scenarios: When a frame has
- // been searched and returned 0 results, we don't need to search that frame
- // again if the user is just adding to the search (making it more specific).
- WTF::String last_search_string_;
-
- // Keeps track of how many matches this frame has found so far, so that we
- // don't lose count between scoping efforts, and is also used (in conjunction
- // with last_search_string_) to figure out if we need to search the frame
- // again.
- int last_match_count_;
-
// This variable keeps a cumulative total of matches found so far in this
// frame, and is only incremented by calling IncreaseMatchCount.
int total_match_count_;
@@ -262,9 +221,6 @@ class CORE_EXPORT TextFinder final
// and the frame area.
int next_invalidate_after_;
- // Pending call to scopeStringMatches.
- Member<IdleScopeStringMatchesCallback> idle_scoping_callback_;
-
// Version number incremented whenever this frame's find-in-page match
// markers change.
int find_match_markers_version_;
diff --git a/chromium/third_party/blink/renderer/core/editing/finder/text_finder_test.cc b/chromium/third_party/blink/renderer/core/editing/finder/text_finder_test.cc
index db536170c49..824e3109cbc 100644
--- a/chromium/third_party/blink/renderer/core/editing/finder/text_finder_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/finder/text_finder_test.cc
@@ -35,7 +35,8 @@ class TextFinderTest : public testing::Test {
web_view_helper_.Initialize();
WebLocalFrameImpl& frame_impl = *web_view_helper_.LocalMainFrame();
frame_impl.ViewImpl()->Resize(WebSize(640, 480));
- frame_impl.ViewImpl()->UpdateAllLifecyclePhases();
+ frame_impl.ViewImpl()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
document_ = static_cast<Document*>(frame_impl.GetDocument());
text_finder_ = &frame_impl.EnsureTextFinder();
}
@@ -49,7 +50,7 @@ class TextFinderTest : public testing::Test {
int end_offset);
private:
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
Persistent<Document> document_;
Persistent<TextFinder> text_finder_;
};
@@ -329,7 +330,7 @@ TEST_F(TextFinderTest, ScopeTextMatchesSimple) {
// Modify the document size and ensure the cached match rects are recomputed
// to reflect the updated layout.
- GetDocument().body()->setAttribute(HTMLNames::styleAttr, "margin: 2000px");
+ GetDocument().body()->setAttribute(html_names::kStyleAttr, "margin: 2000px");
GetDocument().UpdateStyleAndLayout();
match_rects = GetTextFinder().FindMatchRects();
diff --git a/chromium/third_party/blink/renderer/core/editing/frame_caret.cc b/chromium/third_party/blink/renderer/core/editing/frame_caret.cc
index 0c6d9fb8b54..95cce009cde 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_caret.cc
+++ b/chromium/third_party/blink/renderer/core/editing/frame_caret.cc
@@ -181,9 +181,7 @@ IntRect FrameCaret::AbsoluteCaretBounds() const {
if (!IsActive())
return AbsoluteBoundsForLocalRect(caret_node, LayoutRect());
return AbsoluteBoundsForLocalRect(
- caret_node,
- CaretDisplayItemClient::ComputeCaretRect(
- CreateVisiblePosition(CaretPosition()).ToPositionWithAffinity()));
+ caret_node, CaretDisplayItemClient::ComputeCaretRect(CaretPosition()));
}
void FrameCaret::SetShouldShowBlockCursor(bool should_show_block_cursor) {
diff --git a/chromium/third_party/blink/renderer/core/editing/frame_caret_test.cc b/chromium/third_party/blink/renderer/core/editing/frame_caret_test.cc
index 26394e58b62..44f12350d35 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_caret_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/frame_caret_test.cc
@@ -11,21 +11,21 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/scheduler/test/fake_task_runner.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
class FrameCaretTest : public EditingTestBase {
public:
FrameCaretTest()
- : was_running_layout_test_(LayoutTestSupport::IsRunningLayoutTest()) {
- // The caret blink timer doesn't work if isRunningLayoutTest() because
- // LayoutTheme::caretBlinkInterval() returns 0.
- LayoutTestSupport::SetIsRunningLayoutTest(false);
+ : was_running_layout_test_(WebTestSupport::IsRunningWebTest()) {
+ // The caret blink timer doesn't work if IsRunningWebTest() because
+ // LayoutTheme::CaretBlinkInterval() returns 0.
+ WebTestSupport::SetIsRunningWebTest(false);
}
~FrameCaretTest() override {
- LayoutTestSupport::SetIsRunningLayoutTest(was_running_layout_test_);
+ WebTestSupport::SetIsRunningWebTest(was_running_layout_test_);
}
static bool ShouldBlinkCaret(const FrameCaret& caret) {
@@ -50,7 +50,7 @@ TEST_F(FrameCaretTest, BlinkAfterTyping) {
GetDocument().body()->SetInnerHTMLFromString("<textarea>");
Element* editor = ToElement(GetDocument().body()->firstChild());
editor->focus();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(caret.IsActive());
EXPECT_FALSE(caret.ShouldShowBlockCursor());
@@ -62,17 +62,17 @@ TEST_F(FrameCaretTest, BlinkAfterTyping) {
<< "The caret blinks normally.";
TypingCommand::InsertLineBreak(GetDocument());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(caret.ShouldPaintCaretForTesting())
<< "The caret should be in visible cycle just after a typing command.";
task_runner->AdvanceTimeAndRun(kInterval - 1);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(caret.ShouldPaintCaretForTesting())
<< "The typing command reset the timer. The caret is still visible.";
task_runner->AdvanceTimeAndRun(1);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(caret.ShouldPaintCaretForTesting())
<< "The caret should blink after the typing command.";
}
@@ -89,7 +89,7 @@ TEST_F(FrameCaretTest, ShouldNotBlinkWhenSelectionLooseFocus) {
input->focus();
Element* outer = GetDocument().QuerySelector("#outer");
outer->focus();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const SelectionInDOMTree& selection = Selection().GetSelectionInDOMTree();
EXPECT_EQ(selection.Base(),
Position(input, PositionAnchorType::kBeforeChildren));
diff --git a/chromium/third_party/blink/renderer/core/editing/frame_selection.cc b/chromium/third_party/blink/renderer/core/editing/frame_selection.cc
index 78d2e31388c..3bb14d783cb 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/frame_selection.cc
@@ -90,8 +90,6 @@
namespace blink {
-using namespace HTMLNames;
-
static inline bool ShouldAlwaysUseDirectionalSelection(LocalFrame* frame) {
return frame->GetEditor().Behavior().ShouldConsiderSelectionAsDirectional();
}
@@ -105,7 +103,8 @@ FrameSelection::FrameSelection(LocalFrame& frame)
focused_(frame.GetPage() &&
frame.GetPage()->GetFocusController().FocusedFrame() == frame),
is_directional_(ShouldAlwaysUseDirectionalSelection(frame_)),
- frame_caret_(new FrameCaret(frame, *selection_editor_)) {}
+ frame_caret_(
+ MakeGarbageCollected<FrameCaret>(frame, *selection_editor_)) {}
FrameSelection::~FrameSelection() = default;
@@ -167,8 +166,8 @@ void FrameSelection::MoveCaretSelection(const IntPoint& point) {
if (!editable)
return;
- const VisiblePosition position =
- VisiblePositionForContentsPoint(point, GetFrame());
+ const VisiblePosition position = CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(point, GetFrame()));
SelectionInDOMTree::Builder builder;
if (position.IsNotNull())
builder.Collapse(position.ToPositionWithAffinity());
@@ -195,6 +194,19 @@ void FrameSelection::SetSelectionAndEndTyping(
.Build());
}
+static void AssertUserSelection(const SelectionInDOMTree& selection,
+ const SetSelectionOptions& options) {
+// User's selection start/end should have same editability.
+#if DCHECK_IS_ON()
+ if (!options.ShouldShowHandle() &&
+ options.GetSetSelectionBy() != SetSelectionBy::kUser)
+ return;
+ Node* base_editable_root = RootEditableElementOf(selection.Base());
+ Node* extent_editable_root = RootEditableElementOf(selection.Extent());
+ DCHECK_EQ(base_editable_root, extent_editable_root) << selection;
+#endif
+}
+
bool FrameSelection::SetSelectionDeprecated(
const SelectionInDOMTree& new_selection,
const SetSelectionOptions& passed_options) {
@@ -202,7 +214,7 @@ bool FrameSelection::SetSelectionDeprecated(
if (ShouldAlwaysUseDirectionalSelection(frame_)) {
options_builder.SetIsDirectional(true);
}
- SetSelectionOptions options = options_builder.Build();
+ const SetSelectionOptions options = options_builder.Build();
if (granularity_strategy_ && !options.DoNotClearStrategy())
granularity_strategy_->Clear();
@@ -223,8 +235,10 @@ bool FrameSelection::SetSelectionDeprecated(
if (!is_changed && is_handle_visible_ == should_show_handle &&
is_directional_ == options.IsDirectional())
return false;
- if (is_changed)
+ if (is_changed) {
+ AssertUserSelection(new_selection, options);
selection_editor_->SetSelectionAndEndTyping(new_selection);
+ }
is_directional_ = options.IsDirectional();
should_shrink_next_tap_ = options.ShouldShrinkNextTap();
is_handle_visible_ = should_show_handle;
@@ -295,7 +309,7 @@ void FrameSelection::DidSetSelectionDeprecated(
// The task source should be kDOMManipulation, but the spec doesn't say
// anything about this.
frame_->DomWindow()->EnqueueDocumentEvent(
- *Event::Create(EventTypeNames::selectionchange),
+ *Event::Create(event_type_names::kSelectionchange),
TaskType::kMiscPlatformAPI);
}
@@ -334,7 +348,7 @@ static DispatchEventResult DispatchSelectStart(
return DispatchEventResult::kNotCanceled;
return select_start_target->DispatchEvent(
- *Event::CreateCancelableBubble(EventTypeNames::selectstart));
+ *Event::CreateCancelableBubble(event_type_names::kSelectstart));
}
// The return value of |FrameSelection::modify()| is different based on
@@ -471,9 +485,9 @@ bool FrameSelection::IsHidden() const {
return EnclosingTextControl(start);
}
-void FrameSelection::DocumentAttached(Document* document) {
+void FrameSelection::DidAttachDocument(Document* document) {
DCHECK(document);
- selection_editor_->DocumentAttached(document);
+ selection_editor_->DidAttachDocument(document);
SetContext(document);
}
@@ -580,11 +594,10 @@ bool FrameSelection::Contains(const LayoutPoint& point) {
if (!inner_node || !inner_node->GetLayoutObject())
return false;
- const VisiblePositionInFlatTree& visible_pos =
- CreateVisiblePosition(FromPositionInDOMTree<EditingInFlatTreeStrategy>(
- inner_node->GetLayoutObject()->PositionForPoint(
- result.LocalPoint())));
- if (visible_pos.IsNull())
+ const PositionInFlatTreeWithAffinity pos_with_affinity =
+ FromPositionInDOMTree<EditingInFlatTreeStrategy>(
+ inner_node->GetLayoutObject()->PositionForPoint(result.LocalPoint()));
+ if (pos_with_affinity.IsNull())
return false;
const VisiblePositionInFlatTree& visible_start =
@@ -595,7 +608,7 @@ bool FrameSelection::Contains(const LayoutPoint& point) {
const PositionInFlatTree& start = visible_start.DeepEquivalent();
const PositionInFlatTree& end = visible_end.DeepEquivalent();
- const PositionInFlatTree& pos = visible_pos.DeepEquivalent();
+ const PositionInFlatTree& pos = pos_with_affinity.GetPosition();
return start.CompareTo(pos) <= 0 && pos.CompareTo(end) <= 0;
}
@@ -653,33 +666,19 @@ void FrameSelection::SelectFrameElementInParentIfFullySelected() {
if (!blink::HasEditableStyle(*owner_element_parent))
return;
- // Create compute positions before and after the element.
- unsigned owner_element_node_index = owner_element->NodeIndex();
- VisiblePosition before_owner_element = CreateVisiblePosition(
- Position(owner_element_parent, owner_element_node_index));
- VisiblePosition after_owner_element = CreateVisiblePosition(
- Position(owner_element_parent, owner_element_node_index + 1),
- TextAffinity::kUpstreamIfPossible);
-
- SelectionInDOMTree::Builder builder;
- builder
- .SetBaseAndExtentDeprecated(before_owner_element.DeepEquivalent(),
- after_owner_element.DeepEquivalent())
- .SetAffinity(before_owner_element.Affinity());
-
// Focus on the parent frame, and then select from before this element to
// after.
- VisibleSelection new_selection = CreateVisibleSelection(builder.Build());
- // TODO(yosin): We should call |FocusController::setFocusedFrame()| before
- // |createVisibleSelection()|.
page->GetFocusController().SetFocusedFrame(parent);
- // setFocusedFrame can dispatch synchronous focus/blur events. The document
+ // SetFocusedFrame can dispatch synchronous focus/blur events. The document
// tree might be modified.
- if (!new_selection.IsNone() &&
- new_selection.IsValidFor(*(ToLocalFrame(parent)->GetDocument()))) {
- ToLocalFrame(parent)->Selection().SetSelectionAndEndTyping(
- new_selection.AsSelection());
- }
+ if (!owner_element->isConnected() ||
+ owner_element->GetDocument() != ToLocalFrame(parent)->GetDocument())
+ return;
+ ToLocalFrame(parent)->Selection().SetSelectionAndEndTyping(
+ SelectionInDOMTree::Builder()
+ .SetBaseAndExtent(Position::BeforeNode(*owner_element),
+ Position::AfterNode(*owner_element))
+ .Build());
}
// Returns a shadow tree node for legacy shadow trees, a child of the
@@ -728,8 +727,9 @@ void FrameSelection::SelectAll(SetSelectionBy set_selection_by) {
if (select_start_target) {
const Document& expected_document = GetDocument();
- if (select_start_target->DispatchEvent(*Event::CreateCancelableBubble(
- EventTypeNames::selectstart)) != DispatchEventResult::kNotCanceled)
+ if (select_start_target->DispatchEvent(
+ *Event::CreateCancelableBubble(event_type_names::kSelectstart)) !=
+ DispatchEventResult::kNotCanceled)
return;
// The frame may be detached due to selectstart event.
if (!IsAvailable()) {
@@ -953,6 +953,7 @@ String FrameSelection::SelectedTextForClipboard() const {
frame_->GetSettings() &&
frame_->GetSettings()->GetSelectionIncludesAltImageText())
.SetSkipsUnselectableContent(true)
+ .SetEntersTextControls(true)
.Build());
}
@@ -973,8 +974,10 @@ IntRect FrameSelection::ComputeRectToScroll(
if (selection.IsCaret())
return AbsoluteCaretBounds();
DCHECK(selection.IsRange());
- if (reveal_extent_option == kRevealExtent)
- return AbsoluteCaretBoundsOf(CreateVisiblePosition(selection.Extent()));
+ if (reveal_extent_option == kRevealExtent) {
+ return AbsoluteCaretBoundsOf(
+ CreateVisiblePosition(selection.Extent()).ToPositionWithAffinity());
+ }
layout_selection_->SetHasPendingSelection();
return layout_selection_->AbsoluteSelectionBounds();
}
@@ -1084,33 +1087,34 @@ bool FrameSelection::SelectWordAroundCaret() {
// http://crbug.com/657237 for more details.
if (!selection.IsCaret())
return false;
- const VisiblePosition& position = selection.VisibleStart();
+ const Position position = selection.Start();
static const EWordSide kWordSideList[2] = {kNextWordIfOnBoundary,
kPreviousWordIfOnBoundary};
for (EWordSide word_side : kWordSideList) {
- // TODO(yoichio): We should have Position version of |start/endOfWord|
- // for avoiding unnecessary canonicalization.
- VisiblePosition start = StartOfWord(position, word_side);
- VisiblePosition end = EndOfWord(position, word_side);
+ Position start = StartOfWordPosition(position, word_side);
+ Position end = EndOfWordPosition(position, word_side);
// TODO(editing-dev): |StartOfWord()| and |EndOfWord()| should not make null
// for non-null parameter.
// See http://crbug.com/872443
- if (start.DeepEquivalent().IsNull() || end.DeepEquivalent().IsNull())
+ if (start.IsNull() || end.IsNull())
continue;
- String text =
- PlainText(EphemeralRange(start.DeepEquivalent(), end.DeepEquivalent()));
+ if (start > end) {
+ // Since word boundaries are computed on flat tree, they can be reversed
+ // when mapped back to DOM.
+ std::swap(start, end);
+ }
+
+ String text = PlainText(EphemeralRange(start, end));
if (!text.IsEmpty() && !IsSeparator(text.CharacterStartingAt(0))) {
- SetSelection(SelectionInDOMTree::Builder()
- .Collapse(start.ToPositionWithAffinity())
- .Extend(end.DeepEquivalent())
- .Build(),
- SetSelectionOptions::Builder()
- .SetShouldCloseTyping(true)
- .SetShouldClearTypingStyle(true)
- .SetGranularity(TextGranularity::kWord)
- .Build());
+ SetSelection(
+ SelectionInDOMTree::Builder().Collapse(start).Extend(end).Build(),
+ SetSelectionOptions::Builder()
+ .SetShouldCloseTyping(true)
+ .SetShouldClearTypingStyle(true)
+ .SetGranularity(TextGranularity::kWord)
+ .Build());
return true;
}
}
@@ -1160,9 +1164,11 @@ void FrameSelection::MoveRangeSelection(const IntPoint& base_point,
const IntPoint& extent_point,
TextGranularity granularity) {
const VisiblePosition& base_position =
- VisiblePositionForContentsPoint(base_point, GetFrame());
+ CreateVisiblePosition(PositionForContentsPointRespectingEditingBoundary(
+ base_point, GetFrame()));
const VisiblePosition& extent_position =
- VisiblePositionForContentsPoint(extent_point, GetFrame());
+ CreateVisiblePosition(PositionForContentsPointRespectingEditingBoundary(
+ extent_point, GetFrame()));
MoveRangeSelectionInternal(
SelectionInDOMTree::Builder()
.SetBaseAndExtentDeprecated(base_position.DeepEquivalent(),
diff --git a/chromium/third_party/blink/renderer/core/editing/frame_selection.h b/chromium/third_party/blink/renderer/core/editing/frame_selection.h
index ce28d49f1e4..e03de64dcfd 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_selection.h
+++ b/chromium/third_party/blink/renderer/core/editing/frame_selection.h
@@ -125,8 +125,10 @@ class CORE_EXPORT FrameSelection final
public:
static FrameSelection* Create(LocalFrame& frame) {
- return new FrameSelection(frame);
+ return MakeGarbageCollected<FrameSelection>(frame);
}
+
+ explicit FrameSelection(LocalFrame&);
~FrameSelection();
bool IsAvailable() const { return LifecycleContext(); }
@@ -204,7 +206,7 @@ class CORE_EXPORT FrameSelection final
SelectionInDOMTree GetSelectionInDOMTree() const;
bool IsDirectional() const;
- void DocumentAttached(Document*);
+ void DidAttachDocument(Document*);
void DidLayout();
void CommitAppearanceIfNeeded();
@@ -283,8 +285,6 @@ class CORE_EXPORT FrameSelection final
friend class PaintControllerPaintTestBase;
friend class SelectionControllerTest;
- explicit FrameSelection(LocalFrame&);
-
const DisplayItemClient& CaretDisplayItemClientForTesting() const;
// Note: We have |selectionInFlatTree()| for unit tests, we should
diff --git a/chromium/third_party/blink/renderer/core/editing/frame_selection_test.cc b/chromium/third_party/blink/renderer/core/editing/frame_selection_test.cc
index 77eab39f4d9..1f808609774 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_selection_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/frame_selection_test.cc
@@ -97,9 +97,9 @@ TEST_F(FrameSelectionTest, FirstEphemeralRangeOf) {
Position(text, 3), Position(text, 6)))
.Build(),
SetSelectionOptions());
- sample->setAttribute(HTMLNames::styleAttr, "display:none");
+ sample->setAttribute(html_names::kStyleAttr, "display:none");
// Move |VisibleSelection| before "abc".
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const EphemeralRange& range =
FirstEphemeralRangeOf(Selection().ComputeVisibleSelectionInDOMTree());
EXPECT_EQ(Position(sample->nextSibling(), 0), range.StartPosition())
@@ -109,7 +109,7 @@ TEST_F(FrameSelectionTest, FirstEphemeralRangeOf) {
TEST_F(FrameSelectionTest, SetValidSelection) {
Text* text = AppendTextNode("Hello, World!");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
.SetBaseAndExtent(Position(text, 0), Position(text, 5))
@@ -119,7 +119,7 @@ TEST_F(FrameSelectionTest, SetValidSelection) {
TEST_F(FrameSelectionTest, PaintCaretShouldNotLayout) {
Text* text = AppendTextNode("Hello, World!");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
GetDocument().body()->focus();
@@ -128,7 +128,7 @@ TEST_F(FrameSelectionTest, PaintCaretShouldNotLayout) {
Selection().SetCaretVisible(true);
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder().Collapse(Position(text, 0)).Build());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(Selection().ComputeVisibleSelectionInDOMTree().IsCaret());
EXPECT_TRUE(ToLayoutBlock(GetDocument().body()->GetLayoutObject())
->ShouldPaintCursorCaret());
@@ -159,7 +159,7 @@ TEST_F(FrameSelectionTest, PaintCaretShouldNotLayout) {
TEST_F(FrameSelectionTest, SelectWordAroundCaret) {
// "Foo Bar Baz,"
Text* text = AppendTextNode("Foo Bar&nbsp;&nbsp;Baz,");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// "Fo|o Bar Baz,"
EXPECT_TRUE(SelectWordAroundPosition(Position(text, 2)));
@@ -234,7 +234,7 @@ TEST_F(FrameSelectionTest, ModifyWithUserTriggered) {
TEST_F(FrameSelectionTest, MoveRangeSelectionTest) {
// "Foo Bar Baz,"
Text* text = AppendTextNode("Foo Bar Baz,");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Itinitializes with "Foo B|a>r Baz," (| means start and > means end).
Selection().SetSelectionAndEndTyping(
@@ -304,7 +304,7 @@ TEST_F(FrameSelectionTest, SelectAllWithInputElement) {
}
TEST_F(FrameSelectionTest, SelectAllWithUnselectableRoot) {
- Element* select = GetDocument().CreateRawElement(HTMLNames::selectTag);
+ Element* select = GetDocument().CreateRawElement(html_names::kSelectTag);
GetDocument().ReplaceChild(select, GetDocument().documentElement());
GetDocument().UpdateStyleAndLayout();
Selection().SelectAll();
@@ -374,7 +374,7 @@ TEST_F(FrameSelectionTest, BoldCommandPreservesHandle) {
TEST_F(FrameSelectionTest, SelectionOnRangeHidesHandles) {
Text* text = AppendTextNode("Hello, World!");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
.SetBaseAndExtent(Position(text, 0), Position(text, 5))
@@ -1075,4 +1075,30 @@ TEST_F(FrameSelectionTest, SelectionBounds) {
frame_view->FrameToDocument(Selection().AbsoluteUnclippedBounds()));
}
+TEST_F(FrameSelectionTest, SelectionContainsBidiBoundary) {
+ InsertStyleElement("div{font:10px/10px Ahem}");
+ // Rendered as abcFED
+ Selection().SetSelection(
+ SetSelectionTextToBody("<div dir=ltr>^abc<bdo dir=trl>DEF|</bdo></div>"),
+ SetSelectionOptions());
+
+ // Check the right half of 'c'
+ const LayoutPoint c_right(35, 13);
+ EXPECT_TRUE(Selection().Contains(c_right));
+
+ // Check the left half of "F"
+ const LayoutPoint f_left(45, 13);
+ EXPECT_TRUE(Selection().Contains(f_left));
+}
+
+// This is a regression test for https://crbug.com/927394 where 'copy' operation
+// stopped copying content from inside text controls.
+// Note that this is a non-standard behavior.
+TEST_F(FrameSelectionTest, SelectedTextForClipboardEntersTextControls) {
+ Selection().SetSelection(
+ SetSelectionTextToBody("^foo<input value=\"bar\">baz|"),
+ SetSelectionOptions());
+ EXPECT_EQ("foo\nbar\nbaz", Selection().SelectedTextForClipboard());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/granularity_strategy.cc b/chromium/third_party/blink/renderer/core/editing/granularity_strategy.cc
index 0acec8634c1..aa1e71b7610 100644
--- a/chromium/third_party/blink/renderer/core/editing/granularity_strategy.cc
+++ b/chromium/third_party/blink/renderer/core/editing/granularity_strategy.cc
@@ -40,19 +40,19 @@ static bool ArePositionsInSpecifiedOrder(const VisiblePosition& vp1,
// the direction in which to search for the next bound. nextIfOnBound
// controls whether |pos| or the next boundary is returned when |pos| is
// located exactly on word boundary.
-static VisiblePosition NextWordBound(const VisiblePosition& pos,
- SearchDirection direction,
- BoundAdjust word_bound_adjust) {
+static Position NextWordBound(const Position& pos,
+ SearchDirection direction,
+ BoundAdjust word_bound_adjust) {
bool next_bound_if_on_bound =
word_bound_adjust == BoundAdjust::kNextBoundIfOnBound;
if (direction == SearchDirection::kSearchForward) {
EWordSide word_side = next_bound_if_on_bound ? kNextWordIfOnBoundary
: kPreviousWordIfOnBoundary;
- return EndOfWord(pos, word_side);
+ return EndOfWordPosition(pos, word_side);
}
EWordSide word_side = next_bound_if_on_bound ? kPreviousWordIfOnBoundary
: kNextWordIfOnBoundary;
- return StartOfWord(pos, word_side);
+ return StartOfWordPosition(pos, word_side);
}
GranularityStrategy::GranularityStrategy() = default;
@@ -72,8 +72,8 @@ void CharacterGranularityStrategy::Clear() {}
SelectionInDOMTree CharacterGranularityStrategy::UpdateExtent(
const IntPoint& extent_point,
LocalFrame* frame) {
- const VisiblePosition& extent_position =
- VisiblePositionForContentsPoint(extent_point, frame);
+ const VisiblePosition& extent_position = CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(extent_point, frame));
const VisibleSelection& selection =
frame->Selection().ComputeVisibleSelectionInDOMTree();
if (extent_position.IsNull() || selection.VisibleBase().DeepEquivalent() ==
@@ -133,7 +133,8 @@ SelectionInDOMTree DirectionGranularityStrategy::UpdateExtent(
}
VisiblePosition new_offset_extent_position =
- VisiblePositionForContentsPoint(new_offset_extent_point, frame);
+ CreateVisiblePosition(PositionForContentsPointRespectingEditingBoundary(
+ new_offset_extent_point, frame));
if (new_offset_extent_position.IsNull())
return selection.AsSelection();
IntPoint new_offset_location = PositionLocation(new_offset_extent_position);
@@ -145,8 +146,8 @@ SelectionInDOMTree DirectionGranularityStrategy::UpdateExtent(
offset_ = 0;
granularity_ = TextGranularity::kCharacter;
new_offset_extent_point = extent_point;
- new_offset_extent_position =
- VisiblePositionForContentsPoint(extent_point, frame);
+ new_offset_extent_position = CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(extent_point, frame));
}
const VisiblePosition base = selection.VisibleBase();
@@ -197,32 +198,34 @@ SelectionInDOMTree DirectionGranularityStrategy::UpdateExtent(
// Determine the word boundary, i.e. the boundary extending beyond which
// should change the granularity to WordGranularity.
- VisiblePosition word_boundary;
+ Position word_boundary_position;
if (extent_base_order_switched) {
// Special case.
// If the extent-base order was switched, then the selection is now
// expanding in a different direction than before. Therefore we
// calculate the word boundary in this new direction and based on
// the |base| position.
- word_boundary = NextWordBound(base,
- new_extent_base_order > 0
- ? SearchDirection::kSearchForward
- : SearchDirection::kSearchBackwards,
- BoundAdjust::kNextBoundIfOnBound);
+ word_boundary_position = NextWordBound(
+ base.DeepEquivalent(),
+ new_extent_base_order > 0 ? SearchDirection::kSearchForward
+ : SearchDirection::kSearchBackwards,
+ BoundAdjust::kNextBoundIfOnBound);
granularity_ = TextGranularity::kCharacter;
} else {
// Calculate the word boundary based on |oldExtentWithGranularity|.
// If selection was shrunk in the last update and the extent is now
// exactly on the word boundary - we need to take the next bound as
// the bound of the current word.
- word_boundary = NextWordBound(old_offset_extent_position,
- old_extent_base_order > 0
- ? SearchDirection::kSearchForward
- : SearchDirection::kSearchBackwards,
- state_ == StrategyState::kShrinking
- ? BoundAdjust::kNextBoundIfOnBound
- : BoundAdjust::kCurrentPosIfOnBound);
+ word_boundary_position = NextWordBound(
+ old_offset_extent_position.DeepEquivalent(),
+ old_extent_base_order > 0 ? SearchDirection::kSearchForward
+ : SearchDirection::kSearchBackwards,
+ state_ == StrategyState::kShrinking
+ ? BoundAdjust::kNextBoundIfOnBound
+ : BoundAdjust::kCurrentPosIfOnBound);
}
+ VisiblePosition word_boundary =
+ CreateVisiblePosition(word_boundary_position);
bool expanded_beyond_word_boundary;
if (selection_expanded)
@@ -250,12 +253,12 @@ SelectionInDOMTree DirectionGranularityStrategy::UpdateExtent(
// Determine the bounds of the word where the extent is located.
// Set the selection extent to one of the two bounds depending on
// whether the extent is passed the middle of the word.
- VisiblePosition bound_before_extent = NextWordBound(
- new_offset_extent_position, SearchDirection::kSearchBackwards,
- BoundAdjust::kCurrentPosIfOnBound);
- VisiblePosition bound_after_extent = NextWordBound(
- new_offset_extent_position, SearchDirection::kSearchForward,
- BoundAdjust::kCurrentPosIfOnBound);
+ VisiblePosition bound_before_extent = CreateVisiblePosition(NextWordBound(
+ new_offset_extent_position.DeepEquivalent(),
+ SearchDirection::kSearchBackwards, BoundAdjust::kCurrentPosIfOnBound));
+ VisiblePosition bound_after_extent = CreateVisiblePosition(NextWordBound(
+ new_offset_extent_position.DeepEquivalent(),
+ SearchDirection::kSearchForward, BoundAdjust::kCurrentPosIfOnBound));
int x_middle_between_bounds = (PositionLocation(bound_after_extent).X() +
PositionLocation(bound_before_extent).X()) /
2;
diff --git a/chromium/third_party/blink/renderer/core/editing/granularity_strategy_test.cc b/chromium/third_party/blink/renderer/core/editing/granularity_strategy_test.cc
index 6542a2df664..2999cdcc3db 100644
--- a/chromium/third_party/blink/renderer/core/editing/granularity_strategy_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/granularity_strategy_test.cc
@@ -93,7 +93,7 @@ Text* GranularityStrategyTest::AppendTextNode(const String& data) {
void GranularityStrategyTest::SetInnerHTML(const char* html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
void GranularityStrategyTest::ParseText(Text* text) {
@@ -156,7 +156,7 @@ Text* GranularityStrategyTest::SetupTranslateZ(String str) {
Element* div = GetDocument().getElementById("mytext");
div->AppendChild(text);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ParseText(text);
return text;
@@ -181,7 +181,7 @@ Text* GranularityStrategyTest::SetupTransform(String str) {
Element* div = GetDocument().getElementById("mytext");
div->AppendChild(text);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ParseText(text);
return text;
@@ -206,7 +206,7 @@ Text* GranularityStrategyTest::SetupRotate(String str) {
Element* div = GetDocument().getElementById("mytext");
div->AppendChild(text);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ParseText(text);
return text;
@@ -227,7 +227,7 @@ void GranularityStrategyTest::SetupTextSpan(String str1,
span->AppendChild(text2);
div->AppendChild(text3);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Vector<IntPoint> letter_pos;
Vector<IntPoint> word_middle_pos;
@@ -720,11 +720,13 @@ TEST_F(GranularityStrategyTest, UpdateExtentWithNullPositionForCharacter) {
.SetIsDirectional(true)
.Build());
- // Since, it is not obvious that |visiblePositionForContentsPoint()| returns
- // null position, we verify here.
- ASSERT_EQ(Position(),
- VisiblePositionForContentsPoint(IntPoint(0, 0), &GetFrame())
- .DeepEquivalent())
+ // Since, it is not obvious that
+ // |PositionForContentsPointRespectingEditingBoundary()| returns null
+ // position, we verify here.
+ ASSERT_EQ(Position(), CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(
+ IntPoint(0, 0), &GetFrame()))
+ .DeepEquivalent())
<< "This test requires null position.";
// Point to RANGE inside shadow root to get null position from
@@ -756,11 +758,13 @@ TEST_F(GranularityStrategyTest, UpdateExtentWithNullPositionForDirectional) {
.SetIsDirectional(true)
.Build());
- // Since, it is not obvious that |visiblePositionForContentsPoint()| returns
- // null position, we verify here.
- ASSERT_EQ(Position(),
- VisiblePositionForContentsPoint(IntPoint(0, 0), &GetFrame())
- .DeepEquivalent())
+ // Since, it is not obvious that
+ // |PositionForContentsPointRespectingEditingBoundary()| returns null
+ // position, we verify here.
+ ASSERT_EQ(Position(), CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(
+ IntPoint(0, 0), &GetFrame()))
+ .DeepEquivalent())
<< "This test requires null position.";
// Point to RANGE inside shadow root to get null position from
diff --git a/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.cc b/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.cc
index 0926bb93a7e..9295aab63bf 100644
--- a/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.cc
+++ b/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.cc
@@ -16,12 +16,14 @@ ImeTextSpan::ImeTextSpan(Type type,
ws::mojom::ImeTextSpanThickness thickness,
const Color& background_color,
const Color& suggestion_highlight_color,
+ bool remove_on_finish_composing,
const Vector<String>& suggestions)
: type_(type),
underline_color_(underline_color),
thickness_(thickness),
background_color_(background_color),
suggestion_highlight_color_(suggestion_highlight_color),
+ remove_on_finish_composing_(remove_on_finish_composing),
suggestions_(suggestions) {
// Sanitize offsets by ensuring a valid range corresponding to the last
// possible position.
@@ -66,6 +68,7 @@ ImeTextSpan::ImeTextSpan(const WebImeTextSpan& ime_text_span)
ime_text_span.thickness,
Color(ime_text_span.background_color),
Color(ime_text_span.suggestion_highlight_color),
+ ime_text_span.remove_on_finish_composing,
ConvertStdVectorOfStdStringsToVectorOfStrings(
ime_text_span.suggestions)) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.h b/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.h
index 8e5252fe4f6..8a317d58419 100644
--- a/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.h
+++ b/chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.h
@@ -50,6 +50,7 @@ class CORE_EXPORT ImeTextSpan {
ws::mojom::ImeTextSpanThickness,
const Color& background_color,
const Color& suggestion_highlight_color = Color::kTransparent,
+ bool remove_on_finish_composing = false,
const Vector<String>& suggestions = Vector<String>());
ImeTextSpan(const WebImeTextSpan&);
@@ -63,6 +64,9 @@ class CORE_EXPORT ImeTextSpan {
const Color& SuggestionHighlightColor() const {
return suggestion_highlight_color_;
}
+ bool NeedsRemovalOnFinishComposing() const {
+ return remove_on_finish_composing_;
+ }
const Vector<String>& Suggestions() const { return suggestions_; }
private:
@@ -73,6 +77,7 @@ class CORE_EXPORT ImeTextSpan {
ws::mojom::ImeTextSpanThickness thickness_;
Color background_color_;
Color suggestion_highlight_color_;
+ bool remove_on_finish_composing_;
Vector<String> suggestions_;
};
diff --git a/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.cc b/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.cc
index 317afcc65cf..8cecdfb020f 100644
--- a/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.cc
+++ b/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.cc
@@ -69,7 +69,7 @@ void DispatchCompositionUpdateEvent(LocalFrame& frame, const String& text) {
return;
CompositionEvent* event = CompositionEvent::Create(
- EventTypeNames::compositionupdate, frame.DomWindow(), text);
+ event_type_names::kCompositionupdate, frame.DomWindow(), text);
target->DispatchEvent(*event);
}
@@ -84,7 +84,7 @@ void DispatchCompositionEndEvent(LocalFrame& frame, const String& text) {
return;
CompositionEvent* event = CompositionEvent::Create(
- EventTypeNames::compositionend, frame.DomWindow(), text);
+ event_type_names::kCompositionend, frame.DomWindow(), text);
EventDispatcher::DispatchScopedEvent(*target, *event);
}
@@ -210,7 +210,7 @@ AtomicString GetInputModeAttribute(Element* element) {
// TODO(dtapuska): We may wish to restrict this to a yet to be proposed
// <contenteditable> or <richtext> element Mozilla discussed at TPAC 2016.
- return element->FastGetAttribute(HTMLNames::inputmodeAttr).LowerASCII();
+ return element->FastGetAttribute(html_names::kInputmodeAttr).LowerASCII();
}
constexpr int kInvalidDeletionLength = -1;
@@ -324,9 +324,9 @@ int ComputeAutocapitalizeFlags(const Element* element) {
// https://html.spec.whatwg.org/multipage/interaction.html#used-autocapitalization-hint
if (auto* input = ToHTMLInputElementOrNull(*html_element)) {
const AtomicString& input_type = input->type();
- if (input_type == InputTypeNames::email ||
- input_type == InputTypeNames::url ||
- input_type == InputTypeNames::password) {
+ if (input_type == input_type_names::kEmail ||
+ input_type == input_type_names::kUrl ||
+ input_type == input_type_names::kPassword) {
// The autocapitalize IDL attribute value is ignored for these input
// types, so we set the None flag.
return kWebTextInputFlagAutocapitalizeNone;
@@ -366,7 +366,7 @@ int ComputeAutocapitalizeFlags(const Element* element) {
enum class InputMethodController::TypingContinuation { kContinue, kEnd };
InputMethodController* InputMethodController::Create(LocalFrame& frame) {
- return new InputMethodController(frame);
+ return MakeGarbageCollected<InputMethodController>(frame);
}
InputMethodController::InputMethodController(LocalFrame& frame)
@@ -393,6 +393,8 @@ inline Editor& InputMethodController::GetEditor() const {
}
void InputMethodController::Clear() {
+ RemoveSuggestionMarkerInCompositionRange();
+
has_composition_ = false;
if (composition_range_) {
composition_range_->setStart(&GetDocument(), 0);
@@ -407,7 +409,7 @@ void InputMethodController::ContextDestroyed(Document*) {
composition_range_ = nullptr;
}
-void InputMethodController::DocumentAttached(Document* document) {
+void InputMethodController::DidAttachDocument(Document* document) {
DCHECK(document);
SetContext(document);
}
@@ -620,6 +622,8 @@ void InputMethodController::AddImeTextSpans(
.SetUnderlineColor(ime_text_span.UnderlineColor())
.SetThickness(ime_text_span.Thickness())
.SetBackgroundColor(ime_text_span.BackgroundColor())
+ .SetRemoveOnFinishComposing(
+ ime_text_span.NeedsRemovalOnFinishComposing())
.Build());
break;
}
@@ -736,7 +740,7 @@ bool InputMethodController::DispatchCompositionStartEvent(const String& text) {
return IsAvailable();
CompositionEvent* event = CompositionEvent::Create(
- EventTypeNames::compositionstart, GetFrame().DomWindow(), text);
+ event_type_names::kCompositionstart, GetFrame().DomWindow(), text);
target->DispatchEvent(*event);
return IsAvailable();
@@ -1048,6 +1052,13 @@ bool InputMethodController::SetEditableSelectionOffsets(
return SetSelectionOffsets(selection_offsets, typing_continuation);
}
+void InputMethodController::RemoveSuggestionMarkerInCompositionRange() {
+ if (HasComposition()) {
+ GetDocument().Markers().RemoveSuggestionMarkerInRangeOnFinish(
+ EphemeralRangeInFlatTree(composition_range_.Get()));
+ }
+}
+
PlainTextRange InputMethodController::CreateRangeForSelection(
int start,
int end,
@@ -1338,14 +1349,14 @@ int InputMethodController::TextInputFlags() const {
int flags = 0;
const AtomicString& autocomplete =
- element->getAttribute(HTMLNames::autocompleteAttr);
+ element->getAttribute(html_names::kAutocompleteAttr);
if (autocomplete == "on")
flags |= kWebTextInputFlagAutocompleteOn;
else if (autocomplete == "off")
flags |= kWebTextInputFlagAutocompleteOff;
const AtomicString& autocorrect =
- element->getAttribute(HTMLNames::autocorrectAttr);
+ element->getAttribute(html_names::kAutocorrectAttr);
if (autocorrect == "on")
flags |= kWebTextInputFlagAutocorrectOn;
else if (autocorrect == "off")
@@ -1396,21 +1407,21 @@ WebTextInputMode InputMethodController::InputModeOfFocusedElement() const {
if (mode.IsEmpty())
return kWebTextInputModeDefault;
- if (mode == InputModeNames::none)
+ if (mode == input_mode_names::kNone)
return kWebTextInputModeNone;
- if (mode == InputModeNames::text)
+ if (mode == input_mode_names::kText)
return kWebTextInputModeText;
- if (mode == InputModeNames::tel)
+ if (mode == input_mode_names::kTel)
return kWebTextInputModeTel;
- if (mode == InputModeNames::url)
+ if (mode == input_mode_names::kUrl)
return kWebTextInputModeUrl;
- if (mode == InputModeNames::email)
+ if (mode == input_mode_names::kEmail)
return kWebTextInputModeEmail;
- if (mode == InputModeNames::numeric)
+ if (mode == input_mode_names::kNumeric)
return kWebTextInputModeNumeric;
- if (mode == InputModeNames::decimal)
+ if (mode == input_mode_names::kDecimal)
return kWebTextInputModeDecimal;
- if (mode == InputModeNames::search)
+ if (mode == input_mode_names::kSearch)
return kWebTextInputModeSearch;
return kWebTextInputModeDefault;
}
@@ -1440,19 +1451,19 @@ WebTextInputType InputMethodController::TextInputType() const {
if (input->IsDisabledOrReadOnly())
return kWebTextInputTypeNone;
- if (type == InputTypeNames::password)
+ if (type == input_type_names::kPassword)
return kWebTextInputTypePassword;
- if (type == InputTypeNames::search)
+ if (type == input_type_names::kSearch)
return kWebTextInputTypeSearch;
- if (type == InputTypeNames::email)
+ if (type == input_type_names::kEmail)
return kWebTextInputTypeEmail;
- if (type == InputTypeNames::number)
+ if (type == input_type_names::kNumber)
return kWebTextInputTypeNumber;
- if (type == InputTypeNames::tel)
+ if (type == input_type_names::kTel)
return kWebTextInputTypeTelephone;
- if (type == InputTypeNames::url)
+ if (type == input_type_names::kUrl)
return kWebTextInputTypeURL;
- if (type == InputTypeNames::text)
+ if (type == input_type_names::kText)
return kWebTextInputTypeText;
return kWebTextInputTypeNone;
diff --git a/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.h b/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.h
index 9f2ed35bdc2..8c8ed89ea9d 100644
--- a/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.h
+++ b/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.h
@@ -58,6 +58,8 @@ class CORE_EXPORT InputMethodController final
};
static InputMethodController* Create(LocalFrame&);
+
+ explicit InputMethodController(LocalFrame&);
virtual ~InputMethodController();
void Trace(blink::Visitor*) override;
@@ -89,7 +91,7 @@ class CORE_EXPORT InputMethodController final
EphemeralRange CompositionEphemeralRange() const;
void Clear();
- void DocumentAttached(Document*);
+ void DidAttachDocument(Document*);
PlainTextRange GetSelectionOffsets() const;
// Returns true if setting selection to specified offsets, otherwise false.
@@ -120,8 +122,6 @@ class CORE_EXPORT InputMethodController final
Member<Range> composition_range_;
bool has_composition_;
- explicit InputMethodController(LocalFrame&);
-
Editor& GetEditor() const;
LocalFrame& GetFrame() const {
DCHECK(frame_);
@@ -182,6 +182,14 @@ class CORE_EXPORT InputMethodController final
// Returns true if selection offsets were successfully set.
bool SetSelectionOffsets(const PlainTextRange&, TypingContinuation);
+ // There are few cases we need to remove suggestion markers which are also in
+ // composing range. (SuggestionSpan with FLAG_AUTO_CORRECTION and
+ // Spanned#SPAN_COMPOSING)
+ // 1) FinishComposingText()
+ // 2) CommitText()
+ // 3) SetComposingText() (SetComposition())
+ void RemoveSuggestionMarkerInCompositionRange();
+
FRIEND_TEST_ALL_PREFIXES(InputMethodControllerTest,
InputModeOfFocusedElement);
diff --git a/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc b/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc
index 34fefa1e1e5..a015b217940 100644
--- a/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc
@@ -56,7 +56,7 @@ void InputMethodControllerTest::CreateHTMLWithCompositionInputEventListeners() {
GetDocument().GetSettings()->SetScriptEnabled(true);
Element* editable =
InsertHTMLElement("<div id='sample' contenteditable></div>", "sample");
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('beforeinput', "
" event => document.title = `beforeinput.data:${event.data};`);"
@@ -65,7 +65,7 @@ void InputMethodControllerTest::CreateHTMLWithCompositionInputEventListeners() {
"document.getElementById('sample').addEventListener('compositionend', "
" event => document.title += `compositionend.data:${event.data};`);");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
editable->focus();
}
@@ -74,7 +74,7 @@ void InputMethodControllerTest::CreateHTMLWithCompositionEndEventListener(
GetDocument().GetSettings()->SetScriptEnabled(true);
Element* editable =
InsertHTMLElement("<div id='sample' contentEditable></div>", "sample");
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
switch (type) {
case kNoSelection:
@@ -110,7 +110,7 @@ void InputMethodControllerTest::CreateHTMLWithCompositionEndEventListener(
NOTREACHED();
}
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
editable->focus();
}
@@ -1192,7 +1192,7 @@ TEST_F(InputMethodControllerTest, CompositionInputEventIsComposing) {
GetDocument().GetSettings()->SetScriptEnabled(true);
Element* editable =
InsertHTMLElement("<div id='sample' contenteditable></div>", "sample");
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('beforeinput', "
" event => document.title = "
@@ -1201,7 +1201,7 @@ TEST_F(InputMethodControllerTest, CompositionInputEventIsComposing) {
" event => document.title += "
" `input.isComposing:${event.isComposing};`);");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Simulate composition in the |contentEditable|.
Vector<ImeTextSpan> ime_text_spans;
@@ -2363,6 +2363,46 @@ TEST_F(InputMethodControllerTest,
EXPECT_EQ(0u, GetDocument().Markers().Markers().size());
}
+TEST_F(InputMethodControllerTest, RemoveSuggestionMarkerInRangeOnFinish) {
+ InsertHTMLElement(
+ "<div id='sample' contenteditable spellcheck='true'>text</div>",
+ "sample");
+
+ Vector<ImeTextSpan> ime_text_spans;
+ ime_text_spans.push_back(ImeTextSpan(
+ ImeTextSpan::Type::kMisspellingSuggestion, 0, 5, Color::kTransparent,
+ ImeTextSpanThickness::kNone, Color::kTransparent, Color ::kTransparent,
+ /* remove_on_finish_composing */ true));
+
+ // Case 1: SetComposition() -> FinishComposingText() removes the suggestion
+ // marker when remove_on_finish_composing is true.
+ Controller().SetComposition("hello", ime_text_spans, 0, 5);
+ ASSERT_EQ(1u, GetDocument().Markers().Markers().size());
+ ASSERT_TRUE(
+ Controller().FinishComposingText(InputMethodController::kKeepSelection));
+
+ EXPECT_EQ(0u, GetDocument().Markers().Markers().size());
+
+ // Case 2: SetComposition() -> CommitText() removes the suggestion marker when
+ // remove_on_finish_composing is true.
+ Controller().SetComposition("hello", ime_text_spans, 0, 5);
+ ASSERT_EQ(1u, GetDocument().Markers().Markers().size());
+ ASSERT_TRUE(Controller().CommitText("world", Vector<ImeTextSpan>(), 1));
+
+ EXPECT_EQ(0u, GetDocument().Markers().Markers().size());
+
+ // Case 3: SetComposition() -> SetComposingText() removes the suggestion
+ // marker when remove_on_finish_composing is true.
+ Controller().SetComposition("hello", ime_text_spans, 0, 5);
+ ASSERT_EQ(1u, GetDocument().Markers().Markers().size());
+ Controller().SetComposition("helloworld", Vector<ImeTextSpan>(), 0, 10);
+
+ // SetComposing() will add a composition marker.
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+ EXPECT_EQ(DocumentMarker::MarkerType::kComposition,
+ GetDocument().Markers().Markers()[0]->GetType());
+}
+
// For http://crbug.com/712761
TEST_F(InputMethodControllerTest, TextInputTypeAtBeforeEditable) {
GetDocument().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
@@ -2546,7 +2586,7 @@ TEST_F(InputMethodControllerTest,
InsertHTMLElement("<div id='sample' contenteditable>hello</div>", "sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2557,7 +2597,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 11);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "hello".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 0, 5);
@@ -2581,7 +2621,7 @@ TEST_F(InputMethodControllerTest,
"<div id='sample' contenteditable>hello world</div>", "sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2591,7 +2631,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 0);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Select "hello".
GetFrame().Selection().SetSelectionAndEndTyping(
@@ -2619,7 +2659,7 @@ TEST_F(
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2630,7 +2670,7 @@ TEST_F(
" selection.extend(node.firstChild, 2);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2652,7 +2692,7 @@ TEST_F(InputMethodControllerTest,
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2663,7 +2703,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 2);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2686,7 +2726,7 @@ TEST_F(InputMethodControllerTest,
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2696,7 +2736,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 5);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2720,7 +2760,7 @@ TEST_F(InputMethodControllerTest,
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2730,7 +2770,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 5);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2753,7 +2793,7 @@ TEST_F(InputMethodControllerTest,
"<div id='sample' contenteditable>hello world</div>", "sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2763,7 +2803,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 5);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Select "world".
GetFrame().Selection().SetSelectionAndEndTyping(
@@ -2790,7 +2830,7 @@ TEST_F(InputMethodControllerTest,
InsertHTMLElement("<div id='sample' contenteditable>hello</div>", "sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -2801,7 +2841,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 11);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "hello".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 0, 5);
@@ -2826,7 +2866,7 @@ TEST_F(
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -2837,7 +2877,7 @@ TEST_F(
" selection.extend(node.firstChild, 2);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2860,7 +2900,7 @@ TEST_F(
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -2870,7 +2910,7 @@ TEST_F(
" selection.extend(node.firstChild, 5);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2893,7 +2933,7 @@ TEST_F(InputMethodControllerTest,
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -2903,7 +2943,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 5);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2925,7 +2965,7 @@ TEST_F(InputMethodControllerTest,
"sample");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -2935,7 +2975,7 @@ TEST_F(InputMethodControllerTest,
" selection.extend(node.firstChild, 5);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Open composition on "world".
Controller().SetCompositionFromExistingText(Vector<ImeTextSpan>(), 6, 11);
@@ -2957,7 +2997,7 @@ TEST_F(InputMethodControllerTest,
InsertHTMLElement("<input id='sample' maxlength='2'>", "sample"));
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2965,7 +3005,7 @@ TEST_F(InputMethodControllerTest,
" node.setSelectionRange(1, 1);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
input->focus();
@@ -2987,7 +3027,7 @@ TEST_F(InputMethodControllerTest,
InsertHTMLElement("<input id='sample' maxlength='2'>", "sample"));
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('input', "
" event => {"
@@ -2995,7 +3035,7 @@ TEST_F(InputMethodControllerTest,
" node.setSelectionRange(1, 1);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
input->focus();
@@ -3017,7 +3057,7 @@ TEST_F(InputMethodControllerTest,
InsertHTMLElement("<input id='sample' maxlength='2'>", "sample"));
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -3025,7 +3065,7 @@ TEST_F(InputMethodControllerTest,
" node.setSelectionRange(1, 1);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
input->focus();
@@ -3049,7 +3089,7 @@ TEST_F(
InsertHTMLElement("<input id='sample' maxlength='2'>", "sample"));
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.getElementById('sample').addEventListener('compositionend', "
" event => {"
@@ -3057,7 +3097,7 @@ TEST_F(
" node.setSelectionRange(1, 1);"
"});");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
input->focus();
@@ -3076,7 +3116,7 @@ TEST_F(
TEST_F(InputMethodControllerTest, AutocapitalizeTextInputFlags) {
// This test assumes that the behavior tested in
- // LayoutTests/fast/forms/autocapitalize.html works properly and tests the
+ // web_tests/fast/forms/autocapitalize.html works properly and tests the
// following:
// - The autocapitalize IDL states map properly to WebTextInputFlags for
// <input> elements, <textarea> elements, and editable regions
diff --git a/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.cc b/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.cc
index b874d22c20c..1534c8cf7b9 100644
--- a/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.cc
+++ b/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.cc
@@ -159,10 +159,10 @@ class AbstractInlineBox {
enum class InstanceType { kNull, kOldLayout, kNG };
InstanceType type_;
- union {
- const InlineBox* inline_box_;
- NGPaintFragmentTraversalContext paint_fragment_;
- };
+ // Only one of |inline_box_| or |paint_fragment_| is used, but we cannot make
+ // them union because of non-trivial destructor.
+ const InlineBox* inline_box_;
+ NGPaintFragmentTraversalContext paint_fragment_;
};
// |SideAffinity| represents the left or right side of a leaf inline
diff --git a/chromium/third_party/blink/renderer/core/editing/input_mode_names.json5 b/chromium/third_party/blink/renderer/core/editing/input_mode_names.json5
index e210b74d5c8..ff05487d092 100644
--- a/chromium/third_party/blink/renderer/core/editing/input_mode_names.json5
+++ b/chromium/third_party/blink/renderer/core/editing/input_mode_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "InputMode",
+ namespace: "input_mode_names",
export: "CORE_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/character_iterator_test.cc b/chromium/third_party/blink/renderer/core/editing/iterators/character_iterator_test.cc
index 212c2e6d09b..e02baf91af2 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/character_iterator_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/character_iterator_test.cc
@@ -33,16 +33,32 @@
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/testing/editing_test_base.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
class CharacterIteratorTest : public EditingTestBase {};
-TEST_F(CharacterIteratorTest, SubrangeWithReplacedElements) {
+class ParameterizedCharacterIteratorTest
+ : public testing::WithParamInterface<bool>,
+ private ScopedLayoutNGForTest,
+ public CharacterIteratorTest {
+ public:
+ ParameterizedCharacterIteratorTest() : ScopedLayoutNGForTest(GetParam()) {}
+
+ protected:
+ bool LayoutNGEnabled() const { return GetParam(); }
+};
+
+INSTANTIATE_TEST_CASE_P(All,
+ ParameterizedCharacterIteratorTest,
+ testing::Bool());
+
+TEST_P(ParameterizedCharacterIteratorTest, SubrangeWithReplacedElements) {
static const char* body_content =
"<div id='div' contenteditable='true'>1<img src='foo.png'>345</div>";
SetBodyContent(body_content);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* div_node = GetDocument().getElementById("div");
Range* entire_range = Range::Create(GetDocument(), div_node, 0, div_node, 3);
@@ -54,11 +70,11 @@ TEST_F(CharacterIteratorTest, SubrangeWithReplacedElements) {
EXPECT_EQ(Position(text_node, 3), result.EndPosition());
}
-TEST_F(CharacterIteratorTest, CollapsedSubrange) {
+TEST_P(ParameterizedCharacterIteratorTest, CollapsedSubrange) {
static const char* body_content =
"<div id='div' contenteditable='true'>hello</div>";
SetBodyContent(body_content);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* text_node = GetDocument().getElementById("div")->lastChild();
Range* entire_range =
@@ -72,7 +88,7 @@ TEST_F(CharacterIteratorTest, CollapsedSubrange) {
EXPECT_EQ(Position(text_node, 3), result.EndPosition());
}
-TEST_F(CharacterIteratorTest, GetPositionWithBlock) {
+TEST_P(ParameterizedCharacterIteratorTest, GetPositionWithBlock) {
SetBodyContent("a<div>b</div>c");
const Element& body = *GetDocument().body();
@@ -126,7 +142,7 @@ TEST_F(CharacterIteratorTest, GetPositionWithBlock) {
EXPECT_TRUE(it.AtEnd());
}
-TEST_F(CharacterIteratorTest, GetPositionWithBlocks) {
+TEST_P(ParameterizedCharacterIteratorTest, GetPositionWithBlocks) {
SetBodyContent("<p id=a>b</p><p id=c>d</p>");
const Element& body = *GetDocument().body();
@@ -173,7 +189,7 @@ TEST_F(CharacterIteratorTest, GetPositionWithBlocks) {
EXPECT_TRUE(it.AtEnd());
}
-TEST_F(CharacterIteratorTest, GetPositionWithBR) {
+TEST_P(ParameterizedCharacterIteratorTest, GetPositionWithBR) {
SetBodyContent("a<br>b");
const Element& body = *GetDocument().body();
@@ -212,7 +228,8 @@ TEST_F(CharacterIteratorTest, GetPositionWithBR) {
EXPECT_TRUE(it.AtEnd());
}
-TEST_F(CharacterIteratorTest, GetPositionWithCollapsedWhitespaces) {
+TEST_P(ParameterizedCharacterIteratorTest,
+ GetPositionWithCollapsedWhitespaces) {
SetBodyContent("a <div> b </div> c");
const Element& body = *GetDocument().body();
@@ -266,7 +283,7 @@ TEST_F(CharacterIteratorTest, GetPositionWithCollapsedWhitespaces) {
EXPECT_TRUE(it.AtEnd());
}
-TEST_F(CharacterIteratorTest, GetPositionWithEmitChar16Before) {
+TEST_P(ParameterizedCharacterIteratorTest, GetPositionWithEmitChar16Before) {
InsertStyleElement("b { white-space: pre; }");
SetBodyContent("a <b> c</b>");
@@ -289,15 +306,17 @@ TEST_F(CharacterIteratorTest, GetPositionWithEmitChar16Before) {
EXPECT_EQ(Position(text_a, 1), it.StartPosition());
EXPECT_EQ(Position(text_a, 2), it.EndPosition());
- // TODO(editing-dev): We should know why we emit a space character for
- // "white-space: pre" element after trailing whitespace.
- // A space character emitted by |EmitChar16Before()|.
- ASSERT_FALSE(it.AtEnd());
- it.Advance(1);
- EXPECT_EQ(Position(text_c, 0), it.GetPositionBefore());
- EXPECT_EQ(Position(text_c, 0), it.GetPositionAfter());
- EXPECT_EQ(Position(text_c, 0), it.StartPosition());
- EXPECT_EQ(Position(text_c, 0), it.EndPosition());
+ if (!LayoutNGEnabled()) {
+ // TODO(editing-dev): TextIterator with legacy layout incorrectly emits a
+ // space character for "white-space: pre" element after trailing whitespace.
+ // A space character emitted by |EmitChar16Before()|. Fix it.
+ ASSERT_FALSE(it.AtEnd());
+ it.Advance(1);
+ EXPECT_EQ(Position(text_c, 0), it.GetPositionBefore());
+ EXPECT_EQ(Position(text_c, 0), it.GetPositionAfter());
+ EXPECT_EQ(Position(text_c, 0), it.StartPosition());
+ EXPECT_EQ(Position(text_c, 0), it.EndPosition());
+ }
ASSERT_FALSE(it.AtEnd());
it.Advance(1);
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator.cc b/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator.cc
index a81a347948b..9fe4180b251 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator.cc
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator.cc
@@ -50,7 +50,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -74,7 +74,6 @@ TextIteratorBehavior AdjustBehaviorFlags<EditingInFlatTreeStrategy>(
.SetExcludeAutofilledValue(behavior.ForSelectionToString() ||
behavior.ExcludeAutofilledValue())
.SetEntersOpenShadowRoots(false)
- .SetEntersTextControls(false)
.Build();
}
@@ -165,6 +164,19 @@ bool IsRenderedAsTable(const Node* node) {
return layout_object && layout_object->IsTable();
}
+bool ShouldHandleChildren(const Node& node,
+ const TextIteratorBehavior& behavior) {
+ // To support |TextIteratorEmitsImageAltText|, we don't traversal child
+ // nodes, in flat tree.
+ if (IsHTMLImageElement(node))
+ return false;
+ // Traverse internals of text control elements in flat tree only when
+ // |EntersTextControls| flag is set.
+ if (!behavior.EntersTextControls() && IsTextControl(node))
+ return false;
+ return true;
+}
+
} // namespace
template <typename Strategy>
@@ -307,7 +319,8 @@ void TextIteratorAlgorithm<Strategy>::Advance() {
} else {
// Enter author shadow roots, from youngest, if any and if necessary.
if (iteration_progress_ < kHandledOpenShadowRoots) {
- if (EntersOpenShadowRoots() && node_->IsElementNode() &&
+ if (std::is_same<Strategy, EditingStrategy>::value &&
+ EntersOpenShadowRoots() && node_->IsElementNode() &&
ToElement(node_)->OpenShadowRoot()) {
ShadowRoot* youngest_shadow_root = ToElement(node_)->OpenShadowRoot();
DCHECK(youngest_shadow_root->GetType() == ShadowRootType::V0 ||
@@ -324,7 +337,8 @@ void TextIteratorAlgorithm<Strategy>::Advance() {
// Enter user-agent shadow root, if necessary.
if (iteration_progress_ < kHandledUserAgentShadowRoot) {
- if (EntersTextControls() && layout_object->IsTextControl()) {
+ if (std::is_same<Strategy, EditingStrategy>::value &&
+ EntersTextControls() && layout_object->IsTextControl()) {
ShadowRoot* user_agent_shadow_root =
ToElement(node_)->UserAgentShadowRoot();
DCHECK(user_agent_shadow_root->IsUserAgent());
@@ -369,12 +383,10 @@ void TextIteratorAlgorithm<Strategy>::Advance() {
// calling exitNode() as we come back thru a parent node.
//
// 1. Iterate over child nodes, if we haven't done yet.
- // To support |TextIteratorEmitsImageAltText|, we don't traversal child
- // nodes, in flat tree.
- Node* next =
- iteration_progress_ < kHandledChildren && !IsHTMLImageElement(*node_)
- ? Strategy::FirstChild(*node_)
- : nullptr;
+ Node* next = iteration_progress_ < kHandledChildren &&
+ ShouldHandleChildren(*node_, behavior_)
+ ? Strategy::FirstChild(*node_)
+ : nullptr;
if (!next) {
// 2. If we've already iterated children or they are not available, go to
// the next sibling node.
@@ -489,7 +501,7 @@ bool TextIteratorAlgorithm<Strategy>::SupportsAltText(const Node& node) {
if (IsHTMLImageElement(element))
return true;
if (IsHTMLInputElement(element) &&
- ToHTMLInputElement(node).type() == InputTypeNames::image)
+ ToHTMLInputElement(node).type() == input_type_names::kImage)
return true;
return false;
}
@@ -577,16 +589,16 @@ static bool ShouldEmitNewlinesBeforeAndAfterNode(const Node& node) {
if (!r) {
if (HasDisplayContents(node))
return false;
- return (node.HasTagName(blockquoteTag) || node.HasTagName(ddTag) ||
- node.HasTagName(divTag) || node.HasTagName(dlTag) ||
- node.HasTagName(dtTag) || node.HasTagName(h1Tag) ||
- node.HasTagName(h2Tag) || node.HasTagName(h3Tag) ||
- node.HasTagName(h4Tag) || node.HasTagName(h5Tag) ||
- node.HasTagName(h6Tag) || node.HasTagName(hrTag) ||
- node.HasTagName(liTag) || node.HasTagName(listingTag) ||
- node.HasTagName(olTag) || node.HasTagName(pTag) ||
- node.HasTagName(preTag) || node.HasTagName(trTag) ||
- node.HasTagName(ulTag));
+ return (node.HasTagName(kBlockquoteTag) || node.HasTagName(kDdTag) ||
+ node.HasTagName(kDivTag) || node.HasTagName(kDlTag) ||
+ node.HasTagName(kDtTag) || node.HasTagName(kH1Tag) ||
+ node.HasTagName(kH2Tag) || node.HasTagName(kH3Tag) ||
+ node.HasTagName(kH4Tag) || node.HasTagName(kH5Tag) ||
+ node.HasTagName(kH6Tag) || node.HasTagName(kHrTag) ||
+ node.HasTagName(kLiTag) || node.HasTagName(kListingTag) ||
+ node.HasTagName(kOlTag) || node.HasTagName(kPTag) ||
+ node.HasTagName(kPreTag) || node.HasTagName(kTrTag) ||
+ node.HasTagName(kUlTag));
}
// Need to make an exception for option and optgroup, because we want to
@@ -642,7 +654,7 @@ static bool ShouldEmitExtraNewlineForNode(const Node* node) {
if (!r || !r->IsBox())
return false;
- return node->HasTagName(pTag);
+ return node->HasTagName(kPTag);
}
// Whether or not we should emit a character as we enter node_ (if it's a
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc b/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc
index 2221e11d9b3..e000dcc7133 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc
@@ -69,6 +69,12 @@ TextIteratorBehavior EmitsSmallXForTextSecurityBehavior() {
.Build();
}
+TextIteratorBehavior EmitsCharactersBetweenAllVisiblePositionsBehavior() {
+ return TextIteratorBehavior::Builder()
+ .SetEmitsCharactersBetweenAllVisiblePositions(true)
+ .Build();
+}
+
struct DOMTree : NodeTraversal {
using PositionType = Position;
using TextIteratorType = TextIterator;
@@ -79,8 +85,14 @@ struct FlatTree : FlatTreeTraversal {
using TextIteratorType = TextIteratorInFlatTree;
};
-class TextIteratorTest : public EditingTestBase {
+class TextIteratorTest : public testing::WithParamInterface<bool>,
+ private ScopedLayoutNGForTest,
+ public EditingTestBase {
protected:
+ TextIteratorTest() : ScopedLayoutNGForTest(GetParam()) {}
+
+ bool LayoutNGEnabled() const { return GetParam(); }
+
template <typename Tree>
std::string Iterate(const TextIteratorBehavior& = TextIteratorBehavior());
@@ -92,6 +104,11 @@ class TextIteratorTest : public EditingTestBase {
Range* GetBodyRange() const;
+ int TestRangeLength(const std::string& selection_text) {
+ return TextIterator::RangeLength(
+ SetSelectionTextToBody(selection_text).ComputeRange());
+ }
+
private:
template <typename Tree>
std::string IterateWithIterator(typename Tree::TextIteratorType&);
@@ -135,24 +152,9 @@ Range* TextIteratorTest::GetBodyRange() const {
return range;
}
-class ParameterizedTextIteratorTest : public testing::WithParamInterface<bool>,
- private ScopedLayoutNGForTest,
- public TextIteratorTest {
- public:
- ParameterizedTextIteratorTest() : ScopedLayoutNGForTest(GetParam()) {}
+INSTANTIATE_TEST_CASE_P(All, TextIteratorTest, testing::Bool());
- protected:
- bool LayoutNGEnabled() const { return GetParam(); }
-
- int TestRangeLength(const std::string& selection_text) {
- return TextIterator::RangeLength(
- SetSelectionTextToBody(selection_text).ComputeRange());
- }
-};
-
-INSTANTIATE_TEST_CASE_P(All, ParameterizedTextIteratorTest, testing::Bool());
-
-TEST_F(TextIteratorTest, BitStackOverflow) {
+TEST_P(TextIteratorTest, BitStackOverflow) {
const unsigned kBitsInWord = sizeof(unsigned) * 8;
BitStack bs;
@@ -164,14 +166,14 @@ TEST_F(TextIteratorTest, BitStackOverflow) {
EXPECT_TRUE(bs.Top());
}
-TEST_F(TextIteratorTest, BasicIteration) {
+TEST_P(TextIteratorTest, BasicIteration) {
static const char* input = "<p>Hello, \ntext</p><p>iterator.</p>";
SetBodyContent(input);
EXPECT_EQ("[Hello, ][text][\n][\n][iterator.]", Iterate<DOMTree>());
EXPECT_EQ("[Hello, ][text][\n][\n][iterator.]", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, EmitsSmallXForTextSecurity) {
+TEST_P(TextIteratorTest, EmitsSmallXForTextSecurity) {
InsertStyleElement("s {-webkit-text-security:disc;}");
SetBodyContent("abc<s>foo</s>baz");
// E2 80 A2 is U+2022 BULLET
@@ -185,38 +187,37 @@ TEST_F(TextIteratorTest, EmitsSmallXForTextSecurity) {
Iterate<FlatTree>(TextIteratorBehavior()));
}
-TEST_F(TextIteratorTest, IgnoreAltTextInTextControls) {
+TEST_P(TextIteratorTest, IgnoreAltTextInTextControls) {
static const char* input = "<p>Hello <input type='text' value='value'>!</p>";
SetBodyContent(input);
EXPECT_EQ("[Hello ][][!]", Iterate<DOMTree>(EmitsImageAltTextBehavior()));
- EXPECT_EQ("[Hello ][][\n][value][\n][!]",
- Iterate<FlatTree>(EmitsImageAltTextBehavior()));
+ EXPECT_EQ("[Hello ][][!]", Iterate<FlatTree>(EmitsImageAltTextBehavior()));
}
-TEST_F(TextIteratorTest, DisplayAltTextInImageControls) {
+TEST_P(TextIteratorTest, DisplayAltTextInImageControls) {
static const char* input = "<p>Hello <input type='image' alt='alt'>!</p>";
SetBodyContent(input);
EXPECT_EQ("[Hello ][alt][!]", Iterate<DOMTree>(EmitsImageAltTextBehavior()));
EXPECT_EQ("[Hello ][alt][!]", Iterate<FlatTree>(EmitsImageAltTextBehavior()));
}
-TEST_F(TextIteratorTest, NotEnteringTextControls) {
+TEST_P(TextIteratorTest, NotEnteringTextControls) {
static const char* input = "<p>Hello <input type='text' value='input'>!</p>";
SetBodyContent(input);
EXPECT_EQ("[Hello ][][!]", Iterate<DOMTree>());
- EXPECT_EQ("[Hello ][][\n][input][\n][!]", Iterate<FlatTree>());
+ EXPECT_EQ("[Hello ][][!]", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, EnteringTextControlsWithOption) {
+TEST_P(TextIteratorTest, EnteringTextControlsWithOption) {
static const char* input = "<p>Hello <input type='text' value='input'>!</p>";
SetBodyContent(input);
EXPECT_EQ("[Hello ][\n][input][!]",
Iterate<DOMTree>(EntersTextControlsBehavior()));
- EXPECT_EQ("[Hello ][][\n][input][\n][!]",
+ EXPECT_EQ("[Hello ][\n][input][\n][!]",
Iterate<FlatTree>(EntersTextControlsBehavior()));
}
-TEST_F(TextIteratorTest, EnteringTextControlsWithOptionComplex) {
+TEST_P(TextIteratorTest, EnteringTextControlsWithOptionComplex) {
static const char* input =
"<input type='text' value='Beginning of range'><div><div><input "
"type='text' value='Under DOM nodes'></div></div><input type='text' "
@@ -224,13 +225,11 @@ TEST_F(TextIteratorTest, EnteringTextControlsWithOptionComplex) {
SetBodyContent(input);
EXPECT_EQ("[\n][Beginning of range][\n][Under DOM nodes][\n][End of range]",
Iterate<DOMTree>(EntersTextControlsBehavior()));
- EXPECT_EQ(
- "[][\n][Beginning of range][\n][][\n][Under DOM nodes][\n][][\n][End of "
- "range]",
- Iterate<FlatTree>(EntersTextControlsBehavior()));
+ EXPECT_EQ("[Beginning of range][\n][Under DOM nodes][\n][End of range]",
+ Iterate<FlatTree>(EntersTextControlsBehavior()));
}
-TEST_F(TextIteratorTest, NotEnteringShadowTree) {
+TEST_P(TextIteratorTest, NotEnteringShadowTree) {
static const char* body_content =
"<div>Hello, <span id='host'>text</span> iterator.</div>";
static const char* shadow_content = "<span>shadow</span>";
@@ -243,7 +242,7 @@ TEST_F(TextIteratorTest, NotEnteringShadowTree) {
EXPECT_EQ("[Hello, ][shadow][ iterator.]", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, NotEnteringShadowTreeWithNestedShadowTrees) {
+TEST_P(TextIteratorTest, NotEnteringShadowTreeWithNestedShadowTrees) {
static const char* body_content =
"<div>Hello, <span id='host-in-document'>text</span> iterator.</div>";
static const char* shadow_content1 =
@@ -259,7 +258,7 @@ TEST_F(TextIteratorTest, NotEnteringShadowTreeWithNestedShadowTrees) {
Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, NotEnteringShadowTreeWithContentInsertionPoint) {
+TEST_P(TextIteratorTest, NotEnteringShadowTreeWithContentInsertionPoint) {
static const char* body_content =
"<div>Hello, <span id='host'>text</span> iterator.</div>";
static const char* shadow_content =
@@ -272,7 +271,7 @@ TEST_F(TextIteratorTest, NotEnteringShadowTreeWithContentInsertionPoint) {
EXPECT_EQ("[Hello, ][shadow ][text][ iterator.]", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, EnteringShadowTreeWithOption) {
+TEST_P(TextIteratorTest, EnteringShadowTreeWithOption) {
static const char* body_content =
"<div>Hello, <span id='host'>text</span> iterator.</div>";
static const char* shadow_content = "<span>shadow</span>";
@@ -287,7 +286,7 @@ TEST_F(TextIteratorTest, EnteringShadowTreeWithOption) {
Iterate<FlatTree>(EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest, EnteringShadowTreeWithNestedShadowTreesWithOption) {
+TEST_P(TextIteratorTest, EnteringShadowTreeWithNestedShadowTreesWithOption) {
static const char* body_content =
"<div>Hello, <span id='host-in-document'>text</span> iterator.</div>";
static const char* shadow_content1 =
@@ -304,7 +303,7 @@ TEST_F(TextIteratorTest, EnteringShadowTreeWithNestedShadowTreesWithOption) {
Iterate<FlatTree>(EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest,
+TEST_P(TextIteratorTest,
EnteringShadowTreeWithContentInsertionPointWithOption) {
static const char* body_content =
"<div>Hello, <span id='host'>text</span> iterator.</div>";
@@ -324,7 +323,7 @@ TEST_F(TextIteratorTest,
Iterate<FlatTree>(EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest, StartingAtNodeInShadowRoot) {
+TEST_P(TextIteratorTest, StartingAtNodeInShadowRoot) {
static const char* body_content =
"<div id='outer'>Hello, <span id='host'>text</span> iterator.</div>";
static const char* shadow_content =
@@ -349,7 +348,7 @@ TEST_F(TextIteratorTest, StartingAtNodeInShadowRoot) {
EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest, FinishingAtNodeInShadowRoot) {
+TEST_P(TextIteratorTest, FinishingAtNodeInShadowRoot) {
static const char* body_content =
"<div id='outer'>Hello, <span id='host'>text</span> iterator.</div>";
static const char* shadow_content =
@@ -374,7 +373,7 @@ TEST_F(TextIteratorTest, FinishingAtNodeInShadowRoot) {
EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest, FullyClipsContents) {
+TEST_P(TextIteratorTest, FullyClipsContents) {
static const char* body_content =
"<div style='overflow: hidden; width: 200px; height: 0;'>"
"I'm invisible"
@@ -384,7 +383,7 @@ TEST_F(TextIteratorTest, FullyClipsContents) {
EXPECT_EQ("", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, IgnoresContainerClip) {
+TEST_P(TextIteratorTest, IgnoresContainerClip) {
static const char* body_content =
"<div style='overflow: hidden; width: 200px; height: 0;'>"
"<div>I'm not visible</div>"
@@ -398,7 +397,7 @@ TEST_F(TextIteratorTest, IgnoresContainerClip) {
EXPECT_EQ("[but I am!]", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, FullyClippedContentsDistributed) {
+TEST_P(TextIteratorTest, FullyClippedContentsDistributed) {
static const char* body_content =
"<div id='host'>"
"<div>Am I visible?</div>"
@@ -417,7 +416,7 @@ TEST_F(TextIteratorTest, FullyClippedContentsDistributed) {
EXPECT_EQ("", Iterate<FlatTree>(EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest, IgnoresContainersClipDistributed) {
+TEST_P(TextIteratorTest, IgnoresContainersClipDistributed) {
static const char* body_content =
"<div id='host' style='overflow: hidden; width: 200px; height: 0;'>"
"<div>Nobody can find me!</div>"
@@ -438,7 +437,7 @@ TEST_F(TextIteratorTest, IgnoresContainersClipDistributed) {
Iterate<FlatTree>(EntersOpenShadowRootsBehavior()));
}
-TEST_F(TextIteratorTest, EmitsReplacementCharForInput) {
+TEST_P(TextIteratorTest, EmitsReplacementCharForInput) {
static const char* body_content =
"<div contenteditable='true'>"
"Before"
@@ -452,11 +451,11 @@ TEST_F(TextIteratorTest, EmitsReplacementCharForInput) {
Iterate<FlatTree>(EmitsObjectReplacementCharacterBehavior()));
}
-TEST_F(TextIteratorTest, RangeLengthWithReplacedElements) {
+TEST_P(TextIteratorTest, RangeLengthWithReplacedElements) {
static const char* body_content =
"<div id='div' contenteditable='true'>1<img src='foo.png'>3</div>";
SetBodyContent(body_content);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* div_node = GetDocument().getElementById("div");
const EphemeralRange range(Position(div_node, 0), Position(div_node, 3));
@@ -464,7 +463,7 @@ TEST_F(TextIteratorTest, RangeLengthWithReplacedElements) {
EXPECT_EQ(3, TextIterator::RangeLength(range));
}
-TEST_F(TextIteratorTest, RangeLengthInMultilineSpan) {
+TEST_P(TextIteratorTest, RangeLengthInMultilineSpan) {
static const char* body_content =
"<table style='width:5em'>"
"<tbody>"
@@ -477,7 +476,7 @@ TEST_F(TextIteratorTest, RangeLengthInMultilineSpan) {
"</table>";
SetBodyContent(body_content);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Node* span_node = GetDocument().getElementById("span1");
Node* text_node = span_node->firstChild();
@@ -486,13 +485,13 @@ TEST_F(TextIteratorTest, RangeLengthInMultilineSpan) {
const EphemeralRange range(Position(text_node, 4), Position(text_node, 7));
- EXPECT_EQ(4, TextIterator::RangeLength(range));
+ EXPECT_EQ(LayoutNGEnabled() ? 3 : 4, TextIterator::RangeLength(range));
EXPECT_EQ(3, TextIterator::RangeLength(
range,
TextIteratorBehavior::NoTrailingSpaceRangeLengthBehavior()));
}
-TEST_P(ParameterizedTextIteratorTest, RangeLengthBasic) {
+TEST_P(TextIteratorTest, RangeLengthBasic) {
EXPECT_EQ(0, TestRangeLength("<p>^| (1) abc def</p>"));
EXPECT_EQ(0, TestRangeLength("<p>^ |(1) abc def</p>"));
EXPECT_EQ(1, TestRangeLength("<p>^ (|1) abc def</p>"));
@@ -508,7 +507,7 @@ TEST_P(ParameterizedTextIteratorTest, RangeLengthBasic) {
EXPECT_EQ(11, TestRangeLength("<p>^ (1) abc def|</p>"));
}
-TEST_P(ParameterizedTextIteratorTest, RangeLengthWithFirstLetter) {
+TEST_P(TextIteratorTest, RangeLengthWithFirstLetter) {
InsertStyleElement("p::first-letter {font-size:200%;}");
// Expectation should be as same as |RangeLengthBasic|
EXPECT_EQ(0, TestRangeLength("<p>^| (1) abc def</p>"));
@@ -526,8 +525,7 @@ TEST_P(ParameterizedTextIteratorTest, RangeLengthWithFirstLetter) {
EXPECT_EQ(11, TestRangeLength("<p>^ (1) abc def|</p>"));
}
-TEST_P(ParameterizedTextIteratorTest,
- RangeLengthWithFirstLetterMultipleLeadingSpaces) {
+TEST_P(TextIteratorTest, RangeLengthWithFirstLetterMultipleLeadingSpaces) {
InsertStyleElement("p::first-letter {font-size:200%;}");
EXPECT_EQ(0, TestRangeLength("<p>^| foo</p>"));
EXPECT_EQ(0, TestRangeLength("<p>^ | foo</p>"));
@@ -538,18 +536,19 @@ TEST_P(ParameterizedTextIteratorTest,
EXPECT_EQ(3, TestRangeLength("<p>^ foo|</p>"));
}
-TEST_F(TextIteratorTest, WhitespaceCollapseForReplacedElements) {
+TEST_P(TextIteratorTest, WhitespaceCollapseForReplacedElements) {
static const char* body_content =
"<span>Some text </span> <input type='button' value='Button "
"text'/><span>Some more text</span>";
SetBodyContent(body_content);
EXPECT_EQ("[Some text ][][Some more text]",
Iterate<DOMTree>(CollapseTrailingSpaceBehavior()));
+ // <input type=button> is not text control element
EXPECT_EQ("[Some text ][][Button text][Some more text]",
Iterate<FlatTree>(CollapseTrailingSpaceBehavior()));
}
-TEST_F(TextIteratorTest, copyTextTo) {
+TEST_P(TextIteratorTest, copyTextTo) {
const char* body_content =
"<a id=host><b id=one>one</b> not appeared <b id=two>two</b></a>";
const char* shadow_content =
@@ -619,7 +618,7 @@ TEST_F(TextIteratorTest, copyTextTo) {
<< String::Format(message, 2, "three two one zero").Utf8().data();
}
-TEST_F(TextIteratorTest, characterAt) {
+TEST_P(TextIteratorTest, characterAt) {
const char* body_content =
"<a id=host><b id=one>one</b> not appeared <b id=two>two</b></a>";
const char* shadow_content =
@@ -674,7 +673,7 @@ TEST_F(TextIteratorTest, characterAt) {
EXPECT_EQ('o', iter2.CharacterAt(4)) << message2;
}
-TEST_F(TextIteratorTest, CopyWholeCodePoints) {
+TEST_P(TextIteratorTest, CopyWholeCodePoints) {
const char* body_content = "&#x13000;&#x13001;&#x13002; &#x13140;&#x13141;.";
SetBodyContent(body_content);
@@ -699,7 +698,7 @@ TEST_F(TextIteratorTest, CopyWholeCodePoints) {
}
// Regression test for crbug.com/630921
-TEST_F(TextIteratorTest, EndingConditionWithDisplayNone) {
+TEST_P(TextIteratorTest, EndingConditionWithDisplayNone) {
SetBodyContent(
"<div style='display: none'><span>hello</span>world</div>Lorem ipsum "
"dolor sit amet.");
@@ -710,7 +709,7 @@ TEST_F(TextIteratorTest, EndingConditionWithDisplayNone) {
}
// Trickier regression test for crbug.com/630921
-TEST_F(TextIteratorTest, EndingConditionWithDisplayNoneInShadowTree) {
+TEST_P(TextIteratorTest, EndingConditionWithDisplayNoneInShadowTree) {
const char* body_content =
"<div style='display: none'><span id=host><a></a></span>world</div>Lorem "
"ipsum dolor sit amet.";
@@ -728,7 +727,7 @@ TEST_F(TextIteratorTest, EndingConditionWithDisplayNoneInShadowTree) {
EXPECT_TRUE(iter.AtEnd());
}
-TEST_F(TextIteratorTest, PreserveLeadingSpace) {
+TEST_P(TextIteratorTest, PreserveLeadingSpace) {
SetBodyContent("<div style='width: 2em;'><b><i>foo</i></b> bar</div>");
Element* div = GetDocument().QuerySelector("div");
Position start(div->firstChild()->firstChild()->firstChild(), 0);
@@ -739,7 +738,7 @@ TEST_F(TextIteratorTest, PreserveLeadingSpace) {
// We used to have a bug where the leading space was duplicated if we didn't
// emit alt text, this tests for that bug
-TEST_F(TextIteratorTest, PreserveLeadingSpaceWithoutEmittingAltText) {
+TEST_P(TextIteratorTest, PreserveLeadingSpaceWithoutEmittingAltText) {
SetBodyContent("<div style='width: 2em;'><b><i>foo</i></b> bar</div>");
Element* div = GetDocument().QuerySelector("div");
Position start(div->firstChild()->firstChild()->firstChild(), 0);
@@ -747,7 +746,7 @@ TEST_F(TextIteratorTest, PreserveLeadingSpaceWithoutEmittingAltText) {
EXPECT_EQ("foo bar", PlainText(EphemeralRange(start, end)));
}
-TEST_F(TextIteratorTest, PreserveOnlyLeadingSpace) {
+TEST_P(TextIteratorTest, PreserveOnlyLeadingSpace) {
SetBodyContent(
"<div style='width: 2em;'><b><i id='foo'>foo </i></b> bar</div>");
Element* div = GetDocument().QuerySelector("div");
@@ -757,7 +756,7 @@ TEST_F(TextIteratorTest, PreserveOnlyLeadingSpace) {
PlainText(EphemeralRange(start, end), EmitsImageAltTextBehavior()));
}
-TEST_F(TextIteratorTest, StartAtFirstLetter) {
+TEST_P(TextIteratorTest, StartAtFirstLetter) {
SetBodyContent("<style>div:first-letter {color:red;}</style><div>Axyz</div>");
Element* div = GetDocument().QuerySelector("div");
@@ -788,7 +787,7 @@ TEST_F(TextIteratorTest, StartAtFirstLetter) {
EXPECT_EQ("Axyz", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartInMultiCharFirstLetterWithCollapsedSpace) {
+TEST_P(TextIteratorTest, StartInMultiCharFirstLetterWithCollapsedSpace) {
SetBodyContent(
"<style>div:first-letter {color:red;}</style><div> (A) xyz</div>");
@@ -828,7 +827,7 @@ TEST_F(TextIteratorTest, StartInMultiCharFirstLetterWithCollapsedSpace) {
EXPECT_EQ("A) xyz", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartAndEndInMultiCharFirstLetterWithCollapsedSpace) {
+TEST_P(TextIteratorTest, StartAndEndInMultiCharFirstLetterWithCollapsedSpace) {
SetBodyContent(
"<style>div:first-letter {color:red;}</style><div> (A) xyz</div>");
@@ -852,7 +851,7 @@ TEST_F(TextIteratorTest, StartAndEndInMultiCharFirstLetterWithCollapsedSpace) {
EXPECT_EQ("A", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartAtRemainingText) {
+TEST_P(TextIteratorTest, StartAtRemainingText) {
SetBodyContent("<style>div:first-letter {color:red;}</style><div>Axyz</div>");
Element* div = GetDocument().QuerySelector("div");
@@ -875,7 +874,7 @@ TEST_F(TextIteratorTest, StartAtRemainingText) {
EXPECT_EQ("xyz", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartAtFirstLetterInPre) {
+TEST_P(TextIteratorTest, StartAtFirstLetterInPre) {
SetBodyContent("<style>pre:first-letter {color:red;}</style><pre>Axyz</pre>");
Element* pre = GetDocument().QuerySelector("pre");
@@ -906,7 +905,7 @@ TEST_F(TextIteratorTest, StartAtFirstLetterInPre) {
EXPECT_EQ("Axyz", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartInMultiCharFirstLetterInPre) {
+TEST_P(TextIteratorTest, StartInMultiCharFirstLetterInPre) {
SetBodyContent(
"<style>pre:first-letter {color:red;}</style><pre>(A)xyz</pre>");
@@ -938,7 +937,7 @@ TEST_F(TextIteratorTest, StartInMultiCharFirstLetterInPre) {
EXPECT_EQ("A)xyz", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartAndEndInMultiCharFirstLetterInPre) {
+TEST_P(TextIteratorTest, StartAndEndInMultiCharFirstLetterInPre) {
SetBodyContent(
"<style>pre:first-letter {color:red;}</style><pre>(A)xyz</pre>");
@@ -962,7 +961,7 @@ TEST_F(TextIteratorTest, StartAndEndInMultiCharFirstLetterInPre) {
EXPECT_EQ("A", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, StartAtRemainingTextInPre) {
+TEST_P(TextIteratorTest, StartAtRemainingTextInPre) {
SetBodyContent("<style>pre:first-letter {color:red;}</style><pre>Axyz</pre>");
Element* pre = GetDocument().QuerySelector("pre");
@@ -985,7 +984,7 @@ TEST_F(TextIteratorTest, StartAtRemainingTextInPre) {
EXPECT_EQ("xyz", String(buffer.Data()));
}
-TEST_F(TextIteratorTest, VisitsDisplayContentsChildren) {
+TEST_P(TextIteratorTest, VisitsDisplayContentsChildren) {
SetBodyContent(
"<p>Hello, \ntext</p><p style='display: contents'>iterator.</p>");
@@ -993,27 +992,27 @@ TEST_F(TextIteratorTest, VisitsDisplayContentsChildren) {
EXPECT_EQ("[Hello, ][text][iterator.]", Iterate<FlatTree>());
}
-TEST_F(TextIteratorTest, BasicIterationEmptyContent) {
+TEST_P(TextIteratorTest, BasicIterationEmptyContent) {
SetBodyContent("");
EXPECT_EQ("", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationSingleCharacter) {
+TEST_P(TextIteratorTest, BasicIterationSingleCharacter) {
SetBodyContent("a");
EXPECT_EQ("[a]", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationSingleDiv) {
+TEST_P(TextIteratorTest, BasicIterationSingleDiv) {
SetBodyContent("<div>a</div>");
EXPECT_EQ("[a]", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationMultipleDivs) {
+TEST_P(TextIteratorTest, BasicIterationMultipleDivs) {
SetBodyContent("<div>a</div><div>b</div>");
EXPECT_EQ("[a][\n][b]", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationMultipleDivsWithStyle) {
+TEST_P(TextIteratorTest, BasicIterationMultipleDivsWithStyle) {
SetBodyContent(
"<div style='line-height: 18px; min-height: 436px; '>"
"debugging this note"
@@ -1021,12 +1020,12 @@ TEST_F(TextIteratorTest, BasicIterationMultipleDivsWithStyle) {
EXPECT_EQ("[debugging this note]", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationMultipleDivsWithChildren) {
+TEST_P(TextIteratorTest, BasicIterationMultipleDivsWithChildren) {
SetBodyContent("<div>Hello<div><br><span></span></div></div>");
EXPECT_EQ("[Hello][\n][\n]", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationOnChildrenWithStyle) {
+TEST_P(TextIteratorTest, BasicIterationOnChildrenWithStyle) {
SetBodyContent(
"<div style='left:22px'>"
"</div>"
@@ -1053,7 +1052,7 @@ TEST_F(TextIteratorTest, BasicIterationOnChildrenWithStyle) {
EXPECT_EQ("[hey]", Iterate<DOMTree>());
}
-TEST_F(TextIteratorTest, BasicIterationInput) {
+TEST_P(TextIteratorTest, BasicIterationInput) {
SetBodyContent("<input id='a' value='b'>");
auto* input_element = ToTextControl(GetDocument().getElementById("a"));
const ShadowRoot* shadow_root = input_element->UserAgentShadowRoot();
@@ -1062,11 +1061,11 @@ TEST_F(TextIteratorTest, BasicIterationInput) {
EXPECT_EQ("[b]", IteratePartial<DOMTree>(start, end));
}
-TEST_F(TextIteratorTest, BasicIterationInputiWithBr) {
+TEST_P(TextIteratorTest, BasicIterationInputiWithBr) {
SetBodyContent("<input id='a' value='b'>");
auto* input_element = ToTextControl(GetDocument().getElementById("a"));
Element* inner_editor = input_element->InnerEditorElement();
- Element* br = GetDocument().CreateRawElement(HTMLNames::brTag);
+ Element* br = GetDocument().CreateRawElement(html_names::kBrTag);
inner_editor->AppendChild(br);
const ShadowRoot* shadow_root = input_element->UserAgentShadowRoot();
const Position start = Position::FirstPositionInNode(*shadow_root);
@@ -1075,30 +1074,30 @@ TEST_F(TextIteratorTest, BasicIterationInputiWithBr) {
EXPECT_EQ("[b]", IteratePartial<DOMTree>(start, end));
}
-TEST_P(ParameterizedTextIteratorTest, FloatLeft) {
+TEST_P(TextIteratorTest, FloatLeft) {
SetBodyContent("abc<span style='float:left'>DEF</span>ghi");
EXPECT_EQ("[abc][DEF][ghi]", Iterate<DOMTree>())
<< "float doesn't affect text iteration";
}
-TEST_P(ParameterizedTextIteratorTest, FloatRight) {
+TEST_P(TextIteratorTest, FloatRight) {
SetBodyContent("abc<span style='float:right'>DEF</span>ghi");
EXPECT_EQ("[abc][DEF][ghi]", Iterate<DOMTree>())
<< "float doesn't affect text iteration";
}
-TEST_P(ParameterizedTextIteratorTest, InlineBlock) {
+TEST_P(TextIteratorTest, InlineBlock) {
SetBodyContent("abc<span style='display:inline-block'>DEF<br>GHI</span>jkl");
EXPECT_EQ("[abc][DEF][\n][GHI][jkl]", Iterate<DOMTree>())
<< "inline-block doesn't insert newline around itself.";
}
-TEST_P(ParameterizedTextIteratorTest, NoZWSForSpaceAfterNoWrapSpace) {
+TEST_P(TextIteratorTest, NoZWSForSpaceAfterNoWrapSpace) {
SetBodyContent("<span style='white-space: nowrap'>foo </span> bar");
EXPECT_EQ("[foo ][bar]", Iterate<DOMTree>());
}
-TEST_P(ParameterizedTextIteratorTest, PositionInShadowTree) {
+TEST_P(TextIteratorTest, PositionInShadowTree) {
// Flat Tree: <div id=host>A<slot name=c><img slot=c alt=C></slot></div>
SetBodyContent("<div id=host><a></a><b></b><img slot=c alt=C></div>");
Element& host = *GetDocument().getElementById("host");
@@ -1130,18 +1129,27 @@ TEST_P(ParameterizedTextIteratorTest, PositionInShadowTree) {
ASSERT_TRUE(it.AtEnd());
}
-TEST_P(ParameterizedTextIteratorTest, HiddenFirstLetter) {
+TEST_P(TextIteratorTest, HiddenFirstLetter) {
InsertStyleElement("body::first-letter{visibility:hidden}");
SetBodyContent("foo");
EXPECT_EQ("[oo]", Iterate<DOMTree>());
}
-TEST_P(ParameterizedTextIteratorTest, HiddenFirstLetterInPre) {
+TEST_P(TextIteratorTest, HiddenFirstLetterInPre) {
InsertStyleElement(
"body::first-letter{visibility:hidden} body{white-space:pre}");
SetBodyContent("foo");
EXPECT_EQ("[oo]", Iterate<DOMTree>());
}
+TEST_P(TextIteratorTest, TextOffsetMappingAndFlatTree) {
+ // Tests that TextOffsetMapping should skip text control even though it runs
+ // on flat tree.
+ SetBodyContent("foo <input value='bla bla. bla bla.'> bar");
+ EXPECT_EQ(
+ "[foo ][,][ bar]",
+ Iterate<FlatTree>(EmitsCharactersBetweenAllVisiblePositionsBehavior()));
+}
+
} // namespace text_iterator_test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/layout_selection.cc b/chromium/third_party/blink/renderer/core/editing/layout_selection.cc
index c8798dae7b6..a93e9e1f1e6 100644
--- a/chromium/third_party/blink/renderer/core/editing/layout_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/layout_selection.cc
@@ -36,11 +36,28 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
+namespace {
+
+// TODO(yoichio): Share condition between NGOffsetMapping::AcceptsPosition.
+bool ShouldUseLayoutNGTextContent(const Node& node) {
+ LayoutObject* layout_object = node.GetLayoutObject();
+ DCHECK(layout_object);
+ if (layout_object->IsInline())
+ return layout_object->ContainingNGBlockFlow();
+ if (LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(layout_object))
+ return NGBlockNode::CanUseNewLayout(*block_flow);
+ return false;
+}
+
+} // namespace
+
// The current selection to be painted is represented as 2 pairs of
// (Node, offset).
// Each offset represents text offsets on selection edge if it is text.
@@ -464,7 +481,7 @@ static base::Optional<unsigned> GetTextContentOffset(const Position& position) {
#if DCHECK_IS_ON()
DCHECK(IsPositionValidText(position));
#endif
- DCHECK(position.AnchorNode()->GetLayoutObject()->EnclosingNGBlockFlow());
+ DCHECK(ShouldUseLayoutNGTextContent(*position.AnchorNode()));
const NGOffsetMapping* const offset_mapping =
NGOffsetMapping::GetFor(position);
DCHECK(offset_mapping);
@@ -514,13 +531,13 @@ static SelectionPaintRange* ComputeNewPaintRange(
const Node& start_node = *paint_range.start_node;
// If LayoutObject is not in NG, use legacy offset.
const base::Optional<unsigned> start_offset =
- start_node.GetLayoutObject()->EnclosingNGBlockFlow()
+ ShouldUseLayoutNGTextContent(start_node)
? GetTextContentOffsetStart(start_node, paint_range.start_offset)
: paint_range.start_offset;
const Node& end_node = *paint_range.end_node;
const base::Optional<unsigned> end_offset =
- end_node.GetLayoutObject()->EnclosingNGBlockFlow()
+ ShouldUseLayoutNGTextContent(end_node)
? GetTextContentOffsetEnd(end_node, paint_range.end_offset)
: paint_range.end_offset;
@@ -547,7 +564,7 @@ static bool IsLastLineInInlineBlock(const NGPaintFragment& line) {
NGPaintFragment* parent = line.Parent();
if (!parent->PhysicalFragment().IsAtomicInline())
return false;
- return parent->Children().back().get() == &line;
+ return &parent->Children().back() == &line;
}
static bool IsBeforeSoftLineBreak(const NGPaintFragment& fragment) {
@@ -569,9 +586,8 @@ static bool IsBeforeSoftLineBreak(const NGPaintFragment& fragment) {
// Even If |fragment| is before linebreak, if its direction differs to line
// direction, we don't paint line break. See
// paint/selection/text-selection-newline-mixed-ltr-rtl.html.
- const ShapeResult* shape_result =
- ToNGPhysicalTextFragment(fragment.PhysicalFragment()).TextShapeResult();
- return physical_line_box.BaseDirection() == shape_result->Direction();
+ return physical_line_box.BaseDirection() ==
+ fragment.PhysicalFragment().ResolvedDirection();
}
static Text* AssociatedTextNode(const LayoutText& text) {
diff --git a/chromium/third_party/blink/renderer/core/editing/layout_selection.h b/chromium/third_party/blink/renderer/core/editing/layout_selection.h
index bb7561e5859..19607fa30d2 100644
--- a/chromium/third_party/blink/renderer/core/editing/layout_selection.h
+++ b/chromium/third_party/blink/renderer/core/editing/layout_selection.h
@@ -41,9 +41,11 @@ class SelectionPaintRange;
class LayoutSelection final : public GarbageCollected<LayoutSelection> {
public:
static LayoutSelection* Create(FrameSelection& frame_selection) {
- return new LayoutSelection(frame_selection);
+ return MakeGarbageCollected<LayoutSelection>(frame_selection);
}
+ LayoutSelection(FrameSelection&);
+
void SetHasPendingSelection();
void Commit();
@@ -59,8 +61,6 @@ class LayoutSelection final : public GarbageCollected<LayoutSelection> {
void Trace(blink::Visitor*);
private:
- LayoutSelection(FrameSelection&);
-
Member<FrameSelection> frame_selection_;
bool has_pending_selection_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/editing/layout_selection_test.cc b/chromium/third_party/blink/renderer/core/editing/layout_selection_test.cc
index b302133d2d6..120eb68759d 100644
--- a/chromium/third_party/blink/renderer/core/editing/layout_selection_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/layout_selection_test.cc
@@ -30,7 +30,7 @@ static LayoutTextFragment* FirstLetterPartFor(
return nullptr;
}
-class LayoutSelectionTest : public EditingTestBase {
+class LayoutSelectionTestBase : public EditingTestBase {
protected:
static void PrintText(std::ostream& ostream, const Text& text) {
ostream << "'" << text.data().Utf8().data() << "'";
@@ -42,12 +42,16 @@ class LayoutSelectionTest : public EditingTestBase {
SelectionState state) {
const auto fragments = NGPaintFragment::InlineFragmentsFor(&layout_text);
if (fragments.IsInLayoutNGInlineFormattingContext()) {
+ const unsigned text_start =
+ ToNGPhysicalTextFragment(fragments.begin()->PhysicalFragment())
+ .StartOffset();
for (const NGPaintFragment* fragment : fragments) {
const LayoutSelectionStatus status =
selection.ComputeLayoutSelectionStatus(*fragment);
if (state == SelectionState::kNone && status.start == status.end)
continue;
- ostream << "(" << status.start << "," << status.end << ")";
+ ostream << "(" << status.start - text_start << ","
+ << status.end - text_start << ")";
}
return;
}
@@ -139,7 +143,18 @@ class LayoutSelectionTest : public EditingTestBase {
}
};
-TEST_F(LayoutSelectionTest, TraverseLayoutObject) {
+class LayoutSelectionTest : public ::testing::WithParamInterface<bool>,
+ private ScopedLayoutNGForTest,
+ public LayoutSelectionTestBase {
+ protected:
+ LayoutSelectionTest() : ScopedLayoutNGForTest(GetParam()) {}
+
+ bool LayoutNGEnabled() const { return GetParam(); }
+};
+
+INSTANTIATE_TEST_CASE_P(All, LayoutSelectionTest, ::testing::Bool());
+
+TEST_P(LayoutSelectionTest, TraverseLayoutObject) {
SetBodyContent("foo<br>bar");
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
@@ -154,7 +169,7 @@ TEST_F(LayoutSelectionTest, TraverseLayoutObject) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, TraverseLayoutObjectTruncateVisibilityHidden) {
+TEST_P(LayoutSelectionTest, TraverseLayoutObjectTruncateVisibilityHidden) {
SetBodyContent(
"<span style='visibility:hidden;'>before</span>"
"foo"
@@ -174,24 +189,35 @@ TEST_F(LayoutSelectionTest, TraverseLayoutObjectTruncateVisibilityHidden) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, TraverseLayoutObjectBRs) {
+TEST_P(LayoutSelectionTest, TraverseLayoutObjectBRs) {
SetBodyContent("<br><br>foo<br><br>");
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
.SelectAllChildren(*GetDocument().body())
.Build());
Selection().CommitAppearanceIfNeeded();
- EXPECT_EQ(
- "BODY, Contain, NotInvalidate \n"
- " BR, Start(0,1), ShouldInvalidate \n"
- " BR, Inside(0,1), ShouldInvalidate \n"
- " 'foo', Inside(0,3), ShouldInvalidate \n"
- " BR, Inside(0,1), ShouldInvalidate \n"
- " BR, End(0,0), ShouldInvalidate ",
- DumpSelectionInfo());
+ if (LayoutNGEnabled()) {
+ EXPECT_EQ(
+ "BODY, Contain, NotInvalidate \n"
+ " BR, Start(0,1), ShouldInvalidate \n"
+ " BR, Inside(0,1), ShouldInvalidate \n"
+ " 'foo', Inside(0,3), ShouldInvalidate \n"
+ " BR, Inside(0,1), ShouldInvalidate \n"
+ " BR, End(0,1), ShouldInvalidate ",
+ DumpSelectionInfo());
+ } else {
+ EXPECT_EQ(
+ "BODY, Contain, NotInvalidate \n"
+ " BR, Start(0,1), ShouldInvalidate \n"
+ " BR, Inside(0,1), ShouldInvalidate \n"
+ " 'foo', Inside(0,3), ShouldInvalidate \n"
+ " BR, Inside(0,1), ShouldInvalidate \n"
+ " BR, End(0,0), ShouldInvalidate ",
+ DumpSelectionInfo());
+ }
}
-TEST_F(LayoutSelectionTest, TraverseLayoutObjectListStyleImage) {
+TEST_P(LayoutSelectionTest, TraverseLayoutObjectListStyleImage) {
SetBodyContent(
"<style>ul {list-style-image:url(data:"
"image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=)}"
@@ -213,7 +239,7 @@ TEST_F(LayoutSelectionTest, TraverseLayoutObjectListStyleImage) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, TraverseLayoutObjectCrossingShadowBoundary) {
+TEST_P(LayoutSelectionTest, TraverseLayoutObjectCrossingShadowBoundary) {
Selection().SetSelectionAndEndTyping(SetSelectionTextToBody(
"^foo"
"<div>"
@@ -240,7 +266,7 @@ TEST_F(LayoutSelectionTest, TraverseLayoutObjectCrossingShadowBoundary) {
}
// crbug.com/752715
-TEST_F(LayoutSelectionTest,
+TEST_P(LayoutSelectionTest,
InvalidationShouldNotChangeRefferedLayoutObjectState) {
SetBodyContent(
"<div id='d1'>div1</div><div id='d2'>foo<span>bar</span>baz</div>");
@@ -282,20 +308,27 @@ TEST_F(LayoutSelectionTest,
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, TraverseLayoutObjectLineWrap) {
+TEST_P(LayoutSelectionTest, TraverseLayoutObjectLineWrap) {
SetBodyContent("bar\n");
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
.SelectAllChildren(*GetDocument().body())
.Build());
Selection().CommitAppearanceIfNeeded();
- EXPECT_EQ(
- "BODY, Contain, NotInvalidate \n"
- " 'bar\n', StartAndEnd(0,4), ShouldInvalidate ",
- DumpSelectionInfo());
+ if (LayoutNGEnabled()) {
+ EXPECT_EQ(
+ "BODY, Contain, NotInvalidate \n"
+ " 'bar\n', StartAndEnd(0,3), ShouldInvalidate ",
+ DumpSelectionInfo());
+ } else {
+ EXPECT_EQ(
+ "BODY, Contain, NotInvalidate \n"
+ " 'bar\n', StartAndEnd(0,4), ShouldInvalidate ",
+ DumpSelectionInfo());
+ }
}
-TEST_F(LayoutSelectionTest, FirstLetter) {
+TEST_P(LayoutSelectionTest, FirstLetter) {
SetBodyContent(
"<style>::first-letter { color: red; }</style>"
"<span>foo</span>");
@@ -313,21 +346,31 @@ TEST_F(LayoutSelectionTest, FirstLetter) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, FirstLetterMultiple) {
+TEST_P(LayoutSelectionTest, FirstLetterMultiple) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("<style>::first-letter { color: red; }</style>"
"<span> [^f]o|o</span>"));
Selection().CommitAppearanceIfNeeded();
- EXPECT_EQ(
- "BODY, Contain, NotInvalidate \n"
- " <style> \n"
- " SPAN, Contain, NotInvalidate \n"
- " ' [f]oo', StartAndEnd(0,1), ShouldInvalidate \n"
- " :first-letter, None(2,4), ShouldInvalidate ",
- DumpSelectionInfo());
+ if (LayoutNGEnabled()) {
+ EXPECT_EQ(
+ "BODY, Contain, NotInvalidate \n"
+ " <style> \n"
+ " SPAN, Contain, NotInvalidate \n"
+ " ' [f]oo', StartAndEnd(0,1), ShouldInvalidate \n"
+ " :first-letter, None(1,3), ShouldInvalidate ",
+ DumpSelectionInfo());
+ } else {
+ EXPECT_EQ(
+ "BODY, Contain, NotInvalidate \n"
+ " <style> \n"
+ " SPAN, Contain, NotInvalidate \n"
+ " ' [f]oo', StartAndEnd(0,1), ShouldInvalidate \n"
+ " :first-letter, None(2,4), ShouldInvalidate ",
+ DumpSelectionInfo());
+ }
}
-TEST_F(LayoutSelectionTest, FirstLetterClearSeletion) {
+TEST_P(LayoutSelectionTest, FirstLetterClearSeletion) {
InsertStyleElement("div::first-letter { color: red; }");
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("fo^o<div>bar</div>b|az"));
@@ -353,7 +396,7 @@ TEST_F(LayoutSelectionTest, FirstLetterClearSeletion) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, FirstLetterUpdateSeletion) {
+TEST_P(LayoutSelectionTest, FirstLetterUpdateSeletion) {
SetBodyContent(
"<style>div::first-letter { color: red; }</style>"
"foo<div>bar</div>baz");
@@ -378,7 +421,7 @@ TEST_F(LayoutSelectionTest, FirstLetterUpdateSeletion) {
" :first-letter, None(0,1), ShouldInvalidate \n"
" 'baz', End(0,1), ShouldInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" <style> \n"
@@ -388,7 +431,7 @@ TEST_F(LayoutSelectionTest, FirstLetterUpdateSeletion) {
" :first-letter, None(0,1), NotInvalidate \n"
" 'baz', End(0,1), NotInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// <div>foo</div><div>bar</div>ba^z|
Selection().SetSelectionAndEndTyping(SelectionInDOMTree::Builder()
@@ -406,7 +449,7 @@ TEST_F(LayoutSelectionTest, FirstLetterUpdateSeletion) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, CommitAppearanceIfNeededNotCrash) {
+TEST_P(LayoutSelectionTest, CommitAppearanceIfNeededNotCrash) {
Selection().SetSelectionAndEndTyping(SetSelectionTextToBody(
"<div>"
"<template data-mode=open>foo</template>"
@@ -416,7 +459,7 @@ TEST_F(LayoutSelectionTest, CommitAppearanceIfNeededNotCrash) {
Selection().CommitAppearanceIfNeeded();
}
-TEST_F(LayoutSelectionTest, SelectImage) {
+TEST_P(LayoutSelectionTest, SelectImage) {
const SelectionInDOMTree& selection =
SetSelectionTextToBody("^<img style=\"width:100px; height:100px\"/>|");
Selection().SetSelectionAndEndTyping(selection);
@@ -427,7 +470,7 @@ TEST_F(LayoutSelectionTest, SelectImage) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, MoveOnSameNode_Start) {
+TEST_P(LayoutSelectionTest, MoveOnSameNode_Start) {
const SelectionInDOMTree& selection =
SetSelectionTextToBody("f^oo<span>b|ar</span>");
Selection().SetSelectionAndEndTyping(selection);
@@ -440,7 +483,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_Start) {
DumpSelectionInfo());
// Paint virtually and clear ShouldInvalidate flag.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" 'foo', Start(1,3), NotInvalidate \n"
@@ -464,7 +507,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_Start) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, MoveOnSameNode_End) {
+TEST_P(LayoutSelectionTest, MoveOnSameNode_End) {
const SelectionInDOMTree& selection =
SetSelectionTextToBody("f^oo<span>b|ar</span>");
Selection().SetSelectionAndEndTyping(selection);
@@ -477,7 +520,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_End) {
DumpSelectionInfo());
// Paint virtually and clear ShouldInvalidate flag.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" 'foo', Start(1,3), NotInvalidate \n"
@@ -501,7 +544,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_End) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, MoveOnSameNode_StartAndEnd) {
+TEST_P(LayoutSelectionTest, MoveOnSameNode_StartAndEnd) {
const SelectionInDOMTree& selection = SetSelectionTextToBody("f^oob|ar");
Selection().SetSelectionAndEndTyping(selection);
Selection().CommitAppearanceIfNeeded();
@@ -511,7 +554,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_StartAndEnd) {
DumpSelectionInfo());
// Paint virtually and clear ShouldInvalidate flag.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" 'foobar', StartAndEnd(1,4), NotInvalidate ",
@@ -531,7 +574,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_StartAndEnd) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, MoveOnSameNode_StartAndEnd_Collapse) {
+TEST_P(LayoutSelectionTest, MoveOnSameNode_StartAndEnd_Collapse) {
const SelectionInDOMTree& selection = SetSelectionTextToBody("f^oob|ar");
Selection().SetSelectionAndEndTyping(selection);
Selection().CommitAppearanceIfNeeded();
@@ -541,7 +584,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_StartAndEnd_Collapse) {
DumpSelectionInfo());
// Paint virtually and clear ShouldInvalidate flag.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" 'foobar', StartAndEnd(1,4), NotInvalidate ",
@@ -560,7 +603,7 @@ TEST_F(LayoutSelectionTest, MoveOnSameNode_StartAndEnd_Collapse) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, ContentEditableButton) {
+TEST_P(LayoutSelectionTest, ContentEditableButton) {
SetBodyContent("<input type=button value=foo contenteditable>");
Selection().SetSelectionAndEndTyping(
SelectionInDOMTree::Builder()
@@ -575,7 +618,7 @@ TEST_F(LayoutSelectionTest, ContentEditableButton) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, ClearSelection) {
+TEST_P(LayoutSelectionTest, ClearSelection) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("<div>f^o|o</div>"));
Selection().CommitAppearanceIfNeeded();
@@ -585,7 +628,7 @@ TEST_F(LayoutSelectionTest, ClearSelection) {
" 'foo', StartAndEnd(1,2), ShouldInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" DIV, Contain, NotInvalidate \n"
@@ -601,7 +644,7 @@ TEST_F(LayoutSelectionTest, ClearSelection) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, SVG) {
+TEST_P(LayoutSelectionTest, SVG) {
const SelectionInDOMTree& selection =
SetSelectionTextToBody("<svg><text x=10 y=10>fo^o|bar</text></svg>");
Selection().SetSelectionAndEndTyping(selection);
@@ -614,7 +657,7 @@ TEST_F(LayoutSelectionTest, SVG) {
" 'foobar', StartAndEnd(2,3), ShouldInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" svg, Contain, NotInvalidate \n"
@@ -637,7 +680,7 @@ TEST_F(LayoutSelectionTest, SVG) {
}
// crbug.com/781705
-TEST_F(LayoutSelectionTest, SVGAncestor) {
+TEST_P(LayoutSelectionTest, SVGAncestor) {
const SelectionInDOMTree& selection = SetSelectionTextToBody(
"<svg><text x=10 y=10><tspan>fo^o|bar</tspan></text></svg>");
Selection().SetSelectionAndEndTyping(selection);
@@ -651,7 +694,7 @@ TEST_F(LayoutSelectionTest, SVGAncestor) {
" 'foobar', StartAndEnd(2,3), ShouldInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" svg, Contain, NotInvalidate \n"
@@ -675,7 +718,7 @@ TEST_F(LayoutSelectionTest, SVGAncestor) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, Embed) {
+TEST_P(LayoutSelectionTest, Embed) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("^<embed type=foobar></embed>|"));
Selection().CommitAppearanceIfNeeded();
@@ -688,7 +731,7 @@ TEST_F(LayoutSelectionTest, Embed) {
}
// http:/crbug.com/843144
-TEST_F(LayoutSelectionTest, Ruby) {
+TEST_P(LayoutSelectionTest, Ruby) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("^<ruby>foo<rt>bar</rt></ruby>|"));
Selection().CommitAppearanceIfNeeded();
@@ -700,7 +743,7 @@ TEST_F(LayoutSelectionTest, Ruby) {
" 'bar', End(0,3), ShouldInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" RUBY, Contain, NotInvalidate \n"
@@ -720,7 +763,7 @@ TEST_F(LayoutSelectionTest, Ruby) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, ClearByRemoveNode) {
+TEST_P(LayoutSelectionTest, ClearByRemoveNode) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("^foo<span>bar</span>baz|"));
Selection().CommitAppearanceIfNeeded();
@@ -741,7 +784,7 @@ TEST_F(LayoutSelectionTest, ClearByRemoveNode) {
" 'bar', Inside(0,3), ShouldInvalidate ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" 'foo', Start(0,3), NotInvalidate \n"
@@ -750,7 +793,7 @@ TEST_F(LayoutSelectionTest, ClearByRemoveNode) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, ClearByRemoveLayoutObject) {
+TEST_P(LayoutSelectionTest, ClearByRemoveLayoutObject) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("^foo<span>bar</span><span>baz</span>|"));
Selection().CommitAppearanceIfNeeded();
@@ -774,7 +817,7 @@ TEST_F(LayoutSelectionTest, ClearByRemoveLayoutObject) {
" SPAN, <null LayoutObject> \n"
" 'baz', <null LayoutObject> ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" 'foo', Start(0,3), NotInvalidate \n"
@@ -785,7 +828,7 @@ TEST_F(LayoutSelectionTest, ClearByRemoveLayoutObject) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, ClearBySlotChange) {
+TEST_P(LayoutSelectionTest, ClearBySlotChange) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("<div>"
"<template data-mode=open>"
@@ -820,7 +863,7 @@ TEST_F(LayoutSelectionTest, ClearBySlotChange) {
" 'bar', <null LayoutObject> ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" DIV, Contain, NotInvalidate \n"
@@ -833,7 +876,7 @@ TEST_F(LayoutSelectionTest, ClearBySlotChange) {
DumpSelectionInfo());
}
-TEST_F(LayoutSelectionTest, MoveNode) {
+TEST_P(LayoutSelectionTest, MoveNode) {
Selection().SetSelectionAndEndTyping(SetSelectionTextToBody(
"<div id='div1'></div><div id='div2'>^foo<b>ba|r</b></div>"));
Selection().CommitAppearanceIfNeeded();
@@ -857,7 +900,7 @@ TEST_F(LayoutSelectionTest, MoveNode) {
" 'bar', <null LayoutObject> ",
DumpSelectionInfo());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, None, NotInvalidate \n"
" DIV, None, NotInvalidate \n"
@@ -869,7 +912,7 @@ TEST_F(LayoutSelectionTest, MoveNode) {
}
// http://crbug.com/870734
-TEST_F(LayoutSelectionTest, InvalidateSlot) {
+TEST_P(LayoutSelectionTest, InvalidateSlot) {
Selection().SetSelectionAndEndTyping(
SetSelectionTextToBody("^<div>"
"<template data-mode=open>"
@@ -877,7 +920,7 @@ TEST_F(LayoutSelectionTest, InvalidateSlot) {
"</template>"
"foo"
"</div>|"));
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" DIV, Contain, NotInvalidate \n"
@@ -902,9 +945,9 @@ static const NGPaintFragment* FindNGPaintFragmentInternal(
const LayoutObject* layout_object) {
if (paint->GetLayoutObject() == layout_object)
return paint;
- for (const auto& child : paint->Children()) {
+ for (const NGPaintFragment* child : paint->Children()) {
if (const NGPaintFragment* child_fragment =
- FindNGPaintFragmentInternal(child.get(), layout_object))
+ FindNGPaintFragmentInternal(child, layout_object))
return child_fragment;
}
return nullptr;
@@ -913,7 +956,7 @@ static const NGPaintFragment* FindNGPaintFragmentInternal(
static const NGPaintFragment& GetNGPaintFragment(
const LayoutObject* layout_object) {
DCHECK(layout_object->IsText());
- LayoutBlockFlow* block_flow = layout_object->EnclosingNGBlockFlow();
+ LayoutBlockFlow* block_flow = layout_object->ContainingNGBlockFlow();
DCHECK(block_flow);
DCHECK(block_flow->IsLayoutNGMixin());
LayoutNGBlockFlow* layout_ng = ToLayoutNGBlockFlow(block_flow);
@@ -924,7 +967,7 @@ static const NGPaintFragment& GetNGPaintFragment(
}
class NGLayoutSelectionTest
- : public LayoutSelectionTest,
+ : public LayoutSelectionTestBase,
private ScopedLayoutNGForTest,
private ScopedPaintUnderInvalidationCheckingForTest {
public:
@@ -979,7 +1022,7 @@ TEST_F(NGLayoutSelectionTest, SelectOnOneText) {
"BODY, Contain, NotInvalidate \n"
" 'foo', None, NotInvalidate \n"
" SPAN, Contain, NotInvalidate \n"
- " 'bar', StartAndEnd(4,5), ShouldInvalidate ",
+ " 'bar', StartAndEnd(1,2), ShouldInvalidate ",
DumpSelectionInfo());
}
@@ -989,7 +1032,7 @@ TEST_F(NGLayoutSelectionTest, FirstLetterInAnotherBlockFlow) {
EXPECT_EQ(
"BODY, Contain, NotInvalidate \n"
" <style> \n"
- " 'foo', StartAndEnd(1,2), ShouldInvalidate \n"
+ " 'foo', StartAndEnd(0,1), ShouldInvalidate \n"
" :first-letter, None(0,1), ShouldInvalidate ",
DumpSelectionInfo());
}
@@ -1113,4 +1156,15 @@ TEST_F(NGLayoutSelectionTest, BRStatus) {
Selection().ComputeLayoutSelectionStatus(GetNGPaintFragment(layout_br)));
}
+// https://crbug.com/907186
+TEST_F(NGLayoutSelectionTest, WBRStatus) {
+ SetSelectionAndUpdateLayoutSelection(
+ "<div style=\"width:0\">^foo<wbr>bar|</div>");
+ const LayoutObject* layout_wbr =
+ GetDocument().QuerySelector("wbr")->GetLayoutObject();
+ EXPECT_EQ(
+ LayoutSelectionStatus(3u, 4u, SelectSoftLineBreak::kSelected),
+ Selection().ComputeLayoutSelectionStatus(GetNGPaintFragment(layout_wbr)));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/link_selection_test.cc b/chromium/third_party/blink/renderer/core/editing/link_selection_test.cc
index c7432c3de3a..9c0d13e7d49 100644
--- a/chromium/third_party/blink/renderer/core/editing/link_selection_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/link_selection_test.cc
@@ -49,7 +49,7 @@ class LinkSelectionTestBase : public testing::Test {
String GetSelectionText();
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
WebViewImpl* web_view_ = nullptr;
Persistent<WebLocalFrameImpl> main_frame_ = nullptr;
};
@@ -59,7 +59,7 @@ void LinkSelectionTestBase::EmulateMouseDrag(const IntPoint& down_point,
int modifiers,
DragFlags drag_flags) {
if (drag_flags & kSendDownEvent) {
- const auto& down_event = FrameTestHelpers::CreateMouseEvent(
+ const auto& down_event = frame_test_helpers::CreateMouseEvent(
WebMouseEvent::kMouseDown, WebMouseEvent::Button::kLeft, down_point,
modifiers);
web_view_->HandleInputEvent(WebCoalescedInputEvent(down_event));
@@ -71,14 +71,14 @@ void LinkSelectionTestBase::EmulateMouseDrag(const IntPoint& down_point,
for (int i = 0; i < kMoveEventsNumber; ++i) {
const auto& move_point =
down_point + Scaled(up_down_vector, i * kMoveIncrementFraction);
- const auto& move_event = FrameTestHelpers::CreateMouseEvent(
+ const auto& move_event = frame_test_helpers::CreateMouseEvent(
WebMouseEvent::kMouseMove, WebMouseEvent::Button::kLeft, move_point,
modifiers);
web_view_->HandleInputEvent(WebCoalescedInputEvent(move_event));
}
if (drag_flags & kSendUpEvent) {
- const auto& up_event = FrameTestHelpers::CreateMouseEvent(
+ const auto& up_event = frame_test_helpers::CreateMouseEvent(
WebMouseEvent::kMouseUp, WebMouseEvent::Button::kLeft, up_point,
modifiers);
web_view_->HandleInputEvent(WebCoalescedInputEvent(up_event));
@@ -89,7 +89,7 @@ void LinkSelectionTestBase::EmulateMouseClick(const IntPoint& click_point,
WebMouseEvent::Button button,
int modifiers,
int count) {
- auto event = FrameTestHelpers::CreateMouseEvent(
+ auto event = frame_test_helpers::CreateMouseEvent(
WebMouseEvent::kMouseDown, button, click_point, modifiers);
event.click_count = count;
web_view_->HandleInputEvent(WebCoalescedInputEvent(event));
@@ -101,7 +101,7 @@ void LinkSelectionTestBase::EmulateMouseDown(const IntPoint& click_point,
WebMouseEvent::Button button,
int modifiers,
int count) {
- auto event = FrameTestHelpers::CreateMouseEvent(
+ auto event = frame_test_helpers::CreateMouseEvent(
WebMouseEvent::kMouseDown, button, click_point, modifiers);
event.click_count = count;
web_view_->HandleInputEvent(WebCoalescedInputEvent(event));
@@ -111,12 +111,11 @@ String LinkSelectionTestBase::GetSelectionText() {
return main_frame_->SelectionAsText();
}
-class TestFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class TestFrameClient : public frame_test_helpers::TestWebFrameClient {
public:
- WebNavigationPolicy DecidePolicyForNavigation(
- const NavigationPolicyInfo& info) override {
- last_policy_ = info.default_policy;
- return kWebNavigationPolicyIgnore;
+ void BeginNavigation(
+ std::unique_ptr<blink::WebNavigationInfo> info) override {
+ last_policy_ = info->navigation_policy;
}
WebNavigationPolicy GetLastNavigationPolicy() const { return last_policy_; }
@@ -135,8 +134,9 @@ class LinkSelectionTest : public LinkSelectionTestBase {
web_view_ = helper_.Initialize(&test_frame_client_);
main_frame_ = web_view_->MainFrameImpl();
- FrameTestHelpers::LoadHTMLString(
- main_frame_, kHTMLString, URLTestHelpers::ToKURL("http://foobar.com"));
+ frame_test_helpers::LoadHTMLString(
+ main_frame_, kHTMLString,
+ url_test_helpers::ToKURL("http://foobar.com"));
web_view_->Resize(WebSize(800, 600));
web_view_->GetPage()->GetFocusController().SetActive(true);
@@ -267,16 +267,17 @@ class LinkSelectionClickEventsTest : public LinkSelectionTestBase {
protected:
class MockEventListener final : public EventListener {
public:
- static MockEventListener* Create() { return new MockEventListener(); }
+ static MockEventListener* Create() {
+ return MakeGarbageCollected<MockEventListener>();
+ }
+
+ MockEventListener() : EventListener(kCPPEventListenerType) {}
bool operator==(const EventListener& other) const final {
return this == &other;
}
- MOCK_METHOD2(handleEvent, void(ExecutionContext* executionContext, Event*));
-
- private:
- MockEventListener() : EventListener(kCPPEventListenerType) {}
+ MOCK_METHOD2(Invoke, void(ExecutionContext* executionContext, Event*));
};
void SetUp() override {
@@ -286,8 +287,9 @@ class LinkSelectionClickEventsTest : public LinkSelectionTestBase {
web_view_ = helper_.Initialize();
main_frame_ = web_view_->MainFrameImpl();
- FrameTestHelpers::LoadHTMLString(
- main_frame_, kHTMLString, URLTestHelpers::ToKURL("http://foobar.com"));
+ frame_test_helpers::LoadHTMLString(
+ main_frame_, kHTMLString,
+ url_test_helpers::ToKURL("http://foobar.com"));
web_view_->Resize(WebSize(800, 600));
web_view_->GetPage()->GetFocusController().SetActive(true);
@@ -310,12 +312,12 @@ class LinkSelectionClickEventsTest : public LinkSelectionTestBase {
} const listeners_cleaner(&element);
MockEventListener* event_handler = MockEventListener::Create();
- element.addEventListener(
- double_click_event ? EventTypeNames::dblclick : EventTypeNames::click,
- event_handler);
+ element.addEventListener(double_click_event ? event_type_names::kDblclick
+ : event_type_names::kClick,
+ event_handler);
testing::InSequence s;
- EXPECT_CALL(*event_handler, handleEvent(_, _)).Times(1);
+ EXPECT_CALL(*event_handler, Invoke(_, _)).Times(1);
const auto& elem_bounds = element.BoundsInViewport();
const int click_count = double_click_event ? 2 : 1;
diff --git a/chromium/third_party/blink/renderer/core/editing/local_caret_rect.cc b/chromium/third_party/blink/renderer/core/editing/local_caret_rect.cc
index fb4046bc08b..04834d9fd3e 100644
--- a/chromium/third_party/blink/renderer/core/editing/local_caret_rect.cc
+++ b/chromium/third_party/blink/renderer/core/editing/local_caret_rect.cc
@@ -178,17 +178,15 @@ LocalCaretRect LocalSelectionRectOfPosition(
template <typename Strategy>
static IntRect AbsoluteCaretBoundsOfAlgorithm(
- const VisiblePositionTemplate<Strategy>& visible_position) {
- DCHECK(visible_position.IsValid()) << visible_position;
- const LocalCaretRect& caret_rect =
- LocalCaretRectOfPosition(visible_position.ToPositionWithAffinity());
+ const PositionWithAffinityTemplate<Strategy>& position) {
+ const LocalCaretRect& caret_rect = LocalCaretRectOfPosition(position);
if (caret_rect.IsEmpty())
return IntRect();
return LocalToAbsoluteQuadOf(caret_rect).EnclosingBoundingBox();
}
-IntRect AbsoluteCaretBoundsOf(const VisiblePosition& visible_position) {
- return AbsoluteCaretBoundsOfAlgorithm<EditingStrategy>(visible_position);
+IntRect AbsoluteCaretBoundsOf(const PositionWithAffinity& position) {
+ return AbsoluteCaretBoundsOfAlgorithm<EditingStrategy>(position);
}
// TODO(editing-dev): This function does pretty much the same thing as
@@ -223,10 +221,8 @@ IntRect AbsoluteSelectionBoundsOf(const VisiblePosition& visible_position) {
return AbsoluteSelectionBoundsOfAlgorithm<EditingStrategy>(visible_position);
}
-IntRect AbsoluteCaretBoundsOf(
- const VisiblePositionInFlatTree& visible_position) {
- return AbsoluteCaretBoundsOfAlgorithm<EditingInFlatTreeStrategy>(
- visible_position);
+IntRect AbsoluteCaretBoundsOf(const PositionInFlatTreeWithAffinity& position) {
+ return AbsoluteCaretBoundsOfAlgorithm<EditingInFlatTreeStrategy>(position);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/local_caret_rect.h b/chromium/third_party/blink/renderer/core/editing/local_caret_rect.h
index e8e8dc78310..ba6101c33a4 100644
--- a/chromium/third_party/blink/renderer/core/editing/local_caret_rect.h
+++ b/chromium/third_party/blink/renderer/core/editing/local_caret_rect.h
@@ -39,8 +39,9 @@ LocalCaretRectOfPosition(const PositionInFlatTreeWithAffinity&);
LocalCaretRect LocalSelectionRectOfPosition(const PositionWithAffinity&);
// Bounds of (possibly transformed) caret in absolute coords
-CORE_EXPORT IntRect AbsoluteCaretBoundsOf(const VisiblePosition&);
-CORE_EXPORT IntRect AbsoluteCaretBoundsOf(const VisiblePositionInFlatTree&);
+CORE_EXPORT IntRect AbsoluteCaretBoundsOf(const PositionWithAffinity&);
+CORE_EXPORT IntRect
+AbsoluteCaretBoundsOf(const PositionInFlatTreeWithAffinity&);
IntRect AbsoluteCaretRectOfPosition(
const PositionWithAffinity&,
diff --git a/chromium/third_party/blink/renderer/core/editing/local_caret_rect_test.cc b/chromium/third_party/blink/renderer/core/editing/local_caret_rect_test.cc
index ab9e521f808..efe0a2aa616 100644
--- a/chromium/third_party/blink/renderer/core/editing/local_caret_rect_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/local_caret_rect_test.cc
@@ -812,10 +812,11 @@ TEST_P(ParameterizedLocalCaretRectTest, AbsoluteCaretBoundsOfWithShadowDOM) {
Element* body = GetDocument().body();
Element* one = body->QuerySelector("#one");
- IntRect bounds_in_dom_tree =
- AbsoluteCaretBoundsOf(CreateVisiblePosition(Position(one, 0)));
+ IntRect bounds_in_dom_tree = AbsoluteCaretBoundsOf(
+ CreateVisiblePosition(Position(one, 0)).ToPositionWithAffinity());
IntRect bounds_in_flat_tree =
- AbsoluteCaretBoundsOf(CreateVisiblePosition(PositionInFlatTree(one, 0)));
+ AbsoluteCaretBoundsOf(CreateVisiblePosition(PositionInFlatTree(one, 0))
+ .ToPositionWithAffinity());
EXPECT_FALSE(bounds_in_dom_tree.IsEmpty());
EXPECT_EQ(bounds_in_dom_tree, bounds_in_flat_tree);
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc
index e9b56b43b49..0af406cc024 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc
@@ -91,13 +91,13 @@ DocumentMarkerList* CreateListForType(DocumentMarker::MarkerType type) {
case DocumentMarker::kComposition:
return new CompositionMarkerListImpl();
case DocumentMarker::kSpelling:
- return new SpellingMarkerListImpl();
+ return MakeGarbageCollected<SpellingMarkerListImpl>();
case DocumentMarker::kGrammar:
- return new GrammarMarkerListImpl();
+ return MakeGarbageCollected<GrammarMarkerListImpl>();
case DocumentMarker::kSuggestion:
- return new SuggestionMarkerListImpl();
+ return MakeGarbageCollected<SuggestionMarkerListImpl>();
case DocumentMarker::kTextMatch:
- return new TextMatchMarkerListImpl();
+ return MakeGarbageCollected<TextMatchMarkerListImpl>();
}
NOTREACHED();
@@ -154,14 +154,16 @@ void DocumentMarkerController::Clear() {
void DocumentMarkerController::AddSpellingMarker(const EphemeralRange& range,
const String& description) {
AddMarkerInternal(range, [&description](int start_offset, int end_offset) {
- return new SpellingMarker(start_offset, end_offset, description);
+ return MakeGarbageCollected<SpellingMarker>(start_offset, end_offset,
+ description);
});
}
void DocumentMarkerController::AddGrammarMarker(const EphemeralRange& range,
const String& description) {
AddMarkerInternal(range, [&description](int start_offset, int end_offset) {
- return new GrammarMarker(start_offset, end_offset, description);
+ return MakeGarbageCollected<GrammarMarker>(start_offset, end_offset,
+ description);
});
}
@@ -170,7 +172,8 @@ void DocumentMarkerController::AddTextMatchMarker(
TextMatchMarker::MatchStatus match_status) {
DCHECK(!document_->NeedsLayoutTreeUpdate());
AddMarkerInternal(range, [match_status](int start_offset, int end_offset) {
- return new TextMatchMarker(start_offset, end_offset, match_status);
+ return MakeGarbageCollected<TextMatchMarker>(start_offset, end_offset,
+ match_status);
});
// Don't invalidate tickmarks here. TextFinder invalidates tickmarks using a
// throttling algorithm. crbug.com/6819.
@@ -206,10 +209,10 @@ void DocumentMarkerController::AddSuggestionMarker(
const EphemeralRange& range,
const SuggestionMarkerProperties& properties) {
DCHECK(!document_->NeedsLayoutTreeUpdate());
- AddMarkerInternal(
- range, [this, &properties](int start_offset, int end_offset) {
- return new SuggestionMarker(start_offset, end_offset, properties);
- });
+ AddMarkerInternal(range, [&properties](int start_offset, int end_offset) {
+ return MakeGarbageCollected<SuggestionMarker>(start_offset, end_offset,
+ properties);
+ });
}
void DocumentMarkerController::PrepareForDestruction() {
@@ -283,7 +286,7 @@ void DocumentMarkerController::AddMarkerToNode(const Text& text,
Member<MarkerLists>& markers =
markers_.insert(&text, nullptr).stored_value->value;
if (!markers) {
- markers = new MarkerLists;
+ markers = MakeGarbageCollected<MarkerLists>();
markers->Grow(DocumentMarker::kMarkerTypeIndexesCount);
}
@@ -314,8 +317,8 @@ void DocumentMarkerController::MoveMarkers(const Text& src_node,
return;
if (!markers_.Contains(&dst_node)) {
- markers_.insert(&dst_node,
- new MarkerLists(DocumentMarker::kMarkerTypeIndexesCount));
+ markers_.insert(&dst_node, MakeGarbageCollected<MarkerLists>(
+ DocumentMarker::kMarkerTypeIndexesCount));
}
MarkerLists* const dst_markers = markers_.at(&dst_node);
@@ -398,13 +401,11 @@ DocumentMarker* DocumentMarkerController::FirstMarkerAroundPosition(
return nullptr;
const PositionInFlatTree start_of_word_or_null =
- StartOfWord(CreateVisiblePosition(position), kPreviousWordIfOnBoundary)
- .DeepEquivalent();
+ StartOfWordPosition(position, kPreviousWordIfOnBoundary);
const PositionInFlatTree start =
start_of_word_or_null.IsNotNull() ? start_of_word_or_null : position;
const PositionInFlatTree end_of_word_or_null =
- EndOfWord(CreateVisiblePosition(position), kNextWordIfOnBoundary)
- .DeepEquivalent();
+ EndOfWordPosition(position, kNextWordIfOnBoundary);
const PositionInFlatTree end =
end_of_word_or_null.IsNotNull() ? end_of_word_or_null : position;
@@ -784,6 +785,29 @@ void DocumentMarkerController::RemoveSpellingMarkersUnderWords(
}
}
+void DocumentMarkerController::RemoveSuggestionMarkerInRangeOnFinish(
+ const EphemeralRangeInFlatTree& range) {
+ // MarkersIntersectingRange() might be expensive. In practice, we hope we will
+ // only check one node for composing range.
+ const HeapVector<std::pair<Member<Node>, Member<DocumentMarker>>>&
+ node_marker_pairs = MarkersIntersectingRange(
+ range, DocumentMarker::MarkerTypes::Suggestion());
+ for (const auto& node_marker_pair : node_marker_pairs) {
+ SuggestionMarker* suggestion_marker =
+ ToSuggestionMarker(node_marker_pair.second);
+ if (suggestion_marker->NeedsRemovalOnFinishComposing()) {
+ const Text& text = ToText(*node_marker_pair.first);
+ DocumentMarkerList* const list =
+ ListForType(markers_.at(&text), DocumentMarker::kSuggestion);
+ // RemoveMarkerByTag() might be expensive. In practice, we have at most
+ // one suggestion marker needs to be removed.
+ ToSuggestionMarkerListImpl(list)->RemoveMarkerByTag(
+ suggestion_marker->Tag());
+ InvalidatePaintForNode(text);
+ }
+ }
+}
+
void DocumentMarkerController::RemoveSuggestionMarkerByTag(const Text& text,
int32_t marker_tag) {
MarkerLists* markers = markers_.at(&text);
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.h b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.h
index 63e6b805b67..6511198d910 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.h
@@ -86,6 +86,8 @@ class CORE_EXPORT DocumentMarkerController final
DocumentMarker::MarkerTypes = DocumentMarker::MarkerTypes::All());
void RemoveSpellingMarkersUnderWords(const Vector<String>& words);
void RemoveSuggestionMarkerByTag(const Text&, int32_t marker_tag);
+ // Removes suggestion marker with |RemoveOnFinishComposing::kRemove|.
+ void RemoveSuggestionMarkerInRangeOnFinish(const EphemeralRangeInFlatTree&);
void RepaintMarkers(
DocumentMarker::MarkerTypes = DocumentMarker::MarkerTypes::All());
// Returns true if markers within a range are found.
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller_test.cc
index 3474937f4a4..f389a04493a 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller_test.cc
@@ -219,7 +219,7 @@ TEST_F(DocumentMarkerControllerTest, UpdateRenderedRects) {
MarkerController().LayoutRectsForTextMatchMarkers();
EXPECT_EQ(1u, rendered_rects.size());
- div->setAttribute(HTMLNames::styleAttr, "margin: 200px");
+ div->setAttribute(html_names::kStyleAttr, "margin: 200px");
GetDocument().UpdateStyleAndLayout();
Vector<IntRect> new_rendered_rects =
MarkerController().LayoutRectsForTextMatchMarkers();
@@ -370,6 +370,45 @@ TEST_F(DocumentMarkerControllerTest, RemoveSuggestionMarkerByTag) {
EXPECT_EQ(0u, MarkerController().Markers().size());
}
+TEST_F(DocumentMarkerControllerTest, RemoveSuggestionMarkerInRangeOnFinish) {
+ SetBodyContent("<div contenteditable>foo</div>");
+ Element* div = GetDocument().QuerySelector("div");
+ Node* text = div->firstChild();
+
+ // Add a regular suggestion marker, RemoveSuggestionMarkerInRangeOnFinish()
+ // should not remove it.
+ MarkerController().AddSuggestionMarker(
+ EphemeralRange(Position(text, 0), Position(text, 2)),
+ SuggestionMarkerProperties());
+
+ ASSERT_EQ(1u, MarkerController().Markers().size());
+ MarkerController().RemoveSuggestionMarkerInRangeOnFinish(
+ EphemeralRangeInFlatTree(PositionInFlatTree(text, 0),
+ PositionInFlatTree(text, 2)));
+
+ EXPECT_EQ(1u, MarkerController().Markers().size());
+
+ const SuggestionMarker& marker =
+ *ToSuggestionMarker(MarkerController().Markers()[0]);
+ MarkerController().RemoveSuggestionMarkerByTag(*ToText(text), marker.Tag());
+ ASSERT_EQ(0u, MarkerController().Markers().size());
+
+ // Add a suggestion marker which need to be removed after finish composing,
+ // RemoveSuggestionMarkerInRangeOnFinish() should remove it.
+ MarkerController().AddSuggestionMarker(
+ EphemeralRange(Position(text, 0), Position(text, 2)),
+ SuggestionMarkerProperties::Builder()
+ .SetRemoveOnFinishComposing(true)
+ .Build());
+
+ ASSERT_EQ(1u, MarkerController().Markers().size());
+
+ MarkerController().RemoveSuggestionMarkerInRangeOnFinish(
+ EphemeralRangeInFlatTree(PositionInFlatTree(text, 0),
+ PositionInFlatTree(text, 2)));
+ EXPECT_EQ(0u, MarkerController().Markers().size());
+}
+
TEST_F(DocumentMarkerControllerTest, FirstMarkerIntersectingOffsetRange) {
SetBodyContent("<div contenteditable>123456789</div>");
GetDocument().UpdateStyleAndLayout();
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_test.cc
index c2d7b400806..3c28e199dbd 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/document_marker_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/document_marker_test.cc
@@ -14,8 +14,8 @@ using MarkerOffsets = DocumentMarker::MarkerOffsets;
class DocumentMarkerTest : public testing::Test {
protected:
DocumentMarker* CreateMarker(unsigned startOffset, unsigned endOffset) {
- return new TextMatchMarker(startOffset, endOffset,
- TextMatchMarker::MatchStatus::kInactive);
+ return MakeGarbageCollected<TextMatchMarker>(
+ startOffset, endOffset, TextMatchMarker::MatchStatus::kInactive);
}
};
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_list_impl_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_list_impl_test.cc
index 29192ae4191..00c87cafac5 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_list_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_list_impl_test.cc
@@ -15,7 +15,8 @@ namespace blink {
class GrammarMarkerListImplTest : public testing::Test {
protected:
- GrammarMarkerListImplTest() : marker_list_(new GrammarMarkerListImpl()) {}
+ GrammarMarkerListImplTest()
+ : marker_list_(MakeGarbageCollected<GrammarMarkerListImpl>()) {}
Persistent<GrammarMarkerListImpl> marker_list_;
};
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_test.cc
index c7c11974326..6fd426241ae 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/grammar_marker_test.cc
@@ -13,17 +13,20 @@ const char* const kDescription = "Test description";
class GrammarMarkerTest : public testing::Test {};
TEST_F(GrammarMarkerTest, MarkerType) {
- DocumentMarker* marker = new GrammarMarker(0, 1, kDescription);
+ DocumentMarker* marker =
+ MakeGarbageCollected<GrammarMarker>(0, 1, kDescription);
EXPECT_EQ(DocumentMarker::kGrammar, marker->GetType());
}
TEST_F(GrammarMarkerTest, IsSpellCheckMarker) {
- DocumentMarker* marker = new GrammarMarker(0, 1, kDescription);
+ DocumentMarker* marker =
+ MakeGarbageCollected<GrammarMarker>(0, 1, kDescription);
EXPECT_TRUE(IsSpellCheckMarker(*marker));
}
TEST_F(GrammarMarkerTest, ConstructorAndGetters) {
- GrammarMarker* marker = new GrammarMarker(0, 1, kDescription);
+ GrammarMarker* marker =
+ MakeGarbageCollected<GrammarMarker>(0, 1, kDescription);
EXPECT_EQ(kDescription, marker->Description());
}
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/sorted_document_marker_list_editor_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/sorted_document_marker_list_editor_test.cc
index ac2da857338..ee01aa82dc7 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/sorted_document_marker_list_editor_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/sorted_document_marker_list_editor_test.cc
@@ -12,8 +12,8 @@ namespace blink {
class SortedDocumentMarkerListEditorTest : public testing::Test {
protected:
DocumentMarker* CreateMarker(unsigned startOffset, unsigned endOffset) {
- return new TextMatchMarker(startOffset, endOffset,
- TextMatchMarker::MatchStatus::kInactive);
+ return MakeGarbageCollected<TextMatchMarker>(
+ startOffset, endOffset, TextMatchMarker::MatchStatus::kInactive);
}
};
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_list_impl_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_list_impl_test.cc
index 2b2a4af8b2c..dc9f972211b 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_list_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_list_impl_test.cc
@@ -16,10 +16,12 @@ namespace blink {
class SpellingMarkerListImplTest : public testing::Test {
protected:
- SpellingMarkerListImplTest() : marker_list_(new SpellingMarkerListImpl()) {}
+ SpellingMarkerListImplTest()
+ : marker_list_(MakeGarbageCollected<SpellingMarkerListImpl>()) {}
DocumentMarker* CreateMarker(unsigned start_offset, unsigned end_offset) {
- return new SpellingMarker(start_offset, end_offset, g_empty_string);
+ return MakeGarbageCollected<SpellingMarker>(start_offset, end_offset,
+ g_empty_string);
}
Persistent<SpellingMarkerListImpl> marker_list_;
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_test.cc
index f7e868ac199..912779866c2 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/spelling_marker_test.cc
@@ -13,17 +13,20 @@ const char* const kTestDescription = "Test description";
class SpellingMarkerTest : public testing::Test {};
TEST_F(SpellingMarkerTest, MarkerType) {
- DocumentMarker* marker = new SpellingMarker(0, 1, kTestDescription);
+ DocumentMarker* marker =
+ MakeGarbageCollected<SpellingMarker>(0, 1, kTestDescription);
EXPECT_EQ(DocumentMarker::kSpelling, marker->GetType());
}
TEST_F(SpellingMarkerTest, IsSpellCheckMarker) {
- DocumentMarker* marker = new SpellingMarker(0, 1, kTestDescription);
+ DocumentMarker* marker =
+ MakeGarbageCollected<SpellingMarker>(0, 1, kTestDescription);
EXPECT_TRUE(IsSpellCheckMarker(*marker));
}
TEST_F(SpellingMarkerTest, ConstructorAndGetters) {
- SpellingMarker* marker = new SpellingMarker(0, 1, kTestDescription);
+ SpellingMarker* marker =
+ MakeGarbageCollected<SpellingMarker>(0, 1, kTestDescription);
EXPECT_EQ(kTestDescription, marker->Description());
}
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.cc b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.cc
index 2bc08704e06..57b25336eec 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.cc
@@ -21,6 +21,7 @@ SuggestionMarker::SuggestionMarker(unsigned start_offset,
tag_(NextTag()),
suggestions_(properties.Suggestions()),
suggestion_type_(properties.Type()),
+ remove_on_finish_composing_(properties.RemoveOnFinishComposing()),
suggestion_highlight_color_(properties.HighlightColor()) {
DCHECK_GT(tag_, 0);
}
@@ -41,6 +42,10 @@ bool SuggestionMarker::IsMisspelling() const {
return suggestion_type_ == SuggestionType::kMisspelling;
}
+bool SuggestionMarker::NeedsRemovalOnFinishComposing() const {
+ return remove_on_finish_composing_ == RemoveOnFinishComposing::kRemove;
+}
+
Color SuggestionMarker::SuggestionHighlightColor() const {
return suggestion_highlight_color_;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.h b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.h
index 3289450d94a..81d0d0b9b12 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker.h
@@ -20,6 +20,7 @@ class SuggestionMarkerProperties;
class CORE_EXPORT SuggestionMarker final : public StyleableMarker {
public:
enum class SuggestionType { kMisspelling, kNotMisspelling };
+ enum class RemoveOnFinishComposing { kRemove, kDoNotRemove };
SuggestionMarker(unsigned start_offset,
unsigned end_offset,
@@ -32,6 +33,7 @@ class CORE_EXPORT SuggestionMarker final : public StyleableMarker {
int32_t Tag() const;
const Vector<String>& Suggestions() const;
bool IsMisspelling() const;
+ bool NeedsRemovalOnFinishComposing() const;
Color SuggestionHighlightColor() const;
// Replace the suggestion at suggestion_index with new_suggestion.
@@ -47,6 +49,7 @@ class CORE_EXPORT SuggestionMarker final : public StyleableMarker {
const int32_t tag_;
Vector<String> suggestions_;
const SuggestionType suggestion_type_;
+ const RemoveOnFinishComposing remove_on_finish_composing_;
const Color suggestion_highlight_color_;
DISALLOW_COPY_AND_ASSIGN(SuggestionMarker);
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl.cc b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl.cc
index 3e02a14d49b..12300ae9ab0 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl.cc
@@ -34,7 +34,7 @@ ComputeOffsetsAfterNonSuggestionEditingOperating(const DocumentMarker& marker,
// Text inserted/replaced immediately after the marker, remove marker if first
// character is a (Unicode) letter or digit
if (offset == marker_end && new_length > 0) {
- if (WTF::Unicode::IsAlphanumeric(GetCodePointAt(node_text, offset)))
+ if (WTF::unicode::IsAlphanumeric(GetCodePointAt(node_text, offset)))
return {};
return marker.ComputeOffsetsAfterShift(offset, old_length, new_length);
}
@@ -42,7 +42,7 @@ ComputeOffsetsAfterNonSuggestionEditingOperating(const DocumentMarker& marker,
// Text inserted/replaced immediately before the marker, remove marker if
// first character is a (Unicode) letter or digit
if (offset == marker_start && new_length > 0) {
- if (WTF::Unicode::IsAlphanumeric(
+ if (WTF::unicode::IsAlphanumeric(
GetCodePointAt(node_text, offset + new_length - 1)))
return {};
return marker.ComputeOffsetsAfterShift(offset, old_length, new_length);
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl_test.cc
index e3d79276ebc..a994e4dca17 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_list_impl_test.cc
@@ -16,11 +16,11 @@ namespace blink {
class SuggestionMarkerListImplTest : public testing::Test {
protected:
SuggestionMarkerListImplTest()
- : marker_list_(new SuggestionMarkerListImpl()) {}
+ : marker_list_(MakeGarbageCollected<SuggestionMarkerListImpl>()) {}
SuggestionMarker* CreateMarker(unsigned start_offset, unsigned end_offset) {
- return new SuggestionMarker(start_offset, end_offset,
- SuggestionMarkerProperties());
+ return MakeGarbageCollected<SuggestionMarker>(start_offset, end_offset,
+ SuggestionMarkerProperties());
}
Persistent<SuggestionMarkerListImpl> marker_list_;
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.cc b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.cc
index b83a3d8f790..414c6968da5 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.cc
@@ -28,6 +28,16 @@ SuggestionMarkerProperties::Builder::SetType(
}
SuggestionMarkerProperties::Builder&
+SuggestionMarkerProperties::Builder::SetRemoveOnFinishComposing(
+ bool remove_on_finish_composing) {
+ data_.remove_on_finish_composing_ =
+ remove_on_finish_composing
+ ? SuggestionMarker::RemoveOnFinishComposing::kRemove
+ : SuggestionMarker::RemoveOnFinishComposing::kDoNotRemove;
+ return *this;
+}
+
+SuggestionMarkerProperties::Builder&
SuggestionMarkerProperties::Builder::SetSuggestions(
const Vector<String>& suggestions) {
data_.suggestions_ = suggestions;
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.h b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.h
index 474a9b4c001..3fe4bc29b91 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_properties.h
@@ -25,6 +25,9 @@ class CORE_EXPORT SuggestionMarkerProperties final {
SuggestionMarkerProperties();
SuggestionMarker::SuggestionType Type() const { return type_; }
+ SuggestionMarker::RemoveOnFinishComposing RemoveOnFinishComposing() const {
+ return remove_on_finish_composing_;
+ }
Vector<String> Suggestions() const { return suggestions_; }
Color HighlightColor() const { return highlight_color_; }
Color UnderlineColor() const { return underline_color_; }
@@ -34,6 +37,8 @@ class CORE_EXPORT SuggestionMarkerProperties final {
private:
SuggestionMarker::SuggestionType type_ =
SuggestionMarker::SuggestionType::kNotMisspelling;
+ SuggestionMarker::RemoveOnFinishComposing remove_on_finish_composing_ =
+ SuggestionMarker::RemoveOnFinishComposing::kDoNotRemove;
Vector<String> suggestions_;
Color highlight_color_ = Color::kTransparent;
Color underline_color_ = Color::kTransparent;
@@ -52,6 +57,7 @@ class CORE_EXPORT SuggestionMarkerProperties::Builder final {
SuggestionMarkerProperties Build() const;
Builder& SetType(SuggestionMarker::SuggestionType);
+ Builder& SetRemoveOnFinishComposing(bool);
Builder& SetSuggestions(const Vector<String>& suggestions);
Builder& SetHighlightColor(Color);
Builder& SetUnderlineColor(Color);
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_test.cc
index da117c89f30..f5e81d7a847 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_test.cc
@@ -12,20 +12,20 @@ namespace blink {
class SuggestionMarkerTest : public testing::Test {};
TEST_F(SuggestionMarkerTest, MarkerType) {
- DocumentMarker* marker =
- new SuggestionMarker(0, 1, SuggestionMarkerProperties());
+ DocumentMarker* marker = MakeGarbageCollected<SuggestionMarker>(
+ 0, 1, SuggestionMarkerProperties());
EXPECT_EQ(DocumentMarker::kSuggestion, marker->GetType());
}
TEST_F(SuggestionMarkerTest, IsStyleableMarker) {
- DocumentMarker* marker =
- new SuggestionMarker(0, 1, SuggestionMarkerProperties());
+ DocumentMarker* marker = MakeGarbageCollected<SuggestionMarker>(
+ 0, 1, SuggestionMarkerProperties());
EXPECT_TRUE(IsStyleableMarker(*marker));
}
TEST_F(SuggestionMarkerTest, ConstructorAndGetters) {
Vector<String> suggestions = {"this", "that"};
- SuggestionMarker* marker = new SuggestionMarker(
+ SuggestionMarker* marker = MakeGarbageCollected<SuggestionMarker>(
0, 1,
SuggestionMarkerProperties::Builder()
.SetType(SuggestionMarker::SuggestionType::kNotMisspelling)
@@ -42,7 +42,7 @@ TEST_F(SuggestionMarkerTest, ConstructorAndGetters) {
EXPECT_TRUE(marker->HasThicknessThin());
EXPECT_EQ(Color::kGray, marker->BackgroundColor());
- SuggestionMarker* marker2 = new SuggestionMarker(
+ SuggestionMarker* marker2 = MakeGarbageCollected<SuggestionMarker>(
0, 1,
SuggestionMarkerProperties::Builder()
.SetType(SuggestionMarker::SuggestionType::kMisspelling)
@@ -56,11 +56,11 @@ TEST_F(SuggestionMarkerTest, ConstructorAndGetters) {
TEST_F(SuggestionMarkerTest, SetSuggestion) {
Vector<String> suggestions = {"this", "that"};
- SuggestionMarker* marker =
- new SuggestionMarker(0, 1,
- SuggestionMarkerProperties::Builder()
- .SetSuggestions(suggestions)
- .Build());
+ SuggestionMarker* marker = MakeGarbageCollected<SuggestionMarker>(
+ 0, 1,
+ SuggestionMarkerProperties::Builder()
+ .SetSuggestions(suggestions)
+ .Build());
marker->SetSuggestion(1, "these");
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl_test.cc
index 544e07eab33..6dbd5f570ca 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl_test.cc
@@ -11,11 +11,12 @@ namespace blink {
class TextMatchMarkerListImplTest : public EditingTestBase {
protected:
- TextMatchMarkerListImplTest() : marker_list_(new TextMatchMarkerListImpl()) {}
+ TextMatchMarkerListImplTest()
+ : marker_list_(MakeGarbageCollected<TextMatchMarkerListImpl>()) {}
DocumentMarker* CreateMarker(unsigned start_offset, unsigned end_offset) {
- return new TextMatchMarker(start_offset, end_offset,
- TextMatchMarker::MatchStatus::kInactive);
+ return MakeGarbageCollected<TextMatchMarker>(
+ start_offset, end_offset, TextMatchMarker::MatchStatus::kInactive);
}
Persistent<TextMatchMarkerListImpl> marker_list_;
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/unsorted_document_marker_list_editor_test.cc b/chromium/third_party/blink/renderer/core/editing/markers/unsorted_document_marker_list_editor_test.cc
index 2783c293fa1..71bc279b670 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/unsorted_document_marker_list_editor_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/unsorted_document_marker_list_editor_test.cc
@@ -16,12 +16,13 @@ namespace blink {
class UnsortedDocumentMarkerListEditorTest : public testing::Test {
public:
UnsortedDocumentMarkerListEditorTest()
- : marker_list_(new HeapVector<Member<DocumentMarker>>) {}
+ : marker_list_(
+ MakeGarbageCollected<HeapVector<Member<DocumentMarker>>>()) {}
protected:
DocumentMarker* CreateMarker(unsigned start_offset, unsigned end_offset) {
- return new SuggestionMarker(start_offset, end_offset,
- SuggestionMarkerProperties());
+ return MakeGarbageCollected<SuggestionMarker>(start_offset, end_offset,
+ SuggestionMarkerProperties());
}
Persistent<HeapVector<Member<DocumentMarker>>> marker_list_;
@@ -40,7 +41,8 @@ TEST_F(UnsortedDocumentMarkerListEditorTest, MoveMarkers) {
marker_list_->push_back(CreateMarker(10, 20));
marker_list_->push_back(CreateMarker(11, 21));
- DocumentMarkerList* dst_list = new SuggestionMarkerListImpl();
+ DocumentMarkerList* dst_list =
+ MakeGarbageCollected<SuggestionMarkerListImpl>();
// The markers with start and end offset < 11 should be moved to dst_list.
// Markers that start before 11 and end at 11 or later should be removed.
// Markers that start at 11 or later should not be moved.
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_adjuster.cc b/chromium/third_party/blink/renderer/core/editing/selection_adjuster.cc
index 30f3881e094..fd8ec161aae 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_adjuster.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_adjuster.cc
@@ -127,8 +127,9 @@ class GranularityAdjuster final {
// kNextWordIfOnBoundary);
const VisiblePositionTemplate<Strategy> visible_start =
CreateVisiblePosition(passed_start);
- return StartOfWord(visible_start, ChooseWordSide(visible_start))
- .DeepEquivalent();
+ const PositionTemplate<Strategy> word_start = StartOfWordPosition(
+ passed_start.GetPosition(), ChooseWordSide(visible_start));
+ return CreateVisiblePosition(word_start).DeepEquivalent();
}
case TextGranularity::kSentence:
return StartOfSentence(CreateVisiblePosition(passed_start))
@@ -185,7 +186,8 @@ class GranularityAdjuster final {
const VisiblePositionTemplate<Strategy> original_end =
CreateVisiblePosition(passed_end);
const VisiblePositionTemplate<Strategy> word_end =
- EndOfWord(original_end, ChooseWordSide(original_end));
+ CreateVisiblePosition(EndOfWordPosition(
+ passed_end.GetPosition(), ChooseWordSide(original_end)));
if (!IsEndOfParagraph(original_end))
return word_end.DeepEquivalent();
if (IsEmptyTableCell(start.AnchorNode()))
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_controller.cc b/chromium/third_party/blink/renderer/core/editing/selection_controller.cc
index 2ce469c54de..2a7adcfd18e 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_controller.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_controller.cc
@@ -61,7 +61,7 @@
namespace blink {
SelectionController* SelectionController::Create(LocalFrame& frame) {
- return new SelectionController(frame);
+ return MakeGarbageCollected<SelectionController>(frame);
}
SelectionController::SelectionController(LocalFrame& frame)
@@ -84,7 +84,7 @@ DispatchEventResult DispatchSelectStart(Node* node) {
return DispatchEventResult::kNotCanceled;
return node->DispatchEvent(
- *Event::CreateCancelableBubble(EventTypeNames::selectstart));
+ *Event::CreateCancelableBubble(event_type_names::kSelectstart));
}
SelectionInFlatTree ExpandSelectionToRespectUserSelectAll(
@@ -123,11 +123,11 @@ bool CanMouseDownStartSelect(Node* node) {
return true;
}
-VisiblePositionInFlatTree VisiblePositionOfHitTestResult(
+PositionInFlatTreeWithAffinity PositionWithAffinityOfHitTestResult(
const HitTestResult& hit_test_result) {
- return CreateVisiblePosition(FromPositionInDOMTree<EditingInFlatTreeStrategy>(
+ return FromPositionInDOMTree<EditingInFlatTreeStrategy>(
hit_test_result.InnerNode()->GetLayoutObject()->PositionForPoint(
- hit_test_result.LocalPoint())));
+ hit_test_result.LocalPoint()));
}
DocumentMarker* SpellCheckMarkerAtPosition(
@@ -307,8 +307,8 @@ bool SelectionController::HandleSingleClick(
// link or image.
bool extend_selection = IsExtendingSelection(event);
- const VisiblePositionInFlatTree& visible_hit_position =
- VisiblePositionOfHitTestResult(event.GetHitTestResult());
+ const VisiblePositionInFlatTree& visible_hit_position = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(event.GetHitTestResult()));
const PositionInFlatTreeWithAffinity& position_to_use =
visible_hit_position.IsNull()
? CreateVisiblePosition(
@@ -581,7 +581,7 @@ static bool IsEmptyWordRange(const EphemeralRangeInFlatTree range) {
.SetEmitsObjectReplacementCharacter(
HasEditableStyle(*range.StartPosition().AnchorNode()))
.Build());
- return str.IsEmpty() || str.SimplifyWhiteSpace().ContainsOnlyWhitespace();
+ return str.SimplifyWhiteSpace().ContainsOnlyWhitespaceOrEmpty();
}
bool SelectionController::SelectClosestWordFromHitTestResult(
@@ -604,8 +604,8 @@ bool SelectionController::SelectClosestWordFromHitTestResult(
adjusted_hit_test_result.SetNodeAndPosition(result.InnerNode(),
LayoutPoint(0, 0));
- const VisiblePositionInFlatTree& pos =
- VisiblePositionOfHitTestResult(adjusted_hit_test_result);
+ const VisiblePositionInFlatTree& pos = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(adjusted_hit_test_result));
const VisibleSelectionInFlatTree& new_selection =
pos.IsNotNull() ? CreateVisibleSelectionWithGranularity(
SelectionInFlatTree::Builder()
@@ -657,7 +657,8 @@ void SelectionController::SelectClosestMisspellingFromHitTestResult(
if (!inner_node || !inner_node->GetLayoutObject())
return;
- const VisiblePositionInFlatTree& pos = VisiblePositionOfHitTestResult(result);
+ const VisiblePositionInFlatTree& pos =
+ CreateVisiblePosition(PositionWithAffinityOfHitTestResult(result));
if (pos.IsNull()) {
UpdateSelectionForMouseDownDispatchingSelectStart(
inner_node, SelectionInFlatTree(),
@@ -743,8 +744,8 @@ void SelectionController::SelectClosestWordOrLinkFromMouseEvent(
return;
Element* url_element = result.GetHitTestResult().URLElement();
- const VisiblePositionInFlatTree pos =
- VisiblePositionOfHitTestResult(result.GetHitTestResult());
+ const VisiblePositionInFlatTree& pos = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(result.GetHitTestResult()));
const SelectionInFlatTree& new_selection =
pos.IsNotNull() &&
pos.DeepEquivalent().AnchorNode()->IsDescendantOf(url_element)
@@ -842,8 +843,8 @@ void SelectionController::SetCaretAtHitTestResult(
const HitTestResult& hit_test_result) {
Node* inner_node = hit_test_result.InnerNode();
DCHECK(inner_node);
- const VisiblePositionInFlatTree& visible_hit_pos =
- VisiblePositionOfHitTestResult(hit_test_result);
+ const VisiblePositionInFlatTree& visible_hit_pos = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(hit_test_result));
const VisiblePositionInFlatTree& visible_pos =
visible_hit_pos.IsNull()
? CreateVisiblePosition(
@@ -918,8 +919,8 @@ bool SelectionController::HandleTripleClick(
mouse_down_may_start_select_))
return false;
- const VisiblePositionInFlatTree& pos =
- VisiblePositionOfHitTestResult(event.GetHitTestResult());
+ const VisiblePositionInFlatTree& pos = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(event.GetHitTestResult()));
const VisibleSelectionInFlatTree new_selection =
pos.IsNotNull() ? CreateVisibleSelectionWithGranularity(
SelectionInFlatTree::Builder()
@@ -989,7 +990,6 @@ void SelectionController::HandleMouseDraggedEvent(
if (!Selection().IsAvailable())
return;
if (selection_state_ != SelectionState::kExtendedSelection) {
- frame_->LocalFrameRoot().Client()->SetMouseCapture(true);
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
HitTestLocation location(mouse_down_pos);
HitTestResult result(request, location);
@@ -1047,8 +1047,8 @@ bool SelectionController::HandleMouseReleaseEvent(
SelectionInFlatTree::Builder builder;
Node* node = event.InnerNode();
if (node && node->GetLayoutObject() && HasEditableStyle(*node)) {
- const VisiblePositionInFlatTree pos =
- VisiblePositionOfHitTestResult(event.GetHitTestResult());
+ const VisiblePositionInFlatTree& pos = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(event.GetHitTestResult()));
if (pos.IsNotNull())
builder.Collapse(pos.ToPositionWithAffinity());
}
@@ -1063,9 +1063,6 @@ bool SelectionController::HandleMouseReleaseEvent(
handled = true;
}
- if (frame_->LocalFrameRoot().Client())
- frame_->LocalFrameRoot().Client()->SetMouseCapture(false);
-
Selection().NotifyTextControlOfSelectionChange(SetSelectionBy::kUser);
Selection().SelectFrameElementInParentIfFullySelected();
@@ -1158,13 +1155,13 @@ static bool HitTestResultIsMisspelled(const HitTestResult& result) {
Node* inner_node = result.InnerNode();
if (!inner_node || !inner_node->GetLayoutObject())
return false;
- VisiblePosition pos = CreateVisiblePosition(
- inner_node->GetLayoutObject()->PositionForPoint(result.LocalPoint()));
- if (pos.IsNull())
+ PositionWithAffinity pos_with_affinity =
+ inner_node->GetLayoutObject()->PositionForPoint(result.LocalPoint());
+ if (pos_with_affinity.IsNull())
return false;
// TODO(xiaochengh): Don't use |ParentAnchoredEquivalent()|.
const Position marker_position =
- pos.DeepEquivalent().ParentAnchoredEquivalent();
+ pos_with_affinity.GetPosition().ParentAnchoredEquivalent();
if (!SpellChecker::IsSpellCheckingEnabledAt(marker_position))
return false;
return SpellCheckMarkerAtPosition(inner_node->GetDocument().Markers(),
@@ -1217,8 +1214,8 @@ void SelectionController::PassMousePressEventToSubframe(
if (!Selection().Contains(p))
return;
- const VisiblePositionInFlatTree& visible_pos =
- VisiblePositionOfHitTestResult(mev.GetHitTestResult());
+ const VisiblePositionInFlatTree& visible_pos = CreateVisiblePosition(
+ PositionWithAffinityOfHitTestResult(mev.GetHitTestResult()));
if (visible_pos.IsNull()) {
Selection().SetSelectionAndEndTyping(SelectionInDOMTree());
return;
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_controller.h b/chromium/third_party/blink/renderer/core/editing/selection_controller.h
index 636332b541d..d9933c7b37f 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_controller.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_controller.h
@@ -49,6 +49,8 @@ class CORE_EXPORT SelectionController final
public:
static SelectionController* Create(LocalFrame&);
+
+ explicit SelectionController(LocalFrame&);
virtual ~SelectionController();
void Trace(blink::Visitor*) override;
@@ -84,8 +86,6 @@ class CORE_EXPORT SelectionController final
private:
friend class SelectionControllerTest;
- explicit SelectionController(LocalFrame&);
-
enum class AppendTrailingWhitespace { kShouldAppend, kDontAppend };
enum class SelectInputEventType { kTouch, kMouse };
enum EndPointsAdjustmentMode {
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_controller_test.cc b/chromium/third_party/blink/renderer/core/editing/selection_controller_test.cc
index f07c5c78899..64a15750c14 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_controller_test.cc
@@ -110,13 +110,13 @@ TEST_F(SelectionControllerTest, setCaretAtHitTestResult) {
const char* body_content = "<div id='sample' contenteditable>sample</div>";
SetBodyContent(body_content);
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"var sample = document.getElementById('sample');"
"sample.addEventListener('onselectstart', "
" event => elem.parentNode.removeChild(elem));");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
HitTestLocation location((IntPoint(8, 8)));
GetFrame().GetEventHandler().GetSelectionController().HandleGestureLongPress(
GetFrame().GetEventHandler().HitTestResultAtLocation(location));
@@ -130,7 +130,7 @@ TEST_F(SelectionControllerTest, setCaretAtHitTestResultWithNullPosition) {
"#sample { user-select: none; }"
"</style>"
"<div id=sample></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Hit "&nbsp;" in before pseudo element of "sample".
HitTestLocation location((IntPoint(10, 10)));
@@ -144,7 +144,7 @@ TEST_F(SelectionControllerTest, setCaretAtHitTestResultWithNullPosition) {
TEST_F(SelectionControllerTest,
SetCaretAtHitTestResultWithDisconnectedPosition) {
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.designMode = 'on';"
"const selection = window.getSelection();"
@@ -159,7 +159,7 @@ TEST_F(SelectionControllerTest,
"}"
"document.addEventListener('selectstart', selectstart);");
GetDocument().body()->AppendChild(script);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Simulate a tap somewhere in the document
blink::WebMouseEvent mouse_event(
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_editor.cc b/chromium/third_party/blink/renderer/core/editing/selection_editor.cc
index 7fc235964dd..132767f5a7a 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_editor.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_editor.cc
@@ -140,7 +140,7 @@ void SelectionEditor::DidFinishDOMMutation() {
AssertSelectionValid();
}
-void SelectionEditor::DocumentAttached(Document* document) {
+void SelectionEditor::DidAttachDocument(Document* document) {
DCHECK(document);
DCHECK(!LifecycleContext()) << LifecycleContext();
style_version_for_dom_tree_ = static_cast<uint64_t>(-1);
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_editor.h b/chromium/third_party/blink/renderer/core/editing/selection_editor.h
index e5feb9c8e11..9963eecc42c 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_editor.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_editor.h
@@ -45,8 +45,10 @@ class SelectionEditor final : public GarbageCollectedFinalized<SelectionEditor>,
public:
static SelectionEditor* Create(LocalFrame& frame) {
- return new SelectionEditor(frame);
+ return MakeGarbageCollected<SelectionEditor>(frame);
}
+
+ explicit SelectionEditor(LocalFrame&);
virtual ~SelectionEditor();
void Dispose();
@@ -56,7 +58,7 @@ class SelectionEditor final : public GarbageCollectedFinalized<SelectionEditor>,
VisibleSelectionInFlatTree ComputeVisibleSelectionInFlatTree() const;
void SetSelectionAndEndTyping(const SelectionInDOMTree&);
- void DocumentAttached(Document*);
+ void DidAttachDocument(Document*);
// There functions are exposed for |FrameSelection|.
void CacheRangeOfDocument(Range*);
@@ -66,8 +68,6 @@ class SelectionEditor final : public GarbageCollectedFinalized<SelectionEditor>,
void Trace(blink::Visitor*) override;
private:
- explicit SelectionEditor(LocalFrame&);
-
Document& GetDocument() const;
LocalFrame* GetFrame() const { return frame_.Get(); }
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_modifier.cc b/chromium/third_party/blink/renderer/core/editing/selection_modifier.cc
index 3632932b41e..8dbd8c40b5b 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_modifier.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_modifier.cc
@@ -253,15 +253,15 @@ VisiblePosition SelectionModifier::EndForPlatform() const {
return PositionForPlatform(false);
}
-VisiblePosition SelectionModifier::NextWordPositionForPlatform(
- const VisiblePosition& original_position) {
- VisiblePosition position_after_current_word =
- NextWordPosition(original_position);
+Position SelectionModifier::NextWordPositionForPlatform(
+ const Position& original_position) {
+ // Next word position can't be upstream.
+ const Position position_after_current_word =
+ NextWordPosition(original_position).GetPosition();
if (!GetFrame().GetEditor().Behavior().ShouldSkipSpaceWhenMovingRight())
return position_after_current_word;
- return CreateVisiblePosition(
- SkipWhitespace(position_after_current_word.DeepEquivalent()));
+ return SkipWhitespace(position_after_current_word);
}
static VisiblePosition AdjustForwardPositionForUserSelectAll(
@@ -302,9 +302,11 @@ VisiblePosition SelectionModifier::ModifyExtendingRightInternal(
kCanSkipOverEditingBoundary);
case TextGranularity::kWord:
if (DirectionOfEnclosingBlock() == TextDirection::kLtr) {
- return NextWordPositionForPlatform(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(NextWordPositionForPlatform(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
}
- return PreviousWordPosition(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(PreviousWordPosition(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
case TextGranularity::kLineBoundary:
if (DirectionOfEnclosingBlock() == TextDirection::kLtr)
return ModifyExtendingForwardInternal(granularity);
@@ -337,7 +339,8 @@ VisiblePosition SelectionModifier::ModifyExtendingForwardInternal(
return NextPositionOf(ComputeVisibleExtent(selection_),
kCanSkipOverEditingBoundary);
case TextGranularity::kWord:
- return NextWordPositionForPlatform(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(NextWordPositionForPlatform(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
case TextGranularity::kSentence:
return NextSentencePosition(ComputeVisibleExtent(selection_));
case TextGranularity::kLine:
@@ -417,7 +420,8 @@ VisiblePosition SelectionModifier::ModifyMovingForward(
return NextPositionOf(ComputeVisibleExtent(selection_),
kCanSkipOverEditingBoundary);
case TextGranularity::kWord:
- return NextWordPositionForPlatform(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(NextWordPositionForPlatform(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
case TextGranularity::kSentence:
return NextSentencePosition(ComputeVisibleExtent(selection_));
case TextGranularity::kLine: {
@@ -470,9 +474,11 @@ VisiblePosition SelectionModifier::ModifyExtendingLeftInternal(
kCanSkipOverEditingBoundary);
case TextGranularity::kWord:
if (DirectionOfEnclosingBlock() == TextDirection::kLtr) {
- return PreviousWordPosition(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(PreviousWordPosition(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
}
- return NextWordPositionForPlatform(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(NextWordPositionForPlatform(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
case TextGranularity::kLineBoundary:
if (DirectionOfEnclosingBlock() == TextDirection::kLtr)
return ModifyExtendingBackwardInternal(granularity);
@@ -508,7 +514,8 @@ VisiblePosition SelectionModifier::ModifyExtendingBackwardInternal(
return PreviousPositionOf(ComputeVisibleExtent(selection_),
kCanSkipOverEditingBoundary);
case TextGranularity::kWord:
- return PreviousWordPosition(ComputeVisibleExtent(selection_));
+ return CreateVisiblePosition(PreviousWordPosition(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
case TextGranularity::kSentence:
return PreviousSentencePosition(ComputeVisibleExtent(selection_));
case TextGranularity::kLine:
@@ -589,7 +596,8 @@ VisiblePosition SelectionModifier::ModifyMovingBackward(
}
break;
case TextGranularity::kWord:
- pos = PreviousWordPosition(ComputeVisibleExtent(selection_));
+ pos = CreateVisiblePosition(PreviousWordPosition(
+ ComputeVisibleExtent(selection_).DeepEquivalent()));
break;
case TextGranularity::kSentence:
pos = PreviousSentencePosition(ComputeVisibleExtent(selection_));
@@ -767,7 +775,8 @@ bool SelectionModifier::Modify(SelectionModifyAlteration alter,
// TODO(yosin): Maybe baseline would be better?
static bool AbsoluteCaretY(const VisiblePosition& c, int& y) {
- IntRect rect = AbsoluteCaretBoundsOf(c);
+ DCHECK(c.IsValid()) << c;
+ IntRect rect = AbsoluteCaretBoundsOf(c.ToPositionWithAffinity());
if (rect.IsEmpty())
return false;
y = rect.Y() + rect.Height() / 2;
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_modifier.h b/chromium/third_party/blink/renderer/core/editing/selection_modifier.h
index 6d9ce4290fc..30e3d753c2f 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_modifier.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_modifier.h
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/visible_selection.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -98,7 +98,7 @@ class CORE_EXPORT SelectionModifier {
VisiblePosition ModifyExtendingBackwardInternal(TextGranularity);
VisiblePosition ModifyMovingLeft(TextGranularity);
VisiblePosition ModifyMovingBackward(TextGranularity);
- VisiblePosition NextWordPositionForPlatform(const VisiblePosition&);
+ Position NextWordPositionForPlatform(const Position&);
// TODO(editing-dev): We should handle |skips_spaces_when_moving_right| in
// another way, e.g. pass |EditingBehavior()|.
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc b/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc
index f9b7c87e6a1..1b56a06d3ed 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc
@@ -119,8 +119,8 @@ void MarkupAccumulator::AppendElement(StringBuilder& result,
// 3.2. Element: If current node's is value is not null, and the
// element does not have an is attribute in its attribute list, ...
const AtomicString& is_value = element.IsValue();
- if (!is_value.IsNull() && !attributes.Find(HTMLNames::isAttr)) {
- AppendAttribute(result, element, Attribute(HTMLNames::isAttr, is_value),
+ if (!is_value.IsNull() && !attributes.Find(html_names::kIsAttr)) {
+ AppendAttribute(result, element, Attribute(html_names::kIsAttr, is_value),
namespaces);
}
}
@@ -227,7 +227,7 @@ String SerializeNodes(MarkupAccumulator& accumulator,
Namespaces namespace_hash;
if (!accumulator.SerializeAsHTMLDocument(target_node)) {
// Add pre-bound namespaces for XML fragments.
- namespace_hash.Set(g_xml_atom, XMLNames::xmlNamespaceURI);
+ namespace_hash.Set(g_xml_atom, xml_names::kNamespaceURI);
namespaces = &namespace_hash;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc b/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc
index 8580589e56b..298c5571e7a 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
struct EntityDescription {
UChar entity;
@@ -354,62 +354,90 @@ void MarkupFormatter::AppendAttribute(StringBuilder& result,
Namespaces* namespaces) {
bool document_is_html = SerializeAsHTMLDocument(element);
- QualifiedName prefixed_name = attribute.GetName();
if (document_is_html) {
- if (attribute.NamespaceURI() == XMLNSNames::xmlnsNamespaceURI) {
+ // https://html.spec.whatwg.org/multipage/parsing.html#attribute's-serialised-name
+ QualifiedName prefixed_name = attribute.GetName();
+ if (attribute.NamespaceURI() == xmlns_names::kNamespaceURI) {
if (!attribute.Prefix() && attribute.LocalName() != g_xmlns_atom)
prefixed_name.SetPrefix(g_xmlns_atom);
- } else if (attribute.NamespaceURI() == XMLNames::xmlNamespaceURI) {
+ } else if (attribute.NamespaceURI() == xml_names::kNamespaceURI) {
prefixed_name.SetPrefix(g_xml_atom);
- } else if (attribute.NamespaceURI() == XLinkNames::xlinkNamespaceURI) {
+ } else if (attribute.NamespaceURI() == xlink_names::kNamespaceURI) {
prefixed_name.SetPrefix(g_xlink_atom);
}
result.Append(' ');
result.Append(prefixed_name.ToString());
} else {
- if (attribute.NamespaceURI() == XMLNSNames::xmlnsNamespaceURI) {
+ // https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
+
+ // 3.3. Let attribute namespace be the value of attr's namespaceURI value.
+ const AtomicString& attribute_namespace = attribute.NamespaceURI();
+
+ // 3.4. Let candidate prefix be null.
+ AtomicString candidate_prefix;
+
+ // 3.5. If attribute namespace is not null, then run these sub-steps:
+
+ // 3.5.1. Let candidate prefix be the result of retrieving a preferred
+ // prefix string from map given namespace attribute namespace with preferred
+ // prefix being attr's prefix value.
+ // TODO(tkent): Implement it. crbug.com/906807
+ candidate_prefix = attribute.Prefix();
+
+ // 3.5.2. If the value of attribute namespace is the XMLNS namespace, then
+ // run these steps:
+ if (attribute_namespace == xmlns_names::kNamespaceURI) {
if (!attribute.Prefix() && attribute.LocalName() != g_xmlns_atom)
- prefixed_name.SetPrefix(g_xmlns_atom);
+ candidate_prefix = g_xmlns_atom;
// Account for the namespace attribute we're about to append.
if (namespaces) {
const AtomicString& lookup_key =
(!attribute.Prefix()) ? g_empty_atom : attribute.LocalName();
namespaces->Set(lookup_key, attribute.Value());
}
- } else if (attribute.NamespaceURI() == XMLNames::xmlNamespaceURI) {
- if (!attribute.Prefix())
- prefixed_name.SetPrefix(g_xml_atom);
+ } else if (attribute_namespace == xml_names::kNamespaceURI) {
+ if (!candidate_prefix)
+ candidate_prefix = g_xml_atom;
} else {
- if (attribute.NamespaceURI() == XLinkNames::xlinkNamespaceURI) {
- if (!attribute.Prefix())
- prefixed_name.SetPrefix(g_xlink_atom);
+ if (attribute_namespace == xlink_names::kNamespaceURI) {
+ if (!candidate_prefix)
+ candidate_prefix = g_xlink_atom;
}
+ // 3.5.3. Otherwise, the attribute namespace in not the XMLNS namespace.
+ // Run these steps:
if (namespaces && ShouldAddNamespaceAttribute(attribute, element)) {
- if (!prefixed_name.Prefix()) {
+ if (!candidate_prefix) {
// This behavior is in process of being standardized. See
// crbug.com/248044 and
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=24208
String prefix_prefix("ns", 2u);
- for (unsigned i = attribute.NamespaceURI().Impl()->ExistingHash();;
- ++i) {
+ for (unsigned i = attribute_namespace.Impl()->ExistingHash();; ++i) {
AtomicString new_prefix(String(prefix_prefix + String::Number(i)));
AtomicString found_uri = namespaces->at(new_prefix);
- if (found_uri == attribute.NamespaceURI() ||
- found_uri == g_null_atom) {
+ if (found_uri == attribute_namespace || found_uri == g_null_atom) {
// We already generated a prefix for this namespace.
- prefixed_name.SetPrefix(new_prefix);
+ candidate_prefix = new_prefix;
break;
}
}
}
- DCHECK(prefixed_name.Prefix());
- AppendNamespace(result, prefixed_name.Prefix(),
- attribute.NamespaceURI(), *namespaces);
+ // 3.5.3.2. Append the following to result, in the order listed:
+ DCHECK(candidate_prefix);
+ AppendNamespace(result, candidate_prefix, attribute_namespace,
+ *namespaces);
}
}
+ // 3.6. Append a " " (U+0020 SPACE) to result.
result.Append(' ');
- result.Append(prefixed_name.ToString());
+ // 3.7. If candidate prefix is not null, then append to result the
+ // concatenation of candidate prefix with ":" (U+003A COLON).
+ if (candidate_prefix) {
+ result.Append(candidate_prefix);
+ result.Append(':');
+ }
+ // 3.9.1. The value of attr's localName;
+ result.Append(attribute.LocalName());
}
result.Append('=');
@@ -452,7 +480,7 @@ bool MarkupFormatter::ShouldAddNamespaceAttribute(
const Element& element) const {
// xmlns and xmlns:prefix attributes should be handled by another branch in
// appendAttribute.
- DCHECK_NE(attribute.NamespaceURI(), XMLNSNames::xmlnsNamespaceURI);
+ DCHECK_NE(attribute.NamespaceURI(), xmlns_names::kNamespaceURI);
// Attributes are in the null namespace by default.
if (!attribute.NamespaceURI())
@@ -476,11 +504,11 @@ EntityMask MarkupFormatter::EntityMaskForText(const Text& text) const {
parent_name = &(text.parentElement())->TagQName();
if (parent_name &&
- (*parent_name == scriptTag || *parent_name == styleTag ||
- *parent_name == xmpTag || *parent_name == iframeTag ||
- *parent_name == plaintextTag || *parent_name == noembedTag ||
- *parent_name == noframesTag ||
- (*parent_name == noscriptTag && text.GetDocument().GetFrame() &&
+ (*parent_name == kScriptTag || *parent_name == kStyleTag ||
+ *parent_name == kXmpTag || *parent_name == kIFrameTag ||
+ *parent_name == kPlaintextTag || *parent_name == kNoembedTag ||
+ *parent_name == kNoframesTag ||
+ (*parent_name == kNoscriptTag && text.GetDocument().GetFrame() &&
text.GetDocument().CanExecuteScripts(kNotAboutToExecuteScript))))
return kEntityMaskInCDATA;
return kEntityMaskInHTMLPCDATA;
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc b/chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc
index 96cb812e83a..0ad4d70ebaf 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc
@@ -71,7 +71,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class AttributeChange {
DISALLOW_NEW();
@@ -130,7 +130,7 @@ static HTMLElement* AncestorToRetainStructureAndAppearanceForBlock(
if (!common_ancestor_block)
return nullptr;
- if (common_ancestor_block->HasTagName(tbodyTag) ||
+ if (common_ancestor_block->HasTagName(kTbodyTag) ||
IsHTMLTableRowElement(*common_ancestor_block))
return Traversal<HTMLTableElement>::FirstAncestor(*common_ancestor_block);
@@ -243,7 +243,7 @@ static HTMLElement* HighestAncestorToWrapMarkup(
Position::FirstPositionInNode(special_common_ancestor
? *special_common_ancestor
: *common_ancestor),
- aTag)))
+ kATag)))
special_common_ancestor = enclosing_anchor;
return special_common_ancestor;
@@ -551,7 +551,7 @@ DocumentFragment* CreateFragmentFromText(const EphemeralRange& context,
fragment->AppendChild(document.createTextNode(string));
if (string.EndsWith('\n')) {
HTMLBRElement* element = HTMLBRElement::Create(document);
- element->setAttribute(classAttr, AppleInterchangeNewline);
+ element->setAttribute(kClassAttr, AppleInterchangeNewline);
fragment->AppendChild(element);
}
return fragment;
@@ -581,7 +581,7 @@ DocumentFragment* CreateFragmentFromText(const EphemeralRange& context,
if (s.IsEmpty() && i + 1 == num_lines) {
// For last line, use the "magic BR" rather than a P.
element = HTMLBRElement::Create(document);
- element->setAttribute(classAttr, AppleInterchangeNewline);
+ element->setAttribute(kClassAttr, AppleInterchangeNewline);
} else {
if (use_clones_of_enclosing_block)
element = block->CloneWithoutChildren();
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/serialization.h b/chromium/third_party/blink/renderer/core/editing/serializers/serialization.h
index 0dc9a4f9255..9ffe3ae2b85 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/serialization.h
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/serialization.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_SERIALIZERS_SERIALIZATION_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/parser_content_policy.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/editing/serializers/html_interchange.h"
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_accumulator.cc b/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_accumulator.cc
index aa9f5f31839..fb27d4cadaa 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_accumulator.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_accumulator.cc
@@ -49,7 +49,7 @@ wtf_size_t TotalLength(const Vector<String>& strings) {
} // namespace
-using namespace HTMLNames;
+using namespace html_names;
StyledMarkupAccumulator::StyledMarkupAccumulator(
EAbsoluteURLs should_resolve_urls,
@@ -116,7 +116,7 @@ void StyledMarkupAccumulator::AppendTextWithInlineStyle(
AppendText(text);
} else {
const bool use_rendered_text = !EnclosingElementWithTag(
- Position::FirstPositionInNode(text), selectTag);
+ Position::FirstPositionInNode(text), kSelectTag);
String content =
use_rendered_text ? RenderedText(text) : StringValueForRange(text);
StringBuilder buffer;
@@ -143,7 +143,7 @@ void StyledMarkupAccumulator::AppendElementWithInlineStyle(
AttributeCollection attributes = element.Attributes();
for (const auto& attribute : attributes) {
// We'll handle the style attribute separately, below.
- if (attribute.GetName() == styleAttr)
+ if (attribute.GetName() == kStyleAttr)
continue;
formatter_.AppendAttribute(out, element, attribute, nullptr);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer.cc b/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer.cc
index 7e53181da49..5a0865a616d 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer.cc
@@ -79,7 +79,7 @@ bool HandleSelectionBoundary<EditingInFlatTreeStrategy>(const Node& node) {
} // namespace
-using namespace HTMLNames;
+using namespace html_names;
template <typename Strategy>
class StyledMarkupTraverser {
@@ -230,7 +230,7 @@ String StyledMarkupSerializer<Strategy>::CreateMarkup() {
*start_.ComputeContainerNode(), *end_.ComputeContainerNode());
DCHECK(common_ancestor);
HTMLBodyElement* body = ToHTMLBodyElement(EnclosingElementWithTag(
- Position::FirstPositionInNode(*common_ancestor), bodyTag));
+ Position::FirstPositionInNode(*common_ancestor), kBodyTag));
HTMLBodyElement* fully_selected_root = nullptr;
// FIXME: Do this for all fully selected blocks, not just the body.
if (body && AreSameRanges(body, start_, end_))
@@ -252,10 +252,10 @@ String StyledMarkupSerializer<Strategy>::CreateMarkup() {
!fully_selected_root_style->Style() ||
!fully_selected_root_style->Style()->GetPropertyCSSValue(
CSSPropertyBackgroundImage)) &&
- fully_selected_root->hasAttribute(backgroundAttr)) {
+ fully_selected_root->hasAttribute(kBackgroundAttr)) {
fully_selected_root_style->Style()->SetProperty(
CSSPropertyBackgroundImage,
- "url('" + fully_selected_root->getAttribute(backgroundAttr) +
+ "url('" + fully_selected_root->getAttribute(kBackgroundAttr) +
"')",
/* important */ false,
fully_selected_root->GetDocument().GetSecureContextMode());
@@ -361,7 +361,7 @@ Node* StyledMarkupTraverser<Strategy>::Traverse(Node* start_node,
if (!n->GetLayoutObject() &&
(!n->IsElementNode() || !ToElement(n)->HasDisplayContentsStyle()) &&
!EnclosingElementWithTag(FirstPositionInOrBeforeNode(*n),
- selectTag)) {
+ kSelectTag)) {
next = Strategy::NextSkippingChildren(*n);
// Don't skip over pastEnd.
if (past_end && Strategy::IsDescendantOf(*past_end, *n))
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/cold_mode_spell_check_requester.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/cold_mode_spell_check_requester.cc
index a3dc6a7562e..d1f45225520 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/cold_mode_spell_check_requester.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/cold_mode_spell_check_requester.cc
@@ -153,8 +153,7 @@ void ColdModeSpellCheckRequester::RequestCheckingForNextChunk() {
// Chromium spellchecker requires complete sentences to be checked. However,
// EndOfSentence() sometimes returns null or out-of-editable positions, which
// are corrected here.
- const Position extended_end =
- EndOfSentence(CreateVisiblePosition(chunk_end)).DeepEquivalent();
+ const Position extended_end = EndOfSentence(chunk_end).GetPosition();
const Position check_end =
extended_end.IsNull() || extended_end < chunk_end
? chunk_end
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/hot_mode_spell_check_requester.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/hot_mode_spell_check_requester.cc
index 037cbee5320..6a97ae4a32e 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/hot_mode_spell_check_requester.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/hot_mode_spell_check_requester.cc
@@ -27,16 +27,15 @@ const int kHotModeCheckAllThreshold = 128;
const int kHotModeChunkSize = 1024;
EphemeralRange AdjacentWordIfExists(const Position& pos) {
- const VisiblePosition& visible_pos = CreateVisiblePosition(pos);
- const VisiblePosition& word_start = PreviousWordPosition(visible_pos);
+ const Position word_start = PreviousWordPosition(pos).GetPosition();
if (word_start.IsNull())
return EphemeralRange();
- const VisiblePosition& word_end = EndOfWord(word_start);
+ const Position word_end = EndOfWordPosition(word_start);
if (word_end.IsNull())
return EphemeralRange();
- if (ComparePositions(visible_pos, word_end) > 0)
+ if (ComparePositions(pos, word_end) > 0)
return EphemeralRange();
- return EphemeralRange(word_start.DeepEquivalent(), word_end.DeepEquivalent());
+ return EphemeralRange(word_start, word_end);
}
EphemeralRange CurrentWordIfTypingInPartialWord(const Element& editable) {
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc
index 0acffa8ae7f..6dfe7b5ec4e 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc
@@ -22,7 +22,6 @@
#include "third_party/blink/renderer/core/editing/visible_units.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -43,18 +42,18 @@ class IdleSpellCheckController::IdleCallback final
: public ScriptedIdleTaskController::IdleTask {
public:
static IdleCallback* Create(IdleSpellCheckController* controller) {
- return new IdleCallback(controller);
+ return MakeGarbageCollected<IdleCallback>(controller);
}
+ explicit IdleCallback(IdleSpellCheckController* controller)
+ : controller_(controller) {}
+
void Trace(blink::Visitor* visitor) final {
visitor->Trace(controller_);
ScriptedIdleTaskController::IdleTask::Trace(visitor);
}
private:
- explicit IdleCallback(IdleSpellCheckController* controller)
- : controller_(controller) {}
-
void invoke(IdleDeadline* deadline) final { controller_->Invoke(deadline); }
const Member<IdleSpellCheckController> controller_;
@@ -125,16 +124,15 @@ void IdleSpellCheckController::SetNeedsInvocation() {
if (state_ == State::kColdModeRequested)
DisposeIdleCallback();
- IdleRequestOptions options;
- options.setTimeout(kHotModeRequestTimeoutMS);
+ IdleRequestOptions* options = IdleRequestOptions::Create();
+ options->setTimeout(kHotModeRequestTimeoutMS);
idle_callback_handle_ =
GetDocument().RequestIdleCallback(IdleCallback::Create(this), options);
state_ = State::kHotModeRequested;
}
void IdleSpellCheckController::SetNeedsColdModeInvocation() {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled() ||
- !IsSpellCheckingEnabled()) {
+ if (!IsSpellCheckingEnabled()) {
Deactivate();
return;
}
@@ -152,7 +150,6 @@ void IdleSpellCheckController::SetNeedsColdModeInvocation() {
}
void IdleSpellCheckController::ColdModeTimerFired(TimerBase*) {
- DCHECK(RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled());
DCHECK_EQ(State::kColdModeTimerStarted, state_);
if (!IsSpellCheckingEnabled() || !IsAvailable()) {
@@ -161,7 +158,7 @@ void IdleSpellCheckController::ColdModeTimerFired(TimerBase*) {
}
idle_callback_handle_ = GetDocument().RequestIdleCallback(
- IdleCallback::Create(this), IdleRequestOptions());
+ IdleCallback::Create(this), IdleRequestOptions::Create());
state_ = State::kColdModeRequested;
}
@@ -208,7 +205,6 @@ void IdleSpellCheckController::Invoke(IdleDeadline* deadline) {
HotModeInvocation(deadline);
SetNeedsColdModeInvocation();
} else if (state_ == State::kColdModeRequested) {
- DCHECK(RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled());
state_ = State::kInColdModeInvocation;
cold_mode_requester_->Invoke(deadline);
if (cold_mode_requester_->FullyChecked())
@@ -220,7 +216,7 @@ void IdleSpellCheckController::Invoke(IdleDeadline* deadline) {
}
}
-void IdleSpellCheckController::DocumentAttached(Document* document) {
+void IdleSpellCheckController::DidAttachDocument(Document* document) {
SetContext(document);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.h b/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.h
index 72e6fcc39e1..5e03f504dce 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.h
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.h
@@ -52,7 +52,7 @@ class CORE_EXPORT IdleSpellCheckController final
// document is detached or spellchecking is globally disabled.
void Deactivate();
- void DocumentAttached(Document*);
+ void DidAttachDocument(Document*);
// Exposed for testing only.
SpellCheckRequester& GetSpellCheckRequester() const;
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller_test.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller_test.cc
index 91dbdb2e3d7..973f76dc2f3 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller_test.cc
@@ -9,8 +9,6 @@
#include "third_party/blink/renderer/core/editing/spellcheck/spell_checker.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/html_object_element.h"
-#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
@@ -40,10 +38,8 @@ class IdleSpellCheckControllerTest : public SpellCheckTestBase {
IdleChecker().SetNeedsInvocation();
break;
case State::kColdModeTimerStarted:
- DCHECK(RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled());
break;
case State::kColdModeRequested:
- DCHECK(RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled());
IdleChecker().SkipColdModeTimerForTesting();
break;
case State::kInHotModeInvocation:
@@ -56,19 +52,9 @@ class IdleSpellCheckControllerTest : public SpellCheckTestBase {
// Test cases for lifecycle state transitions.
TEST_F(IdleSpellCheckControllerTest, InitializationWithColdMode) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
EXPECT_EQ(State::kColdModeTimerStarted, IdleChecker().GetState());
}
-TEST_F(IdleSpellCheckControllerTest, InitializationWithoutColdMode) {
- if (RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
- EXPECT_EQ(State::kInactive, IdleChecker().GetState());
-}
-
TEST_F(IdleSpellCheckControllerTest, RequestWhenInactive) {
TransitTo(State::kInactive);
IdleChecker().SetNeedsInvocation();
@@ -86,9 +72,6 @@ TEST_F(IdleSpellCheckControllerTest, RequestWhenHotModeRequested) {
}
TEST_F(IdleSpellCheckControllerTest, RequestWhenColdModeTimerStarted) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeTimerStarted);
IdleChecker().SetNeedsInvocation();
EXPECT_EQ(State::kHotModeRequested, IdleChecker().GetState());
@@ -96,9 +79,6 @@ TEST_F(IdleSpellCheckControllerTest, RequestWhenColdModeTimerStarted) {
}
TEST_F(IdleSpellCheckControllerTest, RequestWhenColdModeRequested) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeRequested);
int handle = IdleChecker().IdleCallbackHandle();
IdleChecker().SetNeedsInvocation();
@@ -107,28 +87,13 @@ TEST_F(IdleSpellCheckControllerTest, RequestWhenColdModeRequested) {
EXPECT_NE(-1, IdleChecker().IdleCallbackHandle());
}
-TEST_F(IdleSpellCheckControllerTest, HotModeTransitToInactive) {
- if (RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
- TransitTo(State::kHotModeRequested);
- IdleChecker().ForceInvocationForTesting();
- EXPECT_EQ(State::kInactive, IdleChecker().GetState());
-}
-
TEST_F(IdleSpellCheckControllerTest, HotModeTransitToColdMode) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kHotModeRequested);
IdleChecker().ForceInvocationForTesting();
EXPECT_EQ(State::kColdModeTimerStarted, IdleChecker().GetState());
}
TEST_F(IdleSpellCheckControllerTest, ColdModeTimerStartedToRequested) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeTimerStarted);
IdleChecker().SkipColdModeTimerForTesting();
EXPECT_EQ(State::kColdModeRequested, IdleChecker().GetState());
@@ -136,9 +101,6 @@ TEST_F(IdleSpellCheckControllerTest, ColdModeTimerStartedToRequested) {
}
TEST_F(IdleSpellCheckControllerTest, ColdModeStayAtColdMode) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeRequested);
IdleChecker().SetNeedsMoreColdModeInvocationForTesting();
IdleChecker().ForceInvocationForTesting();
@@ -146,9 +108,6 @@ TEST_F(IdleSpellCheckControllerTest, ColdModeStayAtColdMode) {
}
TEST_F(IdleSpellCheckControllerTest, ColdModeToInactive) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeRequested);
IdleChecker().ForceInvocationForTesting();
EXPECT_EQ(State::kInactive, IdleChecker().GetState());
@@ -167,18 +126,12 @@ TEST_F(IdleSpellCheckControllerTest, DetachWhenHotModeRequested) {
}
TEST_F(IdleSpellCheckControllerTest, DetachWhenColdModeTimerStarted) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeTimerStarted);
GetDocument().Shutdown();
EXPECT_EQ(State::kInactive, IdleChecker().GetState());
}
TEST_F(IdleSpellCheckControllerTest, DetachWhenColdModeRequested) {
- if (!RuntimeEnabledFeatures::IdleTimeColdModeSpellCheckingEnabled())
- return;
-
TransitTo(State::kColdModeRequested);
GetDocument().Shutdown();
EXPECT_EQ(State::kInactive, IdleChecker().GetState());
@@ -186,17 +139,18 @@ TEST_F(IdleSpellCheckControllerTest, DetachWhenColdModeRequested) {
// https://crbug.com/863784
TEST_F(IdleSpellCheckControllerTest, ColdModeRangeCrossesShadow) {
- ScopedIdleTimeColdModeSpellCheckingForTest cold_mode_scope(true);
SetBodyContent(
"<div contenteditable style=\"width:800px\">"
"foo"
"<menu style=\"all: initial\">1127</menu>"
"<object><optgroup></optgroup></object>"
"</div>");
- ToHTMLObjectElement(GetDocument().QuerySelector("object"))
- ->RenderFallbackContent();
+ auto* html_object_element =
+ ToHTMLObjectElement(GetDocument().QuerySelector("object"));
+ html_object_element->RenderFallbackContent(
+ html_object_element->ContentFrame());
GetDocument().QuerySelector("div")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Advance to cold mode invocation
IdleChecker().ForceInvocationForTesting();
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc
index 706f274d258..4f1134de40f 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc
@@ -122,8 +122,8 @@ SpellCheckRequest* SpellCheckRequest::Create(
Range* checking_range_object = CreateRange(checking_range);
- SpellCheckRequest* request =
- new SpellCheckRequest(checking_range_object, text, request_number);
+ SpellCheckRequest* request = MakeGarbageCollected<SpellCheckRequest>(
+ checking_range_object, text, request_number);
if (request->RootEditableElement())
return request;
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h
index 2085f68910f..f8846c9fe86 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h
@@ -51,6 +51,7 @@ class CORE_EXPORT SpellCheckRequest
static SpellCheckRequest* Create(const EphemeralRange& checking_range,
int request_number);
+ SpellCheckRequest(Range* checking_range, const String&, int request_number);
~SpellCheckRequest();
void Dispose();
@@ -70,8 +71,6 @@ class CORE_EXPORT SpellCheckRequest
void Trace(blink::Visitor*);
private:
- SpellCheckRequest(Range* checking_range, const String&, int request_number);
-
Member<SpellCheckRequester> requester_;
Member<Range> checking_range_;
Member<Element> root_editable_element_;
@@ -84,9 +83,10 @@ class CORE_EXPORT SpellCheckRequester final
: public GarbageCollectedFinalized<SpellCheckRequester> {
public:
static SpellCheckRequester* Create(LocalFrame& frame) {
- return new SpellCheckRequester(frame);
+ return MakeGarbageCollected<SpellCheckRequester>(frame);
}
+ explicit SpellCheckRequester(LocalFrame&);
~SpellCheckRequester();
void Trace(blink::Visitor*);
@@ -106,8 +106,6 @@ class CORE_EXPORT SpellCheckRequester final
private:
friend class SpellCheckRequest;
- explicit SpellCheckRequester(LocalFrame&);
-
WebTextCheckClient* GetTextCheckerClient() const;
void TimerFiredToProcessQueuedRequest(TimerBase*);
void InvokeRequest(SpellCheckRequest*);
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.cc
index 83d3f34e258..40387317282 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.cc
@@ -59,12 +59,10 @@
namespace blink {
-using namespace HTMLNames;
-
namespace {
static bool IsWhiteSpaceOrPunctuation(UChar c) {
- return IsSpaceOrNewline(c) || WTF::Unicode::IsPunct(c);
+ return IsSpaceOrNewline(c) || WTF::unicode::IsPunct(c);
}
bool IsAmbiguousBoundaryCharacter(UChar character) {
@@ -81,7 +79,7 @@ bool IsAmbiguousBoundaryCharacter(UChar character) {
} // namespace
SpellChecker* SpellChecker::Create(LocalFrame& frame) {
- return new SpellChecker(frame);
+ return MakeGarbageCollected<SpellChecker>(frame);
}
static WebSpellCheckPanelHostClient& GetEmptySpellCheckPanelHostClient() {
@@ -165,8 +163,9 @@ void SpellChecker::AdvanceToNextMisspelling(bool start_before_selection) {
if (!GetFrame().GetDocument()->documentElement())
return;
- position = FirstEditableVisiblePositionAfterPositionInRoot(
- position, *GetFrame().GetDocument()->documentElement())
+ position = CreateVisiblePosition(
+ FirstEditablePositionAfterPositionInRoot(
+ position, *GetFrame().GetDocument()->documentElement()))
.DeepEquivalent();
if (position.IsNull())
return;
@@ -600,8 +599,8 @@ void SpellChecker::CancelCheck() {
spell_check_requester_->CancelCheck();
}
-void SpellChecker::DocumentAttached(Document* document) {
- idle_spell_check_controller_->DocumentAttached(document);
+void SpellChecker::DidAttachDocument(Document* document) {
+ idle_spell_check_controller_->DidAttachDocument(document);
}
void SpellChecker::Trace(blink::Visitor* visitor) {
@@ -756,7 +755,7 @@ bool SpellChecker::IsSpellCheckingEnabledAt(const Position& position) {
if (auto* input = ToHTMLInputElementOrNull(text_control)) {
// TODO(tkent): The following password type check should be done in
// HTMLElement::spellcheck(). crbug.com/371567
- if (input->type() == InputTypeNames::password)
+ if (input->type() == input_type_names::kPassword)
return false;
if (!input->IsFocusedElementInDocument())
return false;
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.h b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.h
index d312e93e2be..c25947e0511 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.h
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker.h
@@ -51,6 +51,8 @@ class CORE_EXPORT SpellChecker final : public GarbageCollected<SpellChecker> {
public:
static SpellChecker* Create(LocalFrame&);
+ explicit SpellChecker(LocalFrame&);
+
void Trace(blink::Visitor*);
WebSpellCheckPanelHostClient& SpellCheckPanelHostClient() const;
@@ -97,11 +99,9 @@ class CORE_EXPORT SpellChecker final : public GarbageCollected<SpellChecker> {
// ensure leak reporting stability.
void PrepareForLeakDetection();
- void DocumentAttached(Document*);
+ void DidAttachDocument(Document*);
private:
- explicit SpellChecker(LocalFrame&);
-
LocalFrame& GetFrame() const {
DCHECK(frame_);
return *frame_;
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker_test.cc b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker_test.cc
index 022ada60d0f..56bbb3ec01c 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/spell_checker_test.cc
@@ -40,7 +40,7 @@ void SpellCheckerTest::ForceLayout() {
TEST_F(SpellCheckerTest, AdvanceToNextMisspellingWithEmptyInputNoCrash) {
SetBodyContent("<input placeholder='placeholder'>abc");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* input = GetDocument().QuerySelector("input");
input->focus();
// Do not crash in advanceToNextMisspelling.
@@ -57,7 +57,7 @@ TEST_F(SpellCheckerTest, AdvanceToNextMisspellingWithImageInTableNoCrash) {
"zz zz zz"
"</div>");
GetDocument().QuerySelector("div")->focus();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Do not crash in advanceToNextMisspelling.
GetSpellChecker().AdvanceToNextMisspelling(false);
@@ -73,7 +73,7 @@ TEST_F(SpellCheckerTest, AdvancedToNextMisspellingWrapSearchNoCrash) {
SelectionInDOMTree::Builder()
.Collapse(Position::LastPositionInNode(*div))
.Build());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetSpellChecker().AdvanceToNextMisspelling(false);
}
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.cc b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.cc
index 5be73a1cba2..694542f23b5 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.cc
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.cc
@@ -14,7 +14,7 @@
namespace blink {
namespace {
-const UChar32 kInvalidCodePoint = WTF::Unicode::kMaxCodepoint + 1;
+const UChar32 kInvalidCodePoint = WTF::unicode::kMaxCodepoint + 1;
} // namespace
#define FOR_EACH_BACKWARD_GRAPHEME_BOUNDARY_STATE(V) \
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine_test.cc b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine_test.cc
index a6e1c6b1e6d..ca89508aadc 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine_test.cc
@@ -20,7 +20,7 @@ namespace backward_grapheme_boundary_state_machine_test {
// kWatch kVS16, kEye kVS16 are valid standardized variants.
const UChar32 kWatch = 0x231A;
-const UChar32 kEye = WTF::Unicode::kEyeCharacter;
+const UChar32 kEye = WTF::unicode::kEyeCharacter;
const UChar32 kVS16 = 0xFE0F;
// kHanBMP KVS17, kHanSIP kVS17 are valie IVD sequences.
@@ -317,10 +317,10 @@ TEST_F(BackwardGraphemeBoundaryStatemachineTest,
}
TEST_F(BackwardGraphemeBoundaryStatemachineTest, MuchLongerCase) {
- const UChar32 kMan = WTF::Unicode::kManCharacter;
- const UChar32 kZwj = WTF::Unicode::kZeroWidthJoinerCharacter;
- const UChar32 kHeart = WTF::Unicode::kHeavyBlackHeartCharacter;
- const UChar32 kKiss = WTF::Unicode::kKissMarkCharacter;
+ const UChar32 kMan = WTF::unicode::kManCharacter;
+ const UChar32 kZwj = WTF::unicode::kZeroWidthJoinerCharacter;
+ const UChar32 kHeart = WTF::unicode::kHeavyBlackHeartCharacter;
+ const UChar32 kKiss = WTF::unicode::kKissMarkCharacter;
BackwardGraphemeBoundaryStateMachine machine;
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.cc b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.cc
index 9293ebfbcec..a02dd222938 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.cc
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.cc
@@ -12,7 +12,7 @@
namespace blink {
namespace {
-const UChar32 kUnsetCodePoint = WTF::Unicode::kMaxCodepoint + 1;
+const UChar32 kUnsetCodePoint = WTF::unicode::kMaxCodepoint + 1;
} // namespace
#define FOR_EACH_FORWARD_GRAPHEME_BOUNDARY_STATE(V) \
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine_test.cc b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine_test.cc
index 4a4753be9a1..f12b603f506 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine_test.cc
@@ -23,7 +23,7 @@ namespace forward_grapheme_boundary_state_machine_test {
// kWatch kVS16, kEye kVS16 are valid standardized variants.
const UChar32 kWatch = 0x231A;
-const UChar32 kEye = WTF::Unicode::kEyeCharacter;
+const UChar32 kEye = WTF::unicode::kEyeCharacter;
const UChar32 kVS16 = 0xFE0F;
// kHanBMP KVS17, kHanSIP kVS17 are valie IVD sequences.
@@ -465,10 +465,10 @@ TEST_F(ForwardGraphemeBoundaryStatemachineTest,
TEST_F(ForwardGraphemeBoundaryStatemachineTest, MuchLongerCase) {
ForwardGraphemeBoundaryStateMachine machine;
- const UChar32 kMan = WTF::Unicode::kManCharacter;
- const UChar32 kZwj = WTF::Unicode::kZeroWidthJoinerCharacter;
- const UChar32 kHeart = WTF::Unicode::kHeavyBlackHeartCharacter;
- const UChar32 kKiss = WTF::Unicode::kKissMarkCharacter;
+ const UChar32 kMan = WTF::unicode::kManCharacter;
+ const UChar32 kZwj = WTF::unicode::kZeroWidthJoinerCharacter;
+ const UChar32 kHeart = WTF::unicode::kHeavyBlackHeartCharacter;
+ const UChar32 kKiss = WTF::unicode::kKissMarkCharacter;
// U+1F468 U+200D U+2764 U+FE0F U+200D U+1F48B U+200D U+1F468 is a valid ZWJ
// emoji sequence.
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/state_machine_util_test.cc b/chromium/third_party/blink/renderer/core/editing/state_machines/state_machine_util_test.cc
index 047744ebc74..3a1c58751d3 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/state_machine_util_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/state_machine_util_test.cc
@@ -12,7 +12,7 @@ namespace blink {
TEST(StateMachineUtilTest, IsGraphmeBreak_LineBreak) {
// U+000AD (SOFT HYPHEN) has Control grapheme property.
- const UChar32 kControl = WTF::Unicode::kSoftHyphenCharacter;
+ const UChar32 kControl = WTF::unicode::kSoftHyphenCharacter;
// Grapheme Cluster Boundary Rule GB3: CR x LF
EXPECT_FALSE(IsGraphemeBreak('\r', '\n'));
@@ -82,14 +82,14 @@ TEST(StateMachineUtilTest, IsGraphmeBreak_Extend_or_ZWJ) {
const UChar32 kExtend = 0x0300;
// Grapheme Cluster Boundary Rule GB9: x (Extend | ZWJ)
EXPECT_FALSE(IsGraphemeBreak('a', kExtend));
- EXPECT_FALSE(IsGraphemeBreak('a', WTF::Unicode::kZeroWidthJoinerCharacter));
+ EXPECT_FALSE(IsGraphemeBreak('a', WTF::unicode::kZeroWidthJoinerCharacter));
EXPECT_FALSE(IsGraphemeBreak(kExtend, kExtend));
- EXPECT_FALSE(IsGraphemeBreak(WTF::Unicode::kZeroWidthJoinerCharacter,
- WTF::Unicode::kZeroWidthJoinerCharacter));
+ EXPECT_FALSE(IsGraphemeBreak(WTF::unicode::kZeroWidthJoinerCharacter,
+ WTF::unicode::kZeroWidthJoinerCharacter));
EXPECT_FALSE(
- IsGraphemeBreak(kExtend, WTF::Unicode::kZeroWidthJoinerCharacter));
+ IsGraphemeBreak(kExtend, WTF::unicode::kZeroWidthJoinerCharacter));
EXPECT_FALSE(
- IsGraphemeBreak(WTF::Unicode::kZeroWidthJoinerCharacter, kExtend));
+ IsGraphemeBreak(WTF::unicode::kZeroWidthJoinerCharacter, kExtend));
}
TEST(StateMachineUtilTest, IsGraphmeBreak_SpacingMark) {
@@ -137,17 +137,17 @@ TEST(StateMachineUtilTest, IsGraphmeBreak_ZWJSequecne) {
// Grapheme Cluster Boundary Rule GB11: ZWJ x (Glue_After_Zwj | EBG)
EXPECT_FALSE(
- IsGraphemeBreak(WTF::Unicode::kZeroWidthJoinerCharacter, kGlueAfterZwj));
+ IsGraphemeBreak(WTF::unicode::kZeroWidthJoinerCharacter, kGlueAfterZwj));
EXPECT_FALSE(
- IsGraphemeBreak(WTF::Unicode::kZeroWidthJoinerCharacter, kEBaseGAZ));
+ IsGraphemeBreak(WTF::unicode::kZeroWidthJoinerCharacter, kEBaseGAZ));
EXPECT_FALSE(
- IsGraphemeBreak(WTF::Unicode::kZeroWidthJoinerCharacter, kEmoji));
+ IsGraphemeBreak(WTF::unicode::kZeroWidthJoinerCharacter, kEmoji));
EXPECT_TRUE(IsGraphemeBreak(kGlueAfterZwj, kEBaseGAZ));
EXPECT_TRUE(IsGraphemeBreak(kGlueAfterZwj, kGlueAfterZwj));
EXPECT_TRUE(IsGraphemeBreak(kEBaseGAZ, kGlueAfterZwj));
- EXPECT_TRUE(IsGraphemeBreak(WTF::Unicode::kZeroWidthJoinerCharacter, 'a'));
+ EXPECT_TRUE(IsGraphemeBreak(WTF::unicode::kZeroWidthJoinerCharacter, 'a'));
}
TEST(StateMachineUtilTest, IsGraphmeBreak_IndicSyllabicCategoryVirama) {
diff --git a/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.cc b/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.cc
index fccf2900907..62d52520f5e 100644
--- a/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.cc
+++ b/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.cc
@@ -198,7 +198,7 @@ SuggestionInfosWithNodeAndHighlightColor ComputeSuggestionInfos(
TextSuggestionController::TextSuggestionController(LocalFrame& frame)
: is_suggestion_menu_open_(false), frame_(&frame) {}
-void TextSuggestionController::DocumentAttached(Document* document) {
+void TextSuggestionController::DidAttachDocument(Document* document) {
DCHECK(document);
SetContext(document);
}
@@ -232,6 +232,11 @@ void TextSuggestionController::HandlePotentialSuggestionTap(
if (!node_and_marker.first)
return;
+ const SuggestionMarker* marker =
+ ToSuggestionMarkerOrNull(node_and_marker.second);
+ if (marker && marker->Suggestions().IsEmpty())
+ return;
+
if (!text_suggestion_host_) {
GetFrame().GetInterfaceProvider().GetInterface(
mojo::MakeRequest(&text_suggestion_host_));
@@ -454,6 +459,9 @@ void TextSuggestionController::ShowSuggestionMenu(
Vector<TextSuggestionInfo>& suggestion_infos =
suggestion_infos_with_node_and_highlight_color.suggestion_infos;
+ if (suggestion_infos.IsEmpty())
+ return;
+
int span_union_start = suggestion_infos[0].span_start;
int span_union_end = suggestion_infos[0].span_end;
for (wtf_size_t i = 1; i < suggestion_infos.size(); ++i) {
diff --git a/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.h b/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.h
index 43754fab928..428e05c1782 100644
--- a/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.h
+++ b/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.h
@@ -31,7 +31,7 @@ class CORE_EXPORT TextSuggestionController final
public:
explicit TextSuggestionController(LocalFrame&);
- void DocumentAttached(Document*);
+ void DidAttachDocument(Document*);
bool IsMenuOpen() const;
@@ -47,6 +47,7 @@ class CORE_EXPORT TextSuggestionController final
void Trace(blink::Visitor*) override;
private:
+ friend class TextSuggestionControllerTest;
Document& GetDocument() const;
bool IsAvailable() const;
LocalFrame& GetFrame() const;
diff --git a/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc b/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc
index eab4b202994..1f1d3ac4c57 100644
--- a/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller_test.cc
@@ -17,7 +17,34 @@ using ws::mojom::ImeTextSpanThickness;
namespace blink {
-class TextSuggestionControllerTest : public EditingTestBase {};
+class TextSuggestionControllerTest : public EditingTestBase {
+ public:
+ bool IsTextSuggestionHostAvailable() {
+ return bool(GetDocument()
+ .GetFrame()
+ ->GetTextSuggestionController()
+ .text_suggestion_host_);
+ }
+
+ void ShowSuggestionMenu(
+ const HeapVector<std::pair<Member<Node>, Member<DocumentMarker>>>&
+ node_suggestion_marker_pairs,
+ size_t max_number_of_suggestions) {
+ GetDocument().GetFrame()->GetTextSuggestionController().ShowSuggestionMenu(
+ node_suggestion_marker_pairs, max_number_of_suggestions);
+ }
+
+ EphemeralRangeInFlatTree ComputeRangeSurroundingCaret(
+ const PositionInFlatTree& caret_position) {
+ const Node* const position_node = caret_position.ComputeContainerNode();
+ const unsigned position_offset_in_node =
+ caret_position.ComputeOffsetInContainerNode();
+ // See ComputeRangeSurroundingCaret() in TextSuggestionController.
+ return EphemeralRangeInFlatTree(
+ PositionInFlatTree(position_node, position_offset_in_node - 1),
+ PositionInFlatTree(position_node, position_offset_in_node + 1));
+ }
+};
TEST_F(TextSuggestionControllerTest, ApplySpellCheckSuggestion) {
SetBodyContent(
@@ -439,4 +466,83 @@ TEST_F(TextSuggestionControllerTest, CallbackHappensAfterDocumentDestroyed) {
frame.GetTextSuggestionController().SuggestionMenuTimeoutCallback(0);
}
+TEST_F(TextSuggestionControllerTest, SuggestionMarkerWithEmptySuggestion) {
+ SetBodyContent(
+ "<div contenteditable>"
+ "hello"
+ "</div>");
+ Element* div = GetDocument().QuerySelector("div");
+ Text* text = ToText(div->firstChild());
+
+ // Set suggestion marker with empty suggestion list.
+ GetDocument().Markers().AddSuggestionMarker(
+ EphemeralRange(Position(text, 0), Position(text, 5)),
+ SuggestionMarkerProperties::Builder()
+ .SetSuggestions(Vector<String>())
+ .Build());
+
+ // Set the caret inside the word.
+ GetDocument().GetFrame()->Selection().SetSelectionAndEndTyping(
+ SelectionInDOMTree::Builder()
+ .SetBaseAndExtent(Position(text, 3), Position(text, 3))
+ .Build());
+
+ // Handle potential suggestion tap on the caret position.
+ GetDocument()
+ .GetFrame()
+ ->GetTextSuggestionController()
+ .HandlePotentialSuggestionTap(PositionInFlatTree(text, 3));
+
+ // We don't trigger menu in this case so there shouldn't be any mojom
+ // connection available.
+ EXPECT_FALSE(IsTextSuggestionHostAvailable());
+
+ const VisibleSelectionInFlatTree& selection =
+ GetFrame().Selection().ComputeVisibleSelectionInFlatTree();
+ EXPECT_FALSE(selection.IsNone());
+
+ const EphemeralRangeInFlatTree& range_to_check =
+ ComputeRangeSurroundingCaret(selection.Start());
+
+ const HeapVector<std::pair<Member<Node>, Member<DocumentMarker>>>&
+ node_suggestion_marker_pairs =
+ GetFrame().GetDocument()->Markers().MarkersIntersectingRange(
+ range_to_check, DocumentMarker::MarkerTypes::Suggestion());
+ EXPECT_FALSE(node_suggestion_marker_pairs.IsEmpty());
+
+ // Calling ShowSuggestionMenu() shouldn't crash. See crbug.com/901135.
+ // ShowSuggestionMenu() may still get called because of race condition.
+ ShowSuggestionMenu(node_suggestion_marker_pairs, 3);
+}
+
+TEST_F(TextSuggestionControllerTest, SuggestionMarkerWithSuggestion) {
+ SetBodyContent(
+ "<div contenteditable>"
+ "hello"
+ "</div>");
+ Element* div = GetDocument().QuerySelector("div");
+ Text* text = ToText(div->firstChild());
+
+ // Set suggestion marker with two suggestions.
+ GetDocument().Markers().AddSuggestionMarker(
+ EphemeralRange(Position(text, 0), Position(text, 5)),
+ SuggestionMarkerProperties::Builder()
+ .SetSuggestions(Vector<String>({"marker1", "marker2"}))
+ .Build());
+
+ // Set the caret inside the word.
+ GetDocument().GetFrame()->Selection().SetSelectionAndEndTyping(
+ SelectionInDOMTree::Builder()
+ .SetBaseAndExtent(Position(text, 3), Position(text, 3))
+ .Build());
+
+ // Handle potential suggestion tap on the caret position.
+ GetDocument()
+ .GetFrame()
+ ->GetTextSuggestionController()
+ .HandlePotentialSuggestionTap(PositionInFlatTree(text, 3));
+
+ EXPECT_TRUE(IsTextSuggestionHostAvailable());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/testing/editing_test_base.cc b/chromium/third_party/blink/renderer/core/editing/testing/editing_test_base.cc
index 06a769103ab..941df98e852 100644
--- a/chromium/third_party/blink/renderer/core/editing/testing/editing_test_base.cc
+++ b/chromium/third_party/blink/renderer/core/editing/testing/editing_test_base.cc
@@ -37,10 +37,11 @@ EditingTestBase::EditingTestBase() = default;
EditingTestBase::~EditingTestBase() = default;
void EditingTestBase::InsertStyleElement(const std::string& style_rules) {
- Element* const head = GetOrCreateElement(&GetDocument(), HTMLNames::headTag);
- DCHECK_EQ(head, GetOrCreateElement(&GetDocument(), HTMLNames::headTag));
+ Element* const head =
+ GetOrCreateElement(&GetDocument(), html_names::kHeadTag);
+ DCHECK_EQ(head, GetOrCreateElement(&GetDocument(), html_names::kHeadTag));
Element* const style = GetDocument().CreateRawElement(
- HTMLNames::styleTag, CreateElementFlags::ByCreateElement());
+ html_names::kStyleTag, CreateElementFlags::ByCreateElement());
style->setTextContent(String(style_rules.data(), style_rules.size()));
head->appendChild(style);
}
@@ -63,7 +64,7 @@ SelectionInDOMTree EditingTestBase::SetSelectionText(
const std::string& selection_text) {
const SelectionInDOMTree selection =
SelectionSample::SetSelectionText(element, selection_text);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
return selection;
}
@@ -99,7 +100,8 @@ ShadowRoot* EditingTestBase::CreateShadowRootForElementWithIDAndSetInnerHTML(
->CreateV0ShadowRootForTesting();
shadow_root.SetInnerHTMLFromString(String::FromUTF8(shadow_root_content),
ASSERT_NO_EXCEPTION);
- scope.GetDocument().View()->UpdateAllLifecyclePhases();
+ scope.GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
return &shadow_root;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/testing/selection_sample_test.cc b/chromium/third_party/blink/renderer/core/editing/testing/selection_sample_test.cc
index dbbcd245576..75b43ee1785 100644
--- a/chromium/third_party/blink/renderer/core/editing/testing/selection_sample_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/testing/selection_sample_test.cc
@@ -241,7 +241,7 @@ TEST_F(SelectionSampleTest, SerializeVoidElement) {
}
TEST_F(SelectionSampleTest, SerializeVoidElementBR) {
- Element* const br = GetDocument().CreateRawElement(HTMLNames::brTag);
+ Element* const br = GetDocument().CreateRawElement(html_names::kBrTag);
br->appendChild(GetDocument().createTextNode("abc"));
GetDocument().body()->appendChild(br);
EXPECT_EQ(
diff --git a/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.cc b/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.cc
index b507f7be8cd..3e9cdcbe154 100644
--- a/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.cc
+++ b/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/editing/iterators/character_iterator.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h"
#include "third_party/blink/renderer/core/editing/position.h"
+#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
namespace blink {
@@ -103,9 +104,10 @@ const LayoutBlockFlow* ComputeInlineContentsAsBlockFlow(
block_flow.IsFloatingOrOutOfFlowPositioned()) {
const LayoutBlockFlow& root_block_flow =
RootInlineContentsContainerOf(block_flow);
- DCHECK(CanBeInlineContentsContainer(root_block_flow))
- << layout_object << " block_flow=" << block_flow
- << " root_block_flow=" << root_block_flow;
+ // Skip |root_block_flow| if it's an anonymous wrapper created for
+ // pseudo elements. See test AnonymousBlockFlowWrapperForFloatPseudo.
+ if (!CanBeInlineContentsContainer(root_block_flow))
+ return nullptr;
return &root_block_flow;
}
if (!CanBeInlineContentsContainer(block_flow))
@@ -232,10 +234,11 @@ TextOffsetMapping::ForwardRange TextOffsetMapping::ForwardRangeOf(
}
// static
-TextOffsetMapping::InlineContents TextOffsetMapping::FindBackwardInlineContents(
- const PositionInFlatTree& position) {
- for (const Node* node = position.NodeAsRangeLastNode(); node;
- node = FlatTreeTraversal::Previous(*node)) {
+template <typename Traverser>
+TextOffsetMapping::InlineContents TextOffsetMapping::FindInlineContentsInternal(
+ const Node* start_node,
+ Traverser traverser) {
+ for (const Node* node = start_node; node; node = traverser(*node)) {
const InlineContents inline_contents = ComputeInlineContentsFromNode(*node);
if (inline_contents.IsNotNull())
return inline_contents;
@@ -244,17 +247,78 @@ TextOffsetMapping::InlineContents TextOffsetMapping::FindBackwardInlineContents(
}
// static
+TextOffsetMapping::InlineContents TextOffsetMapping::FindBackwardInlineContents(
+ const PositionInFlatTree& position) {
+ const Node* previous_node = position.NodeAsRangeLastNode();
+ if (!previous_node)
+ return InlineContents();
+
+ if (const TextControlElement* enclosing_text_control =
+ EnclosingTextControl(position)) {
+ if (!FlatTreeTraversal::IsDescendantOf(*previous_node,
+ *enclosing_text_control)) {
+ // The first position in a text control reaches here.
+ return InlineContents();
+ }
+
+ return TextOffsetMapping::FindInlineContentsInternal(
+ previous_node, [enclosing_text_control](const Node& node) {
+ return FlatTreeTraversal::Previous(node, enclosing_text_control);
+ });
+ }
+
+ auto previous_skipping_text_control = [](const Node& node) -> const Node* {
+ DCHECK(!EnclosingTextControl(&node));
+ const Node* previous = FlatTreeTraversal::Previous(node);
+ const TextControlElement* previous_text_control =
+ EnclosingTextControl(previous);
+ if (!previous_text_control)
+ return previous;
+ return previous_text_control;
+ };
+
+ if (const TextControlElement* last_enclosing_text_control =
+ EnclosingTextControl(previous_node)) {
+ // Example, <input value=foo><span>bar</span>, span@beforeAnchor
+ return TextOffsetMapping::FindInlineContentsInternal(
+ last_enclosing_text_control, previous_skipping_text_control);
+ }
+ return TextOffsetMapping::FindInlineContentsInternal(
+ previous_node, previous_skipping_text_control);
+}
+
+// static
// Note: "doubleclick-whitespace-img-crash.html" call |NextWordPosition())
// with AfterNode(IMG) for <body><img></body>
TextOffsetMapping::InlineContents TextOffsetMapping::FindForwardInlineContents(
const PositionInFlatTree& position) {
- for (const Node* node = position.NodeAsRangeFirstNode(); node;
- node = FlatTreeTraversal::Next(*node)) {
- const InlineContents inline_contents = ComputeInlineContentsFromNode(*node);
- if (inline_contents.IsNotNull())
- return inline_contents;
+ const Node* next_node = position.NodeAsRangeFirstNode();
+ if (!next_node)
+ return InlineContents();
+
+ if (const TextControlElement* enclosing_text_control =
+ EnclosingTextControl(position)) {
+ if (!FlatTreeTraversal::IsDescendantOf(*next_node,
+ *enclosing_text_control)) {
+ // The last position in a text control reaches here.
+ return InlineContents();
+ }
+
+ return TextOffsetMapping::FindInlineContentsInternal(
+ next_node, [enclosing_text_control](const Node& node) {
+ return FlatTreeTraversal::Next(node, enclosing_text_control);
+ });
}
- return InlineContents();
+
+ auto next_skipping_text_control = [](const Node& node) {
+ DCHECK(!EnclosingTextControl(&node));
+ if (IsTextControl(node))
+ return FlatTreeTraversal::NextSkippingChildren(node);
+ return FlatTreeTraversal::Next(node);
+ };
+ DCHECK(!EnclosingTextControl(next_node));
+ return TextOffsetMapping::FindInlineContentsInternal(
+ next_node, next_skipping_text_control);
}
// ----
@@ -322,38 +386,56 @@ EphemeralRangeInFlatTree TextOffsetMapping::InlineContents::GetRange() const {
: PositionInFlatTree::AfterNode(last_node));
}
+PositionInFlatTree
+TextOffsetMapping::InlineContents::LastPositionBeforeBlockFlow() const {
+ DCHECK(block_flow_);
+ if (const Node* node = block_flow_->NonPseudoNode()) {
+ if (!FlatTreeTraversal::Parent(*node)) {
+ // Reached start of document.
+ return PositionInFlatTree();
+ }
+ return PositionInFlatTree::BeforeNode(*node);
+ }
+ DCHECK(first_);
+ DCHECK(first_->NonPseudoNode());
+ DCHECK(FlatTreeTraversal::Parent(*first_->NonPseudoNode()));
+ return PositionInFlatTree::BeforeNode(*first_->NonPseudoNode());
+}
+
+PositionInFlatTree
+TextOffsetMapping::InlineContents::FirstPositionAfterBlockFlow() const {
+ DCHECK(block_flow_);
+ if (const Node* node = block_flow_->NonPseudoNode()) {
+ if (!FlatTreeTraversal::Parent(*node)) {
+ // Reached end of document.
+ return PositionInFlatTree();
+ }
+ return PositionInFlatTree::AfterNode(*node);
+ }
+ DCHECK(last_);
+ DCHECK(last_->NonPseudoNode());
+ DCHECK(FlatTreeTraversal::Parent(*last_->NonPseudoNode()));
+ return PositionInFlatTree::AfterNode(*last_->NonPseudoNode());
+}
+
// static
TextOffsetMapping::InlineContents TextOffsetMapping::InlineContents::NextOf(
const InlineContents& inline_contents) {
- for (LayoutObject* runner =
- inline_contents.block_flow_->NextInPreOrderAfterChildren();
- runner; runner = runner->NextInPreOrder()) {
- if (!CanBeInlineContentsContainer(*runner))
- continue;
- const LayoutBlockFlow& block_flow = ToLayoutBlockFlow(*runner);
- if (block_flow.IsFloatingOrOutOfFlowPositioned())
- continue;
- DCHECK(!block_flow.IsAtomicInlineLevel()) << block_flow;
- return CreateInlineContentsFromBlockFlow(block_flow);
- }
- return InlineContents();
+ const PositionInFlatTree position_after =
+ inline_contents.FirstPositionAfterBlockFlow();
+ if (position_after.IsNull())
+ return InlineContents();
+ return TextOffsetMapping::FindForwardInlineContents(position_after);
}
// static
TextOffsetMapping::InlineContents TextOffsetMapping::InlineContents::PreviousOf(
const InlineContents& inline_contents) {
- for (LayoutObject* runner = inline_contents.block_flow_->PreviousInPreOrder();
- runner; runner = runner->PreviousInPreOrder()) {
- const LayoutBlockFlow* const block_flow =
- ComputeInlineContentsAsBlockFlow(*runner);
- if (!block_flow || block_flow->IsFloatingOrOutOfFlowPositioned())
- continue;
- DCHECK(!block_flow->IsDescendantOf(inline_contents.block_flow_))
- << block_flow;
- DCHECK(!block_flow->IsAtomicInlineLevel()) << block_flow;
- return CreateInlineContentsFromBlockFlow(*block_flow);
- }
- return InlineContents();
+ const PositionInFlatTree position_before =
+ inline_contents.LastPositionBeforeBlockFlow();
+ if (position_before.IsNull())
+ return InlineContents();
+ return TextOffsetMapping::FindBackwardInlineContents(position_before);
}
std::ostream& operator<<(
diff --git a/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.h b/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.h
index 68547d3aaa5..1cc8985d084 100644
--- a/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.h
+++ b/chromium/third_party/blink/renderer/core/editing/text_offset_mapping.h
@@ -71,6 +71,9 @@ class CORE_EXPORT TextOffsetMapping final {
private:
friend class TextOffsetMapping;
+ PositionInFlatTree FirstPositionAfterBlockFlow() const;
+ PositionInFlatTree LastPositionBeforeBlockFlow() const;
+
const LayoutBlockFlow* block_flow_ = nullptr;
const LayoutObject* first_ = nullptr;
const LayoutObject* last_ = nullptr;
@@ -201,6 +204,9 @@ class CORE_EXPORT TextOffsetMapping final {
private:
TextOffsetMapping(const InlineContents&, const TextIteratorBehavior&);
+ template <typename Traverser>
+ static InlineContents FindInlineContentsInternal(const Node*, Traverser);
+
const TextIteratorBehavior behavior_;
const EphemeralRangeInFlatTree range_;
const String text16_;
diff --git a/chromium/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc b/chromium/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc
index c9c784b3e63..bf46362ecbe 100644
--- a/chromium/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc
@@ -40,7 +40,11 @@ class ParameterizedTextOffsetMappingTest
std::string GetRange(const std::string& selection_text) {
const PositionInFlatTree position =
ToPositionInFlatTree(SetSelectionTextToBody(selection_text).Base());
- TextOffsetMapping mapping(GetInlineContents(position));
+ return GetRange(GetInlineContents(position));
+ }
+
+ std::string GetRange(const TextOffsetMapping::InlineContents& contents) {
+ TextOffsetMapping mapping(contents);
return GetSelectionTextInFlatTreeFromBody(
SelectionInFlatTree::Builder()
.SetBaseAndExtent(mapping.GetRange())
@@ -230,6 +234,76 @@ TEST_P(ParameterizedTextOffsetMappingTest, RangeOfEmptyBlock) {
TextOffsetMapping::FindBackwardInlineContents(position));
}
+// http://crbug.com/900906
+TEST_P(ParameterizedTextOffsetMappingTest,
+ AnonymousBlockFlowWrapperForFloatPseudo) {
+ InsertStyleElement("table::after{content:close-quote;float:right;}");
+ const PositionInFlatTree position =
+ ToPositionInFlatTree(SetCaretTextToBody("<table></table>|foo"));
+ const TextOffsetMapping::InlineContents inline_contents =
+ TextOffsetMapping::FindBackwardInlineContents(position);
+ ASSERT_TRUE(inline_contents.IsNotNull());
+ const TextOffsetMapping::InlineContents previous_contents =
+ TextOffsetMapping::InlineContents::PreviousOf(inline_contents);
+ EXPECT_TRUE(previous_contents.IsNull());
+}
+
+TEST_P(ParameterizedTextOffsetMappingTest, ForwardRangesWithTextControl) {
+ // InlineContents for positions outside text control should cover the entire
+ // containing block.
+ const PositionInFlatTree outside_position = ToPositionInFlatTree(
+ SetCaretTextToBody("foo<!--|--><input value=\"bla\">bar"));
+ const TextOffsetMapping::InlineContents outside_contents =
+ TextOffsetMapping::FindForwardInlineContents(outside_position);
+ EXPECT_EQ("^foo<input value=\"bla\"><div>bla</div></input>bar|",
+ GetRange(outside_contents));
+
+ // InlineContents for positions inside text control should not escape the text
+ // control in forward iteration.
+ const Element* input = GetDocument().QuerySelector("input");
+ const PositionInFlatTree inside_first =
+ PositionInFlatTree::FirstPositionInNode(*input);
+ const TextOffsetMapping::InlineContents inside_contents =
+ TextOffsetMapping::FindForwardInlineContents(inside_first);
+ EXPECT_EQ("foo<input value=\"bla\"><div>^bla|</div></input>bar",
+ GetRange(inside_contents));
+ EXPECT_TRUE(
+ TextOffsetMapping::InlineContents::NextOf(inside_contents).IsNull());
+
+ const PositionInFlatTree inside_last =
+ PositionInFlatTree::LastPositionInNode(*input);
+ EXPECT_TRUE(
+ TextOffsetMapping::FindForwardInlineContents(inside_last).IsNull());
+}
+
+TEST_P(ParameterizedTextOffsetMappingTest, BackwardRangesWithTextControl) {
+ // InlineContents for positions outside text control should cover the entire
+ // containing block.
+ const PositionInFlatTree outside_position = ToPositionInFlatTree(
+ SetCaretTextToBody("foo<input value=\"bla\"><!--|-->bar"));
+ const TextOffsetMapping::InlineContents outside_contents =
+ TextOffsetMapping::FindBackwardInlineContents(outside_position);
+ EXPECT_EQ("^foo<input value=\"bla\"><div>bla</div></input>bar|",
+ GetRange(outside_contents));
+
+ // InlineContents for positions inside text control should not escape the text
+ // control in backward iteration.
+ const Element* input = GetDocument().QuerySelector("input");
+ const PositionInFlatTree inside_last =
+ PositionInFlatTree::LastPositionInNode(*input);
+ const TextOffsetMapping::InlineContents inside_contents =
+ TextOffsetMapping::FindBackwardInlineContents(inside_last);
+ EXPECT_EQ("foo<input value=\"bla\"><div>^bla|</div></input>bar",
+ GetRange(inside_contents));
+ EXPECT_TRUE(
+ TextOffsetMapping::InlineContents::PreviousOf(inside_contents).IsNull());
+
+ const PositionInFlatTree inside_first =
+ PositionInFlatTree::FirstPositionInNode(*input);
+ EXPECT_TRUE(
+ TextOffsetMapping::FindBackwardInlineContents(inside_first).IsNull());
+}
+
// http://crbug.com/832497
TEST_P(ParameterizedTextOffsetMappingTest, RangeWithCollapsedWhitespace) {
// Whitespaces after <div> is collapsed.
@@ -355,4 +429,20 @@ TEST_P(ParameterizedTextOffsetMappingTest, GetPositionAfter) {
// We hit DCHECK for offset 8, because we walk on "012 456".
}
+// https://crbug.com/903723
+TEST_P(ParameterizedTextOffsetMappingTest, InlineContentsWithDocumentBoundary) {
+ InsertStyleElement("*{position:fixed}");
+ SetBodyContent("");
+ const PositionInFlatTree position =
+ PositionInFlatTree::FirstPositionInNode(*GetDocument().body());
+ const TextOffsetMapping::InlineContents inline_contents =
+ TextOffsetMapping::FindForwardInlineContents(position);
+ EXPECT_TRUE(inline_contents.IsNotNull());
+ // Should not crash when previous/next iteration reaches document boundary.
+ EXPECT_TRUE(
+ TextOffsetMapping::InlineContents::PreviousOf(inline_contents).IsNull());
+ EXPECT_TRUE(
+ TextOffsetMapping::InlineContents::NextOf(inline_contents).IsNull());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/text_segments.cc b/chromium/third_party/blink/renderer/core/editing/text_segments.cc
index 4f3e19f7cc3..4ee69a943f9 100644
--- a/chromium/third_party/blink/renderer/core/editing/text_segments.cc
+++ b/chromium/third_party/blink/renderer/core/editing/text_segments.cc
@@ -56,4 +56,28 @@ PositionInFlatTree TextSegments::FindBoundaryForward(
return last_position;
}
+// static
+PositionInFlatTree TextSegments::FindBoundaryBackward(
+ const PositionInFlatTree& position,
+ Finder* finder) {
+ DCHECK(position.IsNotNull());
+ PositionInFlatTree last_position = position;
+ for (const auto& inline_contents :
+ TextOffsetMapping::BackwardRangeOf(position)) {
+ const TextOffsetMapping mapping(inline_contents);
+ const String text = mapping.GetText();
+ const unsigned offset = last_position == position
+ ? mapping.ComputeTextOffset(position)
+ : mapping.GetText().length();
+ const TextSegments::Finder::Position result = finder->Find(text, offset);
+ if (result.IsBefore())
+ return mapping.GetPositionBefore(result.Offset());
+ if (result.IsAfter())
+ return mapping.GetPositionAfter(result.Offset());
+ DCHECK(result.IsNone());
+ last_position = mapping.GetRange().StartPosition();
+ }
+ return last_position;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/text_segments.h b/chromium/third_party/blink/renderer/core/editing/text_segments.h
index f8813fcb76c..5f05aed1381 100644
--- a/chromium/third_party/blink/renderer/core/editing/text_segments.h
+++ b/chromium/third_party/blink/renderer/core/editing/text_segments.h
@@ -51,13 +51,15 @@ class TextSegments final {
virtual Position Find(const String text, unsigned offset) = 0;
};
- // TODO(editing-dev): We should have |FindBoundaryBackward()|.
-
// Returns a boundary position found by |finder| followed by |position|
// (inclusive). |finder| can be stateful or stateless.
static PositionInFlatTree FindBoundaryForward(
const PositionInFlatTree& position,
Finder* finder);
+
+ static PositionInFlatTree FindBoundaryBackward(
+ const PositionInFlatTree& position,
+ Finder* finder);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_position.cc b/chromium/third_party/blink/renderer/core/editing/visible_position.cc
index 4a013d1ef5e..71dab2ad3d9 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_position.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_position.cc
@@ -41,8 +41,6 @@
namespace blink {
-using namespace HTMLNames;
-
template <typename Strategy>
VisiblePositionTemplate<Strategy>::VisiblePositionTemplate()
#if DCHECK_IS_ON()
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_position_test.cc b/chromium/third_party/blink/renderer/core/editing/visible_position_test.cc
index cb28a352879..cabb3c35026 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_position_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_position_test.cc
@@ -69,13 +69,13 @@ TEST_F(VisiblePositionTest, NonNullInvalidatedAfterDOMChange) {
VisiblePosition null_visible_position;
VisiblePosition non_null_visible_position = CreateVisiblePosition(position);
- Element* div = GetDocument().CreateRawElement(HTMLNames::divTag);
+ Element* div = GetDocument().CreateRawElement(html_names::kDivTag);
GetDocument().body()->AppendChild(div);
EXPECT_TRUE(null_visible_position.IsValid());
EXPECT_FALSE(non_null_visible_position.IsValid());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Invalid VisiblePosition can never become valid again.
EXPECT_FALSE(non_null_visible_position.IsValid());
@@ -93,14 +93,14 @@ TEST_F(VisiblePositionTest, NonNullInvalidatedAfterStyleChange) {
ASSERT_NO_EXCEPTION);
EXPECT_FALSE(visible_position1.IsValid());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
VisiblePosition visible_position2 = CreateVisiblePosition(position);
div->style()->setProperty(&GetDocument(), "display", "none", "important",
ASSERT_NO_EXCEPTION);
EXPECT_FALSE(visible_position2.IsValid());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Invalid VisiblePosition can never become valid again.
EXPECT_FALSE(visible_position1.IsValid());
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_selection_test.cc b/chromium/third_party/blink/renderer/core/editing/visible_selection_test.cc
index 87cdec267c5..77e481324ce 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_selection_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_selection_test.cc
@@ -110,7 +110,6 @@ TEST_F(VisibleSelectionTest, expandUsingGranularity) {
Node* three = shadow_root->getElementById("three")->firstChild();
Node* four = shadow_root->getElementById("four")->firstChild();
Node* five = shadow_root->getElementById("five")->firstChild();
- Node* space = shadow_root->getElementById("space")->firstChild();
VisibleSelection selection;
VisibleSelectionInFlatTree selection_in_flat_tree;
@@ -149,8 +148,8 @@ TEST_F(VisibleSelectionTest, expandUsingGranularity) {
EXPECT_EQ(selection.Start(), selection.Base());
EXPECT_EQ(selection.End(), selection.Extent());
- EXPECT_EQ(Position(space, 0), selection.Start());
- EXPECT_EQ(Position(five, 5), selection.End());
+ EXPECT_EQ(Position(three, 0), selection.Start());
+ EXPECT_EQ(Position(four, 4), selection.End());
EXPECT_EQ(selection_in_flat_tree.Start(), selection_in_flat_tree.Base());
EXPECT_EQ(selection_in_flat_tree.End(), selection_in_flat_tree.Extent());
@@ -212,7 +211,8 @@ TEST_F(VisibleSelectionTest, expandUsingGranularity) {
EXPECT_EQ(selection.Start(), selection.Base());
EXPECT_EQ(selection.End(), selection.Extent());
- EXPECT_EQ(Position(five, 0), selection.Start());
+ // DOM tree canonicalization moves position to a wrong place
+ EXPECT_EQ(Position(five, 5), selection.Start());
EXPECT_EQ(Position(five, 5), selection.End());
EXPECT_EQ(selection_in_flat_tree.Start(), selection_in_flat_tree.Base());
@@ -658,6 +658,18 @@ TEST_F(VisibleSelectionTest, WordGranularity) {
}
}
+// https://crbug.com/901492
+TEST_F(VisibleSelectionTest, WordGranularityAfterTextControl) {
+ const PositionInFlatTree position =
+ ToPositionInFlatTree(SetCaretTextToBody("foo<input value=\"bla\">b|ar"));
+ const VisibleSelectionInFlatTree selection =
+ CreateVisibleSelectionWithGranularity(
+ SelectionInFlatTree::Builder().Collapse(position).Build(),
+ TextGranularity::kWord);
+ EXPECT_EQ("foo<input value=\"bla\"><div>bla</div></input>^bar|",
+ GetSelectionTextInFlatTreeFromBody(selection.AsSelection()));
+}
+
// This is for crbug.com/627783, simulating restoring selection
// in undo stack.
TEST_F(VisibleSelectionTest, updateIfNeededWithShadowHost) {
@@ -685,7 +697,7 @@ TEST_F(VisibleSelectionTest, updateIfNeededWithShadowHost) {
// This is a regression test for https://crbug.com/825120
TEST_F(VisibleSelectionTest, BackwardSelectionWithMultipleEmptyBodies) {
Element* body = GetDocument().body();
- Element* new_body = GetDocument().CreateRawElement(HTMLNames::bodyTag);
+ Element* new_body = GetDocument().CreateRawElement(html_names::kBodyTag);
body->appendChild(new_body);
GetDocument().UpdateStyleAndLayout();
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units.cc b/chromium/third_party/blink/renderer/core/editing/visible_units.cc
index d3c3e77fe8e..debe9cadf33 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units.cc
@@ -343,99 +343,6 @@ static Node* ParentEditingBoundary(const PositionTemplate<Strategy>& position) {
return boundary;
}
-template <typename Strategy>
-static PositionTemplate<Strategy> PreviousBoundaryAlgorithm(
- const VisiblePositionTemplate<Strategy>& c,
- BoundarySearchFunction search_function) {
- DCHECK(c.IsValid()) << c;
- const PositionTemplate<Strategy> pos = c.DeepEquivalent();
- Node* boundary = ParentEditingBoundary(pos);
- if (!boundary)
- return PositionTemplate<Strategy>();
-
- const PositionTemplate<Strategy> start =
- PositionTemplate<Strategy>::EditingPositionOf(boundary, 0)
- .ParentAnchoredEquivalent();
- const PositionTemplate<Strategy> end = pos.ParentAnchoredEquivalent();
-
- ForwardsTextBuffer suffix_string;
- if (RequiresContextForWordBoundary(CharacterBefore(c))) {
- TextIteratorAlgorithm<Strategy> forwards_iterator(
- end, PositionTemplate<Strategy>::AfterNode(*boundary));
- while (!forwards_iterator.AtEnd()) {
- forwards_iterator.CopyTextTo(&suffix_string);
- int context_end_index = EndOfFirstWordBoundaryContext(
- suffix_string.Data() + suffix_string.Size() -
- forwards_iterator.length(),
- forwards_iterator.length());
- if (context_end_index < forwards_iterator.length()) {
- suffix_string.Shrink(forwards_iterator.length() - context_end_index);
- break;
- }
- forwards_iterator.Advance();
- }
- }
-
- unsigned suffix_length = suffix_string.Size();
- BackwardsTextBuffer string;
- string.PushRange(suffix_string.Data(), suffix_string.Size());
-
- // Treat bullets used in the text security mode as regular characters when
- // looking for boundaries.
- SimplifiedBackwardsTextIteratorAlgorithm<Strategy> it(
- EphemeralRangeTemplate<Strategy>(start, end),
- TextIteratorBehavior::Builder()
- .SetEmitsSmallXForTextSecurity(true)
- .Build());
- unsigned next = 0;
- bool need_more_context = false;
- while (!it.AtEnd()) {
- // iterate to get chunks until the searchFunction returns a non-zero
- // value.
- int run_offset = 0;
- do {
- run_offset += it.CopyTextTo(&string, run_offset, string.Capacity());
- next = search_function(string.Data(), string.Size(),
- string.Size() - suffix_length, kMayHaveMoreContext,
- need_more_context);
- } while (!next && run_offset < it.length());
- if (next)
- break;
- it.Advance();
- }
- if (need_more_context) {
- // The last search returned the beginning of the buffer and asked for
- // more context, but there is no earlier text. Force a search with
- // what's available.
- next = search_function(string.Data(), string.Size(),
- string.Size() - suffix_length, kDontHaveMoreContext,
- need_more_context);
- DCHECK(!need_more_context);
- }
-
- if (!next)
- return it.AtEnd() ? it.StartPosition() : pos;
-
- // Use the character iterator to translate the next value into a DOM
- // position.
- BackwardsCharacterIteratorAlgorithm<Strategy> char_it(
- EphemeralRangeTemplate<Strategy>(start, end));
- char_it.Advance(string.Size() - suffix_length - next);
- // TODO(yosin) charIt can get out of shadow host.
- return char_it.EndPosition();
-}
-
-Position PreviousBoundary(const VisiblePosition& visible_position,
- BoundarySearchFunction search_function) {
- return PreviousBoundaryAlgorithm(visible_position, search_function);
-}
-
-PositionInFlatTree PreviousBoundary(
- const VisiblePositionInFlatTree& visible_position,
- BoundarySearchFunction search_function) {
- return PreviousBoundaryAlgorithm(visible_position, search_function);
-}
-
// ---------
template <typename Strategy>
@@ -564,8 +471,9 @@ bool HasRenderedNonAnonymousDescendantsWithHeight(
return false;
}
-VisiblePosition VisiblePositionForContentsPoint(const IntPoint& contents_point,
- LocalFrame* frame) {
+PositionWithAffinity PositionForContentsPointRespectingEditingBoundary(
+ const IntPoint& contents_point,
+ LocalFrame* frame) {
HitTestRequest request = HitTestRequest::kMove | HitTestRequest::kReadOnly |
HitTestRequest::kActive |
HitTestRequest::kIgnoreClipping;
@@ -574,11 +482,11 @@ VisiblePosition VisiblePositionForContentsPoint(const IntPoint& contents_point,
frame->GetDocument()->GetLayoutView()->HitTest(location, result);
if (Node* node = result.InnerNode()) {
- return CreateVisiblePosition(PositionRespectingEditingBoundary(
+ return PositionRespectingEditingBoundary(
frame->Selection().ComputeVisibleSelectionInDOMTreeDeprecated().Start(),
- result.LocalPoint(), node));
+ result.LocalPoint(), node);
}
- return VisiblePosition();
+ return PositionWithAffinity();
}
// TODO(yosin): We should use |AssociatedLayoutObjectOf()| in "visible_units.cc"
@@ -1053,16 +961,14 @@ bool IsVisuallyEquivalentCandidate(const PositionInFlatTree& position) {
}
template <typename Strategy>
-static VisiblePositionTemplate<Strategy> SkipToEndOfEditingBoundary(
- const VisiblePositionTemplate<Strategy>& pos,
+static PositionTemplate<Strategy> SkipToEndOfEditingBoundary(
+ const PositionTemplate<Strategy>& pos,
const PositionTemplate<Strategy>& anchor) {
- DCHECK(pos.IsValid()) << pos;
if (pos.IsNull())
return pos;
ContainerNode* highest_root = HighestEditableRoot(anchor);
- ContainerNode* highest_root_of_pos =
- HighestEditableRoot(pos.DeepEquivalent());
+ ContainerNode* highest_root_of_pos = HighestEditableRoot(pos);
// Return |pos| itself if the two are from the very same editable region,
// or both are non-editable.
@@ -1070,17 +976,16 @@ static VisiblePositionTemplate<Strategy> SkipToEndOfEditingBoundary(
return pos;
// If this is not editable but |pos| has an editable root, skip to the end
- if (!highest_root && highest_root_of_pos)
- return CreateVisiblePosition(
- PositionTemplate<Strategy>(highest_root_of_pos,
- PositionAnchorType::kAfterAnchor)
- .ParentAnchoredEquivalent());
+ if (!highest_root && highest_root_of_pos) {
+ return PositionTemplate<Strategy>(highest_root_of_pos,
+ PositionAnchorType::kAfterAnchor)
+ .ParentAnchoredEquivalent();
+ }
// That must mean that |pos| is not editable. Return the next position after
// |pos| that is in the same editable region as this position
DCHECK(highest_root);
- return FirstEditableVisiblePositionAfterPositionInRoot(pos.DeepEquivalent(),
- *highest_root);
+ return FirstEditablePositionAfterPositionInRoot(pos, *highest_root);
}
template <typename Strategy>
@@ -1144,7 +1049,8 @@ static VisiblePositionTemplate<Strategy> NextPositionOfAlgorithm(
return AdjustForwardPositionToAvoidCrossingEditingBoundaries(
next, position.GetPosition());
case kCanSkipOverEditingBoundary:
- return SkipToEndOfEditingBoundary(next, position.GetPosition());
+ return CreateVisiblePosition(SkipToEndOfEditingBoundary(
+ next.DeepEquivalent(), position.GetPosition()));
}
NOTREACHED();
return AdjustForwardPositionToAvoidCrossingEditingBoundaries(
@@ -1167,16 +1073,14 @@ VisiblePositionInFlatTree NextPositionOf(
}
template <typename Strategy>
-static VisiblePositionTemplate<Strategy> SkipToStartOfEditingBoundary(
- const VisiblePositionTemplate<Strategy>& pos,
+static PositionTemplate<Strategy> SkipToStartOfEditingBoundary(
+ const PositionTemplate<Strategy>& pos,
const PositionTemplate<Strategy>& anchor) {
- DCHECK(pos.IsValid()) << pos;
if (pos.IsNull())
return pos;
ContainerNode* highest_root = HighestEditableRoot(anchor);
- ContainerNode* highest_root_of_pos =
- HighestEditableRoot(pos.DeepEquivalent());
+ ContainerNode* highest_root_of_pos = HighestEditableRoot(pos);
// Return |pos| itself if the two are from the very same editable region, or
// both are non-editable.
@@ -1184,17 +1088,17 @@ static VisiblePositionTemplate<Strategy> SkipToStartOfEditingBoundary(
return pos;
// If this is not editable but |pos| has an editable root, skip to the start
- if (!highest_root && highest_root_of_pos)
- return CreateVisiblePosition(PreviousVisuallyDistinctCandidate(
+ if (!highest_root && highest_root_of_pos) {
+ return PreviousVisuallyDistinctCandidate(
PositionTemplate<Strategy>(highest_root_of_pos,
PositionAnchorType::kBeforeAnchor)
- .ParentAnchoredEquivalent()));
+ .ParentAnchoredEquivalent());
+ }
// That must mean that |pos| is not editable. Return the last position
// before |pos| that is in the same editable region as this position
DCHECK(highest_root);
- return LastEditableVisiblePositionBeforePositionInRoot(pos.DeepEquivalent(),
- *highest_root);
+ return LastEditablePositionBeforePositionInRoot(pos, *highest_root);
}
template <typename Strategy>
@@ -1224,7 +1128,8 @@ static VisiblePositionTemplate<Strategy> PreviousPositionOfAlgorithm(
return AdjustBackwardPositionToAvoidCrossingEditingBoundaries(prev,
position);
case kCanSkipOverEditingBoundary:
- return SkipToStartOfEditingBoundary(prev, position);
+ return CreateVisiblePosition(
+ SkipToStartOfEditingBoundary(prev.DeepEquivalent(), position));
}
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units.h b/chromium/third_party/blink/renderer/core/editing/visible_units.h
index fb3495668a8..a696cc393ee 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units.h
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units.h
@@ -116,30 +116,37 @@ PreviousPositionOf(const VisiblePositionInFlatTree&,
// TODO(yoichio): Replace |startOfWord| to |startOfWordPosition| because
// returned Position should be canonicalized with |previousBoundary()| by
// TextItetator.
-CORE_EXPORT Position StartOfWordPosition(const VisiblePosition&,
+CORE_EXPORT Position StartOfWordPosition(const Position&,
EWordSide = kNextWordIfOnBoundary);
CORE_EXPORT VisiblePosition StartOfWord(const VisiblePosition&,
EWordSide = kNextWordIfOnBoundary);
CORE_EXPORT PositionInFlatTree
-StartOfWordPosition(const VisiblePositionInFlatTree&,
+StartOfWordPosition(const PositionInFlatTree&,
EWordSide = kNextWordIfOnBoundary);
CORE_EXPORT VisiblePositionInFlatTree
StartOfWord(const VisiblePositionInFlatTree&,
EWordSide = kNextWordIfOnBoundary);
CORE_EXPORT VisiblePosition EndOfWord(const VisiblePosition&,
EWordSide = kNextWordIfOnBoundary);
+CORE_EXPORT Position EndOfWordPosition(const Position&,
+ EWordSide = kNextWordIfOnBoundary);
CORE_EXPORT PositionInFlatTree
-EndOfWordPosition(const VisiblePositionInFlatTree&,
- EWordSide = kNextWordIfOnBoundary);
+EndOfWordPosition(const PositionInFlatTree&, EWordSide = kNextWordIfOnBoundary);
CORE_EXPORT VisiblePositionInFlatTree
EndOfWord(const VisiblePositionInFlatTree&, EWordSide = kNextWordIfOnBoundary);
-CORE_EXPORT VisiblePosition PreviousWordPosition(const VisiblePosition&);
-CORE_EXPORT VisiblePosition NextWordPosition(const VisiblePosition&);
+CORE_EXPORT PositionWithAffinity PreviousWordPosition(const Position&);
+CORE_EXPORT PositionWithAffinity NextWordPosition(const Position&);
// sentences
+CORE_EXPORT Position StartOfSentencePosition(const Position&);
+CORE_EXPORT PositionInFlatTree
+StartOfSentencePosition(const PositionInFlatTree&);
CORE_EXPORT VisiblePosition StartOfSentence(const VisiblePosition&);
CORE_EXPORT VisiblePositionInFlatTree
StartOfSentence(const VisiblePositionInFlatTree&);
+CORE_EXPORT PositionWithAffinity EndOfSentence(const Position&);
+CORE_EXPORT PositionInFlatTreeWithAffinity
+EndOfSentence(const PositionInFlatTree&);
CORE_EXPORT VisiblePosition EndOfSentence(const VisiblePosition&);
CORE_EXPORT VisiblePositionInFlatTree
EndOfSentence(const VisiblePositionInFlatTree&);
@@ -242,10 +249,11 @@ CORE_EXPORT bool IsEndOfEditableOrNonEditableContent(
bool HasRenderedNonAnonymousDescendantsWithHeight(const LayoutObject*);
-// Returns a hit-tested VisiblePosition for the given point in contents-space
-// coordinates.
-CORE_EXPORT VisiblePosition VisiblePositionForContentsPoint(const IntPoint&,
- LocalFrame*);
+// TODO(editing-dev): We should move this functions to somewhere else.
+// Returns a hit-tested PositionWithAffinity for the given point in
+// contents-space coordinates.
+CORE_EXPORT PositionWithAffinity
+PositionForContentsPointRespectingEditingBoundary(const IntPoint&, LocalFrame*);
CORE_EXPORT bool RendersInDifferentPosition(const Position&, const Position&);
@@ -259,22 +267,6 @@ FloatRect ComputeTextFloatRect(const EphemeralRange&);
// |FirstRectForRange| requires up-to-date layout.
IntRect FirstRectForRange(const EphemeralRange&);
-// Export below functions only for |VisibleUnit| family.
-enum BoundarySearchContextAvailability {
- kDontHaveMoreContext,
- kMayHaveMoreContext
-};
-
-typedef unsigned (*BoundarySearchFunction)(const UChar*,
- unsigned length,
- unsigned offset,
- BoundarySearchContextAvailability,
- bool& need_more_context);
-
-Position PreviousBoundary(const VisiblePosition&, BoundarySearchFunction);
-PositionInFlatTree PreviousBoundary(const VisiblePositionInFlatTree&,
- BoundarySearchFunction);
-
CORE_EXPORT PositionWithAffinity
AdjustForwardPositionToAvoidCrossingEditingBoundaries(
const PositionWithAffinity&,
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_paragraph.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_paragraph.cc
index 50a31761453..de2358b295e 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_paragraph.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_paragraph.cc
@@ -307,6 +307,13 @@ VisiblePosition StartOfNextParagraph(const VisiblePosition& visible_position) {
EndOfParagraph(visible_position, kCanSkipOverEditingBoundary));
VisiblePosition after_paragraph_end(
NextPositionOf(paragraph_end, kCannotCrossEditingBoundary));
+ // It may happen that an element's next visually equivalent candidate is set
+ // to such element when creating the VisualPosition. This may cause infinite
+ // loops when we are iterating over parapgrahs.
+ if (after_paragraph_end.DeepEquivalent() == paragraph_end.DeepEquivalent()) {
+ after_paragraph_end = VisiblePosition::AfterNode(
+ *paragraph_end.DeepEquivalent().AnchorNode());
+ }
// The position after the last position in the last cell of a table
// is not the start of the next paragraph.
if (TableElementJustBefore(after_paragraph_end))
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_sentence.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_sentence.cc
index 870e8c01aa0..50df69b9d00 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_sentence.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_sentence.cc
@@ -40,26 +40,72 @@ namespace blink {
namespace {
-unsigned PreviousSentencePositionBoundary(const UChar* characters,
- unsigned length,
- unsigned,
- BoundarySearchContextAvailability,
- bool&) {
- // FIXME: This is identical to startSentenceBoundary. I'm pretty sure that's
- // not right.
- TextBreakIterator* iterator = SentenceBreakIterator(characters, length);
- // FIXME: The following function can return -1; we don't handle that.
- return iterator->preceding(length);
-}
-
-unsigned StartSentenceBoundary(const UChar* characters,
- unsigned length,
- unsigned,
- BoundarySearchContextAvailability,
- bool&) {
- TextBreakIterator* iterator = SentenceBreakIterator(characters, length);
- // FIXME: The following function can return -1; we don't handle that.
- return iterator->preceding(length);
+PositionInFlatTree PreviousSentencePositionInternal(
+ const PositionInFlatTree& position) {
+ class Finder final : public TextSegments::Finder {
+ STACK_ALLOCATED();
+
+ public:
+ Position Find(const String text, unsigned passed_offset) final {
+ DCHECK_LE(passed_offset, text.length());
+ // "move_by_sentence_boundary.html" requires to skip a space characters
+ // between sentences.
+ const unsigned offset = FindLastNonSpaceCharacter(text, passed_offset);
+ TextBreakIterator* iterator =
+ SentenceBreakIterator(text.Characters16(), text.length());
+ const int result = iterator->preceding(offset);
+ if (result == kTextBreakDone)
+ return Position();
+ return Position::Before(result);
+ }
+
+ private:
+ static unsigned FindLastNonSpaceCharacter(const String text,
+ unsigned passed_offset) {
+ for (unsigned offset = passed_offset; offset; --offset) {
+ if (text[offset - 1] != ' ')
+ return offset;
+ }
+ return 0;
+ }
+ } finder;
+ return TextSegments::FindBoundaryBackward(position, &finder);
+}
+
+PositionInFlatTree StartOfSentenceInternal(const PositionInFlatTree& position) {
+ class Finder final : public TextSegments::Finder {
+ STACK_ALLOCATED();
+
+ public:
+ Position Find(const String text, unsigned passed_offset) final {
+ DCHECK_LE(passed_offset, text.length());
+ // "move_by_sentence_boundary.html" requires to skip a space characters
+ // between sentences.
+ const unsigned offset = FindNonSpaceCharacter(text, passed_offset);
+ TextBreakIterator* iterator =
+ SentenceBreakIterator(text.Characters16(), text.length());
+ const int result = iterator->preceding(offset);
+ if (result == kTextBreakDone) {
+ if (text.length()) {
+ // Block boundaries are also sentence boundaries.
+ return Position::Before(0);
+ }
+ return Position();
+ }
+ return Position::Before(result);
+ }
+
+ private:
+ static unsigned FindNonSpaceCharacter(const String text,
+ unsigned passed_offset) {
+ for (unsigned offset = passed_offset; offset; --offset) {
+ if (text[offset - 1] != ' ')
+ return offset;
+ }
+ return 0;
+ }
+ } finder;
+ return TextSegments::FindBoundaryBackward(position, &finder);
}
// TODO(yosin) This includes the space after the punctuation that marks the end
@@ -77,8 +123,13 @@ PositionInFlatTree EndOfSentenceInternal(const PositionInFlatTree& position) {
// between sentences.
const unsigned offset = FindNonSpaceCharacter(text, passed_offset);
const int result = iterator->following(offset);
- if (result == kTextBreakDone)
+ if (result == kTextBreakDone) {
+ if (text.length()) {
+ // Block boundaries are also sentence boundaries.
+ return Position::After(text.length());
+ }
return Position();
+ }
return result == 0 ? Position::Before(0) : Position::After(result - 1);
}
@@ -141,13 +192,6 @@ PositionInFlatTree NextSentencePositionInternal(
return TextSegments::FindBoundaryForward(position, &finder);
}
-template <typename Strategy>
-VisiblePositionTemplate<Strategy> StartOfSentenceAlgorithm(
- const VisiblePositionTemplate<Strategy>& c) {
- DCHECK(c.IsValid()) << c;
- return CreateVisiblePosition(PreviousBoundary(c, StartSentenceBoundary));
-}
-
} // namespace
PositionInFlatTreeWithAffinity EndOfSentence(const PositionInFlatTree& start) {
@@ -172,10 +216,8 @@ VisiblePositionInFlatTree EndOfSentence(const VisiblePositionInFlatTree& c) {
EphemeralRange ExpandEndToSentenceBoundary(const EphemeralRange& range) {
DCHECK(range.IsNotNull());
- const VisiblePosition& visible_end =
- CreateVisiblePosition(range.EndPosition());
- DCHECK(visible_end.IsNotNull());
- const Position& sentence_end = EndOfSentence(visible_end).DeepEquivalent();
+ const Position sentence_end =
+ EndOfSentence(range.EndPosition()).GetPosition();
// TODO(editing-dev): |sentenceEnd < range.endPosition()| is possible,
// which would trigger a DCHECK in EphemeralRange's constructor if we return
// it directly. However, this shouldn't happen and needs to be fixed.
@@ -188,11 +230,8 @@ EphemeralRange ExpandEndToSentenceBoundary(const EphemeralRange& range) {
EphemeralRange ExpandRangeToSentenceBoundary(const EphemeralRange& range) {
DCHECK(range.IsNotNull());
- const VisiblePosition& visible_start =
- CreateVisiblePosition(range.StartPosition());
- DCHECK(visible_start.IsNotNull());
- const Position& sentence_start =
- StartOfSentence(visible_start).DeepEquivalent();
+ const Position sentence_start =
+ StartOfSentencePosition(range.StartPosition());
// TODO(editing-dev): |sentenceStart > range.startPosition()| is possible,
// which would trigger a DCHECK in EphemeralRange's constructor if we return
// it directly. However, this shouldn't happen and needs to be fixed.
@@ -233,20 +272,43 @@ VisiblePositionInFlatTree NextSentencePosition(
// ----
+PositionInFlatTree PreviousSentencePosition(
+ const PositionInFlatTree& position) {
+ const PositionInFlatTree result = PreviousSentencePositionInternal(position);
+ return AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
+ PositionInFlatTreeWithAffinity(result), position)
+ .GetPosition();
+}
+
+Position PreviousSentencePosition(const Position& position) {
+ return ToPositionInDOMTree(
+ PreviousSentencePosition(ToPositionInFlatTree(position)));
+}
+
VisiblePosition PreviousSentencePosition(const VisiblePosition& c) {
- DCHECK(c.IsValid()) << c;
- VisiblePosition prev = CreateVisiblePosition(
- PreviousBoundary(c, PreviousSentencePositionBoundary));
+ return CreateVisiblePosition(PreviousSentencePosition(c.DeepEquivalent()));
+}
+
+// ----
+
+PositionInFlatTree StartOfSentencePosition(const PositionInFlatTree& position) {
+ const PositionInFlatTree result = StartOfSentenceInternal(position);
return AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
- prev, c.DeepEquivalent());
+ PositionInFlatTreeWithAffinity(result), position)
+ .GetPosition();
+}
+
+Position StartOfSentencePosition(const Position& position) {
+ return ToPositionInDOMTree(
+ StartOfSentencePosition(ToPositionInFlatTree(position)));
}
VisiblePosition StartOfSentence(const VisiblePosition& c) {
- return StartOfSentenceAlgorithm<EditingStrategy>(c);
+ return CreateVisiblePosition(StartOfSentencePosition(c.DeepEquivalent()));
}
VisiblePositionInFlatTree StartOfSentence(const VisiblePositionInFlatTree& c) {
- return StartOfSentenceAlgorithm<EditingInFlatTreeStrategy>(c);
+ return CreateVisiblePosition(StartOfSentencePosition(c.DeepEquivalent()));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_sentence_test.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_sentence_test.cc
index fd08634cbce..ec2ad9687c5 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_sentence_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_sentence_test.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/editing/testing/editing_test_base.h"
#include "third_party/blink/renderer/core/editing/visible_position.h"
+#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
@@ -131,28 +132,28 @@ TEST_F(VisibleUnitsSentenceTest, startOfSentence) {
Node* three = shadow_root->getElementById("three")->firstChild();
Node* four = shadow_root->getElementById("four")->firstChild();
- EXPECT_EQ(Position(one, 0),
+ EXPECT_EQ(Position(three, 0),
StartOfSentence(CreateVisiblePositionInDOMTree(*one, 0))
.DeepEquivalent());
EXPECT_EQ(PositionInFlatTree(three, 0),
StartOfSentence(CreateVisiblePositionInFlatTree(*one, 0))
.DeepEquivalent());
- EXPECT_EQ(Position(one, 0),
+ EXPECT_EQ(Position(three, 0),
StartOfSentence(CreateVisiblePositionInDOMTree(*one, 1))
.DeepEquivalent());
EXPECT_EQ(PositionInFlatTree(three, 0),
StartOfSentence(CreateVisiblePositionInFlatTree(*one, 1))
.DeepEquivalent());
- EXPECT_EQ(Position(one, 0),
+ EXPECT_EQ(Position(three, 0),
StartOfSentence(CreateVisiblePositionInDOMTree(*two, 0))
.DeepEquivalent());
EXPECT_EQ(PositionInFlatTree(three, 0),
StartOfSentence(CreateVisiblePositionInFlatTree(*two, 0))
.DeepEquivalent());
- EXPECT_EQ(Position(one, 0),
+ EXPECT_EQ(Position(three, 0),
StartOfSentence(CreateVisiblePositionInDOMTree(*two, 1))
.DeepEquivalent());
EXPECT_EQ(PositionInFlatTree(three, 0),
@@ -174,4 +175,22 @@ TEST_F(VisibleUnitsSentenceTest, startOfSentence) {
.DeepEquivalent());
}
+TEST_F(VisibleUnitsSentenceTest, SentenceBoundarySkipTextControl) {
+ SetBodyContent("foo <input value=\"xx. xx.\"> bar.");
+ const Node* foo = GetDocument().QuerySelector("input")->previousSibling();
+ const Node* bar = GetDocument().QuerySelector("input")->nextSibling();
+
+ EXPECT_EQ(Position(bar, 5), EndOfSentence(Position(foo, 1)).GetPosition());
+ EXPECT_EQ(PositionInFlatTree(bar, 5),
+ EndOfSentence(PositionInFlatTree(foo, 1)).GetPosition());
+
+ EXPECT_EQ(Position(foo, 0),
+ StartOfSentence(CreateVisiblePosition(Position(bar, 3)))
+ .DeepEquivalent());
+
+ EXPECT_EQ(PositionInFlatTree(foo, 0),
+ StartOfSentence(CreateVisiblePosition(PositionInFlatTree(bar, 3)))
+ .DeepEquivalent());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_test.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_test.cc
index cd11696bd1b..85cc6c02f61 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_test.cc
@@ -103,13 +103,13 @@ TEST_F(VisibleUnitsTest, canonicalPositionOfWithHTMLHtmlElement) {
Node* two = GetDocument().QuerySelector("#two");
Node* three = GetDocument().QuerySelector("#three");
Node* four = GetDocument().QuerySelector("#four");
- Element* html = GetDocument().CreateRawElement(HTMLNames::htmlTag);
+ Element* html = GetDocument().CreateRawElement(html_names::kHTMLTag);
// Move two, three and four into second html element.
html->AppendChild(two);
html->AppendChild(three);
html->AppendChild(four);
one->appendChild(html);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(Position(),
CanonicalPositionOf(Position(GetDocument().documentElement(), 0)));
@@ -282,13 +282,13 @@ TEST_F(VisibleUnitsTest, IsVisuallyEquivalentCandidateWithHTMLHtmlElement) {
Node* two = GetDocument().QuerySelector("#two");
Node* three = GetDocument().QuerySelector("#three");
Node* four = GetDocument().QuerySelector("#four");
- Element* html = GetDocument().CreateRawElement(HTMLNames::htmlTag);
+ Element* html = GetDocument().CreateRawElement(html_names::kHTMLTag);
// Move two, three and four into second html element.
html->AppendChild(two);
html->AppendChild(three);
html->AppendChild(four);
one->appendChild(html);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(IsVisuallyEquivalentCandidate(
Position(GetDocument().documentElement(), 0)));
@@ -319,10 +319,10 @@ TEST_F(VisibleUnitsTest, isVisuallyEquivalentCandidateWithHTMLBodyElement) {
Node* two = GetDocument().QuerySelector("#two");
Node* three = GetDocument().QuerySelector("#three");
Node* four = GetDocument().QuerySelector("#four");
- Element* body = GetDocument().CreateRawElement(HTMLNames::bodyTag);
- Element* empty_body = GetDocument().CreateRawElement(HTMLNames::bodyTag);
- Element* div = GetDocument().CreateRawElement(HTMLNames::divTag);
- Element* br = GetDocument().CreateRawElement(HTMLNames::brTag);
+ Element* body = GetDocument().CreateRawElement(html_names::kBodyTag);
+ Element* empty_body = GetDocument().CreateRawElement(html_names::kBodyTag);
+ Element* div = GetDocument().CreateRawElement(html_names::kDivTag);
+ Element* br = GetDocument().CreateRawElement(html_names::kBrTag);
empty_body->appendChild(div);
empty_body->appendChild(br);
one->appendChild(empty_body);
@@ -354,7 +354,7 @@ TEST_F(VisibleUnitsTest, isVisuallyEquivalentCandidateWithHTMLBodyElement) {
}
TEST_F(VisibleUnitsTest, isVisuallyEquivalentCandidateWithDocument) {
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(IsVisuallyEquivalentCandidate(Position(&GetDocument(), 0)));
}
@@ -421,7 +421,7 @@ TEST_F(VisibleUnitsTest, mostBackwardCaretPositionFirstLetterSplit) {
Node* first_letter = sample->firstChild();
// Split "abc" into "a" "bc"
Text* remaining = ToText(first_letter)->splitText(1, ASSERT_NO_EXCEPTION);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(Position(sample, 0),
MostBackwardCaretPosition(Position(first_letter, 0)));
@@ -445,7 +445,7 @@ TEST_F(VisibleUnitsTest, mostForwardCaretPositionAfterAnchor) {
"<b id='two'>22</b><content select=#one></content><b id='three'>333</b>";
SetBodyContent(body_content);
ShadowRoot* shadow_root = SetShadowContent(shadow_content, "host");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* host = GetDocument().getElementById("host");
Element* one = GetDocument().getElementById("one");
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_word.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_word.cc
index 6bea8e9672f..ae72f1bc5ce 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_word.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_word.cc
@@ -100,7 +100,7 @@ PositionInFlatTree NextWordPositionInternal(
// We stop searching when the character preceding the break is
// alphanumeric or underscore.
if (static_cast<unsigned>(runner) < text.length() &&
- (WTF::Unicode::IsAlphanumeric(text[runner - 1]) ||
+ (WTF::unicode::IsAlphanumeric(text[runner - 1]) ||
text[runner - 1] == kLowLineCharacter))
return Position::After(runner - 1);
}
@@ -110,59 +110,72 @@ PositionInFlatTree NextWordPositionInternal(
return TextSegments::FindBoundaryForward(position, &finder);
}
-unsigned PreviousWordPositionBoundary(
- const UChar* characters,
- unsigned length,
- unsigned offset,
- BoundarySearchContextAvailability may_have_more_context,
- bool& need_more_context) {
- if (may_have_more_context &&
- !StartOfLastWordBoundaryContext(characters, offset)) {
- need_more_context = true;
- return 0;
- }
- need_more_context = false;
- return FindNextWordBackward(characters, length, offset);
-}
-
-unsigned StartWordBoundary(
- const UChar* characters,
- unsigned length,
- unsigned offset,
- BoundarySearchContextAvailability may_have_more_context,
- bool& need_more_context) {
- TRACE_EVENT0("blink", "startWordBoundary");
- DCHECK(offset);
- if (may_have_more_context &&
- !StartOfLastWordBoundaryContext(characters, offset)) {
- need_more_context = true;
- return 0;
- }
- need_more_context = false;
- U16_BACK_1(characters, 0, offset);
- return FindWordStartBoundary(characters, length, offset);
-}
-
-template <typename Strategy>
-PositionTemplate<Strategy> StartOfWordAlgorithm(
- const VisiblePositionTemplate<Strategy>& c,
- EWordSide side) {
- DCHECK(c.IsValid()) << c;
- // TODO(yosin) This returns a null VP for c at the start of the document
- // and |side| == |kPreviousWordIfOnBoundary|
- VisiblePositionTemplate<Strategy> p = c;
- if (side == kNextWordIfOnBoundary) {
- // at paragraph end, the startofWord is the current position
- if (IsEndOfParagraph(c))
- return c.DeepEquivalent();
-
- p = NextPositionOf(c);
- if (p.IsNull())
- return c.DeepEquivalent();
- }
- return PreviousBoundary(p, StartWordBoundary);
+PositionInFlatTree PreviousWordPositionInternal(
+ const PositionInFlatTree& position) {
+ class Finder final : public TextSegments::Finder {
+ STACK_ALLOCATED();
+
+ private:
+ Position Find(const String text, unsigned offset) final {
+ DCHECK_LE(offset, text.length());
+ if (!offset || text.length() == 0)
+ return Position();
+ TextBreakIterator* it =
+ WordBreakIterator(text.Characters16(), text.length());
+ for (int runner = it->preceding(offset); runner != kTextBreakDone;
+ runner = it->preceding(runner)) {
+ // We stop searching when the character following the break is
+ // alphanumeric or underscore.
+ if (runner && (WTF::unicode::IsAlphanumeric(text[runner]) ||
+ text[runner] == kLowLineCharacter))
+ return Position::Before(runner);
+ }
+ return Position::Before(0);
+ }
+ } finder;
+ return TextSegments::FindBoundaryBackward(position, &finder);
}
+PositionInFlatTree StartOfWordPositionInternal(
+ const PositionInFlatTree& position,
+ EWordSide side) {
+ class Finder final : public TextSegments::Finder {
+ STACK_ALLOCATED();
+
+ public:
+ Finder(EWordSide side) : side_(side) {}
+
+ private:
+ Position Find(const String text, unsigned offset) final {
+ DCHECK_LE(offset, text.length());
+ if (!is_first_time_)
+ return FindInternal(text, offset);
+ is_first_time_ = false;
+ if (side_ == kNextWordIfOnBoundary) {
+ if (offset == text.length())
+ return Position::After(text.length());
+ return FindInternal(text, offset + 1);
+ }
+ if (!offset)
+ return Position::Before(offset);
+ return FindInternal(text, offset);
+ }
+
+ static Position FindInternal(const String text, unsigned offset) {
+ DCHECK_LE(offset, text.length());
+ TextBreakIterator* it =
+ WordBreakIterator(text.Characters16(), text.length());
+ const int result = it->preceding(offset);
+ if (result == kTextBreakDone)
+ return Position();
+ return Position::Before(result);
+ }
+
+ const EWordSide side_;
+ bool is_first_time_ = true;
+ } finder(side);
+ return TextSegments::FindBoundaryBackward(position, &finder);
+}
} // namespace
PositionInFlatTree EndOfWordPosition(const PositionInFlatTree& start,
@@ -212,38 +225,41 @@ PositionWithAffinity NextWordPosition(const Position& start) {
return ToPositionInDOMTreeWithAffinity(next);
}
-// TODO(yosin): This function will be removed by replacing call sites to use
-// |Position| version. since there are only two call sites, one is in test.
-VisiblePosition NextWordPosition(const VisiblePosition& c) {
- DCHECK(c.IsValid()) << c;
- return CreateVisiblePosition(NextWordPosition(c.DeepEquivalent()));
+PositionInFlatTreeWithAffinity PreviousWordPosition(
+ const PositionInFlatTree& start) {
+ const PositionInFlatTree prev = PreviousWordPositionInternal(start);
+ return AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
+ PositionInFlatTreeWithAffinity(prev), start);
}
-VisiblePosition PreviousWordPosition(const VisiblePosition& c) {
- DCHECK(c.IsValid()) << c;
- VisiblePosition prev =
- CreateVisiblePosition(PreviousBoundary(c, PreviousWordPositionBoundary));
- return AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
- prev, c.DeepEquivalent());
+PositionWithAffinity PreviousWordPosition(const Position& start) {
+ const PositionInFlatTreeWithAffinity& prev =
+ PreviousWordPosition(ToPositionInFlatTree(start));
+ return ToPositionInDOMTreeWithAffinity(prev);
}
-Position StartOfWordPosition(const VisiblePosition& position, EWordSide side) {
- return StartOfWordAlgorithm<EditingStrategy>(position, side);
+PositionInFlatTree StartOfWordPosition(const PositionInFlatTree& position,
+ EWordSide side) {
+ const PositionInFlatTree start = StartOfWordPositionInternal(position, side);
+ return AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
+ PositionInFlatTreeWithAffinity(start), position)
+ .GetPosition();
}
-VisiblePosition StartOfWord(const VisiblePosition& position, EWordSide side) {
- return CreateVisiblePosition(StartOfWordPosition(position, side));
+Position StartOfWordPosition(const Position& position, EWordSide side) {
+ return ToPositionInDOMTree(
+ StartOfWordPosition(ToPositionInFlatTree(position), side));
}
-PositionInFlatTree StartOfWordPosition(
- const VisiblePositionInFlatTree& position,
- EWordSide side) {
- return StartOfWordAlgorithm<EditingInFlatTreeStrategy>(position, side);
+VisiblePosition StartOfWord(const VisiblePosition& position, EWordSide side) {
+ return CreateVisiblePosition(
+ StartOfWordPosition(position.DeepEquivalent(), side));
}
VisiblePositionInFlatTree StartOfWord(const VisiblePositionInFlatTree& position,
EWordSide side) {
- return CreateVisiblePosition(StartOfWordPosition(position, side));
+ return CreateVisiblePosition(
+ StartOfWordPosition(position.DeepEquivalent(), side));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_word_test.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_word_test.cc
index bf68bf269ed..244f469570b 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_word_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_word_test.cc
@@ -33,13 +33,13 @@ class VisibleUnitsWordTest : public EditingTestBase {
std::string DoNextWord(const std::string& selection_text) {
const Position position = SetSelectionTextToBody(selection_text).Base();
return GetCaretTextFromBody(
- NextWordPosition(CreateVisiblePosition(position)).DeepEquivalent());
+ CreateVisiblePosition(NextWordPosition(position)).DeepEquivalent());
}
std::string DoPreviousWord(const std::string& selection_text) {
const Position position = SetSelectionTextToBody(selection_text).Base();
const Position result =
- PreviousWordPosition(CreateVisiblePosition(position)).DeepEquivalent();
+ CreateVisiblePosition(PreviousWordPosition(position)).DeepEquivalent();
if (result.IsNull())
return GetSelectionTextFromBody(SelectionInDOMTree());
return GetCaretTextFromBody(result);
@@ -75,7 +75,7 @@ INSTANTIATE_TEST_CASE_P(All,
ParameterizedVisibleUnitsWordTest,
::testing::Bool());
-TEST_F(VisibleUnitsWordTest, StartOfWordBasic) {
+TEST_P(ParameterizedVisibleUnitsWordTest, StartOfWordBasic) {
EXPECT_EQ("<p> |(1) abc def</p>", DoStartOfWord("<p>| (1) abc def</p>"));
EXPECT_EQ("<p> |(1) abc def</p>", DoStartOfWord("<p> |(1) abc def</p>"));
EXPECT_EQ("<p> (|1) abc def</p>", DoStartOfWord("<p> (|1) abc def</p>"));
@@ -92,7 +92,8 @@ TEST_F(VisibleUnitsWordTest, StartOfWordBasic) {
EXPECT_EQ("<p> (1) abc def|</p>", DoStartOfWord("<p> (1) abc def</p>|"));
}
-TEST_F(VisibleUnitsWordTest, StartOfWordPreviousWordIfOnBoundaryBasic) {
+TEST_P(ParameterizedVisibleUnitsWordTest,
+ StartOfWordPreviousWordIfOnBoundaryBasic) {
EXPECT_EQ("<p> |(1) abc def</p>",
DoStartOfWord("<p>| (1) abc def</p>",
EWordSide::kPreviousWordIfOnBoundary));
@@ -137,12 +138,12 @@ TEST_F(VisibleUnitsWordTest, StartOfWordPreviousWordIfOnBoundaryBasic) {
EWordSide::kPreviousWordIfOnBoundary));
}
-TEST_F(VisibleUnitsWordTest, StartOfWordCrossing) {
+TEST_P(ParameterizedVisibleUnitsWordTest, StartOfWordCrossing) {
EXPECT_EQ("<b>|abc</b><i>def</i>", DoStartOfWord("<b>abc</b><i>|def</i>"));
EXPECT_EQ("<b>abc</b><i>def|</i>", DoStartOfWord("<b>abc</b><i>def</i>|"));
}
-TEST_F(VisibleUnitsWordTest, StartOfWordFirstLetter) {
+TEST_P(ParameterizedVisibleUnitsWordTest, StartOfWordFirstLetter) {
InsertStyleElement("p::first-letter {font-size:200%;}");
// Note: Expectations should match with |StartOfWordBasic|.
EXPECT_EQ("<p> |(1) abc def</p>", DoStartOfWord("<p>| (1) abc def</p>"));
@@ -161,7 +162,7 @@ TEST_F(VisibleUnitsWordTest, StartOfWordFirstLetter) {
EXPECT_EQ("<p> (1) abc def|</p>", DoStartOfWord("<p> (1) abc def</p>|"));
}
-TEST_F(VisibleUnitsWordTest, StartOfWordShadowDOM) {
+TEST_P(ParameterizedVisibleUnitsWordTest, StartOfWordShadowDOM) {
const char* body_content =
"<a id=host><b id=one>1</b> <b id=two>22</b></a><i id=three>333</i>";
const char* shadow_content =
@@ -199,17 +200,18 @@ TEST_F(VisibleUnitsWordTest, StartOfWordShadowDOM) {
StartOfWord(CreateVisiblePositionInFlatTree(*two, 0)).DeepEquivalent());
EXPECT_EQ(
- Position(one, 0),
+ Position(four, 0),
StartOfWord(CreateVisiblePositionInDOMTree(*two, 1)).DeepEquivalent());
EXPECT_EQ(
PositionInFlatTree(four, 0),
StartOfWord(CreateVisiblePositionInFlatTree(*two, 1)).DeepEquivalent());
+ // DOM tree canonicalization moves the result to a wrong position.
EXPECT_EQ(
- Position(one, 0),
+ Position(two, 2),
StartOfWord(CreateVisiblePositionInDOMTree(*three, 1)).DeepEquivalent());
EXPECT_EQ(
- PositionInFlatTree(space, 1),
+ PositionInFlatTree(three, 0),
StartOfWord(CreateVisiblePositionInFlatTree(*three, 1)).DeepEquivalent());
EXPECT_EQ(
@@ -220,14 +222,15 @@ TEST_F(VisibleUnitsWordTest, StartOfWordShadowDOM) {
StartOfWord(CreateVisiblePositionInFlatTree(*four, 1)).DeepEquivalent());
EXPECT_EQ(
- Position(space, 1),
+ Position(one, 0),
StartOfWord(CreateVisiblePositionInDOMTree(*five, 1)).DeepEquivalent());
+ // Flat tree canonicalization moves result to downstream position
EXPECT_EQ(
PositionInFlatTree(space, 1),
StartOfWord(CreateVisiblePositionInFlatTree(*five, 1)).DeepEquivalent());
}
-TEST_F(VisibleUnitsWordTest, StartOfWordTextSecurity) {
+TEST_P(ParameterizedVisibleUnitsWordTest, StartOfWordTextSecurity) {
// Note: |StartOfWord()| considers security characters as a sequence "x".
InsertStyleElement("s {-webkit-text-security:disc;}");
EXPECT_EQ("|abc<s>foo bar</s>baz", DoStartOfWord("|abc<s>foo bar</s>baz"));
@@ -241,6 +244,53 @@ TEST_F(VisibleUnitsWordTest, StartOfWordTextSecurity) {
EXPECT_EQ("|abc<s>foo bar</s>baz", DoStartOfWord("abc<s>foo bar</s>b|az"));
}
+TEST_P(ParameterizedVisibleUnitsWordTest, StartOfWordTextControl) {
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("|foo<input value=\"bla\">bar"));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("f|oo<input value=\"bla\">bar"));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("fo|o<input value=\"bla\">bar"));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoStartOfWord("foo|<input value=\"bla\">bar"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoStartOfWord("foo<input value=\"bla\">|bar"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoStartOfWord("foo<input value=\"bla\">b|ar"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoStartOfWord("foo<input value=\"bla\">ba|r"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoStartOfWord("foo<input value=\"bla\">bar|"));
+}
+
+TEST_P(ParameterizedVisibleUnitsWordTest,
+ StartOfWordPreviousWordIfOnBoundaryTextControl) {
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("|foo<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("f|oo<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("fo|o<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoStartOfWord("foo|<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoStartOfWord("foo<input value=\"bla\">|bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoStartOfWord("foo<input value=\"bla\">b|ar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoStartOfWord("foo<input value=\"bla\">ba|r",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoStartOfWord("foo<input value=\"bla\">bar|",
+ EWordSide::kPreviousWordIfOnBoundary));
+}
+
TEST_P(ParameterizedVisibleUnitsWordTest, EndOfWordBasic) {
EXPECT_EQ("<p> (|1) abc def</p>", DoEndOfWord("<p>| (1) abc def</p>"));
EXPECT_EQ("<p> (|1) abc def</p>", DoEndOfWord("<p> |(1) abc def</p>"));
@@ -383,6 +433,53 @@ TEST_P(ParameterizedVisibleUnitsWordTest, EndOfWordTextSecurity) {
EXPECT_EQ("abc<s>foo bar</s>baz|", DoEndOfWord("abc<s>foo bar</s>b|az"));
}
+TEST_P(ParameterizedVisibleUnitsWordTest, EndOfWordTextControl) {
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoEndOfWord("|foo<input value=\"bla\">bar"));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoEndOfWord("f|oo<input value=\"bla\">bar"));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoEndOfWord("fo|o<input value=\"bla\">bar"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoEndOfWord("foo|<input value=\"bla\">bar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">|bar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">b|ar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">ba|r"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">bar|"));
+}
+
+TEST_P(ParameterizedVisibleUnitsWordTest,
+ EndOfWordPreviousWordIfOnBoundaryTextControl) {
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoEndOfWord("|foo<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoEndOfWord("f|oo<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoEndOfWord("fo|o<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoEndOfWord("foo|<input value=\"bla\">bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoEndOfWord("foo<input value=\"bla\">|bar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">b|ar",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">ba|r",
+ EWordSide::kPreviousWordIfOnBoundary));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoEndOfWord("foo<input value=\"bla\">bar|",
+ EWordSide::kPreviousWordIfOnBoundary));
+}
+
TEST_P(ParameterizedVisibleUnitsWordTest, NextWordBasic) {
EXPECT_EQ("<p> (1|) abc def</p>", DoNextWord("<p>| (1) abc def</p>"));
EXPECT_EQ("<p> (1|) abc def</p>", DoNextWord("<p> |(1) abc def</p>"));
@@ -449,9 +546,28 @@ TEST_P(ParameterizedVisibleUnitsWordTest, NextWordSkipTab) {
EXPECT_EQ("<p><s>\t</s>foo|</p>", DoNextWord("<p><s>\t|</s>foo</p>"));
}
+TEST_P(ParameterizedVisibleUnitsWordTest, NextWordSkipTextControl) {
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoNextWord("|foo<input value=\"bla\">bar"));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoNextWord("f|oo<input value=\"bla\">bar"));
+ EXPECT_EQ("foo|<input value=\"bla\">bar",
+ DoNextWord("fo|o<input value=\"bla\">bar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoNextWord("foo|<input value=\"bla\">bar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoNextWord("foo<input value=\"bla\">|bar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoNextWord("foo<input value=\"bla\">b|ar"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoNextWord("foo<input value=\"bla\">ba|r"));
+ EXPECT_EQ("foo<input value=\"bla\">bar|",
+ DoNextWord("foo<input value=\"bla\">bar|"));
+}
+
//----
-TEST_F(VisibleUnitsWordTest, PreviousWordBasic) {
+TEST_P(ParameterizedVisibleUnitsWordTest, PreviousWordBasic) {
EXPECT_EQ("<p> |(1) abc def</p>", DoPreviousWord("<p>| (1) abc def</p>"));
EXPECT_EQ("<p> |(1) abc def</p>", DoPreviousWord("<p> |(1) abc def</p>"));
EXPECT_EQ("<p> |(1) abc def</p>", DoPreviousWord("<p> (|1) abc def</p>"));
@@ -468,4 +584,23 @@ TEST_F(VisibleUnitsWordTest, PreviousWordBasic) {
EXPECT_EQ("<p> (1) abc |def</p>", DoPreviousWord("<p> (1) abc def</p>|"));
}
+TEST_P(ParameterizedVisibleUnitsWordTest, PreviousWordSkipTextControl) {
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoPreviousWord("|foo<input value=\"bla\">bar"));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoPreviousWord("f|oo<input value=\"bla\">bar"));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoPreviousWord("fo|o<input value=\"bla\">bar"));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoPreviousWord("foo|<input value=\"bla\">bar"));
+ EXPECT_EQ("|foo<input value=\"bla\">bar",
+ DoPreviousWord("foo<input value=\"bla\">|bar"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoPreviousWord("foo<input value=\"bla\">b|ar"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoPreviousWord("foo<input value=\"bla\">ba|r"));
+ EXPECT_EQ("foo<input value=\"bla\">|bar",
+ DoPreviousWord("foo<input value=\"bla\">bar|"));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/web_substring_util.mm b/chromium/third_party/blink/renderer/core/editing/web_substring_util.mm
index 6e7b50fd2bb..0a0c19a09be 100644
--- a/chromium/third_party/blink/renderer/core/editing/web_substring_util.mm
+++ b/chromium/third_party/blink/renderer/core/editing/web_substring_util.mm
@@ -161,7 +161,7 @@ NSAttributedString* WebSubstringUtil::AttributedWordAtPoint(
WebPoint point,
WebPoint& baseline_point) {
HitTestResult result = static_cast<WebFrameWidgetBase*>(frame_widget)
- ->CoreHitTestResultAt(point);
+ ->CoreHitTestResultAt(IntPoint(point));
if (!result.InnerNode())
return nil;
diff --git a/chromium/third_party/blink/renderer/core/events/animation_event.cc b/chromium/third_party/blink/renderer/core/events/animation_event.cc
index ff1f40aaac3..b633a201e5e 100644
--- a/chromium/third_party/blink/renderer/core/events/animation_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/animation_event.cc
@@ -25,18 +25,18 @@
#include "third_party/blink/renderer/core/events/animation_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
AnimationEvent::AnimationEvent() : elapsed_time_(0.0) {}
AnimationEvent::AnimationEvent(const AtomicString& type,
- const AnimationEventInit& initializer)
+ const AnimationEventInit* initializer)
: Event(type, initializer),
- animation_name_(initializer.animationName()),
- elapsed_time_(initializer.elapsedTime()),
- pseudo_element_(initializer.pseudoElement()) {}
+ animation_name_(initializer->animationName()),
+ elapsed_time_(initializer->elapsedTime()),
+ pseudo_element_(initializer->pseudoElement()) {}
AnimationEvent::AnimationEvent(const AtomicString& type,
const String& animation_name,
@@ -62,7 +62,7 @@ const String& AnimationEvent::pseudoElement() const {
}
const AtomicString& AnimationEvent::InterfaceName() const {
- return EventNames::AnimationEvent;
+ return event_interface_names::kAnimationEvent;
}
void AnimationEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/animation_event.h b/chromium/third_party/blink/renderer/core/events/animation_event.h
index 8d4478eb86e..199d47f182a 100644
--- a/chromium/third_party/blink/renderer/core/events/animation_event.h
+++ b/chromium/third_party/blink/renderer/core/events/animation_event.h
@@ -44,7 +44,7 @@ class AnimationEvent final : public Event {
pseudo_element);
}
static AnimationEvent* Create(const AtomicString& type,
- const AnimationEventInit& initializer) {
+ const AnimationEventInit* initializer) {
return new AnimationEvent(type, initializer);
}
@@ -64,7 +64,7 @@ class AnimationEvent final : public Event {
const String& animation_name,
double elapsed_time,
const String& pseudo_element);
- AnimationEvent(const AtomicString&, const AnimationEventInit&);
+ AnimationEvent(const AtomicString&, const AnimationEventInit*);
String animation_name_;
double elapsed_time_;
diff --git a/chromium/third_party/blink/renderer/core/events/animation_playback_event.cc b/chromium/third_party/blink/renderer/core/events/animation_playback_event.cc
index 538e58dc3bd..e9aeb2b5fd2 100644
--- a/chromium/third_party/blink/renderer/core/events/animation_playback_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/animation_playback_event.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/events/animation_playback_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -17,12 +17,12 @@ AnimationPlaybackEvent::AnimationPlaybackEvent(const AtomicString& type,
AnimationPlaybackEvent::AnimationPlaybackEvent(
const AtomicString& type,
- const AnimationPlaybackEventInit& initializer)
+ const AnimationPlaybackEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasCurrentTime())
- current_time_ = initializer.currentTime();
- if (initializer.hasTimelineTime())
- timeline_time_ = initializer.timelineTime();
+ if (initializer->hasCurrentTime())
+ current_time_ = initializer->currentTime();
+ if (initializer->hasTimelineTime())
+ timeline_time_ = initializer->timelineTime();
}
AnimationPlaybackEvent::~AnimationPlaybackEvent() = default;
@@ -38,7 +38,7 @@ double AnimationPlaybackEvent::timelineTime(bool& is_null) const {
}
const AtomicString& AnimationPlaybackEvent::InterfaceName() const {
- return EventNames::AnimationPlaybackEvent;
+ return event_interface_names::kAnimationPlaybackEvent;
}
void AnimationPlaybackEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/animation_playback_event.h b/chromium/third_party/blink/renderer/core/events/animation_playback_event.h
index f99f5d2d852..ed953d6998b 100644
--- a/chromium/third_party/blink/renderer/core/events/animation_playback_event.h
+++ b/chromium/third_party/blink/renderer/core/events/animation_playback_event.h
@@ -22,7 +22,7 @@ class AnimationPlaybackEvent final : public Event {
}
static AnimationPlaybackEvent* Create(
const AtomicString& type,
- const AnimationPlaybackEventInit& initializer) {
+ const AnimationPlaybackEventInit* initializer) {
return new AnimationPlaybackEvent(type, initializer);
}
@@ -40,7 +40,7 @@ class AnimationPlaybackEvent final : public Event {
double current_time,
double timeline_time);
AnimationPlaybackEvent(const AtomicString&,
- const AnimationPlaybackEventInit&);
+ const AnimationPlaybackEventInit*);
base::Optional<double> current_time_;
base::Optional<double> timeline_time_;
diff --git a/chromium/third_party/blink/renderer/core/events/application_cache_error_event.cc b/chromium/third_party/blink/renderer/core/events/application_cache_error_event.cc
index 4c64c2a489e..561ed3ace45 100644
--- a/chromium/third_party/blink/renderer/core/events/application_cache_error_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/application_cache_error_event.cc
@@ -46,7 +46,7 @@ ApplicationCacheErrorEvent::ApplicationCacheErrorEvent(
const String& url,
int status,
const String& message)
- : Event(EventTypeNames::error, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kError, Bubbles::kNo, Cancelable::kNo),
reason_(ErrorReasonToString(reason)),
url_(url),
status_(status),
@@ -54,16 +54,16 @@ ApplicationCacheErrorEvent::ApplicationCacheErrorEvent(
ApplicationCacheErrorEvent::ApplicationCacheErrorEvent(
const AtomicString& event_type,
- const ApplicationCacheErrorEventInit& initializer)
+ const ApplicationCacheErrorEventInit* initializer)
: Event(event_type, initializer), status_(0) {
- if (initializer.hasReason())
- reason_ = initializer.reason();
- if (initializer.hasURL())
- url_ = initializer.url();
- if (initializer.hasStatus())
- status_ = initializer.status();
- if (initializer.hasMessage())
- message_ = initializer.message();
+ if (initializer->hasReason())
+ reason_ = initializer->reason();
+ if (initializer->hasURL())
+ url_ = initializer->url();
+ if (initializer->hasStatus())
+ status_ = initializer->status();
+ if (initializer->hasMessage())
+ message_ = initializer->message();
}
ApplicationCacheErrorEvent::~ApplicationCacheErrorEvent() = default;
diff --git a/chromium/third_party/blink/renderer/core/events/application_cache_error_event.h b/chromium/third_party/blink/renderer/core/events/application_cache_error_event.h
index c293a8ed2e4..c4822d2dfc1 100644
--- a/chromium/third_party/blink/renderer/core/events/application_cache_error_event.h
+++ b/chromium/third_party/blink/renderer/core/events/application_cache_error_event.h
@@ -7,7 +7,7 @@
#include "third_party/blink/public/platform/web_application_cache_host_client.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/application_cache_error_event_init.h"
#include "third_party/blink/renderer/core/loader/appcache/application_cache_host.h"
@@ -29,7 +29,7 @@ class ApplicationCacheErrorEvent final : public Event {
static ApplicationCacheErrorEvent* Create(
const AtomicString& event_type,
- const ApplicationCacheErrorEventInit& initializer) {
+ const ApplicationCacheErrorEventInit* initializer) {
return new ApplicationCacheErrorEvent(event_type, initializer);
}
@@ -39,7 +39,7 @@ class ApplicationCacheErrorEvent final : public Event {
const String& message() const { return message_; }
const AtomicString& InterfaceName() const override {
- return EventNames::ApplicationCacheErrorEvent;
+ return event_interface_names::kApplicationCacheErrorEvent;
}
void Trace(blink::Visitor*) override;
@@ -50,7 +50,7 @@ class ApplicationCacheErrorEvent final : public Event {
int status,
const String& message);
ApplicationCacheErrorEvent(const AtomicString& event_type,
- const ApplicationCacheErrorEventInit& initializer);
+ const ApplicationCacheErrorEventInit* initializer);
String reason_;
String url_;
diff --git a/chromium/third_party/blink/renderer/core/events/before_text_inserted_event.cc b/chromium/third_party/blink/renderer/core/events/before_text_inserted_event.cc
index c08be5d5a57..8d7166a48ad 100644
--- a/chromium/third_party/blink/renderer/core/events/before_text_inserted_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/before_text_inserted_event.cc
@@ -25,13 +25,13 @@
#include "third_party/blink/renderer/core/events/before_text_inserted_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/event_type_names.h"
namespace blink {
BeforeTextInsertedEvent::BeforeTextInsertedEvent(const String& text)
- : Event(EventTypeNames::webkitBeforeTextInserted,
+ : Event(event_type_names::kWebkitBeforeTextInserted,
Bubbles::kNo,
Cancelable::kYes),
text_(text) {}
@@ -40,7 +40,7 @@ BeforeTextInsertedEvent::~BeforeTextInsertedEvent() = default;
const AtomicString& BeforeTextInsertedEvent::InterfaceName() const {
// Notice that there is no BeforeTextInsertedEvent.idl.
- return EventNames::Event;
+ return event_interface_names::kEvent;
}
void BeforeTextInsertedEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/before_unload_event.h b/chromium/third_party/blink/renderer/core/events/before_unload_event.h
index f82a6a78bef..6d735418639 100644
--- a/chromium/third_party/blink/renderer/core/events/before_unload_event.h
+++ b/chromium/third_party/blink/renderer/core/events/before_unload_event.h
@@ -26,7 +26,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_BEFORE_UNLOAD_EVENT_H_
#include "third_party/blink/renderer/core/dom/events/event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -46,7 +46,7 @@ class BeforeUnloadEvent final : public Event {
String returnValue() const { return return_value_; }
const AtomicString& InterfaceName() const override {
- return EventNames::BeforeUnloadEvent;
+ return event_interface_names::kBeforeUnloadEvent;
}
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/events/clipboard_event.cc b/chromium/third_party/blink/renderer/core/events/clipboard_event.cc
index d4af8dc604d..8bd5975a084 100644
--- a/chromium/third_party/blink/renderer/core/events/clipboard_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/clipboard_event.cc
@@ -22,6 +22,8 @@
#include "third_party/blink/renderer/core/events/clipboard_event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
+
namespace blink {
ClipboardEvent::ClipboardEvent(const AtomicString& type,
@@ -30,13 +32,13 @@ ClipboardEvent::ClipboardEvent(const AtomicString& type,
clipboard_data_(clipboard_data) {}
ClipboardEvent::ClipboardEvent(const AtomicString& type,
- const ClipboardEventInit& initializer)
- : Event(type, initializer), clipboard_data_(initializer.clipboardData()) {}
+ const ClipboardEventInit* initializer)
+ : Event(type, initializer), clipboard_data_(initializer->clipboardData()) {}
ClipboardEvent::~ClipboardEvent() = default;
const AtomicString& ClipboardEvent::InterfaceName() const {
- return EventNames::ClipboardEvent;
+ return event_interface_names::kClipboardEvent;
}
bool ClipboardEvent::IsClipboardEvent() const {
diff --git a/chromium/third_party/blink/renderer/core/events/clipboard_event.h b/chromium/third_party/blink/renderer/core/events/clipboard_event.h
index a0a9d62936e..a0a8afbf758 100644
--- a/chromium/third_party/blink/renderer/core/events/clipboard_event.h
+++ b/chromium/third_party/blink/renderer/core/events/clipboard_event.h
@@ -43,7 +43,7 @@ class ClipboardEvent final : public Event {
}
static ClipboardEvent* Create(const AtomicString& type,
- const ClipboardEventInit& initializer) {
+ const ClipboardEventInit* initializer) {
return new ClipboardEvent(type, initializer);
}
@@ -54,7 +54,7 @@ class ClipboardEvent final : public Event {
private:
ClipboardEvent(const AtomicString& type,
DataTransfer* clipboard_data);
- ClipboardEvent(const AtomicString& type, const ClipboardEventInit&);
+ ClipboardEvent(const AtomicString& type, const ClipboardEventInit*);
const AtomicString& InterfaceName() const override;
bool IsClipboardEvent() const override;
diff --git a/chromium/third_party/blink/renderer/core/events/composition_event.cc b/chromium/third_party/blink/renderer/core/events/composition_event.cc
index 820fd12e59d..cedcc0c65ee 100644
--- a/chromium/third_party/blink/renderer/core/events/composition_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/composition_event.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/events/composition_event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
namespace blink {
@@ -47,10 +48,10 @@ CompositionEvent::CompositionEvent(const AtomicString& type,
data_(data) {}
CompositionEvent::CompositionEvent(const AtomicString& type,
- const CompositionEventInit& initializer)
+ const CompositionEventInit* initializer)
: UIEvent(type, initializer) {
- if (initializer.hasData())
- data_ = initializer.data();
+ if (initializer->hasData())
+ data_ = initializer->data();
}
CompositionEvent::~CompositionEvent() = default;
@@ -69,7 +70,7 @@ void CompositionEvent::initCompositionEvent(const AtomicString& type,
}
const AtomicString& CompositionEvent::InterfaceName() const {
- return EventNames::CompositionEvent;
+ return event_interface_names::kCompositionEvent;
}
bool CompositionEvent::IsCompositionEvent() const {
diff --git a/chromium/third_party/blink/renderer/core/events/composition_event.h b/chromium/third_party/blink/renderer/core/events/composition_event.h
index 5eaecddd477..6588fe28977 100644
--- a/chromium/third_party/blink/renderer/core/events/composition_event.h
+++ b/chromium/third_party/blink/renderer/core/events/composition_event.h
@@ -45,7 +45,7 @@ class CompositionEvent final : public UIEvent {
}
static CompositionEvent* Create(const AtomicString& type,
- const CompositionEventInit& initializer) {
+ const CompositionEventInit* initializer) {
return new CompositionEvent(type, initializer);
}
@@ -68,7 +68,7 @@ class CompositionEvent final : public UIEvent {
private:
CompositionEvent();
CompositionEvent(const AtomicString& type, AbstractView*, const String&);
- CompositionEvent(const AtomicString& type, const CompositionEventInit&);
+ CompositionEvent(const AtomicString& type, const CompositionEventInit*);
String data_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/drag_event.cc b/chromium/third_party/blink/renderer/core/events/drag_event.cc
index 6d592f631d2..429daf97210 100644
--- a/chromium/third_party/blink/renderer/core/events/drag_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/drag_event.cc
@@ -14,11 +14,11 @@ namespace blink {
DragEvent::DragEvent() : data_transfer_(nullptr) {}
DragEvent::DragEvent(const AtomicString& type,
- const DragEventInit& initializer,
+ const DragEventInit* initializer,
TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type)
: MouseEvent(type, initializer, platform_time_stamp, synthetic_event_type),
- data_transfer_(initializer.getDataTransfer()) {}
+ data_transfer_(initializer->getDataTransfer()) {}
bool DragEvent::IsDragEvent() const {
return true;
diff --git a/chromium/third_party/blink/renderer/core/events/drag_event.h b/chromium/third_party/blink/renderer/core/events/drag_event.h
index c03a738f3a0..11a6c43854e 100644
--- a/chromium/third_party/blink/renderer/core/events/drag_event.h
+++ b/chromium/third_party/blink/renderer/core/events/drag_event.h
@@ -17,22 +17,28 @@ class CORE_EXPORT DragEvent final : public MouseEvent {
DEFINE_WRAPPERTYPEINFO();
public:
- static DragEvent* Create() { return new DragEvent; }
+ static DragEvent* Create() { return MakeGarbageCollected<DragEvent>(); }
static DragEvent* Create(const AtomicString& type,
- const DragEventInit& initializer,
+ const DragEventInit* initializer,
TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type) {
- return new DragEvent(type, initializer, platform_time_stamp,
- synthetic_event_type);
+ return MakeGarbageCollected<DragEvent>(
+ type, initializer, platform_time_stamp, synthetic_event_type);
}
static DragEvent* Create(const AtomicString& type,
- const DragEventInit& initializer) {
- return new DragEvent(type, initializer, CurrentTimeTicks(),
- kRealOrIndistinguishable);
+ const DragEventInit* initializer) {
+ return MakeGarbageCollected<DragEvent>(
+ type, initializer, CurrentTimeTicks(), kRealOrIndistinguishable);
}
+ DragEvent();
+ DragEvent(const AtomicString& type,
+ const DragEventInit*,
+ TimeTicks platform_time_stamp,
+ SyntheticEventType);
+
DataTransfer* getDataTransfer() const override {
return IsDragEvent() ? data_transfer_.Get() : nullptr;
}
@@ -45,12 +51,6 @@ class CORE_EXPORT DragEvent final : public MouseEvent {
void Trace(blink::Visitor*) override;
private:
- DragEvent();
- DragEvent(const AtomicString& type,
- const DragEventInit&,
- TimeTicks platform_time_stamp,
- SyntheticEventType);
-
Member<DataTransfer> data_transfer_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/error_event.cc b/chromium/third_party/blink/renderer/core/events/error_event.cc
index ba74dbeadfb..c5980a143d1 100644
--- a/chromium/third_party/blink/renderer/core/events/error_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/error_event.cc
@@ -33,10 +33,21 @@
#include <memory>
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "v8/include/v8.h"
namespace blink {
+ErrorEvent* ErrorEvent::CreateSanitizedError(ScriptState* script_state) {
+ // "6. If script's muted errors is true, then set message to "Script error.",
+ // urlString to the empty string, line and col to 0, and errorValue to null."
+ // https://html.spec.whatwg.org/multipage/webappapis.html#runtime-script-errors:muted-errors
+ DCHECK(script_state);
+ return MakeGarbageCollected<ErrorEvent>(
+ "Script error.", SourceLocation::Create(String(), 0, 0, nullptr),
+ ScriptValue::CreateNull(script_state), &script_state->World());
+}
+
ErrorEvent::ErrorEvent()
: sanitized_message_(),
location_(SourceLocation::Create(String(), 0, 0, nullptr)),
@@ -44,18 +55,19 @@ ErrorEvent::ErrorEvent()
ErrorEvent::ErrorEvent(ScriptState* script_state,
const AtomicString& type,
- const ErrorEventInit& initializer)
+ const ErrorEventInit* initializer)
: Event(type, initializer),
sanitized_message_(),
world_(&script_state->World()) {
- if (initializer.hasMessage())
- sanitized_message_ = initializer.message();
+ if (initializer->hasMessage())
+ sanitized_message_ = initializer->message();
location_ = SourceLocation::Create(
- initializer.hasFilename() ? initializer.filename() : String(),
- initializer.hasLineno() ? initializer.lineno() : 0,
- initializer.hasColno() ? initializer.colno() : 0, nullptr);
- if (initializer.hasError()) {
- error_.Set(initializer.error().GetIsolate(), initializer.error().V8Value());
+ initializer->hasFilename() ? initializer->filename() : String(),
+ initializer->hasLineno() ? initializer->lineno() : 0,
+ initializer->hasColno() ? initializer->colno() : 0, nullptr);
+ if (initializer->hasError()) {
+ error_.Set(initializer->error().GetIsolate(),
+ initializer->error().V8Value());
}
}
@@ -63,7 +75,7 @@ ErrorEvent::ErrorEvent(const String& message,
std::unique_ptr<SourceLocation> location,
ScriptValue error,
DOMWrapperWorld* world)
- : Event(EventTypeNames::error, Bubbles::kNo, Cancelable::kYes),
+ : Event(event_type_names::kError, Bubbles::kNo, Cancelable::kYes),
sanitized_message_(message),
location_(std::move(location)),
world_(world) {
@@ -79,7 +91,7 @@ void ErrorEvent::SetUnsanitizedMessage(const String& message) {
ErrorEvent::~ErrorEvent() = default;
const AtomicString& ErrorEvent::InterfaceName() const {
- return EventNames::ErrorEvent;
+ return event_interface_names::kErrorEvent;
}
bool ErrorEvent::IsErrorEvent() const {
diff --git a/chromium/third_party/blink/renderer/core/events/error_event.h b/chromium/third_party/blink/renderer/core/events/error_event.h
index c4eca9c68b3..8d1f966e777 100644
--- a/chromium/third_party/blink/renderer/core/events/error_event.h
+++ b/chromium/third_party/blink/renderer/core/events/error_event.h
@@ -46,30 +46,37 @@ class ErrorEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static ErrorEvent* Create() { return new ErrorEvent; }
+ static ErrorEvent* Create() { return MakeGarbageCollected<ErrorEvent>(); }
static ErrorEvent* Create(const String& message,
std::unique_ptr<SourceLocation> location,
DOMWrapperWorld* world) {
- return new ErrorEvent(message, std::move(location), ScriptValue(), world);
+ return MakeGarbageCollected<ErrorEvent>(message, std::move(location),
+ ScriptValue(), world);
}
static ErrorEvent* Create(const String& message,
std::unique_ptr<SourceLocation> location,
ScriptValue error,
DOMWrapperWorld* world) {
- return new ErrorEvent(message, std::move(location), error, world);
+ return MakeGarbageCollected<ErrorEvent>(message, std::move(location), error,
+ world);
}
static ErrorEvent* Create(ScriptState* script_state,
const AtomicString& type,
- const ErrorEventInit& initializer) {
- return new ErrorEvent(script_state, type, initializer);
- }
- static ErrorEvent* CreateSanitizedError(DOMWrapperWorld* world) {
- return new ErrorEvent("Script error.",
- SourceLocation::Create(String(), 0, 0, nullptr),
- ScriptValue(), world);
+ const ErrorEventInit* initializer) {
+ return MakeGarbageCollected<ErrorEvent>(script_state, type, initializer);
}
+
+ // Creates an error for a script whose errors are muted.
+ static ErrorEvent* CreateSanitizedError(ScriptState* script_state);
+
+ ErrorEvent();
+ ErrorEvent(const String& message,
+ std::unique_ptr<SourceLocation>,
+ ScriptValue error,
+ DOMWrapperWorld*);
+ ErrorEvent(ScriptState*, const AtomicString&, const ErrorEventInit*);
~ErrorEvent() override;
// As 'message' is exposed to JavaScript, never return unsanitizedMessage.
@@ -98,13 +105,6 @@ class ErrorEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- ErrorEvent();
- ErrorEvent(const String& message,
- std::unique_ptr<SourceLocation>,
- ScriptValue error,
- DOMWrapperWorld*);
- ErrorEvent(ScriptState*, const AtomicString&, const ErrorEventInit&);
-
String unsanitized_message_;
String sanitized_message_;
std::unique_ptr<SourceLocation> location_;
diff --git a/chromium/third_party/blink/renderer/core/events/event_target_names.json5 b/chromium/third_party/blink/renderer/core/events/event_target_names.json5
index 6aab6842f93..e9fdcfb2168 100644
--- a/chromium/third_party/blink/renderer/core/events/event_target_names.json5
+++ b/chromium/third_party/blink/renderer/core/events/event_target_names.json5
@@ -1,45 +1,48 @@
{
metadata: {
- namespace: "EventTarget",
+ namespace: "event_target_names",
export: "CORE_EXPORT",
},
+ # You don't need to specify ImplementedAs even though an interface name and
+ # its C++ class name don't match. You need to specify ImplementedAs only if
+ # you'd like to change recorded names in ActivityLogger.
data: [
- "core/accessibility/AccessibleNode",
- "core/animation/Animation",
- "core/clipboard/Clipboard",
- "core/css/FontFaceSet",
- "core/css/MediaQueryList",
- "core/dom/BroadcastChannel",
- "core/dom/MessagePort",
- "core/dom/Node",
- "core/dom/events/EventTargetImpl",
- "core/fetch/AbortSignal",
- "core/fileapi/FileReader",
- "core/html/ime/InputMethodContext",
- "core/html/track/AudioTrackList",
- "core/html/track/TextTrack",
- "core/html/track/TextTrackCue",
- "core/html/track/TextTrackList",
- "core/html/track/VideoTrackList",
- "core/loader/appcache/ApplicationCache",
- "core/mojo/test/MojoInterfaceInterceptor",
- "core/offscreencanvas/OffscreenCanvas",
- "core/page/EventSource",
- "core/timing/Performance",
+ "AccessibleNode",
+ "Animation",
+ "Clipboard",
+ "FontFaceSet",
+ "MediaQueryList",
+ "BroadcastChannel",
+ "MessagePort",
+ "Node",
+ "EventTargetImpl",
+ "AbortSignal",
+ "FileReader",
+ "InputMethodContext",
+ "AudioTrackList",
+ "TextTrack",
+ "TextTrackCue",
+ "TextTrackList",
+ "VideoTrackList",
+ "ApplicationCache",
+ "MojoInterfaceInterceptor",
+ "OffscreenCanvas",
+ "EventSource",
+ "Performance",
{
- name: "core/frame/VisualViewport",
+ name: "VisualViewport",
ImplementedAs: "DOMVisualViewport",
},
{
- name: "core/frame/Window",
+ name: "Window",
ImplementedAs: "DOMWindow",
},
- "core/workers/DedicatedWorkerGlobalScope",
- "core/workers/SharedWorker",
- "core/workers/SharedWorkerGlobalScope",
- "core/workers/Worker",
- "core/xml/XMLHttpRequest",
- "core/xml/XMLHttpRequestUpload",
+ "DedicatedWorkerGlobalScope",
+ "SharedWorker",
+ "SharedWorkerGlobalScope",
+ "Worker",
+ "XMLHttpRequest",
+ "XMLHttpRequestUpload",
],
}
diff --git a/chromium/third_party/blink/renderer/core/events/event_type_names.json5 b/chromium/third_party/blink/renderer/core/events/event_type_names.json5
index 4a7c65baabb..7ccc7fe8402 100644
--- a/chromium/third_party/blink/renderer/core/events/event_type_names.json5
+++ b/chromium/third_party/blink/renderer/core/events/event_type_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "EventType",
+ namespace: "event_type_names",
export: "CORE_EXPORT",
},
@@ -75,6 +75,7 @@
"connect",
"connecting",
"connectionavailable",
+ "connectionstatechange",
"contextlost",
"contextmenu",
"contextrestored",
diff --git a/chromium/third_party/blink/renderer/core/events/event_util.cc b/chromium/third_party/blink/renderer/core/events/event_util.cc
index f02f66c6639..962b36babfc 100644
--- a/chromium/third_party/blink/renderer/core/events/event_util.cc
+++ b/chromium/third_party/blink/renderer/core/events/event_util.cc
@@ -8,30 +8,30 @@
namespace blink {
-namespace EventUtil {
+namespace event_util {
bool IsPointerEventType(const AtomicString& event_type) {
- return event_type == EventTypeNames::gotpointercapture ||
- event_type == EventTypeNames::lostpointercapture ||
- event_type == EventTypeNames::pointercancel ||
- event_type == EventTypeNames::pointerdown ||
- event_type == EventTypeNames::pointerenter ||
- event_type == EventTypeNames::pointerleave ||
- event_type == EventTypeNames::pointermove ||
- event_type == EventTypeNames::pointerout ||
- event_type == EventTypeNames::pointerover ||
- event_type == EventTypeNames::pointerup;
+ return event_type == event_type_names::kGotpointercapture ||
+ event_type == event_type_names::kLostpointercapture ||
+ event_type == event_type_names::kPointercancel ||
+ event_type == event_type_names::kPointerdown ||
+ event_type == event_type_names::kPointerenter ||
+ event_type == event_type_names::kPointerleave ||
+ event_type == event_type_names::kPointermove ||
+ event_type == event_type_names::kPointerout ||
+ event_type == event_type_names::kPointerover ||
+ event_type == event_type_names::kPointerup;
}
bool IsDOMMutationEventType(const AtomicString& event_type) {
- return event_type == EventTypeNames::DOMCharacterDataModified ||
- event_type == EventTypeNames::DOMNodeInserted ||
- event_type == EventTypeNames::DOMNodeInsertedIntoDocument ||
- event_type == EventTypeNames::DOMNodeRemoved ||
- event_type == EventTypeNames::DOMNodeRemovedFromDocument ||
- event_type == EventTypeNames::DOMSubtreeModified;
+ return event_type == event_type_names::kDOMCharacterDataModified ||
+ event_type == event_type_names::kDOMNodeInserted ||
+ event_type == event_type_names::kDOMNodeInsertedIntoDocument ||
+ event_type == event_type_names::kDOMNodeRemoved ||
+ event_type == event_type_names::kDOMNodeRemovedFromDocument ||
+ event_type == event_type_names::kDOMSubtreeModified;
}
-} // namespace eventUtil
+} // namespace event_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/event_util.h b/chromium/third_party/blink/renderer/core/events/event_util.h
index 16eacf2a531..70b37e6522c 100644
--- a/chromium/third_party/blink/renderer/core/events/event_util.h
+++ b/chromium/third_party/blink/renderer/core/events/event_util.h
@@ -9,13 +9,13 @@
namespace blink {
-namespace EventUtil {
+namespace event_util {
bool IsPointerEventType(const AtomicString& event_type);
bool IsDOMMutationEventType(const AtomicString& event_type);
-} // namespace eventUtil
+} // namespace event_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/focus_event.cc b/chromium/third_party/blink/renderer/core/events/focus_event.cc
index 68cb3aea7e0..f34dfbcf03f 100644
--- a/chromium/third_party/blink/renderer/core/events/focus_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/focus_event.cc
@@ -28,11 +28,12 @@
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
#include "third_party/blink/renderer/core/dom/events/event_path.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
const AtomicString& FocusEvent::InterfaceName() const {
- return EventNames::FocusEvent;
+ return event_interface_names::kFocusEvent;
}
bool FocusEvent::IsFocusEvent() const {
@@ -58,10 +59,10 @@ FocusEvent::FocusEvent(const AtomicString& type,
related_target_(related_target) {}
FocusEvent::FocusEvent(const AtomicString& type,
- const FocusEventInit& initializer)
+ const FocusEventInit* initializer)
: UIEvent(type, initializer) {
- if (initializer.hasRelatedTarget())
- related_target_ = initializer.relatedTarget();
+ if (initializer->hasRelatedTarget())
+ related_target_ = initializer->relatedTarget();
}
void FocusEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/focus_event.h b/chromium/third_party/blink/renderer/core/events/focus_event.h
index 8c0a80576f0..aa7c5102438 100644
--- a/chromium/third_party/blink/renderer/core/events/focus_event.h
+++ b/chromium/third_party/blink/renderer/core/events/focus_event.h
@@ -36,7 +36,7 @@ class FocusEvent final : public UIEvent {
DEFINE_WRAPPERTYPEINFO();
public:
- static FocusEvent* Create() { return new FocusEvent; }
+ static FocusEvent* Create() { return MakeGarbageCollected<FocusEvent>(); }
static FocusEvent* Create(const AtomicString& type,
Bubbles bubbles,
@@ -44,15 +44,24 @@ class FocusEvent final : public UIEvent {
int detail,
EventTarget* related_target,
InputDeviceCapabilities* source_capabilities) {
- return new FocusEvent(type, bubbles, view, detail, related_target,
- source_capabilities);
+ return MakeGarbageCollected<FocusEvent>(
+ type, bubbles, view, detail, related_target, source_capabilities);
}
static FocusEvent* Create(const AtomicString& type,
- const FocusEventInit& initializer) {
- return new FocusEvent(type, initializer);
+ const FocusEventInit* initializer) {
+ return MakeGarbageCollected<FocusEvent>(type, initializer);
}
+ FocusEvent();
+ FocusEvent(const AtomicString& type,
+ Bubbles,
+ AbstractView*,
+ int,
+ EventTarget*,
+ InputDeviceCapabilities*);
+ FocusEvent(const AtomicString& type, const FocusEventInit*);
+
EventTarget* relatedTarget() const { return related_target_.Get(); }
void SetRelatedTarget(EventTarget* related_target) {
related_target_ = related_target;
@@ -66,15 +75,6 @@ class FocusEvent final : public UIEvent {
void Trace(blink::Visitor*) override;
private:
- FocusEvent();
- FocusEvent(const AtomicString& type,
- Bubbles,
- AbstractView*,
- int,
- EventTarget*,
- InputDeviceCapabilities*);
- FocusEvent(const AtomicString& type, const FocusEventInit&);
-
Member<EventTarget> related_target_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/gesture_event.cc b/chromium/third_party/blink/renderer/core/events/gesture_event.cc
index e23f8e8f0a1..7ee15a9418d 100644
--- a/chromium/third_party/blink/renderer/core/events/gesture_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/gesture_event.cc
@@ -36,31 +36,31 @@ GestureEvent* GestureEvent::Create(AbstractView* view,
switch (event.GetType()) {
case WebInputEvent::kGestureScrollBegin:
- event_type = EventTypeNames::gesturescrollstart;
+ event_type = event_type_names::kGesturescrollstart;
break;
case WebInputEvent::kGestureScrollEnd:
- event_type = EventTypeNames::gesturescrollend;
+ event_type = event_type_names::kGesturescrollend;
break;
case WebInputEvent::kGestureScrollUpdate:
- event_type = EventTypeNames::gesturescrollupdate;
+ event_type = event_type_names::kGesturescrollupdate;
break;
case WebInputEvent::kGestureTap:
- event_type = EventTypeNames::gesturetap;
+ event_type = event_type_names::kGesturetap;
break;
case WebInputEvent::kGestureTapUnconfirmed:
- event_type = EventTypeNames::gesturetapunconfirmed;
+ event_type = event_type_names::kGesturetapunconfirmed;
break;
case WebInputEvent::kGestureTapDown:
- event_type = EventTypeNames::gesturetapdown;
+ event_type = event_type_names::kGesturetapdown;
break;
case WebInputEvent::kGestureShowPress:
- event_type = EventTypeNames::gestureshowpress;
+ event_type = event_type_names::kGestureshowpress;
break;
case WebInputEvent::kGestureLongPress:
- event_type = EventTypeNames::gesturelongpress;
+ event_type = event_type_names::kGesturelongpress;
break;
case WebInputEvent::kGestureFlingStart:
- event_type = EventTypeNames::gestureflingstart;
+ event_type = event_type_names::kGestureflingstart;
break;
case WebInputEvent::kGestureTwoFingerTap:
case WebInputEvent::kGesturePinchBegin:
@@ -70,7 +70,7 @@ GestureEvent* GestureEvent::Create(AbstractView* view,
default:
return nullptr;
}
- return new GestureEvent(event_type, view, event);
+ return MakeGarbageCollected<GestureEvent>(event_type, view, event);
}
GestureEvent::GestureEvent(const AtomicString& event_type,
diff --git a/chromium/third_party/blink/renderer/core/events/gesture_event.h b/chromium/third_party/blink/renderer/core/events/gesture_event.h
index aaffffd7168..0cd4fe36786 100644
--- a/chromium/third_party/blink/renderer/core/events/gesture_event.h
+++ b/chromium/third_party/blink/renderer/core/events/gesture_event.h
@@ -36,6 +36,8 @@ namespace blink {
class CORE_EXPORT GestureEvent final : public UIEventWithKeyState {
public:
static GestureEvent* Create(AbstractView*, const WebGestureEvent&);
+
+ GestureEvent(const AtomicString&, AbstractView*, const WebGestureEvent&);
~GestureEvent() override = default;
bool IsGestureEvent() const override;
@@ -47,8 +49,6 @@ class CORE_EXPORT GestureEvent final : public UIEventWithKeyState {
void Trace(blink::Visitor*) override;
private:
- GestureEvent(const AtomicString&, AbstractView*, const WebGestureEvent&);
-
WebGestureEvent native_event_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/hash_change_event.h b/chromium/third_party/blink/renderer/core/events/hash_change_event.h
index efddf9f6d57..e6bc7d7cce9 100644
--- a/chromium/third_party/blink/renderer/core/events/hash_change_event.h
+++ b/chromium/third_party/blink/renderer/core/events/hash_change_event.h
@@ -22,6 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_HASH_CHANGE_EVENT_H_
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/hash_change_event_init.h"
namespace blink {
@@ -30,43 +31,43 @@ class HashChangeEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static HashChangeEvent* Create() { return new HashChangeEvent; }
+ static HashChangeEvent* Create() {
+ return MakeGarbageCollected<HashChangeEvent>();
+ }
static HashChangeEvent* Create(const String& old_url, const String& new_url) {
- return new HashChangeEvent(old_url, new_url);
+ return MakeGarbageCollected<HashChangeEvent>(old_url, new_url);
}
static HashChangeEvent* Create(const AtomicString& type,
- const HashChangeEventInit& initializer) {
- return new HashChangeEvent(type, initializer);
+ const HashChangeEventInit* initializer) {
+ return MakeGarbageCollected<HashChangeEvent>(type, initializer);
+ }
+
+ HashChangeEvent() = default;
+ HashChangeEvent(const String& old_url, const String& new_url)
+ : Event(event_type_names::kHashchange, Bubbles::kNo, Cancelable::kNo),
+ old_url_(old_url),
+ new_url_(new_url) {}
+ HashChangeEvent(const AtomicString& type,
+ const HashChangeEventInit* initializer)
+ : Event(type, initializer) {
+ if (initializer->hasOldURL())
+ old_url_ = initializer->oldURL();
+ if (initializer->hasNewURL())
+ new_url_ = initializer->newURL();
}
const String& oldURL() const { return old_url_; }
const String& newURL() const { return new_url_; }
const AtomicString& InterfaceName() const override {
- return EventNames::HashChangeEvent;
+ return event_interface_names::kHashChangeEvent;
}
void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
private:
- HashChangeEvent() = default;
-
- HashChangeEvent(const String& old_url, const String& new_url)
- : Event(EventTypeNames::hashchange, Bubbles::kNo, Cancelable::kNo),
- old_url_(old_url),
- new_url_(new_url) {}
-
- HashChangeEvent(const AtomicString& type,
- const HashChangeEventInit& initializer)
- : Event(type, initializer) {
- if (initializer.hasOldURL())
- old_url_ = initializer.oldURL();
- if (initializer.hasNewURL())
- new_url_ = initializer.newURL();
- }
-
String old_url_;
String new_url_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/input_event.cc b/chromium/third_party/blink/renderer/core/events/input_event.cc
index 77342f8f213..26f60649ea8 100644
--- a/chromium/third_party/blink/renderer/core/events/input_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/input_event.cc
@@ -84,22 +84,22 @@ InputEvent::InputType ConvertStringToInputType(const String& string_name) {
} // anonymous namespace
InputEvent::InputEvent(const AtomicString& type,
- const InputEventInit& initializer)
+ const InputEventInit* initializer)
: UIEvent(type, initializer) {
// TODO(ojan): We should find a way to prevent conversion like
// String->enum->String just in order to use initializer.
// See InputEvent::createBeforeInput() for the first conversion.
- if (initializer.hasInputType())
- input_type_ = ConvertStringToInputType(initializer.inputType());
- if (initializer.hasData())
- data_ = initializer.data();
- if (initializer.hasDataTransfer())
- data_transfer_ = initializer.dataTransfer();
- if (initializer.hasIsComposing())
- is_composing_ = initializer.isComposing();
- if (!initializer.hasTargetRanges())
+ if (initializer->hasInputType())
+ input_type_ = ConvertStringToInputType(initializer->inputType());
+ if (initializer->hasData())
+ data_ = initializer->data();
+ if (initializer->hasDataTransfer())
+ data_transfer_ = initializer->dataTransfer();
+ if (initializer->hasIsComposing())
+ is_composing_ = initializer->isComposing();
+ if (!initializer->hasTargetRanges())
return;
- for (const auto& range : initializer.targetRanges())
+ for (const auto& range : initializer->targetRanges())
ranges_.push_back(range->toRange());
}
@@ -109,20 +109,20 @@ InputEvent* InputEvent::CreateBeforeInput(InputType input_type,
EventCancelable cancelable,
EventIsComposing is_composing,
const StaticRangeVector* ranges) {
- InputEventInit input_event_init;
+ InputEventInit* input_event_init = InputEventInit::Create();
- input_event_init.setBubbles(true);
- input_event_init.setCancelable(cancelable == kIsCancelable);
+ input_event_init->setBubbles(true);
+ input_event_init->setCancelable(cancelable == kIsCancelable);
// TODO(ojan): We should find a way to prevent conversion like
// String->enum->String just in order to use initializer.
// See InputEvent::InputEvent() for the second conversion.
- input_event_init.setInputType(ConvertInputTypeToString(input_type));
- input_event_init.setData(data);
- input_event_init.setIsComposing(is_composing == kIsComposing);
+ input_event_init->setInputType(ConvertInputTypeToString(input_type));
+ input_event_init->setData(data);
+ input_event_init->setIsComposing(is_composing == kIsComposing);
if (ranges)
- input_event_init.setTargetRanges(*ranges);
- input_event_init.setComposed(true);
- return InputEvent::Create(EventTypeNames::beforeinput, input_event_init);
+ input_event_init->setTargetRanges(*ranges);
+ input_event_init->setComposed(true);
+ return InputEvent::Create(event_type_names::kBeforeinput, input_event_init);
}
/* static */
@@ -131,17 +131,17 @@ InputEvent* InputEvent::CreateBeforeInput(InputType input_type,
EventCancelable cancelable,
EventIsComposing is_composing,
const StaticRangeVector* ranges) {
- InputEventInit input_event_init;
+ InputEventInit* input_event_init = InputEventInit::Create();
- input_event_init.setBubbles(true);
- input_event_init.setCancelable(cancelable == kIsCancelable);
- input_event_init.setInputType(ConvertInputTypeToString(input_type));
- input_event_init.setDataTransfer(data_transfer);
- input_event_init.setIsComposing(is_composing == kIsComposing);
+ input_event_init->setBubbles(true);
+ input_event_init->setCancelable(cancelable == kIsCancelable);
+ input_event_init->setInputType(ConvertInputTypeToString(input_type));
+ input_event_init->setDataTransfer(data_transfer);
+ input_event_init->setIsComposing(is_composing == kIsComposing);
if (ranges)
- input_event_init.setTargetRanges(*ranges);
- input_event_init.setComposed(true);
- return InputEvent::Create(EventTypeNames::beforeinput, input_event_init);
+ input_event_init->setTargetRanges(*ranges);
+ input_event_init->setComposed(true);
+ return InputEvent::Create(event_type_names::kBeforeinput, input_event_init);
}
/* static */
@@ -149,20 +149,20 @@ InputEvent* InputEvent::CreateInput(InputType input_type,
const String& data,
EventIsComposing is_composing,
const StaticRangeVector* ranges) {
- InputEventInit input_event_init;
+ InputEventInit* input_event_init = InputEventInit::Create();
- input_event_init.setBubbles(true);
- input_event_init.setCancelable(false);
+ input_event_init->setBubbles(true);
+ input_event_init->setCancelable(false);
// TODO(ojan): We should find a way to prevent conversion like
// String->enum->String just in order to use initializer.
// See InputEvent::InputEvent() for the second conversion.
- input_event_init.setInputType(ConvertInputTypeToString(input_type));
- input_event_init.setData(data);
- input_event_init.setIsComposing(is_composing == kIsComposing);
+ input_event_init->setInputType(ConvertInputTypeToString(input_type));
+ input_event_init->setData(data);
+ input_event_init->setIsComposing(is_composing == kIsComposing);
if (ranges)
- input_event_init.setTargetRanges(*ranges);
- input_event_init.setComposed(true);
- return InputEvent::Create(EventTypeNames::input, input_event_init);
+ input_event_init->setTargetRanges(*ranges);
+ input_event_init->setComposed(true);
+ return InputEvent::Create(event_type_names::kInput, input_event_init);
}
String InputEvent::inputType() const {
diff --git a/chromium/third_party/blink/renderer/core/events/input_event.h b/chromium/third_party/blink/renderer/core/events/input_event.h
index e2f74bdb22b..1451d951406 100644
--- a/chromium/third_party/blink/renderer/core/events/input_event.h
+++ b/chromium/third_party/blink/renderer/core/events/input_event.h
@@ -18,8 +18,8 @@ class InputEvent final : public UIEvent {
public:
static InputEvent* Create(const AtomicString& type,
- const InputEventInit& initializer) {
- return new InputEvent(type, initializer);
+ const InputEventInit* initializer) {
+ return MakeGarbageCollected<InputEvent>(type, initializer);
}
// https://w3c.github.io/input-events/#h-interface-inputevent-attributes
@@ -97,6 +97,8 @@ class InputEvent final : public UIEvent {
EventIsComposing,
const StaticRangeVector*);
+ InputEvent(const AtomicString&, const InputEventInit*);
+
String inputType() const;
const String& data() const { return data_; }
DataTransfer* dataTransfer() const { return data_transfer_.Get(); }
@@ -112,8 +114,6 @@ class InputEvent final : public UIEvent {
void Trace(blink::Visitor*) override;
private:
- InputEvent(const AtomicString&, const InputEventInit&);
-
InputType input_type_;
String data_;
Member<DataTransfer> data_transfer_;
diff --git a/chromium/third_party/blink/renderer/core/events/keyboard_event.cc b/chromium/third_party/blink/renderer/core/events/keyboard_event.cc
index 16e99ca01a6..70610af511d 100644
--- a/chromium/third_party/blink/renderer/core/events/keyboard_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/keyboard_event.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/renderer/core/editing/ime/input_method_controller.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
@@ -40,11 +41,11 @@ namespace {
const AtomicString& EventTypeForKeyboardEventType(WebInputEvent::Type type) {
switch (type) {
case WebInputEvent::kKeyUp:
- return EventTypeNames::keyup;
+ return event_type_names::kKeyup;
case WebInputEvent::kRawKeyDown:
- return EventTypeNames::keydown;
+ return event_type_names::kKeydown;
case WebInputEvent::kChar:
- return EventTypeNames::keypress;
+ return event_type_names::kKeypress;
case WebInputEvent::kKeyDown:
// The caller should disambiguate the combined event into RawKeyDown or
// Char events.
@@ -53,7 +54,7 @@ const AtomicString& EventTypeForKeyboardEventType(WebInputEvent::Type type) {
break;
}
NOTREACHED();
- return EventTypeNames::keydown;
+ return event_type_names::kKeydown;
}
KeyboardEvent::KeyLocationCode GetKeyLocationCode(const WebInputEvent& key) {
@@ -79,12 +80,13 @@ bool HasCurrentComposition(LocalDOMWindow* dom_window) {
KeyboardEvent* KeyboardEvent::Create(ScriptState* script_state,
const AtomicString& type,
- const KeyboardEventInit& initializer) {
- if (script_state->World().IsIsolatedWorld())
+ const KeyboardEventInit* initializer) {
+ if (script_state->World().IsIsolatedWorld()) {
UIEventWithKeyState::DidCreateEventInIsolatedWorld(
- initializer.ctrlKey(), initializer.altKey(), initializer.shiftKey(),
- initializer.metaKey());
- return new KeyboardEvent(type, initializer);
+ initializer->ctrlKey(), initializer->altKey(), initializer->shiftKey(),
+ initializer->metaKey());
+ }
+ return MakeGarbageCollected<KeyboardEvent>(type, initializer);
}
KeyboardEvent::KeyboardEvent() : location_(kDomKeyLocationStandard) {}
@@ -113,10 +115,11 @@ KeyboardEvent::KeyboardEvent(const WebKeyboardEvent& key,
// Firefox: 0 for keydown/keyup events, character code for keypress
// We match Firefox
- if (type() == EventTypeNames::keypress)
+ if (type() == event_type_names::kKeypress)
char_code_ = key.text[0];
- if (type() == EventTypeNames::keydown || type() == EventTypeNames::keyup)
+ if (type() == event_type_names::kKeydown ||
+ type() == event_type_names::kKeyup)
key_code_ = key.windows_key_code;
else
key_code_ = char_code_;
@@ -130,17 +133,17 @@ KeyboardEvent::KeyboardEvent(const WebKeyboardEvent& key,
}
KeyboardEvent::KeyboardEvent(const AtomicString& event_type,
- const KeyboardEventInit& initializer)
+ const KeyboardEventInit* initializer)
: UIEventWithKeyState(event_type, initializer),
- code_(initializer.code()),
- key_(initializer.key()),
- location_(initializer.location()),
- is_composing_(initializer.isComposing()),
- char_code_(initializer.charCode()),
- key_code_(initializer.keyCode()) {
- if (initializer.repeat())
+ code_(initializer->code()),
+ key_(initializer->key()),
+ location_(initializer->location()),
+ is_composing_(initializer->isComposing()),
+ char_code_(initializer->charCode()),
+ key_code_(initializer->keyCode()) {
+ if (initializer->repeat())
modifiers_ |= WebInputEvent::kIsAutoRepeat;
- InitLocationModifiers(initializer.location());
+ InitLocationModifiers(initializer->location());
}
KeyboardEvent::~KeyboardEvent() = default;
@@ -179,7 +182,7 @@ int KeyboardEvent::charCode() const {
}
const AtomicString& KeyboardEvent::InterfaceName() const {
- return EventNames::KeyboardEvent;
+ return event_interface_names::kKeyboardEvent;
}
bool KeyboardEvent::IsKeyboardEvent() const {
diff --git a/chromium/third_party/blink/renderer/core/events/keyboard_event.h b/chromium/third_party/blink/renderer/core/events/keyboard_event.h
index 947af99b257..7459d6b88ec 100644
--- a/chromium/third_party/blink/renderer/core/events/keyboard_event.h
+++ b/chromium/third_party/blink/renderer/core/events/keyboard_event.h
@@ -44,18 +44,22 @@ class CORE_EXPORT KeyboardEvent final : public UIEventWithKeyState {
kDomKeyLocationNumpad = 0x03
};
- static KeyboardEvent* Create() { return new KeyboardEvent; }
+ static KeyboardEvent* Create() {
+ return MakeGarbageCollected<KeyboardEvent>();
+ }
static KeyboardEvent* Create(const WebKeyboardEvent& web_event,
LocalDOMWindow* dom_window) {
- return new KeyboardEvent(web_event, dom_window);
+ return MakeGarbageCollected<KeyboardEvent>(web_event, dom_window);
}
static KeyboardEvent* Create(ScriptState*,
const AtomicString& type,
- const KeyboardEventInit&);
+ const KeyboardEventInit*);
- KeyboardEvent(const AtomicString&, const KeyboardEventInit&);
+ KeyboardEvent();
+ KeyboardEvent(const WebKeyboardEvent&, LocalDOMWindow*);
+ KeyboardEvent(const AtomicString&, const KeyboardEventInit*);
~KeyboardEvent() override;
void initKeyboardEvent(ScriptState*,
@@ -90,9 +94,6 @@ class CORE_EXPORT KeyboardEvent final : public UIEventWithKeyState {
void Trace(blink::Visitor*) override;
private:
- KeyboardEvent();
- KeyboardEvent(const WebKeyboardEvent&, LocalDOMWindow*);
-
void InitLocationModifiers(unsigned location);
std::unique_ptr<WebKeyboardEvent> key_event_;
diff --git a/chromium/third_party/blink/renderer/core/events/message_event.cc b/chromium/third_party/blink/renderer/core/events/message_event.cc
index 1d32bb8d3df..d8c5d5a2171 100644
--- a/chromium/third_party/blink/renderer/core/events/message_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/message_event.cc
@@ -30,6 +30,7 @@
#include <memory>
#include "third_party/blink/renderer/bindings/core/v8/v8_array_buffer.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/frame/user_activation.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_private_property.h"
@@ -65,22 +66,22 @@ MessageEvent::V8GCAwareString& MessageEvent::V8GCAwareString::operator=(
MessageEvent::MessageEvent() : data_type_(kDataTypeScriptValue) {}
MessageEvent::MessageEvent(const AtomicString& type,
- const MessageEventInit& initializer)
+ const MessageEventInit* initializer)
: Event(type, initializer),
data_type_(kDataTypeScriptValue),
source_(nullptr) {
- if (initializer.hasData())
- data_as_script_value_ = initializer.data();
- if (initializer.hasOrigin())
- origin_ = initializer.origin();
- if (initializer.hasLastEventId())
- last_event_id_ = initializer.lastEventId();
- if (initializer.hasSource() && IsValidSource(initializer.source()))
- source_ = initializer.source();
- if (initializer.hasPorts())
- ports_ = new MessagePortArray(initializer.ports());
- if (initializer.hasUserActivation())
- user_activation_ = initializer.userActivation();
+ if (initializer->hasData())
+ data_as_script_value_ = initializer->data();
+ if (initializer->hasOrigin())
+ origin_ = initializer->origin();
+ if (initializer->hasLastEventId())
+ last_event_id_ = initializer->lastEventId();
+ if (initializer->hasSource() && IsValidSource(initializer->source()))
+ source_ = initializer->source();
+ if (initializer->hasPorts())
+ ports_ = MakeGarbageCollected<MessagePortArray>(initializer->ports());
+ if (initializer->hasUserActivation())
+ user_activation_ = initializer->userActivation();
DCHECK(IsValidSource(source_.Get()));
}
@@ -88,7 +89,7 @@ MessageEvent::MessageEvent(const String& origin,
const String& last_event_id,
EventTarget* source,
MessagePortArray* ports)
- : Event(EventTypeNames::message, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeScriptValue),
origin_(origin),
last_event_id_(last_event_id),
@@ -103,7 +104,7 @@ MessageEvent::MessageEvent(scoped_refptr<SerializedScriptValue> data,
EventTarget* source,
MessagePortArray* ports,
UserActivation* user_activation)
- : Event(EventTypeNames::message, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeSerializedScriptValue),
data_as_serialized_script_value_(
SerializedScriptValue::Unpack(std::move(data))),
@@ -121,7 +122,7 @@ MessageEvent::MessageEvent(scoped_refptr<SerializedScriptValue> data,
EventTarget* source,
Vector<MessagePortChannel> channels,
UserActivation* user_activation)
- : Event(EventTypeNames::message, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeSerializedScriptValue),
data_as_serialized_script_value_(
SerializedScriptValue::Unpack(std::move(data))),
@@ -134,7 +135,7 @@ MessageEvent::MessageEvent(scoped_refptr<SerializedScriptValue> data,
}
MessageEvent::MessageEvent(const String& origin, EventTarget* source)
- : Event(EventTypeNames::messageerror, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessageerror, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeNull),
origin_(origin),
source_(source) {
@@ -142,19 +143,19 @@ MessageEvent::MessageEvent(const String& origin, EventTarget* source)
}
MessageEvent::MessageEvent(const String& data, const String& origin)
- : Event(EventTypeNames::message, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeString),
data_as_string_(data),
origin_(origin) {}
MessageEvent::MessageEvent(Blob* data, const String& origin)
- : Event(EventTypeNames::message, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeBlob),
data_as_blob_(data),
origin_(origin) {}
MessageEvent::MessageEvent(DOMArrayBuffer* data, const String& origin)
- : Event(EventTypeNames::message, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeArrayBuffer),
data_as_array_buffer_(data),
origin_(origin) {}
@@ -162,14 +163,14 @@ MessageEvent::MessageEvent(DOMArrayBuffer* data, const String& origin)
MessageEvent::~MessageEvent() = default;
MessageEvent* MessageEvent::Create(const AtomicString& type,
- const MessageEventInit& initializer,
+ const MessageEventInit* initializer,
ExceptionState& exception_state) {
- if (initializer.source() && !IsValidSource(initializer.source())) {
+ if (initializer->source() && !IsValidSource(initializer->source())) {
exception_state.ThrowTypeError(
"The optional 'source' property is neither a Window nor MessagePort.");
return nullptr;
}
- return new MessageEvent(type, initializer);
+ return MakeGarbageCollected<MessageEvent>(type, initializer);
}
void MessageEvent::initMessageEvent(const AtomicString& type,
@@ -242,7 +243,7 @@ void MessageEvent::initMessageEvent(const AtomicString& type,
}
const AtomicString& MessageEvent::InterfaceName() const {
- return EventNames::MessageEvent;
+ return event_interface_names::kMessageEvent;
}
MessagePortArray MessageEvent::ports() {
diff --git a/chromium/third_party/blink/renderer/core/events/message_event.h b/chromium/third_party/blink/renderer/core/events/message_event.h
index 12fbe776d60..40db5824a30 100644
--- a/chromium/third_party/blink/renderer/core/events/message_event.h
+++ b/chromium/third_party/blink/renderer/core/events/message_event.h
@@ -49,26 +49,27 @@ class CORE_EXPORT MessageEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static MessageEvent* Create() { return new MessageEvent; }
+ static MessageEvent* Create() { return MakeGarbageCollected<MessageEvent>(); }
static MessageEvent* Create(MessagePortArray* ports,
const String& origin = String(),
const String& last_event_id = String(),
EventTarget* source = nullptr) {
- return new MessageEvent(origin, last_event_id, source, ports);
+ return MakeGarbageCollected<MessageEvent>(origin, last_event_id, source,
+ ports);
}
static MessageEvent* Create(MessagePortArray* ports,
scoped_refptr<SerializedScriptValue> data,
const String& origin = String(),
const String& last_event_id = String(),
EventTarget* source = nullptr) {
- return new MessageEvent(std::move(data), origin, last_event_id, source,
- ports, nullptr);
+ return MakeGarbageCollected<MessageEvent>(
+ std::move(data), origin, last_event_id, source, ports, nullptr);
}
static MessageEvent* Create(MessagePortArray* ports,
scoped_refptr<SerializedScriptValue> data,
UserActivation* user_activation) {
- return new MessageEvent(std::move(data), String(), String(), nullptr, ports,
- user_activation);
+ return MakeGarbageCollected<MessageEvent>(
+ std::move(data), String(), String(), nullptr, ports, user_activation);
}
static MessageEvent* Create(Vector<MessagePortChannel> channels,
scoped_refptr<SerializedScriptValue> data,
@@ -76,27 +77,52 @@ class CORE_EXPORT MessageEvent final : public Event {
const String& last_event_id = String(),
EventTarget* source = nullptr,
UserActivation* user_activation = nullptr) {
- return new MessageEvent(std::move(data), origin, last_event_id, source,
- std::move(channels), user_activation);
+ return MakeGarbageCollected<MessageEvent>(
+ std::move(data), origin, last_event_id, source, std::move(channels),
+ user_activation);
}
static MessageEvent* CreateError(const String& origin = String(),
EventTarget* source = nullptr) {
- return new MessageEvent(origin, source);
+ return MakeGarbageCollected<MessageEvent>(origin, source);
}
static MessageEvent* Create(const String& data,
const String& origin = String()) {
- return new MessageEvent(data, origin);
+ return MakeGarbageCollected<MessageEvent>(data, origin);
}
static MessageEvent* Create(Blob* data, const String& origin = String()) {
- return new MessageEvent(data, origin);
+ return MakeGarbageCollected<MessageEvent>(data, origin);
}
static MessageEvent* Create(DOMArrayBuffer* data,
const String& origin = String()) {
- return new MessageEvent(data, origin);
+ return MakeGarbageCollected<MessageEvent>(data, origin);
}
static MessageEvent* Create(const AtomicString& type,
- const MessageEventInit& initializer,
+ const MessageEventInit* initializer,
ExceptionState&);
+
+ MessageEvent();
+ MessageEvent(const AtomicString&, const MessageEventInit*);
+ MessageEvent(const String& origin,
+ const String& last_event_id,
+ EventTarget* source,
+ MessagePortArray*);
+ MessageEvent(scoped_refptr<SerializedScriptValue> data,
+ const String& origin,
+ const String& last_event_id,
+ EventTarget* source,
+ MessagePortArray*,
+ UserActivation* user_activation);
+ MessageEvent(scoped_refptr<SerializedScriptValue> data,
+ const String& origin,
+ const String& last_event_id,
+ EventTarget* source,
+ Vector<MessagePortChannel>,
+ UserActivation* user_activation);
+ // Creates a "messageerror" event.
+ MessageEvent(const String& origin, EventTarget* source);
+ MessageEvent(const String& data, const String& origin);
+ MessageEvent(Blob* data, const String& origin);
+ MessageEvent(DOMArrayBuffer* data, const String& origin);
~MessageEvent() override;
void initMessageEvent(const AtomicString& type,
@@ -197,32 +223,6 @@ class CORE_EXPORT MessageEvent final : public Event {
String string_;
};
- MessageEvent();
- MessageEvent(const AtomicString&, const MessageEventInit&);
- MessageEvent(const String& origin,
- const String& last_event_id,
- EventTarget* source,
- MessagePortArray*);
- MessageEvent(scoped_refptr<SerializedScriptValue> data,
- const String& origin,
- const String& last_event_id,
- EventTarget* source,
- MessagePortArray*,
- UserActivation* user_activation);
- MessageEvent(scoped_refptr<SerializedScriptValue> data,
- const String& origin,
- const String& last_event_id,
- EventTarget* source,
- Vector<MessagePortChannel>,
- UserActivation* user_activation);
-
- // Creates a "messageerror" event.
- MessageEvent(const String& origin, EventTarget* source);
-
- MessageEvent(const String& data, const String& origin);
- MessageEvent(Blob* data, const String& origin);
- MessageEvent(DOMArrayBuffer* data, const String& origin);
-
DataType data_type_;
ScriptValue data_as_script_value_;
Member<UnpackedSerializedScriptValue> data_as_serialized_script_value_;
diff --git a/chromium/third_party/blink/renderer/core/events/mouse_event.cc b/chromium/third_party/blink/renderer/core/events/mouse_event.cc
index 9317e211320..9238a39d59b 100644
--- a/chromium/third_party/blink/renderer/core/events/mouse_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/mouse_event.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
#include "third_party/blink/renderer/core/dom/events/event_path.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
@@ -108,21 +109,23 @@ unsigned ButtonsToWebInputEventModifiers(unsigned short buttons) {
MouseEvent* MouseEvent::Create(ScriptState* script_state,
const AtomicString& type,
- const MouseEventInit& initializer) {
- if (script_state && script_state->World().IsIsolatedWorld())
+ const MouseEventInit* initializer) {
+ if (script_state && script_state->World().IsIsolatedWorld()) {
UIEventWithKeyState::DidCreateEventInIsolatedWorld(
- initializer.ctrlKey(), initializer.altKey(), initializer.shiftKey(),
- initializer.metaKey());
- return new MouseEvent(type, initializer);
+ initializer->ctrlKey(), initializer->altKey(), initializer->shiftKey(),
+ initializer->metaKey());
+ }
+ return MakeGarbageCollected<MouseEvent>(type, initializer);
}
MouseEvent* MouseEvent::Create(const AtomicString& event_type,
- const MouseEventInit& initializer,
+ const MouseEventInit* initializer,
TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type,
WebMenuSourceType menu_source_type) {
- return new MouseEvent(event_type, initializer, platform_time_stamp,
- synthetic_event_type, menu_source_type);
+ return MakeGarbageCollected<MouseEvent>(
+ event_type, initializer, platform_time_stamp, synthetic_event_type,
+ menu_source_type);
}
MouseEvent* MouseEvent::Create(const AtomicString& event_type,
@@ -136,29 +139,29 @@ MouseEvent* MouseEvent::Create(const AtomicString& event_type,
}
SyntheticEventType synthetic_type = kPositionless;
- MouseEventInit initializer;
+ MouseEventInit* initializer = MouseEventInit::Create();
if (underlying_event && underlying_event->IsMouseEvent()) {
synthetic_type = kRealOrIndistinguishable;
MouseEvent* mouse_event = ToMouseEvent(underlying_event);
- initializer.setScreenX(mouse_event->screenX());
- initializer.setScreenY(mouse_event->screenY());
- initializer.setSourceCapabilities(
+ initializer->setScreenX(mouse_event->screenX());
+ initializer->setScreenY(mouse_event->screenY());
+ initializer->setSourceCapabilities(
view ? view->GetInputDeviceCapabilities()->FiresTouchEvents(false)
: nullptr);
}
- initializer.setBubbles(true);
- initializer.setCancelable(true);
- initializer.setView(view);
- initializer.setComposed(true);
+ initializer->setBubbles(true);
+ initializer->setCancelable(true);
+ initializer->setView(view);
+ initializer->setComposed(true);
UIEventWithKeyState::SetFromWebInputEventModifiers(initializer, modifiers);
- initializer.setButtons(
+ initializer->setButtons(
MouseEvent::WebInputEventModifiersToButtons(modifiers));
TimeTicks timestamp = underlying_event ? underlying_event->PlatformTimeStamp()
: CurrentTimeTicks();
- MouseEvent* created_event =
- new MouseEvent(event_type, initializer, timestamp, synthetic_type);
+ MouseEvent* created_event = MakeGarbageCollected<MouseEvent>(
+ event_type, initializer, timestamp, synthetic_type);
created_event->SetTrusted(creation_scope ==
SimulatedClickCreationScope::kFromUserAgent);
@@ -180,25 +183,25 @@ MouseEvent::MouseEvent()
synthetic_event_type_(kRealOrIndistinguishable) {}
MouseEvent::MouseEvent(const AtomicString& event_type,
- const MouseEventInit& initializer,
+ const MouseEventInit* initializer,
TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type,
WebMenuSourceType menu_source_type)
: UIEventWithKeyState(event_type, initializer, platform_time_stamp),
screen_location_(
- DoublePoint(initializer.screenX(), initializer.screenY())),
+ DoublePoint(initializer->screenX(), initializer->screenY())),
movement_delta_(
- IntPoint(initializer.movementX(), initializer.movementY())),
+ DoublePoint(initializer->movementX(), initializer->movementY())),
position_type_(synthetic_event_type == kPositionless
? PositionType::kPositionless
: PositionType::kPosition),
- button_(initializer.button()),
- buttons_(initializer.buttons()),
- related_target_(initializer.relatedTarget()),
+ button_(initializer->button()),
+ buttons_(initializer->buttons()),
+ related_target_(initializer->relatedTarget()),
synthetic_event_type_(synthetic_event_type),
- region_(initializer.region()),
+ region_(initializer->region()),
menu_source_type_(menu_source_type) {
- InitCoordinates(initializer.clientX(), initializer.clientY());
+ InitCoordinates(initializer->clientX(), initializer->clientY());
modifiers_ |= ButtonsToWebInputEventModifiers(buttons_);
}
@@ -218,7 +221,7 @@ void MouseEvent::InitCoordinates(const double client_x, const double client_y) {
void MouseEvent::SetCoordinatesFromWebPointerProperties(
const WebPointerProperties& web_pointer_properties,
const LocalDOMWindow* dom_window,
- MouseEventInit& initializer) {
+ MouseEventInit* initializer) {
FloatPoint client_point;
float scale_factor = 1.0f;
if (dom_window && dom_window->GetFrame() && dom_window->GetFrame()->View()) {
@@ -229,16 +232,18 @@ void MouseEvent::SetCoordinatesFromWebPointerProperties(
client_point = page_point.ScaledBy(scale_factor);
}
- initializer.setScreenX(web_pointer_properties.PositionInScreen().x);
- initializer.setScreenY(web_pointer_properties.PositionInScreen().y);
- initializer.setClientX(client_point.X());
- initializer.setClientY(client_point.Y());
-
- // TODO(nzolghadr): We need to scale movement attrinutes as well. But if we do
- // that here and round it to the int again it causes inconsistencies between
- // screenX/Y and cumulative movementX/Y.
- initializer.setMovementX(web_pointer_properties.movement_x);
- initializer.setMovementY(web_pointer_properties.movement_y);
+ initializer->setScreenX(web_pointer_properties.PositionInScreen().x);
+ initializer->setScreenY(web_pointer_properties.PositionInScreen().y);
+ initializer->setClientX(client_point.X());
+ initializer->setClientY(client_point.Y());
+
+ // TODO(nzolghadr): We need to scale movement attrinutes as well. But if we
+ // do that here and round it to the int again it causes inconsistencies
+ // between screenX/Y and cumulative movementX/Y.
+ if (!RuntimeEnabledFeatures::MovementXYInBlinkEnabled()) {
+ initializer->setMovementX(web_pointer_properties.movement_x);
+ initializer->setMovementY(web_pointer_properties.movement_y);
+ }
}
MouseEvent::~MouseEvent() = default;
@@ -328,7 +333,7 @@ void MouseEvent::InitMouseEventInternal(
}
const AtomicString& MouseEvent::InterfaceName() const {
- return EventNames::MouseEvent;
+ return event_interface_names::kMouseEvent;
}
bool MouseEvent::IsMouseEvent() const {
@@ -337,11 +342,11 @@ bool MouseEvent::IsMouseEvent() const {
short MouseEvent::button() const {
const AtomicString& event_name = type();
- if (button_ == -1 || event_name == EventTypeNames::mousemove ||
- event_name == EventTypeNames::mouseleave ||
- event_name == EventTypeNames::mouseenter ||
- event_name == EventTypeNames::mouseover ||
- event_name == EventTypeNames::mouseout) {
+ if (button_ == -1 || event_name == event_type_names::kMousemove ||
+ event_name == event_type_names::kMouseleave ||
+ event_name == event_type_names::kMouseenter ||
+ event_name == event_type_names::kMouseover ||
+ event_name == event_type_names::kMouseout) {
return 0;
}
return button_;
@@ -359,8 +364,8 @@ unsigned MouseEvent::which() const {
Node* MouseEvent::toElement() const {
// MSIE extension - "the object toward which the user is moving the mouse
// pointer"
- if (type() == EventTypeNames::mouseout ||
- type() == EventTypeNames::mouseleave)
+ if (type() == event_type_names::kMouseout ||
+ type() == event_type_names::kMouseleave)
return relatedTarget() ? relatedTarget()->ToNode() : nullptr;
return target() ? target()->ToNode() : nullptr;
@@ -369,8 +374,8 @@ Node* MouseEvent::toElement() const {
Node* MouseEvent::fromElement() const {
// MSIE extension - "object from which activation or the mouse pointer is
// exiting during the event" (huh?)
- if (type() != EventTypeNames::mouseout &&
- type() != EventTypeNames::mouseleave)
+ if (type() != event_type_names::kMouseout &&
+ type() != event_type_names::kMouseleave)
return relatedTarget() ? relatedTarget()->ToNode() : nullptr;
return target() ? target()->ToNode() : nullptr;
@@ -384,7 +389,7 @@ void MouseEvent::Trace(blink::Visitor* visitor) {
DispatchEventResult MouseEvent::DispatchEvent(EventDispatcher& dispatcher) {
GetEventPath().AdjustForRelatedTarget(dispatcher.GetNode(), relatedTarget());
- bool is_click = type() == EventTypeNames::click;
+ bool is_click = type() == event_type_names::kClick;
bool send_to_disabled_form_controls =
RuntimeEnabledFeatures::SendMouseEventsDisabledFormControlsEnabled();
@@ -401,8 +406,8 @@ DispatchEventResult MouseEvent::DispatchEvent(EventDispatcher& dispatcher) {
if (GetEventPath().HasEventListenersInPath(type())) {
UseCounter::Count(dispatcher.GetNode().GetDocument(),
WebFeature::kDispatchMouseEventOnDisabledFormControl);
- if (type() == EventTypeNames::mousedown ||
- type() == EventTypeNames::mouseup) {
+ if (type() == event_type_names::kMousedown ||
+ type() == event_type_names::kMouseup) {
UseCounter::Count(
dispatcher.GetNode().GetDocument(),
WebFeature::kDispatchMouseUpDownEventOnDisabledFormControl);
@@ -429,7 +434,7 @@ DispatchEventResult MouseEvent::DispatchEvent(EventDispatcher& dispatcher) {
// other DOM-compliant browsers like Firefox, and so we do the same.
MouseEvent& double_click_event = *MouseEvent::Create();
double_click_event.InitMouseEventInternal(
- EventTypeNames::dblclick, bubbles(), cancelable(), view(), detail(),
+ event_type_names::kDblclick, bubbles(), cancelable(), view(), detail(),
screenX(), screenY(), clientX(), clientY(), GetModifiers(), button(),
related_target, sourceCapabilities(), buttons());
double_click_event.SetComposed(composed());
diff --git a/chromium/third_party/blink/renderer/core/events/mouse_event.h b/chromium/third_party/blink/renderer/core/events/mouse_event.h
index 01753e47145..7c5eb200c88 100644
--- a/chromium/third_party/blink/renderer/core/events/mouse_event.h
+++ b/chromium/third_party/blink/renderer/core/events/mouse_event.h
@@ -51,30 +51,38 @@ class CORE_EXPORT MouseEvent : public UIEventWithKeyState {
kPositionless,
};
- static MouseEvent* Create() { return new MouseEvent; }
+ static MouseEvent* Create() { return MakeGarbageCollected<MouseEvent>(); }
static MouseEvent* Create(const AtomicString& event_type,
- const MouseEventInit&,
+ const MouseEventInit*,
TimeTicks platform_time_stamp,
SyntheticEventType,
WebMenuSourceType);
static MouseEvent* Create(ScriptState*,
const AtomicString& event_type,
- const MouseEventInit&);
+ const MouseEventInit*);
static MouseEvent* Create(const AtomicString& event_type,
AbstractView*,
Event* underlying_event,
SimulatedClickCreationScope);
+ MouseEvent(const AtomicString& type,
+ const MouseEventInit*,
+ TimeTicks platform_time_stamp,
+ SyntheticEventType = kRealOrIndistinguishable,
+ WebMenuSourceType = kMenuSourceNone);
+ MouseEvent(const AtomicString& type, const MouseEventInit* init)
+ : MouseEvent(type, init, CurrentTimeTicks()) {}
+ MouseEvent();
~MouseEvent() override;
static unsigned short WebInputEventModifiersToButtons(unsigned modifiers);
static void SetCoordinatesFromWebPointerProperties(
const WebPointerProperties&,
const LocalDOMWindow*,
- MouseEventInit&);
+ MouseEventInit*);
void initMouseEvent(ScriptState*,
const AtomicString& type,
@@ -185,8 +193,8 @@ class CORE_EXPORT MouseEvent : public UIEventWithKeyState {
WebMenuSourceType GetMenuSourceType() const { return menu_source_type_; }
// Page point in "absolute" coordinates (i.e. post-zoomed, page-relative
- // coords, usable with LayoutObject::absoluteToLocal) relative to view(), i.e.
- // the local frame.
+ // coords, usable with LayoutObject::absoluteToLocal) relative to view(),
+ // i.e. the local frame.
const DoublePoint& AbsoluteLocation() const { return absolute_location_; }
DispatchEventResult DispatchEvent(EventDispatcher&) override;
@@ -194,17 +202,6 @@ class CORE_EXPORT MouseEvent : public UIEventWithKeyState {
void Trace(blink::Visitor*) override;
protected:
- MouseEvent(const AtomicString& type,
- const MouseEventInit&,
- TimeTicks platform_time_stamp,
- SyntheticEventType = kRealOrIndistinguishable,
- WebMenuSourceType = kMenuSourceNone);
-
- MouseEvent(const AtomicString& type, const MouseEventInit& init)
- : MouseEvent(type, init, CurrentTimeTicks()) {}
-
- MouseEvent();
-
short RawButton() const { return button_; }
void ReceivedTarget() override;
@@ -215,7 +212,7 @@ class CORE_EXPORT MouseEvent : public UIEventWithKeyState {
DoublePoint screen_location_;
DoublePoint client_location_;
- DoublePoint page_location_; // zoomed CSS pixels
+ DoublePoint page_location_; // zoomed CSS pixels
DoublePoint offset_location_; // zoomed CSS pixels
bool has_cached_relative_position_ = false;
diff --git a/chromium/third_party/blink/renderer/core/events/mutation_event.cc b/chromium/third_party/blink/renderer/core/events/mutation_event.cc
index 103e2928c49..5c350ea1bca 100644
--- a/chromium/third_party/blink/renderer/core/events/mutation_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/mutation_event.cc
@@ -22,6 +22,8 @@
#include "third_party/blink/renderer/core/events/mutation_event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
+
namespace blink {
MutationEvent::MutationEvent() : attr_change_(0) {}
@@ -64,7 +66,7 @@ void MutationEvent::initMutationEvent(const AtomicString& type,
}
const AtomicString& MutationEvent::InterfaceName() const {
- return EventNames::MutationEvent;
+ return event_interface_names::kMutationEvent;
}
void MutationEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/mutation_event.h b/chromium/third_party/blink/renderer/core/events/mutation_event.h
index 7af19a8ea7b..14a55938fb7 100644
--- a/chromium/third_party/blink/renderer/core/events/mutation_event.h
+++ b/chromium/third_party/blink/renderer/core/events/mutation_event.h
@@ -37,7 +37,9 @@ class MutationEvent final : public Event {
enum AttrChangeType { kModification = 1, kAddition = 2, kRemoval = 3 };
- static MutationEvent* Create() { return new MutationEvent; }
+ static MutationEvent* Create() {
+ return MakeGarbageCollected<MutationEvent>();
+ }
static MutationEvent* Create(const AtomicString& type,
Bubbles bubbles,
@@ -46,10 +48,21 @@ class MutationEvent final : public Event {
const String& new_value = String(),
const String& attr_name = String(),
unsigned short attr_change = 0) {
- return new MutationEvent(type, bubbles, Cancelable::kNo, related_node,
- prev_value, new_value, attr_name, attr_change);
+ return MakeGarbageCollected<MutationEvent>(
+ type, bubbles, Cancelable::kNo, related_node, prev_value, new_value,
+ attr_name, attr_change);
}
+ MutationEvent();
+ MutationEvent(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ Node* related_node,
+ const String& prev_value,
+ const String& new_value,
+ const String& attr_name,
+ unsigned short attr_change);
+
void initMutationEvent(const AtomicString& type,
bool bubbles,
bool cancelable,
@@ -70,16 +83,6 @@ class MutationEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- MutationEvent();
- MutationEvent(const AtomicString& type,
- Bubbles,
- Cancelable,
- Node* related_node,
- const String& prev_value,
- const String& new_value,
- const String& attr_name,
- unsigned short attr_change);
-
Member<Node> related_node_;
String prev_value_;
String new_value_;
diff --git a/chromium/third_party/blink/renderer/core/events/page_transition_event.cc b/chromium/third_party/blink/renderer/core/events/page_transition_event.cc
index aa691287186..7d634566862 100644
--- a/chromium/third_party/blink/renderer/core/events/page_transition_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/page_transition_event.cc
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/events/page_transition_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -37,16 +37,16 @@ PageTransitionEvent::PageTransitionEvent(const AtomicString& type,
PageTransitionEvent::PageTransitionEvent(
const AtomicString& type,
- const PageTransitionEventInit& initializer)
+ const PageTransitionEventInit* initializer)
: Event(type, initializer), persisted_(false) {
- if (initializer.hasPersisted())
- persisted_ = initializer.persisted();
+ if (initializer->hasPersisted())
+ persisted_ = initializer->persisted();
}
PageTransitionEvent::~PageTransitionEvent() = default;
const AtomicString& PageTransitionEvent::InterfaceName() const {
- return EventNames::PageTransitionEvent;
+ return event_interface_names::kPageTransitionEvent;
}
void PageTransitionEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/page_transition_event.h b/chromium/third_party/blink/renderer/core/events/page_transition_event.h
index 1c115b54a5f..9570909fe67 100644
--- a/chromium/third_party/blink/renderer/core/events/page_transition_event.h
+++ b/chromium/third_party/blink/renderer/core/events/page_transition_event.h
@@ -35,16 +35,21 @@ class PageTransitionEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static PageTransitionEvent* Create() { return new PageTransitionEvent; }
+ static PageTransitionEvent* Create() {
+ return MakeGarbageCollected<PageTransitionEvent>();
+ }
static PageTransitionEvent* Create(const AtomicString& type, bool persisted) {
- return new PageTransitionEvent(type, persisted);
+ return MakeGarbageCollected<PageTransitionEvent>(type, persisted);
}
static PageTransitionEvent* Create(
const AtomicString& type,
- const PageTransitionEventInit& initializer) {
- return new PageTransitionEvent(type, initializer);
+ const PageTransitionEventInit* initializer) {
+ return MakeGarbageCollected<PageTransitionEvent>(type, initializer);
}
+ PageTransitionEvent();
+ PageTransitionEvent(const AtomicString& type, bool persisted);
+ PageTransitionEvent(const AtomicString&, const PageTransitionEventInit*);
~PageTransitionEvent() override;
const AtomicString& InterfaceName() const override;
@@ -54,10 +59,6 @@ class PageTransitionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- PageTransitionEvent();
- PageTransitionEvent(const AtomicString& type, bool persisted);
- PageTransitionEvent(const AtomicString&, const PageTransitionEventInit&);
-
bool persisted_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.cc b/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.cc
index 6c37f141f1f..17e4158f955 100644
--- a/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.cc
@@ -9,13 +9,13 @@ namespace blink {
PictureInPictureControlEvent* PictureInPictureControlEvent::Create(
const AtomicString& type,
String id) {
- return new PictureInPictureControlEvent(type, id);
+ return MakeGarbageCollected<PictureInPictureControlEvent>(type, id);
}
PictureInPictureControlEvent* PictureInPictureControlEvent::Create(
const AtomicString& type,
- const PictureInPictureControlEventInit& initializer) {
- return new PictureInPictureControlEvent(type, initializer);
+ const PictureInPictureControlEventInit* initializer) {
+ return MakeGarbageCollected<PictureInPictureControlEvent>(type, initializer);
}
String PictureInPictureControlEvent::id() const {
@@ -32,7 +32,7 @@ PictureInPictureControlEvent::PictureInPictureControlEvent(
PictureInPictureControlEvent::PictureInPictureControlEvent(
AtomicString const& type,
- const PictureInPictureControlEventInit& initializer)
- : Event(type, initializer), id_(initializer.id()) {}
+ const PictureInPictureControlEventInit* initializer)
+ : Event(type, initializer), id_(initializer->id()) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.h b/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.h
index 199c2bbfb39..718b80317d8 100644
--- a/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.h
+++ b/chromium/third_party/blink/renderer/core/events/picture_in_picture_control_event.h
@@ -20,16 +20,16 @@ class CORE_EXPORT PictureInPictureControlEvent final : public Event {
static PictureInPictureControlEvent* Create(const AtomicString&, String);
static PictureInPictureControlEvent* Create(
const AtomicString&,
- const PictureInPictureControlEventInit&);
+ const PictureInPictureControlEventInit*);
+
+ PictureInPictureControlEvent(AtomicString const&, String);
+ PictureInPictureControlEvent(AtomicString const&,
+ const PictureInPictureControlEventInit*);
String id() const;
void setId(String id);
private:
- PictureInPictureControlEvent(AtomicString const&, String);
- PictureInPictureControlEvent(AtomicString const&,
- const PictureInPictureControlEventInit&);
-
// id_ holds the id of a PictureIncPictureControlEvent, which is used to
// convey which custom control fired the event by being clicked.
String id_;
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event.cc b/chromium/third_party/blink/renderer/core/events/pointer_event.cc
index 116c06af9ef..a7501d92c46 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event.cc
@@ -11,7 +11,7 @@
namespace blink {
PointerEvent::PointerEvent(const AtomicString& type,
- const PointerEventInit& initializer,
+ const PointerEventInit* initializer,
TimeTicks platform_time_stamp)
: MouseEvent(type, initializer, platform_time_stamp),
pointer_id_(0),
@@ -23,31 +23,36 @@ PointerEvent::PointerEvent(const AtomicString& type,
tangential_pressure_(0),
twist_(0),
is_primary_(false),
- coalesced_events_targets_dirty_(false) {
- if (initializer.hasPointerId())
- pointer_id_ = initializer.pointerId();
- if (initializer.hasWidth())
- width_ = initializer.width();
- if (initializer.hasHeight())
- height_ = initializer.height();
- if (initializer.hasPressure())
- pressure_ = initializer.pressure();
- if (initializer.hasTiltX())
- tilt_x_ = initializer.tiltX();
- if (initializer.hasTiltY())
- tilt_y_ = initializer.tiltY();
- if (initializer.hasTangentialPressure())
- tangential_pressure_ = initializer.tangentialPressure();
- if (initializer.hasTwist())
- twist_ = initializer.twist();
- if (initializer.hasPointerType())
- pointer_type_ = initializer.pointerType();
- if (initializer.hasIsPrimary())
- is_primary_ = initializer.isPrimary();
- if (initializer.hasCoalescedEvents()) {
- for (auto coalesced_event : initializer.coalescedEvents())
+ coalesced_events_targets_dirty_(false),
+ predicted_events_targets_dirty_(false) {
+ if (initializer->hasPointerId())
+ pointer_id_ = initializer->pointerId();
+ if (initializer->hasWidth())
+ width_ = initializer->width();
+ if (initializer->hasHeight())
+ height_ = initializer->height();
+ if (initializer->hasPressure())
+ pressure_ = initializer->pressure();
+ if (initializer->hasTiltX())
+ tilt_x_ = initializer->tiltX();
+ if (initializer->hasTiltY())
+ tilt_y_ = initializer->tiltY();
+ if (initializer->hasTangentialPressure())
+ tangential_pressure_ = initializer->tangentialPressure();
+ if (initializer->hasTwist())
+ twist_ = initializer->twist();
+ if (initializer->hasPointerType())
+ pointer_type_ = initializer->pointerType();
+ if (initializer->hasIsPrimary())
+ is_primary_ = initializer->isPrimary();
+ if (initializer->hasCoalescedEvents()) {
+ for (auto coalesced_event : initializer->coalescedEvents())
coalesced_events_.push_back(coalesced_event);
}
+ if (initializer->hasPredictedEvents()) {
+ for (auto predicted_event : initializer->predictedEvents())
+ predicted_events_.push_back(predicted_event);
+ }
}
bool PointerEvent::IsMouseEvent() const {
@@ -58,57 +63,12 @@ bool PointerEvent::IsPointerEvent() const {
return true;
}
-double PointerEvent::screenX() const {
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? static_cast<int>(screen_location_.X())
- : screen_location_.X();
-}
-
-double PointerEvent::screenY() const {
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? static_cast<int>(screen_location_.Y())
- : screen_location_.Y();
-}
-
-double PointerEvent::clientX() const {
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? static_cast<int>(client_location_.X())
- : client_location_.X();
-}
-
-double PointerEvent::clientY() const {
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? static_cast<int>(client_location_.Y())
- : client_location_.Y();
-}
-
-double PointerEvent::pageX() const {
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? static_cast<int>(page_location_.X())
- : page_location_.X();
-}
-
-double PointerEvent::pageY() const {
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? static_cast<int>(page_location_.Y())
- : page_location_.Y();
-}
-
double PointerEvent::offsetX() {
if (!HasPosition())
return 0;
if (!has_cached_relative_position_)
ComputeRelativePosition();
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? std::round(offset_location_.X())
- : offset_location_.X();
+ return offset_location_.X();
}
double PointerEvent::offsetY() {
@@ -116,14 +76,12 @@ double PointerEvent::offsetY() {
return 0;
if (!has_cached_relative_position_)
ComputeRelativePosition();
- return (!RuntimeEnabledFeatures::FractionalMouseTypePointerEventEnabled() &&
- pointer_type_ == "mouse")
- ? std::round(offset_location_.Y())
- : offset_location_.Y();
+ return offset_location_.Y();
}
void PointerEvent::ReceivedTarget() {
coalesced_events_targets_dirty_ = true;
+ predicted_events_targets_dirty_ = true;
MouseEvent::ReceivedTarget();
}
@@ -144,6 +102,15 @@ HeapVector<Member<PointerEvent>> PointerEvent::getCoalescedEvents() {
return coalesced_events_;
}
+HeapVector<Member<PointerEvent>> PointerEvent::getPredictedEvents() {
+ if (predicted_events_targets_dirty_) {
+ for (auto predicted_event : predicted_events_)
+ predicted_event->SetTarget(target());
+ predicted_events_targets_dirty_ = false;
+ }
+ return predicted_events_;
+}
+
TimeTicks PointerEvent::OldestPlatformTimeStamp() const {
if (coalesced_events_.size() > 0) {
// Assume that time stamps of coalesced events are in ascending order.
@@ -154,6 +121,7 @@ TimeTicks PointerEvent::OldestPlatformTimeStamp() const {
void PointerEvent::Trace(blink::Visitor* visitor) {
visitor->Trace(coalesced_events_);
+ visitor->Trace(predicted_events_);
MouseEvent::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event.h b/chromium/third_party/blink/renderer/core/events/pointer_event.h
index 84ebf1fa0f2..22626408581 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event.h
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event.h
@@ -15,15 +15,20 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
public:
static PointerEvent* Create(const AtomicString& type,
- const PointerEventInit& initializer,
+ const PointerEventInit* initializer,
TimeTicks platform_time_stamp) {
- return new PointerEvent(type, initializer, platform_time_stamp);
+ return MakeGarbageCollected<PointerEvent>(type, initializer,
+ platform_time_stamp);
}
static PointerEvent* Create(const AtomicString& type,
- const PointerEventInit& initializer) {
+ const PointerEventInit* initializer) {
return PointerEvent::Create(type, initializer, CurrentTimeTicks());
}
+ PointerEvent(const AtomicString&,
+ const PointerEventInit*,
+ TimeTicks platform_time_stamp);
+
int32_t pointerId() const { return pointer_id_; }
double width() const { return width_; }
double height() const { return height_; }
@@ -39,14 +44,12 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
bool IsMouseEvent() const override;
bool IsPointerEvent() const override;
- // TODO(eirage): Remove these override of coordinates getters when
- // fractional mouseevent flag is removed.
- double screenX() const override;
- double screenY() const override;
- double clientX() const override;
- double clientY() const override;
- double pageX() const override;
- double pageY() const override;
+ double screenX() const override { return screen_location_.X(); }
+ double screenY() const override { return screen_location_.Y(); }
+ double clientX() const override { return client_location_.X(); }
+ double clientY() const override { return client_location_.Y(); }
+ double pageX() const override { return page_location_.X(); }
+ double pageY() const override { return page_location_.Y(); }
double offsetX() override;
double offsetY() override;
@@ -59,6 +62,7 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
Node* toElement() const final;
HeapVector<Member<PointerEvent>> getCoalescedEvents();
+ HeapVector<Member<PointerEvent>> getPredictedEvents();
TimeTicks OldestPlatformTimeStamp() const;
DispatchEventResult DispatchEvent(EventDispatcher&) override;
@@ -66,10 +70,6 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
void Trace(blink::Visitor*) override;
private:
- PointerEvent(const AtomicString&,
- const PointerEventInit&,
- TimeTicks platform_time_stamp);
-
int32_t pointer_id_;
double width_;
double height_;
@@ -82,8 +82,11 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
bool is_primary_;
bool coalesced_events_targets_dirty_;
+ bool predicted_events_targets_dirty_;
HeapVector<Member<PointerEvent>> coalesced_events_;
+
+ HeapVector<Member<PointerEvent>> predicted_events_;
};
DEFINE_EVENT_TYPE_CASTS(PointerEvent);
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event.idl b/chromium/third_party/blink/renderer/core/events/pointer_event.idl
index cc4a446d47f..1cc1a41d034 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event.idl
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event.idl
@@ -20,4 +20,5 @@
// https://w3c.github.io/pointerevents/extension.html#extensions-to-the-pointerevent-interface
sequence<PointerEvent> getCoalescedEvents();
+ [RuntimeEnabled=PredictedEvents] sequence<PointerEvent> getPredictedEvents();
};
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event_factory.cc b/chromium/third_party/blink/renderer/core/events/pointer_event_factory.cc
index 77839b72ca2..7b57f3554c0 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event_factory.cc
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event_factory.cc
@@ -58,15 +58,15 @@ unsigned short ButtonToButtonsBitfield(WebPointerProperties::Button button) {
const AtomicString& PointerEventNameForEventType(WebInputEvent::Type type) {
switch (type) {
case WebInputEvent::kPointerDown:
- return EventTypeNames::pointerdown;
+ return event_type_names::kPointerdown;
case WebInputEvent::kPointerUp:
- return EventTypeNames::pointerup;
+ return event_type_names::kPointerup;
case WebInputEvent::kPointerMove:
- return EventTypeNames::pointermove;
+ return event_type_names::kPointermove;
case WebInputEvent::kPointerRawMove:
- return EventTypeNames::pointerrawmove;
+ return event_type_names::kPointerrawmove;
case WebInputEvent::kPointerCancel:
- return EventTypeNames::pointercancel;
+ return event_type_names::kPointercancel;
default:
NOTREACHED();
return g_empty_atom;
@@ -82,6 +82,7 @@ float GetPointerEventPressure(float force, int buttons) {
}
void UpdateCommonPointerEventInit(const WebPointerEvent& web_pointer_event,
+ const FloatPoint& last_global_position,
LocalDOMWindow* dom_window,
PointerEventInit* pointer_event_init) {
// This function should not update attributes like pointerId, isPrimary,
@@ -92,7 +93,16 @@ void UpdateCommonPointerEventInit(const WebPointerEvent& web_pointer_event,
web_pointer_event.WebPointerEventInRootFrame();
MouseEvent::SetCoordinatesFromWebPointerProperties(
- web_pointer_event_in_root_frame, dom_window, *pointer_event_init);
+ web_pointer_event_in_root_frame, dom_window, pointer_event_init);
+ if (RuntimeEnabledFeatures::MovementXYInBlinkEnabled() &&
+ web_pointer_event.GetType() == WebInputEvent::kPointerMove) {
+ // TODO(eirage): pointerrawmove event's movements are not calculated.
+ pointer_event_init->setMovementX(web_pointer_event.PositionInScreen().x -
+ last_global_position.X());
+ pointer_event_init->setMovementY(web_pointer_event.PositionInScreen().y -
+ last_global_position.Y());
+ }
+
// If width/height is unknown we let PointerEventInit set it to 1.
// See https://w3c.github.io/pointerevents/#dom-pointerevent-width
if (web_pointer_event_in_root_frame.HasWidth() &&
@@ -118,13 +128,65 @@ void UpdateCommonPointerEventInit(const WebPointerEvent& web_pointer_event,
} // namespace
+HeapVector<Member<PointerEvent>> PointerEventFactory::CreateEventSequence(
+ const WebPointerEvent& web_pointer_event,
+ const PointerEventInit* pointer_event_init,
+ const Vector<WebPointerEvent>& event_list,
+ LocalDOMWindow* view) {
+ AtomicString type = PointerEventNameForEventType(web_pointer_event.GetType());
+ HeapVector<Member<PointerEvent>> result;
+
+ if (!event_list.IsEmpty()) {
+ // Make a copy of LastPointerPosition so we can modify it after creating
+ // each coalesced event.
+ FloatPoint last_global_position = GetLastPointerPosition(
+ pointer_event_init->pointerId(), event_list.front());
+
+ for (const auto& event : event_list) {
+ DCHECK_EQ(web_pointer_event.id, event.id);
+ DCHECK_EQ(web_pointer_event.GetType(), event.GetType());
+ DCHECK_EQ(web_pointer_event.pointer_type, event.pointer_type);
+
+ PointerEventInit* new_event_init = PointerEventInit::Create();
+ if (pointer_event_init->hasButton())
+ new_event_init->setButton(pointer_event_init->button());
+ if (pointer_event_init->hasButtons())
+ new_event_init->setButtons(pointer_event_init->buttons());
+ if (pointer_event_init->hasIsPrimary())
+ new_event_init->setIsPrimary(pointer_event_init->isPrimary());
+ if (pointer_event_init->hasPointerId())
+ new_event_init->setPointerId(pointer_event_init->pointerId());
+ if (pointer_event_init->hasPointerType())
+ new_event_init->setPointerType(pointer_event_init->pointerType());
+ if (pointer_event_init->hasView())
+ new_event_init->setView(pointer_event_init->view());
+
+ new_event_init->setCancelable(false);
+ new_event_init->setBubbles(false);
+ UpdateCommonPointerEventInit(event, last_global_position, view,
+ new_event_init);
+ last_global_position = event.PositionInScreen();
+
+ PointerEvent* pointer_event =
+ PointerEvent::Create(type, new_event_init, event.TimeStamp());
+ // Set the trusted flag for these events at the creation time as oppose to
+ // the normal events which is done at the dispatch time. This is because
+ // we don't want to go over all these events at every dispatch and add the
+ // implementation complexity while it has no sensible usecase at this
+ // time.
+ pointer_event->SetTrusted(true);
+ result.push_back(pointer_event);
+ }
+ }
+ return result;
+}
+
const int PointerEventFactory::kInvalidId = 0;
// Mouse id is 1 to behave the same as MS Edge for compatibility reasons.
const int PointerEventFactory::kMouseId = 1;
-void PointerEventFactory::SetIdTypeButtons(
- PointerEventInit& pointer_event_init,
+PointerEventInit* PointerEventFactory::ConvertIdTypeButtonsEvent(
const WebPointerEvent& web_pointer_event) {
WebPointerProperties::PointerType pointer_type =
web_pointer_event.pointer_type;
@@ -154,36 +216,41 @@ void PointerEventFactory::SetIdTypeButtons(
}
pointer_type = WebPointerProperties::PointerType::kPen;
}
- pointer_event_init.setButtons(buttons);
+ PointerEventInit* pointer_event_init = PointerEventInit::Create();
+ pointer_event_init->setButtons(buttons);
const IncomingId incoming_id(pointer_type, web_pointer_event.id);
int pointer_id = AddIdAndActiveButtons(incoming_id, buttons != 0,
web_pointer_event.hovering);
- pointer_event_init.setPointerId(pointer_id);
- pointer_event_init.setPointerType(
+ pointer_event_init->setPointerId(pointer_id);
+ pointer_event_init->setPointerType(
PointerTypeNameForWebPointPointerType(pointer_type));
- pointer_event_init.setIsPrimary(IsPrimary(pointer_id));
+ pointer_event_init->setIsPrimary(IsPrimary(pointer_id));
+
+ return pointer_event_init;
}
void PointerEventFactory::SetEventSpecificFields(
- PointerEventInit& pointer_event_init,
+ PointerEventInit* pointer_event_init,
const AtomicString& type) {
- pointer_event_init.setBubbles(type != EventTypeNames::pointerenter &&
- type != EventTypeNames::pointerleave);
- pointer_event_init.setCancelable(type != EventTypeNames::pointerenter &&
- type != EventTypeNames::pointerleave &&
- type != EventTypeNames::pointercancel &&
- type != EventTypeNames::pointerrawmove &&
- type != EventTypeNames::gotpointercapture &&
- type != EventTypeNames::lostpointercapture);
-
- pointer_event_init.setComposed(true);
- pointer_event_init.setDetail(0);
+ pointer_event_init->setBubbles(type != event_type_names::kPointerenter &&
+ type != event_type_names::kPointerleave);
+ pointer_event_init->setCancelable(
+ type != event_type_names::kPointerenter &&
+ type != event_type_names::kPointerleave &&
+ type != event_type_names::kPointercancel &&
+ type != event_type_names::kPointerrawmove &&
+ type != event_type_names::kGotpointercapture &&
+ type != event_type_names::kLostpointercapture);
+
+ pointer_event_init->setComposed(true);
+ pointer_event_init->setDetail(0);
}
PointerEvent* PointerEventFactory::Create(
const WebPointerEvent& web_pointer_event,
const Vector<WebPointerEvent>& coalesced_events,
+ const Vector<WebPointerEvent>& predicted_events,
LocalDOMWindow* view) {
const WebInputEvent::Type event_type = web_pointer_event.GetType();
DCHECK(event_type == WebInputEvent::kPointerDown ||
@@ -192,9 +259,8 @@ PointerEvent* PointerEventFactory::Create(
event_type == WebInputEvent::kPointerRawMove ||
event_type == WebInputEvent::kPointerCancel);
- PointerEventInit pointer_event_init;
-
- SetIdTypeButtons(pointer_event_init, web_pointer_event);
+ PointerEventInit* pointer_event_init =
+ ConvertIdTypeButtonsEvent(web_pointer_event);
AtomicString type = PointerEventNameForEventType(event_type);
if (event_type == WebInputEvent::kPointerDown ||
@@ -205,22 +271,26 @@ PointerEvent* PointerEventFactory::Create(
WebPointerProperties::PointerType::kEraser &&
button == WebPointerProperties::Button::kLeft)
button = WebPointerProperties::Button::kEraser;
- pointer_event_init.setButton(static_cast<int>(button));
+ pointer_event_init->setButton(static_cast<int>(button));
// Make sure chorded buttons fire pointermove instead of pointerup/down.
if ((event_type == WebInputEvent::kPointerDown &&
- (pointer_event_init.buttons() & ~ButtonToButtonsBitfield(button)) !=
+ (pointer_event_init->buttons() & ~ButtonToButtonsBitfield(button)) !=
0) ||
(event_type == WebInputEvent::kPointerUp &&
- pointer_event_init.buttons() != 0))
- type = EventTypeNames::pointermove;
+ pointer_event_init->buttons() != 0))
+ type = event_type_names::kPointermove;
} else {
- pointer_event_init.setButton(
+ pointer_event_init->setButton(
static_cast<int>(WebPointerProperties::Button::kNoButton));
}
- pointer_event_init.setView(view);
- UpdateCommonPointerEventInit(web_pointer_event, view, &pointer_event_init);
+ pointer_event_init->setView(view);
+ UpdateCommonPointerEventInit(
+ web_pointer_event,
+ GetLastPointerPosition(pointer_event_init->pointerId(),
+ web_pointer_event),
+ view, pointer_event_init);
UIEventWithKeyState::SetFromWebInputEventModifiers(
pointer_event_init,
@@ -228,36 +298,44 @@ PointerEvent* PointerEventFactory::Create(
SetEventSpecificFields(pointer_event_init, type);
- if (type == EventTypeNames::pointermove ||
- type == EventTypeNames::pointerrawmove) {
- HeapVector<Member<PointerEvent>> coalesced_pointer_events;
- for (const auto& coalesced_event : coalesced_events) {
- DCHECK_EQ(web_pointer_event.id, coalesced_event.id);
- DCHECK_EQ(web_pointer_event.GetType(), coalesced_event.GetType());
- DCHECK_EQ(web_pointer_event.pointer_type, coalesced_event.pointer_type);
-
- PointerEventInit coalesced_event_init = pointer_event_init;
- coalesced_event_init.setCancelable(false);
- coalesced_event_init.setBubbles(false);
- UpdateCommonPointerEventInit(coalesced_event, view,
- &coalesced_event_init);
- PointerEvent* event = PointerEvent::Create(type, coalesced_event_init,
- coalesced_event.TimeStamp());
- // Set the trusted flag for the coalesced events at the creation time
- // as oppose to the normal events which is done at the dispatch time. This
- // is because we don't want to go over all the coalesced events at every
- // dispatch and add the implementation complexity while it has no sensible
- // usecase at this time.
- event->SetTrusted(true);
- coalesced_pointer_events.push_back(event);
- }
- pointer_event_init.setCoalescedEvents(coalesced_pointer_events);
+ HeapVector<Member<PointerEvent>> coalesced_pointer_events,
+ predicted_pointer_events;
+ if (type == event_type_names::kPointermove ||
+ type == event_type_names::kPointerrawmove) {
+ coalesced_pointer_events = CreateEventSequence(
+ web_pointer_event, pointer_event_init, coalesced_events, view);
+ }
+ if (type == event_type_names::kPointermove) {
+ predicted_pointer_events = CreateEventSequence(
+ web_pointer_event, pointer_event_init, predicted_events, view);
}
+ pointer_event_init->setCoalescedEvents(coalesced_pointer_events);
+ pointer_event_init->setPredictedEvents(predicted_pointer_events);
+ SetLastPosition(pointer_event_init->pointerId(), web_pointer_event);
return PointerEvent::Create(type, pointer_event_init,
web_pointer_event.TimeStamp());
}
+void PointerEventFactory::SetLastPosition(int pointer_id,
+ const WebPointerProperties& event) {
+ pointer_id_last_position_mapping_.Set(pointer_id, event.PositionInScreen());
+}
+
+void PointerEventFactory::RemoveLastPosition(const int pointer_id) {
+ return pointer_id_last_position_mapping_.erase(pointer_id);
+}
+
+FloatPoint PointerEventFactory::GetLastPointerPosition(
+ int pointer_id,
+ const WebPointerProperties& event) const {
+ if (pointer_id_last_position_mapping_.Contains(pointer_id))
+ return pointer_id_last_position_mapping_.at(pointer_id);
+ // If pointer_id is not in the map, returns the current position so the
+ // movement will be zero.
+ return event.PositionInScreen();
+}
+
PointerEvent* PointerEventFactory::CreatePointerCancelEvent(
const int pointer_id,
TimeTicks platfrom_time_stamp) {
@@ -267,47 +345,48 @@ PointerEvent* PointerEventFactory::CreatePointerCancelEvent(
PointerAttributes(pointer_id_mapping_.at(pointer_id).incoming_id, false,
true));
- PointerEventInit pointer_event_init;
+ PointerEventInit* pointer_event_init = PointerEventInit::Create();
- pointer_event_init.setPointerId(pointer_id);
- pointer_event_init.setPointerType(PointerTypeNameForWebPointPointerType(
+ pointer_event_init->setPointerId(pointer_id);
+ pointer_event_init->setPointerType(PointerTypeNameForWebPointPointerType(
pointer_id_mapping_.at(pointer_id).incoming_id.GetPointerType()));
- pointer_event_init.setIsPrimary(IsPrimary(pointer_id));
+ pointer_event_init->setIsPrimary(IsPrimary(pointer_id));
- SetEventSpecificFields(pointer_event_init, EventTypeNames::pointercancel);
+ SetEventSpecificFields(pointer_event_init, event_type_names::kPointercancel);
- return PointerEvent::Create(EventTypeNames::pointercancel, pointer_event_init,
- platfrom_time_stamp);
+ return PointerEvent::Create(event_type_names::kPointercancel,
+ pointer_event_init, platfrom_time_stamp);
}
PointerEvent* PointerEventFactory::CreatePointerEventFrom(
PointerEvent* pointer_event,
const AtomicString& type,
EventTarget* related_target) {
- PointerEventInit pointer_event_init;
-
- pointer_event_init.setPointerId(pointer_event->pointerId());
- pointer_event_init.setPointerType(pointer_event->pointerType());
- pointer_event_init.setIsPrimary(pointer_event->isPrimary());
- pointer_event_init.setWidth(pointer_event->width());
- pointer_event_init.setHeight(pointer_event->height());
- pointer_event_init.setScreenX(pointer_event->screenX());
- pointer_event_init.setScreenY(pointer_event->screenY());
- pointer_event_init.setClientX(pointer_event->clientX());
- pointer_event_init.setClientY(pointer_event->clientY());
- pointer_event_init.setButton(pointer_event->button());
- pointer_event_init.setButtons(pointer_event->buttons());
- pointer_event_init.setPressure(pointer_event->pressure());
- pointer_event_init.setTiltX(pointer_event->tiltX());
- pointer_event_init.setTiltY(pointer_event->tiltY());
- pointer_event_init.setTangentialPressure(pointer_event->tangentialPressure());
- pointer_event_init.setTwist(pointer_event->twist());
- pointer_event_init.setView(pointer_event->view());
+ PointerEventInit* pointer_event_init = PointerEventInit::Create();
+
+ pointer_event_init->setPointerId(pointer_event->pointerId());
+ pointer_event_init->setPointerType(pointer_event->pointerType());
+ pointer_event_init->setIsPrimary(pointer_event->isPrimary());
+ pointer_event_init->setWidth(pointer_event->width());
+ pointer_event_init->setHeight(pointer_event->height());
+ pointer_event_init->setScreenX(pointer_event->screenX());
+ pointer_event_init->setScreenY(pointer_event->screenY());
+ pointer_event_init->setClientX(pointer_event->clientX());
+ pointer_event_init->setClientY(pointer_event->clientY());
+ pointer_event_init->setButton(pointer_event->button());
+ pointer_event_init->setButtons(pointer_event->buttons());
+ pointer_event_init->setPressure(pointer_event->pressure());
+ pointer_event_init->setTiltX(pointer_event->tiltX());
+ pointer_event_init->setTiltY(pointer_event->tiltY());
+ pointer_event_init->setTangentialPressure(
+ pointer_event->tangentialPressure());
+ pointer_event_init->setTwist(pointer_event->twist());
+ pointer_event_init->setView(pointer_event->view());
SetEventSpecificFields(pointer_event_init, type);
if (related_target)
- pointer_event_init.setRelatedTarget(related_target);
+ pointer_event_init->setRelatedTarget(related_target);
return PointerEvent::Create(type, pointer_event_init,
pointer_event->PlatformTimeStamp());
@@ -318,21 +397,22 @@ PointerEvent* PointerEventFactory::CreatePointerRawMoveEvent(
// This function is for creating pointerrawmove event from a pointerdown/up
// event that caused by chorded buttons and hence its type is changed to
// pointermove.
- DCHECK(pointer_event->type() == EventTypeNames::pointermove &&
+ DCHECK(pointer_event->type() == event_type_names::kPointermove &&
(pointer_event->buttons() &
~ButtonToButtonsBitfield(static_cast<WebPointerProperties::Button>(
pointer_event->button()))) != 0 &&
pointer_event->button() != 0);
- return CreatePointerEventFrom(pointer_event, EventTypeNames::pointerrawmove,
+ return CreatePointerEventFrom(pointer_event,
+ event_type_names::kPointerrawmove,
pointer_event->relatedTarget());
}
PointerEvent* PointerEventFactory::CreatePointerCaptureEvent(
PointerEvent* pointer_event,
const AtomicString& type) {
- DCHECK(type == EventTypeNames::gotpointercapture ||
- type == EventTypeNames::lostpointercapture);
+ DCHECK(type == event_type_names::kGotpointercapture ||
+ type == event_type_names::kLostpointercapture);
return CreatePointerEventFrom(pointer_event, type,
pointer_event->relatedTarget());
@@ -342,10 +422,10 @@ PointerEvent* PointerEventFactory::CreatePointerBoundaryEvent(
PointerEvent* pointer_event,
const AtomicString& type,
EventTarget* related_target) {
- DCHECK(type == EventTypeNames::pointerout ||
- type == EventTypeNames::pointerleave ||
- type == EventTypeNames::pointerover ||
- type == EventTypeNames::pointerenter);
+ DCHECK(type == event_type_names::kPointerout ||
+ type == event_type_names::kPointerleave ||
+ type == event_type_names::kPointerover ||
+ type == event_type_names::kPointerenter);
return CreatePointerEventFrom(pointer_event, type, related_target);
}
@@ -366,6 +446,7 @@ void PointerEventFactory::Clear() {
}
pointer_incoming_id_mapping_.clear();
pointer_id_mapping_.clear();
+ pointer_id_last_position_mapping_.clear();
// Always add mouse pointer in initialization and never remove it.
// No need to add it to m_pointerIncomingIdMapping as it is not going to be
@@ -416,6 +497,7 @@ bool PointerEventFactory::Remove(const int mapped_id) {
int type_int = p.PointerTypeInt();
pointer_id_mapping_.erase(mapped_id);
pointer_incoming_id_mapping_.erase(p);
+ RemoveLastPosition(mapped_id);
if (primary_id_[type_int] == mapped_id)
primary_id_[type_int] = PointerEventFactory::kInvalidId;
id_count_[type_int]--;
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event_factory.h b/chromium/third_party/blink/renderer/core/events/pointer_event_factory.h
index b2826fa992f..67413673980 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event_factory.h
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event_factory.h
@@ -30,9 +30,10 @@ class CORE_EXPORT PointerEventFactory {
PointerEventFactory();
~PointerEventFactory();
- PointerEvent* Create(const WebPointerEvent&,
- const Vector<WebPointerEvent>&,
- LocalDOMWindow*);
+ PointerEvent* Create(const WebPointerEvent& web_pointer_event,
+ const Vector<WebPointerEvent>& coalesced_events,
+ const Vector<WebPointerEvent>& predicted_events,
+ LocalDOMWindow* view);
PointerEvent* CreatePointerCancelEvent(
const int pointer_id,
@@ -79,6 +80,15 @@ class CORE_EXPORT PointerEventFactory {
static const int kMouseId;
+ // Removes pointer_id from the map.
+ void RemoveLastPosition(const int pointer_id);
+
+ // Returns last_position of for the given pointerId if such id is active.
+ // Otherwise it returns the PositionInScreen of the given events, so we will
+ // get movement = 0 when there is no last position.
+ FloatPoint GetLastPointerPosition(int pointer_id,
+ const WebPointerProperties& event) const;
+
private:
typedef WTF::UnsignedWithZeroKeyHashTraits<int> UnsignedHash;
typedef struct IncomingId : public std::pair<int, int> {
@@ -109,8 +119,8 @@ class CORE_EXPORT PointerEventFactory {
bool is_active_buttons,
bool hovering);
bool IsPrimary(const int) const;
- void SetIdTypeButtons(PointerEventInit&, const WebPointerEvent&);
- void SetEventSpecificFields(PointerEventInit&, const AtomicString& type);
+ PointerEventInit* ConvertIdTypeButtonsEvent(const WebPointerEvent&);
+ void SetEventSpecificFields(PointerEventInit*, const AtomicString& type);
// Creates pointerevents like boundary and capture events from another
// pointerevent (i.e. up/down/move events).
@@ -118,6 +128,14 @@ class CORE_EXPORT PointerEventFactory {
const AtomicString&,
EventTarget*);
+ HeapVector<Member<PointerEvent>> CreateEventSequence(
+ const WebPointerEvent& web_pointer_event,
+ const PointerEventInit* pointer_event_init,
+ const Vector<WebPointerEvent>& event_list,
+ LocalDOMWindow* view);
+
+ void SetLastPosition(int pointer_id, const WebPointerProperties& event);
+
static const int kInvalidId;
int current_id_;
@@ -134,6 +152,9 @@ class CORE_EXPORT PointerEventFactory {
int id_count_[static_cast<int>(
WebPointerProperties::PointerType::kLastEntry) +
1];
+
+ HashMap<int, FloatPoint, WTF::IntHash<int>, UnsignedHash>
+ pointer_id_last_position_mapping_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event_factory_test.cc b/chromium/third_party/blink/renderer/core/events/pointer_event_factory_test.cc
index 0b4ff029145..4999a7ea67c 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event_factory_test.cc
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event_factory_test.cc
@@ -53,7 +53,8 @@ class PointerEventFactoryTest : public testing::Test {
WebInputEvent::Type type = WebInputEvent::kPointerDown,
WebPointerProperties::Button button =
WebPointerProperties::Button::kNoButton,
- wtf_size_t coalesced_event_count = 0) {
+ wtf_size_t coalesced_event_count = 0,
+ wtf_size_t predicted_event_count = 0) {
WebPointerEvent web_pointer_event;
web_pointer_event.pointer_type = pointer_type;
web_pointer_event.id = raw_id;
@@ -67,8 +68,12 @@ class PointerEventFactoryTest : public testing::Test {
for (wtf_size_t i = 0; i < coalesced_event_count; i++) {
coalesced_events.push_back(web_pointer_event);
}
+ Vector<WebPointerEvent> predicted_events;
+ for (wtf_size_t i = 0; i < predicted_event_count; i++) {
+ predicted_events.push_back(web_pointer_event);
+ }
PointerEvent* pointer_event = pointer_event_factory_.Create(
- web_pointer_event, coalesced_events, nullptr);
+ web_pointer_event, coalesced_events, predicted_events, nullptr);
EXPECT_EQ(unique_id, pointer_event->pointerId());
EXPECT_EQ(is_primary, pointer_event->isPrimary());
EXPECT_EQ(WebInputEvent::GetStaticTimeStampForTests(),
@@ -76,15 +81,32 @@ class PointerEventFactoryTest : public testing::Test {
const char* expected_pointer_type =
PointerTypeNameForWebPointPointerType(pointer_type);
EXPECT_EQ(expected_pointer_type, pointer_event->pointerType());
- EXPECT_EQ(coalesced_event_count,
- pointer_event->getCoalescedEvents().size());
- for (wtf_size_t i = 0; i < coalesced_event_count; i++) {
- EXPECT_EQ(unique_id, pointer_event->getCoalescedEvents()[i]->pointerId());
- EXPECT_EQ(is_primary,
- pointer_event->getCoalescedEvents()[i]->isPrimary());
- EXPECT_EQ(expected_pointer_type, pointer_event->pointerType());
- EXPECT_EQ(WebInputEvent::GetStaticTimeStampForTests(),
- pointer_event->PlatformTimeStamp());
+ if (type == WebInputEvent::kPointerMove) {
+ EXPECT_EQ(coalesced_event_count,
+ pointer_event->getCoalescedEvents().size());
+ EXPECT_EQ(predicted_event_count,
+ pointer_event->getPredictedEvents().size());
+ for (wtf_size_t i = 0; i < coalesced_event_count; i++) {
+ EXPECT_EQ(unique_id,
+ pointer_event->getCoalescedEvents()[i]->pointerId());
+ EXPECT_EQ(is_primary,
+ pointer_event->getCoalescedEvents()[i]->isPrimary());
+ EXPECT_EQ(expected_pointer_type, pointer_event->pointerType());
+ EXPECT_EQ(WebInputEvent::GetStaticTimeStampForTests(),
+ pointer_event->PlatformTimeStamp());
+ }
+ for (wtf_size_t i = 0; i < predicted_event_count; i++) {
+ EXPECT_EQ(unique_id,
+ pointer_event->getPredictedEvents()[i]->pointerId());
+ EXPECT_EQ(is_primary,
+ pointer_event->getPredictedEvents()[i]->isPrimary());
+ EXPECT_EQ(expected_pointer_type, pointer_event->pointerType());
+ EXPECT_EQ(WebInputEvent::GetStaticTimeStampForTests(),
+ pointer_event->PlatformTimeStamp());
+ }
+ } else {
+ EXPECT_EQ(0u, pointer_event->getCoalescedEvents().size());
+ EXPECT_EQ(0u, pointer_event->getPredictedEvents().size());
}
return pointer_event;
}
@@ -155,7 +177,7 @@ TEST_F(PointerEventFactoryTest, MousePointer) {
WebInputEvent::kLeftButtonDown);
CreateAndCheckPointerTransitionEvent(pointer_event1,
- EventTypeNames::pointerout);
+ event_type_names::kPointerout);
EXPECT_TRUE(pointer_event_factory_.IsActive(expected_mouse_id_));
EXPECT_TRUE(pointer_event_factory_.IsActiveButtonsState(expected_mouse_id_));
@@ -230,9 +252,9 @@ TEST_F(PointerEventFactoryTest, TouchPointerReleasedAndPressedAgain) {
false /* isprimary */, false /* hovering */);
CreateAndCheckPointerTransitionEvent(pointer_event1,
- EventTypeNames::pointerleave);
+ event_type_names::kPointerleave);
CreateAndCheckPointerTransitionEvent(pointer_event2,
- EventTypeNames::pointerenter);
+ event_type_names::kPointerenter);
EXPECT_TRUE(pointer_event_factory_.IsActive(mapped_id_start_));
EXPECT_TRUE(pointer_event_factory_.IsActive(mapped_id_start_ + 1));
@@ -538,6 +560,31 @@ TEST_F(PointerEventFactoryTest, CoalescedEvents) {
WebInputEvent::kPointerMove, WebPointerProperties::Button::kNoButton, 3);
}
+TEST_F(PointerEventFactoryTest, PredictedEvents) {
+ CreateAndCheckWebPointerEvent(
+ WebPointerProperties::PointerType::kMouse, 0, expected_mouse_id_,
+ true /* isprimary */, true /* hovering */, WebInputEvent::kNoModifiers,
+ WebInputEvent::kPointerMove, WebPointerProperties::Button::kNoButton,
+ 0 /* coalesced_count */, 4 /* predicted_count */);
+ CreateAndCheckWebPointerEvent(
+ WebPointerProperties::PointerType::kTouch, 0, mapped_id_start_,
+ true /* isprimary */, false /* hovering */, WebInputEvent::kNoModifiers,
+ WebInputEvent::kPointerMove, WebPointerProperties::Button::kNoButton,
+ 0 /* coalesced_count */, 3 /* predicted_count */);
+
+ // Check predicted_event_count when type != kPointerMove
+ CreateAndCheckWebPointerEvent(
+ WebPointerProperties::PointerType::kMouse, 0, expected_mouse_id_,
+ true /* isprimary */, true /* hovering */, WebInputEvent::kNoModifiers,
+ WebInputEvent::kPointerDown, WebPointerProperties::Button::kNoButton,
+ 0 /* coalesced_count */, 4 /* predicted_count */);
+ CreateAndCheckWebPointerEvent(
+ WebPointerProperties::PointerType::kTouch, 0, mapped_id_start_,
+ true /* isprimary */, false /* hovering */, WebInputEvent::kNoModifiers,
+ WebInputEvent::kPointerUp, WebPointerProperties::Button::kNoButton,
+ 0 /* coalesced_count */, 3 /* predicted_count */);
+}
+
TEST_F(PointerEventFactoryTest, PenEraserButton) {
// Send the pointerdown event when pressing the eraser button on the tablet.
PointerEvent* first_pointerdown_event = CreateAndCheckWebPointerEvent(
@@ -545,7 +592,7 @@ TEST_F(PointerEventFactoryTest, PenEraserButton) {
true /* isprimary */, false /* hovering */,
WebInputEvent::kLeftButtonDown, WebInputEvent::kPointerDown,
WebPointerProperties::Button::kLeft);
- EXPECT_EQ(EventTypeNames::pointerdown, first_pointerdown_event->type());
+ EXPECT_EQ(event_type_names::kPointerdown, first_pointerdown_event->type());
// Send the pointermove event when pressing any other button while the eraser
// button is still pressed on the tablet.
@@ -555,7 +602,7 @@ TEST_F(PointerEventFactoryTest, PenEraserButton) {
WebPointerProperties::PointerType::kEraser, 1, mapped_id_start_ + 1,
false /* isprimary */, false /* hovering */, modifiers,
WebInputEvent::kPointerDown, WebPointerProperties::Button::kRight);
- EXPECT_EQ(EventTypeNames::pointermove, second_pointerdown_event->type());
+ EXPECT_EQ(event_type_names::kPointermove, second_pointerdown_event->type());
// Send the pointermove event when releasing any other button while the
// eraser button is still pressed on the tablet.
@@ -564,14 +611,14 @@ TEST_F(PointerEventFactoryTest, PenEraserButton) {
false /* isprimary */, true /* hovering */,
WebInputEvent::kLeftButtonDown, WebInputEvent::kPointerUp,
WebPointerProperties::Button::kRight);
- EXPECT_EQ(EventTypeNames::pointermove, first_pointerup_event->type());
+ EXPECT_EQ(event_type_names::kPointermove, first_pointerup_event->type());
// Send the pointerup event when releasing the eraser button from the tablet.
PointerEvent* last_pointerup_event = CreateAndCheckWebPointerEvent(
WebPointerProperties::PointerType::kEraser, 0, mapped_id_start_,
true /* isprimary */, true /* hovering */, WebInputEvent::kNoModifiers,
WebInputEvent::kPointerUp, WebPointerProperties::Button::kLeft);
- EXPECT_EQ(EventTypeNames::pointerup, last_pointerup_event->type());
+ EXPECT_EQ(event_type_names::kPointerup, last_pointerup_event->type());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/pointer_event_init.idl b/chromium/third_party/blink/renderer/core/events/pointer_event_init.idl
index f0fac6802bd..8dafde06d06 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event_init.idl
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event_init.idl
@@ -18,4 +18,5 @@ dictionary PointerEventInit : MouseEventInit {
// https://w3c.github.io/pointerevents/extension.html#extensions-to-the-pointerevent-interface
sequence<PointerEvent> coalescedEvents = [];
+ [RuntimeEnabled=PredictedEvents]sequence<PointerEvent> predictedEvents = [];
};
diff --git a/chromium/third_party/blink/renderer/core/events/pop_state_event.cc b/chromium/third_party/blink/renderer/core/events/pop_state_event.cc
index 60806ea27ef..c7190b0c5fa 100644
--- a/chromium/third_party/blink/renderer/core/events/pop_state_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/pop_state_event.cc
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/events/pop_state_event.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/core/frame/history.h"
@@ -38,18 +38,19 @@ PopStateEvent::PopStateEvent()
PopStateEvent::PopStateEvent(ScriptState* script_state,
const AtomicString& type,
- const PopStateEventInit& initializer)
+ const PopStateEventInit* initializer)
: Event(type, initializer), history_(nullptr) {
- if (initializer.hasState()) {
+ if (initializer->hasState()) {
world_ = WrapRefCounted(&script_state->World());
- state_.Set(initializer.state().GetIsolate(), initializer.state().V8Value());
+ state_.Set(initializer->state().GetIsolate(),
+ initializer->state().V8Value());
}
}
PopStateEvent::PopStateEvent(
scoped_refptr<SerializedScriptValue> serialized_state,
History* history)
- : Event(EventTypeNames::popstate, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kPopstate, Bubbles::kNo, Cancelable::kNo),
serialized_state_(std::move(serialized_state)),
history_(history) {}
@@ -70,19 +71,20 @@ ScriptValue PopStateEvent::state(ScriptState* script_state) const {
}
PopStateEvent* PopStateEvent::Create() {
- return new PopStateEvent;
+ return MakeGarbageCollected<PopStateEvent>();
}
PopStateEvent* PopStateEvent::Create(
scoped_refptr<SerializedScriptValue> serialized_state,
History* history) {
- return new PopStateEvent(std::move(serialized_state), history);
+ return MakeGarbageCollected<PopStateEvent>(std::move(serialized_state),
+ history);
}
PopStateEvent* PopStateEvent::Create(ScriptState* script_state,
const AtomicString& type,
- const PopStateEventInit& initializer) {
- return new PopStateEvent(script_state, type, initializer);
+ const PopStateEventInit* initializer) {
+ return MakeGarbageCollected<PopStateEvent>(script_state, type, initializer);
}
void PopStateEvent::SetSerializedState(
@@ -92,7 +94,7 @@ void PopStateEvent::SetSerializedState(
}
const AtomicString& PopStateEvent::InterfaceName() const {
- return EventNames::PopStateEvent;
+ return event_interface_names::kPopStateEvent;
}
void PopStateEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/pop_state_event.h b/chromium/third_party/blink/renderer/core/events/pop_state_event.h
index 67ed13212bb..05390ec063e 100644
--- a/chromium/third_party/blink/renderer/core/events/pop_state_event.h
+++ b/chromium/third_party/blink/renderer/core/events/pop_state_event.h
@@ -42,12 +42,16 @@ class PopStateEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ PopStateEvent();
+ PopStateEvent(ScriptState*, const AtomicString&, const PopStateEventInit*);
+ PopStateEvent(scoped_refptr<SerializedScriptValue>, History*);
~PopStateEvent() override;
+
static PopStateEvent* Create();
static PopStateEvent* Create(scoped_refptr<SerializedScriptValue>, History*);
static PopStateEvent* Create(ScriptState*,
const AtomicString&,
- const PopStateEventInit&);
+ const PopStateEventInit*);
ScriptValue state(ScriptState*) const;
SerializedScriptValue* SerializedState() const {
@@ -61,10 +65,6 @@ class PopStateEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- PopStateEvent();
- PopStateEvent(ScriptState*, const AtomicString&, const PopStateEventInit&);
- PopStateEvent(scoped_refptr<SerializedScriptValue>, History*);
-
scoped_refptr<SerializedScriptValue> serialized_state_;
scoped_refptr<DOMWrapperWorld> world_;
TraceWrapperV8Reference<v8::Value> state_;
diff --git a/chromium/third_party/blink/renderer/core/events/progress_event.cc b/chromium/third_party/blink/renderer/core/events/progress_event.cc
index ea992bc9416..12ecc576227 100644
--- a/chromium/third_party/blink/renderer/core/events/progress_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/progress_event.cc
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/events/progress_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -33,11 +33,11 @@ ProgressEvent::ProgressEvent()
: length_computable_(false), loaded_(0), total_(0) {}
ProgressEvent::ProgressEvent(const AtomicString& type,
- const ProgressEventInit& initializer)
+ const ProgressEventInit* initializer)
: Event(type, initializer),
- length_computable_(initializer.lengthComputable()),
- loaded_(initializer.loaded()),
- total_(initializer.total()) {}
+ length_computable_(initializer->lengthComputable()),
+ loaded_(initializer->loaded()),
+ total_(initializer->total()) {}
ProgressEvent::ProgressEvent(const AtomicString& type,
bool length_computable,
@@ -49,7 +49,7 @@ ProgressEvent::ProgressEvent(const AtomicString& type,
total_(total) {}
const AtomicString& ProgressEvent::InterfaceName() const {
- return EventNames::ProgressEvent;
+ return event_interface_names::kProgressEvent;
}
void ProgressEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/progress_event.h b/chromium/third_party/blink/renderer/core/events/progress_event.h
index 87d33d4f424..ca1119f79ba 100644
--- a/chromium/third_party/blink/renderer/core/events/progress_event.h
+++ b/chromium/third_party/blink/renderer/core/events/progress_event.h
@@ -36,18 +36,28 @@ class CORE_EXPORT ProgressEvent : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static ProgressEvent* Create() { return new ProgressEvent; }
+ static ProgressEvent* Create() {
+ return MakeGarbageCollected<ProgressEvent>();
+ }
static ProgressEvent* Create(const AtomicString& type,
bool length_computable,
unsigned long long loaded,
unsigned long long total) {
- return new ProgressEvent(type, length_computable, loaded, total);
+ return MakeGarbageCollected<ProgressEvent>(type, length_computable, loaded,
+ total);
}
static ProgressEvent* Create(const AtomicString& type,
- const ProgressEventInit& initializer) {
- return new ProgressEvent(type, initializer);
+ const ProgressEventInit* initializer) {
+ return MakeGarbageCollected<ProgressEvent>(type, initializer);
}
+ ProgressEvent();
+ ProgressEvent(const AtomicString& type,
+ bool length_computable,
+ unsigned long long loaded,
+ unsigned long long total);
+ ProgressEvent(const AtomicString&, const ProgressEventInit*);
+
bool lengthComputable() const { return length_computable_; }
unsigned long long loaded() const { return loaded_; }
unsigned long long total() const { return total_; }
@@ -56,14 +66,6 @@ class CORE_EXPORT ProgressEvent : public Event {
void Trace(blink::Visitor*) override;
- protected:
- ProgressEvent();
- ProgressEvent(const AtomicString& type,
- bool length_computable,
- unsigned long long loaded,
- unsigned long long total);
- ProgressEvent(const AtomicString&, const ProgressEventInit&);
-
private:
bool length_computable_;
unsigned long long loaded_;
diff --git a/chromium/third_party/blink/renderer/core/events/promise_rejection_event.cc b/chromium/third_party/blink/renderer/core/events/promise_rejection_event.cc
index 90fed2e1c2b..d8cfbb6b64c 100644
--- a/chromium/third_party/blink/renderer/core/events/promise_rejection_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/promise_rejection_event.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/events/promise_rejection_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
namespace blink {
@@ -12,14 +12,14 @@ namespace blink {
PromiseRejectionEvent::PromiseRejectionEvent(
ScriptState* state,
const AtomicString& type,
- const PromiseRejectionEventInit& initializer)
+ const PromiseRejectionEventInit* initializer)
: Event(type, initializer), world_(&state->World()) {
- DCHECK(initializer.hasPromise());
- promise_.Set(initializer.promise().GetIsolate(),
- initializer.promise().V8Value());
- if (initializer.hasReason()) {
- reason_.Set(initializer.reason().GetIsolate(),
- initializer.reason().V8Value());
+ DCHECK(initializer->hasPromise());
+ promise_.Set(initializer->promise().GetIsolate(),
+ initializer->promise().V8Value());
+ if (initializer->hasReason()) {
+ reason_.Set(initializer->reason().GetIsolate(),
+ initializer->reason().V8Value());
}
}
@@ -52,7 +52,7 @@ ScriptValue PromiseRejectionEvent::reason(ScriptState* script_state) const {
}
const AtomicString& PromiseRejectionEvent::InterfaceName() const {
- return EventNames::PromiseRejectionEvent;
+ return event_interface_names::kPromiseRejectionEvent;
}
bool PromiseRejectionEvent::CanBeDispatchedInWorld(
diff --git a/chromium/third_party/blink/renderer/core/events/promise_rejection_event.h b/chromium/third_party/blink/renderer/core/events/promise_rejection_event.h
index 3a7997f222e..afcc54a8444 100644
--- a/chromium/third_party/blink/renderer/core/events/promise_rejection_event.h
+++ b/chromium/third_party/blink/renderer/core/events/promise_rejection_event.h
@@ -24,10 +24,15 @@ class CORE_EXPORT PromiseRejectionEvent final : public Event {
static PromiseRejectionEvent* Create(
ScriptState* state,
const AtomicString& type,
- const PromiseRejectionEventInit& initializer) {
- return new PromiseRejectionEvent(state, type, initializer);
+ const PromiseRejectionEventInit* initializer) {
+ return MakeGarbageCollected<PromiseRejectionEvent>(state, type,
+ initializer);
}
+ PromiseRejectionEvent(ScriptState*,
+ const AtomicString&,
+ const PromiseRejectionEventInit*);
+
ScriptValue reason(ScriptState*) const;
ScriptPromise promise(ScriptState*) const;
@@ -40,9 +45,6 @@ class CORE_EXPORT PromiseRejectionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- PromiseRejectionEvent(ScriptState*,
- const AtomicString&,
- const PromiseRejectionEventInit&);
~PromiseRejectionEvent() override;
void Dispose();
diff --git a/chromium/third_party/blink/renderer/core/events/resource_progress_event.cc b/chromium/third_party/blink/renderer/core/events/resource_progress_event.cc
index 09130862539..59599bad256 100644
--- a/chromium/third_party/blink/renderer/core/events/resource_progress_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/resource_progress_event.cc
@@ -26,7 +26,7 @@
#include "third_party/blink/renderer/core/events/resource_progress_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -42,7 +42,7 @@ const String& ResourceProgressEvent::url() const {
}
const AtomicString& ResourceProgressEvent::InterfaceName() const {
- return EventNames::ResourceProgressEvent;
+ return event_interface_names::kResourceProgressEvent;
}
void ResourceProgressEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/resource_progress_event.h b/chromium/third_party/blink/renderer/core/events/resource_progress_event.h
index ade713dbae1..f38c1a60232 100644
--- a/chromium/third_party/blink/renderer/core/events/resource_progress_event.h
+++ b/chromium/third_party/blink/renderer/core/events/resource_progress_event.h
@@ -52,23 +52,22 @@ class CORE_EXPORT ResourceProgressEvent final : public ProgressEvent {
unsigned long long loaded,
unsigned long long total,
const String& url) {
- return new ResourceProgressEvent(type, length_computable, loaded, total,
- url);
+ return MakeGarbageCollected<ResourceProgressEvent>(type, length_computable,
+ loaded, total, url);
}
- const String& url() const;
-
- const AtomicString& InterfaceName() const override;
-
- void Trace(blink::Visitor*) override;
-
- protected:
ResourceProgressEvent(const AtomicString& type,
bool length_computable,
unsigned long long loaded,
unsigned long long total,
const String& url);
+ const String& url() const;
+
+ const AtomicString& InterfaceName() const override;
+
+ void Trace(blink::Visitor*) override;
+
private:
String url_;
};
diff --git a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.cc b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.cc
index 9e50d1619fd..2893d3b4bf6 100644
--- a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.cc
@@ -36,38 +36,42 @@ const char kReport[] = "report";
} // namespace
SecurityPolicyViolationEvent::SecurityPolicyViolationEvent(
- const AtomicString& type,
- const SecurityPolicyViolationEventInit& initializer)
+ const AtomicString& type)
: Event(type, Bubbles::kYes, Cancelable::kNo, ComposedMode::kComposed),
disposition_(kContentSecurityPolicyHeaderTypeEnforce),
line_number_(0),
column_number_(0),
- status_code_(0) {
- if (initializer.hasDocumentURI())
- document_uri_ = initializer.documentURI();
- if (initializer.hasReferrer())
- referrer_ = initializer.referrer();
- if (initializer.hasBlockedURI())
- blocked_uri_ = initializer.blockedURI();
- if (initializer.hasViolatedDirective())
- violated_directive_ = initializer.violatedDirective();
- if (initializer.hasEffectiveDirective())
- effective_directive_ = initializer.effectiveDirective();
- if (initializer.hasOriginalPolicy())
- original_policy_ = initializer.originalPolicy();
- disposition_ = initializer.disposition() == kReport
+ status_code_(0) {}
+
+SecurityPolicyViolationEvent::SecurityPolicyViolationEvent(
+ const AtomicString& type,
+ const SecurityPolicyViolationEventInit* initializer)
+ : SecurityPolicyViolationEvent(type) {
+ if (initializer->hasDocumentURI())
+ document_uri_ = initializer->documentURI();
+ if (initializer->hasReferrer())
+ referrer_ = initializer->referrer();
+ if (initializer->hasBlockedURI())
+ blocked_uri_ = initializer->blockedURI();
+ if (initializer->hasViolatedDirective())
+ violated_directive_ = initializer->violatedDirective();
+ if (initializer->hasEffectiveDirective())
+ effective_directive_ = initializer->effectiveDirective();
+ if (initializer->hasOriginalPolicy())
+ original_policy_ = initializer->originalPolicy();
+ disposition_ = initializer->disposition() == kReport
? kContentSecurityPolicyHeaderTypeReport
: kContentSecurityPolicyHeaderTypeEnforce;
- if (initializer.hasSourceFile())
- source_file_ = initializer.sourceFile();
- if (initializer.hasLineNumber())
- line_number_ = initializer.lineNumber();
- if (initializer.hasColumnNumber())
- column_number_ = initializer.columnNumber();
- if (initializer.hasStatusCode())
- status_code_ = initializer.statusCode();
- if (initializer.hasSample())
- sample_ = initializer.sample();
+ if (initializer->hasSourceFile())
+ source_file_ = initializer->sourceFile();
+ if (initializer->hasLineNumber())
+ line_number_ = initializer->lineNumber();
+ if (initializer->hasColumnNumber())
+ column_number_ = initializer->columnNumber();
+ if (initializer->hasStatusCode())
+ status_code_ = initializer->statusCode();
+ if (initializer->hasSample())
+ sample_ = initializer->sample();
}
const String& SecurityPolicyViolationEvent::disposition() const {
diff --git a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.h b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.h
index 6b9f32d62ce..9940810cbca 100644
--- a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.h
+++ b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_SECURITY_POLICY_VIOLATION_EVENT_H_
#include "third_party/blink/renderer/core/dom/events/event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/security_policy_violation_event_init.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
@@ -37,12 +37,22 @@ class SecurityPolicyViolationEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ static SecurityPolicyViolationEvent* Create(const AtomicString& type) {
+ return MakeGarbageCollected<SecurityPolicyViolationEvent>(type);
+ }
+
static SecurityPolicyViolationEvent* Create(
const AtomicString& type,
- const SecurityPolicyViolationEventInit& initializer) {
- return new SecurityPolicyViolationEvent(type, initializer);
+ const SecurityPolicyViolationEventInit* initializer) {
+ return MakeGarbageCollected<SecurityPolicyViolationEvent>(type,
+ initializer);
}
+ explicit SecurityPolicyViolationEvent(const AtomicString& type);
+ SecurityPolicyViolationEvent(
+ const AtomicString& type,
+ const SecurityPolicyViolationEventInit* initializer);
+
const String& documentURI() const { return document_uri_; }
const String& referrer() const { return referrer_; }
const String& blockedURI() const { return blocked_uri_; }
@@ -57,16 +67,12 @@ class SecurityPolicyViolationEvent final : public Event {
uint16_t statusCode() const { return status_code_; }
const AtomicString& InterfaceName() const override {
- return EventNames::SecurityPolicyViolationEvent;
+ return event_interface_names::kSecurityPolicyViolationEvent;
}
void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
private:
- SecurityPolicyViolationEvent(
- const AtomicString& type,
- const SecurityPolicyViolationEventInit& initializer);
-
String document_uri_;
String referrer_;
String blocked_uri_;
diff --git a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.idl b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.idl
index c928820df93..42afd1031e9 100644
--- a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.idl
+++ b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event.idl
@@ -30,7 +30,8 @@ enum SecurityPolicyViolationEventDisposition {
};
[
- Constructor(DOMString type, optional SecurityPolicyViolationEventInit eventInitDict)
+ Constructor(DOMString type),
+ Constructor(DOMString type, SecurityPolicyViolationEventInit eventInitDict)
] interface SecurityPolicyViolationEvent : Event {
// TODO(foolip): The spec says "documentURL".
[Measure] readonly attribute DOMString documentURI;
diff --git a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event_init.idl b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event_init.idl
index 423027252c6..47d2cab0509 100644
--- a/chromium/third_party/blink/renderer/core/events/security_policy_violation_event_init.idl
+++ b/chromium/third_party/blink/renderer/core/events/security_policy_violation_event_init.idl
@@ -5,18 +5,18 @@
// https://w3c.github.io/webappsec-csp/#idl-index
dictionary SecurityPolicyViolationEventInit : EventInit {
- // TODO(foolip): The spec says "documentURL".
- DOMString documentURI;
- DOMString referrer;
- // TODO(foolip): The spec says "blockedURL".
- DOMString blockedURI;
- DOMString violatedDirective;
- DOMString effectiveDirective;
- DOMString originalPolicy;
- SecurityPolicyViolationEventDisposition disposition;
- DOMString sourceFile;
- unsigned short statusCode;
- long lineNumber;
- long columnNumber;
- DOMString sample;
+ // TODO(foolip): The spec says "documentURL".
+ required DOMString documentURI;
+ DOMString referrer;
+ // TODO(foolip): The spec says "blockedURL".
+ DOMString blockedURI;
+ required DOMString violatedDirective;
+ required DOMString effectiveDirective;
+ required DOMString originalPolicy;
+ required SecurityPolicyViolationEventDisposition disposition;
+ DOMString sourceFile;
+ required unsigned short statusCode;
+ long lineNumber;
+ long columnNumber;
+ DOMString sample;
};
diff --git a/chromium/third_party/blink/renderer/core/events/text_event.cc b/chromium/third_party/blink/renderer/core/events/text_event.cc
index 3163954f477..3c7b317ec2b 100644
--- a/chromium/third_party/blink/renderer/core/events/text_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/text_event.cc
@@ -31,31 +31,32 @@
namespace blink {
TextEvent* TextEvent::Create() {
- return new TextEvent;
+ return MakeGarbageCollected<TextEvent>();
}
TextEvent* TextEvent::Create(AbstractView* view,
const String& data,
TextEventInputType input_type) {
- return new TextEvent(view, data, input_type);
+ return MakeGarbageCollected<TextEvent>(view, data, input_type);
}
TextEvent* TextEvent::CreateForPlainTextPaste(AbstractView* view,
const String& data,
bool should_smart_replace) {
- return new TextEvent(view, data, nullptr, should_smart_replace, false);
+ return MakeGarbageCollected<TextEvent>(view, data, nullptr,
+ should_smart_replace, false);
}
TextEvent* TextEvent::CreateForFragmentPaste(AbstractView* view,
DocumentFragment* data,
bool should_smart_replace,
bool should_match_style) {
- return new TextEvent(view, "", data, should_smart_replace,
- should_match_style);
+ return MakeGarbageCollected<TextEvent>(view, "", data, should_smart_replace,
+ should_match_style);
}
TextEvent* TextEvent::CreateForDrop(AbstractView* view, const String& data) {
- return new TextEvent(view, data, kTextEventInputDrop);
+ return MakeGarbageCollected<TextEvent>(view, data, kTextEventInputDrop);
}
TextEvent::TextEvent()
@@ -66,7 +67,7 @@ TextEvent::TextEvent()
TextEvent::TextEvent(AbstractView* view,
const String& data,
TextEventInputType input_type)
- : UIEvent(EventTypeNames::textInput,
+ : UIEvent(event_type_names::kTextInput,
Bubbles::kYes,
Cancelable::kYes,
ComposedMode::kComposed,
@@ -85,7 +86,7 @@ TextEvent::TextEvent(AbstractView* view,
DocumentFragment* pasting_fragment,
bool should_smart_replace,
bool should_match_style)
- : UIEvent(EventTypeNames::textInput,
+ : UIEvent(event_type_names::kTextInput,
Bubbles::kYes,
Cancelable::kYes,
ComposedMode::kComposed,
@@ -115,7 +116,7 @@ void TextEvent::initTextEvent(const AtomicString& type,
}
const AtomicString& TextEvent::InterfaceName() const {
- return EventNames::TextEvent;
+ return event_interface_names::kTextEvent;
}
void TextEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/text_event.h b/chromium/third_party/blink/renderer/core/events/text_event.h
index 22eb37d0f28..2ba8b9445cd 100644
--- a/chromium/third_party/blink/renderer/core/events/text_event.h
+++ b/chromium/third_party/blink/renderer/core/events/text_event.h
@@ -27,6 +27,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_TEXT_EVENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_TEXT_EVENT_H_
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/text_event_input_type.h"
#include "third_party/blink/renderer/core/events/ui_event.h"
@@ -51,6 +52,15 @@ class TextEvent final : public UIEvent {
bool should_match_style);
static TextEvent* CreateForDrop(AbstractView*, const String& data);
+ TextEvent();
+ TextEvent(AbstractView*,
+ const String& data,
+ TextEventInputType = kTextEventInputKeyboard);
+ TextEvent(AbstractView*,
+ const String& data,
+ DocumentFragment*,
+ bool should_smart_replace,
+ bool should_match_style);
~TextEvent() override;
void initTextEvent(const AtomicString& type,
@@ -80,17 +90,6 @@ class TextEvent final : public UIEvent {
void Trace(blink::Visitor*) override;
private:
- TextEvent();
-
- TextEvent(AbstractView*,
- const String& data,
- TextEventInputType = kTextEventInputKeyboard);
- TextEvent(AbstractView*,
- const String& data,
- DocumentFragment*,
- bool should_smart_replace,
- bool should_match_style);
-
TextEventInputType input_type_;
String data_;
@@ -100,8 +99,8 @@ class TextEvent final : public UIEvent {
};
inline bool IsTextEvent(const Event& event) {
- return event.type() == EventTypeNames::textInput &&
- event.HasInterface(EventNames::TextEvent);
+ return event.type() == event_type_names::kTextInput &&
+ event.HasInterface(event_interface_names::kTextEvent);
}
DEFINE_TYPE_CASTS(TextEvent,
diff --git a/chromium/third_party/blink/renderer/core/events/touch_event.cc b/chromium/third_party/blink/renderer/core/events/touch_event.cc
index f9a44143ef2..f6b3f6fe33f 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/touch_event.cc
@@ -29,6 +29,7 @@
#include "third_party/blink/public/platform/web_coalesced_input_event.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
#include "third_party/blink/renderer/core/dom/events/event_path.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/intervention.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
@@ -242,17 +243,17 @@ TouchEvent::TouchEvent(const WebCoalescedInputEvent& event,
}
TouchEvent::TouchEvent(const AtomicString& type,
- const TouchEventInit& initializer)
+ const TouchEventInit* initializer)
: UIEventWithKeyState(type, initializer),
- touches_(TouchList::Create(initializer.touches())),
- target_touches_(TouchList::Create(initializer.targetTouches())),
- changed_touches_(TouchList::Create(initializer.changedTouches())),
+ touches_(TouchList::Create(initializer->touches())),
+ target_touches_(TouchList::Create(initializer->targetTouches())),
+ changed_touches_(TouchList::Create(initializer->changedTouches())),
current_touch_action_(TouchAction::kTouchActionAuto) {}
TouchEvent::~TouchEvent() = default;
const AtomicString& TouchEvent::InterfaceName() const {
- return EventNames::TouchEvent;
+ return event_interface_names::kTouchEvent;
}
bool TouchEvent::IsTouchEvent() const {
@@ -300,8 +301,8 @@ void TouchEvent::preventDefault() {
message);
}
- if ((type() == EventTypeNames::touchstart ||
- type() == EventTypeNames::touchmove) &&
+ if ((type() == event_type_names::kTouchstart ||
+ type() == event_type_names::kTouchmove) &&
view() && view()->IsLocalDOMWindow() && view()->GetFrame() &&
current_touch_action_ == TouchAction::kTouchActionAuto) {
switch (HandlingPassive()) {
diff --git a/chromium/third_party/blink/renderer/core/events/touch_event.h b/chromium/third_party/blink/renderer/core/events/touch_event.h
index 17f0daa5887..f180f0acd23 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event.h
+++ b/chromium/third_party/blink/renderer/core/events/touch_event.h
@@ -45,7 +45,7 @@ class CORE_EXPORT TouchEvent final : public UIEventWithKeyState {
// We only initialize sourceCapabilities when we create TouchEvent from
// EventHandler, null if it is from JavaScript.
- static TouchEvent* Create() { return new TouchEvent; }
+ static TouchEvent* Create() { return MakeGarbageCollected<TouchEvent>(); }
static TouchEvent* Create(const WebCoalescedInputEvent& event,
TouchList* touches,
TouchList* target_touches,
@@ -53,15 +53,26 @@ class CORE_EXPORT TouchEvent final : public UIEventWithKeyState {
const AtomicString& type,
AbstractView* view,
TouchAction current_touch_action) {
- return new TouchEvent(event, touches, target_touches, changed_touches, type,
- view, current_touch_action);
+ return MakeGarbageCollected<TouchEvent>(event, touches, target_touches,
+ changed_touches, type, view,
+ current_touch_action);
}
static TouchEvent* Create(const AtomicString& type,
- const TouchEventInit& initializer) {
- return new TouchEvent(type, initializer);
+ const TouchEventInit* initializer) {
+ return MakeGarbageCollected<TouchEvent>(type, initializer);
}
+ TouchEvent();
+ TouchEvent(const WebCoalescedInputEvent&,
+ TouchList* touches,
+ TouchList* target_touches,
+ TouchList* changed_touches,
+ const AtomicString& type,
+ AbstractView*,
+ TouchAction current_touch_action);
+ TouchEvent(const AtomicString&, const TouchEventInit*);
+
TouchList* touches() const { return touches_.Get(); }
TouchList* targetTouches() const { return target_touches_.Get(); }
TouchList* changedTouches() const { return changed_touches_.Get(); }
@@ -91,15 +102,6 @@ class CORE_EXPORT TouchEvent final : public UIEventWithKeyState {
void Trace(blink::Visitor*) override;
private:
- TouchEvent();
- TouchEvent(const WebCoalescedInputEvent&,
- TouchList* touches,
- TouchList* target_touches,
- TouchList* changed_touches,
- const AtomicString& type,
- AbstractView*,
- TouchAction current_touch_action);
- TouchEvent(const AtomicString&, const TouchEventInit&);
bool IsTouchStartOrFirstTouchMove() const;
Member<TouchList> touches_;
diff --git a/chromium/third_party/blink/renderer/core/events/touch_event_context.cc b/chromium/third_party/blink/renderer/core/events/touch_event_context.cc
index f7ff772b9be..0761d32f877 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event_context.cc
+++ b/chromium/third_party/blink/renderer/core/events/touch_event_context.cc
@@ -33,7 +33,7 @@
namespace blink {
TouchEventContext* TouchEventContext::Create() {
- return new TouchEventContext;
+ return MakeGarbageCollected<TouchEventContext>();
}
TouchEventContext::TouchEventContext()
diff --git a/chromium/third_party/blink/renderer/core/events/touch_event_context.h b/chromium/third_party/blink/renderer/core/events/touch_event_context.h
index 66c0b702a65..3288741736a 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event_context.h
+++ b/chromium/third_party/blink/renderer/core/events/touch_event_context.h
@@ -37,6 +37,9 @@ class TouchList;
class TouchEventContext : public GarbageCollected<TouchEventContext> {
public:
static TouchEventContext* Create();
+
+ TouchEventContext();
+
void HandleLocalEvents(Event&) const;
TouchList& Touches() { return *touches_; }
TouchList& TargetTouches() { return *target_touches_; }
@@ -45,8 +48,6 @@ class TouchEventContext : public GarbageCollected<TouchEventContext> {
void Trace(blink::Visitor*);
private:
- TouchEventContext();
-
Member<TouchList> touches_;
Member<TouchList> target_touches_;
Member<TouchList> changed_touches_;
diff --git a/chromium/third_party/blink/renderer/core/events/transition_event.cc b/chromium/third_party/blink/renderer/core/events/transition_event.cc
index a8fedb14598..8b3dd28ef48 100644
--- a/chromium/third_party/blink/renderer/core/events/transition_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/transition_event.cc
@@ -26,7 +26,7 @@
#include "third_party/blink/renderer/core/events/transition_event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -42,14 +42,14 @@ TransitionEvent::TransitionEvent(const AtomicString& type,
pseudo_element_(pseudo_element) {}
TransitionEvent::TransitionEvent(const AtomicString& type,
- const TransitionEventInit& initializer)
+ const TransitionEventInit* initializer)
: Event(type, initializer), elapsed_time_(0) {
- if (initializer.hasPropertyName())
- property_name_ = initializer.propertyName();
- if (initializer.hasElapsedTime())
- elapsed_time_ = initializer.elapsedTime();
- if (initializer.hasPseudoElement())
- pseudo_element_ = initializer.pseudoElement();
+ if (initializer->hasPropertyName())
+ property_name_ = initializer->propertyName();
+ if (initializer->hasElapsedTime())
+ elapsed_time_ = initializer->elapsedTime();
+ if (initializer->hasPseudoElement())
+ pseudo_element_ = initializer->pseudoElement();
}
TransitionEvent::~TransitionEvent() = default;
@@ -67,7 +67,7 @@ const String& TransitionEvent::pseudoElement() const {
}
const AtomicString& TransitionEvent::InterfaceName() const {
- return EventNames::TransitionEvent;
+ return event_interface_names::kTransitionEvent;
}
void TransitionEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/events/transition_event.h b/chromium/third_party/blink/renderer/core/events/transition_event.h
index 287d988db8d..4185a60804e 100644
--- a/chromium/third_party/blink/renderer/core/events/transition_event.h
+++ b/chromium/third_party/blink/renderer/core/events/transition_event.h
@@ -36,19 +36,28 @@ class TransitionEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static TransitionEvent* Create() { return new TransitionEvent; }
+ static TransitionEvent* Create() {
+ return MakeGarbageCollected<TransitionEvent>();
+ }
static TransitionEvent* Create(const AtomicString& type,
const String& property_name,
double elapsed_time,
const String& pseudo_element) {
- return new TransitionEvent(type, property_name, elapsed_time,
- pseudo_element);
+ return MakeGarbageCollected<TransitionEvent>(type, property_name,
+ elapsed_time, pseudo_element);
}
static TransitionEvent* Create(const AtomicString& type,
- const TransitionEventInit& initializer) {
- return new TransitionEvent(type, initializer);
+ const TransitionEventInit* initializer) {
+ return MakeGarbageCollected<TransitionEvent>(type, initializer);
}
+ TransitionEvent();
+ TransitionEvent(const AtomicString& type,
+ const String& property_name,
+ double elapsed_time,
+ const String& pseudo_element);
+ TransitionEvent(const AtomicString& type,
+ const TransitionEventInit* initializer);
~TransitionEvent() override;
const String& propertyName() const;
@@ -60,14 +69,6 @@ class TransitionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- TransitionEvent();
- TransitionEvent(const AtomicString& type,
- const String& property_name,
- double elapsed_time,
- const String& pseudo_element);
- TransitionEvent(const AtomicString& type,
- const TransitionEventInit& initializer);
-
String property_name_;
double elapsed_time_;
String pseudo_element_;
diff --git a/chromium/third_party/blink/renderer/core/events/ui_event.cc b/chromium/third_party/blink/renderer/core/events/ui_event.cc
index d08ae5a660c..fbb2d01b0b7 100644
--- a/chromium/third_party/blink/renderer/core/events/ui_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/ui_event.cc
@@ -22,11 +22,12 @@
#include "third_party/blink/renderer/core/events/ui_event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
namespace blink {
-UIEvent::UIEvent() : detail_(0), source_capabilities_(nullptr) {}
+UIEvent::UIEvent() : detail_(0) {}
UIEvent::UIEvent(const AtomicString& event_type,
Bubbles bubbles,
@@ -46,12 +47,12 @@ UIEvent::UIEvent(const AtomicString& event_type,
source_capabilities_(source_capabilities_arg) {}
UIEvent::UIEvent(const AtomicString& event_type,
- const UIEventInit& initializer,
+ const UIEventInit* initializer,
TimeTicks platform_time_stamp)
: Event(event_type, initializer, platform_time_stamp),
- view_(initializer.view()),
- detail_(initializer.detail()),
- source_capabilities_(initializer.sourceCapabilities()) {}
+ view_(initializer->view()),
+ detail_(initializer->detail()),
+ source_capabilities_(initializer->sourceCapabilities()) {}
UIEvent::~UIEvent() = default;
@@ -87,7 +88,7 @@ bool UIEvent::IsUIEvent() const {
}
const AtomicString& UIEvent::InterfaceName() const {
- return EventNames::UIEvent;
+ return event_interface_names::kUIEvent;
}
unsigned UIEvent::which() const {
diff --git a/chromium/third_party/blink/renderer/core/events/ui_event.h b/chromium/third_party/blink/renderer/core/events/ui_event.h
index e8dd2c98d58..2f0757d3966 100644
--- a/chromium/third_party/blink/renderer/core/events/ui_event.h
+++ b/chromium/third_party/blink/renderer/core/events/ui_event.h
@@ -40,11 +40,26 @@ class CORE_EXPORT UIEvent : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static UIEvent* Create() { return new UIEvent; }
+ static UIEvent* Create() { return MakeGarbageCollected<UIEvent>(); }
static UIEvent* Create(const AtomicString& type,
- const UIEventInit& initializer) {
- return new UIEvent(type, initializer);
+ const UIEventInit* initializer) {
+ return MakeGarbageCollected<UIEvent>(type, initializer);
}
+
+ UIEvent();
+ UIEvent(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ ComposedMode,
+ TimeTicks platform_time_stamp,
+ AbstractView*,
+ int detail,
+ InputDeviceCapabilities* source_capabilities);
+ UIEvent(const AtomicString&,
+ const UIEventInit*,
+ TimeTicks platform_time_stamp);
+ UIEvent(const AtomicString& type, const UIEventInit* init)
+ : UIEvent(type, init, CurrentTimeTicks()) {}
~UIEvent() override;
void initUIEvent(const AtomicString& type,
@@ -60,10 +75,10 @@ class CORE_EXPORT UIEvent : public Event {
int detail,
InputDeviceCapabilities* source_capabilities);
- AbstractView* view() const { return view_.Get(); }
+ AbstractView* view() const { return view_; }
int detail() const { return detail_; }
InputDeviceCapabilities* sourceCapabilities() const {
- return source_capabilities_.Get();
+ return source_capabilities_;
}
const AtomicString& InterfaceName() const override;
@@ -73,22 +88,6 @@ class CORE_EXPORT UIEvent : public Event {
void Trace(blink::Visitor*) override;
- protected:
- UIEvent();
- UIEvent(const AtomicString& type,
- Bubbles,
- Cancelable,
- ComposedMode,
- TimeTicks platform_time_stamp,
- AbstractView*,
- int detail,
- InputDeviceCapabilities* source_capabilities);
- UIEvent(const AtomicString&,
- const UIEventInit&,
- TimeTicks platform_time_stamp);
- UIEvent(const AtomicString& type, const UIEventInit& init)
- : UIEvent(type, init, CurrentTimeTicks()) {}
-
private:
Member<AbstractView> view_;
int detail_;
diff --git a/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.cc b/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.cc
index 29211a6696c..0ec52d6247e 100644
--- a/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.cc
+++ b/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.cc
@@ -44,28 +44,28 @@ UIEventWithKeyState::UIEventWithKeyState(
modifiers_(modifiers) {}
UIEventWithKeyState::UIEventWithKeyState(const AtomicString& type,
- const EventModifierInit& initializer,
+ const EventModifierInit* initializer,
TimeTicks platform_time_stamp)
: UIEvent(type, initializer, platform_time_stamp), modifiers_(0) {
- if (initializer.ctrlKey())
+ if (initializer->ctrlKey())
modifiers_ |= WebInputEvent::kControlKey;
- if (initializer.shiftKey())
+ if (initializer->shiftKey())
modifiers_ |= WebInputEvent::kShiftKey;
- if (initializer.altKey())
+ if (initializer->altKey())
modifiers_ |= WebInputEvent::kAltKey;
- if (initializer.metaKey())
+ if (initializer->metaKey())
modifiers_ |= WebInputEvent::kMetaKey;
- if (initializer.modifierAltGraph())
+ if (initializer->modifierAltGraph())
modifiers_ |= WebInputEvent::kAltGrKey;
- if (initializer.modifierFn())
+ if (initializer->modifierFn())
modifiers_ |= WebInputEvent::kFnKey;
- if (initializer.modifierCapsLock())
+ if (initializer->modifierCapsLock())
modifiers_ |= WebInputEvent::kCapsLockOn;
- if (initializer.modifierScrollLock())
+ if (initializer->modifierScrollLock())
modifiers_ |= WebInputEvent::kScrollLockOn;
- if (initializer.modifierNumLock())
+ if (initializer->modifierNumLock())
modifiers_ |= WebInputEvent::kNumLockOn;
- if (initializer.modifierSymbol())
+ if (initializer->modifierSymbol())
modifiers_ |= WebInputEvent::kSymbolKey;
}
@@ -84,28 +84,28 @@ void UIEventWithKeyState::DidCreateEventInIsolatedWorld(bool ctrl_key,
}
void UIEventWithKeyState::SetFromWebInputEventModifiers(
- EventModifierInit& initializer,
+ EventModifierInit* initializer,
WebInputEvent::Modifiers modifiers) {
if (modifiers & WebInputEvent::kControlKey)
- initializer.setCtrlKey(true);
+ initializer->setCtrlKey(true);
if (modifiers & WebInputEvent::kShiftKey)
- initializer.setShiftKey(true);
+ initializer->setShiftKey(true);
if (modifiers & WebInputEvent::kAltKey)
- initializer.setAltKey(true);
+ initializer->setAltKey(true);
if (modifiers & WebInputEvent::kMetaKey)
- initializer.setMetaKey(true);
+ initializer->setMetaKey(true);
if (modifiers & WebInputEvent::kAltGrKey)
- initializer.setModifierAltGraph(true);
+ initializer->setModifierAltGraph(true);
if (modifiers & WebInputEvent::kFnKey)
- initializer.setModifierFn(true);
+ initializer->setModifierFn(true);
if (modifiers & WebInputEvent::kCapsLockOn)
- initializer.setModifierCapsLock(true);
+ initializer->setModifierCapsLock(true);
if (modifiers & WebInputEvent::kScrollLockOn)
- initializer.setModifierScrollLock(true);
+ initializer->setModifierScrollLock(true);
if (modifiers & WebInputEvent::kNumLockOn)
- initializer.setModifierNumLock(true);
+ initializer->setModifierNumLock(true);
if (modifiers & WebInputEvent::kSymbolKey)
- initializer.setModifierSymbol(true);
+ initializer->setModifierSymbol(true);
}
bool UIEventWithKeyState::getModifierState(const String& key_identifier) const {
diff --git a/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.h b/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.h
index 05e38807a7b..0962cb93d77 100644
--- a/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.h
+++ b/chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.h
@@ -54,7 +54,7 @@ class CORE_EXPORT UIEventWithKeyState : public UIEvent {
bool alt_key,
bool meta_key);
- static void SetFromWebInputEventModifiers(EventModifierInit&,
+ static void SetFromWebInputEventModifiers(EventModifierInit*,
WebInputEvent::Modifiers);
bool getModifierState(const String& key_identifier) const;
@@ -75,10 +75,10 @@ class CORE_EXPORT UIEventWithKeyState : public UIEvent {
TimeTicks platform_time_stamp,
InputDeviceCapabilities* source_capabilities = nullptr);
UIEventWithKeyState(const AtomicString& type,
- const EventModifierInit& initializer,
+ const EventModifierInit* initializer,
TimeTicks platform_time_stamp);
UIEventWithKeyState(const AtomicString& type,
- const EventModifierInit& initializer)
+ const EventModifierInit* initializer)
: UIEventWithKeyState(type, initializer, CurrentTimeTicks()) {}
void InitModifiers(bool ctrl_key,
bool alt_key,
diff --git a/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.cc b/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.cc
index 38aa8e7bb37..164c61c3fa8 100644
--- a/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.cc
@@ -13,7 +13,7 @@ namespace blink {
VisualViewportResizeEvent::~VisualViewportResizeEvent() = default;
VisualViewportResizeEvent::VisualViewportResizeEvent()
- : Event(EventTypeNames::resize, Bubbles::kNo, Cancelable::kNo) {}
+ : Event(event_type_names::kResize, Bubbles::kNo, Cancelable::kNo) {}
void VisualViewportResizeEvent::DoneDispatchingEventAtCurrentTarget() {
UseCounter::Count(currentTarget()->GetExecutionContext(),
diff --git a/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.h b/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.h
index 014e503c88d..3d4c1d6f346 100644
--- a/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.h
+++ b/chromium/third_party/blink/renderer/core/events/visual_viewport_resize_event.h
@@ -11,18 +11,16 @@ namespace blink {
class VisualViewportResizeEvent final : public Event {
public:
+ VisualViewportResizeEvent();
~VisualViewportResizeEvent() override;
static VisualViewportResizeEvent* Create() {
- return new VisualViewportResizeEvent();
+ return MakeGarbageCollected<VisualViewportResizeEvent>();
}
void DoneDispatchingEventAtCurrentTarget() override;
void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
-
- private:
- VisualViewportResizeEvent();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc b/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc
index 0eeac6890a6..daecfa329d5 100644
--- a/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.cc
@@ -13,7 +13,7 @@ namespace blink {
VisualViewportScrollEvent::~VisualViewportScrollEvent() = default;
VisualViewportScrollEvent::VisualViewportScrollEvent()
- : Event(EventTypeNames::scroll, Bubbles::kNo, Cancelable::kNo) {}
+ : Event(event_type_names::kScroll, Bubbles::kNo, Cancelable::kNo) {}
void VisualViewportScrollEvent::DoneDispatchingEventAtCurrentTarget() {
UseCounter::Count(currentTarget()->GetExecutionContext(),
diff --git a/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.h b/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.h
index cec353c438b..8a9675e1325 100644
--- a/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.h
+++ b/chromium/third_party/blink/renderer/core/events/visual_viewport_scroll_event.h
@@ -11,18 +11,16 @@ namespace blink {
class VisualViewportScrollEvent final : public Event {
public:
+ VisualViewportScrollEvent();
~VisualViewportScrollEvent() override;
static VisualViewportScrollEvent* Create() {
- return new VisualViewportScrollEvent();
+ return MakeGarbageCollected<VisualViewportScrollEvent>();
}
void DoneDispatchingEventAtCurrentTarget() override;
void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
-
- private:
- VisualViewportScrollEvent();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.cc b/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.cc
index 9d9a9f5ac79..bf8c0684a18 100644
--- a/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.cc
+++ b/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.cc
@@ -177,17 +177,17 @@ WebMouseEventBuilder::WebMouseEventBuilder(const LocalFrameView* plugin_parent,
// OOPIF will prevent synthetic events being dispatched into
// other frames; but for now we allow the fallback to generate
// WebMouseEvents from synthetic events.
- if (event.type() == EventTypeNames::mousemove)
+ if (event.type() == event_type_names::kMousemove)
type_ = WebInputEvent::kMouseMove;
- else if (event.type() == EventTypeNames::mouseout)
+ else if (event.type() == event_type_names::kMouseout)
type_ = WebInputEvent::kMouseLeave;
- else if (event.type() == EventTypeNames::mouseover)
+ else if (event.type() == event_type_names::kMouseover)
type_ = WebInputEvent::kMouseEnter;
- else if (event.type() == EventTypeNames::mousedown)
+ else if (event.type() == event_type_names::kMousedown)
type_ = WebInputEvent::kMouseDown;
- else if (event.type() == EventTypeNames::mouseup)
+ else if (event.type() == event_type_names::kMouseup)
type_ = WebInputEvent::kMouseUp;
- else if (event.type() == EventTypeNames::contextmenu)
+ else if (event.type() == event_type_names::kContextmenu)
type_ = WebInputEvent::kContextMenu;
else
return; // Skip all other mouse events.
@@ -250,7 +250,8 @@ WebMouseEventBuilder::WebMouseEventBuilder(const LocalFrameView* plugin_parent,
if (!event.touches())
return;
if (event.touches()->length() != 1) {
- if (event.touches()->length() || event.type() != EventTypeNames::touchend ||
+ if (event.touches()->length() ||
+ event.type() != event_type_names::kTouchend ||
!event.changedTouches() || event.changedTouches()->length() != 1)
return;
}
@@ -261,11 +262,11 @@ WebMouseEventBuilder::WebMouseEventBuilder(const LocalFrameView* plugin_parent,
if (touch->identifier())
return;
- if (event.type() == EventTypeNames::touchstart)
+ if (event.type() == event_type_names::kTouchstart)
type_ = kMouseDown;
- else if (event.type() == EventTypeNames::touchmove)
+ else if (event.type() == event_type_names::kTouchmove)
type_ = kMouseMove;
- else if (event.type() == EventTypeNames::touchend)
+ else if (event.type() == event_type_names::kTouchend)
type_ = kMouseUp;
else
return;
@@ -304,11 +305,11 @@ WebKeyboardEventBuilder::WebKeyboardEventBuilder(const KeyboardEvent& event) {
return;
}
- if (event.type() == EventTypeNames::keydown)
+ if (event.type() == event_type_names::kKeydown)
type_ = kKeyDown;
- else if (event.type() == EventTypeNames::keyup)
+ else if (event.type() == event_type_names::kKeyup)
type_ = WebInputEvent::kKeyUp;
- else if (event.type() == EventTypeNames::keypress)
+ else if (event.type() == event_type_names::kKeypress)
type_ = WebInputEvent::kChar;
else
return; // Skip all other keyboard events.
diff --git a/chromium/third_party/blink/renderer/core/events/web_input_event_conversion_test.cc b/chromium/third_party/blink/renderer/core/events/web_input_event_conversion_test.cc
index abdd0cea592..ae1d84dfb87 100644
--- a/chromium/third_party/blink/renderer/core/events/web_input_event_conversion_test.cc
+++ b/chromium/third_party/blink/renderer/core/events/web_input_event_conversion_test.cc
@@ -57,11 +57,11 @@ namespace {
KeyboardEvent* CreateKeyboardEventWithLocation(
KeyboardEvent::KeyLocationCode location) {
- KeyboardEventInit key_event_init;
- key_event_init.setBubbles(true);
- key_event_init.setCancelable(true);
- key_event_init.setLocation(location);
- return new KeyboardEvent("keydown", key_event_init);
+ KeyboardEventInit* key_event_init = KeyboardEventInit::Create();
+ key_event_init->setBubbles(true);
+ key_event_init->setCancelable(true);
+ key_event_init->setLocation(location);
+ return MakeGarbageCollected<KeyboardEvent>("keydown", key_event_init);
}
int GetModifiersForKeyLocationCode(KeyboardEvent::KeyLocationCode location) {
@@ -72,9 +72,9 @@ int GetModifiersForKeyLocationCode(KeyboardEvent::KeyLocationCode location) {
void RegisterMockedURL(const std::string& base_url,
const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(WebString::FromUTF8(base_url),
- test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ url_test_helpers::RegisterMockedURLLoadFromBase(
+ WebString::FromUTF8(base_url), test::CoreTestDataPath(),
+ WebString::FromUTF8(file_name));
}
} // namespace
@@ -117,14 +117,15 @@ TEST(WebInputEventConversionTest, InputEventsScaling) {
const std::string file_name("fixed_layout.html");
RegisterMockedURL(base_url, file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url + file_name);
web_view->GetSettings()->SetViewportEnabled(true);
int page_width = 640;
int page_height = 480;
web_view->Resize(WebSize(page_width, page_height));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
web_view->SetPageScaleFactor(3);
@@ -148,10 +149,8 @@ TEST(WebInputEventConversionTest, InputEventsScaling) {
EXPECT_EQ(15, transformed_event.PositionInScreen().x);
EXPECT_EQ(15, transformed_event.PositionInScreen().y);
- IntPoint movement =
- FlooredIntPoint(transformed_event.MovementInRootFrame());
- EXPECT_EQ(5, movement.X());
- EXPECT_EQ(5, movement.Y());
+ EXPECT_EQ(15, transformed_event.movement_x);
+ EXPECT_EQ(15, transformed_event.movement_y);
}
{
@@ -322,8 +321,8 @@ TEST(WebInputEventConversionTest, InputEventsScaling) {
EXPECT_FLOAT_EQ(3.5f, transformed_event.PositionInWidget().y);
EXPECT_FLOAT_EQ(2.2f, transformed_event.width);
EXPECT_FLOAT_EQ(3.3f, transformed_event.height);
- EXPECT_EQ(10, transformed_event.movement_x);
- EXPECT_EQ(10, transformed_event.movement_y);
+ EXPECT_EQ(30, transformed_event.movement_x);
+ EXPECT_EQ(30, transformed_event.movement_y);
}
}
@@ -332,14 +331,15 @@ TEST(WebInputEventConversionTest, InputEventsTransform) {
const std::string file_name("fixed_layout.html");
RegisterMockedURL(base_url, file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url + file_name);
web_view->GetSettings()->SetViewportEnabled(true);
int page_width = 640;
int page_height = 480;
web_view->Resize(WebSize(page_width, page_height));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
web_view->SetPageScaleFactor(2);
web_view->MainFrameImpl()->SetInputEventsScaleForEmulation(1.5);
@@ -363,11 +363,8 @@ TEST(WebInputEventConversionTest, InputEventsTransform) {
EXPECT_FLOAT_EQ(30, position.Y());
EXPECT_EQ(90, transformed_event.PositionInScreen().x);
EXPECT_EQ(90, transformed_event.PositionInScreen().y);
-
- IntPoint movement =
- FlooredIntPoint(transformed_event.MovementInRootFrame());
- EXPECT_EQ(20, movement.X());
- EXPECT_EQ(20, movement.Y());
+ EXPECT_EQ(60, transformed_event.movement_x);
+ EXPECT_EQ(60, transformed_event.movement_y);
}
{
@@ -400,10 +397,8 @@ TEST(WebInputEventConversionTest, InputEventsTransform) {
EXPECT_EQ(90, coalescedevents[0].PositionInScreen().x);
EXPECT_EQ(90, coalescedevents[0].PositionInScreen().y);
- IntPoint movement =
- FlooredIntPoint(coalescedevents[0].MovementInRootFrame());
- EXPECT_EQ(20, movement.X());
- EXPECT_EQ(20, movement.Y());
+ EXPECT_EQ(60, coalescedevents[0].movement_x);
+ EXPECT_EQ(60, coalescedevents[0].movement_y);
position = coalescedevents[1].PositionInRootFrame();
EXPECT_FLOAT_EQ(30, position.X());
@@ -411,9 +406,8 @@ TEST(WebInputEventConversionTest, InputEventsTransform) {
EXPECT_EQ(90, coalescedevents[1].PositionInScreen().x);
EXPECT_EQ(120, coalescedevents[1].PositionInScreen().y);
- movement = FlooredIntPoint(coalescedevents[1].MovementInRootFrame());
- EXPECT_EQ(20, movement.X());
- EXPECT_EQ(10, movement.Y());
+ EXPECT_EQ(60, coalescedevents[1].movement_x);
+ EXPECT_EQ(30, coalescedevents[1].movement_y);
}
{
@@ -595,13 +589,14 @@ TEST(WebInputEventConversionTest, InputEventsConversions) {
const std::string file_name("fixed_layout.html");
RegisterMockedURL(base_url, file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url + file_name);
int page_width = 640;
int page_height = 480;
web_view->Resize(WebSize(page_width, page_height));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
LocalFrameView* view = ToLocalFrame(web_view->GetPage()->MainFrame())->View();
{
@@ -632,13 +627,14 @@ TEST(WebInputEventConversionTest, VisualViewportOffset) {
const std::string file_name("fixed_layout.html");
RegisterMockedURL(base_url, file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url + file_name);
int page_width = 640;
int page_height = 480;
web_view->Resize(WebSize(page_width, page_height));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
web_view->SetPageScaleFactor(2);
@@ -730,19 +726,20 @@ TEST(WebInputEventConversionTest, ElasticOverscroll) {
const std::string file_name("fixed_layout.html");
RegisterMockedURL(base_url, file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url + file_name);
int page_width = 640;
int page_height = 480;
web_view->Resize(WebSize(page_width, page_height));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
LocalFrameView* view = ToLocalFrame(web_view->GetPage()->MainFrame())->View();
gfx::Vector2dF elastic_overscroll(10, -20);
web_view->ApplyViewportChanges(
- {gfx::Vector2dF(), elastic_overscroll, 1.0f, 0.0f});
+ {gfx::ScrollOffset(), elastic_overscroll, 1.0f, 0.0f});
// Just elastic overscroll.
{
@@ -805,18 +802,20 @@ TEST(WebInputEventConversionTest, ElasticOverscrollWithPageReload) {
const std::string file_name("fixed_layout.html");
RegisterMockedURL(base_url, file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url + file_name);
int page_width = 640;
int page_height = 480;
web_view->Resize(WebSize(page_width, page_height));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
gfx::Vector2dF elastic_overscroll(10, -20);
web_view->ApplyViewportChanges(
- {gfx::Vector2dF(), elastic_overscroll, 1.0f, 0.0f});
- FrameTestHelpers::ReloadFrame(web_view_helper.GetWebView()->MainFrameImpl());
+ {gfx::ScrollOffset(), elastic_overscroll, 1.0f, 0.0f});
+ frame_test_helpers::ReloadFrame(
+ web_view_helper.GetWebView()->MainFrameImpl());
LocalFrameView* view = ToLocalFrame(web_view->GetPage()->MainFrame())->View();
// Just elastic overscroll.
diff --git a/chromium/third_party/blink/renderer/core/events/wheel_event.cc b/chromium/third_party/blink/renderer/core/events/wheel_event.cc
index c8c64c6ebc0..c7cb037aef2 100644
--- a/chromium/third_party/blink/renderer/core/events/wheel_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/wheel_event.cc
@@ -25,6 +25,7 @@
#include "third_party/blink/renderer/core/clipboard/data_transfer.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
@@ -44,20 +45,20 @@ long NegateIfPossible(long value) {
return -value;
}
-MouseEventInit GetMouseEventInitForWheel(const WebMouseWheelEvent& event,
- AbstractView* view) {
- MouseEventInit initializer;
- initializer.setBubbles(true);
- initializer.setCancelable(event.IsCancelable());
+MouseEventInit* GetMouseEventInitForWheel(const WebMouseWheelEvent& event,
+ AbstractView* view) {
+ MouseEventInit* initializer = MouseEventInit::Create();
+ initializer->setBubbles(true);
+ initializer->setCancelable(event.IsCancelable());
MouseEvent::SetCoordinatesFromWebPointerProperties(
event.FlattenTransform(),
view->IsLocalDOMWindow() ? ToLocalDOMWindow(view) : nullptr, initializer);
- initializer.setButton(static_cast<short>(event.button));
- initializer.setButtons(
+ initializer->setButton(static_cast<short>(event.button));
+ initializer->setButtons(
MouseEvent::WebInputEventModifiersToButtons(event.GetModifiers()));
- initializer.setView(view);
- initializer.setComposed(true);
- initializer.setDetail(event.click_count);
+ initializer->setView(view);
+ initializer->setComposed(true);
+ initializer->setDetail(event.click_count);
UIEventWithKeyState::SetFromWebInputEventModifiers(
initializer, static_cast<WebInputEvent::Modifiers>(event.GetModifiers()));
@@ -72,30 +73,30 @@ MouseEventInit GetMouseEventInitForWheel(const WebMouseWheelEvent& event,
WheelEvent* WheelEvent::Create(const WebMouseWheelEvent& event,
AbstractView* view) {
- return new WheelEvent(event, view);
+ return MakeGarbageCollected<WheelEvent>(event, view);
}
WheelEvent::WheelEvent()
: delta_x_(0), delta_y_(0), delta_z_(0), delta_mode_(kDomDeltaPixel) {}
WheelEvent::WheelEvent(const AtomicString& type,
- const WheelEventInit& initializer)
+ const WheelEventInit* initializer)
: MouseEvent(type, initializer),
- wheel_delta_(initializer.wheelDeltaX() ? initializer.wheelDeltaX()
- : -initializer.deltaX(),
- initializer.wheelDeltaY() ? initializer.wheelDeltaY()
- : -initializer.deltaY()),
- delta_x_(initializer.deltaX()
- ? initializer.deltaX()
- : NegateIfPossible(initializer.wheelDeltaX())),
- delta_y_(initializer.deltaY()
- ? initializer.deltaY()
- : NegateIfPossible(initializer.wheelDeltaY())),
- delta_z_(initializer.deltaZ()),
- delta_mode_(initializer.deltaMode()) {}
+ wheel_delta_(initializer->wheelDeltaX() ? initializer->wheelDeltaX()
+ : -initializer->deltaX(),
+ initializer->wheelDeltaY() ? initializer->wheelDeltaY()
+ : -initializer->deltaY()),
+ delta_x_(initializer->deltaX()
+ ? initializer->deltaX()
+ : NegateIfPossible(initializer->wheelDeltaX())),
+ delta_y_(initializer->deltaY()
+ ? initializer->deltaY()
+ : NegateIfPossible(initializer->wheelDeltaY())),
+ delta_z_(initializer->deltaZ()),
+ delta_mode_(initializer->deltaMode()) {}
WheelEvent::WheelEvent(const WebMouseWheelEvent& event, AbstractView* view)
- : MouseEvent(EventTypeNames::wheel,
+ : MouseEvent(event_type_names::kWheel,
GetMouseEventInitForWheel(event, view),
event.TimeStamp()),
wheel_delta_(event.wheel_ticks_x * kTickMultiplier,
@@ -107,7 +108,7 @@ WheelEvent::WheelEvent(const WebMouseWheelEvent& event, AbstractView* view)
native_event_(event) {}
const AtomicString& WheelEvent::InterfaceName() const {
- return EventNames::WheelEvent;
+ return event_interface_names::kWheelEvent;
}
bool WheelEvent::IsMouseEvent() const {
diff --git a/chromium/third_party/blink/renderer/core/events/wheel_event.h b/chromium/third_party/blink/renderer/core/events/wheel_event.h
index 2a7b4416ff6..63b491203de 100644
--- a/chromium/third_party/blink/renderer/core/events/wheel_event.h
+++ b/chromium/third_party/blink/renderer/core/events/wheel_event.h
@@ -42,16 +42,20 @@ class CORE_EXPORT WheelEvent final : public MouseEvent {
enum DeltaMode { kDomDeltaPixel = 0, kDomDeltaLine, kDomDeltaPage };
- static WheelEvent* Create() { return new WheelEvent; }
+ static WheelEvent* Create() { return MakeGarbageCollected<WheelEvent>(); }
static WheelEvent* Create(const WebMouseWheelEvent& native_event,
AbstractView*);
static WheelEvent* Create(const AtomicString& type,
- const WheelEventInit& initializer) {
- return new WheelEvent(type, initializer);
+ const WheelEventInit* initializer) {
+ return MakeGarbageCollected<WheelEvent>(type, initializer);
}
+ WheelEvent();
+ WheelEvent(const AtomicString&, const WheelEventInit*);
+ WheelEvent(const WebMouseWheelEvent&, AbstractView*);
+
double deltaX() const { return delta_x_; } // Positive when scrolling right.
double deltaY() const { return delta_y_; } // Positive when scrolling down.
double deltaZ() const { return delta_z_; }
@@ -81,10 +85,6 @@ class CORE_EXPORT WheelEvent final : public MouseEvent {
void Trace(blink::Visitor*) override;
private:
- WheelEvent();
- WheelEvent(const AtomicString&, const WheelEventInit&);
- WheelEvent(const WebMouseWheelEvent&, AbstractView*);
-
IntPoint wheel_delta_;
double delta_x_;
double delta_y_;
diff --git a/chromium/third_party/blink/renderer/core/execution_context/execution_context.cc b/chromium/third_party/blink/renderer/core/execution_context/execution_context.cc
index 8a373f52c7a..4a50fa9f0a6 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/execution_context.cc
+++ b/chromium/third_party/blink/renderer/core/execution_context/execution_context.cc
@@ -45,13 +45,14 @@
namespace blink {
-ExecutionContext::ExecutionContext()
- : circular_sequential_id_(0),
+ExecutionContext::ExecutionContext(v8::Isolate* isolate)
+ : isolate_(isolate),
+ circular_sequential_id_(0),
in_dispatch_error_event_(false),
is_context_paused_(false),
is_context_destroyed_(false),
window_interaction_tokens_(0),
- referrer_policy_(kReferrerPolicyDefault),
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
invalidator_(std::make_unique<InterfaceInvalidator>()) {}
ExecutionContext::~ExecutionContext() = default;
@@ -111,25 +112,16 @@ void ExecutionContext::PausePausableObjectIfNeeded(PausableObject* object) {
object->Pause();
}
-bool ExecutionContext::ShouldSanitizeScriptError(
- const String& source_url,
- AccessControlStatus cors_status) {
- if (cors_status == kOpaqueResource)
- return true;
- const KURL& url = CompleteURL(source_url);
- return !(GetSecurityOrigin()->CanReadContent(url) ||
- cors_status == kSharableCrossOrigin);
-}
-
-void ExecutionContext::DispatchErrorEvent(ErrorEvent* error_event,
- AccessControlStatus cors_status) {
+void ExecutionContext::DispatchErrorEvent(
+ ErrorEvent* error_event,
+ SanitizeScriptErrors sanitize_script_errors) {
if (in_dispatch_error_event_) {
pending_exceptions_.push_back(error_event);
return;
}
// First report the original exception and only then all the nested ones.
- if (!DispatchErrorEventInternal(error_event, cors_status))
+ if (!DispatchErrorEventInternal(error_event, sanitize_script_errors))
ExceptionThrown(error_event);
if (pending_exceptions_.IsEmpty())
@@ -141,13 +133,15 @@ void ExecutionContext::DispatchErrorEvent(ErrorEvent* error_event,
bool ExecutionContext::DispatchErrorEventInternal(
ErrorEvent* error_event,
- AccessControlStatus cors_status) {
+ SanitizeScriptErrors sanitize_script_errors) {
EventTarget* target = ErrorEventTarget();
if (!target)
return false;
- if (ShouldSanitizeScriptError(error_event->filename(), cors_status))
- error_event = ErrorEvent::CreateSanitizedError(error_event->World());
+ if (sanitize_script_errors == SanitizeScriptErrors::kSanitize) {
+ error_event = ErrorEvent::CreateSanitizedError(
+ ToScriptState(this, *error_event->World()));
+ }
DCHECK(!in_dispatch_error_event_);
in_dispatch_error_event_ = true;
@@ -212,13 +206,14 @@ String ExecutionContext::OutgoingReferrer() const {
FetchClientSettingsObjectSnapshot*
ExecutionContext::CreateFetchClientSettingsObjectSnapshot() {
- return new FetchClientSettingsObjectSnapshot(
- BaseURL(), GetSecurityOrigin(), GetReferrerPolicy(), OutgoingReferrer());
+ return MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ BaseURL(), GetSecurityOrigin(), GetReferrerPolicy(), OutgoingReferrer(),
+ GetHttpsState());
}
void ExecutionContext::ParseAndSetReferrerPolicy(const String& policies,
bool support_legacy_keywords) {
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
if (!SecurityPolicy::ReferrerPolicyFromHeaderValue(
policies,
@@ -243,11 +238,12 @@ void ExecutionContext::ParseAndSetReferrerPolicy(const String& policies,
SetReferrerPolicy(referrer_policy);
}
-void ExecutionContext::SetReferrerPolicy(ReferrerPolicy referrer_policy) {
+void ExecutionContext::SetReferrerPolicy(
+ network::mojom::ReferrerPolicy referrer_policy) {
// When a referrer policy has already been set, the latest value takes
// precedence.
UseCounter::Count(this, WebFeature::kSetReferrerPolicy);
- if (referrer_policy_ != kReferrerPolicyDefault)
+ if (referrer_policy_ != network::mojom::ReferrerPolicy::kDefault)
UseCounter::Count(this, WebFeature::kResetReferrerPolicy);
referrer_policy_ = referrer_policy;
diff --git a/chromium/third_party/blink/renderer/core/execution_context/execution_context.h b/chromium/third_party/blink/renderer/core/execution_context/execution_context.h
index d0f26b5979d..0d868015baf 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/execution_context.h
+++ b/chromium/third_party/blink/renderer/core/execution_context/execution_context.h
@@ -33,14 +33,14 @@
#include "base/location.h"
#include "base/macros.h"
#include "base/unguessable_token.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_notifier.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/https_state.h"
#include "third_party/blink/renderer/platform/supplementable.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "v8/include/v8.h"
namespace base {
@@ -135,6 +135,8 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
virtual bool IsContextThread() const { return true; }
+ virtual bool ShouldInstallV8Extensions() const { return false; }
+
const SecurityOrigin* GetSecurityOrigin();
SecurityOrigin* GetMutableSecurityOrigin();
@@ -167,8 +169,7 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
return false;
}
- bool ShouldSanitizeScriptError(const String& source_url, AccessControlStatus);
- void DispatchErrorEvent(ErrorEvent*, AccessControlStatus);
+ void DispatchErrorEvent(ErrorEvent*, SanitizeScriptErrors);
virtual void AddConsoleMessage(ConsoleMessage*) = 0;
virtual void ExceptionThrown(ErrorEvent*) = 0;
@@ -237,8 +238,10 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
// parsed as valid policies.
void ParseAndSetReferrerPolicy(const String& policies,
bool support_legacy_keywords = false);
- void SetReferrerPolicy(ReferrerPolicy);
- virtual ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
+ void SetReferrerPolicy(network::mojom::ReferrerPolicy);
+ virtual network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
virtual CoreProbeSink* GetProbeSink() { return nullptr; }
@@ -252,12 +255,16 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
InterfaceInvalidator* GetInterfaceInvalidator() { return invalidator_.get(); }
+ v8::Isolate* GetIsolate() const { return isolate_; }
+
protected:
- ExecutionContext();
+ explicit ExecutionContext(v8::Isolate* isolate);
~ExecutionContext() override;
private:
- bool DispatchErrorEventInternal(ErrorEvent*, AccessControlStatus);
+ v8::Isolate* const isolate_;
+
+ bool DispatchErrorEventInternal(ErrorEvent*, SanitizeScriptErrors);
unsigned circular_sequential_id_;
@@ -275,7 +282,7 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
// increment and decrement the counter.
int window_interaction_tokens_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
std::unique_ptr<InterfaceInvalidator> invalidator_;
diff --git a/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.cc b/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.cc
index e1012fb2062..7561adc5c01 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.cc
+++ b/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.cc
@@ -24,7 +24,7 @@ RemoteSecurityContext::RemoteSecurityContext() : SecurityContext() {
}
RemoteSecurityContext* RemoteSecurityContext::Create() {
- return new RemoteSecurityContext();
+ return MakeGarbageCollected<RemoteSecurityContext>();
}
void RemoteSecurityContext::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.h b/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.h
index 08f0b8e78fc..3f9b4d7c134 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.h
+++ b/chromium/third_party/blink/renderer/core/execution_context/remote_security_context.h
@@ -17,6 +17,8 @@ class CORE_EXPORT RemoteSecurityContext
USING_GARBAGE_COLLECTED_MIXIN(RemoteSecurityContext);
public:
+ RemoteSecurityContext();
+
void Trace(blink::Visitor*) override;
static RemoteSecurityContext* Create();
@@ -26,9 +28,6 @@ class CORE_EXPORT RemoteSecurityContext
// FIXME: implement
void DidUpdateSecurityOrigin() override {}
-
- private:
- RemoteSecurityContext();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/execution_context/security_context.cc b/chromium/third_party/blink/renderer/core/execution_context/security_context.cc
index 31f98c1bc50..28651e7cca5 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/security_context.cc
+++ b/chromium/third_party/blink/renderer/core/execution_context/security_context.cc
@@ -111,26 +111,70 @@ void SecurityContext::SetFeaturePolicy(
feature_policy_ = std::move(feature_policy);
}
+// Uses the parent enforcing policy; parsed_header and container_policy can
+// both contain report-only directives, which will be used to construct the
+// report-only policy for this context.
void SecurityContext::InitializeFeaturePolicy(
const ParsedFeaturePolicy& parsed_header,
const ParsedFeaturePolicy& container_policy,
const FeaturePolicy* parent_feature_policy) {
+ report_only_feature_policy_ = nullptr;
+ if (!HasCustomizedFeaturePolicy()) {
+ feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
+ nullptr, {}, security_origin_->ToUrlOrigin());
+ return;
+ }
+
feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
- parent_feature_policy, container_policy, security_origin_->ToUrlOrigin());
- feature_policy_->SetHeaderPolicy(parsed_header);
+ parent_feature_policy,
+ *DirectivesWithDisposition(mojom::FeaturePolicyDisposition::kEnforce,
+ container_policy),
+ security_origin_->ToUrlOrigin());
+ feature_policy_->SetHeaderPolicy(*DirectivesWithDisposition(
+ mojom::FeaturePolicyDisposition::kEnforce, parsed_header));
+ if (RuntimeEnabledFeatures::FeaturePolicyReportingEnabled()) {
+ report_only_feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
+ parent_feature_policy,
+ *DirectivesWithDisposition(mojom::FeaturePolicyDisposition::kReport,
+ container_policy),
+ security_origin_->ToUrlOrigin());
+ report_only_feature_policy_->SetHeaderPolicy(*DirectivesWithDisposition(
+ mojom::FeaturePolicyDisposition::kReport, parsed_header));
+ }
}
bool SecurityContext::IsFeatureEnabled(mojom::FeaturePolicyFeature feature,
- ReportOptions report_on_failure) const {
+ ReportOptions report_on_failure,
+ const String& message) const {
+ FeatureEnabledState state = GetFeatureEnabledState(feature);
+ if (state == FeatureEnabledState::kEnabled)
+ return true;
+ if (report_on_failure == ReportOptions::kReportOnFailure &&
+ RuntimeEnabledFeatures::FeaturePolicyReportingEnabled()) {
+ ReportFeaturePolicyViolation(
+ feature,
+ (state == FeatureEnabledState::kReportOnly
+ ? mojom::FeaturePolicyDisposition::kReport
+ : mojom::FeaturePolicyDisposition::kEnforce),
+ message);
+ }
+ return (state != FeatureEnabledState::kDisabled);
+}
+
+FeatureEnabledState SecurityContext::GetFeatureEnabledState(
+ mojom::FeaturePolicyFeature feature) const {
// The policy should always be initialized before checking it to ensure we
// properly inherit the parent policy.
DCHECK(feature_policy_);
- if (feature_policy_->IsFeatureEnabled(feature))
- return true;
- if (report_on_failure == ReportOptions::kReportOnFailure)
- ReportFeaturePolicyViolation(feature);
- return false;
+ if (feature_policy_->IsFeatureEnabled(feature)) {
+ if (report_only_feature_policy_ &&
+ !report_only_feature_policy_->IsFeatureEnabled(feature)) {
+ return FeatureEnabledState::kReportOnly;
+ }
+ return FeatureEnabledState::kEnabled;
+ }
+ return FeatureEnabledState::kDisabled;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/execution_context/security_context.h b/chromium/third_party/blink/renderer/core/execution_context/security_context.h
index 54bffc31a7a..fc777a3388d 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/security_context.h
+++ b/chromium/third_party/blink/renderer/core/execution_context/security_context.h
@@ -32,6 +32,7 @@
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/sandbox_flags.h"
+#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -50,8 +51,10 @@ using ParsedFeaturePolicy = std::vector<ParsedFeaturePolicyDeclaration>;
// Whether to report policy violations when checking whether a feature is
// enabled.
enum class ReportOptions { kReportOnFailure, kDoNotReport };
+enum class FeatureEnabledState { kDisabled, kReportOnly, kEnabled };
namespace mojom {
+enum class FeaturePolicyDisposition : int32_t;
enum class FeaturePolicyFeature : int32_t;
enum class IPAddressSpace : int32_t;
}
@@ -122,7 +125,15 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
return insecure_request_policy_;
}
+ void SetMixedAutoupgradeOptOut(bool opt_out) {
+ mixed_autoupgrade_opt_out_ = opt_out;
+ }
+ bool GetMixedAutoUpgradeOptOut() { return mixed_autoupgrade_opt_out_; }
+
FeaturePolicy* GetFeaturePolicy() const { return feature_policy_.get(); }
+ FeaturePolicy* GetReportOnlyFeaturePolicy() const {
+ return report_only_feature_policy_.get();
+ }
void SetFeaturePolicy(std::unique_ptr<FeaturePolicy> feature_policy);
void InitializeFeaturePolicy(const ParsedFeaturePolicy& parsed_header,
const ParsedFeaturePolicy& container_policy,
@@ -131,12 +142,17 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
// Tests whether the policy-controlled feature is enabled in this frame.
// Optionally sends a report to any registered reporting observers or
// Report-To endpoints, via ReportFeaturePolicyViolation(), if the feature is
- // disabled.
+ // disabled. The optional ConsoleMessage will be sent to the console if
+ // present, or else a default message will be used instead.
bool IsFeatureEnabled(
mojom::FeaturePolicyFeature,
- ReportOptions report_on_failure = ReportOptions::kDoNotReport) const;
- virtual void ReportFeaturePolicyViolation(mojom::FeaturePolicyFeature) const {
- }
+ ReportOptions report_on_failure = ReportOptions::kDoNotReport,
+ const String& message = g_empty_string) const;
+ FeatureEnabledState GetFeatureEnabledState(mojom::FeaturePolicyFeature) const;
+ virtual void ReportFeaturePolicyViolation(
+ mojom::FeaturePolicyFeature,
+ mojom::FeaturePolicyDisposition,
+ const String& message = g_empty_string) const {}
// Apply the sandbox flag. In addition, if the origin is not already opaque,
// the origin is updated to a newly created unique opaque origin, setting the
@@ -150,15 +166,22 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
void SetContentSecurityPolicy(ContentSecurityPolicy*);
+ // Determines whether or not the SecurityContext has a customized feature
+ // policy. If this method returns false, |feature_policy_| is reset to a
+ // default value ignoring container, header, and inherited policies.
+ virtual bool HasCustomizedFeaturePolicy() const { return true; }
+
SandboxFlags sandbox_flags_;
private:
scoped_refptr<SecurityOrigin> security_origin_;
Member<ContentSecurityPolicy> content_security_policy_;
std::unique_ptr<FeaturePolicy> feature_policy_;
+ std::unique_ptr<FeaturePolicy> report_only_feature_policy_;
mojom::IPAddressSpace address_space_;
WebInsecureRequestPolicy insecure_request_policy_;
+ bool mixed_autoupgrade_opt_out_;
InsecureNavigationsSet insecure_navigations_to_upgrade_;
bool require_safe_types_;
DISALLOW_COPY_AND_ASSIGN(SecurityContext);
diff --git a/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.cc b/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.cc
index 185b6e58d57..6a56e3f8bea 100644
--- a/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.cc
@@ -159,36 +159,13 @@ void ResetWheelAndTouchEventHandlerProperties(LocalFrame& frame) {
cc::EventListenerProperties::kNone);
}
-void SetupDocumentLoader(
- DocumentLoader* document_loader,
- std::unique_ptr<WebNavigationParams> navigation_params) {
- if (!navigation_params) {
- document_loader->GetTiming().SetNavigationStart(CurrentTimeTicks());
- return;
- }
-
- const WebNavigationTimings& navigation_timings =
- navigation_params->navigation_timings;
- document_loader->UpdateNavigationTimings(
- navigation_timings.navigation_start, navigation_timings.redirect_start,
- navigation_timings.redirect_end, navigation_timings.fetch_start,
- navigation_timings.input_start);
-
- document_loader->SetSourceLocation(navigation_params->source_location);
- if (navigation_params->is_user_activated)
- document_loader->SetUserActivated();
-
- document_loader->SetServiceWorkerNetworkProvider(
- std::move(navigation_params->service_worker_network_provider));
-}
-
} // namespace
LocalFrameClientImpl::LocalFrameClientImpl(WebLocalFrameImpl* frame)
: web_frame_(frame) {}
LocalFrameClientImpl* LocalFrameClientImpl::Create(WebLocalFrameImpl* frame) {
- return new LocalFrameClientImpl(frame);
+ return MakeGarbageCollected<LocalFrameClientImpl>(frame);
}
LocalFrameClientImpl::~LocalFrameClientImpl() = default;
@@ -442,13 +419,11 @@ void LocalFrameClientImpl::DispatchWillCommitProvisionalLoad() {
void LocalFrameClientImpl::DispatchDidStartProvisionalLoad(
DocumentLoader* loader,
- ResourceRequest& request,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) {
+ const ResourceRequest& request) {
if (web_frame_->Client()) {
WrappedResourceRequest wrapped_request(request);
web_frame_->Client()->DidStartProvisionalLoad(
- WebDocumentLoaderImpl::FromDocumentLoader(loader), wrapped_request,
- std::move(navigation_initiator_handle));
+ WebDocumentLoaderImpl::FromDocumentLoader(loader), wrapped_request);
}
}
@@ -509,45 +484,43 @@ void LocalFrameClientImpl::DispatchDidChangeThemeColor() {
web_frame_->Client()->DidChangeThemeColor();
}
-NavigationPolicy LocalFrameClientImpl::DecidePolicyForNavigation(
+void LocalFrameClientImpl::BeginNavigation(
const ResourceRequest& request,
Document* origin_document,
DocumentLoader* document_loader,
WebNavigationType type,
NavigationPolicy policy,
bool has_transient_activation,
- bool replaces_current_history_item,
+ WebFrameLoadType frame_load_type,
bool is_client_redirect,
WebTriggeringEventInfo triggering_event_info,
HTMLFormElement* form,
ContentSecurityPolicyDisposition
should_check_main_world_content_security_policy,
mojom::blink::BlobURLTokenPtr blob_url_token,
- base::TimeTicks input_start_time) {
+ base::TimeTicks input_start_time,
+ const String& href_translate,
+ mojom::blink::NavigationInitiatorPtr navigation_initiator) {
if (!web_frame_->Client())
- return kNavigationPolicyIgnore;
-
- WebDocumentLoaderImpl* web_document_loader =
- WebDocumentLoaderImpl::FromDocumentLoader(document_loader);
-
- WrappedResourceRequest wrapped_resource_request(request);
- WebLocalFrameClient::NavigationPolicyInfo navigation_info(
- wrapped_resource_request);
- navigation_info.navigation_type = type;
- navigation_info.default_policy = static_cast<WebNavigationPolicy>(policy);
- // TODO(dgozman): remove this after some Canary coverage.
- CHECK(!web_document_loader || !web_document_loader->GetExtraData());
- navigation_info.has_user_gesture = has_transient_activation;
- navigation_info.replaces_current_history_item = replaces_current_history_item;
- navigation_info.is_client_redirect = is_client_redirect;
- navigation_info.triggering_event_info = triggering_event_info;
- navigation_info.should_check_main_world_content_security_policy =
+ return;
+
+ auto navigation_info = std::make_unique<WebNavigationInfo>();
+ navigation_info->url_request = WrappedResourceRequest(request);
+ navigation_info->navigation_type = type;
+ navigation_info->navigation_policy = static_cast<WebNavigationPolicy>(policy);
+ navigation_info->has_transient_user_activation = has_transient_activation;
+ navigation_info->frame_load_type = frame_load_type;
+ navigation_info->is_client_redirect = is_client_redirect;
+ navigation_info->triggering_event_info = triggering_event_info;
+ navigation_info->should_check_main_world_content_security_policy =
should_check_main_world_content_security_policy ==
kCheckContentSecurityPolicy
? kWebContentSecurityPolicyDispositionCheck
: kWebContentSecurityPolicyDispositionDoNotCheck;
- navigation_info.blob_url_token = blob_url_token.PassInterface().PassHandle();
- navigation_info.input_start = input_start_time;
+ navigation_info->blob_url_token = blob_url_token.PassInterface().PassHandle();
+ navigation_info->input_start = input_start_time;
+ navigation_info->navigation_initiator_handle =
+ navigation_initiator.PassInterface().PassHandle();
// Can be null.
LocalFrame* local_parent_frame = GetLocalParentFrame(web_frame_);
@@ -557,20 +530,25 @@ NavigationPolicy LocalFrameClientImpl::DecidePolicyForNavigation(
// is a LocalFrame doing a back/forward navigation that has not completed.
// (If the load has completed and the parent later adds a frame with script,
// we do not want to use a history item for it.)
- navigation_info.is_history_navigation_in_new_child_frame =
+ navigation_info->is_history_navigation_in_new_child_frame =
IsBackForwardNavigationInProgress(local_parent_frame);
// TODO(nasko): How should this work with OOPIF?
// The MHTMLArchive is parsed as a whole, but can be constructed from frames
// in multiple processes. In that case, which process should parse it and how
// should the output be spread back across multiple processes?
- navigation_info.archive_status =
+ navigation_info->archive_status =
IsLoadedAsMHTMLArchive(local_parent_frame)
- ? WebLocalFrameClient::NavigationPolicyInfo::ArchiveStatus::Present
- : WebLocalFrameClient::NavigationPolicyInfo::ArchiveStatus::Absent;
+ ? WebNavigationInfo::ArchiveStatus::Present
+ : WebNavigationInfo::ArchiveStatus::Absent;
if (form)
- navigation_info.form = WebFormElement(form);
+ navigation_info->form = WebFormElement(form);
+
+ navigation_info->is_opener_navigation =
+ origin_document && origin_document->GetFrame() &&
+ origin_document->GetFrame()->Client()->Opener() ==
+ ToCoreFrame(web_frame_);
// The frame has navigated either by itself or by the action of the
// |origin_document| when it is defined. |source_location| represents the
@@ -584,20 +562,21 @@ NavigationPolicy LocalFrameClientImpl::DecidePolicyForNavigation(
? SourceLocation::Capture(origin_document)
: SourceLocation::Capture(web_frame_->GetFrame()->GetDocument());
if (source_location && !source_location->IsUnknown()) {
- navigation_info.source_location.url = source_location->Url();
- navigation_info.source_location.line_number = source_location->LineNumber();
- navigation_info.source_location.column_number =
+ navigation_info->source_location.url = source_location->Url();
+ navigation_info->source_location.line_number =
+ source_location->LineNumber();
+ navigation_info->source_location.column_number =
source_location->ColumnNumber();
}
if (WebDevToolsAgentImpl* devtools = DevToolsAgent()) {
- navigation_info.devtools_initiator_info =
+ navigation_info->devtools_initiator_info =
devtools->NavigationInitiatorInfo(web_frame_->GetFrame());
}
- WebNavigationPolicy web_policy =
- web_frame_->Client()->DecidePolicyForNavigation(navigation_info);
- return static_cast<NavigationPolicy>(web_policy);
+ navigation_info->href_translate = href_translate;
+
+ web_frame_->Client()->BeginNavigation(std::move(navigation_info));
}
void LocalFrameClientImpl::DispatchWillSendSubmitEvent(HTMLFormElement* form) {
@@ -710,6 +689,11 @@ void LocalFrameClientImpl::ReportLegacySymantecCert(const KURL& url,
web_frame_->Client()->ReportLegacySymantecCert(url, did_fail);
}
+void LocalFrameClientImpl::ReportLegacyTLSVersion(const KURL& url) {
+ if (web_frame_->Client())
+ web_frame_->Client()->ReportLegacyTLSVersion(url);
+}
+
void LocalFrameClientImpl::DidChangePerformanceTiming() {
if (web_frame_->Client())
web_frame_->Client()->DidChangePerformanceTiming();
@@ -735,6 +719,11 @@ void LocalFrameClientImpl::DidObserveNewCssPropertyUsage(int css_property,
}
}
+void LocalFrameClientImpl::DidObserveLayoutJank(double jank_fraction) {
+ if (WebLocalFrameClient* client = web_frame_->Client())
+ client->DidObserveLayoutJank(jank_fraction);
+}
+
bool LocalFrameClientImpl::ShouldTrackUseCounter(const KURL& url) {
if (web_frame_->Client())
return web_frame_->Client()->ShouldTrackUseCounter(url);
@@ -756,13 +745,16 @@ DocumentLoader* LocalFrameClientImpl::CreateDocumentLoader(
const SubstituteData& data,
ClientRedirectPolicy client_redirect_policy,
const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType load_type,
+ WebNavigationType navigation_type,
std::unique_ptr<WebNavigationParams> navigation_params,
std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) {
DCHECK(frame);
-
- WebDocumentLoaderImpl* document_loader = WebDocumentLoaderImpl::Create(
- frame, request, data, client_redirect_policy, devtools_navigation_token);
- SetupDocumentLoader(document_loader, std::move(navigation_params));
+ WebDocumentLoaderImpl* document_loader =
+ MakeGarbageCollected<WebDocumentLoaderImpl>(
+ frame, request, data, client_redirect_policy,
+ devtools_navigation_token, load_type, navigation_type,
+ std::move(navigation_params));
document_loader->SetExtraData(std::move(extra_data));
if (web_frame_->Client())
web_frame_->Client()->DidCreateDocumentLoader(document_loader);
@@ -950,7 +942,7 @@ LocalFrameClientImpl::CreateServiceWorkerProvider() {
return web_frame_->Client()->CreateServiceWorkerProvider();
}
-ContentSettingsClient& LocalFrameClientImpl::GetContentSettingsClient() {
+WebContentSettingsClient* LocalFrameClientImpl::GetContentSettingsClient() {
return web_frame_->GetContentSettingsClient();
}
@@ -1137,7 +1129,7 @@ bool LocalFrameClientImpl::IsPluginHandledExternally(
&plugin_element, resource_url, suggesed_mime_type);
}
-std::unique_ptr<WebWorkerFetchContext>
+scoped_refptr<WebWorkerFetchContext>
LocalFrameClientImpl::CreateWorkerFetchContext() {
DCHECK(web_frame_->Client());
return web_frame_->Client()->CreateWorkerFetchContext();
diff --git a/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.h b/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.h
index f0095ae5cfa..518e9b24efa 100644
--- a/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.h
@@ -53,6 +53,7 @@ class LocalFrameClientImpl final : public LocalFrameClient {
public:
static LocalFrameClientImpl* Create(WebLocalFrameImpl*);
+ explicit LocalFrameClientImpl(WebLocalFrameImpl*);
~LocalFrameClientImpl() override;
void Trace(blink::Visitor*) override;
@@ -96,10 +97,8 @@ class LocalFrameClientImpl final : public LocalFrameClient {
WebHistoryCommitType,
bool content_initiated) override;
void DispatchWillCommitProvisionalLoad() override;
- void DispatchDidStartProvisionalLoad(
- DocumentLoader*,
- ResourceRequest&,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) override;
+ void DispatchDidStartProvisionalLoad(DocumentLoader*,
+ const ResourceRequest&) override;
void DispatchDidReceiveTitle(const String&) override;
void DispatchDidChangeIcons(IconType) override;
void DispatchDidCommitLoad(HistoryItem*,
@@ -112,20 +111,22 @@ class LocalFrameClientImpl final : public LocalFrameClient {
void DispatchDidFinishLoad() override;
void DispatchDidChangeThemeColor() override;
- NavigationPolicy DecidePolicyForNavigation(
+ void BeginNavigation(
const ResourceRequest&,
Document* origin_document,
DocumentLoader*,
WebNavigationType,
NavigationPolicy,
bool has_transient_activation,
- bool should_replace_current_entry,
+ WebFrameLoadType,
bool is_client_redirect,
WebTriggeringEventInfo,
HTMLFormElement*,
ContentSecurityPolicyDisposition should_bypass_main_world_csp,
mojom::blink::BlobURLTokenPtr,
- base::TimeTicks input_start_time) override;
+ base::TimeTicks input_start_time,
+ const String& href_translate,
+ mojom::blink::NavigationInitiatorPtr) override;
void DispatchWillSendSubmitEvent(HTMLFormElement*) override;
void DidStartLoading() override;
void DidStopLoading() override;
@@ -144,10 +145,12 @@ class LocalFrameClientImpl final : public LocalFrameClient {
void DidDisplayContentWithCertificateErrors() override;
void DidRunContentWithCertificateErrors() override;
void ReportLegacySymantecCert(const KURL&, bool) override;
+ void ReportLegacyTLSVersion(const KURL&) override;
void DidChangePerformanceTiming() override;
void DidObserveLoadingBehavior(WebLoadingBehaviorFlag) override;
void DidObserveNewFeatureUsage(mojom::WebFeature) override;
void DidObserveNewCssPropertyUsage(int, bool) override;
+ void DidObserveLayoutJank(double jank_fraction) override;
bool ShouldTrackUseCounter(const KURL&) override;
void SelectorMatchChanged(const Vector<String>& added_selectors,
const Vector<String>& removed_selectors) override;
@@ -162,6 +165,8 @@ class LocalFrameClientImpl final : public LocalFrameClient {
const SubstituteData&,
ClientRedirectPolicy,
const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType,
+ WebNavigationType,
std::unique_ptr<WebNavigationParams> navigation_params,
std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override;
@@ -215,7 +220,7 @@ class LocalFrameClientImpl final : public LocalFrameClient {
std::unique_ptr<WebServiceWorkerProvider> CreateServiceWorkerProvider()
override;
- ContentSettingsClient& GetContentSettingsClient() override;
+ WebContentSettingsClient* GetContentSettingsClient() override;
SharedWorkerRepositoryClient* GetSharedWorkerRepositoryClient() override;
@@ -286,7 +291,7 @@ class LocalFrameClientImpl final : public LocalFrameClient {
const KURL&,
const String&) override;
- std::unique_ptr<WebWorkerFetchContext> CreateWorkerFetchContext() override;
+ scoped_refptr<WebWorkerFetchContext> CreateWorkerFetchContext() override;
std::unique_ptr<WebContentSettingsClient> CreateWorkerContentSettingsClient()
override;
@@ -295,8 +300,6 @@ class LocalFrameClientImpl final : public LocalFrameClient {
bool UsePrintingLayout() const override;
private:
- explicit LocalFrameClientImpl(WebLocalFrameImpl*);
-
bool IsLocalFrameClientImpl() const override { return true; }
WebDevToolsAgentImpl* DevToolsAgent();
diff --git a/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc b/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc
index a7f5fdf318e..4c2fde1f247 100644
--- a/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc
@@ -49,7 +49,7 @@ namespace blink {
namespace {
class LocalFrameMockWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
~LocalFrameMockWebFrameClient() override = default;
@@ -63,10 +63,6 @@ class LocalFrameClientImplTest : public testing::Test {
.WillByDefault(Return(WebString()));
helper_.Initialize(&web_frame_client_);
- // FIXME: http://crbug.com/363843. This needs to find a better way to
- // not create graphics layers.
- helper_.GetWebView()->GetSettings()->SetAcceleratedCompositingEnabled(
- false);
}
void TearDown() override {
@@ -94,7 +90,7 @@ class LocalFrameClientImplTest : public testing::Test {
private:
LocalFrameMockWebFrameClient web_frame_client_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
};
TEST_F(LocalFrameClientImplTest, UserAgentOverride) {
diff --git a/chromium/third_party/blink/renderer/core/exported/prerendering_test.cc b/chromium/third_party/blink/renderer/core/exported/prerendering_test.cc
index 7df33de2cbb..59aada9882e 100644
--- a/chromium/third_party/blink/renderer/core/exported/prerendering_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/prerendering_test.cc
@@ -58,7 +58,7 @@ namespace blink {
namespace {
WebURL ToWebURL(const char* url) {
- return WebURL(blink::URLTestHelpers::ToKURL(url));
+ return WebURL(blink::url_test_helpers::ToKURL(url));
}
class TestWebPrerendererClient : public WebPrerendererClient {
@@ -168,19 +168,20 @@ class PrerenderingTest : public testing::Test {
}
void Initialize(const char* base_url, const char* file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url), blink::test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
web_view_helper_.Initialize();
web_view_helper_.GetWebView()->SetPrerendererClient(&prerenderer_client_);
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- std::string(base_url) + file_name);
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(),
+ std::string(base_url) + file_name);
}
void NavigateAway() {
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- "about:blank");
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank");
}
void Close() {
@@ -227,7 +228,7 @@ class PrerenderingTest : public testing::Test {
TestPrerenderingSupport prerendering_support_;
TestWebPrerendererClient prerenderer_client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc b/chromium/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc
index 31367b5fbf7..79069a7d307 100644
--- a/chromium/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc
@@ -87,7 +87,7 @@ class SharedWorkerConnectListener final
}
void ScriptLoadFailed() override {
- worker_->DispatchEvent(*Event::CreateCancelable(EventTypeNames::error));
+ worker_->DispatchEvent(*Event::CreateCancelable(event_type_names::kError));
worker_->SetIsBeingConnected(false);
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc
index 77b4e278d8f..01f76873441 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc
@@ -40,7 +40,6 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/resource_request_blocked_reason.h"
#include "third_party/blink/public/platform/task_type.h"
-#include "third_party/blink/public/platform/web_cors.h"
#include "third_party/blink/public/platform/web_http_header_visitor.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url_error.h"
@@ -84,7 +83,7 @@ class HTTPRequestHeaderValidator : public WebHTTPHeaderVisitor {
void HTTPRequestHeaderValidator::VisitHeader(const WebString& name,
const WebString& value) {
is_safe_ = is_safe_ && IsValidHTTPToken(name) &&
- !CORS::IsForbiddenHeaderName(name) &&
+ !cors::IsForbiddenHeaderName(name) &&
IsValidHTTPHeaderValue(value);
}
@@ -95,15 +94,17 @@ void HTTPRequestHeaderValidator::VisitHeader(const WebString& name,
// It forwards its ThreadableLoaderClient notifications to a
// WebAssociatedURLLoaderClient.
class WebAssociatedURLLoaderImpl::ClientAdapter final
- : public ThreadableLoaderClient {
+ : public GarbageCollectedFinalized<ClientAdapter>,
+ public ThreadableLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(ClientAdapter);
+
public:
- static std::unique_ptr<ClientAdapter> Create(
- WebAssociatedURLLoaderImpl*,
- WebAssociatedURLLoaderClient*,
- const WebAssociatedURLLoaderOptions&,
- network::mojom::FetchRequestMode,
- network::mojom::FetchCredentialsMode,
- scoped_refptr<base::SingleThreadTaskRunner>);
+ ClientAdapter(WebAssociatedURLLoaderImpl*,
+ WebAssociatedURLLoaderClient*,
+ const WebAssociatedURLLoaderOptions&,
+ network::mojom::FetchRequestMode,
+ network::mojom::FetchCredentialsMode,
+ scoped_refptr<base::SingleThreadTaskRunner>);
// ThreadableLoaderClient
void DidSendData(unsigned long long /*bytesSent*/,
@@ -141,13 +142,6 @@ class WebAssociatedURLLoaderImpl::ClientAdapter final
}
private:
- ClientAdapter(WebAssociatedURLLoaderImpl*,
- WebAssociatedURLLoaderClient*,
- const WebAssociatedURLLoaderOptions&,
- network::mojom::FetchRequestMode,
- network::mojom::FetchCredentialsMode,
- scoped_refptr<base::SingleThreadTaskRunner>);
-
void NotifyError(TimerBase*);
WebAssociatedURLLoaderImpl* loader_;
@@ -164,19 +158,6 @@ class WebAssociatedURLLoaderImpl::ClientAdapter final
DISALLOW_COPY_AND_ASSIGN(ClientAdapter);
};
-std::unique_ptr<WebAssociatedURLLoaderImpl::ClientAdapter>
-WebAssociatedURLLoaderImpl::ClientAdapter::Create(
- WebAssociatedURLLoaderImpl* loader,
- WebAssociatedURLLoaderClient* client,
- const WebAssociatedURLLoaderOptions& options,
- network::mojom::FetchRequestMode fetch_request_mode,
- network::mojom::FetchCredentialsMode credentials_mode,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
- return base::WrapUnique(new ClientAdapter(loader, client, options,
- fetch_request_mode,
- credentials_mode, task_runner));
-}
-
WebAssociatedURLLoaderImpl::ClientAdapter::ClientAdapter(
WebAssociatedURLLoaderImpl* loader,
WebAssociatedURLLoaderClient* client,
@@ -227,20 +208,20 @@ void WebAssociatedURLLoaderImpl::ClientAdapter::DidReceiveResponse(
return;
if (options_.expose_all_response_headers ||
- (fetch_request_mode_ != network::mojom::FetchRequestMode::kCORS &&
+ (fetch_request_mode_ != network::mojom::FetchRequestMode::kCors &&
fetch_request_mode_ !=
- network::mojom::FetchRequestMode::kCORSWithForcedPreflight)) {
+ network::mojom::FetchRequestMode::kCorsWithForcedPreflight)) {
// Use the original ResourceResponse.
client_->DidReceiveResponse(WrappedResourceResponse(response));
return;
}
- WebHTTPHeaderSet exposed_headers = WebCORS::ExtractCorsExposedHeaderNamesList(
- credentials_mode_, WrappedResourceResponse(response));
+ WebHTTPHeaderSet exposed_headers =
+ cors::ExtractCorsExposedHeaderNamesList(credentials_mode_, response);
WebHTTPHeaderSet blocked_headers;
for (const auto& header : response.HttpHeaderFields()) {
if (FetchUtils::IsForbiddenResponseHeaderName(header.key) ||
- (!WebCORS::IsOnAccessControlResponseHeaderWhitelist(header.key) &&
+ (!cors::IsOnAccessControlResponseHeaderWhitelist(header.key) &&
exposed_headers.find(header.key.Ascii().data()) ==
exposed_headers.end()))
blocked_headers.insert(header.key.Ascii().data());
@@ -365,7 +346,7 @@ WebAssociatedURLLoaderImpl::WebAssociatedURLLoaderImpl(
const WebAssociatedURLLoaderOptions& options)
: client_(nullptr),
options_(options),
- observer_(new Observer(this, document)) {}
+ observer_(MakeGarbageCollected<Observer>(this, document)) {}
WebAssociatedURLLoaderImpl::~WebAssociatedURLLoaderImpl() {
Cancel();
@@ -393,7 +374,7 @@ void WebAssociatedURLLoaderImpl::LoadAsynchronously(
allow_load = validator.IsSafe();
}
}
- new_request.ToMutableResourceRequest().SetCORSPreflightPolicy(
+ new_request.ToMutableResourceRequest().SetCorsPreflightPolicy(
options_.preflight_policy);
scoped_refptr<base::SingleThreadTaskRunner> task_runner;
@@ -404,10 +385,10 @@ void WebAssociatedURLLoaderImpl::LoadAsynchronously(
task_runner = To<Document>(observer_->LifecycleContext())
->GetTaskRunner(TaskType::kInternalLoading);
} else {
- task_runner = Platform::Current()->CurrentThread()->GetTaskRunner();
+ task_runner = Thread::Current()->GetTaskRunner();
}
client_ = client;
- client_adapter_ = ClientAdapter::Create(
+ client_adapter_ = MakeGarbageCollected<ClientAdapter>(
this, client, options_, request.GetFetchRequestMode(),
request.GetFetchCredentialsMode(), std::move(task_runner));
@@ -417,7 +398,7 @@ void WebAssociatedURLLoaderImpl::LoadAsynchronously(
if (options_.grant_universal_access) {
const auto mode = new_request.GetFetchRequestMode();
- DCHECK(mode == network::mojom::FetchRequestMode::kNoCORS ||
+ DCHECK(mode == network::mojom::FetchRequestMode::kNoCors ||
mode == network::mojom::FetchRequestMode::kNavigate);
scoped_refptr<SecurityOrigin> origin =
SecurityOrigin::CreateUniqueOpaque();
@@ -435,16 +416,16 @@ void WebAssociatedURLLoaderImpl::LoadAsynchronously(
new_request.SetRequestContext(mojom::RequestContextType::INTERNAL);
} else if (context == mojom::RequestContextType::VIDEO) {
resource_loader_options.initiator_info.name =
- FetchInitiatorTypeNames::video;
+ fetch_initiator_type_names::kVideo;
} else if (context == mojom::RequestContextType::AUDIO) {
resource_loader_options.initiator_info.name =
- FetchInitiatorTypeNames::audio;
+ fetch_initiator_type_names::kAudio;
}
if (observer_) {
Document& document = To<Document>(*observer_->LifecycleContext());
- loader_ = new ThreadableLoader(document, client_adapter_.get(),
- resource_loader_options);
+ loader_ = MakeGarbageCollected<ThreadableLoader>(
+ document, client_adapter_, resource_loader_options);
loader_->Start(webcore_request);
}
}
@@ -478,7 +459,7 @@ void WebAssociatedURLLoaderImpl::CancelLoader() {
loader_->Cancel();
loader_ = nullptr;
}
- client_adapter_.reset();
+ client_adapter_ = nullptr;
}
void WebAssociatedURLLoaderImpl::SetDefersLoading(bool defers_loading) {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h b/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h
index b74551d9209..6d6f21c9955 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h
@@ -59,7 +59,7 @@ class CORE_EXPORT WebAssociatedURLLoaderImpl final
// An adapter which converts the hreadableLoaderClient method
// calls into the WebURLLoaderClient method calls.
- std::unique_ptr<ClientAdapter> client_adapter_;
+ Persistent<ClientAdapter> client_adapter_;
Persistent<ThreadableLoader> loader_;
// A ContextLifecycleObserver for cancelling |m_loader| when the Document
diff --git a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc b/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc
index 71a15084c3d..1af35bb2efd 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc
@@ -53,7 +53,7 @@
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-using blink::URLTestHelpers::ToKURL;
+using blink::url_test_helpers::ToKURL;
using blink::test::RunPendingTasks;
namespace blink {
@@ -96,7 +96,7 @@ class WebAssociatedURLLoaderTest : public testing::Test,
RegisterMockedUrl(url_root, iframe_support_files[i]);
}
- FrameTestHelpers::LoadFrame(MainFrame(), url.GetString().Utf8().data());
+ frame_test_helpers::LoadFrame(MainFrame(), url.GetString().Utf8().data());
Platform::Current()->GetURLLoaderMockFactory()->UnregisterURL(url);
}
@@ -180,7 +180,7 @@ class WebAssociatedURLLoaderTest : public testing::Test,
network::mojom::FetchCredentialsMode::kOmit);
if (EqualIgnoringASCIICase(WebString::FromUTF8(header_field), "referer")) {
request.SetHTTPReferrer(WebString::FromUTF8(header_value),
- kWebReferrerPolicyDefault);
+ network::mojom::ReferrerPolicy::kDefault);
} else {
request.SetHTTPHeaderField(WebString::FromUTF8(header_field),
WebString::FromUTF8(header_value));
@@ -215,7 +215,7 @@ class WebAssociatedURLLoaderTest : public testing::Test,
KURL url = ToKURL(id);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(
network::mojom::FetchCredentialsMode::kOmit);
@@ -250,7 +250,7 @@ class WebAssociatedURLLoaderTest : public testing::Test,
protected:
String frame_file_path_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
std::unique_ptr<WebAssociatedURLLoader> expected_loader_;
WebURLResponse actual_response_;
@@ -331,7 +331,7 @@ TEST_F(WebAssociatedURLLoaderTest, CrossOriginWithAccessControlSuccess) {
KURL url =
ToKURL("http://www.other.com/CrossOriginWithAccessControlSuccess.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
expected_response_ = WebURLResponse();
@@ -360,7 +360,7 @@ TEST_F(WebAssociatedURLLoaderTest, CrossOriginWithAccessControlFailure) {
// credentials can't be sent to a server which returns the header
// "access-control-allow-origin" with "*" as its value.
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
expected_response_ = WebURLResponse();
expected_response_.SetMIMEType("text/html");
@@ -389,7 +389,7 @@ TEST_F(WebAssociatedURLLoaderTest,
KURL url =
ToKURL("http://www.other.com/CrossOriginWithAccessControlFailure.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
expected_response_ = WebURLResponse();
@@ -495,7 +495,7 @@ TEST_F(WebAssociatedURLLoaderTest,
KURL redirect_url = ToKURL(redirect);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
expected_redirect_response_ = WebURLResponse();
@@ -538,7 +538,7 @@ TEST_F(WebAssociatedURLLoaderTest,
KURL redirect_url = ToKURL(redirect);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
// Add a CORS simple header.
request.SetHTTPHeaderField("accept", "application/json");
@@ -659,7 +659,7 @@ TEST_F(WebAssociatedURLLoaderTest, CrossOriginHeaderAllowResponseHeaders) {
KURL url =
ToKURL("http://www.other.com/CrossOriginHeaderAllowResponseHeaders.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
WebString header_name_string(WebString::FromUTF8("non-whitelisted"));
@@ -690,7 +690,7 @@ TEST_F(WebAssociatedURLLoaderTest, AccessCheckForLocalURL) {
WebURLRequest request(url);
request.SetRequestContext(mojom::RequestContextType::PLUGIN);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kNoCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kNoCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
expected_response_ = WebURLResponse();
@@ -717,7 +717,7 @@ TEST_F(WebAssociatedURLLoaderTest, BypassAccessCheckForLocalURL) {
WebURLRequest request(url);
request.SetRequestContext(mojom::RequestContextType::PLUGIN);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kNoCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kNoCors);
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
expected_response_ = WebURLResponse();
diff --git a/chromium/third_party/blink/renderer/core/exported/web_blob.cc b/chromium/third_party/blink/renderer/core/exported/web_blob.cc
index 60954fb8064..20aa17e0c8e 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_blob.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_blob.cc
@@ -53,7 +53,7 @@ WebBlob WebBlob::CreateFromFile(const WebString& path, long long size) {
}
WebBlob WebBlob::FromV8Value(v8::Local<v8::Value> value) {
- if (V8Blob::hasInstance(value, v8::Isolate::GetCurrent())) {
+ if (V8Blob::HasInstance(value, v8::Isolate::GetCurrent())) {
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
Blob* blob = V8Blob::ToImpl(object);
DCHECK(blob);
diff --git a/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc
index cb7e13172c8..7520cb45f8d 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc
@@ -55,6 +55,7 @@
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/inspector/dev_tools_emulator.h"
#include "third_party/blink/renderer/core/inspector/devtools_agent.h"
+#include "third_party/blink/renderer/core/inspector/devtools_session.h"
#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
#include "third_party/blink/renderer/core/inspector/inspector_animation_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h"
@@ -74,10 +75,8 @@
#include "third_party/blink/renderer/core/inspector/inspector_performance_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_resource_container.h"
#include "third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h"
-#include "third_party/blink/renderer/core/inspector/inspector_session.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
#include "third_party/blink/renderer/core/inspector/inspector_testing_agent.h"
-#include "third_party/blink/renderer/core/inspector/inspector_worker_agent.h"
#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
@@ -87,8 +86,6 @@
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -185,125 +182,114 @@ class ClientMessageLoopAdapter : public MainThreadDebugger::ClientMessageLoop {
ClientMessageLoopAdapter* ClientMessageLoopAdapter::instance_ = nullptr;
-InspectorSession* WebDevToolsAgentImpl::AttachSession(
- InspectorSession::Client* session_client,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state) {
- if (!sessions_.size())
- Platform::Current()->CurrentThread()->AddTaskObserver(this);
+void WebDevToolsAgentImpl::AttachSession(DevToolsSession* session,
+ bool restore) {
+ if (!network_agents_.size())
+ Thread::Current()->AddTaskObserver(this);
ClientMessageLoopAdapter::EnsureMainThreadDebuggerCreated();
MainThreadDebugger* main_thread_debugger = MainThreadDebugger::Instance();
v8::Isolate* isolate = V8PerIsolateData::MainThreadIsolate();
InspectedFrames* inspected_frames = inspected_frames_.Get();
- bool should_reattach = !reattach_session_state.is_null();
+ int context_group_id =
+ main_thread_debugger->ContextGroupId(inspected_frames->Root());
+ session->ConnectToV8(main_thread_debugger->GetV8Inspector(),
+ context_group_id);
- InspectorSession* inspector_session = new InspectorSession(
- session_client, probe_sink_.Get(), inspected_frames, 0,
- main_thread_debugger->GetV8Inspector(),
- main_thread_debugger->ContextGroupId(inspected_frames->Root()),
- std::move(reattach_session_state));
-
- InspectorDOMAgent* dom_agent = new InspectorDOMAgent(
- isolate, inspected_frames, inspector_session->V8Session());
- inspector_session->Append(dom_agent);
+ InspectorDOMAgent* dom_agent = MakeGarbageCollected<InspectorDOMAgent>(
+ isolate, inspected_frames, session->V8Session());
+ session->Append(dom_agent);
InspectorLayerTreeAgent* layer_tree_agent =
InspectorLayerTreeAgent::Create(inspected_frames, this);
- inspector_session->Append(layer_tree_agent);
+ session->Append(layer_tree_agent);
- InspectorNetworkAgent* network_agent = new InspectorNetworkAgent(
- inspected_frames, nullptr, inspector_session->V8Session());
- inspector_session->Append(network_agent);
+ InspectorNetworkAgent* network_agent =
+ MakeGarbageCollected<InspectorNetworkAgent>(inspected_frames, nullptr,
+ session->V8Session());
+ session->Append(network_agent);
InspectorCSSAgent* css_agent = InspectorCSSAgent::Create(
dom_agent, inspected_frames, network_agent,
resource_content_loader_.Get(), resource_container_.Get());
- inspector_session->Append(css_agent);
+ session->Append(css_agent);
- InspectorDOMDebuggerAgent* dom_debugger_agent = new InspectorDOMDebuggerAgent(
- isolate, dom_agent, inspector_session->V8Session());
- inspector_session->Append(dom_debugger_agent);
+ InspectorDOMDebuggerAgent* dom_debugger_agent =
+ MakeGarbageCollected<InspectorDOMDebuggerAgent>(isolate, dom_agent,
+ session->V8Session());
+ session->Append(dom_debugger_agent);
- inspector_session->Append(
+ session->Append(
InspectorDOMSnapshotAgent::Create(inspected_frames, dom_debugger_agent));
- inspector_session->Append(new InspectorAnimationAgent(
- inspected_frames, css_agent, inspector_session->V8Session()));
-
- inspector_session->Append(InspectorMemoryAgent::Create(inspected_frames));
+ session->Append(MakeGarbageCollected<InspectorAnimationAgent>(
+ inspected_frames, css_agent, session->V8Session()));
- inspector_session->Append(
- InspectorPerformanceAgent::Create(inspected_frames));
+ session->Append(InspectorMemoryAgent::Create(inspected_frames));
- inspector_session->Append(
- InspectorApplicationCacheAgent::Create(inspected_frames));
+ session->Append(InspectorPerformanceAgent::Create(inspected_frames));
- inspector_session->Append(
- new InspectorWorkerAgent(inspected_frames, nullptr));
+ session->Append(InspectorApplicationCacheAgent::Create(inspected_frames));
InspectorPageAgent* page_agent = InspectorPageAgent::Create(
inspected_frames, this, resource_content_loader_.Get(),
- inspector_session->V8Session());
- inspector_session->Append(page_agent);
+ session->V8Session());
+ session->Append(page_agent);
- inspector_session->Append(new InspectorLogAgent(
+ session->Append(MakeGarbageCollected<InspectorLogAgent>(
&inspected_frames->Root()->GetPage()->GetConsoleMessageStorage(),
- inspected_frames->Root()->GetPerformanceMonitor(),
- inspector_session->V8Session()));
+ inspected_frames->Root()->GetPerformanceMonitor(), session->V8Session()));
InspectorOverlayAgent* overlay_agent =
- new InspectorOverlayAgent(web_local_frame_impl_.Get(), inspected_frames,
- inspector_session->V8Session(), dom_agent);
- inspector_session->Append(overlay_agent);
+ MakeGarbageCollected<InspectorOverlayAgent>(
+ web_local_frame_impl_.Get(), inspected_frames, session->V8Session(),
+ dom_agent);
+ session->Append(overlay_agent);
- inspector_session->Append(
- new InspectorIOAgent(isolate, inspector_session->V8Session()));
+ session->Append(
+ MakeGarbageCollected<InspectorIOAgent>(isolate, session->V8Session()));
- inspector_session->Append(new InspectorAuditsAgent(network_agent));
+ session->Append(MakeGarbageCollected<InspectorAuditsAgent>(network_agent));
// TODO(dgozman): we should actually pass the view instead of frame, but
// during remote->local transition we cannot access mainFrameImpl() yet, so
// we have to store the frame which will become the main frame later.
- inspector_session->Append(
- new InspectorEmulationAgent(web_local_frame_impl_.Get()));
+ session->Append(MakeGarbageCollected<InspectorEmulationAgent>(
+ web_local_frame_impl_.Get()));
- inspector_session->Append(new InspectorTestingAgent(inspected_frames));
+ session->Append(new InspectorTestingAgent(inspected_frames));
- // Call session init callbacks registered from higher layers
+ // Call session init callbacks registered from higher layers.
CoreInitializer::GetInstance().InitInspectorAgentSession(
- inspector_session, include_view_agents_, dom_agent, inspected_frames,
+ session, include_view_agents_, dom_agent, inspected_frames,
web_local_frame_impl_->ViewImpl()->GetPage());
- if (should_reattach) {
- inspector_session->Restore();
- if (worker_client_)
- worker_client_->ResumeStartup();
- }
+ if (restore && worker_client_)
+ worker_client_->ResumeStartup();
if (node_to_inspect_) {
overlay_agent->Inspect(node_to_inspect_);
node_to_inspect_ = nullptr;
}
- sessions_.insert(inspector_session);
- network_agents_.insert(inspector_session, network_agent);
- page_agents_.insert(inspector_session, page_agent);
- overlay_agents_.insert(inspector_session, overlay_agent);
- return inspector_session;
+ network_agents_.insert(session, network_agent);
+ page_agents_.insert(session, page_agent);
+ overlay_agents_.insert(session, overlay_agent);
}
// static
WebDevToolsAgentImpl* WebDevToolsAgentImpl::CreateForFrame(
WebLocalFrameImpl* frame) {
- return new WebDevToolsAgentImpl(frame, IsMainFrame(frame), nullptr);
+ return MakeGarbageCollected<WebDevToolsAgentImpl>(frame, IsMainFrame(frame),
+ nullptr);
}
// static
WebDevToolsAgentImpl* WebDevToolsAgentImpl::CreateForWorker(
WebLocalFrameImpl* frame,
WorkerClient* worker_client) {
- return new WebDevToolsAgentImpl(frame, true, worker_client);
+ return MakeGarbageCollected<WebDevToolsAgentImpl>(frame, true, worker_client);
}
WebDevToolsAgentImpl::WebDevToolsAgentImpl(
@@ -315,12 +301,15 @@ WebDevToolsAgentImpl::WebDevToolsAgentImpl(
probe_sink_(web_local_frame_impl_->GetFrame()->GetProbeSink()),
resource_content_loader_(InspectorResourceContentLoader::Create(
web_local_frame_impl_->GetFrame())),
- inspected_frames_(new InspectedFrames(web_local_frame_impl_->GetFrame())),
- resource_container_(new InspectorResourceContainer(inspected_frames_)),
+ inspected_frames_(MakeGarbageCollected<InspectedFrames>(
+ web_local_frame_impl_->GetFrame())),
+ resource_container_(
+ MakeGarbageCollected<InspectorResourceContainer>(inspected_frames_)),
include_view_agents_(include_view_agents) {
DCHECK(IsMainThread());
agent_ = new DevToolsAgent(
- this, web_local_frame_impl_->GetFrame()->GetInspectorTaskRunner(),
+ this, inspected_frames_.Get(), probe_sink_.Get(),
+ web_local_frame_impl_->GetFrame()->GetInspectorTaskRunner(),
Platform::Current()->GetIOTaskRunner());
}
@@ -330,7 +319,6 @@ WebDevToolsAgentImpl::~WebDevToolsAgentImpl() {
void WebDevToolsAgentImpl::Trace(blink::Visitor* visitor) {
visitor->Trace(agent_);
- visitor->Trace(sessions_);
visitor->Trace(network_agents_);
visitor->Trace(page_agents_);
visitor->Trace(overlay_agents_);
@@ -353,16 +341,17 @@ void WebDevToolsAgentImpl::WillBeDestroyed() {
void WebDevToolsAgentImpl::BindRequest(
mojom::blink::DevToolsAgentHostAssociatedPtrInfo host_ptr_info,
mojom::blink::DevToolsAgentAssociatedRequest request) {
- agent_->BindRequest(std::move(host_ptr_info), std::move(request));
+ agent_->BindRequest(
+ std::move(host_ptr_info), std::move(request),
+ web_local_frame_impl_->GetTaskRunner(TaskType::kInternalInspector));
}
-void WebDevToolsAgentImpl::DetachSession(InspectorSession* session) {
+void WebDevToolsAgentImpl::DetachSession(DevToolsSession* session) {
network_agents_.erase(session);
page_agents_.erase(session);
overlay_agents_.erase(session);
- sessions_.erase(session);
- if (!sessions_.size())
- Platform::Current()->CurrentThread()->RemoveTaskObserver(this);
+ if (!network_agents_.size())
+ Thread::Current()->RemoveTaskObserver(this);
}
void WebDevToolsAgentImpl::InspectElement(const WebPoint& point_in_local_root) {
@@ -408,11 +397,13 @@ void WebDevToolsAgentImpl::InspectElement(const WebPoint& point_in_local_root) {
}
}
+void WebDevToolsAgentImpl::DebuggerTaskStarted() {}
+
+void WebDevToolsAgentImpl::DebuggerTaskFinished() {}
+
void WebDevToolsAgentImpl::DidCommitLoadForLocalFrame(LocalFrame* frame) {
resource_container_->DidCommitLoadForLocalFrame(frame);
resource_content_loader_->DidCommitLoadForLocalFrame(frame);
- for (auto& session : sessions_)
- session->DidCommitLoadForLocalFrame(frame);
}
bool WebDevToolsAgentImpl::ScreencastEnabled() {
@@ -474,14 +465,16 @@ void WebDevToolsAgentImpl::FlushProtocolNotifications() {
agent_->FlushProtocolNotifications();
}
-void WebDevToolsAgentImpl::WillProcessTask() {
- if (sessions_.IsEmpty())
+void WebDevToolsAgentImpl::WillProcessTask(
+ const base::PendingTask& pending_task) {
+ if (network_agents_.IsEmpty())
return;
ThreadDebugger::IdleFinished(V8PerIsolateData::MainThreadIsolate());
}
-void WebDevToolsAgentImpl::DidProcessTask() {
- if (sessions_.IsEmpty())
+void WebDevToolsAgentImpl::DidProcessTask(
+ const base::PendingTask& pending_task) {
+ if (network_agents_.IsEmpty())
return;
ThreadDebugger::IdleStarted(V8PerIsolateData::MainThreadIsolate());
FlushProtocolNotifications();
diff --git a/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h b/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h
index 45eae977567..2d963761a90 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h
@@ -70,8 +70,13 @@ class CORE_EXPORT WebDevToolsAgentImpl final
static WebDevToolsAgentImpl* CreateForFrame(WebLocalFrameImpl*);
static WebDevToolsAgentImpl* CreateForWorker(WebLocalFrameImpl*,
WorkerClient*);
+
+ WebDevToolsAgentImpl(WebLocalFrameImpl*,
+ bool include_view_agents,
+ WorkerClient*);
~WebDevToolsAgentImpl() override;
virtual void Trace(blink::Visitor*);
+ DevToolsAgent* GetDevToolsAgent() const { return agent_.Get(); }
void WillBeDestroyed();
void FlushProtocolNotifications();
@@ -90,16 +95,12 @@ class CORE_EXPORT WebDevToolsAgentImpl final
private:
friend class ClientMessageLoopAdapter;
- WebDevToolsAgentImpl(WebLocalFrameImpl*,
- bool include_view_agents,
- WorkerClient*);
-
// DevToolsAgent::Client implementation.
- InspectorSession* AttachSession(
- InspectorSession::Client*,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state) override;
- void DetachSession(InspectorSession*) override;
+ void AttachSession(DevToolsSession*, bool restore) override;
+ void DetachSession(DevToolsSession*) override;
void InspectElement(const WebPoint& point_in_local_root) override;
+ void DebuggerTaskStarted() override;
+ void DebuggerTaskFinished() override;
// InspectorPageAgent::Client implementation.
void PageLayoutInvalidated(bool resized) override;
@@ -108,16 +109,14 @@ class CORE_EXPORT WebDevToolsAgentImpl final
bool IsInspectorLayer(GraphicsLayer*) override;
// Thread::TaskObserver implementation.
- void WillProcessTask() override;
- void DidProcessTask() override;
+ void WillProcessTask(const base::PendingTask&) override;
+ void DidProcessTask(const base::PendingTask&) override;
Member<DevToolsAgent> agent_;
- HeapHashSet<Member<InspectorSession>> sessions_;
- HeapHashMap<Member<InspectorSession>, Member<InspectorNetworkAgent>>
+ HeapHashMap<Member<DevToolsSession>, Member<InspectorNetworkAgent>>
network_agents_;
- HeapHashMap<Member<InspectorSession>, Member<InspectorPageAgent>>
- page_agents_;
- HeapHashMap<Member<InspectorSession>, Member<InspectorOverlayAgent>>
+ HeapHashMap<Member<DevToolsSession>, Member<InspectorPageAgent>> page_agents_;
+ HeapHashMap<Member<DevToolsSession>, Member<InspectorOverlayAgent>>
overlay_agents_;
WorkerClient* worker_client_;
Member<WebLocalFrameImpl> web_local_frame_impl_;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_document.cc b/chromium/third_party/blink/renderer/core/exported/web_document.cc
index ccf99e79f4a..1c09baa37b6 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_document.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_document.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/public/web/web_document.h"
#include "base/memory/scoped_refptr.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/platform/web_distillability.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/web/web_dom_event.h"
@@ -231,9 +232,8 @@ void WebDocument::WatchCSSSelectors(const WebVector<WebString>& web_selectors) {
CSSSelectorWatch::From(*document).WatchCSSSelectors(selectors);
}
-WebReferrerPolicy WebDocument::GetReferrerPolicy() const {
- return static_cast<WebReferrerPolicy>(
- ConstUnwrap<Document>()->GetReferrerPolicy());
+network::mojom::ReferrerPolicy WebDocument::GetReferrerPolicy() const {
+ return ConstUnwrap<Document>()->GetReferrerPolicy();
}
WebString WebDocument::OutgoingReferrer() {
@@ -269,7 +269,7 @@ bool WebDocument::ManifestUseCredentials() const {
if (!link_element)
return false;
return EqualIgnoringASCIICase(
- link_element->FastGetAttribute(HTMLNames::crossoriginAttr),
+ link_element->FastGetAttribute(html_names::kCrossoriginAttr),
"use-credentials");
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.cc
index ffb8a3e72f2..f7dc115595f 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.cc
@@ -48,18 +48,6 @@
namespace blink {
-WebDocumentLoaderImpl* WebDocumentLoaderImpl::Create(
- LocalFrame* frame,
- const ResourceRequest& request,
- const SubstituteData& data,
- ClientRedirectPolicy client_redirect_policy,
- const base::UnguessableToken& devtools_navigation_token) {
- DCHECK(frame);
-
- return new WebDocumentLoaderImpl(frame, request, data, client_redirect_policy,
- devtools_navigation_token);
-}
-
const WebURLRequest& WebDocumentLoaderImpl::OriginalRequest() const {
return original_request_wrapper_;
}
@@ -114,12 +102,18 @@ WebDocumentLoaderImpl::WebDocumentLoaderImpl(
const ResourceRequest& request,
const SubstituteData& data,
ClientRedirectPolicy client_redirect_policy,
- const base::UnguessableToken& devtools_navigation_token)
+ const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType load_type,
+ WebNavigationType navigation_type,
+ std::unique_ptr<WebNavigationParams> navigation_params)
: DocumentLoader(frame,
request,
data,
client_redirect_policy,
- devtools_navigation_token),
+ devtools_navigation_token,
+ load_type,
+ navigation_type,
+ std::move(navigation_params)),
original_request_wrapper_(DocumentLoader::OriginalRequest()),
request_wrapper_(DocumentLoader::GetRequest()),
response_wrapper_(DocumentLoader::GetResponse()) {}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.h b/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.h
index 229788d5896..d83f96afc82 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.h
@@ -49,12 +49,14 @@ namespace blink {
class CORE_EXPORT WebDocumentLoaderImpl final : public DocumentLoader,
public WebDocumentLoader {
public:
- static WebDocumentLoaderImpl* Create(
- LocalFrame*,
- const ResourceRequest&,
- const SubstituteData&,
- ClientRedirectPolicy,
- const base::UnguessableToken& devtools_navigation_token);
+ WebDocumentLoaderImpl(LocalFrame*,
+ const ResourceRequest&,
+ const SubstituteData&,
+ ClientRedirectPolicy,
+ const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType load_type,
+ WebNavigationType navigation_type,
+ std::unique_ptr<WebNavigationParams> navigation_params);
static WebDocumentLoaderImpl* FromDocumentLoader(DocumentLoader* loader) {
return static_cast<WebDocumentLoaderImpl*>(loader);
@@ -87,12 +89,6 @@ class CORE_EXPORT WebDocumentLoaderImpl final : public DocumentLoader,
void Trace(blink::Visitor*) override;
private:
- WebDocumentLoaderImpl(
- LocalFrame*,
- const ResourceRequest&,
- const SubstituteData&,
- ClientRedirectPolicy,
- const base::UnguessableToken& devtools_navigation_token);
~WebDocumentLoaderImpl() override;
void DetachFromFrame(bool flush_microtask_queue) override;
String DebugName() const override { return "WebDocumentLoaderImpl"; }
diff --git a/chromium/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc b/chromium/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc
index 81e4f8508e4..5ff778ae876 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc
@@ -63,8 +63,6 @@ class TestDocumentSubresourceFilter : public WebDocumentSubresourceFilter {
return queried_subresource_paths_;
}
- bool GetIsAssociatedWithAdSubframe() const override { return false; }
-
private:
// Using STL types for compatibility with gtest/gmock.
std::vector<std::string> queried_subresource_paths_;
@@ -73,12 +71,10 @@ class TestDocumentSubresourceFilter : public WebDocumentSubresourceFilter {
};
class SubresourceFilteringWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
- void DidStartProvisionalLoad(
- WebDocumentLoader* data_source,
- WebURLRequest& request,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) override {
+ void DidStartProvisionalLoad(WebDocumentLoader* data_source,
+ WebURLRequest& request) override {
// Normally, the filter should be set when the load is committed. For
// the sake of this test, however, inject it earlier to verify that it
// is not consulted for the main resource load.
@@ -114,7 +110,8 @@ class WebDocumentSubresourceFilterTest : public testing::Test {
void LoadDocument(TestDocumentSubresourceFilter::LoadPolicy policy) {
client_.SetLoadPolicyFromNextLoad(policy);
- FrameTestHelpers::LoadFrame(MainFrame(), BaseURL() + "foo_with_image.html");
+ frame_test_helpers::LoadFrame(MainFrame(),
+ BaseURL() + "foo_with_image.html");
}
void ExpectSubresourceWasLoaded(bool loaded) {
@@ -131,7 +128,7 @@ class WebDocumentSubresourceFilterTest : public testing::Test {
private:
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -144,7 +141,7 @@ class WebDocumentSubresourceFilterTest : public testing::Test {
}
SubresourceFilteringWebFrameClient client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
std::string base_url_;
};
diff --git a/chromium/third_party/blink/renderer/core/exported/web_document_test.cc b/chromium/third_party/blink/renderer/core/exported/web_document_test.cc
index d6d3508f3e0..0f691ce334c 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_document_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_document_test.cc
@@ -11,8 +11,8 @@
#include "third_party/blink/public/common/origin_trials/origin_trial_policy.h"
#include "third_party/blink/public/common/origin_trials/trial_token_validator.h"
#include "third_party/blink/public/web/web_origin_trials.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -31,8 +31,8 @@
namespace blink {
-using blink::FrameTestHelpers::WebViewHelper;
-using blink::URLTestHelpers::ToKURL;
+using blink::frame_test_helpers::WebViewHelper;
+using blink::url_test_helpers::ToKURL;
const char kDefaultOrigin[] = "https://example.test/";
const char kManifestDummyFilePath[] = "manifest-dummy.html";
@@ -51,13 +51,13 @@ class WebDocumentTest : public testing::Test {
};
void WebDocumentTest::SetUpTestCase() {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(std::string(kDefaultOrigin) + kManifestDummyFilePath),
test::CoreTestDataPath(kManifestDummyFilePath));
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(std::string(kDefaultOrigin) + kNoOriginTrialDummyFilePath),
test::CoreTestDataPath(kNoOriginTrialDummyFilePath));
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(std::string(kDefaultOrigin) + kOriginTrialDummyFilePath),
test::CoreTestDataPath(kOriginTrialDummyFilePath));
}
@@ -143,12 +143,12 @@ TEST_F(WebDocumentTest, ManifestURL) {
ASSERT_EQ(link_manifest->Href(), static_cast<KURL>(web_doc.ManifestURL()));
// Set to some absolute url.
- link_manifest->setAttribute(HTMLNames::hrefAttr,
+ link_manifest->setAttribute(html_names::kHrefAttr,
"http://example.com/manifest.json");
ASSERT_EQ(link_manifest->Href(), static_cast<KURL>(web_doc.ManifestURL()));
// Set to some relative url.
- link_manifest->setAttribute(HTMLNames::hrefAttr, "static/manifest.json");
+ link_manifest->setAttribute(html_names::kHrefAttr, "static/manifest.json");
ASSERT_EQ(link_manifest->Href(), static_cast<KURL>(web_doc.ManifestURL()));
}
@@ -160,19 +160,19 @@ TEST_F(WebDocumentTest, ManifestUseCredentials) {
HTMLLinkElement* link_manifest = document->LinkManifest();
// No crossorigin attribute was set so credentials shouldn't be used.
- ASSERT_FALSE(link_manifest->FastHasAttribute(HTMLNames::crossoriginAttr));
+ ASSERT_FALSE(link_manifest->FastHasAttribute(html_names::kCrossoriginAttr));
ASSERT_FALSE(web_doc.ManifestUseCredentials());
// Crossorigin set to a random string shouldn't trigger using credentials.
- link_manifest->setAttribute(HTMLNames::crossoriginAttr, "foobar");
+ link_manifest->setAttribute(html_names::kCrossoriginAttr, "foobar");
ASSERT_FALSE(web_doc.ManifestUseCredentials());
// Crossorigin set to 'anonymous' shouldn't trigger using credentials.
- link_manifest->setAttribute(HTMLNames::crossoriginAttr, "anonymous");
+ link_manifest->setAttribute(html_names::kCrossoriginAttr, "anonymous");
ASSERT_FALSE(web_doc.ManifestUseCredentials());
// Crossorigin set to 'use-credentials' should trigger using credentials.
- link_manifest->setAttribute(HTMLNames::crossoriginAttr, "use-credentials");
+ link_manifest->setAttribute(html_names::kCrossoriginAttr, "use-credentials");
ASSERT_TRUE(web_doc.ManifestUseCredentials());
}
@@ -272,7 +272,7 @@ KURL ToOriginB(const char* file) {
}
void RegisterMockedURLLoad(const KURL& url, const char* path) {
- URLTestHelpers::RegisterMockedURLLoad(url, test::CoreTestDataPath(path));
+ url_test_helpers::RegisterMockedURLLoad(url, test::CoreTestDataPath(path));
}
} // anonymous namespace
diff --git a/chromium/third_party/blink/renderer/core/exported/web_dom_message_event.cc b/chromium/third_party/blink/renderer/core/exported/web_dom_message_event.cc
index 97b23b480cd..ca4632ca8a3 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_dom_message_event.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_dom_message_event.cc
@@ -83,9 +83,8 @@ WebDOMMessageEvent::WebDOMMessageEvent(TransferableMessage message,
UserActivation* user_activation = nullptr;
if (msg.user_activation) {
- user_activation =
- new UserActivation(msg.user_activation->has_been_active,
- msg.user_activation->was_active);
+ user_activation = MakeGarbageCollected<UserActivation>(
+ msg.user_activation->has_been_active, msg.user_activation->was_active);
}
// TODO(esprehn): Chromium always passes empty string for lastEventId, is that
diff --git a/chromium/third_party/blink/renderer/core/exported/web_element.cc b/chromium/third_party/blink/renderer/core/exported/web_element.cc
index 24931b74d5c..3adf9800006 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_element.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_element.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
bool WebElement::IsFormControlElement() const {
return ConstUnwrap<Element>()->IsFormControlElement();
@@ -66,7 +66,7 @@ bool WebElement::IsEditable() const {
return true;
}
- return EqualIgnoringASCIICase(element->getAttribute(roleAttr), "textbox");
+ return EqualIgnoringASCIICase(element->getAttribute(kRoleAttr), "textbox");
}
WebString WebElement::TagName() const {
@@ -80,7 +80,7 @@ bool WebElement::HasHTMLTagName(const WebString& tag_name) const {
// createElementNS(xhtmlNS, 'input') HTMLInputElement INPUT input
// createElementNS(xhtmlNS, 'INPUT') HTMLUnknownElement INPUT INPUT
const Element* element = ConstUnwrap<Element>();
- return HTMLNames::xhtmlNamespaceURI == element->namespaceURI() &&
+ return html_names::xhtmlNamespaceURI == element->namespaceURI() &&
element->localName() == String(tag_name).DeprecatedLower();
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_element_test.cc b/chromium/third_party/blink/renderer/core/exported/web_element_test.cc
index f6665ce8536..0f5b6a05134 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_element_test.cc
@@ -172,7 +172,7 @@ TEST_F(WebElementTest, IsAutonomousCustomElement) {
EXPECT_FALSE(TestElement().IsAutonomousCustomElement());
GetDocument().GetSettings()->SetScriptEnabled(true);
- auto* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ auto* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->setTextContent(R"JS(
customElements.define('v1-custom', class extends HTMLElement {});
document.body.appendChild(document.createElement('v1-custom'));
diff --git a/chromium/third_party/blink/renderer/core/exported/web_form_control_element.cc b/chromium/third_party/blink/renderer/core/exported/web_form_control_element.cc
index 3ddef9c5c59..af93969e43c 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_form_control_element.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_form_control_element.cc
@@ -62,7 +62,7 @@ WebString WebFormControlElement::FormControlType() const {
WebString WebFormControlElement::FormControlTypeForAutofill() const {
if (auto* input = ToHTMLInputElementOrNull(*private_)) {
if (input->IsTextField() && input->HasBeenPasswordField())
- return InputTypeNames::password;
+ return input_type_names::kPassword;
}
return ConstUnwrap<HTMLFormControlElement>()->type();
@@ -135,10 +135,10 @@ void WebFormControlElement::SetAutofillValue(const WebString& value) {
nullptr);
}
Unwrap<Element>()->DispatchScopedEvent(
- *Event::CreateBubble(EventTypeNames::keydown));
+ *Event::CreateBubble(event_type_names::kKeydown));
Unwrap<TextControlElement>()->SetAutofillValue(value);
Unwrap<Element>()->DispatchScopedEvent(
- *Event::CreateBubble(EventTypeNames::keyup));
+ *Event::CreateBubble(event_type_names::kKeyup));
if (!Focused()) {
Unwrap<Element>()->DispatchBlurEvent(nullptr, kWebFocusTypeForward,
nullptr);
diff --git a/chromium/third_party/blink/renderer/core/exported/web_form_element.cc b/chromium/third_party/blink/renderer/core/exported/web_form_element.cc
index 97330c21fd4..3c6fd3461a6 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_form_element.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_form_element.cc
@@ -47,7 +47,7 @@ bool WebFormElement::AutoComplete() const {
WebString WebFormElement::Action() const {
return ConstUnwrap<HTMLFormElement>()->FastGetAttribute(
- HTMLNames::actionAttr);
+ html_names::kActionAttr);
}
WebString WebFormElement::GetName() const {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_form_element_observer_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_form_element_observer_impl.cc
index 6a1a804978e..5c82b6f3d2b 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_form_element_observer_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_form_element_observer_impl.cc
@@ -45,17 +45,17 @@ WebFormElementObserverImpl::ObserverCallback::ObserverCallback(
mutation_observer_(MutationObserver::Create(this)),
callback_(std::move(callback)) {
{
- MutationObserverInit init;
- init.setAttributes(true);
- init.setAttributeFilter({"class", "style"});
+ MutationObserverInit* init = MutationObserverInit::Create();
+ init->setAttributes(true);
+ init->setAttributeFilter({"class", "style"});
mutation_observer_->observe(element_, init, ASSERT_NO_EXCEPTION);
}
for (Node* node = element_; node->parentElement();
node = node->parentElement()) {
- MutationObserverInit init;
- init.setChildList(true);
- init.setAttributes(true);
- init.setAttributeFilter({"class", "style"});
+ MutationObserverInit* init = MutationObserverInit::Create();
+ init->setChildList(true);
+ init->setAttributes(true);
+ init->setAttributeFilter({"class", "style"});
mutation_observer_->observe(node->parentElement(), init,
ASSERT_NO_EXCEPTION);
parents_.insert(node->parentElement());
@@ -111,22 +111,23 @@ void WebFormElementObserverImpl::ObserverCallback::Trace(
WebFormElementObserver* WebFormElementObserver::Create(
WebFormElement& element,
std::unique_ptr<WebFormElementObserverCallback> callback) {
- return new WebFormElementObserverImpl(*element.Unwrap<HTMLFormElement>(),
- std::move(callback));
+ return MakeGarbageCollected<WebFormElementObserverImpl>(
+ *element.Unwrap<HTMLFormElement>(), std::move(callback));
}
WebFormElementObserver* WebFormElementObserver::Create(
WebFormControlElement& element,
std::unique_ptr<WebFormElementObserverCallback> callback) {
- return new WebFormElementObserverImpl(*element.Unwrap<HTMLElement>(),
- std::move(callback));
+ return MakeGarbageCollected<WebFormElementObserverImpl>(
+ *element.Unwrap<HTMLElement>(), std::move(callback));
}
WebFormElementObserverImpl::WebFormElementObserverImpl(
HTMLElement& element,
std::unique_ptr<WebFormElementObserverCallback> callback)
: self_keep_alive_(this) {
- mutation_callback_ = new ObserverCallback(element, std::move(callback));
+ mutation_callback_ =
+ MakeGarbageCollected<ObserverCallback>(element, std::move(callback));
}
WebFormElementObserverImpl::~WebFormElementObserverImpl() = default;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc
index f4a0607d191..867f8106544 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_content_dumper.cc
@@ -232,7 +232,8 @@ WebString WebFrameContentDumper::DumpWebViewAsText(WebView* web_view,
if (!frame)
return WebString();
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
StringBuilder text;
FrameContentAsPlainText(max_chars, ToWebLocalFrameImpl(frame)->GetFrame(),
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer.cc
index 08bc3a23c7f..277218ce3cb 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer.cc
@@ -175,12 +175,12 @@ bool MHTMLFrameSerializerDelegate::ShouldIgnoreHiddenElement(
}
// Do not include the element that is marked with hidden attribute.
- if (element.FastHasAttribute(HTMLNames::hiddenAttr))
+ if (element.FastHasAttribute(html_names::kHiddenAttr))
return true;
// Do not include the hidden form element.
return IsHTMLInputElement(element) &&
- ToHTMLInputElement(&element)->type() == InputTypeNames::hidden;
+ ToHTMLInputElement(&element)->type() == input_type_names::kHidden;
}
bool MHTMLFrameSerializerDelegate::ShouldIgnoreMetaElement(
@@ -193,10 +193,10 @@ bool MHTMLFrameSerializerDelegate::ShouldIgnoreMetaElement(
// scheme could be prevented from loading.
if (!IsHTMLMetaElement(element))
return false;
- if (!element.FastHasAttribute(HTMLNames::contentAttr))
+ if (!element.FastHasAttribute(html_names::kContentAttr))
return false;
const AtomicString& http_equiv =
- element.FastGetAttribute(HTMLNames::http_equivAttr);
+ element.FastGetAttribute(html_names::kHttpEquivAttr);
return http_equiv == "Content-Security-Policy";
}
@@ -237,13 +237,13 @@ bool MHTMLFrameSerializerDelegate::ShouldIgnoreAttribute(
// images, as only the value of src is pulled into the archive. Discarding
// srcset prevents the problem. Long term we should make sure to MHTML plays
// nicely with srcset.
- if (attribute.LocalName() == HTMLNames::srcsetAttr)
+ if (attribute.LocalName() == html_names::kSrcsetAttr)
return true;
// Do not save ping attribute since anyway the ping will be blocked from
// MHTML.
if (IsHTMLAnchorElement(element) &&
- attribute.LocalName() == HTMLNames::pingAttr) {
+ attribute.LocalName() == html_names::kPingAttr) {
return true;
}
@@ -261,13 +261,13 @@ bool MHTMLFrameSerializerDelegate::ShouldIgnoreAttribute(
// containing link instead of html contents, don't ignore the attribute.
// Bail out now to avoid the check in Element::isScriptingAttribute.
bool is_src_doc_attribute = IsHTMLFrameElementBase(element) &&
- attribute.GetName() == HTMLNames::srcdocAttr;
+ attribute.GetName() == html_names::kSrcdocAttr;
String new_link_for_the_element;
if (is_src_doc_attribute && RewriteLink(element, new_link_for_the_element))
return false;
// Drop integrity attribute for those links with subresource loaded.
- if (attribute.LocalName() == HTMLNames::integrityAttr &&
+ if (attribute.LocalName() == html_names::kIntegrityAttr &&
IsHTMLLinkElement(element) && ToHTMLLinkElement(element).sheet()) {
return true;
}
@@ -339,8 +339,8 @@ void MHTMLFrameSerializerDelegate::GetCustomAttributesForImageElement(
}
// The width and height attributes should not be set.
- if (element.FastHasAttribute(HTMLNames::widthAttr) ||
- element.FastHasAttribute(HTMLNames::heightAttr)) {
+ if (element.FastHasAttribute(html_names::kWidthAttr) ||
+ element.FastHasAttribute(html_names::kHeightAttr)) {
return;
}
@@ -351,10 +351,10 @@ void MHTMLFrameSerializerDelegate::GetCustomAttributesForImageElement(
return;
}
- Attribute width_attribute(HTMLNames::widthAttr,
+ Attribute width_attribute(html_names::kWidthAttr,
AtomicString::Number(element.LayoutBoxWidth()));
attributes->push_back(width_attribute);
- Attribute height_attribute(HTMLNames::heightAttr,
+ Attribute height_attribute(html_names::kHeightAttr,
AtomicString::Number(element.LayoutBoxHeight()));
attributes->push_back(height_attribute);
}
@@ -384,7 +384,7 @@ std::pair<Node*, Element*> MHTMLFrameSerializerDelegate::GetAuxiliaryDOMTree(
// Put the shadow DOM content inside a template element. A special attribute
// is set to tell the mode of the shadow DOM.
Element* template_element =
- Element::Create(HTMLNames::templateTag, &(element.GetDocument()));
+ Element::Create(html_names::kTemplateTag, &(element.GetDocument()));
template_element->setAttribute(
QualifiedName(g_null_atom, kShadowModeAttributeName, g_null_atom),
AtomicString(shadow_mode));
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc
index dfe65ba5f09..22f4dfe135d 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc
@@ -116,8 +116,9 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
KURL parsed_url(url);
String file_path("frameserialization/" + file_name);
RegisterMockedFileURLLoad(parsed_url, file_path, mime_type);
- FrameTestHelpers::LoadFrame(MainFrameImpl(), url.Utf8().data());
- MainFrameImpl()->GetFrame()->View()->UpdateAllLifecyclePhases();
+ frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().data());
+ MainFrameImpl()->GetFrame()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
String GenerateMHTML(const bool only_body_parts) {
@@ -171,7 +172,8 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
shadow_root->SetDelegatesFocus(delegates_focus);
shadow_root->SetInnerHTMLFromString(String::FromUTF8(shadow_content),
ASSERT_NO_EXCEPTION);
- scope.GetDocument().View()->UpdateAllLifecyclePhases();
+ scope.GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
return shadow_root;
}
@@ -182,7 +184,7 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
void RegisterMockedFileURLLoad(const KURL& url,
const String& file_path,
const String& mime_type = "image/png") {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
url, test::CoreTestDataPath(file_path.Utf8().data()), mime_type);
}
@@ -193,7 +195,7 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
HistogramTester histogram_tester_;
private:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
SimpleMHTMLPartsGenerationDelegate mhtml_delegate_;
};
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc
index dbe166541cb..e139c411fb0 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc
@@ -77,14 +77,14 @@ class WebFrameSerializerTest : public testing::Test {
void RegisterMockedImageURLLoad(const String& url) {
// Image resources need to be mocked, but irrelevant here what image they
// map to.
- RegisterMockedFileURLLoad(URLTestHelpers::ToKURL(url.Utf8().data()),
+ RegisterMockedFileURLLoad(url_test_helpers::ToKURL(url.Utf8().data()),
"frameserialization/awesome.png");
}
void RegisterMockedFileURLLoad(const KURL& url,
const String& file_path,
const String& mime_type = "image/png") {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
url, test::CoreTestDataPath(file_path.Utf8().data()), mime_type);
}
@@ -116,7 +116,7 @@ class WebFrameSerializerTest : public testing::Test {
KURL parsed_url(url);
String file_path("frameserialization/" + file_name);
RegisterMockedFileURLLoad(parsed_url, file_path, "text/html");
- FrameTestHelpers::LoadFrame(MainFrameImpl(), url.Utf8().data());
+ frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().data());
SingleLinkRewritingDelegate delegate(parsed_url, WebString("local"));
SimpleWebFrameSerializerClient serializer_client;
WebFrameSerializer::Serialize(MainFrameImpl(), &serializer_client,
@@ -127,7 +127,7 @@ class WebFrameSerializerTest : public testing::Test {
WebLocalFrameImpl* MainFrameImpl() { return helper_.LocalMainFrame(); }
private:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
};
TEST_F(WebFrameSerializerTest, URLAttributeValues) {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_test.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_test.cc
index b9ced29e56f..6a958b1f7f0 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_frame_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -39,10 +39,10 @@
#include "build/build_config.h"
#include "cc/layers/picture_layer.h"
-#include "cc/trees/layer_tree_host.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/common/page/launching_process_state.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom-shared.h"
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
@@ -134,7 +134,6 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scoped_page_pauser.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
-#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
@@ -147,31 +146,21 @@
#include "third_party/blink/renderer/platform/cursor.h"
#include "third_party/blink/renderer/platform/drag_image.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h"
-#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
-#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
-#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
-#include "third_party/blink/renderer/platform/testing/paint_test_configurations.h"
#include "third_party/blink/renderer/platform/testing/scoped_fake_plugin_registry.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl_hash.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
-#include "third_party/blink/renderer/platform/wtf/dtoa/utils.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "third_party/skia/include/core/SkCanvas.h"
#include "v8/include/v8.h"
-using blink::URLTestHelpers::ToKURL;
+using blink::url_test_helpers::ToKURL;
using blink::mojom::SelectionMenuBehavior;
using blink::test::RunPendingTasks;
using testing::ElementsAre;
@@ -207,9 +196,7 @@ class WebFrameTest : public testing::Test {
// Make sure that the RendererScheduler is foregrounded to avoid getting
// throttled.
if (kLaunchingProcessIsBackgrounded) {
- Platform::Current()
- ->CurrentThread()
- ->Scheduler()
+ ThreadScheduler::Current()
->GetWebMainThreadSchedulerForTest()
->SetRendererBackgrounded(false);
}
@@ -225,7 +212,7 @@ class WebFrameTest : public testing::Test {
void RegisterMockedURLLoadFromBase(const std::string& base_url,
const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -240,14 +227,14 @@ class WebFrameTest : public testing::Test {
: WebString("Content-Security-Policy"),
WebString::FromUTF8(csp));
std::string full_string = base_url_ + file_name;
- URLTestHelpers::RegisterMockedURLLoadWithCustomResponse(
+ url_test_helpers::RegisterMockedURLLoadWithCustomResponse(
ToKURL(full_string),
test::CoreTestDataPath(WebString::FromUTF8(file_name)), response);
}
void RegisterMockedHttpURLLoadWithMimeType(const std::string& file_name,
const std::string& mime_type) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name), WebString::FromUTF8(mime_type));
}
@@ -270,14 +257,14 @@ class WebFrameTest : public testing::Test {
void InitializeTextSelectionWebView(
const std::string& url,
- FrameTestHelpers::WebViewHelper* web_view_helper) {
+ frame_test_helpers::WebViewHelper* web_view_helper) {
web_view_helper->InitializeAndLoad(url);
web_view_helper->GetWebView()->GetSettings()->SetDefaultFontSize(12);
web_view_helper->Resize(WebSize(640, 480));
}
std::unique_ptr<DragImage> NodeImageTestSetup(
- FrameTestHelpers::WebViewHelper* web_view_helper,
+ frame_test_helpers::WebViewHelper* web_view_helper,
const std::string& testcase) {
RegisterMockedHttpURLLoad("nodeimage.html");
web_view_helper->InitializeAndLoad(base_url_ + "nodeimage.html");
@@ -298,7 +285,8 @@ class WebFrameTest : public testing::Test {
// Both sets the inner html and runs the document lifecycle.
void InitializeWithHTML(LocalFrame& frame, const String& html_content) {
frame.GetDocument()->body()->SetInnerHTMLFromString(html_content);
- frame.GetDocument()->View()->UpdateAllLifecyclePhases();
+ frame.GetDocument()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
WebFrame* LastChild(WebFrame* frame) { return frame->last_child_; }
@@ -348,8 +336,13 @@ class WebFrameTest : public testing::Test {
return node_count;
}
+ void UpdateAllLifecyclePhases(WebViewImpl* web_view) {
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
static void GetElementAndCaretBoundsForFocusedEditableElement(
- FrameTestHelpers::WebViewHelper& helper,
+ frame_test_helpers::WebViewHelper& helper,
IntRect& element_bounds,
IntRect& caret_bounds) {
Element* element = helper.GetWebView()->FocusedElement();
@@ -373,7 +366,7 @@ TEST_F(WebFrameTest, ContentText) {
RegisterMockedHttpURLLoad("invisible_iframe.html");
RegisterMockedHttpURLLoad("zero_sized_iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "iframes_test.html");
// Now retrieve the frames text and test it only includes visible elements.
@@ -393,7 +386,7 @@ TEST_F(WebFrameTest, FrameForEnteredContext) {
RegisterMockedHttpURLLoad("invisible_iframe.html");
RegisterMockedHttpURLLoad("zero_sized_iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "iframes_test.html");
v8::HandleScope scope(v8::Isolate::GetCurrent());
@@ -442,7 +435,7 @@ class ScriptExecutionCallbackHelper : public WebScriptExecutionCallback {
TEST_F(WebFrameTest, RequestExecuteScript) {
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
v8::HandleScope scope(v8::Isolate::GetCurrent());
@@ -461,7 +454,7 @@ TEST_F(WebFrameTest, SuspendedRequestExecuteScript) {
RegisterMockedHttpURLLoad("foo.html");
RegisterMockedHttpURLLoad("bar.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
v8::HandleScope scope(v8::Isolate::GetCurrent());
@@ -483,8 +476,8 @@ TEST_F(WebFrameTest, SuspendedRequestExecuteScript) {
// If the frame navigates, pending scripts should be removed, but the callback
// should always be ran.
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "bar.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "bar.html");
EXPECT_TRUE(callback_helper.DidComplete());
EXPECT_EQ(String(), callback_helper.StringValue());
}
@@ -492,7 +485,7 @@ TEST_F(WebFrameTest, SuspendedRequestExecuteScript) {
TEST_F(WebFrameTest, RequestExecuteV8Function) {
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
auto callback = [](const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -520,7 +513,7 @@ TEST_F(WebFrameTest, RequestExecuteV8FunctionWhileSuspended) {
DisableRendererSchedulerThrottling();
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
auto callback = [](const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -554,7 +547,7 @@ TEST_F(WebFrameTest, RequestExecuteV8FunctionWhileSuspendedWithUserGesture) {
DisableRendererSchedulerThrottling();
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
auto callback = [](const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -619,7 +612,7 @@ class ScriptNotPausedCallbackHelper {
TEST_F(WebFrameTest, CallingPostPausableTaskWhileNotPaused) {
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
@@ -643,7 +636,7 @@ TEST_F(WebFrameTest, CallingPostPausableTaskWhilePaused)
{
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
@@ -668,7 +661,7 @@ TEST_F(WebFrameTest, CallingPostPausableTaskAndNavigating) {
RegisterMockedHttpURLLoad("foo.html");
RegisterMockedHttpURLLoad("bar.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
@@ -684,8 +677,8 @@ TEST_F(WebFrameTest, CallingPostPausableTaskAndNavigating) {
// If the frame navigates, pending scripts should be removed, but the callback
// should always be ran.
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "bar.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "bar.html");
ASSERT_TRUE(callback_helper.result());
EXPECT_EQ(WebLocalFrame::PausableTaskResult::kContextInvalidOrDestroyed,
*callback_helper.result());
@@ -695,14 +688,14 @@ TEST_F(WebFrameTest, CallingPostPausableTaskAndDestroyingTheContext) {
RegisterMockedHttpURLLoad("foo.html");
RegisterMockedHttpURLLoad("bar.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
- auto navigate_frame = [](FrameTestHelpers::WebViewHelper* web_view_helper,
+ auto navigate_frame = [](frame_test_helpers::WebViewHelper* web_view_helper,
const std::string& url) {
- FrameTestHelpers::LoadFrame(web_view_helper->GetWebView()->MainFrameImpl(),
- url);
+ frame_test_helpers::LoadFrame(
+ web_view_helper->GetWebView()->MainFrameImpl(), url);
};
ScriptNotPausedCallbackHelper callback_helper;
@@ -726,7 +719,7 @@ TEST_F(WebFrameTest, IframeScriptRemovesSelf) {
RegisterMockedHttpURLLoad("single_iframe.html");
RegisterMockedHttpURLLoad("visible_iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "single_iframe.html");
v8::HandleScope scope(v8::Isolate::GetCurrent());
@@ -750,7 +743,7 @@ TEST_F(WebFrameTest, IframeScriptRemovesSelf) {
TEST_F(WebFrameTest, FormWithNullFrame) {
RegisterMockedHttpURLLoad("form.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "form.html");
WebVector<WebFormElement> forms;
@@ -766,13 +759,13 @@ TEST_F(WebFrameTest, FormWithNullFrame) {
TEST_F(WebFrameTest, ChromePageJavascript) {
RegisterMockedChromeURLLoad("history.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(chrome_url_ + "history.html");
// Try to run JS against the chrome-style URL.
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- "javascript:document.body.appendChild(document."
- "createTextNode('Clobbered'))");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ "javascript:document.body.appendChild(document."
+ "createTextNode('Clobbered'))");
// Now retrieve the frame's text and ensure it was modified by running
// javascript.
@@ -785,14 +778,14 @@ TEST_F(WebFrameTest, ChromePageJavascript) {
TEST_F(WebFrameTest, ChromePageNoJavascript) {
RegisterMockedChromeURLLoad("history.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(chrome_url_ + "history.html");
// Try to run JS against the chrome-style URL after prohibiting it.
WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs("chrome");
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- "javascript:document.body.appendChild(document."
- "createTextNode('Clobbered'))");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ "javascript:document.body.appendChild(document."
+ "createTextNode('Clobbered'))");
// Now retrieve the frame's text and ensure it wasn't modified by running
// javascript.
@@ -807,15 +800,15 @@ TEST_F(WebFrameTest, LocationSetHostWithMissingPort) {
RegisterMockedHttpURLLoad(file_name);
RegisterMockedURLLoadFromBase("http://internal.test:0/", file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + file_name);
// Setting host to "hostname:" should be treated as "hostname:0".
- FrameTestHelpers::LoadFrame(
+ frame_test_helpers::LoadFrame(
web_view_helper.GetWebView()->MainFrameImpl(),
"javascript:location.host = 'internal.test:'; void 0;");
- FrameTestHelpers::LoadFrame(
+ frame_test_helpers::LoadFrame(
web_view_helper.GetWebView()->MainFrameImpl(),
"javascript:document.body.textContent = location.href; void 0;");
@@ -830,13 +823,13 @@ TEST_F(WebFrameTest, LocationSetEmptyPort) {
RegisterMockedHttpURLLoad(file_name);
RegisterMockedURLLoadFromBase("http://internal.test:0/", file_name);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + file_name);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- "javascript:location.port = ''; void 0;");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ "javascript:location.port = ''; void 0;");
- FrameTestHelpers::LoadFrame(
+ frame_test_helpers::LoadFrame(
web_view_helper.GetWebView()->MainFrameImpl(),
"javascript:document.body.textContent = location.href; void 0;");
@@ -847,12 +840,12 @@ TEST_F(WebFrameTest, LocationSetEmptyPort) {
}
class EvaluateOnLoadWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
EvaluateOnLoadWebFrameClient() : executing_(false), was_executed_(false) {}
~EvaluateOnLoadWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidClearWindowObject() override {
EXPECT_FALSE(executing_);
was_executed_ = true;
@@ -869,17 +862,18 @@ class EvaluateOnLoadWebFrameClient
TEST_F(WebFrameTest, DidClearWindowObjectIsNotRecursive) {
EvaluateOnLoadWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", &web_frame_client);
EXPECT_TRUE(web_frame_client.was_executed_);
}
-class CSSCallbackWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class CSSCallbackWebFrameClient
+ : public frame_test_helpers::TestWebFrameClient {
public:
CSSCallbackWebFrameClient() : update_count_(0) {}
~CSSCallbackWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidMatchCSS(
const WebVector<WebString>& newly_matching_selectors,
const WebVector<WebString>& stopped_matching_selectors) override;
@@ -926,17 +920,18 @@ class WebFrameCSSCallbackTest : public testing::Test {
}
void LoadHTML(const std::string& html) {
- FrameTestHelpers::LoadHTMLString(frame_, html, ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(frame_, html, ToKURL("about:blank"));
}
void ExecuteScript(const WebString& code) {
frame_->ExecuteScript(WebScriptSource(code));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
}
CSSCallbackWebFrameClient client_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
WebLocalFrame* frame_;
};
@@ -954,7 +949,8 @@ TEST_F(WebFrameCSSCallbackTest, AuthorStyleSheet) {
Vector<WebString> selectors;
selectors.push_back(WebString::FromUTF8("div.initial_on"));
frame_->GetDocument().WatchCSSSelectors(WebVector<WebString>(selectors));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(1, UpdateCount());
EXPECT_THAT(MatchedSelectors(), ElementsAre("div.initial_on"));
@@ -962,7 +958,8 @@ TEST_F(WebFrameCSSCallbackTest, AuthorStyleSheet) {
// Check that adding a watched selector calls back for already-present nodes.
selectors.push_back(WebString::FromUTF8("div.initial_off"));
Doc().WatchCSSSelectors(WebVector<WebString>(selectors));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(2, UpdateCount());
EXPECT_THAT(MatchedSelectors(),
@@ -970,7 +967,8 @@ TEST_F(WebFrameCSSCallbackTest, AuthorStyleSheet) {
// Check that we can turn off callbacks for certain selectors.
Doc().WatchCSSSelectors(WebVector<WebString>());
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(3, UpdateCount());
EXPECT_THAT(MatchedSelectors(), ElementsAre());
@@ -1087,7 +1085,8 @@ TEST_F(WebFrameCSSCallbackTest, DisplayContents) {
Vector<WebString> selectors(1u, WebString::FromUTF8("span"));
Doc().WatchCSSSelectors(WebVector<WebString>(selectors));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(1, UpdateCount()) << "Match elements in display:contents trees.";
@@ -1122,7 +1121,8 @@ TEST_F(WebFrameCSSCallbackTest, Reparenting) {
Vector<WebString> selectors;
selectors.push_back(WebString::FromUTF8("span"));
Doc().WatchCSSSelectors(WebVector<WebString>(selectors));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(1, UpdateCount());
@@ -1146,7 +1146,8 @@ TEST_F(WebFrameCSSCallbackTest, MultiSelector) {
selectors.push_back(WebString::FromUTF8("span"));
selectors.push_back(WebString::FromUTF8("span,p"));
Doc().WatchCSSSelectors(WebVector<WebString>(selectors));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(1, UpdateCount());
@@ -1162,7 +1163,8 @@ TEST_F(WebFrameCSSCallbackTest, InvalidSelector) {
selectors.push_back(WebString::FromUTF8("[")); // Invalid.
selectors.push_back(WebString::FromUTF8("p span")); // Not compound.
Doc().WatchCSSSelectors(WebVector<WebString>(selectors));
- frame_->View()->UpdateAllLifecyclePhases();
+ frame_->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
EXPECT_EQ(1, UpdateCount());
@@ -1173,7 +1175,7 @@ TEST_F(WebFrameCSSCallbackTest, InvalidSelector) {
TEST_F(WebFrameTest, DispatchMessageEventWithOriginCheck) {
RegisterMockedHttpURLLoad("postmessage_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "postmessage_test.html");
// Send a message with the correct origin.
@@ -1220,7 +1222,7 @@ scoped_refptr<SerializedScriptValue> SerializeString(
} // namespace
TEST_F(WebFrameTest, PostMessageThenDetach) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
LocalFrame* frame =
@@ -1241,12 +1243,12 @@ TEST_F(WebFrameTest, PostMessageThenDetach) {
namespace {
class FixedLayoutTestWebViewClient
- : public FrameTestHelpers::TestWebViewClient {
+ : public frame_test_helpers::TestWebViewClient {
public:
FixedLayoutTestWebViewClient() = default;
~FixedLayoutTestWebViewClient() override = default;
- // FrameTestHelpers::TestWebViewClient:
+ // frame_test_helpers::TestWebViewClient:
WebScreenInfo GetScreenInfo() override { return screen_info_; }
WebScreenInfo screen_info_;
@@ -1293,7 +1295,7 @@ TEST_F(WebFrameTest, ChangeInFixedLayoutResetsTextAutosizingMultipliers) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -1324,7 +1326,7 @@ TEST_F(WebFrameTest, WorkingTextAutosizingMultipliers_VirtualViewport) {
FixedLayoutTestWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + html_file, nullptr, &client,
nullptr, ConfigureAndroid);
@@ -1349,7 +1351,7 @@ TEST_F(WebFrameTest,
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "iframe_reload.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -1394,7 +1396,7 @@ TEST_F(WebFrameTest, ZeroHeightPositiveWidthNotIgnored) {
int viewport_width = 1280;
int viewport_height = 0;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -1419,7 +1421,7 @@ TEST_F(WebFrameTest, DeviceScaleFactorUsesDefaultWithoutViewportTag) {
FixedLayoutTestWebViewClient client;
client.screen_info_.device_scale_factor = 2;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "no_viewport_tag.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -1432,11 +1434,11 @@ TEST_F(WebFrameTest, DeviceScaleFactorUsesDefaultWithoutViewportTag) {
// Device scale factor should be independent of page scale.
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(1, 2);
web_view_helper.GetWebView()->SetPageScaleFactor(0.5);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(1, web_view_helper.GetWebView()->PageScaleFactor());
// Force the layout to happen before leaving the test.
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
}
TEST_F(WebFrameTest, FixedLayoutInitializeAtMinimumScale) {
@@ -1449,11 +1451,11 @@ TEST_F(WebFrameTest, FixedLayoutInitializeAtMinimumScale) {
// Make sure we initialize to minimum scale, even if the window size
// only becomes available after the load begins.
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 5);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "fixed_layout.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "fixed_layout.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
int default_fixed_layout_width = 980;
@@ -1468,7 +1470,7 @@ TEST_F(WebFrameTest, FixedLayoutInitializeAtMinimumScale) {
float user_pinch_page_scale_factor = 2;
web_view_helper.GetWebView()->SetPageScaleFactor(
user_pinch_page_scale_factor);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
// Make sure we don't reset to initial scale if the page continues to load.
web_view_helper.GetWebView()->DidCommitLoad(false, false);
@@ -1492,11 +1494,11 @@ TEST_F(WebFrameTest, WideDocumentInitializeAtMinimumScale) {
// Make sure we initialize to minimum scale, even if the window size
// only becomes available after the load begins.
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 5);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "wide_document.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "wide_document.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
int wide_document_width = 1500;
@@ -1510,7 +1512,7 @@ TEST_F(WebFrameTest, WideDocumentInitializeAtMinimumScale) {
float user_pinch_page_scale_factor = 2;
web_view_helper.GetWebView()->SetPageScaleFactor(
user_pinch_page_scale_factor);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
// Make sure we don't reset to initial scale if the page continues to load.
web_view_helper.GetWebView()->DidCommitLoad(false, false);
@@ -1532,7 +1534,7 @@ TEST_F(WebFrameTest, DelayedViewportInitialScale) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-auto-initial-scale.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -1547,7 +1549,7 @@ TEST_F(WebFrameTest, DelayedViewportInitialScale) {
ViewportDescription description = viewport.GetViewportDescription();
description.zoom = 2;
viewport.SetViewportDescription(description);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(2, web_view_helper.GetWebView()->PageScaleFactor());
}
@@ -1559,7 +1561,7 @@ TEST_F(WebFrameTest, setLoadWithOverviewModeToFalse) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-auto-initial-scale.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -1580,7 +1582,7 @@ TEST_F(WebFrameTest, SetLoadWithOverviewModeToFalseAndNoWideViewport) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "large-div.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetLoadWithOverviewMode(false);
@@ -1602,7 +1604,7 @@ TEST_F(WebFrameTest, NoWideViewportIgnoresPageViewportWidth) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-auto-initial-scale.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -1633,7 +1635,7 @@ TEST_F(WebFrameTest, NoWideViewportIgnoresPageViewportWidthButAccountsScale) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-wide-2x-initial-scale.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -1665,7 +1667,7 @@ TEST_F(WebFrameTest, WideViewportSetsTo980WithoutViewportTag) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "no_viewport_tag.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
@@ -1696,12 +1698,12 @@ TEST_F(WebFrameTest, WideViewportSetsTo980WithXhtmlMp) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
true);
web_view_helper.GetWebView()->GetSettings()->SetUseWideViewport(true);
- FrameTestHelpers::LoadFrame(
+ frame_test_helpers::LoadFrame(
web_view_helper.GetWebView()->MainFrameImpl(),
base_url_ + "viewport/viewport-legacy-xhtmlmp.html");
@@ -1726,7 +1728,7 @@ TEST_F(WebFrameTest, NoWideViewportAndHeightInMeta) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport-height-1000.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -1750,7 +1752,7 @@ TEST_F(WebFrameTest, WideViewportSetsTo980WithAutoWidth) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-2x-initial-scale.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -1780,7 +1782,7 @@ TEST_F(WebFrameTest, PageViewportInitialScaleOverridesLoadWithOverviewMode) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-wide-2x-initial-scale.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -1799,7 +1801,7 @@ TEST_F(WebFrameTest, setInitialPageScaleFactorPermanently) {
client.screen_info_.device_scale_factor = 1;
float enforced_page_scale_factor = 2.0f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
@@ -1807,7 +1809,7 @@ TEST_F(WebFrameTest, setInitialPageScaleFactorPermanently) {
web_view_helper.GetWebView()->GetSettings()->SetLoadWithOverviewMode(false);
web_view_helper.GetWebView()->SetInitialPageScaleOverride(
enforced_page_scale_factor);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(enforced_page_scale_factor,
web_view_helper.GetWebView()->PageScaleFactor());
@@ -1820,7 +1822,7 @@ TEST_F(WebFrameTest, setInitialPageScaleFactorPermanently) {
web_view_helper.GetWebView()->PageScaleFactor());
web_view_helper.GetWebView()->SetInitialPageScaleOverride(-1);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(1.0, web_view_helper.GetWebView()->PageScaleFactor());
}
@@ -1834,7 +1836,7 @@ TEST_F(WebFrameTest,
int viewport_height = 480;
float enforced_page_scale_factor = 0.5f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-auto-initial-scale.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -1857,7 +1859,7 @@ TEST_F(WebFrameTest,
int viewport_height = 480;
float enforced_page_scale_factor = 0.5f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-wide-2x-initial-scale.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -1890,7 +1892,7 @@ TEST_F(WebFrameTest, SmallPermanentInitialPageScaleFactorIsClobbered) {
for (size_t i = 0; i < arraysize(pages); ++i) {
for (int quirk_enabled = 0; quirk_enabled <= 1; ++quirk_enabled) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + pages[i], nullptr, &client,
nullptr, ConfigureAndroid);
web_view_helper.GetWebView()
@@ -1917,7 +1919,7 @@ TEST_F(WebFrameTest, PermanentInitialPageScaleFactorAffectsLayoutWidth) {
int viewport_height = 480;
float enforced_page_scale_factor = 0.5;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
@@ -1946,7 +1948,7 @@ TEST_F(WebFrameTest, DocumentElementClientHeightWorksWithWrapContentMode) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "0-by-0.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -1967,12 +1969,12 @@ TEST_F(WebFrameTest, SetForceZeroLayoutHeightWorksWithWrapContentMode) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "0-by-0.html", nullptr, &client,
nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetForceZeroLayoutHeight(true);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
PaintLayerCompositor* compositor = web_view_helper.GetWebView()->Compositor();
GraphicsLayer* scroll_container = compositor->RootGraphicsLayer();
@@ -2041,7 +2043,7 @@ TEST_F(WebFrameTest, SetForceZeroLayoutHeight) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "200-by-300.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -2098,7 +2100,7 @@ TEST_F(WebFrameTest, ToggleViewportMetaOnOff) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport-device-width.html",
nullptr, &client);
WebSettings* settings = web_view_helper.GetWebView()->GetSettings();
@@ -2136,7 +2138,7 @@ TEST_F(WebFrameTest,
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "button.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -2174,59 +2176,59 @@ TEST_F(WebFrameTest,
}
TEST_F(WebFrameTest, FrameOwnerPropertiesMargin) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebFrameOwnerProperties properties;
properties.margin_width = 11;
properties.margin_height = 22;
- WebLocalFrameImpl* local_frame = FrameTestHelpers::CreateLocalChild(
+ WebLocalFrameImpl* local_frame = frame_test_helpers::CreateLocalChild(
*helper.RemoteMainFrame(), "frameName", properties);
RegisterMockedHttpURLLoad("frame_owner_properties.html");
- FrameTestHelpers::LoadFrame(local_frame,
- base_url_ + "frame_owner_properties.html");
+ frame_test_helpers::LoadFrame(local_frame,
+ base_url_ + "frame_owner_properties.html");
// Check if the LocalFrame has seen the marginwidth and marginheight
// properties.
Document* child_document = local_frame->GetFrame()->GetDocument();
EXPECT_EQ(11, child_document->FirstBodyElement()->GetIntegralAttribute(
- HTMLNames::marginwidthAttr));
+ html_names::kMarginwidthAttr));
EXPECT_EQ(22, child_document->FirstBodyElement()->GetIntegralAttribute(
- HTMLNames::marginheightAttr));
+ html_names::kMarginheightAttr));
LocalFrameView* frame_view = local_frame->GetFrameView();
frame_view->Resize(800, 600);
frame_view->SetNeedsLayout();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// Expect scrollbars to be enabled by default.
EXPECT_NE(nullptr, frame_view->LayoutViewport()->HorizontalScrollbar());
EXPECT_NE(nullptr, frame_view->LayoutViewport()->VerticalScrollbar());
}
TEST_F(WebFrameTest, FrameOwnerPropertiesScrolling) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebFrameOwnerProperties properties;
// Turn off scrolling in the subframe.
properties.scrolling_mode =
WebFrameOwnerProperties::ScrollingMode::kAlwaysOff;
- WebLocalFrameImpl* local_frame = FrameTestHelpers::CreateLocalChild(
+ WebLocalFrameImpl* local_frame = frame_test_helpers::CreateLocalChild(
*helper.RemoteMainFrame(), "frameName", properties);
RegisterMockedHttpURLLoad("frame_owner_properties.html");
- FrameTestHelpers::LoadFrame(local_frame,
- base_url_ + "frame_owner_properties.html");
+ frame_test_helpers::LoadFrame(local_frame,
+ base_url_ + "frame_owner_properties.html");
Document* child_document = local_frame->GetFrame()->GetDocument();
EXPECT_EQ(0, child_document->FirstBodyElement()->GetIntegralAttribute(
- HTMLNames::marginwidthAttr));
+ html_names::kMarginwidthAttr));
EXPECT_EQ(0, child_document->FirstBodyElement()->GetIntegralAttribute(
- HTMLNames::marginheightAttr));
+ html_names::kMarginheightAttr));
- LocalFrameView* frame_view =
- static_cast<WebLocalFrameImpl*>(local_frame)->GetFrameView();
+ LocalFrameView* frame_view = local_frame->GetFrameView();
EXPECT_EQ(nullptr, frame_view->LayoutViewport()->HorizontalScrollbar());
EXPECT_EQ(nullptr, frame_view->LayoutViewport()->VerticalScrollbar());
}
@@ -2240,16 +2242,16 @@ TEST_F(WebFrameTest, SetForceZeroLayoutHeightWorksAcrossNavigations) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "200-by-300.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetForceZeroLayoutHeight(true);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "large-div.html");
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "large-div.html");
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(0, web_view_helper.GetWebView()
->MainFrameImpl()
@@ -2266,7 +2268,7 @@ TEST_F(WebFrameTest, SetForceZeroLayoutHeightWithWideViewportQuirk) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "200-by-300.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -2292,7 +2294,7 @@ TEST_F(WebFrameTest, WideViewportAndWideContentWithInitialScale) {
int viewport_width = 600;
int viewport_height = 800;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
@@ -2302,8 +2304,9 @@ TEST_F(WebFrameTest, WideViewportAndWideContentWithInitialScale) {
true);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "wide_document_width_viewport.html");
+ frame_test_helpers::LoadFrame(
+ web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "wide_document_width_viewport.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
int wide_document_width = 800;
@@ -2322,7 +2325,7 @@ TEST_F(WebFrameTest, WideViewportQuirkClobbersHeight) {
int viewport_width = 600;
int viewport_height = 800;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
@@ -2332,8 +2335,8 @@ TEST_F(WebFrameTest, WideViewportQuirkClobbersHeight) {
true);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "viewport-height-1000.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "viewport-height-1000.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
EXPECT_EQ(800, web_view_helper.GetWebView()
@@ -2352,7 +2355,7 @@ TEST_F(WebFrameTest, LayoutSize320Quirk) {
int viewport_width = 600;
int viewport_height = 800;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
@@ -2362,8 +2365,8 @@ TEST_F(WebFrameTest, LayoutSize320Quirk) {
true);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "viewport/viewport-30.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "viewport/viewport-30.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
EXPECT_EQ(600, web_view_helper.GetWebView()
@@ -2388,7 +2391,7 @@ TEST_F(WebFrameTest, LayoutSize320Quirk) {
description.min_width = Length(321, blink::kFixed);
description.max_width = Length(321, blink::kFixed);
viewport.SetViewportDescription(description);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(321, web_view_helper.GetWebView()
->MainFrameImpl()
->GetFrameView()
@@ -2398,7 +2401,7 @@ TEST_F(WebFrameTest, LayoutSize320Quirk) {
description.min_width = Length(320, blink::kFixed);
description.max_width = Length(320, blink::kFixed);
viewport.SetViewportDescription(description);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(600, web_view_helper.GetWebView()
->MainFrameImpl()
->GetFrameView()
@@ -2408,7 +2411,7 @@ TEST_F(WebFrameTest, LayoutSize320Quirk) {
description = viewport.GetViewportDescription();
description.max_height = Length(1000, blink::kFixed);
viewport.SetViewportDescription(description);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(1000, web_view_helper.GetWebView()
->MainFrameImpl()
->GetFrameView()
@@ -2417,7 +2420,7 @@ TEST_F(WebFrameTest, LayoutSize320Quirk) {
description.max_height = Length(320, blink::kFixed);
viewport.SetViewportDescription(description);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(800, web_view_helper.GetWebView()
->MainFrameImpl()
->GetFrameView()
@@ -2433,7 +2436,7 @@ TEST_F(WebFrameTest, ZeroValuesQuirk) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetViewportMetaZeroValuesQuirk(
true);
@@ -2441,8 +2444,8 @@ TEST_F(WebFrameTest, ZeroValuesQuirk) {
true);
web_view_helper.GetWebView()->GetSettings()->SetViewportMetaLayoutSizeQuirk(
true);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "viewport-zero-values.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "viewport-zero-values.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
EXPECT_EQ(viewport_width, web_view_helper.GetWebView()
@@ -2453,7 +2456,7 @@ TEST_F(WebFrameTest, ZeroValuesQuirk) {
EXPECT_EQ(1.0f, web_view_helper.GetWebView()->PageScaleFactor());
web_view_helper.GetWebView()->GetSettings()->SetUseWideViewport(true);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(viewport_width, web_view_helper.GetWebView()
->MainFrameImpl()
->GetFrameView()
@@ -2470,10 +2473,10 @@ TEST_F(WebFrameTest, OverflowHiddenDisablesScrolling) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "body-overflow-hidden.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "body-overflow-hidden.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
LocalFrameView* view = web_view_helper.LocalMainFrame()->GetFrameView();
@@ -2490,10 +2493,10 @@ TEST_F(WebFrameTest, OverflowHiddenDisablesScrollingWithSetCanHaveScrollbars) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "body-overflow-hidden-short.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "body-overflow-hidden-short.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
LocalFrameView* view = web_view_helper.LocalMainFrame()->GetFrameView();
@@ -2501,7 +2504,7 @@ TEST_F(WebFrameTest, OverflowHiddenDisablesScrollingWithSetCanHaveScrollbars) {
EXPECT_FALSE(
view->LayoutViewport()->UserInputScrollable(kHorizontalScrollbar));
- web_view_helper.LocalMainFrame()->SetCanHaveScrollbars(true);
+ web_view_helper.LocalMainFrame()->GetFrameView()->SetCanHaveScrollbars(true);
EXPECT_FALSE(view->LayoutViewport()->UserInputScrollable(kVerticalScrollbar));
EXPECT_FALSE(
view->LayoutViewport()->UserInputScrollable(kHorizontalScrollbar));
@@ -2515,13 +2518,13 @@ TEST_F(WebFrameTest, IgnoreOverflowHiddenQuirk) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client);
web_view_helper.GetWebView()
->GetSettings()
->SetIgnoreMainFrameOverflowHiddenQuirk(true);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "body-overflow-hidden.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "body-overflow-hidden.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
LocalFrameView* view = web_view_helper.LocalMainFrame()->GetFrameView();
@@ -2537,14 +2540,14 @@ TEST_F(WebFrameTest, NonZeroValuesNoQuirk) {
int viewport_height = 480;
float expected_page_scale_factor = 0.5f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->GetSettings()->SetViewportMetaZeroValuesQuirk(
true);
web_view_helper.GetWebView()->GetSettings()->SetWideViewportQuirkEnabled(
true);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "viewport-nonzero-values.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "viewport-nonzero-values.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
EXPECT_EQ(viewport_width / expected_page_scale_factor,
@@ -2557,7 +2560,7 @@ TEST_F(WebFrameTest, NonZeroValuesNoQuirk) {
web_view_helper.GetWebView()->PageScaleFactor());
web_view_helper.GetWebView()->GetSettings()->SetUseWideViewport(true);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(viewport_width / expected_page_scale_factor,
web_view_helper.GetWebView()
->MainFrameImpl()
@@ -2577,7 +2580,7 @@ TEST_F(WebFrameTest, setPageScaleFactorDoesNotLayout) {
int viewport_width = 64;
int viewport_height = 48;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -2603,7 +2606,7 @@ TEST_F(WebFrameTest, setPageScaleFactorWithOverlayScrollbarsDoesNotLayout) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -2629,7 +2632,7 @@ TEST_F(WebFrameTest, pageScaleFactorWrittenToHistoryItem) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -2652,11 +2655,11 @@ TEST_F(WebFrameTest, initialScaleWrittenToHistoryItem) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 5);
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "fixed_layout.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "fixed_layout.html");
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
int default_fixed_layout_width = 980;
@@ -2680,7 +2683,7 @@ TEST_F(WebFrameTest, pageScaleFactorDoesntShrinkFrameView) {
int viewport_width = 64;
int viewport_height = 48;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "large-div.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -2722,7 +2725,7 @@ TEST_F(WebFrameTest, pageScaleFactorDoesNotApplyCssTransform) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -2757,7 +2760,7 @@ TEST_F(WebFrameTest, targetDensityDpiHigh) {
float device_dpi = device_scale_factor * 160.0f;
client.screen_info_.device_scale_factor = device_scale_factor;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-target-densitydpi-high.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -2803,7 +2806,7 @@ TEST_F(WebFrameTest, targetDensityDpiDevice) {
for (size_t i = 0; i < arraysize(device_scale_factors); ++i) {
client.screen_info_.device_scale_factor = device_scale_factors[i];
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-target-densitydpi-device.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -2846,7 +2849,7 @@ TEST_F(WebFrameTest, targetDensityDpiDeviceAndFixedWidth) {
for (size_t i = 0; i < arraysize(device_scale_factors); ++i) {
client.screen_info_.device_scale_factor = device_scale_factors[i];
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-target-densitydpi-device-and-fixed-width.html",
nullptr, &client, nullptr, ConfigureAndroid);
@@ -2884,7 +2887,7 @@ TEST_F(WebFrameTest, NoWideViewportAndScaleLessThanOne) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-initial-scale-less-than-1.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -2923,7 +2926,7 @@ TEST_F(WebFrameTest, NoWideViewportAndScaleLessThanOneWithDeviceWidth) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-initial-scale-less-than-1-device-width.html",
nullptr, &client, nullptr, ConfigureAndroid);
@@ -2964,7 +2967,7 @@ TEST_F(WebFrameTest, NoWideViewportAndNoViewportWithInitialPageScaleOverride) {
int viewport_height = 480;
float enforced_page_scale_factor = 5.0f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "large-div.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 5);
@@ -3000,7 +3003,7 @@ TEST_F(WebFrameTest, NoUserScalableQuirkIgnoresViewportScale) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-initial-scale-and-user-scalable-no.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -3035,7 +3038,7 @@ TEST_F(WebFrameTest,
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-initial-scale-and-user-scalable-no.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -3075,7 +3078,7 @@ TEST_F(WebFrameTest, NoUserScalableQuirkIgnoresViewportScaleForWideViewport) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport-2x-initial-scale-non-user-scalable.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -3111,7 +3114,7 @@ TEST_F(WebFrameTest, DesktopPageCanBeZoomedInWhenWideViewportIsTurnedOff) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "no_viewport_tag.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 5);
@@ -3131,7 +3134,7 @@ TEST_F(WebFrameTest, AtViewportInsideAtMediaInitialViewport) {
RegisterMockedHttpURLLoad("viewport-inside-media.html");
FixedLayoutTestWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport-inside-media.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -3156,11 +3159,11 @@ TEST_F(WebFrameTest, AtViewportAffectingAtMediaRecalcCount) {
RegisterMockedHttpURLLoad("viewport-and-media.html");
FixedLayoutTestWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(640, 480));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "viewport-and-media.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "viewport-and-media.html");
Document* document =
web_view_helper.LocalMainFrame()->GetFrame()->GetDocument();
@@ -3182,11 +3185,11 @@ TEST_F(WebFrameTest, AtViewportWithViewportLengths) {
RegisterMockedHttpURLLoad("viewport-lengths.html");
FixedLayoutTestWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, &client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(800, 600));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "viewport-lengths.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "viewport-lengths.html");
LocalFrameView* view = web_view_helper.LocalMainFrame()->GetFrameView();
EXPECT_EQ(400, view->GetLayoutSize().Width());
@@ -3219,7 +3222,7 @@ class WebFrameResizeTest : public WebFrameTest {
const float aspect_ratio =
static_cast<float>(viewport_size.width) / viewport_size.height;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + url, nullptr, nullptr,
nullptr, ConfigureAndroid);
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 5);
@@ -3251,7 +3254,7 @@ class WebFrameResizeTest : public WebFrameTest {
web_view_helper.GetWebView()->SetPageScaleFactor(
initial_page_scale_factor);
web_view_helper.LocalMainFrame()->SetScrollOffset(scroll_offset);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
const WebSize expected_scroll_offset =
web_view_helper.LocalMainFrame()->GetScrollOffset();
web_view_helper.Resize(
@@ -3337,7 +3340,7 @@ TEST_F(WebFrameTest, pageScaleFactorUpdatesScrollbars) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fixed_layout.html", nullptr,
&client, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
@@ -3365,7 +3368,7 @@ TEST_F(WebFrameTest, CanOverrideScaleLimits) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "no_scale_for_you.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -3376,13 +3379,13 @@ TEST_F(WebFrameTest, CanOverrideScaleLimits) {
EXPECT_EQ(2.0f, web_view_helper.GetWebView()->MaximumPageScaleFactor());
web_view_helper.GetWebView()->SetIgnoreViewportTagScaleLimits(true);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(1.0f, web_view_helper.GetWebView()->MinimumPageScaleFactor());
EXPECT_EQ(5.0f, web_view_helper.GetWebView()->MaximumPageScaleFactor());
web_view_helper.GetWebView()->SetIgnoreViewportTagScaleLimits(false);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(2.0f, web_view_helper.GetWebView()->MinimumPageScaleFactor());
EXPECT_EQ(2.0f, web_view_helper.GetWebView()->MaximumPageScaleFactor());
@@ -3403,15 +3406,15 @@ TEST_F(WebFrameTest, updateOverlayScrollbarLayers)
std::unique_ptr<FakeCompositingWebViewClient>
fake_compositing_web_view_client =
std::make_unique<FakeCompositingWebViewClient>();
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, fake_compositing_web_view_client.get(),
nullptr, &ConfigureCompositingWebView);
web_view_helper.Resize(WebSize(view_width, view_height));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "large-div.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "large-div.html");
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
LocalFrameView* view = web_view_helper.LocalMainFrame()->GetFrameView();
EXPECT_TRUE(view->LayoutViewport()->LayerForHorizontalScrollbar());
EXPECT_TRUE(view->LayoutViewport()->LayerForVerticalScrollbar());
@@ -3426,22 +3429,35 @@ void SetScaleAndScrollAndLayout(WebViewImpl* web_view,
float scale) {
web_view->SetPageScaleFactor(scale);
web_view->MainFrameImpl()->SetScrollOffset(WebSize(scroll.x, scroll.y));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
void SimulatePageScale(WebViewImpl* web_view_impl, float& scale) {
float scale_delta =
web_view_impl->FakePageScaleAnimationPageScaleForTesting() /
web_view_impl->PageScaleFactor();
- web_view_impl->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), scale_delta, 0});
+ web_view_impl->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(),
+ scale_delta, 0,
+ cc::BrowserControlsState::kBoth});
scale = web_view_impl->PageScaleFactor();
}
+WebRect ComputeBlockBoundHelper(WebViewImpl* web_view_impl,
+ const gfx::Point& point,
+ bool ignore_clipping) {
+ DCHECK(web_view_impl->MainFrameImpl());
+ WebFrameWidgetBase* widget =
+ web_view_impl->MainFrameImpl()->FrameWidgetImpl();
+ DCHECK(widget);
+ return widget->ComputeBlockBound(point, ignore_clipping);
+}
+
void SimulateDoubleTap(WebViewImpl* web_view_impl,
- WebPoint& point,
+ gfx::Point& point,
float& scale) {
- web_view_impl->AnimateDoubleTapZoom(point);
+ web_view_impl->AnimateDoubleTapZoom(
+ IntPoint(point), ComputeBlockBoundHelper(web_view_impl, point, false));
EXPECT_TRUE(web_view_impl->FakeDoubleTapAnimationPendingForTesting());
SimulatePageScale(web_view_impl, scale);
}
@@ -3453,7 +3469,7 @@ TEST_F(WebFrameTest, DivAutoZoomParamsTest) {
int viewport_width = 640 / kDeviceScaleFactor;
int viewport_height = 1280 / kDeviceScaleFactor;
float double_tap_zoom_already_legible_ratio = 1.2f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_for_auto_zoom_into_div_test.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
@@ -3464,36 +3480,34 @@ TEST_F(WebFrameTest, DivAutoZoomParamsTest) {
WebRect wide_div(200, 100, 400, 150);
WebRect tall_div(200, 300, 400, 800);
- WebPoint double_tap_point_wide(wide_div.x + 50, wide_div.y + 50);
- WebPoint double_tap_point_tall(tall_div.x + 50, tall_div.y + 50);
+ gfx::Point double_tap_point_wide(wide_div.x + 50, wide_div.y + 50);
+ gfx::Point double_tap_point_tall(tall_div.x + 50, tall_div.y + 50);
float scale;
- WebPoint scroll;
+ IntPoint scroll;
float double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
// Test double-tap zooming into wide div.
- WebRect wide_block_bound = web_view_helper.GetWebView()->ComputeBlockBound(
- double_tap_point_wide, false);
+ WebRect wide_block_bound = ComputeBlockBoundHelper(
+ web_view_helper.GetWebView(), double_tap_point_wide, false);
web_view_helper.GetWebView()->ComputeScaleAndScrollForBlockRect(
- WebPoint(double_tap_point_wide.x, double_tap_point_wide.y),
- wide_block_bound, kTouchPointPadding,
+ double_tap_point_wide, wide_block_bound, kTouchPointPadding,
double_tap_zoom_already_legible_scale, scale, scroll);
// The div should horizontally fill the screen (modulo margins), and
// vertically centered (modulo integer rounding).
EXPECT_NEAR(viewport_width / (float)wide_div.width, scale, 0.1);
- EXPECT_NEAR(wide_div.x, scroll.x, 20);
- EXPECT_EQ(0, scroll.y);
+ EXPECT_NEAR(wide_div.x, scroll.X(), 20);
+ EXPECT_EQ(0, scroll.Y());
SetScaleAndScrollAndLayout(web_view_helper.GetWebView(), scroll, scale);
// Test zoom out back to minimum scale.
- wide_block_bound = web_view_helper.GetWebView()->ComputeBlockBound(
- double_tap_point_wide, false);
+ wide_block_bound = ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ double_tap_point_wide, false);
web_view_helper.GetWebView()->ComputeScaleAndScrollForBlockRect(
- WebPoint(double_tap_point_wide.x, double_tap_point_wide.y),
- wide_block_bound, kTouchPointPadding,
+ double_tap_point_wide, wide_block_bound, kTouchPointPadding,
double_tap_zoom_already_legible_scale, scale, scroll);
// FIXME: Looks like we are missing EXPECTs here.
@@ -3502,16 +3516,15 @@ TEST_F(WebFrameTest, DivAutoZoomParamsTest) {
scale);
// Test double-tap zooming into tall div.
- WebRect tall_block_bound = web_view_helper.GetWebView()->ComputeBlockBound(
- double_tap_point_tall, false);
+ WebRect tall_block_bound = ComputeBlockBoundHelper(
+ web_view_helper.GetWebView(), double_tap_point_tall, false);
web_view_helper.GetWebView()->ComputeScaleAndScrollForBlockRect(
- WebPoint(double_tap_point_tall.x, double_tap_point_tall.y),
- tall_block_bound, kTouchPointPadding,
+ double_tap_point_tall, tall_block_bound, kTouchPointPadding,
double_tap_zoom_already_legible_scale, scale, scroll);
// The div should start at the top left of the viewport.
EXPECT_NEAR(viewport_width / (float)tall_div.width, scale, 0.1);
- EXPECT_NEAR(tall_div.x, scroll.x, 20);
- EXPECT_NEAR(tall_div.y, scroll.y, 20);
+ EXPECT_NEAR(tall_div.x, scroll.X(), 20);
+ EXPECT_NEAR(tall_div.y, scroll.Y(), 20);
}
TEST_F(WebFrameTest, DivAutoZoomWideDivTest) {
@@ -3521,14 +3534,14 @@ TEST_F(WebFrameTest, DivAutoZoomWideDivTest) {
int viewport_width = 640 / kDeviceScaleFactor;
int viewport_height = 1280 / kDeviceScaleFactor;
float double_tap_zoom_already_legible_ratio = 1.2f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_wide_div_for_auto_zoom_test.html", nullptr, nullptr,
nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
web_view_helper.GetWebView()->SetDeviceScaleFactor(kDeviceScaleFactor);
web_view_helper.GetWebView()->SetPageScaleFactor(1.0f);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
@@ -3537,7 +3550,7 @@ TEST_F(WebFrameTest, DivAutoZoomWideDivTest) {
double_tap_zoom_already_legible_ratio;
WebRect div(0, 100, viewport_width, 150);
- WebPoint point(div.x + 50, div.y + 50);
+ gfx::Point point(div.x + 50, div.y + 50);
float scale;
SetScaleAndScrollAndLayout(
web_view_helper.GetWebView(), WebPoint(0, 0),
@@ -3560,25 +3573,25 @@ TEST_F(WebFrameTest, DivAutoZoomVeryTallTest) {
const float kDeviceScaleFactor = 2.0f;
int viewport_width = 640 / kDeviceScaleFactor;
int viewport_height = 1280 / kDeviceScaleFactor;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "very_tall_div.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
web_view_helper.GetWebView()->SetDeviceScaleFactor(kDeviceScaleFactor);
web_view_helper.GetWebView()->SetPageScaleFactor(1.0f);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
WebRect div(200, 300, 400, 5000);
- WebPoint point(div.x + 50, div.y + 3000);
+ gfx::Point point(div.x + 50, div.y + 3000);
float scale;
- WebPoint scroll;
+ IntPoint scroll;
WebRect block_bound =
- web_view_helper.GetWebView()->ComputeBlockBound(point, true);
+ ComputeBlockBoundHelper(web_view_helper.GetWebView(), point, true);
web_view_helper.GetWebView()->ComputeScaleAndScrollForBlockRect(
point, block_bound, 0, 1.0f, scale, scroll);
EXPECT_EQ(scale, 1.0f);
- EXPECT_EQ(scroll.y, 2660);
+ EXPECT_EQ(scroll.Y(), 2660);
}
TEST_F(WebFrameTest, DivAutoZoomMultipleDivsTest) {
@@ -3588,7 +3601,7 @@ TEST_F(WebFrameTest, DivAutoZoomMultipleDivsTest) {
int viewport_width = 640 / kDeviceScaleFactor;
int viewport_height = 1280 / kDeviceScaleFactor;
float double_tap_zoom_already_legible_ratio = 1.2f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_multiple_divs_for_auto_zoom_test.html", nullptr, nullptr,
nullptr, ConfigureAndroid);
@@ -3597,14 +3610,14 @@ TEST_F(WebFrameTest, DivAutoZoomMultipleDivsTest) {
web_view_helper.GetWebView()->SetDeviceScaleFactor(kDeviceScaleFactor);
web_view_helper.GetWebView()->SetPageScaleFactor(0.5f);
web_view_helper.GetWebView()->SetMaximumLegibleScale(1.f);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
WebRect top_div(200, 100, 200, 150);
WebRect bottom_div(200, 300, 200, 150);
- WebPoint top_point(top_div.x + 50, top_div.y + 50);
- WebPoint bottom_point(bottom_div.x + 50, bottom_div.y + 50);
+ gfx::Point top_point(top_div.x + 50, top_div.y + 50);
+ gfx::Point bottom_point(bottom_div.x + 50, bottom_div.y + 50);
float scale;
SetScaleAndScrollAndLayout(
web_view_helper.GetWebView(), WebPoint(0, 0),
@@ -3624,7 +3637,8 @@ TEST_F(WebFrameTest, DivAutoZoomMultipleDivsTest) {
SimulateDoubleTap(web_view_helper.GetWebView(), top_point, scale);
EXPECT_FLOAT_EQ(1, scale);
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 0.6f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 0.6f, 0,
+ cc::BrowserControlsState::kBoth});
SimulateDoubleTap(web_view_helper.GetWebView(), bottom_point, scale);
EXPECT_FLOAT_EQ(1, scale);
SimulateDoubleTap(web_view_helper.GetWebView(), bottom_point, scale);
@@ -3634,8 +3648,13 @@ TEST_F(WebFrameTest, DivAutoZoomMultipleDivsTest) {
// If we didn't yet get an auto-zoom update and a second double-tap arrives,
// should go back to minimum scale.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
- web_view_helper.GetWebView()->AnimateDoubleTapZoom(top_point);
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
+
+ WebRect block_bounds =
+ ComputeBlockBoundHelper(web_view_helper.GetWebView(), top_point, false);
+ web_view_helper.GetWebView()->AnimateDoubleTapZoom(IntPoint(top_point),
+ block_bounds);
EXPECT_TRUE(
web_view_helper.GetWebView()->FakeDoubleTapAnimationPendingForTesting());
SimulateDoubleTap(web_view_helper.GetWebView(), bottom_point, scale);
@@ -3649,25 +3668,25 @@ TEST_F(WebFrameTest, DivAutoZoomScaleBoundsTest) {
int viewport_width = 320;
int viewport_height = 480;
float double_tap_zoom_already_legible_ratio = 1.2f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_bounds_check_for_auto_zoom_test.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
web_view_helper.GetWebView()->SetDeviceScaleFactor(1.5f);
web_view_helper.GetWebView()->SetMaximumLegibleScale(1.f);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
WebRect div(200, 100, 200, 150);
- WebPoint double_tap_point(div.x + 50, div.y + 50);
+ gfx::Point double_tap_point(div.x + 50, div.y + 50);
float scale;
// Test double tap scale bounds.
// minimumPageScale < doubleTapZoomAlreadyLegibleScale < 1
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.5f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
float double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3685,10 +3704,11 @@ TEST_F(WebFrameTest, DivAutoZoomScaleBoundsTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// 1 < minimumPageScale < doubleTapZoomAlreadyLegibleScale
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(1.1f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3706,10 +3726,11 @@ TEST_F(WebFrameTest, DivAutoZoomScaleBoundsTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// minimumPageScale < 1 < doubleTapZoomAlreadyLegibleScale
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.95f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3733,14 +3754,14 @@ TEST_F(WebFrameTest, DivAutoZoomScaleLegibleScaleTest) {
int viewport_height = 480;
float double_tap_zoom_already_legible_ratio = 1.2f;
float maximum_legible_scale_factor = 1.13f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_bounds_check_for_auto_zoom_test.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
web_view_helper.GetWebView()->SetMaximumLegibleScale(
maximum_legible_scale_factor);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
web_view_helper.GetWebView()
@@ -3749,7 +3770,7 @@ TEST_F(WebFrameTest, DivAutoZoomScaleLegibleScaleTest) {
.SetTextAutosizingEnabled(true);
WebRect div(200, 100, 200, 150);
- WebPoint double_tap_point(div.x + 50, div.y + 50);
+ gfx::Point double_tap_point(div.x + 50, div.y + 50);
float scale;
// Test double tap scale bounds.
@@ -3764,7 +3785,7 @@ TEST_F(WebFrameTest, DivAutoZoomScaleLegibleScaleTest) {
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.5f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
SimulateDoubleTap(web_view_helper.GetWebView(), double_tap_point, scale);
EXPECT_FLOAT_EQ(legible_scale, scale);
SimulateDoubleTap(web_view_helper.GetWebView(), double_tap_point, scale);
@@ -3775,11 +3796,12 @@ TEST_F(WebFrameTest, DivAutoZoomScaleLegibleScaleTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// 1 < maximumLegibleScaleFactor < minimumPageScale <
// doubleTapZoomAlreadyLegibleScale
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(1.0f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3797,11 +3819,12 @@ TEST_F(WebFrameTest, DivAutoZoomScaleLegibleScaleTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// minimumPageScale < 1 < maximumLegibleScaleFactor <
// doubleTapZoomAlreadyLegibleScale
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.95f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3819,11 +3842,12 @@ TEST_F(WebFrameTest, DivAutoZoomScaleLegibleScaleTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// minimumPageScale < 1 < doubleTapZoomAlreadyLegibleScale <
// maximumLegibleScaleFactor
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.9f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3847,13 +3871,13 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
int viewport_height = 480;
float double_tap_zoom_already_legible_ratio = 1.2f;
float accessibility_font_scale_factor = 1.13f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_bounds_check_for_auto_zoom_test.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
web_view_helper.GetWebView()->SetMaximumLegibleScale(1.f);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
web_view_helper.GetWebView()
@@ -3866,7 +3890,7 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
.SetAccessibilityFontScaleFactor(accessibility_font_scale_factor);
WebRect div(200, 100, 200, 150);
- WebPoint double_tap_point(div.x + 50, div.y + 50);
+ gfx::Point double_tap_point(div.x + 50, div.y + 50);
float scale;
// Test double tap scale bounds.
@@ -3881,7 +3905,7 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.5f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
SimulateDoubleTap(web_view_helper.GetWebView(), double_tap_point, scale);
EXPECT_FLOAT_EQ(legible_scale, scale);
SimulateDoubleTap(web_view_helper.GetWebView(), double_tap_point, scale);
@@ -3892,11 +3916,12 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// 1 < accessibilityFontScaleFactor < minimumPageScale <
// doubleTapZoomAlreadyLegibleScale
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(1.0f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3914,11 +3939,12 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// minimumPageScale < 1 < accessibilityFontScaleFactor <
// doubleTapZoomAlreadyLegibleScale
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.95f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3936,11 +3962,12 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
// Zoom in to reset double_tap_zoom_in_effect flag.
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.1f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.1f, 0,
+ cc::BrowserControlsState::kBoth});
// minimumPageScale < 1 < doubleTapZoomAlreadyLegibleScale <
// accessibilityFontScaleFactor
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.9f, 4);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
double_tap_zoom_already_legible_scale =
web_view_helper.GetWebView()->MinimumPageScaleFactor() *
double_tap_zoom_already_legible_ratio;
@@ -3960,7 +3987,7 @@ TEST_F(WebFrameTest, DivAutoZoomScaleFontScaleFactorTest) {
TEST_F(WebFrameTest, BlockBoundTest) {
RegisterMockedHttpURLLoad("block_bound.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "block_bound.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
web_view_helper.Resize(WebSize(300, 300));
@@ -3970,32 +3997,32 @@ TEST_F(WebFrameTest, BlockBoundTest) {
IntRect rect_right_bottom = IntRect(110, 110, 80, 80);
IntRect block_bound;
- block_bound = IntRect(
- web_view_helper.GetWebView()->ComputeBlockBound(WebPoint(9, 9), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(9, 9), true));
EXPECT_EQ(rect_back, block_bound);
- block_bound = IntRect(
- web_view_helper.GetWebView()->ComputeBlockBound(WebPoint(10, 10), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(10, 10), true));
EXPECT_EQ(rect_left_top, block_bound);
- block_bound = IntRect(
- web_view_helper.GetWebView()->ComputeBlockBound(WebPoint(50, 50), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(50, 50), true));
EXPECT_EQ(rect_left_top, block_bound);
- block_bound = IntRect(
- web_view_helper.GetWebView()->ComputeBlockBound(WebPoint(89, 89), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(89, 89), true));
EXPECT_EQ(rect_left_top, block_bound);
- block_bound = IntRect(
- web_view_helper.GetWebView()->ComputeBlockBound(WebPoint(90, 90), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(90, 90), true));
EXPECT_EQ(rect_back, block_bound);
- block_bound = IntRect(web_view_helper.GetWebView()->ComputeBlockBound(
- WebPoint(109, 109), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(109, 109), true));
EXPECT_EQ(rect_back, block_bound);
- block_bound = IntRect(web_view_helper.GetWebView()->ComputeBlockBound(
- WebPoint(110, 110), true));
+ block_bound = IntRect(ComputeBlockBoundHelper(web_view_helper.GetWebView(),
+ gfx::Point(110, 110), true));
EXPECT_EQ(rect_right_bottom, block_bound);
}
@@ -4005,7 +4032,7 @@ TEST_F(WebFrameTest, DontZoomInOnFocusedInTouchAction) {
int viewport_width = 600;
int viewport_height = 1000;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "textbox_in_touch_action.html");
web_view_helper.GetWebView()->SetDefaultPageScaleLimits(0.25f, 4);
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
@@ -4072,7 +4099,7 @@ TEST_F(WebFrameTest, DivScrollIntoEditableTest) {
float left_box_ratio = 0.3f;
int caret_padding = 10;
float min_readable_caret_height = 16.0f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_for_zoom_into_editable_test.html");
web_view_helper.GetWebView()
@@ -4185,7 +4212,7 @@ TEST_F(WebFrameTest, DivScrollIntoEditablePreservePageScaleTest) {
const int kViewportWidth = 450;
const int kViewportHeight = 300;
const float kMinReadableCaretHeight = 16.0f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_for_zoom_into_editable_test.html");
web_view_helper.GetWebView()
@@ -4263,7 +4290,7 @@ TEST_F(WebFrameTest, DivScrollIntoEditableTestZoomToLegibleScaleDisabled) {
int viewport_width = 100;
int viewport_height = 100;
float left_box_ratio = 0.3f;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_for_zoom_into_editable_test.html");
web_view_helper.GetWebView()
@@ -4341,7 +4368,7 @@ TEST_F(WebFrameTest, DivScrollIntoEditableTestWithDeviceScaleFactor) {
int viewport_height = 150 * kDeviceScaleFactor;
float min_readable_caret_height = 16.0f * kDeviceScaleFactor;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "get_scale_for_zoom_into_editable_test.html", nullptr,
nullptr, nullptr, ConfigureAndroid);
@@ -4388,7 +4415,7 @@ TEST_F(WebFrameTest, DivScrollIntoEditableTestWithDeviceScaleFactor) {
TEST_F(WebFrameTest, CharacterIndexAtPointWithPinchZoom) {
RegisterMockedHttpURLLoad("sometext.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "sometext.html");
web_view_helper.LoadAhem();
web_view_helper.Resize(WebSize(640, 480));
@@ -4414,7 +4441,7 @@ TEST_F(WebFrameTest, CharacterIndexAtPointWithPinchZoom) {
TEST_F(WebFrameTest, FirstRectForCharacterRangeWithPinchZoom) {
RegisterMockedHttpURLLoad("textbox.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "textbox.html");
web_view_helper.Resize(WebSize(640, 480));
@@ -4441,42 +4468,41 @@ TEST_F(WebFrameTest, FirstRectForCharacterRangeWithPinchZoom) {
EXPECT_EQ(old_rect.height * scale, rect.height);
}
class TestReloadDoesntRedirectWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestReloadDoesntRedirectWebFrameClient() = default;
~TestReloadDoesntRedirectWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
- WebNavigationPolicy DecidePolicyForNavigation(
- const NavigationPolicyInfo& info) override {
- EXPECT_FALSE(info.is_client_redirect);
- return kWebNavigationPolicyCurrentTab;
+ // frame_test_helpers::TestWebFrameClient:
+ void BeginNavigation(std::unique_ptr<WebNavigationInfo> info) override {
+ EXPECT_FALSE(info->is_client_redirect);
+ TestWebFrameClient::BeginNavigation(std::move(info));
}
};
TEST_F(WebFrameTest, ReloadDoesntSetRedirect) {
// Test for case in http://crbug.com/73104. Reloading a frame very quickly
- // would sometimes call decidePolicyForNavigation with isRedirect=true
+ // would sometimes call BeginNavigation with isRedirect=true
RegisterMockedHttpURLLoad("form.html");
TestReloadDoesntRedirectWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "form.html", &web_frame_client);
web_view_helper.GetWebView()->MainFrameImpl()->StartReload(
WebFrameLoadType::kReloadBypassingCache);
// start another reload before request is delivered.
- FrameTestHelpers::ReloadFrameBypassingCache(
+ frame_test_helpers::ReloadFrameBypassingCache(
web_view_helper.GetWebView()->MainFrameImpl());
}
class ClearScrollStateOnCommitWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
ClearScrollStateOnCommitWebFrameClient() = default;
~ClearScrollStateOnCommitWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidCommitProvisionalLoad(const WebHistoryItem&,
WebHistoryCommitType,
WebGlobalObjectReusePolicy) override {
@@ -4493,7 +4519,7 @@ TEST_F(WebFrameTest, ReloadPreservesState) {
RegisterMockedHttpURLLoad(url);
ClearScrollStateOnCommitWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + url, &client);
web_view_helper.Resize(WebSize(kPageWidth, kPageHeight));
web_view_helper.LocalMainFrame()->SetScrollOffset(
@@ -4503,7 +4529,7 @@ TEST_F(WebFrameTest, ReloadPreservesState) {
// Reload the page and end up at the same url. State should not be propagated.
web_view_helper.GetWebView()->MainFrameImpl()->StartReload(
WebFrameLoadType::kReload);
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view_helper.LocalMainFrame());
EXPECT_EQ(0, web_view_helper.LocalMainFrame()->GetScrollOffset().width);
EXPECT_EQ(0, web_view_helper.LocalMainFrame()->GetScrollOffset().height);
@@ -4515,12 +4541,12 @@ TEST_F(WebFrameTest, ReloadWhileProvisional) {
// the initial request to get lost.
RegisterMockedHttpURLLoad("fixed_layout.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
WebURLRequest request(ToKURL(base_url_ + "fixed_layout.html"));
web_view_helper.GetWebView()->MainFrameImpl()->StartNavigation(request);
// start reload before first request is delivered.
- FrameTestHelpers::ReloadFrameBypassingCache(
+ frame_test_helpers::ReloadFrameBypassingCache(
web_view_helper.GetWebView()->MainFrameImpl());
WebDocumentLoader* document_loader =
@@ -4534,7 +4560,7 @@ TEST_F(WebFrameTest, AppendRedirects) {
const std::string first_url = "about:blank";
const std::string second_url = "http://internal.test";
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(first_url);
WebDocumentLoader* document_loader =
@@ -4553,11 +4579,11 @@ TEST_F(WebFrameTest, IframeRedirect) {
RegisterMockedHttpURLLoad("iframe_redirect.html");
RegisterMockedHttpURLLoad("visible_iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "iframe_redirect.html");
// Pump pending requests one more time. The test page loads script that
// navigates.
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view_helper.LocalMainFrame());
WebFrame* iframe = web_view_helper.LocalMainFrame()->FindFrameByName(
@@ -4578,7 +4604,7 @@ TEST_F(WebFrameTest, ClearFocusedNodeTest) {
RegisterMockedHttpURLLoad("iframe_clear_focused_node_test.html");
RegisterMockedHttpURLLoad("autofocus_input_field_iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ +
"iframe_clear_focused_node_test.html");
@@ -4589,7 +4615,7 @@ TEST_F(WebFrameTest, ClearFocusedNodeTest) {
EXPECT_EQ(nullptr, web_view_helper.GetWebView()->FocusedElement());
}
-class ChangedSelectionCounter : public FrameTestHelpers::TestWebFrameClient {
+class ChangedSelectionCounter : public frame_test_helpers::TestWebFrameClient {
public:
ChangedSelectionCounter() : call_count_(0) {}
void DidChangeSelection(bool isSelectionEmpty) override { ++call_count_; }
@@ -4602,7 +4628,7 @@ class ChangedSelectionCounter : public FrameTestHelpers::TestWebFrameClient {
TEST_F(WebFrameTest, TabKeyCursorMoveTriggersOneSelectionChange) {
ChangedSelectionCounter counter;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
RegisterMockedHttpURLLoad("editable_elements.html");
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "editable_elements.html", &counter);
@@ -4647,7 +4673,7 @@ TEST_F(WebFrameTest, TabKeyCursorMoveTriggersOneSelectionChange) {
// Implementation of WebLocalFrameClient that tracks the v8 contexts that are
// created and destroyed for verification.
class ContextLifetimeTestWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
struct Notification {
public:
@@ -4689,7 +4715,8 @@ class ContextLifetimeTestWebFrameClient
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties&) override {
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType) override {
return CreateLocalChild(*parent, scope,
std::make_unique<ContextLifetimeTestWebFrameClient>(
create_notifications_, release_notifications_));
@@ -4726,7 +4753,7 @@ TEST_F(WebFrameTest, ContextNotificationsLoadUnload) {
release_notifications;
ContextLifetimeTestWebFrameClient web_frame_client(create_notifications,
release_notifications);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "context_notifications_test.html", &web_frame_client);
@@ -4775,13 +4802,14 @@ TEST_F(WebFrameTest, ContextNotificationsReload) {
release_notifications;
ContextLifetimeTestWebFrameClient web_frame_client(create_notifications,
release_notifications);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "context_notifications_test.html", &web_frame_client);
// Refresh, we should get two release notifications and two more create
// notifications.
- FrameTestHelpers::ReloadFrame(web_view_helper.GetWebView()->MainFrameImpl());
+ frame_test_helpers::ReloadFrame(
+ web_view_helper.GetWebView()->MainFrameImpl());
ASSERT_EQ(4u, create_notifications.size());
ASSERT_EQ(2u, release_notifications.size());
@@ -4823,7 +4851,7 @@ TEST_F(WebFrameTest, ContextNotificationsIsolatedWorlds) {
release_notifications;
ContextLifetimeTestWebFrameClient web_frame_client(create_notifications,
release_notifications);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "context_notifications_test.html", &web_frame_client);
@@ -4864,7 +4892,7 @@ TEST_F(WebFrameTest, ContextNotificationsIsolatedWorlds) {
TEST_F(WebFrameTest, FindInPage) {
RegisterMockedHttpURLLoad("find.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find.html");
ASSERT_TRUE(web_view_helper.LocalMainFrame());
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -4935,7 +4963,7 @@ TEST_F(WebFrameTest, FindInPage) {
}
TEST_F(WebFrameTest, GetContentAsPlainText) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
// We set the size because it impacts line wrapping, which changes the
// resulting text value.
@@ -4945,7 +4973,7 @@ TEST_F(WebFrameTest, GetContentAsPlainText) {
// Generate a simple test case.
const char kSimpleSource[] = "<div>Foo bar</div><div></div>baz";
KURL test_url = ToKURL("about:blank");
- FrameTestHelpers::LoadHTMLString(frame, kSimpleSource, test_url);
+ frame_test_helpers::LoadHTMLString(frame, kSimpleSource, test_url);
// Make sure it comes out OK.
const std::string expected("Foo bar\nbaz");
@@ -4961,12 +4989,12 @@ TEST_F(WebFrameTest, GetContentAsPlainText) {
// Now do a new test with a subframe.
const char kOuterFrameSource[] = "Hello<iframe></iframe> world";
- FrameTestHelpers::LoadHTMLString(frame, kOuterFrameSource, test_url);
+ frame_test_helpers::LoadHTMLString(frame, kOuterFrameSource, test_url);
// Load something into the subframe.
WebLocalFrame* subframe = frame->FirstChild()->ToWebLocalFrame();
ASSERT_TRUE(subframe);
- FrameTestHelpers::LoadHTMLString(subframe, "sub<p>text", test_url);
+ frame_test_helpers::LoadHTMLString(subframe, "sub<p>text", test_url);
text = WebFrameContentDumper::DumpWebViewAsText(
web_view_helper.GetWebView(), std::numeric_limits<size_t>::max());
@@ -4980,14 +5008,14 @@ TEST_F(WebFrameTest, GetContentAsPlainText) {
}
TEST_F(WebFrameTest, GetFullHtmlOfPage) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
// Generate a simple test case.
const char kSimpleSource[] = "<p>Hello</p><p>World</p>";
KURL test_url = ToKURL("about:blank");
- FrameTestHelpers::LoadHTMLString(frame, kSimpleSource, test_url);
+ frame_test_helpers::LoadHTMLString(frame, kSimpleSource, test_url);
WebString text = WebFrameContentDumper::DumpWebViewAsText(
web_view_helper.GetWebView(), std::numeric_limits<size_t>::max());
@@ -4996,7 +5024,7 @@ TEST_F(WebFrameTest, GetFullHtmlOfPage) {
const std::string html = WebFrameContentDumper::DumpAsMarkup(frame).Utf8();
// Load again with the output html.
- FrameTestHelpers::LoadHTMLString(frame, html, test_url);
+ frame_test_helpers::LoadHTMLString(frame, html, test_url);
EXPECT_EQ(html, WebFrameContentDumper::DumpAsMarkup(frame).Utf8());
@@ -5015,12 +5043,12 @@ TEST_F(WebFrameTest, GetFullHtmlOfPage) {
}
class TestExecuteScriptDuringDidCreateScriptContext
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestExecuteScriptDuringDidCreateScriptContext() = default;
~TestExecuteScriptDuringDidCreateScriptContext() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidCreateScriptContext(v8::Local<v8::Context> context,
int world_id) override {
Frame()->ExecuteScript(WebScriptSource("window.history = 'replaced';"));
@@ -5031,11 +5059,12 @@ TEST_F(WebFrameTest, ExecuteScriptDuringDidCreateScriptContext) {
RegisterMockedHttpURLLoad("hello_world.html");
TestExecuteScriptDuringDidCreateScriptContext web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "hello_world.html",
&web_frame_client);
- FrameTestHelpers::ReloadFrame(web_view_helper.GetWebView()->MainFrameImpl());
+ frame_test_helpers::ReloadFrame(
+ web_view_helper.GetWebView()->MainFrameImpl());
}
class TestFindInPageClient : public mojom::blink::FindInPageClient {
@@ -5086,13 +5115,13 @@ class TestFindInPageClient : public mojom::blink::FindInPageClient {
TEST_F(WebFrameTest, FindInPageMatchRects) {
RegisterMockedHttpURLLoad("find_in_page_frame.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find_in_page_frame.html",
&frame_client);
web_view_helper.Resize(WebSize(640, 480));
web_view_helper.GetWebView()->SetMaximumLegibleScale(1.f);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
RunPendingTasks();
// Note that the 'result 19' in the <select> element is not expected to
@@ -5114,7 +5143,7 @@ TEST_F(WebFrameTest, FindInPageMatchRects) {
main_frame->EnsureTextFinder().ResetMatchCount();
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5163,8 +5192,8 @@ TEST_F(WebFrameTest, FindInPageMatchRects) {
TEST_F(WebFrameTest, FindInPageActiveIndex) {
RegisterMockedHttpURLLoad("find_match_count.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find_match_count.html",
&frame_client);
web_view_helper.GetWebView()->Resize(WebSize(640, 480));
@@ -5186,7 +5215,7 @@ TEST_F(WebFrameTest, FindInPageActiveIndex) {
main_frame->EnsureTextFinder().ResetMatchCount();
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5198,7 +5227,7 @@ TEST_F(WebFrameTest, FindInPageActiveIndex) {
mojom::StopFindAction::kStopFindActionClearSelection);
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5215,7 +5244,7 @@ TEST_F(WebFrameTest, FindInPageActiveIndex) {
main_frame->EnsureTextFinder().ResetMatchCount();
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(
kFindIdentifier, search_text_new, *options);
}
@@ -5229,8 +5258,8 @@ TEST_F(WebFrameTest, FindOnDetachedFrame) {
RegisterMockedHttpURLLoad("find_in_page.html");
RegisterMockedHttpURLLoad("find_in_page_frame.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find_in_page.html",
&frame_client);
web_view_helper.Resize(WebSize(640, 480));
@@ -5263,7 +5292,7 @@ TEST_F(WebFrameTest, FindOnDetachedFrame) {
main_frame->EnsureTextFinder().ResetMatchCount();
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5276,8 +5305,8 @@ TEST_F(WebFrameTest, FindDetachFrameBeforeScopeStrings) {
RegisterMockedHttpURLLoad("find_in_page.html");
RegisterMockedHttpURLLoad("find_in_page_frame.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find_in_page.html",
&frame_client);
web_view_helper.Resize(WebSize(640, 480));
@@ -5294,7 +5323,7 @@ TEST_F(WebFrameTest, FindDetachFrameBeforeScopeStrings) {
find_in_page_client.SetFrame(main_frame);
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
EXPECT_TRUE(frame->GetFindInPage()->FindInternal(
kFindIdentifier, search_text, *options, false));
}
@@ -5307,7 +5336,7 @@ TEST_F(WebFrameTest, FindDetachFrameBeforeScopeStrings) {
main_frame->EnsureTextFinder().ResetMatchCount();
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5320,8 +5349,8 @@ TEST_F(WebFrameTest, FindDetachFrameWhileScopingStrings) {
RegisterMockedHttpURLLoad("find_in_page.html");
RegisterMockedHttpURLLoad("find_in_page_frame.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find_in_page.html",
&frame_client);
web_view_helper.Resize(WebSize(640, 480));
@@ -5338,7 +5367,7 @@ TEST_F(WebFrameTest, FindDetachFrameWhileScopingStrings) {
find_in_page_client.SetFrame(main_frame);
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
EXPECT_TRUE(frame->GetFindInPage()->FindInternal(
kFindIdentifier, search_text, *options, false));
}
@@ -5348,7 +5377,7 @@ TEST_F(WebFrameTest, FindDetachFrameWhileScopingStrings) {
main_frame->EnsureTextFinder().ResetMatchCount();
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5358,7 +5387,7 @@ TEST_F(WebFrameTest, FindDetachFrameWhileScopingStrings) {
RemoveElementById(main_frame, "frame");
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
frame->EnsureTextFinder().StartScopingStringMatches(kFindIdentifier,
search_text, *options);
}
@@ -5369,8 +5398,8 @@ TEST_F(WebFrameTest, FindDetachFrameWhileScopingStrings) {
TEST_F(WebFrameTest, ResetMatchCount) {
RegisterMockedHttpURLLoad("find_in_generated_frame.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find_in_generated_frame.html",
&frame_client);
web_view_helper.Resize(WebSize(640, 480));
@@ -5390,7 +5419,7 @@ TEST_F(WebFrameTest, ResetMatchCount) {
EXPECT_TRUE(!!main_frame->TraverseNext());
for (WebLocalFrameImpl* frame = main_frame; frame;
- frame = static_cast<WebLocalFrameImpl*>(frame->TraverseNext())) {
+ frame = ToWebLocalFrameImpl(frame->TraverseNext())) {
EXPECT_FALSE(frame->GetFindInPage()->FindInternal(
kFindIdentifier, search_text, *options, false));
}
@@ -5404,8 +5433,8 @@ TEST_F(WebFrameTest, ResetMatchCount) {
TEST_F(WebFrameTest, SetTickmarks) {
RegisterMockedHttpURLLoad("find.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find.html", &frame_client);
web_view_helper.Resize(WebSize(640, 480));
RunPendingTasks();
@@ -5461,8 +5490,8 @@ TEST_F(WebFrameTest, SetTickmarks) {
TEST_F(WebFrameTest, FindInPageJavaScriptUpdatesDOM) {
RegisterMockedHttpURLLoad("find.html");
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find.html", &frame_client);
web_view_helper.Resize(WebSize(640, 480));
RunPendingTasks();
@@ -5541,13 +5570,13 @@ TEST_F(WebFrameTest, FindInPageJavaScriptUpdatesDOMProperOrdinal) {
"bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo "
"bar foo bar foo abc bar <div id='new_text'></div>";
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&frame_client);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadHTMLString(frame, html,
- URLTestHelpers::ToKURL(base_url_));
+ frame_test_helpers::LoadHTMLString(frame, html,
+ url_test_helpers::ToKURL(base_url_));
web_view_helper.Resize(WebSize(640, 480));
web_view_helper.GetWebView()->SetFocus(true);
RunPendingTasks();
@@ -5596,7 +5625,7 @@ TEST_F(WebFrameTest, FindInPageJavaScriptUpdatesDOMProperOrdinal) {
TEST_F(WebFrameTest, FindInPageStopFindActionKeepSelectionInAnotherDocument) {
RegisterMockedHttpURLLoad("find.html");
RegisterMockedHttpURLLoad("hello_world.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "find.html");
ASSERT_TRUE(web_view_helper.LocalMainFrame());
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -5607,7 +5636,7 @@ TEST_F(WebFrameTest, FindInPageStopFindActionKeepSelectionInAnotherDocument) {
ASSERT_TRUE(frame->GetFindInPage()->FindInternal(
kFindIdentifier, WebString::FromUTF8("foo"), *options, false));
// Move to another page.
- FrameTestHelpers::LoadFrame(frame, base_url_ + "hello_world.html");
+ frame_test_helpers::LoadFrame(frame, base_url_ + "hello_world.html");
// Stop Find-In-Page. |TextFinder::active_match_| still hold a |Range| in
// "find.html".
@@ -5620,13 +5649,13 @@ TEST_F(WebFrameTest, FindInPageStopFindActionKeepSelectionInAnotherDocument) {
TEST_F(WebFrameTest, FindInPageForcedRedoOfFindInPage) {
const WebString search_pattern = WebString::FromUTF8("bar");
const char* html = "foo bar foo foo bar";
- FrameTestHelpers::TestWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebFrameClient frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&frame_client);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadHTMLString(frame, html,
- URLTestHelpers::ToKURL(base_url_));
+ frame_test_helpers::LoadHTMLString(frame, html,
+ url_test_helpers::ToKURL(base_url_));
web_view_helper.Resize(WebSize(640, 480));
web_view_helper.GetWebView()->SetFocus(true);
RunPendingTasks();
@@ -5700,7 +5729,7 @@ TEST_F(WebFrameTest, SelectRange) {
RegisterMockedHttpURLLoad("select_range_basic.html");
RegisterMockedHttpURLLoad("select_range_scroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_basic.html",
&web_view_helper);
frame = web_view_helper.LocalMainFrame();
@@ -5735,7 +5764,7 @@ TEST_F(WebFrameTest, SelectRange) {
TEST_F(WebFrameTest, SelectRangeDefaultHandleVisibility) {
RegisterMockedHttpURLLoad("select_range_basic.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_basic.html",
&web_view_helper);
@@ -5751,7 +5780,7 @@ TEST_F(WebFrameTest, SelectRangeDefaultHandleVisibility) {
TEST_F(WebFrameTest, SelectRangeHideHandle) {
RegisterMockedHttpURLLoad("select_range_basic.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_basic.html",
&web_view_helper);
@@ -5766,7 +5795,7 @@ TEST_F(WebFrameTest, SelectRangeHideHandle) {
TEST_F(WebFrameTest, SelectRangeShowHandle) {
RegisterMockedHttpURLLoad("select_range_basic.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_basic.html",
&web_view_helper);
@@ -5781,7 +5810,7 @@ TEST_F(WebFrameTest, SelectRangeShowHandle) {
TEST_F(WebFrameTest, SelectRangePreserveHandleVisibility) {
RegisterMockedHttpURLLoad("select_range_basic.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_basic.html",
&web_view_helper);
@@ -5811,7 +5840,7 @@ TEST_F(WebFrameTest, SelectRangeInIframe) {
RegisterMockedHttpURLLoad("select_range_iframe.html");
RegisterMockedHttpURLLoad("select_range_basic.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_iframe.html",
&web_view_helper);
frame = web_view_helper.GetWebView()->MainFrame();
@@ -5839,7 +5868,7 @@ TEST_F(WebFrameTest, SelectRangeDivContentEditable) {
// Select the middle of an editable element, then try to extend the selection
// to the top of the document. The selection range should be clipped to the
// bounds of the editable element.
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_div_editable.html",
&web_view_helper);
frame = web_view_helper.LocalMainFrame();
@@ -5880,7 +5909,7 @@ TEST_F(WebFrameTest, DISABLED_SelectRangeSpanContentEditable) {
// to the top of the document.
// The selection range should be clipped to the bounds of the editable
// element.
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_span_editable.html",
&web_view_helper);
frame = web_view_helper.LocalMainFrame();
@@ -5911,7 +5940,7 @@ TEST_F(WebFrameTest, DISABLED_SelectRangeSpanContentEditable) {
TEST_F(WebFrameTest, SelectRangeCanMoveSelectionStart) {
RegisterMockedHttpURLLoad("text_selection.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "text_selection.html",
&web_view_helper);
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -5965,7 +5994,7 @@ TEST_F(WebFrameTest, SelectRangeCanMoveSelectionStart) {
TEST_F(WebFrameTest, SelectRangeCanMoveSelectionEnd) {
RegisterMockedHttpURLLoad("text_selection.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "text_selection.html",
&web_view_helper);
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -6024,7 +6053,7 @@ TEST_F(WebFrameTest, MoveRangeSelectionExtent) {
RegisterMockedHttpURLLoad("move_range_selection_extent.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "move_range_selection_extent.html",
&web_view_helper);
frame = web_view_helper.LocalMainFrame();
@@ -6061,7 +6090,7 @@ TEST_F(WebFrameTest, MoveRangeSelectionExtentCannotCollapse) {
RegisterMockedHttpURLLoad("move_range_selection_extent.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "move_range_selection_extent.html",
&web_view_helper);
frame = web_view_helper.LocalMainFrame();
@@ -6087,7 +6116,7 @@ TEST_F(WebFrameTest, MoveRangeSelectionExtentScollsInputField) {
RegisterMockedHttpURLLoad("move_range_selection_extent_input_field.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(
base_url_ + "move_range_selection_extent_input_field.html",
&web_view_helper);
@@ -6137,11 +6166,11 @@ TEST_F(WebFrameTest, SmartClipData) {
WebRect clip_rect;
RegisterMockedHttpURLLoad("Ahem.ttf");
RegisterMockedHttpURLLoad("smartclip.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "smartclip.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
web_view_helper.Resize(WebSize(500, 500));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
WebRect crop_rect(300, 125, 152, 50);
frame->ExtractSmartClipData(crop_rect, clip_text, clip_html, clip_rect);
EXPECT_STREQ(kExpectedClipText, clip_text.Utf8().c_str());
@@ -6174,11 +6203,11 @@ TEST_F(WebFrameTest, SmartClipDataWithPinchZoom) {
WebRect clip_rect;
RegisterMockedHttpURLLoad("Ahem.ttf");
RegisterMockedHttpURLLoad("smartclip.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "smartclip.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
web_view_helper.Resize(WebSize(500, 500));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view_helper.GetWebView()->SetPageScaleFactor(1.5);
web_view_helper.GetWebView()->SetVisualViewportOffset(
WebFloatPoint(167, 100));
@@ -6194,12 +6223,12 @@ TEST_F(WebFrameTest, SmartClipReturnsEmptyStringsWhenUserSelectIsNone) {
WebRect clip_rect;
RegisterMockedHttpURLLoad("Ahem.ttf");
RegisterMockedHttpURLLoad("smartclip_user_select_none.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ +
"smartclip_user_select_none.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
web_view_helper.Resize(WebSize(500, 500));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
WebRect crop_rect(0, 0, 100, 100);
frame->ExtractSmartClipData(crop_rect, clip_text, clip_html, clip_rect);
EXPECT_STREQ("", clip_text.Utf8().c_str());
@@ -6212,12 +6241,12 @@ TEST_F(WebFrameTest, SmartClipDoesNotCrashPositionReversed) {
WebRect clip_rect;
RegisterMockedHttpURLLoad("Ahem.ttf");
RegisterMockedHttpURLLoad("smartclip_reversed_positions.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ +
"smartclip_reversed_positions.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
web_view_helper.Resize(WebSize(500, 500));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
// Left upper corner of the rect will be end position in the DOM hierarchy.
WebRect crop_rect(30, 110, 400, 250);
// This should not still crash. See crbug.com/589082 for more details.
@@ -6234,7 +6263,7 @@ static int ComputeOffset(LayoutObject* layout_object, int x, int y) {
// http://crbug.com/238334.
TEST_F(WebFrameTest, DISABLED_PositionForPointTest) {
RegisterMockedHttpURLLoad("select_range_span_editable.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "select_range_span_editable.html",
&web_view_helper);
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
@@ -6263,7 +6292,7 @@ TEST_F(WebFrameTest, DISABLED_PositionForPointTest) {
TEST_F(WebFrameTest, SelectRangeStaysHorizontallyAlignedWhenMoved) {
RegisterMockedHttpURLLoad("move_caret.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "move_caret.html",
&web_view_helper);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -6309,7 +6338,7 @@ TEST_F(WebFrameTest, MoveCaretStaysHorizontallyAlignedWhenMoved) {
WebLocalFrameImpl* frame;
RegisterMockedHttpURLLoad("move_caret.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "move_caret.html",
&web_view_helper);
frame = (WebLocalFrameImpl*)web_view_helper.GetWebView()->MainFrame();
@@ -6355,9 +6384,9 @@ class CompositedSelectionBoundsTest
void RunTestWithNoSelection(const char* test_file) {
RegisterMockedHttpURLLoad(test_file);
web_view_helper_.GetWebView()->SetFocus(true);
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- base_url_ + test_file);
- web_view_helper_.GetWebView()->UpdateAllLifecyclePhases();
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), base_url_ + test_file);
+ UpdateAllLifecyclePhases(web_view_helper_.GetWebView());
cc::LayerTreeHost* layer_tree_host =
web_view_client_.layer_tree_view()->layer_tree_host();
@@ -6371,9 +6400,9 @@ class CompositedSelectionBoundsTest
void RunTest(const char* test_file) {
RegisterMockedHttpURLLoad(test_file);
web_view_helper_.GetWebView()->SetFocus(true);
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- base_url_ + test_file);
- web_view_helper_.GetWebView()->UpdateAllLifecyclePhases();
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), base_url_ + test_file);
+ UpdateAllLifecyclePhases(web_view_helper_.GetWebView());
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::Local<v8::Value> result =
@@ -6547,8 +6576,8 @@ class CompositedSelectionBoundsTest
: clm->MainGraphicsLayer();
}
- FrameTestHelpers::TestWebViewClient web_view_client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::TestWebViewClient web_view_client_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
TEST_F(CompositedSelectionBoundsTest, None) {
@@ -6599,12 +6628,12 @@ TEST_F(CompositedSelectionBoundsTest, InputScrolled) {
#endif
class TestSubstituteDataWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestSubstituteDataWebFrameClient() : commit_called_(false) {}
~TestSubstituteDataWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidFailProvisionalLoad(const WebURLError& error,
WebHistoryCommitType) override {
Frame()->CommitDataNavigation(
@@ -6618,7 +6647,7 @@ class TestSubstituteDataWebFrameClient
WebHistoryCommitType,
WebGlobalObjectReusePolicy) override {
if (Frame()->GetDocumentLoader()->GetResponse().Url() !=
- WebURL(URLTestHelpers::ToKURL("about:blank")))
+ WebURL(url_test_helpers::ToKURL("about:blank")))
commit_called_ = true;
}
@@ -6631,7 +6660,7 @@ class TestSubstituteDataWebFrameClient
TEST_F(WebFrameTest, ReplaceNavigationAfterHistoryNavigation) {
TestSubstituteDataWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", &web_frame_client);
WebLocalFrame* frame = web_view_helper.GetWebView()->MainFrameImpl();
@@ -6644,7 +6673,7 @@ TEST_F(WebFrameTest, ReplaceNavigationAfterHistoryNavigation) {
std::string error_url = "http://0.0.0.0";
ResourceError error = ResourceError::Failure(ToKURL(error_url));
WebURLResponse response;
- response.SetURL(URLTestHelpers::ToKURL(error_url));
+ response.SetURL(url_test_helpers::ToKURL(error_url));
response.SetMIMEType("text/html");
response.SetHTTPStatusCode(500);
WebHistoryItem error_history_item;
@@ -6652,9 +6681,9 @@ TEST_F(WebFrameTest, ReplaceNavigationAfterHistoryNavigation) {
error_history_item.SetURLString(
WebString::FromUTF8(error_url.c_str(), error_url.length()));
Platform::Current()->GetURLLoaderMockFactory()->RegisterErrorURL(
- URLTestHelpers::ToKURL(error_url), response, error);
- FrameTestHelpers::LoadHistoryItem(frame, error_history_item,
- mojom::FetchCacheMode::kDefault);
+ url_test_helpers::ToKURL(error_url), response, error);
+ frame_test_helpers::LoadHistoryItem(frame, error_history_item,
+ mojom::FetchCacheMode::kDefault);
WebString text = WebFrameContentDumper::DumpWebViewAsText(
web_view_helper.GetWebView(), std::numeric_limits<size_t>::max());
EXPECT_EQ("This should appear", text.Utf8());
@@ -6662,12 +6691,12 @@ TEST_F(WebFrameTest, ReplaceNavigationAfterHistoryNavigation) {
}
class TestWillInsertBodyWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestWillInsertBodyWebFrameClient() : did_load_(false) {}
~TestWillInsertBodyWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidCommitProvisionalLoad(const WebHistoryItem&,
WebHistoryCommitType,
WebGlobalObjectReusePolicy) override {
@@ -6681,7 +6710,7 @@ TEST_F(WebFrameTest, HTMLDocument) {
RegisterMockedHttpURLLoad("clipped-body.html");
TestWillInsertBodyWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "clipped-body.html",
&web_frame_client);
@@ -6692,14 +6721,14 @@ TEST_F(WebFrameTest, EmptyDocument) {
RegisterMockedHttpURLLoad("frameserializer/svg/green_rectangle.svg");
TestWillInsertBodyWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
EXPECT_FALSE(web_frame_client.did_load_);
}
TEST_F(WebFrameTest, MoveCaretSelectionTowardsWindowPointWithNoSelection) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
WebFrame* frame = web_view_helper.GetWebView()->MainFrame();
@@ -6734,7 +6763,7 @@ class TextCheckClient : public WebTextCheckClient {
TEST_F(WebFrameTest, ReplaceMisspelledRange) {
RegisterMockedHttpURLLoad("spell.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "spell.html", &web_view_helper);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -6745,7 +6774,7 @@ TEST_F(WebFrameTest, ReplaceMisspelledRange) {
Element* element = document->getElementById("data");
web_view_helper.GetWebView()->GetSettings()->SetEditingBehavior(
- WebSettings::kEditingBehaviorWin);
+ WebSettings::EditingBehavior::kWin);
element->focus();
NonThrowableExceptionState exception_state;
@@ -6780,7 +6809,7 @@ TEST_F(WebFrameTest, ReplaceMisspelledRange) {
TEST_F(WebFrameTest, RemoveSpellingMarkers) {
RegisterMockedHttpURLLoad("spell.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "spell.html", &web_view_helper);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -6791,7 +6820,7 @@ TEST_F(WebFrameTest, RemoveSpellingMarkers) {
Element* element = document->getElementById("data");
web_view_helper.GetWebView()->GetSettings()->SetEditingBehavior(
- WebSettings::kEditingBehaviorWin);
+ WebSettings::EditingBehavior::kWin);
element->focus();
NonThrowableExceptionState exception_state;
@@ -6830,7 +6859,7 @@ static void GetSpellingMarkerOffsets(WebVector<unsigned>* offsets,
TEST_F(WebFrameTest, RemoveSpellingMarkersUnderWords) {
RegisterMockedHttpURLLoad("spell.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "spell.html", &web_view_helper);
WebLocalFrameImpl* web_frame = web_view_helper.LocalMainFrame();
@@ -6842,7 +6871,7 @@ TEST_F(WebFrameTest, RemoveSpellingMarkersUnderWords) {
Element* element = document->getElementById("data");
web_view_helper.GetWebView()->GetSettings()->SetEditingBehavior(
- WebSettings::kEditingBehaviorWin);
+ WebSettings::EditingBehavior::kWin);
element->focus();
NonThrowableExceptionState exception_state;
@@ -6910,7 +6939,7 @@ class StubbornTextCheckClient : public WebTextCheckClient {
TEST_F(WebFrameTest, SlowSpellcheckMarkerPosition) {
RegisterMockedHttpURLLoad("spell.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "spell.html", &web_view_helper);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -6921,7 +6950,7 @@ TEST_F(WebFrameTest, SlowSpellcheckMarkerPosition) {
Element* element = document->getElementById("data");
web_view_helper.GetWebView()->GetSettings()->SetEditingBehavior(
- WebSettings::kEditingBehaviorWin);
+ WebSettings::EditingBehavior::kWin);
element->focus();
NonThrowableExceptionState exception_state;
@@ -6944,7 +6973,7 @@ TEST_F(WebFrameTest, SlowSpellcheckMarkerPosition) {
TEST_F(WebFrameTest, SpellcheckResultErasesMarkers) {
RegisterMockedHttpURLLoad("spell.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "spell.html", &web_view_helper);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -6955,7 +6984,7 @@ TEST_F(WebFrameTest, SpellcheckResultErasesMarkers) {
Element* element = document->getElementById("data");
web_view_helper.GetWebView()->GetSettings()->SetEditingBehavior(
- WebSettings::kEditingBehaviorWin);
+ WebSettings::EditingBehavior::kWin);
element->focus();
NonThrowableExceptionState exception_state;
@@ -6980,7 +7009,7 @@ TEST_F(WebFrameTest, SpellcheckResultErasesMarkers) {
TEST_F(WebFrameTest, SpellcheckResultsSavedInDocument) {
RegisterMockedHttpURLLoad("spell.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
InitializeTextSelectionWebView(base_url_ + "spell.html", &web_view_helper);
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -6991,7 +7020,7 @@ TEST_F(WebFrameTest, SpellcheckResultsSavedInDocument) {
Element* element = document->getElementById("data");
web_view_helper.GetWebView()->GetSettings()->SetEditingBehavior(
- WebSettings::kEditingBehaviorWin);
+ WebSettings::EditingBehavior::kWin);
element->focus();
NonThrowableExceptionState exception_state;
@@ -7027,12 +7056,12 @@ TEST_F(WebFrameTest, SpellcheckResultsSavedInDocument) {
}
class TestAccessInitialDocumentWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestAccessInitialDocumentWebFrameClient() = default;
~TestAccessInitialDocumentWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidAccessInitialDocument() override { ++did_access_initial_document_; }
// !!!!!!!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!!!!!!
@@ -7046,13 +7075,13 @@ class TestAccessInitialDocumentWebFrameClient
TEST_F(WebFrameTest, DidAccessInitialDocumentBody) {
TestAccessInitialDocumentWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
RunPendingTasks();
EXPECT_EQ(0, web_frame_client.did_access_initial_document_);
// Create another window that will try to access it.
- FrameTestHelpers::WebViewHelper new_web_view_helper;
+ frame_test_helpers::WebViewHelper new_web_view_helper;
WebViewImpl* new_view = new_web_view_helper.InitializeWithOpener(
web_view_helper.GetWebView()->MainFrame());
RunPendingTasks();
@@ -7069,13 +7098,13 @@ TEST_F(WebFrameTest, DidAccessInitialDocumentBody) {
TEST_F(WebFrameTest, DidAccessInitialDocumentOpen) {
TestAccessInitialDocumentWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
RunPendingTasks();
EXPECT_EQ(0, web_frame_client.did_access_initial_document_);
// Create another window that will try to access it.
- FrameTestHelpers::WebViewHelper new_web_view_helper;
+ frame_test_helpers::WebViewHelper new_web_view_helper;
WebViewImpl* new_view = new_web_view_helper.InitializeWithOpener(
web_view_helper.GetWebView()->MainFrame());
RunPendingTasks();
@@ -7093,13 +7122,13 @@ TEST_F(WebFrameTest, DidAccessInitialDocumentOpen) {
TEST_F(WebFrameTest, DidAccessInitialDocumentNavigator) {
TestAccessInitialDocumentWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
RunPendingTasks();
EXPECT_EQ(0, web_frame_client.did_access_initial_document_);
// Create another window that will try to access it.
- FrameTestHelpers::WebViewHelper new_web_view_helper;
+ frame_test_helpers::WebViewHelper new_web_view_helper;
WebViewImpl* new_view = new_web_view_helper.InitializeWithOpener(
web_view_helper.GetWebView()->MainFrame());
RunPendingTasks();
@@ -7116,15 +7145,15 @@ TEST_F(WebFrameTest, DidAccessInitialDocumentNavigator) {
TEST_F(WebFrameTest, DidAccessInitialDocumentViaJavascriptUrl) {
TestAccessInitialDocumentWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
RunPendingTasks();
EXPECT_EQ(0, web_frame_client.did_access_initial_document_);
// Access the initial document from a javascript: URL.
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- "javascript:document.body.appendChild(document."
- "createTextNode('Modified'))");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ "javascript:document.body.appendChild(document."
+ "createTextNode('Modified'))");
EXPECT_EQ(1, web_frame_client.did_access_initial_document_);
web_view_helper.Reset();
@@ -7132,13 +7161,13 @@ TEST_F(WebFrameTest, DidAccessInitialDocumentViaJavascriptUrl) {
TEST_F(WebFrameTest, DidAccessInitialDocumentBodyBeforeModalDialog) {
TestAccessInitialDocumentWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
RunPendingTasks();
EXPECT_EQ(0, web_frame_client.did_access_initial_document_);
// Create another window that will try to access it.
- FrameTestHelpers::WebViewHelper new_web_view_helper;
+ frame_test_helpers::WebViewHelper new_web_view_helper;
WebViewImpl* new_view = new_web_view_helper.InitializeWithOpener(
web_view_helper.GetWebView()->MainFrame());
RunPendingTasks();
@@ -7164,13 +7193,13 @@ TEST_F(WebFrameTest, DidAccessInitialDocumentBodyBeforeModalDialog) {
TEST_F(WebFrameTest, DidWriteToInitialDocumentBeforeModalDialog) {
TestAccessInitialDocumentWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(&web_frame_client);
RunPendingTasks();
EXPECT_EQ(0, web_frame_client.did_access_initial_document_);
// Create another window that will try to access it.
- FrameTestHelpers::WebViewHelper new_web_view_helper;
+ frame_test_helpers::WebViewHelper new_web_view_helper;
WebViewImpl* new_view = new_web_view_helper.InitializeWithOpener(
web_view_helper.GetWebView()->MainFrame());
RunPendingTasks();
@@ -7196,7 +7225,7 @@ TEST_F(WebFrameTest, DidWriteToInitialDocumentBeforeModalDialog) {
web_view_helper.Reset();
}
-class TestScrolledFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class TestScrolledFrameClient : public frame_test_helpers::TestWebFrameClient {
public:
TestScrolledFrameClient() { Reset(); }
~TestScrolledFrameClient() override = default;
@@ -7228,7 +7257,7 @@ TEST_F(WebFrameTest, CompositorScrollIsUserScrollLongPage) {
// Make sure we initialize to minimum scale, even if the window size
// only becomes available after the load begins.
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html", &client);
web_view_helper.Resize(WebSize(1000, 1000));
@@ -7247,7 +7276,8 @@ TEST_F(WebFrameTest, CompositorScrollIsUserScrollLongPage) {
// Do a compositor scroll, verify that this is counted as a user scroll.
scrollable_area->DidScroll(FloatPoint(0, 1));
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.7f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.7f, 0,
+ cc::BrowserControlsState::kBoth});
EXPECT_TRUE(client.WasFrameScrolled());
EXPECT_TRUE(initial_scroll_state.was_scrolled_by_user);
@@ -7257,7 +7287,8 @@ TEST_F(WebFrameTest, CompositorScrollIsUserScrollLongPage) {
// The page scale 1.0f and scroll.
scrollable_area->DidScroll(FloatPoint(0, 2));
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.0f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f, 0,
+ cc::BrowserControlsState::kBoth});
EXPECT_TRUE(client.WasFrameScrolled());
EXPECT_TRUE(initial_scroll_state.was_scrolled_by_user);
client.Reset();
@@ -7266,7 +7297,8 @@ TEST_F(WebFrameTest, CompositorScrollIsUserScrollLongPage) {
// No scroll event if there is no scroll delta.
scrollable_area->DidScroll(FloatPoint(0, 2));
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1.0f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f, 0,
+ cc::BrowserControlsState::kBoth});
EXPECT_FALSE(client.WasFrameScrolled());
EXPECT_FALSE(initial_scroll_state.was_scrolled_by_user);
client.Reset();
@@ -7274,7 +7306,8 @@ TEST_F(WebFrameTest, CompositorScrollIsUserScrollLongPage) {
// Non zero page scale and scroll.
scrollable_area->DidScroll(FloatPoint(9, 15));
web_view_helper.GetWebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 0.6f, 0});
+ {gfx::ScrollOffset(), gfx::Vector2dF(), 0.6f, 0,
+ cc::BrowserControlsState::kBoth});
EXPECT_TRUE(client.WasFrameScrolled());
EXPECT_TRUE(initial_scroll_state.was_scrolled_by_user);
client.Reset();
@@ -7311,7 +7344,7 @@ TEST_F(WebFrameTest, SiteForCookiesForRedirect) {
Platform::Current()->GetURLLoaderMockFactory()->RegisterURL(
redirect_url, final_response, file_path);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "first_party_redirect.html");
EXPECT_TRUE(web_view_helper.GetWebView()
->MainFrameImpl()
@@ -7319,46 +7352,47 @@ TEST_F(WebFrameTest, SiteForCookiesForRedirect) {
.SiteForCookies() == redirect_url);
}
-class TestNewWindowWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class TestNewWindowWebViewClient
+ : public frame_test_helpers::TestWebViewClient {
public:
TestNewWindowWebViewClient() = default;
~TestNewWindowWebViewClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
WebView* CreateView(WebLocalFrame*,
const WebURLRequest&,
const WebWindowFeatures&,
const WebString&,
WebNavigationPolicy,
bool,
- WebSandboxFlags) override {
+ WebSandboxFlags,
+ const SessionStorageNamespaceId&) override {
EXPECT_TRUE(false);
return nullptr;
}
};
class TestNewWindowWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
- TestNewWindowWebFrameClient() : decide_policy_call_count_(0) {}
+ TestNewWindowWebFrameClient() : begin_navigation_call_count_(0) {}
~TestNewWindowWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
- WebNavigationPolicy DecidePolicyForNavigation(
- const NavigationPolicyInfo& info) override {
+ // frame_test_helpers::TestWebFrameClient:
+ void BeginNavigation(std::unique_ptr<WebNavigationInfo> info) override {
if (ignore_navigations_) {
- decide_policy_call_count_++;
- return kWebNavigationPolicyIgnore;
+ begin_navigation_call_count_++;
+ return;
}
- return info.default_policy;
+ TestWebFrameClient::BeginNavigation(std::move(info));
}
- int DecidePolicyCallCount() const { return decide_policy_call_count_; }
+ int BeginNavigationCallCount() const { return begin_navigation_call_count_; }
void IgnoreNavigations() { ignore_navigations_ = true; }
private:
bool ignore_navigations_ = false;
- int decide_policy_call_count_;
+ int begin_navigation_call_count_;
};
TEST_F(WebFrameTest, ModifiedClickNewWindow) {
@@ -7368,7 +7402,7 @@ TEST_F(WebFrameTest, ModifiedClickNewWindow) {
RegisterMockedHttpURLLoad("hello_world.html");
TestNewWindowWebViewClient web_view_client;
TestNewWindowWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "ctrl_click.html",
&web_frame_client, &web_view_client);
@@ -7378,13 +7412,13 @@ TEST_F(WebFrameTest, ModifiedClickNewWindow) {
KURL destination = ToKURL(base_url_ + "hello_world.html");
// ctrl+click event
- MouseEventInit mouse_initializer;
- mouse_initializer.setView(document->domWindow());
- mouse_initializer.setButton(1);
- mouse_initializer.setCtrlKey(true);
+ MouseEventInit* mouse_initializer = MouseEventInit::Create();
+ mouse_initializer->setView(document->domWindow());
+ mouse_initializer->setButton(1);
+ mouse_initializer->setCtrlKey(true);
Event* event =
- MouseEvent::Create(nullptr, EventTypeNames::click, mouse_initializer);
+ MouseEvent::Create(nullptr, event_type_names::kClick, mouse_initializer);
FrameLoadRequest frame_request(document, ResourceRequest(destination));
frame_request.SetTriggeringEventInfo(
WebTriggeringEventInfo::kFromTrustedEvent);
@@ -7395,16 +7429,16 @@ TEST_F(WebFrameTest, ModifiedClickNewWindow) {
->Loader()
.StartNavigation(frame_request, WebFrameLoadType::kStandard,
NavigationPolicyFromEvent(event));
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view_helper.LocalMainFrame());
- // decidePolicyForNavigation should be called for the ctrl+click.
- EXPECT_EQ(1, web_frame_client.DecidePolicyCallCount());
+ // BeginNavigation should be called for the ctrl+click.
+ EXPECT_EQ(1, web_frame_client.BeginNavigationCallCount());
}
TEST_F(WebFrameTest, BackToReload) {
RegisterMockedHttpURLLoad("fragment_middle_click.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fragment_middle_click.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
const FrameLoader& main_frame_loader =
@@ -7414,23 +7448,23 @@ TEST_F(WebFrameTest, BackToReload) {
EXPECT_TRUE(first_item);
RegisterMockedHttpURLLoad("white-1x1.png");
- FrameTestHelpers::LoadFrame(frame, base_url_ + "white-1x1.png");
+ frame_test_helpers::LoadFrame(frame, base_url_ + "white-1x1.png");
EXPECT_NE(first_item.Get(),
main_frame_loader.GetDocumentLoader()->GetHistoryItem());
- FrameTestHelpers::LoadHistoryItem(frame, WebHistoryItem(first_item.Get()),
- mojom::FetchCacheMode::kDefault);
+ frame_test_helpers::LoadHistoryItem(frame, WebHistoryItem(first_item.Get()),
+ mojom::FetchCacheMode::kDefault);
EXPECT_EQ(first_item.Get(),
main_frame_loader.GetDocumentLoader()->GetHistoryItem());
- FrameTestHelpers::ReloadFrame(frame);
+ frame_test_helpers::ReloadFrame(frame);
EXPECT_EQ(mojom::FetchCacheMode::kValidateCache,
frame->GetDocumentLoader()->GetRequest().GetCacheMode());
}
TEST_F(WebFrameTest, BackDuringChildFrameReload) {
RegisterMockedHttpURLLoad("page_with_blank_iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "page_with_blank_iframe.html");
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
const FrameLoader& main_frame_loader = main_frame->GetFrame()->Loader();
@@ -7455,7 +7489,7 @@ TEST_F(WebFrameTest, BackDuringChildFrameReload) {
false, base::UnguessableToken::Create(), nullptr /* navigation_params */,
nullptr /* extra_data */);
- FrameTestHelpers::ReloadFrame(child_frame);
+ frame_test_helpers::ReloadFrame(child_frame);
EXPECT_EQ(item.UrlString(), main_frame->GetDocument().Url().GetString());
EXPECT_EQ(item.UrlString(), WebString(main_frame_loader.GetDocumentLoader()
->GetHistoryItem()
@@ -7464,20 +7498,20 @@ TEST_F(WebFrameTest, BackDuringChildFrameReload) {
TEST_F(WebFrameTest, ReloadPost) {
RegisterMockedHttpURLLoad("reload_post.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "reload_post.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- "javascript:document.forms[0].submit()");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ "javascript:document.forms[0].submit()");
// Pump requests one more time after the javascript URL has executed to
// trigger the actual POST load request.
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view_helper.LocalMainFrame());
EXPECT_EQ(WebString::FromUTF8("POST"),
frame->GetDocumentLoader()->GetRequest().HttpMethod());
- FrameTestHelpers::ReloadFrame(frame);
+ frame_test_helpers::ReloadFrame(frame);
EXPECT_EQ(mojom::FetchCacheMode::kValidateCache,
frame->GetDocumentLoader()->GetRequest().GetCacheMode());
EXPECT_EQ(kWebNavigationTypeFormResubmitted,
@@ -7486,7 +7520,7 @@ TEST_F(WebFrameTest, ReloadPost) {
TEST_F(WebFrameTest, LoadHistoryItemReload) {
RegisterMockedHttpURLLoad("fragment_middle_click.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "fragment_middle_click.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
const FrameLoader& main_frame_loader =
@@ -7496,13 +7530,13 @@ TEST_F(WebFrameTest, LoadHistoryItemReload) {
EXPECT_TRUE(first_item);
RegisterMockedHttpURLLoad("white-1x1.png");
- FrameTestHelpers::LoadFrame(frame, base_url_ + "white-1x1.png");
+ frame_test_helpers::LoadFrame(frame, base_url_ + "white-1x1.png");
EXPECT_NE(first_item.Get(),
main_frame_loader.GetDocumentLoader()->GetHistoryItem());
// Cache policy overrides should take.
- FrameTestHelpers::LoadHistoryItem(frame, WebHistoryItem(first_item),
- mojom::FetchCacheMode::kValidateCache);
+ frame_test_helpers::LoadHistoryItem(frame, WebHistoryItem(first_item),
+ mojom::FetchCacheMode::kValidateCache);
EXPECT_EQ(first_item.Get(),
main_frame_loader.GetDocumentLoader()->GetHistoryItem());
EXPECT_EQ(mojom::FetchCacheMode::kValidateCache,
@@ -7510,7 +7544,7 @@ TEST_F(WebFrameTest, LoadHistoryItemReload) {
}
class TestCachePolicyWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestCachePolicyWebFrameClient()
: cache_mode_(mojom::FetchCacheMode::kDefault),
@@ -7524,7 +7558,7 @@ class TestCachePolicyWebFrameClient
}
size_t ChildFrameCreationCount() const { return child_clients_.size(); }
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
WebLocalFrame* CreateChildFrame(
WebLocalFrame* parent,
WebTreeScopeType scope,
@@ -7532,7 +7566,8 @@ class TestCachePolicyWebFrameClient
const WebString&,
WebSandboxFlags,
const ParsedFeaturePolicy&,
- const WebFrameOwnerProperties& frame_owner_properties) override {
+ const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType) override {
auto child = std::make_unique<TestCachePolicyWebFrameClient>();
auto* child_ptr = child.get();
child_clients_.push_back(std::move(child));
@@ -7554,7 +7589,7 @@ TEST_F(WebFrameTest, ReloadIframe) {
RegisterMockedHttpURLLoad("visible_iframe.html");
TestCachePolicyWebFrameClient main_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "iframe_reload.html",
&main_frame_client);
WebLocalFrameImpl* main_frame = web_view_helper.LocalMainFrame();
@@ -7569,7 +7604,7 @@ TEST_F(WebFrameTest, ReloadIframe) {
EXPECT_EQ(1, child_client->WillSendRequestCallCount());
EXPECT_EQ(mojom::FetchCacheMode::kDefault, child_client->GetCacheMode());
- FrameTestHelpers::ReloadFrame(main_frame);
+ frame_test_helpers::ReloadFrame(main_frame);
// A new child WebLocalFrame should have been created with a new client.
ASSERT_EQ(2U, main_frame_client.ChildFrameCreationCount());
@@ -7591,12 +7626,12 @@ TEST_F(WebFrameTest, ReloadIframe) {
}
class TestSameDocumentWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestSameDocumentWebFrameClient() : frame_load_type_reload_seen_(false) {}
~TestSameDocumentWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void WillSendRequest(WebURLRequest&) override {
FrameLoader& frame_loader =
ToWebLocalFrameImpl(Frame())->GetFrame()->Loader();
@@ -7614,7 +7649,7 @@ class TestSameDocumentWebFrameClient
TEST_F(WebFrameTest, NavigateToSame) {
RegisterMockedHttpURLLoad("navigate_to_same.html");
TestSameDocumentWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "navigate_to_same.html",
&client);
EXPECT_FALSE(client.FrameLoadTypeReloadSeen());
@@ -7628,19 +7663,19 @@ TEST_F(WebFrameTest, NavigateToSame) {
ToLocalFrame(web_view_helper.GetWebView()->GetPage()->MainFrame())
->Loader()
.StartNavigation(frame_request);
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view_helper.LocalMainFrame());
EXPECT_TRUE(client.FrameLoadTypeReloadSeen());
}
class TestSameDocumentWithImageWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestSameDocumentWithImageWebFrameClient() : num_of_image_requests_(0) {}
~TestSameDocumentWithImageWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void WillSendRequest(WebURLRequest& request) override {
if (request.GetRequestContext() == mojom::RequestContextType::IMAGE) {
num_of_image_requests_++;
@@ -7658,14 +7693,14 @@ TEST_F(WebFrameTest, NavigateToSameNoConditionalRequestForSubresource) {
RegisterMockedHttpURLLoad("foo_with_image.html");
RegisterMockedHttpURLLoad("white-1x1.png");
TestSameDocumentWithImageWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo_with_image.html", &client,
nullptr, nullptr,
&ConfigureLoadsImagesAutomatically);
WebCache::Clear();
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "foo_with_image.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "foo_with_image.html");
// 2 images are requested, and each triggers 2 willSendRequest() calls,
// once for preloading and once for the real request.
@@ -7673,7 +7708,7 @@ TEST_F(WebFrameTest, NavigateToSameNoConditionalRequestForSubresource) {
}
TEST_F(WebFrameTest, WebNodeImageContents) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -7685,7 +7720,7 @@ TEST_F(WebFrameTest, WebNodeImageContents) {
// Load up the image and test that we can extract the contents.
KURL test_url = ToKURL("about:blank");
- FrameTestHelpers::LoadHTMLString(frame, kBluePNG, test_url);
+ frame_test_helpers::LoadHTMLString(frame, kBluePNG, test_url);
WebNode node = frame->GetDocument().Body().FirstChild();
EXPECT_TRUE(node.IsElementNode());
@@ -7698,7 +7733,7 @@ TEST_F(WebFrameTest, WebNodeImageContents) {
}
TEST_F(WebFrameTest, WebNodeImageContentsWithOrientation) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -7734,7 +7769,7 @@ TEST_F(WebFrameTest, WebNodeImageContentsWithOrientation) {
// Load up the image and test that we can extract the contents.
KURL test_url = ToKURL("about:blank");
- FrameTestHelpers::LoadHTMLString(frame, kBlueJPGWithOrientation, test_url);
+ frame_test_helpers::LoadHTMLString(frame, kBlueJPGWithOrientation, test_url);
WebNode node = frame->GetDocument().Body().FirstChild();
EXPECT_TRUE(node.IsElementNode());
@@ -7753,13 +7788,13 @@ TEST_F(WebFrameTest, WebNodeImageContentsWithOrientation) {
}
class TestStartStopCallbackWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestStartStopCallbackWebFrameClient()
: start_loading_count_(0), stop_loading_count_(0) {}
~TestStartStopCallbackWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidStartLoading() override {
TestWebFrameClient::DidStartLoading();
start_loading_count_++;
@@ -7780,7 +7815,7 @@ class TestStartStopCallbackWebFrameClient
TEST_F(WebFrameTest, PushStateStartsAndStops) {
RegisterMockedHttpURLLoad("push_state.html");
TestStartStopCallbackWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "push_state.html", &client);
EXPECT_EQ(client.StartLoadingCount(), 2);
@@ -7788,13 +7823,13 @@ TEST_F(WebFrameTest, PushStateStartsAndStops) {
}
class TestDidNavigateCommitTypeWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestDidNavigateCommitTypeWebFrameClient()
: last_commit_type_(kWebHistoryInertCommit) {}
~TestDidNavigateCommitTypeWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidFinishSameDocumentNavigation(const WebHistoryItem&,
WebHistoryCommitType type,
bool content_initiated) override {
@@ -7810,7 +7845,7 @@ class TestDidNavigateCommitTypeWebFrameClient
TEST_F(WebFrameTest, SameDocumentHistoryNavigationCommitType) {
RegisterMockedHttpURLLoad("push_state.html");
TestDidNavigateCommitTypeWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.InitializeAndLoad(base_url_ + "push_state.html", &client);
Persistent<HistoryItem> item =
@@ -7832,16 +7867,14 @@ TEST_F(WebFrameTest, SameDocumentHistoryNavigationCommitType) {
}
class TestHistoryChildWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestHistoryChildWebFrameClient() = default;
~TestHistoryChildWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
- void DidStartProvisionalLoad(
- WebDocumentLoader* document_loader,
- WebURLRequest& request,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) override {
+ // frame_test_helpers::TestWebFrameClient:
+ void DidStartProvisionalLoad(WebDocumentLoader* document_loader,
+ WebURLRequest& request) override {
replaces_current_history_item_ =
document_loader->ReplacesCurrentHistoryItem();
}
@@ -7852,19 +7885,21 @@ class TestHistoryChildWebFrameClient
bool replaces_current_history_item_ = false;
};
-class TestHistoryWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class TestHistoryWebFrameClient
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestHistoryWebFrameClient() = default;
~TestHistoryWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
WebLocalFrame* CreateChildFrame(WebLocalFrame* parent,
WebTreeScopeType scope,
const WebString& name,
const WebString& fallback_name,
WebSandboxFlags,
const ParsedFeaturePolicy&,
- const WebFrameOwnerProperties&) override {
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType) override {
return CreateLocalChild(*parent, scope, &child_client_);
}
@@ -7881,7 +7916,7 @@ TEST_F(WebFrameTest, FirstBlankSubframeNavigation) {
RegisterMockedHttpURLLoad("find.html");
TestHistoryWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", &client);
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -7893,12 +7928,12 @@ TEST_F(WebFrameTest, FirstBlankSubframeNavigation) {
ASSERT_EQ(&client.ChildClient(), iframe->Client());
std::string url1 = base_url_ + "history.html";
- FrameTestHelpers::LoadFrame(iframe, url1);
+ frame_test_helpers::LoadFrame(iframe, url1);
EXPECT_EQ(url1, iframe->GetDocument().Url().GetString().Utf8());
EXPECT_TRUE(client.ChildClient().ReplacesCurrentHistoryItem());
std::string url2 = base_url_ + "find.html";
- FrameTestHelpers::LoadFrame(iframe, url2);
+ frame_test_helpers::LoadFrame(iframe, url2);
EXPECT_EQ(url2, iframe->GetDocument().Url().GetString().Utf8());
EXPECT_FALSE(client.ChildClient().ReplacesCurrentHistoryItem());
}
@@ -7910,7 +7945,7 @@ TEST_F(WebFrameTest, FirstNonBlankSubframeNavigation) {
RegisterMockedHttpURLLoad("find.html");
TestHistoryWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank", &client);
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -7920,13 +7955,13 @@ TEST_F(WebFrameTest, FirstNonBlankSubframeNavigation) {
"javascript:var f = document.createElement('iframe'); "
"f.src = '";
load_frame_js += url1 + "';" + "document.body.appendChild(f)";
- FrameTestHelpers::LoadFrame(frame, load_frame_js);
+ frame_test_helpers::LoadFrame(frame, load_frame_js);
WebLocalFrame* iframe = frame->FirstChild()->ToWebLocalFrame();
EXPECT_EQ(url1, iframe->GetDocument().Url().GetString().Utf8());
std::string url2 = base_url_ + "find.html";
- FrameTestHelpers::LoadFrame(iframe, url2);
+ frame_test_helpers::LoadFrame(iframe, url2);
EXPECT_EQ(url2, iframe->GetDocument().Url().GetString().Utf8());
EXPECT_FALSE(client.ChildClient().ReplacesCurrentHistoryItem());
}
@@ -7937,15 +7972,15 @@ TEST_F(WebFrameTest, overflowHiddenRewrite) {
std::unique_ptr<FakeCompositingWebViewClient>
fake_compositing_web_view_client =
std::make_unique<FakeCompositingWebViewClient>();
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, fake_compositing_web_view_client.get(),
nullptr, &ConfigureCompositingWebView);
web_view_helper.Resize(WebSize(100, 100));
- FrameTestHelpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
- base_url_ + "non-scrollable.html");
+ frame_test_helpers::LoadFrame(web_view_helper.GetWebView()->MainFrameImpl(),
+ base_url_ + "non-scrollable.html");
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
PaintLayerCompositor* compositor = web_view_helper.GetWebView()->Compositor();
GraphicsLayer* scroll_layer = compositor->ScrollLayer();
ASSERT_TRUE(scroll_layer);
@@ -7958,7 +7993,7 @@ TEST_F(WebFrameTest, overflowHiddenRewrite) {
// Call javascript to make the layer scrollable, and verify it.
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
frame->ExecuteScript(WebScriptSource("allowScroll();"));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
scroll_layer = compositor->ScrollLayer();
cc_scroll_layer = scroll_layer->CcLayer();
@@ -7972,7 +8007,7 @@ TEST_F(WebFrameTest, CurrentHistoryItem) {
RegisterMockedHttpURLLoad("fixed_layout.html");
std::string url = base_url_ + "fixed_layout.html";
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
WebLocalFrame* frame = web_view_helper.GetWebView()->MainFrameImpl();
const FrameLoader& main_frame_loader =
@@ -7983,7 +8018,7 @@ TEST_F(WebFrameTest, CurrentHistoryItem) {
// Before commit, there is no history item.
EXPECT_FALSE(main_frame_loader.GetDocumentLoader()->GetHistoryItem());
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view_helper.LocalMainFrame());
// After commit, there is.
@@ -7992,12 +8027,12 @@ TEST_F(WebFrameTest, CurrentHistoryItem) {
EXPECT_EQ(WTF::String(url.data()), item->UrlString());
}
-class FailCreateChildFrame : public FrameTestHelpers::TestWebFrameClient {
+class FailCreateChildFrame : public frame_test_helpers::TestWebFrameClient {
public:
FailCreateChildFrame() : call_count_(0) {}
~FailCreateChildFrame() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
WebLocalFrame* CreateChildFrame(
WebLocalFrame* parent,
WebTreeScopeType scope,
@@ -8005,7 +8040,8 @@ class FailCreateChildFrame : public FrameTestHelpers::TestWebFrameClient {
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties& frame_owner_properties) override {
+ const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType) override {
++call_count_;
return nullptr;
}
@@ -8020,7 +8056,7 @@ class FailCreateChildFrame : public FrameTestHelpers::TestWebFrameClient {
TEST_F(WebFrameTest, CreateChildFrameFailure) {
RegisterMockedHttpURLLoad("create_child_frame_fail.html");
FailCreateChildFrame client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "create_child_frame_fail.html",
&client);
@@ -8029,7 +8065,7 @@ TEST_F(WebFrameTest, CreateChildFrameFailure) {
TEST_F(WebFrameTest, fixedPositionInFixedViewport) {
RegisterMockedHttpURLLoad("fixed-position-in-fixed-viewport.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "fixed-position-in-fixed-viewport.html", nullptr, nullptr,
nullptr, ConfigureAndroid);
@@ -8057,10 +8093,10 @@ TEST_F(WebFrameTest, fixedPositionInFixedViewport) {
}
TEST_F(WebFrameTest, FrameViewMoveWithSetFrameRect) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
web_view_helper.Resize(WebSize(200, 200));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
LocalFrameView* frame_view = web_view_helper.LocalMainFrame()->GetFrameView();
EXPECT_EQ(IntRect(0, 0, 200, 200), frame_view->FrameRect());
@@ -8071,7 +8107,7 @@ TEST_F(WebFrameTest, FrameViewMoveWithSetFrameRect) {
TEST_F(WebFrameTest, FrameViewScrollAccountsForBrowserControls) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("long_scroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html", nullptr,
&client, nullptr, ConfigureAndroid);
@@ -8082,7 +8118,7 @@ TEST_F(WebFrameTest, FrameViewScrollAccountsForBrowserControls) {
web_view->ResizeWithBrowserControls(WebSize(100, 100),
browser_controls_height, 0, false);
web_view->SetPageScaleFactor(2.0f);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
web_view->MainFrameImpl()->SetScrollOffset(WebSize(0, 2000));
EXPECT_EQ(ScrollOffset(0, 1900),
@@ -8090,47 +8126,53 @@ TEST_F(WebFrameTest, FrameViewScrollAccountsForBrowserControls) {
// Simulate the browser controls showing by 20px, thus shrinking the viewport
// and allowing it to scroll an additional 20px.
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- 20.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ 20.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(ScrollOffset(0, 1920),
frame_view->LayoutViewport()->MaximumScrollOffset());
// Show more, make sure the scroll actually gets clamped.
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- 20.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ 20.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
web_view->MainFrameImpl()->SetScrollOffset(WebSize(0, 2000));
EXPECT_EQ(ScrollOffset(0, 1940),
frame_view->LayoutViewport()->GetScrollOffset());
// Hide until there's 10px showing.
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- -30.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ -30.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(ScrollOffset(0, 1910),
frame_view->LayoutViewport()->MaximumScrollOffset());
// Simulate a LayoutEmbeddedContent::resize. The frame is resized to
// accomodate the browser controls and Blink's view of the browser controls
// matches that of the CC
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- 30.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ 30.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
web_view->ResizeWithBrowserControls(WebSize(100, 60), 40.0f, 0, true);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(ScrollOffset(0, 1940),
frame_view->LayoutViewport()->MaximumScrollOffset());
// Now simulate hiding.
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- -10.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ -10.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(ScrollOffset(0, 1930),
frame_view->LayoutViewport()->MaximumScrollOffset());
// Reset to original state: 100px widget height, browser controls fully
// hidden.
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- -30.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ -30.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
web_view->ResizeWithBrowserControls(WebSize(100, 100),
browser_controls_height, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
EXPECT_EQ(ScrollOffset(0, 1900),
frame_view->LayoutViewport()->MaximumScrollOffset());
@@ -8138,13 +8180,15 @@ TEST_F(WebFrameTest, FrameViewScrollAccountsForBrowserControls) {
// should allow an extra 0.5px of scrolling in the visual viewport. Make
// sure we're not losing any pixels when applying the adjustment on the
// main frame.
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- 1.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ 1.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(ScrollOffset(0, 1901),
frame_view->LayoutViewport()->MaximumScrollOffset());
- web_view->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1.0f,
- 2.0f / browser_controls_height});
+ web_view->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1.0f,
+ 2.0f / browser_controls_height,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(ScrollOffset(0, 1903),
frame_view->LayoutViewport()->MaximumScrollOffset());
}
@@ -8157,7 +8201,7 @@ TEST_F(WebFrameTest, MaximumScrollPositionCanBeNegative) {
int viewport_width = 640;
int viewport_height = 480;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "rtl-overview-mode.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -8167,7 +8211,7 @@ TEST_F(WebFrameTest, MaximumScrollPositionCanBeNegative) {
web_view_helper.GetWebView()->GetSettings()->SetLoadWithOverviewMode(true);
web_view_helper.GetWebView()->GetSettings()->SetUseWideViewport(true);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
LocalFrameView* frame_view = web_view_helper.LocalMainFrame()->GetFrameView();
ScrollableArea* layout_viewport = frame_view->LayoutViewport();
@@ -8177,7 +8221,7 @@ TEST_F(WebFrameTest, MaximumScrollPositionCanBeNegative) {
TEST_F(WebFrameTest, FullscreenLayerSize) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("fullscreen_div.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
int viewport_width = 640;
int viewport_height = 480;
client.screen_info_.rect.width = viewport_width;
@@ -8186,7 +8230,7 @@ TEST_F(WebFrameTest, FullscreenLayerSize) {
base_url_ + "fullscreen_div.html", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
LocalFrame* frame = web_view_impl->MainFrameImpl()->GetFrame();
Document* document = frame->GetDocument();
@@ -8197,7 +8241,7 @@ TEST_F(WebFrameTest, FullscreenLayerSize) {
EXPECT_EQ(nullptr, Fullscreen::FullscreenElementFrom(*document));
web_view_impl->DidEnterFullscreen();
EXPECT_EQ(div_fullscreen, Fullscreen::FullscreenElementFrom(*document));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(div_fullscreen, Fullscreen::FullscreenElementFrom(*document));
// Verify that the element is sized to the viewport.
@@ -8210,7 +8254,7 @@ TEST_F(WebFrameTest, FullscreenLayerSize) {
client.screen_info_.rect.width = viewport_height;
client.screen_info_.rect.height = viewport_width;
web_view_helper.Resize(WebSize(viewport_height, viewport_width));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(viewport_height, fullscreen_layout_object->LogicalWidth().ToInt());
EXPECT_EQ(viewport_width, fullscreen_layout_object->LogicalHeight().ToInt());
}
@@ -8218,14 +8262,14 @@ TEST_F(WebFrameTest, FullscreenLayerSize) {
TEST_F(WebFrameTest, FullscreenLayerNonScrollable) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("fullscreen_div.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
int viewport_width = 640;
int viewport_height = 480;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "fullscreen_div.html", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
LocalFrame* frame = web_view_impl->MainFrameImpl()->GetFrame();
Document* document = frame->GetDocument();
@@ -8236,7 +8280,7 @@ TEST_F(WebFrameTest, FullscreenLayerNonScrollable) {
EXPECT_EQ(nullptr, Fullscreen::FullscreenElementFrom(*document));
web_view_impl->DidEnterFullscreen();
EXPECT_EQ(div_fullscreen, Fullscreen::FullscreenElementFrom(*document));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(div_fullscreen, Fullscreen::FullscreenElementFrom(*document));
// Verify that the viewports are nonscrollable.
@@ -8259,7 +8303,7 @@ TEST_F(WebFrameTest, FullscreenLayerNonScrollable) {
EXPECT_EQ(div_fullscreen, Fullscreen::FullscreenElementFrom(*document));
web_view_impl->DidExitFullscreen();
EXPECT_EQ(nullptr, Fullscreen::FullscreenElementFrom(*document));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(nullptr, Fullscreen::FullscreenElementFrom(*document));
layout_viewport_scroll_layer = web_view_impl->Compositor()->ScrollLayer();
visual_viewport_scroll_layer =
@@ -8277,14 +8321,14 @@ TEST_F(WebFrameTest, FullscreenLayerNonScrollable) {
TEST_F(WebFrameTest, FullscreenMainFrame) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("fullscreen_div.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
int viewport_width = 640;
int viewport_height = 480;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "fullscreen_div.html", nullptr, &client, nullptr,
ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
cc::Layer* cc_scroll_layer = web_view_impl->MainFrameImpl()
->GetFrame()
@@ -8306,7 +8350,7 @@ TEST_F(WebFrameTest, FullscreenMainFrame) {
EXPECT_EQ(document->documentElement(),
Fullscreen::FullscreenElementFrom(*document));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(document->documentElement(),
Fullscreen::FullscreenElementFrom(*document));
@@ -8332,7 +8376,7 @@ TEST_F(WebFrameTest, FullscreenSubframe) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("fullscreen_iframe.html");
RegisterMockedHttpURLLoad("fullscreen_div.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "fullscreen_iframe.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -8341,7 +8385,7 @@ TEST_F(WebFrameTest, FullscreenSubframe) {
client.screen_info_.rect.width = viewport_width;
client.screen_info_.rect.height = viewport_height;
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
LocalFrame* frame =
ToWebLocalFrameImpl(
@@ -8353,7 +8397,7 @@ TEST_F(WebFrameTest, FullscreenSubframe) {
Element* div_fullscreen = document->getElementById("div1");
Fullscreen::RequestFullscreen(*div_fullscreen);
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
// Verify that the element is sized to the viewport.
LayoutBox* fullscreen_layout_object =
@@ -8365,7 +8409,7 @@ TEST_F(WebFrameTest, FullscreenSubframe) {
client.screen_info_.rect.width = viewport_height;
client.screen_info_.rect.height = viewport_width;
web_view_helper.Resize(WebSize(viewport_height, viewport_width));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(viewport_height, fullscreen_layout_object->LogicalWidth().ToInt());
EXPECT_EQ(viewport_width, fullscreen_layout_object->LogicalHeight().ToInt());
}
@@ -8375,11 +8419,11 @@ TEST_F(WebFrameTest, FullscreenSubframe) {
TEST_F(WebFrameTest, FullscreenNestedExit) {
RegisterMockedHttpURLLoad("fullscreen_iframe.html");
RegisterMockedHttpURLLoad("fullscreen_div.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.InitializeAndLoad(base_url_ + "fullscreen_iframe.html");
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
Document* top_doc = web_view_impl->MainFrameImpl()->GetFrame()->GetDocument();
Element* top_body = top_doc->body();
@@ -8395,7 +8439,7 @@ TEST_F(WebFrameTest, FullscreenNestedExit) {
Fullscreen::RequestFullscreen(*top_body);
}
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
{
std::unique_ptr<UserGestureIndicator> gesture =
@@ -8404,7 +8448,7 @@ TEST_F(WebFrameTest, FullscreenNestedExit) {
}
web_view_impl->DidEnterFullscreen();
Microtask::PerformCheckpoint(V8PerIsolateData::MainThreadIsolate());
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
// We are now in nested fullscreen, with both documents having a non-empty
// fullscreen element stack.
@@ -8412,7 +8456,7 @@ TEST_F(WebFrameTest, FullscreenNestedExit) {
EXPECT_EQ(iframe_body, Fullscreen::FullscreenElementFrom(*iframe_doc));
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
// We should now have fully exited fullscreen.
EXPECT_EQ(nullptr, Fullscreen::FullscreenElementFrom(*top_doc));
@@ -8422,7 +8466,7 @@ TEST_F(WebFrameTest, FullscreenNestedExit) {
TEST_F(WebFrameTest, FullscreenWithTinyViewport) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("viewport-tiny.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "viewport-tiny.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -8431,7 +8475,7 @@ TEST_F(WebFrameTest, FullscreenWithTinyViewport) {
client.screen_info_.rect.width = viewport_width;
client.screen_info_.rect.height = viewport_height;
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
auto* layout_view = web_view_helper.GetWebView()
->MainFrameImpl()
@@ -8448,7 +8492,7 @@ TEST_F(WebFrameTest, FullscreenWithTinyViewport) {
LocalFrame::NotifyUserActivation(frame);
Fullscreen::RequestFullscreen(*frame->GetDocument()->documentElement());
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(384, layout_view->LogicalWidth().Floor());
EXPECT_EQ(640, layout_view->LogicalHeight().Floor());
EXPECT_FLOAT_EQ(1.0, web_view_impl->PageScaleFactor());
@@ -8456,7 +8500,7 @@ TEST_F(WebFrameTest, FullscreenWithTinyViewport) {
EXPECT_FLOAT_EQ(1.0, web_view_impl->MaximumPageScaleFactor());
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(320, layout_view->LogicalWidth().Floor());
EXPECT_EQ(533, layout_view->LogicalHeight().Floor());
EXPECT_FLOAT_EQ(1.2, web_view_impl->PageScaleFactor());
@@ -8467,7 +8511,7 @@ TEST_F(WebFrameTest, FullscreenWithTinyViewport) {
TEST_F(WebFrameTest, FullscreenResizeWithTinyViewport) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("viewport-tiny.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "viewport-tiny.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -8476,7 +8520,7 @@ TEST_F(WebFrameTest, FullscreenResizeWithTinyViewport) {
client.screen_info_.rect.width = viewport_width;
client.screen_info_.rect.height = viewport_height;
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
auto* layout_view = web_view_helper.GetWebView()
->MainFrameImpl()
@@ -8487,7 +8531,7 @@ TEST_F(WebFrameTest, FullscreenResizeWithTinyViewport) {
LocalFrame::NotifyUserActivation(frame);
Fullscreen::RequestFullscreen(*frame->GetDocument()->documentElement());
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(384, layout_view->LogicalWidth().Floor());
EXPECT_EQ(640, layout_view->LogicalHeight().Floor());
EXPECT_FLOAT_EQ(1.0, web_view_impl->PageScaleFactor());
@@ -8499,7 +8543,7 @@ TEST_F(WebFrameTest, FullscreenResizeWithTinyViewport) {
client.screen_info_.rect.width = viewport_width;
client.screen_info_.rect.height = viewport_height;
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(640, layout_view->LogicalWidth().Floor());
EXPECT_EQ(384, layout_view->LogicalHeight().Floor());
EXPECT_FLOAT_EQ(1.0, web_view_impl->PageScaleFactor());
@@ -8507,7 +8551,7 @@ TEST_F(WebFrameTest, FullscreenResizeWithTinyViewport) {
EXPECT_FLOAT_EQ(1.0, web_view_impl->MaximumPageScaleFactor());
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_EQ(320, layout_view->LogicalWidth().Floor());
EXPECT_EQ(192, layout_view->LogicalHeight().Floor());
EXPECT_FLOAT_EQ(2, web_view_impl->PageScaleFactor());
@@ -8526,7 +8570,7 @@ TEST_F(WebFrameTest, FullscreenRestoreScaleFactorUponExiting) {
FakeCompositingWebViewClient client;
RegisterMockedHttpURLLoad("fullscreen_restore_scale_factor.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "fullscreen_restore_scale_factor.html", nullptr, &client,
nullptr, &ConfigureAndroid);
@@ -8555,7 +8599,7 @@ TEST_F(WebFrameTest, FullscreenRestoreScaleFactorUponExiting) {
}
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
client.screen_info_.rect.width = screen_size_minus_status_bars.width;
client.screen_info_.rect.height = screen_size_minus_status_bars.height;
web_view_helper.Resize(screen_size_minus_status_bars);
@@ -8569,7 +8613,7 @@ TEST_F(WebFrameTest, FullscreenRestoreScaleFactorUponExiting) {
EXPECT_FLOAT_EQ(1.0, web_view_impl->MaximumPageScaleFactor());
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
client.screen_info_.rect.width = screen_size_minus_status_bars.width;
client.screen_info_.rect.height = screen_size_minus_status_bars.height;
web_view_helper.Resize(screen_size_minus_status_bars);
@@ -8591,7 +8635,7 @@ TEST_F(WebFrameTest, FullscreenRestoreScaleFactorUponExiting) {
// fullscreen page scale constraints.
TEST_F(WebFrameTest, ClearFullscreenConstraintsOnNavigation) {
RegisterMockedHttpURLLoad("viewport-tiny.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
int viewport_width = 100;
int viewport_height = 200;
@@ -8600,7 +8644,7 @@ TEST_F(WebFrameTest, ClearFullscreenConstraintsOnNavigation) {
ConfigureAndroid);
web_view_helper.Resize(WebSize(viewport_width, viewport_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
// viewport-tiny.html specifies a 320px layout width.
auto* layout_view =
@@ -8616,7 +8660,7 @@ TEST_F(WebFrameTest, ClearFullscreenConstraintsOnNavigation) {
LocalFrame::NotifyUserActivation(frame, UserGestureToken::kNewGesture);
Fullscreen::RequestFullscreen(*frame->GetDocument()->documentElement());
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
// Entering fullscreen causes layout size and page scale limits to be
// overridden.
@@ -8631,9 +8675,9 @@ TEST_F(WebFrameTest, ClearFullscreenConstraintsOnNavigation) {
// Load a new page before exiting fullscreen.
KURL test_url = ToKURL("about:blank");
WebLocalFrame* web_frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadHTMLString(web_frame, kSource, test_url);
+ frame_test_helpers::LoadHTMLString(web_frame, kSource, test_url);
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
// Make sure the new page's layout size and scale factor limits aren't
// overridden.
@@ -8647,8 +8691,8 @@ TEST_F(WebFrameTest, ClearFullscreenConstraintsOnNavigation) {
TEST_F(WebFrameTest, OverlayFullscreenVideo) {
ScopedForceOverlayFullscreenVideoForTest force_overlay_fullscreen_video(true);
RegisterMockedHttpURLLoad("fullscreen_video.html");
- FrameTestHelpers::TestWebViewClient web_view_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::TestWebViewClient web_view_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "fullscreen_video.html", nullptr, &web_view_client);
@@ -8666,25 +8710,25 @@ TEST_F(WebFrameTest, OverlayFullscreenVideo) {
video->webkitEnterFullscreen();
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_TRUE(video->IsFullscreen());
EXPECT_LT(SkColorGetA(layer_tree_host->background_color()), SK_AlphaOPAQUE);
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view_impl);
EXPECT_FALSE(video->IsFullscreen());
EXPECT_EQ(SkColorGetA(layer_tree_host->background_color()), SK_AlphaOPAQUE);
}
TEST_F(WebFrameTest, LayoutBlockPercentHeightDescendants) {
RegisterMockedHttpURLLoad("percent-height-descendants.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ +
"percent-height-descendants.html");
WebViewImpl* web_view = web_view_helper.GetWebView();
web_view_helper.Resize(WebSize(800, 800));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument();
LayoutBlock* container =
@@ -8716,7 +8760,7 @@ TEST_F(WebFrameTest, LayoutBlockPercentHeightDescendants) {
TEST_F(WebFrameTest, HasVisibleContentOnVisibleFrames) {
RegisterMockedHttpURLLoad("visible_frames.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.InitializeAndLoad(base_url_ + "visible_frames.html");
for (WebFrame* frame = web_view_impl->MainFrameImpl()->TraverseNext(); frame;
@@ -8727,7 +8771,7 @@ TEST_F(WebFrameTest, HasVisibleContentOnVisibleFrames) {
TEST_F(WebFrameTest, HasVisibleContentOnHiddenFrames) {
RegisterMockedHttpURLLoad("hidden_frames.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.InitializeAndLoad(base_url_ + "hidden_frames.html");
for (WebFrame* frame = web_view_impl->MainFrameImpl()->TraverseNext(); frame;
@@ -8737,12 +8781,12 @@ TEST_F(WebFrameTest, HasVisibleContentOnHiddenFrames) {
}
class ManifestChangeWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
ManifestChangeWebFrameClient() : manifest_change_count_(0) {}
~ManifestChangeWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidChangeManifest() override { ++manifest_change_count_; }
int ManifestChangeCount() { return manifest_change_count_; }
@@ -8755,7 +8799,7 @@ TEST_F(WebFrameTest, NotifyManifestChange) {
RegisterMockedHttpURLLoad("link-manifest-change.html");
ManifestChangeWebFrameClient web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "link-manifest-change.html",
&web_frame_client);
@@ -8773,7 +8817,7 @@ TEST_F(WebFrameTest, ManifestFetch) {
RegisterMockedHttpURLLoad("foo.html");
RegisterMockedHttpURLLoad("link-manifest-fetch.json");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
Document* document =
web_view_helper.LocalMainFrame()->GetFrame()->GetDocument();
@@ -8788,7 +8832,7 @@ TEST_F(WebFrameTest, ManifestCSPFetchAllow) {
RegisterMockedURLLoadFromBase(not_base_url_, "link-manifest-fetch.json");
RegisterMockedHttpURLLoadWithCSP("foo.html", "manifest-src *");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
Document* document =
web_view_helper.LocalMainFrame()->GetFrame()->GetDocument();
@@ -8803,7 +8847,7 @@ TEST_F(WebFrameTest, ManifestCSPFetchSelf) {
RegisterMockedURLLoadFromBase(not_base_url_, "link-manifest-fetch.json");
RegisterMockedHttpURLLoadWithCSP("foo.html", "manifest-src 'self'");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
Document* document =
web_view_helper.LocalMainFrame()->GetFrame()->GetDocument();
@@ -8822,7 +8866,7 @@ TEST_F(WebFrameTest, ManifestCSPFetchSelfReportOnly) {
RegisterMockedHttpURLLoadWithCSP("foo.html", "manifest-src 'self'",
/* report only */ true);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
Document* document =
web_view_helper.LocalMainFrame()->GetFrame()->GetDocument();
@@ -8837,10 +8881,10 @@ TEST_F(WebFrameTest, ReloadBypassingCache) {
// Check that a reload bypassing cache on a frame will result in the cache
// policy of the request being set to ReloadBypassingCache.
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::ReloadFrameBypassingCache(frame);
+ frame_test_helpers::ReloadFrameBypassingCache(frame);
EXPECT_EQ(mojom::FetchCacheMode::kBypassCache,
frame->GetDocumentLoader()->GetRequest().GetCacheMode());
}
@@ -8862,7 +8906,7 @@ static void NodeImageTestValidation(const IntSize& reference_bitmap_size,
}
TEST_F(WebFrameTest, NodeImageTestCSSTransformDescendant) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
std::unique_ptr<DragImage> drag_image = NodeImageTestSetup(
&web_view_helper, std::string("case-css-3dtransform-descendant"));
EXPECT_TRUE(drag_image);
@@ -8871,7 +8915,7 @@ TEST_F(WebFrameTest, NodeImageTestCSSTransformDescendant) {
}
TEST_F(WebFrameTest, NodeImageTestCSSTransform) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
std::unique_ptr<DragImage> drag_image =
NodeImageTestSetup(&web_view_helper, std::string("case-css-transform"));
EXPECT_TRUE(drag_image);
@@ -8880,7 +8924,7 @@ TEST_F(WebFrameTest, NodeImageTestCSSTransform) {
}
TEST_F(WebFrameTest, NodeImageTestCSS3DTransform) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
std::unique_ptr<DragImage> drag_image =
NodeImageTestSetup(&web_view_helper, std::string("case-css-3dtransform"));
EXPECT_TRUE(drag_image);
@@ -8889,7 +8933,7 @@ TEST_F(WebFrameTest, NodeImageTestCSS3DTransform) {
}
TEST_F(WebFrameTest, NodeImageTestInlineBlock) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
std::unique_ptr<DragImage> drag_image =
NodeImageTestSetup(&web_view_helper, std::string("case-inlineblock"));
EXPECT_TRUE(drag_image);
@@ -8898,7 +8942,7 @@ TEST_F(WebFrameTest, NodeImageTestInlineBlock) {
}
TEST_F(WebFrameTest, NodeImageTestFloatLeft) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
std::unique_ptr<DragImage> drag_image = NodeImageTestSetup(
&web_view_helper, std::string("case-float-left-overflow-hidden"));
EXPECT_TRUE(drag_image);
@@ -8913,7 +8957,7 @@ TEST_F(WebFrameTest, DISABLED_PrintingBasic)
TEST_F(WebFrameTest, PrintingBasic)
#endif
{
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("data:text/html,Hello, world.");
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -8928,7 +8972,7 @@ TEST_F(WebFrameTest, PrintingBasic)
}
class ThemeColorTestWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
ThemeColorTestWebFrameClient() : did_notify_(false) {}
~ThemeColorTestWebFrameClient() override = default;
@@ -8938,7 +8982,7 @@ class ThemeColorTestWebFrameClient
bool DidNotify() const { return did_notify_; }
private:
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidChangeThemeColor() override { did_notify_ = true; }
bool did_notify_;
@@ -8947,7 +8991,7 @@ class ThemeColorTestWebFrameClient
TEST_F(WebFrameTest, ThemeColor) {
RegisterMockedHttpURLLoad("theme_color_test.html");
ThemeColorTestWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "theme_color_test.html",
&client);
EXPECT_TRUE(client.DidNotify());
@@ -8979,10 +9023,10 @@ TEST_F(WebFrameTest, ThemeColor) {
// Make sure that an embedder-triggered detach with a remote frame parent
// doesn't leave behind dangling pointers.
TEST_F(WebFrameTest, EmbedderTriggeredDetachWithRemoteMainFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebLocalFrame* child_frame =
- FrameTestHelpers::CreateLocalChild(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateLocalChild(*helper.RemoteMainFrame());
// Purposely keep the LocalFrame alive so it's the last thing to be destroyed.
Persistent<Frame> child_core_frame = WebFrame::ToCoreFrame(*child_frame);
@@ -9007,20 +9051,20 @@ class WebFrameSwapTest : public WebFrameTest {
WebViewImpl* WebView() const { return web_view_helper_.GetWebView(); }
private:
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
TEST_F(WebFrameSwapTest, SwapMainFrame) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
MainFrame()->Swap(remote_frame);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
remote_frame->Swap(local_frame);
// Finally, make sure an embedder triggered load in the local frame swapped
// back in works.
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
std::string content =
WebFrameContentDumper::DumpWebViewAsText(WebView(), 1024).Utf8();
@@ -9030,13 +9074,13 @@ TEST_F(WebFrameSwapTest, SwapMainFrame) {
TEST_F(WebFrameSwapTest, ValidateSizeOnRemoteToLocalMainFrameSwap) {
WebSize size(111, 222);
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
MainFrame()->Swap(remote_frame);
- remote_frame->View()->Resize(size);
+ remote_frame->View()->MainFrameWidget()->Resize(size);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
remote_frame->Swap(local_frame);
// Verify that the size that was set with a remote main frame is correct
@@ -9054,12 +9098,12 @@ TEST_F(WebFrameSwapTest, ValidateSizeOnRemoteToLocalMainFrameSwap) {
// https://crbug.com/769321.
TEST_F(WebFrameSwapTest,
ValidateBrowserControlsSizeOnRemoteToLocalMainFrameSwap) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
MainFrame()->Swap(remote_frame);
// Create a provisional main frame frame but don't swap it in yet.
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
WebViewImpl* web_view = static_cast<WebViewImpl*>(local_frame->View());
EXPECT_TRUE(web_view->MainFrame() &&
@@ -9088,18 +9132,18 @@ TEST_F(WebFrameSwapTest,
namespace {
class SwapMainFrameWhenTitleChangesWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
SwapMainFrameWhenTitleChangesWebFrameClient() = default;
~SwapMainFrameWhenTitleChangesWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidReceiveTitle(const WebString& title, WebTextDirection) override {
if (title.IsEmpty())
return;
if (!Frame()->Parent())
- Frame()->Swap(FrameTestHelpers::CreateRemote());
+ Frame()->Swap(frame_test_helpers::CreateRemote());
}
};
@@ -9108,7 +9152,7 @@ class SwapMainFrameWhenTitleChangesWebFrameClient
TEST_F(WebFrameTest, SwapMainFrameWhileLoading) {
SwapMainFrameWhenTitleChangesWebFrameClient frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
RegisterMockedHttpURLLoad("frame-a-b-c.html");
RegisterMockedHttpURLLoad("subframe-a.html");
RegisterMockedHttpURLLoad("subframe-b.html");
@@ -9133,19 +9177,19 @@ void WebFrameTest::SwapAndVerifyFirstChildConsistency(const char* const message,
}
TEST_F(WebFrameSwapTest, SwapFirstChild) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
SwapAndVerifyFirstChildConsistency("local->remote", MainFrame(),
remote_frame);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
SwapAndVerifyFirstChildConsistency("remote->local", MainFrame(), local_frame);
// FIXME: This almost certainly fires more load events on the iframe element
// than it should.
// Finally, make sure an embedder triggered load in the local frame swapped
// back in works.
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
std::string content =
WebFrameContentDumper::DumpWebViewAsText(WebView(), 1024).Utf8();
EXPECT_EQ("\n\nhello\n\nb\n\n\na\n\nc", content);
@@ -9168,12 +9212,12 @@ void WebFrameTest::SwapAndVerifyMiddleChildConsistency(
}
TEST_F(WebFrameSwapTest, SwapMiddleChild) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
SwapAndVerifyMiddleChildConsistency("local->remote", MainFrame(),
remote_frame);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
SwapAndVerifyMiddleChildConsistency("remote->local", MainFrame(),
local_frame);
@@ -9181,7 +9225,7 @@ TEST_F(WebFrameSwapTest, SwapMiddleChild) {
// than it should.
// Finally, make sure an embedder triggered load in the local frame swapped
// back in works.
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
std::string content =
WebFrameContentDumper::DumpWebViewAsText(WebView(), 1024).Utf8();
EXPECT_EQ("\n\na\n\nhello\n\nc", content);
@@ -9200,30 +9244,30 @@ void WebFrameTest::SwapAndVerifyLastChildConsistency(const char* const message,
}
TEST_F(WebFrameSwapTest, SwapLastChild) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
SwapAndVerifyLastChildConsistency("local->remote", MainFrame(), remote_frame);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
SwapAndVerifyLastChildConsistency("remote->local", MainFrame(), local_frame);
// FIXME: This almost certainly fires more load events on the iframe element
// than it should.
// Finally, make sure an embedder triggered load in the local frame swapped
// back in works.
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
std::string content =
WebFrameContentDumper::DumpWebViewAsText(WebView(), 1024).Utf8();
EXPECT_EQ("\n\na\n\nb\n\n\na\n\nhello", content);
}
TEST_F(WebFrameSwapTest, DetachProvisionalFrame) {
- WebRemoteFrameImpl* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrameImpl* remote_frame = frame_test_helpers::CreateRemote();
SwapAndVerifyMiddleChildConsistency("local->remote", MainFrame(),
remote_frame);
WebLocalFrameImpl* provisional_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
// The provisional frame should have a local frame owner.
FrameOwner* owner = provisional_frame->GetFrame()->Owner();
@@ -9255,13 +9299,13 @@ void WebFrameTest::SwapAndVerifySubframeConsistency(const char* const message,
}
TEST_F(WebFrameSwapTest, EventsOnDisconnectedSubDocumentSkipped) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild()->NextSibling();
EXPECT_TRUE(target_frame);
SwapAndVerifySubframeConsistency("local->remote", target_frame, remote_frame);
- WebLocalFrameImpl* local_child =
- FrameTestHelpers::CreateLocalChild(*remote_frame, "local-inside-remote");
+ WebLocalFrameImpl* local_child = frame_test_helpers::CreateLocalChild(
+ *remote_frame, "local-inside-remote");
LocalFrame* main_frame = WebView()->MainFrameImpl()->GetFrame();
Document* child_document = local_child->GetFrame()->GetDocument();
@@ -9272,17 +9316,18 @@ TEST_F(WebFrameSwapTest, EventsOnDisconnectedSubDocumentSkipped) {
event_registry.DidAddEventHandler(
*child_document, EventHandlerRegistry::kTouchStartOrMoveEventBlocking);
// Passes if this does not crash or DCHECK.
- main_frame->View()->UpdateAllLifecyclePhases();
+ main_frame->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
TEST_F(WebFrameSwapTest, EventsOnDisconnectedElementSkipped) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild()->NextSibling();
EXPECT_TRUE(target_frame);
SwapAndVerifySubframeConsistency("local->remote", target_frame, remote_frame);
- WebLocalFrameImpl* local_child =
- FrameTestHelpers::CreateLocalChild(*remote_frame, "local-inside-remote");
+ WebLocalFrameImpl* local_child = frame_test_helpers::CreateLocalChild(
+ *remote_frame, "local-inside-remote");
LocalFrame* main_frame = WebView()->MainFrameImpl()->GetFrame();
@@ -9299,11 +9344,12 @@ TEST_F(WebFrameSwapTest, EventsOnDisconnectedElementSkipped) {
*child_document->body(),
EventHandlerRegistry::kTouchStartOrMoveEventBlocking);
// Passes if this does not crash or DCHECK.
- main_frame->View()->UpdateAllLifecyclePhases();
+ main_frame->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
TEST_F(WebFrameSwapTest, SwapParentShouldDetachChildren) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild()->NextSibling();
EXPECT_TRUE(target_frame);
SwapAndVerifySubframeConsistency("local->remote", target_frame, remote_frame);
@@ -9312,17 +9358,17 @@ TEST_F(WebFrameSwapTest, SwapParentShouldDetachChildren) {
EXPECT_TRUE(target_frame);
// Create child frames in the target frame before testing the swap.
- FrameTestHelpers::CreateRemoteChild(*remote_frame);
+ frame_test_helpers::CreateRemoteChild(*remote_frame);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
SwapAndVerifySubframeConsistency("remote->local", target_frame, local_frame);
// FIXME: This almost certainly fires more load events on the iframe element
// than it should.
// Finally, make sure an embedder triggered load in the local frame swapped
// back in works.
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
std::string content =
WebFrameContentDumper::DumpWebViewAsText(WebView(), 1024).Utf8();
EXPECT_EQ("\n\na\n\nhello\n\nc", content);
@@ -9339,7 +9385,7 @@ TEST_F(WebFrameSwapTest, SwapPreservesGlobalContext) {
ASSERT_TRUE(original_window->IsObject());
// Make sure window reference stays the same when swapping to a remote frame.
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild()->NextSibling();
target_frame->Swap(remote_frame);
v8::Local<v8::Value> remote_window = MainFrame()->ExecuteScriptAndReturnValue(
@@ -9354,7 +9400,7 @@ TEST_F(WebFrameSwapTest, SwapPreservesGlobalContext) {
// Now check that remote -> local works too, since it goes through a different
// code path.
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
remote_frame->Swap(local_frame);
v8::Local<v8::Value> local_window = MainFrame()->ExecuteScriptAndReturnValue(
WebScriptSource("document.querySelector('#frame2').contentWindow;"));
@@ -9372,7 +9418,7 @@ TEST_F(WebFrameSwapTest, SetTimeoutAfterSwap) {
WebScriptSource("savedSetTimeout = window[0].setTimeout"));
// Swap the frame to a remote frame.
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild();
target_frame->Swap(remote_frame);
remote_frame->SetReplicatedOrigin(
@@ -9407,7 +9453,7 @@ TEST_F(WebFrameSwapTest, SwapInitializesGlobal) {
WebScriptSource("saved = window[2]"));
ASSERT_TRUE(last_child->IsObject());
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrameTest::LastChild(MainFrame())->Swap(remote_frame);
v8::Local<v8::Value> remote_window_top =
MainFrame()->ExecuteScriptAndReturnValue(WebScriptSource("saved.top"));
@@ -9415,7 +9461,7 @@ TEST_F(WebFrameSwapTest, SwapInitializesGlobal) {
EXPECT_TRUE(window_top->StrictEquals(remote_window_top));
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
remote_frame->Swap(local_frame);
v8::Local<v8::Value> local_window_top =
MainFrame()->ExecuteScriptAndReturnValue(WebScriptSource("saved.top"));
@@ -9426,7 +9472,7 @@ TEST_F(WebFrameSwapTest, SwapInitializesGlobal) {
TEST_F(WebFrameSwapTest, RemoteFramesAreIndexable) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
LastChild(MainFrame())->Swap(remote_frame);
v8::Local<v8::Value> remote_window =
MainFrame()->ExecuteScriptAndReturnValue(WebScriptSource("window[2]"));
@@ -9440,7 +9486,7 @@ TEST_F(WebFrameSwapTest, RemoteFramesAreIndexable) {
TEST_F(WebFrameSwapTest, RemoteFrameLengthAccess) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
LastChild(MainFrame())->Swap(remote_frame);
v8::Local<v8::Value> remote_window_length =
MainFrame()->ExecuteScriptAndReturnValue(
@@ -9455,7 +9501,7 @@ TEST_F(WebFrameSwapTest, RemoteWindowNamedAccess) {
// TODO(dcheng): Once OOPIF unit test infrastructure is in place, test that
// named window access on a remote window works. For now, just test that
// accessing a named property doesn't crash.
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
LastChild(MainFrame())->Swap(remote_frame);
remote_frame->SetReplicatedOrigin(
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
@@ -9469,7 +9515,7 @@ TEST_F(WebFrameSwapTest, RemoteWindowToString) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
LastChild(MainFrame())->Swap(remote_frame);
v8::Local<v8::Value> to_string_result =
MainFrame()->ExecuteScriptAndReturnValue(
@@ -9485,14 +9531,14 @@ TEST_F(WebFrameSwapTest, RemoteWindowToString) {
TEST_F(WebFrameSwapTest, FramesOfRemoteParentAreIndexable) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
- WebRemoteFrame* remote_parent_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_parent_frame = frame_test_helpers::CreateRemote();
MainFrame()->Swap(remote_parent_frame);
remote_parent_frame->SetReplicatedOrigin(
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
WebLocalFrame* child_frame =
- FrameTestHelpers::CreateLocalChild(*remote_parent_frame);
- FrameTestHelpers::LoadFrame(child_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::CreateLocalChild(*remote_parent_frame);
+ frame_test_helpers::LoadFrame(child_frame, base_url_ + "subframe-hello.html");
v8::Local<v8::Value> window =
child_frame->ExecuteScriptAndReturnValue(WebScriptSource("window"));
@@ -9513,14 +9559,14 @@ TEST_F(WebFrameSwapTest, FramesOfRemoteParentAreIndexable) {
TEST_F(WebFrameSwapTest, FrameElementInFramesWithRemoteParent) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
- WebRemoteFrame* remote_parent_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_parent_frame = frame_test_helpers::CreateRemote();
MainFrame()->Swap(remote_parent_frame);
remote_parent_frame->SetReplicatedOrigin(
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
WebLocalFrame* child_frame =
- FrameTestHelpers::CreateLocalChild(*remote_parent_frame);
- FrameTestHelpers::LoadFrame(child_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::CreateLocalChild(*remote_parent_frame);
+ frame_test_helpers::LoadFrame(child_frame, base_url_ + "subframe-hello.html");
v8::Local<v8::Value> frame_element = child_frame->ExecuteScriptAndReturnValue(
WebScriptSource("window.frameElement"));
@@ -9530,14 +9576,14 @@ TEST_F(WebFrameSwapTest, FrameElementInFramesWithRemoteParent) {
}
class RemoteToLocalSwapWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
explicit RemoteToLocalSwapWebFrameClient(WebRemoteFrame* remote_frame)
: history_commit_type_(kWebHistoryInertCommit),
remote_frame_(remote_frame) {}
~RemoteToLocalSwapWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidCommitProvisionalLoad(const WebHistoryItem&,
WebHistoryCommitType history_commit_type,
WebGlobalObjectReusePolicy) override {
@@ -9558,7 +9604,7 @@ class RemoteToLocalSwapWebFrameClient
// exists in the same process, such that we create the RemoteFrame before the
// first navigation occurs.
TEST_F(WebFrameSwapTest, HistoryCommitTypeAfterNewRemoteToLocalSwap) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild();
ASSERT_TRUE(target_frame);
target_frame->Swap(remote_frame);
@@ -9567,8 +9613,8 @@ TEST_F(WebFrameSwapTest, HistoryCommitTypeAfterNewRemoteToLocalSwap) {
RemoteToLocalSwapWebFrameClient client(remote_frame);
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame, &client);
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::CreateProvisional(*remote_frame, &client);
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
EXPECT_EQ(kWebHistoryInertCommit, client.HistoryCommitType());
// Manually reset to break WebViewHelper's dependency on the stack allocated
@@ -9580,7 +9626,7 @@ TEST_F(WebFrameSwapTest, HistoryCommitTypeAfterNewRemoteToLocalSwap) {
// LocalFrame after commits have already happened in the frame. The browser
// process will inform us via setCommittedFirstRealLoad.
TEST_F(WebFrameSwapTest, HistoryCommitTypeAfterExistingRemoteToLocalSwap) {
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote();
WebFrame* target_frame = MainFrame()->FirstChild();
ASSERT_TRUE(target_frame);
target_frame->Swap(remote_frame);
@@ -9588,10 +9634,10 @@ TEST_F(WebFrameSwapTest, HistoryCommitTypeAfterExistingRemoteToLocalSwap) {
ASSERT_EQ(MainFrame()->FirstChild(), remote_frame);
RemoteToLocalSwapWebFrameClient client(remote_frame);
- WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame, &client);
+ WebLocalFrameImpl* local_frame =
+ frame_test_helpers::CreateProvisional(*remote_frame, &client);
local_frame->SetCommittedFirstRealLoad();
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "subframe-hello.html");
EXPECT_EQ(kWebStandardCommit, client.HistoryCommitType());
// Manually reset to break WebViewHelper's dependency on the stack allocated
@@ -9600,12 +9646,12 @@ TEST_F(WebFrameSwapTest, HistoryCommitTypeAfterExistingRemoteToLocalSwap) {
}
class RemoteNavigationClient
- : public FrameTestHelpers::TestWebRemoteFrameClient {
+ : public frame_test_helpers::TestWebRemoteFrameClient {
public:
RemoteNavigationClient() = default;
~RemoteNavigationClient() override = default;
- // FrameTestHelpers::TestWebRemoteFrameClient:
+ // frame_test_helpers::TestWebRemoteFrameClient:
void Navigate(const WebURLRequest& request,
bool should_replace_current_entry,
mojo::ScopedMessagePipeHandle) override {
@@ -9620,7 +9666,7 @@ class RemoteNavigationClient
TEST_F(WebFrameSwapTest, NavigateRemoteFrameViaLocation) {
RemoteNavigationClient client;
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote(&client);
+ WebRemoteFrame* remote_frame = frame_test_helpers::CreateRemote(&client);
WebFrame* target_frame = MainFrame()->FirstChild();
ASSERT_TRUE(target_frame);
target_frame->Swap(remote_frame);
@@ -9642,7 +9688,8 @@ TEST_F(WebFrameSwapTest, NavigateRemoteFrameViaLocation) {
TEST_F(WebFrameSwapTest, WindowOpenOnRemoteFrame) {
RemoteNavigationClient remote_client;
- WebRemoteFrame* remote_frame = FrameTestHelpers::CreateRemote(&remote_client);
+ WebRemoteFrame* remote_frame =
+ frame_test_helpers::CreateRemote(&remote_client);
MainFrame()->FirstChild()->Swap(remote_frame);
remote_frame->SetReplicatedOrigin(
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
@@ -9670,12 +9717,12 @@ TEST_F(WebFrameSwapTest, WindowOpenOnRemoteFrame) {
Reset();
}
-class RemoteWindowCloseClient : public FrameTestHelpers::TestWebViewClient {
+class RemoteWindowCloseClient : public frame_test_helpers::TestWebViewClient {
public:
RemoteWindowCloseClient() : closed_(false) {}
~RemoteWindowCloseClient() override = default;
- // FrameTestHelpers::TestWebViewClient:
+ // frame_test_helpers::TestWebViewClient:
void CloseWidgetSoon() override { closed_ = true; }
bool Closed() const { return closed_; }
@@ -9685,12 +9732,12 @@ class RemoteWindowCloseClient : public FrameTestHelpers::TestWebViewClient {
};
TEST_F(WebFrameTest, WindowOpenRemoteClose) {
- FrameTestHelpers::WebViewHelper main_web_view;
+ frame_test_helpers::WebViewHelper main_web_view;
main_web_view.Initialize();
// Create a remote window that will be closed later in the test.
RemoteWindowCloseClient view_client;
- FrameTestHelpers::WebViewHelper popup;
+ frame_test_helpers::WebViewHelper popup;
popup.InitializeRemote(nullptr, nullptr, &view_client);
popup.RemoteMainFrame()->SetOpener(main_web_view.LocalMainFrame());
@@ -9709,12 +9756,12 @@ TEST_F(WebFrameTest, WindowOpenRemoteClose) {
}
TEST_F(WebFrameTest, NavigateRemoteToLocalWithOpener) {
- FrameTestHelpers::WebViewHelper main_web_view;
+ frame_test_helpers::WebViewHelper main_web_view;
main_web_view.Initialize();
WebLocalFrame* main_frame = main_web_view.LocalMainFrame();
// Create a popup with a remote frame and set its opener to the main frame.
- FrameTestHelpers::WebViewHelper popup_helper;
+ frame_test_helpers::WebViewHelper popup_helper;
popup_helper.InitializeRemote(
nullptr, SecurityOrigin::CreateFromString("http://foo.com"));
WebRemoteFrame* popup_remote_frame = popup_helper.RemoteMainFrame();
@@ -9724,7 +9771,7 @@ TEST_F(WebFrameTest, NavigateRemoteToLocalWithOpener) {
// Do a remote-to-local swap in the popup.
WebLocalFrame* popup_local_frame =
- FrameTestHelpers::CreateProvisional(*popup_remote_frame);
+ frame_test_helpers::CreateProvisional(*popup_remote_frame);
popup_remote_frame->Swap(popup_local_frame);
// The initial document created during the remote-to-local swap should have
@@ -9735,26 +9782,26 @@ TEST_F(WebFrameTest, NavigateRemoteToLocalWithOpener) {
TEST_F(WebFrameTest, SwapWithOpenerCycle) {
// First, create a remote main frame with itself as the opener.
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebRemoteFrame* remote_frame = helper.RemoteMainFrame();
helper.RemoteMainFrame()->SetOpener(remote_frame);
// Now swap in a local frame. It shouldn't crash.
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateProvisional(*remote_frame);
+ frame_test_helpers::CreateProvisional(*remote_frame);
remote_frame->Swap(local_frame);
// And the opener cycle should still be preserved.
EXPECT_EQ(local_frame, local_frame->Opener());
}
-class CommitTypeWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class CommitTypeWebFrameClient : public frame_test_helpers::TestWebFrameClient {
public:
CommitTypeWebFrameClient() : history_commit_type_(kWebHistoryInertCommit) {}
~CommitTypeWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidCommitProvisionalLoad(const WebHistoryItem&,
WebHistoryCommitType history_commit_type,
WebGlobalObjectReusePolicy) override {
@@ -9770,30 +9817,30 @@ class CommitTypeWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
};
TEST_F(WebFrameTest, RemoteFrameInitialCommitType) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote(nullptr, SecurityOrigin::CreateFromString(
WebString::FromUTF8(base_url_)));
// If an iframe has a remote main frame, ensure the inital commit is correctly
// identified as kWebHistoryInertCommit.
CommitTypeWebFrameClient child_frame_client;
- WebLocalFrame* child_frame = FrameTestHelpers::CreateLocalChild(
+ WebLocalFrame* child_frame = frame_test_helpers::CreateLocalChild(
*helper.RemoteMainFrame(), "frameName", WebFrameOwnerProperties(),
nullptr, &child_frame_client);
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::LoadFrame(child_frame, base_url_ + "foo.html");
+ frame_test_helpers::LoadFrame(child_frame, base_url_ + "foo.html");
EXPECT_EQ(kWebHistoryInertCommit, child_frame_client.HistoryCommitType());
helper.Reset();
}
class GestureEventTestWebWidgetClient
- : public FrameTestHelpers::TestWebWidgetClient {
+ : public frame_test_helpers::TestWebWidgetClient {
public:
GestureEventTestWebWidgetClient() : did_handle_gesture_event_(false) {}
~GestureEventTestWebWidgetClient() override = default;
- // FrameTestHelpers::TestWebWidgetClient:
+ // frame_test_helpers::TestWebWidgetClient:
void DidHandleGestureEvent(const WebGestureEvent& event,
bool event_cancelled) override {
did_handle_gesture_event_ = true;
@@ -9805,11 +9852,11 @@ class GestureEventTestWebWidgetClient
};
TEST_F(WebFrameTest, FrameWidgetTest) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
GestureEventTestWebWidgetClient child_widget_client;
- WebLocalFrame* child_frame = FrameTestHelpers::CreateLocalChild(
+ WebLocalFrame* child_frame = frame_test_helpers::CreateLocalChild(
*helper.RemoteMainFrame(), WebString(), WebFrameOwnerProperties(),
nullptr, nullptr, &child_widget_client);
@@ -9826,20 +9873,20 @@ TEST_F(WebFrameTest, FrameWidgetTest) {
}
TEST_F(WebFrameTest, DetachRemoteFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebRemoteFrame* child_frame =
- FrameTestHelpers::CreateRemoteChild(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateRemoteChild(*helper.RemoteMainFrame());
child_frame->Detach();
}
class TestConsoleMessageWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestConsoleMessageWebFrameClient() = default;
~TestConsoleMessageWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidAddMessageToConsole(const WebConsoleMessage& message,
const WebString& source_name,
unsigned source_line,
@@ -9854,14 +9901,14 @@ TEST_F(WebFrameTest, CrossDomainAccessErrorsUseCallingWindow) {
RegisterMockedHttpURLLoad("hidden_frames.html");
RegisterMockedChromeURLLoad("hello_world.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
TestConsoleMessageWebFrameClient web_frame_client;
web_view_helper.InitializeAndLoad(base_url_ + "hidden_frames.html",
&web_frame_client);
// Create another window with a cross-origin page, and point its opener to
// first window.
- FrameTestHelpers::WebViewHelper popup_web_view_helper;
+ frame_test_helpers::WebViewHelper popup_web_view_helper;
TestConsoleMessageWebFrameClient popup_web_frame_client;
WebViewImpl* popup_view = popup_web_view_helper.InitializeAndLoad(
chrome_url_ + "hello_world.html", &popup_web_frame_client);
@@ -9899,7 +9946,7 @@ TEST_F(WebFrameTest, CrossDomainAccessErrorsUseCallingWindow) {
TEST_F(WebFrameTest, ResizeInvalidatesDeviceMediaQueries) {
RegisterMockedHttpURLLoad("device_media_queries.html");
FixedLayoutTestWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "device_media_queries.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -9976,7 +10023,7 @@ class DeviceEmulationTest : public WebFrameTest {
}
FixedLayoutTestWebViewClient client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
TEST_F(DeviceEmulationTest, DeviceSizeInvalidatedOnResize) {
@@ -10007,18 +10054,18 @@ TEST_F(DeviceEmulationTest, PointerAndHoverTypes) {
}
TEST_F(WebFrameTest, CreateLocalChildWithPreviousSibling) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebRemoteFrame* parent = helper.RemoteMainFrame();
WebLocalFrame* second_frame(
- FrameTestHelpers::CreateLocalChild(*parent, "name2"));
- WebLocalFrame* fourth_frame(FrameTestHelpers::CreateLocalChild(
+ frame_test_helpers::CreateLocalChild(*parent, "name2"));
+ WebLocalFrame* fourth_frame(frame_test_helpers::CreateLocalChild(
*parent, "name4", WebFrameOwnerProperties(), second_frame));
- WebLocalFrame* third_frame(FrameTestHelpers::CreateLocalChild(
+ WebLocalFrame* third_frame(frame_test_helpers::CreateLocalChild(
*parent, "name3", WebFrameOwnerProperties(), second_frame));
WebLocalFrame* first_frame(
- FrameTestHelpers::CreateLocalChild(*parent, "name1"));
+ frame_test_helpers::CreateLocalChild(*parent, "name1"));
EXPECT_EQ(first_frame, parent->FirstChild());
EXPECT_EQ(nullptr, PreviousSibling(first_frame));
@@ -10041,29 +10088,29 @@ TEST_F(WebFrameTest, CreateLocalChildWithPreviousSibling) {
}
TEST_F(WebFrameTest, SendBeaconFromChildWithRemoteMainFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateLocalChild(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateLocalChild(*helper.RemoteMainFrame());
// Finally, make sure an embedder triggered load in the local frame swapped
// back in works.
RegisterMockedHttpURLLoad("send_beacon.html");
RegisterMockedHttpURLLoad("reload_post.html"); // url param to sendBeacon()
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "send_beacon.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "send_beacon.html");
}
TEST_F(WebFrameTest, SiteForCookiesFromChildWithRemoteMainFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote(nullptr,
SecurityOrigin::Create(ToKURL(not_base_url_)));
WebLocalFrame* local_frame =
- FrameTestHelpers::CreateLocalChild(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateLocalChild(*helper.RemoteMainFrame());
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::LoadFrame(local_frame, base_url_ + "foo.html");
+ frame_test_helpers::LoadFrame(local_frame, base_url_ + "foo.html");
EXPECT_EQ(WebURL(NullURL()), local_frame->GetDocument().SiteForCookies());
SchemeRegistry::RegisterURLSchemeAsFirstPartyWhenTopLevel("http");
@@ -10074,26 +10121,26 @@ TEST_F(WebFrameTest, SiteForCookiesFromChildWithRemoteMainFrame) {
// See https://crbug.com/525285.
TEST_F(WebFrameTest, RemoteToLocalSwapOnMainFrameInitializesCoreFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
- FrameTestHelpers::CreateLocalChild(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateLocalChild(*helper.RemoteMainFrame());
// Do a remote-to-local swap of the top frame.
WebLocalFrame* local_root =
- FrameTestHelpers::CreateProvisional(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateProvisional(*helper.RemoteMainFrame());
helper.RemoteMainFrame()->Swap(local_root);
// Load a page with a child frame in the new root to make sure this doesn't
// crash when the child frame invokes setCoreFrame.
RegisterMockedHttpURLLoad("single_iframe.html");
RegisterMockedHttpURLLoad("visible_iframe.html");
- FrameTestHelpers::LoadFrame(local_root, base_url_ + "single_iframe.html");
+ frame_test_helpers::LoadFrame(local_root, base_url_ + "single_iframe.html");
}
// See https://crbug.com/628942.
TEST_F(WebFrameTest, PausedPageLoadWithRemoteMainFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebRemoteFrameImpl* remote_root = helper.RemoteMainFrame();
@@ -10110,9 +10157,9 @@ TEST_F(WebFrameTest, PausedPageLoadWithRemoteMainFrame) {
// Repeat this for a page with a local child frame, and ensure that the
// child frame's loads are also suspended.
WebLocalFrameImpl* web_local_child =
- FrameTestHelpers::CreateLocalChild(*remote_root);
+ frame_test_helpers::CreateLocalChild(*remote_root);
RegisterMockedHttpURLLoad("foo.html");
- FrameTestHelpers::LoadFrame(web_local_child, base_url_ + "foo.html");
+ frame_test_helpers::LoadFrame(web_local_child, base_url_ + "foo.html");
LocalFrame* local_child = web_local_child->GetFrame();
EXPECT_FALSE(page->Paused());
EXPECT_FALSE(
@@ -10128,7 +10175,7 @@ TEST_F(WebFrameTest, PausedPageLoadWithRemoteMainFrame) {
local_child->GetDocument()->Fetcher()->Context().DefersLoading());
}
-class OverscrollWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class OverscrollWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
MOCK_METHOD5(DidOverscroll,
void(const WebFloatSize&,
@@ -10164,21 +10211,21 @@ class WebFrameOverscrollTest
return WebCoalescedInputEvent(event);
}
- void ScrollBegin(FrameTestHelpers::WebViewHelper* web_view_helper,
+ void ScrollBegin(frame_test_helpers::WebViewHelper* web_view_helper,
float delta_x_hint,
float delta_y_hint) {
web_view_helper->GetWebView()->HandleInputEvent(GenerateEvent(
WebInputEvent::kGestureScrollBegin, delta_x_hint, delta_y_hint));
}
- void ScrollUpdate(FrameTestHelpers::WebViewHelper* web_view_helper,
+ void ScrollUpdate(frame_test_helpers::WebViewHelper* web_view_helper,
float delta_x,
float delta_y) {
web_view_helper->GetWebView()->HandleInputEvent(
GenerateEvent(WebInputEvent::kGestureScrollUpdate, delta_x, delta_y));
}
- void ScrollEnd(FrameTestHelpers::WebViewHelper* web_view_helper) {
+ void ScrollEnd(frame_test_helpers::WebViewHelper* web_view_helper) {
web_view_helper->GetWebView()->HandleInputEvent(
GenerateEvent(WebInputEvent::kGestureScrollEnd));
}
@@ -10193,7 +10240,7 @@ TEST_P(WebFrameOverscrollTest,
AccumulatedRootOverscrollAndUnsedDeltaValuesOnOverscroll) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/overscroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "overscroll/overscroll.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -10247,7 +10294,7 @@ TEST_P(WebFrameOverscrollTest,
AccumulatedOverscrollAndUnusedDeltaValuesOnDifferentAxesOverscroll) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/div-overscroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "overscroll/div-overscroll.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -10296,7 +10343,7 @@ TEST_P(WebFrameOverscrollTest,
TEST_P(WebFrameOverscrollTest, RootLayerOverscrolledOnInnerDivOverScroll) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/div-overscroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "overscroll/div-overscroll.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -10324,7 +10371,7 @@ TEST_P(WebFrameOverscrollTest, RootLayerOverscrolledOnInnerIFrameOverScroll) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/iframe-overscroll.html");
RegisterMockedHttpURLLoad("overscroll/scrollable-iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "overscroll/iframe-overscroll.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -10359,7 +10406,7 @@ TEST_P(WebFrameOverscrollTest, RootLayerOverscrolledOnInnerIFrameOverScroll) {
TEST_P(WebFrameOverscrollTest, ScaledPageRootLayerOverscrolled) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/overscroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "overscroll/overscroll.html", nullptr, &client, nullptr,
ConfigureAndroid);
@@ -10405,7 +10452,7 @@ TEST_P(WebFrameOverscrollTest, ScaledPageRootLayerOverscrolled) {
TEST_P(WebFrameOverscrollTest, NoOverscrollForSmallvalues) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/overscroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "overscroll/overscroll.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -10467,7 +10514,7 @@ TEST_P(WebFrameOverscrollTest, NoOverscrollForSmallvalues) {
TEST_P(WebFrameOverscrollTest, OverscrollBehaviorAffectsDidOverscroll) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/overscroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "overscroll/overscroll.html",
nullptr, &client, nullptr,
ConfigureAndroid);
@@ -10522,7 +10569,7 @@ TEST_P(WebFrameOverscrollTest, OnlyMainFrameOverscrollBehaviorHasEffect) {
OverscrollWebViewClient client;
RegisterMockedHttpURLLoad("overscroll/iframe-overscroll.html");
RegisterMockedHttpURLLoad("overscroll/scrollable-iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "overscroll/iframe-overscroll.html", nullptr, &client,
nullptr, ConfigureAndroid);
@@ -10568,7 +10615,7 @@ TEST_P(WebFrameOverscrollTest, OnlyMainFrameOverscrollBehaviorHasEffect) {
TEST_F(WebFrameTest, OrientationFrameDetach) {
ScopedOrientationEventForTest orientation_event(true);
RegisterMockedHttpURLLoad("orientation-frame-detach.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.InitializeAndLoad(
base_url_ + "orientation-frame-detach.html");
web_view_impl->MainFrameImpl()->SendOrientationChangeEvent();
@@ -10580,7 +10627,7 @@ TEST_F(WebFrameTest, DISABLED_MaxFramesDetach) {
TEST_F(WebFrameTest, MaxFramesDetach) {
#endif // defined(THREAD_SANITIZER)
RegisterMockedHttpURLLoad("max-frames-detach.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.InitializeAndLoad(base_url_ + "max-frames-detach.html");
web_view_impl->MainFrameImpl()->CollectGarbageForTesting();
@@ -10593,7 +10640,7 @@ TEST_F(WebFrameTest, ImageDocumentLoadFinishTime) {
// and the image resource.
RegisterMockedHttpURLLoadWithMimeType("white-1x1.png", "image/png");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "white-1x1.png");
WebViewImpl* web_view = web_view_helper.GetWebView();
Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument();
@@ -10617,7 +10664,7 @@ TEST_F(WebFrameTest, CopyImageDocument) {
// After loading an image document, we should be able to copy it directly.
RegisterMockedHttpURLLoadWithMimeType("white-1x1.png", "image/png");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "white-1x1.png");
WebViewImpl* web_view = web_view_helper.GetWebView();
WebLocalFrameImpl* web_frame = web_view->MainFrameImpl();
@@ -10642,20 +10689,17 @@ TEST_F(WebFrameTest, CopyImageDocument) {
}
class CallbackOrderingWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
CallbackOrderingWebFrameClient() : callback_count_(0) {}
~CallbackOrderingWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void DidStartLoading() override {
EXPECT_EQ(0, callback_count_++);
- FrameTestHelpers::TestWebFrameClient::DidStartLoading();
+ frame_test_helpers::TestWebFrameClient::DidStartLoading();
}
- void DidStartProvisionalLoad(
- WebDocumentLoader*,
- WebURLRequest&,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) override {
+ void DidStartProvisionalLoad(WebDocumentLoader*, WebURLRequest&) override {
EXPECT_EQ(1, callback_count_++);
}
void DidCommitProvisionalLoad(const WebHistoryItem&,
@@ -10668,7 +10712,7 @@ class CallbackOrderingWebFrameClient
void DidFinishLoad() override { EXPECT_EQ(5, callback_count_++); }
void DidStopLoading() override {
EXPECT_EQ(6, callback_count_++);
- FrameTestHelpers::TestWebFrameClient::DidStopLoading();
+ frame_test_helpers::TestWebFrameClient::DidStopLoading();
}
private:
@@ -10678,17 +10722,17 @@ class CallbackOrderingWebFrameClient
TEST_F(WebFrameTest, CallbackOrdering) {
RegisterMockedHttpURLLoad("foo.html");
CallbackOrderingWebFrameClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "foo.html", &client);
}
class TestWebRemoteFrameClientForVisibility
- : public FrameTestHelpers::TestWebRemoteFrameClient {
+ : public frame_test_helpers::TestWebRemoteFrameClient {
public:
TestWebRemoteFrameClientForVisibility() : visible_(true) {}
~TestWebRemoteFrameClientForVisibility() override = default;
- // FrameTestHelpers::TestWebRemoteFrameClient:
+ // frame_test_helpers::TestWebRemoteFrameClient:
void VisibilityChanged(bool visible) override { visible_ = visible; }
bool IsVisible() const { return visible_; }
@@ -10705,14 +10749,15 @@ class WebFrameVisibilityChangeTest : public WebFrameTest {
frame_ =
web_view_helper_.InitializeAndLoad(base_url_ + "single_iframe.html")
->MainFrameImpl();
- web_remote_frame_ = FrameTestHelpers::CreateRemote(&remote_frame_client_);
+ web_remote_frame_ = frame_test_helpers::CreateRemote(&remote_frame_client_);
}
~WebFrameVisibilityChangeTest() override = default;
void ExecuteScriptOnMainFrame(const WebScriptSource& script) {
MainFrame()->ExecuteScript(script);
- MainFrame()->View()->UpdateAllLifecyclePhases();
+ MainFrame()->View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
}
@@ -10728,7 +10773,7 @@ class WebFrameVisibilityChangeTest : public WebFrameTest {
private:
TestWebRemoteFrameClientForVisibility remote_frame_client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
WebLocalFrame* frame_;
Persistent<WebRemoteFrameImpl> web_remote_frame_;
};
@@ -10759,13 +10804,13 @@ static void EnableGlobalReuseForUnownedMainFrames(WebSettings* settings) {
// A main frame with no opener should have a unique security origin. Thus, the
// global should never be reused on the initial navigation.
TEST(WebFrameGlobalReuseTest, MainFrameWithNoOpener) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.Initialize();
WebLocalFrame* main_frame = helper.LocalMainFrame();
v8::HandleScope scope(v8::Isolate::GetCurrent());
main_frame->ExecuteScript(WebScriptSource("hello = 'world';"));
- FrameTestHelpers::LoadFrame(main_frame, "data:text/html,new page");
+ frame_test_helpers::LoadFrame(main_frame, "data:text/html,new page");
v8::Local<v8::Value> result =
main_frame->ExecuteScriptAndReturnValue(WebScriptSource("hello"));
EXPECT_TRUE(result.IsEmpty());
@@ -10775,17 +10820,17 @@ TEST(WebFrameGlobalReuseTest, MainFrameWithNoOpener) {
// if the setting is enabled. It's not safe to since the parent could have
// injected script before the initial navigation.
TEST(WebFrameGlobalReuseTest, ChildFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.Initialize(nullptr, nullptr, nullptr,
EnableGlobalReuseForUnownedMainFrames);
WebLocalFrame* main_frame = helper.LocalMainFrame();
- FrameTestHelpers::LoadFrame(main_frame, "data:text/html,<iframe></iframe>");
+ frame_test_helpers::LoadFrame(main_frame, "data:text/html,<iframe></iframe>");
WebLocalFrame* child_frame = main_frame->FirstChild()->ToWebLocalFrame();
v8::HandleScope scope(v8::Isolate::GetCurrent());
child_frame->ExecuteScript(WebScriptSource("hello = 'world';"));
- FrameTestHelpers::LoadFrame(child_frame, "data:text/html,new page");
+ frame_test_helpers::LoadFrame(child_frame, "data:text/html,new page");
v8::Local<v8::Value> result =
child_frame->ExecuteScriptAndReturnValue(WebScriptSource("hello"));
EXPECT_TRUE(result.IsEmpty());
@@ -10795,9 +10840,9 @@ TEST(WebFrameGlobalReuseTest, ChildFrame) {
// navigation, even if the setting is enabled. It's not safe to since the opener
// could have injected script.
TEST(WebFrameGlobalReuseTest, MainFrameWithOpener) {
- FrameTestHelpers::WebViewHelper opener_helper;
+ frame_test_helpers::WebViewHelper opener_helper;
opener_helper.Initialize();
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeWithOpener(opener_helper.GetWebView()->MainFrame(), nullptr,
nullptr, nullptr,
EnableGlobalReuseForUnownedMainFrames);
@@ -10805,7 +10850,7 @@ TEST(WebFrameGlobalReuseTest, MainFrameWithOpener) {
WebLocalFrame* main_frame = helper.LocalMainFrame();
v8::HandleScope scope(v8::Isolate::GetCurrent());
main_frame->ExecuteScript(WebScriptSource("hello = 'world';"));
- FrameTestHelpers::LoadFrame(main_frame, "data:text/html,new page");
+ frame_test_helpers::LoadFrame(main_frame, "data:text/html,new page");
v8::Local<v8::Value> result =
main_frame->ExecuteScriptAndReturnValue(WebScriptSource("hello"));
EXPECT_TRUE(result.IsEmpty());
@@ -10817,14 +10862,14 @@ TEST(WebFrameGlobalReuseTest, MainFrameWithOpener) {
// the embedder enabling this setting is a signal that the injected script needs
// to persist on the first navigation away from the initial empty document.
TEST(WebFrameGlobalReuseTest, ReuseForMainFrameIfEnabled) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.Initialize(nullptr, nullptr, nullptr,
EnableGlobalReuseForUnownedMainFrames);
WebLocalFrame* main_frame = helper.LocalMainFrame();
v8::HandleScope scope(v8::Isolate::GetCurrent());
main_frame->ExecuteScript(WebScriptSource("hello = 'world';"));
- FrameTestHelpers::LoadFrame(main_frame, "data:text/html,new page");
+ frame_test_helpers::LoadFrame(main_frame, "data:text/html,new page");
v8::Local<v8::Value> result =
main_frame->ExecuteScriptAndReturnValue(WebScriptSource("hello"));
ASSERT_TRUE(result->IsString());
@@ -10834,7 +10879,7 @@ TEST(WebFrameGlobalReuseTest, ReuseForMainFrameIfEnabled) {
}
class SaveImageFromDataURLWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
SaveImageFromDataURLWebFrameClient() = default;
~SaveImageFromDataURLWebFrameClient() override = default;
@@ -10855,14 +10900,14 @@ class SaveImageFromDataURLWebFrameClient
TEST_F(WebFrameTest, SaveImageAt) {
std::string url = base_url_ + "image-with-data-url.html";
RegisterMockedURLLoadFromBase(base_url_, "image-with-data-url.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL("http://test"), test::CoreTestDataPath("white-1x1.png"));
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
SaveImageFromDataURLWebFrameClient client;
WebViewImpl* web_view = helper.InitializeAndLoad(url, &client);
web_view->Resize(WebSize(400, 400));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
WebLocalFrame* local_frame = web_view->MainFrameImpl();
@@ -10895,7 +10940,7 @@ TEST_F(WebFrameTest, SaveImageWithImageMap) {
std::string url = base_url_ + "image-map.html";
RegisterMockedURLLoadFromBase(base_url_, "image-map.html");
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
SaveImageFromDataURLWebFrameClient client;
WebViewImpl* web_view = helper.InitializeAndLoad(url, &client);
web_view->Resize(WebSize(400, 400));
@@ -10930,7 +10975,7 @@ TEST_F(WebFrameTest, CopyImageWithImageMap) {
std::string url = base_url_ + "image-map.html";
RegisterMockedURLLoadFromBase(base_url_, "image-map.html");
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
WebViewImpl* web_view = helper.InitializeAndLoad(url, &client);
web_view->Resize(WebSize(400, 400));
@@ -10957,13 +11002,13 @@ TEST_F(WebFrameTest, CopyImageWithImageMap) {
}
TEST_F(WebFrameTest, LoadJavascriptURLInNewFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.Initialize();
std::string redirect_url = base_url_ + "foo.html";
KURL javascript_url = ToKURL("javascript:location='" + redirect_url + "'");
- URLTestHelpers::RegisterMockedURLLoad(ToKURL(redirect_url),
- test::CoreTestDataPath("foo.html"));
+ url_test_helpers::RegisterMockedURLLoad(ToKURL(redirect_url),
+ test::CoreTestDataPath("foo.html"));
helper.LocalMainFrame()->LoadJavaScriptURL(javascript_url);
// Normally, the result of the JS url replaces the existing contents on the
@@ -10976,7 +11021,7 @@ TEST_F(WebFrameTest, LoadJavascriptURLInNewFrame) {
}
class TestResourcePriorityWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
class ExpectedRequest {
public:
@@ -10991,7 +11036,7 @@ class TestResourcePriorityWebFrameClient
TestResourcePriorityWebFrameClient() = default;
~TestResourcePriorityWebFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void WillSendRequest(WebURLRequest& request) override {
ExpectedRequest* expected_request = expected_requests_.at(request.Url());
DCHECK(expected_request);
@@ -11027,10 +11072,10 @@ TEST_F(WebFrameTest, ChangeResourcePriority) {
ToKURL("http://internal.test/image_slow_out_of_viewport.pl"),
WebURLRequest::Priority::kLow);
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.Initialize(&client);
helper.Resize(WebSize(640, 480));
- FrameTestHelpers::LoadFrame(
+ frame_test_helpers::LoadFrame(
helper.GetWebView()->MainFrameImpl(),
base_url_ + "promote_img_in_viewport_priority.html");
@@ -11078,7 +11123,7 @@ TEST_F(WebFrameTest, ScriptPriority) {
client.AddExpectedRequest(ToKURL("http://internal.test/priorities/body.js"),
WebURLRequest::Priority::kHigh);
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeAndLoad(base_url_ + "script_priority.html", &client);
client.VerifyAllRequests();
}
@@ -11101,11 +11146,11 @@ class MultipleDataChunkDelegate : public WebURLLoaderTestDelegate {
TEST_F(WebFrameTest, ImageDocumentDecodeError) {
std::string url = base_url_ + "not_an_image.ico";
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url), test::CoreTestDataPath("not_an_image.ico"), "image/x-icon");
MultipleDataChunkDelegate delegate;
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(&delegate);
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeAndLoad(url);
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr);
@@ -11124,7 +11169,7 @@ TEST_F(WebFrameTest, RootLayerMinimumHeight) {
constexpr int kViewportHeight = 640;
constexpr int kBrowserControlsHeight = 100;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, nullptr, nullptr, ConfigureAndroid);
WebViewImpl* web_view = web_view_helper.GetWebView();
web_view->ResizeWithBrowserControls(
@@ -11147,7 +11192,7 @@ TEST_F(WebFrameTest, RootLayerMinimumHeight) {
" }"
"</style>"
"<div id='elem'></div>");
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument();
LocalFrameView* frame_view = web_view->MainFrameImpl()->GetFrameView();
@@ -11186,7 +11231,7 @@ TEST_F(WebFrameTest, RootLayerMinimumHeight) {
// due to lack of layoutObject. crbug.com/653327.
TEST_F(WebFrameTest, ScrollBeforeLayoutDoesntCrash) {
RegisterMockedHttpURLLoad("display-none.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "display-none.html");
WebViewImpl* web_view = web_view_helper.GetWebView();
web_view_helper.Resize(WebSize(640, 480));
@@ -11221,7 +11266,7 @@ TEST_F(WebFrameTest, ScrollBeforeLayoutDoesntCrash) {
}
TEST_F(WebFrameTest, MouseOverDifferntNodeClearsTooltip) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize(nullptr, nullptr, nullptr,
[](WebSettings* settings) {});
web_view_helper.Resize(WebSize(200, 200));
@@ -11248,14 +11293,13 @@ TEST_F(WebFrameTest, MouseOverDifferntNodeClearsTooltip) {
" <div id='div2' title='Title Attribute Value'>Then HERE</div>"
" <br><br><br>"
"</body>");
-
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument();
Element* div1_tag = document->getElementById("div1");
HitTestResult hit_test_result = web_view->CoreHitTestResultAt(
- WebPoint(div1_tag->OffsetLeft() + 5, div1_tag->OffsetTop() + 5));
+ gfx::Point(div1_tag->OffsetLeft() + 5, div1_tag->OffsetTop() + 5));
EXPECT_TRUE(hit_test_result.InnerElement());
@@ -11268,7 +11312,8 @@ TEST_F(WebFrameTest, MouseOverDifferntNodeClearsTooltip) {
CurrentTimeTicks());
mouse_move_over_link_event.SetFrameScale(1);
document->GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_over_link_event, Vector<WebMouseEvent>());
+ mouse_move_over_link_event, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
EXPECT_EQ(
document->HoverElement(),
@@ -11287,7 +11332,7 @@ TEST_F(WebFrameTest, MouseOverDifferntNodeClearsTooltip) {
CurrentTimeTicks());
mouse_move_event.SetFrameScale(1);
document->GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
EXPECT_EQ(
document->HoverElement(),
@@ -11490,6 +11535,60 @@ TEST_F(WebFrameSimTest, FindInPageSelectNextMatch) {
<< visual_viewport.VisibleRectInDocument().ToString() << "]";
}
+// Test bubbling a document (End key) scroll from an inner iframe. This test
+// passes if it does not crash. https://crbug.com/904247.
+TEST_F(WebFrameSimTest, ScrollToEndBubblingCrash) {
+ WebView().Resize(WebSize(500, 300));
+ WebView().GetPage()->GetSettings().SetScrollAnimatorEnabled(false);
+
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ }
+ #frame {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ </style>
+ <iframe id="frame" srcdoc="
+ <!DOCTYPE html>
+ <style>html {height: 300%;}</style>
+ "></iframe>
+ )HTML");
+
+ Compositor().BeginFrame();
+ RunPendingTasks();
+
+ // Focus the iframe.
+ WebView().AdvanceFocus(false);
+
+ WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests());
+ key_event.windows_key_code = VKEY_END;
+
+ // Scroll the iframe to the end.
+ key_event.SetType(WebInputEvent::kRawKeyDown);
+ WebView().HandleInputEvent(WebCoalescedInputEvent(key_event));
+ key_event.SetType(WebInputEvent::kKeyUp);
+ WebView().HandleInputEvent(WebCoalescedInputEvent(key_event));
+
+ Compositor().BeginFrame();
+
+ // End key should now bubble from the iframe up to the main viewport.
+ key_event.SetType(WebInputEvent::kRawKeyDown);
+ WebView().HandleInputEvent(WebCoalescedInputEvent(key_event));
+ key_event.SetType(WebInputEvent::kKeyUp);
+ WebView().HandleInputEvent(WebCoalescedInputEvent(key_event));
+}
+
// Basic smoke test of the paint path used by the Android disambiguation popup.
TEST_F(WebFrameSimTest, DisambiguationPopupPixelTest) {
WebView().Resize(WebSize(400, 600));
@@ -11540,7 +11639,8 @@ TEST_F(WebFrameSimTest, DisambiguationPopupPixelTest) {
canvas.scale(scale, scale);
canvas.translate(-zoom_rect.x, -zoom_rect.y);
- WebView().UpdateAllLifecyclePhases();
+ WebView().MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
WebView().PaintContentIgnoringCompositing(&canvas, zoom_rect);
// All the pixels in the canvas should be the <div> color.
@@ -11802,7 +11902,9 @@ TEST_F(WebFrameSimTest, DoubleTapZoomWhileScrolled) {
// Double-tap on the target. Expect that we zoom in and the target is
// contained in the visual viewport.
{
- WebView().AnimateDoubleTapZoom(WebPoint(445, 455));
+ gfx::Point point(445, 455);
+ WebRect block_bounds = ComputeBlockBoundHelper(&WebView(), point, false);
+ WebView().AnimateDoubleTapZoom(IntPoint(point), block_bounds);
EXPECT_TRUE(WebView().FakeDoubleTapAnimationPendingForTesting());
ScrollOffset new_offset = ToScrollOffset(
FloatPoint(WebView().FakePageScaleAnimationTargetPositionForTesting()));
@@ -11822,7 +11924,9 @@ TEST_F(WebFrameSimTest, DoubleTapZoomWhileScrolled) {
// Double-tap on the target again. We should zoom out and the target should
// remain on screen.
{
- WebView().AnimateDoubleTapZoom(WebPoint(445, 455));
+ gfx::Point point(445, 455);
+ WebRect block_bounds = ComputeBlockBoundHelper(&WebView(), point, false);
+ WebView().AnimateDoubleTapZoom(IntPoint(point), block_bounds);
EXPECT_TRUE(WebView().FakeDoubleTapAnimationPendingForTesting());
FloatPoint target_offset(
WebView().FakePageScaleAnimationTargetPositionForTesting());
@@ -12071,12 +12175,12 @@ TEST_F(WebFrameSimTest, NamedLookupIgnoresEmptyNames) {
TEST_F(WebFrameTest, NoLoadingCompletionCallbacksInDetach) {
class LoadingObserverFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
LoadingObserverFrameClient() = default;
~LoadingObserverFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
void FrameDetached(DetachType type) override {
did_call_frame_detached_ = true;
TestWebFrameClient::FrameDetached(type);
@@ -12127,19 +12231,20 @@ TEST_F(WebFrameTest, NoLoadingCompletionCallbacksInDetach) {
bool did_call_did_handle_onload_events_ = false;
};
- class MainFrameClient : public FrameTestHelpers::TestWebFrameClient {
+ class MainFrameClient : public frame_test_helpers::TestWebFrameClient {
public:
MainFrameClient() = default;
~MainFrameClient() override = default;
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
WebLocalFrame* CreateChildFrame(WebLocalFrame* parent,
WebTreeScopeType scope,
const WebString& name,
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties&) override {
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType) override {
return CreateLocalChild(*parent, scope, &child_client_);
}
@@ -12150,12 +12255,12 @@ TEST_F(WebFrameTest, NoLoadingCompletionCallbacksInDetach) {
};
RegisterMockedHttpURLLoad("single_iframe.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(base_url_ + "visible_iframe.html"),
test::CoreTestDataPath("frame_with_frame.html"));
RegisterMockedHttpURLLoad("parent_detaching_frame.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
MainFrameClient main_frame_client;
web_view_helper.InitializeAndLoad(base_url_ + "single_iframe.html",
&main_frame_client);
@@ -12169,9 +12274,9 @@ TEST_F(WebFrameTest, NoLoadingCompletionCallbacksInDetach) {
}
TEST_F(WebFrameTest, ClearClosedOpener) {
- FrameTestHelpers::WebViewHelper opener_helper;
+ frame_test_helpers::WebViewHelper opener_helper;
opener_helper.Initialize();
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeWithOpener(opener_helper.GetWebView()->MainFrame());
opener_helper.Reset();
@@ -12179,13 +12284,13 @@ TEST_F(WebFrameTest, ClearClosedOpener) {
}
class ShowVirtualKeyboardObserverWidgetClient
- : public FrameTestHelpers::TestWebWidgetClient {
+ : public frame_test_helpers::TestWebWidgetClient {
public:
ShowVirtualKeyboardObserverWidgetClient()
: did_show_virtual_keyboard_(false) {}
~ShowVirtualKeyboardObserverWidgetClient() override = default;
- // FrameTestHelpers::TestWebWidgetClient:
+ // frame_test_helpers::TestWebWidgetClient:
void ShowVirtualKeyboardOnElementFocus() override {
did_show_virtual_keyboard_ = true;
}
@@ -12197,17 +12302,17 @@ class ShowVirtualKeyboardObserverWidgetClient
};
TEST_F(WebFrameTest, ShowVirtualKeyboardOnElementFocus) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeRemote();
ShowVirtualKeyboardObserverWidgetClient web_widget_client;
- WebLocalFrameImpl* local_frame = FrameTestHelpers::CreateLocalChild(
+ WebLocalFrameImpl* local_frame = frame_test_helpers::CreateLocalChild(
*web_view_helper.RemoteMainFrame(), "child", WebFrameOwnerProperties(),
nullptr, nullptr, &web_widget_client);
RegisterMockedHttpURLLoad("input_field_default.html");
- FrameTestHelpers::LoadFrame(local_frame,
- base_url_ + "input_field_default.html");
+ frame_test_helpers::LoadFrame(local_frame,
+ base_url_ + "input_field_default.html");
// Simulate an input element focus leading to Element::focus() call with a
// user gesture.
@@ -12223,7 +12328,8 @@ TEST_F(WebFrameTest, ShowVirtualKeyboardOnElementFocus) {
web_view_helper.Reset();
}
-class ContextMenuWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class ContextMenuWebFrameClient
+ : public frame_test_helpers::TestWebFrameClient {
public:
ContextMenuWebFrameClient() = default;
~ContextMenuWebFrameClient() override = default;
@@ -12242,12 +12348,13 @@ class ContextMenuWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
bool TestSelectAll(const std::string& html) {
ContextMenuWebFrameClient frame;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.Initialize(&frame);
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), html,
- ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(), html,
+ ToKURL("about:blank"));
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
web_view->SetInitialFocus(false);
RunPendingTasks();
@@ -12277,13 +12384,13 @@ TEST_F(WebFrameTest, ContextMenuDataSelectAll) {
TEST_F(WebFrameTest, ContextMenuDataSelectedText) {
ContextMenuWebFrameClient frame;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.Initialize(&frame);
const std::string& html = "<input value=' '>";
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), html,
- ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(), html,
+ ToKURL("about:blank"));
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
web_view->SetInitialFocus(false);
RunPendingTasks();
@@ -12305,13 +12412,13 @@ TEST_F(WebFrameTest, ContextMenuDataSelectedText) {
TEST_F(WebFrameTest, ContextMenuDataPasswordSelectedText) {
ContextMenuWebFrameClient frame;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.Initialize(&frame);
const std::string& html = "<input type='password' value='password'>";
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), html,
- ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(), html,
+ ToKURL("about:blank"));
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
web_view->SetInitialFocus(false);
RunPendingTasks();
@@ -12336,15 +12443,15 @@ TEST_F(WebFrameTest, ContextMenuDataPasswordSelectedText) {
TEST_F(WebFrameTest, ContextMenuDataNonLocatedMenu) {
ContextMenuWebFrameClient frame;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.Initialize(&frame);
const std::string& html =
"<div style='font-size: 1000%; line-height: 0.7em'>Select me<br/>"
"Next line</div>";
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), html,
- ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(), html,
+ ToKURL("about:blank"));
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
web_view->SetInitialFocus(false);
RunPendingTasks();
@@ -12367,19 +12474,20 @@ TEST_F(WebFrameTest, ContextMenuDataNonLocatedMenu) {
}
TEST_F(WebFrameTest, LocalFrameWithRemoteParentIsTransparent) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeRemote();
WebLocalFrameImpl* local_frame =
- FrameTestHelpers::CreateLocalChild(*helper.RemoteMainFrame());
- FrameTestHelpers::LoadFrame(local_frame, "data:text/html,some page");
+ frame_test_helpers::CreateLocalChild(*helper.RemoteMainFrame());
+ frame_test_helpers::LoadFrame(local_frame, "data:text/html,some page");
// Local frame with remote parent should have transparent baseBackgroundColor.
Color color = local_frame->GetFrameView()->BaseBackgroundColor();
EXPECT_EQ(Color::kTransparent, color);
}
-class TestFallbackWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class TestFallbackWebFrameClient
+ : public frame_test_helpers::TestWebFrameClient {
public:
TestFallbackWebFrameClient() : child_client_(nullptr) {}
~TestFallbackWebFrameClient() override = default;
@@ -12388,7 +12496,7 @@ class TestFallbackWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
child_client_ = client;
}
- // FrameTestHelpers::TestWebFrameClient:
+ // frame_test_helpers::TestWebFrameClient:
WebLocalFrame* CreateChildFrame(
WebLocalFrame* parent,
WebTreeScopeType scope,
@@ -12396,15 +12504,20 @@ class TestFallbackWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
const WebString&,
WebSandboxFlags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties& frameOwnerProperties) override {
+ const WebFrameOwnerProperties& frameOwnerProperties,
+ FrameOwnerElementType) override {
DCHECK(child_client_);
return CreateLocalChild(*parent, scope, child_client_);
}
- WebNavigationPolicy DecidePolicyForNavigation(
- const NavigationPolicyInfo& info) override {
- if (child_client_ || KURL(info.url_request.Url()) == BlankURL())
- return kWebNavigationPolicyCurrentTab;
- return kWebNavigationPolicyHandledByClient;
+ void BeginNavigation(std::unique_ptr<WebNavigationInfo> info) override {
+ if (child_client_ || KURL(info->url_request.Url()) == BlankURL()) {
+ TestWebFrameClient::BeginNavigation(std::move(info));
+ return;
+ }
+ Frame()->CreatePlaceholderDocumentLoader(
+ info->url_request, info->frame_load_type, info->navigation_type,
+ info->is_client_redirect, base::UnguessableToken::Create(), nullptr,
+ nullptr);
}
private:
@@ -12417,16 +12530,16 @@ TEST_F(WebFrameTest, FallbackForNonexistentProvisionalNavigation) {
TestFallbackWebFrameClient child_client;
main_client.SetChildWebFrameClient(&child_client);
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
web_view_helper_.Initialize(&main_client);
WebLocalFrameImpl* main_frame = web_view_helper_.LocalMainFrame();
WebURLRequest request(ToKURL(base_url_ + "fallback.html"));
main_frame->StartNavigation(request);
- // Because the child frame will be HandledByClient, the main frame will not
- // finish loading, so FrameTestHelpers::PumpPendingRequestsForFrameToLoad
- // doesn't work here.
+ // Because the child frame will have placeholder document loader, the main
+ // frame will not finish loading, so
+ // frame_test_helpers::PumpPendingRequestsForFrameToLoad doesn't work here.
Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests();
// Overwrite the client-handled child frame navigation with about:blank.
@@ -12437,21 +12550,21 @@ TEST_F(WebFrameTest, FallbackForNonexistentProvisionalNavigation) {
// content shouldn't crash. It should return NoLoadInProgress. This is so the
// caller won't attempt to replace the correctly empty frame with an error
// page.
- EXPECT_EQ(
- WebLocalFrame::NoLoadInProgress,
- child->MaybeRenderFallbackContent(ResourceError::Failure(request.Url())));
+ EXPECT_EQ(WebNavigationControl::NoLoadInProgress,
+ ToWebLocalFrameImpl(child)->MaybeRenderFallbackContent(
+ ResourceError::Failure(request.Url())));
}
TEST_F(WebFrameTest, AltTextOnAboutBlankPage) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
web_view_helper.Resize(WebSize(640, 480));
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
const char kSource[] =
"<img id='foo' src='foo' alt='foo alt' width='200' height='200'>";
- FrameTestHelpers::LoadHTMLString(frame, kSource, ToKURL("about:blank"));
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ frame_test_helpers::LoadHTMLString(frame, kSource, ToKURL("about:blank"));
+ UpdateAllLifecyclePhases(web_view_helper.GetWebView());
RunPendingTasks();
// Check LayoutText with alt text "foo alt"
@@ -12473,7 +12586,7 @@ TEST_F(WebFrameTest, AltTextOnAboutBlankPage) {
TEST_F(WebFrameTest, NavigatorPluginsClearedWhenPluginsDisabled) {
ScopedFakePluginRegistry fake_plugins;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
@@ -12492,7 +12605,7 @@ TEST_F(WebFrameTest, NavigatorPluginsClearedWhenPluginsDisabled) {
TEST_F(WebFrameTest, RecordSameDocumentNavigationToHistogram) {
const char* histogramName =
"RendererScheduler.UpdateForSameDocumentNavigationCount";
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
HistogramTester tester;
web_view_helper.InitializeAndLoad("about:blank");
LocalFrame* frame =
@@ -12531,7 +12644,7 @@ TEST_F(WebFrameTest, RecordSameDocumentNavigationToHistogram) {
}
TEST_F(WebFrameTest, DidScrollCallbackAfterScrollableAreaChanges) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
web_view_helper.Resize(WebSize(200, 200));
WebViewImpl* web_view = web_view_helper.GetWebView();
@@ -12550,7 +12663,7 @@ TEST_F(WebFrameTest, DidScrollCallbackAfterScrollableAreaChanges) {
" <div id='forceScroll'></div>"
"</div>");
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument();
Element* scrollable = document->getElementById("scrollable");
@@ -12567,11 +12680,11 @@ TEST_F(WebFrameTest, DidScrollCallbackAfterScrollableAreaChanges) {
// area using the DidScroll callback.
EXPECT_EQ(ScrollOffset(), scrollable_area->GetScrollOffset());
cc_scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 1));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
EXPECT_EQ(ScrollOffset(0, 1), scrollable_area->GetScrollOffset());
// Make the scrollable area non-scrollable.
- scrollable->setAttribute(HTMLNames::styleAttr, "overflow: visible");
+ scrollable->setAttribute(html_names::kStyleAttr, "overflow: visible");
// Update layout without updating compositing state.
WebLocalFrame* frame = web_view_helper.LocalMainFrame();
@@ -12587,361 +12700,6 @@ TEST_F(WebFrameTest, DidScrollCallbackAfterScrollableAreaChanges) {
cc_scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 3));
}
-// Tests the integration between blink and cc with slimming paint where a layer
-// list is sent to cc.
-class SlimmingPaintWebFrameTest : public PaintTestConfigurations,
- public WebFrameTest {
- public:
- void SetUp() override {
- web_view_helper_ = std::make_unique<FrameTestHelpers::WebViewHelper>();
- web_view_helper_->Initialize(nullptr, &web_view_client_, nullptr,
- &ConfigureCompositingWebView);
- web_view_helper_->Resize(WebSize(200, 200));
-
- // The paint artifact compositor should have been created as part of the
- // web view helper setup.
- DCHECK(paint_artifact_compositor());
- paint_artifact_compositor()->EnableExtraDataForTesting();
- }
-
- WebLocalFrame* LocalMainFrame() { return web_view_helper_->LocalMainFrame(); }
-
- LocalFrameView* GetLocalFrameView() {
- return web_view_helper_->LocalMainFrame()->GetFrameView();
- }
-
- WebViewImpl* WebView() { return web_view_helper_->GetWebView(); }
-
- size_t ContentLayerCount() {
- return paint_artifact_compositor()
- ->GetExtraDataForTesting()
- ->content_layers.size();
- }
-
- cc::Layer* ContentLayerAt(size_t index) {
- return paint_artifact_compositor()
- ->GetExtraDataForTesting()
- ->content_layers[index]
- .get();
- }
-
- size_t ScrollHitTestLayerCount() {
- return paint_artifact_compositor()
- ->GetExtraDataForTesting()
- ->scroll_hit_test_layers.size();
- }
-
- cc::Layer* ScrollHitTestLayerAt(unsigned index) {
- return paint_artifact_compositor()
- ->GetExtraDataForTesting()
- ->ScrollHitTestWebLayerAt(index);
- }
-
- cc::LayerTreeHost* LayerTreeHost() {
- return web_view_client_.layer_tree_view()->layer_tree_host();
- }
-
- Element* GetElementById(const AtomicString& id) {
- WebLocalFrameImpl* frame = web_view_helper_->LocalMainFrame();
- return frame->GetFrame()->GetDocument()->getElementById(id);
- }
-
- private:
- PaintArtifactCompositor* paint_artifact_compositor() {
- return GetLocalFrameView()->GetPaintArtifactCompositorForTesting();
- }
- FrameTestHelpers::TestWebViewClient web_view_client_;
- std::unique_ptr<FrameTestHelpers::WebViewHelper> web_view_helper_;
-};
-
-INSTANTIATE_LAYER_LIST_TEST_CASE_P(SlimmingPaintWebFrameTest);
-
-TEST_P(SlimmingPaintWebFrameTest, DidScrollCallbackAfterScrollableAreaChanges) {
- InitializeWithHTML(*WebView()->MainFrameImpl()->GetFrame(),
- "<style>"
- " #scrollable {"
- " height: 100px;"
- " width: 100px;"
- " overflow: scroll;"
- " will-change: transform;"
- " }"
- " #forceScroll { height: 120px; width: 50px; }"
- "</style>"
- "<div id='scrollable'>"
- " <div id='forceScroll'></div>"
- "</div>");
-
- WebView()->UpdateAllLifecyclePhases();
-
- Document* document = WebView()->MainFrameImpl()->GetFrame()->GetDocument();
- Element* scrollable = document->getElementById("scrollable");
-
- auto* scrollable_area =
- ToLayoutBox(scrollable->GetLayoutObject())->GetScrollableArea();
- EXPECT_NE(nullptr, scrollable_area);
-
- auto initial_content_layer_count = ContentLayerCount();
- auto initial_scroll_hit_test_layer_count = ScrollHitTestLayerCount();
-
- cc::Layer* overflow_scroll_layer = nullptr;
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- overflow_scroll_layer = ScrollHitTestLayerAt(ScrollHitTestLayerCount() - 1);
- } else {
- overflow_scroll_layer = ContentLayerAt(ContentLayerCount() - 2);
- }
- EXPECT_TRUE(overflow_scroll_layer->scrollable());
- EXPECT_EQ(overflow_scroll_layer->scroll_container_bounds(),
- gfx::Size(100, 100));
-
- // Ensure a synthetic impl-side scroll offset propagates to the scrollable
- // area using the DidScroll callback.
- EXPECT_EQ(ScrollOffset(), scrollable_area->GetScrollOffset());
- overflow_scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 1));
- WebView()->UpdateAllLifecyclePhases();
- EXPECT_EQ(ScrollOffset(0, 1), scrollable_area->GetScrollOffset());
-
- // Make the scrollable area non-scrollable.
- scrollable->setAttribute(HTMLNames::styleAttr, "overflow: visible");
-
- // Update layout without updating compositing state.
- LocalMainFrame()->ExecuteScript(
- WebScriptSource("var forceLayoutFromScript = scrollable.offsetTop;"));
- EXPECT_EQ(document->Lifecycle().GetState(), DocumentLifecycle::kLayoutClean);
-
- EXPECT_EQ(nullptr,
- ToLayoutBox(scrollable->GetLayoutObject())->GetScrollableArea());
-
- // The web scroll layer has not been deleted yet and we should be able to
- // apply impl-side offsets without crashing.
- EXPECT_EQ(ContentLayerCount(), initial_content_layer_count);
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- EXPECT_EQ(ScrollHitTestLayerCount(), initial_scroll_hit_test_layer_count);
- overflow_scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 3));
-
- WebView()->UpdateAllLifecyclePhases();
- EXPECT_LT(ContentLayerCount(), initial_content_layer_count);
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- EXPECT_LT(ScrollHitTestLayerCount(), initial_scroll_hit_test_layer_count);
-}
-
-TEST_P(SlimmingPaintWebFrameTest, FrameViewScroll) {
- InitializeWithHTML(*WebView()->MainFrameImpl()->GetFrame(),
- "<style>"
- " #forceScroll {"
- " height: 2000px;"
- " width: 100px;"
- " }"
- "</style>"
- "<div id='forceScroll'></div>");
-
- WebView()->UpdateAllLifecyclePhases();
-
- auto* scrollable_area = GetLocalFrameView()->LayoutViewport();
- EXPECT_NE(nullptr, scrollable_area);
-
- cc::Layer* scroll_layer = nullptr;
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- EXPECT_EQ(ScrollHitTestLayerCount(), 1u);
- scroll_layer = ScrollHitTestLayerAt(0);
- } else {
- // Find the last scroll layer.
- for (size_t index = ContentLayerCount() - 1; index >= 0; index--) {
- if (ContentLayerAt(index)->scrollable()) {
- scroll_layer = ContentLayerAt(index);
- break;
- }
- }
- }
- EXPECT_TRUE(scroll_layer->scrollable());
-
- // Ensure a synthetic impl-side scroll offset propagates to the scrollable
- // area using the DidScroll callback.
- EXPECT_EQ(ScrollOffset(), scrollable_area->GetScrollOffset());
- scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 1));
- WebView()->UpdateAllLifecyclePhases();
- EXPECT_EQ(ScrollOffset(0, 1), scrollable_area->GetScrollOffset());
-}
-
-class SlimmingPaintWebFrameSimTest : public PaintTestConfigurations,
- public WebFrameSimTest {
- public:
- void InitializeWithHTML(const String& html) {
- WebView().Resize(WebSize(800, 600));
-
- SimRequest request("https://example.com/test.html", "text/html");
- LoadURL("https://example.com/test.html");
- request.Complete(html);
-
- // Enable the paint artifact compositor extra testing data.
- WebView().UpdateAllLifecyclePhases();
- DCHECK(paint_artifact_compositor());
- paint_artifact_compositor()->EnableExtraDataForTesting();
- WebView().UpdateAllLifecyclePhases();
- DCHECK(paint_artifact_compositor()->GetExtraDataForTesting());
- }
-
- size_t ContentLayerCount() {
- return paint_artifact_compositor()
- ->GetExtraDataForTesting()
- ->content_layers.size();
- }
-
- cc::Layer* ContentLayerAt(size_t index) {
- return paint_artifact_compositor()
- ->GetExtraDataForTesting()
- ->content_layers[index]
- .get();
- }
-
- Element* GetElementById(const AtomicString& id) {
- return MainFrame().GetFrame()->GetDocument()->getElementById(id);
- }
-
- private:
- PaintArtifactCompositor* paint_artifact_compositor() {
- return MainFrame().GetFrameView()->GetPaintArtifactCompositorForTesting();
- }
-};
-
-INSTANTIATE_LAYER_LIST_TEST_CASE_P(SlimmingPaintWebFrameSimTest);
-
-TEST_P(SlimmingPaintWebFrameSimTest, LayerUpdatesDoNotInvalidateEarlierLayers) {
- // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
- // we cannot guarantee that both divs will be composited in this test. When
- // SPV2 gets closer to launch, this test should be updated to pass.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
- InitializeWithHTML(R"HTML(
- <!DOCTYPE html>
- <style>
- html { overflow: hidden; }
- div {
- width: 100px;
- height: 100px;
- will-change: transform;
- }
- </style>
- <div id='a'></div>
- <div id='b'></div>
- )HTML");
-
- Compositor().BeginFrame();
-
- auto* a_element = GetElementById("a");
- auto* a_layer = ContentLayerAt(ContentLayerCount() - 2);
- DCHECK_EQ(a_layer->element_id(), CompositorElementIdFromUniqueObjectId(
- a_element->GetLayoutObject()->UniqueId(),
- CompositorElementIdNamespace::kPrimary));
- auto* b_element = GetElementById("b");
- auto* b_layer = ContentLayerAt(ContentLayerCount() - 1);
- DCHECK_EQ(b_layer->element_id(), CompositorElementIdFromUniqueObjectId(
- b_element->GetLayoutObject()->UniqueId(),
- CompositorElementIdNamespace::kPrimary));
-
- // Initially, neither a nor b should have a layer that should push properties.
- auto* host = Compositor().layer_tree_view().layer_tree_host();
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
-
- // Modifying b should only cause the b layer to need to push properties.
- b_element->setAttribute(HTMLNames::styleAttr, "opacity: 0.2");
- WebView().UpdateAllLifecyclePhases();
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
- EXPECT_TRUE(host->LayersThatShouldPushProperties().count(b_layer));
-
- // After a frame, no layers should need to push properties again.
- Compositor().BeginFrame();
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
-}
-
-TEST_P(SlimmingPaintWebFrameSimTest, LayerUpdatesDoNotInvalidateLaterLayers) {
- // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
- // we cannot guarantee that both divs will be composited in this test. When
- // SPV2 gets closer to launch, this test should be updated to pass.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
- InitializeWithHTML(R"HTML(
- <!DOCTYPE html>
- <style>
- html { overflow: hidden; }
- div {
- width: 100px;
- height: 100px;
- will-change: transform;
- }
- </style>
- <div id='a'></div>
- <div id='b' style='opacity: 0.2;'></div>
- <div id='c'></div>
- )HTML");
-
- Compositor().BeginFrame();
-
- auto* a_element = GetElementById("a");
- auto* a_layer = ContentLayerAt(ContentLayerCount() - 3);
- DCHECK_EQ(a_layer->element_id(), CompositorElementIdFromUniqueObjectId(
- a_element->GetLayoutObject()->UniqueId(),
- CompositorElementIdNamespace::kPrimary));
- auto* b_element = GetElementById("b");
- auto* b_layer = ContentLayerAt(ContentLayerCount() - 2);
- DCHECK_EQ(b_layer->element_id(), CompositorElementIdFromUniqueObjectId(
- b_element->GetLayoutObject()->UniqueId(),
- CompositorElementIdNamespace::kPrimary));
- auto* c_element = GetElementById("c");
- auto* c_layer = ContentLayerAt(ContentLayerCount() - 1);
- DCHECK_EQ(c_layer->element_id(), CompositorElementIdFromUniqueObjectId(
- c_element->GetLayoutObject()->UniqueId(),
- CompositorElementIdNamespace::kPrimary));
-
- // Initially, no layer should need to push properties.
- auto* host = Compositor().layer_tree_view().layer_tree_host();
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(c_layer));
-
- // Modifying a and b (adding opacity to a and removing opacity from b) should
- // not cause the c layer to push properties.
- a_element->setAttribute(HTMLNames::styleAttr, "opacity: 0.3");
- b_element->setAttribute(HTMLNames::styleAttr, "");
- WebView().UpdateAllLifecyclePhases();
- EXPECT_TRUE(host->LayersThatShouldPushProperties().count(a_layer));
- EXPECT_TRUE(host->LayersThatShouldPushProperties().count(b_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(c_layer));
-
- // After a frame, no layers should need to push properties again.
- Compositor().BeginFrame();
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
- EXPECT_FALSE(host->LayersThatShouldPushProperties().count(c_layer));
-}
-
-TEST_P(SlimmingPaintWebFrameSimTest, NoopChangeDoesNotCauseFullTreeSync) {
- InitializeWithHTML(R"HTML(
- <!DOCTYPE html>
- <style>
- div {
- width: 100px;
- height: 100px;
- will-change: transform;
- }
- </style>
- <div></div>
- )HTML");
-
- Compositor().BeginFrame();
-
- // Initially the host should not need to sync.
- auto* layer_tree_host = Compositor().layer_tree_view().layer_tree_host();
- EXPECT_FALSE(layer_tree_host->needs_full_tree_sync());
-
- // A no-op update should not cause the host to need a full tree sync.
- WebView().UpdateAllLifecyclePhases();
- EXPECT_FALSE(layer_tree_host->needs_full_tree_sync());
-}
-
static void TestFramePrinting(WebLocalFrameImpl* frame) {
WebPrintParams print_params;
WebSize page_size(500, 500);
@@ -12955,7 +12713,7 @@ static void TestFramePrinting(WebLocalFrameImpl* frame) {
TEST_F(WebFrameTest, PrintDetachedIframe) {
RegisterMockedHttpURLLoad("print-detached-iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "print-detached-iframe.html");
TestFramePrinting(
ToWebLocalFrameImpl(web_view_helper.LocalMainFrame()->FirstChild()));
@@ -12963,14 +12721,14 @@ TEST_F(WebFrameTest, PrintDetachedIframe) {
TEST_F(WebFrameTest, PrintIframeUnderDetached) {
RegisterMockedHttpURLLoad("print-detached-iframe.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "print-detached-iframe.html");
TestFramePrinting(ToWebLocalFrameImpl(
web_view_helper.LocalMainFrame()->FirstChild()->FirstChild()));
}
TEST_F(WebFrameTest, ExecuteCommandProducesUserGesture) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
@@ -12982,17 +12740,17 @@ TEST_F(WebFrameTest, ExecuteCommandProducesUserGesture) {
}
TEST_F(WebFrameTest, GetCanonicalUrlForSharingNone) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad("about:blank");
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
EXPECT_TRUE(frame->GetDocument().CanonicalUrlForSharing().IsNull());
}
TEST_F(WebFrameTest, GetCanonicalUrlForSharingNotInHead) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadHTMLString(
+ frame_test_helpers::LoadHTMLString(
frame, R"(
<body>
<link rel="canonical" href="https://example.com/canonical.html">
@@ -13001,10 +12759,10 @@ TEST_F(WebFrameTest, GetCanonicalUrlForSharingNotInHead) {
}
TEST_F(WebFrameTest, GetCanonicalUrlForSharing) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadHTMLString(
+ frame_test_helpers::LoadHTMLString(
frame, R"(
<head>
<link rel="canonical" href="https://example.com/canonical.html">
@@ -13014,10 +12772,10 @@ TEST_F(WebFrameTest, GetCanonicalUrlForSharing) {
}
TEST_F(WebFrameTest, GetCanonicalUrlForSharingMultiple) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.Initialize();
WebLocalFrameImpl* frame = web_view_helper.LocalMainFrame();
- FrameTestHelpers::LoadHTMLString(
+ frame_test_helpers::LoadHTMLString(
frame, R"(
<head>
<link rel="canonical" href="https://example.com/canonical1.html">
@@ -13073,7 +12831,8 @@ TEST_F(WebFrameSimTest, EnterFullscreenResetScrollAndScaleState) {
// Confirm that exiting fullscreen restores back to default values.
WebView().DidExitFullscreen();
- WebView().UpdateAllLifecyclePhases();
+ WebView().MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
EXPECT_EQ(0.5f, WebView().PageScaleFactor());
EXPECT_EQ(94, WebView().MainFrameImpl()->GetScrollOffset().width);
@@ -13083,14 +12842,14 @@ TEST_F(WebFrameSimTest, EnterFullscreenResetScrollAndScaleState) {
}
TEST_F(WebFrameTest, MediaQueriesInLocalFrameInsideRemote) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
FixedLayoutTestWebViewClient client;
client.screen_info_.is_monochrome = false;
client.screen_info_.depth_per_component = 8;
helper.InitializeRemote(nullptr, nullptr, &client);
WebLocalFrameImpl* local_frame =
- FrameTestHelpers::CreateLocalChild(*helper.RemoteMainFrame());
+ frame_test_helpers::CreateLocalChild(*helper.RemoteMainFrame());
ASSERT_TRUE(local_frame->GetFrame());
MediaValues* media_values =
diff --git a/chromium/third_party/blink/renderer/core/exported/web_history_item.cc b/chromium/third_party/blink/renderer/core/exported/web_history_item.cc
index 871f080e5ce..a67d23e592a 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_history_item.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_history_item.cc
@@ -70,15 +70,14 @@ WebString WebHistoryItem::GetReferrer() const {
return private_->GetReferrer().referrer;
}
-WebReferrerPolicy WebHistoryItem::GetReferrerPolicy() const {
- return static_cast<WebReferrerPolicy>(
- private_->GetReferrer().referrer_policy);
+network::mojom::ReferrerPolicy WebHistoryItem::GetReferrerPolicy() const {
+ return private_->GetReferrer().referrer_policy;
}
-void WebHistoryItem::SetReferrer(const WebString& referrer,
- WebReferrerPolicy referrer_policy) {
- private_->SetReferrer(
- Referrer(referrer, static_cast<ReferrerPolicy>(referrer_policy)));
+void WebHistoryItem::SetReferrer(
+ const WebString& referrer,
+ network::mojom::ReferrerPolicy referrer_policy) {
+ private_->SetReferrer(Referrer(referrer, referrer_policy));
}
const WebString& WebHistoryItem::Target() const {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_hit_test_result.cc b/chromium/third_party/blink/renderer/core/exported/web_hit_test_result.cc
index 20ebff56a21..c473e267d11 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_hit_test_result.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_hit_test_result.cc
@@ -42,13 +42,14 @@ class WebHitTestResultPrivate
public:
static WebHitTestResultPrivate* Create(const HitTestResult&);
static WebHitTestResultPrivate* Create(const WebHitTestResultPrivate&);
- void Trace(blink::Visitor* visitor) { visitor->Trace(result_); }
- const HitTestResult& Result() const { return result_; }
- private:
WebHitTestResultPrivate(const HitTestResult&);
WebHitTestResultPrivate(const WebHitTestResultPrivate&);
+ void Trace(blink::Visitor* visitor) { visitor->Trace(result_); }
+ const HitTestResult& Result() const { return result_; }
+
+ private:
HitTestResult result_;
};
@@ -62,12 +63,12 @@ inline WebHitTestResultPrivate::WebHitTestResultPrivate(
WebHitTestResultPrivate* WebHitTestResultPrivate::Create(
const HitTestResult& result) {
- return new WebHitTestResultPrivate(result);
+ return MakeGarbageCollected<WebHitTestResultPrivate>(result);
}
WebHitTestResultPrivate* WebHitTestResultPrivate::Create(
const WebHitTestResultPrivate& result) {
- return new WebHitTestResultPrivate(result);
+ return MakeGarbageCollected<WebHitTestResultPrivate>(result);
}
WebNode WebHitTestResult::GetNode() const {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_input_element.cc b/chromium/third_party/blink/renderer/core/exported/web_input_element.cc
index c93cbc20d0d..048beb0d3e9 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_input_element.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_input_element.cc
@@ -50,15 +50,15 @@ bool WebInputElement::IsTextField() const {
bool WebInputElement::IsText() const {
return ConstUnwrap<HTMLInputElement>()->IsTextField() &&
- ConstUnwrap<HTMLInputElement>()->type() != InputTypeNames::number;
+ ConstUnwrap<HTMLInputElement>()->type() != input_type_names::kNumber;
}
bool WebInputElement::IsEmailField() const {
- return ConstUnwrap<HTMLInputElement>()->type() == InputTypeNames::email;
+ return ConstUnwrap<HTMLInputElement>()->type() == input_type_names::kEmail;
}
bool WebInputElement::IsPasswordField() const {
- return ConstUnwrap<HTMLInputElement>()->type() == InputTypeNames::password;
+ return ConstUnwrap<HTMLInputElement>()->type() == input_type_names::kPassword;
}
bool WebInputElement::IsPasswordFieldForAutofill() const {
@@ -67,19 +67,19 @@ bool WebInputElement::IsPasswordFieldForAutofill() const {
return true;
}
- return ConstUnwrap<HTMLInputElement>()->type() == InputTypeNames::password;
+ return ConstUnwrap<HTMLInputElement>()->type() == input_type_names::kPassword;
}
bool WebInputElement::IsImageButton() const {
- return ConstUnwrap<HTMLInputElement>()->type() == InputTypeNames::image;
+ return ConstUnwrap<HTMLInputElement>()->type() == input_type_names::kImage;
}
bool WebInputElement::IsRadioButton() const {
- return ConstUnwrap<HTMLInputElement>()->type() == InputTypeNames::radio;
+ return ConstUnwrap<HTMLInputElement>()->type() == input_type_names::kRadio;
}
bool WebInputElement::IsCheckbox() const {
- return ConstUnwrap<HTMLInputElement>()->type() == InputTypeNames::checkbox;
+ return ConstUnwrap<HTMLInputElement>()->type() == input_type_names::kCheckbox;
}
int WebInputElement::MaxLength() const {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_language_detection_details.cc b/chromium/third_party/blink/renderer/core/exported/web_language_detection_details.cc
index 78910b98955..d54c9a2f896 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_language_detection_details.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_language_detection_details.cc
@@ -19,7 +19,7 @@ const AtomicString& DocumentLanguage(const Document& document) {
Element* html_element = document.documentElement();
if (!html_element)
return g_null_atom;
- return html_element->getAttribute(HTMLNames::langAttr);
+ return html_element->getAttribute(html_names::kLangAttr);
}
bool HasNoTranslate(const Document& document) {
@@ -37,7 +37,7 @@ bool HasNoTranslate(const Document& document) {
// Check if the tag contains content="notranslate" or value="notranslate"
AtomicString content = meta_element.Content();
if (content.IsNull())
- content = meta_element.getAttribute(HTMLNames::valueAttr);
+ content = meta_element.getAttribute(html_names::kValueAttr);
if (EqualIgnoringASCIICase(content, "notranslate"))
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_layer_test.cc b/chromium/third_party/blink/renderer/core/exported/web_layer_test.cc
new file mode 100644
index 00000000000..359904e49a3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/exported/web_layer_test.cc
@@ -0,0 +1,653 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "build/build_config.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
+#include "third_party/blink/public/web/web_script_source.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/core/html/html_element.h"
+#include "third_party/blink/renderer/core/layout/layout_box.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
+#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
+#include "third_party/blink/renderer/platform/testing/paint_test_configurations.h"
+
+namespace blink {
+
+// Tests the integration between blink and cc where a layer list is sent to cc.
+class WebLayerListTest : public PaintTestConfigurations, public testing::Test {
+ public:
+ static void ConfigureCompositingWebView(WebSettings* settings) {
+ settings->SetPreferCompositingToLCDTextEnabled(true);
+ }
+
+ ~WebLayerListTest() override {
+ Platform::Current()
+ ->GetURLLoaderMockFactory()
+ ->UnregisterAllURLsAndClearMemoryCache();
+ }
+
+ void SetUp() override {
+ web_view_helper_ = std::make_unique<frame_test_helpers::WebViewHelper>();
+ web_view_helper_->Initialize(nullptr, &web_view_client_, nullptr,
+ &ConfigureCompositingWebView);
+ web_view_helper_->Resize(WebSize(200, 200));
+
+ // The paint artifact compositor should have been created as part of the
+ // web view helper setup.
+ DCHECK(paint_artifact_compositor());
+ paint_artifact_compositor()->EnableExtraDataForTesting();
+ }
+
+ // Both sets the inner html and runs the document lifecycle.
+ void InitializeWithHTML(LocalFrame& frame, const String& html_content) {
+ frame.GetDocument()->body()->SetInnerHTMLFromString(html_content);
+ frame.GetDocument()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
+ WebLocalFrame* LocalMainFrame() { return web_view_helper_->LocalMainFrame(); }
+
+ LocalFrameView* GetLocalFrameView() {
+ return web_view_helper_->LocalMainFrame()->GetFrameView();
+ }
+
+ WebViewImpl* WebView() { return web_view_helper_->GetWebView(); }
+
+ size_t ContentLayerCount() {
+ return paint_artifact_compositor()
+ ->GetExtraDataForTesting()
+ ->content_layers.size();
+ }
+
+ cc::Layer* ContentLayerAt(size_t index) {
+ return paint_artifact_compositor()
+ ->GetExtraDataForTesting()
+ ->content_layers[index]
+ .get();
+ }
+
+ size_t ScrollHitTestLayerCount() {
+ return paint_artifact_compositor()
+ ->GetExtraDataForTesting()
+ ->scroll_hit_test_layers.size();
+ }
+
+ cc::Layer* ScrollHitTestLayerAt(unsigned index) {
+ return paint_artifact_compositor()
+ ->GetExtraDataForTesting()
+ ->ScrollHitTestWebLayerAt(index);
+ }
+
+ cc::LayerTreeHost* LayerTreeHost() {
+ return web_view_client_.layer_tree_view()->layer_tree_host();
+ }
+
+ Element* GetElementById(const AtomicString& id) {
+ WebLocalFrameImpl* frame = web_view_helper_->LocalMainFrame();
+ return frame->GetFrame()->GetDocument()->getElementById(id);
+ }
+
+ void UpdateAllLifecyclePhases() {
+ WebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
+ private:
+ PaintArtifactCompositor* paint_artifact_compositor() {
+ return GetLocalFrameView()->GetPaintArtifactCompositorForTesting();
+ }
+
+ frame_test_helpers::TestWebViewClient web_view_client_;
+ std::unique_ptr<frame_test_helpers::WebViewHelper> web_view_helper_;
+};
+
+INSTANTIATE_LAYER_LIST_TEST_CASE_P(WebLayerListTest);
+
+TEST_P(WebLayerListTest, DidScrollCallbackAfterScrollableAreaChanges) {
+ InitializeWithHTML(*WebView()->MainFrameImpl()->GetFrame(),
+ "<style>"
+ " #scrollable {"
+ " height: 100px;"
+ " width: 100px;"
+ " overflow: scroll;"
+ " will-change: transform;"
+ " }"
+ " #forceScroll { height: 120px; width: 50px; }"
+ "</style>"
+ "<div id='scrollable'>"
+ " <div id='forceScroll'></div>"
+ "</div>");
+
+ UpdateAllLifecyclePhases();
+
+ Document* document = WebView()->MainFrameImpl()->GetFrame()->GetDocument();
+ Element* scrollable = document->getElementById("scrollable");
+
+ auto* scrollable_area =
+ ToLayoutBox(scrollable->GetLayoutObject())->GetScrollableArea();
+ EXPECT_NE(nullptr, scrollable_area);
+
+ auto initial_content_layer_count = ContentLayerCount();
+ auto initial_scroll_hit_test_layer_count = ScrollHitTestLayerCount();
+
+ cc::Layer* overflow_scroll_layer = nullptr;
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ overflow_scroll_layer = ScrollHitTestLayerAt(ScrollHitTestLayerCount() - 1);
+ } else {
+ overflow_scroll_layer = ContentLayerAt(ContentLayerCount() - 2);
+ }
+ EXPECT_TRUE(overflow_scroll_layer->scrollable());
+ EXPECT_EQ(overflow_scroll_layer->scroll_container_bounds(),
+ gfx::Size(100, 100));
+
+ // Ensure a synthetic impl-side scroll offset propagates to the scrollable
+ // area using the DidScroll callback.
+ EXPECT_EQ(ScrollOffset(), scrollable_area->GetScrollOffset());
+ overflow_scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 1));
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(ScrollOffset(0, 1), scrollable_area->GetScrollOffset());
+
+ // Make the scrollable area non-scrollable.
+ scrollable->setAttribute(html_names::kStyleAttr, "overflow: visible");
+
+ // Update layout without updating compositing state.
+ LocalMainFrame()->ExecuteScript(
+ WebScriptSource("var forceLayoutFromScript = scrollable.offsetTop;"));
+ EXPECT_EQ(document->Lifecycle().GetState(), DocumentLifecycle::kLayoutClean);
+
+ EXPECT_EQ(nullptr,
+ ToLayoutBox(scrollable->GetLayoutObject())->GetScrollableArea());
+
+ // The web scroll layer has not been deleted yet and we should be able to
+ // apply impl-side offsets without crashing.
+ EXPECT_EQ(ContentLayerCount(), initial_content_layer_count);
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ EXPECT_EQ(ScrollHitTestLayerCount(), initial_scroll_hit_test_layer_count);
+ overflow_scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 3));
+
+ UpdateAllLifecyclePhases();
+ EXPECT_LT(ContentLayerCount(), initial_content_layer_count);
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ EXPECT_LT(ScrollHitTestLayerCount(), initial_scroll_hit_test_layer_count);
+}
+
+TEST_P(WebLayerListTest, FrameViewScroll) {
+ InitializeWithHTML(*WebView()->MainFrameImpl()->GetFrame(),
+ "<style>"
+ " #forceScroll {"
+ " height: 2000px;"
+ " width: 100px;"
+ " }"
+ "</style>"
+ "<div id='forceScroll'></div>");
+
+ UpdateAllLifecyclePhases();
+
+ auto* scrollable_area = GetLocalFrameView()->LayoutViewport();
+ EXPECT_NE(nullptr, scrollable_area);
+
+ cc::Layer* scroll_layer = nullptr;
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ EXPECT_EQ(ScrollHitTestLayerCount(), 1u);
+ scroll_layer = ScrollHitTestLayerAt(0);
+ } else {
+ // Find the last scroll layer.
+ for (size_t index = ContentLayerCount() - 1; index >= 0; index--) {
+ if (ContentLayerAt(index)->scrollable()) {
+ scroll_layer = ContentLayerAt(index);
+ break;
+ }
+ }
+ }
+ EXPECT_TRUE(scroll_layer->scrollable());
+
+ // Ensure a synthetic impl-side scroll offset propagates to the scrollable
+ // area using the DidScroll callback.
+ EXPECT_EQ(ScrollOffset(), scrollable_area->GetScrollOffset());
+ scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(0, 1));
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(ScrollOffset(0, 1), scrollable_area->GetScrollOffset());
+}
+
+class WebLayerListSimTest : public PaintTestConfigurations, public SimTest {
+ public:
+ void InitializeWithHTML(const String& html) {
+ WebView().Resize(WebSize(800, 600));
+
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(html);
+
+ // Enable the paint artifact compositor extra testing data.
+ UpdateAllLifecyclePhases();
+ DCHECK(paint_artifact_compositor());
+ paint_artifact_compositor()->EnableExtraDataForTesting();
+ UpdateAllLifecyclePhases();
+
+ DCHECK(paint_artifact_compositor()->GetExtraDataForTesting());
+ }
+
+ size_t ContentLayerCount() {
+ return paint_artifact_compositor()
+ ->GetExtraDataForTesting()
+ ->content_layers.size();
+ }
+
+ cc::Layer* ContentLayerAt(size_t index) {
+ return paint_artifact_compositor()
+ ->GetExtraDataForTesting()
+ ->content_layers[index]
+ .get();
+ }
+
+ Element* GetElementById(const AtomicString& id) {
+ return MainFrame().GetFrame()->GetDocument()->getElementById(id);
+ }
+
+ void UpdateAllLifecyclePhases() {
+ WebView().MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
+ private:
+ PaintArtifactCompositor* paint_artifact_compositor() {
+ return MainFrame().GetFrameView()->GetPaintArtifactCompositorForTesting();
+ }
+};
+
+INSTANTIATE_LAYER_LIST_TEST_CASE_P(WebLayerListSimTest);
+
+TEST_P(WebLayerListSimTest, LayerUpdatesDoNotInvalidateEarlierLayers) {
+ // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // SPV2 gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ div {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ }
+ </style>
+ <div id='a'></div>
+ <div id='b'></div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* a_element = GetElementById("a");
+ auto* a_layer = ContentLayerAt(ContentLayerCount() - 2);
+ DCHECK_EQ(a_layer->element_id(), CompositorElementIdFromUniqueObjectId(
+ a_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+ auto* b_element = GetElementById("b");
+ auto* b_layer = ContentLayerAt(ContentLayerCount() - 1);
+ DCHECK_EQ(b_layer->element_id(), CompositorElementIdFromUniqueObjectId(
+ b_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+
+ // Initially, neither a nor b should have a layer that should push properties.
+ auto* host = Compositor().layer_tree_view().layer_tree_host();
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
+
+ // Modifying b should only cause the b layer to need to push properties.
+ b_element->setAttribute(html_names::kStyleAttr, "opacity: 0.2");
+ UpdateAllLifecyclePhases();
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
+ EXPECT_TRUE(host->LayersThatShouldPushProperties().count(b_layer));
+
+ // After a frame, no layers should need to push properties again.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
+}
+
+TEST_P(WebLayerListSimTest, LayerUpdatesDoNotInvalidateLaterLayers) {
+ // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // SPV2 gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ div {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ }
+ </style>
+ <div id='a'></div>
+ <div id='b' style='opacity: 0.2;'></div>
+ <div id='c'></div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* a_element = GetElementById("a");
+ auto* a_layer = ContentLayerAt(ContentLayerCount() - 3);
+ DCHECK_EQ(a_layer->element_id(), CompositorElementIdFromUniqueObjectId(
+ a_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+ auto* b_element = GetElementById("b");
+ auto* b_layer = ContentLayerAt(ContentLayerCount() - 2);
+ DCHECK_EQ(b_layer->element_id(), CompositorElementIdFromUniqueObjectId(
+ b_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+ auto* c_element = GetElementById("c");
+ auto* c_layer = ContentLayerAt(ContentLayerCount() - 1);
+ DCHECK_EQ(c_layer->element_id(), CompositorElementIdFromUniqueObjectId(
+ c_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+
+ // Initially, no layer should need to push properties.
+ auto* host = Compositor().layer_tree_view().layer_tree_host();
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(c_layer));
+
+ // Modifying a and b (adding opacity to a and removing opacity from b) should
+ // not cause the c layer to push properties.
+ a_element->setAttribute(html_names::kStyleAttr, "opacity: 0.3");
+ b_element->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(host->LayersThatShouldPushProperties().count(a_layer));
+ EXPECT_TRUE(host->LayersThatShouldPushProperties().count(b_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(c_layer));
+
+ // After a frame, no layers should need to push properties again.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(a_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(b_layer));
+ EXPECT_FALSE(host->LayersThatShouldPushProperties().count(c_layer));
+}
+
+TEST_P(WebLayerListSimTest, NoopChangeDoesNotCauseFullTreeSync) {
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ div {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ }
+ </style>
+ <div></div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ // Initially the host should not need to sync.
+ auto* layer_tree_host = Compositor().layer_tree_view().layer_tree_host();
+ EXPECT_FALSE(layer_tree_host->needs_full_tree_sync());
+
+ // A no-op update should not cause the host to need a full tree sync.
+ UpdateAllLifecyclePhases();
+ EXPECT_FALSE(layer_tree_host->needs_full_tree_sync());
+}
+
+// When a property tree change occurs that affects layer position, all layers
+// associated with the changed property tree node, and all layers associated
+// with a descendant of the changed property tree node need to have
+// |subtree_property_changed| set for damage tracking. In non-layer-list mode,
+// this occurs in BuildPropertyTreesInternal (see:
+// SetLayerPropertyChangedForChild).
+TEST_P(WebLayerListSimTest, LayerSubtreeTransformPropertyChanged) {
+ // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // SPV2 gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ #outer {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ transform: translate(10px, 10px);
+ }
+ #inner {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ background: lightblue;
+ }
+ </style>
+ <div id='outer'>
+ <div id='inner'></div>
+ </div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* outer_element = GetElementById("outer");
+ auto* outer_element_layer = ContentLayerAt(ContentLayerCount() - 2);
+ DCHECK_EQ(outer_element_layer->element_id(),
+ CompositorElementIdFromUniqueObjectId(
+ outer_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+ auto* inner_element = GetElementById("inner");
+ auto* inner_element_layer = ContentLayerAt(ContentLayerCount() - 1);
+ DCHECK_EQ(inner_element_layer->element_id(),
+ CompositorElementIdFromUniqueObjectId(
+ inner_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+
+ // Initially, no layer should have |subtree_property_changed| set.
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+
+ // Modifying the transform style should set |subtree_property_changed| on
+ // both layers.
+ outer_element->setAttribute(html_names::kStyleAttr,
+ "transform: translate(20px, 20px)");
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(outer_element_layer->subtree_property_changed());
+ EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+
+ // After a frame the |subtree_property_changed| value should be reset.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+}
+
+// This test is similar to |LayerSubtreeTransformPropertyChanged| but for
+// effect property node changes.
+TEST_P(WebLayerListSimTest, LayerSubtreeEffectPropertyChanged) {
+ // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // SPV2 gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ #outer {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ filter: blur(10px);
+ }
+ #inner {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ background: lightblue;
+ }
+ </style>
+ <div id='outer'>
+ <div id='inner'></div>
+ </div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* outer_element = GetElementById("outer");
+ auto* outer_element_layer = ContentLayerAt(ContentLayerCount() - 2);
+ DCHECK_EQ(outer_element_layer->element_id(),
+ CompositorElementIdFromUniqueObjectId(
+ outer_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+ auto* inner_element = GetElementById("inner");
+ auto* inner_element_layer = ContentLayerAt(ContentLayerCount() - 1);
+ DCHECK_EQ(inner_element_layer->element_id(),
+ CompositorElementIdFromUniqueObjectId(
+ inner_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+
+ // Initially, no layer should have |subtree_property_changed| set.
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+
+ // Modifying the filter style should set |subtree_property_changed| on
+ // both layers.
+ outer_element->setAttribute(html_names::kStyleAttr, "filter: blur(20px)");
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(outer_element_layer->subtree_property_changed());
+ EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+
+ // After a frame the |subtree_property_changed| value should be reset.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+}
+
+// This test is similar to |LayerSubtreeTransformPropertyChanged| but for
+// clip property node changes.
+TEST_P(WebLayerListSimTest, LayerSubtreeClipPropertyChanged) {
+ // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // SPV2 gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ #outer {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ position: absolute;
+ clip: rect(10px, 80px, 70px, 40px);
+ }
+ #inner {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ background: lightblue;
+ }
+ </style>
+ <div id='outer'>
+ <div id='inner'></div>
+ </div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* outer_element = GetElementById("outer");
+ auto* outer_element_layer = ContentLayerAt(ContentLayerCount() - 2);
+ auto* inner_element = GetElementById("inner");
+ auto* inner_element_layer = ContentLayerAt(ContentLayerCount() - 1);
+ DCHECK_EQ(inner_element_layer->element_id(),
+ CompositorElementIdFromUniqueObjectId(
+ inner_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+
+ // Initially, no layer should have |subtree_property_changed| set.
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+
+ // Modifying the clip style should set |subtree_property_changed| on
+ // both layers.
+ outer_element->setAttribute(html_names::kStyleAttr,
+ "clip: rect(1px, 8px, 7px, 4px);");
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(outer_element_layer->subtree_property_changed());
+ EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+
+ // After a frame the |subtree_property_changed| value should be reset.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+}
+
+TEST_P(WebLayerListSimTest, LayerSubtreeOverflowClipPropertyChanged) {
+ // TODO(crbug.com/765003): SPV2 may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // SPV2 gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ #outer {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ position: absolute;
+ overflow: hidden;
+ }
+ #inner {
+ width: 200px;
+ height: 100px;
+ will-change: transform;
+ background: lightblue;
+ }
+ </style>
+ <div id='outer'>
+ <div id='inner'></div>
+ </div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* outer_element = GetElementById("outer");
+ auto* outer_element_layer = ContentLayerAt(ContentLayerCount() - 2);
+ auto* inner_element = GetElementById("inner");
+ auto* inner_element_layer = ContentLayerAt(ContentLayerCount() - 1);
+ DCHECK_EQ(inner_element_layer->element_id(),
+ CompositorElementIdFromUniqueObjectId(
+ inner_element->GetLayoutObject()->UniqueId(),
+ CompositorElementIdNamespace::kPrimary));
+
+ // Initially, no layer should have |subtree_property_changed| set.
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+
+ // Modifying the clip width should set |subtree_property_changed| on
+ // both layers.
+ outer_element->setAttribute(html_names::kStyleAttr, "width: 200px;");
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(outer_element_layer->subtree_property_changed());
+ EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+
+ // After a frame the |subtree_property_changed| value should be reset.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_meaningful_layouts_test.cc b/chromium/third_party/blink/renderer/core/exported/web_meaningful_layouts_test.cc
index 41851306e2c..cca943ffa8f 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_meaningful_layouts_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_meaningful_layouts_test.cc
@@ -210,10 +210,11 @@ TEST_F(WebMeaningfulLayoutsTest, LayoutWithPendingRenderBlockingStylesheet) {
"<link rel=\"stylesheet\" href=\"style.css\">"
"</head><body></body></html>");
- GetDocument().UpdateStyleAndLayoutTreeIgnorePendingStylesheets();
- EXPECT_TRUE(GetDocument().DidLayoutWithPendingStylesheets());
+ GetDocument().UpdateStyleAndLayoutTree();
+ EXPECT_FALSE(GetDocument().IsRenderingReady());
style_resource.Complete("");
+ EXPECT_TRUE(GetDocument().IsRenderingReady());
}
// A pending stylesheet in the body is not render-blocking and should not
@@ -248,10 +249,13 @@ TEST_F(WebMeaningfulLayoutsTest, LayoutWithPendingImportInHead) {
"<link rel=\"import\" href=\"import.html\">"
"</head><body></body></html>");
- GetDocument().UpdateStyleAndLayoutTreeIgnorePendingStylesheets();
- EXPECT_TRUE(GetDocument().DidLayoutWithPendingStylesheets());
+ GetDocument().UpdateStyleAndLayoutTree();
+ EXPECT_FALSE(GetDocument().IsRenderingReady());
import_resource.Complete("");
+ // Pump the HTMLImportTreeRoot::RecalcTimerFired task.
+ test::RunPendingTasks();
+ EXPECT_TRUE(GetDocument().IsRenderingReady());
}
// A pending import in the body is render-blocking and will be treated like
@@ -267,10 +271,13 @@ TEST_F(WebMeaningfulLayoutsTest, LayoutWithPendingImportInBody) {
"<link rel=\"import\" href=\"import.html\">"
"</body></html>");
- GetDocument().UpdateStyleAndLayoutTreeIgnorePendingStylesheets();
- EXPECT_TRUE(GetDocument().DidLayoutWithPendingStylesheets());
+ GetDocument().UpdateStyleAndLayoutTree();
+ EXPECT_FALSE(GetDocument().IsRenderingReady());
import_resource.Complete("");
+ // Pump the HTMLImportTreeRoot::RecalcTimerFired task.
+ test::RunPendingTasks();
+ EXPECT_TRUE(GetDocument().IsRenderingReady());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_node.cc b/chromium/third_party/blink/renderer/core/exported/web_node.cc
index 06ba400d053..f56c99b9c34 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_node.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_node.cc
@@ -133,6 +133,8 @@ bool WebNode::IsCommentNode() const {
bool WebNode::IsFocusable() const {
if (!private_->IsElementNode())
return false;
+ if (!private_->GetDocument().IsRenderingReady())
+ return false;
private_->GetDocument().UpdateStyleAndLayoutTreeForNode(private_.Get());
return ToElement(private_.Get())->IsFocusable();
}
@@ -174,7 +176,7 @@ WebElementCollection WebNode::GetElementsByHTMLTagName(
if (private_->IsContainerNode()) {
return WebElementCollection(
ToContainerNode(private_.Get())
- ->getElementsByTagNameNS(HTMLNames::xhtmlNamespaceURI, tag));
+ ->getElementsByTagNameNS(html_names::xhtmlNamespaceURI, tag));
}
return WebElementCollection();
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_node_test.cc b/chromium/third_party/blink/renderer/core/exported/web_node_test.cc
index bb1d34dcc33..d16be0dbb31 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_node_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_node_test.cc
@@ -67,7 +67,8 @@ TEST_F(WebNodeSimTest, IsFocused) {
LoadURL("https://example.com/test.html");
WebView().Resize(WebSize(800, 600));
- main_resource.Complete(R"HTML(
+ main_resource.Start();
+ main_resource.Write(R"HTML(
<!DOCTYPE html>
<link rel=stylesheet href=style.css>
<input id=focusable>
@@ -79,7 +80,9 @@ TEST_F(WebNodeSimTest, IsFocused) {
WebNode input_node(GetDocument().getElementById("focusable"));
EXPECT_FALSE(input_node.IsFocusable());
+ EXPECT_FALSE(GetDocument().HasNodesWithPlaceholderStyle());
+ main_resource.Finish();
css_resource.Complete("dummy {}");
EXPECT_TRUE(input_node.IsFocusable());
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.cc
index 8bd506f1bff..37e97dc863a 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.cc
@@ -65,14 +65,18 @@
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
class PagePopupChromeClient final : public EmptyChromeClient {
public:
static PagePopupChromeClient* Create(WebPagePopupImpl* popup) {
- return new PagePopupChromeClient(popup);
+ return MakeGarbageCollected<PagePopupChromeClient>(popup);
+ }
+
+ explicit PagePopupChromeClient(WebPagePopupImpl* popup) : popup_(popup) {
+ DCHECK(popup_->WidgetClient());
}
void SetWindowRect(const IntRect& rect, LocalFrame&) override {
@@ -82,10 +86,6 @@ class PagePopupChromeClient final : public EmptyChromeClient {
bool IsPopup() override { return true; }
private:
- explicit PagePopupChromeClient(WebPagePopupImpl* popup) : popup_(popup) {
- DCHECK(popup_->WidgetClient());
- }
-
void CloseWindowSoon() override { popup_->ClosePopup(); }
IntRect RootWindowRect() override { return popup_->WindowRectInScreen(); }
@@ -127,7 +127,7 @@ class PagePopupChromeClient final : public EmptyChromeClient {
void ScheduleAnimation(const LocalFrameView*) override {
// Calling scheduleAnimation on m_webView so WebViewTestProxy will call
// beginFrame.
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
popup_->web_view_->MainFrameImpl()
->FrameWidgetImpl()
->ScheduleAnimation();
@@ -153,9 +153,7 @@ class PagePopupChromeClient final : public EmptyChromeClient {
}
WebScreenInfo GetScreenInfo() const override {
- return popup_->web_view_->Client()
- ? popup_->web_view_->WidgetClient()->GetScreenInfo()
- : WebScreenInfo();
+ return popup_->web_view_->Client()->GetScreenInfo();
}
WebViewImpl* GetWebView() const override { return popup_->web_view_; }
@@ -280,6 +278,7 @@ void WebPagePopupImpl::Initialize(WebViewImpl* web_view,
Settings& main_settings = web_view_->GetPage()->GetSettings();
page_ = Page::Create(page_clients);
+ page_->GetSettings().SetAcceleratedCompositingEnabled(true);
page_->GetSettings().SetScriptEnabled(true);
page_->GetSettings().SetAllowScriptsToCloseWindows(true);
page_->GetSettings().SetDeviceSupportsTouch(
@@ -313,7 +312,6 @@ void WebPagePopupImpl::Initialize(WebViewImpl* web_view,
DCHECK_EQ(popup_client_->OwnerElement().GetDocument().ExistingAXObjectCache(),
frame->GetDocument()->ExistingAXObjectCache());
- layer_tree_view_->SetVisible(true);
page_->LayerTreeViewInitialized(*layer_tree_view_, nullptr);
scoped_refptr<SharedBuffer> data = SharedBuffer::Create();
@@ -403,10 +401,14 @@ void WebPagePopupImpl::WillCloseLayerTreeView() {
animation_host_ = nullptr;
}
-void WebPagePopupImpl::UpdateLifecycle(LifecycleUpdate requested_update) {
+void WebPagePopupImpl::UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) {
if (!page_)
return;
- PageWidgetDelegate::UpdateLifecycle(*page_, MainFrame(), requested_update);
+ // Popups always update their lifecycle in the context of the containing
+ // document's lifecycle, so explicitly override the reason.
+ PageWidgetDelegate::UpdateLifecycle(*page_, MainFrame(), requested_update,
+ WebWidget::LifecycleUpdateReason::kOther);
}
void WebPagePopupImpl::UpdateAllLifecyclePhasesAndCompositeForTesting(
diff --git a/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.h b/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.h
index d954c865404..6193629a2d8 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.h
@@ -85,7 +85,8 @@ class CORE_EXPORT WebPagePopupImpl final : public WebPagePopup,
void SetLayerTreeView(WebLayerTreeView*) override;
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) final;
void BeginFrame(base::TimeTicks last_frame_time) override;
- void UpdateLifecycle(LifecycleUpdate requested_update) override;
+ void UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason /* Not used */) override;
void UpdateAllLifecyclePhasesAndCompositeForTesting(bool do_raster) override;
void WillCloseLayerTreeView() override;
void PaintContent(cc::PaintCanvas*, const WebRect&) override;
@@ -98,6 +99,7 @@ class CORE_EXPORT WebPagePopupImpl final : public WebPagePopup,
return is_accelerated_compositing_active_;
}
WebURL GetURLForDebugTrace() override;
+ WebHitTestResult HitTestResultAt(const gfx::Point&) override { return {}; }
// PageWidgetEventHandler functions
WebInputEventResult HandleCharEvent(const WebKeyboardEvent&) override;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_performance.cc b/chromium/third_party/blink/renderer/core/exported/web_performance.cc
index 4b59070c543..e35518a8ad2 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_performance.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_performance.cc
@@ -175,6 +175,22 @@ double WebPerformance::FirstMeaningfulPaintCandidate() const {
private_->timing()->FirstMeaningfulPaintCandidate());
}
+double WebPerformance::LargestImagePaint() const {
+ return MillisecondsToSeconds(private_->timing()->LargestImagePaint());
+}
+
+double WebPerformance::LastImagePaint() const {
+ return MillisecondsToSeconds(private_->timing()->LastImagePaint());
+}
+
+double WebPerformance::LargestTextPaint() const {
+ return MillisecondsToSeconds(private_->timing()->LargestTextPaint());
+}
+
+double WebPerformance::LastTextPaint() const {
+ return MillisecondsToSeconds(private_->timing()->LastTextPaint());
+}
+
double WebPerformance::PageInteractive() const {
return MillisecondsToSeconds(private_->timing()->PageInteractive());
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc
index db6cf1d4a76..f0a6c825840 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc
@@ -51,6 +51,7 @@
#include "third_party/blink/public/web/web_print_params.h"
#include "third_party/blink/public/web/web_print_preset_options.h"
#include "third_party/blink/public/web/web_view_client.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
@@ -102,7 +103,6 @@
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -136,7 +136,8 @@ void WebPluginContainerImpl::UpdateAllLifecyclePhases() {
if (!web_plugin_)
return;
- web_plugin_->UpdateAllLifecyclePhases();
+ web_plugin_->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kOther);
}
void WebPluginContainerImpl::SetFrameRect(const IntRect& frame_rect) {
@@ -168,17 +169,17 @@ void WebPluginContainerImpl::Paint(GraphicsContext& context,
const CullRect& cull_rect,
const IntSize& paint_offset) const {
// Don't paint anything if the plugin doesn't intersect.
- if (!cull_rect.IntersectsCullRect(FrameRect()))
+ if (!cull_rect.Intersects(FrameRect()))
return;
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() && layer_) {
- layer_->SetBounds(static_cast<gfx::Size>(frame_rect_.Size()));
+ layer_->SetOffsetToTransformParent(
+ gfx::Vector2dF(frame_rect_.X(), frame_rect_.Y()));
+ layer_->SetBounds(gfx::Size(frame_rect_.Size()));
layer_->SetIsDrawable(true);
// With Slimming Paint v2, composited plugins should have their layers
// inserted rather than invoking WebPlugin::paint.
- RecordForeignLayer(context, *element_->GetLayoutObject(),
- DisplayItem::kForeignLayerPlugin, layer_,
- FloatPoint(FrameRect().Location()), frame_rect_.Size());
+ RecordForeignLayer(context, DisplayItem::kForeignLayerPlugin, layer_);
return;
}
@@ -564,7 +565,7 @@ WebString WebPluginContainerImpl::ExecuteScriptURL(const WebURL& url,
v8::Local<v8::Value> result =
frame->GetScriptController().ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode(script, ScriptSourceLocationType::kJavascriptUrl),
- KURL(), kOpaqueResource);
+ KURL(), SanitizeScriptErrors::kSanitize);
// Failure is reported as a null string.
if (result.IsEmpty() || !result->IsString())
@@ -823,7 +824,7 @@ void WebPluginContainerImpl::HandleMouseEvent(MouseEvent& event) {
if (transformed_event.GetType() == WebInputEvent::kUndefined)
return;
- if (event.type() == EventTypeNames::mousedown)
+ if (event.type() == event_type_names::kMousedown)
FocusPlugin();
WebCursorInfo cursor_info;
@@ -846,13 +847,13 @@ void WebPluginContainerImpl::HandleDragEvent(MouseEvent& event) {
DCHECK(event.IsDragEvent());
WebDragStatus drag_status = kWebDragStatusUnknown;
- if (event.type() == EventTypeNames::dragenter)
+ if (event.type() == event_type_names::kDragenter)
drag_status = kWebDragStatusEnter;
- else if (event.type() == EventTypeNames::dragleave)
+ else if (event.type() == event_type_names::kDragleave)
drag_status = kWebDragStatusLeave;
- else if (event.type() == EventTypeNames::dragover)
+ else if (event.type() == event_type_names::kDragover)
drag_status = kWebDragStatusOver;
- else if (event.type() == EventTypeNames::drop)
+ else if (event.type() == event_type_names::kDrop)
drag_status = kWebDragStatusDrop;
if (drag_status == kWebDragStatusUnknown)
@@ -984,11 +985,15 @@ WebCoalescedInputEvent WebPluginContainerImpl::TransformCoalescedTouchEvent(
const WebCoalescedInputEvent& coalesced_event) {
WebCoalescedInputEvent transformed_event(
TransformTouchEvent(coalesced_event.Event()),
- std::vector<const WebInputEvent*>());
+ std::vector<const WebInputEvent*>(), std::vector<const WebInputEvent*>());
for (size_t i = 0; i < coalesced_event.CoalescedEventSize(); ++i) {
transformed_event.AddCoalescedEvent(
TransformTouchEvent(coalesced_event.CoalescedEvent(i)));
}
+ for (size_t i = 0; i < coalesced_event.PredictedEventSize(); ++i) {
+ transformed_event.AddPredictedEvent(
+ TransformTouchEvent(coalesced_event.PredictedEvent(i)));
+ }
return transformed_event;
}
@@ -1001,7 +1006,7 @@ void WebPluginContainerImpl::HandleTouchEvent(TouchEvent& event) {
if (!event.NativeEvent())
return;
- if (event.type() == EventTypeNames::touchstart)
+ if (event.type() == event_type_names::kTouchstart)
FocusPlugin();
WebCoalescedInputEvent transformed_event =
@@ -1089,10 +1094,10 @@ void WebPluginContainerImpl::ComputeClipRectsForPlugin(
// the containing view space, and rounded off. See
// LayoutEmbeddedContent::UpdateGeometry. To remove the lossy effect of
// rounding off, use contentBoxRect directly.
- LayoutRect unclipped_absolute_rect(box->PhysicalContentBoxRect());
- box->MapToVisualRectInAncestorSpace(root_view, unclipped_absolute_rect);
- unclipped_absolute_rect =
- box->View()->GetFrameView()->DocumentToFrame(unclipped_absolute_rect);
+ LayoutRect unclipped_root_frame_rect(box->PhysicalContentBoxRect());
+ box->MapToVisualRectInAncestorSpace(root_view, unclipped_root_frame_rect);
+ unclipped_root_frame_rect =
+ root_view->GetFrameView()->DocumentToFrame(unclipped_root_frame_rect);
// The frameRect is already in absolute space of the local frame to the
// plugin so map it up to the root frame.
@@ -1107,20 +1112,19 @@ void WebPluginContainerImpl::ComputeClipRectsForPlugin(
window_rect = PixelSnappedIntRect(layout_window_rect);
- LayoutRect layout_clipped_local_rect = unclipped_absolute_rect;
- LayoutRect unclipped_layout_local_rect = layout_clipped_local_rect;
- layout_clipped_local_rect.Intersect(
+ LayoutRect clipped_root_frame_rect = unclipped_root_frame_rect;
+ clipped_root_frame_rect.Intersect(
LayoutRect(LayoutPoint(), LayoutSize(root_view->GetFrameView()->Size())));
unclipped_int_local_rect =
- box->AbsoluteToLocalQuad(FloatRect(unclipped_layout_local_rect),
+ box->AbsoluteToLocalQuad(FloatRect(unclipped_root_frame_rect),
kTraverseDocumentBoundaries | kUseTransforms)
.EnclosingBoundingBox();
// As a performance optimization, map the clipped rect separately if is
// different than the unclipped rect.
- if (layout_clipped_local_rect != unclipped_layout_local_rect) {
+ if (clipped_root_frame_rect != unclipped_root_frame_rect) {
clipped_local_rect =
- box->AbsoluteToLocalQuad(FloatRect(layout_clipped_local_rect),
+ box->AbsoluteToLocalQuad(FloatRect(clipped_root_frame_rect),
kTraverseDocumentBoundaries | kUseTransforms)
.EnclosingBoundingBox();
} else {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.h b/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.h
index 1b6b5a18463..51dbf8e51fb 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.h
@@ -78,11 +78,12 @@ class CORE_EXPORT WebPluginContainerImpl final
public:
static WebPluginContainerImpl* Create(HTMLPlugInElement& element,
WebPlugin* web_plugin) {
- return new WebPluginContainerImpl(element, web_plugin);
+ return MakeGarbageCollected<WebPluginContainerImpl>(element, web_plugin);
}
// Check if plugins support a given command |name|.
static bool SupportsCommand(const WebString& name);
+ WebPluginContainerImpl(HTMLPlugInElement&, WebPlugin*);
~WebPluginContainerImpl() override;
// EmbeddedContentView methods
@@ -215,8 +216,6 @@ class CORE_EXPORT WebPluginContainerImpl final
IntRect& clipped_local_rect,
IntRect& unclipped_int_local_rect) const;
- WebPluginContainerImpl(HTMLPlugInElement&, WebPlugin*);
-
WebTouchEvent TransformTouchEvent(const WebInputEvent&);
WebCoalescedInputEvent TransformCoalescedTouchEvent(
const WebCoalescedInputEvent&);
diff --git a/chromium/third_party/blink/renderer/core/exported/web_plugin_container_test.cc b/chromium/third_party/blink/renderer/core/exported/web_plugin_container_test.cc
index db48d723fdf..8e07ace292c 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_plugin_container_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_plugin_container_test.cc
@@ -36,6 +36,7 @@
#include "build/build_config.h"
#include "cc/layers/layer.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_coalesced_input_event.h"
#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
@@ -51,7 +52,6 @@
#include "third_party/blink/renderer/core/clipboard/system_clipboard.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
-#include "third_party/blink/renderer/core/exported/fake_web_plugin.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
#include "third_party/blink/renderer/core/frame/event_handler_registry.h"
@@ -60,6 +60,7 @@
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/page/page.h"
+#include "third_party/blink/renderer/core/testing/fake_web_plugin.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h"
@@ -97,11 +98,16 @@ class WebPluginContainerTest : public testing::Test {
void RegisterMockedURL(
const std::string& file_name,
const std::string& mime_type = std::string("text/html")) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name), WebString::FromUTF8(mime_type));
}
+ void UpdateAllLifecyclePhases(WebViewImpl* web_view) {
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
protected:
ScopedFakePluginRegistry fake_plugins_;
std::string base_url_;
@@ -116,7 +122,8 @@ const WebInputEvent::Modifiers kEditingModifier = WebInputEvent::kControlKey;
#endif
template <typename T>
-class CustomPluginWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class CustomPluginWebFrameClient
+ : public frame_test_helpers::TestWebFrameClient {
public:
WebPlugin* CreatePlugin(const WebPluginParams& params) override {
return new T(params);
@@ -191,14 +198,15 @@ class TestPluginWithEditableText : public FakeWebPlugin {
bool paste_called_;
};
-class TestPluginWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
+class TestPluginWebFrameClient : public frame_test_helpers::TestWebFrameClient {
WebLocalFrame* CreateChildFrame(WebLocalFrame* parent,
WebTreeScopeType scope,
const WebString& name,
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties&) override {
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType owner_type) override {
return CreateLocalChild(*parent, scope,
std::make_unique<TestPluginWebFrameClient>());
}
@@ -234,8 +242,9 @@ void TestPlugin::PrintPage(int page_number, cc::PaintCanvas* canvas) {
void EnablePlugins(WebView* web_view, const WebSize& size) {
DCHECK(web_view);
web_view->GetSettings()->SetPluginsEnabled(true);
- web_view->Resize(size);
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(size);
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
}
@@ -272,9 +281,9 @@ void CreateAndHandleKeyboardEvent(WebElement* plugin_container_one_element,
void ExecuteContextMenuCommand(WebViewImpl* web_view,
const WebString& command_name) {
- auto event = FrameTestHelpers::CreateMouseEvent(WebMouseEvent::kMouseDown,
- WebMouseEvent::Button::kRight,
- WebPoint(30, 30), 0);
+ auto event = frame_test_helpers::CreateMouseEvent(
+ WebMouseEvent::kMouseDown, WebMouseEvent::Button::kRight,
+ WebPoint(30, 30), 0);
event.click_count = 1;
web_view->HandleInputEvent(WebCoalescedInputEvent(event));
@@ -288,7 +297,7 @@ TEST_F(WebPluginContainerTest, WindowToLocalPointTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -323,11 +332,11 @@ TEST_F(WebPluginContainerTest, PluginDocumentPluginIsFocused) {
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "test.pdf", &plugin_web_frame_client);
DCHECK(web_view);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
WebDocument document = web_view->MainFrameImpl()->GetDocument();
EXPECT_TRUE(document.IsPluginDocument());
@@ -342,11 +351,11 @@ TEST_F(WebPluginContainerTest, IFramePluginDocumentNotFocused) {
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "iframe_pdf.html", &plugin_web_frame_client);
DCHECK(web_view);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
WebDocument document = web_view->MainFrameImpl()->GetDocument();
WebLocalFrame* iframe =
@@ -364,11 +373,11 @@ TEST_F(WebPluginContainerTest, PrintOnePage) {
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "test.pdf", &plugin_web_frame_client);
DCHECK(web_view);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebLocalFrame* frame = web_view->MainFrameImpl();
@@ -388,11 +397,11 @@ TEST_F(WebPluginContainerTest, PrintAllPages) {
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "test.pdf", &plugin_web_frame_client);
DCHECK(web_view);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebLocalFrame* frame = web_view->MainFrameImpl();
@@ -411,7 +420,7 @@ TEST_F(WebPluginContainerTest, LocalToWindowPointTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -445,7 +454,7 @@ TEST_F(WebPluginContainerTest, Copy) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -465,7 +474,7 @@ TEST_F(WebPluginContainerTest, CopyFromContextMenu) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -475,9 +484,9 @@ TEST_F(WebPluginContainerTest, CopyFromContextMenu) {
EXPECT_EQ(String("x"), ReadClipboard());
ClearClipboardBuffer();
- auto event = FrameTestHelpers::CreateMouseEvent(WebMouseEvent::kMouseDown,
- WebMouseEvent::Button::kRight,
- WebPoint(30, 30), 0);
+ auto event = frame_test_helpers::CreateMouseEvent(
+ WebMouseEvent::kMouseDown, WebMouseEvent::Button::kRight,
+ WebPoint(30, 30), 0);
event.click_count = 1;
// Now, let's try a more complex scenario:
@@ -498,7 +507,7 @@ TEST_F(WebPluginContainerTest, CopyInsertKeyboardEventsTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -525,7 +534,7 @@ TEST_F(WebPluginContainerTest, CutDeleteKeyboardEventsTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
// Use TestPluginWithEditableText for testing "Cut".
plugin_web_frame_client.SetHasEditableText(true);
@@ -568,7 +577,7 @@ TEST_F(WebPluginContainerTest, PasteInsertKeyboardEventsTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
// Use TestPluginWithEditableText for testing "Paste".
plugin_web_frame_client.SetHasEditableText(true);
@@ -611,7 +620,7 @@ TEST_F(WebPluginContainerTest, PasteAndMatchStyleKeyboardEventsTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
// Use TestPluginWithEditableText for testing "PasteAndMatchStyle".
plugin_web_frame_client.SetHasEditableText(true);
@@ -640,7 +649,7 @@ TEST_F(WebPluginContainerTest, CutFromContextMenu) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
// Use TestPluginWithEditableText for testing "Cut".
plugin_web_frame_client.SetHasEditableText(true);
@@ -663,7 +672,7 @@ TEST_F(WebPluginContainerTest, PasteFromContextMenu) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
// Use TestPluginWithEditableText for testing "Paste".
plugin_web_frame_client.SetHasEditableText(true);
@@ -686,7 +695,7 @@ TEST_F(WebPluginContainerTest, PasteAndMatchStyleFromContextMenu) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
// Use TestPluginWithEditableText for testing "Paste".
plugin_web_frame_client.SetHasEditableText(true);
@@ -763,7 +772,7 @@ TEST_F(WebPluginContainerTest, GestureLongPressReachesPlugin) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -807,7 +816,7 @@ TEST_F(WebPluginContainerTest, MouseEventButtons) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -820,7 +829,7 @@ TEST_F(WebPluginContainerTest, MouseEventButtons) {
->Plugin();
EventTestPlugin* test_plugin = static_cast<EventTestPlugin*>(plugin);
- WebMouseEvent event = FrameTestHelpers::CreateMouseEvent(
+ WebMouseEvent event = frame_test_helpers::CreateMouseEvent(
WebMouseEvent::kMouseMove, WebMouseEvent::Button::kNoButton,
WebPoint(30, 30),
WebInputEvent::kMiddleButtonDown | WebInputEvent::kShiftKey);
@@ -840,7 +849,7 @@ TEST_F(WebPluginContainerTest, MouseWheelEventTranslated) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -872,12 +881,12 @@ TEST_F(WebPluginContainerTest, TouchEventScrolled) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
web_view->SmoothScroll(0, 200, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -913,12 +922,12 @@ TEST_F(WebPluginContainerTest, TouchEventScrolledWithCoalescedTouches) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
web_view->SmoothScroll(0, 200, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -1007,12 +1016,12 @@ TEST_F(WebPluginContainerTest, MouseWheelEventScrolled) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
web_view->SmoothScroll(0, 200, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -1044,12 +1053,12 @@ TEST_F(WebPluginContainerTest, MouseEventScrolled) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
web_view->SmoothScroll(0, 200, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -1080,15 +1089,15 @@ TEST_F(WebPluginContainerTest, MouseEventZoomed) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
DCHECK(web_view);
web_view->GetSettings()->SetPluginsEnabled(true);
- web_view->Resize(WebSize(300, 300));
+ web_view->MainFrameWidget()->Resize(WebSize(300, 300));
web_view->SetPageScaleFactor(2);
web_view->SmoothScroll(0, 300, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -1121,15 +1130,15 @@ TEST_F(WebPluginContainerTest, MouseWheelEventZoomed) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
DCHECK(web_view);
web_view->GetSettings()->SetPluginsEnabled(true);
- web_view->Resize(WebSize(300, 300));
+ web_view->MainFrameWidget()->Resize(WebSize(300, 300));
web_view->SetPageScaleFactor(2);
web_view->SmoothScroll(0, 300, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -1163,7 +1172,7 @@ TEST_F(WebPluginContainerTest, TouchEventZoomed) {
RegisterMockedURL("plugin_scroll.html");
// Must outlive |web_view_helper|.
CustomPluginWebFrameClient<EventTestPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_scroll.html", &plugin_web_frame_client);
DCHECK(web_view);
@@ -1171,7 +1180,7 @@ TEST_F(WebPluginContainerTest, TouchEventZoomed) {
web_view->Resize(WebSize(300, 300));
web_view->SetPageScaleFactor(2);
web_view->SmoothScroll(0, 300, 0);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
RunPendingTasks();
WebElement plugin_container_one_element =
@@ -1210,7 +1219,7 @@ TEST_F(WebPluginContainerTest, IsRectTopmostTest) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -1234,7 +1243,7 @@ TEST_F(WebPluginContainerTest, IsRectTopmostTestWithOddAndEvenDimensions) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -1260,7 +1269,7 @@ TEST_F(WebPluginContainerTest, ClippedRectsForIframedElement) {
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_containing_page.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -1286,12 +1295,108 @@ TEST_F(WebPluginContainerTest, ClippedRectsForIframedElement) {
web_view_helper.Reset();
}
+TEST_F(WebPluginContainerTest, ClippedRectsForShiftedIframedElement) {
+ RegisterMockedURL("plugin_hidden_before_scroll.html");
+ RegisterMockedURL("shifted_plugin_containing_page.html");
+
+ // Must outlive |web_view_helper|.
+ TestPluginWebFrameClient plugin_web_frame_client;
+ frame_test_helpers::WebViewHelper web_view_helper;
+ WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
+ base_url_ + "shifted_plugin_containing_page.html",
+ &plugin_web_frame_client);
+ EnablePlugins(web_view, WebSize(300, 300));
+ UpdateAllLifecyclePhases(web_view);
+ WebLocalFrame* iframe =
+ web_view->MainFrame()->FirstChild()->ToWebLocalFrame();
+ WebElement plugin_element =
+ iframe->GetDocument().GetElementById("plugin-hidden-before-scroll");
+ WebPluginContainerImpl* plugin_container_impl =
+ ToWebPluginContainerImpl(plugin_element.PluginContainer());
+
+ DCHECK(plugin_container_impl);
+
+ IntSize plugin_size(40, 40);
+ IntSize iframe_size(40, 40);
+
+ IntPoint iframe_offset_in_root_frame(0, 300);
+ IntPoint plugin_offset_in_iframe(0, 40);
+
+ auto compute_expected_values = [=](IntSize root_document_scroll_to,
+ IntSize iframe_scroll_to) {
+ IntPoint offset_in_iframe = plugin_offset_in_iframe - iframe_scroll_to;
+ IntPoint offset_in_root_document =
+ iframe_offset_in_root_frame - root_document_scroll_to;
+ // window_rect is a plugin rectangle in the root frame coordinates.
+ IntRect expected_window_rect =
+ IntRect(offset_in_root_document + offset_in_iframe, plugin_size);
+
+ // unobscured_rect is the visible part of the plugin, inside the iframe.
+ IntRect expected_unobscured_rect(IntPoint(iframe_scroll_to), iframe_size);
+ expected_unobscured_rect.Intersect({plugin_offset_in_iframe, plugin_size});
+ expected_unobscured_rect.MoveBy(-plugin_offset_in_iframe);
+
+ // clip_rect is the visible part of the unobscured_rect, inside the
+ // root_frame.
+ IntRect expected_clip_rect = expected_unobscured_rect;
+ expected_clip_rect.MoveBy(expected_window_rect.Location());
+ expected_clip_rect.Intersect({{0, 0}, IntSize(300, 300)});
+ expected_clip_rect.MoveBy(-expected_window_rect.Location());
+
+ return std::make_tuple(expected_window_rect, expected_clip_rect,
+ expected_unobscured_rect);
+ };
+
+ IntSize root_document_scrolls_to[] = {IntSize(0, 0),
+ IntSize(0, 20),
+ IntSize(0, 300),
+ IntSize(0, 320),
+ IntSize(0, 340)};
+
+ IntSize iframe_scrolls_to[] = {IntSize(0, 0),
+ IntSize(0, 20),
+ IntSize(0, 40),
+ IntSize(0, 60),
+ IntSize(0, 80)};
+
+ for (auto& root_document_scroll_to : root_document_scrolls_to) {
+ for (auto& iframe_scroll_to : iframe_scrolls_to) {
+ web_view->SmoothScroll(root_document_scroll_to.Width(),
+ root_document_scroll_to.Height(), 0);
+ iframe->SetScrollOffset(iframe_scroll_to);
+ UpdateAllLifecyclePhases(web_view);
+ RunPendingTasks();
+
+ auto expected_values =
+ compute_expected_values(root_document_scroll_to, iframe_scroll_to);
+
+ IntRect window_rect, clip_rect, unobscured_rect;
+ CalculateGeometry(plugin_container_impl, window_rect, clip_rect,
+ unobscured_rect);
+
+ EXPECT_EQ(std::get<0>(expected_values), window_rect);
+ EXPECT_EQ(std::get<1>(expected_values), clip_rect);
+
+ // It seems that CalculateGeometry calculates x and y values for empty
+ // rectangles slightly differently, but these values are not important in
+ // the empty case.
+ if(std::get<2>(expected_values).IsEmpty())
+ EXPECT_TRUE(unobscured_rect.IsEmpty());
+ else
+ EXPECT_EQ(std::get<2>(expected_values), unobscured_rect);
+ }
+ }
+
+ // Cause the plugin's frame to be detached.
+ web_view_helper.Reset();
+}
+
TEST_F(WebPluginContainerTest, ClippedRectsForSubpixelPositionedPlugin) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|.
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -1339,7 +1444,7 @@ TEST_F(WebPluginContainerTest, TopmostAfterDetachTest) {
RegisterMockedURL("plugin_container.html");
// The client must outlive WebViewHelper.
CustomPluginWebFrameClient<TopmostPlugin> plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -1397,7 +1502,7 @@ TEST_F(WebPluginContainerTest, CompositedPluginSPv2) {
RegisterMockedURL("plugin.html");
// Must outlive |web_view_helper|
CustomPluginWebFrameClient<CompositedPlugin> web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin.html", &web_frame_client);
EnablePlugins(web_view, WebSize(800, 600));
@@ -1405,7 +1510,6 @@ TEST_F(WebPluginContainerTest, CompositedPluginSPv2) {
WebPluginContainerImpl* container = static_cast<WebPluginContainerImpl*>(
GetWebPluginContainer(web_view, WebString::FromUTF8("plugin")));
ASSERT_TRUE(container);
- Element* element = static_cast<Element*>(container->GetElement());
const auto* plugin =
static_cast<const CompositedPlugin*>(container->Plugin());
@@ -1420,7 +1524,6 @@ TEST_F(WebPluginContainerTest, CompositedPluginSPv2) {
const auto& display_items =
paint_controller->GetPaintArtifact().GetDisplayItemList();
ASSERT_EQ(1u, display_items.size());
- EXPECT_EQ(element->GetLayoutObject(), &display_items[0].Client());
ASSERT_EQ(DisplayItem::kForeignLayerPlugin, display_items[0].GetType());
const auto& foreign_layer_display_item =
static_cast<const ForeignLayerDisplayItem&>(display_items[0]);
@@ -1431,7 +1534,7 @@ TEST_F(WebPluginContainerTest, NeedsWheelEvents) {
RegisterMockedURL("plugin_container.html");
// Must outlive |web_view_helper|
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "plugin_container.html", &plugin_web_frame_client);
EnablePlugins(web_view, WebSize(300, 300));
@@ -1453,10 +1556,10 @@ TEST_F(WebPluginContainerTest, IFramePluginDocumentDisplayNone) {
RegisterMockedURL("iframe_pdf_display_none.html", "text/html");
TestPluginWebFrameClient plugin_web_frame_client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "iframe_pdf_display_none.html", &plugin_web_frame_client);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(web_view);
WebFrame* web_iframe = web_view->MainFrame()->FirstChild();
LocalFrame* iframe = ToLocalFrame(WebFrame::ToCoreFrame(*web_iframe));
diff --git a/chromium/third_party/blink/renderer/core/exported/web_range.cc b/chromium/third_party/blink/renderer/core/exported/web_range.cc
index 9e1f83dc508..2f850e715b7 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_range.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_range.cc
@@ -46,6 +46,8 @@ WebRange::WebRange(int start, int length)
<< "These values are reserved to indicate that the range is null";
}
+WebRange::WebRange() = default;
+
WebRange::WebRange(const EphemeralRange& range) {
if (range.IsNull())
return;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc
index 437a05ab379..fab7bc61192 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc
@@ -64,7 +64,8 @@ WebRemoteFrame* WebRemoteFrame::CreateMainFrame(WebView* web_view,
WebRemoteFrameImpl* WebRemoteFrameImpl::Create(WebTreeScopeType scope,
WebRemoteFrameClient* client) {
- WebRemoteFrameImpl* frame = new WebRemoteFrameImpl(scope, client);
+ WebRemoteFrameImpl* frame =
+ MakeGarbageCollected<WebRemoteFrameImpl>(scope, client);
return frame;
}
@@ -72,8 +73,8 @@ WebRemoteFrameImpl* WebRemoteFrameImpl::CreateMainFrame(
WebView* web_view,
WebRemoteFrameClient* client,
WebFrame* opener) {
- WebRemoteFrameImpl* frame =
- new WebRemoteFrameImpl(WebTreeScopeType::kDocument, client);
+ WebRemoteFrameImpl* frame = MakeGarbageCollected<WebRemoteFrameImpl>(
+ WebTreeScopeType::kDocument, client);
frame->SetOpener(opener);
Page& page = *static_cast<WebViewImpl*>(web_view)->GetPage();
// It would be nice to DCHECK that the main frame is not set yet here.
@@ -146,13 +147,14 @@ WebLocalFrame* WebRemoteFrameImpl::CreateLocalChild(
WebFrame* previous_sibling,
const ParsedFeaturePolicy& container_policy,
const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType frame_owner_element_type,
WebFrame* opener) {
WebLocalFrameImpl* child =
WebLocalFrameImpl::Create(scope, client, interface_registry, opener);
InsertAfter(child, previous_sibling);
- RemoteFrameOwner* owner =
- RemoteFrameOwner::Create(static_cast<SandboxFlags>(sandbox_flags),
- container_policy, frame_owner_properties);
+ RemoteFrameOwner* owner = RemoteFrameOwner::Create(
+ static_cast<SandboxFlags>(sandbox_flags), container_policy,
+ frame_owner_properties, frame_owner_element_type);
child->InitializeCoreFrame(*GetFrame()->GetPage(), owner, name);
DCHECK(child->GetFrame());
return child;
@@ -171,14 +173,15 @@ WebRemoteFrame* WebRemoteFrameImpl::CreateRemoteChild(
const WebString& name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
+ FrameOwnerElementType frame_owner_element_type,
WebRemoteFrameClient* client,
WebFrame* opener) {
WebRemoteFrameImpl* child = WebRemoteFrameImpl::Create(scope, client);
child->SetOpener(opener);
AppendChild(child);
- RemoteFrameOwner* owner =
- RemoteFrameOwner::Create(static_cast<SandboxFlags>(sandbox_flags),
- container_policy, WebFrameOwnerProperties());
+ RemoteFrameOwner* owner = RemoteFrameOwner::Create(
+ static_cast<SandboxFlags>(sandbox_flags), container_policy,
+ WebFrameOwnerProperties(), frame_owner_element_type);
child->InitializeCoreFrame(*GetFrame()->GetPage(), owner, name);
return child;
}
@@ -333,7 +336,7 @@ void WebRemoteFrameImpl::WillEnterFullscreen() {
// future, this should plumb in information about which request type
// (prefixed or unprefixed) to use for firing fullscreen events.
Fullscreen::RequestFullscreen(
- *owner_element, FullscreenOptions(),
+ *owner_element, FullscreenOptions::Create(),
Fullscreen::RequestType::kPrefixedForCrossProcessDescendant);
}
@@ -346,6 +349,9 @@ void WebRemoteFrameImpl::UpdateUserActivationState(
case UserActivationUpdateType::kConsumeTransientActivation:
GetFrame()->ConsumeTransientUserActivationInLocalTree();
break;
+ case UserActivationUpdateType::kClearActivation:
+ GetFrame()->ClearUserActivationInLocalTree();
+ break;
}
}
@@ -440,6 +446,15 @@ WebRect WebRemoteFrameImpl::GetCompositingRect() {
return GetFrame()->View()->GetCompositingRect();
}
+void WebRemoteFrameImpl::RenderFallbackContent() const {
+ // TODO(ekaramad): If the owner renders its own content, then the current
+ // ContentFrame() should detach and free-up the OOPIF process (see
+ // https://crbug.com/850223).
+ auto* owner = frame_->DeprecatedLocalOwner();
+ DCHECK(IsHTMLObjectElement(owner));
+ owner->RenderFallbackContent(frame_);
+}
+
WebRemoteFrameImpl::WebRemoteFrameImpl(WebTreeScopeType scope,
WebRemoteFrameClient* client)
: WebRemoteFrame(scope),
diff --git a/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.h b/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.h
index 2337e119fe5..964952f5079 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.h
@@ -36,6 +36,7 @@ class CORE_EXPORT WebRemoteFrameImpl final
WebRemoteFrameClient*,
WebFrame* opener = nullptr);
+ WebRemoteFrameImpl(WebTreeScopeType, WebRemoteFrameClient*);
~WebRemoteFrameImpl() override;
// WebFrame methods:
@@ -53,11 +54,13 @@ class CORE_EXPORT WebRemoteFrameImpl final
WebFrame* previous_sibling,
const ParsedFeaturePolicy&,
const WebFrameOwnerProperties&,
+ FrameOwnerElementType,
WebFrame* opener) override;
WebRemoteFrame* CreateRemoteChild(WebTreeScopeType,
const WebString& name,
WebSandboxFlags,
const ParsedFeaturePolicy&,
+ FrameOwnerElementType,
WebRemoteFrameClient*,
WebFrame* opener) override;
void SetCcLayer(cc::Layer*,
@@ -93,6 +96,7 @@ class CORE_EXPORT WebRemoteFrameImpl final
void SetHasReceivedUserGestureBeforeNavigation(bool value) override;
v8::Local<v8::Object> GlobalProxy() const override;
WebRect GetCompositingRect() override;
+ void RenderFallbackContent() const override;
void InitializeCoreFrame(Page&, FrameOwner*, const AtomicString& name);
RemoteFrame* GetFrame() const { return frame_.Get(); }
@@ -106,8 +110,6 @@ class CORE_EXPORT WebRemoteFrameImpl final
private:
friend class RemoteFrameClientImpl;
- WebRemoteFrameImpl(WebTreeScopeType, WebRemoteFrameClient*);
-
void SetCoreFrame(RemoteFrame*);
void ApplyReplicatedFeaturePolicyHeader();
diff --git a/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data.cc b/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data.cc
index cd36d12251a..58141f56419 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data.cc
@@ -46,14 +46,14 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
// Gets the encoding for the form.
// TODO(tkent): Use FormDataEncoder::encodingFromAcceptCharset().
void GetFormEncoding(const HTMLFormElement& form, WTF::TextEncoding* encoding) {
- String str(form.FastGetAttribute(HTMLNames::accept_charsetAttr));
+ String str(form.FastGetAttribute(html_names::kAcceptCharsetAttr));
str.Replace(',', ' ');
Vector<String> charsets;
str.Split(' ', charsets);
@@ -91,7 +91,7 @@ bool IsSelectInDefaultState(const HTMLSelectElement& select) {
if (select.IsMultiple() || select.size() > 1) {
for (auto* const option_element : select.GetOptionList()) {
if (option_element->Selected() !=
- option_element->FastHasAttribute(selectedAttr))
+ option_element->FastHasAttribute(kSelectedAttr))
return false;
}
return true;
@@ -101,7 +101,7 @@ bool IsSelectInDefaultState(const HTMLSelectElement& select) {
// least one item is selected, determine which one.
HTMLOptionElement* initial_selected = nullptr;
for (auto* const option_element : select.GetOptionList()) {
- if (option_element->FastHasAttribute(selectedAttr)) {
+ if (option_element->FastHasAttribute(kSelectedAttr)) {
// The page specified the option to select.
initial_selected = option_element;
break;
@@ -119,9 +119,9 @@ bool IsSelectInDefaultState(const HTMLSelectElement& select) {
// attribute.
bool IsInDefaultState(const HTMLFormControlElement& form_element) {
if (auto* input = ToHTMLInputElementOrNull(form_element)) {
- if (input->type() == InputTypeNames::checkbox ||
- input->type() == InputTypeNames::radio)
- return input->checked() == input->FastHasAttribute(checkedAttr);
+ if (input->type() == input_type_names::kCheckbox ||
+ input->type() == input_type_names::kRadio)
+ return input->checked() == input->FastHasAttribute(kCheckedAttr);
} else if (auto* select = ToHTMLSelectElementOrNull(form_element)) {
return IsSelectInDefaultState(*select);
}
@@ -153,8 +153,8 @@ HTMLInputElement* FindSuitableSearchInputElement(const HTMLFormElement& form) {
// Return nothing if a file upload field or a password field are
// found.
- if (input.type() == InputTypeNames::file ||
- input.type() == InputTypeNames::password)
+ if (input.type() == input_type_names::kFile ||
+ input.type() == input_type_names::kPassword)
return nullptr;
if (input.IsTextField()) {
@@ -223,7 +223,7 @@ WebSearchableFormData::WebSearchableFormData(
static_cast<HTMLInputElement*>(selected_input_element);
// Only consider forms that GET data.
- if (EqualIgnoringASCIICase(form_element->getAttribute(methodAttr), "post"))
+ if (EqualIgnoringASCIICase(form_element->getAttribute(kMethodAttr), "post"))
return;
WTF::TextEncoding encoding;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc b/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc
index 13a38897028..170095eefca 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_searchable_form_data_test.cc
@@ -50,9 +50,9 @@ namespace {
void RegisterMockedURLLoadFromBaseURL(const std::string& base_url,
const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(WebString::FromUTF8(base_url),
- test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ url_test_helpers::RegisterMockedURLLoadFromBase(
+ WebString::FromUTF8(base_url), test::CoreTestDataPath(),
+ WebString::FromUTF8(file_name));
}
class WebSearchableFormDataTest : public testing::Test {
@@ -65,7 +65,7 @@ class WebSearchableFormDataTest : public testing::Test {
->UnregisterAllURLsAndClearMemoryCache();
}
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/exported/web_security_policy.cc b/chromium/third_party/blink/renderer/core/exported/web_security_policy.cc
index 9ea33562533..88d753e26b5 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_security_policy.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_security_policy.cc
@@ -30,6 +30,7 @@
#include "third_party/blink/public/web/web_security_policy.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url.h"
@@ -70,41 +71,34 @@ void WebSecurityPolicy::AddOriginAccessAllowListEntry(
const WebString& destination_protocol,
const WebString& destination_host,
bool allow_destination_subdomains,
- const network::mojom::CORSOriginAccessMatchPriority priority) {
+ const network::mojom::CorsOriginAccessMatchPriority priority) {
SecurityPolicy::AddOriginAccessAllowListEntry(
*SecurityOrigin::Create(source_origin), destination_protocol,
destination_host, allow_destination_subdomains, priority);
}
-void WebSecurityPolicy::ClearOriginAccessAllowListForOrigin(
- const WebURL& source_origin) {
- SecurityPolicy::ClearOriginAccessAllowListForOrigin(
- *SecurityOrigin::Create(source_origin));
-}
-
-void WebSecurityPolicy::ClearOriginAccessAllowList() {
- SecurityPolicy::ClearOriginAccessAllowList();
-}
-
-void WebSecurityPolicy::ClearOriginAccessListForOrigin(
- const WebURL& source_origin) {
- scoped_refptr<SecurityOrigin> security_origin =
- SecurityOrigin::Create(source_origin);
- SecurityPolicy::ClearOriginAccessAllowListForOrigin(*security_origin);
- SecurityPolicy::ClearOriginAccessBlockListForOrigin(*security_origin);
-}
-
void WebSecurityPolicy::AddOriginAccessBlockListEntry(
const WebURL& source_origin,
const WebString& destination_protocol,
const WebString& destination_host,
bool allow_destination_subdomains,
- const network::mojom::CORSOriginAccessMatchPriority priority) {
+ const network::mojom::CorsOriginAccessMatchPriority priority) {
SecurityPolicy::AddOriginAccessBlockListEntry(
*SecurityOrigin::Create(source_origin), destination_protocol,
destination_host, allow_destination_subdomains, priority);
}
+void WebSecurityPolicy::ClearOriginAccessListForOrigin(
+ const WebURL& source_origin) {
+ scoped_refptr<SecurityOrigin> security_origin =
+ SecurityOrigin::Create(source_origin);
+ SecurityPolicy::ClearOriginAccessListForOrigin(*security_origin);
+}
+
+void WebSecurityPolicy::ClearOriginAccessList() {
+ SecurityPolicy::ClearOriginAccessList();
+}
+
void WebSecurityPolicy::AddOriginTrustworthyWhiteList(const WebString& origin) {
SecurityPolicy::AddOriginTrustworthyWhiteList(origin);
}
@@ -115,11 +109,10 @@ void WebSecurityPolicy::AddSchemeToBypassSecureContextWhitelist(
}
WebString WebSecurityPolicy::GenerateReferrerHeader(
- WebReferrerPolicy referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const WebURL& url,
const WebString& referrer) {
- return SecurityPolicy::GenerateReferrer(
- static_cast<ReferrerPolicy>(referrer_policy), url, referrer)
+ return SecurityPolicy::GenerateReferrer(referrer_policy, url, referrer)
.referrer;
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_settings_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_settings_impl.cc
index 95ddf7175e2..67f8c013de1 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_settings_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_settings_impl.cc
@@ -290,8 +290,8 @@ void WebSettingsImpl::SetPreferHiddenVolumeControls(bool enabled) {
settings_->SetPreferHiddenVolumeControls(enabled);
}
-void WebSettingsImpl::SetShouldThrottlePushState(bool enabled) {
- settings_->SetShouldThrottlePushState(enabled);
+void WebSettingsImpl::SetShouldProtectAgainstIpcFlooding(bool enabled) {
+ settings_->SetShouldProtectAgainstIpcFlooding(enabled);
}
void WebSettingsImpl::SetDOMPasteAllowed(bool enabled) {
@@ -473,10 +473,6 @@ void WebSettingsImpl::SetEditingBehavior(EditingBehavior behavior) {
settings_->SetEditingBehaviorType(static_cast<EditingBehaviorType>(behavior));
}
-void WebSettingsImpl::SetAcceleratedCompositingEnabled(bool enabled) {
- settings_->SetAcceleratedCompositingEnabled(enabled);
-}
-
void WebSettingsImpl::SetMockScrollbarsEnabled(bool enabled) {
settings_->SetMockScrollbarsEnabled(enabled);
}
@@ -715,6 +711,10 @@ void WebSettingsImpl::SetLowPriorityIframesThreshold(
settings_->SetLowPriorityIframesThreshold(effective_connection_type);
}
+void WebSettingsImpl::SetLazyLoadEnabled(bool enabled) {
+ settings_->SetLazyLoadEnabled(enabled);
+}
+
void WebSettingsImpl::SetLazyFrameLoadingDistanceThresholdPxUnknown(
int distance_px) {
settings_->SetLazyFrameLoadingDistanceThresholdPxUnknown(distance_px);
@@ -775,11 +775,11 @@ void WebSettingsImpl::SetLazyImageLoadingDistanceThresholdPx4G(
settings_->SetLazyImageLoadingDistanceThresholdPx4G(distance_px);
}
-STATIC_ASSERT_ENUM(WebSettings::kImageAnimationPolicyAllowed,
+STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kAllowed,
kImageAnimationPolicyAllowed);
-STATIC_ASSERT_ENUM(WebSettings::kImageAnimationPolicyAnimateOnce,
+STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kAnimateOnce,
kImageAnimationPolicyAnimateOnce);
-STATIC_ASSERT_ENUM(WebSettings::kImageAnimationPolicyNoAnimation,
+STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kNoAnimation,
kImageAnimationPolicyNoAnimation);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_settings_impl.h b/chromium/third_party/blink/renderer/core/exported/web_settings_impl.h
index 36c9adb1993..0d4722a8a90 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_settings_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_settings_impl.h
@@ -51,7 +51,6 @@ class CORE_EXPORT WebSettingsImpl final : public WebSettings {
bool ShrinksViewportContentToFit() const override;
bool ViewportEnabled() const override;
void SetAccelerated2dCanvasMSAASampleCount(int) override;
- void SetAcceleratedCompositingEnabled(bool) override;
void SetAutoplayPolicy(AutoplayPolicy) override;
void SetPreferCompositingToLCDTextEnabled(bool) override;
void SetAccessibilityPasswordValuesEnabled(bool) override;
@@ -138,7 +137,7 @@ class CORE_EXPORT WebSettingsImpl final : public WebSettings {
void SetAvailableHoverTypes(int) override;
void SetPrimaryHoverType(HoverType) override;
void SetPreferHiddenVolumeControls(bool) override;
- void SetShouldThrottlePushState(bool) override;
+ void SetShouldProtectAgainstIpcFlooding(bool) override;
void SetRenderVSyncNotificationEnabled(bool) override;
void SetReportScreenSizeInPhysicalPixelsQuirk(bool) override;
void SetRubberBandingOnCompositorThread(bool) override;
@@ -205,6 +204,8 @@ class CORE_EXPORT WebSettingsImpl final : public WebSettings {
void SetMediaDownloadInProductHelpEnabled(bool) override;
void SetLowPriorityIframesThreshold(WebEffectiveConnectionType) override;
+ void SetLazyLoadEnabled(bool) override;
+
// TODO(rajendrant): Remove these lazyload distance threshold settings for
// frames and images, once the values are finalized from the experiment.
void SetLazyFrameLoadingDistanceThresholdPxUnknown(int) override;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc
index 23a80a28079..9de43de6741 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.cc
@@ -33,6 +33,7 @@
#include <memory>
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
@@ -47,6 +48,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/events/message_event.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
@@ -60,7 +62,6 @@
#include "third_party/blink/renderer/core/workers/worker_classic_script_loader.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
@@ -75,8 +76,7 @@
namespace blink {
WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client)
- : worker_inspector_proxy_(WorkerInspectorProxy::Create()),
- client_(client),
+ : client_(client),
creation_address_space_(mojom::IPAddressSpace::kPublic),
parent_execution_context_task_runners_(
ParentExecutionContextTaskRunners::Create()),
@@ -105,9 +105,11 @@ void WebSharedWorkerImpl::TerminateWorkerThread() {
// |this| is deleted at this point.
return;
}
- if (worker_thread_)
+ if (worker_thread_) {
worker_thread_->Terminate();
- worker_inspector_proxy_->WorkerThreadTerminated();
+ DevToolsAgent::WorkerThreadTerminated(shadow_page_->GetDocument(),
+ worker_thread_.get());
+ }
}
std::unique_ptr<WebApplicationCacheHost>
@@ -122,7 +124,7 @@ void WebSharedWorkerImpl::OnShadowPageInitialized() {
DCHECK(!main_script_loader_);
shadow_page_->DocumentLoader()->SetServiceWorkerNetworkProvider(
client_->CreateServiceWorkerNetworkProvider());
- main_script_loader_ = WorkerClassicScriptLoader::Create();
+ main_script_loader_ = MakeGarbageCollected<WorkerClassicScriptLoader>();
network::mojom::FetchRequestMode fetch_request_mode =
network::mojom::FetchRequestMode::kSameOrigin;
@@ -133,6 +135,7 @@ void WebSharedWorkerImpl::OnShadowPageInitialized() {
*shadow_page_->GetDocument(), script_request_url_,
mojom::RequestContextType::SHARED_WORKER, fetch_request_mode,
fetch_credentials_mode, creation_address_space_,
+ false /* is_nested_worker */,
Bind(&WebSharedWorkerImpl::DidReceiveScriptLoaderResponse,
WTF::Unretained(this)),
Bind(&WebSharedWorkerImpl::OnScriptLoaderFinished,
@@ -160,12 +163,6 @@ void WebSharedWorkerImpl::CountFeature(WebFeature feature) {
client_->CountFeature(feature);
}
-void WebSharedWorkerImpl::PostMessageToPageInspector(int session_id,
- const String& message) {
- DCHECK(IsMainThread());
- worker_inspector_proxy_->DispatchMessageFromWorker(session_id, message);
-}
-
void WebSharedWorkerImpl::DidCloseWorkerGlobalScope() {
DCHECK(IsMainThread());
client_->WorkerContextClosed();
@@ -195,11 +192,8 @@ void WebSharedWorkerImpl::ConnectTaskOnWorkerThread(
// Wrap the passed-in channel in a MessagePort, and send it off via a connect
// event.
DCHECK(worker_thread_->IsCurrentThread());
- WorkerGlobalScope* worker_global_scope =
- ToWorkerGlobalScope(worker_thread_->GlobalScope());
- SECURITY_DCHECK(worker_global_scope->IsSharedWorkerGlobalScope());
- static_cast<SharedWorkerGlobalScope*>(worker_global_scope)
- ->ConnectPausable(std::move(channel));
+ auto* scope = To<SharedWorkerGlobalScope>(worker_thread_->GlobalScope());
+ scope->ConnectPausable(std::move(channel));
}
void WebSharedWorkerImpl::StartWorkerContext(
@@ -301,7 +295,7 @@ void WebSharedWorkerImpl::ContinueOnScriptLoaderFinished() {
worker_clients, std::make_unique<SharedWorkerContentSettingsProxy>(
std::move(content_settings_info_)));
- std::unique_ptr<WebWorkerFetchContext> web_worker_fetch_context =
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context =
client_->CreateWorkerFetchContext(
shadow_page_->DocumentLoader()->GetServiceWorkerNetworkProvider());
DCHECK(web_worker_fetch_context);
@@ -310,12 +304,11 @@ void WebSharedWorkerImpl::ContinueOnScriptLoaderFinished() {
->Fetcher()
->Context()
.ApplicationCacheHostID());
- ProvideWorkerFetchContextToWorker(worker_clients,
- std::move(web_worker_fetch_context));
ContentSecurityPolicy* content_security_policy =
main_script_loader_->GetContentSecurityPolicy();
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
if (!main_script_loader_->GetReferrerPolicy().IsNull()) {
SecurityPolicy::ReferrerPolicyFromHeaderValue(
main_script_loader_->GetReferrerPolicy(),
@@ -324,9 +317,9 @@ void WebSharedWorkerImpl::ContinueOnScriptLoaderFinished() {
auto worker_settings = std::make_unique<WorkerSettings>(
shadow_page_->GetDocument()->GetFrame()->GetSettings());
- // TODO(nhiroki); Set |script_type| to ScriptType::kModule for module fetch.
- // (https://crbug.com/824646)
- ScriptType script_type = ScriptType::kClassic;
+ // TODO(nhiroki); Set |script_type| to mojom::ScriptType::kModule for module
+ // fetch (https://crbug.com/824646).
+ mojom::ScriptType script_type = mojom::ScriptType::kClassic;
const KURL script_response_url = main_script_loader_->ResponseURL();
DCHECK(static_cast<KURL>(script_request_url_) == script_response_url ||
@@ -336,6 +329,7 @@ void WebSharedWorkerImpl::ContinueOnScriptLoaderFinished() {
auto global_scope_creation_params =
std::make_unique<GlobalScopeCreationParams>(
script_response_url, script_type, document->UserAgent(),
+ std::move(web_worker_fetch_context),
content_security_policy ? content_security_policy->Headers()
: Vector<CSPHeaderAndType>(),
referrer_policy, starter_origin, starter_secure_context,
@@ -347,7 +341,7 @@ void WebSharedWorkerImpl::ContinueOnScriptLoaderFinished() {
std::move(pending_interface_provider_));
String source_code = main_script_loader_->SourceText();
- reporting_proxy_ = new SharedWorkerReportingProxy(
+ reporting_proxy_ = MakeGarbageCollected<SharedWorkerReportingProxy>(
this, parent_execution_context_task_runners_);
worker_thread_ =
std::make_unique<SharedWorkerThread>(name_, *reporting_proxy_);
@@ -359,17 +353,16 @@ void WebSharedWorkerImpl::ContinueOnScriptLoaderFinished() {
thread_startup_data.atomics_wait_mode =
WorkerBackingThreadStartupData::AtomicsWaitMode::kAllow;
- GetWorkerThread()->Start(
- std::move(global_scope_creation_params), thread_startup_data,
- worker_inspector_proxy_->ShouldPauseOnWorkerStart(document),
- parent_execution_context_task_runners_);
- worker_inspector_proxy_->WorkerThreadCreated(document, GetWorkerThread(),
- script_response_url);
+ auto devtools_params = DevToolsAgent::WorkerThreadCreated(
+ document, GetWorkerThread(), script_response_url);
+
+ GetWorkerThread()->Start(std::move(global_scope_creation_params),
+ thread_startup_data, std::move(devtools_params),
+ parent_execution_context_task_runners_);
// TODO(nhiroki): Support module workers (https://crbug.com/680046).
- // Shared worker is origin-bound, so use kSharableCrossOrigin.
- GetWorkerThread()->EvaluateClassicScript(
- script_response_url, kSharableCrossOrigin, source_code,
- nullptr /* cached_meta_data */, v8_inspector::V8StackTraceId());
+ GetWorkerThread()->EvaluateClassicScript(script_response_url, source_code,
+ nullptr /* cached_meta_data */,
+ v8_inspector::V8StackTraceId());
client_->WorkerScriptLoaded();
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.h b/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.h
index ac4becfb08a..98073b09b4a 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.h
@@ -65,7 +65,6 @@ class WebSharedWorkerClient;
class WebString;
class WebURL;
class WorkerClassicScriptLoader;
-class WorkerInspectorProxy;
// This class is used by the worker process code to talk to the SharedWorker
// implementation. This is basically accessed on the main thread, but some
@@ -110,7 +109,6 @@ class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker,
// Callback methods for SharedWorkerReportingProxy.
void CountFeature(WebFeature);
- void PostMessageToPageInspector(int session_id, const String& message);
void DidCloseWorkerGlobalScope();
void DidTerminateWorkerThread();
@@ -131,8 +129,6 @@ class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker,
// to the same worker.
base::UnguessableToken devtools_worker_token_;
- Persistent<WorkerInspectorProxy> worker_inspector_proxy_;
-
Persistent<SharedWorkerReportingProxy> reporting_proxy_;
std::unique_ptr<WorkerThread> worker_thread_;
mojom::blink::WorkerContentSettingsProxyPtrInfo content_settings_info_;
@@ -145,7 +141,7 @@ class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker,
bool is_paused_on_start_ = false;
// Kept around only while main script loading is ongoing.
- scoped_refptr<WorkerClassicScriptLoader> main_script_loader_;
+ Persistent<WorkerClassicScriptLoader> main_script_loader_;
WebURL script_request_url_;
WebString name_;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_view_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_view_impl.cc
index 1287fac887a..9246cf14bca 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_view_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -251,7 +251,7 @@ class EmptyEventListener final : public EventListener {
private:
EmptyEventListener() : EventListener(kCPPEventListenerType) {}
- void handleEvent(ExecutionContext* execution_context, Event*) override {}
+ void Invoke(ExecutionContext* execution_context, Event*) override {}
};
} // namespace
@@ -288,8 +288,8 @@ void WebView::ResetVisitedLinkState(bool invalidate_visited_link_hashes) {
void WebViewImpl::SetPrerendererClient(
WebPrerendererClient* prerenderer_client) {
DCHECK(page_);
- ProvidePrerendererClientTo(*page_,
- new PrerendererClient(*page_, prerenderer_client));
+ ProvidePrerendererClientTo(*page_, MakeGarbageCollected<PrerendererClient>(
+ *page_, prerenderer_client));
}
WebViewImpl::WebViewImpl(WebViewClient* client,
@@ -315,6 +315,8 @@ WebViewImpl::WebViewImpl(WebViewClient* client,
ime_accept_events_(true),
dev_tools_emulator_(nullptr),
tabs_to_links_(false),
+ does_composite_(widget_client_ &&
+ !widget_client_->AllowsBrokenNullLayerTreeView()),
layer_tree_view_(nullptr),
root_layer_(nullptr),
root_graphics_layer_(nullptr),
@@ -332,8 +334,7 @@ WebViewImpl::WebViewImpl(WebViewClient* client,
should_dispatch_first_layout_after_finished_loading_(false),
display_mode_(kWebDisplayModeBrowser),
elastic_overscroll_(FloatSize()),
- mutator_dispatcher_(nullptr),
- override_compositor_visibility_(false) {
+ mutator_dispatcher_(nullptr) {
DCHECK_EQ(!!client_, !!widget_client_);
Page::PageClients page_clients;
page_clients.chrome_client = chrome_client_.Get();
@@ -343,23 +344,18 @@ WebViewImpl::WebViewImpl(WebViewClient* client,
CoreInitializer::GetInstance().ProvideModulesToPage(*page_, client_);
SetVisibilityState(visibility_state, true);
- // TODO(dcheng): All WebViewImpls should have an associated LayerTreeView,
- // but for various reasons, that's not the case... WebView plugin, printing,
- // workers, and tests don't use a compositor in their WebViews. Sometimes
- // they avoid the compositor by using a null client, and sometimes by having
- // the client return a null compositor. We should make things more consistent
- // and clear.
- // For some reason this was not set when WidgetClient() is not provided,
- // even though there will be no LayerTreeView in that case either.
- if (WidgetClient() && WidgetClient()->AllowsBrokenNullLayerTreeView())
- page_->GetSettings().SetAcceleratedCompositingEnabled(false);
+ // When not compositing, keep the Page in the loop so that it will paint all
+ // content into the root layer, as multiple layers can only be used when
+ // compositing them together later.
+ if (does_composite_)
+ page_->GetSettings().SetAcceleratedCompositingEnabled(true);
dev_tools_emulator_ = DevToolsEmulator::Create(this);
AllInstances().insert(this);
page_importance_signals_.SetObserver(client);
- resize_viewport_anchor_ = new ResizeViewportAnchor(*page_);
+ resize_viewport_anchor_ = MakeGarbageCollected<ResizeViewportAnchor>(*page_);
}
WebViewImpl::~WebViewImpl() {
@@ -536,8 +532,14 @@ WebInputEventResult WebViewImpl::HandleGestureEvent(
case WebInputEvent::kGestureDoubleTap:
if (web_settings_->DoubleTapToZoomEnabled() &&
MinimumPageScaleFactor() != MaximumPageScaleFactor()) {
- AnimateDoubleTapZoom(
- FlooredIntPoint(scaled_event.PositionInRootFrame()));
+ if (auto* main_frame = MainFrameImpl()) {
+ IntPoint pos_in_root_frame =
+ FlooredIntPoint(scaled_event.PositionInRootFrame());
+ WebRect block_bounds =
+ main_frame->FrameWidgetImpl()->ComputeBlockBound(
+ pos_in_root_frame, false);
+ AnimateDoubleTapZoom(pos_in_root_frame, block_bounds);
+ }
}
event_result = WebInputEventResult::kHandledSystem;
WidgetClient()->DidHandleGestureEvent(event, event_cancelled);
@@ -661,7 +663,7 @@ bool WebViewImpl::StartPageScaleAnimation(const IntPoint& target_position,
float new_scale,
double duration_in_seconds) {
VisualViewport& visual_viewport = GetPage()->GetVisualViewport();
- WebPoint clamped_point = target_position;
+ gfx::Point clamped_point = target_position;
if (!use_anchor) {
clamped_point =
visual_viewport.ClampDocumentOffsetAtScale(target_position, new_scale);
@@ -671,7 +673,7 @@ bool WebViewImpl::StartPageScaleAnimation(const IntPoint& target_position,
LocalFrameView* view = MainFrameImpl()->GetFrameView();
if (view && view->GetScrollableArea()) {
view->GetScrollableArea()->SetScrollOffset(
- ScrollOffset(clamped_point.x, clamped_point.y),
+ ScrollOffset(clamped_point.x(), clamped_point.y()),
kProgrammaticScroll);
}
@@ -726,6 +728,11 @@ void WebViewImpl::SetShowScrollBottleneckRects(bool show) {
layer_tree_view_->SetShowScrollBottleneckRects(show);
}
+void WebViewImpl::SetShowHitTestBorders(bool show) {
+ if (layer_tree_view_)
+ layer_tree_view_->SetShowHitTestBorders(show);
+}
+
void WebViewImpl::AcceptLanguagesChanged() {
if (client_)
FontCache::AcceptLanguagesChanged(client_->AcceptLanguages());
@@ -875,43 +882,6 @@ WebInputEventResult WebViewImpl::HandleCharEvent(
return WebInputEventResult::kNotHandled;
}
-WebRect WebViewImpl::ComputeBlockBound(const WebPoint& point_in_root_frame,
- bool ignore_clipping) {
- if (!MainFrameImpl())
- return WebRect();
-
- // Use the point-based hit test to find the node.
- HitTestLocation location(
- MainFrameImpl()->GetFrameView()->ConvertFromRootFrame(
- LayoutPoint(point_in_root_frame)));
- HitTestRequest::HitTestRequestType hit_type =
- HitTestRequest::kReadOnly | HitTestRequest::kActive |
- (ignore_clipping ? HitTestRequest::kIgnoreClipping : 0);
- HitTestResult result =
- MainFrameImpl()->GetFrame()->GetEventHandler().HitTestResultAtLocation(
- location, hit_type);
- result.SetToShadowHostIfInRestrictedShadowRoot();
-
- Node* node = result.InnerNodeOrImageMapImage();
- if (!node)
- return WebRect();
-
- // Find the block type node based on the hit node.
- // FIXME: This wants to walk flat tree with
- // LayoutTreeBuilderTraversal::parent().
- while (node &&
- (!node->GetLayoutObject() || node->GetLayoutObject()->IsInline()))
- node = LayoutTreeBuilderTraversal::Parent(*node);
-
- // Return the bounding box in the root frame's coordinate space.
- if (node) {
- IntRect absolute_rect = node->GetLayoutObject()->AbsoluteBoundingBoxRect();
- LocalFrame* frame = node->GetDocument().GetFrame();
- return frame->View()->ConvertToRootFrame(absolute_rect);
- }
- return WebRect();
-}
-
WebRect WebViewImpl::WidenRectWithinPageBounds(const WebRect& source,
int target_margin,
int minimum_margin) {
@@ -963,14 +933,14 @@ float WebViewImpl::MaximumLegiblePageScale() const {
}
void WebViewImpl::ComputeScaleAndScrollForBlockRect(
- const WebPoint& hit_point_in_root_frame,
+ const gfx::Point& hit_point_in_root_frame,
const WebRect& block_rect_in_root_frame,
float padding,
float default_scale_when_already_legible,
float& scale,
- WebPoint& scroll) {
+ IntPoint& scroll) {
scale = PageScaleFactor();
- scroll.x = scroll.y = 0;
+ scroll = IntPoint();
WebRect rect = block_rect_in_root_frame;
@@ -1012,7 +982,7 @@ void WebViewImpl::ComputeScaleAndScrollForBlockRect(
// Ensure position we're zooming to (+ padding) isn't off the bottom of
// the screen.
rect.y = std::max<float>(
- rect.y, hit_point_in_root_frame.y + padding - screen_height);
+ rect.y, hit_point_in_root_frame.y() + padding - screen_height);
} // Otherwise top align the block.
// Do the same thing for horizontal alignment.
@@ -1020,10 +990,10 @@ void WebViewImpl::ComputeScaleAndScrollForBlockRect(
rect.x -= 0.5 * (screen_width - rect.width);
} else {
rect.x = std::max<float>(
- rect.x, hit_point_in_root_frame.x + padding - screen_width);
+ rect.x, hit_point_in_root_frame.x() + padding - screen_width);
}
- scroll.x = rect.x;
- scroll.y = rect.y;
+ scroll.SetX(rect.x);
+ scroll.SetY(rect.y);
scale = ClampPageScaleFactorToLimits(scale);
scroll = MainFrameImpl()->GetFrameView()->RootFrameToDocument(scroll);
@@ -1118,20 +1088,18 @@ void WebViewImpl::EnableTapHighlightAtPoint(
void WebViewImpl::EnableTapHighlights(
HeapVector<Member<Node>>& highlight_nodes) {
GetPage()->GetLinkHighlights().SetTapHighlights(highlight_nodes);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(LifecycleUpdateReason::kOther);
}
-void WebViewImpl::AnimateDoubleTapZoom(const IntPoint& point_in_root_frame) {
- // TODO(lukasza): https://crbug.com/734209: Add OOPIF support.
- if (!MainFrameImpl())
- return;
+void WebViewImpl::AnimateDoubleTapZoom(const gfx::Point& point_in_root_frame,
+ const WebRect& rect_to_zoom) {
+ DCHECK(MainFrameImpl());
- WebRect block_bounds = ComputeBlockBound(point_in_root_frame, false);
float scale;
- WebPoint scroll;
+ IntPoint scroll;
ComputeScaleAndScrollForBlockRect(
- point_in_root_frame, block_bounds, touchPointPadding,
+ point_in_root_frame, rect_to_zoom, touchPointPadding,
MinimumPageScaleFactor() * doubleTapZoomAlreadyLegibleRatio, scale,
scroll);
@@ -1141,7 +1109,7 @@ void WebViewImpl::AnimateDoubleTapZoom(const IntPoint& point_in_root_frame) {
double_tap_zoom_pending_;
bool scale_unchanged = fabs(PageScaleFactor() - scale) < minScaleDifference;
- bool should_zoom_out = block_bounds.IsEmpty() || scale_unchanged ||
+ bool should_zoom_out = rect_to_zoom.IsEmpty() || scale_unchanged ||
still_at_previous_double_tap_scale;
bool is_animating;
@@ -1150,7 +1118,7 @@ void WebViewImpl::AnimateDoubleTapZoom(const IntPoint& point_in_root_frame) {
scale = MinimumPageScaleFactor();
IntPoint target_position =
MainFrameImpl()->GetFrameView()->RootFrameToDocument(
- point_in_root_frame);
+ IntPoint(point_in_root_frame.x(), point_in_root_frame.y()));
is_animating = StartPageScaleAnimation(
target_position, true, scale, doubleTapZoomAnimationDurationInSeconds);
} else {
@@ -1173,9 +1141,9 @@ void WebViewImpl::ZoomToFindInPageRect(const WebRect& rect_in_root_frame) {
if (!MainFrameImpl())
return;
- WebRect block_bounds = ComputeBlockBound(
- WebPoint(rect_in_root_frame.x + rect_in_root_frame.width / 2,
- rect_in_root_frame.y + rect_in_root_frame.height / 2),
+ WebRect block_bounds = MainFrameImpl()->FrameWidgetImpl()->ComputeBlockBound(
+ gfx::Point(rect_in_root_frame.x + rect_in_root_frame.width / 2,
+ rect_in_root_frame.y + rect_in_root_frame.height / 2),
true);
if (block_bounds.IsEmpty()) {
@@ -1185,10 +1153,10 @@ void WebViewImpl::ZoomToFindInPageRect(const WebRect& rect_in_root_frame) {
}
float scale;
- WebPoint scroll;
+ IntPoint scroll;
ComputeScaleAndScrollForBlockRect(
- WebPoint(rect_in_root_frame.x, rect_in_root_frame.y), block_bounds,
+ gfx::Point(rect_in_root_frame.x, rect_in_root_frame.y), block_bounds,
nonUserInitiatedPointPadding, MinimumPageScaleFactor(), scale, scroll);
StartPageScaleAnimation(scroll, false, scale,
@@ -1287,7 +1255,7 @@ void WebViewImpl::EnablePopupMouseWheelEventListener(
// We register an empty event listener, EmptyEventListener, so that mouse
// wheel events get sent to the WebView.
popup_mouse_wheel_event_listener_ = EmptyEventListener::Create();
- document->addEventListener(EventTypeNames::mousewheel,
+ document->addEventListener(event_type_names::kMousewheel,
popup_mouse_wheel_event_listener_, false);
local_root_with_empty_mouse_wheel_listener_ = local_root;
}
@@ -1301,7 +1269,7 @@ void WebViewImpl::DisablePopupMouseWheelEventListener() {
DCHECK(document);
// Document may have already removed the event listener, for instance, due
// to a navigation, but remove it anyway.
- document->removeEventListener(EventTypeNames::mousewheel,
+ document->removeEventListener(event_type_names::kMousewheel,
popup_mouse_wheel_event_listener_.Release(),
false);
local_root_with_empty_mouse_wheel_listener_ = nullptr;
@@ -1373,14 +1341,13 @@ void WebViewImpl::UpdateICBAndResizeViewport() {
}
}
-void WebViewImpl::UpdateBrowserControlsState(
- cc::BrowserControlsState constraint,
- cc::BrowserControlsState current,
- bool animate) {
+void WebViewImpl::UpdateBrowserControlsConstraint(
+ cc::BrowserControlsState constraint) {
cc::BrowserControlsState old_permitted_state =
GetBrowserControls().PermittedState();
- GetBrowserControls().UpdateConstraintsAndState(constraint, current, animate);
+ GetBrowserControls().UpdateConstraintsAndState(
+ constraint, cc::BrowserControlsState::kBoth, false);
// If the controls are going from a locked hidden to unlocked state, or vice
// versa, the ICB size needs to change but we can't rely on getting a
@@ -1392,9 +1359,6 @@ void WebViewImpl::UpdateBrowserControlsState(
constraint == cc::BrowserControlsState::kHidden)) {
UpdateICBAndResizeViewport();
}
-
- if (layer_tree_view_)
- layer_tree_view_->UpdateBrowserControlsState(constraint, current, animate);
}
void WebViewImpl::DidUpdateBrowserControls() {
@@ -1465,7 +1429,7 @@ void WebViewImpl::ResizeViewWhileAnchored(float top_controls_height,
// Update lifecyle phases immediately to recalculate the minimum scale limit
// for rotation anchoring, and to make sure that no lifecycle states are
// stale if this WebView is embedded in another one.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(LifecycleUpdateReason::kOther);
}
void WebViewImpl::ResizeWithBrowserControls(
@@ -1574,7 +1538,8 @@ void WebViewImpl::RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time) {
frame_begin_time);
}
-void WebViewImpl::UpdateLifecycle(LifecycleUpdate requested_update) {
+void WebViewImpl::UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) {
TRACE_EVENT0("blink", "WebViewImpl::updateAllLifecyclePhases");
if (!MainFrameImpl())
return;
@@ -1583,7 +1548,7 @@ void WebViewImpl::UpdateLifecycle(LifecycleUpdate requested_update) {
MainFrameImpl()->GetFrame()->GetDocument()->Lifecycle());
PageWidgetDelegate::UpdateLifecycle(*page_, *MainFrameImpl()->GetFrame(),
- requested_update);
+ requested_update, reason);
if (requested_update == LifecycleUpdate::kLayout)
return;
@@ -1626,6 +1591,11 @@ void WebViewImpl::UpdateAllLifecyclePhasesAndCompositeForTesting(
}
}
+void WebViewImpl::RequestPresentationCallbackForTesting(
+ base::OnceClosure callback) {
+ layer_tree_view_->RequestPresentationCallback(std::move(callback));
+}
+
void WebViewImpl::PaintContent(cc::PaintCanvas* canvas, const WebRect& rect) {
// This should only be used when compositing is not being used for this
// WebView, and it is painting into the recording of its parent.
@@ -1666,7 +1636,7 @@ void WebViewImpl::ThemeChanged() {
}
void WebViewImpl::EnterFullscreen(LocalFrame& frame,
- const FullscreenOptions& options) {
+ const FullscreenOptions* options) {
fullscreen_controller_->EnterFullscreen(frame, options);
}
@@ -1795,26 +1765,26 @@ WebInputEventResult WebViewImpl::HandleCapturedMouseEvent(
AtomicString event_type;
switch (input_event.GetType()) {
case WebInputEvent::kMouseEnter:
- event_type = EventTypeNames::mouseover;
+ event_type = event_type_names::kMouseover;
break;
case WebInputEvent::kMouseMove:
- event_type = EventTypeNames::mousemove;
+ event_type = event_type_names::kMousemove;
break;
case WebInputEvent::kPointerRawMove:
// There will be no mouse event for raw move events.
- event_type = EventTypeNames::pointerrawmove;
+ event_type = event_type_names::kPointerrawmove;
break;
case WebInputEvent::kMouseLeave:
- event_type = EventTypeNames::mouseout;
+ event_type = event_type_names::kMouseout;
break;
case WebInputEvent::kMouseDown:
- event_type = EventTypeNames::mousedown;
+ event_type = event_type_names::kMousedown;
gesture_indicator = LocalFrame::NotifyUserActivation(
node->GetDocument().GetFrame(), UserGestureToken::kNewGesture);
mouse_capture_gesture_token_ = gesture_indicator->CurrentToken();
break;
case WebInputEvent::kMouseUp:
- event_type = EventTypeNames::mouseup;
+ event_type = event_type_names::kMouseup;
gesture_indicator = std::make_unique<UserGestureIndicator>(
std::move(mouse_capture_gesture_token_));
break;
@@ -1830,7 +1800,10 @@ WebInputEventResult WebViewImpl::HandleCapturedMouseEvent(
node, transformed_event, event_type,
TransformWebMouseEventVector(
MainFrameImpl()->GetFrameView(),
- coalesced_event.GetCoalescedEventsPointers()));
+ coalesced_event.GetCoalescedEventsPointers()),
+ TransformWebMouseEventVector(
+ MainFrameImpl()->GetFrameView(),
+ coalesced_event.GetPredictedEventsPointers()));
}
return WebInputEventResult::kHandledSystem;
}
@@ -2101,7 +2074,7 @@ static bool IsElementEditable(const Element* element) {
return true;
}
- return EqualIgnoringASCIICase(element->getAttribute(HTMLNames::roleAttr),
+ return EqualIgnoringASCIICase(element->getAttribute(html_names::kRoleAttr),
"textbox");
}
@@ -2159,7 +2132,8 @@ bool WebViewImpl::ShouldZoomToLegibleScale(const Element& element) {
// decide not to zoom in if the user won't be able to zoom out. e.g if the
// textbox is within a touch-action: none container the user can't zoom
// back out.
- TouchAction action = TouchActionUtil::ComputeEffectiveTouchAction(element);
+ TouchAction action =
+ touch_action_util::ComputeEffectiveTouchAction(element);
if (!(action & TouchAction::kTouchActionPinchZoom))
zoom_into_legible_scale = false;
}
@@ -2716,9 +2690,10 @@ void WebViewImpl::ResetScrollAndScaleState() {
}
void WebViewImpl::PerformPluginAction(const WebPluginAction& action,
- const WebPoint& location) {
+ const gfx::Point& location) {
// FIXME: Location is probably in viewport coordinates
- HitTestResult result = HitTestResultForRootFramePos(LayoutPoint(location));
+ HitTestResult result =
+ HitTestResultForRootFramePos(LayoutPoint(IntPoint(location)));
Node* node = result.InnerNode();
if (!IsHTMLObjectElement(*node) && !IsHTMLEmbedElement(*node))
return;
@@ -2748,12 +2723,12 @@ void WebViewImpl::AudioStateChanged(bool is_audio_playing) {
GetPage()->GetPageScheduler()->AudioStateChanged(is_audio_playing);
}
-WebHitTestResult WebViewImpl::HitTestResultAt(const WebPoint& point) {
+WebHitTestResult WebViewImpl::HitTestResultAt(const gfx::Point& point) {
return CoreHitTestResultAt(point);
}
HitTestResult WebViewImpl::CoreHitTestResultAt(
- const WebPoint& point_in_viewport) {
+ const gfx::Point& point_in_viewport) {
// TODO(crbug.com/843128): When we do async hit-testing, we might try to do
// hit-testing when the local main frame is not valid anymore. Look into if we
// can avoid getting here earlier in the pipeline.
@@ -2764,7 +2739,7 @@ HitTestResult WebViewImpl::CoreHitTestResultAt(
MainFrameImpl()->GetFrame()->GetDocument()->Lifecycle());
LocalFrameView* view = MainFrameImpl()->GetFrameView();
LayoutPoint point_in_root_frame =
- view->ViewportToFrame(LayoutPoint(point_in_viewport));
+ view->ViewportToFrame(LayoutPoint(IntPoint(point_in_viewport)));
return HitTestResultForRootFramePos(point_in_root_frame);
}
@@ -2854,10 +2829,6 @@ void WebViewImpl::ShowContextMenu(WebMenuSourceType source_type) {
WebURL WebViewImpl::GetURLForDebugTrace() {
WebFrame* main_frame = MainFrame();
- // TODO(crbug.com/896836): Avoid a crash in minimal way for merge. But we'll
- // avoid it properly in a followup.
- if (!main_frame)
- return {};
if (main_frame->IsWebLocalFrame())
return main_frame->ToWebLocalFrame()->GetDocument().Url();
return {};
@@ -3105,7 +3076,7 @@ HitTestResult WebViewImpl::HitTestResultForRootFramePos(
}
WebHitTestResult WebViewImpl::HitTestResultForTap(
- const WebPoint& tap_point_window_pos,
+ const gfx::Point& tap_point_window_pos,
const WebSize& tap_area) {
if (!page_->MainFrame()->IsLocalFrame())
return HitTestResult();
@@ -3114,7 +3085,7 @@ WebHitTestResult WebViewImpl::HitTestResultForTap(
WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers,
WTF::CurrentTimeTicks(), kWebGestureDeviceTouchscreen);
// GestureTap is only ever from a touchscreen.
- tap_event.SetPositionInWidget(FloatPoint(tap_point_window_pos));
+ tap_event.SetPositionInWidget(FloatPoint(IntPoint(tap_point_window_pos)));
tap_event.data.tap.tap_count = 1;
tap_event.data.tap.width = tap_area.width;
tap_event.data.tap.height = tap_area.height;
@@ -3199,12 +3170,6 @@ void WebViewImpl::SetRootGraphicsLayer(GraphicsLayer* graphics_layer) {
// We register viewport layers here since there may not be a layer
// tree view prior to this point.
RegisterViewportLayersWithCompositor();
-
- // TODO(enne): Work around page visibility changes not being
- // propagated to the WebView in some circumstances. This needs to
- // be refreshed here when setting a new root layer to avoid being
- // stuck in a presumed incorrectly invisible state.
- layer_tree_view_->SetVisible(GetPage()->IsPageVisible());
} else {
root_graphics_layer_ = nullptr;
visual_viewport_container_layer_ = nullptr;
@@ -3212,7 +3177,7 @@ void WebViewImpl::SetRootGraphicsLayer(GraphicsLayer* graphics_layer) {
// This means that we're transitioning to a new page. Suppress
// commits until Blink generates invalidations so we don't
// attempt to paint too early in the next page load.
- scoped_defer_commits_ = layer_tree_view_->DeferCommits();
+ scoped_defer_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
layer_tree_view_->ClearRootLayer();
layer_tree_view_->ClearViewportLayers();
}
@@ -3225,13 +3190,12 @@ void WebViewImpl::SetRootLayer(scoped_refptr<cc::Layer> layer) {
if (layer) {
root_layer_ = layer;
layer_tree_view_->SetRootLayer(root_layer_);
- layer_tree_view_->SetVisible(GetPage()->IsPageVisible());
} else {
root_layer_ = nullptr;
// This means that we're transitioning to a new page. Suppress
// commits until Blink generates invalidations so we don't
// attempt to paint too early in the next page load.
- scoped_defer_commits_ = layer_tree_view_->DeferCommits();
+ scoped_defer_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
layer_tree_view_->ClearRootLayer();
layer_tree_view_->ClearViewportLayers();
}
@@ -3282,7 +3246,7 @@ void WebViewImpl::SetLayerTreeView(WebLayerTreeView* layer_tree_view) {
// We don't yet have a page loaded at this point of the initialization of
// WebViewImpl, so don't allow cc to commit any frames Blink might
// try to create in the meantime.
- scoped_defer_commits_ = layer_tree_view_->DeferCommits();
+ scoped_defer_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
}
void WebViewImpl::ApplyViewportChanges(const ApplyViewportChangesArgs& args) {
@@ -3308,6 +3272,11 @@ void WebViewImpl::ApplyViewportChanges(const ApplyViewportChangesArgs& args) {
elastic_overscroll_ += FloatSize(args.elastic_overscroll_delta.x(),
args.elastic_overscroll_delta.y());
+ UpdateBrowserControlsConstraint(args.browser_controls_constraint);
+
+ if (RuntimeEnabledFeatures::NoHoverDuringScrollEnabled() &&
+ args.scroll_gesture_did_end)
+ MainFrameImpl()->GetFrame()->GetEventHandler().RecomputeMouseHoverState();
}
void WebViewImpl::RecordWheelAndTouchScrollingCount(
@@ -3344,7 +3313,8 @@ void WebViewImpl::UpdateDeviceEmulationTransform() {
// scales and fuzzy raster from the compositor, force all content to
// pick ideal raster scales.
visual_viewport_container_layer_->SetTransform(device_emulation_transform_);
- layer_tree_view_->ForceRecalculateRasterScales();
+ if (layer_tree_view_)
+ layer_tree_view_->ForceRecalculateRasterScales();
}
PageScheduler* WebViewImpl::Scheduler() const {
@@ -3357,20 +3327,13 @@ void WebViewImpl::SetVisibilityState(
bool is_initial_state) {
DCHECK(GetPage());
GetPage()->SetVisibilityState(visibility_state, is_initial_state);
-
- bool visible = visibility_state == mojom::PageVisibilityState::kVisible;
- if (layer_tree_view_ && !override_compositor_visibility_)
- layer_tree_view_->SetVisible(visible);
- GetPage()->GetPageScheduler()->SetPageVisible(visible);
+ GetPage()->GetPageScheduler()->SetPageVisible(
+ visibility_state == mojom::PageVisibilityState::kVisible);
}
-void WebViewImpl::SetCompositorVisibility(bool is_visible) {
- if (!is_visible)
- override_compositor_visibility_ = true;
- else
- override_compositor_visibility_ = false;
- if (layer_tree_view_)
- layer_tree_view_->SetVisible(is_visible);
+mojom::PageVisibilityState WebViewImpl::VisibilityState() {
+ DCHECK(GetPage());
+ return GetPage()->VisibilityState();
}
void WebViewImpl::ForceNextWebGLContextCreationToFail() {
@@ -3423,6 +3386,10 @@ void WebViewImpl::SetPageFrozen(bool frozen) {
Scheduler()->SetPageFrozen(frozen);
}
+WebWidget* WebViewImpl::MainFrameWidget() {
+ return this;
+}
+
void WebViewImpl::AddAutoplayFlags(int32_t value) {
page_->AddAutoplayFlags(value);
}
@@ -3435,8 +3402,8 @@ int32_t WebViewImpl::AutoplayFlagsForTest() {
return page_->AutoplayFlags();
}
-void WebViewImpl::DeferCommitsForTesting() {
- scoped_defer_commits_ = layer_tree_view_->DeferCommits();
+void WebViewImpl::DeferMainFrameUpdateForTesting() {
+ scoped_defer_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_view_impl.h b/chromium/third_party/blink/renderer/core/exported/web_view_impl.h
index 6ca3cc1d632..a3c6109531c 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_view_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_view_impl.h
@@ -48,6 +48,7 @@
#include "third_party/blink/public/web/web_navigation_policy.h"
#include "third_party/blink/public/web/web_page_importance_signals.h"
#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_widget.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/exported/web_page_popup_impl.h"
#include "third_party/blink/renderer/core/frame/resize_viewport_anchor.h"
@@ -69,7 +70,7 @@
namespace cc {
class Layer;
-class ScopedDeferCommits;
+class ScopedDeferMainFrameUpdate;
}
namespace blink {
@@ -95,6 +96,7 @@ class WebViewClient;
class WebWidgetClient;
class CORE_EXPORT WebViewImpl final : public WebView,
+ private WebWidget,
public RefCounted<WebViewImpl>,
public PageWidgetEventHandler {
public:
@@ -119,8 +121,11 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) override;
void BeginFrame(base::TimeTicks last_frame_time) override;
void RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time) override;
- void UpdateLifecycle(LifecycleUpdate requested_update) override;
+ void UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) override;
void UpdateAllLifecyclePhasesAndCompositeForTesting(bool do_raster) override;
+ void RequestPresentationCallbackForTesting(
+ base::OnceClosure callback) override;
void PaintContent(cc::PaintCanvas*, const WebRect&) override;
void PaintContentIgnoringCompositing(cc::PaintCanvas*,
const WebRect&) override;
@@ -197,21 +202,22 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void SetIgnoreViewportTagScaleLimits(bool) override;
WebSize ContentsPreferredMinimumSize() override;
void SetDisplayMode(WebDisplayMode) override;
+ void AnimateDoubleTapZoom(const gfx::Point&,
+ const WebRect& block_bounds) override;
void SetDeviceScaleFactor(float) override;
void SetZoomFactorForDeviceScaleFactor(float) override;
float ZoomFactorForDeviceScaleFactor() override {
return zoom_factor_for_device_scale_factor_;
};
-
void EnableAutoResizeMode(const WebSize& min_size,
const WebSize& max_size) override;
void DisableAutoResizeMode() override;
- void PerformPluginAction(const WebPluginAction&, const WebPoint&) override;
+ void PerformPluginAction(const WebPluginAction&, const gfx::Point&) override;
void AudioStateChanged(bool is_audio_playing) override;
void PausePageScheduledTasks(bool paused) override;
- WebHitTestResult HitTestResultAt(const WebPoint&) override;
- WebHitTestResult HitTestResultForTap(const WebPoint&,
+ WebHitTestResult HitTestResultAt(const gfx::Point&) override;
+ WebHitTestResult HitTestResultForTap(const gfx::Point&,
const WebSize&) override;
unsigned long CreateUniqueIdentifierForRequest() override;
void EnableDeviceEmulation(const WebDeviceEmulationParams&) override;
@@ -229,8 +235,10 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void SetShowDebugBorders(bool);
void SetShowFPSCounter(bool) override;
void SetShowScrollBottleneckRects(bool) override;
+ void SetShowHitTestBorders(bool);
void AcceptLanguagesChanged() override;
void SetPageFrozen(bool frozen) override;
+ WebWidget* MainFrameWidget() override;
void DidUpdateFullscreenSize();
@@ -239,7 +247,7 @@ class CORE_EXPORT WebViewImpl final : public WebView,
float ClampPageScaleFactorToLimits(float) const;
void ResetScaleStateImmediately();
- HitTestResult CoreHitTestResultAt(const WebPoint&);
+ HitTestResult CoreHitTestResultAt(const gfx::Point&);
void InvalidateRect(const IntRect&);
void SetBaseBackgroundColor(SkColor);
@@ -339,6 +347,7 @@ class CORE_EXPORT WebViewImpl final : public WebView,
PageScheduler* Scheduler() const override;
void SetVisibilityState(mojom::PageVisibilityState, bool) override;
+ mojom::PageVisibilityState VisibilityState() override;
bool HasOpenedPopup() const { return page_popup_.get(); }
@@ -349,17 +358,16 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void FullFramePluginZoomLevelChanged(double zoom_level);
void ComputeScaleAndScrollForBlockRect(
- const WebPoint& hit_point,
+ const gfx::Point& hit_point,
const WebRect& block_rect,
float padding,
float default_scale_when_already_legible,
float& scale,
- WebPoint& scroll);
+ IntPoint& scroll);
Node* BestTapNode(const GestureEventWithHitTestResults& targeted_tap_event);
void EnableTapHighlightAtPoint(
const GestureEventWithHitTestResults& targeted_tap_event);
void EnableTapHighlights(HeapVector<Member<Node>>&);
- void AnimateDoubleTapZoom(const IntPoint&);
void EnableFakePageScaleAnimationForTesting(bool);
bool FakeDoubleTapAnimationPendingForTesting() const {
@@ -375,7 +383,7 @@ class CORE_EXPORT WebViewImpl final : public WebView,
return fake_page_scale_animation_use_anchor_;
}
- void EnterFullscreen(LocalFrame&, const FullscreenOptions&);
+ void EnterFullscreen(LocalFrame&, const FullscreenOptions*);
void ExitFullscreen(LocalFrame&);
void FullscreenElementChanged(Element* old_element, Element* new_element);
@@ -388,9 +396,6 @@ class CORE_EXPORT WebViewImpl final : public WebView,
WebSettingsImpl* SettingsImpl();
- // Returns the bounding box of the block type node touched by the WebPoint.
- WebRect ComputeBlockBound(const WebPoint&, bool ignore_clipping);
-
WebLayerTreeView* LayerTreeView() const { return layer_tree_view_; }
CompositorAnimationHost* AnimationHost() const {
return animation_host_.get();
@@ -400,10 +405,6 @@ class CORE_EXPORT WebViewImpl final : public WebView,
return matches_heuristics_for_gpu_rasterization_;
}
- void UpdateBrowserControlsState(cc::BrowserControlsState constraint,
- cc::BrowserControlsState current,
- bool animate) override;
-
BrowserControls& GetBrowserControls();
// Called anytime browser controls layout height or content offset have
// changed.
@@ -445,9 +446,9 @@ class CORE_EXPORT WebViewImpl final : public WebView,
const IntRect& caret_bounds_in_document,
bool zoom_into_legible_scale);
- void StopDeferringCommits() { scoped_defer_commits_.reset(); }
+ void StopDeferringCommits() { scoped_defer_main_frame_update_.reset(); }
- void DeferCommitsForTesting();
+ void DeferMainFrameUpdateForTesting();
private:
FRIEND_TEST_ALL_PREFIXES(WebFrameTest, DivScrollIntoEditableTest);
@@ -465,15 +466,12 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void RefreshPageScaleFactor();
IntSize ContentsSize() const;
+ void UpdateBrowserControlsConstraint(cc::BrowserControlsState constraint);
void UpdateICBAndResizeViewport();
void ResizeViewWhileAnchored(float top_controls_height,
float bottom_controls_height,
bool browser_controls_shrink_layout);
- // Overrides the compositor visibility. See the description of
- // m_overrideCompositorVisibility for more details.
- void SetCompositorVisibility(bool);
-
// TODO(lfg): Remove once WebViewFrameWidget is deleted.
void ScheduleAnimationForWidget();
@@ -632,6 +630,21 @@ class CORE_EXPORT WebViewImpl final : public WebView,
Persistent<Node> mouse_capture_node_;
scoped_refptr<UserGestureToken> mouse_capture_gesture_token_;
+ // WebViews, and WebWidgets, are used to host a Page and present it via a
+ // WebLayerTreeView compositor. The WidgetClient() provides compositing
+ // support for the WebView.
+ // In some cases, a WidgetClient() is not provided, or it informs us that
+ // it won't be presenting content via a compositor.
+ // When not compositing, the |layer_tree_view_| will be null, otherwise it
+ // would be non-null until closing.
+ //
+ // TODO(dcheng): All WebViewImpls should have an associated LayerTreeView,
+ // but for various reasons, that's not the case... WebView plugin, printing,
+ // workers, and tests don't use a compositor in their WebViews. Sometimes
+ // they avoid the compositor by using a null client, and sometimes by having
+ // the client return a null compositor. We should make things more consistent
+ // and clear.
+ const bool does_composite_;
WebLayerTreeView* layer_tree_view_;
std::unique_ptr<CompositorAnimationHost> animation_host_;
@@ -670,15 +683,10 @@ class CORE_EXPORT WebViewImpl final : public WebView,
WebPageImportanceSignals page_importance_signals_;
- // TODO(lfg): This is used in order to disable compositor visibility while
- // the page is still visible. This is needed until the WebView and WebWidget
- // split is complete, since in out-of-process iframes the page can be
- // visible, but the WebView should not be used as a widget.
- bool override_compositor_visibility_;
-
// We defer commits when transitioning to a new page. ChromeClientImpl calls
// StopDeferringCommits() to release this when a new page is loaded.
- std::unique_ptr<cc::ScopedDeferCommits> scoped_defer_commits_;
+ std::unique_ptr<cc::ScopedDeferMainFrameUpdate>
+ scoped_defer_main_frame_update_;
Persistent<ResizeViewportAnchor> resize_viewport_anchor_;
};
diff --git a/chromium/third_party/blink/renderer/core/exported/web_view_test.cc b/chromium/third_party/blink/renderer/core/exported/web_view_test.cc
index df548f3fffb..0776bb4f4c1 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_view_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -34,12 +34,14 @@
#include <memory>
#include <string>
+#include "base/time/time.h"
#include "build/build_config.h"
#include "cc/trees/layer_tree_host.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/common/manifest/web_display_mode.h"
#include "third_party/blink/public/mojom/page/page_visibility_state.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
@@ -81,7 +83,6 @@
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/ime/input_method_controller.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h"
-#include "third_party/blink/renderer/core/exported/fake_web_plugin.h"
#include "third_party/blink/renderer/core/exported/web_settings_impl.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
#include "third_party/blink/renderer/core/frame/event_handler_registry.h"
@@ -111,6 +112,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_painter.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
+#include "third_party/blink/renderer/core/testing/fake_web_plugin.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
@@ -140,9 +142,9 @@
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#endif // BUILDFLAG(ENABLE_UNHANDLED_TAP)
-using blink::FrameTestHelpers::LoadFrame;
-using blink::URLTestHelpers::ToKURL;
-using blink::URLTestHelpers::RegisterMockedURLLoad;
+using blink::frame_test_helpers::LoadFrame;
+using blink::url_test_helpers::ToKURL;
+using blink::url_test_helpers::RegisterMockedURLLoad;
using blink::test::RunPendingTasks;
namespace blink {
@@ -179,7 +181,7 @@ class TestData {
WebViewImpl* web_view_;
};
-class AutoResizeWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class AutoResizeWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
// WebViewClient methods
void DidAutoResize(const WebSize& new_size) override {
@@ -193,7 +195,7 @@ class AutoResizeWebViewClient : public FrameTestHelpers::TestWebViewClient {
TestData test_data_;
};
-class TapHandlingWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class TapHandlingWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
// WebViewClient methods
void DidHandleGestureEvent(const WebGestureEvent& event,
@@ -227,7 +229,7 @@ class TapHandlingWebViewClient : public FrameTestHelpers::TestWebViewClient {
};
class DateTimeChooserWebViewClient
- : public FrameTestHelpers::TestWebViewClient {
+ : public frame_test_helpers::TestWebViewClient {
public:
WebDateTimeChooserCompletion* ChooserCompletion() {
return chooser_completion_;
@@ -263,11 +265,12 @@ class WebViewTest : public testing::Test {
web_view_helper_.GetLayerTreeView();
layer_tree_view->SetViewportSizeAndScale(
static_cast<gfx::Size>(size), /*device_scale_factor=*/1.f,
- layer_tree_view->layer_tree_host()->local_surface_id_from_parent());
+ layer_tree_view->layer_tree_host()
+ ->local_surface_id_allocation_from_parent());
}
std::string RegisterMockedHttpURLLoad(const std::string& file_name) {
- return URLTestHelpers::RegisterMockedURLLoadFromBase(
+ return url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name))
.GetString()
@@ -291,19 +294,26 @@ class WebViewTest : public testing::Test {
bool TapElementById(WebInputEvent::Type, const WebString& id);
IntSize PrintICBSizeFromPageSize(const FloatSize& page_size);
+ void UpdateAllLifecyclePhases() {
+ web_view_helper_.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
std::string base_url_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
static bool HitTestIsContentEditable(WebView* view, int x, int y) {
- WebPoint hit_point(x, y);
- WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point);
+ gfx::Point hit_point(x, y);
+ WebHitTestResult hit_test_result =
+ view->MainFrameWidget()->HitTestResultAt(hit_point);
return hit_test_result.IsContentEditable();
}
static std::string HitTestElementId(WebView* view, int x, int y) {
- WebPoint hit_point(x, y);
- WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point);
+ gfx::Point hit_point(x, y);
+ WebHitTestResult hit_test_result =
+ view->MainFrameWidget()->HitTestResultAt(hit_point);
return hit_test_result.GetNode().To<WebElement>().GetAttribute("id").Utf8();
}
@@ -312,7 +322,7 @@ TEST_F(WebViewTest, HitTestVideo) {
// element itself as opposed to its child elements.
std::string url = RegisterMockedHttpURLLoad("video_200x200.html");
WebView* web_view = web_view_helper_.InitializeAndLoad(url);
- web_view->Resize(WebSize(200, 200));
+ web_view->MainFrameWidget()->Resize(WebSize(200, 200));
// Center of video.
EXPECT_EQ("video", HitTestElementId(web_view, 100, 100));
@@ -328,7 +338,7 @@ TEST_F(WebViewTest, HitTestContentEditableImageMaps) {
std::string url =
RegisterMockedHttpURLLoad("content-editable-image-maps.html");
WebView* web_view = web_view_helper_.InitializeAndLoad(url);
- web_view->Resize(WebSize(500, 500));
+ web_view->MainFrameWidget()->Resize(WebSize(500, 500));
EXPECT_EQ("areaANotEditable", HitTestElementId(web_view, 25, 25));
EXPECT_FALSE(HitTestIsContentEditable(web_view, 25, 25));
@@ -352,21 +362,23 @@ TEST_F(WebViewTest, HitTestContentEditableImageMaps) {
}
static std::string HitTestAbsoluteUrl(WebView* view, int x, int y) {
- WebPoint hit_point(x, y);
- WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point);
+ gfx::Point hit_point(x, y);
+ WebHitTestResult hit_test_result =
+ view->MainFrameWidget()->HitTestResultAt(hit_point);
return hit_test_result.AbsoluteImageURL().GetString().Utf8();
}
static WebElement HitTestUrlElement(WebView* view, int x, int y) {
- WebPoint hit_point(x, y);
- WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point);
+ gfx::Point hit_point(x, y);
+ WebHitTestResult hit_test_result =
+ view->MainFrameWidget()->HitTestResultAt(hit_point);
return hit_test_result.UrlElement();
}
TEST_F(WebViewTest, ImageMapUrls) {
std::string url = RegisterMockedHttpURLLoad("image-map.html");
WebView* web_view = web_view_helper_.InitializeAndLoad(url);
- web_view->Resize(WebSize(400, 400));
+ web_view->MainFrameWidget()->Resize(WebSize(400, 400));
std::string image_url =
"data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=";
@@ -382,7 +394,7 @@ TEST_F(WebViewTest, ImageMapUrls) {
}
TEST_F(WebViewTest, BrokenImage) {
- URLTestHelpers::RegisterMockedErrorURLLoad(
+ url_test_helpers::RegisterMockedErrorURLLoad(
KURL(ToKURL(base_url_), "non_existent.png"));
std::string url = RegisterMockedHttpURLLoad("image-broken.html");
@@ -399,7 +411,7 @@ TEST_F(WebViewTest, BrokenImage) {
}
TEST_F(WebViewTest, BrokenInputImage) {
- URLTestHelpers::RegisterMockedErrorURLLoad(
+ url_test_helpers::RegisterMockedErrorURLLoad(
KURL(ToKURL(base_url_), "non_existent.png"));
std::string url = RegisterMockedHttpURLLoad("input-image-broken.html");
@@ -425,19 +437,20 @@ TEST_F(WebViewTest, SetBaseBackgroundColor) {
web_view->SetBaseBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(SK_ColorBLUE, web_view->BackgroundColor());
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><head><style>body "
- "{background-color:#227788}</style></head></"
- "html>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(
+ web_view->MainFrameImpl(),
+ "<html><head><style>body "
+ "{background-color:#227788}</style></head></"
+ "html>",
+ base_url);
EXPECT_EQ(kDarkCyan, web_view->BackgroundColor());
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><head><style>body "
- "{background-color:rgba(255,0,0,0.5)}</"
- "style></head></html>",
- base_url);
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><head><style>body "
+ "{background-color:rgba(255,0,0,0.5)}</"
+ "style></head></html>",
+ base_url);
// Expected: red (50% alpha) blended atop base of SK_ColorBLUE.
EXPECT_EQ(0xFF80007F, web_view->BackgroundColor());
@@ -446,11 +459,11 @@ TEST_F(WebViewTest, SetBaseBackgroundColor) {
EXPECT_EQ(0xBFE93A31, web_view->BackgroundColor());
web_view->SetBaseBackgroundColor(SK_ColorTRANSPARENT);
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><head><style>body "
- "{background-color:transparent}</style></"
- "head></html>",
- base_url);
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><head><style>body "
+ "{background-color:transparent}</style></"
+ "head></html>",
+ base_url);
// Expected: transparent on top of transparent will still be transparent.
EXPECT_EQ(SK_ColorTRANSPARENT, web_view->BackgroundColor());
@@ -473,7 +486,7 @@ TEST_F(WebViewTest, SetBaseBackgroundColor) {
TEST_F(WebViewTest, SetBaseBackgroundColorBeforeMainFrame) {
// Note: this test doesn't use WebViewHelper since it intentionally runs
// initialization code between WebView and WebLocalFrame creation.
- FrameTestHelpers::TestWebViewClient web_view_client;
+ frame_test_helpers::TestWebViewClient web_view_client;
WebViewImpl* web_view = static_cast<WebViewImpl*>(
WebView::Create(&web_view_client, &web_view_client,
mojom::PageVisibilityState::kVisible, nullptr));
@@ -482,7 +495,7 @@ TEST_F(WebViewTest, SetBaseBackgroundColorBeforeMainFrame) {
// background color.
web_view->SetBaseBackgroundColor(SK_ColorBLUE);
EXPECT_EQ(SK_ColorBLUE, web_view->BackgroundColor());
- FrameTestHelpers::TestWebFrameClient web_frame_client;
+ frame_test_helpers::TestWebFrameClient web_frame_client;
WebLocalFrame* frame = WebLocalFrame::CreateMainFrame(
web_view, &web_frame_client, nullptr, nullptr);
web_frame_client.Bind(frame);
@@ -501,7 +514,7 @@ TEST_F(WebViewTest, SetBaseBackgroundColorAndBlendWithExistingContent) {
web_view->SetBaseBackgroundColor(kAlphaGreen);
web_view->GetSettings()->SetShouldClearDocumentBackground(false);
web_view->Resize(WebSize(kWidth, kHeight));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Set canvas background to red with alpha.
SkBitmap bitmap;
@@ -515,7 +528,7 @@ TEST_F(WebViewTest, SetBaseBackgroundColorAndBlendWithExistingContent) {
// would.
LocalFrameView* view = web_view_helper_.LocalMainFrame()->GetFrameView();
PaintLayer* root_layer = view->GetLayoutView()->Layer();
- LayoutRect paint_rect(0, 0, kWidth, kHeight);
+ CullRect paint_rect(IntRect(0, 0, kWidth, kHeight));
PaintLayerPaintingInfo painting_info(root_layer, paint_rect,
kGlobalPaintNormalPhase, LayoutSize());
@@ -570,8 +583,8 @@ TEST_F(WebViewTest, DocumentHasFocus) {
WebViewImpl* web_view = web_view_helper_.Initialize();
web_view->SetFocus(true);
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(
web_view->MainFrameImpl(),
"<input id=input></input>"
"<div id=log></div>"
@@ -624,33 +637,35 @@ TEST_F(WebViewTest, ActiveState) {
TEST_F(WebViewTest, HitTestResultAtWithPageScale) {
std::string url = base_url_ + "specify_size.html?" + "50px" + ":" + "50px";
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url), test::CoreTestDataPath("specify_size.html"));
WebView* web_view = web_view_helper_.InitializeAndLoad(url);
- web_view->Resize(WebSize(100, 100));
- WebPoint hit_point(75, 75);
+ web_view->MainFrameWidget()->Resize(WebSize(100, 100));
+ gfx::Point hit_point(75, 75);
// Image is at top left quandrant, so should not hit it.
- WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point);
+ WebHitTestResult negative_result =
+ web_view->MainFrameWidget()->HitTestResultAt(hit_point);
EXPECT_FALSE(
negative_result.GetNode().To<WebElement>().HasHTMLTagName("img"));
negative_result.Reset();
// Scale page up 2x so image should occupy the whole viewport.
web_view->SetPageScaleFactor(2.0f);
- WebHitTestResult positive_result = web_view->HitTestResultAt(hit_point);
+ WebHitTestResult positive_result =
+ web_view->MainFrameWidget()->HitTestResultAt(hit_point);
EXPECT_TRUE(positive_result.GetNode().To<WebElement>().HasHTMLTagName("img"));
positive_result.Reset();
}
TEST_F(WebViewTest, HitTestResultAtWithPageScaleAndPan) {
std::string url = base_url_ + "specify_size.html?" + "50px" + ":" + "50px";
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url), test::CoreTestDataPath("specify_size.html"));
WebViewImpl* web_view = web_view_helper_.Initialize();
LoadFrame(web_view->MainFrameImpl(), url);
web_view->Resize(WebSize(100, 100));
- WebPoint hit_point(75, 75);
+ gfx::Point hit_point(75, 75);
// Image is at top left quandrant, so should not hit it.
WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point);
@@ -675,11 +690,12 @@ TEST_F(WebViewTest, HitTestResultAtWithPageScaleAndPan) {
TEST_F(WebViewTest, HitTestResultForTapWithTapArea) {
std::string url = RegisterMockedHttpURLLoad("hit_test.html");
WebView* web_view = web_view_helper_.InitializeAndLoad(url);
- web_view->Resize(WebSize(100, 100));
- WebPoint hit_point(55, 55);
+ web_view->MainFrameWidget()->Resize(WebSize(100, 100));
+ gfx::Point hit_point(55, 55);
// Image is at top left quandrant, so should not hit it.
- WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point);
+ WebHitTestResult negative_result =
+ web_view->MainFrameWidget()->HitTestResultAt(hit_point);
EXPECT_FALSE(
negative_result.GetNode().To<WebElement>().HasHTMLTagName("img"));
negative_result.Reset();
@@ -692,7 +708,7 @@ TEST_F(WebViewTest, HitTestResultForTapWithTapArea) {
positive_result.Reset();
// Move the hit point the image is just outside the tapped area now.
- hit_point = WebPoint(61, 61);
+ hit_point = gfx::Point(61, 61);
WebHitTestResult negative_result2 =
web_view->HitTestResultForTap(hit_point, tap_area);
EXPECT_FALSE(
@@ -705,7 +721,7 @@ TEST_F(WebViewTest, HitTestResultForTapWithTapAreaPageScaleAndPan) {
WebViewImpl* web_view = web_view_helper_.Initialize();
LoadFrame(web_view->MainFrameImpl(), url);
web_view->Resize(WebSize(100, 100));
- WebPoint hit_point(55, 55);
+ gfx::Point hit_point(55, 55);
// Image is at top left quandrant, so should not hit it.
WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point);
@@ -742,7 +758,7 @@ void WebViewTest::TestAutoResize(
AutoResizeWebViewClient client;
std::string url =
base_url_ + "specify_size.html?" + page_width + ":" + page_height;
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url), test::CoreTestDataPath("specify_size.html"));
WebViewImpl* web_view =
web_view_helper_.InitializeAndLoad(url, nullptr, &client);
@@ -878,17 +894,17 @@ TEST_F(WebViewTest, TextInputType) {
}
TEST_F(WebViewTest, TextInputInfoUpdateStyleAndLayout) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
// Here, we need to construct a document that has a special property:
// Adding id="foo" to the <path> element will trigger creation of an SVG
// instance tree for the use <use> element.
// This is significant, because SVG instance trees are actually created lazily
// during Document::updateStyleAndLayout code, thus incrementing the DOM tree
// version and freaking out the EphemeralRange (invalidating it).
- FrameTestHelpers::LoadHTMLString(
+ frame_test_helpers::LoadHTMLString(
web_view_impl->MainFrameImpl(),
"<svg height='100%' version='1.1' viewBox='0 0 14 14' width='100%'>"
"<use xmlns:xlink='http://www.w3.org/1999/xlink' xlink:href='#foo'></use>"
@@ -949,7 +965,7 @@ TEST_F(WebViewTest, InputMode) {
TEST_F(WebViewTest, TextInputInfoWithReplacedElements) {
std::string url = RegisterMockedHttpURLLoad("div_with_image.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL("http://www.test.com/foo.png"),
test::CoreTestDataPath("white-1x1.png"));
WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(url);
@@ -1015,7 +1031,7 @@ TEST_F(WebViewTest, FinishComposingTextDoesNotAssert) {
// Do arbitrary change to make layout dirty.
Document& document = *web_view->MainFrameImpl()->GetFrame()->GetDocument();
- Element* br = document.CreateRawElement(HTMLNames::brTag);
+ Element* br = document.CreateRawElement(html_names::kBrTag);
document.body()->AppendChild(br);
// Should not hit assertion when calling
@@ -1032,7 +1048,7 @@ TEST_F(WebViewTest, LongPressOutsideInputShouldNotSelectPlaceholderText) {
web_view_helper_.InitializeAndLoad(base_url_ + "input_placeholder.html");
web_view->SetInitialFocus(false);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString input_id = WebString::FromUTF8("input");
@@ -2239,7 +2255,7 @@ TEST_F(WebViewTest, HistoryResetScrollAndScaleState) {
WebViewImpl* web_view_impl =
web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html");
web_view_impl->Resize(WebSize(100, 150));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().width);
EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height);
@@ -2284,7 +2300,8 @@ TEST_F(WebViewTest, BackForwardRestoreScroll) {
WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(
base_url_ + "back_forward_restore_scroll.html");
web_view_impl->Resize(WebSize(640, 480));
- web_view_impl->UpdateAllLifecyclePhases();
+ web_view_impl->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
// Emulate a user scroll
web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(0, 900));
@@ -2337,7 +2354,7 @@ TEST_F(WebViewTest, FullscreenNoResetScroll) {
WebViewImpl* web_view_impl =
web_view_helper_.InitializeAndLoad(base_url_ + "fullscreen_style.html");
web_view_impl->Resize(WebSize(800, 600));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Scroll the page down.
web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(0, 2000));
@@ -2350,7 +2367,7 @@ TEST_F(WebViewTest, FullscreenNoResetScroll) {
LocalFrame::NotifyUserActivation(frame);
Fullscreen::RequestFullscreen(*element);
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Assert the scroll position on the document element doesn't change.
ASSERT_EQ(2000, web_view_impl->MainFrameImpl()->GetScrollOffset().height);
@@ -2358,7 +2375,7 @@ TEST_F(WebViewTest, FullscreenNoResetScroll) {
web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(0, 2100));
web_view_impl->DidExitFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(2100, web_view_impl->MainFrameImpl()->GetScrollOffset().height);
}
@@ -2369,7 +2386,7 @@ TEST_F(WebViewTest, FullscreenBackgroundColor) {
WebViewImpl* web_view_impl =
web_view_helper_.InitializeAndLoad(base_url_ + "fullscreen_style.html");
web_view_impl->Resize(WebSize(800, 600));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(SK_ColorWHITE, web_view_impl->BackgroundColor());
// Enter fullscreen.
@@ -2380,12 +2397,12 @@ TEST_F(WebViewTest, FullscreenBackgroundColor) {
LocalFrame::NotifyUserActivation(frame);
Fullscreen::RequestFullscreen(*element);
web_view_impl->DidEnterFullscreen();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(SK_ColorYELLOW, web_view_impl->BackgroundColor());
}
-class PrintWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class PrintWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
PrintWebViewClient() : print_called_(false) {}
@@ -2427,7 +2444,7 @@ static void DragAndDropURL(WebViewImpl* web_view, const std::string& url) {
widget->DragTargetDragEnter(drag_data, client_point, screen_point,
kWebDragOperationCopy, 0);
widget->DragTargetDrop(drag_data, client_point, screen_point, 0);
- FrameTestHelpers::PumpPendingRequestsForFrameToLoad(
+ frame_test_helpers::PumpPendingRequestsForFrameToLoad(
web_view->MainFrameImpl());
}
@@ -2516,14 +2533,14 @@ TEST_F(WebViewTest, ClientTapHandling) {
WebInputEvent::GetStaticTimeStampForTests(),
kWebGestureDeviceTouchscreen);
event.SetPositionInWidget(WebFloatPoint(3, 8));
- web_view->HandleInputEvent(WebCoalescedInputEvent(event));
+ web_view->MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(event));
RunPendingTasks();
EXPECT_EQ(3, client.TapX());
EXPECT_EQ(8, client.TapY());
client.Reset();
event.SetType(WebInputEvent::kGestureLongPress);
event.SetPositionInWidget(WebFloatPoint(25, 7));
- web_view->HandleInputEvent(WebCoalescedInputEvent(event));
+ web_view->MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(event));
RunPendingTasks();
EXPECT_EQ(25, client.LongpressX());
EXPECT_EQ(7, client.LongpressY());
@@ -2537,8 +2554,8 @@ TEST_F(WebViewTest, ClientTapHandlingNullWebViewClient) {
// internal WebViewClient on demand if the supplied WebViewClient is null.
WebViewImpl* web_view = static_cast<WebViewImpl*>(WebView::Create(
nullptr, nullptr, mojom::PageVisibilityState::kVisible, nullptr));
- FrameTestHelpers::TestWebFrameClient web_frame_client;
- FrameTestHelpers::TestWebWidgetClient web_widget_client;
+ frame_test_helpers::TestWebFrameClient web_frame_client;
+ frame_test_helpers::TestWebWidgetClient web_widget_client;
WebLocalFrame* local_frame = WebLocalFrame::CreateMainFrame(
web_view, &web_frame_client, nullptr, nullptr);
web_frame_client.Bind(local_frame);
@@ -2560,7 +2577,7 @@ TEST_F(WebViewTest, LongPressEmptyDiv) {
base_url_ + "long_press_empty_div.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2580,7 +2597,7 @@ TEST_F(WebViewTest, LongPressEmptyDivAlwaysShow) {
base_url_ + "long_press_empty_div.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(true);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2600,7 +2617,7 @@ TEST_F(WebViewTest, LongPressObject) {
web_view_helper_.InitializeAndLoad(base_url_ + "long_press_object.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(true);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2624,7 +2641,7 @@ TEST_F(WebViewTest, LongPressObjectFallback) {
base_url_ + "long_press_object_fallback.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(true);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2648,7 +2665,7 @@ TEST_F(WebViewTest, LongPressImage) {
web_view_helper_.InitializeAndLoad(base_url_ + "long_press_image.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2668,7 +2685,7 @@ TEST_F(WebViewTest, LongPressVideo) {
web_view_helper_.InitializeAndLoad(base_url_ + "long_press_video.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2688,7 +2705,7 @@ TEST_F(WebViewTest, LongPressLink) {
web_view_helper_.InitializeAndLoad(base_url_ + "long_press_link.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2705,7 +2722,7 @@ TEST_F(WebViewTest, LongPressLink) {
TEST_F(WebViewTest, TouchCancelOnStartDragging) {
RegisterMockedHttpURLLoad("long_press_draggable_div.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL("http://www.test.com/foo.png"),
test::CoreTestDataPath("white-1x1.png"));
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
@@ -2713,7 +2730,7 @@ TEST_F(WebViewTest, TouchCancelOnStartDragging) {
web_view->SettingsImpl()->SetTouchDragDropEnabled(true);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebPointerEvent pointer_down(
@@ -2745,7 +2762,7 @@ TEST_F(WebViewTest, TouchCancelOnStartDragging) {
TEST_F(WebViewTest, showContextMenuOnLongPressingLinks) {
RegisterMockedHttpURLLoad("long_press_links_and_images.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL("http://www.test.com/foo.png"),
test::CoreTestDataPath("white-1x1.png"));
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
@@ -2753,7 +2770,7 @@ TEST_F(WebViewTest, showContextMenuOnLongPressingLinks) {
web_view->SettingsImpl()->SetTouchDragDropEnabled(true);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString anchor_tag_id = WebString::FromUTF8("anchorTag");
@@ -2775,7 +2792,7 @@ TEST_F(WebViewTest, LongPressEmptyEditableSelection) {
base_url_ + "long_press_empty_editable_selection.html");
web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false);
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2794,7 +2811,7 @@ TEST_F(WebViewTest, LongPressEmptyNonEditableSelection) {
WebViewImpl* web_view =
web_view_helper_.InitializeAndLoad(base_url_ + "long_press_image.html");
web_view->Resize(WebSize(500, 500));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebGestureEvent event(WebInputEvent::kGestureLongPress,
@@ -2815,7 +2832,7 @@ TEST_F(WebViewTest, LongPressSelection) {
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + "longpress_selection.html");
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString target = WebString::FromUTF8("target");
@@ -2835,7 +2852,7 @@ TEST_F(WebViewTest, FinishComposingTextDoesNotDismissHandles) {
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + "longpress_selection.html");
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString target = WebString::FromUTF8("target");
@@ -2871,7 +2888,7 @@ TEST_F(WebViewTest, TouchDoesntSelectEmptyTextarea) {
WebViewImpl* web_view =
web_view_helper_.InitializeAndLoad(base_url_ + "longpress_textarea.html");
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString blanklinestextbox = WebString::FromUTF8("blanklinestextbox");
@@ -2914,7 +2931,7 @@ TEST_F(WebViewTest, LongPressImageTextarea) {
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + "longpress_image_contenteditable.html");
web_view->Resize(WebSize(500, 300));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString image = WebString::FromUTF8("purpleimage");
@@ -2934,7 +2951,7 @@ TEST_F(WebViewTest, BlinkCaretAfterLongPress) {
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + "blink_caret_on_typing_after_long_press.html");
web_view->Resize(WebSize(640, 480));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebString target = WebString::FromUTF8("target");
@@ -2969,7 +2986,7 @@ TEST_F(WebViewTest, BlinkCaretOnClosingContextMenu) {
EXPECT_TRUE(main_frame->GetFrame()->Selection().IsCaretBlinkingSuspended());
// Caret blinking is still suspended after showing context menu.
- web_view->GetWidget()->ShowContextMenu(kMenuSourceMouse);
+ web_view->MainFrameWidget()->ShowContextMenu(kMenuSourceMouse);
EXPECT_TRUE(main_frame->GetFrame()->Selection().IsCaretBlinkingSuspended());
// Caret blinking will be resumed only after context menu is closed.
@@ -2983,7 +3000,7 @@ TEST_F(WebViewTest, SelectionOnReadOnlyInput) {
WebViewImpl* web_view =
web_view_helper_.InitializeAndLoad(base_url_ + "selection_readonly.html");
web_view->Resize(WebSize(640, 480));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
std::string test_word = "This text should be selected.";
@@ -3005,7 +3022,7 @@ TEST_F(WebViewTest, KeyDownScrollsHandled) {
WebViewImpl* web_view =
web_view_helper_.InitializeAndLoad(base_url_ + "content-width-1000.html");
web_view->Resize(WebSize(100, 100));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown,
@@ -3093,7 +3110,7 @@ TEST_F(WebViewTest, KeyDownScrollsHandled) {
}
class MiddleClickAutoscrollWebWidgetClient
- : public FrameTestHelpers::TestWebWidgetClient {
+ : public frame_test_helpers::TestWebWidgetClient {
public:
// WebWidgetClient methods
@@ -3115,7 +3132,7 @@ TEST_F(WebViewTest, MiddleClickAutoscrollCursor) {
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + "content-width-1000.html", nullptr, nullptr, &client);
web_view->Resize(WebSize(100, 100));
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
RunPendingTasks();
WebMouseEvent mouse_event(WebInputEvent::kMouseDown,
@@ -3157,7 +3174,7 @@ static void ConfigueCompositingWebView(WebSettings* settings) {
}
TEST_F(WebViewTest, ShowPressOnTransformedLink) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.Initialize(
nullptr, nullptr, nullptr, &ConfigueCompositingWebView);
@@ -3165,8 +3182,8 @@ TEST_F(WebViewTest, ShowPressOnTransformedLink) {
int page_height = 480;
web_view_impl->Resize(WebSize(page_width, page_height));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(
web_view_impl->MainFrameImpl(),
"<a href='http://www.test.com' style='position: absolute; left: 20px; "
"top: 20px; width: 200px; transform:translateZ(0);'>A link to "
@@ -3373,7 +3390,7 @@ TEST_F(WebViewTest,
frame->SetAutofillClient(nullptr);
}
-class ViewCreatingWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class ViewCreatingWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
ViewCreatingWebViewClient() : did_focus_called_(false) {}
@@ -3384,7 +3401,8 @@ class ViewCreatingWebViewClient : public FrameTestHelpers::TestWebViewClient {
const WebString& name,
WebNavigationPolicy,
bool,
- WebSandboxFlags) override {
+ WebSandboxFlags,
+ const SessionStorageNamespaceId&) override {
return web_view_helper_.InitializeWithOpener(opener);
}
@@ -3395,23 +3413,23 @@ class ViewCreatingWebViewClient : public FrameTestHelpers::TestWebViewClient {
WebView* CreatedWebView() const { return web_view_helper_.GetWebView(); }
private:
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
bool did_focus_called_;
};
TEST_F(WebViewTest, DoNotFocusCurrentFrameOnNavigateFromLocalFrame) {
ViewCreatingWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.Initialize(nullptr, &client);
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(
web_view_impl->MainFrameImpl(),
"<html><body><iframe src=\"about:blank\"></iframe></body></html>",
base_url);
// Make a request from a local frame.
- WebURLRequest web_url_request_with_target_start;
+ WebURLRequest web_url_request_with_target_start(KURL("about:blank"));
LocalFrame* local_frame =
ToWebLocalFrameImpl(web_view_impl->MainFrame()->FirstChild())->GetFrame();
FrameLoadRequest request_with_target_start(
@@ -3425,13 +3443,13 @@ TEST_F(WebViewTest, DoNotFocusCurrentFrameOnNavigateFromLocalFrame) {
TEST_F(WebViewTest, FocusExistingFrameOnNavigate) {
ViewCreatingWebViewClient client;
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl = web_view_helper.Initialize(nullptr, &client);
WebLocalFrameImpl* frame = web_view_impl->MainFrameImpl();
frame->SetName("_start");
// Make a request that will open a new window
- WebURLRequest web_url_request;
+ WebURLRequest web_url_request(KURL("about:blank"));
FrameLoadRequest request(nullptr, web_url_request.ToResourceRequest(),
"_blank");
ToLocalFrame(web_view_impl->GetPage()->MainFrame())
@@ -3442,7 +3460,7 @@ TEST_F(WebViewTest, FocusExistingFrameOnNavigate) {
// Make a request from the new window that will navigate the original window.
// The original window should be focused.
- WebURLRequest web_url_request_with_target_start;
+ WebURLRequest web_url_request_with_target_start(KURL("about:blank"));
FrameLoadRequest request_with_target_start(
nullptr, web_url_request_with_target_start.ToResourceRequest(), "_start");
ToLocalFrame(static_cast<WebViewImpl*>(client.CreatedWebView())
@@ -3492,10 +3510,12 @@ static void OpenDateTimeChooser(WebView* web_view,
WebInputEvent::GetStaticTimeStampForTests());
key_event.dom_key = Platform::Current()->DomKeyEnumFromString(" ");
key_event.windows_key_code = VKEY_SPACE;
- web_view->HandleInputEvent(WebCoalescedInputEvent(key_event));
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(key_event));
key_event.SetType(WebInputEvent::kKeyUp);
- web_view->HandleInputEvent(WebCoalescedInputEvent(key_event));
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(key_event));
}
// TODO(crbug.com/605112) This test is crashing on Android (Nexus 4) bot.
@@ -3596,7 +3616,7 @@ TEST_F(WebViewTest, DispatchesFocusBlurOnViewToggle) {
}
class CreateChildCounterFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
CreateChildCounterFrameClient() : count_(0) {}
WebLocalFrame* CreateChildFrame(WebLocalFrame* parent,
@@ -3605,7 +3625,8 @@ class CreateChildCounterFrameClient
const WebString& fallback_name,
WebSandboxFlags,
const ParsedFeaturePolicy&,
- const WebFrameOwnerProperties&) override;
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType) override;
int Count() const { return count_; }
@@ -3620,11 +3641,12 @@ WebLocalFrame* CreateChildCounterFrameClient::CreateChildFrame(
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties& frame_owner_properties) {
+ const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType frame_owner_element_type) {
++count_;
return TestWebFrameClient::CreateChildFrame(
parent, scope, name, fallback_name, sandbox_flags, container_policy,
- frame_owner_properties);
+ frame_owner_properties, frame_owner_element_type);
}
TEST_F(WebViewTest, ChangeDisplayMode) {
@@ -3666,8 +3688,8 @@ TEST_F(WebViewTest, AddFrameInNavigateUnload) {
RegisterMockedHttpURLLoad("add_frame_in_unload.html");
web_view_helper_.InitializeAndLoad(base_url_ + "add_frame_in_unload.html",
&frame_client);
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- "about:blank");
+ frame_test_helpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
+ "about:blank");
EXPECT_EQ(0, frame_client.Count());
web_view_helper_.Reset();
}
@@ -3678,14 +3700,14 @@ TEST_F(WebViewTest, AddFrameInChildInNavigateUnload) {
RegisterMockedHttpURLLoad("add_frame_in_unload.html");
web_view_helper_.InitializeAndLoad(
base_url_ + "add_frame_in_unload_wrapper.html", &frame_client);
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- "about:blank");
+ frame_test_helpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
+ "about:blank");
EXPECT_EQ(1, frame_client.Count());
web_view_helper_.Reset();
}
class TouchEventHandlerWebWidgetClient
- : public FrameTestHelpers::TestWebWidgetClient {
+ : public frame_test_helpers::TestWebWidgetClient {
public:
// WebWidgetClient methods
void HasTouchEventHandlers(bool state) override {
@@ -3713,7 +3735,7 @@ class TouchEventHandlerWebWidgetClient
// This test verifies that WebWidgetClient::hasTouchEventHandlers is called
// accordingly for various calls to EventHandlerRegistry::did{Add|Remove|
// RemoveAll}EventHandler(..., TouchEvent). Verifying that those calls are made
-// correctly is the job of LayoutTests/fast/events/event-handler-count.html.
+// correctly is the job of web_tests/fast/events/event-handler-count.html.
TEST_F(WebViewTest, HasTouchEventHandlers) {
TouchEventHandlerWebWidgetClient client;
std::string url = RegisterMockedHttpURLLoad("has_touch_event_handlers.html");
@@ -4035,7 +4057,7 @@ TEST_F(WebViewTest, AutoResizeSubtreeLayout) {
TEST_F(WebViewTest, PreferredSize) {
std::string url = base_url_ + "specify_size.html?100px:100px";
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url), test::CoreTestDataPath("specify_size.html"));
WebView* web_view = web_view_helper_.InitializeAndLoad(url);
@@ -4061,7 +4083,7 @@ TEST_F(WebViewTest, PreferredSize) {
EXPECT_EQ(100, size.height);
url = base_url_ + "specify_size.html?1.5px:1.5px";
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url), test::CoreTestDataPath("specify_size.html"));
web_view = web_view_helper_.InitializeAndLoad(url);
@@ -4074,14 +4096,14 @@ TEST_F(WebViewTest, PreferredSize) {
TEST_F(WebViewTest, PreferredMinimumSizeQuirksMode) {
WebViewImpl* web_view = web_view_helper_.Initialize();
web_view->Resize(WebSize(800, 600));
- FrameTestHelpers::LoadHTMLString(
+ frame_test_helpers::LoadHTMLString(
web_view->MainFrameImpl(),
R"HTML(<html>
<body style="margin: 0px;">
<div style="width: 99px; height: 100px; display: inline-block;"></div>
</body>
</html>)HTML",
- URLTestHelpers::ToKURL("http://example.com/"));
+ url_test_helpers::ToKURL("http://example.com/"));
WebSize size = web_view->ContentsPreferredMinimumSize();
EXPECT_EQ(99, size.width);
@@ -4091,9 +4113,9 @@ TEST_F(WebViewTest, PreferredMinimumSizeQuirksMode) {
TEST_F(WebViewTest, PreferredSizeWithGrid) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- R"HTML(<!DOCTYPE html>
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ R"HTML(<!DOCTYPE html>
<style>
html { writing-mode: vertical-rl; }
body { margin: 0px; }
@@ -4104,7 +4126,7 @@ TEST_F(WebViewTest, PreferredSizeWithGrid) {
</div>
</div>
)HTML",
- base_url);
+ base_url);
WebSize size = web_view->ContentsPreferredMinimumSize();
EXPECT_EQ(100, size.width);
@@ -4113,16 +4135,16 @@ TEST_F(WebViewTest, PreferredSizeWithGrid) {
TEST_F(WebViewTest, PreferredSizeWithGridMinWidth) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- R"HTML(<!DOCTYPE html>
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ R"HTML(<!DOCTYPE html>
<body style="margin: 0px;">
<div style="display: inline-grid; min-width: 200px;">
<div>item</div>
</div>
</body>
)HTML",
- base_url);
+ base_url);
WebSize size = web_view->ContentsPreferredMinimumSize();
EXPECT_EQ(200, size.width);
@@ -4130,16 +4152,16 @@ TEST_F(WebViewTest, PreferredSizeWithGridMinWidth) {
TEST_F(WebViewTest, PreferredSizeWithGridMinWidthFlexibleTracks) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- R"HTML(<!DOCTYPE html>
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ R"HTML(<!DOCTYPE html>
<body style="margin: 0px;">
<div style="display: inline-grid; min-width: 200px; grid-template-columns: 1fr;">
<div>item</div>
</div>
</body>
)HTML",
- base_url);
+ base_url);
WebSize size = web_view->ContentsPreferredMinimumSize();
EXPECT_EQ(200, size.width);
@@ -4151,7 +4173,7 @@ TEST_F(WebViewTest, PreferredSizeWithGridMinWidthFlexibleTracks) {
class MojoTestHelper {
public:
MojoTestHelper(const String& test_file,
- FrameTestHelpers::WebViewHelper& web_view_helper)
+ frame_test_helpers::WebViewHelper& web_view_helper)
: web_view_helper_(web_view_helper) {
web_view_ = web_view_helper.InitializeAndLoad(
WebString(test_file).Utf8(), &web_frame_client_, &web_view_client_);
@@ -4173,9 +4195,9 @@ class MojoTestHelper {
private:
WebViewImpl* web_view_;
- FrameTestHelpers::WebViewHelper& web_view_helper_;
- FrameTestHelpers::TestWebFrameClient web_frame_client_;
- FrameTestHelpers::TestWebViewClient web_view_client_;
+ frame_test_helpers::WebViewHelper& web_view_helper_;
+ frame_test_helpers::TestWebFrameClient web_frame_client_;
+ frame_test_helpers::TestWebViewClient web_view_client_;
std::unique_ptr<service_manager::InterfaceProvider::TestApi> test_api_;
};
@@ -4233,7 +4255,8 @@ class ShowUnhandledTapTest : public WebViewTest {
web_view_ = mojo_test_helper_->WebView();
web_view_->Resize(WebSize(500, 300));
- web_view_->UpdateAllLifecyclePhases();
+ web_view_->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
mojo_test_helper_->BindTestApi(
@@ -4360,7 +4383,7 @@ TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeededWithTextSizes) {
TEST_F(WebViewTest, StopLoadingIfJavaScriptURLReturnsNoStringResult) {
ViewCreatingWebViewClient client;
- FrameTestHelpers::WebViewHelper main_web_view;
+ frame_test_helpers::WebViewHelper main_web_view;
main_web_view.InitializeAndLoad("about:blank", nullptr, &client);
WebLocalFrame* frame = main_web_view.GetWebView()->MainFrameImpl();
@@ -4542,7 +4565,7 @@ TEST_F(WebViewTest, SubframeBeforeUnloadUseCounter) {
{
frame->ExecuteScript(
WebScriptSource("addEventListener('beforeunload', function() {});"));
- web_view->MainFrame()->ToWebLocalFrame()->DispatchBeforeUnloadEvent(false);
+ web_view->MainFrameImpl()->DispatchBeforeUnloadEvent(false);
EXPECT_FALSE(UseCounter::IsCounted(*document,
WebFeature::kSubFrameBeforeUnloadFired));
}
@@ -4553,9 +4576,7 @@ TEST_F(WebViewTest, SubframeBeforeUnloadUseCounter) {
frame->ExecuteScript(WebScriptSource(
"document.getElementsByTagName('iframe')[0].contentWindow."
"addEventListener('beforeunload', function() {});"));
- web_view->MainFrame()
- ->FirstChild()
- ->ToWebLocalFrame()
+ ToWebLocalFrameImpl(web_view->MainFrame()->FirstChild()->ToWebLocalFrame())
->DispatchBeforeUnloadEvent(false);
Document* child_document = ToLocalFrame(web_view_helper_.GetWebView()
@@ -4752,14 +4773,14 @@ TEST_F(WebViewTest, ResizeForPrintingViewportUnits) {
WebViewImpl* web_view = web_view_helper_.Initialize();
web_view->Resize(WebSize(800, 600));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<style>"
- " body { margin: 0px; }"
- " #vw { width: 100vw; height: 100vh; }"
- "</style>"
- "<div id=vw></div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<style>"
+ " body { margin: 0px; }"
+ " #vw { width: 100vw; height: 100vh; }"
+ "</style>"
+ "<div id=vw></div>",
+ base_url);
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
Document* document = frame->GetFrame()->GetDocument();
@@ -4796,15 +4817,15 @@ TEST_F(WebViewTest, WidthMediaQueryWithPageZoomAfterPrinting) {
web_view->Resize(WebSize(800, 600));
web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(2.0));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<style>"
- " @media (max-width: 600px) {"
- " div { color: green }"
- " }"
- "</style>"
- "<div id=d></div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<style>"
+ " @media (max-width: 600px) {"
+ " div { color: green }"
+ " }"
+ "</style>"
+ "<div id=d></div>",
+ base_url);
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
Document* document = frame->GetFrame()->GetDocument();
@@ -4831,16 +4852,16 @@ TEST_F(WebViewTest, ViewportUnitsPrintingWithPageZoom) {
web_view->Resize(WebSize(800, 600));
web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(2.0));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<style>"
- " body { margin: 0 }"
- " #t1 { width: 100% }"
- " #t2 { width: 100vw }"
- "</style>"
- "<div id=t1></div>"
- "<div id=t2></div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<style>"
+ " body { margin: 0 }"
+ " #t1 { width: 100% }"
+ " #t2 { width: 100vw }"
+ "</style>"
+ "<div id=t1></div>"
+ "<div id=t2></div>",
+ base_url);
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
Document* document = frame->GetFrame()->GetDocument();
@@ -4869,16 +4890,16 @@ TEST_F(WebViewTest, DeviceEmulationResetScrollbars) {
WebViewImpl* web_view = web_view_helper_.Initialize();
web_view->Resize(WebSize(800, 600));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<!doctype html>"
- "<meta name='viewport'"
- " content='width=device-width'>"
- "<style>"
- " body {margin: 0px; height:3000px;}"
- "</style>",
- base_url);
- web_view->UpdateAllLifecyclePhases();
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<!doctype html>"
+ "<meta name='viewport'"
+ " content='width=device-width'>"
+ "<style>"
+ " body {margin: 0px; height:3000px;}"
+ "</style>",
+ base_url);
+ UpdateAllLifecyclePhases();
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
auto* frame_view = frame->GetFrameView();
@@ -4905,7 +4926,7 @@ TEST_F(WebViewTest, DeviceEmulationResetScrollbars) {
TEST_F(WebViewTest, SetZoomLevelWhilePluginFocused) {
class PluginCreatingWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
// WebLocalFrameClient overrides:
WebPlugin* CreatePlugin(const WebPluginParams& params) override {
@@ -4914,8 +4935,8 @@ TEST_F(WebViewTest, SetZoomLevelWhilePluginFocused) {
};
PluginCreatingWebFrameClient frame_client;
WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client);
- WebURL base_url = URLTestHelpers::ToKURL("https://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("https://example.com/");
+ frame_test_helpers::LoadHTMLString(
web_view->MainFrameImpl(),
"<!DOCTYPE html><html><body>"
"<object type='application/x-webkit-test-plugin'></object>"
@@ -4956,7 +4977,7 @@ TEST_F(WebViewTest, DetachPluginInLayout) {
};
class PluginCreatingWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
// WebLocalFrameClient overrides:
WebPlugin* CreatePlugin(const WebPluginParams& params) override {
@@ -4978,8 +4999,8 @@ TEST_F(WebViewTest, DetachPluginInLayout) {
PluginCreatingWebFrameClient frame_client;
WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client);
- WebURL base_url = URLTestHelpers::ToKURL("https://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("https://example.com/");
+ frame_test_helpers::LoadHTMLString(
web_view->MainFrameImpl(),
"<!DOCTYPE html><html><body>"
"<object type='application/x-webkit-test-plugin'></object>"
@@ -4994,7 +5015,7 @@ TEST_F(WebViewTest, DetachPluginInLayout) {
plugin_element->style()->setCSSText(main_frame->GetDocument(),
"display: none", ASSERT_NO_EXCEPTION);
EXPECT_TRUE(plugin_element->OwnedPlugin());
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_FALSE(plugin_element->OwnedPlugin());
EXPECT_EQ("done", frame_client.Message());
web_view_helper_.Reset(); // Remove dependency on locally scoped client.
@@ -5003,9 +5024,9 @@ TEST_F(WebViewTest, DetachPluginInLayout) {
// Check that first input delay is correctly reported to the document.
TEST_F(WebViewTest, FirstInputDelayReported) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5057,9 +5078,9 @@ TEST_F(WebViewTest, FirstInputDelayReported) {
// Check that longest input delay is correctly reported to the document.
TEST_F(WebViewTest, LongestInputDelayReported) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5118,9 +5139,9 @@ TEST_F(WebViewTest, InputDelayReported) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
clock.Advance(TimeDelta::FromMilliseconds(70));
@@ -5166,9 +5187,9 @@ TEST_F(WebViewTest, InputDelayReported) {
// we do not count its delay to calculate longest input delay.
TEST_F(WebViewTest, LongestInputDelayPageBackgroundedDuringQueuing) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5220,9 +5241,9 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedDuringQueuing) {
TEST_F(WebViewTest, LongestInputDelayPageBackgroundedAtNavStart) {
WebViewImpl* web_view = web_view_helper_.Initialize();
web_view->SetVisibilityState(mojom::PageVisibilityState::kHidden, false);
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5254,9 +5275,9 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedAtNavStart) {
// longest input delay.
TEST_F(WebViewTest, LongestInputDelayPageBackgroundedNotDuringQueuing) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5297,9 +5318,9 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedNotDuringQueuing) {
// first input is a pointer down event, and we receive a pointer up event.
TEST_F(WebViewTest, PointerDownUpFirstInputDelay) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5344,9 +5365,9 @@ TEST_F(WebViewTest, PointerDownUpFirstInputDelay) {
// first input is a pointer down event followed by a pointer cancel event.
TEST_F(WebViewTest, PointerDownCancelFirstInputDelay) {
WebViewImpl* web_view = web_view_helper_.Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5388,7 +5409,7 @@ TEST_F(WebViewTest, PointerDownCancelFirstInputDelay) {
// We need a way for JS to advance the mock clock. Hook into console.log, so
// that logging advances the clock by |event_handling_delay| seconds.
class MockClockAdvancingWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
MockClockAdvancingWebFrameClient(WTF::ScopedMockClock* mock_clock,
TimeDelta event_handling_delay)
@@ -5414,9 +5435,9 @@ TEST_F(WebViewTest, FirstInputDelayExcludesProcessingTime) {
MockClockAdvancingWebFrameClient frame_client(
&clock, TimeDelta::FromMilliseconds(6000));
WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client);
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
@@ -5459,9 +5480,9 @@ TEST_F(WebViewTest, LongestInputDelayExcludesProcessingTime) {
MockClockAdvancingWebFrameClient frame_client(
&clock, TimeDelta::FromMilliseconds(6000));
WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client);
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(),
- "<html><body></body></html>", base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
+ "<html><body></body></html>", base_url);
LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame();
ASSERT_NE(nullptr, main_frame);
diff --git a/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.cc b/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.cc
index b5af600ee4b..1ca8862eda6 100644
--- a/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.cc
+++ b/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.cc
@@ -4,12 +4,10 @@
#include "third_party/blink/renderer/core/exported/worker_shadow_page.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/mojom/page/page_visibility_state.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/public/platform/web_referrer_policy.h"
-#include "third_party/blink/public/web/web_settings.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
-#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/platform/loader/fetch/substitute_data.h"
@@ -41,14 +39,6 @@ WorkerShadowPage::WorkerShadowPage(
preferences_(std::move(preferences)) {
DCHECK(IsMainThread());
- // TODO(http://crbug.com/363843): This needs to find a better way to
- // not create graphics layers.
- web_view_->GetSettings()->SetAcceleratedCompositingEnabled(false);
- // TODO(lunalu): Service worker and shared worker count feature usage on the
- // blink side use counter. Once the blink side use counter is removed
- // (crbug.com/811948), remove this instant from Settings.
- main_frame_->GetFrame()->GetSettings()->SetIsShadowPage(true);
-
main_frame_->SetDevToolsAgentImpl(
WebDevToolsAgentImpl::CreateForWorker(main_frame_, client_));
}
@@ -57,7 +47,7 @@ WorkerShadowPage::~WorkerShadowPage() {
DCHECK(IsMainThread());
// Detach the client before closing the view to avoid getting called back.
main_frame_->SetClient(nullptr);
- web_view_->Close();
+ web_view_->MainFrameWidget()->Close();
main_frame_->Close();
}
@@ -109,10 +99,16 @@ void WorkerShadowPage::WillSendRequest(WebURLRequest& request) {
request.SetHTTPHeaderField(WebString::FromUTF8(kDoNotTrackHeader), "1");
}
if (!preferences_.enable_referrers) {
- request.SetHTTPReferrer(WebString(), kWebReferrerPolicyDefault);
+ request.SetHTTPReferrer(WebString(),
+ network::mojom::ReferrerPolicy::kDefault);
}
}
+void WorkerShadowPage::BeginNavigation(
+ std::unique_ptr<WebNavigationInfo> info) {
+ NOTREACHED();
+}
+
bool WorkerShadowPage::WasInitialized() const {
return state_ == State::kInitialized;
}
diff --git a/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.h b/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.h
index 753396ab1ed..60fc03c0a8a 100644
--- a/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.h
+++ b/chromium/third_party/blink/renderer/core/exported/worker_shadow_page.h
@@ -77,6 +77,7 @@ class CORE_EXPORT WorkerShadowPage : public WebLocalFrameClient {
std::unique_ptr<blink::WebURLLoaderFactory> CreateURLLoaderFactory() override;
base::UnguessableToken GetDevToolsFrameToken() override;
void WillSendRequest(WebURLRequest&) override;
+ void BeginNavigation(std::unique_ptr<WebNavigationInfo> info) override;
Document* GetDocument() { return main_frame_->GetFrame()->GetDocument(); }
WebSettings* GetSettings() { return web_view_->GetSettings(); }
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn b/chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn
index ff3dd58753f..c9aa37d4179 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn
@@ -10,6 +10,8 @@ blink_core_sources("feature_policy") {
"feature_policy.cc",
"feature_policy.h",
"iframe_policy.h",
+ "layout_animations_policy.cc",
+ "layout_animations_policy.h",
"policy.cc",
"policy.h",
]
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.cc b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.cc
index 40161ba7252..c3ec251454e 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.cc
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.cc
@@ -6,6 +6,10 @@
#include <algorithm>
#include "base/metrics/histogram_macros.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
+#include "third_party/blink/renderer/platform/json/json_values.h"
+#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/bit_vector.h"
@@ -14,6 +18,9 @@
namespace blink {
+constexpr char kReportOnlySuffix[] = "-report-only";
+constexpr size_t kReportOnlySuffixLength = 12;
+
ParsedFeaturePolicy ParseFeaturePolicyHeader(
const String& policy,
scoped_refptr<const SecurityOrigin> origin,
@@ -26,9 +33,10 @@ ParsedFeaturePolicy ParseFeaturePolicyAttribute(
const String& policy,
scoped_refptr<const SecurityOrigin> self_origin,
scoped_refptr<const SecurityOrigin> src_origin,
- Vector<String>* messages) {
+ Vector<String>* messages,
+ Document* document) {
return ParseFeaturePolicy(policy, self_origin, src_origin, messages,
- GetDefaultFeatureNameMap());
+ GetDefaultFeatureNameMap(), document);
}
ParsedFeaturePolicy ParseFeaturePolicy(
@@ -36,7 +44,8 @@ ParsedFeaturePolicy ParseFeaturePolicy(
scoped_refptr<const SecurityOrigin> self_origin,
scoped_refptr<const SecurityOrigin> src_origin,
Vector<String>* messages,
- const FeatureNameMap& feature_names) {
+ const FeatureNameMap& feature_names,
+ Document* document) {
ParsedFeaturePolicy allowlists;
BitVector features_specified(
static_cast<int>(mojom::FeaturePolicyFeature::kMaxValue));
@@ -59,26 +68,51 @@ ParsedFeaturePolicy ParseFeaturePolicy(
// Empty policy. Skip.
if (tokens.IsEmpty())
continue;
- if (!feature_names.Contains(tokens[0])) {
- if (messages)
+ mojom::FeaturePolicyDisposition disposition =
+ mojom::FeaturePolicyDisposition::kEnforce;
+ String feature_name;
+ if (RuntimeEnabledFeatures::FeaturePolicyReportingEnabled() &&
+ tokens[0].EndsWith(kReportOnlySuffix)) {
+ feature_name = tokens[0].Substring(
+ 0, tokens[0].length() - kReportOnlySuffixLength);
+ disposition = mojom::FeaturePolicyDisposition::kReport;
+ } else {
+ feature_name = tokens[0];
+ }
+ if (!feature_names.Contains(feature_name)) {
+ if (messages) {
+ // Console message should display the entire string, with
+ // "-report-only" suffix if it was originally included.
messages->push_back("Unrecognized feature: '" + tokens[0] + "'.");
+ }
continue;
}
- mojom::FeaturePolicyFeature feature = feature_names.at(tokens[0]);
+ mojom::FeaturePolicyFeature feature = feature_names.at(feature_name);
// If a policy has already been specified for the current feature, drop
// the new policy.
+ // TODO(crbug.com/904880): Allow a report-only and an enforcing version in
+ // the same parsed policy.
if (features_specified.QuickGet(static_cast<int>(feature)))
continue;
// Count the use of this feature policy.
- if (!src_origin) {
+ if (src_origin) {
+ if (!document || !document->IsParsedFeaturePolicy(feature)) {
+ UMA_HISTOGRAM_ENUMERATION("Blink.UseCounter.FeaturePolicy.Allow",
+ feature);
+ if (document) {
+ document->SetParsedFeaturePolicy(feature);
+ }
+ }
+ } else {
UMA_HISTOGRAM_ENUMERATION("Blink.UseCounter.FeaturePolicy.Header",
feature);
}
ParsedFeaturePolicyDeclaration allowlist;
allowlist.feature = feature;
+ allowlist.disposition = disposition;
features_specified.QuickSet(static_cast<int>(feature));
std::vector<url::Origin> origins;
// If a policy entry has no (optional) values (e,g,
@@ -99,7 +133,7 @@ ParsedFeaturePolicy ParseFeaturePolicy(
}
for (wtf_size_t i = 1; i < tokens.size(); i++) {
- if (!tokens[i].ContainsOnlyASCII()) {
+ if (!tokens[i].ContainsOnlyASCIIOrEmpty()) {
messages->push_back("Non-ASCII characters in origin.");
continue;
}
@@ -123,6 +157,7 @@ ParsedFeaturePolicy ParseFeaturePolicy(
continue;
} else if (tokens[i] == "*") {
allowlist.matches_all_origins = true;
+ origins.clear();
break;
} else {
scoped_refptr<SecurityOrigin> target_origin =
@@ -133,7 +168,10 @@ ParsedFeaturePolicy ParseFeaturePolicy(
messages->push_back("Unrecognized origin: '" + tokens[i] + "'.");
}
}
- allowlist.origins = origins;
+ std::sort(origins.begin(), origins.end());
+ auto new_end = std::unique(origins.begin(), origins.end());
+ origins.erase(new_end, origins.end());
+ allowlist.origins = std::move(origins);
allowlists.push_back(allowlist);
}
}
@@ -168,6 +206,7 @@ bool DisallowFeatureIfNotPresent(mojom::FeaturePolicyFeature feature,
allowlist.feature = feature;
allowlist.matches_all_origins = false;
allowlist.matches_opaque_src = false;
+ allowlist.disposition = mojom::FeaturePolicyDisposition::kEnforce;
policy.push_back(allowlist);
return true;
}
@@ -180,6 +219,7 @@ bool AllowFeatureEverywhereIfNotPresent(mojom::FeaturePolicyFeature feature,
allowlist.feature = feature;
allowlist.matches_all_origins = true;
allowlist.matches_opaque_src = true;
+ allowlist.disposition = mojom::FeaturePolicyDisposition::kEnforce;
policy.push_back(allowlist);
return true;
}
@@ -233,22 +273,26 @@ const FeatureNameMap& GetDefaultFeatureNameMap() {
mojom::FeaturePolicyFeature::kSyncXHR);
// Under origin trial: Should be made conditional on WebVR and WebXR
// runtime flags once it is out of trial.
+ ASSERT_ORIGIN_TRIAL(WebVR);
+ ASSERT_ORIGIN_TRIAL(WebXR);
default_feature_name_map.Set("vr", mojom::FeaturePolicyFeature::kWebVr);
if (RuntimeEnabledFeatures::ExperimentalProductivityFeaturesEnabled()) {
- default_feature_name_map.Set("animations",
- mojom::FeaturePolicyFeature::kAnimations);
+ default_feature_name_map.Set(
+ "layout-animations", mojom::FeaturePolicyFeature::kLayoutAnimations);
default_feature_name_map.Set("document-write",
mojom::FeaturePolicyFeature::kDocumentWrite);
default_feature_name_map.Set(
- "image-compression", mojom::FeaturePolicyFeature::kImageCompression);
+ "document-domain", mojom::FeaturePolicyFeature::kDocumentDomain);
+ default_feature_name_map.Set(
+ "unoptimized-images",
+ mojom::FeaturePolicyFeature::kUnoptimizedImages);
default_feature_name_map.Set("lazyload",
mojom::FeaturePolicyFeature::kLazyLoad);
default_feature_name_map.Set(
"legacy-image-formats",
mojom::FeaturePolicyFeature::kLegacyImageFormats);
default_feature_name_map.Set(
- "max-downscaling-image",
- mojom::FeaturePolicyFeature::kMaxDownscalingImage);
+ "oversized-images", mojom::FeaturePolicyFeature::kOversizedImages);
default_feature_name_map.Set("unsized-media",
mojom::FeaturePolicyFeature::kUnsizedMedia);
default_feature_name_map.Set(
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.h b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.h
index b0b71c79165..ce47d1535ea 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.h
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy.h
@@ -18,6 +18,8 @@
namespace blink {
+class Document;
+
// Returns a map between feature name (string) and mojom::FeaturePolicyFeature
// (enum).
typedef HashMap<String, mojom::FeaturePolicyFeature> FeatureNameMap;
@@ -44,18 +46,20 @@ CORE_EXPORT ParsedFeaturePolicy
ParseFeaturePolicyAttribute(const String& policy,
scoped_refptr<const SecurityOrigin> self_origin,
scoped_refptr<const SecurityOrigin> src_origin,
- Vector<String>* messages);
+ Vector<String>* messages,
+ Document* document = nullptr);
// Converts a feature policy string into a vector of allowlists (see comments
// above), with an explicit FeatureNameMap. This algorithm is called by both
-// header policy parsing and container policy parsing. |self_origin| and
-// |src_origin| are both nullable.
+// header policy parsing and container policy parsing. |self_origin|,
+// |src_origin|, and |document| are nullable.
CORE_EXPORT ParsedFeaturePolicy
ParseFeaturePolicy(const String& policy,
scoped_refptr<const SecurityOrigin> self_origin,
scoped_refptr<const SecurityOrigin> src_origin,
Vector<String>* messages,
- const FeatureNameMap& feature_names);
+ const FeatureNameMap& feature_names,
+ Document* document = nullptr);
// Returns true iff any declaration in the policy is for the given feature.
CORE_EXPORT bool IsFeatureDeclared(mojom::FeaturePolicyFeature,
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_test.cc b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_test.cc
index b9c847ce617..54d36ab9d49 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_test.cc
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_test.cc
@@ -5,7 +5,11 @@
#include "third_party/blink/renderer/core/feature_policy/feature_policy.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
+#include "third_party/blink/renderer/core/loader/empty_clients.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
+
#include "url/gurl.h"
#include "url/origin.h"
@@ -63,6 +67,15 @@ class FeaturePolicyParserTest : public testing::Test {
~FeaturePolicyParserTest() override = default;
+ /*void SetUp() override {
+ chrome_client_ = new ConsoleCapturingChromeClient();
+ Page::PageClients clients;
+ FillWithEmptyClients(clients);
+ clients.chrome_client = chrome_client_.Get();
+ SetupPageWithClients(&clients);
+ Page::InsertOrdinaryPageForTesting(&GetPage());
+ }*/
+
scoped_refptr<const SecurityOrigin> origin_a_ =
SecurityOrigin::CreateFromString(ORIGIN_A);
scoped_refptr<const SecurityOrigin> origin_b_ =
@@ -331,6 +344,57 @@ TEST_F(FeaturePolicyParserTest, HistogramMultiple) {
static_cast<int>(blink::mojom::FeaturePolicyFeature::kFullscreen), 1);
}
+// Test histogram counting the use of feature policies via "allow"
+// attribute. This test parses two policies on the same document.
+TEST_F(FeaturePolicyParserTest, AllowHistogramSameDocument) {
+ const char* histogram_name = "Blink.UseCounter.FeaturePolicy.Allow";
+ HistogramTester tester;
+ Vector<String> messages;
+ std::unique_ptr<DummyPageHolder> dummy = DummyPageHolder::Create();
+
+ ParseFeaturePolicy("payment; fullscreen", origin_a_.get(), origin_b_.get(),
+ &messages, test_feature_name_map, &dummy->GetDocument());
+ ParseFeaturePolicy("fullscreen; geolocation", origin_a_.get(),
+ origin_b_.get(), &messages, test_feature_name_map,
+ &dummy->GetDocument());
+ tester.ExpectTotalCount(histogram_name, 3);
+ tester.ExpectBucketCount(
+ histogram_name,
+ static_cast<int>(blink::mojom::FeaturePolicyFeature::kPayment), 1);
+ tester.ExpectBucketCount(
+ histogram_name,
+ static_cast<int>(blink::mojom::FeaturePolicyFeature::kFullscreen), 1);
+ tester.ExpectBucketCount(
+ histogram_name,
+ static_cast<int>(blink::mojom::FeaturePolicyFeature::kGeolocation), 1);
+}
+
+// Test histogram counting the use of feature policies via "allow"
+// attribute. This test parses two policies on different documents.
+TEST_F(FeaturePolicyParserTest, AllowHistogramDifferentDocument) {
+ const char* histogram_name = "Blink.UseCounter.FeaturePolicy.Allow";
+ HistogramTester tester;
+ Vector<String> messages;
+ std::unique_ptr<DummyPageHolder> dummy = DummyPageHolder::Create();
+ std::unique_ptr<DummyPageHolder> dummy2 = DummyPageHolder::Create();
+
+ ParseFeaturePolicy("payment; fullscreen", origin_a_.get(), origin_b_.get(),
+ &messages, test_feature_name_map, &dummy->GetDocument());
+ ParseFeaturePolicy("fullscreen; geolocation", origin_a_.get(),
+ origin_b_.get(), &messages, test_feature_name_map,
+ &dummy2->GetDocument());
+ tester.ExpectTotalCount(histogram_name, 4);
+ tester.ExpectBucketCount(
+ histogram_name,
+ static_cast<int>(blink::mojom::FeaturePolicyFeature::kPayment), 1);
+ tester.ExpectBucketCount(
+ histogram_name,
+ static_cast<int>(blink::mojom::FeaturePolicyFeature::kFullscreen), 2);
+ tester.ExpectBucketCount(
+ histogram_name,
+ static_cast<int>(blink::mojom::FeaturePolicyFeature::kGeolocation), 1);
+}
+
// Test policy mutation methods
class FeaturePolicyMutationTest : public testing::Test {
protected:
@@ -375,10 +439,12 @@ class FeaturePolicyMutationTest : public testing::Test {
ParsedFeaturePolicy test_policy = {{mojom::FeaturePolicyFeature::kFullscreen,
false,
false,
+ mojom::FeaturePolicyDisposition::kEnforce,
{url_origin_a_, url_origin_b_}},
{mojom::FeaturePolicyFeature::kGeolocation,
false,
false,
+ mojom::FeaturePolicyDisposition::kEnforce,
{url_origin_a_}}};
ParsedFeaturePolicy empty_policy = {};
};
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/iframe_policy.h b/chromium/third_party/blink/renderer/core/feature_policy/iframe_policy.h
index e53ec6427e9..d4645da598f 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/iframe_policy.h
+++ b/chromium/third_party/blink/renderer/core/feature_policy/iframe_policy.h
@@ -33,7 +33,9 @@ class IFramePolicy final : public Policy {
const ParsedFeaturePolicy& container_policy,
scoped_refptr<const SecurityOrigin> src_origin) override {
policy_ = FeaturePolicy::CreateFromParentPolicy(
- parent_document_->GetFeaturePolicy(), container_policy,
+ parent_document_->GetFeaturePolicy(),
+ *DirectivesWithDisposition(mojom::FeaturePolicyDisposition::kEnforce,
+ container_policy),
src_origin->ToUrlOrigin());
}
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc b/chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc
new file mode 100644
index 00000000000..e85b8f52673
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc
@@ -0,0 +1,55 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/feature_policy/layout_animations_policy.h"
+
+#include "third_party/blink/renderer/core/css/properties/css_property.h"
+#include "third_party/blink/renderer/core/execution_context/security_context.h"
+#include "third_party/blink/renderer/core/feature_policy/feature_policy.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
+
+namespace blink {
+namespace {
+String GetViolationMessage(const CSSProperty& property) {
+ return String::Format(
+ "Feature policy violation: CSS property '%s' violates feature policy "
+ "'%s' which is disabled in this document",
+ property.GetPropertyNameString().Utf8().data(),
+ GetNameForFeature(mojom::FeaturePolicyFeature::kLayoutAnimations)
+ .Utf8()
+ .data());
+}
+} // namespace
+
+LayoutAnimationsPolicy::LayoutAnimationsPolicy() = default;
+
+// static
+const HashSet<const CSSProperty*>&
+LayoutAnimationsPolicy::AffectedCSSProperties() {
+ DEFINE_STATIC_LOCAL(
+ HashSet<const CSSProperty*>, properties,
+ ({&GetCSSPropertyBottom(), &GetCSSPropertyHeight(), &GetCSSPropertyLeft(),
+ &GetCSSPropertyRight(), &GetCSSPropertyTop(), &GetCSSPropertyWidth()}));
+ return properties;
+}
+
+// static
+
+// static
+void LayoutAnimationsPolicy::ReportViolation(
+ const CSSProperty& animated_property,
+ const SecurityContext& security_context) {
+ DCHECK(AffectedCSSProperties().Contains(&animated_property));
+ auto state = security_context.GetFeatureEnabledState(
+ mojom::FeaturePolicyFeature::kLayoutAnimations);
+ DCHECK_NE(FeatureEnabledState::kEnabled, state);
+ security_context.ReportFeaturePolicyViolation(
+ mojom::FeaturePolicyFeature::kLayoutAnimations,
+ state == FeatureEnabledState::kReportOnly
+ ? mojom::FeaturePolicyDisposition::kReport
+ : mojom::FeaturePolicyDisposition::kEnforce,
+ GetViolationMessage(animated_property));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.h b/chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.h
new file mode 100644
index 00000000000..3b62d4dc9e3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.h
@@ -0,0 +1,38 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_LAYOUT_ANIMATIONS_POLICY_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_LAYOUT_ANIMATIONS_POLICY_H_
+
+#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/hash_set.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+class CSSProperty;
+class SecurityContext;
+
+// Helper methods for for 'layout-animations' (kLayoutAnimations) feature
+// policy.
+class LayoutAnimationsPolicy {
+ DISALLOW_NEW();
+
+ public:
+ // Returns a set of the CSS properties which are affected by the feature
+ // policy 'layout-animations'.
+ static const HashSet<const CSSProperty*>& AffectedCSSProperties();
+
+ // Generates a violation report for the blocked |animation_property|.
+ static void ReportViolation(const CSSProperty& animated_property,
+ const SecurityContext& security_context);
+
+ private:
+ LayoutAnimationsPolicy();
+
+ DISALLOW_COPY_AND_ASSIGN(LayoutAnimationsPolicy);
+};
+
+} // namespace blink
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_LAYOUT_ANIMATIONS_POLICY_H_
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/policy_test.cc b/chromium/third_party/blink/renderer/core/feature_policy/policy_test.cc
index 93d689f3e1e..2d45104c4b4 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/policy_test.cc
+++ b/chromium/third_party/blink/renderer/core/feature_policy/policy_test.cc
@@ -42,7 +42,7 @@ class DocumentPolicyTest : public PolicyTest {
public:
void SetUp() override {
PolicyTest::SetUp();
- policy_ = new DocumentPolicy(document_);
+ policy_ = MakeGarbageCollected<DocumentPolicy>(document_);
}
};
@@ -50,8 +50,9 @@ class IFramePolicyTest : public PolicyTest {
public:
void SetUp() override {
PolicyTest::SetUp();
- policy_ = new IFramePolicy(document_, {},
- SecurityOrigin::CreateFromString(kSelfOrigin));
+ policy_ = MakeGarbageCollected<IFramePolicy>(
+ document_, ParsedFeaturePolicy(),
+ SecurityOrigin::CreateFromString(kSelfOrigin));
}
};
diff --git a/chromium/third_party/blink/renderer/core/fetch/DEPS b/chromium/third_party/blink/renderer/core/fetch/DEPS
index 30dcb36c0e4..3c497b001fa 100644
--- a/chromium/third_party/blink/renderer/core/fetch/DEPS
+++ b/chromium/third_party/blink/renderer/core/fetch/DEPS
@@ -4,5 +4,4 @@ include_rules = [
"+mojo/public/cpp/bindings/binding_set.h",
"+mojo/public/cpp/system/data_pipe.h",
"+mojo/public/cpp/system/simple_watcher.h",
- "+services/network/public/mojom",
]
diff --git a/chromium/third_party/blink/renderer/core/fetch/blob_bytes_consumer.cc b/chromium/third_party/blink/renderer/core/fetch/blob_bytes_consumer.cc
index 17a17f5b0a5..9308f122515 100644
--- a/chromium/third_party/blink/renderer/core/fetch/blob_bytes_consumer.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/blob_bytes_consumer.cc
@@ -28,8 +28,8 @@ BytesConsumer::Result BlobBytesConsumer::BeginRead(const char** buffer,
scoped_refptr<EncodedFormData> form_data = EncodedFormData::Create();
form_data->AppendDataPipe(base::MakeRefCounted<WrappedDataPipeGetter>(
blob_data_handle_->AsDataPipeGetter()));
- nested_consumer_ =
- new FormDataBytesConsumer(execution_context_, std::move(form_data));
+ nested_consumer_ = MakeGarbageCollected<FormDataBytesConsumer>(
+ execution_context_, std::move(form_data));
if (client_)
nested_consumer_->SetClient(client_);
blob_data_handle_ = nullptr;
diff --git a/chromium/third_party/blink/renderer/core/fetch/body.cc b/chromium/third_party/blink/renderer/core/fetch/body.cc
index b055be8ae42..ded01690aab 100644
--- a/chromium/third_party/blink/renderer/core/fetch/body.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/body.cc
@@ -154,8 +154,11 @@ ScriptPromise Body::arrayBuffer(ScriptState* script_state,
BodyBuffer()->StartLoading(FetchDataLoader::CreateLoaderAsArrayBuffer(),
new BodyArrayBufferConsumer(resolver),
exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
} else {
resolver->Resolve(DOMArrayBuffer::Create(0u, 1));
}
@@ -178,8 +181,11 @@ ScriptPromise Body::blob(ScriptState* script_state,
BodyBuffer()->StartLoading(
FetchDataLoader::CreateLoaderAsBlobHandle(MimeType()),
new BodyBlobConsumer(resolver), exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
} else {
std::unique_ptr<BlobData> blob_data = BlobData::Create();
blob_data->SetContentType(MimeType());
@@ -211,8 +217,11 @@ ScriptPromise Body::formData(ScriptState* script_state,
body_buffer->StartLoading(
FetchDataLoader::CreateLoaderAsFormData(boundary),
new BodyFormDataConsumer(resolver), exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
return promise;
}
} else if (parsedType == "application/x-www-form-urlencoded") {
@@ -220,8 +229,11 @@ ScriptPromise Body::formData(ScriptState* script_state,
BodyBuffer()->StartLoading(FetchDataLoader::CreateLoaderAsString(),
new BodyFormDataConsumer(resolver),
exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
} else {
resolver->Resolve(FormData::Create());
}
@@ -231,8 +243,11 @@ ScriptPromise Body::formData(ScriptState* script_state,
BodyBuffer()->StartLoading(FetchDataLoader::CreateLoaderAsFailure(),
new BodyFormDataConsumer(resolver),
exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
return promise;
}
}
@@ -257,8 +272,11 @@ ScriptPromise Body::json(ScriptState* script_state,
if (BodyBuffer()) {
BodyBuffer()->StartLoading(FetchDataLoader::CreateLoaderAsString(),
new BodyJsonConsumer(resolver), exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
} else {
resolver->Reject(V8ThrowException::CreateSyntaxError(
script_state->GetIsolate(), "Unexpected end of input"));
@@ -281,20 +299,21 @@ ScriptPromise Body::text(ScriptState* script_state,
if (BodyBuffer()) {
BodyBuffer()->StartLoading(FetchDataLoader::CreateLoaderAsString(),
new BodyTextConsumer(resolver), exception_state);
- if (exception_state.HadException())
+ if (exception_state.HadException()) {
+ // Need to resolve the ScriptPromiseResolver to avoid a DCHECK().
+ resolver->Resolve();
return ScriptPromise();
+ }
} else {
resolver->Resolve(String());
}
return promise;
}
-ScriptValue Body::body(ScriptState* script_state) {
+ReadableStream* Body::body() {
if (!BodyBuffer())
- return ScriptValue::CreateNull(script_state);
- ScriptValue stream = BodyBuffer()->Stream();
- DCHECK_EQ(stream.GetScriptState(), script_state);
- return stream;
+ return nullptr;
+ return BodyBuffer()->Stream();
}
Body::BodyUsed Body::IsBodyUsed(ExceptionState& exception_state) {
@@ -327,8 +346,9 @@ bool Body::HasPendingActivity() const {
return body_buffer->HasPendingActivity();
}
-bool Body::IsBodyUsedForDCheck() {
- return BodyBuffer() && BodyBuffer()->IsStreamDisturbedForDCheck();
+bool Body::IsBodyUsedForDCheck(ExceptionState& exception_state) {
+ return BodyBuffer() &&
+ BodyBuffer()->IsStreamDisturbedForDCheck(exception_state);
}
Body::Body(ExecutionContext* context) : ContextClient(context) {}
diff --git a/chromium/third_party/blink/renderer/core/fetch/body.h b/chromium/third_party/blink/renderer/core/fetch/body.h
index 7f8b16d9d32..424e1193122 100644
--- a/chromium/third_party/blink/renderer/core/fetch/body.h
+++ b/chromium/third_party/blink/renderer/core/fetch/body.h
@@ -19,6 +19,7 @@ namespace blink {
class BodyStreamBuffer;
class ExceptionState;
class ExecutionContext;
+class ReadableStream;
class ScriptState;
// This class represents Body mix-in defined in the fetch spec
@@ -45,7 +46,7 @@ class CORE_EXPORT Body : public ScriptWrappable,
ScriptPromise formData(ScriptState*, ExceptionState&);
ScriptPromise json(ScriptState*, ExceptionState&);
ScriptPromise text(ScriptState*, ExceptionState&);
- ScriptValue body(ScriptState*);
+ ReadableStream* body();
virtual BodyStreamBuffer* BodyBuffer() = 0;
virtual const BodyStreamBuffer* BodyBuffer() const = 0;
@@ -74,7 +75,7 @@ class CORE_EXPORT Body : public ScriptWrappable,
protected:
// A version of IsBodyUsed() which catches exceptions and returns
// false. Should never be used outside DCHECK().
- virtual bool IsBodyUsedForDCheck();
+ virtual bool IsBodyUsedForDCheck(ExceptionState& exception_state);
private:
// TODO(e_hakkinen): Fix |MimeType()| to always contain parameters and
diff --git a/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.cc b/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.cc
index 33858b63dc8..d35b65a2f5e 100644
--- a/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.cc
@@ -9,9 +9,8 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fetch/body.h"
#include "third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/streams/readable_stream_default_controller_wrapper.h"
-#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
-#include "third_party/blink/renderer/core/streams/retain_wrapper_during_construction.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
@@ -22,6 +21,7 @@
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -105,30 +105,10 @@ BodyStreamBuffer::BodyStreamBuffer(ScriptState* script_state,
consumer_(consumer),
signal_(signal),
made_from_readable_stream_(false) {
- if (!RetainWrapperDuringConstruction(this, script_state))
- stream_broken_ = true;
+ stream_ =
+ ReadableStream::CreateWithCountQueueingStrategy(script_state_, this, 0);
+ stream_broken_ = !stream_;
- {
- // Leaving an exception pending will cause Blink to crash in the bindings
- // code later, so catch instead.
- v8::TryCatch try_catch(script_state->GetIsolate());
- ScriptValue strategy =
- ReadableStreamOperations::CreateCountQueuingStrategy(script_state, 0);
- if (!strategy.IsEmpty()) {
- ScriptValue readable_stream =
- ReadableStreamOperations::CreateReadableStream(script_state, this,
- strategy);
- if (!readable_stream.IsEmpty()) {
- stream_.Set(script_state->GetIsolate(),
- readable_stream.V8Value().As<v8::Object>());
- } else {
- stream_broken_ = true;
- }
- } else {
- stream_broken_ = true;
- }
- DCHECK_EQ(stream_broken_, try_catch.HasCaught());
- }
consumer_->SetClient(this);
if (signal) {
if (signal->aborted()) {
@@ -142,36 +122,20 @@ BodyStreamBuffer::BodyStreamBuffer(ScriptState* script_state,
}
BodyStreamBuffer::BodyStreamBuffer(ScriptState* script_state,
- ScriptValue stream,
- ExceptionState& exception_state)
+ ReadableStream* stream)
: UnderlyingSourceBase(script_state),
script_state_(script_state),
+ stream_(stream),
signal_(nullptr),
made_from_readable_stream_(true) {
- // This is needed because sometimes a BodyStreamBuffer can be detached from
- // the owner object such as Request. We rely on the wrapper and
- // HasPendingActivity in such a case.
- RetainWrapperDuringConstruction(this, script_state);
- DCHECK(ReadableStreamOperations::IsReadableStreamForDCheck(script_state,
- stream));
-
- stream_.Set(script_state->GetIsolate(), stream.V8Value().As<v8::Object>());
-}
-
-ScriptValue BodyStreamBuffer::Stream() {
- // Since this is the implementation of response.body, we return the stream
- // even if |stream_broken_| is true, so that expected JavaScript attribute
- // behaviour is not changed. User code is still permitted to access the
- // stream even when it has thrown an exception.
- return ScriptValue(script_state_,
- stream_.NewLocal(script_state_->GetIsolate()));
+ DCHECK(stream_);
}
scoped_refptr<BlobDataHandle> BodyStreamBuffer::DrainAsBlobDataHandle(
BytesConsumer::BlobSizePolicy policy,
ExceptionState& exception_state) {
- DCHECK(!IsStreamLockedForDCheck());
- DCHECK(!IsStreamDisturbedForDCheck());
+ DCHECK(!IsStreamLockedForDCheck(exception_state));
+ DCHECK(!IsStreamDisturbedForDCheck(exception_state));
const base::Optional<bool> is_closed = IsStreamClosed(exception_state);
if (exception_state.HadException() || is_closed.value())
return nullptr;
@@ -195,8 +159,8 @@ scoped_refptr<BlobDataHandle> BodyStreamBuffer::DrainAsBlobDataHandle(
scoped_refptr<EncodedFormData> BodyStreamBuffer::DrainAsFormData(
ExceptionState& exception_state) {
- DCHECK(!IsStreamLockedForDCheck());
- DCHECK(!IsStreamDisturbedForDCheck());
+ DCHECK(!IsStreamLockedForDCheck(exception_state));
+ DCHECK(!IsStreamDisturbedForDCheck(exception_state));
const base::Optional<bool> is_closed = IsStreamClosed(exception_state);
if (exception_state.HadException() || is_closed.value())
return nullptr;
@@ -241,8 +205,8 @@ void BodyStreamBuffer::StartLoading(FetchDataLoader* loader,
void BodyStreamBuffer::Tee(BodyStreamBuffer** branch1,
BodyStreamBuffer** branch2,
ExceptionState& exception_state) {
- DCHECK(!IsStreamLockedForDCheck());
- DCHECK(!IsStreamDisturbedForDCheck());
+ DCHECK(!IsStreamLockedForDCheck(exception_state));
+ DCHECK(!IsStreamDisturbedForDCheck(exception_state));
*branch1 = nullptr;
*branch2 = nullptr;
@@ -255,24 +219,17 @@ void BodyStreamBuffer::Tee(BodyStreamBuffer** branch1,
"Unsafe to tee stream in unknown state");
return;
}
- ScriptValue stream1, stream2;
- ReadableStreamOperations::Tee(script_state_, Stream(), &stream1, &stream2,
- exception_state);
+ ReadableStream* stream1 = nullptr;
+ ReadableStream* stream2 = nullptr;
+
+ stream_->Tee(script_state_, &stream1, &stream2, exception_state);
if (exception_state.HadException()) {
stream_broken_ = true;
return;
}
- // Exceptions here imply that |stream1| and/or |stream2| are broken, not the
- // stream owned by this object, so we shouldn't set |stream_broken_|.
- auto* tmp1 = new BodyStreamBuffer(script_state_, stream1, exception_state);
- if (exception_state.HadException())
- return;
- auto* tmp2 = new BodyStreamBuffer(script_state_, stream2, exception_state);
- if (exception_state.HadException())
- return;
- *branch1 = tmp1;
- *branch2 = tmp2;
+ *branch1 = new BodyStreamBuffer(script_state_, stream1);
+ *branch2 = new BodyStreamBuffer(script_state_, stream2);
return;
}
BytesConsumer* dest1 = nullptr;
@@ -345,41 +302,39 @@ void BodyStreamBuffer::ContextDestroyed(ExecutionContext* destroyed_context) {
base::Optional<bool> BodyStreamBuffer::IsStreamReadable(
ExceptionState& exception_state) {
- return BooleanStreamOperation(ReadableStreamOperations::IsReadable,
- exception_state);
+ return BooleanStreamOperation(&ReadableStream::IsReadable, exception_state);
}
base::Optional<bool> BodyStreamBuffer::IsStreamClosed(
ExceptionState& exception_state) {
- return BooleanStreamOperation(ReadableStreamOperations::IsClosed,
- exception_state);
+ return BooleanStreamOperation(&ReadableStream::IsClosed, exception_state);
}
base::Optional<bool> BodyStreamBuffer::IsStreamErrored(
ExceptionState& exception_state) {
- return BooleanStreamOperation(ReadableStreamOperations::IsErrored,
- exception_state);
+ return BooleanStreamOperation(&ReadableStream::IsErrored, exception_state);
}
base::Optional<bool> BodyStreamBuffer::IsStreamLocked(
ExceptionState& exception_state) {
- return BooleanStreamOperation(ReadableStreamOperations::IsLocked,
- exception_state);
+ return BooleanStreamOperation(&ReadableStream::IsLocked, exception_state);
}
-bool BodyStreamBuffer::IsStreamLockedForDCheck() {
- return ReadableStreamOperations::IsLockedForDCheck(script_state_, Stream());
+bool BodyStreamBuffer::IsStreamLockedForDCheck(
+ ExceptionState& exception_state) {
+ auto result = IsStreamLocked(exception_state);
+ return !result || *result;
}
base::Optional<bool> BodyStreamBuffer::IsStreamDisturbed(
ExceptionState& exception_state) {
- return BooleanStreamOperation(ReadableStreamOperations::IsDisturbed,
- exception_state);
+ return BooleanStreamOperation(&ReadableStream::IsDisturbed, exception_state);
}
-bool BodyStreamBuffer::IsStreamDisturbedForDCheck() {
- return ReadableStreamOperations::IsDisturbedForDCheck(script_state_,
- Stream());
+bool BodyStreamBuffer::IsStreamDisturbedForDCheck(
+ ExceptionState& exception_state) {
+ auto result = IsStreamDisturbed(exception_state);
+ return !result || *result;
}
void BodyStreamBuffer::CloseAndLockAndDisturb(ExceptionState& exception_state) {
@@ -390,7 +345,7 @@ void BodyStreamBuffer::CloseAndLockAndDisturb(ExceptionState& exception_state) {
return;
}
- if (stream_.IsEmpty()) {
+ if (stream_->IsInternalStreamMissing()) {
stream_broken_ = true;
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
@@ -410,20 +365,7 @@ void BodyStreamBuffer::CloseAndLockAndDisturb(ExceptionState& exception_state) {
}
DCHECK(!stream_broken_);
- ScriptState::Scope scope(script_state_);
-
- const base::Optional<bool> is_locked = IsStreamLocked(exception_state);
- if (exception_state.HadException() || is_locked.value())
- return;
-
- ScriptValue reader = ReadableStreamOperations::GetReader(
- script_state_, Stream(), exception_state);
- if (exception_state.HadException()) {
- stream_broken_ = true;
- return;
- }
-
- ReadableStreamOperations::DefaultReaderRead(script_state_, reader);
+ stream_->LockAndDisturb(script_state_, exception_state);
}
bool BodyStreamBuffer::IsAborted() {
@@ -488,8 +430,9 @@ void BodyStreamBuffer::ProcessData() {
return;
DOMUint8Array* array = nullptr;
if (result == BytesConsumer::Result::kOk) {
- array = DOMUint8Array::Create(
- reinterpret_cast<const unsigned char*>(buffer), available);
+ array =
+ DOMUint8Array::Create(reinterpret_cast<const unsigned char*>(buffer),
+ SafeCast<uint32_t>(available));
result = consumer_->EndRead(available);
}
switch (result) {
@@ -533,9 +476,8 @@ void BodyStreamBuffer::StopLoading() {
}
base::Optional<bool> BodyStreamBuffer::BooleanStreamOperation(
- base::Optional<bool> (*predicate)(ScriptState*,
- ScriptValue,
- ExceptionState&),
+ base::Optional<bool> (ReadableStream::*predicate)(ScriptState*,
+ ExceptionState&) const,
ExceptionState& exception_state) {
if (stream_broken_) {
exception_state.ThrowDOMException(
@@ -545,7 +487,7 @@ base::Optional<bool> BodyStreamBuffer::BooleanStreamOperation(
}
ScriptState::Scope scope(script_state_);
base::Optional<bool> result =
- predicate(script_state_, Stream(), exception_state);
+ (stream_->*predicate)(script_state_, exception_state);
if (exception_state.HadException()) {
stream_broken_ = true;
return base::nullopt;
@@ -555,8 +497,8 @@ base::Optional<bool> BodyStreamBuffer::BooleanStreamOperation(
BytesConsumer* BodyStreamBuffer::ReleaseHandle(
ExceptionState& exception_state) {
- DCHECK(!IsStreamLockedForDCheck());
- DCHECK(!IsStreamDisturbedForDCheck());
+ DCHECK(!IsStreamLockedForDCheck(exception_state));
+ DCHECK(!IsStreamDisturbedForDCheck(exception_state));
if (stream_broken_) {
exception_state.ThrowDOMException(
@@ -574,13 +516,13 @@ BytesConsumer* BodyStreamBuffer::ReleaseHandle(
// - StartLoading makes HasPendingActivity return true while loading.
// - ReadableStream holds a reference to |reader| inside JS.
// we don't need to keep the reader explicitly.
- ScriptValue reader = ReadableStreamOperations::GetReader(
- script_state_, Stream(), exception_state);
+ ScriptValue reader = stream_->getReader(script_state_, exception_state);
if (exception_state.HadException()) {
stream_broken_ = true;
return nullptr;
}
- return new ReadableStreamBytesConsumer(script_state_, reader);
+ return MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state_,
+ reader);
}
// We need to call these before calling CloseAndLockAndDisturb.
const base::Optional<bool> is_closed = IsStreamClosed(exception_state);
diff --git a/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.h b/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.h
index febd613c288..69c746a98b5 100644
--- a/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.h
+++ b/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.h
@@ -23,6 +23,7 @@ namespace blink {
class EncodedFormData;
class ExceptionState;
+class ReadableStream;
class ScriptState;
class CORE_EXPORT BodyStreamBuffer final : public UnderlyingSourceBase,
@@ -37,11 +38,9 @@ class CORE_EXPORT BodyStreamBuffer final : public UnderlyingSourceBase,
BodyStreamBuffer(ScriptState*,
BytesConsumer* /* consumer */,
AbortSignal* /* signal */);
- // |ReadableStreamOperations::isReadableStream(stream)| must hold.
- // This function must be called with entering an appropriate V8 context.
- BodyStreamBuffer(ScriptState*, ScriptValue stream, ExceptionState&);
+ BodyStreamBuffer(ScriptState*, ReadableStream* stream);
- ScriptValue Stream();
+ ReadableStream* Stream() { return stream_; }
// Callable only when neither locked nor disturbed.
scoped_refptr<BlobDataHandle> DrainAsBlobDataHandle(
@@ -67,9 +66,9 @@ class CORE_EXPORT BodyStreamBuffer final : public UnderlyingSourceBase,
base::Optional<bool> IsStreamClosed(ExceptionState&);
base::Optional<bool> IsStreamErrored(ExceptionState&);
base::Optional<bool> IsStreamLocked(ExceptionState&);
- bool IsStreamLockedForDCheck();
+ bool IsStreamLockedForDCheck(ExceptionState&);
base::Optional<bool> IsStreamDisturbed(ExceptionState&);
- bool IsStreamDisturbedForDCheck();
+ bool IsStreamDisturbedForDCheck(ExceptionState&);
void CloseAndLockAndDisturb(ExceptionState&);
ScriptState* GetScriptState() { return script_state_; }
@@ -90,17 +89,16 @@ class CORE_EXPORT BodyStreamBuffer final : public UnderlyingSourceBase,
void StopLoading();
// Implementation of IsStream*() methods. Delegates to |predicate|, one of the
- // methods defined in ReadableStreamOperations. Sets |stream_broken_| and
- // throws if |predicate| throws. Throws an exception if called when
- // |stream_broken_| is already true.
+ // methods defined in ReadableStream. Sets |stream_broken_| and throws if
+ // |predicate| throws. Throws an exception if called when |stream_broken_|
+ // is already true.
base::Optional<bool> BooleanStreamOperation(
- base::Optional<bool> (*predicate)(ScriptState*,
- ScriptValue,
- ExceptionState&),
+ base::Optional<bool> (ReadableStream::*predicate)(ScriptState*,
+ ExceptionState&) const,
ExceptionState& exception_state);
Member<ScriptState> script_state_;
- TraceWrapperV8Reference<v8::Object> stream_;
+ TraceWrapperMember<ReadableStream> stream_;
TraceWrapperMember<BytesConsumer> consumer_;
// We need this member to keep it alive while loading.
TraceWrapperMember<FetchDataLoader> loader_;
diff --git a/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc b/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc
index 69528dac237..02464aca51c 100644
--- a/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc
@@ -8,12 +8,17 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/fetch/blob_bytes_consumer.h"
#include "third_party/blink/renderer/core/fetch/bytes_consumer.h"
#include "third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h"
#include "third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h"
#include "third_party/blink/renderer/core/html/forms/form_data.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_default_controller_wrapper.h"
+#include "third_party/blink/renderer/core/streams/test_underlying_source.h"
+#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/blob/blob_url.h"
@@ -134,13 +139,26 @@ TEST_F(BodyStreamBufferTest, Tee) {
TEST_F(BodyStreamBufferTest, TeeFromHandleMadeFromStream) {
V8TestingScope scope;
NonThrowableExceptionState exception_state;
- ScriptValue stream = EvalWithPrintingError(
- scope.GetScriptState(),
- "stream = new ReadableStream({start: c => controller = c});"
- "controller.enqueue(new Uint8Array([0x41, 0x42]));"
- "controller.enqueue(new Uint8Array([0x55, 0x58]));"
- "controller.close();"
- "stream");
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* chunk1 = DOMUint8Array::Create(2);
+ chunk1->Data()[0] = 0x41;
+ chunk1->Data()[1] = 0x42;
+ auto* chunk2 = DOMUint8Array::Create(2);
+ chunk2->Data()[0] = 0x55;
+ chunk2->Data()[1] = 0x58;
+
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), underlying_source, 0);
+ ASSERT_TRUE(stream);
+
+ underlying_source->Enqueue(ScriptValue(scope.GetScriptState(),
+ ToV8(chunk1, scope.GetScriptState())));
+ underlying_source->Enqueue(ScriptValue(scope.GetScriptState(),
+ ToV8(chunk2, scope.GetScriptState())));
+ underlying_source->Close();
+
Checkpoint checkpoint;
MockFetchDataLoaderClient* client1 = MockFetchDataLoaderClient::Create();
MockFetchDataLoaderClient* client2 = MockFetchDataLoaderClient::Create();
@@ -154,7 +172,7 @@ TEST_F(BodyStreamBufferTest, TeeFromHandleMadeFromStream) {
EXPECT_CALL(checkpoint, Call(4));
BodyStreamBuffer* buffer =
- new BodyStreamBuffer(scope.GetScriptState(), stream, exception_state);
+ new BodyStreamBuffer(scope.GetScriptState(), stream);
BodyStreamBuffer* new1;
BodyStreamBuffer* new2;
@@ -237,10 +255,11 @@ TEST_F(BodyStreamBufferTest,
DrainAsBlobFromBufferMadeFromBufferMadeFromStream) {
V8TestingScope scope;
NonThrowableExceptionState exception_state;
- ScriptValue stream =
- EvalWithPrintingError(scope.GetScriptState(), "new ReadableStream()");
+ auto* stream =
+ ReadableStream::Create(scope.GetScriptState(), exception_state);
+ ASSERT_TRUE(stream);
BodyStreamBuffer* buffer =
- new BodyStreamBuffer(scope.GetScriptState(), stream, exception_state);
+ new BodyStreamBuffer(scope.GetScriptState(), stream);
EXPECT_FALSE(buffer->HasPendingActivity());
EXPECT_FALSE(buffer->IsStreamLocked(exception_state).value_or(true));
@@ -265,10 +284,11 @@ TEST_F(BodyStreamBufferTest, DrainAsFormData) {
scoped_refptr<EncodedFormData> input_form_data =
data->EncodeMultiPartFormData();
- BodyStreamBuffer* buffer = new BodyStreamBuffer(
- scope.GetScriptState(),
- new FormDataBytesConsumer(scope.GetExecutionContext(), input_form_data),
- nullptr);
+ BodyStreamBuffer* buffer =
+ new BodyStreamBuffer(scope.GetScriptState(),
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ scope.GetExecutionContext(), input_form_data),
+ nullptr);
EXPECT_FALSE(buffer->IsStreamLocked(ASSERT_NO_EXCEPTION).value_or(true));
EXPECT_FALSE(buffer->IsStreamDisturbed(ASSERT_NO_EXCEPTION).value_or(true));
@@ -305,10 +325,10 @@ TEST_F(BodyStreamBufferTest,
DrainAsFormDataFromBufferMadeFromBufferMadeFromStream) {
V8TestingScope scope;
NonThrowableExceptionState exception_state;
- ScriptValue stream =
- EvalWithPrintingError(scope.GetScriptState(), "new ReadableStream()");
+ auto* stream =
+ ReadableStream::Create(scope.GetScriptState(), exception_state);
BodyStreamBuffer* buffer =
- new BodyStreamBuffer(scope.GetScriptState(), stream, exception_state);
+ new BodyStreamBuffer(scope.GetScriptState(), stream);
EXPECT_FALSE(buffer->HasPendingActivity());
EXPECT_FALSE(buffer->IsStreamLocked(exception_state).value_or(true));
@@ -543,7 +563,8 @@ TEST_F(BodyStreamBufferTest, NestedPull) {
auto result =
scope.GetScriptState()->GetContext()->Global()->CreateDataProperty(
scope.GetScriptState()->GetContext(),
- V8String(scope.GetIsolate(), "stream"), buffer->Stream().V8Value());
+ V8String(scope.GetIsolate(), "stream"),
+ ToV8(buffer->Stream(), scope.GetScriptState()));
ASSERT_TRUE(result.IsJust());
ASSERT_TRUE(result.FromJust());
diff --git a/chromium/third_party/blink/renderer/core/fetch/bytes_consumer.cc b/chromium/third_party/blink/renderer/core/fetch/bytes_consumer.cc
index af91e44505f..c8c77e1a933 100644
--- a/chromium/third_party/blink/renderer/core/fetch/bytes_consumer.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/bytes_consumer.cc
@@ -10,10 +10,12 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fetch/blob_bytes_consumer.h"
+#include "third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "v8/include/v8.h"
namespace blink {
@@ -62,7 +64,7 @@ class TeeHelper final : public GarbageCollectedFinalized<TeeHelper>,
}
Chunk* chunk = nullptr;
if (result == Result::kOk) {
- chunk = new Chunk(buffer, available);
+ chunk = new Chunk(buffer, SafeCast<wtf_size_t>(available));
result = src_->EndRead(available);
}
switch (result) {
@@ -115,7 +117,7 @@ class TeeHelper final : public GarbageCollectedFinalized<TeeHelper>,
using Result = BytesConsumer::Result;
class Chunk final : public GarbageCollectedFinalized<Chunk> {
public:
- Chunk(const char* data, size_t size) {
+ Chunk(const char* data, wtf_size_t size) {
buffer_.ReserveInitialCapacity(size);
buffer_.Append(data, size);
// Report buffer size to V8 so GC can be triggered appropriately.
@@ -127,7 +129,7 @@ class TeeHelper final : public GarbageCollectedFinalized<TeeHelper>,
-static_cast<int64_t>(buffer_.size()));
}
const char* data() const { return buffer_.data(); }
- size_t size() const { return buffer_.size(); }
+ wtf_size_t size() const { return buffer_.size(); }
void Trace(blink::Visitor* visitor) {}
@@ -371,6 +373,17 @@ void BytesConsumer::Tee(ExecutionContext* execution_context,
return;
}
+ auto form_data = src->DrainAsFormData();
+ if (form_data) {
+ // Register a client in order to be consistent.
+ src->SetClient(MakeGarbageCollected<NoopClient>());
+ *dest1 = MakeGarbageCollected<FormDataBytesConsumer>(execution_context,
+ form_data);
+ *dest2 = MakeGarbageCollected<FormDataBytesConsumer>(execution_context,
+ form_data);
+ return;
+ }
+
TeeHelper* tee = new TeeHelper(execution_context, src);
*dest1 = tee->Destination1();
*dest2 = tee->Destination2();
diff --git a/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.cc b/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.cc
index 6bbe395bb4f..93bdfddbd84 100644
--- a/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.cc
@@ -177,7 +177,8 @@ void BytesConsumerTestUtil::TwoPhaseReader::OnStateChange() {
// We don't use |available| as-is to test cases where endRead
// is called with a number smaller than |available|. We choose 3
// because of the same reasons as Reader::onStateChange.
- size_t read = std::min(static_cast<size_t>(3), available);
+ wtf_size_t read =
+ static_cast<wtf_size_t>(std::min(static_cast<size_t>(3), available));
data_.Append(buffer, read);
result = consumer_->EndRead(read);
}
diff --git a/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h b/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h
index efe0480ff8a..17acda4e944 100644
--- a/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h
+++ b/chromium/third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h
@@ -93,10 +93,11 @@ class BytesConsumerTestUtil {
explicit Command(Name name) : name_(name) {}
Command(Name name, const Vector<char>& body) : name_(name), body_(body) {}
- Command(Name name, const char* body, size_t size) : name_(name) {
+ Command(Name name, const char* body, wtf_size_t size) : name_(name) {
body_.Append(body, size);
}
- Command(Name name, const char* body) : Command(name, body, strlen(body)) {}
+ Command(Name name, const char* body)
+ : Command(name, body, static_cast<wtf_size_t>(strlen(body))) {}
Name GetName() const { return name_; }
const Vector<char>& Body() const { return body_; }
diff --git a/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.cc b/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.cc
index 5bdf72228e5..d89898bb637 100644
--- a/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.cc
@@ -74,7 +74,7 @@ void DataConsumerHandleTestUtil::Thread::Initialize() {
DOMWrapperWorld::WorldType::kTesting));
}
if (initialization_policy_ >= kWithExecutionContext) {
- execution_context_ = new NullExecutionContext();
+ execution_context_ = MakeGarbageCollected<NullExecutionContext>();
}
waitable_event_->Signal();
}
@@ -129,7 +129,7 @@ void DataConsumerHandleTestUtil::ReplayingHandle::Context::AttachReader(
MutexLocker locker(mutex_);
DCHECK(!reader_thread_);
DCHECK(!client_);
- reader_thread_ = Platform::Current()->CurrentThread();
+ reader_thread_ = blink::Thread::Current();
client_ = client;
if (client_ && !(IsEmpty() && result_ == kShouldWait))
diff --git a/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.h b/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.h
index bd654a3ac1b..7e68118d4cb 100644
--- a/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.h
+++ b/chromium/third_party/blink/renderer/core/fetch/data_consumer_handle_test_util.h
@@ -347,10 +347,11 @@ class DataConsumerHandleTestUtil {
Command(Name name) : name_(name) {}
Command(Name name, const Vector<char>& body) : name_(name), body_(body) {}
- Command(Name name, const char* body, size_t size) : name_(name) {
+ Command(Name name, const char* body, wtf_size_t size) : name_(name) {
body_.Append(body, size);
}
- Command(Name name, const char* body) : Command(name, body, strlen(body)) {}
+ Command(Name name, const char* body)
+ : Command(name, body, static_cast<wtf_size_t>(strlen(body))) {}
Name GetName() const { return name_; }
const Vector<char>& Body() const { return body_; }
diff --git a/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.cc b/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.cc
index e4ddf9b9a59..6f7b6080b58 100644
--- a/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.cc
@@ -14,16 +14,32 @@
namespace blink {
+void DataPipeBytesConsumer::CompletionNotifier::SignalComplete() {
+ if (bytes_consumer_)
+ bytes_consumer_->SignalComplete();
+}
+
+void DataPipeBytesConsumer::CompletionNotifier::SignalError(
+ const BytesConsumer::Error& error) {
+ if (bytes_consumer_)
+ bytes_consumer_->SignalError(error);
+}
+
+void DataPipeBytesConsumer::CompletionNotifier::Trace(Visitor* visitor) {
+ visitor->Trace(bytes_consumer_);
+}
+
DataPipeBytesConsumer::DataPipeBytesConsumer(
ExecutionContext* execution_context,
- mojo::ScopedDataPipeConsumerHandle data_pipe)
+ mojo::ScopedDataPipeConsumerHandle data_pipe,
+ CompletionNotifier** notifier)
: execution_context_(execution_context),
data_pipe_(std::move(data_pipe)),
watcher_(FROM_HERE,
mojo::SimpleWatcher::ArmingPolicy::MANUAL,
execution_context->GetTaskRunner(TaskType::kNetworking)) {
- if (!data_pipe_.is_valid())
- return;
+ DCHECK(data_pipe_.is_valid());
+ *notifier = new CompletionNotifier(this);
watcher_.Watch(
data_pipe_.get(),
MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
@@ -69,7 +85,7 @@ BytesConsumer::Result DataPipeBytesConsumer::BeginRead(const char** buffer,
return Result::kShouldWait;
return Result::kDone;
default:
- SetError();
+ SetError(Error("error"));
return Result::kError;
}
@@ -82,7 +98,7 @@ BytesConsumer::Result DataPipeBytesConsumer::EndRead(size_t read) {
DCHECK(IsReadableOrWaiting());
MojoResult rv = data_pipe_->EndReadData(read);
if (rv != MOJO_RESULT_OK) {
- SetError();
+ SetError(Error("error"));
return Result::kError;
}
if (has_pending_complete_) {
@@ -92,7 +108,7 @@ BytesConsumer::Result DataPipeBytesConsumer::EndRead(size_t read) {
}
if (has_pending_error_) {
has_pending_error_ = false;
- SignalError();
+ SignalError(Error("error"));
return Result::kError;
}
if (has_pending_notification_) {
@@ -127,6 +143,7 @@ void DataPipeBytesConsumer::ClearClient() {
void DataPipeBytesConsumer::Cancel() {
DCHECK(!is_in_two_phase_read_);
+ ClearClient();
ClearDataPipe();
SignalComplete();
}
@@ -176,7 +193,7 @@ void DataPipeBytesConsumer::SignalComplete() {
watcher_.ArmOrNotify();
}
-void DataPipeBytesConsumer::SignalError() {
+void DataPipeBytesConsumer::SignalError(const Error& error) {
if (!IsReadableOrWaiting() || has_pending_complete_ || has_pending_error_)
return;
if (is_in_two_phase_read_) {
@@ -186,18 +203,18 @@ void DataPipeBytesConsumer::SignalError() {
Client* client = client_;
// When we hit an error we switch states immediately. We don't wait for the
// end of the pipe to be read.
- SetError();
+ SetError(error);
if (client)
client->OnStateChange();
}
-void DataPipeBytesConsumer::SetError() {
+void DataPipeBytesConsumer::SetError(const Error& error) {
DCHECK(!is_in_two_phase_read_);
if (!IsReadableOrWaiting())
return;
ClearDataPipe();
state_ = InternalState::kErrored;
- error_ = Error("error");
+ error_ = error;
ClearClient();
}
@@ -244,4 +261,8 @@ void DataPipeBytesConsumer::ClearDataPipe() {
data_pipe_.reset();
}
+void DataPipeBytesConsumer::Dispose() {
+ watcher_.Cancel();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h b/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h
index 240c0b94def..eb986df4881 100644
--- a/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h
+++ b/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h
@@ -18,9 +18,34 @@ namespace blink {
class ExecutionContext;
+// An adapter for mojo::DataPipe. As mojo::DataPipe lacks signals completion and
+// error signals, we define another interface, CompletionNotifier, for the
+// signals.
class CORE_EXPORT DataPipeBytesConsumer final : public BytesConsumer {
+ USING_PRE_FINALIZER(DataPipeBytesConsumer, Dispose);
+
public:
- DataPipeBytesConsumer(ExecutionContext*, mojo::ScopedDataPipeConsumerHandle);
+ class CORE_EXPORT CompletionNotifier final
+ : public GarbageCollected<CompletionNotifier> {
+ public:
+ explicit CompletionNotifier(DataPipeBytesConsumer* bytes_consumer)
+ : bytes_consumer_(bytes_consumer) {}
+
+ // One of these methods must be called to signal the end of the data
+ // stream. We cannot assume that the end of the pipe completes the
+ // stream successfully since errors can occur after the last byte is
+ // written into the pipe.
+ void SignalComplete();
+ void SignalError(const BytesConsumer::Error& error);
+ void Trace(blink::Visitor*);
+
+ private:
+ const WeakMember<DataPipeBytesConsumer> bytes_consumer_;
+ };
+
+ DataPipeBytesConsumer(ExecutionContext*,
+ mojo::ScopedDataPipeConsumerHandle,
+ CompletionNotifier** notifier);
~DataPipeBytesConsumer() override;
Result BeginRead(const char** buffer, size_t* available) override;
@@ -39,19 +64,15 @@ class CORE_EXPORT DataPipeBytesConsumer final : public BytesConsumer {
void Trace(blink::Visitor*) override;
- // One of these methods must be called to signal the end of the data
- // stream. We cannot assume that the end of the pipe completes the
- // stream successfully since errors can occur after the last byte is
- // written into the pipe.
- void SignalComplete();
- void SignalError();
-
private:
bool IsReadableOrWaiting() const;
void MaybeClose();
- void SetError();
+ void SetError(const Error& error);
void Notify(MojoResult);
void ClearDataPipe();
+ void SignalComplete();
+ void SignalError(const Error& error);
+ void Dispose();
Member<ExecutionContext> execution_context_;
mojo::ScopedDataPipeConsumerHandle data_pipe_;
diff --git a/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer_test.cc b/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer_test.cc
index b1fce5d316c..843a98e6500 100644
--- a/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer_test.cc
@@ -32,9 +32,10 @@ TEST_F(DataPipeBytesConsumerTest, TwoPhaseRead) {
// completion is signaled below.
pipe.producer_handle.reset();
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
- consumer->SignalComplete();
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
+ notifier->SignalComplete();
auto result = (new BytesConsumerTestUtil::TwoPhaseReader(consumer))->Run();
EXPECT_EQ(Result::kDone, result.first);
EXPECT_EQ(
@@ -56,12 +57,13 @@ TEST_F(DataPipeBytesConsumerTest, TwoPhaseRead_SignalError) {
pipe.producer_handle.reset();
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
// Then explicitly signal an error. This should override the pipe completion
// and result in kError.
- consumer->SignalError();
+ notifier->SignalError(BytesConsumer::Error());
auto result = (new BytesConsumerTestUtil::TwoPhaseReader(consumer))->Run();
EXPECT_EQ(Result::kError, result.first);
@@ -75,8 +77,9 @@ TEST_F(DataPipeBytesConsumerTest, EndOfPipeBeforeComplete) {
mojo::DataPipe pipe;
ASSERT_TRUE(pipe.producer_handle.is_valid());
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
@@ -91,7 +94,7 @@ TEST_F(DataPipeBytesConsumerTest, EndOfPipeBeforeComplete) {
EXPECT_EQ(Result::kShouldWait, rv);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
- consumer->SignalComplete();
+ notifier->SignalComplete();
EXPECT_EQ(PublicState::kClosed, consumer->GetPublicState());
rv = consumer->BeginRead(&buffer, &available);
@@ -102,8 +105,9 @@ TEST_F(DataPipeBytesConsumerTest, CompleteBeforeEndOfPipe) {
mojo::DataPipe pipe;
ASSERT_TRUE(pipe.producer_handle.is_valid());
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
@@ -113,7 +117,7 @@ TEST_F(DataPipeBytesConsumerTest, CompleteBeforeEndOfPipe) {
Result rv = consumer->BeginRead(&buffer, &available);
EXPECT_EQ(Result::kShouldWait, rv);
- consumer->SignalComplete();
+ notifier->SignalComplete();
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
rv = consumer->BeginRead(&buffer, &available);
@@ -132,8 +136,9 @@ TEST_F(DataPipeBytesConsumerTest, EndOfPipeBeforeError) {
mojo::DataPipe pipe;
ASSERT_TRUE(pipe.producer_handle.is_valid());
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
@@ -148,7 +153,7 @@ TEST_F(DataPipeBytesConsumerTest, EndOfPipeBeforeError) {
EXPECT_EQ(Result::kShouldWait, rv);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
- consumer->SignalError();
+ notifier->SignalError(BytesConsumer::Error());
EXPECT_EQ(PublicState::kErrored, consumer->GetPublicState());
rv = consumer->BeginRead(&buffer, &available);
@@ -159,8 +164,9 @@ TEST_F(DataPipeBytesConsumerTest, ErrorBeforeEndOfPipe) {
mojo::DataPipe pipe;
ASSERT_TRUE(pipe.producer_handle.is_valid());
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
@@ -170,7 +176,7 @@ TEST_F(DataPipeBytesConsumerTest, ErrorBeforeEndOfPipe) {
Result rv = consumer->BeginRead(&buffer, &available);
EXPECT_EQ(Result::kShouldWait, rv);
- consumer->SignalError();
+ notifier->SignalError(BytesConsumer::Error());
EXPECT_EQ(PublicState::kErrored, consumer->GetPublicState());
rv = consumer->BeginRead(&buffer, &available);
@@ -188,8 +194,9 @@ TEST_F(DataPipeBytesConsumerTest, DrainPipeBeforeComplete) {
mojo::DataPipe pipe;
ASSERT_TRUE(pipe.producer_handle.is_valid());
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
@@ -206,7 +213,7 @@ TEST_F(DataPipeBytesConsumerTest, DrainPipeBeforeComplete) {
EXPECT_EQ(Result::kShouldWait, rv);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
- consumer->SignalComplete();
+ notifier->SignalComplete();
EXPECT_EQ(PublicState::kClosed, consumer->GetPublicState());
rv = consumer->BeginRead(&buffer, &available);
@@ -217,8 +224,9 @@ TEST_F(DataPipeBytesConsumerTest, CompleteBeforeDrainPipe) {
mojo::DataPipe pipe;
ASSERT_TRUE(pipe.producer_handle.is_valid());
+ DataPipeBytesConsumer::CompletionNotifier* notifier = nullptr;
DataPipeBytesConsumer* consumer = new DataPipeBytesConsumer(
- &GetDocument(), std::move(pipe.consumer_handle));
+ &GetDocument(), std::move(pipe.consumer_handle), &notifier);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
@@ -228,7 +236,7 @@ TEST_F(DataPipeBytesConsumerTest, CompleteBeforeDrainPipe) {
Result rv = consumer->BeginRead(&buffer, &available);
EXPECT_EQ(Result::kShouldWait, rv);
- consumer->SignalComplete();
+ notifier->SignalComplete();
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
rv = consumer->BeginRead(&buffer, &available);
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_data_loader.cc b/chromium/third_party/blink/renderer/core/fetch/fetch_data_loader.cc
index e0ab571309d..01df3bd6def 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_data_loader.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_data_loader.cc
@@ -16,6 +16,7 @@
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/parsed_content_disposition.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.h"
@@ -140,7 +141,8 @@ class FetchDataLoaderAsArrayBuffer final : public FetchDataLoader,
return;
if (result == BytesConsumer::Result::kOk) {
if (available > 0) {
- unsigned bytes_appended = raw_data_->Append(buffer, available);
+ unsigned bytes_appended =
+ raw_data_->Append(buffer, SafeCast<wtf_size_t>(available));
if (!bytes_appended) {
auto unused = consumer_->EndRead(0);
ALLOW_UNUSED_LOCAL(unused);
@@ -262,8 +264,8 @@ class FetchDataLoaderAsFormData final : public FetchDataLoader,
client_ = client;
form_data_ = FormData::Create();
- multipart_parser_ =
- new MultipartParser(std::move(multipart_boundary_vector), this);
+ multipart_parser_ = MakeGarbageCollected<MultipartParser>(
+ std::move(multipart_boundary_vector), this);
consumer_ = consumer;
consumer_->SetClient(this);
OnStateChange();
@@ -343,7 +345,7 @@ class FetchDataLoaderAsFormData final : public FetchDataLoader,
public:
bool Initialize(const HTTPHeaderMap& header_fields) {
const ParsedContentDisposition disposition(
- header_fields.Get(HTTPNames::Content_Disposition));
+ header_fields.Get(http_names::kContentDisposition));
const String disposition_type = disposition.Type();
filename_ = disposition.Filename();
name_ = disposition.ParameterValueForName("name");
@@ -354,7 +356,7 @@ class FetchDataLoaderAsFormData final : public FetchDataLoader,
if (!filename_.IsNull()) {
blob_data_ = BlobData::Create();
const AtomicString& content_type =
- header_fields.Get(HTTPNames::Content_Type);
+ header_fields.Get(http_names::kContentType);
blob_data_->SetContentType(content_type.IsNull() ? "text/plain"
: content_type);
} else {
@@ -483,6 +485,7 @@ class FetchDataLoaderAsString final : public FetchDataLoader,
class FetchDataLoaderAsDataPipe final : public FetchDataLoader,
public BytesConsumer::Client {
USING_GARBAGE_COLLECTED_MIXIN(FetchDataLoaderAsDataPipe);
+ USING_PRE_FINALIZER(FetchDataLoaderAsDataPipe, Dispose);
public:
explicit FetchDataLoaderAsDataPipe(
@@ -561,7 +564,7 @@ class FetchDataLoaderAsDataPipe final : public FetchDataLoader,
if (available == 0) {
result = consumer_->EndRead(0);
} else {
- uint32_t num_bytes = available;
+ uint32_t num_bytes = SafeCast<uint32_t>(available);
MojoResult mojo_result = out_data_pipe_->WriteData(
buffer, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE);
if (mojo_result == MOJO_RESULT_OK) {
@@ -614,6 +617,8 @@ class FetchDataLoaderAsDataPipe final : public FetchDataLoader,
out_data_pipe_.reset();
}
+ void Dispose() { data_pipe_watcher_.Cancel(); }
+
TraceWrapperMember<BytesConsumer> consumer_;
Member<FetchDataLoader::Client> client_;
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.cc b/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.cc
index 473013ed66e..496df603871 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.cc
@@ -13,7 +13,7 @@
namespace blink {
FetchHeaderList* FetchHeaderList::Create() {
- return new FetchHeaderList();
+ return MakeGarbageCollected<FetchHeaderList>();
}
FetchHeaderList* FetchHeaderList::Clone() const {
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.h b/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.h
index 51d1c8af6be..28178044fe1 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.h
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_header_list.h
@@ -28,7 +28,9 @@ class CORE_EXPORT FetchHeaderList final
static FetchHeaderList* Create();
FetchHeaderList* Clone() const;
+ FetchHeaderList();
~FetchHeaderList();
+
void Append(const String&, const String&);
void Set(const String&, const String&);
// FIXME: Implement parse()
@@ -53,8 +55,6 @@ class CORE_EXPORT FetchHeaderList final
void Trace(blink::Visitor* visitor) {}
private:
- FetchHeaderList();
-
// While using STL data structures in Blink is not very common or
// encouraged, we do need a multimap here. The closest WTF structure
// comparable to what we need would be a
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc b/chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc
index 4c22a80054b..c14847a8eb6 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc
@@ -7,7 +7,6 @@
#include <memory>
#include "base/single_thread_task_runner.h"
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
-#include "third_party/blink/public/platform/web_cors.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
@@ -36,7 +35,6 @@
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
-#include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
@@ -55,6 +53,7 @@
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -106,7 +105,7 @@ class EmptyDataHandle final : public WebDataConsumerHandle {
bool HasNonEmptyLocationHeader(const FetchHeaderList* headers) {
String value;
- if (!headers->Get(HTTPNames::Location, value))
+ if (!headers->Get(http_names::kLocation, value))
return false;
return !value.IsEmpty();
}
@@ -202,7 +201,7 @@ class SRIBytesConsumer final : public BytesConsumer {
class FetchManager::Loader final
: public GarbageCollectedFinalized<FetchManager::Loader>,
public ThreadableLoaderClient {
- USING_PRE_FINALIZER(FetchManager::Loader, Dispose);
+ USING_GARBAGE_COLLECTED_MIXIN(Loader);
public:
static Loader* Create(ExecutionContext* execution_context,
@@ -211,12 +210,19 @@ class FetchManager::Loader final
FetchRequestData* request,
bool is_isolated_world,
AbortSignal* signal) {
- return new Loader(execution_context, fetch_manager, resolver, request,
- is_isolated_world, signal);
+ return MakeGarbageCollected<Loader>(execution_context, fetch_manager,
+ resolver, request, is_isolated_world,
+ signal);
}
+ Loader(ExecutionContext*,
+ FetchManager*,
+ ScriptPromiseResolver*,
+ FetchRequestData*,
+ bool is_isolated_world,
+ AbortSignal*);
~Loader() override;
- virtual void Trace(blink::Visitor*);
+ void Trace(blink::Visitor*) override;
bool WillFollowRedirect(const KURL&, const ResourceResponse&) override;
void DidReceiveResponse(unsigned long,
@@ -274,7 +280,8 @@ class FetchManager::Loader final
r = reader_->BeginRead(&buffer, WebDataConsumerHandle::kFlagNone,
&size);
if (r == WebDataConsumerHandle::kOk) {
- buffer_.Append(static_cast<const char*>(buffer), size);
+ buffer_.Append(static_cast<const char*>(buffer),
+ SafeCast<wtf_size_t>(size));
reader_->EndRead(size);
}
}
@@ -287,7 +294,7 @@ class FetchManager::Loader final
SubresourceIntegrity::ReportInfo report_info;
bool check_result = true;
if (response_type_ != FetchResponseType::kBasic &&
- response_type_ != FetchResponseType::kCORS &&
+ response_type_ != FetchResponseType::kCors &&
response_type_ != FetchResponseType::kDefault) {
report_info.AddConsoleErrorMessage(
"Subresource Integrity: The resource '" + url_.ElidedString() +
@@ -305,8 +312,8 @@ class FetchManager::Loader final
SubresourceIntegrityHelper::DoReport(*loader_->GetExecutionContext(),
report_info);
if (check_result) {
- updater_->Update(
- new FormDataBytesConsumer(buffer_.data(), buffer_.size()));
+ updater_->Update(MakeGarbageCollected<FormDataBytesConsumer>(
+ buffer_.data(), buffer_.size()));
loader_->resolver_->Resolve(response_);
loader_->resolver_.Clear();
// FetchManager::Loader::didFinishLoading() can
@@ -349,13 +356,6 @@ class FetchManager::Loader final
};
private:
- Loader(ExecutionContext*,
- FetchManager*,
- ScriptPromiseResolver*,
- FetchRequestData*,
- bool is_isolated_world,
- AbortSignal*);
-
void PerformSchemeFetch(ExceptionState&);
void PerformNetworkError(const String& message);
void PerformHTTPFetch(ExceptionState&);
@@ -413,6 +413,7 @@ void FetchManager::Loader::Trace(blink::Visitor* visitor) {
visitor->Trace(integrity_verifier_);
visitor->Trace(signal_);
visitor->Trace(execution_context_);
+ ThreadableLoaderClient::Trace(visitor);
}
bool FetchManager::Loader::WillFollowRedirect(
@@ -472,12 +473,12 @@ void FetchManager::Loader::DidReceiveResponse(
// TODO(hiroshige): currently redirects to data URLs in no-cors
// mode is also rejected by Chromium side.
switch (fetch_request_data_->Mode()) {
- case FetchRequestMode::kNoCORS:
+ case FetchRequestMode::kNoCors:
tainting = FetchRequestData::kOpaqueTainting;
break;
case FetchRequestMode::kSameOrigin:
- case FetchRequestMode::kCORS:
- case FetchRequestMode::kCORSWithForcedPreflight:
+ case FetchRequestMode::kCors:
+ case FetchRequestMode::kCorsWithForcedPreflight:
case FetchRequestMode::kNavigate:
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
@@ -494,12 +495,12 @@ void FetchManager::Loader::DidReceiveResponse(
case FetchRequestMode::kSameOrigin:
NOTREACHED();
break;
- case FetchRequestMode::kNoCORS:
+ case FetchRequestMode::kNoCors:
tainting = FetchRequestData::kOpaqueTainting;
break;
- case FetchRequestMode::kCORS:
- case FetchRequestMode::kCORSWithForcedPreflight:
- tainting = FetchRequestData::kCORSTainting;
+ case FetchRequestMode::kCors:
+ case FetchRequestMode::kCorsWithForcedPreflight:
+ tainting = FetchRequestData::kCorsTainting;
break;
case FetchRequestMode::kNavigate:
LOG(FATAL);
@@ -512,15 +513,15 @@ void FetchManager::Loader::DidReceiveResponse(
case FetchResponseType::kDefault:
tainting = FetchRequestData::kBasicTainting;
break;
- case FetchResponseType::kCORS:
- tainting = FetchRequestData::kCORSTainting;
+ case FetchResponseType::kCors:
+ tainting = FetchRequestData::kCorsTainting;
break;
case FetchResponseType::kOpaque:
tainting = FetchRequestData::kOpaqueTainting;
break;
case FetchResponseType::kOpaqueRedirect:
DCHECK(
- NetworkUtils::IsRedirectResponseCode(response_http_status_code_));
+ network_utils::IsRedirectResponseCode(response_http_status_code_));
break; // The code below creates an opaque-redirect filtered response.
case FetchResponseType::kError:
LOG(FATAL) << "When ServiceWorker respond to the request from fetch() "
@@ -556,7 +557,7 @@ void FetchManager::Loader::DidReceiveResponse(
if (response.UrlListViaServiceWorker().IsEmpty()) {
// Note: |urlListViaServiceWorker| is empty, unless the response came from a
// service worker, in which case it will only be empty if it was created
- // through new Response().
+ // through MakeGarbageCollected<Response>().
response_data->SetURLList(url_list_);
} else {
DCHECK(response.WasFetchedViaServiceWorker());
@@ -567,11 +568,11 @@ void FetchManager::Loader::DidReceiveResponse(
FetchResponseData* tainted_response = nullptr;
- DCHECK(!(NetworkUtils::IsRedirectResponseCode(response_http_status_code_) &&
+ DCHECK(!(network_utils::IsRedirectResponseCode(response_http_status_code_) &&
HasNonEmptyLocationHeader(response_data->HeaderList()) &&
fetch_request_data_->Redirect() != FetchRedirectMode::kManual));
- if (NetworkUtils::IsRedirectResponseCode(response_http_status_code_) &&
+ if (network_utils::IsRedirectResponseCode(response_http_status_code_) &&
fetch_request_data_->Redirect() == FetchRedirectMode::kManual) {
tainted_response = response_data->CreateOpaqueRedirectFilteredResponse();
} else {
@@ -579,13 +580,11 @@ void FetchManager::Loader::DidReceiveResponse(
case FetchRequestData::kBasicTainting:
tainted_response = response_data->CreateBasicFilteredResponse();
break;
- case FetchRequestData::kCORSTainting: {
- WebHTTPHeaderSet header_names =
- WebCORS::ExtractCorsExposedHeaderNamesList(
- fetch_request_data_->Credentials(),
- WrappedResourceResponse(response));
+ case FetchRequestData::kCorsTainting: {
+ WebHTTPHeaderSet header_names = cors::ExtractCorsExposedHeaderNamesList(
+ fetch_request_data_->Credentials(), response);
tainted_response =
- response_data->CreateCORSFilteredResponse(header_names);
+ response_data->CreateCorsFilteredResponse(header_names);
break;
}
case FetchRequestData::kOpaqueTainting:
@@ -603,7 +602,7 @@ void FetchManager::Loader::DidReceiveResponse(
resolver_.Clear();
} else {
DCHECK(!integrity_verifier_);
- integrity_verifier_ = new SRIVerifier(
+ integrity_verifier_ = MakeGarbageCollected<SRIVerifier>(
std::move(handle), sri_consumer, r, this,
fetch_request_data_->Integrity(), response.Url(),
r->GetResponse()->GetType(),
@@ -641,7 +640,7 @@ void FetchManager::Loader::LoadSucceeded() {
if (GetDocument() && GetDocument()->GetFrame() &&
GetDocument()->GetFrame()->GetPage() &&
- CORS::IsOkStatus(response_http_status_code_)) {
+ cors::IsOkStatus(response_http_status_code_)) {
GetDocument()->GetFrame()->GetPage()->GetChromeClient().AjaxSucceeded(
GetDocument()->GetFrame());
}
@@ -710,7 +709,7 @@ void FetchManager::Loader::Start(ExceptionState& exception_state) {
}
// "- |request|'s mode is |no CORS|"
- if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
+ if (fetch_request_data_->Mode() == FetchRequestMode::kNoCors) {
// "If |request|'s redirect mode is not |follow|, then return a network
// error.
if (fetch_request_data_->Redirect() != FetchRedirectMode::kFollow) {
@@ -741,7 +740,7 @@ void FetchManager::Loader::Start(ExceptionState& exception_state) {
}
// "Set |request|'s response tainting to |CORS|."
- fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);
+ fetch_request_data_->SetResponseTainting(FetchRequestData::kCorsTainting);
// "The result of performing an HTTP fetch using |request| with the
// |CORS flag| set."
@@ -817,9 +816,9 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
switch (fetch_request_data_->Mode()) {
case FetchRequestMode::kSameOrigin:
- case FetchRequestMode::kNoCORS:
- case FetchRequestMode::kCORS:
- case FetchRequestMode::kCORSWithForcedPreflight:
+ case FetchRequestMode::kNoCors:
+ case FetchRequestMode::kCors:
+ case FetchRequestMode::kCorsWithForcedPreflight:
request.SetFetchRequestMode(fetch_request_data_->Mode());
break;
case FetchRequestMode::kNavigate:
@@ -834,14 +833,14 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
// Since |fetch_request_data_|'s headers are populated with either of the
// "request" guard or "request-no-cors" guard, we can assume that none of
// the headers have a name listed in the forbidden header names.
- DCHECK(!CORS::IsForbiddenHeaderName(header.first));
+ DCHECK(!cors::IsForbiddenHeaderName(header.first));
request.AddHTTPHeaderField(AtomicString(header.first),
AtomicString(header.second));
}
- if (fetch_request_data_->Method() != HTTPNames::GET &&
- fetch_request_data_->Method() != HTTPNames::HEAD) {
+ if (fetch_request_data_->Method() != http_names::kGET &&
+ fetch_request_data_->Method() != http_names::kHEAD) {
if (fetch_request_data_->Buffer()) {
request.SetHTTPBody(
fetch_request_data_->Buffer()->DrainAsFormData(exception_state));
@@ -862,8 +861,8 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
request.SetSkipServiceWorker(is_isolated_world_);
if (fetch_request_data_->Keepalive()) {
- if (!CORS::IsCORSSafelistedMethod(request.HttpMethod()) ||
- !CORS::ContainsOnlyCORSSafelistedOrForbiddenHeaders(
+ if (!cors::IsCorsSafelistedMethod(request.HttpMethod()) ||
+ !cors::ContainsOnlyCorsSafelistedOrForbiddenHeaders(
request.HttpHeaderFields())) {
PerformNetworkError(
"Preflight request for request with keepalive "
@@ -887,7 +886,8 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
// and the |CORS flag| is unset, and unset otherwise."
ResourceLoaderOptions resource_loader_options;
- resource_loader_options.initiator_info.name = FetchInitiatorTypeNames::fetch;
+ resource_loader_options.initiator_info.name =
+ fetch_initiator_type_names::kFetch;
resource_loader_options.data_buffering_policy = kDoNotBufferData;
if (fetch_request_data_->URLLoaderFactory()) {
network::mojom::blink::URLLoaderFactoryPtr factory_clone;
@@ -897,8 +897,8 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
std::move(factory_clone));
}
- threadable_loader_ = new ThreadableLoader(*execution_context_, this,
- resource_loader_options);
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
+ *execution_context_, this, resource_loader_options);
threadable_loader_->Start(request);
}
@@ -924,8 +924,8 @@ void FetchManager::Loader::PerformDataFetch() {
ResourceLoaderOptions resource_loader_options;
resource_loader_options.data_buffering_policy = kDoNotBufferData;
- threadable_loader_ = new ThreadableLoader(*execution_context_, this,
- resource_loader_options);
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
+ *execution_context_, this, resource_loader_options);
threadable_loader_->Start(request);
}
@@ -954,7 +954,7 @@ void FetchManager::Loader::NotifyFinished() {
}
FetchManager* FetchManager::Create(ExecutionContext* execution_context) {
- return new FetchManager(execution_context);
+ return MakeGarbageCollected<FetchManager>(execution_context);
}
FetchManager::FetchManager(ExecutionContext* execution_context)
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_manager.h b/chromium/third_party/blink/renderer/core/fetch/fetch_manager.h
index f6e04ff36a4..521f05d8de6 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_manager.h
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_manager.h
@@ -24,6 +24,9 @@ class CORE_EXPORT FetchManager final : public GarbageCollected<FetchManager>,
public:
static FetchManager* Create(ExecutionContext*);
+
+ explicit FetchManager(ExecutionContext*);
+
ScriptPromise Fetch(ScriptState*,
FetchRequestData*,
AbortSignal*,
@@ -33,8 +36,6 @@ class CORE_EXPORT FetchManager final : public GarbageCollected<FetchManager>,
void Trace(blink::Visitor*) override;
private:
- explicit FetchManager(ExecutionContext*);
-
class Loader;
// Removes loader from |m_loaders|.
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.cc b/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.cc
index 698d4e8ddff..28ef8e1a34c 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.cc
@@ -22,7 +22,7 @@
namespace blink {
FetchRequestData* FetchRequestData::Create() {
- return new FetchRequestData();
+ return MakeGarbageCollected<FetchRequestData>();
}
FetchRequestData* FetchRequestData::Create(
@@ -37,8 +37,8 @@ FetchRequestData* FetchRequestData::Create(
if (scoped_refptr<EncodedFormData> body = web_request.Body()) {
request->SetBuffer(new BodyStreamBuffer(
script_state,
- new FormDataBytesConsumer(ExecutionContext::From(script_state),
- std::move(body)),
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ ExecutionContext::From(script_state), std::move(body)),
nullptr /* AbortSignal */));
} else if (web_request.GetBlobDataHandle()) {
request->SetBuffer(new BodyStreamBuffer(
@@ -49,8 +49,7 @@ FetchRequestData* FetchRequestData::Create(
}
request->SetContext(web_request.GetRequestContext());
request->SetReferrerString(web_request.ReferrerUrl().GetString());
- request->SetReferrerPolicy(
- static_cast<ReferrerPolicy>(web_request.GetReferrerPolicy()));
+ request->SetReferrerPolicy(web_request.GetReferrerPolicy());
request->SetMode(web_request.Mode());
request->SetCredentials(web_request.CredentialsMode());
request->SetCacheMode(web_request.CacheMode());
@@ -65,6 +64,44 @@ FetchRequestData* FetchRequestData::Create(
return request;
}
+FetchRequestData* FetchRequestData::Create(
+ ScriptState* script_state,
+ const mojom::blink::FetchAPIRequest& fetch_api_request) {
+ FetchRequestData* request = FetchRequestData::Create();
+ request->url_ = fetch_api_request.url;
+ request->method_ = AtomicString(fetch_api_request.method);
+ for (const auto& pair : fetch_api_request.headers) {
+ // TODO(leonhsl): Check sources of |fetch_api_request.headers| to make clear
+ // whether we really need this filter.
+ if (DeprecatedEqualIgnoringCase(pair.key, "referer"))
+ continue;
+ request->header_list_->Append(pair.key, pair.value);
+ }
+ if (fetch_api_request.blob) {
+ request->SetBuffer(new BodyStreamBuffer(
+ script_state,
+ new BlobBytesConsumer(ExecutionContext::From(script_state),
+ fetch_api_request.blob),
+ nullptr /* AbortSignal */));
+ }
+ request->SetContext(fetch_api_request.request_context_type);
+ request->SetReferrerString(AtomicString(Referrer::NoReferrer()));
+ if (fetch_api_request.referrer) {
+ if (!fetch_api_request.referrer->url.IsEmpty())
+ request->SetReferrerString(AtomicString(fetch_api_request.referrer->url));
+ request->SetReferrerPolicy(fetch_api_request.referrer->policy);
+ }
+ request->SetMode(fetch_api_request.mode);
+ request->SetCredentials(fetch_api_request.credentials_mode);
+ request->SetCacheMode(fetch_api_request.cache_mode);
+ request->SetRedirect(fetch_api_request.redirect_mode);
+ request->SetMIMEType(request->header_list_->ExtractMIMEType());
+ request->SetIntegrity(fetch_api_request.integrity);
+ request->SetKeepalive(fetch_api_request.keepalive);
+ request->SetIsHistoryNavigation(fetch_api_request.is_history_navigation);
+ return request;
+}
+
FetchRequestData* FetchRequestData::CloneExceptBody() {
FetchRequestData* request = FetchRequestData::Create();
request->url_ = url_;
@@ -126,13 +163,13 @@ FetchRequestData* FetchRequestData::Pass(ScriptState* script_state,
FetchRequestData::~FetchRequestData() {}
FetchRequestData::FetchRequestData()
- : method_(HTTPNames::GET),
+ : method_(http_names::kGET),
header_list_(FetchHeaderList::Create()),
context_(mojom::RequestContextType::UNSPECIFIED),
same_origin_data_url_flag_(false),
referrer_string_(Referrer::ClientReferrerString()),
- referrer_policy_(kReferrerPolicyDefault),
- mode_(network::mojom::FetchRequestMode::kNoCORS),
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
+ mode_(network::mojom::FetchRequestMode::kNoCors),
credentials_(network::mojom::FetchCredentialsMode::kOmit),
cache_mode_(mojom::FetchCacheMode::kDefault),
redirect_(network::mojom::FetchRedirectMode::kFollow),
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.h b/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.h
index 8e3c47b4011..1db691f0d02 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.h
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_request_data.h
@@ -9,8 +9,9 @@
#include "base/memory/scoped_refptr.h"
#include "base/unguessable_token.h"
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "services/network/public/mojom/url_loader_factory.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/fetch/body_stream_buffer.h"
@@ -18,7 +19,6 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -34,13 +34,17 @@ class WebServiceWorkerRequest;
class FetchRequestData final
: public GarbageCollectedFinalized<FetchRequestData> {
public:
- enum Tainting { kBasicTainting, kCORSTainting, kOpaqueTainting };
+ enum Tainting { kBasicTainting, kCorsTainting, kOpaqueTainting };
static FetchRequestData* Create();
static FetchRequestData* Create(ScriptState*, const WebServiceWorkerRequest&);
+ static FetchRequestData* Create(ScriptState*,
+ const mojom::blink::FetchAPIRequest&);
// Call Request::refreshBody() after calling clone() or pass().
FetchRequestData* Clone(ScriptState*, ExceptionState&);
FetchRequestData* Pass(ScriptState*, ExceptionState&);
+
+ FetchRequestData();
~FetchRequestData();
void SetMethod(AtomicString method) { method_ = method; }
@@ -59,8 +63,12 @@ class FetchRequestData final
}
const AtomicString& ReferrerString() const { return referrer_string_; }
void SetReferrerString(const AtomicString& s) { referrer_string_ = s; }
- ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
- void SetReferrerPolicy(ReferrerPolicy p) { referrer_policy_ = p; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
+ void SetReferrerPolicy(network::mojom::ReferrerPolicy p) {
+ referrer_policy_ = p;
+ }
void SetMode(network::mojom::FetchRequestMode mode) { mode_ = mode; }
network::mojom::FetchRequestMode Mode() const { return mode_; }
void SetCredentials(network::mojom::FetchCredentialsMode credentials) {
@@ -113,8 +121,6 @@ class FetchRequestData final
void Trace(blink::Visitor*);
private:
- FetchRequestData();
-
FetchRequestData* CloneExceptBody();
AtomicString method_;
@@ -126,7 +132,7 @@ class FetchRequestData final
// FIXME: Support m_forceOriginHeaderFlag;
bool same_origin_data_url_flag_;
AtomicString referrer_string_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
// FIXME: Support m_authenticationFlag;
// FIXME: Support m_synchronousFlag;
network::mojom::FetchRequestMode mode_;
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.cc b/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.cc
index d9415b84c6d..cdd01b31e69 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.cc
@@ -9,8 +9,10 @@
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
using Type = network::mojom::FetchResponseType;
@@ -30,7 +32,7 @@ WebVector<WebString> HeaderSetToWebVector(const WebHTTPHeaderSet& headers) {
Vector<String> HeaderSetToVector(const WebHTTPHeaderSet& headers) {
Vector<String> result;
- result.ReserveInitialCapacity(headers.size());
+ result.ReserveInitialCapacity(SafeCast<wtf_size_t>(headers.size()));
// WebHTTPHeaderSet stores headers using Latin1 encoding.
for (const auto& header : headers)
result.push_back(String(header.data(), header.size()));
@@ -43,14 +45,15 @@ FetchResponseData* FetchResponseData::Create() {
// "Unless stated otherwise, a response's url is null, status is 200, status
// message is the empty byte sequence, header list is an empty header list,
// and body is null."
- return new FetchResponseData(Type::kDefault, 200, g_empty_atom);
+ return MakeGarbageCollected<FetchResponseData>(Type::kDefault, 200,
+ g_empty_atom);
}
FetchResponseData* FetchResponseData::CreateNetworkErrorResponse() {
// "A network error is a response whose status is always 0, status message
// is always the empty byte sequence, header list is aways an empty list,
// and body is always null."
- return new FetchResponseData(Type::kError, 0, g_empty_atom);
+ return MakeGarbageCollected<FetchResponseData>(Type::kError, 0, g_empty_atom);
}
FetchResponseData* FetchResponseData::CreateWithBuffer(
@@ -65,8 +68,8 @@ FetchResponseData* FetchResponseData::CreateBasicFilteredResponse() const {
// "A basic filtered response is a filtered response whose type is |basic|,
// header list excludes any headers in internal response's header list whose
// name is `Set-Cookie` or `Set-Cookie2`."
- FetchResponseData* response =
- new FetchResponseData(Type::kBasic, status_, status_message_);
+ FetchResponseData* response = MakeGarbageCollected<FetchResponseData>(
+ Type::kBasic, status_, status_message_);
response->SetURLList(url_list_);
for (const auto& header : header_list_->List()) {
if (FetchUtils::IsForbiddenResponseHeaderName(header.first))
@@ -79,7 +82,7 @@ FetchResponseData* FetchResponseData::CreateBasicFilteredResponse() const {
return response;
}
-FetchResponseData* FetchResponseData::CreateCORSFilteredResponse(
+FetchResponseData* FetchResponseData::CreateCorsFilteredResponse(
const WebHTTPHeaderSet& exposed_headers) const {
DCHECK_EQ(type_, Type::kDefault);
// "A CORS filtered response is a filtered response whose type is |CORS|,
@@ -89,12 +92,12 @@ FetchResponseData* FetchResponseData::CreateCORSFilteredResponse(
// `Pragma`, and except those whose name is one of the values resulting from
// parsing `Access-Control-Expose-Headers` in internal response's header
// list."
- FetchResponseData* response =
- new FetchResponseData(Type::kCORS, status_, status_message_);
+ FetchResponseData* response = MakeGarbageCollected<FetchResponseData>(
+ Type::kCors, status_, status_message_);
response->SetURLList(url_list_);
for (const auto& header : header_list_->List()) {
const String& name = header.first;
- if (WebCORS::IsOnAccessControlResponseHeaderWhitelist(name) ||
+ if (cors::IsOnAccessControlResponseHeaderWhitelist(name) ||
(exposed_headers.find(name.Ascii().data()) != exposed_headers.end() &&
!FetchUtils::IsForbiddenResponseHeaderName(name))) {
response->header_list_->Append(name, header.second);
@@ -116,7 +119,7 @@ FetchResponseData* FetchResponseData::CreateOpaqueFilteredResponse() const {
//
// https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
FetchResponseData* response =
- new FetchResponseData(Type::kOpaque, 0, g_empty_atom);
+ MakeGarbageCollected<FetchResponseData>(Type::kOpaque, 0, g_empty_atom);
response->internal_response_ = const_cast<FetchResponseData*>(this);
return response;
}
@@ -129,8 +132,8 @@ FetchResponseData* FetchResponseData::CreateOpaqueRedirectFilteredResponse()
// header list is the empty list, body is null, and cache state is 'none'."
//
// https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect
- FetchResponseData* response =
- new FetchResponseData(Type::kOpaqueRedirect, 0, g_empty_atom);
+ FetchResponseData* response = MakeGarbageCollected<FetchResponseData>(
+ Type::kOpaqueRedirect, 0, g_empty_atom);
response->SetURLList(url_list_);
response->internal_response_ = const_cast<FetchResponseData*>(this);
return response;
@@ -192,7 +195,7 @@ FetchResponseData* FetchResponseData::Clone(ScriptState* script_state,
switch (type_) {
case Type::kBasic:
- case Type::kCORS:
+ case Type::kCors:
DCHECK(internal_response_);
DCHECK_EQ(buffer_, internal_response_->buffer_);
DCHECK_EQ(internal_response_->type_, Type::kDefault);
@@ -291,7 +294,7 @@ FetchResponseData::FetchResponseData(Type type,
response_time_(base::Time::Now()) {}
void FetchResponseData::ReplaceBodyStreamBuffer(BodyStreamBuffer* buffer) {
- if (type_ == Type::kBasic || type_ == Type::kCORS) {
+ if (type_ == Type::kBasic || type_ == Type::kCors) {
DCHECK(internal_response_);
internal_response_->buffer_ = buffer;
buffer_ = buffer;
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.h b/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.h
index b32bb7976ae..d1116775c9a 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.h
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_response_data.h
@@ -13,7 +13,7 @@
#include "third_party/blink/public/mojom/fetch/fetch_api_response.mojom-blink.h"
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
-#include "third_party/blink/public/platform/web_cors.h"
+#include "third_party/blink/public/platform/web_http_header_set.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/fetch/body_stream_buffer.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -44,8 +44,12 @@ class CORE_EXPORT FetchResponseData final
static FetchResponseData* CreateNetworkErrorResponse();
static FetchResponseData* CreateWithBuffer(BodyStreamBuffer*);
+ FetchResponseData(network::mojom::FetchResponseType,
+ unsigned short,
+ AtomicString);
+
FetchResponseData* CreateBasicFilteredResponse() const;
- FetchResponseData* CreateCORSFilteredResponse(
+ FetchResponseData* CreateCorsFilteredResponse(
const WebHTTPHeaderSet& exposed_headers) const;
FetchResponseData* CreateOpaqueFilteredResponse() const;
FetchResponseData* CreateOpaqueRedirectFilteredResponse() const;
@@ -106,10 +110,6 @@ class CORE_EXPORT FetchResponseData final
void Trace(blink::Visitor*);
private:
- FetchResponseData(network::mojom::FetchResponseType,
- unsigned short,
- AtomicString);
-
network::mojom::FetchResponseType type_;
std::unique_ptr<TerminationReason> termination_reason_;
Vector<KURL> url_list_;
diff --git a/chromium/third_party/blink/renderer/core/fetch/fetch_response_data_test.cc b/chromium/third_party/blink/renderer/core/fetch/fetch_response_data_test.cc
index e2772ef522c..2c645d06206 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_response_data_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_response_data_test.cc
@@ -93,10 +93,10 @@ TEST_F(FetchResponseDataTest, ToWebServiceWorkerBasicType) {
CheckHeaders(web_response);
}
-TEST_F(FetchResponseDataTest, CORSFilter) {
+TEST_F(FetchResponseDataTest, CorsFilter) {
FetchResponseData* internal_response = CreateInternalResponse();
FetchResponseData* cors_response_data =
- internal_response->CreateCORSFilteredResponse(WebHTTPHeaderSet());
+ internal_response->CreateCorsFilteredResponse(WebHTTPHeaderSet());
EXPECT_EQ(internal_response, cors_response_data->InternalResponse());
@@ -111,13 +111,13 @@ TEST_F(FetchResponseDataTest, CORSFilter) {
}
TEST_F(FetchResponseDataTest,
- CORSFilterOnResponseWithAccessControlExposeHeaders) {
+ CorsFilterOnResponseWithAccessControlExposeHeaders) {
FetchResponseData* internal_response = CreateInternalResponse();
internal_response->HeaderList()->Append("access-control-expose-headers",
"set-cookie, bar");
FetchResponseData* cors_response_data =
- internal_response->CreateCORSFilteredResponse({"set-cookie", "bar"});
+ internal_response->CreateCorsFilteredResponse({"set-cookie", "bar"});
EXPECT_EQ(internal_response, cors_response_data->InternalResponse());
@@ -128,10 +128,10 @@ TEST_F(FetchResponseDataTest,
EXPECT_EQ("bar", bar_value);
}
-TEST_F(FetchResponseDataTest, CORSFilterWithEmptyHeaderSet) {
+TEST_F(FetchResponseDataTest, CorsFilterWithEmptyHeaderSet) {
FetchResponseData* internal_response = CreateInternalResponse();
FetchResponseData* cors_response_data =
- internal_response->CreateCORSFilteredResponse(WebHTTPHeaderSet());
+ internal_response->CreateCorsFilteredResponse(WebHTTPHeaderSet());
EXPECT_EQ(internal_response, cors_response_data->InternalResponse());
@@ -146,13 +146,13 @@ TEST_F(FetchResponseDataTest, CORSFilterWithEmptyHeaderSet) {
}
TEST_F(FetchResponseDataTest,
- CORSFilterWithEmptyHeaderSetOnResponseWithAccessControlExposeHeaders) {
+ CorsFilterWithEmptyHeaderSetOnResponseWithAccessControlExposeHeaders) {
FetchResponseData* internal_response = CreateInternalResponse();
internal_response->HeaderList()->Append("access-control-expose-headers",
"set-cookie, bar");
FetchResponseData* cors_response_data =
- internal_response->CreateCORSFilteredResponse(WebHTTPHeaderSet());
+ internal_response->CreateCorsFilteredResponse(WebHTTPHeaderSet());
EXPECT_EQ(internal_response, cors_response_data->InternalResponse());
@@ -166,14 +166,14 @@ TEST_F(FetchResponseDataTest,
EXPECT_EQ("no-cache", cache_control_value);
}
-TEST_F(FetchResponseDataTest, CORSFilterWithExplicitHeaderSet) {
+TEST_F(FetchResponseDataTest, CorsFilterWithExplicitHeaderSet) {
FetchResponseData* internal_response = CreateInternalResponse();
WebHTTPHeaderSet exposed_headers;
exposed_headers.insert("set-cookie");
exposed_headers.insert("bar");
FetchResponseData* cors_response_data =
- internal_response->CreateCORSFilteredResponse(exposed_headers);
+ internal_response->CreateCorsFilteredResponse(exposed_headers);
EXPECT_EQ(internal_response, cors_response_data->InternalResponse());
@@ -184,14 +184,14 @@ TEST_F(FetchResponseDataTest, CORSFilterWithExplicitHeaderSet) {
EXPECT_EQ("bar", bar_value);
}
-TEST_F(FetchResponseDataTest, ToWebServiceWorkerCORSType) {
+TEST_F(FetchResponseDataTest, ToWebServiceWorkerCorsType) {
WebServiceWorkerResponse web_response;
FetchResponseData* internal_response = CreateInternalResponse();
FetchResponseData* cors_response_data =
- internal_response->CreateCORSFilteredResponse(WebHTTPHeaderSet());
+ internal_response->CreateCorsFilteredResponse(WebHTTPHeaderSet());
cors_response_data->PopulateWebServiceWorkerResponse(web_response);
- EXPECT_EQ(network::mojom::FetchResponseType::kCORS,
+ EXPECT_EQ(network::mojom::FetchResponseType::kCors,
web_response.ResponseType());
CheckHeaders(web_response);
}
diff --git a/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.cc b/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.cc
index 4d38ebdb542..6561f1c4e80 100644
--- a/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fetch/blob_bytes_consumer.h"
-#include "third_party/blink/renderer/core/fetch/bytes_consumer_for_data_consumer_handle.h"
+#include "third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
@@ -199,11 +199,12 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
std::move(pipe_producer_handle),
WTF::Bind(&DataPipeAndDataBytesConsumer::DataPipeGetterCallback,
WrapWeakPersistent(this)));
- std::unique_ptr<WebDataConsumerHandle> consumer_handle =
- Platform::Current()->CreateDataConsumerHandle(
- std::move(pipe_consumer_handle));
- data_pipe_consumer_ = new BytesConsumerForDataConsumerHandle(
- execution_context_, std::move(consumer_handle));
+ DataPipeBytesConsumer::CompletionNotifier* completion_notifier =
+ nullptr;
+ data_pipe_consumer_ = new DataPipeBytesConsumer(
+ execution_context_, std::move(pipe_consumer_handle),
+ &completion_notifier);
+ completion_notifier_ = completion_notifier;
if (client_)
data_pipe_consumer_->SetClient(client_);
}
@@ -216,14 +217,9 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
}
if (result == Result::kDone) {
- // We've finished reading from the data pipe, but we're not done
- // until we get the DataPipeGetterCallback signalling success.
- if (!was_data_pipe_getter_callback_called_)
- return Result::kShouldWait;
-
// We're done. Move on to the next element.
- was_data_pipe_getter_callback_called_ = false;
data_pipe_consumer_ = nullptr;
+ completion_notifier_ = nullptr;
++iter_;
return BeginRead(buffer, available);
}
@@ -321,6 +317,7 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
visitor->Trace(client_);
visitor->Trace(simple_consumer_);
visitor->Trace(data_pipe_consumer_);
+ visitor->Trace(completion_notifier_);
BytesConsumer::Trace(visitor);
}
@@ -328,22 +325,26 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
void DataPipeGetterCallback(int32_t status, uint64_t size) {
switch (state_) {
case PublicState::kErrored:
+ // The error should have already been propagated to the notifier.
+ DCHECK(!completion_notifier_);
+ DCHECK(!data_pipe_consumer_);
return;
case PublicState::kClosed:
+ // The data_pipe_consumer_ should already be cleaned up.
+ DCHECK(!completion_notifier_);
+ DCHECK(!data_pipe_consumer_);
return;
case PublicState::kReadableOrWaiting:
break;
}
- DCHECK(data_pipe_consumer_);
- auto client = client_;
- if (status != 0) // 0 is net::OK.
- SetError();
- else
- was_data_pipe_getter_callback_called_ = true;
-
- if (client)
- client->OnStateChange();
+ DCHECK(completion_notifier_);
+ if (status != 0) {
+ // 0 is net::OK.
+ completion_notifier_->SignalError(Error("error"));
+ } else {
+ completion_notifier_->SignalComplete();
+ }
}
void Close() {
@@ -353,7 +354,11 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
state_ = PublicState::kClosed;
ClearClient();
simple_consumer_ = nullptr;
- data_pipe_consumer_ = nullptr;
+ if (data_pipe_consumer_) {
+ data_pipe_consumer_->Cancel();
+ data_pipe_consumer_ = nullptr;
+ completion_notifier_ = nullptr;
+ }
}
void SetError() {
@@ -364,7 +369,11 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
error_ = Error("error");
ClearClient();
simple_consumer_ = nullptr;
- data_pipe_consumer_ = nullptr;
+ if (completion_notifier_) {
+ completion_notifier_->SignalError(error_);
+ completion_notifier_ = nullptr;
+ data_pipe_consumer_ = nullptr;
+ }
}
Member<ExecutionContext> execution_context_;
@@ -374,8 +383,8 @@ class DataPipeAndDataBytesConsumer final : public BytesConsumer {
Error error_;
Member<BytesConsumer::Client> client_;
Member<SimpleFormDataBytesConsumer> simple_consumer_;
- Member<BytesConsumerForDataConsumerHandle> data_pipe_consumer_;
- bool was_data_pipe_getter_callback_called_ = false;
+ Member<DataPipeBytesConsumer> data_pipe_consumer_;
+ Member<DataPipeBytesConsumer::CompletionNotifier> completion_notifier_;
};
class ComplexFormDataBytesConsumer final : public BytesConsumer {
@@ -491,7 +500,7 @@ FormDataBytesConsumer::FormDataBytesConsumer(DOMArrayBuffer* buffer)
FormDataBytesConsumer::FormDataBytesConsumer(DOMArrayBufferView* view)
: FormDataBytesConsumer(view->BaseAddress(), view->byteLength()) {}
-FormDataBytesConsumer::FormDataBytesConsumer(const void* data, size_t size)
+FormDataBytesConsumer::FormDataBytesConsumer(const void* data, wtf_size_t size)
: impl_(new SimpleFormDataBytesConsumer(
EncodedFormData::Create(data, size))) {}
diff --git a/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h b/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h
index 009fe4ff542..1ac7e1b8a0c 100644
--- a/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h
+++ b/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h
@@ -23,15 +23,19 @@ class FormDataBytesConsumer final : public BytesConsumer {
explicit CORE_EXPORT FormDataBytesConsumer(const String&);
explicit CORE_EXPORT FormDataBytesConsumer(DOMArrayBuffer*);
explicit CORE_EXPORT FormDataBytesConsumer(DOMArrayBufferView*);
- CORE_EXPORT FormDataBytesConsumer(const void* data, size_t);
+ CORE_EXPORT FormDataBytesConsumer(const void* data, wtf_size_t);
CORE_EXPORT FormDataBytesConsumer(ExecutionContext*,
scoped_refptr<EncodedFormData>);
+ CORE_EXPORT FormDataBytesConsumer(ExecutionContext*,
+ scoped_refptr<EncodedFormData>,
+ BytesConsumer* consumer_for_testing);
+
CORE_EXPORT static FormDataBytesConsumer* CreateForTesting(
ExecutionContext* execution_context,
scoped_refptr<EncodedFormData> form_data,
BytesConsumer* consumer) {
- return new FormDataBytesConsumer(execution_context, std::move(form_data),
- consumer);
+ return MakeGarbageCollected<FormDataBytesConsumer>(
+ execution_context, std::move(form_data), consumer);
}
// BytesConsumer implementation
@@ -68,9 +72,6 @@ class FormDataBytesConsumer final : public BytesConsumer {
static BytesConsumer* GetImpl(ExecutionContext*,
scoped_refptr<EncodedFormData>,
BytesConsumer* consumer_for_testing);
- CORE_EXPORT FormDataBytesConsumer(ExecutionContext*,
- scoped_refptr<EncodedFormData>,
- BytesConsumer* consumer_for_testing);
const TraceWrapperMember<BytesConsumer> impl_;
};
diff --git a/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc b/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc
index 6f28747cac4..0fa2fc170aa 100644
--- a/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc
@@ -126,9 +126,10 @@ class FormDataBytesConsumerTest : public PageTestBase {
};
TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromString) {
- auto result = (new BytesConsumerTestUtil::TwoPhaseReader(
- new FormDataBytesConsumer("hello, world")))
- ->Run();
+ auto result =
+ (new BytesConsumerTestUtil::TwoPhaseReader(
+ MakeGarbageCollected<FormDataBytesConsumer>("hello, world")))
+ ->Run();
EXPECT_EQ(Result::kDone, result.first);
EXPECT_EQ("hello, world",
BytesConsumerTestUtil::CharVectorToString(result.second));
@@ -137,7 +138,7 @@ TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromString) {
TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromStringNonLatin) {
constexpr UChar kCs[] = {0x3042, 0};
auto result = (new BytesConsumerTestUtil::TwoPhaseReader(
- new FormDataBytesConsumer(String(kCs))))
+ MakeGarbageCollected<FormDataBytesConsumer>(String(kCs))))
->Run();
EXPECT_EQ(Result::kDone, result.first);
EXPECT_EQ("\xe3\x81\x82",
@@ -149,7 +150,7 @@ TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromArrayBuffer) {
0x42, 0x30, 0x42, 0x99, 0x88};
DOMArrayBuffer* buffer = DOMArrayBuffer::Create(kData, arraysize(kData));
auto result = (new BytesConsumerTestUtil::TwoPhaseReader(
- new FormDataBytesConsumer(buffer)))
+ MakeGarbageCollected<FormDataBytesConsumer>(buffer)))
->Run();
Vector<char> expected;
expected.Append(kData, arraysize(kData));
@@ -163,10 +164,10 @@ TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromArrayBufferView) {
0x42, 0x30, 0x42, 0x99, 0x88};
constexpr size_t kOffset = 1, kSize = 4;
DOMArrayBuffer* buffer = DOMArrayBuffer::Create(kData, arraysize(kData));
- auto result =
- (new BytesConsumerTestUtil::TwoPhaseReader(new FormDataBytesConsumer(
- DOMUint8Array::Create(buffer, kOffset, kSize))))
- ->Run();
+ auto result = (new BytesConsumerTestUtil::TwoPhaseReader(
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ DOMUint8Array::Create(buffer, kOffset, kSize))))
+ ->Run();
Vector<char> expected;
expected.Append(kData + kOffset, kSize);
@@ -179,9 +180,10 @@ TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromSimpleFormData) {
data->AppendData("foo", 3);
data->AppendData("hoge", 4);
- auto result = (new BytesConsumerTestUtil::TwoPhaseReader(
- new FormDataBytesConsumer(&GetDocument(), data)))
- ->Run();
+ auto result =
+ (new BytesConsumerTestUtil::TwoPhaseReader(
+ MakeGarbageCollected<FormDataBytesConsumer>(&GetDocument(), data)))
+ ->Run();
EXPECT_EQ(Result::kDone, result.first);
EXPECT_EQ("foohoge",
BytesConsumerTestUtil::CharVectorToString(result.second));
@@ -213,7 +215,8 @@ TEST_F(FormDataBytesConsumerTest, TwoPhaseReadFromComplexFormData) {
}
TEST_F(FormDataBytesConsumerTest, EndReadCanReturnDone) {
- BytesConsumer* consumer = new FormDataBytesConsumer("hello, world");
+ BytesConsumer* consumer =
+ MakeGarbageCollected<FormDataBytesConsumer>("hello, world");
const char* buffer = nullptr;
size_t available = 0;
ASSERT_EQ(Result::kOk, consumer->BeginRead(&buffer, &available));
@@ -226,7 +229,8 @@ TEST_F(FormDataBytesConsumerTest, EndReadCanReturnDone) {
}
TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromString) {
- BytesConsumer* consumer = new FormDataBytesConsumer("hello, world");
+ BytesConsumer* consumer =
+ MakeGarbageCollected<FormDataBytesConsumer>("hello, world");
scoped_refptr<BlobDataHandle> blob_data_handle =
consumer->DrainAsBlobDataHandle();
ASSERT_TRUE(blob_data_handle);
@@ -241,8 +245,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromString) {
}
TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromArrayBuffer) {
- BytesConsumer* consumer =
- new FormDataBytesConsumer(DOMArrayBuffer::Create("foo", 3));
+ BytesConsumer* consumer = MakeGarbageCollected<FormDataBytesConsumer>(
+ DOMArrayBuffer::Create("foo", 3));
scoped_refptr<BlobDataHandle> blob_data_handle =
consumer->DrainAsBlobDataHandle();
ASSERT_TRUE(blob_data_handle);
@@ -263,8 +267,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromSimpleFormData) {
scoped_refptr<EncodedFormData> input_form_data =
data->EncodeMultiPartFormData();
- BytesConsumer* consumer =
- new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ BytesConsumer* consumer = MakeGarbageCollected<FormDataBytesConsumer>(
+ &GetDocument(), input_form_data);
scoped_refptr<BlobDataHandle> blob_data_handle =
consumer->DrainAsBlobDataHandle();
ASSERT_TRUE(blob_data_handle);
@@ -282,8 +286,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromSimpleFormData) {
TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromComplexFormData) {
scoped_refptr<EncodedFormData> input_form_data = ComplexFormData();
- BytesConsumer* consumer =
- new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ BytesConsumer* consumer = MakeGarbageCollected<FormDataBytesConsumer>(
+ &GetDocument(), input_form_data);
scoped_refptr<BlobDataHandle> blob_data_handle =
consumer->DrainAsBlobDataHandle();
ASSERT_TRUE(blob_data_handle);
@@ -296,7 +300,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsBlobDataHandleFromComplexFormData) {
}
TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromString) {
- BytesConsumer* consumer = new FormDataBytesConsumer("hello, world");
+ BytesConsumer* consumer =
+ MakeGarbageCollected<FormDataBytesConsumer>("hello, world");
scoped_refptr<EncodedFormData> form_data = consumer->DrainAsFormData();
ASSERT_TRUE(form_data);
EXPECT_EQ("hello, world", form_data->FlattenToString());
@@ -309,8 +314,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromString) {
}
TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromArrayBuffer) {
- BytesConsumer* consumer =
- new FormDataBytesConsumer(DOMArrayBuffer::Create("foo", 3));
+ BytesConsumer* consumer = MakeGarbageCollected<FormDataBytesConsumer>(
+ DOMArrayBuffer::Create("foo", 3));
scoped_refptr<EncodedFormData> form_data = consumer->DrainAsFormData();
ASSERT_TRUE(form_data);
EXPECT_TRUE(form_data->IsSafeToSendToAnotherThread());
@@ -330,8 +335,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromSimpleFormData) {
scoped_refptr<EncodedFormData> input_form_data =
data->EncodeMultiPartFormData();
- BytesConsumer* consumer =
- new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ BytesConsumer* consumer = MakeGarbageCollected<FormDataBytesConsumer>(
+ &GetDocument(), input_form_data);
EXPECT_EQ(input_form_data, consumer->DrainAsFormData());
EXPECT_FALSE(consumer->DrainAsBlobDataHandle());
const char* buffer = nullptr;
@@ -343,8 +348,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromSimpleFormData) {
TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromComplexFormData) {
scoped_refptr<EncodedFormData> input_form_data = ComplexFormData();
- BytesConsumer* consumer =
- new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ BytesConsumer* consumer = MakeGarbageCollected<FormDataBytesConsumer>(
+ &GetDocument(), input_form_data);
EXPECT_EQ(input_form_data, consumer->DrainAsFormData());
EXPECT_FALSE(consumer->DrainAsBlobDataHandle());
const char* buffer = nullptr;
@@ -356,7 +361,8 @@ TEST_F(FormDataBytesConsumerTest, DrainAsFormDataFromComplexFormData) {
TEST_F(FormDataBytesConsumerTest, BeginReadAffectsDraining) {
const char* buffer = nullptr;
size_t available = 0;
- BytesConsumer* consumer = new FormDataBytesConsumer("hello, world");
+ BytesConsumer* consumer =
+ MakeGarbageCollected<FormDataBytesConsumer>("hello, world");
ASSERT_EQ(Result::kOk, consumer->BeginRead(&buffer, &available));
EXPECT_EQ("hello, world", String(buffer, available));
@@ -447,7 +453,8 @@ TEST_F(FormDataBytesConsumerTest, CancelWithComplexFormData) {
// Tests consuming an EncodedFormData with data pipe elements.
TEST_F(FormDataBytesConsumerTest, DataPipeFormData) {
scoped_refptr<EncodedFormData> input_form_data = DataPipeFormData();
- auto* consumer = new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ auto* consumer = MakeGarbageCollected<FormDataBytesConsumer>(&GetDocument(),
+ input_form_data);
auto* reader = new BytesConsumerTestUtil::TwoPhaseReader(consumer);
std::pair<BytesConsumer::Result, Vector<char>> result = reader->Run();
EXPECT_EQ(Result::kDone, result.first);
@@ -458,7 +465,8 @@ TEST_F(FormDataBytesConsumerTest, DataPipeFormData) {
// Tests DrainAsFormData() on an EncodedFormData with data pipe elements.
TEST_F(FormDataBytesConsumerTest, DataPipeFormData_DrainAsFormData) {
scoped_refptr<EncodedFormData> input_form_data = DataPipeFormData();
- auto* consumer = new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ auto* consumer = MakeGarbageCollected<FormDataBytesConsumer>(&GetDocument(),
+ input_form_data);
scoped_refptr<EncodedFormData> drained_form_data =
consumer->DrainAsFormData();
EXPECT_EQ(*input_form_data, *drained_form_data);
@@ -471,7 +479,8 @@ TEST_F(FormDataBytesConsumerTest,
DataPipeFormData_DrainAsFormDataWhileReading) {
// Create the consumer and start reading.
scoped_refptr<EncodedFormData> input_form_data = DataPipeFormData();
- auto* consumer = new FormDataBytesConsumer(&GetDocument(), input_form_data);
+ auto* consumer = MakeGarbageCollected<FormDataBytesConsumer>(&GetDocument(),
+ input_form_data);
const char* buffer = nullptr;
size_t available = 0;
EXPECT_EQ(BytesConsumer::Result::kOk,
diff --git a/chromium/third_party/blink/renderer/core/fetch/global_fetch.cc b/chromium/third_party/blink/renderer/core/fetch/global_fetch.cc
index 2d21c80e665..c152c1d5d23 100644
--- a/chromium/third_party/blink/renderer/core/fetch/global_fetch.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/global_fetch.cc
@@ -42,7 +42,7 @@ class GlobalFetchImpl final
ScriptPromise Fetch(ScriptState* script_state,
const RequestInfo& input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) override {
ExecutionContext* execution_context = fetch_manager_->GetExecutionContext();
if (!script_state->ContextIsValid() || !execution_context) {
@@ -109,7 +109,7 @@ void GlobalFetch::ScopedFetcher::Trace(blink::Visitor* visitor) {}
ScriptPromise GlobalFetch::fetch(ScriptState* script_state,
LocalDOMWindow& window,
const RequestInfo& input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
UseCounter::Count(window.GetExecutionContext(), WebFeature::kFetch);
if (!window.GetFrame()) {
@@ -123,7 +123,7 @@ ScriptPromise GlobalFetch::fetch(ScriptState* script_state,
ScriptPromise GlobalFetch::fetch(ScriptState* script_state,
WorkerGlobalScope& worker,
const RequestInfo& input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
UseCounter::Count(worker.GetExecutionContext(), WebFeature::kFetch);
return ScopedFetcher::From(worker)->Fetch(script_state, input, init,
diff --git a/chromium/third_party/blink/renderer/core/fetch/global_fetch.h b/chromium/third_party/blink/renderer/core/fetch/global_fetch.h
index e36b5d05315..c94a0e90428 100644
--- a/chromium/third_party/blink/renderer/core/fetch/global_fetch.h
+++ b/chromium/third_party/blink/renderer/core/fetch/global_fetch.h
@@ -27,7 +27,7 @@ class CORE_EXPORT GlobalFetch {
virtual ScriptPromise Fetch(ScriptState*,
const RequestInfo&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&) = 0;
static ScopedFetcher* From(LocalDOMWindow&);
@@ -39,12 +39,12 @@ class CORE_EXPORT GlobalFetch {
static ScriptPromise fetch(ScriptState*,
LocalDOMWindow&,
const RequestInfo&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
static ScriptPromise fetch(ScriptState*,
WorkerGlobalScope&,
const RequestInfo&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
};
diff --git a/chromium/third_party/blink/renderer/core/fetch/headers.cc b/chromium/third_party/blink/renderer/core/fetch/headers.cc
index a581c74e56c..1dd5e6a61e6 100644
--- a/chromium/third_party/blink/renderer/core/fetch/headers.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/headers.cc
@@ -40,13 +40,13 @@ class HeadersIterationSource final
private:
Vector<std::pair<String, String>> headers_;
- size_t current_;
+ wtf_size_t current_;
};
} // namespace
Headers* Headers::Create(ExceptionState&) {
- return new Headers;
+ return MakeGarbageCollected<Headers>();
}
Headers* Headers::Create(const HeadersInit& init,
@@ -61,7 +61,7 @@ Headers* Headers::Create(const HeadersInit& init,
}
Headers* Headers::Create(FetchHeaderList* header_list) {
- return new Headers(header_list);
+ return MakeGarbageCollected<Headers>(header_list);
}
Headers* Headers::Clone() const {
@@ -95,12 +95,12 @@ void Headers::append(const String& name,
}
// "4. Otherwise, if guard is |request| and |name| is a forbidden header
// name, return."
- if (guard_ == kRequestGuard && CORS::IsForbiddenHeaderName(name))
+ if (guard_ == kRequestGuard && cors::IsForbiddenHeaderName(name))
return;
// "5. Otherwise, if guard is |request-no-CORS| and |name|/|value| is not a
// no-CORS-safelisted header, return."
- if (guard_ == kRequestNoCORSGuard &&
- !CORS::IsNoCORSSafelistedHeader(name, normalized_value)) {
+ if (guard_ == kRequestNoCorsGuard &&
+ !cors::IsNoCorsSafelistedHeader(name, normalized_value)) {
return;
}
// "6. Otherwise, if guard is |response| and |name| is a forbidden response
@@ -127,12 +127,12 @@ void Headers::remove(const String& name, ExceptionState& exception_state) {
}
// "3. Otherwise, if guard is |request| and |name| is a forbidden header
// name, return."
- if (guard_ == kRequestGuard && CORS::IsForbiddenHeaderName(name))
+ if (guard_ == kRequestGuard && cors::IsForbiddenHeaderName(name))
return;
// "4. Otherwise, if guard is |request-no-CORS| and |name|/`invalid` is not
// a no-CORS-safelisted header, return."
- if (guard_ == kRequestNoCORSGuard &&
- !CORS::IsNoCORSSafelistedHeader(name, "invalid")) {
+ if (guard_ == kRequestNoCorsGuard &&
+ !cors::IsNoCorsSafelistedHeader(name, "invalid")) {
return;
}
// "5. Otherwise, if guard is |response| and |name| is a forbidden response
@@ -195,12 +195,12 @@ void Headers::set(const String& name,
}
// "4. Otherwise, if guard is |request| and |name| is a forbidden header
// name, return."
- if (guard_ == kRequestGuard && CORS::IsForbiddenHeaderName(name))
+ if (guard_ == kRequestGuard && cors::IsForbiddenHeaderName(name))
return;
// "5. Otherwise, if guard is |request-no-CORS| and |name|/|value| is not a
// no-CORS-safelisted header, return."
- if (guard_ == kRequestNoCORSGuard &&
- !CORS::IsNoCORSSafelistedHeader(name, normalized_value)) {
+ if (guard_ == kRequestNoCorsGuard &&
+ !cors::IsNoCorsSafelistedHeader(name, normalized_value)) {
return;
}
// "6. Otherwise, if guard is |response| and |name| is a forbidden response
@@ -246,7 +246,7 @@ void Headers::FillWith(const Vector<Vector<String>>& object,
// TypeError.
// 2. Append |header|’s first item/|header|’s second item to |headers|.
// Rethrow any exception."
- for (size_t i = 0; i < object.size(); ++i) {
+ for (wtf_size_t i = 0; i < object.size(); ++i) {
if (object[i].size() != 2) {
exception_state.ThrowTypeError("Invalid value");
return;
diff --git a/chromium/third_party/blink/renderer/core/fetch/headers.h b/chromium/third_party/blink/renderer/core/fetch/headers.h
index 6c860fb06d0..3b05567055c 100644
--- a/chromium/third_party/blink/renderer/core/fetch/headers.h
+++ b/chromium/third_party/blink/renderer/core/fetch/headers.h
@@ -28,7 +28,7 @@ class CORE_EXPORT Headers final : public ScriptWrappable,
enum Guard {
kImmutableGuard,
kRequestGuard,
- kRequestNoCORSGuard,
+ kRequestNoCorsGuard,
kResponseGuard,
kNoneGuard
};
@@ -39,6 +39,10 @@ class CORE_EXPORT Headers final : public ScriptWrappable,
// Shares the FetchHeaderList. Called when creating a Request or Response.
static Headers* Create(FetchHeaderList*);
+ Headers();
+ // Shares the FetchHeaderList. Called when creating a Request or Response.
+ explicit Headers(FetchHeaderList*);
+
Headers* Clone() const;
// Headers.idl implementation.
@@ -59,10 +63,6 @@ class CORE_EXPORT Headers final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
private:
- Headers();
- // Shares the FetchHeaderList. Called when creating a Request or Response.
- explicit Headers(FetchHeaderList*);
-
// These methods should only be called when size() would return 0.
void FillWith(const Vector<Vector<String>>&, ExceptionState&);
void FillWith(const Vector<std::pair<String, String>>&, ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/core/fetch/multipart_parser.cc b/chromium/third_party/blink/renderer/core/fetch/multipart_parser.cc
index 43d2a3204df..4a3112319d9 100644
--- a/chromium/third_party/blink/renderer/core/fetch/multipart_parser.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/multipart_parser.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include <algorithm>
#include <utility>
@@ -298,14 +299,17 @@ bool MultipartParser::ParseHeaderFields(const char** bytes_pointer,
HTTPHeaderMap* header_fields) {
// Combine the current bytes with buffered header bytes if needed.
const char* header_bytes = *bytes_pointer;
- size_t header_size = static_cast<size_t>(bytes_end - *bytes_pointer);
+ if ((bytes_end - *bytes_pointer) > std::numeric_limits<wtf_size_t>::max())
+ return false;
+
+ wtf_size_t header_size = static_cast<wtf_size_t>(bytes_end - *bytes_pointer);
if (!buffered_header_bytes_.IsEmpty()) {
buffered_header_bytes_.Append(header_bytes, header_size);
header_bytes = buffered_header_bytes_.data();
header_size = buffered_header_bytes_.size();
}
- size_t end = 0u;
+ wtf_size_t end = 0u;
if (!ParseMultipartFormHeadersFromBody(header_bytes, header_size,
header_fields, &end)) {
// Store the current header bytes for the next call unless that has
diff --git a/chromium/third_party/blink/renderer/core/fetch/multipart_parser_test.cc b/chromium/third_party/blink/renderer/core/fetch/multipart_parser_test.cc
index afdf0137d61..e1ad8a927ca 100644
--- a/chromium/third_party/blink/renderer/core/fetch/multipart_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/multipart_parser_test.cc
@@ -6,6 +6,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include <string.h>
#include <algorithm>
@@ -39,16 +40,16 @@ class MockMultipartParserClient final
parts_.push_back(header_fields);
}
void PartDataInMultipartReceived(const char* bytes, size_t size) override {
- parts_.back().data.Append(bytes, size);
+ parts_.back().data.Append(bytes, SafeCast<wtf_size_t>(size));
}
void PartDataInMultipartFullyReceived() override {
parts_.back().data_fully_received = true;
}
- const Part& GetPart(size_t part_index) const {
+ const Part& GetPart(wtf_size_t part_index) const {
EXPECT_LT(part_index, NumberOfParts());
return part_index < NumberOfParts() ? parts_[part_index] : empty_part_;
}
- size_t NumberOfParts() const { return parts_.size(); }
+ wtf_size_t NumberOfParts() const { return parts_.size(); }
private:
Part empty_part_;
@@ -72,7 +73,8 @@ TEST(MultipartParserTest, AppendDataInChunks) {
boundary.Append("boundary", 8u);
for (const size_t size : sizes) {
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
for (size_t i = 0u, length = strlen(kBytes); i < length; i += size)
EXPECT_TRUE(parser->AppendData(kBytes + i, std::min(size, length - i)));
@@ -83,18 +85,18 @@ TEST(MultipartParserTest, AppendDataInChunks) {
EXPECT_TRUE(client->GetPart(0).data_fully_received);
EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
EXPECT_EQ("application/xhtml+xml",
- client->GetPart(1).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(1).header_fields.Get(http_names::kContentType));
EXPECT_EQ("1", toString(client->GetPart(1).data));
EXPECT_TRUE(client->GetPart(1).data_fully_received);
EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
EXPECT_EQ("text/html",
- client->GetPart(2).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(2).header_fields.Get(http_names::kContentType));
EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
toString(client->GetPart(2).data));
EXPECT_TRUE(client->GetPart(2).data_fully_received);
EXPECT_EQ(1u, client->GetPart(3).header_fields.size());
EXPECT_EQ("text/plain; charset=iso-8859-1",
- client->GetPart(3).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(3).header_fields.Get(http_names::kContentType));
EXPECT_EQ("333", toString(client->GetPart(3).data));
EXPECT_TRUE(client->GetPart(3).data_fully_received);
}
@@ -116,7 +118,8 @@ TEST(MultipartParserTest, Epilogue) {
boundary.Append("boundary", 8u);
for (size_t end : ends) {
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
EXPECT_TRUE(parser->AppendData(kBytes, strlen(kBytes) - end));
EXPECT_EQ(end <= 12u, parser->Finish()) << " end=" << end;
@@ -126,18 +129,18 @@ TEST(MultipartParserTest, Epilogue) {
EXPECT_TRUE(client->GetPart(0).data_fully_received);
EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
EXPECT_EQ("application/xhtml+xml",
- client->GetPart(1).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(1).header_fields.Get(http_names::kContentType));
EXPECT_EQ("1", toString(client->GetPart(1).data));
EXPECT_TRUE(client->GetPart(1).data_fully_received);
EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
EXPECT_EQ("text/html",
- client->GetPart(2).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(2).header_fields.Get(http_names::kContentType));
EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
toString(client->GetPart(2).data));
EXPECT_TRUE(client->GetPart(2).data_fully_received);
EXPECT_EQ(1u, client->GetPart(3).header_fields.size());
EXPECT_EQ("text/plain; charset=iso-8859-1",
- client->GetPart(3).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(3).header_fields.Get(http_names::kContentType));
switch (end) {
case 15u:
EXPECT_EQ("333\r\n--boundar", toString(client->GetPart(3).data));
@@ -158,14 +161,15 @@ TEST(MultipartParserTest, NoEndBoundary) {
Vector<char> boundary;
boundary.Append("boundary", 8u);
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
EXPECT_TRUE(parser->AppendData(bytes, strlen(bytes)));
EXPECT_FALSE(parser->Finish()); // No close delimiter.
EXPECT_EQ(1u, client->NumberOfParts());
EXPECT_EQ(1u, client->GetPart(0).header_fields.size());
EXPECT_EQ("application/xhtml+xml",
- client->GetPart(0).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(0).header_fields.Get(http_names::kContentType));
EXPECT_EQ("1", toString(client->GetPart(0).data));
EXPECT_FALSE(client->GetPart(0).data_fully_received);
}
@@ -177,7 +181,8 @@ TEST(MultipartParserTest, NoStartBoundary) {
Vector<char> boundary;
boundary.Append("boundary", 8u);
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
EXPECT_FALSE(parser->AppendData(
bytes, strlen(bytes))); // Close delimiter before delimiter.
@@ -190,7 +195,8 @@ TEST(MultipartParserTest, NoStartNorEndBoundary) {
Vector<char> boundary;
boundary.Append("boundary", 8u);
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
EXPECT_TRUE(parser->AppendData(bytes, strlen(bytes))); // Valid preamble.
EXPECT_FALSE(parser->Finish()); // No parts.
@@ -210,7 +216,8 @@ TEST(MultipartParserTest, Preamble) {
boundary.Append("boundary", 8u);
for (const size_t start : kStarts) {
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
EXPECT_TRUE(parser->AppendData(kBytes + start, strlen(kBytes + start)));
EXPECT_TRUE(parser->Finish());
@@ -220,19 +227,19 @@ TEST(MultipartParserTest, Preamble) {
EXPECT_EQ(3u, client->NumberOfParts()) << " start=" << start;
EXPECT_EQ(1u, client->GetPart(0).header_fields.size());
EXPECT_EQ("application/xhtml+xml", client->GetPart(0).header_fields.Get(
- HTTPNames::Content_Type));
+ http_names::kContentType));
EXPECT_EQ("1", toString(client->GetPart(0).data));
EXPECT_TRUE(client->GetPart(0).data_fully_received);
EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
EXPECT_EQ("text/html", client->GetPart(1).header_fields.Get(
- HTTPNames::Content_Type));
+ http_names::kContentType));
EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
toString(client->GetPart(1).data));
EXPECT_TRUE(client->GetPart(1).data_fully_received);
EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
EXPECT_EQ(
"text/plain; charset=iso-8859-1",
- client->GetPart(2).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(2).header_fields.Get(http_names::kContentType));
EXPECT_EQ("333", toString(client->GetPart(2).data));
EXPECT_TRUE(client->GetPart(2).data_fully_received);
break;
@@ -243,19 +250,19 @@ TEST(MultipartParserTest, Preamble) {
EXPECT_TRUE(client->GetPart(0).data_fully_received);
EXPECT_EQ(1u, client->GetPart(1).header_fields.size());
EXPECT_EQ("application/xhtml+xml", client->GetPart(1).header_fields.Get(
- HTTPNames::Content_Type));
+ http_names::kContentType));
EXPECT_EQ("1", toString(client->GetPart(1).data));
EXPECT_TRUE(client->GetPart(1).data_fully_received);
EXPECT_EQ(1u, client->GetPart(2).header_fields.size());
EXPECT_EQ("text/html", client->GetPart(2).header_fields.Get(
- HTTPNames::Content_Type));
+ http_names::kContentType));
EXPECT_EQ("2\r\n--\r\n--bound--\r\n--\r\n2\r\n",
toString(client->GetPart(2).data));
EXPECT_TRUE(client->GetPart(2).data_fully_received);
EXPECT_EQ(1u, client->GetPart(3).header_fields.size());
EXPECT_EQ(
"text/plain; charset=iso-8859-1",
- client->GetPart(3).header_fields.Get(HTTPNames::Content_Type));
+ client->GetPart(3).header_fields.Get(http_names::kContentType));
EXPECT_EQ("333", toString(client->GetPart(3).data));
EXPECT_TRUE(client->GetPart(3).data_fully_received);
break;
@@ -268,7 +275,8 @@ TEST(MultipartParserTest, PreambleWithMalformedBoundary) {
boundary.Append("--boundary", 10u);
for (const size_t start : kStarts) {
MockMultipartParserClient* client = new MockMultipartParserClient;
- MultipartParser* parser = new MultipartParser(boundary, client);
+ MultipartParser* parser =
+ MakeGarbageCollected<MultipartParser>(boundary, client);
EXPECT_TRUE(parser->AppendData(kBytes + start,
strlen(kBytes + start))); // Valid preamble.
diff --git a/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.cc b/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.cc
index 2f92f6fb9d8..bb43d5f1a1e 100644
--- a/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.cc
@@ -27,9 +27,13 @@ class ReadableStreamBytesConsumer::OnFulfilled final : public ScriptFunction {
static v8::Local<v8::Function> CreateFunction(
ScriptState* script_state,
ReadableStreamBytesConsumer* consumer) {
- return (new OnFulfilled(script_state, consumer))->BindToV8Function();
+ return (MakeGarbageCollected<OnFulfilled>(script_state, consumer))
+ ->BindToV8Function();
}
+ OnFulfilled(ScriptState* script_state, ReadableStreamBytesConsumer* consumer)
+ : ScriptFunction(script_state), consumer_(consumer) {}
+
ScriptValue Call(ScriptValue v) override {
bool done;
v8::Local<v8::Value> item = v.V8Value();
@@ -62,9 +66,6 @@ class ReadableStreamBytesConsumer::OnFulfilled final : public ScriptFunction {
}
private:
- OnFulfilled(ScriptState* script_state, ReadableStreamBytesConsumer* consumer)
- : ScriptFunction(script_state), consumer_(consumer) {}
-
Member<ReadableStreamBytesConsumer> consumer_;
};
@@ -73,9 +74,13 @@ class ReadableStreamBytesConsumer::OnRejected final : public ScriptFunction {
static v8::Local<v8::Function> CreateFunction(
ScriptState* script_state,
ReadableStreamBytesConsumer* consumer) {
- return (new OnRejected(script_state, consumer))->BindToV8Function();
+ return (MakeGarbageCollected<OnRejected>(script_state, consumer))
+ ->BindToV8Function();
}
+ OnRejected(ScriptState* script_state, ReadableStreamBytesConsumer* consumer)
+ : ScriptFunction(script_state), consumer_(consumer) {}
+
ScriptValue Call(ScriptValue v) override {
consumer_->OnRejected();
return v;
@@ -87,9 +92,6 @@ class ReadableStreamBytesConsumer::OnRejected final : public ScriptFunction {
}
private:
- OnRejected(ScriptState* script_state, ReadableStreamBytesConsumer* consumer)
- : ScriptFunction(script_state), consumer_(consumer) {}
-
Member<ReadableStreamBytesConsumer> consumer_;
};
diff --git a/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer_test.cc b/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer_test.cc
index ae715b75b50..8e7a529f8d0 100644
--- a/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer_test.cc
@@ -9,10 +9,10 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
-#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h"
-#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
-#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+#include "third_party/blink/renderer/core/streams/test_underlying_source.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -38,81 +38,48 @@ class MockClient : public GarbageCollectedFinalized<MockClient>,
MOCK_METHOD0(OnStateChange, void());
String DebugName() const override { return "MockClient"; }
- void Trace(blink::Visitor* visitor) override {}
-
- protected:
MockClient() = default;
+
+ void Trace(blink::Visitor* visitor) override {}
};
-class ReadableStreamBytesConsumerTest : public testing::Test {
- public:
- ReadableStreamBytesConsumerTest() : page_(DummyPageHolder::Create()) {}
+TEST(ReadableStreamBytesConsumerTest, Create) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
- ScriptState* GetScriptState() {
- return ToScriptStateForMainWorld(page_->GetDocument().GetFrame());
- }
- v8::Isolate* GetIsolate() { return GetScriptState()->GetIsolate(); }
-
- v8::MaybeLocal<v8::Value> Eval(const char* s) {
- v8::Local<v8::String> source;
- v8::Local<v8::Script> script;
- v8::MicrotasksScope microtasks(GetIsolate(),
- v8::MicrotasksScope::kDoNotRunMicrotasks);
- if (!v8::String::NewFromUtf8(GetIsolate(), s, v8::NewStringType::kNormal)
- .ToLocal(&source)) {
- ADD_FAILURE();
- return v8::MaybeLocal<v8::Value>();
- }
- if (!v8::Script::Compile(GetScriptState()->GetContext(), source)
- .ToLocal(&script)) {
- ADD_FAILURE() << "Compilation fails";
- return v8::MaybeLocal<v8::Value>();
- }
- return script->Run(GetScriptState()->GetContext());
- }
- v8::MaybeLocal<v8::Value> EvalWithPrintingError(const char* s) {
- v8::TryCatch block(GetIsolate());
- v8::MaybeLocal<v8::Value> r = Eval(s);
- if (block.HasCaught()) {
- ADD_FAILURE() << ToCoreString(block.Exception()->ToString(GetIsolate()))
- .Utf8()
- .data();
- block.ReThrow();
- }
- return r;
- }
+ auto* stream = ReadableStream::Create(script_state, exception_state);
+ ASSERT_TRUE(stream);
+ ASSERT_FALSE(exception_state.HadException());
- ReadableStreamBytesConsumer* CreateConsumer(ScriptValue stream) {
- ScriptValue reader = ReadableStreamOperations::GetReader(
- GetScriptState(), stream, ASSERT_NO_EXCEPTION);
- DCHECK(!reader.IsEmpty());
- DCHECK(reader.V8Value()->IsObject());
- return new ReadableStreamBytesConsumer(GetScriptState(), reader);
- }
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
- void Gc() { V8GCController::CollectAllGarbageForTesting(GetIsolate()); }
-
- private:
- std::unique_ptr<DummyPageHolder> page_;
-};
-
-TEST_F(ReadableStreamBytesConsumerTest, Create) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(GetScriptState(),
- EvalWithPrintingError("new ReadableStream"));
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
EXPECT_EQ(PublicState::kReadableOrWaiting, consumer->GetPublicState());
}
-TEST_F(ReadableStreamBytesConsumerTest, EmptyStream) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(
- GetScriptState(),
- EvalWithPrintingError("new ReadableStream({start: c => c.close()})"));
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+TEST(ReadableStreamBytesConsumerTest, EmptyStream) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ underlying_source->Close();
+
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
+
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
+
Persistent<MockClient> client = MockClient::Create();
consumer->SetClient(client);
@@ -138,13 +105,24 @@ TEST_F(ReadableStreamBytesConsumerTest, EmptyStream) {
EXPECT_EQ(Result::kDone, consumer->BeginRead(&buffer, &available));
}
-TEST_F(ReadableStreamBytesConsumerTest, ErroredStream) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(
- GetScriptState(),
- EvalWithPrintingError("new ReadableStream({start: c => c.error()})"));
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+TEST(ReadableStreamBytesConsumerTest, ErroredStream) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ underlying_source->SetError(
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())));
+
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
+
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
Persistent<MockClient> client = MockClient::Create();
consumer->SetClient(client);
Checkpoint checkpoint;
@@ -170,20 +148,41 @@ TEST_F(ReadableStreamBytesConsumerTest, ErroredStream) {
EXPECT_EQ(Result::kError, consumer->BeginRead(&buffer, &available));
}
-TEST_F(ReadableStreamBytesConsumerTest, TwoPhaseRead) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(
- GetScriptState(),
- EvalWithPrintingError(
- "var controller;"
- "var stream = new ReadableStream({start: c => controller = c});"
- "controller.enqueue(new Uint8Array());"
- "controller.enqueue(new Uint8Array([0x43, 0x44, 0x45, 0x46]));"
- "controller.enqueue(new Uint8Array([0x47, 0x48, 0x49, 0x4a]));"
- "controller.close();"
- "stream"));
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+TEST(ReadableStreamBytesConsumerTest, TwoPhaseRead) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ {
+ auto* chunk1 = DOMUint8Array::Create(0);
+ auto* chunk2 = DOMUint8Array::Create(4);
+ chunk2->Data()[0] = 0x43;
+ chunk2->Data()[1] = 0x44;
+ chunk2->Data()[2] = 0x45;
+ chunk2->Data()[3] = 0x46;
+ auto* chunk3 = DOMUint8Array::Create(4);
+ chunk3->Data()[0] = 0x47;
+ chunk3->Data()[1] = 0x48;
+ chunk3->Data()[2] = 0x49;
+ chunk3->Data()[3] = 0x4a;
+ underlying_source->Enqueue(
+ ScriptValue(script_state, ToV8(chunk1, script_state)));
+ underlying_source->Enqueue(
+ ScriptValue(script_state, ToV8(chunk2, script_state)));
+ underlying_source->Enqueue(
+ ScriptValue(script_state, ToV8(chunk3, script_state)));
+ underlying_source->Close();
+ }
+
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
Persistent<MockClient> client = MockClient::Create();
consumer->SetClient(client);
Checkpoint checkpoint;
@@ -261,18 +260,24 @@ TEST_F(ReadableStreamBytesConsumerTest, TwoPhaseRead) {
EXPECT_EQ(Result::kDone, consumer->BeginRead(&buffer, &available));
}
-TEST_F(ReadableStreamBytesConsumerTest, EnqueueUndefined) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(
- GetScriptState(),
- EvalWithPrintingError(
- "var controller;"
- "var stream = new ReadableStream({start: c => controller = c});"
- "controller.enqueue(undefined);"
- "controller.close();"
- "stream"));
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+TEST(ReadableStreamBytesConsumerTest, EnqueueUndefined) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ underlying_source->Enqueue(
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())));
+ underlying_source->Close();
+
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
Persistent<MockClient> client = MockClient::Create();
consumer->SetClient(client);
Checkpoint checkpoint;
@@ -298,19 +303,24 @@ TEST_F(ReadableStreamBytesConsumerTest, EnqueueUndefined) {
EXPECT_EQ(Result::kError, consumer->BeginRead(&buffer, &available));
}
-TEST_F(ReadableStreamBytesConsumerTest, EnqueueNull) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(
- GetScriptState(),
- EvalWithPrintingError(
- "var controller;"
- "var stream = new ReadableStream({start: c => controller = c});"
- "controller.enqueue(null);"
- "controller.close();"
- "stream"));
-
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+TEST(ReadableStreamBytesConsumerTest, EnqueueNull) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ underlying_source->Enqueue(
+ ScriptValue(script_state, v8::Null(script_state->GetIsolate())));
+ underlying_source->Close();
+
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
Persistent<MockClient> client = MockClient::Create();
consumer->SetClient(client);
Checkpoint checkpoint;
@@ -336,18 +346,24 @@ TEST_F(ReadableStreamBytesConsumerTest, EnqueueNull) {
EXPECT_EQ(Result::kError, consumer->BeginRead(&buffer, &available));
}
-TEST_F(ReadableStreamBytesConsumerTest, EnqueueString) {
- ScriptState::Scope scope(GetScriptState());
- ScriptValue stream(
- GetScriptState(),
- EvalWithPrintingError(
- "var controller;"
- "var stream = new ReadableStream({start: c => controller = c});"
- "controller.enqueue('hello');"
- "controller.close();"
- "stream"));
- ASSERT_FALSE(stream.IsEmpty());
- Persistent<BytesConsumer> consumer = CreateConsumer(stream);
+TEST(ReadableStreamBytesConsumerTest, EnqueueString) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ underlying_source->Enqueue(
+ ScriptValue(script_state, V8String(script_state->GetIsolate(), "hello")));
+ underlying_source->Close();
+
+ ScriptValue reader = stream->getReader(script_state, exception_state);
+ ASSERT_FALSE(reader.IsEmpty());
+ ASSERT_FALSE(exception_state.HadException());
+ Persistent<BytesConsumer> consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
Persistent<MockClient> client = MockClient::Create();
consumer->SetClient(client);
Checkpoint checkpoint;
diff --git a/chromium/third_party/blink/renderer/core/fetch/request.cc b/chromium/third_party/blink/renderer/core/fetch/request.cc
index 2b9b263955e..e420f2d219e 100644
--- a/chromium/third_party/blink/renderer/core/fetch/request.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/request.cc
@@ -81,12 +81,12 @@ FetchRequestData* CreateCopyOfFetchRequestDataForFetch(
return request;
}
-static bool AreAnyMembersPresent(const RequestInit& init) {
- return init.hasMethod() || init.hasHeaders() || init.hasBody() ||
- init.hasReferrer() || init.hasReferrerPolicy() || init.hasMode() ||
- init.hasCredentials() || init.hasCache() || init.hasRedirect() ||
- init.hasIntegrity() || init.hasKeepalive() || init.hasImportance() ||
- init.hasSignal();
+static bool AreAnyMembersPresent(const RequestInit* init) {
+ return init->hasMethod() || init->hasHeaders() || init->hasBody() ||
+ init->hasReferrer() || init->hasReferrerPolicy() || init->hasMode() ||
+ init->hasCredentials() || init->hasCache() || init->hasRedirect() ||
+ init->hasIntegrity() || init->hasKeepalive() ||
+ init->hasImportance() || init->hasSignal();
}
static BodyStreamBuffer* ExtractBody(ScriptState* script_state,
@@ -99,7 +99,7 @@ static BodyStreamBuffer* ExtractBody(ScriptState* script_state,
ExecutionContext* execution_context = ExecutionContext::From(script_state);
v8::Isolate* isolate = script_state->GetIsolate();
- if (V8Blob::hasInstance(body, isolate)) {
+ if (V8Blob::HasInstance(body, isolate)) {
Blob* blob = V8Blob::ToImpl(body.As<v8::Object>());
return_buffer = new BodyStreamBuffer(
script_state,
@@ -111,7 +111,7 @@ static BodyStreamBuffer* ExtractBody(ScriptState* script_state,
// is potentially unsafe.
DOMArrayBuffer* array_buffer = V8ArrayBuffer::ToImpl(body.As<v8::Object>());
return_buffer = new BodyStreamBuffer(
- script_state, new FormDataBytesConsumer(array_buffer),
+ script_state, MakeGarbageCollected<FormDataBytesConsumer>(array_buffer),
nullptr /* AbortSignal */);
} else if (body->IsArrayBufferView()) {
// Avoid calling into V8 from the following constructor parameters, which
@@ -119,26 +119,29 @@ static BodyStreamBuffer* ExtractBody(ScriptState* script_state,
DOMArrayBufferView* array_buffer_view =
V8ArrayBufferView::ToImpl(body.As<v8::Object>());
return_buffer = new BodyStreamBuffer(
- script_state, new FormDataBytesConsumer(array_buffer_view),
+ script_state,
+ MakeGarbageCollected<FormDataBytesConsumer>(array_buffer_view),
nullptr /* AbortSignal */);
- } else if (V8FormData::hasInstance(body, isolate)) {
+ } else if (V8FormData::HasInstance(body, isolate)) {
scoped_refptr<EncodedFormData> form_data =
V8FormData::ToImpl(body.As<v8::Object>())->EncodeMultiPartFormData();
// Here we handle formData->boundary() as a C-style string. See
// FormDataEncoder::generateUniqueBoundaryString.
content_type = AtomicString("multipart/form-data; boundary=") +
form_data->Boundary().data();
- return_buffer = new BodyStreamBuffer(
- script_state,
- new FormDataBytesConsumer(execution_context, std::move(form_data)),
- nullptr /* AbortSignal */);
- } else if (V8URLSearchParams::hasInstance(body, isolate)) {
+ return_buffer =
+ new BodyStreamBuffer(script_state,
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ execution_context, std::move(form_data)),
+ nullptr /* AbortSignal */);
+ } else if (V8URLSearchParams::HasInstance(body, isolate)) {
scoped_refptr<EncodedFormData> form_data =
V8URLSearchParams::ToImpl(body.As<v8::Object>())->ToEncodedFormData();
- return_buffer = new BodyStreamBuffer(
- script_state,
- new FormDataBytesConsumer(execution_context, std::move(form_data)),
- nullptr /* AbortSignal */);
+ return_buffer =
+ new BodyStreamBuffer(script_state,
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ execution_context, std::move(form_data)),
+ nullptr /* AbortSignal */);
content_type = "application/x-www-form-urlencoded;charset=UTF-8";
} else {
String string = NativeValueTraits<IDLUSVString>::NativeValue(
@@ -146,9 +149,9 @@ static BodyStreamBuffer* ExtractBody(ScriptState* script_state,
if (exception_state.HadException())
return nullptr;
- return_buffer =
- new BodyStreamBuffer(script_state, new FormDataBytesConsumer(string),
- nullptr /* AbortSignal */);
+ return_buffer = new BodyStreamBuffer(
+ script_state, MakeGarbageCollected<FormDataBytesConsumer>(string),
+ nullptr /* AbortSignal */);
content_type = "text/plain;charset=UTF-8";
}
@@ -159,7 +162,7 @@ Request* Request::CreateRequestWithRequestOrString(
ScriptState* script_state,
Request* input_request,
const String& input_string,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
// Setup RequestInit's body first
// - "If |input| is a Request object and it is disturbed, throw a
@@ -287,25 +290,25 @@ Request* Request::CreateRequestWithRequestOrString(
request->SetReferrerString(AtomicString(Referrer::ClientReferrerString()));
// "Set |request|’s referrer policy to the empty string."
- request->SetReferrerPolicy(kReferrerPolicyDefault);
+ request->SetReferrerPolicy(network::mojom::ReferrerPolicy::kDefault);
}
// "If init’s referrer member is present, then:"
- if (init.hasReferrer()) {
+ if (init->hasReferrer()) {
// Nothing to do for the step "Let |referrer| be |init|'s referrer
// member."
- if (init.referrer().IsEmpty()) {
+ if (init->referrer().IsEmpty()) {
// "If |referrer| is the empty string, set |request|'s referrer to
// "no-referrer" and terminate these substeps."
request->SetReferrerString(AtomicString(Referrer::NoReferrer()));
} else {
// "Let |parsedReferrer| be the result of parsing |referrer| with
// |baseURL|."
- KURL parsed_referrer(base_url, init.referrer());
+ KURL parsed_referrer(base_url, init->referrer());
if (!parsed_referrer.IsValid()) {
// "If |parsedReferrer| is failure, throw a TypeError."
- exception_state.ThrowTypeError("Referrer '" + init.referrer() +
+ exception_state.ThrowTypeError("Referrer '" + init->referrer() +
"' is not a valid URL.");
return nullptr;
}
@@ -336,16 +339,16 @@ Request* Request::CreateRequestWithRequestOrString(
// "If init's referrerPolicy member is present, set request's referrer
// policy to it."
- if (init.hasReferrerPolicy()) {
+ if (init->hasReferrerPolicy()) {
// In case referrerPolicy = "", the SecurityPolicy method below will not
// actually set referrer_policy, so we'll default to
- // kReferrerPolicyDefault.
- ReferrerPolicy referrer_policy;
+ // network::mojom::ReferrerPolicy::kDefault.
+ network::mojom::ReferrerPolicy referrer_policy;
if (!SecurityPolicy::ReferrerPolicyFromString(
- init.referrerPolicy(), kDoNotSupportReferrerPolicyLegacyKeywords,
+ init->referrerPolicy(), kDoNotSupportReferrerPolicyLegacyKeywords,
&referrer_policy)) {
- DCHECK(init.referrerPolicy().IsEmpty());
- referrer_policy = kReferrerPolicyDefault;
+ DCHECK(init->referrerPolicy().IsEmpty());
+ referrer_policy = network::mojom::ReferrerPolicy::kDefault;
}
request->SetReferrerPolicy(referrer_policy);
@@ -356,34 +359,34 @@ Request* Request::CreateRequestWithRequestOrString(
// |fallbackMode| otherwise."
// - "If |mode| is "navigate", throw a TypeError."
// - "If |mode| is non-null, set |request|'s mode to |mode|."
- if (init.mode() == "navigate") {
+ if (init->mode() == "navigate") {
exception_state.ThrowTypeError(
"Cannot construct a Request with a RequestInit whose mode member is "
"set as 'navigate'.");
return nullptr;
}
- if (init.mode() == "same-origin") {
+ if (init->mode() == "same-origin") {
request->SetMode(network::mojom::FetchRequestMode::kSameOrigin);
- } else if (init.mode() == "no-cors") {
- request->SetMode(network::mojom::FetchRequestMode::kNoCORS);
- } else if (init.mode() == "cors") {
- request->SetMode(network::mojom::FetchRequestMode::kCORS);
+ } else if (init->mode() == "no-cors") {
+ request->SetMode(network::mojom::FetchRequestMode::kNoCors);
+ } else if (init->mode() == "cors") {
+ request->SetMode(network::mojom::FetchRequestMode::kCors);
} else {
// |inputRequest| is directly checked here instead of setting and
// checking |fallbackMode| as specified in the spec.
if (!input_request)
- request->SetMode(network::mojom::FetchRequestMode::kCORS);
+ request->SetMode(network::mojom::FetchRequestMode::kCors);
}
// This is not yet standardized, but we can assume the following:
// "If |init|'s importance member is present, set |request|'s importance
// mode to it." For more information see Priority Hints at
// https://crbug.com/821464
- DCHECK(init.importance().IsNull() ||
+ DCHECK(init->importance().IsNull() ||
RuntimeEnabledFeatures::PriorityHintsEnabled());
- if (init.importance() == "low") {
+ if (init->importance() == "low") {
request->SetImportance(mojom::FetchImportanceMode::kImportanceLow);
- } else if (init.importance() == "high") {
+ } else if (init->importance() == "high") {
request->SetImportance(mojom::FetchImportanceMode::kImportanceHigh);
}
@@ -393,24 +396,24 @@ Request* Request::CreateRequestWithRequestOrString(
// |credentials|."
network::mojom::FetchCredentialsMode credentials_mode;
- if (ParseCredentialsMode(init.credentials(), &credentials_mode)) {
+ if (ParseCredentialsMode(init->credentials(), &credentials_mode)) {
request->SetCredentials(credentials_mode);
} else if (!input_request) {
request->SetCredentials(network::mojom::FetchCredentialsMode::kSameOrigin);
}
// "If |init|'s cache member is present, set |request|'s cache mode to it."
- if (init.cache() == "default") {
+ if (init->cache() == "default") {
request->SetCacheMode(mojom::FetchCacheMode::kDefault);
- } else if (init.cache() == "no-store") {
+ } else if (init->cache() == "no-store") {
request->SetCacheMode(mojom::FetchCacheMode::kNoStore);
- } else if (init.cache() == "reload") {
+ } else if (init->cache() == "reload") {
request->SetCacheMode(mojom::FetchCacheMode::kBypassCache);
- } else if (init.cache() == "no-cache") {
+ } else if (init->cache() == "no-cache") {
request->SetCacheMode(mojom::FetchCacheMode::kValidateCache);
- } else if (init.cache() == "force-cache") {
+ } else if (init->cache() == "force-cache") {
request->SetCacheMode(mojom::FetchCacheMode::kForceCache);
- } else if (init.cache() == "only-if-cached") {
+ } else if (init->cache() == "only-if-cached") {
request->SetCacheMode(mojom::FetchCacheMode::kOnlyIfCached);
}
@@ -425,46 +428,46 @@ Request* Request::CreateRequestWithRequestOrString(
// "If |init|'s redirect member is present, set |request|'s redirect mode
// to it."
- if (init.redirect() == "follow") {
+ if (init->redirect() == "follow") {
request->SetRedirect(network::mojom::FetchRedirectMode::kFollow);
- } else if (init.redirect() == "error") {
+ } else if (init->redirect() == "error") {
request->SetRedirect(network::mojom::FetchRedirectMode::kError);
- } else if (init.redirect() == "manual") {
+ } else if (init->redirect() == "manual") {
request->SetRedirect(network::mojom::FetchRedirectMode::kManual);
}
// "If |init|'s integrity member is present, set |request|'s
// integrity metadata to it."
- if (init.hasIntegrity())
- request->SetIntegrity(init.integrity());
+ if (init->hasIntegrity())
+ request->SetIntegrity(init->integrity());
- if (init.hasKeepalive())
- request->SetKeepalive(init.keepalive());
+ if (init->hasKeepalive())
+ request->SetKeepalive(init->keepalive());
// "If |init|'s method member is present, let |method| be it and run these
// substeps:"
- if (init.hasMethod()) {
+ if (init->hasMethod()) {
// "If |method| is not a method or method is a forbidden method, throw
// a TypeError."
- if (!IsValidHTTPToken(init.method())) {
- exception_state.ThrowTypeError("'" + init.method() +
+ if (!IsValidHTTPToken(init->method())) {
+ exception_state.ThrowTypeError("'" + init->method() +
"' is not a valid HTTP method.");
return nullptr;
}
- if (FetchUtils::IsForbiddenMethod(init.method())) {
- exception_state.ThrowTypeError("'" + init.method() +
+ if (FetchUtils::IsForbiddenMethod(init->method())) {
+ exception_state.ThrowTypeError("'" + init->method() +
"' HTTP method is unsupported.");
return nullptr;
}
// "Normalize |method|."
// "Set |request|'s method to |method|."
request->SetMethod(
- FetchUtils::NormalizeMethod(AtomicString(init.method())));
+ FetchUtils::NormalizeMethod(AtomicString(init->method())));
}
// "If |init|'s signal member is present, then set |signal| to it."
- if (init.hasSignal()) {
- signal = init.signal();
+ if (init->hasSignal()) {
+ signal = init->signal();
}
// "Let |r| be a new Request object associated with |request| and a new
@@ -478,30 +481,30 @@ Request* Request::CreateRequestWithRequestOrString(
// We don't create a copy of r's Headers object when init's headers member
// is present.
Headers* headers = nullptr;
- if (!init.hasHeaders()) {
+ if (!init->hasHeaders()) {
headers = r->getHeaders()->Clone();
}
// "Empty |r|'s request's header list."
r->request_->HeaderList()->ClearList();
// "If |r|'s request's mode is "no-cors", run these substeps:
- if (r->GetRequest()->Mode() == network::mojom::FetchRequestMode::kNoCORS) {
+ if (r->GetRequest()->Mode() == network::mojom::FetchRequestMode::kNoCors) {
// "If |r|'s request's method is not a CORS-safelisted method, throw a
// TypeError."
- if (!CORS::IsCORSSafelistedMethod(r->GetRequest()->Method())) {
+ if (!cors::IsCorsSafelistedMethod(r->GetRequest()->Method())) {
exception_state.ThrowTypeError("'" + r->GetRequest()->Method() +
"' is unsupported in no-cors mode.");
return nullptr;
}
// "Set |r|'s Headers object's guard to "request-no-cors"."
- r->getHeaders()->SetGuard(Headers::kRequestNoCORSGuard);
+ r->getHeaders()->SetGuard(Headers::kRequestNoCorsGuard);
}
// "If |signal| is not null, then make |r|’s signal follow |signal|."
if (signal)
r->signal_->Follow(signal);
// "Fill |r|'s Headers object with |headers|. Rethrow any exceptions."
- if (init.hasHeaders()) {
- r->getHeaders()->FillWith(init.headers(), exception_state);
+ if (init->hasHeaders()) {
+ r->getHeaders()->FillWith(init->headers(), exception_state);
} else {
DCHECK(headers);
r->getHeaders()->FillWith(headers, exception_state);
@@ -512,10 +515,10 @@ Request* Request::CreateRequestWithRequestOrString(
// "If either |init|'s body member is present or |temporaryBody| is
// non-null, and |request|'s method is `GET` or `HEAD`, throw a TypeError.
v8::Local<v8::Value> init_body =
- init.hasBody() ? init.body().V8Value() : v8::Local<v8::Value>();
+ init->hasBody() ? init->body().V8Value() : v8::Local<v8::Value>();
if ((!init_body.IsEmpty() && !init_body->IsNull()) || temporary_body) {
- if (request->Method() == HTTPNames::GET ||
- request->Method() == HTTPNames::HEAD) {
+ if (request->Method() == http_names::kGET ||
+ request->Method() == http_names::kHEAD) {
exception_state.ThrowTypeError(
"Request with GET/HEAD method cannot have body.");
return nullptr;
@@ -539,8 +542,8 @@ Request* Request::CreateRequestWithRequestOrString(
temporary_body =
ExtractBody(script_state, exception_state, init_body, content_type);
if (!content_type.IsEmpty() &&
- !r->getHeaders()->has(HTTPNames::Content_Type, exception_state)) {
- r->getHeaders()->append(HTTPNames::Content_Type, content_type,
+ !r->getHeaders()->has(http_names::kContentType, exception_state)) {
+ r->getHeaders()->append(http_names::kContentType, content_type,
exception_state);
}
if (exception_state.HadException())
@@ -577,7 +580,7 @@ Request* Request::CreateRequestWithRequestOrString(
Request* Request::Create(ScriptState* script_state,
const RequestInfo& input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
DCHECK(!input.IsNull());
if (input.IsUSVString())
@@ -588,12 +591,12 @@ Request* Request::Create(ScriptState* script_state,
Request* Request::Create(ScriptState* script_state,
const String& input,
ExceptionState& exception_state) {
- return Create(script_state, input, RequestInit(), exception_state);
+ return Create(script_state, input, RequestInit::Create(), exception_state);
}
Request* Request::Create(ScriptState* script_state,
const String& input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
return CreateRequestWithRequestOrString(script_state, nullptr, input, init,
exception_state);
@@ -602,26 +605,33 @@ Request* Request::Create(ScriptState* script_state,
Request* Request::Create(ScriptState* script_state,
Request* input,
ExceptionState& exception_state) {
- return Create(script_state, input, RequestInit(), exception_state);
+ return Create(script_state, input, RequestInit::Create(), exception_state);
}
Request* Request::Create(ScriptState* script_state,
Request* input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
return CreateRequestWithRequestOrString(script_state, input, String(), init,
exception_state);
}
Request* Request::Create(ScriptState* script_state, FetchRequestData* request) {
- return new Request(script_state, request);
+ return MakeGarbageCollected<Request>(script_state, request);
}
Request* Request::Create(ScriptState* script_state,
const WebServiceWorkerRequest& web_request) {
- FetchRequestData* request =
- FetchRequestData::Create(script_state, web_request);
- return new Request(script_state, request);
+ FetchRequestData* data = FetchRequestData::Create(script_state, web_request);
+ return MakeGarbageCollected<Request>(script_state, data);
+}
+
+Request* Request::Create(
+ ScriptState* script_state,
+ const mojom::blink::FetchAPIRequest& fetch_api_request) {
+ FetchRequestData* data =
+ FetchRequestData::Create(script_state, fetch_api_request);
+ return MakeGarbageCollected<Request>(script_state, data);
}
bool Request::ParseCredentialsMode(
@@ -739,23 +749,24 @@ String Request::referrer() const {
String Request::getReferrerPolicy() const {
switch (request_->GetReferrerPolicy()) {
- case kReferrerPolicyAlways:
+ case network::mojom::ReferrerPolicy::kAlways:
return "unsafe-url";
- case kReferrerPolicyDefault:
+ case network::mojom::ReferrerPolicy::kDefault:
return "";
- case kReferrerPolicyNoReferrerWhenDowngrade:
+ case network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade:
return "no-referrer-when-downgrade";
- case kReferrerPolicyNever:
+ case network::mojom::ReferrerPolicy::kNever:
return "no-referrer";
- case kReferrerPolicyOrigin:
+ case network::mojom::ReferrerPolicy::kOrigin:
return "origin";
- case kReferrerPolicyOriginWhenCrossOrigin:
+ case network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin:
return "origin-when-cross-origin";
- case kReferrerPolicySameOrigin:
+ case network::mojom::ReferrerPolicy::kSameOrigin:
return "same-origin";
- case kReferrerPolicyStrictOrigin:
+ case network::mojom::ReferrerPolicy::kStrictOrigin:
return "strict-origin";
- case kReferrerPolicyStrictOriginWhenCrossOrigin:
+ case network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin:
return "strict-origin-when-cross-origin";
}
NOTREACHED();
@@ -768,10 +779,10 @@ String Request::mode() const {
switch (request_->Mode()) {
case network::mojom::FetchRequestMode::kSameOrigin:
return "same-origin";
- case network::mojom::FetchRequestMode::kNoCORS:
+ case network::mojom::FetchRequestMode::kNoCors:
return "no-cors";
- case network::mojom::FetchRequestMode::kCORS:
- case network::mojom::FetchRequestMode::kCORSWithForcedPreflight:
+ case network::mojom::FetchRequestMode::kCors:
+ case network::mojom::FetchRequestMode::kCorsWithForcedPreflight:
return "cors";
case network::mojom::FetchRequestMode::kNavigate:
return "navigate";
@@ -864,12 +875,12 @@ Request* Request::clone(ScriptState* script_state,
headers->SetGuard(headers_->GetGuard());
auto* signal = new AbortSignal(ExecutionContext::From(script_state));
signal->Follow(signal_);
- return new Request(script_state, request, headers, signal);
+ return MakeGarbageCollected<Request>(script_state, request, headers, signal);
}
FetchRequestData* Request::PassRequestData(ScriptState* script_state,
ExceptionState& exception_state) {
- DCHECK(!IsBodyUsedForDCheck());
+ DCHECK(!IsBodyUsedForDCheck(exception_state));
FetchRequestData* data = request_->Pass(script_state, exception_state);
if (exception_state.HadException())
return nullptr;
@@ -883,35 +894,49 @@ bool Request::HasBody() const {
return BodyBuffer();
}
-void Request::PopulateWebServiceWorkerRequest(
- WebServiceWorkerRequest& web_request) const {
- web_request.SetMethod(method());
- web_request.SetMode(request_->Mode());
- web_request.SetCredentialsMode(request_->Credentials());
- web_request.SetCacheMode(request_->CacheMode());
- web_request.SetRedirectMode(request_->Redirect());
- web_request.SetIntegrity(request_->Integrity());
- web_request.SetIsHistoryNavigation(request_->IsHistoryNavigation());
- web_request.SetRequestContext(request_->Context());
+mojom::blink::FetchAPIRequestPtr Request::CreateFetchAPIRequest() const {
+ auto fetch_api_request = mojom::blink::FetchAPIRequest::New();
+ fetch_api_request->method = method();
+ fetch_api_request->mode = request_->Mode();
+ fetch_api_request->credentials_mode = request_->Credentials();
+ fetch_api_request->cache_mode = request_->CacheMode();
+ fetch_api_request->redirect_mode = request_->Redirect();
+ fetch_api_request->integrity = request_->Integrity();
+ fetch_api_request->is_history_navigation = request_->IsHistoryNavigation();
+ fetch_api_request->request_context_type = request_->Context();
- // Strip off the fragment part of URL. So far, all users of
- // WebServiceWorkerRequest expect the fragment to be excluded.
+ // Strip off the fragment part of URL. So far, all callers expect the fragment
+ // to be excluded.
KURL url(request_->Url());
if (request_->Url().HasFragmentIdentifier())
url.RemoveFragmentIdentifier();
- web_request.SetURL(url);
-
- const FetchHeaderList* header_list = headers_->HeaderList();
- for (const auto& header : header_list->List()) {
- web_request.AppendHeader(header.first, header.second);
+ fetch_api_request->url = url;
+
+ HTTPHeaderMap headers;
+ for (const auto& header : headers_->HeaderList()->List()) {
+ if (DeprecatedEqualIgnoringCase(header.first, "referer"))
+ continue;
+ AtomicString key(header.first);
+ AtomicString value(header.second);
+ HTTPHeaderMap::AddResult result = headers.Add(key, value);
+ if (!result.is_new_entry) {
+ result.stored_value->value =
+ result.stored_value->value + ", " + String(value);
+ }
}
+ for (const auto& pair : headers)
+ fetch_api_request->headers.insert(pair.key, pair.value);
- web_request.SetReferrer(
- request_->ReferrerString(),
- static_cast<WebReferrerPolicy>(request_->GetReferrerPolicy()));
+ if (!request_->ReferrerString().IsEmpty()) {
+ fetch_api_request->referrer =
+ mojom::blink::Referrer::New(KURL(NullURL(), request_->ReferrerString()),
+ request_->GetReferrerPolicy());
+ DCHECK(fetch_api_request->referrer->url.IsValid());
+ }
// FIXME: How can we set isReload properly? What is the correct place to load
// it in to the Request object? We should investigate the right way to plumb
// this information in to here.
+ return fetch_api_request;
}
String Request::MimeType() const {
@@ -920,7 +945,7 @@ String Request::MimeType() const {
String Request::ContentType() const {
String result;
- request_->HeaderList()->Get(HTTPNames::Content_Type, result);
+ request_->HeaderList()->Get(http_names::kContentType, result);
return result;
}
diff --git a/chromium/third_party/blink/renderer/core/fetch/request.h b/chromium/third_party/blink/renderer/core/fetch/request.h
index a4a4471ba38..e51937d1264 100644
--- a/chromium/third_party/blink/renderer/core/fetch/request.h
+++ b/chromium/third_party/blink/renderer/core/fetch/request.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_REQUEST_H_
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/dictionary.h"
#include "third_party/blink/renderer/bindings/core/v8/request_or_usv_string.h"
@@ -37,21 +38,25 @@ class CORE_EXPORT Request final : public Body {
// From Request.idl:
static Request* Create(ScriptState*,
const RequestInfo&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
static Request* Create(ScriptState*, const String&, ExceptionState&);
static Request* Create(ScriptState*,
const String&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
static Request* Create(ScriptState*, Request*, ExceptionState&);
static Request* Create(ScriptState*,
Request*,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
static Request* Create(ScriptState*, FetchRequestData*);
static Request* Create(ScriptState*, const WebServiceWorkerRequest&);
+ static Request* Create(ScriptState*, const mojom::blink::FetchAPIRequest&);
+
+ Request(ScriptState*, FetchRequestData*, Headers*, AbortSignal*);
+ Request(ScriptState*, FetchRequestData*);
// Returns false if |credentials_mode| doesn't represent a valid credentials
// mode.
@@ -79,7 +84,7 @@ class CORE_EXPORT Request final : public Body {
Request* clone(ScriptState*, ExceptionState&);
FetchRequestData* PassRequestData(ScriptState*, ExceptionState&);
- void PopulateWebServiceWorkerRequest(WebServiceWorkerRequest&) const;
+ mojom::blink::FetchAPIRequestPtr CreateFetchAPIRequest() const;
bool HasBody() const;
BodyStreamBuffer* BodyBuffer() override { return request_->Buffer(); }
const BodyStreamBuffer* BodyBuffer() const override {
@@ -89,14 +94,11 @@ class CORE_EXPORT Request final : public Body {
void Trace(blink::Visitor*) override;
private:
- Request(ScriptState*, FetchRequestData*, Headers*, AbortSignal*);
- Request(ScriptState*, FetchRequestData*);
-
const FetchRequestData* GetRequest() const { return request_; }
static Request* CreateRequestWithRequestOrString(ScriptState*,
Request*,
const String&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
String ContentType() const override;
diff --git a/chromium/third_party/blink/renderer/core/fetch/request_test.cc b/chromium/third_party/blink/renderer/core/fetch/request_test.cc
index 4a2e267ebe9..d5720fcfd56 100644
--- a/chromium/third_party/blink/renderer/core/fetch/request_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/request_test.cc
@@ -46,9 +46,9 @@ TEST(ServiceWorkerRequestTest, FromRequest) {
EXPECT_EQ(url, request2->url());
}
-TEST(ServiceWorkerRequestTest, FromAndToWebRequest) {
+TEST(ServiceWorkerRequestTest, FromAndToFetchAPIRequest) {
V8TestingScope scope;
- WebServiceWorkerRequest web_request;
+ auto fetch_api_request = mojom::blink::FetchAPIRequest::New();
const KURL url("http://www.example.com/");
const String method = "GET";
@@ -57,7 +57,8 @@ TEST(ServiceWorkerRequestTest, FromAndToWebRequest) {
const char* value;
} headers[] = {{"X-Foo", "bar"}, {"X-Quux", "foop"}, {nullptr, nullptr}};
const String referrer = "http://www.referrer.com/";
- const WebReferrerPolicy kReferrerPolicy = kWebReferrerPolicyAlways;
+ const network::mojom::ReferrerPolicy kReferrerPolicy =
+ network::mojom::ReferrerPolicy::kAlways;
const mojom::RequestContextType kContext = mojom::RequestContextType::AUDIO;
const network::mojom::FetchRequestMode kMode =
network::mojom::FetchRequestMode::kNavigate;
@@ -67,20 +68,20 @@ TEST(ServiceWorkerRequestTest, FromAndToWebRequest) {
const network::mojom::FetchRedirectMode kRedirectMode =
network::mojom::FetchRedirectMode::kError;
- web_request.SetURL(url);
- web_request.SetMethod(method);
- web_request.SetMode(kMode);
- web_request.SetCredentialsMode(kCredentialsMode);
- web_request.SetCacheMode(kCacheMode);
- web_request.SetRedirectMode(kRedirectMode);
- web_request.SetRequestContext(kContext);
- for (int i = 0; headers[i].key; ++i) {
- web_request.SetHeader(WebString::FromUTF8(headers[i].key),
- WebString::FromUTF8(headers[i].value));
- }
- web_request.SetReferrer(referrer, kReferrerPolicy);
+ fetch_api_request->url = url;
+ fetch_api_request->method = method;
+ fetch_api_request->mode = kMode;
+ fetch_api_request->credentials_mode = kCredentialsMode;
+ fetch_api_request->cache_mode = kCacheMode;
+ fetch_api_request->redirect_mode = kRedirectMode;
+ fetch_api_request->request_context_type = kContext;
+ for (int i = 0; headers[i].key; ++i)
+ fetch_api_request->headers.insert(headers[i].key, headers[i].value);
+ fetch_api_request->referrer =
+ mojom::blink::Referrer::New(KURL(NullURL(), referrer), kReferrerPolicy);
- Request* request = Request::Create(scope.GetScriptState(), web_request);
+ Request* request =
+ Request::Create(scope.GetScriptState(), *fetch_api_request);
DCHECK(request);
EXPECT_EQ(url, request->url());
EXPECT_EQ(method, request->method());
@@ -101,21 +102,22 @@ TEST(ServiceWorkerRequestTest, FromAndToWebRequest) {
EXPECT_FALSE(exception_state.HadException());
}
- WebServiceWorkerRequest second_web_request;
- request->PopulateWebServiceWorkerRequest(second_web_request);
- EXPECT_EQ(url, KURL(second_web_request.Url()));
- EXPECT_EQ(method, String(second_web_request.Method()));
- EXPECT_EQ(kMode, second_web_request.Mode());
- EXPECT_EQ(kCredentialsMode, second_web_request.CredentialsMode());
- EXPECT_EQ(kCacheMode, second_web_request.CacheMode());
- EXPECT_EQ(kRedirectMode, second_web_request.RedirectMode());
- EXPECT_EQ(kContext, second_web_request.GetRequestContext());
- EXPECT_EQ(referrer, KURL(second_web_request.ReferrerUrl()));
- EXPECT_EQ(kWebReferrerPolicyAlways, second_web_request.GetReferrerPolicy());
- EXPECT_EQ(web_request.Headers(), second_web_request.Headers());
+ mojom::blink::FetchAPIRequestPtr second_fetch_api_request =
+ request->CreateFetchAPIRequest();
+ EXPECT_EQ(url, second_fetch_api_request->url);
+ EXPECT_EQ(method, second_fetch_api_request->method);
+ EXPECT_EQ(kMode, second_fetch_api_request->mode);
+ EXPECT_EQ(kCredentialsMode, second_fetch_api_request->credentials_mode);
+ EXPECT_EQ(kCacheMode, second_fetch_api_request->cache_mode);
+ EXPECT_EQ(kRedirectMode, second_fetch_api_request->redirect_mode);
+ EXPECT_EQ(kContext, second_fetch_api_request->request_context_type);
+ EXPECT_EQ(referrer, second_fetch_api_request->referrer->url);
+ EXPECT_EQ(network::mojom::ReferrerPolicy::kAlways,
+ second_fetch_api_request->referrer->policy);
+ EXPECT_EQ(fetch_api_request->headers, second_fetch_api_request->headers);
}
-TEST(ServiceWorkerRequestTest, ToWebRequestStripsURLFragment) {
+TEST(ServiceWorkerRequestTest, ToFetchAPIRequestStripsURLFragment) {
V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
String url_without_fragment = "http://www.example.com/";
@@ -124,9 +126,9 @@ TEST(ServiceWorkerRequestTest, ToWebRequestStripsURLFragment) {
Request::Create(scope.GetScriptState(), url, exception_state);
DCHECK(request);
- WebServiceWorkerRequest web_request;
- request->PopulateWebServiceWorkerRequest(web_request);
- EXPECT_EQ(url_without_fragment, KURL(web_request.Url()));
+ mojom::blink::FetchAPIRequestPtr fetch_api_request =
+ request->CreateFetchAPIRequest();
+ EXPECT_EQ(url_without_fragment, fetch_api_request->url);
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/fetch/response.cc b/chromium/third_party/blink/renderer/core/fetch/response.cc
index fde49976afb..8816b18ff17 100644
--- a/chromium/third_party/blink/renderer/core/fetch/response.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/response.cc
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_array_buffer_view.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_blob.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_form_data.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_url_search_params.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fetch/blob_bytes_consumer.h"
@@ -26,7 +27,6 @@
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/form_data.h"
-#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h"
#include "third_party/blink/renderer/core/url/url_search_params.h"
@@ -44,20 +44,20 @@ namespace blink {
namespace {
-template <typename CORSHeadersContainer>
+template <typename CorsHeadersContainer>
FetchResponseData* FilterResponseData(
network::mojom::FetchResponseType response_type,
FetchResponseData* response,
- CORSHeadersContainer& headers) {
+ CorsHeadersContainer& headers) {
switch (response_type) {
case network::mojom::FetchResponseType::kBasic:
return response->CreateBasicFilteredResponse();
break;
- case network::mojom::FetchResponseType::kCORS: {
+ case network::mojom::FetchResponseType::kCors: {
WebHTTPHeaderSet header_names;
for (const auto& header : headers)
header_names.insert(header.Ascii().data());
- return response->CreateCORSFilteredResponse(header_names);
+ return response->CreateCorsFilteredResponse(header_names);
break;
}
case network::mojom::FetchResponseType::kOpaque:
@@ -140,13 +140,13 @@ bool IsValidReasonPhrase(const String& status_text) {
Response* Response::Create(ScriptState* script_state,
ExceptionState& exception_state) {
- return Create(script_state, nullptr, String(), ResponseInit(),
+ return Create(script_state, nullptr, String(), ResponseInit::Create(),
exception_state);
}
Response* Response::Create(ScriptState* script_state,
ScriptValue body_value,
- const ResponseInit& init,
+ const ResponseInit* init,
ExceptionState& exception_state) {
v8::Local<v8::Value> body = body_value.V8Value();
v8::Isolate* isolate = script_state->GetIsolate();
@@ -157,7 +157,7 @@ Response* Response::Create(ScriptState* script_state,
if (body_value.IsUndefined() || body_value.IsNull()) {
// Note: The IDL processor cannot handle this situation. See
// https://crbug.com/335871.
- } else if (V8Blob::hasInstance(body, isolate)) {
+ } else if (V8Blob::HasInstance(body, isolate)) {
Blob* blob = V8Blob::ToImpl(body.As<v8::Object>());
body_buffer = new BodyStreamBuffer(
script_state,
@@ -168,55 +168,52 @@ Response* Response::Create(ScriptState* script_state,
// Avoid calling into V8 from the following constructor parameters, which
// is potentially unsafe.
DOMArrayBuffer* array_buffer = V8ArrayBuffer::ToImpl(body.As<v8::Object>());
- body_buffer = new BodyStreamBuffer(script_state,
- new FormDataBytesConsumer(array_buffer),
- nullptr /* AbortSignal */);
+ body_buffer = new BodyStreamBuffer(
+ script_state, MakeGarbageCollected<FormDataBytesConsumer>(array_buffer),
+ nullptr /* AbortSignal */);
} else if (body->IsArrayBufferView()) {
// Avoid calling into V8 from the following constructor parameters, which
// is potentially unsafe.
DOMArrayBufferView* array_buffer_view =
V8ArrayBufferView::ToImpl(body.As<v8::Object>());
body_buffer = new BodyStreamBuffer(
- script_state, new FormDataBytesConsumer(array_buffer_view),
+ script_state,
+ MakeGarbageCollected<FormDataBytesConsumer>(array_buffer_view),
nullptr /* AbortSignal */);
- } else if (V8FormData::hasInstance(body, isolate)) {
+ } else if (V8FormData::HasInstance(body, isolate)) {
scoped_refptr<EncodedFormData> form_data =
V8FormData::ToImpl(body.As<v8::Object>())->EncodeMultiPartFormData();
// Here we handle formData->boundary() as a C-style string. See
// FormDataEncoder::generateUniqueBoundaryString.
content_type = AtomicString("multipart/form-data; boundary=") +
form_data->Boundary().data();
- body_buffer = new BodyStreamBuffer(
- script_state,
- new FormDataBytesConsumer(execution_context, std::move(form_data)),
- nullptr /* AbortSignal */);
- } else if (V8URLSearchParams::hasInstance(body, isolate)) {
+ body_buffer =
+ new BodyStreamBuffer(script_state,
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ execution_context, std::move(form_data)),
+ nullptr /* AbortSignal */);
+ } else if (V8URLSearchParams::HasInstance(body, isolate)) {
scoped_refptr<EncodedFormData> form_data =
V8URLSearchParams::ToImpl(body.As<v8::Object>())->ToEncodedFormData();
- body_buffer = new BodyStreamBuffer(
- script_state,
- new FormDataBytesConsumer(execution_context, std::move(form_data)),
- nullptr /* AbortSignal */);
+ body_buffer =
+ new BodyStreamBuffer(script_state,
+ MakeGarbageCollected<FormDataBytesConsumer>(
+ execution_context, std::move(form_data)),
+ nullptr /* AbortSignal */);
content_type = "application/x-www-form-urlencoded;charset=UTF-8";
- } else if (ReadableStreamOperations::IsReadableStream(
- script_state, body_value, exception_state)
- .value_or(true)) {
- if (exception_state.HadException())
- return nullptr;
+ } else if (V8ReadableStream::HasInstance(body, isolate)) {
UseCounter::Count(execution_context,
WebFeature::kFetchResponseConstructionWithStream);
- body_buffer =
- new BodyStreamBuffer(script_state, body_value, exception_state);
- if (exception_state.HadException())
- return nullptr;
+ body_buffer = new BodyStreamBuffer(
+ script_state, V8ReadableStream::ToImpl(body.As<v8::Object>()));
} else {
String string = NativeValueTraits<IDLUSVString>::NativeValue(
isolate, body, exception_state);
if (exception_state.HadException())
return nullptr;
- body_buffer =
- new BodyStreamBuffer(script_state, new FormDataBytesConsumer(string),
- nullptr /* AbortSignal */);
+ body_buffer = new BodyStreamBuffer(
+ script_state, MakeGarbageCollected<FormDataBytesConsumer>(string),
+ nullptr /* AbortSignal */);
content_type = "text/plain;charset=UTF-8";
}
return Create(script_state, body_buffer, content_type, init, exception_state);
@@ -225,9 +222,9 @@ Response* Response::Create(ScriptState* script_state,
Response* Response::Create(ScriptState* script_state,
BodyStreamBuffer* body,
const String& content_type,
- const ResponseInit& init,
+ const ResponseInit* init,
ExceptionState& exception_state) {
- unsigned short status = init.status();
+ unsigned short status = init->status();
// "1. If |init|'s status member is not in the range 200 to 599, inclusive,
// throw a RangeError."
@@ -241,7 +238,7 @@ Response* Response::Create(ScriptState* script_state,
// "2. If |init|'s statusText member does not match the Reason-Phrase
// token production, throw a TypeError."
- if (!IsValidReasonPhrase(init.statusText())) {
+ if (!IsValidReasonPhrase(init->statusText())) {
exception_state.ThrowTypeError("Invalid statusText");
return nullptr;
}
@@ -249,21 +246,22 @@ Response* Response::Create(ScriptState* script_state,
// "3. Let |r| be a new Response object, associated with a new response.
// "4. Set |r|'s headers to a new Headers object whose list is
// |r|'s response's header list, and guard is "response" "
- Response* r = new Response(ExecutionContext::From(script_state));
+ Response* r =
+ MakeGarbageCollected<Response>(ExecutionContext::From(script_state));
// "5. Set |r|'s response's status to |init|'s status member."
- r->response_->SetStatus(init.status());
+ r->response_->SetStatus(init->status());
// "6. Set |r|'s response's status message to |init|'s statusText member."
- r->response_->SetStatusMessage(AtomicString(init.statusText()));
+ r->response_->SetStatusMessage(AtomicString(init->statusText()));
// "7. If |init|'s headers exists, then fill |r|’s headers with
// |init|'s headers"
- if (init.hasHeaders()) {
+ if (init->hasHeaders()) {
// "1. Empty |r|'s response's header list."
r->response_->HeaderList()->ClearList();
// "2. Fill |r|'s Headers object with |init|'s headers member. Rethrow
// any exceptions."
- r->headers_->FillWith(init.headers(), exception_state);
+ r->headers_->FillWith(init->headers(), exception_state);
if (exception_state.HadException())
return nullptr;
}
@@ -322,22 +320,22 @@ Response* Response::Create(ScriptState* script_state,
Response* Response::Create(ExecutionContext* context,
FetchResponseData* response) {
- return new Response(context, response);
+ return MakeGarbageCollected<Response>(context, response);
}
Response* Response::Create(ScriptState* script_state,
mojom::blink::FetchAPIResponse& response) {
auto* fetch_response_data =
CreateFetchResponseDataFromFetchAPIResponse(script_state, response);
- return new Response(ExecutionContext::From(script_state),
- fetch_response_data);
+ return MakeGarbageCollected<Response>(ExecutionContext::From(script_state),
+ fetch_response_data);
}
Response* Response::error(ScriptState* script_state) {
FetchResponseData* response_data =
FetchResponseData::CreateNetworkErrorResponse();
- Response* r =
- new Response(ExecutionContext::From(script_state), response_data);
+ Response* r = MakeGarbageCollected<Response>(
+ ExecutionContext::From(script_state), response_data);
r->headers_->SetGuard(Headers::kImmutableGuard);
return r;
}
@@ -352,12 +350,13 @@ Response* Response::redirect(ScriptState* script_state,
return nullptr;
}
- if (!NetworkUtils::IsRedirectResponseCode(status)) {
+ if (!network_utils::IsRedirectResponseCode(status)) {
exception_state.ThrowRangeError("Invalid status code");
return nullptr;
}
- Response* r = new Response(ExecutionContext::From(script_state));
+ Response* r =
+ MakeGarbageCollected<Response>(ExecutionContext::From(script_state));
r->headers_->SetGuard(Headers::kImmutableGuard);
r->response_->SetStatus(status);
r->response_->HeaderList()->Set("Location", parsed_url);
@@ -370,7 +369,7 @@ String Response::type() const {
switch (response_->GetType()) {
case network::mojom::FetchResponseType::kBasic:
return "basic";
- case network::mojom::FetchResponseType::kCORS:
+ case network::mojom::FetchResponseType::kCors:
return "cors";
case network::mojom::FetchResponseType::kDefault:
return "default";
@@ -411,7 +410,7 @@ unsigned short Response::status() const {
bool Response::ok() const {
// "The ok attribute's getter must return true
// if response's status is in the range 200 to 299, and false otherwise."
- return CORS::IsOkStatus(status());
+ return cors::IsOkStatus(status());
}
String Response::statusText() const {
@@ -441,7 +440,8 @@ Response* Response::clone(ScriptState* script_state,
return nullptr;
Headers* headers = Headers::Create(response->HeaderList());
headers->SetGuard(headers_->GetGuard());
- return new Response(GetExecutionContext(), response, headers);
+ return MakeGarbageCollected<Response>(GetExecutionContext(), response,
+ headers);
}
bool Response::HasPendingActivity() const {
@@ -498,7 +498,7 @@ String Response::MimeType() const {
String Response::ContentType() const {
String result;
- response_->HeaderList()->Get(HTTPNames::Content_Type, result);
+ response_->HeaderList()->Get(http_names::kContentType, result);
return result;
}
@@ -516,9 +516,9 @@ void Response::Trace(blink::Visitor* visitor) {
visitor->Trace(headers_);
}
-bool Response::IsBodyUsedForDCheck() {
+bool Response::IsBodyUsedForDCheck(ExceptionState& exception_state) {
return InternalBodyBuffer() &&
- InternalBodyBuffer()->IsStreamDisturbedForDCheck();
+ InternalBodyBuffer()->IsStreamDisturbedForDCheck(exception_state);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fetch/response.h b/chromium/third_party/blink/renderer/core/fetch/response.h
index 844989f1a5e..b8c76fab0b3 100644
--- a/chromium/third_party/blink/renderer/core/fetch/response.h
+++ b/chromium/third_party/blink/renderer/core/fetch/response.h
@@ -36,13 +36,13 @@ class CORE_EXPORT Response final : public Body {
static Response* Create(ScriptState*, ExceptionState&);
static Response* Create(ScriptState*,
ScriptValue body,
- const ResponseInit&,
+ const ResponseInit*,
ExceptionState&);
static Response* Create(ScriptState*,
BodyStreamBuffer*,
const String& content_type,
- const ResponseInit&,
+ const ResponseInit*,
ExceptionState&);
static Response* Create(ExecutionContext*, FetchResponseData*);
static Response* Create(ScriptState*, mojom::blink::FetchAPIResponse&);
@@ -55,6 +55,10 @@ class CORE_EXPORT Response final : public Body {
unsigned short status,
ExceptionState&);
+ explicit Response(ExecutionContext*);
+ Response(ExecutionContext*, FetchResponseData*);
+ Response(ExecutionContext*, FetchResponseData*, Headers*);
+
const FetchResponseData* GetResponse() const { return response_; }
// From Response.idl:
@@ -105,13 +109,9 @@ class CORE_EXPORT Response final : public Body {
protected:
// A version of IsBodyUsed() which catches exceptions and returns
// false. Should never be used outside DCHECK().
- bool IsBodyUsedForDCheck() override;
+ bool IsBodyUsedForDCheck(ExceptionState&) override;
private:
- explicit Response(ExecutionContext*);
- Response(ExecutionContext*, FetchResponseData*);
- Response(ExecutionContext*, FetchResponseData*, Headers*);
-
const TraceWrapperMember<FetchResponseData> response_;
const Member<Headers> headers_;
DISALLOW_COPY_AND_ASSIGN(Response);
diff --git a/chromium/third_party/blink/renderer/core/fetch/response.idl b/chromium/third_party/blink/renderer/core/fetch/response.idl
index 16e83e2d77d..0b5cdb79ea1 100644
--- a/chromium/third_party/blink/renderer/core/fetch/response.idl
+++ b/chromium/third_party/blink/renderer/core/fetch/response.idl
@@ -27,7 +27,7 @@ enum ResponseType { "basic", "cors", "default", "error", "opaque", "opaqueredire
[RaisesException, CallWith=ScriptState, DoNotTestNewObject, NewObject] Response clone();
- [CallWith=ScriptState, MeasureAs=FetchBodyStream] readonly attribute any body;
+ [MeasureAs=FetchBodyStream] readonly attribute ReadableStream? body;
};
Response implements Body;
diff --git a/chromium/third_party/blink/renderer/core/fetch/response_test.cc b/chromium/third_party/blink/renderer/core/fetch/response_test.cc
index b3abfbf4da7..4bca9a8ba62 100644
--- a/chromium/third_party/blink/renderer/core/fetch/response_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/response_test.cc
@@ -129,7 +129,7 @@ TEST(ServiceWorkerResponseTest, BodyStreamBufferCloneBasic) {
CheckResponseStream(scope.GetScriptState(), response, true);
}
-TEST(ServiceWorkerResponseTest, BodyStreamBufferCloneCORS) {
+TEST(ServiceWorkerResponseTest, BodyStreamBufferCloneCors) {
V8TestingScope scope;
BodyStreamBuffer* buffer = CreateHelloWorldBuffer(scope.GetScriptState());
FetchResponseData* fetch_response_data =
@@ -137,7 +137,7 @@ TEST(ServiceWorkerResponseTest, BodyStreamBufferCloneCORS) {
Vector<KURL> url_list;
url_list.push_back(KURL("http://www.response.com"));
fetch_response_data->SetURLList(url_list);
- fetch_response_data = fetch_response_data->CreateCORSFilteredResponse({});
+ fetch_response_data = fetch_response_data->CreateCorsFilteredResponse({});
Response* response =
Response::Create(scope.GetExecutionContext(), fetch_response_data);
EXPECT_EQ(response->InternalBodyBuffer(), buffer);
diff --git a/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc b/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc
index 4459b432707..a93d99a44b2 100644
--- a/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc
@@ -32,7 +32,7 @@ int WorkerInternalsFetch::getResourcePriority(
return static_cast<int>(ResourceLoadPriority::kUnresolved);
Resource* resource = worker_global->Fetcher()->AllResources().at(
- URLTestHelpers::ToKURL(url.Utf8().data()));
+ url_test_helpers::ToKURL(url.Utf8().data()));
if (!resource)
return static_cast<int>(ResourceLoadPriority::kUnresolved);
diff --git a/chromium/third_party/blink/renderer/core/fileapi/blob.cc b/chromium/third_party/blink/renderer/core/fileapi/blob.cc
index 87c33867bc0..494a2b31ed1 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/blob.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/blob.cc
@@ -84,17 +84,17 @@ Blob::~Blob() = default;
Blob* Blob::Create(
ExecutionContext* context,
const HeapVector<ArrayBufferOrArrayBufferViewOrBlobOrUSVString>& blob_parts,
- const BlobPropertyBag& options,
+ const BlobPropertyBag* options,
ExceptionState& exception_state) {
- DCHECK(options.hasType());
+ DCHECK(options->hasType());
- DCHECK(options.hasEndings());
- bool normalize_line_endings_to_native = options.endings() == "native";
+ DCHECK(options->hasEndings());
+ bool normalize_line_endings_to_native = (options->endings() == "native");
if (normalize_line_endings_to_native)
UseCounter::Count(context, WebFeature::kFileAPINativeLineEndings);
std::unique_ptr<BlobData> blob_data = BlobData::Create();
- blob_data->SetContentType(NormalizeType(options.type()));
+ blob_data->SetContentType(NormalizeType(options->type()));
PopulateBlobData(blob_data.get(), blob_parts,
normalize_line_endings_to_native);
diff --git a/chromium/third_party/blink/renderer/core/fileapi/blob.h b/chromium/third_party/blink/renderer/core/fileapi/blob.h
index 2173f64c1f5..e02dabae0ef 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/blob.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/blob.h
@@ -62,7 +62,7 @@ class CORE_EXPORT Blob : public ScriptWrappable,
static Blob* Create(
ExecutionContext*,
const HeapVector<ArrayBufferOrArrayBufferViewOrBlobOrUSVString>&,
- const BlobPropertyBag&,
+ const BlobPropertyBag*,
ExceptionState&);
static Blob* Create(scoped_refptr<BlobDataHandle> blob_data_handle) {
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file.cc b/chromium/third_party/blink/renderer/core/fileapi/file.cc
index 01df3889651..22cfc7837f4 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file.cc
@@ -126,22 +126,22 @@ File* File::Create(
ExecutionContext* context,
const HeapVector<ArrayBufferOrArrayBufferViewOrBlobOrUSVString>& file_bits,
const String& file_name,
- const FilePropertyBag& options,
+ const FilePropertyBag* options,
ExceptionState& exception_state) {
- DCHECK(options.hasType());
+ DCHECK(options->hasType());
double last_modified;
- if (options.hasLastModified())
- last_modified = static_cast<double>(options.lastModified());
+ if (options->hasLastModified())
+ last_modified = static_cast<double>(options->lastModified());
else
last_modified = CurrentTimeMS();
- DCHECK(options.hasEndings());
- bool normalize_line_endings_to_native = options.endings() == "native";
+ DCHECK(options->hasEndings());
+ bool normalize_line_endings_to_native = options->endings() == "native";
if (normalize_line_endings_to_native)
UseCounter::Count(context, WebFeature::kFileAPINativeLineEndings);
std::unique_ptr<BlobData> blob_data = BlobData::Create();
- blob_data->SetContentType(NormalizeType(options.type()));
+ blob_data->SetContentType(NormalizeType(options->type()));
PopulateBlobData(blob_data.get(), file_bits,
normalize_line_endings_to_native);
@@ -152,7 +152,8 @@ File* File::Create(
File* File::CreateWithRelativePath(const String& path,
const String& relative_path) {
- File* file = new File(path, File::kAllContentTypes, File::kIsUserVisible);
+ File* file = MakeGarbageCollected<File>(path, File::kAllContentTypes,
+ File::kIsUserVisible);
file->relative_path_ = relative_path;
return file;
}
@@ -248,7 +249,7 @@ File::File(const File& other)
relative_path_(other.relative_path_) {}
File* File::Clone(const String& name) const {
- File* file = new File(*this);
+ File* file = MakeGarbageCollected<File>(*this);
if (!name.IsNull())
file->name_ = name;
return file;
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file.h b/chromium/third_party/blink/renderer/core/fileapi/file.h
index 39831f1902c..2ca09ab8903 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file.h
@@ -62,18 +62,19 @@ class CORE_EXPORT File final : public Blob {
ExecutionContext*,
const HeapVector<ArrayBufferOrArrayBufferViewOrBlobOrUSVString>&,
const String& file_name,
- const FilePropertyBag&,
+ const FilePropertyBag*,
ExceptionState&);
static File* Create(const String& path,
ContentTypeLookupPolicy policy = kWellKnownContentTypes) {
- return new File(path, policy, File::kIsUserVisible);
+ return MakeGarbageCollected<File>(path, policy, File::kIsUserVisible);
}
static File* Create(const String& name,
double modification_time,
scoped_refptr<BlobDataHandle> blob_data_handle) {
- return new File(name, modification_time, std::move(blob_data_handle));
+ return MakeGarbageCollected<File>(name, modification_time,
+ std::move(blob_data_handle));
}
// For deserialization.
@@ -86,9 +87,9 @@ class CORE_EXPORT File final : public Blob {
uint64_t size,
double last_modified,
scoped_refptr<BlobDataHandle> blob_data_handle) {
- return new File(path, name, relative_path, user_visibility,
- has_snapshot_data, size, last_modified,
- std::move(blob_data_handle));
+ return MakeGarbageCollected<File>(
+ path, name, relative_path, user_visibility, has_snapshot_data, size,
+ last_modified, std::move(blob_data_handle));
}
static File* CreateFromIndexedSerialization(
const String& path,
@@ -96,8 +97,9 @@ class CORE_EXPORT File final : public Blob {
uint64_t size,
double last_modified,
scoped_refptr<BlobDataHandle> blob_data_handle) {
- return new File(path, name, String(), kIsNotUserVisible, true, size,
- last_modified, std::move(blob_data_handle));
+ return MakeGarbageCollected<File>(path, name, String(), kIsNotUserVisible,
+ true, size, last_modified,
+ std::move(blob_data_handle));
}
static File* CreateWithRelativePath(const String& path,
@@ -112,15 +114,35 @@ class CORE_EXPORT File final : public Blob {
static File* CreateForFileSystemFile(const String& name,
const FileMetadata& metadata,
UserVisibility user_visibility) {
- return new File(name, metadata, user_visibility);
+ return MakeGarbageCollected<File>(name, metadata, user_visibility);
}
static File* CreateForFileSystemFile(const KURL& url,
const FileMetadata& metadata,
UserVisibility user_visibility) {
- return new File(url, metadata, user_visibility);
+ return MakeGarbageCollected<File>(url, metadata, user_visibility);
}
+ File(const String& path, ContentTypeLookupPolicy, UserVisibility);
+ File(const String& path,
+ const String& name,
+ ContentTypeLookupPolicy,
+ UserVisibility);
+ File(const String& path,
+ const String& name,
+ const String& relative_path,
+ UserVisibility,
+ bool has_snapshot_data,
+ uint64_t size,
+ double last_modified,
+ scoped_refptr<BlobDataHandle>);
+ File(const String& name,
+ double modification_time,
+ scoped_refptr<BlobDataHandle>);
+ File(const String& name, const FileMetadata&, UserVisibility);
+ File(const KURL& file_system_url, const FileMetadata&, UserVisibility);
+ File(const File&);
+
KURL FileSystemURL() const {
#if DCHECK_IS_ON()
DCHECK(HasValidFileSystemURL());
@@ -132,10 +154,12 @@ class CORE_EXPORT File final : public Blob {
// associated DOM properties) that differs from the one provided in the path.
static File* CreateForUserProvidedFile(const String& path,
const String& display_name) {
- if (display_name.IsEmpty())
- return new File(path, File::kAllContentTypes, File::kIsUserVisible);
- return new File(path, display_name, File::kAllContentTypes,
- File::kIsUserVisible);
+ if (display_name.IsEmpty()) {
+ return MakeGarbageCollected<File>(path, File::kAllContentTypes,
+ File::kIsUserVisible);
+ }
+ return MakeGarbageCollected<File>(
+ path, display_name, File::kAllContentTypes, File::kIsUserVisible);
}
static File* CreateForFileSystemFile(
@@ -143,8 +167,9 @@ class CORE_EXPORT File final : public Blob {
const String& name,
ContentTypeLookupPolicy policy = kWellKnownContentTypes) {
if (name.IsEmpty())
- return new File(path, policy, File::kIsNotUserVisible);
- return new File(path, name, policy, File::kIsNotUserVisible);
+ return MakeGarbageCollected<File>(path, policy, File::kIsNotUserVisible);
+ return MakeGarbageCollected<File>(path, name, policy,
+ File::kIsNotUserVisible);
}
File* Clone(const String& name = String()) const;
@@ -196,26 +221,6 @@ class CORE_EXPORT File final : public Blob {
bool HasSameSource(const File& other) const;
private:
- File(const String& path, ContentTypeLookupPolicy, UserVisibility);
- File(const String& path,
- const String& name,
- ContentTypeLookupPolicy,
- UserVisibility);
- File(const String& path,
- const String& name,
- const String& relative_path,
- UserVisibility,
- bool has_snapshot_data,
- uint64_t size,
- double last_modified,
- scoped_refptr<BlobDataHandle>);
- File(const String& name,
- double modification_time,
- scoped_refptr<BlobDataHandle>);
- File(const String& name, const FileMetadata&, UserVisibility);
- File(const KURL& file_system_url, const FileMetadata&, UserVisibility);
- File(const File&);
-
void InvalidateSnapshotMetadata() { snapshot_size_ = -1; }
// Returns File's last modified time (in MS since Epoch.)
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_error.cc b/chromium/third_party/blink/renderer/core/fileapi/file_error.cc
index a0d08edc7da..4fbca6770cf 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_error.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_error.cc
@@ -36,7 +36,7 @@
namespace blink {
-namespace FileError {
+namespace file_error {
const char kAbortErrorMessage[] =
"An ongoing operation was aborted, typically with a call to abort().";
@@ -72,33 +72,33 @@ const char kTypeMismatchErrorMessage[] =
namespace {
-DOMExceptionCode ErrorCodeToExceptionCode(ErrorCode code) {
+DOMExceptionCode ErrorCodeToExceptionCode(FileErrorCode code) {
switch (code) {
- case kOK:
+ case FileErrorCode::kOK:
return DOMExceptionCode::kNoError;
- case kNotFoundErr:
+ case FileErrorCode::kNotFoundErr:
return DOMExceptionCode::kNotFoundError;
- case kSecurityErr:
+ case FileErrorCode::kSecurityErr:
return DOMExceptionCode::kSecurityError;
- case kAbortErr:
+ case FileErrorCode::kAbortErr:
return DOMExceptionCode::kAbortError;
- case kNotReadableErr:
+ case FileErrorCode::kNotReadableErr:
return DOMExceptionCode::kNotReadableError;
- case kEncodingErr:
+ case FileErrorCode::kEncodingErr:
return DOMExceptionCode::kEncodingError;
- case kNoModificationAllowedErr:
+ case FileErrorCode::kNoModificationAllowedErr:
return DOMExceptionCode::kNoModificationAllowedError;
- case kInvalidStateErr:
+ case FileErrorCode::kInvalidStateErr:
return DOMExceptionCode::kInvalidStateError;
- case kSyntaxErr:
+ case FileErrorCode::kSyntaxErr:
return DOMExceptionCode::kSyntaxError;
- case kInvalidModificationErr:
+ case FileErrorCode::kInvalidModificationErr:
return DOMExceptionCode::kInvalidModificationError;
- case kQuotaExceededErr:
+ case FileErrorCode::kQuotaExceededErr:
return DOMExceptionCode::kQuotaExceededError;
- case kTypeMismatchErr:
+ case FileErrorCode::kTypeMismatchErr:
return DOMExceptionCode::kTypeMismatchError;
- case kPathExistsErr:
+ case FileErrorCode::kPathExistsErr:
return DOMExceptionCode::kPathExistsError;
default:
NOTREACHED();
@@ -106,35 +106,35 @@ DOMExceptionCode ErrorCodeToExceptionCode(ErrorCode code) {
}
}
-const char* ErrorCodeToMessage(ErrorCode code) {
+const char* ErrorCodeToMessage(FileErrorCode code) {
// Note that some of these do not set message. If message is 0 then the
// default message is used.
switch (code) {
- case kOK:
+ case FileErrorCode::kOK:
return nullptr;
- case kSecurityErr:
+ case FileErrorCode::kSecurityErr:
return kSecurityErrorMessage;
- case kNotFoundErr:
+ case FileErrorCode::kNotFoundErr:
return kNotFoundErrorMessage;
- case kAbortErr:
+ case FileErrorCode::kAbortErr:
return kAbortErrorMessage;
- case kNotReadableErr:
+ case FileErrorCode::kNotReadableErr:
return kNotReadableErrorMessage;
- case kEncodingErr:
+ case FileErrorCode::kEncodingErr:
return kEncodingErrorMessage;
- case kNoModificationAllowedErr:
+ case FileErrorCode::kNoModificationAllowedErr:
return kNoModificationAllowedErrorMessage;
- case kInvalidStateErr:
+ case FileErrorCode::kInvalidStateErr:
return kInvalidStateErrorMessage;
- case kSyntaxErr:
+ case FileErrorCode::kSyntaxErr:
return kSyntaxErrorMessage;
- case kInvalidModificationErr:
+ case FileErrorCode::kInvalidModificationErr:
return nullptr;
- case kQuotaExceededErr:
+ case FileErrorCode::kQuotaExceededErr:
return kQuotaExceededErrorMessage;
- case kTypeMismatchErr:
+ case FileErrorCode::kTypeMismatchErr:
return nullptr;
- case kPathExistsErr:
+ case FileErrorCode::kPathExistsErr:
return kPathExistsErrorMessage;
default:
NOTREACHED();
@@ -229,14 +229,14 @@ const char* FileErrorToMessage(base::File::Error code) {
} // namespace
void ThrowDOMException(ExceptionState& exception_state,
- ErrorCode code,
+ FileErrorCode code,
String message) {
- if (code == kOK)
+ if (code == FileErrorCode::kOK)
return;
// SecurityError is special-cased, as we want to route those exceptions
// through ExceptionState::ThrowSecurityError.
- if (code == kSecurityErr) {
+ if (code == FileErrorCode::kSecurityErr) {
exception_state.ThrowSecurityError(kSecurityErrorMessage);
return;
}
@@ -268,8 +268,8 @@ void ThrowDOMException(ExceptionState& exception_state,
exception_state.ThrowDOMException(FileErrorToExceptionCode(error), message);
}
-DOMException* CreateDOMException(ErrorCode code) {
- DCHECK_NE(code, kOK);
+DOMException* CreateDOMException(FileErrorCode code) {
+ DCHECK_NE(code, FileErrorCode::kOK);
return DOMException::Create(ErrorCodeToExceptionCode(code),
ErrorCodeToMessage(code));
}
@@ -280,6 +280,6 @@ DOMException* CreateDOMException(base::File::Error code) {
FileErrorToMessage(code));
}
-} // namespace FileError
+} // namespace file_error
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_error.h b/chromium/third_party/blink/renderer/core/fileapi/file_error.h
index bea0453e8b3..ac22e5ec09e 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_error.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_error.h
@@ -40,9 +40,7 @@ namespace blink {
class DOMException;
class ExceptionState;
-namespace FileError {
-
-enum ErrorCode {
+enum class FileErrorCode {
kOK = 0,
kNotFoundErr = 1,
kSecurityErr = 2,
@@ -58,6 +56,8 @@ enum ErrorCode {
kPathExistsErr = 12,
};
+namespace file_error {
+
CORE_EXPORT extern const char kAbortErrorMessage[];
CORE_EXPORT extern const char kEncodingErrorMessage[];
CORE_EXPORT extern const char kInvalidStateErrorMessage[];
@@ -71,15 +71,15 @@ CORE_EXPORT extern const char kSyntaxErrorMessage[];
CORE_EXPORT extern const char kTypeMismatchErrorMessage[];
CORE_EXPORT void ThrowDOMException(ExceptionState&,
- ErrorCode,
+ FileErrorCode,
String message = String());
CORE_EXPORT void ThrowDOMException(ExceptionState& exception_state,
base::File::Error error,
String message = String());
-CORE_EXPORT DOMException* CreateDOMException(ErrorCode);
+CORE_EXPORT DOMException* CreateDOMException(FileErrorCode);
CORE_EXPORT DOMException* CreateDOMException(base::File::Error);
-} // namespace FileError
+} // namespace file_error
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_list.cc b/chromium/third_party/blink/renderer/core/fileapi/file_list.cc
index 720371ecba0..323cae340e2 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_list.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_list.cc
@@ -25,6 +25,8 @@
#include "third_party/blink/renderer/core/fileapi/file_list.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+
namespace blink {
FileList::FileList() = default;
@@ -35,14 +37,14 @@ File* FileList::item(unsigned index) const {
return files_[index].Get();
}
-Vector<String> FileList::PathsForUserVisibleFiles() const {
- Vector<String> paths;
+Vector<base::FilePath> FileList::PathsForUserVisibleFiles() const {
+ Vector<base::FilePath> paths;
for (unsigned i = 0; i < files_.size(); ++i) {
if (files_[i]->GetUserVisibility() == File::kIsUserVisible) {
if (files_[i]->HasBackingFile())
- paths.push_back(files_[i]->GetPath());
+ paths.push_back(StringToFilePath(files_[i]->GetPath()));
else
- paths.push_back(files_[i]->name());
+ paths.push_back(StringToFilePath(files_[i]->name()));
}
}
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_list.h b/chromium/third_party/blink/renderer/core/fileapi/file_list.h
index 3796379d6e7..0eeec3d62ce 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_list.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_list.h
@@ -38,7 +38,9 @@ class CORE_EXPORT FileList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static FileList* Create() { return new FileList; }
+ static FileList* Create() { return MakeGarbageCollected<FileList>(); }
+
+ FileList();
unsigned length() const { return files_.size(); }
File* item(unsigned index) const;
@@ -46,13 +48,11 @@ class CORE_EXPORT FileList final : public ScriptWrappable {
bool IsEmpty() const { return files_.IsEmpty(); }
void clear() { files_.clear(); }
void Append(File* file) { files_.push_back(file); }
- Vector<String> PathsForUserVisibleFiles() const;
+ Vector<base::FilePath> PathsForUserVisibleFiles() const;
void Trace(blink::Visitor*) override;
private:
- FileList();
-
HeapVector<Member<File>> files_;
};
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_list_test.cc b/chromium/third_party/blink/renderer/core/fileapi/file_list_test.cc
index 44ac7305177..00b6b4c98c5 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_list_test.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_list_test.cc
@@ -53,12 +53,12 @@ TEST(FileListTest, pathsForUserVisibleFiles) {
File::kIsNotUserVisible));
}
- Vector<String> paths = file_list->PathsForUserVisibleFiles();
+ Vector<base::FilePath> paths = file_list->PathsForUserVisibleFiles();
ASSERT_EQ(3u, paths.size());
- EXPECT_EQ("/native/path", paths[0]);
- EXPECT_EQ("/native/visible/snapshot", paths[1]);
- EXPECT_EQ("visible-non-native-file", paths[2])
+ EXPECT_EQ(FILE_PATH_LITERAL("/native/path"), paths[0].value());
+ EXPECT_EQ(FILE_PATH_LITERAL("/native/visible/snapshot"), paths[1].value());
+ EXPECT_EQ(FILE_PATH_LITERAL("visible-non-native-file"), paths[2].value())
<< "Files not backed by a native file should return name.";
}
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader.cc b/chromium/third_party/blink/renderer/core/fileapi/file_reader.cc
index 5e68a2739ab..7b595c43579 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader.cc
@@ -37,6 +37,7 @@
#include "third_party/blink/renderer/core/events/progress_event.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/file.h"
+#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
@@ -82,7 +83,7 @@ class FileReader::ThrottlingController final
ThrottlingController* controller =
Supplement<ExecutionContext>::From<ThrottlingController>(*context);
if (!controller) {
- controller = new ThrottlingController(*context);
+ controller = MakeGarbageCollected<ThrottlingController>(*context);
ProvideTo(*context, controller);
}
return controller;
@@ -119,6 +120,10 @@ class FileReader::ThrottlingController final
probe::AsyncTaskCanceled(context, reader);
}
+ explicit ThrottlingController(ExecutionContext& context)
+ : Supplement<ExecutionContext>(context),
+ max_running_readers_(kMaxOutstandingRequestsPerThread) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(pending_readers_);
visitor->Trace(running_readers_);
@@ -126,10 +131,6 @@ class FileReader::ThrottlingController final
}
private:
- explicit ThrottlingController(ExecutionContext& context)
- : Supplement<ExecutionContext>(context),
- max_running_readers_(kMaxOutstandingRequestsPerThread) {}
-
void PushReader(FileReader* reader) {
if (pending_readers_.IsEmpty() &&
running_readers_.size() < max_running_readers_) {
@@ -192,7 +193,7 @@ const char FileReader::ThrottlingController::kSupplementName[] =
"FileReaderThrottlingController";
FileReader* FileReader::Create(ExecutionContext* context) {
- return new FileReader(context);
+ return MakeGarbageCollected<FileReader>(context);
}
FileReader::FileReader(ExecutionContext* context)
@@ -208,7 +209,7 @@ FileReader::~FileReader() {
}
const AtomicString& FileReader::InterfaceName() const {
- return EventTargetNames::FileReader;
+ return event_target_names::kFileReader;
}
void FileReader::ContextDestroyed(ExecutionContext* destroyed_context) {
@@ -337,14 +338,14 @@ void FileReader::abort() {
base::AutoReset<bool> firing_events(&still_firing_events_, true);
// Setting error implicitly makes |result| return null.
- error_ = FileError::CreateDOMException(FileError::kAbortErr);
+ error_ = file_error::CreateDOMException(FileErrorCode::kAbortErr);
// Unregister the reader.
ThrottlingController::FinishReaderType final_step =
ThrottlingController::RemoveReader(GetExecutionContext(), this);
- FireEvent(EventTypeNames::abort);
- FireEvent(EventTypeNames::loadend);
+ FireEvent(event_type_names::kAbort);
+ FireEvent(event_type_names::kLoadend);
// All possible events have fired and we're done, no more pending activity.
ThrottlingController::FinishReader(GetExecutionContext(), this, final_step);
@@ -382,7 +383,7 @@ void FileReader::Terminate() {
void FileReader::DidStartLoading() {
base::AutoReset<bool> firing_events(&still_firing_events_, true);
- FireEvent(EventTypeNames::loadstart);
+ FireEvent(event_type_names::kLoadstart);
}
void FileReader::DidReceiveData() {
@@ -393,7 +394,7 @@ void FileReader::DidReceiveData() {
} else if (now - last_progress_notification_time_ms_ >
kProgressNotificationIntervalMS) {
base::AutoReset<bool> firing_events(&still_firing_events_, true);
- FireEvent(EventTypeNames::progress);
+ FireEvent(event_type_names::kProgress);
last_progress_notification_time_ms_ = now;
}
}
@@ -415,7 +416,7 @@ void FileReader::DidFinishLoading() {
// if we're still loading (therefore we need abort process) or not.
loading_state_ = kLoadingStateNone;
- FireEvent(EventTypeNames::progress);
+ FireEvent(event_type_names::kProgress);
DCHECK_NE(kDone, state_);
state_ = kDone;
@@ -424,14 +425,14 @@ void FileReader::DidFinishLoading() {
ThrottlingController::FinishReaderType final_step =
ThrottlingController::RemoveReader(GetExecutionContext(), this);
- FireEvent(EventTypeNames::load);
- FireEvent(EventTypeNames::loadend);
+ FireEvent(event_type_names::kLoad);
+ FireEvent(event_type_names::kLoadend);
// All possible events have fired and we're done, no more pending activity.
ThrottlingController::FinishReader(GetExecutionContext(), this, final_step);
}
-void FileReader::DidFail(FileError::ErrorCode error_code) {
+void FileReader::DidFail(FileErrorCode error_code) {
if (loading_state_ == kLoadingStateAborted)
return;
@@ -443,14 +444,14 @@ void FileReader::DidFail(FileError::ErrorCode error_code) {
DCHECK_NE(kDone, state_);
state_ = kDone;
- error_ = FileError::CreateDOMException(error_code);
+ error_ = file_error::CreateDOMException(error_code);
// Unregister the reader.
ThrottlingController::FinishReaderType final_step =
ThrottlingController::RemoveReader(GetExecutionContext(), this);
- FireEvent(EventTypeNames::error);
- FireEvent(EventTypeNames::loadend);
+ FireEvent(event_type_names::kError);
+ FireEvent(event_type_names::kLoadend);
// All possible events have fired and we're done, no more pending activity.
ThrottlingController::FinishReader(GetExecutionContext(), this, final_step);
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader.h b/chromium/third_party/blink/renderer/core/fileapi/file_reader.h
index 94649ffc368..7c5cfd40127 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader.h
@@ -36,7 +36,6 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
-#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader_client.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -47,6 +46,7 @@ namespace blink {
class Blob;
class ExceptionState;
class ExecutionContext;
+enum class FileErrorCode;
class StringOrArrayBuffer;
class CORE_EXPORT FileReader final : public EventTargetWithInlineData,
@@ -59,6 +59,7 @@ class CORE_EXPORT FileReader final : public EventTargetWithInlineData,
public:
static FileReader* Create(ExecutionContext*);
+ explicit FileReader(ExecutionContext*);
~FileReader() override;
enum ReadyState { kEmpty = 0, kLoading = 1, kDone = 2 };
@@ -90,22 +91,20 @@ class CORE_EXPORT FileReader final : public EventTargetWithInlineData,
void DidStartLoading() override;
void DidReceiveData() override;
void DidFinishLoading() override;
- void DidFail(FileError::ErrorCode) override;
+ void DidFail(FileErrorCode) override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart, kLoadstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(progress, kProgress);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(load, kLoad);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend, kLoadend);
void Trace(blink::Visitor*) override;
private:
class ThrottlingController;
- explicit FileReader(ExecutionContext*);
-
void Terminate();
void ReadInternal(Blob*, FileReaderLoader::ReadType, ExceptionState&);
void FireEvent(const AtomicString& type);
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.cc b/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.cc
index 173a43dfbd0..5a1cc40c235 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.cc
@@ -100,7 +100,7 @@ void FileReaderLoader::Start(scoped_refptr<BlobDataHandle> blob_data) {
mojo::ScopedDataPipeProducerHandle producer_handle;
MojoResult rv = CreateDataPipe(&options, &producer_handle, &consumer_handle_);
if (rv != MOJO_RESULT_OK) {
- Failed(FileError::kNotReadableErr, FailureType::kMojoPipeCreation);
+ Failed(FileErrorCode::kNotReadableErr, FailureType::kMojoPipeCreation);
return;
}
@@ -115,21 +115,22 @@ void FileReaderLoader::Start(scoped_refptr<BlobDataHandle> blob_data) {
if (received_on_complete_)
return;
if (!received_all_data_) {
- Failed(FileError::kNotReadableErr, FailureType::kSyncDataNotAllLoaded);
+ Failed(FileErrorCode::kNotReadableErr,
+ FailureType::kSyncDataNotAllLoaded);
return;
}
// Wait for OnComplete
binding_.WaitForIncomingMethodCall();
if (!received_on_complete_) {
- Failed(FileError::kNotReadableErr,
+ Failed(FileErrorCode::kNotReadableErr,
FailureType::kSyncOnCompleteNotReceived);
}
}
}
void FileReaderLoader::Cancel() {
- error_code_ = FileError::kAbortErr;
+ error_code_ = FileErrorCode::kAbortErr;
Cleanup();
}
@@ -139,7 +140,7 @@ DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() {
return array_buffer_result_;
// If the loading is not started or an error occurs, return an empty result.
- if (!raw_data_ || error_code_)
+ if (!raw_data_ || error_code_ != FileErrorCode::kOK)
return nullptr;
DOMArrayBuffer* result = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer());
@@ -156,8 +157,10 @@ String FileReaderLoader::StringResult() {
DCHECK_NE(read_type_, kReadAsArrayBuffer);
DCHECK_NE(read_type_, kReadByClient);
- if (!raw_data_ || error_code_ || is_raw_data_converted_)
+ if (!raw_data_ || (error_code_ != FileErrorCode::kOK) ||
+ is_raw_data_converted_) {
return string_result_;
+ }
switch (read_type_) {
case kReadAsArrayBuffer:
@@ -197,7 +200,7 @@ void FileReaderLoader::Cleanup() {
consumer_handle_.reset();
// If we get any error, we do not need to keep a buffer around.
- if (error_code_) {
+ if (error_code_ != FileErrorCode::kOK) {
raw_data_.reset();
string_result_ = "";
is_raw_data_converted_ = true;
@@ -207,13 +210,12 @@ void FileReaderLoader::Cleanup() {
}
}
-void FileReaderLoader::Failed(FileError::ErrorCode error_code,
- FailureType type) {
+void FileReaderLoader::Failed(FileErrorCode error_code, FailureType type) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram, failure_histogram,
("Storage.Blob.FileReaderLoader.FailureType",
static_cast<int>(FailureType::kCount)));
// If an error was already reported, don't report this error again.
- if (error_code_ != FileError::kOK)
+ if (error_code_ != FileErrorCode::kOK)
return;
error_code_ = error_code;
failure_histogram.Count(static_cast<int>(type));
@@ -232,13 +234,13 @@ void FileReaderLoader::OnStartLoading(uint64_t total_bytes) {
// so to call ArrayBuffer's create function.
// FIXME: Support reading more than the current size limit of ArrayBuffer.
if (total_bytes > std::numeric_limits<unsigned>::max()) {
- Failed(FileError::kNotReadableErr, FailureType::kTotalBytesTooLarge);
+ Failed(FileErrorCode::kNotReadableErr, FailureType::kTotalBytesTooLarge);
return;
}
raw_data_ = std::make_unique<ArrayBufferBuilder>(total_bytes);
if (!raw_data_->IsValid()) {
- Failed(FileError::kNotReadableErr,
+ Failed(FileErrorCode::kNotReadableErr,
FailureType::kArrayBufferBuilderCreation);
return;
}
@@ -253,7 +255,7 @@ void FileReaderLoader::OnReceivedData(const char* data, unsigned data_length) {
DCHECK(data);
// Bail out if we already encountered an error.
- if (error_code_)
+ if (error_code_ != FileErrorCode::kOK)
return;
if (read_type_ == kReadByClient) {
@@ -268,7 +270,8 @@ void FileReaderLoader::OnReceivedData(const char* data, unsigned data_length) {
if (!bytes_appended) {
raw_data_.reset();
bytes_loaded_ = 0;
- Failed(FileError::kNotReadableErr, FailureType::kArrayBufferBuilderAppend);
+ Failed(FileErrorCode::kNotReadableErr,
+ FailureType::kArrayBufferBuilderAppend);
return;
}
bytes_loaded_ += bytes_appended;
@@ -323,13 +326,13 @@ void FileReaderLoader::OnComplete(int32_t status, uint64_t data_length) {
if (status != net::OK) {
net_error_ = status;
file_reader_loader_read_errors_histogram.Sample(std::max(0, -net_error_));
- Failed(status == net::ERR_FILE_NOT_FOUND ? FileError::kNotFoundErr
- : FileError::kNotReadableErr,
+ Failed(status == net::ERR_FILE_NOT_FOUND ? FileErrorCode::kNotFoundErr
+ : FileErrorCode::kNotReadableErr,
FailureType::kBackendReadError);
return;
}
if (data_length != total_bytes_) {
- Failed(FileError::kNotReadableErr, FailureType::kReadSizesIncorrect);
+ Failed(FileErrorCode::kNotReadableErr, FailureType::kReadSizesIncorrect);
return;
}
@@ -341,7 +344,7 @@ void FileReaderLoader::OnComplete(int32_t status, uint64_t data_length) {
void FileReaderLoader::OnDataPipeReadable(MojoResult result) {
if (result != MOJO_RESULT_OK) {
if (!received_all_data_) {
- Failed(FileError::kNotReadableErr,
+ Failed(FileErrorCode::kNotReadableErr,
FailureType::kDataPipeNotReadableWithBytesLeft);
}
return;
@@ -363,12 +366,13 @@ void FileReaderLoader::OnDataPipeReadable(MojoResult result) {
if (result == MOJO_RESULT_FAILED_PRECONDITION) {
// Pipe closed.
if (!received_all_data_) {
- Failed(FileError::kNotReadableErr, FailureType::kMojoPipeClosedEarly);
+ Failed(FileErrorCode::kNotReadableErr,
+ FailureType::kMojoPipeClosedEarly);
}
return;
}
if (result != MOJO_RESULT_OK) {
- Failed(FileError::kNotReadableErr,
+ Failed(FileErrorCode::kNotReadableErr,
FailureType::kMojoPipeUnexpectedReadError);
return;
}
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.h b/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.h
index 6eeccfd2d55..9f238c8732d 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.h
@@ -97,7 +97,7 @@ class CORE_EXPORT FileReaderLoader : public mojom::blink::BlobReaderClient {
// After OnCalculatedSize() is called: Returns the size of the resource.
base::Optional<uint64_t> TotalBytes() const { return total_bytes_; }
- FileError::ErrorCode GetErrorCode() const { return error_code_; }
+ FileErrorCode GetErrorCode() const { return error_code_; }
int32_t GetNetError() const { return net_error_; }
@@ -128,7 +128,7 @@ class CORE_EXPORT FileReaderLoader : public mojom::blink::BlobReaderClient {
};
void Cleanup();
- void Failed(FileError::ErrorCode, FailureType type);
+ void Failed(FileErrorCode, FailureType type);
void OnStartLoading(uint64_t total_bytes);
void OnReceivedData(const char* data, unsigned data_length);
@@ -172,7 +172,7 @@ class CORE_EXPORT FileReaderLoader : public mojom::blink::BlobReaderClient {
int64_t memory_usage_reported_to_v8_ = 0;
int32_t net_error_ = 0; // net::OK
- FileError::ErrorCode error_code_ = FileError::kOK;
+ FileErrorCode error_code_ = FileErrorCode::kOK;
mojo::ScopedDataPipeConsumerHandle consumer_handle_;
mojo::SimpleWatcher handle_watcher_;
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader_client.h b/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader_client.h
index d52508fbbd3..747a254d098 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader_client.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader_loader_client.h
@@ -32,11 +32,12 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FILEAPI_FILE_READER_LOADER_CLIENT_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
+enum class FileErrorCode;
+
class CORE_EXPORT FileReaderLoaderClient {
public:
virtual ~FileReaderLoaderClient() = default;
@@ -51,7 +52,7 @@ class CORE_EXPORT FileReaderLoaderClient {
NOTREACHED();
}
virtual void DidFinishLoading() = 0;
- virtual void DidFail(FileError::ErrorCode) = 0;
+ virtual void DidFail(FileErrorCode) = 0;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.cc b/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.cc
index ebd429f6a8e..4357025cfce 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.cc
@@ -116,8 +116,8 @@ void FileReaderSync::StartLoading(FileReaderLoader& loader,
const Blob& blob,
ExceptionState& exception_state) {
loader.Start(blob.GetBlobDataHandle());
- if (loader.GetErrorCode())
- FileError::ThrowDOMException(exception_state, loader.GetErrorCode());
+ if (loader.GetErrorCode() != FileErrorCode::kOK)
+ file_error::ThrowDOMException(exception_state, loader.GetErrorCode());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.h b/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.h
index d5db3fca225..2c93cb71614 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.h
@@ -48,9 +48,11 @@ class FileReaderSync final : public ScriptWrappable {
public:
static FileReaderSync* Create(ExecutionContext* context) {
- return new FileReaderSync(context);
+ return MakeGarbageCollected<FileReaderSync>(context);
}
+ explicit FileReaderSync(ExecutionContext*);
+
DOMArrayBuffer* readAsArrayBuffer(Blob*, ExceptionState&);
String readAsBinaryString(Blob*, ExceptionState&);
String readAsText(Blob* blob, ExceptionState& ec) {
@@ -60,8 +62,6 @@ class FileReaderSync final : public ScriptWrappable {
String readAsDataURL(Blob*, ExceptionState&);
private:
- explicit FileReaderSync(ExecutionContext*);
-
void StartLoading(FileReaderLoader&, const Blob&, ExceptionState&);
};
diff --git a/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.cc b/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.cc
index 8c54d944a3d..e3de27cfe89 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.cc
@@ -100,7 +100,7 @@ SecurityOrigin* BlobOriginMap::GetOrigin(const KURL& url) {
} // namespace
PublicURLManager* PublicURLManager::Create(ExecutionContext* context) {
- return new PublicURLManager(context);
+ return MakeGarbageCollected<PublicURLManager>(context);
}
PublicURLManager::PublicURLManager(ExecutionContext* context)
diff --git a/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.h b/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.h
index 26c71d7c913..7c808b2dd83 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/public_url_manager.h
@@ -50,6 +50,8 @@ class CORE_EXPORT PublicURLManager final
public:
static PublicURLManager* Create(ExecutionContext*);
+ explicit PublicURLManager(ExecutionContext*);
+
// Generates a new Blob URL and registers the URLRegistrable to the
// corresponding URLRegistry with the Blob URL. Returns the serialization
// of the Blob URL.
@@ -76,8 +78,6 @@ class CORE_EXPORT PublicURLManager final
}
private:
- explicit PublicURLManager(ExecutionContext*);
-
typedef String URLString;
// Map from URLs to the URLRegistry they are registered with.
typedef HashMap<URLString, URLRegistry*> URLToRegistryMap;
diff --git a/chromium/third_party/blink/renderer/core/fileapi/public_url_manager_test.cc b/chromium/third_party/blink/renderer/core/fileapi/public_url_manager_test.cc
index 77ab63eba0e..0eb443d6357 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/public_url_manager_test.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/public_url_manager_test.cc
@@ -72,7 +72,7 @@ class PublicURLManagerTest : public testing::Test {
void SetUp() override {
scoped_feature_list_.InitAndEnableFeature(features::kMojoBlobURLs);
- execution_context_ = new NullExecutionContext;
+ execution_context_ = MakeGarbageCollected<NullExecutionContext>();
// By default this creates a unique origin, which is exactly what this test
// wants.
execution_context_->SetUpSecurityContext();
diff --git a/chromium/third_party/blink/renderer/core/frame/BUILD.gn b/chromium/third_party/blink/renderer/core/frame/BUILD.gn
index 3bd047669ec..a89c8f6b5f2 100644
--- a/chromium/third_party/blink/renderer/core/frame/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/frame/BUILD.gn
@@ -12,8 +12,6 @@ blink_core_sources("frame") {
"bar_prop.h",
"browser_controls.cc",
"browser_controls.h",
- "content_settings_client.cc",
- "content_settings_client.h",
"csp/content_security_policy.cc",
"csp/content_security_policy.h",
"csp/csp_directive.h",
@@ -44,11 +42,6 @@ blink_core_sources("frame") {
"dom_visual_viewport.h",
"dom_window.cc",
"dom_window.h",
- "dom_window_base64.cc",
- "dom_window_base64.h",
- "dom_window_event_handlers.h",
- "dom_window_timers.cc",
- "dom_window_timers.h",
"embedded_content_view.h",
"event_handler_registry.cc",
"event_handler_registry.h",
@@ -95,6 +88,8 @@ blink_core_sources("frame") {
"location.cc",
"location.h",
"message_report_body.h",
+ "navigation_rate_limiter.cc",
+ "navigation_rate_limiter.h",
"navigator.cc",
"navigator.h",
"navigator_concurrent_hardware.cc",
@@ -184,5 +179,8 @@ blink_core_sources("frame") {
"web_local_frame_impl.h",
"web_view_frame_widget.cc",
"web_view_frame_widget.h",
+ "window_event_handlers.h",
+ "window_or_worker_global_scope.cc",
+ "window_or_worker_global_scope.h",
]
}
diff --git a/chromium/third_party/blink/renderer/core/frame/ad_tracker.cc b/chromium/third_party/blink/renderer/core/frame/ad_tracker.cc
index 89f672f12b4..41c3968f2fe 100644
--- a/chromium/third_party/blink/renderer/core/frame/ad_tracker.cc
+++ b/chromium/third_party/blink/renderer/core/frame/ad_tracker.cc
@@ -66,12 +66,17 @@ void AdTracker::WillExecuteScript(ExecutionContext* execution_context,
bool is_ad = script_url.IsEmpty()
? false
: IsKnownAdScript(execution_context, script_url);
- ExecutingScript script(script_url, is_ad);
- executing_scripts_.push_back(script);
+ stack_frame_is_ad_.push_back(is_ad);
+ if (is_ad)
+ num_ads_in_stack_ += 1;
}
void AdTracker::DidExecuteScript() {
- executing_scripts_.pop_back();
+ if (stack_frame_is_ad_.back()) {
+ DCHECK_LT(0u, num_ads_in_stack_);
+ num_ads_in_stack_ -= 1;
+ }
+ stack_frame_is_ad_.pop_back();
}
void AdTracker::Will(const probe::ExecuteScript& probe) {
@@ -110,18 +115,27 @@ void AdTracker::WillSendRequest(ExecutionContext* execution_context,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo& initiator_info,
ResourceType resource_type) {
- // If the resource is not already marked as an ad, check if any executing
- // script is an ad. If yes, mark this as an ad.
- if (!request.IsAdResource() && IsAdScriptInStack())
+ // If the resource is not already marked as an ad, check if the document
+ // loading the resource is an ad or if any executing script is an ad.
+ if (!request.IsAdResource() &&
+ (IsKnownAdExecutionContext(execution_context) || IsAdScriptInStack())) {
request.SetIsAdResource();
+ }
- // If it is a script marked as an ad, append it to the known ad scripts set.
- if (resource_type == ResourceType::kScript && request.IsAdResource()) {
+ // If it is a script marked as an ad and it's not in an ad context, append it
+ // to the known ad script set. We don't need to keep track of ad scripts in ad
+ // contexts, because any script executed inside an ad context is considered an
+ // ad script by IsKnownAdScript.
+ if (resource_type == ResourceType::kScript && request.IsAdResource() &&
+ !IsKnownAdExecutionContext(execution_context)) {
AppendToKnownAdScripts(*execution_context, request.Url().GetString());
}
}
bool AdTracker::IsAdScriptInStack() {
+ if (num_ads_in_stack_ > 0)
+ return true;
+
ExecutionContext* execution_context = GetCurrentExecutionContext();
if (!execution_context)
return false;
@@ -139,11 +153,6 @@ bool AdTracker::IsAdScriptInStack() {
if (!top_script.IsEmpty() && IsKnownAdScript(execution_context, top_script))
return true;
- // Scan the pseudo-stack for ad scripts.
- for (const auto& executing_script : executing_scripts_) {
- if (executing_script.is_ad)
- return true;
- }
return false;
}
@@ -152,9 +161,6 @@ bool AdTracker::IsKnownAdScript(ExecutionContext* execution_context,
if (!execution_context)
return false;
- // TODO(jkarlin): Minor memory optimization, stop tracking known ad scripts in
- // ad contexts. This will reduce the size of executing_scripts_. Note that
- // this is a minor win, as the strings are already ref-counted.
if (IsKnownAdExecutionContext(execution_context))
return true;
diff --git a/chromium/third_party/blink/renderer/core/frame/ad_tracker.h b/chromium/third_party/blink/renderer/core/frame/ad_tracker.h
index 287ac1449f6..544605c95f7 100644
--- a/chromium/third_party/blink/renderer/core/frame/ad_tracker.h
+++ b/chromium/third_party/blink/renderer/core/frame/ad_tracker.h
@@ -81,18 +81,13 @@ class CORE_EXPORT AdTracker : public GarbageCollectedFinalized<AdTracker> {
Member<LocalFrame> local_root_;
- // Since the script URLs should be external strings in v8 (allocated in Blink)
- // getting it as String should end up with the same StringImpl. Thus storing a
- // vector of Strings here should not be expensive.
- // TODO(jkarlin): We don't need this struct. A Vector<bool> would suffice.
- struct ExecutingScript {
- String url;
- bool is_ad;
- ExecutingScript(String script_url, bool is_ad_script)
- : url(script_url), is_ad(is_ad_script) {}
- };
-
- Vector<ExecutingScript> executing_scripts_;
+ // Each time v8 is started to run a script or function, this records if it was
+ // an ad script. Each time the script or function finishes, it pops the stack.
+ Vector<bool> stack_frame_is_ad_;
+
+ uint32_t num_ads_in_stack_ = 0;
+
+ // The set of ad scripts detected outside of ad-frame contexts.
HeapHashMap<WeakMember<ExecutionContext>, HashSet<String>> known_ad_scripts_;
DISALLOW_COPY_AND_ASSIGN(AdTracker);
diff --git a/chromium/third_party/blink/renderer/core/frame/ad_tracker_test.cc b/chromium/third_party/blink/renderer/core/frame/ad_tracker_test.cc
index c253444f4df..128a79f7c50 100644
--- a/chromium/third_party/blink/renderer/core/frame/ad_tracker_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/ad_tracker_test.cc
@@ -94,6 +94,8 @@ class AdTrackerTest : public testing::Test {
String(script_url));
}
+ void DidExecuteScript() { ad_tracker_->DidExecuteScript(); }
+
bool AnyExecutingScriptsTaggedAsAdResource() {
return ad_tracker_->IsAdScriptInStack();
}
@@ -161,6 +163,39 @@ TEST_F(AdTrackerTest, TopOfStackIncluded) {
EXPECT_TRUE(AnyExecutingScriptsTaggedAsAdResource());
}
+TEST_F(AdTrackerTest, AdStackFrameCounting) {
+ AppendToKnownAdScripts("https://example.com/ad.js");
+
+ WillExecuteScript("https://example.com/vanilla.js");
+ WillExecuteScript("https://example.com/vanilla.js");
+ EXPECT_FALSE(AnyExecutingScriptsTaggedAsAdResource());
+
+ WillExecuteScript("https://example.com/ad.js");
+ EXPECT_TRUE(AnyExecutingScriptsTaggedAsAdResource());
+
+ DidExecuteScript();
+ EXPECT_FALSE(AnyExecutingScriptsTaggedAsAdResource());
+
+ WillExecuteScript("https://example.com/ad.js");
+ WillExecuteScript("https://example.com/ad.js");
+ WillExecuteScript("https://example.com/vanilla.js");
+ EXPECT_TRUE(AnyExecutingScriptsTaggedAsAdResource());
+
+ DidExecuteScript();
+ DidExecuteScript();
+ EXPECT_TRUE(AnyExecutingScriptsTaggedAsAdResource());
+
+ DidExecuteScript();
+ EXPECT_FALSE(AnyExecutingScriptsTaggedAsAdResource());
+
+ DidExecuteScript();
+ DidExecuteScript();
+ EXPECT_FALSE(AnyExecutingScriptsTaggedAsAdResource());
+
+ WillExecuteScript("https://example.com/ad.js");
+ EXPECT_TRUE(AnyExecutingScriptsTaggedAsAdResource());
+}
+
class AdTrackerSimTest : public SimTest {
protected:
void SetUp() override {
@@ -237,6 +272,37 @@ TEST_F(AdTrackerSimTest, ScriptDetectedByContext) {
EXPECT_TRUE(ad_tracker_->IsAdScriptInStack());
}
+TEST_F(AdTrackerSimTest, AdResourceDetectedByContext) {
+ SimRequest ad_script("https://example.com/ad_script.js", "text/javascript");
+ SimRequest ad_frame("https://example.com/ad_frame.html", "text/html");
+ SimRequest foo_css("https://example.com/foo.css", "text/style");
+ ad_tracker_->SetAdSuffix("ad_script.js");
+
+ // Create an iframe that's considered an ad.
+ main_resource_->Complete("<body><script src='ad_script.js'></script></body>");
+ ad_script.Complete(R"SCRIPT(
+ frame = document.createElement("iframe");
+ frame.src="ad_frame.html";
+ document.body.appendChild(frame);
+ )SCRIPT");
+
+ // The child frame should be an ad subframe.
+ LocalFrame* child_frame =
+ ToLocalFrame(GetDocument().GetFrame()->Tree().FirstChild());
+ EXPECT_TRUE(child_frame->IsAdSubframe());
+
+ // Load a resource from the frame. It should be detected as an ad resource due
+ // to its context.
+ ad_frame.Complete(R"HTML(
+ <link rel="stylesheet" href="foo.css">
+ )HTML");
+
+ foo_css.Complete("");
+
+ EXPECT_TRUE(
+ ad_tracker_->RequestWithUrlTaggedAsAd("https://example.com/foo.css"));
+}
+
// When inline script in an ad frame inserts an iframe into a non-ad frame, the
// new frame should be considered an ad.
TEST_F(AdTrackerSimTest, InlineAdScriptRunningInNonAdContext) {
@@ -416,20 +482,12 @@ class AdTrackerDisabledSimTest : public SimTest {
main_resource_->Start();
}
- void TearDown() override { SimTest::TearDown(); }
-
std::unique_ptr<SimRequest> main_resource_;
};
-TEST_F(AdTrackerDisabledSimTest, ResourceLoadedWhenAdTaggingDisabled) {
- SimRequest iframe_resource("https://example.com/iframe.html", "text/html");
-
- main_resource_->Complete(R"HTML(
- <iframe src=https://example.com/iframe.html></iframe>
- )HTML");
-
- iframe_resource.Complete("<body></body>");
-
+TEST_F(AdTrackerDisabledSimTest, VerifyAdTrackingDisabled) {
+ main_resource_->Complete("<body></body>");
+ EXPECT_FALSE(GetDocument().GetFrame()->GetAdTracker());
EXPECT_FALSE(GetDocument().GetFrame()->IsAdSubframe());
}
diff --git a/chromium/third_party/blink/renderer/core/frame/browser_controls.cc b/chromium/third_party/blink/renderer/core/frame/browser_controls.cc
index 1a780d968ab..24d1b75fa8e 100644
--- a/chromium/third_party/blink/renderer/core/frame/browser_controls.cc
+++ b/chromium/third_party/blink/renderer/core/frame/browser_controls.cc
@@ -113,22 +113,6 @@ void BrowserControls::UpdateConstraintsAndState(
current == cc::BrowserControlsState::kHidden));
DCHECK(!(constraints == cc::BrowserControlsState::kHidden &&
current == cc::BrowserControlsState::kShown));
-
- // If the change should be animated, let the impl thread drive the change.
- // Otherwise, immediately set the shown ratio so we don't have to wait for
- // a commit from the impl thread.
- if (animate)
- return;
-
- if (constraints == cc::BrowserControlsState::kBoth &&
- current == cc::BrowserControlsState::kBoth)
- return;
-
- if (constraints == cc::BrowserControlsState::kHidden ||
- current == cc::BrowserControlsState::kHidden)
- SetShownRatio(0.f);
- else
- SetShownRatio(1.f);
}
void BrowserControls::SetHeight(float top_height,
diff --git a/chromium/third_party/blink/renderer/core/frame/browser_controls_test.cc b/chromium/third_party/blink/renderer/core/frame/browser_controls_test.cc
index 272f36c8a23..87ff69a57ba 100644
--- a/chromium/third_party/blink/renderer/core/frame/browser_controls_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/browser_controls_test.cc
@@ -48,6 +48,8 @@
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
@@ -97,7 +99,7 @@ class BrowserControlsTest : public testing::Test {
}
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -139,12 +141,64 @@ class BrowserControlsTest : public testing::Test {
return helper_.GetWebView()->GetPage()->GetVisualViewport();
}
+ void UpdateAllLifecyclePhases() {
+ GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
private:
std::string base_url_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
};
+class BrowserControlsSimTest : public SimTest {
+ public:
+ BrowserControlsSimTest() {}
+
+ void SetUp() override {
+ SimTest::SetUp();
+
+ // Use settings that resemble the Android configuration.
+ WebView().GetSettings()->SetViewportEnabled(true);
+ WebView().GetSettings()->SetPreferCompositingToLCDTextEnabled(true);
+ WebView().GetSettings()->SetViewportMetaEnabled(true);
+ WebView().GetSettings()->SetViewportEnabled(true);
+ WebView().GetSettings()->SetMainFrameResizesAreOrientationChanges(true);
+ WebView().GetSettings()->SetShrinksViewportContentToFit(true);
+ WebView().SetDefaultPageScaleLimits(0.25f, 5);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown,
+ false);
+ WebView().ResizeWithBrowserControls(WebSize(412, 604), 56.f, 0, true);
+ }
+
+ WebCoalescedInputEvent GenerateEvent(WebInputEvent::Type type,
+ int delta_x = 0,
+ int delta_y = 0) {
+ WebGestureEvent event(type, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests(),
+ kWebGestureDeviceTouchscreen);
+ event.SetPositionInWidget(FloatPoint(100, 100));
+ if (type == WebInputEvent::kGestureScrollUpdate) {
+ event.data.scroll_update.delta_x = delta_x;
+ event.data.scroll_update.delta_y = delta_y;
+ } else if (type == WebInputEvent::kGestureScrollBegin) {
+ event.data.scroll_begin.delta_x_hint = delta_x;
+ event.data.scroll_begin.delta_y_hint = delta_y;
+ }
+ return WebCoalescedInputEvent(event);
+ }
+
+ void VerticalScroll(float delta_y) {
+ WebView().HandleInputEvent(
+ GenerateEvent(WebInputEvent::kGestureScrollBegin, 0, delta_y));
+ WebView().HandleInputEvent(
+ GenerateEvent(WebInputEvent::kGestureScrollUpdate, 0, delta_y));
+ WebView().HandleInputEvent(GenerateEvent(WebInputEvent::kGestureScrollEnd));
+ }
+};
+
// Disable these tests on Mac OSX until further investigation.
// Local build on Mac is OK but the bot fails. This is not an issue as
// Browser Controls are currently only used on Android.
@@ -633,78 +687,90 @@ TEST_F(BrowserControlsTest, MAYBE(ScrollUpPastLimitDoesNotHide)) {
}
// Browser controls should honor its constraints
-TEST_F(BrowserControlsTest, MAYBE(StateConstraints)) {
- WebViewImpl* web_view = Initialize();
- web_view->ResizeWithBrowserControls(web_view->Size(), 50.f, 0, false);
- GetFrame()->View()->GetScrollableArea()->SetScrollOffset(ScrollOffset(0, 100),
- kProgrammaticScroll);
-
+TEST_F(BrowserControlsSimTest, MAYBE(StateConstraints)) {
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <meta name="viewport" content="width=device-width">
+ <style>
+ body {
+ margin: 0;
+ height: 1000px;
+ }
+ </style>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().ResizeWithBrowserControls(WebSize(400, 400), 50.f, 0, false);
+ Compositor().BeginFrame();
+
+ GetDocument().View()->GetScrollableArea()->SetScrollOffset(
+ ScrollOffset(0, 100), kProgrammaticScroll);
// Setting permitted state should change the content offset to match the
// constraint.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kShown,
- cc::BrowserControlsState::kShown, false);
- EXPECT_FLOAT_EQ(50.f, web_view->GetBrowserControls().ContentOffset());
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kShown, cc::BrowserControlsState::kShown,
+ false);
+ Compositor().BeginFrame();
+ EXPECT_FLOAT_EQ(50.f, WebView().GetBrowserControls().ContentOffset());
- // Only shown state is permitted so controls cannot hide
+ // Only shown state is permitted so controls cannot hide.
VerticalScroll(-20.f);
- EXPECT_FLOAT_EQ(50, web_view->GetBrowserControls().ContentOffset());
+ EXPECT_FLOAT_EQ(50, WebView().GetBrowserControls().ContentOffset());
EXPECT_EQ(ScrollOffset(0, 120),
- GetFrame()->View()->LayoutViewport()->GetScrollOffset());
+ GetDocument().View()->LayoutViewport()->GetScrollOffset());
// Setting permitted state should change content offset to match the
// constraint.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kHidden,
- false);
- EXPECT_FLOAT_EQ(0, web_view->GetBrowserControls().ContentOffset());
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kHidden,
+ false);
+ Compositor().BeginFrame();
+ EXPECT_FLOAT_EQ(0, WebView().GetBrowserControls().ContentOffset());
// Only hidden state is permitted so controls cannot show
VerticalScroll(30.f);
- EXPECT_FLOAT_EQ(0, web_view->GetBrowserControls().ContentOffset());
+ EXPECT_FLOAT_EQ(0, WebView().GetBrowserControls().ContentOffset());
EXPECT_EQ(ScrollOffset(0, 90),
- GetFrame()->View()->LayoutViewport()->GetScrollOffset());
+ GetDocument().View()->LayoutViewport()->GetScrollOffset());
// Setting permitted state to "both" should not change content offset.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kBoth, false);
- EXPECT_FLOAT_EQ(0, web_view->GetBrowserControls().ContentOffset());
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kBoth, false);
+ Compositor().BeginFrame();
+ EXPECT_FLOAT_EQ(0, WebView().GetBrowserControls().ContentOffset());
// Both states are permitted so controls can either show or hide
VerticalScroll(50.f);
- EXPECT_FLOAT_EQ(50, web_view->GetBrowserControls().ContentOffset());
+ EXPECT_FLOAT_EQ(50, WebView().GetBrowserControls().ContentOffset());
EXPECT_EQ(ScrollOffset(0, 90),
- GetFrame()->View()->LayoutViewport()->GetScrollOffset());
+ GetDocument().View()->LayoutViewport()->GetScrollOffset());
VerticalScroll(-50.f);
- EXPECT_FLOAT_EQ(0, web_view->GetBrowserControls().ContentOffset());
+ EXPECT_FLOAT_EQ(0, WebView().GetBrowserControls().ContentOffset());
EXPECT_EQ(ScrollOffset(0, 90),
- GetFrame()->View()->LayoutViewport()->GetScrollOffset());
+ GetDocument().View()->LayoutViewport()->GetScrollOffset());
// Setting permitted state to "both" should not change an in-flight offset.
VerticalScroll(20.f);
- EXPECT_FLOAT_EQ(20, web_view->GetBrowserControls().ContentOffset());
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kBoth, false);
- EXPECT_FLOAT_EQ(20, web_view->GetBrowserControls().ContentOffset());
-
- // An animated state change shouldn't cause a change to the content offset
- // since it'll be driven from the compositor.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kHidden, true);
- EXPECT_FLOAT_EQ(20, web_view->GetBrowserControls().ContentOffset());
-
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kShown,
- cc::BrowserControlsState::kShown, true);
- EXPECT_FLOAT_EQ(20, web_view->GetBrowserControls().ContentOffset());
+ EXPECT_FLOAT_EQ(20, WebView().GetBrowserControls().ContentOffset());
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kBoth, false);
+ Compositor().BeginFrame();
+ EXPECT_FLOAT_EQ(20, WebView().GetBrowserControls().ContentOffset());
// Setting just the constraint should affect the content offset.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kBoth, false);
- EXPECT_FLOAT_EQ(0, web_view->GetBrowserControls().ContentOffset());
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ false);
+ Compositor().BeginFrame();
+ EXPECT_FLOAT_EQ(0, WebView().GetBrowserControls().ContentOffset());
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kShown,
- cc::BrowserControlsState::kBoth, false);
- EXPECT_FLOAT_EQ(50, web_view->GetBrowserControls().ContentOffset());
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kShown, cc::BrowserControlsState::kBoth, false);
+ Compositor().BeginFrame();
+ EXPECT_FLOAT_EQ(50, WebView().GetBrowserControls().ContentOffset());
}
// Ensure that browser controls do not affect the layout by showing and hiding
@@ -713,10 +779,10 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectLayoutHeight)) {
// Initialize with the browser controls showing.
WebViewImpl* web_view = Initialize("percent-height.html");
web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
+ web_view->GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
@@ -736,7 +802,7 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectLayoutHeight)) {
// Hide the browser controls.
VerticalScroll(-100.f);
web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(0.f, web_view->GetBrowserControls().ContentOffset());
@@ -752,83 +818,119 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectLayoutHeight)) {
// Ensure that browser controls do not affect the layout by showing and hiding
// except for position: fixed elements.
-TEST_F(BrowserControlsTest, MAYBE(AffectLayoutHeightWhenConstrained)) {
- // Initialize with the browser controls showing.
- WebViewImpl* web_view = Initialize("percent-height.html");
- web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
- web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
-
- Element* abs_pos = GetElementById(WebString::FromUTF8("abs"));
- Element* fixed_pos = GetElementById(WebString::FromUTF8("fixed"));
-
- ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
+TEST_F(BrowserControlsSimTest, MAYBE(AffectLayoutHeightWhenConstrained)) {
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ #abs {
+ position: absolute;
+ left: 0px;
+ top: 0px;
+ width: 100px;
+ height: 50%;
+ }
+
+ #fixed {
+ position: fixed;
+ right: 0px;
+ top: 0px;
+ width: 100px;
+ height: 50%;
+ }
+
+ #spacer {
+ height: 1000px;
+ }
+ </style>
+ <div id="abs"></div>
+ <div id="fixed"></div>
+ <div id="spacer"></div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
+ Compositor().BeginFrame();
+
+ Element* abs_pos = GetDocument().getElementById(WebString::FromUTF8("abs"));
+ Element* fixed_pos =
+ GetDocument().getElementById(WebString::FromUTF8("fixed"));
+
+ ASSERT_EQ(100.f, WebView().GetBrowserControls().ContentOffset());
// Hide the browser controls.
VerticalScroll(-100.f);
- web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateAllLifecyclePhases();
- ASSERT_EQ(300, GetFrame()->View()->GetLayoutSize().Height());
+ WebView().ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
+ Compositor().BeginFrame();
+ ASSERT_EQ(300, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
// Now lock the controls in a hidden state. The layout and elements should
// resize without a WebView::resize.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kBoth, false);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ false);
+ Compositor().BeginFrame();
EXPECT_FLOAT_EQ(200.f, abs_pos->getBoundingClientRect()->height());
EXPECT_FLOAT_EQ(200.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(400, GetFrame()->View()->GetLayoutSize().Height());
+ EXPECT_EQ(400, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
// Unlock the controls, the sizes should change even though the controls are
// still hidden.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kBoth, false);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kBoth, false);
+ Compositor().BeginFrame();
EXPECT_FLOAT_EQ(150.f, abs_pos->getBoundingClientRect()->height());
EXPECT_FLOAT_EQ(200.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(300, GetFrame()->View()->GetLayoutSize().Height());
+ EXPECT_EQ(300, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
// Now lock the controls in a shown state.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kShown,
- cc::BrowserControlsState::kBoth, false);
- web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kShown, cc::BrowserControlsState::kBoth, false);
+ WebView().ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
+ Compositor().BeginFrame();
EXPECT_FLOAT_EQ(150.f, abs_pos->getBoundingClientRect()->height());
EXPECT_FLOAT_EQ(150.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(300, GetFrame()->View()->GetLayoutSize().Height());
+ EXPECT_EQ(300, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
// Shown -> Hidden
- web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kBoth, false);
+ WebView().ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ false);
+ Compositor().BeginFrame();
EXPECT_FLOAT_EQ(200.f, abs_pos->getBoundingClientRect()->height());
EXPECT_FLOAT_EQ(200.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(400, GetFrame()->View()->GetLayoutSize().Height());
+ EXPECT_EQ(400, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
// Go from Unlocked and showing, to locked and hidden but issue the resize
// before the constraint update to check for race issues.
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
- web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- ASSERT_EQ(300, GetFrame()->View()->GetLayoutSize().Height());
- web_view->UpdateAllLifecyclePhases();
-
- web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kHidden,
- false);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
+ WebView().ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
+ Compositor().BeginFrame();
+ ASSERT_EQ(300, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
+
+ WebView().ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kHidden,
+ false);
+ Compositor().BeginFrame();
EXPECT_FLOAT_EQ(200.f, abs_pos->getBoundingClientRect()->height());
EXPECT_FLOAT_EQ(200.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(400, GetFrame()->View()->GetLayoutSize().Height());
+ EXPECT_EQ(400, GetDocument().GetFrame()->View()->GetLayoutSize().Height());
}
// Ensure that browser controls do not affect vh units.
@@ -836,10 +938,10 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectVHUnits)) {
// Initialize with the browser controls showing.
WebViewImpl* web_view = Initialize("vh-height.html");
web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
+ web_view->GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
@@ -857,7 +959,7 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectVHUnits)) {
// Hide the browser controls.
VerticalScroll(-100.f);
web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(0.f, web_view->GetBrowserControls().ContentOffset());
@@ -878,10 +980,10 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectVHUnitsWithScale)) {
// Initialize with the browser controls showing.
WebViewImpl* web_view = Initialize("vh-height-width-800.html");
web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
+ web_view->GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
@@ -906,7 +1008,7 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectVHUnitsWithScale)) {
// Hide the browser controls.
VerticalScroll(-100.f);
web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(0.f, web_view->GetBrowserControls().ContentOffset());
@@ -928,10 +1030,10 @@ TEST_F(BrowserControlsTest, MAYBE(DontAffectVHUnitsUseLayoutSize)) {
// Initialize with the browser controls showing.
WebViewImpl* web_view = Initialize("vh-height-width-800-extra-wide.html");
web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
+ web_view->GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
@@ -964,10 +1066,10 @@ TEST_F(BrowserControlsTest,
GetWebView()->SetDefaultPageScaleLimits(min_scale, 5);
web_view->ResizeWithBrowserControls(WebSize(800, layout_viewport_height),
browser_controls_height, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
+ web_view->GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
LocalFrameView* view = GetFrame()->View();
ScrollableArea* root_viewport = GetFrame()->View()->GetScrollableArea();
@@ -1006,7 +1108,7 @@ TEST_F(BrowserControlsTest,
web_view->ResizeWithBrowserControls(
WebSize(800, layout_viewport_height + browser_controls_height),
browser_controls_height, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
ASSERT_EQ(expected_visual_offset,
GetVisualViewport().GetScrollOffset().Height());
ASSERT_EQ(expected_layout_offset,
@@ -1042,57 +1144,87 @@ TEST_F(BrowserControlsTest,
// the ICB height does not. When the controls are locked hidden, the ICB size
// is the full viewport height so there's no need to add the browser controls
// height. crbug.com/688738.
-TEST_F(BrowserControlsTest, MAYBE(ViewportUnitsWhenControlsLocked)) {
+TEST_F(BrowserControlsSimTest, MAYBE(ViewportUnitsWhenControlsLocked)) {
// Initialize with the browser controls showing.
- WebViewImpl* web_view = Initialize("vh-height.html");
- web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kBoth,
- cc::BrowserControlsState::kShown, false);
- web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
-
- ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
- ASSERT_EQ(300, GetFrame()->View()->GetLayoutSize().Height());
-
- Element* abs_pos = GetElementById(WebString::FromUTF8("abs"));
- Element* fixed_pos = GetElementById(WebString::FromUTF8("fixed"));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ #abs {
+ position: absolute;
+ left: 0px;
+ top: 0px;
+ width: 100px;
+ height: 50vh;
+ }
+
+ #fixed {
+ position: fixed;
+ right: 0px;
+ top: 0px;
+ width: 100px;
+ height: 50vh;
+ }
+
+ #spacer {
+ height: 1000px;
+ }
+ </style>
+ <div id="abs"></div>
+ <div id="fixed"></div>
+ <div id="spacer"></div>
+ )HTML");
+ WebView().ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown, false);
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+ ASSERT_EQ(100.f, WebView().GetBrowserControls().ContentOffset());
+ ASSERT_EQ(300, GetDocument().View()->GetLayoutSize().Height());
+
+ Element* abs_pos = GetDocument().getElementById("abs");
+ Element* fixed_pos = GetDocument().getElementById("fixed");
// Lock the browser controls to hidden.
{
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kHidden,
- cc::BrowserControlsState::kHidden,
- false);
- web_view->ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kHidden,
+ false);
+ WebView().ResizeWithBrowserControls(WebSize(400, 400), 100.f, 0, false);
+ Compositor().BeginFrame();
- ASSERT_EQ(0.f, web_view->GetBrowserControls().ContentOffset());
- ASSERT_EQ(400, GetFrame()->View()->GetLayoutSize().Height());
+ ASSERT_EQ(0.f, WebView().GetBrowserControls().ContentOffset());
+ ASSERT_EQ(400, GetDocument().View()->GetLayoutSize().Height());
// Make sure we're not adding the browser controls height to the vh units
// as when they're locked to hidden, the ICB fills the entire viewport
// already.
EXPECT_FLOAT_EQ(200.f, abs_pos->getBoundingClientRect()->height());
EXPECT_FLOAT_EQ(200.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(400, GetFrame()->View()->ViewportSizeForViewportUnits().Height());
+ EXPECT_EQ(400,
+ GetDocument().View()->ViewportSizeForViewportUnits().Height());
}
// Lock the browser controls to shown. This should cause the vh units to
// behave as usual by including the browser controls region in 100vh.
{
- web_view->UpdateBrowserControlsState(cc::BrowserControlsState::kShown,
- cc::BrowserControlsState::kShown,
- false);
- web_view->ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
- web_view->UpdateAllLifecyclePhases();
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kShown, cc::BrowserControlsState::kShown,
+ false);
+ WebView().ResizeWithBrowserControls(WebSize(400, 300), 100.f, 0, true);
+ Compositor().BeginFrame();
- ASSERT_EQ(100.f, web_view->GetBrowserControls().ContentOffset());
- ASSERT_EQ(300, GetFrame()->View()->GetLayoutSize().Height());
+ ASSERT_EQ(100.f, WebView().GetBrowserControls().ContentOffset());
+ ASSERT_EQ(300, GetDocument().View()->GetLayoutSize().Height());
// Make sure we're not adding the browser controls height to the vh units as
- // when they're locked to hidden, the ICB fills the entire viewport already.
- EXPECT_FLOAT_EQ(200.f, abs_pos->getBoundingClientRect()->height());
- EXPECT_FLOAT_EQ(200.f, fixed_pos->getBoundingClientRect()->height());
- EXPECT_EQ(400, GetFrame()->View()->ViewportSizeForViewportUnits().Height());
+ // when they're locked to shown, the ICB fills the entire viewport already.
+ EXPECT_FLOAT_EQ(150.f, abs_pos->getBoundingClientRect()->height());
+ EXPECT_FLOAT_EQ(150.f, fixed_pos->getBoundingClientRect()->height());
+ EXPECT_EQ(400,
+ GetDocument().View()->ViewportSizeForViewportUnits().Height());
}
}
@@ -1161,14 +1293,14 @@ TEST_F(BrowserControlsTest,
WebViewImpl* web_view = Initialize("95-vh.html");
web_view->ResizeWithBrowserControls(WebSize(412, 604), 56.f, 0, true);
web_view->GetBrowserControls().SetShownRatio(1);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
GetFrame()->GetDocument()->View()->SetTracksPaintInvalidations(true);
// Hide the browser controls.
VerticalScroll(-100.f);
web_view->ResizeWithBrowserControls(WebSize(412, 660), 56.f, 0, false);
- web_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Ensure there is a raster invalidation of the bottom of the layer.
const auto& raster_invalidations = GetFrame()
@@ -1188,4 +1320,193 @@ TEST_F(BrowserControlsTest,
#undef MAYBE
+// Test that sending both an animated and non-animated browser control update
+// doesn't cause the animated one to squash the non-animated.
+// https://crbug.com/861618.
+TEST_F(BrowserControlsSimTest, MixAnimatedAndNonAnimatedUpdateState) {
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <meta name="viewport" content="width=device-width">
+ <style>
+ body {
+ height: 2000px;
+ }
+ </style>
+ )HTML");
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Kick off a non-animated clamp to hide the top controls.
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ false /* animated */);
+
+ // Now kick off an animated one to do the same thing.
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ true /* animated */);
+
+ // Advance time. In https://crbug.com/861618, the animation didn't realize
+ // yet we're already at 0, so it would play the compositor-side up to 80ms,
+ // somewhere mid-way hidden. Later on in this BeginFrame the changes from the
+ // main thread are committed so the top controls shown ratio will set to 0.
+ Compositor().BeginFrame(0.080);
+
+ EXPECT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Tick the animation again. The animation should have been stopped. In
+ // https://crbug.com/861618, the animation would continue to play since it
+ // was kicked off after the non-animated call as far as the compositor could
+ // see. This means this animation tick would set the delta to some non-0 value
+ // again. This value will be committed to the main thread causing the controls
+ // to show.
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+}
+
+// Test that requesting an animated hide on the top controls actually
+// animates rather than happening instantly.
+TEST_F(BrowserControlsSimTest, HideAnimated) {
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <meta name="viewport" content="width=device-width">
+ <style>
+ body {
+ height: 2000px;
+ }
+ </style>
+ )HTML");
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Kick off an animated hide.
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kHidden,
+ true /* animated */);
+
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Advance time.
+ Compositor().BeginFrame(0.080);
+
+ EXPECT_NE(0.f, WebView().GetBrowserControls().ShownRatio());
+ EXPECT_NE(1.f, WebView().GetBrowserControls().ShownRatio());
+}
+
+// Test that requesting an animated show on the top controls actually
+// animates rather than happening instantly.
+TEST_F(BrowserControlsSimTest, ShowAnimated) {
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <meta name="viewport" content="width=device-width">
+ <style>
+ body {
+ height: 2000px;
+ }
+ </style>
+ )HTML");
+ Compositor().BeginFrame();
+
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kHidden,
+ false);
+ WebView().ResizeWithBrowserControls(WebSize(412, 660), 56.f, 0, false);
+
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Kick off an animated show.
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown,
+ true /* animated */);
+
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Advance time.
+ Compositor().BeginFrame(0.080);
+
+ EXPECT_NE(0.f, WebView().GetBrowserControls().ShownRatio());
+ EXPECT_NE(1.f, WebView().GetBrowserControls().ShownRatio());
+}
+
+// Test that setting a constraint inside Blink doesn't clamp the ratio to the
+// constraint. This is required since the CC-side will set the ratio correctly.
+// If we did clamp the ratio, an animation running in CC would get clobbered
+// when we commit.
+TEST_F(BrowserControlsSimTest, ConstraintDoesntClampRatioInBlink) {
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <meta name="viewport" content="width=device-width">
+ <style>
+ body {
+ height: 2000px;
+ }
+ </style>
+ )HTML");
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+
+ {
+ // Pass a hidden constraint to Blink (without going through CC). Make sure
+ // the shown ratio doesn't change since CC is repsonsible for updating the
+ // ratio.
+ WebView().GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ true /* animated */);
+ EXPECT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+ WebView().GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kHidden, cc::BrowserControlsState::kBoth,
+ false /* animated */);
+ EXPECT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Constrain the controls to hidden from the compositor. This should
+ // actually cause the controls to hide when we commit.
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kHidden,
+ false /* animated */);
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+ }
+
+ {
+ // Pass a shown constraint to Blink (without going through CC). Make sure
+ // the shown ratio doesn't change.
+ WebView().GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kShown, cc::BrowserControlsState::kBoth,
+ true /* animated */);
+ EXPECT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+ WebView().GetBrowserControls().UpdateConstraintsAndState(
+ cc::BrowserControlsState::kShown, cc::BrowserControlsState::kBoth,
+ false /* animated */);
+ EXPECT_EQ(0.f, WebView().GetBrowserControls().ShownRatio());
+
+ // Constrain the controls to hidden from the compositor. This should
+ // actually cause the controls to hide when we commit.
+ Compositor().layer_tree_view().UpdateBrowserControlsState(
+ cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kShown,
+ false /* animated */);
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(1.f, WebView().GetBrowserControls().ShownRatio());
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/content_settings_client.cc b/chromium/third_party/blink/renderer/core/frame/content_settings_client.cc
deleted file mode 100644
index 388d8084373..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/content_settings_client.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
-
-#include "third_party/blink/public/platform/web_content_setting_callbacks.h"
-#include "third_party/blink/public/platform/web_content_settings_client.h"
-#include "third_party/blink/public/platform/web_security_origin.h"
-#include "third_party/blink/public/platform/web_url.h"
-#include "third_party/blink/renderer/platform/content_setting_callbacks.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
-
-namespace blink {
-
-ContentSettingsClient::ContentSettingsClient() = default;
-
-bool ContentSettingsClient::AllowDatabase(const String& name,
- const String& display_name,
- unsigned estimated_size) {
- if (client_)
- return client_->AllowDatabase(name, display_name, estimated_size);
- return true;
-}
-
-bool ContentSettingsClient::AllowIndexedDB(
- const String& name,
- const SecurityOrigin* security_origin) {
- if (client_)
- return client_->AllowIndexedDB(name, WebSecurityOrigin(security_origin));
- return true;
-}
-
-bool ContentSettingsClient::RequestFileSystemAccessSync() {
- if (client_)
- return client_->RequestFileSystemAccessSync();
- return true;
-}
-
-void ContentSettingsClient::RequestFileSystemAccessAsync(
- std::unique_ptr<ContentSettingCallbacks> callbacks) {
- if (client_)
- client_->RequestFileSystemAccessAsync(std::move(callbacks));
- else
- callbacks->OnAllowed();
-}
-
-bool ContentSettingsClient::AllowScript(bool enabled_per_settings) {
- if (client_)
- return client_->AllowScript(enabled_per_settings);
- return enabled_per_settings;
-}
-
-bool ContentSettingsClient::AllowScriptFromSource(bool enabled_per_settings,
- const KURL& script_url) {
- if (client_)
- return client_->AllowScriptFromSource(enabled_per_settings, script_url);
- return enabled_per_settings;
-}
-
-void ContentSettingsClient::GetAllowedClientHintsFromSource(
- const KURL& url,
- WebEnabledClientHints* client_hints) {
- if (client_)
- client_->GetAllowedClientHintsFromSource(url, client_hints);
-}
-
-bool ContentSettingsClient::AllowImage(bool enabled_per_settings,
- const KURL& image_url) {
- if (client_)
- return client_->AllowImage(enabled_per_settings, image_url);
- return enabled_per_settings;
-}
-
-bool ContentSettingsClient::AllowReadFromClipboard(bool default_value) {
- if (client_)
- return client_->AllowReadFromClipboard(default_value);
- return default_value;
-}
-
-bool ContentSettingsClient::AllowWriteToClipboard(bool default_value) {
- if (client_)
- return client_->AllowWriteToClipboard(default_value);
- return default_value;
-}
-
-bool ContentSettingsClient::AllowStorage(StorageType type) {
- if (client_)
- return client_->AllowStorage(type == StorageType::kLocal);
- return true;
-}
-
-bool ContentSettingsClient::AllowRunningInsecureContent(
- bool enabled_per_settings,
- const SecurityOrigin* origin,
- const KURL& url) {
- if (client_) {
- return client_->AllowRunningInsecureContent(enabled_per_settings,
- WebSecurityOrigin(origin), url);
- }
- return enabled_per_settings;
-}
-
-bool ContentSettingsClient::AllowMutationEvents(bool default_value) {
- if (client_)
- return client_->AllowMutationEvents(default_value);
- return default_value;
-}
-
-bool ContentSettingsClient::AllowAutoplay(bool default_value) {
- if (client_)
- return client_->AllowAutoplay(default_value);
- return default_value;
-}
-
-bool ContentSettingsClient::AllowPopupsAndRedirects(bool default_value) {
- if (client_)
- return client_->AllowPopupsAndRedirects(default_value);
- return default_value;
-}
-
-void ContentSettingsClient::PassiveInsecureContentFound(const KURL& url) {
- if (client_)
- return client_->PassiveInsecureContentFound(url);
-}
-
-void ContentSettingsClient::DidNotAllowScript() {
- if (client_)
- client_->DidNotAllowScript();
-}
-
-void ContentSettingsClient::DidNotAllowPlugins() {
- if (client_)
- client_->DidNotAllowPlugins();
-}
-
-void ContentSettingsClient::PersistClientHints(
- const WebEnabledClientHints& enabled_client_hints,
- TimeDelta duration,
- const KURL& url) {
- if (client_) {
- return client_->PersistClientHints(enabled_client_hints, duration, url);
- }
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/content_settings_client.h b/chromium/third_party/blink/renderer/core/frame/content_settings_client.h
deleted file mode 100644
index 8fce92fe7d3..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/content_settings_client.h
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_CONTENT_SETTINGS_CLIENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_CONTENT_SETTINGS_CLIENT_H_
-
-#include <memory>
-
-#include "third_party/blink/public/platform/web_client_hints_type.h"
-#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/blink/renderer/platform/wtf/time.h"
-
-namespace blink {
-
-class ContentSettingCallbacks;
-class KURL;
-class SecurityOrigin;
-class WebContentSettingsClient;
-struct WebEnabledClientHints;
-
-// This class provides the content settings information which tells
-// whether each feature is allowed. Most of the methods return the
-// given default values if embedder doesn't provide their own
-// content settings client implementation (via m_client).
-class CORE_EXPORT ContentSettingsClient {
- public:
- ContentSettingsClient();
-
- void SetClient(WebContentSettingsClient* client) { client_ = client; }
-
- // Controls whether access to Web Databases is allowed.
- bool AllowDatabase(const String& name,
- const String& display_name,
- unsigned estimated_size);
-
- // Controls whether access to File System is allowed for this frame.
- bool RequestFileSystemAccessSync();
-
- // Controls whether access to File System is allowed for this frame.
- void RequestFileSystemAccessAsync(std::unique_ptr<ContentSettingCallbacks>);
-
- // Controls whether access to File System is allowed.
- bool AllowIndexedDB(const String& name, const SecurityOrigin*);
-
- // Controls whether scripts are allowed to execute.
- bool AllowScript(bool enabled_per_settings);
-
- // Controls whether scripts loaded from the given URL are allowed to execute.
- bool AllowScriptFromSource(bool enabled_per_settings, const KURL&);
-
- // Retrieves the client hints that should be attached to the request for the
- // given URL.
- void GetAllowedClientHintsFromSource(const KURL&, WebEnabledClientHints*);
- // Controls whether images are allowed.
- bool AllowImage(bool enabled_per_settings, const KURL&);
-
- // Controls whether insecure scripts are allowed to execute for this frame.
- bool AllowRunningInsecureContent(bool enabled_per_settings,
- const SecurityOrigin*,
- const KURL&);
-
- // Controls whether HTML5 Web Storage is allowed for this frame.
- enum class StorageType { kLocal, kSession };
- bool AllowStorage(StorageType);
-
- // Controls whether access to read the clipboard is allowed for this frame.
- bool AllowReadFromClipboard(bool default_value);
-
- // Controls whether access to write the clipboard is allowed for this frame.
- bool AllowWriteToClipboard(bool default_value);
-
- // Controls whether to enable MutationEvents for this frame.
- // The common use case of this method is actually to selectively disable
- // MutationEvents, but it's been named for consistency with the rest of the
- // interface.
- bool AllowMutationEvents(bool default_value);
-
- // Controls whether autoplay is allowed for this frame.
- bool AllowAutoplay(bool default_value);
-
- // Controls whether popups and abusive redirects (e.g. framebusting) are
- // allowed for this frame.
- bool AllowPopupsAndRedirects(bool default_value);
-
- // Reports that passive mixed content was found at the provided URL. It may or
- // may not be actually displayed later, what would be flagged by
- // didDisplayInsecureContent.
- void PassiveInsecureContentFound(const KURL&);
-
- // This callback notifies the client that the frame was about to run
- // JavaScript but did not because allowScript returned false. We have a
- // separate callback here because there are a number of places that need to
- // know if JavaScript is enabled but are not necessarily preparing to execute
- // script.
- void DidNotAllowScript();
-
- // This callback is similar, but for plugins.
- void DidNotAllowPlugins();
-
- // Called to persist the client hint preferences received when |url| was
- // fetched. The preferences should be persisted for |duration|.
- void PersistClientHints(const WebEnabledClientHints&,
- TimeDelta duration,
- const KURL&);
-
- private:
- WebContentSettingsClient* client_ = nullptr;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_CONTENT_SETTINGS_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.cc b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.cc
index 586be34a221..181137417d9 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.cc
@@ -32,7 +32,9 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_string_list.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -56,6 +58,7 @@
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
+#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/json/json_values.h"
#include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
@@ -73,6 +76,7 @@
#include "third_party/blink/renderer/platform/wtf/text/parsing_utilities.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
+#include "v8/include/v8.h"
namespace blink {
@@ -312,7 +316,7 @@ bool ContentSecurityPolicy::ShouldEnforceEmbeddersPolicy(
if (parent_origin->CanAccess(SecurityOrigin::Create(response.Url()).get()))
return true;
- String header = response.HttpHeaderField(HTTPNames::Allow_CSP_From);
+ String header = response.HttpHeaderField(http_names::kAllowCSPFrom);
header = header.StripWhiteSpace();
if (header == "*")
return true;
@@ -1301,7 +1305,8 @@ void ContentSecurityPolicy::ReportViolation(
DCHECK((execution_context_ && !context_frame) ||
((effective_type == DirectiveType::kFrameAncestors) && context_frame));
- SecurityPolicyViolationEventInit violation_data;
+ SecurityPolicyViolationEventInit* violation_data =
+ SecurityPolicyViolationEventInit::Create();
// If we're processing 'frame-ancestors', use |contextFrame|'s execution
// context to gather data. Otherwise, use the policy's execution context.
@@ -1309,7 +1314,7 @@ void ContentSecurityPolicy::ReportViolation(
context_frame ? context_frame->GetDocument() : execution_context_;
DCHECK(relevant_context);
GatherSecurityPolicyViolationEventData(
- &violation_data, relevant_context, directive_text, effective_type,
+ violation_data, relevant_context, directive_text, effective_type,
blocked_url, header, redirect_status, header_type, violation_type,
std::move(source_location), source);
@@ -1317,8 +1322,8 @@ void ContentSecurityPolicy::ReportViolation(
// resources should be allowed regardless. We apparently do, however, so
// we should at least stop spamming reporting endpoints. See
// https://crbug.com/524356 for detail.
- if (!violation_data.sourceFile().IsEmpty() &&
- ShouldBypassContentSecurityPolicy(KURL(violation_data.sourceFile()),
+ if (!violation_data->sourceFile().IsEmpty() &&
+ ShouldBypassContentSecurityPolicy(KURL(violation_data->sourceFile()),
execution_context_)) {
return;
}
@@ -1330,15 +1335,16 @@ void ContentSecurityPolicy::ReportViolation(
// we're not processing 'frame-ancestors').
if (execution_context_) {
execution_context_->GetTaskRunner(TaskType::kNetworking)
- ->PostTask(FROM_HERE,
- WTF::Bind(&ContentSecurityPolicy::DispatchViolationEvents,
- WrapPersistent(this), violation_data,
- WrapPersistent(element)));
+ ->PostTask(
+ FROM_HERE,
+ WTF::Bind(&ContentSecurityPolicy::DispatchViolationEvents,
+ WrapPersistent(this), WrapPersistent(violation_data),
+ WrapPersistent(element)));
}
}
void ContentSecurityPolicy::PostViolationReport(
- const SecurityPolicyViolationEventInit& violation_data,
+ const SecurityPolicyViolationEventInit* violation_data,
LocalFrame* context_frame,
const Vector<String>& report_endpoints,
bool use_reporting_api) {
@@ -1356,24 +1362,24 @@ void ContentSecurityPolicy::PostViolationReport(
// let's kill them. https://crbug.com/695363
std::unique_ptr<JSONObject> csp_report = JSONObject::Create();
- csp_report->SetString("document-uri", violation_data.documentURI());
- csp_report->SetString("referrer", violation_data.referrer());
+ csp_report->SetString("document-uri", violation_data->documentURI());
+ csp_report->SetString("referrer", violation_data->referrer());
csp_report->SetString("violated-directive",
- violation_data.violatedDirective());
+ violation_data->violatedDirective());
csp_report->SetString("effective-directive",
- violation_data.effectiveDirective());
- csp_report->SetString("original-policy", violation_data.originalPolicy());
- csp_report->SetString("disposition", violation_data.disposition());
- csp_report->SetString("blocked-uri", violation_data.blockedURI());
- if (violation_data.lineNumber())
- csp_report->SetInteger("line-number", violation_data.lineNumber());
- if (violation_data.columnNumber())
- csp_report->SetInteger("column-number", violation_data.columnNumber());
- if (!violation_data.sourceFile().IsEmpty())
- csp_report->SetString("source-file", violation_data.sourceFile());
- csp_report->SetInteger("status-code", violation_data.statusCode());
-
- csp_report->SetString("script-sample", violation_data.sample());
+ violation_data->effectiveDirective());
+ csp_report->SetString("original-policy", violation_data->originalPolicy());
+ csp_report->SetString("disposition", violation_data->disposition());
+ csp_report->SetString("blocked-uri", violation_data->blockedURI());
+ if (violation_data->lineNumber())
+ csp_report->SetInteger("line-number", violation_data->lineNumber());
+ if (violation_data->columnNumber())
+ csp_report->SetInteger("column-number", violation_data->columnNumber());
+ if (!violation_data->sourceFile().IsEmpty())
+ csp_report->SetString("source-file", violation_data->sourceFile());
+ csp_report->SetInteger("status-code", violation_data->statusCode());
+
+ csp_report->SetString("script-sample", violation_data->sample());
std::unique_ptr<JSONObject> report_object = JSONObject::Create();
report_object->SetObject("csp-report", std::move(csp_report));
@@ -1413,12 +1419,12 @@ void ContentSecurityPolicy::PostViolationReport(
// document's URL.
DCHECK(!context_frame || !execution_context_);
DCHECK(!context_frame ||
- GetDirectiveType(violation_data.effectiveDirective()) ==
+ GetDirectiveType(violation_data->effectiveDirective()) ==
DirectiveType::kFrameAncestors);
KURL url =
context_frame
? frame->GetDocument()->CompleteURLWithOverride(
- report_endpoint, KURL(violation_data.blockedURI()))
+ report_endpoint, KURL(violation_data->blockedURI()))
// We use the FallbackBaseURL to ensure that we don't
// respect base elements when determining the report
// endpoint URL.
@@ -1433,24 +1439,23 @@ void ContentSecurityPolicy::PostViolationReport(
}
void ContentSecurityPolicy::DispatchViolationEvents(
- const SecurityPolicyViolationEventInit& violation_data,
+ const SecurityPolicyViolationEventInit* violation_data,
Element* element) {
// Worklets don't support Events in general.
if (execution_context_->IsWorkletGlobalScope())
return;
SecurityPolicyViolationEvent& event = *SecurityPolicyViolationEvent::Create(
- EventTypeNames::securitypolicyviolation, violation_data);
+ event_type_names::kSecuritypolicyviolation, violation_data);
DCHECK(event.bubbles());
- if (auto* document = DynamicTo<Document>(execution_context_.Get())) {
+ if (auto* document = DynamicTo<Document>(*execution_context_)) {
if (element && element->isConnected() && element->GetDocument() == document)
element->EnqueueEvent(event, TaskType::kInternalDefault);
else
document->EnqueueEvent(event, TaskType::kInternalDefault);
- } else if (execution_context_->IsWorkerGlobalScope()) {
- ToWorkerGlobalScope(execution_context_)
- ->EnqueueEvent(event, TaskType::kInternalDefault);
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_)) {
+ scope->EnqueueEvent(event, TaskType::kInternalDefault);
}
}
@@ -1676,16 +1681,23 @@ const String& ContentSecurityPolicy::GetSelfProtocol() const {
return self_protocol_;
}
+// static
bool ContentSecurityPolicy::ShouldBypassMainWorld(
const ExecutionContext* context) {
- if (const auto* document = DynamicTo<Document>(context)) {
- if (document->GetFrame()) {
- return document->GetFrame()
- ->GetScriptController()
- .ShouldBypassMainWorldCSP();
- }
- }
- return false;
+ if (!context)
+ return false;
+
+ v8::Isolate* isolate = ToIsolate(context);
+ v8::HandleScope handle_scope(isolate);
+ v8::Local<v8::Context> v8_context = isolate->GetCurrentContext();
+ if (v8_context.IsEmpty())
+ return false;
+
+ DOMWrapperWorld& world = DOMWrapperWorld::Current(isolate);
+ if (!world.IsIsolatedWorld())
+ return false;
+
+ return IsolatedWorldCSP::Get().HasContentSecurityPolicy(world.GetWorldId());
}
bool ContentSecurityPolicy::ShouldSendViolationReport(
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.h b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.h
index 3de5b1c783f..6d795e65bf7 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.h
+++ b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.h
@@ -510,9 +510,9 @@ class CORE_EXPORT ContentSecurityPolicy
bool ShouldSendViolationReport(const String&) const;
void DidSendViolationReport(const String&);
- void DispatchViolationEvents(const SecurityPolicyViolationEventInit&,
+ void DispatchViolationEvents(const SecurityPolicyViolationEventInit*,
Element*);
- void PostViolationReport(const SecurityPolicyViolationEventInit&,
+ void PostViolationReport(const SecurityPolicyViolationEventInit*,
LocalFrame*,
const Vector<String>& report_endpoints,
bool use_reporting_api);
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_test.cc b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_test.cc
index 37bf3d38e0f..0ff44e2659e 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_test.cc
@@ -34,7 +34,8 @@ class ContentSecurityPolicyTest : public testing::Test {
void SetUp() override { execution_context = CreateExecutionContext(); }
NullExecutionContext* CreateExecutionContext() {
- NullExecutionContext* context = new NullExecutionContext();
+ NullExecutionContext* context =
+ MakeGarbageCollected<NullExecutionContext>();
context->SetUpSecurityContext();
context->SetSecurityOrigin(secure_origin);
return context;
@@ -936,23 +937,23 @@ TEST_F(ContentSecurityPolicyTest, ShouldEnforceEmbeddersPolicy) {
response, secure_origin.get()),
test.inherits);
- response.SetHTTPHeaderField(HTTPNames::Allow_CSP_From, AtomicString("*"));
+ response.SetHTTPHeaderField(http_names::kAllowCSPFrom, AtomicString("*"));
EXPECT_TRUE(ContentSecurityPolicy::ShouldEnforceEmbeddersPolicy(
response, secure_origin.get()));
- response.SetHTTPHeaderField(HTTPNames::Allow_CSP_From,
+ response.SetHTTPHeaderField(http_names::kAllowCSPFrom,
AtomicString("* not a valid header"));
EXPECT_EQ(ContentSecurityPolicy::ShouldEnforceEmbeddersPolicy(
response, secure_origin.get()),
test.inherits);
- response.SetHTTPHeaderField(HTTPNames::Allow_CSP_From,
+ response.SetHTTPHeaderField(http_names::kAllowCSPFrom,
AtomicString("http://example.test"));
EXPECT_EQ(ContentSecurityPolicy::ShouldEnforceEmbeddersPolicy(
response, secure_origin.get()),
test.inherits);
- response.SetHTTPHeaderField(HTTPNames::Allow_CSP_From,
+ response.SetHTTPHeaderField(http_names::kAllowCSPFrom,
AtomicString("https://example.test"));
EXPECT_TRUE(ContentSecurityPolicy::ShouldEnforceEmbeddersPolicy(
response, secure_origin.get()));
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc b/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
index 6555a608bdd..51884a11a96 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
@@ -709,8 +709,9 @@ bool CSPDirectiveList::AllowEval(
"Policy directive: ",
script_state, exception_status, content);
}
- return CheckEval(
- OperativeDirective(ContentSecurityPolicy::DirectiveType::kScriptSrc));
+ return IsReportOnly() ||
+ CheckEval(OperativeDirective(
+ ContentSecurityPolicy::DirectiveType::kScriptSrc));
}
bool CSPDirectiveList::AllowWasmEval(
@@ -726,8 +727,9 @@ bool CSPDirectiveList::AllowWasmEval(
"Content Security Policy directive: ",
script_state, exception_status, content);
}
- return CheckWasmEval(
- OperativeDirective(ContentSecurityPolicy::DirectiveType::kScriptSrc));
+ return IsReportOnly() ||
+ CheckWasmEval(OperativeDirective(
+ ContentSecurityPolicy::DirectiveType::kScriptSrc));
}
bool CSPDirectiveList::AllowPluginType(
@@ -1118,6 +1120,9 @@ bool CSPDirectiveList::ParseDirective(const UChar* begin,
// The directive-name must be non-empty.
if (name_begin == position) {
+ // Malformed CSP: directive starts with invalid characters
+ UseCounter::Count(policy_->GetDocument(), WebFeature::kMalformedCSP);
+
SkipWhile<UChar, IsNotASCIISpace>(position, end);
policy_->ReportUnsupportedDirective(
String(name_begin, static_cast<wtf_size_t>(position - name_begin)));
@@ -1131,6 +1136,9 @@ bool CSPDirectiveList::ParseDirective(const UChar* begin,
return true;
if (!SkipExactly<UChar, IsASCIISpace>(position, end)) {
+ // Malformed CSP: after the directive name we don't have a space
+ UseCounter::Count(policy_->GetDocument(), WebFeature::kMalformedCSP);
+
SkipWhile<UChar, IsNotASCIISpace>(position, end);
policy_->ReportUnsupportedDirective(
String(name_begin, static_cast<wtf_size_t>(position - name_begin)));
@@ -1143,6 +1151,9 @@ bool CSPDirectiveList::ParseDirective(const UChar* begin,
SkipWhile<UChar, IsCSPDirectiveValueCharacter>(position, end);
if (position != end) {
+ // Malformed CSP: directive value has invalid characters
+ UseCounter::Count(policy_->GetDocument(), WebFeature::kMalformedCSP);
+
policy_->ReportInvalidDirectiveValueCharacter(
*name, String(value_begin, static_cast<wtf_size_t>(end - value_begin)));
return false;
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/media_list_directive_test.cc b/chromium/third_party/blink/renderer/core/frame/csp/media_list_directive_test.cc
index dbfad349cb6..f86ae3e6dc8 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/media_list_directive_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/media_list_directive_test.cc
@@ -139,8 +139,8 @@ TEST_F(MediaListDirectiveTest, Subsumes) {
for (const auto& test : cases) {
HeapVector<Member<MediaListDirective>> policies_b;
for (auto* const policy : test.policies_b) {
- policies_b.push_back(
- new MediaListDirective("plugin-types", policy, csp.Get()));
+ policies_b.push_back(MakeGarbageCollected<MediaListDirective>(
+ "plugin-types", policy, csp.Get()));
}
EXPECT_EQ(a.Subsumes(policies_b), test.subsumed);
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc b/chromium/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc
index 070fbe0ff20..ff0b7139002 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc
@@ -416,8 +416,8 @@ TEST_F(SourceListDirectiveTest, Subsumes) {
HeapVector<Member<SourceListDirective>> returned;
for (const auto& sources : test.sources_vector) {
- SourceListDirective* member =
- new SourceListDirective("script-src", sources, csp.Get());
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
+ "script-src", sources, csp.Get());
returned.push_back(member);
}
@@ -533,8 +533,8 @@ TEST_F(SourceListDirectiveTest, SubsumesWithSelf) {
HeapVector<Member<SourceListDirective>> vector_b;
for (auto* const sources : test.sources_b) {
- SourceListDirective* member =
- new SourceListDirective("script-src", sources, csp_b);
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
+ "script-src", sources, csp_b);
vector_b.push_back(member);
}
@@ -699,7 +699,7 @@ TEST_F(SourceListDirectiveTest, SubsumesAllowAllInline) {
HeapVector<Member<SourceListDirective>> vector_b;
for (const auto& sources : test.sources_b) {
- SourceListDirective* member = new SourceListDirective(
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
test.is_script_src ? "script-src" : "style-src", sources, csp_b);
vector_b.push_back(member);
}
@@ -788,7 +788,7 @@ TEST_F(SourceListDirectiveTest, SubsumesUnsafeAttributes) {
HeapVector<Member<SourceListDirective>> vector_b;
for (const auto& sources : test.sources_b) {
- SourceListDirective* member = new SourceListDirective(
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
test.is_script_src ? "script-src" : "style-src", sources, csp_b);
vector_b.push_back(member);
}
@@ -1051,7 +1051,7 @@ TEST_F(SourceListDirectiveTest, SubsumesNoncesAndHashes) {
HeapVector<Member<SourceListDirective>> vector_b;
for (const auto& sources : test.sources_b) {
- SourceListDirective* member = new SourceListDirective(
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
test.is_script_src ? "script-src" : "style-src", sources, csp_b);
vector_b.push_back(member);
}
@@ -1227,7 +1227,7 @@ TEST_F(SourceListDirectiveTest, SubsumesStrictDynamic) {
HeapVector<Member<SourceListDirective>> vector_b;
for (const auto& sources : test.sources_b) {
- SourceListDirective* member = new SourceListDirective(
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
test.is_script_src ? "script-src" : "style-src", sources, csp_b);
vector_b.push_back(member);
}
@@ -1298,8 +1298,8 @@ TEST_F(SourceListDirectiveTest, SubsumesListWildcard) {
HeapVector<Member<SourceListDirective>> vector_b;
for (auto* const sources : test.sources_b) {
- SourceListDirective* member =
- new SourceListDirective("script-src", sources, csp_b);
+ SourceListDirective* member = MakeGarbageCollected<SourceListDirective>(
+ "script-src", sources, csp_b);
vector_b.push_back(member);
}
diff --git a/chromium/third_party/blink/renderer/core/frame/deferred_loading_test.cc b/chromium/third_party/blink/renderer/core/frame/deferred_loading_test.cc
deleted file mode 100644
index fa7d3fe2e64..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/deferred_loading_test.cc
+++ /dev/null
@@ -1,519 +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 <memory>
-
-#include "third_party/blink/renderer/core/dom/element.h"
-#include "third_party/blink/renderer/core/exported/web_view_impl.h"
-#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
-#include "third_party/blink/renderer/core/testing/sim/sim_compositor.h"
-#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
-#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
-#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
-#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
-
-namespace blink {
-
-static const char kHistogramName[] =
- "Navigation.DeferredDocumentLoading.StatesV4";
-
-class DeferredLoadingTest : public SimTest {
- protected:
- DeferredLoadingTest() = default;
-
- void SetUp() override {
- SimTest::SetUp();
- WebView().Resize(WebSize(640, 480));
- }
- void CompositeFrame() {
- while (Compositor().NeedsBeginFrame()) {
- Compositor().BeginFrame();
- test::RunPendingTasks();
- }
- }
-
- std::unique_ptr<SimRequest> CreateMainResource() {
- std::unique_ptr<SimRequest> main_resource =
- std::make_unique<SimRequest>("https://example.com/", "text/html");
- LoadURL("https://example.com/");
- return main_resource;
- }
-
- void ExpectCount(WouldLoadReason reason, int count) {
- histogram_tester_.ExpectBucketCount(kHistogramName,
- static_cast<int>(reason), count);
- }
-
- void ExpectTotalCount(int count) {
- histogram_tester_.ExpectTotalCount(kHistogramName, count);
- }
-
- private:
- HistogramTester histogram_tester_;
-};
-
-TEST_F(DeferredLoadingTest, Visible) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete("<iframe sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, Right) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; left:105vw;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectTotalCount(1);
-}
-
-TEST_F(DeferredLoadingTest, TwoScreensBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:205vh;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(3);
-}
-
-TEST_F(DeferredLoadingTest, Above) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:-10000px;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, Left) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; left:-10000px;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, AboveAndLeft) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; left:-10000px; top:-10000px' sandbox>"
- "</iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, ZeroByZero) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='height:0px;width:0px;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
-}
-
-TEST_F(DeferredLoadingTest, DisplayNone) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete("<iframe style='display:none' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kNoParent, 1);
- ExpectTotalCount(6);
-}
-
-TEST_F(DeferredLoadingTest, DisplayNoneIn2ScreensBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:205vh' "
- "src='iframe.html' sandbox></iframe>");
- frame_resource.Complete("<iframe style='display:none' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 2);
- ExpectCount(WouldLoadReason::kNoParent, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 2);
- ExpectCount(WouldLoadReason::k3ScreensAway, 2);
- ExpectTotalCount(9);
-}
-
-TEST_F(DeferredLoadingTest, LeftNestedInBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:105vh;' src='iframe.html' "
- "sandbox></iframe>");
- frame_resource.Complete(
- "<iframe style='position:absolute; left:-10000px;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 2);
- ExpectCount(WouldLoadReason::k1ScreenAway, 2);
- ExpectCount(WouldLoadReason::k2ScreensAway, 2);
- ExpectCount(WouldLoadReason::k3ScreensAway, 2);
- ExpectTotalCount(8);
-}
-
-TEST_F(DeferredLoadingTest, OneScreenBelowThenScriptedVisible) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Start();
- main_resource->Write(
- "<iframe id='theFrame' style='position:absolute; top:105vh;' "
- "sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectTotalCount(4);
-
- main_resource->Write("<script>theFrame.style.top='10px'</script>");
- main_resource->Finish();
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, OneScreenBelowThenScrolledVisible) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe id='theFrame' style='position:absolute; top:105vh; height:10px' "
- "sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(4);
-
- MainFrame().SetScrollOffset(WebSize(0, 50));
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, DisplayNoneThenTwoScreensAway) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Start();
- main_resource->Write(
- "<iframe id='theFrame' style='display:none' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectTotalCount(6);
-
- main_resource->Write(R"HTML(
- <script>theFrame.style.top='200vh';
- theFrame.style.position='absolute';
- theFrame.style.display='block';</script>
- )HTML");
- main_resource->Finish();
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kNoParent, 1);
- ExpectTotalCount(6);
-}
-
-TEST_F(DeferredLoadingTest, DisplayNoneAsync) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Start();
- main_resource->Write("some stuff");
-
- CompositeFrame();
-
- main_resource->Write(R"HTML(
- <script>frame = document.createElement('iframe');
- frame.setAttribute('sandbox', true);
- frame.style.display = 'none';
- document.body.appendChild(frame);
- </script>
- )HTML");
- main_resource->Finish();
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kNoParent, 1);
- ExpectTotalCount(6);
-}
-
-TEST_F(DeferredLoadingTest, TwoScreensAwayThenDisplayNoneThenNew) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Start();
- main_resource->Write(
- "<iframe id='theFrame' style='position:absolute; top:205vh' sandbox>"
- "</iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(3);
-
- main_resource->Write("<script>theFrame.style.display='none'</script>");
-
- CompositeFrame();
-
- ExpectTotalCount(6);
-
- main_resource->Write(
- "<script>document.body.appendChild(document.createElement"
- "('iframe'));</script>");
- main_resource->Finish();
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kNoParent, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(6);
-}
-
-TEST_F(DeferredLoadingTest, SameOriginNotCounted) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete("<iframe src='iframe.html'></iframe>");
- frame_resource.Complete("<iframe></iframe>");
- CompositeFrame();
-
- ExpectTotalCount(0);
-}
-
-TEST_F(DeferredLoadingTest, AboveNestedInThreeScreensBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:300vh' src='iframe.html' "
- "sandbox></iframe>");
- frame_resource.Complete(
- "<iframe style='position:absolute; top:-10000px;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 2);
- ExpectCount(WouldLoadReason::k3ScreensAway, 2);
- ExpectTotalCount(4);
-}
-
-TEST_F(DeferredLoadingTest, VisibleNestedInTwoScreensBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:205vh' src='iframe.html' "
- "sandbox></iframe>");
- frame_resource.Complete("<iframe sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 2);
- ExpectCount(WouldLoadReason::k2ScreensAway, 2);
- ExpectCount(WouldLoadReason::k3ScreensAway, 2);
- ExpectTotalCount(6);
-}
-
-TEST_F(DeferredLoadingTest, ThreeScreensBelowNestedInTwoScreensBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:205vh' src='iframe.html' "
- "sandbox></iframe>");
- frame_resource.Complete(
- "<iframe style='position:absolute; top:305vh' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 2);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(4);
-}
-
-TEST_F(DeferredLoadingTest, TriplyNested) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
- SimRequest frame_resource2("https://example.com/iframe2.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:300vh' src='iframe.html' "
- "sandbox></iframe>");
- frame_resource.Complete(
- "<iframe style='position:absolute; top:200vh' src='iframe2.html' "
- "sandbox></iframe>");
- frame_resource2.Complete(
- "<iframe style='position:absolute; top:100vh' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 3);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(4);
-}
-
-TEST_F(DeferredLoadingTest, NestedFramesOfVariousSizes) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
- SimRequest frame_resource2("https://example.com/iframe2.html", "text/html");
- SimRequest frame_resource3("https://example.com/iframe3.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:50vh; height:10px;'"
- "src='iframe.html' sandbox></iframe>");
- frame_resource.Complete(
- "<iframe style='position:absolute; top:200vh; height:100px;'"
- "src='iframe2.html' sandbox></iframe>");
- frame_resource2.Complete(
- "<iframe style='position:absolute; top:100vh; height:50px;'"
- "src='iframe3.html' sandbox></iframe>");
- frame_resource3.Complete(
- "<iframe style='position:absolute; top:100vh' sandbox></iframe>");
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 4);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 2);
- ExpectCount(WouldLoadReason::k3ScreensAway, 3);
- ExpectTotalCount(11);
-}
-
-TEST_F(DeferredLoadingTest, FourScreensBelow) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:405vh;' sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectTotalCount(1);
-}
-
-TEST_F(DeferredLoadingTest, TallIFrameStartsAbove) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:-150vh; height:200vh;' sandbox>"
- "</iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, OneDownAndOneRight) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
-
- main_resource->Complete(
- "<iframe style='position:absolute; left:100vw; top:100vh' sandbox>"
- "</iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectTotalCount(1);
-}
-
-TEST_F(DeferredLoadingTest, VisibleCrossOriginNestedInBelowFoldSameOrigin) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/iframe.html", "text/html");
-
- main_resource->Complete(
- "<iframe style='position:absolute; top:105vh' src='iframe.html'>"
- "</iframe>");
- frame_resource.Complete("<iframe sandbox></iframe>");
-
- CompositeFrame();
-
- ExpectCount(WouldLoadReason::kCreated, 1);
- ExpectCount(WouldLoadReason::kVisible, 1);
- ExpectCount(WouldLoadReason::k1ScreenAway, 1);
- ExpectCount(WouldLoadReason::k2ScreensAway, 1);
- ExpectCount(WouldLoadReason::k3ScreensAway, 1);
- ExpectTotalCount(5);
-}
-
-TEST_F(DeferredLoadingTest, EmbedSVG) {
- std::unique_ptr<SimRequest> main_resource = CreateMainResource();
- SimRequest frame_resource("https://example.com/embed.svg", "image/svg+xml");
- main_resource->Complete("<iframe id='embed' src='embed.svg'></iframe>");
- CompositeFrame();
- Element* embed_element = GetDocument().getElementById("embed");
- embed_element->SetInlineStyleProperty(CSSPropertyDisplay, "none");
- frame_resource.Complete("<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>");
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/deprecation.cc b/chromium/third_party/blink/renderer/core/frame/deprecation.cc
index 013bedba1c2..e8a2f73bda7 100644
--- a/chromium/third_party/blink/renderer/core/frame/deprecation.cc
+++ b/chromium/third_party/blink/renderer/core/frame/deprecation.cc
@@ -549,12 +549,6 @@ DeprecationInfo GetDeprecationInfo(WebFeature feature) {
return {"ChromeLoadTimesWasAlternateProtocolAvailable", kUnknown,
kChromeLoadTimesNextHopProtocol};
- case WebFeature::kDataUriHasOctothorpe:
- return {"DataUriHasOctothorpe", kM71,
- ReplacedWillBeRemoved(
- "Using unescaped '#' characters in a data URI body", "'%23'",
- kM71, "5656049583390720")};
-
case WebFeature::kMediaElementSourceOnOfflineContext:
return {"MediaElementAudioSourceNode", kM71,
WillBeRemoved("Creating a MediaElementAudioSourceNode on an "
@@ -828,9 +822,10 @@ void Deprecation::GenerateReport(const LocalFrame* frame, WebFeature feature) {
// Construct the deprecation report.
double removal_date = MilestoneDate(info.anticipated_removal);
- DeprecationReportBody* body = new DeprecationReportBody(
+ DeprecationReportBody* body = MakeGarbageCollected<DeprecationReportBody>(
info.id, removal_date, info.message, SourceLocation::Capture());
- Report* report = new Report("deprecation", document->Url().GetString(), body);
+ Report* report = MakeGarbageCollected<Report>(
+ "deprecation", document->Url().GetString(), body);
// Send the deprecation report to any ReportingObservers.
ReportingContext::From(document)->QueueReport(report);
diff --git a/chromium/third_party/blink/renderer/core/frame/deprecation.h b/chromium/third_party/blink/renderer/core/frame/deprecation.h
index 6ff03726b0a..6cc1eff3385 100644
--- a/chromium/third_party/blink/renderer/core/frame/deprecation.h
+++ b/chromium/third_party/blink/renderer/core/frame/deprecation.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/bit_vector.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/deprecation_report_body.idl b/chromium/third_party/blink/renderer/core/frame/deprecation_report_body.idl
index 8ac1919fdf8..5b76ce4879d 100644
--- a/chromium/third_party/blink/renderer/core/frame/deprecation_report_body.idl
+++ b/chromium/third_party/blink/renderer/core/frame/deprecation_report_body.idl
@@ -5,8 +5,7 @@
// https://wicg.github.io/reporting/#deprecation-report
[
- NoInterfaceObject,
- RuntimeEnabled=DeprecationReporting
+ NoInterfaceObject
] interface DeprecationReportBody : ReportBody {
readonly attribute DOMString id;
readonly attribute Date? anticipatedRemoval;
diff --git a/chromium/third_party/blink/renderer/core/frame/device_single_window_event_controller.cc b/chromium/third_party/blink/renderer/core/frame/device_single_window_event_controller.cc
index 75ede527e78..44f49c5bd47 100644
--- a/chromium/third_party/blink/renderer/core/frame/device_single_window_event_controller.cc
+++ b/chromium/third_party/blink/renderer/core/frame/device_single_window_event_controller.cc
@@ -96,7 +96,8 @@ bool DeviceSingleWindowEventController::CheckPolicyFeatures(
const Document& document = GetDocument();
return std::all_of(features.begin(), features.end(),
[&document](mojom::FeaturePolicyFeature feature) {
- return document.IsFeatureEnabled(feature);
+ return document.IsFeatureEnabled(
+ feature, ReportOptions::kReportOnFailure);
});
}
diff --git a/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.cc b/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.cc
index 055f69cfb85..ddddffce44f 100644
--- a/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.cc
@@ -33,7 +33,7 @@ void DisplayCutoutClientImpl::BindMojoRequest(
mojom::blink::DisplayCutoutClientAssociatedRequest request) {
if (!frame)
return;
- new DisplayCutoutClientImpl(frame, std::move(request));
+ MakeGarbageCollected<DisplayCutoutClientImpl>(frame, std::move(request));
}
void DisplayCutoutClientImpl::SetSafeArea(
diff --git a/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.h b/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.h
index 56aade212f6..b547e26f590 100644
--- a/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.h
+++ b/chromium/third_party/blink/renderer/core/frame/display_cutout_client_impl.h
@@ -24,15 +24,15 @@ class CORE_EXPORT DisplayCutoutClientImpl final
LocalFrame*,
mojom::blink::DisplayCutoutClientAssociatedRequest);
+ DisplayCutoutClientImpl(LocalFrame*,
+ mojom::blink::DisplayCutoutClientAssociatedRequest);
+
// Notify the renderer that the safe areas have changed.
void SetSafeArea(mojom::blink::DisplayCutoutSafeAreaPtr safe_area) override;
void Trace(Visitor*);
private:
- DisplayCutoutClientImpl(LocalFrame*,
- mojom::blink::DisplayCutoutClientAssociatedRequest);
-
Member<LocalFrame> frame_;
mojo::AssociatedBinding<mojom::blink::DisplayCutoutClient> binding_;
diff --git a/chromium/third_party/blink/renderer/core/frame/document_loading_rendering_test.cc b/chromium/third_party/blink/renderer/core/frame/document_loading_rendering_test.cc
index 1605bb438d1..632f5506bb2 100644
--- a/chromium/third_party/blink/renderer/core/frame/document_loading_rendering_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/document_loading_rendering_test.cc
@@ -29,18 +29,18 @@ TEST_F(DocumentLoadingRenderingTest,
// Still in the head, should not resume commits.
main_resource.Write("<!DOCTYPE html>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
main_resource.Write("<title>Test</title><style>div { color red; }</style>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Implicitly inserts the body. Since there's no loading stylesheets we
// should resume commits.
main_resource.Write("<p>Hello World</p>");
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
// Finish the load, should stay resumed.
main_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest,
@@ -54,24 +54,24 @@ TEST_F(DocumentLoadingRenderingTest,
// Still in the head, should not resume commits.
main_resource.Write("<!DOCTYPE html><link rel=stylesheet href=test.css>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet is streaming in, but not ready yet.
css_resource.Start();
css_resource.Write("a { color: red; }");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet finished, but no body yet, so don't resume.
css_resource.Finish();
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Body inserted and sheet is loaded so resume commits.
main_resource.Write("<body>");
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
// Finish the load, should stay resumed.
main_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest, ShouldResumeCommitsAfterSheetsLoaded) {
@@ -84,24 +84,24 @@ TEST_F(DocumentLoadingRenderingTest, ShouldResumeCommitsAfterSheetsLoaded) {
// Still in the head, should not resume commits.
main_resource.Write("<!DOCTYPE html><link rel=stylesheet href=test.css>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet is streaming in, but not ready yet.
css_resource.Start();
css_resource.Write("a { color: red; }");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Body inserted, but sheet is still loading so don't resume.
main_resource.Write("<body>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet finished and there's a body so resume.
css_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
// Finish the load, should stay resumed.
main_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest,
@@ -115,19 +115,19 @@ TEST_F(DocumentLoadingRenderingTest,
// Sheet loading and no documentElement, so don't resume.
main_resource.Write("<?xml-stylesheet type='text/css' href='test.css'?>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet finishes loading, but no documentElement yet so don't resume.
css_resource.Complete("a { color: red; }");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Root inserted so resume.
main_resource.Write("<svg xmlns='http://www.w3.org/2000/svg'></svg>");
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
// Finish the load, should stay resumed.
main_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest, ShouldResumeCommitsAfterSheetsLoadForXml) {
@@ -140,24 +140,24 @@ TEST_F(DocumentLoadingRenderingTest, ShouldResumeCommitsAfterSheetsLoadForXml) {
// Not done parsing.
main_resource.Write("<?xml-stylesheet type='text/css' href='test.css'?>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet is streaming in, but not ready yet.
css_resource.Start();
css_resource.Write("a { color: red; }");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Root inserted, but sheet is still loading so don't resume.
main_resource.Write("<svg xmlns='http://www.w3.org/2000/svg'></svg>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Finish the load, but sheets still loading so don't resume.
main_resource.Finish();
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Sheet finished, so resume commits.
css_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest, ShouldResumeCommitsAfterFinishParsingXml) {
@@ -169,7 +169,7 @@ TEST_F(DocumentLoadingRenderingTest, ShouldResumeCommitsAfterFinishParsingXml) {
// Finish parsing, no sheets loading so resume.
main_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest, ShouldResumeImmediatelyForImageDocuments) {
@@ -178,15 +178,15 @@ TEST_F(DocumentLoadingRenderingTest, ShouldResumeImmediatelyForImageDocuments) {
LoadURL("https://example.com/test.png");
main_resource.Start();
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
// Not really a valid image but enough for the test. ImageDocuments should
// resume painting as soon as the first bytes arrive.
main_resource.Write("image data");
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
main_resource.Finish();
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
}
TEST_F(DocumentLoadingRenderingTest, ShouldScheduleFrameAfterSheetsLoaded) {
@@ -201,7 +201,7 @@ TEST_F(DocumentLoadingRenderingTest, ShouldScheduleFrameAfterSheetsLoaded) {
// Load a stylesheet.
main_resource.Write(
"<!DOCTYPE html><link id=link rel=stylesheet href=first.css>");
- EXPECT_TRUE(Compositor().DeferCommits());
+ EXPECT_TRUE(Compositor().DeferMainFrameUpdate());
first_css_resource.Start();
first_css_resource.Write("body { color: red; }");
@@ -209,7 +209,7 @@ TEST_F(DocumentLoadingRenderingTest, ShouldScheduleFrameAfterSheetsLoaded) {
first_css_resource.Finish();
// Sheet finished and there's a body so resume.
- EXPECT_FALSE(Compositor().DeferCommits());
+ EXPECT_FALSE(Compositor().DeferMainFrameUpdate());
main_resource.Finish();
Compositor().BeginFrame();
@@ -217,7 +217,7 @@ TEST_F(DocumentLoadingRenderingTest, ShouldScheduleFrameAfterSheetsLoaded) {
// Replace the stylesheet by changing href.
auto* element = GetDocument().getElementById("link");
EXPECT_NE(nullptr, element);
- element->setAttribute(HTMLNames::hrefAttr, "second.css");
+ element->setAttribute(html_names::kHrefAttr, "second.css");
EXPECT_FALSE(Compositor().NeedsBeginFrame());
second_css_resource.Complete("body { color: red; }");
@@ -422,13 +422,11 @@ TEST_F(DocumentLoadingRenderingTest,
// Import loader isn't finish, shoudn't paint.
EXPECT_FALSE(GetDocument().IsRenderingReady());
- // If ignoringPendingStylesheets==true, element should get non-empty rect.
+ // Pending imports should not block layout
Element* element = GetDocument().getElementById("test");
DOMRect* rect = element->getBoundingClientRect();
EXPECT_TRUE(rect->width() > 0.f);
EXPECT_TRUE(rect->height() > 0.f);
-
- // After reset ignoringPendingStylesheets, we should block rendering again.
EXPECT_FALSE(GetDocument().IsRenderingReady());
import_resource.Write("div { color: red; }");
@@ -457,7 +455,7 @@ TEST_F(DocumentLoadingRenderingTest, StableSVGStopStylingWhileLoadingImport) {
// during import loading.
const auto recalc_and_check = [this]() {
GetDocument().SetNeedsStyleRecalc(
- kNeedsReattachStyleChange,
+ kSubtreeStyleChange,
StyleChangeReasonForTracing::Create("test reason"));
GetDocument().UpdateStyleAndLayout();
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_timer.cc b/chromium/third_party/blink/renderer/core/frame/dom_timer.cc
index 11a6310355c..92c91b49c45 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer.cc
@@ -69,7 +69,7 @@ void DOMTimer::RemoveByID(ExecutionContext* context, int timeout_id) {
DOMTimer* timer = context->Timers()->RemoveTimeoutByID(timeout_id);
TRACE_EVENT_INSTANT1("devtools.timeline", "TimerRemove",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorTimerRemoveEvent::Data(context, timeout_id));
+ inspector_timer_remove_event::Data(context, timeout_id));
// Eagerly unregister as ExecutionContext observer.
if (timer)
timer->ClearContext();
@@ -104,8 +104,8 @@ DOMTimer::DOMTimer(ExecutionContext* context,
PauseIfNeeded();
TRACE_EVENT_INSTANT1("devtools.timeline", "TimerInstall",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorTimerInstallEvent::Data(context, timeout_id,
- interval, single_shot));
+ inspector_timer_install_event::Data(
+ context, timeout_id, interval, single_shot));
probe::AsyncTaskScheduledBreakable(
context, single_shot ? "setTimeout" : "setInterval", this);
}
@@ -145,7 +145,7 @@ void DOMTimer::Fired() {
UserGestureIndicator gesture_indicator(std::move(user_gesture_token_));
TRACE_EVENT1("devtools.timeline", "TimerFire", "data",
- InspectorTimerFireEvent::Data(context, timeout_id_));
+ inspector_timer_fire_event::Data(context, timeout_id_));
const bool is_interval = !RepeatInterval().is_zero();
probe::UserCallback probe(context, is_interval ? "setInterval" : "setTimeout",
g_null_atom, true);
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_timer.h b/chromium/third_party/blink/renderer/core/frame/dom_timer.h
index bef454ca035..fee0571722f 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer.h
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer.h
@@ -51,6 +51,11 @@ class CORE_EXPORT DOMTimer final : public GarbageCollectedFinalized<DOMTimer>,
bool single_shot);
static void RemoveByID(ExecutionContext*, int timeout_id);
+ DOMTimer(ExecutionContext*,
+ ScheduledAction*,
+ TimeDelta interval,
+ bool single_shot,
+ int timeout_id);
~DOMTimer() override;
// PausableObject
@@ -73,14 +78,10 @@ class CORE_EXPORT DOMTimer final : public GarbageCollectedFinalized<DOMTimer>,
TimeDelta timeout,
bool single_shot,
int timeout_id) {
- return new DOMTimer(context, action, timeout, single_shot, timeout_id);
+ return MakeGarbageCollected<DOMTimer>(context, action, timeout, single_shot,
+ timeout_id);
}
- DOMTimer(ExecutionContext*,
- ScheduledAction*,
- TimeDelta interval,
- bool single_shot,
- int timeout_id);
void Fired() override;
scoped_refptr<base::SingleThreadTaskRunner> TimerTaskRunner() const override;
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_timer_test.cc b/chromium/third_party/blink/renderer/core/frame/dom_timer_test.cc
index 5398e2db5c5..bab66fcce61 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer_test.cc
@@ -10,12 +10,12 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
using testing::DoubleNear;
@@ -56,8 +56,8 @@ class DOMTimerTest : public RenderingTest {
return GetDocument()
.GetFrame()
->GetScriptController()
- .ExecuteScriptInMainWorldAndReturnValue(ScriptSourceCode(expr), KURL(),
- kOpaqueResource);
+ .ExecuteScriptInMainWorldAndReturnValue(
+ ScriptSourceCode(expr), KURL(), SanitizeScriptErrors::kSanitize);
}
Vector<double> ToDoubleArray(v8::Local<v8::Value> value,
@@ -75,7 +75,7 @@ class DOMTimerTest : public RenderingTest {
void ExecuteScriptAndWaitUntilIdle(const char* script_text) {
ScriptSourceCode script(script_text);
GetDocument().GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
- script, KURL(), kOpaqueResource);
+ script, KURL(), SanitizeScriptErrors::kSanitize);
platform_->RunUntilIdle();
}
};
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.cc b/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.cc
index f3ef4890793..f1fbd9ac07f 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.cc
@@ -49,7 +49,7 @@ void DOMVisualViewport::Trace(blink::Visitor* visitor) {
}
const AtomicString& DOMVisualViewport::InterfaceName() const {
- return EventTargetNames::DOMVisualViewport;
+ return event_target_names::kVisualViewport;
}
ExecutionContext* DOMVisualViewport::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.h b/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.h
index cfbf354303b..be5c2cb9e2a 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.h
+++ b/chromium/third_party/blink/renderer/core/frame/dom_visual_viewport.h
@@ -48,9 +48,10 @@ class CORE_EXPORT DOMVisualViewport final : public EventTargetWithInlineData {
public:
static DOMVisualViewport* Create(LocalDOMWindow* window) {
- return new DOMVisualViewport(window);
+ return MakeGarbageCollected<DOMVisualViewport>(window);
}
+ explicit DOMVisualViewport(LocalDOMWindow*);
~DOMVisualViewport() override;
void Trace(blink::Visitor*) override;
@@ -67,12 +68,10 @@ class CORE_EXPORT DOMVisualViewport final : public EventTargetWithInlineData {
double height() const;
double scale() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resize, kResize);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll, kScroll);
private:
- explicit DOMVisualViewport(LocalDOMWindow*);
-
Member<LocalDOMWindow> window_;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window.cc b/chromium/third_party/blink/renderer/core/frame/dom_window.cc
index ef899382e78..d19eb5424fa 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_window.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_window.cc
@@ -59,7 +59,7 @@ v8::Local<v8::Object> DOMWindow::AssociateWithWrapper(
}
const AtomicString& DOMWindow::InterfaceName() const {
- return EventTargetNames::DOMWindow;
+ return event_target_names::kWindow;
}
const DOMWindow* DOMWindow::ToDOMWindow() const {
@@ -120,16 +120,16 @@ void DOMWindow::postMessage(LocalDOMWindow* incumbent_window,
const String& target_origin,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- WindowPostMessageOptions options;
- options.setTargetOrigin(target_origin);
+ WindowPostMessageOptions* options = WindowPostMessageOptions::Create();
+ options->setTargetOrigin(target_origin);
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(incumbent_window, message, options, exception_state);
}
void DOMWindow::postMessage(LocalDOMWindow* incumbent_window,
const ScriptValue& message,
- const WindowPostMessageOptions& options,
+ const WindowPostMessageOptions* options,
ExceptionState& exception_state) {
UseCounter::Count(incumbent_window->GetFrame(),
WebFeature::kWindowPostMessage);
@@ -391,8 +391,10 @@ void DOMWindow::focus(LocalDOMWindow* incumbent_window) {
}
InputDeviceCapabilitiesConstants* DOMWindow::GetInputDeviceCapabilities() {
- if (!input_capabilities_)
- input_capabilities_ = new InputDeviceCapabilitiesConstants;
+ if (!input_capabilities_) {
+ input_capabilities_ =
+ MakeGarbageCollected<InputDeviceCapabilitiesConstants>();
+ }
return input_capabilities_;
}
@@ -402,14 +404,14 @@ void DOMWindow::PostMessageForTesting(
const String& target_origin,
LocalDOMWindow* source,
ExceptionState& exception_state) {
- WindowPostMessageOptions options;
- options.setTargetOrigin(target_origin);
+ WindowPostMessageOptions* options = WindowPostMessageOptions::Create();
+ options->setTargetOrigin(target_origin);
DoPostMessage(std::move(message), ports, options, source, exception_state);
}
void DOMWindow::DoPostMessage(scoped_refptr<SerializedScriptValue> message,
const MessagePortArray& ports,
- const WindowPostMessageOptions& options,
+ const WindowPostMessageOptions* options,
LocalDOMWindow* source,
ExceptionState& exception_state) {
if (!IsCurrentlyDisplayedInFrame())
@@ -417,7 +419,7 @@ void DOMWindow::DoPostMessage(scoped_refptr<SerializedScriptValue> message,
Document* source_document = source->document();
- const String& target_origin = options.targetOrigin();
+ const String& target_origin = options->targetOrigin();
// Compute the target origin. We need to do this synchronously in order
// to generate the SyntaxError exception correctly.
@@ -484,7 +486,7 @@ void DOMWindow::DoPostMessage(scoped_refptr<SerializedScriptValue> message,
WebFeature::kPostMessageOutgoingWouldBeBlockedByConnectSrc);
}
UserActivation* user_activation = nullptr;
- if (options.includeUserActivation())
+ if (options->includeUserActivation())
user_activation = UserActivation::CreateSnapshot(source);
MessageEvent* event =
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window.h b/chromium/third_party/blink/renderer/core/frame/dom_window.h
index 7583923a563..63e0a019542 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_window.h
+++ b/chromium/third_party/blink/renderer/core/frame/dom_window.h
@@ -8,7 +8,6 @@
#include "third_party/blink/renderer/bindings/core/v8/serialization/transferables.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
-#include "third_party/blink/renderer/core/frame/dom_window_base64.h"
#include "third_party/blink/renderer/core/frame/frame.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -28,8 +27,14 @@ class SerializedScriptValue;
class WindowPostMessageOptions;
class WindowProxyManager;
-class CORE_EXPORT DOMWindow : public EventTargetWithInlineData,
- public DOMWindowBase64 {
+// DOMWindow is an abstract class of Window interface implementations.
+// We have two derived implementation classes; LocalDOMWindow and
+// RemoteDOMWindow.
+//
+// TODO(tkent): Rename DOMWindow to Window. The class was named as 'DOMWindow'
+// because WebKit already had KJS::Window. We have no reasons to avoid
+// blink::Window now.
+class CORE_EXPORT DOMWindow : public EventTargetWithInlineData {
DEFINE_WRAPPERTYPEINFO();
public:
@@ -96,7 +101,7 @@ class CORE_EXPORT DOMWindow : public EventTargetWithInlineData,
void postMessage(LocalDOMWindow* incumbent_window,
const ScriptValue& message,
- const WindowPostMessageOptions& options,
+ const WindowPostMessageOptions* options,
ExceptionState&);
// Indexed properties
@@ -137,7 +142,7 @@ class CORE_EXPORT DOMWindow : public EventTargetWithInlineData,
private:
void DoPostMessage(scoped_refptr<SerializedScriptValue> message,
const MessagePortArray&,
- const WindowPostMessageOptions& options,
+ const WindowPostMessageOptions* options,
LocalDOMWindow* source,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window_base64.cc b/chromium/third_party/blink/renderer/core/frame/dom_window_base64.cc
deleted file mode 100644
index 67a51dded68..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/dom_window_base64.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/core/frame/dom_window_base64.h"
-
-#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/wtf/text/base64.h"
-
-namespace blink {
-
-String DOMWindowBase64::btoa(const String& string_to_encode,
- ExceptionState& exception_state) {
- if (string_to_encode.IsNull())
- return String();
-
- if (!string_to_encode.ContainsOnlyLatin1()) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kInvalidCharacterError,
- "The string to be encoded contains "
- "characters outside of the Latin1 range.");
- return String();
- }
-
- return Base64Encode(string_to_encode.Latin1());
-}
-
-String DOMWindowBase64::atob(const String& encoded_string,
- ExceptionState& exception_state) {
- if (encoded_string.IsNull())
- return String();
-
- if (!encoded_string.ContainsOnlyLatin1()) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kInvalidCharacterError,
- "The string to be decoded contains "
- "characters outside of the Latin1 range.");
- return String();
- }
- Vector<char> out;
- if (!Base64Decode(encoded_string, out, IsHTMLSpace<UChar>,
- kBase64ValidatePadding)) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kInvalidCharacterError,
- "The string to be decoded is not correctly encoded.");
- return String();
- }
-
- return String(out.data(), out.size());
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window_base64.h b/chromium/third_party/blink/renderer/core/frame/dom_window_base64.h
deleted file mode 100644
index 24029e56227..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/dom_window_base64.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_BASE64_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_BASE64_H_
-
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-
-class ExceptionState;
-
-class DOMWindowBase64 {
- public:
- String btoa(const String& string_to_encode, ExceptionState&);
- String atob(const String& encoded_string, ExceptionState&);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_BASE64_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window_timers.h b/chromium/third_party/blink/renderer/core/frame/dom_window_timers.h
deleted file mode 100644
index b4e91ab22d8..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/dom_window_timers.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_TIMERS_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_TIMERS_H_
-
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
-
-namespace blink {
-
-class EventTarget;
-class ExceptionState;
-class ScriptState;
-class ScriptValue;
-class StringOrTrustedScript;
-
-namespace DOMWindowTimers {
-int setTimeout(ScriptState*,
- EventTarget&,
- const ScriptValue& handler,
- int timeout,
- const Vector<ScriptValue>& arguments);
-int setTimeout(ScriptState*,
- EventTarget&,
- const StringOrTrustedScript&,
- int timeout,
- const Vector<ScriptValue>&,
- ExceptionState&);
-int setTimeoutFromString(ScriptState*,
- EventTarget&,
- const String& handler,
- int timeout,
- const Vector<ScriptValue>&);
-int setInterval(ScriptState*,
- EventTarget&,
- const ScriptValue& handler,
- int timeout,
- const Vector<ScriptValue>&);
-int setInterval(ScriptState*,
- EventTarget&,
- const StringOrTrustedScript&,
- int timeout,
- const Vector<ScriptValue>&,
- ExceptionState&);
-int setIntervalFromString(ScriptState*,
- EventTarget&,
- const String& handler,
- int timeout,
- const Vector<ScriptValue>&);
-void clearTimeout(EventTarget&, int timeout_id);
-void clearInterval(EventTarget&, int timeout_id);
-}
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_TIMERS_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/event_handler_registry.cc b/chromium/third_party/blink/renderer/core/frame/event_handler_registry.cc
index cb6cfcb9c72..e9035652d37 100644
--- a/chromium/third_party/blink/renderer/core/frame/event_handler_registry.cc
+++ b/chromium/third_party/blink/renderer/core/frame/event_handler_registry.cc
@@ -54,34 +54,34 @@ EventHandlerRegistry::~EventHandlerRegistry() {
bool EventHandlerRegistry::EventTypeToClass(
const AtomicString& event_type,
- const AddEventListenerOptions& options,
+ const AddEventListenerOptions* options,
EventHandlerClass* result) {
- if (event_type == EventTypeNames::scroll) {
+ if (event_type == event_type_names::kScroll) {
*result = kScrollEvent;
- } else if (event_type == EventTypeNames::wheel ||
- event_type == EventTypeNames::mousewheel) {
- *result = options.passive() ? kWheelEventPassive : kWheelEventBlocking;
- } else if (event_type == EventTypeNames::touchend ||
- event_type == EventTypeNames::touchcancel) {
- *result = options.passive() ? kTouchEndOrCancelEventPassive
- : kTouchEndOrCancelEventBlocking;
- } else if (event_type == EventTypeNames::touchstart ||
- event_type == EventTypeNames::touchmove) {
- *result = options.passive() ? kTouchStartOrMoveEventPassive
- : kTouchStartOrMoveEventBlocking;
- } else if (event_type == EventTypeNames::pointerrawmove) {
+ } else if (event_type == event_type_names::kWheel ||
+ event_type == event_type_names::kMousewheel) {
+ *result = options->passive() ? kWheelEventPassive : kWheelEventBlocking;
+ } else if (event_type == event_type_names::kTouchend ||
+ event_type == event_type_names::kTouchcancel) {
+ *result = options->passive() ? kTouchEndOrCancelEventPassive
+ : kTouchEndOrCancelEventBlocking;
+ } else if (event_type == event_type_names::kTouchstart ||
+ event_type == event_type_names::kTouchmove) {
+ *result = options->passive() ? kTouchStartOrMoveEventPassive
+ : kTouchStartOrMoveEventBlocking;
+ } else if (event_type == event_type_names::kPointerrawmove) {
// This will be used to avoid waking up the main thread to
// process pointerrawmove events and hit-test them when
// there is no listener on the page.
*result = kPointerRawMoveEvent;
- } else if (EventUtil::IsPointerEventType(event_type)) {
+ } else if (event_util::IsPointerEventType(event_type)) {
// The pointer events never block scrolling and the compositor
// only needs to know about the touch listeners.
*result = kPointerEvent;
#if DCHECK_IS_ON()
- } else if (event_type == EventTypeNames::load ||
- event_type == EventTypeNames::mousemove ||
- event_type == EventTypeNames::touchstart) {
+ } else if (event_type == event_type_names::kLoad ||
+ event_type == event_type_names::kMousemove ||
+ event_type == event_type_names::kTouchstart) {
*result = kEventsForTesting;
#endif
} else {
@@ -156,7 +156,7 @@ bool EventHandlerRegistry::UpdateEventHandlerInternal(
void EventHandlerRegistry::UpdateEventHandlerOfType(
ChangeOperation op,
const AtomicString& event_type,
- const AddEventListenerOptions& options,
+ const AddEventListenerOptions* options,
EventTarget* target) {
EventHandlerClass handler_class;
if (!EventTypeToClass(event_type, options, &handler_class))
@@ -167,14 +167,14 @@ void EventHandlerRegistry::UpdateEventHandlerOfType(
void EventHandlerRegistry::DidAddEventHandler(
EventTarget& target,
const AtomicString& event_type,
- const AddEventListenerOptions& options) {
+ const AddEventListenerOptions* options) {
UpdateEventHandlerOfType(kAdd, event_type, options, &target);
}
void EventHandlerRegistry::DidRemoveEventHandler(
EventTarget& target,
const AtomicString& event_type,
- const AddEventListenerOptions& options) {
+ const AddEventListenerOptions* options) {
UpdateEventHandlerOfType(kRemove, event_type, options, &target);
}
diff --git a/chromium/third_party/blink/renderer/core/frame/event_handler_registry.h b/chromium/third_party/blink/renderer/core/frame/event_handler_registry.h
index d841a519fc9..92df7a3036e 100644
--- a/chromium/third_party/blink/renderer/core/frame/event_handler_registry.h
+++ b/chromium/third_party/blink/renderer/core/frame/event_handler_registry.h
@@ -60,11 +60,11 @@ class CORE_EXPORT EventHandlerRegistry final
// Registration and management of event handlers attached to EventTargets.
void DidAddEventHandler(EventTarget&,
const AtomicString& event_type,
- const AddEventListenerOptions&);
+ const AddEventListenerOptions*);
void DidAddEventHandler(EventTarget&, EventHandlerClass);
void DidRemoveEventHandler(EventTarget&,
const AtomicString& event_type,
- const AddEventListenerOptions&);
+ const AddEventListenerOptions*);
void DidRemoveEventHandler(EventTarget&, EventHandlerClass);
void DidRemoveAllEventHandlers(EventTarget&);
@@ -90,7 +90,7 @@ class CORE_EXPORT EventHandlerRegistry final
// Returns true if |eventType| belongs to a class this registry tracks.
static bool EventTypeToClass(const AtomicString& event_type,
- const AddEventListenerOptions&,
+ const AddEventListenerOptions*,
EventHandlerClass* result);
// Returns true if the operation actually added a new target or completely
@@ -116,7 +116,7 @@ class CORE_EXPORT EventHandlerRegistry final
// parent registry and other clients accordingly.
void UpdateEventHandlerOfType(ChangeOperation,
const AtomicString& event_type,
- const AddEventListenerOptions&,
+ const AddEventListenerOptions*,
EventTarget*);
bool UpdateEventHandlerInternal(ChangeOperation,
diff --git a/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.h b/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.h
index b0a54f2e167..d7b1b7665b9 100644
--- a/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.h
+++ b/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.h
@@ -14,17 +14,22 @@ class CORE_EXPORT FeaturePolicyViolationReportBody : public MessageReportBody {
DEFINE_WRAPPERTYPEINFO();
public:
- FeaturePolicyViolationReportBody(const String& feature,
+ FeaturePolicyViolationReportBody(const String& feature_id,
const String& message,
+ const String& disposition,
std::unique_ptr<SourceLocation> location)
- : MessageReportBody(message, std::move(location)), feature_(feature) {}
+ : MessageReportBody(message, std::move(location)),
+ feature_id_(feature_id),
+ disposition_(disposition) {}
- String feature() const { return feature_; }
+ String featureId() const { return feature_id_; }
+ String disposition() const { return disposition_; }
~FeaturePolicyViolationReportBody() override = default;
private:
- const String feature_;
+ const String feature_id_;
+ const String disposition_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.idl b/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.idl
index 16cd1a019ca..b5184ead4c9 100644
--- a/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.idl
+++ b/chromium/third_party/blink/renderer/core/frame/feature_policy_violation_report_body.idl
@@ -2,15 +2,15 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://github.com/WICG/reporting/blob/master/EXPLAINER.md#reportingobserver---observing-reports-from-javascript
+// https://wicg.github.io/feature-policy/#reporting
[
- NoInterfaceObject,
- RuntimeEnabled=ReportingObserver
+ NoInterfaceObject
] interface FeaturePolicyViolationReportBody : ReportBody {
- readonly attribute DOMString feature;
- readonly attribute DOMString message;
+ readonly attribute DOMString featureId;
readonly attribute DOMString? sourceFile;
readonly attribute unsigned long? lineNumber;
readonly attribute unsigned long? columnNumber;
+ readonly attribute DOMString disposition;
+ readonly attribute DOMString? message;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/find_in_page.cc b/chromium/third_party/blink/renderer/core/frame/find_in_page.cc
index 59db2913c72..cbebae1ff99 100644
--- a/chromium/third_party/blink/renderer/core/frame/find_in_page.cc
+++ b/chromium/third_party/blink/renderer/core/frame/find_in_page.cc
@@ -307,7 +307,8 @@ WebPlugin* FindInPage::GetWebPluginForFind() {
void FindInPage::BindToRequest(
mojom::blink::FindInPageAssociatedRequest request) {
- binding_.Bind(std::move(request));
+ binding_.Bind(std::move(request),
+ frame_->GetTaskRunner(blink::TaskType::kInternalDefault));
}
void FindInPage::Dispose() {
diff --git a/chromium/third_party/blink/renderer/core/frame/find_in_page.h b/chromium/third_party/blink/renderer/core/frame/find_in_page.h
index 6bdc6922a29..ba979ce75e7 100644
--- a/chromium/third_party/blink/renderer/core/frame/find_in_page.h
+++ b/chromium/third_party/blink/renderer/core/frame/find_in_page.h
@@ -30,9 +30,11 @@ class CORE_EXPORT FindInPage final
public:
static FindInPage* Create(WebLocalFrameImpl& frame,
InterfaceRegistry* interface_registry) {
- return new FindInPage(frame, interface_registry);
+ return MakeGarbageCollected<FindInPage>(frame, interface_registry);
}
+ FindInPage(WebLocalFrameImpl& frame, InterfaceRegistry* interface_registry);
+
bool FindInternal(int identifier,
const WebString& search_text,
const mojom::blink::FindOptions&,
@@ -101,8 +103,6 @@ class CORE_EXPORT FindInPage final
}
private:
- FindInPage(WebLocalFrameImpl& frame, InterfaceRegistry* interface_registry);
-
// Will be initialized after first call to ensureTextFinder().
Member<TextFinder> text_finder_;
diff --git a/chromium/third_party/blink/renderer/core/frame/find_in_page_test.cc b/chromium/third_party/blink/renderer/core/frame/find_in_page_test.cc
index 1c945bb1c55..49188a6bfd1 100644
--- a/chromium/third_party/blink/renderer/core/frame/find_in_page_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/find_in_page_test.cc
@@ -32,7 +32,7 @@ class FindInPageTest : public testing::Test {
TextFinder& GetTextFinder() const;
private:
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
Persistent<Document> document_;
Persistent<FindInPage> find_in_page_;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/frame.cc b/chromium/third_party/blink/renderer/core/frame/frame.cc
index 19ae96f3806..ec10f62c150 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame.cc
@@ -56,8 +56,6 @@
namespace blink {
-using namespace HTMLNames;
-
Frame::~Frame() {
InstanceCounters::DecrementCounter(InstanceCounters::kFrameCounter);
DCHECK(!owner_);
@@ -71,6 +69,7 @@ void Frame::Trace(blink::Visitor* visitor) {
visitor->Trace(window_proxy_manager_);
visitor->Trace(dom_window_);
visitor->Trace(client_);
+ visitor->Trace(navigation_rate_limiter_);
}
void Frame::Detach(FrameDetachType type) {
@@ -80,6 +79,10 @@ void Frame::Detach(FrameDetachType type) {
lifecycle_.AdvanceTo(FrameLifecycle::kDetaching);
DetachImpl(type);
+
+ if (GetPage())
+ GetPage()->GetFocusController().FrameDetached(this);
+
// Due to re-entrancy, |this| could have completed detaching already.
// TODO(dcheng): This DCHECK is not always true. See https://crbug.com/838348.
DCHECK(IsDetached() == !client_);
@@ -185,6 +188,22 @@ void Frame::DidChangeVisibilityState() {
void Frame::NotifyUserActivationInLocalTree() {
for (Frame* node = this; node; node = node->Tree().Parent())
node->user_activation_state_.Activate();
+
+ // See FrameTreeNode::NotifyUserActivation() for details about this block.
+ if (IsLocalFrame() && RuntimeEnabledFeatures::UserActivationV2Enabled() &&
+ RuntimeEnabledFeatures::UserActivationSameOriginVisibilityEnabled()) {
+ const SecurityOrigin* security_origin =
+ ToLocalFrame(this)->GetSecurityContext()->GetSecurityOrigin();
+
+ Frame& root = Tree().Top();
+ for (Frame* node = &root; node; node = node->Tree().TraverseNext(&root)) {
+ if (node->IsLocalFrame() &&
+ security_origin->CanAccess(
+ ToLocalFrame(node)->GetSecurityContext()->GetSecurityOrigin())) {
+ node->user_activation_state_.Activate();
+ }
+ }
+ }
}
bool Frame::ConsumeTransientUserActivationInLocalTree() {
@@ -200,15 +219,9 @@ bool Frame::ConsumeTransientUserActivationInLocalTree() {
return was_active;
}
-bool Frame::DeprecatedIsFeatureEnabled(
- mojom::FeaturePolicyFeature feature) const {
- return GetSecurityContext()->IsFeatureEnabled(feature,
- ReportOptions::kDoNotReport);
-}
-
-bool Frame::DeprecatedIsFeatureEnabled(mojom::FeaturePolicyFeature feature,
- ReportOptions report_on_failure) const {
- return GetSecurityContext()->IsFeatureEnabled(feature, report_on_failure);
+void Frame::ClearUserActivationInLocalTree() {
+ for (Frame* node = this; node; node = node->Tree().TraverseNext(this))
+ node->user_activation_state_.Clear();
}
void Frame::SetOwner(FrameOwner* owner) {
@@ -251,6 +264,7 @@ Frame::Frame(FrameClient* client,
owner_(owner),
client_(client),
window_proxy_manager_(window_proxy_manager),
+ navigation_rate_limiter_(*this),
is_loading_(false),
devtools_frame_token_(client->GetDevToolsFrameToken()),
create_stack_(base::debug::StackTrace()) {
diff --git a/chromium/third_party/blink/renderer/core/frame/frame.h b/chromium/third_party/blink/renderer/core/frame/frame.h
index 5845feb6328..d6b924b7f83 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame.h
@@ -32,7 +32,6 @@
#include "base/debug/stack_trace.h"
#include "base/optional.h"
#include "base/unguessable_token.h"
-#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/common/frame/user_activation_state.h"
#include "third_party/blink/public/common/frame/user_activation_update_source.h"
#include "third_party/blink/public/web/web_frame_load_type.h"
@@ -40,6 +39,7 @@
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/frame/frame_lifecycle.h"
#include "third_party/blink/renderer/core/frame/frame_view.h"
+#include "third_party/blink/renderer/core/frame/navigation_rate_limiter.h"
#include "third_party/blink/renderer/core/loader/frame_loader_types.h"
#include "third_party/blink/renderer/core/page/frame_tree.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
@@ -56,15 +56,14 @@ class Document;
class FrameClient;
class FrameOwner;
class HTMLFrameOwnerElement;
+class KURL;
class LayoutEmbeddedContent;
class LocalFrame;
-class KURL;
class Page;
class SecurityContext;
class Settings;
class WindowProxy;
class WindowProxyManager;
-enum class ReportOptions;
struct FrameLoadRequest;
enum class FrameDetachType { kRemove, kSwap };
@@ -72,7 +71,6 @@ enum class FrameDetachType { kRemove, kSwap };
// Status of user gesture.
enum class UserGestureStatus { kActive, kNone };
-
// Frame is the base class of LocalFrame and RemoteFrame and should only contain
// functionality shared between both. In particular, any method related to
// input, layout, or painting probably belongs on LocalFrame.
@@ -171,6 +169,9 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
// This should never be called from outside Frame or WebFrame.
bool ConsumeTransientUserActivationInLocalTree();
+ // This should never be called from outside Frame or WebFrame.
+ void ClearUserActivationInLocalTree();
+
bool HasBeenActivated() const {
return user_activation_state_.HasBeenActive();
}
@@ -189,17 +190,6 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
return lifecycle_.GetState() == FrameLifecycle::kAttached;
}
- // Tests whether the policy-controlled feature is enabled in this frame.
- // Optionally sends a report to any registered reporting observers or
- // Report-To endpoints, via ReportFeaturePolicyViolation(), if the feature is
- // disabled.
- // TODO(iclelland): Replace these with methods on SecurityContext/Document
- bool DeprecatedIsFeatureEnabled(mojom::FeaturePolicyFeature) const;
- bool DeprecatedIsFeatureEnabled(mojom::FeaturePolicyFeature,
- ReportOptions report_on_failure) const;
- virtual void DeprecatedReportFeaturePolicyViolation(
- mojom::FeaturePolicyFeature) const {}
-
// Called to make a frame inert or non-inert. A frame is inert when there
// is a modal dialog displayed within an ancestor frame, and this frame
// itself is not within the dialog.
@@ -231,6 +221,10 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
return detach_stack_;
}
+ NavigationRateLimiter& navigation_rate_limiter() {
+ return navigation_rate_limiter_;
+ }
+
protected:
Frame(FrameClient*, Page&, FrameOwner*, WindowProxyManager*);
@@ -267,6 +261,9 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
Member<FrameClient> client_;
const Member<WindowProxyManager> window_proxy_manager_;
FrameLifecycle lifecycle_;
+
+ NavigationRateLimiter navigation_rate_limiter_;
+
// TODO(sashab): Investigate if this can be represented with m_lifecycle.
bool is_loading_;
base::UnguessableToken devtools_frame_token_;
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_console.h b/chromium/third_party/blink/renderer/core/frame/frame_console.h
index 96d9e573ae1..d8061d221da 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_console.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_console.h
@@ -52,9 +52,11 @@ class CORE_EXPORT FrameConsole final
: public GarbageCollectedFinalized<FrameConsole> {
public:
static FrameConsole* Create(LocalFrame& frame) {
- return new FrameConsole(frame);
+ return MakeGarbageCollected<FrameConsole>(frame);
}
+ explicit FrameConsole(LocalFrame&);
+
void AddMessage(ConsoleMessage*);
bool AddMessageToStorage(ConsoleMessage*);
@@ -74,8 +76,6 @@ class CORE_EXPORT FrameConsole final
void Trace(blink::Visitor*);
private:
- explicit FrameConsole(LocalFrame&);
-
Member<LocalFrame> frame_;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_owner.h b/chromium/third_party/blink/renderer/core/frame/frame_owner.h
index 313350e7a27..2c5244703b8 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_owner.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_owner.h
@@ -27,7 +27,7 @@ class CORE_EXPORT FrameOwner : public GarbageCollectedMixin {
virtual bool IsLocal() const = 0;
virtual bool IsRemote() const = 0;
- virtual bool IsPlugin() { return false; }
+ virtual bool IsPlugin() const { return false; }
virtual Frame* ContentFrame() const = 0;
virtual void SetContentFrame(Frame&) = 0;
@@ -43,7 +43,14 @@ class CORE_EXPORT FrameOwner : public GarbageCollectedMixin {
// On load failure, a frame can ask its owner to render fallback content
// which replaces the frame contents.
virtual bool CanRenderFallbackContent() const = 0;
- virtual void RenderFallbackContent() = 0;
+
+ // The argument refers to the frame with the failed navigation. Note that this
+ // is not always the ContentFrame() for this owner; this argument is needed to
+ // support showing fallback using DOM of parent frame in a separate process.
+ // The use case is limited to RemoteFrameOwner when the corresponding local
+ // FrameOwner in parent process is an <object>. In such cases the frame with
+ // failed navigation could be provisional (cross-site navigations).
+ virtual void RenderFallbackContent(Frame*) = 0;
// The intrinsic dimensions of the embedded object changed. This is only
// relevant for SVG documents that are embedded via <object> or <embed>.
@@ -75,7 +82,9 @@ class CORE_EXPORT DummyFrameOwner final
USING_GARBAGE_COLLECTED_MIXIN(DummyFrameOwner);
public:
- static DummyFrameOwner* Create() { return new DummyFrameOwner; }
+ static DummyFrameOwner* Create() {
+ return MakeGarbageCollected<DummyFrameOwner>();
+ }
void Trace(blink::Visitor* visitor) override { FrameOwner::Trace(visitor); }
@@ -87,7 +96,7 @@ class CORE_EXPORT DummyFrameOwner final
void AddResourceTiming(const ResourceTimingInfo&) override {}
void DispatchLoad() override {}
bool CanRenderFallbackContent() const override { return false; }
- void RenderFallbackContent() override {}
+ void RenderFallbackContent(Frame*) override {}
void IntrinsicSizingInfoChanged() override {}
AtomicString BrowsingContextContainerName() const override {
return AtomicString();
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_serializer.cc b/chromium/third_party/blink/renderer/core/frame/frame_serializer.cc
index 89fe3b26025..02eaf6cc202 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_serializer.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_serializer.cc
@@ -197,7 +197,7 @@ void SerializerMarkupAccumulator::AppendAttribute(StringBuilder& out,
// Check if link rewriting can affect the attribute.
bool is_link_attribute = element.HasLegalLinkAttribute(attribute.GetName());
bool is_src_doc_attribute = IsHTMLFrameElementBase(element) &&
- attribute.GetName() == HTMLNames::srcdocAttr;
+ attribute.GetName() == html_names::kSrcdocAttr;
if (is_link_attribute || is_src_doc_attribute) {
// Check if the delegate wants to do link rewriting for the element.
String new_link_for_the_element;
@@ -212,7 +212,7 @@ void SerializerMarkupAccumulator::AppendAttribute(StringBuilder& out,
// serialized subframe to use html contents from the link provided by
// Delegate::rewriteLink rather than html contents from srcdoc
// attribute.
- AppendRewrittenAttribute(out, element, HTMLNames::srcAttr.LocalName(),
+ AppendRewrittenAttribute(out, element, html_names::kSrcAttr.LocalName(),
new_link_for_the_element);
}
return;
@@ -329,11 +329,12 @@ void FrameSerializer::SerializeFrame(const LocalFrame& frame) {
}
if (auto* image = ToHTMLImageElementOrNull(element)) {
- KURL url = document.CompleteURL(image->getAttribute(HTMLNames::srcAttr));
+ KURL url =
+ document.CompleteURL(image->getAttribute(html_names::kSrcAttr));
ImageResourceContent* cached_image = image->CachedImage();
AddImageToResources(cached_image, url);
} else if (auto* input = ToHTMLInputElementOrNull(element)) {
- if (input->type() == InputTypeNames::image && input->ImageLoader()) {
+ if (input->type() == input_type_names::kImage && input->ImageLoader()) {
KURL url = input->Src();
ImageResourceContent* cached_image = input->ImageLoader()->GetContent();
AddImageToResources(cached_image, url);
@@ -341,7 +342,7 @@ void FrameSerializer::SerializeFrame(const LocalFrame& frame) {
} else if (auto* link = ToHTMLLinkElementOrNull(element)) {
if (CSSStyleSheet* sheet = link->sheet()) {
KURL url =
- document.CompleteURL(link->getAttribute(HTMLNames::hrefAttr));
+ document.CompleteURL(link->getAttribute(html_names::kHrefAttr));
SerializeCSSStyleSheet(*sheet, url);
}
} else if (auto* style = ToHTMLStyleElementOrNull(element)) {
@@ -491,6 +492,7 @@ void FrameSerializer::SerializeCSSRule(CSSRule* rule) {
case CSSRule::kKeyframeRule:
case CSSRule::kNamespaceRule:
case CSSRule::kViewportRule:
+ case CSSRule::kFontFeatureValuesRule:
break;
}
}
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_serializer_test.cc b/chromium/third_party/blink/renderer/core/frame/frame_serializer_test.cc
index dda8d921f0f..c17c0a7ca05 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_serializer_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_serializer_test.cc
@@ -61,7 +61,7 @@ class FrameSerializerTest : public testing::Test,
public:
FrameSerializerTest()
: folder_("frameserializer/"),
- base_url_(URLTestHelpers::ToKURL("http://www.test.com")) {}
+ base_url_(url_test_helpers::ToKURL("http://www.test.com")) {}
protected:
void SetUp() override {
@@ -79,7 +79,7 @@ class FrameSerializerTest : public testing::Test,
void SetRewriteURLFolder(const char* folder) { rewrite_folder_ = folder; }
void RegisterURL(const KURL& url, const char* file, const char* mime_type) {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
url, test::CoreTestDataPath(WebString::FromUTF8(folder_ + file)),
WebString::FromUTF8(mime_type));
}
@@ -112,8 +112,9 @@ class FrameSerializerTest : public testing::Test,
}
void Serialize(const char* url) {
- FrameTestHelpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
- KURL(base_url_, url).GetString().Utf8().data());
+ frame_test_helpers::LoadFrame(
+ helper_.GetWebView()->MainFrameImpl(),
+ KURL(base_url_, url).GetString().Utf8().data());
FrameSerializer serializer(resources_, *this);
Frame* frame = helper_.LocalMainFrame()->GetFrame();
for (; frame; frame = frame->Tree().TraverseNext()) {
@@ -187,7 +188,7 @@ class FrameSerializerTest : public testing::Test,
return skip_urls_.Contains(url);
}
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
std::string folder_;
KURL base_url_;
Deque<SerializedResource> resources_;
@@ -355,7 +356,7 @@ TEST_F(FrameSerializerTest, CSS) {
RegisterURL("ol-dot.png", "image.png", "image/png");
const KURL image_url_from_data_url(
- URLTestHelpers::ToKURL("http://www.dataurl.com"),
+ url_test_helpers::ToKURL("http://www.dataurl.com"),
"fuchsia_background.png");
RegisterURL(image_url_from_data_url, "image.png", "image/png");
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.cc b/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.cc
index db8201b2372..27c7728d6af 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.cc
@@ -58,7 +58,7 @@
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
-namespace FrameTestHelpers {
+namespace frame_test_helpers {
namespace {
@@ -113,11 +113,12 @@ std::unique_ptr<WebNavigationParams> BuildDummyNavigationParams() {
} // namespace
void LoadFrame(WebLocalFrame* frame, const std::string& url) {
- WebURL web_url(URLTestHelpers::ToKURL(url));
+ WebLocalFrameImpl* impl = ToWebLocalFrameImpl(frame);
+ WebURL web_url(url_test_helpers::ToKURL(url));
if (web_url.ProtocolIs("javascript")) {
- frame->LoadJavaScriptURL(web_url);
+ impl->LoadJavaScriptURL(web_url);
} else {
- frame->CommitNavigation(
+ impl->CommitNavigation(
WebURLRequest(web_url), blink::WebFrameLoadType::kStandard,
blink::WebHistoryItem(), false, base::UnguessableToken::Create(),
BuildDummyNavigationParams(), nullptr /* extra_data */);
@@ -128,15 +129,17 @@ void LoadFrame(WebLocalFrame* frame, const std::string& url) {
void LoadHTMLString(WebLocalFrame* frame,
const std::string& html,
const WebURL& base_url) {
- frame->LoadHTMLString(WebData(html.data(), html.size()), base_url);
+ WebLocalFrameImpl* impl = ToWebLocalFrameImpl(frame);
+ impl->LoadHTMLString(WebData(html.data(), html.size()), base_url, WebURL());
PumpPendingRequestsForFrameToLoad(frame);
}
void LoadHistoryItem(WebLocalFrame* frame,
const WebHistoryItem& item,
mojom::FetchCacheMode cache_mode) {
+ WebLocalFrameImpl* impl = ToWebLocalFrameImpl(frame);
HistoryItem* history_item = item;
- frame->CommitNavigation(
+ impl->CommitNavigation(
WrappedResourceRequest(history_item->GenerateResourceRequest(cache_mode)),
WebFrameLoadType::kBackForward, item, false /* is_client_redirect */,
base::UnguessableToken::Create(), BuildDummyNavigationParams(),
@@ -246,7 +249,8 @@ WebLocalFrameImpl* CreateLocalChild(WebRemoteFrame& parent,
client = CreateDefaultClientIfNeeded(client, owned_client);
WebLocalFrameImpl* frame = ToWebLocalFrameImpl(parent.CreateLocalChild(
WebTreeScopeType::kDocument, name, WebSandboxFlags::kNone, client,
- nullptr, previous_sibling, ParsedFeaturePolicy(), properties, nullptr));
+ nullptr, previous_sibling, ParsedFeaturePolicy(), properties,
+ FrameOwnerElementType::kIframe, nullptr));
client->Bind(frame, std::move(owned_client));
std::unique_ptr<TestWebWidgetClient> owned_widget_client;
@@ -273,7 +277,7 @@ WebRemoteFrameImpl* CreateRemoteChild(
client = CreateDefaultClientIfNeeded(client, owned_client);
auto* frame = ToWebRemoteFrameImpl(parent.CreateRemoteChild(
WebTreeScopeType::kDocument, name, WebSandboxFlags::kNone,
- ParsedFeaturePolicy(), client, nullptr));
+ ParsedFeaturePolicy(), FrameOwnerElementType::kIframe, client, nullptr));
client->Bind(frame, std::move(owned_client));
if (!security_origin)
security_origin = SecurityOrigin::CreateUniqueOpaque();
@@ -428,7 +432,7 @@ void TestWebFrameClient::Bind(WebLocalFrame* frame,
std::unique_ptr<TestWebFrameClient> self_owned) {
DCHECK(!frame_);
DCHECK(!self_owned || self_owned.get() == this);
- frame_ = frame;
+ frame_ = ToWebLocalFrameImpl(frame);
self_owned_ = std::move(self_owned);
}
@@ -456,7 +460,8 @@ WebLocalFrame* TestWebFrameClient::CreateChildFrame(
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties& frame_owner_properties) {
+ const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType owner_type) {
return CreateLocalChild(*parent, scope);
}
@@ -469,6 +474,14 @@ void TestWebFrameClient::DidStopLoading() {
--loads_in_progress_;
}
+void TestWebFrameClient::BeginNavigation(
+ std::unique_ptr<WebNavigationInfo> info) {
+ frame_->CommitNavigation(
+ info->url_request, info->frame_load_type, blink::WebHistoryItem(),
+ info->is_client_redirect, base::UnguessableToken::Create(),
+ nullptr /* navigation_params */, nullptr /* extra_data */);
+}
+
void TestWebFrameClient::DidCreateDocumentLoader(
WebDocumentLoader* document_loader) {
}
@@ -512,9 +525,9 @@ content::LayerTreeView* LayerTreeViewFactory::Initialize(
layer_tree_view_ = std::make_unique<content::LayerTreeView>(
specified_delegate ? specified_delegate : &delegate_,
- Platform::Current()->CurrentThread()->GetTaskRunner(),
+ Thread::Current()->GetTaskRunner(),
/*compositor_thread=*/nullptr, &test_task_graph_runner_,
- &fake_renderer_scheduler_);
+ &fake_thread_scheduler_);
layer_tree_view_->Initialize(settings,
std::make_unique<cc::TestUkmRecorderFactory>());
return layer_tree_view_.get();
@@ -528,5 +541,5 @@ TestWebViewClient::TestWebViewClient(content::LayerTreeViewDelegate* delegate) {
layer_tree_view_ = layer_tree_view_factory_.Initialize(delegate);
}
-} // namespace FrameTestHelpers
+} // namespace frame_test_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.h b/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.h
index fe7b16c7f1e..ccfbc3273ca 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_test_helpers.h
@@ -41,9 +41,10 @@
#include "content/renderer/gpu/layer_tree_view.h"
#include "content/test/stub_layer_tree_view_delegate.h"
#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/web_fake_thread_scheduler.h"
#include "third_party/blink/public/platform/web_mouse_event.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url_request.h"
@@ -86,7 +87,7 @@ class WebLocalFrameImpl;
class WebRemoteFrameImpl;
class WebSettings;
-namespace FrameTestHelpers {
+namespace frame_test_helpers {
class TestWebFrameClient;
class TestWebRemoteFrameClient;
@@ -174,7 +175,7 @@ class LayerTreeViewFactory {
private:
content::StubLayerTreeViewDelegate delegate_;
cc::TestTaskGraphRunner test_task_graph_runner_;
- blink::scheduler::FakeRendererScheduler fake_renderer_scheduler_;
+ blink::scheduler::WebFakeThreadScheduler fake_thread_scheduler_;
std::unique_ptr<content::LayerTreeView> layer_tree_view_;
};
@@ -205,6 +206,7 @@ class TestWebViewClient : public WebViewClient, public WebWidgetClient {
bool CanHandleGestureEvent() override { return true; }
bool CanUpdateLayout() override { return true; }
WebWidgetClient* WidgetClient() override { return this; }
+ blink::WebScreenInfo GetScreenInfo() override { return {}; }
bool AnimationScheduled() { return animation_scheduled_; }
void ClearAnimationScheduled() { animation_scheduled_ = false; }
@@ -298,7 +300,7 @@ class TestWebFrameClient : public WebLocalFrameClient {
static bool IsLoading() { return loads_in_progress_ > 0; }
- WebLocalFrame* Frame() const { return frame_; }
+ WebNavigationControl* Frame() const { return frame_; }
// Pass ownership of the TestWebFrameClient to |self_owned| here if the
// TestWebFrameClient should delete itself on frame detach.
void Bind(WebLocalFrame*,
@@ -314,7 +316,8 @@ class TestWebFrameClient : public WebLocalFrameClient {
const WebString& fallback_name,
WebSandboxFlags,
const ParsedFeaturePolicy&,
- const WebFrameOwnerProperties&) override;
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType) override;
void DidStartLoading() override;
void DidStopLoading() override;
void DidCreateDocumentLoader(WebDocumentLoader*) override;
@@ -327,6 +330,7 @@ class TestWebFrameClient : public WebLocalFrameClient {
// its own WebURLLoaderFactoryWithMock. (crbug.com/751425)
return Platform::Current()->CreateDefaultURLLoaderFactory();
}
+ void BeginNavigation(std::unique_ptr<WebNavigationInfo> info) override;
private:
static int loads_in_progress_;
@@ -340,7 +344,7 @@ class TestWebFrameClient : public WebLocalFrameClient {
// This is null from when the client is created until it is initialized with
// Bind().
- WebLocalFrame* frame_ = nullptr;
+ WebNavigationControl* frame_ = nullptr;
std::unique_ptr<WebWidgetClient> owned_widget_client_;
};
@@ -376,7 +380,7 @@ class TestWebRemoteFrameClient : public WebRemoteFrameClient {
WebRemoteFrame* frame_ = nullptr;
};
-} // namespace FrameTestHelpers
+} // namespace frame_test_helpers
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FRAME_TEST_HELPERS_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_view_auto_size_info.h b/chromium/third_party/blink/renderer/core/frame/frame_view_auto_size_info.h
index bdda5c657a9..6d99f1d27d2 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_view_auto_size_info.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_view_auto_size_info.h
@@ -19,17 +19,17 @@ class FrameViewAutoSizeInfo final
: public GarbageCollected<FrameViewAutoSizeInfo> {
public:
static FrameViewAutoSizeInfo* Create(LocalFrameView* frame_view) {
- return new FrameViewAutoSizeInfo(frame_view);
+ return MakeGarbageCollected<FrameViewAutoSizeInfo>(frame_view);
}
+ explicit FrameViewAutoSizeInfo(LocalFrameView*);
+
void ConfigureAutoSizeMode(const IntSize& min_size, const IntSize& max_size);
void AutoSizeIfNeeded();
void Trace(blink::Visitor*);
private:
- explicit FrameViewAutoSizeInfo(LocalFrameView*);
-
Member<LocalFrameView> frame_view_;
// The lower bound on the size when autosizing.
diff --git a/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.cc b/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.cc
index 4cd4d333a98..2e6d3604102 100644
--- a/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.cc
+++ b/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.cc
@@ -65,7 +65,7 @@ std::unique_ptr<FullscreenController> FullscreenController::Create(
FullscreenController::FullscreenController(WebViewImpl* web_view_base)
: web_view_base_(web_view_base),
- pending_frames_(new PendingFullscreenSet) {}
+ pending_frames_(MakeGarbageCollected<PendingFullscreenSet>()) {}
void FullscreenController::DidEnterFullscreen() {
// |Browser::EnterFullscreenModeForTab()| can enter fullscreen without going
@@ -136,7 +136,7 @@ void FullscreenController::DidExitFullscreen() {
}
void FullscreenController::EnterFullscreen(LocalFrame& frame,
- const FullscreenOptions& options) {
+ const FullscreenOptions* options) {
// TODO(dtapuska): If we are already in fullscreen. If the options are
// different than the currently requested one we may wish to request
// fullscreen mode again.
@@ -173,7 +173,7 @@ void FullscreenController::EnterFullscreen(LocalFrame& frame,
blink::WebFullscreenOptions blink_options;
// Only clone options if the feature is enabled.
if (RuntimeEnabledFeatures::FullscreenOptionsEnabled())
- blink_options.prefers_navigation_bar = options.navigationUI() != "hide";
+ blink_options.prefers_navigation_bar = options->navigationUI() != "hide";
GetWebFrameClient(frame).EnterFullscreen(blink_options);
state_ = State::kEnteringFullscreen;
diff --git a/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h b/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h
index 5a061e027c3..ab6676c1dd2 100644
--- a/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h
+++ b/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h
@@ -55,7 +55,7 @@ class CORE_EXPORT FullscreenController {
// Called by Fullscreen (via ChromeClient) to request entering or exiting
// fullscreen.
- void EnterFullscreen(LocalFrame&, const FullscreenOptions&);
+ void EnterFullscreen(LocalFrame&, const FullscreenOptions*);
void ExitFullscreen(LocalFrame&);
// Called by content::RenderWidget (via WebWidget) to notify that we've
diff --git a/chromium/third_party/blink/renderer/core/frame/history.cc b/chromium/third_party/blink/renderer/core/frame/history.cc
index b1d17d83269..5446de4128f 100644
--- a/chromium/third_party/blink/renderer/core/frame/history.cc
+++ b/chromium/third_party/blink/renderer/core/frame/history.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
+#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
@@ -151,36 +152,6 @@ HistoryScrollRestorationType History::ScrollRestorationInternal() const {
return history_item->ScrollRestorationType();
}
-// TODO(crbug.com/394296): This is not the long-term fix to IPC flooding that we
-// need. However, it does somewhat mitigate the immediate concern of |pushState|
-// and |replaceState| DoS (assuming the renderer has not been compromised).
-bool History::ShouldThrottleStateObjectChanges() {
- if (!GetFrame()->GetSettings()->GetShouldThrottlePushState())
- return false;
-
- // The aim is to enable 8 'frames' (history updates) per second, but we
- // express it as 80 frames per 10 seconds because some use cases (including
- // tests) do more than 8 updates in 1 second. But over time, applications
- // shooting for 8 FPS should work. If necessary to support legitimate
- // applications, we can increase this threshold somewhat.
- const int kStateUpdateLimit = 80;
-
- if (state_flood_guard.count > kStateUpdateLimit) {
- static constexpr auto kStateUpdateLimitResetInterval =
- TimeDelta::FromSeconds(10);
- const auto now = CurrentTimeTicks();
- if (now - state_flood_guard.last_updated > kStateUpdateLimitResetInterval) {
- state_flood_guard.count = 0;
- state_flood_guard.last_updated = now;
- return false;
- }
- return true;
- }
-
- state_flood_guard.count++;
- return false;
-}
-
bool History::stateChanged() const {
return last_state_object_requested_ != StateInternal();
}
@@ -221,6 +192,9 @@ void History::go(ScriptState* script_state,
return;
}
+ if (!GetFrame()->navigation_rate_limiter().CanProceed())
+ return;
+
if (delta) {
GetFrame()->Client()->NavigateBackForward(delta);
} else {
@@ -239,6 +213,16 @@ void History::pushState(scoped_refptr<SerializedScriptValue> data,
ExceptionState& exception_state) {
StateObjectAdded(std::move(data), title, url, ScrollRestorationInternal(),
WebFrameLoadType::kStandard, exception_state);
+ UseCounter::Count(GetFrame(), WebFeature::kHistoryPushState);
+}
+
+void History::replaceState(scoped_refptr<SerializedScriptValue> data,
+ const String& title,
+ const String& url,
+ ExceptionState& exception_state) {
+ StateObjectAdded(std::move(data), title, url, ScrollRestorationInternal(),
+ WebFrameLoadType::kReplaceCurrentItem, exception_state);
+ UseCounter::Count(GetFrame(), WebFeature::kHistoryReplaceState);
}
KURL History::UrlForState(const String& url_string) {
@@ -308,7 +292,7 @@ void History::StateObjectAdded(scoped_refptr<SerializedScriptValue> data,
return;
}
- if (ShouldThrottleStateObjectChanges()) {
+ if (!GetFrame()->navigation_rate_limiter().CanProceed()) {
// TODO(769592): Get an API spec change so that we can throw an exception:
//
// exception_state.ThrowDOMException(DOMExceptionCode::kQuotaExceededError,
@@ -316,11 +300,6 @@ void History::StateObjectAdded(scoped_refptr<SerializedScriptValue> data,
// "prevent the browser from hanging.");
//
// instead of merely warning.
-
- GetFrame()->Console().AddMessage(
- ConsoleMessage::Create(kJSMessageSource, kWarningMessageLevel,
- "Throttling history state changes to prevent "
- "the browser from hanging."));
return;
}
diff --git a/chromium/third_party/blink/renderer/core/frame/history.h b/chromium/third_party/blink/renderer/core/frame/history.h
index 95e5a6382da..f16dd789fc4 100644
--- a/chromium/third_party/blink/renderer/core/frame/history.h
+++ b/chromium/third_party/blink/renderer/core/frame/history.h
@@ -51,7 +51,11 @@ class CORE_EXPORT History final : public ScriptWrappable,
USING_GARBAGE_COLLECTED_MIXIN(History);
public:
- static History* Create(LocalFrame* frame) { return new History(frame); }
+ static History* Create(LocalFrame* frame) {
+ return MakeGarbageCollected<History>(frame);
+ }
+
+ explicit History(LocalFrame*);
unsigned length(ExceptionState&) const;
SerializedScriptValue* state(ExceptionState&);
@@ -68,10 +72,7 @@ class CORE_EXPORT History final : public ScriptWrappable,
void replaceState(scoped_refptr<SerializedScriptValue> data,
const String& title,
const String& url,
- ExceptionState& exception_state) {
- StateObjectAdded(std::move(data), title, url, ScrollRestorationInternal(),
- WebFrameLoadType::kReplaceCurrentItem, exception_state);
- }
+ ExceptionState& exception_state);
void setScrollRestoration(const String& value, ExceptionState&);
String scrollRestoration(ExceptionState&);
@@ -86,8 +87,6 @@ class CORE_EXPORT History final : public ScriptWrappable,
FRIEND_TEST_ALL_PREFIXES(HistoryTest, CanChangeToURLInFileOrigin);
FRIEND_TEST_ALL_PREFIXES(HistoryTest, CanChangeToURLInUniqueOrigin);
- explicit History(LocalFrame*);
-
static bool CanChangeToUrl(const KURL&,
const SecurityOrigin*,
const KURL& document_url);
@@ -103,13 +102,7 @@ class CORE_EXPORT History final : public ScriptWrappable,
SerializedScriptValue* StateInternal() const;
HistoryScrollRestorationType ScrollRestorationInternal() const;
- bool ShouldThrottleStateObjectChanges();
-
scoped_refptr<SerializedScriptValue> last_state_object_requested_;
- struct {
- int count;
- TimeTicks last_updated;
- } state_flood_guard;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/intervention.cc b/chromium/third_party/blink/renderer/core/frame/intervention.cc
index f65037b839a..1f9c5daa7e7 100644
--- a/chromium/third_party/blink/renderer/core/frame/intervention.cc
+++ b/chromium/third_party/blink/renderer/core/frame/intervention.cc
@@ -33,10 +33,10 @@ void Intervention::GenerateReport(const LocalFrame* frame,
return;
// Construct the intervention report.
- InterventionReportBody* body =
- new InterventionReportBody(id, message, SourceLocation::Capture());
- Report* report =
- new Report("intervention", document->Url().GetString(), body);
+ InterventionReportBody* body = MakeGarbageCollected<InterventionReportBody>(
+ id, message, SourceLocation::Capture());
+ Report* report = MakeGarbageCollected<Report>(
+ "intervention", document->Url().GetString(), body);
// Send the intervention report to any ReportingObservers.
ReportingContext::From(document)->QueueReport(report);
diff --git a/chromium/third_party/blink/renderer/core/frame/intervention_report_body.idl b/chromium/third_party/blink/renderer/core/frame/intervention_report_body.idl
index 303945bddb4..156fbc2c4b5 100644
--- a/chromium/third_party/blink/renderer/core/frame/intervention_report_body.idl
+++ b/chromium/third_party/blink/renderer/core/frame/intervention_report_body.idl
@@ -5,8 +5,7 @@
// https://wicg.github.io/reporting/#intervention-report
[
- NoInterfaceObject,
- RuntimeEnabled=InterventionReporting
+ NoInterfaceObject
] interface InterventionReportBody : ReportBody {
readonly attribute DOMString id;
readonly attribute DOMString message;
diff --git a/chromium/third_party/blink/renderer/core/frame/link_highlights.h b/chromium/third_party/blink/renderer/core/frame/link_highlights.h
index 940eb547673..55bf38e6ddc 100644
--- a/chromium/third_party/blink/renderer/core/frame/link_highlights.h
+++ b/chromium/third_party/blink/renderer/core/frame/link_highlights.h
@@ -24,7 +24,11 @@ class LayoutObject;
class CORE_EXPORT LinkHighlights final
: public GarbageCollectedFinalized<LinkHighlights> {
public:
- static LinkHighlights* Create(Page& page) { return new LinkHighlights(page); }
+ static LinkHighlights* Create(Page& page) {
+ return MakeGarbageCollected<LinkHighlights>(page);
+ }
+
+ explicit LinkHighlights(Page&);
virtual ~LinkHighlights();
virtual void Trace(blink::Visitor*);
@@ -58,8 +62,6 @@ class CORE_EXPORT LinkHighlights final
FRIEND_TEST_ALL_PREFIXES(LinkHighlightImplTest, multipleHighlights);
FRIEND_TEST_ALL_PREFIXES(LinkHighlightImplTest, HighlightLayerEffectNode);
- explicit LinkHighlights(Page&);
-
void RemoveAllHighlights();
LocalFrame* MainFrame() const;
diff --git a/chromium/third_party/blink/renderer/core/frame/local_dom_window.cc b/chromium/third_party/blink/renderer/core/frame/local_dom_window.cc
index b4b1e22c08d..49aa591e6c8 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_dom_window.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_dom_window.cc
@@ -284,7 +284,7 @@ void LocalDOMWindow::AcceptLanguagesChanged() {
if (navigator_)
navigator_->SetLanguagesChanged();
- DispatchEvent(*Event::Create(EventTypeNames::languagechange));
+ DispatchEvent(*Event::Create(event_type_names::kLanguagechange));
}
TrustedTypePolicyFactory* LocalDOMWindow::trustedTypes() const {
@@ -337,9 +337,6 @@ Document* LocalDOMWindow::InstallNewDocument(const String& mime_type,
GetFrame()->GetPage()->GetChromeClient().InstallSupplements(*GetFrame());
}
- if (GetFrame()->IsCrossOriginSubframe())
- document_->RecordDeferredLoadReason(WouldLoadReason::kCreated);
-
return document_;
}
@@ -384,12 +381,12 @@ void LocalDOMWindow::EnqueuePageshowEvent(PageshowEventPersistence persisted) {
// The task source should be kDOMManipulation, but the spec doesn't say
// anything about this.
EnqueueWindowEvent(
- *PageTransitionEvent::Create(EventTypeNames::pageshow, persisted),
+ *PageTransitionEvent::Create(event_type_names::kPageshow, persisted),
TaskType::kMiscPlatformAPI);
return;
}
DispatchEvent(
- *PageTransitionEvent::Create(EventTypeNames::pageshow, persisted),
+ *PageTransitionEvent::Create(event_type_names::kPageshow, persisted),
document_.Get());
}
@@ -503,7 +500,7 @@ void LocalDOMWindow::SendOrientationChangeEvent() {
for (LocalFrame* frame : frames) {
frame->DomWindow()->DispatchEvent(
- *Event::Create(EventTypeNames::orientationchange));
+ *Event::Create(event_type_names::kOrientationchange));
}
}
@@ -606,9 +603,9 @@ void LocalDOMWindow::SchedulePostMessage(
// is problematic; consider imposing a limit or other restriction if this
// surfaces often as a problem (see crbug.com/587012).
std::unique_ptr<SourceLocation> location = SourceLocation::Capture(source);
- PostMessageTimer* timer =
- new PostMessageTimer(*this, event, std::move(target), std::move(location),
- UserGestureIndicator::CurrentToken());
+ PostMessageTimer* timer = MakeGarbageCollected<PostMessageTimer>(
+ *this, event, std::move(target), std::move(location),
+ UserGestureIndicator::CurrentToken());
timer->StartOneShot(TimeDelta(), FROM_HERE);
timer->PauseIfNeeded();
probe::AsyncTaskScheduled(document(), "postMessage", timer);
@@ -1060,13 +1057,13 @@ double LocalDOMWindow::devicePixelRatio() const {
}
void LocalDOMWindow::scrollBy(double x, double y) const {
- ScrollToOptions options;
- options.setLeft(x);
- options.setTop(y);
+ ScrollToOptions* options = ScrollToOptions::Create();
+ options->setLeft(x);
+ options->setTop(y);
scrollBy(options);
}
-void LocalDOMWindow::scrollBy(const ScrollToOptions& scroll_to_options) const {
+void LocalDOMWindow::scrollBy(const ScrollToOptions* scroll_to_options) const {
if (!IsCurrentlyDisplayedInFrame())
return;
@@ -1082,29 +1079,28 @@ void LocalDOMWindow::scrollBy(const ScrollToOptions& scroll_to_options) const {
double x = 0.0;
double y = 0.0;
- if (scroll_to_options.hasLeft())
- x = ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left());
- if (scroll_to_options.hasTop())
- y = ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top());
+ if (scroll_to_options->hasLeft())
+ x = ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left());
+ if (scroll_to_options->hasTop())
+ y = ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top());
PaintLayerScrollableArea* viewport = view->LayoutViewport();
- ScrollOffset current_offset = viewport->GetScrollOffset();
- ScrollOffset scaled_delta(x * GetFrame()->PageZoomFactor(),
- y * GetFrame()->PageZoomFactor());
- FloatPoint new_scaled_position =
- viewport->ScrollOffsetToPosition(scaled_delta + current_offset);
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- new_scaled_position =
- document()
- ->GetSnapCoordinator()
- ->GetSnapPositionForPoint(
- *document()->GetLayoutView(), new_scaled_position,
- scroll_to_options.hasLeft(), scroll_to_options.hasTop())
- .value_or(new_scaled_position);
- }
+ FloatPoint current_position = viewport->ScrollPosition();
+ FloatPoint scaled_delta(x * GetFrame()->PageZoomFactor(),
+ y * GetFrame()->PageZoomFactor());
+ FloatPoint new_scaled_position = current_position + scaled_delta;
+
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndAndDirection(
+ gfx::ScrollOffset(current_position), gfx::ScrollOffset(scaled_delta));
+ new_scaled_position =
+ document()
+ ->GetSnapCoordinator()
+ ->GetSnapPosition(*document()->GetLayoutView(), *strategy)
+ .value_or(new_scaled_position);
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
- ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
+ ScrollableArea::ScrollBehaviorFromString(scroll_to_options->behavior(),
scroll_behavior);
viewport->SetScrollOffset(
viewport->ScrollPositionToOffset(new_scaled_position),
@@ -1112,13 +1108,13 @@ void LocalDOMWindow::scrollBy(const ScrollToOptions& scroll_to_options) const {
}
void LocalDOMWindow::scrollTo(double x, double y) const {
- ScrollToOptions options;
- options.setLeft(x);
- options.setTop(y);
+ ScrollToOptions* options = ScrollToOptions::Create();
+ options->setLeft(x);
+ options->setTop(y);
scrollTo(options);
}
-void LocalDOMWindow::scrollTo(const ScrollToOptions& scroll_to_options) const {
+void LocalDOMWindow::scrollTo(const ScrollToOptions* scroll_to_options) const {
if (!IsCurrentlyDisplayedInFrame())
return;
@@ -1132,8 +1128,8 @@ void LocalDOMWindow::scrollTo(const ScrollToOptions& scroll_to_options) const {
// It is only necessary to have an up-to-date layout if the position may be
// clamped, which is never the case for (0, 0).
- if (!scroll_to_options.hasLeft() || !scroll_to_options.hasTop() ||
- scroll_to_options.left() || scroll_to_options.top()) {
+ if (!scroll_to_options->hasLeft() || !scroll_to_options->hasTop() ||
+ scroll_to_options->left() || scroll_to_options->top()) {
document()->UpdateStyleAndLayoutIgnorePendingStylesheets();
}
@@ -1145,32 +1141,31 @@ void LocalDOMWindow::scrollTo(const ScrollToOptions& scroll_to_options) const {
scaled_x = current_offset.Width();
scaled_y = current_offset.Height();
- if (scroll_to_options.hasLeft())
+ if (scroll_to_options->hasLeft())
scaled_x =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left()) *
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left()) *
GetFrame()->PageZoomFactor();
- if (scroll_to_options.hasTop())
+ if (scroll_to_options->hasTop())
scaled_y =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top()) *
+ ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top()) *
GetFrame()->PageZoomFactor();
FloatPoint new_scaled_position =
viewport->ScrollOffsetToPosition(ScrollOffset(scaled_x, scaled_y));
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
- new_scaled_position =
- document()
- ->GetSnapCoordinator()
- ->GetSnapPositionForPoint(
- *document()->GetLayoutView(), new_scaled_position,
- scroll_to_options.hasLeft(), scroll_to_options.hasTop())
- .value_or(new_scaled_position);
- }
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(
+ gfx::ScrollOffset(new_scaled_position), scroll_to_options->hasLeft(),
+ scroll_to_options->hasTop());
+ new_scaled_position =
+ document()
+ ->GetSnapCoordinator()
+ ->GetSnapPosition(*document()->GetLayoutView(), *strategy)
+ .value_or(new_scaled_position);
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
- ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
+ ScrollableArea::ScrollBehaviorFromString(scroll_to_options->behavior(),
scroll_behavior);
-
viewport->SetScrollOffset(
viewport->ScrollPositionToOffset(new_scaled_position),
kProgrammaticScroll, scroll_behavior);
@@ -1265,7 +1260,7 @@ void LocalDOMWindow::queueMicrotask(V8VoidFunction* callback) {
}
int LocalDOMWindow::requestIdleCallback(V8IdleRequestCallback* callback,
- const IdleRequestOptions& options) {
+ const IdleRequestOptions* options) {
if (Document* document = this->document()) {
return document->RequestIdleCallback(
ScriptedIdleTaskController::V8IdleTask::Create(callback), options);
@@ -1302,7 +1297,7 @@ void LocalDOMWindow::SetModulator(Modulator* modulator) {
External* LocalDOMWindow::external() {
if (!external_)
- external_ = new External;
+ external_ = MakeGarbageCollected<External>();
return external_;
}
@@ -1329,19 +1324,19 @@ void LocalDOMWindow::AddedEventListener(
it->DidAddEventListener(this, event_type);
}
- if (event_type == EventTypeNames::unload) {
+ if (event_type == event_type_names::kUnload) {
UseCounter::Count(document(), WebFeature::kDocumentUnloadRegistered);
TrackUnloadEventListener(this);
- } else if (event_type == EventTypeNames::beforeunload) {
+ } else if (event_type == event_type_names::kBeforeunload) {
UseCounter::Count(document(), WebFeature::kDocumentBeforeUnloadRegistered);
TrackBeforeUnloadEventListener(this);
if (GetFrame() && !GetFrame()->IsMainFrame()) {
UseCounter::Count(document(),
WebFeature::kSubFrameBeforeUnloadRegistered);
}
- } else if (event_type == EventTypeNames::pagehide) {
+ } else if (event_type == event_type_names::kPagehide) {
UseCounter::Count(document(), WebFeature::kDocumentPageHideRegistered);
- } else if (event_type == EventTypeNames::pageshow) {
+ } else if (event_type == event_type_names::kPageshow) {
UseCounter::Count(document(), WebFeature::kDocumentPageShowRegistered);
}
}
@@ -1359,9 +1354,9 @@ void LocalDOMWindow::RemovedEventListener(
it->DidRemoveEventListener(this, event_type);
}
- if (event_type == EventTypeNames::unload) {
+ if (event_type == event_type_names::kUnload) {
UntrackUnloadEventListener(this);
- } else if (event_type == EventTypeNames::beforeunload) {
+ } else if (event_type == event_type_names::kBeforeunload) {
UntrackBeforeUnloadEventListener(this);
}
}
@@ -1385,7 +1380,7 @@ void LocalDOMWindow::WarnUnusedPreloads(TimerBase* base) {
}
void LocalDOMWindow::DispatchLoadEvent() {
- Event& load_event = *Event::Create(EventTypeNames::load);
+ Event& load_event = *Event::Create(event_type_names::kLoad);
DocumentLoader* document_loader =
GetFrame() ? GetFrame()->Loader().GetDocumentLoader() : nullptr;
if (document_loader &&
@@ -1421,7 +1416,7 @@ void LocalDOMWindow::DispatchLoadEvent() {
TRACE_EVENT_INSTANT1("devtools.timeline", "MarkLoad",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorMarkLoadEvent::Data(GetFrame()));
+ inspector_mark_load_event::Data(GetFrame()));
probe::loadEventFired(GetFrame());
}
@@ -1437,7 +1432,7 @@ DispatchEventResult LocalDOMWindow::DispatchEvent(Event& event,
event.SetEventPhase(Event::kAtTarget);
TRACE_EVENT1("devtools.timeline", "EventDispatch", "data",
- InspectorEventDispatchEvent::Data(event));
+ inspector_event_dispatch_event::Data(event));
return FireEventListeners(event);
}
diff --git a/chromium/third_party/blink/renderer/core/frame/local_dom_window.h b/chromium/third_party/blink/renderer/core/frame/local_dom_window.h
index aac28b00384..a15415a0bcc 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_dom_window.h
+++ b/chromium/third_party/blink/renderer/core/frame/local_dom_window.h
@@ -101,11 +101,12 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
const DocumentInit&,
bool force_xhtml);
static LocalDOMWindow* Create(LocalFrame& frame) {
- return new LocalDOMWindow(frame);
+ return MakeGarbageCollected<LocalDOMWindow>(frame);
}
static LocalDOMWindow* From(const ScriptState*);
+ explicit LocalDOMWindow(LocalFrame&);
~LocalDOMWindow() override;
LocalFrame* GetFrame() const { return ToLocalFrame(DOMWindow::GetFrame()); }
@@ -198,11 +199,11 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
// FIXME: ScrollBehaviorSmooth is currently unsupported in VisualViewport.
// crbug.com/434497
void scrollBy(double x, double y) const;
- void scrollBy(const ScrollToOptions&) const;
+ void scrollBy(const ScrollToOptions*) const;
void scrollTo(double x, double y) const;
- void scrollTo(const ScrollToOptions&) const;
+ void scrollTo(const ScrollToOptions*) const;
void scroll(double x, double y) const { scrollTo(x, y); }
- void scroll(const ScrollToOptions& scroll_to_options) const {
+ void scroll(const ScrollToOptions* scroll_to_options) const {
scrollTo(scroll_to_options);
}
void moveBy(int x, int y) const;
@@ -232,7 +233,7 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
void queueMicrotask(V8VoidFunction*);
// Idle callback extensions
- int requestIdleCallback(V8IdleRequestCallback*, const IdleRequestOptions&);
+ int requestIdleCallback(V8IdleRequestCallback*, const IdleRequestOptions*);
void cancelIdleCallback(int id);
// Custom elements
@@ -249,22 +250,19 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
bool isSecureContext() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(animationend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(animationiteration);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(animationstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(animationend, kAnimationend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(animationiteration, kAnimationiteration);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(animationstart, kAnimationstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(search, kSearch);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend, kTransitionend);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationstart,
- webkitAnimationStart);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationiteration,
- webkitAnimationIteration);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationend,
- webkitAnimationEnd);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkittransitionend,
- webkitTransitionEnd);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitanimationstart, kWebkitAnimationStart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitanimationiteration,
+ kWebkitAnimationIteration);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitanimationend, kWebkitAnimationEnd);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(webkittransitionend, kWebkitTransitionEnd);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(orientationchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(orientationchange, kOrientationchange);
void RegisterEventListenerObserver(EventListenerObserver*);
@@ -344,7 +342,6 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
bool IsRemoteDOMWindow() const override { return false; }
void WarnUnusedPreloads(TimerBase*);
- explicit LocalDOMWindow(LocalFrame&);
void Dispose();
void DispatchLoadEvent();
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame.cc b/chromium/third_party/blink/renderer/core/frame/local_frame.cc
index 19862e24a7f..72df3508f9e 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame.cc
@@ -30,7 +30,9 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include <limits>
#include <memory>
+#include <utility>
#include "services/network/public/cpp/features.h"
#include "services/service_manager/public/cpp/connector.h"
@@ -38,6 +40,7 @@
#include "third_party/blink/public/platform/interface_provider.h"
#include "third_party/blink/public/platform/interface_registry.h"
#include "third_party/blink/public/platform/scheduler/web_resource_loading_task_runner_handle.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
@@ -61,7 +64,6 @@
#include "third_party/blink/renderer/core/events/current_input_event.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
#include "third_party/blink/renderer/core/frame/ad_tracker.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/event_handler_registry.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
@@ -106,6 +108,7 @@
#include "third_party/blink/renderer/platform/json/json_values.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
+#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
#include "third_party/blink/renderer/platform/plugins/plugin_data.h"
#include "third_party/blink/renderer/platform/plugins/plugin_script_forbidden_scope.h"
@@ -115,8 +118,6 @@
namespace blink {
-using namespace HTMLNames;
-
namespace {
inline float ParentPageZoomFactor(LocalFrame* frame) {
@@ -214,7 +215,7 @@ LocalFrame* LocalFrame::Create(LocalFrameClient* client,
Page& page,
FrameOwner* owner,
InterfaceRegistry* interface_registry) {
- LocalFrame* frame = new LocalFrame(
+ LocalFrame* frame = MakeGarbageCollected<LocalFrame>(
client, page, owner,
interface_registry ? interface_registry
: InterfaceRegistry::GetEmptyInterfaceRegistry());
@@ -329,12 +330,16 @@ void LocalFrame::ScheduleNavigation(Document& origin_document,
const KURL& url,
WebFrameLoadType frame_load_type,
UserGestureStatus user_gesture_status) {
+ if (!navigation_rate_limiter().CanProceed())
+ return;
navigation_scheduler_->ScheduleFrameNavigation(&origin_document, url,
frame_load_type);
}
void LocalFrame::Navigate(const FrameLoadRequest& request,
WebFrameLoadType frame_load_type) {
+ if (!navigation_rate_limiter().CanProceed())
+ return;
loader_.StartNavigation(request, frame_load_type);
}
@@ -424,9 +429,6 @@ void LocalFrame::DetachImpl(FrameDetachType type) {
DomWindow()->FrameDestroyed();
- if (GetPage() && GetPage()->GetFocusController().FocusedFrame() == this)
- GetPage()->GetFocusController().SetFocusedFrame(nullptr);
-
probe::frameDetachedFromParent(this);
supplements_.clear();
@@ -487,14 +489,19 @@ void LocalFrame::DetachChildren() {
ChildFrameDisconnector(*document).Disconnect();
}
-void LocalFrame::DocumentAttached() {
- DCHECK(GetDocument());
+void LocalFrame::DidAttachDocument() {
+ Document* document = GetDocument();
+ DCHECK(document);
GetEditor().Clear();
+ // Clearing the event handler clears many events, but notably can ensure that
+ // for a drag started on an element in a frame that was moved (likely via
+ // appendChild()), the drag source will detach and stop firing drag events
+ // even after the frame reattaches.
GetEventHandler().Clear();
- Selection().DocumentAttached(GetDocument());
- GetInputMethodController().DocumentAttached(GetDocument());
- GetSpellChecker().DocumentAttached(GetDocument());
- GetTextSuggestionController().DocumentAttached(GetDocument());
+ Selection().DidAttachDocument(document);
+ GetInputMethodController().DidAttachDocument(document);
+ GetSpellChecker().DidAttachDocument(document);
+ GetTextSuggestionController().DidAttachDocument(document);
previews_resource_loading_hints_receiver_.reset();
}
@@ -593,7 +600,7 @@ void LocalFrame::DidResume() {
DCHECK(RuntimeEnabledFeatures::PageLifecycleEnabled());
if (GetDocument()) {
const TimeTicks resume_event_start = CurrentTimeTicks();
- GetDocument()->DispatchEvent(*Event::Create(EventTypeNames::resume));
+ GetDocument()->DispatchEvent(*Event::Create(event_type_names::kResume));
const TimeTicks resume_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, resume_histogram,
@@ -632,7 +639,7 @@ void LocalFrame::SetInheritedEffectiveTouchAction(TouchAction touch_action) {
GetDocument()->documentElement()->SetNeedsStyleRecalc(
kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kInheritedStyleChangeFromParentFrame));
+ style_change_reason::kInheritedStyleChangeFromParentFrame));
}
}
@@ -701,7 +708,7 @@ void LocalFrame::SetPrinting(bool printing,
} else {
if (LayoutView* layout_view = View()->GetLayoutView()) {
layout_view->SetPreferredLogicalWidthsDirty();
- layout_view->SetNeedsLayout(LayoutInvalidationReason::kPrintingChanged);
+ layout_view->SetNeedsLayout(layout_invalidation_reason::kPrintingChanged);
layout_view->SetShouldDoFullPaintInvalidationForViewAndAllDescendants();
}
View()->UpdateLayout();
@@ -813,7 +820,7 @@ void LocalFrame::SetPageAndTextZoomFactors(float page_zoom_factor,
document->MediaQueryAffectingValueChanged();
document->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kZoom));
+ StyleChangeReasonForTracing::Create(style_change_reason::kZoom));
document->UpdateStyleAndLayoutIgnorePendingStylesheets();
}
@@ -821,7 +828,7 @@ void LocalFrame::DeviceScaleFactorChanged() {
GetDocument()->MediaQueryAffectingValueChanged();
GetDocument()->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kZoom));
+ StyleChangeReasonForTracing::Create(style_change_reason::kZoom));
for (Frame* child = Tree().FirstChild(); child;
child = child->Tree().NextSibling()) {
if (child->IsLocalFrame())
@@ -947,21 +954,25 @@ inline LocalFrame::LocalFrame(LocalFrameClient* client,
editor_(Editor::Create(*this)),
spell_checker_(SpellChecker::Create(*this)),
selection_(FrameSelection::Create(*this)),
- event_handler_(new EventHandler(*this)),
+ event_handler_(MakeGarbageCollected<EventHandler>(*this)),
console_(FrameConsole::Create(*this)),
input_method_controller_(InputMethodController::Create(*this)),
- text_suggestion_controller_(new TextSuggestionController(*this)),
+ text_suggestion_controller_(
+ MakeGarbageCollected<TextSuggestionController>(*this)),
navigation_disable_count_(0),
page_zoom_factor_(ParentPageZoomFactor(this)),
text_zoom_factor_(ParentTextZoomFactor(this)),
in_view_source_mode_(false),
inspector_task_runner_(InspectorTaskRunner::Create(
GetTaskRunner(TaskType::kInternalInspector))),
- interface_registry_(interface_registry) {
+ interface_registry_(interface_registry),
+ is_save_data_enabled_(
+ !(GetSettings() && GetSettings()->GetDataSaverHoldbackWebApi()) &&
+ GetNetworkStateNotifier().SaveDataEnabled()) {
if (IsLocalRoot()) {
probe_sink_ = new CoreProbeSink();
- performance_monitor_ = new PerformanceMonitor(this);
- inspector_trace_events_ = new InspectorTraceEvents();
+ performance_monitor_ = MakeGarbageCollected<PerformanceMonitor>(this);
+ inspector_trace_events_ = MakeGarbageCollected<InspectorTraceEvents>();
probe_sink_->addInspectorTraceEvents(inspector_trace_events_);
if (RuntimeEnabledFeatures::AdTaggingEnabled()) {
ad_tracker_ = new AdTracker(this);
@@ -976,7 +987,7 @@ inline LocalFrame::LocalFrame(LocalFrameClient* client,
ad_tracker_ = LocalFrameRoot().ad_tracker_;
performance_monitor_ = LocalFrameRoot().performance_monitor_;
}
- idleness_detector_ = new IdlenessDetector(this);
+ idleness_detector_ = MakeGarbageCollected<IdlenessDetector>(this);
inspector_task_runner_->InitIsolate(V8PerIsolateData::MainThreadIsolate());
if (ad_tracker_) {
@@ -1059,11 +1070,11 @@ bool LocalFrame::CanNavigate(const Frame& target_frame,
return true;
}
- String target_domain = NetworkUtils::GetDomainAndRegistry(
+ String target_domain = network_utils::GetDomainAndRegistry(
target_frame.GetSecurityContext()->GetSecurityOrigin()->Domain(),
- NetworkUtils::kIncludePrivateRegistries);
- String destination_domain = NetworkUtils::GetDomainAndRegistry(
- destination_url.Host(), NetworkUtils::kIncludePrivateRegistries);
+ network_utils::kIncludePrivateRegistries);
+ String destination_domain = network_utils::GetDomainAndRegistry(
+ destination_url.Host(), network_utils::kIncludePrivateRegistries);
if (!target_domain.IsEmpty() && !destination_domain.IsEmpty() &&
target_domain == destination_domain) {
return true;
@@ -1075,10 +1086,14 @@ bool LocalFrame::CanNavigate(const Frame& target_frame,
//
// TODO(csharrison,japhet): Consider not logging an error message if the
// user has allowed popups/redirects.
+ bool allow_popups_and_redirects = false;
+ if (auto* settings_client = Client()->GetContentSettingsClient()) {
+ allow_popups_and_redirects =
+ settings_client->AllowPopupsAndRedirects(allow_popups_and_redirects);
+ }
if (!RuntimeEnabledFeatures::
FramebustingNeedsSameOriginOrUserGestureEnabled() ||
- Client()->GetContentSettingsClient().AllowPopupsAndRedirects(
- false /* default_value */)) {
+ allow_popups_and_redirects) {
String target_frame_description =
target_frame.IsLocalFrame() ? "with URL '" +
ToLocalFrame(target_frame)
@@ -1278,8 +1293,8 @@ LocalFrameClient* LocalFrame::Client() const {
return static_cast<LocalFrameClient*>(Frame::Client());
}
-ContentSettingsClient* LocalFrame::GetContentSettingsClient() {
- return Client() ? &Client()->GetContentSettingsClient() : nullptr;
+WebContentSettingsClient* LocalFrame::GetContentSettingsClient() {
+ return Client() ? Client()->GetContentSettingsClient() : nullptr;
}
FrameResourceCoordinator* LocalFrame::GetFrameResourceCoordinator() {
@@ -1357,6 +1372,10 @@ bool LocalFrame::IsLazyLoadingImageAllowed() const {
return false;
if (Owner() && !Owner()->ShouldLazyLoadChildren())
return false;
+ if (RuntimeEnabledFeatures::RestrictLazyImageLoadingToDataSaverEnabled() &&
+ !is_save_data_enabled_) {
+ return false;
+ }
return true;
}
@@ -1489,7 +1508,7 @@ SmoothScrollSequencer& LocalFrame::GetSmoothScrollSequencer() {
if (!IsLocalRoot())
return LocalFrameRoot().GetSmoothScrollSequencer();
if (!smooth_scroll_sequencer_)
- smooth_scroll_sequencer_ = new SmoothScrollSequencer();
+ smooth_scroll_sequencer_ = MakeGarbageCollected<SmoothScrollSequencer>();
return *smooth_scroll_sequencer_;
}
@@ -1516,11 +1535,6 @@ const mojom::blink::ReportingServiceProxyPtr& LocalFrame::GetReportingService()
return reporting_service_;
}
-void LocalFrame::DeprecatedReportFeaturePolicyViolation(
- mojom::FeaturePolicyFeature feature) const {
- GetSecurityContext()->ReportFeaturePolicyViolation(feature);
-}
-
// static
std::unique_ptr<UserGestureIndicator> LocalFrame::NotifyUserActivation(
LocalFrame* frame,
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame.h b/chromium/third_party/blink/renderer/core/frame/local_frame.h
index b0a066e119d..2c4d2eaf11b 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame.h
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame.h
@@ -68,7 +68,6 @@ class AssociatedInterfaceProvider;
class Color;
class ComputedAccessibleNode;
class ContentSecurityPolicy;
-class ContentSettingsClient;
class Document;
class Editor;
class Element;
@@ -102,6 +101,7 @@ class SmoothScrollSequencer;
class SpellChecker;
class TextSuggestionController;
class WebComputedAXTree;
+class WebContentSettingsClient;
class WebPluginContainerImpl;
class WebURLLoaderFactory;
@@ -118,6 +118,8 @@ class CORE_EXPORT LocalFrame final : public Frame,
FrameOwner*,
InterfaceRegistry* = nullptr);
+ LocalFrame(LocalFrameClient*, Page&, FrameOwner*, InterfaceRegistry*);
+
void Init();
void SetView(LocalFrameView*);
void CreateView(const IntSize&, const Color&);
@@ -148,7 +150,9 @@ class CORE_EXPORT LocalFrame final : public Frame,
Frame* child) override;
void DetachChildren();
- void DocumentAttached();
+ // After Document is attached, resets state related to document, and sets
+ // context to the current document.
+ void DidAttachDocument();
Frame* FindFrameForNavigation(const AtomicString& name,
LocalFrame& active_frame,
@@ -307,7 +311,7 @@ class CORE_EXPORT LocalFrame final : public Frame,
LocalFrameClient* Client() const;
- ContentSettingsClient* GetContentSettingsClient();
+ WebContentSettingsClient* GetContentSettingsClient();
// GetFrameResourceCoordinator may return nullptr when it can not hook up to
// services/resource_coordinator.
@@ -404,17 +408,11 @@ class CORE_EXPORT LocalFrame final : public Frame,
SmoothScrollSequencer& GetSmoothScrollSequencer();
- // TODO(iclelland): Replace this with a method on Document
- void DeprecatedReportFeaturePolicyViolation(
- mojom::FeaturePolicyFeature) const override;
-
const mojom::blink::ReportingServiceProxyPtr& GetReportingService() const;
private:
friend class FrameNavigationDisabler;
- LocalFrame(LocalFrameClient*, Page&, FrameOwner*, InterfaceRegistry*);
-
// Frame protected overrides:
void DetachImpl(FrameDetachType) override;
@@ -528,6 +526,16 @@ class CORE_EXPORT LocalFrame final : public Frame,
previews_resource_loading_hints_receiver_;
ClientHintsPreferences client_hints_preferences_;
+
+ // The value of |is_save_data_enabled_| is read once per frame from
+ // NetworkStateNotifier, which is guarded by a mutex lock, and cached locally
+ // here for performance.
+ // TODO(sclittle): This field doesn't really belong here - we should find some
+ // way to make the state of NetworkStateNotifier accessible without needing to
+ // acquire a mutex, such as by adding thread-local objects to hold the network
+ // state that get updated whenever the network state changes. That way, this
+ // field would be no longer necessary.
+ const bool is_save_data_enabled_;
};
inline FrameLoader& LocalFrame::Loader() const {
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_client.h b/chromium/third_party/blink/renderer/core/frame/local_frame_client.h
index db016b0e270..9f97e491238 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_client.h
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_client.h
@@ -34,6 +34,7 @@
#include <memory>
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/mojom/frame/navigation_initiator.mojom-blink.h"
#include "third_party/blink/public/platform/web_content_security_policy_struct.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_effective_connection_type.h"
@@ -43,6 +44,7 @@
#include "third_party/blink/public/platform/web_sudden_termination_disabler_type.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/platform/web_worker_fetch_context.h"
+#include "third_party/blink/public/web/web_frame_load_type.h"
#include "third_party/blink/public/web/web_global_object_reuse_policy.h"
#include "third_party/blink/public/web/web_history_commit_type.h"
#include "third_party/blink/public/web/web_navigation_params.h"
@@ -94,8 +96,8 @@ class SubstituteData;
class WebApplicationCacheHost;
class WebApplicationCacheHostClient;
class WebCookieJar;
-class WebFrame;
class WebLayerTreeView;
+class WebLocalFrame;
class WebMediaPlayer;
class WebMediaPlayerClient;
class WebMediaPlayerSource;
@@ -115,7 +117,7 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
public:
~LocalFrameClient() override = default;
- virtual WebFrame* GetWebFrame() const { return nullptr; }
+ virtual WebLocalFrame* GetWebFrame() const { return nullptr; }
virtual bool HasWebView() const = 0; // mainly for assertions
@@ -131,10 +133,8 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
WebHistoryCommitType,
bool content_initiated) {}
virtual void DispatchWillCommitProvisionalLoad() = 0;
- virtual void DispatchDidStartProvisionalLoad(
- DocumentLoader*,
- ResourceRequest&,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) = 0;
+ virtual void DispatchDidStartProvisionalLoad(DocumentLoader*,
+ const ResourceRequest&) = 0;
virtual void DispatchDidReceiveTitle(const String&) = 0;
virtual void DispatchDidChangeIcons(IconType) = 0;
virtual void DispatchDidCommitLoad(HistoryItem*,
@@ -148,21 +148,23 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
virtual void DispatchDidFinishLoad() = 0;
virtual void DispatchDidChangeThemeColor() = 0;
- virtual NavigationPolicy DecidePolicyForNavigation(
+ virtual void BeginNavigation(
const ResourceRequest&,
Document* origin_document,
DocumentLoader*,
WebNavigationType,
NavigationPolicy,
bool has_transient_activation,
- bool should_replace_current_entry,
+ WebFrameLoadType,
bool is_client_redirect,
WebTriggeringEventInfo,
HTMLFormElement*,
ContentSecurityPolicyDisposition
should_check_main_world_content_security_policy,
mojom::blink::BlobURLTokenPtr,
- base::TimeTicks input_start_time) = 0;
+ base::TimeTicks input_start_time,
+ const String& href_translate,
+ mojom::blink::NavigationInitiatorPtr) = 0;
virtual void DispatchWillSendSubmitEvent(HTMLFormElement*) = 0;
@@ -208,6 +210,10 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
// certificate.
virtual void ReportLegacySymantecCert(const KURL&, bool did_fail) {}
+ // The frame loaded a resource with a legacy TLS version that will be removed
+ // in the future. Prints a console message to warn about this.
+ virtual void ReportLegacyTLSVersion(const KURL&) {}
+
// Will be called when |PerformanceTiming| events are updated
virtual void DidChangePerformanceTiming() {}
@@ -223,6 +229,10 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
// process for histograms.
virtual void DidObserveNewCssPropertyUsage(int /*css_property*/,
bool /*is_animated*/) {}
+
+ // Reports that visible elements in the frame shifted (bit.ly/lsm-explainer).
+ virtual void DidObserveLayoutJank(double jank_fraction) {}
+
// Will be called by a Page upon DidCommitLoad, deciding whether to track
// UseCounter usage or not based on its url.
virtual bool ShouldTrackUseCounter(const KURL&) { return true; }
@@ -239,6 +249,8 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
const SubstituteData&,
ClientRedirectPolicy,
const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType,
+ WebNavigationType,
std::unique_ptr<WebNavigationParams> navigation_params,
std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) = 0;
@@ -329,7 +341,7 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
virtual std::unique_ptr<WebServiceWorkerProvider>
CreateServiceWorkerProvider() = 0;
- virtual ContentSettingsClient& GetContentSettingsClient() = 0;
+ virtual WebContentSettingsClient* GetContentSettingsClient() = 0;
virtual SharedWorkerRepositoryClient* GetSharedWorkerRepositoryClient() {
return nullptr;
@@ -434,7 +446,7 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
};
// Returns a new WebWorkerFetchContext for a dedicated worker or worklet.
- virtual std::unique_ptr<WebWorkerFetchContext> CreateWorkerFetchContext() {
+ virtual scoped_refptr<WebWorkerFetchContext> CreateWorkerFetchContext() {
return nullptr;
}
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_test.cc b/chromium/third_party/blink/renderer/core/frame/local_frame_test.cc
index 9d8d5a64256..c1aafd6c52a 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_test.cc
@@ -5,10 +5,13 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
+#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
@@ -20,6 +23,14 @@ void MaybeAllowImagePlaceholder(DummyPageHolder* page_holder,
params.SetClientLoFiPlaceholder();
}
+void DisableDataSaverHoldbackInSettings(Settings& settings) {
+ settings.SetDataSaverHoldbackWebApi(false);
+}
+
+void EnableDataSaverHoldbackInSettings(Settings& settings) {
+ settings.SetDataSaverHoldbackWebApi(true);
+}
+
} // namespace
class TestLocalFrameClient : public EmptyLocalFrameClient {
@@ -37,14 +48,22 @@ class TestLocalFrameClient : public EmptyLocalFrameClient {
const WebURLRequest::PreviewsState frame_previews_state_;
};
-TEST(LocalFrameTest, MaybeAllowPlaceholderImageUsesSpecifiedRequestValue) {
+class LocalFrameTest : public testing::Test {
+ public:
+ void TearDown() override {
+ // Reset the global data saver setting to false at the end of the test.
+ GetNetworkStateNotifier().SetSaveDataEnabled(false);
+ }
+};
+
+TEST_F(LocalFrameTest, MaybeAllowPlaceholderImageUsesSpecifiedRequestValue) {
ResourceRequest request1;
request1.SetURL(KURL("http://insecure.com"));
request1.SetPreviewsState(WebURLRequest::kClientLoFiOn);
FetchParameters params1(request1);
auto page_holder = DummyPageHolder::Create(
IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kPreviewsOff));
+ MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kPreviewsOff));
MaybeAllowImagePlaceholder(page_holder.get(), params1);
EXPECT_EQ(FetchParameters::kAllowPlaceholder,
params1.GetImageRequestOptimization());
@@ -55,19 +74,19 @@ TEST(LocalFrameTest, MaybeAllowPlaceholderImageUsesSpecifiedRequestValue) {
FetchParameters params2(request2);
auto page_holder2 = DummyPageHolder::Create(
IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kClientLoFiOn));
+ MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kClientLoFiOn));
MaybeAllowImagePlaceholder(page_holder2.get(), params2);
EXPECT_EQ(FetchParameters::kNone, params2.GetImageRequestOptimization());
}
-TEST(LocalFrameTest, MaybeAllowPlaceholderImageUsesFramePreviewsState) {
+TEST_F(LocalFrameTest, MaybeAllowPlaceholderImageUsesFramePreviewsState) {
ResourceRequest request1;
request1.SetURL(KURL("http://insecure.com"));
request1.SetPreviewsState(WebURLRequest::kPreviewsUnspecified);
FetchParameters params1(request1);
std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(
IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kClientLoFiOn));
+ MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kClientLoFiOn));
MaybeAllowImagePlaceholder(page_holder.get(), params1);
EXPECT_EQ(FetchParameters::kAllowPlaceholder,
params1.GetImageRequestOptimization());
@@ -77,24 +96,25 @@ TEST(LocalFrameTest, MaybeAllowPlaceholderImageUsesFramePreviewsState) {
request2.SetURL(KURL("http://insecure.com"));
request2.SetPreviewsState(WebURLRequest::kPreviewsUnspecified);
FetchParameters params2(request2);
- std::unique_ptr<DummyPageHolder> page_holder2 = DummyPageHolder::Create(
- IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kServerLitePageOn));
+ std::unique_ptr<DummyPageHolder> page_holder2 =
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kServerLitePageOn));
MaybeAllowImagePlaceholder(page_holder2.get(), params2);
EXPECT_EQ(FetchParameters::kNone, params2.GetImageRequestOptimization());
EXPECT_FALSE(page_holder2->GetFrame().IsUsingDataSavingPreview());
}
-TEST(LocalFrameTest,
- MaybeAllowPlaceholderImageConditionalOnSchemeForServerLoFi) {
+TEST_F(LocalFrameTest,
+ MaybeAllowPlaceholderImageConditionalOnSchemeForServerLoFi) {
ResourceRequest request1;
request1.SetURL(KURL("https://secure.com"));
request1.SetPreviewsState(WebURLRequest::kPreviewsUnspecified);
FetchParameters params1(request1);
auto page_holder = DummyPageHolder::Create(
IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kServerLoFiOn |
- WebURLRequest::kClientLoFiOn));
+ MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kServerLoFiOn |
+ WebURLRequest::kClientLoFiOn));
MaybeAllowImagePlaceholder(page_holder.get(), params1);
EXPECT_EQ(FetchParameters::kAllowPlaceholder,
params1.GetImageRequestOptimization());
@@ -105,49 +125,105 @@ TEST(LocalFrameTest,
FetchParameters params2(request2);
auto page_holder2 = DummyPageHolder::Create(
IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kServerLoFiOn |
- WebURLRequest::kClientLoFiOn));
+ MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kServerLoFiOn |
+ WebURLRequest::kClientLoFiOn));
MaybeAllowImagePlaceholder(page_holder2.get(), params2);
EXPECT_EQ(FetchParameters::kNone, params2.GetImageRequestOptimization());
}
-TEST(LocalFrameTest, IsUsingDataSavingPreview) {
- EXPECT_TRUE(DummyPageHolder::Create(
- IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kClientLoFiOn))
- ->GetFrame()
- .IsUsingDataSavingPreview());
- EXPECT_TRUE(DummyPageHolder::Create(
- IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kServerLoFiOn))
- ->GetFrame()
- .IsUsingDataSavingPreview());
- EXPECT_TRUE(DummyPageHolder::Create(
- IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kNoScriptOn))
- ->GetFrame()
- .IsUsingDataSavingPreview());
-
- EXPECT_FALSE(DummyPageHolder::Create(IntSize(800, 600), nullptr,
- new TestLocalFrameClient(
- WebURLRequest::kPreviewsUnspecified))
- ->GetFrame()
- .IsUsingDataSavingPreview());
- EXPECT_FALSE(DummyPageHolder::Create(
- IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kPreviewsOff))
- ->GetFrame()
- .IsUsingDataSavingPreview());
- EXPECT_FALSE(DummyPageHolder::Create(IntSize(800, 600), nullptr,
- new TestLocalFrameClient(
- WebURLRequest::kPreviewsNoTransform))
- ->GetFrame()
- .IsUsingDataSavingPreview());
- EXPECT_FALSE(DummyPageHolder::Create(
- IntSize(800, 600), nullptr,
- new TestLocalFrameClient(WebURLRequest::kServerLitePageOn))
- ->GetFrame()
- .IsUsingDataSavingPreview());
+TEST_F(LocalFrameTest, IsUsingDataSavingPreview) {
+ EXPECT_TRUE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kClientLoFiOn))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+ EXPECT_TRUE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kServerLoFiOn))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+ EXPECT_TRUE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kNoScriptOn))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+
+ EXPECT_FALSE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kPreviewsUnspecified))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+ EXPECT_FALSE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kPreviewsOff))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+ EXPECT_FALSE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kPreviewsNoTransform))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+ EXPECT_FALSE(
+ DummyPageHolder::Create(IntSize(800, 600), nullptr,
+ MakeGarbageCollected<TestLocalFrameClient>(
+ WebURLRequest::kServerLitePageOn))
+ ->GetFrame()
+ .IsUsingDataSavingPreview());
+}
+
+TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWithFeatureDisabled) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(false);
+ std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(
+ IntSize(800, 600), nullptr, nullptr, &DisableDataSaverHoldbackInSettings);
+ EXPECT_FALSE(page_holder->GetFrame().IsLazyLoadingImageAllowed());
+}
+
+TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWhenNotRestricted) {
+ ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
+ ScopedRestrictLazyImageLoadingToDataSaverForTest
+ scoped_restrict_lazy_image_loading_to_data_saver_for_test_(false);
+ std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(
+ IntSize(800, 600), nullptr, nullptr, &DisableDataSaverHoldbackInSettings);
+ EXPECT_TRUE(page_holder->GetFrame().IsLazyLoadingImageAllowed());
+}
+
+TEST_F(LocalFrameTest,
+ IsLazyLoadingImageAllowedWhenRestrictedWithDataSaverDisabled) {
+ ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
+ ScopedRestrictLazyImageLoadingToDataSaverForTest
+ scoped_restrict_lazy_image_loading_to_data_saver_for_test_(true);
+ GetNetworkStateNotifier().SetSaveDataEnabled(false);
+ std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(
+ IntSize(800, 600), nullptr, nullptr, &DisableDataSaverHoldbackInSettings);
+ EXPECT_FALSE(page_holder->GetFrame().IsLazyLoadingImageAllowed());
+}
+
+TEST_F(LocalFrameTest,
+ IsLazyLoadingImageAllowedWhenRestrictedWithDataSaverEnabledHoldback) {
+ ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
+ ScopedRestrictLazyImageLoadingToDataSaverForTest
+ scoped_restrict_lazy_image_loading_to_data_saver_for_test_(true);
+ GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(
+ IntSize(800, 600), nullptr, nullptr, &EnableDataSaverHoldbackInSettings);
+ EXPECT_FALSE(page_holder->GetFrame().IsLazyLoadingImageAllowed());
+}
+
+TEST_F(LocalFrameTest,
+ IsLazyLoadingImageAllowedWhenRestrictedWithDataSaverEnabled) {
+ ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
+ ScopedRestrictLazyImageLoadingToDataSaverForTest
+ scoped_restrict_lazy_image_loading_to_data_saver_for_test_(true);
+ GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ std::unique_ptr<DummyPageHolder> page_holder = DummyPageHolder::Create(
+ IntSize(800, 600), nullptr, nullptr, &DisableDataSaverHoldbackInSettings);
+ EXPECT_TRUE(page_holder->GetFrame().IsLazyLoadingImageAllowed());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc b/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc
index 388b5dbd458..152ba1b4b8c 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc
@@ -53,8 +53,8 @@ LocalFrameUkmAggregator::LocalFrameUkmAggregator(int64_t source_id,
// Set up the substrings to create the UMA names
const String uma_preamble = "Blink.";
const String uma_postscript = ".UpdateTime";
- const String uma_ratio_preamble = "Blink.MainFrame.";
- const String uma_ratio_postscript = "Ratio";
+ const String uma_percentage_preamble = "Blink.MainFrame.";
+ const String uma_percentage_postscript = "Ratio";
// Set up sub-strings for the bucketed UMA metrics
Vector<String> threshold_substrings;
@@ -78,7 +78,7 @@ LocalFrameUkmAggregator::LocalFrameUkmAggregator(int64_t source_id,
// Populate all the sub-metrics.
absolute_metric_records_.ReserveInitialCapacity(kCount);
- ratio_metric_records_.ReserveInitialCapacity(kCount);
+ main_frame_percentage_records_.ReserveInitialCapacity(kCount);
for (unsigned i = 0; i < (unsigned)kCount; ++i) {
const auto& metric_name = metric_strings()[i];
@@ -100,18 +100,18 @@ LocalFrameUkmAggregator::LocalFrameUkmAggregator(int64_t source_id,
// Ratio records report the ratio of each metric to the primary metric,
// average and worst case. UMA counters are also associated with the
// ratios and we allocate and own them here.
- auto& ratio_record = ratio_metric_records_.emplace_back();
- ratio_record.worst_case_metric_name = metric_name;
- ratio_record.worst_case_metric_name.append(".WorstCaseRatio");
- ratio_record.average_metric_name = metric_name;
- ratio_record.average_metric_name.append(".AverageRatio");
- ratio_record.reset();
+ auto& percentage_record = main_frame_percentage_records_.emplace_back();
+ percentage_record.worst_case_metric_name = metric_name;
+ percentage_record.worst_case_metric_name.append(".WorstCaseRatio");
+ percentage_record.average_metric_name = metric_name;
+ percentage_record.average_metric_name.append(".AverageRatio");
+ percentage_record.reset();
for (auto bucket_substring : threshold_substrings) {
- String uma_name = uma_ratio_preamble;
+ String uma_name = uma_percentage_preamble;
uma_name.append(metric_name);
- uma_name.append(uma_ratio_postscript);
+ uma_name.append(uma_percentage_postscript);
uma_name.append(bucket_substring);
- ratio_record.uma_counters_per_bucket.push_back(
+ percentage_record.uma_counters_per_bucket.push_back(
std::make_unique<CustomCountHistogram>(uma_name.Utf8().data(), 0,
10000000, 50));
}
@@ -127,6 +127,11 @@ LocalFrameUkmAggregator::GetScopedTimer(size_t metric_index) {
return ScopedUkmHierarchicalTimer(this, metric_index);
}
+void LocalFrameUkmAggregator::BeginMainFrame() {
+ DCHECK(!in_main_frame_update_);
+ in_main_frame_update_ = true;
+}
+
void LocalFrameUkmAggregator::RecordSample(size_t metric_index,
TimeTicks start,
TimeTicks end) {
@@ -143,14 +148,22 @@ void LocalFrameUkmAggregator::RecordSample(size_t metric_index,
// Record the UMA
record.uma_counter->CountMicroseconds(duration);
- // Just record the duration for ratios. We compute the ratio later
- // when we know the frame time.
- ratio_metric_records_[metric_index].interval_duration += duration;
+ // Only record ratios when inside a main frame.
+ if (in_main_frame_update_) {
+ // Just record the duration for ratios. We compute the ratio later
+ // when we know the frame time.
+ main_frame_percentage_records_[metric_index].interval_duration += duration;
+ }
}
-void LocalFrameUkmAggregator::RecordPrimarySample(TimeTicks start,
- TimeTicks end) {
- FlushIfNeeded(end);
+void LocalFrameUkmAggregator::RecordEndOfFrameMetrics(TimeTicks start,
+ TimeTicks end) {
+ // Any of the early out's in LocalFrameView::UpdateLifecyclePhases
+ // will mean we are not in a main frame update. Recording is triggered
+ // higher in the stack, so we cannot know to avoid calling this method.
+ if (!in_main_frame_update_)
+ return;
+ in_main_frame_update_ = false;
TimeDelta duration = end - start;
@@ -166,18 +179,32 @@ void LocalFrameUkmAggregator::RecordPrimarySample(TimeTicks start,
primary_metric_.total_duration += duration;
++primary_metric_.sample_count;
- // Compute all the dependent metrics
- for (auto& record : ratio_metric_records_) {
- double ratio =
- record.interval_duration.InMicrosecondsF() / duration.InMicrosecondsF();
- if (ratio > record.worst_case_ratio)
- record.worst_case_ratio = ratio;
- record.total_ratio += ratio;
+ // Compute all the dependent metrics, after finding which bucket we're in
+ // for UMA data.
+ size_t bucket_index = bucket_thresholds().size();
+ for (size_t i = 0; i < bucket_index; ++i) {
+ if (duration < bucket_thresholds()[i]) {
+ bucket_index = i;
+ }
+ }
+
+ for (auto& record : main_frame_percentage_records_) {
+ unsigned percentage =
+ (unsigned)floor(record.interval_duration.InMicrosecondsF() * 100.0 /
+ duration.InMicrosecondsF());
+ if (percentage > record.worst_case_percentage)
+ record.worst_case_percentage = percentage;
+ record.total_percentage += percentage;
++record.sample_count;
+ record.uma_counters_per_bucket[bucket_index]->Count(percentage);
record.interval_duration = TimeDelta();
}
has_data_ = true;
+
+ // Flush here to avoid resetting the ratios before this data point is
+ // recorded.
+ FlushIfNeeded(end);
}
void LocalFrameUkmAggregator::FlushIfNeeded(TimeTicks current_time) {
@@ -194,11 +221,9 @@ void LocalFrameUkmAggregator::Flush(TimeTicks current_time) {
ukm::UkmEntryBuilder builder(source_id_, event_name_.Utf8().data());
builder.SetMetric(primary_metric_.worst_case_metric_name.Utf8().data(),
primary_metric_.worst_case_duration.InMicroseconds());
- double average_frame_duration =
- primary_metric_.total_duration.InMicroseconds() /
- static_cast<int64_t>(primary_metric_.sample_count);
builder.SetMetric(primary_metric_.average_metric_name.Utf8().data(),
- average_frame_duration);
+ primary_metric_.total_duration.InMicroseconds() /
+ static_cast<int64_t>(primary_metric_.sample_count));
for (auto& record : absolute_metric_records_) {
if (record.sample_count == 0)
continue;
@@ -208,29 +233,14 @@ void LocalFrameUkmAggregator::Flush(TimeTicks current_time) {
record.total_duration.InMicroseconds() /
static_cast<int64_t>(record.sample_count));
}
-
- for (auto& record : ratio_metric_records_) {
+ for (auto& record : main_frame_percentage_records_) {
if (record.sample_count == 0)
continue;
builder.SetMetric(record.worst_case_metric_name.Utf8().data(),
- record.worst_case_ratio);
- double average_ratio =
- record.total_ratio / static_cast<float>(record.sample_count);
- builder.SetMetric(record.average_metric_name.Utf8().data(), average_ratio);
+ record.worst_case_percentage);
+ builder.SetMetric(record.average_metric_name.Utf8().data(),
+ record.total_percentage / record.sample_count);
record.reset();
-
- // Send ratio UMA data only when flushed to reduce overhead from metrics.
- // Find which bucket we're in for UMA data. We need to do this separately
- // for each metric because not every metric records on every frame.
- size_t bucket_index = bucket_thresholds().size();
- for (size_t i = 0; i < bucket_index; ++i) {
- if (average_frame_duration < bucket_thresholds()[i].InMicroseconds()) {
- bucket_index = i;
- }
- }
-
- record.uma_counters_per_bucket[bucket_index]->Count(
- floor(average_ratio * 100.0));
}
builder.Record(recorder_);
has_data_ = false;
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h b/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h
index 9f532bccabd..5cb8e2774b2 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h
@@ -16,10 +16,10 @@ class UkmRecorder;
namespace blink {
class CustomCountHistogram;
-// This class aggregates and records time based UKM and UMA metrics
+// This class aggregaties and records time based UKM and UMA metrics
// for LocalFrameView. The simplest way to use it is via the
-// SCOPED_UMA_AND_UKM_HIERARCHICAL_TIMER macro in LocalFrameView combined
-// with LocalFrameView::RecordEndOfFrameMetrics.
+// SCOPED_UMA_AND_UKM_TIMER macro combined with
+// LocalFrameView::RecordEndOfFrameMetrics.
//
// It takes the following constructor parameters:
// - source_id: UKM Source ID associated with the events.
@@ -42,19 +42,17 @@ class CustomCountHistogram;
//
// When the primary timed execution completes, this aggregator stores the
// primary time and computes metrics that depend on it. The results are
-// aggregated. A UKM event is
+// aggregated. UMA metrics are updated at this time. A UKM event is
// generated in one of two situations:
// - If a sample is added that lies in the next event frequency interval (this
// will generate an event for the previous interval)
// - If the aggregator is destroyed (this will generate an event for any
// remaining samples in the aggregator)
-// UMA ratio-related metrics are only reported when an event is generated to
-// reduce the overhead of metric gathering.
//
// Note that no event is generated if there were no primary samples in an
// interval.
//
-// Sample usage (see also SCOPED_UMA_AND_UKM_HIERARCHICAL_TIMER):
+// Sample usage (see also SCOPED_UMA_AND_UKM_TIMER):
// std::unique_ptr<UkmHierarchicalTimeAggregator> aggregator(
// new UkmHierarchicalTimeAggregator(
// GetSourceId(),
@@ -70,7 +68,7 @@ class CustomCountHistogram;
// // At this point an sample for kMetric2 is recorded.
// ...
// // When the primary time completes
-// aggregator->RecordPrimaryMetric(time_delta);
+// aggregator->RecordEndOfFrameMetrics(time_delta);
// // This records a primary sample and the sub-metrics that depend on it.
// // It may generate an event.
// ...
@@ -86,7 +84,7 @@ class CustomCountHistogram;
// "sub_metric3.Average", "sub_metric3.WorstCase"
// "sub_metric1.AverageRatio", "sub_metric1.WorstCaseRatio",
// "sub_metric2.AverageRatio", "sub_metric2.WorstCaseRatio",
-// "sub_metric3.AverageRatio", "sub_metric3.WorstCaseRation"
+// "sub_metric3.AverageRatio", "sub_metric3.WorstCaseRatio"
//
// It will report 13 UMA values:
// "primary_uma_counter",
@@ -103,6 +101,23 @@ class CustomCountHistogram;
//
// If the source_id/recorder changes then a new
// UkmHierarchicalTimeAggregator has to be created.
+// Defines a UKM that is part of a hierarchical ukm, recorded in
+// microseconds equal to the duration of the current lexical scope after
+// declaration of the macro. Example usage:
+//
+// void LocalFrameView::DoExpensiveThing() {
+// SCOPED_UMA_AND_UKM_TIMER(kUkmEnumName);
+// // Do computation of expensive thing
+//
+// }
+//
+// |ukm_enum| should be an entry in LocalFrameUkmAggregator's enum of
+// metric names (which in turn corresponds to names in from ukm.xml).
+
+#define SCOPED_UMA_AND_UKM_TIMER(aggregator, ukm_enum) \
+ auto scoped_ukm_hierarchical_timer = \
+ aggregator.GetScopedTimer(static_cast<size_t>(ukm_enum));
+
class CORE_EXPORT LocalFrameUkmAggregator {
public:
// Changing these values requires changing the names of metrics specified
@@ -116,6 +131,7 @@ class CORE_EXPORT LocalFrameUkmAggregator {
kPrePaint,
kStyleAndLayout,
kForcedStyleAndLayout,
+ kScrollingCoordinator,
kCount
};
@@ -125,9 +141,15 @@ class CORE_EXPORT LocalFrameUkmAggregator {
// Add an entry in this arrray every time a new metric is added.
static const Vector<String>& metric_strings() {
// Leaky construction to avoid exit-time destruction.
- static const Vector<String>* strings = new Vector<String>{
- "Compositing", "CompositingCommit", "IntersectionObservation", "Paint",
- "PrePaint", "StyleAndLayout", "ForcedStyleAndLayout"};
+ static const Vector<String>* strings =
+ new Vector<String>{"Compositing",
+ "CompositingCommit",
+ "IntersectionObservation",
+ "Paint",
+ "PrePaint",
+ "StyleAndLayout",
+ "ForcedStyleAndLayout",
+ "ScrollingCoordinator"};
return *strings;
}
@@ -169,15 +191,17 @@ class CORE_EXPORT LocalFrameUkmAggregator {
// correspond to the matching index in metric_names.
ScopedUkmHierarchicalTimer GetScopedTimer(size_t metric_index);
- // Record a primary sample, that also computes the ratios for the
+ // Record a main frame time metric, that also computes the ratios for the
// sub-metrics and may generate an event.
- void RecordPrimarySample(TimeTicks start, TimeTicks end);
+ void RecordEndOfFrameMetrics(TimeTicks start, TimeTicks end);
// Record a sample for a sub-metric. This should only be used when
// a ScopedUkmHierarchicalTimer cannot be used (such as when the timed
// interval does not fall inside a single calling function).
void RecordSample(size_t metric_index, TimeTicks start, TimeTicks end);
+ void BeginMainFrame();
+
private:
struct AbsoluteMetricRecord {
String worst_case_metric_name;
@@ -194,19 +218,19 @@ class CORE_EXPORT LocalFrameUkmAggregator {
}
};
- struct RatioMetricRecord {
+ struct MainFramePercentageRecord {
String worst_case_metric_name;
String average_metric_name;
Vector<std::unique_ptr<CustomCountHistogram>> uma_counters_per_bucket;
TimeDelta interval_duration;
- double total_ratio;
- double worst_case_ratio;
+ unsigned total_percentage;
+ unsigned worst_case_percentage;
size_t sample_count;
void reset() {
interval_duration = TimeDelta();
- total_ratio = 0;
- worst_case_ratio = 0;
+ total_percentage = 0;
+ worst_case_percentage = 0;
sample_count = 0u;
}
};
@@ -220,9 +244,13 @@ class CORE_EXPORT LocalFrameUkmAggregator {
const TimeDelta event_frequency_;
AbsoluteMetricRecord primary_metric_;
Vector<AbsoluteMetricRecord> absolute_metric_records_;
- Vector<RatioMetricRecord> ratio_metric_records_;
+ Vector<MainFramePercentageRecord> main_frame_percentage_records_;
TimeTicks last_flushed_time_;
+ // Set by BeginMainFrame() and cleared in RecordMEndOfFrameMetrics.
+ // Main frame metrics are only recorded if this is true.
+ bool in_main_frame_update_ = false;
+
bool has_data_ = false;
DISALLOW_COPY_AND_ASSIGN(LocalFrameUkmAggregator);
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc b/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc
index 69db1fd6163..c2cbfe55002 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc
@@ -49,6 +49,18 @@ class LocalFrameUkmAggregatorTest : public testing::Test {
".WorstCase";
}
+ std::string GetAverageRatioMetricName(int index) {
+ return std::string(
+ LocalFrameUkmAggregator::metric_strings()[index].Utf8().data()) +
+ ".AverageRatio";
+ }
+
+ std::string GetWorstCaseRatioMetricName(int index) {
+ return std::string(
+ LocalFrameUkmAggregator::metric_strings()[index].Utf8().data()) +
+ ".WorstCaseRatio";
+ }
+
base::TimeTicks Now() {
return base::TimeTicks() + base::TimeDelta::FromSecondsD(clock_->Now());
}
@@ -80,15 +92,25 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedPerSecond) {
if (!base::TimeTicks::IsHighResolution())
return;
- // Have 100 events 999ms each; The records should be recorded once every 30
- // seconds. The total run time is 99.9 seconds, so we should expect 3 events:
- // 0-30 sec, 30-60 sec, 60-90 sec.
- for (int i = 0; i < 100; ++i) {
+ // The records should be recorded once every 30 seconds.
+ // Set this up so that we get 3 events, each with 10 recordings per-metric,
+ // then a final event with 3 recordings per metric. That's 3 * kCount * 10
+ // steps + kCount * 3 more steps. A recording is made every 30s, so we need
+ // each step to be 30s / (kCount * 10), rounded up to be sure we are past 30s
+ // when the last metric is recorded, converted to ms.
+ base::TimeTicks start_time = base::TimeTicks();
+ int num_runs = 33 * LocalFrameUkmAggregator::kCount;
+ unsigned millisecond_per_step =
+ (unsigned)ceil(3000.0 / (double)LocalFrameUkmAggregator::kCount);
+ for (int i = 0; i < num_runs; ++i) {
+ aggregator().BeginMainFrame();
{
- auto timer = aggregator().GetScopedTimer(i % 2);
- clock().Advance(TimeDelta::FromMilliseconds(999));
+ auto timer =
+ aggregator().GetScopedTimer(i % LocalFrameUkmAggregator::kCount);
+ clock().Advance(TimeDelta::FromMilliseconds(millisecond_per_step));
}
- aggregator().RecordPrimarySample(base::TimeTicks(), Now());
+ aggregator().RecordEndOfFrameMetrics(start_time, Now());
+ start_time = Now();
}
EXPECT_EQ(recorder().entries_count(), 3u);
@@ -101,30 +123,35 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedPerSecond) {
auto entries = recorder().GetEntriesByName("Blink.UpdateTime");
EXPECT_EQ(entries.size(), 4u);
+ float expected_average_ratio =
+ floor(100.0 / (float)LocalFrameUkmAggregator::kCount);
for (auto* entry : entries) {
- EXPECT_TRUE(
- ukm::TestUkmRecorder::EntryHasMetric(entry, GetAverageMetricName(0)));
- const int64_t* metric1_average =
- ukm::TestUkmRecorder::GetEntryMetric(entry, GetAverageMetricName(0));
- EXPECT_NEAR(*metric1_average / 1e6, 0.999, 0.0001);
-
- EXPECT_TRUE(
- ukm::TestUkmRecorder::EntryHasMetric(entry, GetWorstCaseMetricName(0)));
- const int64_t* metric1_worst =
- ukm::TestUkmRecorder::GetEntryMetric(entry, GetWorstCaseMetricName(0));
- EXPECT_NEAR(*metric1_worst / 1e6, 0.999, 0.0001);
-
- EXPECT_TRUE(
- ukm::TestUkmRecorder::EntryHasMetric(entry, GetAverageMetricName(1)));
- const int64_t* metric2_average =
- ukm::TestUkmRecorder::GetEntryMetric(entry, GetAverageMetricName(1));
- EXPECT_NEAR(*metric2_average / 1e6, 0.999, 0.0001);
-
- EXPECT_TRUE(
- ukm::TestUkmRecorder::EntryHasMetric(entry, GetWorstCaseMetricName(1)));
- const int64_t* metric2_worst =
- ukm::TestUkmRecorder::GetEntryMetric(entry, GetWorstCaseMetricName(1));
- EXPECT_NEAR(*metric2_worst / 1e6, 0.999, 0.0001);
+ for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) {
+ EXPECT_TRUE(
+ ukm::TestUkmRecorder::EntryHasMetric(entry, GetAverageMetricName(i)));
+ const int64_t* metric1_average =
+ ukm::TestUkmRecorder::GetEntryMetric(entry, GetAverageMetricName(i));
+ EXPECT_NEAR(*metric1_average / 1e3, millisecond_per_step, 0.001);
+
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetWorstCaseMetricName(i)));
+ const int64_t* metric1_worst = ukm::TestUkmRecorder::GetEntryMetric(
+ entry, GetWorstCaseMetricName(i));
+ EXPECT_NEAR(*metric1_worst / 1e3, millisecond_per_step, 0.001);
+
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetAverageRatioMetricName(i)));
+ const int64_t* metric1_average_ratio =
+ ukm::TestUkmRecorder::GetEntryMetric(entry,
+ GetAverageRatioMetricName(i));
+ EXPECT_NEAR(*metric1_average_ratio, expected_average_ratio, 0.001);
+
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetWorstCaseRatioMetricName(i)));
+ const int64_t* metric1_worst_ratio = ukm::TestUkmRecorder::GetEntryMetric(
+ entry, GetWorstCaseRatioMetricName(i));
+ EXPECT_NEAR(*metric1_worst_ratio, 100.0, 0.001);
+ }
}
}
@@ -135,6 +162,8 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsAveragedCorrectly) {
if (!base::TimeTicks::IsHighResolution())
return;
+ aggregator().BeginMainFrame();
+
// 1, 2, and 3 seconds.
for (int i = 1; i <= 3; ++i) {
{
@@ -153,9 +182,8 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsAveragedCorrectly) {
clock().Advance(TimeDelta::FromSeconds(1));
}
- aggregator().RecordPrimarySample(
- base::TimeTicks(),
- base::TimeTicks() + base::TimeDelta::FromSecondsD(120));
+ aggregator().RecordEndOfFrameMetrics(
+ base::TimeTicks(), base::TimeTicks() + base::TimeDelta::FromSecondsD(20));
ResetAggregator();
auto entries = recorder().GetEntriesByName("Blink.UpdateTime");
@@ -176,6 +204,20 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsAveragedCorrectly) {
// metric1 (1, 2, 3) worst case is 3
EXPECT_NEAR(*metric1_worst / 1e6, 3.0, 0.0001);
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetAverageRatioMetricName(0)));
+ const int64_t* metric1_average_ratio =
+ ukm::TestUkmRecorder::GetEntryMetric(entry, GetAverageRatioMetricName(0));
+ // metric1 (1, 2, 3) sums to 6 seconds of time with a frame time of 20
+ EXPECT_NEAR(*metric1_average_ratio, floor(6.0 * 100.0 / 20.0), 0.0001);
+
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetWorstCaseRatioMetricName(0)));
+ const int64_t* metric1_worst_ratio = ukm::TestUkmRecorder::GetEntryMetric(
+ entry, GetWorstCaseRatioMetricName(0));
+ // Only one main frame sample, so worst is same as average
+ EXPECT_NEAR(*metric1_worst_ratio, floor(6.0 * 100.0 / 20.0), 0.0001);
+
EXPECT_TRUE(
ukm::TestUkmRecorder::EntryHasMetric(entry, GetAverageMetricName(1)));
const int64_t* metric2_average =
@@ -189,6 +231,21 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsAveragedCorrectly) {
ukm::TestUkmRecorder::GetEntryMetric(entry, GetWorstCaseMetricName(1));
// metric1 (3, 3, 3, 1) worst case is 3
EXPECT_NEAR(*metric2_worst / 1e6, 3.0, 0.0001);
+
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetAverageRatioMetricName(1)));
+ const int64_t* metric2_average_ratio =
+ ukm::TestUkmRecorder::GetEntryMetric(entry, GetAverageRatioMetricName(1));
+ // metric2 (3, 3, 3, 1) sums to 10 seconds of time with a frame time of 20
+ EXPECT_NEAR(*metric2_average_ratio, floor(10.0 * 100.0 / 20.0), 0.0001);
+
+ EXPECT_TRUE(ukm::TestUkmRecorder::EntryHasMetric(
+ entry, GetWorstCaseRatioMetricName(1)));
+ const int64_t* metric2_worst_ratio = ukm::TestUkmRecorder::GetEntryMetric(
+ entry, GetWorstCaseRatioMetricName(1));
+
+ // Only one main frame sample, so worst is same as average
+ EXPECT_NEAR(*metric2_worst_ratio, floor(10.0 * 100.0 / 20.0), 0.0001);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_view.cc b/chromium/third_party/blink/renderer/core/frame/local_frame_view.cc
index 6a46de482da..87d8798a1df 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_view.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -111,7 +111,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/paint_timing.h"
-#include "third_party/blink/renderer/core/paint/paint_tracker.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/pre_paint_tree_walk.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer_controller.h"
@@ -182,7 +182,9 @@ void LogCursorSizeCounter(LocalFrame* frame, const Cursor& cursor) {
// whether the cursor exceeds its maximum size (see event_handler.cc).
IntSize scaled_size = image->Size();
scaled_size.Scale(1 / cursor.ImageScaleFactor());
- if (scaled_size.Width() > 32 || scaled_size.Height() > 32) {
+ if (scaled_size.Width() > 64 || scaled_size.Height() > 64) {
+ UseCounter::Count(frame, WebFeature::kCursorImageGT64x64);
+ } else if (scaled_size.Width() > 32 || scaled_size.Height() > 32) {
UseCounter::Count(frame, WebFeature::kCursorImageGT32x32);
} else {
UseCounter::Count(frame, WebFeature::kCursorImageLE32x32);
@@ -191,24 +193,6 @@ void LogCursorSizeCounter(LocalFrame* frame, const Cursor& cursor) {
} // namespace
-// Defines a UKM that is part of a hierarchical ukm, recorded in
-// microseconds equal to the duration of the current lexical scope after
-// declaration of the macro. Example usage:
-//
-// void LocalFrameView::DoExpensiveThing() {
-// SCOPED_UMA_AND_UKM_TIMER(kUkmEnumName);
-// // Do computation of expensive thing
-//
-// }
-//
-// |ukm_enum| should be an entry in LocalFrameUkmAggregator's enum of
-// metric names (which in turn corresponds to names in from ukm.xml).
-#define SCOPED_UMA_AND_UKM_TIMER(ukm_enum) \
- auto scoped_ukm_hierarchical_timer = \
- EnsureUkmAggregator().GetScopedTimer(static_cast<size_t>(ukm_enum));
-
-using namespace HTMLNames;
-
// The maximum number of updatePlugins iterations that should be done before
// returning.
static const unsigned kMaxUpdatePluginsIterations = 2;
@@ -232,7 +216,7 @@ LocalFrameView::LocalFrameView(LocalFrame& frame, IntRect frame_rect)
first_layout_(true),
base_background_color_(Color::kWhite),
last_zoom_factor_(1.0f),
- media_type_(MediaTypeNames::screen),
+ media_type_(media_type_names::kScreen),
safe_to_propagate_scroll_to_parent_(true),
visually_non_empty_character_count_(0),
visually_non_empty_pixel_count_(0),
@@ -267,7 +251,7 @@ LocalFrameView::LocalFrameView(LocalFrame& frame, IntRect frame_rect)
paint_frame_count_(0),
unique_id_(NewUniqueObjectId()),
jank_tracker_(std::make_unique<JankTracker>(this)),
- paint_tracker_(new PaintTracker(this)) {
+ paint_timing_detector_(new PaintTimingDetector(this)) {
// Propagate the marginwidth/height and scrolling modes to the view.
if (frame_->Owner() &&
frame_->Owner()->ScrollingMode() == kScrollbarAlwaysOff)
@@ -275,15 +259,15 @@ LocalFrameView::LocalFrameView(LocalFrame& frame, IntRect frame_rect)
}
LocalFrameView* LocalFrameView::Create(LocalFrame& frame) {
- LocalFrameView* view = new LocalFrameView(frame, IntRect());
+ LocalFrameView* view = MakeGarbageCollected<LocalFrameView>(frame, IntRect());
view->Show();
return view;
}
LocalFrameView* LocalFrameView::Create(LocalFrame& frame,
const IntSize& initial_size) {
- LocalFrameView* view =
- new LocalFrameView(frame, IntRect(IntPoint(), initial_size));
+ LocalFrameView* view = MakeGarbageCollected<LocalFrameView>(
+ frame, IntRect(IntPoint(), initial_size));
view->SetLayoutSizeInternal(initial_size);
view->Show();
@@ -309,7 +293,7 @@ void LocalFrameView::Trace(blink::Visitor* visitor) {
visitor->Trace(visibility_observer_);
visitor->Trace(anchoring_adjustment_queue_);
visitor->Trace(print_context_);
- visitor->Trace(paint_tracker_);
+ visitor->Trace(paint_timing_detector_);
}
template <typename Function>
@@ -366,7 +350,7 @@ void LocalFrameView::SetupRenderThrottling() {
if (!target_element)
return;
- visibility_observer_ = new ElementVisibilityObserver(
+ visibility_observer_ = MakeGarbageCollected<ElementVisibilityObserver>(
target_element, WTF::BindRepeating(
[](LocalFrameView* frame_view, bool is_visible) {
if (!frame_view)
@@ -788,7 +772,7 @@ void LocalFrameView::UpdateLayout() {
Document* document = frame_->GetDocument();
TRACE_EVENT_BEGIN1("devtools.timeline", "Layout", "beginData",
- InspectorLayoutEvent::BeginData(this));
+ inspector_layout_event::BeginData(this));
probe::UpdateLayout probe(document);
PerformPreLayoutTasks();
@@ -934,7 +918,7 @@ void LocalFrameView::UpdateLayout() {
// FIXME: The notion of a single root for layout is no longer applicable.
// Remove or update this code. crbug.com/460596
TRACE_EVENT_END1("devtools.timeline", "Layout", "endData",
- InspectorLayoutEvent::EndData(root_for_this_layout));
+ inspector_layout_event::EndData(root_for_this_layout));
probe::didChangeViewport(frame_.Get());
nested_layout_count_--;
@@ -1139,7 +1123,7 @@ void LocalFrameView::AdjustMediaTypeForPrinting(bool printing) {
if (printing) {
if (media_type_when_not_printing_.IsNull())
media_type_when_not_printing_ = MediaType();
- SetMediaType(MediaTypeNames::print);
+ SetMediaType(media_type_names::kPrint);
} else {
if (!media_type_when_not_printing_.IsNull())
SetMediaType(media_type_when_not_printing_);
@@ -1148,7 +1132,7 @@ void LocalFrameView::AdjustMediaTypeForPrinting(bool printing) {
frame_->GetDocument()->SetNeedsStyleRecalc(
kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kStyleSheetChange));
+ style_change_reason::kStyleSheetChange));
}
void LocalFrameView::AddBackgroundAttachmentFixedObject(LayoutObject* object) {
@@ -1185,10 +1169,8 @@ void LocalFrameView::RemoveBackgroundAttachmentFixedObject(
}
void LocalFrameView::AddViewportConstrainedObject(LayoutObject& object) {
- if (!viewport_constrained_objects_) {
- viewport_constrained_objects_ =
- std::make_unique<ViewportConstrainedObjectSet>();
- }
+ if (!viewport_constrained_objects_)
+ viewport_constrained_objects_ = std::make_unique<ObjectSet>();
if (!viewport_constrained_objects_->Contains(&object)) {
viewport_constrained_objects_->insert(&object);
@@ -1218,7 +1200,8 @@ void LocalFrameView::ViewportSizeChanged(bool width_changed,
frame_->GetDocument()->Lifecycle().LifecyclePostponed())
return;
- if (LayoutView* layout_view = this->GetLayoutView()) {
+ auto* layout_view = GetLayoutView();
+ if (layout_view) {
// If this is the main frame, we might have got here by hiding/showing the
// top controls. In that case, layout won't be triggered, so we need to
// clamp the scroll offset here.
@@ -1236,26 +1219,11 @@ void LocalFrameView::ViewportSizeChanged(bool width_changed,
if (GetFrame().GetDocument())
GetFrame().GetDocument()->GetRootScrollerController().DidResizeFrameView();
- if (GetLayoutView() && frame_->IsMainFrame() &&
- frame_->GetPage()->GetBrowserControls().TotalHeight()) {
- if (GetLayoutView()->StyleRef().HasFixedBackgroundImage()) {
- // We've already issued a full invalidation above.
- GetLayoutView()->SetShouldDoFullPaintInvalidationOnResizeIfNeeded(
- width_changed, height_changed);
- } else if (height_changed) {
- // If the document rect doesn't fill the full view height, hiding the
- // URL bar will expose area outside the current LayoutView so we need to
- // paint additional background. If RLS is on, we've already invalidated
- // above.
- auto* layout_view = GetLayoutView();
- DCHECK(layout_view);
- if (layout_view->DocumentRect().Height() <
- layout_view->ViewRect().Height()) {
- layout_view->SetShouldDoFullPaintInvalidation(
- PaintInvalidationReason::kGeometry);
- }
- }
- }
+ // Change of viewport size after browser controls showing/hiding may affect
+ // painting of the background.
+ if (layout_view && frame_->IsMainFrame() &&
+ frame_->GetPage()->GetBrowserControls().TotalHeight())
+ layout_view->SetShouldCheckForPaintInvalidation();
if (GetFrame().GetDocument() && !IsInPerformLayout())
MarkViewportConstrainedObjectsForLayout(width_changed, height_changed);
@@ -1277,7 +1245,7 @@ void LocalFrameView::MarkViewportConstrainedObjectsForLayout(
layout_object->SetNeedsPositionedMovementLayout();
} else {
layout_object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
}
}
if (height_changed) {
@@ -1286,7 +1254,7 @@ void LocalFrameView::MarkViewportConstrainedObjectsForLayout(
layout_object->SetNeedsPositionedMovementLayout();
} else {
layout_object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
}
}
}
@@ -1306,31 +1274,22 @@ void LocalFrameView::NotifyFrameRectsChangedIfNeededRecursive() {
});
}
-void LocalFrameView::InvalidateBackgroundAttachmentFixedDescendants(
- const LayoutObject& object) {
+void LocalFrameView::InvalidateBackgroundAttachmentFixedDescendantsOnScroll(
+ const LayoutObject& scrolled_object) {
for (auto* const layout_object : background_attachment_fixed_objects_) {
- if (object != GetLayoutView() && !layout_object->IsDescendantOf(&object))
+ if (scrolled_object != GetLayoutView() &&
+ !layout_object->IsDescendantOf(&scrolled_object))
continue;
-
- bool needs_scrolling_contents_layer_invalidation = false;
- if (layout_object->HasLayer()) {
- PaintLayer* layer = ToLayoutBoxModelObject(layout_object)->Layer();
- if (layer->GetBackgroundPaintLocation() ==
- kBackgroundPaintInScrollingContents) {
- needs_scrolling_contents_layer_invalidation = true;
- }
- }
- if (needs_scrolling_contents_layer_invalidation) {
- // BoxPaintInvalidator doesn't want to invalidate scrolling contents layer
- // whenever the LayoutObject is marked ShouldDoFullPaintInvalidation() -
- // see crrev.com/433093. (LayoutObject doesn't track full-invalidation
- // reasons independently, so it's not safe for BoxPaintInvalidator to have
- // special handling of kBackground.)
- layout_object->SetBackgroundChangedSinceLastPaintInvalidation();
- } else {
- layout_object->SetShouldDoFullPaintInvalidation(
- PaintInvalidationReason::kBackground);
- }
+ // An object needs to be repainted on scroll when it has background-
+ // attachment:fixed, unless the background will be separately composited
+ // i.e. when a LayoutView paints backgrounds only into scrolling contents.
+ if (layout_object == GetLayoutView() &&
+ GetLayoutView()->GetBackgroundPaintLocation() ==
+ kBackgroundPaintInScrollingContents &&
+ (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
+ GetLayoutView()->Compositor()->PreferCompositingToLCDTextEnabled()))
+ continue;
+ layout_object->SetBackgroundNeedsFullPaintInvalidation();
}
}
@@ -1385,7 +1344,7 @@ bool LocalFrameView::InvalidateViewportConstrainedObjects() {
TRACE_EVENT_INSTANT1(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"ScrollInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorScrollInvalidationTrackingEvent::Data(*layout_object));
+ inspector_scroll_invalidation_tracking_event::Data(*layout_object));
// If the fixed layer has a blur/drop-shadow filter applied on at least one
// of its parents, we cannot scroll using the fast path, otherwise the
@@ -1737,7 +1696,7 @@ void LocalFrameView::ScheduleRelayout() {
return;
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"InvalidateLayout", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorInvalidateLayoutEvent::Data(frame_.Get()));
+ inspector_invalidate_layout_event::Data(frame_.Get()));
ClearLayoutSubtreeRootsAndMarkContainingBlocks();
@@ -1783,7 +1742,7 @@ void LocalFrameView::ScheduleRelayoutOfSubtree(LayoutObject* relayout_root) {
}
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"InvalidateLayout", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorInvalidateLayoutEvent::Data(frame_.Get()));
+ inspector_invalidate_layout_event::Data(frame_.Get()));
}
bool LocalFrameView::LayoutPending() const {
@@ -1820,7 +1779,7 @@ void LocalFrameView::SetNeedsLayout() {
// the check fails.
if (!CheckLayoutInvalidationIsAllowed())
return;
- layout_view->SetNeedsLayout(LayoutInvalidationReason::kUnknown);
+ layout_view->SetNeedsLayout(layout_invalidation_reason::kUnknown);
}
bool LocalFrameView::HasOpaqueBackground() const {
@@ -1891,9 +1850,9 @@ void LocalFrameView::ScrollAndFocusFragmentAnchor() {
? ToElement(anchor_node)
: frame_->GetDocument()->documentElement();
if (anchor_element) {
- ScrollIntoViewOptions options;
- options.setBlock("start");
- options.setInlinePosition("nearest");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
+ options->setInlinePosition("nearest");
anchor_element->ScrollIntoViewNoVisualUpdate(options);
}
@@ -2121,7 +2080,7 @@ void LocalFrameView::DidAttachDocument() {
viewport_scrollable_area_ = root_frame_viewport;
page->GlobalRootScrollerController().InitializeViewportScrollCallback(
- *root_frame_viewport);
+ *root_frame_viewport, *frame_->GetDocument());
}
}
@@ -2190,38 +2149,46 @@ void LocalFrameView::UpdateGeometriesIfNeeded() {
}
}
-void LocalFrameView::UpdateAllLifecyclePhases() {
+void LocalFrameView::UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason reason) {
GetFrame().LocalFrameRoot().View()->UpdateLifecyclePhases(
- DocumentLifecycle::kPaintClean);
+ DocumentLifecycle::kPaintClean, reason);
}
-// TODO(chrishtr): add a scrolling update lifecycle phase.
+// TODO(schenney): add a scrolling update lifecycle phase.
+// TODO(schenney): Pass a LifecycleUpdateReason in here
bool LocalFrameView::UpdateLifecycleToCompositingCleanPlusScrolling() {
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
return UpdateAllLifecyclePhasesExceptPaint();
} else {
return GetFrame().LocalFrameRoot().View()->UpdateLifecyclePhases(
- DocumentLifecycle::kCompositingClean);
+ DocumentLifecycle::kCompositingClean,
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
}
+// TODO(schenney): Pass a LifecycleUpdateReason in here
bool LocalFrameView::UpdateLifecycleToCompositingInputsClean() {
// When SPv2 is enabled, the standard compositing lifecycle steps do not
// exist; compositing is done after paint instead.
DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
return GetFrame().LocalFrameRoot().View()->UpdateLifecyclePhases(
- DocumentLifecycle::kCompositingInputsClean);
+ DocumentLifecycle::kCompositingInputsClean,
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
+// TODO(schenney): Pass a LifecycleUpdateReason in here
bool LocalFrameView::UpdateAllLifecyclePhasesExceptPaint() {
return GetFrame().LocalFrameRoot().View()->UpdateLifecyclePhases(
- DocumentLifecycle::kPrePaintClean);
+ DocumentLifecycle::kPrePaintClean,
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
void LocalFrameView::UpdateLifecyclePhasesForPrinting() {
auto* local_frame_view_root = GetFrame().LocalFrameRoot().View();
local_frame_view_root->UpdateLifecyclePhases(
- DocumentLifecycle::kPrePaintClean);
+ DocumentLifecycle::kPrePaintClean,
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
auto* detached_frame_view = this;
while (detached_frame_view->is_attached_ &&
@@ -2236,17 +2203,21 @@ void LocalFrameView::UpdateLifecyclePhasesForPrinting() {
// was not reached in some phases during during |local_frame_view_root->
// UpdateLifecyclePhasesnormal()|. We need the subtree to be ready for
// painting.
- detached_frame_view->UpdateLifecyclePhases(DocumentLifecycle::kPrePaintClean);
+ detached_frame_view->UpdateLifecyclePhases(
+ DocumentLifecycle::kPrePaintClean,
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
+// TODO(schenney): Pass a LifecycleUpdateReason in here
bool LocalFrameView::UpdateLifecycleToLayoutClean() {
return GetFrame().LocalFrameRoot().View()->UpdateLifecyclePhases(
- DocumentLifecycle::kLayoutClean);
+ DocumentLifecycle::kLayoutClean,
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
void LocalFrameView::RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time) {
LocalFrameUkmAggregator& ukm_aggregator = EnsureUkmAggregator();
- ukm_aggregator.RecordPrimarySample(frame_begin_time, CurrentTimeTicks());
+ ukm_aggregator.RecordEndOfFrameMetrics(frame_begin_time, CurrentTimeTicks());
}
void LocalFrameView::ScheduleVisualUpdateForPaintInvalidationIfNeeded() {
@@ -2285,9 +2256,11 @@ void LocalFrameView::NotifyResizeObservers() {
ErrorEvent* error = ErrorEvent::Create(
"ResizeObserver loop limit exceeded",
SourceLocation::Capture(frame_->GetDocument()), nullptr);
- // We're using |kSharableCrossOrigin| as the error is made by blink itself.
+ // We're using |SanitizeScriptErrors::kDoNotSanitize| as the error is made
+ // by blink itself.
// TODO(yhirano): Reconsider this.
- frame_->GetDocument()->DispatchErrorEvent(error, kSharableCrossOrigin);
+ frame_->GetDocument()->DispatchErrorEvent(
+ error, SanitizeScriptErrors::kDoNotSanitize);
// Ensure notifications will get delivered in next cycle.
ScheduleAnimation();
}
@@ -2308,7 +2281,8 @@ void LocalFrameView::SetupPrintContext() {
if (frame_->GetDocument()->Printing())
return;
if (!print_context_) {
- print_context_ = new PrintContext(frame_, /*use_printing_layout=*/true);
+ print_context_ = MakeGarbageCollected<PrintContext>(
+ frame_, /*use_printing_layout=*/true);
}
if (frame_->GetSettings())
frame_->GetSettings()->SetShouldPrintBackgrounds(true);
@@ -2330,7 +2304,8 @@ void LocalFrameView::ClearPrintContext() {
// TODO(leviw): We don't assert lifecycle information from documents in child
// WebPluginContainerImpls.
bool LocalFrameView::UpdateLifecyclePhases(
- DocumentLifecycle::LifecycleState target_state) {
+ DocumentLifecycle::LifecycleState target_state,
+ DocumentLifecycle::LifecycleUpdateReason reason) {
// If the lifecycle is postponed, which can happen if the inspector requests
// it, then we shouldn't update any lifecycle phases.
if (UNLIKELY(frame_->GetDocument() &&
@@ -2388,6 +2363,9 @@ bool LocalFrameView::UpdateLifecyclePhases(
return Lifecycle().GetState() == target_state;
}
+ if (reason == DocumentLifecycle::LifecycleUpdateReason::kBeginMainFrame)
+ EnsureUkmAggregator().BeginMainFrame();
+
// If we're in PrintBrowser mode, setup a print context.
// TODO(vmpstr): It doesn't seem like we need to do this every lifecycle
// update, but rather once somewhere at creation time.
@@ -2403,7 +2381,8 @@ bool LocalFrameView::UpdateLifecyclePhases(
if (target_state == DocumentLifecycle::kPaintClean) {
TRACE_EVENT0("blink,benchmark",
"LocalFrameView::UpdateViewportIntersectionsForSubtree");
- SCOPED_UMA_AND_UKM_TIMER(LocalFrameUkmAggregator::kIntersectionObservation);
+ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kIntersectionObservation);
UpdateViewportIntersectionsForSubtree();
}
@@ -2430,9 +2409,9 @@ void LocalFrameView::UpdateLifecyclePhasesInternal(
{
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"SetLayerTreeId", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorSetLayerTreeId::Data(frame_.Get()));
+ inspector_set_layer_tree_id::Data(frame_.Get()));
TRACE_EVENT1("devtools.timeline", "UpdateLayerTree", "data",
- InspectorUpdateLayerTreeEvent::Data(frame_.Get()));
+ inspector_update_layer_tree_event::Data(frame_.Get()));
run_more_lifecycle_phases = RunCompositingLifecyclePhase(target_state);
if (!run_more_lifecycle_phases)
@@ -2457,7 +2436,13 @@ void LocalFrameView::UpdateLifecyclePhasesInternal(
bool LocalFrameView::RunStyleAndLayoutLifecyclePhases(
DocumentLifecycle::LifecycleState target_state) {
- UpdateStyleAndLayoutIfNeededRecursive();
+ TRACE_EVENT0("blink,benchmark",
+ "LocalFrameView::RunStyleAndLayoutLifecyclePhases");
+ {
+ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kStyleAndLayout);
+ UpdateStyleAndLayoutIfNeededRecursive();
+ }
DCHECK(Lifecycle().GetState() >= DocumentLifecycle::kLayoutClean);
frame_->GetDocument()
@@ -2516,11 +2501,14 @@ bool LocalFrameView::RunStyleAndLayoutLifecyclePhases(
bool LocalFrameView::RunCompositingLifecyclePhase(
DocumentLifecycle::LifecycleState target_state) {
+ TRACE_EVENT0("blink,benchmark",
+ "LocalFrameView::RunCompositingLifecyclePhase");
auto* layout_view = GetLayoutView();
DCHECK(layout_view);
if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- SCOPED_UMA_AND_UKM_TIMER(LocalFrameUkmAggregator::kCompositing);
+ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kCompositing);
layout_view->Compositor()->UpdateIfNeededRecursive(target_state);
} else {
ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) {
@@ -2548,7 +2536,7 @@ bool LocalFrameView::RunCompositingLifecyclePhase(
bool LocalFrameView::RunPrePaintLifecyclePhase(
DocumentLifecycle::LifecycleState target_state) {
- TRACE_EVENT0("blink,benchmark", "LocalFrameView::prePaint");
+ TRACE_EVENT0("blink,benchmark", "LocalFrameView::RunPrePaintLifecyclePhase");
ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) {
frame_view.Lifecycle().AdvanceTo(DocumentLifecycle::kInPrePaint);
@@ -2564,7 +2552,8 @@ bool LocalFrameView::RunPrePaintLifecyclePhase(
});
{
- SCOPED_UMA_AND_UKM_TIMER(LocalFrameUkmAggregator::kPrePaint);
+ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kPrePaint);
PrePaintTreeWalk().WalkTree(*this);
}
@@ -2576,7 +2565,16 @@ bool LocalFrameView::RunPrePaintLifecyclePhase(
return target_state > DocumentLifecycle::kPrePaintClean;
}
+template <typename Function>
+static void ForAllGraphicsLayers(GraphicsLayer& layer,
+ const Function& function) {
+ function(layer);
+ for (auto* child : layer.Children())
+ ForAllGraphicsLayers(*child, function);
+}
+
void LocalFrameView::RunPaintLifecyclePhase() {
+ TRACE_EVENT0("blink,benchmark", "LocalFrameView::RunPaintLifecyclePhase");
// While printing a document, the paint walk is done by the printing
// component into a special canvas. There is no point doing a normal paint
// step (or animations update for BlinkGenPropertyTrees/SPv2) when in this
@@ -2602,7 +2600,7 @@ void LocalFrameView::RunPaintLifecyclePhase() {
base::Optional<CompositorElementIdSet> composited_element_ids =
CompositorElementIdSet();
PushPaintArtifactToCompositor(composited_element_ids.value());
- // TODO(wkorman): Add call to UpdateCompositorScrollAnimations here.
+ // TODO(pdr): Add call to UpdateCompositorScrollAnimations here.
ForAllNonThrottledLocalFrameViews(
[&composited_element_ids](LocalFrameView& frame_view) {
DocumentAnimations::UpdateAnimations(
@@ -2613,9 +2611,27 @@ void LocalFrameView::RunPaintLifecyclePhase() {
// Notify the controller that the artifact has been pushed and some
// lifecycle state can be freed (such as raster invalidations).
paint_controller_->FinishCycle();
+
// PaintController for BlinkGenPropertyTrees is transient.
- if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // Property tree changed state is typically cleared through
+ // |PaintController::FinishCycle| but that will be a no-op because
+ // the paint controller is transient, so force the changed state to be
+ // cleared here.
+ paint_controller_->ClearPropertyTreeChangedStateTo(
+ PropertyTreeState::Root());
+ auto* root = GetLayoutView()->Compositor()->PaintRootGraphicsLayer();
+ if (root) {
+ ForAllGraphicsLayers(*root, [](GraphicsLayer& layer) {
+ if (layer.DrawsContent() && layer.HasLayerState()) {
+ layer.GetPaintController().ClearPropertyTreeChangedStateTo(
+ layer.GetPropertyTreeState());
+ }
+ });
+ }
paint_controller_ = nullptr;
+ }
}
}
}
@@ -2661,10 +2677,8 @@ static void CollectViewportLayersForLayerList(GraphicsContext& context,
// layers are still attached. In future we will disable all those layer
// hierarchy code so we won't need this line.
container_layer->CcLayer()->RemoveAllChildren();
- RecordForeignLayer(context, *container_layer,
- DisplayItem::kForeignLayerWrapper,
- container_layer->CcLayer(), FloatPoint(),
- IntSize(container_layer->CcLayer()->bounds()));
+ RecordForeignLayer(context, DisplayItem::kForeignLayerWrapper,
+ container_layer->CcLayer());
}
// Collect the page scale layer.
@@ -2675,8 +2689,8 @@ static void CollectViewportLayersForLayerList(GraphicsContext& context,
*scale_layer, DisplayItem::kForeignLayerWrapper);
scale_layer->CcLayer()->RemoveAllChildren();
- RecordForeignLayer(context, *scale_layer, DisplayItem::kForeignLayerWrapper,
- scale_layer->CcLayer(), FloatPoint(), IntSize());
+ RecordForeignLayer(context, DisplayItem::kForeignLayerWrapper,
+ scale_layer->CcLayer());
}
// Collect the visual viewport scroll layer.
@@ -2687,10 +2701,8 @@ static void CollectViewportLayersForLayerList(GraphicsContext& context,
*scroll_layer, DisplayItem::kForeignLayerWrapper);
scroll_layer->CcLayer()->RemoveAllChildren();
- RecordForeignLayer(context, *scroll_layer,
- DisplayItem::kForeignLayerWrapper,
- scroll_layer->CcLayer(), FloatPoint(),
- IntSize(scroll_layer->CcLayer()->bounds()));
+ RecordForeignLayer(context, DisplayItem::kForeignLayerWrapper,
+ scroll_layer->CcLayer());
}
}
@@ -2715,22 +2727,16 @@ static void CollectDrawableLayersForLayerListRecursively(
// extraneous layers are still attached. In future we will disable all
// those layer hierarchy code so we won't need this line.
layer->CcLayer()->RemoveAllChildren();
- RecordForeignLayer(context, *layer, DisplayItem::kForeignLayerWrapper,
- layer->CcLayer(),
- FloatPoint(layer->GetOffsetFromTransformNode()),
- IntSize(layer->Size()));
+ RecordForeignLayer(context, DisplayItem::kForeignLayerWrapper,
+ layer->CcLayer());
}
- if (scoped_refptr<cc::Layer> contents_layer = layer->ContentsLayer()) {
+ if (auto* contents_layer = layer->ContentsLayer()) {
ScopedPaintChunkProperties scope(
context.GetPaintController(), layer->GetContentsPropertyTreeState(),
*layer, DisplayItem::kForeignLayerContentsWrapper);
- auto size = contents_layer->bounds();
- RecordForeignLayer(context, *layer,
- DisplayItem::kForeignLayerContentsWrapper,
- std::move(contents_layer),
- FloatPoint(layer->GetContentsOffsetFromTransformNode()),
- IntSize(size.width(), size.height()));
+ RecordForeignLayer(context, DisplayItem::kForeignLayerContentsWrapper,
+ contents_layer);
}
DCHECK(!layer->ContentsClippingMaskLayer());
@@ -2756,13 +2762,8 @@ static void CollectLinkHighlightLayersForLayerListRecursively(
ScopedPaintChunkProperties scope(context.GetPaintController(),
property_tree_state, *highlight,
DisplayItem::kForeignLayerLinkHighlight);
- auto position = highlight_layer->position();
- auto size = highlight_layer->bounds();
- RecordForeignLayer(context, *highlight,
- DisplayItem::kForeignLayerLinkHighlight, highlight_layer,
- layer->GetOffsetFromTransformNode() +
- FloatSize(position.x(), position.y()),
- IntSize(size.width(), size.height()));
+ RecordForeignLayer(context, DisplayItem::kForeignLayerLinkHighlight,
+ highlight_layer);
}
for (const auto* child : layer->Children())
@@ -2778,8 +2779,8 @@ static void PaintGraphicsLayerRecursively(GraphicsLayer* layer) {
}
void LocalFrameView::PaintTree() {
- TRACE_EVENT0("blink,benchmark", "LocalFrameView::paintTree");
- SCOPED_UMA_AND_UKM_TIMER(LocalFrameUkmAggregator::kPaint);
+ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kPaint);
DCHECK(GetFrame().IsLocalRoot());
@@ -2810,7 +2811,7 @@ void LocalFrameView::PaintTree() {
}
PaintInternal(graphics_context, kGlobalPaintNormalPhase,
- CullRect(LayoutRect::InfiniteIntRect()));
+ CullRect::Infinite());
paint_controller_->CommitNewDisplayItems();
}
} else {
@@ -2863,7 +2864,8 @@ void LocalFrameView::PaintTree() {
if (auto* web_local_frame_impl = WebLocalFrameImpl::FromFrame(frame_))
web_local_frame_impl->UpdateDevToolsOverlays();
- if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
// BlinkGenPropertyTrees just needs a transient PaintController to
// collect the foreign layers which doesn't need caching. It also
// shouldn't affect caching status of DisplayItemClients because it's
@@ -2919,11 +2921,12 @@ void LocalFrameView::PushPaintArtifactToCompositor(
paint_artifact_compositor_->RootLayer(), &GetFrame());
}
- SCOPED_UMA_AND_UKM_TIMER(LocalFrameUkmAggregator::kCompositingCommit);
+ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kCompositingCommit);
paint_artifact_compositor_->Update(
paint_controller_->GetPaintArtifactShared(), composited_element_ids,
- frame_->GetPage()->GetVisualViewport().GetPageScaleNode());
+ page->GetVisualViewport().GetPageScaleNode());
}
std::unique_ptr<JSONObject> LocalFrameView::CompositedLayersAsJSON(
@@ -2935,11 +2938,6 @@ std::unique_ptr<JSONObject> LocalFrameView::CompositedLayersAsJSON(
}
void LocalFrameView::UpdateStyleAndLayoutIfNeededRecursive() {
- SCOPED_UMA_AND_UKM_TIMER(LocalFrameUkmAggregator::kStyleAndLayout);
- UpdateStyleAndLayoutIfNeededRecursiveInternal();
-}
-
-void LocalFrameView::UpdateStyleAndLayoutIfNeededRecursiveInternal() {
if (ShouldThrottleRendering() || !frame_->GetDocument()->IsActive())
return;
@@ -2979,9 +2977,9 @@ void LocalFrameView::UpdateStyleAndLayoutIfNeededRecursiveInternal() {
// WebView plugins need to update regardless of whether the
// LayoutEmbeddedObject that owns them needed layout.
- // TODO(leviw): This currently runs the entire lifecycle on plugin WebViews.
- // We should have a way to only run these other Documents to the same
- // lifecycle stage as this frame.
+ // TODO(schenney): This currently runs the entire lifecycle on plugin
+ // WebViews. We should have a way to only run these other Documents to the
+ // same lifecycle stage as this frame.
for (const auto& plugin : plugins_) {
plugin->UpdateAllLifecyclePhases();
}
@@ -2999,7 +2997,7 @@ void LocalFrameView::UpdateStyleAndLayoutIfNeededRecursiveInternal() {
}
for (const auto& frame_view : frame_views)
- frame_view->UpdateStyleAndLayoutIfNeededRecursiveInternal();
+ frame_view->UpdateStyleAndLayoutIfNeededRecursive();
// These asserts ensure that parent frames are clean, when child frames
// finished updating layout and style.
@@ -3071,7 +3069,7 @@ void LocalFrameView::ForceLayoutForPagination(
layout_view->SetLogicalWidth(floored_page_logical_width);
layout_view->SetPageLogicalHeight(floored_page_logical_height);
layout_view->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kPrintingChanged);
+ layout_invalidation_reason::kPrintingChanged);
UpdateLayout();
// If we don't fit in the given page width, we'll lay out again. If we don't
@@ -3105,7 +3103,7 @@ void LocalFrameView::ForceLayoutForPagination(
layout_view->SetLogicalWidth(floored_page_logical_width);
layout_view->SetPageLogicalHeight(floored_page_logical_height);
layout_view->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kPrintingChanged);
+ layout_invalidation_reason::kPrintingChanged);
UpdateLayout();
const LayoutRect& updated_document_rect =
@@ -3384,7 +3382,7 @@ void LocalFrameView::SetTracksPaintInvalidations(
return;
// Ensure the document is up-to-date before tracking invalidations.
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(DocumentLifecycle::LifecycleUpdateReason::kTest);
for (Frame* frame = &frame_->Tree().Top(); frame;
frame = frame->Tree().TraverseNext()) {
@@ -3472,7 +3470,7 @@ void LocalFrameView::AddScrollableArea(
PaintLayerScrollableArea* scrollable_area) {
DCHECK(scrollable_area);
if (!scrollable_areas_)
- scrollable_areas_ = new ScrollableAreaSet;
+ scrollable_areas_ = MakeGarbageCollected<ScrollableAreaSet>();
scrollable_areas_->insert(scrollable_area);
if (GetScrollingCoordinator())
@@ -3493,7 +3491,7 @@ void LocalFrameView::AddAnimatingScrollableArea(
PaintLayerScrollableArea* scrollable_area) {
DCHECK(scrollable_area);
if (!animating_scrollable_areas_)
- animating_scrollable_areas_ = new ScrollableAreaSet;
+ animating_scrollable_areas_ = MakeGarbageCollected<ScrollableAreaSet>();
animating_scrollable_areas_->insert(scrollable_area);
}
@@ -3575,14 +3573,12 @@ bool LocalFrameView::VisualViewportSuppliesScrollbars() {
!frame_->GetDocument() || !frame_->GetPage())
return false;
- const TopDocumentRootScrollerController& controller =
- frame_->GetPage()->GlobalRootScrollerController();
-
if (!LayoutViewport())
return false;
- return RootScrollerUtil::ScrollableAreaForRootScroller(
- controller.GlobalRootScroller()) == LayoutViewport();
+ const TopDocumentRootScrollerController& controller =
+ frame_->GetPage()->GlobalRootScrollerController();
+ return controller.RootScrollerArea() == LayoutViewport();
}
AXObjectCache* LocalFrameView::ExistingAXObjectCache() const {
@@ -3628,6 +3624,10 @@ void LocalFrameView::SetLayoutSizeInternal(const IntSize& size) {
}
void LocalFrameView::ClipPaintRect(FloatRect* paint_rect) const {
+ // TODO(wangxianzhu): Support ChromeClient::VisibleContentRectForPainting()
+ // for SPv2.
+ DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+
// Paint the whole rect if "mainFrameClipsContent" is false, meaning that
// WebPreferences::record_whole_document is true.
if (!frame_->GetSettings()->GetMainFrameClipsContent())
@@ -3962,7 +3962,6 @@ void LocalFrameView::UpdateViewportIntersectionsForSubtree() {
if (!GetFrame().GetDocument()->IsActive())
return;
- RecordDeferredLoadingStats();
if (!NeedsLayout()) {
// Notify javascript IntersectionObservers
if (GetFrame().GetDocument()->GetIntersectionObserverController()) {
@@ -4101,68 +4100,6 @@ void LocalFrameView::UpdateRenderThrottlingStatus(
#endif
}
-void LocalFrameView::RecordDeferredLoadingStats() {
- if (!GetFrame().GetDocument()->GetFrame() ||
- !GetFrame().IsCrossOriginSubframe())
- return;
-
- LocalFrameView* parent = ParentFrameView();
- if (!parent) {
- HTMLFrameOwnerElement* element = GetFrame().DeprecatedLocalOwner();
- // We would fall into an else block on some teardowns and other weird cases.
- if (!element || !element->GetLayoutObject()) {
- GetFrame().GetDocument()->RecordDeferredLoadReason(
- WouldLoadReason::kNoParent);
- }
- return;
- }
- // Small inaccuracy: frames with origins that match the top level might be
- // nested in a cross-origin frame. To keep code simpler, count such frames as
- // WouldLoadVisible, even when their parent is offscreen.
- WouldLoadReason why_parent_loaded = WouldLoadReason::kVisible;
- if (parent->ParentFrameView() && parent->GetFrame().IsCrossOriginSubframe())
- why_parent_loaded = parent->GetFrame().GetDocument()->DeferredLoadReason();
-
- // If the parent wasn't loaded, the children won't be either.
- if (why_parent_loaded == WouldLoadReason::kCreated)
- return;
- // These frames are never meant to be seen so we will need to load them.
- IntRect frame_rect(FrameRect());
- if (frame_rect.IsEmpty() || frame_rect.MaxY() < 0 || frame_rect.MaxX() < 0) {
- GetFrame().GetDocument()->RecordDeferredLoadReason(why_parent_loaded);
- return;
- }
-
- IntSize parent_size(parent->Size());
- // First clause: for this rough data collection we assume the user never
- // scrolls right.
- if (frame_rect.X() >= parent_size.Width() || parent_size.Height() <= 0)
- return;
-
- int this_frame_screens_away = 0;
- // If an frame is created above the current scoll position, this logic counts
- // it as visible.
- if (frame_rect.Y() > 0)
- this_frame_screens_away = frame_rect.Y() / parent_size.Height();
- DCHECK_GE(this_frame_screens_away, 0);
-
- int parent_screens_away = 0;
- if (why_parent_loaded <= WouldLoadReason::kVisible) {
- parent_screens_away = static_cast<int>(WouldLoadReason::kVisible) -
- static_cast<int>(why_parent_loaded);
- }
-
- int total_screens_away = this_frame_screens_away + parent_screens_away;
-
- // We're collecting data for frames that are at most 3 screens away.
- if (total_screens_away > 3)
- return;
-
- GetFrame().GetDocument()->RecordDeferredLoadReason(
- static_cast<WouldLoadReason>(static_cast<int>(WouldLoadReason::kVisible) -
- total_screens_away));
-}
-
void LocalFrameView::SetNeedsForcedCompositingUpdate() {
needs_forced_compositing_update_ = true;
if (LocalFrameView* parent = ParentFrameView())
@@ -4249,7 +4186,7 @@ void LocalFrameView::BeginLifecycleUpdates() {
bool layout_view_is_empty = layout_view && !layout_view->FirstChild();
if (layout_view_is_empty && !DidFirstLayout() && !NeedsLayout()) {
// Make sure a display:none iframe gets an initial layout pass.
- layout_view->SetNeedsLayout(LayoutInvalidationReason::kAddedToLayout,
+ layout_view->SetNeedsLayout(layout_invalidation_reason::kAddedToLayout,
kMarkOnlyThis);
}
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_view.h b/chromium/third_party/blink/renderer/core/frame/local_frame_view.h
index 421db4044fc..7c8923a7894 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_view.h
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_view.h
@@ -78,7 +78,7 @@ class Page;
class PaintArtifactCompositor;
class PaintController;
class PaintLayerScrollableArea;
-class PaintTracker;
+class PaintTimingDetector;
class PrintContext;
class RootFrameViewport;
class ScrollableArea;
@@ -110,6 +110,7 @@ class CORE_EXPORT LocalFrameView final
static LocalFrameView* Create(LocalFrame&);
static LocalFrameView* Create(LocalFrame&, const IntSize& initial_size);
+ explicit LocalFrameView(LocalFrame&, IntRect);
~LocalFrameView() override;
void Invalidate() { InvalidateRect(IntRect(0, 0, Width(), Height())); }
@@ -270,10 +271,10 @@ class CORE_EXPORT LocalFrameView final
void SetDisplayShape(DisplayShape);
// Fixed-position objects.
- typedef HashSet<LayoutObject*> ViewportConstrainedObjectSet;
+ typedef HashSet<LayoutObject*> ObjectSet;
void AddViewportConstrainedObject(LayoutObject&);
void RemoveViewportConstrainedObject(LayoutObject&);
- const ViewportConstrainedObjectSet* ViewportConstrainedObjects() const {
+ const ObjectSet* ViewportConstrainedObjects() const {
return viewport_constrained_objects_.get();
}
bool HasViewportConstrainedObjects() const {
@@ -287,8 +288,12 @@ class CORE_EXPORT LocalFrameView final
bool HasBackgroundAttachmentFixedObjects() const {
return background_attachment_fixed_objects_.size();
}
+ const ObjectSet& BackgroundAttachmentFixedObjects() const {
+ return background_attachment_fixed_objects_;
+ }
bool HasBackgroundAttachmentFixedDescendants(const LayoutObject&) const;
- void InvalidateBackgroundAttachmentFixedDescendants(const LayoutObject&);
+ void InvalidateBackgroundAttachmentFixedDescendantsOnScroll(
+ const LayoutObject& scrolled_object);
void HandleLoadCompleted();
@@ -315,8 +320,10 @@ class CORE_EXPORT LocalFrameView final
// be in the lifecycle state PaintClean. If lifecycle throttling is allowed
// (see DocumentLifecycle::AllowThrottlingScope), some frames may skip the
// lifecycle update (e.g., based on visibility) and will not end up being
- // PaintClean.
- void UpdateAllLifecyclePhases();
+ // PaintClean. Set |reason| to indicate the reason for this update,
+ // for metrics purposes.
+ void UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason reason);
// Computes the style, layout, compositing and pre-paint lifecycle stages
// if needed.
@@ -679,7 +686,12 @@ class CORE_EXPORT LocalFrameView final
void ScrollAndFocusFragmentAnchor();
JankTracker& GetJankTracker() { return *jank_tracker_; }
- PaintTracker& GetPaintTracker() { return *paint_tracker_; }
+ PaintTimingDetector& GetPaintTimingDetector() const {
+ return *paint_timing_detector_;
+ }
+
+ // Return the UKM aggregator for this frame, creating it if necessary.
+ LocalFrameUkmAggregator& EnsureUkmAggregator();
protected:
void NotifyFrameRectsChangedIfNeeded();
@@ -713,8 +725,6 @@ class CORE_EXPORT LocalFrameView final
};
#endif
- explicit LocalFrameView(LocalFrame&, IntRect);
-
void PaintInternal(GraphicsContext&,
const GlobalPaintFlags,
const CullRect&) const;
@@ -729,7 +739,8 @@ class CORE_EXPORT LocalFrameView final
// Returns whether the lifecycle was succesfully updated to the
// target state.
- bool UpdateLifecyclePhases(DocumentLifecycle::LifecycleState target_state);
+ bool UpdateLifecyclePhases(DocumentLifecycle::LifecycleState target_state,
+ DocumentLifecycle::LifecycleUpdateReason reason);
// The internal version that does the work after the proper context and checks
// have passed in the above function call.
void UpdateLifecyclePhasesInternal(
@@ -747,11 +758,9 @@ class CORE_EXPORT LocalFrameView final
void RunPaintLifecyclePhase();
void NotifyFrameRectsChangedIfNeededRecursive();
- void UpdateStyleAndLayoutIfNeededRecursive();
void PrePaint();
void PaintTree();
-
- void UpdateStyleAndLayoutIfNeededRecursiveInternal();
+ void UpdateStyleAndLayoutIfNeededRecursive();
void PushPaintArtifactToCompositor(
CompositorElementIdSet& composited_element_ids);
@@ -762,8 +771,6 @@ class CORE_EXPORT LocalFrameView final
void PerformLayout(bool in_subtree_layout);
void PerformPostLayoutTasks();
- void RecordDeferredLoadingStats();
-
DocumentLifecycle& Lifecycle() const;
// Methods to do point conversion via layoutObjects, in order to take
@@ -828,8 +835,6 @@ class CORE_EXPORT LocalFrameView final
void LayoutFromRootObject(LayoutObject& root);
- LocalFrameUkmAggregator& EnsureUkmAggregator();
-
LayoutSize size_;
typedef HashSet<scoped_refptr<LayoutEmbeddedObject>> EmbeddedObjectSet;
@@ -879,9 +884,9 @@ class CORE_EXPORT LocalFrameView final
Member<ScrollableAreaSet> scrollable_areas_;
Member<ScrollableAreaSet> animating_scrollable_areas_;
std::unique_ptr<ResizerAreaSet> resizer_areas_;
- std::unique_ptr<ViewportConstrainedObjectSet> viewport_constrained_objects_;
+ std::unique_ptr<ObjectSet> viewport_constrained_objects_;
unsigned sticky_position_object_count_;
- ViewportConstrainedObjectSet background_attachment_fixed_objects_;
+ ObjectSet background_attachment_fixed_objects_;
Member<FrameViewAutoSizeInfo> auto_size_info_;
float input_events_scale_factor_for_emulation_;
@@ -972,7 +977,7 @@ class CORE_EXPORT LocalFrameView final
UniqueObjectId unique_id_;
std::unique_ptr<JankTracker> jank_tracker_;
- Member<PaintTracker> paint_tracker_;
+ Member<PaintTimingDetector> paint_timing_detector_;
FRIEND_TEST_ALL_PREFIXES(WebViewTest, DeviceEmulationResetScrollbars);
};
diff --git a/chromium/third_party/blink/renderer/core/frame/local_frame_view_test.cc b/chromium/third_party/blink/renderer/core/frame/local_frame_view_test.cc
index 24d0f3390e7..058ac945f74 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame_view_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame_view_test.cc
@@ -78,10 +78,10 @@ class LocalFrameViewTest : public RenderingTest {
TEST_F(LocalFrameViewTest, SetPaintInvalidationDuringUpdateAllLifecyclePhases) {
SetBodyInnerHTML("<div id='a' style='color: blue'>A</div>");
- GetDocument().getElementById("a")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("a")->setAttribute(html_names::kStyleAttr,
"color: green");
GetAnimationMockChromeClient().has_scheduled_animation_ = false;
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetAnimationMockChromeClient().has_scheduled_animation_);
}
@@ -100,7 +100,7 @@ TEST_F(LocalFrameViewTest, SetPaintInvalidationOutOfUpdateAllLifecyclePhases) {
->SetShouldDoFullPaintInvalidation();
EXPECT_TRUE(GetAnimationMockChromeClient().has_scheduled_animation_);
GetAnimationMockChromeClient().has_scheduled_animation_ = false;
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetAnimationMockChromeClient().has_scheduled_animation_);
}
diff --git a/chromium/third_party/blink/renderer/core/frame/location.h b/chromium/third_party/blink/renderer/core/frame/location.h
index 0b83297023e..18853bec66f 100644
--- a/chromium/third_party/blink/renderer/core/frame/location.h
+++ b/chromium/third_party/blink/renderer/core/frame/location.h
@@ -54,9 +54,11 @@ class CORE_EXPORT Location final : public ScriptWrappable {
public:
static Location* Create(DOMWindow* dom_window) {
- return new Location(dom_window);
+ return MakeGarbageCollected<Location>(dom_window);
}
+ explicit Location(DOMWindow*);
+
DOMWindow* DomWindow() const { return dom_window_.Get(); }
void setHref(LocalDOMWindow* current_window,
@@ -125,8 +127,6 @@ class CORE_EXPORT Location final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit Location(DOMWindow*);
-
// Note: it is only valid to call this if this is a Location object for a
// LocalDOMWindow.
Document* GetDocument() const;
diff --git a/chromium/third_party/blink/renderer/core/frame/mhtml_archive_test.cc b/chromium/third_party/blink/renderer/core/frame/mhtml_archive_test.cc
index b29a8d5dc9b..82125009a35 100644
--- a/chromium/third_party/blink/renderer/core/frame/mhtml_archive_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/mhtml_archive_test.cc
@@ -30,6 +30,7 @@
#include <map>
+#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/date_components.h"
@@ -44,7 +45,8 @@
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
-using blink::URLTestHelpers::ToKURL;
+using blink::url_test_helpers::ToKURL;
+using LoadResult = blink::MHTMLArchive::LoadResult;
namespace blink {
namespace test {
@@ -144,7 +146,8 @@ class MHTMLArchiveTest : public testing::Test {
MHTMLArchive::EncodingPolicy encoding_policy,
const KURL& url,
const String& title,
- const String& mime_type) {
+ const String& mime_type,
+ bool validate) {
// This boundary is as good as any other. Plus it gets used in almost
// all the examples in the MHTML spec - RFC 2557.
String boundary = String::FromUTF8("boundary-example");
@@ -157,18 +160,21 @@ class MHTMLArchiveTest : public testing::Test {
}
MHTMLArchive::GenerateMHTMLFooterForTesting(boundary, mhtml_data_);
- // Validate the generated MHTML.
- MHTMLParser parser(
- SharedBuffer::Create(mhtml_data_.data(), mhtml_data_.size()));
- EXPECT_FALSE(parser.ParseArchive().IsEmpty())
- << "Generated MHTML is malformed";
+ if (validate) {
+ // Validate the generated MHTML.
+ MHTMLParser parser(
+ SharedBuffer::Create(mhtml_data_.data(), mhtml_data_.size()));
+ EXPECT_FALSE(parser.ParseArchive().IsEmpty())
+ << "Generated MHTML is malformed";
+ }
}
void Serialize(const KURL& url,
const String& title,
const String& mime,
MHTMLArchive::EncodingPolicy encoding_policy) {
- return GenerateMHTMLData(resources_, encoding_policy, url, title, mime);
+ return GenerateMHTMLData(resources_, encoding_policy, url, title, mime,
+ true);
}
Vector<char>& mhtml_data() { return mhtml_data_; }
@@ -176,6 +182,24 @@ class MHTMLArchiveTest : public testing::Test {
WTF::Time mhtml_date() const { return mhtml_date_; }
const String& mhtml_date_header() const { return mhtml_date_header_; }
+ void CheckLoadResult(const KURL url,
+ scoped_refptr<const SharedBuffer> data,
+ LoadResult expected_result) {
+ // Set up histogram testing (takes snapshot of histogram data).
+ base::HistogramTester histogram_tester;
+
+ // Attempt loading the archive and check the returned pointer.
+ MHTMLArchive* archive = MHTMLArchive::Create(url, data);
+ if (expected_result == LoadResult::kSuccess)
+ EXPECT_NE(nullptr, archive);
+ else
+ EXPECT_EQ(nullptr, archive);
+
+ // Check that the correct count, and only the correct count, increased.
+ histogram_tester.ExpectUniqueSample(MHTMLArchive::kLoadResultUmaName,
+ expected_result, 1);
+ }
+
private:
scoped_refptr<SharedBuffer> ReadFile(const char* file_name) {
String file_path = file_path_ + file_name;
@@ -339,16 +363,19 @@ TEST_F(MHTMLArchiveTest, MHTMLFromScheme) {
// MHTMLArchives can only be initialized from local schemes, http/https
// schemes, and content scheme(Android specific).
- EXPECT_NE(nullptr, MHTMLArchive::Create(http_url, data.get()));
+ CheckLoadResult(http_url, data.get(), LoadResult::kSuccess);
+
#if defined(OS_ANDROID)
- EXPECT_NE(nullptr, MHTMLArchive::Create(content_url, data.get()));
+ CheckLoadResult(content_url, data.get(), LoadResult::kSuccess);
#else
- EXPECT_EQ(nullptr, MHTMLArchive::Create(content_url, data.get()));
+ CheckLoadResult(content_url, data.get(), LoadResult::kUrlSchemeNotAllowed);
#endif
- EXPECT_NE(nullptr, MHTMLArchive::Create(file_url, data.get()));
- EXPECT_EQ(nullptr, MHTMLArchive::Create(special_scheme_url, data.get()));
+ CheckLoadResult(file_url, data.get(), LoadResult::kSuccess);
+ CheckLoadResult(special_scheme_url, data.get(),
+ LoadResult::kUrlSchemeNotAllowed);
+
SchemeRegistry::RegisterURLSchemeAsLocal("fooscheme");
- EXPECT_NE(nullptr, MHTMLArchive::Create(special_scheme_url, data.get()));
+ CheckLoadResult(special_scheme_url, data.get(), LoadResult::kSuccess);
}
TEST_F(MHTMLArchiveTest, MHTMLDate) {
@@ -373,12 +400,15 @@ TEST_F(MHTMLArchiveTest, MHTMLDate) {
}
TEST_F(MHTMLArchiveTest, EmptyArchive) {
- char* buf = nullptr;
+ // Test failure to load when |data| is null.
+ KURL http_url = ToKURL("http://www.example.com");
+ CheckLoadResult(http_url, nullptr, LoadResult::kEmptyFile);
+
+ // Test failure to load when |data| is non-null but empty.
+ const char* buf = "";
scoped_refptr<SharedBuffer> data =
SharedBuffer::Create(buf, static_cast<size_t>(0u));
- KURL http_url = ToKURL("http://www.example.com");
- MHTMLArchive* archive = MHTMLArchive::Create(http_url, data.get());
- EXPECT_EQ(nullptr, archive);
+ CheckLoadResult(http_url, data.get(), LoadResult::kEmptyFile);
}
TEST_F(MHTMLArchiveTest, NoMainResource) {
@@ -393,9 +423,21 @@ TEST_F(MHTMLArchiveTest, NoMainResource) {
scoped_refptr<SharedBuffer> data =
SharedBuffer::Create(mhtml_data().data(), mhtml_data().size());
KURL http_url = ToKURL("http://www.example.com");
- MHTMLArchive* archive = MHTMLArchive::Create(http_url, data.get());
- EXPECT_EQ(nullptr, archive);
+ CheckLoadResult(http_url, data.get(), LoadResult::kMissingMainResource);
+}
+
+TEST_F(MHTMLArchiveTest, InvalidMHTML) {
+ const char kURL[] = "http://www.example.com";
+ // Intentionally create MHTML data with no resources.
+ Vector<SerializedResource> resources;
+ GenerateMHTMLData(resources, MHTMLArchive::kUseDefaultEncoding, ToKURL(kURL),
+ "Test invalid mhtml", "text/html", false);
+
+ scoped_refptr<SharedBuffer> data =
+ SharedBuffer::Create(mhtml_data().data(), mhtml_data().size());
+
+ CheckLoadResult(ToKURL(kURL), data.get(), LoadResult::kInvalidArchive);
}
} // namespace test
diff --git a/chromium/third_party/blink/renderer/core/frame/mhtml_loading_test.cc b/chromium/third_party/blink/renderer/core/frame/mhtml_loading_test.cc
index cba070e9822..65dd524db54 100644
--- a/chromium/third_party/blink/renderer/core/frame/mhtml_loading_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/mhtml_loading_test.cc
@@ -50,7 +50,7 @@
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
-using blink::URLTestHelpers::ToKURL;
+using blink::url_test_helpers::ToKURL;
namespace blink {
namespace test {
@@ -69,21 +69,21 @@ class MHTMLLoadingTest : public testing::Test {
void RegisterMockedURLLoad(const std::string& url,
const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url),
test::CoreTestDataPath(WebString::FromUTF8("mhtml/" + file_name)),
WebString::FromUTF8("multipart/related"));
}
void LoadURLInTopFrame(const WebURL& url) {
- FrameTestHelpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
- url.GetString().Utf8().data());
+ frame_test_helpers::LoadFrame(helper_.GetWebView()->MainFrameImpl(),
+ url.GetString().Utf8().data());
}
Page* GetPage() const { return helper_.GetWebView()->GetPage(); }
private:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc b/chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc
new file mode 100644
index 00000000000..625602adde2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc
@@ -0,0 +1,63 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+#include "third_party/blink/renderer/core/frame/navigation_rate_limiter.h"
+#include "third_party/blink/renderer/core/frame/frame.h"
+#include "third_party/blink/renderer/core/frame/frame_console.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
+#include "third_party/blink/renderer/core/inspector/console_message.h"
+
+namespace blink {
+
+NavigationRateLimiter::NavigationRateLimiter(Frame& frame)
+ : frame_(frame),
+ time_first_count_(base::TimeTicks::Now()),
+ enabled(frame_->GetSettings()->GetShouldProtectAgainstIpcFlooding()) {}
+
+void NavigationRateLimiter::Trace(blink::Visitor* visitor) {
+ visitor->Trace(frame_);
+}
+
+bool NavigationRateLimiter::CanProceed() {
+ if (!enabled)
+ return true;
+
+ // The aim is to roughly enable 20 same-document navigation per second, but we
+ // express it as 200 per 10 seconds because some use cases (including tests)
+ // do more than 20 updates in 1 second. But over time, applications shooting
+ // for more should work. If necessary to support legitimate applications, we
+ // can increase this threshold somewhat.
+ static constexpr int kStateUpdateLimit = 200;
+ static constexpr base::TimeDelta kStateUpdateLimitResetInterval =
+ base::TimeDelta::FromSeconds(10);
+
+ if (++count_ <= kStateUpdateLimit)
+ return true;
+
+ const base::TimeTicks now = base::TimeTicks::Now();
+ if (now - time_first_count_ > kStateUpdateLimitResetInterval) {
+ time_first_count_ = now;
+ count_ = 1;
+ error_message_sent_ = false;
+ return true;
+ }
+
+ // Display an error message. Do it only once in a while, else it will flood
+ // the browser process with the FrameHostMsg_DidAddMessageToConsole IPC.
+ if (!error_message_sent_) {
+ error_message_sent_ = true;
+ if (frame_->IsLocalFrame()) {
+ ToLocalFrame(frame_)->Console().AddMessage(ConsoleMessage::Create(
+ kJSMessageSource, kWarningMessageLevel,
+ "Throttling navigation to prevent the browser from hanging. See "
+ "https://crbug.com/882238. Command line switch "
+ "--disable-ipc-flooding-protection can be used to bypass the "
+ "protection"));
+ }
+ }
+
+ return false;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.h b/chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.h
new file mode 100644
index 00000000000..0250fc245f7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/frame/navigation_rate_limiter.h
@@ -0,0 +1,42 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_NAVIGATION_RATE_LIMITER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_NAVIGATION_RATE_LIMITER_H_
+
+#include "base/time/time.h"
+#include "third_party/blink/renderer/platform/heap/member.h"
+
+namespace blink {
+class Visitor;
+class Frame;
+
+// TODO(https://crbug.com/394296, https://crbug.com/882238)
+// Prevent the renderer process to flood the browser process by sending IPC for
+// same-document navigations.
+// This is not the long-term fix to IPC flooding. However, it mitigate the
+// immediate concern assuming the renderer has not been compromised.
+class NavigationRateLimiter final {
+ DISALLOW_NEW();
+
+ public:
+ explicit NavigationRateLimiter(Frame&);
+
+ // Notify this object a new navigation is requested. Return true if this one
+ // is allowed to proceed.
+ bool CanProceed();
+
+ void Trace(blink::Visitor*);
+
+ private:
+ Member<Frame> frame_;
+ base::TimeTicks time_first_count_;
+ int count_ = 0;
+ bool enabled;
+
+ bool error_message_sent_ = false;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_NAVIGATION_RATE_LIMITER_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator.h b/chromium/third_party/blink/renderer/core/frame/navigator.h
index 333194a0514..68d88ddaf08 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator.h
+++ b/chromium/third_party/blink/renderer/core/frame/navigator.h
@@ -48,7 +48,11 @@ class CORE_EXPORT Navigator final : public ScriptWrappable,
USING_GARBAGE_COLLECTED_MIXIN(Navigator);
public:
- static Navigator* Create(LocalFrame* frame) { return new Navigator(frame); }
+ static Navigator* Create(LocalFrame* frame) {
+ return MakeGarbageCollected<Navigator>(frame);
+ }
+
+ explicit Navigator(LocalFrame*);
// NavigatorCookies
bool cookieEnabled() const;
@@ -66,9 +70,6 @@ class CORE_EXPORT Navigator final : public ScriptWrappable,
Vector<String> languages() override;
void Trace(blink::Visitor*) override;
-
- private:
- explicit Navigator(LocalFrame*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator_concurrent_hardware.cc b/chromium/third_party/blink/renderer/core/frame/navigator_concurrent_hardware.cc
index 800e852502e..c72ae254e9d 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator_concurrent_hardware.cc
+++ b/chromium/third_party/blink/renderer/core/frame/navigator_concurrent_hardware.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/frame/navigator_concurrent_hardware.h"
-#include "base/sys_info.h"
+#include "base/system/sys_info.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.cc b/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.cc
index 2c7b3a5e528..775364d0074 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.cc
+++ b/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.cc
@@ -16,7 +16,7 @@ NavigatorUserActivation& NavigatorUserActivation::From(Navigator& navigator) {
NavigatorUserActivation* supplement =
Supplement<Navigator>::From<NavigatorUserActivation>(navigator);
if (!supplement) {
- supplement = new NavigatorUserActivation(navigator);
+ supplement = MakeGarbageCollected<NavigatorUserActivation>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.h b/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.h
index a99263535f2..0baeffb2ca9 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.h
+++ b/chromium/third_party/blink/renderer/core/frame/navigator_user_activation.h
@@ -24,11 +24,11 @@ class CORE_EXPORT NavigatorUserActivation final
static UserActivation* userActivation(Navigator& navigator);
UserActivation* userActivation();
+ explicit NavigatorUserActivation(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorUserActivation(Navigator&);
-
static NavigatorUserActivation& From(Navigator&);
Member<UserActivation> user_activation_;
diff --git a/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.cc b/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.cc
index d483fca0a80..9911e246571 100644
--- a/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.cc
+++ b/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.cc
@@ -33,7 +33,7 @@
#include <algorithm>
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.h b/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.h
index 57c85d2b657..3571f7b5266 100644
--- a/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.h
+++ b/chromium/third_party/blink/renderer/core/frame/page_scale_constraints_set.h
@@ -38,8 +38,8 @@
#include "third_party/blink/renderer/core/frame/page_scale_constraints.h"
#include "third_party/blink/renderer/core/page/viewport_description.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.cc b/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.cc
index dff54987198..322cb06f821 100644
--- a/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.cc
+++ b/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/public/web/web_script_execution_callback.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
@@ -18,7 +19,6 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -62,11 +62,13 @@ Vector<v8::Local<v8::Value>> WebScriptExecutor::Execute(LocalFrame* frame) {
// Note: An error event in an isolated world will never be dispatched to
// a foreign world.
v8::Local<v8::Value> script_value =
- world_id_ ? frame->GetScriptController().ExecuteScriptInIsolatedWorld(
- world_id_, source, KURL(), kSharableCrossOrigin)
- : frame->GetScriptController()
- .ExecuteScriptInMainWorldAndReturnValue(
- source, KURL(), kSharableCrossOrigin);
+ world_id_
+ ? frame->GetScriptController().ExecuteScriptInIsolatedWorld(
+ world_id_, source, KURL(),
+ SanitizeScriptErrors::kDoNotSanitize)
+ : frame->GetScriptController()
+ .ExecuteScriptInMainWorldAndReturnValue(
+ source, KURL(), SanitizeScriptErrors::kDoNotSanitize);
results.push_back(script_value);
}
@@ -138,7 +140,7 @@ PausableScriptExecutor* PausableScriptExecutor::Create(
bool user_gesture,
WebScriptExecutionCallback* callback) {
ScriptState* script_state = ToScriptState(frame, *world);
- return new PausableScriptExecutor(
+ return MakeGarbageCollected<PausableScriptExecutor>(
frame, script_state, callback,
new WebScriptExecutor(sources, world->GetWorldId(), user_gesture));
}
@@ -158,9 +160,10 @@ void PausableScriptExecutor::CreateAndRun(
callback->Completed(Vector<v8::Local<v8::Value>>());
return;
}
- PausableScriptExecutor* executor = new PausableScriptExecutor(
- frame, script_state, callback,
- new V8FunctionExecutor(isolate, function, receiver, argc, argv));
+ PausableScriptExecutor* executor =
+ MakeGarbageCollected<PausableScriptExecutor>(
+ frame, script_state, callback,
+ new V8FunctionExecutor(isolate, function, receiver, argc, argv));
executor->Run();
}
diff --git a/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.h b/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.h
index bc32d083aeb..c268810f799 100644
--- a/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.h
+++ b/chromium/third_party/blink/renderer/core/frame/pausable_script_executor.h
@@ -43,13 +43,6 @@ class CORE_EXPORT PausableScriptExecutor final
int argc,
v8::Local<v8::Value> argv[],
WebScriptExecutionCallback*);
- ~PausableScriptExecutor() override;
-
- void Run();
- void RunAsync(BlockingOption);
- void ContextDestroyed(ExecutionContext*) override;
-
- void Trace(blink::Visitor*) override;
class Executor : public GarbageCollectedFinalized<Executor> {
public:
@@ -60,12 +53,19 @@ class CORE_EXPORT PausableScriptExecutor final
virtual void Trace(blink::Visitor* visitor) {}
};
- private:
PausableScriptExecutor(LocalFrame*,
ScriptState*,
WebScriptExecutionCallback*,
Executor*);
+ ~PausableScriptExecutor() override;
+
+ void Run();
+ void RunAsync(BlockingOption);
+ void ContextDestroyed(ExecutionContext*) override;
+
+ void Trace(blink::Visitor*) override;
+ private:
void Fired() override;
void ExecuteAndDestroySelf();
diff --git a/chromium/third_party/blink/renderer/core/frame/pausable_task.cc b/chromium/third_party/blink/renderer/core/frame/pausable_task.cc
index 292f3a30c26..99b9d6a34c9 100644
--- a/chromium/third_party/blink/renderer/core/frame/pausable_task.cc
+++ b/chromium/third_party/blink/renderer/core/frame/pausable_task.cc
@@ -20,7 +20,7 @@ void PausableTask::Post(ExecutionContext* context,
} else {
// Manages its own lifetime and invokes the callback when script is
// unpaused.
- new PausableTask(context, std::move(callback));
+ MakeGarbageCollected<PausableTask>(context, std::move(callback));
}
}
diff --git a/chromium/third_party/blink/renderer/core/frame/pausable_task.h b/chromium/third_party/blink/renderer/core/frame/pausable_task.h
index 7c7a54cdafb..d5ff5e02e42 100644
--- a/chromium/third_party/blink/renderer/core/frame/pausable_task.h
+++ b/chromium/third_party/blink/renderer/core/frame/pausable_task.h
@@ -23,6 +23,8 @@ class CORE_EXPORT PausableTask final
USING_GARBAGE_COLLECTED_MIXIN(PausableTask);
public:
+ // Note: This asserts that the context is currently suspended.
+ PausableTask(ExecutionContext*, WebLocalFrame::PausableTaskCallback);
~PausableTask() override;
// Checks if the context is paused, and, if not, executes the callback
@@ -35,9 +37,6 @@ class CORE_EXPORT PausableTask final
void Fired() override;
private:
- // Note: This asserts that the context is currently suspended.
- PausableTask(ExecutionContext*, WebLocalFrame::PausableTaskCallback);
-
void Dispose();
WebLocalFrame::PausableTaskCallback callback_;
diff --git a/chromium/third_party/blink/renderer/core/frame/performance_monitor.cc b/chromium/third_party/blink/renderer/core/frame/performance_monitor.cc
index 7306f6c2351..40ebca757b3 100644
--- a/chromium/third_party/blink/renderer/core/frame/performance_monitor.cc
+++ b/chromium/third_party/blink/renderer/core/frame/performance_monitor.cc
@@ -75,7 +75,7 @@ PerformanceMonitor* PerformanceMonitor::InstrumentingMonitor(
PerformanceMonitor::PerformanceMonitor(LocalFrame* local_root)
: local_root_(local_root) {
std::fill(std::begin(thresholds_), std::end(thresholds_), base::TimeDelta());
- Platform::Current()->CurrentThread()->AddTaskTimeObserver(this);
+ Thread::Current()->AddTaskTimeObserver(this);
local_root_->GetProbeSink()->addPerformanceMonitor(this);
}
@@ -89,7 +89,7 @@ void PerformanceMonitor::Subscribe(Violation violation,
DCHECK(violation < kAfterLast);
ClientThresholds* client_thresholds = subscriptions_.at(violation);
if (!client_thresholds) {
- client_thresholds = new ClientThresholds();
+ client_thresholds = MakeGarbageCollected<ClientThresholds>();
subscriptions_.Set(violation, client_thresholds);
}
client_thresholds->Set(client, threshold);
@@ -107,7 +107,7 @@ void PerformanceMonitor::Shutdown() {
return;
subscriptions_.clear();
UpdateInstrumentation();
- Platform::Current()->CurrentThread()->RemoveTaskTimeObserver(this);
+ Thread::Current()->RemoveTaskTimeObserver(this);
local_root_->GetProbeSink()->removePerformanceMonitor(this);
local_root_ = nullptr;
}
diff --git a/chromium/third_party/blink/renderer/core/frame/performance_monitor_test.cc b/chromium/third_party/blink/renderer/core/frame/performance_monitor_test.cc
index 4be237ce6a7..319bd6ec2d0 100644
--- a/chromium/third_party/blink/renderer/core/frame/performance_monitor_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/performance_monitor_test.cc
@@ -76,7 +76,7 @@ class PerformanceMonitorTest : public testing::Test {
void PerformanceMonitorTest::SetUp() {
page_holder_ = DummyPageHolder::Create(IntSize(800, 600));
page_holder_->GetDocument().SetURL(KURL("https://example.com/foo"));
- monitor_ = new PerformanceMonitor(GetFrame());
+ monitor_ = MakeGarbageCollected<PerformanceMonitor>(GetFrame());
// Create another dummy page holder and pretend this is the iframe.
another_page_holder_ = DummyPageHolder::Create(IntSize(400, 300));
diff --git a/chromium/third_party/blink/renderer/core/frame/platform_event_controller.h b/chromium/third_party/blink/renderer/core/frame/platform_event_controller.h
index e24c4661b2a..aab6f4adac3 100644
--- a/chromium/third_party/blink/renderer/core/frame/platform_event_controller.h
+++ b/chromium/third_party/blink/renderer/core/frame/platform_event_controller.h
@@ -9,8 +9,8 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/page/page_visibility_observer.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_dom_window.h b/chromium/third_party/blink/renderer/core/frame/remote_dom_window.h
index dd3ccb0283c..ccacdd3f462 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_dom_window.h
+++ b/chromium/third_party/blink/renderer/core/frame/remote_dom_window.h
@@ -14,9 +14,11 @@ namespace blink {
class RemoteDOMWindow final : public DOMWindow {
public:
static RemoteDOMWindow* Create(RemoteFrame& frame) {
- return new RemoteDOMWindow(frame);
+ return MakeGarbageCollected<RemoteDOMWindow>(frame);
}
+ explicit RemoteDOMWindow(RemoteFrame&);
+
RemoteFrame* GetFrame() const { return ToRemoteFrame(DOMWindow::GetFrame()); }
// EventTarget overrides:
@@ -35,8 +37,6 @@ class RemoteDOMWindow final : public DOMWindow {
Document* source) override;
private:
- explicit RemoteDOMWindow(RemoteFrame&);
-
// Intentionally private to prevent redundant checks when the type is
// already RemoteDOMWindow.
bool IsLocalDOMWindow() const override { return false; }
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame.cc b/chromium/third_party/blink/renderer/core/frame/remote_frame.cc
index d0f8b72a47f..1db7ea1e0f6 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame.cc
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame.cc
@@ -40,7 +40,7 @@ inline RemoteFrame::RemoteFrame(RemoteFrameClient* client,
RemoteFrame* RemoteFrame::Create(RemoteFrameClient* client,
Page& page,
FrameOwner* owner) {
- RemoteFrame* frame = new RemoteFrame(client, page, owner);
+ RemoteFrame* frame = MakeGarbageCollected<RemoteFrame>(client, page, owner);
PageScheduler* page_scheduler = page.GetPageScheduler();
if (frame->IsMainFrame() && page_scheduler)
page_scheduler->SetIsMainFrameLocal(false);
@@ -79,6 +79,9 @@ void RemoteFrame::ScheduleNavigation(Document& origin_document,
void RemoteFrame::Navigate(const FrameLoadRequest& passed_request,
WebFrameLoadType frame_load_type) {
+ if (!navigation_rate_limiter().CanProceed())
+ return;
+
FrameLoadRequest frame_request(passed_request);
// The process where this frame actually lives won't have sufficient
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame.h b/chromium/third_party/blink/renderer/core/frame/remote_frame.h
index 84173c07be1..a2d54a2dee2 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame.h
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame.h
@@ -25,6 +25,7 @@ class CORE_EXPORT RemoteFrame final : public Frame {
public:
static RemoteFrame* Create(RemoteFrameClient*, Page&, FrameOwner*);
+ RemoteFrame(RemoteFrameClient*, Page&, FrameOwner*);
~RemoteFrame() override;
// Frame overrides:
@@ -67,8 +68,6 @@ class CORE_EXPORT RemoteFrame final : public Frame {
bool IsIgnoredForHitTest() const;
private:
- RemoteFrame(RemoteFrameClient*, Page&, FrameOwner*);
-
// Frame protected overrides:
void DetachImpl(FrameDetachType) override;
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.cc b/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.cc
index b60c1a4d3d9..3a840c698e4 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.cc
@@ -41,7 +41,7 @@ RemoteFrameClientImpl::RemoteFrameClientImpl(WebRemoteFrameImpl* web_frame)
RemoteFrameClientImpl* RemoteFrameClientImpl::Create(
WebRemoteFrameImpl* web_frame) {
- return new RemoteFrameClientImpl(web_frame);
+ return MakeGarbageCollected<RemoteFrameClientImpl>(web_frame);
}
void RemoteFrameClientImpl::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.h b/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.h
index fa9ad8cb017..bfdd480b970 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.h
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame_client_impl.h
@@ -18,6 +18,8 @@ class RemoteFrameClientImpl final : public RemoteFrameClient {
public:
static RemoteFrameClientImpl* Create(WebRemoteFrameImpl*);
+ explicit RemoteFrameClientImpl(WebRemoteFrameImpl*);
+
void Trace(blink::Visitor*) override;
// FrameClient overrides:
@@ -56,8 +58,6 @@ class RemoteFrameClientImpl final : public RemoteFrameClient {
WebRemoteFrameImpl* GetWebFrame() const { return web_frame_; }
private:
- explicit RemoteFrameClientImpl(WebRemoteFrameImpl*);
-
Member<WebRemoteFrameImpl> web_frame_;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.cc b/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.cc
index fcbc661ab85..bdab3d1115b 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.cc
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/public/platform/web_resource_timing_info.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
+#include "third_party/blink/renderer/core/exported/web_remote_frame_impl.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/web_frame_widget_base.h"
@@ -18,7 +19,8 @@ namespace blink {
RemoteFrameOwner::RemoteFrameOwner(
SandboxFlags flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties& frame_owner_properties)
+ const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType frame_owner_element_type)
: sandbox_flags_(flags),
browsing_context_container_name_(
static_cast<String>(frame_owner_properties.name)),
@@ -30,7 +32,8 @@ RemoteFrameOwner::RemoteFrameOwner(
allow_payment_request_(frame_owner_properties.allow_payment_request),
is_display_none_(frame_owner_properties.is_display_none),
required_csp_(frame_owner_properties.required_csp),
- container_policy_(container_policy) {}
+ container_policy_(container_policy),
+ frame_owner_element_type_(frame_owner_element_type) {}
void RemoteFrameOwner::Trace(blink::Visitor* visitor) {
visitor->Trace(frame_);
@@ -65,6 +68,17 @@ void RemoteFrameOwner::DispatchLoad() {
web_frame->Client()->DispatchLoad();
}
+void RemoteFrameOwner::RenderFallbackContent(Frame* failed_frame) {
+ if (frame_owner_element_type_ != FrameOwnerElementType::kObject)
+ return;
+ DCHECK(failed_frame->IsLocalFrame());
+ LocalFrame* local_frame = ToLocalFrame(failed_frame);
+ DCHECK(local_frame->IsProvisional() || ContentFrame() == local_frame);
+ WebLocalFrameImpl::FromFrame(local_frame)
+ ->Client()
+ ->RenderFallbackContentInParentProcess();
+}
+
void RemoteFrameOwner::IntrinsicSizingInfoChanged() {
LocalFrame& local_frame = ToLocalFrame(*frame_);
IntrinsicSizingInfo intrinsic_sizing_info;
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.h b/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.h
index 4dfeab05280..2d3a436d5cb 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.h
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame_owner.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REMOTE_FRAME_OWNER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REMOTE_FRAME_OWNER_H_
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/web/web_frame_owner_properties.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/frame_owner.h"
@@ -26,11 +27,18 @@ class CORE_EXPORT RemoteFrameOwner final
static RemoteFrameOwner* Create(
SandboxFlags flags,
const ParsedFeaturePolicy& container_policy,
- const WebFrameOwnerProperties& frame_owner_properties) {
- return new RemoteFrameOwner(flags, container_policy,
- frame_owner_properties);
+ const WebFrameOwnerProperties& frame_owner_properties,
+ FrameOwnerElementType frame_owner_element_type) {
+ return MakeGarbageCollected<RemoteFrameOwner>(flags, container_policy,
+ frame_owner_properties,
+ frame_owner_element_type);
}
+ RemoteFrameOwner(SandboxFlags,
+ const ParsedFeaturePolicy&,
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType frame_owner_element_type);
+
// FrameOwner overrides:
Frame* ContentFrame() const override { return frame_.Get(); }
void SetContentFrame(Frame&) override;
@@ -39,9 +47,10 @@ class CORE_EXPORT RemoteFrameOwner final
void SetSandboxFlags(SandboxFlags flags) { sandbox_flags_ = flags; }
void AddResourceTiming(const ResourceTimingInfo&) override;
void DispatchLoad() override;
- // TODO(dcheng): Implement.
- bool CanRenderFallbackContent() const override { return false; }
- void RenderFallbackContent() override {}
+ bool CanRenderFallbackContent() const override {
+ return frame_owner_element_type_ == FrameOwnerElementType::kObject;
+ }
+ void RenderFallbackContent(Frame*) override;
void IntrinsicSizingInfoChanged() override;
AtomicString BrowsingContextContainerName() const override {
@@ -84,10 +93,6 @@ class CORE_EXPORT RemoteFrameOwner final
void Trace(blink::Visitor*) override;
private:
- RemoteFrameOwner(SandboxFlags,
- const ParsedFeaturePolicy&,
- const WebFrameOwnerProperties&);
-
// Intentionally private to prevent redundant checks when the type is
// already HTMLFrameOwnerElement.
bool IsLocal() const override { return false; }
@@ -104,6 +109,7 @@ class CORE_EXPORT RemoteFrameOwner final
bool is_display_none_;
WebString required_csp_;
ParsedFeaturePolicy container_policy_;
+ const FrameOwnerElementType frame_owner_element_type_;
};
DEFINE_TYPE_CASTS(RemoteFrameOwner,
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame_view.cc b/chromium/third_party/blink/renderer/core/frame/remote_frame_view.cc
index 3551d79e1df..f74fd56d6cc 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame_view.cc
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame_view.cc
@@ -58,7 +58,7 @@ void RemoteFrameView::DetachFromLayout() {
}
RemoteFrameView* RemoteFrameView::Create(RemoteFrame* remote_frame) {
- RemoteFrameView* view = new RemoteFrameView(remote_frame);
+ RemoteFrameView* view = MakeGarbageCollected<RemoteFrameView>(remote_frame);
view->Show();
return view;
}
@@ -258,7 +258,7 @@ void RemoteFrameView::Paint(GraphicsContext& context,
if (!context.Printing())
return;
- if (!rect.IntersectsCullRect(FrameRect()))
+ if (!rect.Intersects(FrameRect()))
return;
DrawingRecorder recorder(context, *GetFrame().OwnerLayoutObject(),
@@ -309,7 +309,7 @@ void RemoteFrameView::SetupRenderThrottling() {
if (!target_element)
return;
- visibility_observer_ = new ElementVisibilityObserver(
+ visibility_observer_ = MakeGarbageCollected<ElementVisibilityObserver>(
target_element, WTF::BindRepeating(
[](RemoteFrameView* remote_view, bool is_visible) {
remote_view->UpdateRenderThrottlingStatus(
diff --git a/chromium/third_party/blink/renderer/core/frame/remote_frame_view.h b/chromium/third_party/blink/renderer/core/frame/remote_frame_view.h
index a9732e5b85e..37e7179f1d4 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame_view.h
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame_view.h
@@ -30,6 +30,7 @@ class RemoteFrameView final : public GarbageCollectedFinalized<RemoteFrameView>,
public:
static RemoteFrameView* Create(RemoteFrame*);
+ explicit RemoteFrameView(RemoteFrame*);
~RemoteFrameView() override;
void AttachToLayout() override;
@@ -73,8 +74,6 @@ class RemoteFrameView final : public GarbageCollectedFinalized<RemoteFrameView>,
void Trace(blink::Visitor*) override;
private:
- explicit RemoteFrameView(RemoteFrame*);
-
LocalFrameView* ParentFrameView() const;
void UpdateRenderThrottlingStatus(bool hidden, bool subtree_throttled);
diff --git a/chromium/third_party/blink/renderer/core/frame/report.idl b/chromium/third_party/blink/renderer/core/frame/report.idl
index b1a271d8356..40d70444cc6 100644
--- a/chromium/third_party/blink/renderer/core/frame/report.idl
+++ b/chromium/third_party/blink/renderer/core/frame/report.idl
@@ -5,8 +5,7 @@
// https://github.com/WICG/reporting/blob/master/EXPLAINER.md#reportingobserver---observing-reports-from-javascript
[
- NoInterfaceObject,
- RuntimeEnabled=ReportingObserver
+ NoInterfaceObject
] interface Report {
readonly attribute DOMString type;
readonly attribute DOMString url;
diff --git a/chromium/third_party/blink/renderer/core/frame/report_body.idl b/chromium/third_party/blink/renderer/core/frame/report_body.idl
index 4ff3db08ff1..b11ae3f428b 100644
--- a/chromium/third_party/blink/renderer/core/frame/report_body.idl
+++ b/chromium/third_party/blink/renderer/core/frame/report_body.idl
@@ -5,7 +5,6 @@
// https://github.com/WICG/reporting/blob/master/EXPLAINER.md#reportingobserver---observing-reports-from-javascript
[
- NoInterfaceObject,
- RuntimeEnabled=ReportingObserver
+ NoInterfaceObject
] interface ReportBody {
};
diff --git a/chromium/third_party/blink/renderer/core/frame/reporting_context.cc b/chromium/third_party/blink/renderer/core/frame/reporting_context.cc
index aac718d505e..7692ab2209a 100644
--- a/chromium/third_party/blink/renderer/core/frame/reporting_context.cc
+++ b/chromium/third_party/blink/renderer/core/frame/reporting_context.cc
@@ -25,7 +25,7 @@ ReportingContext* ReportingContext::From(ExecutionContext* context) {
ReportingContext* reporting_context =
Supplement<ExecutionContext>::From<ReportingContext>(context);
if (!reporting_context) {
- reporting_context = new ReportingContext(*context);
+ reporting_context = MakeGarbageCollected<ReportingContext>(*context);
Supplement<ExecutionContext>::ProvideTo(*context, reporting_context);
}
return reporting_context;
diff --git a/chromium/third_party/blink/renderer/core/frame/reporting_observer.cc b/chromium/third_party/blink/renderer/core/frame/reporting_observer.cc
index 9147f97f682..a296b0485a8 100644
--- a/chromium/third_party/blink/renderer/core/frame/reporting_observer.cc
+++ b/chromium/third_party/blink/renderer/core/frame/reporting_observer.cc
@@ -10,20 +10,21 @@
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_context.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
ReportingObserver* ReportingObserver::Create(
ExecutionContext* execution_context,
V8ReportingObserverCallback* callback,
- ReportingObserverOptions options) {
- return new ReportingObserver(execution_context, callback, options);
+ ReportingObserverOptions* options) {
+ return MakeGarbageCollected<ReportingObserver>(execution_context, callback,
+ options);
}
ReportingObserver::ReportingObserver(ExecutionContext* execution_context,
V8ReportingObserverCallback* callback,
- ReportingObserverOptions options)
+ ReportingObserverOptions* options)
: ContextClient(execution_context),
execution_context_(execution_context),
callback_(callback),
@@ -59,16 +60,16 @@ void ReportingObserver::QueueReport(Report* report) {
}
bool ReportingObserver::ObservedType(const String& type) {
- return !options_.hasTypes() || options_.types().IsEmpty() ||
- options_.types().Find(type) != kNotFound;
+ return !options_->hasTypes() || options_->types().IsEmpty() ||
+ options_->types().Find(type) != kNotFound;
}
bool ReportingObserver::Buffered() {
- return options_.hasBuffered() && options_.buffered();
+ return options_->hasBuffered() && options_->buffered();
}
void ReportingObserver::ClearBuffered() {
- return options_.setBuffered(false);
+ return options_->setBuffered(false);
}
void ReportingObserver::observe() {
@@ -90,6 +91,7 @@ HeapVector<Member<Report>> ReportingObserver::takeRecords() {
void ReportingObserver::Trace(blink::Visitor* visitor) {
visitor->Trace(execution_context_);
visitor->Trace(callback_);
+ visitor->Trace(options_);
visitor->Trace(report_queue_);
ScriptWrappable::Trace(visitor);
ContextClient::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/frame/reporting_observer.h b/chromium/third_party/blink/renderer/core/frame/reporting_observer.h
index 4f358dc8c03..d0b37224817 100644
--- a/chromium/third_party/blink/renderer/core/frame/reporting_observer.h
+++ b/chromium/third_party/blink/renderer/core/frame/reporting_observer.h
@@ -27,7 +27,11 @@ class CORE_EXPORT ReportingObserver final
public:
static ReportingObserver* Create(ExecutionContext*,
V8ReportingObserverCallback*,
- ReportingObserverOptions);
+ ReportingObserverOptions*);
+
+ explicit ReportingObserver(ExecutionContext*,
+ V8ReportingObserverCallback*,
+ ReportingObserverOptions*);
// ActiveScriptWrappable
bool HasPendingActivity() const final;
@@ -56,13 +60,9 @@ class CORE_EXPORT ReportingObserver final
void Trace(blink::Visitor*) override;
private:
- explicit ReportingObserver(ExecutionContext*,
- V8ReportingObserverCallback*,
- ReportingObserverOptions);
-
Member<ExecutionContext> execution_context_;
TraceWrapperMember<V8ReportingObserverCallback> callback_;
- ReportingObserverOptions options_;
+ Member<ReportingObserverOptions> options_;
HeapVector<Member<Report>> report_queue_;
bool registered_;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/reporting_observer.idl b/chromium/third_party/blink/renderer/core/frame/reporting_observer.idl
index 0d273aebc30..a248a08fcd1 100644
--- a/chromium/third_party/blink/renderer/core/frame/reporting_observer.idl
+++ b/chromium/third_party/blink/renderer/core/frame/reporting_observer.idl
@@ -9,8 +9,7 @@ callback ReportingObserverCallback = void (sequence<Report> reports, ReportingOb
[
Constructor(ReportingObserverCallback callback, optional ReportingObserverOptions options),
ConstructorCallWith=ExecutionContext,
- ActiveScriptWrappable,
- RuntimeEnabled=ReportingObserver
+ ActiveScriptWrappable
] interface ReportingObserver {
void observe();
void disconnect();
diff --git a/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.cc b/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.cc
index 7292b061d18..b982371827a 100644
--- a/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.cc
+++ b/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.cc
@@ -8,6 +8,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/scroll_anchor.h"
+#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.h"
@@ -293,6 +294,19 @@ LayoutRect RootFrameViewport::ScrollIntoView(
if (params.GetScrollType() == kUserScroll)
new_scroll_offset = ClampToUserScrollableOffset(new_scroll_offset);
+ FloatPoint end_point = ScrollOffsetToPosition(new_scroll_offset);
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(gfx::ScrollOffset(end_point),
+ true, true);
+ if (GetLayoutBox()) {
+ end_point = GetLayoutBox()
+ ->GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*GetLayoutBox(), *strategy)
+ .value_or(end_point);
+ new_scroll_offset = ScrollPositionToOffset(end_point);
+ }
+
if (new_scroll_offset != GetScrollOffset()) {
if (params.is_for_scroll_sequence) {
DCHECK(params.GetScrollType() == kProgrammaticScroll ||
diff --git a/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.h b/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.h
index d9c8fe851c0..a18c1ed1b7e 100644
--- a/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.h
+++ b/chromium/third_party/blink/renderer/core/frame/root_frame_viewport.h
@@ -32,9 +32,13 @@ class CORE_EXPORT RootFrameViewport final
public:
static RootFrameViewport* Create(ScrollableArea& visual_viewport,
ScrollableArea& layout_viewport) {
- return new RootFrameViewport(visual_viewport, layout_viewport);
+ return MakeGarbageCollected<RootFrameViewport>(visual_viewport,
+ layout_viewport);
}
+ RootFrameViewport(ScrollableArea& visual_viewport,
+ ScrollableArea& layout_viewport);
+
void Trace(blink::Visitor*) override;
void SetLayoutViewport(ScrollableArea&);
@@ -121,9 +125,6 @@ class CORE_EXPORT RootFrameViewport final
ScrollbarTheme& GetPageScrollbarTheme() const override;
private:
- RootFrameViewport(ScrollableArea& visual_viewport,
- ScrollableArea& layout_viewport);
-
enum ViewportToScrollFirst { kVisualViewport, kLayoutViewport };
ScrollOffset ScrollOffsetFromScrollAnimators() const;
diff --git a/chromium/third_party/blink/renderer/core/frame/root_frame_viewport_test.cc b/chromium/third_party/blink/renderer/core/frame/root_frame_viewport_test.cc
index 1b6e230c2c9..50dfcfce455 100644
--- a/chromium/third_party/blink/renderer/core/frame/root_frame_viewport_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/root_frame_viewport_test.cc
@@ -31,9 +31,18 @@ class ScrollableAreaStub : public GarbageCollectedFinalized<ScrollableAreaStub>,
public:
static ScrollableAreaStub* Create(const IntSize& viewport_size,
const IntSize& contents_size) {
- return new ScrollableAreaStub(viewport_size, contents_size);
+ return MakeGarbageCollected<ScrollableAreaStub>(viewport_size,
+ contents_size);
}
+ ScrollableAreaStub(const IntSize& viewport_size, const IntSize& contents_size)
+ : user_input_scrollable_x_(true),
+ user_input_scrollable_y_(true),
+ viewport_size_(viewport_size),
+ contents_size_(contents_size),
+ timer_task_runner_(
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting()) {}
+
void SetViewportSize(const IntSize& viewport_size) {
viewport_size_ = viewport_size;
}
@@ -87,14 +96,6 @@ class ScrollableAreaStub : public GarbageCollectedFinalized<ScrollableAreaStub>,
}
protected:
- ScrollableAreaStub(const IntSize& viewport_size, const IntSize& contents_size)
- : user_input_scrollable_x_(true),
- user_input_scrollable_y_(true),
- viewport_size_(viewport_size),
- contents_size_(contents_size),
- timer_task_runner_(
- blink::scheduler::GetSingleThreadTaskRunnerForTesting()) {}
-
CompositorElementId GetCompositorElementId() const override {
return CompositorElementId();
}
@@ -143,9 +144,14 @@ class RootLayoutViewportStub : public ScrollableAreaStub {
public:
static RootLayoutViewportStub* Create(const IntSize& viewport_size,
const IntSize& contents_size) {
- return new RootLayoutViewportStub(viewport_size, contents_size);
+ return MakeGarbageCollected<RootLayoutViewportStub>(viewport_size,
+ contents_size);
}
+ RootLayoutViewportStub(const IntSize& viewport_size,
+ const IntSize& contents_size)
+ : ScrollableAreaStub(viewport_size, contents_size) {}
+
ScrollOffset MaximumScrollOffset() const override {
return ScrollOffset(ContentsSize() - ViewportSize());
}
@@ -157,10 +163,6 @@ class RootLayoutViewportStub : public ScrollableAreaStub {
}
private:
- RootLayoutViewportStub(const IntSize& viewport_size,
- const IntSize& contents_size)
- : ScrollableAreaStub(viewport_size, contents_size) {}
-
int VisibleWidth() const override { return viewport_size_.Width(); }
int VisibleHeight() const override { return viewport_size_.Height(); }
};
@@ -169,9 +171,13 @@ class VisualViewportStub : public ScrollableAreaStub {
public:
static VisualViewportStub* Create(const IntSize& viewport_size,
const IntSize& contents_size) {
- return new VisualViewportStub(viewport_size, contents_size);
+ return MakeGarbageCollected<VisualViewportStub>(viewport_size,
+ contents_size);
}
+ VisualViewportStub(const IntSize& viewport_size, const IntSize& contents_size)
+ : ScrollableAreaStub(viewport_size, contents_size), scale_(1) {}
+
ScrollOffset MaximumScrollOffset() const override {
ScrollOffset visible_viewport(ViewportSize());
visible_viewport.Scale(1 / scale_);
@@ -183,9 +189,6 @@ class VisualViewportStub : public ScrollableAreaStub {
void SetScale(float scale) { scale_ = scale; }
private:
- VisualViewportStub(const IntSize& viewport_size, const IntSize& contents_size)
- : ScrollableAreaStub(viewport_size, contents_size), scale_(1) {}
-
int VisibleWidth() const override { return viewport_size_.Width() / scale_; }
int VisibleHeight() const override {
return viewport_size_.Height() / scale_;
diff --git a/chromium/third_party/blink/renderer/core/frame/screen.h b/chromium/third_party/blink/renderer/core/frame/screen.h
index e1e9a35f534..06342fa8d66 100644
--- a/chromium/third_party/blink/renderer/core/frame/screen.h
+++ b/chromium/third_party/blink/renderer/core/frame/screen.h
@@ -46,7 +46,11 @@ class CORE_EXPORT Screen final : public ScriptWrappable,
USING_GARBAGE_COLLECTED_MIXIN(Screen);
public:
- static Screen* Create(LocalFrame* frame) { return new Screen(frame); }
+ static Screen* Create(LocalFrame* frame) {
+ return MakeGarbageCollected<Screen>(frame);
+ }
+
+ explicit Screen(LocalFrame*);
int height() const;
int width() const;
@@ -58,9 +62,6 @@ class CORE_EXPORT Screen final : public ScriptWrappable,
int availWidth() const;
void Trace(blink::Visitor*) override;
-
- private:
- explicit Screen(LocalFrame*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/settings.cc b/chromium/third_party/blink/renderer/core/frame/settings.cc
index 18f629d7b51..1c2bbcf5a96 100644
--- a/chromium/third_party/blink/renderer/core/frame/settings.cc
+++ b/chromium/third_party/blink/renderer/core/frame/settings.cc
@@ -62,8 +62,7 @@ static const bool kDefaultSelectTrailingWhitespaceEnabled = false;
#endif
Settings::Settings()
- : text_autosizing_enabled_(false),
- is_shadow_page_(false) SETTINGS_INITIALIZER_LIST {}
+ : text_autosizing_enabled_(false) SETTINGS_INITIALIZER_LIST {}
std::unique_ptr<Settings> Settings::Create() {
return base::WrapUnique(new Settings);
@@ -107,8 +106,4 @@ bool Settings::MockScrollbarsEnabled() {
return ScrollbarTheme::MockScrollbarsEnabled();
}
-void Settings::SetIsShadowPage(bool flag) {
- is_shadow_page_ = flag;
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/settings.h b/chromium/third_party/blink/renderer/core/frame/settings.h
index 30419bda906..5e6cede4f4c 100644
--- a/chromium/third_party/blink/renderer/core/frame/settings.h
+++ b/chromium/third_party/blink/renderer/core/frame/settings.h
@@ -88,12 +88,6 @@ class CORE_EXPORT Settings {
void SetDelegate(SettingsDelegate*);
- // TODO(lunalu): Service worker and shared worker count feature usage on the
- // blink side use counter via the shadow page. Once blink side use counter is
- // removed, this flag is no longer needed (crbug.com/811948).
- void SetIsShadowPage(bool);
- bool IsShadowPage() const { return is_shadow_page_; }
-
private:
Settings();
@@ -104,10 +98,6 @@ class CORE_EXPORT Settings {
GenericFontFamilySettings generic_font_family_settings_;
IntSize text_autosizing_window_size_override_;
bool text_autosizing_enabled_ : 1;
- // TODO(lunalu): Service worker is counting feature usage on the blink side
- // use counter via the shadow page. Once blink side use counter is removed,
- // this flag is no longer needed (crbug.com/811948).
- bool is_shadow_page_;
bool bypass_csp_ = false;
SETTINGS_MEMBER_VARIABLES
diff --git a/chromium/third_party/blink/renderer/core/frame/settings.json5 b/chromium/third_party/blink/renderer/core/frame/settings.json5
index db9341b931a..61e5873fd60 100644
--- a/chromium/third_party/blink/renderer/core/frame/settings.json5
+++ b/chromium/third_party/blink/renderer/core/frame/settings.json5
@@ -146,7 +146,7 @@
},
{
name: "acceleratedCompositingEnabled",
- initial: true,
+ initial: false,
invalidate: "AcceleratedCompositing",
},
@@ -947,10 +947,14 @@
type: "WebEffectiveConnectionType",
},
{
- name: "shouldThrottlePushState",
+ name: "shouldProtectAgainstIpcFlooding",
initial: true,
},
+ {
+ name: "lazyLoadEnabled",
+ initial: false,
+ },
//
// Lazy frame loading distance-from-viewport thresholds for different effective connection types.
//
diff --git a/chromium/third_party/blink/renderer/core/frame/smart_clip.cc b/chromium/third_party/blink/renderer/core/frame/smart_clip.cc
index 36046146061..dda9cb4b971 100644
--- a/chromium/third_party/blink/renderer/core/frame/smart_clip.cc
+++ b/chromium/third_party/blink/renderer/core/frame/smart_clip.cc
@@ -163,7 +163,7 @@ Node* SmartClip::FindBestOverlappingNode(Node* root_node,
if (node->IsElementNode() &&
DeprecatedEqualIgnoringCase(
- ToElement(node)->FastGetAttribute(HTMLNames::aria_hiddenAttr),
+ ToElement(node)->FastGetAttribute(html_names::kAriaHiddenAttr),
"true")) {
node = NodeTraversal::NextSkippingChildren(*node, root_node);
continue;
diff --git a/chromium/third_party/blink/renderer/core/frame/use_counter.h b/chromium/third_party/blink/renderer/core/frame/use_counter.h
index 469777e2c40..22481b447de 100644
--- a/chromium/third_party/blink/renderer/core/frame/use_counter.h
+++ b/chromium/third_party/blink/renderer/core/frame/use_counter.h
@@ -28,8 +28,8 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/use_counter_test.cc b/chromium/third_party/blink/renderer/core/frame/use_counter_test.cc
index abdd32bd61e..a48eba7d023 100644
--- a/chromium/third_party/blink/renderer/core/frame/use_counter_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/use_counter_test.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/use_counter/css_property_id.mojom-blink.h"
-#include "third_party/blink/renderer/core/css/css_test_helper.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
@@ -63,6 +62,11 @@ class UseCounterTest : public testing::Test {
UseCounter::Context context = UseCounter::kDefaultContext);
std::unique_ptr<DummyPageHolder> dummy_;
HistogramTester histogram_tester_;
+
+ void UpdateAllLifecyclePhases(Document& document) {
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
};
template <typename T>
@@ -100,7 +104,7 @@ void UseCounterTest::HistogramBasicTest(
// After a page load, the histograms will be updated, even when the URL
// scheme is internal
UseCounter use_counter1(context);
- SetURL(URLTestHelpers::ToKURL(url));
+ SetURL(url_test_helpers::ToKURL(url));
did_commit_load(GetFrame(), use_counter1);
histogram_tester_.ExpectBucketCount(histogram, histogram_map(item), 1);
histogram_tester_.ExpectBucketCount(histogram, histogram_map(second_item), 1);
@@ -150,16 +154,18 @@ TEST_F(UseCounterTest, SVGImageContextFeatures) {
kSvgUrl, UseCounter::kSVGImageContext);
}
-TEST_F(UseCounterTest, CSSSelectorPseudoIS) {
+TEST_F(UseCounterTest, CSSSelectorPseudoWhere) {
std::unique_ptr<DummyPageHolder> dummy_page_holder =
DummyPageHolder::Create(IntSize(800, 600));
Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
Document& document = dummy_page_holder->GetDocument();
- WebFeature feature = WebFeature::kCSSSelectorPseudoIS;
+ WebFeature feature = WebFeature::kCSSSelectorPseudoWhere;
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
document.documentElement()->SetInnerHTMLFromString(
- "<style>.a+:is(.b, .c+.d) { color: red; }</style>");
+ "<style>.a+:where(.b, .c+.d) { color: red; }</style>");
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
+ EXPECT_FALSE(
+ UseCounter::IsCounted(document, WebFeature::kCSSSelectorPseudoIs));
}
/*
@@ -205,16 +211,18 @@ TEST_F(UseCounterTest, CSSTypedOMStylePropertyMap) {
EXPECT_TRUE(use_counter.IsCounted(GetDocument(), feature));
}
-TEST_F(UseCounterTest, CSSSelectorPseudoMatches) {
+TEST_F(UseCounterTest, CSSSelectorPseudoIs) {
std::unique_ptr<DummyPageHolder> dummy_page_holder =
DummyPageHolder::Create(IntSize(800, 600));
Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
Document& document = dummy_page_holder->GetDocument();
- WebFeature feature = WebFeature::kCSSSelectorPseudoMatches;
+ WebFeature feature = WebFeature::kCSSSelectorPseudoIs;
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
document.documentElement()->SetInnerHTMLFromString(
- "<style>.a+:matches(.b, .c+.d) { color: red; }</style>");
+ "<style>.a+:is(.b, .c+.d) { color: red; }</style>");
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
+ EXPECT_FALSE(
+ UseCounter::IsCounted(document, WebFeature::kCSSSelectorPseudoWhere));
}
TEST_F(UseCounterTest, CSSContainLayoutNonPositionedDescendants) {
@@ -227,7 +235,7 @@ TEST_F(UseCounterTest, CSSContainLayoutNonPositionedDescendants) {
document.documentElement()->SetInnerHTMLFromString(
"<div style='contain: layout;'>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
}
@@ -242,7 +250,7 @@ TEST_F(UseCounterTest, CSSContainLayoutAbsolutelyPositionedDescendants) {
"<div style='contain: layout;'>"
" <div style='position: absolute;'></div>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
}
@@ -258,7 +266,7 @@ TEST_F(UseCounterTest,
"<div style='position: relative; contain: layout;'>"
" <div style='position: absolute;'></div>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
}
@@ -273,7 +281,7 @@ TEST_F(UseCounterTest, CSSContainLayoutFixedPositionedDescendants) {
"<div style='contain: layout;'>"
" <div style='position: fixed;'></div>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
}
@@ -289,7 +297,7 @@ TEST_F(UseCounterTest,
"<div style='transform: translateX(100px); contain: layout;'>"
" <div style='position: fixed;'></div>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
}
@@ -303,7 +311,7 @@ TEST_F(UseCounterTest, CSSGridLayoutPercentageColumnIndefiniteWidth) {
document.documentElement()->SetInnerHTMLFromString(
"<div style='display: inline-grid; grid-template-columns: 50%;'>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
}
@@ -317,7 +325,7 @@ TEST_F(UseCounterTest, CSSGridLayoutPercentageRowIndefiniteHeight) {
document.documentElement()->SetInnerHTMLFromString(
"<div style='display: inline-grid; grid-template-rows: 50%;'>"
"</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
}
@@ -330,7 +338,7 @@ TEST_F(UseCounterTest, CSSFlexibleBox) {
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
document.documentElement()->SetInnerHTMLFromString(
"<div style='display: flex;'>flexbox</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
}
@@ -343,7 +351,7 @@ TEST_F(UseCounterTest, CSSFlexibleBoxInline) {
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
document.documentElement()->SetInnerHTMLFromString(
"<div style='display: inline-flex;'>flexbox</div>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_TRUE(UseCounter::IsCounted(document, feature));
}
@@ -357,7 +365,7 @@ TEST_F(UseCounterTest, CSSFlexibleBoxButton) {
WebFeature feature = WebFeature::kCSSFlexibleBox;
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
document.documentElement()->SetInnerHTMLFromString("<button>button</button>");
- document.View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(document);
EXPECT_FALSE(UseCounter::IsCounted(document, feature));
}
@@ -411,4 +419,27 @@ TEST_F(DeprecationTest, InspectorDisablesDeprecation) {
EXPECT_TRUE(use_counter_.HasRecordedMeasurement(feature));
}
+TEST_F(UseCounterTest, CSSUnknownNamespacePrefixInSelector) {
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
+ Document& document = dummy_page_holder->GetDocument();
+ WebFeature feature = WebFeature::kCSSUnknownNamespacePrefixInSelector;
+ EXPECT_FALSE(UseCounter::IsCounted(document, feature));
+
+ document.documentElement()->SetInnerHTMLFromString(R"HTML(
+ <style>
+ @namespace svg url(http://www.w3.org/2000/svg);
+ svg|a {}
+ a {}
+ </style>
+ )HTML");
+ UpdateAllLifecyclePhases(document);
+ EXPECT_FALSE(UseCounter::IsCounted(document, feature));
+
+ document.documentElement()->SetInnerHTMLFromString("<style>foo|a {}</style>");
+ UpdateAllLifecyclePhases(document);
+ EXPECT_TRUE(UseCounter::IsCounted(document, feature));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/user_activation.cc b/chromium/third_party/blink/renderer/core/frame/user_activation.cc
index 5d575f14e27..788de7a1cce 100644
--- a/chromium/third_party/blink/renderer/core/frame/user_activation.cc
+++ b/chromium/third_party/blink/renderer/core/frame/user_activation.cc
@@ -10,12 +10,13 @@ namespace blink {
UserActivation* UserActivation::CreateSnapshot(LocalDOMWindow* window) {
LocalFrame* frame = window->GetFrame();
- return new UserActivation(frame ? frame->HasBeenActivated() : false,
- LocalFrame::HasTransientUserActivation(frame));
+ return MakeGarbageCollected<UserActivation>(
+ frame ? frame->HasBeenActivated() : false,
+ LocalFrame::HasTransientUserActivation(frame));
}
UserActivation* UserActivation::CreateLive(LocalDOMWindow* window) {
- return new UserActivation(window);
+ return MakeGarbageCollected<UserActivation>(window);
}
UserActivation::UserActivation(bool has_been_active, bool is_active)
diff --git a/chromium/third_party/blink/renderer/core/frame/user_activation.h b/chromium/third_party/blink/renderer/core/frame/user_activation.h
index b6da9d40649..7846c1eb2ea 100644
--- a/chromium/third_party/blink/renderer/core/frame/user_activation.h
+++ b/chromium/third_party/blink/renderer/core/frame/user_activation.h
@@ -22,6 +22,7 @@ class UserActivation final : public ScriptWrappable {
// Creates an instance that represents the live state of this LocalDOMWindow.
static UserActivation* CreateLive(LocalDOMWindow* window);
+ explicit UserActivation(LocalDOMWindow* window);
UserActivation(bool has_been_active, bool is_active);
~UserActivation() override;
@@ -31,8 +32,6 @@ class UserActivation final : public ScriptWrappable {
bool isActive() const;
private:
- explicit UserActivation(LocalDOMWindow* window);
-
Member<LocalDOMWindow> window_;
bool has_been_active_ = false;
bool is_active_ = false;
diff --git a/chromium/third_party/blink/renderer/core/frame/visual_viewport.cc b/chromium/third_party/blink/renderer/core/frame/visual_viewport.cc
index f72f6fec00f..071f9bd7a53 100644
--- a/chromium/third_party/blink/renderer/core/frame/visual_viewport.cc
+++ b/chromium/third_party/blink/renderer/core/frame/visual_viewport.cc
@@ -721,15 +721,6 @@ ChromeClient* VisualViewport::GetChromeClient() const {
return &GetPage().GetChromeClient();
}
-bool VisualViewport::ShouldUseIntegerScrollOffset() const {
- LocalFrame* frame = MainFrame();
- if (frame && frame->GetSettings() &&
- !frame->GetSettings()->GetPreferCompositingToLCDTextEnabled())
- return true;
-
- return ScrollableArea::ShouldUseIntegerScrollOffset();
-}
-
void VisualViewport::SetScrollOffset(const ScrollOffset& offset,
ScrollType scroll_type,
ScrollBehavior scroll_behavior) {
diff --git a/chromium/third_party/blink/renderer/core/frame/visual_viewport.h b/chromium/third_party/blink/renderer/core/frame/visual_viewport.h
index 4fe803daa7f..a3f08928337 100644
--- a/chromium/third_party/blink/renderer/core/frame/visual_viewport.h
+++ b/chromium/third_party/blink/renderer/core/frame/visual_viewport.h
@@ -92,7 +92,11 @@ class CORE_EXPORT VisualViewport final
USING_GARBAGE_COLLECTED_MIXIN(VisualViewport);
public:
- static VisualViewport* Create(Page& host) { return new VisualViewport(host); }
+ static VisualViewport* Create(Page& host) {
+ return MakeGarbageCollected<VisualViewport>(host);
+ }
+
+ explicit VisualViewport(Page&);
~VisualViewport() override;
void Trace(blink::Visitor*) override;
@@ -186,7 +190,6 @@ class CORE_EXPORT VisualViewport final
// ScrollableArea implementation
ChromeClient* GetChromeClient() const override;
- bool ShouldUseIntegerScrollOffset() const override;
void SetScrollOffset(const ScrollOffset&,
ScrollType,
ScrollBehavior = kScrollBehaviorInstant) override;
@@ -273,8 +276,6 @@ class CORE_EXPORT VisualViewport final
bool NeedsPaintPropertyUpdate() const { return needs_paint_property_update_; }
private:
- explicit VisualViewport(Page&);
-
bool DidSetScaleOrLocation(float scale, const FloatPoint& location);
diff --git a/chromium/third_party/blink/renderer/core/frame/visual_viewport_test.cc b/chromium/third_party/blink/renderer/core/frame/visual_viewport_test.cc
index 93621f8daef..9af2fe59732 100644
--- a/chromium/third_party/blink/renderer/core/frame/visual_viewport_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/visual_viewport_test.cc
@@ -59,7 +59,8 @@
using testing::_;
using testing::PrintToString;
using testing::Mock;
-using blink::URLTestHelpers::ToKURL;
+using testing::UnorderedElementsAre;
+using blink::url_test_helpers::ToKURL;
namespace blink {
@@ -70,8 +71,7 @@ namespace blink {
namespace {
-void configureAndroidCompositing(WebSettings* settings) {
- settings->SetAcceleratedCompositingEnabled(true);
+void ConfigureAndroidCompositing(WebSettings* settings) {
settings->SetPreferCompositingToLCDTextEnabled(true);
settings->SetViewportMetaEnabled(true);
settings->SetViewportEnabled(true);
@@ -109,20 +109,25 @@ class VisualViewportTest : public testing::Test,
}
void NavigateTo(const std::string& url) {
- FrameTestHelpers::LoadFrame(WebView()->MainFrameImpl(), url);
+ frame_test_helpers::LoadFrame(WebView()->MainFrameImpl(), url);
}
- void ForceFullCompositingUpdate() { WebView()->UpdateAllLifecyclePhases(); }
+ void UpdateAllLifecyclePhases() {
+ WebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
+ void ForceFullCompositingUpdate() { UpdateAllLifecyclePhases(); }
void RegisterMockedHttpURLLoad(const std::string& fileName) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), blink::test::CoreTestDataPath(),
WebString::FromUTF8(fileName));
}
void RegisterMockedHttpURLLoad(const std::string& url,
const std::string& fileName) {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ToKURL(url),
blink::test::CoreTestDataPath(WebString::FromUTF8(fileName)));
}
@@ -143,12 +148,68 @@ class VisualViewportTest : public testing::Test,
settings->SetMainFrameResizesAreOrientationChanges(true);
}
+ const GraphicsLayer* MainGraphicsLayer(const Document* document) {
+ const auto* layer = document->GetLayoutView()->Layer();
+ return layer->GetCompositedLayerMapping()
+ ? layer->GetCompositedLayerMapping()->MainGraphicsLayer()
+ : nullptr;
+ }
+
+ const GraphicsLayer* ScrollingContentsLayer(const Document* document) {
+ const auto* layer = document->GetLayoutView()->Layer();
+ return layer->GetCompositedLayerMapping()
+ ? layer->GetCompositedLayerMapping()->ScrollingContentsLayer()
+ : nullptr;
+ }
+
+ const DisplayItemClient& ScrollingBackgroundClient(const Document* document) {
+ return document->GetLayoutView()
+ ->GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
+ }
+
+ const RasterInvalidationTracking* MainGraphicsLayerRasterInvalidationTracking(
+ const Document* document) {
+ const auto* layer = MainGraphicsLayer(document);
+ return layer ? layer->GetRasterInvalidationTracking() : nullptr;
+ }
+
+ const RasterInvalidationTracking*
+ ScrollingContentsLayerRasterInvalidationTracking(const Document* document) {
+ const auto* layer = ScrollingContentsLayer(document);
+ return layer ? layer->GetRasterInvalidationTracking() : nullptr;
+ }
+
+ bool MainGraphicsLayerHasRasterInvalidations(const Document* document) {
+ const auto* tracking =
+ MainGraphicsLayerRasterInvalidationTracking(document);
+ return tracking && tracking->HasInvalidations();
+ }
+
+ bool ScrollingContentsLayerHasRasterInvalidations(const Document* document) {
+ const auto* tracking =
+ ScrollingContentsLayerRasterInvalidationTracking(document);
+ return tracking && tracking->HasInvalidations();
+ }
+
+ const Vector<RasterInvalidationInfo>& MainGraphicsLayerRasterInvalidations(
+ const Document* document) {
+ DCHECK(MainGraphicsLayerHasRasterInvalidations(document));
+ return MainGraphicsLayerRasterInvalidationTracking(document)
+ ->Invalidations();
+ }
+
+ const Vector<RasterInvalidationInfo>&
+ ScrollingContentsLayerRasterInvalidations(const Document* document) {
+ DCHECK(ScrollingContentsLayerHasRasterInvalidations(document));
+ return ScrollingContentsLayerRasterInvalidationTracking(document)
+ ->Invalidations();
+ }
+
protected:
std::string base_url_;
- FrameTestHelpers::TestWebViewClient mock_web_view_client_;
-
- private:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::TestWebViewClient mock_web_view_client_;
+ frame_test_helpers::WebViewHelper helper_;
};
INSTANTIATE_PAINT_TEST_CASE_P(VisualViewportTest);
@@ -315,7 +376,7 @@ TEST_P(VisualViewportTest, TestResizeAfterVerticalScroll) {
// Verify the paint property nodes and GeometryMapper cache.
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(TransformationMatrix().Scale(2),
visual_viewport.GetPageScaleNode()->Matrix());
EXPECT_EQ(TransformationMatrix().Translate(0, -300),
@@ -339,7 +400,7 @@ TEST_P(VisualViewportTest, TestResizeAfterVerticalScroll) {
// Verify the paint property nodes and GeometryMapper cache.
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(TransformationMatrix().Scale(4),
visual_viewport.GetPageScaleNode()->Matrix());
EXPECT_EQ(TransformationMatrix().Translate(0, -75),
@@ -403,7 +464,7 @@ TEST_P(VisualViewportTest, TestResizeAfterHorizontalScroll) {
// Verify the paint property nodes and GeometryMapper cache.
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(TransformationMatrix().Scale(2),
visual_viewport.GetPageScaleNode()->Matrix());
EXPECT_EQ(TransformationMatrix().Translate(-150, 0),
@@ -426,7 +487,7 @@ TEST_P(VisualViewportTest, TestResizeAfterHorizontalScroll) {
// Verify the paint property nodes and GeometryMapper cache.
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(TransformationMatrix().Scale(4),
visual_viewport.GetPageScaleNode()->Matrix());
EXPECT_EQ(TransformationMatrix().Translate(-150, 0),
@@ -455,7 +516,7 @@ TEST_P(VisualViewportTest, TestWebViewResizedBeforeAttachment) {
WebView()->Resize(IntSize(320, 240));
NavigateTo("about:blank");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
main_frame_widget->SetRootGraphicsLayer(
frame_view.GetLayoutView()->Compositor()->RootGraphicsLayer());
@@ -486,7 +547,7 @@ TEST_P(VisualViewportTest, TestVisibleRect) {
// Viewport is whole frame.
IntSize size = IntSize(400, 200);
WebView()->Resize(size);
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
visual_viewport.SetSize(size);
// Scale the viewport to 2X; size should not change.
@@ -568,8 +629,8 @@ TEST_P(VisualViewportTest, TestOffsetClamping) {
InitializeWithAndroidSettings();
WebView()->Resize(IntSize(320, 240));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(
WebView()->MainFrameImpl(),
"<!DOCTYPE html>"
"<meta name='viewport' content='width=2000'>",
@@ -727,7 +788,7 @@ TEST_P(VisualViewportTest, TestOffsetClampingWithResizeAndScale) {
// Resize both the viewport and the frame to be larger.
WebView()->Resize(IntSize(640, 480));
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(IntSize(WebView()->Size()), visual_viewport.Size());
EXPECT_EQ(IntSize(WebView()->Size()), GetFrame()->View()->FrameRect().Size());
visual_viewport.SetLocation(FloatPoint(1000, 1000));
@@ -754,7 +815,7 @@ TEST_P(VisualViewportTest, TestFrameViewSizedToContent) {
NavigateTo(base_url_ + "200-by-300-viewport.html");
WebView()->Resize(IntSize(600, 800));
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Note: the size is ceiled and should match the behavior in CC's
// LayerImpl::bounds().
@@ -773,7 +834,7 @@ TEST_P(VisualViewportTest, TestFrameViewSizedToMinimumScale) {
NavigateTo(base_url_ + "200-by-300.html");
WebView()->Resize(IntSize(100, 160));
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(IntSize(100, 160),
WebView()->MainFrameImpl()->GetFrameView()->FrameRect().Size());
@@ -789,7 +850,7 @@ TEST_P(VisualViewportTest, TestAttachingNewFrameSetsInnerScrollLayerSize) {
// the smaller size on the second navigation.
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
visual_viewport.SetScale(2);
@@ -802,7 +863,7 @@ TEST_P(VisualViewportTest, TestAttachingNewFrameSetsInnerScrollLayerSize) {
// Navigate again, this time the LocalFrameView should be smaller.
RegisterMockedHttpURLLoad("viewport-device-width.html");
NavigateTo(base_url_ + "viewport-device-width.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Ensure the scroll contents size matches the frame view's size.
EXPECT_EQ(IntSize(320, 240), IntSize(visual_viewport.ScrollLayer()->Size()));
@@ -826,8 +887,8 @@ TEST_P(VisualViewportTest, TestFrameViewSizedToViewportMetaMinimumScale) {
RegisterMockedHttpURLLoad("200-by-300-min-scale-2.html");
NavigateTo(base_url_ + "200-by-300-min-scale-2.html");
- WebView()->Resize(IntSize(100, 160));
- WebView()->UpdateAllLifecyclePhases();
+ WebView()->MainFrameWidget()->Resize(IntSize(100, 160));
+ UpdateAllLifecyclePhases();
EXPECT_EQ(IntSize(50, 80),
WebView()->MainFrameImpl()->GetFrameView()->FrameRect().Size());
@@ -887,8 +948,8 @@ TEST_P(VisualViewportTest, TestTextSelectionHandles) {
// and scale.
TEST_P(VisualViewportTest, TestSavedToHistoryItem) {
InitializeWithDesktopSettings();
- WebView()->Resize(IntSize(200, 300));
- WebView()->UpdateAllLifecyclePhases();
+ WebView()->MainFrameWidget()->Resize(IntSize(200, 300));
+ UpdateAllLifecyclePhases();
RegisterMockedHttpURLLoad("200-by-300.html");
NavigateTo(base_url_ + "200-by-300.html");
@@ -929,13 +990,14 @@ TEST_P(VisualViewportTest, TestRestoredFromHistoryItem) {
WebHistoryItem item;
item.Initialize();
- WebURL destination_url(URLTestHelpers::ToKURL(base_url_ + "200-by-300.html"));
+ WebURL destination_url(
+ url_test_helpers::ToKURL(base_url_ + "200-by-300.html"));
item.SetURLString(destination_url.GetString());
item.SetVisualViewportScrollOffset(WebFloatPoint(100, 120));
item.SetPageScaleFactor(2);
- FrameTestHelpers::LoadHistoryItem(WebView()->MainFrameImpl(), item,
- mojom::FetchCacheMode::kDefault);
+ frame_test_helpers::LoadHistoryItem(WebView()->MainFrameImpl(), item,
+ mojom::FetchCacheMode::kDefault);
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
EXPECT_EQ(2, visual_viewport.Scale());
@@ -956,7 +1018,7 @@ TEST_P(VisualViewportTest, TestRestoredFromLegacyHistoryItem) {
WebHistoryItem item;
item.Initialize();
WebURL destination_url(
- URLTestHelpers::ToKURL(base_url_ + "200-by-300-viewport.html"));
+ url_test_helpers::ToKURL(base_url_ + "200-by-300-viewport.html"));
item.SetURLString(destination_url.GetString());
// (-1, -1) will be used if the HistoryItem is an older version prior to
// having visual viewport scroll offset.
@@ -964,8 +1026,8 @@ TEST_P(VisualViewportTest, TestRestoredFromLegacyHistoryItem) {
item.SetScrollOffset(WebPoint(120, 180));
item.SetPageScaleFactor(2);
- FrameTestHelpers::LoadHistoryItem(WebView()->MainFrameImpl(), item,
- mojom::FetchCacheMode::kDefault);
+ frame_test_helpers::LoadHistoryItem(WebView()->MainFrameImpl(), item,
+ mojom::FetchCacheMode::kDefault);
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
EXPECT_EQ(2, visual_viewport.Scale());
@@ -980,8 +1042,8 @@ TEST_P(VisualViewportTest, TestRestoredFromLegacyHistoryItem) {
TEST_P(VisualViewportTest,
TestNavigateToSmallerFrameViewHistoryItemClobberBug) {
InitializeWithAndroidSettings();
- WebView()->Resize(IntSize(400, 400));
- WebView()->UpdateAllLifecyclePhases();
+ WebView()->MainFrameWidget()->Resize(IntSize(400, 400));
+ UpdateAllLifecyclePhases();
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
@@ -1075,7 +1137,7 @@ TEST_P(VisualViewportTest, TestWebViewResizeCausesViewportConstrainedLayout) {
}
class VisualViewportMockWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
MOCK_METHOD1(ShowContextMenu, void(const WebContextMenuData&));
MOCK_METHOD0(DidChangeScrollOffset, void());
@@ -1261,7 +1323,7 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustment) {
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
@@ -1271,7 +1333,8 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustment) {
EXPECT_EQ(IntSize(1000, 900), frame_view.FrameRect().Size());
// Simulate bringing down the browser controls by 20px.
- WebView()->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1, 1});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1, 1,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(FloatSize(500, 430), visual_viewport.VisibleRect().Size());
// Test that the scroll bounds are adjusted appropriately: the visual viewport
@@ -1288,8 +1351,9 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustment) {
frame_view.LayoutViewport()->GetScrollOffset());
// Simulate bringing up the browser controls by 10.5px.
- WebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1, -10.5f / 20});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1,
+ -10.5f / 20,
+ cc::BrowserControlsState::kBoth});
EXPECT_FLOAT_SIZE_EQ(FloatSize(500, 440.5f),
visual_viewport.VisibleRect().Size());
@@ -1311,7 +1375,7 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentWithScale) {
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
@@ -1323,7 +1387,8 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentWithScale) {
// Simulate bringing down the browser controls by 20px. Since we're zoomed in,
// the browser controls take up half as much space (in document-space) than
// they do at an unzoomed level.
- WebView()->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1, 1});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1, 1,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(FloatSize(250, 215), visual_viewport.VisibleRect().Size());
// Test that the scroll bounds are adjusted appropriately.
@@ -1339,8 +1404,8 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentWithScale) {
// Scale back out, LocalFrameView max scroll shouldn't have changed. Visual
// viewport should be moved up to accomodate larger view.
- WebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 0.5f, 0});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 0.5f,
+ 0, cc::BrowserControlsState::kBoth});
EXPECT_EQ(1, visual_viewport.Scale());
EXPECT_EQ(expected, frame_view.LayoutViewport()->GetScrollOffset());
frame_view.LayoutViewport()->ScrollBy(ScrollOffset(10000, 10000),
@@ -1352,13 +1417,13 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentWithScale) {
EXPECT_EQ(FloatSize(500, 860 - 430), visual_viewport.GetScrollOffset());
// Scale out, use a scale that causes fractional rects.
- WebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 0.8f, -1});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 0.8f,
+ -1, cc::BrowserControlsState::kBoth});
EXPECT_EQ(FloatSize(625, 562.5), visual_viewport.VisibleRect().Size());
// Bring out the browser controls by 11
- WebView()->ApplyViewportChanges(
- {gfx::Vector2dF(), gfx::Vector2dF(), 1, 11 / 20.f});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1,
+ 11 / 20.f, cc::BrowserControlsState::kBoth});
EXPECT_EQ(FloatSize(625, 548.75), visual_viewport.VisibleRect().Size());
// Ensure max scroll offsets are updated properly.
@@ -1392,7 +1457,7 @@ TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentAndResize) {
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
@@ -1463,7 +1528,7 @@ TEST_P(VisualViewportTest, TestBrowserControlsShrinkAdjustmentAndResize) {
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
@@ -1524,17 +1589,19 @@ TEST_P(VisualViewportTest, TestBrowserControlsShrinkAdjustmentAndResize) {
TEST_P(VisualViewportTest, TestTopControlHidingResizeDoesntClampMainFrame) {
InitializeWithAndroidSettings();
WebView()->ResizeWithBrowserControls(WebView()->Size(), 500, 0, false);
- WebView()->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1, 1});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1, 1,
+ cc::BrowserControlsState::kBoth});
WebView()->ResizeWithBrowserControls(WebSize(1000, 1000), 500, 0, true);
RegisterMockedHttpURLLoad("content-width-1000.html");
NavigateTo(base_url_ + "content-width-1000.html");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Scroll the LocalFrameView to the bottom of the page but "hide" the browser
// controls on the compositor side so the max scroll position should account
// for the full viewport height.
- WebView()->ApplyViewportChanges({gfx::Vector2dF(), gfx::Vector2dF(), 1, -1});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1, -1,
+ cc::BrowserControlsState::kBoth});
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
frame_view.LayoutViewport()->SetScrollOffset(ScrollOffset(0, 10000),
kProgrammaticScroll);
@@ -1596,7 +1663,8 @@ TEST_P(VisualViewportTest, TestChangingContentSizeAffectsScrollBounds) {
WebScriptSource("var content = document.getElementById(\"content\");"
"content.style.width = \"1500px\";"
"content.style.height = \"2400px\";"));
- frame_view.UpdateAllLifecyclePhases();
+ frame_view.UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
cc::Layer* scroll_layer =
frame_view.LayoutViewport()->LayerForScrolling()->CcLayer();
@@ -1615,10 +1683,10 @@ TEST_P(VisualViewportTest, TestChangingContentSizeAffectsScrollBounds) {
// viewport.
TEST_P(VisualViewportTest, ResizeVisualViewportStaysWithinOuterViewport) {
InitializeWithDesktopSettings();
- WebView()->Resize(IntSize(100, 200));
+ WebView()->MainFrameWidget()->Resize(IntSize(100, 200));
NavigateTo("about:blank");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
WebView()->ResizeVisualViewport(IntSize(100, 100));
@@ -1680,14 +1748,13 @@ TEST_P(VisualViewportTest, ElementVisibleBoundsInVisualViewport) {
// Test that the various window.scroll and document.body.scroll properties and
// methods don't change with the visual viewport.
TEST_P(VisualViewportTest, visualViewportIsInert) {
- FrameTestHelpers::WebViewHelper web_view_helper;
- WebViewImpl* web_view_impl = web_view_helper.Initialize(
- nullptr, nullptr, nullptr, &configureAndroidCompositing);
+ WebViewImpl* web_view_impl = helper_.Initialize(nullptr, nullptr, nullptr,
+ &ConfigureAndroidCompositing);
- web_view_impl->Resize(IntSize(200, 300));
+ web_view_impl->MainFrameWidget()->Resize(IntSize(200, 300));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(
web_view_impl->MainFrameImpl(),
"<!DOCTYPE html>"
"<meta name='viewport' content='width=200,minimum-scale=1'>"
@@ -1699,8 +1766,7 @@ TEST_P(VisualViewportTest, visualViewportIsInert) {
" }"
"</style>",
base_url);
- web_view_impl->UpdateAllLifecyclePhases();
-
+ UpdateAllLifecyclePhases();
LocalDOMWindow* window =
web_view_impl->MainFrameImpl()->GetFrame()->DomWindow();
HTMLElement* html = ToHTMLHtmlElement(window->document()->documentElement());
@@ -1808,8 +1874,9 @@ TEST_P(VisualViewportTest, SlowScrollAfterImplScroll) {
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
// Apply some scroll and scale from the impl-side.
- WebView()->ApplyViewportChanges(
- {gfx::Vector2dF(300, 200), gfx::Vector2dF(0, 0), 2, 0});
+ WebView()->ApplyViewportChanges({gfx::ScrollOffset(300, 200),
+ gfx::Vector2dF(0, 0), 2, 0,
+ cc::BrowserControlsState::kBoth});
EXPECT_EQ(FloatSize(300, 200), visual_viewport.GetScrollOffset());
@@ -1845,8 +1912,8 @@ TEST_P(VisualViewportTest, AccessibilityHitTestWhileZoomedIn) {
RegisterMockedHttpURLLoad("hit-test.html");
NavigateTo(base_url_ + "hit-test.html");
- WebView()->Resize(IntSize(500, 500));
- WebView()->UpdateAllLifecyclePhases();
+ WebView()->MainFrameWidget()->Resize(IntSize(500, 500));
+ UpdateAllLifecyclePhases();
WebDocument web_doc = WebView()->MainFrameImpl()->GetDocument();
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
@@ -1958,7 +2025,7 @@ TEST_P(VisualViewportTest, WindowDimensionsOnLoadWideContent) {
TEST_P(VisualViewportTest, ResizeWithScrollAnchoring) {
InitializeWithDesktopSettings();
- WebView()->Resize(IntSize(800, 600));
+ WebView()->MainFrameWidget()->Resize(IntSize(800, 600));
RegisterMockedHttpURLLoad("icb-relative-content.html");
NavigateTo(base_url_ + "icb-relative-content.html");
@@ -1966,7 +2033,7 @@ TEST_P(VisualViewportTest, ResizeWithScrollAnchoring) {
LocalFrameView& frame_view = *WebView()->MainFrameImpl()->GetFrameView();
frame_view.LayoutViewport()->SetScrollOffset(ScrollOffset(700, 500),
kProgrammaticScroll);
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
WebView()->Resize(IntSize(800, 300));
EXPECT_EQ(ScrollOffset(700, 200),
@@ -2008,7 +2075,7 @@ TEST_P(VisualViewportTest, RotationAnchoringWithRootScroller) {
ScopedSetRootScrollerForTest root_scroller(true);
InitializeWithAndroidSettings();
- WebView()->Resize(IntSize(800, 600));
+ WebView()->MainFrameWidget()->Resize(IntSize(800, 600));
RegisterMockedHttpURLLoad("root-scroller-div.html");
NavigateTo(base_url_ + "root-scroller-div.html");
@@ -2018,7 +2085,7 @@ TEST_P(VisualViewportTest, RotationAnchoringWithRootScroller) {
Element* scroller = GetFrame()->GetDocument()->getElementById("rootScroller");
NonThrowableExceptionState non_throw;
GetFrame()->GetDocument()->setRootScroller(scroller, non_throw);
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
scroller->setScrollTop(800);
@@ -2034,9 +2101,8 @@ TEST_P(VisualViewportTest, ResizeCompositedAndFixedBackground) {
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
return;
- FrameTestHelpers::WebViewHelper web_view_helper;
- WebViewImpl* web_view_impl = web_view_helper.Initialize(
- nullptr, nullptr, nullptr, &configureAndroidCompositing);
+ WebViewImpl* web_view_impl = helper_.Initialize(nullptr, nullptr, nullptr,
+ &ConfigureAndroidCompositing);
int page_width = 640;
int page_height = 480;
@@ -2047,22 +2113,22 @@ TEST_P(VisualViewportTest, ResizeCompositedAndFixedBackground) {
browser_controls_height, 0, false);
RegisterMockedHttpURLLoad("http://example.com/foo.png", "white-1x1.png");
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " background: url('foo.png');"
- " background-attachment: fixed;"
- " background-size: cover;"
- " background-repeat: no-repeat;"
- " }"
- " div { height:1000px; width: 200px; }"
- "</style>"
- "<div></div>",
- base_url);
- web_view_impl->UpdateAllLifecyclePhases();
-
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " background: url('foo.png');"
+ " background-attachment: fixed;"
+ " background-size: cover;"
+ " background-repeat: no-repeat;"
+ " }"
+ " div { height:1000px; width: 200px; }"
+ "</style>"
+ "<div></div>",
+ base_url);
+
+ UpdateAllLifecyclePhases();
Document* document =
ToLocalFrame(web_view_impl->GetPage()->MainFrame())->GetDocument();
GraphicsLayer* backgroundLayer = document->GetLayoutView()
@@ -2095,8 +2161,7 @@ TEST_P(VisualViewportTest, ResizeCompositedAndFixedBackground) {
EXPECT_EQ(page_height, backgroundLayer->Size().height());
}
-static void configureAndroidNonCompositing(WebSettings* settings) {
- settings->SetAcceleratedCompositingEnabled(true);
+static void ConfigureAndroidNonCompositing(WebSettings* settings) {
settings->SetPreferCompositingToLCDTextEnabled(false);
settings->SetViewportMetaEnabled(true);
settings->SetViewportEnabled(true);
@@ -2110,9 +2175,8 @@ TEST_P(VisualViewportTest, ResizeNonCompositedAndFixedBackground) {
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
return;
- FrameTestHelpers::WebViewHelper web_view_helper;
- WebViewImpl* web_view_impl = web_view_helper.Initialize(
- nullptr, nullptr, nullptr, &configureAndroidNonCompositing);
+ WebViewImpl* web_view_impl = helper_.Initialize(
+ nullptr, nullptr, nullptr, &ConfigureAndroidNonCompositing);
int page_width = 640;
int page_height = 480;
@@ -2123,23 +2187,22 @@ TEST_P(VisualViewportTest, ResizeNonCompositedAndFixedBackground) {
browser_controls_height, 0, false);
RegisterMockedHttpURLLoad("http://example.com/foo.png", "white-1x1.png");
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " margin: 0px;"
- " background: url('foo.png');"
- " background-attachment: fixed;"
- " background-size: cover;"
- " background-repeat: no-repeat;"
- " }"
- " div { height:1000px; width: 200px; }"
- "</style>"
- "<div></div>",
- base_url);
- web_view_impl->UpdateAllLifecyclePhases();
-
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " margin: 0px;"
+ " background: url('foo.png');"
+ " background-attachment: fixed;"
+ " background-size: cover;"
+ " background-repeat: no-repeat;"
+ " }"
+ " div { height:1000px; width: 200px; }"
+ "</style>"
+ "<div></div>",
+ base_url);
+ UpdateAllLifecyclePhases();
Document* document =
ToLocalFrame(web_view_impl->GetPage()->MainFrame())->GetDocument();
document->View()->SetTracksPaintInvalidations(true);
@@ -2150,41 +2213,31 @@ TEST_P(VisualViewportTest, ResizeNonCompositedAndFixedBackground) {
ASSERT_EQ(page_width, document->View()->GetLayoutSize().Width());
ASSERT_EQ(smallest_height, document->View()->GetLayoutSize().Height());
- const RasterInvalidationTracking* invalidation_tracking =
- document->GetLayoutView()
- ->Layer()
- ->GraphicsLayerBacking(document->GetLayoutView())
- ->GetRasterInvalidationTracking();
- // If no invalidations occured, this will be a nullptr.
- ASSERT_TRUE(invalidation_tracking);
-
- const auto* raster_invalidations = &invalidation_tracking->Invalidations();
- // No raster invalidation is needed because of no change within the root
- // scrolling layer.
- EXPECT_EQ(0u, raster_invalidations->size());
+ // Fixed-attachment background is affected by viewport size.
+ EXPECT_FALSE(MainGraphicsLayerHasRasterInvalidations(document));
+ ASSERT_TRUE(ScrollingContentsLayerHasRasterInvalidations(document));
+ EXPECT_THAT(
+ ScrollingContentsLayerRasterInvalidations(document),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ &ScrollingBackgroundClient(document),
+ ScrollingBackgroundClient(document).DebugName(),
+ IntRect(0, 0, 640, 1000), PaintInvalidationReason::kBackground}));
document->View()->SetTracksPaintInvalidations(false);
- invalidation_tracking = document->GetLayoutView()
- ->Layer()
- ->GraphicsLayerBacking(document->GetLayoutView())
- ->GetRasterInvalidationTracking();
- ASSERT_FALSE(invalidation_tracking);
-
document->View()->SetTracksPaintInvalidations(true);
web_view_impl->ResizeWithBrowserControls(WebSize(page_width, page_height),
browser_controls_height, 0, true);
- invalidation_tracking = document->GetLayoutView()
- ->Layer()
- ->GraphicsLayerBacking(document->GetLayoutView())
- ->GetRasterInvalidationTracking();
- ASSERT_TRUE(invalidation_tracking);
- raster_invalidations = &invalidation_tracking->Invalidations();
-
- // No raster invalidation is needed because of no change within the root
- // scrolling layer.
- EXPECT_EQ(0u, raster_invalidations->size());
+ // Fixed-attachment background is affected by viewport size.
+ EXPECT_FALSE(MainGraphicsLayerHasRasterInvalidations(document));
+ ASSERT_TRUE(ScrollingContentsLayerHasRasterInvalidations(document));
+ EXPECT_THAT(
+ ScrollingContentsLayerRasterInvalidations(document),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ &ScrollingBackgroundClient(document),
+ ScrollingBackgroundClient(document).DebugName(),
+ IntRect(0, 0, 640, 1000), PaintInvalidationReason::kBackground}));
document->View()->SetTracksPaintInvalidations(false);
}
@@ -2192,9 +2245,8 @@ TEST_P(VisualViewportTest, ResizeNonCompositedAndFixedBackground) {
// Make sure a browser control resize with background-attachment:not-fixed
// background doesn't cause invalidation or layout.
TEST_P(VisualViewportTest, ResizeNonFixedBackgroundNoLayoutOrInvalidation) {
- FrameTestHelpers::WebViewHelper web_view_helper;
- WebViewImpl* web_view_impl = web_view_helper.Initialize(
- nullptr, nullptr, nullptr, &configureAndroidCompositing);
+ WebViewImpl* web_view_impl = helper_.Initialize(nullptr, nullptr, nullptr,
+ &ConfigureAndroidCompositing);
int page_width = 640;
int page_height = 480;
@@ -2205,23 +2257,22 @@ TEST_P(VisualViewportTest, ResizeNonFixedBackgroundNoLayoutOrInvalidation) {
browser_controls_height, 0, false);
RegisterMockedHttpURLLoad("http://example.com/foo.png", "white-1x1.png");
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
// This time the background is the default attachment.
- FrameTestHelpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " margin: 0px;"
- " background: url('foo.png');"
- " background-size: cover;"
- " background-repeat: no-repeat;"
- " }"
- " div { height:1000px; width: 200px; }"
- "</style>"
- "<div></div>",
- base_url);
- web_view_impl->UpdateAllLifecyclePhases();
-
+ frame_test_helpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " margin: 0px;"
+ " background: url('foo.png');"
+ " background-size: cover;"
+ " background-repeat: no-repeat;"
+ " }"
+ " div { height:1000px; width: 200px; }"
+ "</style>"
+ "<div></div>",
+ base_url);
+ UpdateAllLifecyclePhases();
Document* document =
ToLocalFrame(web_view_impl->GetPage()->MainFrame())->GetDocument();
@@ -2236,8 +2287,7 @@ TEST_P(VisualViewportTest, ResizeNonFixedBackgroundNoLayoutOrInvalidation) {
total_objects, is_subtree);
EXPECT_EQ(0u, needs_layout_objects);
- web_view_impl->UpdateAllLifecyclePhases();
-
+ UpdateAllLifecyclePhases();
// Do a real resize to check for invalidations.
document->View()->SetTracksPaintInvalidations(true);
web_view_impl->ResizeWithBrowserControls(WebSize(page_width, smallest_height),
@@ -2248,23 +2298,18 @@ TEST_P(VisualViewportTest, ResizeNonFixedBackgroundNoLayoutOrInvalidation) {
ASSERT_EQ(smallest_height, document->View()->GetLayoutSize().Height());
if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- const RasterInvalidationTracking* invalidation_tracking =
- document->GetLayoutView()
- ->Layer()
- ->GraphicsLayerBacking(document->GetLayoutView())
- ->GetRasterInvalidationTracking();
-
- // No invalidations should have occured.
- EXPECT_FALSE(invalidation_tracking->HasInvalidations());
+ // No invalidations should have occurred on either main layer or scrolling
+ // contents layer.
+ EXPECT_FALSE(MainGraphicsLayerHasRasterInvalidations(document));
+ EXPECT_FALSE(ScrollingContentsLayerHasRasterInvalidations(document));
}
document->View()->SetTracksPaintInvalidations(false);
}
TEST_P(VisualViewportTest, InvalidateLayoutViewWhenDocumentSmallerThanView) {
- FrameTestHelpers::WebViewHelper web_view_helper;
- WebViewImpl* web_view_impl = web_view_helper.Initialize(
- nullptr, nullptr, nullptr, &configureAndroidCompositing);
+ WebViewImpl* web_view_impl = helper_.Initialize(nullptr, nullptr, nullptr,
+ &ConfigureAndroidCompositing);
int page_width = 320;
int page_height = 590;
@@ -2274,9 +2319,8 @@ TEST_P(VisualViewportTest, InvalidateLayoutViewWhenDocumentSmallerThanView) {
web_view_impl->ResizeWithBrowserControls(WebSize(page_width, page_height),
browser_controls_height, 0, true);
- FrameTestHelpers::LoadFrame(web_view_impl->MainFrameImpl(), "about:blank");
- web_view_impl->UpdateAllLifecyclePhases();
-
+ frame_test_helpers::LoadFrame(web_view_impl->MainFrameImpl(), "about:blank");
+ UpdateAllLifecyclePhases();
Document* document =
ToLocalFrame(web_view_impl->GetPage()->MainFrame())->GetDocument();
@@ -2290,16 +2334,30 @@ TEST_P(VisualViewportTest, InvalidateLayoutViewWhenDocumentSmallerThanView) {
ASSERT_EQ(page_height, document->View()->GetLayoutSize().Height());
if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- const RasterInvalidationTracking* invalidation_tracking =
- document->GetLayoutView()
- ->Layer()
- ->GraphicsLayerBacking(document->GetLayoutView())
- ->GetRasterInvalidationTracking();
- ASSERT_TRUE(invalidation_tracking);
- const auto* raster_invalidations = &invalidation_tracking->Invalidations();
+ // Incremental raster invalidation is needed because the resize exposes
+ // unpainted area of background.
+ EXPECT_FALSE(MainGraphicsLayerHasRasterInvalidations(document));
+ ASSERT_TRUE(ScrollingContentsLayerHasRasterInvalidations(document));
+ EXPECT_THAT(
+ ScrollingContentsLayerRasterInvalidations(document),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ &ScrollingBackgroundClient(document),
+ ScrollingBackgroundClient(document).DebugName(),
+ IntRect(0, 590, 320, 50), PaintInvalidationReason::kIncremental}));
+ }
+
+ document->View()->SetTracksPaintInvalidations(false);
+
+ // Resize back to the original size.
+ document->View()->SetTracksPaintInvalidations(true);
+ web_view_impl->ResizeWithBrowserControls(WebSize(page_width, page_height),
+ browser_controls_height, 0, false);
+
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
// No raster invalidation is needed because of no change within the root
// scrolling layer.
- EXPECT_EQ(0u, raster_invalidations->size());
+ EXPECT_FALSE(MainGraphicsLayerHasRasterInvalidations(document));
+ EXPECT_FALSE(ScrollingContentsLayerHasRasterInvalidations(document));
}
document->View()->SetTracksPaintInvalidations(false);
@@ -2311,9 +2369,9 @@ TEST_P(VisualViewportTest, EnsureOverscrollElasticityTransformNode) {
return;
InitializeWithAndroidSettings();
- WebView()->Resize(IntSize(400, 400));
+ WebView()->MainFrameWidget()->Resize(IntSize(400, 400));
NavigateTo("about:blank");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
auto* node = visual_viewport.GetOverscrollElasticityTransformNode();
@@ -2329,9 +2387,9 @@ TEST_P(VisualViewportTest, EnsureEffectNodeForScrollbars) {
return;
InitializeWithAndroidSettings();
- WebView()->Resize(IntSize(400, 400));
+ WebView()->MainFrameWidget()->Resize(IntSize(400, 400));
NavigateTo("about:blank");
- WebView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
auto* vertical_scrollbar = visual_viewport.LayerForVerticalScrollbar();
@@ -2373,17 +2431,17 @@ TEST_P(VisualViewportTest, AutoResizeNoHeightUsesMinimumHeight) {
InitializeWithDesktopSettings();
WebView()->ResizeWithBrowserControls(WebSize(0, 0), 0, 0, false);
WebView()->EnableAutoResizeMode(WebSize(25, 25), WebSize(100, 100));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(WebView()->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " margin: 0px;"
- " }"
- " div { height:110vh; width: 110vw; }"
- "</style>"
- "<div></div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(WebView()->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " margin: 0px;"
+ " }"
+ " div { height:110vh; width: 110vw; }"
+ "</style>"
+ "<div></div>",
+ base_url);
}
class VisualViewportSimTest : public SimTest {
@@ -2395,7 +2453,6 @@ class VisualViewportSimTest : public SimTest {
// Use settings that resemble the Android configuration.
WebView().GetSettings()->SetViewportEnabled(true);
- WebView().GetSettings()->SetAcceleratedCompositingEnabled(true);
WebView().GetSettings()->SetPreferCompositingToLCDTextEnabled(true);
WebView().GetSettings()->SetViewportMetaEnabled(true);
WebView().GetSettings()->SetViewportEnabled(true);
@@ -2439,8 +2496,8 @@ TEST_F(VisualViewportSimTest, ScrollingContentsSmallerThanContainer) {
visual_viewport.GetScrollNode()->ContentsSize());
}
- WebView().ApplyViewportChanges(
- {gfx::Vector2dF(1, 1), gfx::Vector2dF(), 2, 1});
+ WebView().ApplyViewportChanges({gfx::ScrollOffset(1, 1), gfx::Vector2dF(), 2,
+ 1, cc::BrowserControlsState::kBoth});
EXPECT_EQ(gfx::Size(400, 600), visual_viewport.ContainerLayer()->Size());
EXPECT_EQ(gfx::Size(400, 600),
visual_viewport.ContainerLayer()->CcLayer()->bounds());
diff --git a/chromium/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc b/chromium/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc
index f1de4c6b353..224dd0b51ee 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc
+++ b/chromium/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc
@@ -320,7 +320,7 @@ void WebFrameSerializerImpl::OpenTagToString(Element* element,
String attr_value = it.Value();
// Skip srcdoc attribute if we will emit src attribute (for frames).
- if (should_rewrite_frame_src && attr_name == HTMLNames::srcdocAttr)
+ if (should_rewrite_frame_src && attr_name == html_names::kSrcdocAttr)
continue;
// Rewrite the attribute value if requested.
@@ -353,7 +353,7 @@ void WebFrameSerializerImpl::OpenTagToString(Element* element,
if (should_rewrite_frame_src && !did_rewrite_frame_src &&
IsHTMLIFrameElement(element)) {
AppendAttribute(result, param->is_html_document,
- HTMLNames::srcAttr.ToString(), rewritten_frame_link);
+ html_names::kSrcAttr.ToString(), rewritten_frame_link);
}
// Do post action for open tag.
diff --git a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.cc b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.cc
index 6504ff5aa90..6dc35ef78f1 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.cc
+++ b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_widget_client.h"
#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/events/web_input_event_conversion.h"
#include "third_party/blink/renderer/core/events/wheel_event.h"
@@ -21,6 +22,9 @@
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/input/context_menu_allowed_scope.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
+#include "third_party/blink/renderer/core/layout/hit_test_location.h"
+#include "third_party/blink/renderer/core/layout/hit_test_request.h"
+#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/page/context_menu_controller.h"
#include "third_party/blink/renderer/core/page/drag_actions.h"
#include "third_party/blink/renderer/core/page/drag_controller.h"
@@ -67,6 +71,39 @@ WebLocalFrame* WebFrameWidgetBase::LocalRoot() const {
return local_root_;
}
+WebRect WebFrameWidgetBase::ComputeBlockBound(
+ const gfx::Point& point_in_root_frame,
+ bool ignore_clipping) const {
+ HitTestLocation location(local_root_->GetFrameView()->ConvertFromRootFrame(
+ LayoutPoint(IntPoint(point_in_root_frame))));
+ HitTestRequest::HitTestRequestType hit_type =
+ HitTestRequest::kReadOnly | HitTestRequest::kActive |
+ (ignore_clipping ? HitTestRequest::kIgnoreClipping : 0);
+ HitTestResult result =
+ local_root_->GetFrame()->GetEventHandler().HitTestResultAtLocation(
+ location, hit_type);
+ result.SetToShadowHostIfInRestrictedShadowRoot();
+
+ Node* node = result.InnerNodeOrImageMapImage();
+ if (!node)
+ return WebRect();
+
+ // Find the block type node based on the hit node.
+ // FIXME: This wants to walk flat tree with
+ // LayoutTreeBuilderTraversal::parent().
+ while (node &&
+ (!node->GetLayoutObject() || node->GetLayoutObject()->IsInline()))
+ node = LayoutTreeBuilderTraversal::Parent(*node);
+
+ // Return the bounding box in the root frame's coordinate space.
+ if (node) {
+ IntRect absolute_rect = node->GetLayoutObject()->AbsoluteBoundingBoxRect();
+ LocalFrame* frame = node->GetDocument().GetFrame();
+ return frame->View()->ConvertToRootFrame(absolute_rect);
+ }
+ return WebRect();
+}
+
void WebFrameWidgetBase::UpdateAllLifecyclePhasesAndCompositeForTesting(
bool do_raster) {
if (WebLayerTreeView* layer_tree_view = GetLayerTreeView()) {
@@ -195,7 +232,7 @@ void WebFrameWidgetBase::DragSourceSystemDragEnded() {
}
void WebFrameWidgetBase::CancelDrag() {
- // It's possible for us this to be callback while we're not doing a drag if
+ // It's possible for this to be called while we're not doing a drag if
// it's from a previous page that got unloaded.
if (!doing_drag_and_drop_)
return;
@@ -203,11 +240,11 @@ void WebFrameWidgetBase::CancelDrag() {
doing_drag_and_drop_ = false;
}
-void WebFrameWidgetBase::StartDragging(WebReferrerPolicy policy,
+void WebFrameWidgetBase::StartDragging(network::mojom::ReferrerPolicy policy,
const WebDragData& data,
WebDragOperationsMask mask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset) {
+ const gfx::Point& drag_image_offset) {
doing_drag_and_drop_ = true;
Client()->StartDragging(policy, data, mask, drag_image, drag_image_offset);
}
@@ -317,7 +354,7 @@ void WebFrameWidgetBase::PointerLockMouseEvent(
AtomicString event_type;
switch (input_event.GetType()) {
case WebInputEvent::kMouseDown:
- event_type = EventTypeNames::mousedown;
+ event_type = event_type_names::kMousedown;
if (!GetPage() || !GetPage()->GetPointerLockController().GetElement())
break;
gesture_indicator =
@@ -330,12 +367,12 @@ void WebFrameWidgetBase::PointerLockMouseEvent(
pointer_lock_gesture_token_ = gesture_indicator->CurrentToken();
break;
case WebInputEvent::kMouseUp:
- event_type = EventTypeNames::mouseup;
+ event_type = event_type_names::kMouseup;
gesture_indicator = std::make_unique<UserGestureIndicator>(
std::move(pointer_lock_gesture_token_));
break;
case WebInputEvent::kMouseMove:
- event_type = EventTypeNames::mousemove;
+ event_type = event_type_names::kMousemove;
break;
default:
NOTREACHED() << input_event.GetType();
@@ -347,6 +384,9 @@ void WebFrameWidgetBase::PointerLockMouseEvent(
TransformWebMouseEventVector(
local_root_->GetFrameView(),
coalesced_event.GetCoalescedEventsPointers()),
+ TransformWebMouseEventVector(
+ local_root_->GetFrameView(),
+ coalesced_event.GetPredictedEventsPointers()),
event_type);
}
}
diff --git a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.h b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.h
index cd1feac94fb..85f7be0fe79 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.h
+++ b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.h
@@ -6,10 +6,10 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_WEB_FRAME_WIDGET_BASE_H_
#include "base/single_thread_task_runner.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/platform/web_coalesced_input_event.h"
#include "third_party/blink/public/platform/web_drag_data.h"
#include "third_party/blink/public/platform/web_gesture_device.h"
-#include "third_party/blink/public/platform/web_referrer_policy.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/renderer/core/clipboard/data_object.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -21,8 +21,11 @@ namespace cc {
class Layer;
}
-namespace blink {
+namespace gfx {
+class Point;
+}
+namespace blink {
class AnimationWorkletMutatorDispatcherImpl;
class CompositorAnimationHost;
class GraphicsLayer;
@@ -44,6 +47,10 @@ class CORE_EXPORT WebFrameWidgetBase
WebWidgetClient* Client() const { return client_; }
WebLocalFrameImpl* LocalRootImpl() const { return local_root_; }
+ // Returns the bounding box of the block type node touched by the WebPoint.
+ WebRect ComputeBlockBound(const gfx::Point& point_in_root_frame,
+ bool ignore_clipping) const;
+
void BindLocalRoot(WebLocalFrame&);
// Called once the local root is bound via |BindLocalRoot()|.
@@ -66,7 +73,7 @@ class CORE_EXPORT WebFrameWidgetBase
virtual WebLayerTreeView* GetLayerTreeView() const = 0;
virtual CompositorAnimationHost* AnimationHost() const = 0;
- virtual HitTestResult CoreHitTestResultAt(const WebPoint&) = 0;
+ virtual HitTestResult CoreHitTestResultAt(const gfx::Point&) = 0;
// WebFrameWidget implementation.
void Close() override;
@@ -95,11 +102,11 @@ class CORE_EXPORT WebFrameWidgetBase
WebLocalFrame* FocusedWebLocalFrameInWidget() const override;
// Called when a drag-n-drop operation should begin.
- void StartDragging(WebReferrerPolicy,
+ void StartDragging(network::mojom::ReferrerPolicy,
const WebDragData&,
WebDragOperationsMask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset);
+ const gfx::Point& drag_image_offset);
bool DoingDragAndDrop() { return doing_drag_and_drop_; }
static void SetIgnoreInputEvents(bool value) { ignore_input_events_ = value; }
diff --git a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
index 6606792b797..fa541de5f81 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
+++ b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
@@ -72,6 +72,7 @@
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
+#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/context_menu_controller.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -121,7 +122,8 @@ WebFrameWidget* WebFrameWidget::CreateForMainFrame(WebWidgetClient* client,
// Note: this isn't a leak, as the object has a self-reference that the
// caller needs to release by calling Close().
// TODO(dcheng): Remove the special bridge class for main frame widgets.
- WebFrameWidgetBase* widget = new WebViewFrameWidget(*client, web_view_impl);
+ WebFrameWidgetBase* widget =
+ MakeGarbageCollected<WebViewFrameWidget>(*client, web_view_impl);
widget->BindLocalRoot(*main_frame);
return widget;
}
@@ -146,7 +148,7 @@ WebFrameWidget* WebFrameWidget::CreateForChildLocalRoot(
WebFrameWidgetImpl* WebFrameWidgetImpl::Create(WebWidgetClient& client) {
// Pass the WebFrameWidgetImpl's self-reference from SelfKeepAlive to the
// caller.
- return new WebFrameWidgetImpl(client);
+ return MakeGarbageCollected<WebFrameWidgetImpl>(client);
}
WebFrameWidgetImpl::WebFrameWidgetImpl(WebWidgetClient& client)
@@ -303,7 +305,17 @@ void WebFrameWidgetImpl::BeginFrame(base::TimeTicks last_frame_time) {
GetPage()->GetValidationMessageClient().LayoutOverlay();
}
-void WebFrameWidgetImpl::UpdateLifecycle(LifecycleUpdate requested_update) {
+void WebFrameWidgetImpl::RecordEndOfFrameMetrics(
+ base::TimeTicks frame_begin_time) {
+ if (!LocalRootImpl())
+ return;
+
+ LocalRootImpl()->GetFrame()->View()->RecordEndOfFrameMetrics(
+ frame_begin_time);
+}
+
+void WebFrameWidgetImpl::UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) {
TRACE_EVENT0("blink", "WebFrameWidgetImpl::updateAllLifecyclePhases");
if (!LocalRootImpl())
return;
@@ -311,7 +323,7 @@ void WebFrameWidgetImpl::UpdateLifecycle(LifecycleUpdate requested_update) {
DocumentLifecycle::AllowThrottlingScope throttling_scope(
LocalRootImpl()->GetFrame()->GetDocument()->Lifecycle());
PageWidgetDelegate::UpdateLifecycle(*GetPage(), *LocalRootImpl()->GetFrame(),
- requested_update);
+ requested_update, reason);
UpdateLayerTreeBackgroundColor();
}
@@ -395,7 +407,7 @@ void WebFrameWidgetImpl::ThemeChanged() {
view->InvalidateRect(damaged_rect);
}
-WebHitTestResult WebFrameWidgetImpl::HitTestResultAt(const WebPoint& point) {
+WebHitTestResult WebFrameWidgetImpl::HitTestResultAt(const gfx::Point& point) {
return CoreHitTestResultAt(point);
}
@@ -474,22 +486,22 @@ WebInputEventResult WebFrameWidgetImpl::HandleInputEvent(
AtomicString event_type;
switch (input_event.GetType()) {
case WebInputEvent::kMouseEnter:
- event_type = EventTypeNames::mouseover;
+ event_type = event_type_names::kMouseover;
break;
case WebInputEvent::kMouseMove:
- event_type = EventTypeNames::mousemove;
+ event_type = event_type_names::kMousemove;
break;
case WebInputEvent::kMouseLeave:
- event_type = EventTypeNames::mouseout;
+ event_type = event_type_names::kMouseout;
break;
case WebInputEvent::kMouseDown:
- event_type = EventTypeNames::mousedown;
+ event_type = event_type_names::kMousedown;
gesture_indicator = LocalFrame::NotifyUserActivation(
node->GetDocument().GetFrame(), UserGestureToken::kNewGesture);
mouse_capture_gesture_token_ = gesture_indicator->CurrentToken();
break;
case WebInputEvent::kMouseUp:
- event_type = EventTypeNames::mouseup;
+ event_type = event_type_names::kMouseup;
gesture_indicator = std::make_unique<UserGestureIndicator>(
std::move(mouse_capture_gesture_token_));
break;
@@ -505,7 +517,10 @@ WebInputEventResult WebFrameWidgetImpl::HandleInputEvent(
node, transformed_event, event_type,
TransformWebMouseEventVector(
LocalRootImpl()->GetFrameView(),
- coalesced_event.GetCoalescedEventsPointers()));
+ coalesced_event.GetCoalescedEventsPointers()),
+ TransformWebMouseEventVector(
+ LocalRootImpl()->GetFrameView(),
+ coalesced_event.GetPredictedEventsPointers()));
}
return WebInputEventResult::kHandledSystem;
}
@@ -889,11 +904,23 @@ WebInputEventResult WebFrameWidgetImpl::HandleGestureEvent(
case WebInputEvent::kGestureShowPress:
break;
case WebInputEvent::kGestureDoubleTap:
- // Until https://crbug.com/734209 is resolved and OOPIFs learn how to
- // handle AnimateDoubleTap, we shouldn't pass this event to the event
- // handler as it will just result in (at best) hitting NOTREACHED() in
- // debug builds.
- LOG(INFO) << "DoubleTap zoom animations not yet implemented for OOPIF.";
+ if (GetPage()->GetChromeClient().DoubleTapToZoomEnabled() &&
+ view_impl->MinimumPageScaleFactor() !=
+ view_impl->MaximumPageScaleFactor()) {
+ LocalFrame* frame = LocalRootImpl()->GetFrame();
+ WebGestureEvent scaled_event =
+ TransformWebGestureEvent(frame->View(), event);
+ IntPoint pos_in_local_frame_root =
+ FlooredIntPoint(scaled_event.PositionInRootFrame());
+ WebRect block_bounds =
+ ComputeBlockBound(pos_in_local_frame_root, false);
+
+ // This sends the tap point and bounds to the main frame renderer via
+ // the browser, where their coordinates will be transformed into the
+ // main frame's coordinate space.
+ Client()->AnimateDoubleTapZoomInMainFrame(pos_in_local_frame_root,
+ block_bounds);
+ }
event_result = WebInputEventResult::kHandledSystem;
Client()->DidHandleGestureEvent(event, event_cancelled);
return event_result;
@@ -1078,8 +1105,6 @@ void WebFrameWidgetImpl::SetIsAcceleratedCompositingActive(bool active) {
TRACE_EVENT0("blink",
"WebViewImpl::setIsAcceleratedCompositingActive(true)");
layer_tree_view_->SetRootLayer(root_layer_);
-
- layer_tree_view_->SetVisible(GetPage()->IsPageVisible());
UpdateLayerTreeBackgroundColor();
UpdateLayerTreeViewport();
is_accelerated_compositing_active_ = true;
@@ -1132,22 +1157,15 @@ CompositorAnimationHost* WebFrameWidgetImpl::AnimationHost() const {
}
HitTestResult WebFrameWidgetImpl::CoreHitTestResultAt(
- const WebPoint& point_in_viewport) {
+ const gfx::Point& point_in_viewport) {
DocumentLifecycle::AllowThrottlingScope throttling_scope(
LocalRootImpl()->GetFrame()->GetDocument()->Lifecycle());
LocalFrameView* view = LocalRootImpl()->GetFrameView();
- IntPoint point_in_root_frame = view->ViewportToFrame(point_in_viewport);
+ IntPoint point_in_root_frame =
+ view->ViewportToFrame(IntPoint(point_in_viewport));
return HitTestResultForRootFramePos(point_in_root_frame);
}
-void WebFrameWidgetImpl::SetVisibilityState(
- mojom::PageVisibilityState visibility_state) {
- if (layer_tree_view_) {
- layer_tree_view_->SetVisible(visibility_state ==
- mojom::PageVisibilityState::kVisible);
- }
-}
-
HitTestResult WebFrameWidgetImpl::HitTestResultForRootFramePos(
const LayoutPoint& pos_in_root_frame) {
LayoutPoint doc_point(
diff --git a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.h b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
index 5d215256a97..53ea0234dc7 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
+++ b/chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.h
@@ -73,6 +73,7 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
public:
static WebFrameWidgetImpl* Create(WebWidgetClient&);
+ explicit WebFrameWidgetImpl(WebWidgetClient&);
~WebFrameWidgetImpl() override;
// WebWidget functions:
@@ -84,13 +85,15 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
void DidExitFullscreen() override;
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) final;
void BeginFrame(base::TimeTicks last_frame_time) override;
- void UpdateLifecycle(LifecycleUpdate requested_update) override;
+ void RecordEndOfFrameMetrics(base::TimeTicks) override;
+ void UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) override;
void PaintContent(cc::PaintCanvas*, const WebRect&) override;
void LayoutAndPaintAsync(base::OnceClosure callback) override;
void CompositeAndReadbackAsync(
base::OnceCallback<void(const SkBitmap&)> callback) override;
void ThemeChanged() override;
- WebHitTestResult HitTestResultAt(const WebPoint&) override;
+ WebHitTestResult HitTestResultAt(const gfx::Point&) override;
WebInputEventResult DispatchBufferedTouchEvents() override;
WebInputEventResult HandleInputEvent(const WebCoalescedInputEvent&) override;
void SetCursorVisibilityState(bool is_visible) override;
@@ -110,7 +113,6 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
WebURL GetURLForDebugTrace() override;
// WebFrameWidget implementation.
- void SetVisibilityState(mojom::PageVisibilityState) override;
void SetBackgroundColorOverride(SkColor) override;
void ClearBackgroundColorOverride() override;
void SetBaseBackgroundColorOverride(SkColor) override;
@@ -144,7 +146,7 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
void SetRootLayer(scoped_refptr<cc::Layer>) override;
WebLayerTreeView* GetLayerTreeView() const override;
CompositorAnimationHost* AnimationHost() const override;
- HitTestResult CoreHitTestResultAt(const WebPoint&) override;
+ HitTestResult CoreHitTestResultAt(const gfx::Point&) override;
// Exposed for the purpose of overriding device metrics.
void SendResizeEventAndRepaint();
@@ -165,8 +167,6 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
private:
friend class WebFrameWidget; // For WebFrameWidget::create.
- explicit WebFrameWidgetImpl(WebWidgetClient&);
-
// Perform a hit test for a point relative to the root frame of the page.
HitTestResult HitTestResultForRootFramePos(
const LayoutPoint& pos_in_root_frame);
diff --git a/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
index a7c0e79100e..6f286a3e400 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
+++ b/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -94,6 +94,8 @@
#include "base/macros.h"
#include "build/build_config.h"
+
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/platform/interface_registry.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_double_size.h"
@@ -131,6 +133,8 @@
#include "third_party/blink/public/web/web_text_direction.h"
#include "third_party/blink/public/web/web_tree_scope_type.h"
#include "third_party/blink/renderer/bindings/core/v8/binding_security.h"
+#include "third_party/blink/renderer/bindings/core/v8/isolated_world_csp.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
@@ -239,7 +243,6 @@
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
@@ -572,7 +575,7 @@ WebVector<WebIconURL> WebLocalFrameImpl::IconURLs(int icon_types_mask) const {
void WebLocalFrameImpl::SetContentSettingsClient(
WebContentSettingsClient* client) {
- content_settings_client_.SetClient(client);
+ content_settings_client_ = client;
}
void WebLocalFrameImpl::SetSharedWorkerRepositoryClient(
@@ -680,8 +683,8 @@ void WebLocalFrameImpl::DispatchUnloadEvent() {
void WebLocalFrameImpl::ExecuteScript(const WebScriptSource& source) {
DCHECK(GetFrame());
v8::HandleScope handle_scope(ToIsolate(GetFrame()));
- GetFrame()->GetScriptController().ExecuteScriptInMainWorld(source, KURL(),
- kOpaqueResource);
+ GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
+ source, KURL(), SanitizeScriptErrors::kSanitize);
}
void WebLocalFrameImpl::ExecuteScriptInIsolatedWorld(
@@ -689,13 +692,13 @@ void WebLocalFrameImpl::ExecuteScriptInIsolatedWorld(
const WebScriptSource& source_in) {
DCHECK(GetFrame());
CHECK_GT(world_id, 0);
- CHECK_LT(world_id, DOMWrapperWorld::kEmbedderWorldIdLimit);
+ CHECK_LT(world_id, DOMWrapperWorld::kDOMWrapperWorldEmbedderWorldIdLimit);
// Note: An error event in an isolated world will never be dispatched to
// a foreign world.
v8::HandleScope handle_scope(ToIsolate(GetFrame()));
GetFrame()->GetScriptController().ExecuteScriptInIsolatedWorld(
- world_id, source_in, KURL(), kSharableCrossOrigin);
+ world_id, source_in, KURL(), SanitizeScriptErrors::kDoNotSanitize);
}
v8::Local<v8::Value>
@@ -704,12 +707,12 @@ WebLocalFrameImpl::ExecuteScriptInIsolatedWorldAndReturnValue(
const WebScriptSource& source_in) {
DCHECK(GetFrame());
CHECK_GT(world_id, 0);
- CHECK_LT(world_id, DOMWrapperWorld::kEmbedderWorldIdLimit);
+ CHECK_LT(world_id, DOMWrapperWorld::kDOMWrapperWorldEmbedderWorldIdLimit);
// Note: An error event in an isolated world will never be dispatched to
// a foreign world.
return GetFrame()->GetScriptController().ExecuteScriptInIsolatedWorld(
- world_id, source_in, KURL(), kSharableCrossOrigin);
+ world_id, source_in, KURL(), SanitizeScriptErrors::kDoNotSanitize);
}
void WebLocalFrameImpl::SetIsolatedWorldSecurityOrigin(
@@ -725,7 +728,7 @@ void WebLocalFrameImpl::SetIsolatedWorldContentSecurityPolicy(
int world_id,
const WebString& policy) {
DCHECK(GetFrame());
- DOMWrapperWorld::SetIsolatedWorldContentSecurityPolicy(world_id, policy);
+ IsolatedWorldCSP::Get().SetContentSecurityPolicy(world_id, policy);
}
void WebLocalFrameImpl::SetIsolatedWorldHumanReadableName(
@@ -805,7 +808,8 @@ v8::Local<v8::Value> WebLocalFrameImpl::ExecuteScriptAndReturnValue(
return GetFrame()
->GetScriptController()
- .ExecuteScriptInMainWorldAndReturnValue(source, KURL(), kOpaqueResource);
+ .ExecuteScriptInMainWorldAndReturnValue(source, KURL(),
+ SanitizeScriptErrors::kSanitize);
}
void WebLocalFrameImpl::RequestExecuteScriptAndReturnValue(
@@ -850,7 +854,7 @@ void WebLocalFrameImpl::RequestExecuteScriptInIsolatedWorld(
WebScriptExecutionCallback* callback) {
DCHECK(GetFrame());
CHECK_GT(world_id, 0);
- CHECK_LT(world_id, DOMWrapperWorld::kEmbedderWorldIdLimit);
+ CHECK_LT(world_id, DOMWrapperWorld::kDOMWrapperWorldEmbedderWorldIdLimit);
scoped_refptr<DOMWrapperWorld> isolated_world =
DOMWrapperWorld::EnsureIsolatedWorld(ToIsolate(GetFrame()), world_id);
@@ -1455,12 +1459,6 @@ void WebLocalFrameImpl::SetCaretVisible(bool visible) {
GetFrame()->Selection().SetCaretVisible(visible);
}
-VisiblePosition WebLocalFrameImpl::VisiblePositionForViewportPoint(
- const WebPoint& point_in_viewport) {
- return VisiblePositionForContentsPoint(
- GetFrame()->View()->ViewportToFrame(point_in_viewport), GetFrame());
-}
-
WebPlugin* WebLocalFrameImpl::FocusedPluginIfInputMethodSupported() {
WebPluginContainerImpl* container = GetFrame()->GetWebPluginContainer();
if (container && container->SupportsInputMethod())
@@ -1476,7 +1474,7 @@ void WebLocalFrameImpl::DispatchBeforePrintEvent() {
is_in_printing_ = true;
#endif
- DispatchPrintEventRecursively(EventTypeNames::beforeprint);
+ DispatchPrintEventRecursively(event_type_names::kBeforeprint);
}
void WebLocalFrameImpl::DispatchAfterPrintEvent() {
@@ -1487,7 +1485,7 @@ void WebLocalFrameImpl::DispatchAfterPrintEvent() {
#endif
if (View())
- DispatchPrintEventRecursively(EventTypeNames::afterprint);
+ DispatchPrintEventRecursively(event_type_names::kAfterprint);
}
void WebLocalFrameImpl::DispatchPrintEventRecursively(
@@ -1664,8 +1662,8 @@ WebLocalFrameImpl* WebLocalFrameImpl::Create(
WebLocalFrameClient* client,
blink::InterfaceRegistry* interface_registry,
WebFrame* opener) {
- WebLocalFrameImpl* frame =
- new WebLocalFrameImpl(scope, client, interface_registry);
+ WebLocalFrameImpl* frame = MakeGarbageCollected<WebLocalFrameImpl>(
+ scope, client, interface_registry);
frame->SetOpener(opener);
return frame;
}
@@ -1677,8 +1675,8 @@ WebLocalFrameImpl* WebLocalFrameImpl::CreateMainFrame(
WebFrame* opener,
const WebString& name,
WebSandboxFlags sandbox_flags) {
- WebLocalFrameImpl* frame = new WebLocalFrameImpl(WebTreeScopeType::kDocument,
- client, interface_registry);
+ WebLocalFrameImpl* frame = MakeGarbageCollected<WebLocalFrameImpl>(
+ WebTreeScopeType::kDocument, client, interface_registry);
frame->SetOpener(opener);
Page& page = *static_cast<WebViewImpl*>(web_view)->GetPage();
DCHECK(!page.MainFrame());
@@ -1696,8 +1694,8 @@ WebLocalFrameImpl* WebLocalFrameImpl::CreateProvisional(
WebSandboxFlags flags,
ParsedFeaturePolicy container_policy) {
DCHECK(client);
- WebLocalFrameImpl* web_frame =
- new WebLocalFrameImpl(old_web_frame, client, interface_registry);
+ WebLocalFrameImpl* web_frame = MakeGarbageCollected<WebLocalFrameImpl>(
+ old_web_frame, client, interface_registry);
Frame* old_frame = ToWebRemoteFrameImpl(old_web_frame)->GetFrame();
web_frame->SetParent(old_web_frame->Parent());
web_frame->SetOpener(old_web_frame->Opener());
@@ -1737,8 +1735,8 @@ WebLocalFrameImpl* WebLocalFrameImpl::CreateLocalChild(
WebTreeScopeType scope,
WebLocalFrameClient* client,
blink::InterfaceRegistry* interface_registry) {
- WebLocalFrameImpl* frame =
- new WebLocalFrameImpl(scope, client, interface_registry);
+ WebLocalFrameImpl* frame = MakeGarbageCollected<WebLocalFrameImpl>(
+ scope, client, interface_registry);
AppendChild(frame);
return frame;
}
@@ -1747,7 +1745,7 @@ WebLocalFrameImpl::WebLocalFrameImpl(
WebTreeScopeType scope,
WebLocalFrameClient* client,
blink::InterfaceRegistry* interface_registry)
- : WebLocalFrame(scope),
+ : WebNavigationControl(scope),
client_(client),
local_frame_client_(LocalFrameClientImpl::Create(this)),
autofill_client_(nullptr),
@@ -1842,12 +1840,14 @@ LocalFrame* WebLocalFrameImpl::CreateChildFrame(
owner_element->getAttribute(
owner_element->SubResourceAttributeName()),
static_cast<WebSandboxFlags>(owner_element->GetSandboxFlags()),
- owner_element->ContainerPolicy(), owner_properties));
+ owner_element->ContainerPolicy(), owner_properties,
+ owner_element->OwnerType()));
if (!webframe_child)
return nullptr;
webframe_child->InitializeCoreFrame(*GetFrame()->GetPage(), owner_element,
name);
+
DCHECK(webframe_child->Parent());
return webframe_child->GetFrame();
}
@@ -1954,11 +1954,6 @@ void WebLocalFrameImpl::DidFinish() {
Client()->DidFinishLoad();
}
-void WebLocalFrameImpl::SetCanHaveScrollbars(bool can_have_scrollbars) {
- if (LocalFrameView* view = GetFrameView())
- view->SetCanHaveScrollbars(can_have_scrollbars);
-}
-
void WebLocalFrameImpl::SetInputEventsScaleForEmulation(
float content_scale_factor) {
input_events_scale_factor_for_emulation_ = content_scale_factor;
@@ -2014,9 +2009,11 @@ WebFrame* WebLocalFrameImpl::FindFrameByName(const WebString& name) {
void WebLocalFrameImpl::SendPings(const WebURL& destination_url) {
DCHECK(GetFrame());
- Element* anchor = ContextMenuNodeInner()->EnclosingLinkEventParentOrSelf();
- if (auto* html_anchor = ToHTMLAnchorElementOrNull(anchor))
- html_anchor->SendPings(destination_url);
+ if (Node* node = ContextMenuNodeInner()) {
+ Element* anchor = node->EnclosingLinkEventParentOrSelf();
+ if (auto* html_anchor = ToHTMLAnchorElementOrNull(anchor))
+ html_anchor->SendPings(destination_url);
+ }
}
bool WebLocalFrameImpl::DispatchBeforeUnloadEvent(bool is_reload) {
@@ -2099,7 +2096,7 @@ void WebLocalFrameImpl::LoadJavaScriptURL(const WebURL& url) {
v8::Local<v8::Value> result =
GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode(script, ScriptSourceLocationType::kJavascriptUrl),
- KURL(), kOpaqueResource);
+ KURL(), SanitizeScriptErrors::kSanitize);
if (result.IsEmpty() || !result->IsString())
return;
String script_result = ToCoreString(v8::Local<v8::String>::Cast(result));
@@ -2129,7 +2126,7 @@ void WebLocalFrameImpl::CommitDataNavigation(
std::move(navigation_params), std::move(navigation_data));
}
-WebLocalFrame::FallbackContentResult
+WebNavigationControl::FallbackContentResult
WebLocalFrameImpl::MaybeRenderFallbackContent(const WebURLError& error) const {
DCHECK(GetFrame());
@@ -2146,6 +2143,14 @@ WebLocalFrameImpl::MaybeRenderFallbackContent(const WebURLError& error) const {
return FallbackRendered;
}
+void WebLocalFrameImpl::RenderFallbackContent() const {
+ // TODO(ekaramad): If the owner renders its own content, then the current
+ // ContentFrame() should detach (see https://crbug.com/850223).
+ auto* owner = frame_->DeprecatedLocalOwner();
+ DCHECK(IsHTMLObjectElement(owner));
+ owner->RenderFallbackContent(frame_);
+}
+
// Called when a navigation is blocked because a Content Security Policy (CSP)
// is infringed.
void WebLocalFrameImpl::ReportContentSecurityPolicyViolation(
@@ -2242,6 +2247,24 @@ void WebLocalFrameImpl::MarkAsLoading() {
GetFrame()->Loader().MarkAsLoading();
}
+bool WebLocalFrameImpl::CreatePlaceholderDocumentLoader(
+ const WebURLRequest& request,
+ WebFrameLoadType frame_load_type,
+ WebNavigationType navigation_type,
+ bool is_client_redirect,
+ const base::UnguessableToken& devtools_navigation_token,
+ std::unique_ptr<WebNavigationParams> navigation_params,
+ std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) {
+ DCHECK(!request.IsNull());
+ DCHECK(!request.Url().ProtocolIs("javascript"));
+ return GetFrame()->Loader().CreatePlaceholderDocumentLoader(
+ request.ToResourceRequest(),
+ is_client_redirect ? ClientRedirectPolicy::kClientRedirect
+ : ClientRedirectPolicy::kNotClientRedirect,
+ devtools_navigation_token, frame_load_type, navigation_type,
+ std::move(navigation_params), std::move(extra_data));
+}
+
void WebLocalFrameImpl::SendOrientationChangeEvent() {
if (!GetFrame())
return;
@@ -2428,10 +2451,10 @@ void WebLocalFrameImpl::ExtractSmartClipData(WebRect rect_in_viewport,
static String CreateMarkupInRect(LocalFrame* frame,
const IntPoint& start_point,
const IntPoint& end_point) {
- VisiblePosition start_visible_position =
- VisiblePositionForContentsPoint(start_point, frame);
- VisiblePosition end_visible_position =
- VisiblePositionForContentsPoint(end_point, frame);
+ VisiblePosition start_visible_position = CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(start_point, frame));
+ VisiblePosition end_visible_position = CreateVisiblePosition(
+ PositionForContentsPointRespectingEditingBoundary(end_point, frame));
Position start_position = start_visible_position.DeepEquivalent();
Position end_position = end_visible_position.DeepEquivalent();
@@ -2476,23 +2499,23 @@ void WebLocalFrameImpl::PerformMediaPlayerAction(
HTMLMediaElement* media_element = ToHTMLMediaElement(node);
switch (action.type) {
- case WebMediaPlayerAction::kPlay:
+ case WebMediaPlayerAction::Type::kPlay:
if (action.enable)
media_element->Play();
else
media_element->pause();
break;
- case WebMediaPlayerAction::kMute:
+ case WebMediaPlayerAction::Type::kMute:
media_element->setMuted(action.enable);
break;
- case WebMediaPlayerAction::kLoop:
+ case WebMediaPlayerAction::Type::kLoop:
media_element->SetLoop(action.enable);
break;
- case WebMediaPlayerAction::kControls:
- media_element->SetBooleanAttribute(HTMLNames::controlsAttr,
+ case WebMediaPlayerAction::Type::kControls:
+ media_element->SetBooleanAttribute(html_names::kControlsAttr,
action.enable);
break;
- case WebMediaPlayerAction::kPictureInPicture:
+ case WebMediaPlayerAction::Type::kPictureInPicture:
DCHECK(media_element->IsHTMLVideoElement());
if (action.enable) {
PictureInPictureController::From(node->GetDocument())
@@ -2502,8 +2525,6 @@ void WebLocalFrameImpl::PerformMediaPlayerAction(
.ExitPictureInPicture(ToHTMLVideoElement(media_element), nullptr);
}
break;
- default:
- NOTREACHED();
}
}
diff --git a/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.h
index e857ff94ca9..3f046d8c623 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.h
+++ b/chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -41,10 +41,10 @@
#include "third_party/blink/public/web/devtools_agent.mojom-blink.h"
#include "third_party/blink/public/web/web_history_commit_type.h"
#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_navigation_control.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/exported/web_input_method_controller_impl.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/heap/self_keep_alive.h"
@@ -63,6 +63,7 @@ class TextFinder;
class WebAssociatedURLLoader;
struct WebAssociatedURLLoaderOptions;
class WebAutofillClient;
+class WebContentSettingsClient;
class WebDevToolsAgentImpl;
class WebLocalFrameClient;
class WebFrameWidgetBase;
@@ -82,7 +83,7 @@ class WebVector;
// Implementation of WebFrame, note that this is a reference counted object.
class CORE_EXPORT WebLocalFrameImpl final
: public GarbageCollectedFinalized<WebLocalFrameImpl>,
- public WebLocalFrame {
+ public WebNavigationControl {
public:
// WebFrame methods:
// TODO(dcheng): Fix sorting here; a number of method have been moved to
@@ -262,40 +263,10 @@ class CORE_EXPORT WebLocalFrameImpl final
WebLocalFrameImpl* LocalRoot() override;
WebFrame* FindFrameByName(const WebString& name) override;
void SendPings(const WebURL& destination_url) override;
- bool DispatchBeforeUnloadEvent(bool) override;
- void CommitNavigation(
- const WebURLRequest&,
- WebFrameLoadType,
- const WebHistoryItem&,
- bool is_client_redirect,
- const base::UnguessableToken& devtools_navigation_token,
- std::unique_ptr<WebNavigationParams> navigation_params,
- std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override;
- blink::mojom::CommitResult CommitSameDocumentNavigation(
- const WebURL&,
- WebFrameLoadType,
- const WebHistoryItem&,
- bool is_client_redirect,
- std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override;
- void LoadJavaScriptURL(const WebURL&) override;
- void CommitDataNavigation(
- const WebURLRequest&,
- const WebData&,
- const WebString& mime_type,
- const WebString& text_encoding,
- const WebURL& unreachable_url,
- WebFrameLoadType,
- const WebHistoryItem&,
- bool is_client_redirect,
- std::unique_ptr<WebNavigationParams> navigation_params,
- std::unique_ptr<WebDocumentLoader::ExtraData> navigation_data) override;
- FallbackContentResult MaybeRenderFallbackContent(
- const WebURLError&) const override;
void ReportContentSecurityPolicyViolation(
const blink::WebContentSecurityPolicyViolation&) override;
bool IsLoading() const override;
bool IsNavigationScheduledWithin(double interval) const override;
- void SetCommittedFirstRealLoad() override;
void NotifyUserActivation() override;
void BlinkFeatureUsageReport(const std::set<int>& features) override;
void MixedContentFound(const WebURL& main_resource_url,
@@ -304,8 +275,6 @@ class CORE_EXPORT WebLocalFrameImpl final
bool was_allowed,
bool had_redirect,
const WebSourceLocation&) override;
- void ClientDroppedNavigation() override;
- void MarkAsLoading() override;
void SendOrientationChangeEvent() override;
WebSandboxFlags EffectiveSandboxFlags() const override;
void DidCallAddSearchProvider() override;
@@ -335,6 +304,49 @@ class CORE_EXPORT WebLocalFrameImpl final
void PerformMediaPlayerAction(const WebPoint&,
const WebMediaPlayerAction&) override;
+ // WebNavigationControl methods:
+ bool DispatchBeforeUnloadEvent(bool) override;
+ void CommitNavigation(
+ const WebURLRequest&,
+ WebFrameLoadType,
+ const WebHistoryItem&,
+ bool is_client_redirect,
+ const base::UnguessableToken& devtools_navigation_token,
+ std::unique_ptr<WebNavigationParams> navigation_params,
+ std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override;
+ blink::mojom::CommitResult CommitSameDocumentNavigation(
+ const WebURL&,
+ WebFrameLoadType,
+ const WebHistoryItem&,
+ bool is_client_redirect,
+ std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override;
+ void LoadJavaScriptURL(const WebURL&) override;
+ void CommitDataNavigation(
+ const WebURLRequest&,
+ const WebData&,
+ const WebString& mime_type,
+ const WebString& text_encoding,
+ const WebURL& unreachable_url,
+ WebFrameLoadType,
+ const WebHistoryItem&,
+ bool is_client_redirect,
+ std::unique_ptr<WebNavigationParams> navigation_params,
+ std::unique_ptr<WebDocumentLoader::ExtraData> navigation_data) override;
+ FallbackContentResult MaybeRenderFallbackContent(
+ const WebURLError&) const override;
+ void RenderFallbackContent() const override;
+ void SetCommittedFirstRealLoad() override;
+ void ClientDroppedNavigation() override;
+ void MarkAsLoading() override;
+ bool CreatePlaceholderDocumentLoader(
+ const WebURLRequest&,
+ WebFrameLoadType,
+ WebNavigationType,
+ bool is_client_redirect,
+ const base::UnguessableToken& devtools_navigation_token,
+ std::unique_ptr<WebNavigationParams>,
+ std::unique_ptr<WebDocumentLoader::ExtraData>) override;
+
void InitializeCoreFrame(Page&, FrameOwner*, const AtomicString& name);
LocalFrame* GetFrame() const { return frame_.Get(); }
@@ -357,6 +369,12 @@ class CORE_EXPORT WebLocalFrameImpl final
WebSandboxFlags,
ParsedFeaturePolicy);
+ WebLocalFrameImpl(WebTreeScopeType,
+ WebLocalFrameClient*,
+ blink::InterfaceRegistry*);
+ WebLocalFrameImpl(WebRemoteFrame*,
+ WebLocalFrameClient*,
+ blink::InterfaceRegistry*);
~WebLocalFrameImpl() override;
LocalFrame* CreateChildFrame(const AtomicString& name,
@@ -394,16 +412,11 @@ class CORE_EXPORT WebLocalFrameImpl final
WebHistoryCommitType);
void DidFinish();
- // Sets whether the WebLocalFrameImpl allows its document to be scrolled.
- // If the parameter is true, allow the document to be scrolled.
- // Otherwise, disallow scrolling.
- void SetCanHaveScrollbars(bool) override;
-
void SetClient(WebLocalFrameClient* client) { client_ = client; }
WebFrameWidgetBase* FrameWidgetImpl() { return frame_widget_; }
- ContentSettingsClient& GetContentSettingsClient() {
+ WebContentSettingsClient* GetContentSettingsClient() {
return content_settings_client_;
}
@@ -428,9 +441,6 @@ class CORE_EXPORT WebLocalFrameImpl final
// Otherwise creates it and then returns.
TextFinder& EnsureTextFinder();
- // Returns a hit-tested VisiblePosition for the given point
- VisiblePosition VisiblePositionForViewportPoint(const WebPoint&);
-
void SetFrameWidget(WebFrameWidgetBase*);
// TODO(dcheng): Remove this and make |FrameWidget()| always return something
@@ -448,13 +458,6 @@ class CORE_EXPORT WebLocalFrameImpl final
private:
friend LocalFrameClientImpl;
- WebLocalFrameImpl(WebTreeScopeType,
- WebLocalFrameClient*,
- blink::InterfaceRegistry*);
- WebLocalFrameImpl(WebRemoteFrame*,
- WebLocalFrameClient*,
- blink::InterfaceRegistry*);
-
// Sets the local core frame and registers destruction observers.
void SetCoreFrame(LocalFrame*);
@@ -492,7 +495,7 @@ class CORE_EXPORT WebLocalFrameImpl final
Member<WebDevToolsAgentImpl> dev_tools_agent_;
WebAutofillClient* autofill_client_;
- ContentSettingsClient content_settings_client_;
+ WebContentSettingsClient* content_settings_client_ = nullptr;
std::unique_ptr<SharedWorkerRepositoryClientImpl>
shared_worker_repository_client_;
diff --git a/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.cc b/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.cc
index 40276e1ee56..9533a997685 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.cc
+++ b/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.cc
@@ -19,13 +19,7 @@ WebViewFrameWidget::WebViewFrameWidget(WebWidgetClient& client,
WebViewFrameWidget::~WebViewFrameWidget() = default;
void WebViewFrameWidget::Close() {
- // Note: it's important to use the captured main frame pointer here. During
- // a frame swap, the swapped frame is detached *after* the frame tree is
- // updated. If the main frame is being swapped, then
- // m_webView()->mainFrameImpl() will no longer point to the original frame.
- web_view_->SetCompositorVisibility(false);
web_view_ = nullptr;
-
WebFrameWidgetBase::Close();
// Note: this intentionally does not forward to WebView::close(), to make it
@@ -67,8 +61,9 @@ void WebViewFrameWidget::RecordEndOfFrameMetrics(
web_view_->RecordEndOfFrameMetrics(frame_begin_time);
}
-void WebViewFrameWidget::UpdateLifecycle(LifecycleUpdate requested_update) {
- web_view_->UpdateLifecycle(requested_update);
+void WebViewFrameWidget::UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) {
+ web_view_->UpdateLifecycle(requested_update, reason);
}
void WebViewFrameWidget::PaintContent(cc::PaintCanvas* canvas,
@@ -143,22 +138,10 @@ WebPagePopup* WebViewFrameWidget::GetPagePopup() const {
return web_view_->GetPagePopup();
}
-void WebViewFrameWidget::UpdateBrowserControlsState(
- cc::BrowserControlsState constraints,
- cc::BrowserControlsState current,
- bool animate) {
- web_view_->UpdateBrowserControlsState(constraints, current, animate);
-}
-
WebURL WebViewFrameWidget::GetURLForDebugTrace() {
return web_view_->GetURLForDebugTrace();
}
-void WebViewFrameWidget::SetVisibilityState(
- mojom::PageVisibilityState visibility_state) {
- web_view_->SetVisibilityState(visibility_state, false);
-}
-
void WebViewFrameWidget::SetBackgroundColorOverride(SkColor color) {
web_view_->SetBackgroundColorOverride(color);
}
@@ -188,9 +171,7 @@ bool WebViewFrameWidget::ScrollFocusedEditableElementIntoView() {
return web_view_->ScrollFocusedEditableElementIntoView();
}
-void WebViewFrameWidget::Initialize() {
- web_view_->SetCompositorVisibility(true);
-}
+void WebViewFrameWidget::Initialize() {}
void WebViewFrameWidget::SetLayerTreeView(WebLayerTreeView*) {
// The WebViewImpl already has its LayerTreeView, the WebWidgetClient
@@ -228,11 +209,11 @@ CompositorAnimationHost* WebViewFrameWidget::AnimationHost() const {
return web_view_->AnimationHost();
}
-WebHitTestResult WebViewFrameWidget::HitTestResultAt(const WebPoint& point) {
+WebHitTestResult WebViewFrameWidget::HitTestResultAt(const gfx::Point& point) {
return web_view_->HitTestResultAt(point);
}
-HitTestResult WebViewFrameWidget::CoreHitTestResultAt(const WebPoint& point) {
+HitTestResult WebViewFrameWidget::CoreHitTestResultAt(const gfx::Point& point) {
return web_view_->CoreHitTestResultAt(point);
}
diff --git a/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.h b/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.h
index 57fd12aa8e9..e9217a0dacb 100644
--- a/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.h
+++ b/chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.h
@@ -50,7 +50,8 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) final;
void BeginFrame(base::TimeTicks last_frame_time) override;
void RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time) override;
- void UpdateLifecycle(LifecycleUpdate requested_update) override;
+ void UpdateLifecycle(LifecycleUpdate requested_update,
+ LifecycleUpdateReason reason) override;
void PaintContent(cc::PaintCanvas*, const WebRect& view_port) override;
void LayoutAndPaintAsync(base::OnceClosure callback) override;
void CompositeAndReadbackAsync(
@@ -71,13 +72,9 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
void WillCloseLayerTreeView() override;
SkColor BackgroundColor() const override;
WebPagePopup* GetPagePopup() const override;
- void UpdateBrowserControlsState(cc::BrowserControlsState constraints,
- cc::BrowserControlsState current,
- bool animate) override;
WebURL GetURLForDebugTrace() override;
// WebFrameWidget overrides:
- void SetVisibilityState(mojom::PageVisibilityState) override;
void SetBackgroundColorOverride(SkColor) override;
void ClearBackgroundColorOverride() override;
void SetBaseBackgroundColorOverride(SkColor) override;
@@ -85,6 +82,7 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
void SetBaseBackgroundColor(SkColor) override;
WebInputMethodController* GetActiveWebInputMethodController() const override;
bool ScrollFocusedEditableElementIntoView() override;
+ WebHitTestResult HitTestResultAt(const gfx::Point&) override;
// WebFrameWidgetBase overrides:
void Initialize() override;
@@ -99,8 +97,7 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
void SetRootLayer(scoped_refptr<cc::Layer>) override;
WebLayerTreeView* GetLayerTreeView() const override;
CompositorAnimationHost* AnimationHost() const override;
- WebHitTestResult HitTestResultAt(const WebPoint&) override;
- HitTestResult CoreHitTestResultAt(const WebPoint&) override;
+ HitTestResult CoreHitTestResultAt(const gfx::Point&) override;
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/frame/window.idl b/chromium/third_party/blink/renderer/core/frame/window.idl
index b142a293cb3..a189cb39294 100644
--- a/chromium/third_party/blink/renderer/core/frame/window.idl
+++ b/chromium/third_party/blink/renderer/core/frame/window.idl
@@ -30,7 +30,8 @@
[
CheckSecurity=Receiver,
ImplementedAs=DOMWindow,
- PrimaryGlobal
+ Global=Window,
+ Exposed=Window
] interface Window : EventTarget {
// the current browsing context
// FIXME: The spec uses the WindowProxy type for this and many other attributes.
@@ -74,7 +75,7 @@
[CrossOrigin, Custom=Setter] attribute Window opener;
[Replaceable, CrossOrigin] readonly attribute Window? parent;
[CheckSecurity=ReturnValue, Custom=Getter] readonly attribute Element? frameElement;
- [CallWith=(ExecutionContext,CurrentWindow,EnteredWindow), RaisesException] Window? open(optional [TreatNullAs=EmptyString] URLString url="", optional DOMString target = "_blank", optional [TreatNullAs=EmptyString] DOMString features = "");
+ [CallWith=(ExecutionContext,CurrentWindow,EnteredWindow), RaisesException] Window? open(optional URLString url="", optional DOMString target = "_blank", optional [TreatNullAs=EmptyString] DOMString features = "");
// indexed properties
// https://html.spec.whatwg.org/C/browsers.html#windowproxy-getownproperty
@@ -96,7 +97,7 @@
[CrossOrigin, CallWith=CurrentWindow, RaisesException] void postMessage(any message, USVString targetOrigin, optional sequence<object> transfer = []);
- [CrossOrigin, CallWith=CurrentWindow, RaisesException, RuntimeEnabled=PostMessageOptions] void postMessage(any message, optional WindowPostMessageOptions options);
+ [CrossOrigin, CallWith=CurrentWindow, RaisesException] void postMessage(any message, optional WindowPostMessageOptions options);
// WindowOrWorkerGlobalScope mixin
// https://html.spec.whatwg.org/#windoworworkerglobalscope-mixin
@@ -146,11 +147,11 @@
[Replaceable] readonly attribute double pageXOffset;
[Replaceable] readonly attribute double scrollY;
[Replaceable] readonly attribute double pageYOffset;
- [RuntimeEnabled=CSSOMSmoothScroll] void scroll(optional ScrollToOptions options);
+ void scroll(optional ScrollToOptions options);
void scroll(unrestricted double x, unrestricted double y);
- [RuntimeEnabled=CSSOMSmoothScroll] void scrollTo(optional ScrollToOptions options);
+ void scrollTo(optional ScrollToOptions options);
void scrollTo(unrestricted double x, unrestricted double y);
- [RuntimeEnabled=CSSOMSmoothScroll] void scrollBy(optional ScrollToOptions options);
+ void scrollBy(optional ScrollToOptions options);
void scrollBy(unrestricted double x, unrestricted double y);
// Visual Viewport API
@@ -186,6 +187,9 @@
// https://github.com/WICG/aom/blob/HEAD/explainer.md
[RuntimeEnabled=AccessibilityObjectModel, CallWith=ScriptState] Promise<ComputedAccessibleNode> getComputedAccessibleNode(Element element);
+ // TODO(yhirano): Move this to url.idl when LegacyWindowAlias is supported.
+ attribute URLConstructor webkitURL;
+
// Non-standard APIs
[MeasureAs=WindowClientInformation, Replaceable] readonly attribute Navigator clientInformation;
[Replaceable, MeasureAs=WindowEvent, Custom=Getter, NotEnumerable] readonly attribute Event event;
@@ -204,7 +208,6 @@
[MeasureAs=StyleMedia] readonly attribute StyleMedia styleMedia;
[DeprecateAs=PrefixedRequestAnimationFrame] long webkitRequestAnimationFrame(FrameRequestCallback callback);
[DeprecateAs=PrefixedCancelAnimationFrame, ImplementedAs=cancelAnimationFrame] void webkitCancelAnimationFrame(long id);
- [DeprecateAs=PrefixedWindowURL] attribute URLConstructor webkitURL;
[MeasureAs=PrefixedMutationObserverConstructor] attribute MutationObserverConstructor WebKitMutationObserver;
// Event handler attributes
@@ -225,10 +228,9 @@
//TrustedTypes API
//http://github.com/wicg/trusted-types
- [RuntimeEnabled=TrustedDOMTypes] readonly attribute TrustedTypePolicyFactory TrustedTypes;
+ [RuntimeEnabled=TrustedDOMTypes, Unforgeable] readonly attribute TrustedTypePolicyFactory TrustedTypes;
};
Window implements GlobalEventHandlers;
-Window implements WindowBase64;
Window implements WindowEventHandlers;
-Window implements WindowTimers;
+Window implements WindowOrWorkerGlobalScope;
diff --git a/chromium/third_party/blink/renderer/core/frame/window_base64.idl b/chromium/third_party/blink/renderer/core/frame/window_base64.idl
deleted file mode 100644
index a19439efcad..00000000000
--- a/chromium/third_party/blink/renderer/core/frame/window_base64.idl
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// https://html.spec.whatwg.org/#atob
-
-[
- NoInterfaceObject, // Always used on target of 'implements'
- Exposed=(Window,Worker)
-] interface WindowBase64 {
- [RaisesException] DOMString btoa(DOMString btoa);
- [RaisesException] DOMString atob(DOMString atob);
-};
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window_event_handlers.h b/chromium/third_party/blink/renderer/core/frame/window_event_handlers.h
index 3ccffc47a53..c5b06f34756 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_window_event_handlers.h
+++ b/chromium/third_party/blink/renderer/core/frame/window_event_handlers.h
@@ -27,32 +27,39 @@
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_EVENT_HANDLERS_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_DOM_WINDOW_EVENT_HANDLERS_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_WINDOW_EVENT_HANDLERS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_WINDOW_EVENT_HANDLERS_H_
#include "third_party/blink/renderer/core/dom/events/event_target.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
-namespace DOMWindowEventHandlers {
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(afterprint);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeprint);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(languagechange);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(messageerror);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pagehide);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pageshow);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(rejectionhandled);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(unhandledrejection);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
-}
+class WindowEventHandlers {
+ STATIC_ONLY(WindowEventHandlers);
-} // namespace
+ public:
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(afterprint, kAfterprint);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeprint, kBeforeprint);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload, kBeforeunload);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange, kHashchange);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(languagechange,
+ kLanguagechange);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(messageerror, kMessageerror);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline, kOffline);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(online, kOnline);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pagehide, kPagehide);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pageshow, kPageshow);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate, kPopstate);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(rejectionhandled,
+ kRejectionhandled);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage, kStorage);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(unhandledrejection,
+ kUnhandledrejection);
+ DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload, kUnload);
+};
+
+} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/core/frame/window_event_handlers.idl b/chromium/third_party/blink/renderer/core/frame/window_event_handlers.idl
index 9bd850d04d8..f8c25fb7ab3 100644
--- a/chromium/third_party/blink/renderer/core/frame/window_event_handlers.idl
+++ b/chromium/third_party/blink/renderer/core/frame/window_event_handlers.idl
@@ -30,7 +30,6 @@
// https://html.spec.whatwg.org/multipage/webappapis.html#windoweventhandlers
[
- ImplementedAs=DOMWindowEventHandlers,
LegacyTreatAsPartialInterface,
NoInterfaceObject // Always used on target of 'implements'
] interface WindowEventHandlers {
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_window_timers.cc b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
index f60523736af..ace639fce91 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_window_timers.cc
+++ b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
@@ -30,7 +30,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/frame/dom_window_timers.h"
+#include "third_party/blink/renderer/core/frame/window_or_worker_global_scope.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_for_context_dispose.h"
@@ -39,15 +39,16 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/dom_timer.h"
+#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
+#include "third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/weborigin/security_violation_reporting_policy.h"
+#include "third_party/blink/renderer/platform/wtf/text/base64.h"
namespace blink {
-namespace DOMWindowTimers {
-
static bool IsAllowed(ScriptState* script_state,
ExecutionContext* execution_context,
bool is_eval,
@@ -82,11 +83,54 @@ static bool IsAllowed(ScriptState* script_state,
return false;
}
-int setTimeout(ScriptState* script_state,
- EventTarget& event_target,
- const ScriptValue& handler,
- int timeout,
- const Vector<ScriptValue>& arguments) {
+String WindowOrWorkerGlobalScope::btoa(EventTarget&,
+ const String& string_to_encode,
+ ExceptionState& exception_state) {
+ if (string_to_encode.IsNull())
+ return String();
+
+ if (!string_to_encode.ContainsOnlyLatin1OrEmpty()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidCharacterError,
+ "The string to be encoded contains "
+ "characters outside of the Latin1 range.");
+ return String();
+ }
+
+ return Base64Encode(string_to_encode.Latin1());
+}
+
+String WindowOrWorkerGlobalScope::atob(EventTarget&,
+ const String& encoded_string,
+ ExceptionState& exception_state) {
+ if (encoded_string.IsNull())
+ return String();
+
+ if (!encoded_string.ContainsOnlyLatin1OrEmpty()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidCharacterError,
+ "The string to be decoded contains "
+ "characters outside of the Latin1 range.");
+ return String();
+ }
+ Vector<char> out;
+ if (!Base64Decode(encoded_string, out, IsHTMLSpace<UChar>,
+ kBase64ValidatePadding)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidCharacterError,
+ "The string to be decoded is not correctly encoded.");
+ return String();
+ }
+
+ return String(out.data(), out.size());
+}
+
+int WindowOrWorkerGlobalScope::setTimeout(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const ScriptValue& handler,
+ int timeout,
+ const Vector<ScriptValue>& arguments) {
ExecutionContext* execution_context = event_target.GetExecutionContext();
if (!IsAllowed(script_state, execution_context, false, g_empty_string))
return 0;
@@ -101,12 +145,13 @@ int setTimeout(ScriptState* script_state,
TimeDelta::FromMilliseconds(timeout), true);
}
-int setTimeout(ScriptState* script_state,
- EventTarget& event_target,
- const StringOrTrustedScript& string_or_trusted_script,
- int timeout,
- const Vector<ScriptValue>& arguments,
- ExceptionState& exception_state) {
+int WindowOrWorkerGlobalScope::setTimeout(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const StringOrTrustedScript& string_or_trusted_script,
+ int timeout,
+ const Vector<ScriptValue>& arguments,
+ ExceptionState& exception_state) {
ExecutionContext* execution_context = event_target.GetExecutionContext();
Document* document = execution_context->IsDocument()
? static_cast<Document*>(execution_context)
@@ -119,11 +164,12 @@ int setTimeout(ScriptState* script_state,
arguments);
}
-int setTimeoutFromString(ScriptState* script_state,
- EventTarget& event_target,
- const String& handler,
- int timeout,
- const Vector<ScriptValue>&) {
+int WindowOrWorkerGlobalScope::setTimeoutFromString(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const String& handler,
+ int timeout,
+ const Vector<ScriptValue>&) {
ExecutionContext* execution_context = event_target.GetExecutionContext();
if (!IsAllowed(script_state, execution_context, true, handler))
return 0;
@@ -142,11 +188,12 @@ int setTimeoutFromString(ScriptState* script_state,
TimeDelta::FromMilliseconds(timeout), true);
}
-int setInterval(ScriptState* script_state,
- EventTarget& event_target,
- const ScriptValue& handler,
- int timeout,
- const Vector<ScriptValue>& arguments) {
+int WindowOrWorkerGlobalScope::setInterval(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const ScriptValue& handler,
+ int timeout,
+ const Vector<ScriptValue>& arguments) {
ExecutionContext* execution_context = event_target.GetExecutionContext();
if (!IsAllowed(script_state, execution_context, false, g_empty_string))
return 0;
@@ -156,12 +203,13 @@ int setInterval(ScriptState* script_state,
TimeDelta::FromMilliseconds(timeout), false);
}
-int setInterval(ScriptState* script_state,
- EventTarget& event_target,
- const StringOrTrustedScript& string_or_trusted_script,
- int timeout,
- const Vector<ScriptValue>& arguments,
- ExceptionState& exception_state) {
+int WindowOrWorkerGlobalScope::setInterval(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const StringOrTrustedScript& string_or_trusted_script,
+ int timeout,
+ const Vector<ScriptValue>& arguments,
+ ExceptionState& exception_state) {
ExecutionContext* execution_context = event_target.GetExecutionContext();
Document* document = execution_context->IsDocument()
? static_cast<Document*>(execution_context)
@@ -174,11 +222,12 @@ int setInterval(ScriptState* script_state,
arguments);
}
-int setIntervalFromString(ScriptState* script_state,
- EventTarget& event_target,
- const String& handler,
- int timeout,
- const Vector<ScriptValue>&) {
+int WindowOrWorkerGlobalScope::setIntervalFromString(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const String& handler,
+ int timeout,
+ const Vector<ScriptValue>&) {
ExecutionContext* execution_context = event_target.GetExecutionContext();
if (!IsAllowed(script_state, execution_context, true, handler))
return 0;
@@ -192,16 +241,38 @@ int setIntervalFromString(ScriptState* script_state,
TimeDelta::FromMilliseconds(timeout), false);
}
-void clearTimeout(EventTarget& event_target, int timeout_id) {
+void WindowOrWorkerGlobalScope::clearTimeout(EventTarget& event_target,
+ int timeout_id) {
if (ExecutionContext* context = event_target.GetExecutionContext())
DOMTimer::RemoveByID(context, timeout_id);
}
-void clearInterval(EventTarget& event_target, int timeout_id) {
+void WindowOrWorkerGlobalScope::clearInterval(EventTarget& event_target,
+ int timeout_id) {
if (ExecutionContext* context = event_target.GetExecutionContext())
DOMTimer::RemoveByID(context, timeout_id);
}
-} // namespace DOMWindowTimers
+ScriptPromise WindowOrWorkerGlobalScope::createImageBitmap(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const ImageBitmapSourceUnion& bitmap_source,
+ const ImageBitmapOptions* options) {
+ return ImageBitmapFactories::CreateImageBitmap(script_state, event_target,
+ bitmap_source, options);
+}
+
+ScriptPromise WindowOrWorkerGlobalScope::createImageBitmap(
+ ScriptState* script_state,
+ EventTarget& event_target,
+ const ImageBitmapSourceUnion& bitmap_source,
+ int sx,
+ int sy,
+ int sw,
+ int sh,
+ const ImageBitmapOptions* options) {
+ return ImageBitmapFactories::CreateImageBitmap(
+ script_state, event_target, bitmap_source, sx, sy, sw, sh, options);
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h
new file mode 100644
index 00000000000..2126c4a515b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_WINDOW_OR_WORKER_GLOBAL_SCOPE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_WINDOW_OR_WORKER_GLOBAL_SCOPE_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/image_bitmap_source.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/forward.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+class EventTarget;
+class ExceptionState;
+class ImageBitmapOptions;
+class ScriptPromise;
+class ScriptState;
+class ScriptValue;
+class StringOrTrustedScript;
+
+typedef HTMLImageElementOrSVGImageElementOrHTMLVideoElementOrHTMLCanvasElementOrBlobOrImageDataOrImageBitmapOrOffscreenCanvas
+ ImageBitmapSourceUnion;
+
+class WindowOrWorkerGlobalScope {
+ STATIC_ONLY(WindowOrWorkerGlobalScope);
+
+ public:
+ static String btoa(EventTarget&,
+ const String& string_to_encode,
+ ExceptionState&);
+ static String atob(EventTarget&,
+ const String& encoded_string,
+ ExceptionState&);
+
+ static int setTimeout(ScriptState*,
+ EventTarget&,
+ const ScriptValue& handler,
+ int timeout,
+ const Vector<ScriptValue>& arguments);
+ static int setTimeout(ScriptState*,
+ EventTarget&,
+ const StringOrTrustedScript&,
+ int timeout,
+ const Vector<ScriptValue>&,
+ ExceptionState&);
+ static int setTimeoutFromString(ScriptState*,
+ EventTarget&,
+ const String& handler,
+ int timeout,
+ const Vector<ScriptValue>&);
+ static int setInterval(ScriptState*,
+ EventTarget&,
+ const ScriptValue& handler,
+ int timeout,
+ const Vector<ScriptValue>&);
+ static int setInterval(ScriptState*,
+ EventTarget&,
+ const StringOrTrustedScript&,
+ int timeout,
+ const Vector<ScriptValue>&,
+ ExceptionState&);
+ static int setIntervalFromString(ScriptState*,
+ EventTarget&,
+ const String& handler,
+ int timeout,
+ const Vector<ScriptValue>&);
+ static void clearTimeout(EventTarget&, int timeout_id);
+ static void clearInterval(EventTarget&, int timeout_id);
+
+ static ScriptPromise createImageBitmap(ScriptState*,
+ EventTarget&,
+ const ImageBitmapSourceUnion&,
+ const ImageBitmapOptions*);
+ static ScriptPromise createImageBitmap(ScriptState*,
+ EventTarget&,
+ const ImageBitmapSourceUnion&,
+ int sx,
+ int sy,
+ int sw,
+ int sh,
+ const ImageBitmapOptions*);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_WINDOW_OR_WORKER_GLOBAL_SCOPE_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/window_timers.idl b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl
index d5183a8ea7a..1b78426e59e 100644
--- a/chromium/third_party/blink/renderer/core/frame/window_timers.idl
+++ b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.idl
@@ -28,12 +28,25 @@
// https://html.spec.whatwg.org/C/webappapis.html#windoworworkerglobalscope-mixin
// https://html.spec.whatwg.org/C/timers-and-user-prompts.html#timers
+// https://html.spec.whatwg.org/#imagebitmapsource
+typedef (HTMLImageElement or
+ SVGImageElement or
+ HTMLVideoElement or
+ HTMLCanvasElement or
+ Blob or
+ ImageData or
+ ImageBitmap or
+ OffscreenCanvas) ImageBitmapSource;
+
[
- ImplementedAs=DOMWindowTimers,
LegacyTreatAsPartialInterface,
NoInterfaceObject, // Always used on target of 'implements'
Exposed=(Window,Worker)
-] interface WindowTimers {
+] interface WindowOrWorkerGlobalScope {
+ // base64 utility methods
+ [RaisesException] DOMString btoa(DOMString btoa);
+ [RaisesException] DOMString atob(DOMString atob);
+
// TODO(yukishiino): Use TimerHandler (or Function at least) to implement
// setTimeout and setInterval.
// https://html.spec.whatwg.org/C/webappapis.html#windoworworkerglobalscope-mixin
@@ -43,4 +56,10 @@
[CallWith=ScriptState] long setInterval(CallbackFunctionTreatedAsScriptValue handler, optional long timeout = 0, any... arguments);
[CallWith=ScriptState, RaisesException] long setInterval(ScriptString handler, optional long timeout = 0, any... arguments);
void clearInterval(optional long handle = 0);
+
+ // ImageBitmap
+ [CallWith=ScriptState] Promise createImageBitmap(
+ ImageBitmapSource imageBitmap, optional ImageBitmapOptions options);
+ [CallWith=ScriptState] Promise createImageBitmap(
+ ImageBitmapSource imageBitmap, long sx, long sy, long sw, long sh, optional ImageBitmapOptions options);
};
diff --git a/chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h b/chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h
index 1b73f7b106c..76e6ec3fe5c 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h
+++ b/chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h
@@ -45,11 +45,13 @@ class DocumentFullscreen {
static ScriptPromise exitFullscreen(ScriptState*, Document&);
static void webkitExitFullscreen(Document&);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenchange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenerror);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenchange, kFullscreenchange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenerror, kFullscreenerror);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange,
+ kWebkitfullscreenchange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror,
+ kWebkitfullscreenerror);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc b/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc
index e31e4848d3e..7fd715191b6 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc
+++ b/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc
@@ -12,20 +12,20 @@ namespace blink {
ScriptPromise ElementFullscreen::requestFullscreen(
ScriptState* script_state,
Element& element,
- const FullscreenOptions& options) {
+ const FullscreenOptions* options) {
return Fullscreen::RequestFullscreen(
element, options, Fullscreen::RequestType::kUnprefixed, script_state);
}
void ElementFullscreen::webkitRequestFullscreen(Element& element) {
- FullscreenOptions options;
- options.setNavigationUI("hide");
+ FullscreenOptions* options = FullscreenOptions::Create();
+ options->setNavigationUI("hide");
webkitRequestFullscreen(element, options);
}
void ElementFullscreen::webkitRequestFullscreen(
Element& element,
- const FullscreenOptions& options) {
+ const FullscreenOptions* options) {
if (element.IsInShadowTree()) {
UseCounter::Count(element.GetDocument(),
WebFeature::kPrefixedElementRequestFullscreenInShadow);
diff --git a/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h b/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h
index 3a7ad9d32f9..c2268f607de 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h
+++ b/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h
@@ -21,16 +21,18 @@ class ElementFullscreen {
public:
static ScriptPromise requestFullscreen(ScriptState*,
Element&,
- const FullscreenOptions&);
+ const FullscreenOptions*);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenchange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenerror);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenchange, kFullscreenchange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(fullscreenerror, kFullscreenerror);
static void webkitRequestFullscreen(Element&);
- static void webkitRequestFullscreen(Element&, const FullscreenOptions&);
+ static void webkitRequestFullscreen(Element&, const FullscreenOptions*);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange,
+ kWebkitfullscreenchange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror,
+ kWebkitfullscreenerror);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc b/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc
index 5c6c80c8a8a..d7b294a975c 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc
+++ b/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc
@@ -125,7 +125,7 @@ using ElementRequestTypeMap =
ElementRequestTypeMap& FullscreenFlagMap() {
DEFINE_STATIC_LOCAL(Persistent<ElementRequestTypeMap>, map,
- (new ElementRequestTypeMap));
+ (MakeGarbageCollected<ElementRequestTypeMap>()));
return *map;
}
@@ -440,14 +440,14 @@ void FireEvent(const AtomicString& type, Element* element, Document* document) {
const AtomicString& AdjustEventType(const AtomicString& type,
Fullscreen::RequestType request_type) {
- DCHECK(type == EventTypeNames::fullscreenchange ||
- type == EventTypeNames::fullscreenerror);
+ DCHECK(type == event_type_names::kFullscreenchange ||
+ type == event_type_names::kFullscreenerror);
if (request_type == Fullscreen::RequestType::kUnprefixed)
return type;
- return type == EventTypeNames::fullscreenchange
- ? EventTypeNames::webkitfullscreenchange
- : EventTypeNames::webkitfullscreenerror;
+ return type == event_type_names::kFullscreenchange
+ ? event_type_names::kWebkitfullscreenchange
+ : event_type_names::kWebkitfullscreenerror;
}
void EnqueueEvent(const AtomicString& type,
@@ -472,7 +472,7 @@ const char Fullscreen::kSupplementName[] = "Fullscreen";
Fullscreen& Fullscreen::From(Document& document) {
Fullscreen* fullscreen = FromIfExists(document);
if (!fullscreen) {
- fullscreen = new Fullscreen(document);
+ fullscreen = MakeGarbageCollected<Fullscreen>(document);
ProvideTo(document, fullscreen);
}
return *fullscreen;
@@ -544,13 +544,13 @@ void Fullscreen::ContextDestroyed(ExecutionContext*) {
void Fullscreen::RequestFullscreen(Element& pending) {
// TODO(foolip): Make RequestType::Unprefixed the default when the unprefixed
// API is enabled. https://crbug.com/383813
- FullscreenOptions options;
- options.setNavigationUI("hide");
+ FullscreenOptions* options = FullscreenOptions::Create();
+ options->setNavigationUI("hide");
RequestFullscreen(pending, options, RequestType::kPrefixed);
}
ScriptPromise Fullscreen::RequestFullscreen(Element& pending,
- const FullscreenOptions& options,
+ const FullscreenOptions* options,
RequestType request_type,
ScriptState* script_state) {
RequestFullscreenScope scope;
@@ -620,7 +620,7 @@ ScriptPromise Fullscreen::RequestFullscreen(Element& pending,
}
From(document).pending_requests_.push_back(
- new PendingRequest(&pending, request_type, resolver));
+ MakeGarbageCollected<PendingRequest>(&pending, request_type, resolver));
LocalFrame& frame = *document.GetFrame();
frame.GetChromeClient().EnterFullscreen(frame, options);
} else {
@@ -673,7 +673,7 @@ void Fullscreen::ContinueRequestFullscreen(Document& document,
if (error) {
// 10.1. Append (fullscreenerror, |pending|) to |pendingDoc|'s list of
// pending fullscreen events.
- EnqueueEvent(EventTypeNames::fullscreenerror, pending, document,
+ EnqueueEvent(event_type_names::kFullscreenerror, pending, document,
request_type);
// 10.2. Reject |promise| with a TypeError exception and terminate these
@@ -730,7 +730,8 @@ void Fullscreen::ContinueRequestFullscreen(Document& document,
// 13.5. Append (fullscreenchange, |element|) to |doc|'s list of pending
// fullscreen events.
- EnqueueEvent(EventTypeNames::fullscreenchange, *element, doc, request_type);
+ EnqueueEvent(event_type_names::kFullscreenchange, *element, doc,
+ request_type);
}
// 14. Resolve |promise| with undefined.
@@ -823,7 +824,8 @@ ScriptPromise Fullscreen::ExitFullscreen(Document& doc,
// 7.1. Append (fullscreenchange, |doc|'s fullscreen element) to
// |doc|'s list of pending fullscreen events.
- EnqueueEvent(EventTypeNames::fullscreenchange, *element, doc, request_type);
+ EnqueueEvent(event_type_names::kFullscreenchange, *element, doc,
+ request_type);
// 7.2. Unfullscreen |element|.
Unfullscreen(*element);
@@ -919,7 +921,7 @@ void Fullscreen::ContinueExitFullscreen(Document* doc,
// 12.1. Append (fullscreenchange, |exitDoc|'s fullscreen element) to
// |exitDoc|'s list of pending fullscreen events.
- EnqueueEvent(EventTypeNames::fullscreenchange, *exit_element, *exit_doc,
+ EnqueueEvent(event_type_names::kFullscreenchange, *exit_element, *exit_doc,
request_type);
// 12.2. If |resize| is true, unfullscreen |exitDoc|.
@@ -938,7 +940,7 @@ void Fullscreen::ContinueExitFullscreen(Document* doc,
// 13.1. Append (fullscreenchange, |descendantDoc|'s fullscreen element) to
// |descendantDoc|'s list of pending fullscreen events.
- EnqueueEvent(EventTypeNames::fullscreenchange, *descendant_element,
+ EnqueueEvent(event_type_names::kFullscreenchange, *descendant_element,
*descendant_doc, request_type);
// 13.2. Unfullscreen |descendantDoc|.
@@ -967,7 +969,7 @@ void Fullscreen::DidUpdateSize(Element& element) {
// bit surprising.
element.SetNeedsStyleRecalc(
kLocalStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kFullscreen));
+ StyleChangeReasonForTracing::Create(style_change_reason::kFullscreen));
}
void Fullscreen::ElementRemoved(Element& node) {
diff --git a/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.h b/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.h
index 38fea663ca8..636f982b02f 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.h
+++ b/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.h
@@ -59,7 +59,9 @@ class CORE_EXPORT Fullscreen final
public:
static const char kSupplementName[];
+ explicit Fullscreen(Document&);
virtual ~Fullscreen();
+
static Fullscreen& From(Document&);
static Element* FullscreenElementFrom(Document&);
static Element* FullscreenElementForBindingFrom(TreeScope&);
@@ -79,7 +81,7 @@ class CORE_EXPORT Fullscreen final
static void RequestFullscreen(Element&);
static ScriptPromise RequestFullscreen(Element&,
- const FullscreenOptions&,
+ const FullscreenOptions*,
RequestType,
ScriptState* state = nullptr);
@@ -107,8 +109,6 @@ class CORE_EXPORT Fullscreen final
private:
static Fullscreen* FromIfExists(Document&);
- explicit Fullscreen(Document&);
-
Document* GetDocument();
static void ContinueRequestFullscreen(Document&,
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_matrix.cc b/chromium/third_party/blink/renderer/core/geometry/dom_matrix.cc
index 4aff622e110..614bb77e8e9 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_matrix.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_matrix.cc
@@ -10,12 +10,12 @@
namespace blink {
DOMMatrix* DOMMatrix::Create() {
- return new DOMMatrix(TransformationMatrix());
+ return MakeGarbageCollected<DOMMatrix>(TransformationMatrix());
}
DOMMatrix* DOMMatrix::Create(ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return new DOMMatrix(TransformationMatrix());
+ return MakeGarbageCollected<DOMMatrix>(TransformationMatrix());
}
DOMMatrix* DOMMatrix::Create(ExecutionContext* execution_context,
@@ -28,7 +28,7 @@ DOMMatrix* DOMMatrix::Create(ExecutionContext* execution_context,
return nullptr;
}
- DOMMatrix* matrix = new DOMMatrix(TransformationMatrix());
+ DOMMatrix* matrix = MakeGarbageCollected<DOMMatrix>(TransformationMatrix());
matrix->SetMatrixValueFromString(execution_context, init.GetAsString(),
exception_state);
return matrix;
@@ -42,7 +42,7 @@ DOMMatrix* DOMMatrix::Create(ExecutionContext* execution_context,
"for a 3D matrix.");
return nullptr;
}
- return new DOMMatrix(sequence, sequence.size());
+ return MakeGarbageCollected<DOMMatrix>(sequence, sequence.size());
}
NOTREACHED();
@@ -51,17 +51,18 @@ DOMMatrix* DOMMatrix::Create(ExecutionContext* execution_context,
DOMMatrix* DOMMatrix::Create(DOMMatrixReadOnly* other,
ExceptionState& exception_state) {
- return new DOMMatrix(other->Matrix(), other->is2D());
+ return MakeGarbageCollected<DOMMatrix>(other->Matrix(), other->is2D());
}
DOMMatrix* DOMMatrix::Create(const SkMatrix44& matrix,
ExceptionState& exception_state) {
TransformationMatrix transformation_matrix(matrix);
- return new DOMMatrix(transformation_matrix, transformation_matrix.IsAffine());
+ return MakeGarbageCollected<DOMMatrix>(transformation_matrix,
+ transformation_matrix.IsAffine());
}
DOMMatrix* DOMMatrix::CreateForSerialization(double sequence[], int size) {
- return new DOMMatrix(sequence, size);
+ return MakeGarbageCollected<DOMMatrix>(sequence, size);
}
DOMMatrix* DOMMatrix::fromFloat32Array(NotShared<DOMFloat32Array> float32_array,
@@ -73,8 +74,8 @@ DOMMatrix* DOMMatrix::fromFloat32Array(NotShared<DOMFloat32Array> float32_array,
"for a 3D matrix.");
return nullptr;
}
- return new DOMMatrix(float32_array.View()->Data(),
- float32_array.View()->length());
+ return MakeGarbageCollected<DOMMatrix>(float32_array.View()->Data(),
+ float32_array.View()->length());
}
DOMMatrix* DOMMatrix::fromFloat64Array(NotShared<DOMFloat64Array> float64_array,
@@ -86,8 +87,8 @@ DOMMatrix* DOMMatrix::fromFloat64Array(NotShared<DOMFloat64Array> float64_array,
"for a 3D matrix.");
return nullptr;
}
- return new DOMMatrix(float64_array.View()->Data(),
- float64_array.View()->length());
+ return MakeGarbageCollected<DOMMatrix>(float64_array.View()->Data(),
+ float64_array.View()->length());
}
template <typename T>
@@ -97,32 +98,26 @@ DOMMatrix::DOMMatrix(T sequence, int size)
DOMMatrix::DOMMatrix(const TransformationMatrix& matrix, bool is2d)
: DOMMatrixReadOnly(matrix, is2d) {}
-DOMMatrix* DOMMatrix::fromMatrix2D(DOMMatrix2DInit& other) {
- if (!ValidateAndFixup2D(other)) {
- return nullptr;
- }
- return new DOMMatrix({other.m11(), other.m12(), other.m21(), other.m22(),
- other.m41(), other.m42()},
- true);
-}
-
-DOMMatrix* DOMMatrix::fromMatrix(DOMMatrixInit& other,
+DOMMatrix* DOMMatrix::fromMatrix(DOMMatrixInit* other,
ExceptionState& exception_state) {
if (!ValidateAndFixup(other, exception_state)) {
DCHECK(exception_state.HadException());
return nullptr;
}
- if (other.is2D()) {
- return new DOMMatrix({other.m11(), other.m12(), other.m21(), other.m22(),
- other.m41(), other.m42()},
- other.is2D());
+ if (other->is2D()) {
+ return MakeGarbageCollected<DOMMatrix>(
+ TransformationMatrix(other->m11(), other->m12(), other->m21(),
+ other->m22(), other->m41(), other->m42()),
+ other->is2D());
}
- return new DOMMatrix({other.m11(), other.m12(), other.m13(), other.m14(),
- other.m21(), other.m22(), other.m23(), other.m24(),
- other.m31(), other.m32(), other.m33(), other.m34(),
- other.m41(), other.m42(), other.m43(), other.m44()},
- other.is2D());
+ return MakeGarbageCollected<DOMMatrix>(
+ TransformationMatrix(
+ other->m11(), other->m12(), other->m13(), other->m14(), other->m21(),
+ other->m22(), other->m23(), other->m24(), other->m31(), other->m32(),
+ other->m33(), other->m34(), other->m41(), other->m42(), other->m43(),
+ other->m44()),
+ other->is2D());
}
void DOMMatrix::SetIs2D(bool value) {
@@ -149,7 +144,7 @@ void DOMMatrix::SetNAN() {
matrix_->SetM44(NAN);
}
-DOMMatrix* DOMMatrix::multiplySelf(DOMMatrixInit& other,
+DOMMatrix* DOMMatrix::multiplySelf(DOMMatrixInit* other,
ExceptionState& exception_state) {
DOMMatrix* other_matrix = DOMMatrix::fromMatrix(other, exception_state);
if (!other_matrix) {
@@ -168,7 +163,7 @@ DOMMatrix* DOMMatrix::multiplySelf(const DOMMatrix& other_matrix) {
return this;
}
-DOMMatrix* DOMMatrix::preMultiplySelf(DOMMatrixInit& other,
+DOMMatrix* DOMMatrix::preMultiplySelf(DOMMatrixInit* other,
ExceptionState& exception_state) {
DOMMatrix* other_matrix = DOMMatrix::fromMatrix(other, exception_state);
if (!other_matrix) {
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_matrix.h b/chromium/third_party/blink/renderer/core/geometry/dom_matrix.h
index a0b53bc7fbe..40a3bb8b69f 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_matrix.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_matrix.h
@@ -31,10 +31,12 @@ class CORE_EXPORT DOMMatrix : public DOMMatrixReadOnly {
ExceptionState&);
static DOMMatrix* fromFloat64Array(NotShared<DOMFloat64Array>,
ExceptionState&);
- static DOMMatrix* fromMatrix(DOMMatrixInit&, ExceptionState&);
+ static DOMMatrix* fromMatrix(DOMMatrixInit*, ExceptionState&);
static DOMMatrix* CreateForSerialization(double[], int size);
- // Used by Canvas2D, not defined on the IDL.
- static DOMMatrix* fromMatrix2D(DOMMatrix2DInit&);
+
+ DOMMatrix(const TransformationMatrix&, bool is2d = true);
+ template <typename T>
+ DOMMatrix(T sequence, int size);
void setA(double value) { matrix_->SetM11(value); }
void setB(double value) { matrix_->SetM12(value); }
@@ -90,9 +92,9 @@ class CORE_EXPORT DOMMatrix : public DOMMatrixReadOnly {
SetIs2D(value == 1);
}
- DOMMatrix* multiplySelf(DOMMatrixInit&, ExceptionState&);
+ DOMMatrix* multiplySelf(DOMMatrixInit*, ExceptionState&);
DOMMatrix* multiplySelf(const DOMMatrix& other_matrix);
- DOMMatrix* preMultiplySelf(DOMMatrixInit&, ExceptionState&);
+ DOMMatrix* preMultiplySelf(DOMMatrixInit*, ExceptionState&);
DOMMatrix* translateSelf(double tx = 0, double ty = 0, double tz = 0);
DOMMatrix* scaleSelf(double sx = 1);
DOMMatrix* scaleSelf(double sx,
@@ -123,10 +125,6 @@ class CORE_EXPORT DOMMatrix : public DOMMatrixReadOnly {
ExceptionState&);
private:
- DOMMatrix(const TransformationMatrix&, bool is2d = true);
- template <typename T>
- DOMMatrix(T sequence, int size);
-
void SetIs2D(bool value);
void SetNAN();
};
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc b/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc
index ce881b7d5f3..3a5ac0c294f 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc
@@ -20,51 +20,51 @@
namespace blink {
namespace {
-void SetDictionaryMembers(DOMMatrix2DInit& other) {
- if (!other.hasM11())
- other.setM11(other.hasA() ? other.a() : 1);
+void SetDictionaryMembers(DOMMatrix2DInit* other) {
+ if (!other->hasM11())
+ other->setM11(other->hasA() ? other->a() : 1);
- if (!other.hasM12())
- other.setM12(other.hasB() ? other.b() : 0);
+ if (!other->hasM12())
+ other->setM12(other->hasB() ? other->b() : 0);
- if (!other.hasM21())
- other.setM21(other.hasC() ? other.c() : 0);
+ if (!other->hasM21())
+ other->setM21(other->hasC() ? other->c() : 0);
- if (!other.hasM22())
- other.setM22(other.hasD() ? other.d() : 1);
+ if (!other->hasM22())
+ other->setM22(other->hasD() ? other->d() : 1);
- if (!other.hasM41())
- other.setM41(other.hasE() ? other.e() : 0);
+ if (!other->hasM41())
+ other->setM41(other->hasE() ? other->e() : 0);
- if (!other.hasM42())
- other.setM42(other.hasF() ? other.f() : 0);
+ if (!other->hasM42())
+ other->setM42(other->hasF() ? other->f() : 0);
}
} // namespace
-bool DOMMatrixReadOnly::ValidateAndFixup2D(DOMMatrix2DInit& other) {
- if (other.hasA() && other.hasM11() && other.a() != other.m11() &&
- !(std::isnan(other.a()) && std::isnan(other.m11()))) {
+bool DOMMatrixReadOnly::ValidateAndFixup2D(DOMMatrix2DInit* other) {
+ if (other->hasA() && other->hasM11() && other->a() != other->m11() &&
+ !(std::isnan(other->a()) && std::isnan(other->m11()))) {
return false;
}
- if (other.hasB() && other.hasM12() && other.b() != other.m12() &&
- !(std::isnan(other.b()) && std::isnan(other.m12()))) {
+ if (other->hasB() && other->hasM12() && other->b() != other->m12() &&
+ !(std::isnan(other->b()) && std::isnan(other->m12()))) {
return false;
}
- if (other.hasC() && other.hasM21() && other.c() != other.m21() &&
- !(std::isnan(other.c()) && std::isnan(other.m21()))) {
+ if (other->hasC() && other->hasM21() && other->c() != other->m21() &&
+ !(std::isnan(other->c()) && std::isnan(other->m21()))) {
return false;
}
- if (other.hasD() && other.hasM22() && other.d() != other.m22() &&
- !(std::isnan(other.d()) && std::isnan(other.m22()))) {
+ if (other->hasD() && other->hasM22() && other->d() != other->m22() &&
+ !(std::isnan(other->d()) && std::isnan(other->m22()))) {
return false;
}
- if (other.hasE() && other.hasM41() && other.e() != other.m41() &&
- !(std::isnan(other.e()) && std::isnan(other.m41()))) {
+ if (other->hasE() && other->hasM41() && other->e() != other->m41() &&
+ !(std::isnan(other->e()) && std::isnan(other->m41()))) {
return false;
}
- if (other.hasF() && other.hasM42() && other.f() != other.m42() &&
- !(std::isnan(other.f()) && std::isnan(other.m42()))) {
+ if (other->hasF() && other->hasM42() && other->f() != other->m42() &&
+ !(std::isnan(other->f()) && std::isnan(other->m42()))) {
return false;
}
@@ -72,7 +72,7 @@ bool DOMMatrixReadOnly::ValidateAndFixup2D(DOMMatrix2DInit& other) {
return true;
}
-bool DOMMatrixReadOnly::ValidateAndFixup(DOMMatrixInit& other,
+bool DOMMatrixReadOnly::ValidateAndFixup(DOMMatrixInit* other,
ExceptionState& exception_state) {
if (!ValidateAndFixup2D(other)) {
exception_state.ThrowTypeError(
@@ -80,20 +80,21 @@ bool DOMMatrixReadOnly::ValidateAndFixup(DOMMatrixInit& other,
return false;
}
- if (other.hasIs2D() && other.is2D() &&
- (other.m31() || other.m32() || other.m13() || other.m23() ||
- other.m43() || other.m14() || other.m24() || other.m34() ||
- other.m33() != 1 || other.m44() != 1)) {
+ if (other->hasIs2D() && other->is2D() &&
+ (other->m31() || other->m32() || other->m13() || other->m23() ||
+ other->m43() || other->m14() || other->m24() || other->m34() ||
+ other->m33() != 1 || other->m44() != 1)) {
exception_state.ThrowTypeError(
"The is2D member is set to true but the input matrix is a 3d matrix.");
return false;
}
- if (!other.hasIs2D()) {
- bool is2d = !(other.m31() || other.m32() || other.m13() || other.m23() ||
- other.m43() || other.m14() || other.m24() || other.m34() ||
- other.m33() != 1 || other.m44() != 1);
- other.setIs2D(is2d);
+ if (!other->hasIs2D()) {
+ bool is2d =
+ !(other->m31() || other->m32() || other->m13() || other->m23() ||
+ other->m43() || other->m14() || other->m24() || other->m34() ||
+ other->m33() != 1 || other->m44() != 1);
+ other->setIs2D(is2d);
}
return true;
}
@@ -101,7 +102,7 @@ bool DOMMatrixReadOnly::ValidateAndFixup(DOMMatrixInit& other,
DOMMatrixReadOnly* DOMMatrixReadOnly::Create(
ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return new DOMMatrixReadOnly(TransformationMatrix());
+ return MakeGarbageCollected<DOMMatrixReadOnly>(TransformationMatrix());
}
DOMMatrixReadOnly* DOMMatrixReadOnly::Create(
@@ -115,7 +116,8 @@ DOMMatrixReadOnly* DOMMatrixReadOnly::Create(
return nullptr;
}
- DOMMatrixReadOnly* matrix = new DOMMatrixReadOnly(TransformationMatrix());
+ DOMMatrixReadOnly* matrix =
+ MakeGarbageCollected<DOMMatrixReadOnly>(TransformationMatrix());
matrix->SetMatrixValueFromString(execution_context, init.GetAsString(),
exception_state);
return matrix;
@@ -129,7 +131,7 @@ DOMMatrixReadOnly* DOMMatrixReadOnly::Create(
"for a 3D matrix.");
return nullptr;
}
- return new DOMMatrixReadOnly(sequence, sequence.size());
+ return MakeGarbageCollected<DOMMatrixReadOnly>(sequence, sequence.size());
}
NOTREACHED();
@@ -138,7 +140,7 @@ DOMMatrixReadOnly* DOMMatrixReadOnly::Create(
DOMMatrixReadOnly* DOMMatrixReadOnly::CreateForSerialization(double sequence[],
int size) {
- return new DOMMatrixReadOnly(sequence, size);
+ return MakeGarbageCollected<DOMMatrixReadOnly>(sequence, size);
}
DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat32Array(
@@ -151,8 +153,8 @@ DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat32Array(
"for 3D matrix.");
return nullptr;
}
- return new DOMMatrixReadOnly(float32_array.View()->Data(),
- float32_array.View()->length());
+ return MakeGarbageCollected<DOMMatrixReadOnly>(
+ float32_array.View()->Data(), float32_array.View()->length());
}
DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat64Array(
@@ -165,50 +167,41 @@ DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat64Array(
"for a 3D matrix.");
return nullptr;
}
- return new DOMMatrixReadOnly(float64_array.View()->Data(),
- float64_array.View()->length());
+ return MakeGarbageCollected<DOMMatrixReadOnly>(
+ float64_array.View()->Data(), float64_array.View()->length());
}
DOMMatrixReadOnly* DOMMatrixReadOnly::fromMatrix2D(
- DOMMatrix2DInit& other,
+ DOMMatrix2DInit* other,
ExceptionState& exception_state) {
if (!ValidateAndFixup2D(other)) {
exception_state.ThrowTypeError(
"Property mismatch on matrix initialization.");
return nullptr;
}
- double args[] = {other.m11(), other.m12(), other.m21(),
- other.m22(), other.m41(), other.m42()};
- return new DOMMatrixReadOnly(args, 6);
-}
-
-DOMMatrixReadOnly* DOMMatrixReadOnly::fromMatrix2D(DOMMatrix2DInit& other) {
- if (!ValidateAndFixup2D(other)) {
- return nullptr;
- }
- double args[] = {other.m11(), other.m12(), other.m21(),
- other.m22(), other.m41(), other.m42()};
- return new DOMMatrixReadOnly(args, 6);
+ double args[] = {other->m11(), other->m12(), other->m21(),
+ other->m22(), other->m41(), other->m42()};
+ return MakeGarbageCollected<DOMMatrixReadOnly>(args, 6);
}
DOMMatrixReadOnly* DOMMatrixReadOnly::fromMatrix(
- DOMMatrixInit& other,
+ DOMMatrixInit* other,
ExceptionState& exception_state) {
if (!ValidateAndFixup(other, exception_state)) {
DCHECK(exception_state.HadException());
return nullptr;
}
- if (other.is2D()) {
- double args[] = {other.m11(), other.m12(), other.m21(),
- other.m22(), other.m41(), other.m42()};
- return new DOMMatrixReadOnly(args, 6);
+ if (other->is2D()) {
+ double args[] = {other->m11(), other->m12(), other->m21(),
+ other->m22(), other->m41(), other->m42()};
+ return MakeGarbageCollected<DOMMatrixReadOnly>(args, 6);
}
- double args[] = {other.m11(), other.m12(), other.m13(), other.m14(),
- other.m21(), other.m22(), other.m23(), other.m24(),
- other.m31(), other.m32(), other.m33(), other.m34(),
- other.m41(), other.m42(), other.m43(), other.m44()};
- return new DOMMatrixReadOnly(args, 16);
+ double args[] = {other->m11(), other->m12(), other->m13(), other->m14(),
+ other->m21(), other->m22(), other->m23(), other->m24(),
+ other->m31(), other->m32(), other->m33(), other->m34(),
+ other->m41(), other->m42(), other->m43(), other->m44()};
+ return MakeGarbageCollected<DOMMatrixReadOnly>(args, 16);
}
DOMMatrixReadOnly::~DOMMatrixReadOnly() = default;
@@ -221,7 +214,7 @@ bool DOMMatrixReadOnly::isIdentity() const {
return matrix_->IsIdentity();
}
-DOMMatrix* DOMMatrixReadOnly::multiply(DOMMatrixInit& other,
+DOMMatrix* DOMMatrixReadOnly::multiply(DOMMatrixInit* other,
ExceptionState& exception_state) {
return DOMMatrix::Create(this)->multiplySelf(other, exception_state);
}
@@ -303,21 +296,21 @@ DOMMatrix* DOMMatrixReadOnly::inverse() {
return DOMMatrix::Create(this)->invertSelf();
}
-DOMPoint* DOMMatrixReadOnly::transformPoint(const DOMPointInit& point) {
- if (is2D() && point.z() == 0 && point.w() == 1) {
- double x = point.x() * m11() + point.y() * m21() + m41();
- double y = point.x() * m12() + point.y() * m22() + m42();
+DOMPoint* DOMMatrixReadOnly::transformPoint(const DOMPointInit* point) {
+ if (is2D() && point->z() == 0 && point->w() == 1) {
+ double x = point->x() * m11() + point->y() * m21() + m41();
+ double y = point->x() * m12() + point->y() * m22() + m42();
return DOMPoint::Create(x, y, 0, 1);
}
- double x = point.x() * m11() + point.y() * m21() + point.z() * m31() +
- point.w() * m41();
- double y = point.x() * m12() + point.y() * m22() + point.z() * m32() +
- point.w() * m42();
- double z = point.x() * m13() + point.y() * m23() + point.z() * m33() +
- point.w() * m43();
- double w = point.x() * m14() + point.y() * m24() + point.z() * m34() +
- point.w() * m44();
+ double x = point->x() * m11() + point->y() * m21() + point->z() * m31() +
+ point->w() * m41();
+ double y = point->x() * m12() + point->y() * m22() + point->z() * m32() +
+ point->w() * m42();
+ double z = point->x() * m13() + point->y() * m23() + point->z() * m33() +
+ point->w() * m43();
+ double w = point->x() * m14() + point->y() * m24() + point->z() * m34() +
+ point->w() * m44();
return DOMPoint::Create(x, y, z, w);
}
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h b/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h
index 05d9535f1dc..7970ea5bf47 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h
@@ -36,12 +36,33 @@ class CORE_EXPORT DOMMatrixReadOnly : public ScriptWrappable {
ExceptionState&);
static DOMMatrixReadOnly* fromFloat64Array(NotShared<DOMFloat64Array>,
ExceptionState&);
- static DOMMatrixReadOnly* fromMatrix(DOMMatrixInit&, ExceptionState&);
- static DOMMatrixReadOnly* fromMatrix2D(DOMMatrix2DInit&, ExceptionState&);
+ static DOMMatrixReadOnly* fromMatrix(DOMMatrixInit*, ExceptionState&);
+ static DOMMatrixReadOnly* fromMatrix2D(DOMMatrix2DInit*, ExceptionState&);
static DOMMatrixReadOnly* CreateForSerialization(double[], int size);
+
+ DOMMatrixReadOnly() = default;
+ DOMMatrixReadOnly(const String&, ExceptionState&);
+ DOMMatrixReadOnly(const TransformationMatrix&, bool is2d = true);
+
+ template <typename T>
+ DOMMatrixReadOnly(T sequence, int size) {
+ if (size == 6) {
+ matrix_ =
+ TransformationMatrix::Create(sequence[0], sequence[1], sequence[2],
+ sequence[3], sequence[4], sequence[5]);
+ is2d_ = true;
+ } else if (size == 16) {
+ matrix_ = TransformationMatrix::Create(
+ sequence[0], sequence[1], sequence[2], sequence[3], sequence[4],
+ sequence[5], sequence[6], sequence[7], sequence[8], sequence[9],
+ sequence[10], sequence[11], sequence[12], sequence[13], sequence[14],
+ sequence[15]);
+ is2d_ = false;
+ } else {
+ NOTREACHED();
+ }
+ }
~DOMMatrixReadOnly() override;
- // Used by Canvas2D, not defined on the IDL.
- static DOMMatrixReadOnly* fromMatrix2D(DOMMatrix2DInit&);
double a() const { return matrix_->M11(); }
double b() const { return matrix_->M12(); }
@@ -70,7 +91,7 @@ class CORE_EXPORT DOMMatrixReadOnly : public ScriptWrappable {
bool is2D() const;
bool isIdentity() const;
- DOMMatrix* multiply(DOMMatrixInit&, ExceptionState&);
+ DOMMatrix* multiply(DOMMatrixInit*, ExceptionState&);
DOMMatrix* translate(double tx = 0, double ty = 0, double tz = 0);
DOMMatrix* scale(double sx = 1);
DOMMatrix* scale(double sx,
@@ -97,7 +118,7 @@ class CORE_EXPORT DOMMatrixReadOnly : public ScriptWrappable {
DOMMatrix* flipY();
DOMMatrix* inverse();
- DOMPoint* transformPoint(const DOMPointInit&);
+ DOMPoint* transformPoint(const DOMPointInit*);
NotShared<DOMFloat32Array> toFloat32Array() const;
NotShared<DOMFloat64Array> toFloat64Array() const;
@@ -115,35 +136,12 @@ class CORE_EXPORT DOMMatrixReadOnly : public ScriptWrappable {
}
protected:
- DOMMatrixReadOnly() = default;
- DOMMatrixReadOnly(const String&, ExceptionState&);
- DOMMatrixReadOnly(const TransformationMatrix&, bool is2d = true);
-
- template <typename T>
- DOMMatrixReadOnly(T sequence, int size) {
- if (size == 6) {
- matrix_ =
- TransformationMatrix::Create(sequence[0], sequence[1], sequence[2],
- sequence[3], sequence[4], sequence[5]);
- is2d_ = true;
- } else if (size == 16) {
- matrix_ = TransformationMatrix::Create(
- sequence[0], sequence[1], sequence[2], sequence[3], sequence[4],
- sequence[5], sequence[6], sequence[7], sequence[8], sequence[9],
- sequence[10], sequence[11], sequence[12], sequence[13], sequence[14],
- sequence[15]);
- is2d_ = false;
- } else {
- NOTREACHED();
- }
- }
-
void SetMatrixValueFromString(const ExecutionContext*,
const String&,
ExceptionState&);
- static bool ValidateAndFixup2D(DOMMatrix2DInit&);
- static bool ValidateAndFixup(DOMMatrixInit&, ExceptionState&);
+ static bool ValidateAndFixup2D(DOMMatrix2DInit*);
+ static bool ValidateAndFixup(DOMMatrixInit*, ExceptionState&);
// TransformationMatrix needs to be 16-byte aligned. PartitionAlloc
// supports 16-byte alignment but Oilpan doesn't. So we use an std::unique_ptr
// to allocate TransformationMatrix on PartitionAlloc.
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_matrix_test.cc b/chromium/third_party/blink/renderer/core/geometry/dom_matrix_test.cc
index 00b851ce793..725fb2e20c9 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_matrix_test.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_matrix_test.cc
@@ -12,137 +12,137 @@ namespace blink {
TEST(DOMMatrixTest, Fixup) {
V8TestingScope scope;
- DOMMatrixInit init;
+ DOMMatrixInit* init = DOMMatrixInit::Create();
- EXPECT_FALSE(init.hasA());
- EXPECT_FALSE(init.hasB());
- EXPECT_FALSE(init.hasC());
- EXPECT_FALSE(init.hasD());
- EXPECT_FALSE(init.hasE());
- EXPECT_FALSE(init.hasF());
- EXPECT_FALSE(init.hasM11());
- EXPECT_FALSE(init.hasM12());
- EXPECT_FALSE(init.hasM21());
- EXPECT_FALSE(init.hasM22());
- EXPECT_FALSE(init.hasM41());
- EXPECT_FALSE(init.hasM42());
+ EXPECT_FALSE(init->hasA());
+ EXPECT_FALSE(init->hasB());
+ EXPECT_FALSE(init->hasC());
+ EXPECT_FALSE(init->hasD());
+ EXPECT_FALSE(init->hasE());
+ EXPECT_FALSE(init->hasF());
+ EXPECT_FALSE(init->hasM11());
+ EXPECT_FALSE(init->hasM12());
+ EXPECT_FALSE(init->hasM21());
+ EXPECT_FALSE(init->hasM22());
+ EXPECT_FALSE(init->hasM41());
+ EXPECT_FALSE(init->hasM42());
- init.setA(1.0);
- init.setB(2.0);
- init.setC(3.0);
- init.setD(4.0);
- init.setE(5.0);
- init.setF(6.0);
+ init->setA(1.0);
+ init->setB(2.0);
+ init->setC(3.0);
+ init->setD(4.0);
+ init->setE(5.0);
+ init->setF(6.0);
- EXPECT_TRUE(init.hasA());
- EXPECT_TRUE(init.hasB());
- EXPECT_TRUE(init.hasC());
- EXPECT_TRUE(init.hasD());
- EXPECT_TRUE(init.hasE());
- EXPECT_TRUE(init.hasF());
- EXPECT_FALSE(init.hasM11());
- EXPECT_FALSE(init.hasM12());
- EXPECT_FALSE(init.hasM21());
- EXPECT_FALSE(init.hasM22());
- EXPECT_FALSE(init.hasM41());
- EXPECT_FALSE(init.hasM42());
+ EXPECT_TRUE(init->hasA());
+ EXPECT_TRUE(init->hasB());
+ EXPECT_TRUE(init->hasC());
+ EXPECT_TRUE(init->hasD());
+ EXPECT_TRUE(init->hasE());
+ EXPECT_TRUE(init->hasF());
+ EXPECT_FALSE(init->hasM11());
+ EXPECT_FALSE(init->hasM12());
+ EXPECT_FALSE(init->hasM21());
+ EXPECT_FALSE(init->hasM22());
+ EXPECT_FALSE(init->hasM41());
+ EXPECT_FALSE(init->hasM42());
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
- EXPECT_TRUE(init.hasA());
- EXPECT_TRUE(init.hasB());
- EXPECT_TRUE(init.hasC());
- EXPECT_TRUE(init.hasD());
- EXPECT_TRUE(init.hasE());
- EXPECT_TRUE(init.hasF());
- EXPECT_TRUE(init.hasM11());
- EXPECT_TRUE(init.hasM12());
- EXPECT_TRUE(init.hasM21());
- EXPECT_TRUE(init.hasM22());
- EXPECT_TRUE(init.hasM41());
- EXPECT_TRUE(init.hasM42());
- EXPECT_EQ(1.0, init.m11());
- EXPECT_EQ(2.0, init.m12());
- EXPECT_EQ(3.0, init.m21());
- EXPECT_EQ(4.0, init.m22());
- EXPECT_EQ(5.0, init.m41());
- EXPECT_EQ(6.0, init.m42());
+ EXPECT_TRUE(init->hasA());
+ EXPECT_TRUE(init->hasB());
+ EXPECT_TRUE(init->hasC());
+ EXPECT_TRUE(init->hasD());
+ EXPECT_TRUE(init->hasE());
+ EXPECT_TRUE(init->hasF());
+ EXPECT_TRUE(init->hasM11());
+ EXPECT_TRUE(init->hasM12());
+ EXPECT_TRUE(init->hasM21());
+ EXPECT_TRUE(init->hasM22());
+ EXPECT_TRUE(init->hasM41());
+ EXPECT_TRUE(init->hasM42());
+ EXPECT_EQ(1.0, init->m11());
+ EXPECT_EQ(2.0, init->m12());
+ EXPECT_EQ(3.0, init->m21());
+ EXPECT_EQ(4.0, init->m22());
+ EXPECT_EQ(5.0, init->m41());
+ EXPECT_EQ(6.0, init->m42());
}
TEST(DOMMatrixTest, FixupWithFallback) {
V8TestingScope scope;
- DOMMatrixInit init;
+ DOMMatrixInit* init = DOMMatrixInit::Create();
- EXPECT_FALSE(init.hasA());
- EXPECT_FALSE(init.hasB());
- EXPECT_FALSE(init.hasC());
- EXPECT_FALSE(init.hasD());
- EXPECT_FALSE(init.hasE());
- EXPECT_FALSE(init.hasF());
- EXPECT_FALSE(init.hasM11());
- EXPECT_FALSE(init.hasM12());
- EXPECT_FALSE(init.hasM21());
- EXPECT_FALSE(init.hasM22());
- EXPECT_FALSE(init.hasM41());
- EXPECT_FALSE(init.hasM42());
+ EXPECT_FALSE(init->hasA());
+ EXPECT_FALSE(init->hasB());
+ EXPECT_FALSE(init->hasC());
+ EXPECT_FALSE(init->hasD());
+ EXPECT_FALSE(init->hasE());
+ EXPECT_FALSE(init->hasF());
+ EXPECT_FALSE(init->hasM11());
+ EXPECT_FALSE(init->hasM12());
+ EXPECT_FALSE(init->hasM21());
+ EXPECT_FALSE(init->hasM22());
+ EXPECT_FALSE(init->hasM41());
+ EXPECT_FALSE(init->hasM42());
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
- EXPECT_TRUE(init.hasM11());
- EXPECT_TRUE(init.hasM12());
- EXPECT_TRUE(init.hasM21());
- EXPECT_TRUE(init.hasM22());
- EXPECT_TRUE(init.hasM41());
- EXPECT_TRUE(init.hasM42());
- EXPECT_EQ(1.0, init.m11());
- EXPECT_EQ(0.0, init.m12());
- EXPECT_EQ(0.0, init.m21());
- EXPECT_EQ(1.0, init.m22());
- EXPECT_EQ(0.0, init.m41());
- EXPECT_EQ(0.0, init.m42());
+ EXPECT_TRUE(init->hasM11());
+ EXPECT_TRUE(init->hasM12());
+ EXPECT_TRUE(init->hasM21());
+ EXPECT_TRUE(init->hasM22());
+ EXPECT_TRUE(init->hasM41());
+ EXPECT_TRUE(init->hasM42());
+ EXPECT_EQ(1.0, init->m11());
+ EXPECT_EQ(0.0, init->m12());
+ EXPECT_EQ(0.0, init->m21());
+ EXPECT_EQ(1.0, init->m22());
+ EXPECT_EQ(0.0, init->m41());
+ EXPECT_EQ(0.0, init->m42());
}
TEST(DOMMatrixTest, ThrowExceptionIfTwoValuesAreDifferent) {
V8TestingScope scope;
{
- DOMMatrixInit init;
- init.setA(1.0);
- init.setM11(2.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setA(1.0);
+ init->setM11(2.0);
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
{
- DOMMatrixInit init;
- init.setB(1.0);
- init.setM12(2.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setB(1.0);
+ init->setM12(2.0);
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
{
- DOMMatrixInit init;
- init.setC(1.0);
- init.setM21(2.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setC(1.0);
+ init->setM21(2.0);
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
{
- DOMMatrixInit init;
- init.setD(1.0);
- init.setM22(2.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setD(1.0);
+ init->setM22(2.0);
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
{
- DOMMatrixInit init;
- init.setE(1.0);
- init.setM41(2.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setE(1.0);
+ init->setM41(2.0);
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
{
- DOMMatrixInit init;
- init.setF(1.0);
- init.setM42(2.0);
+ DOMMatrixInit* init = DOMMatrixInit::Create();
+ init->setF(1.0);
+ init->setM42(2.0);
DOMMatrix::fromMatrix(init, scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
}
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_point.cc b/chromium/third_party/blink/renderer/core/geometry/dom_point.cc
index 717f07474a0..7b05d53a4f5 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_point.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_point.cc
@@ -9,11 +9,12 @@
namespace blink {
DOMPoint* DOMPoint::Create(double x, double y, double z, double w) {
- return new DOMPoint(x, y, z, w);
+ return MakeGarbageCollected<DOMPoint>(x, y, z, w);
}
-DOMPoint* DOMPoint::fromPoint(const DOMPointInit& other) {
- return new DOMPoint(other.x(), other.y(), other.z(), other.w());
+DOMPoint* DOMPoint::fromPoint(const DOMPointInit* other) {
+ return MakeGarbageCollected<DOMPoint>(other->x(), other->y(), other->z(),
+ other->w());
}
DOMPoint::DOMPoint(double x, double y, double z, double w)
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_point.h b/chromium/third_party/blink/renderer/core/geometry/dom_point.h
index 0f237c77f1e..da0a9c80eb2 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_point.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_point.h
@@ -17,15 +17,14 @@ class CORE_EXPORT DOMPoint final : public DOMPointReadOnly {
public:
static DOMPoint* Create(double x, double y, double z = 0, double w = 1);
- static DOMPoint* fromPoint(const DOMPointInit&);
+ static DOMPoint* fromPoint(const DOMPointInit*);
+
+ DOMPoint(double x, double y, double z, double w);
void setX(double x) { x_ = x; }
void setY(double y) { y_ = y; }
void setZ(double z) { z_ = z; }
void setW(double w) { w_ = w; }
-
- protected:
- DOMPoint(double x, double y, double z, double w);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.cc b/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.cc
index 894032c5808..57621db6760 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.cc
@@ -18,7 +18,7 @@ DOMPointReadOnly* DOMPointReadOnly::Create(double x,
double y,
double z,
double w) {
- return new DOMPointReadOnly(x, y, z, w);
+ return MakeGarbageCollected<DOMPointReadOnly>(x, y, z, w);
}
ScriptValue DOMPointReadOnly::toJSONForBinding(
@@ -31,11 +31,12 @@ ScriptValue DOMPointReadOnly::toJSONForBinding(
return result.GetScriptValue();
}
-DOMPointReadOnly* DOMPointReadOnly::fromPoint(const DOMPointInit& other) {
- return new DOMPointReadOnly(other.x(), other.y(), other.z(), other.w());
+DOMPointReadOnly* DOMPointReadOnly::fromPoint(const DOMPointInit* other) {
+ return MakeGarbageCollected<DOMPointReadOnly>(other->x(), other->y(),
+ other->z(), other->w());
}
-DOMPoint* DOMPointReadOnly::matrixTransform(DOMMatrixInit& other,
+DOMPoint* DOMPointReadOnly::matrixTransform(DOMMatrixInit* other,
ExceptionState& exception_state) {
DOMMatrixReadOnly* matrix =
DOMMatrixReadOnly::fromMatrix(other, exception_state);
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.h b/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.h
index 38f12c061bf..c2215620184 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_point_read_only.h
@@ -23,7 +23,9 @@ class CORE_EXPORT DOMPointReadOnly : public ScriptWrappable {
public:
static DOMPointReadOnly* Create(double x, double y, double z, double w);
- static DOMPointReadOnly* fromPoint(const DOMPointInit&);
+ static DOMPointReadOnly* fromPoint(const DOMPointInit*);
+
+ DOMPointReadOnly(double x, double y, double z, double w);
double x() const { return x_; }
double y() const { return y_; }
@@ -31,11 +33,9 @@ class CORE_EXPORT DOMPointReadOnly : public ScriptWrappable {
double w() const { return w_; }
ScriptValue toJSONForBinding(ScriptState*) const;
- DOMPoint* matrixTransform(DOMMatrixInit&, ExceptionState&);
+ DOMPoint* matrixTransform(DOMMatrixInit*, ExceptionState&);
protected:
- DOMPointReadOnly(double x, double y, double z, double w);
-
double x_;
double y_;
double z_;
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_quad.cc b/chromium/third_party/blink/renderer/core/geometry/dom_quad.cc
index 4d40dfd5c7e..2078e62d72e 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_quad.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_quad.cc
@@ -12,22 +12,24 @@
namespace blink {
-DOMQuad* DOMQuad::Create(const DOMPointInit& p1,
- const DOMPointInit& p2,
- const DOMPointInit& p3,
- const DOMPointInit& p4) {
- return new DOMQuad(p1, p2, p3, p4);
+DOMQuad* DOMQuad::Create(const DOMPointInit* p1,
+ const DOMPointInit* p2,
+ const DOMPointInit* p3,
+ const DOMPointInit* p4) {
+ return MakeGarbageCollected<DOMQuad>(p1, p2, p3, p4);
}
-DOMQuad* DOMQuad::fromRect(const DOMRectInit& other) {
- return new DOMQuad(other.x(), other.y(), other.width(), other.height());
+DOMQuad* DOMQuad::fromRect(const DOMRectInit* other) {
+ return MakeGarbageCollected<DOMQuad>(other->x(), other->y(), other->width(),
+ other->height());
}
-DOMQuad* DOMQuad::fromQuad(const DOMQuadInit& other) {
- return new DOMQuad(other.hasP1() ? other.p1() : DOMPointInit(),
- other.hasP2() ? other.p2() : DOMPointInit(),
- other.hasP3() ? other.p3() : DOMPointInit(),
- other.hasP3() ? other.p4() : DOMPointInit());
+DOMQuad* DOMQuad::fromQuad(const DOMQuadInit* other) {
+ return MakeGarbageCollected<DOMQuad>(
+ other->hasP1() ? other->p1() : DOMPointInit::Create(),
+ other->hasP2() ? other->p2() : DOMPointInit::Create(),
+ other->hasP3() ? other->p3() : DOMPointInit::Create(),
+ other->hasP3() ? other->p4() : DOMPointInit::Create());
}
DOMRect* DOMQuad::getBounds() {
@@ -49,10 +51,10 @@ void DOMQuad::CalculateBounds() {
bottom_ = std::max(bottom_, p4()->y());
}
-DOMQuad::DOMQuad(const DOMPointInit& p1,
- const DOMPointInit& p2,
- const DOMPointInit& p3,
- const DOMPointInit& p4)
+DOMQuad::DOMQuad(const DOMPointInit* p1,
+ const DOMPointInit* p2,
+ const DOMPointInit* p3,
+ const DOMPointInit* p4)
: p1_(DOMPoint::fromPoint(p1)),
p2_(DOMPoint::fromPoint(p2)),
p3_(DOMPoint::fromPoint(p3)),
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_quad.h b/chromium/third_party/blink/renderer/core/geometry/dom_quad.h
index 6dec8baa7f3..ff6c6c3d331 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_quad.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_quad.h
@@ -21,12 +21,18 @@ class CORE_EXPORT DOMQuad : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DOMQuad* Create(const DOMPointInit& p1,
- const DOMPointInit& p2,
- const DOMPointInit& p3,
- const DOMPointInit& p4);
- static DOMQuad* fromRect(const DOMRectInit&);
- static DOMQuad* fromQuad(const DOMQuadInit&);
+ static DOMQuad* Create(const DOMPointInit* p1,
+ const DOMPointInit* p2,
+ const DOMPointInit* p3,
+ const DOMPointInit* p4);
+ static DOMQuad* fromRect(const DOMRectInit*);
+ static DOMQuad* fromQuad(const DOMQuadInit*);
+
+ DOMQuad(const DOMPointInit* p1,
+ const DOMPointInit* p2,
+ const DOMPointInit* p3,
+ const DOMPointInit* p4);
+ DOMQuad(double x, double y, double width, double height);
DOMPoint* p1() const { return p1_; }
DOMPoint* p2() const { return p2_; }
@@ -46,12 +52,6 @@ class CORE_EXPORT DOMQuad : public ScriptWrappable {
}
private:
- DOMQuad(const DOMPointInit& p1,
- const DOMPointInit& p2,
- const DOMPointInit& p3,
- const DOMPointInit& p4);
- DOMQuad(double x, double y, double width, double height);
-
void CalculateBounds();
Member<DOMPoint> p1_;
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_rect.cc b/chromium/third_party/blink/renderer/core/geometry/dom_rect.cc
index 18dc2a9653c..7d519c4b33b 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_rect.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_rect.cc
@@ -9,15 +9,17 @@
namespace blink {
DOMRect* DOMRect::Create(double x, double y, double width, double height) {
- return new DOMRect(x, y, width, height);
+ return MakeGarbageCollected<DOMRect>(x, y, width, height);
}
DOMRect* DOMRect::FromFloatRect(const FloatRect& rect) {
- return new DOMRect(rect.X(), rect.Y(), rect.Width(), rect.Height());
+ return MakeGarbageCollected<DOMRect>(rect.X(), rect.Y(), rect.Width(),
+ rect.Height());
}
-DOMRect* DOMRect::fromRect(const DOMRectInit& other) {
- return new DOMRect(other.x(), other.y(), other.width(), other.height());
+DOMRect* DOMRect::fromRect(const DOMRectInit* other) {
+ return MakeGarbageCollected<DOMRect>(other->x(), other->y(), other->width(),
+ other->height());
}
DOMRect::DOMRect(double x, double y, double width, double height)
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_rect.h b/chromium/third_party/blink/renderer/core/geometry/dom_rect.h
index 34aac645e9a..35318a62d71 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_rect.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_rect.h
@@ -24,15 +24,14 @@ class CORE_EXPORT DOMRect final : public DOMRectReadOnly {
double width = 0,
double height = 0);
static DOMRect* FromFloatRect(const FloatRect&);
- static DOMRect* fromRect(const DOMRectInit&);
+ static DOMRect* fromRect(const DOMRectInit*);
+
+ DOMRect(double x, double y, double z, double w);
void setX(double x) { x_ = x; }
void setY(double y) { y_ = y; }
void setWidth(double width) { width_ = width; }
void setHeight(double height) { height_ = height; }
-
- protected:
- DOMRect(double x, double y, double z, double w);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_rect_list.h b/chromium/third_party/blink/renderer/core/geometry/dom_rect_list.h
index d5e13991de7..f3dc17bf273 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_rect_list.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_rect_list.h
@@ -39,22 +39,16 @@ class CORE_EXPORT DOMRectList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DOMRectList* Create() { return new DOMRectList; }
+ static DOMRectList* Create() { return MakeGarbageCollected<DOMRectList>(); }
static DOMRectList* Create(const Vector<FloatQuad>& quads) {
- return new DOMRectList(quads);
+ return MakeGarbageCollected<DOMRectList>(quads);
}
template <typename Rects>
static DOMRectList* Create(const Rects& rects) {
- return new DOMRectList(rects);
+ return MakeGarbageCollected<DOMRectList>(rects);
}
- unsigned length() const;
- DOMRect* item(unsigned index);
-
- void Trace(blink::Visitor*) override;
-
- private:
DOMRectList();
template <typename Rects>
@@ -66,6 +60,12 @@ class CORE_EXPORT DOMRectList final : public ScriptWrappable {
explicit DOMRectList(const Vector<FloatQuad>&);
+ unsigned length() const;
+ DOMRect* item(unsigned index);
+
+ void Trace(blink::Visitor*) override;
+
+ private:
HeapVector<Member<DOMRect>> list_;
};
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc b/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc
index 58593ff5f40..60cfca3bbdb 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc
@@ -14,7 +14,7 @@ DOMRectReadOnly* DOMRectReadOnly::Create(double x,
double y,
double width,
double height) {
- return new DOMRectReadOnly(x, y, width, height);
+ return MakeGarbageCollected<DOMRectReadOnly>(x, y, width, height);
}
ScriptValue DOMRectReadOnly::toJSONForBinding(ScriptState* script_state) const {
@@ -31,16 +31,18 @@ ScriptValue DOMRectReadOnly::toJSONForBinding(ScriptState* script_state) const {
}
DOMRectReadOnly* DOMRectReadOnly::FromIntRect(const IntRect& rect) {
- return new DOMRectReadOnly(rect.X(), rect.Y(), rect.Width(), rect.Height());
+ return MakeGarbageCollected<DOMRectReadOnly>(rect.X(), rect.Y(), rect.Width(),
+ rect.Height());
}
DOMRectReadOnly* DOMRectReadOnly::FromFloatRect(const FloatRect& rect) {
- return new DOMRectReadOnly(rect.X(), rect.Y(), rect.Width(), rect.Height());
+ return MakeGarbageCollected<DOMRectReadOnly>(rect.X(), rect.Y(), rect.Width(),
+ rect.Height());
}
-DOMRectReadOnly* DOMRectReadOnly::fromRect(const DOMRectInit& other) {
- return new DOMRectReadOnly(other.x(), other.y(), other.width(),
- other.height());
+DOMRectReadOnly* DOMRectReadOnly::fromRect(const DOMRectInit* other) {
+ return MakeGarbageCollected<DOMRectReadOnly>(other->x(), other->y(),
+ other->width(), other->height());
}
DOMRectReadOnly::DOMRectReadOnly(double x,
diff --git a/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.h b/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.h
index d7f0014342c..77398f0ee11 100644
--- a/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.h
+++ b/chromium/third_party/blink/renderer/core/geometry/dom_rect_read_only.h
@@ -26,7 +26,9 @@ class CORE_EXPORT DOMRectReadOnly : public ScriptWrappable {
double height);
static DOMRectReadOnly* FromIntRect(const IntRect&);
static DOMRectReadOnly* FromFloatRect(const FloatRect&);
- static DOMRectReadOnly* fromRect(const DOMRectInit&);
+ static DOMRectReadOnly* fromRect(const DOMRectInit*);
+
+ DOMRectReadOnly(double x, double y, double width, double height);
double x() const { return x_; }
double y() const { return y_; }
@@ -41,8 +43,6 @@ class CORE_EXPORT DOMRectReadOnly : public ScriptWrappable {
ScriptValue toJSONForBinding(ScriptState*) const;
protected:
- DOMRectReadOnly(double x, double y, double width, double height);
-
double x_;
double y_;
double width_;
diff --git a/chromium/third_party/blink/renderer/core/html/BUILD.gn b/chromium/third_party/blink/renderer/core/html/BUILD.gn
index ebb55748648..483f737abc3 100644
--- a/chromium/third_party/blink/renderer/core/html/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/html/BUILD.gn
@@ -56,6 +56,8 @@ blink_core_sources("html") {
"custom/custom_element_descriptor_hash.h",
"custom/custom_element_disconnected_callback_reaction.cc",
"custom/custom_element_disconnected_callback_reaction.h",
+ "custom/custom_element_form_associated_callback_reaction.cc",
+ "custom/custom_element_form_associated_callback_reaction.h",
"custom/custom_element_reaction.cc",
"custom/custom_element_reaction.h",
"custom/custom_element_reaction_queue.cc",
@@ -68,6 +70,8 @@ blink_core_sources("html") {
"custom/custom_element_upgrade_reaction.h",
"custom/custom_element_upgrade_sorter.cc",
"custom/custom_element_upgrade_sorter.h",
+ "custom/element_internals.cc",
+ "custom/element_internals.h",
"custom/v0_custom_element.cc",
"custom/v0_custom_element.h",
"custom/v0_custom_element_async_import_microtask_queue.cc",
@@ -500,6 +504,8 @@ blink_core_sources("html") {
"media/picture_in_picture_interstitial.h",
"plugin_document.cc",
"plugin_document.h",
+ "portal/document_portals.cc",
+ "portal/document_portals.h",
"portal/html_portal_element.cc",
"portal/html_portal_element.h",
"rel_list.cc",
@@ -564,7 +570,6 @@ blink_core_sources("html") {
"track/vtt/vtt_token.h",
"track/vtt/vtt_tokenizer.cc",
"track/vtt/vtt_tokenizer.h",
- "void_callback.h",
"window_name_collection.cc",
"window_name_collection.h",
]
diff --git a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.cc b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.cc
index 9666026725e..f9c46deb318 100644
--- a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.cc
+++ b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.cc
@@ -249,9 +249,13 @@ void AnchorElementMetrics::MaybeReportViewportMetricsOnLoad(
for (const auto& member_element : sender->GetAnchorElements()) {
const HTMLAnchorElement& anchor_element = *member_element;
- // We ignore anchor elements that are not in the visual viewport.
- if (!anchor_element.Href().ProtocolIsInHTTPFamily() ||
- anchor_element.VisibleBoundsInVisualViewport().IsEmpty()) {
+ if (!anchor_element.Href().ProtocolIsInHTTPFamily())
+ continue;
+
+ if (anchor_element.VisibleBoundsInVisualViewport().IsEmpty() &&
+ (!anchor_element.GetDocument().GetFrame() ||
+ !GetRootDocument(anchor_element) ||
+ !IsUrlIncrementedByOne(anchor_element))) {
continue;
}
diff --git a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc
index 04a32b6b8c2..78cd5f0a282 100644
--- a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc
+++ b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/html/anchor_element_metrics_sender.h"
+#include "base/metrics/histogram_macros.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -12,6 +13,20 @@
namespace blink {
+namespace {
+
+// Returns true if |anchor_element| should be discarded, and not used for
+// navigation prediction.
+bool ShouldDiscardAnchorElement(const HTMLAnchorElement& anchor_element) {
+ Frame* frame = anchor_element.GetDocument().GetFrame();
+ if (!frame || !frame->IsLocalFrame())
+ return true;
+ LocalFrame* local_frame = ToLocalFrame(frame);
+ return local_frame->IsAdSubframe();
+}
+
+} // namespace
+
// static
const char AnchorElementMetricsSender::kSupplementName[] =
"DocumentAnchorElementMetricsSender";
@@ -64,6 +79,15 @@ void AnchorElementMetricsSender::SendAnchorMetricsVectorToBrowser(
void AnchorElementMetricsSender::AddAnchorElement(HTMLAnchorElement& element) {
if (has_onload_report_sent_)
return;
+
+ bool is_ad_frame_element = ShouldDiscardAnchorElement(element);
+ UMA_HISTOGRAM_BOOLEAN("AnchorElementMetrics.IsAdFrameElement",
+ is_ad_frame_element);
+
+ // We ignore anchor elements that are in ad frames.
+ if (is_ad_frame_element)
+ return;
+
anchor_elements_.insert(&element);
}
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/OWNERS b/chromium/third_party/blink/renderer/core/html/canvas/OWNERS
index ce598427535..5ef87b1aa3f 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/OWNERS
+++ b/chromium/third_party/blink/renderer/core/html/canvas/OWNERS
@@ -1,6 +1,4 @@
fserb@chromium.org
-junov@chromium.org
-xlai@chromium.org
# TEAM: paint-dev@chromium.org
# COMPONENT: Blink>Canvas
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc b/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc
index d7520c16106..ddb353c2327 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc
@@ -5,6 +5,8 @@
#include "third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h"
#include "base/location.h"
+#include "base/metrics/histogram_functions.h"
+#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
@@ -19,9 +21,9 @@
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/image-encoders/image_encoder_utils.h"
#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/skia/include/core/SkSurface.h"
@@ -73,66 +75,54 @@ bool IsEncodeRowDeadlineNearOrPassed(TimeTicks deadline, size_t image_width) {
void RecordIdleTaskStatusHistogram(
CanvasAsyncBlobCreator::IdleTaskStatus status) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram,
- to_blob_idle_task_status,
- ("Blink.Canvas.ToBlob.IdleTaskStatus",
- CanvasAsyncBlobCreator::kIdleTaskCount));
- to_blob_idle_task_status.Count(status);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.ToBlob.IdleTaskStatus", status);
}
-// This enum is used in histogram and any more types should be appended at the
-// end of the list.
-enum ElapsedTimeHistogramType {
- kInitiateEncodingDelay,
- kCompleteEncodingDelay,
- kToBlobDuration,
- kNumberOfElapsedTimeHistogramTypes
-};
-
-void RecordElapsedTimeHistogram(ElapsedTimeHistogramType type,
- ImageEncodingMimeType mime_type,
- TimeDelta elapsed_time) {
- if (type == kInitiateEncodingDelay) {
- if (mime_type == kMimeTypePng) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_png_initiate_encoding_counter,
- ("Blink.Canvas.ToBlob.InitiateEncodingDelay.PNG", 0, 10000000, 50));
- to_blob_png_initiate_encoding_counter.CountMicroseconds(elapsed_time);
- } else if (mime_type == kMimeTypeJpeg) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_jpeg_initiate_encoding_counter,
- ("Blink.Canvas.ToBlob.InitiateEncodingDelay.JPEG", 0, 10000000, 50));
- to_blob_jpeg_initiate_encoding_counter.CountMicroseconds(elapsed_time);
- }
- } else if (type == kCompleteEncodingDelay) {
- if (mime_type == kMimeTypePng) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_png_idle_encode_counter,
- ("Blink.Canvas.ToBlob.CompleteEncodingDelay.PNG", 0, 10000000, 50));
- to_blob_png_idle_encode_counter.CountMicroseconds(elapsed_time);
- } else if (mime_type == kMimeTypeJpeg) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_jpeg_idle_encode_counter,
- ("Blink.Canvas.ToBlob.CompleteEncodingDelay.JPEG", 0, 10000000, 50));
- to_blob_jpeg_idle_encode_counter.CountMicroseconds(elapsed_time);
- }
- } else if (type == kToBlobDuration) {
- if (mime_type == kMimeTypePng) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_png_counter,
- ("Blink.Canvas.ToBlobDuration.PNG", 0, 10000000, 50));
- to_blob_png_counter.CountMicroseconds(elapsed_time);
- } else if (mime_type == kMimeTypeJpeg) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_jpeg_counter,
- ("Blink.Canvas.ToBlobDuration.JPEG", 0, 10000000, 50));
- to_blob_jpeg_counter.CountMicroseconds(elapsed_time);
- } else if (mime_type == kMimeTypeWebp) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, to_blob_webp_counter,
- ("Blink.Canvas.ToBlobDuration.WEBP", 0, 10000000, 50));
- to_blob_webp_counter.CountMicroseconds(elapsed_time);
- }
+void RecordInitiateEncodingTimeHistogram(ImageEncodingMimeType mime_type,
+ TimeDelta elapsed_time) {
+ if (mime_type == kMimeTypePng) {
+ UmaHistogramMicrosecondsTimes(
+ "Blink.Canvas.ToBlob.InitiateEncodingDelay.PNG", elapsed_time);
+ } else if (mime_type == kMimeTypeJpeg) {
+ UmaHistogramMicrosecondsTimes(
+ "Blink.Canvas.ToBlob.InitiateEncodingDelay.JPEG", elapsed_time);
+ }
+}
+
+void RecordCompleteEncodingTimeHistogram(ImageEncodingMimeType mime_type,
+ TimeDelta elapsed_time) {
+ if (mime_type == kMimeTypePng) {
+ UmaHistogramMicrosecondsTimes(
+ "Blink.Canvas.ToBlob.CompleteEncodingDelay.PNG", elapsed_time);
+ } else if (mime_type == kMimeTypeJpeg) {
+ UmaHistogramMicrosecondsTimes(
+ "Blink.Canvas.ToBlob.CompleteEncodingDelay.JPEG", elapsed_time);
+ }
+}
+
+void RecordScaledDurationHistogram(ImageEncodingMimeType mime_type,
+ TimeDelta elapsed_time,
+ float width,
+ float height) {
+ float sqrt_pixels = std::sqrt(width) * std::sqrt(height);
+ float scaled_time_float =
+ elapsed_time.InMicrosecondsF() / (sqrt_pixels == 0 ? 1.0f : sqrt_pixels);
+
+ // If scaled_time_float overflows as integer, CheckedNumeric will store it
+ // as invalid, then ValueOrDefault will return the maximum int.
+ base::CheckedNumeric<int> checked_scaled_time = scaled_time_float;
+ int scaled_time_int =
+ checked_scaled_time.ValueOrDefault(std::numeric_limits<int>::max());
+
+ if (mime_type == kMimeTypePng) {
+ UMA_HISTOGRAM_COUNTS_100000("Blink.Canvas.ToBlob.ScaledDuration.PNG",
+ scaled_time_int);
+ } else if (mime_type == kMimeTypeJpeg) {
+ UMA_HISTOGRAM_COUNTS_100000("Blink.Canvas.ToBlob.ScaledDuration.JPEG",
+ scaled_time_int);
+ } else if (mime_type == kMimeTypeWebp) {
+ UMA_HISTOGRAM_COUNTS_100000("Blink.Canvas.ToBlob.ScaledDuration.WEBP",
+ scaled_time_int);
}
}
@@ -145,26 +135,26 @@ CanvasAsyncBlobCreator* CanvasAsyncBlobCreator::Create(
ToBlobFunctionType function_type,
TimeTicks start_time,
ExecutionContext* context) {
- ImageEncodeOptions options;
- options.setType(ImageEncodingMimeTypeName(mime_type));
- return new CanvasAsyncBlobCreator(image, options, function_type, callback,
- start_time, context, nullptr);
+ ImageEncodeOptions* options = ImageEncodeOptions::Create();
+ options->setType(ImageEncodingMimeTypeName(mime_type));
+ return MakeGarbageCollected<CanvasAsyncBlobCreator>(
+ image, options, function_type, callback, start_time, context, nullptr);
}
CanvasAsyncBlobCreator* CanvasAsyncBlobCreator::Create(
scoped_refptr<StaticBitmapImage> image,
- const ImageEncodeOptions& options,
+ const ImageEncodeOptions* options,
ToBlobFunctionType function_type,
TimeTicks start_time,
ExecutionContext* context,
ScriptPromiseResolver* resolver) {
- return new CanvasAsyncBlobCreator(image, options, function_type, nullptr,
- start_time, context, resolver);
+ return MakeGarbageCollected<CanvasAsyncBlobCreator>(
+ image, options, function_type, nullptr, start_time, context, resolver);
}
CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
scoped_refptr<StaticBitmapImage> image,
- const ImageEncodeOptions& options,
+ const ImageEncodeOptions* options,
ToBlobFunctionType function_type,
V8BlobCallback* callback,
TimeTicks start_time,
@@ -183,7 +173,7 @@ CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
DCHECK(image);
mime_type_ = ImageEncoderUtils::ToEncodingMimeType(
- encode_options_.type(),
+ encode_options_->type(),
ImageEncoderUtils::kEncodeReasonConvertToBlobPromise);
// We use pixmap to access the image pixels. Make the image unaccelerated if
@@ -218,18 +208,18 @@ CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
DCHECK(!src_data_.colorSpace());
} else {
sk_sp<SkColorSpace> blob_color_space =
- BlobColorSpaceToSkColorSpace(encode_options_.colorSpace());
+ BlobColorSpaceToSkColorSpace(encode_options_->colorSpace());
bool needs_color_space_conversion = !ApproximatelyEqualSkColorSpaces(
skia_image->refColorSpace(), blob_color_space);
if (needs_color_space_conversion && !skia_image->colorSpace()) {
skia_image->peekPixels(&src_data_);
src_data_.setColorSpace(SkColorSpace::MakeSRGB());
- skia_image = SkImage::MakeFromRaster(src_data_, nullptr, nullptr);
+ skia_image = SkImage::MakeRasterCopy(src_data_);
DCHECK(skia_image->colorSpace());
}
SkColorType target_color_type = kN32_SkColorType;
- if (encode_options_.pixelFormat() == kRGBA16ImagePixelFormatName)
+ if (encode_options_->pixelFormat() == kRGBA16ImagePixelFormatName)
target_color_type = kRGBA_F16_SkColorType;
// We can do color space and color type conversion together.
if (needs_color_space_conversion) {
@@ -285,10 +275,10 @@ void CanvasAsyncBlobCreator::Dispose() {
image_ = nullptr;
}
-ImageEncodeOptions CanvasAsyncBlobCreator::GetImageEncodeOptionsForMimeType(
+ImageEncodeOptions* CanvasAsyncBlobCreator::GetImageEncodeOptionsForMimeType(
ImageEncodingMimeType mime_type) {
- ImageEncodeOptions encode_options;
- encode_options.setType(ImageEncodingMimeTypeName(mime_type));
+ ImageEncodeOptions* encode_options = ImageEncodeOptions::Create();
+ encode_options->setType(ImageEncodingMimeTypeName(mime_type));
return encode_options;
}
@@ -340,7 +330,7 @@ void CanvasAsyncBlobCreator::ScheduleAsyncBlobCreation(const double& quality) {
WrapPersistent(this)));
} else {
- BackgroundScheduler::PostOnBackgroundThread(
+ background_scheduler::PostOnBackgroundThread(
FROM_HERE,
CrossThreadBind(&CanvasAsyncBlobCreator::EncodeImageOnEncoderThread,
WrapCrossThreadPersistent(this), quality));
@@ -361,7 +351,7 @@ void CanvasAsyncBlobCreator::ScheduleAsyncBlobCreation(const double& quality) {
void CanvasAsyncBlobCreator::ScheduleInitiateEncoding(double quality) {
schedule_idle_task_start_time_ = WTF::CurrentTimeTicks();
- Platform::Current()->CurrentThread()->Scheduler()->PostIdleTask(
+ ThreadScheduler::Current()->PostIdleTask(
FROM_HERE, WTF::Bind(&CanvasAsyncBlobCreator::InitiateEncoding,
WrapPersistent(this), quality));
}
@@ -371,9 +361,8 @@ void CanvasAsyncBlobCreator::InitiateEncoding(double quality,
if (idle_task_status_ == kIdleTaskSwitchedToImmediateTask) {
return;
}
- RecordElapsedTimeHistogram(
- kInitiateEncodingDelay, mime_type_,
- WTF::CurrentTimeTicks() - schedule_idle_task_start_time_);
+ RecordInitiateEncodingTimeHistogram(
+ mime_type_, WTF::CurrentTimeTicks() - schedule_idle_task_start_time_);
DCHECK(idle_task_status_ == kIdleTaskNotStarted);
idle_task_status_ = kIdleTaskStarted;
@@ -396,7 +385,7 @@ void CanvasAsyncBlobCreator::IdleEncodeRows(TimeTicks deadline) {
for (int y = num_rows_completed_; y < src_data_.height(); ++y) {
if (IsEncodeRowDeadlineNearOrPassed(deadline, src_data_.width())) {
num_rows_completed_ = y;
- Platform::Current()->CurrentThread()->Scheduler()->PostIdleTask(
+ ThreadScheduler::Current()->PostIdleTask(
FROM_HERE, WTF::Bind(&CanvasAsyncBlobCreator::IdleEncodeRows,
WrapPersistent(this)));
return;
@@ -413,7 +402,7 @@ void CanvasAsyncBlobCreator::IdleEncodeRows(TimeTicks deadline) {
idle_task_status_ = kIdleTaskCompleted;
TimeDelta elapsed_time =
WTF::CurrentTimeTicks() - schedule_idle_task_start_time_;
- RecordElapsedTimeHistogram(kCompleteEncodingDelay, mime_type_, elapsed_time);
+ RecordCompleteEncodingTimeHistogram(mime_type_, elapsed_time);
if (IsCreateBlobDeadlineNearOrPassed(deadline)) {
context_->GetTaskRunner(TaskType::kCanvasBlobSerialization)
->PostTask(FROM_HERE,
@@ -451,8 +440,6 @@ void CanvasAsyncBlobCreator::ForceEncodeRowsOnCurrentThread() {
void CanvasAsyncBlobCreator::CreateBlobAndReturnResult() {
RecordIdleTaskStatusHistogram(idle_task_status_);
- RecordElapsedTimeHistogram(kToBlobDuration, mime_type_,
- WTF::CurrentTimeTicks() - start_time_);
Blob* result_blob = Blob::Create(encoded_image_.data(), encoded_image_.size(),
ImageEncodingMimeTypeName(mime_type_));
@@ -466,6 +453,10 @@ void CanvasAsyncBlobCreator::CreateBlobAndReturnResult() {
} else {
script_promise_resolver_->Resolve(result_blob);
}
+
+ RecordScaledDurationHistogram(mime_type_,
+ WTF::CurrentTimeTicks() - start_time_,
+ image_->width(), image_->height());
// Avoid unwanted retention, see dispose().
Dispose();
}
@@ -599,6 +590,7 @@ void CanvasAsyncBlobCreator::PostDelayedTaskToCurrentThread(
void CanvasAsyncBlobCreator::Trace(blink::Visitor* visitor) {
visitor->Trace(context_);
+ visitor->Trace(encode_options_);
visitor->Trace(callback_);
visitor->Trace(script_promise_resolver_);
}
@@ -619,7 +611,7 @@ bool CanvasAsyncBlobCreator::EncodeImageForConvertToBlobTest() {
std::unique_ptr<ImageDataBuffer> buffer = ImageDataBuffer::Create(src_data_);
if (!buffer)
return false;
- return buffer->EncodeImage(mime_type_, encode_options_.quality(),
+ return buffer->EncodeImage(mime_type_, encode_options_->quality(),
&encoded_image_);
}
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h b/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h
index 0373a083db3..4e8d51ccb46 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h
@@ -36,18 +36,16 @@ constexpr const char* kRGBA16ImagePixelFormatName = "uint16";
class CORE_EXPORT CanvasAsyncBlobCreator
: public GarbageCollectedFinalized<CanvasAsyncBlobCreator> {
public:
-
// This enum is used to back an UMA histogram, and should therefore be treated
- // as append-only.
+ // as append-only. Idle tasks are not implemented for some image types.
enum IdleTaskStatus {
- kIdleTaskNotStarted,
- kIdleTaskStarted,
- kIdleTaskCompleted,
- kIdleTaskFailed,
- kIdleTaskSwitchedToImmediateTask,
- kIdleTaskNotSupported, // Idle tasks are not implemented for some image
- // types
- kIdleTaskCount, // Should not be seen in production
+ kIdleTaskNotStarted = 0,
+ kIdleTaskStarted = 1,
+ kIdleTaskCompleted = 2,
+ kIdleTaskFailed = 3,
+ kIdleTaskSwitchedToImmediateTask = 4,
+ kIdleTaskNotSupported = 5,
+ kMaxValue = kIdleTaskNotSupported,
};
enum ToBlobFunctionType {
kHTMLCanvasToBlobCallback,
@@ -63,13 +61,21 @@ class CORE_EXPORT CanvasAsyncBlobCreator
TimeTicks start_time,
ExecutionContext*);
static CanvasAsyncBlobCreator* Create(scoped_refptr<StaticBitmapImage>,
- const ImageEncodeOptions& options,
+ const ImageEncodeOptions* options,
ToBlobFunctionType function_type,
TimeTicks start_time,
ExecutionContext*,
ScriptPromiseResolver*);
void ScheduleAsyncBlobCreation(const double& quality);
+
+ CanvasAsyncBlobCreator(scoped_refptr<StaticBitmapImage>,
+ const ImageEncodeOptions*,
+ ToBlobFunctionType,
+ V8BlobCallback*,
+ TimeTicks start_time,
+ ExecutionContext*,
+ ScriptPromiseResolver*);
virtual ~CanvasAsyncBlobCreator();
// Methods are virtual for mocking in unit tests
@@ -87,14 +93,7 @@ class CORE_EXPORT CanvasAsyncBlobCreator
}
protected:
- CanvasAsyncBlobCreator(scoped_refptr<StaticBitmapImage>,
- const ImageEncodeOptions&,
- ToBlobFunctionType,
- V8BlobCallback*,
- TimeTicks start_time,
- ExecutionContext*,
- ScriptPromiseResolver*);
- static ImageEncodeOptions GetImageEncodeOptionsForMimeType(
+ static ImageEncodeOptions* GetImageEncodeOptionsForMimeType(
ImageEncodingMimeType);
// Methods are virtual for unit testing
virtual void ScheduleInitiateEncoding(double quality);
@@ -126,7 +125,7 @@ class CORE_EXPORT CanvasAsyncBlobCreator
SkPixmap src_data_;
ImageEncodingMimeType mime_type_;
- const ImageEncodeOptions encode_options_;
+ Member<const ImageEncodeOptions> encode_options_;
ToBlobFunctionType function_type_;
sk_sp<SkData> png_data_helper_;
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc b/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc
index e539e235ad2..dddd9665758 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc
@@ -63,8 +63,7 @@ void MockCanvasAsyncBlobCreator::PostDelayedTaskToCurrentThread(
base::OnceClosure task,
double delay_ms) {
DCHECK(IsMainThread());
- Platform::Current()->MainThread()->GetTaskRunner()->PostTask(location,
- std::move(task));
+ Thread::Current()->GetTaskRunner()->PostTask(location, std::move(task));
}
//==============================================================================
@@ -99,7 +98,7 @@ class MockCanvasAsyncBlobCreatorWithoutComplete
protected:
void ScheduleInitiateEncoding(double quality) override {
- Platform::Current()->MainThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(&MockCanvasAsyncBlobCreatorWithoutComplete::InitiateEncoding,
WrapPersistent(this), quality, TimeTicks::Max()));
@@ -142,22 +141,25 @@ scoped_refptr<StaticBitmapImage> CreateTransparentImage(int width, int height) {
void CanvasAsyncBlobCreatorTest::
PrepareMockCanvasAsyncBlobCreatorWithoutStart() {
- async_blob_creator_ = new MockCanvasAsyncBlobCreatorWithoutStart(
- CreateTransparentImage(20, 20), &GetDocument());
+ async_blob_creator_ =
+ MakeGarbageCollected<MockCanvasAsyncBlobCreatorWithoutStart>(
+ CreateTransparentImage(20, 20), &GetDocument());
}
void CanvasAsyncBlobCreatorTest::
PrepareMockCanvasAsyncBlobCreatorWithoutComplete() {
- async_blob_creator_ = new MockCanvasAsyncBlobCreatorWithoutComplete(
- CreateTransparentImage(20, 20), &GetDocument());
+ async_blob_creator_ =
+ MakeGarbageCollected<MockCanvasAsyncBlobCreatorWithoutComplete>(
+ CreateTransparentImage(20, 20), &GetDocument());
}
void CanvasAsyncBlobCreatorTest::PrepareMockCanvasAsyncBlobCreatorFail() {
// We reuse the class MockCanvasAsyncBlobCreatorWithoutComplete because
// this test case is expected to fail at initialization step before
// completion.
- async_blob_creator_ = new MockCanvasAsyncBlobCreatorWithoutComplete(
- CreateTransparentImage(20, 20), &GetDocument(), true);
+ async_blob_creator_ =
+ MakeGarbageCollected<MockCanvasAsyncBlobCreatorWithoutComplete>(
+ CreateTransparentImage(20, 20), &GetDocument(), true);
}
void CanvasAsyncBlobCreatorTest::TearDown() {
@@ -273,11 +275,11 @@ TEST_F(CanvasAsyncBlobCreatorTest, ColorManagedConvertToBlob) {
StaticBitmapImage::Create(source_image);
// Prepare encoding options
- ImageEncodeOptions options;
- options.setQuality(1);
- options.setType(blob_mime_type);
- options.setColorSpace(blob_color_space);
- options.setPixelFormat(blob_pixel_format);
+ ImageEncodeOptions* options = ImageEncodeOptions::Create();
+ options->setQuality(1);
+ options->setType(blob_mime_type);
+ options->setColorSpace(blob_color_space);
+ options->setPixelFormat(blob_pixel_format);
// Encode the image using CanvasAsyncBlobCreator
CanvasAsyncBlobCreator* async_blob_creator =
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.cc b/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.cc
index d58830a2de6..7c0c4641fca 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.cc
@@ -119,7 +119,7 @@ MutableCSSPropertyValueSet* CanvasFontCache::ParseFont(
return parsed_style;
}
-void CanvasFontCache::DidProcessTask() {
+void CanvasFontCache::DidProcessTask(const base::PendingTask& pending_task) {
DCHECK(pruning_scheduled_);
DCHECK(main_cache_purge_preventer_);
while (fetched_fonts_.size() > MaxFonts()) {
@@ -128,7 +128,7 @@ void CanvasFontCache::DidProcessTask() {
font_lru_list_.RemoveFirst();
}
main_cache_purge_preventer_.reset();
- Platform::Current()->CurrentThread()->RemoveTaskObserver(this);
+ Thread::Current()->RemoveTaskObserver(this);
pruning_scheduled_ = false;
}
@@ -137,7 +137,7 @@ void CanvasFontCache::SchedulePruningIfNeeded() {
return;
DCHECK(!main_cache_purge_preventer_);
main_cache_purge_preventer_ = std::make_unique<FontCachePurgePreventer>();
- Platform::Current()->CurrentThread()->AddTaskObserver(this);
+ Thread::Current()->AddTaskObserver(this);
pruning_scheduled_ = true;
}
@@ -159,7 +159,7 @@ void CanvasFontCache::Trace(blink::Visitor* visitor) {
void CanvasFontCache::Dispose() {
main_cache_purge_preventer_.reset();
if (pruning_scheduled_) {
- Platform::Current()->CurrentThread()->RemoveTaskObserver(this);
+ Thread::Current()->RemoveTaskObserver(this);
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.h b/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.h
index 70f148b460e..76cd7105c29 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.h
@@ -28,9 +28,11 @@ class CORE_EXPORT CanvasFontCache final
public:
static CanvasFontCache* Create(Document& document) {
- return new CanvasFontCache(document);
+ return MakeGarbageCollected<CanvasFontCache>(document);
}
+ explicit CanvasFontCache(Document&);
+
MutableCSSPropertyValueSet* ParseFont(const String&);
void PruneAll();
unsigned size();
@@ -44,8 +46,8 @@ class CORE_EXPORT CanvasFontCache final
bool GetFontUsingDefaultStyle(const String&, Font&);
// TaskObserver implementation
- void DidProcessTask() override;
- void WillProcessTask() override {}
+ void DidProcessTask(const base::PendingTask&) override;
+ void WillProcessTask(const base::PendingTask&) override {}
// For testing
bool IsInCache(const String&);
@@ -53,7 +55,6 @@ class CORE_EXPORT CanvasFontCache final
~CanvasFontCache() override;
private:
- explicit CanvasFontCache(Document&);
void Dispose();
void SchedulePruningIfNeeded();
typedef HeapHashMap<String, Member<MutableCSSPropertyValueSet>>
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache_test.cc b/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache_test.cc
index 5a3e5dfc608..be64ecda505 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache_test.cc
@@ -45,7 +45,7 @@ void CanvasFontCacheTest::SetUp() {
PageTestBase::SetUp();
GetDocument().documentElement()->SetInnerHTMLFromString(
"<body><canvas id='c'></canvas></body>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
canvas_element_ = ToHTMLCanvasElement(GetDocument().getElementById("c"));
String canvas_type("2d");
CanvasContextCreationAttributesCore attributes;
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_image_source.h b/chromium/third_party/blink/renderer/core/html/canvas/canvas_image_source.h
index 47aa0867820..c1c40cc5e39 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_image_source.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_image_source.h
@@ -62,6 +62,7 @@ class CORE_EXPORT CanvasImageSource {
const SecurityOrigin* destination_security_origin) const = 0;
virtual bool IsCSSImageValue() const { return false; }
+ virtual bool IsImageElement() const { return false; }
virtual bool IsVideoElement() const { return false; }
virtual bool IsCanvasElement() const { return false; }
virtual bool IsSVGSource() const { return false; }
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.cc b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.cc
index bff8def3f1b..d89924b4cd0 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.cc
@@ -42,12 +42,15 @@ CanvasRenderingContext::CanvasRenderingContext(
: host_(host),
color_params_(kSRGBCanvasColorSpace, kRGBA8CanvasPixelFormat, kNonOpaque),
creation_attributes_(attrs) {
- // Supported color spaces: srgb-uint8, srgb-f16, p3-f16, rec2020-f16. For wide
- // gamut color spaces, user must explicitly request for float16 storage.
- // Otherwise, we fall back to srgb-uint8. Invalid requests fall back to
- // srgb-uint8 too.
+ // Supported color spaces and pixel formats: sRGB in uint8, e-sRGB in f16,
+ // linear sRGB and p3 and rec2020 with linear gamma transfer function in f16.
+ // For wide gamut color spaces, user must explicitly request half float
+ // storage. Otherwise, we fall back to sRGB in uint8. Invalid requests fall
+ // back to sRGB in uint8 too.
if (creation_attributes_.pixel_format == kF16CanvasPixelFormatName) {
color_params_.SetCanvasPixelFormat(kF16CanvasPixelFormat);
+ if (creation_attributes_.color_space == kLinearRGBCanvasColorSpaceName)
+ color_params_.SetCanvasColorSpace(kLinearRGBCanvasColorSpace);
if (creation_attributes_.color_space == kRec2020CanvasColorSpaceName)
color_params_.SetCanvasColorSpace(kRec2020CanvasColorSpace);
else if (creation_attributes_.color_space == kP3CanvasColorSpaceName)
@@ -57,7 +60,7 @@ CanvasRenderingContext::CanvasRenderingContext(
if (!creation_attributes_.alpha)
color_params_.SetOpacityMode(kOpaque);
- if (!OriginTrials::LowLatencyCanvasEnabled(host->GetTopExecutionContext()))
+ if (!origin_trials::LowLatencyCanvasEnabled(host->GetTopExecutionContext()))
creation_attributes_.low_latency = false;
// Make creation_attributes_ reflect the effective color_space and
@@ -70,6 +73,8 @@ WTF::String CanvasRenderingContext::ColorSpaceAsString() const {
switch (color_params_.ColorSpace()) {
case kSRGBCanvasColorSpace:
return kSRGBCanvasColorSpaceName;
+ case kLinearRGBCanvasColorSpace:
+ return kLinearRGBCanvasColorSpaceName;
case kRec2020CanvasColorSpace:
return kRec2020CanvasColorSpaceName;
case kP3CanvasColorSpace:
@@ -83,10 +88,6 @@ WTF::String CanvasRenderingContext::PixelFormatAsString() const {
switch (color_params_.PixelFormat()) {
case kRGBA8CanvasPixelFormat:
return kRGBA8CanvasPixelFormatName;
- case kRGB10A2CanvasPixelFormat:
- return kRGB10A2CanvasPixelFormatName;
- case kRGBA12CanvasPixelFormat:
- return kRGBA12CanvasPixelFormatName;
case kF16CanvasPixelFormat:
return kF16CanvasPixelFormatName;
};
@@ -95,14 +96,13 @@ WTF::String CanvasRenderingContext::PixelFormatAsString() const {
}
void CanvasRenderingContext::Dispose() {
- if (finalize_frame_scheduled_)
- Platform::Current()->CurrentThread()->RemoveTaskObserver(this);
+ StopListeningForDidProcessTask();
// HTMLCanvasElement and CanvasRenderingContext have a circular reference.
// When the pair is no longer reachable, their destruction order is non-
// deterministic, so the first of the two to be destroyed needs to notify
// the other in order to break the circular reference. This is to avoid
- // an error when CanvasRenderingContext::didProcessTask() is invoked
+ // an error when CanvasRenderingContext::DidProcessTask() is invoked
// after the HTMLCanvasElement is destroyed.
if (Host()) {
Host()->DetachContext();
@@ -112,24 +112,22 @@ void CanvasRenderingContext::Dispose() {
void CanvasRenderingContext::DidDraw(const SkIRect& dirty_rect) {
Host()->DidDraw(SkRect::Make(dirty_rect));
- NeedsFinalizeFrame();
+ StartListeningForDidProcessTask();
}
void CanvasRenderingContext::DidDraw() {
Host()->DidDraw();
- NeedsFinalizeFrame();
+ StartListeningForDidProcessTask();
}
void CanvasRenderingContext::NeedsFinalizeFrame() {
- if (!finalize_frame_scheduled_) {
- finalize_frame_scheduled_ = true;
- Platform::Current()->CurrentThread()->AddTaskObserver(this);
- }
+ StartListeningForDidProcessTask();
}
-void CanvasRenderingContext::DidProcessTask() {
- Platform::Current()->CurrentThread()->RemoveTaskObserver(this);
- finalize_frame_scheduled_ = false;
+void CanvasRenderingContext::DidProcessTask(
+ const base::PendingTask& /* pending_task */) {
+ StopListeningForDidProcessTask();
+
// The end of a script task that drew content to the canvas is the point
// at which the current frame may be considered complete.
if (Host())
@@ -154,7 +152,7 @@ CanvasRenderingContext::ContextType CanvasRenderingContext::ContextTypeFromId(
return kContextImageBitmap;
if (id == "xrpresent")
return kContextXRPresent;
- return kContextTypeCount;
+ return kContextTypeUnknown;
}
CanvasRenderingContext::ContextType
@@ -168,27 +166,19 @@ CanvasRenderingContext::ResolveContextTypeAliases(
bool CanvasRenderingContext::WouldTaintOrigin(
CanvasImageSource* image_source,
const SecurityOrigin* destination_security_origin) {
+ // Don't taint the canvas on data URLs. This special case is needed here
+ // because CanvasImageSource::WouldTaintOrigin() can return false for data
+ // URLs due to restrictions on SVG foreignObject nodes as described in
+ // https://crbug.com/294129.
+ // TODO(crbug.com/294129): Remove the restriction on foreignObject nodes, then
+ // this logic isn't needed, CanvasImageSource::SourceURL() isn't needed, and
+ // this function can just be image_source->WouldTaintOrigin().
const KURL& source_url = image_source->SourceURL();
const bool has_url = (source_url.IsValid() && !source_url.IsAboutBlankURL());
+ if (has_url && source_url.ProtocolIsData())
+ return false;
- if (has_url) {
- if (source_url.ProtocolIsData() ||
- clean_urls_.Contains(source_url.GetString())) {
- return false;
- }
- if (dirty_urls_.Contains(source_url.GetString()))
- return true;
- }
-
- const bool taint_origin =
- image_source->WouldTaintOrigin(destination_security_origin);
- if (has_url) {
- if (taint_origin)
- dirty_urls_.insert(source_url.GetString());
- else
- clean_urls_.insert(source_url.GetString());
- }
- return taint_origin;
+ return image_source->WouldTaintOrigin(destination_security_origin);
}
void CanvasRenderingContext::Trace(blink::Visitor* visitor) {
@@ -197,4 +187,20 @@ void CanvasRenderingContext::Trace(blink::Visitor* visitor) {
ScriptWrappable::Trace(visitor);
}
+void CanvasRenderingContext::StartListeningForDidProcessTask() {
+ if (listening_for_did_process_task_)
+ return;
+
+ listening_for_did_process_task_ = true;
+ Thread::Current()->AddTaskObserver(this);
+}
+
+void CanvasRenderingContext::StopListeningForDidProcessTask() {
+ if (!listening_for_did_process_task_)
+ return;
+
+ Thread::Current()->RemoveTaskObserver(this);
+ listening_for_did_process_task_ = false;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h
index 2738c10e0fa..6da915a4488 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h
@@ -35,8 +35,6 @@
#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
#include "third_party/blink/renderer/platform/graphics/color_behavior.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkImageInfo.h"
@@ -47,12 +45,11 @@ class HTMLCanvasElement;
class ImageBitmap;
constexpr const char* kSRGBCanvasColorSpaceName = "srgb";
+constexpr const char* kLinearRGBCanvasColorSpaceName = "linear-rgb";
constexpr const char* kRec2020CanvasColorSpaceName = "rec2020";
constexpr const char* kP3CanvasColorSpaceName = "p3";
constexpr const char* kRGBA8CanvasPixelFormatName = "uint8";
-constexpr const char* kRGB10A2CanvasPixelFormatName = "10-10-10-2";
-constexpr const char* kRGBA12CanvasPixelFormatName = "12-12-12-12";
constexpr const char* kF16CanvasPixelFormatName = "float16";
class CORE_EXPORT CanvasRenderingContext : public ScriptWrappable,
@@ -74,7 +71,8 @@ class CORE_EXPORT CanvasRenderingContext : public ScriptWrappable,
kContextImageBitmap = 5,
kContextXRPresent = 6,
kContextWebgl2Compute = 7,
- kContextTypeCount,
+ kContextTypeUnknown = 8,
+ kMaxValue = kContextTypeUnknown,
};
static ContextType ContextTypeFromId(const String& id);
@@ -138,8 +136,8 @@ class CORE_EXPORT CanvasRenderingContext : public ScriptWrappable,
void NeedsFinalizeFrame();
// Thread::TaskObserver implementation
- void DidProcessTask() override;
- void WillProcessTask() final {}
+ void DidProcessTask(const base::PendingTask&) override;
+ void WillProcessTask(const base::PendingTask&) final {}
// Canvas2D-specific interface
virtual bool Is2d() const { return false; }
@@ -203,11 +201,12 @@ class CORE_EXPORT CanvasRenderingContext : public ScriptWrappable,
void Dispose();
Member<CanvasRenderingContextHost> host_;
- HashSet<String> clean_urls_;
- HashSet<String> dirty_urls_;
CanvasColorParams color_params_;
CanvasContextCreationAttributesCore creation_attributes_;
- bool finalize_frame_scheduled_ = false;
+
+ void StartListeningForDidProcessTask();
+ void StopListeningForDidProcessTask();
+ bool listening_for_did_process_task_ = false;
DISALLOW_COPY_AND_ASSIGN(CanvasRenderingContext);
};
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
index a85eb829134..c711d30571a 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
@@ -11,12 +11,27 @@
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
+#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace blink {
CanvasRenderingContextHost::CanvasRenderingContextHost() = default;
+void CanvasRenderingContextHost::RecordCanvasSizeToUMA(unsigned width,
+ unsigned height,
+ HostType hostType) {
+ if (hostType == kCanvasHost) {
+ UMA_HISTOGRAM_CUSTOM_COUNTS("Blink.Canvas.SqrtNumberOfPixels",
+ std::sqrt(width * height), 1, 5000, 100);
+ } else if (hostType == kOffscreenCanvasHost) {
+ UMA_HISTOGRAM_CUSTOM_COUNTS("Blink.OffscreenCanvas.SqrtNumberOfPixels",
+ std::sqrt(width * height), 1, 5000, 100);
+ } else {
+ NOTREACHED();
+ }
+}
+
scoped_refptr<StaticBitmapImage>
CanvasRenderingContextHost::CreateTransparentImage(const IntSize& size) const {
if (!IsValidImageSize(size))
@@ -73,13 +88,19 @@ CanvasRenderingContextHost::GetOrCreateCanvasResourceProviderImpl(
GetOrCreateResourceDispatcher()
? GetOrCreateResourceDispatcher()->GetWeakPtr()
: nullptr;
+
if (Is3d()) {
- const CanvasResourceProvider::ResourceUsage usage =
- SharedGpuContext::IsGpuCompositingEnabled()
- ? CanvasResourceProvider::kAcceleratedCompositedResourceUsage
- : CanvasResourceProvider::kSoftwareCompositedResourceUsage;
+ CanvasResourceProvider::ResourceUsage usage;
+ if (SharedGpuContext::IsGpuCompositingEnabled()) {
+ if (LowLatencyEnabled())
+ usage = CanvasResourceProvider::kAcceleratedDirectResourceUsage;
+ else
+ usage = CanvasResourceProvider::kAcceleratedCompositedResourceUsage;
+ } else {
+ usage = CanvasResourceProvider::kSoftwareCompositedResourceUsage;
+ }
- CanvasResourceProvider::PresentationMode presentation_mode =
+ const CanvasResourceProvider::PresentationMode presentation_mode =
RuntimeEnabledFeatures::WebGLImageChromiumEnabled()
? CanvasResourceProvider::kAllowImageChromiumPresentationMode
: CanvasResourceProvider::kDefaultPresentationMode;
@@ -96,10 +117,15 @@ CanvasRenderingContextHost::GetOrCreateCanvasResourceProviderImpl(
const bool want_acceleration =
hint == kPreferAcceleration && ShouldAccelerate2dContext();
- const CanvasResourceProvider::ResourceUsage usage =
- want_acceleration
- ? CanvasResourceProvider::kAcceleratedCompositedResourceUsage
- : CanvasResourceProvider::kSoftwareCompositedResourceUsage;
+ CanvasResourceProvider::ResourceUsage usage;
+ if (want_acceleration) {
+ if (LowLatencyEnabled())
+ usage = CanvasResourceProvider::kAcceleratedDirectResourceUsage;
+ else
+ usage = CanvasResourceProvider::kAcceleratedCompositedResourceUsage;
+ } else {
+ usage = CanvasResourceProvider::kSoftwareCompositedResourceUsage;
+ }
const CanvasResourceProvider::PresentationMode presentation_mode =
(RuntimeEnabledFeatures::Canvas2dImageChromiumEnabled() ||
@@ -138,7 +164,7 @@ CanvasColorParams CanvasRenderingContextHost::ColorParams() const {
ScriptPromise CanvasRenderingContextHost::convertToBlob(
ScriptState* script_state,
- const ImageEncodeOptions& options,
+ const ImageEncodeOptions* options,
ExceptionState& exception_state) const {
WTF::String object_name = "Canvas";
if (this->IsOffscreenCanvas())
@@ -186,7 +212,7 @@ ScriptPromise CanvasRenderingContextHost::convertToBlob(
CanvasAsyncBlobCreator* async_creator = CanvasAsyncBlobCreator::Create(
image_bitmap, options, function_type, start_time,
ExecutionContext::From(script_state), resolver);
- async_creator->ScheduleAsyncBlobCreation(options.quality());
+ async_creator->ScheduleAsyncBlobCreation(options->quality());
return resolver->Promise();
}
exception_state.ThrowDOMException(DOMExceptionCode::kNotReadableError,
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h
index cc614483968..d0b86e7ab6a 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h
@@ -34,6 +34,12 @@ class CORE_EXPORT CanvasRenderingContextHost : public CanvasResourceHost,
public:
CanvasRenderingContextHost();
+ enum HostType {
+ kCanvasHost,
+ kOffscreenCanvasHost,
+ };
+
+ void static RecordCanvasSizeToUMA(unsigned width, unsigned height, HostType);
virtual void DetachContext() = 0;
virtual void DidDraw(const FloatRect& rect) = 0;
@@ -89,7 +95,7 @@ class CORE_EXPORT CanvasRenderingContextHost : public CanvasResourceHost,
CanvasColorParams ColorParams() const;
ScriptPromise convertToBlob(ScriptState*,
- const ImageEncodeOptions&,
+ const ImageEncodeOptions*,
ExceptionState&) const;
protected:
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc b/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc
index a707c28a074..e2c1a35081b 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc
@@ -34,6 +34,7 @@
#include <utility>
#include "base/location.h"
+#include "base/metrics/histogram_macros.h"
#include "base/numerics/checked_math.h"
#include "build/build_config.h"
#include "third_party/blink/public/platform/task_type.h"
@@ -76,20 +77,18 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h"
#include "third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h"
-#include "third_party/blink/renderer/platform/graphics/canvas_metrics.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/image_data_buffer.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
-#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/image-encoders/image_encoder_utils.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "v8/include/v8.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -123,7 +122,7 @@ constexpr int kUndefinedQualityValue = -1.0;
} // namespace
inline HTMLCanvasElement::HTMLCanvasElement(Document& document)
- : HTMLElement(canvasTag, document),
+ : HTMLElement(kCanvasTag, document),
ContextLifecycleObserver(&document),
PageVisibilityObserver(document.GetPage()),
size_(kDefaultCanvasWidth, kDefaultCanvasHeight),
@@ -135,8 +134,9 @@ inline HTMLCanvasElement::HTMLCanvasElement(Document& document)
externally_allocated_memory_(0),
gpu_readback_invoked_in_current_frame_(false),
gpu_readback_successive_frames_(0) {
- CanvasMetrics::CountCanvasContextUsage(CanvasMetrics::kCanvasCreated);
UseCounter::Count(document, WebFeature::kHTMLCanvasElement);
+
+ GetDocument().IncrementNumberOfCanvases();
}
DEFINE_NODE_FACTORY(HTMLCanvasElement)
@@ -145,6 +145,9 @@ intptr_t HTMLCanvasElement::global_gpu_memory_usage_ = 0;
unsigned HTMLCanvasElement::global_accelerated_context_count_ = 0;
HTMLCanvasElement::~HTMLCanvasElement() {
+ CanvasRenderingContextHost::RecordCanvasSizeToUMA(
+ size_.Width(), size_.Height(),
+ CanvasRenderingContextHost::HostType::kCanvasHost);
if (surface_layer_bridge_ && surface_layer_bridge_->GetCcLayer())
GraphicsLayer::UnregisterContentsLayer(surface_layer_bridge_->GetCcLayer());
v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
@@ -174,7 +177,7 @@ void HTMLCanvasElement::Dispose() {
void HTMLCanvasElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == widthAttr || params.name == heightAttr)
+ if (params.name == kWidthAttr || params.name == kHeightAttr)
Reset();
HTMLElement::ParseAttribute(params);
}
@@ -201,7 +204,7 @@ void HTMLCanvasElement::setHeight(unsigned value,
"Cannot resize canvas after call to transferControlToOffscreen().");
return;
}
- SetUnsignedIntegralAttribute(heightAttr, value, kDefaultCanvasHeight);
+ SetUnsignedIntegralAttribute(kHeightAttr, value, kDefaultCanvasHeight);
}
void HTMLCanvasElement::setWidth(unsigned value,
@@ -212,15 +215,15 @@ void HTMLCanvasElement::setWidth(unsigned value,
"Cannot resize canvas after call to transferControlToOffscreen().");
return;
}
- SetUnsignedIntegralAttribute(widthAttr, value, kDefaultCanvasWidth);
+ SetUnsignedIntegralAttribute(kWidthAttr, value, kDefaultCanvasWidth);
}
void HTMLCanvasElement::SetSize(const IntSize& new_size) {
if (new_size == Size())
return;
ignore_reset_ = true;
- SetIntegralAttribute(widthAttr, new_size.Width());
- SetIntegralAttribute(heightAttr, new_size.Height());
+ SetIntegralAttribute(kWidthAttr, new_size.Width());
+ SetIntegralAttribute(kHeightAttr, new_size.Height());
ignore_reset_ = false;
Reset();
}
@@ -229,13 +232,13 @@ HTMLCanvasElement::ContextFactoryVector&
HTMLCanvasElement::RenderingContextFactories() {
DCHECK(IsMainThread());
DEFINE_STATIC_LOCAL(ContextFactoryVector, context_factories,
- (CanvasRenderingContext::kContextTypeCount));
+ (CanvasRenderingContext::kMaxValue));
return context_factories;
}
CanvasRenderingContextFactory* HTMLCanvasElement::GetRenderingContextFactory(
int type) {
- DCHECK(type < CanvasRenderingContext::kContextTypeCount);
+ DCHECK_LE(type, CanvasRenderingContext::kMaxValue);
return RenderingContextFactories()[type].get();
}
@@ -243,7 +246,7 @@ void HTMLCanvasElement::RegisterRenderingContextFactory(
std::unique_ptr<CanvasRenderingContextFactory> rendering_context_factory) {
CanvasRenderingContext::ContextType type =
rendering_context_factory->GetContextType();
- DCHECK(type < CanvasRenderingContext::kContextTypeCount);
+ DCHECK_LE(type, CanvasRenderingContext::kMaxValue);
DCHECK(!RenderingContextFactories()[type]);
RenderingContextFactories()[type] = std::move(rendering_context_factory);
}
@@ -255,18 +258,15 @@ CanvasRenderingContext* HTMLCanvasElement::GetCanvasRenderingContext(
CanvasRenderingContext::ContextTypeFromId(type);
// Unknown type.
- if (context_type == CanvasRenderingContext::kContextTypeCount ||
+ if (context_type == CanvasRenderingContext::kContextTypeUnknown ||
(context_type == CanvasRenderingContext::kContextXRPresent &&
- !OriginTrials::WebXREnabled(&GetDocument()))) {
+ !origin_trials::WebXREnabled(&GetDocument()))) {
return nullptr;
}
// Log the aliased context type used.
if (!context_) {
- DEFINE_STATIC_LOCAL(
- EnumerationHistogram, context_type_histogram,
- ("Canvas.ContextType", CanvasRenderingContext::kContextTypeCount));
- context_type_histogram.Count(context_type);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.ContextType", context_type);
}
context_type =
@@ -293,6 +293,8 @@ CanvasRenderingContext* HTMLCanvasElement::GetCanvasRenderingContext(
if (!context_)
return nullptr;
+ UMA_HISTOGRAM_BOOLEAN("Blink.Canvas.IsComposited", context_->IsComposited());
+
context_creation_was_blocked_ = false;
probe::didCreateCanvasContext(&GetDocument());
@@ -308,7 +310,7 @@ CanvasRenderingContext* HTMLCanvasElement::GetCanvasRenderingContext(
}
if (attributes.low_latency &&
- OriginTrials::LowLatencyCanvasEnabled(&GetDocument())) {
+ origin_trials::LowLatencyCanvasEnabled(&GetDocument())) {
CreateLayer();
SetNeedsUnbufferedInputEvents(true);
frame_dispatcher_ = std::make_unique<CanvasResourceDispatcher>(
@@ -394,7 +396,7 @@ void HTMLCanvasElement::FinalizeFrame() {
if (canvas2d_bridge_) {
// Compute to determine whether disable accleration is needed
if (IsAccelerated() &&
- CanvasHeuristicParameters::kGPUReadbackForcesNoAcceleration &&
+ canvas_heuristic_parameters::kGPUReadbackForcesNoAcceleration &&
!RuntimeEnabledFeatures::Canvas2dFixedRenderingModeEnabled()) {
if (gpu_readback_invoked_in_current_frame_) {
gpu_readback_successive_frames_++;
@@ -404,7 +406,7 @@ void HTMLCanvasElement::FinalizeFrame() {
}
if (gpu_readback_successive_frames_ >=
- CanvasHeuristicParameters::kGPUReadbackMinSuccessiveFrames) {
+ canvas_heuristic_parameters::kGPUReadbackMinSuccessiveFrames) {
DisableAcceleration();
}
}
@@ -549,14 +551,14 @@ void HTMLCanvasElement::Reset() {
bool had_resource_provider = HasResourceProvider();
unsigned w = 0;
- AtomicString value = getAttribute(widthAttr);
+ AtomicString value = getAttribute(kWidthAttr);
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, w) ||
w > 0x7fffffffu) {
w = kDefaultCanvasWidth;
}
unsigned h = 0;
- value = getAttribute(heightAttr);
+ value = getAttribute(kHeightAttr);
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, h) ||
h > 0x7fffffffu) {
h = kDefaultCanvasHeight;
@@ -811,6 +813,7 @@ String HTMLCanvasElement::ToDataURLInternal(
const String& mime_type,
const double& quality,
SourceDrawingBuffer source_buffer) const {
+ base::TimeTicks start_time = base::TimeTicks::Now();
if (!IsPaintable())
return String("data:,");
@@ -818,35 +821,43 @@ String HTMLCanvasElement::ToDataURLInternal(
ImageEncoderUtils::ToEncodingMimeType(
mime_type, ImageEncoderUtils::kEncodeReasonToDataURL);
- base::Optional<ScopedUsHistogramTimer> timer;
- if (encoding_mime_type == kMimeTypePng) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_png,
- ("Blink.Canvas.ToDataURL.PNG", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_png);
- } else if (encoding_mime_type == kMimeTypeJpeg) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_jpeg,
- ("Blink.Canvas.ToDataURL.JPEG", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_jpeg);
- } else if (encoding_mime_type == kMimeTypeWebp) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_webp,
- ("Blink.Canvas.ToDataURL.WEBP", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_webp);
- } else {
- // Currently we only support three encoding types.
- NOTREACHED();
- }
-
scoped_refptr<StaticBitmapImage> image_bitmap =
Snapshot(source_buffer, kPreferNoAcceleration);
if (image_bitmap) {
std::unique_ptr<ImageDataBuffer> data_buffer =
ImageDataBuffer::Create(image_bitmap);
- if (data_buffer)
- return data_buffer->ToDataURL(encoding_mime_type, quality);
+ if (!data_buffer)
+ return String("data:,");
+
+ String data_url = data_buffer->ToDataURL(encoding_mime_type, quality);
+ base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time;
+ float sqrt_pixels =
+ std::sqrt(image_bitmap->width()) * std::sqrt(image_bitmap->height());
+ float scaled_time_float = elapsed_time.InMicrosecondsF() /
+ (sqrt_pixels == 0 ? 1.0f : sqrt_pixels);
+
+ // If scaled_time_float overflows as integer, CheckedNumeric will store it
+ // as invalid, then ValueOrDefault will return the maximum int.
+ base::CheckedNumeric<int> checked_scaled_time = scaled_time_float;
+ int scaled_time_int =
+ checked_scaled_time.ValueOrDefault(std::numeric_limits<int>::max());
+
+ if (encoding_mime_type == kMimeTypePng) {
+ UMA_HISTOGRAM_COUNTS_100000("Blink.Canvas.ToDataURLScaledDuration.PNG",
+ scaled_time_int);
+ } else if (encoding_mime_type == kMimeTypeJpeg) {
+ UMA_HISTOGRAM_COUNTS_100000("Blink.Canvas.ToDataURLScaledDuration.JPEG",
+ scaled_time_int);
+ } else if (encoding_mime_type == kMimeTypeWebp) {
+ UMA_HISTOGRAM_COUNTS_100000("Blink.Canvas.ToDataURLScaledDuration.WEBP",
+ scaled_time_int);
+ } else {
+ // Currently we only support three encoding types.
+ NOTREACHED();
+ }
+ return data_url;
}
+
return String("data:,");
}
@@ -1001,11 +1012,8 @@ bool HTMLCanvasElement::ShouldAccelerate(AccelerationCriteria criteria) const {
// since it costs us GPU memory.
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper =
SharedGpuContext::ContextProviderWrapper();
- if (!context_provider_wrapper) {
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kAccelerated2DCanvasGPUContextLost);
+ if (!context_provider_wrapper)
return false;
- }
return context_provider_wrapper->Utils()->Accelerated2DCanvasFeatureEnabled();
}
@@ -1020,17 +1028,12 @@ std::unique_ptr<Canvas2DLayerBridge>
HTMLCanvasElement::CreateAccelerated2dBuffer() {
auto surface = std::make_unique<Canvas2DLayerBridge>(
Size(), Canvas2DLayerBridge::kEnableAcceleration, ColorParams());
- if (!surface->IsValid()) {
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kGPUAccelerated2DCanvasImageBufferCreationFailed);
+ if (!surface->IsValid())
return nullptr;
- }
if (MemoryCoordinator::IsLowEndDevice())
surface->DisableDeferral(kDisableDeferralReasonLowEndDevice);
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kGPUAccelerated2DCanvasImageBufferCreated);
return surface;
}
@@ -1038,14 +1041,9 @@ std::unique_ptr<Canvas2DLayerBridge>
HTMLCanvasElement::CreateUnaccelerated2dBuffer() {
auto surface = std::make_unique<Canvas2DLayerBridge>(
Size(), Canvas2DLayerBridge::kDisableAcceleration, ColorParams());
- if (surface->IsValid()) {
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kUnaccelerated2DCanvasImageBufferCreated);
+ if (surface->IsValid())
return surface;
- }
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kUnaccelerated2DCanvasImageBufferCreationFailed);
return nullptr;
}
@@ -1121,8 +1119,8 @@ void HTMLCanvasElement::SetResourceProviderForTesting(
std::unique_ptr<Canvas2DLayerBridge> bridge,
const IntSize& size) {
DiscardResourceProvider();
- SetIntegralAttribute(widthAttr, size.Width());
- SetIntegralAttribute(heightAttr, size.Height());
+ SetIntegralAttribute(kWidthAttr, size.Width());
+ SetIntegralAttribute(kHeightAttr, size.Height());
SetCanvas2DLayerBridgeInternal(std::move(bridge));
ReplaceResourceProvider(std::move(resource_provider));
}
@@ -1163,7 +1161,7 @@ void HTMLCanvasElement::DidMoveToNewDocument(Document& old_document) {
}
void HTMLCanvasElement::WillDrawImageTo2DContext(CanvasImageSource* source) {
- if (CanvasHeuristicParameters::kEnableAccelerationToAvoidReadbacks &&
+ if (canvas_heuristic_parameters::kEnableAccelerationToAvoidReadbacks &&
SharedGpuContext::AllowSoftwareToAcceleratedCanvasUpgrade() &&
source->IsAccelerated() && GetOrCreateCanvas2DLayerBridge() &&
!canvas2d_bridge_->IsAccelerated() &&
@@ -1223,7 +1221,7 @@ scoped_refptr<Image> HTMLCanvasElement::GetSourceImageForCanvas(
else
image = CreateTransparentImage(Size());
} else {
- if (CanvasHeuristicParameters::kDisableAccelerationToAvoidReadbacks &&
+ if (canvas_heuristic_parameters::kDisableAccelerationToAvoidReadbacks &&
!RuntimeEnabledFeatures::Canvas2dFixedRenderingModeEnabled() &&
hint == kPreferNoAcceleration && canvas2d_bridge_ &&
canvas2d_bridge_->IsAccelerated()) {
@@ -1265,7 +1263,7 @@ ScriptPromise HTMLCanvasElement::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
DCHECK(event_target.ToLocalDOMWindow());
return ImageBitmapSource::FulfillImageBitmap(
@@ -1310,8 +1308,8 @@ bool HTMLCanvasElement::IsSupportedInteractiveCanvasFallback(
// Button states. An input element that is a button but its type attribute is
// not in the Image Button state.
if (auto* input_element = ToHTMLInputElementOrNull(element)) {
- if (input_element->type() == InputTypeNames::checkbox ||
- input_element->type() == InputTypeNames::radio ||
+ if (input_element->type() == input_type_names::kCheckbox ||
+ input_element->type() == input_type_names::kRadio ||
input_element->IsTextButton()) {
return true;
}
@@ -1336,19 +1334,19 @@ bool HTMLCanvasElement::IsSupportedInteractiveCanvasFallback(
// An element that would not be interactive content except for having the
// tabindex attribute specified.
- if (element.FastHasAttribute(HTMLNames::tabindexAttr))
+ if (element.FastHasAttribute(html_names::kTabindexAttr))
return true;
// A non-interactive table, caption, thead, tbody, tfoot, tr, td, or th
// element.
if (IsHTMLTableElement(element) ||
- element.HasTagName(HTMLNames::captionTag) ||
- element.HasTagName(HTMLNames::theadTag) ||
- element.HasTagName(HTMLNames::tbodyTag) ||
- element.HasTagName(HTMLNames::tfootTag) ||
- element.HasTagName(HTMLNames::trTag) ||
- element.HasTagName(HTMLNames::tdTag) ||
- element.HasTagName(HTMLNames::thTag))
+ element.HasTagName(html_names::kCaptionTag) ||
+ element.HasTagName(html_names::kTheadTag) ||
+ element.HasTagName(html_names::kTbodyTag) ||
+ element.HasTagName(html_names::kTfootTag) ||
+ element.HasTagName(html_names::kTrTag) ||
+ element.HasTagName(html_names::kTdTag) ||
+ element.HasTagName(html_names::kThTag))
return true;
return false;
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.h b/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.h
index 9bd1a6d3d43..59a1f9549cc 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.h
@@ -225,7 +225,7 @@ class CORE_EXPORT HTMLCanvasElement final
ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions&) override;
+ const ImageBitmapOptions*) override;
// OffscreenCanvasPlaceholder implementation.
void SetPlaceholderFrame(scoped_refptr<CanvasResource>,
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/image_data.cc b/chromium/third_party/blink/renderer/core/html/canvas/image_data.cc
index d5617a1fc7c..d39416e4e22 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/image_data.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/image_data.cc
@@ -238,65 +238,73 @@ ImageData* ImageData::Create(const IntSize& size,
AllocateAndValidateDataArray(4 * static_cast<unsigned>(size.Width()) *
static_cast<unsigned>(size.Height()),
storage_format);
- return data_array ? new ImageData(size, data_array, color_settings) : nullptr;
+ return data_array
+ ? MakeGarbageCollected<ImageData>(size, data_array, color_settings)
+ : nullptr;
}
-ImageDataColorSettings CanvasColorParamsToImageDataColorSettings(
+ImageDataColorSettings* CanvasColorParamsToImageDataColorSettings(
const CanvasColorParams& color_params) {
- ImageDataColorSettings color_settings;
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
switch (color_params.ColorSpace()) {
case kSRGBCanvasColorSpace:
- color_settings.setColorSpace(kSRGBCanvasColorSpaceName);
+ color_settings->setColorSpace(kSRGBCanvasColorSpaceName);
+ break;
+ case kLinearRGBCanvasColorSpace:
+ color_settings->setColorSpace(kLinearRGBCanvasColorSpaceName);
break;
case kRec2020CanvasColorSpace:
- color_settings.setColorSpace(kRec2020CanvasColorSpaceName);
+ color_settings->setColorSpace(kRec2020CanvasColorSpaceName);
break;
case kP3CanvasColorSpace:
- color_settings.setColorSpace(kP3CanvasColorSpaceName);
+ color_settings->setColorSpace(kP3CanvasColorSpaceName);
break;
}
- color_settings.setStorageFormat(kUint8ClampedArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint8ClampedArrayStorageFormatName);
if (color_params.PixelFormat() == kF16CanvasPixelFormat)
- color_settings.setStorageFormat(kFloat32ArrayStorageFormatName);
+ color_settings->setStorageFormat(kFloat32ArrayStorageFormatName);
return color_settings;
}
ImageData* ImageData::Create(const IntSize& size,
const CanvasColorParams& color_params) {
- ImageDataColorSettings color_settings =
+ ImageDataColorSettings* color_settings =
CanvasColorParamsToImageDataColorSettings(color_params);
- return ImageData::Create(size, &color_settings);
+ return ImageData::Create(size, color_settings);
}
ImageData* ImageData::Create(const IntSize& size,
CanvasColorSpace color_space,
ImageDataStorageFormat storage_format) {
- ImageDataColorSettings color_settings;
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
switch (color_space) {
case kSRGBCanvasColorSpace:
- color_settings.setColorSpace(kSRGBCanvasColorSpaceName);
+ color_settings->setColorSpace(kSRGBCanvasColorSpaceName);
+ break;
+ case kLinearRGBCanvasColorSpace:
+ color_settings->setColorSpace(kLinearRGBCanvasColorSpaceName);
break;
case kRec2020CanvasColorSpace:
- color_settings.setColorSpace(kRec2020CanvasColorSpaceName);
+ color_settings->setColorSpace(kRec2020CanvasColorSpaceName);
break;
case kP3CanvasColorSpace:
- color_settings.setColorSpace(kP3CanvasColorSpaceName);
+ color_settings->setColorSpace(kP3CanvasColorSpaceName);
break;
}
switch (storage_format) {
case kUint8ClampedArrayStorageFormat:
- color_settings.setStorageFormat(kUint8ClampedArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint8ClampedArrayStorageFormatName);
break;
case kUint16ArrayStorageFormat:
- color_settings.setStorageFormat(kUint16ArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint16ArrayStorageFormatName);
break;
case kFloat32ArrayStorageFormat:
- color_settings.setStorageFormat(kFloat32ArrayStorageFormatName);
+ color_settings->setStorageFormat(kFloat32ArrayStorageFormatName);
break;
}
- return ImageData::Create(size, &color_settings);
+ return ImageData::Create(size, color_settings);
}
ImageData* ImageData::Create(const IntSize& size,
@@ -306,7 +314,8 @@ ImageData* ImageData::Create(const IntSize& size,
0, 0, data_array.View(),
color_settings))
return nullptr;
- return new ImageData(size, data_array.View(), color_settings);
+ return MakeGarbageCollected<ImageData>(size, data_array.View(),
+ color_settings);
}
static SkImageInfo GetImageInfo(scoped_refptr<StaticBitmapImage> image) {
@@ -354,10 +363,10 @@ ImageData* ImageData::Create(scoped_refptr<StaticBitmapImage> image,
image_info = image_info.makeColorType(kRGBA_F32_SkColorType);
skia_image->readPixels(image_info, f32_array->Data(),
image_info.minRowBytes(), 0, 0);
- ImageDataColorSettings color_settings =
+ ImageDataColorSettings* color_settings =
CanvasColorParamsToImageDataColorSettings(color_params);
return Create(image->Size(), NotShared<blink::DOMArrayBufferView>(f32_array),
- &color_settings);
+ color_settings);
}
ImageData* ImageData::Create(unsigned width,
@@ -370,7 +379,8 @@ ImageData* ImageData::Create(unsigned width,
DOMArrayBufferView* byte_array = AllocateAndValidateDataArray(
4 * width * height, kUint8ClampedArrayStorageFormat, &exception_state);
- return byte_array ? new ImageData(IntSize(width, height), byte_array)
+ return byte_array ? MakeGarbageCollected<ImageData>(IntSize(width, height),
+ byte_array)
: nullptr;
}
@@ -383,7 +393,7 @@ ImageData* ImageData::Create(NotShared<DOMUint8ClampedArray> data,
return nullptr;
unsigned height = data.View()->length() / (width * 4);
- return new ImageData(IntSize(width, height), data.View());
+ return MakeGarbageCollected<ImageData>(IntSize(width, height), data.View());
}
ImageData* ImageData::Create(NotShared<DOMUint8ClampedArray> data,
@@ -395,34 +405,35 @@ ImageData* ImageData::Create(NotShared<DOMUint8ClampedArray> data,
data.View(), nullptr, &exception_state))
return nullptr;
- return new ImageData(IntSize(width, height), data.View());
+ return MakeGarbageCollected<ImageData>(IntSize(width, height), data.View());
}
ImageData* ImageData::CreateImageData(
unsigned width,
unsigned height,
- const ImageDataColorSettings& color_settings,
+ const ImageDataColorSettings* color_settings,
ExceptionState& exception_state) {
if (!ImageData::ValidateConstructorArguments(
kParamWidth | kParamHeight, nullptr, width, height, nullptr,
- &color_settings, &exception_state))
+ color_settings, &exception_state))
return nullptr;
ImageDataStorageFormat storage_format =
- ImageData::GetImageDataStorageFormat(color_settings.storageFormat());
+ ImageData::GetImageDataStorageFormat(color_settings->storageFormat());
DOMArrayBufferView* buffer_view = AllocateAndValidateDataArray(
4 * width * height, storage_format, &exception_state);
if (!buffer_view)
return nullptr;
- return new ImageData(IntSize(width, height), buffer_view, &color_settings);
+ return MakeGarbageCollected<ImageData>(IntSize(width, height), buffer_view,
+ color_settings);
}
ImageData* ImageData::CreateImageData(ImageDataArray& data,
unsigned width,
unsigned height,
- ImageDataColorSettings& color_settings,
+ ImageDataColorSettings* color_settings,
ExceptionState& exception_state) {
DOMArrayBufferView* buffer_view = nullptr;
@@ -444,15 +455,16 @@ ImageData* ImageData::CreateImageData(ImageDataArray& data,
NOTREACHED();
}
- if (storage_format_name != color_settings.storageFormat())
- color_settings.setStorageFormat(storage_format_name);
+ if (storage_format_name != color_settings->storageFormat())
+ color_settings->setStorageFormat(storage_format_name);
if (!ImageData::ValidateConstructorArguments(
kParamData | kParamWidth | kParamHeight, nullptr, width, height,
- buffer_view, &color_settings, &exception_state))
+ buffer_view, color_settings, &exception_state))
return nullptr;
- return new ImageData(IntSize(width, height), buffer_view, &color_settings);
+ return MakeGarbageCollected<ImageData>(IntSize(width, height), buffer_view,
+ color_settings);
}
// This function accepts size (0, 0) and always returns the ImageData in
@@ -470,7 +482,7 @@ ImageData* ImageData::CreateForTest(const IntSize& size) {
if (!byte_array)
return nullptr;
- return new ImageData(size, byte_array);
+ return MakeGarbageCollected<ImageData>(size, byte_array);
}
// This function is called from unit tests, and all the parameters are supposed
@@ -479,7 +491,7 @@ ImageData* ImageData::CreateForTest(
const IntSize& size,
DOMArrayBufferView* buffer_view,
const ImageDataColorSettings* color_settings) {
- return new ImageData(size, buffer_view, color_settings);
+ return MakeGarbageCollected<ImageData>(size, buffer_view, color_settings);
}
// Crops ImageData to the intersect of its size and the given rectangle. If the
@@ -499,7 +511,7 @@ ImageData* ImageData::CropRect(const IntRect& crop_rect, bool flip_y) {
unsigned data_size = 4 * dst_rect.Width() * dst_rect.Height();
DOMArrayBufferView* buffer_view = AllocateAndValidateDataArray(
data_size,
- ImageData::GetImageDataStorageFormat(color_settings_.storageFormat()));
+ ImageData::GetImageDataStorageFormat(color_settings_->storageFormat()));
if (!buffer_view)
return nullptr;
@@ -508,7 +520,7 @@ ImageData* ImageData::CropRect(const IntRect& crop_rect, bool flip_y) {
data_size * buffer_view->TypeSize());
} else {
unsigned data_type_size =
- ImageData::StorageFormatDataSize(color_settings_.storageFormat());
+ ImageData::StorageFormatDataSize(color_settings_->storageFormat());
int src_index = (dst_rect.X() + dst_rect.Y() * src_rect.Width()) * 4;
int dst_index = 0;
if (flip_y)
@@ -525,13 +537,14 @@ ImageData* ImageData::CropRect(const IntRect& crop_rect, bool flip_y) {
dst_index += dst_row_stride;
}
}
- return new ImageData(dst_rect.Size(), buffer_view, &color_settings_);
+ return MakeGarbageCollected<ImageData>(dst_rect.Size(), buffer_view,
+ color_settings_);
}
ScriptPromise ImageData::CreateImageBitmap(ScriptState* script_state,
EventTarget& event_target,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
if (BufferBase()->IsNeutered()) {
return ScriptPromise::RejectWithDOMException(
script_state,
@@ -554,23 +567,27 @@ v8::Local<v8::Object> ImageData::AssociateWithWrapper(
// of the ImageData object to the created v8 object, eliminating the
// C++ callback when accessing the "data" property.
v8::Local<v8::Value> pixel_array = ToV8(data_.Get(), wrapper, isolate);
+ bool defined_property;
if (pixel_array.IsEmpty() ||
- !V8CallBoolean(wrapper->DefineOwnProperty(
- isolate->GetCurrentContext(), V8AtomicString(isolate, "data"),
- pixel_array, v8::ReadOnly)))
+ !wrapper
+ ->DefineOwnProperty(isolate->GetCurrentContext(),
+ V8AtomicString(isolate, "data"), pixel_array,
+ v8::ReadOnly)
+ .To(&defined_property) ||
+ !defined_property)
return v8::Local<v8::Object>();
}
return wrapper;
}
const DOMUint8ClampedArray* ImageData::data() const {
- if (color_settings_.storageFormat() == kUint8ClampedArrayStorageFormatName)
+ if (color_settings_->storageFormat() == kUint8ClampedArrayStorageFormatName)
return data_.Get();
return nullptr;
}
DOMUint8ClampedArray* ImageData::data() {
- if (color_settings_.storageFormat() == kUint8ClampedArrayStorageFormatName)
+ if (color_settings_->storageFormat() == kUint8ClampedArrayStorageFormatName)
return data_.Get();
return nullptr;
}
@@ -579,6 +596,8 @@ CanvasColorSpace ImageData::GetCanvasColorSpace(
const String& color_space_name) {
if (color_space_name == kSRGBCanvasColorSpaceName)
return kSRGBCanvasColorSpace;
+ if (color_space_name == kLinearRGBCanvasColorSpaceName)
+ return kLinearRGBCanvasColorSpace;
if (color_space_name == kRec2020CanvasColorSpaceName)
return kRec2020CanvasColorSpace;
if (color_space_name == kP3CanvasColorSpaceName)
@@ -591,6 +610,8 @@ String ImageData::CanvasColorSpaceName(CanvasColorSpace color_space) {
switch (color_space) {
case kSRGBCanvasColorSpace:
return kSRGBCanvasColorSpaceName;
+ case kLinearRGBCanvasColorSpace:
+ return kLinearRGBCanvasColorSpaceName;
case kRec2020CanvasColorSpace:
return kRec2020CanvasColorSpaceName;
case kP3CanvasColorSpace:
@@ -716,9 +737,9 @@ CanvasColorParams ImageData::GetCanvasColorParams() {
if (!RuntimeEnabledFeatures::CanvasColorManagementEnabled())
return CanvasColorParams();
CanvasColorSpace color_space =
- ImageData::GetCanvasColorSpace(color_settings_.colorSpace());
+ ImageData::GetCanvasColorSpace(color_settings_->colorSpace());
CanvasPixelFormat pixel_format = kRGBA8CanvasPixelFormat;
- if (color_settings_.storageFormat() != kUint8ClampedArrayStorageFormatName)
+ if (color_settings_->storageFormat() != kUint8ClampedArrayStorageFormatName)
pixel_format = kF16CanvasPixelFormat;
return CanvasColorParams(color_space, pixel_format, kNonOpaque);
}
@@ -810,6 +831,7 @@ bool ImageData::ImageDataInCanvasColorSettings(
}
void ImageData::Trace(blink::Visitor* visitor) {
+ visitor->Trace(color_settings_);
visitor->Trace(data_);
visitor->Trace(data_u16_);
visitor->Trace(data_f32_);
@@ -820,7 +842,7 @@ void ImageData::Trace(blink::Visitor* visitor) {
ImageData::ImageData(const IntSize& size,
DOMArrayBufferView* data,
const ImageDataColorSettings* color_settings)
- : size_(size) {
+ : size_(size), color_settings_(ImageDataColorSettings::Create()) {
DCHECK_GE(size.Width(), 0);
DCHECK_GE(size.Height(), 0);
DCHECK(data);
@@ -830,12 +852,12 @@ ImageData::ImageData(const IntSize& size,
data_f32_ = nullptr;
if (color_settings) {
- color_settings_.setColorSpace(color_settings->colorSpace());
- color_settings_.setStorageFormat(color_settings->storageFormat());
+ color_settings_->setColorSpace(color_settings->colorSpace());
+ color_settings_->setStorageFormat(color_settings->storageFormat());
}
ImageDataStorageFormat storage_format =
- GetImageDataStorageFormat(color_settings_.storageFormat());
+ GetImageDataStorageFormat(color_settings_->storageFormat());
// TODO (zakerinasab): crbug.com/779570
// The default color space for ImageData with U16/F32 data should be
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/image_data.h b/chromium/third_party/blink/renderer/core/html/canvas/image_data.h
index 87486fae077..e5adfd82b59 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/image_data.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/image_data.h
@@ -93,23 +93,25 @@ class CORE_EXPORT ImageData final : public ScriptWrappable,
static ImageData* CreateImageData(unsigned width,
unsigned height,
- const ImageDataColorSettings&,
+ const ImageDataColorSettings*,
ExceptionState&);
static ImageData* CreateImageData(ImageDataArray&,
unsigned width,
unsigned height,
- ImageDataColorSettings&,
+ ImageDataColorSettings*,
ExceptionState&);
- void getColorSettings(ImageDataColorSettings& result) {
- result = color_settings_;
- }
+ ImageDataColorSettings* getColorSettings() { return color_settings_; }
static ImageData* CreateForTest(const IntSize&);
static ImageData* CreateForTest(const IntSize&,
DOMArrayBufferView*,
const ImageDataColorSettings* = nullptr);
+ ImageData(const IntSize&,
+ DOMArrayBufferView*,
+ const ImageDataColorSettings* = nullptr);
+
ImageData* CropRect(const IntRect&, bool flip_y = false);
ImageDataStorageFormat GetImageDataStorageFormat();
@@ -155,7 +157,7 @@ class CORE_EXPORT ImageData final : public ScriptWrappable,
ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions&) override;
+ const ImageBitmapOptions*) override;
void Trace(blink::Visitor*) override;
@@ -174,12 +176,8 @@ class CORE_EXPORT ImageData final : public ScriptWrappable,
ExceptionState* = nullptr);
private:
- ImageData(const IntSize&,
- DOMArrayBufferView*,
- const ImageDataColorSettings* = nullptr);
-
IntSize size_;
- ImageDataColorSettings color_settings_;
+ Member<ImageDataColorSettings> color_settings_;
ImageDataArray data_union_;
Member<DOMUint8ClampedArray> data_;
Member<DOMUint16Array> data_u16_;
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/image_data_color_settings.idl b/chromium/third_party/blink/renderer/core/html/canvas/image_data_color_settings.idl
index 917e0e182c8..e8fc5ced5c1 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/image_data_color_settings.idl
+++ b/chromium/third_party/blink/renderer/core/html/canvas/image_data_color_settings.idl
@@ -6,6 +6,7 @@
enum CanvasColorSpace {
"srgb", // default
+ "linear-rgb",
"rec2020",
"p3",
};
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/image_data_test.cc b/chromium/third_party/blink/renderer/core/html/canvas/image_data_test.cc
index d0a8314922e..ec976c7f0e4 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/image_data_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/image_data_test.cc
@@ -129,7 +129,8 @@ TEST_F(ImageDataTest,
TEST_F(ImageDataTest, TestGetImageDataInCanvasColorSettings) {
unsigned num_image_data_color_spaces = 3;
CanvasColorSpace image_data_color_spaces[] = {
- kSRGBCanvasColorSpace, kRec2020CanvasColorSpace, kP3CanvasColorSpace,
+ kSRGBCanvasColorSpace, kLinearRGBCanvasColorSpace,
+ kRec2020CanvasColorSpace, kP3CanvasColorSpace,
};
unsigned num_image_data_storage_formats = 3;
@@ -140,13 +141,14 @@ TEST_F(ImageDataTest, TestGetImageDataInCanvasColorSettings) {
unsigned num_canvas_color_settings = 4;
CanvasColorSpace canvas_color_spaces[] = {
- kSRGBCanvasColorSpace, kSRGBCanvasColorSpace, kRec2020CanvasColorSpace,
+ kSRGBCanvasColorSpace, kSRGBCanvasColorSpace,
+ kLinearRGBCanvasColorSpace, kRec2020CanvasColorSpace,
kP3CanvasColorSpace,
};
CanvasPixelFormat canvas_pixel_formats[] = {
kRGBA8CanvasPixelFormat, kF16CanvasPixelFormat, kF16CanvasPixelFormat,
- kF16CanvasPixelFormat,
+ kF16CanvasPixelFormat, kF16CanvasPixelFormat,
};
// As cross checking the output of Skia color space covnersion API is not in
@@ -187,7 +189,7 @@ TEST_F(ImageDataTest, TestGetImageDataInCanvasColorSettings) {
EXPECT_EQ(data_length, data_f32->length());
ImageData* image_data = nullptr;
- ImageDataColorSettings color_settings;
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
// At most two bytes are needed for output per color component.
std::unique_ptr<uint8_t[]> pixels_converted_manually(
@@ -198,29 +200,29 @@ TEST_F(ImageDataTest, TestGetImageDataInCanvasColorSettings) {
// Loop through different possible combinations of image data color space and
// storage formats and create the respective test image data objects.
for (unsigned i = 0; i < num_image_data_color_spaces; i++) {
- color_settings.setColorSpace(
+ color_settings->setColorSpace(
ImageData::CanvasColorSpaceName(image_data_color_spaces[i]));
for (unsigned j = 0; j < num_image_data_storage_formats; j++) {
switch (image_data_storage_formats[j]) {
case kUint8ClampedArrayStorageFormat:
data_array = static_cast<DOMArrayBufferView*>(data_u8);
- color_settings.setStorageFormat(kUint8ClampedArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint8ClampedArrayStorageFormatName);
break;
case kUint16ArrayStorageFormat:
data_array = static_cast<DOMArrayBufferView*>(data_u16);
- color_settings.setStorageFormat(kUint16ArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint16ArrayStorageFormatName);
break;
case kFloat32ArrayStorageFormat:
data_array = static_cast<DOMArrayBufferView*>(data_f32);
- color_settings.setStorageFormat(kFloat32ArrayStorageFormatName);
+ color_settings->setStorageFormat(kFloat32ArrayStorageFormatName);
break;
default:
NOTREACHED();
}
image_data =
- ImageData::CreateForTest(IntSize(2, 2), data_array, &color_settings);
+ ImageData::CreateForTest(IntSize(2, 2), data_array, color_settings);
for (unsigned k = 0; k < num_canvas_color_settings; k++) {
// Convert the original data used to create ImageData to the
@@ -452,10 +454,10 @@ TEST_F(ImageDataTest, TestCropRect) {
else
data_array = static_cast<DOMArrayBufferView*>(data_f32);
- ImageDataColorSettings color_settings;
- color_settings.setStorageFormat(image_data_storage_format_names[i]);
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
+ color_settings->setStorageFormat(image_data_storage_format_names[i]);
image_data = ImageData::CreateForTest(IntSize(width, height), data_array,
- &color_settings);
+ color_settings);
for (int j = 0; j < num_test_cases; j++) {
// Test the size of the cropped image data
IntRect src_rect(IntPoint(), image_data->Size());
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.cc b/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.cc
index 52acd816c69..25f4742ce1f 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.cc
@@ -40,6 +40,10 @@ bool ImageElementBase::IsSVGSource() const {
return CachedImage() && CachedImage()->GetImage()->IsSVGImage();
}
+bool ImageElementBase::IsImageElement() const {
+ return CachedImage() && !CachedImage()->GetImage()->IsSVGImage();
+}
+
scoped_refptr<Image> ImageElementBase::GetSourceImageForCanvas(
SourceImageStatus* status,
AccelerationHint,
@@ -133,7 +137,7 @@ ScriptPromise ImageElementBase::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
DCHECK(event_target.ToLocalDOMWindow());
ImageResourceContent* image_content = CachedImage();
@@ -148,7 +152,7 @@ ScriptPromise ImageElementBase::CreateImageBitmap(
if (image->IsSVGImage()) {
if (!ToSVGImage(image)->HasIntrinsicDimensions() &&
(!crop_rect &&
- (!options.hasResizeWidth() || !options.hasResizeHeight()))) {
+ (!options->hasResizeWidth() || !options->hasResizeHeight()))) {
return ScriptPromise::RejectWithDOMException(
script_state,
DOMException::Create(
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.h b/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.h
index df77302d24a..8a36a2c7779 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/image_element_base.h
@@ -30,7 +30,7 @@ class CORE_EXPORT ImageElementBase : public CanvasImageSource,
ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect>,
- const ImageBitmapOptions&) override;
+ const ImageBitmapOptions*) override;
scoped_refptr<Image> GetSourceImageForCanvas(SourceImageStatus*,
AccelerationHint,
@@ -47,6 +47,8 @@ class CORE_EXPORT ImageElementBase : public CanvasImageSource,
bool IsSVGSource() const override;
+ bool IsImageElement() const override;
+
bool IsOpaque() const override;
const KURL& SourceURL() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.cc b/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.cc
index 1be8a7ea3b1..7936129e4a1 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.cc
+++ b/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.cc
@@ -38,6 +38,13 @@ float TextMetrics::GetFontBaseline(const TextBaseline& text_baseline,
return 0;
}
+void TextMetrics::Trace(blink::Visitor* visitor) {
+ visitor->Trace(baselines_);
+ ScriptWrappable::Trace(visitor);
+}
+
+TextMetrics::TextMetrics() : baselines_(Baselines::Create()) {}
+
void TextMetrics::Update(const Font& font,
const TextDirection& direction,
const TextBaseline& baseline,
@@ -84,10 +91,10 @@ void TextMetrics::Update(const Font& font,
em_height_descent_ = font_data->EmHeightDescent() + baseline_y;
// TODO(fserb): hanging/ideographic baselines are broken.
- baselines_.setAlphabetic(-baseline_y);
- baselines_.setHanging(ascent * kHangingAsPercentOfAscent / 100.0f -
- baseline_y);
- baselines_.setIdeographic(-descent - baseline_y);
+ baselines_->setAlphabetic(-baseline_y);
+ baselines_->setHanging(ascent * kHangingAsPercentOfAscent / 100.0f -
+ baseline_y);
+ baselines_->setIdeographic(-descent - baseline_y);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.h b/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.h
index 96d63e2e786..b6473de7351 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.h
@@ -39,18 +39,20 @@ class CORE_EXPORT TextMetrics final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static TextMetrics* Create() { return new TextMetrics; }
+ static TextMetrics* Create() { return MakeGarbageCollected<TextMetrics>(); }
static TextMetrics* Create(const Font& font,
const TextDirection& direction,
const TextBaseline& baseline,
const TextAlign& align,
const String& text) {
- TextMetrics* metric = new TextMetrics();
+ TextMetrics* metric = MakeGarbageCollected<TextMetrics>();
metric->Update(font, direction, baseline, align, text);
return metric;
}
+ TextMetrics();
+
double width() const { return width_; }
const Vector<double>& advances() const { return advances_; }
double actualBoundingBoxLeft() const { return actual_bounding_box_left_; }
@@ -63,18 +65,18 @@ class CORE_EXPORT TextMetrics final : public ScriptWrappable {
}
double emHeightAscent() const { return em_height_ascent_; }
double emHeightDescent() const { return em_height_descent_; }
- void getBaselines(Baselines& baselines) const { baselines = baselines_; }
- Baselines getBaselines() const { return baselines_; }
+ Baselines* getBaselines() const { return baselines_; }
static float GetFontBaseline(const TextBaseline&, const SimpleFontData&);
+ void Trace(blink::Visitor*) override;
+
private:
void Update(const Font&,
const TextDirection&,
const TextBaseline&,
const TextAlign&,
const String&);
- TextMetrics() = default;
// x-direction
double width_ = 0.0;
@@ -89,7 +91,7 @@ class CORE_EXPORT TextMetrics final : public ScriptWrappable {
double actual_bounding_box_descent_ = 0.0;
double em_height_ascent_ = 0.0;
double em_height_descent_ = 0.0;
- Baselines baselines_;
+ Member<Baselines> baselines_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/custom/README.md b/chromium/third_party/blink/renderer/core/html/custom/README.md
index 243b82bd0b7..d8cab10145c 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/README.md
+++ b/chromium/third_party/blink/renderer/core/html/custom/README.md
@@ -83,7 +83,7 @@ with CustomElement so you can run them with:
###### Layout Tests
The custom element layout tests are generally in
-third_party/WebKit/LayoutTests/custom-elements.
+third_party/blink/web_tests/custom-elements.
All custom elements layout tests use the [web-platform-tests
harness](https://web-platform-tests.org/) and follow its style. The
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element.cc
index 25176be6956..372e3ec5cb5 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/html/custom/ce_reactions_scope.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
+#include "third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_registry.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element.h"
@@ -98,7 +99,7 @@ bool CustomElement::ShouldCreateCustomElement(const AtomicString& name) {
bool CustomElement::ShouldCreateCustomElement(const QualifiedName& tag_name) {
return ShouldCreateCustomElement(tag_name.LocalName()) &&
- tag_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI;
+ tag_name.NamespaceURI() == html_names::xhtmlNamespaceURI;
}
bool CustomElement::ShouldCreateCustomizedBuiltinElement(
@@ -110,7 +111,7 @@ bool CustomElement::ShouldCreateCustomizedBuiltinElement(
bool CustomElement::ShouldCreateCustomizedBuiltinElement(
const QualifiedName& tag_name) {
return ShouldCreateCustomizedBuiltinElement(tag_name.LocalName()) &&
- tag_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI;
+ tag_name.NamespaceURI() == html_names::xhtmlNamespaceURI;
}
static CustomElementDefinition* DefinitionFor(
@@ -175,7 +176,7 @@ Element* CustomElement::CreateUncustomizedOrUndefinedElementTemplate(
// custom element state to "undefined".
if (level == kQNameIsValid)
element->SetCustomElementState(CustomElementState::kUndefined);
- else if (tag_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI &&
+ else if (tag_name.NamespaceURI() == html_names::xhtmlNamespaceURI &&
(CustomElement::IsValidName(tag_name.LocalName()) ||
!is_value.IsNull()))
element->SetCustomElementState(CustomElementState::kUndefined);
@@ -261,6 +262,17 @@ void CustomElement::EnqueueAttributeChangedCallback(
new_value);
}
+void CustomElement::EnqueueFormAssociatedCallback(
+ Element& element,
+ HTMLFormElement* nullable_form) {
+ auto* definition = DefinitionForElementWithoutCheck(element);
+ if (definition->HasFormAssociatedCallback()) {
+ Enqueue(&element,
+ MakeGarbageCollected<CustomElementFormAssociatedCallbackReaction>(
+ definition, nullable_form));
+ }
+}
+
void CustomElement::TryToUpgrade(Element* element,
bool upgrade_invisible_elements) {
// Try to upgrade an element
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element.h
index a0eb6747e54..a7ce7c32af7 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element.h
@@ -18,6 +18,7 @@ namespace blink {
class Document;
class Element;
class HTMLElement;
+class HTMLFormElement;
class QualifiedName;
class CustomElementDefinition;
class CustomElementReaction;
@@ -103,6 +104,8 @@ class CORE_EXPORT CustomElement {
const QualifiedName&,
const AtomicString& old_value,
const AtomicString& new_value);
+ static void EnqueueFormAssociatedCallback(Element& element,
+ HTMLFormElement* nullable_form);
static void TryToUpgrade(Element*, bool upgrade_invisible_elements = false);
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.cc
index 2764e2efd42..30979be3de3 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.cc
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_upgrade_reaction.h"
+#include "third_party/blink/renderer/core/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html_element_factory.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -29,11 +30,16 @@ CustomElementDefinition::CustomElementDefinition(
CustomElementDefinition::CustomElementDefinition(
const CustomElementDescriptor& descriptor,
- const HashSet<AtomicString>& observed_attributes)
+ const HashSet<AtomicString>& observed_attributes,
+ const Vector<String>& disabled_features,
+ FormAssociationFlag form_association_flag)
: descriptor_(descriptor),
observed_attributes_(observed_attributes),
has_style_attribute_changed_callback_(
- observed_attributes.Contains(HTMLNames::styleAttr.LocalName())) {}
+ observed_attributes.Contains(html_names::kStyleAttr.LocalName())),
+ disable_internals_(disabled_features.Contains(String("internals"))),
+ is_form_associated_(form_association_flag == FormAssociationFlag::kYes) {}
+
CustomElementDefinition::~CustomElementDefinition() = default;
void CustomElementDefinition::Trace(blink::Visitor* visitor) {
@@ -61,7 +67,7 @@ static String ErrorMessageForConstructorResult(Element* element,
return "The result must be in the same document";
// 6.1.8. If result's namespace is not the HTML namespace, then throw a
// NotSupportedError.
- if (element->namespaceURI() != HTMLNames::xhtmlNamespaceURI)
+ if (element->namespaceURI() != html_names::xhtmlNamespaceURI)
return "The result must have HTML namespace";
// 6.1.9. If result's local name is not equal to localName, then throw a
// NotSupportedError.
@@ -104,7 +110,7 @@ HTMLElement* CustomElementDefinition::CreateElementForConstructor(
} else {
element =
HTMLElement::Create(QualifiedName(g_null_atom, Descriptor().LocalName(),
- HTMLNames::xhtmlNamespaceURI),
+ html_names::xhtmlNamespaceURI),
document);
}
// TODO(davaajav): write this as one call to setCustomElementState instead of
@@ -206,6 +212,9 @@ void CustomElementDefinition::Upgrade(Element* element) {
}
element->SetCustomElementDefinition(this);
+
+ if (IsFormAssociated())
+ ToHTMLElement(element)->EnsureElementInternals().DidUpgrade();
AddDefaultStylesTo(*element);
}
@@ -230,9 +239,9 @@ void CustomElementDefinition::AddDefaultStylesTo(Element& element) {
for (CSSStyleSheet* sheet : default_styles)
sheet->AddToCustomElementTagNames(local_tag_name);
}
- element.SetNeedsStyleRecalc(kLocalStyleChange,
- StyleChangeReasonForTracing::Create(
- StyleChangeReason::kActiveStylesheetsUpdate));
+ element.SetNeedsStyleRecalc(
+ kLocalStyleChange, StyleChangeReasonForTracing::Create(
+ style_change_reason::kActiveStylesheetsUpdate));
}
bool CustomElementDefinition::HasAttributeChangedCallback(
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.h
index 760c9b76ce2..f94bf3ae33b 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition.h
@@ -23,8 +23,14 @@ class Document;
class Element;
class ExceptionState;
class HTMLElement;
+class HTMLFormElement;
class QualifiedName;
+enum class FormAssociationFlag {
+ kNo,
+ kYes,
+};
+
class CORE_EXPORT CustomElementDefinition
: public GarbageCollectedFinalized<CustomElementDefinition>,
public NameClient {
@@ -68,6 +74,8 @@ class CORE_EXPORT CustomElementDefinition
virtual bool HasAdoptedCallback() const = 0;
bool HasAttributeChangedCallback(const QualifiedName&) const;
bool HasStyleAttributeChangedCallback() const;
+ virtual bool HasFormAssociatedCallback() const = 0;
+ virtual bool HasDisabledStateChangedCallback() const = 0;
virtual void RunConnectedCallback(Element*) = 0;
virtual void RunDisconnectedCallback(Element*) = 0;
@@ -78,6 +86,10 @@ class CORE_EXPORT CustomElementDefinition
const QualifiedName&,
const AtomicString& old_value,
const AtomicString& new_value) = 0;
+ virtual void RunFormAssociatedCallback(Element* element,
+ HTMLFormElement* nullable_form) = 0;
+ virtual void RunDisabledStateChangedCallback(Element* element,
+ bool is_disabled) = 0;
void EnqueueUpgradeReaction(Element*,
bool upgrade_invisible_elements = false);
@@ -103,6 +115,8 @@ class CORE_EXPORT CustomElementDefinition
bool HasDefaultStyleSheets() const {
return !default_style_sheets_.IsEmpty();
}
+ bool DisableInternals() const { return disable_internals_; }
+ bool IsFormAssociated() const { return is_form_associated_; }
class CORE_EXPORT ConstructionStackScope final {
STACK_ALLOCATED();
@@ -122,7 +136,9 @@ class CORE_EXPORT CustomElementDefinition
CustomElementDefinition(const CustomElementDescriptor&);
CustomElementDefinition(const CustomElementDescriptor&,
- const HashSet<AtomicString>& observed_attributes);
+ const HashSet<AtomicString>& observed_attributes,
+ const Vector<String>& disabled_features,
+ FormAssociationFlag form_association_flag);
void AddDefaultStylesTo(Element&);
@@ -139,6 +155,8 @@ class CORE_EXPORT CustomElementDefinition
HashSet<AtomicString> observed_attributes_;
bool has_style_attribute_changed_callback_;
bool added_default_style_sheet_ = false;
+ bool disable_internals_ = false;
+ bool is_form_associated_ = false;
HeapVector<Member<CSSStyleSheet>> default_style_sheets_;
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_test.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_test.cc
index b9377f13020..07d98d1445b 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_test.cc
@@ -34,9 +34,12 @@ TEST(CustomElementDefinitionTest, upgrade_clearsReactionQueueOnFailure) {
<< "sanity check: this element should be ready to upgrade";
{
CEReactionsScope reactions;
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Unreached>(
+ "upgrade failure should clear the reaction queue"));
reactions.EnqueueToCurrentQueue(
- element, new TestReaction({new Unreached(
- "upgrade failure should clear the reaction queue")}));
+ element, MakeGarbageCollected<TestReaction>(commands));
ConstructorFails definition(CustomElementDescriptor("a-a", "a-a"));
definition.Upgrade(element);
}
@@ -50,9 +53,12 @@ TEST(CustomElementDefinitionTest,
EXPECT_EQ(CustomElementState::kUndefined, element->GetCustomElementState())
<< "sanity check: this element should be ready to upgrade";
ResetCustomElementReactionStackForTest reset_reaction_stack;
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Unreached>(
+ "upgrade failure should clear the reaction queue"));
reset_reaction_stack.Stack().EnqueueToBackupQueue(
- element, new TestReaction({new Unreached(
- "upgrade failure should clear the reaction queue")}));
+ element, MakeGarbageCollected<TestReaction>(commands));
ConstructorFails definition(CustomElementDescriptor("a-a", "a-a"));
definition.Upgrade(element);
EXPECT_EQ(CustomElementState::kFailed, element->GetCustomElementState())
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_descriptor.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_descriptor.h
index d47ce6da73e..d24e368a0b9 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_descriptor.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_descriptor.h
@@ -49,7 +49,7 @@ class CORE_EXPORT CustomElementDescriptor final {
bool Matches(const Element& element) const {
return LocalName() == element.localName() &&
(IsAutonomous() || GetName() == element.IsValue()) &&
- element.namespaceURI() == HTMLNames::xhtmlNamespaceURI;
+ element.namespaceURI() == html_names::xhtmlNamespaceURI;
}
bool IsAutonomous() const { return name_ == local_name_; }
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.cc
new file mode 100644
index 00000000000..dc77d5c9cdf
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.cc
@@ -0,0 +1,30 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.h"
+
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
+#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
+
+namespace blink {
+
+CustomElementFormAssociatedCallbackReaction::
+ CustomElementFormAssociatedCallbackReaction(
+ CustomElementDefinition* definition,
+ HTMLFormElement* nullable_form)
+ : CustomElementReaction(definition), form_(nullable_form) {
+ DCHECK(definition->HasFormAssociatedCallback());
+}
+
+void CustomElementFormAssociatedCallbackReaction::Trace(Visitor* visitor) {
+ visitor->Trace(form_);
+ CustomElementReaction::Trace(visitor);
+}
+
+void CustomElementFormAssociatedCallbackReaction::Invoke(Element* element) {
+ definition_->RunFormAssociatedCallback(element, form_.Get());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.h
new file mode 100644
index 00000000000..01d1d1b2de3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_form_associated_callback_reaction.h
@@ -0,0 +1,32 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_CUSTOM_ELEMENT_FORM_ASSOCIATED_CALLBACK_REACTION_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_CUSTOM_ELEMENT_FORM_ASSOCIATED_CALLBACK_REACTION_H_
+
+#include "base/macros.h"
+#include "third_party/blink/renderer/core/html/custom/custom_element_reaction.h"
+
+namespace blink {
+
+class HTMLFormElement;
+
+class CustomElementFormAssociatedCallbackReaction final
+ : public CustomElementReaction {
+ public:
+ CustomElementFormAssociatedCallbackReaction(CustomElementDefinition*,
+ HTMLFormElement* nullable_form);
+ void Trace(Visitor*) override;
+
+ private:
+ void Invoke(Element*) override;
+
+ Member<HTMLFormElement> form_;
+
+ DISALLOW_COPY_AND_ASSIGN(CustomElementFormAssociatedCallbackReaction);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_CUSTOM_ELEMENT_FORM_ASSOCIATED_CALLBACK_REACTION_H_
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_queue_test.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_queue_test.cc
index af1de9ce0da..651efd1e45e 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_queue_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_queue_test.cc
@@ -17,7 +17,10 @@ namespace blink {
TEST(CustomElementReactionQueueTest, invokeReactions_one) {
std::vector<char> log;
CustomElementReactionQueue* queue = new CustomElementReactionQueue();
- queue->Add(new TestReaction({new Log('a', log)}));
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
queue->InvokeReactions(nullptr);
EXPECT_EQ(log, std::vector<char>({'a'}))
<< "the reaction should have been invoked";
@@ -26,9 +29,24 @@ TEST(CustomElementReactionQueueTest, invokeReactions_one) {
TEST(CustomElementReactionQueueTest, invokeReactions_many) {
std::vector<char> log;
CustomElementReactionQueue* queue = new CustomElementReactionQueue();
- queue->Add(new TestReaction({new Log('a', log)}));
- queue->Add(new TestReaction({new Log('b', log)}));
- queue->Add(new TestReaction({new Log('c', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('b', log));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('c', log));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
+ }
queue->InvokeReactions(nullptr);
EXPECT_EQ(log, std::vector<char>({'a', 'b', 'c'}))
<< "the reaction should have been invoked";
@@ -38,16 +56,27 @@ TEST(CustomElementReactionQueueTest, invokeReactions_recursive) {
std::vector<char> log;
CustomElementReactionQueue* queue = new CustomElementReactionQueue();
- CustomElementReaction* third = new TestReaction(
- {new Log('c', log), new Recurse(queue)}); // "Empty" recursion
+ HeapVector<Member<Command>>* third_commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ third_commands->push_back(MakeGarbageCollected<Log>('c', log));
+ third_commands->push_back(MakeGarbageCollected<Recurse>(queue));
+ CustomElementReaction* third =
+ MakeGarbageCollected<TestReaction>(third_commands); // "Empty" recursion
- CustomElementReaction* second = new TestReaction(
- {new Log('b', log),
- new Enqueue(queue, third)}); // Unwinds one level of recursion
+ HeapVector<Member<Command>>* second_commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ second_commands->push_back(MakeGarbageCollected<Log>('b', log));
+ second_commands->push_back(MakeGarbageCollected<Enqueue>(queue, third));
+ CustomElementReaction* second = MakeGarbageCollected<TestReaction>(
+ second_commands); // Unwinds one level of recursion
- CustomElementReaction* first =
- new TestReaction({new Log('a', log), new Enqueue(queue, second),
- new Recurse(queue)}); // Non-empty recursion
+ HeapVector<Member<Command>>* first_commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ first_commands->push_back(MakeGarbageCollected<Log>('a', log));
+ first_commands->push_back(MakeGarbageCollected<Enqueue>(queue, second));
+ first_commands->push_back(MakeGarbageCollected<Recurse>(queue));
+ CustomElementReaction* first = MakeGarbageCollected<TestReaction>(
+ first_commands); // Non-empty recursion
queue->Add(first);
queue->InvokeReactions(nullptr);
@@ -59,11 +88,26 @@ TEST(CustomElementReactionQueueTest, clear_duringInvoke) {
std::vector<char> log;
CustomElementReactionQueue* queue = new CustomElementReactionQueue();
- queue->Add(new TestReaction({new Log('a', log)}));
- queue->Add(new TestReaction({new Call(WTF::Bind(
- [](CustomElementReactionQueue* queue, Element*) { queue->Clear(); },
- WrapPersistent(queue)))}));
- queue->Add(new TestReaction({new Log('b', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(new Call(WTF::Bind(
+ [](CustomElementReactionQueue* queue, Element*) { queue->Clear(); },
+ WrapPersistent(queue))));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('b', log));
+ queue->Add(MakeGarbageCollected<TestReaction>(commands));
+ }
queue->InvokeReactions(nullptr);
EXPECT_EQ(log, std::vector<char>({'a'}))
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.cc
index 17f2895c4e0..48b65d63226 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.cc
@@ -66,7 +66,7 @@ void CustomElementReactionStack::Enqueue(Member<ElementQueue>& queue,
Element* element,
CustomElementReaction* reaction) {
if (!queue)
- queue = new ElementQueue();
+ queue = MakeGarbageCollected<ElementQueue>();
queue->push_back(element);
CustomElementReactionQueue* reactions = map_.at(element);
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack_test.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack_test.cc
index 5ed8fbfa8b8..49ec44d502d 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack_test.cc
@@ -21,8 +21,11 @@ TEST(CustomElementReactionStackTest, one) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('a', log)}));
+ MakeGarbageCollected<TestReaction>(commands));
stack->PopInvokingReactions();
EXPECT_EQ(log, std::vector<char>({'a'}))
@@ -34,10 +37,20 @@ TEST(CustomElementReactionStackTest, multipleElements) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('a', log)}));
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('b', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('b', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->PopInvokingReactions();
EXPECT_EQ(log, std::vector<char>({'a', 'b'}))
@@ -49,8 +62,11 @@ TEST(CustomElementReactionStackTest, popTopEmpty) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('a', log)}));
+ MakeGarbageCollected<TestReaction>(commands));
stack->Push();
stack->PopInvokingReactions();
@@ -63,11 +79,21 @@ TEST(CustomElementReactionStackTest, popTop) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('a', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->Push();
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('b', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('b', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->PopInvokingReactions();
EXPECT_EQ(log, std::vector<char>({'b'}))
@@ -81,10 +107,27 @@ TEST(CustomElementReactionStackTest, requeueingDoesNotReorderElements) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
- stack->EnqueueToCurrentQueue(element, new TestReaction({new Log('a', log)}));
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('z', log)}));
- stack->EnqueueToCurrentQueue(element, new TestReaction({new Log('b', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ stack->EnqueueToCurrentQueue(element,
+ MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('z', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('b', log));
+ stack->EnqueueToCurrentQueue(element,
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->PopInvokingReactions();
EXPECT_EQ(log, std::vector<char>({'a', 'b', 'z'}))
@@ -98,13 +141,35 @@ TEST(CustomElementReactionStackTest, oneReactionQueuePerElement) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
- stack->EnqueueToCurrentQueue(element, new TestReaction({new Log('a', log)}));
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('z', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('a', log));
+ stack->EnqueueToCurrentQueue(element,
+ MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('z', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->Push();
- stack->EnqueueToCurrentQueue(CreateElement("a"),
- new TestReaction({new Log('y', log)}));
- stack->EnqueueToCurrentQueue(element, new TestReaction({new Log('b', log)}));
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('y', log));
+ stack->EnqueueToCurrentQueue(CreateElement("a"),
+ MakeGarbageCollected<TestReaction>(commands));
+ }
+ {
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<Log>('b', log));
+ stack->EnqueueToCurrentQueue(element,
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->PopInvokingReactions();
EXPECT_EQ(log, std::vector<char>({'y', 'a', 'b'}))
@@ -147,9 +212,17 @@ TEST(CustomElementReactionStackTest, enqueueFromReaction) {
CustomElementReactionStack* stack = new CustomElementReactionStack();
stack->Push();
- stack->EnqueueToCurrentQueue(
- element, new TestReaction({new EnqueueToStack(
- stack, element, new TestReaction({new Log('a', log)}))}));
+ {
+ HeapVector<Member<Command>>* subcommands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ subcommands->push_back(MakeGarbageCollected<Log>('a', log));
+ HeapVector<Member<Command>>* commands =
+ MakeGarbageCollected<HeapVector<Member<Command>>>();
+ commands->push_back(MakeGarbageCollected<EnqueueToStack>(
+ stack, element, MakeGarbageCollected<TestReaction>(subcommands)));
+ stack->EnqueueToCurrentQueue(element,
+ MakeGarbageCollected<TestReaction>(commands));
+ }
stack->PopInvokingReactions();
EXPECT_EQ(log, std::vector<char>({'a'})) << "enqueued reaction from another "
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h
index 29cbabc7ed8..396d89d636c 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h
@@ -107,25 +107,20 @@ class Enqueue : public Command {
class TestReaction : public CustomElementReaction {
public:
- TestReaction(std::initializer_list<Command*> commands)
- : CustomElementReaction(nullptr) {
- // TODO(dominicc): Simply pass the initializer list when
- // HeapVector supports initializer lists like Vector.
- for (auto* const command : commands)
- commands_.push_back(command);
- }
+ TestReaction(HeapVector<Member<Command>>* commands)
+ : CustomElementReaction(nullptr), commands_(commands) {}
~TestReaction() override = default;
void Trace(blink::Visitor* visitor) override {
CustomElementReaction::Trace(visitor);
visitor->Trace(commands_);
}
void Invoke(Element* element) override {
- for (auto& command : commands_)
+ for (auto& command : *commands_)
command->Run(element);
}
private:
- HeapVector<Member<Command>> commands_;
+ Member<HeapVector<Member<Command>>> commands_;
DISALLOW_COPY_AND_ASSIGN(TestReaction);
};
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc
index c4ca5d9e54c..866bdc2f28f 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc
@@ -89,8 +89,8 @@ CustomElementRegistry* CustomElementRegistry::Create(
CustomElementRegistry::CustomElementRegistry(const LocalDOMWindow* owner)
: element_definition_is_running_(false),
owner_(owner),
- v0_(new V0RegistrySet()),
- upgrade_candidates_(new UpgradeCandidateMap()),
+ v0_(MakeGarbageCollected<V0RegistrySet>()),
+ upgrade_candidates_(MakeGarbageCollected<UpgradeCandidateMap>()),
reaction_stack_(&CustomElementReactionStack::Current()) {}
void CustomElementRegistry::Trace(blink::Visitor* visitor) {
@@ -107,7 +107,7 @@ CustomElementDefinition* CustomElementRegistry::define(
ScriptState* script_state,
const AtomicString& name,
V8CustomElementConstructor* constructor,
- const ElementDefinitionOptions& options,
+ const ElementDefinitionOptions* options,
ExceptionState& exception_state) {
ScriptCustomElementDefinitionBuilder builder(script_state, this, constructor,
exception_state);
@@ -119,7 +119,7 @@ CustomElementDefinition* CustomElementRegistry::DefineInternal(
ScriptState* script_state,
const AtomicString& name,
CustomElementDefinitionBuilder& builder,
- const ElementDefinitionOptions& options,
+ const ElementDefinitionOptions* options,
ExceptionState& exception_state) {
TRACE_EVENT1("blink", "CustomElementRegistry::define", "name", name.Utf8());
if (!builder.CheckConstructorIntrinsics())
@@ -150,10 +150,10 @@ CustomElementDefinition* CustomElementRegistry::DefineInternal(
// Step 7. customized built-in elements definition
// element interface extends option checks
- if (options.hasExtends()) {
+ if (options->hasExtends()) {
// 7.1. If element interface is valid custom element name, throw exception
- const AtomicString& extends = AtomicString(options.extends());
- if (ThrowIfValidName(AtomicString(options.extends()), exception_state))
+ const AtomicString& extends = AtomicString(options->extends());
+ if (ThrowIfValidName(AtomicString(options->extends()), exception_state))
return nullptr;
// 7.2. If element interface is undefined element, throw exception
if (htmlElementTypeForTag(extends) ==
@@ -212,9 +212,8 @@ CustomElementDefinition* CustomElementRegistry::DefineInternal(
CHECK(!exception_state.HadException());
CHECK(definition->Descriptor() == descriptor);
if (RuntimeEnabledFeatures::CustomElementDefaultStyleEnabled() &&
- options.hasStyles())
- definition->SetDefaultStyleSheets(options.styles());
-
+ options->hasStyles())
+ definition->SetDefaultStyleSheets(options->styles());
definitions_.emplace_back(definition);
NameIdMap::AddResult result = name_id_map_.insert(descriptor.GetName(), id);
CHECK(result.is_new_entry);
@@ -304,7 +303,8 @@ void CustomElementRegistry::AddCandidate(Element* candidate) {
if (it != upgrade_candidates_->end()) {
set = it->value;
} else {
- set = upgrade_candidates_->insert(name, new UpgradeCandidateSet())
+ set = upgrade_candidates_
+ ->insert(name, MakeGarbageCollected<UpgradeCandidateSet>())
.stored_value->value;
}
set->insert(candidate);
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.h
index a323e28be66..5b3f44845d1 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.h
@@ -42,7 +42,7 @@ class CORE_EXPORT CustomElementRegistry final : public ScriptWrappable {
CustomElementDefinition* define(ScriptState*,
const AtomicString& name,
V8CustomElementConstructor* constructor,
- const ElementDefinitionOptions&,
+ const ElementDefinitionOptions*,
ExceptionState&);
ScriptValue get(const AtomicString& name);
@@ -72,7 +72,7 @@ class CORE_EXPORT CustomElementRegistry final : public ScriptWrappable {
CustomElementDefinition* DefineInternal(ScriptState*,
const AtomicString& name,
CustomElementDefinitionBuilder&,
- const ElementDefinitionOptions&,
+ const ElementDefinitionOptions*,
ExceptionState&);
bool V0NameIsDefined(const AtomicString& name);
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.idl b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.idl
index aab5cdf98ab..8061cb734e4 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.idl
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.idl
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+// https://html.spec.whatwg.org/C/custom-elements.html#customelementregistry
+
interface CustomElementRegistry {
[CallWith=ScriptState, CEReactions, CustomElementCallbacks, RaisesException, MeasureAs=CustomElementRegistryDefine] void define(DOMString name, CustomElementConstructor constructor, optional ElementDefinitionOptions options);
any get(DOMString name);
@@ -10,3 +12,10 @@ interface CustomElementRegistry {
};
callback CustomElementConstructor = any ();
+
+// Blink specific types. HTML standard does not explicitly define these types.
+callback CustomElementAdoptedCallback = void (Document oldOwner, Document newOwner);
+callback CustomElementAttributeChangedCallback = void (DOMString localName, DOMString? oldValue, DOMString? newValue, USVString? attrNamespace);
+callback CustomElementFormAssociatedCallback = void (HTMLFormElement? form);
+callback CustomElementDisabledStateChangedCallback = void (boolean disabled);
+
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry_test.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry_test.cc
index 7cef1b7046a..522e8116366 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry_test.cc
@@ -43,7 +43,7 @@ class CustomElementRegistryTest : public PageTestBase {
CustomElementDefinition* Define(const AtomicString& name,
CustomElementDefinitionBuilder& builder,
- const ElementDefinitionOptions& options,
+ const ElementDefinitionOptions* options,
ExceptionState& exception_state) {
return Registry().DefineInternal(GetScriptState(), name, builder, options,
exception_state);
@@ -170,8 +170,9 @@ class LogUpgradeDefinition : public TestCustomElementDefinition {
: TestCustomElementDefinition(
descriptor,
{
- "attr1", "attr2", HTMLNames::contenteditableAttr.LocalName(),
- }) {}
+ "attr1", "attr2", html_names::kContenteditableAttr.LocalName(),
+ },
+ {}) {}
void Trace(blink::Visitor* visitor) override {
TestCustomElementDefinition::Trace(visitor);
@@ -242,7 +243,7 @@ class LogUpgradeDefinition : public TestCustomElementDefinition {
Document* new_owner) override {
logs_.push_back(kAdoptedCallback);
EXPECT_EQ(element, element_);
- adopted_.push_back(new Adopted(old_owner, new_owner));
+ adopted_.push_back(MakeGarbageCollected<Adopted>(old_owner, new_owner));
}
void RunAttributeChangedCallback(Element* element,
@@ -265,7 +266,7 @@ class LogUpgradeBuilder final : public TestCustomElementDefinitionBuilder {
CustomElementDefinition* Build(const CustomElementDescriptor& descriptor,
CustomElementDefinition::Id) override {
- return new LogUpgradeDefinition(descriptor);
+ return MakeGarbageCollected<LogUpgradeDefinition>(descriptor);
}
DISALLOW_COPY_AND_ASSIGN(LogUpgradeBuilder);
@@ -276,15 +277,16 @@ TEST_F(CustomElementRegistryTest, define_upgradesInDocumentElements) {
Element* element = CreateElement("a-a").InDocument(&GetDocument());
element->setAttribute(
- QualifiedName(g_null_atom, "attr1", HTMLNames::xhtmlNamespaceURI), "v1");
- element->SetBooleanAttribute(HTMLNames::contenteditableAttr, true);
+ QualifiedName(g_null_atom, "attr1", html_names::xhtmlNamespaceURI), "v1");
+ element->SetBooleanAttribute(html_names::kContenteditableAttr, true);
GetDocument().documentElement()->AppendChild(element);
LogUpgradeBuilder builder;
NonThrowableExceptionState should_not_throw;
{
CEReactionsScope reactions;
- Define("a-a", builder, ElementDefinitionOptions(), should_not_throw);
+ Define("a-a", builder, ElementDefinitionOptions::Create(),
+ should_not_throw);
}
LogUpgradeDefinition* definition =
static_cast<LogUpgradeDefinition*>(Registry().DefinitionForName("a-a"));
@@ -326,7 +328,8 @@ TEST_F(CustomElementRegistryTest, attributeChangedCallback) {
NonThrowableExceptionState should_not_throw;
{
CEReactionsScope reactions;
- Define("a-a", builder, ElementDefinitionOptions(), should_not_throw);
+ Define("a-a", builder, ElementDefinitionOptions::Create(),
+ should_not_throw);
}
LogUpgradeDefinition* definition =
static_cast<LogUpgradeDefinition*>(Registry().DefinitionForName("a-a"));
@@ -335,7 +338,7 @@ TEST_F(CustomElementRegistryTest, attributeChangedCallback) {
{
CEReactionsScope reactions;
element->setAttribute(
- QualifiedName(g_null_atom, "attr2", HTMLNames::xhtmlNamespaceURI),
+ QualifiedName(g_null_atom, "attr2", html_names::xhtmlNamespaceURI),
"v2");
}
EXPECT_EQ(LogUpgradeDefinition::kAttributeChangedCallback,
@@ -361,7 +364,8 @@ TEST_F(CustomElementRegistryTest, disconnectedCallback) {
NonThrowableExceptionState should_not_throw;
{
CEReactionsScope reactions;
- Define("a-a", builder, ElementDefinitionOptions(), should_not_throw);
+ Define("a-a", builder, ElementDefinitionOptions::Create(),
+ should_not_throw);
}
LogUpgradeDefinition* definition =
static_cast<LogUpgradeDefinition*>(Registry().DefinitionForName("a-a"));
@@ -388,7 +392,8 @@ TEST_F(CustomElementRegistryTest, adoptedCallback) {
NonThrowableExceptionState should_not_throw;
{
CEReactionsScope reactions;
- Define("a-a", builder, ElementDefinitionOptions(), should_not_throw);
+ Define("a-a", builder, ElementDefinitionOptions::Create(),
+ should_not_throw);
}
LogUpgradeDefinition* definition =
static_cast<LogUpgradeDefinition*>(Registry().DefinitionForName("a-a"));
@@ -417,10 +422,10 @@ TEST_F(CustomElementRegistryTest, adoptedCallback) {
TEST_F(CustomElementRegistryTest, lookupCustomElementDefinition) {
NonThrowableExceptionState should_not_throw;
TestCustomElementDefinitionBuilder builder;
- CustomElementDefinition* definition_a =
- Define("a-a", builder, ElementDefinitionOptions(), should_not_throw);
- ElementDefinitionOptions options;
- options.setExtends("div");
+ CustomElementDefinition* definition_a = Define(
+ "a-a", builder, ElementDefinitionOptions::Create(), should_not_throw);
+ ElementDefinitionOptions* options = ElementDefinitionOptions::Create();
+ options->setExtends("div");
CustomElementDefinition* definition_b =
Define("b-b", builder, options, should_not_throw);
// look up defined autonomous custom element
@@ -451,8 +456,8 @@ TEST_F(CustomElementRegistryTest, DefineEmbedderCustomElements) {
NonThrowableExceptionState should_not_throw;
TestCustomElementDefinitionBuilder builder;
CustomElementDefinition* definition_embedder =
- Define("embeddercustomelement", builder, ElementDefinitionOptions(),
- should_not_throw);
+ Define("embeddercustomelement", builder,
+ ElementDefinitionOptions::Create(), should_not_throw);
CustomElementDefinition* definition =
Registry().DefinitionFor(CustomElementDescriptor(
"embeddercustomelement", "embeddercustomelement"));
@@ -473,8 +478,8 @@ TEST_F(CustomElementRegistryTest, DisallowedEmbedderCustomElements) {
TestCustomElementDefinitionBuilder builder;
CustomElementDefinition* definition_embedder =
- Define("embeddercustomelement", builder, ElementDefinitionOptions(),
- IGNORE_EXCEPTION_FOR_TESTING);
+ Define("embeddercustomelement", builder,
+ ElementDefinitionOptions::Create(), IGNORE_EXCEPTION_FOR_TESTING);
CustomElementDefinition* definition =
Registry().DefinitionFor(CustomElementDescriptor(
"embeddercustomelement", "embeddercustomelement"));
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_test.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_test.cc
index 97f0af76e0b..349c7931623 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_test.cc
@@ -199,12 +199,12 @@ TEST(CustomElementTest, StateByCreateElement) {
EXPECT_EQ(data.state, element->GetCustomElementState()) << data.name;
EXPECT_EQ(data.v0state, element->GetV0CustomElementState()) << data.name;
- element = document.createElementNS(HTMLNames::xhtmlNamespaceURI, data.name,
+ element = document.createElementNS(html_names::xhtmlNamespaceURI, data.name,
ASSERT_NO_EXCEPTION);
EXPECT_EQ(data.state, element->GetCustomElementState()) << data.name;
EXPECT_EQ(data.v0state, element->GetV0CustomElementState()) << data.name;
- element = document.createElementNS(SVGNames::svgNamespaceURI, data.name,
+ element = document.createElementNS(svg_names::kNamespaceURI, data.name,
ASSERT_NO_EXCEPTION);
EXPECT_EQ(CustomElementState::kUncustomized,
element->GetCustomElementState())
@@ -225,7 +225,8 @@ TEST(CustomElementTest,
CEReactionsScope reactions;
TestCustomElementDefinitionBuilder builder;
registry->DefineInternal(script_state, "a-a", builder,
- ElementDefinitionOptions(), should_not_throw);
+ ElementDefinitionOptions::Create(),
+ should_not_throw);
}
CustomElementDefinition* definition =
registry->DefinitionFor(CustomElementDescriptor("a-a", "a-a"));
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.cc
index 37ee736cf49..87b6f04aa50 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.cc
@@ -9,7 +9,7 @@ namespace blink {
CustomElementDefinition* TestCustomElementDefinitionBuilder::Build(
const CustomElementDescriptor& descriptor,
CustomElementDefinition::Id) {
- return new TestCustomElementDefinition(descriptor);
+ return MakeGarbageCollected<TestCustomElementDefinition>(descriptor);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.h
index 97d6c590de2..9f6b8183ad8 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.h
@@ -49,9 +49,12 @@ class TestCustomElementDefinition : public CustomElementDefinition {
: CustomElementDefinition(descriptor) {}
TestCustomElementDefinition(const CustomElementDescriptor& descriptor,
- HashSet<AtomicString>&& observed_attributes)
+ HashSet<AtomicString>&& observed_attributes,
+ const Vector<String>& disabled_features)
: CustomElementDefinition(descriptor,
- std::move(observed_attributes)) {}
+ std::move(observed_attributes),
+ disabled_features,
+ FormAssociationFlag::kNo) {}
~TestCustomElementDefinition() override = default;
@@ -74,6 +77,8 @@ class TestCustomElementDefinition : public CustomElementDefinition {
bool HasConnectedCallback() const override { return false; }
bool HasDisconnectedCallback() const override { return false; }
bool HasAdoptedCallback() const override { return false; }
+ bool HasFormAssociatedCallback() const override { return false; }
+ bool HasDisabledStateChangedCallback() const override { return false; }
void RunConnectedCallback(Element*) override {
NOTREACHED() << "definition does not have connected callback";
@@ -95,6 +100,14 @@ class TestCustomElementDefinition : public CustomElementDefinition {
const AtomicString& new_value) override {
NOTREACHED() << "definition does not have attribute changed callback";
}
+ void RunFormAssociatedCallback(Element* element,
+ HTMLFormElement* nullable_form) override {
+ NOTREACHED() << "definition does not have formAssociatedCallback";
+ }
+ void RunDisabledStateChangedCallback(Element* element,
+ bool is_disabled) override {
+ NOTREACHED() << "definition does not have disabledStateChangedCallback";
+ }
DISALLOW_COPY_AND_ASSIGN(TestCustomElementDefinition);
};
@@ -104,7 +117,8 @@ class CreateElement {
public:
CreateElement(const AtomicString& local_name)
- : namespace_uri_(HTMLNames::xhtmlNamespaceURI), local_name_(local_name) {}
+ : namespace_uri_(html_names::xhtmlNamespaceURI),
+ local_name_(local_name) {}
CreateElement& InDocument(Document* document) {
document_ = document;
@@ -117,7 +131,7 @@ class CreateElement {
}
CreateElement& WithId(const AtomicString& id) {
- attributes_.push_back(std::make_pair(HTMLNames::idAttr, id));
+ attributes_.push_back(std::make_pair(html_names::kIdAttr, id));
return *this;
}
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.cc
index 8c2d88e956a..0e045400c20 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.cc
@@ -15,8 +15,8 @@
namespace blink {
CustomElementUpgradeSorter::CustomElementUpgradeSorter()
- : elements_(new HeapHashSet<Member<Element>>()),
- parent_child_map_(new ParentChildMap()) {}
+ : elements_(MakeGarbageCollected<HeapHashSet<Member<Element>>>()),
+ parent_child_map_(MakeGarbageCollected<ParentChildMap>()) {}
static HTMLLinkElement* GetLinkElementForImport(const Document& import) {
if (HTMLImportLoader* loader = import.ImportLoader())
@@ -33,7 +33,7 @@ CustomElementUpgradeSorter::AddToParentChildMap(Node* parent, Node* child) {
return kParentAlreadyExistsInMap;
}
- ChildSet* child_set = new ChildSet();
+ ChildSet* child_set = MakeGarbageCollected<ChildSet>();
child_set->insert(child);
result.stored_value->value = child_set;
return kParentAddedToMap;
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter_test.cc b/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter_test.cc
index 431aa916d10..93808872260 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter_test.cc
@@ -6,7 +6,7 @@
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/bindings/core/v8/string_or_dictionary.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_element_creation_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -28,8 +28,8 @@ class CustomElementUpgradeSorterTest : public PageTestBase {
Element* CreateElementWithId(const char* local_name, const char* id) {
NonThrowableExceptionState no_exceptions;
Element* element = GetDocument().CreateElementForBinding(
- local_name, StringOrDictionary(), no_exceptions);
- element->setAttribute(HTMLNames::idAttr, id);
+ local_name, StringOrElementCreationOptions(), no_exceptions);
+ element->setAttribute(html_names::kIdAttr, id);
return element;
}
@@ -41,7 +41,7 @@ class CustomElementUpgradeSorterTest : public PageTestBase {
TEST_F(CustomElementUpgradeSorterTest, inOtherDocument_notInSet) {
NonThrowableExceptionState no_exceptions;
Element* element = GetDocument().CreateElementForBinding(
- "a-a", StringOrDictionary(), no_exceptions);
+ "a-a", StringOrElementCreationOptions(), no_exceptions);
Document* other_document = HTMLDocument::CreateForTest();
other_document->AppendChild(element);
@@ -60,7 +60,7 @@ TEST_F(CustomElementUpgradeSorterTest, inOtherDocument_notInSet) {
TEST_F(CustomElementUpgradeSorterTest, oneCandidate) {
NonThrowableExceptionState no_exceptions;
Element* element = GetDocument().CreateElementForBinding(
- "a-a", StringOrDictionary(), no_exceptions);
+ "a-a", StringOrElementCreationOptions(), no_exceptions);
GetDocument().documentElement()->AppendChild(element);
CustomElementUpgradeSorter sorter;
diff --git a/chromium/third_party/blink/renderer/core/html/custom/element_internals.cc b/chromium/third_party/blink/renderer/core/html/custom/element_internals.cc
new file mode 100644
index 00000000000..3d14c75c849
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/custom/element_internals.cc
@@ -0,0 +1,117 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/html/custom/element_internals.h"
+
+#include "third_party/blink/renderer/core/dom/node_lists_node_data.h"
+#include "third_party/blink/renderer/core/fileapi/file.h"
+#include "third_party/blink/renderer/core/html/custom/custom_element.h"
+#include "third_party/blink/renderer/core/html/forms/form_data.h"
+#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
+#include "third_party/blink/renderer/core/html/html_element.h"
+
+namespace blink {
+
+ElementInternals::ElementInternals(HTMLElement& target) : target_(target) {
+ value_.SetUSVString(String());
+}
+
+void ElementInternals::Trace(Visitor* visitor) {
+ visitor->Trace(target_);
+ visitor->Trace(value_);
+ visitor->Trace(entry_source_);
+ ListedElement::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+}
+
+void ElementInternals::setFormValue(const FileOrUSVString& value,
+ ExceptionState& exception_state) {
+ setFormValue(value, nullptr, exception_state);
+}
+
+void ElementInternals::setFormValue(const FileOrUSVString& value,
+ FormData* entry_source,
+ ExceptionState& exception_state) {
+ if (!Target().IsFormAssociatedCustomElement()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The target element is not a form-associated custom element.");
+ return;
+ }
+ if (!entry_source || entry_source->size() == 0u) {
+ value_ = value;
+ entry_source_ = nullptr;
+ return;
+ }
+ value_ = value;
+ entry_source_ = MakeGarbageCollected<FormData>(*entry_source);
+}
+
+HTMLFormElement* ElementInternals::form(ExceptionState& exception_state) const {
+ if (!Target().IsFormAssociatedCustomElement()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The target element is not a form-associated custom element.");
+ return nullptr;
+ }
+ return ListedElement::Form();
+}
+
+void ElementInternals::DidUpgrade() {
+ ContainerNode* parent = Target().parentNode();
+ if (!parent)
+ return;
+ InsertedInto(*parent);
+ if (auto* owner_form = Form()) {
+ if (auto* lists = owner_form->NodeLists())
+ lists->InvalidateCaches(nullptr);
+ }
+ for (ContainerNode* node = parent; node; node = node->parentNode()) {
+ if (IsHTMLFieldSetElement(node)) {
+ // TODO(tkent): Invalidate only HTMLFormControlsCollections.
+ if (auto* lists = node->NodeLists())
+ lists->InvalidateCaches(nullptr);
+ }
+ }
+}
+
+bool ElementInternals::IsFormControlElement() const {
+ return false;
+}
+
+bool ElementInternals::IsElementInternals() const {
+ return true;
+}
+
+bool ElementInternals::IsEnumeratable() const {
+ return true;
+}
+
+void ElementInternals::AppendToFormData(FormData& form_data) {
+ const AtomicString& name = Target().FastGetAttribute(html_names::kNameAttr);
+ if (!entry_source_ || entry_source_->size() == 0u) {
+ if (name.IsNull())
+ return;
+ if (value_.IsFile())
+ form_data.AppendFromElement(name, value_.GetAsFile());
+ else if (value_.IsUSVString())
+ form_data.AppendFromElement(name, value_.GetAsUSVString());
+ else
+ form_data.AppendFromElement(name, g_empty_string);
+ return;
+ }
+ for (const auto& entry : entry_source_->Entries()) {
+ if (entry->isFile())
+ form_data.append(entry->name(), entry->GetFile());
+ else
+ form_data.append(entry->name(), entry->Value());
+ }
+}
+
+void ElementInternals::DidChangeForm() {
+ ListedElement::DidChangeForm();
+ CustomElement::EnqueueFormAssociatedCallback(Target(), Form());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/custom/element_internals.h b/chromium/third_party/blink/renderer/core/html/custom/element_internals.h
new file mode 100644
index 00000000000..d32036402cd
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/custom/element_internals.h
@@ -0,0 +1,60 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_ELEMENT_INTERNALS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_ELEMENT_INTERNALS_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/file_or_usv_string.h"
+#include "third_party/blink/renderer/core/html/forms/listed_element.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
+
+namespace blink {
+
+class HTMLElement;
+
+class ElementInternals : public ScriptWrappable, public ListedElement {
+ DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(ElementInternals);
+
+ public:
+ ElementInternals(HTMLElement& target);
+ void Trace(Visitor* visitor) override;
+
+ HTMLElement& Target() const { return *target_; }
+ void DidUpgrade();
+
+ // IDL attributes/operations
+ void setFormValue(const FileOrUSVString& value,
+ ExceptionState& exception_state);
+ void setFormValue(const FileOrUSVString& value,
+ FormData* entry_source,
+ ExceptionState& exception_state);
+ HTMLFormElement* form(ExceptionState& exception_state) const;
+
+ private:
+ // ListedElement overrides:
+ bool IsFormControlElement() const override;
+ bool IsElementInternals() const override;
+ bool IsEnumeratable() const override;
+ void AppendToFormData(FormData& form_data) override;
+ void DidChangeForm() override;
+
+ Member<HTMLElement> target_;
+
+ FileOrUSVString value_;
+ Member<FormData> entry_source_;
+
+ DISALLOW_COPY_AND_ASSIGN(ElementInternals);
+};
+
+template <>
+struct DowncastTraits<ElementInternals> {
+ static bool AllowFrom(const ListedElement& listed_element) {
+ return listed_element.IsElementInternals();
+ }
+};
+
+} // namespace blink
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_ELEMENT_INTERNALS_H_
diff --git a/chromium/third_party/blink/renderer/core/html/custom/element_internals.idl b/chromium/third_party/blink/renderer/core/html/custom/element_internals.idl
new file mode 100644
index 00000000000..c918fba298d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/custom/element_internals.idl
@@ -0,0 +1,16 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://docs.google.com/document/d/1JO8puctCSpW-ZYGU8lF-h4FWRIDQNDVexzHoOQ2iQmY/edit?pli=1#heading=h.pjt9nhs3gu3k
+
+[
+ Exposed=Window,
+ RuntimeEnabled=ElementInternals
+]
+interface ElementInternals {
+ // Attributes and operations for form-associated custom elements.
+ [RaisesException] void setFormValue(FormDataEntryValue value, optional FormData entrySource);
+ [RaisesException] readonly attribute HTMLFormElement? form;
+};
+
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.cc
index 4901ae8926c..4e10b8db5ee 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.cc
@@ -73,7 +73,7 @@ bool V0CustomElement::IsValidName(const AtomicString& name) {
DEFINE_STATIC_LOCAL(Vector<AtomicString>, reserved_names, ());
if (reserved_names.IsEmpty()) {
// FIXME(crbug.com/426605): We should be able to remove this.
- reserved_names.push_back(MathMLNames::annotation_xmlTag.LocalName());
+ reserved_names.push_back(mathml_names::kAnnotationXmlTag.LocalName());
}
if (kNotFound == reserved_names.Find(name))
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_async_import_microtask_queue.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_async_import_microtask_queue.h
index f3476bc2e81..331eb3fd049 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_async_import_microtask_queue.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_async_import_microtask_queue.h
@@ -39,13 +39,14 @@ class V0CustomElementAsyncImportMicrotaskQueue
: public V0CustomElementMicrotaskQueueBase {
public:
static V0CustomElementAsyncImportMicrotaskQueue* Create() {
- return new V0CustomElementAsyncImportMicrotaskQueue();
+ return MakeGarbageCollected<V0CustomElementAsyncImportMicrotaskQueue>();
}
+ V0CustomElementAsyncImportMicrotaskQueue() = default;
+
void Enqueue(V0CustomElementMicrotaskStep*);
private:
- V0CustomElementAsyncImportMicrotaskQueue() = default;
void DoDispatch() override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.cc
index f7a744a580b..c4de24bce0c 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.cc
@@ -36,7 +36,7 @@ namespace blink {
V0CustomElementCallbackQueue* V0CustomElementCallbackQueue::Create(
Element* element) {
- return new V0CustomElementCallbackQueue(element);
+ return MakeGarbageCollected<V0CustomElementCallbackQueue>(element);
}
V0CustomElementCallbackQueue::V0CustomElementCallbackQueue(Element* element)
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.h
index 370954e4724..529e1c09d91 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_callback_queue.h
@@ -46,6 +46,8 @@ class V0CustomElementCallbackQueue
public:
static V0CustomElementCallbackQueue* Create(Element*);
+ explicit V0CustomElementCallbackQueue(Element*);
+
typedef int ElementQueueId;
ElementQueueId Owner() const { return owner_; }
@@ -66,8 +68,6 @@ class V0CustomElementCallbackQueue
void Trace(blink::Visitor*);
private:
- explicit V0CustomElementCallbackQueue(Element*);
-
Member<Element> element_;
HeapVector<Member<V0CustomElementProcessingStep>> queue_;
ElementQueueId owner_;
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.cc
index 3ac97190502..d7f446b42f0 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.cc
@@ -35,7 +35,7 @@ namespace blink {
V0CustomElementDefinition* V0CustomElementDefinition::Create(
const V0CustomElementDescriptor& descriptor,
V0CustomElementLifecycleCallbacks* callbacks) {
- return new V0CustomElementDefinition(descriptor, callbacks);
+ return MakeGarbageCollected<V0CustomElementDefinition>(descriptor, callbacks);
}
V0CustomElementDefinition::V0CustomElementDefinition(
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.h
index f1ece759b56..6b5806d85a3 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_definition.h
@@ -42,6 +42,9 @@ class V0CustomElementDefinition final
static V0CustomElementDefinition* Create(const V0CustomElementDescriptor&,
V0CustomElementLifecycleCallbacks*);
+ V0CustomElementDefinition(const V0CustomElementDescriptor&,
+ V0CustomElementLifecycleCallbacks*);
+
const V0CustomElementDescriptor& Descriptor() const { return descriptor_; }
V0CustomElementLifecycleCallbacks* Callbacks() const {
return callbacks_.Get();
@@ -50,9 +53,6 @@ class V0CustomElementDefinition final
void Trace(blink::Visitor*);
private:
- V0CustomElementDefinition(const V0CustomElementDescriptor&,
- V0CustomElementLifecycleCallbacks*);
-
V0CustomElementDescriptor descriptor_;
Member<V0CustomElementLifecycleCallbacks> callbacks_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.h
index 3888a2f5e2c..eb152f5d3a6 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.h
@@ -49,9 +49,10 @@ class V0CustomElementMicrotaskImportStep final
: public V0CustomElementMicrotaskStep {
public:
static V0CustomElementMicrotaskImportStep* Create(HTMLImportChild* import) {
- return new V0CustomElementMicrotaskImportStep(import);
+ return MakeGarbageCollected<V0CustomElementMicrotaskImportStep>(import);
}
+ explicit V0CustomElementMicrotaskImportStep(HTMLImportChild*);
~V0CustomElementMicrotaskImportStep() override;
// API for HTML Imports
@@ -61,8 +62,6 @@ class V0CustomElementMicrotaskImportStep final
void Trace(blink::Visitor*) override;
private:
- explicit V0CustomElementMicrotaskImportStep(HTMLImportChild*);
-
void DidUpgradeAllCustomElements();
bool ShouldWaitForImport() const;
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.cc
index 5a0224dea7d..eed62964c73 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.cc
@@ -40,8 +40,8 @@ V0CustomElementMicrotaskResolutionStep::Create(
V0CustomElementRegistrationContext* context,
Element* element,
const V0CustomElementDescriptor& descriptor) {
- return new V0CustomElementMicrotaskResolutionStep(context, element,
- descriptor);
+ return MakeGarbageCollected<V0CustomElementMicrotaskResolutionStep>(
+ context, element, descriptor);
}
V0CustomElementMicrotaskResolutionStep::V0CustomElementMicrotaskResolutionStep(
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.h
index 000de7da616..83bb565de1d 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_resolution_step.h
@@ -48,15 +48,14 @@ class V0CustomElementMicrotaskResolutionStep final
Element*,
const V0CustomElementDescriptor&);
+ V0CustomElementMicrotaskResolutionStep(V0CustomElementRegistrationContext*,
+ Element*,
+ const V0CustomElementDescriptor&);
~V0CustomElementMicrotaskResolutionStep() override;
void Trace(blink::Visitor*) override;
private:
- V0CustomElementMicrotaskResolutionStep(V0CustomElementRegistrationContext*,
- Element*,
- const V0CustomElementDescriptor&);
-
Result Process() override;
#if !defined(NDEBUG)
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_run_queue.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_run_queue.h
index 92c4c36273d..9ac97493dd2 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_run_queue.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_run_queue.h
@@ -18,9 +18,11 @@ class V0CustomElementMicrotaskRunQueue
: public GarbageCollected<V0CustomElementMicrotaskRunQueue> {
public:
static V0CustomElementMicrotaskRunQueue* Create() {
- return new V0CustomElementMicrotaskRunQueue;
+ return MakeGarbageCollected<V0CustomElementMicrotaskRunQueue>();
}
+ V0CustomElementMicrotaskRunQueue();
+
void Enqueue(HTMLImportLoader* parent_loader,
V0CustomElementMicrotaskStep*,
bool import_is_sync);
@@ -30,8 +32,6 @@ class V0CustomElementMicrotaskRunQueue
void Trace(blink::Visitor*);
private:
- V0CustomElementMicrotaskRunQueue();
-
void Dispatch();
Member<V0CustomElementSyncMicrotaskQueue> sync_queue_;
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_observer.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_observer.cc
index 637440bde08..a450e7667cf 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_observer.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_observer.cc
@@ -42,7 +42,7 @@ typedef HeapHashMap<WeakMember<Element>, Member<V0CustomElementObserver>>
static ElementObserverMap& ElementObservers() {
DEFINE_STATIC_LOCAL(Persistent<ElementObserverMap>, map,
- (new ElementObserverMap));
+ (MakeGarbageCollected<ElementObserverMap>()));
return *map;
}
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.cc
index 9fa081ea367..73ad40a0bec 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.cc
@@ -76,9 +76,9 @@ Element* V0CustomElementRegistrationContext::CreateCustomTagElement(
Element* element;
- if (HTMLNames::xhtmlNamespaceURI == tag_name.NamespaceURI()) {
+ if (html_names::xhtmlNamespaceURI == tag_name.NamespaceURI()) {
element = HTMLElement::Create(tag_name, document);
- } else if (SVGNames::svgNamespaceURI == tag_name.NamespaceURI()) {
+ } else if (svg_names::kNamespaceURI == tag_name.NamespaceURI()) {
element = SVGUnknownElement::Create(tag_name, document);
} else {
// XML elements are not custom elements, so return early.
@@ -132,7 +132,7 @@ void V0CustomElementRegistrationContext::SetIsAttributeAndTypeExtension(
const AtomicString& type) {
DCHECK(element);
DCHECK(!type.IsEmpty());
- element->setAttribute(HTMLNames::isAttr, type);
+ element->setAttribute(html_names::kIsAttr, type);
SetTypeExtension(element, type);
}
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h
index 52f2b66497f..fbdc75506d9 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h
@@ -46,9 +46,10 @@ class V0CustomElementRegistrationContext final
: public GarbageCollectedFinalized<V0CustomElementRegistrationContext> {
public:
static V0CustomElementRegistrationContext* Create() {
- return new V0CustomElementRegistrationContext();
+ return MakeGarbageCollected<V0CustomElementRegistrationContext>();
}
+ V0CustomElementRegistrationContext();
~V0CustomElementRegistrationContext() = default;
void DocumentWasDetached() { registry_.DocumentWasDetached(); }
@@ -70,9 +71,6 @@ class V0CustomElementRegistrationContext final
void Trace(blink::Visitor*);
- protected:
- V0CustomElementRegistrationContext();
-
// Instance creation
void DidGiveTypeExtension(Element*, const AtomicString& type);
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registry.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registry.cc
index 40de265ccfd..eccbfad76d2 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registry.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registry.cc
@@ -73,8 +73,8 @@ V0CustomElementDefinition* V0CustomElementRegistry::RegisterElement(
if (!constructor_builder->ValidateOptions(type, tag_name, exception_state))
return nullptr;
- DCHECK(tag_name.NamespaceURI() == HTMLNames::xhtmlNamespaceURI ||
- tag_name.NamespaceURI() == SVGNames::svgNamespaceURI);
+ DCHECK(tag_name.NamespaceURI() == html_names::xhtmlNamespaceURI ||
+ tag_name.NamespaceURI() == svg_names::kNamespaceURI);
DCHECK(!document_was_detached_);
@@ -109,7 +109,7 @@ V0CustomElementDefinition* V0CustomElementRegistry::RegisterElement(
return nullptr;
}
- if (tag_name.NamespaceURI() == SVGNames::svgNamespaceURI) {
+ if (tag_name.NamespaceURI() == svg_names::kNamespaceURI) {
UseCounter::Count(document,
WebFeature::kV0CustomElementsRegisterSVGElement);
} else {
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_scheduler.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_scheduler.cc
index 42c3237e97c..7a8ba361b0c 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_scheduler.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_scheduler.cc
@@ -52,7 +52,7 @@ typedef HeapHashMap<Member<Element>, Member<V0CustomElementCallbackQueue>>
static ElementCallbackQueueMap& CallbackQueues() {
DEFINE_STATIC_LOCAL(Persistent<ElementCallbackQueueMap>, map,
- (new ElementCallbackQueueMap));
+ (MakeGarbageCollected<ElementCallbackQueueMap>()));
return *map;
}
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_sync_microtask_queue.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_sync_microtask_queue.h
index 0385acf794c..ecc502b9ce0 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_sync_microtask_queue.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_sync_microtask_queue.h
@@ -13,13 +13,14 @@ class V0CustomElementSyncMicrotaskQueue
: public V0CustomElementMicrotaskQueueBase {
public:
static V0CustomElementSyncMicrotaskQueue* Create() {
- return new V0CustomElementSyncMicrotaskQueue();
+ return MakeGarbageCollected<V0CustomElementSyncMicrotaskQueue>();
}
+ V0CustomElementSyncMicrotaskQueue() = default;
+
void Enqueue(V0CustomElementMicrotaskStep*);
private:
- V0CustomElementSyncMicrotaskQueue() = default;
void DoDispatch() override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.cc
index 72e0c7757ed..a74a1b2ae3d 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.cc
@@ -36,7 +36,7 @@ namespace blink {
V0CustomElementUpgradeCandidateMap*
V0CustomElementUpgradeCandidateMap::Create() {
- return new V0CustomElementUpgradeCandidateMap();
+ return MakeGarbageCollected<V0CustomElementUpgradeCandidateMap>();
}
V0CustomElementUpgradeCandidateMap::~V0CustomElementUpgradeCandidateMap() =
@@ -55,7 +55,8 @@ void V0CustomElementUpgradeCandidateMap::Add(
unresolved_definitions_.find(descriptor);
ElementSet* elements;
if (it == unresolved_definitions_.end())
- elements = unresolved_definitions_.insert(descriptor, new ElementSet())
+ elements = unresolved_definitions_
+ .insert(descriptor, MakeGarbageCollected<ElementSet>())
.stored_value->value.Get();
else
elements = it->value.Get();
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.h
index df4169720f4..de500414000 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_upgrade_candidate_map.h
@@ -44,6 +44,8 @@ class V0CustomElementUpgradeCandidateMap final
: public V0CustomElementObserver {
public:
static V0CustomElementUpgradeCandidateMap* Create();
+
+ V0CustomElementUpgradeCandidateMap() = default;
~V0CustomElementUpgradeCandidateMap() override;
// API for V0CustomElementRegistrationContext to save and take candidates
@@ -56,8 +58,6 @@ class V0CustomElementUpgradeCandidateMap final
void Trace(blink::Visitor*) override;
private:
- V0CustomElementUpgradeCandidateMap() = default;
-
void ElementWasDestroyed(Element*) override;
typedef HeapHashMap<WeakMember<Element>, V0CustomElementDescriptor>
diff --git a/chromium/third_party/blink/renderer/core/html/document_all_name_collection.cc b/chromium/third_party/blink/renderer/core/html/document_all_name_collection.cc
index 133583537c5..777fd7fdfc9 100644
--- a/chromium/third_party/blink/renderer/core/html/document_all_name_collection.cc
+++ b/chromium/third_party/blink/renderer/core/html/document_all_name_collection.cc
@@ -14,20 +14,20 @@ DocumentAllNameCollection::DocumentAllNameCollection(ContainerNode& document,
bool DocumentAllNameCollection::ElementMatches(const Element& element) const {
// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#all-named-elements
// Match below type of elements by name but any type of element by id.
- if (element.HasTagName(HTMLNames::aTag) ||
- element.HasTagName(HTMLNames::buttonTag) ||
- element.HasTagName(HTMLNames::embedTag) ||
- element.HasTagName(HTMLNames::formTag) ||
- element.HasTagName(HTMLNames::frameTag) ||
- element.HasTagName(HTMLNames::framesetTag) ||
- element.HasTagName(HTMLNames::iframeTag) ||
- element.HasTagName(HTMLNames::imgTag) ||
- element.HasTagName(HTMLNames::inputTag) ||
- element.HasTagName(HTMLNames::mapTag) ||
- element.HasTagName(HTMLNames::metaTag) ||
- element.HasTagName(HTMLNames::objectTag) ||
- element.HasTagName(HTMLNames::selectTag) ||
- element.HasTagName(HTMLNames::textareaTag)) {
+ if (element.HasTagName(html_names::kATag) ||
+ element.HasTagName(html_names::kButtonTag) ||
+ element.HasTagName(html_names::kEmbedTag) ||
+ element.HasTagName(html_names::kFormTag) ||
+ element.HasTagName(html_names::kFrameTag) ||
+ element.HasTagName(html_names::kFramesetTag) ||
+ element.HasTagName(html_names::kIFrameTag) ||
+ element.HasTagName(html_names::kImgTag) ||
+ element.HasTagName(html_names::kInputTag) ||
+ element.HasTagName(html_names::kMapTag) ||
+ element.HasTagName(html_names::kMetaTag) ||
+ element.HasTagName(html_names::kObjectTag) ||
+ element.HasTagName(html_names::kSelectTag) ||
+ element.HasTagName(html_names::kTextareaTag)) {
if (element.GetNameAttribute() == name_)
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/html/document_all_name_collection.h b/chromium/third_party/blink/renderer/core/html/document_all_name_collection.h
index 5dc790a6f39..147a94ea78b 100644
--- a/chromium/third_party/blink/renderer/core/html/document_all_name_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/document_all_name_collection.h
@@ -17,13 +17,12 @@ class DocumentAllNameCollection final : public HTMLNameCollection {
CollectionType type,
const AtomicString& name) {
DCHECK_EQ(type, kDocumentAllNamedItems);
- return new DocumentAllNameCollection(document, name);
+ return MakeGarbageCollected<DocumentAllNameCollection>(document, name);
}
- bool ElementMatches(const Element&) const;
-
- private:
DocumentAllNameCollection(ContainerNode& document, const AtomicString& name);
+
+ bool ElementMatches(const Element&) const;
};
DEFINE_TYPE_CASTS(DocumentAllNameCollection,
diff --git a/chromium/third_party/blink/renderer/core/html/document_name_collection.h b/chromium/third_party/blink/renderer/core/html/document_name_collection.h
index 07229015cc1..63f1cfd039a 100644
--- a/chromium/third_party/blink/renderer/core/html/document_name_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/document_name_collection.h
@@ -16,17 +16,16 @@ class DocumentNameCollection final : public HTMLNameCollection {
CollectionType type,
const AtomicString& name) {
DCHECK_EQ(type, kDocumentNamedItems);
- return new DocumentNameCollection(document, name);
+ return MakeGarbageCollected<DocumentNameCollection>(document, name);
}
+ DocumentNameCollection(ContainerNode& document, const AtomicString& name);
+
HTMLElement* Item(unsigned offset) const {
return ToHTMLElement(HTMLNameCollection::item(offset));
}
bool ElementMatches(const HTMLElement&) const;
-
- private:
- DocumentNameCollection(ContainerNode& document, const AtomicString& name);
};
DEFINE_TYPE_CASTS(DocumentNameCollection,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/base_button_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/base_button_input_type.cc
index 83d3d68fd88..19f35f6d947 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/base_button_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/base_button_input_type.cc
@@ -41,7 +41,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
BaseButtonInputType::BaseButtonInputType(HTMLInputElement& element)
: InputType(element), KeyboardClickableInputTypeView(element) {}
@@ -89,7 +89,7 @@ void BaseButtonInputType::SetValue(const String& sanitized_value,
bool,
TextFieldEventBehavior,
TextControlSetValueSelection) {
- GetElement().setAttribute(valueAttr, AtomicString(sanitized_value));
+ GetElement().setAttribute(kValueAttr, AtomicString(sanitized_value));
}
bool BaseButtonInputType::MatchesDefaultPseudoClass() {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/base_checkable_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/base_checkable_input_type.cc
index fefc9d7011e..2df7aaf0e64 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/base_checkable_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/base_checkable_input_type.cc
@@ -40,7 +40,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
void BaseCheckableInputType::Trace(blink::Visitor* visitor) {
InputTypeView::Trace(visitor);
@@ -95,7 +95,7 @@ void BaseCheckableInputType::AccessKeyAction(bool send_mouse_events) {
}
bool BaseCheckableInputType::MatchesDefaultPseudoClass() {
- return GetElement().FastHasAttribute(checkedAttr);
+ return GetElement().FastHasAttribute(kCheckedAttr);
}
InputType::ValueMode BaseCheckableInputType::GetValueMode() const {
@@ -106,7 +106,7 @@ void BaseCheckableInputType::SetValue(const String& sanitized_value,
bool,
TextFieldEventBehavior,
TextControlSetValueSelection) {
- GetElement().setAttribute(valueAttr, AtomicString(sanitized_value));
+ GetElement().setAttribute(kValueAttr, AtomicString(sanitized_value));
}
void BaseCheckableInputType::ReadingChecked() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.cc
index 7cf6b0fb383..d0d21beffeb 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.cc
@@ -43,7 +43,6 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
static const int kMsecPerMinute = 60 * 1000;
static const int kMsecPerSecond = 1000;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/base_text_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/base_text_input_type.cc
index 5f167ebf233..e41899590f9 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/base_text_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/base_text_input_type.cc
@@ -31,7 +31,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
BaseTextInputType::BaseTextInputType(HTMLInputElement& element)
: TextFieldInputType(element) {}
@@ -79,7 +79,7 @@ bool BaseTextInputType::TooShort(
}
bool BaseTextInputType::PatternMismatch(const String& value) const {
- const AtomicString& raw_pattern = GetElement().FastGetAttribute(patternAttr);
+ const AtomicString& raw_pattern = GetElement().FastGetAttribute(kPatternAttr);
// Empty values can't be mismatched
if (raw_pattern.IsNull() || value.IsEmpty())
return false;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/button_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/button_input_type.cc
index 7c58447907d..f9a3738deca 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/button_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/button_input_type.cc
@@ -39,7 +39,7 @@ InputType* ButtonInputType::Create(HTMLInputElement& element) {
}
const AtomicString& ButtonInputType::FormControlType() const {
- return InputTypeNames::button;
+ return input_type_names::kButton;
}
bool ButtonInputType::SupportsValidation() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/checkbox_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/checkbox_input_type.cc
index 3ef8609c637..26a4522ffb1 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/checkbox_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/checkbox_input_type.cc
@@ -43,7 +43,7 @@ InputType* CheckboxInputType::Create(HTMLInputElement& element) {
}
const AtomicString& CheckboxInputType::FormControlType() const {
- return InputTypeNames::checkbox;
+ return input_type_names::kCheckbox;
}
bool CheckboxInputType::ValueMissing(const String&) const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.cc b/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.cc
index 6321006801d..2efb31cf015 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.cc
@@ -33,7 +33,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline ClearButtonElement::ClearButtonElement(
Document& document,
@@ -46,7 +46,7 @@ ClearButtonElement* ClearButtonElement::Create(
ClearButtonElement* element =
new ClearButtonElement(document, clear_button_owner);
element->SetShadowPseudoId(AtomicString("-webkit-clear-button"));
- element->setAttribute(idAttr, ShadowElementNames::ClearButton());
+ element->setAttribute(kIdAttr, shadow_element_names::ClearButton());
return element;
}
@@ -67,7 +67,7 @@ void ClearButtonElement::DefaultEventHandler(Event& event) {
return;
}
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
if (GetLayoutObject() && GetLayoutObject()->VisibleToHitTesting()) {
clear_button_owner_->FocusAndSelectClearButtonOwner();
clear_button_owner_->ClearValue();
diff --git a/chromium/third_party/blink/renderer/core/html/forms/color_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/color_input_type.cc
index 020384bcd09..88a556cfd6a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/color_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/color_input_type.cc
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/core/html/forms/color_input_type.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
@@ -53,7 +53,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// Upper limit of number of datalist suggestions shown.
static const unsigned kMaxSuggestions = 1000;
@@ -102,7 +102,7 @@ void ColorInputType::CountUsage() {
}
const AtomicString& ColorInputType::FormControlType() const {
- return InputTypeNames::color;
+ return input_type_names::kColor;
}
bool ColorInputType::SupportsRequired() const {
@@ -243,7 +243,7 @@ Color ColorInputType::CurrentColor() {
}
bool ColorInputType::ShouldShowSuggestions() const {
- return GetElement().FastHasAttribute(listAttr);
+ return GetElement().FastHasAttribute(kListAttr);
}
Vector<mojom::blink::ColorSuggestionPtr> ColorInputType::Suggestions() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/date_input_type.cc
index 36be3e524ae..0bd61edbe89 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_input_type.cc
@@ -42,7 +42,7 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
+using namespace html_names;
static const int kDateDefaultStep = 1;
static const int kDateDefaultStepBase = 0;
@@ -52,7 +52,7 @@ inline DateInputType::DateInputType(HTMLInputElement& element)
: BaseTemporalInputType(element) {}
InputType* DateInputType::Create(HTMLInputElement& element) {
- return new DateInputType(element);
+ return MakeGarbageCollected<DateInputType>(element);
}
void DateInputType::CountUsage() {
@@ -60,7 +60,7 @@ void DateInputType::CountUsage() {
}
const AtomicString& DateInputType::FormControlType() const {
- return InputTypeNames::date;
+ return input_type_names::kDate;
}
StepRange DateInputType::CreateStepRange(
@@ -113,10 +113,10 @@ void DateInputType::SetupLayoutParameters(
const DateComponents& date) const {
layout_parameters.date_time_format = layout_parameters.locale.DateFormat();
layout_parameters.fallback_date_time_format = "yyyy-MM-dd";
- if (!ParseToDateComponents(GetElement().FastGetAttribute(minAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMinAttr),
&layout_parameters.minimum))
layout_parameters.minimum = DateComponents();
- if (!ParseToDateComponents(GetElement().FastGetAttribute(maxAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMaxAttr),
&layout_parameters.maximum))
layout_parameters.maximum = DateComponents();
layout_parameters.placeholder_for_day = GetLocale().QueryString(
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/date_input_type.h
index cbae403e3b4..b5a8e7ebbf2 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_input_type.h
@@ -39,9 +39,9 @@ class DateInputType final : public BaseTemporalInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
explicit DateInputType(HTMLInputElement&);
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
StepRange CreateStepRange(AnyStepHandling) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc
index d4127eaea68..b378ec7e84a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc
@@ -62,7 +62,8 @@ DateTimeChooserImpl* DateTimeChooserImpl::Create(
ChromeClient* chrome_client,
DateTimeChooserClient* client,
const DateTimeChooserParameters& parameters) {
- return new DateTimeChooserImpl(chrome_client, client, parameters);
+ return MakeGarbageCollected<DateTimeChooserImpl>(chrome_client, client,
+ parameters);
}
DateTimeChooserImpl::~DateTimeChooserImpl() = default;
@@ -85,15 +86,15 @@ AXObject* DateTimeChooserImpl::RootAXObject() {
static String ValueToDateTimeString(double value, AtomicString type) {
DateComponents components;
- if (type == InputTypeNames::date)
+ if (type == input_type_names::kDate)
components.SetMillisecondsSinceEpochForDate(value);
- else if (type == InputTypeNames::datetime_local)
+ else if (type == input_type_names::kDatetimeLocal)
components.SetMillisecondsSinceEpochForDateTimeLocal(value);
- else if (type == InputTypeNames::month)
+ else if (type == input_type_names::kMonth)
components.SetMonthsSinceEpoch(value);
- else if (type == InputTypeNames::time)
+ else if (type == input_type_names::kTime)
components.SetMillisecondsSinceMidnight(value);
- else if (type == InputTypeNames::week)
+ else if (type == input_type_names::kWeek)
components.SetMillisecondsSinceEpochForWeek(value);
else
NOTREACHED();
@@ -107,12 +108,12 @@ void DateTimeChooserImpl::WriteDocument(SharedBuffer* data) {
String step_base_string = String::Number(parameters_.step_base, 11);
String today_label_string;
String other_date_label_string;
- if (parameters_.type == InputTypeNames::month) {
+ if (parameters_.type == input_type_names::kMonth) {
today_label_string =
GetLocale().QueryString(WebLocalizedString::kThisMonthButtonLabel);
other_date_label_string =
GetLocale().QueryString(WebLocalizedString::kOtherMonthLabel);
- } else if (parameters_.type == InputTypeNames::week) {
+ } else if (parameters_.type == input_type_names::kWeek) {
today_label_string =
GetLocale().QueryString(WebLocalizedString::kThisWeekButtonLabel);
other_date_label_string =
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h
index 92cae9e460f..e896239a7a4 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.h
@@ -48,6 +48,10 @@ class CORE_EXPORT DateTimeChooserImpl final : public DateTimeChooser,
static DateTimeChooserImpl* Create(ChromeClient*,
DateTimeChooserClient*,
const DateTimeChooserParameters&);
+
+ DateTimeChooserImpl(ChromeClient*,
+ DateTimeChooserClient*,
+ const DateTimeChooserParameters&);
~DateTimeChooserImpl() override;
// DateTimeChooser functions:
@@ -57,9 +61,6 @@ class CORE_EXPORT DateTimeChooserImpl final : public DateTimeChooser,
void Trace(blink::Visitor*) override;
private:
- DateTimeChooserImpl(ChromeClient*,
- DateTimeChooserClient*,
- const DateTimeChooserParameters&);
// PagePopupClient functions:
void WriteDocument(SharedBuffer*) override;
void SelectFontsFromOwnerDocument(Document&) override {}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.cc
index 5289eb4fb15..3fc5fed2a27 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.cc
@@ -42,7 +42,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class DateTimeEditBuilder : private DateTimeFormat::TokenHandler {
public:
@@ -467,10 +467,10 @@ void DateTimeEditBuilder::VisitLiteral(const String& text) {
HTMLDivElement* element = HTMLDivElement::Create(EditElement().GetDocument());
element->SetShadowPseudoId(text_pseudo_id);
if (parameters_.locale.IsRTL() && text.length()) {
- WTF::Unicode::CharDirection dir = WTF::Unicode::Direction(text[0]);
- if (dir == WTF::Unicode::kSegmentSeparator ||
- dir == WTF::Unicode::kWhiteSpaceNeutral ||
- dir == WTF::Unicode::kOtherNeutral)
+ WTF::unicode::CharDirection dir = WTF::unicode::Direction(text[0]);
+ if (dir == WTF::unicode::kSegmentSeparator ||
+ dir == WTF::unicode::kWhiteSpaceNeutral ||
+ dir == WTF::unicode::kOtherNeutral)
element->AppendChild(Text::Create(EditElement().GetDocument(),
String(&kRightToLeftMarkCharacter, 1)));
}
@@ -557,9 +557,9 @@ DateTimeEditElement* DateTimeEditElement::Create(
Document& document,
EditControlOwner& edit_control_owner) {
DateTimeEditElement* container =
- new DateTimeEditElement(document, edit_control_owner);
+ MakeGarbageCollected<DateTimeEditElement>(document, edit_control_owner);
container->SetShadowPseudoId(AtomicString("-webkit-datetime-edit"));
- container->setAttribute(idAttr, ShadowElementNames::DateTimeEdit());
+ container->setAttribute(kIdAttr, shadow_element_names::DateTimeEdit());
return container;
}
@@ -764,7 +764,7 @@ void DateTimeEditElement::GetLayout(const LayoutParameters& layout_parameters,
}
SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControl));
+ StyleChangeReasonForTracing::Create(style_change_reason::kControl));
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.h
index d2d4b43e823..dbd24699789 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.h
@@ -84,6 +84,7 @@ class DateTimeEditElement final : public HTMLDivElement,
static DateTimeEditElement* Create(Document&, EditControlOwner&);
+ DateTimeEditElement(Document&, EditControlOwner&);
~DateTimeEditElement() override;
void Trace(blink::Visitor*) override;
@@ -125,8 +126,6 @@ class DateTimeEditElement final : public HTMLDivElement,
// 8. AM/PM
static const int kMaximumNumberOfFields = 8;
- DateTimeEditElement(Document&, EditControlOwner&);
-
DateTimeFieldElement* FieldAt(wtf_size_t) const;
wtf_size_t FieldIndexOf(const DateTimeFieldElement&) const;
DateTimeFieldElement* FocusedField() const;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_field_element.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_field_element.cc
index ac6bc06d4eb..abf1c264e2d 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_field_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_field_element.cc
@@ -37,7 +37,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
DateTimeFieldElement::FieldOwner::~FieldOwner() = default;
@@ -78,7 +78,7 @@ void DateTimeFieldElement::DefaultEventHandler(Event& event) {
void DateTimeFieldElement::DefaultKeyboardEventHandler(
KeyboardEvent& keyboard_event) {
- if (keyboard_event.type() != EventTypeNames::keydown)
+ if (keyboard_event.type() != event_type_names::kKeydown)
return;
if (IsDisabled() || IsFieldOwnerDisabled())
@@ -154,12 +154,12 @@ void DateTimeFieldElement::Initialize(const AtomicString& pseudo,
int ax_minimum,
int ax_maximum) {
// On accessibility, DateTimeFieldElement acts like spin button.
- setAttribute(roleAttr, AtomicString("spinbutton"));
- setAttribute(aria_placeholderAttr, AtomicString(Placeholder()));
- setAttribute(aria_valueminAttr, AtomicString::Number(ax_minimum));
- setAttribute(aria_valuemaxAttr, AtomicString::Number(ax_maximum));
+ setAttribute(kRoleAttr, AtomicString("spinbutton"));
+ setAttribute(kAriaPlaceholderAttr, AtomicString(Placeholder()));
+ setAttribute(kAriaValueminAttr, AtomicString::Number(ax_minimum));
+ setAttribute(kAriaValuemaxAttr, AtomicString::Number(ax_maximum));
- setAttribute(aria_labelAttr, AtomicString(ax_help_text));
+ setAttribute(kAriaLabelAttr, AtomicString(ax_help_text));
SetShadowPseudoId(pseudo);
AppendChild(Text::Create(GetDocument(), VisibleValue()));
}
@@ -177,7 +177,7 @@ bool DateTimeFieldElement::IsFieldOwnerReadOnly() const {
}
bool DateTimeFieldElement::IsDisabled() const {
- return FastHasAttribute(disabledAttr);
+ return FastHasAttribute(kDisabledAttr);
}
Locale& DateTimeFieldElement::LocaleForOwner() const {
@@ -195,11 +195,11 @@ float DateTimeFieldElement::MaximumWidth(const ComputedStyle&) {
void DateTimeFieldElement::SetDisabled() {
// Set HTML attribute disabled to change apperance.
- SetBooleanAttribute(disabledAttr, true);
- SetNeedsStyleRecalc(
- kSubtreeStyleChange,
- StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_disabled));
+ SetBooleanAttribute(kDisabledAttr, true);
+ SetNeedsStyleRecalc(kSubtreeStyleChange,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_disabled));
}
bool DateTimeFieldElement::SupportsFocus() const {
@@ -216,12 +216,12 @@ void DateTimeFieldElement::UpdateVisibleValue(EventBehavior event_behavior) {
text_node->ReplaceWholeText(new_visible_value);
if (HasValue()) {
- setAttribute(aria_valuenowAttr,
+ setAttribute(kAriaValuenowAttr,
AtomicString::Number(ValueForARIAValueNow()));
- setAttribute(aria_valuetextAttr, AtomicString(new_visible_value));
+ setAttribute(kAriaValuetextAttr, AtomicString(new_visible_value));
} else {
- removeAttribute(aria_valuenowAttr);
- removeAttribute(aria_valuetextAttr);
+ removeAttribute(kAriaValuenowAttr);
+ removeAttribute(kAriaValuetextAttr);
}
if (event_behavior == kDispatchEvent && field_owner_)
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.cc
index bfb4b4b71ab..091f984b12a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.cc
@@ -52,7 +52,8 @@ DateTimeAMPMFieldElement* DateTimeAMPMFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, ampm_pseudo_id,
("-webkit-datetime-edit-ampm-field"));
DateTimeAMPMFieldElement* field =
- new DateTimeAMPMFieldElement(document, field_owner, ampm_labels);
+ MakeGarbageCollected<DateTimeAMPMFieldElement>(document, field_owner,
+ ampm_labels);
field->Initialize(ampm_pseudo_id,
QueryString(WebLocalizedString::kAXAMPMFieldText));
return field;
@@ -99,8 +100,10 @@ DateTimeDayFieldElement* DateTimeDayFieldElement::Create(
const Range& range) {
DEFINE_STATIC_LOCAL(AtomicString, day_pseudo_id,
("-webkit-datetime-edit-day-field"));
- DateTimeDayFieldElement* field = new DateTimeDayFieldElement(
- document, field_owner, placeholder.IsEmpty() ? "--" : placeholder, range);
+ DateTimeDayFieldElement* field =
+ MakeGarbageCollected<DateTimeDayFieldElement>(
+ document, field_owner, placeholder.IsEmpty() ? "--" : placeholder,
+ range);
field->Initialize(day_pseudo_id,
QueryString(WebLocalizedString::kAXDayOfMonthFieldText));
return field;
@@ -207,7 +210,8 @@ DateTimeHour11FieldElement* DateTimeHour11FieldElement::Create(
}
DateTimeHour11FieldElement* field =
- new DateTimeHour11FieldElement(document, field_owner, range, step);
+ MakeGarbageCollected<DateTimeHour11FieldElement>(document, field_owner,
+ range, step);
field->Initialize();
return field;
}
@@ -265,7 +269,8 @@ DateTimeHour12FieldElement* DateTimeHour12FieldElement::Create(
range.maximum = 12;
}
DateTimeHour12FieldElement* field =
- new DateTimeHour12FieldElement(document, field_owner, range, step);
+ MakeGarbageCollected<DateTimeHour12FieldElement>(document, field_owner,
+ range, step);
field->Initialize();
return field;
}
@@ -305,7 +310,8 @@ DateTimeHour23FieldElement* DateTimeHour23FieldElement::Create(
DCHECK_LE(hour23_range.maximum, 23);
DCHECK_LE(hour23_range.minimum, hour23_range.maximum);
DateTimeHour23FieldElement* field =
- new DateTimeHour23FieldElement(document, field_owner, hour23_range, step);
+ MakeGarbageCollected<DateTimeHour23FieldElement>(document, field_owner,
+ hour23_range, step);
field->Initialize();
return field;
}
@@ -360,7 +366,8 @@ DateTimeHour24FieldElement* DateTimeHour24FieldElement::Create(
}
DateTimeHour24FieldElement* field =
- new DateTimeHour24FieldElement(document, field_owner, range, step);
+ MakeGarbageCollected<DateTimeHour24FieldElement>(document, field_owner,
+ range, step);
field->Initialize();
return field;
}
@@ -415,7 +422,8 @@ DateTimeMillisecondFieldElement* DateTimeMillisecondFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, millisecond_pseudo_id,
("-webkit-datetime-edit-millisecond-field"));
DateTimeMillisecondFieldElement* field =
- new DateTimeMillisecondFieldElement(document, field_owner, range, step);
+ MakeGarbageCollected<DateTimeMillisecondFieldElement>(
+ document, field_owner, range, step);
field->Initialize(millisecond_pseudo_id,
QueryString(WebLocalizedString::kAXMillisecondFieldText));
return field;
@@ -469,7 +477,8 @@ DateTimeMinuteFieldElement* DateTimeMinuteFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, minute_pseudo_id,
("-webkit-datetime-edit-minute-field"));
DateTimeMinuteFieldElement* field =
- new DateTimeMinuteFieldElement(document, field_owner, range, step);
+ MakeGarbageCollected<DateTimeMinuteFieldElement>(document, field_owner,
+ range, step);
field->Initialize(minute_pseudo_id,
QueryString(WebLocalizedString::kAXMinuteFieldText));
return field;
@@ -520,8 +529,10 @@ DateTimeMonthFieldElement* DateTimeMonthFieldElement::Create(
const Range& range) {
DEFINE_STATIC_LOCAL(AtomicString, month_pseudo_id,
("-webkit-datetime-edit-month-field"));
- DateTimeMonthFieldElement* field = new DateTimeMonthFieldElement(
- document, field_owner, placeholder.IsEmpty() ? "--" : placeholder, range);
+ DateTimeMonthFieldElement* field =
+ MakeGarbageCollected<DateTimeMonthFieldElement>(
+ document, field_owner, placeholder.IsEmpty() ? "--" : placeholder,
+ range);
field->Initialize(month_pseudo_id,
QueryString(WebLocalizedString::kAXMonthFieldText));
return field;
@@ -574,7 +585,8 @@ DateTimeSecondFieldElement* DateTimeSecondFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, second_pseudo_id,
("-webkit-datetime-edit-second-field"));
DateTimeSecondFieldElement* field =
- new DateTimeSecondFieldElement(document, field_owner, range, step);
+ MakeGarbageCollected<DateTimeSecondFieldElement>(document, field_owner,
+ range, step);
field->Initialize(second_pseudo_id,
QueryString(WebLocalizedString::kAXSecondFieldText));
return field;
@@ -629,8 +641,8 @@ DateTimeSymbolicMonthFieldElement* DateTimeSymbolicMonthFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, month_pseudo_id,
("-webkit-datetime-edit-month-field"));
DateTimeSymbolicMonthFieldElement* field =
- new DateTimeSymbolicMonthFieldElement(document, field_owner, labels,
- minimum, maximum);
+ MakeGarbageCollected<DateTimeSymbolicMonthFieldElement>(
+ document, field_owner, labels, minimum, maximum);
field->Initialize(month_pseudo_id,
QueryString(WebLocalizedString::kAXMonthFieldText));
return field;
@@ -684,7 +696,8 @@ DateTimeWeekFieldElement* DateTimeWeekFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, week_pseudo_id,
("-webkit-datetime-edit-week-field"));
DateTimeWeekFieldElement* field =
- new DateTimeWeekFieldElement(document, field_owner, range);
+ MakeGarbageCollected<DateTimeWeekFieldElement>(document, field_owner,
+ range);
field->Initialize(week_pseudo_id,
QueryString(WebLocalizedString::kAXWeekOfYearFieldText));
return field;
@@ -741,7 +754,8 @@ DateTimeYearFieldElement* DateTimeYearFieldElement::Create(
DEFINE_STATIC_LOCAL(AtomicString, year_pseudo_id,
("-webkit-datetime-edit-year-field"));
DateTimeYearFieldElement* field =
- new DateTimeYearFieldElement(document, field_owner, parameters);
+ MakeGarbageCollected<DateTimeYearFieldElement>(document, field_owner,
+ parameters);
field->Initialize(year_pseudo_id,
QueryString(WebLocalizedString::kAXYearFieldText));
return field;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.h
index f2ff719f1d1..9fccb5c7faa 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.h
@@ -39,9 +39,9 @@ class DateTimeAMPMFieldElement final : public DateTimeSymbolicFieldElement {
FieldOwner&,
const Vector<String>&);
- private:
DateTimeAMPMFieldElement(Document&, FieldOwner&, const Vector<String>&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -57,12 +57,12 @@ class DateTimeDayFieldElement final : public DateTimeNumericFieldElement {
const String& placeholder,
const Range&);
- private:
DateTimeDayFieldElement(Document&,
FieldOwner&,
const String& placeholder,
const Range&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -95,12 +95,12 @@ class DateTimeHour11FieldElement final : public DateTimeHourFieldElementBase {
const Range&,
const Step&);
- private:
DateTimeHour11FieldElement(Document&,
FieldOwner&,
const Range& hour23_range,
const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsInteger(int, EventBehavior = kDispatchNoEvent) override;
@@ -115,12 +115,12 @@ class DateTimeHour12FieldElement final : public DateTimeHourFieldElementBase {
const Range&,
const Step&);
- private:
DateTimeHour12FieldElement(Document&,
FieldOwner&,
const Range& hour23_range,
const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsInteger(int, EventBehavior = kDispatchNoEvent) override;
@@ -135,12 +135,12 @@ class DateTimeHour23FieldElement final : public DateTimeHourFieldElementBase {
const Range&,
const Step&);
- private:
DateTimeHour23FieldElement(Document&,
FieldOwner&,
const Range& hour23_range,
const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsInteger(int, EventBehavior = kDispatchNoEvent) override;
@@ -155,12 +155,12 @@ class DateTimeHour24FieldElement final : public DateTimeHourFieldElementBase {
const Range&,
const Step&);
- private:
DateTimeHour24FieldElement(Document&,
FieldOwner&,
const Range& hour23_range,
const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsInteger(int, EventBehavior = kDispatchNoEvent) override;
@@ -176,12 +176,12 @@ class DateTimeMillisecondFieldElement final
const Range&,
const Step&);
- private:
DateTimeMillisecondFieldElement(Document&,
FieldOwner&,
const Range&,
const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -197,9 +197,9 @@ class DateTimeMinuteFieldElement final : public DateTimeNumericFieldElement {
const Range&,
const Step&);
- private:
DateTimeMinuteFieldElement(Document&, FieldOwner&, const Range&, const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -215,12 +215,12 @@ class DateTimeMonthFieldElement final : public DateTimeNumericFieldElement {
const String& placeholder,
const Range&);
- private:
DateTimeMonthFieldElement(Document&,
FieldOwner&,
const String& placeholder,
const Range&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -236,9 +236,9 @@ class DateTimeSecondFieldElement final : public DateTimeNumericFieldElement {
const Range&,
const Step&);
- private:
DateTimeSecondFieldElement(Document&, FieldOwner&, const Range&, const Step&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -256,13 +256,13 @@ class DateTimeSymbolicMonthFieldElement final
int minimum,
int maximum);
- private:
DateTimeSymbolicMonthFieldElement(Document&,
FieldOwner&,
const Vector<String>&,
int minimum,
int maximum);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -275,9 +275,9 @@ class DateTimeWeekFieldElement final : public DateTimeNumericFieldElement {
public:
static DateTimeWeekFieldElement* Create(Document&, FieldOwner&, const Range&);
- private:
DateTimeWeekFieldElement(Document&, FieldOwner&, const Range&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
@@ -309,9 +309,9 @@ class DateTimeYearFieldElement final : public DateTimeNumericFieldElement {
FieldOwner&,
const Parameters&);
- private:
DateTimeYearFieldElement(Document&, FieldOwner&, const Parameters&);
+ private:
// DateTimeFieldElement functions.
void PopulateDateTimeFieldsState(DateTimeFieldsState&) override;
void SetValueAsDate(const DateComponents&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.cc
index 399fe7ae777..ddf1980e620 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.cc
@@ -43,14 +43,14 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
+using namespace html_names;
static const int kDateTimeLocalDefaultStep = 60;
static const int kDateTimeLocalDefaultStepBase = 0;
static const int kDateTimeLocalStepScaleFactor = 1000;
InputType* DateTimeLocalInputType::Create(HTMLInputElement& element) {
- return new DateTimeLocalInputType(element);
+ return MakeGarbageCollected<DateTimeLocalInputType>(element);
}
void DateTimeLocalInputType::CountUsage() {
@@ -58,7 +58,7 @@ void DateTimeLocalInputType::CountUsage() {
}
const AtomicString& DateTimeLocalInputType::FormControlType() const {
- return InputTypeNames::datetime_local;
+ return input_type_names::kDatetimeLocal;
}
double DateTimeLocalInputType::ValueAsDate() const {
@@ -170,10 +170,10 @@ void DateTimeLocalInputType::SetupLayoutParameters(
layout_parameters.locale.DateTimeFormatWithoutSeconds();
layout_parameters.fallback_date_time_format = "yyyy-MM-dd'T'HH:mm";
}
- if (!ParseToDateComponents(GetElement().FastGetAttribute(minAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMinAttr),
&layout_parameters.minimum))
layout_parameters.minimum = DateComponents();
- if (!ParseToDateComponents(GetElement().FastGetAttribute(maxAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMaxAttr),
&layout_parameters.maximum))
layout_parameters.maximum = DateComponents();
layout_parameters.placeholder_for_day = GetLocale().QueryString(
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.h
index 102cdc3e239..8404bdf4be7 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.h
@@ -41,10 +41,10 @@ class DateTimeLocalInputType final : public BaseTemporalInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
explicit DateTimeLocalInputType(HTMLInputElement& element)
: BaseTemporalInputType(element) {}
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
double ValueAsDate() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.cc
index 38ff8175c37..7c75952fd89 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.cc
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
@@ -65,11 +65,11 @@ DateTimeNumericFieldElement::DateTimeNumericFieldElement(
// We show a direction-neutral string such as "--" as a placeholder. It
// should follow the direction of numeric values.
if (LocaleForOwner().IsRTL()) {
- WTF::Unicode::CharDirection dir =
- WTF::Unicode::Direction(FormatValue(Maximum())[0]);
- if (dir == WTF::Unicode::kLeftToRight ||
- dir == WTF::Unicode::kEuropeanNumber ||
- dir == WTF::Unicode::kArabicNumber) {
+ WTF::unicode::CharDirection dir =
+ WTF::unicode::Direction(FormatValue(Maximum())[0]);
+ if (dir == WTF::unicode::kLeftToRight ||
+ dir == WTF::unicode::kEuropeanNumber ||
+ dir == WTF::unicode::kArabicNumber) {
SetInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueBidiOverride);
SetInlineStyleProperty(CSSPropertyDirection, CSSValueLtr);
}
@@ -115,7 +115,7 @@ String DateTimeNumericFieldElement::FormatValue(int value) const {
void DateTimeNumericFieldElement::HandleKeyboardEvent(
KeyboardEvent& keyboard_event) {
DCHECK(!IsDisabled());
- if (keyboard_event.type() != EventTypeNames::keypress)
+ if (keyboard_event.type() != event_type_names::kKeypress)
return;
UChar char_code = static_cast<UChar>(keyboard_event.charCode());
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_symbolic_field_element.cc b/chromium/third_party/blink/renderer/core/html/forms/date_time_symbolic_field_element.cc
index 4c6ba85412b..35276798a10 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_symbolic_field_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_symbolic_field_element.cc
@@ -75,10 +75,10 @@ float DateTimeSymbolicFieldElement::MaximumWidth(const ComputedStyle& style) {
void DateTimeSymbolicFieldElement::HandleKeyboardEvent(
KeyboardEvent& keyboard_event) {
- if (keyboard_event.type() != EventTypeNames::keypress)
+ if (keyboard_event.type() != event_type_names::kKeypress)
return;
- const UChar char_code = WTF::Unicode::ToLower(keyboard_event.charCode());
+ const UChar char_code = WTF::unicode::ToLower(keyboard_event.charCode());
if (char_code < ' ')
return;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/email_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/email_input_type.cc
index 6408a2f0163..dd937e4a47a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/email_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/email_input_type.cc
@@ -65,7 +65,7 @@ std::unique_ptr<ScriptRegexp> EmailInputType::CreateEmailRegexp() {
String EmailInputType::ConvertEmailAddressToASCII(const ScriptRegexp& regexp,
const String& address) {
- if (address.ContainsOnlyASCII())
+ if (address.ContainsOnlyASCIIOrEmpty())
return address;
wtf_size_t at_position = address.find('@');
@@ -104,7 +104,7 @@ String EmailInputType::ConvertEmailAddressToASCII(const ScriptRegexp& regexp,
String EmailInputType::ConvertEmailAddressToUnicode(
const String& address) const {
- if (!address.ContainsOnlyASCII())
+ if (!address.ContainsOnlyASCIIOrEmpty())
return address;
wtf_size_t at_position = address.find('@');
@@ -160,12 +160,13 @@ EmailInputType::EmailInputType(HTMLInputElement& element)
: BaseTextInputType(element) {}
InputType* EmailInputType::Create(HTMLInputElement& element) {
- return new EmailInputType(element);
+ return MakeGarbageCollected<EmailInputType>(element);
}
void EmailInputType::CountUsage() {
CountUsageIfVisible(WebFeature::kInputTypeEmail);
- bool has_max_length = GetElement().FastHasAttribute(HTMLNames::maxlengthAttr);
+ bool has_max_length =
+ GetElement().FastHasAttribute(html_names::kMaxlengthAttr);
if (has_max_length)
CountUsageIfVisible(WebFeature::kInputTypeEmailMaxLength);
if (GetElement().Multiple()) {
@@ -176,7 +177,7 @@ void EmailInputType::CountUsage() {
}
const AtomicString& EmailInputType::FormControlType() const {
- return InputTypeNames::email;
+ return input_type_names::kEmail;
}
ScriptRegexp& EmailInputType::EnsureEmailRegexp() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/email_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/email_input_type.h
index 58a6e745bb0..0e37b497844 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/email_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/email_input_type.h
@@ -39,6 +39,8 @@ class EmailInputType final : public BaseTextInputType {
public:
static InputType* Create(HTMLInputElement&);
+ explicit EmailInputType(HTMLInputElement&);
+
// They are public for unit testing.
CORE_EXPORT static String ConvertEmailAddressToASCII(const ScriptRegexp&,
const String&);
@@ -47,7 +49,6 @@ class EmailInputType final : public BaseTextInputType {
CORE_EXPORT static std::unique_ptr<ScriptRegexp> CreateEmailRegexp();
private:
- explicit EmailInputType(HTMLInputElement&);
void CountUsage() override;
const AtomicString& FormControlType() const override;
bool TypeMismatchFor(const String&) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc b/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc
index a50c2db2d8c..c5dd3246d79 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc
@@ -74,24 +74,25 @@ ExternalDateTimeChooser* ExternalDateTimeChooser::Create(
DateTimeChooserClient* client,
const DateTimeChooserParameters& parameters) {
DCHECK(chrome_client);
- ExternalDateTimeChooser* chooser = new ExternalDateTimeChooser(client);
+ ExternalDateTimeChooser* chooser =
+ MakeGarbageCollected<ExternalDateTimeChooser>(client);
if (!chooser->OpenDateTimeChooser(chrome_client, web_view_client, parameters))
chooser = nullptr;
return chooser;
}
static WebDateTimeInputType ToWebDateTimeInputType(const AtomicString& source) {
- if (source == InputTypeNames::date)
+ if (source == input_type_names::kDate)
return kWebDateTimeInputTypeDate;
- if (source == InputTypeNames::datetime)
+ if (source == input_type_names::kDatetime)
return kWebDateTimeInputTypeDateTime;
- if (source == InputTypeNames::datetime_local)
+ if (source == input_type_names::kDatetimeLocal)
return kWebDateTimeInputTypeDateTimeLocal;
- if (source == InputTypeNames::month)
+ if (source == input_type_names::kMonth)
return kWebDateTimeInputTypeMonth;
- if (source == InputTypeNames::time)
+ if (source == input_type_names::kTime)
return kWebDateTimeInputTypeTime;
- if (source == InputTypeNames::week)
+ if (source == input_type_names::kWeek)
return kWebDateTimeInputTypeWeek;
return kWebDateTimeInputTypeNone;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.h b/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.h
index 19d512520a1..4994a5f361c 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.h
@@ -42,6 +42,8 @@ class CORE_EXPORT ExternalDateTimeChooser final : public DateTimeChooser {
WebViewClient*,
DateTimeChooserClient*,
const DateTimeChooserParameters&);
+
+ ExternalDateTimeChooser(DateTimeChooserClient*);
~ExternalDateTimeChooser() override;
void Trace(blink::Visitor*) override;
@@ -51,7 +53,6 @@ class CORE_EXPORT ExternalDateTimeChooser final : public DateTimeChooser {
void DidCancelChooser();
private:
- ExternalDateTimeChooser(DateTimeChooserClient*);
bool OpenDateTimeChooser(ChromeClient*,
WebViewClient*,
const DateTimeChooserParameters&);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu.cc b/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu.cc
index 2d6e42c466e..d85936423de 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu.cc
@@ -133,7 +133,8 @@ void ExternalPopupMenu::Show() {
}
void ExternalPopupMenu::DispatchEvent(TimerBase*) {
- web_view_.HandleInputEvent(blink::WebCoalescedInputEvent(*synthetic_event_));
+ web_view_.MainFrameWidget()->HandleInputEvent(
+ blink::WebCoalescedInputEvent(*synthetic_event_));
synthetic_event_.reset();
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc b/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc
index d9084519e22..a688821896f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc
@@ -65,7 +65,7 @@ TEST_F(ExternalPopupMenuDisplayNoneItemsTest, IndexMappingTest) {
}
class ExternalPopupMenuWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
WebExternalPopupMenu* CreateExternalPopupMenu(
const WebPopupMenuInfo&,
@@ -107,15 +107,16 @@ class ExternalPopupMenuTest : public testing::Test {
}
void RegisterMockedURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath("popup"),
WebString::FromUTF8(file_name), WebString::FromUTF8("text/html"));
}
void LoadFrame(const std::string& file_name) {
- FrameTestHelpers::LoadFrame(MainFrame(), base_url_ + file_name);
+ frame_test_helpers::LoadFrame(MainFrame(), base_url_ + file_name);
WebView()->Resize(WebSize(800, 600));
- WebView()->UpdateAllLifecyclePhases();
+ WebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
WebViewImpl* WebView() const { return helper_.GetWebView(); }
@@ -127,7 +128,7 @@ class ExternalPopupMenuTest : public testing::Test {
private:
std::string base_url_;
ExternalPopupMenuWebFrameClient web_frame_client_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
};
TEST_F(ExternalPopupMenuTest, PopupAccountsForVisualViewportTransform) {
@@ -135,7 +136,8 @@ TEST_F(ExternalPopupMenuTest, PopupAccountsForVisualViewportTransform) {
LoadFrame("select_mid_screen.html");
WebView()->Resize(WebSize(100, 100));
- WebView()->UpdateAllLifecyclePhases();
+ WebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
HTMLSelectElement* select = ToHTMLSelectElement(
MainFrame()->GetFrame()->GetDocument()->getElementById("select"));
diff --git a/chromium/third_party/blink/renderer/core/html/forms/file_chooser.cc b/chromium/third_party/blink/renderer/core/html/forms/file_chooser.cc
index 50b398986e0..2cd55b413d3 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/file_chooser.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/file_chooser.cc
@@ -28,11 +28,11 @@
#include "third_party/blink/renderer/core/html/forms/file_chooser.h"
+#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/file_path_conversion.h"
-#include "third_party/blink/public/web/web_local_frame_client.h"
-#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/page/chrome_client_impl.h"
-#include "third_party/blink/renderer/platform/wtf/date_math.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -43,7 +43,7 @@ using mojom::blink::NativeFileInfo;
FileChooserClient::~FileChooserClient() = default;
FileChooser* FileChooserClient::NewFileChooser(
- const WebFileChooserParams& params) {
+ const mojom::blink::FileChooserParams& params) {
if (chooser_)
chooser_->DisconnectClient();
@@ -57,12 +57,12 @@ void FileChooserClient::DisconnectFileChooser() {
}
inline FileChooser::FileChooser(FileChooserClient* client,
- const WebFileChooserParams& params)
- : client_(client), params_(params) {}
+ const mojom::blink::FileChooserParams& params)
+ : client_(client), params_(params.Clone()) {}
scoped_refptr<FileChooser> FileChooser::Create(
FileChooserClient* client,
- const WebFileChooserParams& params) {
+ const mojom::blink::FileChooserParams& params) {
return base::AdoptRef(new FileChooser(client, params));
}
@@ -73,44 +73,44 @@ bool FileChooser::OpenFileChooser(ChromeClientImpl& chrome_client_impl) {
if (!frame)
return false;
chrome_client_impl_ = chrome_client_impl;
-
- WebLocalFrameClient* client =
- frame ? WebLocalFrameImpl::FromFrame(frame)->Client() : nullptr;
- if (!client || !client->RunFileChooser(params_, this))
- return false;
-
- // Should be released on file choosing.
+ frame->GetInterfaceProvider().GetInterface(&file_chooser_);
+ file_chooser_.set_connection_error_handler(
+ WTF::Bind(&FileChooser::DidCloseChooser, WTF::Unretained(this)));
+ file_chooser_->OpenFileChooser(
+ params_.Clone(),
+ WTF::Bind(&FileChooser::DidChooseFiles, WTF::Unretained(this)));
+
+ // Should be released on file choosing or connection error.
AddRef();
chrome_client_impl.RegisterPopupOpeningObserver(client_);
return true;
}
-void FileChooser::DidChooseFile(const WebVector<WebString>& file_names) {
- FileChooserFileInfoList file_info;
- for (size_t i = 0; i < file_names.size(); ++i)
- file_info.push_back(CreateFileChooserFileInfoNative(file_names[i]));
- ChooseFiles(file_info);
-}
-
-void FileChooser::DidChooseFile(const WebVector<SelectedFileInfo>& files) {
- FileChooserFileInfoList file_info;
- for (size_t i = 0; i < files.size(); ++i) {
- DCHECK(!files[i].is_directory);
- if (files[i].file_system_url.IsEmpty()) {
- file_info.push_back(FileChooserFileInfo::NewNativeFile(
- NativeFileInfo::New(files[i].file_path, files[i].display_name)));
- } else {
- file_info.push_back(CreateFileChooserFileInfoFileSystem(
- files[i].file_system_url, files[i].modification_time,
- files[i].length));
- }
- }
- ChooseFiles(file_info);
+void FileChooser::EnumerateChosenDirectory() {
+ DCHECK_EQ(params_->selected_files.size(), 1u);
+ LocalFrame* frame = FrameOrNull();
+ if (!frame)
+ return;
+ DCHECK(!chrome_client_impl_);
+ frame->GetInterfaceProvider().GetInterface(&file_chooser_);
+ file_chooser_.set_connection_error_handler(
+ WTF::Bind(&FileChooser::DidCloseChooser, WTF::Unretained(this)));
+ file_chooser_->EnumerateChosenDirectory(
+ std::move(params_->selected_files[0]),
+ WTF::Bind(&FileChooser::DidChooseFiles, WTF::Unretained(this)));
+
+ // Should be released on file choosing or connection error.
+ AddRef();
}
-void FileChooser::ChooseFiles(const FileChooserFileInfoList& files) {
+void FileChooser::DidChooseFiles(mojom::blink::FileChooserResultPtr result) {
+ // TODO(tkent): If |result| is nullptr, we should not clear the
+ // already-selected files in <input type=file> like other browsers.
+ FileChooserFileInfoList files;
+ if (result)
+ files = std::move(result->files);
// FIXME: This is inelegant. We should not be looking at params_ here.
- if (params_.selected_files.size() == files.size()) {
+ if (params_->selected_files.size() == files.size()) {
bool was_changed = false;
for (unsigned i = 0; i < files.size(); ++i) {
// TODO(tkent): If a file system URL was already selected, and new
@@ -121,8 +121,8 @@ void FileChooser::ChooseFiles(const FileChooserFileInfoList& files) {
// file system URLs. Comparing File::name() doesn't make
// sense. We should compare file system URLs.
if (!files[i]->is_native_file() ||
- params_.selected_files[i] !=
- FilePathToWebString(files[i]->get_native_file()->file_path)) {
+ params_->selected_files[i] !=
+ files[i]->get_native_file()->file_path) {
was_changed = true;
break;
}
@@ -133,17 +133,25 @@ void FileChooser::ChooseFiles(const FileChooserFileInfoList& files) {
}
}
- if (client_)
- client_->FilesChosen(files);
+ if (client_) {
+ client_->FilesChosen(std::move(files),
+ result ? result->base_directory : base::FilePath());
+ }
DidCloseChooser();
}
void FileChooser::DidCloseChooser() {
+ // Close the binding explicitly to avoid this function is called again as a
+ // connection error handler.
+ file_chooser_.reset();
+
+ // Some cleanup for OpenFileChooser() path.
if (chrome_client_impl_) {
chrome_client_impl_->DidCompleteFileChooser(*this);
if (client_)
chrome_client_impl_->UnregisterPopupOpeningObserver(client_);
}
+
Release();
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/file_chooser.h b/chromium/third_party/blink/renderer/core/html/forms/file_chooser.h
index 6e22d2f5b3f..1042c13f531 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/file_chooser.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/file_chooser.h
@@ -30,9 +30,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_FILE_CHOOSER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_FILE_CHOOSER_H_
+#include "mojo/public/cpp/bindings/binding.h"
#include "third_party/blink/public/mojom/choosers/file_chooser.mojom-blink.h"
-#include "third_party/blink/public/web/web_file_chooser_completion.h"
-#include "third_party/blink/public/web/web_file_chooser_params.h"
#include "third_party/blink/renderer/core/page/popup_opening_observer.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
@@ -52,12 +51,17 @@ using FileChooserFileInfoList = Vector<mojom::blink::FileChooserFileInfoPtr>;
class CORE_EXPORT FileChooserClient : public PopupOpeningObserver {
public:
- virtual void FilesChosen(const FileChooserFileInfoList&) = 0;
+ virtual void FilesChosen(FileChooserFileInfoList,
+ const base::FilePath& base_dir) = 0;
virtual LocalFrame* FrameOrNull() const = 0;
~FileChooserClient() override;
+ // Accessor for chooser_. This returns null before NewFileChooser() and after
+ // DisconnectFileChooser().
+ FileChooser* FileChooserOrNull() const { return chooser_.get(); }
+
protected:
- FileChooser* NewFileChooser(const WebFileChooserParams&);
+ FileChooser* NewFileChooser(const mojom::blink::FileChooserParams&);
bool HasConnectedFileChooser() const { return chooser_.get(); }
// This should be called if a user chose files or cancel the dialog.
@@ -67,39 +71,35 @@ class CORE_EXPORT FileChooserClient : public PopupOpeningObserver {
scoped_refptr<FileChooser> chooser_;
};
-class FileChooser : public RefCounted<FileChooser>,
- public WebFileChooserCompletion {
+class FileChooser : public RefCounted<FileChooser> {
public:
CORE_EXPORT static scoped_refptr<FileChooser> Create(
FileChooserClient*,
- const WebFileChooserParams&);
- ~FileChooser() override;
+ const mojom::blink::FileChooserParams&);
+ CORE_EXPORT ~FileChooser();
LocalFrame* FrameOrNull() const {
return client_ ? client_->FrameOrNull() : nullptr;
}
void DisconnectClient() { client_ = nullptr; }
- const WebFileChooserParams& Params() const { return params_; }
+ const mojom::blink::FileChooserParams& Params() const { return *params_; }
bool OpenFileChooser(ChromeClientImpl& chrome_client_impl);
+ void EnumerateChosenDirectory();
private:
- FileChooser(FileChooserClient*, const WebFileChooserParams&);
+ FileChooser(FileChooserClient*, const mojom::blink::FileChooserParams&);
void DidCloseChooser();
- // WebFileChooserCompletion implementation:
- void DidChooseFile(const WebVector<WebString>& file_names) override;
- void DidChooseFile(const WebVector<SelectedFileInfo>& files) override;
-
- // FIXME: We should probably just pass file paths that could be virtual paths
- // with proper display names rather than passing structs.
- void ChooseFiles(const FileChooserFileInfoList& files);
+ // mojom::blink::FileChooser callback
+ void DidChooseFiles(mojom::blink::FileChooserResultPtr result);
WeakPersistent<FileChooserClient> client_;
- WebFileChooserParams params_;
+ mojom::blink::FileChooserParamsPtr params_;
Persistent<ChromeClientImpl> chrome_client_impl_;
+ mojom::blink::FileChooserPtr file_chooser_;
};
CORE_EXPORT mojom::blink::FileChooserFileInfoPtr
diff --git a/chromium/third_party/blink/renderer/core/html/forms/file_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/file_input_type.cc
index c6210186086..c1d08ba805b 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/file_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/file_input_type.cc
@@ -48,11 +48,12 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
+using mojom::blink::FileChooserParams;
+using namespace html_names;
namespace {
-WebVector<WebString> CollectAcceptTypes(const HTMLInputElement& input) {
+Vector<String> CollectAcceptTypes(const HTMLInputElement& input) {
Vector<String> mime_types = input.AcceptMIMETypes();
Vector<String> extensions = input.AcceptFileExtensions();
@@ -71,7 +72,7 @@ inline FileInputType::FileInputType(HTMLInputElement& element)
file_list_(FileList::Create()) {}
InputType* FileInputType::Create(HTMLInputElement& element) {
- return new FileInputType(element);
+ return MakeGarbageCollected<FileInputType>(element);
}
void FileInputType::Trace(blink::Visitor* visitor) {
@@ -84,20 +85,31 @@ InputTypeView* FileInputType::CreateView() {
return this;
}
-FileChooserFileInfoList FileInputType::FilesFromFormControlState(
- const FormControlState& state) {
- FileChooserFileInfoList files;
- for (wtf_size_t i = 0; i < state.ValueSize(); i += 2) {
- if (!state[i + 1].IsEmpty())
- files.push_back(CreateFileChooserFileInfoNative(state[i], state[i + 1]));
- else
- files.push_back(CreateFileChooserFileInfoNative(state[i]));
+template <typename ItemType, typename VectorType>
+VectorType CreateFilesFrom(const FormControlState& state,
+ ItemType (*factory)(const String&,
+ const String&,
+ const String&)) {
+ VectorType files;
+ files.ReserveInitialCapacity(state.ValueSize() / 3);
+ for (wtf_size_t i = 0; i < state.ValueSize(); i += 3) {
+ const String& path = state[i];
+ const String& name = state[i + 1];
+ const String& relative_path = state[i + 2];
+ files.push_back(factory(path, name, relative_path));
}
return files;
}
+Vector<String> FileInputType::FilesFromFormControlState(
+ const FormControlState& state) {
+ return CreateFilesFrom<String, Vector<String>>(
+ state,
+ [](const String& path, const String&, const String&) { return path; });
+}
+
const AtomicString& FileInputType::FormControlType() const {
- return InputTypeNames::file;
+ return input_type_names::kFile;
}
FormControlState FileInputType::SaveFormControlState() const {
@@ -109,6 +121,7 @@ FormControlState FileInputType::SaveFormControlState() const {
if (file_list_->item(i)->HasBackingFile()) {
state.Append(file_list_->item(i)->GetPath());
state.Append(file_list_->item(i)->name());
+ state.Append(file_list_->item(i)->webkitRelativePath());
}
// FIXME: handle Blob-backed File instances, see http://crbug.com/394948
}
@@ -116,9 +129,20 @@ FormControlState FileInputType::SaveFormControlState() const {
}
void FileInputType::RestoreFormControlState(const FormControlState& state) {
- if (state.ValueSize() % 2)
+ if (state.ValueSize() % 3)
return;
- FilesChosen(FilesFromFormControlState(state));
+ HeapVector<Member<File>> file_vector =
+ CreateFilesFrom<File*, HeapVector<Member<File>>>(
+ state, [](const String& path, const String& name,
+ const String& relative_path) {
+ if (relative_path.IsEmpty())
+ return File::CreateForUserProvidedFile(path, name);
+ return File::CreateWithRelativePath(path, relative_path);
+ });
+ FileList* file_list = FileList::Create();
+ for (const auto& file : file_vector)
+ file_list->Append(file);
+ SetFiles(file_list);
}
void FileInputType::AppendToFormData(FormData& form_data) const {
@@ -154,21 +178,22 @@ void FileInputType::HandleDOMActivateEvent(Event& event) {
return;
if (ChromeClient* chrome_client = GetChromeClient()) {
- WebFileChooserParams params;
+ FileChooserParams params;
HTMLInputElement& input = GetElement();
Document& document = input.GetDocument();
- bool is_directory = input.FastHasAttribute(webkitdirectoryAttr);
+ bool is_directory = input.FastHasAttribute(kWebkitdirectoryAttr);
if (is_directory)
- params.mode = WebFileChooserParams::Mode::kUploadFolder;
- else if (input.FastHasAttribute(multipleAttr))
- params.mode = WebFileChooserParams::Mode::kOpenMultiple;
+ params.mode = FileChooserParams::Mode::kUploadFolder;
+ else if (input.FastHasAttribute(kMultipleAttr))
+ params.mode = FileChooserParams::Mode::kOpenMultiple;
else
- params.mode = WebFileChooserParams::Mode::kOpen;
+ params.mode = FileChooserParams::Mode::kOpen;
+ params.title = g_empty_string;
params.need_local_path = is_directory;
params.accept_types = CollectAcceptTypes(input);
params.selected_files = file_list_->PathsForUserVisibleFiles();
params.use_media_capture = RuntimeEnabledFeatures::MediaCaptureEnabled() &&
- input.FastHasAttribute(captureAttr);
+ input.FastHasAttribute(kCaptureAttr);
params.requestor = document.Url();
UseCounter::Count(
@@ -229,35 +254,35 @@ void FileInputType::SetValue(const String&,
file_list_->clear();
GetElement().SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
+ StyleChangeReasonForTracing::Create(style_change_reason::kControlValue));
GetElement().SetNeedsValidityCheck();
}
FileList* FileInputType::CreateFileList(const FileChooserFileInfoList& files,
- bool has_webkit_directory_attr) {
+ const base::FilePath& base_dir) {
FileList* file_list(FileList::Create());
wtf_size_t size = files.size();
// If a directory is being selected, the UI allows a directory to be chosen
- // and the paths provided here share a root directory somewhere up the tree;
- // we want to store only the relative paths from that point.
- if (size && has_webkit_directory_attr) {
- // Find the common root path.
- base::FilePath root_path = files[0]->get_native_file()->file_path.DirName();
- for (wtf_size_t i = 1; i < size; ++i) {
- while (files[i]->get_native_file()->file_path.value().find(
- root_path.value()) != 0)
- root_path = root_path.DirName();
- }
- root_path = root_path.DirName();
+ // and the paths provided here should start with |base_dir|.
+ // We want to store only the relative path starting with the basename of
+ // |base_dir|.
+ if (size && !base_dir.empty()) {
+ base::FilePath root_path = base_dir.DirName();
int root_length = FilePathToString(root_path).length();
DCHECK(root_length);
if (!root_path.EndsWithSeparator())
root_length += 1;
+ if (base_dir == root_path)
+ root_length = 0;
for (const auto& file : files) {
// Normalize backslashes to slashes before exposing the relative path to
// script.
String string_path = FilePathToString(file->get_native_file()->file_path);
+ DCHECK(
+ string_path.StartsWithIgnoringASCIICase(FilePathToString(base_dir)))
+ << "A path in a FileChooserFileInfo " << string_path
+ << " should start with " << FilePathToString(base_dir);
String relative_path =
string_path.Substring(root_length).Replace('\\', '/');
file_list->Append(
@@ -296,9 +321,9 @@ void FileInputType::CreateShadowSubtree() {
DCHECK(IsShadowHost(GetElement()));
auto* button = HTMLInputElement::Create(GetElement().GetDocument(),
CreateElementFlags());
- button->setType(InputTypeNames::button);
+ button->setType(input_type_names::kButton);
button->setAttribute(
- valueAttr,
+ kValueAttr,
AtomicString(GetLocale().QueryString(
GetElement().Multiple()
? WebLocalizedString::kFileButtonChooseMultipleFilesLabel
@@ -311,7 +336,7 @@ void FileInputType::DisabledAttributeChanged() {
DCHECK(IsShadowHost(GetElement()));
if (Element* button =
ToElementOrDie(GetElement().UserAgentShadowRoot()->firstChild()))
- button->SetBooleanAttribute(disabledAttr,
+ button->SetBooleanAttribute(kDisabledAttr,
GetElement().IsDisabledFormControl());
}
@@ -320,7 +345,7 @@ void FileInputType::MultipleAttributeChanged() {
if (Element* button =
ToElementOrDie(GetElement().UserAgentShadowRoot()->firstChild()))
button->setAttribute(
- valueAttr,
+ kValueAttr,
AtomicString(GetLocale().QueryString(
GetElement().Multiple()
? WebLocalizedString::kFileButtonChooseMultipleFilesLabel
@@ -359,9 +384,20 @@ void FileInputType::SetFiles(FileList* files) {
}
}
-void FileInputType::FilesChosen(const FileChooserFileInfoList& files) {
- SetFiles(CreateFileList(files,
- GetElement().FastHasAttribute(webkitdirectoryAttr)));
+void FileInputType::FilesChosen(FileChooserFileInfoList files,
+ const base::FilePath& base_dir) {
+ for (wtf_size_t i = 0; i < files.size();) {
+ // Drop files of which names can not be converted to WTF String. We
+ // can't expose such files via File API.
+ if (files[i]->is_native_file() &&
+ FilePathToString(files[i]->get_native_file()->file_path).IsEmpty()) {
+ files.EraseAt(i);
+ // Do not increment |i|.
+ continue;
+ }
+ ++i;
+ }
+ SetFiles(CreateFileList(files, base_dir));
if (HasConnectedFileChooser())
DisconnectFileChooser();
}
@@ -371,16 +407,13 @@ LocalFrame* FileInputType::FrameOrNull() const {
}
void FileInputType::SetFilesFromDirectory(const String& path) {
- if (ChromeClient* chrome_client = GetChromeClient()) {
- Vector<String> files;
- files.push_back(path);
- WebFileChooserParams params;
- params.mode = WebFileChooserParams::Mode::kUploadFolder;
- params.selected_files = files;
- params.accept_types = CollectAcceptTypes(GetElement());
- params.requestor = GetElement().GetDocument().Url();
- chrome_client->EnumerateChosenDirectory(NewFileChooser(params));
- }
+ FileChooserParams params;
+ params.mode = FileChooserParams::Mode::kUploadFolder;
+ params.title = g_empty_string;
+ params.selected_files.push_back(StringToFilePath(path));
+ params.accept_types = CollectAcceptTypes(GetElement());
+ params.requestor = GetElement().GetDocument().Url();
+ NewFileChooser(params)->EnumerateChosenDirectory();
}
void FileInputType::SetFilesFromPaths(const Vector<String>& paths) {
@@ -388,7 +421,7 @@ void FileInputType::SetFilesFromPaths(const Vector<String>& paths) {
return;
HTMLInputElement& input = GetElement();
- if (input.FastHasAttribute(webkitdirectoryAttr)) {
+ if (input.FastHasAttribute(kWebkitdirectoryAttr)) {
SetFilesFromDirectory(paths[0]);
return;
}
@@ -397,12 +430,12 @@ void FileInputType::SetFilesFromPaths(const Vector<String>& paths) {
for (const auto& path : paths)
files.push_back(CreateFileChooserFileInfoNative(path));
- if (input.FastHasAttribute(multipleAttr)) {
- FilesChosen(files);
+ if (input.FastHasAttribute(kMultipleAttr)) {
+ FilesChosen(std::move(files), base::FilePath());
} else {
FileChooserFileInfoList first_file_only;
first_file_only.push_back(std::move(files[0]));
- FilesChosen(first_file_only);
+ FilesChosen(std::move(first_file_only), base::FilePath());
}
}
@@ -412,7 +445,7 @@ bool FileInputType::ReceiveDroppedFiles(const DragData* drag_data) {
if (paths.IsEmpty())
return false;
- if (!GetElement().FastHasAttribute(webkitdirectoryAttr)) {
+ if (!GetElement().FastHasAttribute(kWebkitdirectoryAttr)) {
dropped_file_system_id_ = drag_data->DroppedFileSystemId();
}
SetFilesFromPaths(paths);
@@ -448,7 +481,7 @@ void FileInputType::CopyNonAttributeProperties(const HTMLInputElement& source) {
}
void FileInputType::HandleKeypressEvent(KeyboardEvent& event) {
- if (GetElement().FastHasAttribute(webkitdirectoryAttr)) {
+ if (GetElement().FastHasAttribute(kWebkitdirectoryAttr)) {
// Override to invoke the action on Enter key up (not press) to avoid
// repeats committing the file chooser.
if (event.key() == "Enter") {
@@ -460,7 +493,7 @@ void FileInputType::HandleKeypressEvent(KeyboardEvent& event) {
}
void FileInputType::HandleKeyupEvent(KeyboardEvent& event) {
- if (GetElement().FastHasAttribute(webkitdirectoryAttr)) {
+ if (GetElement().FastHasAttribute(kWebkitdirectoryAttr)) {
// Override to invoke the action on Enter key up (not press) to avoid
// repeats committing the file chooser.
if (event.key() == "Enter") {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/file_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/file_input_type.h
index 298b73cc3c1..0175590f861 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/file_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/file_input_type.h
@@ -52,19 +52,20 @@ class CORE_EXPORT FileInputType final : public InputType,
public:
static InputType* Create(HTMLInputElement&);
+
+ FileInputType(HTMLInputElement&);
+
void Trace(blink::Visitor*) override;
using InputType::GetElement;
- static FileChooserFileInfoList FilesFromFormControlState(
- const FormControlState&);
+ static Vector<String> FilesFromFormControlState(const FormControlState&);
static FileList* CreateFileList(const FileChooserFileInfoList& files,
- bool has_webkit_directory_attr);
+ const base::FilePath& base_dir);
void CountUsage() override;
void SetFilesFromPaths(const Vector<String>&) override;
private:
- FileInputType(HTMLInputElement&);
InputTypeView* CreateView() override;
const AtomicString& FormControlType() const override;
FormControlState SaveFormControlState() const override;
@@ -97,7 +98,8 @@ class CORE_EXPORT FileInputType final : public InputType,
void HandleKeyupEvent(KeyboardEvent&) override;
// FileChooserClient implementation.
- void FilesChosen(const FileChooserFileInfoList&) override;
+ void FilesChosen(FileChooserFileInfoList files,
+ const base::FilePath& base_dir) override;
LocalFrame* FrameOrNull() const override;
// PopupOpeningObserver implementation.
diff --git a/chromium/third_party/blink/renderer/core/html/forms/file_input_type_test.cc b/chromium/third_party/blink/renderer/core/html/forms/file_input_type_test.cc
index bb3d71d4004..47afb404da6 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/file_input_type_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/file_input_type_test.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/fileapi/file_list.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
+#include "third_party/blink/renderer/core/html/forms/mock_file_chooser.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
#include "third_party/blink/renderer/core/page/drag_data.h"
@@ -22,12 +23,6 @@ namespace {
class WebKitDirectoryChromeClient : public EmptyChromeClient {
public:
- void EnumerateChosenDirectory(FileChooser* chooser) override {
- chooser->AddRef(); // Do same as ChromeClientImpl
- static_cast<WebFileChooserCompletion*>(chooser)->DidChooseFile(
- WebVector<WebString>());
- }
-
void RegisterPopupOpeningObserver(PopupOpeningObserver*) override {
NOTREACHED() << "RegisterPopupOpeningObserver should not be called.";
}
@@ -50,7 +45,7 @@ TEST(FileInputTypeTest, createFileList) {
files.push_back(CreateFileChooserFileInfoFileSystem(
url, base::Time::FromJsTime(1.0 * kMsPerDay + 3), 64));
- FileList* list = FileInputType::CreateFileList(files, false);
+ FileList* list = FileInputType::CreateFileList(files, base::FilePath());
ASSERT_TRUE(list);
ASSERT_EQ(2u, list->length());
@@ -117,7 +112,7 @@ TEST(FileInputTypeTest, setFilesFromPaths) {
EXPECT_EQ(String("/native/path1"), file_input->Files()->item(0)->GetPath());
// Try to upload multiple files with multipleAttr
- input->SetBooleanAttribute(HTMLNames::multipleAttr, true);
+ input->SetBooleanAttribute(html_names::kMultipleAttr, true);
paths.clear();
paths.push_back("/native/real/path1");
paths.push_back("/native/real/path2");
@@ -140,10 +135,16 @@ TEST(FileInputTypeTest, DropTouchesNoPopupOpeningObserver) {
doc.body()->SetInnerHTMLFromString("<input type=file webkitdirectory>");
auto& input = *ToHTMLInputElement(doc.body()->firstChild());
+ base::RunLoop run_loop;
+ MockFileChooser chooser(&doc.GetFrame()->GetInterfaceProvider(),
+ run_loop.QuitClosure());
DragData drag_data(DataObject::Create(), FloatPoint(), FloatPoint(),
kDragOperationCopy);
drag_data.PlatformData()->Add(File::Create("/foo/bar"));
input.ReceiveDroppedFiles(&drag_data);
+ run_loop.Run();
+
+ chooser.ResponseOnOpenFileChooser(FileChooserFileInfoList());
// The test passes if WebKitDirectoryChromeClient::
// UnregisterPopupOpeningObserver() was not called.
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_controller.cc b/chromium/third_party/blink/renderer/core/html/forms/form_controller.cc
index e721c5f6214..96c940d9029 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_controller.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_controller.cc
@@ -25,7 +25,6 @@
#include "base/macros.h"
#include "base/memory/ptr_util.h"
-#include "third_party/blink/public/platform/file_path_conversion.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/html/forms/file_chooser.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.h"
@@ -37,14 +36,14 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static inline HTMLFormElement* OwnerFormForState(
const HTMLFormControlElementWithState& control) {
// Assume controls with form attribute have no owners because we restore
// state during parsing and form owners of such controls might be
// indeterminate.
- return control.FastHasAttribute(formAttr) ? nullptr : control.Form();
+ return control.FastHasAttribute(kFormAttr) ? nullptr : control.Form();
}
// ----------------------------------------------------------------------------
@@ -297,13 +296,9 @@ Vector<String> SavedFormState::GetReferencedFilePaths() const {
continue;
const Deque<FormControlState>& queue = form_control.value;
for (const FormControlState& form_control_state : queue) {
- const FileChooserFileInfoList& selected_files =
+ to_return.AppendVector(
HTMLInputElement::FilesFromFileInputFormControlState(
- form_control_state);
- for (const auto& file : selected_files) {
- to_return.push_back(
- FilePathToString(file->get_native_file()->file_path));
- }
+ form_control_state));
}
}
return to_return;
@@ -315,14 +310,17 @@ class FormKeyGenerator final
: public GarbageCollectedFinalized<FormKeyGenerator> {
public:
- static FormKeyGenerator* Create() { return new FormKeyGenerator; }
+ static FormKeyGenerator* Create() {
+ return MakeGarbageCollected<FormKeyGenerator>();
+ }
+
+ FormKeyGenerator() = default;
+
void Trace(blink::Visitor* visitor) { visitor->Trace(form_to_key_map_); }
const AtomicString& FormKey(const HTMLFormControlElementWithState&);
void WillDeleteForm(HTMLFormElement*);
private:
- FormKeyGenerator() = default;
-
using FormToKeyMap = HeapHashMap<Member<HTMLFormElement>, AtomicString>;
using FormSignatureToNextIndexMap = HashMap<String, unsigned>;
FormToKeyMap form_to_key_map_;
@@ -357,7 +355,7 @@ static inline void RecordFormStructure(const HTMLFormElement& form,
}
static inline String FormSignature(const HTMLFormElement& form) {
- KURL action_url = form.GetURLAttribute(actionAttr);
+ KURL action_url = form.GetURLAttribute(kActionAttr);
// Remove the query part because it might contain volatile parameters such
// as a session key.
if (!action_url.IsEmpty())
@@ -406,7 +404,7 @@ void FormKeyGenerator::WillDeleteForm(HTMLFormElement* form) {
// ----------------------------------------------------------------------------
DocumentState* DocumentState::Create() {
- return new DocumentState;
+ return MakeGarbageCollected<DocumentState>();
}
void DocumentState::Trace(blink::Visitor* visitor) {
@@ -429,7 +427,7 @@ static String FormStateSignature() {
// attribute value of a form control. The following string literal should
// contain some characters which are rarely used for name attribute values.
DEFINE_STATIC_LOCAL(String, signature,
- ("\n\r?% Blink serialized form state version 9 \n\r=&"));
+ ("\n\r?% Blink serialized form state version 10 \n\r=&"));
return signature;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_controller.h b/chromium/third_party/blink/renderer/core/html/forms/form_controller.h
index 480b5b35034..9ac07b4719f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_controller.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_controller.h
@@ -92,7 +92,11 @@ class DocumentState final : public GarbageCollected<DocumentState> {
class FormController final : public GarbageCollectedFinalized<FormController> {
public:
- static FormController* Create() { return new FormController; }
+ static FormController* Create() {
+ return MakeGarbageCollected<FormController>();
+ }
+
+ FormController();
~FormController();
void Trace(blink::Visitor*);
@@ -113,7 +117,6 @@ class FormController final : public GarbageCollectedFinalized<FormController> {
const Vector<String>& state_vector);
private:
- FormController();
FormControlState TakeStateForFormElement(
const HTMLFormControlElementWithState&);
static void FormStatesFromStateVector(const Vector<String>&,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_data.cc b/chromium/third_party/blink/renderer/core/html/forms/form_data.cc
index 84a4ef69b2f..f3dd566a761 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_data.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_data.cc
@@ -87,9 +87,27 @@ String Normalize(const String& input) {
FormData::FormData(const WTF::TextEncoding& encoding) : encoding_(encoding) {}
-FormData::FormData(HTMLFormElement* form) : encoding_(UTF8Encoding()) {
- if (form)
- form->ConstructFormDataSet(nullptr, *this);
+FormData::FormData(const FormData& form_data)
+ : encoding_(form_data.encoding_),
+ entries_(form_data.entries_),
+ contains_password_data_(form_data.contains_password_data_) {}
+
+FormData::FormData() : encoding_(UTF8Encoding()) {}
+
+FormData* FormData::Create(HTMLFormElement* form,
+ ExceptionState& exception_state) {
+ auto* form_data = MakeGarbageCollected<FormData>();
+ // TODO(tkent): Null check should be unnecessary. We should remove
+ // LegacyInterfaceTypeChecking from form_data.idl. crbug.com/561338
+ if (!form)
+ return form_data;
+ if (!form->ConstructEntryList(nullptr, *form_data)) {
+ DCHECK(RuntimeEnabledFeatures::FormDataEventEnabled());
+ exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
+ "The form is constructing entry list.");
+ return nullptr;
+ }
+ return form_data;
}
void FormData::Trace(blink::Visitor* visitor) {
@@ -98,7 +116,7 @@ void FormData::Trace(blink::Visitor* visitor) {
}
void FormData::append(const String& name, const String& value) {
- entries_.push_back(new Entry(name, value));
+ entries_.push_back(MakeGarbageCollected<Entry>(name, value));
}
void FormData::append(ScriptState* script_state,
@@ -164,11 +182,11 @@ bool FormData::has(const String& name) {
}
void FormData::set(const String& name, const String& value) {
- SetEntry(new Entry(name, value));
+ SetEntry(MakeGarbageCollected<Entry>(name, value));
}
void FormData::set(const String& name, Blob* blob, const String& filename) {
- SetEntry(new Entry(name, blob, filename));
+ SetEntry(MakeGarbageCollected<Entry>(name, blob, filename));
}
void FormData::SetEntry(const Entry* entry) {
@@ -191,7 +209,7 @@ void FormData::SetEntry(const Entry* entry) {
}
void FormData::append(const String& name, Blob* blob, const String& filename) {
- entries_.push_back(new Entry(name, blob, filename));
+ entries_.push_back(MakeGarbageCollected<Entry>(name, blob, filename));
}
void FormData::AppendFromElement(const String& name, int value) {
@@ -199,11 +217,13 @@ void FormData::AppendFromElement(const String& name, int value) {
}
void FormData::AppendFromElement(const String& name, File* file) {
- entries_.push_back(new Entry(Normalize(name), file, String()));
+ entries_.push_back(
+ MakeGarbageCollected<Entry>(Normalize(name), file, String()));
}
void FormData::AppendFromElement(const String& name, const String& value) {
- entries_.push_back(new Entry(Normalize(name), Normalize(value)));
+ entries_.push_back(
+ MakeGarbageCollected<Entry>(Normalize(name), Normalize(value)));
}
CString FormData::Encode(const String& string) const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_data.h b/chromium/third_party/blink/renderer/core/html/forms/form_data.h
index 75cd949f0d6..d3b6aebf6df 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_data.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_data.h
@@ -54,13 +54,22 @@ class CORE_EXPORT FormData final
DEFINE_WRAPPERTYPEINFO();
public:
- static FormData* Create(HTMLFormElement* form = nullptr) {
- return new FormData(form);
+ static FormData* Create() { return MakeGarbageCollected<FormData>(); }
+ static FormData* Create(ExceptionState& exception_state) {
+ return MakeGarbageCollected<FormData>();
}
+ static FormData* Create(HTMLFormElement* form,
+ ExceptionState& exception_state);
static FormData* Create(const WTF::TextEncoding& encoding) {
- return new FormData(encoding);
+ return MakeGarbageCollected<FormData>(encoding);
}
+
+ explicit FormData(const WTF::TextEncoding&);
+ // Clones form_data. This clones |form_data.entries_| Vector, but
+ // doesn't clone entries in it because they are immutable.
+ FormData(const FormData& form_data);
+ FormData();
void Trace(blink::Visitor*) override;
// FormData IDL interface.
@@ -98,8 +107,6 @@ class CORE_EXPORT FormData final
scoped_refptr<EncodedFormData> EncodeMultiPartFormData();
private:
- explicit FormData(const WTF::TextEncoding&);
- explicit FormData(HTMLFormElement*);
void SetEntry(const Entry*);
IterationSource* StartIteration(ScriptState*, ExceptionState&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_data.idl b/chromium/third_party/blink/renderer/core/html/forms/form_data.idl
index 2fcaf4b3ce9..da74a7983f3 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_data.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_data.idl
@@ -37,6 +37,7 @@ typedef (File or USVString) FormDataEntryValue;
// append/set null values instead of throwing. https://crbug.com/561338
[
Constructor(optional HTMLFormElement form),
+ RaisesException=Constructor,
Exposed=(Window,Worker),
LegacyInterfaceTypeChecking
] interface FormData {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_data_event.cc b/chromium/third_party/blink/renderer/core/html/forms/form_data_event.cc
index 6fe89dd1a08..86cb6840115 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_data_event.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_data_event.cc
@@ -4,16 +4,17 @@
#include "third_party/blink/renderer/core/html/forms/form_data_event.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/html/forms/form_data.h"
namespace blink {
FormDataEvent::FormDataEvent(FormData& form_data)
- : Event(EventTypeNames::formdata, Bubbles::kYes, Cancelable::kNo),
+ : Event(event_type_names::kFormdata, Bubbles::kYes, Cancelable::kNo),
form_data_(form_data) {}
FormDataEvent* FormDataEvent::Create(FormData& form_data) {
- return new FormDataEvent(form_data);
+ return MakeGarbageCollected<FormDataEvent>(form_data);
}
void FormDataEvent::Trace(Visitor* visitor) {
@@ -22,7 +23,7 @@ void FormDataEvent::Trace(Visitor* visitor) {
}
const AtomicString& FormDataEvent::InterfaceName() const {
- return EventNames::FormDataEvent;
+ return event_interface_names::kFormDataEvent;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_data_event.h b/chromium/third_party/blink/renderer/core/html/forms/form_data_event.h
index a3a31a506cd..8b94cb06187 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_data_event.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_data_event.h
@@ -16,6 +16,9 @@ class FormDataEvent : public Event {
public:
static FormDataEvent* Create(FormData& form_data);
+
+ FormDataEvent(FormData& form_data);
+
void Trace(Visitor* visitor) override;
FormData* formData() const { return form_data_; };
@@ -23,8 +26,6 @@ class FormDataEvent : public Event {
const AtomicString& InterfaceName() const override;
private:
- FormDataEvent(FormData& form_data);
-
Member<FormData> form_data_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.cc
index 47277e80186..c4c2c1ae087 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.cc
@@ -39,10 +39,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
InputType* HiddenInputType::Create(HTMLInputElement& element) {
- return new HiddenInputType(element);
+ return MakeGarbageCollected<HiddenInputType>(element);
}
void HiddenInputType::Trace(blink::Visitor* visitor) {
@@ -55,7 +55,7 @@ InputTypeView* HiddenInputType::CreateView() {
}
const AtomicString& HiddenInputType::FormControlType() const {
- return InputTypeNames::hidden;
+ return input_type_names::kHidden;
}
bool HiddenInputType::ShouldSaveAndRestoreFormControlState() const {
@@ -85,7 +85,7 @@ void HiddenInputType::SetValue(const String& sanitized_value,
bool,
TextFieldEventBehavior,
TextControlSetValueSelection) {
- GetElement().setAttribute(valueAttr, AtomicString(sanitized_value));
+ GetElement().setAttribute(kValueAttr, AtomicString(sanitized_value));
}
void HiddenInputType::AppendToFormData(FormData& form_data) const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.h
index ba7b9fc22bb..dfcc310a336 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.h
@@ -41,12 +41,14 @@ class HiddenInputType final : public InputType, private InputTypeView {
public:
static InputType* Create(HTMLInputElement&);
+
+ HiddenInputType(HTMLInputElement& element)
+ : InputType(element), InputTypeView(element) {}
+
void Trace(blink::Visitor*) override;
using InputType::GetElement;
private:
- HiddenInputType(HTMLInputElement& element)
- : InputType(element), InputTypeView(element) {}
InputTypeView* CreateView() override;
const AtomicString& FormControlType() const override;
bool ShouldSaveAndRestoreFormControlState() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_button_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_button_element.cc
index d7f49d9291f..91141142733 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_button_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_button_element.cc
@@ -35,19 +35,19 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLButtonElement::HTMLButtonElement(Document& document)
- : HTMLFormControlElement(buttonTag, document),
+ : HTMLFormControlElement(kButtonTag, document),
type_(SUBMIT),
is_activated_submit_(false) {}
HTMLButtonElement* HTMLButtonElement::Create(Document& document) {
- return new HTMLButtonElement(document);
+ return MakeGarbageCollected<HTMLButtonElement>(document);
}
void HTMLButtonElement::setType(const AtomicString& type) {
- setAttribute(typeAttr, type);
+ setAttribute(kTypeAttr, type);
}
LayoutObject* HTMLButtonElement::CreateLayoutObject(const ComputedStyle&) {
@@ -76,7 +76,7 @@ const AtomicString& HTMLButtonElement::FormControlType() const {
bool HTMLButtonElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
// Don't map 'align' attribute. This matches what Firefox and IE do, but
// not Opera. See http://bugs.webkit.org/show_bug.cgi?id=12071
return false;
@@ -87,7 +87,7 @@ bool HTMLButtonElement::IsPresentationAttribute(
void HTMLButtonElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == typeAttr) {
+ if (params.name == kTypeAttr) {
if (DeprecatedEqualIgnoringCase(params.new_value, "reset"))
type_ = RESET;
else if (DeprecatedEqualIgnoringCase(params.new_value, "button"))
@@ -98,14 +98,15 @@ void HTMLButtonElement::ParseAttribute(
if (formOwner() && isConnected())
formOwner()->InvalidateDefaultButtonStyle();
} else {
- if (params.name == formactionAttr)
+ if (params.name == kFormactionAttr)
LogUpdateAttributeIfIsolatedWorldAndInDocument("button", params);
HTMLFormControlElement::ParseAttribute(params);
}
}
void HTMLButtonElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::DOMActivate && !IsDisabledFormControl()) {
+ if (event.type() == event_type_names::kDOMActivate &&
+ !IsDisabledFormControl()) {
if (Form() && type_ == SUBMIT) {
Form()->PrepareForSubmission(event, this);
event.SetDefaultHandled();
@@ -117,13 +118,13 @@ void HTMLButtonElement::DefaultEventHandler(Event& event) {
}
if (event.IsKeyboardEvent()) {
- if (event.type() == EventTypeNames::keydown &&
+ if (event.type() == event_type_names::kKeydown &&
ToKeyboardEvent(event).key() == " ") {
SetActive(true);
// No setDefaultHandled() - IE dispatches a keypress in this case.
return;
}
- if (event.type() == EventTypeNames::keypress) {
+ if (event.type() == event_type_names::kKeypress) {
switch (ToKeyboardEvent(event).charCode()) {
case '\r':
DispatchSimulatedClick(&event);
@@ -135,7 +136,7 @@ void HTMLButtonElement::DefaultEventHandler(Event& event) {
return;
}
}
- if (event.type() == EventTypeNames::keyup &&
+ if (event.type() == event_type_names::kKeyup &&
ToKeyboardEvent(event).key() == " ") {
if (IsActive())
DispatchSimulatedClick(&event);
@@ -182,12 +183,12 @@ void HTMLButtonElement::AccessKeyAction(bool send_mouse_events) {
}
bool HTMLButtonElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == formactionAttr ||
+ return attribute.GetName() == kFormactionAttr ||
HTMLFormControlElement::IsURLAttribute(attribute);
}
const AtomicString& HTMLButtonElement::Value() const {
- return getAttribute(valueAttr);
+ return getAttribute(kValueAttr);
}
bool HTMLButtonElement::RecalcWillValidate() const {
@@ -213,8 +214,8 @@ Node::InsertionNotificationRequest HTMLButtonElement::InsertedInto(
ContainerNode& insertion_point) {
InsertionNotificationRequest request =
HTMLFormControlElement::InsertedInto(insertion_point);
- LogAddElementIfIsolatedWorldAndInDocument("button", typeAttr, formmethodAttr,
- formactionAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("button", kTypeAttr,
+ kFormmethodAttr, kFormactionAttr);
return request;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_button_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_button_element.h
index 240049aeaba..9347255a87d 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_button_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_button_element.h
@@ -34,6 +34,8 @@ class HTMLButtonElement final : public HTMLFormControlElement {
public:
static HTMLButtonElement* Create(Document&);
+ explicit HTMLButtonElement(Document&);
+
void setType(const AtomicString&);
const AtomicString& Value() const;
@@ -41,8 +43,6 @@ class HTMLButtonElement final : public HTMLFormControlElement {
bool WillRespondToMouseClickEvents() override;
private:
- explicit HTMLButtonElement(Document&);
-
enum Type { SUBMIT, RESET, BUTTON };
const AtomicString& FormControlType() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.cc
index 7ded38a407f..e769bce1746 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.cc
@@ -40,11 +40,11 @@
namespace blink {
inline HTMLDataListElement::HTMLDataListElement(Document& document)
- : HTMLElement(HTMLNames::datalistTag, document) {}
+ : HTMLElement(html_names::kDatalistTag, document) {}
HTMLDataListElement* HTMLDataListElement::Create(Document& document) {
UseCounter::Count(document, WebFeature::kDataListElement);
- return new HTMLDataListElement(document);
+ return MakeGarbageCollected<HTMLDataListElement>(document);
}
HTMLDataListOptionsCollection* HTMLDataListElement::options() {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.h
index abb676f53ae..4215b7deb86 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.h
@@ -44,12 +44,13 @@ class CORE_EXPORT HTMLDataListElement final : public HTMLElement {
public:
static HTMLDataListElement* Create(Document&);
+ HTMLDataListElement(Document&);
+
HTMLDataListOptionsCollection* options();
void OptionElementChildrenChanged();
private:
- HTMLDataListElement(Document&);
void ChildrenChanged(const ChildrenChange&) override;
void FinishParsingChildren() override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h
index cc7a21b476f..b74ac125b82 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h
@@ -15,20 +15,19 @@ class HTMLDataListOptionsCollection : public HTMLCollection {
static HTMLDataListOptionsCollection* Create(ContainerNode& owner_node,
CollectionType type) {
DCHECK_EQ(type, kDataListOptions);
- return new HTMLDataListOptionsCollection(owner_node);
+ return MakeGarbageCollected<HTMLDataListOptionsCollection>(owner_node);
}
+ explicit HTMLDataListOptionsCollection(ContainerNode& owner_node)
+ : HTMLCollection(owner_node,
+ kDataListOptions,
+ kDoesNotOverrideItemAfter) {}
+
HTMLOptionElement* Item(unsigned offset) const {
return ToHTMLOptionElement(HTMLCollection::item(offset));
}
bool ElementMatches(const HTMLElement&) const;
-
- private:
- explicit HTMLDataListOptionsCollection(ContainerNode& owner_node)
- : HTMLCollection(owner_node,
- kDataListOptions,
- kDoesNotOverrideItemAfter) {}
};
DEFINE_TYPE_CASTS(HTMLDataListOptionsCollection,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.cc
index 47970055dbb..08e25f7fce1 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.cc
@@ -37,13 +37,13 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLFieldSetElement::HTMLFieldSetElement(Document& document)
- : HTMLFormControlElement(fieldsetTag, document) {}
+ : HTMLFormControlElement(kFieldsetTag, document) {}
HTMLFieldSetElement* HTMLFieldSetElement::Create(Document& document) {
- return new HTMLFieldSetElement(document);
+ return MakeGarbageCollected<HTMLFieldSetElement>(document);
}
bool HTMLFieldSetElement::MatchesValidityPseudoClasses() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.h
index 3895f752f67..60ff21fbbd4 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.h
@@ -36,6 +36,9 @@ class CORE_EXPORT HTMLFieldSetElement final : public HTMLFormControlElement {
public:
static HTMLFieldSetElement* Create(Document&);
+
+ explicit HTMLFieldSetElement(Document&);
+
HTMLLegendElement* Legend() const;
HTMLCollection* elements();
@@ -43,8 +46,6 @@ class CORE_EXPORT HTMLFieldSetElement final : public HTMLFormControlElement {
void DisabledAttributeChanged() override;
private:
- explicit HTMLFieldSetElement(Document&);
-
bool IsEnumeratable() const override { return true; }
bool SupportsFocus() const override;
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.cc
index bd5a3f6e0b3..eab7f277272 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.cc
@@ -34,7 +34,6 @@
#include "third_party/blink/renderer/core/html/forms/html_field_set_element.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
-#include "third_party/blink/renderer/core/html/forms/html_legend_element.h"
#include "third_party/blink/renderer/core/html/forms/validity_state.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -47,15 +46,13 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tag_name,
Document& document)
: LabelableElement(tag_name, document),
autofill_state_(WebAutofillState::kNotFilled),
- ancestor_disabled_state_(kAncestorDisabledStateUnknown),
data_list_ancestor_state_(kUnknown),
- may_have_field_set_ancestor_(true),
has_validation_message_(false),
will_validate_initialized_(false),
will_validate_(true),
@@ -75,29 +72,29 @@ void HTMLFormControlElement::Trace(blink::Visitor* visitor) {
}
String HTMLFormControlElement::formAction() const {
- const AtomicString& action = FastGetAttribute(formactionAttr);
+ const AtomicString& action = FastGetAttribute(kFormactionAttr);
if (action.IsEmpty())
return GetDocument().Url();
return GetDocument().CompleteURL(StripLeadingAndTrailingHTMLSpaces(action));
}
void HTMLFormControlElement::setFormAction(const AtomicString& value) {
- setAttribute(formactionAttr, value);
+ setAttribute(kFormactionAttr, value);
}
String HTMLFormControlElement::formEnctype() const {
- const AtomicString& form_enctype_attr = FastGetAttribute(formenctypeAttr);
+ const AtomicString& form_enctype_attr = FastGetAttribute(kFormenctypeAttr);
if (form_enctype_attr.IsNull())
return g_empty_string;
return FormSubmission::Attributes::ParseEncodingType(form_enctype_attr);
}
void HTMLFormControlElement::setFormEnctype(const AtomicString& value) {
- setAttribute(formenctypeAttr, value);
+ setAttribute(kFormenctypeAttr, value);
}
String HTMLFormControlElement::formMethod() const {
- const AtomicString& form_method_attr = FastGetAttribute(formmethodAttr);
+ const AtomicString& form_method_attr = FastGetAttribute(kFormmethodAttr);
if (form_method_attr.IsNull())
return g_empty_string;
return FormSubmission::Attributes::MethodString(
@@ -105,45 +102,11 @@ String HTMLFormControlElement::formMethod() const {
}
void HTMLFormControlElement::setFormMethod(const AtomicString& value) {
- setAttribute(formmethodAttr, value);
+ setAttribute(kFormmethodAttr, value);
}
bool HTMLFormControlElement::FormNoValidate() const {
- return FastHasAttribute(formnovalidateAttr);
-}
-
-void HTMLFormControlElement::UpdateAncestorDisabledState() const {
- if (!may_have_field_set_ancestor_) {
- ancestor_disabled_state_ = kAncestorDisabledStateEnabled;
- return;
- }
- may_have_field_set_ancestor_ = false;
- // <fieldset> element of which |disabled| attribute affects |this| element.
- HTMLFieldSetElement* disabled_fieldset_ancestor = nullptr;
- ContainerNode* last_legend_ancestor = nullptr;
- for (HTMLElement* ancestor = Traversal<HTMLElement>::FirstAncestor(*this);
- ancestor; ancestor = Traversal<HTMLElement>::FirstAncestor(*ancestor)) {
- if (IsHTMLLegendElement(*ancestor))
- last_legend_ancestor = ancestor;
- if (IsHTMLFieldSetElement(*ancestor)) {
- may_have_field_set_ancestor_ = true;
- if (ancestor->IsDisabledFormControl()) {
- auto* fieldset = ToHTMLFieldSetElement(ancestor);
- if (last_legend_ancestor && last_legend_ancestor == fieldset->Legend())
- continue;
- disabled_fieldset_ancestor = fieldset;
- break;
- }
- }
- }
- ancestor_disabled_state_ = disabled_fieldset_ancestor
- ? kAncestorDisabledStateDisabled
- : kAncestorDisabledStateEnabled;
-}
-
-void HTMLFormControlElement::AncestorDisabledStateWasChanged() {
- ancestor_disabled_state_ = kAncestorDisabledStateUnknown;
- DisabledAttributeChanged();
+ return FastHasAttribute(kFormnovalidateAttr);
}
void HTMLFormControlElement::Reset() {
@@ -154,7 +117,7 @@ void HTMLFormControlElement::Reset() {
void HTMLFormControlElement::AttributeChanged(
const AttributeModificationParams& params) {
HTMLElement::AttributeChanged(params);
- if (params.name == disabledAttr &&
+ if (params.name == kDisabledAttr &&
params.old_value.IsNull() != params.new_value.IsNull()) {
DisabledAttributeChanged();
if (params.reason == AttributeModificationReason::kDirectly &&
@@ -166,10 +129,10 @@ void HTMLFormControlElement::AttributeChanged(
void HTMLFormControlElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == formAttr) {
+ if (name == kFormAttr) {
FormAttributeChanged();
UseCounter::Count(GetDocument(), WebFeature::kFormAttribute);
- } else if (name == readonlyAttr) {
+ } else if (name == kReadonlyAttr) {
if (params.old_value.IsNull() != params.new_value.IsNull()) {
SetNeedsWillValidateCheck();
PseudoStateChanged(CSSSelector::kPseudoReadOnly);
@@ -177,11 +140,11 @@ void HTMLFormControlElement::ParseAttribute(
if (LayoutObject* o = GetLayoutObject())
o->InvalidateIfControlStateChanged(kReadOnlyControlState);
}
- } else if (name == requiredAttr) {
+ } else if (name == kRequiredAttr) {
if (params.old_value.IsNull() != params.new_value.IsNull())
RequiredAttributeChanged();
UseCounter::Count(GetDocument(), WebFeature::kRequiredAttribute);
- } else if (name == autofocusAttr) {
+ } else if (name == kAutofocusAttr) {
HTMLElement::ParseAttribute(params);
UseCounter::Count(GetDocument(), WebFeature::kAutoFocusAttribute);
} else {
@@ -195,8 +158,7 @@ void HTMLFormControlElement::DisabledAttributeChanged() {
EventDispatchForbiddenScope event_forbidden;
SetNeedsWillValidateCheck();
- PseudoStateChanged(CSSSelector::kPseudoDisabled);
- PseudoStateChanged(CSSSelector::kPseudoEnabled);
+ ListedElement::DisabledAttributeChanged();
if (LayoutObject* o = GetLayoutObject())
o->InvalidateIfControlStateChanged(kEnabledControlState);
@@ -217,7 +179,7 @@ void HTMLFormControlElement::RequiredAttributeChanged() {
}
bool HTMLFormControlElement::IsReadOnly() const {
- return FastHasAttribute(HTMLNames::readonlyAttr);
+ return FastHasAttribute(html_names::kReadonlyAttr);
}
bool HTMLFormControlElement::IsDisabledOrReadOnly() const {
@@ -229,7 +191,7 @@ bool HTMLFormControlElement::SupportsAutofocus() const {
}
bool HTMLFormControlElement::IsAutofocusable() const {
- return FastHasAttribute(autofocusAttr) && SupportsAutofocus();
+ return FastHasAttribute(kAutofocusAttr) && SupportsAutofocus();
}
void HTMLFormControlElement::SetAutofillState(WebAutofillState autofill_state) {
@@ -247,7 +209,7 @@ void HTMLFormControlElement::SetAutofillSection(const WebString& section) {
}
const AtomicString& HTMLFormControlElement::autocapitalize() const {
- if (!FastGetAttribute(autocapitalizeAttr).IsEmpty())
+ if (!FastGetAttribute(kAutocapitalizeAttr).IsEmpty())
return HTMLElement::autocapitalize();
// If the form control itself does not have the autocapitalize attribute set,
@@ -299,13 +261,10 @@ void HTMLFormControlElement::DidMoveToNewDocument(Document& old_document) {
Node::InsertionNotificationRequest HTMLFormControlElement::InsertedInto(
ContainerNode& insertion_point) {
- ancestor_disabled_state_ = kAncestorDisabledStateUnknown;
- // Force traversal to find ancestor
- may_have_field_set_ancestor_ = true;
data_list_ancestor_state_ = kUnknown;
- SetNeedsWillValidateCheck();
HTMLElement::InsertedInto(insertion_point);
ListedElement::InsertedInto(insertion_point);
+ SetNeedsWillValidateCheck();
FieldSetAncestorsSetNeedsValidityCheck(&insertion_point);
// Trigger for elements outside of forms.
@@ -319,11 +278,10 @@ void HTMLFormControlElement::RemovedFrom(ContainerNode& insertion_point) {
FieldSetAncestorsSetNeedsValidityCheck(&insertion_point);
HideVisibleValidationMessage();
has_validation_message_ = false;
- ancestor_disabled_state_ = kAncestorDisabledStateUnknown;
data_list_ancestor_state_ = kUnknown;
- SetNeedsWillValidateCheck();
HTMLElement::RemovedFrom(insertion_point);
ListedElement::RemovedFrom(insertion_point);
+ SetNeedsWillValidateCheck();
}
void HTMLFormControlElement::WillChangeForm() {
@@ -363,7 +321,7 @@ void HTMLFormControlElement::FieldSetAncestorsSetNeedsValidityCheck(
}
void HTMLFormControlElement::DispatchChangeEvent() {
- DispatchScopedEvent(*Event::CreateBubble(EventTypeNames::change));
+ DispatchScopedEvent(*Event::CreateBubble(event_type_names::kChange));
}
HTMLFormElement* HTMLFormControlElement::formOwner() const {
@@ -371,18 +329,13 @@ HTMLFormElement* HTMLFormControlElement::formOwner() const {
}
bool HTMLFormControlElement::IsDisabledFormControl() const {
- if (FastHasAttribute(disabledAttr))
- return true;
-
// Since the MHTML is loaded in sandboxing mode with form submission and
// script execution disabled, we should gray out all form control elements
// to indicate that the form cannot be worked on.
if (GetDocument().Fetcher()->Archive())
return true;
- if (ancestor_disabled_state_ == kAncestorDisabledStateUnknown)
- UpdateAncestorDisabledState();
- return ancestor_disabled_state_ == kAncestorDisabledStateDisabled;
+ return IsActuallyDisabled();
}
bool HTMLFormControlElement::MatchesEnabledPseudoClass() const {
@@ -390,11 +343,11 @@ bool HTMLFormControlElement::MatchesEnabledPseudoClass() const {
}
bool HTMLFormControlElement::IsRequired() const {
- return FastHasAttribute(requiredAttr);
+ return FastHasAttribute(kRequiredAttr);
}
String HTMLFormControlElement::ResultForDialogSubmit() {
- return FastGetAttribute(valueAttr);
+ return FastGetAttribute(kValueAttr);
}
void HTMLFormControlElement::DidRecalcStyle(StyleRecalcChange) {
@@ -546,7 +499,7 @@ bool HTMLFormControlElement::checkValidity(
return false;
Document* original_document = &GetDocument();
DispatchEventResult dispatch_result =
- DispatchEvent(*Event::CreateCancelable(EventTypeNames::invalid));
+ DispatchEvent(*Event::CreateCancelable(event_type_names::kInvalid));
if (dispatch_result == DispatchEventResult::kNotCanceled &&
unhandled_invalid_controls && isConnected() &&
original_document == GetDocument())
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.h
index 0ec0570f6b2..42397ca9ed1 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.h
@@ -62,8 +62,6 @@ class CORE_EXPORT HTMLFormControlElement : public LabelableElement,
void setFormMethod(const AtomicString&);
bool FormNoValidate() const;
- void AncestorDisabledStateWasChanged();
-
void Reset();
void DispatchChangeEvent();
@@ -162,7 +160,7 @@ class CORE_EXPORT HTMLFormControlElement : public LabelableElement,
void AttributeChanged(const AttributeModificationParams&) override;
void ParseAttribute(const AttributeModificationParams&) override;
virtual void RequiredAttributeChanged();
- virtual void DisabledAttributeChanged();
+ void DisabledAttributeChanged() override;
void AttachLayoutTree(AttachContext&) override;
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
@@ -194,7 +192,6 @@ class CORE_EXPORT HTMLFormControlElement : public LabelableElement,
bool IsValidElement() override;
bool MatchesValidityPseudoClasses() const override;
- void UpdateAncestorDisabledState() const;
ValidationMessageClient* GetValidationMessageClient() const;
@@ -208,16 +205,8 @@ class CORE_EXPORT HTMLFormControlElement : public LabelableElement,
WebString autofill_section_;
enum WebAutofillState autofill_state_;
- enum AncestorDisabledState {
- kAncestorDisabledStateUnknown,
- kAncestorDisabledStateEnabled,
- kAncestorDisabledStateDisabled
- };
-
- mutable AncestorDisabledState ancestor_disabled_state_;
enum DataListAncestorState { kUnknown, kInsideDataList, kNotInsideDataList };
mutable enum DataListAncestorState data_list_ancestor_state_;
- mutable bool may_have_field_set_ancestor_ : 1;
bool has_validation_message_ : 1;
// The initial value of will_validate_ depends on the derived class. We can't
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_test.cc b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_test.cc
index d85fbda8d19..a152ce28a85 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_test.cc
@@ -75,7 +75,7 @@ TEST_F(HTMLFormControlElementTest, customValidationMessageTextDirection) {
input->setCustomValidity(
String::FromUTF8("\xD8\xB9\xD8\xB1\xD8\xA8\xD9\x89"));
input->setAttribute(
- HTMLNames::titleAttr,
+ html_names::kTitleAttr,
AtomicString::FromUTF8("\xD8\xB9\xD8\xB1\xD8\xA8\xD9\x89"));
String message = input->validationMessage().StripWhiteSpace();
@@ -135,7 +135,8 @@ TEST_F(HTMLFormControlElementTest, DoNotUpdateLayoutDuringDOMMutation) {
GetDocument().documentElement()->SetInnerHTMLFromString("<select></select>");
HTMLFormControlElement* const select =
ToHTMLFormControlElement(GetDocument().QuerySelector("select"));
- auto* const optgroup = GetDocument().CreateRawElement(HTMLNames::optgroupTag);
+ auto* const optgroup =
+ GetDocument().CreateRawElement(html_names::kOptgroupTag);
auto* validation_client = new MockFormValidationMessageClient();
GetDocument().GetPage()->SetValidationMessageClientForTesting(
validation_client);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.cc b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.cc
index 3971c465fe6..48c95e73363 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.cc
@@ -142,7 +142,7 @@ bool HTMLFormControlElementWithState::ShouldAutocomplete() const {
}
bool HTMLFormControlElementWithState::IsWearingAutofillAnchorMantle() const {
- return FormControlType() == InputTypeNames::hidden;
+ return FormControlType() == input_type_names::kHidden;
}
String HTMLFormControlElementWithState::IDLExposedAutofillValue() const {
@@ -152,7 +152,7 @@ String HTMLFormControlElementWithState::IDLExposedAutofillValue() const {
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill-processing-model
// 1. If the element has no autocomplete attribute, then jump to the step
// labeled default.
- const AtomicString& value = FastGetAttribute(HTMLNames::autocompleteAttr);
+ const AtomicString& value = FastGetAttribute(html_names::kAutocompleteAttr);
if (value.IsNull())
return g_empty_string;
@@ -281,7 +281,7 @@ String HTMLFormControlElementWithState::IDLExposedAutofillValue() const {
void HTMLFormControlElementWithState::setIDLExposedAutofillValue(
const String& autocomplete_value) {
- setAttribute(HTMLNames::autocompleteAttr, AtomicString(autocomplete_value));
+ setAttribute(html_names::kAutocompleteAttr, AtomicString(autocomplete_value));
}
void HTMLFormControlElementWithState::NotifyFormStateChanged() {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.cc b/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.cc
index 8f0d4784c76..d7319390bda 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.cc
@@ -33,7 +33,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// Since the collections are to be "live", we have to do the
// calculation every time if anything has changed.
@@ -50,7 +50,7 @@ HTMLFormControlsCollection* HTMLFormControlsCollection::Create(
ContainerNode& owner_node,
CollectionType type) {
DCHECK_EQ(type, kFormControls);
- return new HTMLFormControlsCollection(owner_node);
+ return MakeGarbageCollected<HTMLFormControlsCollection>(owner_node);
}
HTMLFormControlsCollection::~HTMLFormControlsCollection() = default;
@@ -107,7 +107,7 @@ void HTMLFormControlsCollection::InvalidateCache(Document* old_document) const {
static HTMLElement* FirstNamedItem(const ListedElement::List& elements_array,
const QualifiedName& attr_name,
const String& name) {
- DCHECK(attr_name == idAttr || attr_name == nameAttr);
+ DCHECK(attr_name == kIdAttr || attr_name == kNameAttr);
for (const auto& listed_element : elements_array) {
HTMLElement* element = ToHTMLElement(listed_element);
@@ -125,9 +125,9 @@ HTMLElement* HTMLFormControlsCollection::namedItem(
// attribute. If a match is not found, the method then searches for an
// object with a matching name attribute, but only on those elements
// that are allowed a name attribute.
- if (HTMLElement* item = FirstNamedItem(ListedElements(), idAttr, name))
+ if (HTMLElement* item = FirstNamedItem(ListedElements(), kIdAttr, name))
return item;
- return FirstNamedItem(ListedElements(), nameAttr, name);
+ return FirstNamedItem(ListedElements(), kNameAttr, name);
}
void HTMLFormControlsCollection::UpdateIdNameCache() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.h b/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.h
index 7f9c999cca6..590ea51df68 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.h
@@ -44,6 +44,7 @@ class HTMLFormControlsCollection final : public HTMLCollection {
public:
static HTMLFormControlsCollection* Create(ContainerNode&, CollectionType);
+ explicit HTMLFormControlsCollection(ContainerNode&);
~HTMLFormControlsCollection() override;
HTMLElement* item(unsigned offset) const {
@@ -56,8 +57,6 @@ class HTMLFormControlsCollection final : public HTMLCollection {
void Trace(blink::Visitor*) override;
private:
- explicit HTMLFormControlsCollection(ContainerNode&);
-
void UpdateIdNameCache() const override;
void SupportedPropertyNames(Vector<String>& names) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_form_element.cc
index 62508b4b24f..471e80e6cf1 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_element.cc
@@ -44,6 +44,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/remote_frame.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/html/forms/form_controller.h"
#include "third_party/blink/renderer/core/html/forms/form_data.h"
#include "third_party/blink/renderer/core/html/forms/form_data_event.h"
@@ -65,10 +66,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLFormElement::HTMLFormElement(Document& document)
- : HTMLElement(formTag, document),
+ : HTMLElement(kFormTag, document),
listed_elements_are_dirty_(false),
image_elements_are_dirty_(false),
has_elements_associated_by_parser_(false),
@@ -81,7 +82,7 @@ HTMLFormElement::HTMLFormElement(Document& document)
HTMLFormElement* HTMLFormElement::Create(Document& document) {
UseCounter::Count(document, WebFeature::kFormElement);
- return new HTMLFormElement(document);
+ return MakeGarbageCollected<HTMLFormElement>(document);
}
HTMLFormElement::~HTMLFormElement() = default;
@@ -107,7 +108,7 @@ bool HTMLFormElement::IsValidElement() {
Node::InsertionNotificationRequest HTMLFormElement::InsertedInto(
ContainerNode& insertion_point) {
HTMLElement::InsertedInto(insertion_point);
- LogAddElementIfIsolatedWorldAndInDocument("form", methodAttr, actionAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("form", kMethodAttr, kActionAttr);
if (insertion_point.isConnected())
GetDocument().DidAssociateFormControl(this);
return kInsertionDone;
@@ -156,8 +157,8 @@ void HTMLFormElement::HandleLocalEvents(Event& event) {
Node* target_node = event.target()->ToNode();
if (event.eventPhase() != Event::kCapturingPhase && target_node &&
target_node != this &&
- (event.type() == EventTypeNames::submit ||
- event.type() == EventTypeNames::reset)) {
+ (event.type() == event_type_names::kSubmit ||
+ event.type() == event_type_names::kReset)) {
event.stopPropagation();
return;
}
@@ -289,7 +290,7 @@ void HTMLFormElement::PrepareForSubmission(
"the end of the file. Please add an explicit end tag "
"('</" +
tag_name + ">')"));
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
return;
}
}
@@ -310,8 +311,8 @@ void HTMLFormElement::PrepareForSubmission(
true);
frame->Client()->DispatchWillSendSubmitEvent(this);
should_submit =
- DispatchEvent(*Event::CreateCancelableBubble(EventTypeNames::submit)) ==
- DispatchEventResult::kNotCanceled;
+ DispatchEvent(*Event::CreateCancelableBubble(
+ event_type_names::kSubmit)) == DispatchEventResult::kNotCanceled;
}
if (should_submit) {
planned_navigation_ = nullptr;
@@ -355,6 +356,15 @@ void HTMLFormElement::Submit(Event* event,
return;
}
+ if (is_constructing_entry_list_) {
+ DCHECK(RuntimeEnabledFeatures::FormDataEventEnabled());
+ GetDocument().AddConsoleMessage(
+ ConsoleMessage::Create(kJSMessageSource, kWarningMessageLevel,
+ "Form submission canceled because the form is "
+ "constructing entry list"));
+ return;
+ }
+
if (is_submitting_)
return;
@@ -402,14 +412,12 @@ void HTMLFormElement::Submit(Event* event,
}
}
-void HTMLFormElement::ConstructFormDataSet(
- HTMLFormControlElement* submit_button,
- FormData& form_data) {
- // TODO(tkent): We might move the event dispatching later than the
- // ListedElements iteration.
- if (RuntimeEnabledFeatures::FormDataEventEnabled())
- DispatchEvent(*FormDataEvent::Create(form_data));
-
+bool HTMLFormElement::ConstructEntryList(HTMLFormControlElement* submit_button,
+ FormData& form_data) {
+ if (is_constructing_entry_list_) {
+ return false;
+ }
+ base::AutoReset<bool> entry_list_scope(&is_constructing_entry_list_, true);
if (submit_button)
submit_button->SetActivatedSubmit(true);
for (ListedElement* control : ListedElements()) {
@@ -418,13 +426,17 @@ void HTMLFormElement::ConstructFormDataSet(
if (!element.IsDisabledFormControl())
control->AppendToFormData(form_data);
if (auto* input = ToHTMLInputElementOrNull(element)) {
- if (input->type() == InputTypeNames::password &&
+ if (input->type() == input_type_names::kPassword &&
!input->value().IsEmpty())
form_data.SetContainsPasswordData(true);
}
}
+ if (RuntimeEnabledFeatures::FormDataEventEnabled())
+ DispatchEvent(*FormDataEvent::Create(form_data));
+
if (submit_button)
submit_button->SetActivatedSubmit(false);
+ return true;
}
void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) {
@@ -451,7 +463,7 @@ void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) {
}
if (submission->Action().ProtocolIsJavaScript()) {
- if (FastHasAttribute(disabledAttr)) {
+ if (FastHasAttribute(kDisabledAttr)) {
UseCounter::Count(GetDocument(),
WebFeature::kFormDisabledAttributePresentAndSubmit);
}
@@ -479,7 +491,7 @@ void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) {
UseCounter::Count(GetDocument().GetFrame(),
WebFeature::kMixedContentFormsSubmitted);
}
- if (FastHasAttribute(disabledAttr)) {
+ if (FastHasAttribute(kDisabledAttr)) {
UseCounter::Count(GetDocument(),
WebFeature::kFormDisabledAttributePresentAndSubmit);
}
@@ -510,7 +522,7 @@ void HTMLFormElement::reset() {
is_in_reset_function_ = true;
- if (DispatchEvent(*Event::CreateCancelableBubble(EventTypeNames::reset)) !=
+ if (DispatchEvent(*Event::CreateCancelableBubble(event_type_names::kReset)) !=
DispatchEventResult::kNotCanceled) {
is_in_reset_function_ = false;
return;
@@ -530,7 +542,7 @@ void HTMLFormElement::reset() {
void HTMLFormElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == actionAttr) {
+ if (name == kActionAttr) {
attributes_.ParseAction(params.new_value);
LogUpdateAttributeIfIsolatedWorldAndInDocument("form", params);
@@ -547,15 +559,15 @@ void HTMLFormElement::ParseAttribute(
UseCounter::Count(GetDocument().GetFrame(),
WebFeature::kMixedContentFormPresent);
}
- } else if (name == targetAttr) {
+ } else if (name == kTargetAttr) {
attributes_.SetTarget(params.new_value);
- } else if (name == methodAttr) {
+ } else if (name == kMethodAttr) {
attributes_.UpdateMethodType(params.new_value);
- } else if (name == enctypeAttr) {
+ } else if (name == kEnctypeAttr) {
attributes_.UpdateEncodingType(params.new_value);
- } else if (name == accept_charsetAttr) {
+ } else if (name == kAcceptCharsetAttr) {
attributes_.SetAcceptCharset(params.new_value);
- } else if (name == disabledAttr) {
+ } else if (name == kDisabledAttr) {
UseCounter::Count(GetDocument(), WebFeature::kFormDisabledAttributePresent);
} else {
HTMLElement::ParseAttribute(params);
@@ -565,7 +577,7 @@ void HTMLFormElement::ParseAttribute(
void HTMLFormElement::Associate(ListedElement& e) {
listed_elements_are_dirty_ = true;
listed_elements_.clear();
- if (ToHTMLElement(e).FastHasAttribute(formAttr))
+ if (ToHTMLElement(e).FastHasAttribute(kFormAttr))
has_elements_associated_by_form_attribute_ = true;
}
@@ -576,12 +588,12 @@ void HTMLFormElement::Disassociate(ListedElement& e) {
}
bool HTMLFormElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == actionAttr ||
+ return attribute.GetName() == kActionAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLFormElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == actionAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kActionAttr || HTMLElement::HasLegalLinkAttribute(name);
}
void HTMLFormElement::Associate(HTMLImageElement& e) {
@@ -614,6 +626,8 @@ void HTMLFormElement::CollectListedElements(
ListedElement* listed_element = nullptr;
if (element.IsFormControlElement())
listed_element = ToHTMLFormControlElement(&element);
+ else if (element.IsFormAssociatedCustomElement())
+ listed_element = &element.EnsureElementInternals();
else if (auto* object = ToHTMLObjectElementOrNull(element))
listed_element = object;
else
@@ -667,7 +681,7 @@ String HTMLFormElement::GetName() const {
}
bool HTMLFormElement::NoValidate() const {
- return FastHasAttribute(novalidateAttr);
+ return FastHasAttribute(kNovalidateAttr);
}
String HTMLFormElement::action() const {
@@ -679,11 +693,11 @@ String HTMLFormElement::action() const {
}
void HTMLFormElement::setAction(const AtomicString& value) {
- setAttribute(actionAttr, value);
+ setAttribute(kActionAttr, value);
}
void HTMLFormElement::setEnctype(const AtomicString& value) {
- setAttribute(enctypeAttr, value);
+ setAttribute(kEnctypeAttr, value);
}
String HTMLFormElement::method() const {
@@ -691,7 +705,7 @@ String HTMLFormElement::method() const {
}
void HTMLFormElement::setMethod(const AtomicString& value) {
- setAttribute(methodAttr, value);
+ setAttribute(kMethodAttr, value);
}
HTMLFormControlElement* HTMLFormElement::FindDefaultButton() const {
@@ -768,7 +782,7 @@ void HTMLFormElement::AddToPastNamesMap(Element* element,
if (past_name.IsEmpty())
return;
if (!past_names_map_)
- past_names_map_ = new PastNamesMap;
+ past_names_map_ = MakeGarbageCollected<PastNamesMap>();
past_names_map_->Set(past_name, element);
}
@@ -800,7 +814,7 @@ void HTMLFormElement::GetNamedElements(
}
bool HTMLFormElement::ShouldAutocomplete() const {
- return !DeprecatedEqualIgnoringCase(FastGetAttribute(autocompleteAttr),
+ return !DeprecatedEqualIgnoringCase(FastGetAttribute(kAutocompleteAttr),
"off");
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_form_element.h
index 14cefa21cd5..422613b158a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_element.h
@@ -45,6 +45,8 @@ class CORE_EXPORT HTMLFormElement final : public HTMLElement {
public:
static HTMLFormElement* Create(Document&);
+
+ explicit HTMLFormElement(Document&);
~HTMLFormElement() override;
void Trace(blink::Visitor*) override;
@@ -105,16 +107,15 @@ class CORE_EXPORT HTMLFormElement final : public HTMLElement {
void AnonymousNamedGetter(const AtomicString& name, RadioNodeListOrElement&);
void InvalidateDefaultButtonStyle() const;
- // 'construct the form data set'
+ // 'construct the entry list'
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set
- void ConstructFormDataSet(HTMLFormControlElement* submit_button,
- FormData& form_data);
+ // Returns false if this form is already running this function.
+ bool ConstructEntryList(HTMLFormControlElement* submit_button,
+ FormData& form_data);
unsigned UniqueRendererFormId() const { return unique_renderer_form_id_; }
private:
- explicit HTMLFormElement(Document&);
-
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
void FinishParsingChildren() override;
@@ -172,6 +173,7 @@ class CORE_EXPORT HTMLFormElement final : public HTMLElement {
bool is_submitting_ = false;
bool in_user_js_submit_event_ = false;
+ bool is_constructing_entry_list_ = false;
bool listed_elements_are_dirty_ : 1;
bool image_elements_are_dirty_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_input_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_input_element.cc
index cc0a986a50a..9922ca55e07 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_input_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_input_element.cc
@@ -34,8 +34,8 @@
#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/dom/id_target_observer.h"
@@ -78,18 +78,19 @@
namespace blink {
using ValueMode = InputType::ValueMode;
-using namespace HTMLNames;
+using namespace html_names;
class ListAttributeTargetObserver : public IdTargetObserver {
public:
static ListAttributeTargetObserver* Create(const AtomicString& id,
HTMLInputElement*);
+
+ ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement*);
+
void Trace(blink::Visitor*) override;
void IdTargetChanged() override;
private:
- ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement*);
-
Member<HTMLInputElement> element_;
};
@@ -97,7 +98,7 @@ const int kDefaultSize = 20;
HTMLInputElement::HTMLInputElement(Document& document,
const CreateElementFlags flags)
- : TextControlElement(inputTag, document),
+ : TextControlElement(kInputTag, document),
size_(kDefaultSize),
has_dirty_value_(false),
is_checked_(false),
@@ -125,7 +126,7 @@ HTMLInputElement::HTMLInputElement(Document& document,
HTMLInputElement* HTMLInputElement::Create(Document& document,
const CreateElementFlags flags) {
- auto* input_element = new HTMLInputElement(document, flags);
+ auto* input_element = MakeGarbageCollected<HTMLInputElement>(document, flags);
if (!flags.IsCreatedByParser()) {
DCHECK(input_element->input_type_view_->NeedsShadowSubtree());
input_element->CreateUserAgentShadowRoot();
@@ -164,7 +165,7 @@ const AtomicString& HTMLInputElement::GetName() const {
return name_.IsNull() ? g_empty_atom : name_;
}
-FileChooserFileInfoList HTMLInputElement::FilesFromFileInputFormControlState(
+Vector<String> HTMLInputElement::FilesFromFileInputFormControlState(
const FormControlState& state) {
return FileInputType::FilesFromFormControlState(state);
}
@@ -303,7 +304,7 @@ bool HTMLInputElement::MayTriggerVirtualKeyboard() const {
void HTMLInputElement::UpdateFocusAppearanceWithOptions(
SelectionBehaviorOnFocus selection_behavior,
- const FocusOptions& options) {
+ const FocusOptions* options) {
if (IsTextField()) {
switch (selection_behavior) {
case SelectionBehaviorOnFocus::kReset:
@@ -319,7 +320,7 @@ void HTMLInputElement::UpdateFocusAppearanceWithOptions(
// FrameSelection::revealSelection(). It doesn't scroll correctly in a
// case of RangeSelection. crbug.com/443061.
GetDocument().EnsurePaintLocationDataValidForNode(this);
- if (!options.preventScroll()) {
+ if (!options->preventScroll()) {
if (GetLayoutObject()) {
GetLayoutObject()->ScrollRectToVisible(BoundingBoxForScrollIntoView(),
WebScrollIntoViewParams());
@@ -351,7 +352,7 @@ void HTMLInputElement::DispatchFocusInEvent(
Element* old_focused_element,
WebFocusType type,
InputDeviceCapabilities* source_capabilities) {
- if (event_type == EventTypeNames::DOMFocusIn)
+ if (event_type == event_type_names::kDOMFocusIn)
input_type_view_->HandleFocusInEvent(old_focused_element, type);
HTMLFormControlElementWithState::DispatchFocusInEvent(
event_type, old_focused_element, type, source_capabilities);
@@ -362,7 +363,7 @@ void HTMLInputElement::HandleBlurEvent() {
}
void HTMLInputElement::setType(const AtomicString& type) {
- setAttribute(typeAttr, type);
+ setAttribute(kTypeAttr, type);
}
void HTMLInputElement::InitializeTypeInParsing() {
@@ -371,13 +372,13 @@ void HTMLInputElement::InitializeTypeInParsing() {
DCHECK(!input_type_view_);
const AtomicString& new_type_name =
- InputType::NormalizeTypeName(FastGetAttribute(typeAttr));
+ InputType::NormalizeTypeName(FastGetAttribute(kTypeAttr));
input_type_ = InputType::Create(*this, new_type_name);
input_type_view_ = input_type_->CreateView();
- String default_value = FastGetAttribute(valueAttr);
+ String default_value = FastGetAttribute(kValueAttr);
if (input_type_->GetValueMode() == ValueMode::kValue)
non_attribute_value_ = SanitizeValue(default_value);
- has_been_password_field_ |= new_type_name == InputTypeNames::password;
+ has_been_password_field_ |= new_type_name == input_type_names::kPassword;
if (input_type_view_->NeedsShadowSubtree()) {
CreateUserAgentShadowRoot();
@@ -397,7 +398,7 @@ void HTMLInputElement::UpdateType() {
DCHECK(input_type_view_);
const AtomicString& new_type_name =
- InputType::NormalizeTypeName(FastGetAttribute(typeAttr));
+ InputType::NormalizeTypeName(FastGetAttribute(kTypeAttr));
if (input_type_->FormControlType() == new_type_name)
return;
@@ -434,7 +435,7 @@ void HTMLInputElement::UpdateType() {
bool placeholder_changed =
input_type_->SupportsPlaceholder() != new_type->SupportsPlaceholder();
- has_been_password_field_ |= new_type_name == InputTypeNames::password;
+ has_been_password_field_ |= new_type_name == input_type_names::kPassword;
input_type_ = new_type;
input_type_view_ = input_type_->CreateView();
@@ -468,7 +469,7 @@ void HTMLInputElement::UpdateType() {
(new_value_mode == ValueMode::kDefault ||
new_value_mode == ValueMode::kDefaultOn)) {
if (HasDirtyValue())
- setAttribute(valueAttr, AtomicString(non_attribute_value_));
+ setAttribute(kValueAttr, AtomicString(non_attribute_value_));
non_attribute_value_ = String();
has_dirty_value_ = false;
}
@@ -480,7 +481,7 @@ void HTMLInputElement::UpdateType() {
// set the control's dirty value flag to false.
else if (old_value_mode != ValueMode::kValue &&
new_value_mode == ValueMode::kValue) {
- AtomicString value_string = FastGetAttribute(valueAttr);
+ AtomicString value_string = FastGetAttribute(kValueAttr);
input_type_->WarnIfValueIsInvalid(value_string);
non_attribute_value_ = SanitizeValue(value_string);
has_dirty_value_ = false;
@@ -497,7 +498,7 @@ void HTMLInputElement::UpdateType() {
} else {
// ValueMode wasn't changed, or kDefault <-> kDefaultOn.
if (!HasDirtyValue()) {
- String default_value = FastGetAttribute(valueAttr);
+ String default_value = FastGetAttribute(kValueAttr);
if (!default_value.IsNull())
input_type_->WarnIfValueIsInvalid(default_value);
}
@@ -520,20 +521,20 @@ void HTMLInputElement::UpdateType() {
input_type_->ShouldRespectHeightAndWidthAttributes()) {
DCHECK(GetElementData());
AttributeCollection attributes = AttributesWithoutUpdate();
- if (const Attribute* height = attributes.Find(heightAttr)) {
+ if (const Attribute* height = attributes.Find(kHeightAttr)) {
TextControlElement::AttributeChanged(AttributeModificationParams(
- heightAttr, height->Value(), height->Value(),
+ kHeightAttr, height->Value(), height->Value(),
AttributeModificationReason::kDirectly));
}
- if (const Attribute* width = attributes.Find(widthAttr)) {
- TextControlElement::AttributeChanged(
- AttributeModificationParams(widthAttr, width->Value(), width->Value(),
- AttributeModificationReason::kDirectly));
+ if (const Attribute* width = attributes.Find(kWidthAttr)) {
+ TextControlElement::AttributeChanged(AttributeModificationParams(
+ kWidthAttr, width->Value(), width->Value(),
+ AttributeModificationReason::kDirectly));
}
- if (const Attribute* align = attributes.Find(alignAttr)) {
- TextControlElement::AttributeChanged(
- AttributeModificationParams(alignAttr, align->Value(), align->Value(),
- AttributeModificationReason::kDirectly));
+ if (const Attribute* align = attributes.Find(kAlignAttr)) {
+ TextControlElement::AttributeChanged(AttributeModificationParams(
+ kAlignAttr, align->Value(), align->Value(),
+ AttributeModificationReason::kDirectly));
}
}
@@ -691,9 +692,9 @@ void HTMLInputElement::AccessKeyAction(bool send_mouse_events) {
bool HTMLInputElement::IsPresentationAttribute(
const QualifiedName& name) const {
// FIXME: Remove type check.
- if (name == vspaceAttr || name == hspaceAttr || name == alignAttr ||
- name == widthAttr || name == heightAttr ||
- (name == borderAttr && type() == InputTypeNames::image))
+ if (name == kVspaceAttr || name == kHspaceAttr || name == kAlignAttr ||
+ name == kWidthAttr || name == kHeightAttr ||
+ (name == kBorderAttr && type() == input_type_names::kImage))
return true;
return TextControlElement::IsPresentationAttribute(name);
}
@@ -702,23 +703,23 @@ void HTMLInputElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == vspaceAttr) {
+ if (name == kVspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
- } else if (name == hspaceAttr) {
+ } else if (name == kHspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
- } else if (name == alignAttr) {
+ } else if (name == kAlignAttr) {
if (input_type_->ShouldRespectAlignAttribute())
ApplyAlignmentAttributeToStyle(value, style);
- } else if (name == widthAttr) {
+ } else if (name == kWidthAttr) {
if (input_type_->ShouldRespectHeightAndWidthAttributes())
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
if (input_type_->ShouldRespectHeightAndWidthAttributes())
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
- } else if (name == borderAttr &&
- type() == InputTypeNames::image) { // FIXME: Remove type check.
+ } else if (name == kBorderAttr &&
+ type() == input_type_names::kImage) { // FIXME: Remove type check.
ApplyBorderAttributeToStyle(value, style);
} else {
TextControlElement::CollectStyleForPresentationAttribute(name, value,
@@ -733,12 +734,12 @@ void HTMLInputElement::ParseAttribute(
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == nameAttr) {
+ if (name == kNameAttr) {
RemoveFromRadioButtonGroup();
name_ = value;
AddToRadioButtonGroup();
TextControlElement::ParseAttribute(params);
- } else if (name == autocompleteAttr) {
+ } else if (name == kAutocompleteAttr) {
if (DeprecatedEqualIgnoringCase(value, "off")) {
autocomplete_ = kOff;
} else {
@@ -747,9 +748,9 @@ void HTMLInputElement::ParseAttribute(
else
autocomplete_ = kOn;
}
- } else if (name == typeAttr) {
+ } else if (name == kTypeAttr) {
UpdateType();
- } else if (name == valueAttr) {
+ } else if (name == kValueAttr) {
// We only need to setChanged if the form is looking at the default value
// right now.
if (!HasDirtyValue()) {
@@ -758,14 +759,14 @@ void HTMLInputElement::ParseAttribute(
UpdatePlaceholderVisibility();
SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::FromAttribute(valueAttr));
+ StyleChangeReasonForTracing::FromAttribute(kValueAttr));
}
needs_to_update_view_value_ = true;
SetNeedsValidityCheck();
input_type_->WarnIfValueIsInvalidAndElementIsVisible(value);
input_type_->InRangeChanged();
input_type_view_->ValueAttributeChanged();
- } else if (name == checkedAttr) {
+ } else if (name == kCheckedAttr) {
// Another radio button in the same group might be checked by state
// restore. We shouldn't call setChecked() even if this has the checked
// attribute. So, delay the setChecked() call until
@@ -777,72 +778,73 @@ void HTMLInputElement::ParseAttribute(
dirty_checkedness_ = false;
}
PseudoStateChanged(CSSSelector::kPseudoDefault);
- } else if (name == maxlengthAttr) {
+ } else if (name == kMaxlengthAttr) {
SetNeedsValidityCheck();
- } else if (name == minlengthAttr) {
+ } else if (name == kMinlengthAttr) {
SetNeedsValidityCheck();
- } else if (name == sizeAttr) {
+ } else if (name == kSizeAttr) {
unsigned size = 0;
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, size) ||
size == 0 || size > 0x7fffffffu)
size = kDefaultSize;
if (size_ != size) {
size_ = size;
- if (GetLayoutObject())
+ if (GetLayoutObject()) {
GetLayoutObject()
->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
+ }
}
- } else if (name == altAttr) {
+ } else if (name == kAltAttr) {
input_type_view_->AltAttributeChanged();
- } else if (name == srcAttr) {
+ } else if (name == kSrcAttr) {
input_type_view_->SrcAttributeChanged();
- } else if (name == usemapAttr || name == accesskeyAttr) {
+ } else if (name == kUsemapAttr || name == kAccesskeyAttr) {
// FIXME: ignore for the moment
- } else if (name == onsearchAttr) {
+ } else if (name == kOnsearchAttr) {
// Search field and slider attributes all just cause updateFromElement to be
// called through style recalcing.
- SetAttributeEventListener(EventTypeNames::search,
+ SetAttributeEventListener(event_type_names::kSearch,
CreateAttributeEventListener(this, name, value));
- } else if (name == incrementalAttr) {
+ } else if (name == kIncrementalAttr) {
UseCounter::Count(GetDocument(), WebFeature::kIncrementalAttribute);
- } else if (name == minAttr) {
+ } else if (name == kMinAttr) {
input_type_view_->MinOrMaxAttributeChanged();
input_type_->SanitizeValueInResponseToMinOrMaxAttributeChange();
input_type_->InRangeChanged();
SetNeedsValidityCheck();
UseCounter::Count(GetDocument(), WebFeature::kMinAttribute);
- } else if (name == maxAttr) {
+ } else if (name == kMaxAttr) {
input_type_view_->MinOrMaxAttributeChanged();
input_type_->SanitizeValueInResponseToMinOrMaxAttributeChange();
input_type_->InRangeChanged();
SetNeedsValidityCheck();
UseCounter::Count(GetDocument(), WebFeature::kMaxAttribute);
- } else if (name == multipleAttr) {
+ } else if (name == kMultipleAttr) {
input_type_view_->MultipleAttributeChanged();
SetNeedsValidityCheck();
- } else if (name == stepAttr) {
+ } else if (name == kStepAttr) {
input_type_view_->StepAttributeChanged();
SetNeedsValidityCheck();
UseCounter::Count(GetDocument(), WebFeature::kStepAttribute);
- } else if (name == patternAttr) {
+ } else if (name == kPatternAttr) {
SetNeedsValidityCheck();
UseCounter::Count(GetDocument(), WebFeature::kPatternAttribute);
- } else if (name == readonlyAttr) {
+ } else if (name == kReadonlyAttr) {
TextControlElement::ParseAttribute(params);
input_type_view_->ReadonlyAttributeChanged();
- } else if (name == listAttr) {
+ } else if (name == kListAttr) {
has_non_empty_list_ = !value.IsEmpty();
if (has_non_empty_list_) {
ResetListAttributeTargetObserver();
ListAttributeTargetChanged();
}
UseCounter::Count(GetDocument(), WebFeature::kListAttribute);
- } else if (name == webkitdirectoryAttr) {
+ } else if (name == kWebkitdirectoryAttr) {
TextControlElement::ParseAttribute(params);
UseCounter::Count(GetDocument(), WebFeature::kPrefixedDirectoryAttribute);
} else {
- if (name == formactionAttr)
+ if (name == kFormactionAttr)
LogUpdateAttributeIfIsolatedWorldAndInDocument("input", params);
TextControlElement::ParseAttribute(params);
}
@@ -860,7 +862,7 @@ void HTMLInputElement::FinishParsingChildren() {
DCHECK(input_type_view_);
TextControlElement::FinishParsingChildren();
if (!state_restored_) {
- bool checked = hasAttribute(checkedAttr);
+ bool checked = hasAttribute(kCheckedAttr);
if (checked)
setChecked(checked);
dirty_checkedness_ = false;
@@ -899,12 +901,12 @@ String HTMLInputElement::AltText() const {
// http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
// also heavily discussed by Hixie on bugzilla
// note this is intentionally different to HTMLImageElement::altText()
- String alt = FastGetAttribute(altAttr);
+ String alt = FastGetAttribute(kAltAttr);
// fall back to title attribute
if (alt.IsNull())
- alt = FastGetAttribute(titleAttr);
+ alt = FastGetAttribute(kTitleAttr);
if (alt.IsNull())
- alt = FastGetAttribute(valueAttr);
+ alt = FastGetAttribute(kValueAttr);
if (alt.IsNull())
alt = GetLocale().QueryString(WebLocalizedString::kInputElementAltText);
return alt;
@@ -940,7 +942,7 @@ void HTMLInputElement::ResetImpl() {
SetNeedsValidityCheck();
}
- setChecked(hasAttribute(checkedAttr));
+ setChecked(hasAttribute(kCheckedAttr));
dirty_checkedness_ = false;
}
@@ -1049,9 +1051,9 @@ String HTMLInputElement::value() const {
case ValueMode::kFilename:
return input_type_->ValueInFilenameValueMode();
case ValueMode::kDefault:
- return FastGetAttribute(valueAttr);
+ return FastGetAttribute(kValueAttr);
case ValueMode::kDefaultOn: {
- AtomicString value_string = FastGetAttribute(valueAttr);
+ AtomicString value_string = FastGetAttribute(kValueAttr);
return value_string.IsNull() ? "on" : value_string;
}
case ValueMode::kValue:
@@ -1080,7 +1082,7 @@ void HTMLInputElement::SetSuggestedValue(const String& value) {
TextControlElement::SetSuggestedValue(SanitizeValue(value));
SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
+ StyleChangeReasonForTracing::Create(style_change_reason::kControlValue));
input_type_view_->UpdateView();
}
@@ -1104,7 +1106,7 @@ void HTMLInputElement::setValue(const String& value,
ExceptionState& exception_state,
TextFieldEventBehavior event_behavior) {
// FIXME: Remove type check.
- if (type() == InputTypeNames::file && !value.IsEmpty()) {
+ if (type() == input_type_names::kFile && !value.IsEmpty()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"This input element accepts a filename, "
"which may only be programmatically set "
@@ -1204,7 +1206,7 @@ void HTMLInputElement::setValueAsNumber(double new_value,
void HTMLInputElement::SetValueFromRenderer(const String& value) {
// File upload controls will never use this.
- DCHECK_NE(type(), InputTypeNames::file);
+ DCHECK_NE(type(), input_type_names::kFile);
// Clear the suggested value. Use the base class version to not trigger a view
// update.
@@ -1235,12 +1237,12 @@ void HTMLInputElement::SetValueFromRenderer(const String& value) {
EventDispatchHandlingState* HTMLInputElement::PreDispatchEventHandler(
Event& event) {
- if (event.type() == EventTypeNames::textInput &&
+ if (event.type() == event_type_names::kTextInput &&
input_type_view_->ShouldSubmitImplicitly(event)) {
event.stopPropagation();
return nullptr;
}
- if (event.type() != EventTypeNames::click)
+ if (event.type() != event_type_names::kClick)
return nullptr;
if (!event.IsMouseEvent() ||
ToMouseEvent(event).button() !=
@@ -1259,7 +1261,7 @@ void HTMLInputElement::PostDispatchEventHandler(
}
void HTMLInputElement::DefaultEventHandler(Event& evt) {
- if (evt.IsMouseEvent() && evt.type() == EventTypeNames::click &&
+ if (evt.IsMouseEvent() && evt.type() == event_type_names::kClick &&
ToMouseEvent(evt).button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
input_type_view_->HandleClickEvent(ToMouseEvent(evt));
@@ -1267,7 +1269,7 @@ void HTMLInputElement::DefaultEventHandler(Event& evt) {
return;
}
- if (evt.IsKeyboardEvent() && evt.type() == EventTypeNames::keydown) {
+ if (evt.IsKeyboardEvent() && evt.type() == event_type_names::kKeydown) {
input_type_view_->HandleKeydownEvent(ToKeyboardEvent(evt));
if (evt.DefaultHandled())
return;
@@ -1277,8 +1279,8 @@ void HTMLInputElement::DefaultEventHandler(Event& evt) {
// all events in text fields. Makes editing keyboard handling take precedence
// over the keydown and keypress handling in this function.
bool call_base_class_early =
- IsTextField() && (evt.type() == EventTypeNames::keydown ||
- evt.type() == EventTypeNames::keypress);
+ IsTextField() && (evt.type() == event_type_names::kKeydown ||
+ evt.type() == event_type_names::kKeypress);
if (call_base_class_early) {
TextControlElement::DefaultEventHandler(evt);
if (evt.DefaultHandled())
@@ -1291,7 +1293,7 @@ void HTMLInputElement::DefaultEventHandler(Event& evt) {
// the element, or presses enter while it is the active element. JavaScript
// code wishing to activate the element must dispatch a DOMActivate event - a
// click event will not do the job.
- if (evt.type() == EventTypeNames::DOMActivate) {
+ if (evt.type() == event_type_names::kDOMActivate) {
input_type_view_->HandleDOMActivateEvent(evt);
if (evt.DefaultHandled())
return;
@@ -1299,13 +1301,13 @@ void HTMLInputElement::DefaultEventHandler(Event& evt) {
// Use key press event here since sending simulated mouse events
// on key down blocks the proper sending of the key press event.
- if (evt.IsKeyboardEvent() && evt.type() == EventTypeNames::keypress) {
+ if (evt.IsKeyboardEvent() && evt.type() == event_type_names::kKeypress) {
input_type_view_->HandleKeypressEvent(ToKeyboardEvent(evt));
if (evt.DefaultHandled())
return;
}
- if (evt.IsKeyboardEvent() && evt.type() == EventTypeNames::keyup) {
+ if (evt.IsKeyboardEvent() && evt.type() == event_type_names::kKeyup) {
input_type_view_->HandleKeyupEvent(ToKeyboardEvent(evt));
if (evt.DefaultHandled())
return;
@@ -1313,7 +1315,7 @@ void HTMLInputElement::DefaultEventHandler(Event& evt) {
if (input_type_view_->ShouldSubmitImplicitly(evt)) {
// FIXME: Remove type check.
- if (type() == InputTypeNames::search) {
+ if (type() == input_type_names::kSearch) {
GetDocument()
.GetTaskRunner(TaskType::kUserInteraction)
->PostTask(FROM_HERE, WTF::Bind(&HTMLInputElement::OnSearch,
@@ -1340,7 +1342,7 @@ void HTMLInputElement::DefaultEventHandler(Event& evt) {
static_cast<BeforeTextInsertedEvent&>(evt));
}
- if (evt.IsMouseEvent() && evt.type() == EventTypeNames::mousedown) {
+ if (evt.IsMouseEvent() && evt.type() == event_type_names::kMousedown) {
input_type_view_->HandleMouseDownEvent(ToMouseEvent(evt));
if (evt.DefaultHandled())
return;
@@ -1370,8 +1372,8 @@ bool HTMLInputElement::WillRespondToMouseClickEvents() {
}
bool HTMLInputElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr ||
- attribute.GetName() == formactionAttr ||
+ return attribute.GetName() == kSrcAttr ||
+ attribute.GetName() == kFormactionAttr ||
TextControlElement::IsURLAttribute(attribute);
}
@@ -1385,7 +1387,7 @@ const QualifiedName& HTMLInputElement::SubResourceAttributeName() const {
}
const AtomicString& HTMLInputElement::DefaultValue() const {
- return FastGetAttribute(valueAttr);
+ return FastGetAttribute(kValueAttr);
}
static inline bool IsRFC2616TokenCharacter(UChar ch) {
@@ -1433,20 +1435,20 @@ static Vector<String> ParseAcceptAttribute(const String& accept_string,
}
Vector<String> HTMLInputElement::AcceptMIMETypes() const {
- return ParseAcceptAttribute(FastGetAttribute(acceptAttr), IsValidMIMEType);
+ return ParseAcceptAttribute(FastGetAttribute(kAcceptAttr), IsValidMIMEType);
}
Vector<String> HTMLInputElement::AcceptFileExtensions() const {
- return ParseAcceptAttribute(FastGetAttribute(acceptAttr),
+ return ParseAcceptAttribute(FastGetAttribute(kAcceptAttr),
IsValidFileExtension);
}
const AtomicString& HTMLInputElement::Alt() const {
- return FastGetAttribute(altAttr);
+ return FastGetAttribute(kAltAttr);
}
bool HTMLInputElement::Multiple() const {
- return FastHasAttribute(multipleAttr);
+ return FastHasAttribute(kMultipleAttr);
}
void HTMLInputElement::setSize(unsigned size, ExceptionState& exception_state) {
@@ -1455,13 +1457,13 @@ void HTMLInputElement::setSize(unsigned size, ExceptionState& exception_state) {
DOMExceptionCode::kIndexSizeError,
"The value provided is 0, which is an invalid size.");
} else {
- SetUnsignedIntegralAttribute(sizeAttr, size ? size : kDefaultSize,
+ SetUnsignedIntegralAttribute(kSizeAttr, size ? size : kDefaultSize,
kDefaultSize);
}
}
KURL HTMLInputElement::Src() const {
- return GetDocument().CompleteURL(FastGetAttribute(srcAttr));
+ return GetDocument().CompleteURL(FastGetAttribute(kSrcAttr));
}
FileList* HTMLInputElement::files() const {
@@ -1549,7 +1551,8 @@ Node::InsertionNotificationRequest HTMLInputElement::InsertedInto(
if (insertion_point.isConnected() && !Form())
AddToRadioButtonGroup();
ResetListAttributeTargetObserver();
- LogAddElementIfIsolatedWorldAndInDocument("input", typeAttr, formactionAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("input", kTypeAttr,
+ kFormactionAttr);
return kInsertionShouldCallDidNotifySubtreeInsertions;
}
@@ -1567,7 +1570,7 @@ void HTMLInputElement::DidMoveToNewDocument(Document& old_document) {
ImageLoader()->ElementDidMoveToNewDocument();
// FIXME: Remove type check.
- if (type() == InputTypeNames::radio)
+ if (type() == input_type_names::kRadio)
GetTreeScope().GetRadioButtonGroupScope().RemoveButton(this);
TextControlElement::DidMoveToNewDocument(old_document);
@@ -1612,7 +1615,7 @@ HTMLDataListElement* HTMLInputElement::DataList() const {
return nullptr;
return ToHTMLDataListElementOrNull(
- GetTreeScope().getElementById(FastGetAttribute(listAttr)));
+ GetTreeScope().getElementById(FastGetAttribute(kListAttr)));
}
bool HTMLInputElement::HasValidDataListOptions() const {
@@ -1636,7 +1639,7 @@ HTMLInputElement::FilteredDataListOptions() const {
return filtered;
String value = InnerEditorValue();
- if (Multiple() && type() == InputTypeNames::email) {
+ if (Multiple() && type() == input_type_names::kEmail) {
Vector<String> emails;
value.Split(',', true, emails);
if (!emails.IsEmpty())
@@ -1673,7 +1676,7 @@ void HTMLInputElement::SetListAttributeTargetObserver(
}
void HTMLInputElement::ResetListAttributeTargetObserver() {
- const AtomicString& value = FastGetAttribute(listAttr);
+ const AtomicString& value = FastGetAttribute(kListAttr);
if (!value.IsNull() && isConnected()) {
SetListAttributeTargetObserver(
ListAttributeTargetObserver::Create(value, this));
@@ -1736,7 +1739,7 @@ bool HTMLInputElement::ShouldAppearIndeterminate() const {
bool HTMLInputElement::IsInRequiredRadioButtonGroup() {
// TODO(tkent): Remove type check.
- DCHECK_EQ(type(), InputTypeNames::radio);
+ DCHECK_EQ(type(), input_type_names::kRadio);
if (RadioButtonGroupScope* scope = GetRadioButtonGroupScope())
return scope->IsInRequiredGroup(this);
return false;
@@ -1752,7 +1755,7 @@ HTMLInputElement* HTMLInputElement::CheckedRadioButtonForGroup() {
RadioButtonGroupScope* HTMLInputElement::GetRadioButtonGroupScope() const {
// FIXME: Remove type check.
- if (type() != InputTypeNames::radio)
+ if (type() != input_type_names::kRadio)
return nullptr;
if (HTMLFormElement* form_element = Form())
return &form_element->GetRadioButtonGroupScope();
@@ -1787,17 +1790,17 @@ unsigned HTMLInputElement::width() const {
}
void HTMLInputElement::setHeight(unsigned height) {
- SetUnsignedIntegralAttribute(heightAttr, height);
+ SetUnsignedIntegralAttribute(kHeightAttr, height);
}
void HTMLInputElement::setWidth(unsigned width) {
- SetUnsignedIntegralAttribute(widthAttr, width);
+ SetUnsignedIntegralAttribute(kWidthAttr, width);
}
ListAttributeTargetObserver* ListAttributeTargetObserver::Create(
const AtomicString& id,
HTMLInputElement* element) {
- return new ListAttributeTargetObserver(id, element);
+ return MakeGarbageCollected<ListAttributeTargetObserver>(id, element);
}
ListAttributeTargetObserver::ListAttributeTargetObserver(
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_input_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_input_element.h
index fe681ffc520..75f9122ae9e 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_input_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_input_element.h
@@ -56,6 +56,8 @@ class CORE_EXPORT HTMLInputElement
public:
static HTMLInputElement* Create(Document&, const CreateElementFlags);
+
+ HTMLInputElement(Document&, const CreateElementFlags);
~HTMLInputElement() override;
void Trace(blink::Visitor*) override;
@@ -64,7 +66,7 @@ class CORE_EXPORT HTMLInputElement
bool HasPendingActivity() const final;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitspeechchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitspeechchange, kWebkitspeechchange);
bool ShouldAutocomplete() const final;
@@ -107,7 +109,7 @@ class CORE_EXPORT HTMLInputElement
bool IsTextField() const;
// Do not add type check predicates for concrete input types; e.g. isImage,
// isRadio, isFile. If you want to check the input type, you may use
- // |input->type() == InputTypeNames::image|, etc.
+ // |input->type() == input_type_names::kImage|, etc.
// Returns whether this field is or has ever been a password field so that
// its value can be protected from memorization by autofill or keyboards.
@@ -190,7 +192,7 @@ class CORE_EXPORT HTMLInputElement
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
void DetachLayoutTree(const AttachContext& = AttachContext()) final;
void UpdateFocusAppearanceWithOptions(SelectionBehaviorOnFocus,
- const FocusOptions&) final;
+ const FocusOptions*) final;
// FIXME: For isActivatedSubmit and setActivatedSubmit, we should use the
// NVI-idiom here by making it private virtual in all classes and expose a
@@ -268,7 +270,7 @@ class CORE_EXPORT HTMLInputElement
void EndEditing();
- static FileChooserFileInfoList FilesFromFileInputFormControlState(
+ static Vector<String> FilesFromFileInputFormControlState(
const FormControlState&);
bool MatchesReadOnlyPseudoClass() const final;
@@ -307,8 +309,6 @@ class CORE_EXPORT HTMLInputElement
void ChildrenChanged(const ChildrenChange&) override;
protected:
- HTMLInputElement(Document&, const CreateElementFlags);
-
void DefaultEventHandler(Event&) override;
void CreateShadowSubtree();
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_input_element_test.cc b/chromium/third_party/blink/renderer/core/html/forms/html_input_element_test.cc
index 8ef3fb59c13..967bdeb5da6 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_input_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_input_element_test.cc
@@ -121,7 +121,7 @@ TEST_F(HTMLInputElementTest, NoAssertWhenMovedInNewDocument) {
TEST_F(HTMLInputElementTest, DefaultToolTip) {
auto* input_without_form =
HTMLInputElement::Create(GetDocument(), CreateElementFlags());
- input_without_form->SetBooleanAttribute(HTMLNames::requiredAttr, true);
+ input_without_form->SetBooleanAttribute(html_names::kRequiredAttr, true);
GetDocument().body()->AppendChild(input_without_form);
EXPECT_EQ("<<ValidationValueMissing>>", input_without_form->DefaultToolTip());
@@ -129,23 +129,23 @@ TEST_F(HTMLInputElementTest, DefaultToolTip) {
GetDocument().body()->AppendChild(form);
auto* input_with_form =
HTMLInputElement::Create(GetDocument(), CreateElementFlags());
- input_with_form->SetBooleanAttribute(HTMLNames::requiredAttr, true);
+ input_with_form->SetBooleanAttribute(html_names::kRequiredAttr, true);
form->AppendChild(input_with_form);
EXPECT_EQ("<<ValidationValueMissing>>", input_with_form->DefaultToolTip());
- form->SetBooleanAttribute(HTMLNames::novalidateAttr, true);
+ form->SetBooleanAttribute(html_names::kNovalidateAttr, true);
EXPECT_EQ(String(), input_with_form->DefaultToolTip());
}
// crbug.com/589838
TEST_F(HTMLInputElementTest, ImageTypeCrash) {
auto* input = HTMLInputElement::Create(GetDocument(), CreateElementFlags());
- input->setAttribute(HTMLNames::typeAttr, "image");
+ input->setAttribute(html_names::kTypeAttr, "image");
input->EnsureFallbackContent();
// Make sure ensurePrimaryContent() recreates UA shadow tree, and updating
// |value| doesn't crash.
input->EnsurePrimaryContent();
- input->setAttribute(HTMLNames::valueAttr, "aaa");
+ input->setAttribute(html_names::kValueAttr, "aaa");
}
TEST_F(HTMLInputElementTest, RadioKeyDownDCHECKFailure) {
@@ -157,10 +157,11 @@ TEST_F(HTMLInputElementTest, RadioKeyDownDCHECKFailure) {
HTMLInputElement& radio2 = ToHTMLInputElement(*radio1.nextSibling());
radio1.focus();
// Make layout-dirty.
- radio2.setAttribute(HTMLNames::styleAttr, "position:fixed");
- KeyboardEventInit init;
- init.setKey("ArrowRight");
- radio1.DefaultEventHandler(*new KeyboardEvent("keydown", init));
+ radio2.setAttribute(html_names::kStyleAttr, "position:fixed");
+ KeyboardEventInit* init = KeyboardEventInit::Create();
+ init->setKey("ArrowRight");
+ radio1.DefaultEventHandler(
+ *MakeGarbageCollected<KeyboardEvent>("keydown", init));
EXPECT_EQ(GetDocument().ActiveElement(), &radio2);
}
@@ -169,7 +170,7 @@ TEST_F(HTMLInputElementTest, DateTimeChooserSizeParamRespectsScale) {
GetDocument().View()->GetFrame().GetPage()->GetVisualViewport().SetScale(2.f);
GetDocument().body()->SetInnerHTMLFromString(
"<input type='date' style='width:200px;height:50px' />");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
HTMLInputElement* input =
ToHTMLInputElement(GetDocument().body()->firstChild());
@@ -182,9 +183,9 @@ TEST_F(HTMLInputElementTest, DateTimeChooserSizeParamRespectsScale) {
TEST_F(HTMLInputElementTest, StepDownOverflow) {
auto* input = HTMLInputElement::Create(GetDocument(), CreateElementFlags());
- input->setAttribute(HTMLNames::typeAttr, "date");
- input->setAttribute(HTMLNames::minAttr, "2010-02-10");
- input->setAttribute(HTMLNames::stepAttr, "9223372036854775556");
+ input->setAttribute(html_names::kTypeAttr, "date");
+ input->setAttribute(html_names::kMinAttr, "2010-02-10");
+ input->setAttribute(html_names::kStepAttr, "9223372036854775556");
// InputType::applyStep() should not pass an out-of-range value to
// setValueAsDecimal, and WTF::msToYear() should not cause a DCHECK failure.
input->stepDown(1, ASSERT_NO_EXCEPTION);
@@ -202,7 +203,7 @@ TEST_F(HTMLInputElementTest, ChangingInputTypeCausesShadowRootToBeCreated) {
HTMLInputElement* input =
ToHTMLInputElement(GetDocument().body()->firstChild());
EXPECT_EQ(nullptr, input->UserAgentShadowRoot());
- input->setAttribute(HTMLNames::typeAttr, "text");
+ input->setAttribute(html_names::kTypeAttr, "text");
EXPECT_NE(nullptr, input->UserAgentShadowRoot());
}
@@ -214,12 +215,12 @@ TEST_F(HTMLInputElementTest, RepaintAfterClearingFile) {
FileChooserFileInfoList files;
files.push_back(CreateFileChooserFileInfoNative("/native/path/native-file",
"display-name"));
- FileList* list = FileInputType::CreateFileList(files, false);
+ FileList* list = FileInputType::CreateFileList(files, base::FilePath());
ASSERT_TRUE(list);
EXPECT_EQ(1u, list->length());
input->setFiles(list);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(input->GetLayoutObject());
EXPECT_FALSE(input->GetLayoutObject()->ShouldCheckForPaintInvalidation());
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_label_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_label_element.cc
index 8dcffb2b7e5..3fea461e8dd 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_label_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_label_element.cc
@@ -41,17 +41,17 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLLabelElement::HTMLLabelElement(Document& document)
- : HTMLElement(labelTag, document), processing_click_(false) {}
+ : HTMLElement(kLabelTag, document), processing_click_(false) {}
HTMLLabelElement* HTMLLabelElement::Create(Document& document) {
- return new HTMLLabelElement(document);
+ return MakeGarbageCollected<HTMLLabelElement>(document);
}
LabelableElement* HTMLLabelElement::control() const {
- const AtomicString& control_id = getAttribute(forAttr);
+ const AtomicString& control_id = getAttribute(kForAttr);
if (control_id.IsNull()) {
// Search the children and descendants of the label element for a form
// element.
@@ -138,7 +138,7 @@ bool HTMLLabelElement::IsInInteractiveContent(Node* node) const {
}
void HTMLLabelElement::DefaultEventHandler(Event& evt) {
- if (evt.type() == EventTypeNames::click && !processing_click_) {
+ if (evt.type() == event_type_names::kClick && !processing_click_) {
HTMLElement* element = control();
// If we can't find a control or if the control received the click
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_label_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_label_element.h
index 884851e4d53..0f396c31d3c 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_label_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_label_element.h
@@ -36,13 +36,15 @@ class CORE_EXPORT HTMLLabelElement final : public HTMLElement {
public:
static HTMLLabelElement* Create(Document&);
+
+ explicit HTMLLabelElement(Document&);
+
LabelableElement* control() const;
HTMLFormElement* form() const;
bool WillRespondToMouseClickEvents() override;
private:
- explicit HTMLLabelElement(Document&);
bool IsInInteractiveContent(Node*) const;
bool IsInteractiveContent() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.cc
index 2efbd56c96a..a17111c22ee 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.cc
@@ -25,58 +25,18 @@
#include "third_party/blink/renderer/core/html/forms/html_legend_element.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/dom/element_traversal.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_field_set_element.h"
-#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLLegendElement::HTMLLegendElement(Document& document)
- : HTMLElement(legendTag, document) {}
+ : HTMLElement(kLegendTag, document) {}
DEFINE_NODE_FACTORY(HTMLLegendElement)
-HTMLFormControlElement* HTMLLegendElement::AssociatedControl() {
- // Check if there's a fieldset belonging to this legend.
- HTMLFieldSetElement* fieldset =
- Traversal<HTMLFieldSetElement>::FirstAncestor(*this);
- if (!fieldset)
- return nullptr;
-
- // Find first form element inside the fieldset that is not a legend element.
- // FIXME: Should we consider tabindex?
- if (auto* control =
- Traversal<HTMLFormControlElement>::Next(*fieldset, fieldset)) {
- UseCounter::Count(GetDocument(),
- WebFeature::kLegendDelegateFocusOrAccessKey);
- return control;
- }
- return nullptr;
-}
-
-void HTMLLegendElement::focus(const FocusParams& params) {
- GetDocument().UpdateStyleAndLayoutTreeForNode(this);
- if (IsFocusable()) {
- Element::focus(params);
- return;
- }
-
- // To match other browsers' behavior, never restore previous selection.
- if (HTMLFormControlElement* control = AssociatedControl()) {
- control->focus(FocusParams(SelectionBehaviorOnFocus::kReset, params.type,
- params.source_capabilities, params.options));
- }
-}
-
-void HTMLLegendElement::AccessKeyAction(bool send_mouse_events) {
- if (HTMLFormControlElement* control = AssociatedControl())
- control->AccessKeyAction(send_mouse_events);
-}
-
HTMLFormElement* HTMLLegendElement::form() const {
// According to the specification, If the legend has a fieldset element as
// its parent, then the form attribute must return the same value as the
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.h
index c69a718b330..802daeb1483 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.h
@@ -28,8 +28,6 @@
namespace blink {
-class HTMLFormControlElement;
-
class HTMLLegendElement final : public HTMLElement {
DEFINE_WRAPPERTYPEINFO();
@@ -40,12 +38,6 @@ class HTMLLegendElement final : public HTMLElement {
private:
explicit HTMLLegendElement(Document&);
-
- // Control in the legend's fieldset that gets focus and access key.
- HTMLFormControlElement* AssociatedControl();
-
- void AccessKeyAction(bool send_mouse_events) override;
- void focus(const FocusParams&) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.cc
index f04ceb68d01..0a21f37b1e4 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.cc
@@ -37,10 +37,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLOptGroupElement::HTMLOptGroupElement(Document& document)
- : HTMLElement(optgroupTag, document) {}
+ : HTMLElement(kOptgroupTag, document) {}
// An explicit empty destructor should be in html_opt_group_element.cc, because
// if an implicit destructor is used or an empty destructor is defined in
@@ -50,28 +50,29 @@ inline HTMLOptGroupElement::HTMLOptGroupElement(Document& document)
HTMLOptGroupElement::~HTMLOptGroupElement() = default;
HTMLOptGroupElement* HTMLOptGroupElement::Create(Document& document) {
- HTMLOptGroupElement* opt_group_element = new HTMLOptGroupElement(document);
+ HTMLOptGroupElement* opt_group_element =
+ MakeGarbageCollected<HTMLOptGroupElement>(document);
opt_group_element->EnsureUserAgentShadowRoot();
return opt_group_element;
}
// static
bool HTMLOptGroupElement::CanAssignToOptGroupSlot(const Node& node) {
- return node.HasTagName(optionTag) || node.HasTagName(hrTag);
+ return node.HasTagName(kOptionTag) || node.HasTagName(kHrTag);
}
bool HTMLOptGroupElement::IsDisabledFormControl() const {
- return FastHasAttribute(disabledAttr);
+ return FastHasAttribute(kDisabledAttr);
}
void HTMLOptGroupElement::ParseAttribute(
const AttributeModificationParams& params) {
HTMLElement::ParseAttribute(params);
- if (params.name == disabledAttr) {
+ if (params.name == kDisabledAttr) {
PseudoStateChanged(CSSSelector::kPseudoDisabled);
PseudoStateChanged(CSSSelector::kPseudoEnabled);
- } else if (params.name == labelAttr) {
+ } else if (params.name == kLabelAttr) {
UpdateGroupLabel();
}
}
@@ -106,7 +107,7 @@ void HTMLOptGroupElement::RemovedFrom(ContainerNode& insertion_point) {
}
String HTMLOptGroupElement::GroupLabelText() const {
- String item_text = getAttribute(labelAttr);
+ String item_text = getAttribute(kLabelAttr);
// In WinIE, leading and trailing whitespace is ignored in options and
// optgroups. We match this behavior.
@@ -139,11 +140,11 @@ void HTMLOptGroupElement::DidAddUserAgentShadowRoot(ShadowRoot& root) {
DEFINE_STATIC_LOCAL(AtomicString, label_padding, ("0 2px 1px 2px"));
DEFINE_STATIC_LOCAL(AtomicString, label_min_height, ("1.2em"));
HTMLDivElement* label = HTMLDivElement::Create(GetDocument());
- label->setAttribute(roleAttr, AtomicString("group"));
- label->setAttribute(aria_labelAttr, AtomicString());
+ label->setAttribute(kRoleAttr, AtomicString("group"));
+ label->setAttribute(kAriaLabelAttr, AtomicString());
label->SetInlineStyleProperty(CSSPropertyPadding, label_padding);
label->SetInlineStyleProperty(CSSPropertyMinHeight, label_min_height);
- label->SetIdAttribute(ShadowElementNames::OptGroupLabel());
+ label->SetIdAttribute(shadow_element_names::OptGroupLabel());
root.AppendChild(label);
root.AppendChild(
@@ -154,12 +155,12 @@ void HTMLOptGroupElement::UpdateGroupLabel() {
const String& label_text = GroupLabelText();
HTMLDivElement& label = OptGroupLabelElement();
label.setTextContent(label_text);
- label.setAttribute(aria_labelAttr, AtomicString(label_text));
+ label.setAttribute(kAriaLabelAttr, AtomicString(label_text));
}
HTMLDivElement& HTMLOptGroupElement::OptGroupLabelElement() const {
return *ToHTMLDivElementOrDie(UserAgentShadowRoot()->getElementById(
- ShadowElementNames::OptGroupLabel()));
+ shadow_element_names::OptGroupLabel()));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.h
index 759d835e1bc..c2580c731a6 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.h
@@ -38,6 +38,8 @@ class CORE_EXPORT HTMLOptGroupElement final : public HTMLElement {
public:
static HTMLOptGroupElement* Create(Document&);
+ explicit HTMLOptGroupElement(Document&);
+
bool IsDisabledFormControl() const override;
String DefaultToolTip() const override;
HTMLSelectElement* OwnerSelectElement() const;
@@ -49,7 +51,6 @@ class CORE_EXPORT HTMLOptGroupElement final : public HTMLElement {
static bool CanAssignToOptGroupSlot(const Node&);
private:
- explicit HTMLOptGroupElement(Document&);
~HTMLOptGroupElement() override;
bool SupportsFocus() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_option_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_option_element.cc
index 4f886540103..7ddbf5b1e53 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_option_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_option_element.cc
@@ -44,10 +44,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLOptionElement::HTMLOptionElement(Document& document)
- : HTMLElement(optionTag, document), is_selected_(false) {}
+ : HTMLElement(kOptionTag, document), is_selected_(false) {}
// An explicit empty destructor should be in html_option_element.cc, because
// if an implicit destructor is used or an empty destructor is defined in
@@ -57,7 +57,7 @@ HTMLOptionElement::HTMLOptionElement(Document& document)
HTMLOptionElement::~HTMLOptionElement() = default;
HTMLOptionElement* HTMLOptionElement::Create(Document& document) {
- HTMLOptionElement* option = new HTMLOptionElement(document);
+ HTMLOptionElement* option = MakeGarbageCollected<HTMLOptionElement>(document);
option->EnsureUserAgentShadowRoot();
return option;
}
@@ -69,7 +69,8 @@ HTMLOptionElement* HTMLOptionElement::CreateForJSConstructor(
bool default_selected,
bool selected,
ExceptionState& exception_state) {
- HTMLOptionElement* element = new HTMLOptionElement(document);
+ HTMLOptionElement* element =
+ MakeGarbageCollected<HTMLOptionElement>(document);
element->EnsureUserAgentShadowRoot();
if (!data.IsEmpty()) {
element->AppendChild(Text::Create(document, data), exception_state);
@@ -80,7 +81,7 @@ HTMLOptionElement* HTMLOptionElement::CreateForJSConstructor(
if (!value.IsNull())
element->setValue(value);
if (default_selected)
- element->setAttribute(selectedAttr, g_empty_atom);
+ element->setAttribute(kSelectedAttr, g_empty_atom);
element->SetSelected(selected);
return element;
@@ -94,7 +95,7 @@ bool HTMLOptionElement::SupportsFocus() const {
}
bool HTMLOptionElement::MatchesDefaultPseudoClass() const {
- return FastHasAttribute(selectedAttr);
+ return FastHasAttribute(kSelectedAttr);
}
bool HTMLOptionElement::MatchesEnabledPseudoClass() const {
@@ -107,7 +108,7 @@ String HTMLOptionElement::DisplayLabel() const {
// WinIE does not use the label attribute, so as a quirk, we ignore it.
if (!document.InQuirksMode())
- text = FastGetAttribute(labelAttr);
+ text = FastGetAttribute(kLabelAttr);
// FIXME: The following treats an element with the label attribute set to
// the empty string the same as an element with no label attribute at all.
@@ -172,21 +173,21 @@ int HTMLOptionElement::ListIndex() const {
void HTMLOptionElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == valueAttr) {
+ if (name == kValueAttr) {
if (HTMLDataListElement* data_list = OwnerDataListElement())
data_list->OptionElementChildrenChanged();
- } else if (name == disabledAttr) {
+ } else if (name == kDisabledAttr) {
if (params.old_value.IsNull() != params.new_value.IsNull()) {
PseudoStateChanged(CSSSelector::kPseudoDisabled);
PseudoStateChanged(CSSSelector::kPseudoEnabled);
if (LayoutObject* o = GetLayoutObject())
o->InvalidateIfControlStateChanged(kEnabledControlState);
}
- } else if (name == selectedAttr) {
+ } else if (name == kSelectedAttr) {
if (params.old_value.IsNull() != params.new_value.IsNull() && !is_dirty_)
SetSelected(!params.new_value.IsNull());
PseudoStateChanged(CSSSelector::kPseudoDefault);
- } else if (name == labelAttr) {
+ } else if (name == kLabelAttr) {
UpdateLabel();
} else {
HTMLElement::ParseAttribute(params);
@@ -194,7 +195,7 @@ void HTMLOptionElement::ParseAttribute(
}
String HTMLOptionElement::value() const {
- const AtomicString& value = FastGetAttribute(valueAttr);
+ const AtomicString& value = FastGetAttribute(kValueAttr);
if (!value.IsNull())
return value;
return CollectOptionInnerText()
@@ -203,7 +204,7 @@ String HTMLOptionElement::value() const {
}
void HTMLOptionElement::setValue(const AtomicString& value) {
- setAttribute(valueAttr, value);
+ setAttribute(kValueAttr, value);
}
bool HTMLOptionElement::Selected() const {
@@ -291,7 +292,7 @@ HTMLSelectElement* HTMLOptionElement::OwnerSelectElement() const {
}
String HTMLOptionElement::label() const {
- const AtomicString& label = FastGetAttribute(labelAttr);
+ const AtomicString& label = FastGetAttribute(kLabelAttr);
if (!label.IsNull())
return label;
return CollectOptionInnerText()
@@ -300,7 +301,7 @@ String HTMLOptionElement::label() const {
}
void HTMLOptionElement::setLabel(const AtomicString& label) {
- setAttribute(labelAttr, label);
+ setAttribute(kLabelAttr, label);
}
String HTMLOptionElement::TextIndentedToRespectGroupLabel() const {
@@ -311,7 +312,7 @@ String HTMLOptionElement::TextIndentedToRespectGroupLabel() const {
}
bool HTMLOptionElement::OwnElementDisabled() const {
- return FastHasAttribute(disabledAttr);
+ return FastHasAttribute(kDisabledAttr);
}
bool HTMLOptionElement::IsDisabledFormControl() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_option_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_option_element.h
index 854489f5b46..fb3c45f81dc 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_option_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_option_element.h
@@ -46,6 +46,8 @@ class CORE_EXPORT HTMLOptionElement final : public HTMLElement {
bool selected,
ExceptionState&);
+ explicit HTMLOptionElement(Document&);
+
// A text to be shown to users. The difference from |label()| is |label()|
// returns an empty string if |label| content attribute is empty.
// |displayLabel()| returns the value string in that case.
@@ -91,7 +93,6 @@ class CORE_EXPORT HTMLOptionElement final : public HTMLElement {
int ListIndex() const;
private:
- explicit HTMLOptionElement(Document&);
~HTMLOptionElement() override;
bool SupportsFocus() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.cc b/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.cc
index 98c6e68bc5e..941d29bc6d7 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.cc
@@ -66,7 +66,7 @@ void HTMLOptionsCollection::SupportedPropertyNames(Vector<String>& names) {
HTMLOptionsCollection* HTMLOptionsCollection::Create(ContainerNode& select,
CollectionType) {
- return new HTMLOptionsCollection(select);
+ return MakeGarbageCollected<HTMLOptionsCollection>(select);
}
void HTMLOptionsCollection::add(
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.h b/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.h
index 665d0eb431d..a8886f17907 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.h
@@ -39,6 +39,8 @@ class HTMLOptionsCollection final : public HTMLCollection {
public:
static HTMLOptionsCollection* Create(ContainerNode&, CollectionType);
+ explicit HTMLOptionsCollection(ContainerNode&);
+
HTMLOptionElement* item(unsigned offset) const {
return ToHTMLOptionElement(HTMLCollection::item(offset));
}
@@ -57,8 +59,6 @@ class HTMLOptionsCollection final : public HTMLCollection {
bool ElementMatches(const HTMLElement&) const;
private:
- explicit HTMLOptionsCollection(ContainerNode&);
-
void SupportedPropertyNames(Vector<String>& names) override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_output_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_output_element.cc
index 05478b0d4e9..bb88f6ca769 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_output_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_output_element.cc
@@ -36,15 +36,15 @@
namespace blink {
inline HTMLOutputElement::HTMLOutputElement(Document& document)
- : HTMLFormControlElement(HTMLNames::outputTag, document),
+ : HTMLFormControlElement(html_names::kOutputTag, document),
is_default_value_mode_(true),
default_value_(""),
- tokens_(DOMTokenList::Create(*this, HTMLNames::forAttr)) {}
+ tokens_(DOMTokenList::Create(*this, html_names::kForAttr)) {}
HTMLOutputElement::~HTMLOutputElement() = default;
HTMLOutputElement* HTMLOutputElement::Create(Document& document) {
- return new HTMLOutputElement(document);
+ return MakeGarbageCollected<HTMLOutputElement>(document);
}
const AtomicString& HTMLOutputElement::FormControlType() const {
@@ -66,7 +66,7 @@ bool HTMLOutputElement::SupportsFocus() const {
void HTMLOutputElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == HTMLNames::forAttr)
+ if (params.name == html_names::kForAttr)
tokens_->DidUpdateAttributeValue(params.old_value, params.new_value);
else
HTMLFormControlElement::ParseAttribute(params);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_output_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_output_element.h
index 2c322a0a70f..521e6762d93 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_output_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_output_element.h
@@ -41,6 +41,8 @@ class CORE_EXPORT HTMLOutputElement final : public HTMLFormControlElement {
public:
static HTMLOutputElement* Create(Document&);
+
+ explicit HTMLOutputElement(Document&);
~HTMLOutputElement() override;
bool willValidate() const override { return false; }
@@ -58,8 +60,6 @@ class CORE_EXPORT HTMLOutputElement final : public HTMLFormControlElement {
void Trace(blink::Visitor*) override;
private:
- explicit HTMLOutputElement(Document&);
-
void ParseAttribute(const AttributeModificationParams&) override;
const AtomicString& FormControlType() const override;
bool IsDisabledFormControl() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_output_element_test.cc b/chromium/third_party/blink/renderer/core/html/forms/html_output_element_test.cc
index fdb5cbe5979..92ab80abaaf 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_output_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_output_element_test.cc
@@ -15,9 +15,9 @@ TEST(HTMLLinkElementSizesAttributeTest,
setHTMLForProperty_updatesForAttribute) {
Document* document = Document::CreateForTest();
HTMLOutputElement* element = HTMLOutputElement::Create(*document);
- EXPECT_EQ(g_null_atom, element->getAttribute(HTMLNames::forAttr));
+ EXPECT_EQ(g_null_atom, element->getAttribute(html_names::kForAttr));
element->htmlFor()->setValue(" strawberry ");
- EXPECT_EQ(" strawberry ", element->getAttribute(HTMLNames::forAttr));
+ EXPECT_EQ(" strawberry ", element->getAttribute(html_names::kForAttr));
}
TEST(HTMLOutputElementTest, setForAttribute_updatesHTMLForPropertyValue) {
@@ -25,7 +25,7 @@ TEST(HTMLOutputElementTest, setForAttribute_updatesHTMLForPropertyValue) {
HTMLOutputElement* element = HTMLOutputElement::Create(*document);
DOMTokenList* for_tokens = element->htmlFor();
EXPECT_EQ(g_null_atom, for_tokens->value());
- element->setAttribute(HTMLNames::forAttr, "orange grape");
+ element->setAttribute(html_names::kForAttr, "orange grape");
EXPECT_EQ("orange grape", for_tokens->value());
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_select_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_select_element.cc
index 833ea0c848b..040fee3ae90 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_select_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_select_element.cc
@@ -77,7 +77,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// Upper limit of list_items_. According to the HTML standard, options larger
// than this limit doesn't work well because |selectedIndex| IDL attribute is
@@ -85,7 +85,7 @@ using namespace HTMLNames;
static const unsigned kMaxListItems = INT_MAX;
HTMLSelectElement::HTMLSelectElement(Document& document)
- : HTMLFormControlElementWithState(selectTag, document),
+ : HTMLFormControlElementWithState(kSelectTag, document),
type_ahead_(this),
size_(0),
last_on_change_option_(nullptr),
@@ -99,7 +99,7 @@ HTMLSelectElement::HTMLSelectElement(Document& document)
}
HTMLSelectElement* HTMLSelectElement::Create(Document& document) {
- HTMLSelectElement* select = new HTMLSelectElement(document);
+ HTMLSelectElement* select = MakeGarbageCollected<HTMLSelectElement>(document);
select->EnsureUserAgentShadowRoot();
return select;
}
@@ -108,8 +108,8 @@ HTMLSelectElement::~HTMLSelectElement() = default;
// static
bool HTMLSelectElement::CanAssignToSelectSlot(const Node& node) {
- return node.HasTagName(optionTag) || node.HasTagName(optgroupTag) ||
- node.HasTagName(hrTag);
+ return node.HasTagName(kOptionTag) || node.HasTagName(kOptgroupTag) ||
+ node.HasTagName(kHrTag);
}
const AtomicString& HTMLSelectElement::FormControlType() const {
@@ -258,9 +258,9 @@ void HTMLSelectElement::setValue(const String& value, bool send_events) {
SetSuggestedOption(nullptr);
if (is_autofilled_by_preview_)
SetAutofillState(WebAutofillState::kNotFilled);
- SelectOptionFlags flags = kDeselectOtherOptions | kMakeOptionDirty;
+ SelectOptionFlags flags = kDeselectOtherOptionsFlag | kMakeOptionDirtyFlag;
if (send_events)
- flags |= kDispatchInputAndChangeEvent;
+ flags |= kDispatchInputAndChangeEventFlag;
SelectOption(option, flags);
if (send_events && previous_selected_option != option && !UsesMenuList())
@@ -290,7 +290,7 @@ void HTMLSelectElement::SetSuggestedValue(const String& value) {
bool HTMLSelectElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
// Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
// See http://bugs.webkit.org/show_bug.cgi?id=12072
return false;
@@ -301,7 +301,7 @@ bool HTMLSelectElement::IsPresentationAttribute(
void HTMLSelectElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == sizeAttr) {
+ if (params.name == kSizeAttr) {
unsigned old_size = size_;
if (!ParseHTMLNonNegativeInteger(params.new_value, size_))
size_ = 0;
@@ -313,9 +313,9 @@ void HTMLSelectElement::ParseAttribute(
if (!UsesMenuList())
SaveListboxActiveSelection();
}
- } else if (params.name == multipleAttr) {
+ } else if (params.name == kMultipleAttr) {
ParseMultipleAttribute(params.new_value);
- } else if (params.name == accesskeyAttr) {
+ } else if (params.name == kAccesskeyAttr) {
// FIXME: ignore for the moment.
//
} else {
@@ -700,7 +700,7 @@ void HTMLSelectElement::SetOptionsChangedOnLayoutObject() {
return;
ToLayoutMenuList(layout_object)
->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kMenuOptionsChanged);
+ layout_invalidation_reason::kMenuOptionsChanged);
}
}
@@ -826,7 +826,7 @@ void HTMLSelectElement::ResetToDefaultSelection(ResetReason reason) {
SelectOption(first_enabled_option,
reason == kResetReasonSelectedOptionRemoved
? 0
- : kDeselectOtherOptions);
+ : kDeselectOtherOptionsFlag);
last_selected_option = first_enabled_option;
did_change = true;
}
@@ -857,7 +857,7 @@ int HTMLSelectElement::selectedIndex() const {
}
void HTMLSelectElement::setSelectedIndex(int index) {
- SelectOption(item(index), kDeselectOtherOptions | kMakeOptionDirty);
+ SelectOption(item(index), kDeselectOtherOptionsFlag | kMakeOptionDirtyFlag);
}
int HTMLSelectElement::SelectedListIndex() const {
@@ -919,9 +919,9 @@ void HTMLSelectElement::OptionSelectionStateChanged(HTMLOptionElement* option,
bool option_is_selected) {
DCHECK_EQ(option->OwnerSelectElement(), this);
if (option_is_selected)
- SelectOption(option, IsMultiple() ? 0 : kDeselectOtherOptions);
+ SelectOption(option, IsMultiple() ? 0 : kDeselectOtherOptionsFlag);
else if (!UsesMenuList() || IsMultiple())
- SelectOption(nullptr, IsMultiple() ? 0 : kDeselectOtherOptions);
+ SelectOption(nullptr, IsMultiple() ? 0 : kDeselectOtherOptionsFlag);
else
ResetToDefaultSelection();
}
@@ -931,7 +931,7 @@ void HTMLSelectElement::OptionInserted(HTMLOptionElement& option,
DCHECK_EQ(option.OwnerSelectElement(), this);
SetRecalcListItems();
if (option_is_selected) {
- SelectOption(&option, IsMultiple() ? 0 : kDeselectOtherOptions);
+ SelectOption(&option, IsMultiple() ? 0 : kDeselectOtherOptionsFlag);
} else {
// No need to reset if we already have a selected option.
if (!last_on_change_option_)
@@ -1009,12 +1009,12 @@ void HTMLSelectElement::SelectOption(HTMLOptionElement* element,
if (!element->Selected())
should_update_popup = true;
element->SetSelectedState(true);
- if (flags & kMakeOptionDirty)
+ if (flags & kMakeOptionDirtyFlag)
element->SetDirty(true);
}
// DeselectItemsWithoutValidation() is O(N).
- if (flags & kDeselectOtherOptions)
+ if (flags & kDeselectOtherOptionsFlag)
should_update_popup |= DeselectItemsWithoutValidation(element);
// We should update active selection after finishing OPTION state change
@@ -1022,10 +1022,10 @@ void HTMLSelectElement::SelectOption(HTMLOptionElement* element,
if (element) {
// setActiveSelectionAnchor is O(N).
if (!active_selection_anchor_ || !IsMultiple() ||
- flags & kDeselectOtherOptions)
+ flags & kDeselectOtherOptionsFlag)
SetActiveSelectionAnchor(element);
if (!active_selection_end_ || !IsMultiple() ||
- flags & kDeselectOtherOptions)
+ flags & kDeselectOtherOptionsFlag)
SetActiveSelectionEnd(element);
}
@@ -1033,7 +1033,7 @@ void HTMLSelectElement::SelectOption(HTMLOptionElement* element,
// LayoutMenuList::UpdateFromElement.
bool should_dispatch_events = false;
if (UsesMenuList()) {
- should_dispatch_events = (flags & kDispatchInputAndChangeEvent) &&
+ should_dispatch_events = (flags & kDispatchInputAndChangeEventFlag) &&
last_on_change_option_ != element;
last_on_change_option_ = element;
}
@@ -1163,7 +1163,7 @@ void HTMLSelectElement::RestoreFormControlState(const FormControlState& state) {
if (items_size == 0)
return;
- SelectOption(nullptr, kDeselectOtherOptions);
+ SelectOption(nullptr, kDeselectOtherOptionsFlag);
// The saved state should have at least one value and an index.
DCHECK_GE(state.ValueSize(), 2u);
@@ -1222,7 +1222,7 @@ void HTMLSelectElement::ParseMultipleAttribute(const AtomicString& value) {
// WebKit. However Edge seems to "ask for a reset" simply. As of 2016
// March, the HTML specification says nothing about this.
if (old_selected_option)
- SelectOption(old_selected_option, kDeselectOtherOptions);
+ SelectOption(old_selected_option, kDeselectOtherOptionsFlag);
else
ResetToDefaultSelection();
}
@@ -1241,7 +1241,7 @@ void HTMLSelectElement::AppendToFormData(FormData& form_data) {
void HTMLSelectElement::ResetImpl() {
for (auto* const option : GetOptionList()) {
- option->SetSelectedState(option->FastHasAttribute(selectedAttr));
+ option->SetSelectedState(option->FastHasAttribute(kSelectedAttr));
option->SetDirty(false);
}
ResetToDefaultSelection();
@@ -1293,7 +1293,7 @@ bool HTMLSelectElement::ShouldOpenPopupForKeyPressEvent(
}
void HTMLSelectElement::MenuListDefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::keydown) {
+ if (event.type() == event_type_names::kKeydown) {
if (!GetLayoutObject() || !event.IsKeyboardEvent())
return;
@@ -1345,15 +1345,15 @@ void HTMLSelectElement::MenuListDefaultEventHandler(Event& event) {
handled = false;
if (handled && option) {
- SelectOption(option, kDeselectOtherOptions | kMakeOptionDirty |
- kDispatchInputAndChangeEvent);
+ SelectOption(option, kDeselectOtherOptionsFlag | kMakeOptionDirtyFlag |
+ kDispatchInputAndChangeEventFlag);
}
if (handled)
event.SetDefaultHandled();
}
- if (event.type() == EventTypeNames::keypress) {
+ if (event.type() == event_type_names::kKeypress) {
if (!GetLayoutObject() || !event.IsKeyboardEvent())
return;
@@ -1381,7 +1381,7 @@ void HTMLSelectElement::MenuListDefaultEventHandler(Event& event) {
}
}
- if (event.type() == EventTypeNames::mousedown && event.IsMouseEvent() &&
+ if (event.type() == event_type_names::kMousedown && event.IsMouseEvent() &&
ToMouseEvent(event).button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
InputDeviceCapabilities* source_capabilities =
@@ -1491,7 +1491,7 @@ void HTMLSelectElement::HandleMouseRelease() {
}
void HTMLSelectElement::ListBoxDefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::gesturetap && event.IsGestureEvent()) {
+ if (event.type() == event_type_names::kGesturetap && event.IsGestureEvent()) {
focus();
// Calling focus() may cause us to lose our layoutObject or change the
// layoutObject type, in which case do not want to handle the event.
@@ -1508,7 +1508,7 @@ void HTMLSelectElement::ListBoxDefaultEventHandler(Event& event) {
event.SetDefaultHandled();
}
- } else if (event.type() == EventTypeNames::mousedown &&
+ } else if (event.type() == event_type_names::kMousedown &&
event.IsMouseEvent() &&
ToMouseEvent(event).button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
@@ -1537,7 +1537,7 @@ void HTMLSelectElement::ListBoxDefaultEventHandler(Event& event) {
event.SetDefaultHandled();
}
- } else if (event.type() == EventTypeNames::mousemove &&
+ } else if (event.type() == event_type_names::kMousemove &&
event.IsMouseEvent()) {
auto& mouse_event = ToMouseEvent(event);
if (mouse_event.button() !=
@@ -1573,7 +1573,8 @@ void HTMLSelectElement::ListBoxDefaultEventHandler(Event& event) {
}
}
- } else if (event.type() == EventTypeNames::mouseup && event.IsMouseEvent() &&
+ } else if (event.type() == event_type_names::kMouseup &&
+ event.IsMouseEvent() &&
ToMouseEvent(event).button() ==
static_cast<short>(WebPointerProperties::Button::kLeft) &&
GetLayoutObject()) {
@@ -1586,7 +1587,7 @@ void HTMLSelectElement::ListBoxDefaultEventHandler(Event& event) {
else
HandleMouseRelease();
- } else if (event.type() == EventTypeNames::keydown) {
+ } else if (event.type() == event_type_names::kKeydown) {
if (!event.IsKeyboardEvent())
return;
const String& key = ToKeyboardEvent(event).key();
@@ -1683,7 +1684,7 @@ void HTMLSelectElement::ListBoxDefaultEventHandler(Event& event) {
event.SetDefaultHandled();
}
- } else if (event.type() == EventTypeNames::keypress) {
+ } else if (event.type() == event_type_names::kKeypress) {
if (!event.IsKeyboardEvent())
return;
int key_code = ToKeyboardEvent(event).keyCode();
@@ -1708,8 +1709,8 @@ void HTMLSelectElement::DefaultEventHandler(Event& event) {
if (!GetLayoutObject())
return;
- if (event.type() == EventTypeNames::click ||
- event.type() == EventTypeNames::change) {
+ if (event.type() == event_type_names::kClick ||
+ event.type() == event_type_names::kChange) {
user_has_edited_the_field_ = true;
}
@@ -1725,11 +1726,11 @@ void HTMLSelectElement::DefaultEventHandler(Event& event) {
if (event.DefaultHandled())
return;
- if (event.type() == EventTypeNames::keypress && event.IsKeyboardEvent()) {
+ if (event.type() == event_type_names::kKeypress && event.IsKeyboardEvent()) {
auto& keyboard_event = ToKeyboardEvent(event);
if (!keyboard_event.ctrlKey() && !keyboard_event.altKey() &&
!keyboard_event.metaKey() &&
- WTF::Unicode::IsPrintableChar(keyboard_event.charCode())) {
+ WTF::unicode::IsPrintableChar(keyboard_event.charCode())) {
TypeAheadFind(keyboard_event);
event.SetDefaultHandled();
return;
@@ -1770,9 +1771,9 @@ void HTMLSelectElement::TypeAheadFind(const KeyboardEvent& event) {
event, TypeAhead::kMatchPrefix | TypeAhead::kCycleFirstChar);
if (index < 0)
return;
- SelectOption(OptionAtListIndex(index), kDeselectOtherOptions |
- kMakeOptionDirty |
- kDispatchInputAndChangeEvent);
+ SelectOption(OptionAtListIndex(index), kDeselectOtherOptionsFlag |
+ kMakeOptionDirtyFlag |
+ kDispatchInputAndChangeEventFlag);
if (!UsesMenuList())
ListBoxOnChange();
}
@@ -1787,8 +1788,8 @@ void HTMLSelectElement::SelectOptionByAccessKey(HTMLOptionElement* option) {
EventQueueScope scope;
// If this index is already selected, unselect. otherwise update the
// selected index.
- SelectOptionFlags flags =
- kDispatchInputAndChangeEvent | (IsMultiple() ? 0 : kDeselectOtherOptions);
+ SelectOptionFlags flags = kDispatchInputAndChangeEventFlag |
+ (IsMultiple() ? 0 : kDeselectOtherOptionsFlag);
if (option->Selected()) {
if (UsesMenuList())
SelectOption(nullptr, flags);
@@ -1951,8 +1952,8 @@ void HTMLSelectElement::SelectOptionByPopup(int list_index) {
// the selected option is not change.
if (option == SelectedOption())
return;
- SelectOption(option, kDeselectOtherOptions | kMakeOptionDirty |
- kDispatchInputAndChangeEvent);
+ SelectOption(option, kDeselectOtherOptionsFlag | kMakeOptionDirtyFlag |
+ kDispatchInputAndChangeEventFlag);
}
void HTMLSelectElement::PopupDidCancel() {
@@ -2020,15 +2021,15 @@ class HTMLSelectElement::PopupUpdater : public MutationObserver::Delegate {
public:
explicit PopupUpdater(HTMLSelectElement& select)
: select_(select), observer_(MutationObserver::Create(this)) {
- MutationObserverInit init;
- init.setAttributeOldValue(true);
- init.setAttributes(true);
+ MutationObserverInit* init = MutationObserverInit::Create();
+ init->setAttributeOldValue(true);
+ init->setAttributes(true);
// Observe only attributes which affect popup content.
- init.setAttributeFilter({"disabled", "label", "selected", "value"});
- init.setCharacterData(true);
- init.setCharacterDataOldValue(true);
- init.setChildList(true);
- init.setSubtree(true);
+ init->setAttributeFilter({"disabled", "label", "selected", "value"});
+ init->setCharacterData(true);
+ init->setCharacterDataOldValue(true);
+ init->setChildList(true);
+ init->setSubtree(true);
observer_->observe(select_, init, ASSERT_NO_EXCEPTION);
}
@@ -2071,7 +2072,7 @@ class HTMLSelectElement::PopupUpdater : public MutationObserver::Delegate {
void HTMLSelectElement::ObserveTreeMutation() {
DCHECK(!popup_updater_);
- popup_updater_ = new PopupUpdater(*this);
+ popup_updater_ = MakeGarbageCollected<PopupUpdater>(*this);
}
void HTMLSelectElement::UnobserveTreeMutation() {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_select_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_select_element.h
index eab2da244ec..b3d7f77fe01 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_select_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_select_element.h
@@ -53,6 +53,8 @@ class CORE_EXPORT HTMLSelectElement final
public:
static HTMLSelectElement* Create(Document&);
+
+ explicit HTMLSelectElement(Document&);
~HTMLSelectElement() override;
int selectedIndex() const;
@@ -176,9 +178,6 @@ class CORE_EXPORT HTMLSelectElement final
void CloneNonAttributePropertiesFrom(const Element&,
CloneChildrenFlag) override;
- protected:
- explicit HTMLSelectElement(Document&);
-
private:
const AtomicString& FormControlType() const override;
@@ -233,9 +232,9 @@ class CORE_EXPORT HTMLSelectElement final
bool HasPlaceholderLabelOption() const;
enum SelectOptionFlag {
- kDeselectOtherOptions = 1 << 0,
- kDispatchInputAndChangeEvent = 1 << 1,
- kMakeOptionDirty = 1 << 2,
+ kDeselectOtherOptionsFlag = 1 << 0,
+ kDispatchInputAndChangeEventFlag = 1 << 1,
+ kMakeOptionDirtyFlag = 1 << 2,
};
typedef unsigned SelectOptionFlags;
void SelectOption(HTMLOptionElement*, SelectOptionFlags);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_select_element_test.cc b/chromium/third_party/blink/renderer/core/html/forms/html_select_element_test.cc
index ba3bf9504b8..b6ffdc4838f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_select_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_select_element_test.cc
@@ -158,7 +158,7 @@ TEST_F(HTMLSelectElementTest, FirstSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->FirstSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -167,7 +167,7 @@ TEST_F(HTMLSelectElementTest, FirstSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->FirstSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -176,7 +176,7 @@ TEST_F(HTMLSelectElementTest, FirstSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->FirstSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -185,7 +185,7 @@ TEST_F(HTMLSelectElementTest, FirstSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->FirstSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
}
@@ -202,7 +202,7 @@ TEST_F(HTMLSelectElementTest, LastSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->LastSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -211,7 +211,7 @@ TEST_F(HTMLSelectElementTest, LastSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->LastSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -220,7 +220,7 @@ TEST_F(HTMLSelectElementTest, LastSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->LastSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -229,7 +229,7 @@ TEST_F(HTMLSelectElementTest, LastSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->LastSelectableOption()->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
}
@@ -246,7 +246,7 @@ TEST_F(HTMLSelectElementTest, NextSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->NextSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -255,7 +255,7 @@ TEST_F(HTMLSelectElementTest, NextSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->NextSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -264,7 +264,7 @@ TEST_F(HTMLSelectElementTest, NextSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->NextSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -273,7 +273,7 @@ TEST_F(HTMLSelectElementTest, NextSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->NextSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -282,7 +282,7 @@ TEST_F(HTMLSelectElementTest, NextSelectableOption) {
ToHTMLSelectElement(GetDocument().body()->firstChild());
HTMLOptionElement* option = ToHTMLOptionElement(GetElementById("o1"));
EXPECT_EQ("o2", select->NextSelectableOption(option)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
EXPECT_EQ(nullptr, select->NextSelectableOption(
ToHTMLOptionElement(GetElementById("o2"))));
@@ -295,7 +295,7 @@ TEST_F(HTMLSelectElementTest, NextSelectableOption) {
ToHTMLSelectElement(GetDocument().body()->firstChild());
HTMLOptionElement* option = ToHTMLOptionElement(GetElementById("o1"));
EXPECT_EQ("o2", select->NextSelectableOption(option)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
}
@@ -312,7 +312,7 @@ TEST_F(HTMLSelectElementTest, PreviousSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->PreviousSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -321,7 +321,7 @@ TEST_F(HTMLSelectElementTest, PreviousSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->PreviousSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -330,7 +330,7 @@ TEST_F(HTMLSelectElementTest, PreviousSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o1", select->PreviousSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -339,7 +339,7 @@ TEST_F(HTMLSelectElementTest, PreviousSelectableOption) {
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
EXPECT_EQ("o2", select->PreviousSelectableOption(nullptr)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
{
SetHtmlInnerHTML(
@@ -348,7 +348,7 @@ TEST_F(HTMLSelectElementTest, PreviousSelectableOption) {
ToHTMLSelectElement(GetDocument().body()->firstChild());
HTMLOptionElement* option = ToHTMLOptionElement(GetElementById("o2"));
EXPECT_EQ("o1", select->PreviousSelectableOption(option)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
EXPECT_EQ(nullptr, select->PreviousSelectableOption(
ToHTMLOptionElement(GetElementById("o1"))));
@@ -361,7 +361,7 @@ TEST_F(HTMLSelectElementTest, PreviousSelectableOption) {
ToHTMLSelectElement(GetDocument().body()->firstChild());
HTMLOptionElement* option = ToHTMLOptionElement(GetElementById("o2"));
EXPECT_EQ("o1", select->PreviousSelectableOption(option)->FastGetAttribute(
- HTMLNames::idAttr));
+ html_names::kIdAttr));
}
}
@@ -394,7 +394,7 @@ TEST_F(HTMLSelectElementTest, DefaultToolTip) {
EXPECT_EQ(select->DefaultToolTip(), option->DefaultToolTip());
EXPECT_EQ(select->DefaultToolTip(), optgroup->DefaultToolTip());
- select->SetBooleanAttribute(HTMLNames::requiredAttr, true);
+ select->SetBooleanAttribute(html_names::kRequiredAttr, true);
EXPECT_EQ("<<ValidationValueMissingForSelect>>", select->DefaultToolTip())
<< "defaultToolTip for SELECT without FORM and with required attribute "
"should return a valueMissing message.";
@@ -410,7 +410,7 @@ TEST_F(HTMLSelectElementTest, DefaultToolTip) {
EXPECT_EQ(select->DefaultToolTip(), option->DefaultToolTip());
EXPECT_EQ(select->DefaultToolTip(), optgroup->DefaultToolTip());
- form->SetBooleanAttribute(HTMLNames::novalidateAttr, true);
+ form->SetBooleanAttribute(html_names::kNovalidateAttr, true);
EXPECT_EQ(String(), select->DefaultToolTip())
<< "defaultToolTip for SELECT with FORM[novalidate] and required "
"attribute should return null string.";
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.cc b/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.cc
index 0cf9a4bb9d1..5fd9bc37f46 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.cc
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/before_text_inserted_event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
@@ -53,7 +54,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static const unsigned kDefaultRows = 2;
static const unsigned kDefaultCols = 20;
@@ -69,7 +70,7 @@ static inline unsigned ComputeLengthForAPIValue(const String& text) {
}
HTMLTextAreaElement::HTMLTextAreaElement(Document& document)
- : TextControlElement(textareaTag, document),
+ : TextControlElement(kTextareaTag, document),
rows_(kDefaultRows),
cols_(kDefaultCols),
wrap_(kSoftWrap),
@@ -77,7 +78,8 @@ HTMLTextAreaElement::HTMLTextAreaElement(Document& document)
is_placeholder_visible_(false) {}
HTMLTextAreaElement* HTMLTextAreaElement::Create(Document& document) {
- HTMLTextAreaElement* text_area = new HTMLTextAreaElement(document);
+ HTMLTextAreaElement* text_area =
+ MakeGarbageCollected<HTMLTextAreaElement>(document);
text_area->EnsureUserAgentShadowRoot();
return text_area;
}
@@ -111,13 +113,13 @@ void HTMLTextAreaElement::ChildrenChanged(const ChildrenChange& change) {
bool HTMLTextAreaElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
// Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
// See http://bugs.webkit.org/show_bug.cgi?id=7075
return false;
}
- if (name == wrapAttr)
+ if (name == kWrapAttr)
return true;
return TextControlElement::IsPresentationAttribute(name);
}
@@ -126,7 +128,7 @@ void HTMLTextAreaElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == wrapAttr) {
+ if (name == kWrapAttr) {
if (ShouldWrapText()) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace,
CSSValuePreWrap);
@@ -148,7 +150,7 @@ void HTMLTextAreaElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == rowsAttr) {
+ if (name == kRowsAttr) {
unsigned rows = 0;
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, rows) ||
rows <= 0 || rows > 0x7fffffffu)
@@ -158,10 +160,10 @@ void HTMLTextAreaElement::ParseAttribute(
if (GetLayoutObject()) {
GetLayoutObject()
->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
}
}
- } else if (name == colsAttr) {
+ } else if (name == kColsAttr) {
unsigned cols = 0;
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, cols) ||
cols <= 0 || cols > 0x7fffffffu)
@@ -171,10 +173,10 @@ void HTMLTextAreaElement::ParseAttribute(
if (LayoutObject* layout_object = GetLayoutObject()) {
layout_object
->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
}
}
- } else if (name == wrapAttr) {
+ } else if (name == kWrapAttr) {
// The virtual/physical values were a Netscape extension of HTML 3.0, now
// deprecated. The soft/hard /off values are a recommendation for HTML 4
// extension by IE and NS 4.
@@ -192,15 +194,15 @@ void HTMLTextAreaElement::ParseAttribute(
if (LayoutObject* layout_object = GetLayoutObject()) {
layout_object
->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
}
}
- } else if (name == accesskeyAttr) {
+ } else if (name == kAccesskeyAttr) {
// ignore for the moment
- } else if (name == maxlengthAttr) {
+ } else if (name == kMaxlengthAttr) {
UseCounter::Count(GetDocument(), WebFeature::kTextAreaMaxLength);
SetNeedsValidityCheck();
- } else if (name == minlengthAttr) {
+ } else if (name == kMinlengthAttr) {
UseCounter::Count(GetDocument(), WebFeature::kTextAreaMinLength);
SetNeedsValidityCheck();
} else {
@@ -222,7 +224,7 @@ void HTMLTextAreaElement::AppendToFormData(FormData& form_data) {
(wrap_ == kHardWrap) ? ValueWithHardLineBreaks() : value();
form_data.AppendFromElement(GetName(), text);
- const AtomicString& dirname_attr_value = FastGetAttribute(dirnameAttr);
+ const AtomicString& dirname_attr_value = FastGetAttribute(kDirnameAttr);
if (!dirname_attr_value.IsNull())
form_data.AppendFromElement(dirname_attr_value, DirectionForFormData());
}
@@ -247,7 +249,7 @@ bool HTMLTextAreaElement::MayTriggerVirtualKeyboard() const {
void HTMLTextAreaElement::UpdateFocusAppearanceWithOptions(
SelectionBehaviorOnFocus selection_behavior,
- const FocusOptions& options) {
+ const FocusOptions* options) {
switch (selection_behavior) {
case SelectionBehaviorOnFocus::kReset: // Fallthrough.
case SelectionBehaviorOnFocus::kRestore:
@@ -256,16 +258,17 @@ void HTMLTextAreaElement::UpdateFocusAppearanceWithOptions(
case SelectionBehaviorOnFocus::kNone:
return;
}
- if (!options.preventScroll()) {
+ if (!options->preventScroll()) {
if (GetDocument().GetFrame())
GetDocument().GetFrame()->Selection().RevealSelection();
}
}
void HTMLTextAreaElement::DefaultEventHandler(Event& event) {
- if (GetLayoutObject() && (event.IsMouseEvent() || event.IsDragEvent() ||
- event.HasInterface(EventNames::WheelEvent) ||
- event.type() == EventTypeNames::blur)) {
+ if (GetLayoutObject() &&
+ (event.IsMouseEvent() || event.IsDragEvent() ||
+ event.HasInterface(event_interface_names::kWheelEvent) ||
+ event.type() == event_type_names::kBlur)) {
ForwardEvent(event);
} else if (GetLayoutObject() && event.IsBeforeTextInsertedEvent()) {
HandleBeforeTextInsertedEvent(
@@ -418,7 +421,7 @@ void HTMLTextAreaElement::SetValueCommon(
UpdatePlaceholderVisibility();
SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
+ StyleChangeReasonForTracing::Create(style_change_reason::kControlValue));
SetNeedsValidityCheck();
if (IsFinishedParsingChildren() &&
selection == TextControlSetValueSelection::kSetSelectionToEnd) {
@@ -482,7 +485,7 @@ void HTMLTextAreaElement::SetSuggestedValue(const String& value) {
TextControlElement::SetSuggestedValue(value);
SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
+ StyleChangeReasonForTracing::Create(style_change_reason::kControlValue));
}
String HTMLTextAreaElement::validationMessage() const {
@@ -569,12 +572,12 @@ void HTMLTextAreaElement::AccessKeyAction(bool) {
}
void HTMLTextAreaElement::setCols(unsigned cols) {
- SetUnsignedIntegralAttribute(colsAttr, cols ? cols : kDefaultCols,
+ SetUnsignedIntegralAttribute(kColsAttr, cols ? cols : kDefaultCols,
kDefaultCols);
}
void HTMLTextAreaElement::setRows(unsigned rows) {
- SetUnsignedIntegralAttribute(rowsAttr, rows ? rows : kDefaultRows,
+ SetUnsignedIntegralAttribute(kRowsAttr, rows ? rows : kDefaultRows,
kDefaultRows);
}
@@ -602,7 +605,7 @@ void HTMLTextAreaElement::UpdatePlaceholderText() {
HTMLDivElement* new_element = HTMLDivElement::Create(GetDocument());
placeholder = new_element;
placeholder->SetShadowPseudoId(AtomicString("-webkit-input-placeholder"));
- placeholder->setAttribute(idAttr, ShadowElementNames::Placeholder());
+ placeholder->setAttribute(kIdAttr, shadow_element_names::Placeholder());
placeholder->SetInlineStyleProperty(
CSSPropertyDisplay,
IsPlaceholderVisible() ? CSSValueBlock : CSSValueNone, true);
@@ -613,7 +616,7 @@ void HTMLTextAreaElement::UpdatePlaceholderText() {
String HTMLTextAreaElement::GetPlaceholderValue() const {
return !SuggestedValue().IsEmpty() ? SuggestedValue()
- : FastGetAttribute(placeholderAttr);
+ : FastGetAttribute(kPlaceholderAttr);
}
bool HTMLTextAreaElement::IsInteractiveContent() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.h b/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.h
index 90d2379e4c9..8af71e66d33 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.h
@@ -38,6 +38,8 @@ class CORE_EXPORT HTMLTextAreaElement final : public TextControlElement {
public:
static HTMLTextAreaElement* Create(Document&);
+ explicit HTMLTextAreaElement(Document&);
+
unsigned cols() const { return cols_; }
unsigned rows() const { return rows_; }
@@ -66,7 +68,6 @@ class CORE_EXPORT HTMLTextAreaElement final : public TextControlElement {
private:
FRIEND_TEST_ALL_PREFIXES(HTMLTextAreaElementTest, SanitizeUserInputValue);
- explicit HTMLTextAreaElement(Document&);
enum WrapMethod { kNoWrap, kSoftWrap, kHardWrap };
@@ -125,7 +126,7 @@ class CORE_EXPORT HTMLTextAreaElement final : public TextControlElement {
bool MayTriggerVirtualKeyboard() const override;
bool IsKeyboardFocusable() const override;
void UpdateFocusAppearanceWithOptions(SelectionBehaviorOnFocus,
- const FocusOptions&) override;
+ const FocusOptions*) override;
void AccessKeyAction(bool send_mouse_events) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/image_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/image_input_type.cc
index 7a92a205fbc..cbdad34e6a7 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/image_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/image_input_type.cc
@@ -41,17 +41,17 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline ImageInputType::ImageInputType(HTMLInputElement& element)
: BaseButtonInputType(element), use_fallback_content_(false) {}
InputType* ImageInputType::Create(HTMLInputElement& element) {
- return new ImageInputType(element);
+ return MakeGarbageCollected<ImageInputType>(element);
}
const AtomicString& ImageInputType::FormControlType() const {
- return InputTypeNames::image;
+ return input_type_names::kImage;
}
bool ImageInputType::IsFormDataAppendable() const {
@@ -175,7 +175,7 @@ unsigned ImageInputType::Height() const {
if (!GetElement().GetLayoutObject()) {
// Check the attribute first for an explicit pixel value.
unsigned height;
- if (ParseHTMLNonNegativeInteger(GetElement().FastGetAttribute(heightAttr),
+ if (ParseHTMLNonNegativeInteger(GetElement().FastGetAttribute(kHeightAttr),
height))
return height;
@@ -200,7 +200,7 @@ unsigned ImageInputType::Width() const {
if (!GetElement().GetLayoutObject()) {
// Check the attribute first for an explicit pixel value.
unsigned width;
- if (ParseHTMLNonNegativeInteger(GetElement().FastGetAttribute(widthAttr),
+ if (ParseHTMLNonNegativeInteger(GetElement().FastGetAttribute(kWidthAttr),
width))
return width;
@@ -222,11 +222,11 @@ unsigned ImageInputType::Width() const {
}
bool ImageInputType::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == srcAttr || BaseButtonInputType::HasLegalLinkAttribute(name);
+ return name == kSrcAttr || BaseButtonInputType::HasLegalLinkAttribute(name);
}
const QualifiedName& ImageInputType::SubResourceAttributeName() const {
- return srcAttr;
+ return kSrcAttr;
}
void ImageInputType::EnsureFallbackContent() {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/image_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/image_input_type.h
index b7df5596ff6..0fc4ea61368 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/image_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/image_input_type.h
@@ -41,11 +41,11 @@ namespace blink {
class ImageInputType final : public BaseButtonInputType {
public:
static InputType* Create(HTMLInputElement&);
+ ImageInputType(HTMLInputElement&);
scoped_refptr<ComputedStyle> CustomStyleForLayoutObject(
scoped_refptr<ComputedStyle>) override;
private:
- ImageInputType(HTMLInputElement&);
const AtomicString& FormControlType() const override;
bool IsFormDataAppendable() const override;
void AppendToFormData(FormData&) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/input_type.cc
index a2771e45ee4..c2949159589 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/input_type.cc
@@ -76,7 +76,7 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
+using namespace html_names;
using InputTypeFactoryFunction = InputType* (*)(HTMLInputElement&);
using InputTypeFactoryMap = HashMap<AtomicString, InputTypeFactoryFunction>;
@@ -84,27 +84,27 @@ using InputTypeFactoryMap = HashMap<AtomicString, InputTypeFactoryFunction>;
static std::unique_ptr<InputTypeFactoryMap> CreateInputTypeFactoryMap() {
std::unique_ptr<InputTypeFactoryMap> map =
std::make_unique<InputTypeFactoryMap>();
- map->insert(InputTypeNames::button, ButtonInputType::Create);
- map->insert(InputTypeNames::checkbox, CheckboxInputType::Create);
- map->insert(InputTypeNames::color, ColorInputType::Create);
- map->insert(InputTypeNames::date, DateInputType::Create);
- map->insert(InputTypeNames::datetime_local, DateTimeLocalInputType::Create);
- map->insert(InputTypeNames::email, EmailInputType::Create);
- map->insert(InputTypeNames::file, FileInputType::Create);
- map->insert(InputTypeNames::hidden, HiddenInputType::Create);
- map->insert(InputTypeNames::image, ImageInputType::Create);
- map->insert(InputTypeNames::month, MonthInputType::Create);
- map->insert(InputTypeNames::number, NumberInputType::Create);
- map->insert(InputTypeNames::password, PasswordInputType::Create);
- map->insert(InputTypeNames::radio, RadioInputType::Create);
- map->insert(InputTypeNames::range, RangeInputType::Create);
- map->insert(InputTypeNames::reset, ResetInputType::Create);
- map->insert(InputTypeNames::search, SearchInputType::Create);
- map->insert(InputTypeNames::submit, SubmitInputType::Create);
- map->insert(InputTypeNames::tel, TelephoneInputType::Create);
- map->insert(InputTypeNames::time, TimeInputType::Create);
- map->insert(InputTypeNames::url, URLInputType::Create);
- map->insert(InputTypeNames::week, WeekInputType::Create);
+ map->insert(input_type_names::kButton, ButtonInputType::Create);
+ map->insert(input_type_names::kCheckbox, CheckboxInputType::Create);
+ map->insert(input_type_names::kColor, ColorInputType::Create);
+ map->insert(input_type_names::kDate, DateInputType::Create);
+ map->insert(input_type_names::kDatetimeLocal, DateTimeLocalInputType::Create);
+ map->insert(input_type_names::kEmail, EmailInputType::Create);
+ map->insert(input_type_names::kFile, FileInputType::Create);
+ map->insert(input_type_names::kHidden, HiddenInputType::Create);
+ map->insert(input_type_names::kImage, ImageInputType::Create);
+ map->insert(input_type_names::kMonth, MonthInputType::Create);
+ map->insert(input_type_names::kNumber, NumberInputType::Create);
+ map->insert(input_type_names::kPassword, PasswordInputType::Create);
+ map->insert(input_type_names::kRadio, RadioInputType::Create);
+ map->insert(input_type_names::kRange, RangeInputType::Create);
+ map->insert(input_type_names::kReset, ResetInputType::Create);
+ map->insert(input_type_names::kSearch, SearchInputType::Create);
+ map->insert(input_type_names::kSubmit, SubmitInputType::Create);
+ map->insert(input_type_names::kTel, TelephoneInputType::Create);
+ map->insert(input_type_names::kTime, TimeInputType::Create);
+ map->insert(input_type_names::kUrl, URLInputType::Create);
+ map->insert(input_type_names::kWeek, WeekInputType::Create);
// No need to register "text" because it is the default type.
return map;
}
@@ -131,10 +131,10 @@ InputType* InputType::CreateText(HTMLInputElement& element) {
const AtomicString& InputType::NormalizeTypeName(
const AtomicString& type_name) {
if (type_name.IsEmpty())
- return InputTypeNames::text;
+ return input_type_names::kText;
InputTypeFactoryMap::const_iterator it =
FactoryMap()->find(type_name.LowerASCII());
- return it == FactoryMap()->end() ? InputTypeNames::text : it->key;
+ return it == FactoryMap()->end() ? input_type_names::kText : it->key;
}
InputType::~InputType() = default;
@@ -161,7 +161,7 @@ void InputType::AppendToFormData(FormData& form_data) const {
}
String InputType::ResultForDialogSubmit() const {
- return GetElement().FastGetAttribute(valueAttr);
+ return GetElement().FastGetAttribute(kValueAttr);
}
double InputType::ValueAsDate() const {
@@ -361,7 +361,7 @@ std::pair<String, String> InputType::ValidationMessage(
// is present, when informing the user that the pattern is not matched
return std::make_pair(
GetLocale().QueryString(WebLocalizedString::kValidationPatternMismatch),
- GetElement().FastGetAttribute(titleAttr).GetString());
+ GetElement().FastGetAttribute(kTitleAttr).GetString());
}
if (GetElement().TooLong()) {
@@ -702,7 +702,7 @@ void InputType::ApplyStep(const Decimal& current,
Decimal step = step_range.Step();
EventQueueScope scope;
Decimal new_value = current;
- const AtomicString& step_string = GetElement().FastGetAttribute(stepAttr);
+ const AtomicString& step_string = GetElement().FastGetAttribute(kStepAttr);
if (!DeprecatedEqualIgnoringCase(step_string, "any") &&
step_range.StepMismatch(current)) {
// Snap-to-step / clamping steps
@@ -867,10 +867,11 @@ void InputType::CountUsageIfVisible(WebFeature feature) const {
Decimal InputType::FindStepBase(const Decimal& default_value) const {
Decimal step_base =
- ParseToNumber(GetElement().FastGetAttribute(minAttr), Decimal::Nan());
- if (!step_base.IsFinite())
+ ParseToNumber(GetElement().FastGetAttribute(kMinAttr), Decimal::Nan());
+ if (!step_base.IsFinite()) {
step_base =
- ParseToNumber(GetElement().FastGetAttribute(valueAttr), default_value);
+ ParseToNumber(GetElement().FastGetAttribute(kValueAttr), default_value);
+ }
return step_base;
}
@@ -882,19 +883,19 @@ StepRange InputType::CreateStepRange(
const StepRange::StepDescription& step_description) const {
bool has_range_limitations = false;
const Decimal step_base = FindStepBase(step_base_default);
- Decimal minimum = ParseToNumberOrNaN(GetElement().FastGetAttribute(minAttr));
+ Decimal minimum = ParseToNumberOrNaN(GetElement().FastGetAttribute(kMinAttr));
if (minimum.IsFinite())
has_range_limitations = true;
else
minimum = minimum_default;
- Decimal maximum = ParseToNumberOrNaN(GetElement().FastGetAttribute(maxAttr));
+ Decimal maximum = ParseToNumberOrNaN(GetElement().FastGetAttribute(kMaxAttr));
if (maximum.IsFinite())
has_range_limitations = true;
else
maximum = maximum_default;
const Decimal step =
StepRange::ParseStep(any_step_handling, step_description,
- GetElement().FastGetAttribute(stepAttr));
+ GetElement().FastGetAttribute(kStepAttr));
return StepRange(step_base, minimum, maximum, has_range_limitations, step,
step_description);
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/input_type_names.json5 b/chromium/third_party/blink/renderer/core/html/forms/input_type_names.json5
index 73487a149d6..848598827c0 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/input_type_names.json5
+++ b/chromium/third_party/blink/renderer/core/html/forms/input_type_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "InputType",
+ namespace: "input_type_names",
export: "CORE_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/core/html/forms/input_type_view.cc b/chromium/third_party/blink/renderer/core/html/forms/input_type_view.cc
index 04d1ece53f4..5fdb93d7a2e 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/input_type_view.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/input_type_view.cc
@@ -28,6 +28,7 @@
#include "third_party/blink/renderer/core/html/forms/input_type_view.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/html/forms/form_controller.h"
@@ -77,7 +78,8 @@ void InputTypeView::AccessKeyAction(bool) {
}
bool InputTypeView::ShouldSubmitImplicitly(const Event& event) {
- return event.IsKeyboardEvent() && event.type() == EventTypeNames::keypress &&
+ return event.IsKeyboardEvent() &&
+ event.type() == event_type_names::kKeypress &&
ToKeyboardEvent(event).charCode() == '\r';
}
@@ -96,7 +98,7 @@ scoped_refptr<ComputedStyle> InputTypeView::CustomStyleForLayoutObject(
}
TextDirection InputTypeView::ComputedTextDirection() {
- return GetElement().EnsureComputedStyle()->Direction();
+ return GetElement().ComputedStyleRef().Direction();
}
void InputTypeView::Blur() {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc b/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc
index 56bfa62bee0..12884a037ad 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc
@@ -68,9 +68,11 @@ class PopupMenuCSSFontSelector : public CSSFontSelector,
static PopupMenuCSSFontSelector* Create(
Document* document,
CSSFontSelector* owner_font_selector) {
- return new PopupMenuCSSFontSelector(document, owner_font_selector);
+ return MakeGarbageCollected<PopupMenuCSSFontSelector>(document,
+ owner_font_selector);
}
+ PopupMenuCSSFontSelector(Document*, CSSFontSelector*);
~PopupMenuCSSFontSelector() override;
// We don't override willUseFontData() for now because the old PopupListBox
@@ -81,8 +83,6 @@ class PopupMenuCSSFontSelector : public CSSFontSelector,
void Trace(blink::Visitor*) override;
private:
- PopupMenuCSSFontSelector(Document*, CSSFontSelector*);
-
void FontsNeedUpdate(FontSelector*) override;
Member<CSSFontSelector> owner_font_selector_;
@@ -209,7 +209,7 @@ class InternalPopupMenu::ItemIterationContext {
InternalPopupMenu* InternalPopupMenu::Create(ChromeClient* chrome_client,
HTMLSelectElement& owner_element) {
- return new InternalPopupMenu(chrome_client, owner_element);
+ return MakeGarbageCollected<InternalPopupMenu>(chrome_client, owner_element);
}
InternalPopupMenu::InternalPopupMenu(ChromeClient* chrome_client,
@@ -376,7 +376,7 @@ void InternalPopupMenu::AddOption(ItemIterationContext& context,
if (!element.title().IsEmpty())
AddProperty("title", element.title(), data);
const AtomicString& aria_label =
- element.FastGetAttribute(HTMLNames::aria_labelAttr);
+ element.FastGetAttribute(html_names::kAriaLabelAttr);
if (!aria_label.IsEmpty())
AddProperty("ariaLabel", aria_label, data);
if (element.IsDisabledFormControl())
@@ -392,7 +392,7 @@ void InternalPopupMenu::AddOptGroup(ItemIterationContext& context,
PagePopupClient::AddString("type: \"optgroup\",\n", data);
AddProperty("label", element.GroupLabelText(), data);
AddProperty("title", element.title(), data);
- AddProperty("ariaLabel", element.FastGetAttribute(HTMLNames::aria_labelAttr),
+ AddProperty("ariaLabel", element.FastGetAttribute(html_names::kAriaLabelAttr),
data);
AddProperty("disabled", element.IsDisabledFormControl(), data);
AddElementStyle(context, element);
@@ -406,7 +406,7 @@ void InternalPopupMenu::AddSeparator(ItemIterationContext& context,
PagePopupClient::AddString("{\n", data);
PagePopupClient::AddString("type: \"separator\",\n", data);
AddProperty("title", element.title(), data);
- AddProperty("ariaLabel", element.FastGetAttribute(HTMLNames::aria_labelAttr),
+ AddProperty("ariaLabel", element.FastGetAttribute(html_names::kAriaLabelAttr),
data);
AddProperty("disabled", element.IsDisabledFormControl(), data);
AddElementStyle(context, element);
@@ -448,9 +448,11 @@ void InternalPopupMenu::SetValueAndClosePopup(int num_value,
Element* owner = &OwnerElement();
if (LocalFrame* frame = owner->GetDocument().GetFrame()) {
frame->GetEventHandler().HandleTargetedMouseEvent(
- owner, event, EventTypeNames::mouseup, Vector<WebMouseEvent>());
+ owner, event, event_type_names::kMouseup, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
frame->GetEventHandler().HandleTargetedMouseEvent(
- owner, event, EventTypeNames::click, Vector<WebMouseEvent>());
+ owner, event, event_type_names::kClick, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.h b/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.h
index e3e7a69d08e..d44f353b8da 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/internal_popup_menu.h
@@ -25,6 +25,8 @@ class CORE_EXPORT InternalPopupMenu final : public PopupMenu,
public PagePopupClient {
public:
static InternalPopupMenu* Create(ChromeClient*, HTMLSelectElement&);
+
+ InternalPopupMenu(ChromeClient*, HTMLSelectElement&);
~InternalPopupMenu() override;
void Trace(blink::Visitor*) override;
@@ -33,8 +35,6 @@ class CORE_EXPORT InternalPopupMenu final : public PopupMenu,
void Dispose();
private:
- InternalPopupMenu(ChromeClient*, HTMLSelectElement&);
-
class ItemIterationContext;
void AddOption(ItemIterationContext&, HTMLOptionElement&);
void AddOptGroup(ItemIterationContext&, HTMLOptGroupElement&);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/keyboard_clickable_input_type_view.cc b/chromium/third_party/blink/renderer/core/html/forms/keyboard_clickable_input_type_view.cc
index 31ddcf49a14..ba8e4bb19f8 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/keyboard_clickable_input_type_view.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/keyboard_clickable_input_type_view.cc
@@ -36,8 +36,6 @@
namespace blink {
-using namespace HTMLNames;
-
void KeyboardClickableInputTypeView::HandleKeydownEvent(KeyboardEvent& event) {
if (event.key() == " ") {
GetElement().SetActive(true);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.cc b/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.cc
index e2ff16dda4a..e7d1538a49c 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.cc
@@ -31,8 +31,6 @@
namespace blink {
-using namespace HTMLNames;
-
LabelsNodeList::LabelsNodeList(ContainerNode& owner_node)
: LiveNodeList(owner_node,
kLabelsNodeListType,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.h b/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.h
index fa5b33993ce..432e7f82934 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/labels_node_list.h
@@ -35,14 +35,13 @@ class LabelsNodeList final : public LiveNodeList {
static LabelsNodeList* Create(ContainerNode& owner_node,
CollectionType type) {
DCHECK_EQ(type, kLabelsNodeListType);
- return new LabelsNodeList(owner_node);
+ return MakeGarbageCollected<LabelsNodeList>(owner_node);
}
+ explicit LabelsNodeList(ContainerNode&);
~LabelsNodeList() override;
protected:
- explicit LabelsNodeList(ContainerNode&);
-
bool ElementMatches(const Element&) const override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/listed_element.cc b/chromium/third_party/blink/renderer/core/html/forms/listed_element.cc
index ff7a94f7862..d2cf8cd9da1 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/listed_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/listed_element.cc
@@ -24,28 +24,33 @@
#include "third_party/blink/renderer/core/html/forms/listed_element.h"
+#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/id_target_observer.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
+#include "third_party/blink/renderer/core/html/custom/element_internals.h"
+#include "third_party/blink/renderer/core/html/forms/html_field_set_element.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
+#include "third_party/blink/renderer/core/html/forms/html_legend_element.h"
#include "third_party/blink/renderer/core/html/forms/validity_state.h"
#include "third_party/blink/renderer/core/html/html_object_element.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class FormAttributeTargetObserver : public IdTargetObserver {
public:
static FormAttributeTargetObserver* Create(const AtomicString& id,
ListedElement*);
+
+ FormAttributeTargetObserver(const AtomicString& id, ListedElement*);
+
void Trace(blink::Visitor*) override;
void IdTargetChanged() override;
private:
- FormAttributeTargetObserver(const AtomicString& id, ListedElement*);
-
Member<ListedElement> element_;
};
@@ -70,11 +75,15 @@ ValidityState* ListedElement::validity() {
void ListedElement::DidMoveToNewDocument(Document& old_document) {
HTMLElement* element = ToHTMLElement(this);
- if (element->FastHasAttribute(formAttr))
+ if (element->FastHasAttribute(kFormAttr))
SetFormAttributeTargetObserver(nullptr);
}
void ListedElement::InsertedInto(ContainerNode& insertion_point) {
+ ancestor_disabled_state_ = AncestorDisabledState::kUnknown;
+ // Force traversal to find ancestor
+ may_have_field_set_ancestor_ = true;
+
if (!form_was_set_by_parser_ || !form_ ||
NodeTraversal::HighestAncestorOrSelf(insertion_point) !=
NodeTraversal::HighestAncestorOrSelf(*form_.Get()))
@@ -84,13 +93,15 @@ void ListedElement::InsertedInto(ContainerNode& insertion_point) {
return;
HTMLElement* element = ToHTMLElement(this);
- if (element->FastHasAttribute(formAttr))
+ if (element->FastHasAttribute(kFormAttr))
ResetFormAttributeTargetObserver();
}
void ListedElement::RemovedFrom(ContainerNode& insertion_point) {
+ ancestor_disabled_state_ = AncestorDisabledState::kUnknown;
+
HTMLElement* element = ToHTMLElement(this);
- if (insertion_point.isConnected() && element->FastHasAttribute(formAttr)) {
+ if (insertion_point.isConnected() && element->FastHasAttribute(kFormAttr)) {
SetFormAttributeTargetObserver(nullptr);
ResetFormOwner();
return;
@@ -167,7 +178,7 @@ void ListedElement::DidChangeForm() {
void ListedElement::ResetFormOwner() {
form_was_set_by_parser_ = false;
HTMLElement* element = ToHTMLElement(this);
- const AtomicString& form_id(element->FastGetAttribute(formAttr));
+ const AtomicString& form_id(element->FastGetAttribute(kFormAttr));
HTMLFormElement* nearest_form = element->FindFormAncestor();
// 1. If the element's form owner is not null, and either the element is not
// reassociateable or its form content attribute is not present, and the
@@ -249,6 +260,58 @@ void ListedElement::setCustomValidity(const String& error) {
custom_validation_message_ = error;
}
+void ListedElement::DisabledAttributeChanged() {
+ HTMLElement& element = ToHTMLElement(*this);
+ element.PseudoStateChanged(CSSSelector::kPseudoDisabled);
+ element.PseudoStateChanged(CSSSelector::kPseudoEnabled);
+}
+
+void ListedElement::UpdateAncestorDisabledState() const {
+ if (!may_have_field_set_ancestor_) {
+ ancestor_disabled_state_ = AncestorDisabledState::kEnabled;
+ return;
+ }
+ may_have_field_set_ancestor_ = false;
+ // <fieldset> element of which |disabled| attribute affects the
+ // target element.
+ HTMLFieldSetElement* disabled_fieldset_ancestor = nullptr;
+ ContainerNode* last_legend_ancestor = nullptr;
+ for (HTMLElement* ancestor =
+ Traversal<HTMLElement>::FirstAncestor(ToHTMLElement(*this));
+ ancestor; ancestor = Traversal<HTMLElement>::FirstAncestor(*ancestor)) {
+ if (IsHTMLLegendElement(*ancestor)) {
+ last_legend_ancestor = ancestor;
+ continue;
+ }
+ if (!IsHTMLFieldSetElement(*ancestor))
+ continue;
+ may_have_field_set_ancestor_ = true;
+ if (ancestor->IsDisabledFormControl()) {
+ auto* fieldset = ToHTMLFieldSetElement(ancestor);
+ if (last_legend_ancestor && last_legend_ancestor == fieldset->Legend())
+ continue;
+ disabled_fieldset_ancestor = fieldset;
+ break;
+ }
+ }
+ ancestor_disabled_state_ = disabled_fieldset_ancestor
+ ? AncestorDisabledState::kDisabled
+ : AncestorDisabledState::kEnabled;
+}
+
+void ListedElement::AncestorDisabledStateWasChanged() {
+ ancestor_disabled_state_ = AncestorDisabledState::kUnknown;
+ DisabledAttributeChanged();
+}
+
+bool ListedElement::IsActuallyDisabled() const {
+ if (ToHTMLElement(*this).FastHasAttribute(html_names::kDisabledAttr))
+ return true;
+ if (ancestor_disabled_state_ == AncestorDisabledState::kUnknown)
+ UpdateAncestorDisabledState();
+ return ancestor_disabled_state_ == AncestorDisabledState::kDisabled;
+}
+
void ListedElement::SetFormAttributeTargetObserver(
FormAttributeTargetObserver* new_observer) {
if (form_attribute_target_observer_)
@@ -258,7 +321,7 @@ void ListedElement::SetFormAttributeTargetObserver(
void ListedElement::ResetFormAttributeTargetObserver() {
HTMLElement* element = ToHTMLElement(this);
- const AtomicString& form_id(element->FastGetAttribute(formAttr));
+ const AtomicString& form_id(element->FastGetAttribute(kFormAttr));
if (!form_id.IsNull() && element->isConnected()) {
SetFormAttributeTargetObserver(
FormAttributeTargetObserver::Create(form_id, this));
@@ -280,9 +343,15 @@ bool ListedElement::IsFormControlElementWithState() const {
return false;
}
+bool ListedElement::IsElementInternals() const {
+ return false;
+}
+
const HTMLElement& ToHTMLElement(const ListedElement& listed_element) {
if (listed_element.IsFormControlElement())
return ToHTMLFormControlElement(listed_element);
+ if (listed_element.IsElementInternals())
+ return To<ElementInternals>(listed_element).Target();
return ToHTMLObjectElementFromListedElement(listed_element);
}
@@ -304,7 +373,7 @@ HTMLElement& ToHTMLElement(ListedElement& listed_element) {
FormAttributeTargetObserver* FormAttributeTargetObserver::Create(
const AtomicString& id,
ListedElement* element) {
- return new FormAttributeTargetObserver(id, element);
+ return MakeGarbageCollected<FormAttributeTargetObserver>(id, element);
}
FormAttributeTargetObserver::FormAttributeTargetObserver(const AtomicString& id,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/listed_element.h b/chromium/third_party/blink/renderer/core/html/forms/listed_element.h
index 0da13d53299..577fe86665e 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/listed_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/listed_element.h
@@ -53,6 +53,7 @@ class CORE_EXPORT ListedElement : public GarbageCollectedMixin {
virtual bool IsFormControlElement() const = 0;
virtual bool IsFormControlElementWithState() const;
+ virtual bool IsElementInternals() const;
virtual bool IsEnumeratable() const = 0;
// Returns the 'name' attribute value. If this element has no name
@@ -89,6 +90,13 @@ class CORE_EXPORT ListedElement : public GarbageCollectedMixin {
virtual void setCustomValidity(const String&);
void FormAttributeTargetChanged();
+ void InsertedInto(ContainerNode&);
+ void RemovedFrom(ContainerNode&);
+ void DidMoveToNewDocument(Document& old_document);
+ void AncestorDisabledStateWasChanged();
+
+ // https://html.spec.whatwg.org/multipage/semantics-other.html#concept-element-disabled
+ bool IsActuallyDisabled() const;
typedef HeapVector<Member<ListedElement>> List;
@@ -97,10 +105,6 @@ class CORE_EXPORT ListedElement : public GarbageCollectedMixin {
protected:
ListedElement();
- void InsertedInto(ContainerNode&);
- void RemovedFrom(ContainerNode&);
- void DidMoveToNewDocument(Document& old_document);
-
// FIXME: Remove usage of setForm. resetFormOwner should be enough, and
// setForm is confusing.
void SetForm(HTMLFormElement*);
@@ -115,7 +119,15 @@ class CORE_EXPORT ListedElement : public GarbageCollectedMixin {
String CustomValidationMessage() const;
+ virtual void DisabledAttributeChanged();
+
+ // False; There are no FIELDSET ancestors.
+ // True; There might be a FIELDSET ancestor, and thre might be no
+ // FIELDSET ancestors.
+ mutable bool may_have_field_set_ancestor_ = true;
+
private:
+ void UpdateAncestorDisabledState() const;
void SetFormAttributeTargetObserver(FormAttributeTargetObserver*);
void ResetFormAttributeTargetObserver();
@@ -125,6 +137,10 @@ class CORE_EXPORT ListedElement : public GarbageCollectedMixin {
String custom_validation_message_;
// If form_was_set_by_parser_ is true, form_ is always non-null.
bool form_was_set_by_parser_;
+
+ enum class AncestorDisabledState { kUnknown, kEnabled, kDisabled };
+ mutable AncestorDisabledState ancestor_disabled_state_ =
+ AncestorDisabledState::kUnknown;
};
CORE_EXPORT HTMLElement* ToHTMLElement(ListedElement*);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/mock_file_chooser.h b/chromium/third_party/blink/renderer/core/html/forms/mock_file_chooser.h
new file mode 100644
index 00000000000..2058d12e4be
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/forms/mock_file_chooser.h
@@ -0,0 +1,78 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_MOCK_FILE_CHOOSER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_MOCK_FILE_CHOOSER_H_
+
+#include "mojo/public/cpp/bindings/binding_set.h"
+#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/mojom/choosers/file_chooser.mojom-blink.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
+
+namespace blink {
+
+class MockFileChooser : public mojom::blink::FileChooser {
+ using FileChooser = mojom::blink::FileChooser;
+ using FileChooserFileInfoPtr = mojom::blink::FileChooserFileInfoPtr;
+ using FileChooserParamsPtr = mojom::blink::FileChooserParamsPtr;
+ using FileChooserRequest = mojom::blink::FileChooserRequest;
+
+ public:
+ // |reached_callback| is called when OpenFileChooser() or
+ // |EnumerateChosenDirectory() is called.
+ MockFileChooser(service_manager::InterfaceProvider* provider,
+ base::OnceClosure reached_callback)
+ : provider_(provider), reached_callback_(std::move(reached_callback)) {
+ service_manager::InterfaceProvider::TestApi test_api(provider);
+ test_api.SetBinderForName(
+ FileChooser::Name_,
+ WTF::BindRepeating(&MockFileChooser::OnFileChooserRequest,
+ WTF::Unretained(this)));
+ }
+
+ ~MockFileChooser() override {
+ service_manager::InterfaceProvider::TestApi test_api(provider_);
+ test_api.ClearBinderForName(FileChooser::Name_);
+ }
+
+ void ResponseOnOpenFileChooser(FileChooserFileInfoList files) {
+ DCHECK(callback_)
+ << "OpenFileChooser() or EnumerateChosenDirectory() should "
+ "be called beforehand.";
+ std::move(callback_).Run(mojom::blink::FileChooserResult::New(
+ std::move(files), base::FilePath()));
+ bindings_.FlushForTesting();
+ }
+
+ private:
+ void OnFileChooserRequest(mojo::ScopedMessagePipeHandle handle) {
+ bindings_.AddBinding(this, FileChooserRequest(std::move(handle)));
+ }
+
+ void OpenFileChooser(FileChooserParamsPtr params,
+ OpenFileChooserCallback callback) override {
+ DCHECK(!callback_);
+ callback_ = std::move(callback);
+ if (reached_callback_)
+ std::move(reached_callback_).Run();
+ }
+
+ void EnumerateChosenDirectory(
+ const base::FilePath& directory_path,
+ EnumerateChosenDirectoryCallback callback) override {
+ DCHECK(!callback_);
+ callback_ = std::move(callback);
+ if (reached_callback_)
+ std::move(reached_callback_).Run();
+ }
+
+ service_manager::InterfaceProvider* provider_;
+ mojo::BindingSet<FileChooser> bindings_;
+ OpenFileChooserCallback callback_;
+ FileChooserParamsPtr params_;
+ base::OnceClosure reached_callback_;
+};
+
+} // namespace blink
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_MOCK_FILE_CHOOSER_H_
diff --git a/chromium/third_party/blink/renderer/core/html/forms/month_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/month_input_type.cc
index d36dfd4de74..2dca735b65e 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/month_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/month_input_type.cc
@@ -44,14 +44,14 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static const int kMonthDefaultStep = 1;
static const int kMonthDefaultStepBase = 0;
static const int kMonthStepScaleFactor = 1;
InputType* MonthInputType::Create(HTMLInputElement& element) {
- return new MonthInputType(element);
+ return MakeGarbageCollected<MonthInputType>(element);
}
void MonthInputType::CountUsage() {
@@ -59,7 +59,7 @@ void MonthInputType::CountUsage() {
}
const AtomicString& MonthInputType::FormControlType() const {
- return InputTypeNames::month;
+ return input_type_names::kMonth;
}
double MonthInputType::ValueAsDate() const {
@@ -149,10 +149,10 @@ void MonthInputType::SetupLayoutParameters(
const DateComponents& date) const {
layout_parameters.date_time_format = layout_parameters.locale.MonthFormat();
layout_parameters.fallback_date_time_format = "yyyy-MM";
- if (!ParseToDateComponents(GetElement().FastGetAttribute(minAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMinAttr),
&layout_parameters.minimum))
layout_parameters.minimum = DateComponents();
- if (!ParseToDateComponents(GetElement().FastGetAttribute(maxAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMaxAttr),
&layout_parameters.maximum))
layout_parameters.maximum = DateComponents();
layout_parameters.placeholder_for_month = "--";
diff --git a/chromium/third_party/blink/renderer/core/html/forms/month_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/month_input_type.h
index 402bc58849d..43d0733886a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/month_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/month_input_type.h
@@ -39,10 +39,10 @@ class MonthInputType final : public BaseTemporalInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
explicit MonthInputType(HTMLInputElement& element)
: BaseTemporalInputType(element) {}
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
double ValueAsDate() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.cc b/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.cc
index 30b5ac5f404..17eb4fe5825 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.cc
@@ -136,28 +136,28 @@ DateTimeEditElement*
MultipleFieldsTemporalInputTypeView::GetDateTimeEditElement() const {
return ToDateTimeEditElementOrDie(
GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::DateTimeEdit()));
+ shadow_element_names::DateTimeEdit()));
}
SpinButtonElement* MultipleFieldsTemporalInputTypeView::GetSpinButtonElement()
const {
return ToSpinButtonElementOrDie(
GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SpinButton()));
+ shadow_element_names::SpinButton()));
}
ClearButtonElement* MultipleFieldsTemporalInputTypeView::GetClearButtonElement()
const {
return ToClearButtonElementOrDie(
GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::ClearButton()));
+ shadow_element_names::ClearButton()));
}
PickerIndicatorElement*
MultipleFieldsTemporalInputTypeView::GetPickerIndicatorElement() const {
return ToPickerIndicatorElementOrDie(
GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::PickerIndicator()));
+ shadow_element_names::PickerIndicator()));
}
inline bool MultipleFieldsTemporalInputTypeView::ContainsFocusedShadowElement()
@@ -202,9 +202,9 @@ void MultipleFieldsTemporalInputTypeView::EditControlValueChanged() {
GetElement().SetNeedsValidityCheck();
} else {
GetElement().SetNonAttributeValueByUserEdit(new_value);
- GetElement().SetNeedsStyleRecalc(
- kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
+ GetElement().SetNeedsStyleRecalc(kSubtreeStyleChange,
+ StyleChangeReasonForTracing::Create(
+ style_change_reason::kControlValue));
GetElement().DispatchInputEvent();
}
GetElement().NotifyFormStateChanged();
@@ -317,7 +317,8 @@ MultipleFieldsTemporalInputTypeView::MultipleFieldsTemporalInputTypeView(
MultipleFieldsTemporalInputTypeView*
MultipleFieldsTemporalInputTypeView::Create(HTMLInputElement& element,
BaseTemporalInputType& input_type) {
- return new MultipleFieldsTemporalInputTypeView(element, input_type);
+ return MakeGarbageCollected<MultipleFieldsTemporalInputTypeView>(element,
+ input_type);
}
MultipleFieldsTemporalInputTypeView::~MultipleFieldsTemporalInputTypeView() =
@@ -549,7 +550,7 @@ void MultipleFieldsTemporalInputTypeView::UpdateView() {
edit->setAttribute(datetimeformat_attr,
AtomicString(layout_parameters.date_time_format),
ASSERT_NO_EXCEPTION);
- const AtomicString pattern = edit->FastGetAttribute(HTMLNames::patternAttr);
+ const AtomicString pattern = edit->FastGetAttribute(html_names::kPatternAttr);
if (!pattern.IsEmpty())
layout_parameters.date_time_format = pattern;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.h b/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.h
index 19ba2dd93bf..f25ebbea912 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.h
@@ -55,13 +55,13 @@ class MultipleFieldsTemporalInputTypeView final
public:
static MultipleFieldsTemporalInputTypeView* Create(HTMLInputElement&,
BaseTemporalInputType&);
- ~MultipleFieldsTemporalInputTypeView() override;
- void Trace(blink::Visitor*) override;
- private:
MultipleFieldsTemporalInputTypeView(HTMLInputElement&,
BaseTemporalInputType&);
+ ~MultipleFieldsTemporalInputTypeView() override;
+ void Trace(blink::Visitor*) override;
+ private:
// DateTimeEditElement::EditControlOwner functions
void DidBlurFromControl(WebFocusType) final;
void DidFocusOnControl(WebFocusType) final;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/number_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/number_input_type.cc
index d3a9680a2ae..12b5b06441f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/number_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/number_input_type.cc
@@ -49,7 +49,7 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
+using namespace html_names;
static const int kNumberDefaultStep = 1;
static const int kNumberDefaultStepBase = 0;
@@ -95,7 +95,7 @@ static RealNumberRenderSize CalculateRenderSize(const Decimal& value) {
}
InputType* NumberInputType::Create(HTMLInputElement& element) {
- return new NumberInputType(element);
+ return MakeGarbageCollected<NumberInputType>(element);
}
void NumberInputType::CountUsage() {
@@ -103,7 +103,7 @@ void NumberInputType::CountUsage() {
}
const AtomicString& NumberInputType::FormControlType() const {
- return InputTypeNames::number;
+ return input_type_names::kNumber;
}
void NumberInputType::SetValue(const String& sanitized_value,
@@ -157,17 +157,17 @@ bool NumberInputType::SizeShouldIncludeDecoration(int default_size,
int& preferred_size) const {
preferred_size = default_size;
- const String step_string = GetElement().FastGetAttribute(stepAttr);
+ const String step_string = GetElement().FastGetAttribute(kStepAttr);
if (DeprecatedEqualIgnoringCase(step_string, "any"))
return false;
const Decimal minimum =
- ParseToDecimalForNumberType(GetElement().FastGetAttribute(minAttr));
+ ParseToDecimalForNumberType(GetElement().FastGetAttribute(kMinAttr));
if (!minimum.IsFinite())
return false;
const Decimal maximum =
- ParseToDecimalForNumberType(GetElement().FastGetAttribute(maxAttr));
+ ParseToDecimalForNumberType(GetElement().FastGetAttribute(kMaxAttr));
if (!maximum.IsFinite())
return false;
@@ -286,21 +286,23 @@ bool NumberInputType::SupportsPlaceholder() const {
void NumberInputType::MinOrMaxAttributeChanged() {
TextFieldInputType::MinOrMaxAttributeChanged();
- if (GetElement().GetLayoutObject())
+ if (GetElement().GetLayoutObject()) {
GetElement()
.GetLayoutObject()
->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
+ }
}
void NumberInputType::StepAttributeChanged() {
TextFieldInputType::StepAttributeChanged();
- if (GetElement().GetLayoutObject())
+ if (GetElement().GetLayoutObject()) {
GetElement()
.GetLayoutObject()
->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
+ }
}
bool NumberInputType::SupportsSelectionAPI() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/number_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/number_input_type.h
index d0f9d9b8f82..fe94317f8b2 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/number_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/number_input_type.h
@@ -41,8 +41,9 @@ class NumberInputType final : public TextFieldInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
NumberInputType(HTMLInputElement& element) : TextFieldInputType(element) {}
+
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
void SetValue(const String&,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/option_list_test.cc b/chromium/third_party/blink/renderer/core/html/forms/option_list_test.cc
index f10e65be341..714bbc38272 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/option_list_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/option_list_test.cc
@@ -14,7 +14,7 @@ namespace blink {
namespace {
AtomicString Id(const HTMLOptionElement* option) {
- return option->FastGetAttribute(HTMLNames::idAttr);
+ return option->FastGetAttribute(html_names::kIdAttr);
}
} // namespace
@@ -43,8 +43,8 @@ TEST_F(OptionListTest, OptionOnly) {
Select().SetInnerHTMLFromString(
"text<input><option id=o1></option><input><option "
"id=o2></option><input>");
- auto* div =
- ToHTMLElement(Select().GetDocument().CreateRawElement(HTMLNames::divTag));
+ auto* div = ToHTMLElement(
+ Select().GetDocument().CreateRawElement(html_names::kDivTag));
div->SetInnerHTMLFromString("<option id=o3></option>");
Select().AppendChild(div);
OptionList list = Select().GetOptionList();
diff --git a/chromium/third_party/blink/renderer/core/html/forms/password_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/password_input_type.cc
index 82bcbf68fa6..5260d8fbad4 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/password_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/password_input_type.cc
@@ -45,17 +45,17 @@
namespace blink {
InputType* PasswordInputType::Create(HTMLInputElement& element) {
- return new PasswordInputType(element);
+ return MakeGarbageCollected<PasswordInputType>(element);
}
void PasswordInputType::CountUsage() {
CountUsageIfVisible(WebFeature::kInputTypePassword);
- if (GetElement().FastHasAttribute(HTMLNames::maxlengthAttr))
+ if (GetElement().FastHasAttribute(html_names::kMaxlengthAttr))
CountUsageIfVisible(WebFeature::kInputTypePasswordMaxLength);
}
const AtomicString& PasswordInputType::FormControlType() const {
- return InputTypeNames::password;
+ return input_type_names::kPassword;
}
bool PasswordInputType::ShouldSaveAndRestoreFormControlState() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/password_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/password_input_type.h
index 093a7947405..3722b54932d 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/password_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/password_input_type.h
@@ -39,9 +39,10 @@ class PasswordInputType final : public BaseTextInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
explicit PasswordInputType(HTMLInputElement& element)
: BaseTextInputType(element) {}
+
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
bool ShouldSaveAndRestoreFormControlState() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/password_input_type_test.cc b/chromium/third_party/blink/renderer/core/html/forms/password_input_type_test.cc
index e85ad1b7645..75bf907e2e4 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/password_input_type_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/password_input_type_test.cc
@@ -72,7 +72,8 @@ TEST(PasswordInputTypeTest, PasswordVisibilityEvent) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_TRUE(mock_service.PasswordFieldVisibleCalled());
}
@@ -90,7 +91,8 @@ TEST(PasswordInputTypeTest, PasswordVisibilityEventInSecureContext) {
SecureContextState::kSecure);
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// No message should have been sent from a secure context.
blink::test::RunPendingTasks();
EXPECT_FALSE(mock_service.PasswordFieldVisibleCalled());
@@ -104,7 +106,8 @@ TEST(PasswordInputTypeTest, InvisiblePasswordFieldBecomesVisible) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password' style='display:none;'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
// The message should not be sent for a hidden password field.
EXPECT_FALSE(mock_service.PasswordFieldVisibleCalled());
@@ -113,7 +116,8 @@ TEST(PasswordInputTypeTest, InvisiblePasswordFieldBecomesVisible) {
HTMLInputElement* input =
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setAttribute("style", "", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_TRUE(mock_service.PasswordFieldVisibleCalled());
}
@@ -126,7 +130,8 @@ TEST(PasswordInputTypeTest, NonPasswordFieldBecomesPassword) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='text'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// The message should not be sent for a non-password field.
blink::test::RunPendingTasks();
EXPECT_FALSE(mock_service.PasswordFieldVisibleCalled());
@@ -135,7 +140,8 @@ TEST(PasswordInputTypeTest, NonPasswordFieldBecomesPassword) {
HTMLInputElement* input =
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setType("password");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_TRUE(mock_service.PasswordFieldVisibleCalled());
}
@@ -149,7 +155,8 @@ TEST(PasswordInputTypeTest,
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password' style='display:none;'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
// The message should not be sent for a hidden password field.
EXPECT_FALSE(mock_service.PasswordFieldVisibleCalled());
@@ -159,7 +166,8 @@ TEST(PasswordInputTypeTest,
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setType("text");
input->setAttribute("style", "", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_FALSE(mock_service.PasswordFieldVisibleCalled());
}
@@ -172,7 +180,8 @@ TEST(PasswordInputTypeTest, VisiblePasswordFieldBecomesInvisible) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_TRUE(mock_service.PasswordFieldVisibleCalled());
EXPECT_EQ(0u, mock_service.NumPasswordFieldsInvisibleCalls());
@@ -181,7 +190,8 @@ TEST(PasswordInputTypeTest, VisiblePasswordFieldBecomesInvisible) {
HTMLInputElement* input =
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setAttribute("style", "display:none;", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(1u, mock_service.NumPasswordFieldsInvisibleCalls());
}
@@ -194,7 +204,8 @@ TEST(PasswordInputTypeTest, AllVisiblePasswordFieldBecomeInvisible) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'><input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(0u, mock_service.NumPasswordFieldsInvisibleCalls());
@@ -203,25 +214,29 @@ TEST(PasswordInputTypeTest, AllVisiblePasswordFieldBecomeInvisible) {
HTMLInputElement* input =
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setAttribute("style", "display:none;", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(0u, mock_service.NumPasswordFieldsInvisibleCalls());
// When all inputs are invisible, then a message should be sent.
input = ToHTMLInputElement(page_holder->GetDocument().body()->lastChild());
input->setAttribute("style", "display:none;", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(1u, mock_service.NumPasswordFieldsInvisibleCalls());
// If the count of visible inputs goes positive again and then back to
// zero, a message should be sent again.
input->setAttribute("style", "", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(1u, mock_service.NumPasswordFieldsInvisibleCalls());
input->setAttribute("style", "display:none;", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(2u, mock_service.NumPasswordFieldsInvisibleCalls());
}
@@ -234,7 +249,8 @@ TEST(PasswordInputTypeTest, PasswordFieldContainerBecomesInvisible) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<div><input type='password'></div>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(0u, mock_service.NumPasswordFieldsInvisibleCalls());
@@ -242,18 +258,21 @@ TEST(PasswordInputTypeTest, PasswordFieldContainerBecomesInvisible) {
HTMLElement* div =
ToHTMLDivElement(page_holder->GetDocument().body()->firstChild());
div->setAttribute("style", "display:none;", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(1u, mock_service.NumPasswordFieldsInvisibleCalls());
// If the containing div becomes visible and then invisible again, a message
// should be sent.
div->setAttribute("style", "", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(1u, mock_service.NumPasswordFieldsInvisibleCalls());
div->setAttribute("style", "display:none;", ASSERT_NO_EXCEPTION);
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(2u, mock_service.NumPasswordFieldsInvisibleCalls());
}
@@ -266,7 +285,8 @@ TEST(PasswordInputTypeTest, PasswordFieldsBecomeNonPasswordFields) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'><input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(0u, mock_service.NumPasswordFieldsInvisibleCalls());
@@ -275,14 +295,16 @@ TEST(PasswordInputTypeTest, PasswordFieldsBecomeNonPasswordFields) {
HTMLInputElement* input =
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setType("text");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(0u, mock_service.NumPasswordFieldsInvisibleCalls());
// When all inputs are no longer passwords, then a message should be sent.
input = ToHTMLInputElement(page_holder->GetDocument().body()->lastChild());
input->setType("text");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(1u, mock_service.NumPasswordFieldsInvisibleCalls());
}
@@ -295,12 +317,14 @@ TEST(PasswordInputTypeTest, MultipleEventsInSameTask) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// Make the password field invisible in the same task.
HTMLInputElement* input =
ToHTMLInputElement(page_holder->GetDocument().body()->firstChild());
input->setType("text");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
// Only a single Mojo message should have been sent, with the latest state of
// the page (which is that no password fields are visible).
@@ -316,7 +340,8 @@ TEST(PasswordInputTypeTest, DidEditFieldEvent) {
MockInsecureInputService mock_service(page_holder->GetFrame());
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
blink::test::RunPendingTasks();
EXPECT_EQ(0u, mock_service.DidEditFieldCalls());
// Simulate a text field edit.
@@ -342,7 +367,8 @@ TEST(PasswordInputTypeTest, DidEditFieldEventNotSentFromSecureContext) {
SecureContextState::kSecure);
page_holder->GetDocument().body()->SetInnerHTMLFromString(
"<input type='password'>");
- page_holder->GetDocument().View()->UpdateAllLifecyclePhases();
+ page_holder->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// Simulate a text field edit.
page_holder->GetDocument().MaybeQueueSendDidEditFieldInInsecureContext();
// No message should have been sent from a secure context.
diff --git a/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.cc b/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.cc
index 4ba22bb2f91..252e601eadb 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.cc
@@ -37,12 +37,12 @@
#include "third_party/blink/renderer/core/layout/layout_details_marker.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline PickerIndicatorElement::PickerIndicatorElement(
Document& document,
@@ -54,9 +54,10 @@ PickerIndicatorElement* PickerIndicatorElement::Create(
Document& document,
PickerIndicatorOwner& picker_indicator_owner) {
PickerIndicatorElement* element =
- new PickerIndicatorElement(document, picker_indicator_owner);
+ MakeGarbageCollected<PickerIndicatorElement>(document,
+ picker_indicator_owner);
element->SetShadowPseudoId(AtomicString("-webkit-calendar-picker-indicator"));
- element->setAttribute(idAttr, ShadowElementNames::PickerIndicator());
+ element->setAttribute(kIdAttr, shadow_element_names::PickerIndicator());
return element;
}
@@ -75,10 +76,10 @@ void PickerIndicatorElement::DefaultEventHandler(Event& event) {
picker_indicator_owner_->IsPickerIndicatorOwnerDisabledOrReadOnly())
return;
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
OpenPopup();
event.SetDefaultHandled();
- } else if (event.type() == EventTypeNames::keypress &&
+ } else if (event.type() == event_type_names::kKeypress &&
event.IsKeyboardEvent()) {
int char_code = ToKeyboardEvent(event).charCode();
if (char_code == ' ' || char_code == '\r') {
@@ -161,15 +162,15 @@ Node::InsertionNotificationRequest PickerIndicatorElement::InsertedInto(
void PickerIndicatorElement::DidNotifySubtreeInsertionsToDocument() {
if (!GetDocument().ExistingAXObjectCache())
return;
- // Don't make this focusable if we are in layout tests in order to avoid to
- // break existing tests.
- // FIXME: We should have a way to disable accessibility in layout tests.
- if (LayoutTestSupport::IsRunningLayoutTest())
+ // Don't make this focusable if we are in web tests in order to avoid
+ // breaking existing tests.
+ // FIXME: We should have a way to disable accessibility in web tests.
+ if (WebTestSupport::IsRunningWebTest())
return;
- setAttribute(tabindexAttr, "0");
- setAttribute(aria_haspopupAttr, "menu");
- setAttribute(roleAttr, "button");
- setAttribute(aria_labelAttr,
+ setAttribute(kTabindexAttr, "0");
+ setAttribute(kAriaHaspopupAttr, "menu");
+ setAttribute(kRoleAttr, "button");
+ setAttribute(kAriaLabelAttr,
AtomicString(GetLocale().QueryString(
WebLocalizedString::kAXCalendarShowDatePicker)));
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.h b/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.h
index 9f675b22456..b2d2834dfe2 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.h
@@ -58,6 +58,8 @@ class PickerIndicatorElement final : public HTMLDivElement,
};
static PickerIndicatorElement* Create(Document&, PickerIndicatorOwner&);
+
+ PickerIndicatorElement(Document&, PickerIndicatorOwner&);
~PickerIndicatorElement() override;
void Trace(blink::Visitor*) override;
@@ -74,7 +76,6 @@ class PickerIndicatorElement final : public HTMLDivElement,
void DidEndChooser() override;
private:
- PickerIndicatorElement(Document&, PickerIndicatorOwner&);
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
void DefaultEventHandler(Event&) override;
void DetachLayoutTree(const AttachContext& = AttachContext()) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/radio_button_group_scope.cc b/chromium/third_party/blink/renderer/core/html/forms/radio_button_group_scope.cc
index 52fa27124c6..f4968e4f40d 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/radio_button_group_scope.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/radio_button_group_scope.cc
@@ -30,6 +30,9 @@ namespace blink {
class RadioButtonGroup : public GarbageCollected<RadioButtonGroup> {
public:
static RadioButtonGroup* Create();
+
+ RadioButtonGroup();
+
bool IsEmpty() const { return members_.IsEmpty(); }
bool IsRequired() const { return required_count_; }
HTMLInputElement* CheckedButton() const { return checked_button_; }
@@ -43,7 +46,6 @@ class RadioButtonGroup : public GarbageCollected<RadioButtonGroup> {
void Trace(blink::Visitor*);
private:
- RadioButtonGroup();
void SetNeedsValidityCheckForAllButtons();
bool IsValid() const;
void SetCheckedButton(HTMLInputElement*);
@@ -64,7 +66,7 @@ RadioButtonGroup::RadioButtonGroup()
: checked_button_(nullptr), required_count_(0) {}
RadioButtonGroup* RadioButtonGroup::Create() {
- return new RadioButtonGroup;
+ return MakeGarbageCollected<RadioButtonGroup>();
}
inline bool RadioButtonGroup::IsValid() const {
@@ -95,7 +97,7 @@ void RadioButtonGroup::UpdateRequiredButton(MemberKeyValue& it,
}
void RadioButtonGroup::Add(HTMLInputElement* button) {
- DCHECK_EQ(button->type(), InputTypeNames::radio);
+ DCHECK_EQ(button->type(), input_type_names::kRadio);
auto add_result = members_.insert(button, false);
if (!add_result.is_new_entry)
return;
@@ -115,7 +117,7 @@ void RadioButtonGroup::Add(HTMLInputElement* button) {
}
void RadioButtonGroup::UpdateCheckedState(HTMLInputElement* button) {
- DCHECK_EQ(button->type(), InputTypeNames::radio);
+ DCHECK_EQ(button->type(), input_type_names::kRadio);
DCHECK(members_.Contains(button));
bool was_valid = IsValid();
if (button->checked()) {
@@ -133,7 +135,7 @@ void RadioButtonGroup::UpdateCheckedState(HTMLInputElement* button) {
}
void RadioButtonGroup::RequiredAttributeChanged(HTMLInputElement* button) {
- DCHECK_EQ(button->type(), InputTypeNames::radio);
+ DCHECK_EQ(button->type(), input_type_names::kRadio);
auto it = members_.find(button);
DCHECK_NE(it, members_.end());
bool was_valid = IsValid();
@@ -145,7 +147,7 @@ void RadioButtonGroup::RequiredAttributeChanged(HTMLInputElement* button) {
}
void RadioButtonGroup::Remove(HTMLInputElement* button) {
- DCHECK_EQ(button->type(), InputTypeNames::radio);
+ DCHECK_EQ(button->type(), input_type_names::kRadio);
auto it = members_.find(button);
if (it == members_.end())
return;
@@ -180,7 +182,7 @@ void RadioButtonGroup::Remove(HTMLInputElement* button) {
void RadioButtonGroup::SetNeedsValidityCheckForAllButtons() {
for (auto& element : members_) {
HTMLInputElement* const button = element.key;
- DCHECK_EQ(button->type(), InputTypeNames::radio);
+ DCHECK_EQ(button->type(), input_type_names::kRadio);
button->SetNeedsValidityCheck();
}
}
@@ -208,12 +210,12 @@ RadioButtonGroupScope::RadioButtonGroupScope() = default;
RadioButtonGroupScope::~RadioButtonGroupScope() = default;
void RadioButtonGroupScope::AddButton(HTMLInputElement* element) {
- DCHECK_EQ(element->type(), InputTypeNames::radio);
+ DCHECK_EQ(element->type(), input_type_names::kRadio);
if (element->GetName().IsEmpty())
return;
if (!name_to_group_map_)
- name_to_group_map_ = new NameToGroupMap;
+ name_to_group_map_ = MakeGarbageCollected<NameToGroupMap>();
auto* key_value =
name_to_group_map_->insert(element->GetName(), nullptr).stored_value;
@@ -223,7 +225,7 @@ void RadioButtonGroupScope::AddButton(HTMLInputElement* element) {
}
void RadioButtonGroupScope::UpdateCheckedState(HTMLInputElement* element) {
- DCHECK_EQ(element->type(), InputTypeNames::radio);
+ DCHECK_EQ(element->type(), input_type_names::kRadio);
if (element->GetName().IsEmpty())
return;
DCHECK(name_to_group_map_);
@@ -236,7 +238,7 @@ void RadioButtonGroupScope::UpdateCheckedState(HTMLInputElement* element) {
void RadioButtonGroupScope::RequiredAttributeChanged(
HTMLInputElement* element) {
- DCHECK_EQ(element->type(), InputTypeNames::radio);
+ DCHECK_EQ(element->type(), input_type_names::kRadio);
if (element->GetName().IsEmpty())
return;
DCHECK(name_to_group_map_);
@@ -256,7 +258,7 @@ HTMLInputElement* RadioButtonGroupScope::CheckedButtonForGroup(
}
bool RadioButtonGroupScope::IsInRequiredGroup(HTMLInputElement* element) const {
- DCHECK_EQ(element->type(), InputTypeNames::radio);
+ DCHECK_EQ(element->type(), input_type_names::kRadio);
if (element->GetName().IsEmpty())
return false;
if (!name_to_group_map_)
@@ -277,7 +279,7 @@ unsigned RadioButtonGroupScope::GroupSizeFor(
}
void RadioButtonGroupScope::RemoveButton(HTMLInputElement* element) {
- DCHECK_EQ(element->type(), InputTypeNames::radio);
+ DCHECK_EQ(element->type(), input_type_names::kRadio);
if (element->GetName().IsEmpty())
return;
if (!name_to_group_map_)
diff --git a/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.cc
index b5059052536..f12a9a15980 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.cc
@@ -45,14 +45,12 @@ HTMLInputElement* NextInputElement(const HTMLInputElement& element,
} // namespace
-using namespace HTMLNames;
-
InputType* RadioInputType::Create(HTMLInputElement& element) {
- return new RadioInputType(element);
+ return MakeGarbageCollected<RadioInputType>(element);
}
const AtomicString& RadioInputType::FormControlType() const {
- return InputTypeNames::radio;
+ return input_type_names::kRadio;
}
bool RadioInputType::ValueMissing(const String&) const {
@@ -162,7 +160,7 @@ bool RadioInputType::IsKeyboardFocusable() const {
Element* current_focused_element =
GetElement().GetDocument().FocusedElement();
if (auto* focused_input = ToHTMLInputElementOrNull(current_focused_element)) {
- if (focused_input->type() == InputTypeNames::radio &&
+ if (focused_input->type() == input_type_names::kRadio &&
focused_input->Form() == GetElement().Form() &&
focused_input->GetName() == GetElement().GetName())
return false;
@@ -207,7 +205,7 @@ void RadioInputType::DidDispatchClick(Event& event,
HTMLInputElement* checked_radio_button = state.checked_radio_button.Get();
if (!checked_radio_button)
GetElement().setChecked(false);
- else if (checked_radio_button->type() == InputTypeNames::radio &&
+ else if (checked_radio_button->type() == input_type_names::kRadio &&
checked_radio_button->Form() == GetElement().Form() &&
checked_radio_button->GetName() == GetElement().GetName())
checked_radio_button->setChecked(true);
@@ -235,7 +233,7 @@ HTMLInputElement* RadioInputType::NextRadioButtonInGroup(
input_element; input_element = NextInputElement(
*input_element, current->Form(), forward)) {
if (current->Form() == input_element->Form() &&
- input_element->type() == InputTypeNames::radio &&
+ input_element->type() == input_type_names::kRadio &&
input_element->GetName() == current->GetName())
return input_element;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.h
index 9b9a70a51d1..e90755f0f98 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/radio_input_type.h
@@ -42,8 +42,9 @@ class RadioInputType final : public BaseCheckableInputType {
CORE_EXPORT static HTMLInputElement* NextRadioButtonInGroup(HTMLInputElement*,
bool forward);
- private:
RadioInputType(HTMLInputElement& element) : BaseCheckableInputType(element) {}
+
+ private:
const AtomicString& FormControlType() const override;
bool ValueMissing(const String&) const override;
String ValueMissingText() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.cc b/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.cc
index 7170f0e8803..fa732daaefb 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.cc
@@ -36,8 +36,6 @@
namespace blink {
-using namespace HTMLNames;
-
RadioNodeList::RadioNodeList(ContainerNode& root_node,
const AtomicString& name,
CollectionType type)
@@ -55,7 +53,7 @@ static inline HTMLInputElement* ToRadioButtonInputElement(Element& element) {
if (!IsHTMLInputElement(element))
return nullptr;
HTMLInputElement& input_element = ToHTMLInputElement(element);
- if (input_element.type() != InputTypeNames::radio ||
+ if (input_element.type() != input_type_names::kRadio ||
input_element.value().IsEmpty())
return nullptr;
return &input_element;
@@ -121,7 +119,7 @@ bool RadioNodeList::ElementMatches(const Element& element) const {
return false;
if (IsHTMLInputElement(element) &&
- ToHTMLInputElement(element).type() == InputTypeNames::image)
+ ToHTMLInputElement(element).type() == input_type_names::kImage)
return false;
return CheckElementMatchesRadioNodeListFilter(element);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.h b/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.h
index 81e76d5601c..fd958c1d376 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/radio_node_list.h
@@ -40,17 +40,16 @@ class RadioNodeList final : public LiveNodeList {
CollectionType type,
const AtomicString& name) {
DCHECK(type == kRadioNodeListType || type == kRadioImgNodeListType);
- return new RadioNodeList(owner_node, name, type);
+ return MakeGarbageCollected<RadioNodeList>(owner_node, name, type);
}
+ RadioNodeList(ContainerNode&, const AtomicString& name, CollectionType);
~RadioNodeList() override;
String value() const;
void setValue(const String&);
private:
- RadioNodeList(ContainerNode&, const AtomicString& name, CollectionType);
-
bool CheckElementMatchesRadioNodeListFilter(const Element&) const;
bool MatchesByIdOrName(const Element&) const;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/range_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/range_input_type.cc
index ed0fcbe24bc..d32bc57d454 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/range_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/range_input_type.cc
@@ -57,7 +57,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static const int kRangeDefaultMinimum = 0;
static const int kRangeDefaultMaximum = 100;
@@ -71,7 +71,7 @@ static Decimal EnsureMaximum(const Decimal& proposed_value,
}
InputType* RangeInputType::Create(HTMLInputElement& element) {
- return new RangeInputType(element);
+ return MakeGarbageCollected<RangeInputType>(element);
}
RangeInputType::RangeInputType(HTMLInputElement& element)
@@ -103,7 +103,7 @@ void RangeInputType::CountUsage() {
}
const AtomicString& RangeInputType::FormControlType() const {
- return InputTypeNames::range;
+ return input_type_names::kRange;
}
double RangeInputType::ValueAsDouble() const {
@@ -132,16 +132,16 @@ StepRange RangeInputType::CreateStepRange(
(kRangeDefaultStep, kRangeDefaultStepBase, kRangeStepScaleFactor));
const Decimal step_base = FindStepBase(kRangeDefaultStepBase);
- const Decimal minimum = ParseToNumber(GetElement().FastGetAttribute(minAttr),
+ const Decimal minimum = ParseToNumber(GetElement().FastGetAttribute(kMinAttr),
kRangeDefaultMinimum);
const Decimal maximum =
- EnsureMaximum(ParseToNumber(GetElement().FastGetAttribute(maxAttr),
+ EnsureMaximum(ParseToNumber(GetElement().FastGetAttribute(kMaxAttr),
kRangeDefaultMaximum),
minimum);
const Decimal step =
StepRange::ParseStep(any_step_handling, step_description,
- GetElement().FastGetAttribute(stepAttr));
+ GetElement().FastGetAttribute(kStepAttr));
// Range type always has range limitations because it has default
// minimum/maximum.
// https://html.spec.whatwg.org/multipage/forms.html#range-state-(type=range):concept-input-min-default
@@ -187,7 +187,7 @@ void RangeInputType::HandleKeydownEvent(KeyboardEvent& event) {
// FIXME: We can't use stepUp() for the step value "any". So, we increase
// or decrease the value by 1/100 of the value range. Is it reasonable?
const Decimal step = DeprecatedEqualIgnoringCase(
- GetElement().FastGetAttribute(stepAttr), "any")
+ GetElement().FastGetAttribute(kStepAttr), "any")
? (step_range.Maximum() - step_range.Minimum()) / 100
: step_range.Step();
const Decimal big_step =
@@ -245,7 +245,7 @@ void RangeInputType::CreateShadowSubtree() {
Document& document = GetElement().GetDocument();
HTMLDivElement* track = HTMLDivElement::Create(document);
track->SetShadowPseudoId(AtomicString("-webkit-slider-runnable-track"));
- track->setAttribute(idAttr, ShadowElementNames::SliderTrack());
+ track->setAttribute(kIdAttr, shadow_element_names::SliderTrack());
track->AppendChild(SliderThumbElement::Create(document));
HTMLElement* container = SliderContainerElement::Create(document);
container->AppendChild(track);
@@ -330,12 +330,12 @@ bool RangeInputType::ShouldRespectListAttribute() {
inline SliderThumbElement* RangeInputType::GetSliderThumbElement() const {
return ToSliderThumbElementOrDie(
GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderThumb()));
+ shadow_element_names::SliderThumb()));
}
inline Element* RangeInputType::SliderTrackElement() const {
return GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderTrack());
+ shadow_element_names::SliderTrack());
}
void RangeInputType::ListAttributeTargetChanged() {
@@ -343,9 +343,10 @@ void RangeInputType::ListAttributeTargetChanged() {
if (auto* object = GetElement().GetLayoutObject())
object->SetSubtreeShouldDoFullPaintInvalidation();
Element* slider_track_element = SliderTrackElement();
- if (slider_track_element->GetLayoutObject())
+ if (slider_track_element->GetLayoutObject()) {
slider_track_element->GetLayoutObject()->SetNeedsLayout(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
+ }
}
static bool DecimalCompare(const Decimal& a, const Decimal& b) {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/range_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/range_input_type.h
index bbdb85edb19..a0bd003cb04 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/range_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/range_input_type.h
@@ -44,11 +44,13 @@ class RangeInputType final : public InputType, public InputTypeView {
public:
static InputType* Create(HTMLInputElement&);
+
+ RangeInputType(HTMLInputElement&);
+
void Trace(blink::Visitor*) override;
using InputType::GetElement;
private:
- RangeInputType(HTMLInputElement&);
InputTypeView* CreateView() override;
ValueMode GetValueMode() const override;
void CountUsage() override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.cc
index 98ddebfb25d..f355452bcfe 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.cc
@@ -40,11 +40,11 @@
namespace blink {
InputType* ResetInputType::Create(HTMLInputElement& element) {
- return new ResetInputType(element);
+ return MakeGarbageCollected<ResetInputType>(element);
}
const AtomicString& ResetInputType::FormControlType() const {
- return InputTypeNames::reset;
+ return input_type_names::kReset;
}
bool ResetInputType::SupportsValidation() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.h
index b239a154c21..0e35baefd80 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/reset_input_type.h
@@ -39,8 +39,9 @@ class ResetInputType final : public BaseButtonInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
ResetInputType(HTMLInputElement& element) : BaseButtonInputType(element) {}
+
+ private:
const AtomicString& FormControlType() const override;
bool SupportsValidation() const override;
void HandleDOMActivateEvent(Event&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.css b/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.css
index e5cbb72003b..f05e3a962e7 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.css
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.css
@@ -209,7 +209,7 @@ body {
min-width: 0 !important;
padding-left: 0 !important;
padding-right: 0 !important;
- -webkit-margin-start: 4px !important;
+ margin-inline-start: 4px !important;
}
.year-list-view {
@@ -228,7 +228,7 @@ body {
.year-list-cell .label {
height: 24px;
line-height: 24px;
- -webkit-padding-start: 8px;
+ padding-inline-start: 8px;
background-color: #f5f5f5;
border-bottom: 1px solid #bfbfbf;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.css b/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.css
index 5cce9ac3bb3..d190f9dab12 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.css
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.css
@@ -10,7 +10,7 @@ select hr {
}
option, optgroup {
- -webkit-padding-end: 2px;
+ padding-inline-end: 2px;
}
.wrap option {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.js b/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.js
index 6ed61189f83..2ed7603e366 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.js
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/listPicker.js
@@ -426,11 +426,11 @@ ListPicker.prototype._configureItem = function(element, config, inGroup) {
if (config.ariaLabel)
element.setAttribute('aria-label', config.ariaLabel);
else element.removeAttribute('aria-label');
- element.style.webkitPaddingStart = this._config.paddingStart + 'px';
+ element.style.paddingInlineStart = this._config.paddingStart + 'px';
if (inGroup) {
- element.style.webkitMarginStart = (-this._config.paddingStart) + 'px';
+ element.style.marginInlineStart = (-this._config.paddingStart) + 'px';
// Should be synchronized with padding-end in listPicker.css.
- element.style.webkitMarginEnd = '-2px';
+ element.style.marginInlineEnd = '-2px';
}
} else if (config.type === 'optgroup') {
element.label = config.label;
@@ -438,15 +438,15 @@ ListPicker.prototype._configureItem = function(element, config, inGroup) {
element.disabled = config.disabled;
element.setAttribute('aria-label', config.ariaLabel);
this._updateChildren(element, config);
- element.style.webkitPaddingStart = this._config.paddingStart + 'px';
+ element.style.paddingInlineStart = this._config.paddingStart + 'px';
} else if (config.type === 'separator') {
element.title = config.title;
element.disabled = config.disabled;
element.setAttribute('aria-label', config.ariaLabel);
if (inGroup) {
- element.style.webkitMarginStart = (-this._config.paddingStart) + 'px';
+ element.style.marginInlineStart = (-this._config.paddingStart) + 'px';
// Should be synchronized with padding-end in listPicker.css.
- element.style.webkitMarginEnd = '-2px';
+ element.style.marginInlineEnd = '-2px';
}
}
this._applyItemStyle(element, config.style);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/pickerButton.css b/chromium/third_party/blink/renderer/core/html/forms/resources/pickerButton.css
index c0c6ff1fbab..396d2788023 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/pickerButton.css
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/pickerButton.css
@@ -37,8 +37,8 @@ button {
text-shadow: 0 1px 0 rgb(240, 240, 240);
min-height: 2em;
min-width: 4em;
- -webkit-padding-end: 10px;
- -webkit-padding-start: 10px;
+ padding-inline-end: 10px;
+ padding-inline-start: 10px;
margin: 0;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/validation_bubble.css b/chromium/third_party/blink/renderer/core/html/forms/resources/validation_bubble.css
index a8e2df9765a..2e99f77d57b 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/validation_bubble.css
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/validation_bubble.css
@@ -124,7 +124,7 @@
#icon {
grid-row: 1 / 3;
grid-column: 1;
- -webkit-margin-end: 8px;
+ margin-inline-end: 8px;
}
#main-message {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/search_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/search_input_type.cc
index 82c28f67be9..ab37141505b 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/search_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/search_input_type.cc
@@ -44,7 +44,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline SearchInputType::SearchInputType(HTMLInputElement& element)
: BaseTextInputType(element),
@@ -54,7 +54,7 @@ inline SearchInputType::SearchInputType(HTMLInputElement& element)
&SearchInputType::SearchEventTimerFired) {}
InputType* SearchInputType::Create(HTMLInputElement& element) {
- return new SearchInputType(element);
+ return MakeGarbageCollected<SearchInputType>(element);
}
void SearchInputType::CountUsage() {
@@ -66,7 +66,7 @@ LayoutObject* SearchInputType::CreateLayoutObject(const ComputedStyle&) const {
}
const AtomicString& SearchInputType::FormControlType() const {
- return InputTypeNames::search;
+ return input_type_names::kSearch;
}
bool SearchInputType::NeedsContainer() const {
@@ -77,7 +77,7 @@ void SearchInputType::CreateShadowSubtree() {
TextFieldInputType::CreateShadowSubtree();
Element* container = ContainerElement();
Element* view_port = GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::EditingViewPort());
+ shadow_element_names::EditingViewPort());
DCHECK(container);
DCHECK(view_port);
container->InsertBefore(
@@ -123,7 +123,7 @@ void SearchInputType::StartSearchEventTimer() {
void SearchInputType::DispatchSearchEvent() {
search_event_timer_.Stop();
- GetElement().DispatchEvent(*Event::CreateBubble(EventTypeNames::search));
+ GetElement().DispatchEvent(*Event::CreateBubble(event_type_names::kSearch));
}
void SearchInputType::SearchEventTimerFired(TimerBase*) {
@@ -131,7 +131,7 @@ void SearchInputType::SearchEventTimerFired(TimerBase*) {
}
bool SearchInputType::SearchEventsShouldBeDispatched() const {
- return GetElement().hasAttribute(incrementalAttr);
+ return GetElement().hasAttribute(kIncrementalAttr);
}
void SearchInputType::DidSetValueByUserEdit() {
@@ -151,7 +151,7 @@ void SearchInputType::UpdateView() {
void SearchInputType::UpdateCancelButtonVisibility() {
Element* button = GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SearchClearButton());
+ shadow_element_names::SearchClearButton());
if (!button)
return;
if (GetElement().value().IsEmpty()) {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/search_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/search_input_type.h
index 7724359c187..d8760afca16 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/search_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/search_input_type.h
@@ -40,8 +40,9 @@ class SearchInputType final : public BaseTextInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
SearchInputType(HTMLInputElement&);
+
+ private:
void CountUsage() override;
LayoutObject* CreateLayoutObject(const ComputedStyle&) const override;
const AtomicString& FormControlType() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc b/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc
index 42355024c3b..5ae900a02d0 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc
@@ -50,7 +50,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline static bool HasVerticalAppearance(HTMLInputElement* input) {
return input->ComputedStyleRef().Appearance() == kSliderVerticalPart;
@@ -62,8 +62,9 @@ inline SliderThumbElement::SliderThumbElement(Document& document)
}
SliderThumbElement* SliderThumbElement::Create(Document& document) {
- SliderThumbElement* element = new SliderThumbElement(document);
- element->setAttribute(idAttr, ShadowElementNames::SliderThumb());
+ SliderThumbElement* element =
+ MakeGarbageCollected<SliderThumbElement>(document);
+ element->setAttribute(kIdAttr, shadow_element_names::SliderThumb());
return element;
}
@@ -71,9 +72,10 @@ void SliderThumbElement::SetPositionFromValue() {
// Since the code to calculate position is in the LayoutSliderThumb layout
// path, we don't actually update the value here. Instead, we poke at the
// layoutObject directly to trigger layout.
- if (GetLayoutObject())
+ if (GetLayoutObject()) {
GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSliderValueChanged);
+ layout_invalidation_reason::kSliderValueChanged);
+ }
}
LayoutObject* SliderThumbElement::CreateLayoutObject(
@@ -105,7 +107,7 @@ void SliderThumbElement::DragFrom(const LayoutPoint& point) {
void SliderThumbElement::SetPositionFromPoint(const LayoutPoint& point) {
HTMLInputElement* input(HostInput());
Element* track_element = input->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderTrack());
+ shadow_element_names::SliderTrack());
if (!input->GetLayoutObject() || !GetLayoutBox() ||
!track_element->GetLayoutBox())
@@ -179,9 +181,10 @@ void SliderThumbElement::SetPositionFromPoint(const LayoutPoint& point) {
// FIXME: This is no longer being set from renderer. Consider updating the
// method name.
input->SetValueFromRenderer(value_string);
- if (GetLayoutObject())
+ if (GetLayoutObject()) {
GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSliderValueChanged);
+ layout_invalidation_reason::kSliderValueChanged);
+ }
}
void SliderThumbElement::StartDragging() {
@@ -204,16 +207,17 @@ void SliderThumbElement::StopDragging() {
PointerEventFactory::kMouseId, this);
}
in_drag_mode_ = false;
- if (GetLayoutObject())
+ if (GetLayoutObject()) {
GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSliderValueChanged);
+ layout_invalidation_reason::kSliderValueChanged);
+ }
if (HostInput())
HostInput()->DispatchFormControlChangeEvent();
}
void SliderThumbElement::DefaultEventHandler(Event& event) {
if (event.IsPointerEvent() &&
- event.type() == EventTypeNames::lostpointercapture) {
+ event.type() == event_type_names::kLostpointercapture) {
StopDragging();
return;
}
@@ -241,15 +245,15 @@ void SliderThumbElement::DefaultEventHandler(Event& event) {
// We intentionally do not call event->setDefaultHandled() here because
// MediaControlTimelineElement::defaultEventHandler() wants to handle these
// mouse events.
- if (event_type == EventTypeNames::mousedown && is_left_button) {
+ if (event_type == event_type_names::kMousedown && is_left_button) {
StartDragging();
return;
}
- if (event_type == EventTypeNames::mouseup && is_left_button) {
+ if (event_type == event_type_names::kMouseup && is_left_button) {
StopDragging();
return;
}
- if (event_type == EventTypeNames::mousemove) {
+ if (event_type == event_type_names::kMousemove) {
if (in_drag_mode_)
SetPositionFromPoint(LayoutPoint(mouse_event.AbsoluteLocation()));
return;
@@ -370,7 +374,7 @@ void SliderContainerElement::HandleTouchEvent(TouchEvent* event) {
if (!input || input->IsDisabledFormControl() || !event)
return;
- if (event->type() == EventTypeNames::touchend) {
+ if (event->type() == event_type_names::kTouchend) {
// TODO: Also do this for touchcancel?
input->DispatchFormControlChangeEvent();
event->SetDefaultHandled();
@@ -387,12 +391,12 @@ void SliderContainerElement::HandleTouchEvent(TouchEvent* event) {
TouchList* touches = event->targetTouches();
SliderThumbElement* thumb = ToSliderThumbElement(
- GetTreeScope().getElementById(ShadowElementNames::SliderThumb()));
+ GetTreeScope().getElementById(shadow_element_names::SliderThumb()));
if (!thumb || !touches)
return;
if (touches->length() == 1) {
- if (event->type() == EventTypeNames::touchstart) {
+ if (event->type() == event_type_names::kTouchstart) {
start_point_ = touches->item(0)->AbsoluteLocation();
sliding_direction_ = kNoMove;
touch_started_ = true;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.h b/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.h
index cda495321bb..3eb98535f7f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.h
@@ -45,6 +45,8 @@ class SliderThumbElement final : public HTMLDivElement {
public:
static SliderThumbElement* Create(Document&);
+ SliderThumbElement(Document&);
+
void SetPositionFromValue();
void DragFrom(const LayoutPoint&);
@@ -58,7 +60,6 @@ class SliderThumbElement final : public HTMLDivElement {
void StopDragging();
private:
- SliderThumbElement(Document&);
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
scoped_refptr<ComputedStyle> CustomStyleForLayoutObject() final;
Element* CloneWithoutAttributesAndChildren(Document&) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.cc b/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.cc
index 9aa7296953d..f2f78867196 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.cc
@@ -28,6 +28,7 @@
#include "build/build_config.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/events/wheel_event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -41,7 +42,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline SpinButtonElement::SpinButtonElement(Document& document,
SpinButtonOwner& spin_button_owner)
@@ -58,9 +59,9 @@ SpinButtonElement* SpinButtonElement::Create(
Document& document,
SpinButtonOwner& spin_button_owner) {
SpinButtonElement* element =
- new SpinButtonElement(document, spin_button_owner);
+ MakeGarbageCollected<SpinButtonElement>(document, spin_button_owner);
element->SetShadowPseudoId(AtomicString("-webkit-inner-spin-button"));
- element->setAttribute(idAttr, ShadowElementNames::SpinButton());
+ element->setAttribute(kIdAttr, shadow_element_names::SpinButton());
return element;
}
@@ -92,7 +93,7 @@ void SpinButtonElement::DefaultEventHandler(Event& event) {
auto& mouse_event = ToMouseEvent(event);
IntPoint local = RoundedIntPoint(box->AbsoluteToLocal(
FloatPoint(mouse_event.AbsoluteLocation()), kUseTransforms));
- if (mouse_event.type() == EventTypeNames::mousedown &&
+ if (mouse_event.type() == event_type_names::kMousedown &&
mouse_event.button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
if (box->PixelSnappedBorderBoxRect().Contains(local)) {
@@ -111,11 +112,11 @@ void SpinButtonElement::DefaultEventHandler(Event& event) {
}
event.SetDefaultHandled();
}
- } else if (mouse_event.type() == EventTypeNames::mouseup &&
+ } else if (mouse_event.type() == event_type_names::kMouseup &&
mouse_event.button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
ReleaseCapture();
- } else if (event.type() == EventTypeNames::mousemove) {
+ } else if (event.type() == event_type_names::kMousemove) {
if (box->PixelSnappedBorderBoxRect().Contains(local)) {
if (!capturing_) {
if (LocalFrame* frame = GetDocument().GetFrame()) {
@@ -148,7 +149,7 @@ void SpinButtonElement::ForwardEvent(Event& event) {
if (!GetLayoutBox())
return;
- if (!event.HasInterface(EventNames::WheelEvent))
+ if (!event.HasInterface(event_interface_names::kWheelEvent))
return;
if (!spin_button_owner_)
diff --git a/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.h b/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.h
index 0244fb96b86..13b586d7a42 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/spin_button_element.h
@@ -63,6 +63,9 @@ class CORE_EXPORT SpinButtonElement final : public HTMLDivElement,
// because SpinButtonElement can be outlive SpinButtonOwner
// implementation, e.g. during event handling.
static SpinButtonElement* Create(Document&, SpinButtonOwner&);
+
+ SpinButtonElement(Document&, SpinButtonOwner&);
+
UpDownState GetUpDownState() const { return up_down_state_; }
void ReleaseCapture(EventDispatch = kEventDispatchAllowed);
void RemoveSpinButtonOwner() { spin_button_owner_ = nullptr; }
@@ -77,8 +80,6 @@ class CORE_EXPORT SpinButtonElement final : public HTMLDivElement,
void Trace(blink::Visitor*) override;
private:
- SpinButtonElement(Document&, SpinButtonOwner&);
-
void DetachLayoutTree(const AttachContext&) override;
bool IsSpinButtonElement() const override { return true; }
bool IsDisabledFormControl() const override {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/step_range.cc b/chromium/third_party/blink/renderer/core/html/forms/step_range.cc
index 3507a85450e..d8ea6ddb19f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/step_range.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/step_range.cc
@@ -28,8 +28,6 @@
namespace blink {
-using namespace HTMLNames;
-
StepRange::StepRange()
: maximum_(100),
minimum_(0),
diff --git a/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.cc
index b722264fdd1..0cf43961402 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.cc
@@ -43,11 +43,11 @@ namespace blink {
InputType* SubmitInputType::Create(HTMLInputElement& element) {
UseCounter::Count(element.GetDocument(), WebFeature::kInputTypeSubmit);
- return new SubmitInputType(element);
+ return MakeGarbageCollected<SubmitInputType>(element);
}
const AtomicString& SubmitInputType::FormControlType() const {
- return InputTypeNames::submit;
+ return input_type_names::kSubmit;
}
void SubmitInputType::AppendToFormData(FormData& form_data) const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.h
index 80cd8afd535..7dc51ffe799 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/submit_input_type.h
@@ -39,8 +39,9 @@ class SubmitInputType final : public BaseButtonInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
SubmitInputType(HTMLInputElement& element) : BaseButtonInputType(element) {}
+
+ private:
const AtomicString& FormControlType() const override;
void AppendToFormData(FormData&) const override;
bool SupportsRequired() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.cc
index 75bf3b1677e..2dde47fb886 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.cc
@@ -36,7 +36,7 @@
namespace blink {
InputType* TelephoneInputType::Create(HTMLInputElement& element) {
- return new TelephoneInputType(element);
+ return MakeGarbageCollected<TelephoneInputType>(element);
}
void TelephoneInputType::CountUsage() {
@@ -44,7 +44,7 @@ void TelephoneInputType::CountUsage() {
}
const AtomicString& TelephoneInputType::FormControlType() const {
- return InputTypeNames::tel;
+ return input_type_names::kTel;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.h
index b9b8ca7131d..6ffc76bc094 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.h
@@ -39,8 +39,9 @@ class TelephoneInputType final : public BaseTextInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
TelephoneInputType(HTMLInputElement& element) : BaseTextInputType(element) {}
+
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_control_element.cc b/chromium/third_party/blink/renderer/core/html/forms/text_control_element.cc
index 411880b449d..add2d09f30b 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_control_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_control_element.cc
@@ -62,7 +62,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
TextControlElement::TextControlElement(const QualifiedName& tag_name,
Document& doc)
@@ -104,7 +104,7 @@ void TextControlElement::DispatchBlurEvent(
}
void TextControlElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::webkitEditableContentChanged &&
+ if (event.type() == event_type_names::kWebkitEditableContentChanged &&
GetLayoutObject() && GetLayoutObject()->IsTextControl()) {
last_change_was_user_edit_ = !GetDocument().IsRunningExecCommand();
user_has_edited_the_field_ |= last_change_was_user_edit_;
@@ -128,8 +128,8 @@ void TextControlElement::DefaultEventHandler(Event& event) {
}
void TextControlElement::ForwardEvent(Event& event) {
- if (event.type() == EventTypeNames::blur ||
- event.type() == EventTypeNames::focus)
+ if (event.type() == event_type_names::kBlur ||
+ event.type() == event_type_names::kFocus)
return;
InnerEditorElement()->DefaultEventHandler(event);
}
@@ -137,7 +137,7 @@ void TextControlElement::ForwardEvent(Event& event) {
String TextControlElement::StrippedPlaceholder() const {
// According to the HTML5 specification, we need to remove CR and LF from
// the attribute value.
- const AtomicString& attribute_value = FastGetAttribute(placeholderAttr);
+ const AtomicString& attribute_value = FastGetAttribute(kPlaceholderAttr);
if (!attribute_value.Contains(kNewlineCharacter) &&
!attribute_value.Contains(kCarriageReturnCharacter))
return attribute_value;
@@ -159,7 +159,7 @@ static bool IsNotLineBreak(UChar ch) {
}
bool TextControlElement::IsPlaceholderEmpty() const {
- const AtomicString& attribute_value = FastGetAttribute(placeholderAttr);
+ const AtomicString& attribute_value = FastGetAttribute(kPlaceholderAttr);
return attribute_value.GetString().Find(IsNotLineBreak) == kNotFound;
}
@@ -172,14 +172,15 @@ HTMLElement* TextControlElement::PlaceholderElement() const {
if (!SupportsPlaceholder())
return nullptr;
DCHECK(UserAgentShadowRoot());
- return ToHTMLElementOrDie(
- UserAgentShadowRoot()->getElementById(ShadowElementNames::Placeholder()));
+ return ToHTMLElementOrDie(UserAgentShadowRoot()->getElementById(
+ shadow_element_names::Placeholder()));
}
void TextControlElement::UpdatePlaceholderVisibility() {
HTMLElement* placeholder = PlaceholderElement();
if (!placeholder) {
UpdatePlaceholderText();
+ SetPlaceholderVisibility(PlaceholderShouldBeVisible());
return;
}
@@ -262,7 +263,7 @@ void TextControlElement::DispatchFormControlChangeEvent() {
void TextControlElement::EnqueueChangeEvent() {
if (!value_before_first_user_edit_.IsNull() &&
!EqualIgnoringNullity(value_before_first_user_edit_, value())) {
- Event* event = Event::CreateBubble(EventTypeNames::change);
+ Event* event = Event::CreateBubble(event_type_names::kChange);
event->SetTarget(this);
GetDocument().EnqueueAnimationFrameEvent(event);
}
@@ -356,7 +357,7 @@ static Position PositionForIndex(HTMLElement* inner_editor, unsigned index) {
unsigned remaining_characters_to_move_forward = index;
Node* last_br_or_text = inner_editor;
for (Node& node : NodeTraversal::DescendantsOf(*inner_editor)) {
- if (node.HasTagName(brTag)) {
+ if (node.HasTagName(kBrTag)) {
if (remaining_characters_to_move_forward == 0)
return Position::BeforeNode(node);
--remaining_characters_to_move_forward;
@@ -405,7 +406,7 @@ unsigned TextControlElement::IndexForPosition(HTMLElement* inner_editor,
index += std::min(length, passed_position.OffsetInContainerNode());
else
index += length;
- } else if (node->HasTagName(brTag)) {
+ } else if (node->HasTagName(kBrTag)) {
++index;
}
}
@@ -662,14 +663,14 @@ SelectionInDOMTree TextControlElement::Selection() const {
int TextControlElement::maxLength() const {
int value;
- if (!ParseHTMLInteger(FastGetAttribute(maxlengthAttr), value))
+ if (!ParseHTMLInteger(FastGetAttribute(kMaxlengthAttr), value))
return -1;
return value >= 0 ? value : -1;
}
int TextControlElement::minLength() const {
int value;
- if (!ParseHTMLInteger(FastGetAttribute(minlengthAttr), value))
+ if (!ParseHTMLInteger(FastGetAttribute(kMinlengthAttr), value))
return -1;
return value >= 0 ? value : -1;
}
@@ -688,7 +689,7 @@ void TextControlElement::setMaxLength(int new_value,
ExceptionMessages::IndexExceedsMinimumBound("maxLength", new_value,
min));
} else {
- SetIntegralAttribute(maxlengthAttr, new_value);
+ SetIntegralAttribute(kMaxlengthAttr, new_value);
}
}
@@ -706,7 +707,7 @@ void TextControlElement::setMinLength(int new_value,
ExceptionMessages::IndexExceedsMaximumBound("minLength", new_value,
max));
} else {
- SetIntegralAttribute(minlengthAttr, new_value);
+ SetIntegralAttribute(kMinlengthAttr, new_value);
}
}
@@ -732,18 +733,18 @@ void TextControlElement::SelectionChanged(bool user_triggered) {
frame->Selection().GetSelectionInDOMTree();
if (selection.Type() != kRangeSelection)
return;
- DispatchEvent(*Event::CreateBubble(EventTypeNames::select));
+ DispatchEvent(*Event::CreateBubble(event_type_names::kSelect));
}
void TextControlElement::ScheduleSelectEvent() {
- Event* event = Event::CreateBubble(EventTypeNames::select);
+ Event* event = Event::CreateBubble(event_type_names::kSelect);
event->SetTarget(this);
GetDocument().EnqueueAnimationFrameEvent(event);
}
void TextControlElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == placeholderAttr) {
+ if (params.name == kPlaceholderAttr) {
UpdatePlaceholderText();
UpdatePlaceholderVisibility();
UseCounter::Count(GetDocument(), WebFeature::kPlaceholderAttribute);
@@ -872,7 +873,6 @@ String TextControlElement::ValueWithHardLineBreaks() const {
if (!layout_object)
return value();
- DCHECK(CanUseInlineBox(*layout_object));
Node* break_node;
unsigned break_offset;
RootInlineBox* line = layout_object->FirstRootBox();
@@ -916,6 +916,15 @@ TextControlElement* EnclosingTextControl(const Position& position) {
return EnclosingTextControl(position.ComputeContainerNode());
}
+TextControlElement* EnclosingTextControl(const PositionInFlatTree& position) {
+ Node* container = position.ComputeContainerNode();
+ if (IsTextControl(container)) {
+ // For example, #inner-editor@beforeAnchor reaches here.
+ return ToTextControl(container);
+ }
+ return EnclosingTextControl(container);
+}
+
TextControlElement* EnclosingTextControl(const Node* container) {
if (!container)
return nullptr;
@@ -930,7 +939,7 @@ String TextControlElement::DirectionForFormData() const {
for (const HTMLElement* element = this; element;
element = Traversal<HTMLElement>::FirstAncestor(*element)) {
const AtomicString& dir_attribute_value =
- element->FastGetAttribute(dirAttr);
+ element->FastGetAttribute(kDirAttr);
if (dir_attribute_value.IsNull())
continue;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_control_element.h b/chromium/third_party/blink/renderer/core/html/forms/text_control_element.h
index 46a16b214c3..5673f21316d 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_control_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_control_element.h
@@ -264,6 +264,7 @@ DEFINE_TEXT_CONTROL_CASTS(const TextControlElement, const Node);
#undef DEFINE_TEXT_CONTROL_CASTS
TextControlElement* EnclosingTextControl(const Position&);
+TextControlElement* EnclosingTextControl(const PositionInFlatTree&);
TextControlElement* EnclosingTextControl(const Node*);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_control_element_test.cc b/chromium/third_party/blink/renderer/core/html/forms/text_control_element_test.cc
index 6f528005d96..8b55264a4e3 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_control_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_control_element_test.cc
@@ -29,6 +29,11 @@ class TextControlElementTest : public testing::Test {
TextControlElement& TextControl() const { return *text_control_; }
HTMLInputElement& Input() const { return *input_; }
+ void UpdateAllLifecyclePhases() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
private:
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
@@ -46,7 +51,7 @@ void TextControlElementTest::SetUp() {
document_ = &dummy_page_holder_->GetDocument();
document_->documentElement()->SetInnerHTMLFromString(
"<body><textarea id=textarea></textarea><input id=input /></body>");
- document_->View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
text_control_ = ToTextControl(document_->getElementById("textarea"));
text_control_->focus();
input_ = ToHTMLInputElement(document_->getElementById("input"));
@@ -88,27 +93,27 @@ TEST_F(TextControlElementTest, IndexForPosition) {
}
TEST_F(TextControlElementTest, ReadOnlyAttributeChangeEditability) {
- Input().setAttribute(HTMLNames::styleAttr, "all:initial");
- Input().setAttribute(HTMLNames::readonlyAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ Input().setAttribute(html_names::kStyleAttr, "all:initial");
+ Input().setAttribute(html_names::kReadonlyAttr, "");
+ UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
- Input().removeAttribute(HTMLNames::readonlyAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ Input().removeAttribute(html_names::kReadonlyAttr);
+ UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadWritePlaintextOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
}
TEST_F(TextControlElementTest, DisabledAttributeChangeEditability) {
- Input().setAttribute(HTMLNames::styleAttr, "all:initial");
- Input().setAttribute(HTMLNames::disabledAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ Input().setAttribute(html_names::kStyleAttr, "all:initial");
+ Input().setAttribute(html_names::kDisabledAttr, "");
+ UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
- Input().removeAttribute(HTMLNames::disabledAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ Input().removeAttribute(html_names::kDisabledAttr);
+ UpdateAllLifecyclePhases();
EXPECT_EQ(EUserModify::kReadWritePlaintextOnly,
Input().InnerEditorElement()->GetComputedStyle()->UserModify());
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.cc b/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.cc
index c07c17f5181..7c8e72c9115 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.cc
@@ -30,28 +30,24 @@
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
-#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
-#include "third_party/blink/renderer/core/events/text_event.h"
-#include "third_party/blink/renderer/core/events/text_event_input_type.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/html_names.h"
-#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/layout/layout_text_control_single_line.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
TextControlInnerContainer::TextControlInnerContainer(Document& document)
: HTMLDivElement(document) {}
TextControlInnerContainer* TextControlInnerContainer::Create(
Document& document) {
- TextControlInnerContainer* element = new TextControlInnerContainer(document);
- element->setAttribute(idAttr, ShadowElementNames::TextFieldContainer());
+ TextControlInnerContainer* element =
+ MakeGarbageCollected<TextControlInnerContainer>(document);
+ element->setAttribute(kIdAttr, shadow_element_names::TextFieldContainer());
return element;
}
@@ -68,8 +64,9 @@ EditingViewPortElement::EditingViewPortElement(Document& document)
}
EditingViewPortElement* EditingViewPortElement::Create(Document& document) {
- EditingViewPortElement* element = new EditingViewPortElement(document);
- element->setAttribute(idAttr, ShadowElementNames::EditingViewPort());
+ EditingViewPortElement* element =
+ MakeGarbageCollected<EditingViewPortElement>(document);
+ element->setAttribute(kIdAttr, shadow_element_names::EditingViewPort());
return element;
}
@@ -102,7 +99,7 @@ inline TextControlInnerEditorElement::TextControlInnerEditorElement(
TextControlInnerEditorElement* TextControlInnerEditorElement::Create(
Document& document) {
- return new TextControlInnerEditorElement(document);
+ return MakeGarbageCollected<TextControlInnerEditorElement>(document);
}
void TextControlInnerEditorElement::DefaultEventHandler(Event& event) {
@@ -111,7 +108,7 @@ void TextControlInnerEditorElement::DefaultEventHandler(Event& event) {
// this subclass.
// Or possibly we could just use a normal event listener.
if (event.IsBeforeTextInsertedEvent() ||
- event.type() == EventTypeNames::webkitEditableContentChanged) {
+ event.type() == event_type_names::kWebkitEditableContentChanged) {
Element* shadow_ancestor = OwnerShadowHost();
// A TextControlInnerTextElement can have no host if its been detached,
// but kept alive by an EditCommand. In this case, an undo/redo can
@@ -128,9 +125,9 @@ void TextControlInnerEditorElement::DefaultEventHandler(Event& event) {
void TextControlInnerEditorElement::SetVisibility(bool is_visible) {
if (is_visible_ != is_visible) {
is_visible_ = is_visible;
- SetNeedsStyleRecalc(
- kLocalStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
+ SetNeedsStyleRecalc(kLocalStyleChange,
+ StyleChangeReasonForTracing::Create(
+ style_change_reason::kControlValue));
}
}
@@ -217,26 +214,17 @@ TextControlInnerEditorElement::CreateInnerEditorStyle() const {
inline SearchFieldCancelButtonElement::SearchFieldCancelButtonElement(
Document& document)
- : HTMLDivElement(document), capturing_(false) {}
+ : HTMLDivElement(document) {}
SearchFieldCancelButtonElement* SearchFieldCancelButtonElement::Create(
Document& document) {
SearchFieldCancelButtonElement* element =
- new SearchFieldCancelButtonElement(document);
+ MakeGarbageCollected<SearchFieldCancelButtonElement>(document);
element->SetShadowPseudoId(AtomicString("-webkit-search-cancel-button"));
- element->setAttribute(idAttr, ShadowElementNames::SearchClearButton());
+ element->setAttribute(kIdAttr, shadow_element_names::SearchClearButton());
return element;
}
-void SearchFieldCancelButtonElement::DetachLayoutTree(
- const AttachContext& context) {
- if (capturing_) {
- if (LocalFrame* frame = GetDocument().GetFrame())
- frame->GetEventHandler().SetCapturingMouseEventsNode(nullptr);
- }
- HTMLDivElement::DetachLayoutTree(context);
-}
-
void SearchFieldCancelButtonElement::DefaultEventHandler(Event& event) {
// If the element is visible, on mouseup, clear the value, and set selection
HTMLInputElement* input(ToHTMLInputElement(OwnerShadowHost()));
@@ -246,7 +234,7 @@ void SearchFieldCancelButtonElement::DefaultEventHandler(Event& event) {
return;
}
- if (event.type() == EventTypeNames::click && event.IsMouseEvent() &&
+ if (event.type() == event_type_names::kClick && event.IsMouseEvent() &&
ToMouseEvent(event).button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
input->SetValueForUser("");
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.h b/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.h
index 8ae0bcf469e..b2c75e373da 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.h
@@ -36,8 +36,9 @@ class TextControlInnerContainer final : public HTMLDivElement {
public:
static TextControlInnerContainer* Create(Document&);
- protected:
explicit TextControlInnerContainer(Document&);
+
+ protected:
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
};
@@ -45,8 +46,9 @@ class EditingViewPortElement final : public HTMLDivElement {
public:
static EditingViewPortElement* Create(Document&);
- protected:
explicit EditingViewPortElement(Document&);
+
+ protected:
scoped_refptr<ComputedStyle> CustomStyleForLayoutObject() override;
private:
@@ -57,13 +59,14 @@ class TextControlInnerEditorElement final : public HTMLDivElement {
public:
static TextControlInnerEditorElement* Create(Document&);
+ explicit TextControlInnerEditorElement(Document&);
+
void DefaultEventHandler(Event&) override;
void SetVisibility(bool is_visible);
scoped_refptr<ComputedStyle> CreateInnerEditorStyle() const;
private:
- explicit TextControlInnerEditorElement(Document&);
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
scoped_refptr<ComputedStyle> CustomStyleForLayoutObject() override;
bool SupportsFocus() const override { return false; }
@@ -74,15 +77,13 @@ class SearchFieldCancelButtonElement final : public HTMLDivElement {
public:
static SearchFieldCancelButtonElement* Create(Document&);
+ explicit SearchFieldCancelButtonElement(Document&);
+
void DefaultEventHandler(Event&) override;
bool WillRespondToMouseClickEvents() override;
private:
- explicit SearchFieldCancelButtonElement(Document&);
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
bool SupportsFocus() const override { return false; }
-
- bool capturing_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_field_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/text_field_input_type.cc
index 5e2265d7b00..0968da45e29 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_field_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_field_input_type.cc
@@ -56,12 +56,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class DataListIndicatorElement final : public HTMLDivElement {
private:
- inline DataListIndicatorElement(Document& document)
- : HTMLDivElement(document) {}
inline HTMLInputElement* HostInput() const {
return ToHTMLInputElement(OwnerShadowHost());
}
@@ -75,14 +73,14 @@ class DataListIndicatorElement final : public HTMLDivElement {
// associated to the document. We don't want to open it in this case
// because we opens a datalist chooser later.
// FIXME: We should dispatch mousedown events even in such case.
- if (event.type() == EventTypeNames::mousedown)
+ if (event.type() == event_type_names::kMousedown)
event.stopPropagation();
return nullptr;
}
void DefaultEventHandler(Event& event) override {
DCHECK(GetDocument().IsActive());
- if (event.type() != EventTypeNames::click)
+ if (event.type() != event_type_names::kClick)
return;
HTMLInputElement* host = HostInput();
if (host && !host->IsDisabledOrReadOnly()) {
@@ -98,12 +96,16 @@ class DataListIndicatorElement final : public HTMLDivElement {
public:
static DataListIndicatorElement* Create(Document& document) {
- DataListIndicatorElement* element = new DataListIndicatorElement(document);
+ DataListIndicatorElement* element =
+ MakeGarbageCollected<DataListIndicatorElement>(document);
element->SetShadowPseudoId(
AtomicString("-webkit-calendar-picker-indicator"));
- element->setAttribute(idAttr, ShadowElementNames::PickerIndicator());
+ element->setAttribute(kIdAttr, shadow_element_names::PickerIndicator());
return element;
}
+
+ inline DataListIndicatorElement(Document& document)
+ : HTMLDivElement(document) {}
};
TextFieldInputType::TextFieldInputType(HTMLInputElement& element)
@@ -127,7 +129,7 @@ InputType::ValueMode TextFieldInputType::GetValueMode() const {
SpinButtonElement* TextFieldInputType::GetSpinButtonElement() const {
return ToSpinButtonElementOrDie(
GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SpinButton()));
+ shadow_element_names::SpinButton()));
}
bool TextFieldInputType::MayTriggerVirtualKeyboard() const {
@@ -226,12 +228,12 @@ void TextFieldInputType::ForwardEvent(Event& event) {
if (GetElement().GetLayoutObject() &&
(event.IsMouseEvent() || event.IsDragEvent() ||
- event.HasInterface(EventNames::WheelEvent) ||
- event.type() == EventTypeNames::blur ||
- event.type() == EventTypeNames::focus)) {
+ event.HasInterface(event_interface_names::kWheelEvent) ||
+ event.type() == event_type_names::kBlur ||
+ event.type() == event_type_names::kFocus)) {
LayoutTextControlSingleLine* layout_text_control =
ToLayoutTextControlSingleLine(GetElement().GetLayoutObject());
- if (event.type() == EventTypeNames::blur) {
+ if (event.type() == event_type_names::kBlur) {
if (LayoutBox* inner_editor_layout_object =
GetElement().InnerEditorElement()->GetLayoutBox()) {
// FIXME: This class has no need to know about PaintLayer!
@@ -245,7 +247,7 @@ void TextFieldInputType::ForwardEvent(Event& event) {
}
layout_text_control->CapsLockStateMayHaveChanged();
- } else if (event.type() == EventTypeNames::focus) {
+ } else if (event.type() == event_type_names::kFocus) {
layout_text_control->CapsLockStateMayHaveChanged();
}
@@ -261,8 +263,8 @@ void TextFieldInputType::HandleBlurEvent() {
}
bool TextFieldInputType::ShouldSubmitImplicitly(const Event& event) {
- return (event.type() == EventTypeNames::textInput &&
- event.HasInterface(EventNames::TextEvent) &&
+ return (event.type() == event_type_names::kTextInput &&
+ event.HasInterface(event_interface_names::kTextEvent) &&
ToTextEvent(event).data() == "\n") ||
InputTypeView::ShouldSubmitImplicitly(event);
}
@@ -317,7 +319,7 @@ void TextFieldInputType::CreateShadowSubtree() {
Element* TextFieldInputType::ContainerElement() const {
return GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::TextFieldContainer());
+ shadow_element_names::TextFieldContainer());
}
void TextFieldInputType::DestroyShadowSubtree() {
@@ -330,7 +332,7 @@ void TextFieldInputType::ListAttributeTargetChanged() {
if (ChromeClient* chrome_client = GetChromeClient())
chrome_client->TextFieldDataListChanged(GetElement());
Element* picker = GetElement().UserAgentShadowRoot()->getElementById(
- ShadowElementNames::PickerIndicator());
+ shadow_element_names::PickerIndicator());
bool did_have_picker_indicator = picker;
bool will_have_picker_indicator = GetElement().HasValidDataListOptions();
if (did_have_picker_indicator == will_have_picker_indicator)
@@ -377,11 +379,11 @@ void TextFieldInputType::DisabledOrReadonlyAttributeChanged(
}
void TextFieldInputType::DisabledAttributeChanged() {
- DisabledOrReadonlyAttributeChanged(disabledAttr);
+ DisabledOrReadonlyAttributeChanged(kDisabledAttr);
}
void TextFieldInputType::ReadonlyAttributeChanged() {
- DisabledOrReadonlyAttributeChanged(readonlyAttr);
+ DisabledOrReadonlyAttributeChanged(kReadonlyAttr);
}
bool TextFieldInputType::SupportsReadOnly() const {
@@ -482,7 +484,7 @@ void TextFieldInputType::UpdatePlaceholderText() {
CSSPropertyDisplay,
GetElement().IsPlaceholderVisible() ? CSSValueBlock : CSSValueNone,
true);
- placeholder->setAttribute(idAttr, ShadowElementNames::Placeholder());
+ placeholder->setAttribute(kIdAttr, shadow_element_names::Placeholder());
Element* container = ContainerElement();
Node* previous = container ? container : GetElement().InnerEditorElement();
previous->parentNode()->InsertBefore(placeholder, previous);
@@ -494,7 +496,7 @@ void TextFieldInputType::UpdatePlaceholderText() {
void TextFieldInputType::AppendToFormData(FormData& form_data) const {
InputType::AppendToFormData(form_data);
const AtomicString& dirname_attr_value =
- GetElement().FastGetAttribute(dirnameAttr);
+ GetElement().FastGetAttribute(kDirnameAttr);
if (!dirname_attr_value.IsNull()) {
form_data.AppendFromElement(dirname_attr_value,
GetElement().DirectionForFormData());
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/text_input_type.cc
index 29847acfacd..16432273aa2 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_input_type.cc
@@ -36,25 +36,25 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
InputType* TextInputType::Create(HTMLInputElement& element) {
- return new TextInputType(element);
+ return MakeGarbageCollected<TextInputType>(element);
}
void TextInputType::CountUsage() {
CountUsageIfVisible(WebFeature::kInputTypeText);
- if (GetElement().FastHasAttribute(maxlengthAttr))
+ if (GetElement().FastHasAttribute(kMaxlengthAttr))
CountUsageIfVisible(WebFeature::kInputTypeTextMaxLength);
- const AtomicString& type = GetElement().FastGetAttribute(typeAttr);
- if (DeprecatedEqualIgnoringCase(type, InputTypeNames::datetime))
+ const AtomicString& type = GetElement().FastGetAttribute(kTypeAttr);
+ if (DeprecatedEqualIgnoringCase(type, input_type_names::kDatetime))
CountUsageIfVisible(WebFeature::kInputTypeDateTimeFallback);
- else if (DeprecatedEqualIgnoringCase(type, InputTypeNames::week))
+ else if (DeprecatedEqualIgnoringCase(type, input_type_names::kWeek))
CountUsageIfVisible(WebFeature::kInputTypeWeekFallback);
}
const AtomicString& TextInputType::FormControlType() const {
- return InputTypeNames::text;
+ return input_type_names::kText;
}
bool TextInputType::SupportsInputModeAttribute() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/text_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/text_input_type.h
index 012d79470f9..2032439eb3f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/text_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/text_input_type.h
@@ -39,8 +39,9 @@ class TextInputType final : public BaseTextInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
TextInputType(HTMLInputElement& element) : BaseTextInputType(element) {}
+
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
bool SupportsInputModeAttribute() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/time_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/time_input_type.cc
index a3a7c972960..05d60c12099 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/time_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/time_input_type.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static const int kTimeDefaultStep = 60;
static const int kTimeDefaultStepBase = 0;
@@ -56,7 +56,7 @@ TimeInputType::TimeInputType(HTMLInputElement& element)
: BaseTemporalInputType(element) {}
InputType* TimeInputType::Create(HTMLInputElement& element) {
- return new TimeInputType(element);
+ return MakeGarbageCollected<TimeInputType>(element);
}
void TimeInputType::CountUsage() {
@@ -64,7 +64,7 @@ void TimeInputType::CountUsage() {
}
const AtomicString& TimeInputType::FormControlType() const {
- return InputTypeNames::time;
+ return input_type_names::kTime;
}
Decimal TimeInputType::DefaultValueForStepUp() const {
@@ -158,10 +158,10 @@ void TimeInputType::SetupLayoutParameters(
layout_parameters.locale.ShortTimeFormat();
layout_parameters.fallback_date_time_format = "HH:mm";
}
- if (!ParseToDateComponents(GetElement().FastGetAttribute(minAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMinAttr),
&layout_parameters.minimum))
layout_parameters.minimum = DateComponents();
- if (!ParseToDateComponents(GetElement().FastGetAttribute(maxAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMaxAttr),
&layout_parameters.maximum))
layout_parameters.maximum = DateComponents();
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/time_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/time_input_type.h
index 91abeeead30..d5d74cf8415 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/time_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/time_input_type.h
@@ -39,9 +39,9 @@ class TimeInputType final : public BaseTemporalInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
explicit TimeInputType(HTMLInputElement&);
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
Decimal DefaultValueForStepUp() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/url_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/url_input_type.cc
index 6cc7a579274..c58aa25d330 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/url_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/url_input_type.cc
@@ -39,7 +39,7 @@
namespace blink {
InputType* URLInputType::Create(HTMLInputElement& element) {
- return new URLInputType(element);
+ return MakeGarbageCollected<URLInputType>(element);
}
void URLInputType::CountUsage() {
@@ -47,7 +47,7 @@ void URLInputType::CountUsage() {
}
const AtomicString& URLInputType::FormControlType() const {
- return InputTypeNames::url;
+ return input_type_names::kUrl;
}
bool URLInputType::TypeMismatchFor(const String& value) const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/url_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/url_input_type.h
index 6084b52eddc..8d1ec156b9e 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/url_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/url_input_type.h
@@ -39,8 +39,9 @@ class URLInputType final : public BaseTextInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
URLInputType(HTMLInputElement& element) : BaseTextInputType(element) {}
+
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
bool TypeMismatchFor(const String&) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/validity_state.h b/chromium/third_party/blink/renderer/core/html/forms/validity_state.h
index 483bbcd863d..7daa760dcfa 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/validity_state.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/validity_state.h
@@ -35,8 +35,11 @@ class ValidityState final : public ScriptWrappable {
public:
static ValidityState* Create(ListedElement* control) {
- return new ValidityState(control);
+ return MakeGarbageCollected<ValidityState>(control);
}
+
+ explicit ValidityState(ListedElement* control) : control_(control) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(control_);
ScriptWrappable::Trace(visitor);
@@ -59,8 +62,6 @@ class ValidityState final : public ScriptWrappable {
bool valid() const;
private:
- explicit ValidityState(ListedElement* control) : control_(control) {}
-
Member<ListedElement> control_;
DISALLOW_COPY_AND_ASSIGN(ValidityState);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/week_input_type.cc b/chromium/third_party/blink/renderer/core/html/forms/week_input_type.cc
index 1dcd8d01db2..6a27534a74f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/week_input_type.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/week_input_type.cc
@@ -41,7 +41,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static const int kWeekDefaultStepBase =
-259200000; // The first day of 1970-W01.
@@ -49,7 +49,7 @@ static const int kWeekDefaultStep = 1;
static const int kWeekStepScaleFactor = 604800000;
InputType* WeekInputType::Create(HTMLInputElement& element) {
- return new WeekInputType(element);
+ return MakeGarbageCollected<WeekInputType>(element);
}
void WeekInputType::CountUsage() {
@@ -57,7 +57,7 @@ void WeekInputType::CountUsage() {
}
const AtomicString& WeekInputType::FormControlType() const {
- return InputTypeNames::week;
+ return input_type_names::kWeek;
}
StepRange WeekInputType::CreateStepRange(
@@ -109,10 +109,10 @@ void WeekInputType::SetupLayoutParameters(
const DateComponents&) const {
layout_parameters.date_time_format = GetLocale().WeekFormatInLDML();
layout_parameters.fallback_date_time_format = "yyyy-'W'ww";
- if (!ParseToDateComponents(GetElement().FastGetAttribute(minAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMinAttr),
&layout_parameters.minimum))
layout_parameters.minimum = DateComponents();
- if (!ParseToDateComponents(GetElement().FastGetAttribute(maxAttr),
+ if (!ParseToDateComponents(GetElement().FastGetAttribute(kMaxAttr),
&layout_parameters.maximum))
layout_parameters.maximum = DateComponents();
layout_parameters.placeholder_for_year = "----";
diff --git a/chromium/third_party/blink/renderer/core/html/forms/week_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/week_input_type.h
index 6486a627dc3..f4ed68e3534 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/week_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/week_input_type.h
@@ -39,10 +39,10 @@ class WeekInputType final : public BaseTemporalInputType {
public:
static InputType* Create(HTMLInputElement&);
- private:
explicit WeekInputType(HTMLInputElement& element)
: BaseTemporalInputType(element) {}
+ private:
void CountUsage() override;
const AtomicString& FormControlType() const override;
StepRange CreateStepRange(AnyStepHandling) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/html_all_collection.cc b/chromium/third_party/blink/renderer/core/html/html_all_collection.cc
index bebba4c1c51..885bba2a34c 100644
--- a/chromium/third_party/blink/renderer/core/html/html_all_collection.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_all_collection.cc
@@ -32,7 +32,7 @@ namespace blink {
HTMLAllCollection* HTMLAllCollection::Create(ContainerNode& node,
CollectionType type) {
DCHECK_EQ(type, kDocAll);
- return new HTMLAllCollection(node);
+ return MakeGarbageCollected<HTMLAllCollection>(node);
}
HTMLAllCollection::HTMLAllCollection(ContainerNode& node)
diff --git a/chromium/third_party/blink/renderer/core/html/html_all_collection.h b/chromium/third_party/blink/renderer/core/html/html_all_collection.h
index 6dd056437fd..eae71686267 100644
--- a/chromium/third_party/blink/renderer/core/html/html_all_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/html_all_collection.h
@@ -38,12 +38,12 @@ class HTMLAllCollection final : public HTMLCollection {
public:
static HTMLAllCollection* Create(ContainerNode&, CollectionType);
+
+ explicit HTMLAllCollection(ContainerNode&);
~HTMLAllCollection() override;
+
Element* AnonymousIndexedGetter(unsigned index);
void NamedGetter(const AtomicString& name, HTMLCollectionOrElement&);
-
- private:
- explicit HTMLAllCollection(ContainerNode&);
};
DEFINE_TYPE_CASTS(HTMLAllCollection,
diff --git a/chromium/third_party/blink/renderer/core/html/html_anchor_element.cc b/chromium/third_party/blink/renderer/core/html/html_anchor_element.cc
index 1b4522742e7..c55a66f3f58 100644
--- a/chromium/third_party/blink/renderer/core/html/html_anchor_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_anchor_element.cc
@@ -24,11 +24,14 @@
#include "third_party/blink/renderer/core/html/html_anchor_element.h"
+#include "base/metrics/histogram_macros.h"
+#include "third_party/blink/public/common/download/download_stats.h"
#include "third_party/blink/renderer/bindings/core/v8/usv_string_or_trusted_url.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
+#include "third_party/blink/renderer/core/frame/ad_tracker.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
@@ -41,6 +44,7 @@
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/loader/navigation_policy.h"
#include "third_party/blink/renderer/core/loader/ping_loader.h"
+#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h"
@@ -51,7 +55,30 @@
namespace blink {
-using namespace HTMLNames;
+namespace {
+
+void RecordDownloadMetrics(LocalFrame* frame) {
+ if (frame->IsMainFrame()) {
+ DownloadStats::RecordMainFrameHasGesture(
+ LocalFrame::HasTransientUserActivation(frame));
+ return;
+ }
+
+ unsigned value = 0;
+ if (frame->GetDocument()->IsSandboxed(kSandboxDownloads))
+ value |= DownloadStats::kSandboxBit;
+ if (frame->IsCrossOriginSubframe())
+ value |= DownloadStats::kCrossOriginBit;
+ if (frame->IsAdSubframe())
+ value |= DownloadStats::kAdBit;
+ if (LocalFrame::HasTransientUserActivation(frame))
+ value |= DownloadStats::kGestureBit;
+ DownloadStats::RecordSubframeSandboxOriginAdGesture(value);
+}
+
+} // namespace
+
+using namespace html_names;
HTMLAnchorElement::HTMLAnchorElement(const QualifiedName& tag_name,
Document& document)
@@ -61,7 +88,7 @@ HTMLAnchorElement::HTMLAnchorElement(const QualifiedName& tag_name,
rel_list_(RelList::Create(this)) {}
HTMLAnchorElement* HTMLAnchorElement::Create(Document& document) {
- return new HTMLAnchorElement(aTag, document);
+ return MakeGarbageCollected<HTMLAnchorElement>(kATag, document);
}
HTMLAnchorElement::~HTMLAnchorElement() = default;
@@ -182,7 +209,7 @@ void HTMLAnchorElement::AttributeChanged(
HTMLElement::AttributeChanged(params);
if (params.reason != AttributeModificationReason::kDirectly)
return;
- if (params.name != hrefAttr)
+ if (params.name != kHrefAttr)
return;
if (!IsLink() && AdjustedFocusedElementInTreeScope() == this)
blur();
@@ -190,7 +217,7 @@ void HTMLAnchorElement::AttributeChanged(
void HTMLAnchorElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == hrefAttr) {
+ if (params.name == kHrefAttr) {
bool was_link = IsLink();
SetIsLink(!params.new_value.IsNull());
if (was_link || IsLink()) {
@@ -209,9 +236,9 @@ void HTMLAnchorElement::ParseAttribute(
}
InvalidateCachedVisitedLinkHash();
LogUpdateAttributeIfIsolatedWorldAndInDocument("a", params);
- } else if (params.name == nameAttr || params.name == titleAttr) {
+ } else if (params.name == kNameAttr || params.name == kTitleAttr) {
// Do nothing.
- } else if (params.name == relAttr) {
+ } else if (params.name == kRelAttr) {
SetRel(params.new_value);
rel_list_->DidUpdateAttributeValue(params.old_value, params.new_value);
} else {
@@ -225,12 +252,12 @@ void HTMLAnchorElement::AccessKeyAction(bool send_mouse_events) {
}
bool HTMLAnchorElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName().LocalName() == hrefAttr ||
+ return attribute.GetName().LocalName() == kHrefAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLAnchorElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == hrefAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kHrefAttr || HTMLElement::HasLegalLinkAttribute(name);
}
bool HTMLAnchorElement::CanStartSelection() const {
@@ -241,26 +268,26 @@ bool HTMLAnchorElement::CanStartSelection() const {
bool HTMLAnchorElement::draggable() const {
// Should be draggable if we have an href attribute.
- const AtomicString& value = getAttribute(draggableAttr);
+ const AtomicString& value = getAttribute(kDraggableAttr);
if (DeprecatedEqualIgnoringCase(value, "true"))
return true;
if (DeprecatedEqualIgnoringCase(value, "false"))
return false;
- return hasAttribute(hrefAttr);
+ return hasAttribute(kHrefAttr);
}
KURL HTMLAnchorElement::Href() const {
return GetDocument().CompleteURL(
- StripLeadingAndTrailingHTMLSpaces(getAttribute(hrefAttr)));
+ StripLeadingAndTrailingHTMLSpaces(getAttribute(kHrefAttr)));
}
void HTMLAnchorElement::SetHref(const AtomicString& value) {
- setAttribute(hrefAttr, value);
+ setAttribute(kHrefAttr, value);
}
void HTMLAnchorElement::setHref(const USVStringOrTrustedURL& stringOrTrustedURL,
ExceptionState& exception_state) {
- setAttribute(hrefAttr, stringOrTrustedURL, exception_state);
+ setAttribute(kHrefAttr, stringOrTrustedURL, exception_state);
}
KURL HTMLAnchorElement::Url() const {
@@ -272,7 +299,7 @@ void HTMLAnchorElement::SetURL(const KURL& url) {
}
String HTMLAnchorElement::Input() const {
- return getAttribute(hrefAttr);
+ return getAttribute(kHrefAttr);
}
void HTMLAnchorElement::SetInput(const String& value) {
@@ -307,7 +334,7 @@ bool HTMLAnchorElement::IsLiveLink() const {
}
void HTMLAnchorElement::SendPings(const KURL& destination_url) const {
- const AtomicString& ping_value = getAttribute(pingAttr);
+ const AtomicString& ping_value = getAttribute(kPingAttr);
if (ping_value.IsNull() || !GetDocument().GetSettings() ||
!GetDocument().GetSettings()->GetHyperlinkAuditingEnabled()) {
return;
@@ -350,7 +377,7 @@ void HTMLAnchorElement::HandleClick(Event& event) {
AnchorElementMetrics::MaybeReportClickedMetricsOnClick(this);
StringBuilder url;
- url.Append(StripLeadingAndTrailingHTMLSpaces(FastGetAttribute(hrefAttr)));
+ url.Append(StripLeadingAndTrailingHTMLSpaces(FastGetAttribute(kHrefAttr)));
AppendServerMapMousePosition(url, &event);
KURL completed_url = GetDocument().CompleteURL(url.ToString());
@@ -360,10 +387,10 @@ void HTMLAnchorElement::HandleClick(Event& event) {
ResourceRequest request(completed_url);
- ReferrerPolicy policy;
- if (hasAttribute(referrerpolicyAttr) &&
+ network::mojom::ReferrerPolicy policy;
+ if (hasAttribute(kReferrerpolicyAttr) &&
SecurityPolicy::ReferrerPolicyFromString(
- FastGetAttribute(referrerpolicyAttr),
+ FastGetAttribute(kReferrerpolicyAttr),
kSupportReferrerPolicyLegacyKeywords, &policy) &&
!HasRel(kRelationNoReferrer)) {
UseCounter::Count(GetDocument(),
@@ -371,9 +398,12 @@ void HTMLAnchorElement::HandleClick(Event& event) {
request.SetReferrerPolicy(policy);
}
- if (hasAttribute(downloadAttr)) {
+ // Ignore the download attribute if we either can't read the content, or
+ // the event is an alt-click or similar.
+ if (hasAttribute(kDownloadAttr) &&
+ NavigationPolicyFromEvent(&event) != kNavigationPolicyDownload &&
+ GetDocument().GetSecurityOrigin()->CanReadContent(completed_url)) {
if (GetDocument().IsSandboxed(kSandboxDownloads)) {
- // TODO(jochen): Also measure navigations resulting in downloads.
UseCounter::Count(
GetDocument(),
UserGestureIndicator::ProcessingUserGesture()
@@ -381,28 +411,31 @@ void HTMLAnchorElement::HandleClick(Event& event) {
: WebFeature::
kHTMLAnchorElementDownloadInSandboxWithoutUserGesture);
}
- // Ignore the download attribute if we either can't read the content, or
- // the event is an alt-click or similar.
- if (NavigationPolicyFromEvent(&event) != kNavigationPolicyDownload &&
- GetDocument().GetSecurityOrigin()->CanReadContent(completed_url)) {
- request.SetSuggestedFilename(
- static_cast<String>(FastGetAttribute(downloadAttr)));
- request.SetRequestContext(mojom::RequestContextType::DOWNLOAD);
- request.SetRequestorOrigin(SecurityOrigin::Create(GetDocument().Url()));
- frame->Client()->DownloadURL(request,
- DownloadCrossOriginRedirects::kNavigate);
- return;
- }
+ RecordDownloadMetrics(frame);
+ request.SetSuggestedFilename(
+ static_cast<String>(FastGetAttribute(kDownloadAttr)));
+ request.SetRequestContext(mojom::RequestContextType::DOWNLOAD);
+ request.SetRequestorOrigin(SecurityOrigin::Create(GetDocument().Url()));
+ frame->Client()->DownloadURL(request,
+ DownloadCrossOriginRedirects::kNavigate);
+ return;
}
+
request.SetRequestContext(mojom::RequestContextType::HYPERLINK);
FrameLoadRequest frame_request(&GetDocument(), request,
- getAttribute(targetAttr));
+ getAttribute(kTargetAttr));
if (HasRel(kRelationNoReferrer)) {
frame_request.SetShouldSendReferrer(kNeverSendReferrer);
frame_request.SetShouldSetOpener(kNeverSetOpener);
}
if (HasRel(kRelationNoOpener))
frame_request.SetShouldSetOpener(kNeverSetOpener);
+ if (origin_trials::HrefTranslateEnabled(&GetDocument()) &&
+ hasAttribute(kHreftranslateAttr)) {
+ frame_request.SetHrefTranslate(FastGetAttribute(kHreftranslateAttr));
+ UseCounter::Count(GetDocument(),
+ WebFeature::kHTMLAnchorElementHrefTranslateAttribute);
+ }
frame_request.SetTriggeringEventInfo(
event.isTrusted() ? WebTriggeringEventInfo::kFromTrustedEvent
: WebTriggeringEventInfo::kFromUntrustedEvent);
@@ -414,14 +447,14 @@ void HTMLAnchorElement::HandleClick(Event& event) {
}
bool IsEnterKeyKeydownEvent(Event& event) {
- return event.type() == EventTypeNames::keydown && event.IsKeyboardEvent() &&
- ToKeyboardEvent(event).key() == "Enter" &&
+ return event.type() == event_type_names::kKeydown &&
+ event.IsKeyboardEvent() && ToKeyboardEvent(event).key() == "Enter" &&
!ToKeyboardEvent(event).repeat();
}
bool IsLinkClick(Event& event) {
- if ((event.type() != EventTypeNames::click &&
- event.type() != EventTypeNames::auxclick) ||
+ if ((event.type() != event_type_names::kClick &&
+ event.type() != event_type_names::kAuxclick) ||
!event.IsMouseEvent()) {
return false;
}
@@ -443,7 +476,7 @@ Node::InsertionNotificationRequest HTMLAnchorElement::InsertedInto(
ContainerNode& insertion_point) {
InsertionNotificationRequest request =
HTMLElement::InsertedInto(insertion_point);
- LogAddElementIfIsolatedWorldAndInDocument("a", hrefAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("a", kHrefAttr);
Document& top_document = GetDocument().TopDocument();
if (AnchorElementMetricsSender::HasAnchorElementMetricsSender(top_document))
diff --git a/chromium/third_party/blink/renderer/core/html/html_anchor_element.h b/chromium/third_party/blink/renderer/core/html/html_anchor_element.h
index 9b771fa3897..464ae2a2272 100644
--- a/chromium/third_party/blink/renderer/core/html/html_anchor_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_anchor_element.h
@@ -67,6 +67,7 @@ class CORE_EXPORT HTMLAnchorElement : public HTMLElement, public DOMURLUtils {
public:
static HTMLAnchorElement* Create(Document&);
+ HTMLAnchorElement(const QualifiedName&, Document&);
~HTMLAnchorElement() override;
// Returns attributes that should be checked against Trusted Types
@@ -102,8 +103,6 @@ class CORE_EXPORT HTMLAnchorElement : public HTMLElement, public DOMURLUtils {
void Trace(blink::Visitor*) override;
protected:
- HTMLAnchorElement(const QualifiedName&, Document&);
-
void ParseAttribute(const AttributeModificationParams&) override;
bool SupportsFocus() const override;
bool MatchesEnabledPseudoClass() const override;
@@ -132,9 +131,10 @@ class CORE_EXPORT HTMLAnchorElement : public HTMLElement, public DOMURLUtils {
};
inline LinkHash HTMLAnchorElement::VisitedLinkHash() const {
- if (!cached_visited_link_hash_)
+ if (!cached_visited_link_hash_) {
cached_visited_link_hash_ = blink::VisitedLinkHash(
- GetDocument().BaseURL(), FastGetAttribute(HTMLNames::hrefAttr));
+ GetDocument().BaseURL(), FastGetAttribute(html_names::kHrefAttr));
+ }
return cached_visited_link_hash_;
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_anchor_element.idl b/chromium/third_party/blink/renderer/core/html/html_anchor_element.idl
index b988d1be33c..9d3bf75ec15 100644
--- a/chromium/third_party/blink/renderer/core/html/html_anchor_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_anchor_element.idl
@@ -27,7 +27,7 @@ interface HTMLAnchorElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString rel;
[SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
[CEReactions, Reflect] attribute DOMString hreflang;
- [RuntimeEnabled=HrefTranslate, CEReactions, Reflect] attribute DOMString hrefTranslate;
+ [OriginTrialEnabled=HrefTranslate, CEReactions, Reflect] attribute DOMString hrefTranslate;
[CEReactions, Reflect] attribute DOMString type;
[CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy;
diff --git a/chromium/third_party/blink/renderer/core/html/html_area_element.cc b/chromium/third_party/blink/renderer/core/html/html_area_element.cc
index e7f425381f5..389f334ba23 100644
--- a/chromium/third_party/blink/renderer/core/html/html_area_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_area_element.cc
@@ -42,10 +42,10 @@ float ClampCoordinate(double value) {
}
}
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLAreaElement::HTMLAreaElement(Document& document)
- : HTMLAnchorElement(areaTag, document), shape_(kRect) {}
+ : HTMLAnchorElement(kAreaTag, document), shape_(kRect) {}
// An explicit empty destructor should be in html_area_element.cc, because
// if an implicit destructor is used or an empty destructor is defined in
@@ -59,7 +59,7 @@ DEFINE_NODE_FACTORY(HTMLAreaElement)
void HTMLAreaElement::ParseAttribute(
const AttributeModificationParams& params) {
const AtomicString& value = params.new_value;
- if (params.name == shapeAttr) {
+ if (params.name == kShapeAttr) {
if (EqualIgnoringASCIICase(value, "default")) {
shape_ = kDefault;
} else if (EqualIgnoringASCIICase(value, "circle") ||
@@ -74,10 +74,10 @@ void HTMLAreaElement::ParseAttribute(
shape_ = kRect;
}
InvalidateCachedPath();
- } else if (params.name == coordsAttr) {
+ } else if (params.name == kCoordsAttr) {
coords_ = ParseHTMLListOfFloatingPointNumbers(value.GetString());
InvalidateCachedPath();
- } else if (params.name == altAttr || params.name == accesskeyAttr) {
+ } else if (params.name == kAltAttr || params.name == kAccesskeyAttr) {
// Do nothing.
} else {
HTMLAnchorElement::ParseAttribute(params);
@@ -222,7 +222,7 @@ void HTMLAreaElement::SetFocused(bool should_be_focused,
void HTMLAreaElement::UpdateFocusAppearanceWithOptions(
SelectionBehaviorOnFocus selection_behavior,
- const FocusOptions& options) {
+ const FocusOptions* options) {
GetDocument().UpdateStyleAndLayoutTreeForNode(this);
if (!IsFocusable())
return;
diff --git a/chromium/third_party/blink/renderer/core/html/html_area_element.h b/chromium/third_party/blink/renderer/core/html/html_area_element.h
index 4560faee49f..7d710716267 100644
--- a/chromium/third_party/blink/renderer/core/html/html_area_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_area_element.h
@@ -66,7 +66,7 @@ class CORE_EXPORT HTMLAreaElement final : public HTMLAnchorElement {
bool IsMouseFocusable() const override;
bool IsFocusableStyle() const override;
void UpdateFocusAppearanceWithOptions(SelectionBehaviorOnFocus,
- const FocusOptions&) override;
+ const FocusOptions*) override;
void SetFocused(bool, WebFocusType) override;
enum Shape { kDefault, kPoly, kRect, kCircle };
diff --git a/chromium/third_party/blink/renderer/core/html/html_attribute_names.json5 b/chromium/third_party/blink/renderer/core/html/html_attribute_names.json5
index 3490cba6647..688b1ba533b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_attribute_names.json5
+++ b/chromium/third_party/blink/renderer/core/html/html_attribute_names.json5
@@ -77,6 +77,7 @@
"enctype",
"end",
"event",
+ "exportparts",
"face",
"for",
"form",
@@ -97,7 +98,8 @@
"hspace",
"http-equiv",
"id",
- "imgsizes",
+ "imagesizes",
+ "imagesrcset",
"importance",
"incremental",
"inert",
@@ -258,7 +260,6 @@
"open",
"optimum",
"part",
- "partmap",
"pattern",
"placeholder",
"ping",
diff --git a/chromium/third_party/blink/renderer/core/html/html_base_element.cc b/chromium/third_party/blink/renderer/core/html/html_base_element.cc
index 4553ea5cdb5..c72c4f9dd31 100644
--- a/chromium/third_party/blink/renderer/core/html/html_base_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_base_element.cc
@@ -32,10 +32,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLBaseElement::HTMLBaseElement(Document& document)
- : HTMLElement(baseTag, document) {}
+ : HTMLElement(kBaseTag, document) {}
DEFINE_NODE_FACTORY(HTMLBaseElement)
@@ -46,7 +46,7 @@ const HashSet<AtomicString>& HTMLBaseElement::GetCheckedAttributeNames() const {
void HTMLBaseElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == hrefAttr || params.name == targetAttr)
+ if (params.name == kHrefAttr || params.name == kTargetAttr)
GetDocument().ProcessBaseElement();
else
HTMLElement::ParseAttribute(params);
@@ -67,7 +67,7 @@ void HTMLBaseElement::RemovedFrom(ContainerNode& insertion_point) {
}
bool HTMLBaseElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName().LocalName() == hrefAttr ||
+ return attribute.GetName().LocalName() == kHrefAttr ||
HTMLElement::IsURLAttribute(attribute);
}
@@ -82,7 +82,7 @@ KURL HTMLBaseElement::href() const {
// document's fallback base URL and ignore the base URL.
// https://html.spec.whatwg.org/multipage/semantics.html#dom-base-href
- const AtomicString& attribute_value = FastGetAttribute(hrefAttr);
+ const AtomicString& attribute_value = FastGetAttribute(kHrefAttr);
if (attribute_value.IsNull())
return GetDocument().Url();
@@ -101,7 +101,7 @@ KURL HTMLBaseElement::href() const {
void HTMLBaseElement::setHref(const USVStringOrTrustedURL& stringOrUrl,
ExceptionState& exception_state) {
- setAttribute(hrefAttr, stringOrUrl, exception_state);
+ setAttribute(kHrefAttr, stringOrUrl, exception_state);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_bdi_element.h b/chromium/third_party/blink/renderer/core/html/html_bdi_element.h
index a015a8ec024..2e5a947270b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_bdi_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_bdi_element.h
@@ -31,7 +31,7 @@ class HTMLBDIElement final : public HTMLElement {
private:
inline explicit HTMLBDIElement(Document& document)
- : HTMLElement(HTMLNames::bdiTag, document) {}
+ : HTMLElement(html_names::kBdiTag, document) {}
};
DEFINE_NODE_FACTORY(HTMLBDIElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_body_element.cc b/chromium/third_party/blink/renderer/core/html/html_body_element.cc
index 145122c5fdd..86a99736d2a 100644
--- a/chromium/third_party/blink/renderer/core/html/html_body_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_body_element.cc
@@ -40,19 +40,19 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLBodyElement::HTMLBodyElement(Document& document)
- : HTMLElement(bodyTag, document) {}
+ : HTMLElement(kBodyTag, document) {}
DEFINE_NODE_FACTORY(HTMLBodyElement)
HTMLBodyElement::~HTMLBodyElement() = default;
bool HTMLBodyElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == backgroundAttr || name == marginwidthAttr ||
- name == leftmarginAttr || name == marginheightAttr ||
- name == topmarginAttr || name == bgcolorAttr || name == textAttr)
+ if (name == kBackgroundAttr || name == kMarginwidthAttr ||
+ name == kLeftmarginAttr || name == kMarginheightAttr ||
+ name == kTopmarginAttr || name == kBgcolorAttr || name == kTextAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -61,7 +61,7 @@ void HTMLBodyElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == backgroundAttr) {
+ if (name == kBackgroundAttr) {
String url = StripLeadingAndTrailingHTMLSpaces(value);
if (!url.IsEmpty()) {
CSSImageValue* image_value =
@@ -72,15 +72,15 @@ void HTMLBodyElement::CollectStyleForPresentationAttribute(
style->SetProperty(
CSSPropertyValue(GetCSSPropertyBackgroundImage(), *image_value));
}
- } else if (name == marginwidthAttr || name == leftmarginAttr) {
+ } else if (name == kMarginwidthAttr || name == kLeftmarginAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
- } else if (name == marginheightAttr || name == topmarginAttr) {
+ } else if (name == kMarginheightAttr || name == kTopmarginAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
- } else if (name == bgcolorAttr) {
+ } else if (name == kBgcolorAttr) {
AddHTMLColorToStyle(style, CSSPropertyBackgroundColor, value);
- } else if (name == textAttr) {
+ } else if (name == kTextAttr) {
AddHTMLColorToStyle(style, CSSPropertyColor, value);
} else {
HTMLElement::CollectStyleForPresentationAttribute(name, value, style);
@@ -91,11 +91,11 @@ void HTMLBodyElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == vlinkAttr || name == alinkAttr || name == linkAttr) {
+ if (name == kVlinkAttr || name == kAlinkAttr || name == kLinkAttr) {
if (value.IsNull()) {
- if (name == linkAttr)
+ if (name == kLinkAttr)
GetDocument().GetTextLinkColors().ResetLinkColor();
- else if (name == vlinkAttr)
+ else if (name == kVlinkAttr)
GetDocument().GetTextLinkColors().ResetVisitedLinkColor();
else
GetDocument().GetTextLinkColors().ResetActiveLinkColor();
@@ -105,9 +105,9 @@ void HTMLBodyElement::ParseAttribute(
if (!HTMLElement::ParseColorWithLegacyRules(string_value, color))
return;
- if (name == linkAttr)
+ if (name == kLinkAttr)
GetDocument().GetTextLinkColors().SetLinkColor(color);
- else if (name == vlinkAttr)
+ else if (name == kVlinkAttr)
GetDocument().GetTextLinkColors().SetVisitedLinkColor(color);
else
GetDocument().GetTextLinkColors().SetActiveLinkColor(color);
@@ -115,101 +115,101 @@ void HTMLBodyElement::ParseAttribute(
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kLinkColorChange));
- } else if (name == onafterprintAttr) {
+ style_change_reason::kLinkColorChange));
+ } else if (name == kOnafterprintAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::afterprint,
+ event_type_names::kAfterprint,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onbeforeprintAttr) {
+ } else if (name == kOnbeforeprintAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::beforeprint,
+ event_type_names::kBeforeprint,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onloadAttr) {
+ } else if (name == kOnloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::load,
+ event_type_names::kLoad,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onbeforeunloadAttr) {
+ } else if (name == kOnbeforeunloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::beforeunload,
+ event_type_names::kBeforeunload,
CreateAttributeEventListener(
GetDocument().GetFrame(), name, value,
JSEventHandler::HandlerType::kOnBeforeUnloadEventHandler));
- } else if (name == onunloadAttr) {
+ } else if (name == kOnunloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::unload,
+ event_type_names::kUnload,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onpagehideAttr) {
+ } else if (name == kOnpagehideAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::pagehide,
+ event_type_names::kPagehide,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onpageshowAttr) {
+ } else if (name == kOnpageshowAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::pageshow,
+ event_type_names::kPageshow,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onpopstateAttr) {
+ } else if (name == kOnpopstateAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::popstate,
+ event_type_names::kPopstate,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onblurAttr) {
+ } else if (name == kOnblurAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::blur,
+ event_type_names::kBlur,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onerrorAttr) {
+ } else if (name == kOnerrorAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::error,
+ event_type_names::kError,
CreateAttributeEventListener(
GetDocument().GetFrame(), name, value,
JSEventHandler::HandlerType::kOnErrorEventHandler));
- } else if (name == onfocusAttr) {
+ } else if (name == kOnfocusAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::focus,
+ event_type_names::kFocus,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
} else if (RuntimeEnabledFeatures::OrientationEventEnabled() &&
- name == onorientationchangeAttr) {
+ name == kOnorientationchangeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::orientationchange,
+ event_type_names::kOrientationchange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onhashchangeAttr) {
+ } else if (name == kOnhashchangeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::hashchange,
+ event_type_names::kHashchange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onmessageAttr) {
+ } else if (name == kOnmessageAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::message,
+ event_type_names::kMessage,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onmessageerrorAttr) {
+ } else if (name == kOnmessageerrorAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::messageerror,
+ event_type_names::kMessageerror,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onresizeAttr) {
+ } else if (name == kOnresizeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::resize,
+ event_type_names::kResize,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onscrollAttr) {
+ } else if (name == kOnscrollAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::scroll,
+ event_type_names::kScroll,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onselectionchangeAttr) {
+ } else if (name == kOnselectionchangeAttr) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLBodyElementOnSelectionChangeAttribute);
GetDocument().SetAttributeEventListener(
- EventTypeNames::selectionchange,
+ event_type_names::kSelectionchange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onstorageAttr) {
+ } else if (name == kOnstorageAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::storage,
+ event_type_names::kStorage,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == ononlineAttr) {
+ } else if (name == kOnonlineAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::online,
+ event_type_names::kOnline,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onofflineAttr) {
+ } else if (name == kOnofflineAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::offline,
+ event_type_names::kOffline,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onlanguagechangeAttr) {
+ } else if (name == kOnlanguagechangeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::languagechange,
+ event_type_names::kLanguagechange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
} else {
HTMLElement::ParseAttribute(params);
@@ -230,23 +230,23 @@ void HTMLBodyElement::DidNotifySubtreeInsertionsToDocument() {
int margin_width = GetDocument().GetFrame()->Owner()->MarginWidth();
int margin_height = GetDocument().GetFrame()->Owner()->MarginHeight();
if (margin_width != -1)
- SetIntegralAttribute(marginwidthAttr, margin_width);
+ SetIntegralAttribute(kMarginwidthAttr, margin_width);
if (margin_height != -1)
- SetIntegralAttribute(marginheightAttr, margin_height);
+ SetIntegralAttribute(kMarginheightAttr, margin_height);
}
}
bool HTMLBodyElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == backgroundAttr ||
+ return attribute.GetName() == kBackgroundAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLBodyElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == backgroundAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kBackgroundAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLBodyElement::SubResourceAttributeName() const {
- return backgroundAttr;
+ return kBackgroundAttr;
}
bool HTMLBodyElement::SupportsFocus() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_body_element.h b/chromium/third_party/blink/renderer/core/html/html_body_element.h
index 16bc931578a..b03d6cffee2 100644
--- a/chromium/third_party/blink/renderer/core/html/html_body_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_body_element.h
@@ -39,13 +39,13 @@ class CORE_EXPORT HTMLBodyElement final : public HTMLElement {
DECLARE_NODE_FACTORY(HTMLBodyElement);
~HTMLBodyElement() override;
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur, kBlur);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus, kFocus);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load, kLoad);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize, kResize);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll, kScroll);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange, kOrientationchange);
private:
explicit HTMLBodyElement(Document&);
diff --git a/chromium/third_party/blink/renderer/core/html/html_br_element.cc b/chromium/third_party/blink/renderer/core/html/html_br_element.cc
index 0a552d0d1fd..b11c3915fa6 100644
--- a/chromium/third_party/blink/renderer/core/html/html_br_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_br_element.cc
@@ -22,22 +22,22 @@
#include "third_party/blink/renderer/core/html/html_br_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_br.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLBRElement::HTMLBRElement(Document& document)
- : HTMLElement(brTag, document) {}
+ : HTMLElement(kBrTag, document) {}
DEFINE_NODE_FACTORY(HTMLBRElement)
bool HTMLBRElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == clearAttr)
+ if (name == kClearAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -46,7 +46,7 @@ void HTMLBRElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == clearAttr) {
+ if (name == kClearAttr) {
// If the string is empty, then don't add the clear property.
// <br clear> and <br clear=""> are just treated like <br> by Gecko, Mac IE,
// etc. -dwh
diff --git a/chromium/third_party/blink/renderer/core/html/html_collection.cc b/chromium/third_party/blink/renderer/core/html/html_collection.cc
index 91f3891a194..ca67e176c61 100644
--- a/chromium/third_party/blink/renderer/core/html/html_collection.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_collection.cc
@@ -42,7 +42,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool ShouldTypeOnlyIncludeDirectChildren(CollectionType type) {
switch (type) {
@@ -193,7 +193,8 @@ HTMLCollection::HTMLCollection(ContainerNode& owner_node,
HTMLCollection* HTMLCollection::Create(ContainerNode& base,
CollectionType type) {
- return new HTMLCollection(base, type, kDoesNotOverrideItemAfter);
+ return MakeGarbageCollected<HTMLCollection>(base, type,
+ kDoesNotOverrideItemAfter);
}
HTMLCollection::~HTMLCollection() = default;
@@ -220,22 +221,22 @@ static inline bool IsMatchingHTMLElement(const HTMLCollection& html_collection,
const HTMLElement& element) {
switch (html_collection.GetType()) {
case kDocImages:
- return element.HasTagName(imgTag);
+ return element.HasTagName(kImgTag);
case kDocScripts:
- return element.HasTagName(scriptTag);
+ return element.HasTagName(kScriptTag);
case kDocForms:
- return element.HasTagName(formTag);
+ return element.HasTagName(kFormTag);
case kDocumentNamedItems:
return ToDocumentNameCollection(html_collection).ElementMatches(element);
case kDocumentAllNamedItems:
return ToDocumentAllNameCollection(html_collection)
.ElementMatches(element);
case kTableTBodies:
- return element.HasTagName(tbodyTag);
+ return element.HasTagName(kTbodyTag);
case kTRCells:
- return element.HasTagName(tdTag) || element.HasTagName(thTag);
+ return element.HasTagName(kTdTag) || element.HasTagName(kThTag);
case kTSectionRows:
- return element.HasTagName(trTag);
+ return element.HasTagName(kTrTag);
case kSelectOptions:
return ToHTMLOptionsCollection(html_collection).ElementMatches(element);
case kSelectedOptions:
@@ -245,20 +246,22 @@ static inline bool IsMatchingHTMLElement(const HTMLCollection& html_collection,
return ToHTMLDataListOptionsCollection(html_collection)
.ElementMatches(element);
case kMapAreas:
- return element.HasTagName(areaTag);
+ return element.HasTagName(kAreaTag);
case kDocApplets:
return IsHTMLObjectElement(element) &&
ToHTMLObjectElement(element).ContainsJavaApplet();
case kDocEmbeds:
- return element.HasTagName(embedTag);
+ return element.HasTagName(kEmbedTag);
case kDocLinks:
- return (element.HasTagName(aTag) || element.HasTagName(areaTag)) &&
- element.FastHasAttribute(hrefAttr);
+ return (element.HasTagName(kATag) || element.HasTagName(kAreaTag)) &&
+ element.FastHasAttribute(kHrefAttr);
case kDocAnchors:
- return element.HasTagName(aTag) && element.FastHasAttribute(nameAttr);
+ return element.HasTagName(kATag) && element.FastHasAttribute(kNameAttr);
case kFormControls:
DCHECK(IsHTMLFieldSetElement(html_collection.ownerNode()));
- return IsHTMLObjectElement(element) || IsHTMLFormControlElement(element);
+ return IsHTMLObjectElement(element) ||
+ IsHTMLFormControlElement(element) ||
+ element.IsFormAssociatedCustomElement();
case kClassCollectionType:
case kTagCollectionType:
case kTagCollectionNSType:
@@ -338,13 +341,13 @@ Element* HTMLCollection::VirtualItemAfter(Element*) const {
// although it returns any type of element by id.
static inline bool NameShouldBeVisibleInDocumentAll(
const HTMLElement& element) {
- return element.HasTagName(aTag) || element.HasTagName(buttonTag) ||
- element.HasTagName(embedTag) || element.HasTagName(formTag) ||
- element.HasTagName(frameTag) || element.HasTagName(framesetTag) ||
- element.HasTagName(iframeTag) || element.HasTagName(imgTag) ||
- element.HasTagName(inputTag) || element.HasTagName(mapTag) ||
- element.HasTagName(metaTag) || element.HasTagName(objectTag) ||
- element.HasTagName(selectTag) || element.HasTagName(textareaTag);
+ return element.HasTagName(kATag) || element.HasTagName(kButtonTag) ||
+ element.HasTagName(kEmbedTag) || element.HasTagName(kFormTag) ||
+ element.HasTagName(kFrameTag) || element.HasTagName(kFramesetTag) ||
+ element.HasTagName(kIFrameTag) || element.HasTagName(kImgTag) ||
+ element.HasTagName(kInputTag) || element.HasTagName(kMapTag) ||
+ element.HasTagName(kMetaTag) || element.HasTagName(kObjectTag) ||
+ element.HasTagName(kSelectTag) || element.HasTagName(kTextareaTag);
}
Element* HTMLCollection::TraverseToFirst() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_collection.h b/chromium/third_party/blink/renderer/core/html/html_collection.h
index 986ff159b81..0ba2dfaa56f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/html_collection.h
@@ -77,6 +77,7 @@ class CORE_EXPORT HTMLCollection : public ScriptWrappable,
};
static HTMLCollection* Create(ContainerNode& base, CollectionType);
+ HTMLCollection(ContainerNode& base, CollectionType, ItemAfterOverrideType);
~HTMLCollection() override;
void InvalidateCache(Document* old_document = nullptr) const override;
void InvalidateCacheForAttribute(const QualifiedName*) const;
@@ -114,11 +115,13 @@ class CORE_EXPORT HTMLCollection : public ScriptWrappable,
void Trace(blink::Visitor*) override;
protected:
- HTMLCollection(ContainerNode& base, CollectionType, ItemAfterOverrideType);
-
class NamedItemCache final : public GarbageCollected<NamedItemCache> {
public:
- static NamedItemCache* Create() { return new NamedItemCache; }
+ static NamedItemCache* Create() {
+ return MakeGarbageCollected<NamedItemCache>();
+ }
+
+ NamedItemCache();
const HeapVector<Member<Element>>* GetElementsById(
const AtomicString& id) const {
@@ -147,7 +150,6 @@ class CORE_EXPORT HTMLCollection : public ScriptWrappable,
}
private:
- NamedItemCache();
typedef HeapHashMap<StringImpl*, HeapVector<Member<Element>>>
StringToElementsMap;
static void AddElementToMap(StringToElementsMap& map,
@@ -225,7 +227,8 @@ inline void HTMLCollection::InvalidateCacheForAttribute(
if (!attr_name ||
ShouldInvalidateTypeOnAttributeChange(InvalidationType(), *attr_name))
InvalidateCache();
- else if (*attr_name == HTMLNames::idAttr || *attr_name == HTMLNames::nameAttr)
+ else if (*attr_name == html_names::kIdAttr ||
+ *attr_name == html_names::kNameAttr)
InvalidateIdNameCacheMaps();
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_content_element.cc b/chromium/third_party/blink/renderer/core/html/html_content_element.cc
index 2432601cfe4..00800995151 100644
--- a/chromium/third_party/blink/renderer/core/html/html_content_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_content_element.cc
@@ -36,12 +36,12 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
DEFINE_NODE_FACTORY(HTMLContentElement);
inline HTMLContentElement::HTMLContentElement(Document& document)
- : V0InsertionPoint(contentTag, document),
+ : V0InsertionPoint(kContentTag, document),
should_parse_select_(false),
is_valid_selector_(true) {
UseCounter::Count(document, WebFeature::kHTMLContentElement);
@@ -66,7 +66,7 @@ void HTMLContentElement::ParseSelect() {
void HTMLContentElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == selectAttr) {
+ if (params.name == kSelectAttr) {
if (ShadowRoot* root = ContainingShadowRoot()) {
if (!root->IsV1())
root->V0().WillAffectSelector();
diff --git a/chromium/third_party/blink/renderer/core/html/html_content_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_content_element_test.cc
index 0fbc4ee2528..dca37d4ed5b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_content_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_content_element_test.cc
@@ -30,10 +30,11 @@ TEST_F(HTMLContentElementTest, FallbackRecalcForReattach) {
Element* host = GetDocument().getElementById("host");
ShadowRoot& root = host->CreateV0ShadowRootForTesting();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
- auto* content = GetDocument().CreateRawElement(HTMLNames::contentTag);
- auto* fallback = GetDocument().CreateRawElement(HTMLNames::spanTag);
+ auto* content = GetDocument().CreateRawElement(html_names::kContentTag);
+ auto* fallback = GetDocument().CreateRawElement(html_names::kSpanTag);
content->AppendChild(fallback);
root.AppendChild(content);
diff --git a/chromium/third_party/blink/renderer/core/html/html_data_element.cc b/chromium/third_party/blink/renderer/core/html/html_data_element.cc
index 56732f53b72..67292ced9e0 100644
--- a/chromium/third_party/blink/renderer/core/html/html_data_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_data_element.cc
@@ -9,12 +9,12 @@
namespace blink {
HTMLDataElement::HTMLDataElement(Document& document)
- : HTMLElement(HTMLNames::dataTag, document) {
+ : HTMLElement(html_names::kDataTag, document) {
UseCounter::Count(document, WebFeature::kDataElement);
}
HTMLDataElement* HTMLDataElement::Create(Document& document) {
- return new HTMLDataElement(document);
+ return MakeGarbageCollected<HTMLDataElement>(document);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_data_element.h b/chromium/third_party/blink/renderer/core/html/html_data_element.h
index 889dc0614ac..bf1b1a0a9fa 100644
--- a/chromium/third_party/blink/renderer/core/html/html_data_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_data_element.h
@@ -15,7 +15,6 @@ class CORE_EXPORT HTMLDataElement final : public HTMLElement {
public:
static HTMLDataElement* Create(Document&);
- private:
HTMLDataElement(Document&);
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_details_element.cc b/chromium/third_party/blink/renderer/core/html/html_details_element.cc
index 3873d06703e..1fe24870c6f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_details_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_details_element.cc
@@ -21,7 +21,7 @@
#include "third_party/blink/renderer/core/html/html_details_element.h"
#include "third_party/blink/public/platform/task_type.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
@@ -41,16 +41,17 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLDetailsElement* HTMLDetailsElement::Create(Document& document) {
- HTMLDetailsElement* details = new HTMLDetailsElement(document);
+ HTMLDetailsElement* details =
+ MakeGarbageCollected<HTMLDetailsElement>(document);
details->EnsureUserAgentShadowRoot();
return details;
}
HTMLDetailsElement::HTMLDetailsElement(Document& document)
- : HTMLElement(detailsTag, document), is_open_(false) {
+ : HTMLElement(kDetailsTag, document), is_open_(false) {
UseCounter::Count(document, WebFeature::kDetailsElement);
}
@@ -67,7 +68,7 @@ bool HTMLDetailsElement::IsFirstSummary(const Node& node) {
}
void HTMLDetailsElement::DispatchPendingEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::toggle));
+ DispatchEvent(*Event::Create(event_type_names::kToggle));
}
LayoutObject* HTMLDetailsElement::CreateLayoutObject(
@@ -84,12 +85,12 @@ void HTMLDetailsElement::DidAddUserAgentShadowRoot(ShadowRoot& root) {
HTMLSlotElement* summary_slot =
HTMLSlotElement::CreateUserAgentCustomAssignSlot(GetDocument());
- summary_slot->SetIdAttribute(ShadowElementNames::DetailsSummary());
+ summary_slot->SetIdAttribute(shadow_element_names::DetailsSummary());
summary_slot->AppendChild(default_summary);
root.AppendChild(summary_slot);
HTMLDivElement* content = HTMLDivElement::Create(GetDocument());
- content->SetIdAttribute(ShadowElementNames::DetailsContent());
+ content->SetIdAttribute(shadow_element_names::DetailsContent());
content->AppendChild(
HTMLSlotElement::CreateUserAgentDefaultSlot(GetDocument()));
content->SetInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
@@ -110,7 +111,7 @@ Element* HTMLDetailsElement::FindMainSummary() const {
void HTMLDetailsElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == openAttr) {
+ if (params.name == kOpenAttr) {
bool old_value = is_open_;
is_open_ = !params.new_value.IsNull();
if (is_open_ == old_value)
@@ -123,7 +124,7 @@ void HTMLDetailsElement::ParseAttribute(
WrapPersistent(this)));
Element* content = EnsureUserAgentShadowRoot().getElementById(
- ShadowElementNames::DetailsContent());
+ shadow_element_names::DetailsContent());
DCHECK(content);
if (is_open_)
content->RemoveInlineStyleProperty(CSSPropertyDisplay);
@@ -145,7 +146,7 @@ void HTMLDetailsElement::ParseAttribute(
}
void HTMLDetailsElement::ToggleOpen() {
- setAttribute(openAttr, is_open_ ? g_null_atom : g_empty_atom);
+ setAttribute(kOpenAttr, is_open_ ? g_null_atom : g_empty_atom);
}
bool HTMLDetailsElement::IsInteractiveContent() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_details_element.h b/chromium/third_party/blink/renderer/core/html/html_details_element.h
index 35bf6574652..a3854bd215c 100644
--- a/chromium/third_party/blink/renderer/core/html/html_details_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_details_element.h
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_DETAILS_ELEMENT_H_
#include "third_party/blink/renderer/core/html/html_element.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
namespace blink {
@@ -32,6 +32,8 @@ class HTMLDetailsElement final : public HTMLElement {
public:
static HTMLDetailsElement* Create(Document&);
void ToggleOpen();
+
+ explicit HTMLDetailsElement(Document&);
~HTMLDetailsElement() override;
Element* FindMainSummary() const;
@@ -40,8 +42,6 @@ class HTMLDetailsElement final : public HTMLElement {
static bool IsFirstSummary(const Node&);
private:
- explicit HTMLDetailsElement(Document&);
-
void DispatchPendingEvent();
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/html_dialog_element.cc b/chromium/third_party/blink/renderer/core/html/html_dialog_element.cc
index e3143d836a3..7b1edb61a35 100644
--- a/chromium/third_party/blink/renderer/core/html/html_dialog_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_dialog_element.cc
@@ -38,7 +38,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// This function chooses the focused element when show() or showModal() is
// invoked, as described in their spec.
@@ -82,9 +82,8 @@ static void SetFocusForDialog(HTMLDialogElement* dialog) {
}
static void InertSubtreesChanged(Document& document) {
+ // SetIsInert recurses through subframes to propagate the inert bit.
if (document.GetFrame()) {
- // SetIsInert recurses through subframes to propagate the inert bit as
- // needed.
document.GetFrame()->SetIsInert(document.LocalOwner() &&
document.LocalOwner()->IsInert());
}
@@ -97,7 +96,7 @@ static void InertSubtreesChanged(Document& document) {
}
inline HTMLDialogElement::HTMLDialogElement(Document& document)
- : HTMLElement(dialogTag, document),
+ : HTMLElement(kDialogTag, document),
centering_mode_(kNotCentered),
centered_position_(0),
return_value_("") {
@@ -109,9 +108,9 @@ DEFINE_NODE_FACTORY(HTMLDialogElement)
void HTMLDialogElement::close(const String& return_value) {
// https://html.spec.whatwg.org/#close-the-dialog
- if (!FastHasAttribute(openAttr))
+ if (!FastHasAttribute(kOpenAttr))
return;
- SetBooleanAttribute(openAttr, false);
+ SetBooleanAttribute(kOpenAttr, false);
HTMLDialogElement* active_modal_dialog = GetDocument().ActiveModalDialog();
GetDocument().RemoveFromTopLayer(this);
@@ -132,15 +131,15 @@ void HTMLDialogElement::ForceLayoutForCentering() {
}
void HTMLDialogElement::ScheduleCloseEvent() {
- Event* event = Event::Create(EventTypeNames::close);
+ Event* event = Event::Create(event_type_names::kClose);
event->SetTarget(this);
GetDocument().EnqueueAnimationFrameEvent(event);
}
void HTMLDialogElement::show() {
- if (FastHasAttribute(openAttr))
+ if (FastHasAttribute(kOpenAttr))
return;
- SetBooleanAttribute(openAttr, true);
+ SetBooleanAttribute(kOpenAttr, true);
// The layout must be updated here because setFocusForDialog calls
// Element::isFocusable, which requires an up-to-date layout.
@@ -150,7 +149,7 @@ void HTMLDialogElement::show() {
}
void HTMLDialogElement::showModal(ExceptionState& exception_state) {
- if (FastHasAttribute(openAttr)) {
+ if (FastHasAttribute(kOpenAttr)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"The element already has an 'open' "
"attribute, and therefore cannot be "
@@ -170,14 +169,15 @@ void HTMLDialogElement::showModal(ExceptionState& exception_state) {
}
GetDocument().AddToTopLayer(this);
- SetBooleanAttribute(openAttr, true);
+ SetBooleanAttribute(kOpenAttr, true);
+
+ ForceLayoutForCentering();
// Throw away the AX cache first, so the subsequent steps don't have a chance
// of queuing up AX events on objects that would be invalidated when the cache
// is thrown away.
InertSubtreesChanged(GetDocument());
- ForceLayoutForCentering();
SetFocusForDialog(this);
}
@@ -202,14 +202,14 @@ bool HTMLDialogElement::IsPresentationAttribute(
// FIXME: Workaround for <https://bugs.webkit.org/show_bug.cgi?id=91058>:
// modifying an attribute for which there is an attribute selector in html.css
// sometimes does not trigger a style recalc.
- if (name == openAttr)
+ if (name == kOpenAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
void HTMLDialogElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::cancel) {
+ if (event.type() == event_type_names::kCancel) {
close();
event.SetDefaultHandled();
return;
diff --git a/chromium/third_party/blink/renderer/core/html/html_directory_element.cc b/chromium/third_party/blink/renderer/core/html/html_directory_element.cc
index 54f976c2ad9..35f7b1a69e2 100644
--- a/chromium/third_party/blink/renderer/core/html/html_directory_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_directory_element.cc
@@ -26,10 +26,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLDirectoryElement::HTMLDirectoryElement(Document& document)
- : HTMLElement(dirTag, document) {}
+ : HTMLElement(kDirTag, document) {}
DEFINE_NODE_FACTORY(HTMLDirectoryElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_div_element.cc b/chromium/third_party/blink/renderer/core/html/html_div_element.cc
index ae78e795d27..fbc2f5dd254 100644
--- a/chromium/third_party/blink/renderer/core/html/html_div_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_div_element.cc
@@ -22,16 +22,16 @@
#include "third_party/blink/renderer/core/html/html_div_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLDivElement::HTMLDivElement(Document& document)
- : HTMLElement(divTag, document) {}
+ : HTMLElement(kDivTag, document) {}
DEFINE_NODE_FACTORY(HTMLDivElement)
@@ -39,7 +39,7 @@ void HTMLDivElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
if (DeprecatedEqualIgnoringCase(value, "middle") ||
DeprecatedEqualIgnoringCase(value, "center"))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign,
diff --git a/chromium/third_party/blink/renderer/core/html/html_dlist_element.cc b/chromium/third_party/blink/renderer/core/html/html_dlist_element.cc
index 42ad4663b36..1dc74690e7e 100644
--- a/chromium/third_party/blink/renderer/core/html/html_dlist_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_dlist_element.cc
@@ -26,10 +26,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLDListElement::HTMLDListElement(Document& document)
- : HTMLElement(dlTag, document) {}
+ : HTMLElement(kDlTag, document) {}
DEFINE_NODE_FACTORY(HTMLDListElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_document.cc b/chromium/third_party/blink/renderer/core/html/html_document.cc
index ab5c2a619a3..17c13f90795 100644
--- a/chromium/third_party/blink/renderer/core/html/html_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_document.cc
@@ -61,7 +61,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLDocument::HTMLDocument(const DocumentInit& initializer,
DocumentClassFlags extended_document_classes)
@@ -74,11 +74,11 @@ HTMLDocument::HTMLDocument(const DocumentInit& initializer,
}
HTMLDocument* HTMLDocument::Create(const DocumentInit& initializer) {
- return new HTMLDocument(initializer);
+ return MakeGarbageCollected<HTMLDocument>(initializer);
}
HTMLDocument* HTMLDocument::CreateForTest() {
- return new HTMLDocument(DocumentInit::Create());
+ return MakeGarbageCollected<HTMLDocument>(DocumentInit::Create());
}
HTMLDocument::~HTMLDocument() = default;
@@ -123,18 +123,18 @@ static HashSet<StringImpl*>* CreateHtmlCaseInsensitiveAttributesSet() {
HashSet<StringImpl*>* attr_set = new HashSet<StringImpl*>;
const QualifiedName* case_insensitive_attributes[] = {
- &accept_charsetAttr, &acceptAttr, &alignAttr, &alinkAttr,
- &axisAttr, &bgcolorAttr, &charsetAttr, &checkedAttr,
- &clearAttr, &codetypeAttr, &colorAttr, &compactAttr,
- &declareAttr, &deferAttr, &dirAttr, &directionAttr,
- &disabledAttr, &enctypeAttr, &faceAttr, &frameAttr,
- &hreflangAttr, &http_equivAttr, &langAttr, &languageAttr,
- &linkAttr, &mediaAttr, &methodAttr, &multipleAttr,
- &nohrefAttr, &noresizeAttr, &noshadeAttr, &nowrapAttr,
- &readonlyAttr, &relAttr, &revAttr, &rulesAttr,
- &scopeAttr, &scrollingAttr, &selectedAttr, &shapeAttr,
- &targetAttr, &textAttr, &typeAttr, &valignAttr,
- &valuetypeAttr, &vlinkAttr};
+ &kAcceptCharsetAttr, &kAcceptAttr, &kAlignAttr, &kAlinkAttr,
+ &kAxisAttr, &kBgcolorAttr, &kCharsetAttr, &kCheckedAttr,
+ &kClearAttr, &kCodetypeAttr, &kColorAttr, &kCompactAttr,
+ &kDeclareAttr, &kDeferAttr, &kDirAttr, &kDirectionAttr,
+ &kDisabledAttr, &kEnctypeAttr, &kFaceAttr, &kFrameAttr,
+ &kHreflangAttr, &kHttpEquivAttr, &kLangAttr, &kLanguageAttr,
+ &kLinkAttr, &kMediaAttr, &kMethodAttr, &kMultipleAttr,
+ &kNohrefAttr, &kNoresizeAttr, &kNoshadeAttr, &kNowrapAttr,
+ &kReadonlyAttr, &kRelAttr, &kRevAttr, &kRulesAttr,
+ &kScopeAttr, &kScrollingAttr, &kSelectedAttr, &kShapeAttr,
+ &kTargetAttr, &kTextAttr, &kTypeAttr, &kValignAttr,
+ &kValuetypeAttr, &kVlinkAttr};
attr_set->ReserveCapacityForSize(arraysize(case_insensitive_attributes));
for (const QualifiedName* attr : case_insensitive_attributes)
diff --git a/chromium/third_party/blink/renderer/core/html/html_document.h b/chromium/third_party/blink/renderer/core/html/html_document.h
index 5db2931a7a5..c1ef79668e4 100644
--- a/chromium/third_party/blink/renderer/core/html/html_document.h
+++ b/chromium/third_party/blink/renderer/core/html/html_document.h
@@ -35,6 +35,10 @@ class CORE_EXPORT HTMLDocument : public Document {
public:
static HTMLDocument* Create(const DocumentInit& initializer);
static HTMLDocument* CreateForTest();
+
+ HTMLDocument(
+ const DocumentInit&,
+ DocumentClassFlags extended_document_classes = kDefaultDocumentClass);
~HTMLDocument() override;
void AddNamedItem(const AtomicString& name);
@@ -45,11 +49,6 @@ class CORE_EXPORT HTMLDocument : public Document {
Document* CloneDocumentWithoutChildren() const final;
- protected:
- HTMLDocument(
- const DocumentInit&,
- DocumentClassFlags extended_document_classes = kDefaultDocumentClass);
-
private:
HashCountedSet<AtomicString> named_item_counts_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_element.cc b/chromium/third_party/blink/renderer/core/html/html_element.cc
index 6f20bdf4744..0fc74ac10bb 100644
--- a/chromium/third_party/blink/renderer/core/html/html_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_element.cc
@@ -27,13 +27,16 @@
#include "base/stl_util.h"
#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_treat_null_as_empty_string_or_trusted_script.h"
#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/css_markup.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
+#include "third_party/blink/renderer/core/dom/element_rare_data.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
@@ -49,6 +52,9 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/html/custom/custom_element.h"
+#include "third_party/blink/renderer/core/html/custom/custom_element_registry.h"
+#include "third_party/blink/renderer/core/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/html_br_element.h"
@@ -64,6 +70,7 @@
#include "third_party/blink/renderer/core/mathml_names.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
+#include "third_party/blink/renderer/core/trustedtypes/trusted_script.h"
#include "third_party/blink/renderer/core/xml_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/language.h"
@@ -76,7 +83,7 @@
namespace blink {
using namespace cssvalue;
-using namespace HTMLNames;
+using namespace html_names;
using AttributeChangedFunction =
void (HTMLElement::*)(const Element::AttributeModificationParams& params);
@@ -115,7 +122,8 @@ bool IsEditable(const Node& node) {
return true;
if (IsSVGSVGElement(node))
return true;
- if (node.IsElementNode() && ToElement(node).HasTagName(MathMLNames::mathTag))
+ if (node.IsElementNode() &&
+ ToElement(node).HasTagName(mathml_names::kMathTag))
return true;
return !node.IsElementNode() && node.parentNode()->IsHTMLElement();
}
@@ -152,18 +160,19 @@ String HTMLElement::nodeName() const {
bool HTMLElement::ShouldSerializeEndTag() const {
// See https://www.w3.org/TR/DOM-Parsing/
- if (HasTagName(areaTag) || HasTagName(baseTag) || HasTagName(basefontTag) ||
- HasTagName(bgsoundTag) || HasTagName(brTag) || HasTagName(colTag) ||
- HasTagName(embedTag) || HasTagName(frameTag) || HasTagName(hrTag) ||
- HasTagName(imgTag) || HasTagName(inputTag) || HasTagName(keygenTag) ||
- HasTagName(linkTag) || HasTagName(metaTag) || HasTagName(paramTag) ||
- HasTagName(sourceTag) || HasTagName(trackTag) || HasTagName(wbrTag))
+ if (HasTagName(kAreaTag) || HasTagName(kBaseTag) ||
+ HasTagName(kBasefontTag) || HasTagName(kBgsoundTag) ||
+ HasTagName(kBrTag) || HasTagName(kColTag) || HasTagName(kEmbedTag) ||
+ HasTagName(kFrameTag) || HasTagName(kHrTag) || HasTagName(kImgTag) ||
+ HasTagName(kInputTag) || HasTagName(kKeygenTag) || HasTagName(kLinkTag) ||
+ HasTagName(kMetaTag) || HasTagName(kParamTag) || HasTagName(kSourceTag) ||
+ HasTagName(kTrackTag) || HasTagName(kWbrTag))
return false;
return true;
}
static inline CSSValueID UnicodeBidiAttributeForDirAuto(HTMLElement* element) {
- if (element->HasTagName(preTag) || element->HasTagName(textareaTag))
+ if (element->HasTagName(kPreTag) || element->HasTagName(kTextareaTag))
return CSSValueWebkitPlaintext;
// FIXME: For bdo element, dir="auto" should result in "bidi-override isolate"
// but we don't support having multiple values in unicode-bidi yet.
@@ -175,7 +184,7 @@ unsigned HTMLElement::ParseBorderWidthAttribute(
const AtomicString& value) const {
unsigned border_width = 0;
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, border_width)) {
- if (HasTagName(tableTag) && !value.IsNull())
+ if (HasTagName(kTableTag) && !value.IsNull())
return 1;
}
return border_width;
@@ -230,9 +239,10 @@ void HTMLElement::MapLanguageAttributeToLocale(
}
bool HTMLElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr ||
- name == langAttr || name.Matches(XMLNames::langAttr) ||
- name == draggableAttr || name == dirAttr)
+ if (name == kAlignAttr || name == kContenteditableAttr ||
+ name == kHiddenAttr || name == kLangAttr ||
+ name.Matches(xml_names::kLangAttr) || name == kDraggableAttr ||
+ name == kDirAttr)
return true;
return Element::IsPresentationAttribute(name);
}
@@ -247,14 +257,14 @@ void HTMLElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
if (DeprecatedEqualIgnoringCase(value, "middle"))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign,
CSSValueCenter);
else
AddPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign,
value);
- } else if (name == contenteditableAttr) {
+ } else if (name == kContenteditableAttr) {
if (value.IsEmpty() || DeprecatedEqualIgnoringCase(value, "true")) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyWebkitUserModify, CSSValueReadWrite);
@@ -263,7 +273,7 @@ void HTMLElement::CollectStyleForPresentationAttribute(
AddPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak,
CSSValueAfterWhiteSpace);
UseCounter::Count(GetDocument(), WebFeature::kContentEditableTrue);
- if (HasTagName(htmlTag)) {
+ if (HasTagName(kHTMLTag)) {
UseCounter::Count(GetDocument(),
WebFeature::kContentEditableTrueOnHTML);
}
@@ -280,10 +290,10 @@ void HTMLElement::CollectStyleForPresentationAttribute(
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyWebkitUserModify, CSSValueReadOnly);
}
- } else if (name == hiddenAttr) {
+ } else if (name == kHiddenAttr) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyDisplay,
CSSValueNone);
- } else if (name == draggableAttr) {
+ } else if (name == kDraggableAttr) {
UseCounter::Count(GetDocument(), WebFeature::kDraggableAttribute);
if (DeprecatedEqualIgnoringCase(value, "true")) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag,
@@ -294,7 +304,7 @@ void HTMLElement::CollectStyleForPresentationAttribute(
AddPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag,
CSSValueNone);
}
- } else if (name == dirAttr) {
+ } else if (name == kDirAttr) {
if (DeprecatedEqualIgnoringCase(value, "auto")) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyUnicodeBidi, UnicodeBidiAttributeForDirAuto(this));
@@ -305,15 +315,16 @@ void HTMLElement::CollectStyleForPresentationAttribute(
else if (IsHTMLBodyElement(*this))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyDirection,
"ltr");
- if (!HasTagName(bdiTag) && !HasTagName(bdoTag) && !HasTagName(outputTag))
+ if (!HasTagName(kBdiTag) && !HasTagName(kBdoTag) &&
+ !HasTagName(kOutputTag))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi,
CSSValueIsolate);
}
- } else if (name.Matches(XMLNames::langAttr)) {
+ } else if (name.Matches(xml_names::kLangAttr)) {
MapLanguageAttributeToLocale(value, style);
- } else if (name == langAttr) {
+ } else if (name == kLangAttr) {
// xml:lang has a higher priority than lang.
- if (!FastHasAttribute(XMLNames::langAttr))
+ if (!FastHasAttribute(xml_names::kLangAttr))
MapLanguageAttributeToLocale(value, style);
} else {
Element::CollectStyleForPresentationAttribute(name, value, style);
@@ -325,215 +336,231 @@ AttributeTriggers* HTMLElement::TriggersForAttributeName(
const QualifiedName& attr_name) {
const AtomicString& kNoEvent = g_null_atom;
static AttributeTriggers attribute_triggers[] = {
- {dirAttr, kNoWebFeature, kNoEvent, &HTMLElement::OnDirAttrChanged},
- {inertAttr, WebFeature::kInertAttribute, kNoEvent,
+ {kDirAttr, kNoWebFeature, kNoEvent, &HTMLElement::OnDirAttrChanged},
+ {kInertAttr, WebFeature::kInertAttribute, kNoEvent,
&HTMLElement::OnInertAttrChanged},
- {langAttr, kNoWebFeature, kNoEvent, &HTMLElement::OnLangAttrChanged},
- {nonceAttr, kNoWebFeature, kNoEvent, &HTMLElement::OnNonceAttrChanged},
- {tabindexAttr, kNoWebFeature, kNoEvent,
+ {kLangAttr, kNoWebFeature, kNoEvent, &HTMLElement::OnLangAttrChanged},
+ {kNonceAttr, kNoWebFeature, kNoEvent, &HTMLElement::OnNonceAttrChanged},
+ {kTabindexAttr, kNoWebFeature, kNoEvent,
&HTMLElement::OnTabIndexAttrChanged},
- {XMLNames::langAttr, kNoWebFeature, kNoEvent,
+ {xml_names::kLangAttr, kNoWebFeature, kNoEvent,
&HTMLElement::OnXMLLangAttrChanged},
- {onabortAttr, kNoWebFeature, EventTypeNames::abort, nullptr},
- {onactivateinvisibleAttr, kNoWebFeature,
- EventTypeNames::activateinvisible, nullptr},
- {onanimationendAttr, kNoWebFeature, EventTypeNames::animationend,
+ {kOnabortAttr, kNoWebFeature, event_type_names::kAbort, nullptr},
+ {kOnactivateinvisibleAttr, kNoWebFeature,
+ event_type_names::kActivateinvisible, nullptr},
+ {kOnanimationendAttr, kNoWebFeature, event_type_names::kAnimationend,
nullptr},
- {onanimationiterationAttr, kNoWebFeature,
- EventTypeNames::animationiteration, nullptr},
- {onanimationstartAttr, kNoWebFeature, EventTypeNames::animationstart,
+ {kOnanimationiterationAttr, kNoWebFeature,
+ event_type_names::kAnimationiteration, nullptr},
+ {kOnanimationstartAttr, kNoWebFeature, event_type_names::kAnimationstart,
nullptr},
- {onauxclickAttr, kNoWebFeature, EventTypeNames::auxclick, nullptr},
- {onbeforecopyAttr, kNoWebFeature, EventTypeNames::beforecopy, nullptr},
- {onbeforecutAttr, kNoWebFeature, EventTypeNames::beforecut, nullptr},
- {onbeforepasteAttr, kNoWebFeature, EventTypeNames::beforepaste, nullptr},
- {onblurAttr, kNoWebFeature, EventTypeNames::blur, nullptr},
- {oncancelAttr, kNoWebFeature, EventTypeNames::cancel, nullptr},
- {oncanplayAttr, kNoWebFeature, EventTypeNames::canplay, nullptr},
- {oncanplaythroughAttr, kNoWebFeature, EventTypeNames::canplaythrough,
+ {kOnauxclickAttr, kNoWebFeature, event_type_names::kAuxclick, nullptr},
+ {kOnbeforecopyAttr, kNoWebFeature, event_type_names::kBeforecopy,
nullptr},
- {onchangeAttr, kNoWebFeature, EventTypeNames::change, nullptr},
- {onclickAttr, kNoWebFeature, EventTypeNames::click, nullptr},
- {oncloseAttr, kNoWebFeature, EventTypeNames::close, nullptr},
- {oncontextmenuAttr, kNoWebFeature, EventTypeNames::contextmenu, nullptr},
- {oncopyAttr, kNoWebFeature, EventTypeNames::copy, nullptr},
- {oncuechangeAttr, kNoWebFeature, EventTypeNames::cuechange, nullptr},
- {oncutAttr, kNoWebFeature, EventTypeNames::cut, nullptr},
- {ondblclickAttr, kNoWebFeature, EventTypeNames::dblclick, nullptr},
- {ondragAttr, kNoWebFeature, EventTypeNames::drag, nullptr},
- {ondragendAttr, kNoWebFeature, EventTypeNames::dragend, nullptr},
- {ondragenterAttr, kNoWebFeature, EventTypeNames::dragenter, nullptr},
- {ondragleaveAttr, kNoWebFeature, EventTypeNames::dragleave, nullptr},
- {ondragoverAttr, kNoWebFeature, EventTypeNames::dragover, nullptr},
- {ondragstartAttr, kNoWebFeature, EventTypeNames::dragstart, nullptr},
- {ondropAttr, kNoWebFeature, EventTypeNames::drop, nullptr},
- {ondurationchangeAttr, kNoWebFeature, EventTypeNames::durationchange,
+ {kOnbeforecutAttr, kNoWebFeature, event_type_names::kBeforecut, nullptr},
+ {kOnbeforepasteAttr, kNoWebFeature, event_type_names::kBeforepaste,
nullptr},
- {onemptiedAttr, kNoWebFeature, EventTypeNames::emptied, nullptr},
- {onendedAttr, kNoWebFeature, EventTypeNames::ended, nullptr},
- {onerrorAttr, kNoWebFeature, EventTypeNames::error, nullptr},
- {onfocusAttr, kNoWebFeature, EventTypeNames::focus, nullptr},
- {onfocusinAttr, kNoWebFeature, EventTypeNames::focusin, nullptr},
- {onfocusoutAttr, kNoWebFeature, EventTypeNames::focusout, nullptr},
- {onformdataAttr, kNoWebFeature, EventTypeNames::formdata, nullptr},
- {ongotpointercaptureAttr, kNoWebFeature,
- EventTypeNames::gotpointercapture, nullptr},
- {oninputAttr, kNoWebFeature, EventTypeNames::input, nullptr},
- {oninvalidAttr, kNoWebFeature, EventTypeNames::invalid, nullptr},
- {onkeydownAttr, kNoWebFeature, EventTypeNames::keydown, nullptr},
- {onkeypressAttr, kNoWebFeature, EventTypeNames::keypress, nullptr},
- {onkeyupAttr, kNoWebFeature, EventTypeNames::keyup, nullptr},
- {onloadAttr, kNoWebFeature, EventTypeNames::load, nullptr},
- {onloadeddataAttr, kNoWebFeature, EventTypeNames::loadeddata, nullptr},
- {onloadedmetadataAttr, kNoWebFeature, EventTypeNames::loadedmetadata,
+ {kOnblurAttr, kNoWebFeature, event_type_names::kBlur, nullptr},
+ {kOncancelAttr, kNoWebFeature, event_type_names::kCancel, nullptr},
+ {kOncanplayAttr, kNoWebFeature, event_type_names::kCanplay, nullptr},
+ {kOncanplaythroughAttr, kNoWebFeature, event_type_names::kCanplaythrough,
nullptr},
- {onloadstartAttr, kNoWebFeature, EventTypeNames::loadstart, nullptr},
- {onlostpointercaptureAttr, kNoWebFeature,
- EventTypeNames::lostpointercapture, nullptr},
- {onmousedownAttr, kNoWebFeature, EventTypeNames::mousedown, nullptr},
- {onmouseenterAttr, kNoWebFeature, EventTypeNames::mouseenter, nullptr},
- {onmouseleaveAttr, kNoWebFeature, EventTypeNames::mouseleave, nullptr},
- {onmousemoveAttr, kNoWebFeature, EventTypeNames::mousemove, nullptr},
- {onmouseoutAttr, kNoWebFeature, EventTypeNames::mouseout, nullptr},
- {onmouseoverAttr, kNoWebFeature, EventTypeNames::mouseover, nullptr},
- {onmouseupAttr, kNoWebFeature, EventTypeNames::mouseup, nullptr},
- {onmousewheelAttr, kNoWebFeature, EventTypeNames::mousewheel, nullptr},
- {onpasteAttr, kNoWebFeature, EventTypeNames::paste, nullptr},
- {onpauseAttr, kNoWebFeature, EventTypeNames::pause, nullptr},
- {onplayAttr, kNoWebFeature, EventTypeNames::play, nullptr},
- {onplayingAttr, kNoWebFeature, EventTypeNames::playing, nullptr},
- {onpointercancelAttr, kNoWebFeature, EventTypeNames::pointercancel,
+ {kOnchangeAttr, kNoWebFeature, event_type_names::kChange, nullptr},
+ {kOnclickAttr, kNoWebFeature, event_type_names::kClick, nullptr},
+ {kOncloseAttr, kNoWebFeature, event_type_names::kClose, nullptr},
+ {kOncontextmenuAttr, kNoWebFeature, event_type_names::kContextmenu,
nullptr},
- {onpointerdownAttr, kNoWebFeature, EventTypeNames::pointerdown, nullptr},
- {onpointerenterAttr, kNoWebFeature, EventTypeNames::pointerenter,
+ {kOncopyAttr, kNoWebFeature, event_type_names::kCopy, nullptr},
+ {kOncuechangeAttr, kNoWebFeature, event_type_names::kCuechange, nullptr},
+ {kOncutAttr, kNoWebFeature, event_type_names::kCut, nullptr},
+ {kOndblclickAttr, kNoWebFeature, event_type_names::kDblclick, nullptr},
+ {kOndragAttr, kNoWebFeature, event_type_names::kDrag, nullptr},
+ {kOndragendAttr, kNoWebFeature, event_type_names::kDragend, nullptr},
+ {kOndragenterAttr, kNoWebFeature, event_type_names::kDragenter, nullptr},
+ {kOndragleaveAttr, kNoWebFeature, event_type_names::kDragleave, nullptr},
+ {kOndragoverAttr, kNoWebFeature, event_type_names::kDragover, nullptr},
+ {kOndragstartAttr, kNoWebFeature, event_type_names::kDragstart, nullptr},
+ {kOndropAttr, kNoWebFeature, event_type_names::kDrop, nullptr},
+ {kOndurationchangeAttr, kNoWebFeature, event_type_names::kDurationchange,
nullptr},
- {onpointerleaveAttr, kNoWebFeature, EventTypeNames::pointerleave,
+ {kOnemptiedAttr, kNoWebFeature, event_type_names::kEmptied, nullptr},
+ {kOnendedAttr, kNoWebFeature, event_type_names::kEnded, nullptr},
+ {kOnerrorAttr, kNoWebFeature, event_type_names::kError, nullptr},
+ {kOnfocusAttr, kNoWebFeature, event_type_names::kFocus, nullptr},
+ {kOnfocusinAttr, kNoWebFeature, event_type_names::kFocusin, nullptr},
+ {kOnfocusoutAttr, kNoWebFeature, event_type_names::kFocusout, nullptr},
+ {kOnformdataAttr, kNoWebFeature, event_type_names::kFormdata, nullptr},
+ {kOngotpointercaptureAttr, kNoWebFeature,
+ event_type_names::kGotpointercapture, nullptr},
+ {kOninputAttr, kNoWebFeature, event_type_names::kInput, nullptr},
+ {kOninvalidAttr, kNoWebFeature, event_type_names::kInvalid, nullptr},
+ {kOnkeydownAttr, kNoWebFeature, event_type_names::kKeydown, nullptr},
+ {kOnkeypressAttr, kNoWebFeature, event_type_names::kKeypress, nullptr},
+ {kOnkeyupAttr, kNoWebFeature, event_type_names::kKeyup, nullptr},
+ {kOnloadAttr, kNoWebFeature, event_type_names::kLoad, nullptr},
+ {kOnloadeddataAttr, kNoWebFeature, event_type_names::kLoadeddata,
nullptr},
- {onpointermoveAttr, kNoWebFeature, EventTypeNames::pointermove, nullptr},
- {onpointeroutAttr, kNoWebFeature, EventTypeNames::pointerout, nullptr},
- {onpointeroverAttr, kNoWebFeature, EventTypeNames::pointerover, nullptr},
- {onpointerrawmoveAttr, kNoWebFeature, EventTypeNames::pointerrawmove,
+ {kOnloadedmetadataAttr, kNoWebFeature, event_type_names::kLoadedmetadata,
nullptr},
- {onpointerupAttr, kNoWebFeature, EventTypeNames::pointerup, nullptr},
- {onprogressAttr, kNoWebFeature, EventTypeNames::progress, nullptr},
- {onratechangeAttr, kNoWebFeature, EventTypeNames::ratechange, nullptr},
- {onresetAttr, kNoWebFeature, EventTypeNames::reset, nullptr},
- {onresizeAttr, kNoWebFeature, EventTypeNames::resize, nullptr},
- {onscrollAttr, kNoWebFeature, EventTypeNames::scroll, nullptr},
- {onseekedAttr, kNoWebFeature, EventTypeNames::seeked, nullptr},
- {onseekingAttr, kNoWebFeature, EventTypeNames::seeking, nullptr},
- {onselectAttr, kNoWebFeature, EventTypeNames::select, nullptr},
- {onselectstartAttr, kNoWebFeature, EventTypeNames::selectstart, nullptr},
- {onstalledAttr, kNoWebFeature, EventTypeNames::stalled, nullptr},
- {onsubmitAttr, kNoWebFeature, EventTypeNames::submit, nullptr},
- {onsuspendAttr, kNoWebFeature, EventTypeNames::suspend, nullptr},
- {ontimeupdateAttr, kNoWebFeature, EventTypeNames::timeupdate, nullptr},
- {ontoggleAttr, kNoWebFeature, EventTypeNames::toggle, nullptr},
- {ontouchcancelAttr, kNoWebFeature, EventTypeNames::touchcancel, nullptr},
- {ontouchendAttr, kNoWebFeature, EventTypeNames::touchend, nullptr},
- {ontouchmoveAttr, kNoWebFeature, EventTypeNames::touchmove, nullptr},
- {ontouchstartAttr, kNoWebFeature, EventTypeNames::touchstart, nullptr},
- {ontransitionendAttr, kNoWebFeature, EventTypeNames::webkitTransitionEnd,
+ {kOnloadstartAttr, kNoWebFeature, event_type_names::kLoadstart, nullptr},
+ {kOnlostpointercaptureAttr, kNoWebFeature,
+ event_type_names::kLostpointercapture, nullptr},
+ {kOnmousedownAttr, kNoWebFeature, event_type_names::kMousedown, nullptr},
+ {kOnmouseenterAttr, kNoWebFeature, event_type_names::kMouseenter,
nullptr},
- {onvolumechangeAttr, kNoWebFeature, EventTypeNames::volumechange,
+ {kOnmouseleaveAttr, kNoWebFeature, event_type_names::kMouseleave,
nullptr},
- {onwaitingAttr, kNoWebFeature, EventTypeNames::waiting, nullptr},
- {onwebkitanimationendAttr, kNoWebFeature,
- EventTypeNames::webkitAnimationEnd, nullptr},
- {onwebkitanimationiterationAttr, kNoWebFeature,
- EventTypeNames::webkitAnimationIteration, nullptr},
- {onwebkitanimationstartAttr, kNoWebFeature,
- EventTypeNames::webkitAnimationStart, nullptr},
- {onwebkitfullscreenchangeAttr, kNoWebFeature,
- EventTypeNames::webkitfullscreenchange, nullptr},
- {onwebkitfullscreenerrorAttr, kNoWebFeature,
- EventTypeNames::webkitfullscreenerror, nullptr},
- {onwebkittransitionendAttr, kNoWebFeature,
- EventTypeNames::webkitTransitionEnd, nullptr},
- {onwheelAttr, kNoWebFeature, EventTypeNames::wheel, nullptr},
-
- {aria_activedescendantAttr, WebFeature::kARIAActiveDescendantAttribute,
+ {kOnmousemoveAttr, kNoWebFeature, event_type_names::kMousemove, nullptr},
+ {kOnmouseoutAttr, kNoWebFeature, event_type_names::kMouseout, nullptr},
+ {kOnmouseoverAttr, kNoWebFeature, event_type_names::kMouseover, nullptr},
+ {kOnmouseupAttr, kNoWebFeature, event_type_names::kMouseup, nullptr},
+ {kOnmousewheelAttr, kNoWebFeature, event_type_names::kMousewheel,
+ nullptr},
+ {kOnpasteAttr, kNoWebFeature, event_type_names::kPaste, nullptr},
+ {kOnpauseAttr, kNoWebFeature, event_type_names::kPause, nullptr},
+ {kOnplayAttr, kNoWebFeature, event_type_names::kPlay, nullptr},
+ {kOnplayingAttr, kNoWebFeature, event_type_names::kPlaying, nullptr},
+ {kOnpointercancelAttr, kNoWebFeature, event_type_names::kPointercancel,
+ nullptr},
+ {kOnpointerdownAttr, kNoWebFeature, event_type_names::kPointerdown,
+ nullptr},
+ {kOnpointerenterAttr, kNoWebFeature, event_type_names::kPointerenter,
+ nullptr},
+ {kOnpointerleaveAttr, kNoWebFeature, event_type_names::kPointerleave,
+ nullptr},
+ {kOnpointermoveAttr, kNoWebFeature, event_type_names::kPointermove,
+ nullptr},
+ {kOnpointeroutAttr, kNoWebFeature, event_type_names::kPointerout,
+ nullptr},
+ {kOnpointeroverAttr, kNoWebFeature, event_type_names::kPointerover,
+ nullptr},
+ {kOnpointerrawmoveAttr, kNoWebFeature, event_type_names::kPointerrawmove,
+ nullptr},
+ {kOnpointerupAttr, kNoWebFeature, event_type_names::kPointerup, nullptr},
+ {kOnprogressAttr, kNoWebFeature, event_type_names::kProgress, nullptr},
+ {kOnratechangeAttr, kNoWebFeature, event_type_names::kRatechange,
+ nullptr},
+ {kOnresetAttr, kNoWebFeature, event_type_names::kReset, nullptr},
+ {kOnresizeAttr, kNoWebFeature, event_type_names::kResize, nullptr},
+ {kOnscrollAttr, kNoWebFeature, event_type_names::kScroll, nullptr},
+ {kOnseekedAttr, kNoWebFeature, event_type_names::kSeeked, nullptr},
+ {kOnseekingAttr, kNoWebFeature, event_type_names::kSeeking, nullptr},
+ {kOnselectAttr, kNoWebFeature, event_type_names::kSelect, nullptr},
+ {kOnselectstartAttr, kNoWebFeature, event_type_names::kSelectstart,
+ nullptr},
+ {kOnstalledAttr, kNoWebFeature, event_type_names::kStalled, nullptr},
+ {kOnsubmitAttr, kNoWebFeature, event_type_names::kSubmit, nullptr},
+ {kOnsuspendAttr, kNoWebFeature, event_type_names::kSuspend, nullptr},
+ {kOntimeupdateAttr, kNoWebFeature, event_type_names::kTimeupdate,
+ nullptr},
+ {kOntoggleAttr, kNoWebFeature, event_type_names::kToggle, nullptr},
+ {kOntouchcancelAttr, kNoWebFeature, event_type_names::kTouchcancel,
+ nullptr},
+ {kOntouchendAttr, kNoWebFeature, event_type_names::kTouchend, nullptr},
+ {kOntouchmoveAttr, kNoWebFeature, event_type_names::kTouchmove, nullptr},
+ {kOntouchstartAttr, kNoWebFeature, event_type_names::kTouchstart,
+ nullptr},
+ {kOntransitionendAttr, kNoWebFeature,
+ event_type_names::kWebkitTransitionEnd, nullptr},
+ {kOnvolumechangeAttr, kNoWebFeature, event_type_names::kVolumechange,
+ nullptr},
+ {kOnwaitingAttr, kNoWebFeature, event_type_names::kWaiting, nullptr},
+ {kOnwebkitanimationendAttr, kNoWebFeature,
+ event_type_names::kWebkitAnimationEnd, nullptr},
+ {kOnwebkitanimationiterationAttr, kNoWebFeature,
+ event_type_names::kWebkitAnimationIteration, nullptr},
+ {kOnwebkitanimationstartAttr, kNoWebFeature,
+ event_type_names::kWebkitAnimationStart, nullptr},
+ {kOnwebkitfullscreenchangeAttr, kNoWebFeature,
+ event_type_names::kWebkitfullscreenchange, nullptr},
+ {kOnwebkitfullscreenerrorAttr, kNoWebFeature,
+ event_type_names::kWebkitfullscreenerror, nullptr},
+ {kOnwebkittransitionendAttr, kNoWebFeature,
+ event_type_names::kWebkitTransitionEnd, nullptr},
+ {kOnwheelAttr, kNoWebFeature, event_type_names::kWheel, nullptr},
+
+ {kAriaActivedescendantAttr, WebFeature::kARIAActiveDescendantAttribute,
kNoEvent, nullptr},
- {aria_atomicAttr, WebFeature::kARIAAtomicAttribute, kNoEvent, nullptr},
- {aria_autocompleteAttr, WebFeature::kARIAAutocompleteAttribute, kNoEvent,
+ {kAriaAtomicAttr, WebFeature::kARIAAtomicAttribute, kNoEvent, nullptr},
+ {kAriaAutocompleteAttr, WebFeature::kARIAAutocompleteAttribute, kNoEvent,
nullptr},
- {aria_busyAttr, WebFeature::kARIABusyAttribute, kNoEvent, nullptr},
- {aria_checkedAttr, WebFeature::kARIACheckedAttribute, kNoEvent, nullptr},
- {aria_colcountAttr, WebFeature::kARIAColCountAttribute, kNoEvent,
+ {kAriaBusyAttr, WebFeature::kARIABusyAttribute, kNoEvent, nullptr},
+ {kAriaCheckedAttr, WebFeature::kARIACheckedAttribute, kNoEvent, nullptr},
+ {kAriaColcountAttr, WebFeature::kARIAColCountAttribute, kNoEvent,
nullptr},
- {aria_colindexAttr, WebFeature::kARIAColIndexAttribute, kNoEvent,
+ {kAriaColindexAttr, WebFeature::kARIAColIndexAttribute, kNoEvent,
nullptr},
- {aria_colspanAttr, WebFeature::kARIAColSpanAttribute, kNoEvent, nullptr},
- {aria_controlsAttr, WebFeature::kARIAControlsAttribute, kNoEvent,
+ {kAriaColspanAttr, WebFeature::kARIAColSpanAttribute, kNoEvent, nullptr},
+ {kAriaControlsAttr, WebFeature::kARIAControlsAttribute, kNoEvent,
nullptr},
- {aria_currentAttr, WebFeature::kARIACurrentAttribute, kNoEvent, nullptr},
- {aria_describedbyAttr, WebFeature::kARIADescribedByAttribute, kNoEvent,
+ {kAriaCurrentAttr, WebFeature::kARIACurrentAttribute, kNoEvent, nullptr},
+ {kAriaDescribedbyAttr, WebFeature::kARIADescribedByAttribute, kNoEvent,
nullptr},
- {aria_detailsAttr, WebFeature::kARIADetailsAttribute, kNoEvent, nullptr},
- {aria_disabledAttr, WebFeature::kARIADisabledAttribute, kNoEvent,
+ {kAriaDetailsAttr, WebFeature::kARIADetailsAttribute, kNoEvent, nullptr},
+ {kAriaDisabledAttr, WebFeature::kARIADisabledAttribute, kNoEvent,
nullptr},
- {aria_dropeffectAttr, WebFeature::kARIADropEffectAttribute, kNoEvent,
+ {kAriaDropeffectAttr, WebFeature::kARIADropEffectAttribute, kNoEvent,
nullptr},
- {aria_errormessageAttr, WebFeature::kARIAErrorMessageAttribute, kNoEvent,
+ {kAriaErrormessageAttr, WebFeature::kARIAErrorMessageAttribute, kNoEvent,
nullptr},
- {aria_expandedAttr, WebFeature::kARIAExpandedAttribute, kNoEvent,
+ {kAriaExpandedAttr, WebFeature::kARIAExpandedAttribute, kNoEvent,
nullptr},
- {aria_flowtoAttr, WebFeature::kARIAFlowToAttribute, kNoEvent, nullptr},
- {aria_grabbedAttr, WebFeature::kARIAGrabbedAttribute, kNoEvent, nullptr},
- {aria_haspopupAttr, WebFeature::kARIAHasPopupAttribute, kNoEvent,
+ {kAriaFlowtoAttr, WebFeature::kARIAFlowToAttribute, kNoEvent, nullptr},
+ {kAriaGrabbedAttr, WebFeature::kARIAGrabbedAttribute, kNoEvent, nullptr},
+ {kAriaHaspopupAttr, WebFeature::kARIAHasPopupAttribute, kNoEvent,
nullptr},
- {aria_helpAttr, WebFeature::kARIAHelpAttribute, kNoEvent, nullptr},
- {aria_hiddenAttr, WebFeature::kARIAHiddenAttribute, kNoEvent, nullptr},
- {aria_invalidAttr, WebFeature::kARIAInvalidAttribute, kNoEvent, nullptr},
- {aria_keyshortcutsAttr, WebFeature::kARIAKeyShortcutsAttribute, kNoEvent,
+ {kAriaHelpAttr, WebFeature::kARIAHelpAttribute, kNoEvent, nullptr},
+ {kAriaHiddenAttr, WebFeature::kARIAHiddenAttribute, kNoEvent, nullptr},
+ {kAriaInvalidAttr, WebFeature::kARIAInvalidAttribute, kNoEvent, nullptr},
+ {kAriaKeyshortcutsAttr, WebFeature::kARIAKeyShortcutsAttribute, kNoEvent,
nullptr},
- {aria_labelAttr, WebFeature::kARIALabelAttribute, kNoEvent, nullptr},
- {aria_labeledbyAttr, WebFeature::kARIALabeledByAttribute, kNoEvent,
+ {kAriaLabelAttr, WebFeature::kARIALabelAttribute, kNoEvent, nullptr},
+ {kAriaLabeledbyAttr, WebFeature::kARIALabeledByAttribute, kNoEvent,
nullptr},
- {aria_labelledbyAttr, WebFeature::kARIALabelledByAttribute, kNoEvent,
+ {kAriaLabelledbyAttr, WebFeature::kARIALabelledByAttribute, kNoEvent,
nullptr},
- {aria_levelAttr, WebFeature::kARIALevelAttribute, kNoEvent, nullptr},
- {aria_liveAttr, WebFeature::kARIALiveAttribute, kNoEvent, nullptr},
- {aria_modalAttr, WebFeature::kARIAModalAttribute, kNoEvent, nullptr},
- {aria_multilineAttr, WebFeature::kARIAMultilineAttribute, kNoEvent,
+ {kAriaLevelAttr, WebFeature::kARIALevelAttribute, kNoEvent, nullptr},
+ {kAriaLiveAttr, WebFeature::kARIALiveAttribute, kNoEvent, nullptr},
+ {kAriaModalAttr, WebFeature::kARIAModalAttribute, kNoEvent, nullptr},
+ {kAriaMultilineAttr, WebFeature::kARIAMultilineAttribute, kNoEvent,
nullptr},
- {aria_multiselectableAttr, WebFeature::kARIAMultiselectableAttribute,
+ {kAriaMultiselectableAttr, WebFeature::kARIAMultiselectableAttribute,
kNoEvent, nullptr},
- {aria_orientationAttr, WebFeature::kARIAOrientationAttribute, kNoEvent,
+ {kAriaOrientationAttr, WebFeature::kARIAOrientationAttribute, kNoEvent,
nullptr},
- {aria_ownsAttr, WebFeature::kARIAOwnsAttribute, kNoEvent, nullptr},
- {aria_placeholderAttr, WebFeature::kARIAPlaceholderAttribute, kNoEvent,
+ {kAriaOwnsAttr, WebFeature::kARIAOwnsAttribute, kNoEvent, nullptr},
+ {kAriaPlaceholderAttr, WebFeature::kARIAPlaceholderAttribute, kNoEvent,
nullptr},
- {aria_posinsetAttr, WebFeature::kARIAPosInSetAttribute, kNoEvent,
+ {kAriaPosinsetAttr, WebFeature::kARIAPosInSetAttribute, kNoEvent,
nullptr},
- {aria_pressedAttr, WebFeature::kARIAPressedAttribute, kNoEvent, nullptr},
- {aria_readonlyAttr, WebFeature::kARIAReadOnlyAttribute, kNoEvent,
+ {kAriaPressedAttr, WebFeature::kARIAPressedAttribute, kNoEvent, nullptr},
+ {kAriaReadonlyAttr, WebFeature::kARIAReadOnlyAttribute, kNoEvent,
nullptr},
- {aria_relevantAttr, WebFeature::kARIARelevantAttribute, kNoEvent,
+ {kAriaRelevantAttr, WebFeature::kARIARelevantAttribute, kNoEvent,
nullptr},
- {aria_requiredAttr, WebFeature::kARIARequiredAttribute, kNoEvent,
+ {kAriaRequiredAttr, WebFeature::kARIARequiredAttribute, kNoEvent,
nullptr},
- {aria_roledescriptionAttr, WebFeature::kARIARoleDescriptionAttribute,
+ {kAriaRoledescriptionAttr, WebFeature::kARIARoleDescriptionAttribute,
kNoEvent, nullptr},
- {aria_rowcountAttr, WebFeature::kARIARowCountAttribute, kNoEvent,
+ {kAriaRowcountAttr, WebFeature::kARIARowCountAttribute, kNoEvent,
nullptr},
- {aria_rowindexAttr, WebFeature::kARIARowIndexAttribute, kNoEvent,
+ {kAriaRowindexAttr, WebFeature::kARIARowIndexAttribute, kNoEvent,
nullptr},
- {aria_rowspanAttr, WebFeature::kARIARowSpanAttribute, kNoEvent, nullptr},
- {aria_selectedAttr, WebFeature::kARIASelectedAttribute, kNoEvent,
+ {kAriaRowspanAttr, WebFeature::kARIARowSpanAttribute, kNoEvent, nullptr},
+ {kAriaSelectedAttr, WebFeature::kARIASelectedAttribute, kNoEvent,
nullptr},
- {aria_setsizeAttr, WebFeature::kARIASetSizeAttribute, kNoEvent, nullptr},
- {aria_sortAttr, WebFeature::kARIASortAttribute, kNoEvent, nullptr},
- {aria_valuemaxAttr, WebFeature::kARIAValueMaxAttribute, kNoEvent,
+ {kAriaSetsizeAttr, WebFeature::kARIASetSizeAttribute, kNoEvent, nullptr},
+ {kAriaSortAttr, WebFeature::kARIASortAttribute, kNoEvent, nullptr},
+ {kAriaValuemaxAttr, WebFeature::kARIAValueMaxAttribute, kNoEvent,
nullptr},
- {aria_valueminAttr, WebFeature::kARIAValueMinAttribute, kNoEvent,
+ {kAriaValueminAttr, WebFeature::kARIAValueMinAttribute, kNoEvent,
nullptr},
- {aria_valuenowAttr, WebFeature::kARIAValueNowAttribute, kNoEvent,
+ {kAriaValuenowAttr, WebFeature::kARIAValueNowAttribute, kNoEvent,
nullptr},
- {aria_valuetextAttr, WebFeature::kARIAValueTextAttribute, kNoEvent,
+ {kAriaValuetextAttr, WebFeature::kARIAValueTextAttribute, kNoEvent,
nullptr},
- {autocapitalizeAttr, WebFeature::kAutocapitalizeAttribute, kNoEvent,
+ {kAutocapitalizeAttr, WebFeature::kAutocapitalizeAttribute, kNoEvent,
nullptr},
};
@@ -566,10 +593,10 @@ void HTMLElement::AttributeChanged(const AttributeModificationParams& params) {
return;
// adjustedFocusedElementInTreeScope() is not trivial. We should check
// attribute names, then call adjustedFocusedElementInTreeScope().
- if (params.name == hiddenAttr && !params.new_value.IsNull()) {
+ if (params.name == kHiddenAttr && !params.new_value.IsNull()) {
if (AdjustedFocusedElementInTreeScope() == this)
blur();
- } else if (params.name == contenteditableAttr) {
+ } else if (params.name == kContenteditableAttr) {
if (GetDocument().GetFrame()) {
GetDocument()
.GetFrame()
@@ -626,28 +653,67 @@ DocumentFragment* HTMLElement::TextToFragment(const String& text,
break;
}
- fragment->AppendChild(
- Text::Create(GetDocument(), text.Substring(start, i - start)),
- exception_state);
- if (exception_state.HadException())
- return nullptr;
-
- if (c == '\r' || c == '\n') {
- fragment->AppendChild(HTMLBRElement::Create(GetDocument()),
- exception_state);
+ if (i > start) {
+ fragment->AppendChild(
+ Text::Create(GetDocument(), text.Substring(start, i - start)),
+ exception_state);
if (exception_state.HadException())
return nullptr;
- // Make sure \r\n doesn't result in two line breaks.
- if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
- i++;
}
+ if (i == length)
+ break;
+
+ fragment->AppendChild(HTMLBRElement::Create(GetDocument()),
+ exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+
+ // Make sure \r\n doesn't result in two line breaks.
+ if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
+ i++;
+
start = i + 1; // Character after line break.
}
return fragment;
}
+void HTMLElement::setInnerText(
+ const StringOrTrustedScript& string_or_trusted_script,
+ ExceptionState& exception_state) {
+ String value;
+ if (string_or_trusted_script.IsString())
+ value = string_or_trusted_script.GetAsString();
+ else if (string_or_trusted_script.IsTrustedScript())
+ value = string_or_trusted_script.GetAsTrustedScript()->toString();
+ setInnerText(value, exception_state);
+}
+
+void HTMLElement::setInnerText(
+ const StringTreatNullAsEmptyStringOrTrustedScript& string_or_trusted_script,
+ ExceptionState& exception_state) {
+ StringOrTrustedScript tmp;
+ if (string_or_trusted_script.IsString())
+ tmp.SetString(string_or_trusted_script.GetAsString());
+ else if (string_or_trusted_script.IsTrustedScript())
+ tmp.SetTrustedScript(string_or_trusted_script.GetAsTrustedScript());
+ setInnerText(tmp, exception_state);
+}
+
+void HTMLElement::innerText(
+ StringTreatNullAsEmptyStringOrTrustedScript& result) {
+ result.SetString(innerText());
+}
+
+void HTMLElement::innerText(StringOrTrustedScript& result) {
+ result.SetString(innerText());
+}
+
+String HTMLElement::innerText() {
+ return Element::innerText();
+}
+
void HTMLElement::setInnerText(const String& text,
ExceptionState& exception_state) {
// FIXME: This doesn't take whitespace collapsing into account at all.
@@ -661,25 +727,6 @@ void HTMLElement::setInnerText(const String& text,
return;
}
- // FIXME: Do we need to be able to detect preserveNewline style even when
- // there's no layoutObject?
- // FIXME: Can the layoutObject be out of date here? Do we need to call
- // updateStyleIfNeeded? For example, for the contents of textarea elements
- // that are display:none?
- LayoutObject* r = GetLayoutObject();
- if (r && r->Style()->PreserveNewline()) {
- if (!text.Contains('\r')) {
- ReplaceChildrenWithText(this, text, exception_state);
- return;
- }
- String text_with_consistent_line_breaks = text;
- text_with_consistent_line_breaks.Replace("\r\n", "\n");
- text_with_consistent_line_breaks.Replace('\r', '\n');
- ReplaceChildrenWithText(this, text_with_consistent_line_breaks,
- exception_state);
- return;
- }
-
// Add text nodes and <br> elements.
DocumentFragment* fragment = TextToFragment(text, exception_state);
if (!exception_state.HadException())
@@ -768,7 +815,7 @@ bool HTMLElement::HasCustomFocusLogic() const {
}
String HTMLElement::contentEditable() const {
- const AtomicString& value = FastGetAttribute(contenteditableAttr);
+ const AtomicString& value = FastGetAttribute(kContenteditableAttr);
if (value.IsNull())
return "inherit";
@@ -785,13 +832,13 @@ String HTMLElement::contentEditable() const {
void HTMLElement::setContentEditable(const String& enabled,
ExceptionState& exception_state) {
if (DeprecatedEqualIgnoringCase(enabled, "true"))
- setAttribute(contenteditableAttr, "true");
+ setAttribute(kContenteditableAttr, "true");
else if (DeprecatedEqualIgnoringCase(enabled, "false"))
- setAttribute(contenteditableAttr, "false");
+ setAttribute(kContenteditableAttr, "false");
else if (DeprecatedEqualIgnoringCase(enabled, "plaintext-only"))
- setAttribute(contenteditableAttr, "plaintext-only");
+ setAttribute(kContenteditableAttr, "plaintext-only");
else if (DeprecatedEqualIgnoringCase(enabled, "inherit"))
- removeAttribute(contenteditableAttr);
+ removeAttribute(kContenteditableAttr);
else
exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
"The value provided ('" + enabled +
@@ -806,7 +853,7 @@ const AtomicString& HTMLElement::autocapitalize() const {
DEFINE_STATIC_LOCAL(const AtomicString, kWords, ("words"));
DEFINE_STATIC_LOCAL(const AtomicString, kSentences, ("sentences"));
- const AtomicString& value = FastGetAttribute(autocapitalizeAttr);
+ const AtomicString& value = FastGetAttribute(kAutocapitalizeAttr);
if (value.IsEmpty())
return g_empty_atom;
@@ -822,7 +869,7 @@ const AtomicString& HTMLElement::autocapitalize() const {
}
void HTMLElement::setAutocapitalize(const AtomicString& value) {
- setAttribute(autocapitalizeAttr, value);
+ setAttribute(kAutocapitalizeAttr, value);
}
bool HTMLElement::isContentEditableForBinding() const {
@@ -830,11 +877,11 @@ bool HTMLElement::isContentEditableForBinding() const {
}
bool HTMLElement::draggable() const {
- return DeprecatedEqualIgnoringCase(getAttribute(draggableAttr), "true");
+ return DeprecatedEqualIgnoringCase(getAttribute(kDraggableAttr), "true");
}
void HTMLElement::setDraggable(bool value) {
- setAttribute(draggableAttr, value ? "true" : "false");
+ setAttribute(kDraggableAttr, value ? "true" : "false");
}
bool HTMLElement::spellcheck() const {
@@ -842,7 +889,7 @@ bool HTMLElement::spellcheck() const {
}
void HTMLElement::setSpellcheck(bool enable) {
- setAttribute(spellcheckAttr, enable ? "true" : "false");
+ setAttribute(kSpellcheckAttr, enable ? "true" : "false");
}
void HTMLElement::click() {
@@ -856,17 +903,20 @@ void HTMLElement::AccessKeyAction(bool send_mouse_events) {
}
String HTMLElement::title() const {
- return FastGetAttribute(titleAttr);
+ return FastGetAttribute(kTitleAttr);
}
int HTMLElement::tabIndex() const {
- if (SupportsFocus())
+ if (SupportsFocus() ||
+ (RuntimeEnabledFeatures::KeyboardFocusableScrollersEnabled() &&
+ IsScrollableNode(this))) {
return Element::tabIndex();
+ }
return -1;
}
TranslateAttributeMode HTMLElement::GetTranslateAttributeMode() const {
- const AtomicString& value = getAttribute(translateAttr);
+ const AtomicString& value = getAttribute(kTranslateAttr);
if (value == g_null_atom)
return kTranslateAttributeInherit;
@@ -894,7 +944,7 @@ bool HTMLElement::translate() const {
}
void HTMLElement::setTranslate(bool enable) {
- setAttribute(translateAttr, enable ? "yes" : "no");
+ setAttribute(kTranslateAttr, enable ? "yes" : "no");
}
// Returns the conforming 'dir' value associated with the state the attribute is
@@ -918,11 +968,11 @@ static inline const AtomicString& ToValidDirValue(const AtomicString& value) {
}
const AtomicString& HTMLElement::dir() {
- return ToValidDirValue(FastGetAttribute(dirAttr));
+ return ToValidDirValue(FastGetAttribute(kDirAttr));
}
void HTMLElement::setDir(const AtomicString& value) {
- setAttribute(dirAttr, value);
+ setAttribute(kDirAttr, value);
}
HTMLFormElement* HTMLElement::FindFormAncestor() const {
@@ -931,7 +981,7 @@ HTMLFormElement* HTMLElement::FindFormAncestor() const {
static inline bool ElementAffectsDirectionality(const Node* node) {
return node->IsHTMLElement() && (IsHTMLBDIElement(ToHTMLElement(*node)) ||
- ToHTMLElement(*node).hasAttribute(dirAttr));
+ ToHTMLElement(*node).hasAttribute(kDirAttr));
}
void HTMLElement::ChildrenChanged(const ChildrenChange& change) {
@@ -942,7 +992,7 @@ void HTMLElement::ChildrenChanged(const ChildrenChange& change) {
bool HTMLElement::HasDirectionAuto() const {
// <bdi> defaults to dir="auto"
// https://html.spec.whatwg.org/multipage/semantics.html#the-bdi-element
- const AtomicString& direction = FastGetAttribute(dirAttr);
+ const AtomicString& direction = FastGetAttribute(kDirAttr);
return (IsHTMLBDIElement(*this) && direction == g_null_atom) ||
DeprecatedEqualIgnoringCase(direction, "auto");
}
@@ -985,7 +1035,7 @@ TextDirection HTMLElement::Directionality(
// Skip elements with valid dir attribute
if (node->IsElementNode()) {
AtomicString dir_attribute_value =
- ToElement(node)->FastGetAttribute(dirAttr);
+ ToElement(node)->FastGetAttribute(kDirAttr);
if (IsValidDirAttribute(dir_attribute_value)) {
node = FlatTreeTraversal::NextSkippingChildren(*node, this);
continue;
@@ -1029,7 +1079,7 @@ void HTMLElement::AdjustDirectionalityIfNeededAfterChildAttributeChanged(
if (ElementAffectsDirectionality(element_to_adjust)) {
element_to_adjust->SetNeedsStyleRecalc(
kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kWritingModeChange));
+ style_change_reason::kWritingModeChange));
return;
}
}
@@ -1039,10 +1089,11 @@ void HTMLElement::AdjustDirectionalityIfNeededAfterChildAttributeChanged(
void HTMLElement::CalculateAndAdjustDirectionality() {
TextDirection text_direction = Directionality();
const ComputedStyle* style = GetComputedStyle();
- if (style && style->Direction() != text_direction)
+ if (style && style->Direction() != text_direction) {
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kWritingModeChange));
+ style_change_reason::kWritingModeChange));
+ }
}
void HTMLElement::AdjustDirectionalityIfNeededAfterChildrenChanged(
@@ -1069,13 +1120,27 @@ Node::InsertionNotificationRequest HTMLElement::InsertedInto(
Element::InsertedInto(insertion_point);
if (GetDocument().GetContentSecurityPolicy()->HasHeaderDeliveredPolicy() &&
- InActiveDocument() && FastHasAttribute(nonceAttr)) {
- setAttribute(nonceAttr, g_empty_atom);
+ InActiveDocument() && FastHasAttribute(kNonceAttr)) {
+ setAttribute(kNonceAttr, g_empty_atom);
}
+ if (IsFormAssociatedCustomElement())
+ EnsureElementInternals().InsertedInto(insertion_point);
return kInsertionDone;
}
+void HTMLElement::RemovedFrom(ContainerNode& insertion_point) {
+ Element::RemovedFrom(insertion_point);
+ if (IsFormAssociatedCustomElement())
+ EnsureElementInternals().RemovedFrom(insertion_point);
+}
+
+void HTMLElement::DidMoveToNewDocument(Document& old_document) {
+ if (IsFormAssociatedCustomElement())
+ EnsureElementInternals().DidMoveToNewDocument(old_document);
+ Element::DidMoveToNewDocument(old_document);
+}
+
void HTMLElement::AddHTMLLengthToStyle(MutableCSSPropertyValueSet* style,
CSSPropertyID property_id,
const String& value,
@@ -1215,7 +1280,7 @@ bool HTMLElement::IsInteractiveContent() const {
}
void HTMLElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::keypress && event.IsKeyboardEvent()) {
+ if (event.type() == event_type_names::kKeypress && event.IsKeyboardEvent()) {
HandleKeypressEvent(ToKeyboardEvent(event));
if (event.DefaultHandled())
return;
@@ -1229,8 +1294,8 @@ bool HTMLElement::MatchesReadOnlyPseudoClass() const {
}
bool HTMLElement::MatchesReadWritePseudoClass() const {
- if (FastHasAttribute(contenteditableAttr)) {
- const AtomicString& value = FastGetAttribute(contenteditableAttr);
+ if (FastHasAttribute(kContenteditableAttr)) {
+ const AtomicString& value = FastGetAttribute(kContenteditableAttr);
if (value.IsEmpty() || DeprecatedEqualIgnoringCase(value, "true") ||
DeprecatedEqualIgnoringCase(value, "plaintext-only"))
@@ -1363,6 +1428,44 @@ void HTMLElement::OnXMLLangAttrChanged(
Element::ParseAttribute(params);
}
+ElementInternals* HTMLElement::attachInternals(
+ ExceptionState& exception_state) {
+ CustomElementRegistry* registry = CustomElement::Registry(*this);
+ auto* definition =
+ registry ? registry->DefinitionForName(localName()) : nullptr;
+ if (!definition) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "Unable to attach ElementInternals to non-custom elements.");
+ return nullptr;
+ }
+ if (!definition->Descriptor().IsAutonomous()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "Unable to attach ElementInternals to a customized built-in element.");
+ return nullptr;
+ }
+ if (definition->DisableInternals()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "ElementInternals is disabled by disabledFeature static field.");
+ return nullptr;
+ }
+ if (DidAttachInternals()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "ElementInternals for the specified element was already attached.");
+ return nullptr;
+ }
+ SetDidAttachInternals();
+ return &EnsureElementInternals();
+}
+
+bool HTMLElement::IsFormAssociatedCustomElement() const {
+ return GetCustomElementState() == CustomElementState::kCustom &&
+ GetCustomElementDefinition()->IsFormAssociated();
+}
+
} // namespace blink
#ifndef NDEBUG
diff --git a/chromium/third_party/blink/renderer/core/html/html_element.h b/chromium/third_party/blink/renderer/core/html/html_element.h
index 418bf8c54b9..dae88c91463 100644
--- a/chromium/third_party/blink/renderer/core/html/html_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_element.h
@@ -32,10 +32,13 @@ namespace blink {
struct AttributeTriggers;
class Color;
class DocumentFragment;
+class ElementInternals;
class ExceptionState;
class FormAssociated;
class HTMLFormElement;
class KeyboardEvent;
+class StringOrTrustedScript;
+class StringTreatNullAsEmptyStringOrTrustedScript;
enum TranslateAttributeMode {
kTranslateAttributeYes,
@@ -57,6 +60,12 @@ class CORE_EXPORT HTMLElement : public Element {
int tabIndex() const override;
void setInnerText(const String&, ExceptionState&);
+ virtual void setInnerText(const StringOrTrustedScript&, ExceptionState&);
+ virtual void setInnerText(const StringTreatNullAsEmptyStringOrTrustedScript&,
+ ExceptionState&);
+ String innerText();
+ void innerText(StringOrTrustedScript& result);
+ void innerText(StringTreatNullAsEmptyStringOrTrustedScript& result);
void setOuterText(const String&, ExceptionState&);
virtual bool HasCustomFocusLogic() const;
@@ -121,7 +130,9 @@ class CORE_EXPORT HTMLElement : public Element {
Element* unclosedOffsetParent();
- virtual FormAssociated* ToFormAssociatedOrNull() { return nullptr; };
+ ElementInternals* attachInternals(ExceptionState& exception_state);
+ virtual FormAssociated* ToFormAssociatedOrNull() { return nullptr; }
+ bool IsFormAssociatedCustomElement() const;
protected:
HTMLElement(const QualifiedName& tag_name, Document&, ConstructionType);
@@ -155,6 +166,8 @@ class CORE_EXPORT HTMLElement : public Element {
void CalculateAndAdjustDirectionality();
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
+ void RemovedFrom(ContainerNode& insertion_point) override;
+ void DidMoveToNewDocument(Document& old_document) override;
private:
String DebugNodeName() const final;
diff --git a/chromium/third_party/blink/renderer/core/html/html_element.idl b/chromium/third_party/blink/renderer/core/html/html_element.idl
index 6e1bef02c4d..d148491f641 100644
--- a/chromium/third_party/blink/renderer/core/html/html_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_element.idl
@@ -58,8 +58,12 @@ interface HTMLElement : Element {
// https://drafts.csswg.org/cssom/#the-elementcssinlinestyle-interface
[Affects=Nothing, SameObject, PerWorldBindings, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
+ // Form-associated custom elements
+ // https://docs.google.com/document/d/1JO8puctCSpW-ZYGU8lF-h4FWRIDQNDVexzHoOQ2iQmY/edit?pli=1#heading=h.pjt9nhs3gu3k
+ [RuntimeEnabled=ElementInternals, RaisesException] ElementInternals attachInternals();
+
// Non-standard APIs
- [Affects=Nothing, CEReactions, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementInnerText] attribute [TreatNullAs=EmptyString] DOMString innerText;
+ [Affects=Nothing, CEReactions, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementInnerText] attribute ([TreatNullAs=EmptyString] DOMString or TrustedScript) innerText;
[Affects=Nothing, CEReactions, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementOuterText] attribute [TreatNullAs=EmptyString] DOMString outerText;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_element_test.cc
index f0c8d331cb0..fc0277ea972 100644
--- a/chromium/third_party/blink/renderer/core/html/html_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_element_test.cc
@@ -13,7 +13,7 @@ class HTMLElementTest : public PageTestBase {};
TEST_F(HTMLElementTest, AdjustDirectionalityInFlatTree) {
SetBodyContent("<bdi><summary><i id=target></i></summary></bdi>");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().getElementById("target")->remove();
// Pass if not crashed.
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_embed_element.cc b/chromium/third_party/blink/renderer/core/html/html_embed_element.cc
index 99907cd05e7..1f152c3b471 100644
--- a/chromium/third_party/blink/renderer/core/html/html_embed_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_embed_element.cc
@@ -24,7 +24,7 @@
#include "third_party/blink/renderer/core/html/html_embed_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
@@ -39,18 +39,18 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLEmbedElement::HTMLEmbedElement(Document& document,
const CreateElementFlags flags)
- : HTMLPlugInElement(embedTag,
+ : HTMLPlugInElement(kEmbedTag,
document,
flags,
kShouldPreferPlugInsForImages) {}
HTMLEmbedElement* HTMLEmbedElement::Create(Document& document,
const CreateElementFlags flags) {
- auto* element = new HTMLEmbedElement(document, flags);
+ auto* element = MakeGarbageCollected<HTMLEmbedElement>(document, flags);
element->EnsureUserAgentShadowRoot();
return element;
}
@@ -78,7 +78,7 @@ LayoutEmbeddedContent* HTMLEmbedElement::ExistingLayoutEmbeddedContent() const {
bool HTMLEmbedElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == hiddenAttr)
+ if (name == kHiddenAttr)
return true;
return HTMLPlugInElement::IsPresentationAttribute(name);
}
@@ -87,7 +87,7 @@ void HTMLEmbedElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == hiddenAttr) {
+ if (name == kHiddenAttr) {
if (DeprecatedEqualIgnoringCase(value, "yes") ||
DeprecatedEqualIgnoringCase(value, "true")) {
AddPropertyToPresentationAttributeStyle(
@@ -102,7 +102,7 @@ void HTMLEmbedElement::CollectStyleForPresentationAttribute(
void HTMLEmbedElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == typeAttr) {
+ if (params.name == kTypeAttr) {
SetServiceType(params.new_value.LowerASCII());
wtf_size_t pos = service_type_.Find(";");
if (pos != kNotFound)
@@ -112,11 +112,11 @@ void HTMLEmbedElement::ParseAttribute(
GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
"Embed type changed");
}
- } else if (params.name == codeAttr) {
+ } else if (params.name == kCodeAttr) {
// TODO(schenney): Remove this branch? It's not in the spec and we're not in
// the HTMLAppletElement hierarchy.
SetUrl(StripLeadingAndTrailingHTMLSpaces(params.new_value));
- } else if (params.name == srcAttr) {
+ } else if (params.name == kSrcAttr) {
SetUrl(StripLeadingAndTrailingHTMLSpaces(params.new_value));
if (GetLayoutObject() && IsImageType()) {
if (!image_loader_)
@@ -124,7 +124,7 @@ void HTMLEmbedElement::ParseAttribute(
image_loader_->UpdateFromElement(ImageLoader::kUpdateIgnorePreviousError);
} else if (GetLayoutObject()) {
// Check if this Embed can transition from potentially-active to active
- if (FastHasAttribute(typeAttr)) {
+ if (FastHasAttribute(kTypeAttr)) {
SetNeedsPluginUpdate(true);
LazyReattachIfNeeded();
}
@@ -185,7 +185,7 @@ bool HTMLEmbedElement::LayoutObjectIsNeeded(const ComputedStyle& style) const {
// represents nothing:
// * The element has neither a src attribute nor a type attribute.
- if (!FastHasAttribute(srcAttr) && !FastHasAttribute(typeAttr))
+ if (!FastHasAttribute(kSrcAttr) && !FastHasAttribute(kTypeAttr))
return false;
// * The element has a media element ancestor.
@@ -204,12 +204,12 @@ bool HTMLEmbedElement::LayoutObjectIsNeeded(const ComputedStyle& style) const {
}
bool HTMLEmbedElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr ||
+ return attribute.GetName() == kSrcAttr ||
HTMLPlugInElement::IsURLAttribute(attribute);
}
const QualifiedName& HTMLEmbedElement::SubResourceAttributeName() const {
- return srcAttr;
+ return kSrcAttr;
}
bool HTMLEmbedElement::IsInteractiveContent() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_embed_element.h b/chromium/third_party/blink/renderer/core/html/html_embed_element.h
index 9098cb82d25..98a1e7cad6b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_embed_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_embed_element.h
@@ -23,6 +23,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_EMBED_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_EMBED_ELEMENT_H_
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/html_plugin_element.h"
@@ -36,14 +37,18 @@ class CORE_EXPORT HTMLEmbedElement final : public HTMLPlugInElement {
Document&,
const CreateElementFlags = CreateElementFlags());
+ HTMLEmbedElement(Document&, const CreateElementFlags);
+
// Returns attributes that should be checked against Trusted Types
const HashSet<AtomicString>& GetCheckedAttributeNames() const override;
bool IsExposed() const;
- private:
- HTMLEmbedElement(Document&, const CreateElementFlags);
+ FrameOwnerElementType OwnerType() const final {
+ return FrameOwnerElementType::kEmbed;
+ }
+ private:
void ParseAttribute(const AttributeModificationParams&) override;
bool IsPresentationAttribute(const QualifiedName&) const override;
void CollectStyleForPresentationAttribute(
diff --git a/chromium/third_party/blink/renderer/core/html/html_embed_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_embed_element_test.cc
index 75ac569e134..4a432f020c7 100644
--- a/chromium/third_party/blink/renderer/core/html/html_embed_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_embed_element_test.cc
@@ -46,7 +46,7 @@ TEST_F(HTMLEmbedElementTest, FallbackState) {
ASSERT_TRUE(embed_element);
HTMLEmbedElement* embed = ToHTMLEmbedElement(embed_element);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// We should get |true| as a result and don't trigger a DCHECK.
EXPECT_TRUE(static_cast<Element*>(embed)->LayoutObjectIsNeeded(
@@ -59,7 +59,7 @@ TEST_F(HTMLEmbedElementTest, FallbackState) {
EXPECT_TRUE(object->UseFallbackContent());
EXPECT_TRUE(object->WillUseFallbackContentAtLayout());
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(static_cast<Element*>(embed)->LayoutObjectIsNeeded(
ComputedStyle::InitialStyle()));
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_font_element.cc b/chromium/third_party/blink/renderer/core/html/html_font_element.cc
index 68ac9290544..d61a02c05c6 100644
--- a/chromium/third_party/blink/renderer/core/html/html_font_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_font_element.cc
@@ -22,11 +22,11 @@
#include "third_party/blink/renderer/core/html/html_font_element.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/css_value_pool.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
@@ -37,10 +37,10 @@
namespace blink {
using namespace cssvalue;
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLFontElement::HTMLFontElement(Document& document)
- : HTMLElement(fontTag, document) {}
+ : HTMLElement(kFontTag, document) {}
DEFINE_NODE_FACTORY(HTMLFontElement)
@@ -170,7 +170,7 @@ bool HTMLFontElement::CssValueFromFontSizeNumber(const String& s,
}
bool HTMLFontElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == sizeAttr || name == colorAttr || name == faceAttr)
+ if (name == kSizeAttr || name == kColorAttr || name == kFaceAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -179,13 +179,13 @@ void HTMLFontElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == sizeAttr) {
+ if (name == kSizeAttr) {
CSSValueID size = CSSValueInvalid;
if (CssValueFromFontSizeNumber(value, size))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyFontSize, size);
- } else if (name == colorAttr) {
+ } else if (name == kColorAttr) {
AddHTMLColorToStyle(style, CSSPropertyColor, value);
- } else if (name == faceAttr && !value.IsEmpty()) {
+ } else if (name == kFaceAttr && !value.IsEmpty()) {
if (const CSSValueList* font_face_value = CreateFontFaceValueWithPool(
value, GetDocument().GetSecureContextMode())) {
style->SetProperty(
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_element.cc b/chromium/third_party/blink/renderer/core/html/html_frame_element.cc
index 69915130823..dc1bdd98d4a 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_element.cc
@@ -30,10 +30,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLFrameElement::HTMLFrameElement(Document& document)
- : HTMLFrameElementBase(frameTag, document),
+ : HTMLFrameElementBase(kFrameTag, document),
frame_border_(true),
frame_border_set_(false) {}
@@ -55,7 +55,7 @@ LayoutObject* HTMLFrameElement::CreateLayoutObject(const ComputedStyle&) {
}
bool HTMLFrameElement::NoResize() const {
- return hasAttribute(noresizeAttr);
+ return hasAttribute(kNoresizeAttr);
}
void HTMLFrameElement::AttachLayoutTree(AttachContext& context) {
@@ -70,11 +70,11 @@ void HTMLFrameElement::AttachLayoutTree(AttachContext& context) {
void HTMLFrameElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == frameborderAttr) {
+ if (params.name == kFrameborderAttr) {
frame_border_ = params.new_value.ToInt();
frame_border_set_ = !params.new_value.IsNull();
// FIXME: If we are already attached, this has no effect.
- } else if (params.name == noresizeAttr) {
+ } else if (params.name == kNoresizeAttr) {
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
} else {
@@ -85,14 +85,15 @@ void HTMLFrameElement::ParseAttribute(
ParsedFeaturePolicy HTMLFrameElement::ConstructContainerPolicy(
Vector<String>*) const {
// Frame elements are not allowed to enable the fullscreen feature. Add an
- // empty whitelist for the fullscreen feature so that the framed content is
+ // empty allowlist for the fullscreen feature so that the framed content is
// unable to use the API, regardless of origin.
// https://fullscreen.spec.whatwg.org/#model
ParsedFeaturePolicy container_policy;
- ParsedFeaturePolicyDeclaration whitelist;
- whitelist.feature = mojom::FeaturePolicyFeature::kFullscreen;
- whitelist.matches_all_origins = false;
- container_policy.push_back(whitelist);
+ ParsedFeaturePolicyDeclaration allowlist;
+ allowlist.feature = mojom::FeaturePolicyFeature::kFullscreen;
+ allowlist.matches_all_origins = false;
+ allowlist.disposition = mojom::FeaturePolicyDisposition::kEnforce;
+ container_policy.push_back(allowlist);
return container_policy;
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_element.h b/chromium/third_party/blink/renderer/core/html/html_frame_element.h
index 083e694d27f..0b416f98a78 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_element.h
@@ -25,6 +25,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_FRAME_ELEMENT_H_
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
@@ -46,6 +47,10 @@ class CORE_EXPORT HTMLFrameElement final : public HTMLFrameElementBase {
ParsedFeaturePolicy ConstructContainerPolicy(
Vector<String>* /* messages */) const override;
+ FrameOwnerElementType OwnerType() const final {
+ return FrameOwnerElementType::kFrame;
+ }
+
private:
explicit HTMLFrameElement(Document&);
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_element_base.cc b/chromium/third_party/blink/renderer/core/html/html_frame_element_base.cc
index 3e1fce3c3d4..466ad257e02 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_element_base.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_element_base.cc
@@ -43,7 +43,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLFrameElementBase::HTMLFrameElementBase(const QualifiedName& tag_name,
Document& document)
@@ -125,28 +125,28 @@ void HTMLFrameElementBase::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == srcdocAttr) {
+ if (name == kSrcdocAttr) {
if (!value.IsNull()) {
SetLocation(SrcdocURL().GetString());
} else {
- const AtomicString& src_value = FastGetAttribute(srcAttr);
+ const AtomicString& src_value = FastGetAttribute(kSrcAttr);
if (!src_value.IsNull())
SetLocation(StripLeadingAndTrailingHTMLSpaces(src_value));
}
- } else if (name == srcAttr && !FastHasAttribute(srcdocAttr)) {
+ } else if (name == kSrcAttr && !FastHasAttribute(kSrcdocAttr)) {
SetLocation(StripLeadingAndTrailingHTMLSpaces(value));
- } else if (name == idAttr) {
+ } else if (name == kIdAttr) {
// Important to call through to base for the id attribute so the hasID bit
// gets set.
HTMLFrameOwnerElement::ParseAttribute(params);
frame_name_ = value;
- } else if (name == nameAttr) {
+ } else if (name == kNameAttr) {
frame_name_ = value;
- } else if (name == marginwidthAttr) {
+ } else if (name == kMarginwidthAttr) {
SetMarginWidth(value.ToInt());
- } else if (name == marginheightAttr) {
+ } else if (name == kMarginheightAttr) {
SetMarginHeight(value.ToInt());
- } else if (name == scrollingAttr) {
+ } else if (name == kScrollingAttr) {
// Auto and yes both simply mean "allow scrolling." No means "don't allow
// scrolling."
if (DeprecatedEqualIgnoringCase(value, "auto") ||
@@ -154,10 +154,10 @@ void HTMLFrameElementBase::ParseAttribute(
SetScrollingMode(kScrollbarAuto);
else if (DeprecatedEqualIgnoringCase(value, "no"))
SetScrollingMode(kScrollbarAlwaysOff);
- } else if (name == onbeforeunloadAttr) {
+ } else if (name == kOnbeforeunloadAttr) {
// FIXME: should <frame> elements have beforeunload handlers?
SetAttributeEventListener(
- EventTypeNames::beforeunload,
+ event_type_names::kBeforeunload,
CreateAttributeEventListener(
this, name, value,
JSEventHandler::HandlerType::kOnBeforeUnloadEventHandler));
@@ -241,19 +241,19 @@ void HTMLFrameElementBase::SetFocused(bool received, WebFocusType focus_type) {
}
bool HTMLFrameElementBase::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == longdescAttr ||
- attribute.GetName() == srcAttr ||
+ return attribute.GetName() == kLongdescAttr ||
+ attribute.GetName() == kSrcAttr ||
HTMLFrameOwnerElement::IsURLAttribute(attribute);
}
bool HTMLFrameElementBase::HasLegalLinkAttribute(
const QualifiedName& name) const {
- return name == srcAttr || HTMLFrameOwnerElement::HasLegalLinkAttribute(name);
+ return name == kSrcAttr || HTMLFrameOwnerElement::HasLegalLinkAttribute(name);
}
bool HTMLFrameElementBase::IsHTMLContentAttribute(
const Attribute& attribute) const {
- return attribute.GetName() == srcdocAttr ||
+ return attribute.GetName() == kSrcdocAttr ||
HTMLFrameOwnerElement::IsHTMLContentAttribute(attribute);
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_frame_element_test.cc
index 4e97512d141..54a4cf8ce50 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_element_test.cc
@@ -22,7 +22,7 @@ TEST_F(HTMLFrameElementTest, DefaultContainerPolicy) {
HTMLFrameElement* frame_element = HTMLFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
frame_element->UpdateContainerPolicyForTests();
const ParsedFeaturePolicy& container_policy =
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.cc b/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.cc
index da2aaf41b3f..ddfe3ce43c3 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.cc
@@ -32,6 +32,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/remote_frame.h"
#include "third_party/blink/renderer/core/frame/remote_frame_view.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/lazy_load_frame_observer.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
@@ -45,6 +46,7 @@
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
+#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
@@ -54,7 +56,8 @@ namespace {
using PluginSet = HeapHashSet<Member<WebPluginContainerImpl>>;
PluginSet& PluginsPendingDispose() {
- DEFINE_STATIC_LOCAL(Persistent<PluginSet>, set, (new PluginSet));
+ DEFINE_STATIC_LOCAL(Persistent<PluginSet>, set,
+ (MakeGarbageCollected<PluginSet>()));
return *set;
}
@@ -133,7 +136,7 @@ void HTMLFrameOwnerElement::SetContentFrame(Frame& frame) {
layer->SetNeedsCompositingInputsUpdate();
}
SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
- StyleChangeReason::kFrame));
+ style_change_reason::kFrame));
for (ContainerNode* node = this; node; node = node->ParentOrShadowHostNode())
node->IncrementConnectedSubframeCount();
@@ -262,7 +265,7 @@ void HTMLFrameOwnerElement::DispatchLoad() {
if (lazy_load_frame_observer_)
lazy_load_frame_observer_->RecordMetricsOnLoadFinished();
- DispatchScopedEvent(*Event::Create(EventTypeNames::load));
+ DispatchScopedEvent(*Event::Create(event_type_names::kLoad));
}
const ParsedFeaturePolicy& HTMLFrameOwnerElement::ContainerPolicy() const {
@@ -354,7 +357,7 @@ bool HTMLFrameOwnerElement::LoadOrRedirectSubframe(
// attribute value "off" for "lazyload" is ignored (i.e., interpreted as
// "auto" instead).
if (should_lazy_load_children_ &&
- EqualIgnoringASCIICase(FastGetAttribute(HTMLNames::lazyloadAttr),
+ EqualIgnoringASCIICase(FastGetAttribute(html_names::kLazyloadAttr),
"off") &&
!GetDocument().IsLazyLoadPolicyEnforced()) {
should_lazy_load_children_ = false;
@@ -385,8 +388,8 @@ bool HTMLFrameOwnerElement::LoadOrRedirectSubframe(
if (!child_frame)
return false;
- ResourceRequest request(url);
- ReferrerPolicy policy = ReferrerPolicyAttribute();
+ ResourceRequest request(url.IsNull() ? BlankURL() : url);
+ network::mojom::ReferrerPolicy policy = ReferrerPolicyAttribute();
request.SetReferrerPolicy(policy);
WebFrameLoadType child_load_type = WebFrameLoadType::kReplaceCurrentItem;
@@ -406,14 +409,24 @@ bool HTMLFrameOwnerElement::LoadOrRedirectSubframe(
if ((RuntimeEnabledFeatures::LazyFrameLoadingEnabled() ||
RuntimeEnabledFeatures::LazyFrameVisibleLoadTimeMetricsEnabled()) &&
+ GetDocument().GetSettings() &&
+ GetDocument().GetSettings()->GetLazyLoadEnabled() &&
!lazy_load_frame_observer_ &&
// Only http:// or https:// URLs are eligible for lazy loading, excluding
// URLs like invalid or empty URLs, "about:blank", local file URLs, etc.
// that it doesn't make sense to lazily load.
url.ProtocolIsInHTTPFamily() &&
- (EqualIgnoringASCIICase(FastGetAttribute(HTMLNames::lazyloadAttr),
+ (EqualIgnoringASCIICase(FastGetAttribute(html_names::kLazyloadAttr),
"on") ||
(should_lazy_load_children_ &&
+ // If lazy loading is restricted to only Data Saver users, then avoid
+ // lazy loading unless Data Saver is enabled, taking the Data Saver
+ // holdback into consideration.
+ (!RuntimeEnabledFeatures::
+ RestrictLazyFrameLoadingToDataSaverEnabled() ||
+ (!(GetDocument().GetSettings() &&
+ GetDocument().GetSettings()->GetDataSaverHoldbackWebApi()) &&
+ GetNetworkStateNotifier().SaveDataEnabled())) &&
// Disallow lazy loading by default if javascript in the embedding
// document would be able to access the contents of the frame, since in
// those cases deferring the frame could break the page. Note that this
@@ -427,7 +440,8 @@ bool HTMLFrameOwnerElement::LoadOrRedirectSubframe(
// near the viewport or visible.
should_lazy_load_children_ = false;
- lazy_load_frame_observer_ = new LazyLoadFrameObserver(*this);
+ lazy_load_frame_observer_ =
+ MakeGarbageCollected<LazyLoadFrameObserver>(*this);
if (RuntimeEnabledFeatures::LazyFrameVisibleLoadTimeMetricsEnabled())
lazy_load_frame_observer_->StartTrackingVisibilityMetrics();
@@ -457,7 +471,7 @@ bool HTMLFrameOwnerElement::ShouldLazyLoadChildren() const {
void HTMLFrameOwnerElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == HTMLNames::lazyloadAttr) {
+ if (params.name == html_names::kLazyloadAttr) {
// Note that when the *feature policy* for "lazyload" is disabled, the
// attribute value "off" for "lazyload" is ignored (i.e., interpreted as
// "auto" instead).
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.h b/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.h
index 4209956c4e0..e4f22d0cb0f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_owner_element.h
@@ -21,6 +21,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_FRAME_OWNER_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_FRAME_OWNER_ELEMENT_H_
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/feature_policy/feature_policy.h"
@@ -62,6 +63,8 @@ class CORE_EXPORT HTMLFrameOwnerElement : public HTMLElement,
// is, to remove it from the layout as if it did not exist.
virtual void SetCollapsed(bool) {}
+ virtual FrameOwnerElementType OwnerType() const = 0;
+
Document* getSVGDocument(ExceptionState&) const;
void SetEmbeddedContentView(EmbeddedContentView*);
@@ -98,10 +101,10 @@ class CORE_EXPORT HTMLFrameOwnerElement : public HTMLElement,
void DispatchLoad() final;
SandboxFlags GetSandboxFlags() const final { return sandbox_flags_; }
bool CanRenderFallbackContent() const override { return false; }
- void RenderFallbackContent() override {}
+ void RenderFallbackContent(Frame*) override {}
void IntrinsicSizingInfoChanged() override {}
AtomicString BrowsingContextContainerName() const override {
- return getAttribute(HTMLNames::nameAttr);
+ return getAttribute(html_names::kNameAttr);
}
ScrollbarMode ScrollingMode() const override { return kScrollbarAuto; }
int MarginWidth() const override { return -1; }
@@ -166,8 +169,8 @@ class CORE_EXPORT HTMLFrameOwnerElement : public HTMLElement,
bool IsFrameOwnerElement() const final { return true; }
- virtual ReferrerPolicy ReferrerPolicyAttribute() {
- return kReferrerPolicyDefault;
+ virtual network::mojom::ReferrerPolicy ReferrerPolicyAttribute() {
+ return network::mojom::ReferrerPolicy::kDefault;
}
Member<Frame> content_frame_;
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_set_element.cc b/chromium/third_party/blink/renderer/core/html/html_frame_set_element.cc
index fc7c8112ada..3a3503d4fbb 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_set_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_set_element.cc
@@ -24,8 +24,8 @@
#include "third_party/blink/renderer/core/html/html_frame_set_element.h"
#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
@@ -39,10 +39,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLFrameSetElement::HTMLFrameSetElement(Document& document)
- : HTMLElement(framesetTag, document),
+ : HTMLElement(kFramesetTag, document),
border_(6),
border_set_(false),
border_color_set_(false),
@@ -56,7 +56,7 @@ DEFINE_NODE_FACTORY(HTMLFrameSetElement)
bool HTMLFrameSetElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == bordercolorAttr)
+ if (name == kBordercolorAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -65,7 +65,7 @@ void HTMLFrameSetElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == bordercolorAttr)
+ if (name == kBordercolorAttr)
AddHTMLColorToStyle(style, CSSPropertyBorderColor, value);
else
HTMLElement::CollectStyleForPresentationAttribute(name, value, style);
@@ -75,19 +75,19 @@ void HTMLFrameSetElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == rowsAttr) {
+ if (name == kRowsAttr) {
if (!value.IsNull()) {
row_lengths_ = ParseListOfDimensions(value.GetString());
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::FromAttribute(name));
}
- } else if (name == colsAttr) {
+ } else if (name == kColsAttr) {
if (!value.IsNull()) {
col_lengths_ = ParseListOfDimensions(value.GetString());
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::FromAttribute(name));
}
- } else if (name == frameborderAttr) {
+ } else if (name == kFrameborderAttr) {
if (!value.IsNull()) {
if (DeprecatedEqualIgnoringCase(value, "no") ||
DeprecatedEqualIgnoringCase(value, "0")) {
@@ -101,109 +101,109 @@ void HTMLFrameSetElement::ParseAttribute(
frameborder_ = false;
frameborder_set_ = false;
}
- } else if (name == noresizeAttr) {
+ } else if (name == kNoresizeAttr) {
noresize_ = true;
- } else if (name == borderAttr) {
+ } else if (name == kBorderAttr) {
if (!value.IsNull()) {
border_ = value.ToInt();
border_set_ = true;
} else {
border_set_ = false;
}
- } else if (name == bordercolorAttr) {
+ } else if (name == kBordercolorAttr) {
border_color_set_ = !value.IsEmpty();
- } else if (name == onafterprintAttr) {
+ } else if (name == kOnafterprintAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::afterprint,
+ event_type_names::kAfterprint,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onbeforeprintAttr) {
+ } else if (name == kOnbeforeprintAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::beforeprint,
+ event_type_names::kBeforeprint,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onloadAttr) {
+ } else if (name == kOnloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::load,
+ event_type_names::kLoad,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onbeforeunloadAttr) {
+ } else if (name == kOnbeforeunloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::beforeunload,
+ event_type_names::kBeforeunload,
CreateAttributeEventListener(
GetDocument().GetFrame(), name, value,
JSEventHandler::HandlerType::kOnBeforeUnloadEventHandler));
- } else if (name == onunloadAttr) {
+ } else if (name == kOnunloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::unload,
+ event_type_names::kUnload,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onpagehideAttr) {
+ } else if (name == kOnpagehideAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::pagehide,
+ event_type_names::kPagehide,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onpageshowAttr) {
+ } else if (name == kOnpageshowAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::pageshow,
+ event_type_names::kPageshow,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onblurAttr) {
+ } else if (name == kOnblurAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::blur,
+ event_type_names::kBlur,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onerrorAttr) {
+ } else if (name == kOnerrorAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::error,
+ event_type_names::kError,
CreateAttributeEventListener(
GetDocument().GetFrame(), name, value,
JSEventHandler::HandlerType::kOnErrorEventHandler));
- } else if (name == onfocusAttr) {
+ } else if (name == kOnfocusAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::focus,
+ event_type_names::kFocus,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onfocusinAttr) {
+ } else if (name == kOnfocusinAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::focusin,
+ event_type_names::kFocusin,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onfocusoutAttr) {
+ } else if (name == kOnfocusoutAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::focusout,
+ event_type_names::kFocusout,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
} else if (RuntimeEnabledFeatures::OrientationEventEnabled() &&
- name == onorientationchangeAttr) {
+ name == kOnorientationchangeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::orientationchange,
+ event_type_names::kOrientationchange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onhashchangeAttr) {
+ } else if (name == kOnhashchangeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::hashchange,
+ event_type_names::kHashchange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onmessageAttr) {
+ } else if (name == kOnmessageAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::message,
+ event_type_names::kMessage,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onresizeAttr) {
+ } else if (name == kOnresizeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::resize,
+ event_type_names::kResize,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onscrollAttr) {
+ } else if (name == kOnscrollAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::scroll,
+ event_type_names::kScroll,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onstorageAttr) {
+ } else if (name == kOnstorageAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::storage,
+ event_type_names::kStorage,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == ononlineAttr) {
+ } else if (name == kOnonlineAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::online,
+ event_type_names::kOnline,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onofflineAttr) {
+ } else if (name == kOnofflineAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::offline,
+ event_type_names::kOffline,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onpopstateAttr) {
+ } else if (name == kOnpopstateAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::popstate,
+ event_type_names::kPopstate,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == onlanguagechangeAttr) {
+ } else if (name == kOnlanguagechangeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::languagechange,
+ event_type_names::kLanguagechange,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
} else {
HTMLElement::ParseAttribute(params);
@@ -213,8 +213,7 @@ void HTMLFrameSetElement::ParseAttribute(
bool HTMLFrameSetElement::LayoutObjectIsNeeded(
const ComputedStyle& style) const {
// For compatibility, frames layoutObject even when display: none is set.
- // However, we delay creating a layoutObject until stylesheets have loaded.
- return style.IsStyleAvailable();
+ return true;
}
LayoutObject* HTMLFrameSetElement::CreateLayoutObject(
@@ -268,7 +267,7 @@ Node::InsertionNotificationRequest HTMLFrameSetElement::InsertedInto(
void HTMLFrameSetElement::WillRecalcStyle(StyleRecalcChange) {
if (NeedsStyleRecalc() && GetLayoutObject()) {
GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
ClearNeedsStyleRecalc();
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_set_element.h b/chromium/third_party/blink/renderer/core/html/html_frame_set_element.h
index 0f87e345fff..4f955c7649d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_set_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_set_element.h
@@ -55,13 +55,13 @@ class HTMLFrameSetElement final : public HTMLElement {
bool HasNonInBodyInsertionMode() const override { return true; }
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur, kBlur);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus, kFocus);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load, kLoad);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize, kResize);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll, kScroll);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange, kOrientationchange);
private:
explicit HTMLFrameSetElement(Document&);
diff --git a/chromium/third_party/blink/renderer/core/html/html_head_element.cc b/chromium/third_party/blink/renderer/core/html/html_head_element.cc
index 498dbf3efed..e378e21b205 100644
--- a/chromium/third_party/blink/renderer/core/html/html_head_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_head_element.cc
@@ -27,10 +27,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLHeadElement::HTMLHeadElement(Document& document)
- : HTMLElement(headTag, document) {}
+ : HTMLElement(kHeadTag, document) {}
DEFINE_NODE_FACTORY(HTMLHeadElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_hr_element.cc b/chromium/third_party/blink/renderer/core/html/html_hr_element.cc
index a1835bff94b..9ac421400d6 100644
--- a/chromium/third_party/blink/renderer/core/html/html_hr_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_hr_element.cc
@@ -23,8 +23,8 @@
#include "third_party/blink/renderer/core/html/html_hr_element.h"
#include "third_party/blink/renderer/core/css/css_color_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/html/forms/html_opt_group_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
@@ -33,16 +33,16 @@
namespace blink {
using namespace cssvalue;
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLHRElement::HTMLHRElement(Document& document)
- : HTMLElement(hrTag, document) {}
+ : HTMLElement(kHrTag, document) {}
DEFINE_NODE_FACTORY(HTMLHRElement)
bool HTMLHRElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == alignAttr || name == widthAttr || name == colorAttr ||
- name == noshadeAttr || name == sizeAttr)
+ if (name == kAlignAttr || name == kWidthAttr || name == kColorAttr ||
+ name == kNoshadeAttr || name == kSizeAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -51,7 +51,7 @@ void HTMLHRElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
if (DeprecatedEqualIgnoringCase(value, "left")) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyMarginLeft, 0,
@@ -70,7 +70,7 @@ void HTMLHRElement::CollectStyleForPresentationAttribute(
AddPropertyToPresentationAttributeStyle(style, CSSPropertyMarginRight,
CSSValueAuto);
}
- } else if (name == widthAttr) {
+ } else if (name == kWidthAttr) {
bool ok;
int v = value.ToInt(&ok);
if (ok && !v)
@@ -78,13 +78,13 @@ void HTMLHRElement::CollectStyleForPresentationAttribute(
style, CSSPropertyWidth, 1, CSSPrimitiveValue::UnitType::kPixels);
else
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- } else if (name == colorAttr) {
+ } else if (name == kColorAttr) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle,
CSSValueSolid);
AddHTMLColorToStyle(style, CSSPropertyBorderColor, value);
AddHTMLColorToStyle(style, CSSPropertyBackgroundColor, value);
- } else if (name == noshadeAttr) {
- if (!hasAttribute(colorAttr)) {
+ } else if (name == kNoshadeAttr) {
+ if (!hasAttribute(kColorAttr)) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle,
CSSValueSolid);
@@ -93,7 +93,7 @@ void HTMLHRElement::CollectStyleForPresentationAttribute(
style->SetProperty(CSSPropertyBorderColor, dark_gray_value);
style->SetProperty(CSSPropertyBackgroundColor, dark_gray_value);
}
- } else if (name == sizeAttr) {
+ } else if (name == kSizeAttr) {
int size = value.ToInt();
if (size <= 1)
AddPropertyToPresentationAttributeStyle(
diff --git a/chromium/third_party/blink/renderer/core/html/html_html_element.cc b/chromium/third_party/blink/renderer/core/html/html_html_element.cc
index eb9f3b102f5..6188335ba9c 100644
--- a/chromium/third_party/blink/renderer/core/html/html_html_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_html_element.cc
@@ -36,15 +36,15 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLHtmlElement::HTMLHtmlElement(Document& document)
- : HTMLElement(htmlTag, document) {}
+ : HTMLElement(kHTMLTag, document) {}
DEFINE_NODE_FACTORY(HTMLHtmlElement)
bool HTMLHtmlElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == manifestAttr ||
+ return attribute.GetName() == kManifestAttr ||
HTMLElement::IsURLAttribute(attribute);
}
@@ -73,7 +73,7 @@ void HTMLHtmlElement::MaybeSetupApplicationCache() {
if (!document_loader ||
!GetDocument().Parser()->DocumentWasLoadedAsPartOfNavigation())
return;
- const AtomicString& manifest = FastGetAttribute(manifestAttr);
+ const AtomicString& manifest = FastGetAttribute(kManifestAttr);
if (RuntimeEnabledFeatures::RestrictAppCacheToSecureContextsEnabled() &&
!GetDocument().IsSecureContext()) {
diff --git a/chromium/third_party/blink/renderer/core/html/html_iframe_element.cc b/chromium/third_party/blink/renderer/core/html/html_iframe_element.cc
index 3ae5e74c5a9..2301338b30d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_iframe_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_iframe_element.cc
@@ -26,7 +26,7 @@
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_html.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_html_iframe_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/feature_policy/iframe_policy.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -40,13 +40,13 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLIFrameElement::HTMLIFrameElement(Document& document)
- : HTMLFrameElementBase(iframeTag, document),
+ : HTMLFrameElementBase(kIFrameTag, document),
collapsed_by_client_(false),
sandbox_(HTMLIFrameElementSandbox::Create(this)),
- referrer_policy_(kReferrerPolicyDefault) {}
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {}
DEFINE_NODE_FACTORY(HTMLIFrameElement)
@@ -84,16 +84,16 @@ DOMTokenList* HTMLIFrameElement::sandbox() const {
Policy* HTMLIFrameElement::policy() {
if (!policy_) {
- policy_ = new IFramePolicy(&GetDocument(), ContainerPolicy(),
- GetOriginForFeaturePolicy());
+ policy_ = MakeGarbageCollected<IFramePolicy>(
+ &GetDocument(), ContainerPolicy(), GetOriginForFeaturePolicy());
}
return policy_.Get();
}
bool HTMLIFrameElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == widthAttr || name == heightAttr || name == alignAttr ||
- name == frameborderAttr)
+ if (name == kWidthAttr || name == kHeightAttr || name == kAlignAttr ||
+ name == kFrameborderAttr)
return true;
return HTMLFrameElementBase::IsPresentationAttribute(name);
}
@@ -102,13 +102,13 @@ void HTMLIFrameElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == widthAttr) {
+ if (name == kWidthAttr) {
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
- } else if (name == alignAttr) {
+ } else if (name == kAlignAttr) {
ApplyAlignmentAttributeToStyle(value, style);
- } else if (name == frameborderAttr) {
+ } else if (name == kFrameborderAttr) {
// LocalFrame border doesn't really match the HTML4 spec definition for
// iframes. It simply adds a presentational hint that the border should be
// off if set to zero.
@@ -128,7 +128,7 @@ void HTMLIFrameElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == nameAttr) {
+ if (name == kNameAttr) {
if (IsInDocumentTree() && GetDocument().IsHTMLDocument()) {
HTMLDocument& document = ToHTMLDocument(GetDocument());
document.RemoveNamedItem(name_);
@@ -138,7 +138,7 @@ void HTMLIFrameElement::ParseAttribute(
name_ = value;
if (name_ != old_name)
FrameOwnerPropertiesChanged();
- } else if (name == sandboxAttr) {
+ } else if (name == kSandboxAttr) {
sandbox_->DidUpdateAttributeValue(params.old_value, value);
String invalid_tokens;
SetSandboxFlags(value.IsNull() ? kSandboxNone
@@ -150,15 +150,15 @@ void HTMLIFrameElement::ParseAttribute(
"Error while parsing the 'sandbox' attribute: " + invalid_tokens));
}
UseCounter::Count(GetDocument(), WebFeature::kSandboxViaIFrame);
- } else if (name == referrerpolicyAttr) {
- referrer_policy_ = kReferrerPolicyDefault;
+ } else if (name == kReferrerpolicyAttr) {
+ referrer_policy_ = network::mojom::ReferrerPolicy::kDefault;
if (!value.IsNull()) {
SecurityPolicy::ReferrerPolicyFromString(
value, kSupportReferrerPolicyLegacyKeywords, &referrer_policy_);
UseCounter::Count(GetDocument(),
WebFeature::kHTMLIFrameElementReferrerPolicyAttribute);
}
- } else if (name == allowfullscreenAttr) {
+ } else if (name == kAllowfullscreenAttr) {
bool old_allow_fullscreen = allow_fullscreen_;
allow_fullscreen_ = !value.IsNull();
if (allow_fullscreen_ != old_allow_fullscreen) {
@@ -173,14 +173,14 @@ void HTMLIFrameElement::ParseAttribute(
FrameOwnerPropertiesChanged();
UpdateContainerPolicy();
}
- } else if (name == allowpaymentrequestAttr) {
+ } else if (name == kAllowpaymentrequestAttr) {
bool old_allow_payment_request = allow_payment_request_;
allow_payment_request_ = !value.IsNull();
if (allow_payment_request_ != old_allow_payment_request) {
FrameOwnerPropertiesChanged();
UpdateContainerPolicy();
}
- } else if (name == cspAttr) {
+ } else if (name == kCspAttr) {
if (!ContentSecurityPolicy::IsValidCSPAttr(
value.GetString(), GetDocument().RequiredCSP().GetString())) {
required_csp_ = g_null_atom;
@@ -193,7 +193,7 @@ void HTMLIFrameElement::ParseAttribute(
required_csp_ = value;
FrameOwnerPropertiesChanged();
}
- } else if (name == allowAttr) {
+ } else if (name == kAllowAttr) {
if (allow_ != value) {
allow_ = value;
Vector<String> messages;
@@ -228,7 +228,7 @@ void HTMLIFrameElement::ParseAttribute(
"https://goo.gl/ximf56"));
}
- if (name == srcAttr)
+ if (name == kSrcAttr)
LogUpdateAttributeIfIsolatedWorldAndInDocument("iframe", params);
HTMLFrameElementBase::ParseAttribute(params);
}
@@ -239,8 +239,8 @@ ParsedFeaturePolicy HTMLIFrameElement::ConstructContainerPolicy(
scoped_refptr<const SecurityOrigin> src_origin = GetOriginForFeaturePolicy();
scoped_refptr<const SecurityOrigin> self_origin =
GetDocument().GetSecurityOrigin();
- ParsedFeaturePolicy container_policy =
- ParseFeaturePolicyAttribute(allow_, self_origin, src_origin, messages);
+ ParsedFeaturePolicy container_policy = ParseFeaturePolicyAttribute(
+ allow_, self_origin, src_origin, messages, &GetDocument());
// If allowfullscreen attribute is present and no fullscreen policy is set,
// enable the feature for all origins.
@@ -300,7 +300,7 @@ Node::InsertionNotificationRequest HTMLIFrameElement::InsertedInto(
}
}
}
- LogAddElementIfIsolatedWorldAndInDocument("iframe", srcAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("iframe", kSrcAttr);
return result;
}
@@ -314,7 +314,7 @@ bool HTMLIFrameElement::IsInteractiveContent() const {
return true;
}
-ReferrerPolicy HTMLIFrameElement::ReferrerPolicyAttribute() {
+network::mojom::ReferrerPolicy HTMLIFrameElement::ReferrerPolicyAttribute() {
return referrer_policy_;
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_iframe_element.h b/chromium/third_party/blink/renderer/core/html/html_iframe_element.h
index 63627ac56ee..ece6e8a827c 100644
--- a/chromium/third_party/blink/renderer/core/html/html_iframe_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_iframe_element.h
@@ -25,6 +25,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_IFRAME_ELEMENT_H_
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_iframe_element_sandbox.h"
@@ -53,6 +54,10 @@ class CORE_EXPORT HTMLIFrameElement final
ParsedFeaturePolicy ConstructContainerPolicy(
Vector<String>* /* messages */) const override;
+ FrameOwnerElementType OwnerType() const final {
+ return FrameOwnerElementType::kIframe;
+ }
+
private:
explicit HTMLIFrameElement(Document&);
@@ -73,7 +78,7 @@ class CORE_EXPORT HTMLIFrameElement final
bool IsInteractiveContent() const override;
- ReferrerPolicy ReferrerPolicyAttribute() override;
+ network::mojom::ReferrerPolicy ReferrerPolicyAttribute() override;
// FrameOwner overrides:
bool AllowFullscreen() const override { return allow_fullscreen_; }
@@ -89,7 +94,7 @@ class CORE_EXPORT HTMLIFrameElement final
Member<HTMLIFrameElementSandbox> sandbox_;
Member<Policy> policy_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.cc b/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.cc
index 3e77536fe73..8603fa8bb1b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.cc
@@ -41,7 +41,7 @@ bool IsTokenSupported(const AtomicString& token) {
} // namespace
HTMLIFrameElementSandbox::HTMLIFrameElementSandbox(HTMLIFrameElement* element)
- : DOMTokenList(*element, HTMLNames::sandboxAttr) {}
+ : DOMTokenList(*element, html_names::kSandboxAttr) {}
bool HTMLIFrameElementSandbox::ValidateTokenValue(
const AtomicString& token_value,
diff --git a/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.h b/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.h
index f4bbabaa838..6feeaf414eb 100644
--- a/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.h
+++ b/chromium/third_party/blink/renderer/core/html/html_iframe_element_sandbox.h
@@ -15,11 +15,12 @@ class HTMLIFrameElement;
class HTMLIFrameElementSandbox final : public DOMTokenList {
public:
static HTMLIFrameElementSandbox* Create(HTMLIFrameElement* element) {
- return new HTMLIFrameElementSandbox(element);
+ return MakeGarbageCollected<HTMLIFrameElementSandbox>(element);
}
- private:
explicit HTMLIFrameElementSandbox(HTMLIFrameElement*);
+
+ private:
bool ValidateTokenValue(const AtomicString&, ExceptionState&) const override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_iframe_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_iframe_element_test.cc
index a7c95a8d1ea..6e57695d875 100644
--- a/chromium/third_party/blink/renderer/core/html/html_iframe_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_iframe_element_test.cc
@@ -29,20 +29,20 @@ TEST_F(HTMLIFrameElementTest, FramesUseCorrectOrigin) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcAttr, "about:blank");
+ frame_element->setAttribute(html_names::kSrcAttr, "about:blank");
scoped_refptr<const SecurityOrigin> effective_origin =
GetOriginForFeaturePolicy(frame_element);
EXPECT_TRUE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
- frame_element->setAttribute(HTMLNames::srcAttr,
+ frame_element->setAttribute(html_names::kSrcAttr,
"data:text/html;base64,PHRpdGxlPkFCQzwvdGl0bGU+");
effective_origin = GetOriginForFeaturePolicy(frame_element);
EXPECT_FALSE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
EXPECT_TRUE(effective_origin->IsOpaque());
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
effective_origin = GetOriginForFeaturePolicy(frame_element);
EXPECT_FALSE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
@@ -59,15 +59,15 @@ TEST_F(HTMLIFrameElementTest, SandboxFramesUseCorrectOrigin) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::sandboxAttr, "");
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.com/");
+ frame_element->setAttribute(html_names::kSandboxAttr, "");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.com/");
scoped_refptr<const SecurityOrigin> effective_origin =
GetOriginForFeaturePolicy(frame_element);
EXPECT_FALSE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
EXPECT_TRUE(effective_origin->IsOpaque());
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
effective_origin = GetOriginForFeaturePolicy(frame_element);
EXPECT_FALSE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
@@ -84,8 +84,8 @@ TEST_F(HTMLIFrameElementTest, SameOriginSandboxFramesUseCorrectOrigin) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::sandboxAttr, "allow-same-origin");
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.com/");
+ frame_element->setAttribute(html_names::kSandboxAttr, "allow-same-origin");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.com/");
scoped_refptr<const SecurityOrigin> effective_origin =
GetOriginForFeaturePolicy(frame_element);
EXPECT_TRUE(
@@ -103,7 +103,7 @@ TEST_F(HTMLIFrameElementTest, SrcdocFramesUseCorrectOrigin) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcdocAttr, "<title>title</title>");
+ frame_element->setAttribute(html_names::kSrcdocAttr, "<title>title</title>");
scoped_refptr<const SecurityOrigin> effective_origin =
GetOriginForFeaturePolicy(frame_element);
EXPECT_TRUE(
@@ -120,8 +120,8 @@ TEST_F(HTMLIFrameElementTest, SandboxedSrcdocFramesUseCorrectOrigin) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::sandboxAttr, "");
- frame_element->setAttribute(HTMLNames::srcdocAttr, "<title>title</title>");
+ frame_element->setAttribute(html_names::kSandboxAttr, "");
+ frame_element->setAttribute(html_names::kSrcdocAttr, "<title>title</title>");
scoped_refptr<const SecurityOrigin> effective_origin =
GetOriginForFeaturePolicy(frame_element);
EXPECT_FALSE(
@@ -140,14 +140,15 @@ TEST_F(HTMLIFrameElementTest, RelativeURLsUseCorrectOrigin) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
// Host-relative URLs should resolve to the same domain as the parent.
- frame_element->setAttribute(HTMLNames::srcAttr, "index2.html");
+ frame_element->setAttribute(html_names::kSrcAttr, "index2.html");
scoped_refptr<const SecurityOrigin> effective_origin =
GetOriginForFeaturePolicy(frame_element);
EXPECT_TRUE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
// Scheme-relative URLs should not resolve to the same domain as the parent.
- frame_element->setAttribute(HTMLNames::srcAttr, "//example.net/index2.html");
+ frame_element->setAttribute(html_names::kSrcAttr,
+ "//example.net/index2.html");
effective_origin = GetOriginForFeaturePolicy(frame_element);
EXPECT_FALSE(
effective_origin->IsSameSchemeHostPort(document->GetSecurityOrigin()));
@@ -165,7 +166,7 @@ TEST_F(HTMLIFrameElementTest, DefaultContainerPolicy) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
frame_element->UpdateContainerPolicyForTests();
const ParsedFeaturePolicy& container_policy =
@@ -183,8 +184,8 @@ TEST_F(HTMLIFrameElementTest, AllowAttributeContainerPolicy) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
- frame_element->setAttribute(HTMLNames::allowAttr, "fullscreen");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kAllowAttr, "fullscreen");
frame_element->UpdateContainerPolicyForTests();
const ParsedFeaturePolicy& container_policy1 =
@@ -197,7 +198,7 @@ TEST_F(HTMLIFrameElementTest, AllowAttributeContainerPolicy) {
EXPECT_EQ(1UL, container_policy1[0].origins.size());
EXPECT_EQ("http://example.net", container_policy1[0].origins[0].Serialize());
- frame_element->setAttribute(HTMLNames::allowAttr, "payment; fullscreen");
+ frame_element->setAttribute(html_names::kAllowAttr, "payment; fullscreen");
frame_element->UpdateContainerPolicyForTests();
const ParsedFeaturePolicy& container_policy2 =
@@ -228,9 +229,9 @@ TEST_F(HTMLIFrameElementTest, SandboxAttributeContainerPolicy) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
- frame_element->setAttribute(HTMLNames::allowAttr, "fullscreen");
- frame_element->setAttribute(HTMLNames::sandboxAttr, "");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kAllowAttr, "fullscreen");
+ frame_element->setAttribute(html_names::kSandboxAttr, "");
frame_element->UpdateContainerPolicyForTests();
const ParsedFeaturePolicy& container_policy =
@@ -255,9 +256,9 @@ TEST_F(HTMLIFrameElementTest, SameOriginSandboxAttributeContainerPolicy) {
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::srcAttr, "http://example.net/");
- frame_element->setAttribute(HTMLNames::allowAttr, "fullscreen");
- frame_element->setAttribute(HTMLNames::sandboxAttr, "allow-same-origin");
+ frame_element->setAttribute(html_names::kSrcAttr, "http://example.net/");
+ frame_element->setAttribute(html_names::kAllowAttr, "fullscreen");
+ frame_element->setAttribute(html_names::kSandboxAttr, "allow-same-origin");
frame_element->UpdateContainerPolicyForTests();
const ParsedFeaturePolicy& container_policy =
@@ -297,7 +298,7 @@ TEST_F(HTMLIFrameElementTest, ConstructContainerPolicy) {
document->UpdateSecurityOrigin(SecurityOrigin::Create(document_url));
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::allowAttr, "payment; usb");
+ frame_element->setAttribute(html_names::kAllowAttr, "payment; usb");
ParsedFeaturePolicy container_policy =
frame_element->ConstructContainerPolicy(nullptr);
EXPECT_EQ(2UL, container_policy.size());
@@ -322,7 +323,7 @@ TEST_F(HTMLIFrameElementTest, ConstructContainerPolicyWithAllowFullscreen) {
document->UpdateSecurityOrigin(SecurityOrigin::Create(document_url));
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->SetBooleanAttribute(HTMLNames::allowfullscreenAttr, true);
+ frame_element->SetBooleanAttribute(html_names::kAllowfullscreenAttr, true);
ParsedFeaturePolicy container_policy =
frame_element->ConstructContainerPolicy(nullptr);
@@ -341,8 +342,9 @@ TEST_F(HTMLIFrameElementTest, ConstructContainerPolicyWithAllowPaymentRequest) {
document->UpdateSecurityOrigin(SecurityOrigin::Create(document_url));
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::allowAttr, "usb");
- frame_element->SetBooleanAttribute(HTMLNames::allowpaymentrequestAttr, true);
+ frame_element->setAttribute(html_names::kAllowAttr, "usb");
+ frame_element->SetBooleanAttribute(html_names::kAllowpaymentrequestAttr,
+ true);
ParsedFeaturePolicy container_policy =
frame_element->ConstructContainerPolicy(nullptr);
@@ -369,9 +371,10 @@ TEST_F(HTMLIFrameElementTest, ConstructContainerPolicyWithAllowAttributes) {
document->UpdateSecurityOrigin(SecurityOrigin::Create(document_url));
HTMLIFrameElement* frame_element = HTMLIFrameElement::Create(*document);
- frame_element->setAttribute(HTMLNames::allowAttr, "payment; usb");
- frame_element->SetBooleanAttribute(HTMLNames::allowfullscreenAttr, true);
- frame_element->SetBooleanAttribute(HTMLNames::allowpaymentrequestAttr, true);
+ frame_element->setAttribute(html_names::kAllowAttr, "payment; usb");
+ frame_element->SetBooleanAttribute(html_names::kAllowfullscreenAttr, true);
+ frame_element->SetBooleanAttribute(html_names::kAllowpaymentrequestAttr,
+ true);
ParsedFeaturePolicy container_policy =
frame_element->ConstructContainerPolicy(nullptr);
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_element.cc b/chromium/third_party/blink/renderer/core/html/html_image_element.cc
index 1c6e1e5ee41..eb8a7357e23 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_image_element.cc
@@ -23,11 +23,11 @@
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/media_query_matcher.h"
#include "third_party/blink/renderer/core/css/media_values_dynamic.h"
#include "third_party/blink/renderer/core/css/parser/sizes_attribute_parser.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
@@ -67,15 +67,18 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class HTMLImageElement::ViewportChangeListener final
: public MediaQueryListListener {
public:
static ViewportChangeListener* Create(HTMLImageElement* element) {
- return new ViewportChangeListener(element);
+ return MakeGarbageCollected<ViewportChangeListener>(element);
}
+ explicit ViewportChangeListener(HTMLImageElement* element)
+ : element_(element) {}
+
void NotifyMediaQueryChanged() override {
if (element_)
element_->NotifyViewportChanged();
@@ -87,13 +90,11 @@ class HTMLImageElement::ViewportChangeListener final
}
private:
- explicit ViewportChangeListener(HTMLImageElement* element)
- : element_(element) {}
Member<HTMLImageElement> element_;
};
HTMLImageElement::HTMLImageElement(Document& document, bool created_by_parser)
- : HTMLElement(imgTag, document),
+ : HTMLElement(kImgTag, document),
image_loader_(HTMLImageLoader::Create(this)),
image_device_pixel_ratio_(1.0f),
source_(nullptr),
@@ -103,10 +104,10 @@ HTMLImageElement::HTMLImageElement(Document& document, bool created_by_parser)
is_fallback_image_(false),
should_invert_color_(false),
sizes_set_width_(false),
- referrer_policy_(kReferrerPolicyDefault) {
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {
SetHasCustomStyleCallbacks();
- if (MediaElementParserHelpers::IsMediaElement(this) &&
- !MediaElementParserHelpers::IsUnsizedMediaEnabled(document)) {
+ if (media_element_parser_helpers::IsMediaElement(this) &&
+ !document.IsFeatureEnabled(mojom::FeaturePolicyFeature::kUnsizedMedia)) {
is_default_overridden_intrinsic_size_ = true;
overridden_intrinsic_size_ =
IntSize(LayoutReplaced::kDefaultWidth, LayoutReplaced::kDefaultHeight);
@@ -114,12 +115,13 @@ HTMLImageElement::HTMLImageElement(Document& document, bool created_by_parser)
}
HTMLImageElement* HTMLImageElement::Create(Document& document) {
- return new HTMLImageElement(document);
+ return MakeGarbageCollected<HTMLImageElement>(document);
}
HTMLImageElement* HTMLImageElement::Create(Document& document,
const CreateElementFlags flags) {
- return new HTMLImageElement(document, flags.IsCreatedByParser());
+ return MakeGarbageCollected<HTMLImageElement>(document,
+ flags.IsCreatedByParser());
}
HTMLImageElement::~HTMLImageElement() = default;
@@ -146,14 +148,14 @@ void HTMLImageElement::NotifyViewportChanged() {
}
HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document) {
- HTMLImageElement* image = new HTMLImageElement(document);
+ HTMLImageElement* image = MakeGarbageCollected<HTMLImageElement>(document);
image->element_created_by_parser_ = false;
return image;
}
HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document,
unsigned width) {
- HTMLImageElement* image = new HTMLImageElement(document);
+ HTMLImageElement* image = MakeGarbageCollected<HTMLImageElement>(document);
image->setWidth(width);
image->element_created_by_parser_ = false;
return image;
@@ -162,7 +164,7 @@ HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document,
HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document,
unsigned width,
unsigned height) {
- HTMLImageElement* image = new HTMLImageElement(document);
+ HTMLImageElement* image = MakeGarbageCollected<HTMLImageElement>(document);
image->setWidth(width);
image->setHeight(height);
image->element_created_by_parser_ = false;
@@ -171,9 +173,9 @@ HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document,
bool HTMLImageElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == widthAttr || name == heightAttr || name == borderAttr ||
- name == vspaceAttr || name == hspaceAttr || name == alignAttr ||
- name == valignAttr)
+ if (name == kWidthAttr || name == kHeightAttr || name == kBorderAttr ||
+ name == kVspaceAttr || name == kHspaceAttr || name == kAlignAttr ||
+ name == kValignAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -182,21 +184,21 @@ void HTMLImageElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == widthAttr) {
+ if (name == kWidthAttr) {
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
- } else if (name == borderAttr) {
+ } else if (name == kBorderAttr) {
ApplyBorderAttributeToStyle(value, style);
- } else if (name == vspaceAttr) {
+ } else if (name == kVspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
- } else if (name == hspaceAttr) {
+ } else if (name == kHspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
- } else if (name == alignAttr) {
+ } else if (name == kAlignAttr) {
ApplyAlignmentAttributeToStyle(value, style);
- } else if (name == valignAttr) {
+ } else if (name == kValignAttr) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign,
value);
} else {
@@ -205,7 +207,7 @@ void HTMLImageElement::CollectStyleForPresentationAttribute(
}
const AtomicString HTMLImageElement::ImageSourceURL() const {
- return best_fit_image_url_.IsNull() ? FastGetAttribute(srcAttr)
+ return best_fit_image_url_.IsNull() ? FastGetAttribute(kSrcAttr)
: best_fit_image_url_;
}
@@ -273,19 +275,19 @@ void HTMLImageElement::SetBestFitURLAndDPRFromImageCandidate(
void HTMLImageElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == altAttr || name == titleAttr) {
+ if (name == kAltAttr || name == kTitleAttr) {
if (UserAgentShadowRoot()) {
Element* text = UserAgentShadowRoot()->getElementById("alttext");
String alt_text_content = AltText();
if (text && text->textContent() != alt_text_content)
text->setTextContent(alt_text_content);
}
- } else if (name == srcAttr || name == srcsetAttr || name == sizesAttr) {
+ } else if (name == kSrcAttr || name == kSrcsetAttr || name == kSizesAttr) {
SelectSourceURL(ImageLoader::kUpdateIgnorePreviousError);
- } else if (name == usemapAttr) {
+ } else if (name == kUsemapAttr) {
SetIsLink(!params.new_value.IsNull());
- } else if (name == referrerpolicyAttr) {
- referrer_policy_ = kReferrerPolicyDefault;
+ } else if (name == kReferrerpolicyAttr) {
+ referrer_policy_ = network::mojom::ReferrerPolicy::kDefault;
if (!params.new_value.IsNull()) {
SecurityPolicy::ReferrerPolicyFromString(
params.new_value, kSupportReferrerPolicyLegacyKeywords,
@@ -293,15 +295,15 @@ void HTMLImageElement::ParseAttribute(
UseCounter::Count(GetDocument(),
WebFeature::kHTMLImageElementReferrerPolicyAttribute);
}
- } else if (name == decodingAttr) {
+ } else if (name == kDecodingAttr) {
UseCounter::Count(GetDocument(), WebFeature::kImageDecodingAttribute);
decoding_mode_ = ParseImageDecodingMode(params.new_value);
- } else if (name == intrinsicsizeAttr &&
+ } else if (name == kIntrinsicsizeAttr &&
RuntimeEnabledFeatures::
ExperimentalProductivityFeaturesEnabled()) {
String message;
bool intrinsic_size_changed =
- MediaElementParserHelpers::ParseIntrinsicSizeAttribute(
+ media_element_parser_helpers::ParseIntrinsicSizeAttribute(
params.new_value, this, &overridden_intrinsic_size_,
&is_default_overridden_intrinsic_size_, &message);
if (!message.IsEmpty()) {
@@ -312,8 +314,9 @@ void HTMLImageElement::ParseAttribute(
if (intrinsic_size_changed && GetLayoutObject() &&
GetLayoutObject()->IsLayoutImage())
ToLayoutImage(GetLayoutObject())->IntrinsicSizeChanged();
- } else if (name == lazyloadAttr &&
- EqualIgnoringASCIICase(params.new_value, "off")) {
+ } else if (name == kLazyloadAttr &&
+ EqualIgnoringASCIICase(params.new_value, "off") &&
+ !GetDocument().IsLazyLoadPolicyEnforced()) {
GetImageLoader().LoadDeferredImage(referrer_policy_);
} else {
HTMLElement::ParseAttribute(params);
@@ -324,11 +327,11 @@ String HTMLImageElement::AltText() const {
// lets figure out the alt text.. magic stuff
// http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
// also heavily discussed by Hixie on bugzilla
- const AtomicString& alt = FastGetAttribute(altAttr);
+ const AtomicString& alt = FastGetAttribute(kAltAttr);
if (!alt.IsNull())
return alt;
// fall back to title attribute
- return FastGetAttribute(titleAttr);
+ return FastGetAttribute(kTitleAttr);
}
static bool SupportedImageType(const String& type) {
@@ -355,14 +358,14 @@ ImageCandidate HTMLImageElement::FindBestFitImageFromPictureParent() {
continue;
HTMLSourceElement* source = ToHTMLSourceElement(child);
- if (!source->FastGetAttribute(srcAttr).IsNull()) {
+ if (!source->FastGetAttribute(kSrcAttr).IsNull()) {
Deprecation::CountDeprecation(GetDocument(),
WebFeature::kPictureSourceSrc);
}
- String srcset = source->FastGetAttribute(srcsetAttr);
+ String srcset = source->FastGetAttribute(kSrcsetAttr);
if (srcset.IsEmpty())
continue;
- String type = source->FastGetAttribute(typeAttr);
+ String type = source->FastGetAttribute(kTypeAttr);
if (!type.IsEmpty() && !SupportedImageType(type))
continue;
@@ -371,7 +374,7 @@ ImageCandidate HTMLImageElement::FindBestFitImageFromPictureParent() {
ImageCandidate candidate = BestFitSourceForSrcsetAttribute(
GetDocument().DevicePixelRatio(), SourceSize(*source),
- source->FastGetAttribute(srcsetAttr), &GetDocument());
+ source->FastGetAttribute(kSrcsetAttr), &GetDocument());
if (candidate.IsEmpty())
continue;
source_ = source;
@@ -473,7 +476,7 @@ unsigned HTMLImageElement::width() {
if (!GetLayoutObject()) {
// check the attribute first for an explicit pixel value
unsigned width = 0;
- if (ParseHTMLNonNegativeInteger(getAttribute(widthAttr), width))
+ if (ParseHTMLNonNegativeInteger(getAttribute(kWidthAttr), width))
return width;
// if the image is available, use its width
@@ -494,7 +497,7 @@ unsigned HTMLImageElement::height() {
if (!GetLayoutObject()) {
// check the attribute first for an explicit pixel value
unsigned height = 0;
- if (ParseHTMLNonNegativeInteger(getAttribute(heightAttr), height))
+ if (ParseHTMLNonNegativeInteger(getAttribute(kHeightAttr), height))
return height;
// if the image is available, use its height
@@ -572,27 +575,28 @@ const String& HTMLImageElement::currentSrc() const {
}
bool HTMLImageElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr || attribute.GetName() == lowsrcAttr ||
- attribute.GetName() == longdescAttr ||
- (attribute.GetName() == usemapAttr && attribute.Value()[0] != '#') ||
+ return attribute.GetName() == kSrcAttr ||
+ attribute.GetName() == kLowsrcAttr ||
+ attribute.GetName() == kLongdescAttr ||
+ (attribute.GetName() == kUsemapAttr && attribute.Value()[0] != '#') ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLImageElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == srcAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kSrcAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLImageElement::SubResourceAttributeName() const {
- return srcAttr;
+ return kSrcAttr;
}
bool HTMLImageElement::draggable() const {
// Image elements are draggable by default.
- return !DeprecatedEqualIgnoringCase(getAttribute(draggableAttr), "false");
+ return !DeprecatedEqualIgnoringCase(getAttribute(kDraggableAttr), "false");
}
void HTMLImageElement::setHeight(unsigned value) {
- SetUnsignedIntegralAttribute(heightAttr, value);
+ SetUnsignedIntegralAttribute(kHeightAttr, value);
}
IntSize HTMLImageElement::GetOverriddenIntrinsicSize() const {
@@ -608,20 +612,20 @@ IntSize HTMLImageElement::GetOverriddenIntrinsicSize() const {
}
KURL HTMLImageElement::Src() const {
- return GetDocument().CompleteURL(getAttribute(srcAttr));
+ return GetDocument().CompleteURL(getAttribute(kSrcAttr));
}
void HTMLImageElement::SetSrc(const String& value) {
- setAttribute(srcAttr, AtomicString(value));
+ setAttribute(kSrcAttr, AtomicString(value));
}
void HTMLImageElement::SetSrc(const USVStringOrTrustedURL& value,
ExceptionState& exception_state) {
- setAttribute(srcAttr, value, exception_state);
+ setAttribute(kSrcAttr, value, exception_state);
}
void HTMLImageElement::setWidth(unsigned value) {
- SetUnsignedIntegralAttribute(widthAttr, value);
+ SetUnsignedIntegralAttribute(kWidthAttr, value);
}
int HTMLImageElement::x() const {
@@ -662,10 +666,10 @@ void HTMLImageElement::DidMoveToNewDocument(Document& old_document) {
}
bool HTMLImageElement::IsServerMap() const {
- if (!FastHasAttribute(ismapAttr))
+ if (!FastHasAttribute(kIsmapAttr))
return false;
- const AtomicString& usemap = FastGetAttribute(usemapAttr);
+ const AtomicString& usemap = FastGetAttribute(kUsemapAttr);
// If the usemap attribute starts with '#', it refers to a map element in
// the document.
@@ -685,7 +689,7 @@ Image* HTMLImageElement::ImageContents() {
}
bool HTMLImageElement::IsInteractiveContent() const {
- return FastHasAttribute(usemapAttr);
+ return FastHasAttribute(kUsemapAttr);
}
FloatSize HTMLImageElement::DefaultDestinationSize(
@@ -709,7 +713,7 @@ FloatSize HTMLImageElement::DefaultDestinationSize(
static bool SourceSizeValue(const Element* element,
Document& current_document,
float& source_size) {
- String sizes = element->FastGetAttribute(sizesAttr);
+ String sizes = element->FastGetAttribute(kSizesAttr);
bool exists = !sizes.IsNull();
if (exists)
UseCounter::Count(current_document, WebFeature::kSizes);
@@ -749,7 +753,7 @@ void HTMLImageElement::SelectSourceURL(
if (candidate.IsEmpty()) {
candidate = BestFitSourceForImageAttributes(
GetDocument().DevicePixelRatio(), SourceSize(*this),
- FastGetAttribute(srcAttr), FastGetAttribute(srcsetAttr),
+ FastGetAttribute(kSrcAttr), FastGetAttribute(kSrcsetAttr),
&GetDocument());
}
SetBestFitURLAndDPRFromImageCandidate(candidate);
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_element.h b/chromium/third_party/blink/renderer/core/html/html_image_element.h
index d82664737ac..63817bf8b70 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_image_element.h
@@ -70,6 +70,7 @@ class CORE_EXPORT HTMLImageElement final
unsigned width,
unsigned height);
+ explicit HTMLImageElement(Document&, bool created_by_parser = false);
~HTMLImageElement() override;
void Trace(blink::Visitor*) override;
@@ -182,8 +183,6 @@ class CORE_EXPORT HTMLImageElement final
kCollapsed
};
- explicit HTMLImageElement(Document&, bool created_by_parser = false);
-
void DidMoveToNewDocument(Document& old_document) override;
void DidAddUserAgentShadowRoot(ShadowRoot&) override;
@@ -241,7 +240,7 @@ class CORE_EXPORT HTMLImageElement final
bool sizes_set_width_;
bool is_default_overridden_intrinsic_size_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
IntSize overridden_intrinsic_size_;
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_image_element_test.cc
index d3683c93ee6..1e3ae6781d1 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_image_element_test.cc
@@ -23,19 +23,19 @@ class HTMLImageElementTest : public PageTestBase {
TEST_F(HTMLImageElementTest, width) {
auto* image = HTMLImageElement::Create(GetDocument());
- image->setAttribute(HTMLNames::widthAttr, "400");
+ image->setAttribute(html_names::kWidthAttr, "400");
// TODO(yoav): `width` does not impact resourceWidth until we resolve
// https://github.com/ResponsiveImagesCG/picture-element/issues/268
EXPECT_EQ(500, image->GetResourceWidth().width);
- image->setAttribute(HTMLNames::sizesAttr, "100vw");
+ image->setAttribute(html_names::kSizesAttr, "100vw");
EXPECT_EQ(500, image->GetResourceWidth().width);
}
TEST_F(HTMLImageElementTest, sourceSize) {
auto* image = HTMLImageElement::Create(GetDocument());
- image->setAttribute(HTMLNames::widthAttr, "400");
+ image->setAttribute(html_names::kWidthAttr, "400");
EXPECT_EQ(kViewportWidth, image->SourceSize(*image));
- image->setAttribute(HTMLNames::sizesAttr, "50vw");
+ image->setAttribute(html_names::kSizesAttr, "50vw");
EXPECT_EQ(250, image->SourceSize(*image));
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.cc b/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.cc
index c73fb09b4ed..8f1f32cc16d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.cc
@@ -20,15 +20,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool NoImageSourceSpecified(const Element& element) {
- bool no_src_specified = !element.hasAttribute(srcAttr) ||
- element.getAttribute(srcAttr).IsNull() ||
- element.getAttribute(srcAttr).IsEmpty();
- bool no_srcset_specified = !element.hasAttribute(srcsetAttr) ||
- element.getAttribute(srcsetAttr).IsNull();
- return no_src_specified && no_srcset_specified;
+ return element.getAttribute(kSrcAttr).IsEmpty();
}
static bool ElementRepresentsNothing(const Element& element) {
@@ -57,22 +52,22 @@ void HTMLImageFallbackHelper::CreateAltTextShadowTree(Element& element) {
HTMLSpanElement* container = HTMLSpanElement::Create(element.GetDocument());
root.AppendChild(container);
- container->setAttribute(idAttr, AtomicString("alttext-container"));
+ container->setAttribute(kIdAttr, AtomicString("alttext-container"));
HTMLImageElement* broken_image =
HTMLImageElement::Create(element.GetDocument());
container->AppendChild(broken_image);
broken_image->SetIsFallbackImage();
- broken_image->setAttribute(idAttr, AtomicString("alttext-image"));
- broken_image->setAttribute(widthAttr, AtomicString("16"));
- broken_image->setAttribute(heightAttr, AtomicString("16"));
- broken_image->setAttribute(alignAttr, AtomicString("left"));
+ broken_image->setAttribute(kIdAttr, AtomicString("alttext-image"));
+ broken_image->setAttribute(kWidthAttr, AtomicString("16"));
+ broken_image->setAttribute(kHeightAttr, AtomicString("16"));
+ broken_image->setAttribute(kAlignAttr, AtomicString("left"));
broken_image->SetInlineStyleProperty(CSSPropertyMargin, 0,
CSSPrimitiveValue::UnitType::kPixels);
HTMLSpanElement* alt_text = HTMLSpanElement::Create(element.GetDocument());
container->AppendChild(alt_text);
- alt_text->setAttribute(idAttr, AtomicString("alttext"));
+ alt_text->setAttribute(kIdAttr, AtomicString("alttext"));
Text* text =
Text::Create(element.GetDocument(), ToHTMLElement(element).AltText());
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_loader.cc b/chromium/third_party/blink/renderer/core/html/html_image_loader.cc
index 037b0f90ef3..b7b9d595140 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_loader.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_image_loader.cc
@@ -27,14 +27,11 @@
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/html_object_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loading_log.h"
namespace blink {
-using namespace HTMLNames;
-
HTMLImageLoader::HTMLImageLoader(Element* element) : ImageLoader(element) {}
HTMLImageLoader::~HTMLImageLoader() = default;
@@ -53,7 +50,7 @@ void HTMLImageLoader::DispatchLoadEvent() {
error_occurred = (GetContent()->GetResponse().HttpStatusCode() >= 400);
}
GetElement()->DispatchEvent(*Event::Create(
- error_occurred ? EventTypeNames::error : EventTypeNames::load));
+ error_occurred ? event_type_names::kError : event_type_names::kLoad));
}
void HTMLImageLoader::NoImageResourceToLoad() {
@@ -90,7 +87,7 @@ void HTMLImageLoader::ImageNotifyFinished(ImageResourceContent*) {
if ((load_error || cached_image->GetResponse().HttpStatusCode() >= 400) &&
IsHTMLObjectElement(*element))
- ToHTMLObjectElement(element)->RenderFallbackContent();
+ ToHTMLObjectElement(element)->RenderFallbackContent(nullptr);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_loader.h b/chromium/third_party/blink/renderer/core/html/html_image_loader.h
index 8fdc05c1d65..d4155e1a354 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_loader.h
+++ b/chromium/third_party/blink/renderer/core/html/html_image_loader.h
@@ -31,8 +31,10 @@ namespace blink {
class CORE_EXPORT HTMLImageLoader final : public ImageLoader {
public:
static HTMLImageLoader* Create(Element* element) {
- return new HTMLImageLoader(element);
+ return MakeGarbageCollected<HTMLImageLoader>(element);
}
+
+ explicit HTMLImageLoader(Element*);
~HTMLImageLoader() override;
void DispatchLoadEvent() override;
@@ -41,7 +43,6 @@ class CORE_EXPORT HTMLImageLoader final : public ImageLoader {
String DebugName() const override { return "HTMLImageLoader"; }
private:
- explicit HTMLImageLoader(Element*);
void NoImageResourceToLoad() override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_li_element.cc b/chromium/third_party/blink/renderer/core/html/html_li_element.cc
index 30f2e50b133..15953cd93be 100644
--- a/chromium/third_party/blink/renderer/core/html/html_li_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_li_element.cc
@@ -22,7 +22,7 @@
#include "third_party/blink/renderer/core/html/html_li_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
@@ -32,15 +32,15 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLLIElement::HTMLLIElement(Document& document)
- : HTMLElement(liTag, document) {}
+ : HTMLElement(kLiTag, document) {}
DEFINE_NODE_FACTORY(HTMLLIElement)
bool HTMLLIElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == typeAttr)
+ if (name == kTypeAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -71,7 +71,7 @@ void HTMLLIElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == typeAttr) {
+ if (name == kTypeAttr) {
CSSValueID type_value = ListTypeToCSSValueID(value);
if (type_value != CSSValueInvalid)
AddPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType,
@@ -82,7 +82,7 @@ void HTMLLIElement::CollectStyleForPresentationAttribute(
}
void HTMLLIElement::ParseAttribute(const AttributeModificationParams& params) {
- if (params.name == valueAttr) {
+ if (params.name == kValueAttr) {
if (ListItemOrdinal* ordinal = ListItemOrdinal::Get(*this))
ParseValue(params.new_value, ordinal);
} else {
@@ -113,7 +113,7 @@ void HTMLLIElement::AttachLayoutTree(AttachContext& context) {
if (!list_node)
ordinal->SetNotInList(true, *this);
- ParseValue(FastGetAttribute(valueAttr), ordinal);
+ ParseValue(FastGetAttribute(kValueAttr), ordinal);
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_link_element.cc b/chromium/third_party/blink/renderer/core/html/html_link_element.cc
index a182923316f..8b8de076175 100644
--- a/chromium/third_party/blink/renderer/core/html/html_link_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_link_element.cc
@@ -47,20 +47,20 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLLinkElement::HTMLLinkElement(Document& document,
const CreateElementFlags flags)
- : HTMLElement(linkTag, document),
+ : HTMLElement(kLinkTag, document),
link_loader_(LinkLoader::Create(this)),
- referrer_policy_(kReferrerPolicyDefault),
- sizes_(DOMTokenList::Create(*this, HTMLNames::sizesAttr)),
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
+ sizes_(DOMTokenList::Create(*this, html_names::kSizesAttr)),
rel_list_(RelList::Create(this)),
created_by_parser_(flags.IsCreatedByParser()) {}
HTMLLinkElement* HTMLLinkElement::Create(Document& document,
const CreateElementFlags flags) {
- return new HTMLLinkElement(document, flags);
+ return MakeGarbageCollected<HTMLLinkElement>(document, flags);
}
HTMLLinkElement::~HTMLLinkElement() = default;
@@ -74,31 +74,31 @@ void HTMLLinkElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == relAttr) {
+ if (name == kRelAttr) {
rel_attribute_ = LinkRelAttribute(value);
if (rel_attribute_.IsImport()) {
Deprecation::CountDeprecation(GetDocument(), WebFeature::kHTMLImports);
}
rel_list_->DidUpdateAttributeValue(params.old_value, value);
Process();
- } else if (name == hrefAttr) {
+ } else if (name == kHrefAttr) {
// Log href attribute before logging resource fetching in process().
LogUpdateAttributeIfIsolatedWorldAndInDocument("link", params);
Process();
- } else if (name == typeAttr) {
+ } else if (name == kTypeAttr) {
type_ = value;
Process();
- } else if (name == asAttr) {
+ } else if (name == kAsAttr) {
as_ = value;
Process();
- } else if (name == referrerpolicyAttr) {
+ } else if (name == kReferrerpolicyAttr) {
if (!value.IsNull()) {
SecurityPolicy::ReferrerPolicyFromString(
value, kDoNotSupportReferrerPolicyLegacyKeywords, &referrer_policy_);
UseCounter::Count(GetDocument(),
WebFeature::kHTMLLinkElementReferrerPolicyAttribute);
}
- } else if (name == sizesAttr) {
+ } else if (name == kSizesAttr) {
sizes_->DidUpdateAttributeValue(params.old_value, value);
WebVector<WebSize> web_icon_sizes =
WebIconSizesParser::ParseIconSizes(value);
@@ -106,25 +106,25 @@ void HTMLLinkElement::ParseAttribute(
for (wtf_size_t i = 0; i < icon_sizes_.size(); ++i)
icon_sizes_[i] = web_icon_sizes[i];
Process();
- } else if (name == mediaAttr) {
+ } else if (name == kMediaAttr) {
media_ = value.DeprecatedLower();
Process();
- } else if (name == scopeAttr) {
+ } else if (name == kScopeAttr) {
scope_ = value;
Process();
- } else if (name == integrityAttr) {
+ } else if (name == kIntegrityAttr) {
integrity_ = value;
- } else if (name == importanceAttr &&
+ } else if (name == kImportanceAttr &&
RuntimeEnabledFeatures::PriorityHintsEnabled()) {
importance_ = value;
- } else if (name == disabledAttr) {
+ } else if (name == kDisabledAttr) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLLinkElementDisabled);
if (params.reason == AttributeModificationReason::kByParser)
UseCounter::Count(GetDocument(), WebFeature::kHTMLLinkElementDisabledByParser);
if (LinkStyle* link = GetLinkStyle())
link->SetDisabledState(!value.IsNull());
} else {
- if (name == titleAttr) {
+ if (name == kTitleAttr) {
if (LinkStyle* link = GetLinkStyle())
link->SetSheetTitle(value);
}
@@ -134,7 +134,7 @@ void HTMLLinkElement::ParseAttribute(
}
bool HTMLLinkElement::ShouldLoadLink() {
- const KURL& href = GetNonEmptyURLAttribute(hrefAttr);
+ const KURL& href = GetNonEmptyURLAttribute(kHrefAttr);
return (IsInDocumentTree() ||
(isConnected() && rel_attribute_.IsStyleSheet())) &&
!href.PotentiallyDanglingMarkup();
@@ -177,7 +177,7 @@ LinkResource* HTMLLinkElement::LinkResourceToProcess() {
link_ = LinkManifest::Create(this);
} else {
LinkStyle* link = LinkStyle::Create(this);
- if (FastHasAttribute(disabledAttr)) {
+ if (FastHasAttribute(kDisabledAttr)) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLLinkElementDisabled);
link->SetDisabledState(true);
}
@@ -214,7 +214,7 @@ void HTMLLinkElement::Process() {
Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto(
ContainerNode& insertion_point) {
HTMLElement::InsertedInto(insertion_point);
- LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("link", kRelAttr, kHrefAttr);
if (!insertion_point.isConnected())
return kInsertionDone;
DCHECK(isConnected());
@@ -271,28 +271,28 @@ bool HTMLLinkElement::StyleSheetIsLoading() const {
}
void HTMLLinkElement::LinkLoaded() {
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
}
void HTMLLinkElement::LinkLoadingErrored() {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
void HTMLLinkElement::DidStartLinkPrerender() {
- DispatchEvent(*Event::Create(EventTypeNames::webkitprerenderstart));
+ DispatchEvent(*Event::Create(event_type_names::kWebkitprerenderstart));
}
void HTMLLinkElement::DidStopLinkPrerender() {
- DispatchEvent(*Event::Create(EventTypeNames::webkitprerenderstop));
+ DispatchEvent(*Event::Create(event_type_names::kWebkitprerenderstop));
}
void HTMLLinkElement::DidSendLoadForLinkPrerender() {
- DispatchEvent(*Event::Create(EventTypeNames::webkitprerenderload));
+ DispatchEvent(*Event::Create(event_type_names::kWebkitprerenderload));
}
void HTMLLinkElement::DidSendDOMContentLoadedForLinkPrerender() {
DispatchEvent(
- *Event::Create(EventTypeNames::webkitprerenderdomcontentloaded));
+ *Event::Create(event_type_names::kWebkitprerenderdomcontentloaded));
}
scoped_refptr<base::SingleThreadTaskRunner>
@@ -340,41 +340,41 @@ void HTMLLinkElement::StartLoadingDynamicSheet() {
}
bool HTMLLinkElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName().LocalName() == hrefAttr ||
+ return attribute.GetName().LocalName() == kHrefAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLLinkElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == hrefAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kHrefAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLLinkElement::SubResourceAttributeName() const {
// If the link element is not css, ignore it.
- if (DeprecatedEqualIgnoringCase(getAttribute(typeAttr), "text/css")) {
+ if (DeprecatedEqualIgnoringCase(getAttribute(kTypeAttr), "text/css")) {
// FIXME: Add support for extracting links of sub-resources which
// are inside style-sheet such as @import, @font-face, url(), etc.
- return hrefAttr;
+ return kHrefAttr;
}
return HTMLElement::SubResourceAttributeName();
}
KURL HTMLLinkElement::Href() const {
- const String& url = getAttribute(hrefAttr);
+ const String& url = getAttribute(kHrefAttr);
if (url.IsEmpty())
return KURL();
return GetDocument().CompleteURL(url);
}
const AtomicString& HTMLLinkElement::Rel() const {
- return getAttribute(relAttr);
+ return getAttribute(kRelAttr);
}
const AtomicString& HTMLLinkElement::GetType() const {
- return getAttribute(typeAttr);
+ return getAttribute(kTypeAttr);
}
bool HTMLLinkElement::Async() const {
- return FastHasAttribute(HTMLNames::asyncAttr);
+ return FastHasAttribute(html_names::kAsyncAttr);
}
IconType HTMLLinkElement::GetIconType() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_link_element.h b/chromium/third_party/blink/renderer/core/html/html_link_element.h
index 0bdfb69d802..89f692587bc 100644
--- a/chromium/third_party/blink/renderer/core/html/html_link_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_link_element.h
@@ -53,6 +53,8 @@ class CORE_EXPORT HTMLLinkElement final : public HTMLElement,
public:
static HTMLLinkElement* Create(Document&, const CreateElementFlags);
+
+ HTMLLinkElement(Document&, const CreateElementFlags);
~HTMLLinkElement() override;
// Returns attributes that should be checked against Trusted Types
@@ -65,7 +67,9 @@ class CORE_EXPORT HTMLLinkElement final : public HTMLElement,
String AsValue() const { return as_; }
String IntegrityValue() const { return integrity_; }
String ImportanceValue() const { return importance_; }
- ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
const LinkRelAttribute& RelAttribute() const { return rel_attribute_; }
DOMTokenList& relList() const {
return static_cast<DOMTokenList&>(*rel_list_);
@@ -121,8 +125,6 @@ class CORE_EXPORT HTMLLinkElement final : public HTMLElement,
void Trace(blink::Visitor*) override;
private:
- HTMLLinkElement(Document&, const CreateElementFlags);
-
LinkStyle* GetLinkStyle() const;
LinkImport* GetLinkImport() const;
LinkResource* LinkResourceToProcess();
@@ -165,7 +167,7 @@ class CORE_EXPORT HTMLLinkElement final : public HTMLElement,
String media_;
String integrity_;
String importance_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
Member<DOMTokenList> sizes_;
Vector<IntSize> icon_sizes_;
TraceWrapperMember<RelList> rel_list_;
diff --git a/chromium/third_party/blink/renderer/core/html/html_link_element.idl b/chromium/third_party/blink/renderer/core/html/html_link_element.idl
index 0a34d5da79c..933f8083b59 100644
--- a/chromium/third_party/blink/renderer/core/html/html_link_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_link_element.idl
@@ -36,6 +36,8 @@ interface HTMLLinkElement : HTMLElement {
[CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy;
[PutForwards=value] readonly attribute DOMTokenList sizes;
[CEReactions, RuntimeEnabled=PriorityHints, Reflect, ReflectOnly=("low", "auto", "high"), ReflectMissing="auto", ReflectInvalid="auto"] attribute DOMString importance;
+ [RuntimeEnabled=PreloadImageSrcSet, CEReactions, Reflect] attribute DOMString imageSrcset;
+ [RuntimeEnabled=PreloadImageSrcSet, CEReactions, Reflect] attribute DOMString imageSizes;
// obsolete members
// https://html.spec.whatwg.org/#HTMLLinkElement-partial
diff --git a/chromium/third_party/blink/renderer/core/html/html_link_element_sizes_attribute_test.cc b/chromium/third_party/blink/renderer/core/html/html_link_element_sizes_attribute_test.cc
index af088cc6965..558025102e5 100644
--- a/chromium/third_party/blink/renderer/core/html/html_link_element_sizes_attribute_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_link_element_sizes_attribute_test.cc
@@ -20,7 +20,7 @@ TEST(HTMLLinkElementSizesAttributeTest,
DOMTokenList* sizes = link->sizes();
EXPECT_EQ(g_null_atom, sizes->value());
sizes->setValue(" a b c ");
- EXPECT_EQ(" a b c ", link->getAttribute(HTMLNames::sizesAttr));
+ EXPECT_EQ(" a b c ", link->getAttribute(html_names::kSizesAttr));
EXPECT_EQ(" a b c ", sizes->value());
}
@@ -31,7 +31,7 @@ TEST(HTMLLinkElementSizesAttributeTest,
HTMLLinkElement::Create(*document, CreateElementFlags());
DOMTokenList* sizes = link->sizes();
EXPECT_EQ(g_null_atom, sizes->value());
- link->setAttribute(HTMLNames::sizesAttr, "y x ");
+ link->setAttribute(html_names::kSizesAttr, "y x ");
EXPECT_EQ("y x ", sizes->value());
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_map_element.cc b/chromium/third_party/blink/renderer/core/html/html_map_element.cc
index d7eb12070cf..f4dfd2d0934 100644
--- a/chromium/third_party/blink/renderer/core/html/html_map_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_map_element.cc
@@ -33,10 +33,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLMapElement::HTMLMapElement(Document& document)
- : HTMLElement(mapTag, document) {
+ : HTMLElement(kMapTag, document) {
UseCounter::Count(document, WebFeature::kMapElement);
}
@@ -66,7 +66,7 @@ HTMLImageElement* HTMLMapElement::ImageElement() {
// beginning, which has to be stripped off.
HTMLImageElement& image_element = ToHTMLImageElement(*curr);
String use_map_name =
- image_element.getAttribute(usemapAttr).GetString().Substring(1);
+ image_element.getAttribute(kUsemapAttr).GetString().Substring(1);
if (use_map_name == name_)
return &image_element;
}
@@ -79,8 +79,8 @@ void HTMLMapElement::ParseAttribute(const AttributeModificationParams& params) {
// Either the id or name will be used depending on the order the attributes
// are parsed.
- if (params.name == idAttr || params.name == nameAttr) {
- if (params.name == idAttr) {
+ if (params.name == kIdAttr || params.name == kNameAttr) {
+ if (params.name == kIdAttr) {
// Call base class so that hasID bit gets set.
HTMLElement::ParseAttribute(params);
if (GetDocument().IsHTMLDocument())
diff --git a/chromium/third_party/blink/renderer/core/html/html_marquee_element.cc b/chromium/third_party/blink/renderer/core/html/html_marquee_element.cc
index c13307136df..a1edeaf400f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_marquee_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_marquee_element.cc
@@ -33,9 +33,9 @@
#include "third_party/blink/renderer/core/animation/optional_effect_timing.h"
#include "third_party/blink/renderer/core/animation/string_keyframe.h"
#include "third_party/blink/renderer/core/animation/timing_input.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_style_declaration.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
#include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h"
@@ -52,12 +52,13 @@
namespace blink {
inline HTMLMarqueeElement::HTMLMarqueeElement(Document& document)
- : HTMLElement(HTMLNames::marqueeTag, document) {
+ : HTMLElement(html_names::kMarqueeTag, document) {
UseCounter::Count(document, WebFeature::kHTMLMarqueeElement);
}
HTMLMarqueeElement* HTMLMarqueeElement::Create(Document& document) {
- HTMLMarqueeElement* marquee_element = new HTMLMarqueeElement(document);
+ HTMLMarqueeElement* marquee_element =
+ MakeGarbageCollected<HTMLMarqueeElement>(document);
marquee_element->EnsureUserAgentShadowRoot();
return marquee_element;
}
@@ -111,7 +112,7 @@ class HTMLMarqueeElement::AnimationFinished final : public EventListener {
return this == &that;
}
- void handleEvent(ExecutionContext*, Event*) override {
+ void Invoke(ExecutionContext*, Event*) override {
++marquee_->loop_count_;
marquee_->start();
}
@@ -151,7 +152,7 @@ bool HTMLMarqueeElement::IsHorizontal() const {
unsigned HTMLMarqueeElement::scrollAmount() const {
unsigned scroll_amount = 0;
- AtomicString value = FastGetAttribute(HTMLNames::scrollamountAttr);
+ AtomicString value = FastGetAttribute(html_names::kScrollamountAttr);
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, scroll_amount) ||
scroll_amount > 0x7fffffffu)
return kDefaultScrollAmount;
@@ -159,13 +160,13 @@ unsigned HTMLMarqueeElement::scrollAmount() const {
}
void HTMLMarqueeElement::setScrollAmount(unsigned value) {
- SetUnsignedIntegralAttribute(HTMLNames::scrollamountAttr, value,
+ SetUnsignedIntegralAttribute(html_names::kScrollamountAttr, value,
kDefaultScrollAmount);
}
unsigned HTMLMarqueeElement::scrollDelay() const {
unsigned scroll_delay = 0;
- AtomicString value = FastGetAttribute(HTMLNames::scrolldelayAttr);
+ AtomicString value = FastGetAttribute(html_names::kScrolldelayAttr);
if (value.IsEmpty() || !ParseHTMLNonNegativeInteger(value, scroll_delay) ||
scroll_delay > 0x7fffffffu)
return kDefaultScrollDelayMS;
@@ -173,13 +174,13 @@ unsigned HTMLMarqueeElement::scrollDelay() const {
}
void HTMLMarqueeElement::setScrollDelay(unsigned value) {
- SetUnsignedIntegralAttribute(HTMLNames::scrolldelayAttr, value,
+ SetUnsignedIntegralAttribute(html_names::kScrolldelayAttr, value,
kDefaultScrollDelayMS);
}
int HTMLMarqueeElement::loop() const {
bool ok;
- int loop = FastGetAttribute(HTMLNames::loopAttr).ToInt(&ok);
+ int loop = FastGetAttribute(html_names::kLoopAttr).ToInt(&ok);
if (!ok || loop <= 0)
return kDefaultLoopLimit;
return loop;
@@ -193,7 +194,7 @@ void HTMLMarqueeElement::setLoop(int value, ExceptionState& exception_state) {
") is neither positive nor -1.");
return;
}
- SetIntegralAttribute(HTMLNames::loopAttr, value);
+ SetIntegralAttribute(html_names::kLoopAttr, value);
}
void HTMLMarqueeElement::start() {
@@ -201,7 +202,7 @@ void HTMLMarqueeElement::start() {
return;
RequestAnimationFrameCallback* callback =
- new RequestAnimationFrameCallback(this);
+ MakeGarbageCollected<RequestAnimationFrameCallback>(this);
continue_callback_request_id_ = GetDocument().RequestAnimationFrame(callback);
}
@@ -218,9 +219,9 @@ void HTMLMarqueeElement::stop() {
bool HTMLMarqueeElement::IsPresentationAttribute(
const QualifiedName& attr) const {
- if (attr == HTMLNames::bgcolorAttr || attr == HTMLNames::heightAttr ||
- attr == HTMLNames::hspaceAttr || attr == HTMLNames::vspaceAttr ||
- attr == HTMLNames::widthAttr) {
+ if (attr == html_names::kBgcolorAttr || attr == html_names::kHeightAttr ||
+ attr == html_names::kHspaceAttr || attr == html_names::kVspaceAttr ||
+ attr == html_names::kWidthAttr) {
return true;
}
return HTMLElement::IsPresentationAttribute(attr);
@@ -230,17 +231,17 @@ void HTMLMarqueeElement::CollectStyleForPresentationAttribute(
const QualifiedName& attr,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (attr == HTMLNames::bgcolorAttr) {
+ if (attr == html_names::kBgcolorAttr) {
AddHTMLColorToStyle(style, CSSPropertyBackgroundColor, value);
- } else if (attr == HTMLNames::heightAttr) {
+ } else if (attr == html_names::kHeightAttr) {
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
- } else if (attr == HTMLNames::hspaceAttr) {
+ } else if (attr == html_names::kHspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
- } else if (attr == HTMLNames::vspaceAttr) {
+ } else if (attr == html_names::kVspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
- } else if (attr == HTMLNames::widthAttr) {
+ } else if (attr == html_names::kWidthAttr) {
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
} else {
HTMLElement::CollectStyleForPresentationAttribute(attr, value, style);
@@ -290,7 +291,7 @@ void HTMLMarqueeElement::ContinueAnimation() {
int scroll_amount = scrollAmount();
if (scroll_delay < kMinimumScrollDelayMS &&
- !FastHasAttribute(HTMLNames::truespeedAttr))
+ !FastHasAttribute(html_names::kTruespeedAttr))
scroll_delay = kDefaultScrollDelayMS;
double duration = 0;
if (scroll_amount)
@@ -300,9 +301,9 @@ void HTMLMarqueeElement::ContinueAnimation() {
StringKeyframeEffectModel* effect_model = CreateEffectModel(parameters);
Timing timing;
- OptionalEffectTiming effect_timing;
- effect_timing.setFill("forwards");
- effect_timing.setDuration(
+ OptionalEffectTiming* effect_timing = OptionalEffectTiming::Create();
+ effect_timing->setFill("forwards");
+ effect_timing->setDuration(
UnrestrictedDoubleOrString::FromUnrestrictedDouble(duration));
TimingInput::Update(timing, effect_timing, nullptr, ASSERT_NO_EXCEPTION);
@@ -310,7 +311,7 @@ void HTMLMarqueeElement::ContinueAnimation() {
KeyframeEffect::Create(mover_, effect_model, timing);
Animation* player = mover_->GetDocument().Timeline().Play(keyframe_effect);
player->setId(g_empty_string);
- player->setOnfinish(new AnimationFinished(this));
+ player->setOnfinish(MakeGarbageCollected<AnimationFinished>(this));
player_ = player;
}
@@ -328,7 +329,7 @@ bool HTMLMarqueeElement::ShouldContinue() {
}
HTMLMarqueeElement::Behavior HTMLMarqueeElement::GetBehavior() const {
- const AtomicString& behavior = FastGetAttribute(HTMLNames::behaviorAttr);
+ const AtomicString& behavior = FastGetAttribute(html_names::kBehaviorAttr);
if (EqualIgnoringASCIICase(behavior, "alternate"))
return kAlternate;
if (EqualIgnoringASCIICase(behavior, "slide"))
@@ -337,7 +338,7 @@ HTMLMarqueeElement::Behavior HTMLMarqueeElement::GetBehavior() const {
}
HTMLMarqueeElement::Direction HTMLMarqueeElement::GetDirection() const {
- const AtomicString& direction = FastGetAttribute(HTMLNames::directionAttr);
+ const AtomicString& direction = FastGetAttribute(html_names::kDirectionAttr);
if (EqualIgnoringASCIICase(direction, "down"))
return kDown;
if (EqualIgnoringASCIICase(direction, "up"))
diff --git a/chromium/third_party/blink/renderer/core/html/html_marquee_element.h b/chromium/third_party/blink/renderer/core/html/html_marquee_element.h
index a2b0d56eb07..903870d6804 100644
--- a/chromium/third_party/blink/renderer/core/html/html_marquee_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_marquee_element.h
@@ -37,6 +37,8 @@ class HTMLMarqueeElement final : public HTMLElement {
static HTMLMarqueeElement* Create(Document&);
+ explicit HTMLMarqueeElement(Document&);
+
InsertionNotificationRequest InsertedInto(ContainerNode&) final;
void RemovedFrom(ContainerNode&) final;
@@ -55,7 +57,6 @@ class HTMLMarqueeElement final : public HTMLElement {
void stop();
private:
- explicit HTMLMarqueeElement(Document&);
void DidAddUserAgentShadowRoot(ShadowRoot&) override;
bool IsPresentationAttribute(const QualifiedName&) const override;
diff --git a/chromium/third_party/blink/renderer/core/html/html_menu_element.cc b/chromium/third_party/blink/renderer/core/html/html_menu_element.cc
index 41ee6c9a40e..784d144b53d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_menu_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_menu_element.cc
@@ -26,10 +26,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLMenuElement::HTMLMenuElement(Document& document)
- : HTMLElement(menuTag, document) {}
+ : HTMLElement(kMenuTag, document) {}
DEFINE_NODE_FACTORY(HTMLMenuElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_meta_element.cc b/chromium/third_party/blink/renderer/core/html/html_meta_element.cc
index 8f10ad6f6d1..1c67a2064bf 100644
--- a/chromium/third_party/blink/renderer/core/html/html_meta_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_meta_element.cc
@@ -39,10 +39,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLMetaElement::HTMLMetaElement(Document& document)
- : HTMLElement(metaTag, document) {}
+ : HTMLElement(kMetaTag, document) {}
DEFINE_NODE_FACTORY(HTMLMetaElement)
@@ -474,12 +474,12 @@ void HTMLMetaElement::ProcessViewportContentAttribute(
void HTMLMetaElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == http_equivAttr || params.name == contentAttr) {
+ if (params.name == kHttpEquivAttr || params.name == kContentAttr) {
Process();
return;
}
- if (params.name != nameAttr)
+ if (params.name != kNameAttr)
HTMLElement::ParseAttribute(params);
}
@@ -506,11 +506,11 @@ void HTMLMetaElement::Process() {
// All below situations require a content attribute (which can be the empty
// string).
- const AtomicString& content_value = FastGetAttribute(contentAttr);
+ const AtomicString& content_value = FastGetAttribute(kContentAttr);
if (content_value.IsNull())
return;
- const AtomicString& name_value = FastGetAttribute(nameAttr);
+ const AtomicString& name_value = FastGetAttribute(kNameAttr);
if (!name_value.IsEmpty()) {
if (DeprecatedEqualIgnoringCase(name_value, "viewport"))
ProcessViewportContentAttribute(content_value,
@@ -535,7 +535,7 @@ void HTMLMetaElement::Process() {
// tree (changing a meta tag while it's not in the tree shouldn't have any
// effect on the document).
- const AtomicString& http_equiv_value = FastGetAttribute(http_equivAttr);
+ const AtomicString& http_equiv_value = FastGetAttribute(kHttpEquivAttr);
if (http_equiv_value.IsEmpty())
return;
@@ -552,11 +552,11 @@ WTF::TextEncoding HTMLMetaElement::ComputeEncoding() const {
}
const AtomicString& HTMLMetaElement::Content() const {
- return getAttribute(contentAttr);
+ return getAttribute(kContentAttr);
}
const AtomicString& HTMLMetaElement::HttpEquiv() const {
- return getAttribute(http_equivAttr);
+ return getAttribute(kHttpEquivAttr);
}
const AtomicString& HTMLMetaElement::GetName() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_meter_element.cc b/chromium/third_party/blink/renderer/core/html/html_meter_element.cc
index b4a7f840649..f643e77030b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_meter_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_meter_element.cc
@@ -32,17 +32,17 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLMeterElement::HTMLMeterElement(Document& document)
- : LabelableElement(meterTag, document) {
+ : LabelableElement(kMeterTag, document) {
UseCounter::Count(document, WebFeature::kMeterElement);
}
HTMLMeterElement::~HTMLMeterElement() = default;
HTMLMeterElement* HTMLMeterElement::Create(Document& document) {
- HTMLMeterElement* meter = new HTMLMeterElement(document);
+ HTMLMeterElement* meter = MakeGarbageCollected<HTMLMeterElement>(document);
meter->EnsureUserAgentShadowRoot();
return meter;
}
@@ -66,64 +66,64 @@ LayoutObject* HTMLMeterElement::CreateLayoutObject(const ComputedStyle& style) {
void HTMLMeterElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == valueAttr || name == minAttr || name == maxAttr ||
- name == lowAttr || name == highAttr || name == optimumAttr)
+ if (name == kValueAttr || name == kMinAttr || name == kMaxAttr ||
+ name == kLowAttr || name == kHighAttr || name == kOptimumAttr)
DidElementStateChange();
else
LabelableElement::ParseAttribute(params);
}
double HTMLMeterElement::value() const {
- double value = GetFloatingPointAttribute(valueAttr, 0);
+ double value = GetFloatingPointAttribute(kValueAttr, 0);
return std::min(std::max(value, min()), max());
}
void HTMLMeterElement::setValue(double value) {
- SetFloatingPointAttribute(valueAttr, value);
+ SetFloatingPointAttribute(kValueAttr, value);
}
double HTMLMeterElement::min() const {
- return GetFloatingPointAttribute(minAttr, 0);
+ return GetFloatingPointAttribute(kMinAttr, 0);
}
void HTMLMeterElement::setMin(double min) {
- SetFloatingPointAttribute(minAttr, min);
+ SetFloatingPointAttribute(kMinAttr, min);
}
double HTMLMeterElement::max() const {
- return std::max(GetFloatingPointAttribute(maxAttr, std::max(1.0, min())),
+ return std::max(GetFloatingPointAttribute(kMaxAttr, std::max(1.0, min())),
min());
}
void HTMLMeterElement::setMax(double max) {
- SetFloatingPointAttribute(maxAttr, max);
+ SetFloatingPointAttribute(kMaxAttr, max);
}
double HTMLMeterElement::low() const {
- double low = GetFloatingPointAttribute(lowAttr, min());
+ double low = GetFloatingPointAttribute(kLowAttr, min());
return std::min(std::max(low, min()), max());
}
void HTMLMeterElement::setLow(double low) {
- SetFloatingPointAttribute(lowAttr, low);
+ SetFloatingPointAttribute(kLowAttr, low);
}
double HTMLMeterElement::high() const {
- double high = GetFloatingPointAttribute(highAttr, max());
+ double high = GetFloatingPointAttribute(kHighAttr, max());
return std::min(std::max(high, low()), max());
}
void HTMLMeterElement::setHigh(double high) {
- SetFloatingPointAttribute(highAttr, high);
+ SetFloatingPointAttribute(kHighAttr, high);
}
double HTMLMeterElement::optimum() const {
- double optimum = GetFloatingPointAttribute(optimumAttr, (max() + min()) / 2);
+ double optimum = GetFloatingPointAttribute(kOptimumAttr, (max() + min()) / 2);
return std::min(std::max(optimum, min()), max());
}
void HTMLMeterElement::setOptimum(double optimum) {
- SetFloatingPointAttribute(optimumAttr, optimum);
+ SetFloatingPointAttribute(kOptimumAttr, optimum);
}
HTMLMeterElement::GaugeRegion HTMLMeterElement::GetGaugeRegion() const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_meter_element.h b/chromium/third_party/blink/renderer/core/html/html_meter_element.h
index 8db9dfc47c5..e1917faedbb 100644
--- a/chromium/third_party/blink/renderer/core/html/html_meter_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_meter_element.h
@@ -34,6 +34,8 @@ class CORE_EXPORT HTMLMeterElement final : public LabelableElement {
public:
static HTMLMeterElement* Create(Document&);
+ explicit HTMLMeterElement(Document&);
+
enum GaugeRegion {
kGaugeRegionOptimum,
kGaugeRegionSuboptimal,
@@ -66,7 +68,6 @@ class CORE_EXPORT HTMLMeterElement final : public LabelableElement {
void Trace(blink::Visitor*) override;
private:
- explicit HTMLMeterElement(Document&);
~HTMLMeterElement() override;
bool AreAuthorShadowsAllowed() const override { return false; }
diff --git a/chromium/third_party/blink/renderer/core/html/html_mod_element.cc b/chromium/third_party/blink/renderer/core/html/html_mod_element.cc
index a06b1fcbeab..4087cbda97f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_mod_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_mod_element.cc
@@ -26,7 +26,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLModElement::HTMLModElement(const QualifiedName& tag_name,
Document& document)
@@ -35,16 +35,16 @@ inline HTMLModElement::HTMLModElement(const QualifiedName& tag_name,
DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(HTMLModElement)
bool HTMLModElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == citeAttr ||
+ return attribute.GetName() == kCiteAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLModElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == citeAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kCiteAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLModElement::SubResourceAttributeName() const {
- return citeAttr;
+ return kCiteAttr;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_no_embed_element.cc b/chromium/third_party/blink/renderer/core/html/html_no_embed_element.cc
index fbd4e2eb127..b2ac3a00db9 100644
--- a/chromium/third_party/blink/renderer/core/html/html_no_embed_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_no_embed_element.cc
@@ -37,10 +37,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLNoEmbedElement::HTMLNoEmbedElement(Document& document)
- : HTMLElement(noembedTag, document) {}
+ : HTMLElement(kNoembedTag, document) {}
DEFINE_NODE_FACTORY(HTMLNoEmbedElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_no_script_element.cc b/chromium/third_party/blink/renderer/core/html/html_no_script_element.cc
index d3fb75da9e8..3d9e5cd26f1 100644
--- a/chromium/third_party/blink/renderer/core/html/html_no_script_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_no_script_element.cc
@@ -37,10 +37,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLNoScriptElement::HTMLNoScriptElement(Document& document)
- : HTMLElement(noscriptTag, document) {}
+ : HTMLElement(kNoscriptTag, document) {}
DEFINE_NODE_FACTORY(HTMLNoScriptElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_object_element.cc b/chromium/third_party/blink/renderer/core/html/html_object_element.cc
index 97661052119..1e7cb2ec9db 100644
--- a/chromium/third_party/blink/renderer/core/html/html_object_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_object_element.cc
@@ -45,11 +45,11 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLObjectElement::HTMLObjectElement(Document& document,
const CreateElementFlags flags)
- : HTMLPlugInElement(objectTag,
+ : HTMLPlugInElement(kObjectTag,
document,
flags,
kShouldNotPreferPlugInsForImages),
@@ -59,7 +59,7 @@ inline HTMLObjectElement::~HTMLObjectElement() = default;
HTMLObjectElement* HTMLObjectElement::Create(Document& document,
const CreateElementFlags flags) {
- auto* element = new HTMLObjectElement(document, flags);
+ auto* element = MakeGarbageCollected<HTMLObjectElement>(document, flags);
element->EnsureUserAgentShadowRoot();
return element;
}
@@ -84,7 +84,7 @@ LayoutEmbeddedContent* HTMLObjectElement::ExistingLayoutEmbeddedContent()
bool HTMLObjectElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == borderAttr)
+ if (name == kBorderAttr)
return true;
return HTMLPlugInElement::IsPresentationAttribute(name);
}
@@ -93,7 +93,7 @@ void HTMLObjectElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == borderAttr)
+ if (name == kBorderAttr)
ApplyBorderAttributeToStyle(value, style);
else
HTMLPlugInElement::CollectStyleForPresentationAttribute(name, value, style);
@@ -102,9 +102,9 @@ void HTMLObjectElement::CollectStyleForPresentationAttribute(
void HTMLObjectElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == formAttr) {
+ if (name == kFormAttr) {
FormAttributeChanged();
- } else if (name == typeAttr) {
+ } else if (name == kTypeAttr) {
SetServiceType(params.new_value.LowerASCII());
wtf_size_t pos = service_type_.Find(";");
if (pos != kNotFound)
@@ -113,7 +113,7 @@ void HTMLObjectElement::ParseAttribute(
// Should we suppress the reload stuff when a persistable widget-type is
// specified?
ReloadPluginOnAttributeChange(name);
- } else if (name == dataAttr) {
+ } else if (name == kDataAttr) {
SetUrl(StripLeadingAndTrailingHTMLSpaces(params.new_value));
if (GetLayoutObject() && IsImageType()) {
SetNeedsPluginUpdate(true);
@@ -123,7 +123,7 @@ void HTMLObjectElement::ParseAttribute(
} else {
ReloadPluginOnAttributeChange(name);
}
- } else if (name == classidAttr) {
+ } else if (name == kClassidAttr) {
class_id_ = params.new_value;
ReloadPluginOnAttributeChange(name);
} else {
@@ -196,7 +196,7 @@ bool HTMLObjectElement::HasFallbackContent() const {
// Ignore whitespace-only text, and <param> tags, any other content is
// fallback content.
if (child->IsTextNode()) {
- if (!ToText(child)->ContainsOnlyWhitespace())
+ if (!ToText(child)->ContainsOnlyWhitespaceOrEmpty())
return true;
} else if (!IsHTMLParamElement(*child)) {
return true;
@@ -224,12 +224,12 @@ void HTMLObjectElement::ReloadPluginOnAttributeChange(
// the updating of certain attributes should bring about "redetermination"
// of what the element contains.
bool needs_invalidation;
- if (name == typeAttr) {
+ if (name == kTypeAttr) {
needs_invalidation =
- !FastHasAttribute(classidAttr) && !FastHasAttribute(dataAttr);
- } else if (name == dataAttr) {
- needs_invalidation = !FastHasAttribute(classidAttr);
- } else if (name == classidAttr) {
+ !FastHasAttribute(kClassidAttr) && !FastHasAttribute(kDataAttr);
+ } else if (name == kDataAttr) {
+ needs_invalidation = !FastHasAttribute(kClassidAttr);
+ } else if (name == kClassidAttr) {
needs_invalidation = true;
} else {
NOTREACHED();
@@ -288,7 +288,7 @@ void HTMLObjectElement::UpdatePluginInternal() {
if (!url_.IsEmpty())
DispatchErrorEvent();
if (HasFallbackContent())
- RenderFallbackContent();
+ RenderFallbackContent(ContentFrame());
} else {
if (IsErrorplaceholder())
DispatchErrorEvent();
@@ -316,23 +316,23 @@ void HTMLObjectElement::ChildrenChanged(const ChildrenChange& change) {
}
bool HTMLObjectElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == codebaseAttr ||
- attribute.GetName() == dataAttr ||
- (attribute.GetName() == usemapAttr && attribute.Value()[0] != '#') ||
+ return attribute.GetName() == kCodebaseAttr ||
+ attribute.GetName() == kDataAttr ||
+ (attribute.GetName() == kUsemapAttr && attribute.Value()[0] != '#') ||
HTMLPlugInElement::IsURLAttribute(attribute);
}
bool HTMLObjectElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == classidAttr || name == dataAttr || name == codebaseAttr ||
+ return name == kClassidAttr || name == kDataAttr || name == kCodebaseAttr ||
HTMLPlugInElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLObjectElement::SubResourceAttributeName() const {
- return dataAttr;
+ return kDataAttr;
}
const AtomicString HTMLObjectElement::ImageSourceURL() const {
- return getAttribute(dataAttr);
+ return getAttribute(kDataAttr);
}
void HTMLObjectElement::ReattachFallbackContent() {
@@ -340,7 +340,8 @@ void HTMLObjectElement::ReattachFallbackContent() {
LazyReattachIfAttached();
}
-void HTMLObjectElement::RenderFallbackContent() {
+void HTMLObjectElement::RenderFallbackContent(Frame* frame) {
+ DCHECK(!frame || frame == ContentFrame());
if (UseFallbackContent())
return;
@@ -386,14 +387,14 @@ bool HTMLObjectElement::IsExposed() const {
}
bool HTMLObjectElement::ContainsJavaApplet() const {
- if (MIMETypeRegistry::IsJavaAppletMIMEType(getAttribute(typeAttr)))
+ if (MIMETypeRegistry::IsJavaAppletMIMEType(getAttribute(kTypeAttr)))
return true;
for (HTMLElement& child : Traversal<HTMLElement>::ChildrenOf(*this)) {
if (IsHTMLParamElement(child) &&
DeprecatedEqualIgnoringCase(child.GetNameAttribute(), "type") &&
MIMETypeRegistry::IsJavaAppletMIMEType(
- child.getAttribute(valueAttr).GetString()))
+ child.getAttribute(kValueAttr).GetString()))
return true;
if (IsHTMLObjectElement(child) &&
ToHTMLObjectElement(child).ContainsJavaApplet())
@@ -413,7 +414,7 @@ HTMLFormElement* HTMLObjectElement::formOwner() const {
}
bool HTMLObjectElement::IsInteractiveContent() const {
- return FastHasAttribute(usemapAttr);
+ return FastHasAttribute(kUsemapAttr);
}
bool HTMLObjectElement::UseFallbackContent() const {
@@ -436,7 +437,7 @@ const HTMLObjectElement* ToHTMLObjectElementFromListedElement(
// We need to assert after the cast because ListedElement doesn't
// have hasTagName.
SECURITY_DCHECK(!object_element ||
- object_element->HasTagName(HTMLNames::objectTag));
+ object_element->HasTagName(html_names::kObjectTag));
return object_element;
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_object_element.h b/chromium/third_party/blink/renderer/core/html/html_object_element.h
index f95d78f243f..ae5b59d3d50 100644
--- a/chromium/third_party/blink/renderer/core/html/html_object_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_object_element.h
@@ -23,6 +23,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_OBJECT_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_OBJECT_ELEMENT_H_
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/forms/form_associated.h"
#include "third_party/blink/renderer/core/html/forms/listed_element.h"
@@ -44,6 +45,8 @@ class CORE_EXPORT HTMLObjectElement final : public HTMLPlugInElement,
public:
static HTMLObjectElement* Create(Document&, const CreateElementFlags);
+
+ HTMLObjectElement(Document&, const CreateElementFlags);
~HTMLObjectElement() override;
void Trace(blink::Visitor*) override;
@@ -59,7 +62,7 @@ class CORE_EXPORT HTMLObjectElement final : public HTMLPlugInElement,
bool HasFallbackContent() const override;
bool UseFallbackContent() const override;
bool CanRenderFallbackContent() const override { return true; }
- void RenderFallbackContent() override;
+ void RenderFallbackContent(Frame*) override;
bool IsFormControlElement() const override { return false; }
@@ -68,6 +71,10 @@ class CORE_EXPORT HTMLObjectElement final : public HTMLPlugInElement,
bool ChildrenCanHaveStyle() const override { return UseFallbackContent(); }
+ FrameOwnerElementType OwnerType() const final {
+ return FrameOwnerElementType::kObject;
+ }
+
// Implementations of constraint validation API.
// Note that the object elements are always barred from constraint validation.
String validationMessage() const override { return String(); }
@@ -85,8 +92,6 @@ class CORE_EXPORT HTMLObjectElement final : public HTMLPlugInElement,
void AssociateWith(HTMLFormElement*) override;
private:
- HTMLObjectElement(Document&, const CreateElementFlags);
-
void ParseAttribute(const AttributeModificationParams&) override;
bool IsPresentationAttribute(const QualifiedName&) const override;
void CollectStyleForPresentationAttribute(
diff --git a/chromium/third_party/blink/renderer/core/html/html_object_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_object_element_test.cc
index 4e10fe8655f..976fd39f780 100644
--- a/chromium/third_party/blink/renderer/core/html/html_object_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_object_element_test.cc
@@ -35,9 +35,10 @@ TEST_F(HTMLObjectElementTest, FallbackRecalcForReattach) {
Node* slot = object->GetShadowRoot()->firstChild();
ASSERT_TRUE(slot);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
- object->RenderFallbackContent();
+ object->RenderFallbackContent(nullptr);
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
GetDocument().GetStyleEngine().RecalcStyle(kForce);
diff --git a/chromium/third_party/blink/renderer/core/html/html_olist_element.cc b/chromium/third_party/blink/renderer/core/html/html_olist_element.cc
index cf91df7259c..7fff18fa1b7 100644
--- a/chromium/third_party/blink/renderer/core/html/html_olist_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_olist_element.cc
@@ -22,7 +22,7 @@
#include "third_party/blink/renderer/core/html/html_olist_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/list_item_ordinal.h"
@@ -32,10 +32,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLOListElement::HTMLOListElement(Document& document)
- : HTMLElement(olTag, document),
+ : HTMLElement(kOlTag, document),
start_(0xBADBEEF),
item_count_(0),
has_explicit_start_(false),
@@ -46,7 +46,7 @@ DEFINE_NODE_FACTORY(HTMLOListElement)
bool HTMLOListElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == typeAttr)
+ if (name == kTypeAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -55,7 +55,7 @@ void HTMLOListElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == typeAttr) {
+ if (name == kTypeAttr) {
if (value == "a")
AddPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType,
CSSValueLowerAlpha);
@@ -78,7 +78,7 @@ void HTMLOListElement::CollectStyleForPresentationAttribute(
void HTMLOListElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == startAttr) {
+ if (params.name == kStartAttr) {
int old_start = StartConsideringItemCount();
int parsed_start = 0;
bool can_parse = ParseHTMLInteger(params.new_value, parsed_start);
@@ -87,7 +87,7 @@ void HTMLOListElement::ParseAttribute(
if (old_start == StartConsideringItemCount())
return;
UpdateItemValues();
- } else if (params.name == reversedAttr) {
+ } else if (params.name == kReversedAttr) {
bool reversed = !params.new_value.IsNull();
if (reversed == is_reversed_)
return;
@@ -99,7 +99,7 @@ void HTMLOListElement::ParseAttribute(
}
void HTMLOListElement::setStart(int start) {
- SetIntegralAttribute(startAttr, start);
+ SetIntegralAttribute(kStartAttr, start);
}
void HTMLOListElement::UpdateItemValues() {
diff --git a/chromium/third_party/blink/renderer/core/html/html_paragraph_element.cc b/chromium/third_party/blink/renderer/core/html/html_paragraph_element.cc
index b38c624418a..0deb8c28e33 100644
--- a/chromium/third_party/blink/renderer/core/html/html_paragraph_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_paragraph_element.cc
@@ -22,16 +22,16 @@
#include "third_party/blink/renderer/core/html/html_paragraph_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLParagraphElement::HTMLParagraphElement(Document& document)
- : HTMLElement(pTag, document) {}
+ : HTMLElement(kPTag, document) {}
DEFINE_NODE_FACTORY(HTMLParagraphElement)
@@ -39,7 +39,7 @@ void HTMLParagraphElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
if (DeprecatedEqualIgnoringCase(value, "middle") ||
DeprecatedEqualIgnoringCase(value, "center"))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign,
diff --git a/chromium/third_party/blink/renderer/core/html/html_param_element.cc b/chromium/third_party/blink/renderer/core/html/html_param_element.cc
index f896142ab42..c910bed0cde 100644
--- a/chromium/third_party/blink/renderer/core/html/html_param_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_param_element.cc
@@ -28,10 +28,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLParamElement::HTMLParamElement(Document& document)
- : HTMLElement(paramTag, document) {}
+ : HTMLElement(kParamTag, document) {}
DEFINE_NODE_FACTORY(HTMLParamElement)
@@ -42,7 +42,7 @@ const AtomicString& HTMLParamElement::GetName() const {
}
const AtomicString& HTMLParamElement::Value() const {
- return FastGetAttribute(valueAttr);
+ return FastGetAttribute(kValueAttr);
}
// HTML5 says that an object resource's URL is specified by the object's
@@ -58,7 +58,7 @@ bool HTMLParamElement::IsURLParameter(const String& name) {
}
bool HTMLParamElement::IsURLAttribute(const Attribute& attribute) const {
- if (attribute.GetName() == valueAttr && IsURLParameter(GetName()))
+ if (attribute.GetName() == kValueAttr && IsURLParameter(GetName()))
return true;
return HTMLElement::IsURLAttribute(attribute);
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_picture_element.cc b/chromium/third_party/blink/renderer/core/html/html_picture_element.cc
index acabeb3c412..a2bf86e5594 100644
--- a/chromium/third_party/blink/renderer/core/html/html_picture_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_picture_element.cc
@@ -13,10 +13,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLPictureElement::HTMLPictureElement(Document& document)
- : HTMLElement(pictureTag, document) {}
+ : HTMLElement(kPictureTag, document) {}
DEFINE_NODE_FACTORY(HTMLPictureElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_plugin_element.cc b/chromium/third_party/blink/renderer/core/html/html_plugin_element.cc
index 228c40c942c..301d01dfad2 100644
--- a/chromium/third_party/blink/renderer/core/html/html_plugin_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_plugin_element.cc
@@ -25,7 +25,7 @@
#include "services/network/public/mojom/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/node.h"
@@ -57,7 +57,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -267,7 +267,7 @@ void HTMLPlugInElement::AttachLayoutTree(AttachContext& context) {
void HTMLPlugInElement::IntrinsicSizingInfoChanged() {
if (auto* layout_object = GetLayoutObject()) {
layout_object->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kUnknown);
+ layout_invalidation_reason::kUnknown);
}
}
@@ -299,15 +299,16 @@ bool HTMLPlugInElement::ShouldAccelerate() const {
ParsedFeaturePolicy HTMLPlugInElement::ConstructContainerPolicy(
Vector<String>*) const {
// Plugin elements (<object> and <embed>) are not allowed to enable the
- // fullscreen feature. Add an empty whitelist for the fullscreen feature so
+ // fullscreen feature. Add an empty allowlist for the fullscreen feature so
// that the nested browsing context is unable to use the API, regardless of
// origin.
// https://fullscreen.spec.whatwg.org/#model
ParsedFeaturePolicy container_policy;
- ParsedFeaturePolicyDeclaration whitelist;
- whitelist.feature = mojom::FeaturePolicyFeature::kFullscreen;
- whitelist.matches_all_origins = false;
- container_policy.push_back(whitelist);
+ ParsedFeaturePolicyDeclaration allowlist;
+ allowlist.feature = mojom::FeaturePolicyFeature::kFullscreen;
+ allowlist.matches_all_origins = false;
+ allowlist.disposition = mojom::FeaturePolicyDisposition::kEnforce;
+ container_policy.push_back(allowlist);
return container_policy;
}
@@ -408,8 +409,8 @@ WebPluginContainerImpl* HTMLPlugInElement::OwnedPlugin() const {
bool HTMLPlugInElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == widthAttr || name == heightAttr || name == vspaceAttr ||
- name == hspaceAttr || name == alignAttr)
+ if (name == kWidthAttr || name == kHeightAttr || name == kVspaceAttr ||
+ name == kHspaceAttr || name == kAlignAttr)
return true;
return HTMLFrameOwnerElement::IsPresentationAttribute(name);
}
@@ -418,17 +419,17 @@ void HTMLPlugInElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == widthAttr) {
+ if (name == kWidthAttr) {
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
- } else if (name == vspaceAttr) {
+ } else if (name == kVspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
- } else if (name == hspaceAttr) {
+ } else if (name == kHspaceAttr) {
AddHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
AddHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
- } else if (name == alignAttr) {
+ } else if (name == kAlignAttr) {
ApplyAlignmentAttributeToStyle(value, style);
} else {
HTMLFrameOwnerElement::CollectStyleForPresentationAttribute(name, value,
@@ -638,9 +639,9 @@ bool HTMLPlugInElement::LoadPlugin(const KURL& url,
void HTMLPlugInElement::DispatchErrorEvent() {
if (GetDocument().IsPluginDocument() && GetDocument().LocalOwner()) {
GetDocument().LocalOwner()->DispatchEvent(
- *Event::Create(EventTypeNames::error));
+ *Event::Create(event_type_names::kError));
} else {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
}
@@ -657,7 +658,7 @@ bool HTMLPlugInElement::AllowedToLoadObject(const KURL& url,
if (MIMETypeRegistry::IsJavaAppletMIMEType(mime_type))
return false;
- AtomicString declared_mime_type = FastGetAttribute(HTMLNames::typeAttr);
+ AtomicString declared_mime_type = FastGetAttribute(html_names::kTypeAttr);
if (!GetDocument().GetContentSecurityPolicy()->AllowObjectFromSource(url) ||
!GetDocument().GetContentSecurityPolicy()->AllowPluginTypeForDocument(
GetDocument(), mime_type, declared_mime_type, url)) {
diff --git a/chromium/third_party/blink/renderer/core/html/html_plugin_element.h b/chromium/third_party/blink/renderer/core/html/html_plugin_element.h
index 5120fac04c2..c18b316b963 100644
--- a/chromium/third_party/blink/renderer/core/html/html_plugin_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_plugin_element.h
@@ -69,7 +69,7 @@ class CORE_EXPORT HTMLPlugInElement
~HTMLPlugInElement() override;
void Trace(blink::Visitor*) override;
- bool IsPlugin() override { return true; }
+ bool IsPlugin() const final { return true; }
bool HasPendingActivity() const final;
diff --git a/chromium/third_party/blink/renderer/core/html/html_pre_element.cc b/chromium/third_party/blink/renderer/core/html/html_pre_element.cc
index 9167f295cc4..d0d52b9fd73 100644
--- a/chromium/third_party/blink/renderer/core/html/html_pre_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_pre_element.cc
@@ -22,14 +22,14 @@
#include "third_party/blink/renderer/core/html/html_pre_element.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLPreElement::HTMLPreElement(const QualifiedName& tag_name,
Document& document)
@@ -38,7 +38,7 @@ inline HTMLPreElement::HTMLPreElement(const QualifiedName& tag_name,
DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(HTMLPreElement)
bool HTMLPreElement::IsPresentationAttribute(const QualifiedName& name) const {
- if (name == wrapAttr)
+ if (name == kWrapAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -47,7 +47,7 @@ void HTMLPreElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == wrapAttr)
+ if (name == kWrapAttr)
style->SetProperty(CSSPropertyWhiteSpace, CSSValuePreWrap);
else
HTMLElement::CollectStyleForPresentationAttribute(name, value, style);
diff --git a/chromium/third_party/blink/renderer/core/html/html_progress_element.cc b/chromium/third_party/blink/renderer/core/html/html_progress_element.cc
index d18eaed1f48..ce39f8a147b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_progress_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_progress_element.cc
@@ -30,20 +30,21 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
const double HTMLProgressElement::kIndeterminatePosition = -1;
const double HTMLProgressElement::kInvalidPosition = -2;
HTMLProgressElement::HTMLProgressElement(Document& document)
- : LabelableElement(progressTag, document), value_(nullptr) {
+ : LabelableElement(kProgressTag, document), value_(nullptr) {
UseCounter::Count(document, WebFeature::kProgressElement);
}
HTMLProgressElement::~HTMLProgressElement() = default;
HTMLProgressElement* HTMLProgressElement::Create(Document& document) {
- HTMLProgressElement* progress = new HTMLProgressElement(document);
+ HTMLProgressElement* progress =
+ MakeGarbageCollected<HTMLProgressElement>(document);
progress->EnsureUserAgentShadowRoot();
return progress;
}
@@ -68,11 +69,11 @@ LayoutProgress* HTMLProgressElement::GetLayoutProgress() const {
void HTMLProgressElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == valueAttr) {
+ if (params.name == kValueAttr) {
if (params.old_value.IsNull() != params.new_value.IsNull())
PseudoStateChanged(CSSSelector::kPseudoIndeterminate);
DidElementStateChange();
- } else if (params.name == maxAttr) {
+ } else if (params.name == kMaxAttr) {
DidElementStateChange();
} else {
LabelableElement::ParseAttribute(params);
@@ -86,7 +87,7 @@ void HTMLProgressElement::AttachLayoutTree(AttachContext& context) {
}
double HTMLProgressElement::value() const {
- double value = GetFloatingPointAttribute(valueAttr);
+ double value = GetFloatingPointAttribute(kValueAttr);
// Otherwise, if the parsed value was greater than or equal to the maximum
// value, then the current value of the progress bar is the maximum value
// of the progress bar. Otherwise, if parsing the value attribute's value
@@ -96,11 +97,11 @@ double HTMLProgressElement::value() const {
}
void HTMLProgressElement::setValue(double value) {
- SetFloatingPointAttribute(valueAttr, std::max(value, 0.));
+ SetFloatingPointAttribute(kValueAttr, std::max(value, 0.));
}
double HTMLProgressElement::max() const {
- double max = GetFloatingPointAttribute(maxAttr);
+ double max = GetFloatingPointAttribute(kMaxAttr);
// Otherwise, if the element has no max attribute, or if it has one but
// parsing it resulted in an error, or if the parsed value was less than or
// equal to zero, then the maximum value of the progress bar is 1.0.
@@ -110,7 +111,7 @@ double HTMLProgressElement::max() const {
void HTMLProgressElement::setMax(double max) {
// FIXME: The specification says we should ignore the input value if it is
// inferior or equal to 0.
- SetFloatingPointAttribute(maxAttr, max > 0 ? max : 1);
+ SetFloatingPointAttribute(kMaxAttr, max > 0 ? max : 1);
}
double HTMLProgressElement::position() const {
@@ -120,7 +121,7 @@ double HTMLProgressElement::position() const {
}
bool HTMLProgressElement::IsDeterminate() const {
- return FastHasAttribute(valueAttr);
+ return FastHasAttribute(kValueAttr);
}
void HTMLProgressElement::DidElementStateChange() {
diff --git a/chromium/third_party/blink/renderer/core/html/html_progress_element.h b/chromium/third_party/blink/renderer/core/html/html_progress_element.h
index dc62a4ee8da..cf75eea1e17 100644
--- a/chromium/third_party/blink/renderer/core/html/html_progress_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_progress_element.h
@@ -37,6 +37,8 @@ class CORE_EXPORT HTMLProgressElement final : public LabelableElement {
static HTMLProgressElement* Create(Document&);
+ explicit HTMLProgressElement(Document&);
+
double value() const;
void setValue(double);
@@ -50,7 +52,6 @@ class CORE_EXPORT HTMLProgressElement final : public LabelableElement {
void Trace(blink::Visitor*) override;
private:
- explicit HTMLProgressElement(Document&);
~HTMLProgressElement() override;
bool AreAuthorShadowsAllowed() const override { return false; }
diff --git a/chromium/third_party/blink/renderer/core/html/html_quote_element.cc b/chromium/third_party/blink/renderer/core/html/html_quote_element.cc
index 95e843bd815..8d9fe5eb240 100644
--- a/chromium/third_party/blink/renderer/core/html/html_quote_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_quote_element.cc
@@ -27,27 +27,27 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLQuoteElement::HTMLQuoteElement(const QualifiedName& tag_name,
Document& document)
: HTMLElement(tag_name, document) {
- DCHECK(HasTagName(qTag) || HasTagName(blockquoteTag));
+ DCHECK(HasTagName(kQTag) || HasTagName(kBlockquoteTag));
}
DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(HTMLQuoteElement)
bool HTMLQuoteElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == citeAttr ||
+ return attribute.GetName() == kCiteAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLQuoteElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == citeAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kCiteAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLQuoteElement::SubResourceAttributeName() const {
- return citeAttr;
+ return kCiteAttr;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_quote_element.h b/chromium/third_party/blink/renderer/core/html/html_quote_element.h
index 14df03edf57..f2eb6589314 100644
--- a/chromium/third_party/blink/renderer/core/html/html_quote_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_quote_element.h
@@ -44,8 +44,8 @@ class HTMLQuoteElement final : public HTMLElement {
};
inline bool IsHTMLQuoteElement(const HTMLElement& element) {
- return element.HasTagName(HTMLNames::qTag) ||
- element.HasTagName(HTMLNames::blockquoteTag);
+ return element.HasTagName(html_names::kQTag) ||
+ element.HasTagName(html_names::kBlockquoteTag);
}
DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLQuoteElement);
diff --git a/chromium/third_party/blink/renderer/core/html/html_rt_element.cc b/chromium/third_party/blink/renderer/core/html/html_rt_element.cc
index 8a643c1a4da..a115a3df525 100644
--- a/chromium/third_party/blink/renderer/core/html/html_rt_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_rt_element.cc
@@ -9,10 +9,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLRTElement::HTMLRTElement(Document& document)
- : HTMLElement(rtTag, document) {}
+ : HTMLElement(kRtTag, document) {}
DEFINE_NODE_FACTORY(HTMLRTElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_ruby_element.cc b/chromium/third_party/blink/renderer/core/html/html_ruby_element.cc
index 6a8fa40ea46..3856164b94d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_ruby_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_ruby_element.cc
@@ -9,10 +9,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLRubyElement::HTMLRubyElement(Document& document)
- : HTMLElement(rubyTag, document) {}
+ : HTMLElement(kRubyTag, document) {}
DEFINE_NODE_FACTORY(HTMLRubyElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_script_element.cc b/chromium/third_party/blink/renderer/core/html/html_script_element.cc
index 4d4a077c94e..35f2ca54bf3 100644
--- a/chromium/third_party/blink/renderer/core/html/html_script_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_script_element.cc
@@ -23,8 +23,10 @@
#include "third_party/blink/renderer/core/html/html_script_element.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/html_script_element_or_svg_script_element.h"
#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
@@ -34,21 +36,23 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/script/script_loader.h"
#include "third_party/blink/renderer/core/script/script_runner.h"
+#include "third_party/blink/renderer/core/trustedtypes/trusted_script.h"
+#include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLScriptElement::HTMLScriptElement(Document& document,
const CreateElementFlags flags)
- : HTMLElement(scriptTag, document),
+ : HTMLElement(kScriptTag, document),
loader_(InitializeScriptLoader(flags.IsCreatedByParser(),
flags.WasAlreadyStarted())) {}
HTMLScriptElement* HTMLScriptElement::Create(Document& document,
const CreateElementFlags flags) {
- return new HTMLScriptElement(document, flags);
+ return MakeGarbageCollected<HTMLScriptElement>(document, flags);
}
const HashSet<AtomicString>& HTMLScriptElement::GetCheckedAttributeNames()
@@ -58,16 +62,16 @@ const HashSet<AtomicString>& HTMLScriptElement::GetCheckedAttributeNames()
}
bool HTMLScriptElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr ||
+ return attribute.GetName() == kSrcAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLScriptElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == srcAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kSrcAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLScriptElement::SubResourceAttributeName() const {
- return srcAttr;
+ return kSrcAttr;
}
void HTMLScriptElement::ChildrenChanged(const ChildrenChange& change) {
@@ -83,10 +87,10 @@ void HTMLScriptElement::DidMoveToNewDocument(Document& old_document) {
void HTMLScriptElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == srcAttr) {
+ if (params.name == kSrcAttr) {
loader_->HandleSourceAttribute(params.new_value);
LogUpdateAttributeIfIsolatedWorldAndInDocument("script", params);
- } else if (params.name == asyncAttr) {
+ } else if (params.name == kAsyncAttr) {
loader_->HandleAsyncAttribute();
} else {
HTMLElement::ParseAttribute(params);
@@ -95,7 +99,7 @@ void HTMLScriptElement::ParseAttribute(
Node::InsertionNotificationRequest HTMLScriptElement::InsertedInto(
ContainerNode& insertion_point) {
- ScriptType script_type = ScriptType::kClassic;
+ mojom::ScriptType script_type = mojom::ScriptType::kClassic;
if (insertion_point.isConnected() && HasSourceAttribute() &&
!ScriptLoader::IsValidScriptTypeAndLanguage(
TypeAttributeValue(), LanguageAttributeValue(),
@@ -104,7 +108,7 @@ Node::InsertionNotificationRequest HTMLScriptElement::InsertedInto(
WebFeature::kScriptElementWithInvalidTypeHasSrc);
}
HTMLElement::InsertedInto(insertion_point);
- LogAddElementIfIsolatedWorldAndInDocument("script", srcAttr);
+ LogAddElementIfIsolatedWorldAndInDocument("script", kSrcAttr);
return kInsertionShouldCallDidNotifySubtreeInsertions;
}
@@ -113,17 +117,43 @@ void HTMLScriptElement::DidNotifySubtreeInsertionsToDocument() {
loader_->DidNotifySubtreeInsertionsToDocument();
}
-void HTMLScriptElement::setText(const String& value) {
- setTextContent(value);
+void HTMLScriptElement::setText(
+ const StringOrTrustedScript& string_or_trusted_script,
+ ExceptionState& exception_state) {
+ setTextContent(string_or_trusted_script, exception_state);
+}
+
+void HTMLScriptElement::text(StringOrTrustedScript& result) {
+ result.SetString(TextFromChildren());
+}
+
+void HTMLScriptElement::setInnerText(
+ const StringOrTrustedScript& string_or_trusted_script,
+ ExceptionState& exception_state) {
+ String value = GetStringFromTrustedScript(string_or_trusted_script,
+ &GetDocument(), exception_state);
+ if (!exception_state.HadException()) {
+ HTMLElement::setInnerText(value, exception_state);
+ }
+}
+
+void HTMLScriptElement::setTextContent(
+ const StringOrTrustedScript& string_or_trusted_script,
+ ExceptionState& exception_state) {
+ String value = GetStringFromTrustedScript(string_or_trusted_script,
+ &GetDocument(), exception_state);
+ if (!exception_state.HadException()) {
+ Node::setTextContent(value);
+ }
}
void HTMLScriptElement::setAsync(bool async) {
- SetBooleanAttribute(asyncAttr, async);
+ SetBooleanAttribute(kAsyncAttr, async);
loader_->HandleAsyncAttribute();
}
bool HTMLScriptElement::async() const {
- return FastHasAttribute(asyncAttr) || loader_->IsNonBlocking();
+ return FastHasAttribute(kAsyncAttr) || loader_->IsNonBlocking();
}
KURL HTMLScriptElement::Src() const {
@@ -131,43 +161,43 @@ KURL HTMLScriptElement::Src() const {
}
String HTMLScriptElement::SourceAttributeValue() const {
- return getAttribute(srcAttr).GetString();
+ return getAttribute(kSrcAttr).GetString();
}
String HTMLScriptElement::CharsetAttributeValue() const {
- return getAttribute(charsetAttr).GetString();
+ return getAttribute(kCharsetAttr).GetString();
}
String HTMLScriptElement::TypeAttributeValue() const {
- return getAttribute(typeAttr).GetString();
+ return getAttribute(kTypeAttr).GetString();
}
String HTMLScriptElement::LanguageAttributeValue() const {
- return getAttribute(languageAttr).GetString();
+ return getAttribute(kLanguageAttr).GetString();
}
bool HTMLScriptElement::NomoduleAttributeValue() const {
- return FastHasAttribute(nomoduleAttr);
+ return FastHasAttribute(kNomoduleAttr);
}
String HTMLScriptElement::ForAttributeValue() const {
- return getAttribute(forAttr).GetString();
+ return getAttribute(kForAttr).GetString();
}
String HTMLScriptElement::EventAttributeValue() const {
- return getAttribute(eventAttr).GetString();
+ return getAttribute(kEventAttr).GetString();
}
String HTMLScriptElement::CrossOriginAttributeValue() const {
- return getAttribute(crossoriginAttr);
+ return getAttribute(kCrossoriginAttr);
}
String HTMLScriptElement::IntegrityAttributeValue() const {
- return getAttribute(integrityAttr);
+ return getAttribute(kIntegrityAttr);
}
String HTMLScriptElement::ReferrerPolicyAttributeValue() const {
- return getAttribute(referrerpolicyAttr);
+ return getAttribute(kReferrerpolicyAttr);
}
String HTMLScriptElement::TextFromChildren() {
@@ -175,15 +205,15 @@ String HTMLScriptElement::TextFromChildren() {
}
bool HTMLScriptElement::AsyncAttributeValue() const {
- return FastHasAttribute(asyncAttr);
+ return FastHasAttribute(kAsyncAttr);
}
bool HTMLScriptElement::DeferAttributeValue() const {
- return FastHasAttribute(deferAttr);
+ return FastHasAttribute(kDeferAttr);
}
bool HTMLScriptElement::HasSourceAttribute() const {
- return FastHasAttribute(srcAttr);
+ return FastHasAttribute(kSrcAttr);
}
bool HTMLScriptElement::IsConnected() const {
@@ -214,11 +244,11 @@ Document& HTMLScriptElement::GetDocument() const {
}
void HTMLScriptElement::DispatchLoadEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
}
void HTMLScriptElement::DispatchErrorEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
void HTMLScriptElement::SetScriptElementForBinding(
diff --git a/chromium/third_party/blink/renderer/core/html/html_script_element.h b/chromium/third_party/blink/renderer/core/html/html_script_element.h
index 272096105c6..98418db8aea 100644
--- a/chromium/third_party/blink/renderer/core/html/html_script_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_script_element.h
@@ -33,6 +33,9 @@
namespace blink {
+class StringOrTrustedScript;
+class ExceptionState;
+
class CORE_EXPORT HTMLScriptElement final : public HTMLElement,
public ScriptElementBase {
DEFINE_WRAPPERTYPEINFO();
@@ -41,11 +44,15 @@ class CORE_EXPORT HTMLScriptElement final : public HTMLElement,
public:
static HTMLScriptElement* Create(Document&, const CreateElementFlags);
+ HTMLScriptElement(Document&, const CreateElementFlags);
+
// Returns attributes that should be checked against Trusted Types
const HashSet<AtomicString>& GetCheckedAttributeNames() const override;
- String text() { return TextFromChildren(); }
- void setText(const String&);
+ void text(StringOrTrustedScript& result);
+ void setText(const StringOrTrustedScript&, ExceptionState&);
+ void setInnerText(const StringOrTrustedScript&, ExceptionState&) override;
+ void setTextContent(const StringOrTrustedScript&, ExceptionState&) override;
KURL Src() const;
@@ -60,8 +67,6 @@ class CORE_EXPORT HTMLScriptElement final : public HTMLElement,
void Trace(blink::Visitor*) override;
private:
- HTMLScriptElement(Document&, const CreateElementFlags);
-
void ParseAttribute(const AttributeModificationParams&) override;
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void DidNotifySubtreeInsertionsToDocument() override;
diff --git a/chromium/third_party/blink/renderer/core/html/html_script_element.idl b/chromium/third_party/blink/renderer/core/html/html_script_element.idl
index 7c0464c3719..6c9a17751e3 100644
--- a/chromium/third_party/blink/renderer/core/html/html_script_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_script_element.idl
@@ -27,7 +27,7 @@ interface HTMLScriptElement : HTMLElement {
[CEReactions] attribute boolean async;
[CEReactions, Reflect] attribute boolean defer;
[CEReactions, Reflect, ReflectOnly=("anonymous","use-credentials"), ReflectEmpty="anonymous", ReflectInvalid="anonymous"] attribute DOMString? crossOrigin;
- [CEReactions] attribute DOMString text;
+ [CEReactions, RaisesException=Setter] attribute ScriptString text;
[CEReactions, Reflect, ReflectOnly=("", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url"), ReflectEmpty="", ReflectInvalid=""] attribute DOMString? referrerPolicy;
// obsolete members
diff --git a/chromium/third_party/blink/renderer/core/html/html_shadow_element.cc b/chromium/third_party/blink/renderer/core/html/html_shadow_element.cc
index 9753001e464..db8da597c0b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_shadow_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_shadow_element.cc
@@ -41,7 +41,7 @@ namespace blink {
class Document;
inline HTMLShadowElement::HTMLShadowElement(Document& document)
- : V0InsertionPoint(HTMLNames::shadowTag, document) {
+ : V0InsertionPoint(html_names::kShadowTag, document) {
UseCounter::Count(document, WebFeature::kHTMLShadowElement);
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_slot_element.cc b/chromium/third_party/blink/renderer/core/html/html_slot_element.cc
index 1dfa94af469..7a9df981b0d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_slot_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_slot_element.cc
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/dom/flat_tree_node_data.h"
#include "third_party/blink/renderer/core/dom/mutation_observer.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
@@ -49,32 +50,32 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
constexpr size_t kLCSTableSizeLimit = 16;
}
HTMLSlotElement* HTMLSlotElement::Create(Document& document) {
- return new HTMLSlotElement(document);
+ return MakeGarbageCollected<HTMLSlotElement>(document);
}
HTMLSlotElement* HTMLSlotElement::CreateUserAgentDefaultSlot(
Document& document) {
- HTMLSlotElement* slot = new HTMLSlotElement(document);
- slot->setAttribute(nameAttr, UserAgentDefaultSlotName());
+ HTMLSlotElement* slot = MakeGarbageCollected<HTMLSlotElement>(document);
+ slot->setAttribute(kNameAttr, UserAgentDefaultSlotName());
return slot;
}
HTMLSlotElement* HTMLSlotElement::CreateUserAgentCustomAssignSlot(
Document& document) {
- HTMLSlotElement* slot = new HTMLSlotElement(document);
- slot->setAttribute(nameAttr, UserAgentCustomAssignSlotName());
+ HTMLSlotElement* slot = MakeGarbageCollected<HTMLSlotElement>(document);
+ slot->setAttribute(kNameAttr, UserAgentCustomAssignSlotName());
return slot;
}
inline HTMLSlotElement::HTMLSlotElement(Document& document)
- : HTMLElement(slotTag, document) {
+ : HTMLElement(kSlotTag, document) {
UseCounter::Count(document, WebFeature::kHTMLSlotElement);
SetHasCustomStyleCallbacks();
}
@@ -148,8 +149,8 @@ const HeapVector<Member<Node>> HTMLSlotElement::FlattenedAssignedNodes() {
}
const HeapVector<Member<Node>> HTMLSlotElement::AssignedNodesForBinding(
- const AssignedNodesOptions& options) {
- if (options.hasFlatten() && options.flatten())
+ const AssignedNodesOptions* options) {
+ if (options->hasFlatten() && options->flatten())
return FlattenedAssignedNodes();
return AssignedNodes();
}
@@ -164,7 +165,7 @@ const HeapVector<Member<Element>> HTMLSlotElement::AssignedElements() {
}
const HeapVector<Member<Element>> HTMLSlotElement::AssignedElementsForBinding(
- const AssignedNodesOptions& options) {
+ const AssignedNodesOptions* options) {
HeapVector<Member<Element>> elements;
for (auto& node : AssignedNodesForBinding(options)) {
if (Element* element = ToElementOrNull(node))
@@ -192,10 +193,28 @@ void HTMLSlotElement::ClearAssignedNodes() {
}
void HTMLSlotElement::ClearAssignedNodesAndFlatTreeChildren() {
- assigned_nodes_.clear();
+ ClearAssignedNodes();
flat_tree_children_.clear();
}
+void HTMLSlotElement::UpdateFlatTreeNodeDataForAssignedNodes() {
+ Node* previous = nullptr;
+ for (auto& current : assigned_nodes_) {
+ FlatTreeNodeData& flat_tree_node_data = current->EnsureFlatTreeNodeData();
+ flat_tree_node_data.SetAssignedSlot(this);
+ flat_tree_node_data.SetPreviousInAssignedNodes(previous);
+ if (previous) {
+ DCHECK(previous->GetFlatTreeNodeData());
+ previous->GetFlatTreeNodeData()->SetNextInAssignedNodes(current);
+ }
+ previous = current;
+ }
+ if (previous) {
+ DCHECK(previous->GetFlatTreeNodeData());
+ previous->GetFlatTreeNodeData()->SetNextInAssignedNodes(nullptr);
+ }
+}
+
void HTMLSlotElement::RecalcFlatTreeChildren() {
DCHECK(SupportsAssignment());
@@ -215,35 +234,13 @@ void HTMLSlotElement::RecalcFlatTreeChildren() {
void HTMLSlotElement::DispatchSlotChangeEvent() {
DCHECK(!IsInUserAgentShadowRoot());
- Event* event = Event::CreateBubble(EventTypeNames::slotchange);
+ Event* event = Event::CreateBubble(event_type_names::kSlotchange);
event->SetTarget(this);
DispatchScopedEvent(*event);
}
-Node* HTMLSlotElement::AssignedNodeNextTo(const Node& node) const {
- DCHECK(SupportsAssignment());
- ContainingShadowRoot()->GetSlotAssignment().RecalcAssignment();
- // TODO(crbug.com/776656): Use {node -> index} map to avoid O(N) lookup
- wtf_size_t index = assigned_nodes_.Find(&node);
- DCHECK(index != WTF::kNotFound);
- if (index + 1 == assigned_nodes_.size())
- return nullptr;
- return assigned_nodes_[index + 1].Get();
-}
-
-Node* HTMLSlotElement::AssignedNodePreviousTo(const Node& node) const {
- DCHECK(SupportsAssignment());
- ContainingShadowRoot()->GetSlotAssignment().RecalcAssignment();
- // TODO(crbug.com/776656): Use {node -> index} map to avoid O(N) lookup
- wtf_size_t index = assigned_nodes_.Find(&node);
- DCHECK(index != WTF::kNotFound);
- if (index == 0)
- return nullptr;
- return assigned_nodes_[index - 1].Get();
-}
-
AtomicString HTMLSlotElement::GetName() const {
- return NormalizeSlotName(FastGetAttribute(nameAttr));
+ return NormalizeSlotName(FastGetAttribute(kNameAttr));
}
void HTMLSlotElement::AttachLayoutTree(AttachContext& context) {
@@ -286,7 +283,7 @@ void HTMLSlotElement::RebuildDistributedChildrenLayoutTrees(
void HTMLSlotElement::AttributeChanged(
const AttributeModificationParams& params) {
- if (params.name == nameAttr) {
+ if (params.name == kNameAttr) {
if (ShadowRoot* root = ContainingShadowRoot()) {
if (root->IsV1() && params.old_value != params.new_value) {
root->GetSlotAssignment().DidRenameSlot(
@@ -391,7 +388,7 @@ void HTMLSlotElement::DidRecalcStyle(StyleRecalcChange change) {
node->SetNeedsStyleRecalc(
kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kPropagateInheritChangeToDistributedNodes));
+ style_change_reason::kPropagateInheritChangeToDistributedNodes));
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_slot_element.h b/chromium/third_party/blink/renderer/core/html/html_slot_element.h
index 963edf3b62f..4e127e195c6 100644
--- a/chromium/third_party/blink/renderer/core/html/html_slot_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_slot_element.h
@@ -46,12 +46,14 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
static HTMLSlotElement* CreateUserAgentDefaultSlot(Document&);
static HTMLSlotElement* CreateUserAgentCustomAssignSlot(Document&);
+ HTMLSlotElement(Document&);
+
const HeapVector<Member<Node>>& AssignedNodes() const;
const HeapVector<Member<Node>> AssignedNodesForBinding(
- const AssignedNodesOptions&);
+ const AssignedNodesOptions*);
const HeapVector<Member<Element>> AssignedElements();
const HeapVector<Member<Element>> AssignedElementsForBinding(
- const AssignedNodesOptions&);
+ const AssignedNodesOptions*);
Node* FirstAssignedNode() const {
auto& nodes = AssignedNodes();
@@ -62,14 +64,15 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
return nodes.IsEmpty() ? nullptr : nodes.back().Get();
}
- Node* AssignedNodeNextTo(const Node&) const;
- Node* AssignedNodePreviousTo(const Node&) const;
-
void AppendAssignedNode(Node&);
- void ClearAssignedNodes();
const HeapVector<Member<Node>> FlattenedAssignedNodes();
- void RecalcFlatTreeChildren();
+
+ void WillRecalcAssignedNodes() { ClearAssignedNodes(); }
+ void DidRecalcAssignedNodes() {
+ UpdateFlatTreeNodeDataForAssignedNodes();
+ RecalcFlatTreeChildren();
+ }
void AttachLayoutTree(AttachContext&) final;
void DetachLayoutTree(const AttachContext& = AttachContext()) final;
@@ -112,8 +115,6 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
void Trace(blink::Visitor*) override;
private:
- HTMLSlotElement(Document&);
-
InsertionNotificationRequest InsertedInto(ContainerNode&) final;
void RemovedFrom(ContainerNode&) final;
void DidRecalcStyle(StyleRecalcChange) final;
@@ -134,6 +135,9 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
const HeapVector<Member<Node>>& GetDistributedNodes();
+ void RecalcFlatTreeChildren();
+ void UpdateFlatTreeNodeDataForAssignedNodes();
+ void ClearAssignedNodes();
void ClearAssignedNodesAndFlatTreeChildren();
HeapVector<Member<Node>> assigned_nodes_;
diff --git a/chromium/third_party/blink/renderer/core/html/html_slot_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_slot_element_test.cc
index 9d4ac83b386..f94036d9aef 100644
--- a/chromium/third_party/blink/renderer/core/html/html_slot_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_slot_element_test.cc
@@ -157,9 +157,10 @@ TEST_F(HTMLSlotElementReattachTest, RecalcAssignedNodeStyleForReattach) {
R"HTML(<span><slot /></span>)HTML");
Element& shadow_span = *ToElement(shadow_root.firstChild());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
- shadow_span.setAttribute(HTMLNames::styleAttr, "display:block");
+ shadow_span.setAttribute(html_names::kStyleAttr, "display:block");
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
GetDocument().GetStyleEngine().RecalcStyle(kNoChange);
diff --git a/chromium/third_party/blink/renderer/core/html/html_source_element.cc b/chromium/third_party/blink/renderer/core/html/html_source_element.cc
index 737dc30703e..38ed258c92b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_source_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_source_element.cc
@@ -36,12 +36,13 @@
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_url.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#define SOURCE_LOG_LEVEL 3
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class HTMLSourceElement::Listener final : public MediaQueryListListener {
public:
@@ -62,7 +63,8 @@ class HTMLSourceElement::Listener final : public MediaQueryListListener {
};
inline HTMLSourceElement::HTMLSourceElement(Document& document)
- : HTMLElement(sourceTag, document), listener_(new Listener(this)) {
+ : HTMLElement(kSourceTag, document),
+ listener_(MakeGarbageCollected<Listener>(this)) {
DVLOG(SOURCE_LOG_LEVEL) << "HTMLSourceElement - " << (void*)this;
}
@@ -90,7 +92,7 @@ void HTMLSourceElement::CreateMediaQueryList(const AtomicString& media) {
}
void HTMLSourceElement::DidMoveToNewDocument(Document& old_document) {
- CreateMediaQueryList(FastGetAttribute(mediaAttr));
+ CreateMediaQueryList(FastGetAttribute(kMediaAttr));
HTMLElement::DidMoveToNewDocument(old_document);
}
@@ -129,20 +131,20 @@ void HTMLSourceElement::AddMediaQueryListListener() {
}
void HTMLSourceElement::SetSrc(const String& url) {
- setAttribute(srcAttr, AtomicString(url));
+ setAttribute(kSrcAttr, AtomicString(url));
}
void HTMLSourceElement::SetSrc(const USVStringOrTrustedURL& usvStringOrURL,
ExceptionState& exception_state) {
- setAttribute(srcAttr, usvStringOrURL, exception_state);
+ setAttribute(kSrcAttr, usvStringOrURL, exception_state);
}
const AtomicString& HTMLSourceElement::type() const {
- return getAttribute(typeAttr);
+ return getAttribute(kTypeAttr);
}
void HTMLSourceElement::setType(const AtomicString& type) {
- setAttribute(typeAttr, type);
+ setAttribute(kTypeAttr, type);
}
void HTMLSourceElement::ScheduleErrorEvent() {
@@ -161,7 +163,7 @@ void HTMLSourceElement::CancelPendingErrorEvent() {
void HTMLSourceElement::DispatchPendingEvent() {
DVLOG(SOURCE_LOG_LEVEL) << "dispatchPendingEvent - " << (void*)this;
- DispatchEvent(*Event::CreateCancelable(EventTypeNames::error));
+ DispatchEvent(*Event::CreateCancelable(event_type_names::kError));
}
bool HTMLSourceElement::MediaQueryMatches() const {
@@ -172,7 +174,7 @@ bool HTMLSourceElement::MediaQueryMatches() const {
}
bool HTMLSourceElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr ||
+ return attribute.GetName() == kSrcAttr ||
HTMLElement::IsURLAttribute(attribute);
}
@@ -180,10 +182,10 @@ void HTMLSourceElement::ParseAttribute(
const AttributeModificationParams& params) {
HTMLElement::ParseAttribute(params);
const QualifiedName& name = params.name;
- if (name == mediaAttr)
+ if (name == kMediaAttr)
CreateMediaQueryList(params.new_value);
- if (name == srcsetAttr || name == sizesAttr || name == mediaAttr ||
- name == typeAttr) {
+ if (name == kSrcsetAttr || name == kSizesAttr || name == kMediaAttr ||
+ name == kTypeAttr) {
if (auto* picture = ToHTMLPictureElementOrNull(parentElement()))
picture->SourceOrMediaChanged();
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_source_element.h b/chromium/third_party/blink/renderer/core/html/html_source_element.h
index 43c741279c7..6f3fc9d5c80 100644
--- a/chromium/third_party/blink/renderer/core/html/html_source_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_source_element.h
@@ -28,8 +28,8 @@
#include "third_party/blink/renderer/core/css/media_query_list_listener.h"
#include "third_party/blink/renderer/core/html/html_element.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_span_element.cc b/chromium/third_party/blink/renderer/core/html/html_span_element.cc
index 8686d4422c4..d7a59e3d9e8 100644
--- a/chromium/third_party/blink/renderer/core/html/html_span_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_span_element.cc
@@ -29,10 +29,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLSpanElement::HTMLSpanElement(Document& document)
- : HTMLElement(spanTag, document) {}
+ : HTMLElement(kSpanTag, document) {}
DEFINE_NODE_FACTORY(HTMLSpanElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_style_element.cc b/chromium/third_party/blink/renderer/core/html/html_style_element.cc
index 72a1ca8b937..e4e210e3234 100644
--- a/chromium/third_party/blink/renderer/core/html/html_style_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_style_element.cc
@@ -33,11 +33,11 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLStyleElement::HTMLStyleElement(Document& document,
const CreateElementFlags flags)
- : HTMLElement(styleTag, document),
+ : HTMLElement(kStyleTag, document),
StyleElement(&document, flags.IsCreatedByParser()),
fired_load_(false),
loaded_sheet_(false) {}
@@ -46,18 +46,18 @@ HTMLStyleElement::~HTMLStyleElement() = default;
HTMLStyleElement* HTMLStyleElement::Create(Document& document,
const CreateElementFlags flags) {
- return new HTMLStyleElement(document, flags);
+ return MakeGarbageCollected<HTMLStyleElement>(document, flags);
}
void HTMLStyleElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == titleAttr && sheet_ && IsInDocumentTree()) {
+ if (params.name == kTitleAttr && sheet_ && IsInDocumentTree()) {
sheet_->SetTitle(params.new_value);
- } else if (params.name == mediaAttr && isConnected() &&
+ } else if (params.name == kMediaAttr && isConnected() &&
GetDocument().IsActive() && sheet_) {
sheet_->SetMediaQueries(MediaQuerySet::Create(params.new_value));
GetDocument().GetStyleEngine().MediaQueriesChangedInScope(GetTreeScope());
- } else if (params.name == typeAttr) {
+ } else if (params.name == kTypeAttr) {
HTMLElement::ParseAttribute(params);
StyleElement::ChildrenChanged(*this);
} else {
@@ -101,11 +101,11 @@ void HTMLStyleElement::ChildrenChanged(const ChildrenChange& change) {
}
const AtomicString& HTMLStyleElement::media() const {
- return getAttribute(mediaAttr);
+ return getAttribute(kMediaAttr);
}
const AtomicString& HTMLStyleElement::type() const {
- return getAttribute(typeAttr);
+ return getAttribute(kTypeAttr);
}
void HTMLStyleElement::DispatchPendingEvent(
@@ -113,9 +113,9 @@ void HTMLStyleElement::DispatchPendingEvent(
if (loaded_sheet_) {
if (GetDocument().HasListenerType(
Document::kLoadListenerAtCapturePhaseOrAtStyleElement))
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
} else {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
// Checks Document's load event synchronously here for performance.
// This is safe because dispatchPendingEvent() is called asynchronously.
diff --git a/chromium/third_party/blink/renderer/core/html/html_style_element.h b/chromium/third_party/blink/renderer/core/html/html_style_element.h
index 151ba08bebf..0bb532741f1 100644
--- a/chromium/third_party/blink/renderer/core/html/html_style_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_style_element.h
@@ -37,6 +37,8 @@ class CORE_EXPORT HTMLStyleElement final : public HTMLElement,
public:
static HTMLStyleElement* Create(Document&, const CreateElementFlags);
+
+ HTMLStyleElement(Document&, const CreateElementFlags);
~HTMLStyleElement() override;
using StyleElement::sheet;
@@ -47,8 +49,6 @@ class CORE_EXPORT HTMLStyleElement final : public HTMLElement,
void Trace(blink::Visitor*) override;
private:
- HTMLStyleElement(Document&, const CreateElementFlags);
-
// Always call this asynchronously because this can cause synchronous
// Document load event and JavaScript execution.
void DispatchPendingEvent(std::unique_ptr<IncrementLoadEventDelayCount>);
diff --git a/chromium/third_party/blink/renderer/core/html/html_summary_element.cc b/chromium/third_party/blink/renderer/core/html/html_summary_element.cc
index 751682d9b77..68c1f202450 100644
--- a/chromium/third_party/blink/renderer/core/html/html_summary_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_summary_element.cc
@@ -34,16 +34,17 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLSummaryElement* HTMLSummaryElement::Create(Document& document) {
- HTMLSummaryElement* summary = new HTMLSummaryElement(document);
+ HTMLSummaryElement* summary =
+ MakeGarbageCollected<HTMLSummaryElement>(document);
summary->EnsureUserAgentShadowRoot();
return summary;
}
HTMLSummaryElement::HTMLSummaryElement(Document& document)
- : HTMLElement(summaryTag, document) {}
+ : HTMLElement(kSummaryTag, document) {}
LayoutObject* HTMLSummaryElement::CreateLayoutObject(
const ComputedStyle& style) {
@@ -62,7 +63,7 @@ LayoutObject* HTMLSummaryElement::CreateLayoutObject(
void HTMLSummaryElement::DidAddUserAgentShadowRoot(ShadowRoot& root) {
DetailsMarkerControl* marker_control =
DetailsMarkerControl::Create(GetDocument());
- marker_control->SetIdAttribute(ShadowElementNames::DetailsMarker());
+ marker_control->SetIdAttribute(shadow_element_names::DetailsMarker());
root.AppendChild(marker_control);
root.AppendChild(HTMLSlotElement::CreateUserAgentDefaultSlot(GetDocument()));
}
@@ -77,7 +78,7 @@ HTMLDetailsElement* HTMLSummaryElement::DetailsElement() const {
Element* HTMLSummaryElement::MarkerControl() {
return EnsureUserAgentShadowRoot().getElementById(
- ShadowElementNames::DetailsMarker());
+ shadow_element_names::DetailsMarker());
}
bool HTMLSummaryElement::IsMainSummary() const {
@@ -103,7 +104,7 @@ bool HTMLSummaryElement::SupportsFocus() const {
void HTMLSummaryElement::DefaultEventHandler(Event& event) {
if (IsMainSummary()) {
- if (event.type() == EventTypeNames::DOMActivate &&
+ if (event.type() == event_type_names::kDOMActivate &&
!IsClickableControl(event.target()->ToNode())) {
if (HTMLDetailsElement* details = DetailsElement())
details->ToggleOpen();
@@ -112,13 +113,13 @@ void HTMLSummaryElement::DefaultEventHandler(Event& event) {
}
if (event.IsKeyboardEvent()) {
- if (event.type() == EventTypeNames::keydown &&
+ if (event.type() == event_type_names::kKeydown &&
ToKeyboardEvent(event).key() == " ") {
SetActive(true);
// No setDefaultHandled() - IE dispatches a keypress in this case.
return;
}
- if (event.type() == EventTypeNames::keypress) {
+ if (event.type() == event_type_names::kKeypress) {
switch (ToKeyboardEvent(event).charCode()) {
case '\r':
DispatchSimulatedClick(&event);
@@ -130,7 +131,7 @@ void HTMLSummaryElement::DefaultEventHandler(Event& event) {
return;
}
}
- if (event.type() == EventTypeNames::keyup &&
+ if (event.type() == event_type_names::kKeyup &&
ToKeyboardEvent(event).key() == " ") {
if (IsActive())
DispatchSimulatedClick(&event);
diff --git a/chromium/third_party/blink/renderer/core/html/html_summary_element.h b/chromium/third_party/blink/renderer/core/html/html_summary_element.h
index 4641a8d1222..8d13bdb25be 100644
--- a/chromium/third_party/blink/renderer/core/html/html_summary_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_summary_element.h
@@ -30,14 +30,15 @@ class HTMLDetailsElement;
class HTMLSummaryElement final : public HTMLElement {
public:
static HTMLSummaryElement* Create(Document&);
+
+ explicit HTMLSummaryElement(Document&);
+
bool IsMainSummary() const;
bool WillRespondToMouseClickEvents() override;
Element* MarkerControl();
private:
- explicit HTMLSummaryElement(Document&);
-
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
void DefaultEventHandler(Event&) override;
bool HasActivationBehavior() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_caption_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_caption_element.cc
index 0e5c1b4818e..dd542cb580c 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_caption_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_caption_element.cc
@@ -24,15 +24,15 @@
#include "third_party/blink/renderer/core/html/html_table_caption_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTableCaptionElement::HTMLTableCaptionElement(Document& document)
- : HTMLElement(captionTag, document) {}
+ : HTMLElement(kCaptionTag, document) {}
DEFINE_NODE_FACTORY(HTMLTableCaptionElement)
@@ -40,7 +40,7 @@ void HTMLTableCaptionElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == alignAttr) {
+ if (name == kAlignAttr) {
if (!value.IsEmpty())
AddPropertyToPresentationAttributeStyle(style, CSSPropertyCaptionSide,
value);
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_cell_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_cell_element.cc
index 9992cb89261..a1101778334 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_cell_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_cell_element.cc
@@ -24,7 +24,7 @@
#include "third_party/blink/renderer/core/html/html_table_cell_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
@@ -37,7 +37,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTableCellElement::HTMLTableCellElement(const QualifiedName& tag_name,
Document& document)
@@ -46,7 +46,7 @@ inline HTMLTableCellElement::HTMLTableCellElement(const QualifiedName& tag_name,
DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(HTMLTableCellElement)
unsigned HTMLTableCellElement::colSpan() const {
- const AtomicString& col_span_value = FastGetAttribute(colspanAttr);
+ const AtomicString& col_span_value = FastGetAttribute(kColspanAttr);
unsigned value = 0;
if (!ParseHTMLClampedNonNegativeInteger(col_span_value, kMinColSpan,
kMaxColSpan, value))
@@ -64,7 +64,7 @@ unsigned HTMLTableCellElement::colSpan() const {
}
unsigned HTMLTableCellElement::rowSpan() const {
- const AtomicString& row_span_value = FastGetAttribute(rowspanAttr);
+ const AtomicString& row_span_value = FastGetAttribute(kRowspanAttr);
unsigned value = 0;
if (!ParseHTMLClampedNonNegativeInteger(row_span_value, kMinRowSpan,
kMaxRowSpan, value))
@@ -88,7 +88,7 @@ int HTMLTableCellElement::cellIndex() const {
bool HTMLTableCellElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == nowrapAttr || name == widthAttr || name == heightAttr)
+ if (name == kNowrapAttr || name == kWidthAttr || name == kHeightAttr)
return true;
return HTMLTablePartElement::IsPresentationAttribute(name);
}
@@ -97,16 +97,16 @@ void HTMLTableCellElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == nowrapAttr) {
+ if (name == kNowrapAttr) {
AddPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace,
CSSValueWebkitNowrap);
- } else if (name == widthAttr) {
+ } else if (name == kWidthAttr) {
if (!value.IsEmpty()) {
int width_int = value.ToInt();
if (width_int > 0) // width="0" is ignored for compatibility with WinIE.
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
}
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
if (!value.IsEmpty()) {
int height_int = value.ToInt();
if (height_int >
@@ -121,7 +121,7 @@ void HTMLTableCellElement::CollectStyleForPresentationAttribute(
void HTMLTableCellElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == rowspanAttr || params.name == colspanAttr) {
+ if (params.name == kRowspanAttr || params.name == kColspanAttr) {
if (GetLayoutObject() && GetLayoutObject()->IsTableCell())
ToLayoutTableCell(GetLayoutObject())->ColSpanOrRowSpanChanged();
} else {
@@ -137,39 +137,39 @@ HTMLTableCellElement::AdditionalPresentationAttributeStyle() {
}
bool HTMLTableCellElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == backgroundAttr ||
+ return attribute.GetName() == kBackgroundAttr ||
HTMLTablePartElement::IsURLAttribute(attribute);
}
bool HTMLTableCellElement::HasLegalLinkAttribute(
const QualifiedName& name) const {
- return (HasTagName(tdTag) && name == backgroundAttr) ||
+ return (HasTagName(kTdTag) && name == kBackgroundAttr) ||
HTMLTablePartElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLTableCellElement::SubResourceAttributeName() const {
- return HasTagName(tdTag) ? backgroundAttr
- : HTMLTablePartElement::SubResourceAttributeName();
+ return HasTagName(kTdTag) ? kBackgroundAttr
+ : HTMLTablePartElement::SubResourceAttributeName();
}
const AtomicString& HTMLTableCellElement::Abbr() const {
- return FastGetAttribute(abbrAttr);
+ return FastGetAttribute(kAbbrAttr);
}
const AtomicString& HTMLTableCellElement::Axis() const {
- return FastGetAttribute(axisAttr);
+ return FastGetAttribute(kAxisAttr);
}
void HTMLTableCellElement::setColSpan(unsigned n) {
- SetUnsignedIntegralAttribute(colspanAttr, n, kDefaultColSpan);
+ SetUnsignedIntegralAttribute(kColspanAttr, n, kDefaultColSpan);
}
const AtomicString& HTMLTableCellElement::Headers() const {
- return FastGetAttribute(headersAttr);
+ return FastGetAttribute(kHeadersAttr);
}
void HTMLTableCellElement::setRowSpan(unsigned n) {
- SetUnsignedIntegralAttribute(rowspanAttr, n, kDefaultRowSpan);
+ SetUnsignedIntegralAttribute(kRowspanAttr, n, kDefaultRowSpan);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_cell_element.h b/chromium/third_party/blink/renderer/core/html/html_table_cell_element.h
index a6d99e99e8d..c89631336ce 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_cell_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_table_cell_element.h
@@ -69,8 +69,8 @@ class CORE_EXPORT HTMLTableCellElement final : public HTMLTablePartElement {
};
inline bool IsHTMLTableCellElement(const HTMLElement& element) {
- return element.HasTagName(HTMLNames::tdTag) ||
- element.HasTagName(HTMLNames::thTag);
+ return element.HasTagName(html_names::kTdTag) ||
+ element.HasTagName(html_names::kThTag);
}
DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableCellElement);
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_col_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_col_element.cc
index 7475912be6b..6cff56e0d32 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_col_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_col_element.cc
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/html/html_table_col_element.h"
#include <algorithm>
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/html/html_table_cell_element.h"
#include "third_party/blink/renderer/core/html/html_table_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
@@ -35,7 +35,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTableColElement::HTMLTableColElement(const QualifiedName& tag_name,
Document& document)
@@ -45,7 +45,7 @@ DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(HTMLTableColElement)
bool HTMLTableColElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == widthAttr)
+ if (name == kWidthAttr)
return true;
return HTMLTablePartElement::IsPresentationAttribute(name);
}
@@ -54,7 +54,7 @@ void HTMLTableColElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == widthAttr)
+ if (name == kWidthAttr)
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
else
HTMLTablePartElement::CollectStyleForPresentationAttribute(name, value,
@@ -63,7 +63,7 @@ void HTMLTableColElement::CollectStyleForPresentationAttribute(
void HTMLTableColElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == spanAttr) {
+ if (params.name == kSpanAttr) {
unsigned new_span = 0;
if (!ParseHTMLClampedNonNegativeInteger(params.new_value, kMinColSpan,
kMaxColSpan, new_span)) {
@@ -72,14 +72,15 @@ void HTMLTableColElement::ParseAttribute(
span_ = new_span;
if (GetLayoutObject() && GetLayoutObject()->IsLayoutTableCol())
GetLayoutObject()->UpdateFromElement();
- } else if (params.name == widthAttr) {
+ } else if (params.name == kWidthAttr) {
if (!params.new_value.IsEmpty()) {
if (GetLayoutObject() && GetLayoutObject()->IsLayoutTableCol()) {
LayoutTableCol* col = ToLayoutTableCol(GetLayoutObject());
int new_width = Width().ToInt();
- if (new_width != col->Size().Width())
+ if (new_width != col->Size().Width()) {
col->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
+ }
}
}
} else {
@@ -89,7 +90,7 @@ void HTMLTableColElement::ParseAttribute(
const CSSPropertyValueSet*
HTMLTableColElement::AdditionalPresentationAttributeStyle() {
- if (!HasTagName(colgroupTag))
+ if (!HasTagName(kColgroupTag))
return nullptr;
if (HTMLTableElement* table = FindParentTable())
return table->AdditionalGroupStyle(false);
@@ -97,11 +98,11 @@ HTMLTableColElement::AdditionalPresentationAttributeStyle() {
}
void HTMLTableColElement::setSpan(unsigned n) {
- SetUnsignedIntegralAttribute(spanAttr, n, kDefaultColSpan);
+ SetUnsignedIntegralAttribute(kSpanAttr, n, kDefaultColSpan);
}
const AtomicString& HTMLTableColElement::Width() const {
- return getAttribute(widthAttr);
+ return getAttribute(kWidthAttr);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_col_element.h b/chromium/third_party/blink/renderer/core/html/html_table_col_element.h
index 8e4eef775e1..1e7ff08c793 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_col_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_table_col_element.h
@@ -58,8 +58,8 @@ class HTMLTableColElement final : public HTMLTablePartElement {
};
inline bool IsHTMLTableColElement(const HTMLElement& element) {
- return element.HasTagName(HTMLNames::colTag) ||
- element.HasTagName(HTMLNames::colgroupTag);
+ return element.HasTagName(html_names::kColTag) ||
+ element.HasTagName(html_names::kColgroupTag);
}
DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableColElement);
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_element.cc
index bcf1f64062d..09fcb4d09d0 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_element.cc
@@ -28,9 +28,9 @@
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_image_value.h"
#include "third_party/blink/renderer/core/css/css_inherited_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
@@ -49,10 +49,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTableElement::HTMLTableElement(Document& document)
- : HTMLElement(tableTag, document),
+ : HTMLElement(kTableTag, document),
border_attr_(false),
border_color_attr_(false),
frame_attr_(false),
@@ -81,12 +81,12 @@ void HTMLTableElement::setCaption(HTMLTableCaptionElement* new_caption,
HTMLTableSectionElement* HTMLTableElement::tHead() const {
return ToHTMLTableSectionElement(
- Traversal<HTMLElement>::FirstChild(*this, HasHTMLTagName(theadTag)));
+ Traversal<HTMLElement>::FirstChild(*this, HasHTMLTagName(kTheadTag)));
}
void HTMLTableElement::setTHead(HTMLTableSectionElement* new_head,
ExceptionState& exception_state) {
- if (new_head && !new_head->HasTagName(theadTag)) {
+ if (new_head && !new_head->HasTagName(kTheadTag)) {
exception_state.ThrowDOMException(DOMExceptionCode::kHierarchyRequestError,
"Not a thead element.");
return;
@@ -99,7 +99,7 @@ void HTMLTableElement::setTHead(HTMLTableSectionElement* new_head,
HTMLElement* child;
for (child = Traversal<HTMLElement>::FirstChild(*this); child;
child = Traversal<HTMLElement>::NextSibling(*child)) {
- if (!child->HasTagName(captionTag) && !child->HasTagName(colgroupTag))
+ if (!child->HasTagName(kCaptionTag) && !child->HasTagName(kColgroupTag))
break;
}
@@ -108,12 +108,12 @@ void HTMLTableElement::setTHead(HTMLTableSectionElement* new_head,
HTMLTableSectionElement* HTMLTableElement::tFoot() const {
return ToHTMLTableSectionElement(
- Traversal<HTMLElement>::FirstChild(*this, HasHTMLTagName(tfootTag)));
+ Traversal<HTMLElement>::FirstChild(*this, HasHTMLTagName(kTfootTag)));
}
void HTMLTableElement::setTFoot(HTMLTableSectionElement* new_foot,
ExceptionState& exception_state) {
- if (new_foot && !new_foot->HasTagName(tfootTag)) {
+ if (new_foot && !new_foot->HasTagName(kTfootTag)) {
exception_state.ThrowDOMException(DOMExceptionCode::kHierarchyRequestError,
"Not a tfoot element.");
return;
@@ -129,7 +129,7 @@ HTMLTableSectionElement* HTMLTableElement::createTHead() {
if (HTMLTableSectionElement* existing_head = tHead())
return existing_head;
HTMLTableSectionElement* head =
- HTMLTableSectionElement::Create(theadTag, GetDocument());
+ HTMLTableSectionElement::Create(kTheadTag, GetDocument());
setTHead(head, IGNORE_EXCEPTION_FOR_TESTING);
return head;
}
@@ -142,7 +142,7 @@ HTMLTableSectionElement* HTMLTableElement::createTFoot() {
if (HTMLTableSectionElement* existing_foot = tFoot())
return existing_foot;
HTMLTableSectionElement* foot =
- HTMLTableSectionElement::Create(tfootTag, GetDocument());
+ HTMLTableSectionElement::Create(kTfootTag, GetDocument());
setTFoot(foot, IGNORE_EXCEPTION_FOR_TESTING);
return foot;
}
@@ -153,7 +153,7 @@ void HTMLTableElement::deleteTFoot() {
HTMLTableSectionElement* HTMLTableElement::createTBody() {
HTMLTableSectionElement* body =
- HTMLTableSectionElement::Create(tbodyTag, GetDocument());
+ HTMLTableSectionElement::Create(kTbodyTag, GetDocument());
Node* reference_element = LastBody() ? LastBody()->nextSibling() : nullptr;
InsertBefore(body, reference_element);
@@ -175,7 +175,7 @@ void HTMLTableElement::deleteCaption() {
HTMLTableSectionElement* HTMLTableElement::LastBody() const {
return ToHTMLTableSectionElement(
- Traversal<HTMLElement>::LastChild(*this, HasHTMLTagName(tbodyTag)));
+ Traversal<HTMLElement>::LastChild(*this, HasHTMLTagName(kTbodyTag)));
}
HTMLTableRowElement* HTMLTableElement::insertRow(
@@ -217,7 +217,7 @@ HTMLTableRowElement* HTMLTableElement::insertRow(
parent = LastBody();
if (!parent) {
HTMLTableSectionElement* new_body =
- HTMLTableSectionElement::Create(tbodyTag, GetDocument());
+ HTMLTableSectionElement::Create(kTbodyTag, GetDocument());
HTMLTableRowElement* new_row = HTMLTableRowElement::Create(GetDocument());
new_body->AppendChild(new_row, exception_state);
AppendChild(new_body, exception_state);
@@ -267,7 +267,7 @@ void HTMLTableElement::SetNeedsTableStyleRecalc() const {
while (element) {
element->SetNeedsStyleRecalc(
kLocalStyleChange,
- StyleChangeReasonForTracing::FromAttribute(rulesAttr));
+ StyleChangeReasonForTracing::FromAttribute(kRulesAttr));
if (IsHTMLTableCellElement(*element))
element = ElementTraversal::NextSkippingChildren(*element, this);
else
@@ -309,20 +309,20 @@ void HTMLTableElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == widthAttr) {
+ if (name == kWidthAttr) {
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
- } else if (name == borderAttr) {
+ } else if (name == kBorderAttr) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyBorderWidth, ParseBorderWidthAttribute(value),
CSSPrimitiveValue::UnitType::kPixels);
- } else if (name == bordercolorAttr) {
+ } else if (name == kBordercolorAttr) {
if (!value.IsEmpty())
AddHTMLColorToStyle(style, CSSPropertyBorderColor, value);
- } else if (name == bgcolorAttr) {
+ } else if (name == kBgcolorAttr) {
AddHTMLColorToStyle(style, CSSPropertyBackgroundColor, value);
- } else if (name == backgroundAttr) {
+ } else if (name == kBackgroundAttr) {
String url = StripLeadingAndTrailingHTMLSpaces(value);
if (!url.IsEmpty()) {
UseCounter::Count(
@@ -335,16 +335,16 @@ void HTMLTableElement::CollectStyleForPresentationAttribute(
style->SetProperty(
CSSPropertyValue(GetCSSPropertyBackgroundImage(), *image_value));
}
- } else if (name == valignAttr) {
+ } else if (name == kValignAttr) {
if (!value.IsEmpty())
AddPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign,
value);
- } else if (name == cellspacingAttr) {
+ } else if (name == kCellspacingAttr) {
if (!value.IsEmpty()) {
AddHTMLLengthToStyle(style, CSSPropertyBorderSpacing, value,
kDontAllowPercentageValues);
}
- } else if (name == alignAttr) {
+ } else if (name == kAlignAttr) {
if (!value.IsEmpty()) {
if (DeprecatedEqualIgnoringCase(value, "center")) {
AddPropertyToPresentationAttributeStyle(
@@ -355,13 +355,13 @@ void HTMLTableElement::CollectStyleForPresentationAttribute(
AddPropertyToPresentationAttributeStyle(style, CSSPropertyFloat, value);
}
}
- } else if (name == rulesAttr) {
+ } else if (name == kRulesAttr) {
// The presence of a valid rules attribute causes border collapsing to be
// enabled.
if (rules_attr_ != kUnsetRules)
AddPropertyToPresentationAttributeStyle(style, CSSPropertyBorderCollapse,
CSSValueCollapse);
- } else if (name == frameAttr) {
+ } else if (name == kFrameAttr) {
bool border_top;
bool border_right;
bool border_bottom;
@@ -390,11 +390,11 @@ void HTMLTableElement::CollectStyleForPresentationAttribute(
bool HTMLTableElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == widthAttr || name == heightAttr || name == bgcolorAttr ||
- name == backgroundAttr || name == valignAttr || name == vspaceAttr ||
- name == hspaceAttr || name == alignAttr || name == cellspacingAttr ||
- name == borderAttr || name == bordercolorAttr || name == frameAttr ||
- name == rulesAttr)
+ if (name == kWidthAttr || name == kHeightAttr || name == kBgcolorAttr ||
+ name == kBackgroundAttr || name == kValignAttr || name == kVspaceAttr ||
+ name == kHspaceAttr || name == kAlignAttr || name == kCellspacingAttr ||
+ name == kBorderAttr || name == kBordercolorAttr || name == kFrameAttr ||
+ name == kRulesAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -405,12 +405,12 @@ void HTMLTableElement::ParseAttribute(
CellBorders borders_before = GetCellBorders();
unsigned short old_padding = padding_;
- if (name == borderAttr) {
+ if (name == kBorderAttr) {
// FIXME: This attribute is a mess.
border_attr_ = ParseBorderWidthAttribute(params.new_value);
- } else if (name == bordercolorAttr) {
+ } else if (name == kBordercolorAttr) {
border_color_attr_ = !params.new_value.IsEmpty();
- } else if (name == frameAttr) {
+ } else if (name == kFrameAttr) {
// FIXME: This attribute is a mess.
bool border_top;
bool border_right;
@@ -418,7 +418,7 @@ void HTMLTableElement::ParseAttribute(
bool border_left;
frame_attr_ = GetBordersFromFrameAttributeValue(
params.new_value, border_top, border_right, border_bottom, border_left);
- } else if (name == rulesAttr) {
+ } else if (name == kRulesAttr) {
rules_attr_ = kUnsetRules;
if (DeprecatedEqualIgnoringCase(params.new_value, "none"))
rules_attr_ = kNoneRules;
@@ -430,12 +430,12 @@ void HTMLTableElement::ParseAttribute(
rules_attr_ = kColsRules;
else if (DeprecatedEqualIgnoringCase(params.new_value, "all"))
rules_attr_ = kAllRules;
- } else if (params.name == cellpaddingAttr) {
+ } else if (params.name == kCellpaddingAttr) {
if (!params.new_value.IsEmpty())
padding_ = std::max(0, params.new_value.ToInt());
else
padding_ = 1;
- } else if (params.name == colsAttr) {
+ } else if (params.name == kColsAttr) {
// ###
} else {
HTMLElement::ParseAttribute(params);
@@ -592,16 +592,16 @@ const CSSPropertyValueSet* HTMLTableElement::AdditionalGroupStyle(bool rows) {
}
bool HTMLTableElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == backgroundAttr ||
+ return attribute.GetName() == kBackgroundAttr ||
HTMLElement::IsURLAttribute(attribute);
}
bool HTMLTableElement::HasLegalLinkAttribute(const QualifiedName& name) const {
- return name == backgroundAttr || HTMLElement::HasLegalLinkAttribute(name);
+ return name == kBackgroundAttr || HTMLElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLTableElement::SubResourceAttributeName() const {
- return backgroundAttr;
+ return kBackgroundAttr;
}
HTMLTableRowsCollection* HTMLTableElement::rows() {
@@ -613,11 +613,11 @@ HTMLCollection* HTMLTableElement::tBodies() {
}
const AtomicString& HTMLTableElement::Rules() const {
- return getAttribute(rulesAttr);
+ return getAttribute(kRulesAttr);
}
const AtomicString& HTMLTableElement::Summary() const {
- return getAttribute(summaryAttr);
+ return getAttribute(kSummaryAttr);
}
void HTMLTableElement::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_part_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_part_element.cc
index d8973726080..3f98eaee80a 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_part_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_part_element.cc
@@ -25,8 +25,8 @@
#include "third_party/blink/renderer/core/html/html_table_part_element.h"
#include "third_party/blink/renderer/core/css/css_image_value.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
@@ -38,12 +38,12 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
bool HTMLTablePartElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == bgcolorAttr || name == backgroundAttr || name == valignAttr ||
- name == alignAttr || name == heightAttr)
+ if (name == kBgcolorAttr || name == kBackgroundAttr || name == kValignAttr ||
+ name == kAlignAttr || name == kHeightAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -52,9 +52,9 @@ void HTMLTablePartElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == bgcolorAttr) {
+ if (name == kBgcolorAttr) {
AddHTMLColorToStyle(style, CSSPropertyBackgroundColor, value);
- } else if (name == backgroundAttr) {
+ } else if (name == kBackgroundAttr) {
String url = StripLeadingAndTrailingHTMLSpaces(value);
if (!url.IsEmpty()) {
UseCounter::Count(
@@ -67,7 +67,7 @@ void HTMLTablePartElement::CollectStyleForPresentationAttribute(
style->SetProperty(
CSSPropertyValue(GetCSSPropertyBackgroundImage(), *image_value));
}
- } else if (name == valignAttr) {
+ } else if (name == kValignAttr) {
if (DeprecatedEqualIgnoringCase(value, "top"))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign,
CSSValueTop);
@@ -83,7 +83,7 @@ void HTMLTablePartElement::CollectStyleForPresentationAttribute(
else
AddPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign,
value);
- } else if (name == alignAttr) {
+ } else if (name == kAlignAttr) {
if (DeprecatedEqualIgnoringCase(value, "middle") ||
DeprecatedEqualIgnoringCase(value, "center"))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign,
@@ -100,7 +100,7 @@ void HTMLTablePartElement::CollectStyleForPresentationAttribute(
else
AddPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign,
value);
- } else if (name == heightAttr) {
+ } else if (name == kHeightAttr) {
if (!value.IsEmpty())
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
} else {
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_row_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_row_element.cc
index 7b248e833a4..12c9272ca98 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_row_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_row_element.cc
@@ -37,21 +37,21 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTableRowElement::HTMLTableRowElement(Document& document)
- : HTMLTablePartElement(trTag, document) {}
+ : HTMLTablePartElement(kTrTag, document) {}
DEFINE_NODE_FACTORY(HTMLTableRowElement)
bool HTMLTableRowElement::HasLegalLinkAttribute(
const QualifiedName& name) const {
- return name == backgroundAttr ||
+ return name == kBackgroundAttr ||
HTMLTablePartElement::HasLegalLinkAttribute(name);
}
const QualifiedName& HTMLTableRowElement::SubResourceAttributeName() const {
- return backgroundAttr;
+ return kBackgroundAttr;
}
static int FindIndexInRowCollection(const HTMLCollection& rows,
@@ -103,7 +103,7 @@ HTMLElement* HTMLTableRowElement::insertCell(int index,
}
HTMLTableCellElement* cell =
- HTMLTableCellElement::Create(tdTag, GetDocument());
+ HTMLTableCellElement::Create(kTdTag, GetDocument());
if (num_cells == index || index == -1)
AppendChild(cell, exception_state);
else
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.cc b/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.cc
index e9c293ab65d..8003df2ae80 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.cc
@@ -35,7 +35,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static inline bool IsInSection(HTMLTableRowElement& row,
const HTMLQualifiedName& section_tag) {
@@ -61,10 +61,10 @@ HTMLTableRowElement* HTMLTableRowsCollection::RowAfter(
HTMLElement* child = nullptr;
if (!previous)
child = Traversal<HTMLElement>::FirstChild(table);
- else if (IsInSection(*previous, theadTag))
+ else if (IsInSection(*previous, kTheadTag))
child = Traversal<HTMLElement>::NextSibling(*previous->parentNode());
for (; child; child = Traversal<HTMLElement>::NextSibling(*child)) {
- if (child->HasTagName(theadTag)) {
+ if (child->HasTagName(kTheadTag)) {
if (HTMLTableRowElement* row =
Traversal<HTMLTableRowElement>::FirstChild(*child))
return row;
@@ -73,16 +73,16 @@ HTMLTableRowElement* HTMLTableRowsCollection::RowAfter(
// If still looking at top level and bodies, find the next row in top level or
// the first in the next body section.
- if (!previous || IsInSection(*previous, theadTag))
+ if (!previous || IsInSection(*previous, kTheadTag))
child = Traversal<HTMLElement>::FirstChild(table);
else if (previous->parentNode() == table)
child = Traversal<HTMLElement>::NextSibling(*previous);
- else if (IsInSection(*previous, tbodyTag))
+ else if (IsInSection(*previous, kTbodyTag))
child = Traversal<HTMLElement>::NextSibling(*previous->parentNode());
for (; child; child = Traversal<HTMLElement>::NextSibling(*child)) {
if (auto* row = ToHTMLTableRowElementOrNull(child))
return row;
- if (child->HasTagName(tbodyTag)) {
+ if (child->HasTagName(kTbodyTag)) {
if (HTMLTableRowElement* row =
Traversal<HTMLTableRowElement>::FirstChild(*child))
return row;
@@ -90,12 +90,12 @@ HTMLTableRowElement* HTMLTableRowsCollection::RowAfter(
}
// Find the first row in the next foot section.
- if (!previous || !IsInSection(*previous, tfootTag))
+ if (!previous || !IsInSection(*previous, kTfootTag))
child = Traversal<HTMLElement>::FirstChild(table);
else
child = Traversal<HTMLElement>::NextSibling(*previous->parentNode());
for (; child; child = Traversal<HTMLElement>::NextSibling(*child)) {
- if (child->HasTagName(tfootTag)) {
+ if (child->HasTagName(kTfootTag)) {
if (HTMLTableRowElement* row =
Traversal<HTMLTableRowElement>::FirstChild(*child))
return row;
@@ -107,9 +107,9 @@ HTMLTableRowElement* HTMLTableRowsCollection::RowAfter(
HTMLTableRowElement* HTMLTableRowsCollection::LastRow(HTMLTableElement& table) {
for (HTMLElement* tfoot =
- Traversal<HTMLElement>::LastChild(table, HasHTMLTagName(tfootTag));
+ Traversal<HTMLElement>::LastChild(table, HasHTMLTagName(kTfootTag));
tfoot; tfoot = Traversal<HTMLElement>::PreviousSibling(
- *tfoot, HasHTMLTagName(tfootTag))) {
+ *tfoot, HasHTMLTagName(kTfootTag))) {
if (HTMLTableRowElement* last_row =
Traversal<HTMLTableRowElement>::LastChild(*tfoot))
return last_row;
@@ -119,7 +119,7 @@ HTMLTableRowElement* HTMLTableRowsCollection::LastRow(HTMLTableElement& table) {
child = Traversal<HTMLElement>::PreviousSibling(*child)) {
if (auto* row = ToHTMLTableRowElementOrNull(child))
return row;
- if (child->HasTagName(tbodyTag)) {
+ if (child->HasTagName(kTbodyTag)) {
if (HTMLTableRowElement* last_row =
Traversal<HTMLTableRowElement>::LastChild(*child))
return last_row;
@@ -127,9 +127,9 @@ HTMLTableRowElement* HTMLTableRowsCollection::LastRow(HTMLTableElement& table) {
}
for (HTMLElement* thead =
- Traversal<HTMLElement>::LastChild(table, HasHTMLTagName(theadTag));
+ Traversal<HTMLElement>::LastChild(table, HasHTMLTagName(kTheadTag));
thead; thead = Traversal<HTMLElement>::PreviousSibling(
- *thead, HasHTMLTagName(theadTag))) {
+ *thead, HasHTMLTagName(kTheadTag))) {
if (HTMLTableRowElement* last_row =
Traversal<HTMLTableRowElement>::LastChild(*thead))
return last_row;
@@ -149,7 +149,7 @@ HTMLTableRowsCollection::HTMLTableRowsCollection(ContainerNode& table)
HTMLTableRowsCollection* HTMLTableRowsCollection::Create(ContainerNode& table,
CollectionType type) {
DCHECK_EQ(type, kTableRows);
- return new HTMLTableRowsCollection(table);
+ return MakeGarbageCollected<HTMLTableRowsCollection>(table);
}
Element* HTMLTableRowsCollection::VirtualItemAfter(Element* previous) const {
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.h b/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.h
index 9b4133cd150..3e6d8bfeff6 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/html_table_rows_collection.h
@@ -41,6 +41,8 @@ class HTMLTableRowsCollection final : public HTMLCollection {
public:
static HTMLTableRowsCollection* Create(ContainerNode&, CollectionType);
+ explicit HTMLTableRowsCollection(ContainerNode&);
+
HTMLTableRowElement* Item(unsigned offset) const {
return ToHTMLTableRowElement(HTMLCollection::item(offset));
}
@@ -49,8 +51,6 @@ class HTMLTableRowsCollection final : public HTMLCollection {
static HTMLTableRowElement* LastRow(HTMLTableElement&);
private:
- explicit HTMLTableRowsCollection(ContainerNode&);
-
Element* VirtualItemAfter(Element*) const override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_section_element.cc b/chromium/third_party/blink/renderer/core/html/html_table_section_element.cc
index 640ee3942ea..1c5a455f461 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_section_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_table_section_element.cc
@@ -29,13 +29,10 @@
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_table_element.h"
#include "third_party/blink/renderer/core/html/html_table_row_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
namespace blink {
-using namespace HTMLNames;
-
inline HTMLTableSectionElement::HTMLTableSectionElement(
const QualifiedName& tag_name,
Document& document)
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_section_element.h b/chromium/third_party/blink/renderer/core/html/html_table_section_element.h
index 60c13dbfea8..151730e21e4 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_section_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_table_section_element.h
@@ -52,9 +52,9 @@ class HTMLTableSectionElement final : public HTMLTablePartElement {
};
inline bool IsHTMLTableSectionElement(const HTMLElement& element) {
- return element.HasTagName(HTMLNames::tbodyTag) ||
- element.HasTagName(HTMLNames::tfootTag) ||
- element.HasTagName(HTMLNames::theadTag);
+ return element.HasTagName(html_names::kTbodyTag) ||
+ element.HasTagName(html_names::kTfootTag) ||
+ element.HasTagName(html_names::kTheadTag);
}
DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLTableSectionElement);
diff --git a/chromium/third_party/blink/renderer/core/html/html_tag_collection.h b/chromium/third_party/blink/renderer/core/html/html_tag_collection.h
index aba5b54aef3..473123c3696 100644
--- a/chromium/third_party/blink/renderer/core/html/html_tag_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/html_tag_collection.h
@@ -38,15 +38,15 @@ class HTMLTagCollection final : public TagCollection {
CollectionType type,
const AtomicString& qualified_name) {
DCHECK_EQ(type, kHTMLTagCollectionType);
- return new HTMLTagCollection(root_node, qualified_name);
+ return MakeGarbageCollected<HTMLTagCollection>(root_node, qualified_name);
}
- bool ElementMatches(const Element&) const;
-
- private:
HTMLTagCollection(ContainerNode& root_node,
const AtomicString& qualified_name);
+ bool ElementMatches(const Element&) const;
+
+ private:
AtomicString lowered_qualified_name_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_template_element.cc b/chromium/third_party/blink/renderer/core/html/html_template_element.cc
index dc64c22fa32..1db069621d0 100644
--- a/chromium/third_party/blink/renderer/core/html/html_template_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_template_element.cc
@@ -36,10 +36,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTemplateElement::HTMLTemplateElement(Document& document)
- : HTMLElement(templateTag, document) {}
+ : HTMLElement(kTemplateTag, document) {}
DEFINE_NODE_FACTORY(HTMLTemplateElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_time_element.cc b/chromium/third_party/blink/renderer/core/html/html_time_element.cc
index 6ebe403bfc0..e0c9020ecd0 100644
--- a/chromium/third_party/blink/renderer/core/html/html_time_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_time_element.cc
@@ -9,12 +9,12 @@
namespace blink {
HTMLTimeElement::HTMLTimeElement(Document& document)
- : HTMLElement(HTMLNames::timeTag, document) {
+ : HTMLElement(html_names::kTimeTag, document) {
UseCounter::Count(document, WebFeature::kTimeElement);
}
HTMLTimeElement* HTMLTimeElement::Create(Document& document) {
- return new HTMLTimeElement(document);
+ return MakeGarbageCollected<HTMLTimeElement>(document);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/html_time_element.h b/chromium/third_party/blink/renderer/core/html/html_time_element.h
index ec45b068c99..8572a309b64 100644
--- a/chromium/third_party/blink/renderer/core/html/html_time_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_time_element.h
@@ -15,7 +15,6 @@ class CORE_EXPORT HTMLTimeElement final : public HTMLElement {
public:
static HTMLTimeElement* Create(Document&);
- private:
HTMLTimeElement(Document&);
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_title_element.cc b/chromium/third_party/blink/renderer/core/html/html_title_element.cc
index 7118b49f116..b54bd60c582 100644
--- a/chromium/third_party/blink/renderer/core/html/html_title_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_title_element.cc
@@ -32,10 +32,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLTitleElement::HTMLTitleElement(Document& document)
- : HTMLElement(titleTag, document),
+ : HTMLElement(kTitleTag, document),
ignore_title_updates_when_children_change_(false) {}
DEFINE_NODE_FACTORY(HTMLTitleElement)
diff --git a/chromium/third_party/blink/renderer/core/html/html_ulist_element.cc b/chromium/third_party/blink/renderer/core/html/html_ulist_element.cc
index 41c4ade872d..f4587806428 100644
--- a/chromium/third_party/blink/renderer/core/html/html_ulist_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_ulist_element.cc
@@ -22,21 +22,21 @@
#include "third_party/blink/renderer/core/html/html_ulist_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLUListElement::HTMLUListElement(Document& document)
- : HTMLElement(ulTag, document) {}
+ : HTMLElement(kUlTag, document) {}
DEFINE_NODE_FACTORY(HTMLUListElement)
bool HTMLUListElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == typeAttr)
+ if (name == kTypeAttr)
return true;
return HTMLElement::IsPresentationAttribute(name);
}
@@ -45,7 +45,7 @@ void HTMLUListElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == typeAttr) {
+ if (name == kTypeAttr) {
if (DeprecatedEqualIgnoringCase(value, "disc"))
AddPropertyToPresentationAttributeStyle(style, CSSPropertyListStyleType,
CSSValueDisc);
diff --git a/chromium/third_party/blink/renderer/core/html/html_unknown_element.h b/chromium/third_party/blink/renderer/core/html/html_unknown_element.h
index dfbdf0636da..135dac86d1d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_unknown_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_unknown_element.h
@@ -40,12 +40,12 @@ class HTMLUnknownElement final : public HTMLElement {
public:
static HTMLUnknownElement* Create(const QualifiedName& tag_name,
Document& document) {
- return new HTMLUnknownElement(tag_name, document);
+ return MakeGarbageCollected<HTMLUnknownElement>(tag_name, document);
}
- private:
HTMLUnknownElement(const QualifiedName&, Document&);
+ private:
bool IsHTMLUnknownElement() const override { return true; }
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_view_source_document.cc b/chromium/third_party/blink/renderer/core/html/html_view_source_document.cc
index cd50273127c..fa0c0f937e8 100644
--- a/chromium/third_party/blink/renderer/core/html/html_view_source_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_view_source_document.cc
@@ -41,7 +41,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -74,12 +74,12 @@ void HTMLViewSourceDocument::CreateContainingTable() {
// Create a line gutter div that can be used to make sure the gutter extends
// down the height of the whole document.
HTMLDivElement* div = HTMLDivElement::Create(*this);
- div->setAttribute(classAttr, "line-gutter-backdrop");
+ div->setAttribute(kClassAttr, "line-gutter-backdrop");
body->ParserAppendChild(div);
HTMLTableElement* table = HTMLTableElement::Create(*this);
body->ParserAppendChild(table);
- tbody_ = HTMLTableSectionElement::Create(tbodyTag, *this);
+ tbody_ = HTMLTableSectionElement::Create(kTbodyTag, *this);
table->ParserAppendChild(tbody_);
current_ = tbody_;
line_number_ = 0;
@@ -155,21 +155,21 @@ void HTMLViewSourceDocument::ProcessTagToken(const String& source,
index = AddRange(source, index, iter->NameRange().end - token.StartIndex(),
"html-attribute-name");
- if (tag_name == baseTag && name == hrefAttr)
+ if (tag_name == kBaseTag && name == kHrefAttr)
AddBase(value);
index =
AddRange(source, index, iter->ValueRange().start - token.StartIndex(),
g_empty_atom);
- if (name == srcsetAttr) {
+ if (name == kSrcsetAttr) {
index =
AddSrcset(source, index, iter->ValueRange().end - token.StartIndex());
} else {
- bool is_link = name == srcAttr || name == hrefAttr;
+ bool is_link = name == kSrcAttr || name == kHrefAttr;
index =
AddRange(source, index, iter->ValueRange().end - token.StartIndex(),
- "html-attribute-value", is_link, tag_name == aTag, value);
+ "html-attribute-value", is_link, tag_name == kATag, value);
}
++iter;
@@ -199,7 +199,7 @@ Element* HTMLViewSourceDocument::AddSpanWithClassName(
}
HTMLSpanElement* span = HTMLSpanElement::Create(*this);
- span->setAttribute(classAttr, class_name);
+ span->setAttribute(kClassAttr, class_name);
current_->ParserAppendChild(span);
return span;
}
@@ -211,14 +211,14 @@ void HTMLViewSourceDocument::AddLine(const AtomicString& class_name) {
// Create a cell that will hold the line number (it is generated in the
// stylesheet using counters).
- HTMLTableCellElement* td = HTMLTableCellElement::Create(tdTag, *this);
- td->setAttribute(classAttr, "line-number");
- td->SetIntegralAttribute(valueAttr, ++line_number_);
+ HTMLTableCellElement* td = HTMLTableCellElement::Create(kTdTag, *this);
+ td->setAttribute(kClassAttr, "line-number");
+ td->SetIntegralAttribute(kValueAttr, ++line_number_);
trow->ParserAppendChild(td);
// Create a second cell for the line contents
- td = HTMLTableCellElement::Create(tdTag, *this);
- td->setAttribute(classAttr, "line-content");
+ td = HTMLTableCellElement::Create(kTdTag, *this);
+ td->setAttribute(kClassAttr, "line-content");
trow->ParserAppendChild(td);
current_ = td_ = td;
@@ -294,7 +294,7 @@ int HTMLViewSourceDocument::AddRange(const String& source,
Element* HTMLViewSourceDocument::AddBase(const AtomicString& href) {
HTMLBaseElement* base = HTMLBaseElement::Create(*this);
- base->setAttribute(hrefAttr, href);
+ base->setAttribute(kHrefAttr, href);
current_->ParserAppendChild(base);
return base;
}
@@ -311,13 +311,13 @@ Element* HTMLViewSourceDocument::AddLink(const AtomicString& url,
class_value = "html-attribute-value html-external-link";
else
class_value = "html-attribute-value html-resource-link";
- anchor->setAttribute(classAttr, class_value);
- anchor->setAttribute(targetAttr, "_blank");
- anchor->setAttribute(hrefAttr, url);
- anchor->setAttribute(relAttr, "noreferrer noopener");
+ anchor->setAttribute(kClassAttr, class_value);
+ anchor->setAttribute(kTargetAttr, "_blank");
+ anchor->setAttribute(kHrefAttr, url);
+ anchor->setAttribute(kRelAttr, "noreferrer noopener");
// Disallow JavaScript hrefs. https://crbug.com/808407
if (anchor->Url().ProtocolIsJavaScript())
- anchor->setAttribute(hrefAttr, "about:blank");
+ anchor->setAttribute(kHrefAttr, "about:blank");
current_->ParserAppendChild(anchor);
return anchor;
}
@@ -350,7 +350,7 @@ void HTMLViewSourceDocument::MaybeAddSpanForAnnotation(
SourceAnnotation annotation) {
if (annotation == kAnnotateSourceAsXSS) {
current_ = AddSpanWithClassName("highlight");
- current_->setAttribute(titleAttr, kXSSDetected);
+ current_->setAttribute(kTitleAttr, kXSSDetected);
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_view_source_document.h b/chromium/third_party/blink/renderer/core/html/html_view_source_document.h
index e6a540bc3d8..10644df2bde 100644
--- a/chromium/third_party/blink/renderer/core/html/html_view_source_document.h
+++ b/chromium/third_party/blink/renderer/core/html/html_view_source_document.h
@@ -40,16 +40,16 @@ class CORE_EXPORT HTMLViewSourceDocument final : public HTMLDocument {
static HTMLViewSourceDocument* Create(const DocumentInit& initializer,
const String& mime_type) {
- return new HTMLViewSourceDocument(initializer, mime_type);
+ return MakeGarbageCollected<HTMLViewSourceDocument>(initializer, mime_type);
}
+ HTMLViewSourceDocument(const DocumentInit&, const String& mime_type);
+
void AddSource(const String&, HTMLToken&, SourceAnnotation);
void Trace(blink::Visitor*) override;
private:
- HTMLViewSourceDocument(const DocumentInit&, const String& mime_type);
-
DocumentParser* CreateParser() override;
void ProcessDoctypeToken(const String& source, HTMLToken&);
@@ -80,6 +80,9 @@ class CORE_EXPORT HTMLViewSourceDocument final : public HTMLDocument {
Element* AddLink(const AtomicString& url, bool is_anchor);
Element* AddBase(const AtomicString& href);
+ // A view-source document is not a regular WebPage.
+ bool HasCustomizedFeaturePolicy() const final { return false; }
+
String type_;
Member<Element> current_;
Member<HTMLTableSectionElement> tbody_;
diff --git a/chromium/third_party/blink/renderer/core/html/html_wbr_element.cc b/chromium/third_party/blink/renderer/core/html/html_wbr_element.cc
index f901e6ca775..053085b2505 100644
--- a/chromium/third_party/blink/renderer/core/html/html_wbr_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_wbr_element.cc
@@ -35,10 +35,10 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline HTMLWBRElement::HTMLWBRElement(Document& document)
- : HTMLElement(wbrTag, document) {}
+ : HTMLElement(kWbrTag, document) {}
DEFINE_NODE_FACTORY(HTMLWBRElement)
diff --git a/chromium/third_party/blink/renderer/core/html/image_document.cc b/chromium/third_party/blink/renderer/core/html/image_document.cc
index 06eec5f2cee..7deabda1b28 100644
--- a/chromium/third_party/blink/renderer/core/html/image_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/image_document.cc
@@ -25,11 +25,11 @@
#include "third_party/blink/renderer/core/html/image_document.h"
#include <limits>
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
#include "third_party/blink/renderer/core/dom/raw_data_document_parser.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
@@ -57,12 +57,12 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class ImageEventListener : public EventListener {
public:
static ImageEventListener* Create(ImageDocument* document) {
- return new ImageEventListener(document);
+ return MakeGarbageCollected<ImageEventListener>(document);
}
static const ImageEventListener* Cast(const EventListener* listener) {
return listener->GetType() == kImageEventListenerType
@@ -70,6 +70,9 @@ class ImageEventListener : public EventListener {
: nullptr;
}
+ ImageEventListener(ImageDocument* document)
+ : EventListener(kImageEventListenerType), doc_(document) {}
+
bool operator==(const EventListener& other) const override;
void Trace(blink::Visitor* visitor) override {
@@ -78,10 +81,7 @@ class ImageEventListener : public EventListener {
}
private:
- ImageEventListener(ImageDocument* document)
- : EventListener(kImageEventListenerType), doc_(document) {}
-
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
Member<ImageDocument> doc_;
};
@@ -89,17 +89,17 @@ class ImageEventListener : public EventListener {
class ImageDocumentParser : public RawDataDocumentParser {
public:
static ImageDocumentParser* Create(ImageDocument* document) {
- return new ImageDocumentParser(document);
+ return MakeGarbageCollected<ImageDocumentParser>(document);
}
+ ImageDocumentParser(ImageDocument* document)
+ : RawDataDocumentParser(document) {}
+
ImageDocument* GetDocument() const {
return ToImageDocument(RawDataDocumentParser::GetDocument());
}
private:
- ImageDocumentParser(ImageDocument* document)
- : RawDataDocumentParser(document) {}
-
void AppendBytes(const char*, size_t) override;
void Finish() override;
};
@@ -128,8 +128,10 @@ void ImageDocumentParser::AppendBytes(const char* data, size_t length) {
LocalFrame* frame = GetDocument()->GetFrame();
Settings* settings = frame->GetSettings();
- if (!frame->GetContentSettingsClient()->AllowImage(
- !settings || settings->GetImagesEnabled(), GetDocument()->Url()))
+ bool allow_image = !settings || settings->GetImagesEnabled();
+ if (auto* client = frame->GetContentSettingsClient())
+ allow_image = client->AllowImage(allow_image, GetDocument()->Url());
+ if (!allow_image)
return;
if (GetDocument()->CachedImageResourceDeprecated()) {
@@ -223,20 +225,20 @@ void ImageDocument::CreateDocumentStructure() {
HTMLHeadElement* head = HTMLHeadElement::Create(*this);
HTMLMetaElement* meta = HTMLMetaElement::Create(*this);
- meta->setAttribute(nameAttr, "viewport");
- meta->setAttribute(contentAttr, "width=device-width, minimum-scale=0.1");
+ meta->setAttribute(kNameAttr, "viewport");
+ meta->setAttribute(kContentAttr, "width=device-width, minimum-scale=0.1");
head->AppendChild(meta);
HTMLBodyElement* body = HTMLBodyElement::Create(*this);
if (ShouldShrinkToFit()) {
// Display the image prominently centered in the frame.
- body->setAttribute(styleAttr, "margin: 0px; background: #0e0e0e;");
+ body->setAttribute(kStyleAttr, "margin: 0px; background: #0e0e0e;");
// See w3c example on how to center an element:
// https://www.w3.org/Style/Examples/007/center.en.html
div_element_ = HTMLDivElement::Create(*this);
- div_element_->setAttribute(styleAttr,
+ div_element_->setAttribute(kStyleAttr,
"display: flex;"
"flex-direction: column;"
"justify-content: center;"
@@ -255,7 +257,7 @@ void ImageDocument::CreateDocumentStructure() {
ShadowRoot& shadow_root = body->EnsureUserAgentShadowRoot();
shadow_root.AppendChild(div_element_);
} else {
- body->setAttribute(styleAttr, "margin: 0px;");
+ body->setAttribute(kStyleAttr, "margin: 0px;");
}
WillInsertBody();
@@ -274,14 +276,15 @@ void ImageDocument::CreateDocumentStructure() {
// Add event listeners
EventListener* listener = ImageEventListener::Create(this);
if (LocalDOMWindow* dom_window = domWindow())
- dom_window->addEventListener(EventTypeNames::resize, listener, false);
+ dom_window->addEventListener(event_type_names::kResize, listener, false);
if (shrink_to_fit_mode_ == kDesktop) {
- image_element_->addEventListener(EventTypeNames::click, listener, false);
+ image_element_->addEventListener(event_type_names::kClick, listener,
+ false);
} else if (shrink_to_fit_mode_ == kViewport) {
- image_element_->addEventListener(EventTypeNames::touchend, listener,
+ image_element_->addEventListener(event_type_names::kTouchend, listener,
false);
- image_element_->addEventListener(EventTypeNames::touchcancel, listener,
+ image_element_->addEventListener(event_type_names::kTouchcancel, listener,
false);
}
}
@@ -407,7 +410,7 @@ void ImageDocument::UpdateImageStyle() {
}
}
- image_element_->setAttribute(styleAttr, image_style.ToAtomicString());
+ image_element_->setAttribute(kStyleAttr, image_style.ToAtomicString());
}
void ImageDocument::ImageUpdated() {
@@ -559,14 +562,15 @@ void ImageDocument::Trace(blink::Visitor* visitor) {
// --------
-void ImageEventListener::handleEvent(ExecutionContext*, Event* event) {
- if (event->type() == EventTypeNames::resize) {
+void ImageEventListener::Invoke(ExecutionContext*, Event* event) {
+ if (event->type() == event_type_names::kResize) {
doc_->WindowSizeChanged();
- } else if (event->type() == EventTypeNames::click && event->IsMouseEvent()) {
+ } else if (event->type() == event_type_names::kClick &&
+ event->IsMouseEvent()) {
MouseEvent* mouse_event = ToMouseEvent(event);
doc_->ImageClicked(mouse_event->x(), mouse_event->y());
- } else if ((event->type() == EventTypeNames::touchend ||
- event->type() == EventTypeNames::touchcancel) &&
+ } else if ((event->type() == event_type_names::kTouchend ||
+ event->type() == event_type_names::kTouchcancel) &&
event->IsTouchEvent()) {
doc_->UpdateImageStyle();
}
diff --git a/chromium/third_party/blink/renderer/core/html/image_document.h b/chromium/third_party/blink/renderer/core/html/image_document.h
index 36c0114d292..e8cf65d046b 100644
--- a/chromium/third_party/blink/renderer/core/html/image_document.h
+++ b/chromium/third_party/blink/renderer/core/html/image_document.h
@@ -37,9 +37,11 @@ class ImageResource;
class CORE_EXPORT ImageDocument final : public HTMLDocument {
public:
static ImageDocument* Create(const DocumentInit& initializer) {
- return new ImageDocument(initializer);
+ return MakeGarbageCollected<ImageDocument>(initializer);
}
+ explicit ImageDocument(const DocumentInit&);
+
ImageResourceContent* CachedImage();
// TODO(hiroshige): Remove this.
@@ -58,8 +60,6 @@ class CORE_EXPORT ImageDocument final : public HTMLDocument {
void Trace(blink::Visitor*) override;
private:
- explicit ImageDocument(const DocumentInit&);
-
DocumentParser* CreateParser() override;
void CreateDocumentStructure();
diff --git a/chromium/third_party/blink/renderer/core/html/image_document_test.cc b/chromium/third_party/blink/renderer/core/html/image_document_test.cc
index fb661d20fe3..4caa631220b 100644
--- a/chromium/third_party/blink/renderer/core/html/image_document_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/image_document_test.cc
@@ -99,7 +99,7 @@ void ImageDocumentTest::CreateDocumentWithoutLoadingImage(int view_width,
int view_height) {
Page::PageClients page_clients;
FillWithEmptyClients(page_clients);
- chrome_client_ = new WindowToViewportScalingChromeClient();
+ chrome_client_ = MakeGarbageCollected<WindowToViewportScalingChromeClient>();
page_clients.chrome_client = chrome_client_;
dummy_page_holder_ =
DummyPageHolder::Create(IntSize(view_width, view_height), &page_clients);
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.cc b/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.cc
index 92e15b086a0..7f72b8d9c46 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.cc
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.cc
@@ -69,7 +69,7 @@ void HTMLImportLoader::ResponseReceived(
// Resource may already have been loaded with the import loader
// being added as a client later & now being notified. Fail early.
if (resource->LoadFailedOrCanceled() || response.HttpStatusCode() >= 400 ||
- !response.HttpHeaderField(HTTPNames::Content_Disposition).IsNull()) {
+ !response.HttpHeaderField(http_names::kContentDisposition).IsNull()) {
SetState(kStateError);
return;
}
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.h b/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.h
index 8ca9be2ee1e..f87ea503410 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.h
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_import_loader.h
@@ -63,9 +63,10 @@ class HTMLImportLoader final
};
static HTMLImportLoader* Create(HTMLImportsController* controller) {
- return new HTMLImportLoader(controller);
+ return MakeGarbageCollected<HTMLImportLoader>(controller);
}
+ HTMLImportLoader(HTMLImportsController*);
~HTMLImportLoader() final;
void Dispose();
@@ -95,8 +96,6 @@ class HTMLImportLoader final
void Trace(blink::Visitor*) override;
private:
- HTMLImportLoader(HTMLImportsController*);
-
// RawResourceClient overrides:
void ResponseReceived(Resource*,
const ResourceResponse&,
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc b/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc
index be259e347cb..9c10e031e86 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc
@@ -12,7 +12,7 @@
namespace blink {
HTMLImportTreeRoot* HTMLImportTreeRoot::Create(Document* document) {
- return new HTMLImportTreeRoot(document);
+ return MakeGarbageCollected<HTMLImportTreeRoot>(document);
}
HTMLImportTreeRoot::HTMLImportTreeRoot(Document* document)
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.h b/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.h
index 825fbb294ec..0baace67990 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.h
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_import_tree_root.h
@@ -20,6 +20,7 @@ class HTMLImportTreeRoot final : public HTMLImport, public NameClient {
public:
static HTMLImportTreeRoot* Create(Document*);
+ explicit HTMLImportTreeRoot(Document*);
~HTMLImportTreeRoot() final;
void Dispose();
@@ -40,8 +41,6 @@ class HTMLImportTreeRoot final : public HTMLImport, public NameClient {
}
private:
- explicit HTMLImportTreeRoot(Document*);
-
void RecalcTimerFired(TimerBase*);
TraceWrapperMember<Document> document_;
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.cc b/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.cc
index 76282a097ea..96f17c3bf4b 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.cc
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.cc
@@ -84,7 +84,8 @@ HTMLImportChild* HTMLImportsController::CreateChild(
WebFeature::kHTMLImportsAsyncAttribute);
}
- HTMLImportChild* child = new HTMLImportChild(url, loader, client, mode);
+ HTMLImportChild* child =
+ MakeGarbageCollected<HTMLImportChild>(url, loader, client, mode);
parent->AppendImport(child);
loader->AddImport(child);
return root_->Add(child);
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.h b/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.h
index 237ab8b90fd..74df532bbf9 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.h
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.h
@@ -52,9 +52,11 @@ class HTMLImportsController final
public NameClient {
public:
static HTMLImportsController* Create(Document& master) {
- return new HTMLImportsController(master);
+ return MakeGarbageCollected<HTMLImportsController>(master);
}
+ explicit HTMLImportsController(Document&);
+
HTMLImportTreeRoot* Root() const { return root_; }
bool ShouldBlockScriptExecution(const Document&) const;
@@ -77,8 +79,6 @@ class HTMLImportsController final
}
private:
- explicit HTMLImportsController(Document&);
-
HTMLImportChild* CreateChild(const KURL&,
HTMLImportLoader*,
HTMLImport* parent,
diff --git a/chromium/third_party/blink/renderer/core/html/imports/link_import.cc b/chromium/third_party/blink/renderer/core/html/imports/link_import.cc
index 9f7cfcb5f89..47e5978acf2 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/link_import.cc
+++ b/chromium/third_party/blink/renderer/core/html/imports/link_import.cc
@@ -30,6 +30,7 @@
#include "third_party/blink/renderer/core/html/imports/link_import.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/html/html_link_element.h"
#include "third_party/blink/renderer/core/html/imports/html_import_child.h"
@@ -41,14 +42,13 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
LinkImport* LinkImport::Create(HTMLLinkElement* owner) {
- return new LinkImport(owner);
+ return MakeGarbageCollected<LinkImport>(owner);
}
LinkImport::LinkImport(HTMLLinkElement* owner)
@@ -72,14 +72,14 @@ void LinkImport::Process() {
if (!ShouldLoadResource())
return;
- const KURL& url = owner_->GetNonEmptyURLAttribute(HTMLNames::hrefAttr);
+ const KURL& url = owner_->GetNonEmptyURLAttribute(html_names::kHrefAttr);
if (url.IsEmpty() || !url.IsValid()) {
DidFinish();
return;
}
ResourceRequest resource_request(GetDocument().CompleteURL(url));
- ReferrerPolicy referrer_policy = owner_->GetReferrerPolicy();
+ network::mojom::ReferrerPolicy referrer_policy = owner_->GetReferrerPolicy();
resource_request.SetReferrerPolicy(referrer_policy);
ResourceLoaderOptions options;
diff --git a/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc b/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc
index 4da61acd407..225b335ec65 100644
--- a/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc
+++ b/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc
@@ -21,8 +21,8 @@
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
diff --git a/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer_test.cc b/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer_test.cc
index 566013294d4..2a1da7a02eb 100644
--- a/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer_test.cc
@@ -20,6 +20,7 @@
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
@@ -77,22 +78,24 @@ constexpr std::pair<WebEffectiveConnectionType, const char*>
enum class LazyFrameLoadingFeatureStatus { kDisabled, kEnabled };
enum class LazyFrameVisibleLoadTimeFeatureStatus { kDisabled, kEnabled };
-class LazyLoadFramesTest : public SimTest,
- public ::testing::WithParamInterface<
- std::tuple<LazyFrameLoadingFeatureStatus,
- LazyFrameVisibleLoadTimeFeatureStatus,
- WebEffectiveConnectionType>> {
+class LazyLoadFramesParamsTest
+ : public SimTest,
+ public ::testing::WithParamInterface<
+ std::tuple<LazyFrameLoadingFeatureStatus,
+ LazyFrameVisibleLoadTimeFeatureStatus,
+ WebEffectiveConnectionType>> {
public:
static constexpr int kViewportWidth = 800;
static constexpr int kViewportHeight = 600;
- LazyLoadFramesTest()
+ LazyLoadFramesParamsTest()
: scoped_lazy_frame_loading_for_test_(
std::get<LazyFrameLoadingFeatureStatus>(GetParam()) ==
LazyFrameLoadingFeatureStatus::kEnabled),
scoped_lazy_frame_visible_load_time_metrics_for_test_(
std::get<LazyFrameVisibleLoadTimeFeatureStatus>(GetParam()) ==
- LazyFrameVisibleLoadTimeFeatureStatus::kEnabled) {}
+ LazyFrameVisibleLoadTimeFeatureStatus::kEnabled),
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(false) {}
void SetUp() override {
SetEffectiveConnectionTypeForTesting(
@@ -111,6 +114,7 @@ class LazyLoadFramesTest : public SimTest,
settings.SetLazyFrameLoadingDistanceThresholdPx2G(500);
settings.SetLazyFrameLoadingDistanceThresholdPx3G(600);
settings.SetLazyFrameLoadingDistanceThresholdPx4G(700);
+ settings.SetLazyLoadEnabled(true);
}
int GetLoadingDistanceThreshold() const {
@@ -243,11 +247,13 @@ class LazyLoadFramesTest : public SimTest,
ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test_;
ScopedLazyFrameVisibleLoadTimeMetricsForTest
scoped_lazy_frame_visible_load_time_metrics_for_test_;
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_;
HistogramTester histogram_tester_;
};
-TEST_P(LazyLoadFramesTest, SameOriginFrame) {
+TEST_P(LazyLoadFramesParamsTest, SameOriginFrame) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://example.com/subframe.html",
"text/html");
@@ -287,7 +293,7 @@ TEST_P(LazyLoadFramesTest, SameOriginFrame) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, AboveTheFoldFrame) {
+TEST_P(LazyLoadFramesParamsTest, AboveTheFoldFrame) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
"text/html");
@@ -332,7 +338,7 @@ TEST_P(LazyLoadFramesTest, AboveTheFoldFrame) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, BelowTheFoldButNearViewportFrame) {
+TEST_P(LazyLoadFramesParamsTest, BelowTheFoldButNearViewportFrame) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
"text/html");
@@ -389,7 +395,7 @@ TEST_P(LazyLoadFramesTest, BelowTheFoldButNearViewportFrame) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, HiddenAndTinyFrames) {
+TEST_P(LazyLoadFramesParamsTest, HiddenAndTinyFrames) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest display_none_frame_resource(
@@ -492,7 +498,7 @@ TEST_P(LazyLoadFramesTest, HiddenAndTinyFrames) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, LoadCrossOriginFrameFarFromViewport) {
+TEST_P(LazyLoadFramesParamsTest, LoadCrossOriginFrameFarFromViewport) {
std::unique_ptr<SimRequest> child_frame_resource =
LoadPageWithCrossOriginFrameFarFromViewport();
@@ -545,7 +551,7 @@ TEST_P(LazyLoadFramesTest, LoadCrossOriginFrameFarFromViewport) {
ExpectVisibleAfterDeferredSamplesIfApplicable(1);
}
-TEST_P(LazyLoadFramesTest,
+TEST_P(LazyLoadFramesParamsTest,
CrossOriginFrameFarFromViewportBecomesVisibleBeforeFinishedLoading) {
std::unique_ptr<SimRequest> child_frame_resource =
LoadPageWithCrossOriginFrameFarFromViewport();
@@ -597,7 +603,7 @@ TEST_P(LazyLoadFramesTest,
ExpectVisibleAfterDeferredSamplesIfApplicable(1);
}
-TEST_P(LazyLoadFramesTest, NestedFrameInCrossOriginFrameFarFromViewport) {
+TEST_P(LazyLoadFramesParamsTest, NestedFrameInCrossOriginFrameFarFromViewport) {
std::unique_ptr<SimRequest> child_frame_resource =
LoadPageWithCrossOriginFrameFarFromViewport();
@@ -643,7 +649,7 @@ TEST_P(LazyLoadFramesTest, NestedFrameInCrossOriginFrameFarFromViewport) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, AboutBlankChildFrameNavigation) {
+TEST_P(LazyLoadFramesParamsTest, AboutBlankChildFrameNavigation) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
"text/html");
@@ -697,7 +703,7 @@ TEST_P(LazyLoadFramesTest, AboutBlankChildFrameNavigation) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, JavascriptStringFrameUrl) {
+TEST_P(LazyLoadFramesParamsTest, JavascriptStringFrameUrl) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
@@ -729,7 +735,8 @@ TEST_P(LazyLoadFramesTest, JavascriptStringFrameUrl) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest, CrossOriginFrameFarFromViewportWithLazyLoadAttrOff) {
+TEST_P(LazyLoadFramesParamsTest,
+ CrossOriginFrameFarFromViewportWithLazyLoadAttrOff) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
"text/html");
@@ -769,7 +776,7 @@ TEST_P(LazyLoadFramesTest, CrossOriginFrameFarFromViewportWithLazyLoadAttrOff) {
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest,
+TEST_P(LazyLoadFramesParamsTest,
LoadSameOriginFrameFarFromViewportWithLazyLoadAttributeOn) {
SimRequest main_resource("https://example.com/", "text/html");
base::Optional<SimRequest> child_frame_resource;
@@ -866,7 +873,7 @@ TEST_P(LazyLoadFramesTest,
ExpectVisibleAfterDeferredSamplesIfApplicable(1);
}
-TEST_P(LazyLoadFramesTest,
+TEST_P(LazyLoadFramesParamsTest,
LoadCrossOriginFrameFarFromViewportThenSetLazyLoadAttributeOff) {
SimRequest main_resource("https://example.com/", "text/html");
base::Optional<SimRequest> child_frame_resource;
@@ -907,7 +914,7 @@ TEST_P(LazyLoadFramesTest,
Element* child_frame_element = GetDocument().getElementById("child_frame");
ASSERT_TRUE(child_frame_element);
- child_frame_element->setAttribute(HTMLNames::lazyloadAttr, "off");
+ child_frame_element->setAttribute(html_names::kLazyloadAttr, "off");
ExpectInitialDeferralActionHistogramSamplesIfApplicable(
LazyLoadFrameObserver::FrameInitialDeferralAction::kDeferred, 1);
@@ -935,7 +942,7 @@ TEST_P(LazyLoadFramesTest,
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred", 0);
}
-TEST_P(LazyLoadFramesTest,
+TEST_P(LazyLoadFramesParamsTest,
NestedFrameWithLazyLoadAttributeOnInFrameWithNoLazyLoadAttribute) {
std::unique_ptr<SimRequest> child_frame_resource =
LoadPageWithCrossOriginFrameFarFromViewport();
@@ -979,7 +986,7 @@ TEST_P(LazyLoadFramesTest,
EXPECT_TRUE(ConsoleMessages().Contains("child frame element onload"));
}
-TEST_P(LazyLoadFramesTest,
+TEST_P(LazyLoadFramesParamsTest,
NestedFrameWithLazyLoadAttributeOnInFrameWithLazyLoadAttributeOff) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
@@ -1029,7 +1036,7 @@ TEST_P(LazyLoadFramesTest,
EXPECT_TRUE(ConsoleMessages().Contains("child frame element onload"));
}
-TEST_P(LazyLoadFramesTest,
+TEST_P(LazyLoadFramesParamsTest,
NestedFrameWithLazyLoadAttributeOffInFrameWithLazyLoadAttributeOff) {
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
@@ -1078,7 +1085,7 @@ TEST_P(LazyLoadFramesTest,
INSTANTIATE_TEST_CASE_P(
LazyFrameLoading,
- LazyLoadFramesTest,
+ LazyLoadFramesParamsTest,
::testing::Combine(
::testing::Values(LazyFrameLoadingFeatureStatus::kDisabled,
LazyFrameLoadingFeatureStatus::kEnabled),
@@ -1091,6 +1098,159 @@ INSTANTIATE_TEST_CASE_P(
WebEffectiveConnectionType::kType3G,
WebEffectiveConnectionType::kType4G)));
+class LazyLoadFramesTest : public SimTest {
+ public:
+ static constexpr int kViewportWidth = 800;
+ static constexpr int kViewportHeight = 600;
+ static constexpr int kLoadingDistanceThresholdPx = 1000;
+
+ void SetUp() override {
+ SetEffectiveConnectionTypeForTesting(
+ WebEffectiveConnectionType::kTypeUnknown);
+
+ SimTest::SetUp();
+ WebView().Resize(WebSize(kViewportWidth, kViewportHeight));
+
+ Settings& settings = WebView().GetPage()->GetSettings();
+ settings.SetLazyFrameLoadingDistanceThresholdPxUnknown(
+ kLoadingDistanceThresholdPx);
+ settings.SetLazyLoadEnabled(true);
+ }
+
+ void TearDown() override {
+ GetNetworkStateNotifier().SetSaveDataEnabled(false);
+ SimTest::TearDown();
+ }
+
+ void TestCrossOriginFrameIsImmediatelyLoaded(const char* iframe_attributes) {
+ SimRequest main_resource("https://example.com/", "text/html");
+ SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
+ "text/html");
+ LoadURL("https://example.com/");
+
+ main_resource.Complete(String::Format(
+ R"HTML(
+ <body onload='console.log("main body onload");'>
+ <div style='height: %dpx;'></div>
+ <iframe src='https://crossorigin.com/subframe.html'
+ style='width: 200px; height: 200px;' %s
+ onload='console.log("child frame element onload");'></iframe>
+ </body>)HTML",
+ kViewportHeight + kLoadingDistanceThresholdPx + 100,
+ iframe_attributes));
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ child_frame_resource.Complete("");
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ EXPECT_TRUE(ConsoleMessages().Contains("main body onload"));
+ EXPECT_TRUE(ConsoleMessages().Contains("child frame element onload"));
+ }
+
+ void TestCrossOriginFrameIsLazilyLoaded(const char* iframe_attributes) {
+ SimRequest main_resource("https://example.com/", "text/html");
+ LoadURL("https://example.com/");
+
+ main_resource.Complete(String::Format(
+ R"HTML(
+ <body onload='console.log("main body onload");'>
+ <div style='height: %dpx;'></div>
+ <iframe src='https://crossorigin.com/subframe.html'
+ style='width: 200px; height: 200px;' %s
+ onload='console.log("child frame element onload");'></iframe>
+ </body>)HTML",
+ kViewportHeight + kLoadingDistanceThresholdPx + 100,
+ iframe_attributes));
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ // The body's load event should have already fired.
+ EXPECT_TRUE(ConsoleMessages().Contains("main body onload"));
+ EXPECT_FALSE(ConsoleMessages().Contains("child frame element onload"));
+
+ SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
+ "text/html");
+
+ // Scroll down near the child frame to cause the child frame to start
+ // loading.
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(
+ ScrollOffset(0, 150), kProgrammaticScroll);
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ EXPECT_FALSE(ConsoleMessages().Contains("child frame element onload"));
+
+ child_frame_resource.Complete("");
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ EXPECT_TRUE(ConsoleMessages().Contains("child frame element onload"));
+ }
+};
+
+TEST_F(LazyLoadFramesTest, LazyLoadWhenNotRestricted) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(false);
+
+ TestCrossOriginFrameIsLazilyLoaded("");
+}
+
+TEST_F(LazyLoadFramesTest,
+ LazyLoadWhenDataSaverDisabledAndNotRestrictedAttrOff) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(false);
+
+ TestCrossOriginFrameIsImmediatelyLoaded("lazyload='off'");
+}
+
+TEST_F(LazyLoadFramesTest, LazyLoadWhenDataSaverDisabledAndRestricted) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(true);
+
+ GetNetworkStateNotifier().SetSaveDataEnabled(false);
+ WebView().GetPage()->GetSettings().SetDataSaverHoldbackWebApi(false);
+ TestCrossOriginFrameIsImmediatelyLoaded("");
+}
+
+TEST_F(LazyLoadFramesTest, LazyLoadWhenDataSaverEnabledHoldbackAndRestricted) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(true);
+
+ GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ WebView().GetPage()->GetSettings().SetDataSaverHoldbackWebApi(true);
+ TestCrossOriginFrameIsImmediatelyLoaded("");
+}
+
+TEST_F(LazyLoadFramesTest, LazyLoadWhenDataSaverEnabledAndRestricted) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(true);
+
+ GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ WebView().GetPage()->GetSettings().SetDataSaverHoldbackWebApi(false);
+ TestCrossOriginFrameIsLazilyLoaded("");
+}
+
+TEST_F(LazyLoadFramesTest, LazyLoadWhenDataSaverDisabledAndRestrictedAttrOn) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedRestrictLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_lazy_frame_loading_to_data_saver_for_test_(true);
+
+ GetNetworkStateNotifier().SetSaveDataEnabled(false);
+ WebView().GetPage()->GetSettings().SetDataSaverHoldbackWebApi(false);
+ TestCrossOriginFrameIsLazilyLoaded("lazyload='on'");
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.cc b/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.cc
index 7681186dd9d..9ebbcba427a 100644
--- a/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.cc
+++ b/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.cc
@@ -148,6 +148,7 @@ void LazyLoadImageObserver::StartMonitoringVisibility(
WTF::BindRepeating(&LazyLoadImageObserver::OnVisibilityChanged,
WrapWeakPersistent(this)));
}
+ visible_load_time_metrics.record_visibility_metrics = true;
visibility_metrics_observer_->observe(image_element);
}
@@ -156,10 +157,10 @@ void LazyLoadImageObserver::OnLoadFinished(HTMLImageElement* image_element) {
VisibleLoadTimeMetrics& visible_load_time_metrics =
image_element->EnsureVisibleLoadTimeMetrics();
- if (visible_load_time_metrics.has_visibility_metrics_been_recorded)
+ if (!visible_load_time_metrics.record_visibility_metrics)
return;
- visible_load_time_metrics.has_visibility_metrics_been_recorded = true;
+ visible_load_time_metrics.record_visibility_metrics = false;
visibility_metrics_observer_->unobserve(image_element);
TimeDelta visible_load_delay;
diff --git a/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.h b/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.h
index 5a84e8eab4a..806ee5df855 100644
--- a/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.h
+++ b/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.h
@@ -26,7 +26,8 @@ class LazyLoadImageObserver final
bool is_initially_intersecting = false;
bool has_initial_intersection_been_set = false;
- bool has_visibility_metrics_been_recorded = false;
+ // True if metrics need to be recorded and has not been recorded yet.
+ bool record_visibility_metrics = false;
// Set when the image first becomes visible (i.e. appears in the viewport).
TimeTicks time_when_first_visible;
diff --git a/chromium/third_party/blink/renderer/core/html/link_manifest.cc b/chromium/third_party/blink/renderer/core/html/link_manifest.cc
index 41f4b80ad23..74f632115b0 100644
--- a/chromium/third_party/blink/renderer/core/html/link_manifest.cc
+++ b/chromium/third_party/blink/renderer/core/html/link_manifest.cc
@@ -12,7 +12,7 @@
namespace blink {
LinkManifest* LinkManifest::Create(HTMLLinkElement* owner) {
- return new LinkManifest(owner);
+ return MakeGarbageCollected<LinkManifest>(owner);
}
LinkManifest::LinkManifest(HTMLLinkElement* owner) : LinkResource(owner) {}
diff --git a/chromium/third_party/blink/renderer/core/html/link_manifest.h b/chromium/third_party/blink/renderer/core/html/link_manifest.h
index b1128e4cc51..92d114332ef 100644
--- a/chromium/third_party/blink/renderer/core/html/link_manifest.h
+++ b/chromium/third_party/blink/renderer/core/html/link_manifest.h
@@ -17,6 +17,7 @@ class LinkManifest final : public LinkResource {
public:
static LinkManifest* Create(HTMLLinkElement* owner);
+ explicit LinkManifest(HTMLLinkElement* owner);
~LinkManifest() override;
// LinkResource
@@ -24,9 +25,6 @@ class LinkManifest final : public LinkResource {
LinkResourceType GetType() const override { return kManifest; }
bool HasLoaded() const override;
void OwnerRemoved() override;
-
- private:
- explicit LinkManifest(HTMLLinkElement* owner);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/link_rel_attribute.cc b/chromium/third_party/blink/renderer/core/html/link_rel_attribute.cc
index fc388bbd463..f7fc3615a7c 100644
--- a/chromium/third_party/blink/renderer/core/html/link_rel_attribute.cc
+++ b/chromium/third_party/blink/renderer/core/html/link_rel_attribute.cc
@@ -94,8 +94,7 @@ LinkRelAttribute::LinkRelAttribute(const String& rel) : LinkRelAttribute() {
} else if (DeprecatedEqualIgnoringCase(link_type, "manifest")) {
is_manifest_ = true;
} else if (DeprecatedEqualIgnoringCase(link_type, "modulepreload")) {
- if (RuntimeEnabledFeatures::ModulePreloadEnabled())
- is_module_preload_ = true;
+ is_module_preload_ = true;
} else if (DeprecatedEqualIgnoringCase(link_type, "serviceworker")) {
is_service_worker_ = true;
} else if (DeprecatedEqualIgnoringCase(link_type, "canonical")) {
diff --git a/chromium/third_party/blink/renderer/core/html/link_resource.cc b/chromium/third_party/blink/renderer/core/html/link_resource.cc
index 520c0ecd6b4..35e7b21e9da 100644
--- a/chromium/third_party/blink/renderer/core/html/link_resource.cc
+++ b/chromium/third_party/blink/renderer/core/html/link_resource.cc
@@ -59,7 +59,7 @@ const Document& LinkResource::GetDocument() const {
}
WTF::TextEncoding LinkResource::GetCharset() const {
- AtomicString charset = owner_->getAttribute(HTMLNames::charsetAttr);
+ AtomicString charset = owner_->getAttribute(html_names::kCharsetAttr);
if (charset.IsEmpty() && GetDocument().GetFrame())
return GetDocument().Encoding();
return WTF::TextEncoding(charset);
diff --git a/chromium/third_party/blink/renderer/core/html/link_style.cc b/chromium/third_party/blink/renderer/core/html/link_style.cc
index fbec39a56ff..bccc8cbd29d 100644
--- a/chromium/third_party/blink/renderer/core/html/link_style.cc
+++ b/chromium/third_party/blink/renderer/core/html/link_style.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/html/link_style.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -21,13 +22,12 @@
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool StyleSheetTypeIsSupported(const String& type) {
String trimmed_type = ContentType(type).GetType();
@@ -36,7 +36,7 @@ static bool StyleSheetTypeIsSupported(const String& type) {
}
LinkStyle* LinkStyle::Create(HTMLLinkElement* owner) {
- return new LinkStyle(owner);
+ return MakeGarbageCollected<LinkStyle>(owner);
}
LinkStyle::LinkStyle(HTMLLinkElement* owner)
@@ -73,7 +73,7 @@ void LinkStyle::NotifyFinished(Resource* resource) {
// See the comment in pending_script.cc about why this check is necessary
// here, instead of in the resource fetcher. https://crbug.com/500701.
if (!cached_style_sheet->ErrorOccurred() &&
- !owner_->FastGetAttribute(integrityAttr).IsEmpty() &&
+ !owner_->FastGetAttribute(kIntegrityAttr).IsEmpty() &&
!cached_style_sheet->IntegrityMetadata().IsEmpty()) {
ResourceIntegrityDisposition disposition =
cached_style_sheet->IntegrityDisposition();
@@ -263,7 +263,7 @@ LinkStyle::LoadReturnValue LinkStyle::LoadStylesheetIfNeeded(
if (GetResource()) {
RemovePendingSheet();
ClearResource();
- ClearFetchFollowingCORS();
+ ClearFetchFollowingCors();
}
if (!owner_->ShouldLoadLink())
@@ -292,7 +292,7 @@ LinkStyle::LoadReturnValue LinkStyle::LoadStylesheetIfNeeded(
AddPendingSheet(blocking ? kBlocking : kNonBlocking);
if (params.cross_origin != kCrossOriginAttributeNotSet) {
- SetFetchFollowingCORS();
+ SetFetchFollowingCors();
}
// Load stylesheets that are not needed for the layout immediately with low
@@ -321,14 +321,14 @@ void LinkStyle::Process() {
DCHECK(owner_->ShouldProcessStyle());
const LinkLoadParameters params(
owner_->RelAttribute(),
- GetCrossOriginAttributeValue(owner_->FastGetAttribute(crossoriginAttr)),
+ GetCrossOriginAttributeValue(owner_->FastGetAttribute(kCrossoriginAttr)),
owner_->TypeValue().DeprecatedLower(),
owner_->AsValue().DeprecatedLower(), owner_->Media().DeprecatedLower(),
owner_->nonce(), owner_->IntegrityValue(),
owner_->ImportanceValue().LowerASCII(), owner_->GetReferrerPolicy(),
- owner_->GetNonEmptyURLAttribute(hrefAttr),
- owner_->FastGetAttribute(srcsetAttr),
- owner_->FastGetAttribute(imgsizesAttr));
+ owner_->GetNonEmptyURLAttribute(kHrefAttr),
+ owner_->FastGetAttribute(kImagesrcsetAttr),
+ owner_->FastGetAttribute(kImagesizesAttr));
WTF::TextEncoding charset = GetCharset();
@@ -368,7 +368,7 @@ void LinkStyle::SetSheetTitle(const String& title) {
if (title.IsEmpty() || !IsUnset() || owner_->IsAlternate())
return;
- const KURL& href = owner_->GetNonEmptyURLAttribute(hrefAttr);
+ const KURL& href = owner_->GetNonEmptyURLAttribute(kHrefAttr);
if (href.IsValid() && !href.IsEmpty())
GetDocument().GetStyleEngine().SetPreferredStylesheetSetNameIfNotSet(title);
}
diff --git a/chromium/third_party/blink/renderer/core/html/link_style.h b/chromium/third_party/blink/renderer/core/html/link_style.h
index ba766ba18ab..a9b281b3f4e 100644
--- a/chromium/third_party/blink/renderer/core/html/link_style.h
+++ b/chromium/third_party/blink/renderer/core/html/link_style.h
@@ -75,11 +75,11 @@ class LinkStyle final : public LinkResource, ResourceClient {
void RemovePendingSheet();
void SetCrossOriginStylesheetStatus(CSSStyleSheet*);
- void SetFetchFollowingCORS() {
+ void SetFetchFollowingCors() {
DCHECK(!fetch_following_cors_);
fetch_following_cors_ = true;
}
- void ClearFetchFollowingCORS() { fetch_following_cors_ = false; }
+ void ClearFetchFollowingCors() { fetch_following_cors_ = false; }
Member<CSSStyleSheet> sheet_;
DisabledState disabled_state_;
diff --git a/chromium/third_party/blink/renderer/core/html/list_item_ordinal_test.cc b/chromium/third_party/blink/renderer/core/html/list_item_ordinal_test.cc
index 02d34a04762..cb64c7980a2 100644
--- a/chromium/third_party/blink/renderer/core/html/list_item_ordinal_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/list_item_ordinal_test.cc
@@ -40,7 +40,7 @@ TEST_F(ListItemOrdinalTest, ItemInsertedOrRemoved_ListItemsInSlot) {
ShadowRoot& shadow_root =
host.AttachShadowRootInternal(ShadowRootType::kOpen);
shadow_root.SetInnerHTMLFromString("<slot></slot>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_FALSE(shadow_root.NeedsSlotAssignmentRecalc());
Element& list_item1 = *GetDocument().getElementById("item1");
Element& list_item2 = *GetDocument().getElementById("item2");
@@ -57,7 +57,7 @@ TEST_F(ListItemOrdinalTest, ItemInsertedOrRemoved_ListItemsInSlot) {
EXPECT_EQ(layout_object, list_item2.GetLayoutObject())
<< "remove() doesn't change layout object for list_item2.";
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(1, ListItemOrdinal::Get(list_item2)->Value(list_item2))
<< "Update layout should update list item ordinal too.";
}
diff --git a/chromium/third_party/blink/renderer/core/html/media/autoplay_policy.cc b/chromium/third_party/blink/renderer/core/html/media/autoplay_policy.cc
index 810832151e1..c48fa73a3b8 100644
--- a/chromium/third_party/blink/renderer/core/html/media/autoplay_policy.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/autoplay_policy.cc
@@ -7,6 +7,7 @@
#include "build/build_config.h"
#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
#include "third_party/blink/public/platform/autoplay.mojom-blink.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_media_player.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
@@ -14,7 +15,6 @@
#include "third_party/blink/public/web/web_user_media_client.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element_visibility_observer.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/media/autoplay_uma_helper.h"
@@ -54,6 +54,7 @@ bool IsDocumentWhitelisted(const Document& document) {
if (whitelist_scope.IsNull() || whitelist_scope.IsEmpty())
return false;
+ DCHECK_EQ(KURL(whitelist_scope).GetString(), whitelist_scope);
return document.Url().GetString().StartsWith(whitelist_scope);
}
@@ -171,7 +172,7 @@ bool AutoplayPolicy::DocumentIsCapturingUserMedia(const Document& document) {
WebFrame* web_frame = WebFrame::FromFrame(document.GetFrame());
if (!web_frame)
return false;
-
+
WebLocalFrame* frame = web_frame->ToWebLocalFrame();
if (!frame || !frame->Client())
return false;
@@ -227,10 +228,11 @@ void AutoplayPolicy::StartAutoplayMutedWhenVisible() {
if (autoplay_visibility_observer_)
return;
- autoplay_visibility_observer_ = new ElementVisibilityObserver(
- element_,
- WTF::BindRepeating(&AutoplayPolicy::OnVisibilityChangedForAutoplay,
- WrapWeakPersistent(this)));
+ autoplay_visibility_observer_ =
+ MakeGarbageCollected<ElementVisibilityObserver>(
+ element_,
+ WTF::BindRepeating(&AutoplayPolicy::OnVisibilityChangedForAutoplay,
+ WrapWeakPersistent(this)));
autoplay_visibility_observer_->Start();
}
@@ -423,7 +425,7 @@ void AutoplayPolicy::OnVisibilityChangedForAutoplay(bool is_visible) {
if (ShouldAutoplay()) {
element_->paused_ = false;
- element_->ScheduleEvent(EventTypeNames::play);
+ element_->ScheduleEvent(event_type_names::kPlay);
element_->ScheduleNotifyPlaying();
element_->UpdatePlayState();
@@ -469,7 +471,9 @@ bool AutoplayPolicy::IsAutoplayAllowedPerSettings() const {
LocalFrame* frame = element_->GetDocument().GetFrame();
if (!frame)
return false;
- return frame->GetContentSettingsClient()->AllowAutoplay(true);
+ if (auto* settings_client = frame->GetContentSettingsClient())
+ return settings_client->AllowAutoplay(true /* default_value */);
+ return true;
}
bool AutoplayPolicy::ShouldAutoplay() {
diff --git a/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc b/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc
index 4c15dda7b0e..4fa1e11e7c0 100644
--- a/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc
@@ -62,7 +62,7 @@ AutoplayUmaHelper::AutoplayUmaHelper(HTMLMediaElement* element)
muted_video_play_method_visibility_observer_(nullptr),
is_visible_(false),
muted_video_offscreen_duration_visibility_observer_(nullptr) {
- element->addEventListener(EventTypeNames::loadstart, this, false);
+ element->addEventListener(event_type_names::kLoadstart, this, false);
}
AutoplayUmaHelper::~AutoplayUmaHelper() = default;
@@ -188,7 +188,7 @@ void AutoplayUmaHelper::OnAutoplayInitiated(AutoplaySource source) {
}
}
- element_->addEventListener(EventTypeNames::playing, this, false);
+ element_->addEventListener(event_type_names::kPlaying, this, false);
// Record UKM autoplay event.
if (!element_->GetDocument().IsActive())
@@ -356,13 +356,13 @@ void AutoplayUmaHelper::OnVisibilityChangedForMutedVideoOffscreenDuration(
is_visible_ = is_visible;
}
-void AutoplayUmaHelper::handleEvent(ExecutionContext* execution_context,
- Event* event) {
- if (event->type() == EventTypeNames::loadstart)
+void AutoplayUmaHelper::Invoke(ExecutionContext* execution_context,
+ Event* event) {
+ if (event->type() == event_type_names::kLoadstart)
OnLoadStarted();
- else if (event->type() == EventTypeNames::playing)
+ else if (event->type() == event_type_names::kPlaying)
HandlePlayingEvent();
- else if (event->type() == EventTypeNames::pause)
+ else if (event->type() == event_type_names::kPause)
HandlePauseEvent();
else
NOTREACHED();
@@ -372,7 +372,7 @@ void AutoplayUmaHelper::HandlePlayingEvent() {
MaybeStartRecordingMutedVideoPlayMethodBecomeVisible();
MaybeStartRecordingMutedVideoOffscreenDuration();
- element_->removeEventListener(EventTypeNames::playing, this, false);
+ element_->removeEventListener(event_type_names::kPlaying, this, false);
}
void AutoplayUmaHelper::HandlePauseEvent() {
@@ -394,11 +394,13 @@ void AutoplayUmaHelper::MaybeStartRecordingMutedVideoPlayMethodBecomeVisible() {
!element_->IsHTMLVideoElement() || !element_->muted())
return;
- muted_video_play_method_visibility_observer_ = new ElementVisibilityObserver(
- element_, WTF::BindRepeating(
- &AutoplayUmaHelper::
- OnVisibilityChangedForMutedVideoPlayMethodBecomeVisible,
- WrapWeakPersistent(this)));
+ muted_video_play_method_visibility_observer_ =
+ MakeGarbageCollected<ElementVisibilityObserver>(
+ element_,
+ WTF::BindRepeating(
+ &AutoplayUmaHelper::
+ OnVisibilityChangedForMutedVideoPlayMethodBecomeVisible,
+ WrapWeakPersistent(this)));
muted_video_play_method_visibility_observer_->Start();
SetContext(&element_->GetDocument());
}
@@ -425,14 +427,14 @@ void AutoplayUmaHelper::MaybeStartRecordingMutedVideoOffscreenDuration() {
// Start recording muted video playing offscreen duration.
muted_video_autoplay_offscreen_start_time_ = CurrentTimeTicks();
is_visible_ = false;
- muted_video_offscreen_duration_visibility_observer_ =
- new ElementVisibilityObserver(
- element_, WTF::BindRepeating(
- &AutoplayUmaHelper::
- OnVisibilityChangedForMutedVideoOffscreenDuration,
- WrapWeakPersistent(this)));
+ muted_video_offscreen_duration_visibility_observer_ = MakeGarbageCollected<
+ ElementVisibilityObserver>(
+ element_,
+ WTF::BindRepeating(
+ &AutoplayUmaHelper::OnVisibilityChangedForMutedVideoOffscreenDuration,
+ WrapWeakPersistent(this)));
muted_video_offscreen_duration_visibility_observer_->Start();
- element_->addEventListener(EventTypeNames::pause, this, false);
+ element_->addEventListener(event_type_names::kPause, this, false);
SetContext(&element_->GetDocument());
}
@@ -475,7 +477,7 @@ void AutoplayUmaHelper::MaybeUnregisterMediaElementPauseListener() {
return;
if (ShouldRecordUserPausedAutoplayingCrossOriginVideo())
return;
- element_->removeEventListener(EventTypeNames::pause, this, false);
+ element_->removeEventListener(event_type_names::kPause, this, false);
}
bool AutoplayUmaHelper::ShouldListenToContextDestroyed() const {
diff --git a/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h b/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h
index ce9bdd9a6bf..0b2991d6dd0 100644
--- a/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h
+++ b/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h
@@ -93,7 +93,7 @@ class CORE_EXPORT AutoplayUmaHelper : public EventListener,
void OnLoadStarted();
explicit AutoplayUmaHelper(HTMLMediaElement*);
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
void HandlePlayingEvent();
void HandlePauseEvent();
virtual void HandleContextDestroyed(); // Make virtual for testing.
diff --git a/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper_test.cc b/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper_test.cc
index 4d3ede2afd4..b58c23fc5e1 100644
--- a/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper_test.cc
@@ -15,15 +15,13 @@
namespace blink {
-using testing::Invoke;
-
class MockAutoplayUmaHelper : public AutoplayUmaHelper {
public:
MockAutoplayUmaHelper(HTMLMediaElement* element)
: AutoplayUmaHelper(element) {
ON_CALL(*this, HandleContextDestroyed())
- .WillByDefault(
- Invoke(this, &MockAutoplayUmaHelper::ReallyHandleContextDestroyed));
+ .WillByDefault(testing::Invoke(
+ this, &MockAutoplayUmaHelper::ReallyHandleContextDestroyed));
}
void HandlePlayingEvent() { AutoplayUmaHelper::HandlePlayingEvent(); }
@@ -52,7 +50,7 @@ class AutoplayUmaHelperTest : public PageTestBase {
GetDocument().documentElement()->SetInnerHTMLFromString(
"<video id=video></video>", ASSERT_NO_EXCEPTION);
HTMLMediaElement& element = MediaElement();
- uma_helper_ = new MockAutoplayUmaHelper(&element);
+ uma_helper_ = MakeGarbageCollected<MockAutoplayUmaHelper>(&element);
element.autoplay_policy_->autoplay_uma_helper_ = uma_helper_;
testing::Mock::AllowLeak(&UmaHelper());
}
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_audio_element.cc b/chromium/third_party/blink/renderer/core/html/media/html_audio_element.cc
index d3aff74144c..c2b61579bb6 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_audio_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_audio_element.cc
@@ -30,13 +30,13 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLAudioElement::HTMLAudioElement(Document& document)
- : HTMLMediaElement(audioTag, document) {}
+ : HTMLMediaElement(kAudioTag, document) {}
HTMLAudioElement* HTMLAudioElement::Create(Document& document) {
- HTMLAudioElement* audio = new HTMLAudioElement(document);
+ HTMLAudioElement* audio = MakeGarbageCollected<HTMLAudioElement>(document);
audio->EnsureUserAgentShadowRoot();
audio->PauseIfNeeded();
return audio;
@@ -45,7 +45,7 @@ HTMLAudioElement* HTMLAudioElement::Create(Document& document) {
HTMLAudioElement* HTMLAudioElement::CreateForJSConstructor(
Document& document,
const AtomicString& src) {
- HTMLAudioElement* audio = new HTMLAudioElement(document);
+ HTMLAudioElement* audio = MakeGarbageCollected<HTMLAudioElement>(document);
audio->EnsureUserAgentShadowRoot();
audio->setPreload(AtomicString("auto"));
if (!src.IsNull())
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_audio_element.h b/chromium/third_party/blink/renderer/core/html/media/html_audio_element.h
index 87e78d00ba7..2463517b7d7 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_audio_element.h
+++ b/chromium/third_party/blink/renderer/core/html/media/html_audio_element.h
@@ -43,6 +43,8 @@ class CORE_EXPORT HTMLAudioElement final : public HTMLMediaElement {
Document&,
const AtomicString& src = g_null_atom);
+ HTMLAudioElement(Document&);
+
bool IsHTMLAudioElement() const override { return true; }
// WebMediaPlayerClient implementation.
@@ -53,9 +55,6 @@ class CORE_EXPORT HTMLAudioElement final : public HTMLMediaElement {
void PictureInPictureControlClicked(const WebString& control_id) override {
NOTREACHED();
}
-
- private:
- HTMLAudioElement(Document&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element.cc b/chromium/third_party/blink/renderer/core/html/media/html_media_element.cc
index d18197b93c7..62e70ce5e52 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element.cc
@@ -85,6 +85,7 @@
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/intersection_geometry.h"
#include "third_party/blink/renderer/core/layout/layout_media.h"
+#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
@@ -102,6 +103,7 @@
#include "third_party/blink/renderer/platform/network/parsed_content_type.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -124,7 +126,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
using WeakMediaElementSet = HeapHashSet<WeakMember<HTMLMediaElement>>;
using DocumentElementSetMap =
@@ -133,8 +135,6 @@ using DocumentElementSetMap =
namespace {
constexpr float kMostlyFillViewportThreshold = 0.85f;
-constexpr TimeDelta kCheckViewportIntersectionInterval =
- TimeDelta::FromSeconds(1);
// This enum is used to record histograms. Do not reorder.
enum MediaControlsShow {
@@ -209,7 +209,7 @@ const char* BoolString(bool val) {
DocumentElementSetMap& DocumentToElementSetMap() {
DEFINE_STATIC_LOCAL(Persistent<DocumentElementSetMap>, map,
- (new DocumentElementSetMap));
+ (MakeGarbageCollected<DocumentElementSetMap>()));
return *map;
}
@@ -218,7 +218,7 @@ void AddElementToDocumentMap(HTMLMediaElement* element, Document* document) {
WeakMediaElementSet* set = nullptr;
auto it = map.find(document);
if (it == map.end()) {
- set = new WeakMediaElementSet;
+ set = MakeGarbageCollected<WeakMediaElementSet>();
map.insert(document, set);
} else {
set = it->value;
@@ -410,23 +410,12 @@ MIMETypeRegistry::SupportsType HTMLMediaElement::GetSupportsType(
return result;
}
-URLRegistry* HTMLMediaElement::media_stream_registry_ = nullptr;
-
const HashSet<AtomicString>& HTMLMediaElement::GetCheckedAttributeNames()
const {
DEFINE_STATIC_LOCAL(HashSet<AtomicString>, attribute_set, ({"src"}));
return attribute_set;
}
-void HTMLMediaElement::SetMediaStreamRegistry(URLRegistry* registry) {
- DCHECK(!media_stream_registry_);
- media_stream_registry_ = registry;
-}
-
-bool HTMLMediaElement::IsMediaStreamURL(const String& url) {
- return media_stream_registry_ ? media_stream_registry_->Contains(url) : false;
-}
-
bool HTMLMediaElement::IsHLSURL(const KURL& url) {
// Keep the same logic as in media_codec_util.h.
if (url.IsNull() || url.IsEmpty())
@@ -474,10 +463,6 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tag_name,
audio_tracks_timer_(document.GetTaskRunner(TaskType::kInternalMedia),
this,
&HTMLMediaElement::AudioTracksTimerFired),
- check_viewport_intersection_timer_(
- document.GetTaskRunner(TaskType::kInternalMedia),
- this,
- &HTMLMediaElement::CheckViewportIntersectionTimerFired),
removed_from_document_timer_(
document.GetTaskRunner(TaskType::kInternalMedia),
this,
@@ -578,8 +563,10 @@ void HTMLMediaElement::DidMoveToNewDocument(Document& old_document) {
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
audio_tracks_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
- check_viewport_intersection_timer_.MoveToNewTaskRunner(
- GetDocument().GetTaskRunner(TaskType::kInternalMedia));
+ if (viewport_intersection_observer_) {
+ ActivateViewportIntersectionMonitoring(false);
+ ActivateViewportIntersectionMonitoring(true);
+ }
deferred_load_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
removed_from_document_timer_.MoveToNewTaskRunner(
@@ -635,20 +622,20 @@ bool HTMLMediaElement::IsMouseFocusable() const {
void HTMLMediaElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == srcAttr) {
+ if (name == kSrcAttr) {
BLINK_MEDIA_LOG << "parseAttribute(" << (void*)this
- << ", srcAttr, old=" << params.old_value
+ << ", kSrcAttr, old=" << params.old_value
<< ", new=" << params.new_value << ")";
// Trigger a reload, as long as the 'src' attribute is present.
if (!params.new_value.IsNull()) {
ignore_preload_none_ = false;
InvokeLoadAlgorithm();
}
- } else if (name == controlsAttr) {
+ } else if (name == kControlsAttr) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementControlsAttribute);
UpdateControlsVisibility();
- } else if (name == controlslistAttr) {
+ } else if (name == kControlslistAttr) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementControlsListAttribute);
if (params.old_value != params.new_value) {
@@ -657,9 +644,9 @@ void HTMLMediaElement::ParseAttribute(
if (GetMediaControls())
GetMediaControls()->OnControlsListUpdated();
}
- } else if (name == preloadAttr) {
+ } else if (name == kPreloadAttr) {
SetPlayerPreload();
- } else if (name == disableremoteplaybackAttr) {
+ } else if (name == kDisableremoteplaybackAttr) {
// This attribute is an extension described in the Remote Playback API spec.
// Please see: https://w3c.github.io/remote-playback
UseCounter::Count(GetDocument(),
@@ -678,7 +665,7 @@ void HTMLMediaElement::ParseAttribute(
void HTMLMediaElement::ParserDidSetAttributes() {
HTMLElement::ParserDidSetAttributes();
- if (FastHasAttribute(mutedAttr))
+ if (FastHasAttribute(kMutedAttr))
muted_ = true;
}
@@ -690,7 +677,7 @@ void HTMLMediaElement::CloneNonAttributePropertiesFrom(const Element& other,
CloneChildrenFlag flag) {
HTMLElement::CloneNonAttributePropertiesFrom(other, flag);
- if (FastHasAttribute(mutedAttr))
+ if (FastHasAttribute(kMutedAttr))
muted_ = true;
}
@@ -717,7 +704,7 @@ Node::InsertionNotificationRequest HTMLMediaElement::InsertedInto(
HTMLElement::InsertedInto(insertion_point);
if (insertion_point.isConnected()) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementInDocument);
- if ((!getAttribute(srcAttr).IsEmpty() || src_object_) &&
+ if ((!getAttribute(kSrcAttr).IsEmpty() || src_object_) &&
network_state_ == kNetworkEmpty) {
ignore_preload_none_ = false;
InvokeLoadAlgorithm();
@@ -801,12 +788,12 @@ MediaError* HTMLMediaElement::error() const {
}
void HTMLMediaElement::SetSrc(const AtomicString& url) {
- setAttribute(srcAttr, url);
+ setAttribute(kSrcAttr, url);
}
void HTMLMediaElement::SetSrc(const USVStringOrTrustedURL& stringOrURL,
ExceptionState& exception_state) {
- setAttribute(srcAttr, stringOrURL, exception_state);
+ setAttribute(kSrcAttr, stringOrURL, exception_state);
}
void HTMLMediaElement::SetSrcObject(MediaStreamDescriptor* src_object) {
@@ -909,7 +896,7 @@ void HTMLMediaElement::InvokeLoadAlgorithm() {
// NETWORK_IDLE, queue a task to fire a simple event named abort at the media
// element.
if (network_state_ == kNetworkLoading || network_state_ == kNetworkIdle)
- ScheduleEvent(EventTypeNames::abort);
+ ScheduleEvent(event_type_names::kAbort);
ResetMediaPlayerAndMediaSource();
@@ -918,7 +905,7 @@ void HTMLMediaElement::InvokeLoadAlgorithm() {
if (network_state_ != kNetworkEmpty) {
// 4.1 - Queue a task to fire a simple event named emptied at the media
// element.
- ScheduleEvent(EventTypeNames::emptied);
+ ScheduleEvent(event_type_names::kEmptied);
// 4.2 - If a fetching process is in progress for the media element, the
// user agent should stop it.
@@ -1043,7 +1030,7 @@ void HTMLMediaElement::SelectMediaResource() {
// mode be object.
if (src_object_) {
mode = kObject;
- } else if (FastHasAttribute(srcAttr)) {
+ } else if (FastHasAttribute(kSrcAttr)) {
// Otherwise, if the media element has no assigned media provider object
// but has a src attribute, then let mode be attribute.
mode = kAttribute;
@@ -1086,7 +1073,7 @@ void HTMLMediaElement::SelectMediaResource() {
// 8 - Queue a task to fire a simple event named loadstart at the media
// element.
- ScheduleEvent(EventTypeNames::loadstart);
+ ScheduleEvent(event_type_names::kLoadstart);
// 9 - Run the appropriate steps...
switch (mode) {
@@ -1121,7 +1108,7 @@ void HTMLMediaElement::LoadSourceFromObject() {
void HTMLMediaElement::LoadSourceFromAttribute() {
load_state_ = kLoadingFromSrcAttr;
- const AtomicString& src_value = FastGetAttribute(srcAttr);
+ const AtomicString& src_value = FastGetAttribute(kSrcAttr);
// If the src attribute's value is the empty string ... jump down to the
// failed step below
@@ -1314,7 +1301,7 @@ void HTMLMediaElement::StartPlayerLoad() {
web_media_player_->SetPreload(preload);
web_media_player_->RequestRemotePlaybackDisabled(
- FastHasAttribute(disableremoteplaybackAttr));
+ FastHasAttribute(kDisableremoteplaybackAttr));
auto load_timing = web_media_player_->Load(GetLoadType(), source, CorsMode());
if (load_timing == WebMediaPlayer::LoadTiming::kDeferred) {
@@ -1410,8 +1397,7 @@ WebMediaPlayer::LoadType HTMLMediaElement::GetLoadType() const {
if (media_source_)
return WebMediaPlayer::kLoadTypeMediaSource;
- if (src_object_ ||
- (!current_src_.IsNull() && IsMediaStreamURL(current_src_.GetString())))
+ if (src_object_)
return WebMediaPlayer::kLoadTypeMediaStream;
return WebMediaPlayer::kLoadTypeURL;
@@ -1504,8 +1490,7 @@ bool HTMLMediaElement::IsSafeToLoadURL(const KURL& url,
return true;
}
-bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
- const SecurityOrigin* origin) const {
+bool HTMLMediaElement::IsMediaDataCorsSameOrigin() const {
if (!GetWebMediaPlayer())
return true;
@@ -1579,7 +1564,7 @@ void HTMLMediaElement::NoneSupported(const String& input_message) {
UpdateDisplayState();
// 5 - Fire a simple event named error at the media element.
- ScheduleEvent(EventTypeNames::error);
+ ScheduleEvent(event_type_names::kError);
// 6 - Reject pending play promises with NotSupportedError.
ScheduleRejectPlayPromises(DOMExceptionCode::kNotSupportedError);
@@ -1608,7 +1593,7 @@ void HTMLMediaElement::MediaEngineError(MediaError* err) {
error_ = err;
// 3 - Queue a task to fire a simple event named error at the media element.
- ScheduleEvent(EventTypeNames::error);
+ ScheduleEvent(event_type_names::kError);
// 4 - Set the element's networkState attribute to the NETWORK_IDLE value.
SetNetworkState(kNetworkIdle);
@@ -1753,8 +1738,8 @@ void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() {
// Schedule one last progress event so we guarantee that at least one is
// fired for files that load very quickly.
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress())
- ScheduleEvent(EventTypeNames::progress);
- ScheduleEvent(EventTypeNames::suspend);
+ ScheduleEvent(event_type_names::kProgress);
+ ScheduleEvent(event_type_names::kSuspend);
SetNetworkState(kNetworkIdle);
}
}
@@ -1806,7 +1791,7 @@ void HTMLMediaElement::SetReadyState(ReadyState state) {
// attribute to change to a value lower than kHaveFutureData, then a waiting
// will be fired at the element.
if (was_potentially_playing && ready_state_ < kHaveFutureData)
- ScheduleEvent(EventTypeNames::waiting);
+ ScheduleEvent(event_type_names::kWaiting);
// 4.8.12.9 steps 12-14
if (ready_state_ >= kHaveCurrentData)
@@ -1822,7 +1807,7 @@ void HTMLMediaElement::SetReadyState(ReadyState state) {
// 4.8.12.8
ScheduleTimeupdateEvent(false);
- ScheduleEvent(EventTypeNames::waiting);
+ ScheduleEvent(event_type_names::kWaiting);
}
}
@@ -1839,11 +1824,11 @@ void HTMLMediaElement::SetReadyState(ReadyState state) {
SetOfficialPlaybackPosition(EarliestPossiblePosition());
duration_ = web_media_player_->Duration();
- ScheduleEvent(EventTypeNames::durationchange);
+ ScheduleEvent(event_type_names::kDurationchange);
if (IsHTMLVideoElement())
- ScheduleEvent(EventTypeNames::resize);
- ScheduleEvent(EventTypeNames::loadedmetadata);
+ ScheduleEvent(event_type_names::kResize);
+ ScheduleEvent(event_type_names::kLoadedmetadata);
bool jumped = false;
if (default_playback_start_position_ > 0) {
@@ -1879,24 +1864,25 @@ void HTMLMediaElement::SetReadyState(ReadyState state) {
have_fired_loaded_data_ = true;
should_update_display_state = true;
- ScheduleEvent(EventTypeNames::loadeddata);
+ ScheduleEvent(event_type_names::kLoadeddata);
SetShouldDelayLoadEvent(false);
// If the player did a lazy load, it's expecting to be called when the
// element actually becomes visible to complete the load.
if (IsHTMLVideoElement() && web_media_player_->DidLazyLoad() &&
!is_potentially_playing) {
- lazy_load_visibility_observer_ = new ElementVisibilityObserver(
- this,
- WTF::BindRepeating(&HTMLMediaElement::OnVisibilityChangedForLazyLoad,
- WrapWeakPersistent(this)));
+ lazy_load_visibility_observer_ =
+ MakeGarbageCollected<ElementVisibilityObserver>(
+ this, WTF::BindRepeating(
+ &HTMLMediaElement::OnVisibilityChangedForLazyLoad,
+ WrapWeakPersistent(this)));
lazy_load_visibility_observer_->Start();
}
}
if (ready_state_ == kHaveFutureData && old_state <= kHaveCurrentData &&
tracks_are_ready) {
- ScheduleEvent(EventTypeNames::canplay);
+ ScheduleEvent(event_type_names::kCanplay);
if (is_potentially_playing)
ScheduleNotifyPlaying();
should_update_display_state = true;
@@ -1905,19 +1891,19 @@ void HTMLMediaElement::SetReadyState(ReadyState state) {
if (ready_state_ == kHaveEnoughData && old_state < kHaveEnoughData &&
tracks_are_ready) {
if (old_state <= kHaveCurrentData) {
- ScheduleEvent(EventTypeNames::canplay);
+ ScheduleEvent(event_type_names::kCanplay);
if (is_potentially_playing)
ScheduleNotifyPlaying();
}
if (autoplay_policy_->RequestAutoplayByAttribute()) {
paused_ = false;
- ScheduleEvent(EventTypeNames::play);
+ ScheduleEvent(event_type_names::kPlay);
ScheduleNotifyPlaying();
can_autoplay_ = false;
}
- ScheduleEvent(EventTypeNames::canplaythrough);
+ ScheduleEvent(event_type_names::kCanplaythrough);
should_update_display_state = true;
}
@@ -1944,7 +1930,7 @@ void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
double timedelta = time - previous_progress_time_;
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) {
- ScheduleEvent(EventTypeNames::progress);
+ ScheduleEvent(event_type_names::kProgress);
previous_progress_time_ = time;
sent_stalled_event_ = false;
if (GetLayoutObject())
@@ -1956,7 +1942,7 @@ void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
// 'stalled' does not apply. See discussion in https://crbug.com/517240
// We also don't need to take any action wrt delaying-the-load-event.
// MediaSource disables the delayed load when first attached.
- ScheduleEvent(EventTypeNames::stalled);
+ ScheduleEvent(event_type_names::kStalled);
sent_stalled_event_ = true;
SetShouldDelayLoadEvent(false);
}
@@ -1990,7 +1976,7 @@ bool HTMLMediaElement::SupportsSave() const {
return false;
// MediaStream can't be downloaded.
- if (IsMediaStreamURL(current_src_.GetString()))
+ if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return false;
// MediaSource can't be downloaded.
@@ -2094,7 +2080,7 @@ void HTMLMediaElement::Seek(double time) {
last_seek_time_ = time;
// 10 - Queue a task to fire a simple event named seeking at the element.
- ScheduleEvent(EventTypeNames::seeking);
+ ScheduleEvent(event_type_names::kSeeking);
// 11 - Set the current playback position to the given new playback position.
GetWebMediaPlayer()->Seek(time);
@@ -2117,7 +2103,7 @@ void HTMLMediaElement::FinishSeek() {
ScheduleTimeupdateEvent(false);
// 17 - Queue a task to fire a simple event named seeked at the element.
- ScheduleEvent(EventTypeNames::seeked);
+ ScheduleEvent(event_type_names::kSeeked);
SetDisplayMode(kVideo);
}
@@ -2277,7 +2263,7 @@ void HTMLMediaElement::setDefaultPlaybackRate(double rate) {
return;
default_playback_rate_ = rate;
- ScheduleEvent(EventTypeNames::ratechange);
+ ScheduleEvent(event_type_names::kRatechange);
}
double HTMLMediaElement::playbackRate() const {
@@ -2309,7 +2295,7 @@ void HTMLMediaElement::setPlaybackRate(double rate,
if (playback_rate_ != rate) {
playback_rate_ = rate;
- ScheduleEvent(EventTypeNames::ratechange);
+ ScheduleEvent(event_type_names::kRatechange);
}
UpdatePlaybackRate();
@@ -2336,7 +2322,7 @@ bool HTMLMediaElement::ended() const {
}
bool HTMLMediaElement::Autoplay() const {
- return FastHasAttribute(autoplayAttr);
+ return FastHasAttribute(kAutoplayAttr);
}
String HTMLMediaElement::preload() const {
@@ -2349,11 +2335,11 @@ void HTMLMediaElement::setPreload(const AtomicString& preload) {
BLINK_MEDIA_LOG << "setPreload(" << (void*)this << ", " << preload << ")";
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return;
- setAttribute(preloadAttr, preload);
+ setAttribute(kPreloadAttr, preload);
}
WebMediaPlayer::Preload HTMLMediaElement::PreloadType() const {
- const AtomicString& preload = FastGetAttribute(preloadAttr);
+ const AtomicString& preload = FastGetAttribute(kPreloadAttr);
if (DeprecatedEqualIgnoringCase(preload, "none")) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadNone);
return WebMediaPlayer::kPreloadNone;
@@ -2400,9 +2386,7 @@ WebMediaPlayer::Preload HTMLMediaElement::PreloadType() const {
// The spec does not define an invalid value default:
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=28950
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadDefault);
- return RuntimeEnabledFeatures::PreloadDefaultIsMetadataEnabled()
- ? WebMediaPlayer::kPreloadMetaData
- : WebMediaPlayer::kPreloadAuto;
+ return WebMediaPlayer::kPreloadMetaData;
}
String HTMLMediaElement::EffectivePreload() const {
@@ -2505,10 +2489,10 @@ void HTMLMediaElement::PlayInternal() {
if (paused_) {
paused_ = false;
- ScheduleEvent(EventTypeNames::play);
+ ScheduleEvent(event_type_names::kPlay);
if (ready_state_ <= kHaveCurrentData)
- ScheduleEvent(EventTypeNames::waiting);
+ ScheduleEvent(event_type_names::kWaiting);
else if (ready_state_ >= kHaveFutureData)
ScheduleNotifyPlaying();
} else if (ready_state_ >= kHaveFutureData) {
@@ -2539,7 +2523,7 @@ void HTMLMediaElement::PauseInternal() {
if (!paused_) {
paused_ = true;
ScheduleTimeupdateEvent(false);
- ScheduleEvent(EventTypeNames::pause);
+ ScheduleEvent(event_type_names::kPause);
// Force an update to official playback position. Automatic updates from
// currentPlaybackPosition() will be blocked while paused_ = true. This
@@ -2587,12 +2571,12 @@ void HTMLMediaElement::CloseMediaSource() {
}
bool HTMLMediaElement::Loop() const {
- return FastHasAttribute(loopAttr);
+ return FastHasAttribute(kLoopAttr);
}
void HTMLMediaElement::SetLoop(bool b) {
BLINK_MEDIA_LOG << "setLoop(" << (void*)this << ", " << BoolString(b) << ")";
- SetBooleanAttribute(loopAttr, b);
+ SetBooleanAttribute(kLoopAttr, b);
}
bool HTMLMediaElement::ShouldShowControls(
@@ -2604,7 +2588,7 @@ bool HTMLMediaElement::ShouldShowControls(
return false;
}
- if (FastHasAttribute(controlsAttr)) {
+ if (FastHasAttribute(kControlsAttr)) {
if (record_metrics == RecordMetricsBehavior::kDoRecord)
ShowControlsHistogram().Count(kMediaControlsShowAttribute);
return true;
@@ -2659,7 +2643,7 @@ void HTMLMediaElement::setVolume(double vol, ExceptionState& exception_state) {
if (GetWebMediaPlayer())
GetWebMediaPlayer()->SetVolume(EffectiveMediaVolume());
- ScheduleEvent(EventTypeNames::volumechange);
+ ScheduleEvent(event_type_names::kVolumechange);
}
bool HTMLMediaElement::muted() const {
@@ -2675,7 +2659,7 @@ void HTMLMediaElement::setMuted(bool muted) {
muted_ = muted;
- ScheduleEvent(EventTypeNames::volumechange);
+ ScheduleEvent(event_type_names::kVolumechange);
// If it is unmute and AutoplayPolicy doesn't want the playback to continue,
// pause the playback.
@@ -2747,7 +2731,7 @@ void HTMLMediaElement::ScheduleTimeupdateEvent(bool periodic_event) {
if (periodic_event && !media_time_has_progressed)
return;
- ScheduleEvent(EventTypeNames::timeupdate);
+ ScheduleEvent(event_type_names::kTimeupdate);
last_time_update_event_media_time_ = media_time;
@@ -3003,7 +2987,7 @@ void HTMLMediaElement::DidAddTrackElement(HTMLTrackElement* track_element) {
}
void HTMLMediaElement::DidRemoveTrackElement(HTMLTrackElement* track_element) {
- KURL url = track_element->GetNonEmptyURLAttribute(srcAttr);
+ KURL url = track_element->GetNonEmptyURLAttribute(kSrcAttr);
BLINK_MEDIA_LOG << "didRemoveTrackElement(" << (void*)this << ") - 'src' is "
<< UrlForLoggingMedia(url);
@@ -3109,7 +3093,7 @@ KURL HTMLMediaElement::SelectNextSourceChild(
// 2. If candidate does not have a src attribute, or if its src
// attribute's value is the empty string ... jump down to the failed
// step below
- const AtomicString& src_value = source->FastGetAttribute(srcAttr);
+ const AtomicString& src_value = source->FastGetAttribute(kSrcAttr);
if (should_log) {
BLINK_MEDIA_LOG << "selectNextSourceChild(" << (void*)this
<< ") - 'src' is " << UrlForLoggingMedia(media_url);
@@ -3174,13 +3158,13 @@ KURL HTMLMediaElement::SelectNextSourceChild(
void HTMLMediaElement::SourceWasAdded(HTMLSourceElement* source) {
BLINK_MEDIA_LOG << "sourceWasAdded(" << (void*)this << ", " << source << ")";
- KURL url = source->GetNonEmptyURLAttribute(srcAttr);
+ KURL url = source->GetNonEmptyURLAttribute(kSrcAttr);
BLINK_MEDIA_LOG << "sourceWasAdded(" << (void*)this << ") - 'src' is "
<< UrlForLoggingMedia(url);
// We should only consider a <source> element when there is not src attribute
// at all.
- if (FastHasAttribute(srcAttr))
+ if (FastHasAttribute(kSrcAttr))
return;
// 4.8.8 - If a source element is inserted as a child of a media element that
@@ -3230,7 +3214,7 @@ void HTMLMediaElement::SourceWasRemoved(HTMLSourceElement* source) {
BLINK_MEDIA_LOG << "sourceWasRemoved(" << (void*)this << ", " << source
<< ")";
- KURL url = source->GetNonEmptyURLAttribute(srcAttr);
+ KURL url = source->GetNonEmptyURLAttribute(kSrcAttr);
BLINK_MEDIA_LOG << "sourceWasRemoved(" << (void*)this << ") - 'src' is "
<< UrlForLoggingMedia(url);
@@ -3290,11 +3274,11 @@ void HTMLMediaElement::TimeChanged() {
// changes paused to true and fires a simple event named pause at the
// media element.
paused_ = true;
- ScheduleEvent(EventTypeNames::pause);
+ ScheduleEvent(event_type_names::kPause);
ScheduleRejectPlayPromises(DOMExceptionCode::kAbortError);
}
// Queue a task to fire a simple event named ended at the media element.
- ScheduleEvent(EventTypeNames::ended);
+ ScheduleEvent(event_type_names::kEnded);
}
}
UpdatePlayState();
@@ -3324,7 +3308,7 @@ void HTMLMediaElement::DurationChanged(double duration, bool request_seek) {
BLINK_MEDIA_LOG << "durationChanged(" << (void*)this << ") : " << duration_
<< " -> " << duration;
duration_ = duration;
- ScheduleEvent(EventTypeNames::durationchange);
+ ScheduleEvent(event_type_names::kDurationchange);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
@@ -3416,7 +3400,7 @@ void HTMLMediaElement::SizeChanged() {
DCHECK(HasVideo()); // "resize" makes no sense in absence of video.
if (ready_state_ > kHaveNothing && IsHTMLVideoElement())
- ScheduleEvent(EventTypeNames::resize);
+ ScheduleEvent(event_type_names::kResize);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
@@ -3561,7 +3545,6 @@ void HTMLMediaElement::UpdatePlayState() {
void HTMLMediaElement::StopPeriodicTimers() {
progress_event_timer_.Stop();
playback_progress_timer_.Stop();
- check_viewport_intersection_timer_.Stop();
if (lazy_load_visibility_observer_) {
lazy_load_visibility_observer_->Stop();
lazy_load_visibility_observer_ = nullptr;
@@ -3833,7 +3816,7 @@ uint64_t HTMLMediaElement::webkitVideoDecodedByteCount() const {
}
bool HTMLMediaElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr ||
+ return attribute.GetName() == kSrcAttr ||
HTMLElement::IsURLAttribute(attribute);
}
@@ -3954,13 +3937,13 @@ void HTMLMediaElement::SetAudioSourceNode(
GetAudioSourceProvider().SetClient(audio_source_node_);
}
-WebMediaPlayer::CORSMode HTMLMediaElement::CorsMode() const {
- const AtomicString& cross_origin_mode = FastGetAttribute(crossoriginAttr);
+WebMediaPlayer::CorsMode HTMLMediaElement::CorsMode() const {
+ const AtomicString& cross_origin_mode = FastGetAttribute(kCrossoriginAttr);
if (cross_origin_mode.IsNull())
- return WebMediaPlayer::kCORSModeUnspecified;
+ return WebMediaPlayer::kCorsModeUnspecified;
if (DeprecatedEqualIgnoringCase(cross_origin_mode, "use-credentials"))
- return WebMediaPlayer::kCORSModeUseCredentials;
- return WebMediaPlayer::kCORSModeAnonymous;
+ return WebMediaPlayer::kCorsModeUseCredentials;
+ return WebMediaPlayer::kCorsModeAnonymous;
}
void HTMLMediaElement::SetCcLayer(cc::Layer* cc_layer) {
@@ -3985,10 +3968,11 @@ void HTMLMediaElement::MediaSourceOpened(WebMediaSource* web_media_source) {
}
bool HTMLMediaElement::IsInteractiveContent() const {
- return FastHasAttribute(controlsAttr);
+ return FastHasAttribute(kControlsAttr);
}
void HTMLMediaElement::Trace(blink::Visitor* visitor) {
+ visitor->Trace(viewport_intersection_observer_);
visitor->Trace(played_time_ranges_);
visitor->Trace(async_event_queue_);
visitor->Trace(error_);
@@ -4103,7 +4087,7 @@ void HTMLMediaElement::ScheduleRejectPlayPromises(DOMExceptionCode code) {
}
void HTMLMediaElement::ScheduleNotifyPlaying() {
- ScheduleEvent(EventTypeNames::playing);
+ ScheduleEvent(event_type_names::kPlaying);
ScheduleResolvePlayPromises();
}
@@ -4194,7 +4178,7 @@ void HTMLMediaElement::AudioSourceProviderImpl::SetClient(
MutexLocker locker(provide_input_lock);
if (client)
- client_ = new HTMLMediaElement::AudioClientImpl(client);
+ client_ = MakeGarbageCollected<HTMLMediaElement::AudioClientImpl>(client);
else
client_.Clear();
@@ -4204,7 +4188,7 @@ void HTMLMediaElement::AudioSourceProviderImpl::SetClient(
void HTMLMediaElement::AudioSourceProviderImpl::ProvideInput(
AudioBus* bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(bus);
MutexTryLocker try_locker(provide_input_lock);
@@ -4222,7 +4206,7 @@ void HTMLMediaElement::AudioSourceProviderImpl::ProvideInput(
web_audio_source_provider_->ProvideInput(web_audio_data, frames_to_process);
}
-void HTMLMediaElement::AudioClientImpl::SetFormat(size_t number_of_channels,
+void HTMLMediaElement::AudioClientImpl::SetFormat(uint32_t number_of_channels,
float sample_rate) {
if (client_)
client_->SetFormat(number_of_channels, sample_rate);
@@ -4237,11 +4221,17 @@ void HTMLMediaElement::AudioSourceProviderImpl::Trace(blink::Visitor* visitor) {
}
void HTMLMediaElement::ActivateViewportIntersectionMonitoring(bool activate) {
- if (activate && !check_viewport_intersection_timer_.IsActive()) {
- check_viewport_intersection_timer_.StartRepeating(
- kCheckViewportIntersectionInterval, FROM_HERE);
- } else if (!activate) {
- check_viewport_intersection_timer_.Stop();
+ if (activate && !viewport_intersection_observer_) {
+ viewport_intersection_observer_ = IntersectionObserver::Create(
+ {}, {kMostlyFillViewportThreshold}, &(GetDocument()),
+ WTF::BindRepeating(&HTMLMediaElement::OnViewportIntersectionChanged,
+ WrapWeakPersistent(this)),
+ IntersectionObserver::kFractionOfRoot);
+ viewport_intersection_observer_->observe(this);
+ } else if (!activate && viewport_intersection_observer_) {
+ viewport_intersection_observer_->disconnect();
+ viewport_intersection_observer_ = nullptr;
+ mostly_filling_viewport_ = false;
}
}
@@ -4279,24 +4269,15 @@ void HTMLMediaElement::RequestPause() {
}
bool HTMLMediaElement::MediaShouldBeOpaque() const {
- return !IsMediaDataCORSSameOrigin(GetDocument().GetSecurityOrigin()) &&
- ready_state_ < kHaveMetadata && !FastGetAttribute(srcAttr).IsEmpty() &&
+ return !IsMediaDataCorsSameOrigin() && ready_state_ < kHaveMetadata &&
+ !FastGetAttribute(kSrcAttr).IsEmpty() &&
EffectivePreloadType() != WebMediaPlayer::kPreloadNone;
}
-void HTMLMediaElement::CheckViewportIntersectionTimerFired(TimerBase*) {
- bool should_report_root_bounds = true;
- IntersectionGeometry geometry(nullptr, *this, Vector<Length>(),
- should_report_root_bounds);
- geometry.ComputeGeometry();
- IntRect intersect_rect = geometry.IntersectionIntRect();
- if (current_intersect_rect_ == intersect_rect)
- return;
-
- current_intersect_rect_ = intersect_rect;
- bool is_mostly_filling_viewport =
- (current_intersect_rect_.Size().Area() >
- kMostlyFillViewportThreshold * geometry.RootIntRect().Size().Area());
+void HTMLMediaElement::OnViewportIntersectionChanged(
+ const HeapVector<Member<IntersectionObserverEntry>>& entries) {
+ const bool is_mostly_filling_viewport =
+ (entries.back()->intersectionRatio() >= kMostlyFillViewportThreshold);
if (mostly_filling_viewport_ == is_mostly_filling_viewport)
return;
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element.h b/chromium/third_party/blink/renderer/core/html/media/html_media_element.h
index 26988639146..865fc83725b 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element.h
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element.h
@@ -38,13 +38,14 @@
#include "third_party/blink/renderer/core/dom/pausable_object.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/media/media_controls.h"
+#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "third_party/blink/renderer/platform/audio/audio_source_provider.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace cc {
class Layer;
@@ -76,7 +77,6 @@ class TextTrack;
class TextTrackContainer;
class TextTrackList;
class TimeRanges;
-class URLRegistry;
class VideoTrack;
class VideoTrackList;
class WebAudioSourceProvider;
@@ -101,8 +101,6 @@ class CORE_EXPORT HTMLMediaElement
enum class RecordMetricsBehavior { kDoNotRecord, kDoRecord };
- static void SetMediaStreamRegistry(URLRegistry*);
- static bool IsMediaStreamURL(const String& url);
static bool IsHLSURL(const KURL&);
// If HTMLMediaElement is using MediaTracks (either placeholder or provided
@@ -303,9 +301,8 @@ class CORE_EXPORT HTMLMediaElement
enum InvalidURLAction { kDoNothing, kComplain };
bool IsSafeToLoadURL(const KURL&, InvalidURLAction);
- // Checks to see if current media data is CORS-same-origin as the
- // specified origin.
- bool IsMediaDataCORSSameOrigin(const SecurityOrigin*) const;
+ // Checks to see if current media data is CORS-same-origin.
+ bool IsMediaDataCorsSameOrigin() const;
// Returns this media element is in a cross-origin frame.
bool IsInCrossOriginFrame() const;
@@ -445,7 +442,8 @@ class CORE_EXPORT HTMLMediaElement
void ProgressEventTimerFired(TimerBase*);
void PlaybackProgressTimerFired(TimerBase*);
void ScheduleTimeupdateEvent(bool periodic_event);
- void CheckViewportIntersectionTimerFired(TimerBase*);
+ void OnViewportIntersectionChanged(
+ const HeapVector<Member<IntersectionObserverEntry>>& entries);
void StartPlaybackProgressTimer();
void StartProgressEventTimer();
void StopPeriodicTimers();
@@ -529,7 +527,7 @@ class CORE_EXPORT HTMLMediaElement
void ChangeNetworkStateFromLoadingToIdle();
- WebMediaPlayer::CORSMode CorsMode() const;
+ WebMediaPlayer::CorsMode CorsMode() const;
// Returns the "direction of playback" value as specified in the HTML5 spec.
enum DirectionOfPlayback { kBackward, kForward };
@@ -564,9 +562,10 @@ class CORE_EXPORT HTMLMediaElement
TaskRunnerTimer<HTMLMediaElement> progress_event_timer_;
TaskRunnerTimer<HTMLMediaElement> playback_progress_timer_;
TaskRunnerTimer<HTMLMediaElement> audio_tracks_timer_;
- TaskRunnerTimer<HTMLMediaElement> check_viewport_intersection_timer_;
TaskRunnerTimer<HTMLMediaElement> removed_from_document_timer_;
+ Member<IntersectionObserver> viewport_intersection_observer_;
+
Member<TimeRanges> played_time_ranges_;
Member<EventQueue> async_event_queue_;
@@ -660,6 +659,8 @@ class CORE_EXPORT HTMLMediaElement
bool processing_preference_change_ : 1;
bool playing_remotely_ : 1;
+ // The following is always false unless viewport intersection monitoring is
+ // turned on via ActivateViewportIntersectionMonitoring().
bool mostly_filling_viewport_ : 1;
bool was_always_muted_ : 1;
@@ -696,7 +697,7 @@ class CORE_EXPORT HTMLMediaElement
~AudioClientImpl() override = default;
// WebAudioSourceProviderClient
- void SetFormat(size_t number_of_channels, float sample_rate) override;
+ void SetFormat(uint32_t number_of_channels, float sample_rate) override;
void Trace(blink::Visitor*);
@@ -719,7 +720,7 @@ class CORE_EXPORT HTMLMediaElement
// AudioSourceProvider
void SetClient(AudioSourceProviderClient*) override;
- void ProvideInput(AudioBus*, size_t frames_to_process) override;
+ void ProvideInput(AudioBus*, uint32_t frames_to_process) override;
void Trace(blink::Visitor*);
@@ -750,14 +751,10 @@ class CORE_EXPORT HTMLMediaElement
WebRemotePlaybackClient* remote_playback_client_;
- IntRect current_intersect_rect_;
-
Member<MediaControls> media_controls_;
Member<HTMLMediaElementControlsList> controls_list_;
Member<ElementVisibilityObserver> lazy_load_visibility_observer_;
-
- static URLRegistry* media_stream_registry_;
};
inline bool IsHTMLMediaElement(const HTMLElement& element) {
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.cc b/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.cc
index 4343433ccfe..1f552d45d06 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.cc
@@ -21,7 +21,7 @@ const char* const kSupportedTokens[] = {kNoDownload, kNoFullscreen,
HTMLMediaElementControlsList::HTMLMediaElementControlsList(
HTMLMediaElement* element)
- : DOMTokenList(*element, HTMLNames::controlslistAttr) {}
+ : DOMTokenList(*element, html_names::kControlslistAttr) {}
bool HTMLMediaElementControlsList::ValidateTokenValue(
const AtomicString& token_value,
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.h b/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.h
index c2939d720df..e2f0d14c465 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.h
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element_controls_list.h
@@ -16,16 +16,17 @@ class HTMLMediaElement;
class HTMLMediaElementControlsList final : public DOMTokenList {
public:
static HTMLMediaElementControlsList* Create(HTMLMediaElement* element) {
- return new HTMLMediaElementControlsList(element);
+ return MakeGarbageCollected<HTMLMediaElementControlsList>(element);
}
+ explicit HTMLMediaElementControlsList(HTMLMediaElement*);
+
// Whether the list dictates to hide a certain control.
CORE_EXPORT bool ShouldHideDownload() const;
CORE_EXPORT bool ShouldHideFullscreen() const;
CORE_EXPORT bool ShouldHideRemotePlayback() const;
private:
- explicit HTMLMediaElementControlsList(HTMLMediaElement*);
bool ValidateTokenValue(const AtomicString&, ExceptionState&) const override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element_event_listeners_test.cc b/chromium/third_party/blink/renderer/core/html/media/html_media_element_event_listeners_test.cc
index 040bd9c4aaa..e09c9282b71 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element_event_listeners_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element_event_listeners_test.cc
@@ -94,7 +94,6 @@ class MediaStubLocalFrameClient : public EmptyLocalFrameClient {
using testing::_;
using testing::AtLeast;
-using testing::Invoke;
using testing::Return;
} // anonymous namespace
@@ -218,8 +217,8 @@ TEST_F(HTMLMediaElementEventListenersTest,
std::vector<blink::WebFullscreenVideoStatus> observed_results;
ON_CALL(*WebMediaPlayer(), SetIsEffectivelyFullscreen(_))
- .WillByDefault(
- Invoke([&](blink::WebFullscreenVideoStatus fullscreen_video_status) {
+ .WillByDefault(testing::Invoke(
+ [&](blink::WebFullscreenVideoStatus fullscreen_video_status) {
observed_results.push_back(fullscreen_video_status);
}));
@@ -240,16 +239,17 @@ TEST_F(HTMLMediaElementEventListenersTest,
class MockEventListener final : public EventListener {
public:
- static MockEventListener* Create() { return new MockEventListener(); }
+ static MockEventListener* Create() {
+ return MakeGarbageCollected<MockEventListener>();
+ }
+
+ MockEventListener() : EventListener(kCPPEventListenerType) {}
bool operator==(const EventListener& other) const final {
return this == &other;
}
- MOCK_METHOD2(handleEvent, void(ExecutionContext* executionContext, Event*));
-
- private:
- MockEventListener() : EventListener(kCPPEventListenerType) {}
+ MOCK_METHOD2(Invoke, void(ExecutionContext* executionContext, Event*));
};
class HTMLMediaElementWithMockSchedulerTest
@@ -283,7 +283,7 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, OneTimeupdatePerSeek) {
ASSERT_NE(WebMediaPlayer(), nullptr);
MockEventListener* timeupdate_handler = MockEventListener::Create();
- Video()->addEventListener(EventTypeNames::timeupdate, timeupdate_handler);
+ Video()->addEventListener(event_type_names::kTimeupdate, timeupdate_handler);
// Simulate conditions where playback is possible.
SimulateNetworkState(HTMLMediaElement::kNetworkIdle);
@@ -296,18 +296,18 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, OneTimeupdatePerSeek) {
// While playing, timeupdate should fire every 250 ms -> 4x per second as long
// as media player's CurrentTime continues to advance.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(4);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(4);
platform_->RunForPeriodSeconds(1);
// If media playback time is fixed, periodic timeupdate's should not continue
// to fire.
WebMediaPlayer()->SetAutoAdvanceCurrentTime(false);
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(0);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(0);
platform_->RunForPeriodSeconds(1);
// Seek to some time in the past. A completed seek should trigger a *single*
// timeupdate.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(1);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
ASSERT_GE(WebMediaPlayer()->CurrentTime(), 1);
Video()->setCurrentTime(WebMediaPlayer()->CurrentTime() - 1);
@@ -329,7 +329,7 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
EXPECT_NE(WebMediaPlayer(), nullptr);
MockEventListener* timeupdate_handler = MockEventListener::Create();
- Video()->addEventListener(EventTypeNames::timeupdate, timeupdate_handler);
+ Video()->addEventListener(event_type_names::kTimeupdate, timeupdate_handler);
// Simulate conditions where playback is possible.
SimulateNetworkState(HTMLMediaElement::kNetworkIdle);
@@ -342,20 +342,20 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
// Advance a full periodic timeupdate interval (250 ms) and expect a single
// timeupdate.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(1);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
platform_->RunForPeriodSeconds(.250);
// The event is scheduled, but needs one more scheduler cycle to fire.
platform_->RunUntilIdle();
// Now advance 125 ms to reach the middle of the periodic timeupdate interval.
// no additional timeupdate should trigger.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(0);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(0);
platform_->RunForPeriodSeconds(.125);
platform_->RunUntilIdle();
// While still in the middle of the periodic timeupdate interval, start and
// complete a seek and verify that a *non-periodic* timeupdate is fired.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(1);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
ASSERT_GE(WebMediaPlayer()->CurrentTime(), 1);
Video()->setCurrentTime(WebMediaPlayer()->CurrentTime() - 1);
WebMediaPlayer()->FinishSeek();
@@ -366,20 +366,20 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
// timeupdate occurred only 125ms ago. We desire to fire periodic timeupdates
// exactly every 250ms from the last timeupdate, and the seek's timeupdate
// should reset that 250ms ms countdown.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(0);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(0);
platform_->RunForPeriodSeconds(.125);
platform_->RunUntilIdle();
// Advancing another 125ms, we should expect a new timeupdate because we are
// now 250ms from the seek's timeupdate.
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(1);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
platform_->RunForPeriodSeconds(.125);
platform_->RunUntilIdle();
// Advancing 250ms further, we should expect yet another timeupdate because
// this represents a full periodic timeupdate interval with no interruptions
// (e.g. no-seeks).
- EXPECT_CALL(*timeupdate_handler, handleEvent(_, _)).Times(1);
+ EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
platform_->RunForPeriodSeconds(.250);
platform_->RunUntilIdle();
}
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element_test.cc b/chromium/third_party/blink/renderer/core/html/media/html_media_element_test.cc
index 5c9b880accc..317d3741b5f 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element_test.cc
@@ -38,7 +38,7 @@ class MockWebMediaPlayer : public EmptyWebMediaPlayer {
Load,
WebMediaPlayer::LoadTiming(LoadType load_type,
const blink::WebMediaPlayerSource& source,
- CORSMode cors_mode));
+ CorsMode cors_mode));
MOCK_CONST_METHOD0(DidLazyLoad, bool());
};
@@ -46,7 +46,8 @@ class WebMediaStubLocalFrameClient : public EmptyLocalFrameClient {
public:
static WebMediaStubLocalFrameClient* Create(
std::unique_ptr<WebMediaPlayer> player) {
- return new WebMediaStubLocalFrameClient(std::move(player));
+ return MakeGarbageCollected<WebMediaStubLocalFrameClient>(
+ std::move(player));
}
WebMediaStubLocalFrameClient(std::unique_ptr<WebMediaPlayer> player)
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_video_element.cc b/chromium/third_party/blink/renderer/core/html/media/html_video_element.cc
index fb5b158dbc9..d391f486de7 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_video_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_video_element.cc
@@ -28,7 +28,7 @@
#include <memory>
#include "cc/paint/paint_canvas.h"
#include "third_party/blink/public/platform/web_fullscreen_video_status.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
@@ -56,12 +56,12 @@
#include "third_party/blink/renderer/platform/graphics/gpu/extensions_3d_util.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -75,7 +75,7 @@ enum VideoPersistenceControlsType {
} // anonymous namespace
inline HTMLVideoElement::HTMLVideoElement(Document& document)
- : HTMLMediaElement(videoTag, document),
+ : HTMLMediaElement(kVideoTag, document),
remoting_interstitial_(nullptr),
picture_in_picture_interstitial_(nullptr),
in_overlay_fullscreen_video_(false) {
@@ -86,11 +86,11 @@ inline HTMLVideoElement::HTMLVideoElement(Document& document)
if (RuntimeEnabledFeatures::VideoFullscreenDetectionEnabled()) {
custom_controls_fullscreen_detector_ =
- new MediaCustomControlsFullscreenDetector(*this);
+ MakeGarbageCollected<MediaCustomControlsFullscreenDetector>(*this);
}
- if (MediaElementParserHelpers::IsMediaElement(this) &&
- !MediaElementParserHelpers::IsUnsizedMediaEnabled(document)) {
+ if (media_element_parser_helpers::IsMediaElement(this) &&
+ !document.IsFeatureEnabled(mojom::FeaturePolicyFeature::kUnsizedMedia)) {
is_default_overridden_intrinsic_size_ = true;
overridden_intrinsic_size_ =
IntSize(LayoutReplaced::kDefaultWidth, LayoutReplaced::kDefaultHeight);
@@ -98,7 +98,7 @@ inline HTMLVideoElement::HTMLVideoElement(Document& document)
}
HTMLVideoElement* HTMLVideoElement::Create(Document& document) {
- HTMLVideoElement* video = new HTMLVideoElement(document);
+ HTMLVideoElement* video = MakeGarbageCollected<HTMLVideoElement>(document);
video->EnsureUserAgentShadowRoot();
video->PauseIfNeeded();
return video;
@@ -169,9 +169,9 @@ void HTMLVideoElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == widthAttr)
+ if (name == kWidthAttr)
AddHTMLLengthToStyle(style, CSSPropertyWidth, value);
- else if (name == heightAttr)
+ else if (name == kHeightAttr)
AddHTMLLengthToStyle(style, CSSPropertyHeight, value);
else
HTMLMediaElement::CollectStyleForPresentationAttribute(name, value, style);
@@ -179,14 +179,14 @@ void HTMLVideoElement::CollectStyleForPresentationAttribute(
bool HTMLVideoElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name == widthAttr || name == heightAttr)
+ if (name == kWidthAttr || name == kHeightAttr)
return true;
return HTMLMediaElement::IsPresentationAttribute(name);
}
void HTMLVideoElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == posterAttr) {
+ if (params.name == kPosterAttr) {
// In case the poster attribute is set after playback, don't update the
// display state, post playback the correct state will be picked up.
if (GetDisplayMode() < kVideo || !HasAvailableVideoFrame()) {
@@ -216,12 +216,12 @@ void HTMLVideoElement::ParseAttribute(
remoting_interstitial_->OnPosterImageChanged();
if (picture_in_picture_interstitial_)
picture_in_picture_interstitial_->OnPosterImageChanged();
- } else if (params.name == intrinsicsizeAttr &&
+ } else if (params.name == kIntrinsicsizeAttr &&
RuntimeEnabledFeatures::
ExperimentalProductivityFeaturesEnabled()) {
String message;
bool intrinsic_size_changed =
- MediaElementParserHelpers::ParseIntrinsicSizeAttribute(
+ media_element_parser_helpers::ParseIntrinsicSizeAttribute(
params.new_value, this, &overridden_intrinsic_size_,
&is_default_overridden_intrinsic_size_, &message);
if (!message.IsEmpty()) {
@@ -263,12 +263,12 @@ IntSize HTMLVideoElement::GetOverriddenIntrinsicSize() const {
}
bool HTMLVideoElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == posterAttr ||
+ return attribute.GetName() == kPosterAttr ||
HTMLMediaElement::IsURLAttribute(attribute);
}
const AtomicString HTMLVideoElement::ImageSourceURL() const {
- const AtomicString& url = getAttribute(posterAttr);
+ const AtomicString& url = getAttribute(kPosterAttr);
if (!StripLeadingAndTrailingHTMLSpaces(url).IsEmpty())
return url;
return default_poster_url_;
@@ -376,6 +376,7 @@ void HTMLVideoElement::PaintCurrentFrame(
} else {
media_flags.setAlpha(0xFF);
media_flags.setFilterQuality(kLow_SkFilterQuality);
+ media_flags.setBlendMode(SkBlendMode::kSrc);
}
GetWebMediaPlayer()->Paint(canvas, dest_rect, media_flags,
@@ -454,8 +455,8 @@ bool HTMLVideoElement::HasAvailableVideoFrame() const {
void HTMLVideoElement::webkitEnterFullscreen() {
if (!IsFullscreen()) {
- FullscreenOptions options;
- options.setNavigationUI("hide");
+ FullscreenOptions* options = FullscreenOptions::Create();
+ options->setNavigationUI("hide");
Fullscreen::RequestFullscreen(*this, options,
Fullscreen::RequestType::kPrefixed);
}
@@ -489,8 +490,8 @@ void HTMLVideoElement::DidEnterFullscreen() {
exitPictureInPicture(base::DoNothing());
if (GetWebMediaPlayer()) {
- // FIXME: There is no embedder-side handling in layout test mode.
- if (!LayoutTestSupport::IsRunningLayoutTest())
+ // FIXME: There is no embedder-side handling in web test mode.
+ if (!WebTestSupport::IsRunningWebTest())
GetWebMediaPlayer()->EnteredFullscreen();
GetWebMediaPlayer()->OnDisplayTypeChanged(DisplayType());
}
@@ -582,9 +583,8 @@ scoped_refptr<Image> HTMLVideoElement::GetSourceImageForCanvas(
return snapshot;
}
-bool HTMLVideoElement::WouldTaintOrigin(
- const SecurityOrigin* destination_security_origin) const {
- return !IsMediaDataCORSSameOrigin(destination_security_origin);
+bool HTMLVideoElement::WouldTaintOrigin(const SecurityOrigin*) const {
+ return !IsMediaDataCorsSameOrigin();
}
FloatSize HTMLVideoElement::ElementSize(const FloatSize&) const {
@@ -599,7 +599,7 @@ ScriptPromise HTMLVideoElement::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
DCHECK(event_target.ToLocalDOMWindow());
if (getNetworkState() == HTMLMediaElement::kNetworkEmpty) {
return ScriptPromise::RejectWithDOMException(
@@ -624,7 +624,8 @@ ScriptPromise HTMLVideoElement::CreateImageBitmap(
void HTMLVideoElement::MediaRemotingStarted(
const WebString& remote_device_friendly_name) {
if (!remoting_interstitial_) {
- remoting_interstitial_ = new MediaRemotingInterstitial(*this);
+ remoting_interstitial_ =
+ MakeGarbageCollected<MediaRemotingInterstitial>(*this);
ShadowRoot& shadow_root = EnsureUserAgentShadowRoot();
shadow_root.InsertBefore(remoting_interstitial_, shadow_root.firstChild());
HTMLMediaElement::AssertShadowRootChildren(shadow_root);
@@ -698,7 +699,8 @@ bool HTMLVideoElement::IsInAutoPIP() const {
void HTMLVideoElement::OnEnteredPictureInPicture() {
if (!picture_in_picture_interstitial_) {
- picture_in_picture_interstitial_ = new PictureInPictureInterstitial(*this);
+ picture_in_picture_interstitial_ =
+ MakeGarbageCollected<PictureInPictureInterstitial>(*this);
ShadowRoot& shadow_root = EnsureUserAgentShadowRoot();
shadow_root.InsertBefore(picture_in_picture_interstitial_,
shadow_root.firstChild());
@@ -746,10 +748,10 @@ void HTMLVideoElement::SetIsEffectivelyFullscreen(
void HTMLVideoElement::AddedEventListener(
const AtomicString& event_type,
RegisteredEventListener& registered_listener) {
- if (event_type == EventTypeNames::enterpictureinpicture) {
+ if (event_type == event_type_names::kEnterpictureinpicture) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kEnterPictureInPictureEventListener);
- } else if (event_type == EventTypeNames::leavepictureinpicture) {
+ } else if (event_type == event_type_names::kLeavepictureinpicture) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kLeavePictureInPictureEventListener);
}
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_video_element.h b/chromium/third_party/blink/renderer/core/html/media/html_video_element.h
index 4b92995077e..3d0ec24fb60 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_video_element.h
+++ b/chromium/third_party/blink/renderer/core/html/media/html_video_element.h
@@ -53,6 +53,8 @@ class CORE_EXPORT HTMLVideoElement final : public HTMLMediaElement,
public:
static HTMLVideoElement* Create(Document&);
+
+ HTMLVideoElement(Document&);
void Trace(blink::Visitor*) override;
bool HasPendingActivity() const final;
@@ -85,6 +87,8 @@ class CORE_EXPORT HTMLVideoElement final : public HTMLMediaElement,
unsigned webkitDroppedFrameCount() const;
// Used by canvas to gain raw pixel access
+ //
+ // PaintFlags is optional. If unspecified, its blend mode defaults to kSrc.
void PaintCurrentFrame(
cc::PaintCanvas*,
const IntRect&,
@@ -159,7 +163,7 @@ class CORE_EXPORT HTMLVideoElement final : public HTMLMediaElement,
ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions&) override;
+ const ImageBitmapOptions*) override;
// WebMediaPlayerClient implementation.
void OnBecamePersistentVideo(bool) final;
@@ -192,6 +196,11 @@ class CORE_EXPORT HTMLVideoElement final : public HTMLMediaElement,
void SetIsEffectivelyFullscreen(blink::WebFullscreenVideoStatus);
+ void SetImageForTest(ImageResourceContent* content) {
+ DCHECK(image_loader_);
+ image_loader_->SetImageForTest(content);
+ }
+
protected:
// EventTarget overrides.
void AddedEventListener(const AtomicString& event_type,
@@ -202,8 +211,6 @@ class CORE_EXPORT HTMLVideoElement final : public HTMLMediaElement,
friend class HTMLMediaElementEventListenersTest;
friend class HTMLVideoElementPersistentTest;
- HTMLVideoElement(Document&);
-
// PausableObject functions.
void ContextDestroyed(ExecutionContext*) final;
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_video_element_persistent_test.cc b/chromium/third_party/blink/renderer/core/html/media/html_video_element_persistent_test.cc
index cf2a9aa8409..5cc4de3bb19 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_video_element_persistent_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_video_element_persistent_test.cc
@@ -22,7 +22,7 @@ namespace {
class FullscreenMockChromeClient : public EmptyChromeClient {
public:
- MOCK_METHOD2(EnterFullscreen, void(LocalFrame&, const FullscreenOptions&));
+ MOCK_METHOD2(EnterFullscreen, void(LocalFrame&, const FullscreenOptions*));
MOCK_METHOD1(ExitFullscreen, void(LocalFrame&));
};
@@ -282,7 +282,8 @@ TEST_F(HTMLVideoElementPersistentTest, removeVideoWithLayerWhilePersisting) {
EXPECT_EQ(FullscreenElement(), nullptr);
// Inserting a <span> between the <div> and <video>.
- Persistent<Element> span = GetDocument().CreateRawElement(HTMLNames::spanTag);
+ Persistent<Element> span =
+ GetDocument().CreateRawElement(html_names::kSpanTag);
DivElement()->AppendChild(span);
span->AppendChild(VideoElement());
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_video_element_test.cc b/chromium/third_party/blink/renderer/core/html/media/html_video_element_test.cc
index 78a1a88e979..d34ae82dc73 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_video_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/html_video_element_test.cc
@@ -50,9 +50,10 @@ class HTMLVideoElementTest : public PageTestBase {
std::make_unique<HTMLVideoElementMockMediaPlayer>();
media_player_ = mock_media_player.get();
- SetupPageWithClients(
- nullptr, new HTMLVideoElementFrameClient(std::move(mock_media_player)),
- nullptr);
+ SetupPageWithClients(nullptr,
+ MakeGarbageCollected<HTMLVideoElementFrameClient>(
+ std::move(mock_media_player)),
+ nullptr);
video_ = HTMLVideoElement::Create(GetDocument());
GetDocument().body()->appendChild(video_);
}
@@ -76,7 +77,7 @@ TEST_F(HTMLVideoElementTest, PictureInPictureInterstitialAndTextContainer) {
scoped_refptr<cc::Layer> layer = cc::Layer::Create();
SetFakeCcLayer(layer.get());
- video()->SetBooleanAttribute(HTMLNames::controlsAttr, true);
+ video()->SetBooleanAttribute(html_names::kControlsAttr, true);
video()->SetSrc("http://example.com/foo.mp4");
test::RunPendingTasks();
@@ -100,7 +101,7 @@ TEST_F(HTMLVideoElementTest, PictureInPictureInterstitial_Reattach) {
scoped_refptr<cc::Layer> layer = cc::Layer::Create();
SetFakeCcLayer(layer.get());
- video()->SetBooleanAttribute(HTMLNames::controlsAttr, true);
+ video()->SetBooleanAttribute(html_names::kControlsAttr, true);
video()->SetSrc("http://example.com/foo.mp4");
test::RunPendingTasks();
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc b/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc
index c4dedb2c6ad..c8f46608d54 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc
@@ -43,20 +43,21 @@ bool MediaCustomControlsFullscreenDetector::operator==(
}
void MediaCustomControlsFullscreenDetector::Attach() {
- VideoElement().addEventListener(EventTypeNames::loadedmetadata, this, true);
+ VideoElement().addEventListener(event_type_names::kLoadedmetadata, this,
+ true);
VideoElement().GetDocument().addEventListener(
- EventTypeNames::webkitfullscreenchange, this, true);
+ event_type_names::kWebkitfullscreenchange, this, true);
VideoElement().GetDocument().addEventListener(
- EventTypeNames::fullscreenchange, this, true);
+ event_type_names::kFullscreenchange, this, true);
}
void MediaCustomControlsFullscreenDetector::Detach() {
- VideoElement().removeEventListener(EventTypeNames::loadedmetadata, this,
+ VideoElement().removeEventListener(event_type_names::kLoadedmetadata, this,
true);
VideoElement().GetDocument().removeEventListener(
- EventTypeNames::webkitfullscreenchange, this, true);
+ event_type_names::kWebkitfullscreenchange, this, true);
VideoElement().GetDocument().removeEventListener(
- EventTypeNames::fullscreenchange, this, true);
+ event_type_names::kFullscreenchange, this, true);
check_viewport_intersection_timer_.Stop();
VideoElement().SetIsEffectivelyFullscreen(
@@ -99,12 +100,11 @@ bool MediaCustomControlsFullscreenDetector::ComputeIsDominantVideoForTests(
intersection_rect.Width();
}
-void MediaCustomControlsFullscreenDetector::handleEvent(
- ExecutionContext* context,
- Event* event) {
- DCHECK(event->type() == EventTypeNames::loadedmetadata ||
- event->type() == EventTypeNames::webkitfullscreenchange ||
- event->type() == EventTypeNames::fullscreenchange);
+void MediaCustomControlsFullscreenDetector::Invoke(ExecutionContext* context,
+ Event* event) {
+ DCHECK(event->type() == event_type_names::kLoadedmetadata ||
+ event->type() == event_type_names::kWebkitfullscreenchange ||
+ event->type() == event_type_names::kFullscreenchange);
// Video is not loaded yet.
if (VideoElement().getReadyState() < HTMLMediaElement::kHaveMetadata)
@@ -129,6 +129,8 @@ void MediaCustomControlsFullscreenDetector::ContextDestroyed() {
void MediaCustomControlsFullscreenDetector::
OnCheckViewportIntersectionTimerFired(TimerBase*) {
DCHECK(IsVideoOrParentFullscreen());
+
+ // TODO(crbug.com/906258): This can cause a crash when DCHECKs are enabled!
IntersectionGeometry geometry(nullptr, VideoElement(), Vector<Length>(),
true);
geometry.ComputeGeometry();
@@ -146,7 +148,8 @@ void MediaCustomControlsFullscreenDetector::
// Picture-in-Picture can be disabled by the website when the API is enabled.
bool picture_in_picture_allowed =
!RuntimeEnabledFeatures::PictureInPictureEnabled() &&
- !VideoElement().FastHasAttribute(HTMLNames::disablepictureinpictureAttr);
+ !VideoElement().FastHasAttribute(
+ html_names::kDisablepictureinpictureAttr);
if (picture_in_picture_allowed) {
VideoElement().SetIsEffectivelyFullscreen(
WebFullscreenVideoStatus::kFullscreenAndPictureInPictureEnabled);
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h b/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h
index b75878c500f..072c68fa7f6 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h
+++ b/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h
@@ -35,7 +35,7 @@ class CORE_EXPORT MediaCustomControlsFullscreenDetector final
friend class HTMLMediaElementEventListenersTest;
// EventListener implementation.
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
HTMLVideoElement& VideoElement() { return *video_element_; }
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector_test.cc b/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector_test.cc
index 53b9b0a9955..c3f10037478 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector_test.cc
@@ -113,70 +113,74 @@ TEST_F(MediaCustomControlsFullscreenDetectorTest, computeIsDominantVideo) {
TEST_F(MediaCustomControlsFullscreenDetectorTest,
hasNoListenersBeforeAddingToDocument) {
auto* video =
- ToHTMLVideoElement(GetDocument().CreateRawElement(HTMLNames::videoTag));
+ ToHTMLVideoElement(GetDocument().CreateRawElement(html_names::kVideoTag));
EXPECT_FALSE(CheckEventListenerRegistered(GetDocument(),
- EventTypeNames::fullscreenchange,
+ event_type_names::kFullscreenchange,
FullscreenDetectorFor(video)));
EXPECT_FALSE(CheckEventListenerRegistered(
- GetDocument(), EventTypeNames::webkitfullscreenchange,
+ GetDocument(), event_type_names::kWebkitfullscreenchange,
FullscreenDetectorFor(video)));
EXPECT_FALSE(CheckEventListenerRegistered(
- *video, EventTypeNames::loadedmetadata, FullscreenDetectorFor(video)));
+ *video, event_type_names::kLoadedmetadata, FullscreenDetectorFor(video)));
}
TEST_F(MediaCustomControlsFullscreenDetectorTest,
hasListenersAfterAddToDocumentByScript) {
auto* video =
- ToHTMLVideoElement(GetDocument().CreateRawElement(HTMLNames::videoTag));
+ ToHTMLVideoElement(GetDocument().CreateRawElement(html_names::kVideoTag));
GetDocument().body()->AppendChild(video);
+ EXPECT_TRUE(CheckEventListenerRegistered(GetDocument(),
+ event_type_names::kFullscreenchange,
+ FullscreenDetector()));
EXPECT_TRUE(CheckEventListenerRegistered(
- GetDocument(), EventTypeNames::fullscreenchange, FullscreenDetector()));
- EXPECT_TRUE(CheckEventListenerRegistered(
- GetDocument(), EventTypeNames::webkitfullscreenchange,
+ GetDocument(), event_type_names::kWebkitfullscreenchange,
FullscreenDetector()));
- EXPECT_TRUE(CheckEventListenerRegistered(
- *VideoElement(), EventTypeNames::loadedmetadata, FullscreenDetector()));
+ EXPECT_TRUE(CheckEventListenerRegistered(*VideoElement(),
+ event_type_names::kLoadedmetadata,
+ FullscreenDetector()));
}
TEST_F(MediaCustomControlsFullscreenDetectorTest,
hasListenersAfterAddToDocumentByParser) {
GetDocument().body()->SetInnerHTMLFromString("<body><video></video></body>");
+ EXPECT_TRUE(CheckEventListenerRegistered(GetDocument(),
+ event_type_names::kFullscreenchange,
+ FullscreenDetector()));
EXPECT_TRUE(CheckEventListenerRegistered(
- GetDocument(), EventTypeNames::fullscreenchange, FullscreenDetector()));
- EXPECT_TRUE(CheckEventListenerRegistered(
- GetDocument(), EventTypeNames::webkitfullscreenchange,
+ GetDocument(), event_type_names::kWebkitfullscreenchange,
FullscreenDetector()));
- EXPECT_TRUE(CheckEventListenerRegistered(
- *VideoElement(), EventTypeNames::loadedmetadata, FullscreenDetector()));
+ EXPECT_TRUE(CheckEventListenerRegistered(*VideoElement(),
+ event_type_names::kLoadedmetadata,
+ FullscreenDetector()));
}
TEST_F(MediaCustomControlsFullscreenDetectorTest,
hasListenersAfterDocumentMove) {
auto* video =
- ToHTMLVideoElement(GetDocument().CreateRawElement(HTMLNames::videoTag));
+ ToHTMLVideoElement(GetDocument().CreateRawElement(html_names::kVideoTag));
GetDocument().body()->AppendChild(video);
NewDocument().body()->AppendChild(VideoElement());
EXPECT_FALSE(CheckEventListenerRegistered(GetDocument(),
- EventTypeNames::fullscreenchange,
+ event_type_names::kFullscreenchange,
FullscreenDetectorFor(video)));
EXPECT_FALSE(CheckEventListenerRegistered(
- GetDocument(), EventTypeNames::webkitfullscreenchange,
+ GetDocument(), event_type_names::kWebkitfullscreenchange,
FullscreenDetectorFor(video)));
EXPECT_TRUE(CheckEventListenerRegistered(NewDocument(),
- EventTypeNames::fullscreenchange,
+ event_type_names::kFullscreenchange,
FullscreenDetectorFor(video)));
EXPECT_TRUE(CheckEventListenerRegistered(
- NewDocument(), EventTypeNames::webkitfullscreenchange,
+ NewDocument(), event_type_names::kWebkitfullscreenchange,
FullscreenDetectorFor(video)));
EXPECT_TRUE(CheckEventListenerRegistered(
- *video, EventTypeNames::loadedmetadata, FullscreenDetectorFor(video)));
+ *video, event_type_names::kLoadedmetadata, FullscreenDetectorFor(video)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_document.cc b/chromium/third_party/blink/renderer/core/html/media/media_document.cc
index 5263a790ecb..0cd4b9482ee 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/media_document.cc
@@ -52,19 +52,19 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// FIXME: Share more code with PluginDocumentParser.
class MediaDocumentParser : public RawDataDocumentParser {
public:
static MediaDocumentParser* Create(MediaDocument* document) {
- return new MediaDocumentParser(document);
+ return MakeGarbageCollected<MediaDocumentParser>(document);
}
- private:
explicit MediaDocumentParser(Document* document)
: RawDataDocumentParser(document), did_build_document_structure_(false) {}
+ private:
void AppendBytes(const char*, size_t) override;
void CreateDocumentStructure();
@@ -83,14 +83,14 @@ void MediaDocumentParser::CreateDocumentStructure() {
HTMLHeadElement* head = HTMLHeadElement::Create(*GetDocument());
HTMLMetaElement* meta = HTMLMetaElement::Create(*GetDocument());
- meta->setAttribute(nameAttr, "viewport");
- meta->setAttribute(contentAttr, "width=device-width");
+ meta->setAttribute(kNameAttr, "viewport");
+ meta->setAttribute(kContentAttr, "width=device-width");
head->AppendChild(meta);
HTMLVideoElement* media = HTMLVideoElement::Create(*GetDocument());
- media->setAttribute(controlsAttr, "");
- media->setAttribute(autoplayAttr, "");
- media->setAttribute(nameAttr, "media");
+ media->setAttribute(kControlsAttr, "");
+ media->setAttribute(kAutoplayAttr, "");
+ media->setAttribute(kNameAttr, "media");
HTMLSourceElement* source = HTMLSourceElement::Create(*GetDocument());
source->SetSrc(GetDocument()->Url());
@@ -142,7 +142,7 @@ void MediaDocument::DefaultEventHandler(Event& event) {
if (!target_node)
return;
- if (event.type() == EventTypeNames::keydown && event.IsKeyboardEvent()) {
+ if (event.type() == event_type_names::kKeydown && event.IsKeyboardEvent()) {
HTMLVideoElement* video =
Traversal<HTMLVideoElement>::FirstWithin(*target_node);
if (!video)
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_document.h b/chromium/third_party/blink/renderer/core/html/media/media_document.h
index c877e115d38..9b68b0d3996 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_document.h
+++ b/chromium/third_party/blink/renderer/core/html/media/media_document.h
@@ -33,12 +33,12 @@ namespace blink {
class MediaDocument final : public HTMLDocument {
public:
static MediaDocument* Create(const DocumentInit& initializer) {
- return new MediaDocument(initializer);
+ return MakeGarbageCollected<MediaDocument>(initializer);
}
- private:
MediaDocument(const DocumentInit&);
+ private:
DocumentParser* CreateParser() override;
void DefaultEventHandler(Event&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.cc b/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.cc
index d79dddb5e42..8ab20daca59 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.cc
@@ -17,7 +17,7 @@
namespace blink {
-namespace MediaElementParserHelpers {
+namespace media_element_parser_helpers {
bool IsMediaElement(const Element* element) {
if ((IsHTMLImageElement(element) || IsSVGImageElement(element)) &&
@@ -28,16 +28,6 @@ bool IsMediaElement(const Element* element) {
return false;
}
-bool IsUnsizedMediaEnabled(const Document& document) {
- if (auto* frame = document.GetFrame()) {
- return frame->DeprecatedIsFeatureEnabled(
- mojom::FeaturePolicyFeature::kUnsizedMedia);
- }
- // Unsized media is by default enabled every where, so when the frame is not
- // available return default policy (true).
- return true;
-}
-
bool ParseIntrinsicSizeAttribute(const String& value,
const Element* element,
IntSize* intrinsic_size,
@@ -59,7 +49,8 @@ bool ParseIntrinsicSizeAttribute(const String& value,
new_height = 0;
}
if (new_width == 0 && new_height == 0 && IsMediaElement(element) &&
- !IsUnsizedMediaEnabled(element->GetDocument())) {
+ !element->GetDocument().IsFeatureEnabled(
+ mojom::FeaturePolicyFeature::kUnsizedMedia)) {
new_width = LayoutReplaced::kDefaultWidth;
new_height = LayoutReplaced::kDefaultHeight;
*is_default_intrinsic_size = true;
@@ -76,12 +67,13 @@ bool ParseIntrinsicSizeAttribute(const String& value,
void ReportUnsizedMediaViolation(const LayoutObject* layout_object) {
const ComputedStyle& style = layout_object->StyleRef();
if (!style.LogicalWidth().IsSpecified() &&
- !style.LogicalHeight().IsSpecified() && layout_object->GetFrame()) {
- layout_object->GetFrame()->DeprecatedReportFeaturePolicyViolation(
- mojom::FeaturePolicyFeature::kUnsizedMedia);
+ !style.LogicalHeight().IsSpecified()) {
+ layout_object->GetDocument().ReportFeaturePolicyViolation(
+ mojom::FeaturePolicyFeature::kUnsizedMedia,
+ mojom::FeaturePolicyDisposition::kEnforce);
}
}
-} // namespace MediaElementParserHelpers
+} // namespace media_element_parser_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.h b/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.h
index b231442899d..847f8bd2805 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.h
+++ b/chromium/third_party/blink/renderer/core/html/media/media_element_parser_helpers.h
@@ -10,10 +10,9 @@
namespace blink {
class Element;
-class Document;
class LayoutObject;
-namespace MediaElementParserHelpers {
+namespace media_element_parser_helpers {
// Parses the intrinsicSize attribute of HTMLImageElement, HTMLVideoElement, and
// SVGImageElement. Returns true if the value is updated.
@@ -28,13 +27,9 @@ bool ParseIntrinsicSizeAttribute(const String& value,
// are not in an image or media document; returns false otherwise.
bool IsMediaElement(const Element* element);
-// Returns if the document is allowed to use
-// FeaturePolicyFeature::kUnsizedMedia.
-bool IsUnsizedMediaEnabled(const Document& document);
-
void ReportUnsizedMediaViolation(const LayoutObject* layout_object);
-} // namespace MediaElementParserHelpers
+} // namespace media_element_parser_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_error.h b/chromium/third_party/blink/renderer/core/html/media/media_error.h
index 1558aac028b..1bf2f00d292 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_error.h
+++ b/chromium/third_party/blink/renderer/core/html/media/media_error.h
@@ -44,9 +44,12 @@ class CORE_EXPORT MediaError final : public ScriptWrappable {
};
static MediaError* Create(ErrorCode code, const String& message) {
- return new MediaError(code, message);
+ return MakeGarbageCollected<MediaError>(code, message);
}
+ MediaError(ErrorCode code, const String& message)
+ : code_(code), message_(message) {}
+
ErrorCode code() const { return code_; }
// Returns either an empty string, or a human readable string describing
@@ -54,9 +57,6 @@ class CORE_EXPORT MediaError final : public ScriptWrappable {
String message() const { return message_; }
private:
- MediaError(ErrorCode code, const String& message)
- : code_(code), message_(message) {}
-
ErrorCode code_;
String message_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc b/chromium/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc
index f62a329645d..9b4c467f239 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc
@@ -34,7 +34,7 @@ MediaRemotingInterstitial::MediaRemotingInterstitial(
background_image_ = HTMLImageElement::Create(GetDocument());
background_image_->SetShadowPseudoId(
AtomicString("-internal-media-interstitial-background-image"));
- background_image_->SetSrc(videoElement.getAttribute(HTMLNames::posterAttr));
+ background_image_->SetSrc(videoElement.getAttribute(html_names::kPosterAttr));
AppendChild(background_image_);
cast_icon_ = HTMLDivElement::Create(GetDocument());
@@ -141,7 +141,7 @@ void MediaRemotingInterstitial::DidMoveToNewDocument(Document& old_document) {
void MediaRemotingInterstitial::OnPosterImageChanged() {
background_image_->SetSrc(
- GetVideoElement().getAttribute(HTMLNames::posterAttr));
+ GetVideoElement().getAttribute(html_names::kPosterAttr));
}
void MediaRemotingInterstitial::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc b/chromium/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc
index e0adc27811f..a6d4939854f 100644
--- a/chromium/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc
@@ -57,9 +57,9 @@ class PictureInPictureInterstitial::VideoElementResizeObserverDelegate final
PictureInPictureInterstitial::PictureInPictureInterstitial(
HTMLVideoElement& videoElement)
: HTMLDivElement(videoElement.GetDocument()),
- resize_observer_(
- ResizeObserver::Create(videoElement.GetDocument(),
- new VideoElementResizeObserverDelegate(this))),
+ resize_observer_(ResizeObserver::Create(
+ videoElement.GetDocument(),
+ MakeGarbageCollected<VideoElementResizeObserverDelegate>(this))),
interstitial_timer_(
videoElement.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
this,
@@ -70,7 +70,7 @@ PictureInPictureInterstitial::PictureInPictureInterstitial(
background_image_ = HTMLImageElement::Create(GetDocument());
background_image_->SetShadowPseudoId(
AtomicString("-internal-media-interstitial-background-image"));
- background_image_->SetSrc(videoElement.getAttribute(HTMLNames::posterAttr));
+ background_image_->SetSrc(videoElement.getAttribute(html_names::kPosterAttr));
ParserAppendChild(background_image_);
message_element_ = HTMLDivElement::Create(GetDocument());
@@ -119,9 +119,9 @@ void PictureInPictureInterstitial::Hide() {
Node::InsertionNotificationRequest PictureInPictureInterstitial::InsertedInto(
ContainerNode& root) {
if (GetVideoElement().isConnected() && !resize_observer_) {
- resize_observer_ =
- ResizeObserver::Create(GetVideoElement().GetDocument(),
- new VideoElementResizeObserverDelegate(this));
+ resize_observer_ = ResizeObserver::Create(
+ GetVideoElement().GetDocument(),
+ MakeGarbageCollected<VideoElementResizeObserverDelegate>(this));
resize_observer_->observe(&GetVideoElement());
}
@@ -157,7 +157,7 @@ void PictureInPictureInterstitial::ToggleInterstitialTimerFired(TimerBase*) {
void PictureInPictureInterstitial::OnPosterImageChanged() {
background_image_->SetSrc(
- GetVideoElement().getAttribute(HTMLNames::posterAttr));
+ GetVideoElement().getAttribute(html_names::kPosterAttr));
}
void PictureInPictureInterstitial::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/html/media_element_filling_viewport_test.cc b/chromium/third_party/blink/renderer/core/html/media_element_filling_viewport_test.cc
index e8dda256ce7..6b7b2a69780 100644
--- a/chromium/third_party/blink/renderer/core/html/media_element_filling_viewport_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media_element_filling_viewport_test.cc
@@ -27,11 +27,15 @@ class MediaElementFillingViewportTest : public SimTest {
return element->mostly_filling_viewport_;
}
- void CheckViewportIntersectionChanged(HTMLMediaElement* element) {
- element->ActivateViewportIntersectionMonitoring(true);
- EXPECT_TRUE(element->check_viewport_intersection_timer_.IsActive());
- // TODO(xjz): Mock the time and wait for 1s instead.
- element->CheckViewportIntersectionTimerFired(nullptr);
+ void ActivateViewportIntersectionMonitoring(HTMLMediaElement* element,
+ bool enable) {
+ element->ActivateViewportIntersectionMonitoring(enable);
+ EXPECT_EQ(enable, !!element->viewport_intersection_observer_);
+ }
+
+ void DoCompositeAndPropagate() {
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
}
std::unique_ptr<SimRequest> CreateMainResource() {
@@ -57,8 +61,14 @@ TEST_F(MediaElementFillingViewportTest, MostlyFillingViewport) {
HTMLMediaElement* element =
ToElement<HTMLMediaElement>(GetDocument().getElementById("video"));
- CheckViewportIntersectionChanged(element);
+
+ ActivateViewportIntersectionMonitoring(element, true);
+ DoCompositeAndPropagate();
EXPECT_TRUE(IsMostlyFillingViewport(element));
+
+ ActivateViewportIntersectionMonitoring(element, false);
+ DoCompositeAndPropagate();
+ EXPECT_FALSE(IsMostlyFillingViewport(element));
}
TEST_F(MediaElementFillingViewportTest, NotMostlyFillingViewport) {
@@ -76,7 +86,8 @@ TEST_F(MediaElementFillingViewportTest, NotMostlyFillingViewport) {
HTMLMediaElement* element =
ToElement<HTMLMediaElement>(GetDocument().getElementById("video"));
- CheckViewportIntersectionChanged(element);
+ ActivateViewportIntersectionMonitoring(element, true);
+ DoCompositeAndPropagate();
EXPECT_FALSE(IsMostlyFillingViewport(element));
}
@@ -95,15 +106,15 @@ TEST_F(MediaElementFillingViewportTest, FillingViewportChanged) {
HTMLMediaElement* element =
ToElement<HTMLMediaElement>(GetDocument().getElementById("video"));
- CheckViewportIntersectionChanged(element);
+
+ ActivateViewportIntersectionMonitoring(element, true);
+ DoCompositeAndPropagate();
EXPECT_TRUE(IsMostlyFillingViewport(element));
element->setAttribute("style",
"position:fixed; left:0; top:0; width:80%; height:80%;",
ASSERT_NO_EXCEPTION);
- Compositor().BeginFrame();
-
- CheckViewportIntersectionChanged(element);
+ DoCompositeAndPropagate();
EXPECT_FALSE(IsMostlyFillingViewport(element));
}
@@ -122,7 +133,9 @@ TEST_F(MediaElementFillingViewportTest, LargeVideo) {
HTMLMediaElement* element =
ToElement<HTMLMediaElement>(GetDocument().getElementById("video"));
- CheckViewportIntersectionChanged(element);
+
+ ActivateViewportIntersectionMonitoring(element, true);
+ DoCompositeAndPropagate();
EXPECT_TRUE(IsMostlyFillingViewport(element));
}
@@ -141,14 +154,15 @@ TEST_F(MediaElementFillingViewportTest, VideoScrollOutHalf) {
HTMLMediaElement* element =
ToElement<HTMLMediaElement>(GetDocument().getElementById("video"));
- CheckViewportIntersectionChanged(element);
+
+ ActivateViewportIntersectionMonitoring(element, true);
+ DoCompositeAndPropagate();
EXPECT_TRUE(IsMostlyFillingViewport(element));
element->setAttribute(
"style", "position:fixed; left:0; top:240px; width:100%; height:100%;",
ASSERT_NO_EXCEPTION);
- Compositor().BeginFrame();
- CheckViewportIntersectionChanged(element);
+ DoCompositeAndPropagate();
EXPECT_FALSE(IsMostlyFillingViewport(element));
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.cc b/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.cc
index b4a5845bc2c..8818320915a 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.cc
@@ -37,7 +37,6 @@
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -66,8 +65,6 @@ static const size_t kPendingTokenLimit = 1000;
static_assert(kOutstandingTokenLimit > kPendingTokenLimit,
"Outstanding token limit is applied after pending token limit.");
-using namespace HTMLNames;
-
base::WeakPtr<BackgroundHTMLParser> BackgroundHTMLParser::Create(
std::unique_ptr<Configuration> config,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) {
@@ -249,6 +246,7 @@ void BackgroundHTMLParser::PumpTokenizer() {
if (simulated_token == HTMLTreeBuilderSimulator::kScriptEnd ||
simulated_token == HTMLTreeBuilderSimulator::kStyleEnd ||
simulated_token == HTMLTreeBuilderSimulator::kLink ||
+ simulated_token == HTMLTreeBuilderSimulator::kCustomElementBegin ||
pending_tokens_.size() >= kPendingTokenLimit) {
EnqueueTokenizedChunk();
diff --git a/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.cc b/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.cc
index 2fbecf3ca76..1dd67036707 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.cc
@@ -86,7 +86,8 @@ void CSSPreloadScanner::Scan(const String& tag_name,
predicted_base_element_url);
}
-void CSSPreloadScanner::SetReferrerPolicy(const ReferrerPolicy policy) {
+void CSSPreloadScanner::SetReferrerPolicy(
+ network::mojom::ReferrerPolicy policy) {
referrer_policy_ = policy;
}
@@ -156,12 +157,18 @@ inline void CSSPreloadScanner::Tokenize(UChar c,
}
break;
case kRuleValue:
- if (IsHTMLSpace<UChar>(c))
+ if (IsHTMLSpace<UChar>(c)) {
state_ = kAfterRuleValue;
- else if (c == ';')
+ } else if (c == ';') {
EmitRule(source);
- else
+ } else {
rule_value_.Append(c);
+ // When reading the rule and hitting ')', which signifies the URL end,
+ // emit the rule.
+ if (c == ')') {
+ EmitRule(source);
+ }
+ }
break;
case kAfterRuleValue:
if (IsHTMLSpace<UChar>(c))
@@ -185,14 +192,20 @@ static String ParseCSSStringOrURL(const String& string) {
wtf_size_t offset = 0;
wtf_size_t reduced_length = string.length();
+ // Remove whitespace from the rule start
while (reduced_length && IsHTMLSpace<UChar>(string[offset])) {
++offset;
--reduced_length;
}
+ // Remove whitespace from the rule end
+ // TODO(yoav): Evaluate performance benefits of using raw string operations.
+ // TODO(yoav): Look into moving parsing to use better parsing primitives.
while (reduced_length &&
- IsHTMLSpace<UChar>(string[offset + reduced_length - 1]))
+ IsHTMLSpace<UChar>(string[offset + reduced_length - 1])) {
--reduced_length;
+ }
+ // Skip the "url(" prefix and the ")" suffix
if (reduced_length >= 5 && (string[offset] == 'u' || string[offset] == 'U') &&
(string[offset + 1] == 'r' || string[offset + 1] == 'R') &&
(string[offset + 2] == 'l' || string[offset + 2] == 'L') &&
@@ -201,28 +214,23 @@ static String ParseCSSStringOrURL(const String& string) {
reduced_length -= 5;
}
+ // Skip whitespace before and after the URL inside the "url()" parenthesis.
while (reduced_length && IsHTMLSpace<UChar>(string[offset])) {
++offset;
--reduced_length;
}
while (reduced_length &&
- IsHTMLSpace<UChar>(string[offset + reduced_length - 1]))
+ IsHTMLSpace<UChar>(string[offset + reduced_length - 1])) {
--reduced_length;
+ }
- if (reduced_length < 2 ||
- string[offset] != string[offset + reduced_length - 1] ||
- !(string[offset] == '\'' || string[offset] == '"'))
- return String();
- offset++;
- reduced_length -= 2;
-
- while (reduced_length && IsHTMLSpace<UChar>(string[offset])) {
- ++offset;
- --reduced_length;
+ // Remove single-quotes or double-quotes from the URL
+ if ((reduced_length >= 2) &&
+ (string[offset] == string[offset + reduced_length - 1]) &&
+ (string[offset] == '\'' || string[offset] == '"')) {
+ offset++;
+ reduced_length -= 2;
}
- while (reduced_length &&
- IsHTMLSpace<UChar>(string[offset + reduced_length - 1]))
- --reduced_length;
return string.Substring(offset, reduced_length);
}
@@ -233,7 +241,7 @@ void CSSPreloadScanner::EmitRule(const SegmentedString& source) {
TextPosition position =
TextPosition(source.CurrentLine(), source.CurrentColumn());
auto request = PreloadRequest::CreateIfNeeded(
- FetchInitiatorTypeNames::css, position, url,
+ fetch_initiator_type_names::kCSS, position, url,
*predicted_base_element_url_, ResourceType::kCSSStyleSheet,
referrer_policy_, PreloadRequest::kBaseUrlIsReferrer,
ResourceFetcher::kImageNotImageSet);
diff --git a/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.h b/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.h
index 43fb7394c0e..8fdab879752 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/css_preload_scanner.h
@@ -54,7 +54,7 @@ class CSSPreloadScanner {
PreloadRequestStream&,
const KURL&);
- void SetReferrerPolicy(const ReferrerPolicy);
+ void SetReferrerPolicy(network::mojom::ReferrerPolicy);
private:
enum State {
@@ -84,7 +84,8 @@ class CSSPreloadScanner {
StringBuilder rule_;
StringBuilder rule_value_;
- ReferrerPolicy referrer_policy_ = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy_ =
+ network::mojom::ReferrerPolicy::kDefault;
// Below members only non-null during scan()
PreloadRequestStream* requests_ = nullptr;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_construction_site.cc b/chromium/third_party/blink/renderer/core/html/parser/html_construction_site.cc
index 4e8e09288f3..65faae0350f 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_construction_site.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_construction_site.cc
@@ -68,7 +68,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static const unsigned kMaximumHTMLParserDOMTreeDepth = 512;
@@ -85,11 +85,11 @@ static inline void SetAttributes(Element* element,
}
static bool HasImpliedEndTag(const HTMLStackItem* item) {
- return item->HasTagName(ddTag) || item->HasTagName(dtTag) ||
- item->HasTagName(liTag) || item->HasTagName(optionTag) ||
- item->HasTagName(optgroupTag) || item->HasTagName(pTag) ||
- item->HasTagName(rbTag) || item->HasTagName(rpTag) ||
- item->HasTagName(rtTag) || item->HasTagName(rtcTag);
+ return item->HasTagName(kDdTag) || item->HasTagName(kDtTag) ||
+ item->HasTagName(kLiTag) || item->HasTagName(kOptionTag) ||
+ item->HasTagName(kOptgroupTag) || item->HasTagName(kPTag) ||
+ item->HasTagName(kRbTag) || item->HasTagName(kRpTag) ||
+ item->HasTagName(kRtTag) || item->HasTagName(kRTCTag);
}
static bool ShouldUseLengthLimit(const ContainerNode& node) {
@@ -413,9 +413,9 @@ void HTMLConstructionSite::InsertHTMLHtmlStartTagBeforeHTML(
AtomicHTMLToken* token) {
DCHECK(document_);
HTMLHtmlElement* element;
- if (const auto* is_attribute = token->GetAttributeItem(HTMLNames::isAttr)) {
+ if (const auto* is_attribute = token->GetAttributeItem(html_names::kIsAttr)) {
element = ToHTMLHtmlElement(document_->CreateElement(
- HTMLNames::htmlTag, GetCreateElementFlags(), is_attribute->Value()));
+ html_names::kHTMLTag, GetCreateElementFlags(), is_attribute->Value()));
} else {
element = HTMLHtmlElement::Create(*document_);
}
@@ -737,9 +737,9 @@ void HTMLConstructionSite::InsertScriptElement(AtomicHTMLToken* token) {
kAllowScriptingContentAndDoNotMarkAlreadyStarted)
.SetAlreadyStarted(is_parsing_fragment_ && flags.IsCreatedByParser());
HTMLScriptElement* element = nullptr;
- if (const auto* is_attribute = token->GetAttributeItem(HTMLNames::isAttr)) {
+ if (const auto* is_attribute = token->GetAttributeItem(html_names::kIsAttr)) {
element = ToHTMLScriptElement(OwnerDocumentForCurrentNode().CreateElement(
- HTMLNames::scriptTag, flags, is_attribute->Value()));
+ html_names::kScriptTag, flags, is_attribute->Value()));
} else {
element = HTMLScriptElement::Create(OwnerDocumentForCurrentNode(), flags);
}
@@ -848,7 +848,7 @@ CustomElementDefinition* HTMLConstructionSite::LookUpCustomElementDefinition(
const QualifiedName& tag_name,
const AtomicString& is) {
// "1. If namespace is not the HTML namespace, return null."
- if (tag_name.NamespaceURI() != HTMLNames::xhtmlNamespaceURI)
+ if (tag_name.NamespaceURI() != html_names::xhtmlNamespaceURI)
return nullptr;
// "2. If document does not have a browsing context, return null."
@@ -881,7 +881,7 @@ Element* HTMLConstructionSite::CreateElement(
// "2. Let local name be the tag name of the token."
QualifiedName tag_name(g_null_atom, token->GetName(), namespace_uri);
// "3. Let is be the value of the "is" attribute in the given token ..." etc.
- const Attribute* is_attribute = token->GetAttributeItem(HTMLNames::isAttr);
+ const Attribute* is_attribute = token->GetAttributeItem(html_names::kIsAttr);
const AtomicString& is = is_attribute ? is_attribute->Value() : g_null_atom;
// "4. Let definition be the result of looking up a custom element ..." etc.
auto* definition = LookUpCustomElementDefinition(document, tag_name, is);
@@ -1062,11 +1062,11 @@ bool HTMLConstructionSite::InQuirksMode() {
void HTMLConstructionSite::FindFosterSite(HTMLConstructionSiteTask& task) {
// 2.1
HTMLElementStack::ElementRecord* last_template =
- open_elements_.Topmost(templateTag.LocalName());
+ open_elements_.Topmost(kTemplateTag.LocalName());
// 2.2
HTMLElementStack::ElementRecord* last_table =
- open_elements_.Topmost(tableTag.LocalName());
+ open_elements_.Topmost(kTableTag.LocalName());
// 2.3
if (last_template && (!last_table || last_template->IsAbove(last_table))) {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.cc b/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.cc
index 5637e2f1bd8..6624165f061 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.cc
@@ -64,7 +64,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// This is a direct transcription of step 4 from:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#fragment-case
@@ -77,19 +77,19 @@ static HTMLTokenizer::State TokenizerStateForContextElement(
const QualifiedName& context_tag = context_element->TagQName();
- if (context_tag.Matches(titleTag) || context_tag.Matches(textareaTag))
+ if (context_tag.Matches(kTitleTag) || context_tag.Matches(kTextareaTag))
return HTMLTokenizer::kRCDATAState;
- if (context_tag.Matches(styleTag) || context_tag.Matches(xmpTag) ||
- context_tag.Matches(iframeTag) ||
- (context_tag.Matches(noembedTag) && options.plugins_enabled) ||
- (context_tag.Matches(noscriptTag) && options.script_enabled) ||
- context_tag.Matches(noframesTag))
+ if (context_tag.Matches(kStyleTag) || context_tag.Matches(kXmpTag) ||
+ context_tag.Matches(kIFrameTag) ||
+ (context_tag.Matches(kNoembedTag) && options.plugins_enabled) ||
+ (context_tag.Matches(kNoscriptTag) && options.script_enabled) ||
+ context_tag.Matches(kNoframesTag))
return report_errors ? HTMLTokenizer::kRAWTEXTState
: HTMLTokenizer::kPLAINTEXTState;
- if (context_tag.Matches(scriptTag))
+ if (context_tag.Matches(kScriptTag))
return report_errors ? HTMLTokenizer::kScriptDataState
: HTMLTokenizer::kPLAINTEXTState;
- if (context_tag.Matches(plaintextTag))
+ if (context_tag.Matches(kPlaintextTag))
return HTMLTokenizer::kPLAINTEXTState;
return HTMLTokenizer::kDataState;
}
@@ -1211,8 +1211,9 @@ std::unique_ptr<HTMLPreloadScanner> HTMLDocumentParser::CreatePreloadScanner(
}
void HTMLDocumentParser::ScanAndPreload(HTMLPreloadScanner* scanner) {
- PreloadRequestStream requests =
- scanner->Scan(GetDocument()->ValidBaseElementURL(), nullptr);
+ bool seen_csp_meta_tag = false;
+ PreloadRequestStream requests = scanner->Scan(
+ GetDocument()->ValidBaseElementURL(), nullptr, seen_csp_meta_tag);
preloader_->TakeAndPreload(requests);
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.h b/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.h
index 342b24aa874..4ed141fb82b 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_document_parser.h
@@ -75,8 +75,14 @@ class CORE_EXPORT HTMLDocumentParser : public ScriptableDocumentParser,
static HTMLDocumentParser* Create(
HTMLDocument& document,
ParserSynchronizationPolicy background_parsing_policy) {
- return new HTMLDocumentParser(document, background_parsing_policy);
+ return MakeGarbageCollected<HTMLDocumentParser>(document,
+ background_parsing_policy);
}
+
+ HTMLDocumentParser(HTMLDocument&, ParserSynchronizationPolicy);
+ HTMLDocumentParser(DocumentFragment*,
+ Element* context_element,
+ ParserContentPolicy);
~HTMLDocumentParser() override;
void Trace(blink::Visitor*) override;
@@ -140,11 +146,6 @@ class CORE_EXPORT HTMLDocumentParser : public ScriptableDocumentParser,
void Append(const String&) override;
void Finish() final;
- HTMLDocumentParser(HTMLDocument&, ParserSynchronizationPolicy);
- HTMLDocumentParser(DocumentFragment*,
- Element* context_element,
- ParserContentPolicy);
-
HTMLTreeBuilder* TreeBuilder() const { return tree_builder_.Get(); }
void ForcePlaintextForTextDocument();
@@ -153,8 +154,8 @@ class CORE_EXPORT HTMLDocumentParser : public ScriptableDocumentParser,
static HTMLDocumentParser* Create(DocumentFragment* fragment,
Element* context_element,
ParserContentPolicy parser_content_policy) {
- return new HTMLDocumentParser(fragment, context_element,
- parser_content_policy);
+ return MakeGarbageCollected<HTMLDocumentParser>(fragment, context_element,
+ parser_content_policy);
}
HTMLDocumentParser(Document&,
ParserContentPolicy,
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_document_parser_loading_test.cc b/chromium/third_party/blink/renderer/core/html/parser/html_document_parser_loading_test.cc
index ccbd0f7487f..2c95e30b151 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_document_parser_loading_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_document_parser_loading_test.cc
@@ -6,7 +6,6 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
@@ -14,8 +13,6 @@
namespace blink {
-using namespace HTMLNames;
-
class HTMLDocumentParserSimTest : public SimTest {
protected:
HTMLDocumentParserSimTest() {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.cc b/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.cc
index d1ed8597a03..4e98af78265 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.cc
@@ -36,48 +36,48 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
inline bool IsRootNode(HTMLStackItem* item) {
- return item->IsDocumentFragmentNode() || item->HasTagName(htmlTag);
+ return item->IsDocumentFragmentNode() || item->HasTagName(kHTMLTag);
}
inline bool IsScopeMarker(HTMLStackItem* item) {
- return item->HasTagName(appletTag) || item->HasTagName(captionTag) ||
- item->HasTagName(marqueeTag) || item->HasTagName(objectTag) ||
- item->HasTagName(tableTag) || item->HasTagName(tdTag) ||
- item->HasTagName(thTag) || item->HasTagName(MathMLNames::miTag) ||
- item->HasTagName(MathMLNames::moTag) ||
- item->HasTagName(MathMLNames::mnTag) ||
- item->HasTagName(MathMLNames::msTag) ||
- item->HasTagName(MathMLNames::mtextTag) ||
- item->HasTagName(MathMLNames::annotation_xmlTag) ||
- item->HasTagName(SVGNames::foreignObjectTag) ||
- item->HasTagName(SVGNames::descTag) ||
- item->HasTagName(SVGNames::titleTag) ||
- item->HasTagName(templateTag) || IsRootNode(item);
+ return item->HasTagName(kAppletTag) || item->HasTagName(kCaptionTag) ||
+ item->HasTagName(kMarqueeTag) || item->HasTagName(kObjectTag) ||
+ item->HasTagName(kTableTag) || item->HasTagName(kTdTag) ||
+ item->HasTagName(kThTag) || item->HasTagName(mathml_names::kMiTag) ||
+ item->HasTagName(mathml_names::kMoTag) ||
+ item->HasTagName(mathml_names::kMnTag) ||
+ item->HasTagName(mathml_names::kMsTag) ||
+ item->HasTagName(mathml_names::kMtextTag) ||
+ item->HasTagName(mathml_names::kAnnotationXmlTag) ||
+ item->HasTagName(svg_names::kForeignObjectTag) ||
+ item->HasTagName(svg_names::kDescTag) ||
+ item->HasTagName(svg_names::kTitleTag) ||
+ item->HasTagName(kTemplateTag) || IsRootNode(item);
}
inline bool IsListItemScopeMarker(HTMLStackItem* item) {
- return IsScopeMarker(item) || item->HasTagName(olTag) ||
- item->HasTagName(ulTag);
+ return IsScopeMarker(item) || item->HasTagName(kOlTag) ||
+ item->HasTagName(kUlTag);
}
inline bool IsTableScopeMarker(HTMLStackItem* item) {
- return item->HasTagName(tableTag) || item->HasTagName(templateTag) ||
+ return item->HasTagName(kTableTag) || item->HasTagName(kTemplateTag) ||
IsRootNode(item);
}
inline bool IsTableBodyScopeMarker(HTMLStackItem* item) {
- return item->HasTagName(tbodyTag) || item->HasTagName(tfootTag) ||
- item->HasTagName(theadTag) || item->HasTagName(templateTag) ||
+ return item->HasTagName(kTbodyTag) || item->HasTagName(kTfootTag) ||
+ item->HasTagName(kTheadTag) || item->HasTagName(kTemplateTag) ||
IsRootNode(item);
}
inline bool IsTableRowScopeMarker(HTMLStackItem* item) {
- return item->HasTagName(trTag) || item->HasTagName(templateTag) ||
+ return item->HasTagName(kTrTag) || item->HasTagName(kTemplateTag) ||
IsRootNode(item);
}
@@ -88,11 +88,11 @@ inline bool IsForeignContentScopeMarker(HTMLStackItem* item) {
}
inline bool IsButtonScopeMarker(HTMLStackItem* item) {
- return IsScopeMarker(item) || item->HasTagName(buttonTag);
+ return IsScopeMarker(item) || item->HasTagName(kButtonTag);
}
inline bool IsSelectScopeMarker(HTMLStackItem* item) {
- return !item->HasTagName(optgroupTag) && !item->HasTagName(optionTag);
+ return !item->HasTagName(kOptgroupTag) && !item->HasTagName(kOptionTag);
}
} // namespace
@@ -175,7 +175,7 @@ void HTMLElementStack::PopAll() {
}
void HTMLElementStack::Pop() {
- DCHECK(!TopStackItem()->HasTagName(HTMLNames::headTag));
+ DCHECK(!TopStackItem()->HasTagName(html_names::kHeadTag));
PopCommon();
}
@@ -229,20 +229,20 @@ void HTMLElementStack::PopUntilTableRowScopeMarker() {
bool HTMLElementStack::IsMathMLTextIntegrationPoint(HTMLStackItem* item) {
if (!item->IsElementNode())
return false;
- return item->HasTagName(MathMLNames::miTag) ||
- item->HasTagName(MathMLNames::moTag) ||
- item->HasTagName(MathMLNames::mnTag) ||
- item->HasTagName(MathMLNames::msTag) ||
- item->HasTagName(MathMLNames::mtextTag);
+ return item->HasTagName(mathml_names::kMiTag) ||
+ item->HasTagName(mathml_names::kMoTag) ||
+ item->HasTagName(mathml_names::kMnTag) ||
+ item->HasTagName(mathml_names::kMsTag) ||
+ item->HasTagName(mathml_names::kMtextTag);
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#html-integration-point
bool HTMLElementStack::IsHTMLIntegrationPoint(HTMLStackItem* item) {
if (!item->IsElementNode())
return false;
- if (item->HasTagName(MathMLNames::annotation_xmlTag)) {
+ if (item->HasTagName(mathml_names::kAnnotationXmlTag)) {
Attribute* encoding_attr =
- item->GetAttributeItem(MathMLNames::encodingAttr);
+ item->GetAttributeItem(mathml_names::kEncodingAttr);
if (encoding_attr) {
const String& encoding = encoding_attr->Value();
return DeprecatedEqualIgnoringCase(encoding, "text/html") ||
@@ -250,9 +250,9 @@ bool HTMLElementStack::IsHTMLIntegrationPoint(HTMLStackItem* item) {
}
return false;
}
- return item->HasTagName(SVGNames::foreignObjectTag) ||
- item->HasTagName(SVGNames::descTag) ||
- item->HasTagName(SVGNames::titleTag);
+ return item->HasTagName(svg_names::kForeignObjectTag) ||
+ item->HasTagName(svg_names::kDescTag) ||
+ item->HasTagName(svg_names::kTitleTag);
}
void HTMLElementStack::PopUntilForeignContentScopeMarker() {
@@ -266,7 +266,7 @@ void HTMLElementStack::PushRootNode(HTMLStackItem* root_item) {
}
void HTMLElementStack::PushHTMLHtmlElement(HTMLStackItem* item) {
- DCHECK(item->HasTagName(htmlTag));
+ DCHECK(item->HasTagName(kHTMLTag));
PushRootNodeCommon(item);
}
@@ -278,23 +278,23 @@ void HTMLElementStack::PushRootNodeCommon(HTMLStackItem* root_item) {
}
void HTMLElementStack::PushHTMLHeadElement(HTMLStackItem* item) {
- DCHECK(item->HasTagName(HTMLNames::headTag));
+ DCHECK(item->HasTagName(html_names::kHeadTag));
DCHECK(!head_element_);
head_element_ = item->GetElement();
PushCommon(item);
}
void HTMLElementStack::PushHTMLBodyElement(HTMLStackItem* item) {
- DCHECK(item->HasTagName(HTMLNames::bodyTag));
+ DCHECK(item->HasTagName(html_names::kBodyTag));
DCHECK(!body_element_);
body_element_ = item->GetElement();
PushCommon(item);
}
void HTMLElementStack::Push(HTMLStackItem* item) {
- DCHECK(!item->HasTagName(htmlTag));
- DCHECK(!item->HasTagName(headTag));
- DCHECK(!item->HasTagName(bodyTag));
+ DCHECK(!item->HasTagName(kHTMLTag));
+ DCHECK(!item->HasTagName(kHeadTag));
+ DCHECK(!item->HasTagName(kBodyTag));
DCHECK(root_node_);
PushCommon(item);
}
@@ -304,9 +304,9 @@ void HTMLElementStack::InsertAbove(HTMLStackItem* item,
DCHECK(item);
DCHECK(record_below);
DCHECK(top_);
- DCHECK(!item->HasTagName(htmlTag));
- DCHECK(!item->HasTagName(headTag));
- DCHECK(!item->HasTagName(bodyTag));
+ DCHECK(!item->HasTagName(kHTMLTag));
+ DCHECK(!item->HasTagName(kHeadTag));
+ DCHECK(!item->HasTagName(kBodyTag));
DCHECK(root_node_);
if (record_below == top_) {
Push(item);
@@ -319,7 +319,8 @@ void HTMLElementStack::InsertAbove(HTMLStackItem* item,
continue;
stack_depth_++;
- record_above->SetNext(new ElementRecord(item, record_above->ReleaseNext()));
+ record_above->SetNext(
+ MakeGarbageCollected<ElementRecord>(item, record_above->ReleaseNext()));
record_above->Next()->GetElement()->BeginParsingChildren();
return;
}
@@ -464,7 +465,7 @@ bool HTMLElementStack::InSelectScope(const QualifiedName& tag_name) const {
}
bool HTMLElementStack::HasTemplateInHTMLScope() const {
- return InScopeCommon<IsRootNode>(top_.Get(), templateTag.LocalName());
+ return InScopeCommon<IsRootNode>(top_.Get(), kTemplateTag.LocalName());
}
Element* HTMLElementStack::HtmlElement() const {
@@ -491,13 +492,13 @@ void HTMLElementStack::PushCommon(HTMLStackItem* item) {
DCHECK(root_node_);
stack_depth_++;
- top_ = new ElementRecord(item, top_.Release());
+ top_ = MakeGarbageCollected<ElementRecord>(item, top_.Release());
}
void HTMLElementStack::PopCommon() {
- DCHECK(!TopStackItem()->HasTagName(htmlTag));
- DCHECK(!TopStackItem()->HasTagName(headTag) || !head_element_);
- DCHECK(!TopStackItem()->HasTagName(bodyTag) || !body_element_);
+ DCHECK(!TopStackItem()->HasTagName(kHTMLTag));
+ DCHECK(!TopStackItem()->HasTagName(kHeadTag) || !head_element_);
+ DCHECK(!TopStackItem()->HasTagName(kBodyTag) || !body_element_);
Top()->FinishParsingChildren();
top_ = top_->ReleaseNext();
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.h b/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.h
index 86732f502a4..cdcfeea06c6 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_element_stack.h
@@ -49,6 +49,8 @@ class HTMLElementStack {
class ElementRecord final : public GarbageCollected<ElementRecord> {
public:
+ ElementRecord(HTMLStackItem*, ElementRecord*);
+
Element* GetElement() const { return item_->GetElement(); }
ContainerNode* GetNode() const { return item_->GetNode(); }
const AtomicString& NamespaceURI() const { return item_->NamespaceURI(); }
@@ -64,8 +66,6 @@ class HTMLElementStack {
private:
friend class HTMLElementStack;
- ElementRecord(HTMLStackItem*, ElementRecord*);
-
ElementRecord* ReleaseNext() { return next_.Release(); }
void SetNext(ElementRecord* next) { next_ = next; }
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_meta_charset_parser.cc b/chromium/third_party/blink/renderer/core/html/parser/html_meta_charset_parser.cc
index c6386b81d6d..be893b42279 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_meta_charset_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_meta_charset_parser.cc
@@ -34,7 +34,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HTMLMetaCharsetParser::HTMLMetaCharsetParser()
: tokenizer_(HTMLTokenizer::Create(HTMLParserOptions(nullptr))),
@@ -94,22 +94,22 @@ bool HTMLMetaCharsetParser::CheckForMetaCharset(const char* data,
AttemptStaticStringCreation(token_.GetName(), kLikely8Bit);
if (!end) {
tokenizer_->UpdateStateFor(tag_name);
- if (ThreadSafeMatch(tag_name, metaTag) && ProcessMeta()) {
+ if (ThreadSafeMatch(tag_name, kMetaTag) && ProcessMeta()) {
done_checking_ = true;
return true;
}
}
- if (!ThreadSafeMatch(tag_name, scriptTag) &&
- !ThreadSafeMatch(tag_name, noscriptTag) &&
- !ThreadSafeMatch(tag_name, styleTag) &&
- !ThreadSafeMatch(tag_name, linkTag) &&
- !ThreadSafeMatch(tag_name, metaTag) &&
- !ThreadSafeMatch(tag_name, objectTag) &&
- !ThreadSafeMatch(tag_name, titleTag) &&
- !ThreadSafeMatch(tag_name, baseTag) &&
- (end || !ThreadSafeMatch(tag_name, htmlTag)) &&
- (end || !ThreadSafeMatch(tag_name, headTag))) {
+ if (!ThreadSafeMatch(tag_name, kScriptTag) &&
+ !ThreadSafeMatch(tag_name, kNoscriptTag) &&
+ !ThreadSafeMatch(tag_name, kStyleTag) &&
+ !ThreadSafeMatch(tag_name, kLinkTag) &&
+ !ThreadSafeMatch(tag_name, kMetaTag) &&
+ !ThreadSafeMatch(tag_name, kObjectTag) &&
+ !ThreadSafeMatch(tag_name, kTitleTag) &&
+ !ThreadSafeMatch(tag_name, kBaseTag) &&
+ (end || !ThreadSafeMatch(tag_name, kHTMLTag)) &&
+ (end || !ThreadSafeMatch(tag_name, kHeadTag))) {
in_head_section_ = false;
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.cc b/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.cc
index 0a09f4c4333..4200c56f7d1 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.cc
@@ -36,7 +36,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
template <typename CharType>
static String StripLeadingAndTrailingHTMLSpaces(String string,
@@ -380,14 +380,14 @@ WTF::TextEncoding EncodingFromMetaAttributes(
const String& attribute_name = html_attribute.first;
const AtomicString& attribute_value = AtomicString(html_attribute.second);
- if (ThreadSafeMatch(attribute_name, http_equivAttr)) {
+ if (ThreadSafeMatch(attribute_name, kHttpEquivAttr)) {
if (DeprecatedEqualIgnoringCase(attribute_value, "content-type"))
got_pragma = true;
- } else if (ThreadSafeMatch(attribute_name, charsetAttr)) {
+ } else if (ThreadSafeMatch(attribute_name, kCharsetAttr)) {
has_charset = true;
charset = attribute_value;
mode = MetaAttribute::kCharset;
- } else if (!has_charset && ThreadSafeMatch(attribute_name, contentAttr)) {
+ } else if (!has_charset && ThreadSafeMatch(attribute_name, kContentAttr)) {
charset = ExtractCharset(attribute_value);
if (charset.length())
mode = MetaAttribute::kPragma;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.h b/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.h
index ac928bb675f..1048d1572e0 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_parser_idioms.h
@@ -103,6 +103,11 @@ inline bool IsComma(CharType character) {
}
template <typename CharType>
+inline bool IsColon(CharType character) {
+ return character == ':';
+}
+
+template <typename CharType>
inline bool IsHTMLSpaceOrComma(CharType character) {
return IsComma(character) || IsHTMLSpace(character);
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.cc b/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.cc
index a05859b5f4d..19c929216af 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.cc
@@ -117,10 +117,7 @@ void HTMLParserScheduler::Detach() {
inline bool HTMLParserScheduler::ShouldYield(
const SpeculationsPumpSession& session,
bool starting_script) const {
- if (Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->ShouldYieldForHighPriorityWork())
+ if (ThreadScheduler::Current()->ShouldYieldForHighPriorityWork())
return true;
if (session.ElapsedTime() > parser_time_limit_)
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h b/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h
index 12f950acb75..f555db1e1c1 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h
@@ -32,7 +32,7 @@
#include "base/memory/scoped_refptr.h"
#include "base/single_thread_task_runner.h"
#include "third_party/blink/renderer/core/html/parser/nesting_level_incrementer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -69,8 +69,12 @@ class HTMLParserScheduler final
static HTMLParserScheduler* Create(
HTMLDocumentParser* parser,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) {
- return new HTMLParserScheduler(parser, std::move(loading_task_runner));
+ return MakeGarbageCollected<HTMLParserScheduler>(
+ parser, std::move(loading_task_runner));
}
+
+ HTMLParserScheduler(HTMLDocumentParser*,
+ scoped_refptr<base::SingleThreadTaskRunner>);
~HTMLParserScheduler();
bool IsScheduledForUnpause() const;
@@ -94,9 +98,6 @@ class HTMLParserScheduler final
void Trace(blink::Visitor*);
private:
- HTMLParserScheduler(HTMLDocumentParser*,
- scoped_refptr<base::SingleThreadTaskRunner>);
-
bool ShouldYield(const SpeculationsPumpSession&, bool starting_script) const;
void ContinueParsing();
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc
index 8ff868d5af2..0c9a40302f3 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc
@@ -29,10 +29,14 @@
#include <memory>
#include "base/optional.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
#include "third_party/blink/renderer/core/css/media_list.h"
#include "third_party/blink/renderer/core/css/media_query_evaluator.h"
#include "third_party/blink/renderer/core/css/media_values_cached.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/css/parser/sizes_attribute_parser.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -62,7 +66,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool Match(const StringImpl* impl, const QualifiedName& q_name) {
return impl == q_name.LocalName().Impl();
@@ -94,16 +98,16 @@ static const StringImpl* TagImplFor(const String& tag_name) {
static String InitiatorFor(const StringImpl* tag_impl) {
DCHECK(tag_impl);
- if (Match(tag_impl, imgTag))
- return imgTag.LocalName();
- if (Match(tag_impl, inputTag))
- return inputTag.LocalName();
- if (Match(tag_impl, linkTag))
- return linkTag.LocalName();
- if (Match(tag_impl, scriptTag))
- return scriptTag.LocalName();
- if (Match(tag_impl, videoTag))
- return videoTag.LocalName();
+ if (Match(tag_impl, kImgTag))
+ return kImgTag.LocalName();
+ if (Match(tag_impl, kInputTag))
+ return kInputTag.LocalName();
+ if (Match(tag_impl, kLinkTag))
+ return kLinkTag.LocalName();
+ if (Match(tag_impl, kScriptTag))
+ return kScriptTag.LocalName();
+ if (Match(tag_impl, kVideoTag))
+ return kVideoTag.LocalName();
NOTREACHED();
return g_empty_string;
}
@@ -125,6 +129,28 @@ static bool IsDimensionSmallAndAbsoluteForLazyLoad(
dimension.IsAbsolute() && dimension.Value() <= kMinDimensionToLazyLoad;
}
+static bool IsInlineStyleDimensionsSmall(const String& style_value,
+ bool strict_mode) {
+ // Minimum height or width of the image to start lazyloading.
+ const unsigned kMinDimensionToLazyLoad = 10;
+ CSSParserMode mode = strict_mode ? kHTMLStandardMode : kHTMLQuirksMode;
+ const ImmutableCSSPropertyValueSet* property_set =
+ CSSParser::ParseInlineStyleDeclaration(
+ style_value, mode, SecureContextMode::kInsecureContext);
+ const CSSValue* height = property_set->GetPropertyCSSValue(CSSPropertyHeight);
+ const CSSValue* width = property_set->GetPropertyCSSValue(CSSPropertyWidth);
+
+ if (!height || !height->IsPrimitiveValue() || !width ||
+ !width->IsPrimitiveValue())
+ return false;
+ const CSSPrimitiveValue* width_prim = ToCSSPrimitiveValue(width);
+ const CSSPrimitiveValue* height_prim = ToCSSPrimitiveValue(height);
+ return height_prim->IsPx() &&
+ (height_prim->GetDoubleValue() <= kMinDimensionToLazyLoad) &&
+ width_prim->IsPx() &&
+ (width_prim->GetDoubleValue() <= kMinDimensionToLazyLoad);
+}
+
class TokenPreloadScanner::StartTagScanner {
STACK_ALLOCATED();
@@ -150,19 +176,20 @@ class TokenPreloadScanner::StartTagScanner {
importance_mode_set_(false),
media_values_(media_values),
referrer_policy_set_(false),
- referrer_policy_(kReferrerPolicyDefault),
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
integrity_attr_set_(false),
integrity_features_(features),
lazyload_attr_set_to_off_(false),
width_attr_small_absolute_(false),
height_attr_small_absolute_(false),
+ inline_style_dimensions_small_(false),
scanner_type_(scanner_type) {
- if (Match(tag_impl_, imgTag) || Match(tag_impl_, sourceTag)) {
+ if (Match(tag_impl_, kImgTag) || Match(tag_impl_, kSourceTag)) {
source_size_ = SizesAttributeParser(media_values_, String()).length();
return;
}
- if (!Match(tag_impl_, inputTag) && !Match(tag_impl_, linkTag) &&
- !Match(tag_impl_, scriptTag) && !Match(tag_impl_, videoTag))
+ if (!Match(tag_impl_, kInputTag) && !Match(tag_impl_, kLinkTag) &&
+ !Match(tag_impl_, kScriptTag) && !Match(tag_impl_, kVideoTag))
tag_impl_ = nullptr;
}
@@ -191,14 +218,14 @@ class TokenPreloadScanner::StartTagScanner {
}
void PostProcessAfterAttributes() {
- if (Match(tag_impl_, imgTag) ||
+ if (Match(tag_impl_, kImgTag) ||
(link_is_preload_ && as_attribute_value_ == "image" &&
RuntimeEnabledFeatures::PreloadImageSrcSetEnabled()))
SetUrlFromImageAttributes();
}
void HandlePictureSourceURL(PictureData& picture_data) {
- if (Match(tag_impl_, sourceTag) && matched_ &&
+ if (Match(tag_impl_, kSourceTag) && matched_ &&
picture_data.source_url.IsEmpty()) {
// Must create an IsolatedCopy() since the srcset attribute value will get
// sent back to the main thread between when we set this, and when we
@@ -210,7 +237,8 @@ class TokenPreloadScanner::StartTagScanner {
picture_data.source_size_set = source_size_set_;
picture_data.source_size = source_size_;
picture_data.picked = true;
- } else if (Match(tag_impl_, imgTag) && !picture_data.source_url.IsEmpty()) {
+ } else if (Match(tag_impl_, kImgTag) &&
+ !picture_data.source_url.IsEmpty()) {
SetUrlToLoad(picture_data.source_url, kAllowURLReplacement);
}
}
@@ -220,7 +248,7 @@ class TokenPreloadScanner::StartTagScanner {
const SegmentedString& source,
const ClientHintsPreferences& client_hints_preferences,
const PictureData& picture_data,
- const ReferrerPolicy document_referrer_policy) {
+ const CachedDocumentParameters& document_parameters) {
PreloadRequest::RequestType request_type =
PreloadRequest::kRequestTypePreload;
base::Optional<ResourceType> type;
@@ -265,9 +293,10 @@ class TokenPreloadScanner::StartTagScanner {
// The element's 'referrerpolicy' attribute (if present) takes precedence
// over the document's referrer policy.
- ReferrerPolicy referrer_policy =
- (referrer_policy_ != kReferrerPolicyDefault) ? referrer_policy_
- : document_referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy =
+ (referrer_policy_ != network::mojom::ReferrerPolicy::kDefault)
+ ? referrer_policy_
+ : document_parameters.referrer_policy;
auto request = PreloadRequest::CreateIfNeeded(
InitiatorFor(tag_impl_), position, url_to_load_, predicted_base_url,
type.value(), referrer_policy, PreloadRequest::kDocumentIsReferrer,
@@ -275,9 +304,9 @@ class TokenPreloadScanner::StartTagScanner {
if (!request)
return nullptr;
- if ((Match(tag_impl_, scriptTag) && type_attribute_value_ == "module") ||
+ if ((Match(tag_impl_, kScriptTag) && type_attribute_value_ == "module") ||
IsLinkRelModulePreload()) {
- request->SetScriptType(ScriptType::kModule);
+ request->SetScriptType(mojom::ScriptType::kModule);
}
request->SetCrossOrigin(cross_origin_);
@@ -286,14 +315,18 @@ class TokenPreloadScanner::StartTagScanner {
request->SetCharset(Charset());
request->SetDefer(defer_);
- if (lazyload_attr_set_to_off_ ||
- (width_attr_small_absolute_ && height_attr_small_absolute_)) {
+ // If the 'lazyload' feature policy is enforced, the attribute value "off"
+ // for the 'lazyload' attribute is considered as 'auto'.
+ if ((lazyload_attr_set_to_off_ &&
+ !document_parameters.lazyload_policy_enforced) ||
+ (width_attr_small_absolute_ && height_attr_small_absolute_) ||
+ inline_style_dimensions_small_) {
request->SetIsLazyloadImageDisabled(true);
}
// The only link tags that should keep the integrity metadata are
// stylesheets until crbug.com/677022 is resolved.
- if (link_is_style_sheet_ || !Match(tag_impl_, linkTag))
+ if (link_is_style_sheet_ || !Match(tag_impl_, kLinkTag))
request->SetIntegrityMetadata(integrity_metadata_);
if (scanner_type_ == ScannerType::kInsertion)
@@ -307,28 +340,28 @@ class TokenPreloadScanner::StartTagScanner {
void ProcessScriptAttribute(const NameType& attribute_name,
const String& attribute_value) {
// FIXME - Don't set crossorigin multiple times.
- if (Match(attribute_name, srcAttr)) {
+ if (Match(attribute_name, kSrcAttr)) {
SetUrlToLoad(attribute_value, kDisallowURLReplacement);
- } else if (Match(attribute_name, crossoriginAttr)) {
+ } else if (Match(attribute_name, kCrossoriginAttr)) {
SetCrossOrigin(attribute_value);
- } else if (Match(attribute_name, nonceAttr)) {
+ } else if (Match(attribute_name, kNonceAttr)) {
SetNonce(attribute_value);
- } else if (Match(attribute_name, asyncAttr)) {
+ } else if (Match(attribute_name, kAsyncAttr)) {
SetDefer(FetchParameters::kLazyLoad);
- } else if (Match(attribute_name, deferAttr)) {
+ } else if (Match(attribute_name, kDeferAttr)) {
SetDefer(FetchParameters::kLazyLoad);
- } else if (!integrity_attr_set_ && Match(attribute_name, integrityAttr)) {
+ } else if (!integrity_attr_set_ && Match(attribute_name, kIntegrityAttr)) {
integrity_attr_set_ = true;
SubresourceIntegrity::ParseIntegrityAttribute(
attribute_value, integrity_features_, integrity_metadata_);
- } else if (Match(attribute_name, typeAttr)) {
+ } else if (Match(attribute_name, kTypeAttr)) {
type_attribute_value_ = attribute_value;
- } else if (Match(attribute_name, languageAttr)) {
+ } else if (Match(attribute_name, kLanguageAttr)) {
language_attribute_value_ = attribute_value;
- } else if (Match(attribute_name, nomoduleAttr)) {
+ } else if (Match(attribute_name, kNomoduleAttr)) {
nomodule_attribute_value_ = true;
} else if (!referrer_policy_set_ &&
- Match(attribute_name, referrerpolicyAttr) &&
+ Match(attribute_name, kReferrerpolicyAttr) &&
!attribute_value.IsNull()) {
SetReferrerPolicy(attribute_value,
kDoNotSupportReferrerPolicyLegacyKeywords);
@@ -338,37 +371,43 @@ class TokenPreloadScanner::StartTagScanner {
template <typename NameType>
void ProcessImgAttribute(const NameType& attribute_name,
const String& attribute_value) {
- if (Match(attribute_name, srcAttr) && img_src_url_.IsNull()) {
+ if (Match(attribute_name, kSrcAttr) && img_src_url_.IsNull()) {
img_src_url_ = attribute_value;
- } else if (Match(attribute_name, crossoriginAttr)) {
+ } else if (Match(attribute_name, kCrossoriginAttr)) {
SetCrossOrigin(attribute_value);
- } else if (Match(attribute_name, srcsetAttr) &&
+ } else if (Match(attribute_name, kSrcsetAttr) &&
srcset_attribute_value_.IsNull()) {
srcset_attribute_value_ = attribute_value;
- } else if (Match(attribute_name, sizesAttr) && !source_size_set_) {
+ } else if (Match(attribute_name, kSizesAttr) && !source_size_set_) {
ParseSourceSize(attribute_value);
} else if (!referrer_policy_set_ &&
- Match(attribute_name, referrerpolicyAttr) &&
+ Match(attribute_name, kReferrerpolicyAttr) &&
!attribute_value.IsNull()) {
SetReferrerPolicy(attribute_value, kSupportReferrerPolicyLegacyKeywords);
- } else if (!importance_mode_set_ && Match(attribute_name, importanceAttr) &&
+ } else if (!importance_mode_set_ &&
+ Match(attribute_name, kImportanceAttr) &&
RuntimeEnabledFeatures::PriorityHintsEnabled()) {
SetImportance(attribute_value);
} else if (!lazyload_attr_set_to_off_ &&
- Match(attribute_name, lazyloadAttr) &&
+ Match(attribute_name, kLazyloadAttr) &&
RuntimeEnabledFeatures::LazyImageLoadingEnabled() &&
EqualIgnoringASCIICase(attribute_value, "off")) {
lazyload_attr_set_to_off_ = true;
} else if (!width_attr_small_absolute_ &&
- Match(attribute_name, widthAttr) &&
+ Match(attribute_name, kWidthAttr) &&
RuntimeEnabledFeatures::LazyImageLoadingEnabled()) {
width_attr_small_absolute_ =
IsDimensionSmallAndAbsoluteForLazyLoad(attribute_value);
} else if (!height_attr_small_absolute_ &&
- Match(attribute_name, heightAttr) &&
+ Match(attribute_name, kHeightAttr) &&
RuntimeEnabledFeatures::LazyImageLoadingEnabled()) {
height_attr_small_absolute_ =
IsDimensionSmallAndAbsoluteForLazyLoad(attribute_value);
+ } else if (!inline_style_dimensions_small_ &&
+ Match(attribute_name, kStyleAttr) &&
+ RuntimeEnabledFeatures::LazyImageLoadingEnabled()) {
+ inline_style_dimensions_small_ = IsInlineStyleDimensionsSmall(
+ attribute_value, media_values_->StrictMode());
}
}
@@ -386,11 +425,11 @@ class TokenPreloadScanner::StartTagScanner {
void ProcessLinkAttribute(const NameType& attribute_name,
const String& attribute_value) {
// FIXME - Don't set rel/media/crossorigin multiple times.
- if (Match(attribute_name, hrefAttr)) {
+ if (Match(attribute_name, kHrefAttr)) {
SetUrlToLoad(attribute_value, kDisallowURLReplacement);
// Used in SetUrlFromImageAttributes() when as=image.
img_src_url_ = attribute_value;
- } else if (Match(attribute_name, relAttr)) {
+ } else if (Match(attribute_name, kRelAttr)) {
LinkRelAttribute rel(attribute_value);
link_is_style_sheet_ = rel.IsStyleSheet() && !rel.IsAlternate() &&
rel.GetIconType() == kInvalidIcon &&
@@ -399,31 +438,32 @@ class TokenPreloadScanner::StartTagScanner {
link_is_preload_ = rel.IsLinkPreload();
link_is_modulepreload_ = rel.IsModulePreload();
link_is_import_ = rel.IsImport();
- } else if (Match(attribute_name, mediaAttr)) {
+ } else if (Match(attribute_name, kMediaAttr)) {
matched_ &= MediaAttributeMatches(*media_values_, attribute_value);
- } else if (Match(attribute_name, crossoriginAttr)) {
+ } else if (Match(attribute_name, kCrossoriginAttr)) {
SetCrossOrigin(attribute_value);
- } else if (Match(attribute_name, nonceAttr)) {
+ } else if (Match(attribute_name, kNonceAttr)) {
SetNonce(attribute_value);
- } else if (Match(attribute_name, asAttr)) {
+ } else if (Match(attribute_name, kAsAttr)) {
as_attribute_value_ = attribute_value.DeprecatedLower();
- } else if (Match(attribute_name, typeAttr)) {
+ } else if (Match(attribute_name, kTypeAttr)) {
type_attribute_value_ = attribute_value;
} else if (!referrer_policy_set_ &&
- Match(attribute_name, referrerpolicyAttr) &&
+ Match(attribute_name, kReferrerpolicyAttr) &&
!attribute_value.IsNull()) {
SetReferrerPolicy(attribute_value,
kDoNotSupportReferrerPolicyLegacyKeywords);
- } else if (!integrity_attr_set_ && Match(attribute_name, integrityAttr)) {
+ } else if (!integrity_attr_set_ && Match(attribute_name, kIntegrityAttr)) {
integrity_attr_set_ = true;
SubresourceIntegrity::ParseIntegrityAttribute(
attribute_value, integrity_features_, integrity_metadata_);
- } else if (Match(attribute_name, srcsetAttr) &&
+ } else if (Match(attribute_name, kImagesrcsetAttr) &&
srcset_attribute_value_.IsNull()) {
srcset_attribute_value_ = attribute_value;
- } else if (Match(attribute_name, imgsizesAttr) && !source_size_set_) {
+ } else if (Match(attribute_name, kImagesizesAttr) && !source_size_set_) {
ParseSourceSize(attribute_value);
- } else if (!importance_mode_set_ && Match(attribute_name, importanceAttr) &&
+ } else if (!importance_mode_set_ &&
+ Match(attribute_name, kImportanceAttr) &&
RuntimeEnabledFeatures::PriorityHintsEnabled()) {
SetImportance(attribute_value);
}
@@ -433,33 +473,33 @@ class TokenPreloadScanner::StartTagScanner {
void ProcessInputAttribute(const NameType& attribute_name,
const String& attribute_value) {
// FIXME - Don't set type multiple times.
- if (Match(attribute_name, srcAttr)) {
+ if (Match(attribute_name, kSrcAttr)) {
SetUrlToLoad(attribute_value, kDisallowURLReplacement);
- } else if (Match(attribute_name, typeAttr)) {
- input_is_image_ =
- DeprecatedEqualIgnoringCase(attribute_value, InputTypeNames::image);
+ } else if (Match(attribute_name, kTypeAttr)) {
+ input_is_image_ = DeprecatedEqualIgnoringCase(attribute_value,
+ input_type_names::kImage);
}
}
template <typename NameType>
void ProcessSourceAttribute(const NameType& attribute_name,
const String& attribute_value) {
- if (Match(attribute_name, srcsetAttr) &&
+ if (Match(attribute_name, kSrcsetAttr) &&
srcset_image_candidate_.IsEmpty()) {
srcset_attribute_value_ = attribute_value;
srcset_image_candidate_ = BestFitSourceForSrcsetAttribute(
media_values_->DevicePixelRatio(), source_size_, attribute_value);
- } else if (Match(attribute_name, sizesAttr) && !source_size_set_) {
+ } else if (Match(attribute_name, kSizesAttr) && !source_size_set_) {
ParseSourceSize(attribute_value);
if (!srcset_image_candidate_.IsEmpty()) {
srcset_image_candidate_ = BestFitSourceForSrcsetAttribute(
media_values_->DevicePixelRatio(), source_size_,
srcset_attribute_value_);
}
- } else if (Match(attribute_name, mediaAttr)) {
+ } else if (Match(attribute_name, kMediaAttr)) {
// FIXME - Don't match media multiple times.
matched_ &= MediaAttributeMatches(*media_values_, attribute_value);
- } else if (Match(attribute_name, typeAttr)) {
+ } else if (Match(attribute_name, kTypeAttr)) {
matched_ &= MIMETypeRegistry::IsSupportedImagePrefixedMIMEType(
ContentType(attribute_value).GetType());
}
@@ -468,29 +508,29 @@ class TokenPreloadScanner::StartTagScanner {
template <typename NameType>
void ProcessVideoAttribute(const NameType& attribute_name,
const String& attribute_value) {
- if (Match(attribute_name, posterAttr))
+ if (Match(attribute_name, kPosterAttr))
SetUrlToLoad(attribute_value, kDisallowURLReplacement);
- else if (Match(attribute_name, crossoriginAttr))
+ else if (Match(attribute_name, kCrossoriginAttr))
SetCrossOrigin(attribute_value);
}
template <typename NameType>
void ProcessAttribute(const NameType& attribute_name,
const String& attribute_value) {
- if (Match(attribute_name, charsetAttr))
+ if (Match(attribute_name, kCharsetAttr))
charset_ = attribute_value;
- if (Match(tag_impl_, scriptTag))
+ if (Match(tag_impl_, kScriptTag))
ProcessScriptAttribute(attribute_name, attribute_value);
- else if (Match(tag_impl_, imgTag))
+ else if (Match(tag_impl_, kImgTag))
ProcessImgAttribute(attribute_name, attribute_value);
- else if (Match(tag_impl_, linkTag))
+ else if (Match(tag_impl_, kLinkTag))
ProcessLinkAttribute(attribute_name, attribute_value);
- else if (Match(tag_impl_, inputTag))
+ else if (Match(tag_impl_, kInputTag))
ProcessInputAttribute(attribute_name, attribute_value);
- else if (Match(tag_impl_, sourceTag))
+ else if (Match(tag_impl_, kSourceTag))
ProcessSourceAttribute(attribute_name, attribute_value);
- else if (Match(tag_impl_, videoTag))
+ else if (Match(tag_impl_, kVideoTag))
ProcessVideoAttribute(attribute_name, attribute_value);
}
@@ -508,7 +548,7 @@ class TokenPreloadScanner::StartTagScanner {
const String& Charset() const {
// FIXME: Its not clear that this if is needed, the loader probably ignores
// charset for image requests anyway.
- if (Match(tag_impl_, imgTag) || Match(tag_impl_, videoTag))
+ if (Match(tag_impl_, kImgTag) || Match(tag_impl_, kVideoTag))
return g_empty_string;
return charset_;
}
@@ -519,34 +559,33 @@ class TokenPreloadScanner::StartTagScanner {
}
ResourceType GetResourceType() const {
- if (Match(tag_impl_, scriptTag)) {
+ if (Match(tag_impl_, kScriptTag))
return ResourceType::kScript;
- } else if (Match(tag_impl_, imgTag) || Match(tag_impl_, videoTag) ||
- (Match(tag_impl_, inputTag) && input_is_image_)) {
+ if (Match(tag_impl_, kImgTag) || Match(tag_impl_, kVideoTag) ||
+ (Match(tag_impl_, kInputTag) && input_is_image_))
return ResourceType::kImage;
- } else if (Match(tag_impl_, linkTag) && link_is_style_sheet_) {
+ if (Match(tag_impl_, kLinkTag) && link_is_style_sheet_)
return ResourceType::kCSSStyleSheet;
- } else if (link_is_preconnect_) {
+ if (link_is_preconnect_)
return ResourceType::kRaw;
- } else if (Match(tag_impl_, linkTag) && link_is_import_) {
+ if (Match(tag_impl_, kLinkTag) && link_is_import_)
return ResourceType::kImportResource;
- }
NOTREACHED();
return ResourceType::kRaw;
}
bool ShouldPreconnect() const {
- return Match(tag_impl_, linkTag) && link_is_preconnect_ &&
+ return Match(tag_impl_, kLinkTag) && link_is_preconnect_ &&
!url_to_load_.IsEmpty();
}
bool IsLinkRelPreload() const {
- return Match(tag_impl_, linkTag) && link_is_preload_ &&
+ return Match(tag_impl_, kLinkTag) && link_is_preload_ &&
!url_to_load_.IsEmpty();
}
bool IsLinkRelModulePreload() const {
- return Match(tag_impl_, linkTag) && link_is_modulepreload_ &&
+ return Match(tag_impl_, kLinkTag) && link_is_modulepreload_ &&
!url_to_load_.IsEmpty();
}
@@ -583,12 +622,12 @@ class TokenPreloadScanner::StartTagScanner {
return false;
if (!matched_)
return false;
- if (Match(tag_impl_, linkTag))
+ if (Match(tag_impl_, kLinkTag))
return ShouldPreloadLink(type);
- if (Match(tag_impl_, inputTag) && !input_is_image_)
+ if (Match(tag_impl_, kInputTag) && !input_is_image_)
return false;
- if (Match(tag_impl_, scriptTag)) {
- ScriptType script_type = ScriptType::kClassic;
+ if (Match(tag_impl_, kScriptTag)) {
+ mojom::ScriptType script_type = mojom::ScriptType::kClassic;
if (!ScriptLoader::IsValidScriptTypeAndLanguage(
type_attribute_value_, language_attribute_value_,
ScriptLoader::kAllowLegacyTypeInTypeAttribute, script_type)) {
@@ -658,13 +697,14 @@ class TokenPreloadScanner::StartTagScanner {
String nonce_;
Member<MediaValuesCached> media_values_;
bool referrer_policy_set_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
bool integrity_attr_set_;
IntegrityMetadataSet integrity_metadata_;
SubresourceIntegrity::IntegrityFeatures integrity_features_;
bool lazyload_attr_set_to_off_;
bool width_attr_small_absolute_;
bool height_attr_small_absolute_;
+ bool inline_style_dimensions_small_;
TokenPreloadScanner::ScannerType scanner_type_;
};
@@ -755,7 +795,8 @@ static void HandleMetaViewport(
static void HandleMetaReferrer(const String& attribute_value,
CachedDocumentParameters* document_parameters,
CSSPreloadScanner* css_scanner) {
- ReferrerPolicy meta_referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy meta_referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
if (!attribute_value.IsEmpty() && !attribute_value.IsNull() &&
SecurityPolicy::ReferrerPolicyFromString(
attribute_value, kSupportReferrerPolicyLegacyKeywords,
@@ -773,13 +814,13 @@ static void HandleMetaNameAttribute(
CSSPreloadScanner* css_scanner,
ViewportDescriptionWrapper* viewport) {
const typename Token::Attribute* name_attribute =
- token.GetAttributeItem(nameAttr);
+ token.GetAttributeItem(kNameAttr);
if (!name_attribute)
return;
String name_attribute_value(name_attribute->Value());
const typename Token::Attribute* content_attribute =
- token.GetAttributeItem(contentAttr);
+ token.GetAttributeItem(kContentAttr);
if (!content_attribute)
return;
@@ -815,22 +856,22 @@ void TokenPreloadScanner::ScanCommon(const Token& token,
}
case HTMLToken::kEndTag: {
const StringImpl* tag_impl = TagImplFor(token.Data());
- if (Match(tag_impl, templateTag)) {
+ if (Match(tag_impl, kTemplateTag)) {
if (template_count_)
--template_count_;
return;
}
- if (Match(tag_impl, styleTag)) {
+ if (Match(tag_impl, kStyleTag)) {
if (in_style_)
css_scanner_.Reset();
in_style_ = false;
return;
}
- if (Match(tag_impl, scriptTag)) {
+ if (Match(tag_impl, kScriptTag)) {
in_script_ = false;
return;
}
- if (Match(tag_impl, pictureTag)) {
+ if (Match(tag_impl, kPictureTag)) {
in_picture_ = false;
picture_data_.picked = false;
}
@@ -840,29 +881,29 @@ void TokenPreloadScanner::ScanCommon(const Token& token,
if (template_count_)
return;
const StringImpl* tag_impl = TagImplFor(token.Data());
- if (Match(tag_impl, templateTag)) {
+ if (Match(tag_impl, kTemplateTag)) {
++template_count_;
return;
}
- if (Match(tag_impl, styleTag)) {
+ if (Match(tag_impl, kStyleTag)) {
in_style_ = true;
return;
}
// Don't early return, because the StartTagScanner needs to look at these
// too.
- if (Match(tag_impl, scriptTag)) {
+ if (Match(tag_impl, kScriptTag)) {
in_script_ = true;
}
- if (Match(tag_impl, baseTag)) {
+ if (Match(tag_impl, kBaseTag)) {
// The first <base> element is the one that wins.
if (!predicted_base_element_url_.IsEmpty())
return;
UpdatePredictedBaseURL(token);
return;
}
- if (Match(tag_impl, metaTag)) {
+ if (Match(tag_impl, kMetaTag)) {
const typename Token::Attribute* equiv_attribute =
- token.GetAttributeItem(http_equivAttr);
+ token.GetAttributeItem(kHttpEquivAttr);
if (equiv_attribute) {
String equiv_attribute_value(equiv_attribute->Value());
if (DeprecatedEqualIgnoringCase(equiv_attribute_value,
@@ -871,7 +912,7 @@ void TokenPreloadScanner::ScanCommon(const Token& token,
} else if (DeprecatedEqualIgnoringCase(equiv_attribute_value,
"accept-ch")) {
const typename Token::Attribute* content_attribute =
- token.GetAttributeItem(contentAttr);
+ token.GetAttributeItem(kContentAttr);
if (content_attribute) {
client_hints_preferences_.UpdateFromAcceptClientHintsHeader(
content_attribute->Value(), document_url_, nullptr);
@@ -884,7 +925,7 @@ void TokenPreloadScanner::ScanCommon(const Token& token,
media_values_.Get(), &css_scanner_, viewport);
}
- if (Match(tag_impl, pictureTag)) {
+ if (Match(tag_impl, kPictureTag)) {
in_picture_ = true;
picture_data_ = PictureData();
return;
@@ -901,7 +942,7 @@ void TokenPreloadScanner::ScanCommon(const Token& token,
scanner.HandlePictureSourceURL(picture_data_);
std::unique_ptr<PreloadRequest> request = scanner.CreatePreloadRequest(
predicted_base_element_url_, source, client_hints_preferences_,
- picture_data_, document_parameters_->referrer_policy);
+ picture_data_, *document_parameters_);
if (request)
requests.push_back(std::move(request));
return;
@@ -914,7 +955,7 @@ template <typename Token>
void TokenPreloadScanner::UpdatePredictedBaseURL(const Token& token) {
DCHECK(predicted_base_element_url_.IsEmpty());
if (const typename Token::Attribute* href_attribute =
- token.GetAttributeItem(hrefAttr)) {
+ token.GetAttributeItem(kHrefAttr)) {
KURL url(document_url_, StripLeadingAndTrailingHTMLSpaces(
href_attribute->Value8BitIfNecessary()));
predicted_base_element_url_ =
@@ -942,7 +983,8 @@ void HTMLPreloadScanner::AppendToEnd(const SegmentedString& source) {
PreloadRequestStream HTMLPreloadScanner::Scan(
const KURL& starting_base_element_url,
- ViewportDescriptionWrapper* viewport) {
+ ViewportDescriptionWrapper* viewport,
+ bool& has_csp_meta_tag) {
// HTMLTokenizer::updateStateFor only works on the main thread.
DCHECK(IsMainThread());
@@ -960,14 +1002,20 @@ PreloadRequestStream HTMLPreloadScanner::Scan(
if (token_.GetType() == HTMLToken::kStartTag)
tokenizer_->UpdateStateFor(
AttemptStaticStringCreation(token_.GetName(), kLikely8Bit));
- bool is_csp_meta_tag = false;
- scanner_.Scan(token_, source_, requests, viewport, &is_csp_meta_tag);
+ bool seen_csp_meta_tag = false;
+ scanner_.Scan(token_, source_, requests, viewport, &seen_csp_meta_tag);
+ has_csp_meta_tag |= seen_csp_meta_tag;
token_.Clear();
- // Don't preload anything if a CSP meta tag is found. We should never really
- // find them here because the HTMLPreloadScanner is only used for
- // dynamically added markup.
- if (is_csp_meta_tag)
+ // Don't preload anything if a CSP meta tag is found. We should rarely find
+ // them here because the HTMLPreloadScanner is only used for the synchronous
+ // parsing path.
+ if (seen_csp_meta_tag) {
+ // Reset the tokenizer, to avoid re-scanning tokens that we are about to
+ // start parsing.
+ source_.Clear();
+ tokenizer_->Reset();
return requests;
+ }
}
return requests;
@@ -988,6 +1036,7 @@ CachedDocumentParameters::CachedDocumentParameters(Document* document) {
document->GetSettings()->GetViewportMetaEnabled();
referrer_policy = document->GetReferrerPolicy();
integrity_features = SubresourceIntegrityHelper::GetFeatures(document);
+ lazyload_policy_enforced = document->IsLazyLoadPolicyEnforced();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.h b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.h
index 6002ea8db52..881c54bded9 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.h
@@ -72,8 +72,9 @@ struct CORE_EXPORT CachedDocumentParameters {
Length default_viewport_min_width;
bool viewport_meta_zero_values_quirk;
bool viewport_meta_enabled;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
SubresourceIntegrity::IntegrityFeatures integrity_features;
+ bool lazyload_policy_enforced;
private:
explicit CachedDocumentParameters(Document*);
@@ -188,7 +189,8 @@ class CORE_EXPORT HTMLPreloadScanner {
void AppendToEnd(const SegmentedString&);
PreloadRequestStream Scan(const KURL& document_base_element_url,
- ViewportDescriptionWrapper*);
+ ViewportDescriptionWrapper*,
+ bool& has_csp_meta_tag);
private:
HTMLPreloadScanner(const HTMLParserOptions&,
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_fuzzer.cc b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_fuzzer.cc
index fe32a78bfb2..4d20f391a78 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_fuzzer.cc
@@ -61,7 +61,7 @@ int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
media_data.primary_pointer_type = kPointerTypeFine;
media_data.default_font_size = 16;
media_data.three_d_enabled = true;
- media_data.media_type = MediaTypeNames::screen;
+ media_data.media_type = media_type_names::kScreen;
media_data.strict_mode = true;
media_data.display_mode = kWebDisplayModeBrowser;
@@ -75,7 +75,9 @@ int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
CString bytes = fuzzed_data.ConsumeRemainingBytes();
String decoded_bytes = decoder.Decode(bytes.data(), bytes.length());
scanner->AppendToEnd(decoded_bytes);
- PreloadRequestStream requests = scanner->Scan(document_url, nullptr);
+ bool has_csp_meta_tag_unused = false;
+ PreloadRequestStream requests =
+ scanner->Scan(document_url, nullptr, has_csp_meta_tag_unused);
preloader.TakeAndPreload(requests);
return 0;
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc
index 7608495b3b2..018eab6d5ad 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc
@@ -20,6 +20,7 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h"
#include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -48,19 +49,25 @@ struct ReferrerPolicyTestCase {
const char* output_base_url;
ResourceType type;
int resource_width;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
// Expected referrer header of the preload request, or nullptr if the header
// shouldn't be checked (and no network request should be created).
const char* expected_referrer;
};
-struct CORSTestCase {
+struct CorsTestCase {
const char* base_url;
const char* input_html;
network::mojom::FetchRequestMode request_mode;
network::mojom::FetchCredentialsMode credentials_mode;
};
+struct CSPTestCase {
+ const char* base_url;
+ const char* input_html;
+ bool should_see_csp_tag;
+};
+
struct NonceTestCase {
const char* base_url;
const char* input_html;
@@ -79,6 +86,11 @@ struct IntegrityTestCase {
const char* input_html;
};
+struct LazyImageLoadTestCase {
+ const char* input_html;
+ bool is_lazyload_image_disabled;
+};
+
class HTMLMockHTMLResourcePreloader : public ResourcePreloader {
public:
void PreloadRequestVerification(ResourceType type,
@@ -87,7 +99,7 @@ class HTMLMockHTMLResourcePreloader : public ResourcePreloader {
int width,
const ClientHintsPreferences& preferences) {
if (!url) {
- EXPECT_FALSE(preload_request_);
+ EXPECT_FALSE(preload_request_) << preload_request_->ResourceURL();
return;
}
EXPECT_NE(nullptr, preload_request_.get());
@@ -112,23 +124,25 @@ class HTMLMockHTMLResourcePreloader : public ResourcePreloader {
}
}
- void PreloadRequestVerification(ResourceType type,
- const char* url,
- const char* base_url,
- int width,
- ReferrerPolicy referrer_policy) {
+ void PreloadRequestVerification(
+ ResourceType type,
+ const char* url,
+ const char* base_url,
+ int width,
+ network::mojom::ReferrerPolicy referrer_policy) {
PreloadRequestVerification(type, url, base_url, width,
ClientHintsPreferences());
EXPECT_EQ(referrer_policy, preload_request_->GetReferrerPolicy());
}
- void PreloadRequestVerification(ResourceType type,
- const char* url,
- const char* base_url,
- int width,
- ReferrerPolicy referrer_policy,
- Document* document,
- const char* expected_referrer) {
+ void PreloadRequestVerification(
+ ResourceType type,
+ const char* url,
+ const char* base_url,
+ int width,
+ network::mojom::ReferrerPolicy referrer_policy,
+ Document* document,
+ const char* expected_referrer) {
PreloadRequestVerification(type, url, base_url, width, referrer_policy);
Resource* resource = preload_request_->Start(document);
ASSERT_TRUE(resource);
@@ -145,7 +159,7 @@ class HTMLMockHTMLResourcePreloader : public ResourcePreloader {
}
}
- void CORSRequestVerification(
+ void CorsRequestVerification(
Document* document,
network::mojom::FetchRequestMode request_mode,
network::mojom::FetchCredentialsMode credentials_mode) {
@@ -179,6 +193,12 @@ class HTMLMockHTMLResourcePreloader : public ResourcePreloader {
}
}
+ void LazyImageLoadDisableVerification(bool is_lazyload_image_disabled) {
+ ASSERT_TRUE(preload_request_.get());
+ EXPECT_EQ(preload_request_->IsLazyloadImageDisabledForTesting(),
+ is_lazyload_image_disabled);
+ }
+
protected:
void Preload(std::unique_ptr<PreloadRequest> preload_request,
const NetworkHintsInterface&) override {
@@ -213,17 +233,17 @@ class HTMLPreloadScannerTest : public PageTestBase {
data.primary_pointer_type = kPointerTypeFine;
data.default_font_size = 16;
data.three_d_enabled = true;
- data.media_type = MediaTypeNames::screen;
+ data.media_type = media_type_names::kScreen;
data.strict_mode = true;
data.display_mode = kWebDisplayModeBrowser;
return data;
}
- void RunSetUp(
- ViewportState viewport_state,
- PreloadState preload_state = kPreloadEnabled,
- ReferrerPolicy document_referrer_policy = kReferrerPolicyDefault,
- bool use_secure_document_url = false) {
+ void RunSetUp(ViewportState viewport_state,
+ PreloadState preload_state = kPreloadEnabled,
+ network::mojom::ReferrerPolicy document_referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault,
+ bool use_secure_document_url = false) {
HTMLParserOptions options(&GetDocument());
KURL document_url = KURL("http://whatever.test/");
if (use_secure_document_url)
@@ -249,10 +269,12 @@ class HTMLPreloadScannerTest : public PageTestBase {
}
void Test(PreloadScannerTestCase test_case) {
+ SCOPED_TRACE(test_case.input_html);
HTMLMockHTMLResourcePreloader preloader;
KURL base_url(test_case.base_url);
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
preloader.PreloadRequestVerification(
@@ -264,7 +286,8 @@ class HTMLPreloadScannerTest : public PageTestBase {
HTMLMockHTMLResourcePreloader preloader;
KURL base_url(test_case.base_url);
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
preloader.PreconnectRequestVerification(test_case.preconnected_host,
test_case.cross_origin);
@@ -274,7 +297,8 @@ class HTMLPreloadScannerTest : public PageTestBase {
HTMLMockHTMLResourcePreloader preloader;
KURL base_url(test_case.base_url);
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
if (test_case.expected_referrer) {
@@ -289,24 +313,33 @@ class HTMLPreloadScannerTest : public PageTestBase {
}
}
- void Test(CORSTestCase test_case) {
+ void Test(CorsTestCase test_case) {
HTMLMockHTMLResourcePreloader preloader;
KURL base_url(test_case.base_url);
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
-
- preloader.CORSRequestVerification(&GetDocument(), test_case.request_mode,
+ preloader.CorsRequestVerification(&GetDocument(), test_case.request_mode,
test_case.credentials_mode);
}
+ void Test(CSPTestCase test_case) {
+ HTMLMockHTMLResourcePreloader preloader;
+ KURL base_url(test_case.base_url);
+ seen_csp_meta_tag_ = false;
+ scanner_->AppendToEnd(String(test_case.input_html));
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
+ EXPECT_EQ(test_case.should_see_csp_tag, seen_csp_meta_tag_);
+ }
+
void Test(NonceTestCase test_case) {
HTMLMockHTMLResourcePreloader preloader;
KURL base_url(test_case.base_url);
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
-
preloader.NonceRequestVerification(test_case.nonce);
}
@@ -314,7 +347,8 @@ class HTMLPreloadScannerTest : public PageTestBase {
HTMLMockHTMLResourcePreloader preloader;
KURL base_url(test_case.base_url);
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
preloader.ContextVerification(test_case.is_image_set);
@@ -325,15 +359,29 @@ class HTMLPreloadScannerTest : public PageTestBase {
HTMLMockHTMLResourcePreloader preloader;
KURL base_url("http://example.test/");
scanner_->AppendToEnd(String(test_case.input_html));
- PreloadRequestStream requests = scanner_->Scan(base_url, nullptr);
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
preloader.TakeAndPreload(requests);
preloader.CheckNumberOfIntegrityConstraints(
test_case.number_of_integrity_metadata_found);
}
+ void Test(LazyImageLoadTestCase test_case) {
+ SCOPED_TRACE(test_case.input_html);
+ HTMLMockHTMLResourcePreloader preloader;
+ KURL base_url("http://example.test/");
+ scanner_->AppendToEnd(String(test_case.input_html));
+ PreloadRequestStream requests =
+ scanner_->Scan(base_url, nullptr, seen_csp_meta_tag_);
+ preloader.TakeAndPreload(requests);
+ preloader.LazyImageLoadDisableVerification(
+ test_case.is_lazyload_image_disabled);
+ }
+
private:
std::unique_ptr<HTMLPreloadScanner> scanner_;
+ bool seen_csp_meta_tag_ = false;
};
TEST_F(HTMLPreloadScannerTest, testImages) {
@@ -623,7 +671,8 @@ TEST_F(HTMLPreloadScannerTest, testMetaAcceptCH) {
};
for (const auto& test_case : test_cases) {
- RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault,
+ RunSetUp(kViewportDisabled, kPreloadEnabled,
+ network::mojom::ReferrerPolicy::kDefault,
true /* use_secure_document_url */);
Test(test_case);
}
@@ -657,12 +706,14 @@ TEST_F(HTMLPreloadScannerTest, testMetaAcceptCHInsecureDocument) {
all};
// For an insecure document, client hint should not be attached.
- RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault,
+ RunSetUp(kViewportDisabled, kPreloadEnabled,
+ network::mojom::ReferrerPolicy::kDefault,
false /* use_secure_document_url */);
Test(expect_no_client_hint);
// For a secure document, client hint should be attached.
- RunSetUp(kViewportDisabled, kPreloadEnabled, kReferrerPolicyDefault,
+ RunSetUp(kViewportDisabled, kPreloadEnabled,
+ network::mojom::ReferrerPolicy::kDefault,
true /* use_secure_document_url */);
Test(expect_client_hint);
}
@@ -784,101 +835,104 @@ TEST_F(HTMLPreloadScannerTest, testContext) {
TEST_F(HTMLPreloadScannerTest, testReferrerPolicy) {
ReferrerPolicyTestCase test_cases[] = {
{"http://example.test", "<img src='bla.gif'/>", "bla.gif",
- "http://example.test/", ResourceType::kImage, 0, kReferrerPolicyDefault},
+ "http://example.test/", ResourceType::kImage, 0,
+ network::mojom::ReferrerPolicy::kDefault},
{"http://example.test", "<img referrerpolicy='origin' src='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
{"http://example.test",
"<meta name='referrer' content='not-a-valid-policy'><img "
"src='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyDefault, nullptr},
+ network::mojom::ReferrerPolicy::kDefault, nullptr},
{"http://example.test",
"<img referrerpolicy='origin' referrerpolicy='origin-when-cross-origin' "
"src='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
{"http://example.test",
"<img referrerpolicy='not-a-valid-policy' src='bla.gif'/>", "bla.gif",
- "http://example.test/", ResourceType::kImage, 0, kReferrerPolicyDefault,
- nullptr},
+ "http://example.test/", ResourceType::kImage, 0,
+ network::mojom::ReferrerPolicy::kDefault, nullptr},
{"http://example.test",
"<link rel=preload as=image referrerpolicy='origin-when-cross-origin' "
"href='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyOriginWhenCrossOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, nullptr},
{"http://example.test",
"<link rel=preload as=image referrerpolicy='same-origin' "
"href='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicySameOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kSameOrigin, nullptr},
{"http://example.test",
"<link rel=preload as=image referrerpolicy='strict-origin' "
"href='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyStrictOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kStrictOrigin, nullptr},
{"http://example.test",
"<link rel=preload as=image "
"referrerpolicy='strict-origin-when-cross-origin' "
"href='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyStrictOriginWhenCrossOrigin, nullptr},
+ network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ nullptr},
{"http://example.test",
"<link rel='stylesheet' href='sheet.css' type='text/css'>", "sheet.css",
"http://example.test/", ResourceType::kCSSStyleSheet, 0,
- kReferrerPolicyDefault, nullptr},
+ network::mojom::ReferrerPolicy::kDefault, nullptr},
{"http://example.test",
"<link rel=preload as=image referrerpolicy='origin' "
"referrerpolicy='origin-when-cross-origin' href='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
{"http://example.test",
"<meta name='referrer' content='no-referrer'><img "
"referrerpolicy='origin' src='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
// The scanner's state is not reset between test cases, so all subsequent
// test cases have a document referrer policy of no-referrer.
{"http://example.test",
"<link rel=preload as=image referrerpolicy='not-a-valid-policy' "
"href='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyNever, nullptr},
+ network::mojom::ReferrerPolicy::kNever, nullptr},
{"http://example.test",
"<img referrerpolicy='not-a-valid-policy' src='bla.gif'/>", "bla.gif",
- "http://example.test/", ResourceType::kImage, 0, kReferrerPolicyNever,
- nullptr},
+ "http://example.test/", ResourceType::kImage, 0,
+ network::mojom::ReferrerPolicy::kNever, nullptr},
{"http://example.test", "<img src='bla.gif'/>", "bla.gif",
- "http://example.test/", ResourceType::kImage, 0, kReferrerPolicyNever,
- nullptr}};
+ "http://example.test/", ResourceType::kImage, 0,
+ network::mojom::ReferrerPolicy::kNever, nullptr}};
for (const auto& test_case : test_cases)
Test(test_case);
}
-TEST_F(HTMLPreloadScannerTest, testCORS) {
- CORSTestCase test_cases[] = {
+TEST_F(HTMLPreloadScannerTest, testCors) {
+ CorsTestCase test_cases[] = {
{"http://example.test", "<script src='/script'></script>",
- network::mojom::FetchRequestMode::kNoCORS,
+ network::mojom::FetchRequestMode::kNoCors,
network::mojom::FetchCredentialsMode::kInclude},
{"http://example.test", "<script crossorigin src='/script'></script>",
- network::mojom::FetchRequestMode::kCORS,
+ network::mojom::FetchRequestMode::kCors,
network::mojom::FetchCredentialsMode::kSameOrigin},
{"http://example.test",
"<script crossorigin=use-credentials src='/script'></script>",
- network::mojom::FetchRequestMode::kCORS,
+ network::mojom::FetchRequestMode::kCors,
network::mojom::FetchCredentialsMode::kInclude},
{"http://example.test", "<script type='module' src='/script'></script>",
- network::mojom::FetchRequestMode::kCORS,
+ network::mojom::FetchRequestMode::kCors,
network::mojom::FetchCredentialsMode::kSameOrigin},
{"http://example.test",
"<script type='module' crossorigin='anonymous' src='/script'></script>",
- network::mojom::FetchRequestMode::kCORS,
+ network::mojom::FetchRequestMode::kCors,
network::mojom::FetchCredentialsMode::kSameOrigin},
{"http://example.test",
"<script type='module' crossorigin='use-credentials' "
"src='/script'></script>",
- network::mojom::FetchRequestMode::kCORS,
+ network::mojom::FetchRequestMode::kCors,
network::mojom::FetchCredentialsMode::kInclude},
};
@@ -888,6 +942,22 @@ TEST_F(HTMLPreloadScannerTest, testCORS) {
}
}
+TEST_F(HTMLPreloadScannerTest, testCSP) {
+ CSPTestCase test_cases[] = {
+ {"http://example.test",
+ "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src "
+ "https:\">",
+ true},
+ {"http://example.test",
+ "<meta name=\"viewport\" content=\"width=device-width\">", false},
+ {"http://example.test", "<img src=\"example.gif\">", false}};
+
+ for (const auto& test_case : test_cases) {
+ SCOPED_TRACE(test_case.input_html);
+ Test(test_case);
+ }
+}
+
TEST_F(HTMLPreloadScannerTest, testNonce) {
NonceTestCase test_cases[] = {
{"http://example.test", "<script src='/script'></script>", ""},
@@ -920,27 +990,28 @@ TEST_F(HTMLPreloadScannerTest, testNonce) {
// Tests that a document-level referrer policy (e.g. one set by HTTP header) is
// applied for preload requests.
TEST_F(HTMLPreloadScannerTest, testReferrerPolicyOnDocument) {
- RunSetUp(kViewportEnabled, kPreloadEnabled, kReferrerPolicyOrigin);
+ RunSetUp(kViewportEnabled, kPreloadEnabled,
+ network::mojom::ReferrerPolicy::kOrigin);
ReferrerPolicyTestCase test_cases[] = {
{"http://example.test", "<img src='blah.gif'/>", "blah.gif",
- "http://example.test/", ResourceType::kImage, 0, kReferrerPolicyOrigin,
- nullptr},
+ "http://example.test/", ResourceType::kImage, 0,
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
{"http://example.test", "<style>@import url('blah.css');</style>",
"blah.css", "http://example.test/", ResourceType::kCSSStyleSheet, 0,
- kReferrerPolicyOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
// Tests that a meta-delivered referrer policy with an unrecognized policy
// value does not override the document's referrer policy.
{"http://example.test",
"<meta name='referrer' content='not-a-valid-policy'><img "
"src='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyOrigin, nullptr},
+ network::mojom::ReferrerPolicy::kOrigin, nullptr},
// Tests that a meta-delivered referrer policy with a valid policy value
// does override the document's referrer policy.
{"http://example.test",
"<meta name='referrer' content='unsafe-url'><img src='bla.gif'/>",
"bla.gif", "http://example.test/", ResourceType::kImage, 0,
- kReferrerPolicyAlways, nullptr},
+ network::mojom::ReferrerPolicy::kAlways, nullptr},
};
for (const auto& test_case : test_cases)
@@ -1075,7 +1146,8 @@ TEST_F(HTMLPreloadScannerTest, testUppercaseAsValues) {
}
TEST_F(HTMLPreloadScannerTest, ReferrerHeader) {
- RunSetUp(kViewportEnabled, kPreloadEnabled, kReferrerPolicyAlways);
+ RunSetUp(kViewportEnabled, kPreloadEnabled,
+ network::mojom::ReferrerPolicy::kAlways);
KURL preload_url("http://example.test/sheet.css");
Platform::Current()->GetURLLoaderMockFactory()->RegisterURL(
@@ -1088,7 +1160,7 @@ TEST_F(HTMLPreloadScannerTest, ReferrerHeader) {
"http://example.test/",
ResourceType::kCSSStyleSheet,
0,
- kReferrerPolicyAlways,
+ network::mojom::ReferrerPolicy::kAlways,
"http://whatever.test/"};
Test(test_case);
}
@@ -1117,4 +1189,38 @@ TEST_F(HTMLPreloadScannerTest, Integrity) {
Test(test_case);
}
+// Regression test for http://crbug.com/898795 where preloads after a
+// dynamically inserted meta csp tag are dispatched on subsequent calls to the
+// HTMLPreloadScanner, after they had been parsed.
+TEST_F(HTMLPreloadScannerTest, MetaCsp_NoPreloadsAfter) {
+ PreloadScannerTestCase test_cases[] = {
+ {"http://example.test",
+ "<meta http-equiv='Content-Security-Policy'><link rel=preload href=bla "
+ "as=SCRIPT>",
+ nullptr, "http://example.test/", ResourceType::kScript, 0},
+ // The buffered text referring to the preload above should be cleared, so
+ // make sure it is not preloaded on subsequent calls to Scan.
+ {"http://example.test", "", nullptr, "http://example.test/",
+ ResourceType::kScript, 0},
+ };
+
+ for (const auto& test_case : test_cases)
+ Test(test_case);
+}
+
+TEST_F(HTMLPreloadScannerTest, LazyImageLoadDisabledForSmallImages) {
+ ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
+ LazyImageLoadTestCase test_cases[] = {
+ {"<img src='foo.jpg'>", false},
+ {"<img src='foo.jpg' style='height: 1px; width: 1px'>", true},
+ {"<img src='foo.jpg' style='height: 10px; width: 10px'>", true},
+ {"<img src='foo.jpg' style='height: 20px; width: 20px'>", false},
+ {"<img src='foo.jpg' style='height: 1px;'>", false},
+ {"<img src='foo.jpg' style='width: 1px;'>", false},
+ };
+
+ for (const auto& test_case : test_cases)
+ Test(test_case);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.cc b/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.cc
index d89dfaab23e..d0485f78c89 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.cc
@@ -39,7 +39,7 @@ HTMLResourcePreloader::HTMLResourcePreloader(Document& document)
: document_(document) {}
HTMLResourcePreloader* HTMLResourcePreloader::Create(Document& document) {
- return new HTMLResourcePreloader(document);
+ return MakeGarbageCollected<HTMLResourcePreloader>(document);
}
void HTMLResourcePreloader::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.h b/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.h
index 4eb9de5a91d..3c431cabb2f 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.h
@@ -47,6 +47,9 @@ class CORE_EXPORT HTMLResourcePreloader
public:
static HTMLResourcePreloader* Create(Document&);
+
+ explicit HTMLResourcePreloader(Document&);
+
int CountPreloads();
Document* GetDocument() { return document_.Get(); }
void Trace(blink::Visitor*);
@@ -54,7 +57,6 @@ class CORE_EXPORT HTMLResourcePreloader
protected:
void Preload(std::unique_ptr<PreloadRequest>,
const NetworkHintsInterface&) override;
- explicit HTMLResourcePreloader(Document&);
private:
Member<Document> document_;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader_test.cc b/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader_test.cc
index 85a88d23f95..66cffeb5966 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader_test.cc
@@ -51,7 +51,7 @@ class HTMLResourcePreloaderTest : public PageTestBase {
PreloaderNetworkHintsMock network_hints;
auto preload_request = PreloadRequest::CreateIfNeeded(
String(), TextPosition(), test_case.url, KURL(test_case.base_url),
- ResourceType::kImage, ReferrerPolicy(),
+ ResourceType::kImage, network::mojom::ReferrerPolicy(),
PreloadRequest::kDocumentIsReferrer, ResourceFetcher::kImageNotImageSet,
FetchParameters::ResourceWidth(), ClientHintsPreferences(),
PreloadRequest::kRequestTypePreconnect);
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_stack_item.h b/chromium/third_party/blink/renderer/core/html/parser/html_stack_item.h
index 9cd28abdfb6..d25fe96a9dd 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_stack_item.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_stack_item.h
@@ -43,17 +43,40 @@ class HTMLStackItem : public GarbageCollectedFinalized<HTMLStackItem> {
// Used by document fragment node and context element.
static HTMLStackItem* Create(ContainerNode* node, ItemType type) {
- return new HTMLStackItem(node, type);
+ return MakeGarbageCollected<HTMLStackItem>(node, type);
}
// Used by HTMLElementStack and HTMLFormattingElementList.
static HTMLStackItem* Create(
ContainerNode* node,
AtomicHTMLToken* token,
- const AtomicString& namespace_uri = HTMLNames::xhtmlNamespaceURI) {
- return new HTMLStackItem(node, token, namespace_uri);
+ const AtomicString& namespace_uri = html_names::xhtmlNamespaceURI) {
+ return MakeGarbageCollected<HTMLStackItem>(node, token, namespace_uri);
}
+ HTMLStackItem(ContainerNode* node, ItemType type) : node_(node) {
+ switch (type) {
+ case kItemForDocumentFragmentNode:
+ is_document_fragment_node_ = true;
+ break;
+ case kItemForContextElement:
+ token_local_name_ = GetElement()->localName();
+ namespace_uri_ = GetElement()->namespaceURI();
+ is_document_fragment_node_ = false;
+ break;
+ }
+ }
+
+ HTMLStackItem(
+ ContainerNode* node,
+ AtomicHTMLToken* token,
+ const AtomicString& namespace_uri = html_names::xhtmlNamespaceURI)
+ : node_(node),
+ token_local_name_(token->GetName()),
+ token_attributes_(token->Attributes()),
+ namespace_uri_(namespace_uri),
+ is_document_fragment_node_(false) {}
+
Element* GetElement() const { return ToElement(node_.Get()); }
ContainerNode* GetNode() const { return node_.Get(); }
@@ -82,129 +105,122 @@ class HTMLStackItem : public GarbageCollectedFinalized<HTMLStackItem> {
bool MatchesHTMLTag(const AtomicString& name) const {
return token_local_name_ == name &&
- namespace_uri_ == HTMLNames::xhtmlNamespaceURI;
+ namespace_uri_ == html_names::xhtmlNamespaceURI;
}
bool MatchesHTMLTag(const QualifiedName& name) const {
return token_local_name_ == name &&
- namespace_uri_ == HTMLNames::xhtmlNamespaceURI;
+ namespace_uri_ == html_names::xhtmlNamespaceURI;
}
bool CausesFosterParenting() {
- return HasTagName(HTMLNames::tableTag) || HasTagName(HTMLNames::tbodyTag) ||
- HasTagName(HTMLNames::tfootTag) || HasTagName(HTMLNames::theadTag) ||
- HasTagName(HTMLNames::trTag);
+ return HasTagName(html_names::kTableTag) ||
+ HasTagName(html_names::kTbodyTag) ||
+ HasTagName(html_names::kTfootTag) ||
+ HasTagName(html_names::kTheadTag) || HasTagName(html_names::kTrTag);
}
bool IsInHTMLNamespace() const {
// A DocumentFragment takes the place of the document element when parsing
// fragments and should be considered in the HTML namespace.
- return NamespaceURI() == HTMLNames::xhtmlNamespaceURI ||
+ return NamespaceURI() == html_names::xhtmlNamespaceURI ||
IsDocumentFragmentNode(); // FIXME: Does this also apply to
// ShadowRoot?
}
bool IsNumberedHeaderElement() const {
- return HasTagName(HTMLNames::h1Tag) || HasTagName(HTMLNames::h2Tag) ||
- HasTagName(HTMLNames::h3Tag) || HasTagName(HTMLNames::h4Tag) ||
- HasTagName(HTMLNames::h5Tag) || HasTagName(HTMLNames::h6Tag);
+ return HasTagName(html_names::kH1Tag) || HasTagName(html_names::kH2Tag) ||
+ HasTagName(html_names::kH3Tag) || HasTagName(html_names::kH4Tag) ||
+ HasTagName(html_names::kH5Tag) || HasTagName(html_names::kH6Tag);
}
bool IsTableBodyContextElement() const {
- return HasTagName(HTMLNames::tbodyTag) || HasTagName(HTMLNames::tfootTag) ||
- HasTagName(HTMLNames::theadTag);
+ return HasTagName(html_names::kTbodyTag) ||
+ HasTagName(html_names::kTfootTag) ||
+ HasTagName(html_names::kTheadTag);
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#special
bool IsSpecialNode() const {
- if (HasTagName(MathMLNames::miTag) || HasTagName(MathMLNames::moTag) ||
- HasTagName(MathMLNames::mnTag) || HasTagName(MathMLNames::msTag) ||
- HasTagName(MathMLNames::mtextTag) ||
- HasTagName(MathMLNames::annotation_xmlTag) ||
- HasTagName(SVGNames::foreignObjectTag) ||
- HasTagName(SVGNames::descTag) || HasTagName(SVGNames::titleTag))
+ if (HasTagName(mathml_names::kMiTag) || HasTagName(mathml_names::kMoTag) ||
+ HasTagName(mathml_names::kMnTag) || HasTagName(mathml_names::kMsTag) ||
+ HasTagName(mathml_names::kMtextTag) ||
+ HasTagName(mathml_names::kAnnotationXmlTag) ||
+ HasTagName(svg_names::kForeignObjectTag) ||
+ HasTagName(svg_names::kDescTag) || HasTagName(svg_names::kTitleTag))
return true;
if (IsDocumentFragmentNode())
return true;
if (!IsInHTMLNamespace())
return false;
const AtomicString& tag_name = LocalName();
- return tag_name == HTMLNames::addressTag ||
- tag_name == HTMLNames::areaTag || tag_name == HTMLNames::appletTag ||
- tag_name == HTMLNames::articleTag ||
- tag_name == HTMLNames::asideTag || tag_name == HTMLNames::baseTag ||
- tag_name == HTMLNames::basefontTag ||
- tag_name == HTMLNames::bgsoundTag ||
- tag_name == HTMLNames::blockquoteTag ||
- tag_name == HTMLNames::bodyTag || tag_name == HTMLNames::brTag ||
- tag_name == HTMLNames::buttonTag ||
- tag_name == HTMLNames::captionTag ||
- tag_name == HTMLNames::centerTag || tag_name == HTMLNames::colTag ||
- tag_name == HTMLNames::colgroupTag ||
- tag_name == HTMLNames::commandTag || tag_name == HTMLNames::ddTag ||
- tag_name == HTMLNames::detailsTag || tag_name == HTMLNames::dirTag ||
- tag_name == HTMLNames::divTag || tag_name == HTMLNames::dlTag ||
- tag_name == HTMLNames::dtTag || tag_name == HTMLNames::embedTag ||
- tag_name == HTMLNames::fieldsetTag ||
- tag_name == HTMLNames::figcaptionTag ||
- tag_name == HTMLNames::figureTag ||
- tag_name == HTMLNames::footerTag || tag_name == HTMLNames::formTag ||
- tag_name == HTMLNames::frameTag ||
- tag_name == HTMLNames::framesetTag || IsNumberedHeaderElement() ||
- tag_name == HTMLNames::headTag || tag_name == HTMLNames::headerTag ||
- tag_name == HTMLNames::hgroupTag || tag_name == HTMLNames::hrTag ||
- tag_name == HTMLNames::htmlTag || tag_name == HTMLNames::iframeTag ||
- tag_name == HTMLNames::imgTag || tag_name == HTMLNames::inputTag ||
- tag_name == HTMLNames::liTag || tag_name == HTMLNames::linkTag ||
- tag_name == HTMLNames::listingTag ||
- tag_name == HTMLNames::mainTag ||
- tag_name == HTMLNames::marqueeTag ||
- tag_name == HTMLNames::menuTag ||
- tag_name == HTMLNames::metaTag || tag_name == HTMLNames::navTag ||
- tag_name == HTMLNames::noembedTag ||
- tag_name == HTMLNames::noframesTag ||
- tag_name == HTMLNames::noscriptTag ||
- tag_name == HTMLNames::objectTag || tag_name == HTMLNames::olTag ||
- tag_name == HTMLNames::pTag || tag_name == HTMLNames::paramTag ||
- tag_name == HTMLNames::plaintextTag ||
- tag_name == HTMLNames::preTag || tag_name == HTMLNames::scriptTag ||
- tag_name == HTMLNames::sectionTag ||
- tag_name == HTMLNames::selectTag ||
- tag_name == HTMLNames::styleTag ||
- tag_name == HTMLNames::summaryTag ||
- tag_name == HTMLNames::tableTag || IsTableBodyContextElement() ||
- tag_name == HTMLNames::tdTag || tag_name == HTMLNames::templateTag ||
- tag_name == HTMLNames::textareaTag || tag_name == HTMLNames::thTag ||
- tag_name == HTMLNames::titleTag || tag_name == HTMLNames::trTag ||
- tag_name == HTMLNames::ulTag || tag_name == HTMLNames::wbrTag ||
- tag_name == HTMLNames::xmpTag;
+ return tag_name == html_names::kAddressTag ||
+ tag_name == html_names::kAreaTag ||
+ tag_name == html_names::kAppletTag ||
+ tag_name == html_names::kArticleTag ||
+ tag_name == html_names::kAsideTag ||
+ tag_name == html_names::kBaseTag ||
+ tag_name == html_names::kBasefontTag ||
+ tag_name == html_names::kBgsoundTag ||
+ tag_name == html_names::kBlockquoteTag ||
+ tag_name == html_names::kBodyTag || tag_name == html_names::kBrTag ||
+ tag_name == html_names::kButtonTag ||
+ tag_name == html_names::kCaptionTag ||
+ tag_name == html_names::kCenterTag ||
+ tag_name == html_names::kColTag ||
+ tag_name == html_names::kColgroupTag ||
+ tag_name == html_names::kCommandTag ||
+ tag_name == html_names::kDdTag ||
+ tag_name == html_names::kDetailsTag ||
+ tag_name == html_names::kDirTag || tag_name == html_names::kDivTag ||
+ tag_name == html_names::kDlTag || tag_name == html_names::kDtTag ||
+ tag_name == html_names::kEmbedTag ||
+ tag_name == html_names::kFieldsetTag ||
+ tag_name == html_names::kFigcaptionTag ||
+ tag_name == html_names::kFigureTag ||
+ tag_name == html_names::kFooterTag ||
+ tag_name == html_names::kFormTag ||
+ tag_name == html_names::kFrameTag ||
+ tag_name == html_names::kFramesetTag || IsNumberedHeaderElement() ||
+ tag_name == html_names::kHeadTag ||
+ tag_name == html_names::kHeaderTag ||
+ tag_name == html_names::kHgroupTag ||
+ tag_name == html_names::kHrTag || tag_name == html_names::kHTMLTag ||
+ tag_name == html_names::kIFrameTag ||
+ tag_name == html_names::kImgTag ||
+ tag_name == html_names::kInputTag ||
+ tag_name == html_names::kLiTag || tag_name == html_names::kLinkTag ||
+ tag_name == html_names::kListingTag ||
+ tag_name == html_names::kMainTag ||
+ tag_name == html_names::kMarqueeTag ||
+ tag_name == html_names::kMenuTag ||
+ tag_name == html_names::kMetaTag ||
+ tag_name == html_names::kNavTag ||
+ tag_name == html_names::kNoembedTag ||
+ tag_name == html_names::kNoframesTag ||
+ tag_name == html_names::kNoscriptTag ||
+ tag_name == html_names::kObjectTag ||
+ tag_name == html_names::kOlTag || tag_name == html_names::kPTag ||
+ tag_name == html_names::kParamTag ||
+ tag_name == html_names::kPlaintextTag ||
+ tag_name == html_names::kPreTag ||
+ tag_name == html_names::kScriptTag ||
+ tag_name == html_names::kSectionTag ||
+ tag_name == html_names::kSelectTag ||
+ tag_name == html_names::kStyleTag ||
+ tag_name == html_names::kSummaryTag ||
+ tag_name == html_names::kTableTag || IsTableBodyContextElement() ||
+ tag_name == html_names::kTdTag ||
+ tag_name == html_names::kTemplateTag ||
+ tag_name == html_names::kTextareaTag ||
+ tag_name == html_names::kThTag ||
+ tag_name == html_names::kTitleTag ||
+ tag_name == html_names::kTrTag || tag_name == html_names::kUlTag ||
+ tag_name == html_names::kWbrTag || tag_name == html_names::kXmpTag;
}
void Trace(blink::Visitor* visitor) { visitor->Trace(node_); }
private:
- HTMLStackItem(ContainerNode* node, ItemType type) : node_(node) {
- switch (type) {
- case kItemForDocumentFragmentNode:
- is_document_fragment_node_ = true;
- break;
- case kItemForContextElement:
- token_local_name_ = GetElement()->localName();
- namespace_uri_ = GetElement()->namespaceURI();
- is_document_fragment_node_ = false;
- break;
- }
- }
-
- HTMLStackItem(
- ContainerNode* node,
- AtomicHTMLToken* token,
- const AtomicString& namespace_uri = HTMLNames::xhtmlNamespaceURI)
- : node_(node),
- token_local_name_(token->GetName()),
- token_attributes_(token->Attributes()),
- namespace_uri_(namespace_uri),
- is_document_fragment_node_(false) {}
-
Member<ContainerNode> node_;
AtomicString token_local_name_;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer.cc b/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer.cc
index 83353e4df94..65b4bc446d6 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer.cc
@@ -38,7 +38,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static inline UChar ToLowerCase(UChar cc) {
DCHECK(IsASCIIAlpha(cc));
@@ -603,7 +603,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
HTML_BEGIN_STATE(kScriptDataDoubleEscapeStartState) {
if (IsTokenizerWhitespace(cc) || cc == '/' || cc == '>') {
BufferCharacter(cc);
- if (TemporaryBufferIs(scriptTag.LocalName()))
+ if (TemporaryBufferIs(kScriptTag.LocalName()))
HTML_ADVANCE_TO(kScriptDataDoubleEscapedState);
else
HTML_ADVANCE_TO(kScriptDataEscapedState);
@@ -683,7 +683,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
HTML_BEGIN_STATE(kScriptDataDoubleEscapeEndState) {
if (IsTokenizerWhitespace(cc) || cc == '/' || cc == '>') {
BufferCharacter(cc);
- if (TemporaryBufferIs(scriptTag.LocalName()))
+ if (TemporaryBufferIs(kScriptTag.LocalName()))
HTML_ADVANCE_TO(kScriptDataEscapedState);
else
HTML_ADVANCE_TO(kScriptDataDoubleEscapedState);
@@ -935,7 +935,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
HTML_BEGIN_STATE(kMarkupDeclarationOpenState) {
if (cc == '-') {
SegmentedString::LookAheadResult result =
- source.LookAhead(HTMLTokenizerNames::dashDash);
+ source.LookAhead(html_tokenizer_names::kDashDash);
if (result == SegmentedString::kDidMatch) {
source.AdvanceAndASSERT('-');
source.AdvanceAndASSERT('-');
@@ -945,7 +945,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
return HaveBufferedCharacterToken();
} else if (cc == 'D' || cc == 'd') {
SegmentedString::LookAheadResult result =
- source.LookAheadIgnoringCase(HTMLTokenizerNames::doctype);
+ source.LookAheadIgnoringCase(html_tokenizer_names::kDoctype);
if (result == SegmentedString::kDidMatch) {
AdvanceStringAndASSERTIgnoringCase(source, "doctype");
HTML_SWITCH_TO(kDOCTYPEState);
@@ -953,7 +953,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
return HaveBufferedCharacterToken();
} else if (cc == '[' && ShouldAllowCDATA()) {
SegmentedString::LookAheadResult result =
- source.LookAhead(HTMLTokenizerNames::cdata);
+ source.LookAhead(html_tokenizer_names::kCdata);
if (result == SegmentedString::kDidMatch) {
AdvanceStringAndASSERT(source, "[CDATA[");
HTML_SWITCH_TO(kCDATASectionState);
@@ -1132,7 +1132,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
} else {
if (cc == 'P' || cc == 'p') {
SegmentedString::LookAheadResult result =
- source.LookAheadIgnoringCase(HTMLTokenizerNames::publicString);
+ source.LookAheadIgnoringCase(html_tokenizer_names::kPublic);
if (result == SegmentedString::kDidMatch) {
AdvanceStringAndASSERTIgnoringCase(source, "public");
HTML_SWITCH_TO(kAfterDOCTYPEPublicKeywordState);
@@ -1140,7 +1140,7 @@ bool HTMLTokenizer::NextToken(SegmentedString& source, HTMLToken& token) {
return HaveBufferedCharacterToken();
} else if (cc == 'S' || cc == 's') {
SegmentedString::LookAheadResult result =
- source.LookAheadIgnoringCase(HTMLTokenizerNames::system);
+ source.LookAheadIgnoringCase(html_tokenizer_names::kSystem);
if (result == SegmentedString::kDidMatch) {
AdvanceStringAndASSERTIgnoringCase(source, "system");
HTML_SWITCH_TO(kAfterDOCTYPESystemKeywordState);
@@ -1454,20 +1454,20 @@ String HTMLTokenizer::BufferedCharacters() const {
}
void HTMLTokenizer::UpdateStateFor(const String& tag_name) {
- if (ThreadSafeMatch(tag_name, textareaTag) ||
- ThreadSafeMatch(tag_name, titleTag))
+ if (ThreadSafeMatch(tag_name, kTextareaTag) ||
+ ThreadSafeMatch(tag_name, kTitleTag))
SetState(HTMLTokenizer::kRCDATAState);
- else if (ThreadSafeMatch(tag_name, plaintextTag))
+ else if (ThreadSafeMatch(tag_name, kPlaintextTag))
SetState(HTMLTokenizer::kPLAINTEXTState);
- else if (ThreadSafeMatch(tag_name, scriptTag))
+ else if (ThreadSafeMatch(tag_name, kScriptTag))
SetState(HTMLTokenizer::kScriptDataState);
- else if (ThreadSafeMatch(tag_name, styleTag) ||
- ThreadSafeMatch(tag_name, iframeTag) ||
- ThreadSafeMatch(tag_name, xmpTag) ||
- (ThreadSafeMatch(tag_name, noembedTag) &&
+ else if (ThreadSafeMatch(tag_name, kStyleTag) ||
+ ThreadSafeMatch(tag_name, kIFrameTag) ||
+ ThreadSafeMatch(tag_name, kXmpTag) ||
+ (ThreadSafeMatch(tag_name, kNoembedTag) &&
options_.plugins_enabled) ||
- ThreadSafeMatch(tag_name, noframesTag) ||
- (ThreadSafeMatch(tag_name, noscriptTag) && options_.script_enabled))
+ ThreadSafeMatch(tag_name, kNoframesTag) ||
+ (ThreadSafeMatch(tag_name, kNoscriptTag) && options_.script_enabled))
SetState(HTMLTokenizer::kRAWTEXTState);
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer_names.json5 b/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer_names.json5
index a31d43b6110..d2b1c4dbb3d 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer_names.json5
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_tokenizer_names.json5
@@ -1,23 +1,19 @@
{
metadata: {
- namespace: "HTMLTokenizer",
+ namespace: "html_tokenizer_names",
},
data: [
{
name: "--",
- Symbol: "dashDash",
+ Symbol: "kDashDash",
},
"doctype",
{
name: "[CDATA[",
- Symbol: "cdata",
- },
- // The symbol "public" conflicts with the C++ keyword.
- {
- name: "public",
- Symbol: "publicString",
+ Symbol: "kCdata",
},
+ "public",
"system",
],
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.cc b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.cc
index 214c26eb463..4d0b1346265 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.cc
@@ -56,7 +56,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -81,37 +81,38 @@ static inline bool IsAllWhitespaceOrReplacementCharacters(
}
static bool IsNumberedHeaderTag(const AtomicString& tag_name) {
- return tag_name == h1Tag || tag_name == h2Tag || tag_name == h3Tag ||
- tag_name == h4Tag || tag_name == h5Tag || tag_name == h6Tag;
+ return tag_name == kH1Tag || tag_name == kH2Tag || tag_name == kH3Tag ||
+ tag_name == kH4Tag || tag_name == kH5Tag || tag_name == kH6Tag;
}
static bool IsCaptionColOrColgroupTag(const AtomicString& tag_name) {
- return tag_name == captionTag || tag_name == colTag ||
- tag_name == colgroupTag;
+ return tag_name == kCaptionTag || tag_name == kColTag ||
+ tag_name == kColgroupTag;
}
static bool IsTableCellContextTag(const AtomicString& tag_name) {
- return tag_name == thTag || tag_name == tdTag;
+ return tag_name == kThTag || tag_name == kTdTag;
}
static bool IsTableBodyContextTag(const AtomicString& tag_name) {
- return tag_name == tbodyTag || tag_name == tfootTag || tag_name == theadTag;
+ return tag_name == kTbodyTag || tag_name == kTfootTag ||
+ tag_name == kTheadTag;
}
static bool IsNonAnchorNonNobrFormattingTag(const AtomicString& tag_name) {
- return tag_name == bTag || tag_name == bigTag || tag_name == codeTag ||
- tag_name == emTag || tag_name == fontTag || tag_name == iTag ||
- tag_name == sTag || tag_name == smallTag || tag_name == strikeTag ||
- tag_name == strongTag || tag_name == ttTag || tag_name == uTag;
+ return tag_name == kBTag || tag_name == kBigTag || tag_name == kCodeTag ||
+ tag_name == kEmTag || tag_name == kFontTag || tag_name == kITag ||
+ tag_name == kSTag || tag_name == kSmallTag || tag_name == kStrikeTag ||
+ tag_name == kStrongTag || tag_name == kTtTag || tag_name == kUTag;
}
static bool IsNonAnchorFormattingTag(const AtomicString& tag_name) {
- return tag_name == nobrTag || IsNonAnchorNonNobrFormattingTag(tag_name);
+ return tag_name == kNobrTag || IsNonAnchorNonNobrFormattingTag(tag_name);
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#formatting
static bool IsFormattingTag(const AtomicString& tag_name) {
- return tag_name == aTag || IsNonAnchorFormattingTag(tag_name);
+ return tag_name == kATag || IsNonAnchorFormattingTag(tag_name);
}
class HTMLTreeBuilder::CharacterTokenBuffer {
@@ -403,20 +404,20 @@ void HTMLTreeBuilder::ProcessFakeEndTag(const QualifiedName& tag_name) {
}
void HTMLTreeBuilder::ProcessFakePEndTagIfPInButtonScope() {
- if (!tree_.OpenElements()->InButtonScope(pTag.LocalName()))
+ if (!tree_.OpenElements()->InButtonScope(kPTag.LocalName()))
return;
- AtomicHTMLToken end_p(HTMLToken::kEndTag, pTag.LocalName());
+ AtomicHTMLToken end_p(HTMLToken::kEndTag, kPTag.LocalName());
ProcessEndTag(&end_p);
}
namespace {
bool IsLi(const HTMLStackItem* item) {
- return item->HasTagName(liTag);
+ return item->HasTagName(kLiTag);
}
bool IsDdOrDt(const HTMLStackItem* item) {
- return item->HasTagName(ddTag) || item->HasTagName(dtTag);
+ return item->HasTagName(kDdTag) || item->HasTagName(kDtTag);
}
} // namespace
@@ -433,8 +434,8 @@ void HTMLTreeBuilder::ProcessCloseWhenNestedTag(AtomicHTMLToken* token) {
ProcessFakeEndTag(item->LocalName());
break;
}
- if (item->IsSpecialNode() && !item->HasTagName(addressTag) &&
- !item->HasTagName(divTag) && !item->HasTagName(pTag))
+ if (item->IsSpecialNode() && !item->HasTagName(kAddressTag) &&
+ !item->HasTagName(kDivTag) && !item->HasTagName(kPTag))
break;
node_record = node_record->Next();
}
@@ -463,9 +464,8 @@ static void AdjustSVGTagNameCase(AtomicHTMLToken* token) {
static PrefixedNameToQualifiedNameMap* case_map = nullptr;
if (!case_map) {
case_map = new PrefixedNameToQualifiedNameMap;
- std::unique_ptr<const SVGQualifiedName* []> svg_tags =
- SVGNames::getSVGTags();
- MapLoweredLocalNameToName(case_map, svg_tags.get(), SVGNames::SVGTagsCount);
+ std::unique_ptr<const SVGQualifiedName* []> svg_tags = svg_names::GetTags();
+ MapLoweredLocalNameToName(case_map, svg_tags.get(), svg_names::kTagsCount);
}
const QualifiedName& cased_name = case_map->at(token->GetName());
@@ -492,13 +492,12 @@ static void AdjustAttributes(AtomicHTMLToken* token) {
// https://html.spec.whatwg.org/multipage/parsing.html#adjust-svg-attributes
static void AdjustSVGAttributes(AtomicHTMLToken* token) {
- AdjustAttributes<SVGNames::getSVGAttrs, SVGNames::SVGAttrsCount>(token);
+ AdjustAttributes<svg_names::GetAttrs, svg_names::kAttrsCount>(token);
}
// https://html.spec.whatwg.org/multipage/parsing.html#adjust-mathml-attributes
static void AdjustMathMLAttributes(AtomicHTMLToken* token) {
- AdjustAttributes<MathMLNames::getMathMLAttrs, MathMLNames::MathMLAttrsCount>(
- token);
+ AdjustAttributes<mathml_names::GetAttrs, mathml_names::kAttrsCount>(token);
}
static void AddNamesWithPrefix(PrefixedNameToQualifiedNameMap* map,
@@ -519,19 +518,17 @@ static void AdjustForeignAttributes(AtomicHTMLToken* token) {
if (!map) {
map = new PrefixedNameToQualifiedNameMap;
- std::unique_ptr<const QualifiedName* []> attrs =
- XLinkNames::getXLinkAttrs();
+ std::unique_ptr<const QualifiedName* []> attrs = xlink_names::GetAttrs();
AddNamesWithPrefix(map, g_xlink_atom, attrs.get(),
- XLinkNames::XLinkAttrsCount);
+ xlink_names::kAttrsCount);
- std::unique_ptr<const QualifiedName* []> xml_attrs =
- XMLNames::getXMLAttrs();
+ std::unique_ptr<const QualifiedName* []> xml_attrs = xml_names::GetAttrs();
AddNamesWithPrefix(map, g_xml_atom, xml_attrs.get(),
- XMLNames::XMLAttrsCount);
+ xml_names::kAttrsCount);
- map->insert(WTF::g_xmlns_atom, XMLNSNames::xmlnsAttr);
+ map->insert(WTF::g_xmlns_atom, xmlns_names::kXmlnsAttr);
map->insert("xmlns:xlink", QualifiedName(g_xmlns_atom, g_xlink_atom,
- XMLNSNames::xmlnsNamespaceURI));
+ xmlns_names::kNamespaceURI));
}
for (unsigned i = 0; i < token->Attributes().size(); ++i) {
@@ -544,21 +541,21 @@ static void AdjustForeignAttributes(AtomicHTMLToken* token) {
void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kStartTag);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == baseTag || token->GetName() == basefontTag ||
- token->GetName() == bgsoundTag || token->GetName() == commandTag ||
- token->GetName() == linkTag || token->GetName() == metaTag ||
- token->GetName() == noframesTag || token->GetName() == scriptTag ||
- token->GetName() == styleTag || token->GetName() == titleTag ||
- token->GetName() == templateTag) {
+ if (token->GetName() == kBaseTag || token->GetName() == kBasefontTag ||
+ token->GetName() == kBgsoundTag || token->GetName() == kCommandTag ||
+ token->GetName() == kLinkTag || token->GetName() == kMetaTag ||
+ token->GetName() == kNoframesTag || token->GetName() == kScriptTag ||
+ token->GetName() == kStyleTag || token->GetName() == kTitleTag ||
+ token->GetName() == kTemplateTag) {
bool did_process = ProcessStartTagForInHead(token);
DCHECK(did_process);
return;
}
- if (token->GetName() == bodyTag) {
+ if (token->GetName() == kBodyTag) {
ParseError(token);
if (!tree_.OpenElements()->SecondElementIsHTMLBodyElement() ||
tree_.OpenElements()->HasOnlyOneElement() ||
@@ -570,7 +567,7 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
tree_.InsertHTMLBodyStartTagInBody(token);
return;
}
- if (token->GetName() == framesetTag) {
+ if (token->GetName() == kFramesetTag) {
ParseError(token);
if (!tree_.OpenElements()->SecondElementIsHTMLBodyElement() ||
tree_.OpenElements()->HasOnlyOneElement()) {
@@ -594,18 +591,18 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
SetInsertionMode(kInFramesetMode);
return;
}
- if (token->GetName() == addressTag || token->GetName() == articleTag ||
- token->GetName() == asideTag || token->GetName() == blockquoteTag ||
- token->GetName() == centerTag || token->GetName() == detailsTag ||
- token->GetName() == dirTag || token->GetName() == divTag ||
- token->GetName() == dlTag || token->GetName() == fieldsetTag ||
- token->GetName() == figcaptionTag || token->GetName() == figureTag ||
- token->GetName() == footerTag || token->GetName() == headerTag ||
- token->GetName() == hgroupTag || token->GetName() == mainTag ||
- token->GetName() == menuTag || token->GetName() == navTag ||
- token->GetName() == olTag || token->GetName() == pTag ||
- token->GetName() == sectionTag || token->GetName() == summaryTag ||
- token->GetName() == ulTag) {
+ if (token->GetName() == kAddressTag || token->GetName() == kArticleTag ||
+ token->GetName() == kAsideTag || token->GetName() == kBlockquoteTag ||
+ token->GetName() == kCenterTag || token->GetName() == kDetailsTag ||
+ token->GetName() == kDirTag || token->GetName() == kDivTag ||
+ token->GetName() == kDlTag || token->GetName() == kFieldsetTag ||
+ token->GetName() == kFigcaptionTag || token->GetName() == kFigureTag ||
+ token->GetName() == kFooterTag || token->GetName() == kHeaderTag ||
+ token->GetName() == kHgroupTag || token->GetName() == kMainTag ||
+ token->GetName() == kMenuTag || token->GetName() == kNavTag ||
+ token->GetName() == kOlTag || token->GetName() == kPTag ||
+ token->GetName() == kSectionTag || token->GetName() == kSummaryTag ||
+ token->GetName() == kUlTag) {
ProcessFakePEndTagIfPInButtonScope();
tree_.InsertHTMLElement(token);
return;
@@ -619,14 +616,14 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == preTag || token->GetName() == listingTag) {
+ if (token->GetName() == kPreTag || token->GetName() == kListingTag) {
ProcessFakePEndTagIfPInButtonScope();
tree_.InsertHTMLElement(token);
should_skip_leading_newline_ = true;
frameset_ok_ = false;
return;
}
- if (token->GetName() == formTag) {
+ if (token->GetName() == kFormTag) {
if (tree_.IsFormElementPointerNonNull() && !IsParsingTemplateContents()) {
ParseError(token);
UseCounter::Count(tree_.CurrentNode()->GetDocument(),
@@ -637,25 +634,25 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
tree_.InsertHTMLFormElement(token);
return;
}
- if (token->GetName() == liTag) {
+ if (token->GetName() == kLiTag) {
ProcessCloseWhenNestedTag<IsLi>(token);
return;
}
- if (token->GetName() == ddTag || token->GetName() == dtTag) {
+ if (token->GetName() == kDdTag || token->GetName() == kDtTag) {
ProcessCloseWhenNestedTag<IsDdOrDt>(token);
return;
}
- if (token->GetName() == plaintextTag) {
+ if (token->GetName() == kPlaintextTag) {
ProcessFakePEndTagIfPInButtonScope();
tree_.InsertHTMLElement(token);
if (parser_->Tokenizer())
parser_->Tokenizer()->SetState(HTMLTokenizer::kPLAINTEXTState);
return;
}
- if (token->GetName() == buttonTag) {
- if (tree_.OpenElements()->InScope(buttonTag)) {
+ if (token->GetName() == kButtonTag) {
+ if (tree_.OpenElements()->InScope(kButtonTag)) {
ParseError(token);
- ProcessFakeEndTag(buttonTag);
+ ProcessFakeEndTag(kButtonTag);
ProcessStartTag(token); // FIXME: Could we just fall through here?
return;
}
@@ -664,13 +661,13 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
frameset_ok_ = false;
return;
}
- if (token->GetName() == aTag) {
+ if (token->GetName() == kATag) {
Element* active_a_tag =
tree_.ActiveFormattingElements()->ClosestElementInScopeWithName(
- aTag.LocalName());
+ kATag.LocalName());
if (active_a_tag) {
ParseError(token);
- ProcessFakeEndTag(aTag);
+ ProcessFakeEndTag(kATag);
tree_.ActiveFormattingElements()->Remove(active_a_tag);
if (tree_.OpenElements()->Contains(active_a_tag))
tree_.OpenElements()->Remove(active_a_tag);
@@ -684,56 +681,56 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
tree_.InsertFormattingElement(token);
return;
}
- if (token->GetName() == nobrTag) {
+ if (token->GetName() == kNobrTag) {
tree_.ReconstructTheActiveFormattingElements();
- if (tree_.OpenElements()->InScope(nobrTag)) {
+ if (tree_.OpenElements()->InScope(kNobrTag)) {
ParseError(token);
- ProcessFakeEndTag(nobrTag);
+ ProcessFakeEndTag(kNobrTag);
tree_.ReconstructTheActiveFormattingElements();
}
tree_.InsertFormattingElement(token);
return;
}
- if (token->GetName() == appletTag || token->GetName() == embedTag ||
- token->GetName() == objectTag) {
+ if (token->GetName() == kAppletTag || token->GetName() == kEmbedTag ||
+ token->GetName() == kObjectTag) {
if (!PluginContentIsAllowed(tree_.GetParserContentPolicy()))
return;
}
- if (token->GetName() == appletTag || token->GetName() == marqueeTag ||
- token->GetName() == objectTag) {
+ if (token->GetName() == kAppletTag || token->GetName() == kMarqueeTag ||
+ token->GetName() == kObjectTag) {
tree_.ReconstructTheActiveFormattingElements();
tree_.InsertHTMLElement(token);
tree_.ActiveFormattingElements()->AppendMarker();
frameset_ok_ = false;
return;
}
- if (token->GetName() == tableTag) {
- if (!tree_.InQuirksMode() && tree_.OpenElements()->InButtonScope(pTag))
- ProcessFakeEndTag(pTag);
+ if (token->GetName() == kTableTag) {
+ if (!tree_.InQuirksMode() && tree_.OpenElements()->InButtonScope(kPTag))
+ ProcessFakeEndTag(kPTag);
tree_.InsertHTMLElement(token);
frameset_ok_ = false;
SetInsertionMode(kInTableMode);
return;
}
- if (token->GetName() == imageTag) {
+ if (token->GetName() == kImageTag) {
ParseError(token);
// Apparently we're not supposed to ask.
- token->SetName(imgTag.LocalName());
- // Note the fall through to the imgTag handling below!
+ token->SetName(kImgTag.LocalName());
+ // Note the fall through to the kImgTag handling below!
}
- if (token->GetName() == areaTag || token->GetName() == brTag ||
- token->GetName() == embedTag || token->GetName() == imgTag ||
- token->GetName() == keygenTag || token->GetName() == wbrTag) {
+ if (token->GetName() == kAreaTag || token->GetName() == kBrTag ||
+ token->GetName() == kEmbedTag || token->GetName() == kImgTag ||
+ token->GetName() == kKeygenTag || token->GetName() == kWbrTag) {
tree_.ReconstructTheActiveFormattingElements();
tree_.InsertSelfClosingHTMLElementDestroyingToken(token);
frameset_ok_ = false;
return;
}
- if (token->GetName() == inputTag) {
+ if (token->GetName() == kInputTag) {
// Per spec https://html.spec.whatwg.org/#parsing-main-inbody,
// section "A start tag whose tag name is "input""
- Attribute* type_attribute = token->GetAttributeItem(typeAttr);
+ Attribute* type_attribute = token->GetAttributeItem(kTypeAttr);
bool disable_frameset =
!type_attribute ||
!DeprecatedEqualIgnoringCase(type_attribute->Value(), "hidden");
@@ -745,18 +742,18 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
frameset_ok_ = false;
return;
}
- if (token->GetName() == paramTag || token->GetName() == sourceTag ||
- token->GetName() == trackTag) {
+ if (token->GetName() == kParamTag || token->GetName() == kSourceTag ||
+ token->GetName() == kTrackTag) {
tree_.InsertSelfClosingHTMLElementDestroyingToken(token);
return;
}
- if (token->GetName() == hrTag) {
+ if (token->GetName() == kHrTag) {
ProcessFakePEndTagIfPInButtonScope();
tree_.InsertSelfClosingHTMLElementDestroyingToken(token);
frameset_ok_ = false;
return;
}
- if (token->GetName() == textareaTag) {
+ if (token->GetName() == kTextareaTag) {
tree_.InsertHTMLElement(token);
should_skip_leading_newline_ = true;
if (parser_->Tokenizer())
@@ -766,27 +763,27 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
SetInsertionMode(kTextMode);
return;
}
- if (token->GetName() == xmpTag) {
+ if (token->GetName() == kXmpTag) {
ProcessFakePEndTagIfPInButtonScope();
tree_.ReconstructTheActiveFormattingElements();
frameset_ok_ = false;
ProcessGenericRawTextStartTag(token);
return;
}
- if (token->GetName() == iframeTag) {
+ if (token->GetName() == kIFrameTag) {
frameset_ok_ = false;
ProcessGenericRawTextStartTag(token);
return;
}
- if (token->GetName() == noembedTag && options_.plugins_enabled) {
+ if (token->GetName() == kNoembedTag && options_.plugins_enabled) {
ProcessGenericRawTextStartTag(token);
return;
}
- if (token->GetName() == noscriptTag && options_.script_enabled) {
+ if (token->GetName() == kNoscriptTag && options_.script_enabled) {
ProcessGenericRawTextStartTag(token);
return;
}
- if (token->GetName() == selectTag) {
+ if (token->GetName() == kSelectTag) {
tree_.ReconstructTheActiveFormattingElements();
tree_.InsertHTMLElement(token);
frameset_ok_ = false;
@@ -799,52 +796,52 @@ void HTMLTreeBuilder::ProcessStartTagForInBody(AtomicHTMLToken* token) {
SetInsertionMode(kInSelectMode);
return;
}
- if (token->GetName() == optgroupTag || token->GetName() == optionTag) {
- if (tree_.CurrentStackItem()->HasTagName(optionTag)) {
- AtomicHTMLToken end_option(HTMLToken::kEndTag, optionTag.LocalName());
+ if (token->GetName() == kOptgroupTag || token->GetName() == kOptionTag) {
+ if (tree_.CurrentStackItem()->HasTagName(kOptionTag)) {
+ AtomicHTMLToken end_option(HTMLToken::kEndTag, kOptionTag.LocalName());
ProcessEndTag(&end_option);
}
tree_.ReconstructTheActiveFormattingElements();
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == rbTag || token->GetName() == rtcTag) {
- if (tree_.OpenElements()->InScope(rubyTag.LocalName())) {
+ if (token->GetName() == kRbTag || token->GetName() == kRTCTag) {
+ if (tree_.OpenElements()->InScope(kRubyTag.LocalName())) {
tree_.GenerateImpliedEndTags();
- if (!tree_.CurrentStackItem()->HasTagName(rubyTag))
+ if (!tree_.CurrentStackItem()->HasTagName(kRubyTag))
ParseError(token);
}
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == rtTag || token->GetName() == rpTag) {
- if (tree_.OpenElements()->InScope(rubyTag.LocalName())) {
- tree_.GenerateImpliedEndTagsWithExclusion(rtcTag.LocalName());
- if (!tree_.CurrentStackItem()->HasTagName(rubyTag) &&
- !tree_.CurrentStackItem()->HasTagName(rtcTag))
+ if (token->GetName() == kRtTag || token->GetName() == kRpTag) {
+ if (tree_.OpenElements()->InScope(kRubyTag.LocalName())) {
+ tree_.GenerateImpliedEndTagsWithExclusion(kRTCTag.LocalName());
+ if (!tree_.CurrentStackItem()->HasTagName(kRubyTag) &&
+ !tree_.CurrentStackItem()->HasTagName(kRTCTag))
ParseError(token);
}
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == MathMLNames::mathTag.LocalName()) {
+ if (token->GetName() == mathml_names::kMathTag.LocalName()) {
tree_.ReconstructTheActiveFormattingElements();
AdjustMathMLAttributes(token);
AdjustForeignAttributes(token);
- tree_.InsertForeignElement(token, MathMLNames::mathmlNamespaceURI);
+ tree_.InsertForeignElement(token, mathml_names::kNamespaceURI);
return;
}
- if (token->GetName() == SVGNames::svgTag.LocalName()) {
+ if (token->GetName() == svg_names::kSVGTag.LocalName()) {
tree_.ReconstructTheActiveFormattingElements();
AdjustSVGAttributes(token);
AdjustForeignAttributes(token);
- tree_.InsertForeignElement(token, SVGNames::svgNamespaceURI);
+ tree_.InsertForeignElement(token, svg_names::kNamespaceURI);
return;
}
if (IsCaptionColOrColgroupTag(token->GetName()) ||
- token->GetName() == frameTag || token->GetName() == headTag ||
+ token->GetName() == kFrameTag || token->GetName() == kHeadTag ||
IsTableBodyContextTag(token->GetName()) ||
- IsTableCellContextTag(token->GetName()) || token->GetName() == trTag) {
+ IsTableCellContextTag(token->GetName()) || token->GetName() == kTrTag) {
ParseError(token);
return;
}
@@ -861,7 +858,7 @@ void HTMLTreeBuilder::ProcessTemplateStartTag(AtomicHTMLToken* token) {
}
bool HTMLTreeBuilder::ProcessTemplateEndTag(AtomicHTMLToken* token) {
- DCHECK_EQ(token->GetName(), templateTag.LocalName());
+ DCHECK_EQ(token->GetName(), kTemplateTag.LocalName());
if (!tree_.OpenElements()->HasTemplateInHTMLScope()) {
DCHECK(template_insertion_modes_.IsEmpty() ||
(template_insertion_modes_.size() == 1 &&
@@ -870,9 +867,9 @@ bool HTMLTreeBuilder::ProcessTemplateEndTag(AtomicHTMLToken* token) {
return false;
}
tree_.GenerateImpliedEndTags();
- if (!tree_.CurrentStackItem()->HasTagName(templateTag))
+ if (!tree_.CurrentStackItem()->HasTagName(kTemplateTag))
ParseError(token);
- tree_.OpenElements()->PopUntilPopped(templateTag);
+ tree_.OpenElements()->PopUntilPopped(kTemplateTag);
tree_.ActiveFormattingElements()->ClearToLastMarker();
template_insertion_modes_.pop_back();
ResetInsertionModeAppropriately();
@@ -881,7 +878,7 @@ bool HTMLTreeBuilder::ProcessTemplateEndTag(AtomicHTMLToken* token) {
bool HTMLTreeBuilder::ProcessEndOfFileForInTemplateContents(
AtomicHTMLToken* token) {
- AtomicHTMLToken end_template(HTMLToken::kEndTag, templateTag.LocalName());
+ AtomicHTMLToken end_template(HTMLToken::kEndTag, kTemplateTag.LocalName());
if (!ProcessTemplateEndTag(&end_template))
return false;
@@ -913,33 +910,33 @@ HTMLStackItem* HTMLTreeBuilder::AdjustedCurrentStackItem() const {
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#close-the-cell
void HTMLTreeBuilder::CloseTheCell() {
DCHECK_EQ(GetInsertionMode(), kInCellMode);
- if (tree_.OpenElements()->InTableScope(tdTag)) {
- DCHECK(!tree_.OpenElements()->InTableScope(thTag));
- ProcessFakeEndTag(tdTag);
+ if (tree_.OpenElements()->InTableScope(kTdTag)) {
+ DCHECK(!tree_.OpenElements()->InTableScope(kThTag));
+ ProcessFakeEndTag(kTdTag);
return;
}
- DCHECK(tree_.OpenElements()->InTableScope(thTag));
- ProcessFakeEndTag(thTag);
+ DCHECK(tree_.OpenElements()->InTableScope(kThTag));
+ ProcessFakeEndTag(kThTag);
DCHECK_EQ(GetInsertionMode(), kInRowMode);
}
void HTMLTreeBuilder::ProcessStartTagForInTable(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kStartTag);
- if (token->GetName() == captionTag) {
+ if (token->GetName() == kCaptionTag) {
tree_.OpenElements()->PopUntilTableScopeMarker();
tree_.ActiveFormattingElements()->AppendMarker();
tree_.InsertHTMLElement(token);
SetInsertionMode(kInCaptionMode);
return;
}
- if (token->GetName() == colgroupTag) {
+ if (token->GetName() == kColgroupTag) {
tree_.OpenElements()->PopUntilTableScopeMarker();
tree_.InsertHTMLElement(token);
SetInsertionMode(kInColumnGroupMode);
return;
}
- if (token->GetName() == colTag) {
- ProcessFakeStartTag(colgroupTag);
+ if (token->GetName() == kColTag) {
+ ProcessFakeStartTag(kColgroupTag);
DCHECK(kInColumnGroupMode);
ProcessStartTag(token);
return;
@@ -950,13 +947,13 @@ void HTMLTreeBuilder::ProcessStartTagForInTable(AtomicHTMLToken* token) {
SetInsertionMode(kInTableBodyMode);
return;
}
- if (IsTableCellContextTag(token->GetName()) || token->GetName() == trTag) {
- ProcessFakeStartTag(tbodyTag);
+ if (IsTableCellContextTag(token->GetName()) || token->GetName() == kTrTag) {
+ ProcessFakeStartTag(kTbodyTag);
DCHECK_EQ(GetInsertionMode(), kInTableBodyMode);
ProcessStartTag(token);
return;
}
- if (token->GetName() == tableTag) {
+ if (token->GetName() == kTableTag) {
ParseError(token);
if (!ProcessTableEndTagForInTable()) {
DCHECK(IsParsingFragmentOrTemplateContents());
@@ -965,12 +962,12 @@ void HTMLTreeBuilder::ProcessStartTagForInTable(AtomicHTMLToken* token) {
ProcessStartTag(token);
return;
}
- if (token->GetName() == styleTag || token->GetName() == scriptTag) {
+ if (token->GetName() == kStyleTag || token->GetName() == kScriptTag) {
ProcessStartTagForInHead(token);
return;
}
- if (token->GetName() == inputTag) {
- Attribute* type_attribute = token->GetAttributeItem(typeAttr);
+ if (token->GetName() == kInputTag) {
+ Attribute* type_attribute = token->GetAttributeItem(kTypeAttr);
if (type_attribute &&
DeprecatedEqualIgnoringCase(type_attribute->Value(), "hidden")) {
ParseError(token);
@@ -979,7 +976,7 @@ void HTMLTreeBuilder::ProcessStartTagForInTable(AtomicHTMLToken* token) {
}
// Fall through to "anything else" case.
}
- if (token->GetName() == formTag) {
+ if (token->GetName() == kFormTag) {
ParseError(token);
if (tree_.IsFormElementPointerNonNull() && !IsParsingTemplateContents())
return;
@@ -987,7 +984,7 @@ void HTMLTreeBuilder::ProcessStartTagForInTable(AtomicHTMLToken* token) {
tree_.OpenElements()->Pop();
return;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateStartTag(token);
return;
}
@@ -1005,7 +1002,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
FALLTHROUGH;
case kBeforeHTMLMode:
DCHECK_EQ(GetInsertionMode(), kBeforeHTMLMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
tree_.InsertHTMLHtmlStartTagBeforeHTML(token);
SetInsertionMode(kBeforeHeadMode);
return;
@@ -1014,11 +1011,11 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
FALLTHROUGH;
case kBeforeHeadMode:
DCHECK_EQ(GetInsertionMode(), kBeforeHeadMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == headTag) {
+ if (token->GetName() == kHeadTag) {
tree_.InsertHTMLHeadElement(token);
SetInsertionMode(kInHeadMode);
return;
@@ -1033,26 +1030,26 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
FALLTHROUGH;
case kAfterHeadMode:
DCHECK_EQ(GetInsertionMode(), kAfterHeadMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == bodyTag) {
+ if (token->GetName() == kBodyTag) {
frameset_ok_ = false;
tree_.InsertHTMLBodyElement(token);
SetInsertionMode(kInBodyMode);
return;
}
- if (token->GetName() == framesetTag) {
+ if (token->GetName() == kFramesetTag) {
tree_.InsertHTMLElement(token);
SetInsertionMode(kInFramesetMode);
return;
}
- if (token->GetName() == baseTag || token->GetName() == basefontTag ||
- token->GetName() == bgsoundTag || token->GetName() == linkTag ||
- token->GetName() == metaTag || token->GetName() == noframesTag ||
- token->GetName() == scriptTag || token->GetName() == styleTag ||
- token->GetName() == templateTag || token->GetName() == titleTag) {
+ if (token->GetName() == kBaseTag || token->GetName() == kBasefontTag ||
+ token->GetName() == kBgsoundTag || token->GetName() == kLinkTag ||
+ token->GetName() == kMetaTag || token->GetName() == kNoframesTag ||
+ token->GetName() == kScriptTag || token->GetName() == kStyleTag ||
+ token->GetName() == kTemplateTag || token->GetName() == kTitleTag) {
ParseError(token);
DCHECK(tree_.Head());
tree_.OpenElements()->PushHTMLHeadElement(tree_.HeadStackItem());
@@ -1060,7 +1057,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
tree_.OpenElements()->RemoveHTMLHeadElement(tree_.Head());
return;
}
- if (token->GetName() == headTag) {
+ if (token->GetName() == kHeadTag) {
ParseError(token);
return;
}
@@ -1079,7 +1076,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
if (IsCaptionColOrColgroupTag(token->GetName()) ||
IsTableBodyContextTag(token->GetName()) ||
IsTableCellContextTag(token->GetName()) ||
- token->GetName() == trTag) {
+ token->GetName() == kTrTag) {
ParseError(token);
if (!ProcessCaptionEndTagForInCaption()) {
DCHECK(IsParsingFragment());
@@ -1092,15 +1089,15 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
break;
case kInColumnGroupMode:
DCHECK_EQ(GetInsertionMode(), kInColumnGroupMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == colTag) {
+ if (token->GetName() == kColTag) {
tree_.InsertSelfClosingHTMLElementDestroyingToken(token);
return;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateStartTag(token);
return;
}
@@ -1112,7 +1109,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
break;
case kInTableBodyMode:
DCHECK_EQ(GetInsertionMode(), kInTableBodyMode);
- if (token->GetName() == trTag) {
+ if (token->GetName() == kTrTag) {
// How is there ever anything to pop?
tree_.OpenElements()->PopUntilTableBodyScopeMarker();
tree_.InsertHTMLElement(token);
@@ -1121,7 +1118,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
}
if (IsTableCellContextTag(token->GetName())) {
ParseError(token);
- ProcessFakeStartTag(trTag);
+ ProcessFakeStartTag(kTrTag);
DCHECK_EQ(GetInsertionMode(), kInRowMode);
ProcessStartTag(token);
return;
@@ -1129,9 +1126,9 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
if (IsCaptionColOrColgroupTag(token->GetName()) ||
IsTableBodyContextTag(token->GetName())) {
// FIXME: This is slow.
- if (!tree_.OpenElements()->InTableScope(tbodyTag) &&
- !tree_.OpenElements()->InTableScope(theadTag) &&
- !tree_.OpenElements()->InTableScope(tfootTag)) {
+ if (!tree_.OpenElements()->InTableScope(kTbodyTag) &&
+ !tree_.OpenElements()->InTableScope(kTheadTag) &&
+ !tree_.OpenElements()->InTableScope(kTfootTag)) {
DCHECK(IsParsingFragmentOrTemplateContents());
ParseError(token);
return;
@@ -1153,7 +1150,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
tree_.ActiveFormattingElements()->AppendMarker();
return;
}
- if (token->GetName() == trTag ||
+ if (token->GetName() == kTrTag ||
IsCaptionColOrColgroupTag(token->GetName()) ||
IsTableBodyContextTag(token->GetName())) {
if (!ProcessTrEndTagForInRow()) {
@@ -1170,11 +1167,11 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
DCHECK_EQ(GetInsertionMode(), kInCellMode);
if (IsCaptionColOrColgroupTag(token->GetName()) ||
IsTableCellContextTag(token->GetName()) ||
- token->GetName() == trTag ||
+ token->GetName() == kTrTag ||
IsTableBodyContextTag(token->GetName())) {
// FIXME: This could be more efficient.
- if (!tree_.OpenElements()->InTableScope(tdTag) &&
- !tree_.OpenElements()->InTableScope(thTag)) {
+ if (!tree_.OpenElements()->InTableScope(kTdTag) &&
+ !tree_.OpenElements()->InTableScope(kThTag)) {
DCHECK(IsParsingFragment());
ParseError(token);
return;
@@ -1189,7 +1186,7 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
case kAfterAfterBodyMode:
DCHECK(GetInsertionMode() == kAfterBodyMode ||
GetInsertionMode() == kAfterAfterBodyMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
@@ -1198,18 +1195,18 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
break;
case kInHeadNoscriptMode:
DCHECK_EQ(GetInsertionMode(), kInHeadNoscriptMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == basefontTag || token->GetName() == bgsoundTag ||
- token->GetName() == linkTag || token->GetName() == metaTag ||
- token->GetName() == noframesTag || token->GetName() == styleTag) {
+ if (token->GetName() == kBasefontTag || token->GetName() == kBgsoundTag ||
+ token->GetName() == kLinkTag || token->GetName() == kMetaTag ||
+ token->GetName() == kNoframesTag || token->GetName() == kStyleTag) {
bool did_process = ProcessStartTagForInHead(token);
DCHECK(did_process);
return;
}
- if (token->GetName() == htmlTag || token->GetName() == noscriptTag) {
+ if (token->GetName() == kHTMLTag || token->GetName() == kNoscriptTag) {
ParseError(token);
return;
}
@@ -1218,19 +1215,19 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
break;
case kInFramesetMode:
DCHECK_EQ(GetInsertionMode(), kInFramesetMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == framesetTag) {
+ if (token->GetName() == kFramesetTag) {
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == frameTag) {
+ if (token->GetName() == kFrameTag) {
tree_.InsertSelfClosingHTMLElementDestroyingToken(token);
return;
}
- if (token->GetName() == noframesTag) {
+ if (token->GetName() == kNoframesTag) {
ProcessStartTagForInHead(token);
return;
}
@@ -1240,11 +1237,11 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
case kAfterAfterFramesetMode:
DCHECK(GetInsertionMode() == kAfterFramesetMode ||
GetInsertionMode() == kAfterAfterFramesetMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == noframesTag) {
+ if (token->GetName() == kNoframesTag) {
ProcessStartTagForInHead(token);
return;
}
@@ -1252,12 +1249,12 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
break;
case kInSelectInTableMode:
DCHECK_EQ(GetInsertionMode(), kInSelectInTableMode);
- if (token->GetName() == captionTag || token->GetName() == tableTag ||
+ if (token->GetName() == kCaptionTag || token->GetName() == kTableTag ||
IsTableBodyContextTag(token->GetName()) ||
- token->GetName() == trTag ||
+ token->GetName() == kTrTag ||
IsTableCellContextTag(token->GetName())) {
ParseError(token);
- AtomicHTMLToken end_select(HTMLToken::kEndTag, selectTag.LocalName());
+ AtomicHTMLToken end_select(HTMLToken::kEndTag, kSelectTag.LocalName());
ProcessEndTag(&end_select);
ProcessStartTag(token);
return;
@@ -1266,55 +1263,57 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
case kInSelectMode:
DCHECK(GetInsertionMode() == kInSelectMode ||
GetInsertionMode() == kInSelectInTableMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return;
}
- if (token->GetName() == optionTag) {
- if (tree_.CurrentStackItem()->HasTagName(optionTag)) {
- AtomicHTMLToken end_option(HTMLToken::kEndTag, optionTag.LocalName());
+ if (token->GetName() == kOptionTag) {
+ if (tree_.CurrentStackItem()->HasTagName(kOptionTag)) {
+ AtomicHTMLToken end_option(HTMLToken::kEndTag,
+ kOptionTag.LocalName());
ProcessEndTag(&end_option);
}
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == optgroupTag) {
- if (tree_.CurrentStackItem()->HasTagName(optionTag)) {
- AtomicHTMLToken end_option(HTMLToken::kEndTag, optionTag.LocalName());
+ if (token->GetName() == kOptgroupTag) {
+ if (tree_.CurrentStackItem()->HasTagName(kOptionTag)) {
+ AtomicHTMLToken end_option(HTMLToken::kEndTag,
+ kOptionTag.LocalName());
ProcessEndTag(&end_option);
}
- if (tree_.CurrentStackItem()->HasTagName(optgroupTag)) {
+ if (tree_.CurrentStackItem()->HasTagName(kOptgroupTag)) {
AtomicHTMLToken end_optgroup(HTMLToken::kEndTag,
- optgroupTag.LocalName());
+ kOptgroupTag.LocalName());
ProcessEndTag(&end_optgroup);
}
tree_.InsertHTMLElement(token);
return;
}
- if (token->GetName() == selectTag) {
+ if (token->GetName() == kSelectTag) {
ParseError(token);
- AtomicHTMLToken end_select(HTMLToken::kEndTag, selectTag.LocalName());
+ AtomicHTMLToken end_select(HTMLToken::kEndTag, kSelectTag.LocalName());
ProcessEndTag(&end_select);
return;
}
- if (token->GetName() == inputTag || token->GetName() == keygenTag ||
- token->GetName() == textareaTag) {
+ if (token->GetName() == kInputTag || token->GetName() == kKeygenTag ||
+ token->GetName() == kTextareaTag) {
ParseError(token);
- if (!tree_.OpenElements()->InSelectScope(selectTag)) {
+ if (!tree_.OpenElements()->InSelectScope(kSelectTag)) {
DCHECK(IsParsingFragment());
return;
}
- AtomicHTMLToken end_select(HTMLToken::kEndTag, selectTag.LocalName());
+ AtomicHTMLToken end_select(HTMLToken::kEndTag, kSelectTag.LocalName());
ProcessEndTag(&end_select);
ProcessStartTag(token);
return;
}
- if (token->GetName() == scriptTag) {
+ if (token->GetName() == kScriptTag) {
bool did_process = ProcessStartTagForInHead(token);
DCHECK(did_process);
return;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateStartTag(token);
return;
}
@@ -1327,24 +1326,24 @@ void HTMLTreeBuilder::ProcessStartTag(AtomicHTMLToken* token) {
NOTREACHED();
break;
case kTemplateContentsMode:
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateStartTag(token);
return;
}
- if (token->GetName() == linkTag || token->GetName() == scriptTag ||
- token->GetName() == styleTag || token->GetName() == metaTag) {
+ if (token->GetName() == kLinkTag || token->GetName() == kScriptTag ||
+ token->GetName() == kStyleTag || token->GetName() == kMetaTag) {
ProcessStartTagForInHead(token);
return;
}
InsertionMode insertion_mode = kTemplateContentsMode;
- if (token->GetName() == colTag)
+ if (token->GetName() == kColTag)
insertion_mode = kInColumnGroupMode;
else if (IsCaptionColOrColgroupTag(token->GetName()) ||
IsTableBodyContextTag(token->GetName()))
insertion_mode = kInTableMode;
- else if (token->GetName() == trTag)
+ else if (token->GetName() == kTrTag)
insertion_mode = kInTableBodyMode;
else if (IsTableCellContextTag(token->GetName()))
insertion_mode = kInRowMode;
@@ -1372,8 +1371,8 @@ void HTMLTreeBuilder::ProcessHtmlStartTagForInBody(AtomicHTMLToken* token) {
bool HTMLTreeBuilder::ProcessBodyEndTagForInBody(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kEndTag);
- DCHECK(token->GetName() == bodyTag);
- if (!tree_.OpenElements()->InScope(bodyTag.LocalName())) {
+ DCHECK(token->GetName() == kBodyTag);
+ if (!tree_.OpenElements()->InScope(kBodyTag.LocalName())) {
ParseError(token);
return false;
}
@@ -1525,46 +1524,46 @@ void HTMLTreeBuilder::ResetInsertionModeAppropriately() {
if (IsParsingFragment())
item = fragment_context_.ContextElementStackItem();
}
- if (item->HasTagName(templateTag))
+ if (item->HasTagName(kTemplateTag))
return SetInsertionMode(template_insertion_modes_.back());
- if (item->HasTagName(selectTag)) {
+ if (item->HasTagName(kSelectTag)) {
if (!last) {
while (item->GetNode() != tree_.OpenElements()->RootNode() &&
- !item->HasTagName(templateTag)) {
+ !item->HasTagName(kTemplateTag)) {
node_record = node_record->Next();
item = node_record->StackItem();
- if (item->HasTagName(tableTag))
+ if (item->HasTagName(kTableTag))
return SetInsertionMode(kInSelectInTableMode);
}
}
return SetInsertionMode(kInSelectMode);
}
- if (item->HasTagName(tdTag) || item->HasTagName(thTag))
+ if (item->HasTagName(kTdTag) || item->HasTagName(kThTag))
return SetInsertionMode(kInCellMode);
- if (item->HasTagName(trTag))
+ if (item->HasTagName(kTrTag))
return SetInsertionMode(kInRowMode);
- if (item->HasTagName(tbodyTag) || item->HasTagName(theadTag) ||
- item->HasTagName(tfootTag))
+ if (item->HasTagName(kTbodyTag) || item->HasTagName(kTheadTag) ||
+ item->HasTagName(kTfootTag))
return SetInsertionMode(kInTableBodyMode);
- if (item->HasTagName(captionTag))
+ if (item->HasTagName(kCaptionTag))
return SetInsertionMode(kInCaptionMode);
- if (item->HasTagName(colgroupTag)) {
+ if (item->HasTagName(kColgroupTag)) {
return SetInsertionMode(kInColumnGroupMode);
}
- if (item->HasTagName(tableTag))
+ if (item->HasTagName(kTableTag))
return SetInsertionMode(kInTableMode);
- if (item->HasTagName(headTag)) {
+ if (item->HasTagName(kHeadTag)) {
if (!fragment_context_.Fragment() ||
fragment_context_.ContextElement() != item->GetNode())
return SetInsertionMode(kInHeadMode);
return SetInsertionMode(kInBodyMode);
}
- if (item->HasTagName(bodyTag))
+ if (item->HasTagName(kBodyTag))
return SetInsertionMode(kInBodyMode);
- if (item->HasTagName(framesetTag)) {
+ if (item->HasTagName(kFramesetTag)) {
return SetInsertionMode(kInFramesetMode);
}
- if (item->HasTagName(htmlTag)) {
+ if (item->HasTagName(kHTMLTag)) {
if (tree_.HeadStackItem())
return SetInsertionMode(kAfterHeadMode);
@@ -1591,11 +1590,11 @@ void HTMLTreeBuilder::ProcessEndTagForInTableBody(AtomicHTMLToken* token) {
SetInsertionMode(kInTableMode);
return;
}
- if (token->GetName() == tableTag) {
+ if (token->GetName() == kTableTag) {
// FIXME: This is slow.
- if (!tree_.OpenElements()->InTableScope(tbodyTag) &&
- !tree_.OpenElements()->InTableScope(theadTag) &&
- !tree_.OpenElements()->InTableScope(tfootTag)) {
+ if (!tree_.OpenElements()->InTableScope(kTbodyTag) &&
+ !tree_.OpenElements()->InTableScope(kTheadTag) &&
+ !tree_.OpenElements()->InTableScope(kTfootTag)) {
DCHECK(IsParsingFragmentOrTemplateContents());
ParseError(token);
return;
@@ -1606,10 +1605,10 @@ void HTMLTreeBuilder::ProcessEndTagForInTableBody(AtomicHTMLToken* token) {
ProcessEndTag(token);
return;
}
- if (token->GetName() == bodyTag ||
+ if (token->GetName() == kBodyTag ||
IsCaptionColOrColgroupTag(token->GetName()) ||
- token->GetName() == htmlTag || IsTableCellContextTag(token->GetName()) ||
- token->GetName() == trTag) {
+ token->GetName() == kHTMLTag || IsTableCellContextTag(token->GetName()) ||
+ token->GetName() == kTrTag) {
ParseError(token);
return;
}
@@ -1618,11 +1617,11 @@ void HTMLTreeBuilder::ProcessEndTagForInTableBody(AtomicHTMLToken* token) {
void HTMLTreeBuilder::ProcessEndTagForInRow(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kEndTag);
- if (token->GetName() == trTag) {
+ if (token->GetName() == kTrTag) {
ProcessTrEndTagForInRow();
return;
}
- if (token->GetName() == tableTag) {
+ if (token->GetName() == kTableTag) {
if (!ProcessTrEndTagForInRow()) {
DCHECK(IsParsingFragmentOrTemplateContents());
return;
@@ -1636,14 +1635,14 @@ void HTMLTreeBuilder::ProcessEndTagForInRow(AtomicHTMLToken* token) {
ParseError(token);
return;
}
- ProcessFakeEndTag(trTag);
+ ProcessFakeEndTag(kTrTag);
DCHECK_EQ(GetInsertionMode(), kInTableBodyMode);
ProcessEndTag(token);
return;
}
- if (token->GetName() == bodyTag ||
+ if (token->GetName() == kBodyTag ||
IsCaptionColOrColgroupTag(token->GetName()) ||
- token->GetName() == htmlTag || IsTableCellContextTag(token->GetName())) {
+ token->GetName() == kHTMLTag || IsTableCellContextTag(token->GetName())) {
ParseError(token);
return;
}
@@ -1665,17 +1664,17 @@ void HTMLTreeBuilder::ProcessEndTagForInCell(AtomicHTMLToken* token) {
SetInsertionMode(kInRowMode);
return;
}
- if (token->GetName() == bodyTag ||
+ if (token->GetName() == kBodyTag ||
IsCaptionColOrColgroupTag(token->GetName()) ||
- token->GetName() == htmlTag) {
+ token->GetName() == kHTMLTag) {
ParseError(token);
return;
}
- if (token->GetName() == tableTag || token->GetName() == trTag ||
+ if (token->GetName() == kTableTag || token->GetName() == kTrTag ||
IsTableBodyContextTag(token->GetName())) {
if (!tree_.OpenElements()->InTableScope(token->GetName())) {
DCHECK(IsTableBodyContextTag(token->GetName()) ||
- tree_.OpenElements()->InTableScope(templateTag) ||
+ tree_.OpenElements()->InTableScope(kTemplateTag) ||
IsParsingFragment());
ParseError(token);
return;
@@ -1689,29 +1688,29 @@ void HTMLTreeBuilder::ProcessEndTagForInCell(AtomicHTMLToken* token) {
void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kEndTag);
- if (token->GetName() == bodyTag) {
+ if (token->GetName() == kBodyTag) {
ProcessBodyEndTagForInBody(token);
return;
}
- if (token->GetName() == htmlTag) {
- AtomicHTMLToken end_body(HTMLToken::kEndTag, bodyTag.LocalName());
+ if (token->GetName() == kHTMLTag) {
+ AtomicHTMLToken end_body(HTMLToken::kEndTag, kBodyTag.LocalName());
if (ProcessBodyEndTagForInBody(&end_body))
ProcessEndTag(token);
return;
}
- if (token->GetName() == addressTag || token->GetName() == articleTag ||
- token->GetName() == asideTag || token->GetName() == blockquoteTag ||
- token->GetName() == buttonTag || token->GetName() == centerTag ||
- token->GetName() == detailsTag || token->GetName() == dirTag ||
- token->GetName() == divTag || token->GetName() == dlTag ||
- token->GetName() == fieldsetTag || token->GetName() == figcaptionTag ||
- token->GetName() == figureTag || token->GetName() == footerTag ||
- token->GetName() == headerTag || token->GetName() == hgroupTag ||
- token->GetName() == listingTag || token->GetName() == mainTag ||
- token->GetName() == menuTag || token->GetName() == navTag ||
- token->GetName() == olTag || token->GetName() == preTag ||
- token->GetName() == sectionTag || token->GetName() == summaryTag ||
- token->GetName() == ulTag) {
+ if (token->GetName() == kAddressTag || token->GetName() == kArticleTag ||
+ token->GetName() == kAsideTag || token->GetName() == kBlockquoteTag ||
+ token->GetName() == kButtonTag || token->GetName() == kCenterTag ||
+ token->GetName() == kDetailsTag || token->GetName() == kDirTag ||
+ token->GetName() == kDivTag || token->GetName() == kDlTag ||
+ token->GetName() == kFieldsetTag || token->GetName() == kFigcaptionTag ||
+ token->GetName() == kFigureTag || token->GetName() == kFooterTag ||
+ token->GetName() == kHeaderTag || token->GetName() == kHgroupTag ||
+ token->GetName() == kListingTag || token->GetName() == kMainTag ||
+ token->GetName() == kMenuTag || token->GetName() == kNavTag ||
+ token->GetName() == kOlTag || token->GetName() == kPreTag ||
+ token->GetName() == kSectionTag || token->GetName() == kSummaryTag ||
+ token->GetName() == kUlTag) {
if (!tree_.OpenElements()->InScope(token->GetName())) {
ParseError(token);
return;
@@ -1722,7 +1721,7 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
tree_.OpenElements()->PopUntilPopped(token->GetName());
return;
}
- if (token->GetName() == formTag && !IsParsingTemplateContents()) {
+ if (token->GetName() == kFormTag && !IsParsingTemplateContents()) {
Element* node = tree_.TakeForm();
if (!node || !tree_.OpenElements()->InScope(node)) {
ParseError(token);
@@ -1733,10 +1732,10 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
ParseError(token);
tree_.OpenElements()->Remove(node);
}
- if (token->GetName() == pTag) {
+ if (token->GetName() == kPTag) {
if (!tree_.OpenElements()->InButtonScope(token->GetName())) {
ParseError(token);
- ProcessFakeStartTag(pTag);
+ ProcessFakeStartTag(kPTag);
DCHECK(tree_.OpenElements()->InScope(token->GetName()));
ProcessEndTag(token);
return;
@@ -1747,7 +1746,7 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
tree_.OpenElements()->PopUntilPopped(token->GetName());
return;
}
- if (token->GetName() == liTag) {
+ if (token->GetName() == kLiTag) {
if (!tree_.OpenElements()->InListItemScope(token->GetName())) {
ParseError(token);
return;
@@ -1758,7 +1757,7 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
tree_.OpenElements()->PopUntilPopped(token->GetName());
return;
}
- if (token->GetName() == ddTag || token->GetName() == dtTag) {
+ if (token->GetName() == kDdTag || token->GetName() == kDtTag) {
if (!tree_.OpenElements()->InScope(token->GetName())) {
ParseError(token);
return;
@@ -1784,8 +1783,8 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
CallTheAdoptionAgency(token);
return;
}
- if (token->GetName() == appletTag || token->GetName() == marqueeTag ||
- token->GetName() == objectTag) {
+ if (token->GetName() == kAppletTag || token->GetName() == kMarqueeTag ||
+ token->GetName() == kObjectTag) {
if (!tree_.OpenElements()->InScope(token->GetName())) {
ParseError(token);
return;
@@ -1797,12 +1796,12 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
tree_.ActiveFormattingElements()->ClearToLastMarker();
return;
}
- if (token->GetName() == brTag) {
+ if (token->GetName() == kBrTag) {
ParseError(token);
- ProcessFakeStartTag(brTag);
+ ProcessFakeStartTag(kBrTag);
return;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateEndTag(token);
return;
}
@@ -1810,53 +1809,53 @@ void HTMLTreeBuilder::ProcessEndTagForInBody(AtomicHTMLToken* token) {
}
bool HTMLTreeBuilder::ProcessCaptionEndTagForInCaption() {
- if (!tree_.OpenElements()->InTableScope(captionTag.LocalName())) {
+ if (!tree_.OpenElements()->InTableScope(kCaptionTag.LocalName())) {
DCHECK(IsParsingFragment());
// FIXME: parse error
return false;
}
tree_.GenerateImpliedEndTags();
- // FIXME: parse error if (!tree_.CurrentStackItem()->HasTagName(captionTag))
- tree_.OpenElements()->PopUntilPopped(captionTag.LocalName());
+ // FIXME: parse error if (!tree_.CurrentStackItem()->HasTagName(kCaptionTag))
+ tree_.OpenElements()->PopUntilPopped(kCaptionTag.LocalName());
tree_.ActiveFormattingElements()->ClearToLastMarker();
SetInsertionMode(kInTableMode);
return true;
}
bool HTMLTreeBuilder::ProcessTrEndTagForInRow() {
- if (!tree_.OpenElements()->InTableScope(trTag)) {
+ if (!tree_.OpenElements()->InTableScope(kTrTag)) {
DCHECK(IsParsingFragmentOrTemplateContents());
// FIXME: parse error
return false;
}
tree_.OpenElements()->PopUntilTableRowScopeMarker();
- DCHECK(tree_.CurrentStackItem()->HasTagName(trTag));
+ DCHECK(tree_.CurrentStackItem()->HasTagName(kTrTag));
tree_.OpenElements()->Pop();
SetInsertionMode(kInTableBodyMode);
return true;
}
bool HTMLTreeBuilder::ProcessTableEndTagForInTable() {
- if (!tree_.OpenElements()->InTableScope(tableTag)) {
+ if (!tree_.OpenElements()->InTableScope(kTableTag)) {
DCHECK(IsParsingFragmentOrTemplateContents());
// FIXME: parse error.
return false;
}
- tree_.OpenElements()->PopUntilPopped(tableTag.LocalName());
+ tree_.OpenElements()->PopUntilPopped(kTableTag.LocalName());
ResetInsertionModeAppropriately();
return true;
}
void HTMLTreeBuilder::ProcessEndTagForInTable(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kEndTag);
- if (token->GetName() == tableTag) {
+ if (token->GetName() == kTableTag) {
ProcessTableEndTagForInTable();
return;
}
- if (token->GetName() == bodyTag ||
+ if (token->GetName() == kBodyTag ||
IsCaptionColOrColgroupTag(token->GetName()) ||
- token->GetName() == htmlTag || IsTableBodyContextTag(token->GetName()) ||
- IsTableCellContextTag(token->GetName()) || token->GetName() == trTag) {
+ token->GetName() == kHTMLTag || IsTableBodyContextTag(token->GetName()) ||
+ IsTableCellContextTag(token->GetName()) || token->GetName() == kTrTag) {
ParseError(token);
return;
}
@@ -1875,8 +1874,8 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
FALLTHROUGH;
case kBeforeHTMLMode:
DCHECK_EQ(GetInsertionMode(), kBeforeHTMLMode);
- if (token->GetName() != headTag && token->GetName() != bodyTag &&
- token->GetName() != htmlTag && token->GetName() != brTag) {
+ if (token->GetName() != kHeadTag && token->GetName() != kBodyTag &&
+ token->GetName() != kHTMLTag && token->GetName() != kBrTag) {
ParseError(token);
return;
}
@@ -1884,8 +1883,8 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
FALLTHROUGH;
case kBeforeHeadMode:
DCHECK_EQ(GetInsertionMode(), kBeforeHeadMode);
- if (token->GetName() != headTag && token->GetName() != bodyTag &&
- token->GetName() != htmlTag && token->GetName() != brTag) {
+ if (token->GetName() != kHeadTag && token->GetName() != kBodyTag &&
+ token->GetName() != kHTMLTag && token->GetName() != kBrTag) {
ParseError(token);
return;
}
@@ -1897,17 +1896,17 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
// because other end tag cases now refer to it ("process the token for
// using the rules of the "in head" insertion mode"). but because the
// logic falls through to AfterHeadMode, that gets a little messy.
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateEndTag(token);
return;
}
- if (token->GetName() == headTag) {
+ if (token->GetName() == kHeadTag) {
tree_.OpenElements()->PopHTMLHeadElement();
SetInsertionMode(kAfterHeadMode);
return;
}
- if (token->GetName() != bodyTag && token->GetName() != htmlTag &&
- token->GetName() != brTag) {
+ if (token->GetName() != kBodyTag && token->GetName() != kHTMLTag &&
+ token->GetName() != kBrTag) {
ParseError(token);
return;
}
@@ -1915,8 +1914,8 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
FALLTHROUGH;
case kAfterHeadMode:
DCHECK_EQ(GetInsertionMode(), kAfterHeadMode);
- if (token->GetName() != bodyTag && token->GetName() != htmlTag &&
- token->GetName() != brTag) {
+ if (token->GetName() != kBodyTag && token->GetName() != kHTMLTag &&
+ token->GetName() != kBrTag) {
ParseError(token);
return;
}
@@ -1932,11 +1931,11 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
break;
case kInCaptionMode:
DCHECK_EQ(GetInsertionMode(), kInCaptionMode);
- if (token->GetName() == captionTag) {
+ if (token->GetName() == kCaptionTag) {
ProcessCaptionEndTagForInCaption();
return;
}
- if (token->GetName() == tableTag) {
+ if (token->GetName() == kTableTag) {
ParseError(token);
if (!ProcessCaptionEndTagForInCaption()) {
DCHECK(IsParsingFragment());
@@ -1945,11 +1944,11 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
ProcessEndTag(token);
return;
}
- if (token->GetName() == bodyTag || token->GetName() == colTag ||
- token->GetName() == colgroupTag || token->GetName() == htmlTag ||
+ if (token->GetName() == kBodyTag || token->GetName() == kColTag ||
+ token->GetName() == kColgroupTag || token->GetName() == kHTMLTag ||
IsTableBodyContextTag(token->GetName()) ||
IsTableCellContextTag(token->GetName()) ||
- token->GetName() == trTag) {
+ token->GetName() == kTrTag) {
ParseError(token);
return;
}
@@ -1957,15 +1956,15 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
break;
case kInColumnGroupMode:
DCHECK_EQ(GetInsertionMode(), kInColumnGroupMode);
- if (token->GetName() == colgroupTag) {
+ if (token->GetName() == kColgroupTag) {
ProcessColgroupEndTagForInColumnGroup();
return;
}
- if (token->GetName() == colTag) {
+ if (token->GetName() == kColTag) {
ParseError(token);
return;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateEndTag(token);
return;
}
@@ -1989,7 +1988,7 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
break;
case kAfterBodyMode:
DCHECK_EQ(GetInsertionMode(), kAfterBodyMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
if (IsParsingFragment()) {
ParseError(token);
return;
@@ -2007,14 +2006,14 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
break;
case kInHeadNoscriptMode:
DCHECK_EQ(GetInsertionMode(), kInHeadNoscriptMode);
- if (token->GetName() == noscriptTag) {
- DCHECK(tree_.CurrentStackItem()->HasTagName(noscriptTag));
+ if (token->GetName() == kNoscriptTag) {
+ DCHECK(tree_.CurrentStackItem()->HasTagName(kNoscriptTag));
tree_.OpenElements()->Pop();
- DCHECK(tree_.CurrentStackItem()->HasTagName(headTag));
+ DCHECK(tree_.CurrentStackItem()->HasTagName(kHeadTag));
SetInsertionMode(kInHeadMode);
return;
}
- if (token->GetName() != brTag) {
+ if (token->GetName() != kBrTag) {
ParseError(token);
return;
}
@@ -2022,8 +2021,8 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
ProcessToken(token);
break;
case kTextMode:
- if (token->GetName() == scriptTag &&
- tree_.CurrentStackItem()->HasTagName(scriptTag)) {
+ if (token->GetName() == kScriptTag &&
+ tree_.CurrentStackItem()->HasTagName(kScriptTag)) {
// Pause ourselves so that parsing stops until the script can be
// processed by the caller.
if (ScriptingContentIsAllowed(tree_.GetParserContentPolicy()))
@@ -2043,7 +2042,7 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
break;
case kInFramesetMode:
DCHECK_EQ(GetInsertionMode(), kInFramesetMode);
- if (token->GetName() == framesetTag) {
+ if (token->GetName() == kFramesetTag) {
bool ignore_frameset_for_fragment_parsing = tree_.CurrentIsRootNode();
ignore_frameset_for_fragment_parsing =
ignore_frameset_for_fragment_parsing ||
@@ -2055,14 +2054,14 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
}
tree_.OpenElements()->Pop();
if (!IsParsingFragment() &&
- !tree_.CurrentStackItem()->HasTagName(framesetTag))
+ !tree_.CurrentStackItem()->HasTagName(kFramesetTag))
SetInsertionMode(kAfterFramesetMode);
return;
}
break;
case kAfterFramesetMode:
DCHECK_EQ(GetInsertionMode(), kAfterFramesetMode);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
SetInsertionMode(kAfterAfterFramesetMode);
return;
}
@@ -2074,13 +2073,14 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
break;
case kInSelectInTableMode:
DCHECK(GetInsertionMode() == kInSelectInTableMode);
- if (token->GetName() == captionTag || token->GetName() == tableTag ||
+ if (token->GetName() == kCaptionTag || token->GetName() == kTableTag ||
IsTableBodyContextTag(token->GetName()) ||
- token->GetName() == trTag ||
+ token->GetName() == kTrTag ||
IsTableCellContextTag(token->GetName())) {
ParseError(token);
if (tree_.OpenElements()->InTableScope(token->GetName())) {
- AtomicHTMLToken end_select(HTMLToken::kEndTag, selectTag.LocalName());
+ AtomicHTMLToken end_select(HTMLToken::kEndTag,
+ kSelectTag.LocalName());
ProcessEndTag(&end_select);
ProcessEndTag(token);
}
@@ -2090,36 +2090,37 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
case kInSelectMode:
DCHECK(GetInsertionMode() == kInSelectMode ||
GetInsertionMode() == kInSelectInTableMode);
- if (token->GetName() == optgroupTag) {
- if (tree_.CurrentStackItem()->HasTagName(optionTag) &&
- tree_.OneBelowTop() && tree_.OneBelowTop()->HasTagName(optgroupTag))
- ProcessFakeEndTag(optionTag);
- if (tree_.CurrentStackItem()->HasTagName(optgroupTag)) {
+ if (token->GetName() == kOptgroupTag) {
+ if (tree_.CurrentStackItem()->HasTagName(kOptionTag) &&
+ tree_.OneBelowTop() &&
+ tree_.OneBelowTop()->HasTagName(kOptgroupTag))
+ ProcessFakeEndTag(kOptionTag);
+ if (tree_.CurrentStackItem()->HasTagName(kOptgroupTag)) {
tree_.OpenElements()->Pop();
return;
}
ParseError(token);
return;
}
- if (token->GetName() == optionTag) {
- if (tree_.CurrentStackItem()->HasTagName(optionTag)) {
+ if (token->GetName() == kOptionTag) {
+ if (tree_.CurrentStackItem()->HasTagName(kOptionTag)) {
tree_.OpenElements()->Pop();
return;
}
ParseError(token);
return;
}
- if (token->GetName() == selectTag) {
+ if (token->GetName() == kSelectTag) {
if (!tree_.OpenElements()->InSelectScope(token->GetName())) {
DCHECK(IsParsingFragment());
ParseError(token);
return;
}
- tree_.OpenElements()->PopUntilPopped(selectTag.LocalName());
+ tree_.OpenElements()->PopUntilPopped(kSelectTag.LocalName());
ResetInsertionModeAppropriately();
return;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateEndTag(token);
return;
}
@@ -2129,7 +2130,7 @@ void HTMLTreeBuilder::ProcessEndTag(AtomicHTMLToken* token) {
ProcessEndTag(token);
break;
case kTemplateContentsMode:
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateEndTag(token);
return;
}
@@ -2251,11 +2252,11 @@ ReprocessBuffer:
GetInsertionMode() == kInRowMode);
DCHECK(pending_table_characters_.IsEmpty());
if (tree_.CurrentStackItem()->IsElementNode() &&
- (tree_.CurrentStackItem()->HasTagName(tableTag) ||
- tree_.CurrentStackItem()->HasTagName(tbodyTag) ||
- tree_.CurrentStackItem()->HasTagName(tfootTag) ||
- tree_.CurrentStackItem()->HasTagName(theadTag) ||
- tree_.CurrentStackItem()->HasTagName(trTag))) {
+ (tree_.CurrentStackItem()->HasTagName(kTableTag) ||
+ tree_.CurrentStackItem()->HasTagName(kTbodyTag) ||
+ tree_.CurrentStackItem()->HasTagName(kTfootTag) ||
+ tree_.CurrentStackItem()->HasTagName(kTheadTag) ||
+ tree_.CurrentStackItem()->HasTagName(kTrTag))) {
original_insertion_mode_ = insertion_mode_;
SetInsertionMode(kInTableTextMode);
// Note that we fall through to the InTableTextMode case below.
@@ -2408,7 +2409,7 @@ void HTMLTreeBuilder::ProcessEndOfFile(AtomicHTMLToken* token) {
DCHECK(IsParsingFragment());
return; // FIXME: Should we break here instead of returning?
}
- DCHECK(tree_.CurrentNode()->HasTagName(colgroupTag) ||
+ DCHECK(tree_.CurrentNode()->HasTagName(kColgroupTag) ||
IsHTMLTemplateElement(tree_.CurrentNode()));
ProcessColgroupEndTagForInColumnGroup();
FALLTHROUGH;
@@ -2435,7 +2436,7 @@ void HTMLTreeBuilder::ProcessEndOfFile(AtomicHTMLToken* token) {
return;
case kTextMode: {
ParseError(token);
- if (tree_.CurrentStackItem()->HasTagName(scriptTag)) {
+ if (tree_.CurrentStackItem()->HasTagName(kScriptTag)) {
// Mark the script element as "already started".
DVLOG(1) << "Not implemented.";
}
@@ -2464,28 +2465,28 @@ void HTMLTreeBuilder::DefaultForInitial() {
}
void HTMLTreeBuilder::DefaultForBeforeHTML() {
- AtomicHTMLToken start_html(HTMLToken::kStartTag, htmlTag.LocalName());
+ AtomicHTMLToken start_html(HTMLToken::kStartTag, kHTMLTag.LocalName());
tree_.InsertHTMLHtmlStartTagBeforeHTML(&start_html);
SetInsertionMode(kBeforeHeadMode);
}
void HTMLTreeBuilder::DefaultForBeforeHead() {
- AtomicHTMLToken start_head(HTMLToken::kStartTag, headTag.LocalName());
+ AtomicHTMLToken start_head(HTMLToken::kStartTag, kHeadTag.LocalName());
ProcessStartTag(&start_head);
}
void HTMLTreeBuilder::DefaultForInHead() {
- AtomicHTMLToken end_head(HTMLToken::kEndTag, headTag.LocalName());
+ AtomicHTMLToken end_head(HTMLToken::kEndTag, kHeadTag.LocalName());
ProcessEndTag(&end_head);
}
void HTMLTreeBuilder::DefaultForInHeadNoscript() {
- AtomicHTMLToken end_noscript(HTMLToken::kEndTag, noscriptTag.LocalName());
+ AtomicHTMLToken end_noscript(HTMLToken::kEndTag, kNoscriptTag.LocalName());
ProcessEndTag(&end_noscript);
}
void HTMLTreeBuilder::DefaultForAfterHead() {
- AtomicHTMLToken start_body(HTMLToken::kStartTag, bodyTag.LocalName());
+ AtomicHTMLToken start_body(HTMLToken::kStartTag, kBodyTag.LocalName());
ProcessStartTag(&start_body);
frameset_ok_ = true;
}
@@ -2508,23 +2509,23 @@ void HTMLTreeBuilder::DefaultForInTableText() {
bool HTMLTreeBuilder::ProcessStartTagForInHead(AtomicHTMLToken* token) {
DCHECK_EQ(token->GetType(), HTMLToken::kStartTag);
- if (token->GetName() == htmlTag) {
+ if (token->GetName() == kHTMLTag) {
ProcessHtmlStartTagForInBody(token);
return true;
}
- if (token->GetName() == baseTag || token->GetName() == basefontTag ||
- token->GetName() == bgsoundTag || token->GetName() == commandTag ||
- token->GetName() == linkTag || token->GetName() == metaTag) {
+ if (token->GetName() == kBaseTag || token->GetName() == kBasefontTag ||
+ token->GetName() == kBgsoundTag || token->GetName() == kCommandTag ||
+ token->GetName() == kLinkTag || token->GetName() == kMetaTag) {
tree_.InsertSelfClosingHTMLElementDestroyingToken(token);
// Note: The custom processing for the <meta> tag is done in
// HTMLMetaElement::process().
return true;
}
- if (token->GetName() == titleTag) {
+ if (token->GetName() == kTitleTag) {
ProcessGenericRCDATAStartTag(token);
return true;
}
- if (token->GetName() == noscriptTag) {
+ if (token->GetName() == kNoscriptTag) {
if (options_.script_enabled) {
ProcessGenericRawTextStartTag(token);
return true;
@@ -2533,19 +2534,19 @@ bool HTMLTreeBuilder::ProcessStartTagForInHead(AtomicHTMLToken* token) {
SetInsertionMode(kInHeadNoscriptMode);
return true;
}
- if (token->GetName() == noframesTag || token->GetName() == styleTag) {
+ if (token->GetName() == kNoframesTag || token->GetName() == kStyleTag) {
ProcessGenericRawTextStartTag(token);
return true;
}
- if (token->GetName() == scriptTag) {
+ if (token->GetName() == kScriptTag) {
ProcessScriptStartTag(token);
return true;
}
- if (token->GetName() == templateTag) {
+ if (token->GetName() == kTemplateTag) {
ProcessTemplateStartTag(token);
return true;
}
- if (token->GetName() == headTag) {
+ if (token->GetName() == kHeadTag) {
ParseError(token);
return true;
}
@@ -2595,15 +2596,15 @@ bool HTMLTreeBuilder::ShouldProcessTokenInForeignContent(
return false;
if (HTMLElementStack::IsMathMLTextIntegrationPoint(adjusted_current_node)) {
if (token->GetType() == HTMLToken::kStartTag &&
- token->GetName() != MathMLNames::mglyphTag &&
- token->GetName() != MathMLNames::malignmarkTag)
+ token->GetName() != mathml_names::kMglyphTag &&
+ token->GetName() != mathml_names::kMalignmarkTag)
return false;
if (token->GetType() == HTMLToken::kCharacter)
return false;
}
- if (adjusted_current_node->HasTagName(MathMLNames::annotation_xmlTag) &&
+ if (adjusted_current_node->HasTagName(mathml_names::kAnnotationXmlTag) &&
token->GetType() == HTMLToken::kStartTag &&
- token->GetName() == SVGNames::svgTag)
+ token->GetName() == svg_names::kSVGTag)
return false;
if (HTMLElementStack::IsHTMLIntegrationPoint(adjusted_current_node)) {
if (token->GetType() == HTMLToken::kStartTag)
@@ -2636,43 +2637,43 @@ void HTMLTreeBuilder::ProcessTokenInForeignContent(AtomicHTMLToken* token) {
ParseError(token);
break;
case HTMLToken::kStartTag: {
- if (token->GetName() == bTag || token->GetName() == bigTag ||
- token->GetName() == blockquoteTag || token->GetName() == bodyTag ||
- token->GetName() == brTag || token->GetName() == centerTag ||
- token->GetName() == codeTag || token->GetName() == ddTag ||
- token->GetName() == divTag || token->GetName() == dlTag ||
- token->GetName() == dtTag || token->GetName() == emTag ||
- token->GetName() == embedTag ||
+ if (token->GetName() == kBTag || token->GetName() == kBigTag ||
+ token->GetName() == kBlockquoteTag || token->GetName() == kBodyTag ||
+ token->GetName() == kBrTag || token->GetName() == kCenterTag ||
+ token->GetName() == kCodeTag || token->GetName() == kDdTag ||
+ token->GetName() == kDivTag || token->GetName() == kDlTag ||
+ token->GetName() == kDtTag || token->GetName() == kEmTag ||
+ token->GetName() == kEmbedTag ||
IsNumberedHeaderTag(token->GetName()) ||
- token->GetName() == headTag || token->GetName() == hrTag ||
- token->GetName() == iTag || token->GetName() == imgTag ||
- token->GetName() == liTag || token->GetName() == listingTag ||
- token->GetName() == menuTag || token->GetName() == metaTag ||
- token->GetName() == nobrTag || token->GetName() == olTag ||
- token->GetName() == pTag || token->GetName() == preTag ||
- token->GetName() == rubyTag || token->GetName() == sTag ||
- token->GetName() == smallTag || token->GetName() == spanTag ||
- token->GetName() == strongTag || token->GetName() == strikeTag ||
- token->GetName() == subTag || token->GetName() == supTag ||
- token->GetName() == tableTag || token->GetName() == ttTag ||
- token->GetName() == uTag || token->GetName() == ulTag ||
- token->GetName() == varTag ||
- (token->GetName() == fontTag &&
- (token->GetAttributeItem(colorAttr) ||
- token->GetAttributeItem(faceAttr) ||
- token->GetAttributeItem(sizeAttr)))) {
+ token->GetName() == kHeadTag || token->GetName() == kHrTag ||
+ token->GetName() == kITag || token->GetName() == kImgTag ||
+ token->GetName() == kLiTag || token->GetName() == kListingTag ||
+ token->GetName() == kMenuTag || token->GetName() == kMetaTag ||
+ token->GetName() == kNobrTag || token->GetName() == kOlTag ||
+ token->GetName() == kPTag || token->GetName() == kPreTag ||
+ token->GetName() == kRubyTag || token->GetName() == kSTag ||
+ token->GetName() == kSmallTag || token->GetName() == kSpanTag ||
+ token->GetName() == kStrongTag || token->GetName() == kStrikeTag ||
+ token->GetName() == kSubTag || token->GetName() == kSupTag ||
+ token->GetName() == kTableTag || token->GetName() == kTtTag ||
+ token->GetName() == kUTag || token->GetName() == kUlTag ||
+ token->GetName() == kVarTag ||
+ (token->GetName() == kFontTag &&
+ (token->GetAttributeItem(kColorAttr) ||
+ token->GetAttributeItem(kFaceAttr) ||
+ token->GetAttributeItem(kSizeAttr)))) {
ParseError(token);
tree_.OpenElements()->PopUntilForeignContentScopeMarker();
ProcessStartTag(token);
return;
- } else if (token->GetName() == scriptTag) {
- script_to_process_start_position_ = parser_->GetTextPosition();
}
+ if (token->GetName() == kScriptTag)
+ script_to_process_start_position_ = parser_->GetTextPosition();
const AtomicString& current_namespace =
adjusted_current_node->NamespaceURI();
- if (current_namespace == MathMLNames::mathmlNamespaceURI)
+ if (current_namespace == mathml_names::kNamespaceURI)
AdjustMathMLAttributes(token);
- if (current_namespace == SVGNames::svgNamespaceURI) {
+ if (current_namespace == svg_names::kNamespaceURI) {
AdjustSVGTagNameCase(token);
AdjustSVGAttributes(token);
}
@@ -2681,11 +2682,11 @@ void HTMLTreeBuilder::ProcessTokenInForeignContent(AtomicHTMLToken* token) {
break;
}
case HTMLToken::kEndTag: {
- if (adjusted_current_node->NamespaceURI() == SVGNames::svgNamespaceURI)
+ if (adjusted_current_node->NamespaceURI() == svg_names::kNamespaceURI)
AdjustSVGTagNameCase(token);
- if (token->GetName() == SVGNames::scriptTag &&
- tree_.CurrentStackItem()->HasTagName(SVGNames::scriptTag)) {
+ if (token->GetName() == svg_names::kScriptTag &&
+ tree_.CurrentStackItem()->HasTagName(svg_names::kScriptTag)) {
if (ScriptingContentIsAllowed(tree_.GetParserContentPolicy()))
script_to_process_ = tree_.CurrentElement();
tree_.OpenElements()->Pop();
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.h b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.h
index 5cc33fd0a98..8615b67c5fa 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.h
@@ -56,17 +56,27 @@ class HTMLTreeBuilder final
Document& document,
ParserContentPolicy parser_content_policy,
const HTMLParserOptions& options) {
- return new HTMLTreeBuilder(parser, document, parser_content_policy,
- options);
+ return MakeGarbageCollected<HTMLTreeBuilder>(
+ parser, document, parser_content_policy, options);
}
static HTMLTreeBuilder* Create(HTMLDocumentParser* parser,
DocumentFragment* fragment,
Element* context_element,
ParserContentPolicy parser_content_policy,
const HTMLParserOptions& options) {
- return new HTMLTreeBuilder(parser, fragment, context_element,
- parser_content_policy, options);
+ return MakeGarbageCollected<HTMLTreeBuilder>(
+ parser, fragment, context_element, parser_content_policy, options);
}
+
+ HTMLTreeBuilder(HTMLDocumentParser*,
+ Document&,
+ ParserContentPolicy,
+ const HTMLParserOptions&);
+ HTMLTreeBuilder(HTMLDocumentParser*,
+ DocumentFragment*,
+ Element* context_element,
+ ParserContentPolicy,
+ const HTMLParserOptions&);
~HTMLTreeBuilder();
void Trace(blink::Visitor*);
@@ -133,16 +143,6 @@ class HTMLTreeBuilder final
static const char* ToString(InsertionMode);
#endif
- HTMLTreeBuilder(HTMLDocumentParser*,
- Document&,
- ParserContentPolicy,
- const HTMLParserOptions&);
- HTMLTreeBuilder(HTMLDocumentParser*,
- DocumentFragment*,
- Element* context_element,
- ParserContentPolicy,
- const HTMLParserOptions&);
-
void ProcessToken(AtomicHTMLToken*);
void ProcessDoctypeToken(AtomicHTMLToken*);
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.cc b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.cc
index 0d84be7f033..2bfaf2be20e 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.cc
@@ -25,6 +25,7 @@
#include "third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/parser/html_tokenizer.h"
#include "third_party/blink/renderer/core/html/parser/html_tree_builder.h"
@@ -35,71 +36,79 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool TokenExitsForeignContent(const CompactHTMLToken& token) {
// FIXME: This is copied from HTMLTreeBuilder::processTokenInForeignContent
// and changed to use threadSafeHTMLNamesMatch.
const String& tag_name = token.Data();
- return ThreadSafeMatch(tag_name, bTag) || ThreadSafeMatch(tag_name, bigTag) ||
- ThreadSafeMatch(tag_name, blockquoteTag) ||
- ThreadSafeMatch(tag_name, bodyTag) ||
- ThreadSafeMatch(tag_name, brTag) ||
- ThreadSafeMatch(tag_name, centerTag) ||
- ThreadSafeMatch(tag_name, codeTag) ||
- ThreadSafeMatch(tag_name, ddTag) ||
- ThreadSafeMatch(tag_name, divTag) ||
- ThreadSafeMatch(tag_name, dlTag) || ThreadSafeMatch(tag_name, dtTag) ||
- ThreadSafeMatch(tag_name, emTag) ||
- ThreadSafeMatch(tag_name, embedTag) ||
- ThreadSafeMatch(tag_name, h1Tag) || ThreadSafeMatch(tag_name, h2Tag) ||
- ThreadSafeMatch(tag_name, h3Tag) || ThreadSafeMatch(tag_name, h4Tag) ||
- ThreadSafeMatch(tag_name, h5Tag) || ThreadSafeMatch(tag_name, h6Tag) ||
- ThreadSafeMatch(tag_name, headTag) ||
- ThreadSafeMatch(tag_name, hrTag) || ThreadSafeMatch(tag_name, iTag) ||
- ThreadSafeMatch(tag_name, imgTag) ||
- ThreadSafeMatch(tag_name, liTag) ||
- ThreadSafeMatch(tag_name, listingTag) ||
- ThreadSafeMatch(tag_name, menuTag) ||
- ThreadSafeMatch(tag_name, metaTag) ||
- ThreadSafeMatch(tag_name, nobrTag) ||
- ThreadSafeMatch(tag_name, olTag) || ThreadSafeMatch(tag_name, pTag) ||
- ThreadSafeMatch(tag_name, preTag) ||
- ThreadSafeMatch(tag_name, rubyTag) ||
- ThreadSafeMatch(tag_name, sTag) ||
- ThreadSafeMatch(tag_name, smallTag) ||
- ThreadSafeMatch(tag_name, spanTag) ||
- ThreadSafeMatch(tag_name, strongTag) ||
- ThreadSafeMatch(tag_name, strikeTag) ||
- ThreadSafeMatch(tag_name, subTag) ||
- ThreadSafeMatch(tag_name, supTag) ||
- ThreadSafeMatch(tag_name, tableTag) ||
- ThreadSafeMatch(tag_name, ttTag) || ThreadSafeMatch(tag_name, uTag) ||
- ThreadSafeMatch(tag_name, ulTag) ||
- ThreadSafeMatch(tag_name, varTag) ||
- (ThreadSafeMatch(tag_name, fontTag) &&
- (token.GetAttributeItem(colorAttr) ||
- token.GetAttributeItem(faceAttr) ||
- token.GetAttributeItem(sizeAttr)));
+ return ThreadSafeMatch(tag_name, kBTag) ||
+ ThreadSafeMatch(tag_name, kBigTag) ||
+ ThreadSafeMatch(tag_name, kBlockquoteTag) ||
+ ThreadSafeMatch(tag_name, kBodyTag) ||
+ ThreadSafeMatch(tag_name, kBrTag) ||
+ ThreadSafeMatch(tag_name, kCenterTag) ||
+ ThreadSafeMatch(tag_name, kCodeTag) ||
+ ThreadSafeMatch(tag_name, kDdTag) ||
+ ThreadSafeMatch(tag_name, kDivTag) ||
+ ThreadSafeMatch(tag_name, kDlTag) ||
+ ThreadSafeMatch(tag_name, kDtTag) ||
+ ThreadSafeMatch(tag_name, kEmTag) ||
+ ThreadSafeMatch(tag_name, kEmbedTag) ||
+ ThreadSafeMatch(tag_name, kH1Tag) ||
+ ThreadSafeMatch(tag_name, kH2Tag) ||
+ ThreadSafeMatch(tag_name, kH3Tag) ||
+ ThreadSafeMatch(tag_name, kH4Tag) ||
+ ThreadSafeMatch(tag_name, kH5Tag) ||
+ ThreadSafeMatch(tag_name, kH6Tag) ||
+ ThreadSafeMatch(tag_name, kHeadTag) ||
+ ThreadSafeMatch(tag_name, kHrTag) ||
+ ThreadSafeMatch(tag_name, kITag) ||
+ ThreadSafeMatch(tag_name, kImgTag) ||
+ ThreadSafeMatch(tag_name, kLiTag) ||
+ ThreadSafeMatch(tag_name, kListingTag) ||
+ ThreadSafeMatch(tag_name, kMenuTag) ||
+ ThreadSafeMatch(tag_name, kMetaTag) ||
+ ThreadSafeMatch(tag_name, kNobrTag) ||
+ ThreadSafeMatch(tag_name, kOlTag) ||
+ ThreadSafeMatch(tag_name, kPTag) ||
+ ThreadSafeMatch(tag_name, kPreTag) ||
+ ThreadSafeMatch(tag_name, kRubyTag) ||
+ ThreadSafeMatch(tag_name, kSTag) ||
+ ThreadSafeMatch(tag_name, kSmallTag) ||
+ ThreadSafeMatch(tag_name, kSpanTag) ||
+ ThreadSafeMatch(tag_name, kStrongTag) ||
+ ThreadSafeMatch(tag_name, kStrikeTag) ||
+ ThreadSafeMatch(tag_name, kSubTag) ||
+ ThreadSafeMatch(tag_name, kSupTag) ||
+ ThreadSafeMatch(tag_name, kTableTag) ||
+ ThreadSafeMatch(tag_name, kTtTag) ||
+ ThreadSafeMatch(tag_name, kUTag) ||
+ ThreadSafeMatch(tag_name, kUlTag) ||
+ ThreadSafeMatch(tag_name, kVarTag) ||
+ (ThreadSafeMatch(tag_name, kFontTag) &&
+ (token.GetAttributeItem(kColorAttr) ||
+ token.GetAttributeItem(kFaceAttr) ||
+ token.GetAttributeItem(kSizeAttr)));
}
static bool TokenExitsMath(const CompactHTMLToken& token) {
// FIXME: This is copied from HTMLElementStack::isMathMLTextIntegrationPoint
// and changed to use threadSafeMatch.
const String& tag_name = token.Data();
- return ThreadSafeMatch(tag_name, MathMLNames::miTag) ||
- ThreadSafeMatch(tag_name, MathMLNames::moTag) ||
- ThreadSafeMatch(tag_name, MathMLNames::mnTag) ||
- ThreadSafeMatch(tag_name, MathMLNames::msTag) ||
- ThreadSafeMatch(tag_name, MathMLNames::mtextTag);
+ return ThreadSafeMatch(tag_name, mathml_names::kMiTag) ||
+ ThreadSafeMatch(tag_name, mathml_names::kMoTag) ||
+ ThreadSafeMatch(tag_name, mathml_names::kMnTag) ||
+ ThreadSafeMatch(tag_name, mathml_names::kMsTag) ||
+ ThreadSafeMatch(tag_name, mathml_names::kMtextTag);
}
static bool TokenExitsInSelect(const CompactHTMLToken& token) {
// https://html.spec.whatwg.org/#parsing-main-inselect
const String& tag_name = token.Data();
- return ThreadSafeMatch(tag_name, inputTag) ||
- ThreadSafeMatch(tag_name, keygenTag) ||
- ThreadSafeMatch(tag_name, textareaTag);
+ return ThreadSafeMatch(tag_name, kInputTag) ||
+ ThreadSafeMatch(tag_name, kKeygenTag) ||
+ ThreadSafeMatch(tag_name, kTextareaTag);
}
HTMLTreeBuilderSimulator::HTMLTreeBuilderSimulator(
@@ -116,9 +125,9 @@ HTMLTreeBuilderSimulator::State HTMLTreeBuilderSimulator::StateFor(
tree_builder->OpenElements()->TopRecord();
record; record = record->Next()) {
Namespace current_namespace = HTML;
- if (record->NamespaceURI() == SVGNames::svgNamespaceURI)
+ if (record->NamespaceURI() == svg_names::kNamespaceURI)
current_namespace = SVG;
- else if (record->NamespaceURI() == MathMLNames::mathmlNamespaceURI)
+ else if (record->NamespaceURI() == mathml_names::kNamespaceURI)
current_namespace = kMathML;
if (namespace_stack.IsEmpty() ||
@@ -136,9 +145,9 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate(
if (token.GetType() == HTMLToken::kStartTag) {
const String& tag_name = token.Data();
- if (ThreadSafeMatch(tag_name, SVGNames::svgTag))
+ if (ThreadSafeMatch(tag_name, svg_names::kSVGTag))
namespace_stack_.push_back(SVG);
- if (ThreadSafeMatch(tag_name, MathMLNames::mathTag))
+ if (ThreadSafeMatch(tag_name, mathml_names::kMathTag))
namespace_stack_.push_back(kMathML);
if (InForeignContent() && TokenExitsForeignContent(token))
namespace_stack_.pop_back();
@@ -148,44 +157,44 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate(
} else if (!InForeignContent()) {
// FIXME: This is just a copy of Tokenizer::updateStateFor which uses
// threadSafeMatches.
- if (ThreadSafeMatch(tag_name, textareaTag) ||
- ThreadSafeMatch(tag_name, titleTag)) {
+ if (ThreadSafeMatch(tag_name, kTextareaTag) ||
+ ThreadSafeMatch(tag_name, kTitleTag)) {
tokenizer->SetState(HTMLTokenizer::kRCDATAState);
- } else if (ThreadSafeMatch(tag_name, scriptTag)) {
+ } else if (ThreadSafeMatch(tag_name, kScriptTag)) {
tokenizer->SetState(HTMLTokenizer::kScriptDataState);
String type_attribute_value;
- if (auto* item = token.GetAttributeItem(typeAttr)) {
+ if (auto* item = token.GetAttributeItem(kTypeAttr)) {
type_attribute_value = item->Value();
}
String language_attribute_value;
- if (auto* item = token.GetAttributeItem(languageAttr)) {
+ if (auto* item = token.GetAttributeItem(kLanguageAttr)) {
language_attribute_value = item->Value();
}
- ScriptType script_type;
+ mojom::ScriptType script_type;
if (ScriptLoader::IsValidScriptTypeAndLanguage(
type_attribute_value, language_attribute_value,
ScriptLoader::kAllowLegacyTypeInTypeAttribute, script_type)) {
simulated_token = kValidScriptStart;
}
- } else if (ThreadSafeMatch(tag_name, linkTag)) {
+ } else if (ThreadSafeMatch(tag_name, kLinkTag)) {
simulated_token = kLink;
} else if (!in_select_insertion_mode_) {
// If we're in the "in select" insertion mode, all of these tags are
// ignored, so we shouldn't change the tokenizer state:
// https://html.spec.whatwg.org/#parsing-main-inselect
- if (ThreadSafeMatch(tag_name, plaintextTag) &&
+ if (ThreadSafeMatch(tag_name, kPlaintextTag) &&
!in_select_insertion_mode_) {
tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState);
- } else if (ThreadSafeMatch(tag_name, styleTag) ||
- ThreadSafeMatch(tag_name, iframeTag) ||
- ThreadSafeMatch(tag_name, xmpTag) ||
- (ThreadSafeMatch(tag_name, noembedTag) &&
+ } else if (ThreadSafeMatch(tag_name, kStyleTag) ||
+ ThreadSafeMatch(tag_name, kIFrameTag) ||
+ ThreadSafeMatch(tag_name, kXmpTag) ||
+ (ThreadSafeMatch(tag_name, kNoembedTag) &&
options_.plugins_enabled) ||
- ThreadSafeMatch(tag_name, noframesTag) ||
- (ThreadSafeMatch(tag_name, noscriptTag) &&
+ ThreadSafeMatch(tag_name, kNoframesTag) ||
+ (ThreadSafeMatch(tag_name, kNoscriptTag) &&
options_.script_enabled)) {
tokenizer->SetState(HTMLTokenizer::kRAWTEXTState);
}
@@ -197,7 +206,7 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate(
// textual content.
//
// https://html.spec.whatwg.org/#parsing-main-inselect
- if (ThreadSafeMatch(tag_name, selectTag)) {
+ if (ThreadSafeMatch(tag_name, kSelectTag)) {
in_select_insertion_mode_ = true;
} else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) {
in_select_insertion_mode_ = false;
@@ -210,24 +219,32 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate(
InForeignContent())) {
const String& tag_name = token.Data();
if ((namespace_stack_.back() == SVG &&
- ThreadSafeMatch(tag_name, SVGNames::svgTag)) ||
+ ThreadSafeMatch(tag_name, svg_names::kSVGTag)) ||
(namespace_stack_.back() == kMathML &&
- ThreadSafeMatch(tag_name, MathMLNames::mathTag)) ||
+ ThreadSafeMatch(tag_name, mathml_names::kMathTag)) ||
IsHTMLIntegrationPointForEndTag(token) ||
(namespace_stack_.Contains(kMathML) &&
namespace_stack_.back() == HTML && TokenExitsMath(token))) {
namespace_stack_.pop_back();
}
- if (ThreadSafeMatch(tag_name, scriptTag)) {
+ if (ThreadSafeMatch(tag_name, kScriptTag)) {
if (!InForeignContent())
tokenizer->SetState(HTMLTokenizer::kDataState);
return kScriptEnd;
- } else if (ThreadSafeMatch(tag_name, selectTag)) {
- in_select_insertion_mode_ = false;
}
- if (ThreadSafeMatch(tag_name, styleTag))
+ if (ThreadSafeMatch(tag_name, kSelectTag))
+ in_select_insertion_mode_ = false;
+ if (ThreadSafeMatch(tag_name, kStyleTag))
simulated_token = kStyleEnd;
}
+ if (token.GetType() == HTMLToken::kStartTag &&
+ simulated_token == kOtherToken) {
+ const String& tag_name = token.Data();
+ // Use the presence of a dash in the tag name as a proxy for
+ // "is a custom element".
+ if (tag_name.find('-') != kNotFound)
+ simulated_token = kCustomElementBegin;
+ }
// FIXME: Also setForceNullCharacterReplacement when in text mode.
tokenizer->SetForceNullCharacterReplacement(InForeignContent());
@@ -243,9 +260,9 @@ bool HTMLTreeBuilderSimulator::IsHTMLIntegrationPointForStartTag(
Namespace tokens_ns = namespace_stack_.back();
const String& tag_name = token.Data();
if (tokens_ns == kMathML) {
- if (!ThreadSafeMatch(tag_name, MathMLNames::annotation_xmlTag))
+ if (!ThreadSafeMatch(tag_name, mathml_names::kAnnotationXmlTag))
return false;
- if (auto* encoding = token.GetAttributeItem(MathMLNames::encodingAttr)) {
+ if (auto* encoding = token.GetAttributeItem(mathml_names::kEncodingAttr)) {
return EqualIgnoringASCIICase(encoding->Value(), "text/html") ||
EqualIgnoringASCIICase(encoding->Value(), "application/xhtml+xml");
}
@@ -253,10 +270,10 @@ bool HTMLTreeBuilderSimulator::IsHTMLIntegrationPointForStartTag(
// FIXME: It's very fragile that we special case foreignObject here to be
// case-insensitive.
if (DeprecatedEqualIgnoringCase(tag_name,
- SVGNames::foreignObjectTag.LocalName()))
+ svg_names::kForeignObjectTag.LocalName()))
return true;
- return ThreadSafeMatch(tag_name, SVGNames::descTag) ||
- ThreadSafeMatch(tag_name, SVGNames::titleTag);
+ return ThreadSafeMatch(tag_name, svg_names::kDescTag) ||
+ ThreadSafeMatch(tag_name, svg_names::kTitleTag);
}
return false;
}
@@ -277,15 +294,15 @@ bool HTMLTreeBuilderSimulator::IsHTMLIntegrationPointForEndTag(
const String& tag_name = token.Data();
if (tokens_ns == kMathML)
- return ThreadSafeMatch(tag_name, MathMLNames::annotation_xmlTag);
+ return ThreadSafeMatch(tag_name, mathml_names::kAnnotationXmlTag);
if (tokens_ns == SVG) {
// FIXME: It's very fragile that we special case foreignObject here to be
// case-insensitive.
if (DeprecatedEqualIgnoringCase(tag_name,
- SVGNames::foreignObjectTag.LocalName()))
+ svg_names::kForeignObjectTag.LocalName()))
return true;
- return ThreadSafeMatch(tag_name, SVGNames::descTag) ||
- ThreadSafeMatch(tag_name, SVGNames::titleTag);
+ return ThreadSafeMatch(tag_name, svg_names::kDescTag) ||
+ ThreadSafeMatch(tag_name, svg_names::kTitleTag);
}
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.h b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.h
index bfbd1161356..c838ae36595 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_tree_builder_simulator.h
@@ -48,6 +48,7 @@ class CORE_EXPORT HTMLTreeBuilderSimulator {
kScriptEnd,
kLink,
kStyleEnd,
+ kCustomElementBegin,
kOtherToken
};
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_view_source_parser.h b/chromium/third_party/blink/renderer/core/html/parser/html_view_source_parser.h
index e3c2b886890..ba9cd5366f6 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_view_source_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_view_source_parser.h
@@ -42,13 +42,13 @@ class CORE_EXPORT HTMLViewSourceParser final
public:
static HTMLViewSourceParser* Create(HTMLViewSourceDocument& document,
const String& mime_type) {
- return new HTMLViewSourceParser(document, mime_type);
+ return MakeGarbageCollected<HTMLViewSourceParser>(document, mime_type);
}
- ~HTMLViewSourceParser() override = default;
- private:
HTMLViewSourceParser(HTMLViewSourceDocument&, const String& mime_type);
+ ~HTMLViewSourceParser() override = default;
+ private:
// DocumentParser
void insert(const String&) override { NOTREACHED(); }
void Append(const String&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/preload_request.cc b/chromium/third_party/blink/renderer/core/html/parser/preload_request.cc
index 5a4b09f6fdc..892cf94dece 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/preload_request.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/preload_request.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/script/document_write_intervention.h"
#include "third_party/blink/renderer/core/script/script_loader.h"
@@ -57,7 +58,7 @@ Resource* PreloadRequest::Start(Document* document) {
kCrossOriginAttributeAnonymous);
}
- if (script_type_ == ScriptType::kModule) {
+ if (script_type_ == mojom::ScriptType::kModule) {
DCHECK_EQ(resource_type_, ResourceType::kScript);
params.SetCrossOriginAccessControl(
document->GetSecurityOrigin(),
@@ -77,7 +78,7 @@ Resource* PreloadRequest::Start(Document* document) {
if (request_type_ == kRequestTypeLinkRelPreload)
params.SetLinkPreload(true);
- if (script_type_ == ScriptType::kModule) {
+ if (script_type_ == mojom::ScriptType::kModule) {
DCHECK_EQ(resource_type_, ResourceType::kScript);
params.SetDecoderOptions(
TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText());
diff --git a/chromium/third_party/blink/renderer/core/html/parser/preload_request.h b/chromium/third_party/blink/renderer/core/html/parser/preload_request.h
index 0bd0956019e..dbe82c976f8 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/preload_request.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/preload_request.h
@@ -8,6 +8,7 @@
#include <memory>
#include "base/memory/ptr_util.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/script/script.h"
@@ -46,7 +47,7 @@ class CORE_EXPORT PreloadRequest {
const String& resource_url,
const KURL& base_url,
ResourceType resource_type,
- const ReferrerPolicy referrer_policy,
+ const network::mojom::ReferrerPolicy referrer_policy,
ReferrerSource referrer_source,
ResourceFetcher::IsImageSet is_image_set,
const FetchParameters::ResourceWidth& resource_width =
@@ -99,9 +100,13 @@ class CORE_EXPORT PreloadRequest {
const ClientHintsPreferences& Preferences() const {
return client_hints_preferences_;
}
- ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
- void SetScriptType(ScriptType script_type) { script_type_ = script_type; }
+ void SetScriptType(mojom::ScriptType script_type) {
+ script_type_ = script_type;
+ }
// Only scripts and css stylesheets need to have integrity set on preloads.
// This is because neither resource keeps raw data around to redo an
@@ -124,6 +129,9 @@ class CORE_EXPORT PreloadRequest {
void SetIsLazyloadImageDisabled(bool is_lazyload_image_disable) {
is_lazyload_image_disabled_ = is_lazyload_image_disable;
}
+ bool IsLazyloadImageDisabledForTesting() {
+ return is_lazyload_image_disabled_;
+ }
private:
PreloadRequest(const String& initiator_name,
@@ -134,7 +142,7 @@ class CORE_EXPORT PreloadRequest {
const FetchParameters::ResourceWidth& resource_width,
const ClientHintsPreferences& client_hints_preferences,
RequestType request_type,
- const ReferrerPolicy referrer_policy,
+ const network::mojom::ReferrerPolicy referrer_policy,
ReferrerSource referrer_source,
ResourceFetcher::IsImageSet is_image_set)
: initiator_name_(initiator_name),
@@ -142,7 +150,7 @@ class CORE_EXPORT PreloadRequest {
resource_url_(resource_url),
base_url_(base_url),
resource_type_(resource_type),
- script_type_(ScriptType::kClassic),
+ script_type_(mojom::ScriptType::kClassic),
cross_origin_(kCrossOriginAttributeNotSet),
importance_(mojom::FetchImportanceMode::kImportanceAuto),
defer_(FetchParameters::kNoDefer),
@@ -163,7 +171,7 @@ class CORE_EXPORT PreloadRequest {
KURL base_url_;
String charset_;
ResourceType resource_type_;
- ScriptType script_type_;
+ mojom::ScriptType script_type_;
CrossOriginAttributeValue cross_origin_;
mojom::FetchImportanceMode importance_;
String nonce_;
@@ -171,7 +179,7 @@ class CORE_EXPORT PreloadRequest {
FetchParameters::ResourceWidth resource_width_;
ClientHintsPreferences client_hints_preferences_;
RequestType request_type_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
ReferrerSource referrer_source_;
IntegrityMetadataSet integrity_metadata_;
bool from_insertion_scanner_;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.cc b/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.cc
index 65d993155e3..56b282b4569 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.cc
@@ -30,7 +30,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
TextDocumentParser::TextDocumentParser(HTMLDocument& document,
ParserSynchronizationPolicy sync_policy)
@@ -56,8 +56,8 @@ void TextDocumentParser::InsertFakePreElement() {
// line/column number calculations.
Vector<Attribute> attributes;
attributes.push_back(
- Attribute(styleAttr, "word-wrap: break-word; white-space: pre-wrap;"));
- AtomicHTMLToken fake_pre(HTMLToken::kStartTag, preTag.LocalName(),
+ Attribute(kStyleAttr, "word-wrap: break-word; white-space: pre-wrap;"));
+ AtomicHTMLToken fake_pre(HTMLToken::kStartTag, kPreTag.LocalName(),
attributes);
TreeBuilder()->ConstructTree(&fake_pre);
diff --git a/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.h b/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.h
index c9efc1d39cf..0fc7fbff054 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/text_document_parser.h
@@ -33,13 +33,13 @@ class TextDocumentParser final : public HTMLDocumentParser {
public:
static TextDocumentParser* Create(HTMLDocument& document,
ParserSynchronizationPolicy sync_policy) {
- return new TextDocumentParser(document, sync_policy);
+ return MakeGarbageCollected<TextDocumentParser>(document, sync_policy);
}
- ~TextDocumentParser() override;
- private:
explicit TextDocumentParser(HTMLDocument&, ParserSynchronizationPolicy);
+ ~TextDocumentParser() override;
+ private:
void AppendBytes(const char*, size_t) override;
void InsertFakePreElement();
diff --git a/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder.cc b/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder.cc
index 23d1073a340..8ff95d82df8 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder.cc
@@ -24,7 +24,6 @@
#include "third_party/blink/renderer/core/dom/dom_implementation.h"
#include "third_party/blink/renderer/core/html/parser/html_meta_charset_parser.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/text/text_encoding_detector.h"
#include "third_party/blink/renderer/platform/wtf/string_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/text_codec.h"
@@ -32,8 +31,6 @@
namespace blink {
-using namespace HTMLNames;
-
const int kMinimumLengthOfXMLDeclaration = 8;
static inline bool BytesEqual(const char* p,
diff --git a/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_for_fuzzing.h b/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_for_fuzzing.h
index f407437c7b0..d71506c9ede 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_for_fuzzing.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_for_fuzzing.h
@@ -22,7 +22,7 @@ class TextResourceDecoderForFuzzing : public TextResourceDecoder {
static TextResourceDecoderOptions FuzzedOption(
FuzzedDataProvider& fuzzed_data) {
switch (static_cast<TextResourceDecoderOptions::EncodingDetectionOption>(
- fuzzed_data.ConsumeInt32InRange(
+ fuzzed_data.ConsumeIntegralInRange<int32_t>(
TextResourceDecoderOptions::kUseAllAutoDetection,
TextResourceDecoderOptions::kAlwaysUseUTF8ForText))) {
case TextResourceDecoderOptions::kUseAllAutoDetection:
@@ -42,7 +42,7 @@ class TextResourceDecoderForFuzzing : public TextResourceDecoder {
static TextResourceDecoderOptions::ContentType FuzzedContentType(
FuzzedDataProvider& fuzzed_data) {
return static_cast<TextResourceDecoderOptions::ContentType>(
- fuzzed_data.ConsumeInt32InRange(
+ fuzzed_data.ConsumeIntegralInRange<int32_t>(
TextResourceDecoderOptions::kPlainTextContent,
TextResourceDecoderOptions::kMaxContentType));
}
diff --git a/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.cc b/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.cc
index c9117fe635a..0ed6267168d 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.cc
@@ -60,7 +60,7 @@ const char kSafeJavaScriptURL[] = "javascript:void(0)";
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static bool IsNonCanonicalCharacter(UChar c) {
// We remove all non-ASCII characters, including non-printable ASCII
@@ -166,7 +166,7 @@ static bool FindAttributeWithName(const HTMLToken& token,
wtf_size_t& index_of_matching_attribute) {
// Notice that we're careful not to ref the StringImpl here because we might
// be on a background thread.
- const String& attr_name = name.NamespaceURI() == XLinkNames::xlinkNamespaceURI
+ const String& attr_name = name.NamespaceURI() == xlink_names::kNamespaceURI
? "xlink:" + name.LocalName().GetString()
: name.LocalName().GetString();
@@ -325,7 +325,7 @@ static void TruncateForSemicolonSeparatedScriptLikeAttribute(
static bool IsSemicolonSeparatedAttribute(
const HTMLToken::Attribute& attribute) {
- return ThreadSafeMatch(attribute.NameAsVector(), SVGNames::valuesAttr);
+ return ThreadSafeMatch(attribute.NameAsVector(), svg_names::kValuesAttr);
}
static bool IsSemicolonSeparatedValueContainingJavaScriptURL(
@@ -374,7 +374,9 @@ void XSSAuditor::Init(Document* document,
if (!is_enabled_)
return;
- document_url_ = document->Url().Copy();
+ document_url_ = document->Url();
+ document_url_.RemoveFragmentIdentifier();
+ document_url_ = document_url_.Copy(); // Make thread safe.
// In theory, the Document could have detached from the LocalFrame after the
// XSSAuditor was constructed.
@@ -402,7 +404,7 @@ void XSSAuditor::Init(Document* document,
document->GetFrame()->Loader().GetDocumentLoader()) {
const AtomicString& header_value =
document_loader->GetResponse().HttpHeaderField(
- HTTPNames::X_XSS_Protection);
+ http_names::kXXSSProtection);
String error_details;
unsigned error_position = 0;
String report_url;
@@ -520,30 +522,30 @@ bool XSSAuditor::FilterStartToken(const FilterTokenRequest& request) {
state_ = kFilteringTokens;
bool did_block_script = EraseDangerousAttributesIfInjected(request);
- if (HasName(request.token, scriptTag)) {
+ if (HasName(request.token, kScriptTag)) {
did_block_script |= FilterScriptToken(request);
DCHECK(request.should_allow_cdata || !script_tag_nesting_level_);
script_tag_nesting_level_++;
- } else if (HasName(request.token, objectTag))
+ } else if (HasName(request.token, kObjectTag))
did_block_script |= FilterObjectToken(request);
- else if (HasName(request.token, paramTag))
+ else if (HasName(request.token, kParamTag))
did_block_script |= FilterParamToken(request);
- else if (HasName(request.token, embedTag))
+ else if (HasName(request.token, kEmbedTag))
did_block_script |= FilterEmbedToken(request);
- else if (HasName(request.token, iframeTag) ||
- HasName(request.token, frameTag))
+ else if (HasName(request.token, kIFrameTag) ||
+ HasName(request.token, kFrameTag))
did_block_script |= FilterFrameToken(request);
- else if (HasName(request.token, metaTag))
+ else if (HasName(request.token, kMetaTag))
did_block_script |= FilterMetaToken(request);
- else if (HasName(request.token, baseTag))
+ else if (HasName(request.token, kBaseTag))
did_block_script |= FilterBaseToken(request);
- else if (HasName(request.token, formTag))
+ else if (HasName(request.token, kFormTag))
did_block_script |= FilterFormToken(request);
- else if (HasName(request.token, inputTag))
+ else if (HasName(request.token, kInputTag))
did_block_script |= FilterInputToken(request);
- else if (HasName(request.token, buttonTag))
+ else if (HasName(request.token, kButtonTag))
did_block_script |= FilterButtonToken(request);
- else if (HasName(request.token, linkTag))
+ else if (HasName(request.token, kLinkTag))
did_block_script |= FilterLinkToken(request);
return did_block_script;
@@ -552,7 +554,7 @@ bool XSSAuditor::FilterStartToken(const FilterTokenRequest& request) {
void XSSAuditor::FilterEndToken(const FilterTokenRequest& request) {
DCHECK(script_tag_nesting_level_);
state_ = kFilteringTokens;
- if (HasName(request.token, scriptTag)) {
+ if (HasName(request.token, kScriptTag)) {
script_tag_nesting_level_--;
DCHECK(request.should_allow_cdata || !script_tag_nesting_level_);
}
@@ -582,44 +584,45 @@ bool XSSAuditor::FilterCharacterToken(const FilterTokenRequest& request) {
bool XSSAuditor::FilterScriptToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, scriptTag));
+ DCHECK(HasName(request.token, kScriptTag));
bool did_block_script = false;
script_tag_found_in_request_ =
IsContainedInRequest(CanonicalizedSnippetForTagName(request));
if (script_tag_found_in_request_) {
did_block_script |= EraseAttributeIfInjected(
- request, srcAttr, BlankURL().GetString(), kSrcLikeAttributeTruncation);
- did_block_script |= EraseAttributeIfInjected(request, SVGNames::hrefAttr,
- BlankURL().GetString(),
- kSrcLikeAttributeTruncation);
- did_block_script |= EraseAttributeIfInjected(request, XLinkNames::hrefAttr,
+ request, kSrcAttr, BlankURL().GetString(), kSrcLikeAttributeTruncation);
+ did_block_script |= EraseAttributeIfInjected(request, svg_names::kHrefAttr,
BlankURL().GetString(),
kSrcLikeAttributeTruncation);
+ did_block_script |= EraseAttributeIfInjected(
+ request, xlink_names::kHrefAttr, BlankURL().GetString(),
+ kSrcLikeAttributeTruncation);
}
return did_block_script;
}
bool XSSAuditor::FilterObjectToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, objectTag));
+ DCHECK(HasName(request.token, kObjectTag));
bool did_block_script = false;
if (IsContainedInRequest(CanonicalizedSnippetForTagName(request))) {
- did_block_script |= EraseAttributeIfInjected(
- request, dataAttr, BlankURL().GetString(), kSrcLikeAttributeTruncation);
- did_block_script |= EraseAttributeIfInjected(request, typeAttr);
- did_block_script |= EraseAttributeIfInjected(request, classidAttr);
+ did_block_script |=
+ EraseAttributeIfInjected(request, kDataAttr, BlankURL().GetString(),
+ kSrcLikeAttributeTruncation);
+ did_block_script |= EraseAttributeIfInjected(request, kTypeAttr);
+ did_block_script |= EraseAttributeIfInjected(request, kClassidAttr);
}
return did_block_script;
}
bool XSSAuditor::FilterParamToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, paramTag));
+ DCHECK(HasName(request.token, kParamTag));
wtf_size_t index_of_name_attribute;
- if (!FindAttributeWithName(request.token, nameAttr, index_of_name_attribute))
+ if (!FindAttributeWithName(request.token, kNameAttr, index_of_name_attribute))
return false;
const HTMLToken::Attribute& name_attribute =
@@ -627,33 +630,34 @@ bool XSSAuditor::FilterParamToken(const FilterTokenRequest& request) {
if (!HTMLParamElement::IsURLParameter(name_attribute.Value()))
return false;
- return EraseAttributeIfInjected(request, valueAttr, BlankURL().GetString(),
+ return EraseAttributeIfInjected(request, kValueAttr, BlankURL().GetString(),
kSrcLikeAttributeTruncation);
}
bool XSSAuditor::FilterEmbedToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, embedTag));
+ DCHECK(HasName(request.token, kEmbedTag));
bool did_block_script = false;
if (IsContainedInRequest(CanonicalizedSnippetForTagName(request))) {
- did_block_script |= EraseAttributeIfInjected(request, codeAttr, String(),
+ did_block_script |= EraseAttributeIfInjected(request, kCodeAttr, String(),
kSrcLikeAttributeTruncation);
did_block_script |= EraseAttributeIfInjected(
- request, srcAttr, BlankURL().GetString(), kSrcLikeAttributeTruncation);
- did_block_script |= EraseAttributeIfInjected(request, typeAttr);
+ request, kSrcAttr, BlankURL().GetString(), kSrcLikeAttributeTruncation);
+ did_block_script |= EraseAttributeIfInjected(request, kTypeAttr);
}
return did_block_script;
}
bool XSSAuditor::FilterFrameToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, iframeTag) || HasName(request.token, frameTag));
+ DCHECK(HasName(request.token, kIFrameTag) ||
+ HasName(request.token, kFrameTag));
bool did_block_script = EraseAttributeIfInjected(
- request, srcdocAttr, String(), kScriptLikeAttributeTruncation);
+ request, kSrcdocAttr, String(), kScriptLikeAttributeTruncation);
if (IsContainedInRequest(CanonicalizedSnippetForTagName(request)))
- did_block_script |= EraseAttributeIfInjected(request, srcAttr, String(),
+ did_block_script |= EraseAttributeIfInjected(request, kSrcAttr, String(),
kSrcLikeAttributeTruncation);
return did_block_script;
@@ -661,49 +665,51 @@ bool XSSAuditor::FilterFrameToken(const FilterTokenRequest& request) {
bool XSSAuditor::FilterMetaToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, metaTag));
+ DCHECK(HasName(request.token, kMetaTag));
- return EraseAttributeIfInjected(request, http_equivAttr);
+ return EraseAttributeIfInjected(request, kHttpEquivAttr);
}
bool XSSAuditor::FilterBaseToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, baseTag));
+ DCHECK(HasName(request.token, kBaseTag));
- return EraseAttributeIfInjected(request, hrefAttr, String(),
+ return EraseAttributeIfInjected(request, kHrefAttr, String(),
kSrcLikeAttributeTruncation);
}
bool XSSAuditor::FilterFormToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, formTag));
+ DCHECK(HasName(request.token, kFormTag));
- return EraseAttributeIfInjected(request, actionAttr, kURLWithUniqueOrigin,
+ return EraseAttributeIfInjected(request, kActionAttr, kURLWithUniqueOrigin,
kSrcLikeAttributeTruncation);
}
bool XSSAuditor::FilterInputToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, inputTag));
+ DCHECK(HasName(request.token, kInputTag));
- return EraseAttributeIfInjected(request, formactionAttr, kURLWithUniqueOrigin,
+ return EraseAttributeIfInjected(request, kFormactionAttr,
+ kURLWithUniqueOrigin,
kSrcLikeAttributeTruncation);
}
bool XSSAuditor::FilterButtonToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, buttonTag));
+ DCHECK(HasName(request.token, kButtonTag));
- return EraseAttributeIfInjected(request, formactionAttr, kURLWithUniqueOrigin,
+ return EraseAttributeIfInjected(request, kFormactionAttr,
+ kURLWithUniqueOrigin,
kSrcLikeAttributeTruncation);
}
bool XSSAuditor::FilterLinkToken(const FilterTokenRequest& request) {
DCHECK_EQ(request.token.GetType(), HTMLToken::kStartTag);
- DCHECK(HasName(request.token, linkTag));
+ DCHECK(HasName(request.token, kLinkTag));
wtf_size_t index_of_attribute = 0;
- if (!FindAttributeWithName(request.token, relAttr, index_of_attribute))
+ if (!FindAttributeWithName(request.token, kRelAttr, index_of_attribute))
return false;
const HTMLToken::Attribute& attribute =
@@ -712,7 +718,7 @@ bool XSSAuditor::FilterLinkToken(const FilterTokenRequest& request) {
if (!parsed_attribute.IsImport())
return false;
- return EraseAttributeIfInjected(request, hrefAttr, kURLWithUniqueOrigin,
+ return EraseAttributeIfInjected(request, kHrefAttr, kURLWithUniqueOrigin,
kSrcLikeAttributeTruncation,
kAllowSameOriginHref);
}
@@ -772,12 +778,12 @@ bool XSSAuditor::EraseAttributeIfInjected(const FilterTokenRequest& request,
Canonicalize(SnippetFromAttribute(request, attribute), treatment)))
return false;
- if (ThreadSafeMatch(attribute_name, srcAttr) ||
+ if (ThreadSafeMatch(attribute_name, kSrcAttr) ||
(restriction == kAllowSameOriginHref &&
- ThreadSafeMatch(attribute_name, hrefAttr))) {
+ ThreadSafeMatch(attribute_name, kHrefAttr))) {
if (IsLikelySafeResource(attribute.Value()))
return false;
- } else if (ThreadSafeMatch(attribute_name, http_equivAttr)) {
+ } else if (ThreadSafeMatch(attribute_name, kHttpEquivAttr)) {
if (!IsDangerousHTTPEquiv(attribute.Value()))
return false;
}
@@ -911,10 +917,12 @@ String XSSAuditor::CanonicalizedSnippetForJavaScript(
last_non_space_position = kNotFound;
for (found_position = start_position; found_position < end_position;
found_position++) {
+ if (StartsSingleLineCommentAt(string, found_position) ||
+ StartsMultiLineCommentAt(string, found_position)) {
+ break;
+ }
if (!request.should_allow_cdata) {
- if (StartsSingleLineCommentAt(string, found_position) ||
- StartsMultiLineCommentAt(string, found_position) ||
- StartsHTMLOpenCommentAt(string, found_position) ||
+ if (StartsHTMLOpenCommentAt(string, found_position) ||
StartsHTMLCloseCommentAt(string, found_position)) {
break;
}
diff --git a/chromium/third_party/blink/renderer/core/html/plugin_document.cc b/chromium/third_party/blink/renderer/core/html/plugin_document.cc
index 9c5746dd5ba..70c83c295de 100644
--- a/chromium/third_party/blink/renderer/core/html/plugin_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/plugin_document.cc
@@ -47,14 +47,17 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class PluginDocument::BeforeUnloadEventListener : public EventListener {
public:
static BeforeUnloadEventListener* Create(PluginDocument* document) {
- return new BeforeUnloadEventListener(document);
+ return MakeGarbageCollected<BeforeUnloadEventListener>(document);
}
+ explicit BeforeUnloadEventListener(PluginDocument* document)
+ : EventListener(kCPPEventListenerType), doc_(document) {}
+
bool operator==(const EventListener& listener) const override {
return this == &listener;
}
@@ -69,11 +72,8 @@ class PluginDocument::BeforeUnloadEventListener : public EventListener {
}
private:
- explicit BeforeUnloadEventListener(PluginDocument* document)
- : EventListener(kCPPEventListenerType), doc_(document) {}
-
- void handleEvent(ExecutionContext*, Event* event) override {
- DCHECK_EQ(event->type(), EventTypeNames::beforeunload);
+ void Invoke(ExecutionContext*, Event* event) override {
+ DCHECK_EQ(event->type(), event_type_names::kBeforeunload);
if (show_dialog_)
ToBeforeUnloadEvent(event)->setReturnValue(g_empty_string);
}
@@ -87,20 +87,21 @@ class PluginDocumentParser : public RawDataDocumentParser {
public:
static PluginDocumentParser* Create(PluginDocument* document,
Color background_color) {
- return new PluginDocumentParser(document, background_color);
+ return MakeGarbageCollected<PluginDocumentParser>(document,
+ background_color);
}
+ PluginDocumentParser(Document* document, Color background_color)
+ : RawDataDocumentParser(document),
+ embed_element_(nullptr),
+ background_color_(background_color) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(embed_element_);
RawDataDocumentParser::Trace(visitor);
}
private:
- PluginDocumentParser(Document* document, Color background_color)
- : RawDataDocumentParser(document),
- embed_element_(nullptr),
- background_color_(background_color) {}
-
void AppendBytes(const char*, size_t) override;
void Finish() override;
@@ -136,7 +137,7 @@ void PluginDocumentParser::CreateDocumentStructure() {
return; // runScriptsAtDocumentElementAvailable can detach the frame.
HTMLBodyElement* body = HTMLBodyElement::Create(*GetDocument());
- body->setAttribute(styleAttr,
+ body->setAttribute(kStyleAttr,
"height: 100%; width: 100%; overflow: hidden; margin: 0");
body->SetInlineStyleProperty(
CSSPropertyBackgroundColor,
@@ -149,13 +150,13 @@ void PluginDocumentParser::CreateDocumentStructure() {
}
embed_element_ = HTMLEmbedElement::Create(*GetDocument());
- embed_element_->setAttribute(widthAttr, "100%");
- embed_element_->setAttribute(heightAttr, "100%");
- embed_element_->setAttribute(nameAttr, "plugin");
- embed_element_->setAttribute(idAttr, "plugin");
- embed_element_->setAttribute(srcAttr,
+ embed_element_->setAttribute(kWidthAttr, "100%");
+ embed_element_->setAttribute(kHeightAttr, "100%");
+ embed_element_->setAttribute(kNameAttr, "plugin");
+ embed_element_->setAttribute(kIdAttr, "plugin");
+ embed_element_->setAttribute(kSrcAttr,
AtomicString(GetDocument()->Url().GetString()));
- embed_element_->setAttribute(typeAttr, GetDocument()->Loader()->MimeType());
+ embed_element_->setAttribute(kTypeAttr, GetDocument()->Loader()->MimeType());
body->AppendChild(embed_element_);
if (IsStopped()) {
// Possibly detached by a mutation event listener installed in
@@ -229,7 +230,7 @@ void PluginDocument::SetShowBeforeUnloadDialog(bool show_dialog) {
return;
before_unload_event_listener_ = BeforeUnloadEventListener::Create(this);
- domWindow()->addEventListener(EventTypeNames::beforeunload,
+ domWindow()->addEventListener(event_type_names::kBeforeunload,
before_unload_event_listener_, false);
}
before_unload_event_listener_->SetShowBeforeUnloadDialog(show_dialog);
diff --git a/chromium/third_party/blink/renderer/core/html/plugin_document.h b/chromium/third_party/blink/renderer/core/html/plugin_document.h
index 5566a47a21f..8339e572464 100644
--- a/chromium/third_party/blink/renderer/core/html/plugin_document.h
+++ b/chromium/third_party/blink/renderer/core/html/plugin_document.h
@@ -38,9 +38,11 @@ class CORE_EXPORT PluginDocument final : public HTMLDocument {
public:
static PluginDocument* Create(const DocumentInit& initializer,
Color background_color) {
- return new PluginDocument(initializer, background_color);
+ return MakeGarbageCollected<PluginDocument>(initializer, background_color);
}
+ PluginDocument(const DocumentInit&, Color background_color);
+
void SetPluginNode(HTMLPlugInElement* plugin_node) {
plugin_node_ = plugin_node;
}
@@ -57,8 +59,6 @@ class CORE_EXPORT PluginDocument final : public HTMLDocument {
private:
class BeforeUnloadEventListener;
- PluginDocument(const DocumentInit&, Color background_color);
-
DocumentParser* CreateParser() override;
Member<HTMLPlugInElement> plugin_node_;
diff --git a/chromium/third_party/blink/renderer/core/html/portal/document_portals.cc b/chromium/third_party/blink/renderer/core/html/portal/document_portals.cc
new file mode 100644
index 00000000000..4afc5ddc4fe
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/portal/document_portals.cc
@@ -0,0 +1,51 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/html/portal/document_portals.h"
+
+#include "third_party/blink/renderer/core/html/portal/html_portal_element.h"
+
+namespace blink {
+
+// static
+const char DocumentPortals::kSupplementName[] = "DocumentPortals";
+
+// static
+DocumentPortals& DocumentPortals::From(Document& document) {
+ DocumentPortals* supplement =
+ Supplement<Document>::From<DocumentPortals>(document);
+ if (!supplement) {
+ supplement = new DocumentPortals(document);
+ Supplement<Document>::ProvideTo(document, supplement);
+ }
+ return *supplement;
+}
+
+DocumentPortals::DocumentPortals(Document& document)
+ : Supplement<Document>(document) {}
+
+void DocumentPortals::OnPortalInserted(HTMLPortalElement* portal) {
+ portals_.push_back(portal);
+}
+
+void DocumentPortals::OnPortalRemoved(HTMLPortalElement* portal) {
+ portals_.EraseAt(portals_.Find(portal));
+}
+
+HTMLPortalElement* DocumentPortals::GetPortal(
+ const base::UnguessableToken& token) const {
+ for (HTMLPortalElement* portal : portals_) {
+ if (portal->GetToken() == token)
+ return portal;
+ }
+
+ return nullptr;
+}
+
+void DocumentPortals::Trace(Visitor* visitor) {
+ Supplement<Document>::Trace(visitor);
+ visitor->Trace(portals_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/portal/document_portals.h b/chromium/third_party/blink/renderer/core/html/portal/document_portals.h
new file mode 100644
index 00000000000..6c9ec61adcd
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/portal/document_portals.h
@@ -0,0 +1,43 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PORTAL_DOCUMENT_PORTALS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PORTAL_DOCUMENT_PORTALS_H_
+
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/supplementable.h"
+
+namespace blink {
+
+class HTMLPortalElement;
+
+class DocumentPortals : public GarbageCollected<DocumentPortals>,
+ public Supplement<Document> {
+ USING_GARBAGE_COLLECTED_MIXIN(DocumentPortals);
+
+ public:
+ static const char kSupplementName[];
+ static DocumentPortals& From(Document&);
+
+ // Used to notify the document that a portal was inserted.
+ void OnPortalInserted(HTMLPortalElement* portal);
+
+ // Notifies that a portal was removed from the Document.
+ void OnPortalRemoved(HTMLPortalElement* portal);
+
+ // Retrieves the portal identified by the token.
+ HTMLPortalElement* GetPortal(const base::UnguessableToken&) const;
+
+ void Trace(Visitor*) override;
+
+ private:
+ explicit DocumentPortals(Document&);
+
+ HeapVector<Member<HTMLPortalElement>> portals_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PORTAL_DOCUMENT_PORTALS_H_
diff --git a/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.cc b/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.cc
index 47dc3b9948e..617ddfff7e8 100644
--- a/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.cc
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/html_unknown_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
+#include "third_party/blink/renderer/core/html/portal/document_portals.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -22,18 +23,18 @@
namespace blink {
HTMLPortalElement::HTMLPortalElement(Document& document)
- : HTMLFrameOwnerElement(HTMLNames::portalTag, document) {}
+ : HTMLFrameOwnerElement(html_names::kPortalTag, document) {}
HTMLPortalElement::~HTMLPortalElement() {}
HTMLElement* HTMLPortalElement::Create(Document& document) {
if (RuntimeEnabledFeatures::PortalsEnabled())
- return new HTMLPortalElement(document);
- return HTMLUnknownElement::Create(HTMLNames::portalTag, document);
+ return MakeGarbageCollected<HTMLPortalElement>(document);
+ return HTMLUnknownElement::Create(html_names::kPortalTag, document);
}
void HTMLPortalElement::Navigate() {
- KURL url = GetNonEmptyURLAttribute(HTMLNames::srcAttr);
+ KURL url = GetNonEmptyURLAttribute(html_names::kSrcAttr);
if (!url.IsEmpty() && portal_ptr_) {
portal_ptr_->Navigate(url);
}
@@ -85,6 +86,7 @@ HTMLPortalElement::InsertionNotificationRequest HTMLPortalElement::InsertedInto(
[](HTMLPortalElement* portal,
const base::UnguessableToken& portal_token) {
portal->portal_token_ = portal_token;
+ DocumentPortals::From(portal->GetDocument()).OnPortalInserted(portal);
},
WrapPersistent(this)));
Navigate();
@@ -99,12 +101,20 @@ void HTMLPortalElement::RemovedFrom(ContainerNode& node) {
Document& document = GetDocument();
if (node.IsInDocumentTree() && document.IsHTMLDocument()) {
+ // The portal creation is asynchronous, and the Document only gets notified
+ // after the element receives a callback from the browser that assigns its
+ // token, so we need to check whether that has been completed before
+ // notifying the document about the portal's removal.
+ if (!portal_token_.is_empty())
+ DocumentPortals::From(GetDocument()).OnPortalRemoved(this);
+
+ portal_token_ = base::UnguessableToken();
portal_ptr_.reset();
}
}
bool HTMLPortalElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == HTMLNames::srcAttr ||
+ return attribute.GetName() == html_names::kSrcAttr ||
HTMLFrameOwnerElement::IsURLAttribute(attribute);
}
@@ -112,7 +122,7 @@ void HTMLPortalElement::ParseAttribute(
const AttributeModificationParams& params) {
HTMLFrameOwnerElement::ParseAttribute(params);
- if (params.name == HTMLNames::srcAttr)
+ if (params.name == html_names::kSrcAttr)
Navigate();
}
diff --git a/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.h b/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.h
index f5da63a08e4..6c801cc24a8 100644
--- a/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.h
+++ b/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.h
@@ -30,14 +30,19 @@ class CORE_EXPORT HTMLPortalElement : public HTMLFrameOwnerElement {
public:
static HTMLElement* Create(Document&);
+ explicit HTMLPortalElement(Document&);
~HTMLPortalElement() override;
// idl implementation.
ScriptPromise activate(ScriptState*);
- private:
- explicit HTMLPortalElement(Document&);
+ const base::UnguessableToken& GetToken() const { return portal_token_; }
+ FrameOwnerElementType OwnerType() const override {
+ return FrameOwnerElementType::kPortal;
+ }
+
+ private:
// Navigates the portal to |url_|.
void Navigate();
diff --git a/chromium/third_party/blink/renderer/core/html/rel_list.cc b/chromium/third_party/blink/renderer/core/html/rel_list.cc
index 4bcce39232a..f279eefdb83 100644
--- a/chromium/third_party/blink/renderer/core/html/rel_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/rel_list.cc
@@ -15,7 +15,7 @@
namespace blink {
RelList::RelList(Element* element)
- : DOMTokenList(*element, HTMLNames::relAttr) {}
+ : DOMTokenList(*element, html_names::kRelAttr) {}
static HashSet<AtomicString>& SupportedTokensLink() {
DEFINE_STATIC_LOCAL(
@@ -41,14 +41,13 @@ static HashSet<AtomicString>& SupportedTokensAnchorAndArea() {
bool RelList::ValidateTokenValue(const AtomicString& token_value,
ExceptionState&) const {
// https://html.spec.whatwg.org/multipage/links.html#linkTypes
- if (GetElement().HasTagName(HTMLNames::linkTag)) {
+ if (GetElement().HasTagName(html_names::kLinkTag)) {
if (SupportedTokensLink().Contains(token_value) ||
- (RuntimeEnabledFeatures::ModulePreloadEnabled() &&
- token_value == "modulepreload")) {
+ token_value == "modulepreload") {
return true;
}
- } else if ((GetElement().HasTagName(HTMLNames::aTag) ||
- GetElement().HasTagName(HTMLNames::areaTag)) &&
+ } else if ((GetElement().HasTagName(html_names::kATag) ||
+ GetElement().HasTagName(html_names::kAreaTag)) &&
SupportedTokensAnchorAndArea().Contains(token_value)) {
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/html/rel_list.h b/chromium/third_party/blink/renderer/core/html/rel_list.h
index a7c227f685c..62c0c9e7458 100644
--- a/chromium/third_party/blink/renderer/core/html/rel_list.h
+++ b/chromium/third_party/blink/renderer/core/html/rel_list.h
@@ -11,10 +11,13 @@ namespace blink {
class RelList final : public DOMTokenList {
public:
- static RelList* Create(Element* element) { return new RelList(element); }
+ static RelList* Create(Element* element) {
+ return MakeGarbageCollected<RelList>(element);
+ }
- private:
explicit RelList(Element*);
+
+ private:
bool ValidateTokenValue(const AtomicString&, ExceptionState&) const override;
};
diff --git a/chromium/third_party/blink/renderer/core/css/themeChromiumAndroid.css b/chromium/third_party/blink/renderer/core/html/resources/android.css
index ce254bb4010..ce254bb4010 100644
--- a/chromium/third_party/blink/renderer/core/css/themeChromiumAndroid.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/android.css
diff --git a/chromium/third_party/blink/renderer/core/css/html.css b/chromium/third_party/blink/renderer/core/html/resources/html.css
index 9ad329ba565..ec500730902 100644
--- a/chromium/third_party/blink/renderer/core/css/html.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/html.css
@@ -65,10 +65,10 @@ body:-webkit-full-page-media {
p {
display: block;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1__qem;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 1__qem;
+ margin-block-end: 1__qem;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
}
div {
@@ -94,10 +94,10 @@ address {
blockquote {
display: block;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1em;
- -webkit-margin-start: 40px;
- -webkit-margin-end: 40px;
+ margin-block-start: 1__qem;
+ margin-block-end: 1em;
+ margin-inline-start: 40px;
+ margin-inline-end: 40px;
}
figcaption {
@@ -106,10 +106,10 @@ figcaption {
figure {
display: block;
- -webkit-margin-before: 1em;
- -webkit-margin-after: 1em;
- -webkit-margin-start: 40px;
- -webkit-margin-end: 40px;
+ margin-block-start: 1em;
+ margin-block-end: 1em;
+ margin-inline-start: 40px;
+ margin-inline-end: 40px;
}
q {
@@ -134,10 +134,10 @@ hr {
display: block;
overflow: hidden;
unicode-bidi: isolate;
- -webkit-margin-before: 0.5em;
- -webkit-margin-after: 0.5em;
- -webkit-margin-start: auto;
- -webkit-margin-end: auto;
+ margin-block-start: 0.5em;
+ margin-block-end: 0.5em;
+ margin-inline-start: auto;
+ margin-inline-end: auto;
border-style: inset;
border-width: 1px
}
@@ -155,89 +155,89 @@ video {
h1 {
display: block;
font-size: 2em;
- -webkit-margin-before: 0.67__qem;
- -webkit-margin-after: 0.67em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 0.67__qem;
+ margin-block-end: 0.67em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
font-weight: bold
}
:-webkit-any(article,aside,nav,section) h1 {
font-size: 1.5em;
- -webkit-margin-before: 0.83__qem;
- -webkit-margin-after: 0.83em;
+ margin-block-start: 0.83__qem;
+ margin-block-end: 0.83em;
}
:-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 {
font-size: 1.17em;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1em;
+ margin-block-start: 1__qem;
+ margin-block-end: 1em;
}
:-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 {
font-size: 1.00em;
- -webkit-margin-before: 1.33__qem;
- -webkit-margin-after: 1.33em;
+ margin-block-start: 1.33__qem;
+ margin-block-end: 1.33em;
}
:-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 {
font-size: .83em;
- -webkit-margin-before: 1.67__qem;
- -webkit-margin-after: 1.67em;
+ margin-block-start: 1.67__qem;
+ margin-block-end: 1.67em;
}
:-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 {
font-size: .67em;
- -webkit-margin-before: 2.33__qem;
- -webkit-margin-after: 2.33em;
+ margin-block-start: 2.33__qem;
+ margin-block-end: 2.33em;
}
h2 {
display: block;
font-size: 1.5em;
- -webkit-margin-before: 0.83__qem;
- -webkit-margin-after: 0.83em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 0.83__qem;
+ margin-block-end: 0.83em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
font-weight: bold
}
h3 {
display: block;
font-size: 1.17em;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 1__qem;
+ margin-block-end: 1em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
font-weight: bold
}
h4 {
display: block;
- -webkit-margin-before: 1.33__qem;
- -webkit-margin-after: 1.33em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 1.33__qem;
+ margin-block-end: 1.33em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
font-weight: bold
}
h5 {
display: block;
font-size: .83em;
- -webkit-margin-before: 1.67__qem;
- -webkit-margin-after: 1.67em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 1.67__qem;
+ margin-block-end: 1.67em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
font-weight: bold
}
h6 {
display: block;
font-size: .67em;
- -webkit-margin-before: 2.33__qem;
- -webkit-margin-after: 2.33em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 2.33__qem;
+ margin-block-end: 2.33em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
font-weight: bold
}
@@ -307,21 +307,21 @@ caption {
ul, menu, dir {
display: block;
list-style-type: disc;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
- -webkit-padding-start: 40px
+ margin-block-start: 1__qem;
+ margin-block-end: 1em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
+ padding-inline-start: 40px
}
ol {
display: block;
list-style-type: decimal;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
- -webkit-padding-start: 40px
+ margin-block-start: 1__qem;
+ margin-block-end: 1em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
+ padding-inline-start: 40px
}
li {
@@ -339,15 +339,15 @@ ol ol ul, ol ul ul, ul ol ul, ul ul ul {
dd {
display: block;
- -webkit-margin-start: 40px
+ margin-inline-start: 40px
}
dl {
display: block;
- -webkit-margin-before: 1__qem;
- -webkit-margin-after: 1em;
- -webkit-margin-start: 0;
- -webkit-margin-end: 0;
+ margin-block-start: 1__qem;
+ margin-block-end: 1em;
+ margin-inline-start: 0;
+ margin-inline-end: 0;
}
dt {
@@ -355,8 +355,8 @@ dt {
}
ol ul, ul ol, ul ul, ol ol {
- -webkit-margin-before: 0;
- -webkit-margin-after: 0
+ margin-block-start: 0;
+ margin-block-end: 0
}
/* form elements */
@@ -376,19 +376,19 @@ label {
legend {
display: block;
- -webkit-padding-start: 2px;
- -webkit-padding-end: 2px;
+ padding-inline-start: 2px;
+ padding-inline-end: 2px;
border: none
}
fieldset {
display: block;
- -webkit-margin-start: 2px;
- -webkit-margin-end: 2px;
- -webkit-padding-before: 0.35em;
- -webkit-padding-start: 0.75em;
- -webkit-padding-end: 0.75em;
- -webkit-padding-after: 0.625em;
+ margin-inline-start: 2px;
+ margin-inline-end: 2px;
+ padding-block-start: 0.35em;
+ padding-inline-start: 0.75em;
+ padding-inline-end: 0.75em;
+ padding-block-end: 0.625em;
border: 2px groove ThreeDFace;
min-inline-size: min-content;
}
@@ -448,7 +448,7 @@ input::-webkit-clear-button {
cursor: default;
flex: none;
-webkit-user-modify: read-only !important;
- -webkit-margin-start: 2px;
+ margin-inline-start: 2px;
opacity: 0;
pointer-events: none;
}
@@ -464,7 +464,7 @@ input[type="search" i]::-webkit-search-cancel-button {
cursor: default;
flex: none;
-webkit-user-modify: read-only !important;
- -webkit-margin-start: 1px;
+ margin-inline-start: 1px;
opacity: 0;
pointer-events: none;
user-select: none !important;
@@ -644,8 +644,8 @@ input:disabled, textarea:disabled {
}
option:-internal-spatial-navigation-focus {
- outline: black dashed 1px;
- outline-offset: -1px;
+ outline: black dashed 1px !important;
+ outline-offset: -1px !important;
}
datalist {
@@ -706,8 +706,8 @@ input[type="color" i][list] {
}
input[type="color" i][list]::-webkit-color-swatch-wrapper {
- -webkit-padding-start: 8px;
- -webkit-padding-end: 24px;
+ padding-inline-start: 8px;
+ padding-inline-end: 24px;
}
input[type="color" i][list]::-webkit-color-swatch {
@@ -826,8 +826,8 @@ select:-internal-list-box option:checked:disabled {
select:-internal-list-box hr {
border-style: none;
- -webkit-margin-before: 0.5em;
- -webkit-margin-after: 0;
+ margin-block-start: 0.5em;
+ margin-block-end: 0;
}
output {
@@ -988,6 +988,11 @@ nobr {
/* states */
+:-internal-spatial-navigation-focus {
+ outline: auto 5px -webkit-focus-ring-color !important;
+ box-shadow: none !important
+}
+
:focus {
outline: auto 5px -webkit-focus-ring-color
}
@@ -1081,7 +1086,7 @@ summary::-webkit-details-marker {
display: inline-block;
width: 0.66em;
height: 0.66em;
- -webkit-margin-end: 0.4em;
+ margin-inline-end: 0.4em;
}
template {
diff --git a/chromium/third_party/blink/renderer/core/css/themeInputMultipleFields.css b/chromium/third_party/blink/renderer/core/html/resources/input_multiple_fields.css
index e0ff0efb7b5..db849b0d5ff 100644
--- a/chromium/third_party/blink/renderer/core/css/themeInputMultipleFields.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/input_multiple_fields.css
@@ -13,7 +13,7 @@ input[type="week" i] {
font-family: monospace;
overflow: hidden;
padding: 0;
- -webkit-padding-start: 1px;
+ padding-inline-start: 1px;
cursor: default;
}
@@ -93,5 +93,5 @@ input[type="time" i]::-webkit-inner-spin-button,
input[type="week" i]::-webkit-inner-spin-button {
/* FIXME: Remove height. */
height: 1.5em;
- -webkit-margin-start: 2px;
+ margin-inline-start: 2px;
}
diff --git a/chromium/third_party/blink/renderer/core/css/themeChromiumLinux.css b/chromium/third_party/blink/renderer/core/html/resources/linux.css
index f45f6c7678a..f45f6c7678a 100644
--- a/chromium/third_party/blink/renderer/core/css/themeChromiumLinux.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/linux.css
diff --git a/chromium/third_party/blink/renderer/core/css/themeMac.css b/chromium/third_party/blink/renderer/core/html/resources/mac.css
index a99fce958a5..a99fce958a5 100644
--- a/chromium/third_party/blink/renderer/core/css/themeMac.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/mac.css
diff --git a/chromium/third_party/blink/renderer/core/css/quirks.css b/chromium/third_party/blink/renderer/core/html/resources/quirks.css
index e880fe0e90f..e880fe0e90f 100644
--- a/chromium/third_party/blink/renderer/core/css/quirks.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/quirks.css
diff --git a/chromium/third_party/blink/renderer/core/css/themeWin.css b/chromium/third_party/blink/renderer/core/html/resources/win.css
index ed659eed4df..e3d49d191b9 100644
--- a/chromium/third_party/blink/renderer/core/css/themeWin.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/win.css
@@ -29,13 +29,13 @@
*/
/* These styles override the default styling for HTML elements as defined in
- WebCore/css/html.css. So far we have used this file exclusively for
- making our form elements match Firefox's. */
+ core/html/resources/tml.css. So far we have used this file exclusively
+ for making our form elements match Firefox's. */
/*
* Update padding for all text-like types including unknown types.
* Non-text types have input[type="foo" i] with padding properties in
- * html.css or themeInputMultipleFields.css.
+ * html.css or input_multiple_fields.css.
*/
input {
padding:1px 0;
diff --git a/chromium/third_party/blink/renderer/core/css/themeWinQuirks.css b/chromium/third_party/blink/renderer/core/html/resources/win_quirks.css
index c69b74c7146..196d082011d 100644
--- a/chromium/third_party/blink/renderer/core/css/themeWinQuirks.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/win_quirks.css
@@ -29,8 +29,8 @@
*/
/* These styles override the default styling for HTML elements in quirks-mode
- as defined in WebCore/css/quirks.css. So far we have used this file exclusively for
- making our form elements match Firefox's. */
+ as defined in core/html/resources/quirks.css. So far we have used this
+ file exclusively for making our form elements match Firefox's. */
textarea {
/* Matches IE's text offsets in quirksmode (causes text to wrap the same as IE). */
diff --git a/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.cc b/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.cc
index b60bd081ad3..a57b5ce5e63 100644
--- a/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.cc
+++ b/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.cc
@@ -31,13 +31,10 @@
#include "third_party/blink/renderer/core/html/shadow/details_marker_control.h"
#include "third_party/blink/renderer/core/html/html_summary_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_details_marker.h"
namespace blink {
-using namespace HTMLNames;
-
DetailsMarkerControl::DetailsMarkerControl(Document& document)
: HTMLDivElement(document) {}
diff --git a/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.h b/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.h
index 4a4740a521f..95f42761a4e 100644
--- a/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.h
+++ b/chromium/third_party/blink/renderer/core/html/shadow/details_marker_control.h
@@ -51,7 +51,8 @@ class DetailsMarkerControl final : public HTMLDivElement {
};
inline DetailsMarkerControl* DetailsMarkerControl::Create(Document& document) {
- DetailsMarkerControl* element = new DetailsMarkerControl(document);
+ DetailsMarkerControl* element =
+ MakeGarbageCollected<DetailsMarkerControl>(document);
element->SetShadowPseudoId(AtomicString("-webkit-details-marker"));
return element;
}
diff --git a/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element.cc b/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element.cc
index a59576cf9cd..0532db10600 100644
--- a/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element.cc
@@ -32,12 +32,9 @@
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/html/html_progress_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
namespace blink {
-using namespace HTMLNames;
-
ProgressShadowElement::ProgressShadowElement(Document& document)
: HTMLDivElement(document) {}
diff --git a/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element_test.cc b/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element_test.cc
index 213362bd671..3536077ee96 100644
--- a/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element_test.cc
@@ -37,7 +37,8 @@ TEST_F(ProgressShadowElementTest, LayoutObjectIsNeeded) {
Element* shadow_element = ToElement(progress->GetShadowRoot()->firstChild());
ASSERT_TRUE(shadow_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
progress->LazyReattachIfAttached();
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
diff --git a/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.cc b/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.cc
index 1c8be6321d3..5acf6932e3f 100644
--- a/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.cc
+++ b/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.cc
@@ -32,7 +32,7 @@
namespace blink {
-namespace ShadowElementNames {
+namespace shadow_element_names {
const AtomicString& DetailsContent() {
DEFINE_STATIC_LOCAL(AtomicString, name, ("details-content"));
@@ -109,6 +109,6 @@ const AtomicString& OptGroupLabel() {
return name;
}
-} // namespace ShadowElementNames
+} // namespace shadow_element_names
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.h b/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.h
index 9f02f2b5494..8de90495cef 100644
--- a/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.h
+++ b/chromium/third_party/blink/renderer/core/html/shadow/shadow_element_names.h
@@ -36,7 +36,7 @@
namespace blink {
-namespace ShadowElementNames {
+namespace shadow_element_names {
const AtomicString& DetailsContent();
const AtomicString& DetailsSummary();
@@ -54,7 +54,7 @@ const AtomicString& SliderTrack();
const AtomicString& TextFieldContainer();
const AtomicString& OptGroupLabel();
-} // namespace ShadowElementNames
+} // namespace shadow_element_names
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/text_document.h b/chromium/third_party/blink/renderer/core/html/text_document.h
index 0d93748f0de..bdff4437d40 100644
--- a/chromium/third_party/blink/renderer/core/html/text_document.h
+++ b/chromium/third_party/blink/renderer/core/html/text_document.h
@@ -32,12 +32,12 @@ namespace blink {
class TextDocument final : public HTMLDocument {
public:
static TextDocument* Create(const DocumentInit& initializer) {
- return new TextDocument(initializer);
+ return MakeGarbageCollected<TextDocument>(initializer);
}
- private:
TextDocument(const DocumentInit&);
+ private:
DocumentParser* CreateParser() override;
};
diff --git a/chromium/third_party/blink/renderer/core/html/time_ranges.h b/chromium/third_party/blink/renderer/core/html/time_ranges.h
index 983e2f111c7..c8ed9af8bd0 100644
--- a/chromium/third_party/blink/renderer/core/html/time_ranges.h
+++ b/chromium/third_party/blink/renderer/core/html/time_ranges.h
@@ -84,12 +84,15 @@ class CORE_EXPORT TimeRanges final : public ScriptWrappable {
}
};
- static TimeRanges* Create() { return new TimeRanges; }
+ static TimeRanges* Create() { return MakeGarbageCollected<TimeRanges>(); }
static TimeRanges* Create(double start, double end) {
- return new TimeRanges(start, end);
+ return MakeGarbageCollected<TimeRanges>(start, end);
}
static TimeRanges* Create(const WebTimeRanges&);
+ TimeRanges() = default;
+ TimeRanges(double start, double end);
+
TimeRanges* Copy() const;
void IntersectWith(const TimeRanges*);
void UnionWith(const TimeRanges*);
@@ -106,10 +109,6 @@ class CORE_EXPORT TimeRanges final : public ScriptWrappable {
double current_playback_position) const;
private:
- TimeRanges() = default;
-
- TimeRanges(double start, double end);
-
void Invert();
Vector<Range> ranges_;
diff --git a/chromium/third_party/blink/renderer/core/html/track/audio_track_list.cc b/chromium/third_party/blink/renderer/core/html/track/audio_track_list.cc
index 9c306e33048..0b9cb73be56 100644
--- a/chromium/third_party/blink/renderer/core/html/track/audio_track_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/audio_track_list.cc
@@ -25,7 +25,7 @@ bool AudioTrackList::HasEnabledTrack() const {
}
const AtomicString& AudioTrackList::InterfaceName() const {
- return EventTargetNames::AudioTrackList;
+ return event_target_names::kAudioTrackList;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/track/cue_timeline.cc b/chromium/third_party/blink/renderer/core/html/track/cue_timeline.cc
index 791d3112662..37f7e02c0fb 100644
--- a/chromium/third_party/blink/renderer/core/html/track/cue_timeline.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/cue_timeline.cc
@@ -299,13 +299,13 @@ void CueTimeline::UpdateActiveCues(double movie_time) {
// less than the endTime in the cue.
if (task.second->startTime() >= task.second->endTime()) {
media_element.ScheduleEvent(
- CreateEventWithTarget(EventTypeNames::enter, task.second.Get()));
+ CreateEventWithTarget(event_type_names::kEnter, task.second.Get()));
media_element.ScheduleEvent(
- CreateEventWithTarget(EventTypeNames::exit, task.second.Get()));
+ CreateEventWithTarget(event_type_names::kExit, task.second.Get()));
} else {
bool is_enter_event = task.first == task.second->startTime();
AtomicString event_name =
- is_enter_event ? EventTypeNames::enter : EventTypeNames::exit;
+ is_enter_event ? event_type_names::kEnter : event_type_names::kExit;
media_element.ScheduleEvent(
CreateEventWithTarget(event_name, task.second.Get()));
}
@@ -320,7 +320,7 @@ void CueTimeline::UpdateActiveCues(double movie_time) {
// ...
for (const auto& track : affected_tracks) {
media_element.ScheduleEvent(
- CreateEventWithTarget(EventTypeNames::cuechange, track.Get()));
+ CreateEventWithTarget(event_type_names::kCuechange, track.Get()));
// ... if the text track has a corresponding track element, to then fire a
// simple event named cuechange at the track element as well.
@@ -329,7 +329,7 @@ void CueTimeline::UpdateActiveCues(double movie_time) {
ToLoadableTextTrack(track.Get())->TrackElement();
DCHECK(track_element);
media_element.ScheduleEvent(
- CreateEventWithTarget(EventTypeNames::cuechange, track_element));
+ CreateEventWithTarget(event_type_names::kCuechange, track_element));
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/track/html_track_element.cc b/chromium/third_party/blink/renderer/core/html/track/html_track_element.cc
index ba60beffed9..21b74d44baa 100644
--- a/chromium/third_party/blink/renderer/core/html/track/html_track_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/html_track_element.cc
@@ -38,7 +38,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static String UrlForLoggingTrack(const KURL& url) {
static const unsigned kMaximumURLLengthForLogging = 128;
@@ -49,7 +49,7 @@ static String UrlForLoggingTrack(const KURL& url) {
}
inline HTMLTrackElement::HTMLTrackElement(Document& document)
- : HTMLElement(trackTag, document),
+ : HTMLElement(kTrackTag, document),
load_timer_(document.GetTaskRunner(TaskType::kNetworking),
this,
&HTMLTrackElement::LoadTimerFired) {
@@ -89,13 +89,13 @@ void HTMLTrackElement::RemovedFrom(ContainerNode& insertion_point) {
void HTMLTrackElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == srcAttr) {
+ if (name == kSrcAttr) {
ScheduleLoad();
// 4.8.10.12.3 Sourcing out-of-band text tracks
// As the kind, label, and srclang attributes are set, changed, or removed,
// the text track must update accordingly...
- } else if (name == kindAttr) {
+ } else if (name == kKindAttr) {
AtomicString lower_case_value = params.new_value.LowerASCII();
// 'missing value default' ("subtitles")
if (lower_case_value.IsNull())
@@ -105,11 +105,11 @@ void HTMLTrackElement::ParseAttribute(
lower_case_value = TextTrack::MetadataKeyword();
track()->SetKind(lower_case_value);
- } else if (name == labelAttr) {
+ } else if (name == kLabelAttr) {
track()->SetLabel(params.new_value);
- } else if (name == srclangAttr) {
+ } else if (name == kSrclangAttr) {
track()->SetLanguage(params.new_value);
- } else if (name == idAttr) {
+ } else if (name == kIdAttr) {
track()->SetId(params.new_value);
}
@@ -121,7 +121,7 @@ const AtomicString& HTMLTrackElement::kind() {
}
void HTMLTrackElement::setKind(const AtomicString& kind) {
- setAttribute(kindAttr, kind);
+ setAttribute(kKindAttr, kind);
}
LoadableTextTrack* HTMLTrackElement::EnsureTrack() {
@@ -137,7 +137,7 @@ TextTrack* HTMLTrackElement::track() {
}
bool HTMLTrackElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName() == srcAttr ||
+ return attribute.GetName() == kSrcAttr ||
HTMLElement::IsURLAttribute(attribute);
}
@@ -175,7 +175,7 @@ void HTMLTrackElement::LoadTimerFired(TimerBase*) {
DVLOG(TRACK_LOG_LEVEL) << "loadTimerFired";
// 7. [X] Let URL be the track URL of the track element.
- KURL url = GetNonEmptyURLAttribute(srcAttr);
+ KURL url = GetNonEmptyURLAttribute(kSrcAttr);
// Whenever a track element has its src attribute set, changed,
// or removed, the user agent must immediately empty the
@@ -265,7 +265,7 @@ void HTMLTrackElement::DidCompleteLoad(LoadStatus status) {
// simple event named error at the track element.
if (status == kFailure) {
SetReadyState(kError);
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
return;
}
@@ -275,7 +275,7 @@ void HTMLTrackElement::DidCompleteLoad(LoadStatus status) {
// readiness state to loaded, and fire a simple event named load at the track
// element.
SetReadyState(kLoaded);
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
}
void HTMLTrackElement::NewCuesAvailable(TextTrackLoader* loader) {
@@ -327,7 +327,7 @@ HTMLTrackElement::ReadyState HTMLTrackElement::getReadyState() {
const AtomicString& HTMLTrackElement::MediaElementCrossOriginAttribute() const {
if (HTMLMediaElement* parent = MediaElement())
- return parent->FastGetAttribute(HTMLNames::crossoriginAttr);
+ return parent->FastGetAttribute(html_names::kCrossoriginAttr);
return g_null_atom;
}
diff --git a/chromium/third_party/blink/renderer/core/html/track/inband_text_track.cc b/chromium/third_party/blink/renderer/core/html/track/inband_text_track.cc
index 454642cd60c..3c0f256c32d 100644
--- a/chromium/third_party/blink/renderer/core/html/track/inband_text_track.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/inband_text_track.cc
@@ -60,7 +60,7 @@ const AtomicString& TextTrackKindToString(WebInbandTextTrack::Kind kind) {
} // namespace
InbandTextTrack* InbandTextTrack::Create(WebInbandTextTrack* web_track) {
- return new InbandTextTrack(web_track);
+ return MakeGarbageCollected<InbandTextTrack>(web_track);
}
InbandTextTrack::InbandTextTrack(WebInbandTextTrack* web_track)
diff --git a/chromium/third_party/blink/renderer/core/html/track/inband_text_track.h b/chromium/third_party/blink/renderer/core/html/track/inband_text_track.h
index 6d4c15ff4b0..819df92fa70 100644
--- a/chromium/third_party/blink/renderer/core/html/track/inband_text_track.h
+++ b/chromium/third_party/blink/renderer/core/html/track/inband_text_track.h
@@ -42,13 +42,13 @@ class InbandTextTrack final : public TextTrack,
public WebInbandTextTrackClient {
public:
static InbandTextTrack* Create(WebInbandTextTrack*);
+
+ explicit InbandTextTrack(WebInbandTextTrack*);
~InbandTextTrack() override;
void SetTrackList(TextTrackList*) override;
private:
- explicit InbandTextTrack(WebInbandTextTrack*);
-
void AddWebVTTCue(double,
double,
const WebString&,
diff --git a/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.cc b/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.cc
index 5cc4303c694..adc5bf3e86d 100644
--- a/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.cc
@@ -43,7 +43,7 @@ LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track)
LoadableTextTrack::~LoadableTextTrack() = default;
bool LoadableTextTrack::IsDefault() const {
- return track_element_->FastHasAttribute(HTMLNames::defaultAttr);
+ return track_element_->FastHasAttribute(html_names::kDefaultAttr);
}
void LoadableTextTrack::setMode(const AtomicString& mode) {
diff --git a/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.h b/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.h
index fd35fee038c..2a5f44c740b 100644
--- a/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.h
+++ b/chromium/third_party/blink/renderer/core/html/track/loadable_text_track.h
@@ -37,8 +37,10 @@ class HTMLTrackElement;
class LoadableTextTrack final : public TextTrack {
public:
static LoadableTextTrack* Create(HTMLTrackElement* track) {
- return new LoadableTextTrack(track);
+ return MakeGarbageCollected<LoadableTextTrack>(track);
}
+
+ explicit LoadableTextTrack(HTMLTrackElement*);
~LoadableTextTrack() override;
// TextTrack method.
@@ -54,8 +56,6 @@ class LoadableTextTrack final : public TextTrack {
void Trace(blink::Visitor*) override;
private:
- explicit LoadableTextTrack(HTMLTrackElement*);
-
Member<HTMLTrackElement> track_element_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track.cc b/chromium/third_party/blink/renderer/core/html/track/text_track.cc
index 36828b44680..59c52cdb198 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track.cc
@@ -348,7 +348,7 @@ int TextTrack::TrackIndexRelativeToRenderedTracks() {
}
const AtomicString& TextTrack::InterfaceName() const {
- return EventTargetNames::TextTrack;
+ return event_target_names::kTextTrack;
}
ExecutionContext* TextTrack::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track.h b/chromium/third_party/blink/renderer/core/html/track/text_track.h
index 323e86eeb7c..6f291977244 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track.h
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track.h
@@ -53,8 +53,17 @@ class CORE_EXPORT TextTrack : public EventTargetWithInlineData,
static TextTrack* Create(const AtomicString& kind,
const AtomicString& label,
const AtomicString& language) {
- return new TextTrack(kind, label, language, g_empty_atom, kAddTrack);
+ return MakeGarbageCollected<TextTrack>(kind, label, language, g_empty_atom,
+ kAddTrack);
}
+
+ enum TextTrackType { kTrackElement, kAddTrack, kInBand };
+
+ TextTrack(const AtomicString& kind,
+ const AtomicString& label,
+ const AtomicString& language,
+ const AtomicString& id,
+ TextTrackType);
~TextTrack() override;
virtual void SetTrackList(TextTrackList*);
@@ -102,9 +111,8 @@ class CORE_EXPORT TextTrack : public EventTargetWithInlineData,
void CueWillChange(TextTrackCue*);
void CueDidChange(TextTrackCue*, bool update_cue_index);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(cuechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(cuechange, kCuechange);
- enum TextTrackType { kTrackElement, kAddTrack, kInBand };
TextTrackType TrackType() const { return track_type_; }
int TrackIndex();
@@ -128,12 +136,6 @@ class CORE_EXPORT TextTrack : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
protected:
- TextTrack(const AtomicString& kind,
- const AtomicString& label,
- const AtomicString& language,
- const AtomicString& id,
- TextTrackType);
-
void AddListOfCues(HeapVector<Member<TextTrackCue>>&);
private:
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_container.cc b/chromium/third_party/blink/renderer/core/html/track/text_track_container.cc
index f2b58c04b6a..8a571082375 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_container.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_container.cc
@@ -77,7 +77,7 @@ void TextTrackContainer::Trace(blink::Visitor* visitor) {
TextTrackContainer* TextTrackContainer::Create(
HTMLMediaElement& media_element) {
TextTrackContainer* element =
- new TextTrackContainer(media_element.GetDocument());
+ MakeGarbageCollected<TextTrackContainer>(media_element.GetDocument());
element->SetShadowPseudoId(
AtomicString("-webkit-media-text-track-container"));
if (IsHTMLVideoElement(media_element))
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_container.h b/chromium/third_party/blink/renderer/core/html/track/text_track_container.h
index d265cd73ec7..01a234e7400 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_container.h
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_container.h
@@ -40,6 +40,8 @@ class TextTrackContainer final : public HTMLDivElement {
public:
static TextTrackContainer* Create(HTMLMediaElement&);
+ TextTrackContainer(Document&);
+
// Runs the "rules for updating the text track rendering". The
// ExposingControls enum is used in the WebVTT processing model to reset the
// layout when the media controls become visible, to avoid overlapping them.
@@ -53,8 +55,6 @@ class TextTrackContainer final : public HTMLDivElement {
void Trace(blink::Visitor*) override;
private:
- TextTrackContainer(Document&);
-
bool IsTextTrackContainer() const override { return true; }
void ObserveSizeChanges(Element&);
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_cue.cc b/chromium/third_party/blink/renderer/core/html/track/text_track_cue.cc
index 2c037af48f5..ee1c59a070e 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_cue.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_cue.cc
@@ -129,7 +129,7 @@ DispatchEventResult TextTrackCue::DispatchEventInternal(Event& event) {
}
const AtomicString& TextTrackCue::InterfaceName() const {
- return EventTargetNames::TextTrackCue;
+ return event_target_names::kTextTrackCue;
}
void TextTrackCue::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_cue.h b/chromium/third_party/blink/renderer/core/html/track/text_track_cue.h
index 51d3734993d..e992c3ff305 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_cue.h
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_cue.h
@@ -94,8 +94,8 @@ class TextTrackCue : public EventTargetWithInlineData {
virtual String ToString() const = 0;
#endif
- DEFINE_ATTRIBUTE_EVENT_LISTENER(enter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(exit);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(enter, kEnter);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(exit, kExit);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.h b/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.h
index a72890ca84e..a08d4e41d9a 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.h
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.h
@@ -37,7 +37,11 @@ class TextTrackCueList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static TextTrackCueList* Create() { return new TextTrackCueList; }
+ static TextTrackCueList* Create() {
+ return MakeGarbageCollected<TextTrackCueList>();
+ }
+
+ TextTrackCueList();
wtf_size_t length() const;
@@ -59,7 +63,6 @@ class TextTrackCueList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- TextTrackCueList();
wtf_size_t FindInsertionIndex(const TextTrackCue*) const;
void InvalidateCueIndex(wtf_size_t index);
void Clear();
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_list.cc b/chromium/third_party/blink/renderer/core/html/track/text_track_list.cc
index ae30ca5edb2..126f1e0eb46 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_list.cc
@@ -236,7 +236,7 @@ bool TextTrackList::Contains(TextTrack* track) const {
}
const AtomicString& TextTrackList::InterfaceName() const {
- return EventTargetNames::TextTrackList;
+ return event_target_names::kTextTrackList;
}
ExecutionContext* TextTrackList::GetExecutionContext() const {
@@ -256,7 +256,7 @@ void TextTrackList::ScheduleAddTrackEvent(TextTrack* track) {
// not bubble and is not cancelable, and that uses the TrackEvent interface,
// with the track attribute initialized to the text track's TextTrack object,
// at the media element's textTracks attribute's TextTrackList object.
- ScheduleTrackEvent(EventTypeNames::addtrack, track);
+ ScheduleTrackEvent(event_type_names::kAddtrack, track);
}
void TextTrackList::ScheduleChangeEvent() {
@@ -267,7 +267,7 @@ void TextTrackList::ScheduleChangeEvent() {
// ...
// Fire a simple event named change at the media element's textTracks
// attribute's TextTrackList object.
- EnqueueEvent(*Event::Create(EventTypeNames::change),
+ EnqueueEvent(*Event::Create(event_type_names::kChange),
TaskType::kMediaElementEvent);
}
@@ -281,7 +281,7 @@ void TextTrackList::ScheduleRemoveTrackEvent(TextTrack* track) {
// interface, with the track attribute initialized to the text track's
// TextTrack object, at the media element's textTracks attribute's
// TextTrackList object.
- ScheduleTrackEvent(EventTypeNames::removetrack, track);
+ ScheduleTrackEvent(event_type_names::kRemovetrack, track);
}
bool TextTrackList::HasShowingTracks() {
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_list.h b/chromium/third_party/blink/renderer/core/html/track/text_track_list.h
index 45fde7480e2..f8f8ad3f4e7 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_list.h
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_list.h
@@ -43,8 +43,10 @@ class CORE_EXPORT TextTrackList final : public EventTargetWithInlineData {
public:
static TextTrackList* Create(HTMLMediaElement* owner) {
- return new TextTrackList(owner);
+ return MakeGarbageCollected<TextTrackList>(owner);
}
+
+ explicit TextTrackList(HTMLMediaElement*);
~TextTrackList() override;
unsigned length() const;
@@ -61,9 +63,9 @@ class CORE_EXPORT TextTrackList final : public EventTargetWithInlineData {
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack, kAddtrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack, kRemovetrack);
HTMLMediaElement* Owner() const;
@@ -75,8 +77,6 @@ class CORE_EXPORT TextTrackList final : public EventTargetWithInlineData {
void Trace(blink::Visitor*) override;
private:
- explicit TextTrackList(HTMLMediaElement*);
-
void ScheduleTrackEvent(const AtomicString& event_name, TextTrack*);
void ScheduleAddTrackEvent(TextTrack*);
diff --git a/chromium/third_party/blink/renderer/core/html/track/track_event.cc b/chromium/third_party/blink/renderer/core/html/track/track_event.cc
index 88ef5ca41f7..218fb465a53 100644
--- a/chromium/third_party/blink/renderer/core/html/track/track_event.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/track_event.cc
@@ -27,6 +27,7 @@
#include "third_party/blink/public/platform/web_media_player.h"
#include "third_party/blink/renderer/bindings/core/v8/video_track_or_audio_track_or_text_track.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
#include "third_party/blink/renderer/core/html/track/audio_track.h"
#include "third_party/blink/renderer/core/html/track/text_track.h"
#include "third_party/blink/renderer/core/html/track/video_track.h"
@@ -36,12 +37,12 @@ namespace blink {
TrackEvent::TrackEvent() = default;
TrackEvent::TrackEvent(const AtomicString& type,
- const TrackEventInit& initializer)
+ const TrackEventInit* initializer)
: Event(type, initializer) {
- if (!initializer.hasTrack())
+ if (!initializer->hasTrack())
return;
- const VideoTrackOrAudioTrackOrTextTrack& track = initializer.track();
+ const VideoTrackOrAudioTrackOrTextTrack& track = initializer->track();
if (track.IsVideoTrack())
track_ = track.GetAsVideoTrack();
else if (track.IsAudioTrack())
@@ -55,7 +56,7 @@ TrackEvent::TrackEvent(const AtomicString& type,
TrackEvent::~TrackEvent() = default;
const AtomicString& TrackEvent::InterfaceName() const {
- return EventNames::TrackEvent;
+ return event_interface_names::kTrackEvent;
}
void TrackEvent::track(VideoTrackOrAudioTrackOrTextTrack& return_value) {
diff --git a/chromium/third_party/blink/renderer/core/html/track/track_event.h b/chromium/third_party/blink/renderer/core/html/track/track_event.h
index 9349378700b..ce10e6c3f87 100644
--- a/chromium/third_party/blink/renderer/core/html/track/track_event.h
+++ b/chromium/third_party/blink/renderer/core/html/track/track_event.h
@@ -38,18 +38,21 @@ class CORE_EXPORT TrackEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ TrackEvent();
+ TrackEvent(const AtomicString& type, const TrackEventInit* initializer);
+ TrackEvent(const AtomicString& type, TrackBase* track)
+ : Event(type, Bubbles::kNo, Cancelable::kNo), track_(track) {}
~TrackEvent() override;
- static TrackEvent* Create() { return new TrackEvent; }
+ static TrackEvent* Create() { return MakeGarbageCollected<TrackEvent>(); }
static TrackEvent* Create(const AtomicString& type,
- const TrackEventInit& initializer) {
- return new TrackEvent(type, initializer);
+ const TrackEventInit* initializer) {
+ return MakeGarbageCollected<TrackEvent>(type, initializer);
}
- template <typename T>
- static TrackEvent* Create(const AtomicString& type, T* track) {
- return new TrackEvent(type, track);
+ static TrackEvent* Create(const AtomicString& type, TrackBase* track) {
+ return MakeGarbageCollected<TrackEvent>(type, track);
}
const AtomicString& InterfaceName() const override;
@@ -59,12 +62,6 @@ class CORE_EXPORT TrackEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- TrackEvent();
- TrackEvent(const AtomicString& type, const TrackEventInit& initializer);
- template <typename T>
- TrackEvent(const AtomicString& type, T* track)
- : Event(type, Bubbles::kNo, Cancelable::kNo), track_(track) {}
-
Member<TrackBase> track_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/track/track_list_base.h b/chromium/third_party/blink/renderer/core/html/track/track_list_base.h
index 0ddbf151553..ebfc9ac6d80 100644
--- a/chromium/third_party/blink/renderer/core/html/track/track_list_base.h
+++ b/chromium/third_party/blink/renderer/core/html/track/track_list_base.h
@@ -37,9 +37,9 @@ class TrackListBase : public EventTargetWithInlineData {
return nullptr;
}
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack, kAddtrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack, kRemovetrack);
// EventTarget interface
ExecutionContext* GetExecutionContext() const override {
@@ -51,7 +51,7 @@ class TrackListBase : public EventTargetWithInlineData {
void Add(T* track) {
track->SetMediaElement(media_element_);
tracks_.push_back(track);
- ScheduleEvent(TrackEvent::Create(EventTypeNames::addtrack, track));
+ ScheduleEvent(TrackEvent::Create(event_type_names::kAddtrack, track));
}
void Remove(WebMediaPlayer::TrackId track_id) {
@@ -61,7 +61,7 @@ class TrackListBase : public EventTargetWithInlineData {
tracks_[i]->SetMediaElement(nullptr);
ScheduleEvent(
- TrackEvent::Create(EventTypeNames::removetrack, tracks_[i].Get()));
+ TrackEvent::Create(event_type_names::kRemovetrack, tracks_[i].Get()));
tracks_.EraseAt(i);
return;
}
@@ -76,7 +76,7 @@ class TrackListBase : public EventTargetWithInlineData {
}
void ScheduleChangeEvent() {
- ScheduleEvent(Event::Create(EventTypeNames::change));
+ ScheduleEvent(Event::Create(event_type_names::kChange));
}
void Trace(blink::Visitor* visitor) override {
diff --git a/chromium/third_party/blink/renderer/core/html/track/video_track.h b/chromium/third_party/blink/renderer/core/html/track/video_track.h
index 1e922dea2bc..3f836c9a67b 100644
--- a/chromium/third_party/blink/renderer/core/html/track/video_track.h
+++ b/chromium/third_party/blink/renderer/core/html/track/video_track.h
@@ -21,10 +21,16 @@ class CORE_EXPORT VideoTrack final : public ScriptWrappable, public TrackBase {
const AtomicString& label,
const AtomicString& language,
bool selected) {
- return new VideoTrack(id, IsValidKindKeyword(kind) ? kind : g_empty_atom,
- label, language, selected);
+ return MakeGarbageCollected<VideoTrack>(
+ id, IsValidKindKeyword(kind) ? kind : g_empty_atom, label, language,
+ selected);
}
+ VideoTrack(const String& id,
+ const AtomicString& kind,
+ const AtomicString& label,
+ const AtomicString& language,
+ bool selected);
~VideoTrack() override;
void Trace(blink::Visitor*) override;
@@ -46,12 +52,6 @@ class CORE_EXPORT VideoTrack final : public ScriptWrappable, public TrackBase {
static bool IsValidKindKeyword(const String&);
private:
- VideoTrack(const String& id,
- const AtomicString& kind,
- const AtomicString& label,
- const AtomicString& language,
- bool selected);
-
bool selected_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/track/video_track_list.cc b/chromium/third_party/blink/renderer/core/html/track/video_track_list.cc
index b782edd1c69..a84e34adf44 100644
--- a/chromium/third_party/blink/renderer/core/html/track/video_track_list.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/video_track_list.cc
@@ -10,7 +10,7 @@
namespace blink {
VideoTrackList* VideoTrackList::Create(HTMLMediaElement& media_element) {
- return new VideoTrackList(media_element);
+ return MakeGarbageCollected<VideoTrackList>(media_element);
}
VideoTrackList::~VideoTrackList() = default;
@@ -19,7 +19,7 @@ VideoTrackList::VideoTrackList(HTMLMediaElement& media_element)
: TrackListBase<VideoTrack>(&media_element) {}
const AtomicString& VideoTrackList::InterfaceName() const {
- return EventTargetNames::VideoTrackList;
+ return event_target_names::kVideoTrackList;
}
int VideoTrackList::selectedIndex() const {
diff --git a/chromium/third_party/blink/renderer/core/html/track/video_track_list.h b/chromium/third_party/blink/renderer/core/html/track/video_track_list.h
index 2d1b95c75d9..fbe37cf3618 100644
--- a/chromium/third_party/blink/renderer/core/html/track/video_track_list.h
+++ b/chromium/third_party/blink/renderer/core/html/track/video_track_list.h
@@ -16,6 +16,7 @@ class CORE_EXPORT VideoTrackList final : public TrackListBase<VideoTrack> {
public:
static VideoTrackList* Create(HTMLMediaElement&);
+ explicit VideoTrackList(HTMLMediaElement&);
~VideoTrackList() override;
int selectedIndex() const;
@@ -28,9 +29,6 @@ class CORE_EXPORT VideoTrackList final : public TrackListBase<VideoTrack> {
void Trace(blink::Visitor* visitor) override {
TrackListBase<VideoTrack>::Trace(visitor);
}
-
- private:
- explicit VideoTrackList(HTMLMediaElement&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc
index a147bf0f02e..df6990bb286 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/core/html/track/vtt/vtt_cue.h"
#include "third_party/blink/renderer/bindings/core/v8/double_or_auto_keyword.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
@@ -530,8 +530,8 @@ class VTTTextRunIterator : public TextRunIterator {
// Within a cue, paragraph boundaries are only denoted by Type B characters,
// such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL),
// and U+2029 PARAGRAPH SEPARATOR.
- return WTF::Unicode::Category(Current()) &
- WTF::Unicode::kSeparator_Paragraph;
+ return WTF::unicode::Category(Current()) &
+ WTF::unicode::kSeparator_Paragraph;
}
};
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h
index 59271258e49..2d2df08047c 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h
@@ -62,14 +62,14 @@ struct VTTDisplayParameters {
class VTTCueBox final : public HTMLDivElement {
public:
static VTTCueBox* Create(Document& document) {
- return new VTTCueBox(document);
+ return MakeGarbageCollected<VTTCueBox>(document);
}
+ explicit VTTCueBox(Document&);
+
void ApplyCSSProperties(const VTTDisplayParameters&);
private:
- explicit VTTCueBox(Document&);
-
LayoutObject* CreateLayoutObject(const ComputedStyle&) override;
// The computed line position for snap-to-lines layout, and NaN for
@@ -86,9 +86,10 @@ class VTTCue final : public TextTrackCue {
double start_time,
double end_time,
const String& text) {
- return new VTTCue(document, start_time, end_time, text);
+ return MakeGarbageCollected<VTTCue>(document, start_time, end_time, text);
}
+ VTTCue(Document&, double start_time, double end_time, const String& text);
~VTTCue() override;
VTTRegion* region() const { return region_; }
@@ -157,8 +158,6 @@ class VTTCue final : public TextTrackCue {
void Trace(blink::Visitor*) override;
private:
- VTTCue(Document&, double start_time, double end_time, const String& text);
-
Document& GetDocument() const;
VTTCueBox* GetDisplayTree();
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.cc b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.cc
index 4e705cf4b64..1ca3c8f1ad0 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.cc
@@ -71,7 +71,7 @@ VTTElement::VTTElement(VTTNodeType node_type, Document* document)
web_vtt_node_type_(node_type) {}
VTTElement* VTTElement::Create(VTTNodeType node_type, Document* document) {
- return new VTTElement(node_type, document);
+ return MakeGarbageCollected<VTTElement>(node_type, document);
}
Element* VTTElement::CloneWithoutAttributesAndChildren(
@@ -88,39 +88,39 @@ HTMLElement* VTTElement::CreateEquivalentHTMLElement(Document& document) {
case kVTTNodeTypeClass:
case kVTTNodeTypeLanguage:
case kVTTNodeTypeVoice:
- html_element = document.CreateRawElement(HTMLNames::spanTag,
+ html_element = document.CreateRawElement(html_names::kSpanTag,
CreateElementFlags::ByParser());
- html_element->setAttribute(HTMLNames::titleAttr,
+ html_element->setAttribute(html_names::kTitleAttr,
getAttribute(VoiceAttributeName()));
- html_element->setAttribute(HTMLNames::langAttr,
+ html_element->setAttribute(html_names::kLangAttr,
getAttribute(LangAttributeName()));
break;
case kVTTNodeTypeItalic:
- html_element = document.CreateRawElement(HTMLNames::iTag,
+ html_element = document.CreateRawElement(html_names::kITag,
CreateElementFlags::ByParser());
break;
case kVTTNodeTypeBold:
- html_element = document.CreateRawElement(HTMLNames::bTag,
+ html_element = document.CreateRawElement(html_names::kBTag,
CreateElementFlags::ByParser());
break;
case kVTTNodeTypeUnderline:
- html_element = document.CreateRawElement(HTMLNames::uTag,
+ html_element = document.CreateRawElement(html_names::kUTag,
CreateElementFlags::ByParser());
break;
case kVTTNodeTypeRuby:
- html_element = document.CreateRawElement(HTMLNames::rubyTag,
+ html_element = document.CreateRawElement(html_names::kRubyTag,
CreateElementFlags::ByParser());
break;
case kVTTNodeTypeRubyText:
- html_element = document.CreateRawElement(HTMLNames::rtTag,
+ html_element = document.CreateRawElement(html_names::kRtTag,
CreateElementFlags::ByParser());
break;
default:
NOTREACHED();
}
- html_element->setAttribute(HTMLNames::classAttr,
- getAttribute(HTMLNames::classAttr));
+ html_element->setAttribute(html_names::kClassAttr,
+ getAttribute(html_names::kClassAttr));
return ToHTMLElement(html_element);
}
@@ -132,7 +132,7 @@ void VTTElement::SetIsPastNode(bool is_past_node) {
SetNeedsStyleRecalc(
kLocalStyleChange,
StyleChangeReasonForTracing::CreateWithExtraData(
- StyleChangeReason::kPseudoClass, StyleChangeExtraData::g_past));
+ style_change_reason::kPseudoClass, style_change_extra_data::g_past));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.h
index d7abc856c1c..7e4f9f3fe0b 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_element.h
@@ -48,6 +48,9 @@ class VTTElement final : public Element {
static VTTElement* Create(const QualifiedName&, Document*);
HTMLElement* CreateEquivalentHTMLElement(Document&);
+ VTTElement(const QualifiedName&, Document*);
+ VTTElement(VTTNodeType, Document*);
+
Element* CloneWithoutAttributesAndChildren(Document&) const override;
void SetVTTNodeType(VTTNodeType type) {
@@ -77,9 +80,6 @@ class VTTElement final : public Element {
}
private:
- VTTElement(const QualifiedName&, Document*);
- VTTElement(VTTNodeType, Document*);
-
unsigned is_past_node_ : 1;
unsigned web_vtt_node_type_ : 4;
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.cc b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.cc
index 4a36c646621..42c93811aa4 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.cc
@@ -45,7 +45,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
const unsigned kFileIdentifierLength = 6;
const unsigned kRegionIdentifierLength = 6;
@@ -542,7 +542,7 @@ void VTTTreeBuilder::ConstructTreeFromToken(Document& document) {
VTTElement* child = VTTElement::Create(node_type, &document);
if (!token_.Classes().IsEmpty())
- child->setAttribute(classAttr, token_.Classes());
+ child->setAttribute(kClassAttr, token_.Classes());
if (node_type == kVTTNodeTypeVoice) {
child->setAttribute(VTTElement::VoiceAttributeName(),
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.h
index e3ef84fd4ab..209228dc495 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.h
@@ -71,14 +71,16 @@ class VTTParser final : public GarbageCollectedFinalized<VTTParser> {
};
static VTTParser* Create(VTTParserClient* client, Document& document) {
- return new VTTParser(client, document);
+ return MakeGarbageCollected<VTTParser>(client, document);
}
+
+ VTTParser(VTTParserClient*, Document&);
~VTTParser() = default;
static inline bool IsRecognizedTag(const AtomicString& tag_name) {
- return tag_name == HTMLNames::iTag || tag_name == HTMLNames::bTag ||
- tag_name == HTMLNames::uTag || tag_name == HTMLNames::rubyTag ||
- tag_name == HTMLNames::rtTag;
+ return tag_name == html_names::kITag || tag_name == html_names::kBTag ||
+ tag_name == html_names::kUTag || tag_name == html_names::kRubyTag ||
+ tag_name == html_names::kRtTag;
}
static inline bool IsASpace(UChar c) {
// WebVTT space characters are U+0020 SPACE, U+0009 CHARACTER
@@ -113,8 +115,6 @@ class VTTParser final : public GarbageCollectedFinalized<VTTParser> {
void Trace(blink::Visitor*);
private:
- VTTParser(VTTParserClient*, Document&);
-
Member<Document> document_;
ParseState state_;
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc
index bf337576d58..44d1347d995 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc
@@ -94,7 +94,7 @@ VTTRegion::VTTRegion()
viewport_anchor_(DoublePoint(kDefaultAnchorPointX, kDefaultAnchorPointY)),
scroll_(kDefaultScroll),
current_top_(0),
- scroll_timer_(Platform::Current()->CurrentThread()->GetTaskRunner(),
+ scroll_timer_(Thread::Current()->GetTaskRunner(),
this,
&VTTRegion::ScrollTimerFired) {}
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.h
index 320934d34f3..44958e7088c 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.h
@@ -49,8 +49,9 @@ class VTTRegion final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static VTTRegion* Create() { return new VTTRegion; }
+ static VTTRegion* Create() { return MakeGarbageCollected<VTTRegion>(); }
+ VTTRegion();
~VTTRegion() override;
const String& id() const { return id_; }
@@ -90,8 +91,6 @@ class VTTRegion final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- VTTRegion();
-
void PrepareRegionDisplayTree();
// The timer is needed to continue processing when cue scrolling ended.
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.cc b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.cc
index 95d3acebfcc..a6ded6dd91d 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.cc
@@ -33,8 +33,8 @@
namespace blink {
-VTTScanner::VTTScanner(const String& line) : is8_bit_(line.Is8Bit()) {
- if (is8_bit_) {
+VTTScanner::VTTScanner(const String& line) : is_8bit_(line.Is8Bit()) {
+ if (is_8bit_) {
data_.characters8 = line.Characters8();
end_.characters8 = data_.characters8 + line.length();
} else {
@@ -52,13 +52,13 @@ bool VTTScanner::Scan(char c) {
bool VTTScanner::Scan(const LChar* characters, wtf_size_t characters_count) {
wtf_size_t match_length =
- is8_bit_
+ is_8bit_
? static_cast<wtf_size_t>(end_.characters8 - data_.characters8)
: static_cast<wtf_size_t>(end_.characters16 - data_.characters16);
if (match_length < characters_count)
return false;
bool matched;
- if (is8_bit_)
+ if (is_8bit_)
matched = WTF::Equal(data_.characters8, characters, characters_count);
else
matched = WTF::Equal(data_.characters16, characters, characters_count);
@@ -76,7 +76,7 @@ bool VTTScanner::ScanRun(const Run& run, const String& to_match) {
if (to_match.length() > match_length)
return false;
bool matched;
- if (is8_bit_)
+ if (is_8bit_)
matched = WTF::Equal(to_match.Impl(), data_.characters8, match_length);
else
matched = WTF::Equal(to_match.Impl(), data_.characters16, match_length);
@@ -98,7 +98,7 @@ String VTTScanner::ExtractString(const Run& run) {
DCHECK_GE(run.end(), run.Start());
DCHECK_LE(run.end(), end());
String s;
- if (is8_bit_)
+ if (is_8bit_)
s = String(data_.characters8, run.length());
else
s = String(data_.characters16, run.length());
@@ -107,7 +107,7 @@ String VTTScanner::ExtractString(const Run& run) {
}
String VTTScanner::RestOfInputAsString() {
- Run rest(GetPosition(), end(), is8_bit_);
+ Run rest(GetPosition(), end(), is_8bit_);
return ExtractString(rest);
}
@@ -119,7 +119,7 @@ unsigned VTTScanner::ScanDigits(unsigned& number) {
}
bool valid_number;
wtf_size_t num_digits = run_of_digits.length();
- if (is8_bit_) {
+ if (is_8bit_) {
number = CharactersToUInt(data_.characters8, num_digits,
WTF::NumberParsingOptions::kNone, &valid_number);
} else {
@@ -141,7 +141,7 @@ unsigned VTTScanner::ScanDigits(unsigned& number) {
bool VTTScanner::ScanDouble(double& number) {
Run integer_run = CollectWhile<IsASCIIDigit>();
SeekTo(integer_run.end());
- Run decimal_run(GetPosition(), GetPosition(), is8_bit_);
+ Run decimal_run(GetPosition(), GetPosition(), is_8bit_);
if (Scan('.')) {
decimal_run = CollectWhile<IsASCIIDigit>();
SeekTo(decimal_run.end());
@@ -155,9 +155,9 @@ bool VTTScanner::ScanDouble(double& number) {
}
size_t length_of_double =
- Run(integer_run.Start(), GetPosition(), is8_bit_).length();
+ Run(integer_run.Start(), GetPosition(), is_8bit_).length();
bool valid_number;
- if (is8_bit_) {
+ if (is_8bit_) {
number = CharactersToDouble(integer_run.Start(), length_of_double,
&valid_number);
} else {
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h
index 2532e7ce8da..a84847617d5 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h
@@ -61,8 +61,8 @@ class CORE_EXPORT VTTScanner {
STACK_ALLOCATED();
public:
- Run(Position start, Position end, bool is8_bit)
- : start_(start), end_(end), is8_bit_(is8_bit) {}
+ Run(Position start, Position end, bool is_8bit)
+ : start_(start), end_(end), is_8bit_(is_8bit) {}
Position Start() const { return start_; }
Position end() const { return end_; }
@@ -73,7 +73,7 @@ class CORE_EXPORT VTTScanner {
private:
Position start_;
Position end_;
- bool is8_bit_;
+ bool is_8bit_;
};
// Check if the input pointer points at the specified position.
@@ -161,13 +161,13 @@ class CORE_EXPORT VTTScanner {
const LChar* characters8;
const UChar* characters16;
} end_;
- bool is8_bit_;
+ bool is_8bit_;
DISALLOW_COPY_AND_ASSIGN(VTTScanner);
};
inline wtf_size_t VTTScanner::Run::length() const {
- if (is8_bit_)
+ if (is_8bit_)
return static_cast<wtf_size_t>(end_ - start_);
return static_cast<wtf_size_t>(reinterpret_cast<const UChar*>(end_) -
reinterpret_cast<const UChar*>(start_));
@@ -180,7 +180,7 @@ inline bool VTTScanner::Scan(const char (&characters)[charactersCount]) {
template <bool characterPredicate(UChar)>
inline void VTTScanner::SkipWhile() {
- if (is8_bit_)
+ if (is_8bit_)
WTF::SkipWhile<LChar, LCharPredicateAdapter<characterPredicate>>(
data_.characters8, end_.characters8);
else
@@ -190,7 +190,7 @@ inline void VTTScanner::SkipWhile() {
template <bool characterPredicate(UChar)>
inline void VTTScanner::SkipUntil() {
- if (is8_bit_)
+ if (is_8bit_)
WTF::SkipUntil<LChar, LCharPredicateAdapter<characterPredicate>>(
data_.characters8, end_.characters8);
else
@@ -200,28 +200,28 @@ inline void VTTScanner::SkipUntil() {
template <bool characterPredicate(UChar)>
inline VTTScanner::Run VTTScanner::CollectWhile() {
- if (is8_bit_) {
+ if (is_8bit_) {
const LChar* current = data_.characters8;
WTF::SkipWhile<LChar, LCharPredicateAdapter<characterPredicate>>(
current, end_.characters8);
- return Run(GetPosition(), current, is8_bit_);
+ return Run(GetPosition(), current, is_8bit_);
}
const UChar* current = data_.characters16;
WTF::SkipWhile<UChar, characterPredicate>(current, end_.characters16);
- return Run(GetPosition(), reinterpret_cast<Position>(current), is8_bit_);
+ return Run(GetPosition(), reinterpret_cast<Position>(current), is_8bit_);
}
template <bool characterPredicate(UChar)>
inline VTTScanner::Run VTTScanner::CollectUntil() {
- if (is8_bit_) {
+ if (is_8bit_) {
const LChar* current = data_.characters8;
WTF::SkipUntil<LChar, LCharPredicateAdapter<characterPredicate>>(
current, end_.characters8);
- return Run(GetPosition(), current, is8_bit_);
+ return Run(GetPosition(), current, is_8bit_);
}
const UChar* current = data_.characters16;
WTF::SkipUntil<UChar, characterPredicate>(current, end_.characters16);
- return Run(GetPosition(), reinterpret_cast<Position>(current), is8_bit_);
+ return Run(GetPosition(), reinterpret_cast<Position>(current), is_8bit_);
}
inline void VTTScanner::SeekTo(Position position) {
@@ -231,12 +231,12 @@ inline void VTTScanner::SeekTo(Position position) {
inline UChar VTTScanner::CurrentChar() const {
DCHECK_LT(GetPosition(), end());
- return is8_bit_ ? *data_.characters8 : *data_.characters16;
+ return is_8bit_ ? *data_.characters8 : *data_.characters16;
}
inline void VTTScanner::Advance(unsigned amount) {
DCHECK_LT(GetPosition(), end());
- if (is8_bit_)
+ if (is_8bit_)
data_.characters8 += amount;
else
data_.characters16 += amount;
diff --git a/chromium/third_party/blink/renderer/core/html/window_name_collection.h b/chromium/third_party/blink/renderer/core/html/window_name_collection.h
index 0fb82ee0610..677a556f91e 100644
--- a/chromium/third_party/blink/renderer/core/html/window_name_collection.h
+++ b/chromium/third_party/blink/renderer/core/html/window_name_collection.h
@@ -15,13 +15,12 @@ class WindowNameCollection final : public HTMLNameCollection {
CollectionType type,
const AtomicString& name) {
DCHECK_EQ(type, kWindowNamedItems);
- return new WindowNameCollection(document, name);
+ return MakeGarbageCollected<WindowNameCollection>(document, name);
}
- bool ElementMatches(const Element&) const;
-
- private:
WindowNameCollection(ContainerNode& document, const AtomicString& name);
+
+ bool ElementMatches(const Element&) const;
};
DEFINE_TYPE_CASTS(WindowNameCollection,
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/OWNERS b/chromium/third_party/blink/renderer/core/imagebitmap/OWNERS
index 5bbede4677e..c10da38a164 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/OWNERS
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/OWNERS
@@ -1,4 +1,4 @@
-junov@chromium.org
+fserb@chromium.org
zakerinasab@chromium.org
# TEAM: paint-dev@chromium.org
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc
index 36a687c01f1..6a20a923983 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc
@@ -18,6 +18,7 @@
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/saturated_arithmetic.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImageInfo.h"
@@ -60,53 +61,54 @@ static inline IntRect NormalizeRect(const IntRect& rect) {
return IntRect(x, y, width, height);
}
-ImageBitmap::ParsedOptions ParseOptions(const ImageBitmapOptions& options,
+ImageBitmap::ParsedOptions ParseOptions(const ImageBitmapOptions* options,
base::Optional<IntRect> crop_rect,
IntSize source_size) {
ImageBitmap::ParsedOptions parsed_options;
- if (options.imageOrientation() == kImageOrientationFlipY) {
+ if (options->imageOrientation() == kImageOrientationFlipY) {
parsed_options.flip_y = true;
} else {
parsed_options.flip_y = false;
- DCHECK(options.imageOrientation() == kImageBitmapOptionNone);
+ DCHECK(options->imageOrientation() == kImageBitmapOptionNone);
}
- if (options.imagePixelFormat() == kImageBitmapPixelFormatUint8Name)
+ if (options->imagePixelFormat() == kImageBitmapPixelFormatUint8Name)
parsed_options.pixel_format = kImageBitmapPixelFormat_Uint8;
- if (options.premultiplyAlpha() == kImageBitmapOptionNone) {
+ if (options->premultiplyAlpha() == kImageBitmapOptionNone) {
parsed_options.premultiply_alpha = false;
} else {
parsed_options.premultiply_alpha = true;
- DCHECK(options.premultiplyAlpha() == kImageBitmapOptionDefault ||
- options.premultiplyAlpha() == kImageBitmapOptionPremultiply);
+ DCHECK(options->premultiplyAlpha() == kImageBitmapOptionDefault ||
+ options->premultiplyAlpha() == kImageBitmapOptionPremultiply);
}
parsed_options.has_color_space_conversion =
- (options.colorSpaceConversion() != kImageBitmapOptionNone);
+ (options->colorSpaceConversion() != kImageBitmapOptionNone);
parsed_options.preserve_source_color_space =
- (options.colorSpaceConversion() ==
+ (options->colorSpaceConversion() ==
kPreserveImageBitmapColorSpaceConversion);
parsed_options.color_params.SetCanvasColorSpace(kSRGBCanvasColorSpace);
- if (options.colorSpaceConversion() != kSRGBImageBitmapColorSpaceConversion &&
- options.colorSpaceConversion() !=
+ if (options->colorSpaceConversion() != kSRGBImageBitmapColorSpaceConversion &&
+ options->colorSpaceConversion() !=
kPreserveImageBitmapColorSpaceConversion &&
- options.colorSpaceConversion() != kImageBitmapOptionNone &&
- options.colorSpaceConversion() != kImageBitmapOptionDefault) {
+ options->colorSpaceConversion() != kImageBitmapOptionNone &&
+ options->colorSpaceConversion() != kImageBitmapOptionDefault) {
parsed_options.color_params.SetCanvasPixelFormat(kF16CanvasPixelFormat);
- if (options.colorSpaceConversion() ==
+ if (options->colorSpaceConversion() ==
kLinearRGBImageBitmapColorSpaceConversion) {
- parsed_options.color_params.SetCanvasColorSpace(kSRGBCanvasColorSpace);
- } else if (options.colorSpaceConversion() ==
+ parsed_options.color_params.SetCanvasColorSpace(
+ kLinearRGBCanvasColorSpace);
+ } else if (options->colorSpaceConversion() ==
kP3ImageBitmapColorSpaceConversion) {
parsed_options.color_params.SetCanvasColorSpace(kP3CanvasColorSpace);
- } else if (options.colorSpaceConversion() ==
+ } else if (options->colorSpaceConversion() ==
kRec2020ImageBitmapColorSpaceConversion) {
parsed_options.color_params.SetCanvasColorSpace(kRec2020CanvasColorSpace);
} else {
NOTREACHED()
<< "Invalid ImageBitmap creation attribute colorSpaceConversion: "
- << options.colorSpaceConversion();
+ << options->colorSpaceConversion();
}
}
@@ -117,21 +119,21 @@ ImageBitmap::ParsedOptions ParseOptions(const ImageBitmapOptions& options,
} else {
parsed_options.crop_rect = NormalizeRect(*crop_rect);
}
- if (!options.hasResizeWidth() && !options.hasResizeHeight()) {
+ if (!options->hasResizeWidth() && !options->hasResizeHeight()) {
parsed_options.resize_width = parsed_options.crop_rect.Width();
parsed_options.resize_height = parsed_options.crop_rect.Height();
- } else if (options.hasResizeWidth() && options.hasResizeHeight()) {
- parsed_options.resize_width = options.resizeWidth();
- parsed_options.resize_height = options.resizeHeight();
- } else if (options.hasResizeWidth() && !options.hasResizeHeight()) {
- parsed_options.resize_width = options.resizeWidth();
+ } else if (options->hasResizeWidth() && options->hasResizeHeight()) {
+ parsed_options.resize_width = options->resizeWidth();
+ parsed_options.resize_height = options->resizeHeight();
+ } else if (options->hasResizeWidth() && !options->hasResizeHeight()) {
+ parsed_options.resize_width = options->resizeWidth();
parsed_options.resize_height = ceil(
- static_cast<float>(options.resizeWidth()) /
+ static_cast<float>(options->resizeWidth()) /
parsed_options.crop_rect.Width() * parsed_options.crop_rect.Height());
} else {
- parsed_options.resize_height = options.resizeHeight();
+ parsed_options.resize_height = options->resizeHeight();
parsed_options.resize_width = ceil(
- static_cast<float>(options.resizeHeight()) /
+ static_cast<float>(options->resizeHeight()) /
parsed_options.crop_rect.Height() * parsed_options.crop_rect.Width());
}
if (static_cast<int>(parsed_options.resize_width) ==
@@ -143,11 +145,11 @@ ImageBitmap::ParsedOptions ParseOptions(const ImageBitmapOptions& options,
}
parsed_options.should_scale_input = true;
- if (options.resizeQuality() == kImageBitmapOptionResizeQualityHigh)
+ if (options->resizeQuality() == kImageBitmapOptionResizeQualityHigh)
parsed_options.resize_quality = kHigh_SkFilterQuality;
- else if (options.resizeQuality() == kImageBitmapOptionResizeQualityMedium)
+ else if (options->resizeQuality() == kImageBitmapOptionResizeQualityMedium)
parsed_options.resize_quality = kMedium_SkFilterQuality;
- else if (options.resizeQuality() == kImageBitmapOptionResizeQualityPixelated)
+ else if (options->resizeQuality() == kImageBitmapOptionResizeQualityPixelated)
parsed_options.resize_quality = kNone_SkFilterQuality;
else
parsed_options.resize_quality = kLow_SkFilterQuality;
@@ -177,32 +179,10 @@ bool DstBufferSizeHasOverflow(const ImageBitmap::ParsedOptions& options) {
return false;
}
-SkImageInfo GetSkImageInfo(sk_sp<SkImage> skia_image) {
- SkColorType color_type = kN32_SkColorType;
- sk_sp<SkColorSpace> color_space = skia_image->refColorSpace();
-
- if (skia_image->colorType() == kRGBA_F16_SkColorType ||
- (skia_image->colorSpace() && skia_image->colorSpace()->gammaIsLinear())) {
- color_type = kRGBA_F16_SkColorType;
- }
-
- if (color_type == kN32_SkColorType && skia_image->colorSpace() &&
- skia_image->colorSpace()->isSRGB()) {
- // Skia is in the middle of transitioning this scenario from meaning
- // linearly blended sRGB uint8 to non-linearly blended sRGB uint8. While
- // the transition is happening, we'll strip the color space to force
- // non-linearly blended sRGB uint8. (This nullptr will continue to mean
- // non-linearly blended sRGB uint8 after the transition too, so there's
- // really no harm leaving this indefinitely.)
- color_space.reset(nullptr);
- }
- return SkImageInfo::Make(skia_image->width(), skia_image->height(),
- color_type, skia_image->alphaType(),
- std::move(color_space));
-}
-
-SkImageInfo GetSkImageInfo(const scoped_refptr<StaticBitmapImage>& image) {
- return GetSkImageInfo(image->PaintImageForCurrentFrame().GetSkImage());
+SkImageInfo GetSkImageInfo(const scoped_refptr<StaticBitmapImage>& input) {
+ auto image = input->PaintImageForCurrentFrame().GetSkImage();
+ return SkImageInfo::Make(image->width(), image->height(), image->colorType(),
+ image->alphaType(), image->refColorSpace());
}
// This function results in a readback due to using SkImage::readPixels().
@@ -369,7 +349,7 @@ scoped_refptr<StaticBitmapImage> ScaleImage(
sk_image.get(),
SkRect::MakeWH(parsed_options.resize_width,
parsed_options.resize_height),
- &paint, SkCanvas::SrcRectConstraint::kStrict_SrcRectConstraint);
+ &paint);
resized_sk_image = surface->makeImageSnapshot();
}
}
@@ -575,7 +555,7 @@ sk_sp<SkImage> ImageBitmap::GetSkImageFromDecoder(
ImageBitmap::ImageBitmap(ImageElementBase* image,
base::Optional<IntRect> crop_rect,
Document* document,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
scoped_refptr<Image> input = image->CachedImage()->GetImage();
ParsedOptions parsed_options =
ParseOptions(options, crop_rect, image->BitmapSourceSize());
@@ -592,12 +572,13 @@ ImageBitmap::ImageBitmap(ImageElementBase* image,
image_->SetOriginClean(
!image->WouldTaintOrigin(document->GetSecurityOrigin()));
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(HTMLVideoElement* video,
base::Optional<IntRect> crop_rect,
Document* document,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
ParsedOptions parsed_options =
ParseOptions(options, crop_rect, video->BitmapSourceSize());
if (DstBufferSizeHasOverflow(parsed_options))
@@ -627,11 +608,12 @@ ImageBitmap::ImageBitmap(HTMLVideoElement* video,
image_->SetOriginClean(
!video->WouldTaintOrigin(document->GetSecurityOrigin()));
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
SourceImageStatus status;
scoped_refptr<Image> image_input = canvas->GetSourceImageForCanvas(
&status, kPreferAcceleration, FloatSize());
@@ -652,11 +634,12 @@ ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas,
return;
image_->SetOriginClean(canvas->OriginClean());
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(OffscreenCanvas* offscreen_canvas,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
SourceImageStatus status;
scoped_refptr<Image> raw_input = offscreen_canvas->GetSourceImageForCanvas(
&status, kPreferNoAcceleration, FloatSize(offscreen_canvas->Size()));
@@ -678,6 +661,7 @@ ImageBitmap::ImageBitmap(OffscreenCanvas* offscreen_canvas,
if (!image_)
return;
image_->SetOriginClean(offscreen_canvas->OriginClean());
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(const void* pixel_data,
@@ -699,11 +683,12 @@ ImageBitmap::ImageBitmap(const void* pixel_data,
if (!image_)
return;
image_->SetOriginClean(is_image_bitmap_origin_clean);
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(ImageData* data,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
ParsedOptions parsed_options =
ParseOptions(options, crop_rect, data->BitmapSourceSize());
// ImageData is always unpremul.
@@ -774,11 +759,13 @@ ImageBitmap::ImageBitmap(ImageData* data,
// resize if up-scaling
if (up_scaling)
image_ = ScaleImage(std::move(image_), parsed_options);
+
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(ImageBitmap* bitmap,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
scoped_refptr<StaticBitmapImage> input = bitmap->BitmapImage();
if (!input)
return;
@@ -796,11 +783,12 @@ ImageBitmap::ImageBitmap(ImageBitmap* bitmap,
return;
image_->SetOriginClean(bitmap->OriginClean());
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(scoped_refptr<StaticBitmapImage> image,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
bool origin_clean = image->OriginClean();
ParsedOptions parsed_options =
ParseOptions(options, crop_rect, image->Size());
@@ -816,10 +804,12 @@ ImageBitmap::ImageBitmap(scoped_refptr<StaticBitmapImage> image,
return;
image_->SetOriginClean(origin_clean);
+ UpdateImageBitmapMemoryUsage();
}
ImageBitmap::ImageBitmap(scoped_refptr<StaticBitmapImage> image) {
image_ = std::move(image);
+ UpdateImageBitmapMemoryUsage();
}
scoped_refptr<StaticBitmapImage> ImageBitmap::Transfer() {
@@ -829,54 +819,74 @@ scoped_refptr<StaticBitmapImage> ImageBitmap::Transfer() {
return std::move(image_);
}
-ImageBitmap::~ImageBitmap() = default;
+void ImageBitmap::UpdateImageBitmapMemoryUsage() {
+ // TODO(fserb): We should be calling GetCanvasColorParams().BytesPerPixel()
+ // but this is breaking some tests due to the repaint of the image.
+ int bytes_per_pixel = 4;
+
+ base::CheckedNumeric<int32_t> memory_usage_checked = bytes_per_pixel;
+ memory_usage_checked *= image_->width();
+ memory_usage_checked *= image_->height();
+ int32_t new_memory_usage =
+ memory_usage_checked.ValueOrDefault(std::numeric_limits<int32_t>::max());
+ v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
+ new_memory_usage - memory_usage_);
+ memory_usage_ = new_memory_usage;
+}
+
+ImageBitmap::~ImageBitmap() {
+ v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
+ -memory_usage_);
+}
ImageBitmap* ImageBitmap::Create(ImageElementBase* image,
base::Optional<IntRect> crop_rect,
Document* document,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(image, crop_rect, document, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(image, crop_rect, document, options);
}
ImageBitmap* ImageBitmap::Create(HTMLVideoElement* video,
base::Optional<IntRect> crop_rect,
Document* document,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(video, crop_rect, document, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(video, crop_rect, document, options);
}
ImageBitmap* ImageBitmap::Create(HTMLCanvasElement* canvas,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(canvas, crop_rect, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(canvas, crop_rect, options);
}
ImageBitmap* ImageBitmap::Create(OffscreenCanvas* offscreen_canvas,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(offscreen_canvas, crop_rect, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(offscreen_canvas, crop_rect,
+ options);
}
ImageBitmap* ImageBitmap::Create(ImageData* data,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(data, crop_rect, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(data, crop_rect, options);
}
ImageBitmap* ImageBitmap::Create(ImageBitmap* bitmap,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(bitmap, crop_rect, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(bitmap, crop_rect, options);
}
ImageBitmap* ImageBitmap::Create(scoped_refptr<StaticBitmapImage> image,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
- return new ImageBitmap(std::move(image), crop_rect, options);
+ const ImageBitmapOptions* options) {
+ return MakeGarbageCollected<ImageBitmap>(std::move(image), crop_rect,
+ options);
}
ImageBitmap* ImageBitmap::Create(scoped_refptr<StaticBitmapImage> image) {
- return new ImageBitmap(std::move(image));
+ return MakeGarbageCollected<ImageBitmap>(std::move(image));
}
ImageBitmap* ImageBitmap::Create(const void* pixel_data,
@@ -885,9 +895,9 @@ ImageBitmap* ImageBitmap::Create(const void* pixel_data,
bool is_image_bitmap_premultiplied,
bool is_image_bitmap_origin_clean,
const CanvasColorParams& color_params) {
- return new ImageBitmap(pixel_data, width, height,
- is_image_bitmap_premultiplied,
- is_image_bitmap_origin_clean, color_params);
+ return MakeGarbageCollected<ImageBitmap>(
+ pixel_data, width, height, is_image_bitmap_premultiplied,
+ is_image_bitmap_origin_clean, color_params);
}
void ImageBitmap::ResolvePromiseOnOriginalThread(
@@ -920,7 +930,7 @@ void ImageBitmap::ResolvePromiseOnOriginalThread(
v8::Null(resolver->GetScriptState()->GetIsolate())));
return;
}
- ImageBitmap* bitmap = new ImageBitmap(image);
+ ImageBitmap* bitmap = MakeGarbageCollected<ImageBitmap>(image);
bitmap->BitmapImage()->SetOriginClean(origin_clean);
resolver->Resolve(bitmap);
}
@@ -941,7 +951,7 @@ void ImageBitmap::RasterizeImageOnBackgroundThread(
skia_image = surface->makeImageSnapshot();
}
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- Platform::Current()->MainThread()->GetTaskRunner();
+ Thread::MainThread()->GetTaskRunner();
PostCrossThreadTask(*task_runner, FROM_HERE,
CrossThreadBind(&ResolvePromiseOnOriginalThread,
WrapCrossThreadPersistent(resolver),
@@ -953,7 +963,7 @@ ScriptPromise ImageBitmap::CreateAsync(ImageElementBase* image,
base::Optional<IntRect> crop_rect,
Document* document,
ScriptState* script_state,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -974,7 +984,8 @@ ScriptPromise ImageBitmap::CreateAsync(ImageElementBase* image,
// a transparent black image, respecting the color_params but ignoring
// poremultiply_alpha.
if (src_rect.IsEmpty()) {
- ImageBitmap* bitmap = new ImageBitmap(MakeBlankImage(parsed_options));
+ ImageBitmap* bitmap =
+ MakeGarbageCollected<ImageBitmap>(MakeBlankImage(parsed_options));
if (bitmap->BitmapImage()) {
bitmap->BitmapImage()->SetOriginClean(
!image->WouldTaintOrigin(document->GetSecurityOrigin()));
@@ -995,7 +1006,7 @@ ScriptPromise ImageBitmap::CreateAsync(ImageElementBase* image,
draw_dst_rect, parsed_options.flip_y);
std::unique_ptr<ParsedOptions> passed_parsed_options =
std::make_unique<ParsedOptions>(parsed_options);
- BackgroundScheduler::PostOnBackgroundThread(
+ background_scheduler::PostOnBackgroundThread(
FROM_HERE,
CrossThreadBind(&RasterizeImageOnBackgroundThread,
WrapCrossThreadPersistent(resolver),
@@ -1041,14 +1052,14 @@ scoped_refptr<Uint8Array> ImageBitmap::CopyBitmapData() {
return CopyImageData(image_);
}
-unsigned long ImageBitmap::width() const {
+unsigned ImageBitmap::width() const {
if (!image_)
return 0;
DCHECK_GT(image_->width(), 0);
return image_->width();
}
-unsigned long ImageBitmap::height() const {
+unsigned ImageBitmap::height() const {
if (!image_)
return 0;
DCHECK_GT(image_->height(), 0);
@@ -1071,7 +1082,7 @@ ScriptPromise ImageBitmap::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
return ImageBitmapSource::FulfillImageBitmap(
script_state, Create(this, crop_rect, options));
}
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.h b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.h
index 258a6a7d54c..08e225280c0 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.h
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.h
@@ -38,30 +38,37 @@ class CORE_EXPORT ImageBitmap final : public ScriptWrappable,
DEFINE_WRAPPERTYPEINFO();
public:
- static ImageBitmap* Create(ImageElementBase*,
- base::Optional<IntRect>,
- Document*,
- const ImageBitmapOptions& = ImageBitmapOptions());
- static ImageBitmap* Create(HTMLVideoElement*,
- base::Optional<IntRect>,
- Document*,
- const ImageBitmapOptions& = ImageBitmapOptions());
- static ImageBitmap* Create(HTMLCanvasElement*,
- base::Optional<IntRect>,
- const ImageBitmapOptions& = ImageBitmapOptions());
- static ImageBitmap* Create(OffscreenCanvas*,
- base::Optional<IntRect>,
- const ImageBitmapOptions& = ImageBitmapOptions());
- static ImageBitmap* Create(ImageData*,
- base::Optional<IntRect>,
- const ImageBitmapOptions& = ImageBitmapOptions());
- static ImageBitmap* Create(ImageBitmap*,
- base::Optional<IntRect>,
- const ImageBitmapOptions& = ImageBitmapOptions());
+ static ImageBitmap* Create(
+ ImageElementBase*,
+ base::Optional<IntRect>,
+ Document*,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
+ static ImageBitmap* Create(
+ HTMLVideoElement*,
+ base::Optional<IntRect>,
+ Document*,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
+ static ImageBitmap* Create(
+ HTMLCanvasElement*,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
+ static ImageBitmap* Create(
+ OffscreenCanvas*,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
+ static ImageBitmap* Create(
+ ImageData*,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
+ static ImageBitmap* Create(
+ ImageBitmap*,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
static ImageBitmap* Create(scoped_refptr<StaticBitmapImage>);
- static ImageBitmap* Create(scoped_refptr<StaticBitmapImage>,
- base::Optional<IntRect>,
- const ImageBitmapOptions& = ImageBitmapOptions());
+ static ImageBitmap* Create(
+ scoped_refptr<StaticBitmapImage>,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
// This function is called by structured-cloning an ImageBitmap.
// isImageBitmapPremultiplied indicates whether the original ImageBitmap is
// premultiplied or not.
@@ -78,9 +85,36 @@ class CORE_EXPORT ImageBitmap final : public ScriptWrappable,
base::Optional<IntRect>,
Document*,
ScriptState*,
- const ImageBitmapOptions& = ImageBitmapOptions());
+ const ImageBitmapOptions* = ImageBitmapOptions::Create());
static sk_sp<SkImage> GetSkImageFromDecoder(std::unique_ptr<ImageDecoder>);
+ ImageBitmap(ImageElementBase*,
+ base::Optional<IntRect>,
+ Document*,
+ const ImageBitmapOptions*);
+ ImageBitmap(HTMLVideoElement*,
+ base::Optional<IntRect>,
+ Document*,
+ const ImageBitmapOptions*);
+ ImageBitmap(HTMLCanvasElement*,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions*);
+ ImageBitmap(OffscreenCanvas*,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions*);
+ ImageBitmap(ImageData*, base::Optional<IntRect>, const ImageBitmapOptions*);
+ ImageBitmap(ImageBitmap*, base::Optional<IntRect>, const ImageBitmapOptions*);
+ ImageBitmap(scoped_refptr<StaticBitmapImage>);
+ ImageBitmap(scoped_refptr<StaticBitmapImage>,
+ base::Optional<IntRect>,
+ const ImageBitmapOptions*);
+ ImageBitmap(const void* pixel_data,
+ uint32_t width,
+ uint32_t height,
+ bool is_image_bitmap_premultiplied,
+ bool is_image_bitmap_origin_clean,
+ const CanvasColorParams&);
+
// Type and helper function required by CallbackPromiseAdapter:
using WebType = sk_sp<SkImage>;
static ImageBitmap* Take(ScriptPromiseResolver*, sk_sp<SkImage>);
@@ -89,8 +123,8 @@ class CORE_EXPORT ImageBitmap final : public ScriptWrappable,
scoped_refptr<Uint8Array> CopyBitmapData();
scoped_refptr<Uint8Array> CopyBitmapData(AlphaDisposition,
DataU8ColorType = kRGBAColorType);
- unsigned long width() const;
- unsigned long height() const;
+ unsigned width() const;
+ unsigned height() const;
IntSize Size() const;
bool IsNeutered() const { return is_neutered_; }
@@ -120,7 +154,7 @@ class CORE_EXPORT ImageBitmap final : public ScriptWrappable,
ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect>,
- const ImageBitmapOptions&) override;
+ const ImageBitmapOptions*) override;
struct ParsedOptions {
bool flip_y = false;
@@ -138,32 +172,7 @@ class CORE_EXPORT ImageBitmap final : public ScriptWrappable,
};
private:
- ImageBitmap(ImageElementBase*,
- base::Optional<IntRect>,
- Document*,
- const ImageBitmapOptions&);
- ImageBitmap(HTMLVideoElement*,
- base::Optional<IntRect>,
- Document*,
- const ImageBitmapOptions&);
- ImageBitmap(HTMLCanvasElement*,
- base::Optional<IntRect>,
- const ImageBitmapOptions&);
- ImageBitmap(OffscreenCanvas*,
- base::Optional<IntRect>,
- const ImageBitmapOptions&);
- ImageBitmap(ImageData*, base::Optional<IntRect>, const ImageBitmapOptions&);
- ImageBitmap(ImageBitmap*, base::Optional<IntRect>, const ImageBitmapOptions&);
- ImageBitmap(scoped_refptr<StaticBitmapImage>);
- ImageBitmap(scoped_refptr<StaticBitmapImage>,
- base::Optional<IntRect>,
- const ImageBitmapOptions&);
- ImageBitmap(const void* pixel_data,
- uint32_t width,
- uint32_t height,
- bool is_image_bitmap_premultiplied,
- bool is_image_bitmap_origin_clean,
- const CanvasColorParams&);
+ void UpdateImageBitmapMemoryUsage();
static void ResolvePromiseOnOriginalThread(ScriptPromiseResolver*,
sk_sp<SkImage>,
bool origin_clean,
@@ -175,6 +184,7 @@ class CORE_EXPORT ImageBitmap final : public ScriptWrappable,
std::unique_ptr<ParsedOptions>);
scoped_refptr<StaticBitmapImage> image_;
bool is_neutered_ = false;
+ int32_t memory_usage_ = 0;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc
index c188cbc5a77..af929850d93 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc
@@ -46,7 +46,6 @@
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap_options.h"
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
-#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -54,12 +53,14 @@
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "v8/include/v8.h"
namespace blink {
+namespace {
// This enum is used in a UMA histogram.
enum CreateImageBitmapSource {
kCreateImageBitmapSourceBlob = 0,
@@ -70,51 +71,53 @@ enum CreateImageBitmapSource {
kCreateImageBitmapSourceHTMLVideoElement = 5,
kCreateImageBitmapSourceOffscreenCanvas = 6,
kCreateImageBitmapSourceSVGImageElement = 7,
- kCreateImageBitmapSourceCount,
+ kMaxValue = kCreateImageBitmapSourceSVGImageElement,
};
+} // namespace
+
static inline ImageBitmapSource* ToImageBitmapSourceInternal(
const ImageBitmapSourceUnion& value,
- const ImageBitmapOptions& options,
+ const ImageBitmapOptions* options,
bool has_crop_rect) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- EnumerationHistogram, image_bitmap_source_histogram,
- ("Canvas.CreateImageBitmapSource", kCreateImageBitmapSourceCount));
if (value.IsHTMLVideoElement()) {
- image_bitmap_source_histogram.Count(
- kCreateImageBitmapSourceHTMLVideoElement);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceHTMLVideoElement);
return value.GetAsHTMLVideoElement();
}
if (value.IsHTMLImageElement()) {
- image_bitmap_source_histogram.Count(
- kCreateImageBitmapSourceHTMLImageElement);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceHTMLImageElement);
return value.GetAsHTMLImageElement();
}
if (value.IsSVGImageElement()) {
- image_bitmap_source_histogram.Count(
- kCreateImageBitmapSourceSVGImageElement);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceSVGImageElement);
return value.GetAsSVGImageElement();
}
if (value.IsHTMLCanvasElement()) {
- image_bitmap_source_histogram.Count(
- kCreateImageBitmapSourceHTMLCanvasElement);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceHTMLCanvasElement);
return value.GetAsHTMLCanvasElement();
}
if (value.IsBlob()) {
- image_bitmap_source_histogram.Count(kCreateImageBitmapSourceBlob);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceBlob);
return value.GetAsBlob();
}
if (value.IsImageData()) {
- image_bitmap_source_histogram.Count(kCreateImageBitmapSourceImageData);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceImageData);
return value.GetAsImageData();
}
if (value.IsImageBitmap()) {
- image_bitmap_source_histogram.Count(kCreateImageBitmapSourceImageBitmap);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceImageBitmap);
return value.GetAsImageBitmap();
}
if (value.IsOffscreenCanvas()) {
- image_bitmap_source_histogram.Count(
- kCreateImageBitmapSourceOffscreenCanvas);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.CreateImageBitmapSource",
+ kCreateImageBitmapSourceOffscreenCanvas);
return value.GetAsOffscreenCanvas();
}
NOTREACHED();
@@ -126,7 +129,7 @@ ScriptPromise ImageBitmapFactories::CreateImageBitmapFromBlob(
EventTarget& event_target,
ImageBitmapSource* bitmap_source,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
Blob* blob = static_cast<Blob*>(bitmap_source);
ImageBitmapLoader* loader = ImageBitmapFactories::ImageBitmapLoader::Create(
From(event_target), crop_rect, options, script_state);
@@ -136,22 +139,22 @@ ScriptPromise ImageBitmapFactories::CreateImageBitmapFromBlob(
return promise;
}
-ScriptPromise ImageBitmapFactories::createImageBitmap(
+ScriptPromise ImageBitmapFactories::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
const ImageBitmapSourceUnion& bitmap_source,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
WebFeature feature = WebFeature::kCreateImageBitmap;
UseCounter::Count(ExecutionContext::From(script_state), feature);
ImageBitmapSource* bitmap_source_internal =
ToImageBitmapSourceInternal(bitmap_source, options, false);
if (!bitmap_source_internal)
return ScriptPromise();
- return createImageBitmap(script_state, event_target, bitmap_source_internal,
+ return CreateImageBitmap(script_state, event_target, bitmap_source_internal,
base::Optional<IntRect>(), options);
}
-ScriptPromise ImageBitmapFactories::createImageBitmap(
+ScriptPromise ImageBitmapFactories::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
const ImageBitmapSourceUnion& bitmap_source,
@@ -159,7 +162,7 @@ ScriptPromise ImageBitmapFactories::createImageBitmap(
int sy,
int sw,
int sh,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
WebFeature feature = WebFeature::kCreateImageBitmap;
UseCounter::Count(ExecutionContext::From(script_state), feature);
ImageBitmapSource* bitmap_source_internal =
@@ -167,16 +170,16 @@ ScriptPromise ImageBitmapFactories::createImageBitmap(
if (!bitmap_source_internal)
return ScriptPromise();
base::Optional<IntRect> crop_rect = IntRect(sx, sy, sw, sh);
- return createImageBitmap(script_state, event_target, bitmap_source_internal,
+ return CreateImageBitmap(script_state, event_target, bitmap_source_internal,
crop_rect, options);
}
-ScriptPromise ImageBitmapFactories::createImageBitmap(
+ScriptPromise ImageBitmapFactories::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
ImageBitmapSource* bitmap_source,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
if (crop_rect && (crop_rect->Width() == 0 || crop_rect->Height() == 0)) {
return ScriptPromise::Reject(
script_state,
@@ -213,9 +216,8 @@ ImageBitmapFactories& ImageBitmapFactories::From(EventTarget& event_target) {
if (LocalDOMWindow* window = event_target.ToLocalDOMWindow())
return FromInternal(*window);
- DCHECK(event_target.GetExecutionContext()->IsWorkerGlobalScope());
return ImageBitmapFactories::FromInternal(
- *ToWorkerGlobalScope(event_target.GetExecutionContext()));
+ *To<WorkerGlobalScope>(event_target.GetExecutionContext()));
}
template <class GlobalObject>
@@ -223,7 +225,7 @@ ImageBitmapFactories& ImageBitmapFactories::FromInternal(GlobalObject& object) {
ImageBitmapFactories* supplement =
Supplement<GlobalObject>::template From<ImageBitmapFactories>(object);
if (!supplement) {
- supplement = new ImageBitmapFactories;
+ supplement = MakeGarbageCollected<ImageBitmapFactories>();
Supplement<GlobalObject>::ProvideTo(object, supplement);
}
return *supplement;
@@ -238,27 +240,31 @@ void ImageBitmapFactories::DidFinishLoading(ImageBitmapLoader* loader) {
pending_loaders_.erase(loader);
}
+void ImageBitmapFactories::Trace(blink::Visitor* visitor) {
+ visitor->Trace(pending_loaders_);
+ Supplement<LocalDOMWindow>::Trace(visitor);
+ Supplement<WorkerGlobalScope>::Trace(visitor);
+}
+
ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(
ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
ScriptState* script_state,
- const ImageBitmapOptions& options)
- : loader_(
+ const ImageBitmapOptions* options)
+ : ContextLifecycleObserver(ExecutionContext::From(script_state)),
+ loader_(
FileReaderLoader::Create(FileReaderLoader::kReadAsArrayBuffer, this)),
factory_(&factory),
resolver_(ScriptPromiseResolver::Create(script_state)),
crop_rect_(crop_rect),
options_(options) {}
-void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync(
- Blob* blob) {
+void ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync(Blob* blob) {
loader_->Start(blob->GetBlobDataHandle());
}
-void ImageBitmapFactories::Trace(blink::Visitor* visitor) {
- visitor->Trace(pending_loaders_);
- Supplement<LocalDOMWindow>::Trace(visitor);
- Supplement<WorkerGlobalScope>::Trace(visitor);
+ImageBitmapFactories::ImageBitmapLoader::~ImageBitmapLoader() {
+ DCHECK(!loader_);
}
void ImageBitmapFactories::ImageBitmapLoader::RejectPromise(
@@ -277,11 +283,20 @@ void ImageBitmapFactories::ImageBitmapLoader::RejectPromise(
default:
NOTREACHED();
}
+ loader_.reset();
factory_->DidFinishLoading(this);
}
+void ImageBitmapFactories::ImageBitmapLoader::ContextDestroyed(
+ ExecutionContext*) {
+ if (loader_)
+ factory_->DidFinishLoading(this);
+ loader_.reset();
+}
+
void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() {
DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult();
+ loader_.reset();
if (!array_buffer) {
RejectPromise(kAllocationFailureImageBitmapRejectionReason);
return;
@@ -289,21 +304,21 @@ void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() {
ScheduleAsyncImageBitmapDecoding(array_buffer);
}
-void ImageBitmapFactories::ImageBitmapLoader::DidFail(FileError::ErrorCode) {
+void ImageBitmapFactories::ImageBitmapLoader::DidFail(FileErrorCode) {
RejectPromise(kUndecodableImageBitmapRejectionReason);
}
void ImageBitmapFactories::ImageBitmapLoader::ScheduleAsyncImageBitmapDecoding(
DOMArrayBuffer* array_buffer) {
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- Platform::Current()->CurrentThread()->GetTaskRunner();
- BackgroundScheduler::PostOnBackgroundThread(
+ Thread::Current()->GetTaskRunner();
+ background_scheduler::PostOnBackgroundThread(
FROM_HERE,
CrossThreadBind(
&ImageBitmapFactories::ImageBitmapLoader::DecodeImageOnDecoderThread,
WrapCrossThreadPersistent(this), std::move(task_runner),
- WrapCrossThreadPersistent(array_buffer), options_.premultiplyAlpha(),
- options_.colorSpaceConversion()));
+ WrapCrossThreadPersistent(array_buffer), options_->premultiplyAlpha(),
+ options_->colorSpaceConversion()));
}
void ImageBitmapFactories::ImageBitmapLoader::DecodeImageOnDecoderThread(
@@ -359,8 +374,10 @@ void ImageBitmapFactories::ImageBitmapLoader::ResolvePromiseOnOriginalThread(
}
void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) {
+ ContextLifecycleObserver::Trace(visitor);
visitor->Trace(factory_);
visitor->Trace(resolver_);
+ visitor->Trace(options_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h
index 25bdf1ffd1e..c4b90edae2b 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h
@@ -32,13 +32,16 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_IMAGEBITMAP_IMAGE_BITMAP_FACTORIES_H_
#include <memory>
+
#include "base/single_thread_task_runner.h"
#include "third_party/blink/renderer/bindings/core/v8/image_bitmap_source.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
+#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader_client.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
+#include "third_party/blink/renderer/core/frame/window_or_worker_global_scope.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap_options.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/name_client.h"
@@ -56,9 +59,6 @@ class EventTarget;
class ImageBitmapSource;
class ImageBitmapOptions;
-typedef HTMLImageElementOrSVGImageElementOrHTMLVideoElementOrHTMLCanvasElementOrBlobOrImageDataOrImageBitmapOrOffscreenCanvas
- ImageBitmapSourceUnion;
-
class ImageBitmapFactories final
: public GarbageCollectedFinalized<ImageBitmapFactories>,
public Supplement<LocalDOMWindow>,
@@ -69,29 +69,29 @@ class ImageBitmapFactories final
public:
static const char kSupplementName[];
- static ScriptPromise createImageBitmap(ScriptState*,
+ static ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
const ImageBitmapSourceUnion&,
- const ImageBitmapOptions&);
- static ScriptPromise createImageBitmap(ScriptState*,
+ const ImageBitmapOptions*);
+ static ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
const ImageBitmapSourceUnion&,
int sx,
int sy,
int sw,
int sh,
- const ImageBitmapOptions&);
- static ScriptPromise createImageBitmap(ScriptState*,
+ const ImageBitmapOptions*);
+ static ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
ImageBitmapSource*,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions&);
+ const ImageBitmapOptions*);
static ScriptPromise CreateImageBitmapFromBlob(
ScriptState*,
EventTarget&,
ImageBitmapSource*,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions&);
+ const ImageBitmapOptions*);
virtual ~ImageBitmapFactories() = default;
@@ -103,28 +103,32 @@ class ImageBitmapFactories final
private:
class ImageBitmapLoader final
: public GarbageCollectedFinalized<ImageBitmapLoader>,
+ public ContextLifecycleObserver,
public FileReaderLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(ImageBitmapLoader);
+
public:
static ImageBitmapLoader* Create(ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options,
+ const ImageBitmapOptions* options,
ScriptState* script_state) {
- return new ImageBitmapLoader(factory, crop_rect, script_state, options);
+ return MakeGarbageCollected<ImageBitmapLoader>(factory, crop_rect,
+ script_state, options);
}
+ ImageBitmapLoader(ImageBitmapFactories&,
+ base::Optional<IntRect> crop_rect,
+ ScriptState*,
+ const ImageBitmapOptions*);
+
void LoadBlobAsync(Blob*);
ScriptPromise Promise() { return resolver_->Promise(); }
- void Trace(blink::Visitor*);
+ void Trace(blink::Visitor*) override;
- ~ImageBitmapLoader() override = default;
+ ~ImageBitmapLoader() override;
private:
- ImageBitmapLoader(ImageBitmapFactories&,
- base::Optional<IntRect> crop_rect,
- ScriptState*,
- const ImageBitmapOptions&);
-
enum ImageBitmapRejectionReason {
kUndecodableImageBitmapRejectionReason,
kAllocationFailureImageBitmapRejectionReason,
@@ -140,17 +144,20 @@ class ImageBitmapFactories final
const String& color_space_conversion_option);
void ResolvePromiseOnOriginalThread(sk_sp<SkImage>);
+ // ContextLifecycleObserver
+ void ContextDestroyed(ExecutionContext*) override;
+
// FileReaderLoaderClient
void DidStartLoading() override {}
void DidReceiveData() override {}
void DidFinishLoading() override;
- void DidFail(FileError::ErrorCode) override;
+ void DidFail(FileErrorCode) override;
std::unique_ptr<FileReaderLoader> loader_;
Member<ImageBitmapFactories> factory_;
Member<ScriptPromiseResolver> resolver_;
base::Optional<IntRect> crop_rect_;
- ImageBitmapOptions options_;
+ Member<const ImageBitmapOptions> options_;
};
static ImageBitmapFactories& From(EventTarget&);
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.idl b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.idl
deleted file mode 100644
index 5ef7a454ae2..00000000000
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.idl
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// https://html.spec.whatwg.org/#imagebitmapfactories
-
-typedef (HTMLImageElement or
- SVGImageElement or
- HTMLVideoElement or
- HTMLCanvasElement or
- Blob or
- ImageData or
- ImageBitmap or
- OffscreenCanvas) ImageBitmapSource;
-
-[
- LegacyTreatAsPartialInterface,
- NoInterfaceObject, // Always used on target of 'implements'
- Exposed=(Window,Worker)
-] interface ImageBitmapFactories {
- [CallWith=ScriptState] Promise createImageBitmap(
- ImageBitmapSource imageBitmap, optional ImageBitmapOptions options);
- [CallWith=ScriptState] Promise createImageBitmap(
- ImageBitmapSource imageBitmap, long sx, long sy, long sw, long sh, optional ImageBitmapOptions options);
-};
-
-Window implements ImageBitmapFactories;
-WorkerGlobalScope implements ImageBitmapFactories;
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_options.idl b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_options.idl
index b52dca214c7..0026c35dd4f 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_options.idl
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_options.idl
@@ -7,7 +7,7 @@
enum ImageOrientation { "none", "flipY" };
enum ImageBitmapPixelFormat { "default", "uint8" };
enum PremultiplyAlpha { "none", "premultiply", "default" };
-enum ColorSpaceConversion { "none", "default", "preserve", "srgb", "linear-rgb", "rec2020", "p3" };
+enum ColorSpaceConversion { "none", "default", "srgb", "linear-rgb", "rec2020", "p3" };
enum ResizeQuality { "pixelated", "low", "medium", "high" };
dictionary ImageBitmapOptions {
ImageOrientation imageOrientation = "none";
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.cc b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.cc
index 6a743d0b354..20f0e69b782 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.cc
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.cc
@@ -28,7 +28,7 @@ ScriptPromise ImageBitmapSource::CreateImageBitmap(
ScriptState* script_state,
EventTarget& event_target,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
return ScriptPromise();
}
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h
index 129d7b17f82..d8dbcb2b052 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h
@@ -24,7 +24,7 @@ class CORE_EXPORT ImageBitmapSource {
virtual ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect>,
- const ImageBitmapOptions&);
+ const ImageBitmapOptions*);
virtual bool IsBlob() const { return false; }
diff --git a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc
index bd511ecd8dd..0b2b63e3962 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_test.cc
@@ -105,7 +105,7 @@ class ImageBitmapTest : public testing::Test {
};
TEST_F(ImageBitmapTest, ImageResourceConsistency) {
- const ImageBitmapOptions default_options;
+ const ImageBitmapOptions* default_options = ImageBitmapOptions::Create();
HTMLImageElement* image_element =
HTMLImageElement::Create(*Document::CreateForTest());
sk_sp<SkColorSpace> src_rgb_color_space = SkColorSpace::MakeSRGB();
@@ -189,7 +189,7 @@ TEST_F(ImageBitmapTest, ImageBitmapSourceChanged) {
StaticBitmapImage::Create(raster_image).get());
image->SetImageForTest(original_image_resource);
- const ImageBitmapOptions default_options;
+ const ImageBitmapOptions* default_options = ImageBitmapOptions::Create();
base::Optional<IntRect> crop_rect =
IntRect(0, 0, image_->width(), image_->height());
ImageBitmap* image_bitmap = ImageBitmap::Create(
@@ -247,7 +247,7 @@ TEST_F(ImageBitmapTest, ImageBitmapSourceChanged) {
static void TestImageBitmapTextureBacked(
scoped_refptr<StaticBitmapImage> bitmap,
IntRect& rect,
- ImageBitmapOptions options,
+ ImageBitmapOptions* options,
bool is_texture_backed) {
ImageBitmap* image_bitmap = ImageBitmap::Create(bitmap, rect, options);
EXPECT_TRUE(image_bitmap);
@@ -274,7 +274,7 @@ TEST_F(ImageBitmapTest, AvoidGPUReadback) {
EXPECT_TRUE(image_bitmap->BitmapImage()->IsTextureBacked());
IntRect image_bitmap_rect(25, 25, 50, 50);
- ImageBitmapOptions image_bitmap_options;
+ ImageBitmapOptions* image_bitmap_options = ImageBitmapOptions::Create();
TestImageBitmapTextureBacked(bitmap, image_bitmap_rect, image_bitmap_options,
true);
@@ -292,14 +292,15 @@ TEST_F(ImageBitmapTest, AvoidGPUReadback) {
for (auto resize_width : resize_widths) {
for (auto resize_height : resize_heights) {
for (auto resize_quality : resize_qualities) {
- ImageBitmapOptions image_bitmap_options;
- image_bitmap_options.setImageOrientation(image_orientation);
- image_bitmap_options.setPremultiplyAlpha(premultiply_alpha);
- image_bitmap_options.setColorSpaceConversion(
+ ImageBitmapOptions* image_bitmap_options =
+ ImageBitmapOptions::Create();
+ image_bitmap_options->setImageOrientation(image_orientation);
+ image_bitmap_options->setPremultiplyAlpha(premultiply_alpha);
+ image_bitmap_options->setColorSpaceConversion(
color_space_conversion);
- image_bitmap_options.setResizeWidth(resize_width);
- image_bitmap_options.setResizeHeight(resize_height);
- image_bitmap_options.setResizeQuality(resize_quality);
+ image_bitmap_options->setResizeWidth(resize_width);
+ image_bitmap_options->setResizeHeight(resize_height);
+ image_bitmap_options->setResizeQuality(resize_quality);
// Setting premuliply_alpha to none will cause a read back.
// Otherwise, we expect to avoid GPU readback when creaing an
// ImageBitmap from a texture-backed source.
@@ -341,8 +342,8 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionHTMLImageElement) {
for (int conversion_iterator = kColorSpaceConversion_Default;
conversion_iterator <= kColorSpaceConversion_Last;
conversion_iterator++) {
- ImageBitmapOptions options;
- options.setColorSpaceConversion(
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
static_cast<ColorSpaceConversion>(conversion_iterator)));
ImageBitmap* image_bitmap = ImageBitmap::Create(
@@ -400,8 +401,8 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionImageBitmap) {
base::Optional<IntRect> crop_rect =
IntRect(0, 0, source_image->width(), source_image->height());
- ImageBitmapOptions options;
- options.setColorSpaceConversion(
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
kColorSpaceConversion_Preserve));
ImageBitmap* source_image_bitmap = ImageBitmap::Create(
@@ -411,7 +412,7 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionImageBitmap) {
for (int conversion_iterator = kColorSpaceConversion_Default;
conversion_iterator <= kColorSpaceConversion_Last;
conversion_iterator++) {
- options.setColorSpaceConversion(
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
static_cast<ColorSpaceConversion>(conversion_iterator)));
ImageBitmap* image_bitmap =
@@ -473,8 +474,8 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionStaticBitmapImage) {
for (int conversion_iterator = kColorSpaceConversion_Default;
conversion_iterator <= kColorSpaceConversion_Last;
conversion_iterator++) {
- ImageBitmapOptions options;
- options.setColorSpaceConversion(
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
static_cast<ColorSpaceConversion>(conversion_iterator)));
ImageBitmap* image_bitmap = ImageBitmap::Create(
@@ -520,9 +521,9 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionStaticBitmapImage) {
TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionImageData) {
unsigned char data_buffer[4] = {32, 96, 160, 128};
DOMUint8ClampedArray* data = DOMUint8ClampedArray::Create(data_buffer, 4);
- ImageDataColorSettings color_settings;
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
ImageData* image_data = ImageData::Create(
- IntSize(1, 1), NotShared<DOMUint8ClampedArray>(data), &color_settings);
+ IntSize(1, 1), NotShared<DOMUint8ClampedArray>(data), color_settings);
SkImageInfo image_info =
SkImageInfo::Make(1, 1, kRGBA_8888_SkColorType, kUnpremul_SkAlphaType,
@@ -538,8 +539,8 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionImageData) {
for (int conversion_iterator = kColorSpaceConversion_Default;
conversion_iterator <= kColorSpaceConversion_Last;
conversion_iterator++) {
- ImageBitmapOptions options;
- options.setColorSpaceConversion(
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
static_cast<ColorSpaceConversion>(conversion_iterator)));
ImageBitmap* image_bitmap =
@@ -589,7 +590,7 @@ TEST_F(ImageBitmapTest, ImageBitmapPixelFormat) {
StaticBitmapImage::Create(sk_image);
// source: uint8, bitmap pixel format: default
- ImageBitmapOptions options;
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
ImageBitmap* image_bitmap =
ImageBitmap::Create(bitmap_image, bitmap_image->Rect(), options);
@@ -599,7 +600,7 @@ TEST_F(ImageBitmapTest, ImageBitmapPixelFormat) {
ASSERT_EQ(kN32_SkColorType, sk_image_internal->colorType());
// source: uint8, bitmap pixel format: uint8
- options.setImagePixelFormat("uint8");
+ options->setImagePixelFormat("uint8");
ImageBitmap* image_bitmap_8888 =
ImageBitmap::Create(bitmap_image, bitmap_image->Rect(), options);
ASSERT_TRUE(image_bitmap_8888);
@@ -623,7 +624,7 @@ TEST_F(ImageBitmapTest, ImageBitmapPixelFormat) {
StaticBitmapImage::Create(sk_image_f16);
// source: f16, bitmap pixel format: default
- ImageBitmapOptions options_f16;
+ ImageBitmapOptions* options_f16 = ImageBitmapOptions::Create();
ImageBitmap* image_bitmap_f16 = ImageBitmap::Create(
bitmap_image_f16, bitmap_image_f16->Rect(), options_f16);
ASSERT_TRUE(image_bitmap_f16);
@@ -632,7 +633,7 @@ TEST_F(ImageBitmapTest, ImageBitmapPixelFormat) {
ASSERT_EQ(kRGBA_F16_SkColorType, sk_image_internal_f16->colorType());
// source: f16, bitmap pixel format: uint8
- options_f16.setImagePixelFormat("uint8");
+ options_f16->setImagePixelFormat("uint8");
ImageBitmap* image_bitmap_f16_8888 = ImageBitmap::Create(
bitmap_image_f16, bitmap_image_f16->Rect(), options_f16);
ASSERT_TRUE(image_bitmap_f16_8888);
@@ -660,8 +661,8 @@ TEST_F(ImageBitmapTest,
ImageData* image_data =
ImageData::CreateForTest(IntSize(v8::TypedArray::kMaxLength / 16, 1));
DCHECK(image_data);
- ImageBitmapOptions options;
- options.setColorSpaceConversion(
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
kColorSpaceConversion_Default));
ImageBitmap* image_bitmap = ImageBitmap::Create(
diff --git a/chromium/third_party/blink/renderer/core/input/boundary_event_dispatcher.cc b/chromium/third_party/blink/renderer/core/input/boundary_event_dispatcher.cc
index d026c5240a5..5f349b19d55 100644
--- a/chromium/third_party/blink/renderer/core/input/boundary_event_dispatcher.cc
+++ b/chromium/third_party/blink/renderer/core/input/boundary_event_dispatcher.cc
@@ -14,7 +14,7 @@ namespace {
void BuildAncestorChain(EventTarget* target,
HeapVector<Member<Node>, 20>* ancestors) {
- if (!EventHandlingUtil::IsInDocument(target))
+ if (!event_handling_util::IsInDocument(target))
return;
Node* target_node = target->ToNode();
DCHECK(target_node);
@@ -62,7 +62,7 @@ void BoundaryEventDispatcher::SendBoundaryEvents(EventTarget* exited_target,
return;
// Dispatch out event
- if (EventHandlingUtil::IsInDocument(exited_target))
+ if (event_handling_util::IsInDocument(exited_target))
DispatchOut(exited_target, entered_target);
// Create lists of all exited/entered ancestors, locate the common ancestor
@@ -112,7 +112,7 @@ void BoundaryEventDispatcher::SendBoundaryEvents(EventTarget* exited_target,
!exited_node_has_capturing_ancestor);
// Dispatch over event
- if (EventHandlingUtil::IsInDocument(entered_target))
+ if (event_handling_util::IsInDocument(entered_target))
DispatchOver(entered_target, exited_target);
// Defer locating capturing enter listener until /after/ dispatching the leave
diff --git a/chromium/third_party/blink/renderer/core/input/event_handler.cc b/chromium/third_party/blink/renderer/core/input/event_handler.cc
index 919ccaa4f88..e27e2f2f2c3 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handler.cc
+++ b/chromium/third_party/blink/renderer/core/input/event_handler.cc
@@ -65,7 +65,6 @@
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_frame_set_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input/event_handling_util.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/input/touch_action_util.h"
@@ -123,8 +122,6 @@ bool ShouldRefetchEventTarget(const MouseEventWithHitTestResults& mev) {
} // namespace
-using namespace HTMLNames;
-
// The amount of time to wait for a cursor update on style and layout changes
// Set to 50Hz, no need to be faster than common screen refresh rate
static constexpr TimeDelta kCursorUpdateInterval =
@@ -156,20 +153,24 @@ EventHandler::EventHandler(LocalFrame& frame)
should_only_fire_drag_over_event_(false),
event_handler_registry_(
frame_->IsLocalRoot()
- ? new EventHandlerRegistry(*frame_)
+ ? MakeGarbageCollected<EventHandlerRegistry>(*frame_)
: &frame_->LocalFrameRoot().GetEventHandlerRegistry()),
- scroll_manager_(new ScrollManager(frame)),
- mouse_event_manager_(new MouseEventManager(frame, *scroll_manager_)),
- mouse_wheel_event_manager_(new MouseWheelEventManager(frame)),
+ scroll_manager_(MakeGarbageCollected<ScrollManager>(frame)),
+ mouse_event_manager_(
+ MakeGarbageCollected<MouseEventManager>(frame, *scroll_manager_)),
+ mouse_wheel_event_manager_(
+ MakeGarbageCollected<MouseWheelEventManager>(frame)),
keyboard_event_manager_(
- new KeyboardEventManager(frame, *scroll_manager_)),
+ MakeGarbageCollected<KeyboardEventManager>(frame, *scroll_manager_)),
pointer_event_manager_(
- new PointerEventManager(frame, *mouse_event_manager_)),
- gesture_manager_(new GestureManager(frame,
- *scroll_manager_,
- *mouse_event_manager_,
- *pointer_event_manager_,
- *selection_controller_)),
+ MakeGarbageCollected<PointerEventManager>(frame,
+ *mouse_event_manager_)),
+ gesture_manager_(
+ MakeGarbageCollected<GestureManager>(frame,
+ *scroll_manager_,
+ *mouse_event_manager_,
+ *pointer_event_manager_,
+ *selection_controller_)),
active_interval_timer_(frame.GetTaskRunner(TaskType::kUserInteraction),
this,
&EventHandler::ActiveIntervalTimerFired) {}
@@ -336,7 +337,7 @@ IntPoint EventHandler::DragDataTransferLocationForTesting() {
static bool IsSubmitImage(Node* node) {
return IsHTMLInputElement(node) &&
- ToHTMLInputElement(node)->type() == InputTypeNames::image;
+ ToHTMLInputElement(node)->type() == input_type_names::kImage;
}
bool EventHandler::UseHandCursor(Node* node, bool is_over_link) {
@@ -592,9 +593,10 @@ WebInputEventResult EventHandler::DispatchBufferedTouchEvents() {
WebInputEventResult EventHandler::HandlePointerEvent(
const WebPointerEvent& web_pointer_event,
- const Vector<WebPointerEvent>& coalesced_events) {
- return pointer_event_manager_->HandlePointerEvent(web_pointer_event,
- coalesced_events);
+ const Vector<WebPointerEvent>& coalesced_events,
+ const Vector<WebPointerEvent>& predicted_events) {
+ return pointer_event_manager_->HandlePointerEvent(
+ web_pointer_event, coalesced_events, predicted_events);
}
WebInputEventResult EventHandler::HandleMousePressEvent(
@@ -630,7 +632,7 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
frame_->GetDocument()->SetSequentialFocusNavigationStartingPoint(
mev.InnerNode());
- LocalFrame* subframe = EventHandlingUtil::SubframeForHitTestResult(mev);
+ LocalFrame* subframe = event_handling_util::GetTargetSubframe(mev);
if (subframe) {
WebInputEventResult result = PassMousePressEventToSubframe(mev, subframe);
// Start capturing future events for this frame. We only do this if we
@@ -679,7 +681,7 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
WebInputEventResult event_result = DispatchMousePointerEvent(
WebInputEvent::kPointerDown, mev.InnerNode(), mev.CanvasRegionId(),
- mev.Event(), Vector<WebMouseEvent>());
+ mev.Event(), Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
// Disabled form controls still need to resize the scrollable area.
if ((event_result == WebInputEventResult::kNotHandled ||
@@ -706,7 +708,7 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
// dragging if we keep the selection in case of mousedown. FireFox also has
// the same behavior and it's more compatible with other browsers.
GetSelectionController().InitializeSelectionState();
- HitTestResult hit_test_result = EventHandlingUtil::HitTestResultInFrame(
+ HitTestResult hit_test_result = event_handling_util::HitTestResultInFrame(
frame_, HitTestLocation(document_point), HitTestRequest::kReadOnly);
InputDeviceCapabilities* source_capabilities =
frame_->GetDocument()
@@ -773,21 +775,23 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
WebInputEventResult EventHandler::HandleMouseMoveEvent(
const WebMouseEvent& event,
- const Vector<WebMouseEvent>& coalesced_events) {
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events) {
TRACE_EVENT0("blink", "EventHandler::handleMouseMoveEvent");
HitTestResult hovered_node_result;
HitTestLocation location;
- WebInputEventResult result = HandleMouseMoveOrLeaveEvent(
- event, coalesced_events, &hovered_node_result, &location);
+ WebInputEventResult result =
+ HandleMouseMoveOrLeaveEvent(event, coalesced_events, predicted_events,
+ &hovered_node_result, &location);
Page* page = frame_->GetPage();
if (!page)
return result;
if (PaintLayer* layer =
- EventHandlingUtil::LayerForNode(hovered_node_result.InnerNode())) {
+ event_handling_util::LayerForNode(hovered_node_result.InnerNode())) {
if (ScrollableArea* layer_scrollable_area =
- EventHandlingUtil::AssociatedScrollableArea(layer))
+ event_handling_util::AssociatedScrollableArea(layer))
layer_scrollable_area->MouseMovedInContentArea();
}
@@ -804,20 +808,22 @@ void EventHandler::HandleMouseLeaveEvent(const WebMouseEvent& event) {
Page* page = frame_->GetPage();
if (page)
page->GetChromeClient().ClearToolTip(*frame_);
- HandleMouseMoveOrLeaveEvent(event, Vector<WebMouseEvent>(), nullptr, nullptr,
- false, true);
+ HandleMouseMoveOrLeaveEvent(event, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>(), nullptr, nullptr, false,
+ true);
+ pointer_event_manager_->RemoveLastMousePosition();
}
WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
const WebMouseEvent& mouse_event,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
HitTestResult* hovered_node_result,
HitTestLocation* hit_test_location,
bool only_update_scrollbars,
bool force_leave) {
DCHECK(frame_);
DCHECK(frame_->View());
-
mouse_event_manager_->SetLastKnownMousePosition(mouse_event);
hover_timer_.Stop();
@@ -853,9 +859,9 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
}
if (frame_set_being_resized_) {
- return DispatchMousePointerEvent(WebInputEvent::kPointerMove,
- frame_set_being_resized_.Get(), String(),
- mouse_event, coalesced_events);
+ return DispatchMousePointerEvent(
+ WebInputEvent::kPointerMove, frame_set_being_resized_.Get(), String(),
+ mouse_event, coalesced_events, predicted_events);
}
// Send events right to a scrollbar if the mouse is pressed.
@@ -892,8 +898,8 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
if (force_leave) {
frame_->GetDocument()->UpdateHoverActiveState(request, nullptr);
} else {
- mev = EventHandlingUtil::PerformMouseEventHitTest(frame_, request,
- mouse_event);
+ mev = event_handling_util::PerformMouseEventHitTest(frame_, request,
+ mouse_event);
}
if (hovered_node_result)
@@ -917,11 +923,9 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
}
WebInputEventResult event_result = WebInputEventResult::kNotHandled;
- LocalFrame* new_subframe =
- capturing_mouse_events_node_.Get()
- ? EventHandlingUtil::SubframeForTargetNode(
- capturing_mouse_events_node_.Get())
- : EventHandlingUtil::SubframeForHitTestResult(mev);
+ bool is_remote_frame = false;
+ LocalFrame* new_subframe = event_handling_util::GetTargetSubframe(
+ mev, capturing_mouse_events_node_.Get(), &is_remote_frame);
// We want mouseouts to happen first, from the inside out. First send a
// move event to the last subframe so that it will fire mouseouts.
@@ -944,8 +948,9 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
// subframe of the target node to be detached from its LocalFrameView, in
// which case the event should not be passed.
if (new_subframe->View()) {
- event_result = PassMouseMoveEventToSubframe(
- mev, coalesced_events, new_subframe, hovered_node_result);
+ event_result =
+ PassMouseMoveEventToSubframe(mev, coalesced_events, predicted_events,
+ new_subframe, hovered_node_result);
}
} else {
if (scrollbar && !mouse_event_manager_->MousePressed()) {
@@ -953,7 +958,8 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
// scrollbar hovering.
scrollbar->MouseMoved(mev.Event());
}
- if (LocalFrameView* view = frame_->View()) {
+ LocalFrameView* view = frame_->View();
+ if (!is_remote_frame && view) {
EventHandler::OptionalCursor optional_cursor =
SelectCursor(mev.GetHitTestLocation(), mev.GetHitTestResult());
if (optional_cursor.IsCursorChange()) {
@@ -969,7 +975,7 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
event_result = DispatchMousePointerEvent(
WebInputEvent::kPointerMove, mev.InnerNode(), mev.CanvasRegionId(),
- mev.Event(), coalesced_events);
+ mev.Event(), coalesced_events, predicted_events);
// TODO(crbug.com/346473): Since there is no default action for the mousemove
// event we should consider doing drag&drop even when js cancels the
// mouse move event.
@@ -1007,9 +1013,10 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
mouse_event_manager_->HandleSvgPanIfNeeded(true);
if (frame_set_being_resized_) {
+ CaptureMouseEventsToWidget(false);
return mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
EffectiveMouseEventTargetNode(frame_set_being_resized_.Get()), String(),
- EventTypeNames::mouseup, mouse_event);
+ event_type_names::kMouseup, mouse_event);
}
if (last_scrollbar_under_mouse_) {
@@ -1018,7 +1025,8 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
CaptureMouseEventsToWidget(false);
return DispatchMousePointerEvent(
WebInputEvent::kPointerUp, mouse_event_manager_->GetNodeUnderMouse(),
- String(), mouse_event, Vector<WebMouseEvent>());
+ String(), mouse_event, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
}
// Mouse events simulated from touch should not hit-test again.
@@ -1027,12 +1035,11 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kRelease;
HitTestRequest request(hit_type);
MouseEventWithHitTestResults mev =
- EventHandlingUtil::PerformMouseEventHitTest(frame_, request, mouse_event);
+ event_handling_util::PerformMouseEventHitTest(frame_, request,
+ mouse_event);
Element* mouse_release_target = mev.InnerElement();
- LocalFrame* subframe = capturing_mouse_events_node_.Get()
- ? EventHandlingUtil::SubframeForTargetNode(
- capturing_mouse_events_node_.Get())
- : EventHandlingUtil::SubframeForHitTestResult(mev);
+ LocalFrame* subframe = event_handling_util::GetTargetSubframe(
+ mev, capturing_mouse_events_node_.Get());
if (event_handler_will_reset_capturing_mouse_events_node_)
capturing_mouse_events_node_ = nullptr;
if (subframe)
@@ -1057,7 +1064,7 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
WebInputEventResult event_result = DispatchMousePointerEvent(
WebInputEvent::kPointerUp, mev.InnerNode(), mev.CanvasRegionId(),
- mev.Event(), Vector<WebMouseEvent>());
+ mev.Event(), Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
WebInputEventResult click_event_result =
mouse_release_target ? mouse_event_manager_->DispatchMouseClickIfNeeded(
@@ -1072,7 +1079,8 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
mouse_event_manager_->HandleMouseReleaseEventUpdateStates();
CaptureMouseEventsToWidget(false);
- return EventHandlingUtil::MergeEventResult(click_event_result, event_result);
+ return event_handling_util::MergeEventResult(click_event_result,
+ event_result);
}
static bool TargetIsFrame(Node* target, LocalFrame*& frame) {
@@ -1098,7 +1106,7 @@ WebInputEventResult EventHandler::UpdateDragAndDrop(
HitTestRequest request(HitTestRequest::kReadOnly);
MouseEventWithHitTestResults mev =
- EventHandlingUtil::PerformMouseEventHitTest(frame_, request, event);
+ event_handling_util::PerformMouseEventHitTest(frame_, request, event);
// Drag events should never go to text nodes (following IE, and proper
// mouseover/out dispatch)
@@ -1116,7 +1124,7 @@ WebInputEventResult EventHandler::UpdateDragAndDrop(
if (drag_target_ != new_target) {
// FIXME: this ordering was explicitly chosen to match WinIE. However,
// it is sometimes incorrect when dragging within subframes, as seen with
- // LayoutTests/fast/events/drag-in-frames.html.
+ // web_tests/fast/events/drag-in-frames.html.
//
// Moreover, this ordering conforms to section 7.9.4 of the HTML 5 spec.
// <http://dev.w3.org/html5/spec/Overview.html#drag-and-drop-processing-model>.
@@ -1131,10 +1139,11 @@ WebInputEventResult EventHandler::UpdateDragAndDrop(
if (mouse_event_manager_->GetDragState().drag_src_) {
// For now we don't care if event handler cancels default behavior,
// since there is none.
- mouse_event_manager_->DispatchDragSrcEvent(EventTypeNames::drag, event);
+ mouse_event_manager_->DispatchDragSrcEvent(event_type_names::kDrag,
+ event);
}
event_result = mouse_event_manager_->DispatchDragEvent(
- EventTypeNames::dragenter, new_target, drag_target_, event,
+ event_type_names::kDragenter, new_target, drag_target_, event,
data_transfer);
}
@@ -1143,7 +1152,7 @@ WebInputEventResult EventHandler::UpdateDragAndDrop(
event_result = target_frame->GetEventHandler().UpdateDragAndDrop(
event, data_transfer);
} else if (drag_target_) {
- mouse_event_manager_->DispatchDragEvent(EventTypeNames::dragleave,
+ mouse_event_manager_->DispatchDragEvent(event_type_names::kDragleave,
drag_target_.Get(), new_target,
event, data_transfer);
}
@@ -1168,10 +1177,12 @@ WebInputEventResult EventHandler::UpdateDragAndDrop(
mouse_event_manager_->GetDragState().drag_src_) {
// For now we don't care if event handler cancels default behavior,
// since there is none.
- mouse_event_manager_->DispatchDragSrcEvent(EventTypeNames::drag, event);
+ mouse_event_manager_->DispatchDragSrcEvent(event_type_names::kDrag,
+ event);
}
event_result = mouse_event_manager_->DispatchDragEvent(
- EventTypeNames::dragover, new_target, nullptr, event, data_transfer);
+ event_type_names::kDragover, new_target, nullptr, event,
+ data_transfer);
should_only_fire_drag_over_event_ = false;
}
}
@@ -1187,9 +1198,11 @@ void EventHandler::CancelDragAndDrop(const WebMouseEvent& event,
if (target_frame)
target_frame->GetEventHandler().CancelDragAndDrop(event, data_transfer);
} else if (drag_target_.Get()) {
- if (mouse_event_manager_->GetDragState().drag_src_)
- mouse_event_manager_->DispatchDragSrcEvent(EventTypeNames::drag, event);
- mouse_event_manager_->DispatchDragEvent(EventTypeNames::dragleave,
+ if (mouse_event_manager_->GetDragState().drag_src_) {
+ mouse_event_manager_->DispatchDragSrcEvent(event_type_names::kDrag,
+ event);
+ }
+ mouse_event_manager_->DispatchDragEvent(event_type_names::kDragleave,
drag_target_.Get(), nullptr, event,
data_transfer);
}
@@ -1207,7 +1220,7 @@ WebInputEventResult EventHandler::PerformDragAndDrop(
event, data_transfer);
} else if (drag_target_.Get()) {
result = mouse_event_manager_->DispatchDragEvent(
- EventTypeNames::drop, drag_target_.Get(), nullptr, event,
+ event_type_names::kDrop, drag_target_.Get(), nullptr, event,
data_transfer);
}
ClearDragState();
@@ -1225,6 +1238,10 @@ void EventHandler::AnimateSnapFling(base::TimeTicks monotonic_time) {
scroll_manager_->AnimateSnapFling(monotonic_time);
}
+void EventHandler::RecomputeMouseHoverState() {
+ mouse_event_manager_->RecomputeMouseHoverState();
+}
+
void EventHandler::SetCapturingMouseEventsNode(Node* n) {
CaptureMouseEventsToWidget(n);
capturing_mouse_events_node_ = n;
@@ -1320,10 +1337,11 @@ WebInputEventResult EventHandler::DispatchMousePointerEvent(
Node* target_node,
const String& canvas_region_id,
const WebMouseEvent& mouse_event,
- const Vector<WebMouseEvent>& coalesced_events) {
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events) {
const auto& event_result = pointer_event_manager_->SendMousePointerEvent(
EffectiveMouseEventTargetNode(target_node), canvas_region_id, event_type,
- mouse_event, coalesced_events);
+ mouse_event, coalesced_events, predicted_events);
return event_result;
}
@@ -1339,10 +1357,12 @@ WebInputEventResult EventHandler::HandleTargetedMouseEvent(
const WebMouseEvent& event,
const AtomicString& mouse_event_type,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
const String& canvas_region_id) {
mouse_event_manager_->SetClickCount(event.click_count);
return pointer_event_manager_->DirectDispatchMousePointerEvent(
- target, event, mouse_event_type, coalesced_events, canvas_region_id);
+ target, event, mouse_event_type, coalesced_events, predicted_events,
+ canvas_region_id);
}
WebInputEventResult EventHandler::HandleGestureEvent(
@@ -1877,8 +1897,9 @@ WebInputEventResult EventHandler::SendContextMenuEvent(
Node* target_node =
override_target_node ? override_target_node : mev.InnerNode();
return mouse_event_manager_->DispatchMouseEvent(
- EffectiveMouseEventTargetNode(target_node), EventTypeNames::contextmenu,
- event, mev.GetHitTestResult().CanvasRegionId(), nullptr);
+ EffectiveMouseEventTargetNode(target_node),
+ event_type_names::kContextmenu, event,
+ mev.GetHitTestResult().CanvasRegionId(), nullptr, nullptr);
}
static bool ShouldShowContextMenuAtSelection(const FrameSelection& selection) {
@@ -2011,6 +2032,11 @@ bool EventHandler::FakeMouseMovePending() const {
void EventHandler::MayUpdateHoverWhenContentUnderMouseChanged(
MouseEventManager::UpdateHoverReason update_hover_reason) {
+ if (update_hover_reason ==
+ MouseEventManager::UpdateHoverReason::kScrollOffsetChanged &&
+ RuntimeEnabledFeatures::NoHoverDuringScrollEnabled()) {
+ return;
+ }
mouse_event_manager_->MayUpdateHoverWhenContentUnderMouseChanged(
update_hover_reason);
}
@@ -2021,6 +2047,7 @@ void EventHandler::MayUpdateHoverAfterScroll(
}
void EventHandler::SetResizingFrameSet(HTMLFrameSetElement* frame_set) {
+ CaptureMouseEventsToWidget(true);
frame_set_being_resized_ = frame_set;
}
@@ -2088,7 +2115,7 @@ void EventHandler::DragSourceEndedAt(const WebMouseEvent& event,
// opportunity for Layer to update the :hover and :active pseudoclasses.
HitTestRequest request(HitTestRequest::kRelease);
MouseEventWithHitTestResults mev =
- EventHandlingUtil::PerformMouseEventHitTest(frame_, request, event);
+ event_handling_util::PerformMouseEventHitTest(frame_, request, event);
LocalFrame* target_frame;
if (TargetIsFrame(mev.InnerNode(), target_frame)) {
@@ -2117,7 +2144,8 @@ bool EventHandler::HandleTextInputEvent(const String& text,
// in disguise (like insertNewline), and avoid dispatching text input events
// from keydown default handlers.
DCHECK(!underlying_event || !underlying_event->IsKeyboardEvent() ||
- ToKeyboardEvent(underlying_event)->type() == EventTypeNames::keypress);
+ ToKeyboardEvent(underlying_event)->type() ==
+ event_type_names::kKeypress);
if (!frame_)
return false;
@@ -2199,6 +2227,7 @@ WebInputEventResult EventHandler::PassMousePressEventToSubframe(
WebInputEventResult EventHandler::PassMouseMoveEventToSubframe(
MouseEventWithHitTestResults& mev,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
LocalFrame* subframe,
HitTestResult* hovered_node,
HitTestLocation* hit_test_location) {
@@ -2206,7 +2235,8 @@ WebInputEventResult EventHandler::PassMouseMoveEventToSubframe(
return WebInputEventResult::kNotHandled;
WebInputEventResult result =
subframe->GetEventHandler().HandleMouseMoveOrLeaveEvent(
- mev.Event(), coalesced_events, hovered_node, hit_test_location);
+ mev.Event(), coalesced_events, predicted_events, hovered_node,
+ hit_test_location);
if (result != WebInputEventResult::kNotHandled)
return result;
return WebInputEventResult::kHandledSystem;
diff --git a/chromium/third_party/blink/renderer/core/input/event_handler.h b/chromium/third_party/blink/renderer/core/input/event_handler.h
index d10b63c9c8f..d268bfd532d 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handler.h
+++ b/chromium/third_party/blink/renderer/core/input/event_handler.h
@@ -78,6 +78,7 @@ class WebGestureEvent;
class WebMouseEvent;
class WebMouseWheelEvent;
+// Handles events for Pointers (Mouse/Touch), HitTests, DragAndDrop, etc.
class CORE_EXPORT EventHandler final
: public GarbageCollectedFinalized<EventHandler> {
public:
@@ -147,12 +148,14 @@ class CORE_EXPORT EventHandler final
WebInputEventResult HandleMouseMoveEvent(
const WebMouseEvent&,
- const Vector<WebMouseEvent>& coalesced_events);
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events);
void HandleMouseLeaveEvent(const WebMouseEvent&);
WebInputEventResult HandlePointerEvent(
const WebPointerEvent&,
- const Vector<WebPointerEvent>& coalesced_events);
+ const Vector<WebPointerEvent>& coalesced_events,
+ const Vector<WebPointerEvent>& predicted_events);
WebInputEventResult DispatchBufferedTouchEvents();
@@ -165,6 +168,7 @@ class CORE_EXPORT EventHandler final
const WebMouseEvent&,
const AtomicString& event_type,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
const String& canvas_node_id = String());
// Called on the local root frame exactly once per gesture event.
@@ -282,6 +286,8 @@ class CORE_EXPORT EventHandler final
void AnimateSnapFling(base::TimeTicks monotonic_time);
+ void RecomputeMouseHoverState();
+
private:
enum NoCursorChangeType { kNoCursorChange };
@@ -304,7 +310,8 @@ class CORE_EXPORT EventHandler final
WebInputEventResult HandleMouseMoveOrLeaveEvent(
const WebMouseEvent&,
- const Vector<WebMouseEvent>&,
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
HitTestResult* hovered_node = nullptr,
HitTestLocation* hit_test_location = nullptr,
bool only_update_scrollbars = false,
@@ -355,14 +362,16 @@ class CORE_EXPORT EventHandler final
Node* target,
const String& canvas_region_id,
const WebMouseEvent&,
- const Vector<WebMouseEvent>& coalesced_events);
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events);
WebInputEventResult PassMousePressEventToSubframe(
MouseEventWithHitTestResults&,
LocalFrame* subframe);
WebInputEventResult PassMouseMoveEventToSubframe(
MouseEventWithHitTestResults&,
- const Vector<WebMouseEvent>&,
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
LocalFrame* subframe,
HitTestResult* hovered_node = nullptr,
HitTestLocation* hit_test_location = nullptr);
diff --git a/chromium/third_party/blink/renderer/core/input/event_handler_test.cc b/chromium/third_party/blink/renderer/core/input/event_handler_test.cc
index c8947ab4b56..6a9e9886b0f 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handler_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/event_handler_test.cc
@@ -126,7 +126,7 @@ void EventHandlerTest::SetUp() {
void EventHandlerTest::SetHtmlInnerHTML(const char* html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
ShadowRoot* EventHandlerTest::SetShadowContent(const char* shadow_content,
@@ -178,7 +178,7 @@ TEST_F(EventHandlerTest, dragSelectionAfterScroll) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
GetPage().GetAutoscrollController().Animate();
GetPage().Animator().ServiceScriptedAnimations(WTF::CurrentTimeTicks());
@@ -301,7 +301,7 @@ TEST_F(EventHandlerTest, draggedInlinePositionTest) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
EXPECT_EQ(IntPoint(12, 29), GetDocument()
.GetFrame()
@@ -339,7 +339,7 @@ TEST_F(EventHandlerTest, draggedSVGImagePositionTest) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
EXPECT_EQ(IntPoint(45, 44), GetDocument()
.GetFrame()
@@ -596,7 +596,7 @@ TEST_F(EventHandlerTest, sendContextMenuEventWithHover) {
"<style>*:hover { color: red; }</style>"
"<div>foo</div>");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.addEventListener('contextmenu', event => "
"event.preventDefault());");
@@ -777,7 +777,7 @@ TEST_F(EventHandlerTest, dragEndInNewDrag) {
WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
// This reproduces what might be the conditions of http://crbug.com/677916
//
@@ -824,9 +824,10 @@ TEST_F(EventHandlerTest, FakeMouseMoveNotStartDrag) {
WebInputEvent::Modifiers::kRelativeMotionEvent,
WebInputEvent::GetStaticTimeStampForTests());
fake_mouse_move.SetFrameScale(1);
- EXPECT_EQ(WebInputEventResult::kHandledSuppressed,
- GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- fake_mouse_move, Vector<WebMouseEvent>()));
+ EXPECT_EQ(
+ WebInputEventResult::kHandledSuppressed,
+ GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
+ fake_mouse_move, Vector<WebMouseEvent>(), Vector<WebMouseEvent>()));
EXPECT_EQ(IntPoint(0, 0), GetDocument()
.GetFrame()
@@ -853,7 +854,7 @@ class EventHandlerTooltipTest : public EventHandlerTest {
EventHandlerTooltipTest() = default;
void SetUp() override {
- chrome_client_ = new TooltipCapturingChromeClient();
+ chrome_client_ = MakeGarbageCollected<TooltipCapturingChromeClient>();
Page::PageClients clients;
FillWithEmptyClients(clients);
clients.chrome_client = chrome_client_.Get();
@@ -880,7 +881,7 @@ TEST_F(EventHandlerTooltipTest, mouseLeaveClearsTooltip) {
CurrentTimeTicks());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
EXPECT_EQ("tooltip", LastToolTip());
@@ -916,7 +917,8 @@ class UnbufferedInputEventsTrackingChromeClient : public EmptyChromeClient {
class EventHandlerLatencyTest : public PageTestBase {
protected:
void SetUp() override {
- chrome_client_ = new UnbufferedInputEventsTrackingChromeClient();
+ chrome_client_ =
+ MakeGarbageCollected<UnbufferedInputEventsTrackingChromeClient>();
Page::PageClients page_clients;
FillWithEmptyClients(page_clients);
page_clients.chrome_client = chrome_client_.Get();
@@ -926,7 +928,7 @@ class EventHandlerLatencyTest : public PageTestBase {
void SetHtmlInnerHTML(const char* html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
Persistent<UnbufferedInputEventsTrackingChromeClient> chrome_client_;
@@ -984,7 +986,7 @@ class EventHandlerNavigationTest : public EventHandlerTest {
EventHandlerNavigationTest() = default;
void SetUp() override {
- frame_client_ = new NavigationCapturingFrameClient();
+ frame_client_ = MakeGarbageCollected<NavigationCapturingFrameClient>();
Page::PageClients clients;
FillWithEmptyClients(clients);
SetupPageWithClients(&clients, frame_client_);
@@ -1025,7 +1027,7 @@ TEST_F(EventHandlerNavigationTest, MouseButtonsNavigate) {
TEST_F(EventHandlerNavigationTest, MouseButtonsDontNavigate) {
SetHtmlInnerHTML("<div>");
GetDocument().GetSettings()->SetScriptEnabled(true);
- Element* script = GetDocument().CreateRawElement(HTMLNames::scriptTag);
+ Element* script = GetDocument().CreateRawElement(html_names::kScriptTag);
script->SetInnerHTMLFromString(
"document.addEventListener('mouseup', event => "
"event.preventDefault());");
@@ -1115,7 +1117,8 @@ TEST_F(EventHandlerSimTest, MouseLeaveIFrameResets) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_inside_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_inside_event, Vector<WebMouseEvent>());
+ mouse_move_inside_event, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
EXPECT_FALSE(
GetDocument().GetFrame()->GetEventHandler().IsMousePositionUnknown());
auto* child_frame =
@@ -1135,7 +1138,8 @@ TEST_F(EventHandlerSimTest, MouseLeaveIFrameResets) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_outside_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_outside_event, Vector<WebMouseEvent>());
+ mouse_move_outside_event, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
EXPECT_FALSE(
GetDocument().GetFrame()->GetEventHandler().IsMousePositionUnknown());
EXPECT_TRUE(GetDocument().GetFrame()->Tree().FirstChild());
@@ -1180,7 +1184,7 @@ TEST_F(EventHandlerSimTest, CursorStyleBeforeStartDragging) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>());
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
EXPECT_EQ(Cursor::Type::kHelp, GetDocument()
.GetFrame()
->GetChromeClient()
diff --git a/chromium/third_party/blink/renderer/core/input/event_handling_util.cc b/chromium/third_party/blink/renderer/core/input/event_handling_util.cc
index 6404452c679..9f552bbb040 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handling_util.cc
+++ b/chromium/third_party/blink/renderer/core/input/event_handling_util.cc
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
namespace blink {
-namespace EventHandlingUtil {
+namespace event_handling_util {
HitTestResult HitTestResultInFrame(
LocalFrame* frame,
@@ -129,7 +129,7 @@ MouseEventWithHitTestResults PerformMouseEventHitTest(
mev);
}
-LocalFrame* SubframeForTargetNode(Node* node) {
+LocalFrame* SubframeForTargetNode(Node* node, bool* is_remote_frame) {
if (!node)
return nullptr;
@@ -141,18 +141,29 @@ LocalFrame* SubframeForTargetNode(Node* node) {
ToLayoutEmbeddedContent(layout_object)->ChildFrameView();
if (!frame_view)
return nullptr;
- if (!frame_view->IsLocalFrameView())
+ if (!frame_view->IsLocalFrameView()) {
+ if (is_remote_frame)
+ *is_remote_frame = true;
return nullptr;
+ }
return &ToLocalFrameView(frame_view)->GetFrame();
}
-LocalFrame* SubframeForHitTestResult(
- const MouseEventWithHitTestResults& hit_test_result) {
+LocalFrame* GetTargetSubframe(
+ const MouseEventWithHitTestResults& hit_test_result,
+ Node* capturing_node,
+ bool* is_remote_frame) {
+ if (capturing_node) {
+ return event_handling_util::SubframeForTargetNode(capturing_node,
+ is_remote_frame);
+ }
+
if (!hit_test_result.IsOverEmbeddedContentView())
return nullptr;
- return SubframeForTargetNode(hit_test_result.InnerNode());
+
+ return SubframeForTargetNode(hit_test_result.InnerNode(), is_remote_frame);
}
-} // namespace EventHandlingUtil
+} // namespace event_handling_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/input/event_handling_util.h b/chromium/third_party/blink/renderer/core/input/event_handling_util.h
index 6e36d3a341f..fc457c2c8c2 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handling_util.h
+++ b/chromium/third_party/blink/renderer/core/input/event_handling_util.h
@@ -20,7 +20,7 @@ class ScrollableArea;
class PaintLayer;
enum class DispatchEventResult;
-namespace EventHandlingUtil {
+namespace event_handling_util {
HitTestResult HitTestResultInFrame(
LocalFrame*,
@@ -46,9 +46,11 @@ MouseEventWithHitTestResults PerformMouseEventHitTest(LocalFrame*,
const HitTestRequest&,
const WebMouseEvent&);
-LocalFrame* SubframeForHitTestResult(const MouseEventWithHitTestResults&);
+LocalFrame* GetTargetSubframe(const MouseEventWithHitTestResults&,
+ Node* capturing_node = nullptr,
+ bool* is_remote_frame = nullptr);
-LocalFrame* SubframeForTargetNode(Node*);
+LocalFrame* SubframeForTargetNode(Node*, bool* is_remote_frame = nullptr);
class PointerEventTarget {
DISALLOW_NEW();
@@ -64,10 +66,11 @@ class PointerEventTarget {
String region;
};
-} // namespace EventHandlingUtil
+} // namespace event_handling_util
} // namespace blink
-WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::EventHandlingUtil::PointerEventTarget);
+WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(
+ blink::event_handling_util::PointerEventTarget);
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_INPUT_EVENT_HANDLING_UTIL_H_
diff --git a/chromium/third_party/blink/renderer/core/input/gesture_manager.cc b/chromium/third_party/blink/renderer/core/input/gesture_manager.cc
index 83a2ff8c130..b148e1b134d 100644
--- a/chromium/third_party/blink/renderer/core/input/gesture_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/gesture_manager.cc
@@ -108,7 +108,7 @@ WebInputEventResult GestureManager::HandleGestureEventInFrame(
if (gesture_dom_event_result != DispatchEventResult::kNotCanceled) {
DCHECK(gesture_dom_event_result !=
DispatchEventResult::kCanceledByEventHandler);
- return EventHandlingUtil::ToWebInputEventResult(
+ return event_handling_util::ToWebInputEventResult(
gesture_dom_event_result);
}
}
@@ -177,7 +177,7 @@ WebInputEventResult GestureManager::HandleGestureTap(
gesture_event.TimeStamp());
mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
current_hit_test.InnerNode(), current_hit_test.CanvasRegionId(),
- EventTypeNames::mousemove, fake_mouse_move);
+ event_type_names::kMousemove, fake_mouse_move);
}
// Do a new hit-test in case the mousemove event changed the DOM.
@@ -196,7 +196,7 @@ WebInputEventResult GestureManager::HandleGestureTap(
return WebInputEventResult::kNotHandled;
adjusted_point = frame_view->ConvertFromRootFrame(
FlooredIntPoint(gesture_event.PositionInRootFrame()));
- current_hit_test = EventHandlingUtil::HitTestResultInFrame(
+ current_hit_test = event_handling_util::HitTestResultInFrame(
frame_, HitTestLocation(adjusted_point), hit_type);
}
@@ -229,7 +229,7 @@ WebInputEventResult GestureManager::HandleGestureTap(
mouse_down_event_result =
mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
current_hit_test.InnerNode(), current_hit_test.CanvasRegionId(),
- EventTypeNames::mousedown, fake_mouse_down);
+ event_type_names::kMousedown, fake_mouse_down);
selection_controller_->InitializeSelectionState();
if (mouse_down_event_result == WebInputEventResult::kNotHandled) {
mouse_down_event_result = mouse_event_manager_->HandleMouseFocus(
@@ -256,10 +256,12 @@ WebInputEventResult GestureManager::HandleGestureTap(
// http://crbug.com/398920
if (current_hit_test.InnerNode()) {
LocalFrame& main_frame = frame_->LocalFrameRoot();
- if (main_frame.View())
- main_frame.View()->UpdateAllLifecyclePhases();
+ if (main_frame.View()) {
+ main_frame.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
+ }
adjusted_point = frame_view->ConvertFromRootFrame(tapped_position);
- current_hit_test = EventHandlingUtil::HitTestResultInFrame(
+ current_hit_test = event_handling_util::HitTestResultInFrame(
frame_, HitTestLocation(adjusted_point), hit_type);
}
@@ -274,7 +276,7 @@ WebInputEventResult GestureManager::HandleGestureTap(
? WebInputEventResult::kHandledSuppressed
: mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
current_hit_test.InnerNode(), current_hit_test.CanvasRegionId(),
- EventTypeNames::mouseup, fake_mouse_up);
+ event_type_names::kMouseup, fake_mouse_up);
WebInputEventResult click_event_result = WebInputEventResult::kNotHandled;
if (tapped_element) {
@@ -287,10 +289,10 @@ WebInputEventResult GestureManager::HandleGestureTap(
// different.
tapped_element->UpdateDistributionForFlatTreeTraversal();
Node* click_target_node = current_hit_test.InnerNode()->CommonAncestor(
- *tapped_element, EventHandlingUtil::ParentForClickEvent);
+ *tapped_element, event_handling_util::ParentForClickEvent);
click_event_result =
mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
- click_target_node, String(), EventTypeNames::click,
+ click_target_node, String(), event_type_names::kClick,
fake_mouse_up);
}
mouse_event_manager_->SetClickElement(nullptr);
@@ -303,9 +305,9 @@ WebInputEventResult GestureManager::HandleGestureTap(
}
mouse_event_manager_->ClearDragHeuristicState();
- WebInputEventResult event_result = EventHandlingUtil::MergeEventResult(
- EventHandlingUtil::MergeEventResult(mouse_down_event_result,
- mouse_up_event_result),
+ WebInputEventResult event_result = event_handling_util::MergeEventResult(
+ event_handling_util::MergeEventResult(mouse_down_event_result,
+ mouse_up_event_result),
click_event_result);
if (event_result == WebInputEventResult::kNotHandled && tapped_node &&
frame_->GetPage()) {
@@ -401,7 +403,7 @@ WebInputEventResult GestureManager::SendContextMenuEventForGesture(
gesture_event.TimeStamp());
mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
targeted_event.GetHitTestResult().InnerNode(),
- targeted_event.CanvasRegionId(), EventTypeNames::mousemove,
+ targeted_event.CanvasRegionId(), event_type_names::kMousemove,
fake_mouse_move);
}
diff --git a/chromium/third_party/blink/renderer/core/input/ime_on_focus_test.cc b/chromium/third_party/blink/renderer/core/input/ime_on_focus_test.cc
index 7127ee87cbb..a334dbd7e65 100644
--- a/chromium/third_party/blink/renderer/core/input/ime_on_focus_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/ime_on_focus_test.cc
@@ -16,14 +16,14 @@
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
-using blink::FrameTestHelpers::LoadFrame;
+using blink::frame_test_helpers::LoadFrame;
using blink::test::RunPendingTasks;
-using blink::URLTestHelpers::RegisterMockedURLLoadFromBase;
+using blink::url_test_helpers::RegisterMockedURLLoadFromBase;
namespace blink {
class ImeRequestTrackingWebViewClient
- : public FrameTestHelpers::TestWebWidgetClient {
+ : public frame_test_helpers::TestWebWidgetClient {
public:
ImeRequestTrackingWebViewClient() : virtual_keyboard_request_count_(0) {}
@@ -61,7 +61,7 @@ class ImeOnFocusTest : public testing::Test {
std::string frame = "");
std::string base_url_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
Persistent<Document> document_;
};
@@ -77,7 +77,8 @@ void ImeOnFocusTest::SendGestureTap(WebView* web_view, IntPoint client_point) {
web_gesture_event.data.tap.width = 10;
web_gesture_event.data.tap.height = 10;
- web_view->HandleInputEvent(WebCoalescedInputEvent(web_gesture_event));
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(web_gesture_event));
RunPendingTasks();
}
diff --git a/chromium/third_party/blink/renderer/core/input/input_device_capabilities.cc b/chromium/third_party/blink/renderer/core/input/input_device_capabilities.cc
index 720756db68d..076adfba3c6 100644
--- a/chromium/third_party/blink/renderer/core/input/input_device_capabilities.cc
+++ b/chromium/third_party/blink/renderer/core/input/input_device_capabilities.cc
@@ -11,8 +11,8 @@ InputDeviceCapabilities::InputDeviceCapabilities(bool fires_touch_events) {
}
InputDeviceCapabilities::InputDeviceCapabilities(
- const InputDeviceCapabilitiesInit& initializer) {
- fires_touch_events_ = initializer.firesTouchEvents();
+ const InputDeviceCapabilitiesInit* initializer) {
+ fires_touch_events_ = initializer->firesTouchEvents();
}
InputDeviceCapabilities* InputDeviceCapabilitiesConstants::FiresTouchEvents(
diff --git a/chromium/third_party/blink/renderer/core/input/input_device_capabilities.h b/chromium/third_party/blink/renderer/core/input/input_device_capabilities.h
index 8ebfdd74308..21cf5e4b7a3 100644
--- a/chromium/third_party/blink/renderer/core/input/input_device_capabilities.h
+++ b/chromium/third_party/blink/renderer/core/input/input_device_capabilities.h
@@ -16,20 +16,20 @@ class CORE_EXPORT InputDeviceCapabilities final : public ScriptWrappable {
public:
static InputDeviceCapabilities* Create(bool fires_touch_events) {
- return new InputDeviceCapabilities(fires_touch_events);
+ return MakeGarbageCollected<InputDeviceCapabilities>(fires_touch_events);
}
static InputDeviceCapabilities* Create(
- const InputDeviceCapabilitiesInit& initializer) {
- return new InputDeviceCapabilities(initializer);
+ const InputDeviceCapabilitiesInit* initializer) {
+ return MakeGarbageCollected<InputDeviceCapabilities>(initializer);
}
+ InputDeviceCapabilities(bool fires_touch_events);
+ InputDeviceCapabilities(const InputDeviceCapabilitiesInit*);
+
bool firesTouchEvents() const { return fires_touch_events_; }
private:
- InputDeviceCapabilities(bool fires_touch_events);
- InputDeviceCapabilities(const InputDeviceCapabilitiesInit&);
-
// Whether this device dispatches touch events. This mainly lets developers
// avoid handling both touch and mouse events dispatched for a single user
// action.
diff --git a/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.cc b/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.cc
index f39d657a13c..04ee9f4ba4f 100644
--- a/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.cc
@@ -221,7 +221,7 @@ WebInputEventResult KeyboardEventManager::KeyEvent(
KeyboardEvent* dom_event = KeyboardEvent::Create(
initial_key_event, frame_->GetDocument()->domWindow());
- return EventHandlingUtil::ToWebInputEventResult(
+ return event_handling_util::ToWebInputEventResult(
node->DispatchEvent(*dom_event));
}
@@ -236,7 +236,7 @@ WebInputEventResult KeyboardEventManager::KeyEvent(
DispatchEventResult dispatch_result = node->DispatchEvent(*keydown);
if (dispatch_result != DispatchEventResult::kNotCanceled)
- return EventHandlingUtil::ToWebInputEventResult(dispatch_result);
+ return event_handling_util::ToWebInputEventResult(dispatch_result);
// If frame changed as a result of keydown dispatch, then return early to
// avoid sending a subsequent keypress message to the new frame.
bool changed_focused_frame =
@@ -273,7 +273,7 @@ WebInputEventResult KeyboardEventManager::KeyEvent(
KeyboardEvent* keypress = KeyboardEvent::Create(
key_press_event, frame_->GetDocument()->domWindow());
keypress->SetTarget(node);
- return EventHandlingUtil::ToWebInputEventResult(
+ return event_handling_util::ToWebInputEventResult(
node->DispatchEvent(*keypress));
}
@@ -289,7 +289,7 @@ void KeyboardEventManager::CapsLockStateMayHaveChanged() {
void KeyboardEventManager::DefaultKeyboardEventHandler(
KeyboardEvent* event,
Node* possible_focused_node) {
- if (event->type() == EventTypeNames::keydown) {
+ if (event->type() == event_type_names::kKeydown) {
frame_->GetEditor().HandleKeyboardEvent(event);
if (event->DefaultHandled())
return;
@@ -306,7 +306,7 @@ void KeyboardEventManager::DefaultKeyboardEventHandler(
DefaultArrowEventHandler(event, possible_focused_node);
}
}
- if (event->type() == EventTypeNames::keypress) {
+ if (event->type() == event_type_names::kKeypress) {
frame_->GetEditor().HandleKeyboardEvent(event);
if (event->DefaultHandled())
return;
@@ -318,7 +318,7 @@ void KeyboardEventManager::DefaultKeyboardEventHandler(
void KeyboardEventManager::DefaultSpaceEventHandler(
KeyboardEvent* event,
Node* possible_focused_node) {
- DCHECK_EQ(event->type(), EventTypeNames::keypress);
+ DCHECK_EQ(event->type(), event_type_names::kKeypress);
if (event->ctrlKey() || event->metaKey() || event->altKey())
return;
@@ -339,7 +339,7 @@ void KeyboardEventManager::DefaultSpaceEventHandler(
void KeyboardEventManager::DefaultArrowEventHandler(
KeyboardEvent* event,
Node* possible_focused_node) {
- DCHECK_EQ(event->type(), EventTypeNames::keydown);
+ DCHECK_EQ(event->type(), event_type_names::kKeydown);
Page* page = frame_->GetPage();
if (!page)
@@ -374,7 +374,7 @@ void KeyboardEventManager::DefaultArrowEventHandler(
}
void KeyboardEventManager::DefaultTabEventHandler(KeyboardEvent* event) {
- DCHECK_EQ(event->type(), EventTypeNames::keydown);
+ DCHECK_EQ(event->type(), event_type_names::kKeydown);
// We should only advance focus on tabs if no special modifier keys are held
// down.
@@ -411,7 +411,7 @@ void KeyboardEventManager::DefaultTabEventHandler(KeyboardEvent* event) {
void KeyboardEventManager::DefaultEscapeEventHandler(KeyboardEvent* event) {
if (HTMLDialogElement* dialog = frame_->GetDocument()->ActiveModalDialog())
- dialog->DispatchEvent(*Event::CreateCancelable(EventTypeNames::cancel));
+ dialog->DispatchEvent(*Event::CreateCancelable(event_type_names::kCancel));
}
static OverrideCapsLockState g_override_caps_lock_state;
diff --git a/chromium/third_party/blink/renderer/core/input/mouse_event_manager.cc b/chromium/third_party/blink/renderer/core/input/mouse_event_manager.cc
index 10775801d02..7b5b4009d8e 100644
--- a/chromium/third_party/blink/renderer/core/input/mouse_event_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/mouse_event_manager.cc
@@ -61,6 +61,27 @@ String CanvasRegionId(Node* node, const WebMouseEvent& mouse_event) {
return canvas->GetIdFromControl(element);
}
+void UpdateMouseMovementXY(const WebMouseEvent& mouse_event,
+ const FloatPoint* last_position,
+ MouseEventInit* initializer) {
+ if (RuntimeEnabledFeatures::MovementXYInBlinkEnabled() &&
+ mouse_event.GetType() == WebInputEvent::kMouseMove && last_position) {
+ if (RuntimeEnabledFeatures::FractionalMouseEventEnabled()) {
+ initializer->setMovementX(mouse_event.PositionInScreen().x -
+ last_position->X());
+ initializer->setMovementY(mouse_event.PositionInScreen().y -
+ last_position->Y());
+ } else {
+ initializer->setMovementX(
+ static_cast<int>(mouse_event.PositionInScreen().x) -
+ static_cast<int>(last_position->X()));
+ initializer->setMovementY(
+ static_cast<int>(mouse_event.PositionInScreen().y) -
+ static_cast<int>(last_position->Y()));
+ }
+ }
+}
+
// The amount of time to wait before sending a fake mouse event triggered
// during a scroll.
constexpr TimeDelta kFakeMouseMoveIntervalDuringScroll =
@@ -116,7 +137,7 @@ void MouseEventManager::Clear() {
svg_pan_ = false;
drag_start_pos_ = LayoutPoint();
fake_mouse_move_event_timer_.Stop();
- ResetDragState();
+ ResetDragSource();
ClearDragDataTransfer();
}
@@ -145,7 +166,7 @@ MouseEventManager::MouseEventBoundaryEventDispatcher::
void MouseEventManager::MouseEventBoundaryEventDispatcher::DispatchOut(
EventTarget* target,
EventTarget* related_target) {
- Dispatch(target, related_target, EventTypeNames::mouseout,
+ Dispatch(target, related_target, event_type_names::kMouseout,
CanvasRegionId(exited_target_->ToNode(), *web_mouse_event_),
*web_mouse_event_, false);
}
@@ -153,15 +174,15 @@ void MouseEventManager::MouseEventBoundaryEventDispatcher::DispatchOut(
void MouseEventManager::MouseEventBoundaryEventDispatcher::DispatchOver(
EventTarget* target,
EventTarget* related_target) {
- Dispatch(target, related_target, EventTypeNames::mouseover, canvas_region_id_,
- *web_mouse_event_, false);
+ Dispatch(target, related_target, event_type_names::kMouseover,
+ canvas_region_id_, *web_mouse_event_, false);
}
void MouseEventManager::MouseEventBoundaryEventDispatcher::DispatchLeave(
EventTarget* target,
EventTarget* related_target,
bool check_for_listener) {
- Dispatch(target, related_target, EventTypeNames::mouseleave,
+ Dispatch(target, related_target, event_type_names::kMouseleave,
CanvasRegionId(exited_target_->ToNode(), *web_mouse_event_),
*web_mouse_event_, check_for_listener);
}
@@ -170,18 +191,18 @@ void MouseEventManager::MouseEventBoundaryEventDispatcher::DispatchEnter(
EventTarget* target,
EventTarget* related_target,
bool check_for_listener) {
- Dispatch(target, related_target, EventTypeNames::mouseenter,
+ Dispatch(target, related_target, event_type_names::kMouseenter,
canvas_region_id_, *web_mouse_event_, check_for_listener);
}
AtomicString
MouseEventManager::MouseEventBoundaryEventDispatcher::GetLeaveEvent() {
- return EventTypeNames::mouseleave;
+ return event_type_names::kMouseleave;
}
AtomicString
MouseEventManager::MouseEventBoundaryEventDispatcher::GetEnterEvent() {
- return EventTypeNames::mouseenter;
+ return event_type_names::kMouseenter;
}
void MouseEventManager::MouseEventBoundaryEventDispatcher::Dispatch(
@@ -192,8 +213,8 @@ void MouseEventManager::MouseEventBoundaryEventDispatcher::Dispatch(
const WebMouseEvent& web_mouse_event,
bool check_for_listener) {
mouse_event_manager_->DispatchMouseEvent(target, type, web_mouse_event,
- canvas_region_id, related_target,
- check_for_listener);
+ canvas_region_id, nullptr,
+ related_target, check_for_listener);
}
void MouseEventManager::SendBoundaryEvents(EventTarget* exited_target,
@@ -210,40 +231,42 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
const AtomicString& mouse_event_type,
const WebMouseEvent& mouse_event,
const String& canvas_region_id,
+ const FloatPoint* last_position,
EventTarget* related_target,
bool check_for_listener) {
if (target && target->ToNode() &&
(!check_for_listener || target->HasEventListeners(mouse_event_type))) {
Node* target_node = target->ToNode();
int click_count = 0;
- if (mouse_event_type == EventTypeNames::mouseup ||
- mouse_event_type == EventTypeNames::mousedown ||
- mouse_event_type == EventTypeNames::click ||
- mouse_event_type == EventTypeNames::auxclick ||
- mouse_event_type == EventTypeNames::dblclick) {
+ if (mouse_event_type == event_type_names::kMouseup ||
+ mouse_event_type == event_type_names::kMousedown ||
+ mouse_event_type == event_type_names::kClick ||
+ mouse_event_type == event_type_names::kAuxclick ||
+ mouse_event_type == event_type_names::kDblclick) {
click_count = click_count_;
}
bool is_mouse_enter_or_leave =
- mouse_event_type == EventTypeNames::mouseenter ||
- mouse_event_type == EventTypeNames::mouseleave;
- MouseEventInit initializer;
- initializer.setBubbles(!is_mouse_enter_or_leave);
- initializer.setCancelable(!is_mouse_enter_or_leave);
+ mouse_event_type == event_type_names::kMouseenter ||
+ mouse_event_type == event_type_names::kMouseleave;
+ MouseEventInit* initializer = MouseEventInit::Create();
+ initializer->setBubbles(!is_mouse_enter_or_leave);
+ initializer->setCancelable(!is_mouse_enter_or_leave);
MouseEvent::SetCoordinatesFromWebPointerProperties(
mouse_event.FlattenTransform(), target_node->GetDocument().domWindow(),
initializer);
- initializer.setButton(static_cast<short>(mouse_event.button));
- initializer.setButtons(MouseEvent::WebInputEventModifiersToButtons(
+ UpdateMouseMovementXY(mouse_event, last_position, initializer);
+ initializer->setButton(static_cast<short>(mouse_event.button));
+ initializer->setButtons(MouseEvent::WebInputEventModifiersToButtons(
mouse_event.GetModifiers()));
- initializer.setView(target_node->GetDocument().domWindow());
- initializer.setComposed(true);
- initializer.setDetail(click_count);
- initializer.setRegion(canvas_region_id);
- initializer.setRelatedTarget(related_target);
+ initializer->setView(target_node->GetDocument().domWindow());
+ initializer->setComposed(true);
+ initializer->setDetail(click_count);
+ initializer->setRegion(canvas_region_id);
+ initializer->setRelatedTarget(related_target);
UIEventWithKeyState::SetFromWebInputEventModifiers(
initializer,
static_cast<WebInputEvent::Modifiers>(mouse_event.GetModifiers()));
- initializer.setSourceCapabilities(
+ initializer->setSourceCapabilities(
target_node->GetDocument().domWindow()
? target_node->GetDocument()
.domWindow()
@@ -258,7 +281,7 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
mouse_event.menu_source_type);
DispatchEventResult dispatch_result = target->DispatchEvent(*event);
- return EventHandlingUtil::ToWebInputEventResult(dispatch_result);
+ return event_handling_util::ToWebInputEventResult(dispatch_result);
}
return WebInputEventResult::kNotHandled;
}
@@ -275,7 +298,7 @@ WebInputEventResult MouseEventManager::SetMousePositionAndDispatchMouseEvent(
SetNodeUnderMouse(target_node, canvas_region_id, web_mouse_event);
return DispatchMouseEvent(node_under_mouse_, event_type, web_mouse_event,
- canvas_region_id, nullptr);
+ canvas_region_id, nullptr, nullptr);
}
WebInputEventResult MouseEventManager::DispatchMouseClickIfNeeded(
@@ -316,7 +339,7 @@ WebInputEventResult MouseEventManager::DispatchMouseClickIfNeeded(
mouse_down_element_->UpdateDistributionForFlatTreeTraversal();
mouse_release_target.UpdateDistributionForFlatTreeTraversal();
click_target_node = mouse_release_target.CommonAncestor(
- *mouse_down_element_, EventHandlingUtil::ParentForClickEvent);
+ *mouse_down_element_, event_handling_util::ParentForClickEvent);
}
if (!click_target_node)
return WebInputEventResult::kNotHandled;
@@ -338,9 +361,9 @@ WebInputEventResult MouseEventManager::DispatchMouseClickIfNeeded(
return DispatchMouseEvent(
click_target_node,
(mev.Event().button == WebPointerProperties::Button::kLeft)
- ? EventTypeNames::click
- : EventTypeNames::auxclick,
- mev.Event(), mev.CanvasRegionId(), nullptr);
+ ? event_type_names::kClick
+ : event_type_names::kAuxclick,
+ mev.Event(), mev.CanvasRegionId(), nullptr, nullptr);
}
return WebInputEventResult::kNotHandled;
@@ -350,6 +373,10 @@ void MouseEventManager::FakeMouseMoveEventTimerFired(TimerBase* timer) {
TRACE_EVENT0("input", "MouseEventManager::fakeMouseMoveEventTimerFired");
DCHECK(timer == &fake_mouse_move_event_timer_);
+ RecomputeMouseHoverState();
+}
+
+void MouseEventManager::RecomputeMouseHoverState() {
if (is_mouse_position_unknown_)
return;
@@ -376,9 +403,10 @@ void MouseEventManager::FakeMouseMoveEventTimerFired(TimerBase* timer) {
last_known_mouse_position_,
last_known_mouse_global_position_, button,
0, modifiers, CurrentTimeTicks());
- Vector<WebMouseEvent> coalesced_events;
+ Vector<WebMouseEvent> coalesced_events, predicted_events;
frame_->GetEventHandler().HandleMouseMoveEvent(
- TransformWebMouseEvent(view, fake_mouse_move_event), coalesced_events);
+ TransformWebMouseEvent(view, fake_mouse_move_event), coalesced_events,
+ predicted_events);
}
void MouseEventManager::CancelFakeMouseMoveEvent() {
@@ -393,9 +421,9 @@ void MouseEventManager::SetNodeUnderMouse(
node_under_mouse_ = target;
PaintLayer* layer_for_last_node =
- EventHandlingUtil::LayerForNode(last_node_under_mouse);
+ event_handling_util::LayerForNode(last_node_under_mouse);
PaintLayer* layer_for_node_under_mouse =
- EventHandlingUtil::LayerForNode(node_under_mouse_.Get());
+ event_handling_util::LayerForNode(node_under_mouse_.Get());
Page* page = frame_->GetPage();
if (page && (layer_for_last_node &&
@@ -403,7 +431,7 @@ void MouseEventManager::SetNodeUnderMouse(
layer_for_node_under_mouse != layer_for_last_node))) {
// The mouse has moved between layers.
if (ScrollableArea* scrollable_area_for_last_node =
- EventHandlingUtil::AssociatedScrollableArea(layer_for_last_node))
+ event_handling_util::AssociatedScrollableArea(layer_for_last_node))
scrollable_area_for_last_node->MouseExitedContentArea();
}
@@ -412,7 +440,7 @@ void MouseEventManager::SetNodeUnderMouse(
layer_for_node_under_mouse != layer_for_last_node))) {
// The mouse has moved between layers.
if (ScrollableArea* scrollable_area_for_node_under_mouse =
- EventHandlingUtil::AssociatedScrollableArea(
+ event_handling_util::AssociatedScrollableArea(
layer_for_node_under_mouse))
scrollable_area_for_node_under_mouse->MouseEnteredContentArea();
}
@@ -614,7 +642,6 @@ void MouseEventManager::MayUpdateHoverWhenContentUnderMouseChanged(
if (RuntimeEnabledFeatures::NoHoverAfterLayoutChangeEnabled() &&
update_hover_reason ==
MouseEventManager::UpdateHoverReason::kLayoutOrStyleChanged) {
- frame_->LocalFrameRoot().GetEventHandler().ScheduleCursorUpdate();
return;
}
@@ -662,7 +689,7 @@ WebInputEventResult MouseEventManager::HandleMousePressEvent(
const MouseEventWithHitTestResults& event) {
TRACE_EVENT0("blink", "MouseEventManager::handleMousePressEvent");
- ResetDragState();
+ ResetDragSource();
CancelFakeMouseMoveEvent();
frame_->GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
@@ -759,10 +786,10 @@ bool MouseEventManager::HandleDragDropIfPossible(
CurrentTimeTicks());
HitTestRequest request(HitTestRequest::kReadOnly);
MouseEventWithHitTestResults mev =
- EventHandlingUtil::PerformMouseEventHitTest(frame_, request,
- mouse_drag_event);
+ event_handling_util::PerformMouseEventHitTest(frame_, request,
+ mouse_drag_event);
mouse_down_may_start_drag_ = true;
- ResetDragState();
+ ResetDragSource();
mouse_down_pos_ = frame_->View()->ConvertFromRootFrame(
FlooredIntPoint(mouse_drag_event.PositionInRootFrame()));
return HandleDrag(mev, DragInitiator::kTouch);
@@ -895,7 +922,7 @@ bool MouseEventManager::HandleDrag(const MouseEventWithHitTestResults& event,
frame_, node, mouse_down_pos_, selection_drag_policy,
GetDragState().drag_type_);
} else {
- ResetDragState();
+ ResetDragSource();
}
if (!GetDragState().drag_src_)
@@ -913,7 +940,7 @@ bool MouseEventManager::HandleDrag(const MouseEventWithHitTestResults& event,
if (initiator == DragInitiator::kMouse &&
!DragThresholdExceeded(
FlooredIntPoint(event.Event().PositionInRootFrame()))) {
- ResetDragState();
+ ResetDragSource();
return true;
}
@@ -924,7 +951,7 @@ bool MouseEventManager::HandleDrag(const MouseEventWithHitTestResults& event,
if (!TryStartDrag(event)) {
// Something failed to start the drag, clean up.
ClearDragDataTransfer();
- ResetDragState();
+ ResetDragSource();
} else {
// Since drag operation started we need to send a pointercancel for the
// corresponding pointer.
@@ -933,7 +960,7 @@ bool MouseEventManager::HandleDrag(const MouseEventWithHitTestResults& event,
WebPointerEvent::CreatePointerCausesUaActionEvent(
WebPointerProperties::PointerType::kMouse,
event.Event().TimeStamp()),
- Vector<WebPointerEvent>());
+ Vector<WebPointerEvent>(), Vector<WebPointerEvent>());
}
// TODO(crbug.com/708278): If the drag starts with touch the touch cancel
// should trigger the release of pointer capture.
@@ -964,7 +991,7 @@ bool MouseEventManager::TryStartDrag(
mouse_down_pos_))
return false;
- if (DispatchDragSrcEvent(EventTypeNames::dragstart, mouse_down_) !=
+ if (DispatchDragSrcEvent(event_type_names::kDragstart, mouse_down_) !=
WebInputEventResult::kNotHandled)
return false;
@@ -1001,7 +1028,7 @@ bool MouseEventManager::TryStartDrag(
return true;
// Drag was canned at the last minute - we owe m_dragSrc a DRAGEND event
- DispatchDragSrcEvent(EventTypeNames::dragend, event.Event());
+ DispatchDragSrcEvent(event_type_names::kDragend, event.Event());
return false;
}
@@ -1033,21 +1060,21 @@ WebInputEventResult MouseEventManager::DispatchDragEvent(
related_target->GetDocument() != drag_target->GetDocument())
related_target = nullptr;
- DragEventInit initializer;
- initializer.setBubbles(true);
- initializer.setCancelable(event_type != EventTypeNames::dragleave &&
- event_type != EventTypeNames::dragend);
+ DragEventInit* initializer = DragEventInit::Create();
+ initializer->setBubbles(true);
+ initializer->setCancelable(event_type != event_type_names::kDragleave &&
+ event_type != event_type_names::kDragend);
MouseEvent::SetCoordinatesFromWebPointerProperties(
event.FlattenTransform(), frame_->GetDocument()->domWindow(),
initializer);
- initializer.setButton(0);
- initializer.setButtons(
+ initializer->setButton(0);
+ initializer->setButtons(
MouseEvent::WebInputEventModifiersToButtons(event.GetModifiers()));
- initializer.setRelatedTarget(related_target);
- initializer.setView(frame_->GetDocument()->domWindow());
- initializer.setComposed(true);
- initializer.setGetDataTransfer(data_transfer);
- initializer.setSourceCapabilities(
+ initializer->setRelatedTarget(related_target);
+ initializer->setView(frame_->GetDocument()->domWindow());
+ initializer->setComposed(true);
+ initializer->setGetDataTransfer(data_transfer);
+ initializer->setSourceCapabilities(
frame_->GetDocument()->domWindow()
? frame_->GetDocument()
->domWindow()
@@ -1062,7 +1089,7 @@ WebInputEventResult MouseEventManager::DispatchDragEvent(
? MouseEvent::kFromTouch
: MouseEvent::kRealOrIndistinguishable);
- return EventHandlingUtil::ToWebInputEventResult(
+ return event_handling_util::ToWebInputEventResult(
drag_target->DispatchEvent(*me));
}
@@ -1081,10 +1108,10 @@ void MouseEventManager::DragSourceEndedAt(const WebMouseEvent& event,
if (GetDragState().drag_src_) {
GetDragState().drag_data_transfer_->SetDestinationOperation(operation);
// The return value is ignored because dragend is not cancelable.
- DispatchDragSrcEvent(EventTypeNames::dragend, event);
+ DispatchDragSrcEvent(event_type_names::kDragend, event);
}
ClearDragDataTransfer();
- ResetDragState();
+ ResetDragSource();
// In case the drag was ended due to an escape key press we need to ensure
// that consecutive mousemove events don't reinitiate the drag and drop.
mouse_down_may_start_drag_ = false;
@@ -1095,9 +1122,30 @@ DragState& MouseEventManager::GetDragState() {
return frame_->GetPage()->GetDragController().GetDragState();
}
-void MouseEventManager::ResetDragState() {
+void MouseEventManager::ResetDragSource() {
+ // Check validity of drag source.
if (!frame_->GetPage())
return;
+
+ Node* drag_src = GetDragState().drag_src_;
+ if (!drag_src)
+ return;
+
+ Frame* drag_src_frame = drag_src->GetDocument().GetFrame();
+ if (!drag_src_frame) {
+ // The frame containing the drag_src has been navigated away, so the
+ // drag_src is no longer has an owning frame and is invalid.
+ // See https://crbug.com/903705 for more details.
+ GetDragState().drag_src_ = nullptr;
+ return;
+ }
+
+ // Only allow resetting drag_src_ if the frame requesting reset is above the
+ // drag_src_ node's frame in the frame hierarchy. This way, unrelated frames
+ // can't reset a drag state.
+ if (!drag_src_frame->Tree().IsDescendantOf(frame_))
+ return;
+
GetDragState().drag_src_ = nullptr;
}
diff --git a/chromium/third_party/blink/renderer/core/input/mouse_event_manager.h b/chromium/third_party/blink/renderer/core/input/mouse_event_manager.h
index 2f2d6028ba1..c234d92e0df 100644
--- a/chromium/third_party/blink/renderer/core/input/mouse_event_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/mouse_event_manager.h
@@ -49,6 +49,7 @@ class CORE_EXPORT MouseEventManager final
const AtomicString&,
const WebMouseEvent&,
const String& canvas_region_id,
+ const FloatPoint* last_position,
EventTarget* related_target,
bool check_for_listener = false);
@@ -154,6 +155,8 @@ class CORE_EXPORT MouseEventManager final
bool FakeMouseMovePending() const;
+ void RecomputeMouseHoverState();
+
private:
class MouseEventBoundaryEventDispatcher : public BoundaryEventDispatcher {
public:
@@ -199,7 +202,7 @@ class CORE_EXPORT MouseEventManager final
void ClearDragDataTransfer();
DataTransfer* CreateDraggingDataTransfer() const;
- void ResetDragState();
+ void ResetDragSource();
// Implementations of |SynchronousMutationObserver|
void NodeChildrenWillBeRemoved(ContainerNode&) final;
diff --git a/chromium/third_party/blink/renderer/core/input/mouse_wheel_event_manager.cc b/chromium/third_party/blink/renderer/core/input/mouse_wheel_event_manager.cc
index 38e5e843b98..824e1e8e715 100644
--- a/chromium/third_party/blink/renderer/core/input/mouse_wheel_event_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/mouse_wheel_event_manager.cc
@@ -56,20 +56,21 @@ WebInputEventResult MouseWheelEventManager::HandleWheelEvent(
return WebInputEventResult::kNotHandled;
}
+ // Synthetic wheel events generated from GestureDoubleTap are phaseless.
+ // Wheel events generated from plugin and tests may not have phase info.
bool has_phase_info = event.phase != WebMouseWheelEvent::kPhaseNone ||
event.momentum_phase != WebMouseWheelEvent::kPhaseNone;
- if (!has_phase_info) {
- // Wheel events generated from plugin and tests may not have phase info.
- // Send these events to the target under the cursor.
- wheel_target_ = FindTargetNode(event, doc, view);
- } else if (event.phase == WebMouseWheelEvent::kPhaseBegan || !wheel_target_) {
- // Find and save the wheel_target_, this target will be used for the rest
- // of the current scrolling sequence.
+
+ // Find and save the wheel_target_, this target will be used for the rest
+ // of the current scrolling sequence. In the absence of phase info, send the
+ // event to the target under the cursor.
+ if (event.phase == WebMouseWheelEvent::kPhaseBegan || !wheel_target_ ||
+ !has_phase_info) {
wheel_target_ = FindTargetNode(event, doc, view);
}
LocalFrame* subframe =
- EventHandlingUtil::SubframeForTargetNode(wheel_target_.Get());
+ event_handling_util::SubframeForTargetNode(wheel_target_.Get());
if (subframe) {
WebInputEventResult result =
subframe->GetEventHandler().HandleWheelEvent(event);
@@ -99,7 +100,7 @@ WebInputEventResult MouseWheelEventManager::HandleWheelEvent(
// blocked by disabled frames.
return (should_enforce_vertical_scroll && is_vertical)
? WebInputEventResult::kNotHandled
- : EventHandlingUtil::ToWebInputEventResult(dom_event_result);
+ : event_handling_util::ToWebInputEventResult(dom_event_result);
}
}
diff --git a/chromium/third_party/blink/renderer/core/input/pointer_event_manager.cc b/chromium/third_party/blink/renderer/core/input/pointer_event_manager.cc
index 2c3f634f0ff..fffde3296b6 100644
--- a/chromium/third_party/blink/renderer/core/input/pointer_event_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/pointer_event_manager.cc
@@ -41,11 +41,11 @@ const AtomicString& MouseEventNameForPointerEventInputType(
const WebInputEvent::Type& event_type) {
switch (event_type) {
case WebInputEvent::Type::kPointerDown:
- return EventTypeNames::mousedown;
+ return event_type_names::kMousedown;
case WebInputEvent::Type::kPointerUp:
- return EventTypeNames::mouseup;
+ return event_type_names::kMouseup;
case WebInputEvent::Type::kPointerMove:
- return EventTypeNames::mousemove;
+ return event_type_names::kMousemove;
default:
NOTREACHED();
return g_empty_atom;
@@ -65,7 +65,7 @@ Element* GetPointerLockedElement(LocalFrame* frame) {
PointerEventManager::PointerEventManager(LocalFrame& frame,
MouseEventManager& mouse_event_manager)
: frame_(frame),
- touch_event_manager_(new TouchEventManager(frame)),
+ touch_event_manager_(MakeGarbageCollected<TouchEventManager>(frame)),
mouse_event_manager_(mouse_event_manager) {
Clear();
}
@@ -103,20 +103,20 @@ PointerEventManager::PointerEventBoundaryEventDispatcher::
void PointerEventManager::PointerEventBoundaryEventDispatcher::DispatchOut(
EventTarget* target,
EventTarget* related_target) {
- Dispatch(target, related_target, EventTypeNames::pointerout, false);
+ Dispatch(target, related_target, event_type_names::kPointerout, false);
}
void PointerEventManager::PointerEventBoundaryEventDispatcher::DispatchOver(
EventTarget* target,
EventTarget* related_target) {
- Dispatch(target, related_target, EventTypeNames::pointerover, false);
+ Dispatch(target, related_target, event_type_names::kPointerover, false);
}
void PointerEventManager::PointerEventBoundaryEventDispatcher::DispatchLeave(
EventTarget* target,
EventTarget* related_target,
bool check_for_listener) {
- Dispatch(target, related_target, EventTypeNames::pointerleave,
+ Dispatch(target, related_target, event_type_names::kPointerleave,
check_for_listener);
}
@@ -124,18 +124,18 @@ void PointerEventManager::PointerEventBoundaryEventDispatcher::DispatchEnter(
EventTarget* target,
EventTarget* related_target,
bool check_for_listener) {
- Dispatch(target, related_target, EventTypeNames::pointerenter,
+ Dispatch(target, related_target, event_type_names::kPointerenter,
check_for_listener);
}
AtomicString
PointerEventManager::PointerEventBoundaryEventDispatcher::GetLeaveEvent() {
- return EventTypeNames::pointerleave;
+ return event_type_names::kPointerleave;
}
AtomicString
PointerEventManager::PointerEventBoundaryEventDispatcher::GetEnterEvent() {
- return EventTypeNames::pointerenter;
+ return event_type_names::kPointerenter;
}
void PointerEventManager::PointerEventBoundaryEventDispatcher::Dispatch(
@@ -163,7 +163,7 @@ WebInputEventResult PointerEventManager::DispatchPointerEvent(
if (!frame_ || !HasPointerEventListener(frame_->GetEventHandlerRegistry()))
return WebInputEventResult::kNotHandled;
- if (event_type == EventTypeNames::pointerdown) {
+ if (event_type == event_type_names::kPointerdown) {
Node* node = target->ToNode();
if (node && IsHTMLCanvasElement(*node) &&
ToHTMLCanvasElement(*node).NeedsUnbufferedInputEvents()) {
@@ -173,13 +173,13 @@ WebInputEventResult PointerEventManager::DispatchPointerEvent(
if (!check_for_listener || target->HasEventListeners(event_type)) {
UseCounter::Count(frame_, WebFeature::kPointerEventDispatch);
- if (event_type == EventTypeNames::pointerdown)
+ if (event_type == event_type_names::kPointerdown)
UseCounter::Count(frame_, WebFeature::kPointerEventDispatchPointerDown);
DCHECK(!dispatching_pointer_id_);
base::AutoReset<int> dispatch_holder(&dispatching_pointer_id_, pointer_id);
DispatchEventResult dispatch_result = target->DispatchEvent(*pointer_event);
- return EventHandlingUtil::ToWebInputEventResult(dispatch_result);
+ return event_handling_util::ToWebInputEventResult(dispatch_result);
}
return WebInputEventResult::kNotHandled;
}
@@ -202,7 +202,7 @@ void PointerEventManager::SendMouseAndPointerBoundaryEvents(
const WebPointerEvent web_pointer_event(WebInputEvent::kPointerMove,
mouse_event);
PointerEvent* dummy_pointer_event = pointer_event_factory_.Create(
- web_pointer_event, Vector<WebPointerEvent>(),
+ web_pointer_event, Vector<WebPointerEvent>(), Vector<WebPointerEvent>(),
frame_->GetDocument()->domWindow());
// TODO(crbug/545647): This state should reset with pointercancel too.
@@ -353,10 +353,10 @@ void PointerEventManager::AdjustTouchPointerEvent(
pointer_event.unique_touch_event_id, pointer_event.PositionInWidget());
}
-EventHandlingUtil::PointerEventTarget
+event_handling_util::PointerEventTarget
PointerEventManager::ComputePointerEventTarget(
const WebPointerEvent& web_pointer_event) {
- EventHandlingUtil::PointerEventTarget pointer_event_target;
+ event_handling_util::PointerEventTarget pointer_event_target;
int pointer_id = pointer_event_factory_.GetPointerEventId(web_pointer_event);
// Do the hit test either when the touch first starts or when the touch
@@ -408,7 +408,8 @@ PointerEventManager::ComputePointerEventTarget(
WebInputEventResult PointerEventManager::DispatchTouchPointerEvent(
const WebPointerEvent& web_pointer_event,
const Vector<WebPointerEvent>& coalesced_events,
- const EventHandlingUtil::PointerEventTarget& pointer_event_target) {
+ const Vector<WebPointerEvent>& predicted_events,
+ const event_handling_util::PointerEventTarget& pointer_event_target) {
DCHECK_NE(web_pointer_event.GetType(),
WebInputEvent::Type::kPointerCausedUaAction);
@@ -416,7 +417,7 @@ WebInputEventResult PointerEventManager::DispatchTouchPointerEvent(
if (pointer_event_target.target_node && pointer_event_target.target_frame &&
!non_hovering_pointers_canceled_) {
PointerEvent* pointer_event = pointer_event_factory_.Create(
- web_pointer_event, coalesced_events,
+ web_pointer_event, coalesced_events, predicted_events,
pointer_event_target.target_node
? pointer_event_target.target_node->GetDocument().domWindow()
: nullptr);
@@ -431,7 +432,7 @@ WebInputEventResult PointerEventManager::DispatchTouchPointerEvent(
// primary pointers.
// TODO(mustaq): What about other cases (e.g. GestureTwoFingerTap)?
if (result != WebInputEventResult::kNotHandled &&
- pointer_event->type() == EventTypeNames::pointerdown &&
+ pointer_event->type() == event_type_names::kPointerdown &&
pointer_event->isPrimary()) {
touch_ids_for_canceled_pointerdowns_.push_back(
web_pointer_event.unique_touch_event_id);
@@ -450,15 +451,15 @@ WebInputEventResult PointerEventManager::SendTouchPointerEvent(
ProcessCaptureAndPositionOfPointerEvent(pointer_event, target);
// Setting the implicit capture for touch
- if (pointer_event->type() == EventTypeNames::pointerdown)
+ if (pointer_event->type() == event_type_names::kPointerdown)
SetPointerCapture(pointer_event->pointerId(), target);
WebInputEventResult result = DispatchPointerEvent(
GetEffectiveTargetForPointerEvent(target, pointer_event->pointerId()),
pointer_event);
- if (pointer_event->type() == EventTypeNames::pointerup ||
- pointer_event->type() == EventTypeNames::pointercancel) {
+ if (pointer_event->type() == event_type_names::kPointerup ||
+ pointer_event->type() == event_type_names::kPointercancel) {
ReleasePointerCapture(pointer_event->pointerId());
// If the pointer is not hovering it implies that pointerup also means
@@ -484,7 +485,8 @@ WebInputEventResult PointerEventManager::FlushEvents() {
WebInputEventResult PointerEventManager::HandlePointerEvent(
const WebPointerEvent& event,
- const Vector<WebPointerEvent>& coalesced_events) {
+ const Vector<WebPointerEvent>& coalesced_events,
+ const Vector<WebPointerEvent>& predicted_events) {
if (event.GetType() == WebInputEvent::Type::kPointerRawMove) {
if (!RuntimeEnabledFeatures::PointerRawMoveEnabled() ||
!frame_->GetEventHandlerRegistry().HasEventHandlers(
@@ -508,8 +510,8 @@ WebInputEventResult PointerEventManager::HandlePointerEvent(
if (!target_frame)
return WebInputEventResult::kHandledSystem;
if (target_frame != frame_) {
- target_frame->GetEventHandler().HandlePointerEvent(event,
- coalesced_events);
+ target_frame->GetEventHandler().HandlePointerEvent(
+ event, coalesced_events, predicted_events);
return WebInputEventResult::kHandledSystem;
}
target = pointer_locked_element;
@@ -517,8 +519,9 @@ WebInputEventResult PointerEventManager::HandlePointerEvent(
target = ComputePointerEventTarget(event).target_node;
}
- PointerEvent* pointer_event = pointer_event_factory_.Create(
- event, coalesced_events, frame_->GetDocument()->domWindow());
+ PointerEvent* pointer_event =
+ pointer_event_factory_.Create(event, coalesced_events, predicted_events,
+ frame_->GetDocument()->domWindow());
DispatchPointerEvent(target, pointer_event);
return WebInputEventResult::kHandledSystem;
}
@@ -540,7 +543,7 @@ WebInputEventResult PointerEventManager::HandlePointerEvent(
WebPointerEvent pointer_event = event.WebPointerEventInRootFrame();
if (ShouldAdjustPointerEvent(event))
AdjustTouchPointerEvent(pointer_event);
- EventHandlingUtil::PointerEventTarget pointer_event_target =
+ event_handling_util::PointerEventTarget pointer_event_target =
ComputePointerEventTarget(pointer_event);
// Any finger lifting is a user gesture only when it wasn't associated with a
@@ -557,8 +560,8 @@ WebInputEventResult PointerEventManager::HandlePointerEvent(
LocalFrame::NotifyUserActivation(pointer_event_target.target_frame);
}
- WebInputEventResult result =
- DispatchTouchPointerEvent(event, coalesced_events, pointer_event_target);
+ WebInputEventResult result = DispatchTouchPointerEvent(
+ event, coalesced_events, predicted_events, pointer_event_target);
touch_event_manager_->HandleTouchPoint(event, coalesced_events,
pointer_event_target);
@@ -570,15 +573,16 @@ WebInputEventResult PointerEventManager::CreateAndDispatchPointerEvent(
Node* target,
const AtomicString& mouse_event_name,
const WebMouseEvent& mouse_event,
- const Vector<WebMouseEvent>& coalesced_events) {
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events) {
WebInputEvent::Type event_type;
// TODO(crbug.com/665924): The following ifs skip the mouseover/leave cases,
// we should fixed them when further merge the code path.
- if (mouse_event_name == EventTypeNames::mousemove)
+ if (mouse_event_name == event_type_names::kMousemove)
event_type = WebInputEvent::kPointerMove;
- else if (mouse_event_name == EventTypeNames::mousedown)
+ else if (mouse_event_name == event_type_names::kMousedown)
event_type = WebInputEvent::kPointerDown;
- else if (mouse_event_name == EventTypeNames::mouseup)
+ else if (mouse_event_name == event_type_names::kMouseup)
event_type = WebInputEvent::kPointerUp;
else
return WebInputEventResult::kNotHandled;
@@ -587,10 +591,13 @@ WebInputEventResult PointerEventManager::CreateAndDispatchPointerEvent(
Vector<WebPointerEvent> pointer_coalesced_events;
for (const WebMouseEvent& e : coalesced_events)
pointer_coalesced_events.push_back(WebPointerEvent(event_type, e));
+ Vector<WebPointerEvent> pointer_predicted_events;
+ for (const WebMouseEvent& e : predicted_events)
+ pointer_predicted_events.push_back(WebPointerEvent(event_type, e));
- PointerEvent* pointer_event =
- pointer_event_factory_.Create(web_pointer_event, pointer_coalesced_events,
- target->GetDocument().domWindow());
+ PointerEvent* pointer_event = pointer_event_factory_.Create(
+ web_pointer_event, pointer_coalesced_events, pointer_predicted_events,
+ target->GetDocument().domWindow());
return DispatchPointerEvent(target, pointer_event);
}
@@ -601,13 +608,20 @@ WebInputEventResult PointerEventManager::DirectDispatchMousePointerEvent(
const WebMouseEvent& event,
const AtomicString& mouse_event_type,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
const String& canvas_region_id) {
+ // Fetch the last_mouse_position for creating MouseEvent before
+ // pointer_event_factory updates it.
+ FloatPoint last_mouse_position =
+ pointer_event_factory_.GetLastPointerPosition(
+ PointerEventFactory::kMouseId, event);
WebInputEventResult result = CreateAndDispatchPointerEvent(
- target, mouse_event_type, event, coalesced_events);
+ target, mouse_event_type, event, coalesced_events, predicted_events);
- result = EventHandlingUtil::MergeEventResult(
+ result = event_handling_util::MergeEventResult(
result, mouse_event_manager_->DispatchMouseEvent(
- target, mouse_event_type, event, canvas_region_id, nullptr));
+ target, mouse_event_type, event, canvas_region_id,
+ &last_mouse_position, nullptr));
return result;
}
@@ -617,7 +631,8 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
const String& canvas_region_id,
const WebInputEvent::Type event_type,
const WebMouseEvent& mouse_event,
- const Vector<WebMouseEvent>& coalesced_events) {
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events) {
DCHECK(event_type == WebInputEvent::kPointerDown ||
event_type == WebInputEvent::kPointerMove ||
event_type == WebInputEvent::kPointerUp);
@@ -626,10 +641,19 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
Vector<WebPointerEvent> pointer_coalesced_events;
for (const WebMouseEvent& e : coalesced_events)
pointer_coalesced_events.push_back(WebPointerEvent(event_type, e));
+ Vector<WebPointerEvent> pointer_predicted_events;
+ for (const WebMouseEvent& e : predicted_events)
+ pointer_predicted_events.push_back(WebPointerEvent(event_type, e));
- PointerEvent* pointer_event =
- pointer_event_factory_.Create(web_pointer_event, pointer_coalesced_events,
- frame_->GetDocument()->domWindow());
+ // Fetch the last_mouse_position for creating MouseEvent before
+ // pointer_event_factory updates it.
+ FloatPoint last_mouse_position =
+ pointer_event_factory_.GetLastPointerPosition(
+ PointerEventFactory::kMouseId, mouse_event);
+
+ PointerEvent* pointer_event = pointer_event_factory_.Create(
+ web_pointer_event, pointer_coalesced_events, pointer_predicted_events,
+ frame_->GetDocument()->domWindow());
bool fake_event = (web_pointer_event.GetModifiers() &
WebInputEvent::Modifiers::kRelativeMotionEvent);
@@ -662,7 +686,7 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
if ((event_type == WebInputEvent::kPointerDown ||
event_type == WebInputEvent::kPointerUp) &&
- pointer_event->type() == EventTypeNames::pointermove &&
+ pointer_event->type() == event_type_names::kPointermove &&
RuntimeEnabledFeatures::PointerRawMoveEnabled() &&
frame_->GetEventHandlerRegistry().HasEventHandlers(
EventHandlerRegistry::kPointerRawMoveEvent)) {
@@ -676,7 +700,7 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
DispatchPointerEvent(effective_target, pointer_event);
if (result != WebInputEventResult::kNotHandled &&
- pointer_event->type() == EventTypeNames::pointerdown &&
+ pointer_event->type() == event_type_names::kPointerdown &&
pointer_event->isPrimary()) {
prevent_mouse_event_for_pointer_type_[ToPointerTypeIndex(
mouse_event.pointer_type)] = true;
@@ -688,29 +712,29 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
EventTarget* mouse_target = effective_target;
// Event path could be null if pointer event is not dispatched and
// that happens for example when pointer event feature is not enabled.
- if (!EventHandlingUtil::IsInDocument(mouse_target) &&
+ if (!event_handling_util::IsInDocument(mouse_target) &&
pointer_event->HasEventPath()) {
for (const auto& context :
pointer_event->GetEventPath().NodeEventContexts()) {
- if (EventHandlingUtil::IsInDocument(context.GetNode())) {
- mouse_target = context.GetNode();
+ if (event_handling_util::IsInDocument(&context.GetNode())) {
+ mouse_target = &context.GetNode();
break;
}
}
}
- result = EventHandlingUtil::MergeEventResult(
+ result = event_handling_util::MergeEventResult(
result,
mouse_event_manager_->DispatchMouseEvent(
mouse_target, MouseEventNameForPointerEventInputType(event_type),
- mouse_event, canvas_region_id, nullptr));
+ mouse_event, canvas_region_id, &last_mouse_position, nullptr));
}
- if (pointer_event->type() == EventTypeNames::pointerup ||
- pointer_event->type() == EventTypeNames::pointercancel) {
+ if (pointer_event->type() == event_type_names::kPointerup ||
+ pointer_event->type() == event_type_names::kPointercancel) {
ReleasePointerCapture(pointer_event->pointerId());
// Send got/lostpointercapture rightaway if necessary.
- if (pointer_event->type() == EventTypeNames::pointerup) {
+ if (pointer_event->type() == event_type_names::kPointerup) {
// If pointerup releases the capture we also send boundary events
// rightaway when the pointer that supports hover. The following function
// does nothing when there was no capture to begin with in the first
@@ -802,14 +826,15 @@ void PointerEventManager::ProcessPendingPointerCapture(
}
DispatchPointerEvent(
target, pointer_event_factory_.CreatePointerCaptureEvent(
- pointer_event, EventTypeNames::lostpointercapture));
+ pointer_event, event_type_names::kLostpointercapture));
}
if (pending_pointer_capture_target) {
SetNodeUnderPointer(pointer_event, pending_pointer_capture_target);
- DispatchPointerEvent(pending_pointer_capture_target,
- pointer_event_factory_.CreatePointerCaptureEvent(
- pointer_event, EventTypeNames::gotpointercapture));
+ DispatchPointerEvent(
+ pending_pointer_capture_target,
+ pointer_event_factory_.CreatePointerCaptureEvent(
+ pointer_event, event_type_names::kGotpointercapture));
pointer_capture_target_.Set(pointer_id, pending_pointer_capture_target);
} else {
pointer_capture_target_.erase(pointer_id);
@@ -820,7 +845,8 @@ void PointerEventManager::ProcessPendingPointerCaptureForPointerLock(
const WebMouseEvent& mouse_event) {
PointerEvent* pointer_event = pointer_event_factory_.Create(
WebPointerEvent(WebInputEvent::kPointerMove, mouse_event),
- Vector<WebPointerEvent>(), frame_->GetDocument()->domWindow());
+ Vector<WebPointerEvent>(), Vector<WebPointerEvent>(),
+ frame_->GetDocument()->domWindow());
ProcessPendingPointerCapture(pointer_event);
}
@@ -944,4 +970,8 @@ bool PointerEventManager::PrimaryPointerdownCanceled(
return false;
}
+void PointerEventManager::RemoveLastMousePosition() {
+ pointer_event_factory_.RemoveLastPosition(PointerEventFactory::kMouseId);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/input/pointer_event_manager.h b/chromium/third_party/blink/renderer/core/input/pointer_event_manager.h
index 9636ca58ec1..479d0189515 100644
--- a/chromium/third_party/blink/renderer/core/input/pointer_event_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/pointer_event_manager.h
@@ -36,7 +36,8 @@ class CORE_EXPORT PointerEventManager
// through this function.
WebInputEventResult HandlePointerEvent(
const WebPointerEvent&,
- const Vector<WebPointerEvent>& coalesced_events);
+ const Vector<WebPointerEvent>& coalesced_events,
+ const Vector<WebPointerEvent>& predicted_events);
// Sends the mouse pointer events and the boundary events
// that it may cause. It also sends the compat mouse events
@@ -47,7 +48,8 @@ class CORE_EXPORT PointerEventManager
const String& canvas_region_id,
const WebInputEvent::Type,
const WebMouseEvent&,
- const Vector<WebMouseEvent>& coalesced_events);
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events);
// Sends boundary events pointerout/leave/over/enter and
// mouseout/leave/over/enter to the corresponding targets.
@@ -64,13 +66,15 @@ class CORE_EXPORT PointerEventManager
const WebMouseEvent&,
const AtomicString& event_type,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
const String& canvas_node_id = String());
WebInputEventResult CreateAndDispatchPointerEvent(
Node* target,
const AtomicString& mouse_event_name,
const WebMouseEvent&,
- const Vector<WebMouseEvent>& coalesced_events);
+ const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events);
// Resets the internal state of this object.
void Clear();
@@ -103,6 +107,8 @@ class CORE_EXPORT PointerEventManager
void ProcessPendingPointerCaptureForPointerLock(const WebMouseEvent&);
+ void RemoveLastMousePosition();
+
// Sends any outstanding events. For example it notifies TouchEventManager
// to group any changes to touch since last FlushEvents and send the touch
// event out to js. Since after this function any outstanding event is sent,
@@ -163,13 +169,14 @@ class CORE_EXPORT PointerEventManager
void HandlePointerInterruption(const WebPointerEvent&);
// Returns PointerEventTarget for a WebTouchPoint, hit-testing as necessary.
- EventHandlingUtil::PointerEventTarget ComputePointerEventTarget(
+ event_handling_util::PointerEventTarget ComputePointerEventTarget(
const WebPointerEvent&);
WebInputEventResult DispatchTouchPointerEvent(
const WebPointerEvent&,
const Vector<WebPointerEvent>& coalesced_events,
- const EventHandlingUtil::PointerEventTarget&);
+ const Vector<WebPointerEvent>& predicted_events,
+ const event_handling_util::PointerEventTarget&);
// Returns whether the event is consumed or not.
WebInputEventResult SendTouchPointerEvent(EventTarget*,
diff --git a/chromium/third_party/blink/renderer/core/input/pointer_event_manager_test.cc b/chromium/third_party/blink/renderer/core/input/pointer_event_manager_test.cc
index b9e9945be85..99456b36254 100644
--- a/chromium/third_party/blink/renderer/core/input/pointer_event_manager_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/pointer_event_manager_test.cc
@@ -24,7 +24,7 @@ class CheckPointerEventListenerCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
+ void Invoke(ExecutionContext*, Event* event) override {
const String pointer_type = ((PointerEvent*)event)->pointerType();
if (pointer_type == "mouse")
mouse_event_received_count_++;
@@ -56,7 +56,7 @@ class PointerEventCoordinateListenerCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
+ void Invoke(ExecutionContext*, Event* event) override {
const PointerEvent* pointer_event = (PointerEvent*)event;
last_client_x_ = pointer_event->clientX();
last_client_y_ = pointer_event->clientY();
@@ -66,6 +66,8 @@ class PointerEventCoordinateListenerCallback final : public EventListener {
last_screen_y_ = pointer_event->screenY();
last_width_ = pointer_event->width();
last_height_ = pointer_event->height();
+ last_movement_x_ = pointer_event->movementX();
+ last_movement_y_ = pointer_event->movementY();
}
double last_client_x_ = 0;
@@ -76,6 +78,8 @@ class PointerEventCoordinateListenerCallback final : public EventListener {
double last_screen_y_ = 0;
double last_width_ = 0;
double last_height_ = 0;
+ double last_movement_x_ = 0;
+ double last_movement_y_ = 0;
private:
PointerEventCoordinateListenerCallback()
@@ -126,18 +130,18 @@ TEST_F(PointerEventManagerTest, PointerCancelsOfAllTypes) {
"</body>");
CheckPointerEventListenerCallback* callback =
CheckPointerEventListenerCallback::Create();
- GetDocument().body()->addEventListener(EventTypeNames::pointercancel,
+ GetDocument().body()->addEventListener(event_type_names::kPointercancel,
callback);
WebView().HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerDown,
WebPointerProperties::PointerType::kTouch),
- std::vector<WebPointerEvent>()));
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
WebView().HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerDown,
WebPointerProperties::PointerType::kPen),
- std::vector<WebPointerEvent>()));
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
GetEventHandler().HandleMousePressEvent(
CreateTestMouseEvent(WebInputEvent::kMouseDown, WebFloatPoint(100, 100)));
@@ -149,7 +153,7 @@ TEST_F(PointerEventManagerTest, PointerCancelsOfAllTypes) {
WebView().HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerCausedUaAction,
WebPointerProperties::PointerType::kPen),
- std::vector<WebPointerEvent>()));
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
ASSERT_EQ(callback->mouseEventCount(), 0);
ASSERT_EQ(callback->touchEventCount(), 1);
ASSERT_EQ(callback->penEventCount(), 1);
@@ -157,14 +161,14 @@ TEST_F(PointerEventManagerTest, PointerCancelsOfAllTypes) {
WebView().HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerCausedUaAction,
WebPointerProperties::PointerType::kTouch),
- std::vector<WebPointerEvent>()));
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
ASSERT_EQ(callback->mouseEventCount(), 0);
ASSERT_EQ(callback->touchEventCount(), 1);
ASSERT_EQ(callback->penEventCount(), 1);
GetEventHandler().HandleMouseMoveEvent(
CreateTestMouseEvent(WebInputEvent::kMouseMove, WebFloatPoint(200, 200)),
- Vector<WebMouseEvent>());
+ Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
ASSERT_EQ(callback->mouseEventCount(), 1);
ASSERT_EQ(callback->touchEventCount(), 1);
@@ -181,14 +185,15 @@ TEST_F(PointerEventManagerTest, PointerEventCoordinates) {
WebView().SetPageScaleFactor(2);
PointerEventCoordinateListenerCallback* callback =
PointerEventCoordinateListenerCallback::Create();
- GetDocument().body()->addEventListener(EventTypeNames::pointerdown, callback);
+ GetDocument().body()->addEventListener(event_type_names::kPointerdown,
+ callback);
WebView().HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerDown,
WebPointerProperties::PointerType::kTouch,
WebFloatPoint(150, 200), WebFloatPoint(100, 50),
10, 10, 16, 24),
- std::vector<WebPointerEvent>()));
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
ASSERT_EQ(callback->last_client_x_, 75);
ASSERT_EQ(callback->last_client_y_, 100);
@@ -198,6 +203,75 @@ TEST_F(PointerEventManagerTest, PointerEventCoordinates) {
ASSERT_EQ(callback->last_screen_y_, 50);
ASSERT_EQ(callback->last_width_, 8);
ASSERT_EQ(callback->last_height_, 12);
+ ASSERT_EQ(callback->last_movement_x_, 10);
+ ASSERT_EQ(callback->last_movement_y_, 10);
+}
+
+TEST_F(PointerEventManagerTest, PointerEventMovements) {
+ WebView().Resize(WebSize(400, 400));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(
+ "<body style='padding: 0px; width: 400px; height: 400px;'>"
+ "</body>");
+ PointerEventCoordinateListenerCallback* callback =
+ PointerEventCoordinateListenerCallback::Create();
+ GetDocument().body()->addEventListener(event_type_names::kPointermove,
+ callback);
+
+ // Turn on the flag for test.
+ RuntimeEnabledFeatures::SetMovementXYInBlinkEnabled(true);
+
+ WebView().HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210), WebFloatPoint(100, 50),
+ 10, 10),
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ // The first pointermove event has movement_x/y 0.
+ ASSERT_EQ(callback->last_screen_x_, 100);
+ ASSERT_EQ(callback->last_screen_y_, 50);
+ ASSERT_EQ(callback->last_movement_x_, 0);
+ ASSERT_EQ(callback->last_movement_y_, 0);
+
+ WebView().HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 200), WebFloatPoint(132, 29),
+ 10, 10),
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ // pointermove event movement = event.screenX/Y - last_event.screenX/Y.
+ ASSERT_EQ(callback->last_screen_x_, 132);
+ ASSERT_EQ(callback->last_screen_y_, 29);
+ ASSERT_EQ(callback->last_movement_x_, 32);
+ ASSERT_EQ(callback->last_movement_y_, -21);
+
+ WebView().HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210),
+ WebFloatPoint(113.8, 32.7), 10, 10),
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ // fractional screen coordinates result in fractional movement.
+ ASSERT_FLOAT_EQ(callback->last_screen_x_, 113.8);
+ ASSERT_FLOAT_EQ(callback->last_screen_y_, 32.7);
+ // TODO(eirage): These should be float value once mouse_event.idl change.
+ ASSERT_FLOAT_EQ(callback->last_movement_x_, -18);
+ ASSERT_FLOAT_EQ(callback->last_movement_y_, 3);
+
+ // When flag is off, movementX/Y follows the value in WebPointerProperties.
+ RuntimeEnabledFeatures::SetMovementXYInBlinkEnabled(false);
+
+ WebView().HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210), WebFloatPoint(100, 16.25),
+ 1024, -8765),
+ std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ ASSERT_EQ(callback->last_screen_x_, 100);
+ ASSERT_EQ(callback->last_screen_y_, 16.25);
+ ASSERT_EQ(callback->last_movement_x_, 1024);
+ ASSERT_EQ(callback->last_movement_y_, -8765);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/input/scroll_manager.cc b/chromium/third_party/blink/renderer/core/input/scroll_manager.cc
index 8b8d2a7faf1..68e636a737a 100644
--- a/chromium/third_party/blink/renderer/core/input/scroll_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/scroll_manager.cc
@@ -70,8 +70,7 @@ ScrollableArea* ScrollableAreaForSnapping(LayoutBox* layout_box) {
} // namespace
ScrollManager::ScrollManager(LocalFrame& frame) : frame_(frame) {
- if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled())
- snap_fling_controller_ = std::make_unique<cc::SnapFlingController>(this);
+ snap_fling_controller_ = std::make_unique<cc::SnapFlingController>(this);
Clear();
}
@@ -87,14 +86,14 @@ void ScrollManager::Clear() {
void ScrollManager::Trace(blink::Visitor* visitor) {
visitor->Trace(frame_);
visitor->Trace(scroll_gesture_handling_node_);
- visitor->Trace(previous_gesture_scrolled_element_);
+ visitor->Trace(previous_gesture_scrolled_node_);
visitor->Trace(scrollbar_handling_scroll_gesture_);
visitor->Trace(resize_scrollable_area_);
}
void ScrollManager::ClearGestureScrollState() {
scroll_gesture_handling_node_ = nullptr;
- previous_gesture_scrolled_element_ = nullptr;
+ previous_gesture_scrolled_node_ = nullptr;
delta_consumed_for_scroll_sequence_ = false;
did_scroll_x_for_scroll_gesture_ = false;
did_scroll_y_for_scroll_gesture_ = false;
@@ -128,9 +127,8 @@ AutoscrollController* ScrollManager::GetAutoscrollController() const {
return nullptr;
}
-static bool CanPropagate(const ScrollState& scroll_state,
- const Element& element) {
- ScrollableArea* scrollable_area = element.GetLayoutBox()->GetScrollableArea();
+static bool CanPropagate(const ScrollState& scroll_state, const Node& node) {
+ ScrollableArea* scrollable_area = node.GetLayoutBox()->GetScrollableArea();
if (!scrollable_area)
return true;
@@ -139,10 +137,10 @@ static bool CanPropagate(const ScrollState& scroll_state,
return true;
return (scroll_state.deltaXHint() == 0 ||
- element.GetComputedStyle()->OverscrollBehaviorX() ==
+ node.GetComputedStyle()->OverscrollBehaviorX() ==
EOverscrollBehavior::kAuto) &&
(scroll_state.deltaYHint() == 0 ||
- element.GetComputedStyle()->OverscrollBehaviorY() ==
+ node.GetComputedStyle()->OverscrollBehaviorY() ==
EOverscrollBehavior::kAuto);
}
@@ -154,38 +152,27 @@ void ScrollManager::RecomputeScrollChain(const Node& start_node,
DCHECK(start_node.GetLayoutObject());
LayoutBox* cur_box = start_node.GetLayoutObject()->EnclosingBox();
- Element* document_element = frame_->GetDocument()->documentElement();
// Scrolling propagates along the containing block chain and ends at the
- // RootScroller element. The RootScroller element will have a custom
- // applyScroll callback that scrolls the frame or element.
+ // RootScroller node. The RootScroller node will have a custom applyScroll
+ // callback that performs scrolling as well as associated "root" actions like
+ // browser control movement and overscroll glow.
while (cur_box) {
Node* cur_node = cur_box->GetNode();
- Element* cur_element = nullptr;
-
- // FIXME: this should reject more elements, as part of crbug.com/410974.
- if (cur_node && cur_node->IsElementNode()) {
- cur_element = ToElement(cur_node);
- } else if (cur_node && cur_node->IsDocumentNode()) {
- // In normal circumastances, the documentElement will be the root
- // scroller but the documentElement itself isn't a containing block,
- // that'll be the document node rather than the element.
- cur_element = document_element;
- }
- if (cur_element) {
- if (CanScroll(scroll_state, *cur_element))
- scroll_chain.push_front(DOMNodeIds::IdForNode(cur_element));
- if (IsViewportScrollingElement(*cur_element) ||
- cur_element == document_element)
+ if (cur_node) {
+ if (CanScroll(scroll_state, *cur_node))
+ scroll_chain.push_front(DOMNodeIds::IdForNode(cur_node));
+
+ if (cur_node->IsEffectiveRootScroller())
break;
- if (!CanPropagate(scroll_state, *cur_element)) {
+ if (!CanPropagate(scroll_state, *cur_node)) {
// We should add the first node with non-auto overscroll-behavior to
// the scroll chain regardlessly, as it's the only node we can latch to.
if (scroll_chain.empty() ||
- scroll_chain.front() != DOMNodeIds::IdForNode(cur_element)) {
- scroll_chain.push_front(DOMNodeIds::IdForNode(cur_element));
+ scroll_chain.front() != DOMNodeIds::IdForNode(cur_node)) {
+ scroll_chain.push_front(DOMNodeIds::IdForNode(cur_node));
}
break;
}
@@ -196,25 +183,18 @@ void ScrollManager::RecomputeScrollChain(const Node& start_node,
}
bool ScrollManager::CanScroll(const ScrollState& scroll_state,
- const Element& current_element) {
- ScrollableArea* scrollable_area = nullptr;
- if (IsViewportScrollingElement(current_element) ||
- current_element == *(frame_->GetDocument()->documentElement())) {
- if (!current_element.GetLayoutObject())
- return false;
-
- if (frame_->IsMainFrame())
- return true;
+ const Node& current_node) {
+ if (!current_node.GetLayoutBox())
+ return false;
- // For subframes, the viewport is added to the scroll chain only if it can
- // actually consume some delta hints. The main frame always gets added
- // since it produces overscroll effects.
- scrollable_area =
- frame_->View() ? frame_->View()->GetScrollableArea() : nullptr;
- }
+ // We need to always add the global root scroller even if it isn't scrollable
+ // since we can always pinch-zoom and scroll as well as for overscroll
+ // effects.
+ if (current_node.GetLayoutBox()->IsGlobalRootScroller())
+ return true;
- if (!scrollable_area && current_element.GetLayoutBox())
- scrollable_area = current_element.GetLayoutBox()->GetScrollableArea();
+ ScrollableArea* scrollable_area =
+ current_node.GetLayoutBox()->GetScrollableArea();
if (!scrollable_area)
return false;
@@ -282,20 +262,27 @@ bool ScrollManager::LogicalScroll(ScrollDirection direction,
ScrollableArea* scrollable_area = nullptr;
// The global root scroller must be scrolled by the RootFrameViewport.
- if (RootScrollerUtil::IsGlobal(*box)) {
+ if (box->IsGlobalRootScroller()) {
LocalFrame& main_frame = frame_->LocalFrameRoot();
// The local root must be the main frame if we have the global root
// scroller since it can't yet be set on OOPIFs.
DCHECK(main_frame.IsMainFrame());
scrollable_area = main_frame.View()->GetScrollableArea();
- } else if (node == document.documentElement()) {
- scrollable_area = document.GetLayoutView()->GetScrollableArea();
} else {
scrollable_area = box->GetScrollableArea();
}
DCHECK(scrollable_area);
+
+ SnapCoordinator* snap_coordinator =
+ frame_->GetDocument()->GetSnapCoordinator();
+ ScrollOffset delta = ToScrollDelta(physical_direction, 1);
+ delta.Scale(scrollable_area->ScrollStep(granularity, kHorizontalScrollbar),
+ scrollable_area->ScrollStep(granularity, kVerticalScrollbar));
+ if (snap_coordinator->SnapForDirection(*box, delta))
+ return true;
+
ScrollResult result = scrollable_area->UserScroll(
granularity, ToScrollDelta(physical_direction, 1));
@@ -419,7 +406,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollBegin(
scroll_gesture_handling_node_->ParentOrShadowHostNode();
if (!scroll_gesture_handling_node_)
- scroll_gesture_handling_node_ = frame_->GetDocument()->documentElement();
+ scroll_gesture_handling_node_ = frame_->GetDocument();
if (!scroll_gesture_handling_node_ ||
!scroll_gesture_handling_node_->GetLayoutObject()) {
@@ -482,7 +469,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollUpdate(
if (!node || !node->GetLayoutObject()) {
TRACE_EVENT_INSTANT0("input", "Lost scroll_gesture_handling_node",
TRACE_EVENT_SCOPE_THREAD);
- if (previous_gesture_scrolled_element_) {
+ if (previous_gesture_scrolled_node_) {
// When the scroll_gesture_handling_node_ gets deleted in the middle of
// scrolling call HandleGestureScrollEvent to start scrolling a new node
// if possible.
@@ -557,18 +544,17 @@ WebInputEventResult ScrollManager::HandleGestureScrollUpdate(
scroll_state_data->delta_consumed_for_scroll_sequence =
delta_consumed_for_scroll_sequence_;
ScrollState* scroll_state = ScrollState::Create(std::move(scroll_state_data));
- if (previous_gesture_scrolled_element_) {
+ if (previous_gesture_scrolled_node_) {
// The ScrollState needs to know what the current
// native scrolling element is, so that for an
// inertial scroll that shouldn't propagate, only the
// currently scrolling element responds.
- scroll_state->SetCurrentNativeScrollingElement(
- previous_gesture_scrolled_element_);
+ scroll_state->SetCurrentNativeScrollingNode(
+ previous_gesture_scrolled_node_);
}
CustomizedScroll(*scroll_state);
- previous_gesture_scrolled_element_ =
- scroll_state->CurrentNativeScrollingElement();
+ previous_gesture_scrolled_node_ = scroll_state->CurrentNativeScrollingNode();
delta_consumed_for_scroll_sequence_ =
scroll_state->DeltaConsumedForScrollSequence();
@@ -578,9 +564,11 @@ WebInputEventResult ScrollManager::HandleGestureScrollUpdate(
did_scroll_x_for_scroll_gesture_ |= did_scroll_x;
did_scroll_y_for_scroll_gesture_ |= did_scroll_y;
- if ((!previous_gesture_scrolled_element_ ||
- !IsViewportScrollingElement(*previous_gesture_scrolled_element_)) &&
- GetPage())
+ // TODO(bokan): This looks like it resets overscroll if any *effective* root
+ // scroller is scrolled. This should probably be if the *global* root
+ // scroller is scrolled.
+ if (!previous_gesture_scrolled_node_ ||
+ !previous_gesture_scrolled_node_->IsEffectiveRootScroller())
GetPage()->GetOverscrollController().ResetAccumulated(did_scroll_x,
did_scroll_y);
@@ -619,20 +607,19 @@ WebInputEventResult ScrollManager::HandleGestureScrollEnd(
}
ClearGestureScrollState();
+ if (RuntimeEnabledFeatures::NoHoverDuringScrollEnabled())
+ frame_->GetEventHandler().RecomputeMouseHoverState();
return WebInputEventResult::kNotHandled;
}
LayoutBox* ScrollManager::LayoutBoxForSnapping() const {
- if (!previous_gesture_scrolled_element_)
+ if (!previous_gesture_scrolled_node_)
return nullptr;
- Element* document_element = frame_->GetDocument()->documentElement();
- return previous_gesture_scrolled_element_ == document_element
- ? frame_->GetDocument()->GetLayoutView()
- : previous_gesture_scrolled_element_->GetLayoutBox();
+ return previous_gesture_scrolled_node_->GetLayoutBox();
}
void ScrollManager::SnapAtGestureScrollEnd() {
- if (!previous_gesture_scrolled_element_ ||
+ if (!previous_gesture_scrolled_node_ ||
(!did_scroll_x_for_scroll_gesture_ && !did_scroll_y_for_scroll_gesture_))
return;
SnapCoordinator* snap_coordinator =
@@ -641,24 +628,34 @@ void ScrollManager::SnapAtGestureScrollEnd() {
if (!snap_coordinator || !layout_box)
return;
- snap_coordinator->PerformSnapping(*layout_box,
- did_scroll_x_for_scroll_gesture_,
- did_scroll_y_for_scroll_gesture_);
+ snap_coordinator->SnapForEndPosition(*layout_box,
+ did_scroll_x_for_scroll_gesture_,
+ did_scroll_y_for_scroll_gesture_);
}
-bool ScrollManager::GetSnapFlingInfo(const gfx::Vector2dF& natural_displacement,
- gfx::Vector2dF* out_initial_offset,
- gfx::Vector2dF* out_target_offset) const {
- if (!previous_gesture_scrolled_element_)
- return false;
-
+bool ScrollManager::GetSnapFlingInfo(
+ const gfx::Vector2dF& natural_displacement,
+ gfx::Vector2dF* out_initial_position,
+ gfx::Vector2dF* out_target_position) const {
SnapCoordinator* snap_coordinator =
frame_->GetDocument()->GetSnapCoordinator();
LayoutBox* layout_box = LayoutBoxForSnapping();
- if (!snap_coordinator || !layout_box || !layout_box->GetScrollableArea())
+ ScrollableArea* scrollable_area = ScrollableAreaForSnapping(layout_box);
+ if (!snap_coordinator || !layout_box || !scrollable_area)
+ return false;
+
+ FloatPoint current_position = scrollable_area->ScrollPosition();
+ *out_initial_position = gfx::Vector2dF(current_position);
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndAndDirection(
+ gfx::ScrollOffset(*out_initial_position),
+ gfx::ScrollOffset(natural_displacement));
+ base::Optional<FloatPoint> snap_end =
+ snap_coordinator->GetSnapPosition(*layout_box, *strategy);
+ if (!snap_end.has_value())
return false;
- return snap_coordinator->GetSnapFlingInfo(
- *layout_box, natural_displacement, out_initial_offset, out_target_offset);
+ *out_target_position = gfx::Vector2dF(snap_end.value());
+ return true;
}
gfx::Vector2dF ScrollManager::ScrollByForSnapFling(
@@ -681,8 +678,7 @@ gfx::Vector2dF ScrollManager::ScrollByForSnapFling(
scroll_state_data->delta_consumed_for_scroll_sequence =
delta_consumed_for_scroll_sequence_;
ScrollState* scroll_state = ScrollState::Create(std::move(scroll_state_data));
- scroll_state->SetCurrentNativeScrollingElement(
- previous_gesture_scrolled_element_);
+ scroll_state->SetCurrentNativeScrollingNode(previous_gesture_scrolled_node_);
CustomizedScroll(*scroll_state);
FloatPoint end_position = scrollable_area->ScrollPosition();
@@ -743,16 +739,6 @@ WebInputEventResult ScrollManager::PassScrollGestureEvent(
.HandleGestureScrollEvent(gesture_event);
}
-bool ScrollManager::IsViewportScrollingElement(const Element& element) const {
- // The root scroller is the one Element on the page designated to perform
- // "viewport actions" like browser controls movement and overscroll glow.
- if (!frame_->GetDocument())
- return false;
-
- return frame_->GetDocument()->GetRootScrollerController().ScrollsViewport(
- element);
-}
-
WebInputEventResult ScrollManager::HandleGestureScrollEvent(
const WebGestureEvent& gesture_event) {
if (!frame_->View())
@@ -788,7 +774,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollEvent(
last_gesture_scroll_over_embedded_content_view_ =
result.IsOverEmbeddedContentView();
scroll_gesture_handling_node_ = event_target;
- previous_gesture_scrolled_element_ = nullptr;
+ previous_gesture_scrolled_node_ = nullptr;
delta_consumed_for_scroll_sequence_ = false;
did_scroll_x_for_scroll_gesture_ = false;
did_scroll_y_for_scroll_gesture_ = false;
@@ -820,7 +806,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollEvent(
if (gesture_dom_event_result != DispatchEventResult::kNotCanceled) {
DCHECK(gesture_dom_event_result !=
DispatchEventResult::kCanceledByEventHandler);
- return EventHandlingUtil::ToWebInputEventResult(
+ return event_handling_util::ToWebInputEventResult(
gesture_dom_event_result);
}
}
@@ -954,21 +940,21 @@ WebGestureEvent ScrollManager::SynthesizeGestureScrollBegin(
void ScrollManager::NotifyScrollPhaseBeginForCustomizedScroll(
const ScrollState& scroll_state) {
- ScrollCustomization::ScrollDirection direction =
- ScrollCustomization::GetScrollDirectionFromDeltas(
+ scroll_customization::ScrollDirection direction =
+ scroll_customization::GetScrollDirectionFromDeltas(
scroll_state.deltaXHint(), scroll_state.deltaYHint());
for (auto id : current_scroll_chain_) {
Node* node = DOMNodeIds::NodeForId(id);
- if (node && node->IsElementNode())
- ToElement(node)->WillBeginCustomizedScrollPhase(direction);
+ if (node)
+ node->WillBeginCustomizedScrollPhase(direction);
}
}
void ScrollManager::NotifyScrollPhaseEndForCustomizedScroll() {
for (auto id : current_scroll_chain_) {
Node* node = DOMNodeIds::NodeForId(id);
- if (node && node->IsElementNode())
- ToElement(node)->DidEndCustomizedScrollPhase();
+ if (node)
+ node->DidEndCustomizedScrollPhase();
}
}
diff --git a/chromium/third_party/blink/renderer/core/input/scroll_manager.h b/chromium/third_party/blink/renderer/core/input/scroll_manager.h
index 834dfee1022..c76f8eb4a76 100644
--- a/chromium/third_party/blink/renderer/core/input/scroll_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/scroll_manager.h
@@ -96,8 +96,8 @@ class CORE_EXPORT ScrollManager
// SnapFlingClient implementation.
bool GetSnapFlingInfo(const gfx::Vector2dF& natural_displacement,
- gfx::Vector2dF* out_initial_offset,
- gfx::Vector2dF* out_target_offset) const override;
+ gfx::Vector2dF* out_initial_position,
+ gfx::Vector2dF* out_target_position) const override;
gfx::Vector2dF ScrollByForSnapFling(const gfx::Vector2dF& delta) override;
void ScrollEndForSnapFling() override;
void RequestAnimationForSnapFling() override;
@@ -117,14 +117,12 @@ class CORE_EXPORT ScrollManager
Page* GetPage() const;
- bool IsViewportScrollingElement(const Element&) const;
-
bool HandleScrollGestureOnResizer(Node*, const WebGestureEvent&);
void RecomputeScrollChain(const Node& start_node,
const ScrollState&,
std::deque<DOMNodeId>& scroll_chain);
- bool CanScroll(const ScrollState&, const Element& current_element);
+ bool CanScroll(const ScrollState&, const Node& current_node);
// scroller_size is set only when scrolling non root scroller.
void ComputeScrollRelatedMetrics(
@@ -153,11 +151,11 @@ class CORE_EXPORT ScrollManager
bool last_gesture_scroll_over_embedded_content_view_;
- // The most recent element to scroll natively during this scroll
+ // The most recent Node to scroll natively during this scroll
// sequence. Null if no native element has scrolled this scroll
// sequence, or if the most recent element to scroll used scroll
// customization.
- Member<Element> previous_gesture_scrolled_element_;
+ Member<Node> previous_gesture_scrolled_node_;
// True iff some of the delta has been consumed for the current
// scroll sequence in this frame, or any child frames. Only used
diff --git a/chromium/third_party/blink/renderer/core/input/scroll_snap_test.cc b/chromium/third_party/blink/renderer/core/input/scroll_snap_test.cc
index ab29a7e495f..4ad3129285f 100644
--- a/chromium/third_party/blink/renderer/core/input/scroll_snap_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/scroll_snap_test.cc
@@ -115,7 +115,7 @@ void ScrollSnapTest::ScrollUpdate(double x,
event.data.scroll_update.delta_y = delta_y;
if (is_in_inertial_phase) {
event.data.scroll_update.inertial_phase = WebGestureEvent::kMomentumPhase;
- event.SetTimeStamp(base::TimeTicks());
+ event.SetTimeStamp(Compositor().LastFrameTime());
}
event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleGestureScrollEvent(event);
@@ -190,9 +190,8 @@ TEST_F(ScrollSnapTest, AnimateFlingToArriveAtSnapPoint) {
// Fling with an inertial GSU.
ScrollUpdate(95, 100, -5, 0, true);
ScrollEnd(90, 100);
- Compositor().BeginFrame();
// Animate halfway through the fling.
- Compositor().BeginFrame(0.2);
+ Compositor().BeginFrame(0.25);
ASSERT_GT(scroller->scrollLeft(), 150);
ASSERT_LT(scroller->scrollLeft(), 180);
ASSERT_EQ(scroller->scrollTop(), 200);
diff --git a/chromium/third_party/blink/renderer/core/input/touch.cc b/chromium/third_party/blink/renderer/core/input/touch.cc
index 3cc4da79099..717090b8554 100644
--- a/chromium/third_party/blink/renderer/core/input/touch.cc
+++ b/chromium/third_party/blink/renderer/core/input/touch.cc
@@ -99,22 +99,22 @@ Touch::Touch(EventTarget* target,
region_(region),
absolute_location_(absolute_location) {}
-Touch::Touch(LocalFrame* frame, const TouchInit& initializer)
- : target_(initializer.target()),
- identifier_(initializer.identifier()),
- client_pos_(FloatPoint(initializer.clientX(), initializer.clientY())),
- screen_pos_(FloatPoint(initializer.screenX(), initializer.screenY())),
- page_pos_(FloatPoint(initializer.pageX(), initializer.pageY())),
- radius_(FloatSize(initializer.radiusX(), initializer.radiusY())),
- rotation_angle_(initializer.rotationAngle()),
- force_(initializer.force()),
- region_(initializer.region()),
+Touch::Touch(LocalFrame* frame, const TouchInit* initializer)
+ : target_(initializer->target()),
+ identifier_(initializer->identifier()),
+ client_pos_(FloatPoint(initializer->clientX(), initializer->clientY())),
+ screen_pos_(FloatPoint(initializer->screenX(), initializer->screenY())),
+ page_pos_(FloatPoint(initializer->pageX(), initializer->pageY())),
+ radius_(FloatSize(initializer->radiusX(), initializer->radiusY())),
+ rotation_angle_(initializer->rotationAngle()),
+ force_(initializer->force()),
+ region_(initializer->region()),
absolute_location_(PageToAbsolute(frame, page_pos_)) {}
Touch* Touch::CloneWithNewTarget(EventTarget* event_target) const {
- return new Touch(event_target, identifier_, client_pos_, screen_pos_,
- page_pos_, radius_, rotation_angle_, force_, region_,
- absolute_location_);
+ return MakeGarbageCollected<Touch>(
+ event_target, identifier_, client_pos_, screen_pos_, page_pos_, radius_,
+ rotation_angle_, force_, region_, absolute_location_);
}
void Touch::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/input/touch.h b/chromium/third_party/blink/renderer/core/input/touch.h
index 50344780247..d0301b926d3 100644
--- a/chromium/third_party/blink/renderer/core/input/touch.h
+++ b/chromium/third_party/blink/renderer/core/input/touch.h
@@ -53,14 +53,38 @@ class CORE_EXPORT Touch final : public ScriptWrappable {
float rotation_angle,
float force,
String region) {
- return new Touch(frame, target, identifier, screen_pos, page_pos, radius,
- rotation_angle, force, region);
+ return MakeGarbageCollected<Touch>(frame, target, identifier, screen_pos,
+ page_pos, radius, rotation_angle, force,
+ region);
}
- static Touch* Create(const Document& document, const TouchInit& initializer) {
- return new Touch(document.GetFrame(), initializer);
+ static Touch* Create(const Document& document, const TouchInit* initializer) {
+ return MakeGarbageCollected<Touch>(document.GetFrame(), initializer);
}
+ Touch(LocalFrame*,
+ EventTarget*,
+ int identifier,
+ const FloatPoint& screen_pos,
+ const FloatPoint& page_pos,
+ const FloatSize& radius,
+ float rotation_angle,
+ float force,
+ String region);
+
+ Touch(EventTarget*,
+ int identifier,
+ const FloatPoint& client_pos,
+ const FloatPoint& screen_pos,
+ const FloatPoint& page_pos,
+ const FloatSize& radius,
+ float rotation_angle,
+ float force,
+ String region,
+ LayoutPoint absolute_location);
+
+ Touch(LocalFrame*, const TouchInit*);
+
// DOM Touch implementation
EventTarget* target() const { return target_.Get(); }
int identifier() const { return identifier_; }
@@ -84,29 +108,6 @@ class CORE_EXPORT Touch final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- Touch(LocalFrame*,
- EventTarget*,
- int identifier,
- const FloatPoint& screen_pos,
- const FloatPoint& page_pos,
- const FloatSize& radius,
- float rotation_angle,
- float force,
- String region);
-
- Touch(EventTarget*,
- int identifier,
- const FloatPoint& client_pos,
- const FloatPoint& screen_pos,
- const FloatPoint& page_pos,
- const FloatSize& radius,
- float rotation_angle,
- float force,
- String region,
- LayoutPoint absolute_location);
-
- Touch(LocalFrame*, const TouchInit&);
-
Member<EventTarget> target_;
int identifier_;
// Position relative to the viewport in CSS px.
diff --git a/chromium/third_party/blink/renderer/core/input/touch_action_test.cc b/chromium/third_party/blink/renderer/core/input/touch_action_test.cc
index 632763a1d21..4e3e1f4d0cd 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_action_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/touch_action_test.cc
@@ -64,7 +64,7 @@ using blink::test::RunPendingTasks;
namespace blink {
class TouchActionTrackingWebWidgetClient
- : public FrameTestHelpers::TestWebWidgetClient {
+ : public frame_test_helpers::TestWebWidgetClient {
public:
TouchActionTrackingWebWidgetClient()
: action_set_count_(0), action_(TouchAction::kTouchActionAuto) {}
@@ -93,13 +93,13 @@ class TouchActionTrackingWebWidgetClient
class TouchActionTest : public testing::Test {
public:
TouchActionTest() : base_url_("http://www.test.com/") {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
"touch-action-tests.css", "text/css");
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
"touch-action-tests.js", "text/javascript");
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
"white-1x1.png", "image/png");
}
@@ -121,7 +121,7 @@ class TouchActionTest : public testing::Test {
TouchActionTrackingWebWidgetClient&);
std::string base_url_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
void TouchActionTest::RunTouchActionTest(std::string file) {
@@ -197,9 +197,9 @@ void TouchActionTest::RunIFrameTest(std::string file) {
WebViewImpl* TouchActionTest::SetupTest(
std::string file,
TouchActionTrackingWebWidgetClient& client) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(WebString::FromUTF8(base_url_),
- test::CoreTestDataPath(),
- WebString::FromUTF8(file));
+ url_test_helpers::RegisterMockedURLLoadFromBase(
+ WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
+ WebString::FromUTF8(file));
// Note that JavaScript must be enabled for shadow DOM tests.
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + file, nullptr, nullptr, &client);
@@ -387,8 +387,8 @@ void TouchActionTest::SendTouchEvent(WebView* web_view,
if (type == WebInputEvent::kPointerCancel)
event.dispatch_type = WebInputEvent::kEventNonBlocking;
- web_view->HandleInputEvent(WebCoalescedInputEvent(event));
- web_view->DispatchBufferedTouchEvents();
+ web_view->MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(event));
+ web_view->MainFrameWidget()->DispatchBufferedTouchEvents();
RunPendingTasks();
}
diff --git a/chromium/third_party/blink/renderer/core/input/touch_action_util.cc b/chromium/third_party/blink/renderer/core/input/touch_action_util.cc
index 9e5b508219a..7aea46b6d69 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_action_util.cc
+++ b/chromium/third_party/blink/renderer/core/input/touch_action_util.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
namespace blink {
-namespace TouchActionUtil {
+namespace touch_action_util {
TouchAction ComputeEffectiveTouchAction(const Node& node) {
if (node.GetComputedStyle())
@@ -20,5 +20,5 @@ TouchAction ComputeEffectiveTouchAction(const Node& node) {
return TouchAction::kTouchActionAuto;
}
-} // namespace TouchActionUtil
+} // namespace touch_action_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/input/touch_action_util.h b/chromium/third_party/blink/renderer/core/input/touch_action_util.h
index 8b9ed5b57e8..930d6cb708d 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_action_util.h
+++ b/chromium/third_party/blink/renderer/core/input/touch_action_util.h
@@ -12,9 +12,9 @@ namespace blink {
class Node;
-namespace TouchActionUtil {
+namespace touch_action_util {
CORE_EXPORT TouchAction ComputeEffectiveTouchAction(const Node&);
-} // namespace TouchActionUtil
+} // namespace touch_action_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/input/touch_event_manager.cc b/chromium/third_party/blink/renderer/core/input/touch_event_manager.cc
index 7448ec43283..b066894903a 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_event_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/touch_event_manager.cc
@@ -66,13 +66,13 @@ const AtomicString& TouchEventNameForPointerEventType(
WebInputEvent::Type type) {
switch (type) {
case WebInputEvent::kPointerUp:
- return EventTypeNames::touchend;
+ return event_type_names::kTouchend;
case WebInputEvent::kPointerCancel:
- return EventTypeNames::touchcancel;
+ return event_type_names::kTouchcancel;
case WebInputEvent::kPointerDown:
- return EventTypeNames::touchstart;
+ return event_type_names::kTouchstart;
case WebInputEvent::kPointerMove:
- return EventTypeNames::touchmove;
+ return event_type_names::kTouchmove;
default:
NOTREACHED();
return g_empty_atom;
@@ -283,7 +283,8 @@ WebCoalescedInputEvent TouchEventManager::GenerateWebCoalescedInputEvent() {
} timestamp_based_event_comparison;
std::sort(all_coalesced_events.begin(), all_coalesced_events.end(),
timestamp_based_event_comparison);
- WebCoalescedInputEvent result(event, std::vector<const WebInputEvent*>());
+ WebCoalescedInputEvent result(event, std::vector<const WebInputEvent*>(),
+ std::vector<const WebInputEvent*>());
for (const auto& web_pointer_event : all_coalesced_events) {
if (web_pointer_event.GetType() == WebInputEvent::kPointerDown) {
// TODO(crbug.com/732842): Technically we should never receive the
@@ -481,9 +482,9 @@ TouchEventManager::DispatchTouchEventFromAccumulatdTouchPoints() {
DispatchEventResult dom_dispatch_result =
touch_event_target->DispatchEvent(*touch_event);
- event_result = EventHandlingUtil::MergeEventResult(
+ event_result = event_handling_util::MergeEventResult(
event_result,
- EventHandlingUtil::ToWebInputEventResult(dom_dispatch_result));
+ event_handling_util::ToWebInputEventResult(dom_dispatch_result));
}
}
@@ -502,7 +503,7 @@ TouchEventManager::DispatchTouchEventFromAccumulatdTouchPoints() {
void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
const WebPointerEvent& event,
- const EventHandlingUtil::PointerEventTarget& pointer_event_target) {
+ const event_handling_util::PointerEventTarget& pointer_event_target) {
// Touch events implicitly capture to the touched node, and don't change
// active/hover states themselves (Gesture events do). So we only need
// to hit-test on touchstart and when the target could be different than
@@ -514,7 +515,8 @@ void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
// some tests that take advantage of it. There may also be edge
// cases in the browser where this happens.
// See http://crbug.com/345372.
- touch_attribute_map_.Set(event.id, new TouchPointAttributes(event));
+ touch_attribute_map_.Set(event.id,
+ MakeGarbageCollected<TouchPointAttributes>(event));
Node* touch_node = pointer_event_target.target_node;
String region = pointer_event_target.region;
@@ -536,7 +538,7 @@ void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
HitTestLocation location(LayoutPoint(
touch_sequence_document_->GetFrame()->View()->ConvertFromRootFrame(
event.PositionInWidget())));
- result = EventHandlingUtil::HitTestResultInFrame(
+ result = event_handling_util::HitTestResultInFrame(
touch_sequence_document_->GetFrame(), location, hit_type);
Node* node = result.InnerNode();
if (!node)
@@ -572,7 +574,7 @@ void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
attributes->region_ = region;
TouchAction effective_touch_action =
- TouchActionUtil::ComputeEffectiveTouchAction(*touch_node);
+ touch_action_util::ComputeEffectiveTouchAction(*touch_node);
should_enforce_vertical_scroll_ =
touch_sequence_document_->IsVerticalScrollEnforced();
@@ -595,7 +597,7 @@ void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
void TouchEventManager::HandleTouchPoint(
const WebPointerEvent& event,
const Vector<WebPointerEvent>& coalesced_events,
- const EventHandlingUtil::PointerEventTarget& pointer_event_target) {
+ const event_handling_util::PointerEventTarget& pointer_event_target) {
DCHECK_GE(event.GetType(), WebInputEvent::kPointerTypeFirst);
DCHECK_LE(event.GetType(), WebInputEvent::kPointerTypeLast);
DCHECK_NE(event.GetType(), WebInputEvent::kPointerCausedUaAction);
@@ -634,7 +636,8 @@ void TouchEventManager::HandleTouchPoint(
// them. For those just keep them in the map with a null target. Later they
// will be targeted at the |touch_sequence_document_|.
if (!touch_attribute_map_.Contains(event.id)) {
- touch_attribute_map_.insert(event.id, new TouchPointAttributes(event));
+ touch_attribute_map_.insert(
+ event.id, MakeGarbageCollected<TouchPointAttributes>(event));
}
TouchPointAttributes* attributes = touch_attribute_map_.at(event.id);
diff --git a/chromium/third_party/blink/renderer/core/input/touch_event_manager.h b/chromium/third_party/blink/renderer/core/input/touch_event_manager.h
index 60357035711..dd7294c1b85 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_event_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/touch_event_manager.h
@@ -35,7 +35,7 @@ class CORE_EXPORT TouchEventManager
void HandleTouchPoint(const WebPointerEvent&,
const Vector<WebPointerEvent>&,
- const EventHandlingUtil::PointerEventTarget&);
+ const event_handling_util::PointerEventTarget&);
WebInputEventResult FlushEvents();
@@ -79,7 +79,7 @@ class CORE_EXPORT TouchEventManager
// touch events.
void UpdateTouchAttributeMapsForPointerDown(
const WebPointerEvent&,
- const EventHandlingUtil::PointerEventTarget&);
+ const event_handling_util::PointerEventTarget&);
// This is triggered either by VSync signal to send one touch event per frame
// accumulating all move events or by discrete events pointerdown/up/cancel.
diff --git a/chromium/third_party/blink/renderer/core/input/touch_event_manager_test.cc b/chromium/third_party/blink/renderer/core/input/touch_event_manager_test.cc
index 2a919455f33..82f8ae64a44 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_event_manager_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/touch_event_manager_test.cc
@@ -41,7 +41,7 @@ class CheckEventListenerCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
+ void Invoke(ExecutionContext*, Event* event) override {
event_received_ = true;
}
@@ -65,23 +65,24 @@ TEST_F(TouchEventManagerTest, LostTouchDueToInnerIframeRemove) {
</body>
)HTML");
CheckEventListenerCallback* callback = CheckEventListenerCallback::Create();
- GetDocument().body()->addEventListener(EventTypeNames::touchstart, callback);
+ GetDocument().body()->addEventListener(event_type_names::kTouchstart,
+ callback);
GetEventHandler().HandlePointerEvent(
CreateTouchPointerEvent(WebInputEvent::kPointerDown),
- Vector<WebPointerEvent>());
+ Vector<WebPointerEvent>(), Vector<WebPointerEvent>());
GetEventHandler().DispatchBufferedTouchEvents();
GetDocument().getElementById("target")->remove();
GetEventHandler().HandlePointerEvent(
CreateTouchPointerEvent(WebInputEvent::kPointerUp),
- Vector<WebPointerEvent>());
+ Vector<WebPointerEvent>(), Vector<WebPointerEvent>());
GetEventHandler().DispatchBufferedTouchEvents();
GetEventHandler().HandlePointerEvent(
CreateTouchPointerEvent(WebInputEvent::kPointerDown),
- Vector<WebPointerEvent>());
+ Vector<WebPointerEvent>(), Vector<WebPointerEvent>());
GetEventHandler().DispatchBufferedTouchEvents();
ASSERT_TRUE(callback->HasReceivedEvent());
diff --git a/chromium/third_party/blink/renderer/core/input/touch_list.h b/chromium/third_party/blink/renderer/core/input/touch_list.h
index 32547e11721..59960305a73 100644
--- a/chromium/third_party/blink/renderer/core/input/touch_list.h
+++ b/chromium/third_party/blink/renderer/core/input/touch_list.h
@@ -38,18 +38,21 @@ class CORE_EXPORT TouchList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static TouchList* Create() { return new TouchList; }
+ static TouchList* Create() { return MakeGarbageCollected<TouchList>(); }
static TouchList* Create(const HeapVector<Member<Touch>>& touches) {
- TouchList* list = new TouchList;
+ TouchList* list = MakeGarbageCollected<TouchList>();
list->values_.AppendVector(touches);
return list;
}
static TouchList* Adopt(HeapVector<Member<Touch>>& touches) {
- return new TouchList(touches);
+ return MakeGarbageCollected<TouchList>(touches);
}
+ TouchList() = default;
+ TouchList(HeapVector<Member<Touch>>& touches) { values_.swap(touches); }
+
unsigned length() const { return values_.size(); }
Touch* item(unsigned);
@@ -60,10 +63,6 @@ class CORE_EXPORT TouchList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- TouchList() = default;
-
- TouchList(HeapVector<Member<Touch>>& touches) { values_.swap(touches); }
-
HeapVector<Member<Touch>> values_;
};
diff --git a/chromium/third_party/blink/renderer/core/inspector/BUILD.gn b/chromium/third_party/blink/renderer/core/inspector/BUILD.gn
index 9d1daad203f..ce5a13bf603 100644
--- a/chromium/third_party/blink/renderer/core/inspector/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/inspector/BUILD.gn
@@ -25,6 +25,8 @@ blink_core_sources("inspector") {
"dev_tools_host.h",
"devtools_agent.cc",
"devtools_agent.h",
+ "devtools_session.cc",
+ "devtools_session.h",
"dom_editor.cc",
"dom_editor.h",
"dom_patch_support.cc",
@@ -77,8 +79,6 @@ blink_core_sources("inspector") {
"inspector_resource_container.h",
"inspector_resource_content_loader.cc",
"inspector_resource_content_loader.h",
- "inspector_session.cc",
- "inspector_session.h",
"inspector_session_state.cc",
"inspector_session_state.h",
"inspector_style_sheet.cc",
@@ -89,8 +89,6 @@ blink_core_sources("inspector") {
"inspector_testing_agent.h",
"inspector_trace_events.cc",
"inspector_trace_events.h",
- "inspector_worker_agent.cc",
- "inspector_worker_agent.h",
"main_thread_debugger.cc",
"main_thread_debugger.h",
"network_resources_data.cc",
@@ -101,6 +99,7 @@ blink_core_sources("inspector") {
"thread_debugger.h",
"v8_inspector_string.cc",
"v8_inspector_string.h",
+ "worker_devtools_params.h",
"worker_inspector_controller.cc",
"worker_inspector_controller.h",
"worker_thread_debugger.cc",
@@ -177,8 +176,6 @@ inspector_protocol_generate("protocol_sources") {
"inspector/protocol/Runtime.h",
"inspector/protocol/Security.cpp",
"inspector/protocol/Security.h",
- "inspector/protocol/Target.cpp",
- "inspector/protocol/Target.h",
"inspector/protocol/Testing.cpp",
"inspector/protocol/Testing.h",
]
diff --git a/chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl b/chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl
index b63737e1114..704c6b7e2c5 100644
--- a/chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl
+++ b/chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl
@@ -116,10 +116,14 @@ experimental domain Accessibility
enum
busy
disabled
+ editable
+ focusable
+ focused
hidden
hiddenRoot
invalid
keyshortcuts
+ settable
roledescription
live
atomic
@@ -174,6 +178,13 @@ experimental domain Accessibility
# The backend ID for the associated DOM node, if any.
optional DOM.BackendNodeId backendDOMNodeId
+ # Disables the accessibility domain.
+ command disable
+
+ # Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls.
+ # This turns on accessibility for the page, which can impact performance until accessibility is disabled.
+ command enable
+
# Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists.
experimental command getPartialAXTree
parameters
@@ -452,7 +463,7 @@ experimental domain Audits
optional boolean sizeOnly
returns
# The encoded body as a base64 string. Omitted if sizeOnly is true.
- optional string body
+ optional binary body
# Size before re-encoding.
integer originalSize
# Size after re-encoding.
@@ -490,6 +501,7 @@ domain Browser
accessibilityEvents
audioCapture
backgroundSync
+ backgroundFetch
clipboardRead
clipboardWrite
durableStorage
@@ -605,8 +617,8 @@ domain Browser
# Get the browser window that contains the devtools target.
experimental command getWindowForTarget
parameters
- # Devtools agent host id.
- Target.TargetID targetId
+ # Devtools agent host id. If called as a part of the session, associated targetId is used.
+ optional Target.TargetID targetId
returns
# Browser window id.
WindowID windowId
@@ -623,6 +635,13 @@ domain Browser
# with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged.
Bounds bounds
+ # Set dock tile details, platform-specific.
+ experimental command setDockTile
+ parameters
+ optional string badgeLabel
+ # Png encoded image.
+ optional binary image
+
# This domain exposes CSS read/write operations. All CSS objects (stylesheets, rules, and styles)
# have an associated `id` used in subsequent operations on the related object. Each object type has
# a specific `id` structure, and those are not interchangeable between objects of different kinds.
@@ -1143,6 +1162,16 @@ experimental domain CacheStorage
# Unique identifier of the Cache object.
type CacheId extends string
+ # type of HTTP response cached
+ type CachedResponseType extends string
+ enum
+ basic
+ cors
+ default
+ error
+ opaqueResponse
+ opaqueRedirect
+
# Data entry.
type DataEntry extends object
properties
@@ -1158,6 +1187,8 @@ experimental domain CacheStorage
integer responseStatus
# HTTP response status text.
string responseStatusText
+ # HTTP response type
+ CachedResponseType responseType
# Response headers
array of Header responseHeaders
@@ -1180,7 +1211,7 @@ experimental domain CacheStorage
type CachedResponse extends object
properties
# Entry content, base64-encoded.
- string body
+ binary body
# Deletes a cache.
command deleteCache
@@ -2683,7 +2714,7 @@ experimental domain HeadlessExperimental
# display. Reported for diagnostic uses, may be removed in the future.
boolean hasDamage
# Base64-encoded image data of the screenshot, if one was requested and successfully taken.
- optional string screenshotData
+ optional binary screenshotData
# Disables headless events for the target.
command disable
@@ -3190,7 +3221,7 @@ experimental domain LayerTree
# Offset from owning layer top boundary
number y
# Base64-encoded snapshot data.
- string picture
+ binary picture
# Information about a compositing layer.
type Layer extends object
@@ -4030,7 +4061,7 @@ domain Network
optional ErrorReason errorReason
# If set the requests completes using with the provided base64 encoded raw response, including
# HTTP status line and headers etc... Must not be set in response to an authChallenge.
- optional string rawResponse
+ optional binary rawResponse
# If set the request url will be modified in a way that's not observable by page. Must not be
# set in response to an authChallenge.
optional string url
@@ -4127,7 +4158,7 @@ domain Network
# Identifier of the network request to get content for.
RequestId requestId
returns
- # Base64-encoded request body.
+ # Request body string, omitting files from multipart requests
string postData
# Returns content served for the given currently intercepted request.
@@ -4627,6 +4658,12 @@ experimental domain Overlay
# True for showing scroll bottleneck rects
boolean show
+ # Requests that backend shows hit-test borders on layers
+ command setShowHitTestBorders
+ parameters
+ # True for showing hit-test borders
+ boolean show
+
# Paints viewport size upon main frame resize.
command setShowViewportSizeOnResize
parameters
@@ -4902,6 +4939,17 @@ domain Page
experimental optional boolean fromSurface
returns
# Base64-encoded image data.
+ binary data
+
+ # Returns a snapshot of the page as a string. For MHTML format, the serialization includes
+ # iframes, shadow DOM, external resources, and element-inline styles.
+ experimental command captureSnapshot
+ parameters
+ # Format (defaults to mhtml).
+ optional enum format
+ mhtml
+ returns
+ # Serialized page data.
string data
# Clears the overriden device metrics.
@@ -5089,7 +5137,7 @@ domain Page
optional boolean preferCSSPageSize
returns
# Base64-encoded pdf data.
- string data
+ binary data
# Reloads given page optionally ignoring the cache.
command reload
@@ -5304,7 +5352,7 @@ domain Page
parameters
string url
# Base64-encoded data
- string data
+ binary data
# Clears seeded compilation cache.
experimental command clearCompilationCache
@@ -5441,7 +5489,7 @@ domain Page
experimental event screencastFrame
parameters
# Base64-encoded compressed image.
- string data
+ binary data
# Screencast frame metadata.
ScreencastFrameMetadata metadata
# Frame number.
@@ -5472,7 +5520,7 @@ domain Page
parameters
string url
# Base64-encoded data
- string data
+ binary data
domain Performance
@@ -5555,6 +5603,8 @@ domain Security
MixedContentType mixedContentType
# Page certificate.
array of string certificate
+ # Recommendations to fix any issues.
+ optional array of string recommendations
# Information about insecure content on the page.
type InsecureContentStatus extends object
@@ -5875,6 +5925,17 @@ experimental domain SystemInfo
# An optional array of GPU driver bug workarounds.
array of string driverBugWorkarounds
+ # Represents process info.
+ type ProcessInfo extends object
+ properties
+ # Specifies process type.
+ string type
+ # Specifies process id.
+ integer id
+ # Specifies cumulative CPU usage in seconds across all threads of the
+ # process since the process start.
+ number cpuTime
+
# Returns information about the system.
command getInfo
returns
@@ -5890,6 +5951,12 @@ experimental domain SystemInfo
# supported.
string commandLine
+ # Returns information about all running processes.
+ command getProcessInfo
+ returns
+ # An array of process info blocks.
+ array of ProcessInfo processInfo
+
# Supports additional targets discovery and allows to attach to them.
domain Target
@@ -6243,3 +6310,199 @@ experimental domain Testing
string message
# Specifies the endpoint group to deliver the report to.
optional string group
+
+# A domain for letting clients substitute browser's network layer with client code.
+experimental domain Fetch
+ depends on Network
+ depends on IO
+ depends on Page
+
+ # Unique request identifier.
+ type RequestId extends string
+
+ # Stages of the request to handle. Request will intercept before the request is
+ # sent. Response will intercept after the response is received (but before response
+ # body is received.
+ experimental type RequestStage extends string
+ enum
+ Request
+ Response
+
+ experimental type RequestPattern extends object
+ properties
+ # Wildcards ('*' -> zero or more, '?' -> exactly one) are allowed. Escape character is
+ # backslash. Omitting is equivalent to "*".
+ optional string urlPattern
+ # If set, only requests for matching resource types will be intercepted.
+ optional Network.ResourceType resourceType
+ # Stage at wich to begin intercepting requests. Default is Request.
+ optional RequestStage requestStage
+
+ # Response HTTP header entry
+ type HeaderEntry extends object
+ properties
+ string name
+ string value
+
+ # Authorization challenge for HTTP status code 401 or 407.
+ experimental type AuthChallenge extends object
+ properties
+ # Source of the authentication challenge.
+ optional enum source
+ Server
+ Proxy
+ # Origin of the challenger.
+ string origin
+ # The authentication scheme used, such as basic or digest
+ string scheme
+ # The realm of the challenge. May be empty.
+ string realm
+
+ # Response to an AuthChallenge.
+ experimental type AuthChallengeResponse extends object
+ properties
+ # The decision on what to do in response to the authorization challenge. Default means
+ # deferring to the default behavior of the net stack, which will likely either the Cancel
+ # authentication or display a popup dialog box.
+ enum response
+ Default
+ CancelAuth
+ ProvideCredentials
+ # The username to provide, possibly empty. Should only be set if response is
+ # ProvideCredentials.
+ optional string username
+ # The password to provide, possibly empty. Should only be set if response is
+ # ProvideCredentials.
+ optional string password
+
+ # Disables the fetch domain.
+ command disable
+
+ # Enables issuing of requestPaused events. A request will be paused until client
+ # calls one of failRequest, fulfillRequest or continueRequest/continueWithAuth.
+ command enable
+ parameters
+ # If specified, only requests matching any of these patterns will produce
+ # fetchRequested event and will be paused until clients response. If not set,
+ # all requests will be affected.
+ optional array of RequestPattern patterns
+ # If true, authRequired events will be issued and requests will be paused
+ # expecting a call to continueWithAuth.
+ optional boolean handleAuthRequests
+
+ # Causes the request to fail with specified reason.
+ command failRequest
+ parameters
+ # An id the client received in requestPaused event.
+ RequestId requestId
+ # Causes the request to fail with the given reason.
+ Network.ErrorReason errorReason
+
+ # Provides response to the request.
+ command fulfillRequest
+ parameters
+ # An id the client received in requestPaused event.
+ RequestId requestId
+ # An HTTP response code.
+ integer responseCode
+ # Response headers.
+ array of HeaderEntry responseHeaders
+ # A response body.
+ optional binary body
+ # A textual representation of responseCode.
+ # If absent, a standard phrase mathcing responseCode is used.
+ optional string responsePhrase
+
+ # Continues the request, optionally modifying some of its parameters.
+ command continueRequest
+ parameters
+ # An id the client received in requestPaused event.
+ RequestId requestId
+ # If set, the request url will be modified in a way that's not observable by page.
+ optional string url
+ # If set, the request method is overridden.
+ optional string method
+ # If set, overrides the post data in the request.
+ optional string postData
+ # If set, overrides the request headrts.
+ optional array of HeaderEntry headers
+
+ # Continues a request supplying authChallengeResponse following authRequired event.
+ command continueWithAuth
+ parameters
+ # An id the client received in authRequired event.
+ RequestId requestId
+ # Response to with an authChallenge.
+ AuthChallengeResponse authChallengeResponse
+
+ # Causes the body of the response to be received from the server and
+ # returned as a single string. May only be issued for a request that
+ # is paused in the Response stage and is mutually exclusive with
+ # takeResponseBodyForInterceptionAsStream. Calling other methods that
+ # affect the request or disabling fetch domain before body is received
+ # results in an undefined behavior.
+ command getResponseBody
+ parameters
+ # Identifier for the intercepted request to get body for.
+ RequestId requestId
+ returns
+ # Response body.
+ string body
+ # True, if content was sent as base64.
+ boolean base64Encoded
+
+ # Returns a handle to the stream representing the response body.
+ # The request must be paused in the HeadersReceived stage.
+ # Note that after this command the request can't be continued
+ # as is -- client either needs to cancel it or to provide the
+ # response body.
+ # The stream only supports sequential read, IO.read will fail if the position
+ # is specified.
+ # This method is mutually exclusive with getResponseBody.
+ # Calling other methods that affect the request or disabling fetch
+ # domain before body is received results in an undefined behavior.
+ command takeResponseBodyAsStream
+ parameters
+ RequestId requestId
+ returns
+ IO.StreamHandle stream
+
+ # Issued when the domain is enabled and the request URL matches the
+ # specified filter. The request is paused until the client responds
+ # with one of continueRequest, failRequest or fulfillRequest.
+ # The stage of the request can be determined by presence of responseErrorReason
+ # and responseStatusCode -- the request is at the response stage if either
+ # of these fields is present and in the request stage otherwise.
+ event requestPaused
+ parameters
+ # Each request the page makes will have a unique id.
+ RequestId requestId
+ # The details of the request.
+ Network.Request request
+ # The id of the frame that initiated the request.
+ Page.FrameId frameId
+ # How the requested resource will be used.
+ Network.ResourceType resourceType
+ # Response error if intercepted at response stage.
+ optional Network.ErrorReason responseErrorReason
+ # Response code if intercepted at response stage.
+ optional integer responseStatusCode
+ # Response headers if intercepted at the response stage.
+ optional array of HeaderEntry responseHeaders
+
+ # Issued when the domain is enabled with handleAuthRequests set to true.
+ # The request is paused until client responds with continueWithAuth.
+ event authRequired
+ parameters
+ # Each request the page makes will have a unique id.
+ RequestId requestId
+ # The details of the request.
+ Network.Request request
+ # The id of the frame that initiated the request.
+ Page.FrameId frameId
+ # How the requested resource will be used.
+ Network.ResourceType resourceType
+ # Details of the Authorization Challenge encountered.
+ # If this is set, client should respond with continueRequest that
+ # contains AuthChallengeResponse.
+ AuthChallenge authChallenge
diff --git a/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc b/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc
index 77d1fd86d81..c0f40a77e0e 100644
--- a/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc
@@ -111,7 +111,7 @@ DevToolsEmulator::DevToolsEmulator(WebViewImpl* web_view)
DevToolsEmulator::~DevToolsEmulator() = default;
DevToolsEmulator* DevToolsEmulator::Create(WebViewImpl* web_view_base) {
- return new DevToolsEmulator(web_view_base);
+ return MakeGarbageCollected<DevToolsEmulator>(web_view_base);
}
void DevToolsEmulator::Trace(blink::Visitor* visitor) {}
diff --git a/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.h b/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.h
index e860b7b2524..0d3d98fddf6 100644
--- a/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.h
+++ b/chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.h
@@ -24,6 +24,7 @@ class WebViewImpl;
class CORE_EXPORT DevToolsEmulator final
: public GarbageCollectedFinalized<DevToolsEmulator> {
public:
+ explicit DevToolsEmulator(WebViewImpl*);
~DevToolsEmulator();
static DevToolsEmulator* Create(WebViewImpl*);
void Trace(blink::Visitor*);
@@ -66,8 +67,6 @@ class CORE_EXPORT DevToolsEmulator final
base::Optional<IntRect> VisibleContentRectForPainting() const;
private:
- explicit DevToolsEmulator(WebViewImpl*);
-
void EnableMobileEmulation();
void DisableMobileEmulation();
diff --git a/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.cc b/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.cc
index c7c1687cf2a..64c10cbf7ed 100644
--- a/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.cc
@@ -65,9 +65,13 @@ class FrontendMenuProvider final : public ContextMenuProvider {
public:
static FrontendMenuProvider* Create(DevToolsHost* devtools_host,
WebVector<WebMenuItemInfo> items) {
- return new FrontendMenuProvider(devtools_host, std::move(items));
+ return MakeGarbageCollected<FrontendMenuProvider>(devtools_host,
+ std::move(items));
}
+ FrontendMenuProvider(DevToolsHost* devtools_host,
+ WebVector<WebMenuItemInfo> items)
+ : devtools_host_(devtools_host), items_(std::move(items)) {}
~FrontendMenuProvider() override {
// Verify that this menu provider has been detached.
DCHECK(!devtools_host_);
@@ -101,10 +105,6 @@ class FrontendMenuProvider final : public ContextMenuProvider {
}
private:
- FrontendMenuProvider(DevToolsHost* devtools_host,
- WebVector<WebMenuItemInfo> items)
- : devtools_host_(devtools_host), items_(std::move(items)) {}
-
Member<DevToolsHost> devtools_host_;
WebVector<WebMenuItemInfo> items_;
};
diff --git a/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.h b/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.h
index 32279ebc6ed..7e47396306f 100644
--- a/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.h
+++ b/chromium/third_party/blink/renderer/core/inspector/dev_tools_host.h
@@ -48,10 +48,12 @@ class CORE_EXPORT DevToolsHost final : public ScriptWrappable {
public:
static DevToolsHost* Create(InspectorFrontendClient* client,
LocalFrame* frontend_frame) {
- return new DevToolsHost(client, frontend_frame);
+ return MakeGarbageCollected<DevToolsHost>(client, frontend_frame);
}
+ DevToolsHost(InspectorFrontendClient*, LocalFrame* frontend_frame);
~DevToolsHost() override;
+
void Trace(blink::Visitor*) override;
void DisconnectClient();
@@ -85,7 +87,6 @@ class CORE_EXPORT DevToolsHost final : public ScriptWrappable {
private:
friend class FrontendMenuProvider;
- DevToolsHost(InspectorFrontendClient*, LocalFrame* frontend_frame);
void EvaluateScript(const String&);
Member<InspectorFrontendClient> client_;
diff --git a/chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc b/chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc
index 6d31a13f56b..ce60e4be4cc 100644
--- a/chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc
@@ -7,236 +7,112 @@
#include <v8-inspector.h>
#include <memory>
-#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/blink/renderer/core/inspector/inspector_session.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/core/inspector/devtools_session.h"
+#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
+#include "third_party/blink/renderer/core/inspector/worker_inspector_controller.h"
+#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
-// --------- DevToolsAgent::Session -------------
+namespace {
-class DevToolsAgent::Session : public GarbageCollectedFinalized<Session>,
- public mojom::blink::DevToolsSession,
- public InspectorSession::Client {
- public:
- Session(DevToolsAgent*,
- mojom::blink::DevToolsSessionHostAssociatedPtrInfo host_ptr_info,
- mojom::blink::DevToolsSessionAssociatedRequest main_request,
- mojom::blink::DevToolsSessionRequest io_request,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state);
- ~Session() override;
-
- virtual void Trace(blink::Visitor*);
- void Detach();
-
- InspectorSession* inspector_session() { return inspector_session_.Get(); }
-
- private:
- class IOSession;
-
- // mojom::blink::DevToolsSession implementation.
- void DispatchProtocolCommand(int call_id,
- const String& method,
- const String& message) override;
-
- // InspectorSession::Client implementation.
- void SendProtocolResponse(
- int session_id,
- int call_id,
- const String& response,
- mojom::blink::DevToolsSessionStatePtr updates) override;
- void SendProtocolNotification(
- int session_id,
- const String& message,
- mojom::blink::DevToolsSessionStatePtr updates) override;
-
- void DispatchProtocolCommandInternal(int call_id,
- const String& method,
- const String& message);
-
- Member<DevToolsAgent> agent_;
- mojo::AssociatedBinding<mojom::blink::DevToolsSession> binding_;
- mojom::blink::DevToolsSessionHostAssociatedPtr host_ptr_;
- IOSession* io_session_;
- Member<InspectorSession> inspector_session_;
-
- DISALLOW_COPY_AND_ASSIGN(Session);
-};
-
-// Created and stored in unique_ptr on UI.
-// Binds request, receives messages and destroys on IO.
-class DevToolsAgent::Session::IOSession : public mojom::blink::DevToolsSession {
- public:
- IOSession(scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
- scoped_refptr<InspectorTaskRunner> inspector_task_runner,
- CrossThreadWeakPersistent<DevToolsAgent::Session> session,
- mojom::blink::DevToolsSessionRequest request)
- : io_task_runner_(io_task_runner),
- inspector_task_runner_(inspector_task_runner),
- session_(std::move(session)),
- binding_(this) {
- io_task_runner->PostTask(
- FROM_HERE, ConvertToBaseCallback(CrossThreadBind(
- &IOSession::BindInterface, CrossThreadUnretained(this),
- WTF::Passed(std::move(request)))));
+DevToolsAgent* DevToolsAgentFromContext(ExecutionContext* execution_context) {
+ if (!execution_context)
+ return nullptr;
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) {
+ return scope->GetThread()
+ ->GetWorkerInspectorController()
+ ->GetDevToolsAgent();
}
-
- ~IOSession() override {}
-
- void BindInterface(mojom::blink::DevToolsSessionRequest request) {
- binding_.Bind(std::move(request));
- }
-
- void DeleteSoon() { io_task_runner_->DeleteSoon(FROM_HERE, this); }
-
- // mojom::blink::DevToolsSession implementation.
- void DispatchProtocolCommand(int call_id,
- const String& method,
- const String& message) override {
- DCHECK(InspectorSession::ShouldInterruptForMethod(method));
- // Crash renderer.
- if (method == "Page.crash")
- CHECK(false);
- inspector_task_runner_->AppendTask(
- CrossThreadBind(&DevToolsAgent::Session::DispatchProtocolCommand,
- session_, call_id, method, message));
+ if (auto* document = DynamicTo<Document>(execution_context)) {
+ LocalFrame* frame = document->GetFrame();
+ if (!frame)
+ return nullptr;
+ WebLocalFrameImpl* web_frame =
+ WebLocalFrameImpl::FromFrame(frame->LocalFrameRoot());
+ if (!web_frame)
+ return nullptr;
+ return web_frame->DevToolsAgentImpl()->GetDevToolsAgent();
}
-
- private:
- scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
- scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
- CrossThreadWeakPersistent<DevToolsAgent::Session> session_;
- mojo::Binding<mojom::blink::DevToolsSession> binding_;
-
- DISALLOW_COPY_AND_ASSIGN(IOSession);
-};
-
-DevToolsAgent::Session::Session(
- DevToolsAgent* agent,
- mojom::blink::DevToolsSessionHostAssociatedPtrInfo host_ptr_info,
- mojom::blink::DevToolsSessionAssociatedRequest request,
- mojom::blink::DevToolsSessionRequest io_request,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state)
- : agent_(agent), binding_(this, std::move(request)) {
- io_session_ =
- new IOSession(agent_->io_task_runner_, agent_->inspector_task_runner_,
- WrapCrossThreadWeakPersistent(this), std::move(io_request));
-
- host_ptr_.Bind(std::move(host_ptr_info));
- host_ptr_.set_connection_error_handler(
- WTF::Bind(&DevToolsAgent::Session::Detach, WrapWeakPersistent(this)));
- inspector_session_ =
- agent_->client_->AttachSession(this, std::move(reattach_session_state));
-}
-
-DevToolsAgent::Session::~Session() {
- DCHECK(!host_ptr_.is_bound());
+ return nullptr;
}
-void DevToolsAgent::Session::Trace(blink::Visitor* visitor) {
- visitor->Trace(agent_);
- visitor->Trace(inspector_session_);
-}
-
-void DevToolsAgent::Session::Detach() {
- agent_->client_->DetachSession(inspector_session_.Get());
- agent_->sessions_.erase(this);
- binding_.Close();
- host_ptr_.reset();
- io_session_->DeleteSoon();
- io_session_ = nullptr;
- inspector_session_->Dispose();
-}
-
-void DevToolsAgent::Session::SendProtocolResponse(
- int session_id,
- int call_id,
- const String& response,
- mojom::blink::DevToolsSessionStatePtr updates) {
- if (!host_ptr_.is_bound())
- return;
- // Make tests more predictable by flushing all sessions before sending
- // protocol response in any of them.
- if (LayoutTestSupport::IsRunningLayoutTest())
- agent_->FlushProtocolNotifications();
- host_ptr_->DispatchProtocolResponse(response, call_id, std::move(updates));
-}
-
-void DevToolsAgent::Session::SendProtocolNotification(
- int session_id,
- const String& message,
- mojom::blink::DevToolsSessionStatePtr updates) {
- if (!host_ptr_.is_bound())
- return;
- host_ptr_->DispatchProtocolNotification(message, std::move(updates));
-}
-
-void DevToolsAgent::Session::DispatchProtocolCommand(int call_id,
- const String& method,
- const String& message) {
- // IOSession does not provide ordering guarantees relative to
- // Session, so a command may come to IOSession after Session is detached,
- // and get posted to main thread to this method.
- //
- // At the same time, Session may not be garbage collected yet
- // (even though already detached), and CrossThreadWeakPersistent<Session>
- // will still be valid.
- //
- // Both these factors combined may lead to this method being called after
- // detach, so we have to check it here.
- if (!host_ptr_.is_bound())
- return;
- inspector_session_->DispatchProtocolMessage(call_id, method, message);
-}
-
-// --------- DevToolsAgent -------------
+} // namespace
DevToolsAgent::DevToolsAgent(
Client* client,
+ InspectedFrames* inspected_frames,
+ CoreProbeSink* probe_sink,
scoped_refptr<InspectorTaskRunner> inspector_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner)
: client_(client),
binding_(this),
+ associated_binding_(this),
+ inspected_frames_(inspected_frames),
+ probe_sink_(probe_sink),
inspector_task_runner_(std::move(inspector_task_runner)),
io_task_runner_(std::move(io_task_runner)) {}
DevToolsAgent::~DevToolsAgent() {}
void DevToolsAgent::Trace(blink::Visitor* visitor) {
+ visitor->Trace(inspected_frames_);
+ visitor->Trace(probe_sink_);
visitor->Trace(sessions_);
}
void DevToolsAgent::Dispose() {
- HeapHashSet<Member<Session>> copy(sessions_);
+ HeapHashSet<Member<DevToolsSession>> copy(sessions_);
for (auto& session : copy)
session->Detach();
CleanupConnection();
}
void DevToolsAgent::BindRequest(
- mojom::blink::DevToolsAgentHostAssociatedPtrInfo host_ptr_info,
- mojom::blink::DevToolsAgentAssociatedRequest request) {
+ mojom::blink::DevToolsAgentHostPtrInfo host_ptr_info,
+ mojom::blink::DevToolsAgentRequest request,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
DCHECK(!binding_);
- binding_.Bind(std::move(request));
+ DCHECK(!associated_binding_);
+ binding_.Bind(std::move(request), std::move(task_runner));
host_ptr_.Bind(std::move(host_ptr_info));
host_ptr_.set_connection_error_handler(
WTF::Bind(&DevToolsAgent::CleanupConnection, WrapWeakPersistent(this)));
}
+void DevToolsAgent::BindRequest(
+ mojom::blink::DevToolsAgentHostAssociatedPtrInfo host_ptr_info,
+ mojom::blink::DevToolsAgentAssociatedRequest request,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
+ DCHECK(!binding_);
+ DCHECK(!associated_binding_);
+ associated_binding_.Bind(std::move(request), std::move(task_runner));
+ associated_host_ptr_.Bind(std::move(host_ptr_info));
+ associated_host_ptr_.set_connection_error_handler(
+ WTF::Bind(&DevToolsAgent::CleanupConnection, WrapWeakPersistent(this)));
+}
+
void DevToolsAgent::AttachDevToolsSession(
mojom::blink::DevToolsSessionHostAssociatedPtrInfo host,
mojom::blink::DevToolsSessionAssociatedRequest session_request,
mojom::blink::DevToolsSessionRequest io_session_request,
mojom::blink::DevToolsSessionStatePtr reattach_session_state) {
- Session* session = new Session(
+ client_->DebuggerTaskStarted();
+ DevToolsSession* session = new DevToolsSession(
this, std::move(host), std::move(session_request),
std::move(io_session_request), std::move(reattach_session_state));
sessions_.insert(session);
+ client_->DebuggerTaskFinished();
}
void DevToolsAgent::InspectElement(const WebPoint& point) {
@@ -245,12 +121,76 @@ void DevToolsAgent::InspectElement(const WebPoint& point) {
void DevToolsAgent::FlushProtocolNotifications() {
for (auto& session : sessions_)
- session->inspector_session()->flushProtocolNotifications();
+ session->FlushProtocolNotifications();
+}
+
+void DevToolsAgent::ReportChildWorkers(bool report, bool wait_for_debugger) {
+ report_child_workers_ = report;
+ pause_child_workers_on_start_ = wait_for_debugger;
+ if (!report_child_workers_)
+ return;
+ auto workers = std::move(unreported_child_worker_threads_);
+ for (auto& it : workers)
+ ReportChildWorker(std::move(it.value));
+}
+
+// static
+std::unique_ptr<WorkerDevToolsParams> DevToolsAgent::WorkerThreadCreated(
+ ExecutionContext* parent_context,
+ WorkerThread* worker_thread,
+ const KURL& url) {
+ auto result = std::make_unique<WorkerDevToolsParams>();
+ result->devtools_worker_token = base::UnguessableToken::Create();
+
+ DevToolsAgent* agent = DevToolsAgentFromContext(parent_context);
+ if (!agent)
+ return result;
+
+ auto data = std::make_unique<WorkerData>();
+ data->url = url;
+ result->agent_request = mojo::MakeRequest(&data->agent_ptr);
+ data->host_request = mojo::MakeRequest(&result->agent_host_ptr_info);
+ data->devtools_worker_token = result->devtools_worker_token;
+ data->waiting_for_debugger = agent->pause_child_workers_on_start_;
+ result->wait_for_debugger = agent->pause_child_workers_on_start_;
+
+ if (agent->report_child_workers_) {
+ agent->ReportChildWorker(std::move(data));
+ } else {
+ agent->unreported_child_worker_threads_.insert(worker_thread,
+ std::move(data));
+ }
+ return result;
+}
+
+// static
+void DevToolsAgent::WorkerThreadTerminated(ExecutionContext* parent_context,
+ WorkerThread* worker_thread) {
+ if (DevToolsAgent* agent = DevToolsAgentFromContext(parent_context))
+ agent->unreported_child_worker_threads_.erase(worker_thread);
+}
+
+void DevToolsAgent::ReportChildWorker(std::unique_ptr<WorkerData> data) {
+ if (host_ptr_.is_bound()) {
+ host_ptr_->ChildWorkerCreated(
+ std::move(data->agent_ptr), std::move(data->host_request),
+ std::move(data->url), data->devtools_worker_token,
+ data->waiting_for_debugger);
+ } else if (associated_host_ptr_.is_bound()) {
+ associated_host_ptr_->ChildWorkerCreated(
+ std::move(data->agent_ptr), std::move(data->host_request),
+ std::move(data->url), data->devtools_worker_token,
+ data->waiting_for_debugger);
+ }
}
void DevToolsAgent::CleanupConnection() {
binding_.Close();
+ associated_binding_.Close();
host_ptr_.reset();
+ associated_host_ptr_.reset();
+ report_child_workers_ = false;
+ pause_child_workers_on_start_ = false;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/devtools_agent.h b/chromium/third_party/blink/renderer/core/inspector/devtools_agent.h
index 3b0d4ec9ff7..51c69ac9eaa 100644
--- a/chromium/third_party/blink/renderer/core/inspector/devtools_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_agent.h
@@ -8,17 +8,24 @@
#include <memory>
#include "base/single_thread_task_runner.h"
+#include "base/unguessable_token.h"
#include "mojo/public/cpp/bindings/associated_binding.h"
+#include "mojo/public/cpp/bindings/binding.h"
#include "third_party/blink/public/web/devtools_agent.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/inspector/inspector_session.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
namespace blink {
+class CoreProbeSink;
+class DevToolsSession;
+class ExecutionContext;
+class InspectedFrames;
class InspectorTaskRunner;
+class WorkerThread;
+struct WorkerDevToolsParams;
class CORE_EXPORT DevToolsAgent
: public GarbageCollectedFinalized<DevToolsAgent>,
@@ -27,26 +34,39 @@ class CORE_EXPORT DevToolsAgent
class Client {
public:
virtual ~Client() {}
- virtual InspectorSession* AttachSession(
- InspectorSession::Client*,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state) = 0;
- virtual void DetachSession(InspectorSession*) = 0;
+ virtual void AttachSession(DevToolsSession*, bool restore) = 0;
+ virtual void DetachSession(DevToolsSession*) = 0;
virtual void InspectElement(const WebPoint&) = 0;
+ virtual void DebuggerTaskStarted() = 0;
+ virtual void DebuggerTaskFinished() = 0;
};
+ static std::unique_ptr<WorkerDevToolsParams> WorkerThreadCreated(
+ ExecutionContext* parent_context,
+ WorkerThread*,
+ const KURL&);
+ static void WorkerThreadTerminated(ExecutionContext* parent_context,
+ WorkerThread*);
+
DevToolsAgent(Client*,
+ InspectedFrames*,
+ CoreProbeSink*,
scoped_refptr<InspectorTaskRunner> inspector_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
~DevToolsAgent() override;
void Dispose();
void FlushProtocolNotifications();
+ void BindRequest(mojom::blink::DevToolsAgentHostPtrInfo,
+ mojom::blink::DevToolsAgentRequest,
+ scoped_refptr<base::SingleThreadTaskRunner>);
void BindRequest(mojom::blink::DevToolsAgentHostAssociatedPtrInfo,
- mojom::blink::DevToolsAgentAssociatedRequest);
+ mojom::blink::DevToolsAgentAssociatedRequest,
+ scoped_refptr<base::SingleThreadTaskRunner>);
virtual void Trace(blink::Visitor*);
private:
- class Session;
+ friend class DevToolsSession;
// mojom::blink::DevToolsAgent implementation.
void AttachDevToolsSession(
@@ -55,15 +75,33 @@ class CORE_EXPORT DevToolsAgent
mojom::blink::DevToolsSessionRequest io_session,
mojom::blink::DevToolsSessionStatePtr reattach_session_state) override;
void InspectElement(const WebPoint& point) override;
+ void ReportChildWorkers(bool report, bool wait_for_debugger) override;
+
+ struct WorkerData {
+ KURL url;
+ mojom::blink::DevToolsAgentPtr agent_ptr;
+ mojom::blink::DevToolsAgentHostRequest host_request;
+ base::UnguessableToken devtools_worker_token;
+ bool waiting_for_debugger;
+ };
+ void ReportChildWorker(std::unique_ptr<WorkerData>);
void CleanupConnection();
Client* client_;
- mojo::AssociatedBinding<mojom::blink::DevToolsAgent> binding_;
- mojom::blink::DevToolsAgentHostAssociatedPtr host_ptr_;
- HeapHashSet<Member<Session>> sessions_;
+ mojo::Binding<mojom::blink::DevToolsAgent> binding_;
+ mojo::AssociatedBinding<mojom::blink::DevToolsAgent> associated_binding_;
+ mojom::blink::DevToolsAgentHostPtr host_ptr_;
+ mojom::blink::DevToolsAgentHostAssociatedPtr associated_host_ptr_;
+ Member<InspectedFrames> inspected_frames_;
+ Member<CoreProbeSink> probe_sink_;
+ HeapHashSet<Member<DevToolsSession>> sessions_;
scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
+ HashMap<WorkerThread*, std::unique_ptr<WorkerData>>
+ unreported_child_worker_threads_;
+ bool report_child_workers_ = false;
+ bool pause_child_workers_on_start_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc b/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc
new file mode 100644
index 00000000000..347b9a74d34
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc
@@ -0,0 +1,315 @@
+// 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 "third_party/blink/renderer/core/inspector/devtools_session.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/inspector/devtools_agent.h"
+#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
+#include "third_party/blink/renderer/core/inspector/inspector_base_agent.h"
+#include "third_party/blink/renderer/core/inspector/inspector_session_state.h"
+#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
+#include "third_party/blink/renderer/core/inspector/protocol/Protocol.h"
+#include "third_party/blink/renderer/core/inspector/v8_inspector_string.h"
+#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/heap/persistent.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
+
+namespace blink {
+
+namespace {
+const char kV8StateKey[] = "v8";
+bool ShouldInterruptForMethod(const String& method) {
+ // Keep in sync with DevToolsSession::ShouldSendOnIO.
+ // TODO(dgozman): find a way to share this.
+ return method == "Debugger.pause" || method == "Debugger.setBreakpoint" ||
+ method == "Debugger.setBreakpointByUrl" ||
+ method == "Debugger.removeBreakpoint" ||
+ method == "Debugger.setBreakpointsActive" ||
+ method == "Performance.getMetrics" || method == "Page.crash" ||
+ method == "Runtime.terminateExecution" ||
+ method == "Emulation.setScriptExecutionDisabled";
+}
+} // namespace
+
+// Created and stored in unique_ptr on UI.
+// Binds request, receives messages and destroys on IO.
+class DevToolsSession::IOSession : public mojom::blink::DevToolsSession {
+ public:
+ IOSession(scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
+ scoped_refptr<InspectorTaskRunner> inspector_task_runner,
+ CrossThreadWeakPersistent<::blink::DevToolsSession> session,
+ mojom::blink::DevToolsSessionRequest request)
+ : io_task_runner_(io_task_runner),
+ inspector_task_runner_(inspector_task_runner),
+ session_(std::move(session)),
+ binding_(this) {
+ io_task_runner->PostTask(
+ FROM_HERE, ConvertToBaseCallback(CrossThreadBind(
+ &IOSession::BindInterface, CrossThreadUnretained(this),
+ WTF::Passed(std::move(request)))));
+ }
+
+ ~IOSession() override {}
+
+ void BindInterface(mojom::blink::DevToolsSessionRequest request) {
+ binding_.Bind(std::move(request), io_task_runner_);
+ }
+
+ void DeleteSoon() { io_task_runner_->DeleteSoon(FROM_HERE, this); }
+
+ // mojom::blink::DevToolsSession implementation.
+ void DispatchProtocolCommand(int call_id,
+ const String& method,
+ const String& message) override {
+ DCHECK(ShouldInterruptForMethod(method));
+ // Crash renderer.
+ if (method == "Page.crash")
+ CHECK(false);
+ inspector_task_runner_->AppendTask(
+ CrossThreadBind(&DevToolsSession::DispatchProtocolCommand, session_,
+ call_id, method, message));
+ }
+
+ private:
+ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
+ scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
+ CrossThreadWeakPersistent<::blink::DevToolsSession> session_;
+ mojo::Binding<mojom::blink::DevToolsSession> binding_;
+
+ DISALLOW_COPY_AND_ASSIGN(IOSession);
+};
+
+DevToolsSession::DevToolsSession(
+ DevToolsAgent* agent,
+ mojom::blink::DevToolsSessionHostAssociatedPtrInfo host_ptr_info,
+ mojom::blink::DevToolsSessionAssociatedRequest main_request,
+ mojom::blink::DevToolsSessionRequest io_request,
+ mojom::blink::DevToolsSessionStatePtr reattach_session_state)
+ : agent_(agent),
+ binding_(this, std::move(main_request)),
+ inspector_backend_dispatcher_(new protocol::UberDispatcher(this)),
+ session_state_(std::move(reattach_session_state)),
+ v8_session_state_(kV8StateKey),
+ v8_session_state_json_(&v8_session_state_, /*default_value=*/String()) {
+ io_session_ =
+ new IOSession(agent_->io_task_runner_, agent_->inspector_task_runner_,
+ WrapCrossThreadWeakPersistent(this), std::move(io_request));
+
+ host_ptr_.Bind(std::move(host_ptr_info));
+ host_ptr_.set_connection_error_handler(
+ WTF::Bind(&DevToolsSession::Detach, WrapWeakPersistent(this)));
+
+ bool restore = !!session_state_.ReattachState();
+ v8_session_state_.InitFrom(&session_state_);
+ agent_->client_->AttachSession(this, restore);
+ agent_->probe_sink_->addDevToolsSession(this);
+ if (restore) {
+ for (wtf_size_t i = 0; i < agents_.size(); i++)
+ agents_[i]->Restore();
+ }
+}
+
+DevToolsSession::~DevToolsSession() {
+ DCHECK(IsDetached());
+}
+
+void DevToolsSession::ConnectToV8(v8_inspector::V8Inspector* inspector,
+ int context_group_id) {
+ v8_session_ =
+ inspector->connect(context_group_id, this,
+ ToV8InspectorStringView(v8_session_state_json_.Get()));
+}
+
+bool DevToolsSession::IsDetached() {
+ return !host_ptr_.is_bound();
+}
+
+void DevToolsSession::Append(InspectorAgent* agent) {
+ agents_.push_back(agent);
+ agent->Init(agent_->probe_sink_.Get(), inspector_backend_dispatcher_.get(),
+ &session_state_);
+}
+
+void DevToolsSession::Detach() {
+ agent_->client_->DebuggerTaskStarted();
+ agent_->client_->DetachSession(this);
+ agent_->sessions_.erase(this);
+ binding_.Close();
+ host_ptr_.reset();
+ io_session_->DeleteSoon();
+ io_session_ = nullptr;
+ agent_->probe_sink_->removeDevToolsSession(this);
+ inspector_backend_dispatcher_.reset();
+ for (wtf_size_t i = agents_.size(); i > 0; i--)
+ agents_[i - 1]->Dispose();
+ agents_.clear();
+ v8_session_.reset();
+ agent_->client_->DebuggerTaskFinished();
+}
+
+void DevToolsSession::FlushProtocolNotifications() {
+ flushProtocolNotifications();
+}
+
+void DevToolsSession::DispatchProtocolCommand(int call_id,
+ const String& method,
+ const String& message) {
+ // IOSession does not provide ordering guarantees relative to
+ // Session, so a command may come to IOSession after Session is detached,
+ // and get posted to main thread to this method.
+ //
+ // At the same time, Session may not be garbage collected yet
+ // (even though already detached), and CrossThreadWeakPersistent<Session>
+ // will still be valid.
+ //
+ // Both these factors combined may lead to this method being called after
+ // detach, so we have to check it here.
+ if (IsDetached())
+ return;
+ agent_->client_->DebuggerTaskStarted();
+ if (v8_inspector::V8InspectorSession::canDispatchMethod(
+ ToV8InspectorStringView(method))) {
+ v8_session_->dispatchProtocolMessage(ToV8InspectorStringView(message));
+ } else {
+ inspector_backend_dispatcher_->dispatch(
+ call_id, method, protocol::StringUtil::parseJSON(message), message);
+ }
+ agent_->client_->DebuggerTaskFinished();
+}
+
+void DevToolsSession::DidStartProvisionalLoad(LocalFrame* frame) {
+ if (v8_session_ && agent_->inspected_frames_->Root() == frame) {
+ v8_session_->setSkipAllPauses(true);
+ v8_session_->resume();
+ }
+}
+
+void DevToolsSession::DidFailProvisionalLoad(LocalFrame* frame) {
+ if (v8_session_ && agent_->inspected_frames_->Root() == frame)
+ v8_session_->setSkipAllPauses(false);
+}
+
+void DevToolsSession::DidCommitLoad(LocalFrame* frame, DocumentLoader*) {
+ for (wtf_size_t i = 0; i < agents_.size(); i++)
+ agents_[i]->DidCommitLoadForLocalFrame(frame);
+ if (v8_session_ && agent_->inspected_frames_->Root() == frame)
+ v8_session_->setSkipAllPauses(false);
+}
+
+void DevToolsSession::sendProtocolResponse(
+ int call_id,
+ std::unique_ptr<protocol::Serializable> message) {
+ SendProtocolResponse(call_id, message->serialize());
+}
+
+void DevToolsSession::fallThrough(int call_id,
+ const String& method,
+ const String& message) {
+ // There's no other layer to handle the command.
+ NOTREACHED();
+}
+
+void DevToolsSession::sendResponse(
+ int call_id,
+ std::unique_ptr<v8_inspector::StringBuffer> message) {
+ // We can potentially avoid copies if WebString would convert to utf8 right
+ // from StringView, but it uses StringImpl itself, so we don't create any
+ // extra copies here.
+ SendProtocolResponse(call_id, ToCoreString(message->string()));
+}
+
+void DevToolsSession::SendProtocolResponse(int call_id, const String& message) {
+ if (IsDetached())
+ return;
+ flushProtocolNotifications();
+ if (v8_session_)
+ v8_session_state_json_.Set(ToCoreString(v8_session_->stateJSON()));
+ // Make tests more predictable by flushing all sessions before sending
+ // protocol response in any of them.
+ if (WebTestSupport::IsRunningWebTest())
+ agent_->FlushProtocolNotifications();
+ host_ptr_->DispatchProtocolResponse(message, call_id,
+ session_state_.TakeUpdates());
+}
+
+class DevToolsSession::Notification {
+ public:
+ static std::unique_ptr<Notification> CreateForBlink(
+ std::unique_ptr<protocol::Serializable> notification) {
+ return std::unique_ptr<Notification>(
+ new Notification(std::move(notification)));
+ }
+
+ static std::unique_ptr<Notification> CreateForV8(
+ std::unique_ptr<v8_inspector::StringBuffer> notification) {
+ return std::unique_ptr<Notification>(
+ new Notification(std::move(notification)));
+ }
+
+ explicit Notification(std::unique_ptr<protocol::Serializable> notification)
+ : blink_notification_(std::move(notification)) {}
+
+ explicit Notification(
+ std::unique_ptr<v8_inspector::StringBuffer> notification)
+ : v8_notification_(std::move(notification)) {}
+
+ String Serialize() {
+ if (blink_notification_) {
+ serialized_ = blink_notification_->serialize();
+ blink_notification_.reset();
+ } else if (v8_notification_) {
+ serialized_ = ToCoreString(v8_notification_->string());
+ v8_notification_.reset();
+ }
+ return serialized_;
+ }
+
+ private:
+ std::unique_ptr<protocol::Serializable> blink_notification_;
+ std::unique_ptr<v8_inspector::StringBuffer> v8_notification_;
+ String serialized_;
+};
+
+void DevToolsSession::sendProtocolNotification(
+ std::unique_ptr<protocol::Serializable> notification) {
+ if (IsDetached())
+ return;
+ notification_queue_.push_back(
+ Notification::CreateForBlink(std::move(notification)));
+}
+
+void DevToolsSession::sendNotification(
+ std::unique_ptr<v8_inspector::StringBuffer> notification) {
+ if (IsDetached())
+ return;
+ notification_queue_.push_back(
+ Notification::CreateForV8(std::move(notification)));
+}
+
+void DevToolsSession::flushProtocolNotifications() {
+ if (IsDetached())
+ return;
+ for (wtf_size_t i = 0; i < agents_.size(); i++)
+ agents_[i]->FlushPendingProtocolNotifications();
+ if (!notification_queue_.size())
+ return;
+ if (v8_session_)
+ v8_session_state_json_.Set(ToCoreString(v8_session_->stateJSON()));
+ for (wtf_size_t i = 0; i < notification_queue_.size(); ++i) {
+ host_ptr_->DispatchProtocolNotification(notification_queue_[i]->Serialize(),
+ session_state_.TakeUpdates());
+ }
+ notification_queue_.clear();
+}
+
+void DevToolsSession::Trace(blink::Visitor* visitor) {
+ visitor->Trace(agent_);
+ visitor->Trace(agents_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_session.h b/chromium/third_party/blink/renderer/core/inspector/devtools_session.h
index fc3e45dcee3..b187664e09f 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_session.h
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_session.h
@@ -2,10 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_SESSION_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_SESSION_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_DEVTOOLS_SESSION_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_DEVTOOLS_SESSION_H_
#include "base/macros.h"
+#include "mojo/public/cpp/bindings/associated_binding.h"
#include "third_party/blink/public/web/devtools_agent.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/inspector/inspector_session_state.h"
@@ -18,67 +19,56 @@
namespace blink {
+class DevToolsAgent;
+class DocumentLoader;
class InspectorAgent;
-class InspectedFrames;
-class CoreProbeSink;
class LocalFrame;
-class CORE_EXPORT InspectorSession
- : public GarbageCollectedFinalized<InspectorSession>,
+class CORE_EXPORT DevToolsSession
+ : public GarbageCollectedFinalized<DevToolsSession>,
+ public mojom::blink::DevToolsSession,
public protocol::FrontendChannel,
public v8_inspector::V8Inspector::Channel {
public:
- class Client {
- public:
- virtual void SendProtocolResponse(
- int session_id,
- int call_id,
- const String& response,
- mojom::blink::DevToolsSessionStatePtr updates) = 0;
- virtual void SendProtocolNotification(
- int session_id,
- const String& message,
- mojom::blink::DevToolsSessionStatePtr updates) = 0;
- virtual ~Client() = default;
- };
-
- InspectorSession(
- Client*,
- CoreProbeSink*,
- InspectedFrames*,
- int session_id,
- v8_inspector::V8Inspector*,
- int context_group_id,
+ DevToolsSession(
+ DevToolsAgent*,
+ mojom::blink::DevToolsSessionHostAssociatedPtrInfo host_ptr_info,
+ mojom::blink::DevToolsSessionAssociatedRequest main_request,
+ mojom::blink::DevToolsSessionRequest io_request,
mojom::blink::DevToolsSessionStatePtr reattach_session_state);
- ~InspectorSession() override;
- // TODO(dgozman): remove session id once WokrerInspectorController
- // does not use it anymore.
- int SessionId() { return session_id_; }
+ ~DevToolsSession() override;
+
+ void ConnectToV8(v8_inspector::V8Inspector*, int context_group_id);
v8_inspector::V8InspectorSession* V8Session() { return v8_session_.get(); }
void Append(InspectorAgent*);
- void Restore();
- void Dispose();
+ void Detach();
+ void FlushProtocolNotifications();
+ void Trace(blink::Visitor*);
+
+ // Core probes.
void DidStartProvisionalLoad(LocalFrame*);
void DidFailProvisionalLoad(LocalFrame*);
- void DidCommitLoadForLocalFrame(LocalFrame*);
- void DispatchProtocolMessage(int call_id,
- const String& method,
- const String& message);
- void DispatchProtocolMessage(const String& message);
- void flushProtocolNotifications() override;
+ void DidCommitLoad(LocalFrame*, DocumentLoader*);
- void Trace(blink::Visitor*);
+ private:
+ class IOSession;
- static bool ShouldInterruptForMethod(const String& method);
+ // mojom::blink::DevToolsSession implementation.
+ void DispatchProtocolCommand(int call_id,
+ const String& method,
+ const String& message) override;
- private:
// protocol::FrontendChannel implementation.
void sendProtocolResponse(
int call_id,
std::unique_ptr<protocol::Serializable> message) override;
void sendProtocolNotification(
std::unique_ptr<protocol::Serializable> message) override;
+ void fallThrough(int call_id,
+ const String& method,
+ const String& message) override;
+ void flushProtocolNotifications() override;
// v8_inspector::V8Inspector::Channel implementation.
void sendResponse(
@@ -87,17 +77,14 @@ class CORE_EXPORT InspectorSession
void sendNotification(
std::unique_ptr<v8_inspector::StringBuffer> message) override;
+ bool IsDetached();
void SendProtocolResponse(int call_id, const String& message);
- void fallThrough(int call_id,
- const String& method,
- const String& message) override;
- Client* client_;
+ Member<DevToolsAgent> agent_;
+ mojo::AssociatedBinding<mojom::blink::DevToolsSession> binding_;
+ mojom::blink::DevToolsSessionHostAssociatedPtr host_ptr_;
+ IOSession* io_session_;
std::unique_ptr<v8_inspector::V8InspectorSession> v8_session_;
- int session_id_;
- bool disposed_;
- Member<CoreProbeSink> instrumenting_agents_;
- Member<InspectedFrames> inspected_frames_;
std::unique_ptr<protocol::UberDispatcher> inspector_backend_dispatcher_;
InspectorSessionState session_state_;
HeapVector<Member<InspectorAgent>> agents_;
@@ -106,9 +93,9 @@ class CORE_EXPORT InspectorSession
InspectorAgentState v8_session_state_;
InspectorAgentState::String v8_session_state_json_;
- DISALLOW_COPY_AND_ASSIGN(InspectorSession);
+ DISALLOW_COPY_AND_ASSIGN(DevToolsSession);
};
} // namespace blink
-#endif // !defined(InspectorSession_h)
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_DEVTOOLS_SESSION_H_
diff --git a/chromium/third_party/blink/renderer/core/inspector/dom_editor.cc b/chromium/third_party/blink/renderer/core/inspector/dom_editor.cc
index 973608f7832..80f56824c3e 100644
--- a/chromium/third_party/blink/renderer/core/inspector/dom_editor.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/dom_editor.cc
@@ -94,8 +94,8 @@ class DOMEditor::InsertBeforeAction final : public InspectorHistory::Action {
bool Perform(ExceptionState& exception_state) override {
if (node_->parentNode()) {
- remove_child_action_ =
- new RemoveChildAction(node_->parentNode(), node_.Get());
+ remove_child_action_ = MakeGarbageCollected<RemoveChildAction>(
+ node_->parentNode(), node_.Get());
if (!remove_child_action_->Perform(exception_state))
return false;
}
@@ -225,8 +225,8 @@ class DOMEditor::SetOuterHTMLAction final : public InspectorHistory::Action {
next_sibling_(node->nextSibling()),
html_(html),
new_node_(nullptr),
- history_(new InspectorHistory()),
- dom_editor_(new DOMEditor(history_.Get())) {}
+ history_(MakeGarbageCollected<InspectorHistory>()),
+ dom_editor_(MakeGarbageCollected<DOMEditor>(history_.Get())) {}
bool Perform(ExceptionState& exception_state) override {
old_html_ = CreateMarkup(node_.Get());
@@ -384,14 +384,16 @@ bool DOMEditor::InsertBefore(ContainerNode* parent_node,
Node* anchor_node,
ExceptionState& exception_state) {
return history_->Perform(
- new InsertBeforeAction(parent_node, node, anchor_node), exception_state);
+ MakeGarbageCollected<InsertBeforeAction>(parent_node, node, anchor_node),
+ exception_state);
}
bool DOMEditor::RemoveChild(ContainerNode* parent_node,
Node* node,
ExceptionState& exception_state) {
- return history_->Perform(new RemoveChildAction(parent_node, node),
- exception_state);
+ return history_->Perform(
+ MakeGarbageCollected<RemoveChildAction>(parent_node, node),
+ exception_state);
}
bool DOMEditor::SetAttribute(Element* element,
@@ -399,7 +401,8 @@ bool DOMEditor::SetAttribute(Element* element,
const String& value,
ExceptionState& exception_state) {
return history_->Perform(
- new SetAttributeAction(element, AtomicString(name), AtomicString(value)),
+ MakeGarbageCollected<SetAttributeAction>(element, AtomicString(name),
+ AtomicString(value)),
exception_state);
}
@@ -407,14 +410,16 @@ bool DOMEditor::RemoveAttribute(Element* element,
const String& name,
ExceptionState& exception_state) {
return history_->Perform(
- new RemoveAttributeAction(element, AtomicString(name)), exception_state);
+ MakeGarbageCollected<RemoveAttributeAction>(element, AtomicString(name)),
+ exception_state);
}
bool DOMEditor::SetOuterHTML(Node* node,
const String& html,
Node** new_node,
ExceptionState& exception_state) {
- SetOuterHTMLAction* action = new SetOuterHTMLAction(node, html);
+ SetOuterHTMLAction* action =
+ MakeGarbageCollected<SetOuterHTMLAction>(node, html);
bool result = history_->Perform(action, exception_state);
if (result)
*new_node = action->NewNode();
@@ -424,24 +429,25 @@ bool DOMEditor::SetOuterHTML(Node* node,
bool DOMEditor::ReplaceWholeText(Text* text_node,
const String& text,
ExceptionState& exception_state) {
- return history_->Perform(new ReplaceWholeTextAction(text_node, text),
- exception_state);
+ return history_->Perform(
+ MakeGarbageCollected<ReplaceWholeTextAction>(text_node, text),
+ exception_state);
}
bool DOMEditor::ReplaceChild(ContainerNode* parent_node,
Node* new_node,
Node* old_node,
ExceptionState& exception_state) {
- return history_->Perform(
- new ReplaceChildNodeAction(parent_node, new_node, old_node),
- exception_state);
+ return history_->Perform(MakeGarbageCollected<ReplaceChildNodeAction>(
+ parent_node, new_node, old_node),
+ exception_state);
}
bool DOMEditor::SetNodeValue(Node* node,
const String& value,
ExceptionState& exception_state) {
- return history_->Perform(new SetNodeValueAction(node, value),
- exception_state);
+ return history_->Perform(
+ MakeGarbageCollected<SetNodeValueAction>(node, value), exception_state);
}
static Response ToResponse(ExceptionState& exception_state) {
diff --git a/chromium/third_party/blink/renderer/core/inspector/dom_patch_support.cc b/chromium/third_party/blink/renderer/core/inspector/dom_patch_support.cc
index dd0b3ab8190..2c51503b789 100644
--- a/chromium/third_party/blink/renderer/core/inspector/dom_patch_support.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/dom_patch_support.cc
@@ -434,7 +434,7 @@ bool DOMPatchSupport::InnerPatchChildren(
DOMPatchSupport::Digest* DOMPatchSupport::CreateDigest(
Node* node,
UnusedNodesMap* unused_nodes_map) {
- Digest* digest = new Digest(node);
+ Digest* digest = MakeGarbageCollected<Digest>(node);
std::unique_ptr<WebCryptoDigestor> digestor =
CreateDigestor(kHashAlgorithmSha1);
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc
index a740f0a1754..a4b87bc9279 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc
@@ -84,9 +84,9 @@ void InspectorAnimationAgent::DidCommitLoadForLocalFrame(LocalFrame* frame) {
static std::unique_ptr<protocol::Animation::AnimationEffect>
BuildObjectForAnimationEffect(KeyframeEffect* effect, bool is_transition) {
- ComputedEffectTiming computed_timing = effect->getComputedTiming();
- double delay = computed_timing.delay();
- double duration = computed_timing.duration().GetAsUnrestrictedDouble();
+ ComputedEffectTiming* computed_timing = effect->getComputedTiming();
+ double delay = computed_timing->delay();
+ double duration = computed_timing->duration().GetAsUnrestrictedDouble();
String easing = effect->SpecifiedTiming().timing_function->ToString();
if (is_transition) {
@@ -105,12 +105,12 @@ BuildObjectForAnimationEffect(KeyframeEffect* effect, bool is_transition) {
std::unique_ptr<protocol::Animation::AnimationEffect> animation_object =
protocol::Animation::AnimationEffect::create()
.setDelay(delay)
- .setEndDelay(computed_timing.endDelay())
- .setIterationStart(computed_timing.iterationStart())
- .setIterations(computed_timing.iterations())
+ .setEndDelay(computed_timing->endDelay())
+ .setIterationStart(computed_timing->iterationStart())
+ .setIterations(computed_timing->iterations())
.setDuration(duration)
- .setDirection(computed_timing.direction())
- .setFill(computed_timing.fill())
+ .setDirection(computed_timing->direction())
+ .setFill(computed_timing->fill())
.setEasing(easing)
.build();
if (effect->target()) {
@@ -383,15 +383,15 @@ Response InspectorAnimationAgent::setTiming(const String& animation_id,
UnrestrictedDoubleOrString unrestricted_duration;
unrestricted_duration.SetUnrestrictedDouble(duration + delay);
- OptionalEffectTiming timing;
- timing.setDuration(unrestricted_duration);
+ OptionalEffectTiming* timing = OptionalEffectTiming::Create();
+ timing->setDuration(unrestricted_duration);
effect->updateTiming(timing, exception_state);
} else {
- OptionalEffectTiming timing;
+ OptionalEffectTiming* timing = OptionalEffectTiming::Create();
UnrestrictedDoubleOrString unrestricted_duration;
unrestricted_duration.SetUnrestrictedDouble(duration);
- timing.setDuration(unrestricted_duration);
- timing.setDelay(delay);
+ timing->setDuration(unrestricted_duration);
+ timing->setDelay(delay);
animation->effect()->updateTiming(timing, exception_state);
}
return Response::OK();
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h
index 8853a40b9c2..2cde4bc3d10 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h
@@ -42,8 +42,11 @@ class CORE_EXPORT InspectorApplicationCacheAgent final
public:
static InspectorApplicationCacheAgent* Create(
InspectedFrames* inspected_frames) {
- return new InspectorApplicationCacheAgent(inspected_frames);
+ return MakeGarbageCollected<InspectorApplicationCacheAgent>(
+ inspected_frames);
}
+
+ explicit InspectorApplicationCacheAgent(InspectedFrames*);
~InspectorApplicationCacheAgent() override = default;
void Trace(blink::Visitor*) override;
@@ -71,7 +74,6 @@ class CORE_EXPORT InspectorApplicationCacheAgent final
// Unconditionally enables the agent, even if |enabled_.Get()==true|.
// For idempotence, call enable().
void InnerEnable();
- explicit InspectorApplicationCacheAgent(InspectedFrames*);
std::unique_ptr<protocol::ApplicationCache::ApplicationCache>
BuildObjectForApplicationCache(const ApplicationCacheHost::ResourceInfoList&,
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc
index ea1ce1399ab..a08852239d1 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc
@@ -16,7 +16,7 @@ namespace blink {
using protocol::Maybe;
using protocol::Response;
-namespace EncodingEnum = protocol::Audits::GetEncodedResponse::EncodingEnum;
+namespace encoding_enum = protocol::Audits::GetEncodedResponse::EncodingEnum;
namespace {
@@ -79,11 +79,11 @@ protocol::Response InspectorAuditsAgent::getEncodedResponse(
const String& encoding,
Maybe<double> quality,
Maybe<bool> size_only,
- Maybe<String>* out_body,
+ Maybe<protocol::Binary>* out_body,
int* out_original_size,
int* out_encoded_size) {
- DCHECK(encoding == EncodingEnum::Jpeg || encoding == EncodingEnum::Png ||
- encoding == EncodingEnum::Webp);
+ DCHECK(encoding == encoding_enum::Jpeg || encoding == encoding_enum::Png ||
+ encoding == encoding_enum::Webp);
String body;
bool is_base64_encoded;
@@ -105,11 +105,12 @@ protocol::Response InspectorAuditsAgent::getEncodedResponse(
return Response::Error("Could not encode image with given settings");
}
- if (!size_only.fromMaybe(false))
- *out_body = Base64Encode(encoded_image);
-
*out_original_size = static_cast<int>(base64_decoded_buffer.size());
*out_encoded_size = static_cast<int>(encoded_image.size());
+
+ if (!size_only.fromMaybe(false)) {
+ *out_body = protocol::Binary::fromVector(std::move(encoded_image));
+ }
return Response::OK();
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.h
index 06a359f40e2..966524e3e40 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_audits_agent.h
@@ -21,13 +21,14 @@ class CORE_EXPORT InspectorAuditsAgent final
void Trace(blink::Visitor*) override;
// Protocol methods.
- protocol::Response getEncodedResponse(const String& request_id,
- const String& encoding,
- protocol::Maybe<double> quality,
- protocol::Maybe<bool> size_only,
- protocol::Maybe<String>* out_body,
- int* out_original_size,
- int* out_encoded_size) override;
+ protocol::Response getEncodedResponse(
+ const String& request_id,
+ const String& encoding,
+ protocol::Maybe<double> quality,
+ protocol::Maybe<bool> size_only,
+ protocol::Maybe<protocol::Binary>* out_body,
+ int* out_original_size,
+ int* out_encoded_size) override;
private:
Member<InspectorNetworkAgent> network_agent_;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
index 379dfd69885..0e2d2e8bc0d 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/css/css_import_rule.h"
#include "third_party/blink/renderer/core/css/css_keyframe_rule.h"
#include "third_party/blink/renderer/core/css/css_media_rule.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_rule.h"
#include "third_party/blink/renderer/core/css/css_rule_list.h"
@@ -56,7 +57,6 @@
#include "third_party/blink/renderer/core/css/style_sheet.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/css/style_sheet_list.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/node.h"
@@ -90,6 +90,7 @@
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_custom_platform_data.h"
#include "third_party/blink/renderer/platform/fonts/shaping/caching_word_shaper.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_concatenate.h"
@@ -209,7 +210,7 @@ void AddColorsFromImageStyle(const ComputedStyle& style,
bool& found_non_transparent_color,
const LayoutObject& layout_object) {
const FillLayer& background_layers = style.BackgroundLayers();
- if (!background_layers.HasImage())
+ if (!background_layers.AnyLayerHasImage())
return;
StyleImage* style_image = background_layers.GetImage();
@@ -806,7 +807,8 @@ void InspectorCSSAgent::SetActiveStyleSheets(
HeapHashSet<Member<CSSStyleSheet>>* document_css_style_sheets =
document_to_css_style_sheets_.at(document);
if (!document_css_style_sheets) {
- document_css_style_sheets = new HeapHashSet<Member<CSSStyleSheet>>();
+ document_css_style_sheets =
+ MakeGarbageCollected<HeapHashSet<Member<CSSStyleSheet>>>();
document_to_css_style_sheets_.Set(document, document_css_style_sheets);
}
@@ -1186,7 +1188,7 @@ void InspectorCSSAgent::CollectPlatformFontsForLayoutObject(
DCHECK(fragment->PhysicalFragment().IsText());
const NGPhysicalTextFragment& text_fragment =
ToNGPhysicalTextFragment(fragment->PhysicalFragment());
- const ShapeResult* shape_result = text_fragment.TextShapeResult();
+ const ShapeResultView* shape_result = text_fragment.TextShapeResult();
if (!shape_result)
continue;
Vector<ShapeResult::RunFontData> run_font_data_list;
@@ -1279,9 +1281,9 @@ Response InspectorCSSAgent::setStyleSheetText(
return response;
DummyExceptionStateForTesting exception_state;
- dom_agent_->History()->Perform(
- new SetStyleSheetTextAction(inspector_style_sheet, text),
- exception_state);
+ dom_agent_->History()->Perform(MakeGarbageCollected<SetStyleSheetTextAction>(
+ inspector_style_sheet, text),
+ exception_state);
response = InspectorDOMAgent::ToResponse(exception_state);
if (!response.isSuccess())
return response;
@@ -1338,9 +1340,9 @@ Response InspectorCSSAgent::setRuleSelector(
return response;
DummyExceptionStateForTesting exception_state;
- ModifyRuleAction* action =
- new ModifyRuleAction(ModifyRuleAction::kSetRuleSelector,
- inspector_style_sheet, selector_range, selector);
+ ModifyRuleAction* action = MakeGarbageCollected<ModifyRuleAction>(
+ ModifyRuleAction::kSetRuleSelector, inspector_style_sheet, selector_range,
+ selector);
bool success = dom_agent_->History()->Perform(action, exception_state);
if (success) {
CSSStyleRule* rule = InspectorCSSAgent::AsCSSStyleRule(action->TakeRule());
@@ -1371,9 +1373,9 @@ Response InspectorCSSAgent::setKeyframeKey(
return response;
DummyExceptionStateForTesting exception_state;
- ModifyRuleAction* action =
- new ModifyRuleAction(ModifyRuleAction::kSetKeyframeKey,
- inspector_style_sheet, key_range, key_text);
+ ModifyRuleAction* action = MakeGarbageCollected<ModifyRuleAction>(
+ ModifyRuleAction::kSetKeyframeKey, inspector_style_sheet, key_range,
+ key_text);
bool success = dom_agent_->History()->Perform(action, exception_state);
if (success) {
CSSKeyframeRule* rule = ToCSSKeyframeRule(action->TakeRule());
@@ -1421,10 +1423,11 @@ Response InspectorCSSAgent::MultipleStyleTextsActions(
static_cast<InspectorStyleSheetForInlineStyle*>(
inspector_style_sheet);
SetElementStyleAction* action =
- new SetElementStyleAction(inline_style_sheet, edit->getText());
+ MakeGarbageCollected<SetElementStyleAction>(inline_style_sheet,
+ edit->getText());
actions->push_back(action);
} else {
- ModifyRuleAction* action = new ModifyRuleAction(
+ ModifyRuleAction* action = MakeGarbageCollected<ModifyRuleAction>(
ModifyRuleAction::kSetStyleText,
static_cast<InspectorStyleSheet*>(inspector_style_sheet), range,
edit->getText());
@@ -1483,14 +1486,14 @@ Response InspectorCSSAgent::SetStyleText(
InspectorStyleSheetForInlineStyle* inline_style_sheet =
static_cast<InspectorStyleSheetForInlineStyle*>(inspector_style_sheet);
SetElementStyleAction* action =
- new SetElementStyleAction(inline_style_sheet, text);
+ MakeGarbageCollected<SetElementStyleAction>(inline_style_sheet, text);
bool success = dom_agent_->History()->Perform(action, exception_state);
if (success) {
result = inline_style_sheet->InlineStyle();
return Response::OK();
}
} else {
- ModifyRuleAction* action = new ModifyRuleAction(
+ ModifyRuleAction* action = MakeGarbageCollected<ModifyRuleAction>(
ModifyRuleAction::kSetStyleText,
static_cast<InspectorStyleSheet*>(inspector_style_sheet), range, text);
bool success = dom_agent_->History()->Perform(action, exception_state);
@@ -1527,9 +1530,9 @@ Response InspectorCSSAgent::setMediaText(
return response;
DummyExceptionStateForTesting exception_state;
- ModifyRuleAction* action =
- new ModifyRuleAction(ModifyRuleAction::kSetMediaRuleText,
- inspector_style_sheet, text_range, text);
+ ModifyRuleAction* action = MakeGarbageCollected<ModifyRuleAction>(
+ ModifyRuleAction::kSetMediaRuleText, inspector_style_sheet, text_range,
+ text);
bool success = dom_agent_->History()->Perform(action, exception_state);
if (success) {
CSSMediaRule* rule = InspectorCSSAgent::AsCSSMediaRule(action->TakeRule());
@@ -1583,8 +1586,8 @@ Response InspectorCSSAgent::addRule(
return response;
DummyExceptionStateForTesting exception_state;
- AddRuleAction* action =
- new AddRuleAction(inspector_style_sheet, rule_text, rule_location);
+ AddRuleAction* action = MakeGarbageCollected<AddRuleAction>(
+ inspector_style_sheet, rule_text, rule_location);
bool success = dom_agent_->History()->Perform(action, exception_state);
if (!success)
return InspectorDOMAgent::ToResponse(exception_state);
@@ -1621,7 +1624,7 @@ Response InspectorCSSAgent::forcePseudoState(
node_id_to_forced_pseudo_state_.erase(node_id);
element->ownerDocument()->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kInspector));
+ StyleChangeReasonForTracing::Create(style_change_reason::kInspector));
return Response::OK();
}
@@ -1655,7 +1658,8 @@ std::unique_ptr<protocol::CSS::CSSMedia> InspectorCSSAgent::BuildMediaObject(
if (Document* document = parent_style_sheet->OwnerDocument())
frame = document->GetFrame();
}
- MediaQueryEvaluator* media_evaluator = new MediaQueryEvaluator(frame);
+ MediaQueryEvaluator* media_evaluator =
+ MakeGarbageCollected<MediaQueryEvaluator>(frame);
InspectorStyleSheet* inspector_style_sheet =
parent_style_sheet
@@ -2082,7 +2086,7 @@ void InspectorCSSAgent::DidAddDocument(Document* document) {
document->GetStyleEngine().SetRuleUsageTracker(tracker_);
document->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kInspector));
+ StyleChangeReasonForTracing::Create(style_change_reason::kInspector));
}
void InspectorCSSAgent::DidRemoveDocument(Document* document) {}
@@ -2133,10 +2137,11 @@ void InspectorCSSAgent::ResetPseudoStates() {
}
node_id_to_forced_pseudo_state_.clear();
- for (auto& document : documents_to_change)
+ for (auto& document : documents_to_change) {
document->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kInspector));
+ StyleChangeReasonForTracing::Create(style_change_reason::kInspector));
+ }
}
HeapVector<Member<CSSStyleDeclaration>> InspectorCSSAgent::MatchingStyles(
@@ -2356,7 +2361,7 @@ Response InspectorCSSAgent::getBackgroundColors(
*background_colors = protocol::Array<String>::create();
for (auto color : colors) {
background_colors->fromJust()->addItem(
- color.SerializedAsCSSComponentValue());
+ cssvalue::CSSColorValue::SerializeAsCSSComponentValue(color));
}
CSSComputedStyleDeclaration* computed_style_info =
@@ -2395,7 +2400,7 @@ Response InspectorCSSAgent::getBackgroundColors(
void InspectorCSSAgent::SetCoverageEnabled(bool enabled) {
if (enabled == !!tracker_)
return;
- tracker_ = enabled ? new StyleRuleUsageTracker() : nullptr;
+ tracker_ = enabled ? MakeGarbageCollected<StyleRuleUsageTracker>() : nullptr;
for (Document* document : dom_agent_->Documents())
document->GetStyleEngine().SetRuleUsageTracker(tracker_);
@@ -2412,7 +2417,7 @@ Response InspectorCSSAgent::startRuleUsageTracking() {
for (Document* document : dom_agent_->Documents()) {
document->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kInspector));
+ StyleChangeReasonForTracing::Create(style_change_reason::kInspector));
document->UpdateStyleAndLayoutTree();
}
@@ -2421,6 +2426,8 @@ Response InspectorCSSAgent::startRuleUsageTracking() {
Response InspectorCSSAgent::stopRuleUsageTracking(
std::unique_ptr<protocol::Array<protocol::CSS::RuleUsage>>* result) {
+ for (Document* document : dom_agent_->Documents())
+ document->UpdateStyleAndLayoutTree();
Response response = takeCoverageDelta(result);
SetCoverageEnabled(false);
return response;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.h
index daf24b45595..863e80996a7 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.h
@@ -101,13 +101,19 @@ class CORE_EXPORT InspectorCSSAgent final
InspectorNetworkAgent* network_agent,
InspectorResourceContentLoader* resource_content_loader,
InspectorResourceContainer* resource_container) {
- return new InspectorCSSAgent(dom_agent, inspected_frames, network_agent,
- resource_content_loader, resource_container);
+ return MakeGarbageCollected<InspectorCSSAgent>(
+ dom_agent, inspected_frames, network_agent, resource_content_loader,
+ resource_container);
}
static void CollectAllDocumentStyleSheets(Document*,
HeapVector<Member<CSSStyleSheet>>&);
+ InspectorCSSAgent(InspectorDOMAgent*,
+ InspectedFrames*,
+ InspectorNetworkAgent*,
+ InspectorResourceContentLoader*,
+ InspectorResourceContainer*);
~InspectorCSSAgent() override;
void Trace(blink::Visitor*) override;
@@ -238,12 +244,6 @@ class CORE_EXPORT InspectorCSSAgent final
static void CollectStyleSheets(CSSStyleSheet*,
HeapVector<Member<CSSStyleSheet>>&);
- InspectorCSSAgent(InspectorDOMAgent*,
- InspectedFrames*,
- InspectorNetworkAgent*,
- InspectorResourceContentLoader*,
- InspectorResourceContainer*);
-
typedef HeapHashMap<String, Member<InspectorStyleSheet>>
IdToInspectorStyleSheet;
typedef HeapHashMap<String, Member<InspectorStyleSheetForInlineStyle>>
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc
index 2fe328d5ea0..333a9ddbe14 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc
@@ -87,7 +87,6 @@
namespace blink {
-using namespace HTMLNames;
using protocol::Maybe;
using protocol::Response;
@@ -237,7 +236,7 @@ InspectorDOMAgent::InspectorDOMAgent(
inspected_frames_(inspected_frames),
v8_session_(v8_session),
dom_listener_(nullptr),
- document_node_to_id_map_(new NodeToIdMap()),
+ document_node_to_id_map_(MakeGarbageCollected<NodeToIdMap>()),
last_node_id_(1),
suppress_attribute_modified_event_(false),
enabled_(&agent_state_, /*default_value=*/false) {}
@@ -451,8 +450,8 @@ Response InspectorDOMAgent::AssertEditableElement(int node_id,
void InspectorDOMAgent::EnableAndReset() {
enabled_.Set(true);
- history_ = new InspectorHistory();
- dom_editor_ = new DOMEditor(history_.Get());
+ history_ = MakeGarbageCollected<InspectorHistory>();
+ dom_editor_ = MakeGarbageCollected<DOMEditor>(history_.Get());
document_ = inspected_frames_->Root()->GetDocument();
instrumenting_agents_->addInspectorDOMAgent(this);
}
@@ -713,7 +712,7 @@ int InspectorDOMAgent::PushNodePathToFrontend(Node* node_to_push) {
node = parent;
// Node being pushed is detached -> push subtree root.
- NodeToIdMap* new_map = new NodeToIdMap;
+ NodeToIdMap* new_map = MakeGarbageCollected<NodeToIdMap>();
NodeToIdMap* dangling_map = new_map;
dangling_node_to_id_maps_.push_back(new_map);
std::unique_ptr<protocol::Array<protocol::DOM::Node>> children =
@@ -1140,7 +1139,7 @@ Response InspectorDOMAgent::NodeForRemoteObjectId(const String& object_id,
if (!v8_session_->unwrapObject(&error, ToV8InspectorStringView(object_id),
&value, &context, nullptr))
return Response::Error(ToCoreString(std::move(error)));
- if (!V8Node::hasInstance(value, isolate_))
+ if (!V8Node::HasInstance(value, isolate_))
return Response::Error("Object id doesn't reference a Node");
node = V8Node::ToImpl(v8::Local<v8::Object>::Cast(value));
if (!node) {
@@ -1270,7 +1269,7 @@ Response InspectorDOMAgent::setFileInputFiles(
if (!response.isSuccess())
return response;
if (!IsHTMLInputElement(*node) ||
- ToHTMLInputElement(*node).type() != InputTypeNames::file)
+ ToHTMLInputElement(*node).type() != input_type_names::kFile)
return Response::Error("Node is not a file input element");
Vector<String> paths;
@@ -1968,7 +1967,7 @@ void InspectorDOMAgent::CharacterDataModified(CharacterData* character_data) {
InspectorRevalidateDOMTask* InspectorDOMAgent::RevalidateTask() {
if (!revalidate_task_)
- revalidate_task_ = new InspectorRevalidateDOMTask(this);
+ revalidate_task_ = MakeGarbageCollected<InspectorRevalidateDOMTask>(this);
return revalidate_task_.Get();
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc
index 6c8165eca41..31f427113af 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc
@@ -430,8 +430,8 @@ int InspectorDOMSnapshotAgent::VisitNode(Node* node,
if (auto* input_element = ToHTMLInputElementOrNull(*element)) {
value->setInputValue(input_element->value());
- if ((input_element->type() == InputTypeNames::radio) ||
- (input_element->type() == InputTypeNames::checkbox)) {
+ if ((input_element->type() == input_type_names::kRadio) ||
+ (input_element->type() == input_type_names::kCheckbox)) {
value->setInputChecked(input_element->checked());
}
}
@@ -647,8 +647,8 @@ int InspectorDOMSnapshotAgent::VisitNode2(Node* node, int parent_index) {
if (auto* input_element = ToHTMLInputElementOrNull(*element)) {
SetRare(nodes->getInputValue(nullptr), index, input_element->value());
- if ((input_element->type() == InputTypeNames::radio) ||
- (input_element->type() == InputTypeNames::checkbox)) {
+ if ((input_element->type() == input_type_names::kRadio) ||
+ (input_element->type() == input_type_names::kCheckbox)) {
if (input_element->checked()) {
SetRare(nodes->getInputChecked(nullptr), index);
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h
index 603dad2210f..5e29bd3199a 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_DOM_SNAPSHOT_AGENT_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/inspector/inspector_base_agent.h"
#include "third_party/blink/renderer/core/inspector/protocol/DOMSnapshot.h"
@@ -28,9 +28,11 @@ class CORE_EXPORT InspectorDOMSnapshotAgent final
static InspectorDOMSnapshotAgent* Create(
InspectedFrames* inspected_frames,
InspectorDOMDebuggerAgent* dom_debugger_agent) {
- return new InspectorDOMSnapshotAgent(inspected_frames, dom_debugger_agent);
+ return MakeGarbageCollected<InspectorDOMSnapshotAgent>(inspected_frames,
+ dom_debugger_agent);
}
+ InspectorDOMSnapshotAgent(InspectedFrames*, InspectorDOMDebuggerAgent*);
~InspectorDOMSnapshotAgent() override;
void Trace(blink::Visitor*) override;
@@ -60,7 +62,6 @@ class CORE_EXPORT InspectorDOMSnapshotAgent final
void DidInsertDOMNode(Node*);
private:
- InspectorDOMSnapshotAgent(InspectedFrames*, InspectorDOMDebuggerAgent*);
// Unconditionally enables the agent, even if |enabled_.Get()==true|.
// For idempotence, call enable().
void EnableAndReset();
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
index 84fa61c3465..8b8013da6cc 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
@@ -21,7 +21,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread_cpu_throttler.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -129,6 +129,10 @@ void InspectorEmulationAgent::Restore() {
Response InspectorEmulationAgent::disable() {
if (enabled_)
instrumenting_agents_->removeInspectorEmulationAgent(this);
+ setUserAgentOverride(String(), protocol::Maybe<String>(),
+ protocol::Maybe<String>());
+ if (!web_local_frame_)
+ return Response::OK();
setScriptExecutionDisabled(false);
setScrollbarsHidden(false);
setDocumentCookieDisabled(false);
@@ -142,8 +146,6 @@ Response InspectorEmulationAgent::disable() {
web_local_frame_->View()->Scheduler()->RemoveVirtualTimeObserver(this);
virtual_time_setup_ = false;
}
- setUserAgentOverride(String(), protocol::Maybe<String>(),
- protocol::Maybe<String>());
return Response::OK();
}
@@ -369,7 +371,7 @@ void InspectorEmulationAgent::WillSendRequest(
request.HttpHeaderField("Accept-Language").IsEmpty()) {
request.SetHTTPHeaderField(
"Accept-Language",
- AtomicString(NetworkUtils::GenerateAcceptLanguageHeader(
+ AtomicString(network_utils::GenerateAcceptLanguageHeader(
accept_language_override_.Get())));
}
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc
index 2132b81f5e9..a303dac5196 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc
@@ -19,7 +19,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/graphics/path.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -240,6 +240,20 @@ std::unique_ptr<protocol::DictionaryValue> BuildElementInfo(Element* element) {
return element_info;
}
+std::unique_ptr<protocol::DictionaryValue> BuildTextNodeInfo(Text* text_node) {
+ std::unique_ptr<protocol::DictionaryValue> text_info =
+ protocol::DictionaryValue::create();
+ LayoutObject* layout_object = text_node->GetLayoutObject();
+ if (!layout_object || !layout_object->IsText())
+ return text_info;
+ LayoutRect bounding_box = ToLayoutText(layout_object)->VisualOverflowRect();
+ text_info->setString("nodeWidth", bounding_box.Width().ToString());
+ text_info->setString("nodeHeight", bounding_box.Height().ToString());
+ text_info->setString("tagName", "#text");
+
+ return text_info;
+}
+
std::unique_ptr<protocol::Value> BuildGapAndPositions(
double origin,
LayoutUnit gap,
@@ -346,6 +360,8 @@ InspectorHighlight::InspectorHighlight(
AppendNodeHighlight(node, highlight_config);
if (append_element_info && node->IsElementNode())
element_info_ = BuildElementInfo(ToElement(node));
+ else if (append_element_info && node->IsTextNode())
+ element_info_ = BuildTextNodeInfo(ToText(node));
}
InspectorHighlight::~InspectorHighlight() = default;
@@ -421,10 +437,10 @@ void InspectorHighlight::AppendNodeHighlight(
// Just for testing, invert the content color for nodes rendered by LayoutNG.
// TODO(layout-dev): Stop munging the color before NG ships. crbug.com/869866
- Color content_color = layout_object->IsLayoutNGObject() &&
- !LayoutTestSupport::IsRunningLayoutTest()
- ? Color(highlight_config.content.Rgb() ^ 0x00ffffff)
- : highlight_config.content;
+ Color content_color =
+ layout_object->IsLayoutNGObject() && !WebTestSupport::IsRunningWebTest()
+ ? Color(highlight_config.content.Rgb() ^ 0x00ffffff)
+ : highlight_config.content;
Vector<FloatQuad> svg_quads;
if (BuildSVGQuads(node, svg_quads)) {
@@ -606,7 +622,8 @@ bool InspectorHighlight::BuildNodeQuads(Node* node,
LocalFrameView* containing_view = layout_object->GetFrameView();
if (!containing_view)
return false;
- if (!layout_object->IsBox() && !layout_object->IsLayoutInline())
+ if (!layout_object->IsBox() && !layout_object->IsLayoutInline() &&
+ !layout_object->IsText())
return false;
LayoutRect content_box;
@@ -614,7 +631,14 @@ bool InspectorHighlight::BuildNodeQuads(Node* node,
LayoutRect border_box;
LayoutRect margin_box;
- if (layout_object->IsBox()) {
+ if (layout_object->IsText()) {
+ LayoutText* layout_text = ToLayoutText(layout_object);
+ LayoutRect text_rect = layout_text->VisualOverflowRect();
+ content_box = text_rect;
+ padding_box = text_rect;
+ border_box = text_rect;
+ margin_box = text_rect;
+ } else if (layout_object->IsBox()) {
LayoutBox* layout_box = ToLayoutBox(layout_object);
// LayoutBox returns the "pure" content area box, exclusive of the
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_io_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_io_agent.cc
index be530e502f0..dc913e60697 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_io_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_io_agent.cc
@@ -27,7 +27,7 @@ Response InspectorIOAgent::resolveBlob(const String& object_id, String* uuid) {
&value, &context, nullptr))
return Response::Error(ToCoreString(std::move(error)));
- if (!V8Blob::hasInstance(value, isolate_))
+ if (!V8Blob::HasInstance(value, isolate_))
return Response::Error("Object id doesn't reference a Blob");
Blob* blob = V8Blob::ToImpl(v8::Local<v8::Object>::Cast(value));
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc
index 0b09500e86d..0188270a673 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc
@@ -57,8 +57,9 @@
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/picture_snapshot.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
-#include "third_party/blink/renderer/platform/wtf/text/base64.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+#include "third_party/skia/include/core/SkPicture.h"
+#include "third_party/skia/include/core/SkRefCnt.h"
#include "ui/gfx/geometry/rect.h"
namespace blink {
@@ -478,8 +479,9 @@ Response InspectorLayerTreeAgent::loadSnapshot(
protocol::LayerTree::PictureTile* tile = tiles->get(i);
decoded_tiles[i] = base::AdoptRef(new PictureSnapshot::TilePictureStream());
decoded_tiles[i]->layer_offset.Set(tile->getX(), tile->getY());
- if (!Base64Decode(tile->getPicture(), decoded_tiles[i]->data))
- return Response::Error("Invalid base64 encoding");
+ const protocol::Binary& data = tile->getPicture();
+ decoded_tiles[i]->picture =
+ SkPicture::MakeFromData(data.data(), data.size());
}
scoped_refptr<PictureSnapshot> snapshot =
PictureSnapshot::Load(decoded_tiles);
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.h
index 8b68ba114d5..cb022887be5 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.h
@@ -60,9 +60,11 @@ class CORE_EXPORT InspectorLayerTreeAgent final
static InspectorLayerTreeAgent* Create(InspectedFrames* inspected_frames,
Client* client) {
- return new InspectorLayerTreeAgent(inspected_frames, client);
+ return MakeGarbageCollected<InspectorLayerTreeAgent>(inspected_frames,
+ client);
}
+ InspectorLayerTreeAgent(InspectedFrames*, Client*);
~InspectorLayerTreeAgent() override;
void Trace(blink::Visitor*) override;
@@ -107,8 +109,6 @@ class CORE_EXPORT InspectorLayerTreeAgent final
private:
static unsigned last_snapshot_id_;
- InspectorLayerTreeAgent(InspectedFrames*, Client*);
-
GraphicsLayer* RootGraphicsLayer();
PaintLayerCompositor* GetPaintLayerCompositor();
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.h
index e89c94d0016..eb02549afa0 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.h
@@ -44,11 +44,13 @@ class CORE_EXPORT InspectorMemoryAgent final
: public InspectorBaseAgent<protocol::Memory::Metainfo> {
public:
static InspectorMemoryAgent* Create(InspectedFrames* frames) {
- return new InspectorMemoryAgent(frames);
+ return MakeGarbageCollected<InspectorMemoryAgent>(frames);
}
- ~InspectorMemoryAgent() override;
+ explicit InspectorMemoryAgent(InspectedFrames*);
+ ~InspectorMemoryAgent() override;
void Trace(blink::Visitor*) override;
+
void Restore() override;
protocol::Response getDOMCounters(int* documents,
@@ -66,8 +68,6 @@ class CORE_EXPORT InspectorMemoryAgent final
std::unique_ptr<protocol::Memory::SamplingProfile>*) override;
private:
- explicit InspectorMemoryAgent(InspectedFrames*);
-
std::vector<std::string> Symbolize(const std::vector<void*>& addresses);
std::unique_ptr<protocol::Memory::SamplingProfile> GetSamplingProfileById(
uint32_t id);
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
index f92bf229bdf..4ab6d6c4648 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -36,6 +36,7 @@
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "build/build_config.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "services/network/public/mojom/request_context_frame_type.mojom-shared.h"
#include "services/network/public/mojom/websocket.mojom-blink.h"
#include "third_party/blink/public/platform/task_type.h"
@@ -77,7 +78,6 @@
#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -186,7 +186,7 @@ class InspectorFileReaderLoaderClient final : public FileReaderLoaderClient {
void DidFinishLoading() override { Done(raw_data_); }
- void DidFail(FileError::ErrorCode) override { Done(nullptr); }
+ void DidFail(FileErrorCode) override { Done(nullptr); }
private:
void Done(scoped_refptr<SharedBuffer> output) {
@@ -375,11 +375,11 @@ WebConnectionType ToWebConnectionType(const String& connection_type) {
return kWebConnectionTypeUnknown;
}
-String GetReferrerPolicy(ReferrerPolicy policy) {
+String GetReferrerPolicy(network::mojom::ReferrerPolicy policy) {
switch (policy) {
- case kReferrerPolicyAlways:
+ case network::mojom::ReferrerPolicy::kAlways:
return protocol::Network::Request::ReferrerPolicyEnum::UnsafeUrl;
- case kReferrerPolicyDefault:
+ case network::mojom::ReferrerPolicy::kDefault:
if (RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()) {
return protocol::Network::Request::ReferrerPolicyEnum::
StrictOriginWhenCrossOrigin;
@@ -387,21 +387,22 @@ String GetReferrerPolicy(ReferrerPolicy policy) {
return protocol::Network::Request::ReferrerPolicyEnum::
NoReferrerWhenDowngrade;
}
- case kReferrerPolicyNoReferrerWhenDowngrade:
+ case network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade:
return protocol::Network::Request::ReferrerPolicyEnum::
NoReferrerWhenDowngrade;
- case kReferrerPolicyNever:
+ case network::mojom::ReferrerPolicy::kNever:
return protocol::Network::Request::ReferrerPolicyEnum::NoReferrer;
- case kReferrerPolicyOrigin:
+ case network::mojom::ReferrerPolicy::kOrigin:
return protocol::Network::Request::ReferrerPolicyEnum::Origin;
- case kReferrerPolicyOriginWhenCrossOrigin:
+ case network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin:
return protocol::Network::Request::ReferrerPolicyEnum::
OriginWhenCrossOrigin;
- case kReferrerPolicySameOrigin:
+ case network::mojom::ReferrerPolicy::kSameOrigin:
return protocol::Network::Request::ReferrerPolicyEnum::SameOrigin;
- case kReferrerPolicyStrictOrigin:
+ case network::mojom::ReferrerPolicy::kStrictOrigin:
return protocol::Network::Request::ReferrerPolicyEnum::StrictOrigin;
- case kReferrerPolicyStrictOriginWhenCrossOrigin:
+ case network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin:
return protocol::Network::Request::ReferrerPolicyEnum::
StrictOriginWhenCrossOrigin;
}
@@ -663,6 +664,7 @@ void InspectorNetworkAgent::Trace(blink::Visitor* visitor) {
visitor->Trace(inspected_frames_);
visitor->Trace(worker_global_scope_);
visitor->Trace(resources_data_);
+ visitor->Trace(pending_request_);
visitor->Trace(replay_xhrs_);
visitor->Trace(replay_xhrs_to_be_deleted_);
visitor->Trace(pending_xhr_replay_data_);
@@ -748,9 +750,9 @@ void InspectorNetworkAgent::WillSendRequestInternal(
resources_data_->ResourceCreated(execution_context, request_id, loader_id,
request.Url(), post_data);
- if (initiator_info.name == FetchInitiatorTypeNames::xmlhttprequest)
+ if (initiator_info.name == fetch_initiator_type_names::kXmlhttprequest)
type = InspectorPageAgent::kXHRResource;
- else if (initiator_info.name == FetchInitiatorTypeNames::fetch)
+ else if (initiator_info.name == fetch_initiator_type_names::kFetch)
type = InspectorPageAgent::kFetchResource;
if (pending_request_)
@@ -818,10 +820,10 @@ void InspectorNetworkAgent::WillSendRequest(
const FetchInitiatorInfo& initiator_info,
ResourceType resource_type) {
// Ignore the request initiated internally.
- if (initiator_info.name == FetchInitiatorTypeNames::internal)
+ if (initiator_info.name == fetch_initiator_type_names::kInternal)
return;
- if (initiator_info.name == FetchInitiatorTypeNames::document &&
+ if (initiator_info.name == fetch_initiator_type_names::kDocument &&
loader->GetSubstituteData().IsValid())
return;
@@ -835,10 +837,12 @@ void InspectorNetworkAgent::WillSendRequest(
// use ResourceRequest::referrer_. See https://crbug.com/850813. This
// seems to require storing the referrer info that is currently stored
// inside state_'s kExtraRequestHeaders, somewhere else.
- if (header_name.LowerASCII() == HTTPNames::Referer.LowerASCII())
- request.SetHTTPReferrer(Referrer(value, kReferrerPolicyAlways));
- else
+ if (header_name.LowerASCII() == http_names::kReferer.LowerASCII()) {
+ request.SetHTTPReferrer(
+ Referrer(value, network::mojom::ReferrerPolicy::kAlways));
+ } else {
request.SetHTTPHeaderField(header_name, AtomicString(value));
+ }
}
}
@@ -951,7 +955,7 @@ static bool IsErrorStatusCode(int status_code) {
void InspectorNetworkAgent::DidReceiveData(unsigned long identifier,
DocumentLoader* loader,
const char* data,
- int data_length) {
+ size_t data_length) {
String request_id = IdentifiersFactory::RequestId(loader, identifier);
if (data) {
@@ -980,7 +984,7 @@ void InspectorNetworkAgent::DidReceiveBlob(unsigned long identifier,
void InspectorNetworkAgent::DidReceiveEncodedDataLength(
DocumentLoader* loader,
unsigned long identifier,
- int encoded_data_length) {
+ size_t encoded_data_length) {
String request_id = IdentifiersFactory::RequestId(loader, identifier);
resources_data_->AddPendingEncodedDataLength(request_id, encoded_data_length);
}
@@ -1020,7 +1024,7 @@ void InspectorNetworkAgent::DidFinishLoading(unsigned long identifier,
encoded_data_length, should_report_corb_blocking);
}
-void InspectorNetworkAgent::DidReceiveCORSRedirectResponse(
+void InspectorNetworkAgent::DidReceiveCorsRedirectResponse(
unsigned long identifier,
DocumentLoader* loader,
const ResourceResponse& response,
@@ -1659,7 +1663,7 @@ InspectorNetworkAgent::InspectorNetworkAgent(
(!IsMainThread() && worker_global_scope_));
}
-void InspectorNetworkAgent::ShouldForceCORSPreflight(bool* result) {
+void InspectorNetworkAgent::ShouldForceCorsPreflight(bool* result) {
if (cache_disabled_.Get())
*result = true;
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.h
index 5f2d2ed181e..48c5fae036e 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.h
@@ -109,20 +109,20 @@ class CORE_EXPORT InspectorNetworkAgent final
void DidReceiveData(unsigned long identifier,
DocumentLoader*,
const char* data,
- int data_length);
+ size_t data_length);
void DidReceiveBlob(unsigned long identifier,
DocumentLoader*,
scoped_refptr<BlobDataHandle>);
void DidReceiveEncodedDataLength(DocumentLoader*,
unsigned long identifier,
- int encoded_data_length);
+ size_t encoded_data_length);
void DidFinishLoading(unsigned long identifier,
DocumentLoader*,
TimeTicks monotonic_finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
bool should_report_corb_blocking);
- void DidReceiveCORSRedirectResponse(unsigned long identifier,
+ void DidReceiveCorsRedirectResponse(unsigned long identifier,
DocumentLoader*,
const ResourceResponse&,
Resource*);
@@ -132,7 +132,7 @@ class CORE_EXPORT InspectorNetworkAgent final
void DidCommitLoad(LocalFrame*, DocumentLoader*);
void ScriptImported(unsigned long identifier, const String& source_string);
void DidReceiveScriptResponse(unsigned long identifier);
- void ShouldForceCORSPreflight(bool* result);
+ void ShouldForceCorsPreflight(bool* result);
void ShouldBlockRequest(const KURL&, bool* result);
void ShouldBypassServiceWorker(bool* result);
@@ -269,7 +269,7 @@ class CORE_EXPORT InspectorNetworkAgent final
// Stores the pending ThreadableLoaderClient till an identifier for
// the load is generated by the loader and passed to the inspector
// via the WillSendRequest() method.
- ThreadableLoaderClient* pending_request_;
+ Member<ThreadableLoaderClient> pending_request_;
InspectorPageAgent::ResourceType pending_request_type_;
Member<XHRReplayData> pending_xhr_replay_data_;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
index 632c6a6ac4d..42874d1a5fe 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -37,6 +37,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
@@ -68,7 +69,6 @@
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "v8/include/v8.h"
namespace blink {
@@ -169,9 +169,13 @@ class InspectorOverlayAgent::InspectorOverlayChromeClient final
public:
static InspectorOverlayChromeClient* Create(ChromeClient& client,
InspectorOverlayAgent& overlay) {
- return new InspectorOverlayChromeClient(client, overlay);
+ return MakeGarbageCollected<InspectorOverlayChromeClient>(client, overlay);
}
+ InspectorOverlayChromeClient(ChromeClient& client,
+ InspectorOverlayAgent& overlay)
+ : client_(&client), overlay_(&overlay) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(client_);
visitor->Trace(overlay_);
@@ -194,10 +198,6 @@ class InspectorOverlayAgent::InspectorOverlayChromeClient final
void InvalidateRect(const IntRect&) override { overlay_->Invalidate(); }
private:
- InspectorOverlayChromeClient(ChromeClient& client,
- InspectorOverlayAgent& overlay)
- : client_(&client), overlay_(&overlay) {}
-
Member<ChromeClient> client_;
Member<InspectorOverlayAgent> overlay_;
};
@@ -229,6 +229,7 @@ InspectorOverlayAgent::InspectorOverlayAgent(
show_fps_counter_(&agent_state_, /*default_value=*/false),
show_paint_rects_(&agent_state_, /*default_value=*/false),
show_scroll_bottleneck_rects_(&agent_state_, /*default_value=*/false),
+ show_hit_test_borders_(&agent_state_, /*default_value=*/false),
show_size_on_resize_(&agent_state_, /*default_value=*/false),
paused_in_debugger_message_(&agent_state_, /*default_value=*/String()) {}
@@ -254,6 +255,7 @@ void InspectorOverlayAgent::Restore() {
setShowFPSCounter(show_fps_counter_.Get());
setShowPaintRects(show_paint_rects_.Get());
setShowScrollBottleneckRects(show_scroll_bottleneck_rects_.Get());
+ setShowHitTestBorders(show_hit_test_borders_.Get());
setShowViewportSizeOnResize(show_size_on_resize_.Get());
if (paused_in_debugger_message_.Get().IsNull())
setPausedInDebuggerMessage(paused_in_debugger_message_.Get());
@@ -284,6 +286,7 @@ Response InspectorOverlayAgent::disable() {
setShowFPSCounter(false);
setShowPaintRects(false);
setShowScrollBottleneckRects(false);
+ setShowHitTestBorders(false);
setShowViewportSizeOnResize(false);
setPausedInDebuggerMessage(String());
setSuspended(false);
@@ -338,6 +341,17 @@ Response InspectorOverlayAgent::setShowScrollBottleneckRects(bool show) {
return Response::OK();
}
+Response InspectorOverlayAgent::setShowHitTestBorders(bool show) {
+ show_hit_test_borders_.Set(show);
+ if (show) {
+ Response response = CompositingEnabled();
+ if (!response.isSuccess())
+ return response;
+ }
+ frame_impl_->ViewImpl()->SetShowHitTestBorders(show);
+ return Response::OK();
+}
+
Response InspectorOverlayAgent::setShowViewportSizeOnResize(bool show) {
show_size_on_resize_.Set(show);
return Response::OK();
@@ -490,7 +504,8 @@ void InspectorOverlayAgent::UpdateAllOverlayLifecyclePhases() {
needs_update_ = false;
RebuildOverlayPage();
}
- OverlayMainFrame()->View()->UpdateAllLifecyclePhases();
+ OverlayMainFrame()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
if (page_overlay_ && page_overlay_->GetGraphicsLayer())
@@ -540,11 +555,15 @@ bool InspectorOverlayAgent::HandleInputEvent(const WebInputEvent& input_event) {
return true;
if (mouse_event.GetType() == WebInputEvent::kMouseMove) {
- handled = OverlayMainFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_event, TransformWebMouseEventVector(
- frame_impl_->GetFrameView(),
- std::vector<const WebInputEvent*>())) !=
- WebInputEventResult::kNotHandled;
+ handled =
+ OverlayMainFrame()->GetEventHandler().HandleMouseMoveEvent(
+ mouse_event,
+ TransformWebMouseEventVector(frame_impl_->GetFrameView(),
+ std::vector<const WebInputEvent*>()),
+ TransformWebMouseEventVector(
+ frame_impl_->GetFrameView(),
+ std::vector<const WebInputEvent*>())) !=
+ WebInputEventResult::kNotHandled;
}
if (mouse_event.GetType() == WebInputEvent::kMouseDown) {
handled = OverlayMainFrame()->GetEventHandler().HandleMousePressEvent(
@@ -564,7 +583,8 @@ bool InspectorOverlayAgent::HandleInputEvent(const WebInputEvent& input_event) {
if (handled)
return true;
OverlayMainFrame()->GetEventHandler().HandlePointerEvent(
- transformed_event, Vector<WebPointerEvent>());
+ transformed_event, Vector<WebPointerEvent>(),
+ Vector<WebPointerEvent>());
}
if (WebInputEvent::IsKeyboardEventType(input_event.GetType())) {
OverlayMainFrame()->GetEventHandler().KeyEvent(
@@ -692,8 +712,9 @@ void InspectorOverlayAgent::DrawNodeHighlight() {
}
bool append_element_info =
- highlight_node_->IsElementNode() && !omit_tooltip_ &&
- node_highlight_config_.show_info && highlight_node_->GetLayoutObject() &&
+ (highlight_node_->IsElementNode() || highlight_node_->IsTextNode()) &&
+ !omit_tooltip_ && node_highlight_config_.show_info &&
+ highlight_node_->GetLayoutObject() &&
highlight_node_->GetDocument().GetFrame();
InspectorHighlight highlight(highlight_node_.Get(), node_highlight_config_,
append_element_info);
@@ -768,7 +789,7 @@ Page* InspectorOverlayAgent::OverlayPage() {
frame_impl_->GetFrame()->GetPage()->GetChromeClient(), *this);
page_clients.chrome_client = overlay_chrome_client_.Get();
overlay_page_ = Page::Create(page_clients);
- overlay_host_ = new InspectorOverlayHost(this);
+ overlay_host_ = MakeGarbageCollected<InspectorOverlayHost>(this);
Settings& settings = frame_impl_->GetFrame()->GetPage()->GetSettings();
Settings& overlay_settings = overlay_page_->GetSettings();
@@ -791,10 +812,6 @@ Page* InspectorOverlayAgent::OverlayPage() {
overlay_settings.SetScriptEnabled(true);
overlay_settings.SetPluginsEnabled(false);
overlay_settings.SetLoadsImagesAutomatically(true);
- // FIXME: http://crbug.com/363843. Inspector should probably create its
- // own graphics layers and attach them to the tree rather than going
- // through some non-composited paint function.
- overlay_settings.SetAcceleratedCompositingEnabled(false);
LocalFrame* frame =
LocalFrame::Create(dummy_local_frame_client, *overlay_page_, nullptr);
@@ -903,7 +920,7 @@ String InspectorOverlayAgent::EvaluateInOverlayForTest(const String& script) {
->GetScriptController()
.ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode(script, ScriptSourceLocationType::kInspector),
- KURL(), kOpaqueResource, ScriptFetchOptions(),
+ KURL(), SanitizeScriptErrors::kSanitize, ScriptFetchOptions(),
ScriptController::kExecuteScriptWhenScriptsDisabled);
return ToCoreStringWithUndefinedOrNullCheck(string);
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h
index fc4c27d5192..d84956c95fa 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h
@@ -82,6 +82,7 @@ class CORE_EXPORT InspectorOverlayAgent final
protocol::Response setShowDebugBorders(bool) override;
protocol::Response setShowFPSCounter(bool) override;
protocol::Response setShowScrollBottleneckRects(bool) override;
+ protocol::Response setShowHitTestBorders(bool) override;
protocol::Response setShowViewportSizeOnResize(bool) override;
protocol::Response setPausedInDebuggerMessage(
protocol::Maybe<String>) override;
@@ -224,6 +225,7 @@ class CORE_EXPORT InspectorOverlayAgent final
InspectorAgentState::Boolean show_fps_counter_;
InspectorAgentState::Boolean show_paint_rects_;
InspectorAgentState::Boolean show_scroll_bottleneck_rects_;
+ InspectorAgentState::Boolean show_hit_test_borders_;
InspectorAgentState::Boolean show_size_on_resize_;
InspectorAgentState::String paused_in_debugger_message_;
DISALLOW_COPY_AND_ASSIGN(InspectorOverlayAgent);
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.cc
index 1c898a2bbda..04bb17da7ee 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.cc
@@ -348,9 +348,7 @@ bool InspectorPageAgent::CachedResourceContent(Resource* cached_resource,
return true;
case blink::ResourceType::kScript:
MaybeEncodeTextContent(
- cached_resource->ResourceBuffer()
- ? ToScriptResource(cached_resource)->DecodedText()
- : ToScriptResource(cached_resource)->SourceText().ToString(),
+ ToScriptResource(cached_resource)->TextForInspector(),
cached_resource->ResourceBuffer(), result, base64_encoded);
return true;
default:
@@ -371,8 +369,8 @@ InspectorPageAgent* InspectorPageAgent::Create(
Client* client,
InspectorResourceContentLoader* resource_content_loader,
v8_inspector::V8InspectorSession* v8_session) {
- return new InspectorPageAgent(inspected_frames, client,
- resource_content_loader, v8_session);
+ return MakeGarbageCollected<InspectorPageAgent>(
+ inspected_frames, client, resource_content_loader, v8_session);
}
String InspectorPageAgent::ResourceTypeJson(
@@ -873,7 +871,7 @@ void InspectorPageAgent::DidClearDocumentOfWindowObject(LocalFrame* frame) {
// a foreign world.
v8::HandleScope handle_scope(V8PerIsolateData::MainThreadIsolate());
frame->GetScriptController().ExecuteScriptInIsolatedWorld(
- world_id, source, KURL(), kOpaqueResource);
+ world_id, source, KURL(), SanitizeScriptErrors::kSanitize);
}
if (!script_to_evaluate_on_load_once_.IsEmpty()) {
@@ -1035,7 +1033,7 @@ std::unique_ptr<protocol::Page::Frame> InspectorPageAgent::BuildObjectForFrame(
frame_object->setParentId(IdentifiersFactory::FrameId(parent_frame));
AtomicString name = frame->Tree().GetName();
if (name.IsEmpty() && frame->DeprecatedLocalOwner())
- name = frame->DeprecatedLocalOwner()->getAttribute(HTMLNames::idAttr);
+ name = frame->DeprecatedLocalOwner()->getAttribute(html_names::kIdAttr);
frame_object->setName(name);
}
if (loader && !loader->UnreachableURL().IsEmpty())
@@ -1286,10 +1284,9 @@ void InspectorPageAgent::ConsumeCompilationCache(
auto it = compilation_cache_.find(source.Url().GetString());
if (it == compilation_cache_.end())
return;
- const Vector<char>& data = it->value;
+ const protocol::Binary& data = it->value;
*cached_data = new v8::ScriptCompiler::CachedData(
- reinterpret_cast<const uint8_t*>(data.data()), data.size(),
- v8::ScriptCompiler::CachedData::BufferNotOwned);
+ data.data(), data.size(), v8::ScriptCompiler::CachedData::BufferNotOwned);
}
void InspectorPageAgent::ProduceCompilationCache(const ScriptSourceCode& source,
@@ -1313,9 +1310,11 @@ void InspectorPageAgent::ProduceCompilationCache(const ScriptSourceCode& source,
std::unique_ptr<v8::ScriptCompiler::CachedData> cached_data(
v8::ScriptCompiler::CreateCodeCache(script->GetUnboundScript()));
if (cached_data) {
- String base64data = Base64Encode(
- reinterpret_cast<const char*>(cached_data->data), cached_data->length);
- GetFrontend()->compilationCacheProduced(url_string, base64data);
+ // CachedData produced by CreateCodeCache always owns its buffer.
+ CHECK_EQ(cached_data->buffer_policy,
+ v8::ScriptCompiler::CachedData::BufferOwned);
+ GetFrontend()->compilationCacheProduced(
+ url_string, protocol::Binary::fromCachedData(std::move(cached_data)));
}
}
@@ -1325,11 +1324,8 @@ Response InspectorPageAgent::setProduceCompilationCache(bool enabled) {
}
Response InspectorPageAgent::addCompilationCache(const String& url,
- const String& base64data) {
- Vector<char> data;
- if (!Base64Decode(base64data, data))
- return Response::Error("data should be base64-encoded");
- compilation_cache_.Set(url, std::move(data));
+ const protocol::Binary& data) {
+ compilation_cache_.Set(url, data);
return Response::OK();
}
@@ -1344,7 +1340,8 @@ protocol::Response InspectorPageAgent::generateTestReport(const String& message,
// Construct the test report.
TestReportBody* body = new TestReportBody(message);
- Report* report = new Report("test", document->Url().GetString(), body);
+ Report* report =
+ MakeGarbageCollected<Report>("test", document->Url().GetString(), body);
// Send the test report to any ReportingObservers.
ReportingContext::From(document)->QueueReport(report);
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.h
index 65325e4f955..e8109fe51e0 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.h
@@ -106,6 +106,11 @@ class CORE_EXPORT InspectorPageAgent final
static ResourceType ToResourceType(const blink::ResourceType);
static String CachedResourceTypeJson(const Resource&);
+ InspectorPageAgent(InspectedFrames*,
+ Client*,
+ InspectorResourceContentLoader*,
+ v8_inspector::V8InspectorSession*);
+
// Page API for frontend
protocol::Response enable() override;
protocol::Response disable() override;
@@ -164,7 +169,7 @@ class CORE_EXPORT InspectorPageAgent final
protocol::Response setProduceCompilationCache(bool enabled) override;
protocol::Response addCompilationCache(const String& url,
- const String& data) override;
+ const protocol::Binary& data) override;
protocol::Response clearCompilationCache() override;
// InspectorInstrumentation API
@@ -209,11 +214,6 @@ class CORE_EXPORT InspectorPageAgent final
void Trace(blink::Visitor*) override;
private:
- InspectorPageAgent(InspectedFrames*,
- Client*,
- InspectorResourceContentLoader*,
- v8_inspector::V8InspectorSession*);
-
void GetResourceContentAfterResourcesContentLoaded(
const String& frame_id,
const String& url,
@@ -236,7 +236,7 @@ class CORE_EXPORT InspectorPageAgent final
std::unique_ptr<protocol::Page::FrameResourceTree> BuildObjectForResourceTree(
LocalFrame*);
Member<InspectedFrames> inspected_frames_;
- HashMap<String, Vector<char>> compilation_cache_;
+ HashMap<String, protocol::Binary> compilation_cache_;
v8_inspector::V8InspectorSession* v8_session_;
Client* client_;
String pending_script_to_evaluate_on_load_once_;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc
index e715aa31e67..83fbd7734fc 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc
@@ -49,7 +49,7 @@ void InspectorPerformanceAgent::Restore() {
void InspectorPerformanceAgent::InnerEnable() {
instrumenting_agents_->addInspectorPerformanceAgent(this);
- Platform::Current()->CurrentThread()->AddTaskTimeObserver(this);
+ Thread::Current()->AddTaskTimeObserver(this);
layout_start_ticks_ = TimeTicks();
recalc_style_start_ticks_ = TimeTicks();
task_start_ticks_ = TimeTicks();
@@ -70,7 +70,7 @@ protocol::Response InspectorPerformanceAgent::disable() {
return Response::OK();
enabled_.Clear();
instrumenting_agents_->removeInspectorPerformanceAgent(this);
- Platform::Current()->CurrentThread()->RemoveTaskTimeObserver(this);
+ Thread::Current()->RemoveTaskTimeObserver(this);
return Response::OK();
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.h
index 856bbbaf1f5..57a34dbf76d 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.h
@@ -33,8 +33,10 @@ class CORE_EXPORT InspectorPerformanceAgent final
void Trace(blink::Visitor*) override;
static InspectorPerformanceAgent* Create(InspectedFrames* inspected_frames) {
- return new InspectorPerformanceAgent(inspected_frames);
+ return MakeGarbageCollected<InspectorPerformanceAgent>(inspected_frames);
}
+
+ explicit InspectorPerformanceAgent(InspectedFrames*);
~InspectorPerformanceAgent() override;
void Restore() override;
@@ -66,7 +68,6 @@ class CORE_EXPORT InspectorPerformanceAgent final
base::TimeTicks end_time) override;
private:
- explicit InspectorPerformanceAgent(InspectedFrames*);
void ScriptStarts();
void ScriptEnds();
void InnerEnable();
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_protocol_config.json b/chromium/third_party/blink/renderer/core/inspector/inspector_protocol_config.json
index 4b76bfd27ca..5441041d51d 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_protocol_config.json
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_protocol_config.json
@@ -74,7 +74,7 @@
{
"domain": "Page",
"exclude": ["getNavigationHistory", "navigateToHistoryEntry", "captureScreenshot", "screencastFrameAck", "handleJavaScriptDialog", "setColorPickerEnabled",
- "getAppManifest", "requestAppBanner", "setControlNavigations", "processNavigation", "printToPDF", "bringToFront", "setDownloadBehavior", "navigate", "crash", "close", "setWebLifecycleState"],
+ "getAppManifest", "requestAppBanner", "setControlNavigations", "processNavigation", "printToPDF", "bringToFront", "setDownloadBehavior", "navigate", "crash", "close", "setWebLifecycleState", "captureSnapshot"],
"async": ["getResourceContent", "searchInResource"],
"exclude_events": ["screencastFrame", "screencastVisibilityChanged", "colorPicked", "interstitialShown", "interstitialHidden", "javascriptDialogOpening", "javascriptDialogClosed", "navigationRequested"]
},
@@ -96,11 +96,6 @@
"async": ["getResponseBody", "getRequestPostData"]
},
{
- "domain": "Target",
- "include": ["setAutoAttach", "sendMessageToTarget"],
- "include_events": ["attachedToTarget", "detachedFromTarget", "receivedMessageFromTarget"]
- },
- {
"domain": "Testing"
}
]
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.cc
index 6d7db14dcf0..bb59c3a5f39 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.cc
@@ -68,7 +68,8 @@ InspectorResourceContentLoader::InspectorResourceContentLoader(
void InspectorResourceContentLoader::Start() {
started_ = true;
HeapVector<Member<Document>> documents;
- InspectedFrames* inspected_frames = new InspectedFrames(inspected_frame_);
+ InspectedFrames* inspected_frames =
+ MakeGarbageCollected<InspectedFrames>(inspected_frame_);
for (LocalFrame* frame : *inspected_frames) {
documents.push_back(frame->GetDocument());
documents.AppendVector(InspectorPageAgent::ImportsForFrame(frame));
@@ -87,13 +88,15 @@ void InspectorResourceContentLoader::Start() {
resource_request.SetCacheMode(mojom::FetchCacheMode::kOnlyIfCached);
}
resource_request.SetRequestContext(mojom::RequestContextType::INTERNAL);
+ resource_request.SetSkipServiceWorker(true);
if (!resource_request.Url().GetString().IsEmpty()) {
urls_to_fetch.insert(resource_request.Url().GetString());
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::internal;
+ options.initiator_info.name = fetch_initiator_type_names::kInternal;
FetchParameters params(resource_request, options);
- ResourceClient* resource_client = new ResourceClient(this);
+ ResourceClient* resource_client =
+ MakeGarbageCollected<ResourceClient>(this);
// Prevent garbage collection by holding a reference to this resource.
resources_.push_back(
RawResource::Fetch(params, document->Fetcher(), resource_client));
@@ -112,9 +115,10 @@ void InspectorResourceContentLoader::Start() {
ResourceRequest resource_request(url);
resource_request.SetRequestContext(mojom::RequestContextType::INTERNAL);
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::internal;
+ options.initiator_info.name = fetch_initiator_type_names::kInternal;
FetchParameters params(resource_request, options);
- ResourceClient* resource_client = new ResourceClient(this);
+ ResourceClient* resource_client =
+ MakeGarbageCollected<ResourceClient>(this);
// Prevent garbage collection by holding a reference to this resource.
resources_.push_back(CSSStyleSheetResource::Fetch(
params, document->Fetcher(), resource_client));
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h b/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h
index bbcd8ee1196..b1f872867aa 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h
@@ -23,8 +23,10 @@ class CORE_EXPORT InspectorResourceContentLoader final
: public GarbageCollectedFinalized<InspectorResourceContentLoader> {
public:
static InspectorResourceContentLoader* Create(LocalFrame* inspected_frame) {
- return new InspectorResourceContentLoader(inspected_frame);
+ return MakeGarbageCollected<InspectorResourceContentLoader>(
+ inspected_frame);
}
+ explicit InspectorResourceContentLoader(LocalFrame*);
~InspectorResourceContentLoader();
void Dispose();
void Trace(blink::Visitor*);
@@ -39,7 +41,6 @@ class CORE_EXPORT InspectorResourceContentLoader final
private:
class ResourceClient;
- explicit InspectorResourceContentLoader(LocalFrame*);
void ResourceFinished(ResourceClient*);
void CheckDone();
void Start();
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_session.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_session.cc
deleted file mode 100644
index b13a6107efa..00000000000
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_session.cc
+++ /dev/null
@@ -1,254 +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 "third_party/blink/renderer/core/inspector/inspector_session.h"
-
-#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
-#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
-#include "third_party/blink/renderer/core/inspector/inspector_base_agent.h"
-#include "third_party/blink/renderer/core/inspector/inspector_session_state.h"
-#include "third_party/blink/renderer/core/inspector/protocol/Protocol.h"
-#include "third_party/blink/renderer/core/inspector/v8_inspector_string.h"
-#include "third_party/blink/renderer/core/probe/core_probes.h"
-
-namespace blink {
-
-namespace {
-const char kV8StateKey[] = "v8";
-}
-
-// static
-bool InspectorSession::ShouldInterruptForMethod(const String& method) {
- // Keep in sync with DevToolsSession::ShouldSendOnIO.
- // TODO(dgozman): find a way to share this.
- return method == "Debugger.pause" || method == "Debugger.setBreakpoint" ||
- method == "Debugger.setBreakpointByUrl" ||
- method == "Debugger.removeBreakpoint" ||
- method == "Debugger.setBreakpointsActive" ||
- method == "Performance.getMetrics" || method == "Page.crash" ||
- method == "Runtime.terminateExecution" ||
- method == "Emulation.setScriptExecutionDisabled";
-}
-
-InspectorSession::InspectorSession(
- Client* client,
- CoreProbeSink* instrumenting_agents,
- InspectedFrames* inspected_frames,
- int session_id,
- v8_inspector::V8Inspector* inspector,
- int context_group_id,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state)
- : client_(client),
- v8_session_(nullptr),
- session_id_(session_id),
- disposed_(false),
- instrumenting_agents_(instrumenting_agents),
- inspected_frames_(inspected_frames),
- inspector_backend_dispatcher_(new protocol::UberDispatcher(this)),
- session_state_(std::move(reattach_session_state)),
- v8_session_state_(kV8StateKey),
- v8_session_state_json_(&v8_session_state_, /*default_value=*/String()) {
- v8_session_state_.InitFrom(&session_state_);
-
- // inspector->connect may result in calls to |this| against the
- // V8Inspector::Channel interface for receiving responses / notifications,
- // while v8_session_ is still nullptr.
- v8_session_ =
- inspector->connect(context_group_id, /*channel*/ this,
- ToV8InspectorStringView(v8_session_state_json_.Get()));
-
- instrumenting_agents_->addInspectorSession(this);
-}
-
-InspectorSession::~InspectorSession() {
- DCHECK(disposed_);
-}
-
-void InspectorSession::Append(InspectorAgent* agent) {
- agents_.push_back(agent);
- agent->Init(instrumenting_agents_.Get(), inspector_backend_dispatcher_.get(),
- &session_state_);
-}
-
-void InspectorSession::Restore() {
- DCHECK(!disposed_);
- for (wtf_size_t i = 0; i < agents_.size(); i++)
- agents_[i]->Restore();
-}
-
-void InspectorSession::Dispose() {
- DCHECK(!disposed_);
- disposed_ = true;
- instrumenting_agents_->removeInspectorSession(this);
- inspector_backend_dispatcher_.reset();
- for (wtf_size_t i = agents_.size(); i > 0; i--)
- agents_[i - 1]->Dispose();
- agents_.clear();
- v8_session_.reset();
-}
-
-void InspectorSession::DispatchProtocolMessage(int call_id,
- const String& method,
- const String& message) {
- DCHECK(!disposed_);
- if (v8_inspector::V8InspectorSession::canDispatchMethod(
- ToV8InspectorStringView(method))) {
- v8_session_->dispatchProtocolMessage(ToV8InspectorStringView(message));
- } else {
- inspector_backend_dispatcher_->dispatch(
- call_id, method, protocol::StringUtil::parseJSON(message), message);
- }
-}
-
-void InspectorSession::DispatchProtocolMessage(const String& message) {
- DCHECK(!disposed_);
- int call_id;
- String method;
- std::unique_ptr<protocol::Value> parsed_message =
- protocol::StringUtil::parseJSON(message);
- if (!inspector_backend_dispatcher_->parseCommand(parsed_message.get(),
- &call_id, &method)) {
- return;
- }
- if (v8_inspector::V8InspectorSession::canDispatchMethod(
- ToV8InspectorStringView(method))) {
- v8_session_->dispatchProtocolMessage(ToV8InspectorStringView(message));
- } else {
- inspector_backend_dispatcher_->dispatch(call_id, method,
- std::move(parsed_message), message);
- }
-}
-
-void InspectorSession::DidStartProvisionalLoad(LocalFrame* frame) {
- if (inspected_frames_->Root() == frame) {
- v8_session_->setSkipAllPauses(true);
- v8_session_->resume();
- }
-}
-
-void InspectorSession::DidFailProvisionalLoad(LocalFrame* frame) {
- if (inspected_frames_->Root() == frame)
- v8_session_->setSkipAllPauses(false);
-}
-
-void InspectorSession::DidCommitLoadForLocalFrame(LocalFrame* frame) {
- for (wtf_size_t i = 0; i < agents_.size(); i++)
- agents_[i]->DidCommitLoadForLocalFrame(frame);
- if (inspected_frames_->Root() == frame)
- v8_session_->setSkipAllPauses(false);
-}
-
-void InspectorSession::sendProtocolResponse(
- int call_id,
- std::unique_ptr<protocol::Serializable> message) {
- SendProtocolResponse(call_id, message->serialize());
-}
-
-void InspectorSession::fallThrough(int call_id,
- const String& method,
- const String& message) {
- // There's no other layer to handle the command.
- NOTREACHED();
-}
-
-void InspectorSession::sendResponse(
- int call_id,
- std::unique_ptr<v8_inspector::StringBuffer> message) {
- // We can potentially avoid copies if WebString would convert to utf8 right
- // from StringView, but it uses StringImpl itself, so we don't create any
- // extra copies here.
- SendProtocolResponse(call_id, ToCoreString(message->string()));
-}
-
-void InspectorSession::SendProtocolResponse(int call_id,
- const String& message) {
- if (disposed_)
- return;
- flushProtocolNotifications();
- if (v8_session_)
- v8_session_state_json_.Set(ToCoreString(v8_session_->stateJSON()));
- client_->SendProtocolResponse(session_id_, call_id, message,
- session_state_.TakeUpdates());
-}
-
-class InspectorSession::Notification {
- public:
- static std::unique_ptr<Notification> CreateForBlink(
- std::unique_ptr<protocol::Serializable> notification) {
- return std::unique_ptr<Notification>(
- new Notification(std::move(notification)));
- }
-
- static std::unique_ptr<Notification> CreateForV8(
- std::unique_ptr<v8_inspector::StringBuffer> notification) {
- return std::unique_ptr<Notification>(
- new Notification(std::move(notification)));
- }
-
- String Serialize() {
- if (blink_notification_) {
- serialized_ = blink_notification_->serialize();
- blink_notification_.reset();
- } else if (v8_notification_) {
- serialized_ = ToCoreString(v8_notification_->string());
- v8_notification_.reset();
- }
- return serialized_;
- }
-
- private:
- explicit Notification(std::unique_ptr<protocol::Serializable> notification)
- : blink_notification_(std::move(notification)) {}
-
- explicit Notification(
- std::unique_ptr<v8_inspector::StringBuffer> notification)
- : v8_notification_(std::move(notification)) {}
-
- std::unique_ptr<protocol::Serializable> blink_notification_;
- std::unique_ptr<v8_inspector::StringBuffer> v8_notification_;
- String serialized_;
-};
-
-void InspectorSession::sendProtocolNotification(
- std::unique_ptr<protocol::Serializable> notification) {
- if (disposed_)
- return;
- notification_queue_.push_back(
- Notification::CreateForBlink(std::move(notification)));
-}
-
-void InspectorSession::sendNotification(
- std::unique_ptr<v8_inspector::StringBuffer> notification) {
- if (disposed_)
- return;
- notification_queue_.push_back(
- Notification::CreateForV8(std::move(notification)));
-}
-
-void InspectorSession::flushProtocolNotifications() {
- if (disposed_)
- return;
- for (wtf_size_t i = 0; i < agents_.size(); i++)
- agents_[i]->FlushPendingProtocolNotifications();
- if (!notification_queue_.size())
- return;
- if (v8_session_)
- v8_session_state_json_.Set(ToCoreString(v8_session_->stateJSON()));
- for (wtf_size_t i = 0; i < notification_queue_.size(); ++i) {
- client_->SendProtocolNotification(session_id_,
- notification_queue_[i]->Serialize(),
- session_state_.TakeUpdates());
- }
- notification_queue_.clear();
-}
-
-void InspectorSession::Trace(blink::Visitor* visitor) {
- visitor->Trace(instrumenting_agents_);
- visitor->Trace(inspected_frames_);
- visitor->Trace(agents_);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_session_state_test.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_session_state_test.cc
index 73dc4ea72b2..3c8d948ab01 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_session_state_test.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_session_state_test.cc
@@ -17,7 +17,7 @@ using testing::UnorderedElementsAre;
// This session object is normally on the browser side; see
// content/browser/devtools/devtools_session.{h,cc}, but here's a minimal
// reimplementation to allow testing without sending data through a Mojo pipe.
-class DevToolsSession {
+class FakeDevToolsSession {
public:
void ApplyUpdates(DevToolsSessionStatePtr updates) {
if (!updates)
@@ -65,9 +65,8 @@ struct AgentWithSimpleFields {
TEST(InspectorSessionStateTest, SimpleFields) {
// The browser session (DevToolsSession) remains live while renderer
- // sessions (InspectorSession - here we just exercise
- // InspectorSessionState) may come and go.
- DevToolsSession dev_tools_session;
+ // sessions (here we just exercise InspectorSessionState) may come and go.
+ FakeDevToolsSession dev_tools_session;
{ // Renderer session.
InspectorSessionState session_state(dev_tools_session.CloneCookie());
@@ -138,7 +137,7 @@ struct AgentWithMapFields {
};
TEST(InspectorSessionStateTest, MapFields) {
- DevToolsSession dev_tools_session; // Browser session.
+ FakeDevToolsSession dev_tools_session; // Browser session.
{ // Renderer session.
InspectorSessionState session_state(dev_tools_session.CloneCookie());
@@ -205,7 +204,7 @@ TEST(InspectorSessionStateTest, MapFields) {
}
TEST(InspectorSessionStateTest, MultipleAgents) {
- DevToolsSession dev_tools_session; // Browser session.
+ FakeDevToolsSession dev_tools_session; // Browser session.
{ // Renderer session.
InspectorSessionState session_state(dev_tools_session.CloneCookie());
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc
index 7426bd97569..5d66cde08b0 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/css/css_keyframe_rule.h"
#include "third_party/blink/renderer/core/css/css_keyframes_rule.h"
#include "third_party/blink/renderer/core/css/css_media_rule.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_rule_list.h"
#include "third_party/blink/renderer/core/css/css_style_rule.h"
@@ -41,7 +42,6 @@
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/css/style_rule.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -188,7 +188,7 @@ void StyleSheetHandler::StartRuleHeader(StyleRule::RuleType type,
if (current_rule_data_)
current_rule_data_stack_.pop_back();
- CSSRuleSourceData* data = new CSSRuleSourceData(type);
+ CSSRuleSourceData* data = MakeGarbageCollected<CSSRuleSourceData>(type);
data->rule_header_range.start = offset;
current_rule_data_ = data;
current_rule_data_stack_.push_back(data);
@@ -318,7 +318,8 @@ void StyleSheetHandler::ObserveComment(unsigned start_offset,
return;
// FIXME: Use the actual rule type rather than STYLE_RULE?
- CSSRuleSourceDataList* source_data = new CSSRuleSourceDataList();
+ CSSRuleSourceDataList* source_data =
+ MakeGarbageCollected<CSSRuleSourceDataList>();
StyleSheetHandler handler(comment_text, document_, source_data);
CSSParser::ParseDeclarationListForInspector(
@@ -345,7 +346,8 @@ bool VerifyRuleText(Document* document, const String& rule_text) {
DEFINE_STATIC_LOCAL(String, bogus_property_name, ("-webkit-boguz-propertee"));
StyleSheetContents* style_sheet =
StyleSheetContents::Create(ParserContextForDocument(document));
- CSSRuleSourceDataList* source_data = new CSSRuleSourceDataList();
+ CSSRuleSourceDataList* source_data =
+ MakeGarbageCollected<CSSRuleSourceDataList>();
String text = rule_text + " div { " + bogus_property_name + ": none; }";
StyleSheetHandler handler(text, document, source_data);
CSSParser::ParseSheetForInspector(ParserContextForDocument(document),
@@ -382,7 +384,8 @@ bool VerifyStyleText(Document* document, const String& text) {
bool VerifyKeyframeKeyText(Document* document, const String& key_text) {
StyleSheetContents* style_sheet =
StyleSheetContents::Create(ParserContextForDocument(document));
- CSSRuleSourceDataList* source_data = new CSSRuleSourceDataList();
+ CSSRuleSourceDataList* source_data =
+ MakeGarbageCollected<CSSRuleSourceDataList>();
String text = "@keyframes boguzAnim { " + key_text +
" { -webkit-boguz-propertee : none; } }";
StyleSheetHandler handler(text, document, source_data);
@@ -412,7 +415,8 @@ bool VerifySelectorText(Document* document, const String& selector_text) {
DEFINE_STATIC_LOCAL(String, bogus_property_name, ("-webkit-boguz-propertee"));
StyleSheetContents* style_sheet =
StyleSheetContents::Create(ParserContextForDocument(document));
- CSSRuleSourceDataList* source_data = new CSSRuleSourceDataList();
+ CSSRuleSourceDataList* source_data =
+ MakeGarbageCollected<CSSRuleSourceDataList>();
String text = selector_text + " { " + bogus_property_name + ": none; }";
StyleSheetHandler handler(text, document, source_data);
CSSParser::ParseSheetForInspector(ParserContextForDocument(document),
@@ -441,7 +445,8 @@ bool VerifyMediaText(Document* document, const String& media_text) {
DEFINE_STATIC_LOCAL(String, bogus_property_name, ("-webkit-boguz-propertee"));
StyleSheetContents* style_sheet =
StyleSheetContents::Create(ParserContextForDocument(document));
- CSSRuleSourceDataList* source_data = new CSSRuleSourceDataList();
+ CSSRuleSourceDataList* source_data =
+ MakeGarbageCollected<CSSRuleSourceDataList>();
String text = "@media " + media_text + " { div { " + bogus_property_name +
": none; } }";
StyleSheetHandler handler(text, document, source_data);
@@ -533,6 +538,7 @@ void CollectFlatRules(RuleList rule_list, CSSRuleVector* result) {
case CSSRule::kFontFaceRule:
case CSSRule::kViewportRule:
case CSSRule::kKeyframeRule:
+ case CSSRule::kFontFeatureValuesRule:
result->push_back(rule);
break;
case CSSRule::kMediaRule:
@@ -718,7 +724,8 @@ InspectorStyle* InspectorStyle::Create(
CSSStyleDeclaration* style,
CSSRuleSourceData* source_data,
InspectorStyleSheetBase* parent_style_sheet) {
- return new InspectorStyle(style, source_data, parent_style_sheet);
+ return MakeGarbageCollected<InspectorStyle>(style, source_data,
+ parent_style_sheet);
}
InspectorStyle::InspectorStyle(CSSStyleDeclaration* style,
@@ -955,8 +962,9 @@ InspectorStyleSheet* InspectorStyleSheet::Create(
const String& document_url,
InspectorStyleSheetBase::Listener* listener,
InspectorResourceContainer* resource_container) {
- return new InspectorStyleSheet(network_agent, page_style_sheet, origin,
- document_url, listener, resource_container);
+ return MakeGarbageCollected<InspectorStyleSheet>(
+ network_agent, page_style_sheet, origin, document_url, listener,
+ resource_container);
}
InspectorStyleSheet::InspectorStyleSheet(
@@ -1410,7 +1418,8 @@ void InspectorStyleSheet::ReplaceText(const SourceRange& range,
void InspectorStyleSheet::InnerSetText(const String& text,
bool mark_as_locally_modified) {
- CSSRuleSourceDataList* rule_tree = new CSSRuleSourceDataList();
+ CSSRuleSourceDataList* rule_tree =
+ MakeGarbageCollected<CSSRuleSourceDataList>();
StyleSheetContents* style_sheet = StyleSheetContents::Create(
page_style_sheet_->Contents()->ParserContext());
StyleSheetHandler handler(text, page_style_sheet_->OwnerDocument(),
@@ -1430,7 +1439,7 @@ void InspectorStyleSheet::InnerSetText(const String& text,
parsed_flat_rules_.clear();
CollectFlatRules(source_data_sheet, &parsed_flat_rules_);
- source_data_ = new CSSRuleSourceDataList();
+ source_data_ = MakeGarbageCollected<CSSRuleSourceDataList>();
FlattenSourceData(*rule_tree, source_data_.Get());
text_ = text;
@@ -1891,7 +1900,8 @@ bool InspectorStyleSheet::InspectorStyleSheetText(String* result) {
InspectorStyleSheetForInlineStyle* InspectorStyleSheetForInlineStyle::Create(
Element* element,
Listener* listener) {
- return new InspectorStyleSheetForInlineStyle(element, listener);
+ return MakeGarbageCollected<InspectorStyleSheetForInlineStyle>(element,
+ listener);
}
InspectorStyleSheetForInlineStyle::InspectorStyleSheetForInlineStyle(
@@ -1943,12 +1953,13 @@ CSSRuleSourceData* InspectorStyleSheetForInlineStyle::RuleSourceData() {
const String& text = ElementStyleText();
CSSRuleSourceData* rule_source_data = nullptr;
if (text.IsEmpty()) {
- rule_source_data = new CSSRuleSourceData(StyleRule::kStyle);
+ rule_source_data =
+ MakeGarbageCollected<CSSRuleSourceData>(StyleRule::kStyle);
rule_source_data->rule_body_range.start = 0;
rule_source_data->rule_body_range.end = 0;
} else {
CSSRuleSourceDataList* rule_source_data_result =
- new CSSRuleSourceDataList();
+ MakeGarbageCollected<CSSRuleSourceDataList>();
StyleSheetHandler handler(text, &element_->GetDocument(),
rule_source_data_result);
CSSParser::ParseDeclarationListForInspector(
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.h b/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.h
index abfd1e9b40c..f72b15cfe87 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_style_sheet.h
@@ -57,6 +57,9 @@ class InspectorStyle final : public GarbageCollectedFinalized<InspectorStyle> {
static InspectorStyle* Create(CSSStyleDeclaration*,
CSSRuleSourceData*,
InspectorStyleSheetBase* parent_style_sheet);
+ InspectorStyle(CSSStyleDeclaration*,
+ CSSRuleSourceData*,
+ InspectorStyleSheetBase* parent_style_sheet);
~InspectorStyle();
CSSStyleDeclaration* CssStyle() { return style_.Get(); }
@@ -67,10 +70,6 @@ class InspectorStyle final : public GarbageCollectedFinalized<InspectorStyle> {
void Trace(blink::Visitor*);
private:
- InspectorStyle(CSSStyleDeclaration*,
- CSSRuleSourceData*,
- InspectorStyleSheetBase* parent_style_sheet);
-
void PopulateAllProperties(Vector<CSSPropertySourceData>& result);
std::unique_ptr<protocol::CSS::CSSStyle> StyleWithProperties();
String ShorthandValue(const String& shorthand_property);
@@ -133,6 +132,12 @@ class InspectorStyleSheet : public InspectorStyleSheetBase {
InspectorStyleSheetBase::Listener*,
InspectorResourceContainer*);
+ InspectorStyleSheet(InspectorNetworkAgent*,
+ CSSStyleSheet* page_style_sheet,
+ const String& origin,
+ const String& document_url,
+ InspectorStyleSheetBase::Listener*,
+ InspectorResourceContainer*);
~InspectorStyleSheet() override;
void Trace(blink::Visitor*) override;
@@ -192,12 +197,6 @@ class InspectorStyleSheet : public InspectorStyleSheetBase {
InspectorStyle* GetInspectorStyle(CSSStyleDeclaration*) override;
private:
- InspectorStyleSheet(InspectorNetworkAgent*,
- CSSStyleSheet* page_style_sheet,
- const String& origin,
- const String& document_url,
- InspectorStyleSheetBase::Listener*,
- InspectorResourceContainer*);
CSSRuleSourceData* RuleSourceDataAfterSourceRange(const SourceRange&);
CSSRuleSourceData* FindRuleByHeaderRange(const SourceRange&);
CSSRuleSourceData* FindRuleByBodyRange(const SourceRange&);
@@ -255,6 +254,7 @@ class InspectorStyleSheetForInlineStyle final : public InspectorStyleSheetBase {
public:
static InspectorStyleSheetForInlineStyle* Create(Element*, Listener*);
+ InspectorStyleSheetForInlineStyle(Element*, Listener*);
void DidModifyElementAttribute();
bool SetText(const String&, ExceptionState&) override;
bool GetText(String* result) override;
@@ -270,7 +270,6 @@ class InspectorStyleSheetForInlineStyle final : public InspectorStyleSheetBase {
bool IsInlineStyle() override { return true; }
private:
- InspectorStyleSheetForInlineStyle(Element*, Listener*);
const String& ElementStyleText();
Member<Element> element_;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.cc
index 42cdf055190..656bff66466 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.cc
@@ -6,7 +6,7 @@
#include "third_party/blink/renderer/core/inspector/thread_debugger.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -122,7 +122,6 @@ void InspectorTaskRunner::PerformSingleTaskDontWait() {
void InspectorTaskRunner::V8InterruptCallback(v8::Isolate*, void* data) {
InspectorTaskRunner* runner = static_cast<InspectorTaskRunner*>(data);
- DCHECK(runner->isolate_task_runner_->BelongsToCurrentThread());
if (runner->ignore_interrupts_)
return;
while (true) {
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
index 1d6549b2e87..a2a44cb8792 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -113,7 +113,7 @@ void InspectorTraceEvents::WillSendRequest(
TRACE_EVENT_INSTANT1(
"devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD,
"data",
- InspectorSendRequestEvent::Data(loader, identifier, frame, request));
+ inspector_send_request_event::Data(loader, identifier, frame, request));
}
void InspectorTraceEvents::DidReceiveResourceResponse(
@@ -122,10 +122,10 @@ void InspectorTraceEvents::DidReceiveResourceResponse(
const ResourceResponse& response,
Resource*) {
LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
- TRACE_EVENT_INSTANT1(
- "devtools.timeline", "ResourceReceiveResponse", TRACE_EVENT_SCOPE_THREAD,
- "data",
- InspectorReceiveResponseEvent::Data(loader, identifier, frame, response));
+ TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceReceiveResponse",
+ TRACE_EVENT_SCOPE_THREAD, "data",
+ inspector_receive_response_event::Data(
+ loader, identifier, frame, response));
}
void InspectorTraceEvents::DidReceiveData(unsigned long identifier,
@@ -135,7 +135,7 @@ void InspectorTraceEvents::DidReceiveData(unsigned long identifier,
LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceReceivedData",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorReceiveDataEvent::Data(
+ inspector_receive_data_event::Data(
loader, identifier, frame, encoded_data_length));
probe::AsyncTask async_task(frame ? frame->GetDocument() : nullptr,
AsyncId(identifier), "data");
@@ -150,9 +150,9 @@ void InspectorTraceEvents::DidFinishLoading(unsigned long identifier,
LocalFrame* frame = loader ? loader->GetFrame() : nullptr;
TRACE_EVENT_INSTANT1(
"devtools.timeline", "ResourceFinish", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorResourceFinishEvent::Data(loader, identifier, finish_time, false,
- encoded_data_length,
- decoded_body_length));
+ inspector_resource_finish_event::Data(loader, identifier, finish_time,
+ false, encoded_data_length,
+ decoded_body_length));
probe::AsyncTask async_task(frame ? frame->GetDocument() : nullptr,
AsyncId(identifier));
}
@@ -162,7 +162,7 @@ void InspectorTraceEvents::DidFailLoading(unsigned long identifier,
const ResourceError&) {
TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceFinish",
TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorResourceFinishEvent::Data(
+ inspector_resource_finish_event::Data(
loader, identifier, TimeTicks(), true, 0, 0));
}
@@ -171,7 +171,7 @@ void InspectorTraceEvents::Will(const probe::ExecuteScript&) {}
void InspectorTraceEvents::Did(const probe::ExecuteScript&) {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorUpdateCountersEvent::Data());
+ inspector_update_counters_event::Data());
}
void InspectorTraceEvents::Will(const probe::ParseHTML& probe) {
@@ -188,7 +188,7 @@ void InspectorTraceEvents::Did(const probe::ParseHTML& probe) {
InspectorParseHtmlEndData(probe.parser->LineNumber().ZeroBasedInt() - 1));
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorUpdateCountersEvent::Data());
+ inspector_update_counters_event::Data());
}
void InspectorTraceEvents::Will(const probe::CallFunction& probe) {
@@ -196,7 +196,7 @@ void InspectorTraceEvents::Will(const probe::CallFunction& probe) {
return;
TRACE_EVENT_BEGIN1(
"devtools.timeline", "FunctionCall", "data",
- InspectorFunctionCallEvent::Data(probe.context, probe.function));
+ inspector_function_call_event::Data(probe.context, probe.function));
}
void InspectorTraceEvents::Did(const probe::CallFunction& probe) {
@@ -205,14 +205,14 @@ void InspectorTraceEvents::Did(const probe::CallFunction& probe) {
TRACE_EVENT_END0("devtools.timeline", "FunctionCall");
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorUpdateCountersEvent::Data());
+ inspector_update_counters_event::Data());
}
void InspectorTraceEvents::PaintTiming(Document* document,
const char* name,
double timestamp) {
TRACE_EVENT_MARK_WITH_TIMESTAMP2("loading,rail,devtools.timeline", name,
- TraceEvent::ToTraceTimestamp(timestamp),
+ trace_event::ToTraceTimestamp(timestamp),
"frame", ToTraceValue(document->GetFrame()),
"data", GetNavigationTracingData(document));
}
@@ -257,8 +257,8 @@ const char* PseudoTypeToString(CSSSelector::PseudoType pseudo_type) {
DEFINE_STRING_MAPPING(PseudoLink)
DEFINE_STRING_MAPPING(PseudoVisited)
DEFINE_STRING_MAPPING(PseudoAny)
- DEFINE_STRING_MAPPING(PseudoMatches)
- DEFINE_STRING_MAPPING(PseudoIS)
+ DEFINE_STRING_MAPPING(PseudoIs)
+ DEFINE_STRING_MAPPING(PseudoWhere)
DEFINE_STRING_MAPPING(PseudoWebkitAnyLink)
DEFINE_STRING_MAPPING(PseudoAnyLink)
DEFINE_STRING_MAPPING(PseudoAutofill)
@@ -371,8 +371,8 @@ const char* NotStreamedReasonString(ScriptStreamer::NotStreamingReason reason) {
switch (reason) {
case ScriptStreamer::kNotHTTP:
return "not http/https protocol";
- case ScriptStreamer::kReload:
- return "reload event";
+ case ScriptStreamer::kRevalidate:
+ return "revalidation event";
case ScriptStreamer::kContextNotValid:
return "script context not valid";
case ScriptStreamer::kEncodingNotSupported:
@@ -395,6 +395,12 @@ const char* NotStreamedReasonString(ScriptStreamer::NotStreamingReason reason) {
return "start streaming not called";
case ScriptStreamer::kErrorOccurred:
return "an error occurred";
+ case ScriptStreamer::kStreamingDisabled:
+ return "already disabled streaming";
+ case ScriptStreamer::kSecondScriptResourceUse:
+ return "already used streamed data";
+ case ScriptStreamer::kWorkerTopLevelScript:
+ return "worker top-level scripts are not streamable";
case ScriptStreamer::kAlreadyLoaded:
case ScriptStreamer::kCount:
case ScriptStreamer::kInvalid:
@@ -406,7 +412,7 @@ const char* NotStreamedReasonString(ScriptStreamer::NotStreamingReason reason) {
} // namespace
-namespace InspectorScheduleStyleInvalidationTrackingEvent {
+namespace inspector_schedule_style_invalidation_tracking_event {
std::unique_ptr<TracedValue> FillCommonPart(
ContainerNode& node,
const InvalidationSet& invalidation_set,
@@ -421,15 +427,16 @@ std::unique_ptr<TracedValue> FillCommonPart(
SourceLocation::Capture()->ToTracedValue(value.get(), "stackTrace");
return value;
}
-} // namespace InspectorScheduleStyleInvalidationTrackingEvent
+} // namespace inspector_schedule_style_invalidation_tracking_event
-const char InspectorScheduleStyleInvalidationTrackingEvent::kAttribute[] =
+const char inspector_schedule_style_invalidation_tracking_event::kAttribute[] =
"attribute";
-const char InspectorScheduleStyleInvalidationTrackingEvent::kClass[] = "class";
-const char InspectorScheduleStyleInvalidationTrackingEvent::kId[] = "id";
-const char InspectorScheduleStyleInvalidationTrackingEvent::kPseudo[] =
+const char inspector_schedule_style_invalidation_tracking_event::kClass[] =
+ "class";
+const char inspector_schedule_style_invalidation_tracking_event::kId[] = "id";
+const char inspector_schedule_style_invalidation_tracking_event::kPseudo[] =
"pseudo";
-const char InspectorScheduleStyleInvalidationTrackingEvent::kRuleSet[] =
+const char inspector_schedule_style_invalidation_tracking_event::kRuleSet[] =
"ruleset";
const char* ResourcePriorityString(ResourceLoadPriority priority) {
@@ -457,7 +464,7 @@ const char* ResourcePriorityString(ResourceLoadPriority priority) {
}
std::unique_ptr<TracedValue>
-InspectorScheduleStyleInvalidationTrackingEvent::IdChange(
+inspector_schedule_style_invalidation_tracking_event::IdChange(
Element& element,
const InvalidationSet& invalidation_set,
const AtomicString& id) {
@@ -468,7 +475,7 @@ InspectorScheduleStyleInvalidationTrackingEvent::IdChange(
}
std::unique_ptr<TracedValue>
-InspectorScheduleStyleInvalidationTrackingEvent::ClassChange(
+inspector_schedule_style_invalidation_tracking_event::ClassChange(
Element& element,
const InvalidationSet& invalidation_set,
const AtomicString& class_name) {
@@ -479,7 +486,7 @@ InspectorScheduleStyleInvalidationTrackingEvent::ClassChange(
}
std::unique_ptr<TracedValue>
-InspectorScheduleStyleInvalidationTrackingEvent::AttributeChange(
+inspector_schedule_style_invalidation_tracking_event::AttributeChange(
Element& element,
const InvalidationSet& invalidation_set,
const QualifiedName& attribute_name) {
@@ -490,7 +497,7 @@ InspectorScheduleStyleInvalidationTrackingEvent::AttributeChange(
}
std::unique_ptr<TracedValue>
-InspectorScheduleStyleInvalidationTrackingEvent::PseudoChange(
+inspector_schedule_style_invalidation_tracking_event::PseudoChange(
Element& element,
const InvalidationSet& invalidation_set,
CSSSelector::PseudoType pseudo_type) {
@@ -501,7 +508,7 @@ InspectorScheduleStyleInvalidationTrackingEvent::PseudoChange(
}
std::unique_ptr<TracedValue>
-InspectorScheduleStyleInvalidationTrackingEvent::RuleSetInvalidation(
+inspector_schedule_style_invalidation_tracking_event::RuleSetInvalidation(
ContainerNode& root_node,
const InvalidationSet& invalidation_set) {
std::unique_ptr<TracedValue> value =
@@ -513,27 +520,25 @@ String DescendantInvalidationSetToIdString(const InvalidationSet& set) {
return ToHexString(&set);
}
-const char InspectorStyleInvalidatorInvalidateEvent::
+const char inspector_style_invalidator_invalidate_event::
kElementHasPendingInvalidationList[] =
"Element has pending invalidation list";
-const char InspectorStyleInvalidatorInvalidateEvent::kInvalidateCustomPseudo[] =
- "Invalidate custom pseudo element";
-const char InspectorStyleInvalidatorInvalidateEvent::
- kInvalidationSetMatchedAttribute[] = "Invalidation set matched attribute";
const char
- InspectorStyleInvalidatorInvalidateEvent::kInvalidationSetMatchedClass[] =
- "Invalidation set matched class";
+ inspector_style_invalidator_invalidate_event::kInvalidateCustomPseudo[] =
+ "Invalidate custom pseudo element";
+const char inspector_style_invalidator_invalidate_event::
+ kInvalidationSetMatchedAttribute[] = "Invalidation set matched attribute";
+const char inspector_style_invalidator_invalidate_event::
+ kInvalidationSetMatchedClass[] = "Invalidation set matched class";
const char
- InspectorStyleInvalidatorInvalidateEvent::kInvalidationSetMatchedId[] =
+ inspector_style_invalidator_invalidate_event::kInvalidationSetMatchedId[] =
"Invalidation set matched id";
-const char
- InspectorStyleInvalidatorInvalidateEvent::kInvalidationSetMatchedTagName[] =
- "Invalidation set matched tagName";
-const char
- InspectorStyleInvalidatorInvalidateEvent::kInvalidationSetMatchedPart[] =
- "Invalidation set matched part";
+const char inspector_style_invalidator_invalidate_event::
+ kInvalidationSetMatchedTagName[] = "Invalidation set matched tagName";
+const char inspector_style_invalidator_invalidate_event::
+ kInvalidationSetMatchedPart[] = "Invalidation set matched part";
-namespace InspectorStyleInvalidatorInvalidateEvent {
+namespace inspector_style_invalidator_invalidate_event {
std::unique_ptr<TracedValue> FillCommonPart(ContainerNode& node,
const char* reason) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -543,16 +548,16 @@ std::unique_ptr<TracedValue> FillCommonPart(ContainerNode& node,
value->SetString("reason", reason);
return value;
}
-} // namespace InspectorStyleInvalidatorInvalidateEvent
+} // namespace inspector_style_invalidator_invalidate_event
-std::unique_ptr<TracedValue> InspectorStyleInvalidatorInvalidateEvent::Data(
+std::unique_ptr<TracedValue> inspector_style_invalidator_invalidate_event::Data(
Element& element,
const char* reason) {
return FillCommonPart(element, reason);
}
std::unique_ptr<TracedValue>
-InspectorStyleInvalidatorInvalidateEvent::SelectorPart(
+inspector_style_invalidator_invalidate_event::SelectorPart(
Element& element,
const char* reason,
const InvalidationSet& invalidation_set,
@@ -566,7 +571,7 @@ InspectorStyleInvalidatorInvalidateEvent::SelectorPart(
}
std::unique_ptr<TracedValue>
-InspectorStyleInvalidatorInvalidateEvent::InvalidationList(
+inspector_style_invalidator_invalidate_event::InvalidationList(
ContainerNode& node,
const Vector<scoped_refptr<InvalidationSet>>& invalidation_list) {
std::unique_ptr<TracedValue> value =
@@ -579,7 +584,7 @@ InspectorStyleInvalidatorInvalidateEvent::InvalidationList(
}
std::unique_ptr<TracedValue>
-InspectorStyleRecalcInvalidationTrackingEvent::Data(
+inspector_style_recalc_invalidation_tracking_event::Data(
Node* node,
const StyleChangeReasonForTracing& reason) {
DCHECK(node);
@@ -594,7 +599,7 @@ InspectorStyleRecalcInvalidationTrackingEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorLayoutEvent::BeginData(
+std::unique_ptr<TracedValue> inspector_layout_event::BeginData(
LocalFrameView* frame_view) {
bool is_partial;
unsigned needs_layout_objects;
@@ -640,7 +645,7 @@ static void SetGeneratingNodeInfo(TracedValue* value,
SetNodeInfo(value, node, id_field_name, name_field_name);
}
-std::unique_ptr<TracedValue> InspectorLayoutEvent::EndData(
+std::unique_ptr<TracedValue> inspector_layout_event::EndData(
LayoutObject* root_for_this_layout) {
Vector<FloatQuad> quads;
root_for_this_layout->AbsoluteQuads(quads);
@@ -655,7 +660,7 @@ std::unique_ptr<TracedValue> InspectorLayoutEvent::EndData(
return value;
}
-namespace LayoutInvalidationReason {
+namespace layout_invalidation_reason {
const char kUnknown[] = "Unknown";
const char kSizeChanged[] = "Size changed";
const char kAncestorMoved[] = "Ancestor moved";
@@ -688,9 +693,10 @@ const char kPaddingChanged[] = "Padding changed";
const char kTextControlChanged[] = "Text control changed";
const char kSvgChanged[] = "SVG changed";
const char kScrollbarChanged[] = "Scrollbar changed";
-} // namespace LayoutInvalidationReason
+const char kDisplayLockCommitting[] = "Display lock committing";
+} // namespace layout_invalidation_reason
-std::unique_ptr<TracedValue> InspectorLayoutInvalidationTrackingEvent::Data(
+std::unique_ptr<TracedValue> inspector_layout_invalidation_tracking_event::Data(
const LayoutObject* layout_object,
LayoutInvalidationReasonForTracing reason) {
DCHECK(layout_object);
@@ -703,7 +709,7 @@ std::unique_ptr<TracedValue> InspectorLayoutInvalidationTrackingEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorPaintInvalidationTrackingEvent::Data(
+std::unique_ptr<TracedValue> inspector_paint_invalidation_tracking_event::Data(
const LayoutObject& layout_object) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("frame",
@@ -716,7 +722,7 @@ std::unique_ptr<TracedValue> InspectorPaintInvalidationTrackingEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorScrollInvalidationTrackingEvent::Data(
+std::unique_ptr<TracedValue> inspector_scroll_invalidation_tracking_event::Data(
const LayoutObject& layout_object) {
static const char kScrollInvalidationReason[] =
"Scroll with viewport-constrained element";
@@ -730,7 +736,7 @@ std::unique_ptr<TracedValue> InspectorScrollInvalidationTrackingEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorChangeResourcePriorityEvent::Data(
+std::unique_ptr<TracedValue> inspector_change_resource_priority_event::Data(
DocumentLoader* loader,
unsigned long identifier,
const ResourceLoadPriority& load_priority) {
@@ -742,7 +748,7 @@ std::unique_ptr<TracedValue> InspectorChangeResourcePriorityEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorSendRequestEvent::Data(
+std::unique_ptr<TracedValue> inspector_send_request_event::Data(
DocumentLoader* loader,
unsigned long identifier,
LocalFrame* frame,
@@ -795,7 +801,7 @@ void RecordTiming(const ResourceLoadTiming& timing, TracedValue* value) {
}
} // namespace
-std::unique_ptr<TracedValue> InspectorReceiveResponseEvent::Data(
+std::unique_ptr<TracedValue> inspector_receive_response_event::Data(
DocumentLoader* loader,
unsigned long identifier,
LocalFrame* frame,
@@ -820,7 +826,7 @@ std::unique_ptr<TracedValue> InspectorReceiveResponseEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorReceiveDataEvent::Data(
+std::unique_ptr<TracedValue> inspector_receive_data_event::Data(
DocumentLoader* loader,
unsigned long identifier,
LocalFrame* frame,
@@ -834,7 +840,7 @@ std::unique_ptr<TracedValue> InspectorReceiveDataEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorResourceFinishEvent::Data(
+std::unique_ptr<TracedValue> inspector_resource_finish_event::Data(
DocumentLoader* loader,
unsigned long identifier,
TimeTicks finish_time,
@@ -868,7 +874,7 @@ static std::unique_ptr<TracedValue> GenericTimerData(ExecutionContext* context,
return value;
}
-std::unique_ptr<TracedValue> InspectorTimerInstallEvent::Data(
+std::unique_ptr<TracedValue> inspector_timer_install_event::Data(
ExecutionContext* context,
int timer_id,
TimeDelta timeout,
@@ -880,7 +886,7 @@ std::unique_ptr<TracedValue> InspectorTimerInstallEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorTimerRemoveEvent::Data(
+std::unique_ptr<TracedValue> inspector_timer_remove_event::Data(
ExecutionContext* context,
int timer_id) {
std::unique_ptr<TracedValue> value = GenericTimerData(context, timer_id);
@@ -888,13 +894,13 @@ std::unique_ptr<TracedValue> InspectorTimerRemoveEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorTimerFireEvent::Data(
+std::unique_ptr<TracedValue> inspector_timer_fire_event::Data(
ExecutionContext* context,
int timer_id) {
return GenericTimerData(context, timer_id);
}
-std::unique_ptr<TracedValue> InspectorAnimationFrameEvent::Data(
+std::unique_ptr<TracedValue> inspector_animation_frame_event::Data(
ExecutionContext* context,
int callback_id) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -902,8 +908,8 @@ std::unique_ptr<TracedValue> InspectorAnimationFrameEvent::Data(
if (auto* document = DynamicTo<Document>(context)) {
value->SetString("frame",
IdentifiersFactory::FrameId(document->GetFrame()));
- } else if (context->IsWorkerGlobalScope()) {
- value->SetString("worker", ToHexString(ToWorkerGlobalScope(context)));
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(context)) {
+ value->SetString("worker", ToHexString(scope));
}
SetCallStack(value.get());
return value;
@@ -919,7 +925,7 @@ std::unique_ptr<TracedValue> GenericIdleCallbackEvent(ExecutionContext* context,
return value;
}
-std::unique_ptr<TracedValue> InspectorIdleCallbackRequestEvent::Data(
+std::unique_ptr<TracedValue> inspector_idle_callback_request_event::Data(
ExecutionContext* context,
int id,
double timeout) {
@@ -928,13 +934,13 @@ std::unique_ptr<TracedValue> InspectorIdleCallbackRequestEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorIdleCallbackCancelEvent::Data(
+std::unique_ptr<TracedValue> inspector_idle_callback_cancel_event::Data(
ExecutionContext* context,
int id) {
return GenericIdleCallbackEvent(context, id);
}
-std::unique_ptr<TracedValue> InspectorIdleCallbackFireEvent::Data(
+std::unique_ptr<TracedValue> inspector_idle_callback_fire_event::Data(
ExecutionContext* context,
int id,
double allotted_milliseconds,
@@ -945,14 +951,14 @@ std::unique_ptr<TracedValue> InspectorIdleCallbackFireEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorParseAuthorStyleSheetEvent::Data(
+std::unique_ptr<TracedValue> inspector_parse_author_style_sheet_event::Data(
const CSSStyleSheetResource* cached_style_sheet) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("styleSheetUrl", cached_style_sheet->Url().GetString());
return value;
}
-std::unique_ptr<TracedValue> InspectorXhrReadyStateChangeEvent::Data(
+std::unique_ptr<TracedValue> inspector_xhr_ready_state_change_event::Data(
ExecutionContext* context,
XMLHttpRequest* request) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -964,7 +970,7 @@ std::unique_ptr<TracedValue> InspectorXhrReadyStateChangeEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorXhrLoadEvent::Data(
+std::unique_ptr<TracedValue> inspector_xhr_load_event::Data(
ExecutionContext* context,
XMLHttpRequest* request) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -993,20 +999,22 @@ static void LocalToPageQuad(const LayoutObject& layout_object,
quad->SetP4(LocalCoordToFloatPoint(view, absolute.P4()));
}
-const char InspectorLayerInvalidationTrackingEvent::
+const char inspector_layer_invalidation_tracking_event::
kSquashingLayerGeometryWasUpdated[] =
"Squashing layer geometry was updated";
-const char InspectorLayerInvalidationTrackingEvent::kAddedToSquashingLayer[] =
- "The layer may have been added to an already-existing squashing layer";
const char
- InspectorLayerInvalidationTrackingEvent::kRemovedFromSquashingLayer[] =
+ inspector_layer_invalidation_tracking_event::kAddedToSquashingLayer[] =
+ "The layer may have been added to an already-existing squashing layer";
+const char
+ inspector_layer_invalidation_tracking_event::kRemovedFromSquashingLayer[] =
"Removed the layer from a squashing layer";
-const char InspectorLayerInvalidationTrackingEvent::kReflectionLayerChanged[] =
- "Reflection layer change";
-const char InspectorLayerInvalidationTrackingEvent::kNewCompositedLayer[] =
+const char
+ inspector_layer_invalidation_tracking_event::kReflectionLayerChanged[] =
+ "Reflection layer change";
+const char inspector_layer_invalidation_tracking_event::kNewCompositedLayer[] =
"Assigned a new composited layer";
-std::unique_ptr<TracedValue> InspectorLayerInvalidationTrackingEvent::Data(
+std::unique_ptr<TracedValue> inspector_layer_invalidation_tracking_event::Data(
const PaintLayer* layer,
const char* reason) {
const LayoutObject& paint_invalidation_container =
@@ -1020,7 +1028,7 @@ std::unique_ptr<TracedValue> InspectorLayerInvalidationTrackingEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorPaintEvent::Data(
+std::unique_ptr<TracedValue> inspector_paint_event::Data(
LayoutObject* layout_object,
const LayoutRect& clip_rect,
const GraphicsLayer* graphics_layer) {
@@ -1063,19 +1071,21 @@ void FillCommonFrameData(TracedValue* frame_data, LocalFrame* frame) {
frame_data->SetString("parent", IdentifiersFactory::FrameId(parent));
}
-std::unique_ptr<TracedValue> InspectorCommitLoadEvent::Data(LocalFrame* frame) {
+std::unique_ptr<TracedValue> inspector_commit_load_event::Data(
+ LocalFrame* frame) {
std::unique_ptr<TracedValue> frame_data = FrameEventData(frame);
FillCommonFrameData(frame_data.get(), frame);
return frame_data;
}
-std::unique_ptr<TracedValue> InspectorMarkLoadEvent::Data(LocalFrame* frame) {
+std::unique_ptr<TracedValue> inspector_mark_load_event::Data(
+ LocalFrame* frame) {
std::unique_ptr<TracedValue> frame_data = FrameEventData(frame);
frame_data->SetString("frame", IdentifiersFactory::FrameId(frame));
return frame_data;
}
-std::unique_ptr<TracedValue> InspectorScrollLayerEvent::Data(
+std::unique_ptr<TracedValue> inspector_scroll_layer_event::Data(
LayoutObject* layout_object) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("frame",
@@ -1084,7 +1094,7 @@ std::unique_ptr<TracedValue> InspectorScrollLayerEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorUpdateLayerTreeEvent::Data(
+std::unique_ptr<TracedValue> inspector_update_layer_tree_event::Data(
LocalFrame* frame) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("frame", IdentifiersFactory::FrameId(frame));
@@ -1102,7 +1112,7 @@ std::unique_ptr<TracedValue> FillLocation(const String& url,
}
} // namespace
-std::unique_ptr<TracedValue> InspectorEvaluateScriptEvent::Data(
+std::unique_ptr<TracedValue> inspector_evaluate_script_event::Data(
LocalFrame* frame,
const String& url,
const TextPosition& text_position) {
@@ -1112,7 +1122,7 @@ std::unique_ptr<TracedValue> InspectorEvaluateScriptEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorParseScriptEvent::Data(
+std::unique_ptr<TracedValue> inspector_parse_script_event::Data(
unsigned long identifier,
const String& url) {
String request_id = IdentifiersFactory::RequestId(nullptr, identifier);
@@ -1122,7 +1132,7 @@ std::unique_ptr<TracedValue> InspectorParseScriptEvent::Data(
return value;
}
-InspectorCompileScriptEvent::V8CacheResult::ProduceResult::ProduceResult(
+inspector_compile_script_event::V8CacheResult::ProduceResult::ProduceResult(
v8::ScriptCompiler::CompileOptions produce_options,
int cache_size)
: produce_options(produce_options), cache_size(cache_size) {
@@ -1130,7 +1140,7 @@ InspectorCompileScriptEvent::V8CacheResult::ProduceResult::ProduceResult(
produce_options == v8::ScriptCompiler::kEagerCompile);
}
-InspectorCompileScriptEvent::V8CacheResult::ConsumeResult::ConsumeResult(
+inspector_compile_script_event::V8CacheResult::ConsumeResult::ConsumeResult(
v8::ScriptCompiler::CompileOptions consume_options,
int cache_size,
bool rejected)
@@ -1140,13 +1150,13 @@ InspectorCompileScriptEvent::V8CacheResult::ConsumeResult::ConsumeResult(
DCHECK_EQ(consume_options, v8::ScriptCompiler::kConsumeCodeCache);
}
-InspectorCompileScriptEvent::V8CacheResult::V8CacheResult(
+inspector_compile_script_event::V8CacheResult::V8CacheResult(
base::Optional<ProduceResult> produce_result,
base::Optional<ConsumeResult> consume_result)
: produce_result(std::move(produce_result)),
consume_result(std::move(consume_result)) {}
-std::unique_ptr<TracedValue> InspectorCompileScriptEvent::Data(
+std::unique_ptr<TracedValue> inspector_compile_script_event::Data(
const String& url,
const TextPosition& text_position,
const V8CacheResult& cache_result,
@@ -1178,7 +1188,7 @@ std::unique_ptr<TracedValue> InspectorCompileScriptEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorFunctionCallEvent::Data(
+std::unique_ptr<TracedValue> inspector_function_call_event::Data(
ExecutionContext* context,
const v8::Local<v8::Function>& function) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -1203,7 +1213,7 @@ std::unique_ptr<TracedValue> InspectorFunctionCallEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
+std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
const LayoutImage& layout_image,
const FloatRect& src_rect,
const FloatRect& dest_rect) {
@@ -1222,7 +1232,7 @@ std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
+std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
const LayoutObject& owning_layout_object,
const StyleImage& style_image) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -1232,7 +1242,7 @@ std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
+std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
Node* node,
const StyleImage& style_image,
const FloatRect& src_rect,
@@ -1253,7 +1263,7 @@ std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorPaintImageEvent::Data(
+std::unique_ptr<TracedValue> inspector_paint_image_event::Data(
const LayoutObject* owning_layout_object,
const ImageResourceContent& image_resource) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -1268,7 +1278,7 @@ static size_t UsedHeapSize() {
return heap_statistics.used_heap_size();
}
-std::unique_ptr<TracedValue> InspectorUpdateCountersEvent::Data() {
+std::unique_ptr<TracedValue> inspector_update_counters_event::Data() {
std::unique_ptr<TracedValue> value = TracedValue::Create();
if (IsMainThread()) {
value->SetInteger("documents", InstanceCounters::CounterValue(
@@ -1283,7 +1293,7 @@ std::unique_ptr<TracedValue> InspectorUpdateCountersEvent::Data() {
return value;
}
-std::unique_ptr<TracedValue> InspectorInvalidateLayoutEvent::Data(
+std::unique_ptr<TracedValue> inspector_invalidate_layout_event::Data(
LocalFrame* frame) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("frame", IdentifiersFactory::FrameId(frame));
@@ -1291,7 +1301,7 @@ std::unique_ptr<TracedValue> InspectorInvalidateLayoutEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorRecalculateStylesEvent::Data(
+std::unique_ptr<TracedValue> inspector_recalculate_styles_event::Data(
LocalFrame* frame) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("frame", IdentifiersFactory::FrameId(frame));
@@ -1299,7 +1309,7 @@ std::unique_ptr<TracedValue> InspectorRecalculateStylesEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorEventDispatchEvent::Data(
+std::unique_ptr<TracedValue> inspector_event_dispatch_event::Data(
const Event& event) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("type", event.type());
@@ -1307,7 +1317,7 @@ std::unique_ptr<TracedValue> InspectorEventDispatchEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorTimeStampEvent::Data(
+std::unique_ptr<TracedValue> inspector_time_stamp_event::Data(
ExecutionContext* context,
const String& message) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -1317,7 +1327,8 @@ std::unique_ptr<TracedValue> InspectorTimeStampEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorTracingSessionIdForWorkerEvent::Data(
+std::unique_ptr<TracedValue>
+inspector_tracing_session_id_for_worker_event::Data(
const base::UnguessableToken& worker_devtools_token,
const base::UnguessableToken& parent_devtools_token,
const KURL& url,
@@ -1332,7 +1343,7 @@ std::unique_ptr<TracedValue> InspectorTracingSessionIdForWorkerEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorTracingStartedInFrame::Data(
+std::unique_ptr<TracedValue> inspector_tracing_started_in_frame::Data(
const String& session_id,
LocalFrame* frame) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
@@ -1352,7 +1363,8 @@ std::unique_ptr<TracedValue> InspectorTracingStartedInFrame::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorSetLayerTreeId::Data(LocalFrame* frame) {
+std::unique_ptr<TracedValue> inspector_set_layer_tree_id::Data(
+ LocalFrame* frame) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("frame", IdentifiersFactory::FrameId(frame));
WebLayerTreeView* layerTreeView =
@@ -1362,7 +1374,7 @@ std::unique_ptr<TracedValue> InspectorSetLayerTreeId::Data(LocalFrame* frame) {
return value;
}
-std::unique_ptr<TracedValue> InspectorAnimationEvent::Data(
+std::unique_ptr<TracedValue> inspector_animation_event::Data(
const Animation& animation) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("id", String::Number(animation.SequenceNumber()));
@@ -1377,14 +1389,14 @@ std::unique_ptr<TracedValue> InspectorAnimationEvent::Data(
return value;
}
-std::unique_ptr<TracedValue> InspectorAnimationStateEvent::Data(
+std::unique_ptr<TracedValue> inspector_animation_state_event::Data(
const Animation& animation) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("state", animation.playState());
return value;
}
-std::unique_ptr<TracedValue> InspectorHitTestEvent::EndData(
+std::unique_ptr<TracedValue> inspector_hit_test_event::EndData(
const HitTestRequest& request,
const HitTestLocation& location,
const HitTestResult& result) {
@@ -1406,7 +1418,8 @@ std::unique_ptr<TracedValue> InspectorHitTestEvent::EndData(
return value;
}
-std::unique_ptr<TracedValue> InspectorAsyncTask::Data(const StringView& name) {
+std::unique_ptr<TracedValue> inspector_async_task::Data(
+ const StringView& name) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("name", name.ToString());
return value;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.h b/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.h
index 5b0e5db87c3..b52199fda1f 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.h
@@ -126,12 +126,12 @@ class CORE_EXPORT InspectorTraceEvents
DISALLOW_COPY_AND_ASSIGN(InspectorTraceEvents);
};
-namespace InspectorLayoutEvent {
+namespace inspector_layout_event {
std::unique_ptr<TracedValue> BeginData(LocalFrameView*);
std::unique_ptr<TracedValue> EndData(LayoutObject* root_for_this_layout);
-} // namespace InspectorLayoutEvent
+} // namespace inspector_layout_event
-namespace InspectorScheduleStyleInvalidationTrackingEvent {
+namespace inspector_schedule_style_invalidation_tracking_event {
extern const char kAttribute[];
extern const char kClass[];
extern const char kId[];
@@ -152,23 +152,23 @@ std::unique_ptr<TracedValue> PseudoChange(Element&,
CSSSelector::PseudoType);
std::unique_ptr<TracedValue> RuleSetInvalidation(ContainerNode&,
const InvalidationSet&);
-} // namespace InspectorScheduleStyleInvalidationTrackingEvent
+} // namespace inspector_schedule_style_invalidation_tracking_event
#define TRACE_SCHEDULE_STYLE_INVALIDATION(element, invalidationSet, \
changeType, ...) \
TRACE_EVENT_INSTANT1( \
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"), \
"ScheduleStyleInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data", \
- InspectorScheduleStyleInvalidationTrackingEvent::changeType( \
+ inspector_schedule_style_invalidation_tracking_event::changeType( \
(element), (invalidationSet), ##__VA_ARGS__));
-namespace InspectorStyleRecalcInvalidationTrackingEvent {
+namespace inspector_style_recalc_invalidation_tracking_event {
std::unique_ptr<TracedValue> Data(Node*, const StyleChangeReasonForTracing&);
}
String DescendantInvalidationSetToIdString(const InvalidationSet&);
-namespace InspectorStyleInvalidatorInvalidateEvent {
+namespace inspector_style_invalidator_invalidate_event {
extern const char kElementHasPendingInvalidationList[];
extern const char kInvalidateCustomPseudo[];
extern const char kInvalidationSetMatchedAttribute[];
@@ -185,29 +185,29 @@ std::unique_ptr<TracedValue> SelectorPart(Element&,
std::unique_ptr<TracedValue> InvalidationList(
ContainerNode&,
const Vector<scoped_refptr<InvalidationSet>>&);
-} // namespace InspectorStyleInvalidatorInvalidateEvent
+} // namespace inspector_style_invalidator_invalidate_event
#define TRACE_STYLE_INVALIDATOR_INVALIDATION(element, reason) \
TRACE_EVENT_INSTANT1( \
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"), \
"StyleInvalidatorInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, \
"data", \
- InspectorStyleInvalidatorInvalidateEvent::Data( \
- (element), (InspectorStyleInvalidatorInvalidateEvent::reason)))
+ inspector_style_invalidator_invalidate_event::Data( \
+ (element), (inspector_style_invalidator_invalidate_event::reason)))
-#define TRACE_STYLE_INVALIDATOR_INVALIDATION_SELECTORPART( \
- element, reason, invalidationSet, singleSelectorPart) \
- TRACE_EVENT_INSTANT1( \
- TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"), \
- "StyleInvalidatorInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, \
- "data", \
- InspectorStyleInvalidatorInvalidateEvent::SelectorPart( \
- (element), (InspectorStyleInvalidatorInvalidateEvent::reason), \
+#define TRACE_STYLE_INVALIDATOR_INVALIDATION_SELECTORPART( \
+ element, reason, invalidationSet, singleSelectorPart) \
+ TRACE_EVENT_INSTANT1( \
+ TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"), \
+ "StyleInvalidatorInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, \
+ "data", \
+ inspector_style_invalidator_invalidate_event::SelectorPart( \
+ (element), (inspector_style_invalidator_invalidate_event::reason), \
(invalidationSet), (singleSelectorPart)))
// From a web developer's perspective: what caused this layout? This is strictly
// for tracing. Blink logic must not depend on these.
-namespace LayoutInvalidationReason {
+namespace layout_invalidation_reason {
extern const char kUnknown[];
extern const char kSizeChanged[];
extern const char kAncestorMoved[];
@@ -242,53 +242,54 @@ extern const char kTextControlChanged[];
// size related invalidations.
extern const char kSvgChanged[];
extern const char kScrollbarChanged[];
-} // namespace LayoutInvalidationReason
+extern const char kDisplayLockCommitting[];
+} // namespace layout_invalidation_reason
// LayoutInvalidationReasonForTracing is strictly for tracing. Blink logic must
// not depend on this value.
typedef const char LayoutInvalidationReasonForTracing[];
-namespace InspectorLayoutInvalidationTrackingEvent {
+namespace inspector_layout_invalidation_tracking_event {
std::unique_ptr<TracedValue> CORE_EXPORT
Data(const LayoutObject*, LayoutInvalidationReasonForTracing);
}
-namespace InspectorPaintInvalidationTrackingEvent {
+namespace inspector_paint_invalidation_tracking_event {
std::unique_ptr<TracedValue> Data(const LayoutObject&);
}
-namespace InspectorScrollInvalidationTrackingEvent {
+namespace inspector_scroll_invalidation_tracking_event {
std::unique_ptr<TracedValue> Data(const LayoutObject&);
}
-namespace InspectorChangeResourcePriorityEvent {
+namespace inspector_change_resource_priority_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
unsigned long identifier,
const ResourceLoadPriority&);
}
-namespace InspectorSendRequestEvent {
+namespace inspector_send_request_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
unsigned long identifier,
LocalFrame*,
const ResourceRequest&);
}
-namespace InspectorReceiveResponseEvent {
+namespace inspector_receive_response_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
unsigned long identifier,
LocalFrame*,
const ResourceResponse&);
}
-namespace InspectorReceiveDataEvent {
+namespace inspector_receive_data_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
unsigned long identifier,
LocalFrame*,
int encoded_data_length);
}
-namespace InspectorResourceFinishEvent {
+namespace inspector_resource_finish_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
unsigned long identifier,
TimeTicks finish_time,
@@ -297,53 +298,53 @@ std::unique_ptr<TracedValue> Data(DocumentLoader*,
int64_t decoded_body_length);
}
-namespace InspectorTimerInstallEvent {
+namespace inspector_timer_install_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*,
int timer_id,
TimeDelta timeout,
bool single_shot);
}
-namespace InspectorTimerRemoveEvent {
+namespace inspector_timer_remove_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, int timer_id);
}
-namespace InspectorTimerFireEvent {
+namespace inspector_timer_fire_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, int timer_id);
}
-namespace InspectorIdleCallbackRequestEvent {
+namespace inspector_idle_callback_request_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, int id, double timeout);
}
-namespace InspectorIdleCallbackCancelEvent {
+namespace inspector_idle_callback_cancel_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, int id);
}
-namespace InspectorIdleCallbackFireEvent {
+namespace inspector_idle_callback_fire_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*,
int id,
double allotted_milliseconds,
bool timed_out);
}
-namespace InspectorAnimationFrameEvent {
+namespace inspector_animation_frame_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, int callback_id);
}
-namespace InspectorParseAuthorStyleSheetEvent {
+namespace inspector_parse_author_style_sheet_event {
std::unique_ptr<TracedValue> Data(const CSSStyleSheetResource*);
}
-namespace InspectorXhrReadyStateChangeEvent {
+namespace inspector_xhr_ready_state_change_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, XMLHttpRequest*);
}
-namespace InspectorXhrLoadEvent {
+namespace inspector_xhr_load_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, XMLHttpRequest*);
}
-namespace InspectorLayerInvalidationTrackingEvent {
+namespace inspector_layer_invalidation_tracking_event {
extern const char kSquashingLayerGeometryWasUpdated[];
extern const char kAddedToSquashingLayer[];
extern const char kRemovedFromSquashingLayer[];
@@ -351,21 +352,21 @@ extern const char kReflectionLayerChanged[];
extern const char kNewCompositedLayer[];
std::unique_ptr<TracedValue> Data(const PaintLayer*, const char* reason);
-} // namespace InspectorLayerInvalidationTrackingEvent
+} // namespace inspector_layer_invalidation_tracking_event
#define TRACE_LAYER_INVALIDATION(LAYER, REASON) \
TRACE_EVENT_INSTANT1( \
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"), \
"LayerInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data", \
- InspectorLayerInvalidationTrackingEvent::Data((LAYER), (REASON)));
+ inspector_layer_invalidation_tracking_event::Data((LAYER), (REASON)));
-namespace InspectorPaintEvent {
+namespace inspector_paint_event {
std::unique_ptr<TracedValue> Data(LayoutObject*,
const LayoutRect& clip_rect,
const GraphicsLayer*);
}
-namespace InspectorPaintImageEvent {
+namespace inspector_paint_image_event {
std::unique_ptr<TracedValue> Data(const LayoutImage&,
const FloatRect& src_rect,
const FloatRect& dest_rect);
@@ -376,35 +377,35 @@ std::unique_ptr<TracedValue> Data(Node*,
const FloatRect& dest_rect);
std::unique_ptr<TracedValue> Data(const LayoutObject*,
const ImageResourceContent&);
-} // namespace InspectorPaintImageEvent
+} // namespace inspector_paint_image_event
-namespace InspectorCommitLoadEvent {
+namespace inspector_commit_load_event {
std::unique_ptr<TracedValue> Data(LocalFrame*);
}
-namespace InspectorMarkLoadEvent {
+namespace inspector_mark_load_event {
std::unique_ptr<TracedValue> Data(LocalFrame*);
}
-namespace InspectorScrollLayerEvent {
+namespace inspector_scroll_layer_event {
std::unique_ptr<TracedValue> Data(LayoutObject*);
}
-namespace InspectorUpdateLayerTreeEvent {
+namespace inspector_update_layer_tree_event {
std::unique_ptr<TracedValue> Data(LocalFrame*);
}
-namespace InspectorEvaluateScriptEvent {
+namespace inspector_evaluate_script_event {
std::unique_ptr<TracedValue> Data(LocalFrame*,
const String& url,
const WTF::TextPosition&);
}
-namespace InspectorParseScriptEvent {
+namespace inspector_parse_script_event {
std::unique_ptr<TracedValue> Data(unsigned long identifier, const String& url);
}
-namespace InspectorCompileScriptEvent {
+namespace inspector_compile_script_event {
struct V8CacheResult {
struct ProduceResult {
@@ -433,34 +434,34 @@ std::unique_ptr<TracedValue> Data(const String& url,
const V8CacheResult&,
bool streamed,
ScriptStreamer::NotStreamingReason);
-} // namespace InspectorCompileScriptEvent
+} // namespace inspector_compile_script_event
-namespace InspectorFunctionCallEvent {
+namespace inspector_function_call_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*,
const v8::Local<v8::Function>&);
}
-namespace InspectorUpdateCountersEvent {
+namespace inspector_update_counters_event {
std::unique_ptr<TracedValue> Data();
}
-namespace InspectorInvalidateLayoutEvent {
+namespace inspector_invalidate_layout_event {
std::unique_ptr<TracedValue> Data(LocalFrame*);
}
-namespace InspectorRecalculateStylesEvent {
+namespace inspector_recalculate_styles_event {
std::unique_ptr<TracedValue> Data(LocalFrame*);
}
-namespace InspectorEventDispatchEvent {
+namespace inspector_event_dispatch_event {
std::unique_ptr<TracedValue> Data(const Event&);
}
-namespace InspectorTimeStampEvent {
+namespace inspector_time_stamp_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, const String& message);
}
-namespace InspectorTracingSessionIdForWorkerEvent {
+namespace inspector_tracing_session_id_for_worker_event {
std::unique_ptr<TracedValue> Data(
const base::UnguessableToken& worker_devtools_token,
const base::UnguessableToken& parent_devtools_token,
@@ -468,29 +469,29 @@ std::unique_ptr<TracedValue> Data(
PlatformThreadId worker_thread_id);
}
-namespace InspectorTracingStartedInFrame {
+namespace inspector_tracing_started_in_frame {
std::unique_ptr<TracedValue> Data(const String& session_id, LocalFrame*);
}
-namespace InspectorSetLayerTreeId {
+namespace inspector_set_layer_tree_id {
std::unique_ptr<TracedValue> Data(LocalFrame* local_root);
}
-namespace InspectorAnimationEvent {
+namespace inspector_animation_event {
std::unique_ptr<TracedValue> Data(const Animation&);
}
-namespace InspectorAnimationStateEvent {
+namespace inspector_animation_state_event {
std::unique_ptr<TracedValue> Data(const Animation&);
}
-namespace InspectorHitTestEvent {
+namespace inspector_hit_test_event {
std::unique_ptr<TracedValue> EndData(const HitTestRequest&,
const HitTestLocation&,
const HitTestResult&);
}
-namespace InspectorAsyncTask {
+namespace inspector_async_task {
std::unique_ptr<TracedValue> Data(const StringView&);
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.cc
deleted file mode 100644
index 1bc6721bd0c..00000000000
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.cc
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/core/inspector/inspector_worker_agent.h"
-
-#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
-#include "third_party/blink/renderer/core/workers/execution_context_worker_registry.h"
-#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-
-using protocol::Maybe;
-using protocol::Response;
-
-int InspectorWorkerAgent::s_last_connection_ = 0;
-
-InspectorWorkerAgent::InspectorWorkerAgent(
- InspectedFrames* inspected_frames,
- WorkerGlobalScope* worker_global_scope)
- : inspected_frames_(inspected_frames),
- worker_global_scope_(worker_global_scope),
- auto_attach_(&agent_state_, /*default_value=*/ false),
- wait_for_debugger_on_start_(&agent_state_, /*default_value=*/ false),
- attached_session_ids_(&agent_state_, /*default_value*/ false) {}
-
-InspectorWorkerAgent::~InspectorWorkerAgent() = default;
-
-void InspectorWorkerAgent::Restore() {
- if (!auto_attach_.Get())
- return;
- instrumenting_agents_->addInspectorWorkerAgent(this);
- for (const WTF::String& session_id : attached_session_ids_.Keys())
- GetFrontend()->detachedFromTarget(session_id);
- attached_session_ids_.Clear();
- ConnectToAllProxies();
-}
-
-Response InspectorWorkerAgent::disable() {
- if (auto_attach_.Get()) {
- DisconnectFromAllProxies(false);
- instrumenting_agents_->removeInspectorWorkerAgent(this);
- }
- agent_state_.ClearAllFields();
- return Response::OK();
-}
-
-Response InspectorWorkerAgent::setAutoAttach(bool auto_attach,
- bool wait_for_debugger_on_start,
- Maybe<bool> flatten) {
- wait_for_debugger_on_start_.Set(wait_for_debugger_on_start);
-
- if (auto_attach == auto_attach_.Get())
- return Response::OK();
- auto_attach_.Set(auto_attach);
- if (auto_attach) {
- instrumenting_agents_->addInspectorWorkerAgent(this);
- ConnectToAllProxies();
- } else {
- DisconnectFromAllProxies(true);
- instrumenting_agents_->removeInspectorWorkerAgent(this);
- }
- return Response::OK();
-}
-
-Response InspectorWorkerAgent::sendMessageToTarget(const String& message,
- Maybe<String> session_id,
- Maybe<String> target_id) {
- if (session_id.isJust()) {
- auto it = session_id_to_connection_.find(session_id.fromJust());
- if (it == session_id_to_connection_.end())
- return Response::Error("No session with given id");
- WorkerInspectorProxy* proxy = connected_proxies_.at(it->value);
- proxy->SendMessageToInspector(it->value, message);
- return Response::OK();
- }
- if (target_id.isJust()) {
- int connection = 0;
- for (auto& it : connected_proxies_) {
- if (it.value->InspectorId() == target_id.fromJust()) {
- if (connection)
- return Response::Error("Multiple sessions attached, specify id");
- connection = it.key;
- }
- }
- if (!connection)
- return Response::Error("No target with given id");
- WorkerInspectorProxy* proxy = connected_proxies_.at(connection);
- proxy->SendMessageToInspector(connection, message);
- return Response::OK();
- }
- return Response::Error("Session id must be specified");
-}
-
-void InspectorWorkerAgent::ShouldWaitForDebuggerOnWorkerStart(bool* result) {
- if (auto_attach_.Get() && wait_for_debugger_on_start_.Get())
- *result = true;
-}
-
-void InspectorWorkerAgent::DidStartWorker(WorkerInspectorProxy* proxy,
- bool waiting_for_debugger) {
- DCHECK(GetFrontend() && auto_attach_.Get());
- ConnectToProxy(proxy, waiting_for_debugger);
-}
-
-void InspectorWorkerAgent::WorkerTerminated(WorkerInspectorProxy* proxy) {
- DCHECK(GetFrontend() && auto_attach_.Get());
- Vector<String> session_ids;
- for (auto& it : session_id_to_connection_) {
- if (connected_proxies_.at(it.value) == proxy)
- session_ids.push_back(it.key);
- }
- for (const String& session_id : session_ids) {
- attached_session_ids_.Clear(session_id);
- GetFrontend()->detachedFromTarget(session_id, proxy->InspectorId());
- int connection = session_id_to_connection_.at(session_id);
- proxy->DisconnectFromInspector(connection, this);
- connected_proxies_.erase(connection);
- connection_to_session_id_.erase(connection);
- session_id_to_connection_.erase(session_id);
- }
-}
-
-void InspectorWorkerAgent::ConnectToAllProxies() {
- if (worker_global_scope_) {
- for (WorkerInspectorProxy* proxy :
- ExecutionContextWorkerRegistry::From(*worker_global_scope_)
- ->GetWorkerInspectorProxies()) {
- ConnectToProxy(proxy, false);
- }
- return;
- }
-
- for (LocalFrame* frame : *inspected_frames_) {
- for (WorkerInspectorProxy* proxy :
- ExecutionContextWorkerRegistry::From(*frame->GetDocument())
- ->GetWorkerInspectorProxies()) {
- ConnectToProxy(proxy, false);
- }
- }
-}
-
-void InspectorWorkerAgent::DisconnectFromAllProxies(bool report_to_frontend) {
- for (auto& it : session_id_to_connection_) {
- WorkerInspectorProxy* proxy = connected_proxies_.at(it.value);
- if (report_to_frontend) {
- attached_session_ids_.Clear(it.key);
- GetFrontend()->detachedFromTarget(it.key, proxy->InspectorId());
- }
- proxy->DisconnectFromInspector(it.value, this);
- }
- connection_to_session_id_.clear();
- session_id_to_connection_.clear();
- connected_proxies_.clear();
-}
-
-void InspectorWorkerAgent::DidCommitLoadForLocalFrame(LocalFrame* frame) {
- if (!auto_attach_.Get() || frame != inspected_frames_->Root())
- return;
-
- // During navigation workers from old page may die after a while.
- // Usually, it's fine to report them terminated later, but some tests
- // expect strict set of workers, and we reuse renderer between tests.
- DisconnectFromAllProxies(true);
-}
-
-void InspectorWorkerAgent::ConnectToProxy(WorkerInspectorProxy* proxy,
- bool waiting_for_debugger) {
- int connection = ++s_last_connection_;
- connected_proxies_.Set(connection, proxy);
-
- String session_id = proxy->InspectorId() + "-" + String::Number(connection);
- session_id_to_connection_.Set(session_id, connection);
- connection_to_session_id_.Set(connection, session_id);
-
- proxy->ConnectToInspector(connection, this);
- DCHECK(GetFrontend());
- attached_session_ids_.Set(session_id, true);
- GetFrontend()->attachedToTarget(session_id,
- protocol::Target::TargetInfo::create()
- .setTargetId(proxy->InspectorId())
- .setType("worker")
- .setTitle(proxy->Url())
- .setUrl(proxy->Url())
- .setAttached(true)
- .build(),
- waiting_for_debugger);
-}
-
-void InspectorWorkerAgent::DispatchMessageFromWorker(
- WorkerInspectorProxy* proxy,
- int connection,
- const String& message) {
- auto it = connection_to_session_id_.find(connection);
- if (it == connection_to_session_id_.end())
- return;
- GetFrontend()->receivedMessageFromTarget(it->value, message,
- proxy->InspectorId());
-}
-
-void InspectorWorkerAgent::Trace(blink::Visitor* visitor) {
- visitor->Trace(connected_proxies_);
- visitor->Trace(inspected_frames_);
- visitor->Trace(worker_global_scope_);
- InspectorBaseAgent::Trace(visitor);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.h
deleted file mode 100644
index 6f2a733f327..00000000000
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_worker_agent.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_WORKER_AGENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_WORKER_AGENT_H_
-
-#include "base/macros.h"
-#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/inspector/inspector_base_agent.h"
-#include "third_party/blink/renderer/core/inspector/protocol/Target.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
-
-namespace blink {
-class InspectedFrames;
-class WorkerGlobalScope;
-class WorkerInspectorProxy;
-
-class CORE_EXPORT InspectorWorkerAgent final
- : public InspectorBaseAgent<protocol::Target::Metainfo>,
- public WorkerInspectorProxy::PageInspector {
- public:
- InspectorWorkerAgent(InspectedFrames*, WorkerGlobalScope*);
- ~InspectorWorkerAgent() override;
- void Trace(blink::Visitor*) override;
-
- protocol::Response disable() override;
- void Restore() override;
- void DidCommitLoadForLocalFrame(LocalFrame*) override;
-
- // Probes
- void ShouldWaitForDebuggerOnWorkerStart(bool* result);
- void DidStartWorker(WorkerInspectorProxy*, bool waiting_for_debugger);
- void WorkerTerminated(WorkerInspectorProxy*);
-
- // Called from Dispatcher
- protocol::Response setAutoAttach(bool auto_attach,
- bool wait_for_debugger_on_start,
- protocol::Maybe<bool> flatten) override;
- protocol::Response sendMessageToTarget(
- const String& message,
- protocol::Maybe<String> session_id,
- protocol::Maybe<String> target_id) override;
-
- private:
- void ConnectToAllProxies();
- void DisconnectFromAllProxies(bool report_to_frontend);
- void ConnectToProxy(WorkerInspectorProxy*, bool waiting_for_debugger);
-
- // WorkerInspectorProxy::PageInspector implementation.
- void DispatchMessageFromWorker(WorkerInspectorProxy*,
- int connection,
- const String& message) override;
-
- // This is null while inspecting workers.
- Member<InspectedFrames> inspected_frames_;
- // This is null while inspecting frames.
- Member<WorkerGlobalScope> worker_global_scope_;
- HeapHashMap<int, Member<WorkerInspectorProxy>> connected_proxies_;
- HashMap<int, String> connection_to_session_id_;
- HashMap<String, int> session_id_to_connection_;
- InspectorAgentState::Boolean auto_attach_;
- InspectorAgentState::Boolean wait_for_debugger_on_start_;
- InspectorAgentState::BooleanMap attached_session_ids_;
- static int s_last_connection_;
- DISALLOW_COPY_AND_ASSIGN(InspectorWorkerAgent);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_WORKER_AGENT_H_
diff --git a/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger.cc b/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger.cc
index 1af591c725a..dccc07048a7 100644
--- a/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger.cc
@@ -82,7 +82,7 @@ LocalFrame* ToFrame(ExecutionContext* context) {
if (auto* document = DynamicTo<Document>(context))
return document->GetFrame();
if (context->IsMainThreadWorkletGlobalScope())
- return ToWorkletGlobalScope(context)->GetFrame();
+ return To<WorkletGlobalScope>(context)->GetFrame();
return nullptr;
}
}
@@ -179,11 +179,11 @@ void MainThreadDebugger::ExceptionThrown(ExecutionContext* context,
script_state =
event->World() ? ToScriptState(frame, *event->World()) : nullptr;
} else if (context->IsMainThreadWorkletGlobalScope()) {
- frame = ToWorkletGlobalScope(context)->GetFrame();
+ auto* scope = To<WorkletGlobalScope>(context);
+ frame = scope->GetFrame();
if (!frame)
return;
- script_state =
- ToWorkletGlobalScope(context)->ScriptController()->GetScriptState();
+ script_state = scope->ScriptController()->GetScriptState();
} else {
NOTREACHED();
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger_test.cc b/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger_test.cc
index f5332209967..6f87c321343 100644
--- a/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger_test.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/main_thread_debugger_test.cc
@@ -23,7 +23,8 @@ TEST_F(MainThreadDebuggerTest, HitBreakPointDuringLifecycle) {
// The following steps would cause either style update or layout, it should
// never crash.
document.View()->ViewportSizeChanged(true, true);
- document.View()->UpdateAllLifecyclePhases();
+ document.View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
document.UpdateStyleAndLayoutIgnorePendingStylesheets();
document.UpdateStyleAndLayoutTree();
diff --git a/chromium/third_party/blink/renderer/core/inspector/network_resources_data.cc b/chromium/third_party/blink/renderer/core/inspector/network_resources_data.cc
index b83e1c23a5e..29613e8a713 100644
--- a/chromium/third_party/blink/renderer/core/inspector/network_resources_data.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/network_resources_data.cc
@@ -46,7 +46,8 @@ XHRReplayData* XHRReplayData::Create(const AtomicString& method,
const KURL& url,
bool async,
bool include_credentials) {
- return new XHRReplayData(method, url, async, include_credentials);
+ return MakeGarbageCollected<XHRReplayData>(method, url, async,
+ include_credentials);
}
void XHRReplayData::AddHeader(const AtomicString& key,
@@ -202,8 +203,8 @@ void NetworkResourcesData::ResourceCreated(
const KURL& requested_url,
scoped_refptr<EncodedFormData> post_data) {
EnsureNoDataForRequestId(request_id);
- ResourceData* data =
- new ResourceData(this, context, request_id, loader_id, requested_url);
+ ResourceData* data = MakeGarbageCollected<ResourceData>(
+ this, context, request_id, loader_id, requested_url);
request_id_to_resource_data_map_.Set(request_id, data);
if (post_data &&
PrepareToAddResourceData(request_id, post_data->SizeInBytes())) {
@@ -368,20 +369,21 @@ NetworkResourcesData::Resources() {
return result;
}
-int NetworkResourcesData::GetAndClearPendingEncodedDataLength(
+int64_t NetworkResourcesData::GetAndClearPendingEncodedDataLength(
const String& request_id) {
ResourceData* resource_data = ResourceDataForRequestId(request_id);
if (!resource_data)
return 0;
- int pending_encoded_data_length = resource_data->PendingEncodedDataLength();
+ int64_t pending_encoded_data_length =
+ resource_data->PendingEncodedDataLength();
resource_data->ClearPendingEncodedDataLength();
return pending_encoded_data_length;
}
void NetworkResourcesData::AddPendingEncodedDataLength(
const String& request_id,
- int encoded_data_length) {
+ size_t encoded_data_length) {
ResourceData* resource_data = ResourceDataForRequestId(request_id);
if (!resource_data)
return;
diff --git a/chromium/third_party/blink/renderer/core/inspector/network_resources_data.h b/chromium/third_party/blink/renderer/core/inspector/network_resources_data.h
index 18537410f37..0b6b795eb09 100644
--- a/chromium/third_party/blink/renderer/core/inspector/network_resources_data.h
+++ b/chromium/third_party/blink/renderer/core/inspector/network_resources_data.h
@@ -56,6 +56,11 @@ class XHRReplayData final : public GarbageCollectedFinalized<XHRReplayData> {
bool async,
bool include_credentials);
+ XHRReplayData(const AtomicString& method,
+ const KURL&,
+ bool async,
+ bool include_credentials);
+
void AddHeader(const AtomicString& key, const AtomicString& value);
const AtomicString& Method() const { return method_; }
const KURL& Url() const { return url_; }
@@ -66,11 +71,6 @@ class XHRReplayData final : public GarbageCollectedFinalized<XHRReplayData> {
virtual void Trace(blink::Visitor*) {}
private:
- XHRReplayData(const AtomicString& method,
- const KURL&,
- bool async,
- bool include_credentials);
-
AtomicString method_;
KURL url_;
bool async_;
@@ -152,11 +152,11 @@ class NetworkResourcesData final
void SetCertificate(const Vector<AtomicString>& certificate) {
certificate_ = certificate;
}
- int PendingEncodedDataLength() const {
+ int64_t PendingEncodedDataLength() const {
return pending_encoded_data_length_;
}
void ClearPendingEncodedDataLength() { pending_encoded_data_length_ = 0; }
- void AddPendingEncodedDataLength(int encoded_data_length) {
+ void AddPendingEncodedDataLength(size_t encoded_data_length) {
pending_encoded_data_length_ += encoded_data_length;
}
void SetPostData(scoped_refptr<EncodedFormData> post_data) {
@@ -189,7 +189,7 @@ class NetworkResourcesData final
String mime_type_;
String text_encoding_name_;
int64_t raw_header_size_;
- int pending_encoded_data_length_;
+ int64_t pending_encoded_data_length_;
scoped_refptr<SharedBuffer> buffer_;
WeakMember<Resource> cached_resource_;
@@ -201,8 +201,11 @@ class NetworkResourcesData final
static NetworkResourcesData* Create(size_t total_buffer_size,
size_t resource_buffer_size) {
- return new NetworkResourcesData(total_buffer_size, resource_buffer_size);
+ return MakeGarbageCollected<NetworkResourcesData>(total_buffer_size,
+ resource_buffer_size);
}
+
+ NetworkResourcesData(size_t total_buffer_size, size_t resource_buffer_size);
~NetworkResourcesData();
void ResourceCreated(ExecutionContext*,
@@ -236,14 +239,12 @@ class NetworkResourcesData final
const Vector<AtomicString>& certificate);
HeapVector<Member<ResourceData>> Resources();
- int GetAndClearPendingEncodedDataLength(const String& request_id);
+ int64_t GetAndClearPendingEncodedDataLength(const String& request_id);
void AddPendingEncodedDataLength(const String& request_id,
- int encoded_data_length);
+ size_t encoded_data_length);
void Trace(blink::Visitor*);
private:
- NetworkResourcesData(size_t total_buffer_size, size_t resource_buffer_size);
-
ResourceData* ResourceDataForRequestId(const String& request_id) const;
void EnsureNoDataForRequestId(const String& request_id);
bool EnsureFreeSpace(size_t);
diff --git a/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc b/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc
new file mode 100644
index 00000000000..376c836c616
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc
@@ -0,0 +1,60 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/inspector/v8_inspector_string.h"
+
+#include <vector>
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace blink {
+namespace protocol {
+namespace {
+TEST(ProtocolBinaryTest, base64EmptyArgs) {
+ EXPECT_EQ(protocol::String(), Binary().toBase64());
+
+ bool success = false;
+ Binary decoded = Binary::fromBase64("", &success);
+ EXPECT_TRUE(success);
+ EXPECT_EQ(
+ std::vector<uint8_t>(),
+ std::vector<uint8_t>(decoded.data(), decoded.data() + decoded.size()));
+}
+
+TEST(ProtocolStringTest, AllBytesBase64Roundtrip) {
+ Vector<uint8_t> all_bytes;
+ for (int ii = 0; ii < 255; ++ii)
+ all_bytes.push_back(ii);
+ Binary binary = Binary::fromVector(all_bytes);
+ bool success = false;
+ Binary decoded = Binary::fromBase64(binary.toBase64(), &success);
+ EXPECT_TRUE(success);
+ Vector<uint8_t> decoded_bytes;
+ decoded_bytes.Append(decoded.data(), decoded.size());
+ EXPECT_EQ(all_bytes, decoded_bytes);
+}
+
+TEST(ProtocolStringTest, HelloWorldBase64Roundtrip) {
+ const char* kMsg = "Hello, world.";
+ Vector<uint8_t> msg;
+ msg.Append(reinterpret_cast<const uint8_t*>(kMsg), strlen(kMsg));
+ EXPECT_EQ(strlen(kMsg), msg.size());
+
+ protocol::String encoded = Binary::fromVector(msg).toBase64();
+ EXPECT_EQ("SGVsbG8sIHdvcmxkLg==", encoded);
+ bool success = false;
+ Binary decoded_binary = Binary::fromBase64(encoded, &success);
+ EXPECT_TRUE(success);
+ Vector<uint8_t> decoded;
+ decoded.Append(decoded_binary.data(), decoded_binary.size());
+ EXPECT_EQ(msg, decoded);
+}
+
+TEST(ProtocolBinaryTest, InvalidBase64Decode) {
+ bool success = true;
+ Binary binary = Binary::fromBase64("This is not base64.", &success);
+ EXPECT_FALSE(success);
+}
+} // namespace
+} // namespace protocol
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc b/chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc
index ba7feadd084..28050e24d87 100644
--- a/chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc
@@ -168,17 +168,17 @@ std::unique_ptr<v8_inspector::StringBuffer> ThreadDebugger::valueSubtype(
static const char kArray[] = "array";
static const char kError[] = "error";
static const char kBlob[] = "blob";
- if (V8Node::hasInstance(value, isolate_))
+ if (V8Node::HasInstance(value, isolate_))
return ToV8InspectorStringBuffer(kNode);
- if (V8NodeList::hasInstance(value, isolate_) ||
- V8DOMTokenList::hasInstance(value, isolate_) ||
- V8HTMLCollection::hasInstance(value, isolate_) ||
- V8HTMLAllCollection::hasInstance(value, isolate_)) {
+ if (V8NodeList::HasInstance(value, isolate_) ||
+ V8DOMTokenList::HasInstance(value, isolate_) ||
+ V8HTMLCollection::HasInstance(value, isolate_) ||
+ V8HTMLAllCollection::HasInstance(value, isolate_)) {
return ToV8InspectorStringBuffer(kArray);
}
- if (V8DOMException::hasInstance(value, isolate_))
+ if (V8DOMException::HasInstance(value, isolate_))
return ToV8InspectorStringBuffer(kError);
- if (V8Blob::hasInstance(value, isolate_))
+ if (V8Blob::HasInstance(value, isolate_))
return ToV8InspectorStringBuffer(kBlob);
return nullptr;
}
@@ -477,9 +477,9 @@ void ThreadDebugger::consoleTimeStamp(const v8_inspector::StringView& title) {
ExecutionContext* ec = CurrentExecutionContext(isolate_);
// TODO(dgozman): we can save on a copy here if TracedValue would take a
// StringView.
- TRACE_EVENT_INSTANT1("devtools.timeline", "TimeStamp",
- TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorTimeStampEvent::Data(ec, ToCoreString(title)));
+ TRACE_EVENT_INSTANT1(
+ "devtools.timeline", "TimeStamp", TRACE_EVENT_SCOPE_THREAD, "data",
+ inspector_time_stamp_event::Data(ec, ToCoreString(title)));
probe::consoleTimeStamp(ec, ToCoreString(title));
}
@@ -492,8 +492,8 @@ void ThreadDebugger::startRepeatingTimer(
std::unique_ptr<TaskRunnerTimer<ThreadDebugger>> timer =
std::make_unique<TaskRunnerTimer<ThreadDebugger>>(
- Platform::Current()->CurrentThread()->Scheduler()->V8TaskRunner(),
- this, &ThreadDebugger::OnTimer);
+ ThreadScheduler::Current()->V8TaskRunner(), this,
+ &ThreadDebugger::OnTimer);
TaskRunnerTimer<ThreadDebugger>* timer_ptr = timer.get();
timers_.push_back(std::move(timer));
timer_ptr->StartRepeating(TimeDelta::FromSecondsD(interval), FROM_HERE);
diff --git a/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.cc b/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.cc
index 674a2470e27..f1d6ef86e16 100644
--- a/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.cc
@@ -4,7 +4,9 @@
#include "third_party/blink/renderer/core/inspector/v8_inspector_string.h"
+#include <utility>
#include "third_party/blink/renderer/core/inspector/protocol/Protocol.h"
+#include "third_party/blink/renderer/platform/wtf/text/base64.h"
namespace blink {
@@ -74,6 +76,79 @@ void StringUtil::builderAppendQuotedString(StringBuilder& builder,
builder.Append('"');
}
-} // namespace protocol
+namespace {
+class BinaryBasedOnSharedBuffer : public Binary::Impl {
+ public:
+ explicit BinaryBasedOnSharedBuffer(scoped_refptr<SharedBuffer> buffer)
+ : buffer_(buffer) {}
+
+ const uint8_t* data() const override {
+ return reinterpret_cast<const uint8_t*>(buffer_->Data());
+ }
+ size_t size() const override { return buffer_->size(); }
+
+ private:
+ // buffer_ is mutable so we can call SharedBuffer::Data(),
+ // which flattens the segments of the buffer.
+ mutable scoped_refptr<SharedBuffer> buffer_;
+};
+
+class BinaryBasedOnVector : public Binary::Impl {
+ public:
+ explicit BinaryBasedOnVector(Vector<uint8_t> values)
+ : values_(std::move(values)) {}
+
+ const uint8_t* data() const override { return values_.data(); }
+ size_t size() const override { return values_.size(); }
+
+ private:
+ Vector<uint8_t> values_;
+};
+class BinaryBasedOnCachedData : public Binary::Impl {
+ public:
+ explicit BinaryBasedOnCachedData(
+ std::unique_ptr<v8::ScriptCompiler::CachedData> data)
+ : data_(std::move(data)) {}
+
+ const uint8_t* data() const override { return data_->data; }
+ size_t size() const override { return data_->length; }
+
+ private:
+ std::unique_ptr<v8::ScriptCompiler::CachedData> data_;
+};
+} // namespace
+
+String Binary::toBase64() const {
+ return impl_ ? WTF::Base64Encode(reinterpret_cast<const char*>(impl_->data()),
+ impl_->size())
+ : String();
+}
+
+// static
+Binary Binary::fromBase64(const String& base64, bool* success) {
+ Vector<char> out;
+ *success = WTF::Base64Decode(base64, out);
+ return Binary(base::AdoptRef(
+ new BinaryBasedOnSharedBuffer(SharedBuffer::AdoptVector(out))));
+}
+
+// static
+Binary Binary::fromSharedBuffer(scoped_refptr<SharedBuffer> buffer) {
+ return Binary(base::AdoptRef(new BinaryBasedOnSharedBuffer(buffer)));
+}
+
+// static
+Binary Binary::fromVector(Vector<uint8_t> in) {
+ return Binary(base::AdoptRef(new BinaryBasedOnVector(std::move(in))));
+}
+
+// static
+Binary Binary::fromCachedData(
+ std::unique_ptr<v8::ScriptCompiler::CachedData> data) {
+ CHECK_EQ(data->buffer_policy, v8::ScriptCompiler::CachedData::BufferOwned);
+ return Binary(base::AdoptRef(new BinaryBasedOnCachedData(std::move(data))));
+}
+
+} // namespace protocol
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.h b/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.h
index 0083f1a80cb..ec2881753c8 100644
--- a/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.h
+++ b/chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.h
@@ -8,9 +8,11 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/decimal.h"
+#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/text/string_to_number.h"
@@ -76,6 +78,36 @@ class CORE_EXPORT StringUtil {
static std::unique_ptr<protocol::Value> parseJSON(const String&);
};
+// A read-only sequence of uninterpreted bytes with reference-counted storage.
+class CORE_EXPORT Binary {
+ public:
+ class Impl : public RefCounted<Impl> {
+ public:
+ Impl() = default;
+ virtual ~Impl() = default;
+ virtual const uint8_t* data() const = 0;
+ virtual size_t size() const = 0;
+ };
+
+ Binary() = default;
+
+ const uint8_t* data() const { return impl_->data(); }
+ size_t size() const { return impl_->size(); }
+
+ String toBase64() const;
+ static Binary fromBase64(const String& base64, bool* success);
+ static Binary fromSharedBuffer(scoped_refptr<SharedBuffer> buffer);
+ static Binary fromVector(Vector<uint8_t> in);
+
+ // Note: |data.buffer_policy| must be
+ // ScriptCompiler::ScriptCompiler::CachedData::BufferOwned.
+ static Binary fromCachedData(
+ std::unique_ptr<v8::ScriptCompiler::CachedData> data);
+
+ private:
+ explicit Binary(scoped_refptr<Impl> impl) : impl_(impl) {}
+ scoped_refptr<Impl> impl_;
+};
} // namespace protocol
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/worker_devtools_params.h b/chromium/third_party/blink/renderer/core/inspector/worker_devtools_params.h
new file mode 100644
index 00000000000..f42f46550d6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/inspector/worker_devtools_params.h
@@ -0,0 +1,22 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_WORKER_DEVTOOLS_PARAMS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_WORKER_DEVTOOLS_PARAMS_H_
+
+#include "base/unguessable_token.h"
+#include "third_party/blink/public/web/devtools_agent.mojom-blink.h"
+
+namespace blink {
+
+struct CORE_EXPORT WorkerDevToolsParams {
+ mojom::blink::DevToolsAgentRequest agent_request;
+ mojom::blink::DevToolsAgentHostPtrInfo agent_host_ptr_info;
+ bool wait_for_debugger = false;
+ base::UnguessableToken devtools_worker_token;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_WORKER_DEVTOOLS_PARAMS_H_
diff --git a/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc b/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc
index 83e69621ae9..486bb38c5b6 100644
--- a/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc
@@ -30,141 +30,136 @@
#include "third_party/blink/renderer/core/inspector/worker_inspector_controller.h"
+#include "base/single_thread_task_runner.h"
#include "third_party/blink/renderer/core/core_probe_sink.h"
+#include "third_party/blink/renderer/core/inspector/devtools_session.h"
#include "third_party/blink/renderer/core/inspector/inspector_emulation_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_log_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_network_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-#include "third_party/blink/renderer/core/inspector/inspector_worker_agent.h"
#include "third_party/blink/renderer/core/inspector/protocol/Protocol.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/inspector/worker_thread_debugger.h"
#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
namespace blink {
+// static
WorkerInspectorController* WorkerInspectorController::Create(
- WorkerThread* thread) {
+ WorkerThread* thread,
+ scoped_refptr<InspectorTaskRunner> inspector_task_runner,
+ std::unique_ptr<WorkerDevToolsParams> devtools_params) {
WorkerThreadDebugger* debugger =
WorkerThreadDebugger::From(thread->GetIsolate());
- return debugger ? new WorkerInspectorController(thread, debugger) : nullptr;
+ return debugger ? MakeGarbageCollected<WorkerInspectorController>(
+ thread, debugger, std::move(inspector_task_runner),
+ std::move(devtools_params))
+ : nullptr;
}
WorkerInspectorController::WorkerInspectorController(
WorkerThread* thread,
- WorkerThreadDebugger* debugger)
- : debugger_(debugger), thread_(thread), probe_sink_(new CoreProbeSink()) {
- probe_sink_->addInspectorTraceEvents(new InspectorTraceEvents());
- if (thread->GlobalScope()->IsWorkerGlobalScope()) {
- WorkerGlobalScope* scope = ToWorkerGlobalScope(thread->GlobalScope());
- worker_devtools_token_ = thread->GetDevToolsWorkerToken();
+ WorkerThreadDebugger* debugger,
+ scoped_refptr<InspectorTaskRunner> inspector_task_runner,
+ std::unique_ptr<WorkerDevToolsParams> devtools_params)
+ : debugger_(debugger),
+ thread_(thread),
+ inspected_frames_(nullptr),
+ probe_sink_(new CoreProbeSink()) {
+ probe_sink_->addInspectorTraceEvents(
+ MakeGarbageCollected<InspectorTraceEvents>());
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(thread->GlobalScope())) {
+ worker_devtools_token_ = devtools_params->devtools_worker_token;
parent_devtools_token_ = scope->GetParentDevToolsToken();
url_ = scope->Url();
worker_thread_id_ = thread->GetPlatformThreadId();
}
- TraceEvent::AddEnabledStateObserver(this);
+ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
+ Platform::Current()->GetIOTaskRunner();
+ if (!parent_devtools_token_.is_empty() && io_task_runner) {
+ // There may be no io task runner in unit tests.
+ wait_for_debugger_ = devtools_params->wait_for_debugger;
+ agent_ = new DevToolsAgent(this, inspected_frames_.Get(), probe_sink_.Get(),
+ std::move(inspector_task_runner),
+ std::move(io_task_runner));
+ agent_->BindRequest(std::move(devtools_params->agent_host_ptr_info),
+ std::move(devtools_params->agent_request),
+ thread->GetTaskRunner(TaskType::kInternalInspector));
+ }
+ trace_event::AddEnabledStateObserver(this);
EmitTraceEvent();
}
WorkerInspectorController::~WorkerInspectorController() {
DCHECK(!thread_);
- TraceEvent::RemoveEnabledStateObserver(this);
+ trace_event::RemoveEnabledStateObserver(this);
}
-void WorkerInspectorController::ConnectFrontend(int session_id) {
- WorkerThread::ScopedDebuggerTask debugger_task(thread_);
- if (sessions_.find(session_id) != sessions_.end())
- return;
-
- InspectedFrames* inspected_frames = new InspectedFrames(nullptr);
- InspectorSession* session = new InspectorSession(
- this, probe_sink_.Get(), inspected_frames, session_id,
- debugger_->GetV8Inspector(), debugger_->ContextGroupId(thread_), nullptr);
- session->Append(new InspectorLogAgent(thread_->GetConsoleMessageStorage(),
- nullptr, session->V8Session()));
- if (thread_->GlobalScope()->IsWorkerGlobalScope()) {
- WorkerGlobalScope* worker_global_scope =
- ToWorkerGlobalScope(thread_->GlobalScope());
- DCHECK(worker_global_scope->EnsureFetcher());
- session->Append(new InspectorNetworkAgent(
- inspected_frames, worker_global_scope, session->V8Session()));
- session->Append(new InspectorEmulationAgent(nullptr));
- session->Append(
- new InspectorWorkerAgent(inspected_frames, worker_global_scope));
- }
- if (sessions_.IsEmpty())
+void WorkerInspectorController::AttachSession(DevToolsSession* session,
+ bool restore) {
+ if (!session_count_)
thread_->GetWorkerBackingThread().BackingThread().AddTaskObserver(this);
- sessions_.insert(session_id, session);
+ session->ConnectToV8(debugger_->GetV8Inspector(),
+ debugger_->ContextGroupId(thread_));
+ session->Append(MakeGarbageCollected<InspectorLogAgent>(
+ thread_->GetConsoleMessageStorage(), nullptr, session->V8Session()));
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(thread_->GlobalScope())) {
+ DCHECK(scope->EnsureFetcher());
+ session->Append(MakeGarbageCollected<InspectorNetworkAgent>(
+ inspected_frames_.Get(), scope, session->V8Session()));
+ session->Append(MakeGarbageCollected<InspectorEmulationAgent>(nullptr));
+ }
+ ++session_count_;
}
-void WorkerInspectorController::DisconnectFrontend(int session_id) {
- WorkerThread::ScopedDebuggerTask debugger_task(thread_);
- auto it = sessions_.find(session_id);
- if (it == sessions_.end())
- return;
- it->value->Dispose();
- sessions_.erase(it);
- if (sessions_.IsEmpty())
+void WorkerInspectorController::DetachSession(DevToolsSession*) {
+ --session_count_;
+ if (!session_count_)
thread_->GetWorkerBackingThread().BackingThread().RemoveTaskObserver(this);
}
-void WorkerInspectorController::DispatchMessageFromFrontend(
- int session_id,
- const String& message) {
- WorkerThread::ScopedDebuggerTask debugger_task(thread_);
- auto it = sessions_.find(session_id);
- if (it == sessions_.end())
- return;
- it->value->DispatchProtocolMessage(message);
+void WorkerInspectorController::InspectElement(const WebPoint&) {
+ NOTREACHED();
+}
+
+void WorkerInspectorController::DebuggerTaskStarted() {
+ thread_->DebuggerTaskStarted();
+}
+
+void WorkerInspectorController::DebuggerTaskFinished() {
+ thread_->DebuggerTaskFinished();
}
void WorkerInspectorController::Dispose() {
- Vector<int> ids;
- CopyKeysToVector(sessions_, ids);
- for (int session_id : ids)
- DisconnectFrontend(session_id);
+ if (agent_)
+ agent_->Dispose();
thread_ = nullptr;
}
void WorkerInspectorController::FlushProtocolNotifications() {
- for (auto& it : sessions_)
- it.value->flushProtocolNotifications();
+ if (agent_)
+ agent_->FlushProtocolNotifications();
}
-void WorkerInspectorController::SendProtocolResponse(
- int session_id,
- int call_id,
- const String& response,
- mojom::blink::DevToolsSessionStatePtr updates) {
- // Make tests more predictable by flushing all sessions before sending
- // protocol response in any of them.
- if (LayoutTestSupport::IsRunningLayoutTest())
- FlushProtocolNotifications();
- // Worker messages are wrapped, no need to handle callId or state.
- thread_->GetWorkerReportingProxy().PostMessageToPageInspector(session_id,
- response);
-}
-
-void WorkerInspectorController::SendProtocolNotification(
- int session_id,
- const String& message,
- mojom::blink::DevToolsSessionStatePtr updates) {
- thread_->GetWorkerReportingProxy().PostMessageToPageInspector(session_id,
- message);
+void WorkerInspectorController::WaitForDebuggerIfNeeded() {
+ if (!wait_for_debugger_)
+ return;
+ wait_for_debugger_ = false;
+ debugger_->PauseWorkerOnStart(thread_);
}
-void WorkerInspectorController::WillProcessTask() {}
+void WorkerInspectorController::WillProcessTask(
+ const base::PendingTask& pending_task) {}
-void WorkerInspectorController::DidProcessTask() {
- for (auto& it : sessions_)
- it.value->flushProtocolNotifications();
+void WorkerInspectorController::DidProcessTask(
+ const base::PendingTask& pending_task) {
+ FlushProtocolNotifications();
}
void WorkerInspectorController::OnTraceLogEnabled() {
@@ -179,14 +174,15 @@ void WorkerInspectorController::EmitTraceEvent() {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"TracingSessionIdForWorker", TRACE_EVENT_SCOPE_THREAD,
"data",
- InspectorTracingSessionIdForWorkerEvent::Data(
+ inspector_tracing_session_id_for_worker_event::Data(
worker_devtools_token_, parent_devtools_token_, url_,
worker_thread_id_));
}
void WorkerInspectorController::Trace(blink::Visitor* visitor) {
+ visitor->Trace(agent_);
+ visitor->Trace(inspected_frames_);
visitor->Trace(probe_sink_);
- visitor->Trace(sessions_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.h b/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.h
index 2383ed2bc15..a154fe3825b 100644
--- a/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.h
+++ b/chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.h
@@ -31,70 +31,76 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_WORKER_INSPECTOR_CONTROLLER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_WORKER_INSPECTOR_CONTROLLER_H_
+#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/unguessable_token.h"
-#include "third_party/blink/renderer/core/inspector/inspector_session.h"
+#include "third_party/blink/renderer/core/inspector/devtools_agent.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
class CoreProbeSink;
+class InspectedFrames;
class WorkerThread;
class WorkerThreadDebugger;
+struct WorkerDevToolsParams;
class WorkerInspectorController final
: public GarbageCollectedFinalized<WorkerInspectorController>,
- public TraceEvent::EnabledStateObserver,
- public InspectorSession::Client,
+ public trace_event::EnabledStateObserver,
+ public DevToolsAgent::Client,
private Thread::TaskObserver {
public:
- static WorkerInspectorController* Create(WorkerThread*);
+ static WorkerInspectorController* Create(
+ WorkerThread*,
+ scoped_refptr<InspectorTaskRunner>,
+ std::unique_ptr<WorkerDevToolsParams>);
+
+ WorkerInspectorController(WorkerThread*,
+ WorkerThreadDebugger*,
+ scoped_refptr<InspectorTaskRunner>,
+ std::unique_ptr<WorkerDevToolsParams>);
~WorkerInspectorController() override;
void Trace(blink::Visitor*);
CoreProbeSink* GetProbeSink() const { return probe_sink_.Get(); }
-
- void ConnectFrontend(int session_id);
- void DisconnectFrontend(int session_id);
- void DispatchMessageFromFrontend(int session_id, const String& message);
+ DevToolsAgent* GetDevToolsAgent() const { return agent_.Get(); }
void Dispose();
void FlushProtocolNotifications();
+ void WaitForDebuggerIfNeeded();
private:
- WorkerInspectorController(WorkerThread*, WorkerThreadDebugger*);
-
- // InspectorSession::Client implementation.
- void SendProtocolResponse(
- int session_id,
- int call_id,
- const String& response,
- mojom::blink::DevToolsSessionStatePtr updates) override;
- void SendProtocolNotification(
- int session_id,
- const String& message,
- mojom::blink::DevToolsSessionStatePtr updates) override;
-
// Thread::TaskObserver implementation.
- void WillProcessTask() override;
- void DidProcessTask() override;
+ void WillProcessTask(const base::PendingTask&) override;
+ void DidProcessTask(const base::PendingTask&) override;
- // blink::TraceEvent::EnabledStateObserver implementation:
+ // blink::trace_event::EnabledStateObserver implementation:
void OnTraceLogEnabled() override;
void OnTraceLogDisabled() override;
void EmitTraceEvent();
+ // DevToolsAgent::Client implementation.
+ void AttachSession(DevToolsSession*, bool restore) override;
+ void DetachSession(DevToolsSession*) override;
+ void InspectElement(const WebPoint&) override;
+ void DebuggerTaskStarted() override;
+ void DebuggerTaskFinished() override;
+
+ Member<DevToolsAgent> agent_;
WorkerThreadDebugger* debugger_;
WorkerThread* thread_;
+ Member<InspectedFrames> inspected_frames_;
Member<CoreProbeSink> probe_sink_;
- HeapHashMap<int, Member<InspectorSession>> sessions_;
+ int session_count_ = 0;
+ bool wait_for_debugger_ = false;
// These fields are set up in the constructor and then read
// on a random thread from EmitTraceEvent().
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc
index 1de156b1081..8b392c7fd10 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observation.cc
@@ -60,8 +60,12 @@ void IntersectionObservation::Compute(unsigned flags) {
DOMHighResTimeStamp timestamp = observer_->GetTimeStamp();
if (timestamp == -1)
return;
- if (timestamp - last_run_time_ < observer_->GetEffectiveDelay())
+ if (timestamp - last_run_time_ < observer_->GetEffectiveDelay()) {
+ // TODO(crbug.com/915495): Need to eventually notify the observer of the
+ // updated intersection because there's currently nothing to guarantee this
+ // Compute() method will be called again after the delay period has passed.
return;
+ }
last_run_time_ = timestamp;
needs_update_ = 0;
Vector<Length> root_margin(4);
@@ -92,15 +96,19 @@ void IntersectionObservation::Compute(unsigned flags) {
float new_visible_ratio;
bool is_visible = false;
if (geometry.DoesIntersect()) {
- if (geometry.TargetRect().IsEmpty()) {
+ const LayoutRect comparison_rect = observer_->trackFractionOfRoot()
+ ? geometry.RootRect()
+ : geometry.TargetRect();
+ if (comparison_rect.IsEmpty()) {
new_visible_ratio = 1;
} else {
- float intersection_area =
- geometry.IntersectionRect().Size().Width().ToFloat() *
- geometry.IntersectionRect().Size().Height().ToFloat();
- float target_area = geometry.TargetRect().Size().Width().ToFloat() *
- geometry.TargetRect().Size().Height().ToFloat();
- new_visible_ratio = intersection_area / target_area;
+ const LayoutSize& intersection_size = geometry.IntersectionRect().Size();
+ const float intersection_area = intersection_size.Width().ToFloat() *
+ intersection_size.Height().ToFloat();
+ const LayoutSize& comparison_size = comparison_rect.Size();
+ const float area_of_interest = comparison_size.Width().ToFloat() *
+ comparison_size.Height().ToFloat();
+ new_visible_ratio = intersection_area / area_of_interest;
}
new_threshold_index =
Observer()->FirstThresholdGreaterThan(new_visible_ratio);
@@ -123,10 +131,12 @@ void IntersectionObservation::Compute(unsigned flags) {
FloatRect root_bounds(geometry.UnZoomedRootRect());
FloatRect* root_bounds_pointer =
report_root_bounds ? &root_bounds : nullptr;
- IntersectionObserverEntry* new_entry = new IntersectionObserverEntry(
- timestamp, new_visible_ratio, FloatRect(geometry.UnZoomedTargetRect()),
- root_bounds_pointer, FloatRect(geometry.UnZoomedIntersectionRect()),
- new_threshold_index > 0, is_visible, Target());
+ IntersectionObserverEntry* new_entry =
+ MakeGarbageCollected<IntersectionObserverEntry>(
+ timestamp, new_visible_ratio,
+ FloatRect(geometry.UnZoomedTargetRect()), root_bounds_pointer,
+ FloatRect(geometry.UnZoomedIntersectionRect()),
+ new_threshold_index > 0, is_visible, Target());
entries_.push_back(new_entry);
To<Document>(Observer()->GetExecutionContext())
->EnsureIntersectionObserverController()
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc
index 49265e40289..e933ead7541 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.cc
@@ -142,16 +142,16 @@ void IntersectionObserver::SetThrottleDelayEnabledForTesting(bool enabled) {
}
IntersectionObserver* IntersectionObserver::Create(
- const IntersectionObserverInit& observer_init,
+ const IntersectionObserverInit* observer_init,
IntersectionObserverDelegate& delegate,
ExceptionState& exception_state) {
- Element* root = observer_init.root();
+ Element* root = observer_init->root();
DOMHighResTimeStamp delay = 0;
bool track_visibility = false;
if (RuntimeEnabledFeatures::IntersectionObserverV2Enabled()) {
- delay = observer_init.delay();
- track_visibility = observer_init.trackVisibility();
+ delay = observer_init->delay();
+ track_visibility = observer_init->trackVisibility();
if (track_visibility && delay < 100) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
@@ -166,26 +166,28 @@ IntersectionObserver* IntersectionObserver::Create(
}
Vector<Length> root_margin;
- ParseRootMargin(observer_init.rootMargin(), root_margin, exception_state);
+ ParseRootMargin(observer_init->rootMargin(), root_margin, exception_state);
if (exception_state.HadException())
return nullptr;
Vector<float> thresholds;
- ParseThresholds(observer_init.threshold(), thresholds, exception_state);
+ ParseThresholds(observer_init->threshold(), thresholds, exception_state);
if (exception_state.HadException())
return nullptr;
- return new IntersectionObserver(delegate, root, root_margin, thresholds,
- delay, track_visibility);
+ return MakeGarbageCollected<IntersectionObserver>(
+ delegate, root, root_margin, thresholds, kFractionOfTarget, delay,
+ track_visibility);
}
IntersectionObserver* IntersectionObserver::Create(
ScriptState* script_state,
V8IntersectionObserverCallback* callback,
- const IntersectionObserverInit& observer_init,
+ const IntersectionObserverInit* observer_init,
ExceptionState& exception_state) {
V8IntersectionObserverDelegate* delegate =
- new V8IntersectionObserverDelegate(callback, script_state);
+ MakeGarbageCollected<V8IntersectionObserverDelegate>(callback,
+ script_state);
return Create(observer_init, *delegate, exception_state);
}
@@ -194,14 +196,15 @@ IntersectionObserver* IntersectionObserver::Create(
const Vector<float>& thresholds,
Document* document,
EventCallback callback,
+ ThresholdInterpretation semantics,
DOMHighResTimeStamp delay,
bool track_visibility,
ExceptionState& exception_state) {
IntersectionObserverDelegateImpl* intersection_observer_delegate =
new IntersectionObserverDelegateImpl(document, std::move(callback));
- return new IntersectionObserver(*intersection_observer_delegate, nullptr,
- root_margin, thresholds, delay,
- track_visibility);
+ return MakeGarbageCollected<IntersectionObserver>(
+ *intersection_observer_delegate, nullptr, root_margin, thresholds,
+ semantics, delay, track_visibility);
}
IntersectionObserver::IntersectionObserver(
@@ -209,6 +212,7 @@ IntersectionObserver::IntersectionObserver(
Element* root,
const Vector<Length>& root_margin,
const Vector<float>& thresholds,
+ ThresholdInterpretation semantics,
DOMHighResTimeStamp delay,
bool track_visibility)
: ContextClient(delegate.GetExecutionContext()),
@@ -221,7 +225,8 @@ IntersectionObserver::IntersectionObserver(
bottom_margin_(kFixed),
left_margin_(kFixed),
root_is_implicit_(root ? 0 : 1),
- track_visibility_(track_visibility ? 1 : 0) {
+ track_visibility_(track_visibility ? 1 : 0),
+ track_fraction_of_root_(semantics == kFractionOfRoot) {
switch (root_margin.size()) {
case 0:
break;
@@ -278,7 +283,7 @@ void IntersectionObserver::observe(Element* target,
return;
IntersectionObservation* observation =
- new IntersectionObservation(*this, *target);
+ MakeGarbageCollected<IntersectionObservation>(*this, *target);
target->EnsureIntersectionObserverData().AddObservation(*observation);
observations_.insert(observation);
if (target->isConnected()) {
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.h b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.h
index 877510a86e9..082a306ec26 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.h
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.h
@@ -13,8 +13,8 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -39,22 +39,60 @@ class CORE_EXPORT IntersectionObserver final
using EventCallback = base::RepeatingCallback<void(
const HeapVector<Member<IntersectionObserverEntry>>&)>;
- static IntersectionObserver* Create(const IntersectionObserverInit&,
+ // The IntersectionObserver can be configured to notify based on changes to
+ // how much of the target element's area intersects with the root, or based on
+ // changes to how much of the root element's area intersects with the
+ // target. Examples illustrating the distinction:
+ //
+ // 1.0 of target, 0.5 of target, 1.0 of target,
+ // 0.25 of root 0.5 of root 1.0 of root
+ // +------------------+ +------------------+ *~~~~~~~~~~~~~~~~~~*
+ // | ////////// | | | ;//////////////////;
+ // | ////////// | | | ;//////////////////;
+ // | ////////// | ;//////////////////; ;//////////////////;
+ // | | ;//////////////////; ;//////////////////;
+ // +------------------+ *~~~~~~~~~~~~~~~~~~* *~~~~~~~~~~~~~~~~~~*
+ // ////////////////////
+ // ////////////////////
+ // ////////////////////
+ enum ThresholdInterpretation { kFractionOfTarget, kFractionOfRoot };
+
+ static IntersectionObserver* Create(const IntersectionObserverInit*,
IntersectionObserverDelegate&,
ExceptionState&);
static IntersectionObserver* Create(ScriptState*,
V8IntersectionObserverCallback*,
- const IntersectionObserverInit&,
+ const IntersectionObserverInit*,
ExceptionState&);
- static IntersectionObserver* Create(const Vector<Length>& root_margin,
- const Vector<float>& thresholds,
- Document*,
- EventCallback,
- DOMHighResTimeStamp delay = 0,
- bool track_visbility = false,
- ExceptionState& = ASSERT_NO_EXCEPTION);
+
+ // Creates an IntersectionObserver that monitors changes to the intersection
+ // between its target element relative to its implicit root and notifies via
+ // the given |callback|. |thresholds| should be in the range [0,1], and are
+ // interpreted according to the given |semantics|. |delay| specifies the
+ // minimum period between change notifications.
+ //
+ // TODO(crbug.com/915495): The |delay| feature is broken. See comments in
+ // intersection_observation.cc.
+ static IntersectionObserver* Create(
+ const Vector<Length>& root_margin,
+ const Vector<float>& thresholds,
+ Document* document,
+ EventCallback callback,
+ ThresholdInterpretation semantics = kFractionOfTarget,
+ DOMHighResTimeStamp delay = 0,
+ bool track_visbility = false,
+ ExceptionState& = ASSERT_NO_EXCEPTION);
+
static void ResumeSuspendedObservers();
+ explicit IntersectionObserver(IntersectionObserverDelegate&,
+ Element*,
+ const Vector<Length>& root_margin,
+ const Vector<float>& thresholds,
+ ThresholdInterpretation semantics,
+ DOMHighResTimeStamp delay,
+ bool track_visibility);
+
// API methods.
void observe(Element*, ExceptionState& = ASSERT_NO_EXCEPTION);
void unobserve(Element*, ExceptionState& = ASSERT_NO_EXCEPTION);
@@ -67,6 +105,7 @@ class CORE_EXPORT IntersectionObserver final
const Vector<float>& thresholds() const { return thresholds_; }
DOMHighResTimeStamp delay() const { return delay_; }
bool trackVisibility() const { return track_visibility_; }
+ bool trackFractionOfRoot() const { return track_fraction_of_root_; }
// An observer can either track intersections with an explicit root Element,
// or with the the top-level frame's viewport (the "implicit root"). When
@@ -98,12 +137,6 @@ class CORE_EXPORT IntersectionObserver final
static void SetThrottleDelayEnabledForTesting(bool);
private:
- explicit IntersectionObserver(IntersectionObserverDelegate&,
- Element*,
- const Vector<Length>& root_margin,
- const Vector<float>& thresholds,
- DOMHighResTimeStamp delay,
- bool track_visibility);
void ClearWeakMembers(Visitor*);
const TraceWrapperMember<IntersectionObserverDelegate> delegate_;
@@ -117,6 +150,7 @@ class CORE_EXPORT IntersectionObserver final
Length left_margin_;
unsigned root_is_implicit_ : 1;
unsigned track_visibility_ : 1;
+ unsigned track_fraction_of_root_ : 1;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc
index afd22255f56..c8610b5afae 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc
@@ -12,13 +12,14 @@
#include "third_party/blink/renderer/core/intersection_observer/intersection_observation.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
IntersectionObserverController* IntersectionObserverController::Create(
Document* document) {
IntersectionObserverController* result =
- new IntersectionObserverController(document);
+ MakeGarbageCollected<IntersectionObserverController>(document);
result->PauseIfNeeded();
return result;
}
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h
index acd4112f8ba..9bafb39ba4b 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h
@@ -27,6 +27,8 @@ class IntersectionObserverController
public:
static IntersectionObserverController* Create(Document*);
+
+ explicit IntersectionObserverController(Document*);
~IntersectionObserverController() override;
void Unpause() override;
@@ -43,7 +45,6 @@ class IntersectionObserverController
}
private:
- explicit IntersectionObserverController(Document*);
void PostTaskToDeliverObservations();
private:
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_test.cc b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_test.cc
index c88711f07bc..ec2a522d617 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_test.cc
@@ -18,7 +18,6 @@
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
-
namespace blink {
namespace {
@@ -80,7 +79,7 @@ TEST_F(IntersectionObserverTest, ObserveSchedulesFrame) {
LoadURL("https://example.com/");
main_resource.Complete("<div id='target'></div>");
- IntersectionObserverInit observer_init;
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -116,8 +115,8 @@ TEST_F(IntersectionObserverTest, NotificationSentWhenRootRemoved) {
Element* root = GetDocument().getElementById("root");
ASSERT_TRUE(root);
- IntersectionObserverInit observer_init;
- observer_init.setRoot(root);
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
+ observer_init->setRoot(root);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -144,6 +143,68 @@ TEST_F(IntersectionObserverTest, NotificationSentWhenRootRemoved) {
EXPECT_FALSE(observer_delegate->LastEntry()->isIntersecting());
}
+TEST_F(IntersectionObserverTest, ReportsFractionOfTargetOrRoot) {
+ // Place a 100x100 target element in the middle of a 200x200 main frame.
+ WebView().MainFrameWidget()->Resize(WebSize(200, 200));
+ SimRequest main_resource("https://example.com/", "text/html");
+ LoadURL("https://example.com/");
+ main_resource.Complete(R"HTML(
+ <style>
+ #target {
+ position: absolute;
+ top: 50px; left: 50px; width: 100px; height: 100px;
+ }
+ </style>
+ <div id='target'></div>
+ )HTML");
+
+ Element* target = GetDocument().getElementById("target");
+ ASSERT_TRUE(target);
+
+ // 100% of the target element's area intersects with the frame.
+ constexpr float kExpectedFractionOfTarget = 1.0f;
+
+ // 25% of the frame's area is covered by the target element.
+ constexpr float kExpectedFractionOfRoot = 0.25f;
+
+ TestIntersectionObserverDelegate* target_observer_delegate =
+ MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
+ IntersectionObserver* target_observer =
+ MakeGarbageCollected<IntersectionObserver>(
+ *target_observer_delegate, nullptr, Vector<Length>(),
+ Vector<float>{kExpectedFractionOfTarget / 2},
+ IntersectionObserver::kFractionOfTarget, 0, false);
+ DummyExceptionStateForTesting exception_state;
+ target_observer->observe(target, exception_state);
+ ASSERT_FALSE(exception_state.HadException());
+
+ TestIntersectionObserverDelegate* root_observer_delegate =
+ MakeGarbageCollected<TestIntersectionObserverDelegate>(GetDocument());
+ IntersectionObserver* root_observer =
+ MakeGarbageCollected<IntersectionObserver>(
+ *root_observer_delegate, nullptr, Vector<Length>(),
+ Vector<float>{kExpectedFractionOfRoot / 2},
+ IntersectionObserver::kFractionOfRoot, 0, false);
+ root_observer->observe(target, exception_state);
+ ASSERT_FALSE(exception_state.HadException());
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+ ASSERT_FALSE(Compositor().NeedsBeginFrame());
+
+ EXPECT_EQ(target_observer_delegate->CallCount(), 1);
+ EXPECT_EQ(target_observer_delegate->EntryCount(), 1);
+ EXPECT_TRUE(target_observer_delegate->LastEntry()->isIntersecting());
+ EXPECT_NEAR(kExpectedFractionOfTarget,
+ target_observer_delegate->LastEntry()->intersectionRatio(), 1e-6);
+
+ EXPECT_EQ(root_observer_delegate->CallCount(), 1);
+ EXPECT_EQ(root_observer_delegate->EntryCount(), 1);
+ EXPECT_TRUE(root_observer_delegate->LastEntry()->isIntersecting());
+ EXPECT_NEAR(kExpectedFractionOfRoot,
+ root_observer_delegate->LastEntry()->intersectionRatio(), 1e-6);
+}
+
TEST_F(IntersectionObserverTest, ResumePostsTask) {
WebView().Resize(WebSize(800, 600));
SimRequest main_resource("https://example.com/", "text/html");
@@ -154,7 +215,7 @@ TEST_F(IntersectionObserverTest, ResumePostsTask) {
<div id='trailing-space' style='height: 700px;'></div>
)HTML");
- IntersectionObserverInit observer_init;
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -214,7 +275,7 @@ TEST_F(IntersectionObserverTest, HitTestAfterMutation) {
<div id='trailing-space' style='height: 700px;'></div>
)HTML");
- IntersectionObserverInit observer_init;
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -261,7 +322,7 @@ TEST_F(IntersectionObserverTest, DisconnectClearsNotifications) {
<div id='trailing-space' style='height: 700px;'></div>
)HTML");
- IntersectionObserverInit observer_init;
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -311,7 +372,7 @@ TEST_F(IntersectionObserverTest, RootIntersectionWithForceZeroLayoutHeight) {
<div id='target'></div>
)HTML");
- IntersectionObserverInit observer_init;
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -346,7 +407,7 @@ TEST_F(IntersectionObserverTest, RootIntersectionWithForceZeroLayoutHeight) {
}
TEST_F(IntersectionObserverV2Test, TrackVisibilityInit) {
- IntersectionObserverInit observer_init;
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -356,20 +417,20 @@ TEST_F(IntersectionObserverV2Test, TrackVisibilityInit) {
EXPECT_FALSE(observer->trackVisibility());
// This should fail because no delay is set.
- observer_init.setTrackVisibility(true);
+ observer_init->setTrackVisibility(true);
observer = IntersectionObserver::Create(observer_init, *observer_delegate,
exception_state);
EXPECT_TRUE(exception_state.HadException());
// This should fail because the delay is < 100.
exception_state.ClearException();
- observer_init.setDelay(99.9);
+ observer_init->setDelay(99.9);
observer = IntersectionObserver::Create(observer_init, *observer_delegate,
exception_state);
EXPECT_TRUE(exception_state.HadException());
exception_state.ClearException();
- observer_init.setDelay(101.);
+ observer_init->setDelay(101.);
observer = IntersectionObserver::Create(observer_init, *observer_delegate,
exception_state);
ASSERT_FALSE(exception_state.HadException());
@@ -394,9 +455,9 @@ TEST_F(IntersectionObserverV2Test, BasicOcclusion) {
<div id='occluder'></div>
)HTML");
- IntersectionObserverInit observer_init;
- observer_init.setTrackVisibility(true);
- observer_init.setDelay(100);
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
+ observer_init->setTrackVisibility(true);
+ observer_init->setDelay(100);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -452,9 +513,9 @@ TEST_F(IntersectionObserverV2Test, BasicOpacity) {
</div>
)HTML");
- IntersectionObserverInit observer_init;
- observer_init.setTrackVisibility(true);
- observer_init.setDelay(100);
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
+ observer_init->setTrackVisibility(true);
+ observer_init->setDelay(100);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
@@ -501,9 +562,9 @@ TEST_F(IntersectionObserverV2Test, BasicTransform) {
</div>
)HTML");
- IntersectionObserverInit observer_init;
- observer_init.setTrackVisibility(true);
- observer_init.setDelay(100);
+ IntersectionObserverInit* observer_init = IntersectionObserverInit::Create();
+ observer_init->setTrackVisibility(true);
+ observer_init->setDelay(100);
DummyExceptionStateForTesting exception_state;
TestIntersectionObserverDelegate* observer_delegate =
new TestIntersectionObserverDelegate(GetDocument());
diff --git a/chromium/third_party/blink/renderer/core/invisible_dom/activate_invisible_event.cc b/chromium/third_party/blink/renderer/core/invisible_dom/activate_invisible_event.cc
index 3257145ef6d..2e596735150 100644
--- a/chromium/third_party/blink/renderer/core/invisible_dom/activate_invisible_event.cc
+++ b/chromium/third_party/blink/renderer/core/invisible_dom/activate_invisible_event.cc
@@ -6,12 +6,12 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
const AtomicString& ActivateInvisibleEvent::InterfaceName() const {
- return EventNames::ActivateInvisibleEvent;
+ return event_interface_names::kActivateInvisibleEvent;
}
bool ActivateInvisibleEvent::IsActivateInvisibleEvent() const {
@@ -19,7 +19,7 @@ bool ActivateInvisibleEvent::IsActivateInvisibleEvent() const {
}
ActivateInvisibleEvent::ActivateInvisibleEvent(Element* activated_element)
- : Event(EventTypeNames::activateinvisible,
+ : Event(event_type_names::kActivateinvisible,
Bubbles::kYes,
Cancelable::kYes,
ComposedMode::kScoped),
diff --git a/chromium/third_party/blink/renderer/core/layout/BUILD.gn b/chromium/third_party/blink/renderer/core/layout/BUILD.gn
index 63a6e40eef0..c3d109daed6 100644
--- a/chromium/third_party/blink/renderer/core/layout/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/layout/BUILD.gn
@@ -94,6 +94,8 @@ blink_core_sources("layout") {
"intersection_geometry.cc",
"intersection_geometry.h",
"intrinsic_sizing_info.h",
+ "jank_region.cc",
+ "jank_region.h",
"jank_tracker.cc",
"jank_tracker.h",
"layout_analyzer.cc",
@@ -281,6 +283,8 @@ blink_core_sources("layout") {
"line/word_measurement.h",
"list_marker_text.cc",
"list_marker_text.h",
+ "logical_values.cc",
+ "logical_values.h",
"map_coordinates_flags.h",
"min_max_size.cc",
"min_max_size.h",
@@ -323,6 +327,8 @@ blink_core_sources("layout") {
"ng/geometry/ng_static_position.cc",
"ng/geometry/ng_static_position.h",
"ng/inline/empty_offset_mapping_builder.h",
+ "ng/inline/layout_ng_text.h",
+ "ng/inline/layout_ng_text_fragment.h",
"ng/inline/ng_abstract_inline_text_box.cc",
"ng/inline/ng_abstract_inline_text_box.h",
"ng/inline/ng_baseline.cc",
@@ -345,6 +351,7 @@ blink_core_sources("layout") {
"ng/inline/ng_inline_item.h",
"ng/inline/ng_inline_item_result.cc",
"ng/inline/ng_inline_item_result.h",
+ "ng/inline/ng_inline_items.h",
"ng/inline/ng_inline_items_builder.cc",
"ng/inline/ng_inline_items_builder.h",
"ng/inline/ng_inline_layout_algorithm.cc",
@@ -401,8 +408,6 @@ blink_core_sources("layout") {
"ng/list/ng_unpositioned_list_marker.h",
"ng/ng_absolute_utils.cc",
"ng/ng_absolute_utils.h",
- "ng/ng_base_fragment_builder.cc",
- "ng/ng_base_fragment_builder.h",
"ng/ng_block_break_token.cc",
"ng/ng_block_break_token.h",
"ng/ng_block_child_iterator.cc",
@@ -413,6 +418,8 @@ blink_core_sources("layout") {
"ng/ng_block_node.h",
"ng/ng_box_fragment.cc",
"ng/ng_box_fragment.h",
+ "ng/ng_box_fragment_builder.cc",
+ "ng/ng_box_fragment_builder.h",
"ng/ng_break_token.cc",
"ng/ng_break_token.h",
"ng/ng_column_layout_algorithm.cc",
@@ -430,7 +437,6 @@ blink_core_sources("layout") {
"ng/ng_floats_utils.cc",
"ng/ng_floats_utils.h",
"ng/ng_fragment.h",
- "ng/ng_fragment_builder.cc",
"ng/ng_fragment_builder.h",
"ng/ng_fragmentation_utils.cc",
"ng/ng_fragmentation_utils.h",
@@ -458,7 +464,6 @@ blink_core_sources("layout") {
"ng/ng_physical_container_fragment.h",
"ng/ng_physical_fragment.cc",
"ng/ng_physical_fragment.h",
- "ng/ng_positioned_float.cc",
"ng/ng_positioned_float.h",
"ng/ng_relative_utils.cc",
"ng/ng_relative_utils.h",
@@ -466,7 +471,6 @@ blink_core_sources("layout") {
"ng/ng_space_utils.h",
"ng/ng_text_decoration_offset.cc",
"ng/ng_text_decoration_offset.h",
- "ng/ng_unpositioned_float.cc",
"ng/ng_unpositioned_float.h",
"ng/ng_unpositioned_float_vector.h",
"order_iterator.cc",
diff --git a/chromium/third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h b/chromium/third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h
index d7888707f07..7008563d988 100644
--- a/chromium/third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h
+++ b/chromium/third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h
@@ -28,7 +28,7 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_block_flow.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_block_flow.h
index 5cd24511d59..95a06d108bf 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_block_flow.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_block_flow.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_box.h"
#include "third_party/blink/renderer/core/layout/floating_objects.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_box.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_box.h
index 49ec16eb92a..d288801aae3 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_box.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_box_model.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_box_model.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_box_model.h
index e9ddcad6e51..245aa79943c 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_box_model.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_box_model.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_inline.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_inline.h
index 885fd9ba19b..3099fb2dd32 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_inline.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_inline.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_box_model.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_item.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_item.h
index 15d4a51beca..799ea6fa6bc 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_item.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_item.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_text.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_text.h
index 5154d693423..eb666a9eddf 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_text.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/bidi_run.h b/chromium/third_party/blink/renderer/core/layout/bidi_run.h
index 92658f3daf9..4e22d2c111e 100644
--- a/chromium/third_party/blink/renderer/core/layout/bidi_run.h
+++ b/chromium/third_party/blink/renderer/core/layout/bidi_run.h
@@ -37,8 +37,8 @@ struct BidiRun : BidiCharacterRun {
int start,
int stop,
LineLayoutItem line_layout_item,
- WTF::Unicode::CharDirection dir,
- WTF::Unicode::CharDirection override_dir)
+ WTF::unicode::CharDirection dir,
+ WTF::unicode::CharDirection override_dir)
: BidiCharacterRun(override, level, start, stop, dir, override_dir),
line_layout_item_(line_layout_item),
box_(nullptr) {
diff --git a/chromium/third_party/blink/renderer/core/layout/column_balancer.cc b/chromium/third_party/blink/renderer/core/layout/column_balancer.cc
index ba3cc6bbb31..1db86174e73 100644
--- a/chromium/third_party/blink/renderer/core/layout/column_balancer.cc
+++ b/chromium/third_party/blink/renderer/core/layout/column_balancer.cc
@@ -237,10 +237,14 @@ static inline LayoutUnit ColumnLogicalHeightRequirementForLine(
// satisfy orphans and widows, and that may affect the minimum page height.
unsigned minimum_line_count =
std::max<unsigned>(style.Orphans(), style.Widows());
- const RootInlineBox* first_line = &last_line;
- for (unsigned i = 1; i < minimum_line_count && first_line->PrevRootBox(); i++)
- first_line = first_line->PrevRootBox();
- return last_line.LineBottomWithLeading() - first_line->LineTopWithLeading();
+ const RootInlineBox* line = &last_line;
+ LayoutUnit logical_height_requirement;
+ for (unsigned i = 0; i < minimum_line_count && line; i++) {
+ logical_height_requirement +=
+ line->LineBottomWithLeading() - line->LineTopWithLeading();
+ line = line->PrevRootBox();
+ }
+ return logical_height_requirement;
}
void InitialColumnHeightFinder::ExamineLine(const RootInlineBox& line) {
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc b/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc
index e94d9fce9a8..d591ee54a01 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc
@@ -127,7 +127,7 @@ bool CSSLayoutDefinition::Instance::Layout(
// TODO(ikilpatrick): Instead of creating a new style_map each time here,
// store on LayoutCustom, and update when the style changes.
StylePropertyMapReadOnly* style_map =
- new PrepopulatedComputedStylePropertyMap(
+ MakeGarbageCollected<PrepopulatedComputedStylePropertyMap>(
layout_custom.GetDocument(), layout_custom.StyleRef(),
layout_custom.GetNode(), definition_->native_invalidation_properties_,
definition_->custom_invalidation_properties_);
@@ -167,7 +167,7 @@ bool CSSLayoutDefinition::Instance::Layout(
v8::Local<v8::Value> value = iterator.GetValue().ToLocalChecked();
// Process a single fragment request.
- if (V8LayoutFragmentRequest::hasInstance(value, isolate)) {
+ if (V8LayoutFragmentRequest::HasInstance(value, isolate)) {
CustomLayoutFragmentRequest* fragment_request =
V8LayoutFragmentRequest::ToImpl(v8::Local<v8::Object>::Cast(value));
@@ -241,7 +241,7 @@ bool CSSLayoutDefinition::Instance::Layout(
// Attempt to convert the result.
V8FragmentResultOptions::ToImpl(isolate, result_value,
- *fragment_result_options, exception_state);
+ fragment_result_options, exception_state);
if (exception_state.HadException()) {
V8ScriptRunner::ReportException(isolate, exception_state.GetException());
@@ -314,7 +314,7 @@ CSSLayoutDefinition::Instance* CSSLayoutDefinition::CreateInstance() {
if (V8ScriptRunner::CallAsConstructor(
isolate, constructor, ExecutionContext::From(script_state_), 0, {})
.ToLocal(&layout_instance)) {
- instance = new Instance(this, layout_instance);
+ instance = MakeGarbageCollected<Instance>(this, layout_instance);
} else {
constructor_has_failed_ = true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.h b/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.h
index bec75b92da7..7364c994f3d 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/css_layout_definition.h
@@ -5,8 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_CUSTOM_CSS_LAYOUT_DEFINITION_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_CUSTOM_CSS_LAYOUT_DEFINITION_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/platform/bindings/name_client.h"
#include "third_party/blink/renderer/platform/bindings/scoped_persistent.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc
index cf6efdfd738..a992eaab899 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc
@@ -15,7 +15,7 @@ namespace blink {
CustomLayoutChild::CustomLayoutChild(const CSSLayoutDefinition& definition,
LayoutBox* box)
: box_(box),
- style_map_(new PrepopulatedComputedStylePropertyMap(
+ style_map_(MakeGarbageCollected<PrepopulatedComputedStylePropertyMap>(
box->GetDocument(),
box->StyleRef(),
box->GetNode(),
@@ -24,15 +24,15 @@ CustomLayoutChild::CustomLayoutChild(const CSSLayoutDefinition& definition,
CustomLayoutFragmentRequest* CustomLayoutChild::layoutNextFragment(
ScriptState* script_state,
- const CustomLayoutConstraintsOptions& options,
+ const CustomLayoutConstraintsOptions* options,
ExceptionState& exception_state) {
// Serialize the provided data if needed.
scoped_refptr<SerializedScriptValue> constraint_data;
- if (options.hasData()) {
+ if (options->hasData()) {
// We serialize "kForStorage" so that SharedArrayBuffers can't be shared
// between LayoutWorkletGlobalScopes.
constraint_data = SerializedScriptValue::Serialize(
- script_state->GetIsolate(), options.data().V8Value(),
+ script_state->GetIsolate(), options->data().V8Value(),
SerializedScriptValue::SerializeOptions(
SerializedScriptValue::kForStorage),
exception_state);
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.h b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.h
index 6312ea1659d..f168f01a8dd 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_child.h
@@ -33,7 +33,7 @@ class CustomLayoutChild : public ScriptWrappable {
PrepopulatedComputedStylePropertyMap* styleMap() const { return style_map_; }
CustomLayoutFragmentRequest* layoutNextFragment(
ScriptState*,
- const CustomLayoutConstraintsOptions&,
+ const CustomLayoutConstraintsOptions*,
ExceptionState&);
LayoutBox* GetLayoutBox() const {
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_constraints.h b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_constraints.h
index a419cf2e3f9..de087cd23d2 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_constraints.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_constraints.h
@@ -7,8 +7,8 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h
index 7623897382e..120c688fd80 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h
@@ -7,8 +7,8 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.cc b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.cc
index cb5dd8c5c7e..fd45906b1c4 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.cc
@@ -16,7 +16,7 @@ namespace blink {
CustomLayoutFragmentRequest::CustomLayoutFragmentRequest(
CustomLayoutChild* child,
- const CustomLayoutConstraintsOptions& options,
+ const CustomLayoutConstraintsOptions* options,
scoped_refptr<SerializedScriptValue> constraint_data)
: child_(child),
options_(options),
@@ -40,34 +40,35 @@ CustomLayoutFragment* CustomLayoutFragmentRequest::PerformLayout(
bool is_parallel_writing_mode = IsParallelWritingMode(
parent->StyleRef().GetWritingMode(), style.GetWritingMode());
- if (options_.hasFixedInlineSize()) {
+ if (options_->hasFixedInlineSize()) {
if (is_parallel_writing_mode) {
box->SetOverrideLogicalWidth(
- LayoutUnit::FromDoubleRound(options_.fixedInlineSize()));
+ LayoutUnit::FromDoubleRound(options_->fixedInlineSize()));
} else {
box->SetOverrideLogicalHeight(
- LayoutUnit::FromDoubleRound(options_.fixedInlineSize()));
+ LayoutUnit::FromDoubleRound(options_->fixedInlineSize()));
}
} else {
box->SetOverrideContainingBlockContentLogicalWidth(
- options_.hasAvailableInlineSize() &&
- options_.availableInlineSize() >= 0.0
- ? LayoutUnit::FromDoubleRound(options_.availableInlineSize())
+ options_->hasAvailableInlineSize() &&
+ options_->availableInlineSize() >= 0.0
+ ? LayoutUnit::FromDoubleRound(options_->availableInlineSize())
: LayoutUnit());
}
- if (options_.hasFixedBlockSize()) {
+ if (options_->hasFixedBlockSize()) {
if (is_parallel_writing_mode) {
box->SetOverrideLogicalHeight(
- LayoutUnit::FromDoubleRound(options_.fixedBlockSize()));
+ LayoutUnit::FromDoubleRound(options_->fixedBlockSize()));
} else {
box->SetOverrideLogicalWidth(
- LayoutUnit::FromDoubleRound(options_.fixedBlockSize()));
+ LayoutUnit::FromDoubleRound(options_->fixedBlockSize()));
}
} else {
box->SetOverrideContainingBlockContentLogicalHeight(
- options_.hasAvailableBlockSize() && options_.availableBlockSize() >= 0.0
- ? LayoutUnit::FromDoubleRound(options_.availableBlockSize())
+ options_->hasAvailableBlockSize() &&
+ options_->availableBlockSize() >= 0.0
+ ? LayoutUnit::FromDoubleRound(options_->availableBlockSize())
: LayoutUnit());
}
@@ -76,24 +77,24 @@ CustomLayoutFragment* CustomLayoutFragmentRequest::PerformLayout(
LayoutUnit percentage_resolution_logical_height(-1);
if (is_parallel_writing_mode) {
- if (options_.hasPercentageBlockSize() &&
- options_.percentageBlockSize() >= 0.0) {
+ if (options_->hasPercentageBlockSize() &&
+ options_->percentageBlockSize() >= 0.0) {
percentage_resolution_logical_height =
- LayoutUnit::FromDoubleRound(options_.percentageBlockSize());
- } else if (options_.hasAvailableBlockSize() &&
- options_.availableBlockSize() >= 0.0) {
+ LayoutUnit::FromDoubleRound(options_->percentageBlockSize());
+ } else if (options_->hasAvailableBlockSize() &&
+ options_->availableBlockSize() >= 0.0) {
percentage_resolution_logical_height =
- LayoutUnit::FromDoubleRound(options_.availableBlockSize());
+ LayoutUnit::FromDoubleRound(options_->availableBlockSize());
}
} else {
- if (options_.hasPercentageInlineSize() &&
- options_.percentageInlineSize() >= 0.0) {
+ if (options_->hasPercentageInlineSize() &&
+ options_->percentageInlineSize() >= 0.0) {
percentage_resolution_logical_height =
- LayoutUnit::FromDoubleRound(options_.percentageInlineSize());
- } else if (options_.hasAvailableInlineSize() &&
- options_.availableInlineSize() >= 0.0) {
+ LayoutUnit::FromDoubleRound(options_->percentageInlineSize());
+ } else if (options_->hasAvailableInlineSize() &&
+ options_->availableInlineSize() >= 0.0) {
percentage_resolution_logical_height =
- LayoutUnit::FromDoubleRound(options_.availableInlineSize());
+ LayoutUnit::FromDoubleRound(options_->availableInlineSize());
}
}
@@ -131,6 +132,7 @@ bool CustomLayoutFragmentRequest::IsValid() const {
void CustomLayoutFragmentRequest::Trace(blink::Visitor* visitor) {
visitor->Trace(child_);
+ visitor->Trace(options_);
ScriptWrappable::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.h b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.h
index eafa09b3e28..e16608f268a 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/custom_layout_fragment_request.h
@@ -24,7 +24,7 @@ class CustomLayoutFragmentRequest : public ScriptWrappable {
public:
CustomLayoutFragmentRequest(
CustomLayoutChild*,
- const CustomLayoutConstraintsOptions&,
+ const CustomLayoutConstraintsOptions*,
scoped_refptr<SerializedScriptValue> constraint_data);
~CustomLayoutFragmentRequest() override = default;
@@ -40,7 +40,7 @@ class CustomLayoutFragmentRequest : public ScriptWrappable {
private:
Member<CustomLayoutChild> child_;
- const CustomLayoutConstraintsOptions options_;
+ Member<const CustomLayoutConstraintsOptions> options_;
scoped_refptr<SerializedScriptValue> constraint_data_;
DISALLOW_COPY_AND_ASSIGN(CustomLayoutFragmentRequest);
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_custom.cc b/chromium/third_party/blink/renderer/core/layout/custom/layout_custom.cc
index bddcb4a2184..5c62e93ddfe 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_custom.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_custom.cc
@@ -171,15 +171,16 @@ bool LayoutCustom::PerformLayout(bool relayout_children,
return false;
}
- FragmentResultOptions fragment_result_options;
+ FragmentResultOptions* fragment_result_options =
+ FragmentResultOptions::Create();
scoped_refptr<SerializedScriptValue> fragment_result_data;
- if (!instance_->Layout(*this, &fragment_result_options,
+ if (!instance_->Layout(*this, fragment_result_options,
&fragment_result_data))
return false;
size_t index = 0;
const HeapVector<Member<CustomLayoutFragment>>& child_fragments =
- fragment_result_options.childFragments();
+ fragment_result_options->childFragments();
for (LayoutBox* child = FirstChildBox(); child;
child = child->NextSiblingBox()) {
if (child->IsOutOfFlowPositioned()) {
@@ -256,7 +257,7 @@ bool LayoutCustom::PerformLayout(bool relayout_children,
fragment_result_data_ = std::move(fragment_result_data);
SetLogicalHeight(
- LayoutUnit::FromDoubleRound(fragment_result_options.autoBlockSize()));
+ LayoutUnit::FromDoubleRound(fragment_result_options->autoBlockSize()));
LayoutUnit old_client_after_edge = ClientLogicalBottom();
UpdateLogicalHeight();
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.cc b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.cc
index 13080b41a2c..85f475c877c 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.cc
@@ -30,13 +30,13 @@ LayoutWorklet* LayoutWorklet::From(LocalDOMWindow& window) {
// static
LayoutWorklet* LayoutWorklet::Create(LocalFrame* frame) {
- return new LayoutWorklet(frame);
+ return MakeGarbageCollected<LayoutWorklet>(frame);
}
LayoutWorklet::LayoutWorklet(LocalFrame* frame)
: Worklet(frame->GetDocument()),
Supplement<LocalDOMWindow>(*frame->DomWindow()),
- pending_layout_registry_(new PendingLayoutRegistry()) {}
+ pending_layout_registry_(MakeGarbageCollected<PendingLayoutRegistry>()) {}
LayoutWorklet::~LayoutWorklet() = default;
@@ -63,7 +63,7 @@ bool LayoutWorklet::NeedsToCreateGlobalScope() {
WorkletGlobalScopeProxy* LayoutWorklet::CreateGlobalScope() {
DCHECK(NeedsToCreateGlobalScope());
- return new LayoutWorkletGlobalScopeProxy(
+ return MakeGarbageCollected<LayoutWorkletGlobalScopeProxy>(
To<Document>(GetExecutionContext())->GetFrame(), ModuleResponsesMap(),
pending_layout_registry_, GetNumberOfGlobalScopes() + 1);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.h b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.h
index d9e569ce69a..06412375d81 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet.h
@@ -35,6 +35,7 @@ class CORE_EXPORT LayoutWorklet : public Worklet,
static LayoutWorklet* From(LocalDOMWindow&);
static LayoutWorklet* Create(LocalFrame*);
+ explicit LayoutWorklet(LocalFrame*);
~LayoutWorklet() override;
typedef HeapHashMap<String, Member<DocumentLayoutDefinition>>
@@ -49,10 +50,8 @@ class CORE_EXPORT LayoutWorklet : public Worklet,
void Trace(blink::Visitor*) override;
protected:
- explicit LayoutWorklet(LocalFrame*);
-
// TODO(ikilpatrick): Make selection of the global scope non-deterministic.
- size_t SelectGlobalScope() final { return 0u; }
+ wtf_size_t SelectGlobalScope() final { return 0u; }
private:
friend class LayoutWorkletTest;
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc
index 01d4e46dba7..81217385369 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc
@@ -6,7 +6,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_object_parser.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -26,9 +26,9 @@ LayoutWorkletGlobalScope* LayoutWorkletGlobalScope::Create(
WorkerReportingProxy& reporting_proxy,
PendingLayoutRegistry* pending_layout_registry,
size_t global_scope_number) {
- auto* global_scope =
- new LayoutWorkletGlobalScope(frame, std::move(creation_params),
- reporting_proxy, pending_layout_registry);
+ auto* global_scope = MakeGarbageCollected<LayoutWorkletGlobalScope>(
+ frame, std::move(creation_params), reporting_proxy,
+ pending_layout_registry);
String context_name("LayoutWorklet #");
context_name.append(String::Number(global_scope_number));
global_scope->ScriptController()->InitializeContextIfNeeded(context_name,
@@ -113,7 +113,7 @@ void LayoutWorkletGlobalScope::registerLayout(
&layout, &exception_state))
return;
- CSSLayoutDefinition* definition = new CSSLayoutDefinition(
+ CSSLayoutDefinition* definition = MakeGarbageCollected<CSSLayoutDefinition>(
ScriptController()->GetScriptState(), constructor, intrinsic_sizes,
layout, native_invalidation_properties, custom_invalidation_properties,
child_native_invalidation_properties,
@@ -146,7 +146,7 @@ void LayoutWorkletGlobalScope::registerLayout(
pending_layout_registry_->NotifyLayoutReady(name);
} else {
DocumentLayoutDefinition* document_definition =
- new DocumentLayoutDefinition(definition);
+ MakeGarbageCollected<DocumentLayoutDefinition>(definition);
document_definition_map->Set(name, document_definition);
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.h b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.h
index b66123b3bf9..69c2f994961 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.h
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/layout/custom/pending_layout_registry.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -28,6 +29,11 @@ class CORE_EXPORT LayoutWorkletGlobalScope final : public WorkletGlobalScope {
WorkerReportingProxy&,
PendingLayoutRegistry*,
size_t global_scope_number);
+
+ LayoutWorkletGlobalScope(LocalFrame*,
+ std::unique_ptr<GlobalScopeCreationParams>,
+ WorkerReportingProxy&,
+ PendingLayoutRegistry*);
~LayoutWorkletGlobalScope() override;
void Dispose() final;
@@ -43,11 +49,6 @@ class CORE_EXPORT LayoutWorkletGlobalScope final : public WorkletGlobalScope {
void Trace(blink::Visitor*) override;
private:
- LayoutWorkletGlobalScope(LocalFrame*,
- std::unique_ptr<GlobalScopeCreationParams>,
- WorkerReportingProxy&,
- PendingLayoutRegistry*);
-
// https://drafts.css-houdini.org/css-layout-api/#layout-definitions
typedef HeapHashMap<String, TraceWrapperMember<CSSLayoutDefinition>>
DefinitionMap;
@@ -55,11 +56,12 @@ class CORE_EXPORT LayoutWorkletGlobalScope final : public WorkletGlobalScope {
Member<PendingLayoutRegistry> pending_layout_registry_;
};
-DEFINE_TYPE_CASTS(LayoutWorkletGlobalScope,
- ExecutionContext,
- context,
- context->IsLayoutWorkletGlobalScope(),
- context.IsLayoutWorkletGlobalScope());
+template <>
+struct DowncastTraits<LayoutWorkletGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsLayoutWorkletGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.cc b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.cc
index 7c053e510eb..89a5b15d86f 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -36,13 +37,12 @@ LayoutWorkletGlobalScopeProxy::LayoutWorkletGlobalScopeProxy(
std::make_unique<MainThreadWorkletReportingProxy>(document);
WorkerClients* worker_clients = WorkerClients::Create();
- ProvideWorkerFetchContextToWorker(
- worker_clients, frame->Client()->CreateWorkerFetchContext());
ProvideContentSettingsClientToWorker(
worker_clients, frame->Client()->CreateWorkerContentSettingsClient());
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ frame->Client()->CreateWorkerFetchContext(),
document->GetContentSecurityPolicy()->Headers(),
document->GetReferrerPolicy(), document->GetSecurityOrigin(),
document->IsSecureContext(), document->GetHttpsState(), worker_clients,
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_test.cc b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_test.cc
index 9d214566e45..528773e1b73 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_test.cc
@@ -49,8 +49,8 @@ class LayoutWorkletTest : public PageTestBase {
KURL js_url("https://example.com/worklet.js");
ScriptModule module = ScriptModule::Compile(
script_state->GetIsolate(), source_code, js_url, js_url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
EXPECT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(script_state);
@@ -63,46 +63,6 @@ class LayoutWorkletTest : public PageTestBase {
Persistent<LayoutWorklet> layout_worklet_;
};
-TEST_F(LayoutWorkletTest, GarbageCollectionOfCSSLayoutDefinition) {
- EvaluateScriptModule(R"JS(
- registerLayout('foo', class {
- *intrinsicSizes() { }
- *layout() { }
- });
- )JS");
-
- LayoutWorkletGlobalScope* global_scope = GetGlobalScope();
- CSSLayoutDefinition* definition = global_scope->FindDefinition("foo");
- EXPECT_NE(nullptr, definition);
-
- v8::Isolate* isolate =
- global_scope->ScriptController()->GetScriptState()->GetIsolate();
- DCHECK(isolate);
-
- // Set our ScopedPersistent to the layout function, and make weak.
- ScopedPersistent<v8::Function> handle;
- {
- v8::HandleScope handle_scope(isolate);
- handle.Set(isolate, definition->LayoutFunctionForTesting(isolate));
- handle.SetPhantom();
- }
- EXPECT_FALSE(handle.IsEmpty());
- EXPECT_TRUE(handle.IsWeak());
-
- // Run a GC, persistent shouldn't have been collected yet.
- ThreadState::Current()->CollectAllGarbage();
- V8GCController::CollectAllGarbageForTesting(isolate);
- EXPECT_FALSE(handle.IsEmpty());
-
- // Delete the page & associated objects.
- Terminate();
-
- // Run a GC, the persistent should have been collected.
- ThreadState::Current()->CollectAllGarbage();
- V8GCController::CollectAllGarbageForTesting(isolate);
- EXPECT_TRUE(handle.IsEmpty());
-}
-
TEST_F(LayoutWorkletTest, ParseProperties) {
EvaluateScriptModule(R"JS(
registerLayout('foo', class {
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/pending_layout_registry.cc b/chromium/third_party/blink/renderer/core/layout/custom/pending_layout_registry.cc
index f230f122db3..68559c90bb6 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/pending_layout_registry.cc
+++ b/chromium/third_party/blink/renderer/core/layout/custom/pending_layout_registry.cc
@@ -38,7 +38,7 @@ void PendingLayoutRegistry::AddPendingLayout(const AtomicString& name,
Member<PendingSet>& set =
pending_layouts_.insert(name, nullptr).stored_value->value;
if (!set)
- set = new PendingSet;
+ set = MakeGarbageCollected<PendingSet>();
set->insert(node);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc
index 817d529d7a6..c9b7f5e5c22 100644
--- a/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/layout/flexible_box_algorithm.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
+#include "third_party/blink/renderer/core/layout/layout_flexible_box.h"
#include "third_party/blink/renderer/core/layout/min_max_size.h"
namespace blink {
@@ -40,7 +41,9 @@ FlexItem::FlexItem(LayoutBox* box,
MinMaxSize min_max_sizes,
LayoutUnit main_axis_border_and_padding,
LayoutUnit main_axis_margin)
- : box(box),
+ : algorithm(nullptr),
+ line_number(0),
+ box(box),
flex_base_content_size(flex_base_content_size),
min_max_sizes(min_max_sizes),
hypothetical_main_content_size(
@@ -54,8 +57,8 @@ FlexItem::FlexItem(LayoutBox* box,
<< "Use LayoutUnit::Max() for no max size";
}
-bool FlexItem::HasOrthogonalFlow() const {
- return algorithm->IsHorizontalFlow() != box->IsHorizontalWritingMode();
+bool FlexItem::MainAxisIsInlineAxis() const {
+ return algorithm->IsHorizontalFlow() == box->IsHorizontalWritingMode();
}
LayoutUnit FlexItem::FlowAwareMarginStart() const {
@@ -103,10 +106,9 @@ LayoutUnit FlexItem::MarginBoxAscent() const {
return ascent + FlowAwareMarginBefore();
}
-LayoutUnit FlexItem::AvailableAlignmentSpace(
- LayoutUnit line_cross_axis_extent) const {
+LayoutUnit FlexItem::AvailableAlignmentSpace() const {
LayoutUnit cross_extent = CrossAxisMarginExtent() + cross_axis_size;
- return line_cross_axis_extent - cross_extent;
+ return Line()->cross_axis_extent - cross_extent;
}
bool FlexItem::HasAutoMarginsInCrossAxis() const {
@@ -139,6 +141,30 @@ void FlexItem::UpdateAutoMarginsInMainAxis(LayoutUnit auto_margin_offset) {
}
}
+void FlexItem::ComputeStretchedSize() {
+ // TODO(dgrogan): Pass resolved cross-axis MinMaxSize to FlexItem
+ // constructor. Then use cross_axis_min_max.ClampSizeToMinAndMax instead of
+ // relying on legacy in this method.
+ DCHECK_EQ(Alignment(), ItemPosition::kStretch);
+ LayoutFlexibleBox* flexbox = ToLayoutFlexibleBox(box->Parent());
+ if (MainAxisIsInlineAxis() && box->StyleRef().LogicalHeight().IsAuto()) {
+ LayoutUnit stretched_logical_height =
+ std::max(box->BorderAndPaddingLogicalHeight(),
+ Line()->cross_axis_extent - CrossAxisMarginExtent());
+ cross_axis_size = box->ConstrainLogicalHeightByMinMax(
+ stretched_logical_height, box->IntrinsicContentLogicalHeight());
+ } else if (!MainAxisIsInlineAxis() &&
+ box->StyleRef().LogicalWidth().IsAuto()) {
+ LayoutUnit child_width =
+ (Line()->cross_axis_extent - CrossAxisMarginExtent())
+ .ClampNegativeToZero();
+ // This probably doesn't work in NG because flexbox might not yet know its
+ // CrossAxisContentExtent()
+ cross_axis_size = box->ConstrainLogicalWidthByMinMax(
+ child_width, flexbox->CrossAxisContentExtent(), flexbox);
+ }
+}
+
void FlexLine::FreezeViolations(ViolationsVector& violations) {
for (size_t i = 0; i < violations.size(); ++i) {
DCHECK(!violations[i]->frozen) << i;
@@ -377,7 +403,7 @@ FlexLine* FlexLayoutAlgorithm::ComputeNextFlexLine(
wtf_size_t start_index = next_item_index_;
for (; next_item_index_ < all_items_.size(); ++next_item_index_) {
- const FlexItem& flex_item = all_items_[next_item_index_];
+ FlexItem& flex_item = all_items_[next_item_index_];
DCHECK(!flex_item.box->IsOutOfFlowPositioned());
if (IsMultiline() &&
sum_hypothetical_main_size +
@@ -393,6 +419,7 @@ FlexLine* FlexLayoutAlgorithm::ComputeNextFlexLine(
total_weighted_flex_shrink += flex_item.box->StyleRef().FlexShrink() *
flex_item.flex_base_content_size;
sum_hypothetical_main_size += flex_item.HypotheticalMainAxisMarginBoxSize();
+ flex_item.line_number = flex_lines_.size();
}
DCHECK(next_item_index_ > start_index ||
@@ -446,7 +473,6 @@ bool FlexLayoutAlgorithm::ShouldApplyMinSizeAutoForChild(
// TODO(cbiesinger): For now, we do not handle min-height: auto for nested
// column flexboxes. See crbug.com/596743
// css-flexbox section 4.5
-
Length min = IsHorizontalFlow() ? child.StyleRef().MinWidth()
: child.StyleRef().MinHeight();
return min.IsAuto() && !child.ShouldApplySizeContainment() &&
diff --git a/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.h b/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.h
index e3390e9b571..6e0c48e7338 100644
--- a/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.h
@@ -39,12 +39,13 @@
#include "third_party/blink/renderer/core/layout/order_iterator.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
class FlexItem;
+class FlexLine;
class FlexLayoutAlgorithm;
class LayoutBox;
struct MinMaxSize;
@@ -97,7 +98,7 @@ class FlexItem {
ItemPosition Alignment() const;
- bool HasOrthogonalFlow() const;
+ bool MainAxisIsInlineAxis() const;
LayoutUnit FlowAwareMarginStart() const;
LayoutUnit FlowAwareMarginEnd() const;
@@ -106,13 +107,20 @@ class FlexItem {
LayoutUnit MarginBoxAscent() const;
- LayoutUnit AvailableAlignmentSpace(LayoutUnit) const;
+ LayoutUnit AvailableAlignmentSpace() const;
bool HasAutoMarginsInCrossAxis() const;
void UpdateAutoMarginsInMainAxis(LayoutUnit auto_margin_offset);
+ // Computes the cross-axis size that a stretched item should have and stores
+ // it in cross_axis_size. DCHECKs if the item is not stretch aligned.
+ void ComputeStretchedSize();
+
+ inline const FlexLine* Line() const;
+
FlexLayoutAlgorithm* algorithm;
+ wtf_size_t line_number;
LayoutBox* box;
const LayoutUnit flex_base_content_size;
const MinMaxSize min_max_sizes;
@@ -148,6 +156,11 @@ class FlexItemVectorView {
return vector_->at(start_ + i);
}
+ FlexItem* begin() { return vector_->begin() + start_; }
+ const FlexItem* begin() const { return vector_->begin() + start_; }
+ FlexItem* end() { return vector_->begin() + end_; }
+ const FlexItem* end() const { return vector_->begin() + end_; }
+
private:
FlexItemVector* vector_;
wtf_size_t start_;
@@ -284,6 +297,7 @@ class FlexLayoutAlgorithm {
bool IsHorizontalFlow() const;
bool IsColumnFlow() const;
+ bool IsMultiline() const { return style_->FlexWrap() != EFlexWrap::kNowrap; }
static bool IsHorizontalFlow(const ComputedStyle&);
bool IsLeftToRightFlow() const;
TransformedWritingMode GetTransformedWritingMode() const;
@@ -309,7 +323,6 @@ class FlexLayoutAlgorithm {
private:
EOverflow MainAxisOverflowForChild(const LayoutBox& child) const;
- bool IsMultiline() const { return style_->FlexWrap() != EFlexWrap::kNowrap; }
const ComputedStyle* style_;
const LayoutUnit line_break_length_;
@@ -319,6 +332,10 @@ class FlexLayoutAlgorithm {
DISALLOW_COPY_AND_ASSIGN(FlexLayoutAlgorithm);
};
+inline const FlexLine* FlexItem::Line() const {
+ return &algorithm->FlexLines()[line_number];
+}
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_FLEXIBLE_BOX_ALGORITHM_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/floating_objects.cc b/chromium/third_party/blink/renderer/core/layout/floating_objects.cc
index 2395bd9ac64..f5cf1c6dae0 100644
--- a/chromium/third_party/blink/renderer/core/layout/floating_objects.cc
+++ b/chromium/third_party/blink/renderer/core/layout/floating_objects.cc
@@ -47,24 +47,20 @@ struct SameSizeAsFloatingObject {
static_assert(sizeof(FloatingObject) == sizeof(SameSizeAsFloatingObject),
"FloatingObject should stay small");
-FloatingObject::FloatingObject(LayoutBox* layout_object)
+FloatingObject::FloatingObject(LayoutBox* layout_object, Type type)
: layout_object_(layout_object),
originating_line_(nullptr),
+ type_(type),
should_paint_(true),
is_descendant_(false),
is_placed_(false),
is_lowest_non_overhanging_float_in_child_(false)
#if DCHECK_IS_ON()
,
- is_in_placed_tree_(false)
+ is_in_placed_tree_(false),
+ has_geometry_(false)
#endif
{
- EFloat type = layout_object->StyleRef().Floating();
- DCHECK_NE(type, EFloat::kNone);
- if (type == EFloat::kLeft)
- type_ = kFloatLeft;
- else if (type == EFloat::kRight)
- type_ = kFloatRight;
}
FloatingObject::FloatingObject(LayoutBox* layout_object,
@@ -84,15 +80,16 @@ FloatingObject::FloatingObject(LayoutBox* layout_object,
is_lowest_non_overhanging_float_in_child)
#if DCHECK_IS_ON()
,
- is_in_placed_tree_(false)
+ is_in_placed_tree_(false),
+ has_geometry_(false)
#endif
{
}
-std::unique_ptr<FloatingObject> FloatingObject::Create(
- LayoutBox* layout_object) {
+std::unique_ptr<FloatingObject> FloatingObject::Create(LayoutBox* layout_object,
+ Type type) {
std::unique_ptr<FloatingObject> new_obj =
- base::WrapUnique(new FloatingObject(layout_object));
+ base::WrapUnique(new FloatingObject(layout_object, type));
// If a layer exists, the float will paint itself. Otherwise someone else
// will.
@@ -127,6 +124,9 @@ std::unique_ptr<FloatingObject> FloatingObject::UnsafeClone() const {
new FloatingObject(GetLayoutObject(), GetType(), frame_rect_,
should_paint_, is_descendant_, false));
clone_object->is_placed_ = is_placed_;
+#if DCHECK_IS_ON()
+ clone_object->has_geometry_ = has_geometry_;
+#endif
return clone_object;
}
@@ -516,6 +516,7 @@ inline FloatingObjectInterval FloatingObjects::IntervalForFloatingObject(
}
void FloatingObjects::AddPlacedObject(FloatingObject& floating_object) {
+ DCHECK(!layout_object_->IsLayoutNGMixin());
DCHECK(!floating_object.IsInPlacedTree());
floating_object.SetIsPlaced(true);
@@ -529,6 +530,7 @@ void FloatingObjects::AddPlacedObject(FloatingObject& floating_object) {
}
void FloatingObjects::RemovePlacedObject(FloatingObject& floating_object) {
+ DCHECK(!layout_object_->IsLayoutNGMixin());
DCHECK(floating_object.IsPlaced());
DCHECK(floating_object.IsInPlacedTree());
diff --git a/chromium/third_party/blink/renderer/core/layout/floating_objects.h b/chromium/third_party/blink/renderer/core/layout/floating_objects.h
index 0eaa0deda7d..7820696f20c 100644
--- a/chromium/third_party/blink/renderer/core/layout/floating_objects.h
+++ b/chromium/third_party/blink/renderer/core/layout/floating_objects.h
@@ -53,7 +53,7 @@ class FloatingObject {
// for both left and right.
enum Type { kFloatLeft = 1, kFloatRight = 2, kFloatLeftRight = 3 };
- static std::unique_ptr<FloatingObject> Create(LayoutBox*);
+ static std::unique_ptr<FloatingObject> Create(LayoutBox*, Type);
std::unique_ptr<FloatingObject> CopyToNewContainer(
LayoutSize,
@@ -66,22 +66,39 @@ class FloatingObject {
LayoutBox* GetLayoutObject() const { return layout_object_; }
bool IsPlaced() const { return is_placed_; }
- void SetIsPlaced(bool placed = true) { is_placed_ = placed; }
+ void SetIsPlaced(bool placed = true) {
+ is_placed_ = placed;
+#if DCHECK_IS_ON()
+ has_geometry_ = placed;
+#endif
+ }
+
+#if DCHECK_IS_ON()
+ void SetHasGeometry() { has_geometry_ = true; }
+#endif
+
+ bool HasGeometry() const {
+#if DCHECK_IS_ON()
+ return has_geometry_;
+#else
+ return true;
+#endif
+ }
LayoutUnit X() const {
- DCHECK(IsPlaced());
+ DCHECK(HasGeometry());
return frame_rect_.X();
}
LayoutUnit MaxX() const {
- DCHECK(IsPlaced());
+ DCHECK(HasGeometry());
return frame_rect_.MaxX();
}
LayoutUnit Y() const {
- DCHECK(IsPlaced());
+ DCHECK(HasGeometry());
return frame_rect_.Y();
}
LayoutUnit MaxY() const {
- DCHECK(IsPlaced());
+ DCHECK(HasGeometry());
return frame_rect_.MaxY();
}
LayoutUnit Width() const { return frame_rect_.Width(); }
@@ -105,7 +122,7 @@ class FloatingObject {
}
const LayoutRect& FrameRect() const {
- DCHECK(IsPlaced());
+ DCHECK(HasGeometry());
return frame_rect_;
}
@@ -131,7 +148,7 @@ class FloatingObject {
void SetOriginatingLine(RootInlineBox* line) { originating_line_ = line; }
private:
- explicit FloatingObject(LayoutBox*);
+ FloatingObject(LayoutBox*, Type);
FloatingObject(LayoutBox*,
Type,
const LayoutRect&,
@@ -149,6 +166,14 @@ class FloatingObject {
unsigned is_placed_ : 1;
unsigned is_lowest_non_overhanging_float_in_child_ : 1;
unsigned is_in_placed_tree_ : 1;
+
+#if DCHECK_IS_ON()
+ // If set, it's safe to read out position data for this float. For LayoutNG
+ // this will always be true, while for legacy layout, it depends on whether
+ // the float IsPlaced() or not.
+ unsigned has_geometry_ : 1;
+#endif
+
DISALLOW_COPY_AND_ASSIGN(FloatingObject);
};
diff --git a/chromium/third_party/blink/renderer/core/layout/fragmentation_context.h b/chromium/third_party/blink/renderer/core/layout/fragmentation_context.h
index 014d8bf62a1..0b8b8ba6105 100644
--- a/chromium/third_party/blink/renderer/core/layout/fragmentation_context.h
+++ b/chromium/third_party/blink/renderer/core/layout/fragmentation_context.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc
index 2b74ea75ab2..1348a467789 100644
--- a/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/layout/grid.h"
#include "third_party/blink/renderer/core/layout/grid_layout_utils.h"
#include "third_party/blink/renderer/core/layout/layout_grid.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -294,7 +294,8 @@ LayoutUnit GridTrackSizingAlgorithmStrategy::LogicalHeightForChild(
*GetLayoutGrid(), child, child_block_direction)) {
SetOverrideContainingBlockContentSizeForChild(child, child_block_direction,
LayoutUnit(-1));
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged, kMarkOnlyThis);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged,
+ kMarkOnlyThis);
}
child.LayoutIfNeeded();
@@ -324,7 +325,8 @@ LayoutUnit GridTrackSizingAlgorithmStrategy::MinContentForChild(
if (UpdateOverrideContainingBlockContentSizeForChild(
child, child_inline_direction)) {
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged, kMarkOnlyThis);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged,
+ kMarkOnlyThis);
}
return LogicalHeightForChild(child);
}
@@ -348,7 +350,8 @@ LayoutUnit GridTrackSizingAlgorithmStrategy::MaxContentForChild(
if (UpdateOverrideContainingBlockContentSizeForChild(
child, child_inline_direction)) {
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged, kMarkOnlyThis);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged,
+ kMarkOnlyThis);
}
return LogicalHeightForChild(child);
}
@@ -535,7 +538,8 @@ void DefiniteSizeStrategy::LayoutGridItemForMinSizeComputation(
LayoutBox& child,
bool override_size_has_changed) const {
if (override_size_has_changed) {
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged, kMarkOnlyThis);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged,
+ kMarkOnlyThis);
child.LayoutIfNeeded();
}
}
@@ -577,7 +581,8 @@ void IndefiniteSizeStrategy::LayoutGridItemForMinSizeComputation(
LayoutBox& child,
bool override_size_has_changed) const {
if (override_size_has_changed && Direction() != kForColumns) {
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged, kMarkOnlyThis);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged,
+ kMarkOnlyThis);
child.LayoutIfNeeded();
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h b/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h
index 33f9299845e..0b2bf5e7a85 100644
--- a/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/style/grid_positions_resolver.h"
#include "third_party/blink/renderer/core/style/grid_track_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_cache.h b/chromium/third_party/blink/renderer/core/layout/hit_test_cache.h
index d7eff08565e..4cd439c02c0 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_cache.h
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_cache.h
@@ -47,7 +47,9 @@ struct HitTestCacheEntry {
class CORE_EXPORT HitTestCache final
: public GarbageCollectedFinalized<HitTestCache> {
public:
- static HitTestCache* Create() { return new HitTestCache; }
+ static HitTestCache* Create() { return MakeGarbageCollected<HitTestCache>(); }
+
+ HitTestCache() : update_index_(0), dom_tree_version_(0) {}
// Check the cache for a possible hit and update |result| if
// hit encountered; returning true. Otherwise false.
@@ -65,8 +67,6 @@ class CORE_EXPORT HitTestCache final
void Trace(blink::Visitor*);
private:
- HitTestCache() : update_index_(0), dom_tree_version_(0) {}
-
// The below UMA values reference a validity region. This code has not
// been written yet; and exact matches are only supported but the
// UMA enumerations have been added for future support.
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_canvas_result.h b/chromium/third_party/blink/renderer/core/layout/hit_test_canvas_result.h
index a37c95a5847..7e77a0f99b1 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_canvas_result.h
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_canvas_result.h
@@ -13,17 +13,17 @@ class CORE_EXPORT HitTestCanvasResult final
: public GarbageCollectedFinalized<HitTestCanvasResult> {
public:
static HitTestCanvasResult* Create(String id, Member<Element> control) {
- return new HitTestCanvasResult(id, control);
+ return MakeGarbageCollected<HitTestCanvasResult>(id, control);
}
+ HitTestCanvasResult(String id, Member<Element> control);
+
String GetId() const;
Element* GetControl() const;
void Trace(blink::Visitor*);
private:
- HitTestCanvasResult(String id, Member<Element> control);
-
String id_;
Member<Element> control_;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_result.cc b/chromium/third_party/blink/renderer/core/layout/hit_test_result.cc
index 5467908d751..e93774969dc 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_result.cc
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_result.cc
@@ -46,7 +46,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
HitTestResult::HitTestResult()
: hit_test_request_(HitTestRequest::kReadOnly | HitTestRequest::kActive),
@@ -72,9 +72,10 @@ HitTestResult::HitTestResult(const HitTestResult& other)
is_over_embedded_content_view_(other.IsOverEmbeddedContentView()),
canvas_region_id_(other.CanvasRegionId()) {
// Only copy the NodeSet in case of list hit test.
- list_based_test_result_ = other.list_based_test_result_
- ? new NodeSet(*other.list_based_test_result_)
- : nullptr;
+ list_based_test_result_ =
+ other.list_based_test_result_
+ ? MakeGarbageCollected<NodeSet>(*other.list_based_test_result_)
+ : nullptr;
}
HitTestResult::~HitTestResult() = default;
@@ -114,9 +115,10 @@ void HitTestResult::PopulateFromCachedResult(const HitTestResult& other) {
canvas_region_id_ = other.CanvasRegionId();
// Only copy the NodeSet in case of list hit test.
- list_based_test_result_ = other.list_based_test_result_
- ? new NodeSet(*other.list_based_test_result_)
- : nullptr;
+ list_based_test_result_ =
+ other.list_based_test_result_
+ ? MakeGarbageCollected<NodeSet>(*other.list_based_test_result_)
+ : nullptr;
}
void HitTestResult::Trace(blink::Visitor* visitor) {
@@ -181,7 +183,7 @@ HTMLAreaElement* HitTestResult::ImageAreaForImage() const {
return nullptr;
HTMLMapElement* map = image_element->GetTreeScope().GetImageMap(
- image_element->FastGetAttribute(usemapAttr));
+ image_element->FastGetAttribute(kUsemapAttr));
if (!map)
return nullptr;
@@ -253,7 +255,7 @@ const AtomicString& HitTestResult::AltDisplayString() const {
return g_null_atom;
if (auto* image = ToHTMLImageElementOrNull(*inner_node_or_image_map_image))
- return image->getAttribute(altAttr);
+ return image->getAttribute(kAltAttr);
if (auto* input = ToHTMLInputElementOrNull(*inner_node_or_image_map_image))
return input->Alt();
@@ -299,7 +301,7 @@ KURL HitTestResult::AbsoluteImageURL() const {
if (IsHTMLImageElement(*inner_node_or_image_map_image) ||
(IsHTMLInputElement(*inner_node_or_image_map_image) &&
ToHTMLInputElement(inner_node_or_image_map_image)->type() ==
- InputTypeNames::image))
+ input_type_names::kImage))
url_string = ToElement(*inner_node_or_image_map_image).ImageSourceURL();
else if ((inner_node_or_image_map_image->GetLayoutObject() &&
inner_node_or_image_map_image->GetLayoutObject()->IsImage()) &&
@@ -445,13 +447,13 @@ void HitTestResult::Append(const HitTestResult& other) {
const HitTestResult::NodeSet& HitTestResult::ListBasedTestResult() const {
if (!list_based_test_result_)
- list_based_test_result_ = new NodeSet;
+ list_based_test_result_ = MakeGarbageCollected<NodeSet>();
return *list_based_test_result_;
}
HitTestResult::NodeSet& HitTestResult::MutableListBasedTestResult() {
if (!list_based_test_result_)
- list_based_test_result_ = new NodeSet;
+ list_based_test_result_ = MakeGarbageCollected<NodeSet>();
return *list_based_test_result_;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/intersection_geometry.h b/chromium/third_party/blink/renderer/core/layout/intersection_geometry.h
index f08cfdbcc07..3a625f97abd 100644
--- a/chromium/third_party/blink/renderer/core/layout/intersection_geometry.h
+++ b/chromium/third_party/blink/renderer/core/layout/intersection_geometry.h
@@ -6,8 +6,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_INTERSECTION_GEOMETRY_H_
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_region.cc b/chromium/third_party/blink/renderer/core/layout/jank_region.cc
new file mode 100644
index 00000000000..8a0b58081b4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/jank_region.cc
@@ -0,0 +1,317 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/jank_region.h"
+
+namespace blink {
+
+namespace {
+
+// A segment is a contiguous range of one or more basic intervals.
+struct Segment {
+ // These are the 0-based indexes into the basic intervals, of the first and
+ // last basic interval in the segment.
+ unsigned first_interval;
+ unsigned last_interval;
+};
+
+// An "event" occurs when a rectangle starts intersecting the sweep line
+// (START), or when it ceases to intersect the sweep line (END).
+enum class EventType { START, END };
+struct SweepEvent {
+ // X-coordinate at which the event occurs.
+ int x;
+ // Whether the sweep line is entering or exiting the generating rect.
+ EventType type;
+ // The generating rect's intersection with the sweep line.
+ Segment y_segment;
+};
+
+// The sequence of adjacent intervals on the y-axis whose endpoints are the
+// extents (IntRect::Y and IntRect::MaxY) of all the rectangles in the input.
+class BasicIntervals {
+ public:
+ // Add all the endpoints before creating the index.
+ void AddEndpoint(int endpoint);
+ void CreateIndex();
+
+ // Create the index before querying these.
+ unsigned NumIntervals() const;
+ Segment SegmentFromEndpoints(int start, int end) const;
+ unsigned SegmentLength(Segment) const;
+
+ private:
+ Vector<int> endpoints_;
+ std::map<int, unsigned> endpoint_to_index_;
+
+#if DCHECK_IS_ON()
+ bool has_index_ = false;
+#endif
+};
+
+#if DCHECK_IS_ON()
+#define DCHECK_HAS_INDEX(expected) DCHECK(has_index_ == expected)
+#else
+#define DCHECK_HAS_INDEX(expected)
+#endif
+
+inline void BasicIntervals::AddEndpoint(int endpoint) {
+ DCHECK_HAS_INDEX(false);
+
+ // We can't index yet, but use the map to de-dupe.
+ auto ret = endpoint_to_index_.insert(std::make_pair(endpoint, 0u));
+ if (ret.second)
+ endpoints_.push_back(endpoint);
+}
+
+void BasicIntervals::CreateIndex() {
+ DCHECK_HAS_INDEX(false);
+ std::sort(endpoints_.begin(), endpoints_.end());
+ unsigned i = 0;
+ for (const int& e : endpoints_)
+ endpoint_to_index_[e] = i++;
+
+#if DCHECK_IS_ON()
+ has_index_ = true;
+#endif
+}
+
+inline unsigned BasicIntervals::NumIntervals() const {
+ DCHECK_HAS_INDEX(true);
+ return endpoints_.size() - 1;
+}
+
+inline Segment BasicIntervals::SegmentFromEndpoints(int start, int end) const {
+ DCHECK_HAS_INDEX(true);
+ return Segment{endpoint_to_index_.at(start), endpoint_to_index_.at(end) - 1};
+}
+
+inline unsigned BasicIntervals::SegmentLength(Segment segment) const {
+ DCHECK_HAS_INDEX(true);
+ return endpoints_[segment.last_interval + 1] -
+ endpoints_[segment.first_interval];
+}
+
+#undef DCHECK_HAS_INDEX
+
+// An array-backed, weight-balanced binary tree whose leaves represent the basic
+// intervals. Non-leaf nodes represent the union of their children's intervals.
+class SegmentTree {
+ public:
+ SegmentTree(const BasicIntervals&);
+
+ // The RefSegment and DerefSegment methods mark nodes corresponding to a
+ // segment by touching the minimal set of nodes that comprise the segment,
+ // i.e. every node that is fully within the segment, but whose parent isn't.
+ // There are only O(log N) nodes in this set.
+ void RefSegment(Segment);
+ void DerefSegment(Segment);
+
+ // Combined length of all active segments.
+ unsigned ActiveLength() const;
+
+ private:
+ static unsigned ComputeCapacity(unsigned leaf_count);
+
+ static unsigned LeftChild(unsigned node_index);
+ static unsigned RightChild(unsigned node_index);
+
+ Segment RootSegment() const;
+ unsigned ComputeActiveLength(unsigned node_index, Segment node_segment) const;
+
+ // Visit implements the recursive descent through the tree to update nodes for
+ // a RefSegment or DerefSegment operation.
+ void Visit(unsigned node_index,
+ Segment node_segment,
+ Segment query_segment,
+ int refcount_delta);
+
+ struct Node {
+ // The ref count for a node tells the number of active segments (rectangles
+ // intersecting the sweep line) that fully contain this node but not its
+ // parent. It's updated by RefSegment and DerefSegment.
+ unsigned ref_count = 0;
+
+ // Length-contribution of the intervals in this node's subtree that have
+ // non-zero ref counts.
+ unsigned active_length = 0;
+ };
+
+ const BasicIntervals& intervals_;
+ Vector<Node> nodes_;
+};
+
+SegmentTree::SegmentTree(const BasicIntervals& intervals)
+ : intervals_(intervals) {
+ nodes_.resize(ComputeCapacity(intervals.NumIntervals()));
+}
+
+inline void SegmentTree::RefSegment(Segment segment) {
+ Visit(0, RootSegment(), segment, 1);
+}
+
+inline void SegmentTree::DerefSegment(Segment segment) {
+ Visit(0, RootSegment(), segment, -1);
+}
+
+inline unsigned SegmentTree::ActiveLength() const {
+ return nodes_.front().active_length;
+}
+
+unsigned SegmentTree::ComputeCapacity(unsigned leaf_count) {
+ unsigned cap = 1;
+ while (cap < leaf_count)
+ cap = cap << 1;
+ return (cap << 1) - 1;
+}
+
+inline unsigned SegmentTree::LeftChild(unsigned node_index) {
+ return (node_index << 1) + 1;
+}
+
+inline unsigned SegmentTree::RightChild(unsigned node_index) {
+ return (node_index << 1) + 2;
+}
+
+inline Segment SegmentTree::RootSegment() const {
+ return {0, intervals_.NumIntervals() - 1};
+}
+
+inline unsigned SegmentTree::ComputeActiveLength(unsigned node_index,
+ Segment node_segment) const {
+ // If any segment fully covers the interval represented by this node,
+ // then its active length contribution is the entire interval.
+ if (nodes_[node_index].ref_count > 0)
+ return intervals_.SegmentLength(node_segment);
+
+ // Otherwise, it contributes only the active lengths of its children.
+ if (node_segment.last_interval > node_segment.first_interval) {
+ return nodes_[LeftChild(node_index)].active_length +
+ nodes_[RightChild(node_index)].active_length;
+ }
+ return 0;
+}
+
+void SegmentTree::Visit(unsigned node_index,
+ Segment node_segment,
+ Segment query_segment,
+ int refcount_delta) {
+ Node& node = nodes_[node_index];
+
+ // node_segment is the interval represented by this node. (We save some space
+ // by computing it as we descend instead of storing it in the Node.)
+ unsigned node_low = node_segment.first_interval;
+ unsigned node_high = node_segment.last_interval;
+
+ // query_segment is the interval we want to update within the node.
+ unsigned query_low = query_segment.first_interval;
+ unsigned query_high = query_segment.last_interval;
+
+ DCHECK(query_low >= node_low && query_high <= node_high);
+
+ if (node_low == query_low && node_high == query_high) {
+ // The entire node is covered.
+ node.ref_count += refcount_delta;
+ } else {
+ // Last interval in left subtree.
+ unsigned lower_mid = (node_low + node_high) >> 1;
+ // First interval in right subtree.
+ unsigned upper_mid = lower_mid + 1;
+
+ if (query_low <= lower_mid) {
+ Visit(LeftChild(node_index), {node_low, lower_mid},
+ {query_low, std::min(query_high, lower_mid)}, refcount_delta);
+ }
+ if (query_high >= upper_mid) {
+ Visit(RightChild(node_index), {upper_mid, node_high},
+ {std::max(query_low, upper_mid), query_high}, refcount_delta);
+ }
+ }
+ node.active_length = ComputeActiveLength(node_index, node_segment);
+}
+
+// Runs the sweep line algorithm to compute the area of a set of rects.
+class Sweeper {
+ public:
+ Sweeper(const Vector<IntRect>&);
+
+ // Returns the area.
+ uint64_t Sweep() const;
+
+ private:
+ void InitIntervals(BasicIntervals&) const;
+ void InitEventQueue(Vector<SweepEvent>&, const BasicIntervals&) const;
+ uint64_t SweepImpl(SegmentTree&, const Vector<SweepEvent>&) const;
+
+ // The input.
+ const Vector<IntRect>& rects_;
+};
+
+Sweeper::Sweeper(const Vector<IntRect>& rects) : rects_(rects) {}
+
+uint64_t Sweeper::Sweep() const {
+ BasicIntervals y_vals;
+ InitIntervals(y_vals);
+ SegmentTree tree(y_vals);
+
+ Vector<SweepEvent> events;
+ InitEventQueue(events, y_vals);
+ return SweepImpl(tree, events);
+}
+
+void Sweeper::InitIntervals(BasicIntervals& y_vals) const {
+ for (const IntRect& rect : rects_) {
+ y_vals.AddEndpoint(rect.Y());
+ y_vals.AddEndpoint(rect.MaxY());
+ }
+ y_vals.CreateIndex();
+}
+
+void Sweeper::InitEventQueue(Vector<SweepEvent>& events,
+ const BasicIntervals& y_vals) const {
+ events.ReserveInitialCapacity(rects_.size() << 1);
+ for (const IntRect& rect : rects_) {
+ Segment segment = y_vals.SegmentFromEndpoints(rect.Y(), rect.MaxY());
+ events.push_back(SweepEvent{rect.X(), EventType::START, segment});
+ events.push_back(SweepEvent{rect.MaxX(), EventType::END, segment});
+ }
+ std::sort(events.begin(), events.end(),
+ [](const SweepEvent& e1, const SweepEvent& e2) -> bool {
+ return e1.x < e2.x;
+ });
+}
+
+uint64_t Sweeper::SweepImpl(SegmentTree& tree,
+ const Vector<SweepEvent>& events) const {
+ uint64_t area = 0;
+ int sweep_x = events.front().x;
+
+ for (const SweepEvent& e : events) {
+ if (e.x > sweep_x) {
+ area += (uint64_t)(e.x - sweep_x) * (uint64_t)tree.ActiveLength();
+ sweep_x = e.x;
+ }
+ if (e.type == EventType::START)
+ tree.RefSegment(e.y_segment);
+ else
+ tree.DerefSegment(e.y_segment);
+ }
+ return area;
+}
+
+} // namespace
+
+uint64_t JankRegion::Area() const {
+ if (rects_.IsEmpty())
+ return 0;
+
+ // Optimization: for a single rect, we don't need Sweeper.
+ if (rects_.size() == 1) {
+ const IntRect& rect = rects_.front();
+ return rect.Width() * rect.Height();
+ }
+ return Sweeper(rects_).Sweep();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_region.h b/chromium/third_party/blink/renderer/core/layout/jank_region.h
new file mode 100644
index 00000000000..6e19fcdd46a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/jank_region.h
@@ -0,0 +1,54 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_JANK_REGION_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_JANK_REGION_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+// Represents a per-frame jank region for JankTracker. Only used when the
+// JankTrackingSweepLine feature is enabled.
+//
+// This class uses a sweep line algorithm to compute the area in O(n log n) time
+// where n is the number of rects recorded by AddRect. For complex jank regions,
+// this is more efficient than using blink::Region, which is worst-case O(n^2)
+// from the repeated calls to Region::Unite.
+//
+// The high-level approach is described here:
+// http://jeffe.cs.illinois.edu/open/klee.html
+//
+// The sweep line moves from left to right. (TODO: compare performance against a
+// top-to-bottom sweep.)
+//
+// The sweep line's current intersection with the jank region ("active length")
+// is tracked by a segment tree, similar to what is described at:
+// https://en.wikipedia.org/wiki/Segment_tree
+//
+// There are some subtleties to the segment tree, which are described by the
+// comments in the implementation.
+
+class CORE_EXPORT JankRegion {
+ public:
+ void AddRect(const IntRect& rect) {
+ if (!rect.IsEmpty())
+ rects_.push_back(rect);
+ }
+
+ const Vector<IntRect>& GetRects() const { return rects_; }
+ bool IsEmpty() const { return rects_.IsEmpty(); }
+ void Reset() { rects_.clear(); }
+
+ uint64_t Area() const;
+
+ private:
+ Vector<IntRect> rects_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_JANK_REGION_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_region_test.cc b/chromium/third_party/blink/renderer/core/layout/jank_region_test.cc
new file mode 100644
index 00000000000..a688fec0592
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/jank_region_test.cc
@@ -0,0 +1,122 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/jank_region.h"
+
+#include <gtest/gtest.h>
+#include "third_party/blink/renderer/platform/geometry/region.h"
+
+namespace blink {
+
+class JankRegionTest : public testing::Test {};
+
+TEST_F(JankRegionTest, Basic) {
+ JankRegion region;
+ EXPECT_EQ(0u, region.Area());
+
+ region.AddRect(IntRect(2, 1, 1, 3));
+ EXPECT_EQ(3u, region.Area());
+
+ region.AddRect(IntRect(1, 2, 3, 1));
+ EXPECT_EQ(5u, region.Area());
+
+ region.AddRect(IntRect(1, 2, 1, 1));
+ region.AddRect(IntRect(3, 2, 1, 1));
+ region.AddRect(IntRect(2, 1, 1, 1));
+ region.AddRect(IntRect(2, 3, 1, 1));
+ EXPECT_EQ(5u, region.Area());
+
+ region.AddRect(IntRect(1, 1, 1, 1));
+ EXPECT_EQ(6u, region.Area());
+
+ region.AddRect(IntRect(1, 1, 3, 3));
+ EXPECT_EQ(9u, region.Area());
+
+ region.AddRect(IntRect(0, 0, 2, 2));
+ EXPECT_EQ(12u, region.Area());
+
+ region.AddRect(IntRect(-1, -1, 2, 2));
+ EXPECT_EQ(15u, region.Area());
+
+ region.Reset();
+ EXPECT_EQ(0u, region.Area());
+}
+
+TEST_F(JankRegionTest, LargeRandom) {
+ JankRegion region;
+ Region naive_region;
+ static const int data[] = {
+ 52613, 38528, 20785, 40550, 29734, 48229, 37113, 3520, 66776, 26746,
+ 20527, 11398, 27951, 50399, 37139, 17597, 20593, 57272, 12528, 5907,
+ 18369, 6955, 50779, 41129, 66685, 46725, 30708, 32429, 140, 55034,
+ 14770, 40886, 54560, 53666, 15350, 12692, 29354, 47388, 47542, 15474,
+ 17770, 70300, 27992, 6731, 47459, 42205, 45231, 9398, 15606, 2238,
+ 8387, 44579, 45222, 35626, 53932, 2907, 14899, 18234, 60609, 34125,
+ 23985, 48145, 40247, 25215, 64427, 41207, 29742, 35282, 21390, 12640,
+ 14653, 71326, 41293, 4593, 54114, 55398, 17797, 55637, 64133, 25985,
+ 45213, 6428, 6496, 37832, 31291, 27955, 32967, 4134, 35992, 3226,
+ 43190, 31310, 49828, 6737, 31847, 65511, 52287, 41393, 33728, 29813,
+ 32425, 74095, 41857, 2537, 14073, 16177, 23053, 75553, 3570, 76482,
+ 49801, 17920, 45628, 59408, 44788, 18020, 11607, 21027, 27095, 52992,
+ 37770, 51722, 15857, 38088, 22031, 68391, 66615, 2592, 91, 16324,
+ 64393, 51544, 3848, 1924, 90673, 16461, 97524, 42603, 122, 55027,
+ 7945, 10493, 89602, 38306, 73269, 72165, 15014, 23160, 10208, 66632,
+ 78104, 22252, 52910, 7870, 293, 61338, 54913, 48813, 3949, 6507,
+ 82176, 60067, 13639, 13096, 71024, 52767, 20514, 4716, 15125, 14158,
+ 24315, 46986, 62316, 95391, 8390, 1007, 9520, 67532, 69963, 20117,
+ 51649, 42999, 1441, 34966, 17616, 16544, 51218, 72116, 1780, 12254,
+ 52065, 67026, 88250, 39824, 1786, 22090, 14884, 41933, 46081, 25596,
+ 89968, 51346, 2479, 36409, 11513, 36037, 19481, 4287, 33831, 28199,
+ 56514, 52659, 54910, 14740, 43540, 45912, 44651, 4232, 15199, 45442,
+ 45856, 19374, 17597, 50923, 24227, 17000, 47585, 61718, 48390, 37848,
+ 23677, 2669, 49142, 37207, 30794, 11373, 41719, 40002, 39749, 39146,
+ 39144, 59801, 23772, 17552, 26731, 7802, 29291, 40281, 82706, 9370,
+ 7006, 75864, 94618, 75409, 5267, 5222, 47927, 19430, 4425, 14295,
+ 16662, 22094, 33027, 48759, 42250, 5205, 5424, 70064, 36751, 60688,
+ 45415, 24027, 37665, 88085, 16011, 8785, 12656, 1662, 68336, 62175,
+ 2132, 66236, 5301, 5174, 9575, 42509, 41511, 44451, 59069, 43296,
+ 3246, 11251, 37176, 25619, 60728, 36030, 40982, 33756, 46296, 4407,
+ 84886, 59809, 8127, 34846, 44433, 4366, 4823, 52452, 4594, 69662,
+ 59199, 18623, 29345, 36375, 20166, 12254, 30879, 84106, 29786, 7838,
+ 35875, 32227, 34871, 31142, 71453, 74402, 3243, 4475, 1974, 62754,
+ 80498, 26875, 22957, 25916, 74769, 66343, 18666, 28537, 41799, 54598,
+ 32617, 73615, 51275, 20602, 10642, 57506, 72158, 38152, 12552, 36601,
+ 29638, 28894, 67153, 27560, 1577, 67248, 65745, 53338, 4220, 20883,
+ 72059, 33747, 11195, 47783, 21251, 92912, 25, 4257, 17625, 29683,
+ 32964, 31019, 37510, 2205, 47755, 15187, 9769, 28377, 28890, 6955,
+ 31621, 21088, 54431, 30372, 14567, 47483, 80553, 4324, 10574, 870,
+ 59862, 86272, 8682, 49237, 85735, 10570, 21034, 50807, 47647, 37221,
+ };
+ uint64_t expected_area = 9201862875ul;
+ for (unsigned i = 0; i < 100; i++) {
+ const int* d = data + (i * 4);
+ IntRect r(d[0], d[1], d[2], d[3]);
+ region.AddRect(r);
+ naive_region.Unite(Region(r));
+ }
+ EXPECT_EQ(expected_area, region.Area());
+ EXPECT_EQ(expected_area, naive_region.Area());
+}
+
+// Creates a region like this:
+// █ █ █
+// ███████
+// █ █ █
+// ███████
+// █ █ █
+// ███████
+// █ █ █
+TEST_F(JankRegionTest, Waffle) {
+ JankRegion region;
+ unsigned n = 250000;
+ for (unsigned i = 2; i <= n; i += 2) {
+ region.AddRect(IntRect(i, 1, 1, n + 1));
+ region.AddRect(IntRect(1, i, n + 1, 1));
+ }
+ uint64_t half = n >> 1;
+ uint64_t area = n * (half + 1) + half * half;
+ EXPECT_EQ(area, region.Area());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_tracker.cc b/chromium/third_party/blink/renderer/core/layout/jank_tracker.cc
index bbbf56be7d8..cbd97b744fe 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_tracker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/jank_tracker.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/location.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -80,6 +81,15 @@ static void RegionToTracedValue(const Region& region,
value.EndArray();
}
+static void RegionToTracedValue(const JankRegion& region,
+ double granularity_scale,
+ TracedValue& value) {
+ Region old_region;
+ for (IntRect rect : region.GetRects())
+ old_region.Unite(Region(rect));
+ RegionToTracedValue(old_region, granularity_scale, value);
+}
+
JankTracker::JankTracker(LocalFrameView* frame_view)
: frame_view_(frame_view),
score_(0.0),
@@ -130,8 +140,13 @@ void JankTracker::AccumulateJank(const LayoutObject& source,
visible_old_rect.Scale(scale);
visible_new_rect.Scale(scale);
- region_.Unite(Region(visible_old_rect));
- region_.Unite(Region(visible_new_rect));
+ if (RuntimeEnabledFeatures::JankTrackingSweepLineEnabled()) {
+ region_experimental_.AddRect(visible_old_rect);
+ region_experimental_.AddRect(visible_new_rect);
+ } else {
+ region_.Unite(Region(visible_old_rect));
+ region_.Unite(Region(visible_new_rect));
+ }
}
void JankTracker::NotifyObjectPrePaint(const LayoutObject& object,
@@ -165,15 +180,27 @@ void JankTracker::NotifyCompositedLayerMoved(const PaintLayer& paint_layer,
}
void JankTracker::NotifyPrePaintFinished() {
- if (!IsActive() || region_.IsEmpty())
+ if (!IsActive())
+ return;
+ bool use_sweep_line = RuntimeEnabledFeatures::JankTrackingSweepLineEnabled();
+ bool region_is_empty =
+ use_sweep_line ? region_experimental_.IsEmpty() : region_.IsEmpty();
+ if (region_is_empty)
return;
IntRect viewport = frame_view_->GetScrollableArea()->VisibleContentRect();
double granularity_scale = RegionGranularityScale(viewport);
viewport.Scale(granularity_scale);
+
+ if (viewport.IsEmpty())
+ return;
+
double viewport_area = double(viewport.Width()) * double(viewport.Height());
+ uint64_t region_area =
+ use_sweep_line ? region_experimental_.Area() : region_.Area();
+ double jank_fraction = region_area / viewport_area;
+ DCHECK_GT(jank_fraction, 0);
- double jank_fraction = region_.Area() / viewport_area;
score_ += jank_fraction;
DVLOG(1) << "viewport " << (jank_fraction * 100)
@@ -184,7 +211,9 @@ void JankTracker::NotifyPrePaintFinished() {
PerFrameTraceData(jank_fraction, granularity_scale),
"frame", ToTraceValue(&frame_view_->GetFrame()));
- if (RuntimeEnabledFeatures::LayoutJankAPIEnabled() && jank_fraction > 0 &&
+ frame_view_->GetFrame().Client()->DidObserveLayoutJank(jank_fraction);
+
+ if (RuntimeEnabledFeatures::LayoutJankAPIEnabled() &&
frame_view_->GetFrame().DomWindow()) {
WindowPerformance* performance =
DOMWindowPerformance::performance(*frame_view_->GetFrame().DomWindow());
@@ -194,7 +223,10 @@ void JankTracker::NotifyPrePaintFinished() {
}
}
- region_ = Region();
+ if (use_sweep_line)
+ region_experimental_.Reset();
+ else
+ region_ = Region();
}
void JankTracker::NotifyInput(const WebInputEvent& event) {
@@ -234,7 +266,10 @@ std::unique_ptr<TracedValue> JankTracker::PerFrameTraceData(
value->SetDouble("jank_fraction", jank_fraction);
value->SetDouble("cumulative_score", score_);
value->SetDouble("max_distance", max_distance_);
- RegionToTracedValue(region_, granularity_scale, *value);
+ if (RuntimeEnabledFeatures::JankTrackingSweepLineEnabled())
+ RegionToTracedValue(region_experimental_, granularity_scale, *value);
+ else
+ RegionToTracedValue(region_, granularity_scale, *value);
value->SetBoolean("is_main_frame", frame_view_->GetFrame().IsMainFrame());
return value;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_tracker.h b/chromium/third_party/blink/renderer/core/layout/jank_tracker.h
index 5d496d8ec46..6c3e2f1396c 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_tracker.h
+++ b/chromium/third_party/blink/renderer/core/layout/jank_tracker.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_JANK_TRACKER_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/jank_region.h"
#include "third_party/blink/renderer/platform/geometry/region.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -59,6 +60,9 @@ class CORE_EXPORT JankTracker {
// The per-frame jank region.
Region region_;
+ // Experimental jank region implementation using sweep-line algorithm.
+ JankRegion region_experimental_;
+
// Tracks the short period after an input event during which we ignore jank.
TaskRunnerTimer<JankTracker> timer_;
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc b/chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc
index ca815420964..abe86ef53f3 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc
@@ -24,6 +24,11 @@ class JankTrackerTest : public RenderingTest {
WebPointerProperties::Button::kLeft, 0,
WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks()));
}
+
+ void UpdateAllLifecyclePhases() {
+ GetFrameView().UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
};
TEST_F(JankTrackerTest, SimpleBlockMovement) {
@@ -37,9 +42,9 @@ TEST_F(JankTrackerTest, SimpleBlockMovement) {
EXPECT_EQ(0.0, GetJankTracker().Score());
EXPECT_EQ(0.0, GetJankTracker().MaxDistance());
- GetDocument().getElementById("j")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 60px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// 300 * (100 + 60) / (default viewport size 800 * 600)
EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
EXPECT_FLOAT_EQ(60.0, GetJankTracker().MaxDistance());
@@ -52,9 +57,9 @@ TEST_F(JankTrackerTest, GranularitySnapping) {
</style>
<div id='j'></div>
)HTML");
- GetDocument().getElementById("j")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 58px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Rect locations and sizes should snap to multiples of 600 / 60 = 10.
EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
}
@@ -71,9 +76,9 @@ TEST_F(JankTrackerTest, Transform) {
</div>
)HTML");
- GetDocument().getElementById("j")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 60px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// (600 - 300) * (140 - 40 + 60) / (default viewport size 800 * 600)
EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
}
@@ -86,8 +91,8 @@ TEST_F(JankTrackerTest, RtlDistance) {
<div id='j'></div>
)HTML");
GetDocument().getElementById("j")->setAttribute(
- HTMLNames::styleAttr, AtomicString("width: 70px; left: 10px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ html_names::kStyleAttr, AtomicString("width: 70px; left: 10px"));
+ UpdateAllLifecyclePhases();
EXPECT_FLOAT_EQ(20.0, GetJankTracker().MaxDistance());
}
@@ -98,9 +103,9 @@ TEST_F(JankTrackerTest, SmallMovementIgnored) {
</style>
<div id='j'></div>
)HTML");
- GetDocument().getElementById("j")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 2px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(0.0, GetJankTracker().Score());
}
@@ -112,9 +117,9 @@ TEST_F(JankTrackerTest, SmallMovementIgnoredWithZoom) {
</style>
<div id='j'></div>
)HTML");
- GetDocument().getElementById("j")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 2px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(0.0, GetJankTracker().Score());
}
@@ -125,10 +130,10 @@ TEST_F(JankTrackerTest, IgnoreAfterInput) {
</style>
<div id='j'></div>
)HTML");
- GetDocument().getElementById("j")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 60px"));
SimulateInput();
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(0.0, GetJankTracker().Score());
}
@@ -158,8 +163,8 @@ TEST_F(JankTrackerTest, CompositedElementMovement) {
)HTML");
GetDocument().getElementById("space")->setAttribute(
- HTMLNames::styleAttr, AtomicString("height: 100px"));
- GetFrameView().UpdateAllLifecyclePhases();
+ html_names::kStyleAttr, AtomicString("height: 100px"));
+ UpdateAllLifecyclePhases();
// #jank is 400x200 after viewport intersection with correct application of
// composited #container offset, and 100px lower after janking, so jank score
@@ -186,12 +191,12 @@ TEST_F(JankTrackerTest, CompositedJankBeforeFirstPaint) {
</div>
)HTML");
- GetDocument().getElementById("B")->setAttribute(HTMLNames::classAttr,
+ GetDocument().getElementById("B")->setAttribute(html_names::kClassAttr,
AtomicString("tr"));
GetFrameView().UpdateLifecycleToCompositingCleanPlusScrolling();
- GetDocument().getElementById("A")->setAttribute(HTMLNames::classAttr,
+ GetDocument().getElementById("A")->setAttribute(html_names::kClassAttr,
AtomicString("hide"));
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_analyzer.h b/chromium/third_party/blink/renderer/core/layout/layout_analyzer.h
index 7925e607f7e..b4178849c50 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_analyzer.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_analyzer.h
@@ -7,7 +7,7 @@
#include <memory>
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_block.cc b/chromium/third_party/blink/renderer/core/layout/layout_block.cc
index e2aa1401e54..09d769f4ca1 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block.cc
@@ -55,6 +55,7 @@
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/text_autosizer.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -433,6 +434,9 @@ void LayoutBlock::UpdateLayout() {
LayoutAnalyzer::Scope analyzer(*this);
+ if (LayoutBlockedByDisplayLock())
+ return;
+
bool needs_scroll_anchoring =
HasOverflowClip() && GetScrollableArea()->ShouldPerformScrollAnchoring();
if (needs_scroll_anchoring)
@@ -451,6 +455,7 @@ void LayoutBlock::UpdateLayout() {
height_available_to_children_changed_ = false;
cached_constraint_space_.reset();
+ NotifyDisplayLockDidLayout();
}
bool LayoutBlock::WidthAvailableToChildrenHasChanged() {
@@ -892,8 +897,8 @@ void LayoutBlock::LayoutPositionedObject(LayoutBox* positioned_object,
// here instead of a full layout. Need to investigate why it does not
// trigger the correct invalidations in that case. crbug.com/350756
if (info == kForcedLayoutAfterContainingBlockMoved) {
- positioned_object->SetNeedsLayout(LayoutInvalidationReason::kAncestorMoved,
- kMarkOnlyThis);
+ positioned_object->SetNeedsLayout(
+ layout_invalidation_reason::kAncestorMoved, kMarkOnlyThis);
}
positioned_object->LayoutIfNeeded();
@@ -1140,7 +1145,7 @@ void LayoutBlock::DirtyForLayoutFromPercentageHeightDescendants(
LayoutUnit LayoutBlock::TextIndentOffset() const {
LayoutUnit cw;
if (StyleRef().TextIndent().IsPercentOrCalc())
- cw = ContainingBlock()->AvailableLogicalWidth();
+ cw = ContentLogicalWidth();
return MinimumValueForLength(StyleRef().TextIndent(), cw);
}
@@ -1326,7 +1331,7 @@ PositionWithAffinity LayoutBlock::PositionForPointIfOutsideAtomicInlineLevel(
static inline bool IsChildHitTestCandidate(LayoutBox* box) {
return box->Size().Height() &&
box->StyleRef().Visibility() == EVisibility::kVisible &&
- !box->IsOutOfFlowPositioned() && !box->IsLayoutFlowThread();
+ !box->IsFloatingOrOutOfFlowPositioned() && !box->IsLayoutFlowThread();
}
PositionWithAffinity LayoutBlock::PositionForPoint(
@@ -1368,9 +1373,6 @@ PositionWithAffinity LayoutBlock::PositionForPoint(
continue;
LayoutUnit child_logical_bottom =
LogicalTopForChild(*child_box) + LogicalHeightForChild(*child_box);
- if (child_box->IsLayoutBlockFlow())
- child_logical_bottom += ToLayoutBlockFlow(child_box)->LowestFloatLogicalBottom();
-
// We hit child if our click is above the bottom of its padding box (like
// IE6/7 and FF3).
if (point_in_logical_contents.Y() < child_logical_bottom ||
@@ -1532,13 +1534,12 @@ void LayoutBlock::ComputeBlockPreferredLogicalWidths(
if (child->IsFloating() ||
(child->IsBox() && ToLayoutBox(child)->AvoidsFloats())) {
LayoutUnit float_total_width = float_left_width + float_right_width;
- if (child_style->Clear() == EClear::kBoth ||
- child_style->Clear() == EClear::kLeft) {
+ EClear c = ResolvedClear(*child_style, style_to_use);
+ if (c == EClear::kBoth || c == EClear::kLeft) {
max_logical_width = std::max(float_total_width, max_logical_width);
float_left_width = LayoutUnit();
}
- if (child_style->Clear() == EClear::kBoth ||
- child_style->Clear() == EClear::kRight) {
+ if (c == EClear::kBoth || c == EClear::kRight) {
max_logical_width = std::max(float_total_width, max_logical_width);
float_right_width = LayoutUnit();
}
@@ -1603,7 +1604,7 @@ void LayoutBlock::ComputeBlockPreferredLogicalWidths(
}
if (child->IsFloating()) {
- if (child_style->Floating() == EFloat::kLeft)
+ if (ResolvedFloating(*child_style, style_to_use) == EFloat::kLeft)
float_left_width += w;
else
float_right_width += w;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_block.h b/chromium/third_party/blink/renderer/core/layout/layout_block.h
index fb9ba1b1e3f..211c5569465 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block.h
@@ -449,11 +449,11 @@ class CORE_EXPORT LayoutBlock : public LayoutBox {
private:
void AddVisualOverflowFromBlockChildren();
- void AddVisualOverflowFromTheme();
void AddLayoutOverflowFromPositionedObjects();
void AddLayoutOverflowFromBlockChildren();
protected:
+ void AddVisualOverflowFromTheme();
virtual void ComputeVisualOverflow(
const LayoutRect& previous_visual_overflow_rect,
bool recompute_floats);
@@ -461,7 +461,7 @@ class CORE_EXPORT LayoutBlock : public LayoutBox {
bool recompute_floats);
virtual void AddLayoutOverflowFromChildren();
- virtual void AddVisualOverflowFromChildren();
+ void AddVisualOverflowFromChildren();
void AddOutlineRects(Vector<LayoutRect>&,
const LayoutPoint& additional_offset,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_block_flow.cc b/chromium/third_party/blink/renderer/core/layout/layout_block_flow.cc
index 7f51035100f..b5a5ce372c2 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block_flow.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block_flow.cc
@@ -53,6 +53,7 @@
#include "third_party/blink/renderer/core/layout/line/inline_iterator.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
#include "third_party/blink/renderer/core/layout/line/line_width.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h"
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
#include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h"
@@ -1942,9 +1943,10 @@ LayoutUnit LayoutBlockFlow::CollapseMargins(
bool logical_top_intrudes_into_float =
logical_top < before_collapse_logical_top;
if (logical_top_intrudes_into_float && ContainsFloats() &&
- !child.AvoidsFloats() && LowestFloatLogicalBottom() > logical_top)
+ !child.AvoidsFloats() && LowestFloatLogicalBottom() > logical_top) {
child.SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kAncestorMarginCollapsing);
+ layout_invalidation_reason::kAncestorMarginCollapsing);
+ }
}
return logical_top;
@@ -2362,7 +2364,7 @@ bool LayoutBlockFlow::MustDiscardMarginAfter() const {
bool LayoutBlockFlow::MustDiscardMarginBeforeForChild(
const LayoutBox& child) const {
- DCHECK(!child.SelfNeedsLayout());
+ DCHECK(!child.SelfNeedsLayout() || child.LayoutBlockedByDisplayLock());
if (!child.IsWritingModeRoot()) {
return child.IsLayoutBlockFlow()
? ToLayoutBlockFlow(&child)->MustDiscardMarginBefore()
@@ -2385,7 +2387,7 @@ bool LayoutBlockFlow::MustDiscardMarginBeforeForChild(
bool LayoutBlockFlow::MustDiscardMarginAfterForChild(
const LayoutBox& child) const {
- DCHECK(!child.SelfNeedsLayout());
+ DCHECK(!child.SelfNeedsLayout() || child.LayoutBlockedByDisplayLock());
if (!child.IsWritingModeRoot()) {
return child.IsLayoutBlockFlow()
? ToLayoutBlockFlow(&child)->MustDiscardMarginAfter()
@@ -2427,7 +2429,7 @@ void LayoutBlockFlow::SetMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg) {
bool LayoutBlockFlow::MustSeparateMarginBeforeForChild(
const LayoutBox& child) const {
- DCHECK(!child.SelfNeedsLayout());
+ DCHECK(!child.SelfNeedsLayout() || child.LayoutBlockedByDisplayLock());
const ComputedStyle& child_style = child.StyleRef();
if (!child.IsWritingModeRoot())
return child_style.MarginBeforeCollapse() == EMarginCollapse::kSeparate;
@@ -2440,7 +2442,7 @@ bool LayoutBlockFlow::MustSeparateMarginBeforeForChild(
bool LayoutBlockFlow::MustSeparateMarginAfterForChild(
const LayoutBox& child) const {
- DCHECK(!child.SelfNeedsLayout());
+ DCHECK(!child.SelfNeedsLayout() || child.LayoutBlockedByDisplayLock());
const ComputedStyle& child_style = child.StyleRef();
if (!child.IsWritingModeRoot())
return child_style.MarginAfterCollapse() == EMarginCollapse::kSeparate;
@@ -2539,7 +2541,7 @@ void LayoutBlockFlow::AddLayoutOverflowFromFloats() {
scoped_refptr<NGLayoutResult> LayoutBlockFlow::CachedLayoutResult(
const NGConstraintSpace&,
- const NGBreakToken*) const {
+ const NGBreakToken*) {
return nullptr;
}
@@ -2554,6 +2556,10 @@ void LayoutBlockFlow::SetCachedLayoutResult(const NGConstraintSpace&,
void LayoutBlockFlow::ClearCachedLayoutResult() {}
+bool LayoutBlockFlow::AreCachedLinesValidFor(const NGConstraintSpace&) const {
+ return false;
+}
+
void LayoutBlockFlow::SetPaintFragment(const NGBreakToken*,
scoped_refptr<const NGPhysicalFragment>,
NGPhysicalOffset) {}
@@ -2566,11 +2572,20 @@ void LayoutBlockFlow::UpdatePaintFragmentFromCachedLayoutResult(
void LayoutBlockFlow::ComputeVisualOverflow(
const LayoutRect& previous_visual_overflow_rect,
bool recompute_floats) {
- LayoutBlock::ComputeVisualOverflow(previous_visual_overflow_rect,
- recompute_floats);
+ AddVisualOverflowFromChildren();
+
+ AddVisualEffectOverflow();
+ AddVisualOverflowFromTheme();
+
if (recompute_floats || CreatesNewFormattingContext() ||
HasSelfPaintingLayer())
AddVisualOverflowFromFloats();
+
+ if (VisualOverflowRect() != previous_visual_overflow_rect) {
+ if (Layer())
+ Layer()->SetNeedsCompositingInputsUpdate();
+ GetFrameView()->SetIntersectionObservationState(LocalFrameView::kDesired);
+ }
}
void LayoutBlockFlow::ComputeLayoutOverflow(LayoutUnit old_client_after_edge,
@@ -2689,6 +2704,8 @@ int LayoutBlockFlow::LineCount(
}
LayoutUnit LayoutBlockFlow::FirstLineBoxBaseline() const {
+ if (ShouldApplyLayoutContainment())
+ return LayoutUnit(-1);
// Orthogonal grid items can participante in baseline alignment along column
// axis.
if (IsWritingModeRoot() && !IsRubyRun() && !IsGridItem())
@@ -2887,7 +2904,7 @@ LayoutUnit LayoutBlockFlow::GetClearDelta(LayoutBox* child,
// At least one float is present. We need to perform the clearance
// computation.
- EClear clear = child->StyleRef().Clear();
+ EClear clear = ResolvedClear(child->StyleRef(), StyleRef());
LayoutUnit logical_bottom = LowestFloatLogicalBottom(clear);
// We also clear floats if we are too big to sit on the same line as a float
@@ -3021,7 +3038,7 @@ void LayoutBlockFlow::StyleDidChange(StyleDifference diff,
bool needs_update_ancestor_float_object_should_paint_flags = false;
if (HasSelfPaintingLayer() != had_self_painting_layer &&
HasOverhangingFloats()) {
- SetNeedsLayout(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayout(layout_invalidation_reason::kStyleChange);
if (had_self_painting_layer)
MarkAllDescendantsWithFloatsForLayout();
else
@@ -3108,13 +3125,12 @@ bool LayoutBlockFlow::NeedsAnonymousInlineWrapper() const {
DCHECK(RuntimeEnabledFeatures::LayoutNGEnabled());
if (!GetDocument().GetStyleEngine().UsesFirstLineRules())
return false;
+ // We need an anonymous inline wrapper only if ::first-line has different
+ // background, but excessive anonymous inline will not harm much. To simplify,
+ // create the wrapper whenever ::first-line is applied.
const ComputedStyle& first_line_style = FirstLineStyleRef();
const ComputedStyle& style = StyleRef();
- if (&first_line_style == &style)
- return false;
- // We need an anonymous inline wrapper only if ::first-line has different
- // background, but excessive anonymous inline will not harm.
- return first_line_style.HasBackground();
+ return &first_line_style != &style;
}
void LayoutBlockFlow::AddChild(LayoutObject* new_child,
@@ -3403,7 +3419,7 @@ void LayoutBlockFlow::CollapseAnonymousBlockChild(LayoutBlockFlow* child) {
if (child->IsRubyRun() || child->IsRubyBase())
return;
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kChildAnonymousBlockChanged);
+ layout_invalidation_reason::kChildAnonymousBlockChanged);
child->MoveAllChildrenTo(this, child->NextSibling(), child->HasLayer());
// If we make an object's children inline we are going to frustrate any future
@@ -3429,7 +3445,7 @@ bool LayoutBlockFlow::MergeSiblingContiguousAnonymousBlock(
return false;
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAnonymousBlockChange);
+ layout_invalidation_reason::kAnonymousBlockChange);
// If the inlineness of children of the two block don't match, we'd need
// special code here (but there should be no need for it).
@@ -3522,8 +3538,8 @@ void LayoutBlockFlow::MakeChildrenInlineIfPossible() {
// at layout.
RemoveFloatingObjectsFromDescendants();
- for (size_t i = 0; i < blocks_to_remove.size(); i++)
- CollapseAnonymousBlockChild(blocks_to_remove[i]);
+ for (LayoutBlockFlow* child : blocks_to_remove)
+ CollapseAnonymousBlockChild(child);
SetChildrenInline(true);
}
@@ -3723,7 +3739,7 @@ LayoutPoint LayoutBlockFlow::ComputeLogicalLocationForFloat(
LayoutUnit float_logical_left;
- if (child_box->StyleRef().Floating() == EFloat::kLeft) {
+ if (ResolvedFloating(child_box->StyleRef(), StyleRef()) == EFloat::kLeft) {
LayoutUnit height_remaining_left = LayoutUnit(1);
LayoutUnit height_remaining_right = LayoutUnit(1);
float_logical_left = LogicalLeftOffsetForPositioningFloat(
@@ -3780,8 +3796,12 @@ FloatingObject* LayoutBlockFlow::InsertFloatingObject(LayoutBox& float_box) {
}
// Create the special object entry & append it to the list
-
- std::unique_ptr<FloatingObject> new_obj = FloatingObject::Create(&float_box);
+ EFloat f = ResolvedFloating(float_box.StyleRef(), StyleRef());
+ DCHECK(f == EFloat::kLeft || f == EFloat::kRight);
+ FloatingObject::Type type = f == EFloat::kLeft ? FloatingObject::kFloatLeft
+ : FloatingObject::kFloatRight;
+ std::unique_ptr<FloatingObject> new_obj =
+ FloatingObject::Create(&float_box, type);
return floating_objects_->Add(std::move(new_obj));
}
@@ -3908,9 +3928,9 @@ LayoutUnit LayoutBlockFlow::PositionAndLayoutFloat(
// FIXME Investigate if this can be removed. crbug.com/370006
child.SetShouldCheckForPaintInvalidation();
- logical_top_margin_edge =
- std::max(logical_top_margin_edge,
- LowestFloatLogicalBottom(child.StyleRef().Clear()));
+ logical_top_margin_edge = std::max(
+ logical_top_margin_edge,
+ LowestFloatLogicalBottom(ResolvedClear(child.StyleRef(), StyleRef())));
bool is_paginated = View()->GetLayoutState()->IsPaginated();
if (is_paginated && !ChildrenInline()) {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_block_flow.h b/chromium/third_party/blink/renderer/core/layout/layout_block_flow.h
index 215b9a217e2..9a000f4cbaa 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block_flow.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block_flow.h
@@ -458,12 +458,13 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
virtual NGPaintFragment* PaintFragment() const { return nullptr; }
virtual scoped_refptr<NGLayoutResult> CachedLayoutResult(
const NGConstraintSpace&,
- const NGBreakToken*) const;
+ const NGBreakToken*);
virtual scoped_refptr<const NGLayoutResult> CachedLayoutResultForTesting();
virtual void SetCachedLayoutResult(const NGConstraintSpace&,
const NGBreakToken*,
const NGLayoutResult&);
virtual void ClearCachedLayoutResult();
+ virtual bool AreCachedLinesValidFor(const NGConstraintSpace&) const;
virtual void WillCollectInlines() {}
virtual void SetPaintFragment(const NGBreakToken*,
scoped_refptr<const NGPhysicalFragment>,
@@ -820,6 +821,9 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
int GetLayoutPassCountForTesting();
+ // This is public only for use by LayoutNG, so that NGBlockNode can call it.
+ void IncrementLayoutPassCount();
+
protected:
LayoutUnit MaxPositiveMarginBefore() const {
return rare_data_
@@ -1053,7 +1057,6 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
// Positions new floats and also adjust all floats encountered on the line if
// any of them have to move to the next page/column.
void PositionDialog();
- void IncrementLayoutPassCount();
// END METHODS DEFINED IN LayoutBlockFlowLine
};
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_block_flow_line.cc b/chromium/third_party/blink/renderer/core/layout/layout_block_flow_line.cc
index a27e1170067..20531ff0e3b 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block_flow_line.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block_flow_line.cc
@@ -35,6 +35,7 @@
#include "third_party/blink/renderer/core/layout/line/line_layout_state.h"
#include "third_party/blink/renderer/core/layout/line/line_width.h"
#include "third_party/blink/renderer/core/layout/line/word_measurement.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h"
#include "third_party/blink/renderer/core/layout/vertical_position_cache.h"
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
@@ -1081,9 +1082,9 @@ void LayoutBlockFlow::LayoutRunsAndFloatsInRange(
VerticalPositionCache vertical_position_cache;
// Pagination may require us to delete and re-create a line due to floats.
- // When this happens,
- // we need to store the pagination strut in the meantime.
- LayoutUnit pagination_strut_from_deleted_line;
+ // When this happens, we need to know the old offset of the line, to calculate
+ // the correct pagination strut.
+ LayoutUnit deleted_line_old_offset = LayoutUnit::Min();
LineBreaker line_breaker(LineLayoutBlockFlow(this));
@@ -1139,7 +1140,7 @@ void LayoutBlockFlow::LayoutRunsAndFloatsInRange(
// This is a short-cut for empty lines.
if (layout_state.GetLineInfo().IsEmpty()) {
- DCHECK(!pagination_strut_from_deleted_line);
+ DCHECK_EQ(deleted_line_old_offset, LayoutUnit::Min());
if (LastRootBox())
LastRootBox()->SetLineBreakInfo(end_of_line.GetLineLayoutItem(),
end_of_line.Offset(),
@@ -1201,60 +1202,74 @@ void LayoutBlockFlow::LayoutRunsAndFloatsInRange(
// If we decided to re-create the line due to pagination, we better have a
// new line now.
- DCHECK(line_box || !pagination_strut_from_deleted_line);
+ DCHECK(line_box || deleted_line_old_offset == LayoutUnit::Min());
if (line_box) {
line_box->SetLineBreakInfo(end_of_line.GetLineLayoutItem(),
end_of_line.Offset(), resolver.Status());
if (recalculate_struts) {
- if (pagination_strut_from_deleted_line) {
- // This is a line that got re-created because it got pushed to the
- // next fragmentainer, and there were floats in the vicinity that
- // affected the available width.
- // Restore the pagination info for this line.
- line_box->SetIsFirstAfterPageBreak(true);
- line_box->SetPaginationStrut(pagination_strut_from_deleted_line);
- pagination_strut_from_deleted_line = LayoutUnit();
- } else {
- LayoutUnit adjustment;
- AdjustLinePositionForPagination(*line_box, adjustment);
- if (adjustment) {
- LayoutUnit old_line_width = AvailableLogicalWidthForLine(
- old_logical_height, layout_state.GetLineInfo().IsFirstLine()
- ? kIndentText
- : kDoNotIndentText);
- line_box->MoveInBlockDirection(adjustment);
- if (AvailableLogicalWidthForLine(
- old_logical_height + adjustment,
- layout_state.GetLineInfo().IsFirstLine()
- ? kIndentText
- : kDoNotIndentText) != old_line_width) {
- // We have to delete this line, remove all floats that got
- // added, and let line layout re-run. We had just calculated the
- // pagination strut for this line, and we need to stow it away,
- // so that we can re-apply it when the new line has been
- // created.
- pagination_strut_from_deleted_line =
- line_box->PaginationStrut();
- DCHECK(pagination_strut_from_deleted_line);
- // We're also going to assume that we're right after a page
- // break when re-creating this line, so it better be so.
- DCHECK(line_box->IsFirstAfterPageBreak());
- line_box->DeleteLine();
- end_of_line = RestartLayoutRunsAndFloatsInRange(
- old_logical_height, old_logical_height + adjustment,
- last_float_from_previous_line, resolver,
- previous_endof_line);
- } else {
- SetLogicalHeight(line_box->LineBottomWithLeading());
- }
+ LayoutUnit adjustment;
+ AdjustLinePositionForPagination(*line_box, adjustment);
+ if (adjustment) {
+ DCHECK_GT(adjustment, LayoutUnit());
+ IndentTextOrNot indent = layout_state.GetLineInfo().IsFirstLine()
+ ? kIndentText
+ : kDoNotIndentText;
+ LayoutUnit old_line_width =
+ AvailableLogicalWidthForLine(old_logical_height, indent);
+ LayoutUnit old_logical_top = line_box->LogicalTop();
+ line_box->MoveInBlockDirection(adjustment);
+ if (AvailableLogicalWidthForLine(old_logical_height + adjustment,
+ indent) != old_line_width) {
+ // We have to delete this line, remove all floats that got added,
+ // and let line layout re-run. Store the offset, so that when we
+ // eventually get to a location where the line can fit, we
+ // calculate the correct pagination strut. Store the offset the
+ // first time this happens for a line; it may happen several
+ // times. Example: a line is too tall to fit in the current
+ // fragmentainer, so we attempt to lay it out into the next
+ // one. In the next fragmentainer there may be a float that's too
+ // wide to fit anything beside it, so the line will have to go
+ // below it. But there may not be enough space to fit the line
+ // below the float, so we'll have to skip to the fragmentainer
+ // after that, and retry *again* there. And so on.
+ if (deleted_line_old_offset == LayoutUnit::Min())
+ deleted_line_old_offset = old_logical_top;
+ DCHECK_NE(deleted_line_old_offset, LayoutUnit::Min());
+ // We're also going to assume that we're right after a page
+ // break when re-creating this line, so it better be so.
+ DCHECK(line_box->IsFirstAfterPageBreak());
+ line_box->DeleteLine();
+ line_box = nullptr;
+ end_of_line = RestartLayoutRunsAndFloatsInRange(
+ old_logical_height, old_logical_height + adjustment,
+ last_float_from_previous_line, resolver, previous_endof_line);
+ }
+ }
+ if (line_box &&
+ (adjustment || deleted_line_old_offset != LayoutUnit::Min())) {
+ if (deleted_line_old_offset != LayoutUnit::Min()) {
+ // This is a line that got re-created because it got pushed to the
+ // next fragmentainer, and there were floats in the vicinity that
+ // affected the available width, so we had to re-lay out and
+ // re-paginate. We've finally got to a place where the line
+ // fits. Calculate a new pagination strut.
+ LayoutUnit strut =
+ line_box->LogicalTop() - deleted_line_old_offset;
+ line_box->SetIsFirstAfterPageBreak(true);
+ line_box->SetPaginationStrut(strut);
+ deleted_line_old_offset = LayoutUnit::Min();
}
+ // If the line got adjusted (just now, or in a previous run), we
+ // need to encompass its logical bottom in the logical height of the
+ // block.
+ SetLogicalHeight(line_box->LineBottomWithLeading());
}
}
}
}
- if (!pagination_strut_from_deleted_line) {
+ if (deleted_line_old_offset == LayoutUnit::Min()) {
for (const auto& positioned_object : line_breaker.PositionedObjects()) {
if (positioned_object.StyleRef().IsOriginalDisplayInlineType()) {
// Auto-positioned "inline" out-of-flow objects have already been
@@ -1591,9 +1606,6 @@ void LayoutBlockFlow::ComputeInlinePreferredLogicalWidths(
LayoutUnit inline_min;
const ComputedStyle& style_to_use = StyleRef();
- LayoutBlock* containing_block = ContainingBlock();
- LayoutUnit cw =
- containing_block ? containing_block->ContentLogicalWidth() : LayoutUnit();
// If we are at the start of a line, we want to ignore all white-space.
// Also strip spaces if we previously had text that ended in a trailing space.
@@ -1618,7 +1630,9 @@ void LayoutBlockFlow::ComputeInlinePreferredLogicalWidths(
// Signals the text indent was more negative than the min preferred width
bool has_remaining_negative_text_indent = false;
- LayoutUnit text_indent = MinimumValueForLength(style_to_use.TextIndent(), cw);
+ // Always resolve percentages to 0 when calculating preferred logical widths.
+ LayoutUnit text_indent =
+ MinimumValueForLength(style_to_use.TextIndent(), LayoutUnit());
LayoutObject* prev_float = nullptr;
bool is_prev_child_inline_flow = false;
bool should_break_line_after_text = false;
@@ -1704,15 +1718,17 @@ void LayoutBlockFlow::ComputeInlinePreferredLogicalWidths(
bool clear_previous_float;
if (child->IsFloating()) {
- const ComputedStyle& child_style = child->StyleRef();
- clear_previous_float =
- (prev_float &&
- ((prev_float->StyleRef().Floating() == EFloat::kLeft &&
- (child_style.Clear() == EClear::kBoth ||
- child_style.Clear() == EClear::kLeft)) ||
- (prev_float->StyleRef().Floating() == EFloat::kRight &&
- (child_style.Clear() == EClear::kBoth ||
- child_style.Clear() == EClear::kRight))));
+ if (prev_float) {
+ EFloat f = ResolvedFloating(prev_float->StyleRef(), style_to_use);
+ EClear c = ResolvedClear(child->StyleRef(), style_to_use);
+ clear_previous_float =
+ ((f == EFloat::kLeft &&
+ (c == EClear::kBoth || c == EClear::kLeft)) ||
+ (f == EFloat::kRight &&
+ (c == EClear::kBoth || c == EClear::kRight)));
+ } else {
+ clear_previous_float = false;
+ }
prev_float = child;
} else {
clear_previous_float = false;
@@ -2075,7 +2091,7 @@ RootInlineBox* LayoutBlockFlow::DetermineStartPosition(
// force us to issue paint invalidations.
if (layout_state.HasInlineChild() && !SelfNeedsLayout()) {
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kFloatDescendantChanged, kMarkOnlyThis);
+ layout_invalidation_reason::kFloatDescendantChanged, kMarkOnlyThis);
SetShouldDoFullPaintInvalidation();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_block_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_block_test.cc
index a4fb4c9803e..d4e73a8d192 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block_test.cc
@@ -5,11 +5,14 @@
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/layout/layout_block.h"
+#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
+using ::testing::MatchesRegex;
+
namespace blink {
class LayoutBlockTest : public RenderingTest {};
@@ -19,8 +22,8 @@ TEST_F(LayoutBlockTest, LayoutNameCalledWithNullStyle) {
LayoutObject* obj = LayoutBlockFlow::CreateAnonymous(&GetDocument(), style);
obj->SetStyleInternal(nullptr);
EXPECT_FALSE(obj->Style());
- EXPECT_STREQ("LayoutBlockFlow (anonymous)",
- obj->DecoratedName().Ascii().data());
+ EXPECT_THAT(obj->DecoratedName().Ascii().data(),
+ MatchesRegex("LayoutN?G?BlockFlow \\(anonymous\\)"));
obj->Destroy();
}
@@ -50,7 +53,7 @@ TEST_F(LayoutBlockTest, WidthAvailableToChildrenChanged) {
list_element->style()->setCSSText(&GetDocument(), "width:150px;height:100px;",
exception_state);
ASSERT_FALSE(exception_state.HadException());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_EQ(list_box->VerticalScrollbarWidth(), 0);
ASSERT_EQ(item_element->OffsetWidth(), 150);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_box.cc b/chromium/third_party/blink/renderer/core/layout/layout_box.cc
index 9e26e570c6a..8afce7ccbae 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box.cc
@@ -77,7 +77,7 @@
#include "third_party/blink/renderer/platform/geometry/double_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -222,7 +222,7 @@ void LayoutBox::StyleWillChange(StyleDifference diff,
// mark the current containing block chain for preferred widths
// recalculation.
SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
} else {
MarkContainerChainForLayout();
}
@@ -387,21 +387,9 @@ void LayoutBox::UpdateBackgroundAttachmentFixedStatusAfterStyleChange() {
if (ignore_fixed_background_attachment)
return;
- // An object needs to be repainted on frame scroll when it has background-
- // attachment:fixed, unless the background will be separately composited.
- // LayoutView is responsible for painting root background, thus the root
- // element (and the body element if html element has no background) skips
- // painting backgrounds.
- bool is_background_attachment_fixed_object =
- !IsDocumentElement() && !BackgroundStolenForBeingBody() &&
- StyleRef().HasFixedBackgroundImage();
- if (IsLayoutView() &&
- View()->Compositor()->PreferCompositingToLCDTextEnabled() &&
- StyleRef().HasEntirelyFixedBackground()) {
- is_background_attachment_fixed_object = false;
- }
-
- SetIsBackgroundAttachmentFixedObject(is_background_attachment_fixed_object);
+ SetIsBackgroundAttachmentFixedObject(
+ !BackgroundTransfersToView() &&
+ StyleRef().HasFixedAttachmentBackgroundImage());
}
void LayoutBox::UpdateShapeOutsideInfoAfterStyleChange(
@@ -511,6 +499,9 @@ void LayoutBox::UpdateLayout() {
DCHECK(NeedsLayout());
LayoutAnalyzer::Scope analyzer(*this);
+ if (LayoutBlockedByDisplayLock())
+ return;
+
LayoutObject* child = SlowFirstChild();
if (!child) {
ClearNeedsLayout();
@@ -525,6 +516,7 @@ void LayoutBox::UpdateLayout() {
}
UpdateAfterLayout();
ClearNeedsLayout();
+ NotifyDisplayLockDidLayout();
}
// ClientWidth and ClientHeight represent the interior of an object excluding
@@ -693,13 +685,6 @@ LayoutRect LayoutBox::ScrollRectToVisibleRecursive(
absolute_rect_for_parent =
area_to_scroll->ScrollIntoView(absolute_rect_to_scroll, params);
- // TODO(bokan): This is a hack to reconcile the fact that scrolling a
- // FrameView pre-RLS and post-RLS resulted in different absolute coordinate
- // changes to the target. This line and PendingOffsetToScroll can be
- // removed once RLS is stable. https://crbug.com/823365.
- if (params.is_for_scroll_sequence)
- absolute_rect_for_parent.Move(PendingOffsetToScroll());
-
// If the parent is a local iframe, convert to the absolute coordinate
// space of its document. For remote frames, this will happen on the other
// end of the IPC call.
@@ -786,9 +771,10 @@ LayoutUnit LayoutBox::LogicalHeightWithVisibleOverflow() const {
return overflow.MaxX();
}
-LayoutUnit LayoutBox::ConstrainLogicalWidthByMinMax(LayoutUnit logical_width,
- LayoutUnit available_width,
- LayoutBlock* cb) const {
+LayoutUnit LayoutBox::ConstrainLogicalWidthByMinMax(
+ LayoutUnit logical_width,
+ LayoutUnit available_width,
+ const LayoutBlock* cb) const {
const ComputedStyle& style_to_use = StyleRef();
if (!style_to_use.LogicalMaxWidth().IsMaxSizeNone())
logical_width = std::min(
@@ -1728,7 +1714,9 @@ bool LayoutBox::GetBackgroundPaintedExtent(LayoutRect& painted_extent) const {
bool LayoutBox::BackgroundIsKnownToBeOpaqueInRect(
const LayoutRect& local_rect) const {
- if (IsDocumentElement() || BackgroundStolenForBeingBody())
+ // If the background transfers to view, the used background of this object
+ // is transparent.
+ if (BackgroundTransfersToView())
return false;
// If the element has appearance, it might be painted by theme.
@@ -1872,7 +1860,7 @@ void LayoutBox::ImageChanged(WrappedImagePtr image,
}
}
- if (!IsDocumentElement() && !BackgroundStolenForBeingBody()) {
+ if (!BackgroundTransfersToView()) {
for (const FillLayer* layer = &StyleRef().BackgroundLayers(); layer;
layer = layer->Next()) {
if (layer->GetImage() && image == layer->GetImage()->Data()) {
@@ -1881,13 +1869,10 @@ void LayoutBox::ImageChanged(WrappedImagePtr image,
layer->GetImage()->CachedImage() &&
layer->GetImage()->CachedImage()->GetImage() &&
layer->GetImage()->CachedImage()->GetImage()->MaybeAnimated();
- if (defer == CanDeferInvalidation::kYes && maybe_animated) {
+ if (defer == CanDeferInvalidation::kYes && maybe_animated)
SetMayNeedPaintInvalidationAnimatedBackgroundImage();
- } else {
- SetShouldDoFullPaintInvalidationWithoutGeometryChange(
- PaintInvalidationReason::kImage);
- SetBackgroundChangedSinceLastPaintInvalidation();
- }
+ else
+ SetBackgroundNeedsFullPaintInvalidation();
break;
}
}
@@ -1966,8 +1951,7 @@ void LayoutBox::EnsureIsReadyForPaintInvalidation() {
if (MayNeedPaintInvalidationAnimatedBackgroundImage() &&
!BackgroundIsKnownToBeObscured()) {
- SetShouldDoFullPaintInvalidationWithoutGeometryChange(
- PaintInvalidationReason::kBackground);
+ SetBackgroundNeedsFullPaintInvalidation();
SetShouldDelayFullPaintInvalidation();
}
@@ -1975,9 +1959,9 @@ void LayoutBox::EnsureIsReadyForPaintInvalidation() {
return;
// Do regular full paint invalidation if the object with delayed paint
- // invalidation is onscreen. Conservatively assume the delayed paint
- // invalidation was caused by background image change.
- SetBackgroundChangedSinceLastPaintInvalidation();
+ // invalidation is onscreen. This will clear
+ // ShouldDelayFullPaintInvalidation() flag and enable previous
+ // BackgroundNeedsFullPaintInvalidaiton() if it's set.
SetShouldDoFullPaintInvalidationWithoutGeometryChange(
FullPaintInvalidationReason());
}
@@ -3181,7 +3165,12 @@ void LayoutBox::ComputeMarginsForDirection(MarginDirection flow_direction,
DISABLE_CFI_PERF
void LayoutBox::UpdateLogicalHeight() {
- intrinsic_content_logical_height_ = ContentLogicalHeight();
+ if (!HasOverrideLogicalHeight()) {
+ // If we have an override height, our children will have sized themselves
+ // relative to our override height, which would make our intrinsic size
+ // incorrect (too big).
+ intrinsic_content_logical_height_ = ContentLogicalHeight();
+ }
LogicalExtentComputedValues computed_values;
ComputeLogicalHeight(computed_values);
@@ -3476,6 +3465,7 @@ LayoutUnit LayoutBox::ContainingBlockLogicalHeightForPercentageResolution(
LayoutBlock** out_cb,
bool* out_skipped_auto_height_containing_block) const {
LayoutBlock* cb = ContainingBlock();
+ const LayoutBlock* const real_cb = cb;
const LayoutBox* containing_block_child = this;
bool skipped_auto_height_containing_block = false;
LayoutUnit root_margin_border_padding_height;
@@ -3509,11 +3499,15 @@ LayoutUnit LayoutBox::ContainingBlockLogicalHeightForPercentageResolution(
cb->HasOverrideContainingBlockPercentageResolutionLogicalHeight()) {
available_height =
cb->OverrideContainingBlockPercentageResolutionLogicalHeight();
+ } else if (HasOverrideContainingBlockContentLogicalWidth() &&
+ IsHorizontalWritingMode() != real_cb->IsHorizontalWritingMode()) {
+ available_height = OverrideContainingBlockContentLogicalWidth();
+ } else if (HasOverrideContainingBlockContentLogicalHeight() &&
+ IsHorizontalWritingMode() == real_cb->IsHorizontalWritingMode()) {
+ available_height = OverrideContainingBlockContentLogicalHeight();
} else if (IsHorizontalWritingMode() != cb->IsHorizontalWritingMode()) {
available_height =
containing_block_child->ContainingBlockLogicalWidthForContent();
- } else if (HasOverrideContainingBlockContentLogicalHeight()) {
- available_height = OverrideContainingBlockContentLogicalHeight();
} else if (cb->IsTableCell()) {
if (!skipped_auto_height_containing_block) {
// Table cells violate what the CSS spec says to do with heights.
@@ -3765,21 +3759,6 @@ LayoutUnit LayoutBox::ComputeReplacedLogicalHeightUsing(
}
}
- if (cb->IsOutOfFlowPositioned() && cb->StyleRef().Height().IsAuto() &&
- !(cb->StyleRef().Top().IsAuto() ||
- cb->StyleRef().Bottom().IsAuto())) {
- SECURITY_DCHECK(cb->IsLayoutBlock());
- LayoutBlock* block = ToLayoutBlock(cb);
- LogicalExtentComputedValues computed_values;
- block->ComputeLogicalHeight(block->LogicalHeight(), LayoutUnit(),
- computed_values);
- LayoutUnit new_content_height = computed_values.extent_ -
- block->BorderAndPaddingLogicalHeight() -
- block->ScrollbarLogicalHeight();
- return AdjustContentBoxLogicalHeightForBoxSizing(
- ValueForLength(logical_height, new_content_height));
- }
-
LayoutUnit available_height;
if (IsOutOfFlowPositioned()) {
available_height = ContainingBlockLogicalHeightForPositioned(
@@ -3975,12 +3954,20 @@ LayoutUnit LayoutBox::ContainingBlockLogicalWidthForPositioned(
if (HasOverrideContainingBlockContentLogicalWidth())
return OverrideContainingBlockContentLogicalWidth();
- // Ensure we compute our width based on the width of our rel-pos inline
- // container rather than any anonymous block created to manage a block-flow
- // ancestor of ours in the rel-pos inline's inline flow.
if (containing_block->IsAnonymousBlock() &&
containing_block->IsRelPositioned()) {
+ // Ensure we compute our width based on the width of our rel-pos inline
+ // container rather than any anonymous block created to manage a block-flow
+ // ancestor of ours in the rel-pos inline's inline flow.
containing_block = ToLayoutBox(containing_block)->Continuation();
+ // There may be nested parallel inline continuations. We have now found the
+ // innermost inline (which may not be relatively positioned). Locate the
+ // inline that serves as the containing block of this box.
+ while (!containing_block->CanContainOutOfFlowPositionedElement(
+ StyleRef().GetPosition())) {
+ containing_block = ToLayoutBoxModelObject(containing_block->Container());
+ DCHECK(containing_block->IsLayoutInline());
+ }
} else if (containing_block->IsBox()) {
return std::max(LayoutUnit(),
ToLayoutBox(containing_block)->ClientLogicalWidth());
@@ -4046,11 +4033,8 @@ LayoutUnit LayoutBox::ContainingBlockLogicalHeightForPositioned(
StyleRef().GetPosition()));
const LayoutInline* flow = ToLayoutInline(containing_block);
- InlineFlowBox* first = flow->FirstLineBox();
- InlineFlowBox* last = flow->LastLineBox();
-
// If the containing block is empty, return a height of 0.
- if (!first || !last)
+ if (flow->IsEmpty())
return LayoutUnit();
LayoutUnit height_result;
@@ -5667,7 +5651,7 @@ static void MarkBoxForRelayoutAfterSplit(LayoutBox* box) {
}
box->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAnonymousBlockChange);
+ layout_invalidation_reason::kAnonymousBlockChange);
}
static void CollapseLoneAnonymousBlockChild(LayoutBox* parent,
@@ -5785,129 +5769,6 @@ void LayoutBox::LogicalExtentAfterUpdatingLogicalWidth(
SetMarginRight(old_margin_right);
}
-bool LayoutBox::MustInvalidateFillLayersPaintOnHeightChange(
- const FillLayer& layer) {
- // Nobody will use multiple layers without wanting fancy positioning.
- if (layer.Next())
- return true;
-
- // Make sure we have a valid image.
- StyleImage* img = layer.GetImage();
- if (!img || !img->CanRender())
- return false;
-
- if (layer.RepeatY() != EFillRepeat::kRepeatFill &&
- layer.RepeatY() != EFillRepeat::kNoRepeatFill)
- return true;
-
- // TODO(alancutter): Make this work correctly for calc lengths.
- if (layer.PositionY().IsPercentOrCalc() && !layer.PositionY().IsZero())
- return true;
-
- if (layer.BackgroundYOrigin() != BackgroundEdgeOrigin::kTop)
- return true;
-
- EFillSizeType size_type = layer.SizeType();
-
- if (size_type == EFillSizeType::kContain ||
- size_type == EFillSizeType::kCover)
- return true;
-
- if (size_type == EFillSizeType::kSizeLength) {
- // TODO(alancutter): Make this work correctly for calc lengths.
- if (layer.SizeLength().Height().IsPercentOrCalc() &&
- !layer.SizeLength().Height().IsZero())
- return true;
- if (img->IsGeneratedImage() && layer.SizeLength().Height().IsAuto())
- return true;
- } else if (img->UsesImageContainerSize()) {
- return true;
- }
-
- return false;
-}
-
-bool LayoutBox::MustInvalidateFillLayersPaintOnWidthChange(
- const FillLayer& layer) {
- // Nobody will use multiple layers without wanting fancy positioning.
- if (layer.Next())
- return true;
-
- // Make sure we have a valid image.
- StyleImage* img = layer.GetImage();
- if (!img || !img->CanRender())
- return false;
-
- if (layer.RepeatX() != EFillRepeat::kRepeatFill &&
- layer.RepeatX() != EFillRepeat::kNoRepeatFill)
- return true;
-
- // TODO(alancutter): Make this work correctly for calc lengths.
- if (layer.PositionX().IsPercentOrCalc() && !layer.PositionX().IsZero())
- return true;
-
- if (layer.BackgroundXOrigin() != BackgroundEdgeOrigin::kLeft)
- return true;
-
- EFillSizeType size_type = layer.SizeType();
-
- if (size_type == EFillSizeType::kContain ||
- size_type == EFillSizeType::kCover)
- return true;
-
- if (size_type == EFillSizeType::kSizeLength) {
- // TODO(alancutter): Make this work correctly for calc lengths.
- if (layer.SizeLength().Width().IsPercentOrCalc() &&
- !layer.SizeLength().Width().IsZero())
- return true;
- if (img->IsGeneratedImage() && layer.SizeLength().Width().IsAuto())
- return true;
- } else if (img->UsesImageContainerSize()) {
- return true;
- }
-
- return false;
-}
-
-bool LayoutBox::MustInvalidateBackgroundOrBorderPaintOnWidthChange() const {
- if (HasMask() &&
- MustInvalidateFillLayersPaintOnWidthChange(StyleRef().MaskLayers()))
- return true;
-
- // If we don't have a background/border/mask, then nothing to do.
- if (!HasBoxDecorationBackground())
- return false;
-
- if (MustInvalidateFillLayersPaintOnWidthChange(StyleRef().BackgroundLayers()))
- return true;
-
- // Our fill layers are ok. Let's check border.
- if (StyleRef().CanRenderBorderImage())
- return true;
-
- return false;
-}
-
-bool LayoutBox::MustInvalidateBackgroundOrBorderPaintOnHeightChange() const {
- if (HasMask() &&
- MustInvalidateFillLayersPaintOnHeightChange(StyleRef().MaskLayers()))
- return true;
-
- // If we don't have a background/border/mask, then nothing to do.
- if (!HasBoxDecorationBackground())
- return false;
-
- if (MustInvalidateFillLayersPaintOnHeightChange(
- StyleRef().BackgroundLayers()))
- return true;
-
- // Our fill layers are ok. Let's check border.
- if (StyleRef().CanRenderBorderImage())
- return true;
-
- return false;
-}
-
ShapeOutsideInfo* LayoutBox::GetShapeOutsideInfo() const {
return ShapeOutsideInfo::IsEnabledFor(*this) ? ShapeOutsideInfo::Info(*this)
: nullptr;
@@ -6132,10 +5993,6 @@ void LayoutBox::ClearCustomLayoutChild() {
rare_data_->layout_child_ = nullptr;
}
-void LayoutBox::SetPendingOffsetToScroll(LayoutSize offset) {
- EnsureRareData().pending_offset_to_scroll_ = offset;
-}
-
LayoutRect LayoutBox::DebugRect() const {
LayoutRect rect = FrameRect();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_box.h b/chromium/third_party/blink/renderer/core/layout/layout_box.h
index ed52e8671d3..9334ec858b3 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box.h
@@ -118,13 +118,6 @@ struct LayoutBoxRareData {
LayoutRect previous_physical_content_box_rect_;
LayoutRect previous_physical_layout_overflow_rect_;
- // Used by LocalFrameView::ScrollIntoView. When the scroll is sequenced
- // rather than instantly performed, we need the pending_offset_to_scroll
- // to calculate the next rect_to_scroll as if the scroll has been performed.
- // TODO(sunyunjia): We should get rid of this variable and move the next
- // rect_to_scroll calculation into ScrollRectToVisible. crbug.com/741830
- LayoutSize pending_offset_to_scroll_;
-
// Used by CSSLayoutDefinition::Instance::Layout. Represents the script
// object for this box that web developers can query style, and perform
// layout upon. Only created if IsCustomItem() is true.
@@ -295,7 +288,7 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
LayoutUnit ConstrainLogicalWidthByMinMax(LayoutUnit,
LayoutUnit,
- LayoutBlock*) const;
+ const LayoutBlock*) const;
LayoutUnit ConstrainLogicalHeightByMinMax(
LayoutUnit logical_height,
LayoutUnit intrinsic_content_height) const;
@@ -845,11 +838,6 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
}
void SetOffsetToNextPage(LayoutUnit);
- LayoutSize PendingOffsetToScroll() const {
- return rare_data_ ? rare_data_->pending_offset_to_scroll_ : LayoutSize();
- }
- void SetPendingOffsetToScroll(LayoutSize);
-
// Specify which page or column to associate with an offset, if said offset is
// exactly at a page or column boundary.
enum PageBoundaryRule { kAssociateWithFormerPage, kAssociateWithLatterPage };
@@ -1436,12 +1424,6 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
bool HitTestClippedOutByBorder(const HitTestLocation& location_in_container,
const LayoutPoint& border_box_location) const;
- static bool MustInvalidateFillLayersPaintOnWidthChange(const FillLayer&);
- static bool MustInvalidateFillLayersPaintOnHeightChange(const FillLayer&);
-
- bool MustInvalidateBackgroundOrBorderPaintOnHeightChange() const;
- bool MustInvalidateBackgroundOrBorderPaintOnWidthChange() const;
-
// Returns true if the box intersects the viewport visible to the user.
bool IntersectsVisibleViewport() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.cc b/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.cc
index 1128e3f3cf1..f1c2dfea9dd 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.cc
@@ -25,6 +25,7 @@
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/html/html_body_element.h"
@@ -39,7 +40,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/shadow_list.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/scroll/main_thread_scrolling_reason.h"
#include "third_party/blink/renderer/platform/transforms/transform_state.h"
@@ -97,18 +98,30 @@ bool LayoutBoxModelObject::UsesCompositedScrolling() const {
}
BackgroundPaintLocation LayoutBoxModelObject::GetBackgroundPaintLocation(
- uint32_t* reasons) const {
- bool has_custom_scrollbars = false;
+ uint32_t* main_thread_scrolling_reasons) const {
+ bool may_have_scrolling_layers_without_scrolling = IsLayoutView();
+ const auto* scrollable_area = GetScrollableArea();
+ bool scrolls_overflow = scrollable_area && scrollable_area->ScrollsOverflow();
+ if (!scrolls_overflow && !may_have_scrolling_layers_without_scrolling)
+ return kBackgroundPaintInGraphicsLayer;
+
+ // If we care about LCD text, paint root backgrounds into scrolling contents
+ // layer even if style suggests otherwise. (For non-root scrollers, we just
+ // avoid compositing - see PLSA::ComputeNeedsCompositedScrolling.)
+ if (IsLayoutView()) {
+ DCHECK(Layer()->Compositor());
+ if (!Layer()->Compositor()->PreferCompositingToLCDTextEnabled())
+ return kBackgroundPaintInScrollingContents;
+ }
+
// TODO(flackr): Detect opaque custom scrollbars which would cover up a
// border-box background.
- if (PaintLayerScrollableArea* scrollable_area = GetScrollableArea()) {
- if ((scrollable_area->HorizontalScrollbar() &&
- scrollable_area->HorizontalScrollbar()->IsCustomScrollbar()) ||
- (scrollable_area->VerticalScrollbar() &&
- scrollable_area->VerticalScrollbar()->IsCustomScrollbar())) {
- has_custom_scrollbars = true;
- }
- }
+ bool has_custom_scrollbars =
+ scrollable_area &&
+ ((scrollable_area->HorizontalScrollbar() &&
+ scrollable_area->HorizontalScrollbar()->IsCustomScrollbar()) ||
+ (scrollable_area->VerticalScrollbar() &&
+ scrollable_area->VerticalScrollbar()->IsCustomScrollbar()));
// TODO(flackr): When we correctly clip the scrolling contents layer we can
// paint locally equivalent backgrounds into it. https://crbug.com/645957
@@ -119,8 +132,10 @@ BackgroundPaintLocation LayoutBoxModelObject::GetBackgroundPaintLocation(
// painting into the composited scrolling contents layer.
// https://crbug.com/646464
if (StyleRef().BoxShadow()) {
- if (reasons)
- *reasons |= MainThreadScrollingReason::kHasBoxShadowFromNonRootLayer;
+ if (main_thread_scrolling_reasons) {
+ *main_thread_scrolling_reasons |=
+ MainThreadScrollingReason::kHasBoxShadowFromNonRootLayer;
+ }
return kBackgroundPaintInGraphicsLayer;
}
@@ -144,13 +159,17 @@ BackgroundPaintLocation LayoutBoxModelObject::GetBackgroundPaintLocation(
if (clip == EFillBox::kBorder) {
if (!has_custom_scrollbars &&
(StyleRef().BorderTopWidth() == 0 ||
- !ResolveColor(GetCSSPropertyBorderTopColor()).HasAlpha()) &&
+ (!ResolveColor(GetCSSPropertyBorderTopColor()).HasAlpha() &&
+ StyleRef().BorderTopStyle() == EBorderStyle::kSolid)) &&
(StyleRef().BorderLeftWidth() == 0 ||
- !ResolveColor(GetCSSPropertyBorderLeftColor()).HasAlpha()) &&
+ (!ResolveColor(GetCSSPropertyBorderLeftColor()).HasAlpha() &&
+ StyleRef().BorderLeftStyle() == EBorderStyle::kSolid)) &&
(StyleRef().BorderRightWidth() == 0 ||
- !ResolveColor(GetCSSPropertyBorderRightColor()).HasAlpha()) &&
+ (!ResolveColor(GetCSSPropertyBorderRightColor()).HasAlpha() &&
+ StyleRef().BorderRightStyle() == EBorderStyle::kSolid)) &&
(StyleRef().BorderBottomWidth() == 0 ||
- !ResolveColor(GetCSSPropertyBorderBottomColor()).HasAlpha())) {
+ (!ResolveColor(GetCSSPropertyBorderBottomColor()).HasAlpha() &&
+ StyleRef().BorderBottomStyle() == EBorderStyle::kSolid))) {
continue;
}
// If we have an opaque background color only, we can safely paint it
@@ -268,7 +287,7 @@ void LayoutBoxModelObject::StyleDidChange(StyleDifference diff,
(StyleRef().OriginalDisplay() == EDisplay::kInlineBlock)) &&
((old_style->OriginalDisplay() == EDisplay::kBlock) ||
(old_style->OriginalDisplay() == EDisplay::kInlineBlock)))
- Parent()->SetNeedsLayout(LayoutInvalidationReason::kChildChanged,
+ Parent()->SetNeedsLayout(layout_invalidation_reason::kChildChanged,
kMarkContainerChain);
PaintLayerType type = LayerTypeRequired();
@@ -298,7 +317,7 @@ void LayoutBoxModelObject::StyleDidChange(StyleDifference diff,
SetChildNeedsLayout();
if (had_transform_related_property) {
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
}
if (!NeedsLayout()) {
// FIXME: We should call a specialized version of this function.
@@ -349,22 +368,21 @@ void LayoutBoxModelObject::StyleDidChange(StyleDifference diff,
}
// The used style for body background may change due to computed style change
- // on the document element because of background stealing.
- // Refer to backgroundStolenForBeingBody() and
- // http://www.w3.org/TR/css3-background/#body-background for more info.
+ // on the document element because of change of BackgroundTransfersToView()
+ // which depends on the document element style.
if (IsDocumentElement()) {
- HTMLBodyElement* body = GetDocument().FirstBodyElement();
- LayoutObject* body_layout = body ? body->GetLayoutObject() : nullptr;
- if (body_layout && body_layout->IsBoxModelObject()) {
- bool new_stole_body_background =
- ToLayoutBoxModelObject(body_layout)
- ->BackgroundStolenForBeingBody(Style());
- bool old_stole_body_background =
- old_style && ToLayoutBoxModelObject(body_layout)
- ->BackgroundStolenForBeingBody(old_style);
- if (new_stole_body_background != old_stole_body_background &&
- body_layout->Style() && body_layout->StyleRef().HasBackground()) {
- body_layout->SetShouldDoFullPaintInvalidation();
+ if (HTMLBodyElement* body = GetDocument().FirstBodyElement()) {
+ if (auto* body_object = body->GetLayoutObject()) {
+ if (body_object->IsBoxModelObject()) {
+ auto* body_box_model = ToLayoutBoxModelObject(body_object);
+ bool new_body_background_transfers =
+ body_box_model->BackgroundTransfersToView(Style());
+ bool old_body_background_transfers =
+ old_style && body_box_model->BackgroundTransfersToView(old_style);
+ if (new_body_background_transfers != old_body_background_transfers &&
+ body_object->Style() && body_object->StyleRef().HasBackground())
+ body_object->SetBackgroundNeedsFullPaintInvalidation();
+ }
}
}
}
@@ -1453,22 +1471,28 @@ void LayoutBoxModelObject::MoveChildrenTo(
}
}
-bool LayoutBoxModelObject::BackgroundStolenForBeingBody(
- const ComputedStyle* root_element_style) const {
+bool LayoutBoxModelObject::BackgroundTransfersToView(
+ const ComputedStyle* document_element_style) const {
+ // In our painter implementation, ViewPainter instead of the painter of the
+ // layout object of the document element paints the view background.
+ if (IsDocumentElement())
+ return true;
+
// http://www.w3.org/TR/css3-background/#body-background
- // If the root element is <html> with no background, and a <body> child
- // element exists, the root element steals the first <body> child element's
- // background.
+ // If the document element is <html> with no background, and a <body> child
+ // element exists, the <body> element's background transfers to the document
+ // element which in turn transfers to the view in our painter implementation.
if (!IsBody())
return false;
- Element* root_element = GetDocument().documentElement();
- if (!IsHTMLHtmlElement(root_element))
+ Element* document_element = GetDocument().documentElement();
+ if (!IsHTMLHtmlElement(document_element))
return false;
- if (!root_element_style)
- root_element_style = root_element->EnsureComputedStyle();
- if (root_element_style->HasBackground())
+ if (!document_element_style)
+ document_element_style = document_element->GetComputedStyle();
+ DCHECK(document_element_style);
+ if (document_element_style->HasBackground())
return false;
if (GetNode() != GetDocument().FirstBodyElement())
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.h b/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.h
index f28bfbc94a9..6b383419fd8 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box_model_object.h
@@ -188,7 +188,12 @@ class CORE_EXPORT LayoutBoxModelObject : public LayoutObject {
// Returns which layers backgrounds should be painted into for overflow
// scrolling boxes.
- BackgroundPaintLocation GetBackgroundPaintLocation(uint32_t* reasons) const;
+ // TODO(yigu): PaintLayerScrollableArea::ComputeNeedsCompositedScrolling
+ // calls this method to obtain main thread scrolling reasons due to
+ // background paint location. Once the cases get handled on compositor the
+ // parameter "reasons" could be removed.
+ BackgroundPaintLocation GetBackgroundPaintLocation(
+ uint32_t* main_thread_scrolling_reasons = nullptr) const;
// These return the CSS computed padding values.
LayoutUnit ComputedCSSPaddingTop() const {
@@ -425,12 +430,16 @@ class CORE_EXPORT LayoutBoxModelObject : public LayoutObject {
return false;
}
- // http://www.w3.org/TR/css3-background/#body-background
- // <html> root element with no background steals background from its first
- // <body> child. The used background for such body element should be the
- // initial value. (i.e. transparent)
- bool BackgroundStolenForBeingBody(
- const ComputedStyle* root_element_style = nullptr) const;
+ // This object's background is transferred to its LayoutView if:
+ // 1. it's the document element, or
+ // 2. it's the first <body> if the document element is <html> and doesn't have
+ // a background. http://www.w3.org/TR/css3-background/#body-background
+ // If it's the case, the used background should be the initial value (i.e.
+ // transparent). The first condition is actually an implementation detail
+ // because we paint the view background in ViewPainter instead of the painter
+ // of the layout object of the document element.
+ bool BackgroundTransfersToView(
+ const ComputedStyle* document_element_style = nullptr) const;
void AbsoluteQuads(Vector<FloatQuad>& quads,
MapCoordinatesFlags mode = 0) const override;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_box_model_object_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_box_model_object_test.cc
index 1054c045c7b..a92e8df53c0 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box_model_object_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box_model_object_test.cc
@@ -432,7 +432,7 @@ TEST_F(LayoutBoxModelObjectTest, StickyPositionConstraintInvalidation) {
EXPECT_TRUE(sticky->Layer()->NeedsCompositingInputsUpdate());
// After updating compositing inputs we should have the updated position.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50.f, scrollable_area->GetStickyConstraintsMap()
.at(sticky->Layer())
.scroll_container_relative_sticky_box_rect.Location()
@@ -1089,7 +1089,7 @@ TEST_F(LayoutBoxModelObjectTest, InvalidatePaintLayerOnStackedChange) {
EXPECT_FALSE(parent->StyleRef().IsStacked());
EXPECT_NE(parent, original_compositing_container->GetLayoutObject());
- target_element->setAttribute(HTMLNames::classAttr, "non-stacked");
+ target_element->setAttribute(html_names::kClassAttr, "non-stacked");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_FALSE(target->StyleRef().IsStacked());
@@ -1098,8 +1098,8 @@ TEST_F(LayoutBoxModelObjectTest, InvalidatePaintLayerOnStackedChange) {
auto* new_compositing_container = target->Layer()->CompositingContainer();
EXPECT_EQ(parent, new_compositing_container->GetLayoutObject());
- GetDocument().View()->UpdateAllLifecyclePhases();
- target_element->setAttribute(HTMLNames::classAttr, "stacked");
+ UpdateAllLifecyclePhasesForTest();
+ target_element->setAttribute(html_names::kClassAttr, "stacked");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_TRUE(target->StyleRef().IsStacked());
@@ -1141,7 +1141,7 @@ TEST_F(LayoutBoxModelObjectTest, StickyRemovedFromRootScrollableArea) {
// overflow layer to nullptr.
ToElement(scroller->GetNode())
->SetInlineStyleProperty(CSSPropertyOverflow, "scroll");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The sticky element should no longer be viewport constrained.
EXPECT_FALSE(GetDocument().View()->HasViewportConstrainedObjects());
@@ -1169,17 +1169,17 @@ TEST_F(LayoutBoxModelObjectTest, BackfaceVisibilityChange) {
ASSERT_NE(nullptr, target_layer);
EXPECT_FALSE(target_layer->NeedsRepaint());
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
base_style + "; backface-visibility: hidden");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(target_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(target_layer->NeedsRepaint());
- target->setAttribute(HTMLNames::styleAttr, base_style);
+ target->setAttribute(html_names::kStyleAttr, base_style);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(target_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(target_layer->NeedsRepaint());
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_button.cc b/chromium/third_party/blink/renderer/core/layout/layout_button.cc
index b5c23c5fc24..0ff22292a4c 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_button.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_button.cc
@@ -22,8 +22,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutButton::LayoutButton(Element* element)
: LayoutFlexibleBox(element), inner_(nullptr) {}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_counter.cc b/chromium/third_party/blink/renderer/core/layout/layout_counter.cc
index 23603688411..c47492d4c3d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_counter.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_counter.cc
@@ -30,7 +30,6 @@
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/html/html_olist_element.h"
#include "third_party/blink/renderer/core/html/list_item_ordinal.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/counter_node.h"
#include "third_party/blink/renderer/core/layout/layout_list_item.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -44,8 +43,6 @@
namespace blink {
-using namespace HTMLNames;
-
typedef HashMap<AtomicString, scoped_refptr<CounterNode>> CounterMap;
typedef HashMap<const LayoutObject*, std::unique_ptr<CounterMap>> CounterMaps;
@@ -158,7 +155,7 @@ static bool PlanCounter(LayoutObject& object,
switch (style.StyleType()) {
case kPseudoIdNone:
// Sometimes nodes have more than one layout object. Only the first one
- // gets the counter. See LayoutTests/http/tests/css/counter-crash.html
+ // gets the counter. See web_tests/http/tests/css/counter-crash.html
if (generating_node->GetLayoutObject() != &object)
return false;
break;
@@ -524,7 +521,7 @@ void LayoutCounter::Invalidate() {
if (DocumentBeingDestroyed())
return;
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kCountersChanged);
+ layout_invalidation_reason::kCountersChanged);
}
static void DestroyCounterNodeWithoutMapRemoval(const AtomicString& identifier,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_details_marker.cc b/chromium/third_party/blink/renderer/core/layout/layout_details_marker.cc
index 16f354effd5..857827e6aa3 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_details_marker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_details_marker.cc
@@ -27,7 +27,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
LayoutDetailsMarker::LayoutDetailsMarker(Element* element)
: LayoutBlockFlow(element) {}
@@ -65,7 +65,7 @@ bool LayoutDetailsMarker::IsOpen() const {
continue;
if (IsHTMLDetailsElement(*layout_object->GetNode()))
return !ToElement(layout_object->GetNode())
- ->getAttribute(openAttr)
+ ->getAttribute(kOpenAttr)
.IsNull();
if (IsHTMLInputElement(*layout_object->GetNode()))
return true;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_embedded_object.cc b/chromium/third_party/blink/renderer/core/layout/layout_embedded_object.cc
index 58387dc7a89..2cdbd8328f9 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_embedded_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_embedded_object.cc
@@ -29,7 +29,6 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/html/html_plugin_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/intrinsic_sizing_info.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -39,8 +38,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutEmbeddedObject::LayoutEmbeddedObject(Element* element)
: LayoutEmbeddedContent(element) {
View()->GetFrameView()->SetIsVisuallyNonEmpty();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_fieldset.cc b/chromium/third_party/blink/renderer/core/layout/layout_fieldset.cc
index 9209773bacb..e5b45b1b73f 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_fieldset.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_fieldset.cc
@@ -23,16 +23,13 @@
#include "third_party/blink/renderer/core/layout/layout_fieldset.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/html/forms/html_legend_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/paint/fieldset_painter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
-using namespace HTMLNames;
-
LayoutFieldset::LayoutFieldset(Element* element) : LayoutBlockFlow(element) {}
void LayoutFieldset::ComputePreferredLogicalWidths() {
@@ -65,9 +62,10 @@ LayoutObject* LayoutFieldset::LayoutSpecialExcludedChild(bool relayout_children,
if (legend) {
LayoutRect old_legend_frame_rect = legend->FrameRect();
- if (relayout_children)
+ if (relayout_children) {
legend->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kFieldsetChanged);
+ layout_invalidation_reason::kFieldsetChanged);
+ }
legend->LayoutIfNeeded();
LayoutUnit logical_left;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.cc b/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.cc
index c0bc37891ee..d8f5e03ae33 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.cc
@@ -25,7 +25,6 @@
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/fileapi/file_list.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/paint/file_upload_control_painter.h"
@@ -35,8 +34,6 @@
namespace blink {
-using namespace HTMLNames;
-
const int kDefaultWidthNumChars = 34;
const int kButtonShadowHeight = 2;
@@ -48,7 +45,7 @@ LayoutFileUploadControl::~LayoutFileUploadControl() = default;
void LayoutFileUploadControl::UpdateFromElement() {
HTMLInputElement* input = ToHTMLInputElement(GetNode());
- DCHECK_EQ(input->type(), InputTypeNames::file);
+ DCHECK_EQ(input->type(), input_type_names::kFile);
if (HTMLInputElement* button = UploadButton()) {
bool new_can_receive_dropped_files_state = input->CanReceiveDroppedFiles();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.cc b/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.cc
index 6fdc8c13018..8b3de628017 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.cc
@@ -44,7 +44,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -202,12 +202,12 @@ LayoutUnit LayoutFlexibleBox::FirstLineBoxBaseline() const {
if (!baseline_child)
return LayoutUnit(-1);
- if (!IsColumnFlow() && HasOrthogonalFlow(*baseline_child)) {
+ if (!IsColumnFlow() && !MainAxisIsInlineAxis(*baseline_child)) {
// TODO(cbiesinger): Should LogicalTop here be LogicalLeft?
return CrossAxisExtentForChild(*baseline_child) +
baseline_child->LogicalTop();
}
- if (IsColumnFlow() && !HasOrthogonalFlow(*baseline_child)) {
+ if (IsColumnFlow() && MainAxisIsInlineAxis(*baseline_child)) {
return MainAxisExtentForChild(*baseline_child) +
baseline_child->LogicalTop();
}
@@ -379,6 +379,13 @@ void LayoutFlexibleBox::RepositionLogicalHeightDependentFlexItems(
LayoutUnit cross_axis_start_edge = line_contexts.IsEmpty()
? LayoutUnit()
: line_contexts[0].cross_axis_offset;
+ // If we have a single line flexbox, the line height is all the available
+ // space. For flex-direction: row, this means we need to use the height, so
+ // we do this after calling updateLogicalHeight.
+ if (!IsMultiline() && !line_contexts.IsEmpty()) {
+ line_contexts[0].cross_axis_extent = CrossAxisContentExtent();
+ }
+
AlignFlexLines(line_contexts);
AlignChildren(line_contexts);
@@ -408,8 +415,14 @@ LayoutUnit LayoutFlexibleBox::ClientLogicalBottomAfterRepositioning() {
max_child_logical_bottom + PaddingAfter());
}
-bool LayoutFlexibleBox::HasOrthogonalFlow(const LayoutBox& child) const {
- return IsHorizontalFlow() != child.IsHorizontalWritingMode();
+bool LayoutFlexibleBox::MainAxisIsInlineAxis(const LayoutBox& child) const {
+ // If we have a horizontal flow, that means the main size is the width.
+ // That's the inline size for horizontal writing modes, and the block
+ // size in vertical writing modes. For a vertical flow, main size is the
+ // height, so it's the inverse. So we need the inline size if we have a
+ // horizontal flow and horizontal writing mode, or vertical flow and vertical
+ // writing mode. Otherwise we need the block size.
+ return IsHorizontalFlow() == child.IsHorizontalWritingMode();
}
bool LayoutFlexibleBox::IsColumnFlow() const {
@@ -452,7 +465,7 @@ LayoutUnit LayoutFlexibleBox::CrossAxisExtentForChild(
LayoutUnit LayoutFlexibleBox::ChildIntrinsicLogicalHeight(
const LayoutBox& child) const {
// This should only be called if the logical height is the cross size
- DCHECK(!HasOrthogonalFlow(child));
+ DCHECK(MainAxisIsInlineAxis(child));
if (NeedToStretchChildLogicalHeight(child)) {
LayoutUnit child_intrinsic_content_logical_height;
if (!child.ShouldApplySizeContainment()) {
@@ -472,19 +485,22 @@ DISABLE_CFI_PERF
LayoutUnit LayoutFlexibleBox::ChildIntrinsicLogicalWidth(
const LayoutBox& child) const {
// This should only be called if the logical width is the cross size
- DCHECK(HasOrthogonalFlow(child));
+ DCHECK(!MainAxisIsInlineAxis(child));
// If our height is auto, make sure that our returned height is unaffected by
- // earlier layouts by returning the max preferred logical width
- if (!CrossAxisLengthIsDefinite(child, child.StyleRef().LogicalWidth()))
- return child.MaxPreferredLogicalWidth();
+ // earlier layouts by returning the shrink-to-fit size.
+ if (!CrossAxisLengthIsDefinite(child, child.StyleRef().LogicalWidth())) {
+ MinMaxSize sizes{child.MinPreferredLogicalWidth(),
+ child.MaxPreferredLogicalWidth()};
+ return sizes.ShrinkToFit(ContentLogicalWidth());
+ }
return child.LogicalWidth();
}
LayoutUnit LayoutFlexibleBox::CrossAxisIntrinsicExtentForChild(
const LayoutBox& child) const {
- return HasOrthogonalFlow(child) ? ChildIntrinsicLogicalWidth(child)
- : ChildIntrinsicLogicalHeight(child);
+ return MainAxisIsInlineAxis(child) ? ChildIntrinsicLogicalHeight(child)
+ : ChildIntrinsicLogicalWidth(child);
}
LayoutUnit LayoutFlexibleBox::MainAxisExtentForChild(
@@ -529,13 +545,7 @@ LayoutUnit LayoutFlexibleBox::ComputeMainAxisExtentForChild(
const LayoutBox& child,
SizeType size_type,
const Length& size) const {
- // If we have a horizontal flow, that means the main size is the width.
- // That's the logical width for horizontal writing modes, and the logical
- // height in vertical writing modes. For a vertical flow, main size is the
- // height, so it's the inverse. So we need the logical width if we have a
- // horizontal flow and horizontal writing mode, or vertical flow and vertical
- // writing mode. Otherwise we need the logical height.
- if (IsHorizontalFlow() != child.StyleRef().IsHorizontalWritingMode()) {
+ if (!MainAxisIsInlineAxis(child)) {
// We don't have to check for "auto" here - computeContentLogicalHeight
// will just return -1 for that case anyway. It's safe to access
// scrollbarLogicalHeight here because ComputeNextFlexLine will have
@@ -654,10 +664,10 @@ LayoutUnit LayoutFlexibleBox::ComputeMainSizeFromAspectRatioUsing(
cross_size = LayoutUnit(cross_size_length.Value());
} else {
DCHECK(cross_size_length.IsPercentOrCalc());
- cross_size = HasOrthogonalFlow(child)
- ? AdjustBorderBoxLogicalWidthForBoxSizing(
- ValueForLength(cross_size_length, ContentWidth()))
- : child.ComputePercentageLogicalHeight(cross_size_length);
+ cross_size = MainAxisIsInlineAxis(child)
+ ? child.ComputePercentageLogicalHeight(cross_size_length)
+ : AdjustBorderBoxLogicalWidthForBoxSizing(
+ ValueForLength(cross_size_length, ContentWidth()));
}
const LayoutSize& child_intrinsic_size = child.IntrinsicSize();
@@ -705,7 +715,7 @@ bool LayoutFlexibleBox::CrossAxisLengthIsDefinite(const LayoutBox& child,
if (length.IsAuto())
return false;
if (length.IsPercentOrCalc()) {
- if (HasOrthogonalFlow(child) ||
+ if (!MainAxisIsInlineAxis(child) ||
has_definite_height_ == SizeDefiniteness::kDefinite)
return true;
if (has_definite_height_ == SizeDefiniteness::kIndefinite)
@@ -723,10 +733,10 @@ bool LayoutFlexibleBox::CrossAxisLengthIsDefinite(const LayoutBox& child,
void LayoutFlexibleBox::CacheChildMainSize(const LayoutBox& child) {
DCHECK(!child.NeedsLayout());
LayoutUnit main_size;
- if (HasOrthogonalFlow(child))
- main_size = child.LogicalHeight();
- else
+ if (MainAxisIsInlineAxis(child))
main_size = child.MaxPreferredLogicalWidth();
+ else
+ main_size = child.LogicalHeight();
intrinsic_size_along_main_axis_.Set(&child, main_size);
relaid_out_children_.insert(&child);
}
@@ -784,7 +794,11 @@ LayoutUnit LayoutFlexibleBox::ComputeInnerFlexBaseSizeForChild(
// width of the child. For the logical width axis we just use the preferred
// width; for the height we need to lay out the child.
LayoutUnit main_axis_extent;
- if (HasOrthogonalFlow(child)) {
+ if (MainAxisIsInlineAxis(child)) {
+ // We don't need to add scrollbarLogicalWidth here because the preferred
+ // width includes the scrollbar, even for overflow: auto.
+ main_axis_extent = child.MaxPreferredLogicalWidth();
+ } else {
if (child_layout_type == kNeverLayout)
return LayoutUnit();
@@ -796,10 +810,6 @@ LayoutUnit LayoutFlexibleBox::ComputeInnerFlexBaseSizeForChild(
CacheChildMainSize(child);
}
main_axis_extent = intrinsic_size_along_main_axis_.at(&child);
- } else {
- // We don't need to add scrollbarLogicalWidth here because the preferred
- // width includes the scrollbar, even for overflow: auto.
- main_axis_extent = child.MaxPreferredLogicalWidth();
}
DCHECK_GE(main_axis_extent - main_axis_border_and_padding, LayoutUnit())
<< main_axis_extent << " - " << main_axis_border_and_padding;
@@ -1046,9 +1056,9 @@ bool LayoutFlexibleBox::CrossSizeIsDefiniteForPercentageResolution(
return false;
// Here we implement https://drafts.csswg.org/css-flexbox/#algo-stretch
- if (HasOrthogonalFlow(child) && child.HasOverrideLogicalWidth())
+ if (!MainAxisIsInlineAxis(child) && child.HasOverrideLogicalWidth())
return true;
- if (!HasOrthogonalFlow(child) && child.HasOverrideLogicalHeight())
+ if (MainAxisIsInlineAxis(child) && child.HasOverrideLogicalHeight())
return true;
// We don't currently implement the optimization from
@@ -1064,27 +1074,19 @@ bool LayoutFlexibleBox::MainSizeIsDefiniteForPercentageResolution(
const LayoutBox& child) const {
// This function implements section 9.8. Definite and Indefinite Sizes, case
// 2) of the flexbox spec.
- // We need to check for the flexbox to have a definite main size, and for the
- // flex item to have a definite flex basis.
- const Length& flex_basis = FlexBasisForChild(child);
- if (!MainAxisLengthIsDefinite(child, flex_basis))
+ // We need to check for the flexbox to have a definite main size.
+ // We make up a percentage to check whether we have a definite size.
+ if (!MainAxisLengthIsDefinite(child, Length(0, kPercent)))
return false;
- if (!flex_basis.IsPercentOrCalc()) {
- // If flex basis had a percentage, our size is guaranteed to be definite or
- // the flex item's size could not be definite. Otherwise, we make up a
- // percentage to check whether we have a definite size.
- if (!MainAxisLengthIsDefinite(child, Length(0, kPercent)))
- return false;
- }
- if (HasOrthogonalFlow(child))
- return child.HasOverrideLogicalHeight();
- return child.HasOverrideLogicalWidth();
+ if (MainAxisIsInlineAxis(child))
+ return child.HasOverrideLogicalWidth();
+ return child.HasOverrideLogicalHeight();
}
bool LayoutFlexibleBox::UseOverrideLogicalHeightForPerentageResolution(
const LayoutBox& child) const {
- if (!HasOrthogonalFlow(child))
+ if (MainAxisIsInlineAxis(child))
return CrossSizeIsDefiniteForPercentageResolution(child);
return MainSizeIsDefiniteForPercentageResolution(child);
}
@@ -1195,14 +1197,27 @@ static LayoutUnit AlignmentOffset(LayoutUnit available_free_space,
}
void LayoutFlexibleBox::SetOverrideMainAxisContentSizeForChild(FlexItem& item) {
- // child_preferred_size includes scrollbar width.
- if (HasOrthogonalFlow(*item.box)) {
- item.box->SetOverrideLogicalHeight(item.FlexedBorderBoxSize());
- } else {
+ if (MainAxisIsInlineAxis(*item.box)) {
item.box->SetOverrideLogicalWidth(item.FlexedBorderBoxSize());
+ } else {
+ item.box->SetOverrideLogicalHeight(item.FlexedBorderBoxSize());
}
}
+bool LayoutFlexibleBox::ChildLogicalHeightStretchesToFlexboxSize(
+ FlexItem& item) const {
+ if (IsMultiline())
+ return false;
+ if (!NeedToStretchChildLogicalHeight(*item.box))
+ return false;
+ if (HasAutoMarginsInCrossAxis(*item.box))
+ return false;
+ if (item.box->IntrinsicContentLogicalHeight() == -1)
+ return false;
+
+ return HasDefiniteLogicalHeight();
+}
+
LayoutUnit LayoutFlexibleBox::StaticMainAxisPositionForPositionedChild(
const LayoutBox& child) {
const LayoutUnit available_space =
@@ -1350,7 +1365,7 @@ DISABLE_CFI_PERF
void LayoutFlexibleBox::LayoutLineItems(FlexLine* current_line,
bool relayout_children,
SubtreeLayoutScope& layout_scope) {
- for (size_t i = 0; i < current_line->line_items.size(); ++i) {
+ for (wtf_size_t i = 0; i < current_line->line_items.size(); ++i) {
FlexItem& flex_item = current_line->line_items[i];
LayoutBox* child = flex_item.box;
@@ -1359,6 +1374,35 @@ void LayoutFlexibleBox::LayoutLineItems(FlexLine* current_line,
child->SetShouldCheckForPaintInvalidation();
SetOverrideMainAxisContentSizeForChild(flex_item);
+
+ // We may have already forced relayout for orthogonal flowing children in
+ // computeInnerFlexBaseSizeForChild.
+ bool force_child_relayout =
+ relayout_children && !relaid_out_children_.Contains(child);
+
+ // Apply optimization 1 from section 9.8 for row flexboxes by overriding
+ // the logical height of stretchable children to the parent's definite
+ // height, if present (https://crbug.com/703512).
+ if (ChildLogicalHeightStretchesToFlexboxSize(flex_item)) {
+ LogicalExtentComputedValues computed_values;
+ ComputeLogicalHeight(computed_values);
+ LayoutUnit cross_axis_extent = computed_values.extent_;
+ DCHECK_NE(cross_axis_extent, LayoutUnit(-1));
+
+ // Compute the maximum possible cross axis extent available, since we
+ // don't optimize for intrinsically sized children.
+ LayoutUnit stretched_logical_height =
+ std::max(child->BorderAndPaddingLogicalHeight(),
+ cross_axis_extent - flex_item.CrossAxisMarginExtent());
+ LayoutUnit clamped_logical_height = child->ConstrainLogicalHeightByMinMax(
+ stretched_logical_height, child->IntrinsicContentLogicalHeight());
+
+ child->SetOverrideLogicalHeight(clamped_logical_height);
+ if (clamped_logical_height != child->LogicalHeight()) {
+ force_child_relayout = true;
+ }
+ }
+
// The flexed content size and the override size include the scrollbar
// width, so we need to compare to the size including the scrollbar.
if (flex_item.flexed_content_size !=
@@ -1369,10 +1413,6 @@ void LayoutFlexibleBox::LayoutLineItems(FlexLine* current_line,
// updateAutoMarginsInCrossAxis, we reset the margins here.
ResetAutoMarginsAndLogicalTopInCrossAxis(*child);
}
- // We may have already forced relayout for orthogonal flowing children in
- // computeInnerFlexBaseSizeForChild.
- bool force_child_relayout =
- relayout_children && !relaid_out_children_.Contains(child);
// TODO(dgrogan): Broaden the NG part of this check once NG types other
// than Mixin derivatives are cached.
if (child->IsLayoutBlock() &&
@@ -1405,7 +1445,7 @@ void LayoutFlexibleBox::LayoutLineItems(FlexLine* current_line,
void LayoutFlexibleBox::ApplyLineItemsPosition(FlexLine* current_line) {
bool is_paginated = View()->GetLayoutState()->IsPaginated();
- for (size_t i = 0; i < current_line->line_items.size(); ++i) {
+ for (wtf_size_t i = 0; i < current_line->line_items.size(); ++i) {
const FlexItem& flex_item = current_line->line_items[i];
LayoutBox* child = flex_item.box;
SetFlowAwareLocationForChild(*child, flex_item.desired_location);
@@ -1448,7 +1488,7 @@ void LayoutFlexibleBox::LayoutColumnReverse(FlexItemVectorView& children,
main_axis_offset -= FlexLayoutAlgorithm::InitialContentPositionOffset(
available_free_space, justify_content, children.size());
- for (size_t i = 0; i < children.size(); ++i) {
+ for (wtf_size_t i = 0; i < children.size(); ++i) {
FlexItem& flex_item = children[i];
LayoutBox* child = flex_item.box;
@@ -1473,37 +1513,29 @@ void LayoutFlexibleBox::LayoutColumnReverse(FlexItemVectorView& children,
void LayoutFlexibleBox::AlignFlexLines(Vector<FlexLine>& line_contexts) {
const StyleContentAlignmentData align_content =
FlexLayoutAlgorithm::ResolvedAlignContent(StyleRef());
-
- // If we have a single line flexbox or a multiline line flexbox with only one
- // flex line, the line height is all the available space. For
- // flex-direction: row, this means we need to use the height, so we do this
- // after calling updateLogicalHeight.
- if (line_contexts.size() == 1) {
- line_contexts[0].cross_axis_extent = CrossAxisContentExtent();
+ if (align_content.GetPosition() == ContentPosition::kFlexStart)
return;
+
+ if (IsMultiline() && !line_contexts.IsEmpty()) {
+ UseCounter::Count(GetDocument(),
+ WebFeature::kFlexboxSingleLineAlignContent);
}
- if (align_content.GetPosition() == ContentPosition::kFlexStart)
+ if (line_contexts.IsEmpty() || !IsMultiline())
return;
LayoutUnit available_cross_axis_space = CrossAxisContentExtent();
- for (size_t i = 0; i < line_contexts.size(); ++i)
- available_cross_axis_space -= line_contexts[i].cross_axis_extent;
+ for (const FlexLine& line : line_contexts)
+ available_cross_axis_space -= line.cross_axis_extent;
- LayoutUnit line_offset;
- if (line_contexts.size() > 1) {
- line_offset = FlexLayoutAlgorithm::InitialContentPositionOffset(
- available_cross_axis_space, align_content, line_contexts.size());
- }
+ LayoutUnit line_offset = FlexLayoutAlgorithm::InitialContentPositionOffset(
+ available_cross_axis_space, align_content, line_contexts.size());
for (unsigned line_number = 0; line_number < line_contexts.size();
++line_number) {
FlexLine& line_context = line_contexts[line_number];
line_context.cross_axis_offset += line_offset;
- for (size_t child_number = 0; child_number < line_context.line_items.size();
- ++child_number) {
- FlexItem& flex_item = line_context.line_items[child_number];
+ for (FlexItem& flex_item : line_context.line_items)
AdjustAlignmentForChild(*flex_item.box, line_offset);
- }
if (align_content.Distribution() == ContentDistributionType::kStretch &&
available_cross_axis_space > 0)
@@ -1527,43 +1559,36 @@ void LayoutFlexibleBox::AdjustAlignmentForChild(LayoutBox& child,
void LayoutFlexibleBox::AlignChildren(Vector<FlexLine>& line_contexts) {
// Keep track of the space between the baseline edge and the after edge of
// the box for each line.
+ // TODO(cbiesinger): This should be stored in FlexLine
Vector<LayoutUnit> min_margin_after_baselines;
- for (size_t line_number = 0; line_number < line_contexts.size();
- ++line_number) {
- FlexLine& line_context = line_contexts[line_number];
-
+ for (FlexLine& line_context : line_contexts) {
LayoutUnit min_margin_after_baseline = LayoutUnit::Max();
- LayoutUnit line_cross_axis_extent = line_context.cross_axis_extent;
LayoutUnit max_ascent = line_context.max_ascent;
- for (size_t child_number = 0; child_number < line_context.line_items.size();
- ++child_number) {
- FlexItem& flex_item = line_context.line_items[child_number];
+ for (FlexItem& flex_item : line_context.line_items) {
DCHECK(!flex_item.box->IsOutOfFlowPositioned());
if (UpdateAutoMarginsInCrossAxis(
*flex_item.box,
- std::max(LayoutUnit(), flex_item.AvailableAlignmentSpace(
- line_cross_axis_extent))))
+ std::max(LayoutUnit(), flex_item.AvailableAlignmentSpace())))
continue;
ItemPosition position = flex_item.Alignment();
if (position == ItemPosition::kStretch) {
- ComputeStretchedSizeForChild(flex_item, line_cross_axis_extent);
+ flex_item.ComputeStretchedSize();
ApplyStretchAlignmentToChild(flex_item);
}
- LayoutUnit available_space =
- flex_item.AvailableAlignmentSpace(line_cross_axis_extent);
+ LayoutUnit available_space = flex_item.AvailableAlignmentSpace();
LayoutUnit offset = AlignmentOffset(
available_space, position, flex_item.MarginBoxAscent(), max_ascent,
StyleRef().FlexWrap() == EFlexWrap::kWrapReverse);
AdjustAlignmentForChild(*flex_item.box, offset);
if (position == ItemPosition::kBaseline &&
StyleRef().FlexWrap() == EFlexWrap::kWrapReverse) {
- min_margin_after_baseline = std::min(
- min_margin_after_baseline,
- flex_item.AvailableAlignmentSpace(line_cross_axis_extent) - offset);
+ min_margin_after_baseline =
+ std::min(min_margin_after_baseline,
+ flex_item.AvailableAlignmentSpace() - offset);
}
}
min_margin_after_baselines.push_back(min_margin_after_baseline);
@@ -1575,14 +1600,11 @@ void LayoutFlexibleBox::AlignChildren(Vector<FlexLine>& line_contexts) {
// wrap-reverse flips the cross axis start and end. For baseline alignment,
// this means we need to align the after edge of baseline elements with the
// after edge of the flex line.
- for (size_t line_number = 0; line_number < line_contexts.size();
- ++line_number) {
- const FlexLine& line_context = line_contexts[line_number];
+ wtf_size_t line_number = 0;
+ for (FlexLine& line_context : line_contexts) {
LayoutUnit min_margin_after_baseline =
- min_margin_after_baselines[line_number];
- for (size_t child_number = 0; child_number < line_context.line_items.size();
- ++child_number) {
- const FlexItem& flex_item = line_context.line_items[child_number];
+ min_margin_after_baselines[line_number++];
+ for (FlexItem& flex_item : line_context.line_items) {
if (flex_item.Alignment() == ItemPosition::kBaseline &&
!flex_item.HasAutoMarginsInCrossAxis() && min_margin_after_baseline)
AdjustAlignmentForChild(*flex_item.box, min_margin_after_baseline);
@@ -1590,32 +1612,9 @@ void LayoutFlexibleBox::AlignChildren(Vector<FlexLine>& line_contexts) {
}
}
-void LayoutFlexibleBox::ComputeStretchedSizeForChild(
- FlexItem& flex_item,
- LayoutUnit line_cross_axis_extent) {
- DCHECK_EQ(flex_item.Alignment(), ItemPosition::kStretch);
- LayoutBox& child = *flex_item.box;
- if (!flex_item.HasOrthogonalFlow() &&
- child.StyleRef().LogicalHeight().IsAuto()) {
- LayoutUnit stretched_logical_height =
- std::max(child.BorderAndPaddingLogicalHeight(),
- line_cross_axis_extent - flex_item.CrossAxisMarginExtent());
- DCHECK(!child.NeedsLayout());
- flex_item.cross_axis_size = child.ConstrainLogicalHeightByMinMax(
- stretched_logical_height, child.IntrinsicContentLogicalHeight());
- } else if (flex_item.HasOrthogonalFlow() &&
- child.StyleRef().LogicalWidth().IsAuto()) {
- LayoutUnit child_width =
- (line_cross_axis_extent - flex_item.CrossAxisMarginExtent())
- .ClampNegativeToZero();
- flex_item.cross_axis_size = child.ConstrainLogicalWidthByMinMax(
- child_width, CrossAxisContentExtent(), this);
- }
-}
-
void LayoutFlexibleBox::ApplyStretchAlignmentToChild(FlexItem& flex_item) {
LayoutBox& child = *flex_item.box;
- if (!flex_item.HasOrthogonalFlow() &&
+ if (flex_item.MainAxisIsInlineAxis() &&
child.StyleRef().LogicalHeight().IsAuto()) {
// FIXME: Can avoid laying out here in some cases. See
// https://webkit.org/b/87905.
@@ -1623,7 +1622,7 @@ void LayoutFlexibleBox::ApplyStretchAlignmentToChild(FlexItem& flex_item) {
flex_item.cross_axis_size != child.LogicalHeight();
if (child.IsLayoutBlock() &&
ToLayoutBlock(child).HasPercentHeightDescendants() &&
- !CanAvoidLayoutForNGChild(child)) {
+ !CanAvoidLayoutForNGChild(child) && !child.HasOverrideLogicalHeight()) {
// Have to force another relayout even though the child is sized
// correctly, because its descendants are not sized correctly yet. Our
// previous layout of the child was done without an override height set.
@@ -1633,19 +1632,11 @@ void LayoutFlexibleBox::ApplyStretchAlignmentToChild(FlexItem& flex_item) {
if (child_needs_relayout || !child.HasOverrideLogicalHeight())
child.SetOverrideLogicalHeight(flex_item.cross_axis_size);
if (child_needs_relayout) {
+ // TODO(cbiesinger): Why is this necessary?
child.SetLogicalHeight(LayoutUnit());
- // We cache the child's intrinsic content logical height to avoid it being
- // reset to the stretched height.
- // FIXME: This is fragile. LayoutBoxes should be smart enough to
- // determine their intrinsic content logical height correctly even when
- // there's an overrideHeight.
- LayoutUnit child_intrinsic_content_logical_height =
- child.IntrinsicContentLogicalHeight();
child.ForceChildLayout();
- child.SetIntrinsicContentLogicalHeight(
- child_intrinsic_content_logical_height);
}
- } else if (flex_item.HasOrthogonalFlow() &&
+ } else if (!flex_item.MainAxisIsInlineAxis() &&
child.StyleRef().LogicalWidth().IsAuto()) {
if (flex_item.cross_axis_size != child.LogicalWidth()) {
child.SetOverrideLogicalWidth(flex_item.cross_axis_size);
@@ -1660,12 +1651,8 @@ void LayoutFlexibleBox::FlipForRightToLeftColumn(
return;
LayoutUnit cross_extent = CrossAxisExtent();
- for (size_t line_number = 0; line_number < line_contexts.size();
- ++line_number) {
- const FlexLine& line_context = line_contexts[line_number];
- for (size_t child_number = 0; child_number < line_context.line_items.size();
- ++child_number) {
- const FlexItem& flex_item = line_context.line_items[child_number];
+ for (const FlexLine& line_context : line_contexts) {
+ for (const FlexItem& flex_item : line_context.line_items) {
DCHECK(!flex_item.box->IsOutOfFlowPositioned());
LayoutPoint location = FlowAwareLocationForChild(*flex_item.box);
@@ -1681,16 +1668,11 @@ void LayoutFlexibleBox::FlipForWrapReverse(
const Vector<FlexLine>& line_contexts,
LayoutUnit cross_axis_start_edge) {
LayoutUnit content_extent = CrossAxisContentExtent();
- for (size_t line_number = 0; line_number < line_contexts.size();
- ++line_number) {
- const FlexLine& line_context = line_contexts[line_number];
- for (size_t child_number = 0; child_number < line_context.line_items.size();
- ++child_number) {
- const FlexItem& flex_item = line_context.line_items[child_number];
- LayoutUnit line_cross_axis_extent =
- line_contexts[line_number].cross_axis_extent;
+ for (const FlexLine& line_context : line_contexts) {
+ for (const FlexItem& flex_item : line_context.line_items) {
+ LayoutUnit line_cross_axis_extent = line_context.cross_axis_extent;
LayoutUnit original_offset =
- line_contexts[line_number].cross_axis_offset - cross_axis_start_edge;
+ line_context.cross_axis_offset - cross_axis_start_edge;
LayoutUnit new_offset =
content_extent - original_offset - line_cross_axis_extent;
AdjustAlignmentForChild(*flex_item.box, new_offset - original_offset);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.h b/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.h
index 4870be7c3bd..ab18de0f4ba 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_flexible_box.h
@@ -94,6 +94,7 @@ class CORE_EXPORT LayoutFlexibleBox : public LayoutBlock {
// Returns true if the position changed. In that case, the child will have to
// be laid out again.
bool SetStaticPositionForPositionedLayout(LayoutBox& child);
+ LayoutUnit CrossAxisContentExtent() const;
protected:
void ComputeIntrinsicLogicalWidths(
@@ -108,7 +109,7 @@ class CORE_EXPORT LayoutFlexibleBox : public LayoutBlock {
enum class SizeDefiniteness { kDefinite, kIndefinite, kUnknown };
- bool HasOrthogonalFlow(const LayoutBox& child) const;
+ bool MainAxisIsInlineAxis(const LayoutBox& child) const;
bool IsColumnFlow() const;
bool IsLeftToRightFlow() const;
bool IsMultiline() const;
@@ -121,7 +122,6 @@ class CORE_EXPORT LayoutFlexibleBox : public LayoutBlock {
LayoutUnit MainAxisContentExtentForChildIncludingScrollbar(
const LayoutBox& child) const;
LayoutUnit CrossAxisExtent() const;
- LayoutUnit CrossAxisContentExtent() const;
LayoutUnit MainAxisContentExtent(LayoutUnit content_logical_height);
LayoutUnit ComputeMainAxisExtentForChild(const LayoutBox& child,
SizeType,
@@ -182,6 +182,7 @@ class CORE_EXPORT LayoutFlexibleBox : public LayoutBlock {
void ResetAutoMarginsAndLogicalTopInCrossAxis(LayoutBox& child);
void SetOverrideMainAxisContentSizeForChild(FlexItem&);
+ bool ChildLogicalHeightStretchesToFlexboxSize(FlexItem&) const;
void PrepareChildForPositionedLayout(LayoutBox& child);
void LayoutLineItems(FlexLine*, bool relayout_children, SubtreeLayoutScope&);
void ApplyLineItemsPosition(FlexLine*);
@@ -190,10 +191,6 @@ class CORE_EXPORT LayoutFlexibleBox : public LayoutBlock {
LayoutUnit available_free_space);
void AlignFlexLines(Vector<FlexLine>&);
void AlignChildren(Vector<FlexLine>&);
- // Computes the cross-axis size that a stretched child should have and stores
- // it in child.cross_axis_size.
- void ComputeStretchedSizeForChild(FlexItem& child,
- LayoutUnit line_cross_axis_extent);
void ApplyStretchAlignmentToChild(FlexItem& child);
void FlipForRightToLeftColumn(const Vector<FlexLine>& line_contexts);
void FlipForWrapReverse(const Vector<FlexLine>&,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_frame_set.cc b/chromium/third_party/blink/renderer/core/layout/layout_frame_set.cc
index 70ab4ee452f..3c5b54027e1 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_frame_set.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_frame_set.cc
@@ -428,7 +428,7 @@ void LayoutFrameSet::PositionFrames() {
if (size != child->Size() || size.IsEmpty()) {
child->SetSize(size);
child->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
child->UpdateLayout();
}
@@ -467,14 +467,14 @@ void LayoutFrameSet::ContinueResizing(GridAxis& axis, int position) {
axis.deltas_[axis.split_being_resized_ - 1] += delta;
axis.deltas_[axis.split_being_resized_] -= delta;
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
}
bool LayoutFrameSet::UserResize(const MouseEvent& evt) {
if (!is_resizing_) {
if (NeedsLayout())
return false;
- if (evt.type() == EventTypeNames::mousedown &&
+ if (evt.type() == event_type_names::kMousedown &&
evt.button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
FloatPoint local_pos =
@@ -488,15 +488,15 @@ bool LayoutFrameSet::UserResize(const MouseEvent& evt) {
}
}
} else {
- if (evt.type() == EventTypeNames::mousemove ||
- (evt.type() == EventTypeNames::mouseup &&
+ if (evt.type() == event_type_names::kMousemove ||
+ (evt.type() == event_type_names::kMouseup &&
evt.button() ==
static_cast<short>(WebPointerProperties::Button::kLeft))) {
FloatPoint local_pos =
AbsoluteToLocal(FloatPoint(evt.AbsoluteLocation()), kUseTransforms);
ContinueResizing(cols_, local_pos.X());
ContinueResizing(rows_, local_pos.Y());
- if (evt.type() == EventTypeNames::mouseup &&
+ if (evt.type() == event_type_names::kMouseup &&
evt.button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
SetIsResizing(false);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.cc b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.cc
index 73c4c9b6996..e60bd3b8f24 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.cc
@@ -196,8 +196,8 @@ void LayoutGeometryMap::PushMappingsToAncestor(
const LayoutBoxModelObject* ancestor_layout_object) {
// We need to push mappings in reverse order here, so do insertions rather
// than appends.
- base::AutoReset<size_t> position_change(&insertion_position_,
- mapping_.size());
+ base::AutoReset<wtf_size_t> position_change(&insertion_position_,
+ mapping_.size());
do {
layout_object =
layout_object->PushMappingToContainer(ancestor_layout_object, *this);
@@ -266,8 +266,8 @@ void LayoutGeometryMap::PushMappingsToAncestor(
PushMappingsToAncestor(&ancestor_layer->GetLayoutObject(), nullptr);
}
- base::AutoReset<size_t> position_change(&insertion_position_,
- mapping_.size());
+ base::AutoReset<wtf_size_t> position_change(&insertion_position_,
+ mapping_.size());
bool accumulating_transform =
layout_object.StyleRef().Preserves3D() ||
ancestor_layer->GetLayoutObject().StyleRef().Preserves3D();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.h b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.h
index 32e56d2bc4d..54d310c1bae 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map.h
@@ -113,7 +113,7 @@ class CORE_EXPORT LayoutGeometryMap {
typedef Vector<LayoutGeometryMapStep, 32> LayoutGeometryMapSteps;
- size_t insertion_position_;
+ wtf_size_t insertion_position_;
int non_uniform_steps_count_;
int transformed_steps_count_;
int fixed_steps_count_;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc
index cfa392065c4..d67642b5243 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_test.cc
@@ -156,21 +156,26 @@ class LayoutGeometryMapTest : public testing::Test {
}
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
+ void UpdateAllLifecyclePhases(WebView* web_view) {
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
const std::string base_url_;
};
TEST_F(LayoutGeometryMapTest, SimpleGeometryMapTest) {
RegisterMockedHttpURLLoad("rgm_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view =
web_view_helper.InitializeAndLoad(base_url_ + "rgm_test.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
// We are going test everything twice. Once with FloatPoints and once with
// FloatRects. This is because LayoutGeometryMap treats both slightly
@@ -210,11 +215,11 @@ TEST_F(LayoutGeometryMapTest, TransformedGeometryTest)
#endif
{
RegisterMockedHttpURLLoad("rgm_transformed_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "rgm_transformed_test.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
LayoutGeometryMap rgm;
rgm.PushMappingsToAncestor(GetLayoutBox(web_view, "InitialDiv"), nullptr);
@@ -269,11 +274,11 @@ TEST_F(LayoutGeometryMapTest, TransformedGeometryTest)
TEST_F(LayoutGeometryMapTest, FixedGeometryTest) {
RegisterMockedHttpURLLoad("rgm_fixed_position_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "rgm_fixed_position_test.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
LayoutGeometryMap rgm;
rgm.PushMappingsToAncestor(GetLayoutBox(web_view, "InitialDiv"), nullptr);
@@ -307,11 +312,11 @@ TEST_F(LayoutGeometryMapTest, FixedGeometryTest) {
TEST_F(LayoutGeometryMapTest, ContainsFixedPositionTest) {
RegisterMockedHttpURLLoad("rgm_contains_fixed_position_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "rgm_contains_fixed_position_test.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
FloatRect rect(0.0f, 0.0f, 100.0f, 100.0f);
LayoutGeometryMap rgm;
@@ -355,11 +360,11 @@ TEST_F(LayoutGeometryMapTest, ContainsFixedPositionTest) {
TEST_F(LayoutGeometryMapTest, IframeTest) {
RegisterMockedHttpURLLoad("rgm_iframe_test.html");
RegisterMockedHttpURLLoad("rgm_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view =
web_view_helper.InitializeAndLoad(base_url_ + "rgm_iframe_test.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
LayoutGeometryMap rgm(kTraverseDocumentBoundaries);
LayoutGeometryMap rgm_no_frame;
@@ -451,11 +456,11 @@ TEST_F(LayoutGeometryMapTest, IframeTest) {
TEST_F(LayoutGeometryMapTest, ColumnTest) {
RegisterMockedHttpURLLoad("rgm_column_test.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view =
web_view_helper.InitializeAndLoad(base_url_ + "rgm_column_test.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
// The document is 1000f wide (we resized to that size).
// We have a 8px margin on either side of the document.
@@ -499,11 +504,11 @@ TEST_F(LayoutGeometryMapTest, ColumnTest) {
TEST_F(LayoutGeometryMapTest, FloatUnderInlineLayer) {
RegisterMockedHttpURLLoad("rgm_float_under_inline.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebView* web_view = web_view_helper.InitializeAndLoad(
base_url_ + "rgm_float_under_inline.html");
- web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
+ UpdateAllLifecyclePhases(web_view);
LayoutGeometryMap rgm;
auto* layer_under_float = GetLayoutBox(web_view, "layer-under-float");
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_grid.cc b/chromium/third_party/blink/renderer/core/layout/layout_grid.cc
index 5b9446366b7..7b734e3d506 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_grid.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_grid.cc
@@ -39,7 +39,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/grid_area.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
@@ -156,7 +156,7 @@ void LayoutGrid::StyleDidChange(StyleDifference diff,
*child) ||
SelfAlignmentChangedSize(kGridColumnAxis, *old_style, new_style,
*child)) {
- child->SetNeedsLayout(LayoutInvalidationReason::kGridChanged);
+ child->SetNeedsLayout(layout_invalidation_reason::kGridChanged);
}
}
}
@@ -323,13 +323,20 @@ void LayoutGrid::UpdateBlockLayout(bool relayout_children) {
ComputeTrackSizesForDefiniteSize(
kForRows, AvailableLogicalHeight(kExcludeMarginBorderPadding));
} else {
- ComputeTrackSizesForIndefiniteSize(track_sizing_algorithm_, kForRows,
- min_content_height_,
- max_content_height_);
+ ComputeTrackSizesForIndefiniteSize(track_sizing_algorithm_, kForRows);
}
LayoutUnit track_based_logical_height =
track_sizing_algorithm_.ComputeTrackBasedSize() +
- BorderAndPaddingLogicalHeight() + ScrollbarLogicalHeight();
+ BorderAndPaddingLogicalHeight();
+
+ // TODO(rego): We shouldn't need this once crbug.com/906530 is fixed.
+ // Right now we need this because
+ // LayoutBox::ComputeContentAndScrollbarLogicalHeightUsing() is adding the
+ // ScrollbarLogicalHeight() for the intrinsic height cases. But that's
+ // causing more problems as described in the bug linked before.
+ if (!StyleRef().LogicalHeight().IsIntrinsic())
+ track_based_logical_height += ScrollbarLogicalHeight();
+
SetLogicalHeight(track_based_logical_height);
LayoutUnit old_client_after_edge = ClientLogicalBottom();
@@ -512,8 +519,8 @@ void LayoutGrid::ComputeIntrinsicLogicalWidths(
}
}
- ComputeTrackSizesForIndefiniteSize(algorithm, kForColumns, min_logical_width,
- max_logical_width);
+ ComputeTrackSizesForIndefiniteSize(algorithm, kForColumns, &min_logical_width,
+ &max_logical_width);
LayoutUnit scrollbar_width = LayoutUnit(ScrollbarLogicalWidth());
min_logical_width += scrollbar_width;
@@ -523,54 +530,26 @@ void LayoutGrid::ComputeIntrinsicLogicalWidths(
void LayoutGrid::ComputeTrackSizesForIndefiniteSize(
GridTrackSizingAlgorithm& algo,
GridTrackSizingDirection direction,
- LayoutUnit& min_intrinsic_size,
- LayoutUnit& max_intrinsic_size) const {
+ LayoutUnit* min_intrinsic_size,
+ LayoutUnit* max_intrinsic_size) const {
const Grid& grid = algo.GetGrid();
algo.Setup(direction, NumTracks(direction, grid), base::nullopt);
algo.Run();
- min_intrinsic_size = algo.MinContentSize();
- max_intrinsic_size = algo.MaxContentSize();
-
size_t number_of_tracks = algo.Tracks(direction).size();
LayoutUnit total_gutters_size =
GuttersSize(grid, direction, 0, number_of_tracks, base::nullopt);
- min_intrinsic_size += total_gutters_size;
- max_intrinsic_size += total_gutters_size;
+
+ if (min_intrinsic_size)
+ *min_intrinsic_size = algo.MinContentSize() + total_gutters_size;
+ if (max_intrinsic_size)
+ *max_intrinsic_size = algo.MaxContentSize() + total_gutters_size;
#if DCHECK_IS_ON()
DCHECK(algo.TracksAreWiderThanMinTrackBreadth());
#endif
}
-LayoutUnit LayoutGrid::ComputeIntrinsicLogicalContentHeightUsing(
- const Length& logical_height_length,
- LayoutUnit intrinsic_content_height,
- LayoutUnit border_and_padding) const {
- if (logical_height_length.IsMinContent())
- return min_content_height_;
-
- if (logical_height_length.IsMaxContent())
- return max_content_height_;
-
- if (logical_height_length.IsFitContent()) {
- if (min_content_height_ == -1 || max_content_height_ == -1)
- return LayoutUnit(-1);
- LayoutUnit fill_available_extent =
- ContainingBlock()->AvailableLogicalHeight(kExcludeMarginBorderPadding);
- return std::min<LayoutUnit>(
- max_content_height_,
- std::max(min_content_height_, fill_available_extent));
- }
-
- if (logical_height_length.IsFillAvailable())
- return ContainingBlock()->AvailableLogicalHeight(
- kExcludeMarginBorderPadding) -
- border_and_padding;
- NOTREACHED();
- return LayoutUnit();
-}
-
LayoutUnit LayoutGrid::OverrideContainingBlockContentSizeForChild(
const LayoutBox& child,
GridTrackSizingDirection direction) {
@@ -1241,7 +1220,8 @@ void LayoutGrid::UpdateGridAreaLogicalSize(
OverrideSizeChanged(child, kForRows, grid_area_logical_size);
if (grid_area_width_changed ||
(grid_area_height_changed && HasRelativeBlockAxisSize(*this, child))) {
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged, kMarkOnlyThis);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged,
+ kMarkOnlyThis);
}
child.SetOverrideContainingBlockContentLogicalWidth(
@@ -1347,7 +1327,7 @@ void LayoutGrid::LayoutPositionedObjects(bool relayout_children,
// Mark for layout as we're resetting the position before and we relay in
// generic layout logic for positioned items in order to get the offsets
// properly resolved.
- child->SetNeedsLayout(LayoutInvalidationReason::kGridChanged,
+ child->SetNeedsLayout(layout_invalidation_reason::kGridChanged,
kMarkOnlyThis);
LayoutPositionedObject(child, relayout_children, info);
@@ -1403,8 +1383,18 @@ void LayoutGrid::PopulateGridPositionsForDirection(
direction == kForColumns ? offset_between_columns_ : offset_between_rows_;
auto& positions = is_row_axis ? column_positions_ : row_positions_;
positions.resize(number_of_lines);
+
auto border_and_padding =
is_row_axis ? BorderAndPaddingLogicalLeft() : BorderAndPaddingBefore();
+ if (is_row_axis) {
+ if (StyleRef().IsHorizontalWritingMode() &&
+ !StyleRef().IsLeftToRightDirection())
+ border_and_padding += ScrollbarLogicalWidth();
+ } else {
+ if (StyleRef().GetWritingMode() == WritingMode::kVerticalRl)
+ border_and_padding += ScrollbarLogicalHeight();
+ }
+
positions[0] = border_and_padding + offset.position_offset;
if (number_of_lines > 1) {
// If we have collapsed tracks we just ignore gaps here and add them later
@@ -1519,7 +1509,7 @@ void LayoutGrid::ApplyStretchAlignmentToChildIfNeeded(LayoutBox& child) {
// TODO (lajava): Can avoid laying out here in some cases. See
// https://webkit.org/b/87905.
child.SetLogicalHeight(LayoutUnit());
- child.SetNeedsLayout(LayoutInvalidationReason::kGridChanged);
+ child.SetNeedsLayout(layout_invalidation_reason::kGridChanged);
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_grid.h b/chromium/third_party/blink/renderer/core/layout/layout_grid.h
index 00cd7ee9d01..8d08fb1feea 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_grid.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_grid.h
@@ -132,11 +132,6 @@ class LayoutGrid final : public LayoutBlock {
LayoutUnit& min_logical_width,
LayoutUnit& max_logical_width) const override;
- LayoutUnit ComputeIntrinsicLogicalContentHeightUsing(
- const Length& logical_height_length,
- LayoutUnit intrinsic_content_height,
- LayoutUnit border_and_padding) const override;
-
void AddChild(LayoutObject* new_child,
LayoutObject* before_child = nullptr) override;
void RemoveChild(LayoutObject*) override;
@@ -184,10 +179,11 @@ class LayoutGrid final : public LayoutBlock {
GridTrackSizingDirection AutoPlacementMajorAxisDirection() const;
GridTrackSizingDirection AutoPlacementMinorAxisDirection() const;
- void ComputeTrackSizesForIndefiniteSize(GridTrackSizingAlgorithm&,
- GridTrackSizingDirection,
- LayoutUnit& min_intrinsic_size,
- LayoutUnit& max_intrinsic_size) const;
+ void ComputeTrackSizesForIndefiniteSize(
+ GridTrackSizingAlgorithm&,
+ GridTrackSizingDirection,
+ LayoutUnit* min_intrinsic_size = nullptr,
+ LayoutUnit* max_intrinsic_size = nullptr) const;
void ComputeTrackSizesForDefiniteSize(GridTrackSizingDirection,
LayoutUnit free_space);
@@ -319,9 +315,6 @@ class LayoutGrid final : public LayoutBlock {
OutOfFlowPositionsMap column_of_positioned_item_;
OutOfFlowPositionsMap row_of_positioned_item_;
- LayoutUnit min_content_height_{-1};
- LayoutUnit max_content_height_{-1};
-
bool has_any_orthogonal_item_{false};
bool baseline_items_cached_{false};
base::Optional<bool> has_definite_logical_height_;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_html_canvas.cc b/chromium/third_party/blink/renderer/core/layout/layout_html_canvas.cc
index c3276c21c64..28aa60fd8c7 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_html_canvas.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_html_canvas.cc
@@ -34,8 +34,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutHTMLCanvas::LayoutHTMLCanvas(HTMLCanvasElement* element)
: LayoutReplaced(element, LayoutSize(element->Size())) {
View()->GetFrameView()->SetIsVisuallyNonEmpty();
@@ -79,7 +77,7 @@ void LayoutHTMLCanvas::CanvasSizeChanged() {
}
if (!SelfNeedsLayout())
- SetNeedsLayout(LayoutInvalidationReason::kSizeChanged);
+ SetNeedsLayout(layout_invalidation_reason::kSizeChanged);
}
void LayoutHTMLCanvas::InvalidatePaint(
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_image.cc b/chromium/third_party/blink/renderer/core/layout/layout_image.cc
index 972b84ee22d..44a4204a2f0 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image.cc
@@ -50,42 +50,42 @@
namespace blink {
namespace {
-constexpr float kmax_downscaling_ratio = 2.0f;
+constexpr float kmax_oversize_ratio = 2.0f;
-bool CheckForOptimizedImagePolicy(const LocalFrame& frame,
- LayoutImage* layout_image,
+bool CheckForOptimizedImagePolicy(const Document& document,
ImageResourceContent* new_image) {
- // Invert the image if the document does not have the 'legacy-image-formats'
- // feature enabled, and the image is not one of the allowed formats.
+ // Render the image as a placeholder image if the document does not have the
+ // 'legacy-image-formats' feature enabled, and the image is not one of the
+ // allowed formats.
if (RuntimeEnabledFeatures::ExperimentalProductivityFeaturesEnabled() &&
- !frame.DeprecatedIsFeatureEnabled(
+ !document.IsFeatureEnabled(
mojom::FeaturePolicyFeature::kLegacyImageFormats)) {
if (!new_image->IsAcceptableContentType()) {
return true;
}
}
- // Invert the image if the document does not have the image-compression'
- // feature enabled and the image is not sufficiently-well-compressed.
+ // Render the image as a placeholder image if the document does not have the
+ // 'unoptimized-images' feature enabled and the image is not
+ // sufficiently-well-compressed.
if (RuntimeEnabledFeatures::ExperimentalProductivityFeaturesEnabled() &&
- !frame.DeprecatedIsFeatureEnabled(
- mojom::FeaturePolicyFeature::kImageCompression)) {
+ !document.IsFeatureEnabled(
+ mojom::FeaturePolicyFeature::kUnoptimizedImages)) {
if (!new_image->IsAcceptableCompressionRatio())
return true;
}
return false;
}
-bool CheckForMaxDownscalingImagePolicy(const LocalFrame& frame,
- ImageResourceContent* new_image,
- LayoutImage* layout_image) {
+bool CheckForOversizedImagesPolicy(const Document& document,
+ ImageResourceContent* new_image,
+ LayoutImage* layout_image) {
DCHECK(new_image);
if (!RuntimeEnabledFeatures::ExperimentalProductivityFeaturesEnabled() ||
- frame.DeprecatedIsFeatureEnabled(
- mojom::FeaturePolicyFeature::kMaxDownscalingImage))
+ document.IsFeatureEnabled(mojom::FeaturePolicyFeature::kOversizedImages))
return false;
if (auto* image = new_image->GetImage()) {
- // Invert the image if the image's size is more than 2 times bigger than the
- // size it is being laid-out by.
+ // Render the image as a placeholder image if the image's size is more
+ // than 2 times bigger than the size it is being laid-out by.
LayoutUnit layout_width = layout_image->ContentWidth();
LayoutUnit layout_height = layout_image->ContentHeight();
int image_width = image->width();
@@ -93,10 +93,10 @@ bool CheckForMaxDownscalingImagePolicy(const LocalFrame& frame,
if (layout_width > 0 && layout_height > 0 && image_width > 0 &&
image_height > 0) {
- double device_pixel_ratio = frame.DevicePixelRatio();
- if (LayoutUnit(image_width / (kmax_downscaling_ratio *
- device_pixel_ratio)) > layout_width ||
- LayoutUnit(image_height / (kmax_downscaling_ratio *
+ double device_pixel_ratio = document.GetFrame()->DevicePixelRatio();
+ if (LayoutUnit(image_width / (kmax_oversize_ratio * device_pixel_ratio)) >
+ layout_width ||
+ LayoutUnit(image_height / (kmax_oversize_ratio *
device_pixel_ratio)) > layout_height)
return true;
}
@@ -106,15 +106,15 @@ bool CheckForMaxDownscalingImagePolicy(const LocalFrame& frame,
} // namespace
-using namespace HTMLNames;
+using namespace html_names;
LayoutImage::LayoutImage(Element* element)
: LayoutReplaced(element, LayoutSize()),
did_increment_visually_non_empty_pixel_count_(false),
is_generated_content_(false),
image_device_pixel_ratio_(1.0f),
- is_legacy_format_or_compressed_image_(false),
- is_downscaled_image_(false) {}
+ is_legacy_format_or_unoptimized_image_(false),
+ is_oversized_image_(false) {}
LayoutImage* LayoutImage::CreateAnonymous(PseudoElement& pseudo) {
LayoutImage* image = new LayoutImage(nullptr);
@@ -247,7 +247,7 @@ void LayoutImage::InvalidatePaintAndMarkForLayoutIfNeeded(
(!image_size_is_constrained ||
containing_block_needs_to_recompute_preferred_size)) {
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
return;
}
@@ -272,18 +272,8 @@ void LayoutImage::ImageNotifyFinished(ImageResourceContent* new_image) {
InvalidateBackgroundObscurationStatus();
// Check for optimized image policies.
- if (View() && View()->GetFrameView()) {
- bool old_flag = ShouldInvertColor();
- const LocalFrame& frame = View()->GetFrameView()->GetFrame();
- is_legacy_format_or_compressed_image_ =
- CheckForOptimizedImagePolicy(frame, this, new_image);
- if (auto* image_element = ToHTMLImageElementOrNull(GetNode())) {
- is_downscaled_image_ =
- CheckForMaxDownscalingImagePolicy(frame, new_image, this);
- }
- if (old_flag != ShouldInvertColor())
- UpdateShouldInvertColor();
- }
+ if (IsHTMLImageElement(GetNode()))
+ ValidateImagePolicies();
if (new_image == image_resource_->CachedImage()) {
// tell any potential compositing layers
@@ -341,7 +331,7 @@ bool LayoutImage::ForegroundIsKnownToBeOpaqueInRect(
return false;
// Check for image with alpha.
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage",
- "data", InspectorPaintImageEvent::Data(this, *image_content));
+ "data", inspector_paint_image_event::Data(this, *image_content));
return image_content->GetImage()->CurrentFrameKnownToBeOpaque();
}
@@ -362,7 +352,7 @@ LayoutUnit LayoutImage::MinimumReplacedHeight() const {
HTMLMapElement* LayoutImage::ImageMap() const {
HTMLImageElement* i = ToHTMLImageElementOrNull(GetNode());
- return i ? i->GetTreeScope().GetImageMap(i->FastGetAttribute(usemapAttr))
+ return i ? i->GetTreeScope().GetImageMap(i->FastGetAttribute(kUsemapAttr))
: nullptr;
}
@@ -444,14 +434,23 @@ void LayoutImage::ComputeIntrinsicSizingInfo(
if (intrinsic_sizing_info.size.IsEmpty() &&
image_resource_->ImageHasRelativeSize() &&
!IsLayoutNGListMarkerImage()) {
- LayoutObject* containing_block =
- IsOutOfFlowPositioned() ? Container() : ContainingBlock();
- if (containing_block->IsBox()) {
- LayoutBox* box = ToLayoutBox(containing_block);
+ if (HasOverrideContainingBlockContentLogicalWidth() &&
+ HasOverrideContainingBlockContentLogicalHeight()) {
intrinsic_sizing_info.size.SetWidth(
- box->AvailableLogicalWidth().ToFloat());
+ OverrideContainingBlockContentLogicalWidth().ToFloat());
intrinsic_sizing_info.size.SetHeight(
- box->AvailableLogicalHeight(kIncludeMarginBorderPadding).ToFloat());
+ OverrideContainingBlockContentLogicalHeight().ToFloat());
+ } else {
+ LayoutObject* containing_block =
+ IsOutOfFlowPositioned() ? Container() : ContainingBlock();
+ if (containing_block->IsBox()) {
+ LayoutBox* box = ToLayoutBox(containing_block);
+ intrinsic_sizing_info.size.SetWidth(
+ box->AvailableLogicalWidth().ToFloat());
+ intrinsic_sizing_info.size.SetHeight(
+ box->AvailableLogicalHeight(kIncludeMarginBorderPadding)
+ .ToFloat());
+ }
}
}
}
@@ -483,43 +482,30 @@ SVGImage* LayoutImage::EmbeddedSVGImage() const {
return ToSVGImageOrNull(cached_image->GetImage());
}
-bool LayoutImage::ShouldInvertColor() const {
- return is_downscaled_image_ || is_legacy_format_or_compressed_image_;
-}
-
-void LayoutImage::UpdateShouldInvertColor() {
- SetNeedsPaintPropertyUpdate();
- // If composited image, update compositing layer.
- if (Layer())
- Layer()->SetNeedsCompositingInputsUpdate();
+bool LayoutImage::IsImagePolicyViolated() const {
+ return is_oversized_image_ || is_legacy_format_or_unoptimized_image_;
}
-void LayoutImage::UpdateShouldInvertColorForTest(bool value) {
- is_downscaled_image_ = value;
- is_legacy_format_or_compressed_image_ = value;
- UpdateShouldInvertColor();
+void LayoutImage::ValidateImagePolicies() {
+ if (image_resource_ && image_resource_->CachedImage()) {
+ is_oversized_image_ = CheckForOversizedImagesPolicy(
+ GetDocument(), image_resource_->CachedImage(), this);
+ is_legacy_format_or_unoptimized_image_ = CheckForOptimizedImagePolicy(
+ GetDocument(), image_resource_->CachedImage());
+ }
}
void LayoutImage::UpdateAfterLayout() {
LayoutBox::UpdateAfterLayout();
Node* node = GetNode();
+
if (auto* image_element = ToHTMLImageElementOrNull(node)) {
- if (View() && View()->GetFrameView()) {
- const LocalFrame& frame = View()->GetFrameView()->GetFrame();
-
- if (image_resource_ && image_resource_->CachedImage()) {
- // Check for optimized image policies.
- bool old_flag = ShouldInvertColor();
- is_downscaled_image_ = CheckForMaxDownscalingImagePolicy(
- frame, image_resource_->CachedImage(), this);
- if (old_flag != ShouldInvertColor())
- UpdateShouldInvertColor();
- }
- }
+ // Check for optimized image policies.
+ ValidateImagePolicies();
// Report violation of unsized-media policy.
if (image_element->IsDefaultIntrinsicSize())
- MediaElementParserHelpers::ReportUnsizedMediaViolation(this);
+ media_element_parser_helpers::ReportUnsizedMediaViolation(this);
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_image.h b/chromium/third_party/blink/renderer/core/layout/layout_image.h
index 0ce310d4a4c..7db612ea834 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image.h
@@ -88,11 +88,9 @@ class CORE_EXPORT LayoutImage : public LayoutReplaced {
const char* GetName() const override { return "LayoutImage"; }
// When an image element violates feature policy optimized image policies, it
- // should be rendered with inverted color.
+ // should be rendered with a placeholder image.
// https://github.com/WICG/feature-policy/blob/master/policies/optimized-images.md
- bool ShouldInvertColor() const;
- void UpdateShouldInvertColor();
- void UpdateShouldInvertColorForTest(bool);
+ bool IsImagePolicyViolated() const;
void UpdateAfterLayout() override;
@@ -144,6 +142,8 @@ class CORE_EXPORT LayoutImage : public LayoutReplaced {
FloatSize ImageSizeOverriddenByIntrinsicSize(float multiplier) const;
IntSize GetOverriddenIntrinsicSize() const;
+ void ValidateImagePolicies();
+
// This member wraps the associated decoded image.
//
// This field is set using setImageResource above which can be called in
@@ -161,10 +161,10 @@ class CORE_EXPORT LayoutImage : public LayoutReplaced {
float image_device_pixel_ratio_;
// These flags indicate if the image violates one or more optimized image
- // policies. When any policy is violated, the image should be rendered with
- // inverted color.
- bool is_legacy_format_or_compressed_image_;
- bool is_downscaled_image_;
+ // policies. When any policy is violated, the image should be rendered as a
+ // placeholder image.
+ bool is_legacy_format_or_unoptimized_image_;
+ bool is_oversized_image_;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutImage, IsLayoutImage());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_image_resource.cc b/chromium/third_party/blink/renderer/core/layout/layout_image_resource.cc
index 62ebf5cc5c5..2b2ca04c9c4 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image_resource.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image_resource.cc
@@ -32,6 +32,7 @@
#include "third_party/blink/renderer/core/layout/layout_image.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h"
+#include "third_party/blink/renderer/platform/graphics/placeholder_image.h"
namespace blink {
@@ -154,6 +155,11 @@ scoped_refptr<Image> LayoutImageResource::GetImage(
return Image::NullImage();
Image* image = cached_image_->GetImage();
+ if (image->IsPlaceholderImage()) {
+ static_cast<PlaceholderImage*>(image)->SetIconAndTextScaleFactor(
+ layout_object_->StyleRef().EffectiveZoom());
+ }
+
if (!image->IsSVGImage())
return image;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_image_resource.h b/chromium/third_party/blink/renderer/core/layout/layout_image_resource.h
index 4d2776a9f6e..ffd214d18ec 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image_resource.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image_resource.h
@@ -39,9 +39,12 @@ class LayoutObject;
class CORE_EXPORT LayoutImageResource
: public GarbageCollectedFinalized<LayoutImageResource> {
public:
+ LayoutImageResource();
virtual ~LayoutImageResource();
- static LayoutImageResource* Create() { return new LayoutImageResource; }
+ static LayoutImageResource* Create() {
+ return MakeGarbageCollected<LayoutImageResource>();
+ }
virtual void Initialize(LayoutObject*);
virtual void Shutdown();
@@ -73,8 +76,6 @@ class CORE_EXPORT LayoutImageResource
virtual void Trace(blink::Visitor* visitor) { visitor->Trace(cached_image_); }
protected:
- LayoutImageResource();
-
// Device scale factor for the associated LayoutObject.
float DeviceScaleFactor() const;
// Returns an image based on the passed device scale factor.
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_image_resource_style_image.h b/chromium/third_party/blink/renderer/core/layout/layout_image_resource_style_image.h
index 644d3e77a27..bdc4d0dbbd2 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image_resource_style_image.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image_resource_style_image.h
@@ -37,10 +37,11 @@ class LayoutObject;
class LayoutImageResourceStyleImage final : public LayoutImageResource {
public:
+ explicit LayoutImageResourceStyleImage(StyleImage*);
~LayoutImageResourceStyleImage() override;
static LayoutImageResource* Create(StyleImage* style_image) {
- return new LayoutImageResourceStyleImage(style_image);
+ return MakeGarbageCollected<LayoutImageResourceStyleImage>(style_image);
}
void Initialize(LayoutObject*) override;
void Shutdown() override;
@@ -60,7 +61,6 @@ class LayoutImageResourceStyleImage final : public LayoutImageResource {
void Trace(blink::Visitor*) override;
private:
- explicit LayoutImageResourceStyleImage(StyleImage*);
Member<StyleImage> style_image_;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_inline.cc b/chromium/third_party/blink/renderer/core/layout/layout_inline.cc
index 828d0821aad..b3c2a8bfec3 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_inline.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_inline.cc
@@ -35,6 +35,7 @@
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h"
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_outline_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/paint/box_painter.h"
#include "third_party/blink/renderer/core/paint/inline_painter.h"
@@ -52,11 +53,24 @@ namespace {
// TODO(layout-dev): Once we generate fragment for all inline element, we should
// use |LayoutObject::EnclosingBlockFlowFragment()|.
-const NGPhysicalBoxFragment* EnclosingBlockFlowFragmentOf(
+const NGPhysicalBoxFragment* ContainingBlockFlowFragmentOf(
const LayoutInline& node) {
if (!RuntimeEnabledFeatures::LayoutNGEnabled())
return nullptr;
- return node.EnclosingBlockFlowFragment();
+ return node.ContainingBlockFlowFragment();
+}
+
+// TODO(xiaochengh): Deduplicate with a similar function in ng_paint_fragment.cc
+// ::before, ::after and ::first-letter can be hit test targets.
+bool CanBeHitTestTargetPseudoNodeStyle(const ComputedStyle& style) {
+ switch (style.StyleType()) {
+ case kPseudoIdBefore:
+ case kPseudoIdAfter:
+ case kPseudoIdFirstLetter:
+ return true;
+ default:
+ return false;
+ }
}
} // anonymous namespace
@@ -230,40 +244,92 @@ void LayoutInline::StyleDidChange(StyleDifference diff,
// before and after the block share the same style, but the block doesn't need
// to pass its style on to anyone else.
const ComputedStyle& new_style = StyleRef();
- LayoutInline* continuation = InlineElementContinuation();
- LayoutInline* end_of_continuation = nullptr;
- for (LayoutInline* curr_cont = continuation; curr_cont;
- curr_cont = curr_cont->InlineElementContinuation()) {
- LayoutBoxModelObject* next_cont = curr_cont->Continuation();
- curr_cont->SetContinuation(nullptr);
- curr_cont->SetStyle(MutableStyle());
- curr_cont->SetContinuation(next_cont);
- end_of_continuation = curr_cont;
- }
+ if (LayoutInline* continuation = InlineElementContinuation()) {
+ bool position_type_changed =
+ old_style && (new_style.GetPosition() != old_style->GetPosition()) &&
+ (new_style.HasInFlowPosition() || old_style->HasInFlowPosition());
+
+ // An inline that establishes a continuation is normally wrapped inside an
+ // anonymous block, of course, but if the continuation chain has been
+ // partially torn down (read comment further below), this is not the
+ // case. Here we want to find the nearest containing block that's an
+ // ancestor of all the continuations.
+ const LayoutBlock* boundary = ContainingBlock();
+ if (boundary->IsAnonymousBlock())
+ boundary = boundary->ContainingBlock();
+ LayoutInline* previous_part = this;
+ LayoutInline* end_of_continuation = nullptr;
+ bool needs_anon_block_position_update = false;
+ for (LayoutInline* curr_cont = continuation; curr_cont;
+ curr_cont = curr_cont->InlineElementContinuation()) {
+ if (position_type_changed && !needs_anon_block_position_update) {
+ // When we have a continuation chain, and the block child that was the
+ // reason for creating that in the first place is removed, we don't
+ // clean up the continuation chain. Previously split inlines should
+ // ideally be joined when this happens, but we don't do that, but rather
+ // leave the mess around. We'll end up with LayoutInline siblings or
+ // cousins for the same Node (that form a bogus continuation chain),
+ // without any blocks in-between. Here we check that we're NOT in such a
+ // situation, and that the Node actually forms a real continuation
+ // chain. This matters when it comes to marking the anonymous
+ // container(s) of block children as relatively positioned (further
+ // below). We should only do that if the Node is an ancestor of the
+ // blocks. Otherwise out-of-flow positioned descendants will use the
+ // wrong containing block.
+ for (LayoutObject* walker = previous_part->NextInPreOrder(boundary);
+ walker;) {
+ if (walker == curr_cont)
+ break;
+ if (walker->IsAnonymousBlock()) {
+ needs_anon_block_position_update = true;
+ break;
+ }
+ if (walker->IsLayoutInline())
+ walker = walker->NextInPreOrder(boundary);
+ else
+ walker = walker->NextInPreOrderAfterChildren(boundary);
+ }
+ }
+ previous_part = curr_cont;
+
+ LayoutBoxModelObject* next_cont = curr_cont->Continuation();
+ curr_cont->SetContinuation(nullptr);
+ curr_cont->SetStyle(MutableStyle());
+ curr_cont->SetContinuation(next_cont);
+ end_of_continuation = curr_cont;
+ }
- if (continuation && old_style) {
- DCHECK(end_of_continuation);
- LayoutObject* block = ContainingBlock()->NextSibling();
- // If an inline's in-flow positioning has changed then any descendant blocks
- // will need to change their styles accordingly.
- if (block && block->IsAnonymousBlock() &&
- new_style.GetPosition() != old_style->GetPosition() &&
- (new_style.HasInFlowPosition() || old_style->HasInFlowPosition()))
- UpdateInFlowPositionOfAnonymousBlockContinuations(
- block, new_style, *old_style, end_of_continuation->ContainingBlock());
+ if (needs_anon_block_position_update) {
+ DCHECK(old_style);
+ DCHECK(end_of_continuation);
+ LayoutObject* block = ContainingBlock()->NextSibling();
+ // If an inline's in-flow positioning has changed then any descendant
+ // blocks will need to change their styles accordingly.
+ if (block && block->IsAnonymousBlock()) {
+ UpdateInFlowPositionOfAnonymousBlockContinuations(
+ block, new_style, *old_style,
+ end_of_continuation->ContainingBlock());
+ }
+ }
}
- if (!AlwaysCreateLineBoxes()) {
- bool always_create_line_boxes_new =
- HasSelfPaintingLayer() || HasBoxDecorationBackground() ||
- new_style.HasPadding() || new_style.HasMargin() ||
- new_style.HasOutline();
- if (old_style && always_create_line_boxes_new) {
- DirtyLineBoxes(false);
- SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ if (!IsInLayoutNGInlineFormattingContext()) {
+ if (!AlwaysCreateLineBoxes()) {
+ bool always_create_line_boxes_new =
+ HasSelfPaintingLayer() || HasBoxDecorationBackground() ||
+ new_style.HasPadding() || new_style.HasMargin() ||
+ new_style.HasOutline();
+ if (old_style && always_create_line_boxes_new) {
+ DirtyLineBoxes(false);
+ SetNeedsLayoutAndFullPaintInvalidation(
+ layout_invalidation_reason::kStyleChange);
+ }
+ SetAlwaysCreateLineBoxes(always_create_line_boxes_new);
+ }
+ } else {
+ if (!ShouldCreateBoxFragment()) {
+ UpdateShouldCreateBoxFragment();
}
- SetAlwaysCreateLineBoxes(always_create_line_boxes_new);
}
// If we are changing to/from static, we need to reposition
@@ -290,6 +356,8 @@ void LayoutInline::StyleDidChange(StyleDifference diff,
}
void LayoutInline::UpdateAlwaysCreateLineBoxes(bool full_layout) {
+ DCHECK(!IsInLayoutNGInlineFormattingContext());
+
// Once we have been tainted once, just assume it will happen again. This way
// effects like hover highlighting that change the background color will only
// cause a layout on the first rollover.
@@ -329,6 +397,49 @@ void LayoutInline::UpdateAlwaysCreateLineBoxes(bool full_layout) {
}
}
+bool LayoutInline::ComputeInitialShouldCreateBoxFragment(
+ const ComputedStyle& style) const {
+ if (style.HasBoxDecorationBackground() || style.HasPadding() ||
+ style.HasMargin())
+ return true;
+
+ return style.CanContainAbsolutePositionObjects() ||
+ style.CanContainFixedPositionObjects(false) ||
+ NGOutlineUtils::HasPaintedOutline(style, GetNode()) ||
+ CanBeHitTestTargetPseudoNodeStyle(style);
+}
+
+bool LayoutInline::ComputeInitialShouldCreateBoxFragment() const {
+ const ComputedStyle& style = StyleRef();
+ if (HasSelfPaintingLayer() || ComputeInitialShouldCreateBoxFragment(style) ||
+ ShouldApplyPaintContainment() || ShouldApplyLayoutContainment())
+ return true;
+
+ const ComputedStyle& first_line_style = FirstLineStyleRef();
+ if (UNLIKELY(&style != &first_line_style &&
+ ComputeInitialShouldCreateBoxFragment(first_line_style)))
+ return true;
+
+ return false;
+}
+
+void LayoutInline::UpdateShouldCreateBoxFragment() {
+ // Once we have been tainted once, just assume it will happen again. This way
+ // effects like hover highlighting that change the background color will only
+ // cause a layout on the first rollover.
+ if (IsInLayoutNGInlineFormattingContext()) {
+ if (ShouldCreateBoxFragment())
+ return;
+ } else {
+ SetIsInLayoutNGInlineFormattingContext(true);
+ SetShouldCreateBoxFragment(false);
+ }
+
+ if (ComputeInitialShouldCreateBoxFragment()) {
+ SetShouldCreateBoxFragment();
+ }
+}
+
LayoutRect LayoutInline::LocalCaretRect(
const InlineBox* inline_box,
int,
@@ -449,12 +560,17 @@ void LayoutInline::AddChildIgnoringContinuation(LayoutObject* new_child,
LayoutBoxModelObject::AddChild(new_child, before_child);
new_child->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kChildChanged);
+ layout_invalidation_reason::kChildChanged);
}
LayoutInline* LayoutInline::Clone() const {
- LayoutInline* clone_inline = new LayoutInline(GetNode());
- DCHECK(!IsAnonymous());
+ LayoutInline* clone_inline = nullptr;
+ if (UNLIKELY(IsFirstLineAnonymous())) {
+ clone_inline = CreateAnonymousForFirstLine(&GetDocument());
+ } else {
+ DCHECK(!IsAnonymous());
+ clone_inline = new LayoutInline(GetNode());
+ }
clone_inline->SetStyle(MutableStyle());
clone_inline->SetIsInsideFlowThread(IsInsideFlowThread());
return clone_inline;
@@ -463,8 +579,8 @@ LayoutInline* LayoutInline::Clone() const {
void LayoutInline::MoveChildrenToIgnoringContinuation(
LayoutInline* to,
LayoutObject* start_child) {
- DCHECK(!IsAnonymous());
- DCHECK(!to->IsAnonymous());
+ DCHECK(!IsAnonymous() || IsFirstLineAnonymous());
+ DCHECK(!to->IsAnonymous() || to->IsFirstLineAnonymous());
LayoutObject* child = start_child;
while (child) {
LayoutObject* current_child = child;
@@ -480,7 +596,7 @@ void LayoutInline::SplitInlines(LayoutBlockFlow* from_block,
LayoutObject* before_child,
LayoutBoxModelObject* old_cont) {
DCHECK(IsDescendantOf(from_block));
- DCHECK(!IsAnonymous());
+ DCHECK(!IsAnonymous() || IsFirstLineAnonymous());
// FIXME: Because splitting is O(n^2) as tags nest pathologically, we cap the
// depth at which we're willing to clone.
@@ -602,7 +718,7 @@ void LayoutInline::SplitFlow(LayoutObject* before_child,
pre->Children()->AppendChildNode(
pre, block->Children()->RemoveChildNode(block, no));
no->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAnonymousBlockChange);
+ layout_invalidation_reason::kAnonymousBlockChange);
}
}
@@ -620,11 +736,11 @@ void LayoutInline::SplitFlow(LayoutObject* before_child,
// pre block into the post block, we want to make new line boxes instead of
// leaving the old line boxes around.
pre->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAnonymousBlockChange);
+ layout_invalidation_reason::kAnonymousBlockChange);
block->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAnonymousBlockChange);
+ layout_invalidation_reason::kAnonymousBlockChange);
post->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAnonymousBlockChange);
+ layout_invalidation_reason::kAnonymousBlockChange);
}
void LayoutInline::AddChildToContinuation(LayoutObject* new_child,
@@ -678,8 +794,11 @@ void LayoutInline::Paint(const PaintInfo& paint_info) const {
template <typename GeneratorContext>
void LayoutInline::GenerateLineBoxRects(GeneratorContext& yield) const {
- if (const NGPhysicalBoxFragment* box_fragment =
- EnclosingBlockFlowFragmentOf(*this)) {
+ if (IsInLayoutNGInlineFormattingContext()) {
+ const NGPhysicalBoxFragment* box_fragment =
+ ContainingBlockFlowFragmentOf(*this);
+ if (!box_fragment)
+ return;
const auto& descendants =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
const LayoutBlock* block_for_flipping = nullptr;
@@ -883,8 +1002,11 @@ LayoutPoint LayoutInline::FirstLineBoxTopLeft() const {
// hand, sets the block-axis coordinate relatively to the block-start border
// edge, which means that offsetLeft will be wrong when writing-mode is
// vertical-rl.
- if (const NGPhysicalBoxFragment* box_fragment =
- EnclosingBlockFlowFragmentOf(*this)) {
+ if (IsInLayoutNGInlineFormattingContext()) {
+ const NGPhysicalBoxFragment* box_fragment =
+ ContainingBlockFlowFragmentOf(*this);
+ if (!box_fragment)
+ return LayoutPoint();
const auto& fragments =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
if (fragments.IsEmpty())
@@ -936,7 +1058,7 @@ bool LayoutInline::NodeAtPoint(HitTestResult& result,
const HitTestLocation& location_in_container,
const LayoutPoint& accumulated_offset,
HitTestAction hit_test_action) {
- if (EnclosingNGBlockFlow()) {
+ if (ContainingNGBlockFlow()) {
// In LayoutNG, we reach here only when called from
// PaintLayer::HitTestContents() without going through any ancestor, in
// which case the element must have self painting layer.
@@ -1004,9 +1126,9 @@ bool LayoutInline::HitTestCulledInline(
// offset on the rectangles relatively to the block-start. NG is doing the
// right thing. Legacy is wrong.
if (container_fragment) {
- DCHECK(EnclosingNGBlockFlow());
+ DCHECK(ContainingNGBlockFlow());
DCHECK(container_fragment->IsDescendantOfNotSelf(
- *EnclosingNGBlockFlow()->PaintFragment()));
+ *ContainingNGBlockFlow()->PaintFragment()));
const NGPhysicalContainerFragment& traversal_root =
ToNGPhysicalContainerFragment(container_fragment->PhysicalFragment());
DCHECK(traversal_root.IsInline() || traversal_root.IsLineBox());
@@ -1020,7 +1142,7 @@ bool LayoutInline::HitTestCulledInline(
context(rect);
}
} else {
- DCHECK(!EnclosingNGBlockFlow());
+ DCHECK(!ContainingNGBlockFlow());
GenerateCulledLineBoxRects(context, this);
}
@@ -1048,7 +1170,7 @@ PositionWithAffinity LayoutInline::PositionForPoint(
continuation = ToLayoutBlockFlow(continuation)->InlineElementContinuation();
}
- if (const LayoutBlockFlow* ng_block_flow = EnclosingNGBlockFlow())
+ if (const LayoutBlockFlow* ng_block_flow = ContainingNGBlockFlow())
return ng_block_flow->PositionForPoint(point);
DCHECK(CanUseInlineBox(*this));
@@ -1078,8 +1200,11 @@ class LinesBoundingBoxGeneratorContext {
} // unnamed namespace
LayoutRect LayoutInline::LinesBoundingBox() const {
- if (const NGPhysicalBoxFragment* box_fragment =
- EnclosingBlockFlowFragmentOf(*this)) {
+ if (IsInLayoutNGInlineFormattingContext()) {
+ const NGPhysicalBoxFragment* box_fragment =
+ ContainingBlockFlowFragmentOf(*this);
+ if (!box_fragment)
+ return LayoutRect();
NGPhysicalOffsetRect bounding_box;
auto children =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
@@ -1223,8 +1348,11 @@ LayoutRect LayoutInline::CulledInlineVisualOverflowBoundingBox() const {
}
LayoutRect LayoutInline::LinesVisualOverflowBoundingBox() const {
- if (const NGPhysicalBoxFragment* box_fragment =
- EnclosingBlockFlowFragmentOf(*this)) {
+ if (IsInLayoutNGInlineFormattingContext()) {
+ const NGPhysicalBoxFragment* box_fragment =
+ ContainingBlockFlowFragmentOf(*this);
+ if (!box_fragment)
+ return LayoutRect();
NGPhysicalOffsetRect result;
auto children =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_inline.h b/chromium/third_party/blink/renderer/core/layout/layout_inline.h
index ea47f4007b8..8dfcc41d40f 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_inline.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_inline.h
@@ -185,6 +185,10 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
NGPaintFragment* FirstInlineFragment() const final;
void SetFirstInlineFragment(NGPaintFragment*) final;
+ // Return true if this inline doesn't occur on any lines, i.e. when it creates
+ // no fragments.
+ bool IsEmpty() const { return !FirstLineBox() && !FirstInlineFragment(); }
+
LayoutBoxModelObject* VirtualContinuation() const final {
return Continuation();
}
@@ -209,13 +213,25 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
using LayoutBoxModelObject::SetContinuation;
bool AlwaysCreateLineBoxes() const {
+ DCHECK(!IsInLayoutNGInlineFormattingContext());
return AlwaysCreateLineBoxesForLayoutInline();
}
void SetAlwaysCreateLineBoxes(bool always_create_line_boxes = true) {
+ DCHECK(!IsInLayoutNGInlineFormattingContext());
SetAlwaysCreateLineBoxesForLayoutInline(always_create_line_boxes);
}
void UpdateAlwaysCreateLineBoxes(bool full_layout);
+ // True if this inline box should force creation of NGPhysicalBoxFragment.
+ bool ShouldCreateBoxFragment() const {
+ DCHECK(IsInLayoutNGInlineFormattingContext());
+ return AlwaysCreateLineBoxesForLayoutInline();
+ }
+ void SetShouldCreateBoxFragment(bool value = true) {
+ SetAlwaysCreateLineBoxesForLayoutInline(value);
+ }
+ void UpdateShouldCreateBoxFragment();
+
LayoutRect LocalCaretRect(const InlineBox*,
int,
LayoutUnit* extra_width_to_end_of_line) const final;
@@ -272,6 +288,11 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
bool IsLayoutInline() const final { return true; }
+ // Compute the initial value of |ShouldCreateBoxFragment()| for this
+ // LayoutInline. It maybe flipped to true later for other conditions.
+ bool ComputeInitialShouldCreateBoxFragment() const;
+ bool ComputeInitialShouldCreateBoxFragment(const ComputedStyle& style) const;
+
LayoutRect CulledInlineVisualOverflowBoundingBox() const;
InlineBox* CulledInlineFirstLineBox() const;
InlineBox* CulledInlineLastLineBox() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_inline_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_inline_test.cc
index ed7396ecd58..03d7085b18d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_inline_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_inline_test.cc
@@ -99,7 +99,7 @@ TEST_F(LayoutInlineTest, RegionHitTest) {
</span></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutInline* lots_of_boxes =
ToLayoutInline(GetLayoutObjectByElementId("lotsOfBoxes"));
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_list_item.cc b/chromium/third_party/blink/renderer/core/layout/layout_list_item.cc
index f2a7ed19648..cb6d6172e22 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_list_item.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_list_item.cc
@@ -26,17 +26,15 @@
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/html/html_li_element.h"
#include "third_party/blink/renderer/core/html/html_olist_element.h"
-#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_list_marker.h"
#include "third_party/blink/renderer/core/paint/list_item_painter.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/platform/wtf/saturated_arithmetic.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
-using namespace HTMLNames;
-
LayoutListItem::LayoutListItem(Element* element)
: LayoutBlockFlow(element),
marker_(nullptr),
@@ -289,6 +287,25 @@ bool LayoutListItem::UpdateMarkerLocation() {
return false;
}
+void LayoutListItem::ComputeVisualOverflow(
+ const LayoutRect& previous_visual_overflow_rect,
+ bool recompute_floats) {
+ AddVisualOverflowFromChildren();
+
+ AddVisualEffectOverflow();
+ AddVisualOverflowFromTheme();
+
+ if (recompute_floats || CreatesNewFormattingContext() ||
+ HasSelfPaintingLayer())
+ AddVisualOverflowFromFloats();
+
+ if (VisualOverflowRect() != previous_visual_overflow_rect) {
+ if (Layer())
+ Layer()->SetNeedsCompositingInputsUpdate();
+ GetFrameView()->SetIntersectionObservationState(LocalFrameView::kDesired);
+ }
+}
+
void LayoutListItem::AddVisualOverflowFromChildren() {
LayoutBlockFlow::AddVisualOverflowFromChildren();
UpdateOverflow(Visual);
@@ -539,7 +556,7 @@ void LayoutListItem::OrdinalValueChanged() {
if (!marker_)
return;
marker_->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kListValueChange);
+ layout_invalidation_reason::kListValueChange);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_list_item.h b/chromium/third_party/blink/renderer/core/layout/layout_list_item.h
index e180df75cfd..e0d77368362 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_list_item.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_list_item.h
@@ -70,7 +70,9 @@ class LayoutListItem final : public LayoutBlockFlow {
void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
- void AddVisualOverflowFromChildren() override;
+ void ComputeVisualOverflow(const LayoutRect&, bool recompute_floats) final;
+
+ void AddVisualOverflowFromChildren();
void AddLayoutOverflowFromChildren() override;
void AlignMarkerInBlockDirection();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_list_marker.cc b/chromium/third_party/blink/renderer/core/layout/layout_list_marker.cc
index fff04ce2b25..9529cd96095 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_list_marker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_list_marker.cc
@@ -36,7 +36,7 @@ namespace blink {
const int kCMarkerPaddingPx = 7;
-// TODO(glebl): Move to WebKit/Source/core/css/html.css after
+// TODO(glebl): Move to core/html/resources/html.css after
// Blink starts to support ::marker crbug.com/457718
// Recommended UA margin for list markers.
const int kCUAMarkerMarginEm = 1;
@@ -84,9 +84,10 @@ void LayoutListMarker::StyleWillChange(StyleDifference diff,
const ComputedStyle& new_style) {
if (Style() &&
(new_style.ListStylePosition() != StyleRef().ListStylePosition() ||
- new_style.ListStyleType() != StyleRef().ListStyleType()))
+ new_style.ListStyleType() != StyleRef().ListStyleType())) {
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
+ }
LayoutBox::StyleWillChange(diff, new_style);
}
@@ -166,11 +167,12 @@ void LayoutListMarker::ImageChanged(WrappedImagePtr o, CanDeferInvalidation) {
return;
LayoutSize image_size = IsImage() ? ImageBulletSize() : LayoutSize();
- if (Size() != image_size || image_->ErrorOccurred())
+ if (Size() != image_size || image_->ErrorOccurred()) {
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kImageChanged);
- else
+ layout_invalidation_reason::kImageChanged);
+ } else {
SetShouldDoFullPaintInvalidation();
+ }
}
void LayoutListMarker::UpdateMarginsAndContent() {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_menu_list.cc b/chromium/third_party/blink/renderer/core/layout/layout_menu_list.cc
index b94bd3119a9..e92a4a30491 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_menu_list.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_menu_list.cc
@@ -153,7 +153,7 @@ void LayoutMenuList::AdjustInnerStyle(ComputedStyle& inner_style) const {
if (HasOptionStyleChanged(inner_style)) {
inner_block_->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
inner_style.SetDirection(option_style_->Direction());
inner_style.SetUnicodeBidi(option_style_->GetUnicodeBidi());
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.cc b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.cc
index 5fc48cc8d8a..f006da14466 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.cc
@@ -604,7 +604,7 @@ bool LayoutMultiColumnFlowThread::RemoveSpannerPlaceholderIfNoLongerValid(
// it for relayout.
spanner_object_in_flow_thread->ContainingBlock()
->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kColumnsChanged);
+ layout_invalidation_reason::kColumnsChanged);
// Now generate a column set for this ex-spanner, if needed and none is there
// for us already.
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.cc b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.cc
index a7ae1371f34..0adaeba0997 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.cc
@@ -29,6 +29,7 @@
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
#include "third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h"
#include "third_party/blink/renderer/core/paint/multi_column_set_painter.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
namespace blink {
@@ -520,6 +521,25 @@ LayoutRect LayoutMultiColumnSet::FragmentsBoundingBox(
return result;
}
+void LayoutMultiColumnSet::ComputeVisualOverflow(
+ const LayoutRect& previous_visual_overflow_rect,
+ bool recompute_floats) {
+ AddVisualOverflowFromChildren();
+
+ AddVisualEffectOverflow();
+ AddVisualOverflowFromTheme();
+
+ if (recompute_floats || CreatesNewFormattingContext() ||
+ HasSelfPaintingLayer())
+ AddVisualOverflowFromFloats();
+
+ if (VisualOverflowRect() != previous_visual_overflow_rect) {
+ if (Layer())
+ Layer()->SetNeedsCompositingInputsUpdate();
+ GetFrameView()->SetIntersectionObservationState(LocalFrameView::kDesired);
+ }
+}
+
void LayoutMultiColumnSet::AddVisualOverflowFromChildren() {
// It's useless to calculate overflow if we haven't determined the page
// logical height yet.
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.h b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.h
index 8dbe3d27d03..8e66f98b8f0 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.h
@@ -255,7 +255,9 @@ class CORE_EXPORT LayoutMultiColumnSet : public LayoutBlockFlow {
void PaintObject(const PaintInfo&,
const LayoutPoint& paint_offset) const override;
- void AddVisualOverflowFromChildren() override;
+ void ComputeVisualOverflow(const LayoutRect&, bool recompute_floats) final;
+
+ void AddVisualOverflowFromChildren();
void AddLayoutOverflowFromChildren() override;
MultiColumnFragmentainerGroupList fragmentainer_groups_;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.cc b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.cc
index 97f9fff388a..01c564f4009 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.cc
@@ -27,11 +27,7 @@ LayoutMultiColumnSpannerPlaceholder::CreateAnonymous(
new LayoutMultiColumnSpannerPlaceholder(&layout_object_in_flow_thread);
Document& document = layout_object_in_flow_thread.GetDocument();
new_spanner->SetDocumentForAnonymous(&document);
- scoped_refptr<ComputedStyle> new_style =
- ComputedStyle::CreateAnonymousStyleWithDisplay(parent_style,
- EDisplay::kBlock);
- CopyMarginProperties(*new_style, layout_object_in_flow_thread.StyleRef());
- new_spanner->SetStyle(new_style);
+ new_spanner->UpdateProperties(parent_style);
return new_spanner;
}
@@ -56,17 +52,20 @@ void LayoutMultiColumnSpannerPlaceholder::
// its containing block chain, we need to mark it here, or we risk that
// the object isn't laid out.
object_in_flow_thread->Parent()->SetNeedsLayout(
- LayoutInvalidationReason::kColumnsChanged);
+ layout_invalidation_reason::kColumnsChanged);
}
return;
}
- UpdateMarginProperties();
+ UpdateProperties(Parent()->StyleRef());
}
-void LayoutMultiColumnSpannerPlaceholder::UpdateMarginProperties() {
- scoped_refptr<ComputedStyle> new_style = ComputedStyle::Clone(StyleRef());
+void LayoutMultiColumnSpannerPlaceholder::UpdateProperties(
+ const ComputedStyle& parent_style) {
+ scoped_refptr<ComputedStyle> new_style =
+ ComputedStyle::CreateAnonymousStyleWithDisplay(parent_style,
+ EDisplay::kBlock);
CopyMarginProperties(*new_style, layout_object_in_flow_thread_->StyleRef());
- SetStyle(new_style);
+ SetStyle(std::move(new_style));
}
void LayoutMultiColumnSpannerPlaceholder::InsertedIntoTree() {
@@ -74,7 +73,7 @@ void LayoutMultiColumnSpannerPlaceholder::InsertedIntoTree() {
// The object may previously have been laid out as a non-spanner, but since
// it's a spanner now, it needs to be relaid out.
layout_object_in_flow_thread_->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kColumnsChanged);
+ layout_invalidation_reason::kColumnsChanged);
}
void LayoutMultiColumnSpannerPlaceholder::WillBeRemovedFromTree() {
@@ -85,7 +84,7 @@ void LayoutMultiColumnSpannerPlaceholder::WillBeRemovedFromTree() {
// might live on. Since it's not a spanner anymore, it needs to be relaid
// out.
ex_spanner->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kColumnsChanged);
+ layout_invalidation_reason::kColumnsChanged);
}
LayoutBox::WillBeRemovedFromTree();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h
index 41fcd594689..b1705d538f7 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h
@@ -42,8 +42,10 @@ class LayoutMultiColumnSpannerPlaceholder final : public LayoutBox {
SetChildNeedsLayout(kMarkOnlyThis);
}
+ bool AnonymousHasStylePropagationOverride() final { return true; }
+
void LayoutObjectInFlowThreadStyleDidChange(const ComputedStyle* old_style);
- void UpdateMarginProperties();
+ void UpdateProperties(const ComputedStyle& parent_style);
const char* GetName() const override {
return "LayoutMultiColumnSpannerPlaceholder";
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object.cc b/chromium/third_party/blink/renderer/core/layout/layout_object.cc
index ad740b0df26..3bb45426382 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object.cc
@@ -94,7 +94,7 @@
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/core/paint/paint_tracker.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.h"
#include "third_party/blink/renderer/core/style/content_data.h"
#include "third_party/blink/renderer/core/style/cursor_data.h"
@@ -747,21 +747,24 @@ LayoutBox* LayoutObject::EnclosingBox() const {
return nullptr;
}
-LayoutBlockFlow* LayoutObject::EnclosingNGBlockFlow() const {
+LayoutBlockFlow* LayoutObject::ContainingNGBlockFlow() const {
+ DCHECK(IsInline());
if (!RuntimeEnabledFeatures::LayoutNGEnabled())
return nullptr;
- LayoutBox* box = EnclosingBox();
- DCHECK(box);
-#if DCHECK_IS_ON()
- if (NGBlockNode::CanUseNewLayout(*box))
- DCHECK(box->IsLayoutBlockFlow());
-#endif
- return NGBlockNode::CanUseNewLayout(*box) ? ToLayoutBlockFlow(box) : nullptr;
+ if (LayoutObject* parent = Parent()) {
+ LayoutBox* box = parent->EnclosingBox();
+ DCHECK(box);
+ if (NGBlockNode::CanUseNewLayout(*box)) {
+ DCHECK(box->IsLayoutBlockFlow());
+ return ToLayoutBlockFlow(box);
+ }
+ }
+ return nullptr;
}
-const NGPhysicalBoxFragment* LayoutObject::EnclosingBlockFlowFragment() const {
+const NGPhysicalBoxFragment* LayoutObject::ContainingBlockFlowFragment() const {
DCHECK(IsInline() || IsText());
- LayoutBlockFlow* const block_flow = EnclosingNGBlockFlow();
+ LayoutBlockFlow* const block_flow = ContainingNGBlockFlow();
if (!block_flow || !block_flow->ChildrenInline())
return nullptr;
// TODO(kojii): CurrentFragment isn't always available after layout clean.
@@ -909,7 +912,7 @@ void LayoutObject::MarkContainerChainForLayout(bool schedule_relayout,
object->SetNeedsCollectInlines(true);
while (object) {
- if (object->SelfNeedsLayout())
+ if (object->SelfNeedsLayout() || object->LayoutBlockedByDisplayLock())
return;
// Don't mark the outermost object of an unrooted subtree. That object will
@@ -1090,12 +1093,12 @@ FloatRect LayoutObject::AbsoluteBoundingBoxFloatRect(
Vector<FloatQuad> quads;
AbsoluteQuads(quads, flags);
- size_t n = quads.size();
+ wtf_size_t n = quads.size();
if (n == 0)
return FloatRect();
FloatRect result = quads[0].BoundingBox();
- for (size_t i = 1; i < n; ++i)
+ for (wtf_size_t i = 1; i < n; ++i)
result.Unite(quads[i].BoundingBox());
return result;
}
@@ -1104,12 +1107,12 @@ IntRect LayoutObject::AbsoluteBoundingBoxRect(MapCoordinatesFlags flags) const {
Vector<FloatQuad> quads;
AbsoluteQuads(quads, flags);
- size_t n = quads.size();
+ wtf_size_t n = quads.size();
if (!n)
return IntRect();
IntRect result = quads[0].EnclosingBoundingBox();
- for (size_t i = 1; i < n; ++i)
+ for (wtf_size_t i = 1; i < n; ++i)
result.Unite(quads[i].EnclosingBoundingBox());
return result;
}
@@ -1119,12 +1122,12 @@ IntRect LayoutObject::AbsoluteBoundingBoxRectIgnoringTransforms() const {
Vector<IntRect> rects;
AbsoluteRects(rects, FlooredLayoutPoint(abs_pos));
- size_t n = rects.size();
+ wtf_size_t n = rects.size();
if (!n)
return IntRect();
IntRect result = rects[0];
- for (size_t i = 1; i < n; ++i)
+ for (wtf_size_t i = 1; i < n; ++i)
result.Unite(rects[i]);
return result;
}
@@ -1447,7 +1450,7 @@ bool LayoutObject::HasDistortingVisualEffects() const {
// No filters, no blends, no opacity < 100%.
for (const auto* effect = SafeUnalias(paint_properties.Effect()); effect;
effect = SafeUnalias(effect->Parent())) {
- if (!effect->Filter().IsEmpty() ||
+ if (!effect->Filter().IsEmpty() || !effect->BackdropFilter().IsEmpty() ||
effect->GetColorFilter() != kColorFilterNone ||
effect->BlendMode() != SkBlendMode::kSrcOver ||
effect->Opacity() != 1.0) {
@@ -1744,7 +1747,8 @@ void LayoutObject::DirtyLinesFromChangedChild(LayoutObject*, MarkingBehavior) {}
std::ostream& operator<<(std::ostream& out, const LayoutObject& object) {
StringBuilder string_builder;
object.DumpLayoutObject(string_builder, false, 0);
- return out << string_builder.ToString().Utf8().data();
+ return out << static_cast<const void*>(&object) << ":"
+ << string_builder.ToString().Utf8().data();
}
std::ostream& operator<<(std::ostream& out, const LayoutObject* object) {
@@ -1965,7 +1969,7 @@ void LayoutObject::FirstLineStyleDidChange(const ComputedStyle& old_style,
first_line_container->SetShouldDoFullPaintInvalidationForFirstLine();
}
if (diff.NeedsLayout())
- SetNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayoutAndPrefWidthsRecalc(layout_invalidation_reason::kStyleChange);
}
void LayoutObject::MarkContainerChainForOverflowRecalcIfNeeded() {
@@ -2072,10 +2076,12 @@ void LayoutObject::SetStyle(scoped_refptr<ComputedStyle> style) {
StyleDifference updated_diff = AdjustStyleDifference(diff);
if (!diff.NeedsFullLayout()) {
- if (updated_diff.NeedsFullLayout())
- SetNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::kStyleChange);
- else if (updated_diff.NeedsPositionedMovementLayout())
+ if (updated_diff.NeedsFullLayout()) {
+ SetNeedsLayoutAndPrefWidthsRecalc(
+ layout_invalidation_reason::kStyleChange);
+ } else if (updated_diff.NeedsPositionedMovementLayout()) {
SetNeedsPositionedMovementLayout();
+ }
}
if (diff.TransformChanged() && !NeedsLayout()) {
@@ -2085,10 +2091,12 @@ void LayoutObject::SetStyle(scoped_refptr<ComputedStyle> style) {
if (diff.NeedsRecomputeOverflow() && !NeedsLayout()) {
// TODO(rhogan): Make inlines capable of recomputing overflow too.
- if (IsLayoutBlock())
+ if (IsLayoutBlock()) {
SetNeedsOverflowRecalc();
- else
- SetNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::kStyleChange);
+ } else {
+ SetNeedsLayoutAndPrefWidthsRecalc(
+ layout_invalidation_reason::kStyleChange);
+ }
}
if (diff.NeedsPaintInvalidationSubtree() ||
@@ -2142,6 +2150,12 @@ void LayoutObject::StyleWillChange(StyleDifference diff,
}
}
+ if (diff.TextDecorationOrColorChanged() ||
+ style_->InsideLink() != new_style.InsideLink()) {
+ if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
+ cache->TextChanged(this);
+ }
+
if (diff.TransformChanged()) {
if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
cache->LocationChanged(this);
@@ -2289,7 +2303,7 @@ void LayoutObject::StyleDidChange(StyleDifference diff,
old_style->GetPosition() != style_->GetPosition())
MarkContainerChainForOverflowRecalcIfNeeded();
- SetNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayoutAndPrefWidthsRecalc(layout_invalidation_reason::kStyleChange);
} else if (diff.NeedsPositionedMovementLayout()) {
SetNeedsPositionedMovementLayout();
}
@@ -2315,7 +2329,7 @@ void LayoutObject::StyleDidChange(StyleDifference diff,
if (ResolveColor(*old_style, GetCSSPropertyBackgroundColor()) !=
ResolveColor(GetCSSPropertyBackgroundColor()) ||
old_style->BackgroundLayers() != StyleRef().BackgroundLayers())
- SetBackgroundChangedSinceLastPaintInvalidation();
+ SetBackgroundNeedsFullPaintInvalidation();
}
if (old_style && old_style->StyleType() == kPseudoIdNone)
@@ -2352,7 +2366,7 @@ void LayoutObject::ApplyFirstLineChanges(const ComputedStyle& old_style) {
}
}
}
- SetNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayoutAndPrefWidthsRecalc(layout_invalidation_reason::kStyleChange);
}
void LayoutObject::PropagateStyleToAnonymousChildren() {
@@ -2362,7 +2376,6 @@ void LayoutObject::PropagateStyleToAnonymousChildren() {
child = child->NextSibling()) {
if (!child->IsAnonymous() || child->StyleRef().StyleType() != kPseudoIdNone)
continue;
-
if (child->AnonymousHasStylePropagationOverride())
continue;
@@ -2384,6 +2397,32 @@ void LayoutObject::PropagateStyleToAnonymousChildren() {
child->SetStyle(std::move(new_style));
}
+
+ if (StyleRef().StyleType() == kPseudoIdNone)
+ return;
+
+ // Propagate style from pseudo elements to generated content. We skip children
+ // with pseudo element StyleType() in the for-loop above and skip over
+ // descendants which are not generated content in this subtree traversal.
+ //
+ // TODO(futhark): It's possible we could propagate anonymous style from pseudo
+ // elements through anonymous table layout objects in the recursive
+ // implementation above, but it would require propagating the StyleType()
+ // somehow because there is code relying on generated content having a certain
+ // StyleType().
+ LayoutObject* child = NextInPreOrder(this);
+ while (child) {
+ if (!child->IsAnonymous()) {
+ // Don't propagate into non-anonymous descendants of pseudo elements. This
+ // can typically happen for ::first-letter inside ::before. The
+ // ::first-letter will propagate to its anonymous children separately.
+ child = child->NextInPreOrderAfterChildren(this);
+ continue;
+ }
+ if (child->IsText() || child->IsQuote() || child->IsImage())
+ child->SetPseudoStyle(MutableStyle());
+ child = child->NextInPreOrder(this);
+ }
}
void LayoutObject::SetStyleWithWritingModeOf(scoped_refptr<ComputedStyle> style,
@@ -2752,7 +2791,7 @@ void LayoutObject::LocalToAncestorRects(Vector<LayoutRect>& rects,
const LayoutBoxModelObject* ancestor,
const LayoutPoint& pre_offset,
const LayoutPoint& post_offset) const {
- for (size_t i = 0; i < rects.size(); ++i) {
+ for (wtf_size_t i = 0; i < rects.size(); ++i) {
LayoutRect& rect = rects[i];
rect.MoveBy(pre_offset);
FloatQuad container_quad =
@@ -2901,7 +2940,7 @@ void LayoutObject::AddLayerHitTestRects(
// testing.
// FIXME: This limit needs to be low due to the O(n^2) algorithm in
// ScrollingCoordinator::SetTouchEventTargetRects() - crbug.com/300282.
- const size_t kMaxRectsPerLayer = 100;
+ const wtf_size_t kMaxRectsPerLayer = 100;
LayerHitTestRects::iterator iter = layer_rects.find(current_layer);
Vector<HitTestRect>* iter_value;
@@ -2913,7 +2952,7 @@ void LayoutObject::AddLayerHitTestRects(
}
TouchAction whitelisted_touch_action =
StyleRef().GetEffectiveTouchAction() & supported_fast_actions;
- for (size_t i = 0; i < own_rects.size(); i++) {
+ for (wtf_size_t i = 0; i < own_rects.size(); i++) {
// If we have a different touch action than the container the rect needs to
// be reported even if it is contained.
if (whitelisted_touch_action != container_whitelisted_touch_action ||
@@ -3227,9 +3266,9 @@ void LayoutObject::WillBeRemovedFromTree() {
FindReferencingScrollAnchors(this, kClear);
}
- if (RuntimeEnabledFeatures::PaintTrackingEnabled()) {
+ if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
if (LocalFrameView* frame_view = GetFrameView()) {
- frame_view->GetPaintTracker().NotifyNodeRemoved(*this);
+ frame_view->GetPaintTimingDetector().NotifyNodeRemoved(*this);
}
}
}
@@ -3945,8 +3984,10 @@ void LayoutObject::ClearPaintInvalidationFlags() {
DCHECK(!ShouldCheckForPaintInvalidation() || PaintInvalidationStateIsDirty());
#endif
fragment_.SetPartialInvalidationLocalRect(LayoutRect());
- if (!ShouldDelayFullPaintInvalidation())
+ if (!ShouldDelayFullPaintInvalidation()) {
full_paint_invalidation_reason_ = PaintInvalidationReason::kNone;
+ bitfields_.SetBackgroundNeedsFullPaintInvalidation(false);
+ }
bitfields_.SetShouldCheckForPaintInvalidation(false);
bitfields_.SetSubtreeShouldCheckForPaintInvalidation(false);
bitfields_.SetSubtreeShouldDoFullPaintInvalidation(false);
@@ -3954,12 +3995,11 @@ void LayoutObject::ClearPaintInvalidationFlags() {
bitfields_.SetNeedsPaintOffsetAndVisualRectUpdate(false);
bitfields_.SetDescendantNeedsPaintOffsetAndVisualRectUpdate(false);
bitfields_.SetShouldInvalidateSelection(false);
- bitfields_.SetBackgroundChangedSinceLastPaintInvalidation(false);
}
#if DCHECK_IS_ON()
bool LayoutObject::PaintInvalidationStateIsDirty() const {
- return BackgroundChangedSinceLastPaintInvalidation() ||
+ return BackgroundNeedsFullPaintInvalidation() ||
ShouldCheckForPaintInvalidation() || ShouldInvalidateSelection() ||
NeedsPaintOffsetAndVisualRectUpdate() ||
DescendantNeedsPaintOffsetAndVisualRectUpdate() ||
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object.h b/chromium/third_party/blink/renderer/core/layout/layout_object.h
index d398e47ab4e..fecff01ceae 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object.h
@@ -30,6 +30,7 @@
#include "base/auto_reset.h"
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/document_lifecycle.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -332,12 +333,15 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
LayoutBox* EnclosingScrollableBox() const;
- // Returns |EnclosingBox()| if it's a LayoutNGBlockFlow, or nullptr otherwise.
- LayoutBlockFlow* EnclosingNGBlockFlow() const;
+ // Returns the containing block flow if it's a LayoutNGBlockFlow, or nullptr
+ // otherwise. Note that the semantics is different from |EnclosingBox| for
+ // atomic inlines that this function returns the container, while
+ // |EnclosingBox| returns the atomic inline itself.
+ LayoutBlockFlow* ContainingNGBlockFlow() const;
- // Returns |NGPhysicalBoxFragment| for |EnclosingNGBlockFlow()| or nullptr
+ // Returns |NGPhysicalBoxFragment| for |ContainingNGBlockFlow()| or nullptr
// otherwise.
- const NGPhysicalBoxFragment* EnclosingBlockFlowFragment() const;
+ const NGPhysicalBoxFragment* ContainingBlockFlowFragment() const;
// Function to return our enclosing flow thread if we are contained inside
// one. This function follows the containing block chain.
@@ -364,21 +368,24 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
void AssertLaidOut() const {
#ifndef NDEBUG
- if (NeedsLayout())
+ if (NeedsLayout() && !LayoutBlockedByDisplayLock())
ShowLayoutTreeForThis();
#endif
- SECURITY_DCHECK(!NeedsLayout());
+ SECURITY_DCHECK(!NeedsLayout() || LayoutBlockedByDisplayLock());
}
void AssertSubtreeIsLaidOut() const {
for (const LayoutObject* layout_object = this; layout_object;
- layout_object = layout_object->NextInPreOrder())
+ layout_object = layout_object->LayoutBlockedByDisplayLock()
+ ? layout_object->NextInPreOrderAfterChildren()
+ : layout_object->NextInPreOrder()) {
layout_object->AssertLaidOut();
+ }
}
void AssertClearedPaintInvalidationFlags() const {
#ifndef NDEBUG
- if (PaintInvalidationStateIsDirty()) {
+ if (PaintInvalidationStateIsDirty() && !PrePaintBlockedByDisplayLock()) {
ShowLayoutTreeForThis();
NOTREACHED();
}
@@ -387,8 +394,11 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
void AssertSubtreeClearedPaintInvalidationFlags() const {
for (const LayoutObject* layout_object = this; layout_object;
- layout_object = layout_object->NextInPreOrder())
+ layout_object = layout_object->PrePaintBlockedByDisplayLock()
+ ? layout_object->NextInPreOrderAfterChildren()
+ : layout_object->NextInPreOrder()) {
layout_object->AssertClearedPaintInvalidationFlags();
+ }
}
#endif
@@ -465,6 +475,13 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
(!IsInline() || IsAtomicInlineLevel()) && !IsRubyText() &&
(!IsTablePart() || IsTableCaption()) && !IsTable();
}
+ inline bool ShouldApplyStyleContainment() const {
+ return StyleRef().ContainsStyle();
+ }
+ inline bool ShouldApplyContentContainment() const {
+ return ShouldApplyPaintContainment() && ShouldApplyLayoutContainment() &&
+ ShouldApplyStyleContainment();
+ }
private:
//////////////////////////////////////////
@@ -639,8 +656,9 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
}
// isBody is called from LayoutBox::styleWillChange and is thus quite hot.
bool IsBody() const {
- return GetNode() && GetNode()->HasTagName(HTMLNames::bodyTag);
+ return GetNode() && GetNode()->HasTagName(html_names::kBodyTag);
}
+
bool IsHR() const;
bool IsTablePart() const {
@@ -685,9 +703,10 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
}
void SetAncestorLineBoxDirty(bool value = true) {
bitfields_.SetAncestorLineBoxDirty(value);
- if (value)
+ if (value) {
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kLineBoxesChanged);
+ layout_invalidation_reason::kLineBoxesChanged);
+ }
}
void SetIsInsideFlowThreadIncludingDescendants(bool);
@@ -746,8 +765,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
bool IsBlendingAllowed() const {
return !IsSVG() || IsSVGShape() || IsSVGImage() || IsSVGText() ||
IsSVGInline() || IsSVGRoot() || IsSVGForeignObject() ||
- // TODO(pdr): According to the current spec, blending should apply to
- // hidden containers (e.g. pattern).
+ // Blending does not apply to non-renderable elements such as
+ // patterns (see: https://github.com/w3c/fxtf-drafts/issues/309).
(IsSVGContainer() && !IsSVGHiddenContainer());
}
virtual bool HasNonIsolatedBlendingDescendants() const {
@@ -994,6 +1013,12 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
return bitfields_.IsEffectiveRootScroller();
}
+ // Returns true if the given object is the global root scroller. See
+ // |global root scroller| in page/scrolling/README.md.
+ bool IsGlobalRootScroller() const {
+ return bitfields_.IsGlobalRootScroller();
+ }
+
// Return true if this is the "rendered legend" of a fieldset. They get
// special treatment, in that they establish a new formatting context, and
// shrink to fit if no logical width is specified.
@@ -1231,6 +1256,9 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
void SetIsEffectiveRootScroller(bool is_effective_root_scroller) {
bitfields_.SetIsEffectiveRootScroller(is_effective_root_scroller);
}
+ void SetIsGlobalRootScroller(bool is_global_root_scroller) {
+ bitfields_.SetIsGlobalRootScroller(is_global_root_scroller);
+ }
virtual void Paint(const PaintInfo&) const;
@@ -1772,6 +1800,11 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
: NGOutlineType::kDontIncludeBlockVisualOverflow;
}
+ // Only public for LayoutNG.
+ void SetContainsInlineWithOutlineAndContinuation(bool b) {
+ bitfields_.SetContainsInlineWithOutlineAndContinuation(b);
+ }
+
// Collects rectangles enclosing visual overflows of the DOM subtree under
// this object.
// The rects also cover continuations which may be not in the layout subtree
@@ -1814,6 +1847,16 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
}
return false;
}
+ // Indicates that the paint of the object should be fully invalidated.
+ // We will repaint the object, and reraster the area on the composited layer
+ // where the object shows. Note that this function doesn't automatically
+ // cause invalidation of background painted on the scrolling contents layer
+ // because we don't want to invalidate the whole scrolling contents layer on
+ // non-background changes. It's also not safe to specially handle
+ // PaintInvalidationReason::kBackground in paint invalidator because we don't
+ // track paint invalidation reasons separately. To indicate that the
+ // background needs full invalidation, use
+ // SetBackgroundNeedsFullPaintInvalidation().
void SetShouldDoFullPaintInvalidation(
PaintInvalidationReason = PaintInvalidationReason::kFull);
void SetShouldDoFullPaintInvalidationWithoutGeometryChange(
@@ -1915,6 +1958,9 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
return TouchAction::kTouchActionNone;
return StyleRef().GetEffectiveTouchAction();
}
+ bool HasEffectiveWhitelistedTouchAction() const {
+ return EffectiveWhitelistedTouchAction() != TouchAction::kTouchActionAuto;
+ }
// Whether this object's Node has a blocking touch event handler on itself
// or an ancestor.
@@ -1964,8 +2010,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
layout_object_.SetShouldDoFullPaintInvalidationWithoutGeometryChange(
reason);
}
- void SetBackgroundChangedSinceLastPaintInvalidation() {
- layout_object_.SetBackgroundChangedSinceLastPaintInvalidation();
+ void SetBackgroundNeedsFullPaintInvalidation() {
+ layout_object_.SetBackgroundNeedsFullPaintInvalidation();
}
void SetShouldDelayFullPaintInvalidation() {
layout_object_.SetShouldDelayFullPaintInvalidation();
@@ -2108,11 +2154,14 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
return bitfields_.IsBackgroundAttachmentFixedObject();
}
- bool BackgroundChangedSinceLastPaintInvalidation() const {
- return bitfields_.BackgroundChangedSinceLastPaintInvalidation();
+ bool BackgroundNeedsFullPaintInvalidation() const {
+ return !ShouldDelayFullPaintInvalidation() &&
+ bitfields_.BackgroundNeedsFullPaintInvalidation();
}
- void SetBackgroundChangedSinceLastPaintInvalidation() {
- bitfields_.SetBackgroundChangedSinceLastPaintInvalidation(true);
+ void SetBackgroundNeedsFullPaintInvalidation() {
+ SetShouldDoFullPaintInvalidationWithoutGeometryChange(
+ PaintInvalidationReason::kBackground);
+ bitfields_.SetBackgroundNeedsFullPaintInvalidation(true);
}
bool OutlineMayBeAffectedByDescendants() const {
@@ -2139,6 +2188,31 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
bitfields_.SetOutlineMayBeAffectedByDescendants(b);
}
+ bool LayoutBlockedByDisplayLock() const {
+ auto* context = GetDisplayLockContext();
+ return context && !context->ShouldLayout();
+ }
+
+ bool PrePaintBlockedByDisplayLock() const {
+ auto* context = GetDisplayLockContext();
+ return context && !context->ShouldPrePaint();
+ }
+
+ bool PaintBlockedByDisplayLock() const {
+ auto* context = GetDisplayLockContext();
+ return context && !context->ShouldPaint();
+ }
+
+ void NotifyDisplayLockDidPrePaint() const {
+ if (auto* context = GetDisplayLockContext())
+ context->DidPrePaint();
+ }
+
+ void NotifyDisplayLockDidPaint() const {
+ if (auto* context = GetDisplayLockContext())
+ context->DidPaint();
+ }
+
protected:
enum LayoutObjectType {
kLayoutObjectBr,
@@ -2302,10 +2376,6 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// LayoutFlowThread.
void RemoveFromLayoutFlowThread();
- void SetContainsInlineWithOutlineAndContinuation(bool b) {
- bitfields_.SetContainsInlineWithOutlineAndContinuation(b);
- }
-
void SetPreviousOutlineMayBeAffectedByDescendants(bool b) {
bitfields_.SetPreviousOutlineMayBeAffectedByDescendants(b);
}
@@ -2321,6 +2391,11 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
LayoutSize OffsetFromScrollableContainer(const LayoutObject*,
bool ignore_scroll_offset) const;
+ void NotifyDisplayLockDidLayout() {
+ if (auto* context = GetDisplayLockContext())
+ context->DidLayout();
+ }
+
private:
// Used only by applyFirstLineChanges to get a first line style based off of a
// given new style, without accessing the cache.
@@ -2404,6 +2479,14 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
}
LayoutRect AdjustVisualRectForInlineBox(const LayoutRect&) const;
+ DisplayLockContext* GetDisplayLockContext() const {
+ if (!RuntimeEnabledFeatures::DisplayLockingEnabled())
+ return nullptr;
+ if (!GetNode() || !GetNode()->IsElementNode())
+ return nullptr;
+ return ToElement(GetNode())->GetDisplayLockContext();
+ }
+
// This is set by Set[Subtree]ShouldDoFullPaintInvalidation, and cleared
// during PrePaint in this object's InvalidatePaint(). It's different from
// DisplayItemClient::GetPaintInvalidationReason() which is set during
@@ -2512,7 +2595,7 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
is_scroll_anchor_object_(false),
scroll_anchor_disabling_style_changed_(false),
has_box_decoration_background_(false),
- background_changed_since_last_paint_invalidation_(true),
+ background_needs_full_paint_invalidation_(true),
outline_may_be_affected_by_descendants_(false),
previous_outline_may_be_affected_by_descendants_(false),
is_truncated_(false),
@@ -2520,6 +2603,7 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
effective_whitelisted_touch_action_changed_(true),
descendant_effective_whitelisted_touch_action_changed_(false),
is_effective_root_scroller_(false),
+ is_global_root_scroller_(false),
positioned_state_(kIsStaticallyPositioned),
selection_state_(static_cast<unsigned>(SelectionState::kNone)),
background_obscuration_state_(kBackgroundObscurationStatusInvalid),
@@ -2724,8 +2808,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
ADD_BOOLEAN_BITFIELD(has_box_decoration_background_,
HasBoxDecorationBackground);
- ADD_BOOLEAN_BITFIELD(background_changed_since_last_paint_invalidation_,
- BackgroundChangedSinceLastPaintInvalidation);
+ ADD_BOOLEAN_BITFIELD(background_needs_full_paint_invalidation_,
+ BackgroundNeedsFullPaintInvalidation);
// Whether shape of outline may be affected by any descendants. This is
// updated before paint invalidation, checked during paint invalidation.
@@ -2756,7 +2840,10 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
ADD_BOOLEAN_BITFIELD(descendant_effective_whitelisted_touch_action_changed_,
DescendantEffectiveWhitelistedTouchActionChanged);
+ // See page/scrolling/README.md for an explanation of root scroller and how
+ // it works.
ADD_BOOLEAN_BITFIELD(is_effective_root_scroller_, IsEffectiveRootScroller);
+ ADD_BOOLEAN_BITFIELD(is_global_root_scroller_, IsGlobalRootScroller);
private:
// This is the cached 'position' value of this object
@@ -2917,11 +3004,11 @@ inline void LayoutObject::SetNeedsLayout(
bool already_needed_layout = bitfields_.SelfNeedsLayout();
SetSelfNeedsLayout(true);
MarkContainerNeedsCollectInlines();
- if (!already_needed_layout) {
+ if (!already_needed_layout && !LayoutBlockedByDisplayLock()) {
TRACE_EVENT_INSTANT1(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"LayoutInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorLayoutInvalidationTrackingEvent::Data(this, reason));
+ inspector_layout_invalidation_tracking_event::Data(this, reason));
if (mark_parents == kMarkContainerChain &&
(!layouter || layouter->Root() != this))
MarkContainerChainForLayout(!layouter, layouter);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object_child_list.cc b/chromium/third_party/blink/renderer/core/layout/layout_object_child_list.cc
index 6dd333bebe7..a520da71068 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object_child_list.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object_child_list.cc
@@ -31,7 +31,6 @@
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h"
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
namespace blink {
@@ -45,8 +44,8 @@ namespace {
void InvalidateInlineItems(LayoutObject* object) {
if (object->IsInLayoutNGInlineFormattingContext())
object->SetFirstInlineFragment(nullptr);
- if (object->IsLayoutNGText()) {
- ToLayoutNGText(object)->InvalidateInlineItems();
+ if (object->IsText()) {
+ ToLayoutText(object)->InvalidateInlineItems();
} else if (object->IsLayoutInline()) {
// When moving without |notify_layout_object|, only top-level objects are
// moved. Ensure to invalidate all LayoutNGText in this inline formatting
@@ -92,9 +91,10 @@ LayoutObject* LayoutObjectChildList::RemoveChildNode(
// flow child got yanked or that a positioned child got yanked). We also
// issue paint invalidations, so that the area exposed when the child
// disappears gets paint invalidated properly.
- if (notify_layout_object && old_child->EverHadLayout())
+ if (notify_layout_object && old_child->EverHadLayout()) {
old_child->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kRemovedFromLayout);
+ layout_invalidation_reason::kRemovedFromLayout);
+ }
InvalidatePaintOnRemoval(*old_child);
}
@@ -212,7 +212,7 @@ void LayoutObjectChildList::InsertChildNode(LayoutObject* owner,
new_child->ClearNeedsCollectInlines();
new_child->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kAddedToLayout);
+ layout_invalidation_reason::kAddedToLayout);
new_child->SetShouldDoFullPaintInvalidation(
PaintInvalidationReason::kAppeared);
new_child->AddSubtreePaintPropertyUpdateReason(
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_object_test.cc
index 78c066b8917..d74784be9e0 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object_test.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
@@ -22,6 +23,7 @@
namespace blink {
using testing::Return;
+using testing::MatchesRegex;
class LayoutObjectTest : public RenderingTest {
public:
@@ -54,8 +56,8 @@ TEST_F(LayoutObjectTest, LayoutDecoratedNameCalledWithPositionedObject) {
DCHECK(div);
LayoutObject* obj = div->GetLayoutObject();
DCHECK(obj);
- EXPECT_STREQ("LayoutBlockFlow (positioned)",
- obj->DecoratedName().Ascii().data());
+ EXPECT_THAT(obj->DecoratedName().Ascii().data(),
+ MatchesRegex("LayoutN?G?BlockFlow \\(positioned\\)"));
}
// Some display checks.
@@ -327,8 +329,8 @@ TEST_F(LayoutObjectTest, MutableForPaintingClearPaintFlags) {
EXPECT_TRUE(object->MayNeedPaintInvalidationAnimatedBackgroundImage());
object->SetShouldInvalidateSelection();
EXPECT_TRUE(object->ShouldInvalidateSelection());
- object->SetBackgroundChangedSinceLastPaintInvalidation();
- EXPECT_TRUE(object->BackgroundChangedSinceLastPaintInvalidation());
+ object->SetBackgroundNeedsFullPaintInvalidation();
+ EXPECT_TRUE(object->BackgroundNeedsFullPaintInvalidation());
object->SetNeedsPaintPropertyUpdate();
EXPECT_TRUE(object->NeedsPaintPropertyUpdate());
EXPECT_TRUE(object->Parent()->DescendantNeedsPaintPropertyUpdate());
@@ -343,7 +345,7 @@ TEST_F(LayoutObjectTest, MutableForPaintingClearPaintFlags) {
EXPECT_FALSE(object->SubtreeShouldCheckForPaintInvalidation());
EXPECT_FALSE(object->MayNeedPaintInvalidationAnimatedBackgroundImage());
EXPECT_FALSE(object->ShouldInvalidateSelection());
- EXPECT_FALSE(object->BackgroundChangedSinceLastPaintInvalidation());
+ EXPECT_FALSE(object->BackgroundNeedsFullPaintInvalidation());
EXPECT_FALSE(object->NeedsPaintPropertyUpdate());
EXPECT_FALSE(object->DescendantNeedsPaintPropertyUpdate());
}
@@ -465,7 +467,7 @@ TEST_F(LayoutObjectTest, AssociatedLayoutObjectOfFirstLetterSplit) {
Node* first_letter = sample->firstChild();
// Split "abc" into "a" "bc"
ToText(first_letter)->splitText(1, ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const LayoutTextFragment* layout_object0 =
ToLayoutTextFragment(AssociatedLayoutObjectOf(*first_letter, 0));
@@ -565,7 +567,7 @@ TEST_F(LayoutObjectTest, DisplayContentsAddInlineWrapper) {
ExpectAnonymousInlineWrapperFor<false>(text);
div->SetInlineStyleProperty(CSSPropertyColor, "pink");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ExpectAnonymousInlineWrapperFor<true>(text);
}
@@ -578,7 +580,7 @@ TEST_F(LayoutObjectTest, DisplayContentsRemoveInlineWrapper) {
ExpectAnonymousInlineWrapperFor<true>(text);
div->RemoveInlineStyleProperty(CSSPropertyColor);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ExpectAnonymousInlineWrapperFor<false>(text);
}
@@ -618,7 +620,7 @@ TEST_F(LayoutObjectTest, DisplayContentsWrapperInTable) {
ExpectAnonymousInlineWrapperFor<true>(contents->firstChild());
none->SetInlineStyleProperty(CSSPropertyDisplay, "inline");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(none->GetLayoutObject());
LayoutObject* inline_parent = none->GetLayoutObject()->Parent();
ASSERT_TRUE(inline_parent);
@@ -644,7 +646,7 @@ TEST_F(LayoutObjectTest, DisplayContentsWrapperInTableSection) {
ExpectAnonymousInlineWrapperFor<true>(contents->firstChild());
none->SetInlineStyleProperty(CSSPropertyDisplay, "inline");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(none->GetLayoutObject());
LayoutObject* inline_parent = none->GetLayoutObject()->Parent();
ASSERT_TRUE(inline_parent);
@@ -670,7 +672,7 @@ TEST_F(LayoutObjectTest, DisplayContentsWrapperInTableRow) {
ExpectAnonymousInlineWrapperFor<true>(contents->firstChild());
none->SetInlineStyleProperty(CSSPropertyDisplay, "inline");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(none->GetLayoutObject());
LayoutObject* inline_parent = none->GetLayoutObject()->Parent();
ASSERT_TRUE(inline_parent);
@@ -697,7 +699,7 @@ TEST_F(LayoutObjectTest, DisplayContentsWrapperInTableCell) {
ExpectAnonymousInlineWrapperFor<true>(contents->firstChild());
none->SetInlineStyleProperty(CSSPropertyDisplay, "inline");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(none->GetLayoutObject());
EXPECT_EQ(cell->GetLayoutObject(), none->GetLayoutObject()->Parent());
}
@@ -719,9 +721,9 @@ lime'>
StringBuilder result;
block->DumpLayoutObject(result, false, 0);
- EXPECT_EQ(
- result.ToString(),
- String("LayoutBlockFlow\tDIV id=\"block\" style=\"background:\\nlime\""));
+ EXPECT_THAT(result.ToString().Utf8().data(),
+ MatchesRegex("LayoutN?G?BlockFlow\tDIV id=\"block\" "
+ "style=\"background:\\\\nlime\""));
result.Clear();
text->DumpLayoutObject(result, false, 0);
@@ -744,7 +746,7 @@ TEST_F(LayoutObjectTest, DisplayContentsSVGGElementInHTML) {
svg_element->appendChild(text);
span->appendChild(svg_element);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_FALSE(svg_element->GetLayoutObject());
ASSERT_FALSE(text->GetLayoutObject());
@@ -763,7 +765,7 @@ TEST_F(LayoutObjectTest, HasDistortingVisualEffects) {
<div class=inner></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* outer = GetDocument().getElementById("opaque");
Element* inner = outer->QuerySelector(".inner");
@@ -810,7 +812,8 @@ TEST_F(LayoutObjectTest, DistortingVisualEffectsUnaliases) {
class LayoutObjectSimTest : public SimTest {
public:
bool DocumentHasTouchActionRegion(const EventHandlerRegistry& registry) {
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
return registry.HasEventHandlers(
EventHandlerRegistry::EventHandlerClass::kTouchAction);
}
@@ -884,20 +887,22 @@ TEST_F(LayoutObjectSimTest, HitTestForOcclusionInIframe) {
<div id='target'>target</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
Element* iframe_element = GetDocument().QuerySelector("iframe");
HTMLFrameOwnerElement* frame_owner_element =
ToHTMLFrameOwnerElement(iframe_element);
Document* iframe_doc = frame_owner_element->contentDocument();
Element* target = iframe_doc->getElementById("target");
HitTestResult result = target->GetLayoutObject()->HitTestForOcclusion();
- EXPECT_TRUE(result.InnerNode() == target);
+ EXPECT_EQ(result.InnerNode(), target);
Element* occluder = GetDocument().getElementById("occluder");
occluder->SetInlineStyleProperty(CSSPropertyMarginTop, "-150px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
result = target->GetLayoutObject()->HitTestForOcclusion();
- EXPECT_TRUE(result.InnerNode() == occluder);
+ EXPECT_EQ(result.InnerNode(), occluder);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_progress_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_progress_test.cc
index 7034a850a89..82e287162c4 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_progress_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_progress_test.cc
@@ -22,7 +22,7 @@ class LayoutProgressTest : public RenderingTest {
TEST_F(LayoutProgressTest, AnimationScheduling) {
RenderingTest::SetBodyInnerHTML(
"<progress id=\"progressElement\" value=0.3 max=1.0></progress>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* progress_element =
GetDocument().getElementById(AtomicString("progressElement"));
LayoutProgress* layout_progress =
@@ -33,14 +33,14 @@ TEST_F(LayoutProgressTest, AnimationScheduling) {
EXPECT_FALSE(LayoutProgressTest::IsAnimatiing(layout_progress));
progress_element->removeAttribute("value");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Verify that we schedule a timer for an indeterminant progress element
EXPECT_TRUE(LayoutProgressTest::IsAnimationTimerActive(layout_progress));
EXPECT_TRUE(LayoutProgressTest::IsAnimatiing(layout_progress));
- progress_element->setAttribute(HTMLNames::valueAttr, "0.7");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ progress_element->setAttribute(html_names::kValueAttr, "0.7");
+ UpdateAllLifecyclePhasesForTest();
// Verify that we cancel the timer for a determinant progress element
EXPECT_FALSE(LayoutProgressTest::IsAnimationTimerActive(layout_progress));
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_quote.cc b/chromium/third_party/blink/renderer/core/layout/layout_quote.cc
index 473122e721e..3ab2a8a4164 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_quote.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_quote.cc
@@ -269,8 +269,8 @@ void LayoutQuote::UpdateText() {
fragment->SetStyle(MutableStyle());
fragment->SetContentString(text_.Impl());
} else {
- fragment =
- LayoutTextFragment::CreateAnonymous(*owning_pseudo_, text_.Impl());
+ fragment = LayoutTextFragment::CreateAnonymous(*Style(), *owning_pseudo_,
+ text_.Impl());
fragment->SetStyle(MutableStyle());
AddChild(fragment);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_replaced.cc b/chromium/third_party/blink/renderer/core/layout/layout_replaced.cc
index 7169488d622..6a1daea6062 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_replaced.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_replaced.cc
@@ -38,7 +38,7 @@
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/replaced_painter.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -116,7 +116,7 @@ void LayoutReplaced::IntrinsicSizeChanged() {
static_cast<int>(kDefaultHeight * StyleRef().EffectiveZoom());
intrinsic_size_ = LayoutSize(scaled_width, scaled_height);
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
}
void LayoutReplaced::Paint(const PaintInfo& paint_info) const {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_replaced_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_replaced_test.cc
index f3d3d28a356..5b157b6a6c8 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_replaced_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_replaced_test.cc
@@ -24,7 +24,7 @@ TEST_F(LayoutReplacedTest, InvalidateAfterAddingBorderRadius) {
LayoutObject* layout_object = target_element->GetLayoutObject();
ASSERT_FALSE(layout_object->StyleRef().HasBorderRadius());
- target_element->setAttribute(HTMLNames::styleAttr, "border-radius: 10px");
+ target_element->setAttribute(html_names::kStyleAttr, "border-radius: 10px");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_TRUE(layout_object->NeedsPaintPropertyUpdate());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_ruby_base.cc b/chromium/third_party/blink/renderer/core/layout/layout_ruby_base.cc
index 5635dfe5a5b..8dcbcefd71c 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_ruby_base.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_ruby_base.cc
@@ -66,9 +66,9 @@ void LayoutRubyBase::MoveChildren(LayoutRubyBase* to_base,
MoveBlockChildren(to_base, before_child);
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kUnknown);
+ layout_invalidation_reason::kUnknown);
to_base->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kUnknown);
+ layout_invalidation_reason::kUnknown);
}
void LayoutRubyBase::MoveInlineChildren(LayoutRubyBase* to_base,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.cc b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.cc
index 33ce179c5e1..39ecd158ccf 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.cc
@@ -40,7 +40,8 @@ Scrollbar* LayoutScrollbar::CreateCustomScrollbar(
ScrollableArea* scrollable_area,
ScrollbarOrientation orientation,
Element* style_source) {
- return new LayoutScrollbar(scrollable_area, orientation, style_source);
+ return MakeGarbageCollected<LayoutScrollbar>(scrollable_area, orientation,
+ style_source);
}
LayoutScrollbar::LayoutScrollbar(ScrollableArea* scrollable_area,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.h b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.h
index 135055581dd..da7effaae77 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar.h
@@ -44,6 +44,8 @@ class LayoutScrollbar final : public Scrollbar {
static Scrollbar* CreateCustomScrollbar(ScrollableArea*,
ScrollbarOrientation,
Element*);
+
+ LayoutScrollbar(ScrollableArea*, ScrollbarOrientation, Element*);
~LayoutScrollbar() override;
// Return the thickness that a custom scrollbar would have, without actually
@@ -78,9 +80,6 @@ class LayoutScrollbar final : public Scrollbar {
void Trace(blink::Visitor*) override;
- protected:
- LayoutScrollbar(ScrollableArea*, ScrollbarOrientation, Element*);
-
private:
friend class Scrollbar;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_part.cc b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_part.cc
index d026087da9e..7a6de8c0564 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_part.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_part.cc
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/core/layout/layout_scrollbar.h"
#include "third_party/blink/renderer/core/layout/layout_scrollbar_theme.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_search_field.cc b/chromium/third_party/blink/renderer/core/layout/layout_search_field.cc
index 053c6c5b36f..54159e3348f 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_search_field.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_search_field.cc
@@ -31,25 +31,21 @@
namespace blink {
-using namespace HTMLNames;
-
-// ----------------------------
-
LayoutSearchField::LayoutSearchField(HTMLInputElement* element)
: LayoutTextControlSingleLine(element) {
- DCHECK_EQ(element->type(), InputTypeNames::search);
+ DCHECK_EQ(element->type(), input_type_names::kSearch);
}
LayoutSearchField::~LayoutSearchField() = default;
inline Element* LayoutSearchField::SearchDecorationElement() const {
return InputElement()->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SearchDecoration());
+ shadow_element_names::SearchDecoration());
}
inline Element* LayoutSearchField::CancelButtonElement() const {
return InputElement()->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::ClearButton());
+ shadow_element_names::ClearButton());
}
LayoutUnit LayoutSearchField::ComputeControlLogicalHeight(
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_slider.cc b/chromium/third_party/blink/renderer/core/layout/layout_slider.cc
index 7918e4b2a2a..4e349a8a5f0 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_slider.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_slider.cc
@@ -33,7 +33,7 @@ const int LayoutSlider::kDefaultTrackLength = 129;
LayoutSlider::LayoutSlider(HTMLInputElement* element)
: LayoutFlexibleBox(element) {
// We assume LayoutSlider works only with <input type=range>.
- DCHECK_EQ(element->type(), InputTypeNames::range);
+ DCHECK_EQ(element->type(), input_type_names::kRange);
}
LayoutSlider::~LayoutSlider() = default;
@@ -60,7 +60,7 @@ void LayoutSlider::ComputeIntrinsicLogicalWidths(
inline SliderThumbElement* LayoutSlider::GetSliderThumbElement() const {
return ToSliderThumbElement(
ToElement(GetNode())->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderThumb()));
+ shadow_element_names::SliderThumb()));
}
bool LayoutSlider::InDragMode() const {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_slider_container.cc b/chromium/third_party/blink/renderer/core/layout/layout_slider_container.cc
index 4a8785ddf0a..6c217bf19a5 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_slider_container.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_slider_container.cc
@@ -102,9 +102,9 @@ void LayoutSliderContainer::UpdateLayout() {
bool is_vertical = HasVerticalAppearance(input);
Element* thumb_element = input->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderThumb());
+ shadow_element_names::SliderThumb());
Element* track_element = input->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderTrack());
+ shadow_element_names::SliderTrack());
LayoutBox* thumb = thumb_element ? thumb_element->GetLayoutBox() : nullptr;
LayoutBox* track = track_element ? track_element->GetLayoutBox() : nullptr;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table.cc b/chromium/third_party/blink/renderer/core/layout/layout_table.cc
index c28b0e72b04..ffc3ea95d11 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table.cc
@@ -49,8 +49,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutTable::LayoutTable(Element* element)
: LayoutBlock(element),
head_(nullptr),
@@ -242,7 +240,7 @@ void LayoutTable::AddCaption(const LayoutTableCaption* caption) {
}
void LayoutTable::RemoveCaption(const LayoutTableCaption* old_caption) {
- size_t index = captions_.Find(old_caption);
+ wtf_size_t index = captions_.Find(old_caption);
DCHECK_NE(index, kNotFound);
if (index == kNotFound)
return;
@@ -623,9 +621,10 @@ void LayoutTable::UpdateLayout() {
UpdateLogicalWidth();
if (LogicalWidth() != old_logical_width) {
- for (unsigned i = 0; i < captions_.size(); i++)
+ for (unsigned i = 0; i < captions_.size(); i++) {
layouter.SetNeedsLayout(captions_[i],
- LayoutInvalidationReason::kTableChanged);
+ layout_invalidation_reason::kTableChanged);
+ }
}
// FIXME: The optimisation below doesn't work since the internal table
// layout could have changed. We need to add a flag to the table
@@ -842,7 +841,7 @@ void LayoutTable::AdjustWidthsForCollapsedColumns(
unsigned n_eff_cols = NumEffectiveColumns();
// Update vector of collapsed widths.
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (unsigned i = 0; i < n_eff_cols; ++i) {
// TODO(joysyu): Here, we are at O(n^2) for every table that has ever had a
// collapsed column. ColElementAtAbsoluteColumn() is currently O(n);
// ideally, it would be O(1). We have to improve the runtime before shipping
@@ -861,7 +860,7 @@ void LayoutTable::AdjustWidthsForCollapsedColumns(
// Adjust column positions according to collapsed widths.
int total_collapsed_width = 0;
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (unsigned i = 0; i < n_eff_cols; ++i) {
total_collapsed_width += col_collapsed_width[i];
SetEffectiveColumnPosition(
i + 1, EffectiveColumnPositions()[i + 1] - total_collapsed_width);
@@ -910,6 +909,21 @@ void LayoutTable::InvalidateCollapsedBordersForAllCellsIfNeeded() {
}
}
+void LayoutTable::ComputeVisualOverflow(
+ const LayoutRect& previous_visual_overflow_rect,
+ bool recompute_floats) {
+ AddVisualOverflowFromChildren();
+
+ AddVisualEffectOverflow();
+ AddVisualOverflowFromTheme();
+
+ if (VisualOverflowRect() != previous_visual_overflow_rect) {
+ if (Layer())
+ Layer()->SetNeedsCompositingInputsUpdate();
+ GetFrameView()->SetIntersectionObservationState(LocalFrameView::kDesired);
+ }
+}
+
void LayoutTable::AddVisualOverflowFromChildren() {
// Add overflow from borders.
// Technically it's odd that we are incorporating the borders into layout
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table.h b/chromium/third_party/blink/renderer/core/layout/layout_table.h
index 48af1bc9a43..5582a244d09 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table.h
@@ -28,7 +28,7 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/layout/layout_block.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -320,7 +320,7 @@ class CORE_EXPORT LayoutTable final : public LayoutBlock {
needs_section_recalc_ = true;
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kTableChanged);
+ layout_invalidation_reason::kTableChanged);
// Grid structure affects cell adjacence relationships which affect
// conflict resolution of collapsed borders.
@@ -474,7 +474,9 @@ class CORE_EXPORT LayoutTable final : public LayoutBlock {
OverlayScrollbarClipBehavior =
kIgnorePlatformOverlayScrollbarSize) const override;
- void AddVisualOverflowFromChildren() override;
+ void ComputeVisualOverflow(const LayoutRect&, bool recompute_floats) final;
+
+ void AddVisualOverflowFromChildren();
void AddLayoutOverflowFromChildren() override;
void RecalcSections() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_cell.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_cell.cc
index 9c85ac7f206..c4d51b4495e 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_cell.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_cell.cc
@@ -43,7 +43,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
struct SameSizeAsLayoutTableCell : public LayoutBlockFlow {
unsigned bitfields;
@@ -87,12 +87,12 @@ void LayoutTableCell::WillBeRemovedFromTree() {
// TODO(dgrogan): Should this be setChildNeedsLayout or setNeedsLayout?
// remove-cell-with-border-box.html only passes with setNeedsLayout but
// other places use setChildNeedsLayout.
- PreviousCell()->SetNeedsLayout(LayoutInvalidationReason::kTableChanged);
+ PreviousCell()->SetNeedsLayout(layout_invalidation_reason::kTableChanged);
PreviousCell()->SetPreferredLogicalWidthsDirty();
}
if (NextCell()) {
// TODO(dgrogan): Same as above re: setChildNeedsLayout vs setNeedsLayout.
- NextCell()->SetNeedsLayout(LayoutInvalidationReason::kTableChanged);
+ NextCell()->SetNeedsLayout(layout_invalidation_reason::kTableChanged);
NextCell()->SetPreferredLogicalWidthsDirty();
}
}
@@ -129,7 +129,7 @@ void LayoutTableCell::ColSpanOrRowSpanChanged() {
UpdateColAndRowSpanFlags();
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
if (Parent() && Section()) {
Section()->SetNeedsCellRecalc();
if (Table() && Table()->ShouldCollapseBorders())
@@ -201,7 +201,8 @@ void LayoutTableCell::ComputePreferredLogicalWidths() {
if (GetNode() && StyleRef().AutoWrap()) {
// See if nowrap was set.
Length w = StyleOrColLogicalWidth();
- const AtomicString& nowrap = ToElement(GetNode())->getAttribute(nowrapAttr);
+ const AtomicString& nowrap =
+ ToElement(GetNode())->getAttribute(kNowrapAttr);
if (!nowrap.IsNull() && w.IsFixed()) {
// Nowrap is set, but we didn't actually use it because of the fixed width
// set on the cell. Even so, it is a WinIE/Moz trait to make the minwidth
@@ -282,7 +283,7 @@ void LayoutTableCell::ComputeIntrinsicPadding(int collapsed_height,
// only shifts the cell inside the row but doesn't change the logical height.
if (intrinsic_padding_before != old_intrinsic_padding_before ||
intrinsic_padding_after != old_intrinsic_padding_after)
- layouter.SetNeedsLayout(this, LayoutInvalidationReason::kPaddingChanged);
+ layouter.SetNeedsLayout(this, layout_invalidation_reason::kPaddingChanged);
}
void LayoutTableCell::UpdateLogicalWidth() {}
@@ -292,7 +293,7 @@ void LayoutTableCell::SetCellLogicalWidth(int table_layout_logical_width,
if (table_layout_logical_width == LogicalWidth())
return;
- layouter.SetNeedsLayout(this, LayoutInvalidationReason::kSizeChanged);
+ layouter.SetNeedsLayout(this, layout_invalidation_reason::kSizeChanged);
SetLogicalWidth(LayoutUnit(table_layout_logical_width));
SetCellChildrenNeedLayout(true);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_cell.h b/chromium/third_party/blink/renderer/core/layout/layout_table_cell.h
index cd8500cf1f1..52baeefc2f1 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_cell.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_cell.h
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_table_row.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/text/writing_mode_utils.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_cell_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_cell_test.cc
index 3647756046d..b5a12586679 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_cell_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_cell_test.cc
@@ -134,11 +134,11 @@ TEST_F(LayoutTableCellTest, RepaintContentInTableCell) {
// Create an overflow recalc.
Element* cell = GetDocument().getElementById("cell");
- cell->setAttribute(HTMLNames::styleAttr, "outline: 1px solid black;");
+ cell->setAttribute(html_names::kStyleAttr, "outline: 1px solid black;");
// Trigger a layout on the table that doesn't require cell layout.
Element* table = GetDocument().getElementById("table");
- table->setAttribute(HTMLNames::styleAttr, "position: absolute; left: 2px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ table->setAttribute(html_names::kStyleAttr, "position: absolute; left: 2px;");
+ UpdateAllLifecyclePhasesForTest();
// Check that overflow was calculated on the cell.
auto* input_block = ToLayoutBlock(cell->GetLayoutObject());
@@ -296,9 +296,9 @@ TEST_F(LayoutTableCellTest, BorderWidthsWithCollapsedBorders) {
EXPECT_EQ(2u, cell2->CollapsedOuterBorderAfter());
ToElement(cell1->Table()->GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
"writing-mode: vertical-rl; direction: rtl");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(5, cell1->BorderLeft());
EXPECT_EQ(0, cell1->BorderRight());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_col.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_col.cc
index f70ca598132..97ffbb81bbd 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_col.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_col.cc
@@ -32,8 +32,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutTableCol::LayoutTableCol(Element* element)
: LayoutTableBoxComponent(element), span_(1) {
// init LayoutObject attributes
@@ -81,9 +79,10 @@ void LayoutTableCol::UpdateFromElement() {
} else {
span_ = 1;
}
- if (span_ != old_span && Style() && Parent())
+ if (span_ != old_span && Style() && Parent()) {
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kAttributeChanged);
+ layout_invalidation_reason::kAttributeChanged);
+ }
}
void LayoutTableCol::InsertedIntoTree() {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_row.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_row.cc
index 616212e45a5..6ee697026fa 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_row.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_row.cc
@@ -37,8 +37,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutTableRow::LayoutTableRow(Element* element)
: LayoutTableBoxComponent(element), row_index_(kUnsetRowIndex) {
// init LayoutObject attributes
@@ -171,12 +169,14 @@ void LayoutTableRow::AddChild(LayoutObject* child, LayoutObject* before_child) {
LayoutTable* enclosing_table = Table();
if (enclosing_table && enclosing_table->ShouldCollapseBorders()) {
enclosing_table->InvalidateCollapsedBorders();
- if (LayoutTableCell* previous_cell = cell->PreviousCell())
+ if (LayoutTableCell* previous_cell = cell->PreviousCell()) {
previous_cell->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kTableChanged);
- if (LayoutTableCell* next_cell = cell->NextCell())
+ layout_invalidation_reason::kTableChanged);
+ }
+ if (LayoutTableCell* next_cell = cell->NextCell()) {
next_cell->SetNeedsLayoutAndPrefWidthsRecalc(
- LayoutInvalidationReason::kTableChanged);
+ layout_invalidation_reason::kTableChanged);
+ }
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_section.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_section.cc
index fe70f5d5e59..74d0dbbb3d7 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_section.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_section.cc
@@ -42,8 +42,6 @@
namespace blink {
-using namespace HTMLNames;
-
void LayoutTableSection::TableGridRow::
SetRowLogicalHeightToRowStyleLogicalHeight() {
DCHECK(row);
@@ -209,7 +207,7 @@ static inline void CheckThatVectorIsDOMOrdered(
DCHECK_GT(cells.size(), 0u);
const LayoutTableCell* previous_cell = cells[0];
- for (size_t i = 1; i < cells.size(); ++i) {
+ for (wtf_size_t i = 1; i < cells.size(); ++i) {
const LayoutTableCell* current_cell = cells[i];
// The check assumes that all cells belong to the same row group.
DCHECK_EQ(previous_cell->Section(), current_cell->Section());
@@ -1602,9 +1600,9 @@ void LayoutTableSection::DirtiedRowsAndEffectiveColumns(
CellSpan LayoutTableSection::SpannedRows(const LayoutRect& flipped_rect) const {
// Find the first row that starts after rect top.
- unsigned next_row =
+ unsigned next_row = static_cast<unsigned>(
std::upper_bound(row_pos_.begin(), row_pos_.end(), flipped_rect.Y()) -
- row_pos_.begin();
+ row_pos_.begin());
// After all rows.
if (next_row == row_pos_.size())
@@ -1617,9 +1615,10 @@ CellSpan LayoutTableSection::SpannedRows(const LayoutRect& flipped_rect) const {
if (row_pos_[next_row] >= flipped_rect.MaxY()) {
end_row = next_row;
} else {
- end_row = std::upper_bound(row_pos_.begin() + next_row, row_pos_.end(),
- flipped_rect.MaxY()) -
- row_pos_.begin();
+ end_row = static_cast<unsigned>(
+ std::upper_bound(row_pos_.begin() + next_row, row_pos_.end(),
+ flipped_rect.MaxY()) -
+ row_pos_.begin());
if (end_row == row_pos_.size())
end_row = row_pos_.size() - 1;
}
@@ -1636,9 +1635,9 @@ CellSpan LayoutTableSection::SpannedEffectiveColumns(
// wrongly return the cell on the logical top/left.
// upper_bound on the other hand properly returns the cell on the logical
// bottom/right, which also matches the behavior of other browsers.
- unsigned next_column =
+ unsigned next_column = static_cast<unsigned>(
std::upper_bound(column_pos.begin(), column_pos.end(), flipped_rect.X()) -
- column_pos.begin();
+ column_pos.begin());
if (next_column == column_pos.size())
return CellSpan(column_pos.size() - 1,
@@ -1651,9 +1650,10 @@ CellSpan LayoutTableSection::SpannedEffectiveColumns(
if (column_pos[next_column] >= flipped_rect.MaxX()) {
end_column = next_column;
} else {
- end_column = std::upper_bound(column_pos.begin() + next_column,
- column_pos.end(), flipped_rect.MaxX()) -
- column_pos.begin();
+ end_column = static_cast<unsigned>(
+ std::upper_bound(column_pos.begin() + next_column, column_pos.end(),
+ flipped_rect.MaxX()) -
+ column_pos.begin());
if (end_column == column_pos.size())
end_column = column_pos.size() - 1;
}
@@ -1702,7 +1702,7 @@ void LayoutTableSection::RecalcCells() {
}
grid_.ShrinkToFit();
- SetNeedsLayoutAndFullPaintInvalidation(LayoutInvalidationReason::kUnknown);
+ SetNeedsLayoutAndFullPaintInvalidation(layout_invalidation_reason::kUnknown);
}
// FIXME: This function could be made O(1) in certain cases (like for the
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_section_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_section_test.cc
index 78a184c9b6d..a06ed4f74f7 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_section_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_section_test.cc
@@ -18,17 +18,17 @@ class LayoutTableSectionTest : public RenderingTest {
}
LayoutTableSection* CreateSection(unsigned rows, unsigned columns) {
- auto* table = GetDocument().CreateRawElement(HTMLNames::tableTag);
+ auto* table = GetDocument().CreateRawElement(html_names::kTableTag);
GetDocument().body()->appendChild(table);
- auto* section = GetDocument().CreateRawElement(HTMLNames::tbodyTag);
+ auto* section = GetDocument().CreateRawElement(html_names::kTbodyTag);
table->appendChild(section);
for (unsigned i = 0; i < rows; ++i) {
- auto* row = GetDocument().CreateRawElement(HTMLNames::trTag);
+ auto* row = GetDocument().CreateRawElement(html_names::kTrTag);
section->appendChild(row);
for (unsigned i = 0; i < columns; ++i)
- row->appendChild(GetDocument().CreateRawElement(HTMLNames::tdTag));
+ row->appendChild(GetDocument().CreateRawElement(html_names::kTdTag));
}
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
return ToLayoutTableSection(section->GetLayoutObject());
}
};
@@ -316,8 +316,10 @@ TEST_F(LayoutTableSectionTest, VisualOverflowWithCollapsedBorders) {
}
static void SetCellsOverflowInRow(LayoutTableRow* row) {
- for (auto* cell = row->FirstCell(); cell; cell = cell->NextCell())
- ToElement(cell->GetNode())->setAttribute(HTMLNames::classAttr, "overflow");
+ for (auto* cell = row->FirstCell(); cell; cell = cell->NextCell()) {
+ ToElement(cell->GetNode())
+ ->setAttribute(html_names::kClassAttr, "overflow");
+ }
}
TEST_F(LayoutTableSectionTest, OverflowingCells) {
@@ -345,7 +347,7 @@ TEST_F(LayoutTableSectionTest, OverflowingCells) {
SetCellsOverflowInRow(small_section->FirstRow());
SetCellsOverflowInRow(big_section->FirstRow());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Small sections with overflowing cells always use the full paint path.
EXPECT_TRUE(small_section->HasOverflowingCell());
@@ -365,7 +367,7 @@ TEST_F(LayoutTableSectionTest, OverflowingCells) {
SetCellsOverflowInRow(row);
for (auto* row = big_section->FirstRow(); row; row = row->NextRow())
SetCellsOverflowInRow(row);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Small sections with overflowing cells always use the full paint path.
EXPECT_TRUE(small_section->HasOverflowingCell());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_table_test.cc
index ff1d80f7a5b..d43c46e86b4 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_test.cc
@@ -30,13 +30,14 @@ TEST_F(LayoutTableTest, OverflowViaOutline) {
auto* target = GetTableByElementId("target");
EXPECT_EQ(LayoutRect(0, 0, 100, 200), target->SelfVisualOverflowRect());
ToElement(target->GetNode())
- ->setAttribute(HTMLNames::styleAttr, "outline: 2px solid black");
+ ->setAttribute(html_names::kStyleAttr, "outline: 2px solid black");
auto* child = GetTableByElementId("child");
ToElement(child->GetNode())
- ->setAttribute(HTMLNames::styleAttr, "outline: 2px solid black");
+ ->setAttribute(html_names::kStyleAttr, "outline: 2px solid black");
- target->GetFrameView()->UpdateAllLifecyclePhases();
+ target->GetFrameView()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_EQ(LayoutRect(-2, -2, 104, 204), target->SelfVisualOverflowRect());
EXPECT_EQ(LayoutRect(-2, -2, 104, 204), child->SelfVisualOverflowRect());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text.cc b/chromium/third_party/blink/renderer/core/layout/layout_text.cc
index e33717dca00..6c609ed13e6 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text.cc
@@ -180,7 +180,7 @@ void LayoutText::StyleDidChange(StyleDifference diff,
// We do have to schedule layouts, though, since a style change can force us
// to need to relayout.
if (diff.NeedsFullLayout()) {
- SetNeedsLayoutAndPrefWidthsRecalc(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayoutAndPrefWidthsRecalc(layout_invalidation_reason::kStyleChange);
known_to_have_no_overflow_and_no_fallback_fonts_ = false;
}
@@ -194,7 +194,7 @@ void LayoutText::StyleDidChange(StyleDifference diff,
TransformText();
// This is an optimization that kicks off font load before layout.
- if (!GetText().ContainsOnlyWhitespace())
+ if (!GetText().ContainsOnlyWhitespaceOrEmpty())
new_style.GetFont().WillUseFontData(GetText());
TextAutosizer* text_autosizer = GetDocument().GetTextAutosizer();
@@ -217,8 +217,9 @@ void LayoutText::RemoveAndDestroyTextBoxes() {
for (InlineTextBox* box : TextBoxes())
box->Remove();
} else if (Parent()) {
- if (!FirstInlineFragment() ||
- !NGPaintFragment::TryMarkLineBoxDirtyFor(*this))
+ if (NGPaintFragment* first_fragment = FirstInlineFragment())
+ first_fragment->MarkContainingLineBoxDirty();
+ else
Parent()->DirtyLinesFromChangedChild(this);
}
}
@@ -376,7 +377,7 @@ String LayoutText::PlainText() const {
plain_text_builder.Append(text);
if (text_box->NextForSameLayoutObject() &&
text_box->NextForSameLayoutObject()->Start() > text_box->end() &&
- text.length() && !text.Right(1).ContainsOnlyWhitespace())
+ text.length() && !text.Right(1).ContainsOnlyWhitespaceOrEmpty())
plain_text_builder.Append(kSpaceCharacter);
}
return plain_text_builder.ToString();
@@ -485,7 +486,7 @@ void LayoutText::Quads(Vector<FloatQuad>& quads,
LocalOrAbsoluteOption local_or_absolute,
MapCoordinatesFlags mode) const {
if (const NGPhysicalBoxFragment* box_fragment =
- EnclosingBlockFlowFragment()) {
+ ContainingBlockFlowFragment()) {
const auto children =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
const LayoutBlock* block_for_flipping = nullptr;
@@ -751,10 +752,7 @@ CreatePositionWithAffinityForBoxAfterAdjustingOffsetForBiDi(
ShouldAffinityBeDownstream should_affinity_be_downstream) {
DCHECK(box);
DCHECK_GE(offset, 0);
-
- // TODO(layout-dev): Stop passing out-of-range |offset|.
- if (static_cast<unsigned>(offset) > box->Len())
- offset = box->Len();
+ DCHECK_LE(static_cast<unsigned>(offset), box->Len());
if (offset && static_cast<unsigned>(offset) < box->Len()) {
return CreatePositionWithAffinityForBox(box, box->Start() + offset,
@@ -772,7 +770,7 @@ CreatePositionWithAffinityForBoxAfterAdjustingOffsetForBiDi(
PositionWithAffinity LayoutText::PositionForPoint(
const LayoutPoint& point) const {
- if (const LayoutBlockFlow* ng_block_flow = EnclosingNGBlockFlow())
+ if (const LayoutBlockFlow* ng_block_flow = ContainingNGBlockFlow())
return ng_block_flow->PositionForPoint(point);
DCHECK(CanUseInlineBox(*this));
@@ -822,8 +820,7 @@ PositionWithAffinity LayoutText::PositionForPoint(
return CreatePositionWithAffinityForBoxAfterAdjustingOffsetForBiDi(
last_box,
last_box->OffsetForPosition(point_line_direction, IncludePartialGlyphs,
- BreakGlyphs) +
- last_box->Start(),
+ BreakGlyphs),
should_affinity_be_downstream);
}
return CreatePositionWithAffinity(0);
@@ -998,8 +995,8 @@ void LayoutText::TrimmedPrefWidths(LayoutUnit lead_width_layout_unit,
int len = TextLength();
- if (!len ||
- (strip_front_spaces && GetText().Impl()->ContainsOnlyWhitespace())) {
+ if (!len || (strip_front_spaces &&
+ GetText().Impl()->ContainsOnlyWhitespaceOrEmpty())) {
first_line_min_width = LayoutUnit();
last_line_min_width = LayoutUnit();
first_line_max_width = LayoutUnit();
@@ -1265,7 +1262,7 @@ void LayoutText::ComputePreferredLogicalWidths(
if (run) {
// Treat adjacent runs with the same resolved directionality
- // (TextDirection as opposed to WTF::Unicode::Direction) as belonging
+ // (TextDirection as opposed to WTF::unicode::Direction) as belonging
// to the same run to avoid breaking unnecessarily.
while (i >= run->Stop() ||
(run->Next() && run->Next()->Direction() == run->Direction()))
@@ -1567,16 +1564,26 @@ UChar32 LayoutText::FirstCharacterAfterWhitespaceCollapsing() const {
String text = text_box->GetText();
return text.length() ? text.CharacterStartingAt(0) : 0;
}
- // TODO(kojii): Support LayoutNG once we have NGInlineItem pointers.
+ if (const NGPaintFragment* paint_fragment = FirstInlineFragment()) {
+ const StringView text =
+ ToNGPhysicalTextFragment(paint_fragment->PhysicalFragment()).Text();
+ return text.length() ? text.CodepointAt(0) : 0;
+ }
return 0;
}
UChar32 LayoutText::LastCharacterAfterWhitespaceCollapsing() const {
if (InlineTextBox* text_box = LastTextBox()) {
String text = text_box->GetText();
- return text.length() ? text.CharacterStartingAt(text.length() - 1) : 0;
+ return text.length() ? StringView(text).CodepointAt(text.length() - 1) : 0;
+ }
+ if (const NGPaintFragment* paint_fragment = FirstInlineFragment()) {
+ const StringView text =
+ ToNGPhysicalTextFragment(
+ paint_fragment->LastForSameLayoutObject()->PhysicalFragment())
+ .Text();
+ return text.length() ? text.CodepointAt(text.length() - 1) : 0;
}
- // TODO(kojii): Support LayoutNG once we have NGInlineItem pointers.
return 0;
}
@@ -1606,10 +1613,39 @@ bool LayoutText::CanOptimizeSetText() const {
// If "line-height" is "normal" we might need to recompute the
// baseline which is not straight forward.
!StyleRef().LineHeight().IsNegative() &&
- // We would need to recompute the position if "direction" is "rtl" or
- // "text-align" is not the default one.
+ // We would need to recompute the position if "direction" is "rtl".
StyleRef().IsLeftToRightDirection() &&
- (StyleRef().GetTextAlign(true) == ETextAlign::kStart));
+ // We would need to layout the text if it is justified.
+ (StyleRef().GetTextAlign(true) != ETextAlign::kJustify));
+}
+
+void LayoutText::SetFirstTextBoxLogicalLeft(float text_width) const {
+ DCHECK(FirstTextBox());
+ DCHECK(ContainingBlock());
+ DCHECK(StyleRef().IsLeftToRightDirection());
+
+ LayoutUnit offset_left = ContainingBlock()->LogicalLeftOffsetForContent();
+ LayoutUnit available_space = ContainingBlock()->ContentLogicalWidth();
+
+ switch (StyleRef().GetTextAlign(true)) {
+ case ETextAlign::kLeft:
+ case ETextAlign::kWebkitLeft:
+ case ETextAlign::kJustify:
+ case ETextAlign::kStart:
+ // Do nothing.
+ break;
+ case ETextAlign::kRight:
+ case ETextAlign::kWebkitRight:
+ case ETextAlign::kEnd:
+ offset_left += available_space - text_width;
+ break;
+ case ETextAlign::kCenter:
+ case ETextAlign::kWebkitCenter:
+ offset_left += (available_space - text_width) / 2;
+ break;
+ }
+
+ FirstTextBox()->SetLogicalLeft(offset_left);
}
void LayoutText::SetTextWithOffset(scoped_refptr<StringImpl> text,
@@ -1631,12 +1667,13 @@ void LayoutText::SetTextWithOffset(scoped_refptr<StringImpl> text,
FloatRect glyph_bounds;
float text_width =
style_to_use->GetFont().Width(text_run, nullptr, &glyph_bounds);
- // TODO(rego): We could avoid measuring text width in some specific
- // situations (e.g. if "white-space" property is "pre" and "overflow-wrap"
- // is "normal").
- if (text_width <= ContainingBlock()->ContentLogicalWidth()) {
+ // If the text is not wrapping we don't care if it fits or not in the
+ // container as it's not going to be split in multiple lines.
+ if (!style_to_use->AutoWrap() ||
+ (text_width <= ContainingBlock()->ContentLogicalWidth())) {
FirstTextBox()->ManuallySetStartLenAndLogicalWidth(
offset, text->length(), LayoutUnit(text_width));
+ SetFirstTextBoxLogicalLeft(text_width);
SetText(std::move(text), force, true);
lines_dirty_ = false;
valid_ng_items_ = false;
@@ -1841,7 +1878,7 @@ void LayoutText::SetText(scoped_refptr<StringImpl> text,
SetShouldDoFullPaintInvalidation();
} else {
SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kTextChanged);
+ layout_invalidation_reason::kTextChanged);
}
}
known_to_have_no_overflow_and_no_fallback_fonts_ = false;
@@ -1971,7 +2008,7 @@ float LayoutText::Width(unsigned from,
LayoutRect LayoutText::LinesBoundingBox() const {
if (const NGPhysicalBoxFragment* box_fragment =
- EnclosingBlockFlowFragment()) {
+ ContainingBlockFlowFragment()) {
NGPhysicalOffsetRect bounding_box;
auto children =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
@@ -2435,4 +2472,25 @@ LayoutRect LayoutText::DebugRect() const {
return rect;
}
+void LayoutText::AddInlineItem(NGInlineItem* item) {
+ DCHECK_EQ(this, item->GetLayoutObject());
+ NGInlineItems* items = GetNGInlineItems();
+ if (!items)
+ return;
+ valid_ng_items_ = true;
+ items->Add(item);
+}
+
+void LayoutText::ClearInlineItems() {
+ valid_ng_items_ = false;
+ if (NGInlineItems* items = GetNGInlineItems())
+ items->Clear();
+}
+
+const Vector<NGInlineItem*>& LayoutText::InlineItems() const {
+ DCHECK(valid_ng_items_);
+ DCHECK(!GetNGInlineItems()->Items().IsEmpty());
+ return GetNGInlineItems()->Items();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text.h b/chromium/third_party/blink/renderer/core/layout/layout_text.h
index a60e125c71c..cfefdc2e764 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text.h
@@ -30,13 +30,15 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/line/line_box_list.h"
#include "third_party/blink/renderer/core/layout/text_run_constructor.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
class AbstractInlineTextBox;
class InlineTextBox;
+class NGInlineItem;
+class NGInlineItems;
class NGOffsetMapping;
enum class OnlyWhitespaceOrNbsp : unsigned { kUnknown = 0, kNo = 1, kYes = 2 };
@@ -312,7 +314,17 @@ class CORE_EXPORT LayoutText : public LayoutObject {
unsigned* start,
unsigned* end) const;
+ void AddInlineItem(NGInlineItem* item);
+ void ClearInlineItems();
+ bool HasValidInlineItems() const { return valid_ng_items_; }
+ const Vector<NGInlineItem*>& InlineItems() const;
+ // Inline items depends on context. It needs to be invalidated not only when
+ // it was inserted/changed but also it was moved.
+ void InvalidateInlineItems() { valid_ng_items_ = false; }
+
protected:
+ virtual const NGInlineItems* GetNGInlineItems() const { return nullptr; }
+ virtual NGInlineItems* GetNGInlineItems() { return nullptr; }
void WillBeDestroyed() override;
void StyleWillChange(StyleDifference, const ComputedStyle&) final {}
@@ -386,6 +398,7 @@ class CORE_EXPORT LayoutText : public LayoutObject {
LayoutRect LocalVisualRectIgnoringVisibility() const final;
bool CanOptimizeSetText() const;
+ void SetFirstTextBoxLogicalLeft(float text_width) const;
// We put the bitfield first to minimize padding on 64-bit.
protected:
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_control.cc
index a067429a595..e3074199b92 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control.cc
@@ -56,7 +56,7 @@ void LayoutTextControl::StyleDidChange(StyleDifference diff,
if (inner_editor_layout_object) {
inner_editor->SetNeedsStyleRecalc(
kSubtreeStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kControl));
+ StyleChangeReasonForTracing::Create(style_change_reason::kControl));
// The inner editor element uses the LayoutTextControl's ::selection style
// (see: GetUncachedSelectionStyle in SelectionPaintingUtils.cpp) so ensure
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc
index 79a43d16f82..0c6689925fc 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc
@@ -34,13 +34,12 @@
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/text_control_single_line_painter.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
namespace blink {
-using namespace HTMLNames;
-
LayoutTextControlSingleLine::LayoutTextControlSingleLine(
HTMLInputElement* element)
: LayoutTextControl(element), should_draw_caps_lock_indicator_(false) {}
@@ -49,18 +48,18 @@ LayoutTextControlSingleLine::~LayoutTextControlSingleLine() = default;
inline Element* LayoutTextControlSingleLine::ContainerElement() const {
return InputElement()->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::TextFieldContainer());
+ shadow_element_names::TextFieldContainer());
}
inline Element* LayoutTextControlSingleLine::EditingViewPortElement() const {
return InputElement()->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::EditingViewPort());
+ shadow_element_names::EditingViewPort());
}
inline HTMLElement* LayoutTextControlSingleLine::InnerSpinButtonElement()
const {
return ToHTMLElement(InputElement()->UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SpinButton()));
+ shadow_element_names::SpinButton()));
}
void LayoutTextControlSingleLine::Paint(const PaintInfo& paint_info) const {
@@ -178,7 +177,7 @@ void LayoutTextControlSingleLine::CapsLockStateMayHaveChanged() {
if (LocalFrame* frame = GetDocument().GetFrame())
should_draw_caps_lock_indicator =
- InputElement()->type() == InputTypeNames::password &&
+ InputElement()->type() == input_type_names::kPassword &&
frame->Selection().FrameIsFocusedAndActive() &&
GetDocument().FocusedElement() == GetNode() &&
KeyboardEventManager::CurrentCapsLockState();
@@ -243,10 +242,10 @@ LayoutUnit LayoutTextControlSingleLine::PreferredContentLogicalWidth(
if (LayoutBox* spin_layout_object =
spin_button ? spin_button->GetLayoutBox() : nullptr) {
result += spin_layout_object->BorderAndPaddingLogicalWidth();
- // Since the width of spinLayoutObject is not calculated yet,
- // spinLayoutObject->logicalWidth() returns 0.
- // So ensureComputedStyle()->logicalWidth() is used instead.
- result += spin_button->EnsureComputedStyle()->LogicalWidth().Value();
+ // Since the width of spin_layout_object is not calculated yet,
+ // spin_layout_object->LogicalWidth() returns 0. Use the computed logical
+ // width instead.
+ result += spin_layout_object->StyleRef().LogicalWidth().Value();
}
}
@@ -317,4 +316,23 @@ HTMLInputElement* LayoutTextControlSingleLine::InputElement() const {
return ToHTMLInputElement(GetNode());
}
+void LayoutTextControlSingleLine::ComputeVisualOverflow(
+ const LayoutRect& previous_visual_overflow_rect,
+ bool recompute_floats) {
+ AddVisualOverflowFromChildren();
+
+ AddVisualEffectOverflow();
+ AddVisualOverflowFromTheme();
+
+ if (recompute_floats || CreatesNewFormattingContext() ||
+ HasSelfPaintingLayer())
+ AddVisualOverflowFromFloats();
+
+ if (VisualOverflowRect() != previous_visual_overflow_rect) {
+ if (Layer())
+ Layer()->SetNeedsCompositingInputsUpdate();
+ GetFrameView()->SetIntersectionObservationState(LocalFrameView::kDesired);
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.h b/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.h
index 9132a9e75ee..66c2a232863 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.h
@@ -78,10 +78,11 @@ class LayoutTextControlSingleLine : public LayoutTextControl {
LayoutUnit line_height,
LayoutUnit non_content_height) const override;
+ void ComputeVisualOverflow(const LayoutRect&, bool recompute_floats) override;
+
// If the INPUT content height is smaller than the font height, the
// inner-editor element overflows the INPUT box intentionally, however it
// shouldn't affect outside of the INPUT box. So we ignore child overflow.
- void AddVisualOverflowFromChildren() final {}
void AddLayoutOverflowFromChildren() final {}
bool AllowsOverflowClip() const override { return false; }
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_control_test.cc
index f26c94067a5..8e6066e214a 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control_test.cc
@@ -38,16 +38,16 @@ TEST_F(LayoutTextControlTest,
auto* inputElement = GetHTMLInputElementById("input");
inputElement->focus();
inputElement->SetSelectionRange(1, 3);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* selectedText = GetInnerLayoutText(inputElement);
EXPECT_FALSE(selectedText->ShouldInvalidateSelection());
- inputElement->setAttribute(HTMLNames::classAttr, "pseudoSelection");
+ inputElement->setAttribute(html_names::kClassAttr, "pseudoSelection");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_TRUE(selectedText->ShouldInvalidateSelection());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(selectedText->ShouldInvalidateSelection());
}
@@ -63,16 +63,16 @@ TEST_F(LayoutTextControlTest,
auto* inputElement = GetHTMLInputElementById("input");
inputElement->focus();
inputElement->SetSelectionRange(1, 3);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* selectedText = GetInnerLayoutText(inputElement);
EXPECT_FALSE(selectedText->ShouldInvalidateSelection());
- inputElement->setAttribute(HTMLNames::classAttr, "pseudoSelection");
+ inputElement->setAttribute(html_names::kClassAttr, "pseudoSelection");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_TRUE(selectedText->ShouldInvalidateSelection());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(selectedText->ShouldInvalidateSelection());
}
@@ -88,16 +88,16 @@ TEST_F(LayoutTextControlTest,
auto* inputElement = GetHTMLInputElementById("input");
inputElement->focus();
inputElement->SetSelectionRange(1, 3);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* selectedText = GetInnerLayoutText(inputElement);
EXPECT_FALSE(selectedText->ShouldInvalidateSelection());
- inputElement->removeAttribute(HTMLNames::classAttr);
+ inputElement->removeAttribute(html_names::kClassAttr);
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_TRUE(selectedText->ShouldInvalidateSelection());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(selectedText->ShouldInvalidateSelection());
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.cc
index 98b9b00e0f1..54ece45472f 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.cc
@@ -28,6 +28,7 @@
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
namespace blink {
@@ -43,19 +44,28 @@ LayoutTextFragment::LayoutTextFragment(Node* node,
content_string_(str),
first_letter_pseudo_element_(nullptr) {}
-LayoutTextFragment::LayoutTextFragment(Node* node, StringImpl* str)
- : LayoutTextFragment(node, str, 0, str ? str->length() : 0) {}
-
LayoutTextFragment::~LayoutTextFragment() {
DCHECK(!first_letter_pseudo_element_);
}
-LayoutTextFragment* LayoutTextFragment::CreateAnonymous(PseudoElement& pseudo,
- StringImpl* text,
- unsigned start,
- unsigned length) {
+LayoutTextFragment* LayoutTextFragment::Create(const ComputedStyle& style,
+ Node* node,
+ StringImpl* str,
+ int start_offset,
+ int length) {
+ if (RuntimeEnabledFeatures::LayoutNGEnabled() && !style.ForceLegacyLayout())
+ return new LayoutNGTextFragment(node, str, start_offset, length);
+ return new LayoutTextFragment(node, str, start_offset, length);
+}
+
+LayoutTextFragment* LayoutTextFragment::CreateAnonymous(
+ const ComputedStyle& style,
+ PseudoElement& pseudo,
+ StringImpl* text,
+ unsigned start,
+ unsigned length) {
LayoutTextFragment* fragment =
- new LayoutTextFragment(nullptr, text, start, length);
+ LayoutTextFragment::Create(style, nullptr, text, start, length);
fragment->SetDocumentForAnonymous(&pseudo.GetDocument());
if (length)
pseudo.GetDocument().View()->IncrementVisuallyNonEmptyCharacterCount(
@@ -63,9 +73,11 @@ LayoutTextFragment* LayoutTextFragment::CreateAnonymous(PseudoElement& pseudo,
return fragment;
}
-LayoutTextFragment* LayoutTextFragment::CreateAnonymous(PseudoElement& pseudo,
- StringImpl* text) {
- return CreateAnonymous(pseudo, text, 0, text ? text->length() : 0);
+LayoutTextFragment* LayoutTextFragment::CreateAnonymous(
+ const ComputedStyle& style,
+ PseudoElement& pseudo,
+ StringImpl* text) {
+ return CreateAnonymous(style, pseudo, text, 0, text ? text->length() : 0);
}
void LayoutTextFragment::WillBeDestroyed() {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.h b/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.h
index 56272e472ea..8f3cc2145ed 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_fragment.h
@@ -37,14 +37,21 @@ class FirstLetterPseudoElement;
// We cache offsets so that text transformations can be applied in such a way
// that we can recover the original unaltered string from our corresponding DOM
// node.
-class CORE_EXPORT LayoutTextFragment final : public LayoutText {
+class CORE_EXPORT LayoutTextFragment : public LayoutText {
public:
- LayoutTextFragment(Node*, StringImpl*, int start_offset, int length);
- LayoutTextFragment(Node*, StringImpl*);
~LayoutTextFragment() override;
- static LayoutTextFragment* CreateAnonymous(PseudoElement&, StringImpl*);
- static LayoutTextFragment* CreateAnonymous(PseudoElement&,
+ // |style| is used for checking |ForceLegacyLayout()|.
+ static LayoutTextFragment* Create(const ComputedStyle& style,
+ Node*,
+ StringImpl*,
+ int start_offset,
+ int length);
+ static LayoutTextFragment* CreateAnonymous(const ComputedStyle& style,
+ PseudoElement&,
+ StringImpl*);
+ static LayoutTextFragment* CreateAnonymous(const ComputedStyle& style,
+ PseudoElement&,
StringImpl*,
unsigned start,
unsigned length);
@@ -99,6 +106,7 @@ class CORE_EXPORT LayoutTextFragment final : public LayoutText {
LayoutText* GetFirstLetterPart() const override;
protected:
+ LayoutTextFragment(Node*, StringImpl*, int start_offset, int length);
void WillBeDestroyed() override;
private:
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_test.cc
index bcc7bebc531..0296a5e0750 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_test.cc
@@ -40,7 +40,7 @@ class LayoutTextTest : public RenderingTest {
void SetSelectionAndUpdateLayoutSelection(const std::string& selection_text) {
const SelectionInDOMTree selection =
SelectionSample::SetSelectionText(GetDocument().body(), selection_text);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Selection().SetSelectionAndEndTyping(selection);
Selection().CommitAppearanceIfNeeded();
}
@@ -233,9 +233,7 @@ TEST_P(MapDOMOffsetToTextContentOffset, Basic) {
}
}
-// TODO(kojii): Include LayoutNG tests by switching to
-// ParameterizedLayoutTextTest when these functions support LayoutNG.
-TEST_F(LayoutTextTest, CharacterAfterWhitespaceCollapsing) {
+TEST_P(ParameterizedLayoutTextTest, CharacterAfterWhitespaceCollapsing) {
SetBodyInnerHTML("a<span id=target> b </span>");
LayoutText* layout_text = GetLayoutTextById("target");
EXPECT_EQ(' ', layout_text->FirstCharacterAfterWhitespaceCollapsing());
@@ -272,6 +270,11 @@ TEST_F(LayoutTextTest, CharacterAfterWhitespaceCollapsing) {
DCHECK(!layout_text->HasTextBoxes());
EXPECT_EQ(0, layout_text->FirstCharacterAfterWhitespaceCollapsing());
EXPECT_EQ(0, layout_text->LastCharacterAfterWhitespaceCollapsing());
+
+ SetBodyInnerHTML("<b id=target>&#x1F34C;_&#x1F34D;</b>");
+ layout_text = GetLayoutTextById("target");
+ EXPECT_EQ(0x1F34C, layout_text->FirstCharacterAfterWhitespaceCollapsing());
+ EXPECT_EQ(0x1F34D, layout_text->LastCharacterAfterWhitespaceCollapsing());
}
TEST_P(ParameterizedLayoutTextTest, CaretMinMaxOffset) {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme.cc b/chromium/third_party/blink/renderer/core/layout/layout_theme.cc
index 3de4d5780b3..b5aee03b8c5 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme.cc
@@ -58,10 +58,10 @@
#include "third_party/blink/renderer/platform/fonts/string_truncator.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/theme.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "ui/native_theme/native_theme.h"
@@ -101,12 +101,10 @@ void GetAutofillPreviewColorsFromFieldTrial(std::string* color,
// Wrapper function defined in WebKit.h
void SetMockThemeEnabledForTest(bool value) {
- LayoutTestSupport::SetMockThemeEnabledForTest(value);
+ WebTestSupport::SetMockThemeEnabledForTest(value);
LayoutTheme::GetTheme().DidChangeThemeEngine();
}
-using namespace HTMLNames;
-
LayoutTheme& LayoutTheme::GetTheme() {
if (RuntimeEnabledFeatures::MobileLayoutThemeEnabled()) {
DEFINE_STATIC_REF(LayoutTheme, layout_theme_mobile,
@@ -644,7 +642,7 @@ TimeDelta LayoutTheme::AnimationDurationForProgressBar() const {
bool LayoutTheme::ShouldHaveSpinButton(HTMLInputElement* input_element) const {
return input_element->IsSteppable() &&
- input_element->type() != InputTypeNames::range;
+ input_element->type() != input_type_names::kRange;
}
void LayoutTheme::AdjustMenuListButtonStyle(ComputedStyle&, Element*) const {}
@@ -684,8 +682,8 @@ void LayoutTheme::SetCaretBlinkInterval(TimeDelta interval) {
TimeDelta LayoutTheme::CaretBlinkInterval() const {
// Disable the blinking caret in layout test mode, as it introduces
// a race condition for the pixel tests. http://b/1198440
- return LayoutTestSupport::IsRunningLayoutTest() ? TimeDelta()
- : caret_blink_interval_;
+ return WebTestSupport::IsRunningWebTest() ? TimeDelta()
+ : caret_blink_interval_;
}
static FontDescription& GetCachedFontDescription(CSSValueID system_font_id) {
@@ -874,9 +872,10 @@ bool LayoutTheme::ShouldOpenPickerWithF4Key() const {
bool LayoutTheme::SupportsCalendarPicker(const AtomicString& type) const {
DCHECK(RuntimeEnabledFeatures::InputMultipleFieldsUIEnabled());
- return type == InputTypeNames::date || type == InputTypeNames::datetime ||
- type == InputTypeNames::datetime_local ||
- type == InputTypeNames::month || type == InputTypeNames::week;
+ return type == input_type_names::kDate ||
+ type == input_type_names::kDatetime ||
+ type == input_type_names::kDatetimeLocal ||
+ type == input_type_names::kMonth || type == input_type_names::kWeek;
}
bool LayoutTheme::ShouldUseFallbackTheme(const ComputedStyle&) const {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme.h b/chromium/third_party/blink/renderer/core/layout/layout_theme.h
index 61e2790d404..d3b89e41ba2 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme.h
@@ -26,8 +26,8 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/platform/fonts/font_selection_types.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/theme_types.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_default.cc b/chromium/third_party/blink/renderer/core/layout/layout_theme_default.cc
index 18bd95dfb4c..5c154fb4891 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_default.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_default.cc
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -44,7 +44,7 @@ static const float kMinCancelButtonSize = 5;
static const float kMaxCancelButtonSize = 21;
static bool UseMockTheme() {
- return LayoutTestSupport::IsMockThemeEnabledForTest();
+ return WebTestSupport::IsMockThemeEnabledForTest();
}
unsigned LayoutThemeDefault::active_selection_background_color_ = 0xff1e90ff;
@@ -92,9 +92,9 @@ String LayoutThemeDefault::ExtraDefaultStyleSheet() {
String extra_style_sheet = LayoutTheme::ExtraDefaultStyleSheet();
String multiple_fields_style_sheet =
RuntimeEnabledFeatures::InputMultipleFieldsUIEnabled()
- ? GetDataResourceAsASCIIString("themeInputMultipleFields.css")
+ ? GetDataResourceAsASCIIString("input_multiple_fields.css")
: String();
- String windows_style_sheet = GetDataResourceAsASCIIString("themeWin.css");
+ String windows_style_sheet = GetDataResourceAsASCIIString("win.css");
StringBuilder builder;
builder.ReserveCapacity(extra_style_sheet.length() +
multiple_fields_style_sheet.length() +
@@ -106,7 +106,7 @@ String LayoutThemeDefault::ExtraDefaultStyleSheet() {
}
String LayoutThemeDefault::ExtraQuirksStyleSheet() {
- return GetDataResourceAsASCIIString("themeWinQuirks.css");
+ return GetDataResourceAsASCIIString("win_quirks.css");
}
Color LayoutThemeDefault::ActiveListBoxSelectionBackgroundColor() const {
@@ -162,6 +162,9 @@ int LayoutThemeDefault::SliderTickOffsetFromTrackCenter() const {
}
void LayoutThemeDefault::AdjustSliderThumbSize(ComputedStyle& style) const {
+ if (!Platform::Current()->ThemeEngine())
+ return;
+
IntSize size = Platform::Current()->ThemeEngine()->GetSize(
WebThemeEngine::kPartSliderThumb);
@@ -290,9 +293,9 @@ void LayoutThemeDefault::AdjustSearchFieldCancelButtonStyle(
ComputedStyle& style) const {
// Scale the button size based on the font size
float font_scale = style.FontSize() / kDefaultControlFontPixelSize;
- int cancel_button_size = lroundf(std::min(
+ int cancel_button_size = static_cast<int>(lroundf(std::min(
std::max(kMinCancelButtonSize, kDefaultCancelButtonSize * font_scale),
- kMaxCancelButtonSize));
+ kMaxCancelButtonSize)));
style.SetWidth(Length(cancel_button_size, kFixed));
style.SetHeight(Length(cancel_button_size, kFixed));
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_linux.cc b/chromium/third_party/blink/renderer/core/layout/layout_theme_linux.cc
index 73418a4804d..6033536b4be 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_linux.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_linux.cc
@@ -19,7 +19,7 @@ LayoutTheme& LayoutTheme::NativeTheme() {
String LayoutThemeLinux::ExtraDefaultStyleSheet() {
return LayoutThemeDefault::ExtraDefaultStyleSheet() +
- GetDataResourceAsASCIIString("themeChromiumLinux.css");
+ GetDataResourceAsASCIIString("linux.css");
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm b/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm
index 3c60c8a5e53..2563c9fb78b 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm
@@ -24,6 +24,9 @@
#import <Carbon/Carbon.h>
#import <Cocoa/Cocoa.h>
#import <math.h>
+
+#import "third_party/blink/public/platform/mac/web_sandbox_support.h"
+#import "third_party/blink/public/platform/platform.h"
#import "third_party/blink/renderer/core/css_value_keywords.h"
#import "third_party/blink/renderer/core/fileapi/file_list.h"
#import "third_party/blink/renderer/core/html_names.h"
@@ -33,7 +36,6 @@
#import "third_party/blink/renderer/platform/data_resource_helper.h"
#import "third_party/blink/renderer/platform/fonts/string_truncator.h"
#import "third_party/blink/renderer/platform/graphics/bitmap_image.h"
-#import "third_party/blink/renderer/platform/layout_test_support.h"
#import "third_party/blink/renderer/platform/mac/color_mac.h"
#import "third_party/blink/renderer/platform/mac/theme_mac.h"
#import "third_party/blink/renderer/platform/mac/version_util_mac.h"
@@ -41,6 +43,7 @@
#import "third_party/blink/renderer/platform/runtime_enabled_features.h"
#import "third_party/blink/renderer/platform/text/platform_locale.h"
#import "third_party/blink/renderer/platform/theme.h"
+#import "third_party/blink/renderer/platform/web_test_support.h"
// The methods in this file are specific to the Mac OS X platform.
@@ -128,14 +131,17 @@ bool FontSizeMatchesToControlSize(const ComputedStyle& style) {
return false;
}
-NSColor* ColorInColorSpace(NSColor* color) {
- return [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]];
+Color GetSystemColor(MacSystemColorID color_id) {
+ // In tests, a WebSandboxSupport may not be set up. Just return a dummy
+ // color, in this case, black.
+ auto* sandbox_support = Platform::Current()->GetSandboxSupport();
+ if (!sandbox_support)
+ return Color();
+ return sandbox_support->GetSystemColor(color_id);
}
} // namespace
-using namespace HTMLNames;
-
LayoutThemeMac::LayoutThemeMac()
: LayoutTheme(PlatformTheme()),
notification_observer_(
@@ -155,17 +161,11 @@ LayoutThemeMac::~LayoutThemeMac() {
}
Color LayoutThemeMac::PlatformActiveSelectionBackgroundColor() const {
- NSColor* color = ColorInColorSpace([NSColor selectedTextBackgroundColor]);
- return Color(static_cast<int>(255.0 * [color redComponent]),
- static_cast<int>(255.0 * [color greenComponent]),
- static_cast<int>(255.0 * [color blueComponent]));
+ return GetSystemColor(MacSystemColorID::kSelectedTextBackground);
}
Color LayoutThemeMac::PlatformInactiveSelectionBackgroundColor() const {
- NSColor* color = ColorInColorSpace([NSColor secondarySelectedControlColor]);
- return Color(static_cast<int>(255.0 * [color redComponent]),
- static_cast<int>(255.0 * [color greenComponent]),
- static_cast<int>(255.0 * [color blueComponent]));
+ return GetSystemColor(MacSystemColorID::kSecondarySelectedControl);
}
Color LayoutThemeMac::PlatformActiveSelectionForegroundColor() const {
@@ -173,10 +173,7 @@ Color LayoutThemeMac::PlatformActiveSelectionForegroundColor() const {
}
Color LayoutThemeMac::PlatformActiveListBoxSelectionBackgroundColor() const {
- NSColor* color = ColorInColorSpace([NSColor alternateSelectedControlColor]);
- return Color(static_cast<int>(255.0 * [color redComponent]),
- static_cast<int>(255.0 * [color greenComponent]),
- static_cast<int>(255.0 * [color blueComponent]));
+ return GetSystemColor(MacSystemColorID::kAlternateSelectedControl);
}
Color LayoutThemeMac::PlatformActiveListBoxSelectionForegroundColor() const {
@@ -262,84 +259,7 @@ void LayoutThemeMac::SystemFont(CSSValueID system_font_id,
: NormalSlopeValue();
font_weight = ToFontWeight([font_manager weightOfFont:font]);
font_size = [font pointSize];
- font_family = FontFamilyNames::system_ui;
-}
-
-static RGBA32 ConvertNSColorToColor(NSColor* color) {
- NSColor* color_in_color_space = ColorInColorSpace(color);
- if (color_in_color_space) {
- static const double kScaleFactor = nextafter(256.0, 0.0);
- return MakeRGB(
- static_cast<int>(kScaleFactor * [color_in_color_space redComponent]),
- static_cast<int>(kScaleFactor * [color_in_color_space greenComponent]),
- static_cast<int>(kScaleFactor * [color_in_color_space blueComponent]));
- }
-
- // This conversion above can fail if the NSColor in question is an
- // NSPatternColor (as many system colors are). These colors are actually a
- // repeating pattern not just a solid color. To work around this we simply
- // draw a 1x1 image of the color and use that pixel's color. It might be
- // better to use an average of the colors in the pattern instead.
- NSBitmapImageRep* offscreen_rep =
- [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
- pixelsWide:1
- pixelsHigh:1
- bitsPerSample:8
- samplesPerPixel:4
- hasAlpha:YES
- isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bytesPerRow:4
- bitsPerPixel:32];
-
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext
- setCurrentContext:[NSGraphicsContext
- graphicsContextWithBitmapImageRep:offscreen_rep]];
- NSEraseRect(NSMakeRect(0, 0, 1, 1));
- [color drawSwatchInRect:NSMakeRect(0, 0, 1, 1)];
- [NSGraphicsContext restoreGraphicsState];
-
- NSUInteger pixel[4];
- [offscreen_rep getPixel:pixel atX:0 y:0];
- [offscreen_rep release];
- // This recursive call will not recurse again, because the color space
- // the second time around is NSDeviceRGBColorSpace.
- return ConvertNSColorToColor([NSColor colorWithDeviceRed:pixel[0] / 255.
- green:pixel[1] / 255.
- blue:pixel[2] / 255.
- alpha:1.]);
-}
-
-static RGBA32 MenuBackgroundColor() {
- NSBitmapImageRep* offscreen_rep =
- [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
- pixelsWide:1
- pixelsHigh:1
- bitsPerSample:8
- samplesPerPixel:4
- hasAlpha:YES
- isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bytesPerRow:4
- bitsPerPixel:32];
-
- CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext
- graphicsContextWithBitmapImageRep:offscreen_rep] graphicsPort]);
- CGRect rect = CGRectMake(0, 0, 1, 1);
- HIThemeMenuDrawInfo draw_info;
- draw_info.version = 0;
- draw_info.menuType = kThemeMenuTypePopUp;
- HIThemeDrawMenuBackground(&rect, &draw_info, context,
- kHIThemeOrientationInverted);
-
- NSUInteger pixel[4];
- [offscreen_rep getPixel:pixel atX:0 y:0];
- [offscreen_rep release];
- return ConvertNSColorToColor([NSColor colorWithDeviceRed:pixel[0] / 255.
- green:pixel[1] / 255.
- blue:pixel[2] / 255.
- alpha:1.]);
+ font_family = font_family_names::kSystemUi;
}
void LayoutThemeMac::PlatformColorsDidChange() {
@@ -358,50 +278,50 @@ Color LayoutThemeMac::SystemColor(CSSValueID css_value_id) const {
bool needs_fallback = false;
switch (css_value_id) {
case CSSValueActiveborder:
- color = ConvertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
+ color = GetSystemColor(MacSystemColorID::kKeyboardFocusIndicator);
break;
case CSSValueActivecaption:
- color = ConvertNSColorToColor([NSColor windowFrameTextColor]);
+ color = GetSystemColor(MacSystemColorID::kWindowFrameText);
break;
case CSSValueAppworkspace:
- color = ConvertNSColorToColor([NSColor headerColor]);
+ color = GetSystemColor(MacSystemColorID::kHeader);
break;
case CSSValueBackground:
// Use theme independent default
needs_fallback = true;
break;
case CSSValueButtonface:
- color = ConvertNSColorToColor([NSColor controlBackgroundColor]);
+ color = GetSystemColor(MacSystemColorID::kControlBackground);
break;
case CSSValueButtonhighlight:
- color = ConvertNSColorToColor([NSColor controlHighlightColor]);
+ color = GetSystemColor(MacSystemColorID::kControlHighlight);
break;
case CSSValueButtonshadow:
- color = ConvertNSColorToColor([NSColor controlShadowColor]);
+ color = GetSystemColor(MacSystemColorID::kControlShadow);
break;
case CSSValueButtontext:
- color = ConvertNSColorToColor([NSColor controlTextColor]);
+ color = GetSystemColor(MacSystemColorID::kControlText);
break;
case CSSValueCaptiontext:
- color = ConvertNSColorToColor([NSColor textColor]);
+ color = GetSystemColor(MacSystemColorID::kText);
break;
case CSSValueGraytext:
- color = ConvertNSColorToColor([NSColor disabledControlTextColor]);
+ color = GetSystemColor(MacSystemColorID::kDisabledControlText);
break;
case CSSValueHighlight:
- color = ConvertNSColorToColor([NSColor selectedTextBackgroundColor]);
+ color = GetSystemColor(MacSystemColorID::kSelectedTextBackground);
break;
case CSSValueHighlighttext:
- color = ConvertNSColorToColor([NSColor selectedTextColor]);
+ color = GetSystemColor(MacSystemColorID::kSelectedText);
break;
case CSSValueInactiveborder:
- color = ConvertNSColorToColor([NSColor controlBackgroundColor]);
+ color = GetSystemColor(MacSystemColorID::kControlBackground);
break;
case CSSValueInactivecaption:
- color = ConvertNSColorToColor([NSColor controlBackgroundColor]);
+ color = GetSystemColor(MacSystemColorID::kControlBackground);
break;
case CSSValueInactivecaptiontext:
- color = ConvertNSColorToColor([NSColor textColor]);
+ color = GetSystemColor(MacSystemColorID::kText);
break;
case CSSValueInfobackground:
// There is no corresponding NSColor for this so we use a hard coded
@@ -409,25 +329,25 @@ Color LayoutThemeMac::SystemColor(CSSValueID css_value_id) const {
color = 0xFFFBFCC5;
break;
case CSSValueInfotext:
- color = ConvertNSColorToColor([NSColor textColor]);
+ color = GetSystemColor(MacSystemColorID::kText);
break;
case CSSValueMenu:
- color = MenuBackgroundColor();
+ color = GetSystemColor(MacSystemColorID::kMenuBackground);
break;
case CSSValueMenutext:
- color = ConvertNSColorToColor([NSColor selectedMenuItemTextColor]);
+ color = GetSystemColor(MacSystemColorID::kSelectedMenuItemText);
break;
case CSSValueScrollbar:
- color = ConvertNSColorToColor([NSColor scrollBarColor]);
+ color = GetSystemColor(MacSystemColorID::kScrollBar);
break;
case CSSValueText:
- color = ConvertNSColorToColor([NSColor textColor]);
+ color = GetSystemColor(MacSystemColorID::kText);
break;
case CSSValueThreeddarkshadow:
- color = ConvertNSColorToColor([NSColor controlDarkShadowColor]);
+ color = GetSystemColor(MacSystemColorID::kControlDarkShadow);
break;
case CSSValueThreedshadow:
- color = ConvertNSColorToColor([NSColor shadowColor]);
+ color = GetSystemColor(MacSystemColorID::kShadow);
break;
case CSSValueThreedface:
// We use this value instead of NSColor's controlColor to avoid website
@@ -436,22 +356,22 @@ Color LayoutThemeMac::SystemColor(CSSValueID css_value_id) const {
color = 0xFFC0C0C0;
break;
case CSSValueThreedhighlight:
- color = ConvertNSColorToColor([NSColor highlightColor]);
+ color = GetSystemColor(MacSystemColorID::kHighlight);
break;
case CSSValueThreedlightshadow:
- color = ConvertNSColorToColor([NSColor controlLightHighlightColor]);
+ color = GetSystemColor(MacSystemColorID::kControlLightHighlight);
break;
case CSSValueWebkitFocusRingColor:
- color = ConvertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
+ color = GetSystemColor(MacSystemColorID::kKeyboardFocusIndicator);
break;
case CSSValueWindow:
- color = ConvertNSColorToColor([NSColor windowBackgroundColor]);
+ color = GetSystemColor(MacSystemColorID::kWindowBackground);
break;
case CSSValueWindowframe:
- color = ConvertNSColorToColor([NSColor windowFrameColor]);
+ color = GetSystemColor(MacSystemColorID::kWindowFrame);
break;
case CSSValueWindowtext:
- color = ConvertNSColorToColor([NSColor windowFrameTextColor]);
+ color = GetSystemColor(MacSystemColorID::kWindowFrameText);
break;
default:
needs_fallback = true;
@@ -483,7 +403,7 @@ bool LayoutThemeMac::IsControlStyled(const ComputedStyle& style) const {
if (!FontSizeMatchesToControlSize(style))
return true;
if (style.GetFontDescription().Family().Family() !=
- FontFamilyNames::system_ui)
+ font_family_names::kSystemUi)
return true;
if (!style.Height().IsIntrinsicOrAuto())
return true;
@@ -649,7 +569,7 @@ void LayoutThemeMac::SetFontFromControlSize(ComputedStyle& style,
NSFont* font = [NSFont
systemFontOfSize:[NSFont systemFontSizeForControlSize:control_size]];
- font_description.FirstFamily().SetFamily(FontFamilyNames::system_ui);
+ font_description.FirstFamily().SetFamily(font_family_names::kSystemUi);
font_description.SetComputedSize([font pointSize] * style.EffectiveZoom());
font_description.SetSpecifiedSize([font pointSize] * style.EffectiveZoom());
@@ -1050,7 +970,7 @@ scoped_refptr<LayoutTheme> LayoutThemeMac::Create() {
}
bool LayoutThemeMac::UsesTestModeFocusRingColor() const {
- return LayoutTestSupport::IsRunningLayoutTest();
+ return WebTestSupport::IsRunningWebTest();
}
NSView* LayoutThemeMac::DocumentView() const {
@@ -1084,8 +1004,8 @@ String LayoutThemeMac::ExtraFullscreenStyleSheet() {
String LayoutThemeMac::ExtraDefaultStyleSheet() {
return LayoutTheme::ExtraDefaultStyleSheet() +
- GetDataResourceAsASCIIString("themeInputMultipleFields.css") +
- GetDataResourceAsASCIIString("themeMac.css");
+ GetDataResourceAsASCIIString("input_multiple_fields.css") +
+ GetDataResourceAsASCIIString("mac.css");
}
bool LayoutThemeMac::ThemeDrawsFocusRing(const ComputedStyle& style) const {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_mobile.cc b/chromium/third_party/blink/renderer/core/layout/layout_theme_mobile.cc
index f0b845c633d..34ebc54d40c 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_mobile.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_mobile.cc
@@ -30,7 +30,7 @@
#include "third_party/blink/public/platform/web_theme_engine.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -42,8 +42,8 @@ LayoutThemeMobile::~LayoutThemeMobile() = default;
String LayoutThemeMobile::ExtraDefaultStyleSheet() {
return LayoutThemeDefault::ExtraDefaultStyleSheet() +
- GetDataResourceAsASCIIString("themeChromiumLinux.css") +
- GetDataResourceAsASCIIString("themeChromiumAndroid.css");
+ GetDataResourceAsASCIIString("linux.css") +
+ GetDataResourceAsASCIIString("android.css");
}
String LayoutThemeMobile::ExtraFullscreenStyleSheet() {
@@ -51,7 +51,7 @@ String LayoutThemeMobile::ExtraFullscreenStyleSheet() {
}
void LayoutThemeMobile::AdjustInnerSpinButtonStyle(ComputedStyle& style) const {
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
// Match Linux spin button style in layout tests.
// FIXME: Consider removing the conditional if a future Android theme
// matches this.
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_theme_test.cc
index 013a073bbb7..eb401429dff 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_test.cc
@@ -26,7 +26,7 @@ class LayoutThemeTest : public PageTestBase {
void LayoutThemeTest::SetHtmlInnerHTML(const char* html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
inline Color OutlineColor(Element* element) {
@@ -55,7 +55,7 @@ TEST_F(LayoutThemeTest, ChangeFocusRingColor) {
GetDocument().GetPage()->GetFocusController().SetActive(true);
GetDocument().GetPage()->GetFocusController().SetFocused(true);
span->focus();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Checking focused style.
EXPECT_NE(EBorderStyle::kNone, OutlineStyle(span));
@@ -64,7 +64,7 @@ TEST_F(LayoutThemeTest, ChangeFocusRingColor) {
// Change focus ring color.
LayoutTheme::GetTheme().SetCustomFocusRingColor(custom_color);
Page::PlatformColorsChanged();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Check that the focus ring color is updated.
EXPECT_NE(EBorderStyle::kNone, OutlineStyle(span));
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.cc b/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.cc
index 5aff0e67a0c..ab89c956050 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.cc
@@ -60,15 +60,13 @@
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/hex_number.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
-using namespace HTMLNames;
-
static void PrintBorderStyle(WTF::TextStream& ts,
const EBorderStyle border_style) {
switch (border_style) {
@@ -318,7 +316,7 @@ void LayoutTreeAsText::WriteLayoutObject(WTF::TextStream& ts,
if (element.HasClass()) {
ts << " class=\"";
- for (size_t i = 0; i < element.ClassNames().size(); ++i) {
+ for (wtf_size_t i = 0; i < element.ClassNames().size(); ++i) {
if (i > 0)
ts << " ";
ts << element.ClassNames()[i];
@@ -560,7 +558,7 @@ void Write(WTF::TextStream& ts,
if (o.IsText() && !o.IsBR()) {
const LayoutText& text = ToLayoutText(o);
if (const NGPhysicalBoxFragment* box_fragment =
- text.EnclosingBlockFlowFragment()) {
+ text.ContainingBlockFlowFragment()) {
for (const auto& child :
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, &text)) {
WriteIndent(ts, indent + 1);
@@ -587,9 +585,7 @@ void Write(WTF::TextStream& ts,
if (auto* layout_view = ToLocalFrameView(frame_view)->GetLayoutView()) {
layout_view->GetDocument().UpdateStyleAndLayout();
if (auto* layer = layout_view->Layer()) {
- LayoutTreeAsText::WriteLayers(
- ts, layer, layer, layer->RectIgnoringNeedsPositionUpdate(),
- indent + 1, behavior);
+ LayoutTreeAsText::WriteLayers(ts, layer, layer, indent + 1, behavior);
}
}
}
@@ -707,7 +703,6 @@ static PaintLayerStackingNode::PaintLayers NormalFlowListFor(
void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
const PaintLayer* root_layer,
PaintLayer* layer,
- const LayoutRect& paint_rect,
int indent,
LayoutAsTextBehavior behavior,
const PaintLayer* marked_layer) {
@@ -719,7 +714,7 @@ void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
ClipRectsContext(root_layer,
&root_layer->GetLayoutObject().FirstFragment(),
kUncachedClipRects),
- &layer->GetLayoutObject().FirstFragment(), &paint_rect, layer_bounds,
+ &layer->GetLayoutObject().FirstFragment(), nullptr, layer_bounds,
damage_rect, clip_rect_to_apply);
LayoutPoint offset_from_root;
@@ -760,8 +755,8 @@ void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
++curr_indent;
}
for (unsigned i = 0; i != neg_list->size(); ++i) {
- WriteLayers(ts, root_layer, neg_list->at(i), paint_rect, curr_indent,
- behavior, marked_layer);
+ WriteLayers(ts, root_layer, neg_list->at(i), curr_indent, behavior,
+ marked_layer);
}
}
}
@@ -785,8 +780,8 @@ void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
++curr_indent;
}
for (unsigned i = 0; i != normal_flow_list.size(); ++i) {
- WriteLayers(ts, root_layer, normal_flow_list.at(i), paint_rect,
- curr_indent, behavior, marked_layer);
+ WriteLayers(ts, root_layer, normal_flow_list.at(i), curr_indent,
+ behavior, marked_layer);
}
}
@@ -799,8 +794,8 @@ void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
++curr_indent;
}
for (unsigned i = 0; i != pos_list->size(); ++i) {
- WriteLayers(ts, root_layer, pos_list->at(i), paint_rect, curr_indent,
- behavior, marked_layer);
+ WriteLayers(ts, root_layer, pos_list->at(i), curr_indent, behavior,
+ marked_layer);
}
}
}
@@ -874,9 +869,7 @@ static String ExternalRepresentation(LayoutBox* layout_object,
return ts.Release();
PaintLayer* layer = layout_object->Layer();
- LayoutTreeAsText::WriteLayers(ts, layer, layer,
- layer->RectIgnoringNeedsPositionUpdate(), 0,
- behavior, marked_layer);
+ LayoutTreeAsText::WriteLayers(ts, layer, layer, 0, behavior, marked_layer);
WriteSelection(ts, layout_object);
return ts.Release();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.h b/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.h
index 2c6191a187d..9b46537c3ec 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.h
@@ -36,7 +36,6 @@ namespace blink {
class Color;
class PaintLayer;
class Element;
-class LayoutRect;
class LocalFrame;
class LayoutBlockFlow;
class LayoutObject;
@@ -94,7 +93,6 @@ class LayoutTreeAsText {
static void WriteLayers(WTF::TextStream&,
const PaintLayer* root_layer,
PaintLayer*,
- const LayoutRect& paint_dirty_rect,
int indent = 0,
LayoutAsTextBehavior = kLayoutAsTextBehaviorNormal,
const PaintLayer* marked_layer = nullptr);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_video.cc b/chromium/third_party/blink/renderer/core/layout/layout_video.cc
index a5357719d85..a9a9763ef6c 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_video.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_video.cc
@@ -33,8 +33,6 @@
namespace blink {
-using namespace HTMLNames;
-
LayoutVideo::LayoutVideo(HTMLVideoElement* video) : LayoutMedia(video) {
SetIntrinsicSize(CalculateIntrinsicSize());
}
@@ -66,7 +64,7 @@ void LayoutVideo::UpdateIntrinsicSize() {
SetIntrinsicSize(size);
SetPreferredLogicalWidthsDirty();
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
}
LayoutSize LayoutVideo::CalculateIntrinsicSize() {
@@ -203,7 +201,7 @@ void LayoutVideo::UpdateAfterLayout() {
// Report violation of unsized-media policy.
if (auto* video_element = ToHTMLVideoElementOrNull(GetNode())) {
if (video_element->IsDefaultIntrinsicSize())
- MediaElementParserHelpers::ReportUnsizedMediaViolation(this);
+ media_element_parser_helpers::ReportUnsizedMediaViolation(this);
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_view.cc b/chromium/third_party/blink/renderer/core/layout/layout_view.cc
index 11d3e763ab7..0b71fa97f23 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_view.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_view.cc
@@ -43,6 +43,7 @@
#include "third_party/blink/renderer/core/layout/view_fragmentation_context.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
+#include "third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h"
#include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_context.h"
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
@@ -111,6 +112,13 @@ LayoutView::LayoutView(Document* document)
SetPreferredLogicalWidthsDirty(kMarkOnlyThis);
SetPositionState(EPosition::kAbsolute); // to 0,0 :)
+
+ // Update the cached bit here since the Document is made the effective root
+ // scroller before we've created the layout tree.
+ if (GetDocument().GetRootScrollerController().EffectiveRootScroller() ==
+ GetDocument()) {
+ SetIsEffectiveRootScroller(true);
+ }
}
LayoutView::~LayoutView() = default;
@@ -121,7 +129,7 @@ bool LayoutView::HitTest(const HitTestLocation& location,
// hit test recurses into a child document, it could trigger a layout on the
// parent document, which can destroy PaintLayer that are higher up in the
// call stack, leading to crashes.
- // Note that Document::updateLayout calls its parent's updateLayout.
+ // Note that Document::UpdateLayout calls its parent's UpdateLayout.
// Note that if an iframe has its render pipeline throttled, it will not
// update layout here, and it will also not propagate the hit test into the
// iframe's inner document.
@@ -189,8 +197,8 @@ bool LayoutView::HitTestNoLifecycleUpdate(const HitTestLocation& location,
}
TRACE_EVENT_END1("blink,devtools.timeline", "HitTest", "endData",
- InspectorHitTestEvent::EndData(result.GetHitTestRequest(),
- location, result));
+ inspector_hit_test_event::EndData(result.GetHitTestRequest(),
+ location, result));
return hit_layer;
}
@@ -221,8 +229,6 @@ bool LayoutView::CanHaveChildren() const {
FrameOwner* owner = GetFrame()->Owner();
if (!owner)
return true;
- if (!RuntimeEnabledFeatures::DisplayNoneIFrameCreatesNoLayoutObjectEnabled())
- return true;
// Although it is not spec compliant, many websites intentionally call
// Window.print() on display:none iframes. https://crbug.com/819327.
if (GetDocument().Printing())
@@ -243,29 +249,6 @@ void LayoutView::CheckLayoutState() {
}
#endif
-void LayoutView::SetShouldDoFullPaintInvalidationOnResizeIfNeeded(
- bool width_changed,
- bool height_changed) {
- // When background-attachment is 'fixed', we treat the viewport (instead of
- // the 'root' i.e. html or body) as the background positioning area, and we
- // should fully invalidate on viewport resize if the background image is not
- // composited and needs full paint invalidation on background positioning area
- // resize.
- if (StyleRef().HasFixedBackgroundImage()) {
- if ((width_changed && MustInvalidateFillLayersPaintOnWidthChange(
- StyleRef().BackgroundLayers())) ||
- (height_changed && MustInvalidateFillLayersPaintOnHeightChange(
- StyleRef().BackgroundLayers()))) {
- SetShouldDoFullPaintInvalidation(PaintInvalidationReason::kBackground);
- // In case that the background will be painted on the scrolling contents
- // layer, we need this to invalidate the background.
- // TODO(wangxianzhu): Clean up and fix other such cases about invalidation
- // of background painted on the scrolling contents layer.
- SetBackgroundChangedSinceLastPaintInvalidation();
- }
- }
-}
-
bool LayoutView::ShouldPlaceBlockDirectionScrollbarOnLogicalLeft() const {
LocalFrame& frame = GetFrameView()->GetFrame();
// See crbug.com/249860
@@ -322,11 +305,6 @@ void LayoutView::UpdateLayout() {
if (!GetDocument().Printing())
SetPageLogicalHeight(LayoutUnit());
- // TODO(wangxianzhu): Move this into ViewPaintInvalidator.
- SetShouldDoFullPaintInvalidationOnResizeIfNeeded(
- OffsetWidth() != GetLayoutSize(kIncludeScrollbars).Width(),
- OffsetHeight() != GetLayoutSize(kIncludeScrollbars).Height());
-
if (PageLogicalHeight() && ShouldUsePrintingLayout()) {
min_preferred_logical_width_ = max_preferred_logical_width_ =
LogicalWidth();
@@ -626,9 +604,10 @@ LayoutRect LayoutView::OverflowClipRect(
const LayoutPoint& location,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior) const {
LayoutRect rect = ViewRect();
- if (rect.IsEmpty())
+ if (rect.IsEmpty()) {
return LayoutBox::OverflowClipRect(location,
overlay_scrollbar_clip_behavior);
+ }
rect.SetLocation(location);
if (HasOverflowClip())
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_view.h b/chromium/third_party/blink/renderer/core/layout/layout_view.h
index 9129fdca4a7..63534044824 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_view.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_view.h
@@ -236,9 +236,6 @@ class CORE_EXPORT LayoutView final : public LayoutBlockFlow {
// It is very likely you do not want to call this method.
void SetShouldDoFullPaintInvalidationForViewAndAllDescendants();
- void SetShouldDoFullPaintInvalidationOnResizeIfNeeded(bool width_changed,
- bool height_changed);
-
bool ShouldPlaceBlockDirectionScrollbarOnLogicalLeft() const override;
LayoutRect DebugRect() const override;
@@ -257,6 +254,23 @@ class CORE_EXPORT LayoutView final : public LayoutBlockFlow {
bool RecalcOverflow() override;
+ // The visible background area, in the local coordinates. The view background
+ // will be painted in this rect. It's also the positioning area of fixed-
+ // attachment backgrounds.
+ LayoutRect BackgroundRect() const { return OverflowClipRect(LayoutPoint()); }
+
+ // The previous BackgroundRect after the previous paint invalidation.
+ LayoutRect PreviousBackgroundRect() const {
+ DCHECK_EQ(GetDocument().Lifecycle().GetState(),
+ DocumentLifecycle::kInPrePaint);
+ return previous_background_rect_;
+ }
+ void SetPreviousBackgroundRect(const LayoutRect& r) const {
+ DCHECK_EQ(GetDocument().Lifecycle().GetState(),
+ DocumentLifecycle::kInPrePaint);
+ previous_background_rect_ = r;
+ }
+
private:
void MapLocalToAncestor(
const LayoutBoxModelObject* ancestor,
@@ -325,6 +339,8 @@ class CORE_EXPORT LayoutView final : public LayoutBlockFlow {
ScrollbarMode autosize_v_scrollbar_mode_;
Vector<IntRect> tickmarks_override_;
+
+ mutable LayoutRect previous_background_rect_;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutView, IsLayoutView());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_view_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_view_test.cc
index d76321fad3b..6cda24cf7ad 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_view_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_view_test.cc
@@ -20,14 +20,14 @@ TEST_F(LayoutViewTest, UpdateCountersLayout) {
<div id=inc></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* inc = GetDocument().getElementById("inc");
inc->setAttribute("class", "incX");
GetDocument().UpdateStyleAndLayoutTree();
EXPECT_FALSE(GetDocument().View()->NeedsLayout());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
inc->setAttribute("class", "incY");
GetDocument().UpdateStyleAndLayoutTree();
EXPECT_TRUE(GetDocument().View()->NeedsLayout());
diff --git a/chromium/third_party/blink/renderer/core/layout/line/DEPS b/chromium/third_party/blink/renderer/core/layout/line/DEPS
index 9b76eeb5c12..8578476ba5c 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/DEPS
+++ b/chromium/third_party/blink/renderer/core/layout/line/DEPS
@@ -3,6 +3,7 @@ include_rules = [
"-third_party/blink/renderer/core/layout",
"+third_party/blink/renderer/core/layout/api",
"+third_party/blink/renderer/core/layout/line",
+ "+third_party/blink/renderer/core/layout/logical_values.h",
"+third_party/blink/renderer/platform",
"!third_party/blink/renderer/core/layout/bidi_run.h",
diff --git a/chromium/third_party/blink/renderer/core/layout/line/abstract_inline_text_box.cc b/chromium/third_party/blink/renderer/core/layout/line/abstract_inline_text_box.cc
index 2d8baac93aa..b3147d31bd9 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/abstract_inline_text_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/abstract_inline_text_box.cc
@@ -207,7 +207,7 @@ String LegacyAbstractInlineTextBox::GetText() const {
if (inline_text_box_->NextForSameLayoutObject() &&
inline_text_box_->NextForSameLayoutObject()->Start() >
inline_text_box_->end() &&
- result.length() && !result.Right(1).ContainsOnlyWhitespace())
+ result.length() && !result.Right(1).ContainsOnlyWhitespaceOrEmpty())
return result + " ";
return result;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/line/breaking_context_inline_headers.h b/chromium/third_party/blink/renderer/core/layout/line/breaking_context_inline_headers.h
index 9a81d6a19a7..be12bbc0dae 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/breaking_context_inline_headers.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/breaking_context_inline_headers.h
@@ -39,6 +39,7 @@
#include "third_party/blink/renderer/core/layout/line/line_width.h"
#include "third_party/blink/renderer/core/layout/line/trailing_objects.h"
#include "third_party/blink/renderer/core/layout/line/word_measurement.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/text_run_constructor.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/platform/fonts/character_range.h"
@@ -208,6 +209,7 @@ class BreakingContext {
bool ignoring_spaces_;
bool current_character_is_space_;
bool single_leading_space_;
+ unsigned current_start_offset_; // initial offset for the current text
bool applied_start_width_;
bool include_end_width_;
bool auto_wrap_;
@@ -379,6 +381,10 @@ inline void BreakingContext::InitializeForCurrentObject() {
if (collapse_white_space_ && !ComputedStyle::CollapseWhiteSpace(last_ws_))
current_character_is_space_ = false;
+ // Since current_ iterates all along the text's length, we need to store the
+ // initial offset of the current handle text so that we can then identify
+ // a single leading white-space as potential breaking opportunities.
+ current_start_offset_ = current_.Offset();
single_leading_space_ = false;
}
@@ -416,7 +422,7 @@ inline void BreakingContext::HandleBR(EClear& clear) {
EnsureLineBoxInsideIgnoredSpaces(&line_midpoint_state_, br);
if (!line_info_.IsEmpty())
- clear = current_style_->Clear();
+ clear = ResolvedClear(*current_style_, block_.StyleRef());
}
at_end_ = true;
}
@@ -698,17 +704,17 @@ ALWAYS_INLINE void BreakingContext::SetCurrentCharacterIsSpace(UChar c) {
}
inline float FirstPositiveWidth(const WordMeasurements& word_measurements) {
- for (size_t i = 0; i < word_measurements.size(); ++i) {
- if (word_measurements[i].width > 0)
- return word_measurements[i].width;
+ for (const WordMeasurement& word_measurement : word_measurements) {
+ if (word_measurement.width > 0)
+ return word_measurement.width;
}
return 0;
}
ALWAYS_INLINE TextDirection
-TextDirectionFromUnicode(WTF::Unicode::CharDirection direction) {
- return direction == WTF::Unicode::kRightToLeft ||
- direction == WTF::Unicode::kRightToLeftArabic
+TextDirectionFromUnicode(WTF::unicode::CharDirection direction) {
+ return direction == WTF::unicode::kRightToLeft ||
+ direction == WTF::unicode::kRightToLeftArabic
? TextDirection::kRtl
: TextDirection::kLtr;
}
@@ -1362,7 +1368,7 @@ inline void BreakingContext::PrepareForNextCharacter(
if (auto_wrap_ && current_style_->BreakOnlyAfterWhiteSpace()) {
line_break_.MoveTo(current_.GetLineLayoutItem(), current_.Offset(),
current_.NextBreakablePosition());
- if (current_.Offset() == 1)
+ if (current_.Offset() == current_start_offset_ + 1)
single_leading_space_ = true;
}
}
@@ -1426,7 +1432,7 @@ inline bool BreakingContext::TrailingSpaceExceedsAvailableWidth(
// If we break only after white-space, consider the current character
// as candidate width for this line.
if (width_.FitsOnLine() && current_character_is_space_ &&
- current_style_->BreakOnlyAfterWhiteSpace() && !can_break_mid_word) {
+ current_style_->BreakOnlyAfterWhiteSpace()) {
float char_width = TextWidth(layout_text, current_.Offset(), 1, font,
width_.CurrentWidth(), collapse_white_space_,
&word_measurement.fallback_fonts,
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_box.cc b/chromium/third_party/blink/renderer/core/layout/line/inline_box.cc
index 5df6f360650..70f6d1c644e 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_box.cc
@@ -389,7 +389,7 @@ void InlineBox::SetLineLayoutItemShouldDoFullPaintInvalidationIfNeeded() {
bool CanUseInlineBox(const LayoutObject& node) {
DCHECK(node.IsText() || node.IsInline() || node.IsLayoutBlockFlow());
return !RuntimeEnabledFeatures::LayoutNGEnabled() ||
- !node.EnclosingNGBlockFlow();
+ !node.ContainingNGBlockFlow();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.cc b/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.cc
index 46ff8799881..6de638ad9a3 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.cc
@@ -22,7 +22,7 @@
#include <math.h>
#include <algorithm>
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_box.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.h b/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.h
index 7891306c124..6c14c1f5e50 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.h
@@ -54,9 +54,9 @@ class InlineFlowBox : public InlineBox {
baseline_type_(kAlphabeticBaseline),
has_annotations_before_(false),
has_annotations_after_(false),
- line_break_bidi_status_eor_(WTF::Unicode::kLeftToRight),
- line_break_bidi_status_last_strong_(WTF::Unicode::kLeftToRight),
- line_break_bidi_status_last_(WTF::Unicode::kLeftToRight),
+ line_break_bidi_status_eor_(WTF::unicode::kLeftToRight),
+ line_break_bidi_status_last_strong_(WTF::unicode::kLeftToRight),
+ line_break_bidi_status_last_(WTF::unicode::kLeftToRight),
is_first_after_page_break_(false)
#if DCHECK_IS_ON()
,
@@ -471,9 +471,9 @@ class InlineFlowBox : public InlineBox {
unsigned has_annotations_before_ : 1;
unsigned has_annotations_after_ : 1;
- unsigned line_break_bidi_status_eor_ : 5; // WTF::Unicode::Direction
- unsigned line_break_bidi_status_last_strong_ : 5; // WTF::Unicode::Direction
- unsigned line_break_bidi_status_last_ : 5; // WTF::Unicode::Direction
+ unsigned line_break_bidi_status_eor_ : 5; // WTF::unicode::Direction
+ unsigned line_break_bidi_status_last_strong_ : 5; // WTF::unicode::Direction
+ unsigned line_break_bidi_status_last_ : 5; // WTF::unicode::Direction
unsigned is_first_after_page_break_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_iterator.h b/chromium/third_party/blink/renderer/core/layout/line/inline_iterator.h
index 6ab6f1969ea..95732c8993f 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_iterator.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_iterator.h
@@ -125,7 +125,7 @@ class InlineIterator {
UChar PreviousInSameNode() const;
UChar32 CodepointAt(unsigned) const;
UChar32 CurrentCodepoint() const;
- ALWAYS_INLINE WTF::Unicode::CharDirection Direction() const;
+ ALWAYS_INLINE WTF::unicode::CharDirection Direction() const;
private:
LineLayoutItem root_;
@@ -145,15 +145,15 @@ inline bool operator!=(const InlineIterator& it1, const InlineIterator& it2) {
it1.GetLineLayoutItem() != it2.GetLineLayoutItem();
}
-static inline WTF::Unicode::CharDirection EmbedCharFromDirection(
+static inline WTF::unicode::CharDirection EmbedCharFromDirection(
TextDirection dir,
UnicodeBidi unicode_bidi) {
if (unicode_bidi == UnicodeBidi::kEmbed) {
- return dir == TextDirection::kRtl ? WTF::Unicode::kRightToLeftEmbedding
- : WTF::Unicode::kLeftToRightEmbedding;
+ return dir == TextDirection::kRtl ? WTF::unicode::kRightToLeftEmbedding
+ : WTF::unicode::kLeftToRightEmbedding;
}
- return dir == TextDirection::kRtl ? WTF::Unicode::kRightToLeftOverride
- : WTF::Unicode::kLeftToRightOverride;
+ return dir == TextDirection::kRtl ? WTF::unicode::kRightToLeftOverride
+ : WTF::unicode::kLeftToRightOverride;
}
static inline bool TreatAsIsolated(const ComputedStyle& style) {
@@ -208,7 +208,7 @@ static inline void NotifyObserverWillExitObject(Observer* observer,
// Otherwise we pop any embed/override character we added when we opened this
// tag.
if (!observer->InIsolate())
- observer->Embed(WTF::Unicode::kPopDirectionalFormat, kFromStyleOrDOM);
+ observer->Embed(WTF::unicode::kPopDirectionalFormat, kFromStyleOrDOM);
}
static inline bool IsIteratorTarget(LineLayoutItem object) {
@@ -512,16 +512,17 @@ inline UChar32 InlineIterator::CurrentCodepoint() const {
return CodepointAt(pos_);
}
-ALWAYS_INLINE WTF::Unicode::CharDirection InlineIterator::Direction() const {
+ALWAYS_INLINE WTF::unicode::CharDirection InlineIterator::Direction() const {
if (UChar32 c = CurrentCodepoint())
- return WTF::Unicode::Direction(c);
+ return WTF::unicode::Direction(c);
- if (line_layout_item_ && line_layout_item_.IsListMarker())
+ if (line_layout_item_ && line_layout_item_.IsListMarker()) {
return line_layout_item_.StyleRef().IsLeftToRightDirection()
- ? WTF::Unicode::kLeftToRight
- : WTF::Unicode::kRightToLeft;
+ ? WTF::unicode::kLeftToRight
+ : WTF::unicode::kRightToLeft;
+ }
- return WTF::Unicode::kOtherNeutral;
+ return WTF::unicode::kOtherNeutral;
}
template <>
@@ -538,7 +539,7 @@ inline bool InlineBidiResolver::IsEndOfLine(const InlineIterator& end) {
current_.MoveTo(current_.GetLineLayoutItem(), end.Offset(),
current_.NextBreakablePosition());
last_ = current_;
- UpdateStatusLastFromCurrentDirection(WTF::Unicode::kOtherNeutral);
+ UpdateStatusLastFromCurrentDirection(WTF::unicode::kOtherNeutral);
}
return in_end_of_line;
}
@@ -598,7 +599,7 @@ inline BidiRun* InlineBidiResolver::AddTrailingRun(
DCHECK(context);
BidiRun* new_trailing_run = new BidiRun(
context->Override(), context->Level(), start, stop,
- run->line_layout_item_, WTF::Unicode::kOtherNeutral, context->Dir());
+ run->line_layout_item_, WTF::unicode::kOtherNeutral, context->Dir());
if (direction == TextDirection::kLtr)
runs.AddRun(new_trailing_run);
else
@@ -706,7 +707,7 @@ class IsolateTracker {
bool InIsolate() const { return nested_isolate_count_; }
// We don't care if we encounter bidi directional overrides.
- void Embed(WTF::Unicode::CharDirection, BidiEmbeddingSource) {}
+ void Embed(WTF::unicode::CharDirection, BidiEmbeddingSource) {}
void CommitExplicitEmbedding(BidiRunList<BidiRun>&) {}
BidiRunList<BidiRun>& Runs() { return runs_; }
@@ -899,8 +900,8 @@ inline void InlineBidiResolver::AppendRun(BidiRunList<BidiRun>& runs) {
sor_ = eor_;
}
- direction_ = WTF::Unicode::kOtherNeutral;
- status_.eor = WTF::Unicode::kOtherNeutral;
+ direction_ = WTF::unicode::kOtherNeutral;
+ status_.eor = WTF::unicode::kOtherNeutral;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/line/line_width.h b/chromium/third_party/blink/renderer/core/layout/line/line_width.h
index e3c5892163a..6ca5d0752bd 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/line_width.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/line_width.h
@@ -31,7 +31,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LINE_LINE_WIDTH_H_
#include "third_party/blink/renderer/core/layout/api/line_layout_block_flow.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.cc b/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.cc
index f7e51aad918..b574a9bbe79 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.cc
@@ -478,10 +478,10 @@ InlineBox* RootInlineBox::ClosestLeafChildForLogicalLeftPosition(
BidiStatus RootInlineBox::LineBreakBidiStatus() const {
return BidiStatus(
- static_cast<WTF::Unicode::CharDirection>(line_break_bidi_status_eor_),
- static_cast<WTF::Unicode::CharDirection>(
+ static_cast<WTF::unicode::CharDirection>(line_break_bidi_status_eor_),
+ static_cast<WTF::unicode::CharDirection>(
line_break_bidi_status_last_strong_),
- static_cast<WTF::Unicode::CharDirection>(line_break_bidi_status_last_),
+ static_cast<WTF::unicode::CharDirection>(line_break_bidi_status_last_),
line_break_context_);
}
@@ -604,8 +604,8 @@ void RootInlineBox::AscentAndDescentForBox(
.PrimaryFont();
if (primary_font)
used_fonts->push_back(primary_font);
- for (size_t i = 0; i < used_fonts->size(); ++i) {
- const FontMetrics& font_metrics = used_fonts->at(i)->GetFontMetrics();
+ for (const SimpleFontData* font_data : *used_fonts) {
+ const FontMetrics& font_metrics = font_data->GetFontMetrics();
LayoutUnit used_font_ascent(font_metrics.Ascent(BaselineType()));
LayoutUnit used_font_descent(font_metrics.Descent(BaselineType()));
LayoutUnit half_leading(
@@ -808,9 +808,9 @@ void RootInlineBox::CollectLeafBoxesInLogicalOrder(
const InlineBox* RootInlineBox::GetLogicalStartNonPseudoBox() const {
Vector<InlineBox*> leaf_boxes_in_logical_order;
CollectLeafBoxesInLogicalOrder(leaf_boxes_in_logical_order);
- for (size_t i = 0; i < leaf_boxes_in_logical_order.size(); ++i) {
- if (leaf_boxes_in_logical_order[i]->GetLineLayoutItem().NonPseudoNode())
- return leaf_boxes_in_logical_order[i];
+ for (InlineBox* box : leaf_boxes_in_logical_order) {
+ if (box->GetLineLayoutItem().NonPseudoNode())
+ return box;
}
return nullptr;
}
@@ -818,7 +818,7 @@ const InlineBox* RootInlineBox::GetLogicalStartNonPseudoBox() const {
const InlineBox* RootInlineBox::GetLogicalEndNonPseudoBox() const {
Vector<InlineBox*> leaf_boxes_in_logical_order;
CollectLeafBoxesInLogicalOrder(leaf_boxes_in_logical_order);
- for (size_t i = leaf_boxes_in_logical_order.size(); i > 0; --i) {
+ for (wtf_size_t i = leaf_boxes_in_logical_order.size(); i > 0; --i) {
if (leaf_boxes_in_logical_order[i - 1]
->GetLineLayoutItem()
.NonPseudoNode()) {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.cc b/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.cc
index f2c82df2b4a..f3a9e9e2182 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.cc
@@ -57,8 +57,8 @@ void TrailingObjects::UpdateMidpointsForTrailingObjects(
// Now make sure every single trailingPositionedBox following the
// trailingSpaceMidpoint properly stops and starts ignoring spaces.
- size_t current_midpoint = trailing_space_midpoint + 1;
- for (size_t i = 0; i < objects_.size(); ++i) {
+ wtf_size_t current_midpoint = trailing_space_midpoint + 1;
+ for (wtf_size_t i = 0; i < objects_.size(); ++i) {
if (current_midpoint >= line_midpoint_state.NumMidpoints()) {
// We don't have a midpoint for this box yet.
EnsureLineBoxInsideIgnoredSpaces(&line_midpoint_state,
@@ -78,8 +78,8 @@ void TrailingObjects::UpdateMidpointsForTrailingObjects(
unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
InlineIterator end_mid(nullptr, whitespace_, pos);
line_midpoint_state.StartIgnoringSpaces(end_mid);
- for (size_t i = 0; i < objects_.size(); ++i) {
- EnsureLineBoxInsideIgnoredSpaces(&line_midpoint_state, objects_[i]);
+ for (const LineLayoutItem& item : objects_) {
+ EnsureLineBoxInsideIgnoredSpaces(&line_midpoint_state, item);
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/list_marker_text.cc b/chromium/third_party/blink/renderer/core/layout/list_marker_text.cc
index 7e392497907..4d76b7e4490 100644
--- a/chromium/third_party/blink/renderer/core/layout/list_marker_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/list_marker_text.cc
@@ -333,8 +333,14 @@ static String ToCJKIdeographic(int number,
return String(&table[kDigit0], 1);
const bool negative = number < 0;
- if (negative)
- number = -number;
+ if (negative) {
+ // Negating the most negative integer (INT_MIN) doesn't work, since it has
+ // no positive counterpart. Deal with that here, manually.
+ if (UNLIKELY(number == INT_MIN))
+ number = INT_MAX;
+ else
+ number = -number;
+ }
const int kGroupLength =
9; // 4 digits, 3 digit markers, group marker of size 2.
diff --git a/chromium/third_party/blink/renderer/core/layout/logical_values.cc b/chromium/third_party/blink/renderer/core/layout/logical_values.cc
new file mode 100644
index 00000000000..dc275ba19c4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/logical_values.cc
@@ -0,0 +1,48 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/logical_values.h"
+
+namespace blink {
+
+EClear ResolvedClear(EClear value, TextDirection direction) {
+ switch (value) {
+ case EClear::kInlineStart:
+ case EClear::kInlineEnd: {
+ return IsLtr(direction) == (value == EClear::kInlineStart)
+ ? EClear::kLeft
+ : EClear::kRight;
+ }
+ default:
+ return value;
+ }
+}
+
+EFloat ResolvedFloating(EFloat value, TextDirection direction) {
+ switch (value) {
+ case EFloat::kInlineStart:
+ case EFloat::kInlineEnd: {
+ return IsLtr(direction) == (value == EFloat::kInlineStart)
+ ? EFloat::kLeft
+ : EFloat::kRight;
+ }
+ default:
+ return value;
+ }
+}
+
+EResize ResolvedResize(EResize value, WritingMode writing_mode) {
+ switch (value) {
+ case EResize::kBlock:
+ case EResize::kInline: {
+ return IsHorizontalWritingMode(writing_mode) == (value == EResize::kBlock)
+ ? EResize::kVertical
+ : EResize::kHorizontal;
+ }
+ default:
+ return value;
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/logical_values.h b/chromium/third_party/blink/renderer/core/layout/logical_values.h
new file mode 100644
index 00000000000..5d1dee1ab76
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/logical_values.h
@@ -0,0 +1,38 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LOGICAL_VALUES_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LOGICAL_VALUES_H_
+
+#include "third_party/blink/renderer/core/style/computed_style.h"
+
+namespace blink {
+
+// The following functions resolve CSS logical values and return other ones
+// as-is. They can be called with the value to be resolved and the TextDirection
+// or WritingMode that will be used for that resolution. Alternatively, they
+// also accept two ComputedStyle arguments, the first one to retrieve the value,
+// and the second one to get the TextDirection or WritingMode.
+
+EClear ResolvedClear(EClear, TextDirection);
+inline EClear ResolvedClear(const ComputedStyle& style,
+ const ComputedStyle& cb_style) {
+ return ResolvedClear(style.Clear(), cb_style.Direction());
+}
+
+EFloat ResolvedFloating(EFloat, TextDirection);
+inline EFloat ResolvedFloating(const ComputedStyle& style,
+ const ComputedStyle& cb_style) {
+ return ResolvedFloating(style.Floating(), cb_style.Direction());
+}
+
+EResize ResolvedResize(EResize, WritingMode);
+inline EResize ResolvedResize(const ComputedStyle& style,
+ const ComputedStyle& cb_style) {
+ return ResolvedResize(style.Resize(), cb_style.GetWritingMode());
+}
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LOGICAL_VALUES_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/map_coordinates_test.cc b/chromium/third_party/blink/renderer/core/layout/map_coordinates_test.cc
index c6bca021396..a4fad37261e 100644
--- a/chromium/third_party/blink/renderer/core/layout/map_coordinates_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/map_coordinates_test.cc
@@ -552,7 +552,7 @@ TEST_F(MapCoordinatesTest, FixedPosInFixedPosScrollView) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0.0, 50),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50,
GetDocument().View()->LayoutViewport()->ScrollOffsetInt().Height());
@@ -585,7 +585,7 @@ TEST_F(MapCoordinatesTest, FixedPosInAbsolutePosScrollView) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0.0, 50),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50,
GetDocument().View()->LayoutViewport()->ScrollOffsetInt().Height());
@@ -612,7 +612,7 @@ TEST_F(MapCoordinatesTest, FixedPosInTransform) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0.0, 50),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50,
GetDocument().View()->LayoutViewport()->ScrollOffsetInt().Height());
@@ -651,7 +651,7 @@ TEST_F(MapCoordinatesTest, FixedPosInContainPaint) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0.0, 50),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50,
GetDocument().View()->LayoutViewport()->ScrollOffsetInt().Height());
@@ -694,7 +694,7 @@ TEST_F(MapCoordinatesTest, FixedPosInIFrameWhenMainFrameScrolled) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 1000), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = ChildDocument().getElementById("target");
ASSERT_TRUE(target);
@@ -721,11 +721,12 @@ TEST_F(MapCoordinatesTest, IFrameTransformed) {
"<style>body { margin: 0; } #target { width: 200px; "
"height: 8000px}</style><div id=target></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 1000), kProgrammaticScroll);
- ChildDocument().View()->UpdateAllLifecyclePhases();
+ ChildDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
Element* target = ChildDocument().getElementById("target");
ASSERT_TRUE(target);
@@ -758,10 +759,10 @@ TEST_F(MapCoordinatesTest, FixedPosInScrolledIFrameWithTransform) {
<div style='width: 200; height: 8000px'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 1000), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = ChildDocument().getElementById("target");
ASSERT_TRUE(target);
@@ -1633,8 +1634,9 @@ TEST_F(MapCoordinatesTest, LocalToAncestorTransform) {
}
TEST_F(MapCoordinatesTest, LocalToAbsoluteTransformFlattens) {
- GetDocument().GetFrame()->GetSettings()->SetAcceleratedCompositingEnabled(
- true);
+ // This Page is not actually being shown by a compositor, but we act like it
+ // will in order to test behaviour.
+ GetPage().GetSettings().SetAcceleratedCompositingEnabled(true);
SetBodyInnerHTML(R"HTML(
<div style='position: absolute; left: 0; top: 0;'>
<div style='transform: rotateY(45deg);
diff --git a/chromium/third_party/blink/renderer/core/layout/min_max_size.h b/chromium/third_party/blink/renderer/core/layout/min_max_size.h
index b8069c11456..c3fdbde6e4b 100644
--- a/chromium/third_party/blink/renderer/core/layout/min_max_size.h
+++ b/chromium/third_party/blink/renderer/core/layout/min_max_size.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_MIN_MAX_SIZE_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h b/chromium/third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h
index 12f7c64fa4d..72527915c9c 100644
--- a/chromium/third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h
+++ b/chromium/third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h
@@ -231,16 +231,18 @@ class CORE_EXPORT MultiColumnFragmentainerGroupList {
iterator end() { return groups_.end(); }
const_iterator end() const { return groups_.end(); }
- size_t size() const { return groups_.size(); }
- MultiColumnFragmentainerGroup& operator[](size_t i) { return groups_.at(i); }
- const MultiColumnFragmentainerGroup& operator[](size_t i) const {
+ wtf_size_t size() const { return groups_.size(); }
+ MultiColumnFragmentainerGroup& operator[](wtf_size_t i) {
+ return groups_.at(i);
+ }
+ const MultiColumnFragmentainerGroup& operator[](wtf_size_t i) const {
return groups_.at(i);
}
void Append(const MultiColumnFragmentainerGroup& group) {
groups_.push_back(group);
}
- void Shrink(size_t size) { groups_.Shrink(size); }
+ void Shrink(wtf_size_t size) { groups_.Shrink(size); }
private:
LayoutMultiColumnSet& column_set_;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.cc b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.cc
index 54a9c6a86b4..ec634cd1fe4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.cc
@@ -25,7 +25,7 @@ void InsertOpportunity(const NGLayoutOpportunity& opportunity,
// We go backwards through the list as there is a higher probability that a
// new opportunity will be at the end of the list.
- for (size_t j = opportunities->size() - 1; j >= 0; --j) {
+ for (wtf_size_t j = opportunities->size() - 1; j >= 0; --j) {
const NGLayoutOpportunity& other = opportunities->at(j);
if (other.rect.BlockStartOffset() <= opportunity.rect.BlockStartOffset()) {
#if DCHECK_IS_ON()
@@ -47,17 +47,17 @@ void InsertOpportunity(const NGLayoutOpportunity& opportunity,
}
// Returns true if there is at least one edge between block_start and block_end.
-bool HasSolidEdges(const Vector<scoped_refptr<const NGExclusion>, 1>& edges,
- LayoutUnit block_start,
- LayoutUnit block_end) {
+bool HasSolidEdges(
+ const Vector<NGExclusionSpaceInternal::NGShelfEdge, 1>& edges,
+ LayoutUnit block_start,
+ LayoutUnit block_end) {
// If there aren't any adjacent exclusions, we must be the initial shelf.
// This always has "solid" edges on either side.
if (edges.IsEmpty())
return true;
for (const auto& edge : edges) {
- if (edge->rect.BlockEndOffset() > block_start &&
- edge->rect.BlockStartOffset() < block_end)
+ if (edge.block_end > block_start && edge.block_start < block_end)
return true;
}
@@ -68,12 +68,13 @@ bool HasSolidEdges(const Vector<scoped_refptr<const NGExclusion>, 1>& edges,
// (block_offset, LayoutUnit::Max())
// to the given out_edges vector.
// edges will be invalid after this call.
-void CollectSolidEdges(Vector<scoped_refptr<const NGExclusion>, 1>* edges,
- LayoutUnit block_offset,
- Vector<scoped_refptr<const NGExclusion>, 1>* out_edges) {
+void CollectSolidEdges(
+ Vector<NGExclusionSpaceInternal::NGShelfEdge, 1>* edges,
+ LayoutUnit block_offset,
+ Vector<NGExclusionSpaceInternal::NGShelfEdge, 1>* out_edges) {
*out_edges = std::move(*edges);
for (auto* it = out_edges->begin(); it != out_edges->end();) {
- if ((*it)->rect.BlockEndOffset() <= block_offset) {
+ if ((*it).block_end <= block_offset) {
out_edges->erase(it);
} else {
++it;
@@ -136,8 +137,11 @@ NGLayoutOpportunity CreateLayoutOpportunity(const NGLayoutOpportunity& other,
std::min(other.rect.LineEndOffset(), offset.line_offset + inline_size),
other.rect.BlockEndOffset());
- return NGLayoutOpportunity(NGBfcRect(start_offset, end_offset),
- other.shape_exclusions);
+ return NGLayoutOpportunity(
+ NGBfcRect(start_offset, end_offset),
+ other.shape_exclusions
+ ? base::AdoptRef(new NGShapeExclusions(*other.shape_exclusions))
+ : nullptr);
}
// Creates a new layout opportunity. The given shelf *must* intersect with the
@@ -171,6 +175,7 @@ NGExclusionSpaceInternal::NGExclusionSpaceInternal()
: exclusions_(RefVector<scoped_refptr<const NGExclusion>>::Create()),
num_exclusions_(0),
both_clear_offset_(LayoutUnit::Min()),
+ track_shape_exclusions_(false),
derived_geometry_(nullptr) {}
NGExclusionSpaceInternal::NGExclusionSpaceInternal(
@@ -178,34 +183,39 @@ NGExclusionSpaceInternal::NGExclusionSpaceInternal(
: exclusions_(other.exclusions_),
num_exclusions_(other.num_exclusions_),
both_clear_offset_(other.both_clear_offset_),
+ track_shape_exclusions_(other.track_shape_exclusions_),
derived_geometry_(std::move(other.derived_geometry_)) {
// This copy-constructor does fun things. It moves the derived_geometry_ to
// the newly created exclusion space where it'll more-likely be used.
other.derived_geometry_ = nullptr;
}
-NGExclusionSpaceInternal::NGExclusionSpaceInternal(NGExclusionSpaceInternal&&) =
- default;
+NGExclusionSpaceInternal::NGExclusionSpaceInternal(
+ NGExclusionSpaceInternal&&) noexcept = default;
NGExclusionSpaceInternal& NGExclusionSpaceInternal::operator=(
const NGExclusionSpaceInternal& other) {
exclusions_ = other.exclusions_;
num_exclusions_ = other.num_exclusions_;
both_clear_offset_ = other.both_clear_offset_;
+ track_shape_exclusions_ = other.track_shape_exclusions_;
derived_geometry_ = std::move(other.derived_geometry_);
other.derived_geometry_ = nullptr;
return *this;
}
NGExclusionSpaceInternal& NGExclusionSpaceInternal::operator=(
- NGExclusionSpaceInternal&&) = default;
+ NGExclusionSpaceInternal&&) noexcept = default;
-NGExclusionSpaceInternal::DerivedGeometry::DerivedGeometry()
- : last_float_block_start_(LayoutUnit::Min()),
+NGExclusionSpaceInternal::DerivedGeometry::DerivedGeometry(
+ bool track_shape_exclusions)
+ : track_shape_exclusions_(track_shape_exclusions),
+ last_float_block_start_(LayoutUnit::Min()),
left_float_clear_offset_(LayoutUnit::Min()),
right_float_clear_offset_(LayoutUnit::Min()) {
// The exclusion space must always have at least one shelf, at -Infinity.
- shelves_.emplace_back(/* block_offset */ LayoutUnit::Min());
+ shelves_.emplace_back(/* block_offset */ LayoutUnit::Min(),
+ track_shape_exclusions_);
}
void NGExclusionSpaceInternal::Add(scoped_refptr<const NGExclusion> exclusion) {
@@ -220,7 +230,14 @@ void NGExclusionSpaceInternal::Add(scoped_refptr<const NGExclusion> exclusion) {
exclusions_->GetVector().begin() + num_exclusions_);
std::swap(exclusions_, exclusions);
- // The derived_geometry_ is now invalid.
+ // The derived_geometry_ member is now invalid.
+ derived_geometry_ = nullptr;
+ }
+
+ // If this is the first exclusion with shape_data, the derived_geometry_
+ // member now needs to perform additional bookkeeping, and is invalid.
+ if (!track_shape_exclusions_ && exclusion->shape_data) {
+ track_shape_exclusions_ = true;
derived_geometry_ = nullptr;
}
@@ -263,7 +280,7 @@ void NGExclusionSpaceInternal::DerivedGeometry::Add(
//
// NOTE: This could potentially be done lazily when we query the exclusion
// space for a layout opportunity.
- for (size_t i = 0; i < shelves_.size(); ++i) {
+ for (wtf_size_t i = 0; i < shelves_.size(); ++i) {
// We modify the current shelf in-place. However we need to keep a copy of
// the shelf if we need to insert a new shelf later in the loop.
base::Optional<NGShelf> shelf_copy;
@@ -403,9 +420,12 @@ void NGExclusionSpaceInternal::DerivedGeometry::Add(
if (exclusion.rect.LineEndOffset() > shelf.line_left)
shelf.line_left_edges.clear();
shelf.line_left = exclusion.rect.LineEndOffset();
- shelf.line_left_edges.emplace_back(&exclusion);
+ shelf.line_left_edges.emplace_back(
+ exclusion.rect.BlockStartOffset(),
+ exclusion.rect.BlockEndOffset());
}
- shelf.shape_exclusions->line_left_shapes.emplace_back(&exclusion);
+ if (shelf.shape_exclusions)
+ shelf.shape_exclusions->line_left_shapes.emplace_back(&exclusion);
} else {
DCHECK_EQ(exclusion.type, EFloat::kRight);
if (exclusion.rect.LineStartOffset() <= shelf.line_right) {
@@ -413,9 +433,12 @@ void NGExclusionSpaceInternal::DerivedGeometry::Add(
if (exclusion.rect.LineStartOffset() < shelf.line_right)
shelf.line_right_edges.clear();
shelf.line_right = exclusion.rect.LineStartOffset();
- shelf.line_right_edges.emplace_back(&exclusion);
+ shelf.line_right_edges.emplace_back(
+ exclusion.rect.BlockStartOffset(),
+ exclusion.rect.BlockEndOffset());
}
- shelf.shape_exclusions->line_right_shapes.emplace_back(&exclusion);
+ if (shelf.shape_exclusions)
+ shelf.shape_exclusions->line_right_shapes.emplace_back(&exclusion);
}
// We collect all exclusions in shape_exclusions (even if they don't
@@ -463,7 +486,8 @@ void NGExclusionSpaceInternal::DerivedGeometry::Add(
// We only want to add the shelf if it's at a different block offset.
if (exclusion_end_offset != shelf_copy->block_offset) {
- NGShelf new_shelf(/* block_offset */ exclusion_end_offset);
+ NGShelf new_shelf(/* block_offset */ exclusion_end_offset,
+ track_shape_exclusions_);
// shelf_copy->line_{left,right}_edges will not valid after these calls.
CollectSolidEdges(&shelf_copy->line_left_edges, new_shelf.block_offset,
@@ -508,25 +532,28 @@ NGExclusionSpaceInternal::DerivedGeometry::FindLayoutOpportunity(
const LayoutUnit available_inline_size,
const NGLogicalSize& minimum_size) const {
// TODO(ikilpatrick): Determine what to do for a -ve available_inline_size.
- // TODO(ikilpatrick): Change this so that it iterates over the
- // shelves/opportunities instead for querying for all of them.
- LayoutOpportunityVector opportunities =
- AllLayoutOpportunities(offset, available_inline_size);
-
- for (const auto& opportunity : opportunities) {
- // Determine if this opportunity will fit the given size.
- //
- // NOTE: There are cases where the available_inline_size may be smaller
- // than the minimum_size.inline_size. In such cases if the opportunity is
- // the same as the available_inline_size, it pretends that it "fits".
- if ((opportunity.rect.InlineSize() >= minimum_size.inline_size ||
- opportunity.rect.InlineSize() == available_inline_size) &&
- opportunity.rect.BlockSize() >= minimum_size.block_size)
- return opportunity;
- }
- NOTREACHED();
- return NGLayoutOpportunity();
+ NGLayoutOpportunity return_opportunity;
+ IterateAllLayoutOpportunities(
+ offset, available_inline_size,
+ [&return_opportunity, &minimum_size,
+ &available_inline_size](const NGLayoutOpportunity opportunity) -> bool {
+ // Determine if this opportunity will fit the given size.
+ //
+ // NOTE: There are cases where the available_inline_size may be smaller
+ // than the minimum_size.inline_size. In such cases if the opportunity
+ // is the same as the available_inline_size, it pretends that it "fits".
+ if ((opportunity.rect.InlineSize() >= minimum_size.inline_size ||
+ opportunity.rect.InlineSize() == available_inline_size) &&
+ opportunity.rect.BlockSize() >= minimum_size.block_size) {
+ return_opportunity = std::move(opportunity);
+ return true;
+ }
+
+ return false;
+ });
+
+ return return_opportunity;
}
LayoutOpportunityVector
@@ -535,6 +562,21 @@ NGExclusionSpaceInternal::DerivedGeometry::AllLayoutOpportunities(
const LayoutUnit available_inline_size) const {
LayoutOpportunityVector opportunities;
+ IterateAllLayoutOpportunities(
+ offset, available_inline_size,
+ [&opportunities](const NGLayoutOpportunity opportunity) -> bool {
+ opportunities.push_back(std::move(opportunity));
+ return false;
+ });
+
+ return opportunities;
+}
+
+template <typename LambdaFunc>
+void NGExclusionSpaceInternal::DerivedGeometry::IterateAllLayoutOpportunities(
+ const NGBfcOffset& offset,
+ const LayoutUnit available_inline_size,
+ const LambdaFunc& lambda) const {
auto* shelves_it = shelves_.begin();
auto* opps_it = opportunities_.begin();
@@ -563,8 +605,10 @@ NGExclusionSpaceInternal::DerivedGeometry::AllLayoutOpportunities(
// We always prefer the closed-off opportunity, instead of the shelf
// opportunity if they exist at the some offset.
if (opportunity.rect.BlockStartOffset() <= shelf.block_offset) {
- opportunities.push_back(CreateLayoutOpportunity(opportunity, offset,
- available_inline_size));
+ if (lambda(CreateLayoutOpportunity(opportunity, offset,
+ available_inline_size)))
+ return;
+
++opps_it;
continue;
}
@@ -577,13 +621,11 @@ NGExclusionSpaceInternal::DerivedGeometry::AllLayoutOpportunities(
HasSolidEdges(shelf.line_right_edges, offset.block_offset,
LayoutUnit::Max());
if (has_solid_edges) {
- opportunities.push_back(
- CreateLayoutOpportunity(shelf, offset, available_inline_size));
+ if (lambda(CreateLayoutOpportunity(shelf, offset, available_inline_size)))
+ return;
}
++shelves_it;
}
-
- return opportunities;
}
LayoutUnit NGExclusionSpaceInternal::DerivedGeometry::ClearanceOffset(
@@ -608,9 +650,10 @@ const NGExclusionSpaceInternal::DerivedGeometry&
NGExclusionSpaceInternal::GetDerivedGeometry() const {
// Re-build the geometry if it isn't present.
if (!derived_geometry_) {
- derived_geometry_ = std::make_unique<DerivedGeometry>();
+ derived_geometry_ =
+ std::make_unique<DerivedGeometry>(track_shape_exclusions_);
DCHECK_LE(num_exclusions_, exclusions_->size());
- for (size_t i = 0; i < num_exclusions_; ++i)
+ for (wtf_size_t i = 0; i < num_exclusions_; ++i)
derived_geometry_->Add(*exclusions_->GetVector()[i]);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h
index 6ea898083cb..e8d970d7bdd 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_vector.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -31,7 +31,7 @@ class CORE_EXPORT NGExclusionSpaceInternal {
NGExclusionSpaceInternal(const NGExclusionSpaceInternal&);
NGExclusionSpaceInternal(NGExclusionSpaceInternal&&) noexcept;
NGExclusionSpaceInternal& operator=(const NGExclusionSpaceInternal&);
- NGExclusionSpaceInternal& operator=(NGExclusionSpaceInternal&&);
+ NGExclusionSpaceInternal& operator=(NGExclusionSpaceInternal&&) noexcept;
~NGExclusionSpaceInternal() {}
void Add(scoped_refptr<const NGExclusion> exclusion);
@@ -88,6 +88,15 @@ class CORE_EXPORT NGExclusionSpaceInternal {
return !(*this == other);
}
+ // This struct represents the side of a float against the "edge" of a shelf.
+ struct NGShelfEdge {
+ NGShelfEdge(LayoutUnit block_start, LayoutUnit block_end)
+ : block_start(block_start), block_end(block_end) {}
+
+ LayoutUnit block_start;
+ LayoutUnit block_end;
+ };
+
// The shelf is an internal data-structure representing the bottom of a
// float. A shelf has a inline-size which is defined by the line_left and
// line_right members. E.g.
@@ -120,23 +129,26 @@ class CORE_EXPORT NGExclusionSpaceInternal {
// - The opportunity also holds onto a list of these edges to support
// css-shapes.
struct NGShelf {
- explicit NGShelf(LayoutUnit block_offset)
+ NGShelf(LayoutUnit block_offset, bool track_shape_exclusions)
: block_offset(block_offset),
line_left(LayoutUnit::Min()),
line_right(LayoutUnit::Max()),
- shape_exclusions(base::AdoptRef(new NGShapeExclusions)),
+ shape_exclusions(track_shape_exclusions
+ ? base::AdoptRef(new NGShapeExclusions)
+ : nullptr),
has_shape_exclusions(false) {}
- // The copy constructor explicitly copies the shape_exclusions member,
- // instead of just incrementing the ref.
+ // The copy constructor explicitly copies the shape_exclusions member.
NGShelf(const NGShelf& other)
: block_offset(other.block_offset),
line_left(other.line_left),
line_right(other.line_right),
line_left_edges(other.line_left_edges),
line_right_edges(other.line_right_edges),
- shape_exclusions(
- base::AdoptRef(new NGShapeExclusions(*other.shape_exclusions))),
+ shape_exclusions(other.shape_exclusions
+ ? base::AdoptRef(new NGShapeExclusions(
+ *other.shape_exclusions))
+ : nullptr),
has_shape_exclusions(other.has_shape_exclusions) {}
NGShelf(NGShelf&& other) noexcept = default;
@@ -146,8 +158,8 @@ class CORE_EXPORT NGExclusionSpaceInternal {
LayoutUnit line_left;
LayoutUnit line_right;
- Vector<scoped_refptr<const NGExclusion>, 1> line_left_edges;
- Vector<scoped_refptr<const NGExclusion>, 1> line_right_edges;
+ Vector<NGShelfEdge, 1> line_left_edges;
+ Vector<NGShelfEdge, 1> line_right_edges;
// shape_exclusions contains all the floats which sit below this shelf. The
// has_shape_exclusions member will be true if shape_exclusions contains an
@@ -168,9 +180,15 @@ class CORE_EXPORT NGExclusionSpaceInternal {
// num_exclusions_ is how many exclusions *this* instance of an exclusion
// space has, which may differ to the number of exclusions in the Vector.
scoped_refptr<RefVector<scoped_refptr<const NGExclusion>>> exclusions_;
- size_t num_exclusions_;
+ wtf_size_t num_exclusions_;
LayoutUnit both_clear_offset_;
+ // In order to reduce the amount of copies related to bookkeeping shape data,
+ // we initially ignore exclusions with shape data. When we first see an
+ // exclusion with shape data, we set this flag, and rebuild the
+ // DerivedGeometry data-structure, to perform the additional bookkeeping.
+ bool track_shape_exclusions_;
+
// The derived geometry struct, is the data-structure which handles all of the
// queries on the exclusion space. It can always be rebuilt from exclusions_
// and num_exclusions_. This is mutable as it is passed down a chain of
@@ -189,11 +207,11 @@ class CORE_EXPORT NGExclusionSpaceInternal {
// exclusion space in the copy-chain is used for answering queries. Only when
// we trigger a (rare) re-layout case will we need to rebuild the
// derived_geometry_ data-structure.
- struct DerivedGeometry {
+ struct CORE_EXPORT DerivedGeometry {
USING_FAST_MALLOC(DerivedGeometry);
public:
- DerivedGeometry();
+ explicit DerivedGeometry(bool track_shape_exclusions);
DerivedGeometry(DerivedGeometry&& o) noexcept = default;
void Add(const NGExclusion& exclusion);
@@ -207,6 +225,11 @@ class CORE_EXPORT NGExclusionSpaceInternal {
const NGBfcOffset& offset,
const LayoutUnit available_inline_size) const;
+ template <typename LambdaFunc>
+ void IterateAllLayoutOpportunities(const NGBfcOffset& offset,
+ const LayoutUnit available_inline_size,
+ const LambdaFunc&) const;
+
LayoutUnit ClearanceOffset(EClear clear_type) const;
LayoutUnit LastFloatBlockStart() const { return last_float_block_start_; }
@@ -245,6 +268,8 @@ class CORE_EXPORT NGExclusionSpaceInternal {
Vector<NGShelf, 4> shelves_;
Vector<NGLayoutOpportunity, 4> opportunities_;
+ bool track_shape_exclusions_;
+
// This member is used for implementing the "top edge alignment rule" for
// floats. Floats can be positioned at negative offsets, hence is
// initialized the minimum value.
@@ -313,6 +338,7 @@ class CORE_EXPORT NGExclusionSpace {
offset, available_inline_size, minimum_size);
}
+ // If possible prefer FindLayoutOpportunity over this function.
LayoutOpportunityVector AllLayoutOpportunities(
const NGBfcOffset& offset,
const LayoutUnit available_inline_size) const {
@@ -362,4 +388,7 @@ class CORE_EXPORT NGExclusionSpace {
} // namespace blink
+WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(
+ blink::NGExclusionSpaceInternal::NGShelfEdge);
+
#endif // NGExclusionSpace_h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_line_layout_opportunity.h b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_line_layout_opportunity.h
index cf853395678..830ce4998ed 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_line_layout_opportunity.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_line_layout_opportunity.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_EXCLUSIONS_NG_LINE_LAYOUT_OPPORTUNITY_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_shape_exclusions.h b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_shape_exclusions.h
index 667d37fa45c..2b91cf5caf4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_shape_exclusions.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_shape_exclusions.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h
index 1bfa71a5f3a..f20e1123072 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h
@@ -6,7 +6,7 @@
#define NGBfcOffset_h
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h
index a7855ad23f1..397a5811258 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_rect.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h
index 038ec7580f0..4a128618a2a 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h
index 0932ddec30b..00d51ca8204 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h
@@ -6,7 +6,7 @@
#define NGLogicalOffset_h
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.cc
index 29feb3c4d89..ed4c4fac767 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.cc
@@ -8,17 +8,6 @@
namespace blink {
-NGPhysicalSize NGLogicalSize::ConvertToPhysical(WritingMode mode) const {
- return mode == WritingMode::kHorizontalTb
- ? NGPhysicalSize(inline_size, block_size)
- : NGPhysicalSize(block_size, inline_size);
-}
-
-bool NGLogicalSize::operator==(const NGLogicalSize& other) const {
- return std::tie(other.inline_size, other.block_size) ==
- std::tie(inline_size, block_size);
-}
-
std::ostream& operator<<(std::ostream& stream, const NGLogicalSize& value) {
return stream << value.inline_size << "x" << value.block_size;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h
index 773d33c9589..344170e609e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h
@@ -8,13 +8,12 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
struct NGLogicalOffset;
-struct NGPhysicalSize;
#define NGSizeIndefinite LayoutUnit(-1)
// NGLogicalSize is the size of rect (typically a fragment) in the logical
@@ -24,11 +23,18 @@ struct CORE_EXPORT NGLogicalSize {
NGLogicalSize(LayoutUnit inline_size, LayoutUnit block_size)
: inline_size(inline_size), block_size(block_size) {}
+ // Use ToNGPhysicalSize to convert to a physical size.
+
LayoutUnit inline_size;
LayoutUnit block_size;
- NGPhysicalSize ConvertToPhysical(WritingMode mode) const;
- bool operator==(const NGLogicalSize& other) const;
+ bool operator==(const NGLogicalSize& other) const {
+ return std::tie(other.inline_size, other.block_size) ==
+ std::tie(inline_size, block_size);
+ }
+ bool operator!=(const NGLogicalSize& other) const {
+ return !(*this == other);
+ }
bool IsEmpty() const {
return inline_size == LayoutUnit() || block_size == LayoutUnit();
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.cc
index dac9dbeeccc..08086d001ec 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.cc
@@ -8,18 +8,6 @@
namespace blink {
-LayoutUnit NGMarginStrut::Sum() const {
- if (discard_margins)
- return LayoutUnit();
- return std::max(quirky_positive_margin, positive_margin) + negative_margin;
-}
-
-LayoutUnit NGMarginStrut::QuirkyContainerSum() const {
- if (discard_margins)
- return LayoutUnit();
- return positive_margin + negative_margin;
-}
-
void NGMarginStrut::Append(const LayoutUnit& value, bool is_quirky) {
if (is_quirky_container_start && is_quirky)
return;
@@ -48,6 +36,7 @@ bool NGMarginStrut::operator==(const NGMarginStrut& other) const {
return positive_margin == other.positive_margin &&
negative_margin == other.negative_margin &&
quirky_positive_margin == other.quirky_positive_margin &&
+ discard_margins == other.discard_margins &&
is_quirky_container_start == other.is_quirky_container_start;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h
index e46e7a73bf1..d5337978b10 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h
@@ -6,7 +6,7 @@
#define NGMarginStrut_h
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
@@ -32,11 +32,19 @@ struct CORE_EXPORT NGMarginStrut {
void Append(const LayoutUnit& value, bool is_quirky);
// Sum up negative and positive margins of this strut.
- LayoutUnit Sum() const;
+ LayoutUnit Sum() const {
+ if (discard_margins)
+ return LayoutUnit();
+ return std::max(quirky_positive_margin, positive_margin) + negative_margin;
+ }
// Sum up non-quirky margins of this strut, used by quirky
// containers to sum up the last margin.
- LayoutUnit QuirkyContainerSum() const;
+ LayoutUnit QuirkyContainerSum() const {
+ if (discard_margins)
+ return LayoutUnit();
+ return positive_margin + negative_margin;
+ }
// Whether there have been no margins appended to this margin strut.
bool IsEmpty() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_location.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_location.h
index 3ac884febc5..3a3ba0d9dea 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_location.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_location.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.cc
index b335ff8a4e3..9dc7146f5f5 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.cc
@@ -48,47 +48,6 @@ NGLogicalOffset NGPhysicalOffset::ConvertToLogical(
}
}
-NGPhysicalOffset NGPhysicalOffset::operator+(
- const NGPhysicalOffset& other) const {
- return NGPhysicalOffset{this->left + other.left, this->top + other.top};
-}
-
-NGPhysicalOffset& NGPhysicalOffset::operator+=(const NGPhysicalOffset& other) {
- *this = *this + other;
- return *this;
-}
-
-NGPhysicalOffset NGPhysicalOffset::operator-(
- const NGPhysicalOffset& other) const {
- return NGPhysicalOffset{this->left - other.left, this->top - other.top};
-}
-
-NGPhysicalOffset& NGPhysicalOffset::operator-=(const NGPhysicalOffset& other) {
- *this = *this - other;
- return *this;
-}
-
-bool NGPhysicalOffset::operator==(const NGPhysicalOffset& other) const {
- return other.left == left && other.top == top;
-}
-
-NGPhysicalOffset::NGPhysicalOffset(const LayoutPoint& point) {
- left = point.X();
- top = point.Y();
-}
-NGPhysicalOffset::NGPhysicalOffset(const LayoutSize& size) {
- left = size.Width();
- top = size.Height();
-}
-
-LayoutPoint NGPhysicalOffset::ToLayoutPoint() const {
- return {left, top};
-}
-
-LayoutSize NGPhysicalOffset::ToLayoutSize() const {
- return {left, top};
-}
-
String NGPhysicalOffset::ToString() const {
return String::Format("%d,%d", left.ToInt(), top.ToInt());
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h
index 9bb9c3aa91a..4295353bb79 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h
@@ -6,7 +6,9 @@
#define NGPhysicalOffset_h
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_point.h"
+#include "third_party/blink/renderer/platform/geometry/layout_size.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
@@ -35,23 +37,41 @@ struct CORE_EXPORT NGPhysicalOffset {
NGPhysicalSize outer_size,
NGPhysicalSize inner_size) const;
- NGPhysicalOffset operator+(const NGPhysicalOffset& other) const;
- NGPhysicalOffset& operator+=(const NGPhysicalOffset& other);
-
- NGPhysicalOffset operator-(const NGPhysicalOffset& other) const;
- NGPhysicalOffset& operator-=(const NGPhysicalOffset& other);
-
- bool operator==(const NGPhysicalOffset& other) const;
+ NGPhysicalOffset operator+(const NGPhysicalOffset& other) const {
+ return NGPhysicalOffset{this->left + other.left, this->top + other.top};
+ }
+ NGPhysicalOffset& operator+=(const NGPhysicalOffset& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ NGPhysicalOffset operator-(const NGPhysicalOffset& other) const {
+ return NGPhysicalOffset{this->left - other.left, this->top - other.top};
+ }
+ NGPhysicalOffset& operator-=(const NGPhysicalOffset& other) {
+ *this = *this - other;
+ return *this;
+ }
+
+ bool operator==(const NGPhysicalOffset& other) const {
+ return other.left == left && other.top == top;
+ }
// Conversions from/to existing code. New code prefers type safety for
// logical/physical distinctions.
- explicit NGPhysicalOffset(const LayoutPoint& point);
- explicit NGPhysicalOffset(const LayoutSize& size);
+ explicit NGPhysicalOffset(const LayoutPoint& point) {
+ left = point.X();
+ top = point.Y();
+ }
+ explicit NGPhysicalOffset(const LayoutSize& size) {
+ left = size.Width();
+ top = size.Height();
+ }
// Conversions from/to existing code. New code prefers type safety for
// logical/physical distinctions.
- LayoutPoint ToLayoutPoint() const;
- LayoutSize ToLayoutSize() const;
+ LayoutPoint ToLayoutPoint() const { return {left, top}; }
+ LayoutSize ToLayoutSize() const { return {left, top}; }
String ToString() const;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.cc
index 1c7546adee7..d4198ae7092 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.cc
@@ -15,6 +15,11 @@ bool NGPhysicalOffsetRect::operator==(const NGPhysicalOffsetRect& other) const {
return other.offset == offset && other.size == size;
}
+bool NGPhysicalOffsetRect::Contains(const NGPhysicalOffsetRect& other) const {
+ return offset.left <= other.offset.left && offset.top <= other.offset.top &&
+ Right() >= other.Right() && Bottom() >= other.Bottom();
+}
+
NGPhysicalOffsetRect NGPhysicalOffsetRect::operator+(
const NGPhysicalOffset& offset) const {
return {this->offset + offset, size};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h
index b894db5c435..82754b6bfce 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
@@ -34,6 +34,8 @@ struct CORE_EXPORT NGPhysicalOffsetRect {
bool operator==(const NGPhysicalOffsetRect& other) const;
+ bool Contains(const NGPhysicalOffsetRect& other) const;
+
NGPhysicalOffsetRect operator+(const NGPhysicalOffset&) const;
void Unite(const NGPhysicalOffsetRect&);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_rect.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_rect.h
index 3bd44db77a4..179f98c1c45 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_rect.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_rect.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_location.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.cc
index 1dcc8553e4c..e8661406658 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.cc
@@ -4,25 +4,10 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h"
-#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
-#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
-bool NGPhysicalSize::operator==(const NGPhysicalSize& other) const {
- return std::tie(other.width, other.height) == std::tie(width, height);
-}
-
-NGLogicalSize NGPhysicalSize::ConvertToLogical(WritingMode mode) const {
- return mode == WritingMode::kHorizontalTb ? NGLogicalSize(width, height)
- : NGLogicalSize(height, width);
-}
-
-LayoutSize NGPhysicalSize::ToLayoutSize() const {
- return {width, height};
-}
-
String NGPhysicalSize::ToString() const {
return String::Format("%dx%d", width.ToInt(), height.ToInt());
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h
index 4ae9473aecc..cbeb617810c 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h
@@ -6,7 +6,9 @@
#define NGPhysicalSize_h
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
+#include "third_party/blink/renderer/platform/geometry/layout_size.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
@@ -24,9 +26,17 @@ struct CORE_EXPORT NGPhysicalSize {
LayoutUnit width;
LayoutUnit height;
- NGLogicalSize ConvertToLogical(WritingMode mode) const;
+ NGLogicalSize ConvertToLogical(WritingMode mode) const {
+ return mode == WritingMode::kHorizontalTb ? NGLogicalSize(width, height)
+ : NGLogicalSize(height, width);
+ }
- bool operator==(const NGPhysicalSize& other) const;
+ bool operator==(const NGPhysicalSize& other) const {
+ return std::tie(other.width, other.height) == std::tie(width, height);
+ }
+ bool operator!=(const NGPhysicalSize& other) const {
+ return !(*this == other);
+ }
bool IsEmpty() const {
return width == LayoutUnit() || height == LayoutUnit();
@@ -37,13 +47,20 @@ struct CORE_EXPORT NGPhysicalSize {
// Conversions from/to existing code. New code prefers type safety for
// logical/physical distinctions.
- LayoutSize ToLayoutSize() const;
+ LayoutSize ToLayoutSize() const { return {width, height}; }
String ToString() const;
};
CORE_EXPORT std::ostream& operator<<(std::ostream&, const NGPhysicalSize&);
+inline NGPhysicalSize ToNGPhysicalSize(const NGLogicalSize& other,
+ WritingMode mode) {
+ return mode == WritingMode::kHorizontalTb
+ ? NGPhysicalSize(other.inline_size, other.block_size)
+ : NGPhysicalSize(other.block_size, other.inline_size);
+}
+
} // namespace blink
#endif // NGPhysicalSize_h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h
index 5db6c3fe515..7bd2d6cfd2b 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/README.md b/chromium/third_party/blink/renderer/core/layout/ng/inline/README.md
index 87d62fbb0b3..715f1d0e84e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/README.md
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/README.md
@@ -256,7 +256,7 @@ Computing baselines in LayoutNG goes the following process.
Algorithms are responsible
for checking [NGConstraintSpace]`::BaselineRequests()`,
computing requested baselines, and
-calling [NGFragmentBuilder]`::AddBaseline()`
+calling [NGBoxFragmentBuilder]`::AddBaseline()`
to add them to [NGPhysicalBoxFragment].
[NGBaselineRequest] consists of [NGBaselineAlgorithmType] and [FontBaseline].
@@ -314,9 +314,9 @@ In a bird's‐eye view, it consists of two parts:
[NGBidiParagraph]: ng_bidi_paragraph.h
[NGBlockNode]: ../ng_block_node.h
[NGBoxFragment]: ../ng_box_fragment.h
+[NGBoxFragmentBuilder]: ../ng_box_fragment_builder.h
[NGConstraintSpace]: ../ng_constraint_space_builder.h
[NGConstraintSpaceBuilder]: ../ng_constraint_space_builder.h
-[NGFragmentBuilder]: ../ng_fragment_builder.h
[NGInlineBoxState]: ng_inline_box_state.h
[NGInlineItem]: ng_inline_item.h
[NGInlineItemResult]: ng_inline_item_result.h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h
index 5a456f2d8cf..d922dbf5684 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h
@@ -6,18 +6,13 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_H_
#include "third_party/blink/renderer/core/layout/layout_text.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h"
namespace blink {
-class NGInlineItem;
-
// This overrides the default LayoutText to reference LayoutNGInlineItems
// instead of InlineTextBoxes.
//
-// ***** INLINE ITEMS OWNERSHIP *****
-// NGInlineItems in items_ are not owned by LayoutText but are pointers into the
-// LayoutNGBlockFlow's items_. Should not be accessed outside of layout.
class CORE_EXPORT LayoutNGText : public LayoutText {
public:
LayoutNGText(Node* node, scoped_refptr<StringImpl> text)
@@ -28,26 +23,6 @@ class CORE_EXPORT LayoutNGText : public LayoutText {
}
bool IsLayoutNGObject() const override { return true; }
- bool HasValidLayout() const { return valid_ng_items_; }
- const Vector<NGInlineItem*>& InlineItems() const {
- DCHECK(valid_ng_items_);
- return inline_items_;
- }
-
- // Inline items depends on context. It needs to be invalidated not only when
- // it was inserted/changed but also it was moved.
- void InvalidateInlineItems() { valid_ng_items_ = false; }
-
- void ClearInlineItems() {
- inline_items_.clear();
- valid_ng_items_ = false;
- }
-
- void AddInlineItem(NGInlineItem* item) {
- inline_items_.push_back(item);
- valid_ng_items_ = true;
- }
-
protected:
void InsertedIntoTree() override {
valid_ng_items_ = false;
@@ -55,7 +30,10 @@ class CORE_EXPORT LayoutNGText : public LayoutText {
}
private:
- Vector<NGInlineItem*> inline_items_;
+ const NGInlineItems* GetNGInlineItems() const final { return &inline_items_; }
+ NGInlineItems* GetNGInlineItems() final { return &inline_items_; }
+
+ NGInlineItems inline_items_;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutNGText, IsLayoutNGText());
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_fragment.h
new file mode 100644
index 00000000000..130a7b4c8ea
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_fragment.h
@@ -0,0 +1,40 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_FRAGMENT_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_FRAGMENT_H_
+
+#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h"
+
+namespace blink {
+
+// This overrides the default LayoutText to reference LayoutNGInlineItems
+// instead of InlineTextBoxes.
+//
+class CORE_EXPORT LayoutNGTextFragment final : public LayoutTextFragment {
+ public:
+ LayoutNGTextFragment(Node* node,
+ StringImpl* text,
+ int start_offset,
+ int length)
+ : LayoutTextFragment(node, text, start_offset, length) {}
+
+ bool IsLayoutNGObject() const final { return true; }
+
+ private:
+ const NGInlineItems* GetNGInlineItems() const final { return &inline_items_; }
+ NGInlineItems* GetNGInlineItems() final { return &inline_items_; }
+
+ void InsertedIntoTree() final {
+ valid_ng_items_ = false;
+ LayoutText::InsertedIntoTree();
+ }
+
+ NGInlineItems inline_items_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_LAYOUT_NG_TEXT_FRAGMENT_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc
index 236022d3b6b..a416f652496 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h"
#include "third_party/blink/renderer/platform/fonts/character_range.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_buffer.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
@@ -146,9 +147,12 @@ void NGAbstractInlineTextBox::CharacterWidths(Vector<float>& widths) const {
widths.resize(Len());
return;
}
- const ShapeResult& shape_result = *PhysicalTextFragment().TextShapeResult();
+ // TODO(layout-dev): Add support for IndividualCharacterRanges to
+ // ShapeResultView to avoid the copy below.
+ auto shape_result =
+ PhysicalTextFragment().TextShapeResult()->CreateShapeResult();
Vector<CharacterRange> ranges;
- shape_result.IndividualCharacterRanges(&ranges);
+ shape_result->IndividualCharacterRanges(&ranges);
widths.ReserveCapacity(ranges.size());
widths.resize(0);
for (const auto& range : ranges)
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.cc
index 50e9985c623..f9059f05c5f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.cc
@@ -10,9 +10,26 @@
namespace blink {
+const unsigned NGBaselineRequest::kTypeIdCount;
+const LayoutUnit NGBaselineList::kEmptyOffset;
+
bool NGBaselineRequest::operator==(const NGBaselineRequest& other) const {
- return algorithm_type == other.algorithm_type &&
- baseline_type == other.baseline_type;
+ return algorithm_type_ == other.algorithm_type_ &&
+ baseline_type_ == other.baseline_type_;
+}
+
+bool NGBaselineRequestList::operator==(
+ const NGBaselineRequestList& other) const {
+ return type_id_mask_ == other.type_id_mask_;
+}
+
+void NGBaselineRequestList::push_back(const NGBaselineRequest& request) {
+ type_id_mask_ |= 1 << request.TypeId();
+}
+
+void NGBaselineRequestList::AppendVector(
+ const NGBaselineRequestList& requests) {
+ type_id_mask_ |= requests.type_id_mask_;
}
bool NGBaseline::ShouldPropagateBaselines(const NGLayoutInputNode node) {
@@ -38,4 +55,35 @@ bool NGBaseline::ShouldPropagateBaselines(LayoutBox* layout_box) {
return true;
}
+NGBaselineList::NGBaselineList() {
+ std::fill(std::begin(offsets_), std::end(offsets_), kEmptyOffset);
+}
+
+bool NGBaselineList::IsEmpty() const {
+ for (LayoutUnit offset : offsets_) {
+ if (offset != kEmptyOffset)
+ return false;
+ }
+ return true;
+}
+
+base::Optional<LayoutUnit> NGBaselineList::Offset(
+ const NGBaselineRequest request) const {
+ LayoutUnit offset = offsets_[request.TypeId()];
+ if (offset != kEmptyOffset)
+ return offset;
+ return base::nullopt;
+}
+
+void NGBaselineList::emplace_back(NGBaselineRequest request,
+ LayoutUnit offset) {
+ // Round LayoutUnit::Min() because we use it for an empty value.
+ DCHECK_EQ(kEmptyOffset, LayoutUnit::Min())
+ << "Change the rounding if kEmptyOffset was changed";
+ if (UNLIKELY(offset == LayoutUnit::Min()))
+ offset = LayoutUnit::NearlyMin();
+ DCHECK_NE(offset, kEmptyOffset);
+ offsets_[request.TypeId()] = offset;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h
index cfcd9a218cb..edb7d9aeb12 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h
@@ -5,8 +5,9 @@
#ifndef NGBaseline_h
#define NGBaseline_h
+#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
@@ -22,18 +23,103 @@ enum class NGBaselineAlgorithmType {
// Baselines are products of layout.
// To compute baseline, add requests to NGConstraintSpace and run Layout().
-struct NGBaselineRequest {
- NGBaselineAlgorithmType algorithm_type;
- FontBaseline baseline_type;
+class CORE_EXPORT NGBaselineRequest {
+ public:
+ NGBaselineRequest(NGBaselineAlgorithmType algorithm_type,
+ FontBaseline baseline_type)
+ : algorithm_type_(static_cast<unsigned>(algorithm_type)),
+ baseline_type_(static_cast<unsigned>(baseline_type)) {}
+
+ NGBaselineAlgorithmType AlgorithmType() const {
+ return static_cast<NGBaselineAlgorithmType>(algorithm_type_);
+ }
+
+ FontBaseline BaselineType() const {
+ return static_cast<FontBaseline>(baseline_type_);
+ }
bool operator==(const NGBaselineRequest& other) const;
bool operator!=(const NGBaselineRequest& other) const {
return !(*this == other);
}
+
+ private:
+ // TypeId is an integer that identifies all combinations of
+ // |NGBaselineRequest|. Visible only to |NGBaselineRequestList| and
+ // |NGBaselineList|.
+ static constexpr unsigned kTypeIdCount = 4;
+ unsigned TypeId() const { return algorithm_type_ | (baseline_type_ << 1); }
+ static NGBaselineRequest FromTypeId(unsigned type_id) {
+ DCHECK_LE(type_id, kTypeIdCount);
+ return NGBaselineRequest(static_cast<NGBaselineAlgorithmType>(type_id & 1),
+ static_cast<FontBaseline>((type_id >> 1) & 1));
+ }
+ friend class NGBaselineList;
+ friend class NGBaselineRequestList;
+ friend class NGBaselineTest;
+
+ unsigned algorithm_type_ : 1; // NGBaselineAlgorithmType
+ unsigned baseline_type_ : 1; // FontBaseline
+};
+
+// A list of |NGBaselineRequest| in a packed format, with similar interface as
+// |Vector|.
+class CORE_EXPORT NGBaselineRequestList {
+ public:
+ NGBaselineRequestList() = default;
+
+ bool IsEmpty() const { return !type_id_mask_; }
+
+ bool operator==(const NGBaselineRequestList& other) const;
+
+ void push_back(const NGBaselineRequest& request);
+ void AppendVector(const NGBaselineRequestList& requests);
+
+ class const_iterator {
+ public:
+ const_iterator() : type_id_(NGBaselineRequest::kTypeIdCount), mask_(0) {}
+ explicit const_iterator(unsigned mask) : type_id_(0), mask_(mask) {
+ if (!(mask_ & 1))
+ ++(*this);
+ }
+
+ const NGBaselineRequest operator*() const {
+ return NGBaselineRequest::FromTypeId(type_id_);
+ }
+ bool operator!=(const const_iterator& other) const {
+ return type_id_ != other.type_id_;
+ }
+ void operator++() {
+ while (type_id_ < NGBaselineRequest::kTypeIdCount) {
+ ++type_id_;
+ mask_ >>= 1;
+ if (mask_ & 1)
+ break;
+ }
+ }
+
+ private:
+ unsigned type_id_;
+ unsigned mask_;
+ };
+
+ const_iterator begin() const { return const_iterator(type_id_mask_); }
+ const_iterator end() const { return const_iterator(); }
+
+ private:
+ // Serialize/deserialize to a bit fields.
+ static constexpr unsigned kSerializedBits = NGBaselineRequest::kTypeIdCount;
+ unsigned Serialize() const { return type_id_mask_; }
+ explicit NGBaselineRequestList(unsigned serialized)
+ : type_id_mask_(serialized) {}
+ friend class NGConstraintSpace;
+ friend class NGConstraintSpaceBuilder;
+
+ unsigned type_id_mask_ = 0;
};
// Represents a computed baseline position.
-struct NGBaseline {
+struct CORE_EXPORT NGBaseline {
NGBaselineRequest request;
LayoutUnit offset;
@@ -42,6 +128,59 @@ struct NGBaseline {
static bool ShouldPropagateBaselines(LayoutBox*);
};
+// A list of |NGBaseline| in a packed format, with similar interface as
+// |Vector|.
+class CORE_EXPORT NGBaselineList {
+ public:
+ NGBaselineList();
+
+ bool IsEmpty() const;
+
+ base::Optional<LayoutUnit> Offset(const NGBaselineRequest request) const;
+
+ void emplace_back(NGBaselineRequest request, LayoutUnit offset);
+
+ class const_iterator {
+ public:
+ explicit const_iterator(unsigned type_id, const LayoutUnit* offset)
+ : type_id_(type_id), offset_(offset) {
+ DCHECK(offset);
+ if (*offset == kEmptyOffset)
+ ++(*this);
+ }
+ const_iterator()
+ : type_id_(NGBaselineRequest::kTypeIdCount), offset_(nullptr) {}
+
+ const NGBaseline operator*() const {
+ return NGBaseline{NGBaselineRequest::FromTypeId(type_id_), *offset_};
+ }
+ bool operator!=(const const_iterator& other) const {
+ return type_id_ != other.type_id_;
+ }
+ void operator++() {
+ while (type_id_ < NGBaselineRequest::kTypeIdCount) {
+ ++type_id_;
+ ++offset_;
+ if (type_id_ < NGBaselineRequest::kTypeIdCount &&
+ *offset_ != kEmptyOffset)
+ break;
+ }
+ }
+
+ private:
+ unsigned type_id_;
+ const LayoutUnit* offset_;
+ };
+
+ const_iterator begin() const { return const_iterator(0, offsets_); }
+ const_iterator end() const { return const_iterator(); }
+
+ private:
+ static constexpr LayoutUnit kEmptyOffset = LayoutUnit::Min();
+
+ LayoutUnit offsets_[NGBaselineRequest::kTypeIdCount];
+};
+
} // namespace blink
#endif // NGBaseline_h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline_test.cc
new file mode 100644
index 00000000000..4e311e71bdd
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline_test.cc
@@ -0,0 +1,76 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h"
+
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+using ::testing::ElementsAre;
+using ::testing::ElementsAreArray;
+
+class NGBaselineTest : public testing::Test {
+ public:
+ static NGBaselineRequest RequestFromTypeId(unsigned type_id) {
+ return NGBaselineRequest::FromTypeId(type_id);
+ }
+
+ static Vector<NGBaselineRequest> ToList(NGBaselineRequestList requests) {
+ Vector<NGBaselineRequest> list;
+ for (const NGBaselineRequest request : requests)
+ list.push_back(request);
+ return list;
+ }
+};
+
+struct NGBaselineRequestListTestData {
+ unsigned count;
+ unsigned type_ids[4];
+} baseline_request_list_test_data[] = {
+ {0, {}}, {1, {0}}, {1, {1}}, {1, {2}},
+ {1, {3}}, {2, {0, 1}}, {2, {0, 2}}, {2, {1, 3}},
+ {3, {0, 1, 2}}, {3, {0, 2, 3}}, {3, {1, 2, 3}}, {4, {0, 1, 2, 3}},
+};
+
+class NGBaselineRequestListDataTest
+ : public NGBaselineTest,
+ public testing::WithParamInterface<NGBaselineRequestListTestData> {};
+
+INSTANTIATE_TEST_CASE_P(NGBaselineTest,
+ NGBaselineRequestListDataTest,
+ testing::ValuesIn(baseline_request_list_test_data));
+
+TEST_P(NGBaselineRequestListDataTest, Data) {
+ const auto& data = GetParam();
+ NGBaselineRequestList requests;
+ Vector<NGBaselineRequest> expected;
+ for (unsigned i = 0; i < data.count; i++) {
+ NGBaselineRequest request = RequestFromTypeId(data.type_ids[i]);
+ requests.push_back(request);
+ expected.push_back(request);
+ }
+
+ EXPECT_EQ(requests.IsEmpty(), !data.count);
+
+ Vector<NGBaselineRequest> actual = ToList(requests);
+ EXPECT_THAT(actual, expected);
+}
+
+TEST_F(NGBaselineTest, BaselineList) {
+ NGBaselineList list;
+ EXPECT_TRUE(list.IsEmpty());
+
+ NGBaselineRequest request(NGBaselineAlgorithmType::kFirstLine,
+ FontBaseline::kAlphabeticBaseline);
+ list.emplace_back(request, LayoutUnit(123));
+ EXPECT_FALSE(list.IsEmpty());
+ EXPECT_EQ(list.Offset(request), LayoutUnit(123));
+ EXPECT_FALSE(list.Offset({NGBaselineAlgorithmType::kFirstLine,
+ FontBaseline::kIdeographicBaseline}));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc
index a139ca08482..d0267eb4142 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.cc
@@ -269,12 +269,13 @@ NGCaretPosition ComputeNGCaretPosition(const LayoutBlockFlow& context,
NGCaretPosition ComputeNGCaretPosition(const PositionWithAffinity& position) {
AssertValidPositionForCaretPositionComputation(position);
- const LayoutBlockFlow* context =
+ LayoutBlockFlow* context =
NGInlineFormattingContextOf(position.GetPosition());
if (!context)
return NGCaretPosition();
- const NGOffsetMapping* mapping = NGOffsetMapping::GetFor(context);
+ const NGOffsetMapping* mapping =
+ NGOffsetMapping::GetForContainingBlockFlow(context);
DCHECK(mapping);
const base::Optional<unsigned> maybe_offset =
mapping->GetTextContentOffset(position.GetPosition());
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_rect.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_rect.cc
index b0e7e25ba52..9d6fa0a16cf 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_rect.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_rect.cc
@@ -141,7 +141,7 @@ LocalCaretRect ComputeLocalCaretRect(const NGCaretPosition& caret_position) {
// See core/layout/README.md#coordinate-spaces for details.
if (fragment.Style().IsFlippedBlocksWritingMode()) {
const LayoutBlockFlow* container =
- layout_object->EnclosingNGBlockFlow();
+ layout_object->ContainingNGBlockFlow();
container->FlipForWritingMode(layout_rect);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc
index da1b76499c1..19a1adf2d90 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc
@@ -9,9 +9,10 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
@@ -67,7 +68,7 @@ void NGInlineBoxState::EnsureTextMetrics(const ComputedStyle& style,
ComputeTextMetrics(style, baseline_type);
}
-void NGInlineBoxState::AccumulateUsedFonts(const ShapeResult* shape_result,
+void NGInlineBoxState::AccumulateUsedFonts(const ShapeResultView* shape_result,
FontBaseline baseline_type) {
HashSet<const SimpleFontData*> fallback_fonts;
shape_result->FallbackFonts(&fallback_fonts);
@@ -80,6 +81,15 @@ void NGInlineBoxState::AccumulateUsedFonts(const ShapeResult* shape_result,
}
}
+LayoutUnit NGInlineBoxState::TextTop(FontBaseline baseline_type) const {
+ if (!text_metrics.IsEmpty())
+ return text_top;
+ if (const SimpleFontData* font_data = style->GetFont().PrimaryFont())
+ return -font_data->GetFontMetrics().FixedAscent(baseline_type);
+ NOTREACHED();
+ return LayoutUnit();
+}
+
bool NGInlineBoxState::CanAddTextOfStyle(
const ComputedStyle& text_style) const {
if (text_style.VerticalAlign() != EVerticalAlign::kBaseline)
@@ -158,10 +168,8 @@ NGInlineBoxState* NGInlineLayoutStateStack::OnOpenTag(
NGInlineBoxState* box = OnOpenTag(*item.Style(), line_box);
box->item = &item;
- if (item.ShouldCreateBoxFragment()) {
- box->SetNeedsBoxFragment(
- ContainingLayoutObjectForAbsolutePositionObjects());
- }
+ if (item.ShouldCreateBoxFragment())
+ box->SetNeedsBoxFragment();
// Compute box properties regardless of needs_box_fragment since close tag may
// also set needs_box_fragment.
@@ -208,6 +216,16 @@ void NGInlineLayoutStateStack::OnEndPlaceItems(
box->has_end_edge = true;
EndBoxState(box, line_box, baseline_type);
}
+
+ // Up to this point, the offset of inline boxes are stored in placeholder so
+ // that |ApplyBaselineShift()| can compute offset for both children and boxes.
+ // Copy the final offset to |box_data_list_|.
+ for (BoxData& box_data : box_data_list_) {
+ const NGLineBoxFragmentBuilder::Child& placeholder =
+ (*line_box)[box_data.fragment_end];
+ DCHECK(!placeholder.HasFragment());
+ box_data.offset = placeholder.offset;
+ }
}
void NGInlineLayoutStateStack::EndBoxState(
@@ -232,13 +250,10 @@ void NGInlineLayoutStateStack::EndBoxState(
parent_box.metrics.Unite(box->metrics);
}
-void NGInlineBoxState::SetNeedsBoxFragment(
- const LayoutObject* inline_container) {
+void NGInlineBoxState::SetNeedsBoxFragment() {
DCHECK(item);
DCHECK(!needs_box_fragment);
needs_box_fragment = true;
- DCHECK(!this->inline_container);
- this->inline_container = inline_container;
}
// Crete a placeholder for a box fragment.
@@ -250,30 +265,30 @@ void NGInlineLayoutStateStack::AddBoxFragmentPlaceholder(
NGLineBoxFragmentBuilder::ChildList* line_box,
FontBaseline baseline_type) {
DCHECK(box->needs_box_fragment);
-
- // The inline box should have the height of the font metrics without the
- // line-height property. Compute from style because |box->metrics| includes
- // the line-height property.
DCHECK(box->style);
const ComputedStyle& style = *box->style;
- NGLineHeightMetrics metrics(style, baseline_type);
- // Extend the block direction of the box by borders and paddings. Inline
- // direction is already included into positions in NGLineBreaker.
- NGLogicalOffset offset(
- LayoutUnit(),
- -metrics.ascent - (box->borders.line_over + box->padding.line_over));
- NGLogicalSize size(
- LayoutUnit(),
- metrics.LineHeight() + box->borders.BlockSum() + box->padding.BlockSum());
+ NGLogicalOffset offset;
+ NGLogicalSize size;
+ if (!is_empty_line_) {
+ // The inline box should have the height of the font metrics without the
+ // line-height property. Compute from style because |box->metrics| includes
+ // the line-height property.
+ NGLineHeightMetrics metrics(style, baseline_type);
+
+ // Extend the block direction of the box by borders and paddings. Inline
+ // direction is already included into positions in NGLineBreaker.
+ offset.block_offset =
+ -metrics.ascent - (box->borders.line_over + box->padding.line_over);
+ size.block_size = metrics.LineHeight() + box->borders.BlockSum() +
+ box->padding.BlockSum();
+ }
unsigned fragment_end = line_box->size();
DCHECK(box->item);
- box_data_list_.push_back(
- BoxData{box->fragment_start, fragment_end, box->item, size});
- BoxData& box_data = box_data_list_.back();
+ BoxData& box_data = box_data_list_.emplace_back(
+ box->fragment_start, fragment_end, box->item, size);
box_data.padding = box->padding;
- box_data.inline_container = box->inline_container;
if (box->has_start_edge) {
box_data.has_line_left_edge = true;
box_data.margin_line_left = box->margin_inline_start;
@@ -317,13 +332,17 @@ void NGInlineLayoutStateStack::AddBoxFragmentPlaceholder(
box_data.size.inline_size =
advance - box_data.margin_line_left - box_data.margin_line_right;
line_box->AddChild(box_data.CreateBoxFragment(line_box), offset, advance,
- 0);
+ /* bidi_level */ 0);
box_data_list_.pop_back();
}
}
void NGInlineLayoutStateStack::PrepareForReorder(
NGLineBoxFragmentBuilder::ChildList* line_box) {
+ // There's nothing to do if no boxes.
+ if (box_data_list_.IsEmpty())
+ return;
+
// Set indexes of BoxData to the children of the line box.
unsigned box_data_index = 0;
for (const BoxData& box_data : box_data_list_) {
@@ -341,43 +360,29 @@ void NGInlineLayoutStateStack::PrepareForReorder(
const NGLineBoxFragmentBuilder::Child& placeholder =
(*line_box)[box_data.fragment_end];
DCHECK(!placeholder.HasFragment());
- box_data.offset = placeholder.offset;
- box_data.box_data_index = placeholder.box_data_index;
+ box_data.parent_box_data_index = placeholder.box_data_index;
}
}
void NGInlineLayoutStateStack::UpdateAfterReorder(
NGLineBoxFragmentBuilder::ChildList* line_box) {
+ // There's nothing to do if no boxes.
+ if (box_data_list_.IsEmpty())
+ return;
+
// Compute start/end of boxes from the children of the line box.
+ // Clear start/end first.
for (BoxData& box_data : box_data_list_)
box_data.fragment_start = box_data.fragment_end = 0;
- for (unsigned i = 0; i < line_box->size(); i++) {
- const NGLineBoxFragmentBuilder::Child& child = (*line_box)[i];
- if (child.IsPlaceholder())
- continue;
- if (unsigned box_data_index = child.box_data_index) {
- BoxData& box_data = box_data_list_[box_data_index - 1];
- if (!box_data.fragment_end)
- box_data.fragment_start = i;
- box_data.fragment_end = i + 1;
- }
- }
- // Extend start/end of boxes when they are nested.
- for (BoxData& box_data : box_data_list_) {
- if (box_data.box_data_index) {
- BoxData& parent_box_data = box_data_list_[box_data.box_data_index - 1];
- if (!parent_box_data.fragment_end) {
- parent_box_data.fragment_start = box_data.fragment_start;
- parent_box_data.fragment_end = box_data.fragment_end;
- } else {
- parent_box_data.fragment_start =
- std::min(box_data.fragment_start, parent_box_data.fragment_start);
- parent_box_data.fragment_end =
- std::max(box_data.fragment_end, parent_box_data.fragment_end);
- }
- }
- }
+ // Scan children and update start/end from their box_data_index.
+ unsigned box_count = box_data_list_.size();
+ for (unsigned index = 0; index < line_box->size();)
+ index = UpdateBoxDataFragmentRange(line_box, index);
+
+ // If any inline fragmentation due to BiDi reorder, adjust box edges.
+ if (box_count != box_data_list_.size())
+ UpdateFragmentedBoxDataEdges();
#if DCHECK_IS_ON()
// Check all BoxData have ranges.
@@ -385,15 +390,102 @@ void NGInlineLayoutStateStack::UpdateAfterReorder(
DCHECK_NE(box_data.fragment_end, 0u);
DCHECK_GT(box_data.fragment_end, box_data.fragment_start);
}
+ // Check all |box_data_index| were migrated to BoxData.
+ for (const NGLineBoxFragmentBuilder::Child& child : *line_box) {
+ DCHECK_EQ(child.box_data_index, 0u);
+ }
#endif
}
+unsigned NGInlineLayoutStateStack::UpdateBoxDataFragmentRange(
+ NGLineBoxFragmentBuilder::ChildList* line_box,
+ unsigned index) {
+ // Find the first line box item that should create a box fragment.
+ for (; index < line_box->size(); index++) {
+ NGLineBoxFragmentBuilder::Child* start = &(*line_box)[index];
+ if (start->IsPlaceholder())
+ continue;
+ const unsigned box_data_index = start->box_data_index;
+ if (!box_data_index)
+ continue;
+
+ // As |box_data_index| is converted to start/end of BoxData, update
+ // |box_data_index| to the parent box, or to 0 if no parent boxes.
+ // This allows including this box to the nested parent box.
+ BoxData* box_data = &box_data_list_[box_data_index - 1];
+ start->box_data_index = box_data->parent_box_data_index;
+
+ // Find the end line box item.
+ const unsigned start_index = index;
+ for (index++; index < line_box->size(); index++) {
+ NGLineBoxFragmentBuilder::Child* end = &(*line_box)[index];
+ if (end->IsPlaceholder())
+ continue;
+
+ // If we found another box that maybe included in this box, update it
+ // first. Updating will change |end->box_data_index| so that we can
+ // determine if it should be included into this box or not.
+ // It also changes other BoxData, but not the one we're dealing with here
+ // because the update is limited only when its |box_data_index| is lower.
+ while (end->box_data_index && end->box_data_index < box_data_index) {
+ UpdateBoxDataFragmentRange(line_box, index);
+ // Re-compute |box_data| in case |box_data_list_| was reallocated when
+ // |UpdateBoxDataFragmentRange| added new fragments.
+ box_data = &box_data_list_[box_data_index - 1];
+ }
+
+ if (box_data_index != end->box_data_index)
+ break;
+ end->box_data_index = box_data->parent_box_data_index;
+ }
+
+ // If this is the first range for this BoxData, set it.
+ if (!box_data->fragment_end) {
+ box_data->fragment_start = start_index;
+ box_data->fragment_end = index;
+ } else {
+ // This box is fragmented by BiDi reordering. Add a new BoxData for the
+ // fragmented range.
+ box_data->fragmented_box_data_index = box_data_list_.size();
+ box_data_list_.emplace_back(*box_data, start_index, index);
+ }
+ return box_data->parent_box_data_index ? start_index : index;
+ }
+ return index;
+}
+
+void NGInlineLayoutStateStack::UpdateFragmentedBoxDataEdges() {
+ for (BoxData& box_data : box_data_list_) {
+ if (box_data.fragmented_box_data_index)
+ box_data.UpdateFragmentEdges(box_data_list_);
+ }
+}
+
+void NGInlineLayoutStateStack::BoxData::UpdateFragmentEdges(
+ Vector<BoxData, 4>& list) {
+ DCHECK(fragmented_box_data_index);
+
+ // If this box has the right edge, move it to the last fragment.
+ if (has_line_right_edge) {
+ BoxData& last = list[fragmented_box_data_index];
+ last.has_line_right_edge = true;
+ last.margin_line_right = margin_line_right;
+ last.margin_border_padding_line_right = margin_border_padding_line_right;
+ last.padding.inline_end = padding.inline_end;
+
+ has_line_right_edge = false;
+ margin_line_right = margin_border_padding_line_right = padding.inline_end =
+ LayoutUnit();
+ }
+}
+
LayoutUnit NGInlineLayoutStateStack::ComputeInlinePositions(
NGLineBoxFragmentBuilder::ChildList* line_box) {
// At this point, children are in the visual order, and they have their
// origins at (0, 0). Accumulate inline offset from left to right.
LayoutUnit position;
for (NGLineBoxFragmentBuilder::Child& child : *line_box) {
+ child.margin_line_left = child.offset.inline_offset;
child.offset.inline_offset += position;
// Box margins/boders/paddings will be processed later.
// TODO(kojii): we could optimize this if the reordering did not occur.
@@ -439,7 +531,8 @@ LayoutUnit NGInlineLayoutStateStack::ComputeInlinePositions(
// boxes, while accumulating its margin/border/padding.
unsigned start = box_data.fragment_start;
NGLineBoxFragmentBuilder::Child& start_child = (*line_box)[start];
- LayoutUnit line_left_offset = start_child.offset.inline_offset;
+ LayoutUnit line_left_offset =
+ start_child.offset.inline_offset - start_child.margin_line_left;
LinePadding& start_padding = accumulated_padding[start];
start_padding.line_left += box_data.margin_border_padding_line_left;
line_left_offset -= start_padding.line_left - box_data.margin_line_left;
@@ -447,8 +540,9 @@ LayoutUnit NGInlineLayoutStateStack::ComputeInlinePositions(
DCHECK_GT(box_data.fragment_end, start);
unsigned last = box_data.fragment_end - 1;
NGLineBoxFragmentBuilder::Child& last_child = (*line_box)[last];
- LayoutUnit line_right_offset =
- last_child.offset.inline_offset + last_child.inline_size;
+ LayoutUnit line_right_offset = last_child.offset.inline_offset -
+ last_child.margin_line_left +
+ last_child.inline_size;
LinePadding& last_padding = accumulated_padding[last];
last_padding.line_right += box_data.margin_border_padding_line_right;
line_right_offset += last_padding.line_right - box_data.margin_line_right;
@@ -494,8 +588,8 @@ NGInlineLayoutStateStack::BoxData::CreateBoxFragment(
const ComputedStyle& style = *item->Style();
// Because children are already in the visual order, use LTR for the
// fragment builder so that it should not transform the coordinates for RTL.
- NGFragmentBuilder box(item->GetLayoutObject(), &style, style.GetWritingMode(),
- TextDirection::kLtr);
+ NGBoxFragmentBuilder box(item->GetLayoutObject(), &style,
+ style.GetWritingMode(), TextDirection::kLtr);
box.SetBoxType(NGPhysicalFragment::kInlineBox);
box.SetStyleVariant(item->StyleVariant());
@@ -519,7 +613,8 @@ NGInlineLayoutStateStack::BoxData::CreateBoxFragment(
// NGInlineLayoutAlgorithm can handle them later.
DCHECK(!child.HasInFlowFragment());
}
- box.MoveOutOfFlowDescendantCandidatesToDescendants(inline_container);
+
+ box.MoveOutOfFlowDescendantCandidatesToDescendants();
return box.ToInlineBoxFragment();
}
@@ -533,15 +628,14 @@ NGInlineLayoutStateStack::ApplyBaselineShift(
// |pending_descendants|.
LayoutUnit baseline_shift;
if (!box->pending_descendants.IsEmpty()) {
- NGLineHeightMetrics max = box->MetricsForTopAndBottomAlign();
+ NGLineHeightMetrics max = MetricsForTopAndBottomAlign(*box, *line_box);
for (NGPendingPositions& child : box->pending_descendants) {
// In quirks mode, metrics is empty if no content.
if (child.metrics.IsEmpty())
child.metrics = NGLineHeightMetrics::Zero();
switch (child.vertical_align) {
case EVerticalAlign::kTextTop:
- DCHECK(!box->text_metrics.IsEmpty());
- baseline_shift = child.metrics.ascent + box->text_top;
+ baseline_shift = child.metrics.ascent + box->TextTop(baseline_type);
break;
case EVerticalAlign::kTop:
baseline_shift = child.metrics.ascent - max.ascent;
@@ -646,30 +740,42 @@ NGInlineLayoutStateStack::ApplyBaselineShift(
return kPositionNotPending;
}
-NGLineHeightMetrics NGInlineBoxState::MetricsForTopAndBottomAlign() const {
+NGLineHeightMetrics NGInlineLayoutStateStack::MetricsForTopAndBottomAlign(
+ const NGInlineBoxState& box,
+ const NGLineBoxFragmentBuilder::ChildList& line_box) const {
+ DCHECK(!box.pending_descendants.IsEmpty());
+
// |metrics| is the bounds of "aligned subtree", that is, bounds of
// descendants that are not 'vertical-align: top' nor 'bottom'.
// https://drafts.csswg.org/css2/visudet.html#propdef-vertical-align
- NGLineHeightMetrics box = metrics;
+ NGLineHeightMetrics metrics = box.metrics;
+
+ // BoxData contains inline boxes to be created later. Take them into account.
+ for (const BoxData& box_data : box_data_list_) {
+ LayoutUnit box_ascent =
+ -line_box[box_data.fragment_end].offset.block_offset;
+ metrics.Unite(
+ NGLineHeightMetrics(box_ascent, box_data.size.block_size - box_ascent));
+ }
// In quirks mode, metrics is empty if no content.
- if (box.IsEmpty())
- box = NGLineHeightMetrics::Zero();
+ if (metrics.IsEmpty())
+ metrics = NGLineHeightMetrics::Zero();
// If the height of a box that has 'vertical-align: top' or 'bottom' exceeds
// the height of the "aligned subtree", align the edge to the "aligned
// subtree" and extend the other edge.
- NGLineHeightMetrics max = box;
- for (const NGPendingPositions& child : pending_descendants) {
+ NGLineHeightMetrics max = metrics;
+ for (const NGPendingPositions& child : box.pending_descendants) {
if ((child.vertical_align == EVerticalAlign::kTop ||
child.vertical_align == EVerticalAlign::kBottom) &&
child.metrics.LineHeight() > max.LineHeight()) {
if (child.vertical_align == EVerticalAlign::kTop) {
- max = NGLineHeightMetrics(box.ascent,
- child.metrics.LineHeight() - box.ascent);
+ max = NGLineHeightMetrics(metrics.ascent,
+ child.metrics.LineHeight() - metrics.ascent);
} else if (child.vertical_align == EVerticalAlign::kBottom) {
- max = NGLineHeightMetrics(child.metrics.LineHeight() - box.descent,
- box.descent);
+ max = NGLineHeightMetrics(child.metrics.LineHeight() - metrics.descent,
+ metrics.descent);
}
}
}
@@ -693,7 +799,6 @@ void NGInlineBoxState::CheckSame(const NGInlineBoxState& other) const {
DCHECK_EQ(fragment_start, other.fragment_start);
DCHECK_EQ(item, other.item);
DCHECK_EQ(style, other.style);
- DCHECK_EQ(inline_container, other.inline_container);
DCHECK_EQ(metrics, other.metrics);
DCHECK_EQ(text_metrics, other.text_metrics);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h
index b49228cec95..80d9eb33bf0 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -18,7 +18,7 @@ namespace blink {
class LayoutObject;
class NGInlineItem;
struct NGInlineItemResult;
-class ShapeResult;
+class ShapeResultView;
// Fragments that require the layout position/size of ancestor are packed in
// this struct.
@@ -40,7 +40,6 @@ struct NGInlineBoxState {
unsigned fragment_start = 0;
const NGInlineItem* item = nullptr;
const ComputedStyle* style = nullptr;
- const LayoutObject* inline_container = nullptr;
// The united metrics for the current box. This includes all objects in this
// box, including descendants, and adjusted by placement properties such as
@@ -85,20 +84,19 @@ struct NGInlineBoxState {
void EnsureTextMetrics(const ComputedStyle&, FontBaseline);
void ResetTextMetrics();
- void AccumulateUsedFonts(const ShapeResult*, FontBaseline);
+ void AccumulateUsedFonts(const ShapeResultView*, FontBaseline);
+
+ // 'text-top' offset for 'vertical-align'.
+ LayoutUnit TextTop(FontBaseline baseline_type) const;
// Create a box fragment for this box.
- void SetNeedsBoxFragment(const LayoutObject* inline_container);
+ void SetNeedsBoxFragment();
// Returns if the text style can be added without open-tag.
// Text with different font or vertical-align needs to be wrapped with an
// inline box.
bool CanAddTextOfStyle(const ComputedStyle&) const;
- // Compute the metrics for when 'vertical-align' is 'top' and 'bottom' from
- // |pending_descendants|.
- NGLineHeightMetrics MetricsForTopAndBottomAlign() const;
-
#if DCHECK_IS_ON()
void CheckSame(const NGInlineBoxState&) const;
#endif
@@ -115,6 +113,8 @@ class CORE_EXPORT NGInlineLayoutStateStack {
// The box state for the line box.
NGInlineBoxState& LineBoxState() { return stack_.front(); }
+ void SetIsEmptyLine(bool is_empty_line) { is_empty_line_ = is_empty_line; }
+
// Initialize the box state stack for a new line.
// @return The initial box state for the line.
NGInlineBoxState* OnBeginPlaceItems(const ComputedStyle*, FontBaseline, bool);
@@ -149,6 +149,18 @@ class CORE_EXPORT NGInlineLayoutStateStack {
// reordering.
void UpdateAfterReorder(NGLineBoxFragmentBuilder::ChildList*);
+ // Update start/end of the first BoxData found at |index|.
+ //
+ // If inline fragmentation is found, a new BoxData is added.
+ //
+ // Returns the index to process next. It should be given to the next call to
+ // this function.
+ unsigned UpdateBoxDataFragmentRange(NGLineBoxFragmentBuilder::ChildList*,
+ unsigned index);
+
+ // Update edges of inline fragmented boxes.
+ void UpdateFragmentedBoxDataEdges();
+
// Compute inline positions of fragments and boxes.
LayoutUnit ComputeInlinePositions(NGLineBoxFragmentBuilder::ChildList*);
@@ -183,15 +195,35 @@ class CORE_EXPORT NGInlineLayoutStateStack {
NGLineBoxFragmentBuilder::ChildList*,
FontBaseline);
+ // Compute the metrics for when 'vertical-align' is 'top' and 'bottom' from
+ // |pending_descendants|.
+ NGLineHeightMetrics MetricsForTopAndBottomAlign(
+ const NGInlineBoxState&,
+ const NGLineBoxFragmentBuilder::ChildList&) const;
+
// Data for a box fragment. See AddBoxFragmentPlaceholder().
// This is a transient object only while building a line box.
struct BoxData {
+ BoxData(unsigned start,
+ unsigned end,
+ const NGInlineItem* item,
+ NGLogicalSize size)
+ : fragment_start(start), fragment_end(end), item(item), size(size) {}
+
+ BoxData(const BoxData& other, unsigned start, unsigned end)
+ : fragment_start(start),
+ fragment_end(end),
+ item(other.item),
+ size(other.size),
+ offset(other.offset) {}
+
+ // The range of child fragments this box contains.
unsigned fragment_start;
unsigned fragment_end;
+
const NGInlineItem* item;
NGLogicalSize size;
- const LayoutObject* inline_container = nullptr;
bool has_line_left_edge = false;
bool has_line_right_edge = false;
NGLineBoxStrut padding;
@@ -202,7 +234,10 @@ class CORE_EXPORT NGInlineLayoutStateStack {
LayoutUnit margin_border_padding_line_right;
NGLogicalOffset offset;
- unsigned box_data_index = 0;
+ unsigned parent_box_data_index = 0;
+ unsigned fragmented_box_data_index = 0;
+
+ void UpdateFragmentEdges(Vector<BoxData, 4>& list);
scoped_refptr<NGLayoutResult> CreateBoxFragment(
NGLineBoxFragmentBuilder::ChildList*);
@@ -210,6 +245,8 @@ class CORE_EXPORT NGInlineLayoutStateStack {
Vector<NGInlineBoxState, 4> stack_;
Vector<BoxData, 4> box_data_list_;
+
+ bool is_empty_line_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h
index cbacb3243a1..ff301ee8364 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h
@@ -12,7 +12,7 @@
namespace blink {
// Represents a break token for an inline node.
-class CORE_EXPORT NGInlineBreakToken : public NGBreakToken {
+class CORE_EXPORT NGInlineBreakToken final : public NGBreakToken {
public:
enum NGInlineBreakTokenFlags {
kDefault = 0,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.cc
index 765ddf3e5cd..00946fc018e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.cc
@@ -6,7 +6,6 @@
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_outline_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_buffer.h"
@@ -23,32 +22,37 @@ const char* kNGInlineItemTypeStrings[] = {
// While the spec defines "non-zero margins, padding, or borders" prevents
// line boxes to be zero-height, tests indicate that only inline direction
// of them do so. https://drafts.csswg.org/css2/visuren.html
-bool IsInlineBoxEmpty(const ComputedStyle& style,
- const LayoutObject& layout_object) {
- if (style.BorderStart().NonZero() || !style.PaddingStart().IsZero() ||
- style.BorderEnd().NonZero() || !style.PaddingEnd().IsZero())
+bool IsInlineBoxStartEmpty(const ComputedStyle& style,
+ const LayoutObject& layout_object) {
+ if (style.BorderStartWidth() || !style.PaddingStart().IsZero())
return false;
// Non-zero margin can prevent "empty" only in non-quirks mode.
// https://quirks.spec.whatwg.org/#the-line-height-calculation-quirk
- if ((!style.MarginStart().IsZero() || !style.MarginEnd().IsZero()) &&
+ if (!style.MarginStart().IsZero() &&
!layout_object.GetDocument().InLineHeightQuirksMode())
return false;
return true;
}
-// TODO(xiaochengh): Deduplicate with a similar function in ng_paint_fragment.cc
-// ::before, ::after and ::first-letter can be hit test targets.
-bool CanBeHitTestTargetPseudoNodeStyle(const ComputedStyle& style) {
- switch (style.StyleType()) {
- case kPseudoIdBefore:
- case kPseudoIdAfter:
- case kPseudoIdFirstLetter:
- return true;
- default:
- return false;
- }
+// Determines if the end of a box is "empty" as defined above.
+//
+// Keeping the "empty" state for start and end separately is important when they
+// belong to different lines, as non-empty item can force the line it belongs to
+// as non-empty.
+bool IsInlineBoxEndEmpty(const ComputedStyle& style,
+ const LayoutObject& layout_object) {
+ if (style.BorderEndWidth() || !style.PaddingEnd().IsZero())
+ return false;
+
+ // Non-zero margin can prevent "empty" only in non-quirks mode.
+ // https://quirks.spec.whatwg.org/#the-line-height-calculation-quirk
+ if (!style.MarginEnd().IsZero() &&
+ !layout_object.GetDocument().InLineHeightQuirksMode())
+ return false;
+
+ return true;
}
} // namespace
@@ -69,7 +73,6 @@ NGInlineItem::NGInlineItem(NGInlineItemType type,
bidi_level_(UBIDI_LTR),
shape_options_(kPreContext | kPostContext),
is_empty_item_(false),
- should_create_box_fragment_(false),
style_variant_(static_cast<unsigned>(NGStyleVariant::kStandard)),
end_collapse_type_(kNotCollapsible),
is_end_collapsible_newline_(false),
@@ -95,7 +98,6 @@ NGInlineItem::NGInlineItem(const NGInlineItem& other,
bidi_level_(other.bidi_level_),
shape_options_(other.shape_options_),
is_empty_item_(other.is_empty_item_),
- should_create_box_fragment_(other.should_create_box_fragment_),
style_variant_(other.style_variant_),
end_collapse_type_(other.end_collapse_type_),
is_end_collapsible_newline_(other.is_end_collapsible_newline_),
@@ -106,9 +108,20 @@ NGInlineItem::NGInlineItem(const NGInlineItem& other,
NGInlineItem::~NGInlineItem() = default;
+bool NGInlineItem::ShouldCreateBoxFragment() const {
+ if (Type() == kOpenTag || Type() == kCloseTag)
+ return ToLayoutInline(layout_object_)->ShouldCreateBoxFragment();
+ DCHECK_EQ(Type(), kAtomicInline);
+ return false;
+}
+
+void NGInlineItem::SetShouldCreateBoxFragment() {
+ DCHECK(Type() == kOpenTag || Type() == kCloseTag);
+ ToLayoutInline(layout_object_)->SetShouldCreateBoxFragment();
+}
+
void NGInlineItem::ComputeBoxProperties() {
DCHECK(!is_empty_item_);
- DCHECK(!should_create_box_fragment_);
if (type_ == NGInlineItem::kText || type_ == NGInlineItem::kAtomicInline ||
type_ == NGInlineItem::kControl)
@@ -116,24 +129,13 @@ void NGInlineItem::ComputeBoxProperties() {
if (type_ == NGInlineItem::kOpenTag) {
DCHECK(style_ && layout_object_ && layout_object_->IsLayoutInline());
- if (style_->HasBoxDecorationBackground() || style_->HasPadding() ||
- style_->HasMargin()) {
- is_empty_item_ = IsInlineBoxEmpty(*style_, *layout_object_);
- should_create_box_fragment_ = true;
- } else {
- is_empty_item_ = true;
- should_create_box_fragment_ =
- ToLayoutBoxModelObject(layout_object_)->HasSelfPaintingLayer() ||
- style_->CanContainAbsolutePositionObjects() ||
- style_->CanContainFixedPositionObjects(false) ||
- NGOutlineUtils::HasPaintedOutline(*style_,
- layout_object_->GetNode()) ||
- ToLayoutBoxModelObject(layout_object_)
- ->ShouldApplyPaintContainment() ||
- ToLayoutBoxModelObject(layout_object_)
- ->ShouldApplyLayoutContainment() ||
- CanBeHitTestTargetPseudoNodeStyle(*style_);
- }
+ is_empty_item_ = IsInlineBoxStartEmpty(*style_, *layout_object_);
+ return;
+ }
+
+ if (type_ == NGInlineItem::kCloseTag) {
+ DCHECK(style_ && layout_object_ && layout_object_->IsLayoutInline());
+ is_empty_item_ = IsInlineBoxEndEmpty(*style_, *layout_object_);
return;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h
index fff083fed85..8becfc61e55 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h
@@ -91,8 +91,8 @@ class CORE_EXPORT NGInlineItem {
// If this item should create a box fragment. Box fragments can be omitted for
// optimization if this is false.
- bool ShouldCreateBoxFragment() const { return should_create_box_fragment_; }
- void SetShouldCreateBoxFragment() { should_create_box_fragment_ = true; }
+ bool ShouldCreateBoxFragment() const;
+ void SetShouldCreateBoxFragment();
unsigned StartOffset() const { return start_offset_; }
unsigned EndOffset() const { return end_offset_; }
@@ -196,7 +196,6 @@ class CORE_EXPORT NGInlineItem {
unsigned bidi_level_ : 8; // UBiDiLevel is defined as uint8_t.
unsigned shape_options_ : 2;
unsigned is_empty_item_ : 1;
- unsigned should_create_box_fragment_ : 1;
unsigned style_variant_ : 2;
unsigned end_collapse_type_ : 2; // NGCollapseType
unsigned is_end_collapsible_newline_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.cc
index d81c185d04e..960648adae9 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
@@ -25,30 +26,10 @@ NGInlineItemResult::NGInlineItemResult(const NGInlineItem* item,
void NGLineInfo::SetLineStyle(const NGInlineNode& node,
const NGInlineItemsData& items_data,
- const NGConstraintSpace& constraint_space,
- bool is_first_line,
- bool use_first_line_style,
- bool is_after_forced_break) {
+ bool use_first_line_style) {
use_first_line_style_ = use_first_line_style;
items_data_ = &items_data;
line_style_ = node.GetLayoutBox()->Style(use_first_line_style_);
-
- if (line_style_->ShouldUseTextIndent(is_first_line, is_after_forced_break)) {
- // 'text-indent' applies to block container, and percentage is of its
- // containing block.
- // https://drafts.csswg.org/css-text-3/#valdef-text-indent-percentage
- // In our constraint space tree, parent constraint space is of its
- // containing block.
- // TODO(kojii): ComputeMinMaxSize does not know parent constraint
- // space that we cannot compute percent for text-indent.
- const Length& length = line_style_->TextIndent();
- LayoutUnit maximum_value;
- if (length.IsPercentOrCalc())
- maximum_value = constraint_space.ParentPercentageResolutionInlineSize();
- text_indent_ = MinimumValueForLength(length, maximum_value);
- } else {
- text_indent_ = LayoutUnit();
- }
}
#if DCHECK_IS_ON()
@@ -60,8 +41,8 @@ void NGInlineItemResult::CheckConsistency(bool during_line_break) const {
return;
DCHECK(shape_result);
DCHECK_EQ(end_offset - start_offset, shape_result->NumCharacters());
- DCHECK_EQ(start_offset, shape_result->StartIndexForResult());
- DCHECK_EQ(end_offset, shape_result->EndIndexForResult());
+ DCHECK_EQ(start_offset, shape_result->StartIndex());
+ DCHECK_EQ(end_offset, shape_result->EndIndex());
}
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h
index da38185ccf8..e10711c4ea3 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h
@@ -10,12 +10,11 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_end_effect.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
-class NGConstraintSpace;
class NGInlineItem;
class NGInlineNode;
@@ -45,7 +44,7 @@ struct CORE_EXPORT NGInlineItemResult {
// ShapeResult for text items. Maybe different from NGInlineItem if re-shape
// is needed in the line breaker.
- scoped_refptr<const ShapeResult> shape_result;
+ scoped_refptr<const ShapeResultView> shape_result;
// NGLayoutResult for atomic inline items.
scoped_refptr<NGLayoutResult> layout_result;
@@ -132,10 +131,7 @@ class CORE_EXPORT NGLineInfo {
}
void SetLineStyle(const NGInlineNode&,
const NGInlineItemsData&,
- const NGConstraintSpace&,
- bool is_first_formatted_line,
- bool use_first_line_style,
- bool is_after_forced_break);
+ bool use_first_line_style);
// Use ::first-line style if true.
// https://drafts.csswg.org/css-pseudo/#selectordef-first-line
@@ -159,6 +155,7 @@ class CORE_EXPORT NGLineInfo {
NGInlineItemResults* MutableResults() { return &results_; }
const NGInlineItemResults& Results() const { return results_; }
+ void SetTextIndent(LayoutUnit indent) { text_indent_ = indent; }
LayoutUnit TextIndent() const { return text_indent_; }
NGBfcOffset BfcOffset() const { return bfc_offset_; }
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h
new file mode 100644
index 00000000000..6990f6d2a23
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h
@@ -0,0 +1,37 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_INLINE_ITEMS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_INLINE_ITEMS_H_
+
+#include "base/macros.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+class NGInlineItem;
+
+// A collection of |NGInlineItem| associated to |LayoutNGText|.
+//
+// ***** INLINE ITEMS OWNERSHIP *****
+// NGInlineItems in items_ are not owned by LayoutText but are pointers into the
+// LayoutNGBlockFlow's items_. Should not be accessed outside of layout.
+class NGInlineItems final {
+ public:
+ NGInlineItems() = default;
+
+ void Add(NGInlineItem* item) { items_.push_back(item); }
+ void Clear() { items_.clear(); }
+ const Vector<NGInlineItem*>& Items() const { return items_; }
+
+ private:
+ Vector<NGInlineItem*> items_;
+
+ DISALLOW_COPY_AND_ASSIGN(NGInlineItems);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_INLINE_ITEMS_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.cc
index 1757b0fd6e1..2fe5b2fd4a1 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.cc
@@ -4,14 +4,23 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h"
+#include <type_traits>
+
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
+// Returns true if items builder is used for other than offset mapping.
+template <typename OffsetMappingBuilder>
+bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::NeedsBoxInfo() {
+ return !std::is_same<NGOffsetMappingBuilder, OffsetMappingBuilder>::value;
+}
+
template <typename OffsetMappingBuilder>
NGInlineItemsBuilderTemplate<
OffsetMappingBuilder>::~NGInlineItemsBuilderTemplate() {
@@ -21,11 +30,6 @@ NGInlineItemsBuilderTemplate<
template <typename OffsetMappingBuilder>
String NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::ToString() {
- // Segment Break Transformation Rules[1] defines to keep trailing new lines,
- // but it will be removed in Phase II[2]. We prefer not to add trailing new
- // lines and collapsible spaces in Phase I.
- RemoveTrailingCollapsibleSpaceIfExists();
-
return text_.ToString();
}
@@ -247,8 +251,8 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::
template <typename OffsetMappingBuilder>
bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::Append(
const String& original_string,
- LayoutNGText* layout_text,
- const Vector<NGInlineItem*>& items) {
+ LayoutText* layout_text) {
+ const Vector<NGInlineItem*>& items = layout_text->InlineItems();
// Don't reuse existing items if they might be affected by whitespace
// collapsing.
// TODO(layout-dev): This could likely be optimized further.
@@ -335,8 +339,8 @@ bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::Append(
DCHECK_EQ(start, adjusted_item.StartOffset());
DCHECK_EQ(end, adjusted_item.EndOffset());
if (adjusted_item.TextShapeResult()) {
- DCHECK_EQ(start, adjusted_item.TextShapeResult()->StartIndexForResult());
- DCHECK_EQ(end, adjusted_item.TextShapeResult()->EndIndexForResult());
+ DCHECK_EQ(start, adjusted_item.TextShapeResult()->StartIndex());
+ DCHECK_EQ(end, adjusted_item.TextShapeResult()->EndIndex());
}
DCHECK_EQ(item->IsEmptyItem(), adjusted_item.IsEmptyItem());
#endif
@@ -348,10 +352,8 @@ bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::Append(
}
template <>
-bool NGInlineItemsBuilderTemplate<NGOffsetMappingBuilder>::Append(
- const String&,
- LayoutNGText*,
- const Vector<NGInlineItem*>&) {
+bool NGInlineItemsBuilderTemplate<NGOffsetMappingBuilder>::Append(const String&,
+ LayoutText*) {
NOTREACHED();
return false;
}
@@ -600,7 +602,7 @@ void NGInlineItemsBuilderTemplate<
continue;
}
- size_t end = string.Find(IsControlItemCharacter, start + 1);
+ wtf_size_t end = string.Find(IsControlItemCharacter, start + 1);
if (end == kNotFound)
end = string.length();
AppendTextItem(string, start, end, style, layout_object);
@@ -620,7 +622,7 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendPreserveNewline(
continue;
}
- size_t end = string.find(kNewlineCharacter, start + 1);
+ wtf_size_t end = string.find(kNewlineCharacter, start + 1);
if (end == kNotFound)
end = string.length();
DCHECK_GE(end, start);
@@ -777,8 +779,13 @@ void NGInlineItemsBuilderTemplate<
// Remove the item if the item has only one space that we're removing.
if (item->Length() == 1) {
DCHECK_EQ(item->StartOffset(), space_offset);
- unsigned index = std::distance(items_->begin(), item);
+ wtf_size_t index =
+ static_cast<wtf_size_t>(std::distance(items_->begin(), item));
items_->EraseAt(index);
+ for (BoxInfo& box : boxes_) {
+ if (box.item_index >= index)
+ --box.item_index;
+ }
if (index == items_->size())
return;
// Re-compute |item| because |EraseAt| may have reallocated the buffer.
@@ -937,6 +944,9 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::EnterInline(
AppendOpaque(NGInlineItem::kOpenTag, style, node);
+ if (!NeedsBoxInfo())
+ return;
+
// Set |ShouldCreateBoxFragment| of the parent box if needed.
BoxInfo* current_box =
&boxes_.emplace_back(items_->size() - 1, items_->back());
@@ -952,6 +962,11 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::EnterInline(
template <typename OffsetMappingBuilder>
void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::ExitBlock() {
Exit(nullptr);
+
+ // Segment Break Transformation Rules[1] defines to keep trailing new lines,
+ // but it will be removed in Phase II[2]. We prefer not to add trailing new
+ // lines and collapsible spaces in Phase I.
+ RemoveTrailingCollapsibleSpaceIfExists();
}
template <typename OffsetMappingBuilder>
@@ -961,7 +976,8 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::ExitInline(
AppendOpaque(NGInlineItem::kCloseTag, node->Style(), node);
- boxes_.pop_back();
+ if (NeedsBoxInfo())
+ boxes_.pop_back();
Exit(node);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h
index b72fb3970ff..1a09cfdb092 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h
@@ -18,7 +18,6 @@
namespace blink {
class ComputedStyle;
-class LayoutNGText;
class LayoutObject;
class LayoutText;
@@ -59,7 +58,7 @@ class NGInlineItemsBuilderTemplate {
// Returns whether the existing items could be reused.
// NOTE: The state of the builder remains unchanged if the append operation
// fails (i.e. if it returns false).
- bool Append(const String&, LayoutNGText*, const Vector<NGInlineItem*>&);
+ bool Append(const String&, LayoutText*);
// Append a string.
// When appending, spaces are collapsed according to CSS Text, The white space
@@ -112,6 +111,8 @@ class NGInlineItemsBuilderTemplate {
void SetIsSymbolMarker(bool b);
private:
+ static bool NeedsBoxInfo();
+
Vector<NGInlineItem>* items_;
StringBuilder text_;
@@ -185,8 +186,7 @@ class NGInlineItemsBuilderTemplate {
template <>
CORE_EXPORT bool NGInlineItemsBuilderTemplate<NGOffsetMappingBuilder>::Append(
const String&,
- LayoutNGText*,
- const Vector<NGInlineItem*>&);
+ LayoutText*);
extern template class CORE_EXTERN_TEMPLATE_EXPORT
NGInlineItemsBuilderTemplate<EmptyOffsetMappingBuilder>;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder_test.cc
index 12dbf885f0e..bdbc6558e00 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder_test.cc
@@ -57,6 +57,7 @@ class NGInlineItemsBuilderTest : public NGLayoutTest {
}
builder.Append(input.text, input.layout_text->Style(), input.layout_text);
}
+ builder.ExitBlock();
text_ = builder.ToString();
ValidateItems();
CheckReuseItemsProducesSameResult(inputs);
@@ -97,23 +98,21 @@ class NGInlineItemsBuilderTest : public NGLayoutTest {
for (Input& input : inputs) {
// Collect items for this LayoutObject.
DCHECK(input.layout_text);
- Vector<NGInlineItem*> previous_items;
for (auto& item : items_) {
if (item.GetLayoutObject() == input.layout_text)
- previous_items.push_back(&item);
+ input.layout_text->AddInlineItem(&item);
}
// Try to re-use previous items, or Append if it was not re-usable.
- bool reused =
- !previous_items.IsEmpty() &&
- reuse_builder.Append(text_, ToLayoutNGText(input.layout_text),
- previous_items);
+ bool reused = input.layout_text->HasValidInlineItems() &&
+ reuse_builder.Append(text_, input.layout_text);
if (!reused) {
reuse_builder.Append(input.text, input.layout_text->Style(),
input.layout_text);
}
}
+ reuse_builder.ExitBlock();
String reuse_text = reuse_builder.ToString();
EXPECT_EQ(text_, reuse_text);
}
@@ -406,6 +405,7 @@ static std::unique_ptr<LayoutInline> CreateLayoutInline(
initialize_style(style.get());
std::unique_ptr<LayoutInline> node = std::make_unique<LayoutInline>(nullptr);
node->SetStyleInternal(std::move(style));
+ node->SetIsInLayoutNGInlineFormattingContext(true);
return node;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc
index 94888b48188..87358fff774 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -6,6 +6,7 @@
#include <memory>
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
@@ -31,6 +32,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
namespace {
@@ -129,6 +131,17 @@ NGInlineBoxState* NGInlineLayoutAlgorithm::HandleOpenTag(
return box;
}
+NGInlineBoxState* NGInlineLayoutAlgorithm::HandleCloseTag(
+ const NGInlineItem& item,
+ const NGInlineItemResult& item_result,
+ NGInlineBoxState* box) {
+ if (UNLIKELY(quirks_mode_ && !item.IsEmptyItem()))
+ box->EnsureTextMetrics(*item.Style(), baseline_type_);
+ box = box_states_->OnCloseTag(&line_box_, box, baseline_type_,
+ item.HasEndEdge());
+ return box;
+}
+
// Prepare NGInlineLayoutStateStack for a new line.
void NGInlineLayoutAlgorithm::PrepareBoxStates(
const NGLineInfo& line_info,
@@ -206,7 +219,7 @@ void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info,
NGExclusionSpace* exclusion_space) {
// Needs MutableResults to move ShapeResult out of the NGLineInfo.
NGInlineItemResults* line_items = line_info->MutableResults();
- line_box_.clear();
+ line_box_.resize(0);
// Apply justification before placing items, because it affects size/position
// of items, which are needed to compute inline static positions.
@@ -226,6 +239,7 @@ void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info,
// Compute heights of all inline items by placing the dominant baseline at 0.
// The baseline is adjusted after the height of the line box is computed.
+ box_states_->SetIsEmptyLine(line_info->IsEmptyLine());
NGInlineBoxState* box =
box_states_->OnBeginPlaceItems(&line_style, baseline_type_, quirks_mode_);
#if DCHECK_IS_ON()
@@ -248,7 +262,7 @@ void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info,
item.GetLayoutObject()->IsLayoutNGListItem());
DCHECK(item_result.shape_result);
- if (quirks_mode_)
+ if (UNLIKELY(quirks_mode_))
box->EnsureTextMetrics(*item.Style(), baseline_type_);
// Take all used fonts into account if 'line-height: normal'.
@@ -273,12 +287,9 @@ void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info,
} else if (item.Type() == NGInlineItem::kOpenTag) {
box = HandleOpenTag(item, item_result, box_states_);
} else if (item.Type() == NGInlineItem::kCloseTag) {
- if (quirks_mode_ && box->needs_box_fragment)
- box->EnsureTextMetrics(*item.Style(), baseline_type_);
- box = box_states_->OnCloseTag(&line_box_, box, baseline_type_,
- item.HasEndEdge());
+ box = HandleCloseTag(item, item_result, box);
} else if (item.Type() == NGInlineItem::kAtomicInline) {
- box = PlaceAtomicInline(item, &item_result, *line_info);
+ box = PlaceAtomicInline(item, *line_info, &item_result);
} else if (item.Type() == NGInlineItem::kListMarker) {
PlaceListMarker(item, &item_result, *line_info);
} else if (item.Type() == NGInlineItem::kOutOfFlowPositioned) {
@@ -300,14 +311,11 @@ void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info,
box_states_->OnEndPlaceItems(&line_box_, baseline_type_);
- // TODO(kojii): For LTR, we can optimize ComputeInlinePositions() to compute
- // without PrepareForReorder() and UpdateAfterReorder() even when
- // HasBoxFragments(). We do this to share the logic between LTR and RTL, and
- // to get more coverage for RTL, but when we're more stabilized, we could have
- // optimized code path for LTR.
- box_states_->PrepareForReorder(&line_box_);
- BidiReorder();
- box_states_->UpdateAfterReorder(&line_box_);
+ if (UNLIKELY(Node().IsBidiEnabled())) {
+ box_states_->PrepareForReorder(&line_box_);
+ BidiReorder();
+ box_states_->UpdateAfterReorder(&line_box_);
+ }
LayoutUnit inline_size = box_states_->ComputeInlinePositions(&line_box_);
// Truncate the line if 'text-overflow: ellipsis' is set.
@@ -350,8 +358,11 @@ void NGInlineLayoutAlgorithm::CreateLine(NGLineInfo* line_info,
// Even if we have something in-flow, it may just be empty items that
// shouldn't trigger creation of a line. Exit now if that's the case.
- if (line_info->IsEmptyLine())
+ if (line_info->IsEmptyLine()) {
+ container_builder_.SetIsEmptyLineBox();
+ container_builder_.AddChildren(line_box_);
return;
+ }
DCHECK(!line_box_metrics.IsEmpty());
@@ -399,7 +410,7 @@ void NGInlineLayoutAlgorithm::PlaceControlItem(const NGInlineItem& item,
DCHECK(item.GetLayoutObject());
DCHECK(item.GetLayoutObject()->IsText());
- if (quirks_mode_ && !box->HasMetrics())
+ if (UNLIKELY(quirks_mode_ && !box->HasMetrics()))
box->EnsureTextMetrics(*item.Style(), baseline_type_);
NGTextFragmentBuilder text_builder(Node(),
@@ -420,7 +431,7 @@ void NGInlineLayoutAlgorithm::PlaceGeneratedContent(
: fragment->Size().height;
const ComputedStyle& style = fragment->Style();
if (box->CanAddTextOfStyle(style)) {
- if (quirks_mode_)
+ if (UNLIKELY(quirks_mode_))
box->EnsureTextMetrics(style, baseline_type_);
DCHECK(!box->text_metrics.IsEmpty());
line_box_.AddChild(std::move(fragment), box->text_top, inline_size,
@@ -440,8 +451,8 @@ void NGInlineLayoutAlgorithm::PlaceGeneratedContent(
NGInlineBoxState* NGInlineLayoutAlgorithm::PlaceAtomicInline(
const NGInlineItem& item,
- NGInlineItemResult* item_result,
- const NGLineInfo& line_info) {
+ const NGLineInfo& line_info,
+ NGInlineItemResult* item_result) {
DCHECK(item_result->layout_result);
// The input |position| is the line-left edge of the margin box.
@@ -488,48 +499,47 @@ void NGInlineLayoutAlgorithm::PlaceOutOfFlowObjects(
TextDirection line_direction = line_info.BaseDirection();
for (NGLineBoxFragmentBuilder::Child& child : line_box_) {
- if (LayoutObject* box = child.out_of_flow_positioned_box) {
- // The static position is at the line-top. Ignore the block_offset.
- NGLogicalOffset static_offset(child.offset.inline_offset, LayoutUnit());
-
- // If a block-level box appears in the middle of a line, move the static
- // position to where the next block will be placed.
- if (!box->StyleRef().IsOriginalDisplayInlineType()) {
- LayoutUnit inline_offset = container_builder_.BfcLineOffset() -
- ConstraintSpace().BfcOffset().line_offset;
-
- // Flip the inline_offset if we are in RTL.
- if (IsRtl(line_direction)) {
- LayoutUnit container_inline_size =
- ConstraintSpace().AvailableSize().inline_size;
- inline_offset = container_inline_size - inline_offset + inline_size;
- }
-
- inline_offset += line_info.TextIndent();
-
- // We need to subtract the line offset, in order to ignore
- // floats and text-indent.
- static_offset.inline_offset = -inline_offset;
-
- if (child.offset.inline_offset && !line_box_metrics.IsEmpty())
- static_offset.block_offset = line_box_metrics.LineHeight();
- } else {
- // Our child offset is line-relative, but the static offset is
- // flow-relative, using the direction we give to
- // |AddInlineOutOfFlowChildCandidate|.
- if (IsRtl(line_direction)) {
- static_offset.inline_offset =
- inline_size - static_offset.inline_offset;
- }
+ LayoutObject* box = child.out_of_flow_positioned_box;
+ if (!box)
+ continue;
+
+ // The static position is at the line-top. Ignore the block_offset.
+ NGLogicalOffset static_offset(child.offset.inline_offset, LayoutUnit());
+
+ // If a block-level box appears in the middle of a line, move the static
+ // position to where the next block will be placed.
+ if (!box->StyleRef().IsOriginalDisplayInlineType()) {
+ LayoutUnit inline_offset = container_builder_.BfcLineOffset() -
+ ConstraintSpace().BfcOffset().line_offset;
+
+ // Flip the inline_offset if we are in RTL.
+ if (IsRtl(line_direction)) {
+ LayoutUnit container_inline_size =
+ ConstraintSpace().AvailableSize().inline_size;
+ inline_offset = container_inline_size - inline_offset + inline_size;
}
- container_builder_.AddInlineOutOfFlowChildCandidate(
- NGBlockNode(ToLayoutBox(box)), static_offset, line_direction,
- child.out_of_flow_containing_box);
+ inline_offset += line_info.TextIndent();
+
+ // We need to subtract the line offset, in order to ignore floats and
+ // text-indent.
+ static_offset.inline_offset = -inline_offset;
- child.out_of_flow_positioned_box = child.out_of_flow_containing_box =
- nullptr;
+ if (child.offset.inline_offset && !line_box_metrics.IsEmpty())
+ static_offset.block_offset = line_box_metrics.LineHeight();
+ } else if (IsRtl(line_direction)) {
+ // Our child offset is line-relative, but the static offset is
+ // flow-relative, using the direction we give to
+ // |AddInlineOutOfFlowChildCandidate|.
+ static_offset.inline_offset = inline_size - static_offset.inline_offset;
}
+
+ container_builder_.AddInlineOutOfFlowChildCandidate(
+ NGBlockNode(ToLayoutBox(box)), static_offset, line_direction,
+ child.out_of_flow_containing_box);
+
+ child.out_of_flow_positioned_box = nullptr;
+ child.out_of_flow_containing_box = nullptr;
}
}
@@ -537,7 +547,7 @@ void NGInlineLayoutAlgorithm::PlaceOutOfFlowObjects(
void NGInlineLayoutAlgorithm::PlaceListMarker(const NGInlineItem& item,
NGInlineItemResult* item_result,
const NGLineInfo& line_info) {
- if (quirks_mode_) {
+ if (UNLIKELY(quirks_mode_)) {
box_states_->LineBoxState().EnsureTextMetrics(*item.Style(),
baseline_type_);
}
@@ -577,20 +587,18 @@ bool NGInlineLayoutAlgorithm::ApplyJustify(NGLineInfo* line_info) {
if (item_result.has_only_trailing_spaces)
break;
if (item_result.shape_result) {
- // Mutate the existing shape result if only used here, if not create a
- // copy.
scoped_refptr<ShapeResult> shape_result =
- item_result.shape_result->MutableUnique();
+ item_result.shape_result->CreateShapeResult();
DCHECK_GE(item_result.start_offset, line_info->StartOffset());
// |shape_result| has more characters if it's hyphenated.
DCHECK(item_result.text_end_effect != NGTextEndEffect::kNone ||
shape_result->NumCharacters() ==
item_result.end_offset - item_result.start_offset);
- shape_result->ApplySpacing(
- spacing, item_result.start_offset - line_info->StartOffset() -
- shape_result->StartIndexForResult());
+ shape_result->ApplySpacing(spacing, item_result.start_offset -
+ line_info->StartOffset() -
+ shape_result->StartIndex());
item_result.inline_size = shape_result->SnappedWidth();
- item_result.shape_result = std::move(shape_result);
+ item_result.shape_result = ShapeResultView::Create(shape_result.get());
} else if (item_result.item->Type() == NGInlineItem::kAtomicInline) {
float offset = 0.f;
DCHECK_LE(line_info->StartOffset(), item_result.start_offset);
@@ -640,8 +648,9 @@ LayoutUnit NGInlineLayoutAlgorithm::ComputeContentSize(
if (layout_object && layout_object->IsBR()) {
NGBfcOffset bfc_offset = {ContainerBfcOffset().line_offset,
ContainerBfcOffset().block_offset + content_size};
- AdjustToClearance(exclusion_space.ClearanceOffset(item.Style()->Clear()),
- &bfc_offset);
+ AdjustToClearance(
+ exclusion_space.ClearanceOffset(ResolvedClear(*item.Style(), Style())),
+ &bfc_offset);
content_size = bfc_offset.block_offset - ContainerBfcOffset().block_offset;
}
@@ -725,8 +734,8 @@ scoped_refptr<NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
#endif
// Reset any state that may have been modified in a previous pass.
- positioned_floats.clear();
- unpositioned_floats_.clear();
+ positioned_floats.Shrink(0);
+ unpositioned_floats_.Shrink(0);
container_builder_.Reset();
exclusion_space = initial_exclusion_space;
@@ -832,7 +841,7 @@ scoped_refptr<NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
DCHECK(unpositioned_floats_.IsEmpty() || is_empty_inline);
container_builder_.SwapPositionedFloats(&positioned_floats_);
container_builder_.SetExclusionSpace(std::move(exclusion_space));
- container_builder_.MoveOutOfFlowDescendantCandidatesToDescendants(nullptr);
+ container_builder_.MoveOutOfFlowDescendantCandidatesToDescendants();
return container_builder_.ToLineBoxFragment();
}
@@ -849,9 +858,9 @@ unsigned NGInlineLayoutAlgorithm::PositionLeadingFloats(
if (item.Type() == NGInlineItem::kFloating) {
NGBlockNode node(ToLayoutBox(item.GetLayoutObject()));
- AddUnpositionedFloat(
- &unpositioned_floats_, &container_builder_,
- NGUnpositionedFloat(node, /* break_token */ nullptr));
+ AddUnpositionedFloat(&unpositioned_floats_, &container_builder_,
+ NGUnpositionedFloat(node, /* break_token */ nullptr),
+ ConstraintSpace());
}
// Abort if we've found something that makes this a non-empty inline.
@@ -876,7 +885,7 @@ void NGInlineLayoutAlgorithm::PositionPendingFloats(
<< "The floats BFC block offset should be known here";
if (BreakToken() && BreakToken()->IgnoreFloats()) {
- unpositioned_floats_.clear();
+ unpositioned_floats_.Shrink(0);
return;
}
@@ -888,15 +897,15 @@ void NGInlineLayoutAlgorithm::PositionPendingFloats(
NGBfcOffset origin_bfc_offset = {ConstraintSpace().BfcOffset().line_offset,
bfc_block_offset + content_size};
- const NGPositionedFloatVector positioned_floats =
- PositionFloats(ConstraintSpace().AvailableSize(),
- ConstraintSpace().PercentageResolutionSize(),
- ConstraintSpace().ReplacedPercentageResolutionSize(),
- origin_bfc_offset, bfc_block_offset, unpositioned_floats_,
- ConstraintSpace(), exclusion_space);
+ NGPositionedFloatVector positioned_floats;
+ PositionFloats(ConstraintSpace().AvailableSize(),
+ ConstraintSpace().PercentageResolutionSize(),
+ ConstraintSpace().ReplacedPercentageResolutionSize(),
+ origin_bfc_offset, unpositioned_floats_, ConstraintSpace(),
+ Style(), exclusion_space, &positioned_floats);
positioned_floats_.AppendVector(positioned_floats);
- unpositioned_floats_.clear();
+ unpositioned_floats_.Shrink(0);
}
void NGInlineLayoutAlgorithm::BidiReorder() {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.h
index e5f89bf3b6a..a65f542436a 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.h
@@ -8,8 +8,8 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float_vector.h"
@@ -69,6 +69,9 @@ class CORE_EXPORT NGInlineLayoutAlgorithm final
NGInlineBoxState* HandleOpenTag(const NGInlineItem&,
const NGInlineItemResult&,
NGInlineLayoutStateStack*) const;
+ NGInlineBoxState* HandleCloseTag(const NGInlineItem&,
+ const NGInlineItemResult&,
+ NGInlineBoxState*);
void BidiReorder();
@@ -80,8 +83,8 @@ class CORE_EXPORT NGInlineLayoutAlgorithm final
UBiDiLevel,
NGInlineBoxState*);
NGInlineBoxState* PlaceAtomicInline(const NGInlineItem&,
- NGInlineItemResult*,
- const NGLineInfo&);
+ const NGLineInfo&,
+ NGInlineItemResult*);
void PlaceLayoutResult(NGInlineItemResult*,
NGInlineBoxState*,
LayoutUnit inline_offset = LayoutUnit());
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc
index 73ab95e3d80..4585f67824a 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc
@@ -44,30 +44,27 @@ TEST_F(NGInlineLayoutAlgorithmTest, BreakToken) {
NGConstraintSpace constraint_space =
NGConstraintSpaceBuilder(
- WritingMode::kHorizontalTb,
- /* icb_size */ size.ConvertToPhysical(WritingMode::kHorizontalTb))
+ WritingMode::kHorizontalTb, WritingMode::kHorizontalTb,
+ /* is_new_fc */ false)
.SetAvailableSize(size)
- .ToConstraintSpace(WritingMode::kHorizontalTb);
+ .ToConstraintSpace();
NGInlineChildLayoutContext context;
scoped_refptr<NGLayoutResult> layout_result =
inline_node.Layout(constraint_space, nullptr, &context);
- auto* line1 =
- ToNGPhysicalLineBoxFragment(layout_result->PhysicalFragment().get());
+ auto* line1 = ToNGPhysicalLineBoxFragment(layout_result->PhysicalFragment());
EXPECT_FALSE(line1->BreakToken()->IsFinished());
// Perform 2nd layout with the break token from the 1st line.
scoped_refptr<NGLayoutResult> layout_result2 =
inline_node.Layout(constraint_space, line1->BreakToken(), &context);
- auto* line2 =
- ToNGPhysicalLineBoxFragment(layout_result2->PhysicalFragment().get());
+ auto* line2 = ToNGPhysicalLineBoxFragment(layout_result2->PhysicalFragment());
EXPECT_FALSE(line2->BreakToken()->IsFinished());
// Perform 3rd layout with the break token from the 2nd line.
scoped_refptr<NGLayoutResult> layout_result3 =
inline_node.Layout(constraint_space, line2->BreakToken(), &context);
- auto* line3 =
- ToNGPhysicalLineBoxFragment(layout_result3->PhysicalFragment().get());
+ auto* line3 = ToNGPhysicalLineBoxFragment(layout_result3->PhysicalFragment());
EXPECT_TRUE(line3->BreakToken()->IsFinished());
}
@@ -129,6 +126,51 @@ TEST_F(NGInlineLayoutAlgorithmTest, GenerateEllipsis) {
EXPECT_EQ(line1.Children()[0]->GetLayoutObject(), ellipsis.GetLayoutObject());
}
+// This test ensures box fragments are generated when necessary, even when the
+// line is empty. One such case is when the line contains a containing box of an
+// out-of-flow object.
+TEST_F(NGInlineLayoutAlgorithmTest,
+ EmptyLineWithOutOfFlowInInlineContainingBlock) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ oof-container {
+ position: relative;
+ }
+ oof {
+ position: absolute;
+ width: 100px;
+ height: 100px;
+ }
+ html, body { margin: 0; }
+ html {
+ font-size: 10px;
+ }
+ </style>
+ <div id=container>
+ <oof-container>
+ <oof></oof>
+ </oof-container>
+ </div>
+ )HTML");
+ LayoutBlockFlow* block_flow =
+ ToLayoutBlockFlow(GetLayoutObjectByElementId("container"));
+ const NGPhysicalBoxFragment* container = block_flow->CurrentFragment();
+ ASSERT_TRUE(container);
+ EXPECT_EQ(LayoutUnit(), container->Size().height);
+
+ EXPECT_EQ(2u, container->Children().size());
+ const NGPhysicalLineBoxFragment& linebox =
+ ToNGPhysicalLineBoxFragment(*container->Children()[0]);
+
+ EXPECT_EQ(1u, linebox.Children().size());
+ EXPECT_EQ(NGPhysicalSize(), linebox.Size());
+
+ const NGPhysicalBoxFragment& oof_container =
+ ToNGPhysicalBoxFragment(*linebox.Children()[0]);
+ EXPECT_EQ(NGPhysicalSize(), oof_container.Size());
+}
+
// This test ensures that if an inline box generates (or does not generate) box
// fragments for a wrapped line, it should consistently do so for other lines
// too, when the inline box is fragmented to multiple lines.
@@ -177,6 +219,7 @@ TEST_F(NGInlineLayoutAlgorithmTest, ContainerBorderPadding) {
div {
padding-left: 5px;
padding-top: 10px;
+ display: flow-root;
}
</style>
<div id=container>test</div>
@@ -188,8 +231,7 @@ TEST_F(NGInlineLayoutAlgorithmTest, ContainerBorderPadding) {
NGConstraintSpace::CreateFromLayoutObject(*block_flow);
scoped_refptr<NGLayoutResult> layout_result = block_node.Layout(space);
- auto* block_box =
- ToNGPhysicalBoxFragment(layout_result->PhysicalFragment().get());
+ auto* block_box = ToNGPhysicalBoxFragment(layout_result->PhysicalFragment());
EXPECT_TRUE(layout_result->BfcBlockOffset().has_value());
EXPECT_EQ(0, layout_result->BfcBlockOffset().value());
EXPECT_EQ(0, layout_result->BfcLineOffset());
@@ -223,8 +265,7 @@ TEST_F(NGInlineLayoutAlgorithmTest, MAYBE_VerticalAlignBottomReplaced) {
scoped_refptr<NGLayoutResult> layout_result =
inline_node.Layout(space, nullptr, &context);
- auto* line =
- ToNGPhysicalLineBoxFragment(layout_result->PhysicalFragment().get());
+ auto* line = ToNGPhysicalLineBoxFragment(layout_result->PhysicalFragment());
EXPECT_EQ(LayoutUnit(96), line->Size().height);
NGPhysicalOffset img_offset = line->Children()[0].Offset();
EXPECT_EQ(LayoutUnit(0), img_offset.top);
@@ -441,6 +482,7 @@ TEST_F(NGInlineLayoutAlgorithmTest, InkOverflow) {
<style>
#container {
font: 20px/.5 Ahem;
+ display: flow-root;
}
</style>
<div id="container">Hello</div>
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
index 24322a11fad..a9ee04102d0 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
@@ -29,10 +30,12 @@
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/run_segmenter.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
namespace blink {
@@ -74,8 +77,8 @@ void ClearNeedsLayout(LayoutObject* object) {
// Reset previous items if they cannot be reused to prevent stale items
// for subsequent layouts. Items that can be reused have already been
// added to the builder.
- if (object->IsLayoutNGText())
- ToLayoutNGText(object)->ClearInlineItems();
+ if (object->IsText())
+ ToLayoutText(object)->ClearInlineItems();
}
// The function is templated to indicate the purpose of collected inlines:
@@ -108,11 +111,8 @@ void CollectInlinesInternal(
// if the last ended with space and this starts with space, do not allow
// reuse. builder->MightCollapseWithPreceding(*previous_text)
bool item_reused = false;
- if (node->IsLayoutNGText() && ToLayoutNGText(node)->HasValidLayout() &&
- previous_text) {
- item_reused = builder->Append(*previous_text, ToLayoutNGText(node),
- ToLayoutNGText(node)->InlineItems());
- }
+ if (previous_text && layout_text->HasValidInlineItems())
+ item_reused = builder->Append(*previous_text, layout_text);
// If not create a new item as needed.
if (!item_reused) {
@@ -160,20 +160,23 @@ void CollectInlinesInternal(
// should not appear. LayoutObject tree should have created an anonymous
// box to prevent having inline/block-mixed children.
DCHECK(node->IsInline());
+ LayoutInline* layout_inline = ToLayoutInline(node);
+ if (update_layout)
+ layout_inline->UpdateShouldCreateBoxFragment();
- builder->EnterInline(node);
+ builder->EnterInline(layout_inline);
// Traverse to children if they exist.
- if (LayoutObject* child = node->SlowFirstChild()) {
+ if (LayoutObject* child = layout_inline->FirstChild()) {
node = child;
continue;
}
// An empty inline node.
- builder->ExitInline(node);
+ builder->ExitInline(layout_inline);
if (update_layout)
- ClearNeedsLayout(node);
+ ClearNeedsLayout(layout_inline);
}
// Find the next sibling, or parent, until we reach |block|.
@@ -284,32 +287,72 @@ const NGOffsetMapping* NGInlineNode::ComputeOffsetMappingIfNeeded() {
NGInlineNodeData* data = MutableData();
if (!data->offset_mapping) {
- // TODO(xiaochengh): ComputeOffsetMappingIfNeeded() discards the
- // NGInlineItems and text content built by |builder|, because they are
- // already there in NGInlineNodeData. For efficiency, we should make
- // |builder| not construct items and text content.
- Vector<NGInlineItem> items;
- items.ReserveCapacity(EstimateInlineItemsCount(*GetLayoutBlockFlow()));
- NGInlineItemsBuilderForOffsetMapping builder(&items);
- builder.GetOffsetMappingBuilder().ReserveCapacity(
- EstimateOffsetMappingItemsCount(*GetLayoutBlockFlow()));
- const bool update_layout = false;
- CollectInlinesInternal(GetLayoutBlockFlow(), &builder, nullptr,
- update_layout);
- String text = builder.ToString();
- DCHECK_EQ(data->text_content, text);
-
- // TODO(xiaochengh): This doesn't compute offset mapping correctly when
- // text-transform CSS property changes text length.
- NGOffsetMappingBuilder& mapping_builder = builder.GetOffsetMappingBuilder();
- mapping_builder.SetDestinationString(data->text_content);
- data->offset_mapping =
- std::make_unique<NGOffsetMapping>(mapping_builder.Build());
+ DCHECK(!data->text_content.IsNull());
+ ComputeOffsetMapping(GetLayoutBlockFlow(), data);
+ DCHECK(data->offset_mapping);
}
return data->offset_mapping.get();
}
+void NGInlineNode::ComputeOffsetMapping(LayoutBlockFlow* layout_block_flow,
+ NGInlineNodeData* data) {
+ DCHECK(!data->offset_mapping);
+ DCHECK(!layout_block_flow->GetDocument().NeedsLayoutTreeUpdate());
+
+ // TODO(xiaochengh): ComputeOffsetMappingIfNeeded() discards the
+ // NGInlineItems and text content built by |builder|, because they are
+ // already there in NGInlineNodeData. For efficiency, we should make
+ // |builder| not construct items and text content.
+ Vector<NGInlineItem> items;
+ items.ReserveCapacity(EstimateInlineItemsCount(*layout_block_flow));
+ NGInlineItemsBuilderForOffsetMapping builder(&items);
+ builder.GetOffsetMappingBuilder().ReserveCapacity(
+ EstimateOffsetMappingItemsCount(*layout_block_flow));
+ const bool update_layout = false;
+ CollectInlinesInternal(layout_block_flow, &builder, nullptr, update_layout);
+
+ // We need the text for non-NG object. Otherwise |data| already has the text
+ // from the pre-layout phase, check they match.
+ if (data->text_content.IsNull())
+ data->text_content = builder.ToString();
+ else
+ DCHECK_EQ(data->text_content, builder.ToString());
+
+ // TODO(xiaochengh): This doesn't compute offset mapping correctly when
+ // text-transform CSS property changes text length.
+ NGOffsetMappingBuilder& mapping_builder = builder.GetOffsetMappingBuilder();
+ mapping_builder.SetDestinationString(data->text_content);
+ data->offset_mapping =
+ std::make_unique<NGOffsetMapping>(mapping_builder.Build());
+ DCHECK(data->offset_mapping);
+}
+
+const NGOffsetMapping* NGInlineNode::GetOffsetMapping(
+ LayoutBlockFlow* layout_block_flow,
+ std::unique_ptr<NGOffsetMapping>* storage) {
+ DCHECK(!layout_block_flow->GetDocument().NeedsLayoutTreeUpdate());
+
+ // If |layout_block_flow| is LayoutNG, compute from |NGInlineNode|.
+ if (layout_block_flow->IsLayoutNGMixin()) {
+ NGInlineNode node(layout_block_flow);
+ if (node.IsPrepareLayoutFinished())
+ return node.ComputeOffsetMappingIfNeeded();
+
+ // When this is not laid out yet, compute each time it is requested.
+ // TODO(kojii): We could still keep the result for later uses but it would
+ // add more states. Reconsider if this turned out to be needed.
+ }
+
+ // If this is not LayoutNG, compute the offset mapping and store in |storage|.
+ // The caller is responsible to keep |storage| for the life cycle.
+ NGInlineNodeData data;
+ ComputeOffsetMapping(layout_block_flow, &data);
+ *storage = std::move(data.offset_mapping);
+ DCHECK(*storage);
+ return storage->get();
+}
+
// Depth-first-scan of all LayoutInline and LayoutText nodes that make up this
// NGInlineNode object. Collects LayoutText items, merging them up into the
// parent LayoutInline where possible, and joining all text content in a single
@@ -504,9 +547,9 @@ void NGInlineNode::ShapeText(const String& text_content,
if (previous_text && end_offset == start_item.EndOffset() &&
!NeedsShaping(start_item)) {
DCHECK_EQ(start_item.StartOffset(),
- start_item.TextShapeResult()->StartIndexForResult());
+ start_item.TextShapeResult()->StartIndex());
DCHECK_EQ(start_item.EndOffset(),
- start_item.TextShapeResult()->EndIndexForResult());
+ start_item.TextShapeResult()->EndIndex());
index++;
continue;
}
@@ -554,6 +597,7 @@ void NGInlineNode::ShapeText(const String& text_content,
// If the text is from multiple items, split the ShapeResult to
// corresponding items.
+ unsigned opaque_context = 0;
for (; index < end_index; index++) {
NGInlineItem& item = (*items)[index];
if (item.Type() != NGInlineItem::kText)
@@ -565,8 +609,8 @@ void NGInlineNode::ShapeText(const String& text_content,
//
// When multiple code units shape to one glyph, such as ligatures, the
// item that has its first code unit keeps the glyph.
- item.shape_result_ =
- shape_result->SubRange(item.StartOffset(), item.EndOffset());
+ item.shape_result_ = shape_result->SubRange(
+ item.StartOffset(), item.EndOffset(), &opaque_context);
}
}
}
@@ -622,7 +666,7 @@ void NGInlineNode::ShapeTextForFirstLineIfNeeded(NGInlineNodeData* data) {
item.layout_object_->IsLayoutInline() &&
item.layout_object_->Parent() == GetLayoutBox() &&
ToLayoutInline(item.layout_object_)->IsFirstLineAnonymous()) {
- item.should_create_box_fragment_ = true;
+ item.SetShouldCreateBoxFragment();
}
break;
}
@@ -641,8 +685,10 @@ void NGInlineNode::AssociateItemsWithInlines(NGInlineNodeData* data) {
LayoutObject* last_object = nullptr;
for (auto& item : data->items) {
LayoutObject* object = item.GetLayoutObject();
- if (object && object->IsLayoutNGText()) {
- LayoutNGText* layout_text = ToLayoutNGText(object);
+ if (!object)
+ continue;
+ if (object->IsText()) {
+ LayoutText* layout_text = ToLayoutText(object);
if (object != last_object)
layout_text->ClearInlineItems();
layout_text->AddInlineItem(&item);
@@ -693,6 +739,120 @@ scoped_refptr<NGLayoutResult> NGInlineNode::Layout(
return algorithm.Layout();
}
+bool NGInlineNode::PrepareReuseFragments(
+ const NGConstraintSpace& constraint_space) {
+ if (!IsPrepareLayoutFinished())
+ return false;
+
+ LayoutBlockFlow* block_flow = GetLayoutBlockFlow();
+ if (!block_flow->EverHadLayout())
+ return false;
+
+ // If the block flow itself was changed, re-layout may be needed.
+ if (block_flow->SelfNeedsLayout())
+ return false;
+
+ // Check the cached result is valid for the constraint space.
+ if (!block_flow->AreCachedLinesValidFor(constraint_space))
+ return false;
+
+ if (!MarkLineBoxesDirty(block_flow))
+ return false;
+
+ PrepareLayoutIfNeeded();
+
+ return true;
+}
+
+// Mark the first line box that have |NeedsLayout()| dirty.
+//
+// Removals of LayoutObject already marks relevant line boxes dirty by calling
+// |DirtyLinesFromChangedChild()|, but insertions and style changes are not
+// marked yet.
+bool NGInlineNode::MarkLineBoxesDirty(LayoutBlockFlow* block_flow) {
+ DCHECK(block_flow);
+ DCHECK(block_flow->PaintFragment());
+ bool has_dirtied_lines = false;
+ NGPaintFragment* last_fragment = nullptr;
+ for (LayoutObject* layout_object = block_flow->NextInPreOrder(block_flow);
+ layout_object;) {
+ bool should_dirty_lines = false;
+ NGPaintFragment* fragment = nullptr;
+ LayoutObject* next = nullptr;
+ if (LayoutText* layout_text = ToLayoutTextOrNull(layout_object)) {
+ if (!has_dirtied_lines) {
+ should_dirty_lines = layout_object->SelfNeedsLayout();
+ if (!should_dirty_lines)
+ fragment = layout_text->FirstInlineFragment();
+ }
+ next = layout_object->NextInPreOrderAfterChildren(block_flow);
+ layout_object->ClearNeedsLayout();
+ } else if (LayoutInline* layout_inline =
+ ToLayoutInlineOrNull(layout_object)) {
+ if (!has_dirtied_lines) {
+ should_dirty_lines = layout_object->SelfNeedsLayout();
+ // Do not keep fragments of LayoutInline unless it's a leaf, because
+ // the last fragment of LayoutInline is not the previous fragment of its
+ // descendants.
+ if (!should_dirty_lines && !layout_inline->FirstChild())
+ fragment = layout_inline->FirstInlineFragment();
+ }
+ next = layout_object->NextInPreOrder(block_flow);
+ layout_object->ClearNeedsLayout();
+ } else if (UNLIKELY(layout_object->IsFloatingOrOutOfFlowPositioned())) {
+ // Aborting in the middle of the traversal is safe because this function
+ // ClearNeedsLayout() on text and LayoutInline, but since an inline
+ // formatting context is laid out as a whole, these flags don't matter.
+ // For that reason, this traversal should not ClearNeedsLayout() atomic
+ // inlines, floats, or OOF -- objects that need to be laid out separately
+ // from the inline formatting context.
+ // TODO(kojii): This looks a bit tricky, better to come up with clearner
+ // solution if any.
+ return false;
+ } else if (layout_object->IsAtomicInlineLevel()) {
+ if (!has_dirtied_lines) {
+ should_dirty_lines = layout_object->NeedsLayout();
+ if (!should_dirty_lines)
+ fragment = layout_object->FirstInlineFragment();
+ }
+ next = layout_object->NextInPreOrderAfterChildren(block_flow);
+ } else {
+ NOTREACHED();
+ // With LayoutNGBlockFragmentation, LayoutFlowThread/LayoutMultiColumnSet
+ // appear in fast/multicol/paged-becomes-multicol-auto-height.html.
+ // crbug.com/897141
+ next = layout_object->NextInPreOrder(block_flow);
+ }
+
+ if (!has_dirtied_lines) {
+ if (should_dirty_lines) {
+ if (last_fragment) {
+ // Changes in this LayoutObject may affect the line that contains its
+ // previous object. Mark the line box that contains the last fragment
+ // of the previous object.
+ last_fragment->LastForSameLayoutObject()
+ ->MarkContainingLineBoxDirty();
+ } else {
+ // If there were no fragments so far in this pre-order traversal, mark
+ // the first line box dirty.
+ NGPaintFragment* block_fragment = block_flow->PaintFragment();
+ DCHECK(block_fragment);
+ if (NGPaintFragment* first_line = block_fragment->FirstLineBox())
+ first_line->MarkLineBoxDirty();
+ }
+ has_dirtied_lines = true;
+ } else if (fragment) {
+ last_fragment = fragment;
+ }
+ }
+
+ ClearInlineFragment(layout_object);
+ layout_object = next;
+ }
+ block_flow->ClearNeedsLayout();
+ return true;
+}
+
static LayoutUnit ComputeContentSize(
NGInlineNode node,
WritingMode container_writing_mode,
@@ -704,20 +864,14 @@ static LayoutUnit ComputeContentSize(
LayoutUnit available_inline_size =
mode == NGLineBreakerMode::kMaxContent ? LayoutUnit::Max() : LayoutUnit();
- NGPhysicalSize icb_size = constraint_space
- ? constraint_space->InitialContainingBlockSize()
- : node.InitialContainingBlockSize();
- DCHECK(!constraint_space || constraint_space->InitialContainingBlockSize() ==
- node.InitialContainingBlockSize())
- << constraint_space->InitialContainingBlockSize() << " vs "
- << node.InitialContainingBlockSize();
-
NGConstraintSpace space =
- NGConstraintSpaceBuilder(writing_mode, icb_size)
+ NGConstraintSpaceBuilder(/* parent_writing_mode */ writing_mode,
+ /* out_writing_mode */ writing_mode,
+ /* is_new_fc */ false)
.SetTextDirection(style.Direction())
.SetAvailableSize({available_inline_size, NGSizeIndefinite})
.SetIsIntermediateLayout(true)
- .ToConstraintSpace(writing_mode);
+ .ToConstraintSpace();
Vector<NGPositionedFloat> positioned_floats;
NGUnpositionedFloatVector unpositioned_floats;
@@ -733,7 +887,7 @@ static LayoutUnit ComputeContentSize(
nullptr /* container_builder */, &empty_exclusion_space, 0u,
line_opportunity, nullptr /* break_token */);
do {
- unpositioned_floats.clear();
+ unpositioned_floats.Shrink(0);
NGLineInfo line_info;
line_breaker.NextLine(&line_info);
@@ -761,27 +915,15 @@ static LayoutUnit ComputeContentSize(
const ComputedStyle& float_style = float_node.Style();
MinMaxSizeInput zero_input; // Floats don't intrude into floats.
- // We'll need extrinsic sizing data when computing min/max for orthogonal
- // flow roots.
- NGConstraintSpace extrinsic_constraint_space;
- const NGConstraintSpace* optional_constraint_space = nullptr;
- if (!IsParallelWritingMode(container_writing_mode,
- float_node.Style().GetWritingMode())) {
- DCHECK(constraint_space);
- extrinsic_constraint_space = CreateExtrinsicConstraintSpaceForChild(
- *constraint_space, input.extrinsic_block_size, float_node);
- optional_constraint_space = &extrinsic_constraint_space;
- }
-
- MinMaxSize child_sizes = ComputeMinAndMaxContentContribution(
- writing_mode, float_node, zero_input, optional_constraint_space);
+ MinMaxSize child_sizes =
+ ComputeMinAndMaxContentContribution(style, float_node, zero_input);
LayoutUnit child_inline_margins =
ComputeMinMaxMargins(style, float_node).InlineSum();
if (mode == NGLineBreakerMode::kMinContent) {
result = std::max(result, child_sizes.min_size + child_inline_margins);
} else {
- const EClear float_clear = float_style.Clear();
+ const EClear float_clear = ResolvedClear(float_style, style);
// If this float clears the previous float we start a new "line".
// This is subtly different to block layout which will only reset either
@@ -798,7 +940,7 @@ static LayoutUnit ComputeContentSize(
// such float should not affect the content size.
floats_inline_size +=
(child_sizes.max_size + child_inline_margins).ClampNegativeToZero();
- previous_float_type = float_style.Floating();
+ previous_float_type = ResolvedFloating(float_style, style);
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h
index 57c0776bbd9..1e38711ccd3 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h
@@ -45,6 +45,9 @@ class CORE_EXPORT NGInlineNode : public NGLayoutInputNode {
const NGBreakToken*,
NGInlineChildLayoutContext* context);
+ // Prepare to reuse fragments. Returns false if reuse is not possible.
+ bool PrepareReuseFragments(const NGConstraintSpace&);
+
// Computes the value of min-content and max-content for this anonymous block
// box. min-content is the inline size when lines wrap at every break
// opportunity, and max-content is when lines do not wrap at all.
@@ -67,6 +70,17 @@ class CORE_EXPORT NGInlineNode : public NGLayoutInputNode {
// This funciton must be called with clean layout.
const NGOffsetMapping* ComputeOffsetMappingIfNeeded();
+ // Get |NGOffsetMapping| for the |layout_block_flow|. If |layout_block_flow|
+ // is LayoutNG and it is already laid out, this function is the same as
+ // |ComputeOffsetMappingIfNeeded|. |storage| is not used in this case.
+ //
+ // Otherwise, this function computes |NGOffsetMapping| and store in |storage|
+ // as well as returning the pointer. The caller is responsible for keeping
+ // |storage| for the life cycle of the returned |NGOffsetMapping|.
+ static const NGOffsetMapping* GetOffsetMapping(
+ LayoutBlockFlow* layout_block_flow,
+ std::unique_ptr<NGOffsetMapping>* storage);
+
bool IsBidiEnabled() const { return Data().is_bidi_enabled_; }
TextDirection BaseDirection() const { return Data().BaseDirection(); }
@@ -106,6 +120,8 @@ class CORE_EXPORT NGInlineNode : public NGLayoutInputNode {
void ClearAssociatedFragments(const NGInlineBreakToken*);
+ bool MarkLineBoxesDirty(LayoutBlockFlow*);
+
NGInlineNodeData* MutableData() {
return ToLayoutBlockFlow(box_)->GetNGInlineNodeData();
}
@@ -116,6 +132,9 @@ class CORE_EXPORT NGInlineNode : public NGLayoutInputNode {
}
const NGInlineNodeData& EnsureData();
+ static void ComputeOffsetMapping(LayoutBlockFlow* layout_block_flow,
+ NGInlineNodeData* data);
+
friend class NGLineBreakerTest;
friend class NGInlineNodeLegacy;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc
index d095df4757c..788aecf9934 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc
@@ -16,6 +16,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_test.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
@@ -67,6 +68,10 @@ class NGInlineNodeForTest : public NGInlineNode {
void CollectInlines() { NGInlineNode::CollectInlines(MutableData()); }
void ShapeText() { NGInlineNode::ShapeText(MutableData()); }
+
+ bool MarkLineBoxesDirty() {
+ return NGInlineNode::MarkLineBoxesDirty(GetLayoutBlockFlow());
+ }
};
class NGInlineNodeTest : public NGLayoutTest {
@@ -102,12 +107,12 @@ class NGInlineNodeTest : public NGLayoutTest {
void CreateLine(
NGInlineNode node,
Vector<scoped_refptr<const NGPhysicalTextFragment>>* fragments_out) {
- NGPhysicalSize icb_size(LayoutUnit(200), LayoutUnit(200));
-
NGConstraintSpace constraint_space =
- NGConstraintSpaceBuilder(WritingMode::kHorizontalTb, icb_size)
+ NGConstraintSpaceBuilder(WritingMode::kHorizontalTb,
+ WritingMode::kHorizontalTb,
+ /* is_new_fc */ false)
.SetAvailableSize({LayoutUnit::Max(), LayoutUnit(-1)})
- .ToConstraintSpace(WritingMode::kHorizontalTb);
+ .ToConstraintSpace();
NGInlineChildLayoutContext context;
scoped_refptr<NGLayoutResult> result =
NGInlineLayoutAlgorithm(node, constraint_space,
@@ -115,7 +120,7 @@ class NGInlineNodeTest : public NGLayoutTest {
.Layout();
const NGPhysicalLineBoxFragment* line =
- ToNGPhysicalLineBoxFragment(result->PhysicalFragment().get());
+ ToNGPhysicalLineBoxFragment(result->PhysicalFragment());
for (const auto& child : line->Children()) {
fragments_out->push_back(ToNGPhysicalTextFragment(child.get()));
}
@@ -127,6 +132,24 @@ class NGInlineNodeTest : public NGLayoutTest {
return data->text_content;
}
+ // Mark line boxes dirty and returns child paint fragments of
+ // |layout_block_flow_|.
+ Vector<NGPaintFragment*, 16> MarkLineBoxesDirty() const {
+ // Attach new LayoutObjects if there were any, but do not run layout,
+ // because running layout will re-create fragments.
+ GetDocument().UpdateStyleAndLayoutTree();
+
+ NGInlineNodeForTest node(layout_block_flow_);
+ EXPECT_TRUE(node.MarkLineBoxesDirty());
+
+ scoped_refptr<const NGPaintFragment> fragment =
+ layout_block_flow_->PaintFragment();
+ EXPECT_TRUE(fragment);
+ Vector<NGPaintFragment*, 16> children;
+ fragment->Children().ToList(&children);
+ return children;
+ }
+
Vector<NGInlineItem>& Items() {
NGInlineNodeData* data = layout_block_flow_->GetNGInlineNodeData();
CHECK(data);
@@ -467,13 +490,26 @@ TEST_F(NGInlineNodeTest, MinMaxSizeFloatsClearance) {
EXPECT_EQ(160, sizes.max_size);
}
+TEST_F(NGInlineNodeTest, AssociatedItemsWithControlItem) {
+ SetBodyInnerHTML(
+ "<pre id=t style='-webkit-rtl-ordering:visual'>ab\nde</pre>");
+ LayoutText* const layout_text = ToLayoutText(
+ GetDocument().getElementById("t")->firstChild()->GetLayoutObject());
+ ASSERT_TRUE(layout_text->HasValidInlineItems());
+ const Vector<NGInlineItem*>& items = layout_text->InlineItems();
+ ASSERT_EQ(3u, items.size());
+ TEST_ITEM_TYPE_OFFSET((*items[0]), kText, 1u, 3u);
+ TEST_ITEM_TYPE_OFFSET((*items[1]), kControl, 4u, 5u);
+ TEST_ITEM_TYPE_OFFSET((*items[2]), kText, 6u, 8u);
+}
+
TEST_F(NGInlineNodeTest, InvalidateAddSpan) {
SetupHtml("t", "<div id=t>before</div>");
EXPECT_FALSE(layout_block_flow_->NeedsCollectInlines());
unsigned item_count_before = Items().size();
Element* parent = ToElement(layout_block_flow_->GetNode());
- Element* span = GetDocument().CreateRawElement(HTMLNames::spanTag);
+ Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
// NeedsCollectInlines() is marked during the layout.
@@ -499,7 +535,7 @@ TEST_F(NGInlineNodeTest, InvalidateAddInnerSpan) {
Element* parent = GetElementById("x");
ASSERT_TRUE(parent);
- Element* span = GetDocument().CreateRawElement(HTMLNames::spanTag);
+ Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
// NeedsCollectInlines() is marked during the layout.
@@ -544,7 +580,7 @@ TEST_F(NGInlineNodeTest, InvalidateAddAbsolute) {
unsigned item_count_before = Items().size();
Element* parent = ToElement(layout_block_flow_->GetNode());
- Element* span = GetDocument().CreateRawElement(HTMLNames::spanTag);
+ Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
// NeedsCollectInlines() is marked during the layout.
@@ -609,7 +645,7 @@ TEST_F(NGInlineNodeTest, InvalidateAddFloat) {
unsigned item_count_before = Items().size();
Element* parent = ToElement(layout_block_flow_->GetNode());
- Element* span = GetDocument().CreateRawElement(HTMLNames::spanTag);
+ Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
// NeedsCollectInlines() is marked during the layout.
@@ -645,4 +681,187 @@ TEST_F(NGInlineNodeTest, SpaceRestoredByInsertingWord) {
EXPECT_EQ(String("before mid after"), GetText());
}
+// Test marking line boxes when inserting a span before the first child.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnInsert) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 12345678
+ </div>
+ )HTML");
+
+ Element* span = GetDocument().CreateElementForBinding("span");
+ Element* container = GetElementById("container");
+ container->insertBefore(span, container->firstChild());
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+// Test marking line boxes when appending a span.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnAppend) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 12345678
+ </div>
+ )HTML");
+
+ Element* span = GetDocument().CreateElementForBinding("span");
+ layout_block_flow_->GetNode()->appendChild(span);
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+// Test marking line boxes when appending a span on 2nd line.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnAppend2) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 12345678
+ 2234
+ </div>
+ )HTML");
+
+ Element* span = GetDocument().CreateElementForBinding("span");
+ layout_block_flow_->GetNode()->appendChild(span);
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_FALSE(lines[0]->IsDirty());
+ EXPECT_TRUE(lines[1]->IsDirty());
+}
+
+// Test marking line boxes when removing a span.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnRemove) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 1234<span id=t>5678</span>
+ </div>
+ )HTML");
+
+ Element* span = GetElementById("t");
+ span->remove();
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+// Test marking line boxes when removing a span.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnRemoveFirst) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ <span id=t>1234</span>5678
+ </div>
+ )HTML");
+
+ Element* span = GetElementById("t");
+ span->remove();
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+// Test marking line boxes when removing a span on 2nd line.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnRemove2) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 12345678
+ 2234<span id=t>5678 3334</span>
+ </div>
+ )HTML");
+
+ Element* span = GetElementById("t");
+ span->remove();
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_FALSE(lines[0]->IsDirty());
+ EXPECT_TRUE(lines[1]->IsDirty());
+}
+
+// Test marking line boxes when the first span has NeedsLayout. The span is
+// culled.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnNeedsLayoutFirst) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ <span id=t>1234</span>5678
+ </div>
+ )HTML");
+
+ LayoutObject* span = GetLayoutObjectByElementId("t");
+ span->SetNeedsLayout("");
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+// Test marking line boxes when the first span has NeedsLayout. The span has a
+// box fragment.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnNeedsLayoutFirstWithBox) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ <span id=t style="background: blue">1234</span>5678
+ </div>
+ )HTML");
+
+ LayoutObject* span = GetLayoutObjectByElementId("t");
+ span->SetNeedsLayout("");
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+// Test marking line boxes when a span has NeedsLayout. The span is culled.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnNeedsLayout) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 12345678
+ 2234<span id=t>5678 3334</span>
+ </div>
+ )HTML");
+
+ LayoutObject* span = GetLayoutObjectByElementId("t");
+ span->SetNeedsLayout("");
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_FALSE(lines[0]->IsDirty());
+ EXPECT_TRUE(lines[1]->IsDirty());
+}
+
+// Test marking line boxes when a span has NeedsLayout. The span has a box
+// fragment.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnNeedsLayoutWithBox) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px; width: 10ch">
+ 12345678
+ 2234<span id=t style="background: blue">5678 3334</span>
+ </div>
+ )HTML");
+
+ LayoutObject* span = GetLayoutObjectByElementId("t");
+ span->SetNeedsLayout("");
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_FALSE(lines[0]->IsDirty());
+ EXPECT_TRUE(lines[1]->IsDirty());
+}
+
+// Test marking line boxes when a span inside a span has NeedsLayout.
+// The parent span has a box fragment, and wraps, so that its fragment
+// is seen earlier in pre-order DFS.
+TEST_F(NGInlineNodeTest, MarkLineBoxesDirtyOnChildOfWrappedBox) {
+ SetupHtml("container", R"HTML(
+ <div id=container style="font-size: 10px">
+ <span style="background: yellow">
+ <span id=t>target</span>
+ <br>
+ 12345678
+ </span>
+ </div>
+ )HTML");
+
+ LayoutObject* span = GetLayoutObjectByElementId("t");
+ span->SetNeedsLayout("");
+
+ auto lines = MarkLineBoxesDirty();
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.cc
index b9a2451e7df..d70c22a17f3 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.cc
@@ -14,32 +14,16 @@
namespace blink {
-NGLineBoxFragmentBuilder::NGLineBoxFragmentBuilder(
- NGInlineNode node,
- scoped_refptr<const ComputedStyle> style,
- WritingMode writing_mode,
- TextDirection)
- : NGContainerFragmentBuilder(style, writing_mode, TextDirection::kLtr),
- node_(node),
- base_direction_(TextDirection::kLtr) {}
-
-NGLineBoxFragmentBuilder::~NGLineBoxFragmentBuilder() = default;
-
void NGLineBoxFragmentBuilder::Reset() {
- children_.clear();
- offsets_.clear();
+ children_.resize(0);
+ offsets_.resize(0);
+ line_box_type_ = NGPhysicalLineBoxFragment::kNormalLineBox;
metrics_ = NGLineHeightMetrics();
size_.inline_size = LayoutUnit();
}
-LayoutUnit NGLineBoxFragmentBuilder::LineHeight() const {
- return metrics_.LineHeight().ClampNegativeToZero();
-}
-
-const NGPhysicalFragment* NGLineBoxFragmentBuilder::Child::PhysicalFragment()
- const {
- return layout_result ? layout_result->PhysicalFragment().get()
- : fragment.get();
+void NGLineBoxFragmentBuilder::SetIsEmptyLineBox() {
+ line_box_type_ = NGPhysicalLineBoxFragment::kEmptyLineBox;
}
NGLineBoxFragmentBuilder::Child*
@@ -61,16 +45,6 @@ NGLineBoxFragmentBuilder::ChildList::LastInFlowChild() {
return nullptr;
}
-void NGLineBoxFragmentBuilder::ChildList::InsertChild(
- unsigned index,
- scoped_refptr<NGLayoutResult> layout_result,
- const NGLogicalOffset& offset,
- LayoutUnit inline_size,
- UBiDiLevel bidi_level) {
- children_.insert(
- index, Child{std::move(layout_result), offset, inline_size, bidi_level});
-}
-
void NGLineBoxFragmentBuilder::ChildList::MoveInInlineDirection(
LayoutUnit delta,
unsigned start,
@@ -92,24 +66,6 @@ void NGLineBoxFragmentBuilder::ChildList::MoveInBlockDirection(LayoutUnit delta,
children_[index].offset.block_offset += delta;
}
-void NGLineBoxFragmentBuilder::SetMetrics(const NGLineHeightMetrics& metrics) {
- metrics_ = metrics;
-}
-
-void NGLineBoxFragmentBuilder::SetBaseDirection(TextDirection direction) {
- base_direction_ = direction;
-}
-
-void NGLineBoxFragmentBuilder::SwapPositionedFloats(
- Vector<NGPositionedFloat>* positioned_floats) {
- positioned_floats_.swap(*positioned_floats);
-}
-
-void NGLineBoxFragmentBuilder::SetBreakToken(
- scoped_refptr<NGInlineBreakToken> break_token) {
- break_token_ = std::move(break_token);
-}
-
void NGLineBoxFragmentBuilder::AddChildren(ChildList& children) {
offsets_.ReserveCapacity(children.size());
children_.ReserveCapacity(children.size());
@@ -127,39 +83,15 @@ void NGLineBoxFragmentBuilder::AddChildren(ChildList& children) {
}
scoped_refptr<NGLayoutResult> NGLineBoxFragmentBuilder::ToLineBoxFragment() {
- DCHECK_EQ(offsets_.size(), children_.size());
+ writing_mode_ = ToLineWritingMode(writing_mode_);
- WritingMode line_writing_mode(ToLineWritingMode(GetWritingMode()));
- NGPhysicalSize physical_size = Size().ConvertToPhysical(line_writing_mode);
-
- DCHECK_EQ(children_.size(), offsets_.size());
- for (size_t i = 0; i < children_.size(); i++) {
- auto& child = children_[i];
- child.offset_ = offsets_[i].ConvertToPhysical(
- line_writing_mode, Direction(), physical_size, child->Size());
- }
-
- // Because this vector will be long-lived, make sure to not waaste space.
- // (We reserve an initial capacity when adding the first child)
- if (children_.size())
- children_.ShrinkToReasonableCapacity();
+ if (!break_token_)
+ break_token_ = NGInlineBreakToken::Create(node_);
scoped_refptr<const NGPhysicalLineBoxFragment> fragment =
- base::AdoptRef(new NGPhysicalLineBoxFragment(
- Style(), style_variant_, physical_size, children_, metrics_,
- base_direction_,
- break_token_ ? std::move(break_token_)
- : NGInlineBreakToken::Create(node_)));
-
- return base::AdoptRef(new NGLayoutResult(
- std::move(fragment), std::move(oof_positioned_descendants_),
- std::move(positioned_floats_), unpositioned_list_marker_,
- std::move(exclusion_space_), bfc_line_offset_, bfc_block_offset_,
- end_margin_strut_,
- /* intrinsic_block_size */ LayoutUnit(),
- /* minimal_space_shortage */ LayoutUnit::Max(), EBreakBetween::kAuto,
- EBreakBetween::kAuto, /* has_forced_break */ false, is_pushed_by_floats_,
- adjoining_floats_, NGLayoutResult::kSuccess));
+ NGPhysicalLineBoxFragment::Create(this);
+
+ return base::AdoptRef(new NGLayoutResult(std::move(fragment), this));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h
index 39699703599..4e2cd3e3185 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h
@@ -6,10 +6,13 @@
#define NGLineBoxFragmentBuilder_h
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_offset.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -24,26 +27,40 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
STACK_ALLOCATED();
public:
- NGLineBoxFragmentBuilder(NGInlineNode,
- scoped_refptr<const ComputedStyle>,
- WritingMode,
- TextDirection);
- ~NGLineBoxFragmentBuilder() override;
+ NGLineBoxFragmentBuilder(NGInlineNode node,
+ scoped_refptr<const ComputedStyle> style,
+ WritingMode writing_mode,
+ TextDirection)
+ : NGContainerFragmentBuilder(style, writing_mode, TextDirection::kLtr),
+ node_(node),
+ line_box_type_(NGPhysicalLineBoxFragment::kNormalLineBox),
+ base_direction_(TextDirection::kLtr) {}
void Reset();
- LayoutUnit LineHeight() const;
+ LayoutUnit LineHeight() const {
+ return metrics_.LineHeight().ClampNegativeToZero();
+ }
+
+ // Mark this line box is an "empty" line box. See NGLineBoxType.
+ void SetIsEmptyLineBox();
const NGLineHeightMetrics& Metrics() const { return metrics_; }
- void SetMetrics(const NGLineHeightMetrics&);
+ void SetMetrics(const NGLineHeightMetrics& metrics) { metrics_ = metrics; }
- void SetBaseDirection(TextDirection);
+ void SetBaseDirection(TextDirection direction) {
+ base_direction_ = direction;
+ }
- void SwapPositionedFloats(Vector<NGPositionedFloat>*);
+ void SwapPositionedFloats(Vector<NGPositionedFloat>* positioned_floats) {
+ positioned_floats_.swap(*positioned_floats);
+ }
// Set the break token for the fragment to build.
// A finished break token will be attached if not set.
- void SetBreakToken(scoped_refptr<NGInlineBreakToken>);
+ void SetBreakToken(scoped_refptr<NGInlineBreakToken> break_token) {
+ break_token_ = std::move(break_token);
+ }
// A data struct to keep NGLayoutResult or fragment until the box tree
// structures and child offsets are finalized.
@@ -54,8 +71,14 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
scoped_refptr<const NGPhysicalFragment> fragment;
LayoutObject* out_of_flow_positioned_box = nullptr;
LayoutObject* out_of_flow_containing_box = nullptr;
+ // The offset of the border box, initially in this child coordinate system.
+ // |ComputeInlinePositions()| converts it to the offset within the line box.
NGLogicalOffset offset;
+ // The inline size of the margin box.
LayoutUnit inline_size;
+ LayoutUnit margin_line_left;
+ // The index of |box_data_list_|, used in |PrepareForReorder()| and
+ // |UpdateAfterReorder()| to track children of boxes across BiDi reorder.
unsigned box_data_index = 0;
UBiDiLevel bidi_level = 0xff;
@@ -108,7 +131,9 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
}
bool HasBidiLevel() const { return bidi_level != 0xff; }
bool IsPlaceholder() const { return !HasFragment() && !HasBidiLevel(); }
- const NGPhysicalFragment* PhysicalFragment() const;
+ const NGPhysicalFragment* PhysicalFragment() const {
+ return layout_result ? layout_result->PhysicalFragment() : fragment.get();
+ }
};
// A vector of Child.
@@ -123,15 +148,16 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
children_ = std::move(other.children_);
}
- Child& operator[](unsigned i) { return children_[i]; }
+ Child& operator[](wtf_size_t i) { return children_[i]; }
+ const Child& operator[](wtf_size_t i) const { return children_[i]; }
- unsigned size() const { return children_.size(); }
+ wtf_size_t size() const { return children_.size(); }
bool IsEmpty() const { return children_.IsEmpty(); }
void ReserveInitialCapacity(unsigned capacity) {
children_.ReserveInitialCapacity(capacity);
}
- void clear() { children_.clear(); }
- void resize(size_t size) { children_.resize(size); }
+ void clear() { children_.resize(0); }
+ void resize(wtf_size_t size) { children_.resize(size); }
using iterator = Vector<Child, 16>::iterator;
iterator begin() { return children_.begin(); }
@@ -154,11 +180,14 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
void AddChild(Args&&... args) {
children_.emplace_back(std::forward<Args>(args)...);
}
- void InsertChild(unsigned,
- scoped_refptr<NGLayoutResult>,
- const NGLogicalOffset&,
+ void InsertChild(unsigned index,
+ scoped_refptr<NGLayoutResult> layout_result,
+ const NGLogicalOffset& offset,
LayoutUnit inline_size,
- UBiDiLevel);
+ UBiDiLevel bidi_level) {
+ children_.insert(index, Child{std::move(layout_result), offset,
+ inline_size, bidi_level});
+ }
void MoveInInlineDirection(LayoutUnit, unsigned start, unsigned end);
void MoveInBlockDirection(LayoutUnit);
@@ -180,13 +209,18 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
NGLineHeightMetrics metrics_;
Vector<NGPositionedFloat> positioned_floats_;
- scoped_refptr<NGInlineBreakToken> break_token_;
-
+ NGPhysicalLineBoxFragment::NGLineBoxType line_box_type_;
TextDirection base_direction_;
+ friend class NGLayoutResult;
+ friend class NGPhysicalLineBoxFragment;
+
DISALLOW_COPY_AND_ASSIGN(NGLineBoxFragmentBuilder);
};
} // namespace blink
+WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(
+ blink::NGLineBoxFragmentBuilder::Child);
+
#endif // NGLineBoxFragmentBuilder
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc
index 4ff79b7653b..b35d9baa564 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h"
#include "third_party/blink/renderer/core/layout/layout_list_marker.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
@@ -17,6 +18,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h"
namespace blink {
@@ -134,7 +136,7 @@ void NGLineBreaker::ComputeBaseDirection() {
const String& text = Text();
if (text.Is8Bit())
return;
- size_t end_offset = text.find(kNewlineCharacter, offset_);
+ wtf_size_t end_offset = text.find(kNewlineCharacter, offset_);
base_direction_ = NGBidiParagraph::BaseDirectionForString(
end_offset == kNotFound
? StringView(text, offset_)
@@ -156,9 +158,20 @@ void NGLineBreaker::PrepareNextLine() {
}
line_info_->SetStartOffset(offset_);
- line_info_->SetLineStyle(node_, items_data_, constraint_space_,
- is_first_formatted_line_, use_first_line_style_,
- previous_line_had_forced_break_);
+ line_info_->SetLineStyle(node_, items_data_, use_first_line_style_);
+
+ DCHECK(!line_info_->TextIndent());
+ if (line_info_->LineStyle().ShouldUseTextIndent(
+ is_first_formatted_line_, previous_line_had_forced_break_)) {
+ const Length& length = line_info_->LineStyle().TextIndent();
+ LayoutUnit maximum_value;
+ // Ignore percentages (resolve to 0) when calculating min/max intrinsic
+ // sizes.
+ if (length.IsPercentOrCalc() && mode_ == NGLineBreakerMode::kContent)
+ maximum_value = constraint_space_.AvailableSize().inline_size;
+ line_info_->SetTextIndent(MinimumValueForLength(length, maximum_value));
+ }
+
// Set the initial style of this line from the break token. Example:
// <p>...<span>....</span></p>
// When the line wraps in <span>, the 2nd line needs to start with the style
@@ -314,9 +327,15 @@ void NGLineBreaker::HandleText(const NGInlineItem& item) {
DCHECK(item.TextShapeResult());
// If we're trailing, only trailing spaces can be included in this line.
- if (state_ == LineBreakState::kTrailing &&
- CanBreakAfterLast(*item_results_)) {
- return HandleTrailingSpaces(item);
+ if (state_ == LineBreakState::kTrailing) {
+ if (CanBreakAfterLast(*item_results_))
+ return HandleTrailingSpaces(item);
+ // When a run of preserved spaces are across items, |CanBreakAfterLast| is
+ // false for between spaces. But we still need to handle them as trailing
+ // spaces.
+ const String& text = Text();
+ if (offset_ < text.length() && text[offset_] == kSpaceCharacter)
+ return HandleTrailingSpaces(item);
}
// Skip leading collapsible spaces.
@@ -402,8 +421,8 @@ void NGLineBreaker::BreakText(NGInlineItemResult* item_result,
// has item-specific info as context. Should they be part of ShapeLine() to
// instantiate once, or is this just fine since instatiation is not
// expensive?
- DCHECK_EQ(item.TextShapeResult()->StartIndexForResult(), item.StartOffset());
- DCHECK_EQ(item.TextShapeResult()->EndIndexForResult(), item.EndOffset());
+ DCHECK_EQ(item.TextShapeResult()->StartIndex(), item.StartOffset());
+ DCHECK_EQ(item.TextShapeResult()->EndIndex(), item.EndOffset());
RunSegmenter::RunSegmenterRange segment_range =
item.CreateRunSegmenterRange();
ShapingLineBreaker breaker(&shaper_, &item.Style()->GetFont(),
@@ -424,7 +443,7 @@ void NGLineBreaker::BreakText(NGInlineItemResult* item_result,
if (break_anywhere_if_overflow_ && !override_break_anywhere_)
options |= ShapingLineBreaker::kNoResultIfOverflow;
ShapingLineBreaker::Result result;
- scoped_refptr<const ShapeResult> shape_result = breaker.ShapeLine(
+ scoped_refptr<const ShapeResultView> shape_result = breaker.ShapeLine(
item_result->start_offset, available_width, options, &result);
// If this item overflows and 'break-word' is set, this line will be
@@ -447,7 +466,9 @@ void NGLineBreaker::BreakText(NGInlineItemResult* item_result,
item_result->inline_size = shape_result->SnappedWidth().ClampNegativeToZero();
item_result->end_offset = result.break_offset;
item_result->shape_result = std::move(shape_result);
- DCHECK_GT(item_result->end_offset, item_result->start_offset);
+ // It is critical to move offset forward, or NGLineBreaker may keep adding
+ // NGInlineItemResult until all the memory is consumed.
+ CHECK_GT(item_result->end_offset, item_result->start_offset) << Text();
// * If width <= available_width:
// * If offset < item.EndOffset(): the break opportunity to fit is found.
@@ -482,33 +503,37 @@ scoped_refptr<ShapeResult> NGLineBreaker::ShapeText(const NGInlineItem& item,
// Compute a new ShapeResult for the specified end offset.
// The end is re-shaped if it is not safe-to-break.
-scoped_refptr<ShapeResult> NGLineBreaker::TruncateLineEndResult(
+scoped_refptr<ShapeResultView> NGLineBreaker::TruncateLineEndResult(
const NGInlineItemResult& item_result,
unsigned end_offset) {
DCHECK(item_result.item);
DCHECK(item_result.shape_result);
- const ShapeResult& source_result = *item_result.shape_result;
+ // TODO(layout-dev): Add support for subsetting a ShapeResultView thereby
+ // avoiding extra copy to create a new full ShapeResult here.
+ auto source_result = item_result.shape_result->CreateShapeResult();
const unsigned start_offset = item_result.start_offset;
- DCHECK_GE(start_offset, source_result.StartIndexForResult());
- DCHECK_LE(end_offset, source_result.EndIndexForResult());
- DCHECK(start_offset > source_result.StartIndexForResult() ||
- end_offset < source_result.EndIndexForResult());
+ DCHECK_GE(start_offset, source_result->StartIndex());
+ DCHECK_LE(end_offset, source_result->EndIndex());
+ DCHECK(start_offset > source_result->StartIndex() ||
+ end_offset < source_result->EndIndex());
+
+ ShapeResultView::Segment segments[2];
+ unsigned count = 0;
- scoped_refptr<ShapeResult> new_result;
- unsigned last_safe = source_result.PreviousSafeToBreakOffset(end_offset);
+ unsigned last_safe = source_result->PreviousSafeToBreakOffset(end_offset);
DCHECK_LE(last_safe, end_offset);
if (last_safe > start_offset)
- new_result = source_result.SubRange(start_offset, last_safe);
+ segments[count++] = {source_result.get(), start_offset, last_safe};
+
+ scoped_refptr<ShapeResult> end_result;
if (last_safe < end_offset) {
- scoped_refptr<ShapeResult> end_result = ShapeText(
- *item_result.item, std::max(last_safe, start_offset), end_offset);
- if (new_result)
- end_result->CopyRange(0, end_offset, new_result.get());
- else
- new_result = std::move(end_result);
+ end_result = ShapeText(*item_result.item, std::max(last_safe, start_offset),
+ end_offset);
+ segments[count++] = {end_result.get(), 0, end_offset};
+ DCHECK_EQ(end_result->Direction(), source_result->Direction());
}
- DCHECK(new_result);
- return new_result;
+ DCHECK_GE(count, 1u);
+ return ShapeResultView::Create(&segments[0], count);
}
// Update |ShapeResult| in |item_result| to match to its |start_offset| and
@@ -556,7 +581,8 @@ void NGLineBreaker::HandleTrailingSpaces(const NGInlineItem& item) {
NGInlineItemResult* item_result = AddItem(item, end);
item_result->has_only_trailing_spaces = true;
- item_result->shape_result = item.TextShapeResult();
+ item_result->shape_result =
+ ShapeResultView::Create(item.TextShapeResult().get());
if (item_result->start_offset == item.StartOffset() &&
item_result->end_offset == item.EndOffset())
item_result->inline_size = item_result->shape_result->SnappedWidth();
@@ -592,11 +618,11 @@ void NGLineBreaker::RemoveTrailingCollapsibleSpace() {
// We have a trailing collapsible space. Remove it.
NGInlineItemResult* item_result = trailing_collapsible_space_->item_result;
position_ -= item_result->inline_size;
- if (scoped_refptr<const ShapeResult>& collapsed_shape_result =
+ if (scoped_refptr<const ShapeResultView>& collapsed_shape_result =
trailing_collapsible_space_->collapsed_shape_result) {
DCHECK_GE(item_result->end_offset, item_result->start_offset + 2);
--item_result->end_offset;
- item_result->shape_result = std::move(collapsed_shape_result);
+ item_result->shape_result = collapsed_shape_result;
item_result->inline_size = item_result->shape_result->SnappedWidth();
position_ += item_result->inline_size;
} else {
@@ -617,7 +643,7 @@ LayoutUnit NGLineBreaker::TrailingCollapsibleSpaceWidth() {
// Normally, the width of new_reuslt is smaller, but technically it can be
// larger. In such case, it means the trailing spaces has negative width.
NGInlineItemResult* item_result = trailing_collapsible_space_->item_result;
- if (scoped_refptr<const ShapeResult>& collapsed_shape_result =
+ if (scoped_refptr<const ShapeResultView>& collapsed_shape_result =
trailing_collapsible_space_->collapsed_shape_result) {
return item_result->inline_size - collapsed_shape_result->SnappedWidth();
}
@@ -671,7 +697,8 @@ void NGLineBreaker::AppendHyphen(const NGInlineItem& item) {
shaper.Shape(&style.GetFont(), direction);
NGTextFragmentBuilder builder(node_, constraint_space_.GetWritingMode());
builder.SetText(item.GetLayoutObject(), hyphen_string, &style,
- /* is_ellipsis_style */ false, std::move(hyphen_result));
+ /* is_ellipsis_style */ false,
+ ShapeResultView::Create(hyphen_result.get()));
SetLineEndFragment(builder.ToTextFragment());
}
@@ -769,7 +796,7 @@ void NGLineBreaker::HandleAtomicInline(const NGInlineItem& item) {
if (mode_ == NGLineBreakerMode::kContent) {
item_result->layout_result =
NGBlockNode(ToLayoutBox(item.GetLayoutObject()))
- .LayoutAtomicInline(constraint_space_,
+ .LayoutAtomicInline(constraint_space_, node_.Style(),
line_info_->LineStyle().GetFontBaseline(),
line_info_->UseFirstLineStyle());
DCHECK(item_result->layout_result->PhysicalFragment());
@@ -779,11 +806,10 @@ void NGLineBreaker::HandleAtomicInline(const NGInlineItem& item) {
*item_result->layout_result->PhysicalFragment())
.InlineSize();
} else {
- NGBlockNode block_node(ToLayoutBox(item.GetLayoutObject()));
+ NGBlockNode child(ToLayoutBox(item.GetLayoutObject()));
MinMaxSizeInput input;
- MinMaxSize sizes = ComputeMinAndMaxContentContribution(
- constraint_space_.GetWritingMode(), block_node, input,
- &constraint_space_);
+ MinMaxSize sizes =
+ ComputeMinAndMaxContentContribution(node_.Style(), child, input);
item_result->inline_size = mode_ == NGLineBreakerMode::kMinContent
? sizes.min_size
: sizes.max_size;
@@ -846,13 +872,13 @@ void NGLineBreaker::HandleFloat(const NGInlineItem& item) {
// to the unpositioned floats list and abort.
if (mode_ != NGLineBreakerMode::kContent) {
AddUnpositionedFloat(unpositioned_floats_, container_builder_,
- std::move(unpositioned_float));
+ std::move(unpositioned_float), constraint_space_);
return;
}
LayoutUnit inline_margin_size =
- ComputeMarginBoxInlineSizeForUnpositionedFloat(constraint_space_,
- &unpositioned_float);
+ ComputeMarginBoxInlineSizeForUnpositionedFloat(
+ constraint_space_, node_.Style(), &unpositioned_float);
LayoutUnit bfc_block_offset = line_opportunity_.bfc_block_offset;
@@ -878,21 +904,23 @@ void NGLineBreaker::HandleFloat(const NGInlineItem& item) {
bool float_after_line =
!can_fit_float ||
exclusion_space_->LastFloatBlockStart() > bfc_block_offset ||
- exclusion_space_->ClearanceOffset(float_style.Clear()) > bfc_block_offset;
+ exclusion_space_->ClearanceOffset(
+ ResolvedClear(float_style.Clear(), constraint_space_.Direction())) >
+ bfc_block_offset;
// Check if we already have a pending float. That's because a float cannot be
// higher than any block or floated box generated before.
if (!unpositioned_floats_->IsEmpty() || float_after_line) {
AddUnpositionedFloat(unpositioned_floats_, container_builder_,
- std::move(unpositioned_float));
+ std::move(unpositioned_float), constraint_space_);
} else {
NGPositionedFloat positioned_float = PositionFloat(
constraint_space_.AvailableSize(),
constraint_space_.PercentageResolutionSize(),
constraint_space_.ReplacedPercentageResolutionSize(),
{constraint_space_.BfcOffset().line_offset, bfc_block_offset},
- constraint_space_.BfcOffset().block_offset, &unpositioned_float,
- constraint_space_, exclusion_space_);
+ &unpositioned_float, constraint_space_, node_.Style(),
+ exclusion_space_);
positioned_floats_->push_back(positioned_float);
NGLayoutOpportunity opportunity = exclusion_space_->FindLayoutOpportunity(
@@ -943,9 +971,7 @@ void NGLineBreaker::HandleOpenTag(const NGInlineItem& item) {
// line boxes to be zero-height, tests indicate that only inline direction
// of them do so. See should_create_line_box_.
// Force to create a box, because such inline boxes affect line heights.
- if (!item_result->should_create_line_box &&
- (item_result->inline_size ||
- (item_result->margins.inline_start && !in_line_height_quirks_mode_)))
+ if (!item_result->should_create_line_box && !item.IsEmptyItem())
item_result->should_create_line_box = true;
}
@@ -968,9 +994,7 @@ void NGLineBreaker::HandleCloseTag(const NGInlineItem& item) {
margins.inline_end + borders.inline_end + paddings.inline_end;
position_ += item_result->inline_size;
- if (!item_result->should_create_line_box &&
- (item_result->inline_size ||
- (margins.inline_end && !in_line_height_quirks_mode_)))
+ if (!item_result->should_create_line_box && !item.IsEmptyItem())
item_result->should_create_line_box = true;
}
DCHECK(item.GetLayoutObject() && item.GetLayoutObject()->Parent());
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h
index 9ccd74c3bd8..987037c1666 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h
@@ -98,7 +98,7 @@ class CORE_EXPORT NGLineBreaker {
const NGInlineItem&,
LayoutUnit available_width);
- scoped_refptr<ShapeResult> TruncateLineEndResult(
+ scoped_refptr<ShapeResultView> TruncateLineEndResult(
const NGInlineItemResult& item_result,
unsigned end_offset);
void UpdateShapeResult(NGInlineItemResult*);
@@ -212,7 +212,7 @@ class CORE_EXPORT NGLineBreaker {
// multiple times.
struct TrailingCollapsibleSpace {
NGInlineItemResult* item_result;
- scoped_refptr<const ShapeResult> collapsed_shape_result;
+ scoped_refptr<const ShapeResultView> collapsed_shape_result;
};
base::Optional<TrailingCollapsibleSpace> trailing_collapsible_space_;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc
index 6522f958568..53f11d1ac57 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc
@@ -8,10 +8,11 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h"
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -35,10 +36,10 @@ class NGLineBreakerTest : public NGBaseLayoutAlgorithmTest {
NGConstraintSpace space =
NGConstraintSpaceBuilder(
- WritingMode::kHorizontalTb,
- /* icb_size */ {NGSizeIndefinite, NGSizeIndefinite})
+ WritingMode::kHorizontalTb, WritingMode::kHorizontalTb,
+ /* is_new_fc */ false)
.SetAvailableSize({available_width, NGSizeIndefinite})
- .ToConstraintSpace(WritingMode::kHorizontalTb);
+ .ToConstraintSpace();
Vector<NGPositionedFloat> positioned_floats;
NGUnpositionedFloatVector unpositioned_floats;
@@ -209,6 +210,29 @@ TEST_F(NGLineBreakerTest, OverflowMargin) {
EXPECT_EQ("789", ToString(lines[2], node));
}
+TEST_F(NGLineBreakerTest, OverflowAfterSpacesAcrossElements) {
+ LoadAhem();
+ NGInlineNode node = CreateInlineNode(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ div {
+ font: 10px/1 Ahem;
+ white-space: pre-wrap;
+ width: 10ch;
+ word-wrap: break-word;
+ }
+ </style>
+ <div id=container><span>12345 </span> 1234567890123</div>
+ )HTML");
+
+ Vector<NGInlineItemResults> lines;
+ lines = BreakLines(node, LayoutUnit(100));
+ EXPECT_EQ(3u, lines.size());
+ EXPECT_EQ("12345 ", ToString(lines[0], node));
+ EXPECT_EQ("1234567890", ToString(lines[1], node));
+ EXPECT_EQ("123", ToString(lines[2], node));
+}
+
// Tests when the last word in a node wraps, and another node continues.
TEST_F(NGLineBreakerTest, WrapLastWord) {
LoadAhem();
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h
index 7289666f0c5..d8d9eba3f0f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h
@@ -6,7 +6,7 @@
#define NGLineHeightMetrics_h
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc
index 49df71cfc51..2301f6c98a2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc
@@ -6,8 +6,10 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
@@ -55,8 +57,8 @@ LayoutUnit NGLineTruncator::TruncateLine(
? String(&kHorizontalEllipsisCharacter, 1)
: String(u"...");
HarfBuzzShaper shaper(ellipsis_text);
- scoped_refptr<ShapeResult> ellipsis_shape_result =
- shaper.Shape(&font, line_direction_);
+ scoped_refptr<ShapeResultView> ellipsis_shape_result =
+ ShapeResultView::Create(shaper.Shape(&font, line_direction_).get());
LayoutUnit ellipsis_width = ellipsis_shape_result->SnappedWidth();
// Loop children from the logical last to the logical first to determine where
@@ -115,6 +117,24 @@ LayoutUnit NGLineTruncator::TruncateLine(
// Hide this child from being painted.
void NGLineTruncator::HideChild(NGLineBoxFragmentBuilder::Child* child) {
DCHECK(child->HasInFlowFragment());
+
+ // If this child has self painting layer, not producing fragments will not
+ // suppress painting because layers are painted separately. Move it out of the
+ // clipping area.
+ const NGPhysicalFragment* fragment = child->PhysicalFragment();
+ DCHECK(fragment);
+ if (const NGPhysicalBoxFragment* box_fragment =
+ ToNGPhysicalBoxFragmentOrNull(fragment)) {
+ if (box_fragment->HasSelfPaintingLayer()) {
+ // |avilable_width_| may not be enough when the contaning block has
+ // paddings, because clipping is at the content box but ellipsizing is at
+ // the padding box. Just move to the max because we don't know paddings,
+ // and max should do what we need.
+ child->offset.inline_offset = LayoutUnit::NearlyMax();
+ return;
+ }
+ }
+
// TODO(kojii): Not producing fragments is the most clean and efficient way to
// hide them, but we may want to revisit how to do this to reduce special
// casing in other code.
@@ -185,7 +205,10 @@ bool NGLineTruncator::TruncateChild(LayoutUnit space_for_child,
if (!child->fragment)
return is_first_child;
auto& fragment = ToNGPhysicalTextFragment(*child->fragment);
- const ShapeResult* shape_result = fragment.TextShapeResult();
+ // TODO(layout-dev): Add support for OffsetToFit to ShapeResultView to avoid
+ // this copy.
+ scoped_refptr<blink::ShapeResult> shape_result =
+ fragment.TextShapeResult()->CreateShapeResult();
if (!shape_result)
return is_first_child;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.cc
index 95d3b67e193..de77686df59 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.cc
@@ -54,7 +54,7 @@ std::pair<const Node&, unsigned> ToNodeOffsetPair(const Position& position) {
} // namespace
-const LayoutBlockFlow* NGInlineFormattingContextOf(const Position& position) {
+LayoutBlockFlow* NGInlineFormattingContextOf(const Position& position) {
if (!RuntimeEnabledFeatures::LayoutNGEnabled())
return nullptr;
if (!NGOffsetMapping::AcceptsPosition(position))
@@ -62,14 +62,7 @@ const LayoutBlockFlow* NGInlineFormattingContextOf(const Position& position) {
const auto node_offset_pair = ToNodeOffsetPair(position);
const LayoutObject* layout_object =
AssociatedLayoutObjectOf(node_offset_pair.first, node_offset_pair.second);
- // For an atomic inline, EnclosingNGBlockFlow() may return itself. Example:
- // <div><span style='display: inline-block'>foo</span></div>
- // EnclosingNGBlockFlow() on SPAN returns SPAN itself. However, the inline
- // formatting context of SPAN@Before/After is DIV, not SPAN.
- // Therefore, we return its parent's EnclosingNGBlockFlow() instead.
- if (layout_object->IsAtomicInlineLevel())
- layout_object = layout_object->Parent();
- return layout_object->EnclosingNGBlockFlow();
+ return layout_object->ContainingNGBlockFlow();
}
NGOffsetMappingUnit::NGOffsetMappingUnit(NGOffsetMappingUnitType type,
@@ -174,7 +167,7 @@ const NGOffsetMapping* NGOffsetMapping::GetFor(const Position& position) {
return nullptr;
if (!NGOffsetMapping::AcceptsPosition(position))
return nullptr;
- return GetFor(NGInlineFormattingContextOf(position));
+ return GetForContainingBlockFlow(NGInlineFormattingContextOf(position));
}
// static
@@ -184,7 +177,12 @@ const NGOffsetMapping* NGOffsetMapping::GetFor(
return nullptr;
if (!layout_object)
return nullptr;
- LayoutBlockFlow* block_flow = layout_object->EnclosingNGBlockFlow();
+ return GetForContainingBlockFlow(layout_object->ContainingNGBlockFlow());
+}
+
+// static
+const NGOffsetMapping* NGOffsetMapping::GetForContainingBlockFlow(
+ LayoutBlockFlow* block_flow) {
if (!block_flow || !block_flow->ChildrenInline())
return nullptr;
NGBlockNode block_node = NGBlockNode(block_flow);
@@ -271,6 +269,16 @@ NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForDOMRange(
return {result_begin, result_end};
}
+NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForNode(
+ const Node& node) const {
+ const auto it = ranges_.find(&node);
+ if (it == ranges_.end()) {
+ NOTREACHED() << node;
+ return NGMappingUnitRange();
+ }
+ return {units_.begin() + it->value.first, units_.begin() + it->value.second};
+}
+
NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForTextContentOffsetRange(
unsigned start,
unsigned end) const {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h
index 195b88cc584..fcea9c0caba 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h
@@ -130,6 +130,10 @@ class CORE_EXPORT NGOffsetMapping {
// a LayoutObject at hand.
static const NGOffsetMapping* GetFor(const LayoutObject*);
+ // Returns the mapping object of the inline formatting context the given
+ // LayoutBlockFlow has.
+ static const NGOffsetMapping* GetForContainingBlockFlow(LayoutBlockFlow*);
+
// Returns the NGOffsetMappingUnit whose DOM range contains the position.
// If there are multiple qualifying units, returns the last one.
const NGOffsetMappingUnit* GetMappingUnitForPosition(const Position&) const;
@@ -139,6 +143,10 @@ class CORE_EXPORT NGOffsetMapping {
// only accepts ranges whose start and end have the same anchor node.
NGMappingUnitRange GetMappingUnitsForDOMRange(const EphemeralRange&) const;
+ // Returns all NGOffsetMappingUnits associated to |node|. Note: |node| should
+ // have associated mapping.
+ NGMappingUnitRange GetMappingUnitsForNode(const Node& node) const;
+
// Returns the text content offset corresponding to the given position.
// Returns nullopt when the position is not laid out in this context.
base::Optional<unsigned> GetTextContentOffset(const Position&) const;
@@ -206,7 +214,7 @@ class CORE_EXPORT NGOffsetMapping {
DISALLOW_COPY_AND_ASSIGN(NGOffsetMapping);
};
-CORE_EXPORT const LayoutBlockFlow* NGInlineFormattingContextOf(const Position&);
+CORE_EXPORT LayoutBlockFlow* NGInlineFormattingContextOf(const Position&);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_test.cc
index 50b791d9a08..2705012b3d4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_test.cc
@@ -1149,4 +1149,40 @@ TEST_F(NGOffsetMappingTest, TextOverflowEllipsis) {
TEST_RANGE(mapping.GetRanges(), text, 0u, 1u);
}
+// Test |GetOffsetMapping| which is available both for LayoutNG and for legacy.
+class NGOffsetMappingGetterTest : public RenderingTest,
+ public testing::WithParamInterface<bool>,
+ private ScopedLayoutNGForTest {
+ public:
+ NGOffsetMappingGetterTest() : ScopedLayoutNGForTest(GetParam()) {}
+};
+
+INSTANTIATE_TEST_CASE_P(NGOffsetMappingTest,
+ NGOffsetMappingGetterTest,
+ testing::Bool());
+
+TEST_P(NGOffsetMappingGetterTest, Get) {
+ SetBodyInnerHTML(R"HTML(
+ <div id=container>
+ Whitespaces in this text should be collapsed.
+ </div>
+ )HTML");
+ LayoutBlockFlow* layout_block_flow =
+ ToLayoutBlockFlow(GetLayoutObjectByElementId("container"));
+ DCHECK(layout_block_flow->ChildrenInline());
+
+ // For the purpose of this test, ensure this is laid out by each layout
+ // engine.
+ DCHECK_EQ(layout_block_flow->IsLayoutNGMixin(), GetParam());
+
+ std::unique_ptr<NGOffsetMapping> storage;
+ const NGOffsetMapping* mapping =
+ NGInlineNode::GetOffsetMapping(layout_block_flow, &storage);
+ EXPECT_TRUE(mapping);
+ EXPECT_EQ(!storage, GetParam()); // |storage| is used only for legacy.
+
+ const String& text_content = mapping->GetText();
+ EXPECT_EQ(text_content, "Whitespaces in this text should be collapsed.");
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.cc
index 9564e068cb3..751766a4c72 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.cc
@@ -5,29 +5,50 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
+namespace {
+
+struct SameSizeAsNGPhysicalLineBoxFragment : NGPhysicalContainerFragment {
+ void* pointer;
+ NGLineHeightMetrics metrics;
+};
+
+static_assert(sizeof(NGPhysicalLineBoxFragment) ==
+ sizeof(SameSizeAsNGPhysicalLineBoxFragment),
+ "NGPhysicalLineBoxFragment should stay small");
+
+} // namespace
+
+scoped_refptr<const NGPhysicalLineBoxFragment>
+NGPhysicalLineBoxFragment::Create(NGLineBoxFragmentBuilder* builder) {
+ // We store the children list inline in the fragment as a flexible
+ // array. Therefore, we need to make sure to allocate enough space for
+ // that array here, which requires a manual allocation + placement new.
+ // The initialization of the array is done by NGPhysicalContainerFragment;
+ // we pass the buffer as a constructor argument.
+ void* data = ::WTF::Partitions::FastMalloc(
+ sizeof(NGPhysicalLineBoxFragment) +
+ builder->children_.size() * sizeof(NGLinkStorage),
+ ::WTF::GetStringWithTypeName<NGPhysicalLineBoxFragment>());
+ new (data) NGPhysicalLineBoxFragment(builder);
+ return base::AdoptRef(static_cast<NGPhysicalLineBoxFragment*>(data));
+}
+
NGPhysicalLineBoxFragment::NGPhysicalLineBoxFragment(
- const ComputedStyle& style,
- NGStyleVariant style_variant,
- NGPhysicalSize size,
- Vector<NGLink>& children,
- const NGLineHeightMetrics& metrics,
- TextDirection base_direction,
- scoped_refptr<NGBreakToken> break_token)
- : NGPhysicalContainerFragment(nullptr,
- style,
- style_variant,
- size,
+ NGLineBoxFragmentBuilder* builder)
+ : NGPhysicalContainerFragment(builder,
+ builder->GetWritingMode(),
+ children_,
kFragmentLineBox,
- 0,
- children,
- std::move(break_token)),
- metrics_(metrics) {
- base_direction_ = static_cast<unsigned>(base_direction);
+ builder->line_box_type_),
+ metrics_(builder->metrics_) {
+ style_ = std::move(builder->style_);
+ base_direction_ = static_cast<unsigned>(builder->base_direction_);
}
NGLineHeightMetrics NGPhysicalLineBoxFragment::BaselineMetrics(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h
index 3fa31d418a4..57a4a6876a4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h
@@ -12,18 +12,39 @@
namespace blink {
+class NGLineBoxFragmentBuilder;
+
class CORE_EXPORT NGPhysicalLineBoxFragment final
: public NGPhysicalContainerFragment {
public:
- // This modifies the passed-in children vector.
- NGPhysicalLineBoxFragment(const ComputedStyle&,
- NGStyleVariant style_variant,
- NGPhysicalSize size,
- Vector<NGLink>& children,
- const NGLineHeightMetrics&,
- TextDirection base_direction,
- scoped_refptr<NGBreakToken> break_token = nullptr);
+ enum NGLineBoxType {
+ kNormalLineBox,
+ // This is an "empty" line box, or "certain zero-height line boxes":
+ // https://drafts.csswg.org/css2/visuren.html#phantom-line-box
+ // that are ignored for margin collapsing and for other purposes.
+ // https://drafts.csswg.org/css2/box.html#collapsing-margins
+ // Also see |NGInlineItem::IsEmptyItem|.
+ kEmptyLineBox
+ };
+
+ static scoped_refptr<const NGPhysicalLineBoxFragment> Create(
+ NGLineBoxFragmentBuilder* builder);
+
+ ~NGPhysicalLineBoxFragment() {
+ for (const NGLinkStorage& child : Children())
+ child.fragment->Release();
+ }
+
+ NGLineBoxType LineBoxType() const {
+ return static_cast<NGLineBoxType>(sub_type_);
+ }
+ bool IsEmptyLineBox() const { return LineBoxType() == kEmptyLineBox; }
+ ChildLinkList Children() const final {
+ return ChildLinkList(num_children_, &children_[0]);
+ }
+
+ const ComputedStyle& Style() const { return *style_; }
const NGLineHeightMetrics& Metrics() const { return metrics_; }
// The base direction of this line. Also known as the paragraph direction.
@@ -59,7 +80,11 @@ class CORE_EXPORT NGPhysicalLineBoxFragment final
bool HasSoftWrapToNextLine() const;
private:
+ NGPhysicalLineBoxFragment(NGLineBoxFragmentBuilder* builder);
+
+ scoped_refptr<const ComputedStyle> style_;
NGLineHeightMetrics metrics_;
+ NGLinkStorage children_[];
};
DEFINE_TYPE_CASTS(NGPhysicalLineBoxFragment,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc
index 7644d245120..183f690f962 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc
@@ -10,12 +10,23 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
namespace {
+struct SameSizeAsNGPhysicalTextFragment : NGPhysicalFragment {
+ void* pointers[3];
+ unsigned offsets[2];
+};
+
+static_assert(sizeof(NGPhysicalTextFragment) ==
+ sizeof(SameSizeAsNGPhysicalTextFragment),
+ "NGPhysicalTextFragment should stay small");
+
inline bool IsPhysicalTextFragmentAnonymousText(
const LayoutObject* layout_object) {
if (!layout_object)
@@ -26,35 +37,86 @@ inline bool IsPhysicalTextFragmentAnonymousText(
return !node || node->IsPseudoElement();
}
+NGLineOrientation ToLineOrientation(WritingMode writing_mode) {
+ switch (writing_mode) {
+ case WritingMode::kHorizontalTb:
+ return NGLineOrientation::kHorizontal;
+ case WritingMode::kVerticalRl:
+ case WritingMode::kVerticalLr:
+ case WritingMode::kSidewaysRl:
+ return NGLineOrientation::kClockWiseVertical;
+ case WritingMode::kSidewaysLr:
+ return NGLineOrientation::kCounterClockWiseVertical;
+ }
+ NOTREACHED();
+ return NGLineOrientation::kHorizontal;
+}
+
} // anonymous namespace
NGPhysicalTextFragment::NGPhysicalTextFragment(
- LayoutObject* layout_object,
- const ComputedStyle& style,
- NGStyleVariant style_variant,
- NGTextType text_type,
- const String& text,
+ const NGPhysicalTextFragment& source,
unsigned start_offset,
unsigned end_offset,
- NGPhysicalSize size,
- NGLineOrientation line_orientation,
- NGTextEndEffect end_effect,
- scoped_refptr<const ShapeResult> shape_result)
- : NGPhysicalFragment(layout_object,
- style,
- style_variant,
- size,
+ scoped_refptr<const ShapeResultView> shape_result)
+ : NGPhysicalFragment(source.GetLayoutObject(),
+ source.StyleVariant(),
+ source.IsHorizontal()
+ ? NGPhysicalSize{shape_result->SnappedWidth(),
+ source.Size().height}
+ : NGPhysicalSize{source.Size().width,
+ shape_result->SnappedWidth()},
kFragmentText,
- text_type),
- text_(text),
+ source.TextType()),
+ text_(source.text_),
start_offset_(start_offset),
end_offset_(end_offset),
- shape_result_(shape_result),
- line_orientation_(static_cast<unsigned>(line_orientation)),
- end_effect_(static_cast<unsigned>(end_effect)),
- is_anonymous_text_(IsPhysicalTextFragmentAnonymousText(layout_object)) {
+ shape_result_(shape_result) {
+ DCHECK_GE(start_offset_, source.StartOffset());
+ DCHECK_LE(end_offset_, source.EndOffset());
DCHECK(shape_result_ || IsFlowControl()) << ToString();
- self_ink_overflow_ = ComputeSelfInkOverflow();
+ DCHECK(!source.rare_data_ || !source.rare_data_->style_);
+ line_orientation_ = source.line_orientation_;
+ is_anonymous_text_ = source.is_anonymous_text_;
+
+ UpdateSelfInkOverflow();
+}
+
+NGPhysicalTextFragment::NGPhysicalTextFragment(NGTextFragmentBuilder* builder)
+ : NGPhysicalFragment(builder, kFragmentText, builder->text_type_),
+ text_(builder->text_),
+ start_offset_(builder->start_offset_),
+ end_offset_(builder->end_offset_),
+ shape_result_(std::move(builder->shape_result_)) {
+ DCHECK(shape_result_ || IsFlowControl()) << ToString();
+ line_orientation_ =
+ static_cast<unsigned>(ToLineOrientation(builder->GetWritingMode()));
+ is_anonymous_text_ =
+ IsPhysicalTextFragmentAnonymousText(builder->layout_object_);
+
+ if (UNLIKELY(StyleVariant() == NGStyleVariant::kEllipsis))
+ EnsureRareData()->style_ = std::move(builder->style_);
+
+ UpdateSelfInkOverflow();
+}
+
+NGPhysicalTextFragment::RareData* NGPhysicalTextFragment::EnsureRareData() {
+ if (!rare_data_)
+ rare_data_ = std::make_unique<RareData>();
+ return rare_data_.get();
+}
+
+const ComputedStyle& NGPhysicalTextFragment::Style() const {
+ switch (StyleVariant()) {
+ case NGStyleVariant::kStandard:
+ case NGStyleVariant::kFirstLine:
+ return NGPhysicalFragment::Style();
+ case NGStyleVariant::kEllipsis:
+ DCHECK(rare_data_ && rare_data_->style_);
+ return *rare_data_->style_;
+ }
+ NOTREACHED();
+ return NGPhysicalFragment::Style();
}
// Convert logical cooridnate to local physical coordinate.
@@ -85,8 +147,11 @@ LayoutUnit NGPhysicalTextFragment::InlinePositionForOffset(
offset -= start_offset_;
if (shape_result_) {
- return round(shape_result_->CaretPositionForOffset(offset, Text(),
- adjust_mid_cluster));
+ // TODO(layout-dev): Move caret position out of ShapeResult and into a
+ // separate support class that can take a ShapeResult or ShapeResultView.
+ // Allows for better code separation and avoids the extra copy below.
+ return round(shape_result_->CreateShapeResult()->CaretPositionForOffset(
+ offset, Text(), adjust_mid_cluster));
}
// This fragment is a flow control because otherwise ShapeResult exists.
@@ -141,9 +206,20 @@ NGPhysicalOffsetRect NGPhysicalTextFragment::LocalRect(
return {};
}
-NGPhysicalOffsetRect NGPhysicalTextFragment::ComputeSelfInkOverflow() const {
- if (UNLIKELY(!shape_result_))
- return LocalRect();
+NGPhysicalOffsetRect NGPhysicalTextFragment::SelfInkOverflow() const {
+ return UNLIKELY(rare_data_) ? rare_data_->self_ink_overflow_ : LocalRect();
+}
+
+void NGPhysicalTextFragment::ClearSelfInkOverflow() {
+ if (UNLIKELY(rare_data_))
+ rare_data_->self_ink_overflow_ = LocalRect();
+}
+
+void NGPhysicalTextFragment::UpdateSelfInkOverflow() {
+ if (UNLIKELY(!shape_result_)) {
+ ClearSelfInkOverflow();
+ return;
+ }
// Glyph bounds is in logical coordinate, origin at the alphabetic baseline.
LayoutRect ink_overflow = EnclosingLayoutRect(shape_result_->Bounds());
@@ -190,8 +266,13 @@ NGPhysicalOffsetRect NGPhysicalTextFragment::ComputeSelfInkOverflow() const {
// Uniting the frame rect ensures that non-ink spaces such side bearings, or
// even space characters, are included in the visual rect for decorations.
NGPhysicalOffsetRect local_ink_overflow = ConvertToLocal(ink_overflow);
- local_ink_overflow.Unite(LocalRect());
- return local_ink_overflow;
+ NGPhysicalOffsetRect local_rect = LocalRect();
+ if (local_rect.Contains(local_ink_overflow)) {
+ ClearSelfInkOverflow();
+ return;
+ }
+ local_ink_overflow.Unite(local_rect);
+ EnsureRareData()->self_ink_overflow_ = local_ink_overflow;
}
scoped_refptr<const NGPhysicalFragment> NGPhysicalTextFragment::TrimText(
@@ -201,15 +282,14 @@ scoped_refptr<const NGPhysicalFragment> NGPhysicalTextFragment::TrimText(
DCHECK_GE(new_start_offset, StartOffset());
DCHECK_GT(new_end_offset, new_start_offset);
DCHECK_LE(new_end_offset, EndOffset());
+ // TODO(layout-dev): Add sub-range version of CreateShapeResult to avoid
+ // this double copy.
scoped_refptr<ShapeResult> new_shape_result =
- shape_result_->SubRange(new_start_offset, new_end_offset);
- LayoutUnit new_inline_size = new_shape_result->SnappedWidth();
+ shape_result_->CreateShapeResult()->SubRange(new_start_offset,
+ new_end_offset);
return base::AdoptRef(new NGPhysicalTextFragment(
- layout_object_, Style(), static_cast<NGStyleVariant>(style_variant_),
- TextType(), text_, new_start_offset, new_end_offset,
- IsHorizontal() ? NGPhysicalSize{new_inline_size, size_.height}
- : NGPhysicalSize{size_.width, new_inline_size},
- LineOrientation(), EndEffect(), std::move(new_shape_result)));
+ *this, new_start_offset, new_end_offset,
+ ShapeResultView::Create(new_shape_result.get())));
}
unsigned NGPhysicalTextFragment::TextOffsetForPoint(
@@ -217,8 +297,10 @@ unsigned NGPhysicalTextFragment::TextOffsetForPoint(
const ComputedStyle& style = Style();
const LayoutUnit& point_in_line_direction =
style.IsHorizontalWritingMode() ? point.left : point.top;
- if (const ShapeResult* shape_result = TextShapeResult()) {
- return shape_result->CaretOffsetForHitTest(
+ if (const ShapeResultView* shape_result = TextShapeResult()) {
+ // TODO(layout-dev): Move caret logic out of ShapeResult into separate
+ // support class for code health and to avoid this copy.
+ return shape_result->CreateShapeResult()->CaretOffsetForHitTest(
point_in_line_direction.ToFloat(), Text(), BreakGlyphs) +
StartOffset();
}
@@ -258,7 +340,7 @@ UBiDiLevel NGPhysicalTextFragment::BidiLevel() const {
TextDirection NGPhysicalTextFragment::ResolvedDirection() const {
if (TextShapeResult())
return TextShapeResult()->Direction();
- return NGPhysicalFragment::ResolvedDirection();
+ return DirectionFromLevel(BidiLevel());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h
index 52d6924555c..b9111472f07 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h
@@ -10,12 +10,14 @@
#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
#include "third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
struct NGPhysicalOffsetRect;
+class NGTextFragmentBuilder;
enum class AdjustMidCluster;
@@ -57,17 +59,7 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
// enough to store.
};
- NGPhysicalTextFragment(LayoutObject* layout_object,
- const ComputedStyle& style,
- NGStyleVariant style_variant,
- NGTextType text_type,
- const String& text,
- unsigned start_offset,
- unsigned end_offset,
- NGPhysicalSize size,
- NGLineOrientation line_orientation,
- NGTextEndEffect end_effect,
- scoped_refptr<const ShapeResult> shape_result);
+ NGPhysicalTextFragment(NGTextFragmentBuilder*);
NGTextType TextType() const { return static_cast<NGTextType>(sub_type_); }
// True if this is a generated text.
@@ -80,12 +72,14 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
return IsLineBreak() || TextType() == kFlowControl;
}
+ const ComputedStyle& Style() const;
+
unsigned Length() const { return end_offset_ - start_offset_; }
StringView Text() const { return StringView(text_, start_offset_, Length()); }
const String& TextContent() const { return text_; }
// ShapeResult may be nullptr if |IsFlowControl()|.
- const ShapeResult* TextShapeResult() const { return shape_result_.get(); }
+ const ShapeResultView* TextShapeResult() const { return shape_result_.get(); }
// Start/end offset to the text of the block container.
unsigned StartOffset() const { return start_offset_; }
@@ -110,11 +104,7 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
// The visual bounding box that includes glpyh bounding box and CSS
// properties, in local coordinates.
- NGPhysicalOffsetRect SelfInkOverflow() const { return self_ink_overflow_; }
-
- NGTextEndEffect EndEffect() const {
- return static_cast<NGTextEndEffect>(end_effect_);
- }
+ NGPhysicalOffsetRect SelfInkOverflow() const;
// Create a new fragment that has part of the text of this fragment.
// All other properties are the same as this fragment.
@@ -135,8 +125,8 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
// Returns the text offset in the fragment placed closest to the given point.
unsigned TextOffsetForPoint(const NGPhysicalOffset&) const;
- UBiDiLevel BidiLevel() const override;
- TextDirection ResolvedDirection() const override;
+ UBiDiLevel BidiLevel() const;
+ TextDirection ResolvedDirection() const;
// Compute line-relative coordinates for given offsets, this is not
// flow-relative:
@@ -146,13 +136,26 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
unsigned end_offset) const;
private:
+ // For use by TrimText only
+ NGPhysicalTextFragment(const NGPhysicalTextFragment& source,
+ unsigned start_offset,
+ unsigned end_offset,
+ scoped_refptr<const ShapeResultView> shape_result);
+
+ struct RareData {
+ NGPhysicalOffsetRect self_ink_overflow_;
+ scoped_refptr<const ComputedStyle> style_; // Used only for ellipsis.
+ };
+ RareData* EnsureRareData();
+
LayoutUnit InlinePositionForOffset(unsigned offset,
LayoutUnit (*round)(float),
AdjustMidCluster) const;
NGPhysicalOffsetRect ConvertToLocal(const LayoutRect&) const;
- NGPhysicalOffsetRect ComputeSelfInkOverflow() const;
+ void UpdateSelfInkOverflow();
+ void ClearSelfInkOverflow();
// The text of NGInlineNode; i.e., of a parent block. The text for this
// fragment is a substring(start_offset_, end_offset_) of this string.
@@ -161,12 +164,9 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
// Start and end offset of the parent block text.
const unsigned start_offset_;
const unsigned end_offset_;
- NGPhysicalOffsetRect self_ink_overflow_;
- const scoped_refptr<const ShapeResult> shape_result_;
+ const scoped_refptr<const ShapeResultView> shape_result_;
- const unsigned line_orientation_ : 2; // NGLineOrientation
- const unsigned end_effect_ : 1; // NGTextEndEffect
- const unsigned is_anonymous_text_ : 1;
+ std::unique_ptr<RareData> rare_data_;
};
DEFINE_TYPE_CASTS(NGPhysicalTextFragment,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc
index 4419bfca2e6..0797df848c4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc
@@ -76,9 +76,10 @@ TEST_F(NGPhysicalTextFragmentTest, LocalRectRTL) {
ASSERT_EQ(2u, text_fragments.size());
// The 2nd line starts at 12, because the div has a bidi-control.
EXPECT_EQ(12u, text_fragments[1]->StartOffset());
- EXPECT_EQ(NGPhysicalOffsetRect({LayoutUnit(50), LayoutUnit(0)},
- {LayoutUnit(20), LayoutUnit(10)}),
- text_fragments[1]->LocalRect(14, 16));
+ // TODO(layout-dev): Investigate whether this is correct.
+ // EXPECT_EQ(NGPhysicalOffsetRect({LayoutUnit(50), LayoutUnit(0)},
+ // {LayoutUnit(20), LayoutUnit(10)}),
+ // text_fragments[1]->LocalRect(14, 16));
}
TEST_F(NGPhysicalTextFragmentTest, LocalRectVLR) {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.cc
index 64a42f1a618..07ee69f28b1 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.cc
@@ -8,33 +8,10 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
-namespace {
-
-NGLineOrientation ToLineOrientation(WritingMode writing_mode) {
- switch (writing_mode) {
- case WritingMode::kHorizontalTb:
- return NGLineOrientation::kHorizontal;
- case WritingMode::kVerticalRl:
- case WritingMode::kVerticalLr:
- case WritingMode::kSidewaysRl:
- return NGLineOrientation::kClockWiseVertical;
- case WritingMode::kSidewaysLr:
- return NGLineOrientation::kCounterClockWiseVertical;
- }
- NOTREACHED();
- return NGLineOrientation::kHorizontal;
-}
-
-} // namespace
-
-NGTextFragmentBuilder::NGTextFragmentBuilder(NGInlineNode node,
- WritingMode writing_mode)
- : NGBaseFragmentBuilder(writing_mode, TextDirection::kLtr),
- inline_node_(node) {}
-
void NGTextFragmentBuilder::SetItem(
NGPhysicalTextFragment::NGTextType text_type,
const NGInlineItemsData& items_data,
@@ -62,7 +39,7 @@ void NGTextFragmentBuilder::SetText(
const String& text,
scoped_refptr<const ComputedStyle> style,
bool is_ellipsis_style,
- scoped_refptr<const ShapeResult> shape_result) {
+ scoped_refptr<const ShapeResultView> shape_result) {
DCHECK(layout_object);
DCHECK(style);
DCHECK(shape_result);
@@ -70,8 +47,8 @@ void NGTextFragmentBuilder::SetText(
text_type_ = NGPhysicalTextFragment::kGeneratedText;
text_ = text;
item_index_ = std::numeric_limits<unsigned>::max();
- start_offset_ = shape_result->StartIndexForResult();
- end_offset_ = shape_result->EndIndexForResult();
+ start_offset_ = shape_result->StartIndex();
+ end_offset_ = shape_result->EndIndex();
SetStyle(style, is_ellipsis_style ? NGStyleVariant::kEllipsis
: NGStyleVariant::kStandard);
size_ = {shape_result->SnappedWidth(),
@@ -84,11 +61,7 @@ void NGTextFragmentBuilder::SetText(
scoped_refptr<const NGPhysicalTextFragment>
NGTextFragmentBuilder::ToTextFragment() {
scoped_refptr<const NGPhysicalTextFragment> fragment =
- base::AdoptRef(new NGPhysicalTextFragment(
- layout_object_, Style(), style_variant_, text_type_, text_,
- start_offset_, end_offset_, size_.ConvertToPhysical(GetWritingMode()),
- ToLineOrientation(GetWritingMode()), end_effect_,
- std::move(shape_result_)));
+ base::AdoptRef(new NGPhysicalTextFragment(this));
return fragment;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h
index 2621674b787..bf000858f53 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h
@@ -9,20 +9,22 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_end_effect.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
class LayoutObject;
-class ShapeResult;
+class ShapeResultView;
struct NGInlineItemResult;
-class CORE_EXPORT NGTextFragmentBuilder final : public NGBaseFragmentBuilder {
+class CORE_EXPORT NGTextFragmentBuilder final : public NGFragmentBuilder {
STACK_ALLOCATED();
public:
- NGTextFragmentBuilder(NGInlineNode, WritingMode);
+ NGTextFragmentBuilder(NGInlineNode node, WritingMode writing_mode)
+ : NGFragmentBuilder(writing_mode, TextDirection::kLtr),
+ inline_node_(node) {}
// NOTE: Takes ownership of the shape result within the item result.
void SetItem(NGPhysicalTextFragment::NGTextType,
@@ -35,7 +37,7 @@ class CORE_EXPORT NGTextFragmentBuilder final : public NGBaseFragmentBuilder {
const String& text,
scoped_refptr<const ComputedStyle>,
bool is_ellipsis_style,
- scoped_refptr<const ShapeResult>);
+ scoped_refptr<const ShapeResultView>);
// Creates the fragment. Can only be called once.
scoped_refptr<const NGPhysicalTextFragment> ToTextFragment();
@@ -46,14 +48,14 @@ class CORE_EXPORT NGTextFragmentBuilder final : public NGBaseFragmentBuilder {
unsigned item_index_;
unsigned start_offset_;
unsigned end_offset_;
- NGLogicalSize size_;
- scoped_refptr<const ShapeResult> shape_result_;
+ scoped_refptr<const ShapeResultView> shape_result_;
NGPhysicalTextFragment::NGTextType text_type_ =
NGPhysicalTextFragment::kNormalText;
NGTextEndEffect end_effect_ = NGTextEndEffect::kNone;
- LayoutObject* layout_object_ = nullptr;
+
+ friend class NGPhysicalTextFragment;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.cc
index 387ad8d2703..a944c30ae0d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.cc
@@ -5,16 +5,18 @@
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
+#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/min_max_size.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
namespace blink {
@@ -65,12 +67,12 @@ void LayoutNGBlockFlow::UpdateBlockLayout(bool relayout_children) {
scoped_refptr<NGLayoutResult> result =
NGBlockNode(this).Layout(constraint_space);
- for (NGOutOfFlowPositionedDescendant descendant :
+ for (const NGOutOfFlowPositionedDescendant& descendant :
result->OutOfFlowPositionedDescendants())
descendant.node.UseOldOutOfFlowPositioning();
const NGPhysicalBoxFragment* fragment =
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ ToNGPhysicalBoxFragment(result->PhysicalFragment());
// This object has already been positioned in legacy layout by our containing
// block. Copy the position and place the fragment.
@@ -105,9 +107,12 @@ void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
const ComputedStyle* parent_style = Parent()->Style();
NGConstraintSpace constraint_space =
NGConstraintSpace::CreateFromLayoutObject(*this);
- NGFragmentBuilder container_builder(
- container, scoped_refptr<const ComputedStyle>(container_style),
+ NGBlockNode container_node(container);
+ NGBoxFragmentBuilder container_builder(
+ container_node, scoped_refptr<const ComputedStyle>(container_style),
container_style->GetWritingMode(), container_style->Direction());
+ container_builder.SetIsNewFormattingContext(
+ container_node.CreatesNewFormattingContext());
// Compute ContainingBlock logical size.
// OverrideContainingBlockContentLogicalWidth/Height are used by e.g. grid
@@ -207,7 +212,7 @@ void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
// border-box relative, flip it around the size of the border box, rather than
// the size of the containing block (padding box).
LayoutUnit block_top_or_left =
- parent_style->IsFlippedBlocksWritingMode()
+ container_style->IsFlippedBlocksWritingMode()
? container_border_box_logical_height - static_block
: static_block;
@@ -218,7 +223,7 @@ void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
? NGPhysicalOffset(inline_left_or_top, block_top_or_left)
: NGPhysicalOffset(block_top_or_left, inline_left_or_top);
NGStaticPosition static_position =
- NGStaticPosition::Create(parent_style->GetWritingMode(),
+ NGStaticPosition::Create(container_style->GetWritingMode(),
parent_style->Direction(), static_location);
// Set correct container for inline containing blocks.
@@ -226,6 +231,17 @@ void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
NGBlockNode(this), static_position,
css_container->IsBox() ? nullptr : css_container);
+ base::Optional<NGLogicalSize> initial_containing_block_fixed_size;
+ if (container->IsLayoutView() && !GetDocument().Printing()) {
+ if (LocalFrameView* frame_view = ToLayoutView(container)->GetFrameView()) {
+ IntSize size =
+ frame_view->LayoutViewport()->ExcludeScrollbars(frame_view->Size());
+ NGPhysicalSize physical_size =
+ NGPhysicalSize(LayoutUnit(size.Width()), LayoutUnit(size.Height()));
+ initial_containing_block_fixed_size =
+ physical_size.ConvertToLogical(container->Style()->GetWritingMode());
+ }
+ }
// We really only want to lay out ourselves here, so we pass |this| to
// Run(). Otherwise, NGOutOfFlowLayoutPart may also lay out other objects
// it discovers that are part of the same containing block, but those
@@ -233,7 +249,7 @@ void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
NGOutOfFlowLayoutPart(
&container_builder, css_container->CanContainAbsolutePositionObjects(),
css_container->CanContainFixedPositionObjects(), borders_and_scrollbars,
- constraint_space, *container_style)
+ constraint_space, *container_style, initial_containing_block_fixed_size)
.Run(/* only_layout */ this);
scoped_refptr<NGLayoutResult> result = container_builder.ToBoxFragment();
// These are the unpositioned OOF descendants of the current OOF block.
@@ -241,8 +257,8 @@ void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
result->OutOfFlowPositionedDescendants())
descendant.node.UseOldOutOfFlowPositioning();
- scoped_refptr<const NGPhysicalBoxFragment> fragment =
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ const NGPhysicalBoxFragment* fragment =
+ ToNGPhysicalBoxFragment(result->PhysicalFragment());
DCHECK_GT(fragment->Children().size(), 0u);
// Copy sizes of all child fragments to Legacy.
// There could be multiple fragments, when this node has descendants whose
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc
index 80f9623c20a..da796eccc5f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc
@@ -33,7 +33,7 @@ void LayoutNGFlexibleBox::UpdateBlockLayout(bool relayout_children) {
descendant.node.UseOldOutOfFlowPositioning();
const NGPhysicalBoxFragment* fragment =
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ ToNGPhysicalBoxFragment(result->PhysicalFragment());
// Pasted from layout_ng_block_flow. TODO(dgrogan): Factor a utility method.
const LayoutBlock* containing_block = ContainingBlock();
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc
index d5f95c561e5..2f2abd0bd4a 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h"
#include "third_party/blink/renderer/core/paint/ng/ng_block_flow_painter.h"
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
namespace blink {
@@ -61,11 +62,26 @@ void LayoutNGMixin<Base>::ResetNGInlineNodeData() {
template <typename Base>
const NGPhysicalBoxFragment* LayoutNGMixin<Base>::CurrentFragment() const {
if (cached_result_)
- return ToNGPhysicalBoxFragment(cached_result_->PhysicalFragment().get());
+ return ToNGPhysicalBoxFragment(cached_result_->PhysicalFragment());
return nullptr;
}
template <typename Base>
+void LayoutNGMixin<Base>::ComputeVisualOverflow(
+ const LayoutRect& previous_visual_overflow_rect,
+ bool recompute_floats) {
+ Base::ComputeVisualOverflow(previous_visual_overflow_rect, recompute_floats);
+ AddVisualOverflowFromChildren();
+
+ if (Base::VisualOverflowRect() != previous_visual_overflow_rect) {
+ if (Base::Layer())
+ Base::Layer()->SetNeedsCompositingInputsUpdate();
+ Base::GetFrameView()->SetIntersectionObservationState(
+ LocalFrameView::kDesired);
+ }
+}
+
+template <typename Base>
void LayoutNGMixin<Base>::AddVisualOverflowFromChildren() {
// |ComputeOverflow()| calls this, which is called from
// |CopyFragmentDataToLayoutBox()| and |RecalcOverflowAfterStyleChange()|.
@@ -168,22 +184,25 @@ void LayoutNGMixin<Base>::AddOutlineRects(
// Retrieve NGBaseline from the current fragment.
template <typename Base>
-const NGBaseline* LayoutNGMixin<Base>::FragmentBaseline(
+base::Optional<LayoutUnit> LayoutNGMixin<Base>::FragmentBaseline(
NGBaselineAlgorithmType type) const {
+ if (Base::ShouldApplyLayoutContainment())
+ return base::nullopt;
+
if (const NGPhysicalFragment* physical_fragment = CurrentFragment()) {
FontBaseline baseline_type = Base::StyleRef().GetFontBaseline();
return ToNGPhysicalBoxFragment(physical_fragment)
->Baseline({type, baseline_type});
}
- return nullptr;
+ return base::nullopt;
}
template <typename Base>
LayoutUnit LayoutNGMixin<Base>::FirstLineBoxBaseline() const {
if (Base::ChildrenInline()) {
- if (const NGBaseline* baseline =
+ if (base::Optional<LayoutUnit> offset =
FragmentBaseline(NGBaselineAlgorithmType::kFirstLine)) {
- return baseline->offset;
+ return offset.value();
}
}
return Base::FirstLineBoxBaseline();
@@ -193,9 +212,9 @@ template <typename Base>
LayoutUnit LayoutNGMixin<Base>::InlineBlockBaseline(
LineDirectionMode line_direction) const {
if (Base::ChildrenInline()) {
- if (const NGBaseline* baseline =
+ if (base::Optional<LayoutUnit> offset =
FragmentBaseline(NGBaselineAlgorithmType::kAtomicInline)) {
- return baseline->offset;
+ return offset.value();
}
}
return Base::InlineBlockBaseline(line_direction);
@@ -203,19 +222,14 @@ LayoutUnit LayoutNGMixin<Base>::InlineBlockBaseline(
template <typename Base>
scoped_refptr<NGLayoutResult> LayoutNGMixin<Base>::CachedLayoutResult(
- const NGConstraintSpace& constraint_space,
- const NGBreakToken* break_token) const {
+ const NGConstraintSpace& new_space,
+ const NGBreakToken* break_token) {
if (!RuntimeEnabledFeatures::LayoutNGFragmentCachingEnabled())
return nullptr;
if (!cached_result_ || !Base::cached_constraint_space_ || break_token ||
Base::NeedsLayout())
return nullptr;
- if (constraint_space != *Base::cached_constraint_space_)
- return nullptr;
- // The checks above should be enough to bail if layout is incomplete, but
- // let's verify:
- DCHECK(
- IsBlockLayoutComplete(*Base::cached_constraint_space_, *cached_result_));
+ const NGConstraintSpace& old_space = *Base::cached_constraint_space_;
// If we used to contain abspos items, we can't reuse the fragment, because
// we can't be sure that the list of items hasn't changed (as we bubble them
// up during layout). In the case of newly-added abspos items to this
@@ -224,7 +238,55 @@ scoped_refptr<NGLayoutResult> LayoutNGMixin<Base>::CachedLayoutResult(
// TODO(layout-ng): Come up with a better solution for this
if (cached_result_->OutOfFlowPositionedDescendants().size())
return nullptr;
- return cached_result_->CloneWithoutOffset();
+ if (!new_space.MaySkipLayout(old_space))
+ return nullptr;
+
+ // If we have an orthogonal flow root descendant, we don't attempt to cache
+ // our layout result. This is because the initial containing block size may
+ // have changed, having a high likelihood of changing the size of the
+ // orthogonal flow root.
+ if (cached_result_->HasOrthogonalFlowRoots())
+ return nullptr;
+
+ if (!new_space.AreSizesEqual(old_space)) {
+ // We need to descend all the way down into BODY if we're in quirks mode,
+ // since it magically follows the viewport size.
+ if (NGBlockNode(this).IsQuirkyAndFillsViewport())
+ return nullptr;
+
+ // If the available / percentage sizes have changed in a way that may affect
+ // layout, we cannot re-use the previous result.
+ if (SizeMayChange(Base::StyleRef(), new_space, old_space))
+ return nullptr;
+ }
+
+ // Check BFC block offset. Even if they don't match, there're some cases we
+ // can still reuse the fragment.
+ base::Optional<LayoutUnit> bfc_block_offset =
+ cached_result_->BfcBlockOffset();
+ if (new_space.BfcOffset().block_offset !=
+ old_space.BfcOffset().block_offset) {
+ // Earlier floats may affect this box if block offset changes.
+ if (new_space.HasFloats() || old_space.HasFloats())
+ return nullptr;
+
+ // Even for the first fragment, when block fragmentation is enabled, block
+ // offset changes should cause re-layout, since we will fragment at other
+ // locations than before.
+ if (new_space.HasBlockFragmentation() || old_space.HasBlockFragmentation())
+ return nullptr;
+
+ if (bfc_block_offset.has_value()) {
+ bfc_block_offset = bfc_block_offset.value() -
+ old_space.BfcOffset().block_offset +
+ new_space.BfcOffset().block_offset;
+ }
+ }
+
+ // The checks above should be enough to bail if layout is incomplete, but
+ // let's verify:
+ DCHECK(IsBlockLayoutComplete(old_space, *cached_result_));
+ return base::AdoptRef(new NGLayoutResult(*cached_result_, bfc_block_offset));
}
template <typename Base>
@@ -256,6 +318,31 @@ LayoutNGMixin<Base>::CachedLayoutResultForTesting() {
}
template <typename Base>
+bool LayoutNGMixin<Base>::AreCachedLinesValidFor(
+ const NGConstraintSpace& constraint_space) const {
+ if (!Base::cached_constraint_space_)
+ return false;
+ const NGConstraintSpace& cached_constraint_space =
+ *Base::cached_constraint_space_;
+ DCHECK(cached_result_);
+
+ if (constraint_space.AvailableSize().inline_size !=
+ cached_constraint_space.AvailableSize().inline_size)
+ return false;
+
+ // Floats in either cached or new constraint space prevents reusing cached
+ // lines.
+ if (constraint_space.HasFloats() || cached_constraint_space.HasFloats())
+ return false;
+
+ // Propagating OOF needs re-layout.
+ if (!cached_result_->OutOfFlowPositionedDescendants().IsEmpty())
+ return false;
+
+ return true;
+}
+
+template <typename Base>
void LayoutNGMixin<Base>::SetPaintFragment(
scoped_refptr<const NGPhysicalFragment> fragment,
NGPhysicalOffset offset,
@@ -381,7 +468,12 @@ void LayoutNGMixin<Base>::DirtyLinesFromChangedChild(
LayoutObject* child,
MarkingBehavior marking_behavior) {
DCHECK_EQ(marking_behavior, kMarkContainerChain);
- NGPaintFragment::DirtyLinesFromChangedChild(child);
+
+ // We need to dirty line box fragments only if the child is once laid out in
+ // LayoutNG inline formatting context. New objects are handled in
+ // NGInlineNode::MarkLineBoxesDirty().
+ if (child->IsInLayoutNGInlineFormattingContext())
+ NGPaintFragment::DirtyLinesFromChangedChild(child);
}
template class CORE_TEMPLATE_EXPORT LayoutNGMixin<LayoutTableCaption>;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h
index 477d924a18b..eccfd23525d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h
@@ -22,7 +22,6 @@ class NGConstraintSpace;
class NGLayoutResult;
class NGPaintFragment;
class NGPhysicalFragment;
-struct NGBaseline;
struct NGInlineNodeData;
struct NGPhysicalOffset;
@@ -59,14 +58,14 @@ class LayoutNGMixin : public Base {
// Returns the last layout result for this block flow with the given
// constraint space and break token, or null if it is not up-to-date or
// otherwise unavailable.
- scoped_refptr<NGLayoutResult> CachedLayoutResult(
- const NGConstraintSpace&,
- const NGBreakToken*) const final;
+ scoped_refptr<NGLayoutResult> CachedLayoutResult(const NGConstraintSpace&,
+ const NGBreakToken*) final;
void SetCachedLayoutResult(const NGConstraintSpace&,
const NGBreakToken*,
const NGLayoutResult&) final;
void ClearCachedLayoutResult() final;
+ bool AreCachedLinesValidFor(const NGConstraintSpace&) const final;
// For testing only.
scoped_refptr<const NGLayoutResult> CachedLayoutResultForTesting() final;
@@ -83,7 +82,9 @@ class LayoutNGMixin : public Base {
protected:
bool IsOfType(LayoutObject::LayoutObjectType) const override;
- void AddVisualOverflowFromChildren() final;
+ void ComputeVisualOverflow(const LayoutRect&, bool recompute_floats) final;
+
+ void AddVisualOverflowFromChildren();
void AddLayoutOverflowFromChildren() final;
private:
@@ -99,7 +100,7 @@ class LayoutNGMixin : public Base {
const NGPhysicalBoxFragment* CurrentFragment() const final;
- const NGBaseline* FragmentBaseline(NGBaselineAlgorithmType) const;
+ base::Optional<LayoutUnit> FragmentBaseline(NGBaselineAlgorithmType) const;
void DirtyLinesFromChangedChild(LayoutObject* child,
MarkingBehavior marking_behavior) final;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.cc
index 12689da35c5..5f6eb022548 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.cc
@@ -37,8 +37,8 @@ void LayoutNGTableCaption::CalculateAndSetMargins(
LayoutUnit caption_inline_size_in_cb_writing_mode = box_fragment.InlineSize();
LayoutUnit available_inline_size_in_cb_writing_mode =
- constraint_space.AvailableSize()
- .ConvertToPhysical(constraint_space.GetWritingMode())
+ ToNGPhysicalSize(constraint_space.AvailableSize(),
+ constraint_space.GetWritingMode())
.ConvertToLogical(containing_block_style.GetWritingMode())
.inline_size;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.cc
index 8a6125e87d4..7db04f9dedd 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.cc
@@ -33,7 +33,7 @@ void LayoutNGTableCell::UpdateBlockLayout(bool relayout_children) {
descendant.node.UseOldOutOfFlowPositioning();
const NGPhysicalBoxFragment* fragment =
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ ToNGPhysicalBoxFragment(result->PhysicalFragment());
const LayoutBox* section = LocationContainer();
NGPhysicalOffset physical_offset;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc
index 38ccae67d2a..be144715fee 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc
@@ -58,7 +58,7 @@ void LayoutNGListItem::OrdinalValueChanged() {
is_marker_text_updated_ = false;
DCHECK(marker_);
marker_->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- LayoutInvalidationReason::kListValueChange);
+ layout_invalidation_reason::kListValueChange);
}
}
@@ -247,6 +247,12 @@ LayoutNGListItem::MarkerType LayoutNGListItem::MarkerText(
return kStatic;
}
+String LayoutNGListItem::MarkerTextWithSuffix() const {
+ StringBuilder text;
+ MarkerText(&text, kWithSuffix);
+ return text.ToString();
+}
+
String LayoutNGListItem::MarkerTextWithoutSuffix() const {
StringBuilder text;
MarkerText(&text, kWithoutSuffix);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h
index a060bb11312..204a7ef83a8 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h
@@ -19,6 +19,7 @@ class CORE_EXPORT LayoutNGListItem final : public LayoutNGBlockFlow {
ListItemOrdinal& Ordinal() { return ordinal_; }
int Value() const;
+ String MarkerTextWithSuffix() const;
String MarkerTextWithoutSuffix() const;
LayoutObject* Marker() const { return marker_; }
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.cc b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.cc
index b7cd49debf1..23378967744 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.cc
@@ -66,7 +66,11 @@ LayoutObject* LayoutNGListMarker::SymbolMarkerLayoutText() const {
}
String LayoutNGListMarker::TextAlternative() const {
- return ToLayoutText(FirstChild())->GetText();
+ // Compute from the list item, in the logical order even in RTL, reflecting
+ // speech order.
+ if (LayoutNGListItem* list_item = ListItem())
+ return list_item->MarkerTextWithSuffix();
+ return g_empty_string;
}
bool LayoutNGListMarker::NeedsOccupyWholeLine() const {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc b/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc
index 8f2c5bf8019..8780421d63d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc
@@ -8,8 +8,8 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
namespace blink {
@@ -39,13 +39,14 @@ LayoutUnit NGUnpositionedListMarker::InlineOffset(
}
scoped_refptr<NGLayoutResult> NGUnpositionedListMarker::Layout(
- const NGConstraintSpace& space,
+ const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
FontBaseline baseline_type) const {
DCHECK(marker_layout_object_);
NGBlockNode marker_node(marker_layout_object_);
scoped_refptr<NGLayoutResult> marker_layout_result =
- marker_node.LayoutAtomicInline(space, baseline_type,
- space.UseFirstLineStyle());
+ marker_node.LayoutAtomicInline(parent_space, parent_style, baseline_type,
+ parent_space.UseFirstLineStyle());
DCHECK(marker_layout_result && marker_layout_result->PhysicalFragment());
return marker_layout_result;
}
@@ -55,7 +56,7 @@ bool NGUnpositionedListMarker::AddToBox(
FontBaseline baseline_type,
const NGPhysicalFragment& content,
NGLogicalOffset* content_offset,
- NGFragmentBuilder* container_builder,
+ NGBoxFragmentBuilder* container_builder,
const NGBoxStrut& border_scrollbar_padding) const {
// Baselines from two different writing-mode cannot be aligned.
if (UNLIKELY(space.GetWritingMode() != content.Style().GetWritingMode()))
@@ -70,7 +71,7 @@ bool NGUnpositionedListMarker::AddToBox(
// If this child is an empty line-box, the list marker should be aligned
// with the next non-empty line box produced. (This can occur with floats
// producing empty line-boxes).
- if (line_box.Children().IsEmpty() && !line_box.BreakToken()->IsFinished())
+ if (line_box.IsEmptyLineBox() && !line_box.BreakToken()->IsFinished())
return false;
content_metrics = line_box.Metrics();
@@ -89,7 +90,7 @@ bool NGUnpositionedListMarker::AddToBox(
// Layout the list marker.
scoped_refptr<NGLayoutResult> marker_layout_result =
- Layout(space, baseline_type);
+ Layout(space, container_builder->Style(), baseline_type);
DCHECK(marker_layout_result && marker_layout_result->PhysicalFragment());
const NGPhysicalBoxFragment& marker_physical_fragment =
ToNGPhysicalBoxFragment(*marker_layout_result->PhysicalFragment());
@@ -125,10 +126,10 @@ bool NGUnpositionedListMarker::AddToBox(
LayoutUnit NGUnpositionedListMarker::AddToBoxWithoutLineBoxes(
const NGConstraintSpace& space,
FontBaseline baseline_type,
- NGFragmentBuilder* container_builder) const {
+ NGBoxFragmentBuilder* container_builder) const {
// Layout the list marker.
scoped_refptr<NGLayoutResult> marker_layout_result =
- Layout(space, baseline_type);
+ Layout(space, container_builder->Style(), baseline_type);
DCHECK(marker_layout_result && marker_layout_result->PhysicalFragment());
const NGPhysicalBoxFragment& marker_physical_fragment =
ToNGPhysicalBoxFragment(*marker_layout_result->PhysicalFragment());
@@ -149,7 +150,7 @@ LayoutUnit NGUnpositionedListMarker::AddToBoxWithoutLineBoxes(
// diff as intruded offset.
LayoutUnit NGUnpositionedListMarker::ComputeIntrudedFloatOffset(
const NGConstraintSpace& space,
- const NGFragmentBuilder* container_builder,
+ const NGBoxFragmentBuilder* container_builder,
const NGBoxStrut& border_scrollbar_padding,
LayoutUnit marker_block_offset) const {
DCHECK(container_builder);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h b/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h
index 47dfff9cf2e..f235396041b 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h
@@ -13,11 +13,12 @@
namespace blink {
+class ComputedStyle;
class LayoutNGListMarker;
class LayoutUnit;
class NGBlockNode;
class NGConstraintSpace;
-class NGFragmentBuilder;
+class NGBoxFragmentBuilder;
class NGLayoutResult;
class NGPhysicalFragment;
@@ -50,7 +51,7 @@ class CORE_EXPORT NGUnpositionedListMarker final {
FontBaseline,
const NGPhysicalFragment& content,
NGLogicalOffset* content_offset,
- NGFragmentBuilder*,
+ NGBoxFragmentBuilder*,
const NGBoxStrut&) const;
// Add a fragment for an outside list marker when the list item has no line
@@ -58,16 +59,17 @@ class CORE_EXPORT NGUnpositionedListMarker final {
// Returns the block size of the list marker.
LayoutUnit AddToBoxWithoutLineBoxes(const NGConstraintSpace&,
FontBaseline,
- NGFragmentBuilder*) const;
+ NGBoxFragmentBuilder*) const;
LayoutUnit InlineOffset(const LayoutUnit marker_inline_size) const;
private:
bool IsImage() const;
- scoped_refptr<NGLayoutResult> Layout(const NGConstraintSpace&,
+ scoped_refptr<NGLayoutResult> Layout(const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
FontBaseline) const;
LayoutUnit ComputeIntrudedFloatOffset(const NGConstraintSpace&,
- const NGFragmentBuilder*,
+ const NGBoxFragmentBuilder*,
const NGBoxStrut&,
LayoutUnit) const;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc
index 976ee25a0e5..196f33775bc 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -158,9 +158,11 @@ void ComputeAbsoluteHorizontal(const NGConstraintSpace& space,
const WritingMode container_writing_mode,
const TextDirection container_direction,
NGAbsolutePhysicalPosition* position) {
- NGPhysicalSize percentage_physical =
- space.PercentageResolutionSize().ConvertToPhysical(
- space.GetWritingMode());
+ LayoutUnit percentage_width =
+ LIKELY(space.GetWritingMode() == WritingMode::kHorizontalTb)
+ ? space.PercentageResolutionInlineSize()
+ : space.PercentageResolutionBlockSize();
+
base::Optional<LayoutUnit> margin_left;
if (!style.MarginLeft().IsAuto())
margin_left = ResolveMarginPaddingLength(space, style.MarginLeft());
@@ -169,13 +171,13 @@ void ComputeAbsoluteHorizontal(const NGConstraintSpace& space,
margin_right = ResolveMarginPaddingLength(space, style.MarginRight());
base::Optional<LayoutUnit> left;
if (!style.Left().IsAuto())
- left = ValueForLength(style.Left(), percentage_physical.width);
+ left = ValueForLength(style.Left(), percentage_width);
base::Optional<LayoutUnit> right;
if (!style.Right().IsAuto())
- right = ValueForLength(style.Right(), percentage_physical.width);
+ right = ValueForLength(style.Right(), percentage_width);
base::Optional<LayoutUnit> width = incoming_width;
NGPhysicalSize container_size =
- space.AvailableSize().ConvertToPhysical(space.GetWritingMode());
+ ToNGPhysicalSize(space.AvailableSize(), space.GetWritingMode());
DCHECK_NE(container_size.width, NGSizeIndefinite);
// Solving the equation:
@@ -206,7 +208,7 @@ void ComputeAbsoluteHorizontal(const NGConstraintSpace& space,
if (!margin_left && !margin_right) {
if (margin_space > 0) {
margin_left = margin_space / 2;
- margin_right = margin_space / 2;
+ margin_right = margin_space - *margin_left;
} else {
// Margins are negative.
if (IsLeftDominant(container_writing_mode, container_direction)) {
@@ -321,9 +323,10 @@ void ComputeAbsoluteVertical(const NGConstraintSpace& space,
const WritingMode container_writing_mode,
const TextDirection container_direction,
NGAbsolutePhysicalPosition* position) {
- NGPhysicalSize percentage_physical =
- space.PercentageResolutionSize().ConvertToPhysical(
- space.GetWritingMode());
+ LayoutUnit percentage_height =
+ LIKELY(space.GetWritingMode() == WritingMode::kHorizontalTb)
+ ? space.PercentageResolutionBlockSize()
+ : space.PercentageResolutionInlineSize();
base::Optional<LayoutUnit> margin_top;
if (!style.MarginTop().IsAuto())
@@ -333,15 +336,15 @@ void ComputeAbsoluteVertical(const NGConstraintSpace& space,
margin_bottom = ResolveMarginPaddingLength(space, style.MarginBottom());
base::Optional<LayoutUnit> top;
if (!style.Top().IsAuto())
- top = ValueForLength(style.Top(), percentage_physical.height);
+ top = ValueForLength(style.Top(), percentage_height);
base::Optional<LayoutUnit> bottom;
if (!style.Bottom().IsAuto())
- bottom = ValueForLength(style.Bottom(), percentage_physical.height);
+ bottom = ValueForLength(style.Bottom(), percentage_height);
LayoutUnit border_padding = VerticalBorderPadding(space, style);
base::Optional<LayoutUnit> height = incoming_height;
NGPhysicalSize container_size =
- space.AvailableSize().ConvertToPhysical(space.GetWritingMode());
+ ToNGPhysicalSize(space.AvailableSize(), space.GetWritingMode());
DCHECK_NE(container_size.height, NGSizeIndefinite);
// Solving the equation:
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h
index 22e207b4dad..3f120d1959d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/layout/min_max_size.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc
index 88827c12ffa..e94c6d8b9f4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc
@@ -17,6 +17,16 @@ namespace {
class NGAbsoluteUtilsTest : public testing::Test {
protected:
+ NGConstraintSpace CreateConstraintSpace(TextDirection direction,
+ WritingMode out_writing_mode) {
+ NGConstraintSpaceBuilder builder(
+ WritingMode::kHorizontalTb, out_writing_mode,
+ /* is_new_fc */ true);
+ builder.SetAvailableSize(container_size_);
+ builder.SetTextDirection(direction);
+ return builder.ToConstraintSpace();
+ }
+
void SetUp() override {
style_ = ComputedStyle::Create();
// If not set, border widths will always be 0.
@@ -26,19 +36,15 @@ class NGAbsoluteUtilsTest : public testing::Test {
style_->SetBorderBottomStyle(EBorderStyle::kSolid);
style_->SetBoxSizing(EBoxSizing::kBorderBox);
container_size_ = NGLogicalSize(LayoutUnit(200), LayoutUnit(300));
- NGConstraintSpaceBuilder builder(
- WritingMode::kHorizontalTb,
- /* icb_size */ container_size_.ConvertToPhysical(
- WritingMode::kHorizontalTb));
- builder.SetAvailableSize(container_size_);
- ltr_space_ = builder.SetTextDirection(TextDirection::kLtr)
- .ToConstraintSpace(WritingMode::kHorizontalTb);
- rtl_space_ = builder.SetTextDirection(TextDirection::kRtl)
- .ToConstraintSpace(WritingMode::kHorizontalTb);
- vertical_lr_space_ = builder.SetTextDirection(TextDirection::kLtr)
- .ToConstraintSpace(WritingMode::kVerticalLr);
- vertical_rl_space_ = builder.SetTextDirection(TextDirection::kLtr)
- .ToConstraintSpace(WritingMode::kVerticalRl);
+
+ ltr_space_ =
+ CreateConstraintSpace(TextDirection::kLtr, WritingMode::kHorizontalTb);
+ rtl_space_ =
+ CreateConstraintSpace(TextDirection::kRtl, WritingMode::kHorizontalTb);
+ vertical_lr_space_ =
+ CreateConstraintSpace(TextDirection::kLtr, WritingMode::kVerticalLr);
+ vertical_rl_space_ =
+ CreateConstraintSpace(TextDirection::kLtr, WritingMode::kVerticalRl);
}
void SetHorizontalStyle(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.cc
deleted file mode 100644
index 0899ba13b26..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h"
-
-#include "third_party/blink/renderer/core/style/computed_style.h"
-
-namespace blink {
-
-NGBaseFragmentBuilder::NGBaseFragmentBuilder(
- scoped_refptr<const ComputedStyle> style,
- WritingMode writing_mode,
- TextDirection direction)
- : style_(std::move(style)),
- writing_mode_(writing_mode),
- direction_(direction),
- style_variant_(NGStyleVariant::kStandard) {
- DCHECK(style_);
-}
-
-NGBaseFragmentBuilder::NGBaseFragmentBuilder(WritingMode writing_mode,
- TextDirection direction)
- : writing_mode_(writing_mode), direction_(direction) {}
-
-NGBaseFragmentBuilder::~NGBaseFragmentBuilder() = default;
-
-NGBaseFragmentBuilder& NGBaseFragmentBuilder::SetStyle(
- scoped_refptr<const ComputedStyle> style,
- NGStyleVariant style_variant) {
- DCHECK(style);
- style_ = std::move(style);
- style_variant_ = style_variant;
- return *this;
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h
deleted file mode 100644
index 5d8c6103645..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef NGBaseFragmentBuilder_h
-#define NGBaseFragmentBuilder_h
-
-#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_style_variant.h"
-#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/text/writing_mode.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-
-namespace blink {
-
-class ComputedStyle;
-
-class CORE_EXPORT NGBaseFragmentBuilder {
- STACK_ALLOCATED();
- public:
- virtual ~NGBaseFragmentBuilder();
-
- const ComputedStyle& Style() const {
- DCHECK(style_);
- return *style_;
- }
- NGBaseFragmentBuilder& SetStyleVariant(NGStyleVariant style_variant) {
- style_variant_ = style_variant;
- return *this;
- }
- NGBaseFragmentBuilder& SetStyle(scoped_refptr<const ComputedStyle>,
- NGStyleVariant);
-
- WritingMode GetWritingMode() const { return writing_mode_; }
- TextDirection Direction() const { return direction_; }
-
- protected:
- NGBaseFragmentBuilder(scoped_refptr<const ComputedStyle>,
- WritingMode,
- TextDirection);
- NGBaseFragmentBuilder(WritingMode, TextDirection);
-
- private:
- scoped_refptr<const ComputedStyle> style_;
- WritingMode writing_mode_;
- TextDirection direction_;
-
- protected:
- NGStyleVariant style_variant_;
-};
-
-} // namespace blink
-
-#endif // NGBaseFragmentBuilder
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc
index fa48c1f17f8..1f64fa00c22 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc
@@ -37,9 +37,8 @@ NGBaseLayoutAlgorithmTest::RunBlockLayoutAlgorithmForElement(Element* element) {
scoped_refptr<NGLayoutResult> result =
NGBlockLayoutAlgorithm(node, space).Layout();
- return std::make_pair(
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get()),
- std::move(space));
+ return std::make_pair(ToNGPhysicalBoxFragment(result->PhysicalFragment()),
+ std::move(space));
}
scoped_refptr<const NGPhysicalBoxFragment>
@@ -87,17 +86,15 @@ NGConstraintSpace ConstructBlockLayoutTestConstraintSpace(
? NGFragmentationType::kFragmentColumn
: NGFragmentationType::kFragmentNone;
- return NGConstraintSpaceBuilder(
- writing_mode,
- /* icb_size */ NGPhysicalSize(LayoutUnit(800), LayoutUnit(600)))
+ return NGConstraintSpaceBuilder(writing_mode, writing_mode,
+ is_new_formatting_context)
.SetAvailableSize(size)
.SetPercentageResolutionSize(size)
.SetTextDirection(direction)
.SetIsShrinkToFit(shrink_to_fit)
- .SetIsNewFormattingContext(is_new_formatting_context)
.SetFragmentainerSpaceAtBfcStart(fragmentainer_space_available)
.SetFragmentationType(block_fragmentation)
- .ToConstraintSpace(writing_mode);
+ .ToConstraintSpace();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc
index 5b81b529f57..69eee903ba2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc
@@ -11,12 +11,16 @@ namespace blink {
NGBlockBreakToken::NGBlockBreakToken(
NGLayoutInputNode node,
LayoutUnit used_block_size,
- Vector<scoped_refptr<NGBreakToken>>& child_break_tokens,
+ const NGBreakTokenVector& child_break_tokens,
bool has_last_resort_break)
: NGBreakToken(kBlockBreakToken, kUnfinished, node),
used_block_size_(used_block_size),
- has_last_resort_break_(has_last_resort_break) {
- child_break_tokens_.swap(child_break_tokens);
+ has_last_resort_break_(has_last_resort_break),
+ num_children_(child_break_tokens.size()) {
+ for (wtf_size_t i = 0; i < child_break_tokens.size(); ++i) {
+ child_break_tokens_[i] = child_break_tokens[i].get();
+ child_break_tokens_[i]->AddRef();
+ }
}
NGBlockBreakToken::NGBlockBreakToken(NGLayoutInputNode node,
@@ -24,10 +28,11 @@ NGBlockBreakToken::NGBlockBreakToken(NGLayoutInputNode node,
bool has_last_resort_break)
: NGBreakToken(kBlockBreakToken, kFinished, node),
used_block_size_(used_block_size),
- has_last_resort_break_(has_last_resort_break) {}
+ has_last_resort_break_(has_last_resort_break),
+ num_children_(0) {}
NGBlockBreakToken::NGBlockBreakToken(NGLayoutInputNode node)
- : NGBreakToken(kBlockBreakToken, kUnfinished, node) {}
+ : NGBreakToken(kBlockBreakToken, kUnfinished, node), num_children_(0) {}
#ifndef NDEBUG
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h
index be8ea67d1d1..cef4eab54ad 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h
@@ -8,29 +8,52 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
// Represents a break token for a block node.
-class CORE_EXPORT NGBlockBreakToken : public NGBreakToken {
+class CORE_EXPORT NGBlockBreakToken final : public NGBreakToken {
public:
+ class ChildTokenList {
+ public:
+ ChildTokenList(wtf_size_t count, const NGBreakToken* const* buffer)
+ : count_(count), buffer_(buffer) {}
+
+ wtf_size_t size() const { return count_; }
+ const NGBreakToken* operator[](wtf_size_t idx) const {
+ return buffer_[idx];
+ }
+
+ const NGBreakToken* const* begin() const { return buffer_; }
+ const NGBreakToken* const* end() const { return begin() + count_; }
+
+ private:
+ wtf_size_t count_;
+ const NGBreakToken* const* buffer_;
+ };
+
// Creates a break token for a node which did fragment, and can potentially
// produce more fragments.
//
- // The NGBlockBreakToken takes ownership of child_break_tokens, leaving it
- // empty for the caller.
- //
// The node is NGBlockNode, or any other NGLayoutInputNode that produces
// anonymous box.
static scoped_refptr<NGBlockBreakToken> Create(
NGLayoutInputNode node,
LayoutUnit used_block_size,
- Vector<scoped_refptr<NGBreakToken>>& child_break_tokens,
+ const NGBreakTokenVector& child_break_tokens,
bool has_last_resort_break = false) {
- return base::AdoptRef(new NGBlockBreakToken(
- node, used_block_size, child_break_tokens, has_last_resort_break));
+ // We store the children list inline in the break token as a flexible
+ // array. Therefore, we need to make sure to allocate enough space for
+ // that array here, which requires a manual allocation + placement new.
+ void* data = ::WTF::Partitions::FastMalloc(
+ sizeof(NGBlockBreakToken) +
+ child_break_tokens.size() * sizeof(NGBreakToken*),
+ ::WTF::GetStringWithTypeName<NGBlockBreakToken>());
+ new (data) NGBlockBreakToken(node, used_block_size, child_break_tokens,
+ has_last_resort_break);
+ return base::AdoptRef(static_cast<NGBlockBreakToken*>(data));
}
// Creates a break token for a node which cannot produce any more fragments.
@@ -52,6 +75,11 @@ class CORE_EXPORT NGBlockBreakToken : public NGBreakToken {
return base::AdoptRef(token);
}
+ ~NGBlockBreakToken() override {
+ for (const NGBreakToken* token : ChildBreakTokens())
+ token->Release();
+ }
+
// Represents the amount of block size used in previous fragments.
//
// E.g. if the layout block specifies a block size of 200px, and the previous
@@ -75,8 +103,8 @@ class CORE_EXPORT NGBlockBreakToken : public NGBreakToken {
// this child).
//
// A child which we haven't visited yet doesn't have a break token here.
- const Vector<scoped_refptr<NGBreakToken>>& ChildBreakTokens() const {
- return child_break_tokens_;
+ const ChildTokenList ChildBreakTokens() const {
+ return ChildTokenList(num_children_, &child_break_tokens_[0]);
}
#ifndef NDEBUG
@@ -84,9 +112,11 @@ class CORE_EXPORT NGBlockBreakToken : public NGBreakToken {
#endif
private:
+ // Must only be called from Create(), because it assumes that enough space
+ // has been allocated in the flexible array to store the children.
NGBlockBreakToken(NGLayoutInputNode node,
LayoutUnit used_block_size,
- Vector<scoped_refptr<NGBreakToken>>& child_break_tokens,
+ const NGBreakTokenVector& child_break_tokens,
bool has_last_resort_break);
NGBlockBreakToken(NGLayoutInputNode node,
@@ -95,7 +125,6 @@ class CORE_EXPORT NGBlockBreakToken : public NGBreakToken {
explicit NGBlockBreakToken(NGLayoutInputNode node);
- Vector<scoped_refptr<NGBreakToken>> child_break_tokens_;
LayoutUnit used_block_size_;
bool is_break_before_ = false;
@@ -104,6 +133,10 @@ class CORE_EXPORT NGBlockBreakToken : public NGBreakToken {
// unavoidable, but we should only break here if we cannot find a better break
// point further up in the ancestry.
bool has_last_resort_break_ = false;
+
+ wtf_size_t num_children_;
+ // This must be the last member, because it is a flexible array.
+ NGBreakToken* child_break_tokens_[];
};
DEFINE_TYPE_CASTS(NGBlockBreakToken,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc
index e3b8336fa24..00309e85615 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc
@@ -62,10 +62,10 @@ NGBlockChildIterator::Entry NGBlockChildIterator::NextChild(
// structure will not be of any help at all, since the break tokens will
// be associated with nodes that are not siblings.
while (child_token_idx_ < child_break_tokens.size()) {
- const auto& token = child_break_tokens[child_token_idx_];
+ const auto* token = child_break_tokens[child_token_idx_];
child_token_idx_++;
if (!token->IsFinished())
- return Entry(token->InputNode(), token.get());
+ return Entry(token->InputNode(), token);
}
return Entry(nullptr, nullptr);
}
@@ -78,7 +78,7 @@ NGBlockChildIterator::Entry NGBlockChildIterator::NextChild(
// This child break token candidate doesn't match the current node, this
// node must be unfinished.
const NGBreakToken* child_break_token_candidate =
- child_break_tokens[child_token_idx_].get();
+ child_break_tokens[child_token_idx_];
if (child_break_token_candidate->InputNode() != child_)
break;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h
index 106e5242a76..fcda3a4be81 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h
@@ -39,7 +39,7 @@ class CORE_EXPORT NGBlockChildIterator {
// An index into break_token_'s ChildBreakTokens() vector. Used for keeping
// track of the next child break token to inspect.
- size_t child_token_idx_;
+ wtf_size_t child_token_idx_;
bool resuming_at_inline_formatting_context_ = false;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc
index 5b315e8cada..ecee6ef67b5 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc
@@ -54,7 +54,7 @@ TEST_F(NGBlockChildIteratorTest, BreakTokenWithFinishedChild) {
NGLayoutInputNode node2 = node1.NextSibling();
NGLayoutInputNode node3 = node2.NextSibling();
- Vector<scoped_refptr<NGBreakToken>> child_break_tokens;
+ NGBreakTokenVector child_break_tokens;
child_break_tokens.push_back(NGBlockBreakToken::Create(node1, LayoutUnit()));
scoped_refptr<NGBlockBreakToken> parent_token =
NGBlockBreakToken::Create(container, LayoutUnit(50), child_break_tokens);
@@ -93,12 +93,14 @@ TEST_F(NGBlockChildIteratorTest, BreakTokenWithUnFinishedChild) {
NGLayoutInputNode node2 = node1.NextSibling();
NGLayoutInputNode node3 = node2.NextSibling();
- Vector<scoped_refptr<NGBreakToken>> child_break_tokens;
+ NGBreakTokenVector child_break_tokens;
scoped_refptr<NGBreakToken> child_token =
NGBlockBreakToken::Create(node1, LayoutUnit(), child_break_tokens);
+ child_break_tokens.clear();
child_break_tokens.push_back(child_token);
scoped_refptr<NGBlockBreakToken> parent_token =
NGBlockBreakToken::Create(container, LayoutUnit(50), child_break_tokens);
+ child_break_tokens.clear();
// The iterator should loop through three children, one with a break token.
NGBlockChildIterator iterator(node1, parent_token.get());
@@ -111,9 +113,11 @@ TEST_F(NGBlockChildIteratorTest, BreakTokenWithUnFinishedChild) {
child_token =
NGBlockBreakToken::Create(node2, LayoutUnit(), child_break_tokens);
+ child_break_tokens.clear();
child_break_tokens.push_back(child_token);
parent_token =
NGBlockBreakToken::Create(container, LayoutUnit(50), child_break_tokens);
+ child_break_tokens.clear();
// The first break token is for the #child2. That means that everything
// preceding it (i.e. #child1) has already been finished. The break token for
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
index 156f1664dbf..c5e715369eb 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
@@ -10,15 +10,16 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_floats_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
@@ -28,6 +29,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
#include "third_party/blink/renderer/core/layout/text_autosizer.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
@@ -40,8 +42,9 @@ namespace {
// since that's what clearance is all about. This means that if we have any such
// floats to clear, we know for sure that we get clearance, even before layout.
inline bool HasClearancePastAdjoiningFloats(NGFloatTypes adjoining_floats,
- const ComputedStyle& child_style) {
- return ToFloatTypes(child_style.Clear()) & adjoining_floats;
+ const ComputedStyle& child_style,
+ const ComputedStyle& cb_style) {
+ return ToFloatTypes(ResolvedClear(child_style, cb_style)) & adjoining_floats;
}
// Adjust BFC block offset for clearance, if applicable. Return true of
@@ -78,7 +81,7 @@ bool ApplyClearance(const NGConstraintSpace& constraint_space,
// Returns if the resulting fragment should be considered an "empty block".
// There is special casing for fragments like this, e.g. margins "collapse
// through", etc.
-bool IsEmptyBlock(bool is_new_fc, const NGLayoutResult& layout_result) {
+inline bool IsEmptyBlock(bool is_new_fc, const NGLayoutResult& layout_result) {
// TODO(ikilpatrick): This should be a DCHECK.
if (is_new_fc)
return false;
@@ -101,8 +104,8 @@ bool IsEmptyBlock(bool is_new_fc, const NGLayoutResult& layout_result) {
}
// As above; for convenience if you have a child_space.
-bool IsEmptyBlock(const NGConstraintSpace& child_space,
- const NGLayoutResult& layout_result) {
+inline bool IsEmptyBlock(const NGConstraintSpace& child_space,
+ const NGLayoutResult& layout_result) {
return IsEmptyBlock(child_space.IsNewFormattingContext(), layout_result);
}
@@ -166,7 +169,9 @@ NGBlockLayoutAlgorithm::NGBlockLayoutAlgorithm(
const NGBlockBreakToken* break_token)
: NGLayoutAlgorithm(node, space, break_token),
is_resuming_(break_token && !break_token->IsBreakBefore()),
- exclusion_space_(space.ExclusionSpace()) {}
+ exclusion_space_(space.ExclusionSpace()) {
+ container_builder_.SetIsNewFormattingContext(space.IsNewFormattingContext());
+}
// Define the destructor here, so that we can forward-declare more in the
// header.
@@ -195,21 +200,13 @@ base::Optional<MinMaxSize> NGBlockLayoutAlgorithm::ComputeMinMaxSize(
LayoutUnit float_left_inline_size = input.float_left_inline_size;
LayoutUnit float_right_inline_size = input.float_right_inline_size;
- LayoutUnit extrinsic_block_size = ComputeBlockSizeForFragment(
- ConstraintSpace(), Style(), NGSizeIndefinite, border_padding);
- if (extrinsic_block_size != NGSizeIndefinite) {
- extrinsic_block_size -=
- (border_padding + Node().GetScrollbarSizes()).BlockSum();
- extrinsic_block_size = extrinsic_block_size.ClampNegativeToZero();
- }
-
for (NGLayoutInputNode child = Node().FirstChild(); child;
child = child.NextSibling()) {
if (child.IsOutOfFlowPositioned() || child.IsColumnSpanAll())
continue;
const ComputedStyle& child_style = child.Style();
- const EClear child_clear = child_style.Clear();
+ const EClear child_clear = ResolvedClear(child_style, Style());
bool child_is_new_fc = child.CreatesNewFormattingContext();
// Conceptually floats and a single new-FC would just get positioned on a
@@ -233,10 +230,8 @@ base::Optional<MinMaxSize> NGBlockLayoutAlgorithm::ComputeMinMaxSize(
}
MinMaxSizeInput child_input;
- if (child.IsInline() || child.IsAnonymousBlock()) {
- child_input = {float_left_inline_size, float_right_inline_size,
- extrinsic_block_size};
- }
+ if (child.IsInline() || child.IsAnonymousBlock())
+ child_input = {float_left_inline_size, float_right_inline_size};
MinMaxSize child_sizes;
if (child.IsInline()) {
@@ -245,27 +240,12 @@ base::Optional<MinMaxSize> NGBlockLayoutAlgorithm::ComputeMinMaxSize(
// all inline nodes following |child| and their descendants, and produces
// an anonymous box that contains all line boxes.
// |NextSibling| returns the next block sibling, or nullptr, skipping all
- // following inline siblings and descendants. We'll pass our constraint
- // space here, so that floated orthogonal flow roots can calculate an
- // extrinsic constraint space.
- child_sizes = child.ComputeMinMaxSize(Style().GetWritingMode(),
- child_input, &constraint_space_);
+ // following inline siblings and descendants.
+ child_sizes =
+ child.ComputeMinMaxSize(Style().GetWritingMode(), child_input);
} else {
- // We'll need extrinsic sizing data when computing min/max for orthogonal
- // flow roots. If the child is a block node, we can check that right away,
- // but if it's inline, there's no way of telling; there may be floated
- // children that establish an orthogonal flow root.
- NGConstraintSpace extrinsic_constraint_space;
- const NGConstraintSpace* optional_constraint_space = nullptr;
- if (!IsParallelWritingMode(Style().GetWritingMode(),
- child.Style().GetWritingMode())) {
- extrinsic_constraint_space = CreateExtrinsicConstraintSpaceForChild(
- ConstraintSpace(), extrinsic_block_size, child);
- optional_constraint_space = &extrinsic_constraint_space;
- }
- child_sizes = ComputeMinAndMaxContentContribution(
- Style().GetWritingMode(), child, child_input,
- optional_constraint_space);
+ child_sizes =
+ ComputeMinAndMaxContentContribution(Style(), child, child_input);
}
DCHECK_LE(child_sizes.min_size, child_sizes.max_size) << child.ToString();
@@ -282,7 +262,7 @@ base::Optional<MinMaxSize> NGBlockLayoutAlgorithm::ComputeMinMaxSize(
// the content area, by e.g., negative margins. Such floats do not affect
// the content size.
if (float_inline_size > 0) {
- if (child_style.Floating() == EFloat::kLeft)
+ if (ResolvedFloating(child_style, Style()) == EFloat::kLeft)
float_left_inline_size += float_inline_size;
else
float_right_inline_size += float_inline_size;
@@ -368,15 +348,15 @@ NGLogicalOffset NGBlockLayoutAlgorithm::CalculateLogicalOffset(
scoped_refptr<NGLayoutResult> NGBlockLayoutAlgorithm::Layout() {
NGBoxStrut borders = ComputeBorders(ConstraintSpace(), Node());
NGBoxStrut padding = ComputePadding(ConstraintSpace(), Style());
-
border_padding_ = borders + padding;
- NGLogicalSize border_box_size = CalculateBorderBoxSize(
- ConstraintSpace(), Node(), CalculateDefaultBlockSize(), border_padding_);
NGBoxStrut scrollbars = Node().GetScrollbarSizes();
border_scrollbar_padding_ = ConstraintSpace().IsAnonymous()
? NGBoxStrut()
: border_padding_ + scrollbars;
+ NGLogicalSize border_box_size = CalculateBorderBoxSize(
+ ConstraintSpace(), Node(), CalculateDefaultBlockSize(), border_padding_);
+
child_available_size_ =
ShrinkAvailableSize(border_box_size, border_scrollbar_padding_);
@@ -404,6 +384,8 @@ scoped_refptr<NGLayoutResult> NGBlockLayoutAlgorithm::Layout() {
ComputeIntrinsicPadding(ConstraintSpace(), Node());
border_scrollbar_padding_ += intrinsic_padding;
+ if (ConstraintSpace().HasBlockFragmentation())
+ container_builder_.SetNeedsFinishedBreakToken();
container_builder_.SetInlineSize(border_box_size.inline_size);
container_builder_.SetBfcLineOffset(
ConstraintSpace().BfcOffset().line_offset);
@@ -504,8 +486,10 @@ scoped_refptr<NGLayoutResult> NGBlockLayoutAlgorithm::Layout() {
TextAutosizer::NGLayoutScope text_autosizer_layout_scope(
Node(), border_box_size.inline_size);
+ // Try to reuse line box fragments from cached fragments if possible.
+ // When possible, this adds fragments to |container_builder_| and update
+ // |previous_inflow_position| and |BreakToken()|.
scoped_refptr<const NGBreakToken> previous_inline_break_token;
-
NGBlockChildIterator child_iterator(Node().FirstChild(), BreakToken());
for (auto entry = child_iterator.NextChild();
NGLayoutInputNode child = entry.node;
@@ -527,7 +511,8 @@ scoped_refptr<NGLayoutResult> NGBlockLayoutAlgorithm::Layout() {
// all the way to the root of the fragmentation context without finding
// any such container, we have no valid class A break point, and if a
// forced break was requested, none will be inserted.
- container_builder_.SetInitialBreakBefore(child.Style().BreakBefore());
+ if (!child.IsInline())
+ container_builder_.SetInitialBreakBefore(child.Style().BreakBefore());
bool success =
child.CreatesNewFormattingContext()
@@ -706,6 +691,114 @@ scoped_refptr<NGLayoutResult> NGBlockLayoutAlgorithm::Layout() {
return container_builder_.ToBoxFragment();
}
+const NGPaintFragment* NGBlockLayoutAlgorithm::ReusableLineBoxContainer(
+ NGInlineNode inline_node) const {
+ // If floats are intruding into this node, re-layout may be needed.
+ if (!exclusion_space_.IsEmpty() || !unpositioned_floats_.IsEmpty())
+ return nullptr;
+
+ // Cached fragments are not for intermediate layout.
+ if (constraint_space_.IsIntermediateLayout())
+ return nullptr;
+
+ // Block fragmentation is not supported yet.
+ if (constraint_space_.HasBlockFragmentation())
+ return nullptr;
+
+ // Laying out from a break token is not supported yet, because this logic
+ // synthesize a break token.
+ if (BreakToken())
+ return nullptr;
+
+ // Re-use from a NGPaintFragment, because currently dirty flags are on
+ // NGPaintFragment.
+ const NGPaintFragment* paint_fragment = inline_node.PaintFragment();
+ if (!paint_fragment)
+ return nullptr;
+
+ if (!inline_node.PrepareReuseFragments(constraint_space_))
+ return nullptr;
+
+ return paint_fragment;
+}
+
+const NGBreakToken* NGBlockLayoutAlgorithm::TryReuseFragmentsFromCache(
+ NGInlineNode inline_node,
+ NGPreviousInflowPosition* previous_inflow_position,
+ bool* aborted_out) {
+ const NGPaintFragment* lineboxes = ReusableLineBoxContainer(inline_node);
+ if (!lineboxes)
+ return nullptr;
+
+ // Following is a copy of logic from HandleInFlow(). They need to keep in
+ // sync.
+ if (inline_node.IsEmptyInline())
+ return nullptr;
+ if (!ResolveBfcBlockOffset(previous_inflow_position)) {
+ *aborted_out = true;
+ return nullptr;
+ }
+ DCHECK(container_builder_.BfcBlockOffset());
+
+ WritingMode writing_mode = container_builder_.GetWritingMode();
+ TextDirection direction = container_builder_.Direction();
+ DCHECK_EQ(writing_mode, lineboxes->Style().GetWritingMode());
+ DCHECK_EQ(direction, lineboxes->Style().Direction());
+ const NGPhysicalSize outer_size = lineboxes->Size();
+
+ struct FragmentWithLogicalOffset {
+ const NGPhysicalFragment& fragment;
+ NGLogicalOffset offset;
+ };
+ Vector<FragmentWithLogicalOffset, 64> fragments;
+ fragments.ReserveInitialCapacity(lineboxes->Children().size());
+ for (const NGPaintFragment* child : lineboxes->Children()) {
+ if (child->IsDirty())
+ break;
+
+ // Abort if there are floats, oof, or list marker. They need re-layout.
+ const NGPhysicalFragment& child_fragment = child->PhysicalFragment();
+ if (!child_fragment.IsLineBox())
+ return nullptr;
+
+ NGLogicalOffset logical_offset = child->Offset().ConvertToLogical(
+ writing_mode, direction, outer_size, child_fragment.Size());
+ fragments.push_back(
+ FragmentWithLogicalOffset{child_fragment, logical_offset});
+ }
+ if (fragments.IsEmpty())
+ return nullptr;
+
+ // TODO(kojii): Running the normal layout code at least once for this child
+ // helps reducing the code to setup internal states after the reuse. Remove
+ // the last fragment if it is the end of the fragmentation to do so, but we
+ // should figure out how to setup the states without doing this.
+ DCHECK(fragments.back().fragment.BreakToken());
+ if (fragments.back().fragment.BreakToken()->IsFinished()) {
+ fragments.Shrink(fragments.size() - 1);
+ if (fragments.IsEmpty())
+ return nullptr;
+ }
+
+ for (const auto& fragment : fragments) {
+ container_builder_.AddChild(&fragment.fragment, fragment.offset);
+ }
+
+ // Update the internal states to after the re-used fragments.
+ const auto& last_fragment = fragments.back();
+ LayoutUnit used_block_size =
+ last_fragment.offset.block_offset +
+ last_fragment.fragment.Size().ConvertToLogical(writing_mode).block_size;
+ previous_inflow_position->logical_block_offset = used_block_size;
+
+ // In order to layout the rest of lines, return the break token from the last
+ // reused line box.
+ NGBreakToken* last_break_token = last_fragment.fragment.BreakToken();
+ DCHECK(last_break_token);
+ DCHECK(!last_break_token->IsFinished());
+ return last_break_token;
+}
+
void NGBlockLayoutAlgorithm::HandleOutOfFlowPositioned(
const NGPreviousInflowPosition& previous_inflow_position,
NGBlockNode child) {
@@ -736,7 +829,8 @@ void NGBlockLayoutAlgorithm::HandleFloat(
NGBlockNode child,
const NGBlockBreakToken* child_break_token) {
AddUnpositionedFloat(&unpositioned_floats_, &container_builder_,
- NGUnpositionedFloat(child, child_break_token));
+ NGUnpositionedFloat(child, child_break_token),
+ ConstraintSpace());
// If there is a break token for a float we must be resuming layout, we must
// always know our position in the BFC.
@@ -771,10 +865,10 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
const ComputedStyle& child_style = child.Style();
const TextDirection direction = ConstraintSpace().Direction();
bool has_clearance_past_adjoining_floats = HasClearancePastAdjoiningFloats(
- container_builder_.AdjoiningFloatTypes(), child_style);
- NGInflowChildData child_data =
- ComputeChildData(*previous_inflow_position, child, child_break_token,
- has_clearance_past_adjoining_floats);
+ container_builder_.AdjoiningFloatTypes(), child_style, Style());
+ NGInflowChildData child_data = ComputeChildData(
+ *previous_inflow_position, child, child_break_token,
+ has_clearance_past_adjoining_floats, /* is_new_fc */ true);
LayoutUnit child_origin_line_offset =
ConstraintSpace().BfcOffset().line_offset +
@@ -964,7 +1058,7 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
PositionOrPropagateListMarker(*layout_result, &logical_offset);
container_builder_.AddChild(*layout_result, logical_offset);
- container_builder_.PropagateBreak(layout_result);
+ container_builder_.PropagateBreak(*layout_result);
// The margins we store will be used by e.g. getComputedStyle().
// When calculating these values, ignore any floats that might have
@@ -991,8 +1085,9 @@ NGBlockLayoutAlgorithm::LayoutNewFormattingContext(
bool abort_if_cleared) {
// The origin offset is where we should start looking for layout
// opportunities. It needs to be adjusted by the child's clearance.
- AdjustToClearance(exclusion_space_.ClearanceOffset(child.Style().Clear()),
- &origin_offset);
+ AdjustToClearance(
+ exclusion_space_.ClearanceOffset(ResolvedClear(child.Style(), Style())),
+ &origin_offset);
DCHECK(container_builder_.BfcBlockOffset());
// Before we lay out, figure out how much inline space we have available at
@@ -1089,27 +1184,41 @@ bool NGBlockLayoutAlgorithm::HandleInflow(
DCHECK(!child.IsOutOfFlowPositioned());
DCHECK(!child.CreatesNewFormattingContext());
+ if (child.IsInline() && !child_break_token) {
+ DCHECK(!*previous_inline_break_token);
+ bool aborted = false;
+ *previous_inline_break_token = TryReuseFragmentsFromCache(
+ ToNGInlineNode(child), previous_inflow_position, &aborted);
+ if (*previous_inline_break_token)
+ return true;
+ if (aborted)
+ return false;
+ }
+
bool is_non_empty_inline =
child.IsInline() && !ToNGInlineNode(child).IsEmptyInline();
bool has_clearance_past_adjoining_floats =
child.IsBlock() &&
HasClearancePastAdjoiningFloats(container_builder_.AdjoiningFloatTypes(),
- child.Style());
+ child.Style(), Style());
// If we can separate the previous margin strut from what is to follow, do
// that. Then we're able to resolve *our* BFC block offset and position any
// pending floats. There are two situations where this is necessary:
// 1. If the child is to be cleared by adjoining floats.
// 2. If the child is a non-empty inline.
+ //
+ // Note this logic is copied to TryReuseFragmentsFromCache(), they need to
+ // keep in sync.
if (has_clearance_past_adjoining_floats || is_non_empty_inline) {
if (!ResolveBfcBlockOffset(previous_inflow_position))
return false;
}
// Perform layout on the child.
- NGInflowChildData child_data =
- ComputeChildData(*previous_inflow_position, child, child_break_token,
- has_clearance_past_adjoining_floats);
+ NGInflowChildData child_data = ComputeChildData(
+ *previous_inflow_position, child, child_break_token,
+ has_clearance_past_adjoining_floats, /* is_new_fc */ false);
NGConstraintSpace child_space =
CreateConstraintSpaceForChild(child, child_data, child_available_size_);
scoped_refptr<NGLayoutResult> layout_result = child.Layout(
@@ -1315,10 +1424,22 @@ bool NGBlockLayoutAlgorithm::HandleInflow(
container_builder_.AddChild(*layout_result, logical_offset);
if (child.IsBlock())
- container_builder_.PropagateBreak(layout_result);
+ container_builder_.PropagateBreak(*layout_result);
+
+ if (child.IsBlock()) {
+ // We haven't yet resolved margins wrt. overconstrainedness, unless that was
+ // also required to calculate line-left offset (due to block alignment)
+ // before layout. Do so now, so that we store the correct values (which is
+ // required by e.g. getComputedStyle()).
+ if (!child_data.margins_fully_resolved) {
+ ResolveInlineMargins(child.Style(), Style(),
+ child_available_size_.inline_size,
+ fragment.InlineSize(), &child_data.margins);
+ child_data.margins_fully_resolved = true;
+ }
- if (child.IsBlock())
ToNGBlockNode(child).StoreMargins(ConstraintSpace(), child_data.margins);
+ }
*previous_inflow_position = ComputeInflowPosition(
*previous_inflow_position, child, child_data, child_bfc_block_offset,
@@ -1336,12 +1457,16 @@ NGInflowChildData NGBlockLayoutAlgorithm::ComputeChildData(
const NGPreviousInflowPosition& previous_inflow_position,
NGLayoutInputNode child,
const NGBreakToken* child_break_token,
- bool force_clearance) {
+ bool force_clearance,
+ bool is_new_fc) {
DCHECK(child);
DCHECK(!child.IsFloating());
+ DCHECK_EQ(is_new_fc, child.CreatesNewFormattingContext());
// Calculate margins in parent's writing mode.
- NGBoxStrut margins = CalculateMargins(child, child_break_token);
+ bool margins_fully_resolved;
+ NGBoxStrut margins = CalculateMargins(child, is_new_fc, child_break_token,
+ &margins_fully_resolved);
// Append the current margin strut with child's block start margin.
// Non empty border/padding, and new FC use cases are handled inside of the
@@ -1367,7 +1492,8 @@ NGInflowChildData NGBlockLayoutAlgorithm::ComputeChildData(
margins.LineLeft(ConstraintSpace().Direction()),
BfcBlockOffset() + logical_block_offset};
- return {child_bfc_offset, margin_strut, margins, force_clearance};
+ return {child_bfc_offset, margin_strut, margins,
+ margins_fully_resolved, force_clearance, is_new_fc};
}
NGPreviousInflowPosition NGBlockLayoutAlgorithm::ComputeInflowPosition(
@@ -1382,8 +1508,7 @@ NGPreviousInflowPosition NGBlockLayoutAlgorithm::ComputeInflowPosition(
// Determine the child's end logical offset, for the next child to use.
LayoutUnit logical_block_offset;
- bool is_empty_block =
- IsEmptyBlock(child.CreatesNewFormattingContext(), layout_result);
+ bool is_empty_block = IsEmptyBlock(child_data.is_new_fc, layout_result);
if (is_empty_block) {
// The default behaviour for empty blocks is they just pass through the
// previous inflow position.
@@ -1798,26 +1923,48 @@ NGBlockLayoutAlgorithm::BreakType NGBlockLayoutAlgorithm::BreakTypeBeforeChild(
NGBoxStrut NGBlockLayoutAlgorithm::CalculateMargins(
NGLayoutInputNode child,
- const NGBreakToken* child_break_token) {
+ bool is_new_fc,
+ const NGBreakToken* child_break_token,
+ bool* margins_fully_resolved) {
+ // We need to at least partially resolve margins before creating a constraint
+ // space for layout. Layout needs to know the line-left offset before
+ // starting. If the line-left offset cannot be calculated without fully
+ // resolving the margins (because of block alignment), we have to create a
+ // temporary constraint space now to figure out the inline size first. In all
+ // other cases we'll postpone full resolution until after child layout, when
+ // we actually have a child constraint space to use (and know the inline
+ // size).
+ *margins_fully_resolved = false;
+
DCHECK(child);
if (child.IsInline())
return {};
const ComputedStyle& child_style = child.Style();
+ bool needs_inline_size =
+ NeedsInlineSizeToResolveLineLeft(child_style, Style());
+ if (!needs_inline_size && !child_style.HasMargin())
+ return {};
- NGConstraintSpace space =
- NGConstraintSpaceBuilder(ConstraintSpace())
- .SetAvailableSize(child_available_size_)
- .SetPercentageResolutionSize(child_percentage_size_)
- .ToConstraintSpace(child_style.GetWritingMode());
-
- NGBoxStrut margins = ComputeMarginsFor(space, child_style, ConstraintSpace());
+ NGBoxStrut margins = ComputeMarginsFor(
+ child_style, child_percentage_size_.inline_size,
+ ConstraintSpace().GetWritingMode(), ConstraintSpace().Direction());
if (ShouldIgnoreBlockStartMargin(ConstraintSpace(), child, child_break_token))
margins.block_start = LayoutUnit();
// As long as the child isn't establishing a new formatting context, we need
- // to resolve auto margins before layout, to be able to position child floats
- // correctly.
- if (!child.CreatesNewFormattingContext()) {
+ // to know its line-left offset before layout, to be able to position child
+ // floats correctly. If we need to resolve auto margins or other alignment
+ // properties to calculate the line-left offset, we also need to calculate its
+ // inline size first.
+ if (!is_new_fc && needs_inline_size) {
+ NGConstraintSpace space =
+ NGConstraintSpaceBuilder(ConstraintSpace(),
+ child_style.GetWritingMode(),
+ /* is_new_fc */ false)
+ .SetAvailableSize(child_available_size_)
+ .SetPercentageResolutionSize(child_percentage_size_)
+ .ToConstraintSpace();
+
NGBoxStrut child_border_padding =
ComputeBorders(space, child) + ComputePadding(space, child.Style());
LayoutUnit child_inline_size =
@@ -1826,6 +1973,7 @@ NGBoxStrut NGBlockLayoutAlgorithm::CalculateMargins(
ResolveInlineMargins(child_style, Style(),
space.AvailableSize().inline_size, child_inline_size,
&margins);
+ *margins_fully_resolved = true;
}
return margins;
}
@@ -1835,66 +1983,70 @@ NGConstraintSpace NGBlockLayoutAlgorithm::CreateConstraintSpaceForChild(
const NGInflowChildData& child_data,
const NGLogicalSize child_available_size,
const base::Optional<LayoutUnit> floats_bfc_block_offset) {
- NGConstraintSpaceBuilder space_builder(ConstraintSpace());
+ const ComputedStyle& style = Style();
+ const ComputedStyle& child_style = child.Style();
+ WritingMode child_writing_mode =
+ child.IsInline() ? style.GetWritingMode() : child_style.GetWritingMode();
+
+ NGConstraintSpaceBuilder builder(ConstraintSpace(), child_writing_mode,
+ child_data.is_new_fc);
+ SetOrthogonalFallbackInlineSizeIfNeeded(Style(), child, &builder);
- space_builder.SetAvailableSize(child_available_size)
+ if (!IsParallelWritingMode(ConstraintSpace().GetWritingMode(),
+ child_writing_mode))
+ builder.SetIsShrinkToFit(child_style.LogicalWidth().IsAuto());
+
+ builder.SetAvailableSize(child_available_size)
.SetPercentageResolutionSize(child_percentage_size_)
.SetReplacedPercentageResolutionSize(replaced_child_percentage_size_);
if (Node().IsTableCell()) {
// If we have a fixed block-size we are in the "layout" phase.
- space_builder.SetTableCellChildLayoutPhase(
+ builder.SetTableCellChildLayoutPhase(
ConstraintSpace().IsFixedSizeBlock()
? NGTableCellChildLayoutPhase::kLayout
: NGTableCellChildLayoutPhase::kMeasure);
}
if (NGBaseline::ShouldPropagateBaselines(child))
- space_builder.AddBaselineRequests(ConstraintSpace().BaselineRequests());
+ builder.AddBaselineRequests(ConstraintSpace().BaselineRequests());
- bool is_new_fc = child.CreatesNewFormattingContext();
- space_builder.SetIsNewFormattingContext(is_new_fc)
- .SetBfcOffset(child_data.bfc_offset_estimate)
+ builder.SetBfcOffset(child_data.bfc_offset_estimate)
.SetMarginStrut(child_data.margin_strut);
if (!container_builder_.BfcBlockOffset() &&
ConstraintSpace().FloatsBfcBlockOffset()) {
- space_builder.SetFloatsBfcBlockOffset(
+ builder.SetFloatsBfcBlockOffset(
ConstraintSpace().FloatsBfcBlockOffset().value());
}
if (floats_bfc_block_offset)
- space_builder.SetFloatsBfcBlockOffset(floats_bfc_block_offset);
+ builder.SetFloatsBfcBlockOffset(floats_bfc_block_offset);
- WritingMode writing_mode;
LayoutUnit clearance_offset = constraint_space_.IsNewFormattingContext()
? LayoutUnit::Min()
: ConstraintSpace().ClearanceOffset();
- if (child.IsInline()) {
- writing_mode = Style().GetWritingMode();
- } else {
- const ComputedStyle& child_style = child.Style();
+ if (child.IsBlock()) {
LayoutUnit child_clearance_offset =
- exclusion_space_.ClearanceOffset(child_style.Clear());
+ exclusion_space_.ClearanceOffset(ResolvedClear(child_style, Style()));
clearance_offset = std::max(clearance_offset, child_clearance_offset);
- space_builder.SetIsShrinkToFit(ShouldShrinkToFit(Style(), child_style));
- space_builder.SetTextDirection(child_style.Direction());
- writing_mode = child_style.GetWritingMode();
+ builder.SetTextDirection(child_style.Direction());
// PositionListMarker() requires a first line baseline.
if (container_builder_.UnpositionedListMarker()) {
- space_builder.AddBaselineRequest(
- {NGBaselineAlgorithmType::kFirstLine, Style().GetFontBaseline()});
+ builder.AddBaselineRequest(
+ {NGBaselineAlgorithmType::kFirstLine, style.GetFontBaseline()});
}
+ } else {
+ builder.SetTextDirection(style.Direction());
}
- space_builder.SetClearanceOffset(clearance_offset);
+ builder.SetClearanceOffset(clearance_offset);
if (child_data.force_clearance)
- space_builder.SetShouldForceClearance(true);
+ builder.SetShouldForceClearance(true);
- if (!is_new_fc) {
- space_builder.SetExclusionSpace(exclusion_space_);
- space_builder.SetAdjoiningFloatTypes(
- container_builder_.AdjoiningFloatTypes());
+ if (!child_data.is_new_fc) {
+ builder.SetExclusionSpace(exclusion_space_);
+ builder.SetAdjoiningFloatTypes(container_builder_.AdjoiningFloatTypes());
}
LayoutUnit space_available;
@@ -1903,29 +2055,30 @@ NGConstraintSpace NGBlockLayoutAlgorithm::CreateConstraintSpaceForChild(
// If a block establishes a new formatting context we must know our
// position in the formatting context, and are able to adjust the
// fragmentation line.
- if (is_new_fc) {
+ if (child_data.is_new_fc) {
space_available -= child_data.bfc_offset_estimate.block_offset;
}
// The policy regarding collapsing block-start margin with the fragmentainer
// block-start is the same throughout the entire fragmentainer (although it
// really only matters at the beginning of each fragmentainer, we don't need
// to bother to check whether we're actually at the start).
- space_builder.SetSeparateLeadingFragmentainerMargins(
+ builder.SetSeparateLeadingFragmentainerMargins(
ConstraintSpace().HasSeparateLeadingFragmentainerMargins());
+ builder.SetFragmentainerBlockSize(
+ ConstraintSpace().FragmentainerBlockSize());
+ builder.SetFragmentainerSpaceAtBfcStart(space_available);
+ builder.SetFragmentationType(ConstraintSpace().BlockFragmentationType());
}
- space_builder.SetFragmentainerBlockSize(
- ConstraintSpace().FragmentainerBlockSize());
- space_builder.SetFragmentainerSpaceAtBfcStart(space_available);
- space_builder.SetFragmentationType(
- ConstraintSpace().BlockFragmentationType());
- return space_builder.ToConstraintSpace(writing_mode);
+ return builder.ToConstraintSpace();
}
LayoutUnit NGBlockLayoutAlgorithm::ComputeLineBoxBaselineOffset(
const NGBaselineRequest& request,
const NGPhysicalLineBoxFragment& line_box,
LayoutUnit line_box_block_offset) const {
- NGLineHeightMetrics metrics = line_box.BaselineMetrics(request.baseline_type);
+ NGLineHeightMetrics metrics =
+ line_box.BaselineMetrics(request.BaselineType());
+ DCHECK(!metrics.IsEmpty());
// NGLineHeightMetrics is line-relative, which matches to the flow-relative
// unless this box is in flipped-lines writing-mode.
@@ -1957,9 +2110,9 @@ bool NGBlockLayoutAlgorithm::AddBaseline(const NGBaselineRequest& request,
const NGPhysicalLineBoxFragment* line_box =
ToNGPhysicalLineBoxFragment(child);
- // Skip over a line-box which is empty. These don't any baselines which
+ // Skip over a line-box which is empty. These don't have any baselines which
// should be added.
- if (line_box->Children().IsEmpty())
+ if (line_box->IsEmptyLineBox())
return false;
LayoutUnit offset =
@@ -1973,8 +2126,8 @@ bool NGBlockLayoutAlgorithm::AddBaseline(const NGBaselineRequest& request,
if (child->IsBox()) {
const NGPhysicalBoxFragment* box = ToNGPhysicalBoxFragment(child);
- if (const NGBaseline* baseline = box->Baseline(request)) {
- container_builder_.AddBaseline(request, baseline->offset + child_offset);
+ if (base::Optional<LayoutUnit> baseline = box->Baseline(request)) {
+ container_builder_.AddBaseline(request, baseline.value() + child_offset);
return true;
}
}
@@ -1985,13 +2138,12 @@ bool NGBlockLayoutAlgorithm::AddBaseline(const NGBaselineRequest& request,
// Propagate computed baselines from children.
// Skip children that do not produce baselines (e.g., empty blocks.)
void NGBlockLayoutAlgorithm::PropagateBaselinesFromChildren() {
- const Vector<NGBaselineRequest>& requests =
- ConstraintSpace().BaselineRequests();
+ const NGBaselineRequestList requests = ConstraintSpace().BaselineRequests();
if (requests.IsEmpty())
return;
for (const auto& request : requests) {
- switch (request.algorithm_type) {
+ switch (request.AlgorithmType()) {
case NGBaselineAlgorithmType::kAtomicInline:
if (Node().UseLogicalBottomMarginEdgeForInlineBlockBaseline())
break;
@@ -2076,19 +2228,14 @@ void NGBlockLayoutAlgorithm::PositionPendingFloats(
border_scrollbar_padding_.LineLeft(ConstraintSpace().Direction()),
origin_block_offset};
- LayoutUnit bfc_block_offset =
- container_builder_.BfcBlockOffset()
- ? container_builder_.BfcBlockOffset().value()
- : ConstraintSpace().FloatsBfcBlockOffset().value();
-
- const auto positioned_floats = PositionFloats(
- child_available_size_, child_percentage_size_,
- replaced_child_percentage_size_, origin_bfc_offset, bfc_block_offset,
- unpositioned_floats_, ConstraintSpace(), &exclusion_space_);
+ NGPositionedFloatVector positioned_floats;
+ PositionFloats(child_available_size_, child_percentage_size_,
+ replaced_child_percentage_size_, origin_bfc_offset,
+ unpositioned_floats_, ConstraintSpace(), Style(),
+ &exclusion_space_, &positioned_floats);
AddPositionedFloats(positioned_floats);
-
- unpositioned_floats_.clear();
+ unpositioned_floats_.Shrink(0);
}
template <class Vec>
@@ -2117,7 +2264,7 @@ void NGBlockLayoutAlgorithm::AddPositionedFloats(const Vec& positioned_floats) {
container_builder_.AddChild(*positioned_float.layout_result,
logical_offset);
- container_builder_.PropagateBreak(positioned_float.layout_result);
+ container_builder_.PropagateBreak(*positioned_float.layout_result);
}
}
@@ -2125,14 +2272,11 @@ void NGBlockLayoutAlgorithm::AddPositionedFloats(const Vec& positioned_floats) {
// containing block. Percentage resolution size is minimal size
// that would fill the ICB.
LayoutUnit NGBlockLayoutAlgorithm::CalculateDefaultBlockSize() {
- if (!Node().GetDocument().InQuirksMode())
- return NGSizeIndefinite;
-
- bool is_quirky_element = Node().IsDocumentElement() || Node().IsBody();
- if (is_quirky_element && !Style().HasOutOfFlowPosition()) {
+ if (Node().IsQuirkyAndFillsViewport()) {
LayoutUnit block_size = ConstraintSpace().AvailableSize().block_size;
block_size -= ComputeMarginsForSelf(ConstraintSpace(), Style()).BlockSum();
- return block_size.ClampNegativeToZero();
+ return std::max(block_size.ClampNegativeToZero(),
+ border_scrollbar_padding_.BlockSum());
}
return NGSizeIndefinite;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
index 76264bdc9ad..e8bca18b6f6 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
@@ -12,8 +12,8 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_floats_utils.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float_vector.h"
@@ -39,14 +39,16 @@ struct NGInflowChildData {
NGBfcOffset bfc_offset_estimate;
NGMarginStrut margin_strut;
NGBoxStrut margins;
+ bool margins_fully_resolved;
bool force_clearance;
+ bool is_new_fc;
};
// A class for general block layout (e.g. a <div> with no special style).
// Lays out the children in sequence.
class CORE_EXPORT NGBlockLayoutAlgorithm
: public NGLayoutAlgorithm<NGBlockNode,
- NGFragmentBuilder,
+ NGBoxFragmentBuilder,
NGBlockBreakToken> {
public:
// Default constructor.
@@ -86,7 +88,9 @@ class CORE_EXPORT NGBlockLayoutAlgorithm
}
NGBoxStrut CalculateMargins(NGLayoutInputNode child,
- const NGBreakToken* child_break_token);
+ bool is_new_fc,
+ const NGBreakToken* child_break_token,
+ bool* margins_fully_resolved);
// Creates a new constraint space for the current child.
NGConstraintSpace CreateConstraintSpaceForChild(
@@ -99,7 +103,8 @@ class CORE_EXPORT NGBlockLayoutAlgorithm
NGInflowChildData ComputeChildData(const NGPreviousInflowPosition&,
NGLayoutInputNode,
const NGBreakToken* child_break_token,
- bool force_clearance);
+ bool force_clearance,
+ bool is_new_fc);
NGPreviousInflowPosition ComputeInflowPosition(
const NGPreviousInflowPosition&,
@@ -124,6 +129,18 @@ class CORE_EXPORT NGBlockLayoutAlgorithm
const NGInflowChildData& child_data,
const NGLayoutResult&) const;
+ // Find the container of reusable line boxes. Returns nullptr if there are no
+ // reusable line boxes.
+ const NGPaintFragment* ReusableLineBoxContainer(NGInlineNode child) const;
+
+ // Try to reuse part of cached fragments. When reusing is possible, this
+ // function adds part of cached fragments to |container_builder_|, update
+ // |break_token_| to continue layout from the last reused fragment, and
+ // returns |true|. Otherwise returns |false|.
+ const NGBreakToken* TryReuseFragmentsFromCache(NGInlineNode child,
+ NGPreviousInflowPosition*,
+ bool* abort_out);
+
void HandleOutOfFlowPositioned(const NGPreviousInflowPosition&, NGBlockNode);
void HandleFloat(const NGPreviousInflowPosition&,
NGBlockNode,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc
index ae17cc183ae..20dda1742e4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc
@@ -39,7 +39,7 @@ class NGBlockLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
scoped_refptr<NGLayoutResult> result =
NGBlockLayoutAlgorithm(node, space).Layout();
- return ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ return ToNGPhysicalBoxFragment(result->PhysicalFragment());
}
MinMaxSize RunComputeMinAndMax(NGBlockNode node) {
@@ -95,12 +95,12 @@ TEST_F(NGBlockLayoutAlgorithmTest, Caching) {
ScopedLayoutNGFragmentCachingForTest layout_ng_fragment_caching(true);
SetBodyInnerHTML(R"HTML(
- <div id="box" style="width:30px; height:40px"></div>
+ <div id="box" style="width:30px; height:40%;"></div>
)HTML");
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(100), NGSizeIndefinite));
+ NGLogicalSize(LayoutUnit(100), LayoutUnit(100)));
LayoutBlockFlow* block_flow =
ToLayoutBlockFlow(GetLayoutObjectByElementId("box"));
@@ -117,14 +117,22 @@ TEST_F(NGBlockLayoutAlgorithmTest, Caching) {
// Test identical, but not pointer-equal, constraint space
space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(100), NGSizeIndefinite));
+ NGLogicalSize(LayoutUnit(100), LayoutUnit(100)));
result = block_flow->CachedLayoutResult(space, nullptr);
EXPECT_NE(result.get(), nullptr);
// Test different constraint space
space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(200), NGSizeIndefinite));
+ NGLogicalSize(LayoutUnit(200), LayoutUnit(100)));
+ result = block_flow->CachedLayoutResult(space, nullptr);
+ EXPECT_NE(result.get(), nullptr);
+
+ // Test a different constraint space that will actually result in a different
+ // size.
+ space = ConstructBlockLayoutTestConstraintSpace(
+ WritingMode::kHorizontalTb, TextDirection::kLtr,
+ NGLogicalSize(LayoutUnit(200), LayoutUnit(200)));
result = block_flow->CachedLayoutResult(space, nullptr);
EXPECT_EQ(result.get(), nullptr);
@@ -747,7 +755,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, CollapsingMarginsEmptyBlockWithClearance) {
MutableStyleForElement(inflow_element)->SetMarginTop(inflow_margin_top);
inflow_element->GetLayoutObject()->SetNeedsLayout("");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutNGBlockFlow* child;
// #float
@@ -847,7 +855,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, NewFormattingContextAutoMargins) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
- #container { width: 200px; direction: rtl; }
+ #container { width: 200px; direction: rtl; display: flow-root; }
#float { width: 100px; height: 60px; background: hotpink; float: left; }
#newfc { direction: rtl; width: 50px; height: 20px; background: green; overflow: hidden; }
</style>
@@ -1100,14 +1108,12 @@ TEST_F(NGBlockLayoutAlgorithmTest, PositionFloatInsideEmptyBlocks) {
->MutableSet();
ASSERT_EQ(2UL, floating_objects.size());
auto left_floating_object = floating_objects.TakeFirst();
- ASSERT_TRUE(left_floating_object->IsPlaced());
// 80 = float_inline_offset(25) + accumulative offset of empty blocks(35 + 20)
EXPECT_THAT(left_floating_object->X(), LayoutUnit(15));
// 10 = left float's margin
EXPECT_THAT(left_floating_object->Y(), LayoutUnit());
auto right_floating_object = floating_objects.TakeFirst();
- ASSERT_TRUE(right_floating_object->IsPlaced());
// 150 = float_inline_offset(25) +
// right float offset(125)
EXPECT_THAT(right_floating_object->X(), LayoutUnit(140));
@@ -1664,8 +1670,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, NoFragmentation) {
NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
// We should only have one 150x200 fragment with no fragmentation.
scoped_refptr<const NGPhysicalFragment> fragment =
@@ -1692,8 +1698,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, SimpleFragmentation) {
NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
@@ -1738,8 +1744,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, InnerChildrenFragmentation) {
NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
@@ -1806,8 +1812,8 @@ TEST_F(NGBlockLayoutAlgorithmTest,
NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
@@ -1872,8 +1878,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, InnerChildrenFragmentationSmallHeight) {
NGBlockNode node(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
@@ -1915,6 +1921,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationParallelFlows) {
#container {
width: 150px;
height: 50px;
+ display: flow-root;
}
#float1 {
width: 50px;
@@ -1939,8 +1946,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationParallelFlows) {
NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
@@ -1962,8 +1969,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationParallelFlows) {
space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
fragment = NGBlockLayoutAlgorithm(node, space,
ToNGBlockBreakToken(fragment->BreakToken()))
.Layout()
@@ -2026,7 +2033,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationOrthogonalFlows) {
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
EXPECT_EQ(NGPhysicalSize(LayoutUnit(150), LayoutUnit(60)), fragment->Size());
- ASSERT_TRUE(fragment->BreakToken()->IsFinished());
+ ASSERT_TRUE(!fragment->BreakToken() || fragment->BreakToken()->IsFinished());
// float2 should only have one fragment.
FragmentChildIterator iterator(ToNGPhysicalBoxFragment(fragment.get()));
@@ -2035,7 +2042,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationOrthogonalFlows) {
child = iterator.NextChild(&offset);
EXPECT_EQ(NGPhysicalSize(LayoutUnit(60), LayoutUnit(200)), child->Size());
EXPECT_EQ(NGPhysicalOffset(LayoutUnit(90), LayoutUnit(50)), offset);
- ASSERT_TRUE(child->BreakToken()->IsFinished());
+ ASSERT_TRUE(!child->BreakToken() || child->BreakToken()->IsFinished());
}
// Tests that a float child inside a zero height block fragments correctly.
@@ -2046,6 +2053,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationZeroHeight) {
#container {
width: 150px;
height: 50px;
+ display: flow-root;
}
#float {
width: 75px;
@@ -2066,8 +2074,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationZeroHeight) {
NGBlockNode node(ToLayoutBlockFlow(GetLayoutObjectByElementId("container")));
NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
scoped_refptr<const NGPhysicalFragment> fragment =
NGBlockLayoutAlgorithm(node, space).Layout()->PhysicalFragment();
@@ -2086,8 +2094,8 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationZeroHeight) {
space = ConstructBlockLayoutTestConstraintSpace(
WritingMode::kHorizontalTb, TextDirection::kLtr,
- NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false, true,
- kFragmentainerSpaceAvailable);
+ NGLogicalSize(LayoutUnit(1000), NGSizeIndefinite), false,
+ node.CreatesNewFormattingContext(), kFragmentainerSpaceAvailable);
fragment = NGBlockLayoutAlgorithm(node, space,
ToNGBlockBreakToken(fragment->BreakToken()))
.Layout()
@@ -2294,7 +2302,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, RootFragmentOffsetInsideLegacy) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const LayoutObject* innerNGRoot = GetLayoutObjectByElementId("innerNGRoot");
ASSERT_TRUE(innerNGRoot->IsLayoutNGMixin());
@@ -2314,7 +2322,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, DetailsFlexDoesntCrash) {
SetBodyInnerHTML(R"HTML(
<details style="display:flex"></details>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// No crash is good.
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
index 972033db071..10fee840917 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/html/html_marquee_element.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_fieldset.h"
+#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_set.h"
#include "third_party/blink/renderer/core/layout/min_max_size.h"
@@ -19,18 +20,19 @@
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/layout/shapes/shape_outside_info.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
@@ -103,8 +105,7 @@ void UpdateLegacyMultiColumnFlowThread(
if (!has_processed_first_child) {
// The offset of the flow thread should be the same as that of the first
// first column.
- flow_thread->SetX(child.Offset().left);
- flow_thread->SetY(child.Offset().top);
+ flow_thread->SetLocation(child.Offset().ToLayoutPoint());
flow_thread->SetLogicalWidth(child_fragment.InlineSize());
column_block_size = child_fragment.BlockSize();
has_processed_first_child = true;
@@ -134,12 +135,12 @@ void UpdateLegacyMultiColumnFlowThread(
}
NGConstraintSpaceBuilder CreateConstraintSpaceBuilderForMinMax(
- NGBlockNode node,
- NGPhysicalSize icb_size) {
- return NGConstraintSpaceBuilder(node.Style().GetWritingMode(), icb_size)
+ NGBlockNode node) {
+ return NGConstraintSpaceBuilder(node.Style().GetWritingMode(),
+ node.Style().GetWritingMode(),
+ node.CreatesNewFormattingContext())
.SetTextDirection(node.Style().Direction())
.SetIsIntermediateLayout(true)
- .SetIsNewFormattingContext(node.CreatesNewFormattingContext())
.SetFloatsBfcBlockOffset(LayoutUnit());
}
@@ -148,9 +149,9 @@ LayoutUnit CalculateAvailableInlineSizeForLegacy(
const NGConstraintSpace& space) {
if (box.StyleRef().LogicalWidth().IsPercent()) {
if (box.ShouldComputeSizeAsReplaced())
- return space.ReplacedPercentageResolutionSize().inline_size;
+ return space.ReplacedPercentageResolutionInlineSize();
- return space.PercentageResolutionSize().inline_size;
+ return space.PercentageResolutionInlineSize();
}
return space.AvailableSize().inline_size;
@@ -161,9 +162,9 @@ LayoutUnit CalculateAvailableBlockSizeForLegacy(
const NGConstraintSpace& space) {
if (box.StyleRef().LogicalHeight().IsPercent()) {
if (box.ShouldComputeSizeAsReplaced())
- return space.ReplacedPercentageResolutionSize().block_size;
+ return space.ReplacedPercentageResolutionBlockSize();
- return space.PercentageResolutionSize().block_size;
+ return space.PercentageResolutionBlockSize();
}
return space.AvailableSize().block_size;
@@ -181,16 +182,19 @@ scoped_refptr<NGLayoutResult> NGBlockNode::Layout(
LayoutBlockFlow* block_flow =
box_->IsLayoutNGMixin() ? ToLayoutBlockFlow(box_) : nullptr;
+ if (RuntimeEnabledFeatures::TrackLayoutPassesPerBlockEnabled() && block_flow)
+ block_flow->IncrementLayoutPassCount();
+
NGLayoutInputNode first_child = FirstChild();
scoped_refptr<NGLayoutResult> layout_result;
- if (box_->IsLayoutNGMixin()) {
- layout_result = ToLayoutBlockFlow(box_)->CachedLayoutResult(
- constraint_space, break_token);
+ if (block_flow) {
+ layout_result =
+ block_flow->CachedLayoutResult(constraint_space, break_token);
if (layout_result) {
// TODO(layoutng): Figure out why these two call can't be inside the
// !constraint_space.IsIntermediateLayout() block below.
UpdateShapeOutsideInfoIfNeeded(
- constraint_space.PercentageResolutionSize().inline_size);
+ *layout_result, constraint_space.PercentageResolutionInlineSize());
// We may need paint invalidation even if we can reuse layout, as our
// paint offset/visual rect may have changed due to relative
// positioning changes. Otherwise we fail fast/css/
@@ -204,8 +208,8 @@ scoped_refptr<NGLayoutResult> NGBlockNode::Layout(
// LayoutNGMixin::CurrentFragment and therefore has to be up-to-date.
// In particular, that fragment would have an incorrect offset if we
// don't re-set the result here.
- ToLayoutBlockFlow(box_)->SetCachedLayoutResult(
- constraint_space, break_token, *layout_result);
+ block_flow->SetCachedLayoutResult(constraint_space, break_token,
+ *layout_result);
if (!constraint_space.IsIntermediateLayout() && first_child &&
first_child.IsInline()) {
block_flow->UpdatePaintFragmentFromCachedLayoutResult(
@@ -214,12 +218,6 @@ scoped_refptr<NGLayoutResult> NGBlockNode::Layout(
}
return layout_result;
}
- // Cached fragment was stale. Its fragment children might point to
- // deleted LayoutObjects.
- // Removing cached result to ensure that stale children cannot be
- // reached through LayoutNGMixin::CurrentFragment.
- if (box_->NeedsLayout())
- ToLayoutBlockFlow(box_)->ClearCachedLayoutResult();
}
// This follows the code from LayoutBox::UpdateLogicalWidth
@@ -246,7 +244,7 @@ scoped_refptr<NGLayoutResult> NGBlockNode::Layout(
layout_result = LayoutWithAlgorithm(*this, constraint_space, break_token,
/* ignored */ nullptr);
- FinishLayout(constraint_space, break_token, layout_result);
+ FinishLayout(block_flow, constraint_space, break_token, layout_result);
if (old_scrollbars != GetScrollbarSizes()) {
// If our scrollbars have changed, we need to relayout because either:
// - Our size has changed (if shrinking to fit), or
@@ -258,11 +256,30 @@ scoped_refptr<NGLayoutResult> NGBlockNode::Layout(
// and a child gained a vertical scrollbar. However, no test fails
// without that check.
PaintLayerScrollableArea::FreezeScrollbarsScope freeze_scrollbars;
+
+ // Scrollbar changes are hard to detect. Make sure everyone gets the
+ // message.
+ box_->SetNeedsLayout(layout_invalidation_reason::kScrollbarChanged,
+ kMarkOnlyThis);
+
layout_result = LayoutWithAlgorithm(*this, constraint_space, break_token,
/* ignored */ nullptr);
- FinishLayout(constraint_space, break_token, layout_result);
+ FinishLayout(block_flow, constraint_space, break_token, layout_result);
}
+ // We always need to update the ShapeOutsideInfo even if the layout is
+ // intermediate (e.g. called during a min/max pass).
+ //
+ // If a shape-outside float is present in an orthogonal flow, when
+ // calculating the min/max-size (by performing an intermediate layout), we
+ // might calculate this incorrectly, as the layout won't take into account the
+ // shape-outside area.
+ //
+ // TODO(ikilpatrick): This should be fixed by moving the shape-outside data
+ // to the NGLayoutResult, removing this "side" data-structure.
+ UpdateShapeOutsideInfoIfNeeded(
+ *layout_result, constraint_space.PercentageResolutionInlineSize());
+
return layout_result;
}
@@ -280,7 +297,8 @@ void NGBlockNode::PrepareForLayout() {
ToLayoutNGListItem(box_)->UpdateMarkerTextIfNeeded();
}
-void NGBlockNode::FinishLayout(const NGConstraintSpace& constraint_space,
+void NGBlockNode::FinishLayout(LayoutBlockFlow* block_flow,
+ const NGConstraintSpace& constraint_space,
const NGBreakToken* break_token,
scoped_refptr<NGLayoutResult> layout_result) {
if (!IsBlockLayoutComplete(constraint_space, *layout_result))
@@ -288,8 +306,7 @@ void NGBlockNode::FinishLayout(const NGConstraintSpace& constraint_space,
DCHECK(layout_result->PhysicalFragment());
- if (box_->IsLayoutNGMixin()) {
- LayoutBlockFlow* block_flow = ToLayoutBlockFlow(box_);
+ if (block_flow) {
block_flow->SetCachedLayoutResult(constraint_space, break_token,
*layout_result);
NGLayoutInputNode first_child = FirstChild();
@@ -330,12 +347,8 @@ MinMaxSize NGBlockNode::ComputeMinMaxSize(
return ComputeMinMaxSizeFromLegacy(input.size_type);
}
- NGPhysicalSize icb_size = constraint_space
- ? constraint_space->InitialContainingBlockSize()
- : InitialContainingBlockSize();
NGConstraintSpace zero_constraint_space =
- CreateConstraintSpaceBuilderForMinMax(*this, icb_size)
- .ToConstraintSpace(Style().GetWritingMode());
+ CreateConstraintSpaceBuilderForMinMax(*this).ToConstraintSpace();
if (!constraint_space) {
// Using the zero-sized constraint space when measuring for an orthogonal
@@ -388,10 +401,10 @@ MinMaxSize NGBlockNode::ComputeMinMaxSize(
// Now, redo with infinite space for max_content
NGConstraintSpace infinite_constraint_space =
- CreateConstraintSpaceBuilderForMinMax(*this, icb_size)
+ CreateConstraintSpaceBuilderForMinMax(*this)
.SetAvailableSize({LayoutUnit::Max(), LayoutUnit()})
.SetPercentageResolutionSize({LayoutUnit(), LayoutUnit()})
- .ToConstraintSpace(Style().GetWritingMode());
+ .ToConstraintSpace();
layout_result = Layout(infinite_constraint_space);
NGBoxFragment max_fragment(
@@ -496,7 +509,7 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
const NGConstraintSpace& constraint_space,
const NGLayoutResult& layout_result) {
DCHECK(layout_result.PhysicalFragment());
- if (constraint_space.IsIntermediateLayout())
+ if (UNLIKELY(constraint_space.IsIntermediateLayout()))
return;
const NGPhysicalBoxFragment& physical_fragment =
@@ -513,7 +526,7 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
// legacy layout doesn't support non-uniform fragmentainer widths.
LayoutUnit logical_height;
LayoutUnit intrinsic_content_logical_height;
- if (IsFirstFragment(constraint_space, physical_fragment)) {
+ if (LIKELY(IsFirstFragment(constraint_space, physical_fragment))) {
box_->SetLogicalWidth(fragment_logical_size.inline_size);
} else {
DCHECK_EQ(box_->LogicalWidth(), fragment_logical_size.inline_size)
@@ -533,7 +546,7 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
NGBoxStrut padding = fragment.Padding();
NGBoxStrut border_scrollbar_padding = borders + scrollbars + padding;
- if (IsLastFragment(physical_fragment))
+ if (LIKELY(IsLastFragment(physical_fragment)))
intrinsic_content_logical_height -= border_scrollbar_padding.BlockSum();
box_->SetLogicalHeight(logical_height);
box_->SetIntrinsicContentLogicalHeight(intrinsic_content_logical_height);
@@ -543,11 +556,11 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
box_->SetMargin(ComputePhysicalMargins(constraint_space, Style()));
LayoutMultiColumnFlowThread* flow_thread = GetFlowThread(*box_);
- if (flow_thread) {
+ if (UNLIKELY(flow_thread)) {
PlaceChildrenInFlowThread(constraint_space, physical_fragment);
} else {
NGPhysicalOffset offset_from_start;
- if (constraint_space.HasBlockFragmentation()) {
+ if (UNLIKELY(constraint_space.HasBlockFragmentation())) {
// Need to include any block space that this container has used in
// previous fragmentainers. The offset of children will be relative to
// the container, in flow thread coordinates, i.e. the model where
@@ -562,16 +575,17 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
offset_from_start);
}
- if (box_->IsLayoutBlock() && IsLastFragment(physical_fragment)) {
- LayoutBlock* block = ToLayoutBlock(box_);
+ LayoutBlock* block = ToLayoutBlockOrNull(box_);
+ if (LIKELY(block && IsLastFragment(physical_fragment))) {
LayoutUnit intrinsic_block_size = layout_result.IntrinsicBlockSize();
- if (constraint_space.HasBlockFragmentation()) {
+ if (UNLIKELY(constraint_space.HasBlockFragmentation())) {
intrinsic_block_size +=
PreviouslyUsedBlockSpace(constraint_space, physical_fragment);
}
- block->LayoutPositionedObjects(/* relayout_children */ false);
+ if (UNLIKELY(block->HasPositionedObjects()))
+ block->LayoutPositionedObjects(/* relayout_children */ false);
- if (flow_thread) {
+ if (UNLIKELY(flow_thread)) {
UpdateLegacyMultiColumnFlowThread(*this, flow_thread, constraint_space,
physical_fragment);
}
@@ -585,18 +599,10 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
box_->UpdateAfterLayout();
box_->ClearNeedsLayout();
- UpdateShapeOutsideInfoIfNeeded(
- constraint_space.PercentageResolutionSize().inline_size);
-
- if (box_->IsLayoutBlockFlow()) {
- LayoutBlockFlow* block_flow = ToLayoutBlockFlow(box_);
+ // Overflow computation depends on this being set.
+ LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(box_);
+ if (LIKELY(block_flow))
block_flow->UpdateIsSelfCollapsing();
-
- if (constraint_space.IsNewFormattingContext()) {
- block_flow->AddVisualOverflowFromFloats();
- block_flow->AddLayoutOverflowFromFloats();
- }
- }
}
void NGBlockNode::PlaceChildrenInLayoutBox(
@@ -694,14 +700,13 @@ void NGBlockNode::CopyChildFragmentPosition(
horizontal_offset = containing_block->Size().Width() - horizontal_offset -
fragment.Size().width;
}
- layout_box->SetX(horizontal_offset);
- layout_box->SetY(fragment_offset.top + additional_offset.top);
+ layout_box->SetLocation(LayoutPoint(
+ horizontal_offset, fragment_offset.top + additional_offset.top));
// Floats need an associated FloatingObject for painting.
if (IsFloatFragment(fragment) && containing_block->IsLayoutBlockFlow()) {
FloatingObject* floating_object =
ToLayoutBlockFlow(containing_block)->InsertFloatingObject(*layout_box);
- floating_object->SetIsInPlacedTree(false);
floating_object->SetShouldPaint(!layout_box->HasSelfPaintingLayer());
LayoutUnit horizontal_margin_edge_offset = horizontal_offset;
if (has_flipped_x_axis)
@@ -711,8 +716,15 @@ void NGBlockNode::CopyChildFragmentPosition(
floating_object->SetX(horizontal_margin_edge_offset);
floating_object->SetY(fragment_offset.top + additional_offset.top -
layout_box->MarginTop());
- floating_object->SetIsPlaced(true);
- floating_object->SetIsInPlacedTree(true);
+#if DCHECK_IS_ON()
+ // Being "placed" is a legacy thing. Make sure the flags remain unset in NG.
+ DCHECK(!floating_object->IsPlaced());
+ DCHECK(!floating_object->IsInPlacedTree());
+
+ // Set this flag to tell the float machinery that it's safe to read out
+ // position data.
+ floating_object->SetHasGeometry();
+#endif
}
}
@@ -742,6 +754,15 @@ void NGBlockNode::CopyFragmentDataToLayoutBoxForInlineChildren(
layout_box.SetLocation(maybe_flipped_offset.ToLayoutPoint());
}
+ // Legacy compatibility. This flag is used in paint layer for
+ // invalidation.
+ if (layout_object && layout_object->IsLayoutInline() &&
+ layout_object->StyleRef().HasOutline() &&
+ !layout_object->IsElementContinuation() &&
+ ToLayoutInline(layout_object)->Continuation()) {
+ box_->SetContainsInlineWithOutlineAndContinuation(true);
+ }
+
// The Location() of inline LayoutObject is relative to the
// LayoutBlockFlow. If |child| establishes a new block formatting context,
// it also creates another inline formatting context. Do not copy to its
@@ -774,30 +795,38 @@ bool NGBlockNode::UseLogicalBottomMarginEdgeForInlineBlockBaseline() const {
scoped_refptr<NGLayoutResult> NGBlockNode::LayoutAtomicInline(
const NGConstraintSpace& parent_constraint_space,
+ const ComputedStyle& parent_style,
FontBaseline baseline_type,
bool use_first_line_style) {
- NGConstraintSpaceBuilder space_builder(parent_constraint_space);
- space_builder.SetUseFirstLineStyle(use_first_line_style);
+ NGConstraintSpaceBuilder builder(
+ parent_constraint_space, Style().GetWritingMode(), /* is_new_fc */ true);
+ SetOrthogonalFallbackInlineSizeIfNeeded(parent_style, *this, &builder);
+
+ builder.SetUseFirstLineStyle(use_first_line_style);
// Request to compute baseline during the layout, except when we know the box
// would synthesize box-baseline.
- if (NGBaseline::ShouldPropagateBaselines(GetLayoutBox())) {
- space_builder.AddBaselineRequest(
+ LayoutBox* layout_box = GetLayoutBox();
+ if (NGBaseline::ShouldPropagateBaselines(layout_box)) {
+ builder.AddBaselineRequest(
{NGBaselineAlgorithmType::kAtomicInline, baseline_type});
}
- const ComputedStyle& style = Style();
NGConstraintSpace constraint_space =
- space_builder.SetIsNewFormattingContext(true)
- .SetIsShrinkToFit(true)
+ builder.SetIsShrinkToFit(Style().LogicalWidth().IsAuto())
.SetAvailableSize(parent_constraint_space.AvailableSize())
.SetPercentageResolutionSize(
parent_constraint_space.PercentageResolutionSize())
.SetReplacedPercentageResolutionSize(
parent_constraint_space.ReplacedPercentageResolutionSize())
- .SetTextDirection(style.Direction())
- .ToConstraintSpace(style.GetWritingMode());
- return Layout(constraint_space);
+ .SetTextDirection(Style().Direction())
+ .ToConstraintSpace();
+ scoped_refptr<NGLayoutResult> result = Layout(constraint_space);
+ // TODO(kojii): Investigate why ClearNeedsLayout() isn't called automatically
+ // when it's being laid out.
+ if (!constraint_space.IsIntermediateLayout())
+ layout_box->ClearNeedsLayout();
+ return result;
}
scoped_refptr<NGLayoutResult> NGBlockNode::RunOldLayout(
@@ -809,9 +838,9 @@ scoped_refptr<NGLayoutResult> NGBlockNode::RunOldLayout(
ToLayoutBlock(box_)->CreatesNewFormattingContext());
WritingMode writing_mode = Style().GetWritingMode();
+ LayoutBlock* block = box_->IsLayoutBlock() ? ToLayoutBlock(box_) : nullptr;
const NGConstraintSpace* old_space =
- box_->IsLayoutBlock() ? ToLayoutBlock(box_)->CachedConstraintSpace()
- : nullptr;
+ block ? block->CachedConstraintSpace() : nullptr;
if (!old_space || box_->NeedsLayout() || *old_space != constraint_space) {
LayoutUnit inline_size =
CalculateAvailableInlineSizeForLegacy(*box_, constraint_space);
@@ -845,7 +874,7 @@ scoped_refptr<NGLayoutResult> NGBlockNode::RunOldLayout(
}
box_->ComputeAndSetBlockDirectionMargins(box_->ContainingBlock());
- if (box_->IsLayoutNGMixin() && box_->NeedsLayout()) {
+ if (box_->NeedsLayout() && box_->IsLayoutNGMixin()) {
ToLayoutBlockFlow(box_)->LayoutBlockFlow::UpdateBlockLayout(true);
} else {
box_->ForceLayout();
@@ -856,13 +885,14 @@ scoped_refptr<NGLayoutResult> NGBlockNode::RunOldLayout(
// container (e.g. objects with intrinsic ratio and percentage block size)
// in a subsequent layout pass might otherwise become wrong.
box_->ClearOverrideContainingBlockContentSize();
- if (box_->IsLayoutBlock())
- ToLayoutBlock(box_)->SetCachedConstraintSpace(constraint_space);
+ if (block)
+ block->SetCachedConstraintSpace(constraint_space);
}
NGLogicalSize box_size(box_->LogicalWidth(), box_->LogicalHeight());
// TODO(kojii): Implement use_first_line_style.
- NGFragmentBuilder builder(*this, box_->Style(), writing_mode,
- box_->StyleRef().Direction());
+ NGBoxFragmentBuilder builder(*this, box_->Style(), writing_mode,
+ box_->StyleRef().Direction());
+ builder.SetIsNewFormattingContext(constraint_space.IsNewFormattingContext());
builder.SetIsOldLayoutRoot();
builder.SetInlineSize(box_size.inline_size);
builder.SetBlockSize(box_size.block_size);
@@ -874,16 +904,18 @@ scoped_refptr<NGLayoutResult> NGBlockNode::RunOldLayout(
builder.SetPadding(padding);
CopyBaselinesFromOldLayout(constraint_space, &builder);
+
+ scoped_refptr<NGLayoutResult> layout_result = builder.ToBoxFragment();
UpdateShapeOutsideInfoIfNeeded(
- constraint_space.PercentageResolutionSize().inline_size);
- return builder.ToBoxFragment();
+ *layout_result, constraint_space.PercentageResolutionInlineSize());
+
+ return layout_result;
}
void NGBlockNode::CopyBaselinesFromOldLayout(
const NGConstraintSpace& constraint_space,
- NGFragmentBuilder* builder) {
- const Vector<NGBaselineRequest>& requests =
- constraint_space.BaselineRequests();
+ NGBoxFragmentBuilder* builder) {
+ const NGBaselineRequestList requests = constraint_space.BaselineRequests();
if (requests.IsEmpty())
return;
@@ -891,7 +923,7 @@ void NGBlockNode::CopyBaselinesFromOldLayout(
return;
for (const auto& request : requests) {
- switch (request.algorithm_type) {
+ switch (request.AlgorithmType()) {
case NGBaselineAlgorithmType::kAtomicInline: {
LayoutUnit position =
AtomicInlineBaselineFromOldLayout(request, constraint_space);
@@ -920,7 +952,7 @@ LayoutUnit NGBlockNode::AtomicInlineBaselineFromOldLayout(
// classes override it assuming inline layout calls |BaselinePosition()|.
if (box_->IsInline()) {
LayoutUnit position = LayoutUnit(box_->BaselinePosition(
- request.baseline_type, constraint_space.UseFirstLineStyle(),
+ request.BaselineType(), constraint_space.UseFirstLineStyle(),
line_direction, kPositionOnContainingLine));
// BaselinePosition() uses margin edge for atomic inlines. Subtract
@@ -940,24 +972,29 @@ LayoutUnit NGBlockNode::AtomicInlineBaselineFromOldLayout(
// current shape machinery requires setting the size of the float after layout
// in the parents writing mode.
void NGBlockNode::UpdateShapeOutsideInfoIfNeeded(
+ const NGLayoutResult& layout_result,
LayoutUnit percentage_resolution_inline_size) {
if (!box_->IsFloating() || !box_->GetShapeOutsideInfo())
return;
+ // The box_ may not have a valid size yet (due to an intermediate layout),
+ // use the fragment's size instead.
+ DCHECK(layout_result.PhysicalFragment());
+ LayoutSize box_size = layout_result.PhysicalFragment()->Size().ToLayoutSize();
+
// TODO(ikilpatrick): Ideally this should be moved to a NGLayoutResult
// computing the shape area. There may be an issue with the new fragmentation
// model and computing the correct sizes of shapes.
ShapeOutsideInfo* shape_outside = box_->GetShapeOutsideInfo();
LayoutBlock* containing_block = box_->ContainingBlock();
shape_outside->SetReferenceBoxLogicalSize(
- containing_block->IsHorizontalWritingMode()
- ? box_->Size()
- : box_->Size().TransposedSize());
+ containing_block->IsHorizontalWritingMode() ? box_size
+ : box_size.TransposedSize());
shape_outside->SetPercentageResolutionInlineSize(
percentage_resolution_inline_size);
}
-void NGBlockNode::UseOldOutOfFlowPositioning() {
+void NGBlockNode::UseOldOutOfFlowPositioning() const {
DCHECK(box_->IsOutOfFlowPositioned());
box_->ContainingBlock()->InsertPositionedObject(box_);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.h
index ce12f580984..c3035be705e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.h
@@ -13,15 +13,15 @@
namespace blink {
class LayoutBox;
+class NGBaselineRequest;
class NGBreakToken;
class NGConstraintSpace;
-class NGFragmentBuilder;
+class NGBoxFragmentBuilder;
class NGLayoutResult;
class NGPhysicalBoxFragment;
class NGPhysicalContainerFragment;
class NGPhysicalFragment;
struct MinMaxSize;
-struct NGBaselineRequest;
struct NGBoxStrut;
struct NGLogicalOffset;
@@ -77,9 +77,11 @@ class CORE_EXPORT NGBlockNode final : public NGLayoutInputNode {
bool UseLogicalBottomMarginEdgeForInlineBlockBaseline() const;
// Layout an atomic inline; e.g., inline block.
- scoped_refptr<NGLayoutResult> LayoutAtomicInline(const NGConstraintSpace&,
- FontBaseline,
- bool use_first_line_style);
+ scoped_refptr<NGLayoutResult> LayoutAtomicInline(
+ const NGConstraintSpace& parent_constraint_space,
+ const ComputedStyle& parent_style,
+ FontBaseline,
+ bool use_first_line_style);
// Runs layout on the underlying LayoutObject and creates a fragment for the
// resulting geometry.
@@ -87,7 +89,7 @@ class CORE_EXPORT NGBlockNode final : public NGLayoutInputNode {
// Called if this is an out-of-flow block which needs to be
// positioned with legacy layout.
- void UseOldOutOfFlowPositioning();
+ void UseOldOutOfFlowPositioning() const;
// Save static position for legacy AbsPos layout.
void SaveStaticOffsetForLegacy(const NGLogicalOffset&,
@@ -104,7 +106,10 @@ class CORE_EXPORT NGBlockNode final : public NGLayoutInputNode {
private:
void PrepareForLayout();
- void FinishLayout(const NGConstraintSpace&,
+ // If this node is a LayoutNGMixin, the caller must pass the layout object for
+ // this node cast to a LayoutBlockFlow as the first argument.
+ void FinishLayout(LayoutBlockFlow*,
+ const NGConstraintSpace&,
const NGBreakToken*,
scoped_refptr<NGLayoutResult>);
@@ -127,11 +132,13 @@ class CORE_EXPORT NGBlockNode final : public NGLayoutInputNode {
const NGPhysicalOffset fragment_offset,
const NGPhysicalOffset additional_offset = NGPhysicalOffset());
- void CopyBaselinesFromOldLayout(const NGConstraintSpace&, NGFragmentBuilder*);
+ void CopyBaselinesFromOldLayout(const NGConstraintSpace&,
+ NGBoxFragmentBuilder*);
LayoutUnit AtomicInlineBaselineFromOldLayout(const NGBaselineRequest&,
const NGConstraintSpace&);
void UpdateShapeOutsideInfoIfNeeded(
+ const NGLayoutResult&,
LayoutUnit percentage_resolution_inline_size);
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc
index b5a5bf1bb27..2214302d5f3 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.cc
@@ -30,8 +30,9 @@ NGLineHeightMetrics NGBoxFragment::BaselineMetricsWithoutSynthesize(
}
// Check if we have a propagated baseline.
- if (const NGBaseline* baseline = physical_fragment.Baseline(request)) {
- LayoutUnit ascent = baseline->offset;
+ if (base::Optional<LayoutUnit> baseline =
+ physical_fragment.Baseline(request)) {
+ LayoutUnit ascent = baseline.value();
LayoutUnit descent = BlockSize() - ascent;
// For replaced elements, inline-block elements, and inline-table
@@ -78,7 +79,7 @@ NGLineHeightMetrics NGBoxFragment::BaselineMetrics(
block_size += layout_box.MarginLogicalWidth();
}
- if (request.baseline_type == kAlphabeticBaseline)
+ if (request.BaselineType() == kAlphabeticBaseline)
return NGLineHeightMetrics(block_size, LayoutUnit());
return NGLineHeightMetrics(block_size - block_size / 2, block_size / 2);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.h
index 921446d74fc..2595461f77b 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.h
@@ -13,7 +13,7 @@
namespace blink {
-struct NGBaselineRequest;
+class NGBaselineRequest;
struct NGLineHeightMetrics;
class CORE_EXPORT NGBoxFragment final : public NGFragment {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc
new file mode 100644
index 00000000000..f6d802b5056
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc
@@ -0,0 +1,268 @@
+// 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 "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
+
+#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
+
+namespace blink {
+
+void NGBoxFragmentBuilder::RemoveChildren() {
+ child_break_tokens_.resize(0);
+ inline_break_tokens_.resize(0);
+ children_.resize(0);
+ offsets_.resize(0);
+}
+
+NGBoxFragmentBuilder& NGBoxFragmentBuilder::AddBreakBeforeChild(
+ NGLayoutInputNode child) {
+ if (child.IsInline()) {
+ if (inline_break_tokens_.IsEmpty()) {
+ // In some cases we may want to break before the first line, as a last
+ // resort. We need a break token for that as well, so that the machinery
+ // will understand that we should resume at the beginning of the inline
+ // formatting context, rather than concluding that we're done with the
+ // whole thing.
+ inline_break_tokens_.push_back(NGInlineBreakToken::Create(
+ ToNGInlineNode(child), nullptr, 0, 0, NGInlineBreakToken::kDefault));
+ }
+ return *this;
+ }
+ auto token = NGBlockBreakToken::CreateBreakBefore(child);
+ child_break_tokens_.push_back(token);
+ return *this;
+}
+
+NGBoxFragmentBuilder& NGBoxFragmentBuilder::AddBreakBeforeLine(
+ int line_number) {
+ DCHECK_GT(line_number, 0);
+ DCHECK_LE(unsigned(line_number), inline_break_tokens_.size());
+ int lines_to_remove = inline_break_tokens_.size() - line_number;
+ if (lines_to_remove > 0) {
+ // Remove widows that should be pushed to the next fragment. We'll also
+ // remove all other child fragments than line boxes (typically floats) that
+ // come after the first line that's moved, as those also have to be re-laid
+ // out in the next fragment.
+ inline_break_tokens_.resize(line_number);
+ DCHECK_GT(children_.size(), 0UL);
+ for (int i = children_.size() - 1; i >= 0; i--) {
+ DCHECK_NE(i, 0);
+ if (!children_[i]->IsLineBox())
+ continue;
+ if (!--lines_to_remove) {
+ // This is the first line that is going to the next fragment. Remove it,
+ // and everything after it.
+ children_.resize(i);
+ offsets_.resize(i);
+ break;
+ }
+ }
+ }
+
+ // We need to resume at the right inline location in the next fragment, but
+ // broken floats, which are resumed and positioned by the parent block layout
+ // algorithm, need to be ignored by the inline layout algorithm.
+ ToNGInlineBreakToken(inline_break_tokens_.back().get())->SetIgnoreFloats();
+ return *this;
+}
+
+NGBoxFragmentBuilder& NGBoxFragmentBuilder::PropagateBreak(
+ const NGLayoutResult& child_layout_result) {
+ if (!did_break_)
+ PropagateBreak(*child_layout_result.PhysicalFragment());
+ if (child_layout_result.HasForcedBreak())
+ SetHasForcedBreak();
+ else
+ PropagateSpaceShortage(child_layout_result.MinimalSpaceShortage());
+ return *this;
+}
+
+NGBoxFragmentBuilder& NGBoxFragmentBuilder::PropagateBreak(
+ const NGPhysicalFragment& child_fragment) {
+ if (!did_break_) {
+ const auto* token = child_fragment.BreakToken();
+ did_break_ = token && !token->IsFinished();
+ }
+ return *this;
+}
+
+void NGBoxFragmentBuilder::AddOutOfFlowLegacyCandidate(
+ NGBlockNode node,
+ const NGStaticPosition& static_position,
+ LayoutObject* inline_container) {
+ DCHECK_GE(InlineSize(), LayoutUnit());
+ DCHECK_GE(BlockSize(), LayoutUnit());
+
+ NGOutOfFlowPositionedDescendant descendant{node, static_position,
+ inline_container};
+ // Need 0,0 physical coordinates as child offset. Because offset
+ // is stored as logical, must convert physical 0,0 to logical.
+ NGLogicalOffset zero_offset;
+ switch (GetWritingMode()) {
+ case WritingMode::kHorizontalTb:
+ if (IsLtr(Direction()))
+ zero_offset = NGLogicalOffset();
+ else
+ zero_offset = NGLogicalOffset(InlineSize(), LayoutUnit());
+ break;
+ case WritingMode::kVerticalRl:
+ case WritingMode::kSidewaysRl:
+ if (IsLtr(Direction()))
+ zero_offset = NGLogicalOffset(LayoutUnit(), BlockSize());
+ else
+ zero_offset = NGLogicalOffset(InlineSize(), BlockSize());
+ break;
+ case WritingMode::kVerticalLr:
+ case WritingMode::kSidewaysLr:
+ if (IsLtr(Direction()))
+ zero_offset = NGLogicalOffset();
+ else
+ zero_offset = NGLogicalOffset(InlineSize(), LayoutUnit());
+ break;
+ }
+ oof_positioned_candidates_.push_back(
+ NGOutOfFlowPositionedCandidate{descendant, zero_offset});
+}
+
+NGPhysicalFragment::NGBoxType NGBoxFragmentBuilder::BoxType() const {
+ if (box_type_ != NGPhysicalFragment::NGBoxType::kNormalBox)
+ return box_type_;
+
+ // When implicit, compute from LayoutObject.
+ DCHECK(layout_object_);
+ if (layout_object_->IsFloating())
+ return NGPhysicalFragment::NGBoxType::kFloating;
+ if (layout_object_->IsOutOfFlowPositioned())
+ return NGPhysicalFragment::NGBoxType::kOutOfFlowPositioned;
+ if (layout_object_->IsAtomicInlineLevel())
+ return NGPhysicalFragment::NGBoxType::kAtomicInline;
+ if (layout_object_->IsInline())
+ return NGPhysicalFragment::NGBoxType::kInlineBox;
+ DCHECK(node_) << "Must call SetBoxType if there is no node";
+ DCHECK_EQ(is_new_fc_, node_.CreatesNewFormattingContext())
+ << "Forgot to call builder.SetIsNewFormattingContext";
+ if (is_new_fc_)
+ return NGPhysicalFragment::NGBoxType::kBlockFlowRoot;
+ return NGPhysicalFragment::NGBoxType::kNormalBox;
+}
+
+void NGBoxFragmentBuilder::AddBaseline(NGBaselineRequest request,
+ LayoutUnit offset) {
+#if DCHECK_IS_ON()
+ for (const auto& baseline : baselines_)
+ DCHECK(baseline.request != request);
+#endif
+ baselines_.emplace_back(request, offset);
+}
+
+EBreakBetween NGBoxFragmentBuilder::JoinedBreakBetweenValue(
+ EBreakBetween break_before) const {
+ return JoinFragmentainerBreakValues(previous_break_after_, break_before);
+}
+
+scoped_refptr<NGLayoutResult> NGBoxFragmentBuilder::ToBoxFragment(
+ WritingMode block_or_line_writing_mode) {
+ if (node_) {
+ if (!inline_break_tokens_.IsEmpty()) {
+ if (auto token = inline_break_tokens_.back()) {
+ if (!token->IsFinished())
+ child_break_tokens_.push_back(std::move(token));
+ }
+ }
+ if (did_break_) {
+ break_token_ = NGBlockBreakToken::Create(
+ node_, used_block_size_, child_break_tokens_, has_last_resort_break_);
+ } else if (needs_finished_break_token_) {
+ break_token_ = NGBlockBreakToken::Create(node_, used_block_size_,
+ has_last_resort_break_);
+ }
+ }
+
+ scoped_refptr<const NGPhysicalBoxFragment> fragment =
+ NGPhysicalBoxFragment::Create(this, block_or_line_writing_mode);
+
+ return base::AdoptRef(new NGLayoutResult(std::move(fragment), this));
+}
+
+scoped_refptr<NGLayoutResult> NGBoxFragmentBuilder::Abort(
+ NGLayoutResult::NGLayoutResultStatus status) {
+ return base::AdoptRef(new NGLayoutResult(status, this));
+}
+
+// Finds FragmentPairs that define inline containing blocks.
+// inline_container_fragments is a map whose keys specify which
+// inline containing blocks are required.
+// Not finding a required block is an unexpected behavior (DCHECK).
+void NGBoxFragmentBuilder::ComputeInlineContainerFragments(
+ HashMap<const LayoutObject*, FragmentPair>* inline_container_fragments,
+ NGLogicalSize* container_size) {
+ // This function has detailed knowledge of inline fragment tree structure,
+ // and will break if this changes.
+ DCHECK_GE(InlineSize(), LayoutUnit());
+ DCHECK_GE(BlockSize(), LayoutUnit());
+ *container_size = Size();
+
+ for (wtf_size_t i = 0; i < children_.size(); i++) {
+ if (children_[i]->IsLineBox()) {
+ const NGPhysicalLineBoxFragment* linebox =
+ ToNGPhysicalLineBoxFragment(children_[i].get());
+ const NGPhysicalOffset linebox_offset = offsets_[i].ConvertToPhysical(
+ GetWritingMode(), Direction(),
+ ToNGPhysicalSize(Size(), GetWritingMode()), linebox->Size());
+
+ for (auto& descendant :
+ NGInlineFragmentTraversal::DescendantsOf(*linebox)) {
+ LayoutObject* key = {};
+ if (descendant.fragment->IsText()) {
+ key = descendant.fragment->GetLayoutObject();
+ DCHECK(key);
+ key = key->Parent();
+ DCHECK(key);
+ } else if (descendant.fragment->IsBox()) {
+ key = descendant.fragment->GetLayoutObject();
+ }
+ if (!key)
+ continue;
+ auto it = inline_container_fragments->find(key);
+ if (it != inline_container_fragments->end()) {
+ NGBoxFragmentBuilder::FragmentPair& value = it->value;
+ // |DescendantsOf| returns the offset from the given fragment. Since
+ // we give it the line box, need to add the |linebox_offset|.
+ NGPhysicalOffsetRect fragment_rect(
+ linebox_offset + descendant.offset_to_container_box,
+ descendant.fragment->Size());
+ if (value.start_linebox_fragment == linebox) {
+ value.start_fragment_union_rect.Unite(fragment_rect);
+ } else if (!value.start_fragment) {
+ value.start_fragment = descendant.fragment.get();
+ value.start_fragment_union_rect = fragment_rect;
+ value.start_linebox_fragment = linebox;
+ }
+ // Skip fragments within an empty line boxes for the end fragment.
+ if (value.end_linebox_fragment == linebox) {
+ value.end_fragment_union_rect.Unite(fragment_rect);
+ } else if (!value.end_fragment || !linebox->IsEmptyLineBox()) {
+ value.end_fragment = descendant.fragment.get();
+ value.end_fragment_union_rect = fragment_rect;
+ value.end_linebox_fragment = linebox;
+ }
+ }
+ }
+ }
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h
new file mode 100644
index 00000000000..a506bffe580
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h
@@ -0,0 +1,268 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BOX_FRAGMENT_BUILDER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BOX_FRAGMENT_BUILDER_H_
+
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_border_edges.h"
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
+#include "third_party/blink/renderer/core/style/computed_style_constants.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+
+namespace blink {
+
+class NGPhysicalFragment;
+class NGPhysicalLineBoxFragment;
+
+class CORE_EXPORT NGBoxFragmentBuilder final
+ : public NGContainerFragmentBuilder {
+ DISALLOW_NEW();
+
+ public:
+ NGBoxFragmentBuilder(NGLayoutInputNode node,
+ scoped_refptr<const ComputedStyle> style,
+ WritingMode writing_mode,
+ TextDirection direction)
+ : NGContainerFragmentBuilder(std::move(style), writing_mode, direction),
+ node_(node),
+ box_type_(NGPhysicalFragment::NGBoxType::kNormalBox),
+ is_old_layout_root_(false),
+ did_break_(false) {
+ layout_object_ = node.GetLayoutBox();
+ }
+
+ // Build a fragment for LayoutObject without NGLayoutInputNode. LayoutInline
+ // has NGInlineItem but does not have corresponding NGLayoutInputNode.
+ NGBoxFragmentBuilder(LayoutObject* layout_object,
+ scoped_refptr<const ComputedStyle> style,
+ WritingMode writing_mode,
+ TextDirection direction)
+ : NGContainerFragmentBuilder(std::move(style), writing_mode, direction),
+ node_(nullptr),
+ box_type_(NGPhysicalFragment::NGBoxType::kNormalBox),
+ is_old_layout_root_(false),
+ did_break_(false) {
+ layout_object_ = layout_object;
+ }
+
+ NGBoxFragmentBuilder& SetIntrinsicBlockSize(LayoutUnit intrinsic_block_size) {
+ intrinsic_block_size_ = intrinsic_block_size;
+ return *this;
+ }
+ NGBoxFragmentBuilder& SetBorders(const NGBoxStrut& border) {
+ DCHECK_NE(BoxType(), NGPhysicalFragment::kInlineBox);
+ borders_ = border;
+ return *this;
+ }
+ NGBoxFragmentBuilder& SetPadding(const NGBoxStrut& padding) {
+ DCHECK_NE(BoxType(), NGPhysicalFragment::kInlineBox);
+ padding_ = padding;
+ return *this;
+ }
+ NGBoxFragmentBuilder& SetPadding(const NGLineBoxStrut& padding) {
+ DCHECK_EQ(BoxType(), NGPhysicalFragment::kInlineBox);
+ // Convert to flow-relative, because ToInlineBoxFragment() will convert
+ // the padding to physical coordinates using flow-relative writing-mode.
+ padding_ = NGBoxStrut(padding, IsFlippedLinesWritingMode(GetWritingMode()));
+ return *this;
+ }
+
+ // Remove all children.
+ void RemoveChildren();
+
+ // Add a break token for a child that doesn't yet have any fragments, because
+ // its first fragment is to be produced in the next fragmentainer. This will
+ // add a break token for the child, but no fragment.
+ NGBoxFragmentBuilder& AddBreakBeforeChild(NGLayoutInputNode child);
+
+ // Prepare for a break token before the specified line.
+ NGBoxFragmentBuilder& AddBreakBeforeLine(int line_number);
+
+ // Update if we have fragmented in this flow.
+ NGBoxFragmentBuilder& PropagateBreak(const NGLayoutResult&);
+ NGBoxFragmentBuilder& PropagateBreak(const NGPhysicalFragment&);
+
+ void AddOutOfFlowLegacyCandidate(NGBlockNode,
+ const NGStaticPosition&,
+ LayoutObject* inline_container);
+
+ // Set how much of the block size we've used so far for this box.
+ NGBoxFragmentBuilder& SetUsedBlockSize(LayoutUnit used_block_size) {
+ used_block_size_ = used_block_size;
+ return *this;
+ }
+
+ NGBoxFragmentBuilder& SetNeedsFinishedBreakToken() {
+ needs_finished_break_token_ = true;
+ return *this;
+ }
+
+ // Specify that we broke.
+ //
+ // This will result in a fragment which has an unfinished break token.
+ NGBoxFragmentBuilder& SetDidBreak() {
+ did_break_ = true;
+ return *this;
+ }
+
+ NGBoxFragmentBuilder& SetHasForcedBreak() {
+ has_forced_break_ = true;
+ minimal_space_shortage_ = LayoutUnit();
+ return *this;
+ }
+
+ // Report space shortage, i.e. how much more space would have been sufficient
+ // to prevent some piece of content from breaking. This information may be
+ // used by the column balancer to stretch columns.
+ NGBoxFragmentBuilder& PropagateSpaceShortage(LayoutUnit space_shortage) {
+ DCHECK_GT(space_shortage, LayoutUnit());
+ if (minimal_space_shortage_ > space_shortage)
+ minimal_space_shortage_ = space_shortage;
+ return *this;
+ }
+
+ void SetInitialBreakBefore(EBreakBetween break_before) {
+ initial_break_before_ = break_before;
+ }
+
+ void SetPreviousBreakAfter(EBreakBetween break_after) {
+ previous_break_after_ = break_after;
+ }
+
+ // Join/"collapse" the previous (stored) break-after value with the next
+ // break-before value, to determine how to deal with breaking between two
+ // in-flow siblings.
+ EBreakBetween JoinedBreakBetweenValue(EBreakBetween break_before) const;
+
+ // Return the number of line boxes laid out.
+ int LineCount() const { return inline_break_tokens_.size(); }
+
+ // Call when we're setting an undersirable break. It may be possible to avoid
+ // the break if we instead break at an earlier element.
+ void SetHasLastResortBreak() { has_last_resort_break_ = true; }
+
+ // Offsets are not supposed to be set during fragment construction, so we
+ // do not provide a setter here.
+
+ // Creates the fragment. Can only be called once.
+ scoped_refptr<NGLayoutResult> ToBoxFragment() {
+ DCHECK_NE(BoxType(), NGPhysicalFragment::kInlineBox);
+ return ToBoxFragment(GetWritingMode());
+ }
+ scoped_refptr<NGLayoutResult> ToInlineBoxFragment() {
+ // The logical coordinate for inline box uses line-relative writing-mode,
+ // not
+ // flow-relative.
+ DCHECK_EQ(BoxType(), NGPhysicalFragment::kInlineBox);
+ return ToBoxFragment(ToLineWritingMode(GetWritingMode()));
+ }
+
+ scoped_refptr<NGLayoutResult> Abort(NGLayoutResult::NGLayoutResultStatus);
+
+ // A vector of child offsets. Initially set by AddChild().
+ const OffsetVector& Offsets() const { return offsets_; }
+
+ NGPhysicalFragment::NGBoxType BoxType() const;
+ NGBoxFragmentBuilder& SetBoxType(NGPhysicalFragment::NGBoxType box_type) {
+ box_type_ = box_type;
+ return *this;
+ }
+ NGBoxFragmentBuilder& SetIsFieldsetContainer() {
+ is_fieldset_container_ = true;
+ return *this;
+ }
+ NGBoxFragmentBuilder& SetIsOldLayoutRoot() {
+ is_old_layout_root_ = true;
+ return *this;
+ }
+
+ bool DidBreak() const { return did_break_; }
+
+ NGBoxFragmentBuilder& SetBorderEdges(NGBorderEdges border_edges) {
+ border_edges_ = border_edges;
+ return *this;
+ }
+
+ // Either this function or SetBoxType must be called before ToBoxFragment().
+ NGBoxFragmentBuilder& SetIsNewFormattingContext(bool is_new_fc) {
+ is_new_fc_ = is_new_fc;
+ return *this;
+ }
+
+ // Layout algorithms should call this function for each baseline request in
+ // the constraint space.
+ //
+ // If a request should use a synthesized baseline from the box rectangle,
+ // algorithms can omit the call.
+ //
+ // This function should be called at most once for a given algorithm/baseline
+ // type pair.
+ void AddBaseline(NGBaselineRequest, LayoutUnit);
+
+ // Inline containing block geometry is defined by two fragments:
+ // start and end. FragmentPair holds the information needed to compute
+ // inline containing block geometry wrt enclosing container block.
+ struct FragmentPair {
+ DISALLOW_NEW();
+ // Linebox that contains start_fragment.
+ const NGPhysicalLineBoxFragment* start_linebox_fragment;
+ // Start fragment of inline containing block.
+ const NGPhysicalFragment* start_fragment;
+ // Start fragment rect combined with rectangles of all fragments
+ // generated by same Element as start_fragment.
+ NGPhysicalOffsetRect start_fragment_union_rect;
+ // end_** variables are end fragment counterparts to start fragment.
+ const NGPhysicalLineBoxFragment* end_linebox_fragment;
+ const NGPhysicalFragment* end_fragment;
+ NGPhysicalOffsetRect end_fragment_union_rect;
+ };
+
+ void ComputeInlineContainerFragments(
+ HashMap<const LayoutObject*, FragmentPair>* inline_container_fragments,
+ NGLogicalSize* container_size);
+
+ private:
+ scoped_refptr<NGLayoutResult> ToBoxFragment(WritingMode);
+
+ NGLayoutInputNode node_;
+
+ LayoutUnit intrinsic_block_size_;
+ NGBoxStrut borders_;
+ NGBoxStrut padding_;
+
+ NGPhysicalFragment::NGBoxType box_type_;
+ bool is_fieldset_container_ = false;
+ bool is_old_layout_root_;
+ bool needs_finished_break_token_ = false;
+ bool did_break_;
+ bool has_forced_break_ = false;
+ bool is_new_fc_ = false;
+ LayoutUnit used_block_size_;
+
+ LayoutUnit minimal_space_shortage_ = LayoutUnit::Max();
+
+ // The break-before value on the initial child we cannot honor. There's no
+ // valid class A break point before a first child, only *between* siblings.
+ EBreakBetween initial_break_before_ = EBreakBetween::kAuto;
+
+ // The break-after value of the previous in-flow sibling.
+ EBreakBetween previous_break_after_ = EBreakBetween::kAuto;
+
+ NGBaselineList baselines_;
+
+ NGBorderEdges border_edges_;
+
+ friend class NGPhysicalBoxFragment;
+ friend class NGLayoutResult;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BOX_FRAGMENT_BUILDER_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.cc
index 4ba888daa75..75bcf1fff0c 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.cc
@@ -27,8 +27,8 @@ void AppendBreakTokenToString(const NGBreakToken* token,
if (token->Type() == NGBreakToken::kBlockBreakToken) {
const auto children = ToNGBlockBreakToken(token)->ChildBreakTokens();
- for (const auto& child : children)
- AppendBreakTokenToString(child.get(), string_builder, indent + 2);
+ for (const auto* child : children)
+ AppendBreakTokenToString(child, string_builder, indent + 2);
}
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.h
index 605ad81abd8..14111476499 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.h
@@ -67,6 +67,8 @@ class CORE_EXPORT NGBreakToken : public RefCounted<NGBreakToken> {
NGLayoutInputNode node_;
};
+typedef Vector<scoped_refptr<NGBreakToken>, 16> NGBreakTokenVector;
+
} // namespace blink
#endif // NGBreakToken_h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
index 5ddfb1f0df2..12bc8e69d46 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
@@ -69,7 +69,9 @@ NGColumnLayoutAlgorithm::NGColumnLayoutAlgorithm(
NGBlockNode node,
const NGConstraintSpace& space,
const NGBreakToken* break_token)
- : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {}
+ : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {
+ container_builder_.SetIsNewFormattingContext(space.IsNewFormattingContext());
+}
scoped_refptr<NGLayoutResult> NGColumnLayoutAlgorithm::Layout() {
NGBoxStrut borders = ComputeBorders(ConstraintSpace(), Node());
@@ -116,8 +118,8 @@ scoped_refptr<NGLayoutResult> NGColumnLayoutAlgorithm::Layout() {
break_token.get());
child_algorithm.SetBoxType(NGPhysicalFragment::kColumnBox);
scoped_refptr<NGLayoutResult> result = child_algorithm.Layout();
- scoped_refptr<const NGPhysicalBoxFragment> column(
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get()));
+ const NGPhysicalBoxFragment* column =
+ ToNGPhysicalBoxFragment(result->PhysicalFragment());
NGLogicalOffset logical_offset(column_inline_offset, column_block_offset);
container_builder_.AddChild(*result, logical_offset);
@@ -291,7 +293,8 @@ LayoutUnit NGColumnLayoutAlgorithm::StretchColumnBlockSize(
NGConstraintSpace NGColumnLayoutAlgorithm::CreateConstraintSpaceForColumns(
const NGLogicalSize& column_size,
bool separate_leading_margins) const {
- NGConstraintSpaceBuilder space_builder(ConstraintSpace());
+ NGConstraintSpaceBuilder space_builder(
+ ConstraintSpace(), Style().GetWritingMode(), /* is_new_fc */ true);
space_builder.SetAvailableSize(column_size);
space_builder.SetPercentageResolutionSize(column_size);
@@ -307,24 +310,23 @@ NGConstraintSpace NGColumnLayoutAlgorithm::CreateConstraintSpaceForColumns(
space_builder.SetFragmentationType(kFragmentColumn);
space_builder.SetFragmentainerBlockSize(column_block_size);
space_builder.SetFragmentainerSpaceAtBfcStart(column_block_size);
- space_builder.SetIsNewFormattingContext(true);
space_builder.SetIsAnonymous(true);
space_builder.SetSeparateLeadingFragmentainerMargins(
separate_leading_margins);
- return space_builder.ToConstraintSpace(Style().GetWritingMode());
+ return space_builder.ToConstraintSpace();
}
NGConstraintSpace NGColumnLayoutAlgorithm::CreateConstaintSpaceForBalancing(
const NGLogicalSize& column_size) const {
- NGConstraintSpaceBuilder space_builder(ConstraintSpace());
+ NGConstraintSpaceBuilder space_builder(
+ ConstraintSpace(), Style().GetWritingMode(), /* is_new_fc */ true);
space_builder.SetAvailableSize({column_size.inline_size, NGSizeIndefinite});
space_builder.SetPercentageResolutionSize(column_size);
- space_builder.SetIsNewFormattingContext(true);
space_builder.SetIsAnonymous(true);
space_builder.SetIsIntermediateLayout(true);
- return space_builder.ToConstraintSpace(Style().GetWritingMode());
+ return space_builder.ToConstraintSpace();
}
} // namespace Blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h
index bf04748e47d..93be8b66d22 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h
@@ -5,7 +5,7 @@
#ifndef NGColumnLayoutAlgorithm_h
#define NGColumnLayoutAlgorithm_h
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h"
namespace blink {
@@ -18,7 +18,7 @@ struct NGLogicalSize;
class CORE_EXPORT NGColumnLayoutAlgorithm
: public NGLayoutAlgorithm<NGBlockNode,
- NGFragmentBuilder,
+ NGBoxFragmentBuilder,
NGBlockBreakToken> {
public:
NGColumnLayoutAlgorithm(NGBlockNode node,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
index ce4ee45ad1e..9c2e939da13 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
@@ -33,7 +33,7 @@ class NGColumnLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
scoped_refptr<NGLayoutResult> result =
NGBlockLayoutAlgorithm(node, space).Layout();
- return ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ return ToNGPhysicalBoxFragment(result->PhysicalFragment());
}
scoped_refptr<const NGPhysicalBoxFragment> RunBlockLayoutAlgorithm(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.cc
index b4c9d8f410d..8653c4b2dd9 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.cc
@@ -15,111 +15,22 @@
namespace blink {
-NGConstraintSpace::NGConstraintSpace(WritingMode out_writing_mode,
- bool is_new_fc,
- NGConstraintSpaceBuilder& builder)
- : available_size_(builder.available_size_),
- percentage_resolution_size_(builder.percentage_resolution_size_),
- replaced_percentage_resolution_size_(
- builder.replaced_percentage_resolution_size_),
- parent_percentage_resolution_inline_size_(
- builder.parent_percentage_resolution_size_
- .value_or(percentage_resolution_size_)
- .inline_size),
- initial_containing_block_size_(builder.initial_containing_block_size_),
- fragmentainer_block_size_(builder.fragmentainer_block_size_),
- fragmentainer_space_at_bfc_start_(
- builder.fragmentainer_space_at_bfc_start_),
- block_direction_fragmentation_type_(builder.fragmentation_type_),
- table_cell_child_layout_phase_(builder.table_cell_child_layout_phase_),
- adjoining_floats_(builder.adjoining_floats_),
- writing_mode_(static_cast<unsigned>(out_writing_mode)),
- direction_(static_cast<unsigned>(builder.text_direction_)),
- flags_(builder.flags_),
- margin_strut_(is_new_fc ? NGMarginStrut() : builder.margin_strut_),
- bfc_offset_(is_new_fc ? NGBfcOffset() : builder.bfc_offset_),
- floats_bfc_block_offset_(is_new_fc ? base::nullopt
- : builder.floats_bfc_block_offset_),
- clearance_offset_(is_new_fc ? LayoutUnit::Min()
- : builder.clearance_offset_),
- baseline_requests_(std::move(builder.baseline_requests_)) {
- bool is_in_parallel_flow =
- IsParallelWritingMode(builder.parent_writing_mode_, out_writing_mode);
+namespace {
- DCHECK(!is_new_fc || !adjoining_floats_);
-
- auto SetResolvedFlag = [this](unsigned mask, bool value) {
- flags_ = (flags_ & ~static_cast<unsigned>(mask)) |
- (-(int32_t)value & static_cast<unsigned>(mask));
+struct SameSizeAsNGConstraintSpace {
+ NGLogicalSize available_size;
+ union {
+ NGBfcOffset bfc_offset;
+ void* rare_data;
};
- if (!is_in_parallel_flow) {
- available_size_.Flip();
- percentage_resolution_size_.Flip();
- replaced_percentage_resolution_size_.Flip();
- parent_percentage_resolution_inline_size_ =
- builder.parent_percentage_resolution_size_
- .value_or(percentage_resolution_size_)
- .block_size;
- // Swap the fixed size block/inline flags
- bool fixed_size_block = flags_ & kFixedSizeBlock;
- bool fixed_size_inline = flags_ & kFixedSizeInline;
- SetResolvedFlag(kFixedSizeInline, fixed_size_block);
- SetResolvedFlag(kFixedSizeBlock, fixed_size_inline);
- SetResolvedFlag(kFixedSizeBlockIsDefinite, true);
- SetResolvedFlag(kOrthogonalWritingModeRoot, true);
- }
- DCHECK_EQ(flags_ & kOrthogonalWritingModeRoot, !is_in_parallel_flow);
+ NGExclusionSpace exclusion_space;
+ unsigned bitfields[1];
+};
- // For ConstraintSpace instances created from layout objects,
- // parent_writing_mode_ isn't actually the parent's, it's the same as the out
- // writing mode. So we miss setting kOrthogonalWritingModeRoot on such
- // constraint spaces unless it is forced.
- if (builder.force_orthogonal_writing_mode_root_) {
- DCHECK(is_in_parallel_flow)
- << "Forced and inferred ortho writing mode shouldn't happen "
- "simultaneously. Inferred means the constraints are in parent "
- "writing mode, forced means they are in child writing mode. "
- "parent_writing_mode_ = "
- << static_cast<int>(builder.parent_writing_mode_)
- << ", requested writing mode = " << static_cast<int>(out_writing_mode);
- SetResolvedFlag(kOrthogonalWritingModeRoot, true);
- SetResolvedFlag(kFixedSizeBlockIsDefinite, true);
- }
-
- // If inline size is indefinite, use size of initial containing block.
- // https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto
- if (available_size_.inline_size == NGSizeIndefinite) {
- DCHECK(!is_in_parallel_flow);
- if (out_writing_mode == WritingMode::kHorizontalTb) {
- available_size_.inline_size = initial_containing_block_size_.width;
- } else {
- available_size_.inline_size = initial_containing_block_size_.height;
- }
- }
- if (percentage_resolution_size_.inline_size == NGSizeIndefinite) {
- DCHECK(!is_in_parallel_flow);
- if (out_writing_mode == WritingMode::kHorizontalTb) {
- percentage_resolution_size_.inline_size =
- initial_containing_block_size_.width;
- } else {
- percentage_resolution_size_.inline_size =
- initial_containing_block_size_.height;
- }
- }
- if (replaced_percentage_resolution_size_.inline_size == NGSizeIndefinite) {
- DCHECK(!is_in_parallel_flow);
- if (out_writing_mode == WritingMode::kHorizontalTb) {
- replaced_percentage_resolution_size_.inline_size =
- initial_containing_block_size_.width;
- } else {
- replaced_percentage_resolution_size_.inline_size =
- initial_containing_block_size_.height;
- }
- }
+static_assert(sizeof(NGConstraintSpace) == sizeof(SameSizeAsNGConstraintSpace),
+ "NGConstraintSpace should stay small.");
- if (!is_new_fc && builder.exclusion_space_)
- exclusion_space_ = *builder.exclusion_space_;
-}
+} // namespace
NGConstraintSpace NGConstraintSpace::CreateFromLayoutObject(
const LayoutBox& box) {
@@ -178,9 +89,12 @@ NGConstraintSpace NGConstraintSpace::CreateFromLayoutObject(
fixed_block = true;
}
if (box.IsFlexItem() && fixed_block) {
+ // The flexbox-specific behavior is in addition to regular definite-ness, so
+ // if the flex item would normally have a definite height it should keep it.
fixed_block_is_definite =
ToLayoutFlexibleBox(box.Parent())
- ->UseOverrideLogicalHeightForPerentageResolution(box);
+ ->UseOverrideLogicalHeightForPerentageResolution(box) ||
+ (box.IsLayoutBlock() && ToLayoutBlock(box).HasDefiniteLogicalHeight());
}
bool is_new_fc = true;
@@ -193,15 +107,8 @@ NGConstraintSpace NGConstraintSpace::CreateFromLayoutObject(
// DCHECK(is_new_fc,
// box.IsLayoutBlock() && ToLayoutBlock(box).CreatesNewFormattingContext());
- IntSize icb_size = box.View()->GetLayoutSize(kExcludeScrollbars);
- NGPhysicalSize initial_containing_block_size{LayoutUnit(icb_size.Width()),
- LayoutUnit(icb_size.Height())};
-
- // ICB cannot be indefinite by the spec.
- DCHECK_GE(initial_containing_block_size.width, LayoutUnit());
- DCHECK_GE(initial_containing_block_size.height, LayoutUnit());
-
- NGConstraintSpaceBuilder builder(writing_mode, initial_containing_block_size);
+ NGConstraintSpaceBuilder builder(writing_mode, writing_mode, is_new_fc,
+ !parallel_containing_block);
if (!box.IsWritingModeRoot() || box.IsGridItem()) {
// Add all types because we don't know which baselines will be requested.
@@ -224,56 +131,22 @@ NGConstraintSpace NGConstraintSpace::CreateFromLayoutObject(
.SetFixedSizeBlockIsDefinite(fixed_block_is_definite)
.SetIsShrinkToFit(
box.SizesLogicalWidthToFitContent(box.StyleRef().LogicalWidth()))
- .SetIsNewFormattingContext(is_new_fc)
.SetTextDirection(box.StyleRef().Direction())
- .SetIsOrthogonalWritingModeRoot(!parallel_containing_block)
- .ToConstraintSpace(writing_mode);
+ .ToConstraintSpace();
}
-LayoutUnit
-NGConstraintSpace::PercentageResolutionInlineSizeForParentWritingMode() const {
- if (!IsOrthogonalWritingModeRoot())
- return PercentageResolutionSize().inline_size;
- if (PercentageResolutionSize().block_size != NGSizeIndefinite)
- return PercentageResolutionSize().block_size;
- if (IsHorizontalWritingMode(GetWritingMode()))
- return InitialContainingBlockSize().height;
- return InitialContainingBlockSize().width;
-}
+bool NGConstraintSpace::operator==(const NGConstraintSpace& other) const {
+ if (!AreSizesEqual(other))
+ return false;
-LayoutUnit NGConstraintSpace::ParentPercentageResolutionInlineSize() const {
- if (parent_percentage_resolution_inline_size_ != NGSizeIndefinite)
- return parent_percentage_resolution_inline_size_;
- return initial_containing_block_size_.ConvertToLogical(GetWritingMode())
- .inline_size;
-}
+ if (!MaySkipLayout(other))
+ return false;
-bool NGConstraintSpace::operator==(const NGConstraintSpace& other) const {
- return available_size_ == other.available_size_ &&
- percentage_resolution_size_ == other.percentage_resolution_size_ &&
- replaced_percentage_resolution_size_ ==
- other.replaced_percentage_resolution_size_ &&
- parent_percentage_resolution_inline_size_ ==
- other.parent_percentage_resolution_inline_size_ &&
- initial_containing_block_size_ ==
- other.initial_containing_block_size_ &&
- fragmentainer_block_size_ == other.fragmentainer_block_size_ &&
- fragmentainer_space_at_bfc_start_ ==
- other.fragmentainer_space_at_bfc_start_ &&
- block_direction_fragmentation_type_ ==
- other.block_direction_fragmentation_type_ &&
- table_cell_child_layout_phase_ ==
- other.table_cell_child_layout_phase_ &&
- flags_ == other.flags_ &&
- adjoining_floats_ == other.adjoining_floats_ &&
- writing_mode_ == other.writing_mode_ &&
- direction_ == other.direction_ &&
- margin_strut_ == other.margin_strut_ &&
- bfc_offset_ == other.bfc_offset_ &&
- floats_bfc_block_offset_ == other.floats_bfc_block_offset_ &&
- exclusion_space_ == other.exclusion_space_ &&
- clearance_offset_ == other.clearance_offset_ &&
- baseline_requests_ == other.baseline_requests_;
+ if (!HasRareData() && !other.HasRareData() &&
+ bfc_offset_.block_offset != other.bfc_offset_.block_offset)
+ return false;
+
+ return true;
}
String NGConstraintSpace::ToString() const {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h
index f2caee8c334..cccbaabe723 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h
@@ -43,6 +43,15 @@ enum NGTableCellChildLayoutPhase {
kLayout // The node is a table cell child, in the "layout" phase.
};
+// Percentages are frequently the same as the available-size, zero, or
+// indefinite (thanks non-quirks mode)! This enum encodes this information.
+enum NGPercentageStorage {
+ kSameAsAvailable,
+ kZero,
+ kIndefinite,
+ kRareDataPercentage
+};
+
// The NGConstraintSpace represents a set of constraints and available space
// which a layout algorithm may produce a NGFragment within.
class CORE_EXPORT NGConstraintSpace final {
@@ -61,16 +70,68 @@ class CORE_EXPORT NGConstraintSpace final {
kAnonymous = 1 << 8,
kUseFirstLineStyle = 1 << 9,
kForceClearance = 1 << 10,
+ kHasRareData = 1 << 11,
// Size of bitfield used to store the flags.
- kNumberOfConstraintSpaceFlags = 11
+ kNumberOfConstraintSpaceFlags = 12
};
- NGConstraintSpace() {}
- NGConstraintSpace(const NGConstraintSpace&) = default;
- NGConstraintSpace(NGConstraintSpace&&) = default;
- NGConstraintSpace& operator=(const NGConstraintSpace&) = default;
- NGConstraintSpace& operator=(NGConstraintSpace&&) = default;
+ // To ensure that the bfc_offset_, rare_data_ union doesn't get polluted,
+ // always initialize the bfc_offset_.
+ NGConstraintSpace() : bfc_offset_() {}
+
+ NGConstraintSpace(const NGConstraintSpace& other)
+ : available_size_(other.available_size_),
+ exclusion_space_(other.exclusion_space_),
+ bitfields_(other.bitfields_) {
+ if (HasRareData())
+ rare_data_ = new RareData(*other.rare_data_);
+ else
+ bfc_offset_ = other.bfc_offset_;
+ }
+ NGConstraintSpace(NGConstraintSpace&& other)
+ : available_size_(other.available_size_),
+ exclusion_space_(std::move(other.exclusion_space_)),
+ bitfields_(other.bitfields_) {
+ if (HasRareData()) {
+ rare_data_ = other.rare_data_;
+ other.rare_data_ = nullptr;
+ } else {
+ bfc_offset_ = other.bfc_offset_;
+ }
+ }
+
+ NGConstraintSpace& operator=(const NGConstraintSpace& other) {
+ available_size_ = other.available_size_;
+ if (HasRareData())
+ delete rare_data_;
+ if (other.HasRareData())
+ rare_data_ = new RareData(*other.rare_data_);
+ else
+ bfc_offset_ = other.bfc_offset_;
+ exclusion_space_ = other.exclusion_space_;
+ bitfields_ = other.bitfields_;
+ return *this;
+ }
+ NGConstraintSpace& operator=(NGConstraintSpace&& other) {
+ available_size_ = other.available_size_;
+ if (HasRareData())
+ delete rare_data_;
+ if (other.HasRareData()) {
+ rare_data_ = other.rare_data_;
+ other.rare_data_ = nullptr;
+ } else {
+ bfc_offset_ = other.bfc_offset_;
+ }
+ exclusion_space_ = std::move(other.exclusion_space_);
+ bitfields_ = other.bitfields_;
+ return *this;
+ }
+
+ ~NGConstraintSpace() {
+ if (HasRareData())
+ delete rare_data_;
+ }
// Creates NGConstraintSpace representing LayoutObject's containing block.
// This should live on NGBlockNode or another layout bridge and probably take
@@ -80,47 +141,123 @@ class CORE_EXPORT NGConstraintSpace final {
const NGExclusionSpace& ExclusionSpace() const { return exclusion_space_; }
TextDirection Direction() const {
- return static_cast<TextDirection>(direction_);
+ return static_cast<TextDirection>(bitfields_.direction);
}
WritingMode GetWritingMode() const {
- return static_cast<WritingMode>(writing_mode_);
+ return static_cast<WritingMode>(bitfields_.writing_mode);
}
bool IsOrthogonalWritingModeRoot() const {
return HasFlag(kOrthogonalWritingModeRoot);
}
+ // The available space size.
+ // See: https://drafts.csswg.org/css-sizing/#available
+ NGLogicalSize AvailableSize() const { return available_size_; }
+
// The size to use for percentage resolution.
// See: https://drafts.csswg.org/css-sizing/#percentage-sizing
+ LayoutUnit PercentageResolutionInlineSize() const {
+ switch (static_cast<NGPercentageStorage>(
+ bitfields_.percentage_inline_storage)) {
+ default:
+ NOTREACHED();
+ U_FALLTHROUGH;
+ case kSameAsAvailable:
+ return available_size_.inline_size;
+ case kZero:
+ return LayoutUnit();
+ case kIndefinite:
+ return NGSizeIndefinite;
+ case kRareDataPercentage:
+ DCHECK(HasRareData());
+ return rare_data_->percentage_resolution_size.inline_size;
+ }
+ }
+
+ LayoutUnit PercentageResolutionBlockSize() const {
+ switch (
+ static_cast<NGPercentageStorage>(bitfields_.percentage_block_storage)) {
+ default:
+ NOTREACHED();
+ U_FALLTHROUGH;
+ case kSameAsAvailable:
+ return available_size_.block_size;
+ case kZero:
+ return LayoutUnit();
+ case kIndefinite:
+ return NGSizeIndefinite;
+ case kRareDataPercentage:
+ DCHECK(HasRareData());
+ return rare_data_->percentage_resolution_size.block_size;
+ }
+ }
+
NGLogicalSize PercentageResolutionSize() const {
- return percentage_resolution_size_;
+ return {PercentageResolutionInlineSize(), PercentageResolutionBlockSize()};
+ }
+
+ LayoutUnit ReplacedPercentageResolutionInlineSize() const {
+ switch (static_cast<NGPercentageStorage>(
+ bitfields_.replaced_percentage_inline_storage)) {
+ case kSameAsAvailable:
+ return available_size_.inline_size;
+ case kZero:
+ return LayoutUnit();
+ case kIndefinite:
+ return NGSizeIndefinite;
+ case kRareDataPercentage:
+ DCHECK(HasRareData());
+ return rare_data_->replaced_percentage_resolution_size.inline_size;
+ default:
+ NOTREACHED();
+ }
+
+ return available_size_.inline_size;
+ }
+
+ LayoutUnit ReplacedPercentageResolutionBlockSize() const {
+ switch (static_cast<NGPercentageStorage>(
+ bitfields_.replaced_percentage_block_storage)) {
+ case kSameAsAvailable:
+ return available_size_.block_size;
+ case kZero:
+ return LayoutUnit();
+ case kIndefinite:
+ return NGSizeIndefinite;
+ case kRareDataPercentage:
+ DCHECK(HasRareData());
+ return rare_data_->replaced_percentage_resolution_size.block_size;
+ default:
+ NOTREACHED();
+ }
+
+ return available_size_.block_size;
}
// The size to use for percentage resolution of replaced elements.
NGLogicalSize ReplacedPercentageResolutionSize() const {
- return replaced_percentage_resolution_size_;
+ return {ReplacedPercentageResolutionInlineSize(),
+ ReplacedPercentageResolutionBlockSize()};
}
// The size to use for percentage resolution for margin/border/padding.
// They are always get computed relative to the inline size, in the parent
// writing mode.
- LayoutUnit PercentageResolutionInlineSizeForParentWritingMode() const;
-
- // Parent's PercentageResolutionInlineSize().
- // This is not always available.
- LayoutUnit ParentPercentageResolutionInlineSize() const;
-
- // The available space size.
- // See: https://drafts.csswg.org/css-sizing/#available
- NGLogicalSize AvailableSize() const { return available_size_; }
-
- NGPhysicalSize InitialContainingBlockSize() const {
- return initial_containing_block_size_;
+ LayoutUnit PercentageResolutionInlineSizeForParentWritingMode() const {
+ if (!IsOrthogonalWritingModeRoot())
+ return PercentageResolutionInlineSize();
+ if (PercentageResolutionBlockSize() != NGSizeIndefinite)
+ return PercentageResolutionBlockSize();
+ // TODO(mstensho): Figure out why we get here. It seems wrong, but we do get
+ // here in some grid layout situations.
+ return LayoutUnit();
}
LayoutUnit FragmentainerBlockSize() const {
- return fragmentainer_block_size_;
+ return HasRareData() ? rare_data_->fragmentainer_block_size
+ : NGSizeIndefinite;
}
// Return the block space that was available in the current fragmentainer at
@@ -129,7 +266,8 @@ class CORE_EXPORT NGConstraintSpace final {
// size of the current fragmentainer is returned instead.
LayoutUnit FragmentainerSpaceAtBfcStart() const {
DCHECK(HasBlockFragmentation());
- return fragmentainer_space_at_bfc_start_;
+ return HasRareData() ? rare_data_->fragmentainer_space_at_bfc_start
+ : NGSizeIndefinite;
}
// Whether the current constraint space is for the newly established
@@ -185,8 +323,9 @@ class CORE_EXPORT NGConstraintSpace final {
// If specified a layout should produce a Fragment which fragments at the
// blockSize if possible.
NGFragmentationType BlockFragmentationType() const {
- return static_cast<NGFragmentationType>(
- block_direction_fragmentation_type_);
+ return HasRareData() ? static_cast<NGFragmentationType>(
+ rare_data_->block_direction_fragmentation_type)
+ : kFragmentNone;
}
// Return true if this constraint space participates in a fragmentation
@@ -199,10 +338,12 @@ class CORE_EXPORT NGConstraintSpace final {
// is occurring.
NGTableCellChildLayoutPhase TableCellChildLayoutPhase() const {
return static_cast<NGTableCellChildLayoutPhase>(
- table_cell_child_layout_phase_);
+ bitfields_.table_cell_child_layout_phase);
}
- NGMarginStrut MarginStrut() const { return margin_strut_; }
+ NGMarginStrut MarginStrut() const {
+ return HasRareData() ? rare_data_->margin_strut : NGMarginStrut();
+ }
// The BfcOffset is where the MarginStrut is placed within the block
// formatting context.
@@ -220,7 +361,9 @@ class CORE_EXPORT NGConstraintSpace final {
// - Text content, atomic inlines, (see NGLineBreaker).
// - The current layout having a block_size.
// - Clearance before a child.
- NGBfcOffset BfcOffset() const { return bfc_offset_; }
+ NGBfcOffset BfcOffset() const {
+ return HasRareData() ? rare_data_->bfc_offset : bfc_offset_;
+ }
// If present, and the current layout hasn't resolved its BFC offset yet (see
// BfcOffset), the layout should position all of its unpositioned floats at
@@ -235,7 +378,7 @@ class CORE_EXPORT NGConstraintSpace final {
// This value is calculated *after* an initial pass of the tree, and should
// only be present during subsequent passes.
base::Optional<LayoutUnit> FloatsBfcBlockOffset() const {
- return floats_bfc_block_offset_;
+ return HasRareData() ? rare_data_->floats_bfc_block_offset : base::nullopt;
}
// Return the types (none, left, right, both) of preceding adjoining
@@ -247,12 +390,20 @@ class CORE_EXPORT NGConstraintSpace final {
// (in such cases we will know up front that the block will need clearance,
// since, if it doesn't, the float will be pulled along with the block, and
// the block will fail to clear).
- NGFloatTypes AdjoiningFloatTypes() const { return adjoining_floats_; }
+ NGFloatTypes AdjoiningFloatTypes() const {
+ return bitfields_.adjoining_floats;
+ }
+
+ // Return true if there were any earlier floats that may affect the current
+ // layout.
+ bool HasFloats() const { return !ExclusionSpace().IsEmpty(); }
bool HasClearanceOffset() const {
- return clearance_offset_ != LayoutUnit::Min();
+ return HasRareData() && rare_data_->clearance_offset != LayoutUnit::Min();
+ }
+ LayoutUnit ClearanceOffset() const {
+ return HasRareData() ? rare_data_->clearance_offset : LayoutUnit::Min();
}
- LayoutUnit ClearanceOffset() const { return clearance_offset_; }
// Return true if the fragment needs to have clearance applied to it,
// regardless of its hypothetical position. The fragment will then go exactly
@@ -270,16 +421,89 @@ class CORE_EXPORT NGConstraintSpace final {
// pulled both #container and #float along with it. No margin, no matter how
// large, would ever be able to pull #clearee below the float then. But we
// have clearance, the margins are separated, and in this case we know that we
- // have clearance even before we have laid out (because of the adjoing
+ // have clearance even before we have laid out (because of the adjoining
// float). So it would just be wrong to check for clearance when we position
// #clearee. Nothing can prevent clearance here. A large margin on the cleared
// child will be canceled out with negative clearance.
bool ShouldForceClearance() const { return HasFlag(kForceClearance); }
- const Vector<NGBaselineRequest>& BaselineRequests() const {
- return baseline_requests_;
+ const NGBaselineRequestList BaselineRequests() const {
+ return NGBaselineRequestList(bitfields_.baseline_requests);
+ }
+
+ // Return true if the two constraint spaces are similar enough that it *may*
+ // be possible to skip re-layout. If true is returned, the caller is expected
+ // to verify that any constraint space size (available size, percentage size,
+ // and so on) and BFC offset changes won't require re-layout, before skipping.
+ bool MaySkipLayout(const NGConstraintSpace& other) const {
+ if (HasRareData() && other.HasRareData()) {
+ if (!rare_data_->MaySkipLayout(*other.rare_data_))
+ return false;
+ } else if (!HasRareData() && !other.HasRareData()) {
+ if (bfc_offset_.line_offset != other.bfc_offset_.line_offset)
+ return false;
+ } else {
+ // We have a bfc_offset_, and a rare_data_ (or vice-versa).
+ return false;
+ }
+
+ return exclusion_space_ == other.exclusion_space_ &&
+ bitfields_.MaySkipLayout(other.bitfields_);
}
+ bool AreSizesEqual(const NGConstraintSpace& other) const {
+ if (available_size_ != other.available_size_)
+ return false;
+
+ if (bitfields_.percentage_inline_storage !=
+ other.bitfields_.percentage_inline_storage)
+ return false;
+
+ if (bitfields_.percentage_block_storage !=
+ other.bitfields_.percentage_block_storage)
+ return false;
+
+ if (bitfields_.replaced_percentage_inline_storage !=
+ other.bitfields_.replaced_percentage_inline_storage)
+ return false;
+
+ if (bitfields_.replaced_percentage_block_storage !=
+ other.bitfields_.replaced_percentage_block_storage)
+ return false;
+
+ // The rest of this method just checks the percentage resolution sizes. If
+ // neither space has rare data, we know that they must equal now.
+ if (!HasRareData() && !other.HasRareData())
+ return true;
+
+ if (bitfields_.percentage_inline_storage == kRareDataPercentage &&
+ other.bitfields_.percentage_inline_storage == kRareDataPercentage &&
+ rare_data_->percentage_resolution_size.inline_size !=
+ other.rare_data_->percentage_resolution_size.inline_size)
+ return false;
+
+ if (bitfields_.percentage_block_storage == kRareDataPercentage &&
+ other.bitfields_.percentage_block_storage == kRareDataPercentage &&
+ rare_data_->percentage_resolution_size.block_size !=
+ other.rare_data_->percentage_resolution_size.block_size)
+ return false;
+
+ if (bitfields_.replaced_percentage_inline_storage == kRareDataPercentage &&
+ other.bitfields_.replaced_percentage_inline_storage ==
+ kRareDataPercentage &&
+ rare_data_->replaced_percentage_resolution_size.inline_size !=
+ other.rare_data_->replaced_percentage_resolution_size.inline_size)
+ return false;
+
+ if (bitfields_.replaced_percentage_block_storage == kRareDataPercentage &&
+ other.bitfields_.replaced_percentage_block_storage ==
+ kRareDataPercentage &&
+ rare_data_->replaced_percentage_resolution_size.block_size !=
+ other.rare_data_->replaced_percentage_resolution_size.block_size)
+ return false;
+
+ return true;
+ }
bool operator==(const NGConstraintSpace&) const;
bool operator!=(const NGConstraintSpace& other) const {
return !(*this == other);
@@ -289,40 +513,128 @@ class CORE_EXPORT NGConstraintSpace final {
private:
friend class NGConstraintSpaceBuilder;
- // Default constructor.
- // is_new_fc is technically redundant, but simplifies the code here a bit.
- NGConstraintSpace(WritingMode out_writing_mode,
- bool is_new_fc,
- NGConstraintSpaceBuilder& builder);
- bool HasFlag(ConstraintSpaceFlags mask) const {
- return flags_ & static_cast<unsigned>(mask);
+ explicit NGConstraintSpace(WritingMode writing_mode)
+ : bfc_offset_(), bitfields_(writing_mode) {}
+
+ // This struct defines all of the inputs to layout which we consider rare.
+ // Primarily this is:
+ // - Percentage resolution sizes which differ from the available size or
+ // aren't indefinite.
+ // - The margin strut.
+ // - Anything to do with floats (the exclusion space, clearance offset, etc).
+ // - Anything to do with fragmentation.
+ //
+ // This information is kept in a separate in this heap-allocated struct to
+ // reduce memory usage. Over time this may have to change based on usage data.
+ struct RareData {
+ USING_FAST_MALLOC(RareData);
+
+ public:
+ explicit RareData(const NGBfcOffset bfc_offset)
+ : bfc_offset(bfc_offset),
+ block_direction_fragmentation_type(
+ static_cast<unsigned>(kFragmentNone)) {}
+ RareData(const RareData&) = default;
+ ~RareData() = default;
+
+ NGLogicalSize percentage_resolution_size;
+ NGLogicalSize replaced_percentage_resolution_size;
+
+ NGBfcOffset bfc_offset;
+ NGMarginStrut margin_strut;
+
+ base::Optional<LayoutUnit> floats_bfc_block_offset;
+ LayoutUnit clearance_offset = LayoutUnit::Min();
+
+ LayoutUnit fragmentainer_block_size = NGSizeIndefinite;
+ LayoutUnit fragmentainer_space_at_bfc_start = NGSizeIndefinite;
+
+ unsigned block_direction_fragmentation_type : 2;
+
+ bool MaySkipLayout(const RareData& other) const {
+ return margin_strut == other.margin_strut &&
+ bfc_offset.line_offset == other.bfc_offset.line_offset &&
+ floats_bfc_block_offset == other.floats_bfc_block_offset &&
+ clearance_offset == other.clearance_offset &&
+ fragmentainer_block_size == other.fragmentainer_block_size &&
+ fragmentainer_space_at_bfc_start ==
+ other.fragmentainer_space_at_bfc_start &&
+ block_direction_fragmentation_type ==
+ other.block_direction_fragmentation_type;
+ }
+ };
+
+ // This struct simply allows us easily copy, compare, and initialize all the
+ // bitfields without having to explicitly copy, compare, and initialize each
+ // one (see the outer class constructors, and assignment operators).
+ struct Bitfields {
+ DISALLOW_NEW();
+
+ public:
+ // We explicitly define a default constructor to ensure the kHasRareData
+ // bitfield doesn't accidently get set.
+ Bitfields() : Bitfields(WritingMode::kHorizontalTb) {}
+
+ explicit Bitfields(WritingMode writing_mode)
+ : table_cell_child_layout_phase(
+ static_cast<unsigned>(kNotTableCellChild)),
+ adjoining_floats(static_cast<unsigned>(kFloatTypeNone)),
+ writing_mode(static_cast<unsigned>(writing_mode)),
+ direction(static_cast<unsigned>(TextDirection::kLtr)),
+ flags(kFixedSizeBlockIsDefinite),
+ percentage_inline_storage(kSameAsAvailable),
+ percentage_block_storage(kSameAsAvailable),
+ replaced_percentage_inline_storage(kSameAsAvailable),
+ replaced_percentage_block_storage(kSameAsAvailable) {}
+
+ bool MaySkipLayout(const Bitfields& other) const {
+ return table_cell_child_layout_phase ==
+ other.table_cell_child_layout_phase &&
+ adjoining_floats == other.adjoining_floats &&
+ writing_mode == other.writing_mode && flags == other.flags &&
+ baseline_requests == other.baseline_requests;
+ }
+
+ unsigned table_cell_child_layout_phase : 2; // NGTableCellChildLayoutPhase
+ unsigned adjoining_floats : 2; // NGFloatTypes
+ unsigned writing_mode : 3;
+ unsigned direction : 1;
+ unsigned flags : kNumberOfConstraintSpaceFlags; // ConstraintSpaceFlags
+ unsigned baseline_requests : NGBaselineRequestList::kSerializedBits;
+
+ unsigned percentage_inline_storage : 2; // NGPercentageStorage
+ unsigned percentage_block_storage : 2; // NGPercentageStorage
+ unsigned replaced_percentage_inline_storage : 2; // NGPercentageStorage
+ unsigned replaced_percentage_block_storage : 2; // NGPercentageStorage
+ };
+
+ inline bool HasFlag(ConstraintSpaceFlags mask) const {
+ return bitfields_.flags & static_cast<unsigned>(mask);
}
- NGLogicalSize available_size_;
- NGLogicalSize percentage_resolution_size_;
- NGLogicalSize replaced_percentage_resolution_size_;
- LayoutUnit parent_percentage_resolution_inline_size_;
- NGPhysicalSize initial_containing_block_size_;
+ inline bool HasRareData() const { return HasFlag(kHasRareData); }
- LayoutUnit fragmentainer_block_size_;
- LayoutUnit fragmentainer_space_at_bfc_start_;
+ RareData* EnsureRareData() {
+ if (!HasRareData()) {
+ rare_data_ = new RareData(bfc_offset_);
+ bitfields_.flags |= kHasRareData;
+ }
- unsigned block_direction_fragmentation_type_ : 2;
- unsigned table_cell_child_layout_phase_ : 2; // NGTableCellChildLayoutPhase
- unsigned adjoining_floats_ : 2; // NGFloatTypes
- unsigned writing_mode_ : 3;
- unsigned direction_ : 1;
- unsigned flags_ : kNumberOfConstraintSpaceFlags; // ConstraintSpaceFlags
+ return rare_data_;
+ }
- NGMarginStrut margin_strut_;
- NGBfcOffset bfc_offset_;
- base::Optional<LayoutUnit> floats_bfc_block_offset_;
+ NGLogicalSize available_size_;
- NGExclusionSpace exclusion_space_;
- LayoutUnit clearance_offset_;
+ // To save a little space, we union these two fields. rare_data_ is valid if
+ // the kHasRareData bitfield is set, otherwise bfc_offset_ is valid.
+ union {
+ NGBfcOffset bfc_offset_;
+ RareData* rare_data_;
+ };
- Vector<NGBaselineRequest> baseline_requests_;
+ NGExclusionSpace exclusion_space_;
+ Bitfields bitfields_;
};
inline std::ostream& operator<<(std::ostream& stream,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.cc
index 6b9a51000e3..25f6b5b8345 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.cc
@@ -1,20 +1,122 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
+// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
-#include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
namespace blink {
-NGConstraintSpaceBuilder& NGConstraintSpaceBuilder::AddBaselineRequest(
- const NGBaselineRequest& request) {
- for (const auto& existing : baseline_requests_) {
- if (existing == request)
- return *this;
+namespace {
+
+NGPercentageStorage GetPercentageStorage(LayoutUnit percentage_size,
+ LayoutUnit available_size) {
+ if (percentage_size == available_size)
+ return kSameAsAvailable;
+
+ if (percentage_size == NGSizeIndefinite)
+ return kIndefinite;
+
+ if (percentage_size == LayoutUnit())
+ return kZero;
+
+ return kRareDataPercentage;
+}
+
+} // namespace
+
+NGConstraintSpaceBuilder& NGConstraintSpaceBuilder::SetPercentageResolutionSize(
+ NGLogicalSize percentage_resolution_size) {
+#if DCHECK_IS_ON()
+ DCHECK(is_available_size_set_);
+#endif
+ if (LIKELY(is_in_parallel_flow_)) {
+ space_.bitfields_.percentage_inline_storage =
+ GetPercentageStorage(percentage_resolution_size.inline_size,
+ space_.available_size_.inline_size);
+ if (UNLIKELY(space_.bitfields_.percentage_inline_storage ==
+ kRareDataPercentage)) {
+ space_.EnsureRareData()->percentage_resolution_size.inline_size =
+ percentage_resolution_size.inline_size;
+ }
+
+ space_.bitfields_.percentage_block_storage =
+ GetPercentageStorage(percentage_resolution_size.block_size,
+ space_.available_size_.block_size);
+ if (space_.bitfields_.percentage_block_storage == kRareDataPercentage) {
+ space_.EnsureRareData()->percentage_resolution_size.block_size =
+ percentage_resolution_size.block_size;
+ }
+ } else {
+ AdjustInlineSizeIfNeeded(&percentage_resolution_size.block_size);
+
+ space_.bitfields_.percentage_inline_storage =
+ GetPercentageStorage(percentage_resolution_size.block_size,
+ space_.available_size_.inline_size);
+ if (space_.bitfields_.percentage_inline_storage == kRareDataPercentage) {
+ space_.EnsureRareData()->percentage_resolution_size.inline_size =
+ percentage_resolution_size.block_size;
+ }
+
+ space_.bitfields_.percentage_block_storage =
+ GetPercentageStorage(percentage_resolution_size.inline_size,
+ space_.available_size_.block_size);
+ if (space_.bitfields_.percentage_block_storage == kRareDataPercentage) {
+ space_.EnsureRareData()->percentage_resolution_size.block_size =
+ percentage_resolution_size.inline_size;
+ }
}
- baseline_requests_.push_back(request);
+
+ return *this;
+}
+
+NGConstraintSpaceBuilder&
+NGConstraintSpaceBuilder::SetReplacedPercentageResolutionSize(
+ NGLogicalSize replaced_percentage_resolution_size) {
+#if DCHECK_IS_ON()
+ DCHECK(is_available_size_set_);
+#endif
+ if (LIKELY(is_in_parallel_flow_)) {
+ space_.bitfields_.replaced_percentage_inline_storage =
+ GetPercentageStorage(replaced_percentage_resolution_size.inline_size,
+ space_.available_size_.inline_size);
+ if (UNLIKELY(space_.bitfields_.replaced_percentage_inline_storage ==
+ kRareDataPercentage)) {
+ space_.EnsureRareData()->replaced_percentage_resolution_size.inline_size =
+ replaced_percentage_resolution_size.inline_size;
+ }
+
+ space_.bitfields_.replaced_percentage_block_storage =
+ GetPercentageStorage(replaced_percentage_resolution_size.block_size,
+ space_.available_size_.block_size);
+ if (space_.bitfields_.replaced_percentage_block_storage ==
+ kRareDataPercentage) {
+ space_.EnsureRareData()->replaced_percentage_resolution_size.block_size =
+ replaced_percentage_resolution_size.block_size;
+ }
+ } else {
+ AdjustInlineSizeIfNeeded(&replaced_percentage_resolution_size.block_size);
+
+ space_.bitfields_.replaced_percentage_inline_storage =
+ GetPercentageStorage(replaced_percentage_resolution_size.block_size,
+ space_.available_size_.inline_size);
+ if (space_.bitfields_.replaced_percentage_inline_storage ==
+ kRareDataPercentage) {
+ space_.EnsureRareData()->replaced_percentage_resolution_size.inline_size =
+ replaced_percentage_resolution_size.block_size;
+ }
+
+ space_.bitfields_.replaced_percentage_block_storage =
+ GetPercentageStorage(replaced_percentage_resolution_size.inline_size,
+ space_.available_size_.block_size);
+ if (space_.bitfields_.replaced_percentage_block_storage ==
+ kRareDataPercentage) {
+ space_.EnsureRareData()->replaced_percentage_resolution_size.block_size =
+ replaced_percentage_resolution_size.inline_size;
+ }
+ }
+
return *this;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h
index 9cd328cc435..e7a0eeafe4a 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h
@@ -22,71 +22,127 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
STACK_ALLOCATED();
public:
- // NOTE: This constructor doesn't act like a copy-constructor, it uses the
- // writing_mode and icb_size from the parent constraint space, and passes
- // them to the constructor below.
- NGConstraintSpaceBuilder(const NGConstraintSpace& parent_space)
+ // The setters on this builder are in the writing mode of parent_space.
+ NGConstraintSpaceBuilder(const NGConstraintSpace& parent_space,
+ WritingMode out_writing_mode,
+ bool is_new_fc)
: NGConstraintSpaceBuilder(parent_space.GetWritingMode(),
- parent_space.InitialContainingBlockSize()) {
- parent_percentage_resolution_size_ =
- parent_space.PercentageResolutionSize();
- flags_ = NGConstraintSpace::kFixedSizeBlockIsDefinite;
+ out_writing_mode,
+ is_new_fc) {
+ // Propagate the intermediate layout bit to the child constraint space.
if (parent_space.IsIntermediateLayout())
- flags_ |= NGConstraintSpace::kIntermediateLayout;
+ space_.bitfields_.flags |= NGConstraintSpace::kIntermediateLayout;
}
- // writing_mode is the writing mode that the logical sizes passed to the
- // setters are in.
- NGConstraintSpaceBuilder(WritingMode writing_mode, NGPhysicalSize icb_size)
- : initial_containing_block_size_(icb_size),
- parent_writing_mode_(writing_mode) {
- flags_ = NGConstraintSpace::kFixedSizeBlockIsDefinite;
+ // The setters on this builder are in the writing mode of parent_writing_mode.
+ //
+ // forced_orthogonal_writing_mode_root is set for constraint spaces created
+ // directly from a LayoutObject. In this case parent_writing_mode isn't
+ // actually the parent's, it's the same as out_writing_mode.
+ // When this occurs we would miss setting the kOrthogonalWritingModeRoot flag
+ // unless we force it.
+ NGConstraintSpaceBuilder(WritingMode parent_writing_mode,
+ WritingMode out_writing_mode,
+ bool is_new_fc,
+ bool force_orthogonal_writing_mode_root = false)
+ : space_(out_writing_mode),
+ is_in_parallel_flow_(
+ IsParallelWritingMode(parent_writing_mode, out_writing_mode)),
+ is_new_fc_(is_new_fc),
+ force_orthogonal_writing_mode_root_(
+ force_orthogonal_writing_mode_root) {
+ if (is_new_fc_)
+ space_.bitfields_.flags |= NGConstraintSpace::kNewFormattingContext;
+
+ if (!is_in_parallel_flow_ || force_orthogonal_writing_mode_root_)
+ space_.bitfields_.flags |= NGConstraintSpace::kOrthogonalWritingModeRoot;
+ }
+
+ // If inline size is indefinite, use the fallback size for available inline
+ // size for orthogonal flow roots. See:
+ // https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto
+ void AdjustInlineSizeIfNeeded(LayoutUnit* inline_size) const {
+ DCHECK(!is_in_parallel_flow_);
+ if (*inline_size != NGSizeIndefinite)
+ return;
+ DCHECK_NE(orthogonal_fallback_inline_size_, NGSizeIndefinite);
+ *inline_size = orthogonal_fallback_inline_size_;
}
NGConstraintSpaceBuilder& SetAvailableSize(NGLogicalSize available_size) {
- available_size_ = available_size;
+#if DCHECK_IS_ON()
+ is_available_size_set_ = true;
+#endif
+ space_.available_size_ = available_size;
+
+ if (UNLIKELY(!is_in_parallel_flow_)) {
+ space_.available_size_.Flip();
+ AdjustInlineSizeIfNeeded(&space_.available_size_.inline_size);
+ }
+
return *this;
}
NGConstraintSpaceBuilder& SetPercentageResolutionSize(
- NGLogicalSize percentage_resolution_size) {
- percentage_resolution_size_ = percentage_resolution_size;
- return *this;
- }
+ NGLogicalSize percentage_resolution_size);
NGConstraintSpaceBuilder& SetReplacedPercentageResolutionSize(
- NGLogicalSize replaced_percentage_resolution_size) {
- replaced_percentage_resolution_size_ = replaced_percentage_resolution_size;
+ NGLogicalSize replaced_percentage_resolution_size);
+
+ // Set the fallback available inline-size for an orthogonal child. The size is
+ // the inline size in the writing mode of the orthogonal child.
+ NGConstraintSpaceBuilder& SetOrthogonalFallbackInlineSize(LayoutUnit size) {
+ orthogonal_fallback_inline_size_ = size;
return *this;
}
NGConstraintSpaceBuilder& SetFragmentainerBlockSize(LayoutUnit size) {
- fragmentainer_block_size_ = size;
+#if DCHECK_IS_ON()
+ DCHECK(!is_fragmentainer_block_size_set_);
+ is_fragmentainer_block_size_set_ = true;
+#endif
+ if (size != NGSizeIndefinite)
+ space_.EnsureRareData()->fragmentainer_block_size = size;
return *this;
}
NGConstraintSpaceBuilder& SetFragmentainerSpaceAtBfcStart(LayoutUnit space) {
- fragmentainer_space_at_bfc_start_ = space;
+#if DCHECK_IS_ON()
+ DCHECK(!is_fragmentainer_space_at_bfc_start_set_);
+ is_fragmentainer_space_at_bfc_start_set_ = true;
+#endif
+ if (space != NGSizeIndefinite)
+ space_.EnsureRareData()->fragmentainer_space_at_bfc_start = space;
return *this;
}
- NGConstraintSpaceBuilder& SetTextDirection(TextDirection text_direction) {
- text_direction_ = text_direction;
+ NGConstraintSpaceBuilder& SetTextDirection(TextDirection direction) {
+ space_.bitfields_.direction = static_cast<unsigned>(direction);
return *this;
}
NGConstraintSpaceBuilder& SetIsFixedSizeInline(bool b) {
- SetFlag(NGConstraintSpace::kFixedSizeInline, b);
+ if (LIKELY(is_in_parallel_flow_))
+ SetFlag(NGConstraintSpace::kFixedSizeInline, b);
+ else
+ SetFlag(NGConstraintSpace::kFixedSizeBlock, b);
+
return *this;
}
NGConstraintSpaceBuilder& SetIsFixedSizeBlock(bool b) {
- SetFlag(NGConstraintSpace::kFixedSizeBlock, b);
+ if (LIKELY(is_in_parallel_flow_))
+ SetFlag(NGConstraintSpace::kFixedSizeBlock, b);
+ else
+ SetFlag(NGConstraintSpace::kFixedSizeInline, b);
+
return *this;
}
NGConstraintSpaceBuilder& SetFixedSizeBlockIsDefinite(bool b) {
- SetFlag(NGConstraintSpace::kFixedSizeBlockIsDefinite, b);
+ if (LIKELY(is_in_parallel_flow_ || !force_orthogonal_writing_mode_root_))
+ SetFlag(NGConstraintSpace::kFixedSizeBlockIsDefinite, b);
+
return *this;
}
@@ -102,7 +158,14 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
NGConstraintSpaceBuilder& SetFragmentationType(
NGFragmentationType fragmentation_type) {
- fragmentation_type_ = fragmentation_type;
+#if DCHECK_IS_ON()
+ DCHECK(!is_block_direction_fragmentation_type_set_);
+ is_block_direction_fragmentation_type_set_ = true;
+#endif
+ if (fragmentation_type != NGFragmentationType::kFragmentNone) {
+ space_.EnsureRareData()->block_direction_fragmentation_type =
+ fragmentation_type;
+ }
return *this;
}
@@ -111,10 +174,6 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
return *this;
}
- NGConstraintSpaceBuilder& SetIsNewFormattingContext(bool b) {
- SetFlag(NGConstraintSpace::kNewFormattingContext, b);
- return *this;
- }
NGConstraintSpaceBuilder& SetIsAnonymous(bool b) {
SetFlag(NGConstraintSpace::kAnonymous, b);
return *this;
@@ -126,27 +185,55 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
}
NGConstraintSpaceBuilder& SetAdjoiningFloatTypes(NGFloatTypes floats) {
- adjoining_floats_ = floats;
+ if (!is_new_fc_)
+ space_.bitfields_.adjoining_floats = static_cast<unsigned>(floats);
+
return *this;
}
NGConstraintSpaceBuilder& SetMarginStrut(const NGMarginStrut& margin_strut) {
- margin_strut_ = margin_strut;
+#if DCHECK_IS_ON()
+ DCHECK(!is_margin_strut_set_);
+ is_margin_strut_set_ = true;
+#endif
+ if (!is_new_fc_ && margin_strut != NGMarginStrut())
+ space_.EnsureRareData()->margin_strut = margin_strut;
+
return *this;
}
NGConstraintSpaceBuilder& SetBfcOffset(const NGBfcOffset& bfc_offset) {
- bfc_offset_ = bfc_offset;
+ if (!is_new_fc_) {
+ if (space_.HasRareData())
+ space_.rare_data_->bfc_offset = bfc_offset;
+ else
+ space_.bfc_offset_ = bfc_offset;
+ }
+
return *this;
}
NGConstraintSpaceBuilder& SetFloatsBfcBlockOffset(
const base::Optional<LayoutUnit>& floats_bfc_block_offset) {
- floats_bfc_block_offset_ = floats_bfc_block_offset;
+#if DCHECK_IS_ON()
+ DCHECK(!is_floats_bfc_block_offset_set_);
+ is_floats_bfc_block_offset_set_ = true;
+#endif
+ if (LIKELY(!is_new_fc_ && floats_bfc_block_offset != base::nullopt)) {
+ space_.EnsureRareData()->floats_bfc_block_offset =
+ floats_bfc_block_offset;
+ }
+
return *this;
}
NGConstraintSpaceBuilder& SetClearanceOffset(LayoutUnit clearance_offset) {
- clearance_offset_ = clearance_offset;
+#if DCHECK_IS_ON()
+ DCHECK(!is_clearance_offset_set_);
+ is_clearance_offset_set_ = true;
+#endif
+ if (!is_new_fc_ && clearance_offset != LayoutUnit::Min())
+ space_.EnsureRareData()->clearance_offset = clearance_offset;
+
return *this;
}
@@ -157,80 +244,81 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
NGConstraintSpaceBuilder& SetTableCellChildLayoutPhase(
NGTableCellChildLayoutPhase table_cell_child_layout_phase) {
- table_cell_child_layout_phase_ = table_cell_child_layout_phase;
- return *this;
- }
-
- // Usually orthogonality is inferred from the WritingMode parameters passed to
- // the constructor and ToConstraintSpace. But if you're passing the same
- // writing mode to those methods but the node targeted by this ConstraintSpace
- // is an orthogonal writing mode root, call this method to have the
- // appropriate flags set on the resulting ConstraintSpace.
- NGConstraintSpaceBuilder& SetIsOrthogonalWritingModeRoot(bool b) {
- force_orthogonal_writing_mode_root_ = b;
+ space_.bitfields_.table_cell_child_layout_phase =
+ table_cell_child_layout_phase;
return *this;
}
NGConstraintSpaceBuilder& SetExclusionSpace(
const NGExclusionSpace& exclusion_space) {
- exclusion_space_ = &exclusion_space;
+ if (!is_new_fc_)
+ space_.exclusion_space_ = exclusion_space;
+
return *this;
}
- void AddBaselineRequests(const Vector<NGBaselineRequest>& requests) {
+ void AddBaselineRequests(const NGBaselineRequestList requests) {
DCHECK(baseline_requests_.IsEmpty());
baseline_requests_.AppendVector(requests);
}
- NGConstraintSpaceBuilder& AddBaselineRequest(const NGBaselineRequest&);
+ NGConstraintSpaceBuilder& AddBaselineRequest(
+ const NGBaselineRequest request) {
+ baseline_requests_.push_back(request);
+ return *this;
+ }
- // Creates a new constraint space. This may be called multiple times, for
- // example the constraint space will be different for a child which:
- // - Establishes a new formatting context.
- // - Is within a fragmentation container and needs its fragmentation offset
- // updated.
- // - Has its size is determined by its parent layout (flex, abs-pos).
- //
- // WritingMode specifies the writing mode of the generated space.
- const NGConstraintSpace ToConstraintSpace(WritingMode out_writing_mode) {
- return NGConstraintSpace(out_writing_mode,
- flags_ & NGConstraintSpace::kNewFormattingContext,
- *this);
+ // Creates a new constraint space.
+ const NGConstraintSpace ToConstraintSpace() {
+#if DCHECK_IS_ON()
+ DCHECK(!to_constraint_space_called_)
+ << "ToConstraintSpace should only be called once.";
+ to_constraint_space_called_ = true;
+#endif
+
+ DCHECK(!is_new_fc_ || !space_.bitfields_.adjoining_floats);
+ DCHECK_EQ(space_.HasFlag(NGConstraintSpace::kOrthogonalWritingModeRoot),
+ !is_in_parallel_flow_ || force_orthogonal_writing_mode_root_);
+
+ DCHECK(!force_orthogonal_writing_mode_root_ || is_in_parallel_flow_)
+ << "Forced and inferred orthogonal writing mode shouldn't happen "
+ "simultaneously. Inferred means the constraints are in parent "
+ "writing mode, forced means they are in child writing mode.";
+
+ space_.bitfields_.baseline_requests = baseline_requests_.Serialize();
+ return std::move(space_);
}
private:
void SetFlag(NGConstraintSpace::ConstraintSpaceFlags mask, bool value) {
- flags_ = (flags_ & ~static_cast<unsigned>(mask)) |
- (-(int32_t)value & static_cast<unsigned>(mask));
- }
-
- // NOTE: The below NGLogicalSizes are relative to parent_writing_mode_.
- NGLogicalSize available_size_;
- NGLogicalSize percentage_resolution_size_;
- NGLogicalSize replaced_percentage_resolution_size_;
-
- base::Optional<NGLogicalSize> parent_percentage_resolution_size_;
- NGPhysicalSize initial_containing_block_size_;
- LayoutUnit fragmentainer_block_size_ = NGSizeIndefinite;
- LayoutUnit fragmentainer_space_at_bfc_start_ = NGSizeIndefinite;
-
- WritingMode parent_writing_mode_;
- NGFragmentationType fragmentation_type_ = kFragmentNone;
- NGTableCellChildLayoutPhase table_cell_child_layout_phase_ =
- kNotTableCellChild;
- NGFloatTypes adjoining_floats_ = kFloatTypeNone;
- TextDirection text_direction_ = TextDirection::kLtr;
- bool force_orthogonal_writing_mode_root_ = false;
-
- unsigned flags_;
-
- NGMarginStrut margin_strut_;
- NGBfcOffset bfc_offset_;
- base::Optional<LayoutUnit> floats_bfc_block_offset_;
- const NGExclusionSpace* exclusion_space_ = nullptr;
- LayoutUnit clearance_offset_;
- Vector<NGBaselineRequest> baseline_requests_;
-
- friend class NGConstraintSpace;
+ space_.bitfields_.flags =
+ (space_.bitfields_.flags & ~static_cast<unsigned>(mask)) |
+ (-(int32_t)value & static_cast<unsigned>(mask));
+ }
+
+ NGConstraintSpace space_;
+
+ // Orthogonal writing mode roots may need a fallback, to prevent available
+ // inline size from being indefinite, which isn't allowed. This is the
+ // available inline size in the writing mode of the orthogonal child.
+ LayoutUnit orthogonal_fallback_inline_size_ = NGSizeIndefinite;
+
+ bool is_in_parallel_flow_;
+ bool is_new_fc_;
+ bool force_orthogonal_writing_mode_root_;
+
+#if DCHECK_IS_ON()
+ bool is_available_size_set_ = false;
+ bool is_fragmentainer_block_size_set_ = false;
+ bool is_fragmentainer_space_at_bfc_start_set_ = false;
+ bool is_block_direction_fragmentation_type_set_ = false;
+ bool is_margin_strut_set_ = false;
+ bool is_floats_bfc_block_offset_set_ = false;
+ bool is_clearance_offset_set_ = false;
+
+ bool to_constraint_space_called_ = false;
+#endif
+
+ NGBaselineRequestList baseline_requests_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder_test.cc
index 98cfab981a6..21e6911fae9 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder_test.cc
@@ -17,24 +17,27 @@ TEST(NGConstraintSpaceBuilderTest, AvailableSizeFromHorizontalICB) {
NGPhysicalSize icb_size{NGSizeIndefinite, LayoutUnit(51)};
NGConstraintSpaceBuilder horizontal_builder(WritingMode::kHorizontalTb,
- icb_size);
+ WritingMode::kHorizontalTb,
+ /* is_new_fc */ true);
NGLogicalSize fixed_size{LayoutUnit(100), LayoutUnit(200)};
NGLogicalSize indefinite_size{NGSizeIndefinite, NGSizeIndefinite};
+ horizontal_builder.SetOrthogonalFallbackInlineSize(icb_size.height);
horizontal_builder.SetAvailableSize(fixed_size);
horizontal_builder.SetPercentageResolutionSize(fixed_size);
NGConstraintSpaceBuilder vertical_builder(
- horizontal_builder.ToConstraintSpace(WritingMode::kHorizontalTb));
+ horizontal_builder.ToConstraintSpace(), WritingMode::kVerticalLr,
+ /* is_new_fc */ true);
+ vertical_builder.SetOrthogonalFallbackInlineSize(icb_size.height);
vertical_builder.SetAvailableSize(indefinite_size);
vertical_builder.SetPercentageResolutionSize(indefinite_size);
- NGConstraintSpace space =
- vertical_builder.ToConstraintSpace(WritingMode::kVerticalLr);
+ NGConstraintSpace space = vertical_builder.ToConstraintSpace();
EXPECT_EQ(space.AvailableSize().inline_size, icb_size.height);
- EXPECT_EQ(space.PercentageResolutionSize().inline_size, icb_size.height);
+ EXPECT_EQ(space.PercentageResolutionInlineSize(), icb_size.height);
};
// Asserts that indefinite inline length becomes initial containing
@@ -43,24 +46,27 @@ TEST(NGConstraintSpaceBuilderTest, AvailableSizeFromVerticalICB) {
NGPhysicalSize icb_size{LayoutUnit(51), NGSizeIndefinite};
NGConstraintSpaceBuilder horizontal_builder(WritingMode::kVerticalLr,
- icb_size);
+ WritingMode::kVerticalLr,
+ /* is_new_fc */ true);
NGLogicalSize fixed_size{LayoutUnit(100), LayoutUnit(200)};
NGLogicalSize indefinite_size{NGSizeIndefinite, NGSizeIndefinite};
+ horizontal_builder.SetOrthogonalFallbackInlineSize(icb_size.width);
horizontal_builder.SetAvailableSize(fixed_size);
horizontal_builder.SetPercentageResolutionSize(fixed_size);
NGConstraintSpaceBuilder vertical_builder(
- horizontal_builder.ToConstraintSpace(WritingMode::kVerticalLr));
+ horizontal_builder.ToConstraintSpace(), WritingMode::kHorizontalTb,
+ /* is_new_fc */ true);
+ vertical_builder.SetOrthogonalFallbackInlineSize(icb_size.width);
vertical_builder.SetAvailableSize(indefinite_size);
vertical_builder.SetPercentageResolutionSize(indefinite_size);
- NGConstraintSpace space =
- vertical_builder.ToConstraintSpace(WritingMode::kHorizontalTb);
+ NGConstraintSpace space = vertical_builder.ToConstraintSpace();
EXPECT_EQ(space.AvailableSize().inline_size, icb_size.width);
- EXPECT_EQ(space.PercentageResolutionSize().inline_size, icb_size.width);
+ EXPECT_EQ(space.PercentageResolutionInlineSize(), icb_size.width);
};
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc
index eddb2067b2e..5a75ed36bf2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc
@@ -9,17 +9,10 @@
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
-NGContainerFragmentBuilder::NGContainerFragmentBuilder(
- scoped_refptr<const ComputedStyle> style,
- WritingMode writing_mode,
- TextDirection direction)
- : NGBaseFragmentBuilder(std::move(style), writing_mode, direction) {}
-
-NGContainerFragmentBuilder::~NGContainerFragmentBuilder() = default;
-
NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
const NGLayoutResult& child,
const NGLogicalOffset& child_offset) {
@@ -59,17 +52,60 @@ NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
}
for (const NGOutOfFlowPositionedDescendant& descendant :
out_of_flow_descendants) {
- oof_positioned_candidates_.push_back(
- NGOutOfFlowPositionedCandidate{descendant, top_left_offset});
+ // If we are inside the inline algorithm, (and creating a fragment for a
+ // <span> or similar), we may add a child (e.g. an atomic-inline) which
+ // has OOF descandants.
+ //
+ // This checks if the object creating this box will be the container for
+ // the given descendant.
+ if (layout_object_ && layout_object_->IsLayoutInline() &&
+ layout_object_->CanContainOutOfFlowPositionedElement(
+ descendant.node.Style().GetPosition()) &&
+ !descendant.inline_container) {
+ NGOutOfFlowPositionedDescendant descendant_copy(descendant);
+ descendant_copy.inline_container = layout_object_;
+ oof_positioned_candidates_.push_back(
+ NGOutOfFlowPositionedCandidate(descendant_copy, top_left_offset));
+ } else {
+ oof_positioned_candidates_.push_back(
+ NGOutOfFlowPositionedCandidate{descendant, top_left_offset});
+ }
}
}
+ if (child.HasOrthogonalFlowRoots())
+ has_orthogonal_flow_roots_ = true;
+
return AddChild(child.PhysicalFragment(), child_offset);
}
NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
scoped_refptr<const NGPhysicalFragment> child,
const NGLogicalOffset& child_offset) {
+ NGBreakToken* child_break_token = child->BreakToken();
+ if (child_break_token) {
+ switch (child->Type()) {
+ case NGPhysicalFragment::kFragmentBox:
+ case NGPhysicalFragment::kFragmentRenderedLegend:
+ child_break_tokens_.push_back(child_break_token);
+ break;
+ case NGPhysicalFragment::kFragmentLineBox:
+ // NGInlineNode produces multiple line boxes in an anonymous box. We
+ // won't know up front which line box to insert a fragment break before
+ // (due to widows), so keep them all until we know.
+ inline_break_tokens_.push_back(child_break_token);
+ break;
+ case NGPhysicalFragment::kFragmentText:
+ default:
+ NOTREACHED();
+ break;
+ }
+ }
+
+ if (!IsParallelWritingMode(child->Style().GetWritingMode(),
+ Style().GetWritingMode()))
+ has_orthogonal_flow_roots_ = true;
+
if (!has_last_resort_break_) {
if (const auto* token = child->BreakToken()) {
if (token->IsBlockType() &&
@@ -77,11 +113,7 @@ NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
has_last_resort_break_ = true;
}
}
- // Assume that if we have one child, we may have more than one and try to
- // limit the number of allocations we would do in that case.
- if (!children_.capacity())
- children_.ReserveCapacity(16);
- children_.emplace_back(std::move(child), NGPhysicalOffset());
+ children_.emplace_back(std::move(child));
offsets_.push_back(child_offset);
return *this;
}
@@ -139,8 +171,8 @@ void NGContainerFragmentBuilder::GetAndClearOutOfFlowDescendantCandidates(
DCHECK_GE(InlineSize(), LayoutUnit());
DCHECK_GE(BlockSize(), LayoutUnit());
- NGPhysicalSize builder_physical_size{
- Size().ConvertToPhysical(GetWritingMode())};
+ NGPhysicalSize builder_physical_size =
+ ToNGPhysicalSize(Size(), GetWritingMode());
for (NGOutOfFlowPositionedCandidate& candidate : oof_positioned_candidates_) {
TextDirection direction =
@@ -171,19 +203,13 @@ void NGContainerFragmentBuilder::GetAndClearOutOfFlowDescendantCandidates(
// The descendant may be a "position: absolute" which contains a "position:
// fixed" for example. (This fragment isn't the containing block for the
// fixed descendant).
- oof_positioned_candidates_.clear();
+ oof_positioned_candidates_.Shrink(0);
}
-void NGContainerFragmentBuilder::MoveOutOfFlowDescendantCandidatesToDescendants(
- const LayoutObject* inline_container) {
+void NGContainerFragmentBuilder::
+ MoveOutOfFlowDescendantCandidatesToDescendants() {
GetAndClearOutOfFlowDescendantCandidates(&oof_positioned_descendants_,
nullptr);
- if (inline_container) {
- for (auto& descendant : oof_positioned_descendants_) {
- if (!descendant.inline_container)
- descendant.inline_container = inline_container;
- }
- }
}
#ifndef NDEBUG
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h
index 43fc62abf0c..2c2a2cc3f4b 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h
@@ -12,39 +12,28 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_margin_strut.h"
#include "third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_base_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_floats_utils.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_link.h"
#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
-class ComputedStyle;
class NGExclusionSpace;
class NGLayoutResult;
class NGPhysicalFragment;
-class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
+class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
STACK_ALLOCATED();
public:
+ typedef Vector<scoped_refptr<const NGPhysicalFragment>, 16> ChildrenVector;
typedef Vector<NGLogicalOffset, 16> OffsetVector;
- ~NGContainerFragmentBuilder() override;
-
- LayoutUnit InlineSize() const { return size_.inline_size; }
- LayoutUnit BlockSize() const { return size_.block_size; }
- const NGLogicalSize& Size() const { return size_; }
- NGContainerFragmentBuilder& SetInlineSize(LayoutUnit inline_size) {
- DCHECK_GE(inline_size, LayoutUnit());
- size_.inline_size = inline_size;
- return *this;
- }
- void SetBlockSize(LayoutUnit block_size) { size_.block_size = block_size; }
-
LayoutUnit BfcLineOffset() const { return bfc_line_offset_; }
NGContainerFragmentBuilder& SetBfcLineOffset(LayoutUnit bfc_line_offset) {
bfc_line_offset_ = bfc_line_offset;
@@ -87,16 +76,15 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
return *this;
}
- virtual NGContainerFragmentBuilder& AddChild(const NGLayoutResult&,
- const NGLogicalOffset&);
+ NGContainerFragmentBuilder& AddChild(const NGLayoutResult&,
+ const NGLogicalOffset&);
// This version of AddChild will not propagate floats/out_of_flow.
// Use the AddChild(NGLayoutResult) variant if NGLayoutResult is available.
- virtual NGContainerFragmentBuilder& AddChild(
- scoped_refptr<const NGPhysicalFragment>,
- const NGLogicalOffset&);
+ NGContainerFragmentBuilder& AddChild(scoped_refptr<const NGPhysicalFragment>,
+ const NGLogicalOffset&);
- const Vector<NGLink>& Children() const { return children_; }
+ const ChildrenVector& Children() const { return children_; }
// Builder has non-trivial out-of-flow descendant methods.
// These methods are building blocks for implementation of
@@ -144,10 +132,18 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
Vector<NGOutOfFlowPositionedDescendant>* descendant_candidates,
const LayoutObject* container);
- // Utility routine to move all OOF descendant candidates to descendants.
- // Use if fragment cannot position any OOF children.
- void MoveOutOfFlowDescendantCandidatesToDescendants(
- const LayoutObject* inline_container);
+ bool HasOutOfFlowDescendantCandidates() const {
+ return !oof_positioned_candidates_.IsEmpty();
+ }
+
+ // This method should only be used within the inline layout algorithm. It is
+ // used to convert all OOF descendant candidates to descendants.
+ //
+ // During the inline layout algorithm, we don't have enough information to
+ // position OOF candidates yet, (as a containing box may be split over
+ // multiple lines), instead we bubble all the descendants up to the parent
+ // block layout algorithm, to perform the final OOF layout and positioning.
+ void MoveOutOfFlowDescendantCandidatesToDescendants();
NGContainerFragmentBuilder& SetIsPushedByFloats() {
is_pushed_by_floats_ = true;
@@ -171,7 +167,7 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
protected:
// An out-of-flow positioned-candidate is a temporary data structure used
- // within the NGFragmentBuilder.
+ // within the NGBoxFragmentBuilder.
//
// A positioned-candidate can be:
// 1. A direct out-of-flow positioned child. The child_offset is (0,0).
@@ -182,7 +178,7 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
// cannot be computed until we know the current fragment's size.
//
// When returning the positioned-candidates (from
- // GetAndClearOutOfFlowDescendantCandidates), the NGFragmentBuilder will
+ // GetAndClearOutOfFlowDescendantCandidates), the NGBoxFragmentBuilder will
// convert the positioned-candidate to a positioned-descendant using the
// physical size the fragment builder.
struct NGOutOfFlowPositionedCandidate {
@@ -208,11 +204,10 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
line_direction(line_direction_arg) {}
};
- NGContainerFragmentBuilder(scoped_refptr<const ComputedStyle>,
- WritingMode,
- TextDirection);
-
- NGLogicalSize size_;
+ NGContainerFragmentBuilder(scoped_refptr<const ComputedStyle> style,
+ WritingMode writing_mode,
+ TextDirection direction)
+ : NGFragmentBuilder(std::move(style), writing_mode, direction) {}
LayoutUnit bfc_line_offset_;
base::Optional<LayoutUnit> bfc_block_offset_;
@@ -224,26 +219,27 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGBaseFragmentBuilder {
NGUnpositionedListMarker unpositioned_list_marker_;
- // Store NGLinks rather than NGPhysicalOffsets even though we don't have the
- // offsets yet to allow us to move the entire vector to the fragment at
- // construction time.
- // Unlike OffsetVector, we don't want to keep the inline capacity around
- // because this vector will be long-lived, and it would be wasteful to reserve
- // space for 16 children in every fragment. Instead, we reserve some initial
- // capacity for it when adding the first child and shrink it down when
- // creating the fragment.
- Vector<NGLink> children_;
+ ChildrenVector children_;
// Logical offsets for the children. Stored as logical offsets as we can't
// convert to physical offsets until layout of all children has been
// determined.
OffsetVector offsets_;
+ // Only used by the NGBoxFragmentBuilder subclass, but defined here to avoid
+ // a virtual function call.
+ NGBreakTokenVector child_break_tokens_;
+ NGBreakTokenVector inline_break_tokens_;
+
NGFloatTypes adjoining_floats_ = kFloatTypeNone;
bool has_last_resort_break_ = false;
bool is_pushed_by_floats_ = false;
+
+ bool has_orthogonal_flow_roots_ = false;
+
+ friend class NGPhysicalContainerFragment;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc
index 548cdf19aaa..600074f594f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc
@@ -22,7 +22,9 @@ NGFieldsetLayoutAlgorithm::NGFieldsetLayoutAlgorithm(
NGBlockNode node,
const NGConstraintSpace& space,
const NGBreakToken* break_token)
- : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {}
+ : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {
+ container_builder_.SetIsNewFormattingContext(space.IsNewFormattingContext());
+}
scoped_refptr<NGLayoutResult> NGFieldsetLayoutAlgorithm::Layout() {
// TODO(mstensho): Support block fragmentation.
@@ -146,33 +148,7 @@ base::Optional<MinMaxSize> NGFieldsetLayoutAlgorithm::ComputeMinMaxSize(
return sizes;
if (NGBlockNode legend = Node().GetRenderedLegend()) {
- // We'll need extrinsic sizing data when computing min/max for orthogonal
- // flow roots, because calculating min/max in that case will involve doing
- // layout. Note that we only need to do this for the legend, and not for the
- // fieldset contents. The contents child is just an anonymous one, which
- // inherits writing-mode from the fieldset, so it can never be a writing
- // mode root.
- NGConstraintSpace extrinsic_constraint_space;
- const NGConstraintSpace* optional_constraint_space = nullptr;
- if (!IsParallelWritingMode(Style().GetWritingMode(),
- legend.Style().GetWritingMode())) {
- NGBoxStrut border_padding = ComputeBorders(ConstraintSpace(), Node()) +
- ComputePadding(ConstraintSpace(), Style());
- // If there is a resolvable extrinsic block size, use that as input.
- // Otherwise we'll fall back to the initial containing block size as a
- // constraint.
- LayoutUnit extrinsic_block_size = ComputeBlockSizeForFragment(
- ConstraintSpace(), Style(), NGSizeIndefinite, border_padding);
- if (extrinsic_block_size != NGSizeIndefinite) {
- extrinsic_block_size -= border_padding.BlockSum();
- extrinsic_block_size = extrinsic_block_size.ClampNegativeToZero();
- }
- extrinsic_constraint_space = CreateExtrinsicConstraintSpaceForChild(
- ConstraintSpace(), extrinsic_block_size, legend);
- optional_constraint_space = &extrinsic_constraint_space;
- }
- sizes = ComputeMinAndMaxContentContribution(
- Style().GetWritingMode(), legend, input, optional_constraint_space);
+ sizes = ComputeMinAndMaxContentContribution(Style(), legend, input);
sizes += ComputeMinMaxMargins(Style(), legend).InlineSum();
}
// The fieldset content includes the fieldset padding (and any scrollbars),
@@ -181,8 +157,8 @@ base::Optional<MinMaxSize> NGFieldsetLayoutAlgorithm::ComputeMinMaxSize(
sizes += ComputePadding(ConstraintSpace(), node_.Style()).InlineSum();
if (NGBlockNode content = Node().GetFieldsetContent()) {
- MinMaxSize content_minmax = ComputeMinAndMaxContentContribution(
- Style().GetWritingMode(), content, input);
+ MinMaxSize content_minmax =
+ ComputeMinAndMaxContentContribution(Style(), content, input);
content_minmax += ComputeMinMaxMargins(Style(), content).InlineSum();
sizes.Encompass(content_minmax);
}
@@ -195,27 +171,30 @@ const NGConstraintSpace
NGFieldsetLayoutAlgorithm::CreateConstraintSpaceForLegend(
NGBlockNode legend,
NGLogicalSize available_size) {
- NGConstraintSpaceBuilder builder(ConstraintSpace());
+ NGConstraintSpaceBuilder builder(
+ ConstraintSpace(), legend.Style().GetWritingMode(), /* is_new_fc */ true);
+ SetOrthogonalFallbackInlineSizeIfNeeded(Style(), legend, &builder);
+
builder.SetAvailableSize(available_size);
NGLogicalSize percentage_size =
CalculateChildPercentageSize(ConstraintSpace(), Node(), available_size);
builder.SetPercentageResolutionSize(percentage_size);
- builder.SetIsNewFormattingContext(true);
- builder.SetIsShrinkToFit(true);
+ builder.SetIsShrinkToFit(legend.Style().LogicalWidth().IsAuto());
builder.SetTextDirection(legend.Style().Direction());
- return builder.ToConstraintSpace(legend.Style().GetWritingMode());
+ return builder.ToConstraintSpace();
}
const NGConstraintSpace
NGFieldsetLayoutAlgorithm::CreateConstraintSpaceForFieldsetContent(
NGLogicalSize padding_box_size) {
- NGConstraintSpaceBuilder builder(ConstraintSpace());
+ NGConstraintSpaceBuilder builder(ConstraintSpace(),
+ ConstraintSpace().GetWritingMode(),
+ /* is_new_fc */ true);
+ builder.SetAvailableSize(padding_box_size);
builder.SetPercentageResolutionSize(
ConstraintSpace().PercentageResolutionSize());
- builder.SetAvailableSize(padding_box_size);
builder.SetIsFixedSizeBlock(padding_box_size.block_size != NGSizeIndefinite);
- builder.SetIsNewFormattingContext(true);
- return builder.ToConstraintSpace(ConstraintSpace().GetWritingMode());
+ return builder.ToConstraintSpace();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h
index e4fb5a95466..3f1946d0f84 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
namespace blink {
@@ -18,7 +18,7 @@ class NGConstraintSpace;
class CORE_EXPORT NGFieldsetLayoutAlgorithm
: public NGLayoutAlgorithm<NGBlockNode,
- NGFragmentBuilder,
+ NGBoxFragmentBuilder,
NGBlockBreakToken> {
public:
NGFieldsetLayoutAlgorithm(NGBlockNode node,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc
index 22ce230d365..1172302da6d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc
@@ -35,7 +35,7 @@ class NGFieldsetLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
scoped_refptr<NGLayoutResult> result =
NGBlockLayoutAlgorithm(node, space).Layout();
- return ToNGPhysicalBoxFragment(result->PhysicalFragment().get());
+ return ToNGPhysicalBoxFragment(result->PhysicalFragment());
}
scoped_refptr<const NGPhysicalBoxFragment> RunBlockLayoutAlgorithm(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc
index a28b35973bb..2b3e9f641b2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.cc
@@ -7,10 +7,12 @@
#include <memory>
#include "third_party/blink/renderer/core/layout/flexible_box_algorithm.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
+#include "third_party/blink/renderer/core/layout/layout_flexible_box.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -18,7 +20,9 @@ namespace blink {
NGFlexLayoutAlgorithm::NGFlexLayoutAlgorithm(NGBlockNode node,
const NGConstraintSpace& space,
const NGBreakToken* break_token)
- : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {}
+ : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {
+ container_builder_.SetIsNewFormattingContext(space.IsNewFormattingContext());
+}
scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
DCHECK(!Style().IsColumnFlexDirection())
@@ -28,9 +32,10 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
NGLogicalSize flex_container_border_box_size =
CalculateBorderBoxSize(ConstraintSpace(), Node());
+ NGBoxStrut flex_container_border_scrollbar_padding =
+ CalculateBorderScrollbarPadding(ConstraintSpace(), Node());
NGLogicalSize flex_container_content_box_size = ShrinkAvailableSize(
- flex_container_border_box_size,
- CalculateBorderScrollbarPadding(ConstraintSpace(), Node()));
+ flex_container_border_box_size, flex_container_border_scrollbar_padding);
LayoutUnit flex_container_border_box_inline_size =
flex_container_border_box_size.inline_size;
LayoutUnit flex_container_content_inline_size =
@@ -43,15 +48,20 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
if (child.IsOutOfFlowPositioned())
continue;
+ const ComputedStyle& child_style = child.Style();
+ NGConstraintSpaceBuilder builder(ConstraintSpace(),
+ child_style.GetWritingMode(),
+ /* is_new_fc */ true);
+ SetOrthogonalFallbackInlineSizeIfNeeded(Style(), child, &builder);
+
NGConstraintSpace child_space =
- NGConstraintSpaceBuilder(ConstraintSpace())
- .SetAvailableSize(flex_container_content_box_size)
+ builder.SetAvailableSize(flex_container_content_box_size)
.SetPercentageResolutionSize(flex_container_content_box_size)
- .ToConstraintSpace(child.Style().GetWritingMode());
+ .ToConstraintSpace();
LayoutUnit main_axis_border_and_padding =
- ComputeBorders(child_space, child.Style()).InlineSum() +
- ComputePadding(child_space, child.Style()).InlineSum();
+ ComputeBorders(child_space, child_style).InlineSum() +
+ ComputePadding(child_space, child_style).InlineSum();
// ComputeMinMaxSize will layout the child if it has an orthogonal writing
// mode. MinMaxSize will be in the container's inline direction.
MinMaxSizeInput zero_input;
@@ -59,20 +69,19 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
ConstraintSpace().GetWritingMode(), zero_input, &child_space);
LayoutUnit flex_base_border_box;
- if (child.Style().FlexBasis().IsAuto() && child.Style().Width().IsAuto()) {
+ if (child_style.FlexBasis().IsAuto() && child_style.Width().IsAuto()) {
flex_base_border_box = min_max_sizes_border_box.max_size;
} else {
- Length length_to_resolve = child.Style().FlexBasis();
+ Length length_to_resolve = child_style.FlexBasis();
if (length_to_resolve.IsAuto())
- length_to_resolve = child.Style().Width();
+ length_to_resolve = child_style.Width();
DCHECK(!length_to_resolve.IsAuto());
// TODO(dgrogan): Use ResolveBlockLength here for column flex boxes.
flex_base_border_box = ResolveInlineLength(
- child_space, child.Style(), min_max_sizes_border_box,
- length_to_resolve, LengthResolveType::kContentSize,
- LengthResolvePhase::kLayout);
+ child_space, child_style, min_max_sizes_border_box, length_to_resolve,
+ LengthResolveType::kContentSize, LengthResolvePhase::kLayout);
}
// Spec calls this "flex base size"
@@ -83,7 +92,7 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
flex_base_border_box - main_axis_border_and_padding;
LayoutUnit main_axis_margin =
- ComputeMarginsForSelf(child_space, child.Style()).InlineSum();
+ ComputeMarginsForSelf(child_space, child_style).InlineSum();
// TODO(dgrogan): When child has a min/max-{width,height} set, call
// Resolve{Inline,Block}Length here with child's style and constraint space.
@@ -101,10 +110,10 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
.ng_input_node = child;
}
- NGBoxStrut borders_scrollbar_padding =
- CalculateBorderScrollbarPadding(ConstraintSpace(), Node());
- LayoutUnit main_axis_offset = borders_scrollbar_padding.inline_start;
- LayoutUnit cross_axis_offset = borders_scrollbar_padding.block_start;
+ LayoutUnit main_axis_offset =
+ flex_container_border_scrollbar_padding.inline_start;
+ LayoutUnit cross_axis_offset =
+ flex_container_border_scrollbar_padding.block_start;
FlexLine* line;
while ((line = algorithm.ComputeNextFlexLine(
flex_container_border_box_inline_size))) {
@@ -114,18 +123,23 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
while (!line->ResolveFlexibleLengths()) {
continue;
}
- for (size_t i = 0; i < line->line_items.size(); ++i) {
+ for (wtf_size_t i = 0; i < line->line_items.size(); ++i) {
FlexItem& flex_item = line->line_items[i];
- NGConstraintSpaceBuilder space_builder(ConstraintSpace());
+
+ WritingMode child_writing_mode =
+ flex_item.box->StyleRef().GetWritingMode();
+ NGConstraintSpaceBuilder builder(ConstraintSpace(), child_writing_mode,
+ /* is_new_fc */ true);
+ SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item.ng_input_node,
+ &builder);
+
NGLogicalSize available_size(flex_item.flexed_content_size +
flex_item.main_axis_border_and_padding,
flex_container_content_box_size.block_size);
- space_builder.SetAvailableSize(available_size);
- space_builder.SetPercentageResolutionSize(
- flex_container_content_box_size);
- space_builder.SetIsFixedSizeInline(true);
- NGConstraintSpace child_space = space_builder.ToConstraintSpace(
- flex_item.box->Style()->GetWritingMode());
+ builder.SetAvailableSize(available_size);
+ builder.SetPercentageResolutionSize(flex_container_content_box_size);
+ builder.SetIsFixedSizeInline(true);
+ NGConstraintSpace child_space = builder.ToConstraintSpace();
flex_item.layout_result =
ToNGBlockNode(flex_item.ng_input_node)
.Layout(child_space, nullptr /*break token*/);
@@ -139,21 +153,59 @@ scoped_refptr<NGLayoutResult> NGFlexLayoutAlgorithm::Layout() {
// in to the next iteration.
line->ComputeLineItemsPosition(main_axis_offset, cross_axis_offset);
- for (size_t i = 0; i < line->line_items.size(); ++i) {
- FlexItem& flex_item = line->line_items[i];
- container_builder_.AddChild(
- *flex_item.layout_result,
- {flex_item.desired_location.X(), flex_item.desired_location.Y()});
- }
// TODO(dgrogan): For column flex containers, keep track of tallest flex
// line and pass to ComputeBlockSizeForFragment as content_size.
}
LayoutUnit intrinsic_block_content_size = cross_axis_offset;
LayoutUnit intrinsic_block_size =
- intrinsic_block_content_size + borders_scrollbar_padding.BlockSum();
+ intrinsic_block_content_size +
+ flex_container_border_scrollbar_padding.BlockSum();
LayoutUnit block_size = ComputeBlockSizeForFragment(
ConstraintSpace(), Style(), intrinsic_block_size);
+
+ // Apply stretch alignment.
+ // TODO(dgrogan): Move this to its own method, which means making some of the
+ // container-specific local variables into data members.
+ // TODO(dgrogan): Change this to final_content_cross_size when column
+ // flexboxes are supported.
+ LayoutUnit final_content_block_size =
+ block_size - flex_container_border_scrollbar_padding.BlockSum();
+ if (!algorithm.IsMultiline() && !algorithm.FlexLines().IsEmpty())
+ algorithm.FlexLines()[0].cross_axis_extent = final_content_block_size;
+
+ for (FlexLine& line_context : algorithm.FlexLines()) {
+ for (wtf_size_t child_number = 0;
+ child_number < line_context.line_items.size(); ++child_number) {
+ FlexItem& flex_item = line_context.line_items[child_number];
+ if (flex_item.Alignment() == ItemPosition::kStretch) {
+ flex_item.ComputeStretchedSize();
+
+ WritingMode child_writing_mode =
+ flex_item.box->StyleRef().GetWritingMode();
+ NGConstraintSpaceBuilder builder(ConstraintSpace(), child_writing_mode,
+ /* is_new_fc */ true);
+ SetOrthogonalFallbackInlineSizeIfNeeded(
+ Style(), flex_item.ng_input_node, &builder);
+
+ NGLogicalSize available_size(flex_item.flexed_content_size +
+ flex_item.main_axis_border_and_padding,
+ flex_item.cross_axis_size);
+ builder.SetAvailableSize(available_size);
+ builder.SetPercentageResolutionSize(flex_container_content_box_size);
+ builder.SetIsFixedSizeInline(true);
+ builder.SetIsFixedSizeBlock(true);
+ NGConstraintSpace child_space = builder.ToConstraintSpace();
+ flex_item.layout_result =
+ ToNGBlockNode(flex_item.ng_input_node)
+ .Layout(child_space, /* break_token */ nullptr);
+ }
+ container_builder_.AddChild(
+ *flex_item.layout_result,
+ {flex_item.desired_location.X(), flex_item.desired_location.Y()});
+ }
+ }
+
container_builder_.SetBlockSize(block_size);
container_builder_.SetInlineSize(flex_container_border_box_inline_size);
container_builder_.SetBorders(ComputeBorders(ConstraintSpace(), Style()));
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h
index 8364187cc3d..bdea54d0137 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_flex_layout_algorithm.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
namespace blink {
@@ -18,7 +18,7 @@ class NGConstraintSpace;
class CORE_EXPORT NGFlexLayoutAlgorithm
: public NGLayoutAlgorithm<NGBlockNode,
- NGFragmentBuilder,
+ NGBoxFragmentBuilder,
NGBlockBreakToken> {
public:
NGFlexLayoutAlgorithm(NGBlockNode,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc
index 6e4315d6812..e9472e84174 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc
@@ -43,11 +43,12 @@ NGLayoutOpportunity FindLayoutOpportunityForFloat(
const NGExclusionSpace& exclusion_space,
const NGUnpositionedFloat& unpositioned_float,
const NGBoxStrut& fragment_margins,
+ const NGConstraintSpace& parent_space,
LayoutUnit inline_size) {
NGBfcOffset adjusted_origin_point =
AdjustToTopEdgeAlignmentRule(exclusion_space, origin_bfc_offset);
- LayoutUnit clearance_offset =
- exclusion_space.ClearanceOffset(unpositioned_float.ClearType());
+ LayoutUnit clearance_offset = exclusion_space.ClearanceOffset(
+ unpositioned_float.ClearType(parent_space.Direction()));
AdjustToClearance(clearance_offset, &adjusted_origin_point);
@@ -65,9 +66,13 @@ NGConstraintSpace CreateConstraintSpaceForFloat(
const NGLogicalSize& float_replaced_percentage_size,
const NGUnpositionedFloat& unpositioned_float,
const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
base::Optional<LayoutUnit> origin_block_offset = base::nullopt) {
const ComputedStyle& style = unpositioned_float.node.Style();
- NGConstraintSpaceBuilder builder(parent_space);
+ NGConstraintSpaceBuilder builder(parent_space, style.GetWritingMode(),
+ /* is_new_fc */ true);
+ SetOrthogonalFallbackInlineSizeIfNeeded(parent_style, unpositioned_float.node,
+ &builder);
if (origin_block_offset) {
DCHECK(parent_space.HasBlockFragmentation());
@@ -83,13 +88,12 @@ NGConstraintSpace CreateConstraintSpaceForFloat(
builder.SetFragmentationType(NGFragmentationType::kFragmentNone);
}
- return builder.SetPercentageResolutionSize(float_percentage_size)
- .SetAvailableSize(float_available_size)
+ return builder.SetAvailableSize(float_available_size)
+ .SetPercentageResolutionSize(float_percentage_size)
.SetReplacedPercentageResolutionSize(float_replaced_percentage_size)
- .SetIsNewFormattingContext(true)
- .SetIsShrinkToFit(true)
+ .SetIsShrinkToFit(style.LogicalWidth().IsAuto())
.SetTextDirection(style.Direction())
- .ToConstraintSpace(style.GetWritingMode());
+ .ToConstraintSpace();
}
std::unique_ptr<NGExclusionShapeData> CreateExclusionShapeData(
@@ -100,8 +104,9 @@ std::unique_ptr<NGExclusionShapeData> CreateExclusionShapeData(
const LayoutBox* layout_box,
const NGUnpositionedFloat& unpositioned_float,
const NGConstraintSpace& parent_space,
- TextDirection direction) {
+ const ComputedStyle& parent_style) {
DCHECK(layout_box->GetShapeOutsideInfo());
+ TextDirection direction = parent_space.Direction();
// We make the margins on the shape-data relative to line-left/line-right.
NGBoxStrut new_margins(margins.LineLeft(direction),
@@ -118,25 +123,16 @@ std::unique_ptr<NGExclusionShapeData> CreateExclusionShapeData(
case CSSBoxType::kBorder:
break;
case CSSBoxType::kPadding:
- shape_insets =
- ComputeBorders(CreateConstraintSpaceForFloat(
- float_available_size, float_percentage_size,
- float_replaced_percentage_size, unpositioned_float,
- parent_space),
- style)
- .ConvertToPhysical(style.GetWritingMode(), style.Direction())
- .ConvertToLogical(parent_space.GetWritingMode(),
- TextDirection::kLtr);
- break;
case CSSBoxType::kContent:
const NGConstraintSpace space = CreateConstraintSpaceForFloat(
float_available_size, float_percentage_size,
- float_replaced_percentage_size, unpositioned_float, parent_space);
- NGBoxStrut border_padding =
- ComputeBorders(space, style) + ComputePadding(space, style);
+ float_replaced_percentage_size, unpositioned_float, parent_space,
+ parent_style);
+ NGBoxStrut strut = ComputeBorders(space, style);
+ if (style.ShapeOutside()->CssBox() == CSSBoxType::kContent)
+ strut += ComputePadding(space, style);
shape_insets =
- border_padding
- .ConvertToPhysical(style.GetWritingMode(), style.Direction())
+ strut.ConvertToPhysical(style.GetWritingMode(), style.Direction())
.ConvertToLogical(parent_space.GetWritingMode(),
TextDirection::kLtr);
break;
@@ -158,7 +154,7 @@ scoped_refptr<NGExclusion> CreateExclusion(
const LayoutBox* layout_box,
const NGUnpositionedFloat& unpositioned_float,
const NGConstraintSpace& parent_space,
- TextDirection direction,
+ const ComputedStyle& parent_style,
EFloat type) {
NGBfcOffset start_offset = float_margin_bfc_offset;
NGBfcOffset end_offset(
@@ -172,7 +168,7 @@ scoped_refptr<NGExclusion> CreateExclusion(
? CreateExclusionShapeData(
float_available_size, float_percentage_size,
float_replaced_percentage_size, margins, layout_box,
- unpositioned_float, parent_space, direction)
+ unpositioned_float, parent_space, parent_style)
: nullptr;
return NGExclusion::Create(NGBfcRect(start_offset, end_offset), type,
@@ -186,13 +182,15 @@ void LayoutFloatWithoutFragmentation(
const NGLogicalSize& float_percentage_size,
const NGLogicalSize& float_replaced_percentage_size,
const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
NGUnpositionedFloat* unpositioned_float) {
if (unpositioned_float->layout_result)
return;
const NGConstraintSpace space = CreateConstraintSpaceForFloat(
float_available_size, float_percentage_size,
- float_replaced_percentage_size, *unpositioned_float, parent_space);
+ float_replaced_percentage_size, *unpositioned_float, parent_space,
+ parent_style);
unpositioned_float->layout_result = unpositioned_float->node.Layout(space);
unpositioned_float->margins =
@@ -203,6 +201,7 @@ void LayoutFloatWithoutFragmentation(
LayoutUnit ComputeMarginBoxInlineSizeForUnpositionedFloat(
const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
NGUnpositionedFloat* unpositioned_float) {
DCHECK(unpositioned_float);
@@ -211,12 +210,12 @@ LayoutUnit ComputeMarginBoxInlineSizeForUnpositionedFloat(
LayoutFloatWithoutFragmentation(
parent_space.AvailableSize(), parent_space.PercentageResolutionSize(),
parent_space.ReplacedPercentageResolutionSize(), parent_space,
- unpositioned_float);
+ parent_style, unpositioned_float);
DCHECK(unpositioned_float->layout_result);
- const auto& fragment = unpositioned_float->layout_result->PhysicalFragment();
+ const auto* fragment = unpositioned_float->layout_result->PhysicalFragment();
DCHECK(fragment);
- DCHECK(fragment->BreakToken()->IsFinished());
+ DCHECK(!fragment->BreakToken() || fragment->BreakToken()->IsFinished());
return (NGFragment(parent_space.GetWritingMode(), *fragment).InlineSize() +
unpositioned_float->margins.InlineSum())
@@ -228,9 +227,9 @@ NGPositionedFloat PositionFloat(
const NGLogicalSize& float_percentage_size,
const NGLogicalSize& float_replaced_percentage_size,
const NGBfcOffset& origin_bfc_offset,
- LayoutUnit parent_bfc_block_offset,
NGUnpositionedFloat* unpositioned_float,
const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
NGExclusionSpace* exclusion_space) {
DCHECK(unpositioned_float);
@@ -249,14 +248,15 @@ NGPositionedFloat PositionFloat(
if (!is_fragmentable) {
LayoutFloatWithoutFragmentation(float_available_size, float_percentage_size,
float_replaced_percentage_size,
- parent_space, unpositioned_float);
+ parent_space, parent_style,
+ unpositioned_float);
layout_result = unpositioned_float->layout_result;
fragment_margins = unpositioned_float->margins;
} else {
NGConstraintSpace space = CreateConstraintSpaceForFloat(
float_available_size, float_percentage_size,
float_replaced_percentage_size, *unpositioned_float, parent_space,
- origin_bfc_offset.block_offset);
+ parent_style, origin_bfc_offset.block_offset);
layout_result =
unpositioned_float->node.Layout(space, unpositioned_float->token.get());
fragment_margins = ComputeMarginsFor(
@@ -266,8 +266,11 @@ NGPositionedFloat PositionFloat(
if (ShouldIgnoreBlockStartMargin(parent_space, unpositioned_float->node,
unpositioned_float->token.get()))
fragment_margins.block_start = LayoutUnit();
- if (!layout_result->PhysicalFragment()->BreakToken()->IsFinished())
- fragment_margins.block_end = LayoutUnit();
+ if (const NGBreakToken* break_token =
+ layout_result->PhysicalFragment()->BreakToken()) {
+ if (!break_token->IsFinished())
+ fragment_margins.block_end = LayoutUnit();
+ }
}
DCHECK(layout_result->PhysicalFragment());
@@ -277,11 +280,12 @@ NGPositionedFloat PositionFloat(
// Find a layout opportunity that will fit our float.
NGLayoutOpportunity opportunity = FindLayoutOpportunityForFloat(
float_available_size, origin_bfc_offset, *exclusion_space,
- *unpositioned_float, fragment_margins, float_fragment.InlineSize());
+ *unpositioned_float, fragment_margins, parent_space,
+ float_fragment.InlineSize());
// Calculate the float's margin box BFC offset.
NGBfcOffset float_margin_bfc_offset = opportunity.rect.start_offset;
- if (unpositioned_float->IsRight()) {
+ if (unpositioned_float->IsLineRight(parent_space.Direction())) {
LayoutUnit float_margin_box_inline_size =
float_fragment.InlineSize() + fragment_margins.InlineSum();
float_margin_bfc_offset.line_offset +=
@@ -293,8 +297,10 @@ NGPositionedFloat PositionFloat(
float_available_size, float_percentage_size,
float_replaced_percentage_size, float_fragment, float_margin_bfc_offset,
fragment_margins, unpositioned_float->node.GetLayoutBox(),
- *unpositioned_float, parent_space, parent_space.Direction(),
- unpositioned_float->IsRight() ? EFloat::kRight : EFloat::kLeft);
+ *unpositioned_float, parent_space, parent_style,
+ unpositioned_float->IsLineRight(parent_space.Direction())
+ ? EFloat::kRight
+ : EFloat::kLeft);
exclusion_space->Add(std::move(exclusion));
// Adjust the float's bfc_offset to its border-box (instead of margin-box).
@@ -306,38 +312,39 @@ NGPositionedFloat PositionFloat(
return NGPositionedFloat(std::move(layout_result), float_bfc_offset);
}
-const NGPositionedFloatVector PositionFloats(
- const NGLogicalSize& float_available_size,
- const NGLogicalSize& float_percentage_size,
- const NGLogicalSize& float_replaced_percentage_size,
- const NGBfcOffset& origin_bfc_offset,
- LayoutUnit parent_bfc_block_offset,
- NGUnpositionedFloatVector& unpositioned_floats,
- const NGConstraintSpace& space,
- NGExclusionSpace* exclusion_space) {
- NGPositionedFloatVector positioned_floats;
- positioned_floats.ReserveCapacity(unpositioned_floats.size());
+void PositionFloats(const NGLogicalSize& float_available_size,
+ const NGLogicalSize& float_percentage_size,
+ const NGLogicalSize& float_replaced_percentage_size,
+ const NGBfcOffset& origin_bfc_offset,
+ NGUnpositionedFloatVector& unpositioned_floats,
+ const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
+ NGExclusionSpace* exclusion_space,
+ NGPositionedFloatVector* positioned_floats) {
+ positioned_floats->ReserveCapacity(positioned_floats->size() +
+ unpositioned_floats.size());
for (NGUnpositionedFloat& unpositioned_float : unpositioned_floats) {
- positioned_floats.push_back(PositionFloat(
+ positioned_floats->push_back(PositionFloat(
float_available_size, float_percentage_size,
- float_replaced_percentage_size, origin_bfc_offset,
- parent_bfc_block_offset, &unpositioned_float, space, exclusion_space));
+ float_replaced_percentage_size, origin_bfc_offset, &unpositioned_float,
+ parent_space, parent_style, exclusion_space));
}
-
- return positioned_floats;
}
void AddUnpositionedFloat(NGUnpositionedFloatVector* unpositioned_floats,
NGContainerFragmentBuilder* fragment_builder,
- NGUnpositionedFloat unpositioned_float) {
+ NGUnpositionedFloat unpositioned_float,
+ const NGConstraintSpace& parent_space) {
// The same float node should not be added more than once.
DCHECK(
!RemoveUnpositionedFloat(unpositioned_floats, unpositioned_float.node));
if (fragment_builder && !fragment_builder->BfcBlockOffset()) {
fragment_builder->AddAdjoiningFloatTypes(
- unpositioned_float.IsLeft() ? kFloatTypeLeft : kFloatTypeRight);
+ unpositioned_float.IsLineLeft(parent_space.Direction())
+ ? kFloatTypeLeft
+ : kFloatTypeRight);
}
unpositioned_floats->push_back(std::move(unpositioned_float));
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h
index dd1c0170e4f..7ccfa6cb82a 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h
@@ -9,11 +9,12 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float_vector.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
+class ComputedStyle;
class NGBlockNode;
class NGConstraintSpace;
class NGContainerFragmentBuilder;
@@ -35,8 +36,9 @@ typedef int NGFloatTypes;
// Returns the inline size (relative to {@code parent_space}) of the
// unpositioned float.
-CORE_EXPORT LayoutUnit ComputeMarginBoxInlineSizeForUnpositionedFloat(
+LayoutUnit ComputeMarginBoxInlineSizeForUnpositionedFloat(
const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
NGUnpositionedFloat* unpositioned_float);
// Positions {@code unpositioned_float} into {@code new_parent_space}.
@@ -46,28 +48,30 @@ PositionFloat(const NGLogicalSize& float_available_size,
const NGLogicalSize& float_percentage_size,
const NGLogicalSize& float_replaced_percentage_size,
const NGBfcOffset& origin_bfc_offset,
- LayoutUnit parent_bfc_block_offset,
NGUnpositionedFloat*,
const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
NGExclusionSpace* exclusion_space);
// Positions the list of {@code unpositioned_floats}. Adds them as exclusions to
// {@code space}.
-CORE_EXPORT const NGPositionedFloatVector
-PositionFloats(const NGLogicalSize& float_available_size,
- const NGLogicalSize& float_percentage_size,
- const NGLogicalSize& float_replaced_percentage_size,
- const NGBfcOffset& origin_bfc_offset,
- LayoutUnit container_block_offset,
- NGUnpositionedFloatVector& unpositioned_floats,
- const NGConstraintSpace& space,
- NGExclusionSpace* exclusion_space);
+CORE_EXPORT void PositionFloats(
+ const NGLogicalSize& float_available_size,
+ const NGLogicalSize& float_percentage_size,
+ const NGLogicalSize& float_replaced_percentage_size,
+ const NGBfcOffset& origin_bfc_offset,
+ NGUnpositionedFloatVector& unpositioned_floats,
+ const NGConstraintSpace& parent_space,
+ const ComputedStyle& parent_style,
+ NGExclusionSpace* exclusion_space,
+ NGPositionedFloatVector* positioned_floats);
// Add a pending float to the list. It will be committed (positioned) once we
// have resolved the BFC block offset.
void AddUnpositionedFloat(NGUnpositionedFloatVector* unpositioned_floats,
NGContainerFragmentBuilder* fragment_builder,
- NGUnpositionedFloat unpositioned_float);
+ NGUnpositionedFloat unpositioned_float,
+ const NGConstraintSpace& parent_space);
// Remove a pending float from the list.
bool RemoveUnpositionedFloat(NGUnpositionedFloatVector* unpositioned_floats,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment.h
index 4c21a682214..e02d39a23e7 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_border_edges.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc
deleted file mode 100644
index f6a909a5386..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc
+++ /dev/null
@@ -1,384 +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 "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
-
-#include "third_party/blink/renderer/core/layout/layout_object.h"
-#include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
-
-namespace blink {
-
-namespace {
-
-NGPhysicalFragment::NGBoxType BoxTypeFromLayoutObject(
- const LayoutObject* layout_object) {
- DCHECK(layout_object);
- if (layout_object->IsFloating())
- return NGPhysicalFragment::NGBoxType::kFloating;
- if (layout_object->IsOutOfFlowPositioned())
- return NGPhysicalFragment::NGBoxType::kOutOfFlowPositioned;
- if (layout_object->IsAtomicInlineLevel())
- return NGPhysicalFragment::NGBoxType::kAtomicInline;
- if (layout_object->IsInline())
- return NGPhysicalFragment::NGBoxType::kInlineBox;
- if (layout_object->IsLayoutBlock() &&
- ToLayoutBlock(layout_object)->CreatesNewFormattingContext())
- return NGPhysicalFragment::NGBoxType::kBlockFlowRoot;
- return NGPhysicalFragment::NGBoxType::kNormalBox;
-}
-
-} // namespace
-
-NGFragmentBuilder::NGFragmentBuilder(NGLayoutInputNode node,
- scoped_refptr<const ComputedStyle> style,
- WritingMode writing_mode,
- TextDirection direction)
- : NGContainerFragmentBuilder(std::move(style), writing_mode, direction),
- node_(node),
- layout_object_(node.GetLayoutBox()),
- box_type_(NGPhysicalFragment::NGBoxType::kNormalBox),
- is_old_layout_root_(false),
- did_break_(false) {}
-
-NGFragmentBuilder::NGFragmentBuilder(LayoutObject* layout_object,
- scoped_refptr<const ComputedStyle> style,
- WritingMode writing_mode,
- TextDirection direction)
- : NGContainerFragmentBuilder(std::move(style), writing_mode, direction),
- node_(nullptr),
- layout_object_(layout_object),
- box_type_(NGPhysicalFragment::NGBoxType::kNormalBox),
- is_old_layout_root_(false),
- did_break_(false) {}
-
-NGFragmentBuilder::~NGFragmentBuilder() = default;
-
-NGContainerFragmentBuilder& NGFragmentBuilder::AddChild(
- scoped_refptr<const NGPhysicalFragment> child,
- const NGLogicalOffset& child_offset) {
- switch (child->Type()) {
- case NGPhysicalBoxFragment::kFragmentBox:
- case NGPhysicalBoxFragment::kFragmentRenderedLegend:
- if (child->BreakToken())
- child_break_tokens_.push_back(child->BreakToken());
- break;
- case NGPhysicalBoxFragment::kFragmentLineBox:
- // NGInlineNode produces multiple line boxes in an anonymous box. We won't
- // know up front which line box to insert a fragment break before (due to
- // widows), so keep them all until we know.
- DCHECK(child->BreakToken());
- DCHECK(child->BreakToken()->InputNode() == node_);
- inline_break_tokens_.push_back(child->BreakToken());
- break;
- case NGPhysicalBoxFragment::kFragmentText:
- DCHECK(!child->BreakToken());
- break;
- default:
- NOTREACHED();
- break;
- }
-
- return NGContainerFragmentBuilder::AddChild(std::move(child), child_offset);
-}
-
-void NGFragmentBuilder::RemoveChildren() {
- child_break_tokens_.clear();
- inline_break_tokens_.clear();
- children_.clear();
- offsets_.clear();
-}
-
-NGFragmentBuilder& NGFragmentBuilder::AddBreakBeforeChild(
- NGLayoutInputNode child) {
- if (child.IsInline()) {
- if (inline_break_tokens_.IsEmpty()) {
- // In some cases we may want to break before the first line, as a last
- // resort. We need a break token for that as well, so that the machinery
- // will understand that we should resume at the beginning of the inline
- // formatting context, rather than concluding that we're done with the
- // whole thing.
- inline_break_tokens_.push_back(NGInlineBreakToken::Create(
- ToNGInlineNode(child), nullptr, 0, 0, NGInlineBreakToken::kDefault));
- }
- return *this;
- }
- auto token = NGBlockBreakToken::CreateBreakBefore(child);
- child_break_tokens_.push_back(token);
- return *this;
-}
-
-NGFragmentBuilder& NGFragmentBuilder::AddBreakBeforeLine(int line_number) {
- DCHECK_GT(line_number, 0);
- DCHECK_LE(unsigned(line_number), inline_break_tokens_.size());
- int lines_to_remove = inline_break_tokens_.size() - line_number;
- if (lines_to_remove > 0) {
- // Remove widows that should be pushed to the next fragment. We'll also
- // remove all other child fragments than line boxes (typically floats) that
- // come after the first line that's moved, as those also have to be re-laid
- // out in the next fragment.
- inline_break_tokens_.resize(line_number);
- DCHECK_GT(children_.size(), 0UL);
- for (int i = children_.size() - 1; i >= 0; i--) {
- DCHECK_NE(i, 0);
- if (!children_[i]->IsLineBox())
- continue;
- if (!--lines_to_remove) {
- // This is the first line that is going to the next fragment. Remove it,
- // and everything after it.
- children_.resize(i);
- offsets_.resize(i);
- break;
- }
- }
- }
-
- // We need to resume at the right inline location in the next fragment, but
- // broken floats, which are resumed and positioned by the parent block layout
- // algorithm, need to be ignored by the inline layout algorithm.
- ToNGInlineBreakToken(inline_break_tokens_.back().get())->SetIgnoreFloats();
- return *this;
-}
-
-NGFragmentBuilder& NGFragmentBuilder::PropagateBreak(
- scoped_refptr<NGLayoutResult> child_layout_result) {
- if (!did_break_)
- PropagateBreak(child_layout_result->PhysicalFragment());
- if (child_layout_result->HasForcedBreak())
- SetHasForcedBreak();
- else
- PropagateSpaceShortage(child_layout_result->MinimalSpaceShortage());
- return *this;
-}
-
-NGFragmentBuilder& NGFragmentBuilder::PropagateBreak(
- scoped_refptr<const NGPhysicalFragment> child_fragment) {
- if (!did_break_) {
- const auto* token = child_fragment->BreakToken();
- did_break_ = token && !token->IsFinished();
- }
- return *this;
-}
-
-void NGFragmentBuilder::AddOutOfFlowLegacyCandidate(
- NGBlockNode node,
- const NGStaticPosition& static_position,
- LayoutObject* inline_container) {
- DCHECK_GE(InlineSize(), LayoutUnit());
- DCHECK_GE(BlockSize(), LayoutUnit());
-
- NGOutOfFlowPositionedDescendant descendant{node, static_position,
- inline_container};
- // Need 0,0 physical coordinates as child offset. Because offset
- // is stored as logical, must convert physical 0,0 to logical.
- NGLogicalOffset zero_offset;
- switch (GetWritingMode()) {
- case WritingMode::kHorizontalTb:
- if (IsLtr(Direction()))
- zero_offset = NGLogicalOffset();
- else
- zero_offset = NGLogicalOffset(InlineSize(), LayoutUnit());
- break;
- case WritingMode::kVerticalRl:
- case WritingMode::kSidewaysRl:
- if (IsLtr(Direction()))
- zero_offset = NGLogicalOffset(LayoutUnit(), BlockSize());
- else
- zero_offset = NGLogicalOffset(InlineSize(), BlockSize());
- break;
- case WritingMode::kVerticalLr:
- case WritingMode::kSidewaysLr:
- if (IsLtr(Direction()))
- zero_offset = NGLogicalOffset();
- else
- zero_offset = NGLogicalOffset(InlineSize(), LayoutUnit());
- break;
- }
- oof_positioned_candidates_.push_back(
- NGOutOfFlowPositionedCandidate{descendant, zero_offset});
-}
-
-NGPhysicalFragment::NGBoxType NGFragmentBuilder::BoxType() const {
- if (box_type_ != NGPhysicalFragment::NGBoxType::kNormalBox)
- return box_type_;
-
- // When implicit, compute from LayoutObject.
- return BoxTypeFromLayoutObject(layout_object_);
-}
-
-void NGFragmentBuilder::AddBaseline(NGBaselineRequest request,
- LayoutUnit offset) {
-#if DCHECK_IS_ON()
- for (const auto& baseline : baselines_)
- DCHECK(baseline.request != request);
-#endif
- baselines_.push_back(NGBaseline{request, offset});
-}
-
-EBreakBetween NGFragmentBuilder::JoinedBreakBetweenValue(
- EBreakBetween break_before) const {
- return JoinFragmentainerBreakValues(previous_break_after_, break_before);
-}
-
-scoped_refptr<NGLayoutResult> NGFragmentBuilder::ToBoxFragment(
- WritingMode block_or_line_writing_mode) {
- DCHECK_EQ(offsets_.size(), children_.size());
-
- NGPhysicalSize physical_size = Size().ConvertToPhysical(GetWritingMode());
-
- DCHECK_EQ(children_.size(), offsets_.size());
- for (size_t i = 0; i < children_.size(); i++) {
- auto& child = children_[i];
- child.offset_ = offsets_[i].ConvertToPhysical(
- block_or_line_writing_mode, Direction(), physical_size, child->Size());
- }
-
- scoped_refptr<NGBreakToken> break_token;
- bool is_rendered_legend = false;
- if (node_) {
- is_rendered_legend = node_.IsRenderedLegend();
- if (!inline_break_tokens_.IsEmpty()) {
- if (auto token = inline_break_tokens_.back()) {
- if (!token->IsFinished())
- child_break_tokens_.push_back(std::move(token));
- }
- }
- if (did_break_) {
- break_token = NGBlockBreakToken::Create(
- node_, used_block_size_, child_break_tokens_, has_last_resort_break_);
- } else {
- break_token = NGBlockBreakToken::Create(node_, used_block_size_,
- has_last_resort_break_);
- }
- }
-
- // Because this vector will be long-lived, make sure to not waste space.
- // (We reserve an initial capacity when adding the first child)
- if (children_.size())
- children_.ShrinkToReasonableCapacity();
- scoped_refptr<const NGPhysicalBoxFragment> fragment =
- base::AdoptRef(new NGPhysicalBoxFragment(
- layout_object_, Style(), style_variant_, physical_size, children_,
- borders_.ConvertToPhysical(GetWritingMode(), Direction()),
- padding_.ConvertToPhysical(GetWritingMode(), Direction()), baselines_,
- BoxType(), is_fieldset_container_, is_rendered_legend,
- is_old_layout_root_, border_edges_.ToPhysical(GetWritingMode()),
- std::move(break_token)));
-
- Vector<NGPositionedFloat> positioned_floats;
-
- return base::AdoptRef(new NGLayoutResult(
- std::move(fragment), std::move(oof_positioned_descendants_),
- std::move(positioned_floats), unpositioned_list_marker_,
- std::move(exclusion_space_), bfc_line_offset_, bfc_block_offset_,
- end_margin_strut_, intrinsic_block_size_, minimal_space_shortage_,
- initial_break_before_, previous_break_after_, has_forced_break_,
- is_pushed_by_floats_, adjoining_floats_, NGLayoutResult::kSuccess));
-}
-
-scoped_refptr<NGLayoutResult> NGFragmentBuilder::Abort(
- NGLayoutResult::NGLayoutResultStatus status) {
- Vector<NGOutOfFlowPositionedDescendant> oof_positioned_descendants;
- Vector<NGPositionedFloat> positioned_floats;
- return base::AdoptRef(new NGLayoutResult(
- nullptr, std::move(oof_positioned_descendants),
- std::move(positioned_floats), NGUnpositionedListMarker(),
- NGExclusionSpace(), bfc_line_offset_, bfc_block_offset_,
- end_margin_strut_, LayoutUnit(), LayoutUnit(), EBreakBetween::kAuto,
- EBreakBetween::kAuto, false, false, kFloatTypeNone, status));
-}
-
-// Finds FragmentPairs that define inline containing blocks.
-// inline_container_fragments is a map whose keys specify which
-// inline containing blocks are required.
-// Not finding a required block is an unexpected behavior (DCHECK).
-void NGFragmentBuilder::ComputeInlineContainerFragments(
- HashMap<const LayoutObject*, FragmentPair>* inline_container_fragments,
- NGLogicalSize* container_size) {
- // This function has detailed knowledge of inline fragment tree structure,
- // and will break if this changes.
- DCHECK_GE(InlineSize(), LayoutUnit());
- DCHECK_GE(BlockSize(), LayoutUnit());
- *container_size = Size();
-
- for (size_t i = 0; i < children_.size(); i++) {
- if (children_[i]->IsLineBox()) {
- const NGPhysicalLineBoxFragment* linebox =
- ToNGPhysicalLineBoxFragment(children_[i].get());
- for (auto& descendant :
- NGInlineFragmentTraversal::DescendantsOf(*linebox)) {
- LayoutObject* key = {};
- if (descendant.fragment->IsText()) {
- key = descendant.fragment->GetLayoutObject();
- DCHECK(key);
- key = key->Parent();
- DCHECK(key);
- } else if (descendant.fragment->IsBox()) {
- key = descendant.fragment->GetLayoutObject();
- }
- if (key && inline_container_fragments->Contains(key)) {
- NGFragmentBuilder::FragmentPair value =
- inline_container_fragments->at(key);
- if (!value.start_fragment) {
- value.start_fragment = descendant.fragment.get();
- value.start_fragment_union_rect.offset =
- descendant.offset_to_container_box;
- value.start_fragment_union_rect =
- NGPhysicalOffsetRect(descendant.offset_to_container_box,
- value.start_fragment->Size());
- value.start_linebox_fragment = linebox;
- value.start_linebox_offset = offsets_.at(i);
- }
- if (!value.end_fragment || value.end_linebox_fragment != linebox) {
- value.end_fragment = descendant.fragment.get();
- value.end_fragment_union_rect = NGPhysicalOffsetRect(
- descendant.offset_to_container_box, value.end_fragment->Size());
- value.end_linebox_fragment = linebox;
- value.end_linebox_offset = offsets_.at(i);
- }
- // Extend the union size
- if (value.start_linebox_fragment == linebox) {
- // std::max because initial box might have larger extent than its
- // descendants.
- value.start_fragment_union_rect.size.width =
- std::max(descendant.offset_to_container_box.left +
- descendant.fragment->Size().width -
- value.start_fragment_union_rect.offset.left,
- value.start_fragment_union_rect.size.width);
- value.start_fragment_union_rect.size.height =
- std::max(descendant.offset_to_container_box.top +
- descendant.fragment->Size().height -
- value.start_fragment_union_rect.offset.top,
- value.start_fragment_union_rect.size.height);
- }
- if (value.end_linebox_fragment == linebox) {
- value.end_fragment_union_rect.size.width =
- std::max(descendant.offset_to_container_box.left +
- descendant.fragment->Size().width -
- value.start_fragment_union_rect.offset.left,
- value.end_fragment_union_rect.size.width);
- value.end_fragment_union_rect.size.height =
- std::max(descendant.offset_to_container_box.top +
- descendant.fragment->Size().height -
- value.start_fragment_union_rect.offset.top,
- value.end_fragment_union_rect.size.height);
- }
- inline_container_fragments->Set(key, value);
- }
- }
- }
- }
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h
index cf662d0d1a8..f5da6f6bb79 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h
@@ -1,255 +1,84 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
+// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef NGFragmentBuilder_h
-#define NGFragmentBuilder_h
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENT_BUILDER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENT_BUILDER_H_
-#include "third_party/blink/renderer/core/layout/ng/geometry/ng_border_edges.h"
-#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
-#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset_rect.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h"
+#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
-#include "third_party/blink/renderer/core/style/computed_style_constants.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_style_variant.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/text/text_direction.h"
+#include "third_party/blink/renderer/platform/text/writing_mode.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
-class NGPhysicalFragment;
-class NGPhysicalLineBoxFragment;
+class LayoutObject;
-class CORE_EXPORT NGFragmentBuilder final : public NGContainerFragmentBuilder {
- DISALLOW_NEW();
+class CORE_EXPORT NGFragmentBuilder {
+ STACK_ALLOCATED();
public:
- NGFragmentBuilder(NGLayoutInputNode,
- scoped_refptr<const ComputedStyle>,
- WritingMode,
- TextDirection);
-
- // Build a fragment for LayoutObject without NGLayoutInputNode. LayoutInline
- // has NGInlineItem but does not have corresponding NGLayoutInputNode.
- NGFragmentBuilder(LayoutObject*,
- scoped_refptr<const ComputedStyle>,
- WritingMode,
- TextDirection);
-
- ~NGFragmentBuilder() override;
-
- NGFragmentBuilder& SetIntrinsicBlockSize(LayoutUnit intrinsic_block_size) {
- intrinsic_block_size_ = intrinsic_block_size;
- return *this;
+ const ComputedStyle& Style() const {
+ DCHECK(style_);
+ return *style_;
}
- NGFragmentBuilder& SetBorders(const NGBoxStrut& border) {
- DCHECK_NE(BoxType(), NGPhysicalFragment::kInlineBox);
- borders_ = border;
+ NGFragmentBuilder& SetStyleVariant(NGStyleVariant style_variant) {
+ style_variant_ = style_variant;
return *this;
}
- NGFragmentBuilder& SetPadding(const NGBoxStrut& padding) {
- DCHECK_NE(BoxType(), NGPhysicalFragment::kInlineBox);
- padding_ = padding;
+ NGFragmentBuilder& SetStyle(scoped_refptr<const ComputedStyle> style,
+ NGStyleVariant style_variant) {
+ DCHECK(style);
+ style_ = std::move(style);
+ style_variant_ = style_variant;
return *this;
}
- NGFragmentBuilder& SetPadding(const NGLineBoxStrut& padding) {
- DCHECK_EQ(BoxType(), NGPhysicalFragment::kInlineBox);
- // Convert to flow-relative, because ToInlineBoxFragment() will convert
- // the padding to physical coordinates using flow-relative writing-mode.
- padding_ = NGBoxStrut(padding, IsFlippedLinesWritingMode(GetWritingMode()));
- return *this;
- }
-
- using NGContainerFragmentBuilder::AddChild;
-
- // Our version of AddChild captures any child NGBreakTokens.
- NGContainerFragmentBuilder& AddChild(scoped_refptr<const NGPhysicalFragment>,
- const NGLogicalOffset&) final;
- // Remove all children.
- void RemoveChildren();
-
- // Add a break token for a child that doesn't yet have any fragments, because
- // its first fragment is to be produced in the next fragmentainer. This will
- // add a break token for the child, but no fragment.
- NGFragmentBuilder& AddBreakBeforeChild(NGLayoutInputNode child);
-
- // Prepare for a break token before the specified line.
- NGFragmentBuilder& AddBreakBeforeLine(int line_number);
-
- // Update if we have fragmented in this flow.
- NGFragmentBuilder& PropagateBreak(scoped_refptr<NGLayoutResult>);
- NGFragmentBuilder& PropagateBreak(scoped_refptr<const NGPhysicalFragment>);
-
- void AddOutOfFlowLegacyCandidate(NGBlockNode,
- const NGStaticPosition&,
- LayoutObject* inline_container);
-
- // Set how much of the block size we've used so far for this box.
- NGFragmentBuilder& SetUsedBlockSize(LayoutUnit used_block_size) {
- used_block_size_ = used_block_size;
- return *this;
- }
+ WritingMode GetWritingMode() const { return writing_mode_; }
+ TextDirection Direction() const { return direction_; }
- // Specify that we broke.
- //
- // This will result in a fragment which has an unfinished break token.
- NGFragmentBuilder& SetDidBreak() {
- did_break_ = true;
+ LayoutUnit InlineSize() const { return size_.inline_size; }
+ LayoutUnit BlockSize() const { return size_.block_size; }
+ const NGLogicalSize& Size() const { return size_; }
+ NGFragmentBuilder& SetInlineSize(LayoutUnit inline_size) {
+ DCHECK_GE(inline_size, LayoutUnit());
+ size_.inline_size = inline_size;
return *this;
}
-
- NGFragmentBuilder& SetHasForcedBreak() {
- has_forced_break_ = true;
- minimal_space_shortage_ = LayoutUnit();
- return *this;
- }
-
- // Report space shortage, i.e. how much more space would have been sufficient
- // to prevent some piece of content from breaking. This information may be
- // used by the column balancer to stretch columns.
- NGFragmentBuilder& PropagateSpaceShortage(LayoutUnit space_shortage) {
- DCHECK_GT(space_shortage, LayoutUnit());
- if (minimal_space_shortage_ > space_shortage)
- minimal_space_shortage_ = space_shortage;
- return *this;
- }
-
- void SetInitialBreakBefore(EBreakBetween break_before) {
- initial_break_before_ = break_before;
- }
-
- void SetPreviousBreakAfter(EBreakBetween break_after) {
- previous_break_after_ = break_after;
- }
-
- // Join/"collapse" the previous (stored) break-after value with the next
- // break-before value, to determine how to deal with breaking between two
- // in-flow siblings.
- EBreakBetween JoinedBreakBetweenValue(EBreakBetween break_before) const;
-
- // Return the number of line boxes laid out.
- int LineCount() const { return inline_break_tokens_.size(); }
-
- // Call when we're setting an undersirable break. It may be possible to avoid
- // the break if we instead break at an earlier element.
- void SetHasLastResortBreak() { has_last_resort_break_ = true; }
-
- // Offsets are not supposed to be set during fragment construction, so we
- // do not provide a setter here.
-
- // Creates the fragment. Can only be called once.
- scoped_refptr<NGLayoutResult> ToBoxFragment() {
- DCHECK_NE(BoxType(), NGPhysicalFragment::kInlineBox);
- return ToBoxFragment(GetWritingMode());
- }
- scoped_refptr<NGLayoutResult> ToInlineBoxFragment() {
- // The logical coordinate for inline box uses line-relative writing-mode,
- // not
- // flow-relative.
- DCHECK_EQ(BoxType(), NGPhysicalFragment::kInlineBox);
- return ToBoxFragment(ToLineWritingMode(GetWritingMode()));
- }
-
- scoped_refptr<NGLayoutResult> Abort(NGLayoutResult::NGLayoutResultStatus);
-
- // A vector of child offsets. Initially set by AddChild().
- const OffsetVector& Offsets() const { return offsets_; }
- OffsetVector& MutableOffsets() { return offsets_; }
-
- NGPhysicalFragment::NGBoxType BoxType() const;
- NGFragmentBuilder& SetBoxType(NGPhysicalFragment::NGBoxType box_type) {
- box_type_ = box_type;
- return *this;
- }
- NGFragmentBuilder& SetIsFieldsetContainer() {
- is_fieldset_container_ = true;
- return *this;
- }
- NGFragmentBuilder& SetIsOldLayoutRoot() {
- is_old_layout_root_ = true;
- return *this;
- }
-
- bool DidBreak() const { return did_break_; }
-
- NGFragmentBuilder& SetBorderEdges(NGBorderEdges border_edges) {
- border_edges_ = border_edges;
- return *this;
- }
-
- // Layout algorithms should call this function for each baseline request in
- // the constraint space.
- //
- // If a request should use a synthesized baseline from the box rectangle,
- // algorithms can omit the call.
- //
- // This function should be called at most once for a given algorithm/baseline
- // type pair.
- void AddBaseline(NGBaselineRequest, LayoutUnit);
-
- // Inline containing block geometry is defined by two fragments:
- // start and end. FragmentPair holds the information needed to compute
- // inline containing block geometry wrt enclosing container block.
- struct FragmentPair {
- DISALLOW_NEW();
- // Linebox that contains start_fragment.
- const NGPhysicalLineBoxFragment* start_linebox_fragment;
- // Offset of start_linebox from containing block.
- NGLogicalOffset start_linebox_offset;
- // Start fragment of inline containing block.
- const NGPhysicalFragment* start_fragment;
- // Start fragment rect combined with rectangles of all fragments
- // generated by same Element as start_fragment.
- NGPhysicalOffsetRect start_fragment_union_rect;
- // end_** variables are end fragment counterparts to start fragment.
- const NGPhysicalLineBoxFragment* end_linebox_fragment;
- NGLogicalOffset end_linebox_offset;
- const NGPhysicalFragment* end_fragment;
- NGPhysicalOffsetRect end_fragment_union_rect;
- };
-
- void ComputeInlineContainerFragments(
- HashMap<const LayoutObject*, FragmentPair>* inline_container_fragments,
- NGLogicalSize* container_size);
+ void SetBlockSize(LayoutUnit block_size) { size_.block_size = block_size; }
LayoutObject* GetLayoutObject() { return layout_object_; }
- private:
- scoped_refptr<NGLayoutResult> ToBoxFragment(WritingMode);
-
- NGLayoutInputNode node_;
- LayoutObject* layout_object_;
-
- LayoutUnit intrinsic_block_size_;
- NGBoxStrut borders_;
- NGBoxStrut padding_;
-
- NGPhysicalFragment::NGBoxType box_type_;
- bool is_fieldset_container_ = false;
- bool is_old_layout_root_;
- bool did_break_;
- bool has_forced_break_ = false;
- LayoutUnit used_block_size_;
-
- LayoutUnit minimal_space_shortage_ = LayoutUnit::Max();
-
- // The break-before value on the initial child we cannot honor. There's no
- // valid class A break point before a first child, only *between* siblings.
- EBreakBetween initial_break_before_ = EBreakBetween::kAuto;
-
- // The break-after value of the previous in-flow sibling.
- EBreakBetween previous_break_after_ = EBreakBetween::kAuto;
-
- Vector<scoped_refptr<NGBreakToken>> child_break_tokens_;
- Vector<scoped_refptr<NGBreakToken>> inline_break_tokens_;
-
- Vector<NGBaseline> baselines_;
-
- NGBorderEdges border_edges_;
+ protected:
+ NGFragmentBuilder(scoped_refptr<const ComputedStyle> style,
+ WritingMode writing_mode,
+ TextDirection direction)
+ : style_(std::move(style)),
+ writing_mode_(writing_mode),
+ direction_(direction),
+ style_variant_(NGStyleVariant::kStandard) {
+ DCHECK(style_);
+ }
+ NGFragmentBuilder(WritingMode writing_mode, TextDirection direction)
+ : writing_mode_(writing_mode), direction_(direction) {}
+
+ protected:
+ scoped_refptr<const ComputedStyle> style_;
+ WritingMode writing_mode_;
+ TextDirection direction_;
+ NGStyleVariant style_variant_;
+ NGLogicalSize size_;
+ LayoutObject* layout_object_ = nullptr;
+ scoped_refptr<NGBreakToken> break_token_;
+
+ friend class NGPhysicalFragment;
};
} // namespace blink
-#endif // NGFragmentBuilder
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENT_BUILDER_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc
index f6b09988a80..05552e066e1 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc
@@ -26,24 +26,6 @@ LayoutUnit PreviouslyUsedBlockSpace(const NGConstraintSpace& constraint_space,
return break_token->UsedBlockSize() - logical_fragment.BlockSize();
}
-// Return true if the specified fragment is the first generated fragment of
-// some node.
-bool IsFirstFragment(const NGConstraintSpace& constraint_space,
- const NGPhysicalFragment& fragment) {
- // TODO(mstensho): Figure out how to behave for non-box fragments here. How
- // can we tell whether it's the first one? Looking for previously used block
- // space certainly isn't the answer.
- if (!fragment.IsBox())
- return true;
- return PreviouslyUsedBlockSpace(constraint_space, fragment) <= LayoutUnit();
-}
-
-// Return true if the specified fragment is the final fragment of some node.
-bool IsLastFragment(const NGPhysicalFragment& fragment) {
- const auto* break_token = fragment.BreakToken();
- return !break_token || break_token->IsFinished();
-}
-
// At a class A break point [1], the break value with the highest precedence
// wins. If the two values have the same precedence (e.g. "left" and "right"),
// the value specified on a latter object wins.
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
index db556bf3ef3..6231e4e5572 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
@@ -5,14 +5,15 @@
#ifndef NGFragmentationUtils_h
#define NGFragmentationUtils_h
+#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
class NGConstraintSpace;
-class NGPhysicalFragment;
// Return the total amount of block space spent on a node by fragments
// preceding this one (but not including this one).
@@ -21,10 +22,21 @@ LayoutUnit PreviouslyUsedBlockSpace(const NGConstraintSpace&,
// Return true if the specified fragment is the first generated fragment of
// some node.
-bool IsFirstFragment(const NGConstraintSpace&, const NGPhysicalFragment&);
+inline bool IsFirstFragment(const NGConstraintSpace& constraint_space,
+ const NGPhysicalFragment& fragment) {
+ // TODO(mstensho): Figure out how to behave for non-box fragments here. How
+ // can we tell whether it's the first one? Looking for previously used block
+ // space certainly isn't the answer.
+ if (!fragment.IsBox())
+ return true;
+ return PreviouslyUsedBlockSpace(constraint_space, fragment) <= LayoutUnit();
+}
// Return true if the specified fragment is the final fragment of some node.
-bool IsLastFragment(const NGPhysicalFragment&);
+inline bool IsLastFragment(const NGPhysicalFragment& fragment) {
+ const auto* break_token = fragment.BreakToken();
+ return !break_token || break_token->IsFinished();
+}
// Join two adjacent break values specified on break-before and/or break-
// after. avoid* values win over auto values, and forced break values win over
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc
index 5533923b272..708fab7572f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc
@@ -23,11 +23,12 @@ class NGInlineLayoutTest : public SimTest {
NGConstraintSpace ConstraintSpaceForElement(LayoutBlockFlow* block_flow) {
return NGConstraintSpaceBuilder(
block_flow->Style()->GetWritingMode(),
- /* icb_size */ {NGSizeIndefinite, NGSizeIndefinite})
+ block_flow->Style()->GetWritingMode(),
+ /* is_new_fc */ false)
.SetAvailableSize(NGLogicalSize(LayoutUnit(), LayoutUnit()))
.SetPercentageResolutionSize(NGLogicalSize(LayoutUnit(), LayoutUnit()))
.SetTextDirection(block_flow->Style()->Direction())
- .ToConstraintSpace(block_flow->Style()->GetWritingMode());
+ .ToConstraintSpace();
}
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h
index 092665f7c97..398293d8127 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h
@@ -19,7 +19,7 @@ struct MinMaxSizeInput;
// Base class for all LayoutNG algorithms.
template <typename NGInputNodeType,
- typename NGFragmentBuilderType,
+ typename NGBoxFragmentBuilderType,
typename NGBreakTokenType>
class CORE_EXPORT NGLayoutAlgorithm {
STACK_ALLOCATED();
@@ -74,15 +74,15 @@ class CORE_EXPORT NGLayoutAlgorithm {
NGInputNodeType Node() const { return node_; }
- const NGBreakTokenType* BreakToken() const { return break_token_; }
+ const NGBreakTokenType* BreakToken() const { return break_token_.get(); }
NGInputNodeType node_;
const NGConstraintSpace& constraint_space_;
// The break token from which we are currently resuming layout.
- const NGBreakTokenType* break_token_;
+ scoped_refptr<const NGBreakTokenType> break_token_;
- NGFragmentBuilderType container_builder_;
+ NGBoxFragmentBuilderType container_builder_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc
index 9c1f54fb3f1..a52471a7cd2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc
@@ -127,6 +127,12 @@ NGPhysicalSize NGLayoutInputNode::InitialContainingBlockSize() const {
LayoutUnit(icb_size.Height())};
}
+const NGPaintFragment* NGLayoutInputNode::PaintFragment() const {
+ if (LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(GetLayoutBox()))
+ return block_flow->PaintFragment();
+ return nullptr;
+}
+
String NGLayoutInputNode::ToString() const {
return IsInline() ? ToNGInlineNode(*this).ToString()
: ToNGBlockNode(*this).ToString();
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h
index b9a51df2e9f..b7cbcd6206e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
@@ -23,6 +23,7 @@ class NGBreakToken;
class NGConstraintSpace;
class NGInlineChildLayoutContext;
class NGLayoutResult;
+class NGPaintFragment;
struct MinMaxSize;
struct NGLogicalSize;
struct NGPhysicalSize;
@@ -31,15 +32,11 @@ enum class NGMinMaxSizeType { kContentBoxSize, kBorderBoxSize };
// Input to the min/max inline size calculation algorithm for child nodes. Child
// nodes within the same formatting context need to know which floats are beside
-// them. Additionally, orthogonal writing mode roots will need the extrinsic
-// block-size of the container.
+// them.
struct MinMaxSizeInput {
LayoutUnit float_left_inline_size;
LayoutUnit float_right_inline_size;
- // Extrinsic block-size of the containing block.
- LayoutUnit extrinsic_block_size = NGSizeIndefinite;
-
// Whether to return the size as a content-box size or border-box size.
NGMinMaxSizeType size_type = NGMinMaxSizeType::kBorderBoxSize;
};
@@ -109,6 +106,14 @@ class CORE_EXPORT NGLayoutInputNode {
(box_->IsBody() || box_->IsTableCell());
}
+ // In quirks mode, in-flow positioned BODY and root elements must completely
+ // fill the viewport. Return true if this is such a node.
+ bool IsQuirkyAndFillsViewport() const {
+ if (!GetDocument().InQuirksMode())
+ return false;
+ return (IsDocumentElement() || IsBody()) && !Style().HasOutOfFlowPosition();
+ }
+
bool CreatesNewFormattingContext() const {
return IsBlock() && box_->AvoidsFloats();
}
@@ -152,6 +157,10 @@ class CORE_EXPORT NGLayoutInputNode {
return box_->ShouldApplySizeContainment();
}
+ // Returns the first NGPaintFragment for this node. When block fragmentation
+ // occurs, there will be multiple NGPaintFragment for a node.
+ const NGPaintFragment* PaintFragment() const;
+
String ToString() const;
explicit operator bool() const { return box_ != nullptr; }
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc
index 7c47dcbaa52..c17b1a98d7c 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc
@@ -8,60 +8,94 @@
#include <utility>
#include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
namespace blink {
NGLayoutResult::NGLayoutResult(
scoped_refptr<const NGPhysicalFragment> physical_fragment,
- Vector<NGOutOfFlowPositionedDescendant>&& oof_positioned_descendants,
- Vector<NGPositionedFloat>&& positioned_floats,
- const NGUnpositionedListMarker& unpositioned_list_marker,
- NGExclusionSpace&& exclusion_space,
- LayoutUnit bfc_line_offset,
- const base::Optional<LayoutUnit> bfc_block_offset,
- const NGMarginStrut end_margin_strut,
- const LayoutUnit intrinsic_block_size,
- LayoutUnit minimal_space_shortage,
- EBreakBetween initial_break_before,
- EBreakBetween final_break_after,
- bool has_forced_break,
- bool is_pushed_by_floats,
- NGFloatTypes adjoining_floats,
- NGLayoutResultStatus status)
- : unpositioned_list_marker_(unpositioned_list_marker),
- exclusion_space_(std::move(exclusion_space)),
- bfc_line_offset_(bfc_line_offset),
- bfc_block_offset_(bfc_block_offset),
- end_margin_strut_(end_margin_strut),
- intrinsic_block_size_(intrinsic_block_size),
- minimal_space_shortage_(minimal_space_shortage),
- initial_break_before_(initial_break_before),
- final_break_after_(final_break_after),
- has_forced_break_(has_forced_break),
- is_pushed_by_floats_(is_pushed_by_floats),
- adjoining_floats_(adjoining_floats),
+ NGBoxFragmentBuilder* builder)
+ : unpositioned_list_marker_(builder->unpositioned_list_marker_),
+ exclusion_space_(std::move(builder->exclusion_space_)),
+ bfc_line_offset_(builder->bfc_line_offset_),
+ bfc_block_offset_(builder->bfc_block_offset_),
+ end_margin_strut_(builder->end_margin_strut_),
+ intrinsic_block_size_(builder->intrinsic_block_size_),
+ minimal_space_shortage_(builder->minimal_space_shortage_),
+ initial_break_before_(builder->initial_break_before_),
+ final_break_after_(builder->previous_break_after_),
+ has_forced_break_(builder->has_forced_break_),
+ is_pushed_by_floats_(builder->is_pushed_by_floats_),
+ adjoining_floats_(builder->adjoining_floats_),
+ has_orthogonal_flow_roots_(builder->has_orthogonal_flow_roots_),
+ status_(kSuccess) {
+ DCHECK(physical_fragment) << "Use the other constructor for aborting layout";
+ root_fragment_.fragment_ = std::move(physical_fragment);
+ oof_positioned_descendants_ = std::move(builder->oof_positioned_descendants_);
+}
+
+NGLayoutResult::NGLayoutResult(NGLayoutResultStatus status,
+ NGBoxFragmentBuilder* builder)
+ : bfc_line_offset_(builder->bfc_line_offset_),
+ bfc_block_offset_(builder->bfc_block_offset_),
+ end_margin_strut_(builder->end_margin_strut_),
+ initial_break_before_(EBreakBetween::kAuto),
+ final_break_after_(EBreakBetween::kAuto),
+ has_forced_break_(false),
+ is_pushed_by_floats_(false),
+ adjoining_floats_(kFloatTypeNone),
+ has_orthogonal_flow_roots_(builder->has_orthogonal_flow_roots_),
status_(status) {
+ DCHECK_NE(status, kSuccess)
+ << "Use the other constructor for successful layout";
+}
+
+NGLayoutResult::NGLayoutResult(
+ scoped_refptr<const NGPhysicalFragment> physical_fragment,
+ NGLineBoxFragmentBuilder* builder)
+ : unpositioned_list_marker_(builder->unpositioned_list_marker_),
+ exclusion_space_(std::move(builder->exclusion_space_)),
+ bfc_line_offset_(builder->bfc_line_offset_),
+ bfc_block_offset_(builder->bfc_block_offset_),
+ end_margin_strut_(builder->end_margin_strut_),
+ minimal_space_shortage_(LayoutUnit::Max()),
+ initial_break_before_(EBreakBetween::kAuto),
+ final_break_after_(EBreakBetween::kAuto),
+ has_forced_break_(false),
+ is_pushed_by_floats_(builder->is_pushed_by_floats_),
+ adjoining_floats_(builder->adjoining_floats_),
+ has_orthogonal_flow_roots_(builder->has_orthogonal_flow_roots_),
+ status_(kSuccess) {
root_fragment_.fragment_ = std::move(physical_fragment);
- oof_positioned_descendants_.swap(oof_positioned_descendants);
- positioned_floats_.swap(positioned_floats);
+ oof_positioned_descendants_ = std::move(builder->oof_positioned_descendants_);
+ positioned_floats_ = std::move(builder->positioned_floats_);
}
+// We can't use =default here because RefCounted can't be copied.
+NGLayoutResult::NGLayoutResult(const NGLayoutResult& other,
+ base::Optional<LayoutUnit> bfc_block_offset)
+ : root_fragment_(other.root_fragment_),
+ oof_positioned_descendants_(other.oof_positioned_descendants_),
+ positioned_floats_(other.positioned_floats_),
+ unpositioned_list_marker_(other.unpositioned_list_marker_),
+ exclusion_space_(other.exclusion_space_),
+ bfc_line_offset_(other.bfc_line_offset_),
+ bfc_block_offset_(bfc_block_offset),
+ end_margin_strut_(other.end_margin_strut_),
+ intrinsic_block_size_(other.intrinsic_block_size_),
+ minimal_space_shortage_(other.minimal_space_shortage_),
+ initial_break_before_(other.initial_break_before_),
+ final_break_after_(other.final_break_after_),
+ has_forced_break_(other.has_forced_break_),
+ is_pushed_by_floats_(other.is_pushed_by_floats_),
+ adjoining_floats_(other.adjoining_floats_),
+ has_orthogonal_flow_roots_(other.has_orthogonal_flow_roots_),
+ status_(other.status_) {}
+
// Define the destructor here, so that we can forward-declare more in the
// header.
NGLayoutResult::~NGLayoutResult() = default;
-scoped_refptr<NGLayoutResult> NGLayoutResult::CloneWithoutOffset() const {
- Vector<NGOutOfFlowPositionedDescendant> oof_positioned_descendants(
- oof_positioned_descendants_);
- Vector<NGPositionedFloat> positioned_floats(positioned_floats_);
- return base::AdoptRef(new NGLayoutResult(
- root_fragment_.fragment_, std::move(oof_positioned_descendants),
- std::move(positioned_floats), unpositioned_list_marker_,
- NGExclusionSpace(exclusion_space_), bfc_line_offset_, bfc_block_offset_,
- end_margin_strut_, intrinsic_block_size_, minimal_space_shortage_,
- initial_break_before_, final_break_after_, has_forced_break_,
- is_pushed_by_floats_, adjoining_floats_, Status()));
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.h
index cbf54b08b5c..1ed7835c703 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.h
@@ -20,7 +20,9 @@
namespace blink {
+class NGBoxFragmentBuilder;
class NGExclusionSpace;
+class NGLineBoxFragmentBuilder;
struct NGPositionedFloat;
// The NGLayoutResult stores the resulting data from layout. This includes
@@ -38,9 +40,14 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
// enough to store.
};
+ // Create a copy of NGLayoutResult with |BfcBlockOffset| replaced by the given
+ // parameter. Note, when |bfc_block_offset| is |nullopt|, |BfcBlockOffset| is
+ // still replaced with |nullopt|.
+ NGLayoutResult(const NGLayoutResult&,
+ base::Optional<LayoutUnit> bfc_block_offset);
~NGLayoutResult();
- scoped_refptr<const NGPhysicalFragment> PhysicalFragment() const {
+ const NGPhysicalFragment* PhysicalFragment() const {
return root_fragment_.get();
}
NGPhysicalOffset Offset() const { return root_fragment_.Offset(); }
@@ -110,29 +117,23 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
// the block, and the block will fail to clear).
NGFloatTypes AdjoiningFloatTypes() const { return adjoining_floats_; }
- scoped_refptr<NGLayoutResult> CloneWithoutOffset() const;
+ bool HasOrthogonalFlowRoots() const { return has_orthogonal_flow_roots_; }
private:
- friend class NGFragmentBuilder;
+ friend class NGBoxFragmentBuilder;
friend class NGLineBoxFragmentBuilder;
+ // This constructor requires a non-null fragment and sets a success status.
NGLayoutResult(scoped_refptr<const NGPhysicalFragment> physical_fragment,
- Vector<NGOutOfFlowPositionedDescendant>&&
- out_of_flow_positioned_descendants,
- Vector<NGPositionedFloat>&& positioned_floats,
- const NGUnpositionedListMarker& unpositioned_list_marker,
- NGExclusionSpace&& exclusion_space,
- LayoutUnit bfc_line_offset,
- const base::Optional<LayoutUnit> bfc_block_offset,
- const NGMarginStrut end_margin_strut,
- const LayoutUnit intrinsic_block_size,
- LayoutUnit minimal_space_shortage,
- EBreakBetween initial_break_before,
- EBreakBetween final_break_after,
- bool has_forced_break,
- bool is_pushed_by_floats,
- NGFloatTypes adjoining_floats,
- NGLayoutResultStatus status);
+ NGBoxFragmentBuilder*);
+ // This constructor is for a non-success status.
+ NGLayoutResult(NGLayoutResultStatus, NGBoxFragmentBuilder*);
+ NGLayoutResult(scoped_refptr<const NGPhysicalFragment> physical_fragment,
+ NGLineBoxFragmentBuilder*);
+
+ // We don't need copy constructor today. Delete this to clarify that the
+ // default copy constructor will not work because RefCounted can't be copied.
+ NGLayoutResult(const NGLayoutResult&) = delete;
NGLink root_fragment_;
Vector<NGOutOfFlowPositionedDescendant> oof_positioned_descendants_;
@@ -156,6 +157,8 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
unsigned is_pushed_by_floats_ : 1;
unsigned adjoining_floats_ : 2; // NGFloatTypes
+ unsigned has_orthogonal_flow_roots_ : 1;
+
unsigned status_ : 1;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc
index 1f0e3a7d9d3..912a10ee5fa 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc
@@ -13,25 +13,89 @@
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
-bool NeedMinMaxSize(const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- // This check is technically too broad (fill-available does not need intrinsic
- // size computation) but that's a rare case and only affects performance, not
- // correctness.
- return constraint_space.IsShrinkToFit() || NeedMinMaxSize(style);
+namespace {
+
+enum class EBlockAlignment { kStart, kCenter, kEnd };
+
+inline EBlockAlignment BlockAlignment(const ComputedStyle& style,
+ const ComputedStyle& container_style) {
+ bool start_auto = style.MarginStartUsing(container_style).IsAuto();
+ bool end_auto = style.MarginEndUsing(container_style).IsAuto();
+ if (start_auto || end_auto) {
+ if (start_auto)
+ return end_auto ? EBlockAlignment::kCenter : EBlockAlignment::kEnd;
+ return EBlockAlignment::kStart;
+ }
+
+ // If none of the inline margins are auto, look for -webkit- text-align
+ // values (which are really about block alignment). These are typically
+ // mapped from the legacy "align" HTML attribute.
+ switch (container_style.GetTextAlign()) {
+ case ETextAlign::kWebkitLeft:
+ if (container_style.IsLeftToRightDirection())
+ return EBlockAlignment::kStart;
+ return EBlockAlignment::kEnd;
+ case ETextAlign::kWebkitRight:
+ if (container_style.IsLeftToRightDirection())
+ return EBlockAlignment::kEnd;
+ return EBlockAlignment::kStart;
+ case ETextAlign::kWebkitCenter:
+ return EBlockAlignment::kCenter;
+ default:
+ return EBlockAlignment::kStart;
+ }
}
-bool NeedMinMaxSize(const ComputedStyle& style) {
- return style.LogicalWidth().IsIntrinsic() ||
- style.LogicalMinWidth().IsIntrinsic() ||
- style.LogicalMaxWidth().IsIntrinsic();
+inline bool InlineLengthMayChange(Length length,
+ const NGConstraintSpace& new_space,
+ const NGConstraintSpace& old_space) {
+ // Percentage inline margins will affect the size if the size is unspecified
+ // (auto and similar). So we need to check both available size and the
+ // percentage resolution size in that case.
+ bool is_unspecified =
+ length.IsAuto() || length.IsFitContent() || length.IsFillAvailable();
+ if (is_unspecified) {
+ if (new_space.AvailableSize().inline_size !=
+ old_space.AvailableSize().inline_size)
+ return true;
+ }
+ if (is_unspecified || length.IsPercentOrCalc()) {
+ if (new_space.PercentageResolutionInlineSize() !=
+ old_space.PercentageResolutionInlineSize())
+ return true;
+ }
+ return false;
+}
+
+inline bool BlockLengthMayChange(Length length,
+ const NGConstraintSpace& new_space,
+ const NGConstraintSpace& old_space) {
+ if (length.IsFillAvailable()) {
+ if (new_space.AvailableSize().block_size !=
+ old_space.AvailableSize().block_size)
+ return true;
+ } else if (length.IsAuto() || length.IsPercentOrCalc()) {
+ // Note that we check percentage resolution changes for 'auto' values here
+ // (in addition to percent values). The reason is that percentage resolution
+ // block sizes may be passed through auto-sized blocks, in some cases,
+ // e.g. for anonymous blocks, and also in quirks mode.
+ if (new_space.PercentageResolutionBlockSize() !=
+ old_space.PercentageResolutionBlockSize())
+ return true;
+ if (new_space.ReplacedPercentageResolutionBlockSize() !=
+ old_space.ReplacedPercentageResolutionBlockSize())
+ return true;
+ }
+ return false;
}
+} // anonymous namespace
+
bool NeedMinMaxSizeForContentContribution(WritingMode mode,
const ComputedStyle& style) {
// During the intrinsic sizes pass percentages/calc() are defined to behave
@@ -59,8 +123,7 @@ LayoutUnit ResolveInlineLength(
LengthResolvePhase phase,
const base::Optional<NGBoxStrut>& opt_border_padding) {
DCHECK_GE(constraint_space.AvailableSize().inline_size, LayoutUnit());
- DCHECK_GE(constraint_space.PercentageResolutionSize().inline_size,
- LayoutUnit());
+ DCHECK_GE(constraint_space.PercentageResolutionInlineSize(), LayoutUnit());
DCHECK_EQ(constraint_space.GetWritingMode(), style.GetWritingMode());
if (constraint_space.IsAnonymous())
@@ -79,9 +142,10 @@ LayoutUnit ResolveInlineLength(
if (type == LengthResolveType::kMinSize && length.IsAuto())
return border_and_padding.InlineSum();
- // Check if we shouldn't resolve a percentage/calc() if we are in the
- // intrinsic sizes phase.
- if (phase == LengthResolvePhase::kIntrinsic && length.IsPercentOrCalc()) {
+ // Check if we shouldn't resolve a percentage/calc()/-webkit-fill-available
+ // if we are in the intrinsic sizes phase.
+ if (phase == LengthResolvePhase::kIntrinsic &&
+ (length.IsPercentOrCalc() || length.GetType() == kFillAvailable)) {
// min-width/min-height should be "0", i.e. no min limit is applied.
if (type == LengthResolveType::kMinSize)
return border_and_padding.InlineSum();
@@ -103,7 +167,7 @@ LayoutUnit ResolveInlineLength(
case kFixed:
case kCalculated: {
LayoutUnit percentage_resolution_size =
- constraint_space.PercentageResolutionSize().inline_size;
+ constraint_space.PercentageResolutionInlineSize();
LayoutUnit value = ValueForLength(length, percentage_resolution_size);
if (style.BoxSizing() == EBoxSizing::kContentBox) {
value += border_and_padding.InlineSum();
@@ -180,15 +244,19 @@ LayoutUnit ResolveBlockLength(
style.OverflowY() == EOverflow::kScroll))
return border_and_padding.BlockSum();
- bool is_percentage_indefinite =
- constraint_space.PercentageResolutionSize().block_size ==
- NGSizeIndefinite;
-
- // Check if we can't/shouldn't resolve a percentage/calc() - because the
- // percentage resolution size is indefinite or because we are in the
- // intrinsic sizes phase.
- if ((phase == LengthResolvePhase::kIntrinsic || is_percentage_indefinite) &&
- length.IsPercentOrCalc()) {
+ // When the containing block size to resolve against is indefinite, we
+ // cannot resolve percentages / calc() / -webkit-fill-available.
+ bool size_is_unresolvable = false;
+ if (length.IsPercentOrCalc()) {
+ size_is_unresolvable =
+ phase == LengthResolvePhase::kIntrinsic ||
+ constraint_space.PercentageResolutionBlockSize() == NGSizeIndefinite;
+ } else if (length.GetType() == kFillAvailable) {
+ size_is_unresolvable =
+ phase == LengthResolvePhase::kIntrinsic ||
+ constraint_space.AvailableSize().block_size == NGSizeIndefinite;
+ }
+ if (size_is_unresolvable) {
// min-width/min-height should be "0", i.e. no min limit is applied.
if (type == LengthResolveType::kMinSize)
return border_and_padding.BlockSum();
@@ -213,7 +281,7 @@ LayoutUnit ResolveBlockLength(
case kFixed:
case kCalculated: {
LayoutUnit percentage_resolution_size =
- constraint_space.PercentageResolutionSize().block_size;
+ constraint_space.PercentageResolutionBlockSize();
LayoutUnit value = ValueForLength(length, percentage_resolution_size);
// Percentage-sized children of table cells, in the table "layout" phase,
@@ -256,9 +324,9 @@ LayoutUnit ResolveBlockLength(
}
}
-LayoutUnit ResolveMarginPaddingLength(const NGConstraintSpace& constraint_space,
+LayoutUnit ResolveMarginPaddingLength(LayoutUnit percentage_resolution_size,
const Length& length) {
- DCHECK_GE(constraint_space.AvailableSize().inline_size, LayoutUnit());
+ DCHECK_GE(percentage_resolution_size, LayoutUnit());
// Margins and padding always get computed relative to the inline size:
// https://www.w3.org/TR/CSS2/box.html#value-def-margin-width
@@ -268,11 +336,8 @@ LayoutUnit ResolveMarginPaddingLength(const NGConstraintSpace& constraint_space,
return LayoutUnit();
case kPercent:
case kFixed:
- case kCalculated: {
- LayoutUnit percentage_resolution_size =
- constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ case kCalculated:
return ValueForLength(length, percentage_resolution_size);
- }
case kMinContent:
case kMaxContent:
case kFillAvailable:
@@ -298,9 +363,9 @@ MinMaxSize ComputeMinAndMaxContentContribution(
// use the passed-in mode here.
NGConstraintSpace space =
NGConstraintSpaceBuilder(
- style.GetWritingMode(),
- /* icb_size */ {NGSizeIndefinite, NGSizeIndefinite})
- .ToConstraintSpace(style.GetWritingMode());
+ style.GetWritingMode(), style.GetWritingMode(),
+ /* is_new_fc */ false)
+ .ToConstraintSpace();
LayoutUnit content_size =
min_and_max ? min_and_max->max_size : NGSizeIndefinite;
@@ -360,11 +425,12 @@ MinMaxSize ComputeMinAndMaxContentContribution(
}
MinMaxSize ComputeMinAndMaxContentContribution(
- WritingMode writing_mode,
- NGLayoutInputNode node,
- const MinMaxSizeInput& input,
- const NGConstraintSpace* constraint_space) {
- LayoutBox* box = node.GetLayoutBox();
+ const ComputedStyle& parent_style,
+ NGLayoutInputNode child,
+ const MinMaxSizeInput& input) {
+ const ComputedStyle& child_style = child.Style();
+ WritingMode parent_writing_mode = parent_style.GetWritingMode();
+ LayoutBox* box = child.GetLayoutBox();
if (box->NeedsPreferredWidthsRecalculation()) {
// Some objects (when there's an intrinsic ratio) have their min/max inline
@@ -375,7 +441,8 @@ MinMaxSize ComputeMinAndMaxContentContribution(
box->SetPreferredLogicalWidthsDirty();
}
- if (IsParallelWritingMode(writing_mode, node.Style().GetWritingMode())) {
+ if (IsParallelWritingMode(parent_writing_mode,
+ child_style.GetWritingMode())) {
if (!box->PreferredLogicalWidthsDirty()) {
return {box->MinPreferredLogicalWidth(), box->MaxPreferredLogicalWidth()};
}
@@ -389,32 +456,24 @@ MinMaxSize ComputeMinAndMaxContentContribution(
}
base::Optional<MinMaxSize> minmax;
- if (NeedMinMaxSizeForContentContribution(writing_mode, node.Style())) {
- NGConstraintSpace adjusted_constraint_space;
- if (constraint_space) {
- // TODO(layout-ng): Check if our constraint space produces spec-compliant
- // outputs.
- // It is important to set a floats bfc block offset so that we don't get a
- // partial layout. It is also important that we shrink to fit, by
- // definition.
- adjusted_constraint_space =
- NGConstraintSpaceBuilder(*constraint_space)
- .SetAvailableSize(constraint_space->AvailableSize())
- .SetPercentageResolutionSize(
- constraint_space->PercentageResolutionSize())
- .SetFloatsBfcBlockOffset(LayoutUnit())
- .SetIsNewFormattingContext(
- constraint_space->IsNewFormattingContext())
- .SetIsShrinkToFit(true)
- .ToConstraintSpace(node.Style().GetWritingMode());
- constraint_space = &adjusted_constraint_space;
+ if (NeedMinMaxSizeForContentContribution(parent_writing_mode, child_style)) {
+ // We need to set up a constraint space with correct fallback available
+ // inline size in case of orthogonal children.
+ NGConstraintSpace indefinite_constraint_space;
+ const NGConstraintSpace* child_constraint_space = nullptr;
+ if (!IsParallelWritingMode(parent_writing_mode,
+ child_style.GetWritingMode())) {
+ indefinite_constraint_space =
+ CreateIndefiniteConstraintSpaceForChild(parent_style, child);
+ child_constraint_space = &indefinite_constraint_space;
}
- minmax = node.ComputeMinMaxSize(writing_mode, input, constraint_space);
+ minmax = child.ComputeMinMaxSize(parent_writing_mode, input,
+ child_constraint_space);
}
- MinMaxSize sizes =
- ComputeMinAndMaxContentContribution(writing_mode, node.Style(), minmax);
- if (IsParallelWritingMode(writing_mode, node.Style().GetWritingMode()))
+ MinMaxSize sizes = ComputeMinAndMaxContentContribution(parent_writing_mode,
+ child_style, minmax);
+ if (IsParallelWritingMode(parent_writing_mode, child_style.GetWritingMode()))
box->SetPreferredLogicalWidthsFromNG(sizes);
return sizes;
}
@@ -593,6 +652,58 @@ NGLogicalSize ComputeReplacedSize(
return replaced_size;
}
+bool SizeMayChange(const ComputedStyle& style,
+ const NGConstraintSpace& new_space,
+ const NGConstraintSpace& old_space) {
+ DCHECK_EQ(new_space.IsFixedSizeInline(), old_space.IsFixedSizeInline());
+ DCHECK_EQ(new_space.IsFixedSizeBlock(), old_space.IsFixedSizeBlock());
+
+ // Go through all length properties, and, depending on length type
+ // (percentages, auto, etc.), check whether the constraint spaces differ in
+ // such a way that the resulting size *may* change. There are currently many
+ // possible false-positive situations here, as we don't rule out length
+ // changes that won't have any effect on the final size (e.g. if inline-size
+ // is 100px, max-inline-size is 50%, and percentage resolution inline size
+ // changes from 1000px to 500px). If the constraint space has "fixed" size in
+ // a dimension, we can skip checking properties in that dimension and just
+ // look for available size changes, since that's how a "fixed" constraint
+ // space works.
+ if (new_space.IsFixedSizeInline()) {
+ if (new_space.AvailableSize().inline_size !=
+ old_space.AvailableSize().inline_size)
+ return true;
+ } else {
+ if (InlineLengthMayChange(style.LogicalWidth(), new_space, old_space) ||
+ InlineLengthMayChange(style.LogicalMaxWidth(), new_space, old_space) ||
+ InlineLengthMayChange(style.LogicalMaxWidth(), new_space, old_space))
+ return true;
+ }
+
+ if (new_space.IsFixedSizeBlock()) {
+ if (new_space.AvailableSize().block_size !=
+ old_space.AvailableSize().block_size)
+ return true;
+ } else {
+ if (BlockLengthMayChange(style.LogicalHeight(), new_space, old_space) ||
+ BlockLengthMayChange(style.LogicalMinHeight(), new_space, old_space) ||
+ BlockLengthMayChange(style.LogicalMaxHeight(), new_space, old_space))
+ return true;
+ }
+
+ if (new_space.PercentageResolutionInlineSize() !=
+ old_space.PercentageResolutionInlineSize()) {
+ // Percentage-based padding is resolved against the inline content box size
+ // of the containing block.
+ if (style.PaddingTop().IsPercentOrCalc() ||
+ style.PaddingRight().IsPercentOrCalc() ||
+ style.PaddingBottom().IsPercentOrCalc() ||
+ style.PaddingLeft().IsPercentOrCalc())
+ return true;
+ }
+
+ return false;
+}
+
int ResolveUsedColumnCount(int computed_count,
LayoutUnit computed_size,
LayoutUnit used_gap,
@@ -655,56 +766,34 @@ LayoutUnit ResolveUsedColumnGap(LayoutUnit available_size,
}
NGPhysicalBoxStrut ComputePhysicalMargins(
- const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- if (style.MarginLeft().IsZero() && style.MarginRight().IsZero() &&
- style.MarginTop().IsZero() && style.MarginBottom().IsZero()) {
- return NGPhysicalBoxStrut();
- }
-
- if (constraint_space.IsAnonymous())
+ const ComputedStyle& style,
+ LayoutUnit percentage_resolution_size) {
+ if (!style.HasMargin())
return NGPhysicalBoxStrut();
NGPhysicalBoxStrut physical_dim;
- physical_dim.left =
- ResolveMarginPaddingLength(constraint_space, style.MarginLeft());
- physical_dim.right =
- ResolveMarginPaddingLength(constraint_space, style.MarginRight());
+ physical_dim.left = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.MarginLeft());
+ physical_dim.right = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.MarginRight());
physical_dim.top =
- ResolveMarginPaddingLength(constraint_space, style.MarginTop());
- physical_dim.bottom =
- ResolveMarginPaddingLength(constraint_space, style.MarginBottom());
+ ResolveMarginPaddingLength(percentage_resolution_size, style.MarginTop());
+ physical_dim.bottom = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.MarginBottom());
return physical_dim;
}
NGBoxStrut ComputeMarginsFor(const NGConstraintSpace& constraint_space,
const ComputedStyle& style,
const NGConstraintSpace& compute_for) {
- return ComputePhysicalMargins(constraint_space, style)
+ if (constraint_space.IsAnonymous())
+ return NGBoxStrut();
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ return ComputePhysicalMargins(style, percentage_resolution_size)
.ConvertToLogical(compute_for.GetWritingMode(), compute_for.Direction());
}
-NGLineBoxStrut ComputeLineMarginsForVisualContainer(
- const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- return ComputePhysicalMargins(constraint_space, style)
- .ConvertToLineLogical(constraint_space.GetWritingMode(),
- TextDirection::kLtr);
-}
-
-NGBoxStrut ComputeMarginsForSelf(const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- return ComputePhysicalMargins(constraint_space, style)
- .ConvertToLogical(style.GetWritingMode(), style.Direction());
-}
-
-NGLineBoxStrut ComputeLineMarginsForSelf(
- const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- return ComputePhysicalMargins(constraint_space, style)
- .ConvertToLineLogical(style.GetWritingMode(), style.Direction());
-}
-
NGBoxStrut ComputeMinMaxMargins(const ComputedStyle& parent_style,
NGLayoutInputNode child) {
// An inline child just produces line-boxes which don't have any margins.
@@ -758,12 +847,6 @@ NGBoxStrut ComputeBorders(const NGConstraintSpace& constraint_space,
return ComputeBorders(constraint_space, node.Style());
}
-NGLineBoxStrut ComputeLineBorders(const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- return NGLineBoxStrut(ComputeBorders(constraint_space, style),
- style.IsFlippedLinesWritingMode());
-}
-
NGBoxStrut ComputeIntrinsicPadding(const NGConstraintSpace& constraint_space,
const NGLayoutInputNode node) {
if (constraint_space.IsAnonymous() || !node.IsTableCell())
@@ -786,26 +869,33 @@ NGBoxStrut ComputePadding(const NGConstraintSpace& constraint_space,
if (constraint_space.IsAnonymous())
return NGBoxStrut();
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
NGBoxStrut padding;
- padding.inline_start =
- ResolveMarginPaddingLength(constraint_space, style.PaddingStart());
- padding.inline_end =
- ResolveMarginPaddingLength(constraint_space, style.PaddingEnd());
- padding.block_start =
- ResolveMarginPaddingLength(constraint_space, style.PaddingBefore());
- padding.block_end =
- ResolveMarginPaddingLength(constraint_space, style.PaddingAfter());
+ padding.inline_start = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.PaddingStart());
+ padding.inline_end = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.PaddingEnd());
+ padding.block_start = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.PaddingBefore());
+ padding.block_end = ResolveMarginPaddingLength(percentage_resolution_size,
+ style.PaddingAfter());
return padding;
}
-NGLineBoxStrut ComputeLinePadding(const NGConstraintSpace& constraint_space,
- const ComputedStyle& style) {
- return NGLineBoxStrut(ComputePadding(constraint_space, style),
- style.IsFlippedLinesWritingMode());
+
+bool NeedsInlineSizeToResolveLineLeft(const ComputedStyle& style,
+ const ComputedStyle& container_style) {
+ // In RTL, there's no block alignment where we can guarantee that line-left
+ // doesn't depend on the inline size of a fragment.
+ if (IsRtl(container_style.Direction()))
+ return true;
+
+ return BlockAlignment(style, container_style) != EBlockAlignment::kStart;
}
void ResolveInlineMargins(const ComputedStyle& style,
- const ComputedStyle& containing_block_style,
+ const ComputedStyle& container_style,
LayoutUnit available_inline_size,
LayoutUnit inline_size,
NGBoxStrut* margins) {
@@ -813,36 +903,10 @@ void ResolveInlineMargins(const ComputedStyle& style,
const LayoutUnit used_space = inline_size + margins->InlineSum();
const LayoutUnit available_space = available_inline_size - used_space;
if (available_space > LayoutUnit()) {
- bool start_auto = style.MarginStartUsing(containing_block_style).IsAuto();
- bool end_auto = style.MarginEndUsing(containing_block_style).IsAuto();
- enum EBlockAlignment { kStart, kCenter, kEnd };
- EBlockAlignment alignment;
- if (start_auto || end_auto) {
- alignment = start_auto ? (end_auto ? kCenter : kEnd) : kStart;
- } else {
- // If none of the inline margins are auto, look for -webkit- text-align
- // values (which are really about block alignment). These are typically
- // mapped from the legacy "align" HTML attribute.
- switch (containing_block_style.GetTextAlign()) {
- case ETextAlign::kWebkitLeft:
- alignment =
- containing_block_style.IsLeftToRightDirection() ? kStart : kEnd;
- break;
- case ETextAlign::kWebkitRight:
- alignment =
- containing_block_style.IsLeftToRightDirection() ? kEnd : kStart;
- break;
- case ETextAlign::kWebkitCenter:
- alignment = kCenter;
- break;
- default:
- alignment = kStart;
- break;
- }
- }
- if (alignment == kCenter)
+ EBlockAlignment alignment = BlockAlignment(style, container_style);
+ if (alignment == EBlockAlignment::kCenter)
margins->inline_start += available_space / 2;
- else if (alignment == kEnd)
+ else if (alignment == EBlockAlignment::kEnd)
margins->inline_start += available_space;
}
margins->inline_end =
@@ -905,12 +969,6 @@ LayoutUnit InlineOffsetForTextAlign(const ComputedStyle& container_style,
return IsLtr(direction) ? line_offset : space_left - line_offset;
}
-LayoutUnit ConstrainByMinMax(LayoutUnit length,
- LayoutUnit min,
- LayoutUnit max) {
- return std::max(min, std::min(length, max));
-}
-
bool ClampScrollbarToContentBox(NGBoxStrut* scrollbars,
LayoutUnit content_box_inline_size) {
DCHECK(scrollbars->InlineSum());
@@ -1037,7 +1095,7 @@ NGLogicalSize CalculateChildPercentageSize(
return AdjustChildPercentageSizeForQuirksAndFlex(
space, node, child_percentage_size,
- space.PercentageResolutionSize().block_size);
+ space.PercentageResolutionBlockSize());
}
NGLogicalSize CalculateReplacedChildPercentageSize(
@@ -1072,7 +1130,7 @@ NGLogicalSize CalculateReplacedChildPercentageSize(
return AdjustChildPercentageSizeForQuirksAndFlex(
space, node, child_percentage_size,
- space.ReplacedPercentageResolutionSize().block_size);
+ space.ReplacedPercentageResolutionBlockSize());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.h
index 06f060ca92b..20bb742474f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils.h
@@ -10,6 +10,9 @@
#include "third_party/blink/renderer/core/layout/min_max_size.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_size.h"
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
@@ -34,13 +37,23 @@ enum class LengthResolvePhase { kIntrinsic, kLayout };
// kContentSize - width / height
enum class LengthResolveType { kMinSize, kMaxSize, kContentSize };
+inline bool NeedMinMaxSize(const ComputedStyle& style) {
+ // This check is technically too broad (fill-available does not need intrinsic
+ // size computation) but that's a rare case and only affects performance, not
+ // correctness.
+ return style.LogicalWidth().IsIntrinsic() ||
+ style.LogicalMinWidth().IsIntrinsic() ||
+ style.LogicalMaxWidth().IsIntrinsic();
+}
+
// Whether the caller needs to compute min-content and max-content sizes to
// pass them to ResolveInlineLength / ComputeInlineSizeForFragment.
// If this function returns false, it is safe to pass an empty
// MinMaxSize struct to those functions.
-CORE_EXPORT bool NeedMinMaxSize(const NGConstraintSpace&, const ComputedStyle&);
-
-CORE_EXPORT bool NeedMinMaxSize(const ComputedStyle&);
+inline bool NeedMinMaxSize(const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ return constraint_space.IsShrinkToFit() || NeedMinMaxSize(style);
+}
// Like NeedMinMaxSize, but for use when calling
// ComputeMinAndMaxContentContribution.
@@ -79,8 +92,15 @@ CORE_EXPORT LayoutUnit ResolveBlockLength(
// Convert margin/border/padding length to a layout unit using the
// given constraint space.
-CORE_EXPORT LayoutUnit ResolveMarginPaddingLength(const NGConstraintSpace&,
- const Length&);
+LayoutUnit ResolveMarginPaddingLength(LayoutUnit percentage_resolution_size,
+ const Length&);
+inline LayoutUnit ResolveMarginPaddingLength(
+ const NGConstraintSpace& constraint_space,
+ const Length& length) {
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ return ResolveMarginPaddingLength(percentage_resolution_size, length);
+}
// For the given style and min/max content sizes, computes the min and max
// content contribution (https://drafts.csswg.org/css-sizing/#contributions).
@@ -98,19 +118,17 @@ ComputeMinAndMaxContentContribution(WritingMode writing_mode,
const base::Optional<MinMaxSize>&);
// A version of ComputeMinAndMaxContentContribution that does not require you
-// to compute the min/max content size of the node. Instead, this function
+// to compute the min/max content size of the child. Instead, this function
// will compute it if necessary.
-// writing_mode is the desired output writing mode (ie. often the writing mode
-// of the parent); node is the node of which to compute the min/max content
-// contribution.
-// If a constraint space is provided, this function will convert it to the
-// correct writing mode and otherwise make sure it is suitable for computing
-// the desired value.
+// |child| is the node of which to compute the min/max content contribution.
+// Note that if the writing mode of the child is orthogonal to that of the
+// parent, we'll still return the inline min/max contribution in the writing
+// mode of the parent (i.e. typically something based on the preferred *block*
+// size of the child).
MinMaxSize ComputeMinAndMaxContentContribution(
- WritingMode writing_mode,
- NGLayoutInputNode node,
- const MinMaxSizeInput& input,
- const NGConstraintSpace* space = nullptr);
+ const ComputedStyle& parent_style,
+ NGLayoutInputNode child,
+ const MinMaxSizeInput& input);
// Resolves the computed value in style.logicalWidth (Length) to a layout unit,
// then constrains the result by the resolved min logical width and max logical
@@ -137,6 +155,13 @@ ComputeReplacedSize(const NGLayoutInputNode&,
const NGConstraintSpace&,
const base::Optional<MinMaxSize>&);
+// Return true if it's possible (but not necessarily guaranteed) that the new
+// constraint space will give a different size compared to the old one, when
+// computed style and child content remain unchanged.
+bool SizeMayChange(const ComputedStyle&,
+ const NGConstraintSpace& new_space,
+ const NGConstraintSpace& old_space);
+
// Based on available inline size, CSS computed column-width, CSS computed
// column-count and CSS used column-gap, return CSS used column-count.
CORE_EXPORT int ResolveUsedColumnCount(int computed_count,
@@ -159,30 +184,71 @@ CORE_EXPORT LayoutUnit ResolveUsedColumnGap(LayoutUnit available_size,
const ComputedStyle&);
// Compute physical margins.
-CORE_EXPORT NGPhysicalBoxStrut ComputePhysicalMargins(const NGConstraintSpace&,
- const ComputedStyle&);
+CORE_EXPORT NGPhysicalBoxStrut
+ComputePhysicalMargins(const ComputedStyle&,
+ LayoutUnit percentage_resolution_size);
+
+inline NGPhysicalBoxStrut ComputePhysicalMargins(
+ const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ return ComputePhysicalMargins(style, percentage_resolution_size);
+}
// Compute margins for the specified NGConstraintSpace.
CORE_EXPORT NGBoxStrut ComputeMarginsFor(const NGConstraintSpace&,
const ComputedStyle&,
const NGConstraintSpace& compute_for);
+inline NGBoxStrut ComputeMarginsFor(const ComputedStyle& child_style,
+ LayoutUnit percentage_resolution_size,
+ WritingMode container_writing_mode,
+ TextDirection container_direction) {
+ return ComputePhysicalMargins(child_style, percentage_resolution_size)
+ .ConvertToLogical(container_writing_mode, container_direction);
+}
+
// Compute margins for the style owner.
-CORE_EXPORT NGBoxStrut ComputeMarginsForSelf(const NGConstraintSpace&,
- const ComputedStyle&);
+inline NGBoxStrut ComputeMarginsForSelf(
+ const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ if (constraint_space.IsAnonymous())
+ return NGBoxStrut();
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ return ComputePhysicalMargins(style, percentage_resolution_size)
+ .ConvertToLogical(style.GetWritingMode(), style.Direction());
+}
// Compute line logical margins for the style owner.
//
// The "line" versions compute line-relative logical values. See NGLineBoxStrut
// for more details.
-CORE_EXPORT NGLineBoxStrut ComputeLineMarginsForSelf(const NGConstraintSpace&,
- const ComputedStyle&);
+inline NGLineBoxStrut ComputeLineMarginsForSelf(
+ const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ if (constraint_space.IsAnonymous())
+ return NGLineBoxStrut();
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ return ComputePhysicalMargins(style, percentage_resolution_size)
+ .ConvertToLineLogical(style.GetWritingMode(), style.Direction());
+}
// Compute line logical margins for the constraint space, in the visual order
// (always assumes LTR, ignoring the direction) for inline layout algorithm.
-CORE_EXPORT NGLineBoxStrut
-ComputeLineMarginsForVisualContainer(const NGConstraintSpace&,
- const ComputedStyle&);
+inline NGLineBoxStrut ComputeLineMarginsForVisualContainer(
+ const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ if (constraint_space.IsAnonymous())
+ return NGLineBoxStrut();
+ LayoutUnit percentage_resolution_size =
+ constraint_space.PercentageResolutionInlineSizeForParentWritingMode();
+ return ComputePhysicalMargins(style, percentage_resolution_size)
+ .ConvertToLineLogical(constraint_space.GetWritingMode(),
+ TextDirection::kLtr);
+}
// Compute margins for a child during the min-max size calculation.
CORE_EXPORT NGBoxStrut ComputeMinMaxMargins(const ComputedStyle& parent_style,
@@ -194,8 +260,12 @@ CORE_EXPORT NGBoxStrut ComputeBorders(const NGConstraintSpace&,
CORE_EXPORT NGBoxStrut ComputeBorders(const NGConstraintSpace&,
const NGLayoutInputNode);
-CORE_EXPORT NGLineBoxStrut ComputeLineBorders(const NGConstraintSpace&,
- const ComputedStyle&);
+inline NGLineBoxStrut ComputeLineBorders(
+ const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ return NGLineBoxStrut(ComputeBorders(constraint_space, style),
+ style.IsFlippedLinesWritingMode());
+}
CORE_EXPORT NGBoxStrut ComputeIntrinsicPadding(const NGConstraintSpace&,
const NGLayoutInputNode);
@@ -203,8 +273,20 @@ CORE_EXPORT NGBoxStrut ComputeIntrinsicPadding(const NGConstraintSpace&,
CORE_EXPORT NGBoxStrut ComputePadding(const NGConstraintSpace&,
const ComputedStyle&);
-CORE_EXPORT NGLineBoxStrut ComputeLinePadding(const NGConstraintSpace&,
- const ComputedStyle&);
+inline NGLineBoxStrut ComputeLinePadding(
+ const NGConstraintSpace& constraint_space,
+ const ComputedStyle& style) {
+ return NGLineBoxStrut(ComputePadding(constraint_space, style),
+ style.IsFlippedLinesWritingMode());
+}
+
+// Return true if we need to know the inline size of the fragment in order to
+// calculate its line-left offset. This is the case when we have auto margins,
+// or when block alignment isn't line-left (e.g. with align!=left, and always in
+// RTL mode).
+bool NeedsInlineSizeToResolveLineLeft(
+ const ComputedStyle& style,
+ const ComputedStyle& containing_block_style);
// Convert inline margins from computed to used values. This will resolve 'auto'
// values and over-constrainedness. This uses the available size from the
@@ -231,9 +313,11 @@ CORE_EXPORT LayoutUnit LineOffsetForTextAlign(ETextAlign,
CORE_EXPORT LayoutUnit InlineOffsetForTextAlign(const ComputedStyle&,
LayoutUnit space_left);
-CORE_EXPORT LayoutUnit ConstrainByMinMax(LayoutUnit length,
- LayoutUnit min,
- LayoutUnit max);
+inline LayoutUnit ConstrainByMinMax(LayoutUnit length,
+ LayoutUnit min,
+ LayoutUnit max) {
+ return std::max(min, std::min(length, max));
+}
// Clamp the inline size of the scrollbar, unless it's larger than the inline
// size of the content box, in which case we'll return that instead. Scrollbar
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc
index 596f139299c..f0f212b7978 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc
@@ -11,9 +11,9 @@
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_test.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/calculation_value.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/calculation_value.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
namespace {
@@ -27,13 +27,13 @@ static NGConstraintSpace ConstructConstraintSpace(
NGLogicalSize size = {LayoutUnit(inline_size), LayoutUnit(block_size)};
return NGConstraintSpaceBuilder(
- writing_mode,
- /* icb_size */ size.ConvertToPhysical(writing_mode))
+ writing_mode, writing_mode,
+ /* is_new_fc */ false)
.SetAvailableSize(size)
.SetPercentageResolutionSize(size)
.SetIsFixedSizeInline(fixed_inline)
.SetIsFixedSizeBlock(fixed_block)
- .ToConstraintSpace(writing_mode);
+ .ToConstraintSpace();
}
class NGLengthUtilsTest : public testing::Test {
@@ -105,7 +105,7 @@ TEST_F(NGLengthUtilsTest, testResolveInlineLength) {
ResolveInlineLength(Length(30, kPercent), LengthResolveType::kMaxSize,
LengthResolvePhase::kIntrinsic));
EXPECT_EQ(
- LayoutUnit(200),
+ LayoutUnit::Max(),
ResolveInlineLength(Length(kFillAvailable), LengthResolveType::kMaxSize,
LengthResolvePhase::kIntrinsic));
MinMaxSize sizes;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_link.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_link.h
index 8d67c7e247c..089992de2ae 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_link.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_link.h
@@ -12,6 +12,21 @@
namespace blink {
+// We use this struct to store NGLinks in a flexible array in fragments. We have
+// to use this struct instead of using NGLink because flexible array members
+// cannot have destructors, so we need to do manual refcounting.
+struct NGLinkStorage {
+ NGPhysicalOffset Offset() const { return offset; }
+ const NGPhysicalFragment* get() const { return fragment; }
+
+ operator bool() const { return fragment; }
+ const NGPhysicalFragment& operator*() const { return *fragment; }
+ const NGPhysicalFragment* operator->() const { return fragment; }
+
+ const NGPhysicalFragment* fragment;
+ NGPhysicalOffset offset;
+};
+
// Class representing the offset of a child fragment relative to the
// parent fragment. Fragments themselves have no position information
// allowing entire fragment subtrees to be reused and cached regardless
@@ -26,6 +41,8 @@ class CORE_EXPORT NGLink {
: fragment_(std::move(fragment)), offset_(offset) {}
NGLink(NGLink&& o) noexcept
: fragment_(std::move(o.fragment_)), offset_(o.offset_) {}
+ NGLink(const NGLinkStorage& storage)
+ : fragment_(storage.fragment), offset_(storage.offset) {}
~NGLink() = default;
NGLink(const NGLink&) = default;
NGLink& operator=(const NGLink&) = default;
@@ -46,8 +63,6 @@ class CORE_EXPORT NGLink {
// The builder classes needs to set the offset_ field during
// fragment construciton to allow the child vector to be moved
// instead of reconstructed during fragment construction.
- friend class NGFragmentBuilder;
- friend class NGLineBoxFragmentBuilder;
friend class NGLayoutResult;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc
index 20fd62a50a6..6a8ee5eaedd 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc
@@ -10,9 +10,9 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.h"
@@ -22,30 +22,36 @@
namespace blink {
NGOutOfFlowLayoutPart::NGOutOfFlowLayoutPart(
- NGFragmentBuilder* container_builder,
+ NGBoxFragmentBuilder* container_builder,
bool contains_absolute,
bool contains_fixed,
const NGBoxStrut& borders_and_scrollers,
const NGConstraintSpace& container_space,
- const ComputedStyle& container_style)
+ const ComputedStyle& container_style,
+ base::Optional<NGLogicalSize> initial_containing_block_fixed_size)
: container_builder_(container_builder),
contains_absolute_(contains_absolute),
contains_fixed_(contains_fixed) {
+ if (!container_builder->HasOutOfFlowDescendantCandidates())
+ return;
NGPhysicalBoxStrut physical_borders = borders_and_scrollers.ConvertToPhysical(
container_style.GetWritingMode(), container_style.Direction());
- icb_size_ = container_space.InitialContainingBlockSize();
-
default_containing_block_.style = &container_style;
- default_containing_block_.content_size = container_builder_->Size();
- default_containing_block_.content_size.inline_size =
- std::max(default_containing_block_.content_size.inline_size -
+ default_containing_block_.content_size_for_absolute =
+ container_builder_->Size();
+ default_containing_block_.content_size_for_absolute.inline_size =
+ std::max(default_containing_block_.content_size_for_absolute.inline_size -
borders_and_scrollers.InlineSum(),
LayoutUnit());
- default_containing_block_.content_size.block_size =
- std::max(default_containing_block_.content_size.block_size -
+ default_containing_block_.content_size_for_absolute.block_size =
+ std::max(default_containing_block_.content_size_for_absolute.block_size -
borders_and_scrollers.BlockSum(),
LayoutUnit());
+ default_containing_block_.content_size_for_fixed =
+ initial_containing_block_fixed_size
+ ? initial_containing_block_fixed_size.value()
+ : default_containing_block_.content_size_for_absolute;
default_containing_block_.content_offset = NGLogicalOffset{
borders_and_scrollers.inline_start, borders_and_scrollers.block_start};
default_containing_block_.content_physical_offset =
@@ -74,7 +80,7 @@ void NGOutOfFlowLayoutPart::Run(LayoutBox* only_layout) {
}
// Sweep any descendants that might have been added.
// This happens when an absolute container has a fixed child.
- descendant_candidates.clear();
+ descendant_candidates.Shrink(0);
container_builder_->GetAndClearOutOfFlowDescendantCandidates(
&descendant_candidates, container_builder_->GetLayoutObject());
}
@@ -94,13 +100,13 @@ NGOutOfFlowLayoutPart::GetContainingBlockInfo(
void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
Vector<NGOutOfFlowPositionedDescendant> descendants) {
- HashMap<const LayoutObject*, NGFragmentBuilder::FragmentPair>
+ HashMap<const LayoutObject*, NGBoxFragmentBuilder::FragmentPair>
inline_container_fragments;
for (auto& descendant : descendants) {
if (descendant.inline_container &&
!inline_container_fragments.Contains(descendant.inline_container)) {
- NGFragmentBuilder::FragmentPair fragment_pair = {};
+ NGBoxFragmentBuilder::FragmentPair fragment_pair = {};
inline_container_fragments.insert(descendant.inline_container,
fragment_pair);
}
@@ -110,8 +116,8 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
container_builder_->ComputeInlineContainerFragments(
&inline_container_fragments, &container_builder_size);
NGPhysicalSize container_builder_physical_size =
- container_builder_size.ConvertToPhysical(
- default_containing_block_.style->GetWritingMode());
+ ToNGPhysicalSize(container_builder_size,
+ default_containing_block_.style->GetWritingMode());
// Translate start/end fragments into ContainingBlockInfo.
for (auto& block_info : inline_container_fragments) {
// Variables needed to describe ContainingBlockInfo
@@ -133,8 +139,11 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
} else {
inline_cb_style = &block_info.value.start_fragment->Style();
NGConstraintSpace dummy_constraint_space =
- NGConstraintSpaceBuilder(inline_cb_style->GetWritingMode(), icb_size_)
- .ToConstraintSpace(inline_cb_style->GetWritingMode());
+ NGConstraintSpaceBuilder(inline_cb_style->GetWritingMode(),
+ inline_cb_style->GetWritingMode(),
+ /* is_new_fc */ false)
+ .ToConstraintSpace();
+
// TODO Creating dummy constraint space just to get borders feels wrong.
NGBoxStrut inline_cb_borders =
ComputeBorders(dummy_constraint_space, *inline_cb_style);
@@ -198,11 +207,6 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
start_fragment_logical_offset.ConvertToPhysical(
container_writing_mode, container_direction,
start_linebox_fragment->Size(), NGPhysicalSize());
- NGPhysicalOffset start_linebox_physical_offset =
- block_info.value.start_linebox_offset.ConvertToPhysical(
- container_writing_mode, container_direction,
- container_builder_physical_size, start_linebox_fragment->Size());
- start_fragment_physical_offset += start_linebox_physical_offset;
// Step 2
const NGPhysicalLineBoxFragment* end_linebox_fragment =
block_info.value.end_linebox_fragment;
@@ -227,11 +231,6 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
end_fragment_bottom_right.ConvertToPhysical(
container_writing_mode, container_direction,
end_linebox_fragment->Size(), NGPhysicalSize());
- NGPhysicalOffset end_linebox_physical_offset =
- block_info.value.end_linebox_offset.ConvertToPhysical(
- container_writing_mode, container_direction,
- container_builder_physical_size, end_linebox_fragment->Size());
- end_fragment_physical_offset += end_linebox_physical_offset;
// Step 3
NGLogicalOffset start_fragment_logical_offset_wrt_box =
start_fragment_physical_offset.ConvertToLogical(
@@ -276,10 +275,11 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
default_container_offset += inline_cb_borders.StartOffset();
}
containing_blocks_map_.insert(
- block_info.key, ContainingBlockInfo{inline_cb_style, inline_cb_size,
- inline_content_offset,
- inline_content_physical_offset,
- default_container_offset});
+ block_info.key,
+ ContainingBlockInfo{inline_cb_style, inline_cb_size, inline_cb_size,
+ inline_content_offset,
+ inline_content_physical_offset,
+ default_container_offset});
}
}
@@ -300,8 +300,9 @@ scoped_refptr<NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
// and default_container border width.
NGStaticPosition static_position(descendant.static_position);
NGPhysicalSize default_containing_block_physical_size =
- default_containing_block_.content_size.ConvertToPhysical(
- default_containing_block_.style->GetWritingMode());
+ ToNGPhysicalSize(default_containing_block_.ContentSize(
+ descendant.node.Style().GetPosition()),
+ default_containing_block_.style->GetWritingMode());
NGPhysicalOffset default_container_physical_offset =
container_info.default_container_offset.ConvertToPhysical(
default_containing_block_.style->GetWritingMode(),
@@ -313,13 +314,16 @@ scoped_refptr<NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
default_containing_block_.content_physical_offset -
default_container_physical_offset;
+ NGLogicalSize container_content_size =
+ container_info.ContentSize(descendant.node.Style().GetPosition());
// The block estimate is in the descendant's writing mode.
NGConstraintSpace descendant_constraint_space =
- NGConstraintSpaceBuilder(container_writing_mode, icb_size_)
+ NGConstraintSpaceBuilder(container_writing_mode, descendant_writing_mode,
+ /* is_new_fc */ true)
.SetTextDirection(container_info.style->Direction())
- .SetAvailableSize(container_info.content_size)
- .SetPercentageResolutionSize(container_info.content_size)
- .ToConstraintSpace(descendant_writing_mode);
+ .SetAvailableSize(container_content_size)
+ .SetPercentageResolutionSize(container_content_size)
+ .ToConstraintSpace();
base::Optional<MinMaxSize> min_max_size;
base::Optional<LayoutUnit> block_estimate;
@@ -362,7 +366,7 @@ scoped_refptr<NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
layout_result = GenerateFragment(descendant.node, container_info,
block_estimate, node_position);
- DCHECK(layout_result->PhysicalFragment().get());
+ DCHECK(layout_result->PhysicalFragment());
NGFragment fragment(descendant_writing_mode,
*layout_result->PhysicalFragment());
@@ -439,8 +443,9 @@ scoped_refptr<NGLayoutResult> NGOutOfFlowLayoutPart::GenerateFragment(
// the constraint space in the descendant's writing mode.
WritingMode writing_mode(descendant.Style().GetWritingMode());
NGLogicalSize container_size(
- container_info.content_size
- .ConvertToPhysical(default_containing_block_.style->GetWritingMode())
+ ToNGPhysicalSize(
+ container_info.ContentSize(descendant.Style().GetPosition()),
+ default_containing_block_.style->GetWritingMode())
.ConvertToLogical(writing_mode));
LayoutUnit inline_size =
@@ -451,15 +456,15 @@ scoped_refptr<NGLayoutResult> NGOutOfFlowLayoutPart::GenerateFragment(
NGLogicalSize available_size{inline_size, block_size};
// TODO(atotic) will need to be adjusted for scrollbars.
- NGConstraintSpaceBuilder builder(writing_mode, icb_size_);
+ NGConstraintSpaceBuilder builder(writing_mode, writing_mode,
+ /* is_new_fc */ true);
builder.SetAvailableSize(available_size)
.SetTextDirection(descendant.Style().Direction())
.SetPercentageResolutionSize(container_size)
- .SetIsNewFormattingContext(true)
.SetIsFixedSizeInline(true);
if (block_estimate)
builder.SetIsFixedSizeBlock(true);
- NGConstraintSpace space = builder.ToConstraintSpace(writing_mode);
+ NGConstraintSpace space = builder.ToConstraintSpace();
scoped_refptr<NGLayoutResult> result = descendant.Layout(space);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h
index 49b8ffb4023..caa039058f4 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h
@@ -10,6 +10,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h"
#include "third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h"
+#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
@@ -18,14 +19,14 @@ class ComputedStyle;
class LayoutBox;
class LayoutObject;
class NGBlockNode;
-class NGFragmentBuilder;
+class NGBoxFragmentBuilder;
class NGConstraintSpace;
class NGLayoutResult;
struct NGOutOfFlowPositionedDescendant;
// Helper class for positioning of out-of-flow blocks.
-// It should be used together with NGFragmentBuilder.
-// See NGFragmentBuilder::AddOutOfFlowChildCandidate documentation
+// It should be used together with NGBoxFragmentBuilder.
+// See NGBoxFragmentBuilder::AddOutOfFlowChildCandidate documentation
// for example of using these classes together.
class CORE_EXPORT NGOutOfFlowLayoutPart {
STACK_ALLOCATED();
@@ -37,12 +38,15 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
// block" of such an out-of-flow positioned descendant isn't a true block (but
// e.g. a relatively positioned inline instead), the containing block here is
// the containing block of said non-block.
- NGOutOfFlowLayoutPart(NGFragmentBuilder* container_builder,
- bool contains_absolute,
- bool contains_fixed,
- const NGBoxStrut& borders_and_scrollers,
- const NGConstraintSpace& container_space,
- const ComputedStyle& container_style);
+ NGOutOfFlowLayoutPart(
+ NGBoxFragmentBuilder* container_builder,
+ bool contains_absolute,
+ bool contains_fixed,
+ const NGBoxStrut& borders_and_scrollers,
+ const NGConstraintSpace& container_space,
+ const ComputedStyle& container_style,
+ base::Optional<NGLogicalSize> initial_containing_block_fixed_size =
+ base::nullopt);
// Normally this function lays out and positions all out-of-flow objects
// from the container_builder and additional ones it discovers through laying
@@ -70,7 +74,9 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
// Containing block style.
const ComputedStyle* style;
// Logical in containing block coordinates.
- NGLogicalSize content_size;
+ NGLogicalSize content_size_for_absolute;
+ // Content size for fixed is different for icb
+ NGLogicalSize content_size_for_fixed;
// Content offset wrt border box.
NGLogicalOffset content_offset;
// Physical content offset wrt border box.
@@ -78,6 +84,11 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
// Logical offset of container padding box
// wrt default containing block padding box.
NGLogicalOffset default_container_offset;
+
+ NGLogicalSize ContentSize(EPosition position) const {
+ return position == EPosition::kAbsolute ? content_size_for_absolute
+ : content_size_for_fixed;
+ }
};
ContainingBlockInfo GetContainingBlockInfo(
@@ -98,10 +109,9 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
const base::Optional<LayoutUnit>& block_estimate,
const NGAbsolutePhysicalPosition& node_position);
- NGFragmentBuilder* container_builder_;
+ NGBoxFragmentBuilder* container_builder_;
bool contains_absolute_;
bool contains_fixed_;
- NGPhysicalSize icb_size_;
ContainingBlockInfo default_containing_block_;
HashMap<const LayoutObject*, ContainingBlockInfo> containing_blocks_map_;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc
index 78847173228..21f09278232 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc
@@ -19,7 +19,9 @@ namespace blink {
NGPageLayoutAlgorithm::NGPageLayoutAlgorithm(NGBlockNode node,
const NGConstraintSpace& space,
const NGBreakToken* break_token)
- : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {}
+ : NGLayoutAlgorithm(node, space, ToNGBlockBreakToken(break_token)) {
+ container_builder_.SetIsNewFormattingContext(space.IsNewFormattingContext());
+}
scoped_refptr<NGLayoutResult> NGPageLayoutAlgorithm::Layout() {
NGBoxStrut borders = ComputeBorders(ConstraintSpace(), Node());
@@ -52,8 +54,8 @@ scoped_refptr<NGLayoutResult> NGPageLayoutAlgorithm::Layout() {
NGBlockLayoutAlgorithm child_algorithm(Node(), child_space,
break_token.get());
scoped_refptr<NGLayoutResult> result = child_algorithm.Layout();
- scoped_refptr<const NGPhysicalBoxFragment> page(
- ToNGPhysicalBoxFragment(result->PhysicalFragment().get()));
+ const NGPhysicalBoxFragment* page =
+ ToNGPhysicalBoxFragment(result->PhysicalFragment());
container_builder_.AddChild(*result, page_offset);
@@ -93,25 +95,21 @@ base::Optional<MinMaxSize> NGPageLayoutAlgorithm::ComputeMinMaxSize(
NGConstraintSpace NGPageLayoutAlgorithm::CreateConstraintSpaceForPages(
const NGLogicalSize& page_size) const {
- NGConstraintSpaceBuilder space_builder(ConstraintSpace());
+ NGConstraintSpaceBuilder space_builder(
+ ConstraintSpace(), Style().GetWritingMode(), /* is_new_fc */ true);
space_builder.SetAvailableSize(page_size);
space_builder.SetPercentageResolutionSize(page_size);
if (NGBaseline::ShouldPropagateBaselines(Node()))
space_builder.AddBaselineRequests(ConstraintSpace().BaselineRequests());
- // TODO(mstensho): Handle auto block size. For now just disable fragmentation
- // if block size is auto. With the current approach, we'll just end up with
- // one tall page. This is only correct if there are no explicit page breaks.
- if (page_size.block_size != NGSizeIndefinite) {
- space_builder.SetFragmentationType(kFragmentPage);
- space_builder.SetFragmentainerBlockSize(page_size.block_size);
- space_builder.SetFragmentainerSpaceAtBfcStart(page_size.block_size);
- }
- space_builder.SetIsNewFormattingContext(true);
+ // TODO(mstensho): Handle auto block size.
+ space_builder.SetFragmentationType(kFragmentPage);
+ space_builder.SetFragmentainerBlockSize(page_size.block_size);
+ space_builder.SetFragmentainerSpaceAtBfcStart(page_size.block_size);
space_builder.SetIsAnonymous(true);
- return space_builder.ToConstraintSpace(Style().GetWritingMode());
+ return space_builder.ToConstraintSpace();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h
index 2b5b088178e..8ad62b50009 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
namespace blink {
@@ -19,7 +19,7 @@ struct NGLogicalSize;
class CORE_EXPORT NGPageLayoutAlgorithm
: public NGLayoutAlgorithm<NGBlockNode,
- NGFragmentBuilder,
+ NGBoxFragmentBuilder,
NGBlockBreakToken> {
public:
NGPageLayoutAlgorithm(NGBlockNode node,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
index abb73b5dee1..a9db9c28c9d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
@@ -12,51 +12,61 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_outline_utils.h"
namespace blink {
+namespace {
+
+struct SameSizeAsNGPhysicalBoxFragment : NGPhysicalContainerFragment {
+ NGBaselineList baselines;
+ NGPhysicalBoxStrut box_struts[2];
+};
+
+static_assert(sizeof(NGPhysicalBoxFragment) ==
+ sizeof(SameSizeAsNGPhysicalBoxFragment),
+ "NGPhysicalBoxFragment should stay small");
+
+} // namespace
+
+scoped_refptr<const NGPhysicalBoxFragment> NGPhysicalBoxFragment::Create(
+ NGBoxFragmentBuilder* builder,
+ WritingMode block_or_line_writing_mode) {
+ // We store the children list inline in the fragment as a flexible
+ // array. Therefore, we need to make sure to allocate enough space for
+ // that array here, which requires a manual allocation + placement new.
+ // The initialization of the array is done by NGPhysicalContainerFragment;
+ // we pass the buffer as a constructor argument.
+ void* data = ::WTF::Partitions::FastMalloc(
+ sizeof(NGPhysicalBoxFragment) +
+ builder->children_.size() * sizeof(NGLinkStorage),
+ ::WTF::GetStringWithTypeName<NGPhysicalBoxFragment>());
+ new (data) NGPhysicalBoxFragment(builder, block_or_line_writing_mode);
+ return base::AdoptRef(static_cast<NGPhysicalBoxFragment*>(data));
+}
+
NGPhysicalBoxFragment::NGPhysicalBoxFragment(
- LayoutObject* layout_object,
- const ComputedStyle& style,
- NGStyleVariant style_variant,
- NGPhysicalSize size,
- Vector<NGLink>& children,
- const NGPhysicalBoxStrut& borders,
- const NGPhysicalBoxStrut& padding,
- Vector<NGBaseline>& baselines,
- NGBoxType box_type,
- bool is_fieldset_container,
- bool is_rendered_legend,
- bool is_old_layout_root,
- unsigned border_edges, // NGBorderEdges::Physical
- scoped_refptr<NGBreakToken> break_token)
+ NGBoxFragmentBuilder* builder,
+ WritingMode block_or_line_writing_mode)
: NGPhysicalContainerFragment(
- layout_object,
- style,
- style_variant,
- size,
- is_rendered_legend ? kFragmentRenderedLegend : kFragmentBox,
- box_type,
- children,
- std::move(break_token)),
- baselines_(std::move(baselines)),
- borders_(borders),
- padding_(padding) {
- DCHECK(baselines.IsEmpty()); // Ensure move semantics is used.
- is_fieldset_container_ = is_fieldset_container;
- is_old_layout_root_ = is_old_layout_root;
- border_edge_ = border_edges;
- children_inline_ = layout_object && layout_object->ChildrenInline();
-}
-
-const NGBaseline* NGPhysicalBoxFragment::Baseline(
- const NGBaselineRequest& request) const {
- for (const auto& baseline : baselines_) {
- if (baseline.request == request)
- return &baseline;
- }
- return nullptr;
+ builder,
+ block_or_line_writing_mode,
+ children_,
+ (builder->node_ && builder->node_.IsRenderedLegend())
+ ? kFragmentRenderedLegend
+ : kFragmentBox,
+ builder->BoxType()),
+ baselines_(builder->baselines_),
+ borders_(builder->borders_.ConvertToPhysical(builder->GetWritingMode(),
+ builder->Direction())),
+ padding_(builder->padding_.ConvertToPhysical(builder->GetWritingMode(),
+ builder->Direction())) {
+ is_fieldset_container_ = builder->is_fieldset_container_;
+ is_old_layout_root_ = builder->is_old_layout_root_;
+ border_edge_ = builder->border_edges_.ToPhysical(builder->GetWritingMode());
+ children_inline_ =
+ builder->layout_object_ && builder->layout_object_->ChildrenInline();
}
bool NGPhysicalBoxFragment::HasSelfPaintingLayer() const {
@@ -150,7 +160,6 @@ NGPhysicalOffsetRect NGPhysicalBoxFragment::SelfInkOverflow() const {
ink_overflow.Unite(rect);
}
}
- ink_overflow.Unite(descendant_outlines_.ToLayoutRect());
return NGPhysicalOffsetRect(ink_overflow);
}
@@ -182,6 +191,10 @@ void NGPhysicalBoxFragment::AddSelfOutlineRects(
}
LayoutSize corrected_offset = additional_offset - first_fragment_offset;
for (auto& outline : blockflow_outline_rects) {
+ // Skip if both width and height are zero. Contaning blocks in empty
+ // linebox is one such case.
+ if (outline.Size().IsZero())
+ continue;
if (UNLIKELY(block_for_flipping))
block_for_flipping->FlipForWritingMode(outline);
outline.Move(corrected_offset);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h
index 6861243eeee..9eaf65e692e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h
@@ -13,27 +13,28 @@
namespace blink {
+class NGBoxFragmentBuilder;
enum class NGOutlineType;
+
class CORE_EXPORT NGPhysicalBoxFragment final
: public NGPhysicalContainerFragment {
public:
- // This modifies the passed-in children vector.
- NGPhysicalBoxFragment(LayoutObject* layout_object,
- const ComputedStyle& style,
- NGStyleVariant style_variant,
- NGPhysicalSize size,
- Vector<NGLink>& children,
- const NGPhysicalBoxStrut& border,
- const NGPhysicalBoxStrut& padding,
- Vector<NGBaseline>& baselines,
- NGBoxType box_type,
- bool is_fieldset_container,
- bool is_rendered_legend,
- bool is_old_layout_root,
- unsigned, // NGBorderEdges::Physical
- scoped_refptr<NGBreakToken> break_token = nullptr);
-
- const NGBaseline* Baseline(const NGBaselineRequest&) const;
+ static scoped_refptr<const NGPhysicalBoxFragment> Create(
+ NGBoxFragmentBuilder* builder,
+ WritingMode block_or_line_writing_mode);
+
+ ~NGPhysicalBoxFragment() {
+ for (const NGLinkStorage& child : Children())
+ child.fragment->Release();
+ }
+
+ ChildLinkList Children() const final {
+ return ChildLinkList(num_children_, &children_[0]);
+ }
+
+ base::Optional<LayoutUnit> Baseline(const NGBaselineRequest& request) const {
+ return baselines_.Offset(request);
+ }
const NGPhysicalBoxStrut Borders() const { return borders_; }
@@ -81,15 +82,18 @@ class CORE_EXPORT NGPhysicalBoxFragment final
const LayoutPoint& additional_offset,
NGOutlineType include_block_overflows) const;
- UBiDiLevel BidiLevel() const override;
+ UBiDiLevel BidiLevel() const;
scoped_refptr<const NGPhysicalFragment> CloneWithoutOffset() const;
private:
- Vector<NGBaseline> baselines_;
+ NGPhysicalBoxFragment(NGBoxFragmentBuilder* builder,
+ WritingMode block_or_line_writing_mode);
+
+ NGBaselineList baselines_;
NGPhysicalBoxStrut borders_;
NGPhysicalBoxStrut padding_;
- NGPhysicalOffsetRect descendant_outlines_;
+ NGLinkStorage children_[];
};
DEFINE_TYPE_CASTS(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc
index 35500173a50..c0f2b6c4206 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc
@@ -7,30 +7,47 @@
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_outline_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
namespace blink {
+namespace {
+
+struct SameSizeAsNGPhysicalContainerFragment : NGPhysicalFragment {
+ wtf_size_t size;
+ void* pointer;
+};
+
+static_assert(sizeof(NGPhysicalContainerFragment) ==
+ sizeof(SameSizeAsNGPhysicalContainerFragment),
+ "NGPhysicalContainerFragment should stay small");
+
+} // namespace
+
NGPhysicalContainerFragment::NGPhysicalContainerFragment(
- LayoutObject* layout_object,
- const ComputedStyle& style,
- NGStyleVariant style_variant,
- NGPhysicalSize size,
+ NGContainerFragmentBuilder* builder,
+ WritingMode block_or_line_writing_mode,
+ NGLinkStorage* buffer,
NGFragmentType type,
- unsigned sub_type,
- Vector<NGLink>& children,
- scoped_refptr<NGBreakToken> break_token)
- : NGPhysicalFragment(layout_object,
- style,
- style_variant,
- size,
- type,
- sub_type,
- std::move(break_token)),
- children_(std::move(children)) {
- DCHECK(children.IsEmpty()); // Ensure move semantics is used.
+ unsigned sub_type)
+ : NGPhysicalFragment(builder, type, sub_type),
+ num_children_(builder->children_.size()) {
+ DCHECK_EQ(builder->children_.size(), builder->offsets_.size());
+ // Because flexible arrays need to be the last member in a class, we need to
+ // have the buffer passed as a constructor argument and have the actual
+ // storage be part of the subclass.
+ wtf_size_t i = 0;
+ for (auto& child : builder->children_) {
+ buffer[i].fragment = child.get();
+ buffer[i].fragment->AddRef();
+ buffer[i].offset = builder->offsets_[i].ConvertToPhysical(
+ block_or_line_writing_mode, builder->Direction(), Size(),
+ child->Size());
+ ++i;
+ }
}
void NGPhysicalContainerFragment::AddOutlineRectsForNormalChildren(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h
index 207035eed86..9ef9a353063 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h
@@ -13,11 +13,34 @@
namespace blink {
+class NGContainerFragmentBuilder;
enum class NGOutlineType;
class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
public:
- const Vector<NGLink>& Children() const { return children_; }
+ class ChildLinkList {
+ public:
+ ChildLinkList(wtf_size_t count, const NGLinkStorage* buffer)
+ : count_(count), buffer_(buffer) {}
+
+ wtf_size_t size() const { return count_; }
+ const NGLinkStorage& operator[](wtf_size_t idx) const {
+ return buffer_[idx];
+ }
+ const NGLinkStorage& front() const { return buffer_[0]; }
+ const NGLinkStorage& back() const { return buffer_[count_ - 1]; }
+
+ const NGLinkStorage* begin() const { return buffer_; }
+ const NGLinkStorage* end() const { return begin() + count_; }
+
+ bool IsEmpty() const { return count_ == 0; }
+
+ private:
+ wtf_size_t count_;
+ const NGLinkStorage* buffer_;
+ };
+
+ virtual ChildLinkList Children() const = 0;
void AddOutlineRectsForNormalChildren(Vector<LayoutRect>* outline_rects,
const LayoutPoint& additional_offset,
@@ -28,17 +51,14 @@ class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
NGOutlineType outline_type) const;
protected:
- // This modifies the passed-in children vector.
- NGPhysicalContainerFragment(LayoutObject*,
- const ComputedStyle&,
- NGStyleVariant,
- NGPhysicalSize,
+ // block_or_line_writing_mode is used for converting the child offsets.
+ NGPhysicalContainerFragment(NGContainerFragmentBuilder*,
+ WritingMode block_or_line_writing_mode,
+ NGLinkStorage* buffer,
NGFragmentType,
- unsigned sub_type,
- Vector<NGLink>& children,
- scoped_refptr<NGBreakToken> = nullptr);
+ unsigned sub_type);
- Vector<NGLink> children_;
+ wtf_size_t num_children_;
};
DEFINE_TYPE_CASTS(NGPhysicalContainerFragment,
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc
index 8e9f15743b0..7b36ae549e1 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc
@@ -12,13 +12,26 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_break_token.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
namespace {
+struct SameSizeAsNGPhysicalFragment
+ : RefCounted<const NGPhysicalFragment, NGPhysicalFragmentTraits> {
+ void* pointers[2];
+ NGPhysicalSize size;
+ unsigned flags;
+};
+
+static_assert(sizeof(NGPhysicalFragment) ==
+ sizeof(SameSizeAsNGPhysicalFragment),
+ "NGPhysicalFragment should stay small");
+
bool AppendFragmentOffsetAndSize(
const NGPhysicalFragment* fragment,
base::Optional<NGPhysicalOffset> fragment_offset,
@@ -163,10 +176,9 @@ void AppendFragmentToString(const NGPhysicalFragment* fragment,
builder->Append("\n");
if (flags & NGPhysicalFragment::DumpSubtree) {
- const auto& children = box->Children();
- for (unsigned i = 0; i < children.size(); i++) {
- AppendFragmentToString(children[i].get(), children[i].Offset(), builder,
- flags, indent + 2);
+ for (auto& child : box->Children()) {
+ AppendFragmentToString(child.get(), child.Offset(), builder, flags,
+ indent + 2);
}
}
return;
@@ -183,10 +195,9 @@ void AppendFragmentToString(const NGPhysicalFragment* fragment,
if (flags & NGPhysicalFragment::DumpSubtree) {
const auto* line_box = ToNGPhysicalLineBoxFragment(fragment);
- const auto& children = line_box->Children();
- for (unsigned i = 0; i < children.size(); i++) {
- AppendFragmentToString(children[i].get(), children[i].Offset(), builder,
- flags, indent + 2);
+ for (auto& child : line_box->Children()) {
+ AppendFragmentToString(child.get(), child.Offset(), builder, flags,
+ indent + 2);
}
return;
}
@@ -234,22 +245,32 @@ void NGPhysicalFragmentTraits::Destruct(const NGPhysicalFragment* fragment) {
fragment->Destroy();
}
+NGPhysicalFragment::NGPhysicalFragment(NGFragmentBuilder* builder,
+ NGFragmentType type,
+ unsigned sub_type)
+ : layout_object_(builder->layout_object_),
+ size_(ToNGPhysicalSize(builder->size_, builder->GetWritingMode())),
+ break_token_(std::move(builder->break_token_)),
+ type_(type),
+ sub_type_(sub_type),
+ style_variant_((unsigned)builder->style_variant_),
+ is_fieldset_container_(false),
+ is_old_layout_root_(false) {}
+
NGPhysicalFragment::NGPhysicalFragment(LayoutObject* layout_object,
- const ComputedStyle& style,
NGStyleVariant style_variant,
NGPhysicalSize size,
NGFragmentType type,
unsigned sub_type,
scoped_refptr<NGBreakToken> break_token)
: layout_object_(layout_object),
- style_(&style),
size_(size),
break_token_(std::move(break_token)),
type_(type),
sub_type_(sub_type),
+ style_variant_((unsigned)style_variant),
is_fieldset_container_(false),
- is_old_layout_root_(false),
- style_variant_((unsigned)style_variant) {}
+ is_old_layout_root_(false) {}
// Keep the implementation of the destructor here, to avoid dependencies on
// ComputedStyle in the header file.
@@ -274,21 +295,20 @@ void NGPhysicalFragment::Destroy() const {
}
const ComputedStyle& NGPhysicalFragment::Style() const {
- DCHECK(style_);
- // TODO(kojii): Returning |style_| locks the style at the layout time, and
- // will not be updated when its base style is updated later. Line styles and
- // ellipsis styles have this problem.
- if (!GetLayoutObject())
- return *style_;
+ if (Type() == kFragmentLineBox)
+ return ToNGPhysicalLineBoxFragment(this)->Style();
switch (StyleVariant()) {
case NGStyleVariant::kStandard:
+ DCHECK(GetLayoutObject());
return *GetLayoutObject()->Style();
case NGStyleVariant::kFirstLine:
+ DCHECK(GetLayoutObject());
return *GetLayoutObject()->FirstLineStyle();
case NGStyleVariant::kEllipsis:
- return *style_;
+ return ToNGPhysicalTextFragment(this)->Style();
}
- return *style_;
+ NOTREACHED();
+ return *GetLayoutObject()->Style();
}
Node* NGPhysicalFragment::GetNode() const {
@@ -400,8 +420,7 @@ const Vector<NGInlineItem>& NGPhysicalFragment::InlineItemsOfContainingBlock()
const {
DCHECK(IsInline());
DCHECK(GetLayoutObject());
- LayoutBlockFlow* block_flow =
- GetLayoutObject()->Parent()->EnclosingNGBlockFlow();
+ LayoutBlockFlow* block_flow = GetLayoutObject()->ContainingNGBlockFlow();
// TODO(xiaochengh): Code below is copied from ng_offset_mapping.cc with
// modification. Unify them.
DCHECK(block_flow);
@@ -422,15 +441,33 @@ TouchAction NGPhysicalFragment::EffectiveWhitelistedTouchAction() const {
}
UBiDiLevel NGPhysicalFragment::BidiLevel() const {
+ switch (Type()) {
+ case kFragmentText:
+ return ToNGPhysicalTextFragment(*this).BidiLevel();
+ case kFragmentBox:
+ case kFragmentRenderedLegend:
+ return ToNGPhysicalBoxFragment(*this).BidiLevel();
+ case kFragmentLineBox:
+ break;
+ }
NOTREACHED();
return 0;
}
TextDirection NGPhysicalFragment::ResolvedDirection() const {
- DCHECK(IsInline());
- DCHECK(IsText() || IsAtomicInline());
- // TODO(xiaochengh): Store direction in |base_direction_| flag.
- return DirectionFromLevel(BidiLevel());
+ switch (Type()) {
+ case kFragmentText:
+ return ToNGPhysicalTextFragment(*this).ResolvedDirection();
+ case kFragmentBox:
+ case kFragmentRenderedLegend:
+ DCHECK(IsInline() && IsAtomicInline());
+ // TODO(xiaochengh): Store direction in |base_direction_| flag.
+ return DirectionFromLevel(BidiLevel());
+ case kFragmentLineBox:
+ break;
+ }
+ NOTREACHED();
+ return TextDirection::kLtr;
}
String NGPhysicalFragment::ToString() const {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h
index a4e54763454..16ccfd8b8e0 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h
@@ -23,6 +23,7 @@ namespace blink {
class ComputedStyle;
class LayoutObject;
class Node;
+class NGFragmentBuilder;
class NGBreakToken;
class NGInlineItem;
struct NGPixelSnappedPhysicalBoxStrut;
@@ -198,11 +199,11 @@ class CORE_EXPORT NGPhysicalFragment
TouchAction EffectiveWhitelistedTouchAction() const;
// Returns the bidi level of a text or atomic inline fragment.
- virtual UBiDiLevel BidiLevel() const;
+ UBiDiLevel BidiLevel() const;
// Returns the resolved direction of a text or atomic inline fragment. Not to
// be confused with the CSS 'direction' property.
- virtual TextDirection ResolvedDirection() const;
+ TextDirection ResolvedDirection() const;
String ToString() const;
@@ -230,8 +231,11 @@ class CORE_EXPORT NGPhysicalFragment
#endif
protected:
+ NGPhysicalFragment(NGFragmentBuilder*,
+ NGFragmentType type,
+ unsigned sub_type);
+
NGPhysicalFragment(LayoutObject* layout_object,
- const ComputedStyle& style,
NGStyleVariant,
NGPhysicalSize size,
NGFragmentType type,
@@ -241,21 +245,28 @@ class CORE_EXPORT NGPhysicalFragment
const Vector<NGInlineItem>& InlineItemsOfContainingBlock() const;
LayoutObject* const layout_object_;
- scoped_refptr<const ComputedStyle> style_;
const NGPhysicalSize size_;
scoped_refptr<NGBreakToken> break_token_;
const unsigned type_ : 2; // NGFragmentType
- const unsigned sub_type_ : 3; // Union of NGBoxType and NGTextType
- unsigned is_fieldset_container_ : 1;
- unsigned is_old_layout_root_ : 1;
- unsigned border_edge_ : 4; // NGBorderEdges::Physical
+ const unsigned sub_type_ : 3; // NGBoxType, NGTextType, or NGLineBoxType
const unsigned style_variant_ : 2; // NGStyleVariant
- unsigned base_direction_ : 1; // TextDirection, for NGPhysicalLineBoxFragment
+
+ // The following bitfield is only to be used by NGPhysicalLineBoxFragment
+ // (it's defined here to save memory, since that class has no bitfields).
+ unsigned base_direction_ : 1; // TextDirection
// The following bitfield is only to be used by NGPhysicalBoxFragment (it's
// defined here to save memory, since that class has no bitfields).
unsigned children_inline_ : 1;
+ unsigned is_fieldset_container_ : 1;
+ unsigned is_old_layout_root_ : 1;
+ unsigned border_edge_ : 4; // NGBorderEdges::Physical
+
+ // The following bitfield is only to be used by NGPhysicalTextFragment (it's
+ // defined here to save memory, since that class has no bitfields).
+ unsigned line_orientation_ : 2; // NGLineOrientation
+ unsigned is_anonymous_text_ : 1;
private:
friend struct NGPhysicalFragmentTraits;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.cc
deleted file mode 100644
index ef9bec90325..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.cc
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
-
-#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
-
-namespace blink {
-
-NGPositionedFloat::NGPositionedFloat(
- scoped_refptr<NGLayoutResult> layout_result,
- const NGBfcOffset& bfc_offset)
- : layout_result(layout_result), bfc_offset(bfc_offset) {}
-
-// Define the destructor here, so that we can forward-declare more in the header
-// file.
-NGPositionedFloat::~NGPositionedFloat() = default;
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.h
index 99d3164964d..d6d109bee22 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_positioned_float.h
@@ -8,6 +8,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
namespace blink {
@@ -16,8 +17,8 @@ class NGLayoutResult;
// Contains the information necessary for copying back data to a FloatingObject.
struct CORE_EXPORT NGPositionedFloat {
NGPositionedFloat(scoped_refptr<NGLayoutResult> layout_result,
- const NGBfcOffset& bfc_offset);
- ~NGPositionedFloat();
+ const NGBfcOffset& bfc_offset)
+ : layout_result(layout_result), bfc_offset(bfc_offset) {}
NGPositionedFloat(NGPositionedFloat&&) noexcept = default;
NGPositionedFloat(const NGPositionedFloat&) = default;
NGPositionedFloat& operator=(NGPositionedFloat&&) = default;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc
index 9a48401064a..d7b970f29d2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_relative_utils.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_offset.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_physical_size.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc
index f43794da497..8cb6b8f4d29 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc
@@ -7,22 +7,12 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/text/writing_mode.h"
namespace blink {
-bool ShouldShrinkToFit(const ComputedStyle& parent_style,
- const ComputedStyle& style) {
- // Whether the child and the containing block are parallel to each other.
- // Example: vertical-rl and vertical-lr
- bool is_in_parallel_flow = IsParallelWritingMode(
- parent_style.GetWritingMode(), style.GetWritingMode());
-
- return style.Display() == EDisplay::kInlineBlock || style.IsFloating() ||
- !is_in_parallel_flow;
-}
-
bool AdjustToClearance(LayoutUnit clearance_offset, NGBfcOffset* offset) {
DCHECK(offset);
if (clearance_offset > offset->block_offset) {
@@ -33,20 +23,79 @@ bool AdjustToClearance(LayoutUnit clearance_offset, NGBfcOffset* offset) {
return false;
}
-NGConstraintSpace CreateExtrinsicConstraintSpaceForChild(
- const NGConstraintSpace& container_constraint_space,
- LayoutUnit container_extrinsic_block_size,
+NGConstraintSpace CreateIndefiniteConstraintSpaceForChild(
+ const ComputedStyle& container_style,
NGLayoutInputNode child) {
- NGLogicalSize extrinsic_size(NGSizeIndefinite,
- container_extrinsic_block_size);
+ WritingMode parent_writing_mode = container_style.GetWritingMode();
+ WritingMode child_writing_mode = child.Style().GetWritingMode();
+ DCHECK(!IsParallelWritingMode(parent_writing_mode, child_writing_mode));
+
+ NGLogicalSize indefinite_size(NGSizeIndefinite, NGSizeIndefinite);
+ NGConstraintSpaceBuilder builder(parent_writing_mode, child_writing_mode,
+ child.CreatesNewFormattingContext());
+ SetOrthogonalFallbackInlineSizeIfNeeded(container_style, child, &builder);
- return NGConstraintSpaceBuilder(container_constraint_space)
- .SetAvailableSize(extrinsic_size)
- .SetPercentageResolutionSize(extrinsic_size)
+ return builder.SetAvailableSize(indefinite_size)
+ .SetPercentageResolutionSize(indefinite_size)
+ .SetReplacedPercentageResolutionSize(indefinite_size)
.SetIsIntermediateLayout(true)
- .SetIsNewFormattingContext(child.CreatesNewFormattingContext())
.SetFloatsBfcBlockOffset(LayoutUnit())
- .ToConstraintSpace(child.Style().GetWritingMode());
+ .ToConstraintSpace();
+}
+
+void SetOrthogonalFallbackInlineSizeIfNeeded(
+ const ComputedStyle& parent_style,
+ const NGLayoutInputNode child,
+ NGConstraintSpaceBuilder* builder) {
+ if (IsParallelWritingMode(parent_style.GetWritingMode(),
+ child.Style().GetWritingMode()))
+ return;
+
+ NGPhysicalSize orthogonal_children_containing_block_size =
+ child.InitialContainingBlockSize();
+
+ LayoutUnit fallback_size;
+ if (IsHorizontalWritingMode(parent_style.GetWritingMode()))
+ fallback_size = orthogonal_children_containing_block_size.height;
+ else
+ fallback_size = orthogonal_children_containing_block_size.width;
+
+ LayoutUnit size(LayoutUnit::Max());
+ if (parent_style.LogicalHeight().IsFixed()) {
+ // Note that during layout, fixed size will already be taken care of (and
+ // set in the constraint space), but when calculating intrinsic sizes of
+ // orthogonal children, that won't be the case.
+ size = LayoutUnit(parent_style.LogicalHeight().GetFloatValue());
+ }
+ if (parent_style.LogicalMaxHeight().IsFixed()) {
+ size = std::min(
+ size, LayoutUnit(parent_style.LogicalMaxHeight().GetFloatValue()));
+ }
+ if (parent_style.LogicalMinHeight().IsFixed()) {
+ size = std::max(
+ size, LayoutUnit(parent_style.LogicalMinHeight().GetFloatValue()));
+ }
+ // Calculate the content-box size.
+ if (parent_style.BoxSizing() == EBoxSizing::kBorderBox) {
+ // We're unable to resolve percentages at this point, so make sure we're
+ // only dealing with fixed-size values.
+ if (!parent_style.PaddingBefore().IsFixed() ||
+ !parent_style.PaddingAfter().IsFixed()) {
+ builder->SetOrthogonalFallbackInlineSize(fallback_size);
+ return;
+ }
+
+ LayoutUnit border_padding(parent_style.BorderBefore().Width() +
+ parent_style.BorderAfter().Width() +
+ parent_style.PaddingBefore().GetFloatValue() +
+ parent_style.PaddingAfter().GetFloatValue());
+
+ size -= border_padding;
+ size = size.ClampNegativeToZero();
+ }
+
+ fallback_size = std::min(fallback_size, size);
+ builder->SetOrthogonalFallbackInlineSize(fallback_size);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.h
index 66419159309..90f3adb0432 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_space_utils.h
@@ -9,42 +9,39 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
class ComputedStyle;
struct NGBfcOffset;
-// Whether child's constraint space should shrink to its intrinsic width.
-// This is needed for buttons, select, input, floats and orthogonal children.
-// See LayoutBox::sizesLogicalWidthToFitContent for the rationale behind this.
-bool ShouldShrinkToFit(const ComputedStyle& parent_style,
- const ComputedStyle& style);
-
// Adjusts {@code offset} to the clearance line.
CORE_EXPORT bool AdjustToClearance(LayoutUnit clearance_offset,
NGBfcOffset* offset);
-// Create a child constraint space with only extrinsic block sizing data. This
-// will and can not be used for final layout, but is needed in an intermediate
-// measure pass that calculates the min/max size contribution from a child that
-// establishes an orthogonal flow root.
-//
-// Note that it's the child's *block* size that will be propagated as min/max
-// inline size to the container. Therefore it's crucial to provide the child
-// with an available inline size (which can be derived from the block size of
-// the container if definite). We'll provide any extrinsic available block size
-// that we have. This includes fixed and resolvable percentage sizes, for
-// instance, while auto will not resolve. If no extrinsic size can be
-// determined, we will resort to using a fallback later on, such as the initial
-// containing block size. Spec:
-// https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto
-NGConstraintSpace CreateExtrinsicConstraintSpaceForChild(
- const NGConstraintSpace& container_constraint_space,
- LayoutUnit container_extrinsic_block_size,
+// Create a child constraint space with no sizing data, except for fallback
+// inline sizing for orthongonal flow roots. This will not and can not be used
+// for final layout, but is needed in an intermediate measure pass that
+// calculates the min/max size contribution from a child that establishes an
+// orthogonal flow root.
+NGConstraintSpace CreateIndefiniteConstraintSpaceForChild(
+ const ComputedStyle& container_style,
NGLayoutInputNode child);
+// Calculate and set the available inline fallback size for orthogonal flow
+// children. This size will be used if it's not resolvable via other means [1].
+//
+// TODO(mstensho): The spec [1] says to use the size of the nearest scrollport
+// as constraint, if that's smaller than the initial containing block, but we
+// haven't implemented that yet; we always just use the initial containing
+// block size.
+//
+// [1] https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto
+void SetOrthogonalFallbackInlineSizeIfNeeded(const ComputedStyle& parent_style,
+ const NGLayoutInputNode child,
+ NGConstraintSpaceBuilder* builder);
+
} // namespace blink
#endif // NGSpaceUtils_h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc
index f902a9947cf..0446cfb6734 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_text_decoration_offset.cc
@@ -25,9 +25,9 @@ int NGTextDecorationOffset::ComputeUnderlineOffsetForUnder(
NGBaselineAlgorithmType::kAtomicInline,
FontBaseline::kIdeographicBaseline};
- const NGBaseline* baseline = decorating_box_->Baseline(baseline_request);
- if (baseline)
- offset = baseline->offset;
+ if (base::Optional<LayoutUnit> baseline =
+ decorating_box_->Baseline(baseline_request))
+ offset = baseline.value();
}
if (offset == LayoutUnit::Max()) {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.cc
deleted file mode 100644
index 7ebcb521666..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.cc
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
-
-#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
-
-namespace blink {
-
-// Define the constructor and destructor here, so that we can forward-declare
-// more in the header file.
-NGUnpositionedFloat::NGUnpositionedFloat(NGBlockNode node,
- const NGBlockBreakToken* token)
- : node(node), token(token) {}
-
-NGUnpositionedFloat::~NGUnpositionedFloat() = default;
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h
index 08eca9bb0f2..d8181ab8fa2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h
@@ -6,6 +6,7 @@
#define NGUnpositionedFloat_h
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
@@ -20,8 +21,8 @@ struct CORE_EXPORT NGUnpositionedFloat final {
DISALLOW_NEW();
public:
- NGUnpositionedFloat(NGBlockNode node, const NGBlockBreakToken* token);
- ~NGUnpositionedFloat();
+ NGUnpositionedFloat(NGBlockNode node, const NGBlockBreakToken* token)
+ : node(node), token(token) {}
NGUnpositionedFloat(NGUnpositionedFloat&&) noexcept = default;
NGUnpositionedFloat(const NGUnpositionedFloat&) noexcept = default;
@@ -36,9 +37,17 @@ struct CORE_EXPORT NGUnpositionedFloat final {
scoped_refptr<NGLayoutResult> layout_result;
NGBoxStrut margins;
- bool IsLeft() const { return node.Style().Floating() == EFloat::kLeft; }
- bool IsRight() const { return node.Style().Floating() == EFloat::kRight; }
- EClear ClearType() const { return node.Style().Clear(); }
+ bool IsLineLeft(TextDirection direction) const {
+ return ResolvedFloating(node.Style().Floating(), direction) ==
+ EFloat::kLeft;
+ }
+ bool IsLineRight(TextDirection direction) const {
+ return ResolvedFloating(node.Style().Floating(), direction) ==
+ EFloat::kRight;
+ }
+ EClear ClearType(TextDirection direction) const {
+ return ResolvedClear(node.Style().Clear(), direction);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.cc b/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.cc
index de77d9801bd..adb53d3b726 100644
--- a/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.cc
+++ b/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.cc
@@ -48,7 +48,7 @@ PointerEventsHitRules::PointerEventsHitRules(EHitTesting hit_testing,
case EPointerEvents::kBoundingBox:
can_hit_bounding_box = true;
break;
- case EPointerEvents::kVisiblePainted:
+ case EPointerEvents::kVisiblepainted:
case EPointerEvents::kAuto: // "auto" is like "visiblePainted" when in
// SVG content
require_fill = true;
@@ -59,11 +59,11 @@ PointerEventsHitRules::PointerEventsHitRules(EHitTesting hit_testing,
can_hit_fill = true;
can_hit_stroke = true;
break;
- case EPointerEvents::kVisibleFill:
+ case EPointerEvents::kVisiblefill:
require_visible = true;
can_hit_fill = true;
break;
- case EPointerEvents::kVisibleStroke:
+ case EPointerEvents::kVisiblestroke:
require_visible = true;
can_hit_stroke = true;
break;
@@ -90,7 +90,7 @@ PointerEventsHitRules::PointerEventsHitRules(EHitTesting hit_testing,
case EPointerEvents::kBoundingBox:
can_hit_bounding_box = true;
break;
- case EPointerEvents::kVisiblePainted:
+ case EPointerEvents::kVisiblepainted:
case EPointerEvents::kAuto: // "auto" is like "visiblePainted" when in
// SVG content
require_visible = true;
@@ -99,8 +99,8 @@ PointerEventsHitRules::PointerEventsHitRules(EHitTesting hit_testing,
can_hit_fill = true;
can_hit_stroke = true;
break;
- case EPointerEvents::kVisibleFill:
- case EPointerEvents::kVisibleStroke:
+ case EPointerEvents::kVisiblefill:
+ case EPointerEvents::kVisiblestroke:
case EPointerEvents::kVisible:
require_visible = true;
can_hit_fill = true;
diff --git a/chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc b/chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc
index a1ed2381322..eb20ced2fae 100644
--- a/chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc
+++ b/chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc
@@ -153,14 +153,14 @@ static const AtomicString UniqueClassnameAmongSiblings(Element* element) {
*sibling_element->ToNode())) {
if (sibling_element->HasClass() && sibling_element != element) {
const SpaceSplitString& class_names = sibling_element->ClassNames();
- for (size_t i = 0; i < class_names.size(); ++i) {
+ for (wtf_size_t i = 0; i < class_names.size(); ++i) {
classname_filter->Add(class_names[i]);
}
}
}
const SpaceSplitString& class_names = element->ClassNames();
- for (size_t i = 0; i < class_names.size(); ++i) {
+ for (wtf_size_t i = 0; i < class_names.size(); ++i) {
// MayContain allows for false positives, but a false positive is relatively
// harmless; it just means we have to choose a different classname, or in
// the worst case a different selector.
diff --git a/chromium/third_party/blink/renderer/core/layout/scroll_anchor_test.cc b/chromium/third_party/blink/renderer/core/layout/scroll_anchor_test.cc
index 95aacabe817..546e97c8e2d 100644
--- a/chromium/third_party/blink/renderer/core/layout/scroll_anchor_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/scroll_anchor_test.cc
@@ -29,7 +29,7 @@ class ScrollAnchorTest : public testing::WithParamInterface<bool>,
void Update() {
// TODO(skobes): Use SimTest instead of RenderingTest and move into
// Source/web?
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
ScrollableArea* LayoutViewport() {
@@ -51,7 +51,7 @@ class ScrollAnchorTest : public testing::WithParamInterface<bool>,
}
void SetHeight(Element* element, int height) {
- element->setAttribute(HTMLNames::styleAttr,
+ element->setAttribute(html_names::kStyleAttr,
AtomicString(String::Format("height: %dpx", height)));
Update();
}
@@ -268,7 +268,7 @@ TEST_P(ScrollAnchorTest, FractionalOffsetsAreRoundedBeforeComparing) {
ScrollableArea* viewport = LayoutViewport();
ScrollLayoutViewport(ScrollOffset(0, 100));
- GetDocument().getElementById("block1")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("block1")->setAttribute(html_names::kStyleAttr,
"height: 50.6px");
Update();
@@ -286,7 +286,7 @@ TEST_P(ScrollAnchorTest, AvoidStickyAnchorWhichMovesWithScroll) {
ScrollableArea* viewport = LayoutViewport();
ScrollLayoutViewport(ScrollOffset(0, 60));
- GetDocument().getElementById("block1")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("block1")->setAttribute(html_names::kStyleAttr,
"height: 100px");
Update();
@@ -427,7 +427,7 @@ TEST_P(ScrollAnchorTest, FlexboxDelayedAdjustmentRespectsSANACLAP) {
Element* scroller = GetDocument().getElementById("scroller");
scroller->setScrollTop(100);
- GetDocument().getElementById("spacer")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("spacer")->setAttribute(html_names::kStyleAttr,
"margin-top: 50px");
Update();
EXPECT_EQ(100, ScrollerForElement(scroller)->ScrollOffsetInt().Height());
@@ -436,10 +436,6 @@ TEST_P(ScrollAnchorTest, FlexboxDelayedAdjustmentRespectsSANACLAP) {
// TODO(skobes): Convert this to web-platform-tests when document.rootScroller
// is launched (http://crbug.com/505516).
TEST_P(ScrollAnchorTest, NonDefaultRootScroller) {
- // TODO(crbug.com/889449): The test fails in LayoutNG mode.
- if (RuntimeEnabledFeatures::LayoutNGEnabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<style>
::-webkit-scrollbar {
@@ -470,7 +466,7 @@ TEST_P(ScrollAnchorTest, NonDefaultRootScroller) {
NonThrowableExceptionState non_throw;
GetDocument().setRootScroller(root_scroller_element, non_throw);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ScrollableArea* scroller = ScrollerForElement(root_scroller_element);
diff --git a/chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc b/chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc
index 7a0d0cd7c0e..e26fe4bafb0 100644
--- a/chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc
@@ -35,7 +35,7 @@ namespace {
class ScrollbarsTest : public SimTest {
public:
HitTestResult HitTest(int x, int y) {
- return WebView().CoreHitTestResultAt(WebPoint(x, y));
+ return WebView().CoreHitTestResultAt(gfx::Point(x, y));
}
EventHandler& GetEventHandler() {
@@ -48,7 +48,8 @@ class ScrollbarsTest : public SimTest {
WebPointerProperties::Button::kNoButton, 0,
WebInputEvent::kNoModifiers, CurrentTimeTicks());
event.SetFrameScale(1);
- GetEventHandler().HandleMouseMoveEvent(event, Vector<WebMouseEvent>());
+ GetEventHandler().HandleMouseMoveEvent(event, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
}
void HandleMousePressEvent(int x, int y) {
@@ -179,7 +180,7 @@ TEST_F(ScrollbarsTest, DocumentStyleRecalcPreservesScrollbars) {
layout_viewport->HorizontalScrollbar());
}
-class ScrollbarsWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class ScrollbarsWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
void ConvertWindowToViewport(WebFloatRect* rect) override {
rect->x *= device_scale_factor_;
@@ -199,7 +200,7 @@ TEST_F(ScrollbarsTest, ScrollbarSizeForUseZoomDSF) {
ScrollbarsWebViewClient client;
client.set_device_scale_factor(1.f);
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view_impl =
web_view_helper.Initialize(nullptr, &client, nullptr, nullptr);
@@ -207,19 +208,20 @@ TEST_F(ScrollbarsTest, ScrollbarSizeForUseZoomDSF) {
web_view_impl->GetSettings()->SetViewportEnabled(true);
web_view_impl->Resize(IntSize(800, 600));
- WebURL base_url = URLTestHelpers::ToKURL("http://example.com/");
- FrameTestHelpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " width: 1600px;"
- " height: 1200px;"
- " }"
- "</style>"
- "<body>"
- "</body>",
- base_url);
- web_view_impl->UpdateAllLifecyclePhases();
+ WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
+ frame_test_helpers::LoadHTMLString(web_view_impl->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " width: 1600px;"
+ " height: 1200px;"
+ " }"
+ "</style>"
+ "<body>"
+ "</body>",
+ base_url);
+ web_view_impl->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
Document* document =
ToLocalFrame(web_view_impl->GetPage()->MainFrame())->GetDocument();
@@ -411,8 +413,8 @@ TEST_F(ScrollbarsTest, OverlayScrollbarChangeToDisplayNoneDynamically) {
DCHECK(!scrollable_root->HorizontalScrollbar());
// Set display:none.
- div->setAttribute(HTMLNames::classAttr, "noscrollbars");
- document.body()->setAttribute(HTMLNames::classAttr, "noscrollbars");
+ div->setAttribute(html_names::kClassAttr, "noscrollbars");
+ document.body()->setAttribute(html_names::kClassAttr, "noscrollbars");
Compositor().BeginFrame();
EXPECT_TRUE(scrollable_div->VerticalScrollbar());
@@ -1263,7 +1265,7 @@ TEST_F(ScrollbarsTest, CustomScrollbarWhenStyleOwnerChange) {
DCHECK(!div_scrollable->VerticalScrollbar()->IsOverlayScrollbar());
DCHECK(!div_scrollable->VerticalScrollbar()->GetTheme().IsMockTheme());
- div->setAttribute(HTMLNames::classAttr, "custom");
+ div->setAttribute(html_names::kClassAttr, "custom");
Compositor().BeginFrame();
EXPECT_TRUE(div_scrollable->VerticalScrollbar()->IsCustomScrollbar());
@@ -1998,7 +2000,7 @@ TEST_F(ScrollbarsTest,
EXPECT_FALSE(scrollable_div->ScrollbarsHiddenIfOverlay());
// Set display:none calls Dispose().
- div->setAttribute(HTMLNames::classAttr, "hide");
+ div->setAttribute(html_names::kClassAttr, "hide");
Compositor().BeginFrame();
// After paint layer in scrollable dispose, we can still call scrollbar hidden
@@ -2044,7 +2046,7 @@ TEST_F(ScrollbarsTest, PLSADisposeShouldClearPointerInLayers) {
GraphicsLayer* graphics_layer = scrollable_div->LayerForScrolling();
ASSERT_TRUE(graphics_layer);
- div->setAttribute(HTMLNames::classAttr, "hide");
+ div->setAttribute(html_names::kClassAttr, "hide");
document.UpdateStyleAndLayout();
EXPECT_FALSE(paint_layer->GetScrollableArea());
diff --git a/chromium/third_party/blink/renderer/core/layout/shapes/polygon_shape.cc b/chromium/third_party/blink/renderer/core/layout/shapes/polygon_shape.cc
index da0b28b58f1..698a6bdb876 100644
--- a/chromium/third_party/blink/renderer/core/layout/shapes/polygon_shape.cc
+++ b/chromium/third_party/blink/renderer/core/layout/shapes/polygon_shape.cc
@@ -171,7 +171,7 @@ void PolygonShape::BuildDisplayPaths(DisplayPaths& paths) const {
if (!polygon_.NumberOfVertices())
return;
paths.shape.MoveTo(polygon_.VertexAt(0));
- for (size_t i = 1; i < polygon_.NumberOfVertices(); ++i)
+ for (wtf_size_t i = 1; i < polygon_.NumberOfVertices(); ++i)
paths.shape.AddLineTo(polygon_.VertexAt(i));
paths.shape.CloseSubpath();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/shapes/shape.cc b/chromium/third_party/blink/renderer/core/layout/shapes/shape.cc
index 22bee377b05..8509e4a8231 100644
--- a/chromium/third_party/blink/renderer/core/layout/shapes/shape.cc
+++ b/chromium/third_party/blink/renderer/core/layout/shapes/shape.cc
@@ -44,11 +44,11 @@
#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h"
#include "third_party/skia/include/core/SkSurface.h"
@@ -162,10 +162,10 @@ std::unique_ptr<Shape> Shape::CreateShape(const BasicShape* basic_shape,
case BasicShape::kBasicShapePolygonType: {
const BasicShapePolygon* polygon = ToBasicShapePolygon(basic_shape);
const Vector<Length>& values = polygon->Values();
- size_t values_size = values.size();
+ wtf_size_t values_size = values.size();
DCHECK(!(values_size % 2));
Vector<FloatPoint> vertices(values_size / 2);
- for (unsigned i = 0; i < values_size; i += 2) {
+ for (wtf_size_t i = 0; i < values_size; i += 2) {
FloatPoint vertex(FloatValueForLength(values.at(i), box_width),
FloatValueForLength(values.at(i + 1), box_height));
vertices[i / 2] = PhysicalPointToLogical(
diff --git a/chromium/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc b/chromium/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc
index f87c3ff3435..5648f5fbf09 100644
--- a/chromium/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc
+++ b/chromium/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc
@@ -38,7 +38,7 @@
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_image.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -231,7 +231,8 @@ const Shape& ShapeOutsideInfo::ComputedShape() const {
writing_mode, margin);
break;
case ShapeValue::kImage:
- DCHECK(shape_value.IsImageValid());
+ DCHECK(shape_value.GetImage());
+ DCHECK(shape_value.GetImage()->CanRender());
shape_ = CreateShapeForImage(shape_value.GetImage(),
shape_image_threshold, writing_mode, margin);
break;
@@ -364,10 +365,12 @@ bool ShapeOutsideInfo::IsEnabledFor(const LayoutBox& box) {
switch (shape_value->GetType()) {
case ShapeValue::kShape:
return shape_value->Shape();
- case ShapeValue::kImage:
- return shape_value->IsImageValid() &&
- CheckShapeImageOrigin(box.GetDocument(),
- *(shape_value->GetImage()));
+ case ShapeValue::kImage: {
+ StyleImage* image = shape_value->GetImage();
+ DCHECK(image);
+ return image->CanRender() &&
+ CheckShapeImageOrigin(box.GetDocument(), *image);
+ }
case ShapeValue::kBox:
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.cc b/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.cc
index 6b6579ac9e7..6843f158e8b 100644
--- a/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.cc
+++ b/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.cc
@@ -40,7 +40,7 @@ SubtreeLayoutScope::SubtreeLayoutScope(LayoutObject& root) : root_(root) {
}
SubtreeLayoutScope::~SubtreeLayoutScope() {
- CHECK(!root_.NeedsLayout());
+ CHECK(!root_.NeedsLayout() || root_.LayoutBlockedByDisplayLock());
#if DCHECK_IS_ON()
for (auto* layout_object : layout_objects_to_layout_)
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/BUILD.gn b/chromium/third_party/blink/renderer/core/layout/svg/BUILD.gn
index 470debebcaf..8d013890a44 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/layout/svg/BUILD.gn
@@ -91,5 +91,7 @@ blink_core_sources("svg_layout") {
"svg_text_metrics.h",
"svg_text_query.cc",
"svg_text_query.h",
+ "transformed_hit_test_location.cc",
+ "transformed_hit_test_location.h",
]
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc
index 65c9e44aa0b..a72c858e3af 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.cc
@@ -62,7 +62,7 @@ void LayoutSVGBlock::StyleDidChange(StyleDifference diff,
// Since layout depends on the bounds of the filter, we need to force layout
// when the filter changes.
if (diff.FilterChanged())
- SetNeedsLayout(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayout(layout_invalidation_reason::kStyleChange);
if (diff.NeedsFullLayout()) {
SetNeedsBoundariesUpdate();
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.cc
index 44b1badee7c..c2de62b7eed 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.cc
@@ -25,10 +25,10 @@
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
-#include "third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/svg_container_painter.h"
namespace blink {
@@ -180,34 +180,17 @@ bool LayoutSVGContainer::NodeAtPoint(
const LayoutPoint& accumulated_offset,
HitTestAction hit_test_action) {
DCHECK_EQ(accumulated_offset, LayoutPoint());
- base::Optional<HitTestLocation> local_storage;
- const HitTestLocation* local_location =
- SVGLayoutSupport::TransformToUserSpaceAndCheckClipping(
- *this, LocalToSVGParentTransform(), location_in_container,
- local_storage);
+ TransformedHitTestLocation local_location(location_in_container,
+ LocalToSVGParentTransform());
if (!local_location)
return false;
+ if (!SVGLayoutSupport::IntersectsClipPath(*this, *local_location))
+ return false;
+
+ if (SVGLayoutSupport::HitTestChildren(LastChild(), result, *local_location,
+ accumulated_offset, hit_test_action))
+ return true;
- for (LayoutObject* child = LastChild(); child;
- child = child->PreviousSibling()) {
- bool found = false;
- if (child->IsSVGForeignObject()) {
- found = ToLayoutSVGForeignObject(child)->NodeAtPointFromSVG(
- result, *local_location, accumulated_offset, hit_test_action);
- } else {
- found = child->NodeAtPoint(result, *local_location, accumulated_offset,
- hit_test_action);
- }
- if (found) {
- const LayoutPoint& local_layout_point =
- LayoutPoint(local_location->TransformedPoint());
- UpdateHitTestResult(result, local_layout_point);
- if (result.AddNodeToListBasedTestResult(
- child->GetNode(), *local_location) == kStopHitTesting) {
- return true;
- }
- }
- }
// pointer-events: bounding-box makes it possible for containers to be direct
// targets.
if (StyleRef().PointerEvents() == EPointerEvents::kBoundingBox) {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.cc
index 2b0bad97a45..93a6b9089df 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.cc
@@ -33,7 +33,7 @@
namespace blink {
LayoutSVGEllipse::LayoutSVGEllipse(SVGGeometryElement* node)
- : LayoutSVGShape(node), use_path_fallback_(false) {}
+ : LayoutSVGShape(node, kSimple), use_path_fallback_(false) {}
LayoutSVGEllipse::~LayoutSVGEllipse() = default;
@@ -74,9 +74,7 @@ void LayoutSVGEllipse::UpdateShapeFromElement() {
ClearPath();
fill_bounding_box_ = FloatRect(center_ - radii_, radii_.ScaledBy(2));
- stroke_bounding_box_ = fill_bounding_box_;
- if (StyleRef().SvgStyle().HasStroke())
- stroke_bounding_box_.Inflate(StrokeWidth() / 2);
+ stroke_bounding_box_ = CalculateStrokeBoundingBox();
}
void LayoutSVGEllipse::CalculateRadiiAndCenter() {
@@ -101,15 +99,17 @@ void LayoutSVGEllipse::CalculateRadiiAndCenter() {
}
}
-bool LayoutSVGEllipse::ShapeDependentStrokeContains(const FloatPoint& point) {
+bool LayoutSVGEllipse::ShapeDependentStrokeContains(
+ const HitTestLocation& location) {
if (radii_.Width() < 0 || radii_.Height() < 0)
return false;
// The optimized check below for circles does not support non-circular and
// the cases that we set use_path_fallback_ in UpdateShapeFromElement().
if (use_path_fallback_ || radii_.Width() != radii_.Height())
- return LayoutSVGShape::ShapeDependentStrokeContains(point);
+ return LayoutSVGShape::ShapeDependentStrokeContains(location);
+ const FloatPoint& point = location.TransformedPoint();
const FloatPoint center =
FloatPoint(center_.X() - point.X(), center_.Y() - point.Y());
const float half_stroke_width = StrokeWidth() / 2;
@@ -118,8 +118,9 @@ bool LayoutSVGEllipse::ShapeDependentStrokeContains(const FloatPoint& point) {
}
bool LayoutSVGEllipse::ShapeDependentFillContains(
- const FloatPoint& point,
+ const HitTestLocation& location,
const WindRule fill_rule) const {
+ const FloatPoint& point = location.TransformedPoint();
const FloatPoint center =
FloatPoint(center_.X() - point.X(), center_.Y() - point.Y());
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.h
index 1cc039d9091..9672a40b6ac 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_ellipse.h
@@ -48,8 +48,8 @@ class LayoutSVGEllipse final : public LayoutSVGShape {
return use_path_fallback_ ? LayoutSVGShape::IsShapeEmpty()
: fill_bounding_box_.IsEmpty();
}
- bool ShapeDependentStrokeContains(const FloatPoint&) override;
- bool ShapeDependentFillContains(const FloatPoint&,
+ bool ShapeDependentStrokeContains(const HitTestLocation&) override;
+ bool ShapeDependentFillContains(const HitTestLocation&,
const WindRule) const override;
void CalculateRadiiAndCenter();
bool HasContinuousStroke() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc
index 4ef7808bdaa..cd3401bbce7 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc
@@ -24,6 +24,7 @@
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/svg_foreign_object_painter.h"
#include "third_party/blink/renderer/core/svg/svg_foreign_object_element.h"
@@ -130,23 +131,13 @@ bool LayoutSVGForeignObject::NodeAtPointFromSVG(
const LayoutPoint& accumulated_offset,
HitTestAction) {
DCHECK_EQ(accumulated_offset, LayoutPoint());
- AffineTransform local_transform = LocalSVGTransform();
- if (!local_transform.IsInvertible())
+ TransformedHitTestLocation local_location(location_in_parent,
+ LocalSVGTransform());
+ if (!local_location)
return false;
- AffineTransform inverse = local_transform.Inverse();
- base::Optional<HitTestLocation> local_location;
- if (location_in_parent.IsRectBasedTest()) {
- local_location.emplace(
- inverse.MapPoint(location_in_parent.TransformedPoint()),
- inverse.MapQuad(location_in_parent.TransformedRect()));
- } else {
- local_location.emplace(
- (inverse.MapPoint(location_in_parent.TransformedPoint())));
- }
-
- // |local_point| already includes the offset of the <foreignObject> element,
- // but PaintLayer::HitTestLayer assumes it has not been.
+ // |local_location| already includes the offset of the <foreignObject>
+ // element, but PaintLayer::HitTestLayer assumes it has not been.
HitTestLocation local_without_offset(
*local_location, -ToLayoutSize(Layer()->LayoutBoxLocation()));
HitTestResult layer_result(result.GetHitTestRequest(), local_without_offset);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h
index 7fdaa7cc6df..6d11b4249a2 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h
@@ -59,6 +59,7 @@ class LayoutSVGForeignObject final : public LayoutSVGBlock {
FloatRect VisualRectInLocalSVGCoordinates() const override {
return ObjectBoundingBox();
}
+ bool IsObjectBoundingBoxValid() const { return !FrameRect().IsEmpty(); }
bool NodeAtPoint(HitTestResult&,
const HitTestLocation&,
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object_test.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object_test.cc
index 8ba8bf6b86b..d26dfb93b2d 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object_test.cc
@@ -98,7 +98,7 @@ TEST_F(LayoutSVGForeignObjectTest, IframeInForeignObject) {
</style>
<div id='div' style='margin: 70px; width: 100px; height: 50px'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto& svg = *GetDocument().getElementById("svg");
const auto& foreign = *GetDocument().getElementById("foreign");
@@ -166,7 +166,7 @@ TEST_F(LayoutSVGForeignObjectTest, HitTestZoomedForeignObject) {
SetBodyInnerHTML(R"HTML(
<style>* { margin: 0; zoom: 150% }</style>
<svg id='svg' style='width: 200px; height: 200px'>
- <foreignObject id='foreign' x='10' y='10' width='100' height='150'>
+ <foreignObject id='foreign' x='10' y='10' width='100' height='150' style='overflow: visible'>
<div id='div' style='margin: 50px; width: 50px; height: 50px'>
</div>
</foreignObject>
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.cc
index 8b169e251e2..8494c388ccb 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.cc
@@ -34,10 +34,11 @@
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/svg_image_painter.h"
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
namespace blink {
@@ -157,7 +158,7 @@ void LayoutSVGImage::UpdateLayout() {
if (auto* svg_image_element = ToSVGImageElementOrNull(GetElement())) {
if (svg_image_element->IsDefaultIntrinsicSize())
- MediaElementParserHelpers::ReportUnsizedMediaViolation(this);
+ media_element_parser_helpers::ReportUnsizedMediaViolation(this);
}
ClearNeedsLayout();
}
@@ -170,7 +171,7 @@ bool LayoutSVGImage::NodeAtPoint(HitTestResult& result,
const HitTestLocation& location_in_container,
const LayoutPoint& accumulated_offset,
HitTestAction hit_test_action) {
- DCHECK(accumulated_offset == LayoutPoint());
+ DCHECK_EQ(accumulated_offset, LayoutPoint());
// We only draw in the forground phase, so we only hit-test then.
if (hit_test_action != kHitTestForeground)
return false;
@@ -182,13 +183,12 @@ bool LayoutSVGImage::NodeAtPoint(HitTestResult& result,
if (hit_rules.require_visible && style.Visibility() != EVisibility::kVisible)
return false;
- base::Optional<HitTestLocation> local_storage;
- const HitTestLocation* local_location =
- SVGLayoutSupport::TransformToUserSpaceAndCheckClipping(
- *this, LocalToSVGParentTransform(), location_in_container,
- local_storage);
+ TransformedHitTestLocation local_location(location_in_container,
+ LocalToSVGParentTransform());
if (!local_location)
return false;
+ if (!SVGLayoutSupport::IntersectsClipPath(*this, *local_location))
+ return false;
if (hit_rules.can_hit_fill || hit_rules.can_hit_bounding_box) {
if (local_location->Intersects(object_bounding_box_)) {
@@ -212,7 +212,7 @@ void LayoutSVGImage::ImageChanged(WrappedImagePtr, CanDeferInvalidation defer) {
if (StyleRef().Width().IsAuto() || StyleRef().Height().IsAuto()) {
if (UpdateBoundingBox())
- SetNeedsLayout(LayoutInvalidationReason::kSizeChanged);
+ SetNeedsLayout(layout_invalidation_reason::kSizeChanged);
}
SetShouldDoFullPaintInvalidation(PaintInvalidationReason::kImage);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.h
index e179cc5c642..863c6fffec7 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_image.h
@@ -45,6 +45,10 @@ class LayoutSVGImage final : public LayoutSVGModelObject {
}
FloatRect ObjectBoundingBox() const override { return object_bounding_box_; }
+ bool IsObjectBoundingBoxValid() const {
+ return !object_bounding_box_.IsEmpty();
+ }
+
bool IsOfType(LayoutObjectType type) const override {
return type == kLayoutObjectSVGImage ||
LayoutSVGModelObject::IsOfType(type);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc
index 172eff5f721..8bd7610f6a1 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline.cc
@@ -130,7 +130,7 @@ void LayoutSVGInline::StyleDidChange(StyleDifference diff,
// Since layout depends on the bounds of the filter, we need to force layout
// when the filter changes.
if (diff.FilterChanged())
- SetNeedsLayout(LayoutInvalidationReason::kStyleChange);
+ SetNeedsLayout(layout_invalidation_reason::kStyleChange);
if (diff.NeedsFullLayout())
SetNeedsBoundariesUpdate();
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.cc
index 5d8001c47c3..c008a9501ba 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.cc
@@ -85,7 +85,7 @@ void LayoutSVGInlineText::StyleDidChange(StyleDifference diff,
LayoutSVGText::LocateLayoutSVGTextAncestor(this)) {
text_layout_object->SetNeedsTextMetricsUpdate();
text_layout_object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
}
}
@@ -351,15 +351,15 @@ void LayoutSVGInlineText::UpdateMetricsList(
bool bidi_override = IsOverride(StyleRef().GetUnicodeBidi());
BidiStatus status(TextDirection::kLtr, bidi_override);
if (run.Is8Bit() || bidi_override) {
- WTF::Unicode::CharDirection direction = WTF::Unicode::kLeftToRight;
+ WTF::unicode::CharDirection direction = WTF::unicode::kLeftToRight;
// If BiDi override is in effect, use the specified direction.
if (bidi_override && !StyleRef().IsLeftToRightDirection())
- direction = WTF::Unicode::kRightToLeft;
+ direction = WTF::unicode::kRightToLeft;
bidi_runs.AddRun(new BidiCharacterRun(
status.context->Override(), status.context->Level(), 0,
run.CharactersLength(), direction, status.context->Dir()));
} else {
- status.last = status.last_strong = WTF::Unicode::kOtherNeutral;
+ status.last = status.last_strong = WTF::unicode::kOtherNeutral;
bidi_resolver.SetStatus(status);
bidi_resolver.SetPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));
const bool kHardLineBreak = false;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc
index f988fbf784b..5864f8ad0b2 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_model_object.cc
@@ -131,7 +131,7 @@ void LayoutSVGModelObject::StyleDidChange(StyleDifference diff,
// before and thus will not flag paint in ClientLayoutChanged.
if (diff.FilterChanged()) {
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kStyleChange);
+ layout_invalidation_reason::kStyleChange);
}
if (diff.NeedsFullLayout()) {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc
index 76c671628c6..96428abd09e 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc
@@ -34,7 +34,9 @@
namespace blink {
-LayoutSVGPath::LayoutSVGPath(SVGGeometryElement* node) : LayoutSVGShape(node) {}
+LayoutSVGPath::LayoutSVGPath(SVGGeometryElement* node)
+ // <line> elements have no joins and thus needn't care about miters.
+ : LayoutSVGShape(node, IsSVGLineElement(node) ? kNoMiters : kComplex) {}
LayoutSVGPath::~LayoutSVGPath() = default;
@@ -54,12 +56,6 @@ void LayoutSVGPath::UpdateShapeFromElement() {
UpdateMarkers();
}
-FloatRect LayoutSVGPath::HitTestStrokeBoundingBox() const {
- if (StyleRef().SvgStyle().HasStroke())
- return stroke_bounding_box_;
- return ApproximateStrokeBoundingBox(fill_bounding_box_);
-}
-
void LayoutSVGPath::UpdateMarkers() {
marker_positions_.clear();
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.h
index b7e127d53b5..94cdea0c76c 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.h
@@ -46,7 +46,6 @@ class LayoutSVGPath final : public LayoutSVGShape {
void WillBeDestroyed() override;
void UpdateShapeFromElement() override;
- FloatRect HitTestStrokeBoundingBox() const override;
void UpdateMarkers();
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc
index aa88e855883..f895585e42d 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc
@@ -33,7 +33,7 @@
namespace blink {
LayoutSVGRect::LayoutSVGRect(SVGRectElement* node)
- : LayoutSVGShape(node), use_path_fallback_(false) {}
+ : LayoutSVGShape(node, kSimple), use_path_fallback_(false) {}
LayoutSVGRect::~LayoutSVGRect() = default;
@@ -43,10 +43,8 @@ void LayoutSVGRect::UpdateShapeFromElement() {
fill_bounding_box_ = FloatRect();
stroke_bounding_box_ = FloatRect();
use_path_fallback_ = false;
- SVGRectElement* rect = ToSVGRectElement(GetElement());
- DCHECK(rect);
- SVGLengthContext length_context(rect);
+ SVGLengthContext length_context(GetElement());
const ComputedStyle& style = StyleRef();
FloatSize bounding_box_size(ToFloatSize(
length_context.ResolveLengthPair(style.Width(), style.Height(), style)));
@@ -79,17 +77,17 @@ void LayoutSVGRect::UpdateShapeFromElement() {
fill_bounding_box_ = FloatRect(
length_context.ResolveLengthPair(svg_style.X(), svg_style.Y(), style),
bounding_box_size);
- stroke_bounding_box_ = fill_bounding_box_;
- if (svg_style.HasStroke())
- stroke_bounding_box_.Inflate(StrokeWidth() / 2);
+ stroke_bounding_box_ = CalculateStrokeBoundingBox();
}
-bool LayoutSVGRect::ShapeDependentStrokeContains(const FloatPoint& point) {
+bool LayoutSVGRect::ShapeDependentStrokeContains(
+ const HitTestLocation& location) {
// The optimized code below does not support the cases that we set
// use_path_fallback_ in UpdateShapeFromElement().
if (use_path_fallback_)
- return LayoutSVGShape::ShapeDependentStrokeContains(point);
+ return LayoutSVGShape::ShapeDependentStrokeContains(location);
+ const FloatPoint& point = location.TransformedPoint();
const float half_stroke_width = StrokeWidth() / 2;
const float half_width = fill_bounding_box_.Width() / 2;
const float half_height = fill_bounding_box_.Height() / 2;
@@ -108,10 +106,11 @@ bool LayoutSVGRect::ShapeDependentStrokeContains(const FloatPoint& point) {
(half_height - half_stroke_width <= abs_delta_y);
}
-bool LayoutSVGRect::ShapeDependentFillContains(const FloatPoint& point,
+bool LayoutSVGRect::ShapeDependentFillContains(const HitTestLocation& location,
const WindRule fill_rule) const {
if (use_path_fallback_)
- return LayoutSVGShape::ShapeDependentFillContains(point, fill_rule);
+ return LayoutSVGShape::ShapeDependentFillContains(location, fill_rule);
+ const FloatPoint& point = location.TransformedPoint();
return fill_bounding_box_.Contains(point.X(), point.Y());
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.h
index a2352f9d406..9dc9c7642cf 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_rect.h
@@ -49,8 +49,8 @@ class LayoutSVGRect final : public LayoutSVGShape {
return use_path_fallback_ ? LayoutSVGShape::IsShapeEmpty()
: fill_bounding_box_.IsEmpty();
}
- bool ShapeDependentStrokeContains(const FloatPoint&) override;
- bool ShapeDependentFillContains(const FloatPoint&,
+ bool ShapeDependentStrokeContains(const HitTestLocation&) override;
+ bool ShapeDependentFillContains(const HitTestLocation&,
const WindRule) const override;
bool DefinitelyHasSimpleStroke() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc
index 0cc835c02a7..f1169d2f6f3 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/svg/svg_clip_path_element.h"
#include "third_party/blink/renderer/core/svg/svg_geometry_element.h"
@@ -236,30 +237,26 @@ AffineTransform LayoutSVGResourceClipper::CalculateClipTransform(
bool LayoutSVGResourceClipper::HitTestClipContent(
const FloatRect& object_bounding_box,
- const FloatPoint& node_at_point) {
- FloatPoint point = node_at_point;
- if (!SVGLayoutSupport::PointInClippingArea(*this, point))
+ const HitTestLocation& location) const {
+ if (!SVGLayoutSupport::IntersectsClipPath(*this, location))
return false;
- AffineTransform user_space_transform =
- CalculateClipTransform(object_bounding_box);
- if (!user_space_transform.IsInvertible())
+ TransformedHitTestLocation local_location(
+ location, CalculateClipTransform(object_bounding_box));
+ if (!local_location)
return false;
- point = user_space_transform.Inverse().MapPoint(point);
-
+ HitTestResult result(HitTestRequest::kSVGClipContent, *local_location);
for (const SVGElement& child_element :
Traversal<SVGElement>::ChildrenOf(*GetElement())) {
if (!ContributesToClip(child_element))
continue;
- HitTestLocation location(point);
- HitTestResult result(HitTestRequest::kSVGClipContent, location);
LayoutObject* layout_object = child_element.GetLayoutObject();
DCHECK(!layout_object->IsBoxModelObject() ||
!ToLayoutBoxModelObject(layout_object)->HasSelfPaintingLayer());
- if (layout_object->NodeAtPoint(result, location, LayoutPoint(),
+ if (layout_object->NodeAtPoint(result, *local_location, LayoutPoint(),
kHitTestForeground))
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.h
index b7913abce78..b8f71fbb74e 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.h
@@ -42,7 +42,7 @@ class LayoutSVGResourceClipper final : public LayoutSVGResourceContainer {
static const LayoutSVGResourceType kResourceType = kClipperResourceType;
LayoutSVGResourceType ResourceType() const override { return kResourceType; }
- bool HitTestClipContent(const FloatRect&, const FloatPoint&);
+ bool HitTestClipContent(const FloatRect&, const HitTestLocation&) const;
SVGUnitTypes::SVGUnitType ClipPathUnits() const;
AffineTransform CalculateClipTransform(const FloatRect& reference_box) const;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.cc
index ba9064af86d..2fc5cecdb63 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.cc
@@ -142,7 +142,7 @@ void LayoutSVGResourceContainer::InvalidateCacheAndMarkForLayout(
void LayoutSVGResourceContainer::InvalidateCacheAndMarkForLayout(
SubtreeLayoutScope* layout_scope) {
InvalidateCacheAndMarkForLayout(
- LayoutInvalidationReason::kSvgResourceInvalidated, layout_scope);
+ layout_invalidation_reason::kSvgResourceInvalidated, layout_scope);
}
static inline void RemoveFromCacheAndInvalidateDependencies(
@@ -174,9 +174,10 @@ void LayoutSVGResourceContainer::MarkForLayoutAndParentResourceInvalidation(
bool needs_layout) {
DCHECK(object.GetNode());
- if (needs_layout && !object.DocumentBeingDestroyed())
+ if (needs_layout && !object.DocumentBeingDestroyed()) {
object.SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSvgResourceInvalidated);
+ layout_invalidation_reason::kSvgResourceInvalidated);
+ }
RemoveFromCacheAndInvalidateDependencies(object, needs_layout);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.cc
index 66fad9a8272..e2cb27b87e0 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.cc
@@ -43,7 +43,8 @@ void FilterData::Dispose() {
}
LayoutSVGResourceFilter::LayoutSVGResourceFilter(SVGFilterElement* node)
- : LayoutSVGResourceContainer(node), filter_(new FilterMap) {}
+ : LayoutSVGResourceContainer(node),
+ filter_(MakeGarbageCollected<FilterMap>()) {}
LayoutSVGResourceFilter::~LayoutSVGResourceFilter() = default;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h
index c93abbf6c79..265c6b3df72 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h
@@ -52,7 +52,9 @@ class FilterData final : public GarbageCollected<FilterData> {
kPaintingFilterCycleDetected
};
- static FilterData* Create() { return new FilterData(); }
+ static FilterData* Create() { return MakeGarbageCollected<FilterData>(); }
+
+ FilterData() : state_(kInitial) {}
void Dispose();
@@ -61,9 +63,6 @@ class FilterData final : public GarbageCollected<FilterData> {
Member<FilterEffect> last_effect;
Member<SVGFilterGraphNodeMap> node_map;
FilterDataState state_;
-
- private:
- FilterData() : state_(kInitial) {}
};
class LayoutSVGResourceFilter final : public LayoutSVGResourceContainer {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter_primitive.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter_primitive.cc
index 014b405c9dd..b76d248235c 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter_primitive.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter_primitive.cc
@@ -49,19 +49,19 @@ void LayoutSVGResourceFilterPrimitive::StyleDidChange(
if (IsSVGFEFloodElement(element) || IsSVGFEDropShadowElement(element)) {
if (new_style.FloodColor() != old_style->SvgStyle().FloodColor() ||
CurrentColorChanged(diff, new_style.FloodColor()))
- element.PrimitiveAttributeChanged(SVGNames::flood_colorAttr);
+ element.PrimitiveAttributeChanged(svg_names::kFloodColorAttr);
if (new_style.FloodOpacity() != old_style->SvgStyle().FloodOpacity())
- element.PrimitiveAttributeChanged(SVGNames::flood_opacityAttr);
+ element.PrimitiveAttributeChanged(svg_names::kFloodOpacityAttr);
} else if (IsSVGFEDiffuseLightingElement(element) ||
IsSVGFESpecularLightingElement(element)) {
if (new_style.LightingColor() != old_style->SvgStyle().LightingColor() ||
CurrentColorChanged(diff, new_style.LightingColor()))
- element.PrimitiveAttributeChanged(SVGNames::lighting_colorAttr);
+ element.PrimitiveAttributeChanged(svg_names::kLightingColorAttr);
}
if (new_style.ColorInterpolationFilters() !=
old_style->SvgStyle().ColorInterpolationFilters()) {
element.PrimitiveAttributeChanged(
- SVGNames::color_interpolation_filtersAttr);
+ svg_names::kColorInterpolationFiltersAttr);
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_gradient.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_gradient.cc
index 1eb83b116c7..66a23138953 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_gradient.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_gradient.cc
@@ -29,7 +29,7 @@ namespace blink {
LayoutSVGResourceGradient::LayoutSVGResourceGradient(SVGGradientElement* node)
: LayoutSVGResourcePaintServer(node),
should_collect_gradient_attributes_(true),
- gradient_map_(new GradientMap) {}
+ gradient_map_(MakeGarbageCollected<GradientMap>()) {}
void LayoutSVGResourceGradient::RemoveAllClientsFromCache(
bool mark_for_invalidation) {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc
index 3866307cb36..a794cca3532 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_linear_gradient.cc
@@ -57,7 +57,8 @@ scoped_refptr<Gradient> LayoutSVGResourceLinearGradient::BuildGradient() const {
scoped_refptr<Gradient> gradient = Gradient::CreateLinear(
StartPoint(attributes), EndPoint(attributes),
PlatformSpreadMethodFromSVGType(attributes.SpreadMethod()),
- Gradient::ColorInterpolation::kUnpremultiplied);
+ Gradient::ColorInterpolation::kUnpremultiplied,
+ Gradient::DegenerateHandling::kAllow);
gradient->AddColorStops(attributes.Stops());
return gradient;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc
index 61a7258c763..34353aeecc7 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_pattern.cc
@@ -49,7 +49,7 @@ LayoutSVGResourcePattern::LayoutSVGResourcePattern(SVGPatternElement* node)
: LayoutSVGResourcePaintServer(node),
should_collect_pattern_attributes_(true),
attributes_wrapper_(PatternAttributesWrapper::Create()),
- pattern_map_(new PatternMap) {}
+ pattern_map_(MakeGarbageCollected<PatternMap>()) {}
void LayoutSVGResourcePattern::RemoveAllClientsFromCache(
bool mark_for_invalidation) {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc
index 9b66ea5a387..ed292d47d5a 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_radial_gradient.cc
@@ -71,7 +71,8 @@ scoped_refptr<Gradient> LayoutSVGResourceRadialGradient::BuildGradient() const {
FocalPoint(attributes), FocalRadius(attributes), CenterPoint(attributes),
Radius(attributes), 1,
PlatformSpreadMethodFromSVGType(attributes.SpreadMethod()),
- Gradient::ColorInterpolation::kUnpremultiplied);
+ Gradient::ColorInterpolation::kUnpremultiplied,
+ Gradient::DegenerateHandling::kDisallow);
gradient->AddColorStops(attributes.Stops());
return gradient;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc
index 34f188eff44..62a15b2e2a0 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc
@@ -30,18 +30,18 @@
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
-#include "third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_masker.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_text.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/svg_root_painter.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
@@ -469,19 +469,6 @@ LayoutRect LayoutSVGRoot::LocalVisualRectIgnoringVisibility() const {
return LayoutRect(EnclosingIntRect(visual_rect));
}
-bool LayoutSVGRoot::PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const {
- // The rule extends LayoutBox's instead of LayoutReplaced's.
- if (!LayoutBox::PaintedOutputOfObjectHasNoEffectRegardlessOfSize())
- return false;
-
- if (SVGResources* resources =
- SVGResourcesCache::CachedResourcesForLayoutObject(*this)) {
- if (resources->Masker())
- return false;
- }
- return true;
-}
-
// This method expects local CSS box coordinates.
// Callers with local SVG viewport coordinates should first apply the
// localToBorderBoxTransform to convert from SVG viewport coordinates to local
@@ -524,42 +511,14 @@ bool LayoutSVGRoot::NodeAtPoint(HitTestResult& result,
(local_border_box_location.Intersects(PhysicalContentBoxRect()) ||
(!ShouldApplyViewportClip() &&
local_border_box_location.Intersects(VisualOverflowRect())))) {
- const AffineTransform& local_to_border_box_transform =
- LocalToBorderBoxTransform();
- if (local_to_border_box_transform.IsInvertible()) {
- AffineTransform inverse = local_to_border_box_transform.Inverse();
- FloatPoint local_point =
- inverse.MapPoint(local_border_box_location.TransformedPoint());
-
- base::Optional<HitTestLocation> local_location;
- if (location_in_container.IsRectBasedTest()) {
- FloatQuad quad_in_container =
- local_border_box_location.TransformedRect();
-
- local_location.emplace(local_point, inverse.MapQuad(quad_in_container));
- } else {
- local_location.emplace(local_point);
- }
-
- for (LayoutObject* child = LastChild(); child;
- child = child->PreviousSibling()) {
- bool found = false;
- if (child->IsSVGForeignObject()) {
- found = ToLayoutSVGForeignObject(child)->NodeAtPointFromSVG(
- result, *local_location, LayoutPoint(), hit_test_action);
- } else {
- found = child->NodeAtPoint(result, *local_location, LayoutPoint(),
- hit_test_action);
- }
-
- if (found) {
- UpdateHitTestResult(result, local_border_box_location.Point());
- if (result.AddNodeToListBasedTestResult(
- child->GetNode(), location_in_container) == kStopHitTesting) {
- return true;
- }
- }
- }
+ TransformedHitTestLocation local_location(local_border_box_location,
+ LocalToBorderBoxTransform());
+ if (local_location) {
+ LayoutPoint accumulated_offset_for_children;
+ if (SVGLayoutSupport::HitTestChildren(
+ LastChild(), result, *local_location,
+ accumulated_offset_for_children, hit_test_action))
+ return true;
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.h
index a79fff4435a..91c97212585 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.h
@@ -72,7 +72,7 @@ class CORE_EXPORT LayoutSVGRoot final : public LayoutReplaced {
// the layout may be incorrectly using the old size.
if (container_size_ != container_size) {
SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kSizeChanged);
+ layout_invalidation_reason::kSizeChanged);
}
container_size_ = container_size;
}
@@ -91,8 +91,6 @@ class CORE_EXPORT LayoutSVGRoot final : public LayoutReplaced {
const char* GetName() const override { return "LayoutSVGRoot"; }
- bool PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const final;
-
private:
bool ComputeShouldClipOverflow() const override {
return LayoutBox::ComputeShouldClipOverflow() || ShouldApplyViewportClip();
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root_test.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root_test.cc
index 3887f1e7670..1558bb16ad4 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root_test.cc
@@ -61,7 +61,7 @@ TEST_F(LayoutSVGRootTest, VisualOverflowExpandsLayer) {
EXPECT_EQ(graphics_layer->Size(), gfx::Size(100, 100));
GetDocument().getElementById("rect")->setAttribute("height", "200");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(graphics_layer->Size(), gfx::Size(100, 200));
}
@@ -134,7 +134,7 @@ TEST_F(LayoutSVGRootTest,
const LayoutSVGRoot& root =
*ToLayoutSVGRoot(GetLayoutObjectByElementId("svg"));
- EXPECT_TRUE(root.PaintedOutputOfObjectHasNoEffectRegardlessOfSize());
+ EXPECT_FALSE(root.PaintedOutputOfObjectHasNoEffectRegardlessOfSize());
}
TEST_F(LayoutSVGRootTest,
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
index d57d29e0211..5d50614337a 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc
@@ -35,18 +35,22 @@
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/svg_shape_painter.h"
#include "third_party/blink/renderer/core/svg/svg_geometry_element.h"
#include "third_party/blink/renderer/core/svg/svg_length_context.h"
-#include "third_party/blink/renderer/core/svg/svg_path_element.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/graphics/stroke_data.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
-LayoutSVGShape::LayoutSVGShape(SVGGeometryElement* node)
+LayoutSVGShape::LayoutSVGShape(SVGGeometryElement* node,
+ StrokeGeometryClass geometry_class)
: LayoutSVGModelObject(node),
+ // Geometry classification - used to compute stroke bounds more
+ // efficiently.
+ geometry_class_(geometry_class),
// Default is false, the cached rects are empty from the beginning.
needs_boundaries_update_(false),
// Default is true, so we grab a Path object once from SVGGeometryElement.
@@ -54,8 +58,6 @@ LayoutSVGShape::LayoutSVGShape(SVGGeometryElement* node)
// Default is true, so we grab a AffineTransform object once from
// SVGGeometryElement.
needs_transform_update_(true),
- // <line> elements have no joins and thus needn't care about miters.
- affected_by_miter_(!IsSVGLineElement(node)),
// Default to false, since |needs_transform_update_| is true this will be
// updated the first time transforms are updated.
transform_uses_reference_box_(false) {}
@@ -87,7 +89,7 @@ float LayoutSVGShape::DashScaleFactor() const {
void LayoutSVGShape::UpdateShapeFromElement() {
CreatePath();
- fill_bounding_box_ = CalculateObjectBoundingBox();
+ fill_bounding_box_ = GetPath().BoundingRect();
if (HasNonScalingStroke()) {
// NonScalingStrokeTransform may depend on LocalTransform which in turn may
@@ -110,9 +112,8 @@ bool HasSquareCapStyle(const SVGComputedStyle& svg_style) {
} // namespace
-FloatRect LayoutSVGShape::ApproximateStrokeBoundingBox(
- const FloatRect& shape_bbox) const {
- FloatRect stroke_box = shape_bbox;
+FloatRect LayoutSVGShape::ApproximateStrokeBoundingBox() const {
+ FloatRect stroke_box = fill_bounding_box_;
// Implementation of
// https://drafts.fxtf.org/css-masking/#compute-stroke-bounding-box
@@ -122,18 +123,19 @@ FloatRect LayoutSVGShape::ApproximateStrokeBoundingBox(
if (stroke_width <= 0)
return stroke_box;
- const SVGComputedStyle& svg_style = StyleRef().SvgStyle();
float delta = stroke_width / 2;
- if (affected_by_miter_ && HasMiterJoinStyle(svg_style)) {
- const float miter = svg_style.StrokeMiterLimit();
- if (miter < M_SQRT2 && HasSquareCapStyle(svg_style))
+ if (geometry_class_ != kSimple) {
+ const SVGComputedStyle& svg_style = StyleRef().SvgStyle();
+ if (geometry_class_ != kNoMiters && HasMiterJoinStyle(svg_style)) {
+ const float miter = svg_style.StrokeMiterLimit();
+ if (miter < M_SQRT2 && HasSquareCapStyle(svg_style))
+ delta *= M_SQRT2;
+ else
+ delta *= std::max(miter, 1.0f);
+ } else if (HasSquareCapStyle(svg_style)) {
delta *= M_SQRT2;
- else
- delta *= std::max(miter, 1.0f);
- } else if (HasSquareCapStyle(svg_style)) {
- delta *= M_SQRT2;
+ }
}
-
stroke_box.Inflate(delta);
return stroke_box;
}
@@ -141,20 +143,11 @@ FloatRect LayoutSVGShape::ApproximateStrokeBoundingBox(
FloatRect LayoutSVGShape::HitTestStrokeBoundingBox() const {
if (StyleRef().SvgStyle().HasStroke())
return stroke_bounding_box_;
-
- // Implementation of
- // https://drafts.fxtf.org/css-masking/#compute-stroke-bounding-box
- // for the <rect> / <ellipse> / <circle> case except that we ignore whether
- // the stroke is none.
-
- // TODO(fs): Fold this into ApproximateStrokeBoundingBox.
- FloatRect box = fill_bounding_box_;
- const float stroke_width = StrokeWidth();
- box.Inflate(stroke_width / 2);
- return box;
+ return ApproximateStrokeBoundingBox();
}
-bool LayoutSVGShape::ShapeDependentStrokeContains(const FloatPoint& point) {
+bool LayoutSVGShape::ShapeDependentStrokeContains(
+ const HitTestLocation& location) {
// In case the subclass didn't create path during UpdateShapeFromElement()
// for optimization but still calls this method.
if (!HasPath())
@@ -169,50 +162,50 @@ bool LayoutSVGShape::ShapeDependentStrokeContains(const FloatPoint& point) {
if (!rare_data_)
UpdateNonScalingStrokeData();
return NonScalingStrokePath().StrokeContains(
- NonScalingStrokeTransform().MapPoint(point), stroke_data);
+ NonScalingStrokeTransform().MapPoint(location.TransformedPoint()),
+ stroke_data);
}
-
- return path_->StrokeContains(point, stroke_data);
+ return path_->StrokeContains(location.TransformedPoint(), stroke_data);
}
bool LayoutSVGShape::ShapeDependentFillContains(
- const FloatPoint& point,
+ const HitTestLocation& location,
const WindRule fill_rule) const {
- return GetPath().Contains(point, fill_rule);
+ return GetPath().Contains(location.TransformedPoint(), fill_rule);
}
-bool LayoutSVGShape::FillContains(const FloatPoint& point,
+bool LayoutSVGShape::FillContains(const HitTestLocation& location,
bool requires_fill,
const WindRule fill_rule) {
- if (!fill_bounding_box_.Contains(point))
+ if (!fill_bounding_box_.Contains(location.TransformedPoint()))
return false;
if (requires_fill && !SVGPaintServer::ExistsForLayoutObject(*this, StyleRef(),
kApplyToFillMode))
return false;
- return ShapeDependentFillContains(point, fill_rule);
+ return ShapeDependentFillContains(location, fill_rule);
}
-bool LayoutSVGShape::StrokeContains(const FloatPoint& point,
+bool LayoutSVGShape::StrokeContains(const HitTestLocation& location,
bool requires_stroke) {
// "A zero value causes no stroke to be painted."
if (StyleRef().SvgStyle().StrokeWidth().IsZero())
return false;
if (requires_stroke) {
- if (!StrokeBoundingBox().Contains(point))
+ if (!StrokeBoundingBox().Contains(location.TransformedPoint()))
return false;
if (!SVGPaintServer::ExistsForLayoutObject(*this, StyleRef(),
kApplyToStrokeMode))
return false;
} else {
- if (!HitTestStrokeBoundingBox().Contains(point))
+ if (!HitTestStrokeBoundingBox().Contains(location.TransformedPoint()))
return false;
}
- return ShapeDependentStrokeContains(point);
+ return ShapeDependentStrokeContains(location);
}
static inline bool TransformOriginIsFixed(const ComputedStyle& style) {
@@ -316,31 +309,35 @@ void LayoutSVGShape::UpdateLayout() {
ClearNeedsLayout();
}
-void LayoutSVGShape::UpdateNonScalingStrokeData() {
- DCHECK(HasNonScalingStroke());
-
+AffineTransform LayoutSVGShape::ComputeNonScalingStrokeTransform() const {
// Compute the CTM to the SVG root. This should probably be the CTM all the
// way to the "canvas" of the page ("host" coordinate system), but with our
// current approach of applying/painting non-scaling-stroke, that can break in
// unpleasant ways (see crbug.com/747708 for an example.) Maybe it would be
// better to apply this effect during rasterization?
const LayoutSVGRoot* svg_root = SVGLayoutSupport::FindTreeRootObject(this);
- AffineTransform t;
- t.Scale(1 / StyleRef().EffectiveZoom())
+ AffineTransform host_transform;
+ host_transform.Scale(1 / StyleRef().EffectiveZoom())
.Multiply(LocalToAncestorTransform(svg_root).ToAffineTransform());
// Width of non-scaling stroke is independent of translation, so zero it out
// here.
- t.SetE(0);
- t.SetF(0);
+ host_transform.SetE(0);
+ host_transform.SetF(0);
+ return host_transform;
+}
+void LayoutSVGShape::UpdateNonScalingStrokeData() {
+ DCHECK(HasNonScalingStroke());
+
+ const AffineTransform transform = ComputeNonScalingStrokeTransform();
auto& rare_data = EnsureRareData();
- if (rare_data.non_scaling_stroke_transform_ != t) {
+ if (rare_data.non_scaling_stroke_transform_ != transform) {
SetShouldDoFullPaintInvalidation(PaintInvalidationReason::kStyle);
- rare_data.non_scaling_stroke_transform_ = t;
+ rare_data.non_scaling_stroke_transform_ = transform;
}
rare_data.non_scaling_stroke_path_ = *path_;
- rare_data.non_scaling_stroke_path_.Transform(t);
+ rare_data.non_scaling_stroke_path_.Transform(transform);
}
void LayoutSVGShape::Paint(const PaintInfo& paint_info) const {
@@ -355,20 +352,23 @@ bool LayoutSVGShape::NodeAtPoint(HitTestResult& result,
// We only draw in the foreground phase, so we only hit-test then.
if (hit_test_action != kHitTestForeground)
return false;
+ if (IsShapeEmpty())
+ return false;
+ const ComputedStyle& style = StyleRef();
+ const PointerEventsHitRules hit_rules(
+ PointerEventsHitRules::SVG_GEOMETRY_HITTESTING,
+ result.GetHitTestRequest(), style.PointerEvents());
+ if (hit_rules.require_visible && style.Visibility() != EVisibility::kVisible)
+ return false;
- base::Optional<HitTestLocation> local_storage;
- const HitTestLocation* local_location =
- SVGLayoutSupport::TransformToUserSpaceAndCheckClipping(
- *this, LocalToSVGParentTransform(), location_in_parent,
- local_storage);
+ TransformedHitTestLocation local_location(location_in_parent,
+ LocalToSVGParentTransform());
if (!local_location)
return false;
+ if (!SVGLayoutSupport::IntersectsClipPath(*this, *local_location))
+ return false;
- PointerEventsHitRules hit_rules(
- PointerEventsHitRules::SVG_GEOMETRY_HITTESTING,
- result.GetHitTestRequest(), StyleRef().PointerEvents());
- if (NodeAtPointInternal(result.GetHitTestRequest(), *local_location,
- hit_rules)) {
+ if (HitTestShape(result.GetHitTestRequest(), *local_location, hit_rules)) {
const LayoutPoint local_layout_point(local_location->TransformedPoint());
UpdateHitTestResult(result, local_layout_point);
if (result.AddNodeToListBasedTestResult(GetElement(), *local_location) ==
@@ -379,61 +379,56 @@ bool LayoutSVGShape::NodeAtPoint(HitTestResult& result,
return false;
}
-bool LayoutSVGShape::NodeAtPointInternal(const HitTestRequest& request,
- const HitTestLocation& local_location,
- PointerEventsHitRules hit_rules) {
- const ComputedStyle& style = StyleRef();
- if (hit_rules.require_visible && style.Visibility() != EVisibility::kVisible)
- return false;
+bool LayoutSVGShape::HitTestShape(const HitTestRequest& request,
+ const HitTestLocation& local_location,
+ PointerEventsHitRules hit_rules) {
if (hit_rules.can_hit_bounding_box &&
local_location.Intersects(ObjectBoundingBox()))
return true;
// TODO(chrishtr): support rect-based intersections in the cases below.
- const SVGComputedStyle& svg_style = style.SvgStyle();
+ const SVGComputedStyle& svg_style = StyleRef().SvgStyle();
if (hit_rules.can_hit_stroke &&
(svg_style.HasStroke() || !hit_rules.require_stroke) &&
- StrokeContains(local_location.TransformedPoint(),
- hit_rules.require_stroke))
+ StrokeContains(local_location, hit_rules.require_stroke))
return true;
WindRule fill_rule = svg_style.FillRule();
if (request.SvgClipContent())
fill_rule = svg_style.ClipRule();
if (hit_rules.can_hit_fill &&
(svg_style.HasFill() || !hit_rules.require_fill) &&
- FillContains(local_location.TransformedPoint(), hit_rules.require_fill,
- fill_rule))
+ FillContains(local_location, hit_rules.require_fill, fill_rule))
return true;
return false;
}
-FloatRect LayoutSVGShape::CalculateObjectBoundingBox() const {
- return GetPath().BoundingRect();
+FloatRect LayoutSVGShape::CalculateStrokeBoundingBox() const {
+ if (!StyleRef().SvgStyle().HasStroke() || IsShapeEmpty())
+ return fill_bounding_box_;
+ if (HasNonScalingStroke())
+ return CalculateNonScalingStrokeBoundingBox();
+ return ApproximateStrokeBoundingBox();
}
-FloatRect LayoutSVGShape::CalculateStrokeBoundingBox() const {
+FloatRect LayoutSVGShape::CalculateNonScalingStrokeBoundingBox() const {
DCHECK(path_);
- FloatRect stroke_bounding_box = fill_bounding_box_;
+ DCHECK(StyleRef().SvgStyle().HasStroke());
+ DCHECK(HasNonScalingStroke());
- if (StyleRef().SvgStyle().HasStroke()) {
- StrokeData stroke_data;
- SVGLayoutSupport::ApplyStrokeStyleToStrokeData(stroke_data, StyleRef(),
- *this, DashScaleFactor());
- if (HasNonScalingStroke()) {
- const auto& non_scaling_transform = NonScalingStrokeTransform();
- if (non_scaling_transform.IsInvertible()) {
- const auto& non_scaling_stroke = NonScalingStrokePath();
- FloatRect stroke_bounding_rect =
- non_scaling_stroke.StrokeBoundingRect(stroke_data);
- stroke_bounding_rect =
- non_scaling_transform.Inverse().MapRect(stroke_bounding_rect);
- stroke_bounding_box.Unite(stroke_bounding_rect);
- }
- } else {
- stroke_bounding_box = ApproximateStrokeBoundingBox(stroke_bounding_box);
- }
- }
+ StrokeData stroke_data;
+ SVGLayoutSupport::ApplyStrokeStyleToStrokeData(stroke_data, StyleRef(), *this,
+ DashScaleFactor());
+ FloatRect stroke_bounding_box = fill_bounding_box_;
+ const auto& non_scaling_transform = NonScalingStrokeTransform();
+ if (non_scaling_transform.IsInvertible()) {
+ const auto& non_scaling_stroke = NonScalingStrokePath();
+ FloatRect stroke_bounding_rect =
+ non_scaling_stroke.StrokeBoundingRect(stroke_data);
+ stroke_bounding_rect =
+ non_scaling_transform.Inverse().MapRect(stroke_bounding_rect);
+ stroke_bounding_box.Unite(stroke_bounding_rect);
+ }
return stroke_bounding_box;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.h
index 098fe31108d..dc37505e219 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.h
@@ -36,7 +36,6 @@
namespace blink {
-class FloatPoint;
class PointerEventsHitRules;
class SVGGeometryElement;
@@ -58,17 +57,12 @@ struct LayoutSVGShapeRareData {
class LayoutSVGShape : public LayoutSVGModelObject {
public:
- explicit LayoutSVGShape(SVGGeometryElement*);
~LayoutSVGShape() override;
void SetNeedsShapeUpdate() { needs_shape_update_ = true; }
void SetNeedsBoundariesUpdate() final { needs_boundaries_update_ = true; }
void SetNeedsTransformUpdate() final { needs_transform_update_ = true; }
- bool NodeAtPointInternal(const HitTestRequest&,
- const HitTestLocation&,
- PointerEventsHitRules);
-
Path& GetPath() const {
DCHECK(path_);
return *path_;
@@ -99,6 +93,7 @@ class LayoutSVGShape : public LayoutSVGModelObject {
return rare_data_->non_scaling_stroke_transform_;
}
+ AffineTransform ComputeNonScalingStrokeTransform() const;
AffineTransform LocalSVGTransform() const final { return local_transform_; }
virtual const Vector<MarkerPosition>* MarkerPositions() const {
@@ -116,6 +111,20 @@ class LayoutSVGShape : public LayoutSVGModelObject {
const char* GetName() const override { return "LayoutSVGShape"; }
protected:
+ // Description of the geometry of the shape for stroking.
+ enum StrokeGeometryClass : uint8_t {
+ kComplex, // We don't know anything about the geometry => use the generic
+ // approximation.
+ kNoMiters, // We know that the shape will not have any joins, so no miters
+ // will be generated. This means we can use an approximation
+ // that does not factor in miters (and thus get tighter
+ // approximated bounds.)
+ kSimple, // We know that the geometry is convex and has no acute angles
+ // (rect, rounded rect, circle, ellipse) => use the simple
+ // approximation.
+ };
+ LayoutSVGShape(SVGGeometryElement*, StrokeGeometryClass);
+
void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
void WillBeDestroyed() override;
@@ -124,31 +133,24 @@ class LayoutSVGShape : public LayoutSVGModelObject {
void ClearPath() { path_.reset(); }
void CreatePath();
+ // Update (cached) shape data and the (object) bounding box.
virtual void UpdateShapeFromElement();
- // Calculates an inclusive bounding box of this shape as if this shape has
- // a stroke. If this shape has a stroke, then m_strokeBoundingBox is returned;
- // otherwise, estimates a bounding box (not necessarily tight) that would
- // include this shape's stroke bounding box if it had a stroke.
- virtual FloatRect HitTestStrokeBoundingBox() const;
- virtual bool ShapeDependentStrokeContains(const FloatPoint&);
- virtual bool ShapeDependentFillContains(const FloatPoint&,
+ FloatRect CalculateStrokeBoundingBox() const;
+ virtual bool ShapeDependentStrokeContains(const HitTestLocation&);
+ virtual bool ShapeDependentFillContains(const HitTestLocation&,
const WindRule) const;
- // Compute an approximation of the bounding box that this stroke geometry
- // would generate when applied to a shape with the (tight-fitting) bounding
- // box |shape_bbox|.
- FloatRect ApproximateStrokeBoundingBox(const FloatRect& shape_bbox) const;
-
FloatRect fill_bounding_box_;
FloatRect stroke_bounding_box_;
+
LayoutSVGShapeRareData& EnsureRareData() const;
private:
// Hit-detection separated for the fill and the stroke
- bool FillContains(const FloatPoint&,
+ bool FillContains(const HitTestLocation&,
bool requires_fill = true,
const WindRule fill_rule = RULE_NONZERO);
- bool StrokeContains(const FloatPoint&, bool requires_stroke = true);
+ bool StrokeContains(const HitTestLocation&, bool requires_stroke = true);
bool IsOfType(LayoutObjectType type) const override {
return type == kLayoutObjectSVGShape ||
@@ -160,11 +162,22 @@ class LayoutSVGShape : public LayoutSVGModelObject {
bool NodeAtPoint(HitTestResult&,
const HitTestLocation& location_in_parent,
const LayoutPoint& accumulated_offset,
- HitTestAction) override;
+ HitTestAction) final;
+ bool HitTestShape(const HitTestRequest&,
+ const HitTestLocation&,
+ PointerEventsHitRules);
FloatRect StrokeBoundingBox() const final { return stroke_bounding_box_; }
- FloatRect CalculateObjectBoundingBox() const;
- FloatRect CalculateStrokeBoundingBox() const;
+
+ // Calculates an inclusive bounding box of this shape as if this shape has a
+ // stroke. If this shape has a stroke, then |stroke_bounding_box_| is
+ // returned; otherwise, estimates a bounding box (not necessarily tight) that
+ // would include this shape's stroke bounding box if it had a stroke.
+ FloatRect HitTestStrokeBoundingBox() const;
+ // Compute an approximation of the bounding box that this stroke geometry
+ // would generate when applied to the shape.
+ FloatRect ApproximateStrokeBoundingBox() const;
+ FloatRect CalculateNonScalingStrokeBoundingBox() const;
void UpdateNonScalingStrokeData();
bool UpdateLocalTransform();
@@ -177,10 +190,10 @@ class LayoutSVGShape : public LayoutSVGModelObject {
std::unique_ptr<Path> path_;
mutable std::unique_ptr<LayoutSVGShapeRareData> rare_data_;
+ StrokeGeometryClass geometry_class_;
bool needs_boundaries_update_ : 1;
bool needs_shape_update_ : 1;
bool needs_transform_update_ : 1;
- bool affected_by_miter_ : 1;
bool transform_uses_reference_box_ : 1;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc
index b187ea377aa..79297b4fae9 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc
@@ -35,12 +35,14 @@
#include "third_party/blink/renderer/core/layout/pointer_events_hit_rules.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_inline.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h"
+#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_root.h"
#include "third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
#include "third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.h"
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/svg_text_painter.h"
#include "third_party/blink/renderer/core/style/shadow_list.h"
#include "third_party/blink/renderer/core/svg/svg_text_element.h"
@@ -113,7 +115,8 @@ void LayoutSVGText::InvalidatePositioningValues(
LayoutInvalidationReasonForTracing reason) {
descendant_text_nodes_.clear();
SetNeedsPositioningValuesUpdate();
- SetNeedsLayoutAndFullPaintInvalidation(reason);
+ // TODO(fs): Restore the passing of |reason| here.
+ LayoutSVGResourceContainer::MarkForLayoutAndParentResourceInvalidation(*this);
}
void LayoutSVGText::SubtreeChildWasAdded() {
@@ -127,7 +130,7 @@ void LayoutSVGText::SubtreeChildWasAdded() {
// The positioning elements cache depends on the size of each text
// layoutObject in the subtree. If this changes, clear the cache. It will be
// rebuilt on the next layout.
- InvalidatePositioningValues(LayoutInvalidationReason::kChildChanged);
+ InvalidatePositioningValues(layout_invalidation_reason::kChildChanged);
SetNeedsTextMetricsUpdate();
}
@@ -140,7 +143,7 @@ void LayoutSVGText::SubtreeChildWillBeRemoved() {
// The positioning elements cache depends on the size of each text
// layoutObject in the subtree. If this changes, clear the cache. It will be
// rebuilt on the next layout.
- InvalidatePositioningValues(LayoutInvalidationReason::kChildChanged);
+ InvalidatePositioningValues(layout_invalidation_reason::kChildChanged);
SetNeedsTextMetricsUpdate();
}
@@ -154,7 +157,7 @@ void LayoutSVGText::SubtreeTextDidChange() {
// The positioning elements cache depends on the size of each text object in
// the subtree. If this changes, clear the cache and mark it for rebuilding
// in the next layout.
- InvalidatePositioningValues(LayoutInvalidationReason::kTextChanged);
+ InvalidatePositioningValues(layout_invalidation_reason::kTextChanged);
SetNeedsTextMetricsUpdate();
}
@@ -314,13 +317,12 @@ bool LayoutSVGText::NodeAtPoint(HitTestResult& result,
if (hit_test_action != kHitTestForeground)
return false;
- base::Optional<HitTestLocation> local_storage;
- const HitTestLocation* local_location =
- SVGLayoutSupport::TransformToUserSpaceAndCheckClipping(
- *this, LocalToSVGParentTransform(), location_in_parent,
- local_storage);
+ TransformedHitTestLocation local_location(location_in_parent,
+ LocalToSVGParentTransform());
if (!local_location)
return false;
+ if (!SVGLayoutSupport::IntersectsClipPath(*this, *local_location))
+ return false;
if (LayoutBlock::NodeAtPoint(result, *local_location, accumulated_offset,
hit_test_action))
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.cc b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.cc
index 0c9e8cf34bc..44562a162ff 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.cc
@@ -276,6 +276,25 @@ FloatRect SVGInlineTextBox::CalculateBoundaries() const {
return text_bounding_rect;
}
+bool SVGInlineTextBox::HitTestFragments(
+ const HitTestLocation& location_in_container) const {
+ auto line_layout_item = LineLayoutSVGInlineText(GetLineLayoutItem());
+ const SimpleFontData* font_data = line_layout_item.ScaledFont().PrimaryFont();
+ DCHECK(font_data);
+ if (!font_data)
+ return false;
+
+ DCHECK(line_layout_item.ScalingFactor());
+ float baseline = font_data->GetFontMetrics().FloatAscent() /
+ line_layout_item.ScalingFactor();
+ for (const SVGTextFragment& fragment : text_fragments_) {
+ FloatQuad fragment_quad = fragment.BoundingQuad(baseline);
+ if (location_in_container.Intersects(fragment_quad))
+ return true;
+ }
+ return false;
+}
+
bool SVGInlineTextBox::NodeAtPoint(HitTestResult& result,
const HitTestLocation& location_in_container,
const LayoutPoint& accumulated_offset,
@@ -299,26 +318,14 @@ bool SVGInlineTextBox::NodeAtPoint(HitTestResult& result,
LayoutRect rect(Location(), Size());
rect.MoveBy(accumulated_offset);
if (location_in_container.Intersects(rect)) {
- const SimpleFontData* font_data =
- line_layout_item.ScaledFont().PrimaryFont();
- DCHECK(font_data);
- if (!font_data)
- return false;
-
- DCHECK(line_layout_item.ScalingFactor());
- float baseline = font_data->GetFontMetrics().FloatAscent() /
- line_layout_item.ScalingFactor();
- for (const SVGTextFragment& fragment : text_fragments_) {
- FloatQuad fragment_quad = fragment.BoundingQuad(baseline);
- if (location_in_container.Intersects(fragment_quad)) {
- line_layout_item.UpdateHitTestResult(
- result,
- location_in_container.Point() - ToLayoutSize(accumulated_offset));
- if (result.AddNodeToListBasedTestResult(line_layout_item.GetNode(),
- location_in_container,
- rect) == kStopHitTesting)
- return true;
- }
+ if (HitTestFragments(location_in_container)) {
+ line_layout_item.UpdateHitTestResult(
+ result,
+ location_in_container.Point() - ToLayoutSize(accumulated_offset));
+ if (result.AddNodeToListBasedTestResult(line_layout_item.GetNode(),
+ location_in_container,
+ rect) == kStopHitTesting)
+ return true;
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.h b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.h
index 00cbed811a4..efaa8c538af 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.h
@@ -97,6 +97,7 @@ class SVGInlineTextBox final : public InlineTextBox {
const ComputedStyle&,
const Font&) const final;
+ bool HitTestFragments(const HitTestLocation& location_in_container) const;
bool NodeAtPoint(HitTestResult&,
const HitTestLocation& location_in_container,
const LayoutPoint& accumulated_offset,
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.cc b/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.cc
index 239e936ee9c..e59c0a20b29 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.cc
@@ -26,6 +26,8 @@
#include "third_party/blink/renderer/core/layout/layout_geometry_map.h"
#include "third_party/blink/renderer/core/layout/subtree_layout_scope.h"
+#include "third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h"
+#include "third_party/blink/renderer/core/layout/svg/layout_svg_image.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h"
@@ -224,6 +226,27 @@ inline void SVGLayoutSupport::UpdateObjectBoundingBox(
object_bounding_box.UniteEvenIfEmpty(other_bounding_box);
}
+static bool HasValidBoundingBoxForContainer(const LayoutObject* object) {
+ if (object->IsSVGShape())
+ return !ToLayoutSVGShape(object)->IsShapeEmpty();
+
+ if (object->IsSVGText())
+ return ToLayoutSVGText(object)->IsObjectBoundingBoxValid();
+
+ if (object->IsSVGHiddenContainer())
+ return false;
+
+ if (object->IsSVGForeignObject())
+ return ToLayoutSVGForeignObject(object)->IsObjectBoundingBoxValid();
+
+ if (object->IsSVGImage())
+ return ToLayoutSVGImage(object)->IsObjectBoundingBoxValid();
+
+ // TODO(fs): Can we refactor this code to include the container case
+ // in a more natural way?
+ return true;
+}
+
void SVGLayoutSupport::ComputeContainerBoundingBoxes(
const LayoutObject* container,
FloatRect& object_bounding_box,
@@ -242,15 +265,8 @@ void SVGLayoutSupport::ComputeContainerBoundingBoxes(
// situation also.
for (LayoutObject* current = container->SlowFirstChild(); current;
current = current->NextSibling()) {
- if (current->IsSVGHiddenContainer())
- continue;
-
- // Don't include elements in the union that do not layout.
- if (current->IsSVGShape() && ToLayoutSVGShape(current)->IsShapeEmpty())
- continue;
-
- if (current->IsSVGText() &&
- !ToLayoutSVGText(current)->IsObjectBoundingBoxValid())
+ // Don't include elements that are not rendered in the union.
+ if (!HasValidBoundingBoxForContainer(current))
continue;
const AffineTransform& transform = current->LocalToSVGParentTransform();
@@ -355,9 +371,10 @@ void SVGLayoutSupport::LayoutChildren(LayoutObject* first_child,
child->LayoutIfNeeded();
} else {
SubtreeLayoutScope layout_scope(*child);
- if (force_child_layout)
+ if (force_child_layout) {
layout_scope.SetNeedsLayout(child,
- LayoutInvalidationReason::kSvgChanged);
+ layout_invalidation_reason::kSvgChanged);
+ }
// Lay out any referenced resources before the child.
LayoutResourcesIfNeeded(*child);
@@ -410,53 +427,44 @@ bool SVGLayoutSupport::HasFilterResource(const LayoutObject& object) {
return resources && resources->Filter();
}
-bool SVGLayoutSupport::PointInClippingArea(const LayoutObject& object,
- const FloatPoint& point) {
+bool SVGLayoutSupport::IntersectsClipPath(const LayoutObject& object,
+ const HitTestLocation& location) {
ClipPathOperation* clip_path_operation = object.StyleRef().ClipPath();
if (!clip_path_operation)
return true;
+ const FloatRect& reference_box = object.ObjectBoundingBox();
if (clip_path_operation->GetType() == ClipPathOperation::SHAPE) {
ShapeClipPathOperation& clip_path =
ToShapeClipPathOperation(*clip_path_operation);
- return clip_path.GetPath(object.ObjectBoundingBox()).Contains(point);
+ return clip_path.GetPath(reference_box)
+ .Contains(location.TransformedPoint());
}
DCHECK_EQ(clip_path_operation->GetType(), ClipPathOperation::REFERENCE);
SVGResources* resources =
SVGResourcesCache::CachedResourcesForLayoutObject(object);
if (!resources || !resources->Clipper())
return true;
- return resources->Clipper()->HitTestClipContent(object.ObjectBoundingBox(),
- point);
+ return resources->Clipper()->HitTestClipContent(reference_box, location);
}
-const HitTestLocation* SVGLayoutSupport::TransformToUserSpaceAndCheckClipping(
- const LayoutObject& object,
- const AffineTransform& local_transform,
- const HitTestLocation& location_in_parent,
- base::Optional<HitTestLocation>& local_storage) {
- // Use a fast path for an identity transform which creates no new
- // HitTestLocation objects or inverse AffineTransforms, and performs no
- // matrix multiplies.
- if (local_transform.IsIdentity()) {
- if (PointInClippingArea(object, location_in_parent.TransformedPoint()))
- return &location_in_parent;
- return nullptr;
- }
- if (!local_transform.IsInvertible())
- return nullptr;
- const AffineTransform inverse = local_transform.Inverse();
- if (location_in_parent.IsRectBasedTest()) {
- local_storage.emplace(
- HitTestLocation(inverse.MapPoint(location_in_parent.TransformedPoint()),
- inverse.MapQuad(location_in_parent.TransformedRect())));
- } else {
- local_storage.emplace(HitTestLocation(
- inverse.MapPoint(location_in_parent.TransformedPoint())));
+bool SVGLayoutSupport::HitTestChildren(LayoutObject* last_child,
+ HitTestResult& result,
+ const HitTestLocation& location,
+ const LayoutPoint& accumulated_offset,
+ HitTestAction hit_test_action) {
+ for (LayoutObject* child = last_child; child;
+ child = child->PreviousSibling()) {
+ if (child->IsSVGForeignObject()) {
+ if (ToLayoutSVGForeignObject(child)->NodeAtPointFromSVG(
+ result, location, accumulated_offset, hit_test_action))
+ return true;
+ } else {
+ if (child->NodeAtPoint(result, location, accumulated_offset,
+ hit_test_action))
+ return true;
+ }
}
-
- if (PointInClippingArea(object, local_storage->TransformedPoint()))
- return &*local_storage;
- return nullptr;
+ return false;
}
DashArray SVGLayoutSupport::ResolveSVGDashArray(
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.h
index 0f06d90882c..5486a303e45 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.h
@@ -73,20 +73,15 @@ class CORE_EXPORT SVGLayoutSupport {
// Determine if the LayoutObject references a filter resource object.
static bool HasFilterResource(const LayoutObject&);
- // Determines whether the passed point lies in a clipping area
- static bool PointInClippingArea(const LayoutObject&, const FloatPoint&);
-
- // Transform |pointInParent| to |object|'s user-space and check if it is
- // within the clipping area. Returns a pointer to a HitTestLocation object
- // to use as the local location. Returns nullptr if the transform is singular
- // or the point is outside the clipping area. The object backing
- // the pointer is either |location_in_parent| or an emplacement of
- // |local_storage|.
- static const HitTestLocation* TransformToUserSpaceAndCheckClipping(
- const LayoutObject&,
- const AffineTransform& local_transform,
- const HitTestLocation& location_in_parent,
- base::Optional<HitTestLocation>& local_storage);
+ // Determine whether the passed location intersects the clip path of |object|.
+ static bool IntersectsClipPath(const LayoutObject&, const HitTestLocation&);
+
+ // Shared child hit-testing code between LayoutSVGRoot/LayoutSVGContainer.
+ static bool HitTestChildren(LayoutObject* last_child,
+ HitTestResult&,
+ const HitTestLocation&,
+ const LayoutPoint& accumulated_offset,
+ HitTestAction);
static void ComputeContainerBoundingBoxes(const LayoutObject* container,
FloatRect& object_bounding_box,
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc b/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc
index c77274eb6e0..9ad37d5e881 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc
@@ -57,6 +57,7 @@
#include "third_party/blink/renderer/core/svg/radial_gradient_attributes.h"
#include "third_party/blink/renderer/core/svg/svg_circle_element.h"
#include "third_party/blink/renderer/core/svg/svg_ellipse_element.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg/svg_filter_element.h"
#include "third_party/blink/renderer/core/svg/svg_line_element.h"
#include "third_party/blink/renderer/core/svg/svg_linear_gradient_element.h"
@@ -172,40 +173,21 @@ static WTF::TextStream& operator<<(WTF::TextStream& ts, const WindRule rule) {
return ts;
}
-namespace {
-
-template <typename Enum>
-String SVGEnumerationToString(Enum value) {
- const SVGEnumerationStringEntries& entries = GetStaticStringEntries<Enum>();
-
- SVGEnumerationStringEntries::const_iterator it = entries.begin();
- SVGEnumerationStringEntries::const_iterator it_end = entries.end();
- for (; it != it_end; ++it) {
- if (value == it->first)
- return it->second;
- }
-
- NOTREACHED();
- return String();
-}
-
-} // namespace
-
static WTF::TextStream& operator<<(WTF::TextStream& ts,
const SVGUnitTypes::SVGUnitType& unit_type) {
- ts << SVGEnumerationToString<SVGUnitTypes::SVGUnitType>(unit_type);
+ ts << GetEnumerationMap<SVGUnitTypes::SVGUnitType>().NameFromValue(unit_type);
return ts;
}
static WTF::TextStream& operator<<(WTF::TextStream& ts,
const SVGMarkerUnitsType& marker_unit) {
- ts << SVGEnumerationToString<SVGMarkerUnitsType>(marker_unit);
+ ts << GetEnumerationMap<SVGMarkerUnitsType>().NameFromValue(marker_unit);
return ts;
}
static WTF::TextStream& operator<<(WTF::TextStream& ts,
const SVGMarkerOrientType& orient_type) {
- ts << SVGEnumerationToString<SVGMarkerOrientType>(orient_type);
+ ts << GetEnumerationMap<SVGMarkerOrientType>().NameFromValue(orient_type);
return ts;
}
@@ -243,7 +225,8 @@ static WTF::TextStream& operator<<(WTF::TextStream& ts, LineJoin style) {
static WTF::TextStream& operator<<(WTF::TextStream& ts,
const SVGSpreadMethodType& type) {
- ts << SVGEnumerationToString<SVGSpreadMethodType>(type).UpperASCII();
+ auto* name = GetEnumerationMap<SVGSpreadMethodType>().NameFromValue(type);
+ ts << String(name).UpperASCII();
return ts;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.cc b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.cc
index 5728ea3e0be..a24b06dc9af 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.cc
@@ -43,7 +43,7 @@
namespace blink {
-using namespace SVGNames;
+using namespace svg_names;
SVGResources::SVGResources() : linked_resource_(nullptr) {}
@@ -59,25 +59,26 @@ static HashSet<AtomicString>& ClipperFilterMaskerTags() {
// http://www.w3.org/TR/SVG11/intro.html#TermContainerElement
// "graphics elements" :
// http://www.w3.org/TR/SVG11/intro.html#TermGraphicsElement
- aTag.LocalName(), circleTag.LocalName(), ellipseTag.LocalName(),
- gTag.LocalName(), imageTag.LocalName(), lineTag.LocalName(),
- markerTag.LocalName(), maskTag.LocalName(), pathTag.LocalName(),
- polygonTag.LocalName(), polylineTag.LocalName(), rectTag.LocalName(),
- svgTag.LocalName(), textTag.LocalName(), useTag.LocalName(),
+ kATag.LocalName(), kCircleTag.LocalName(), kEllipseTag.LocalName(),
+ kGTag.LocalName(), kImageTag.LocalName(), kLineTag.LocalName(),
+ kMarkerTag.LocalName(), kMaskTag.LocalName(), kPathTag.LocalName(),
+ kPolygonTag.LocalName(), kPolylineTag.LocalName(),
+ kRectTag.LocalName(), kSVGTag.LocalName(), kTextTag.LocalName(),
+ kUseTag.LocalName(),
// Not listed in the definitions is the clipPath element, the SVG spec
// says though:
// The "clipPath" element or any of its children can specify property
// "clip-path".
- // So we have to add clipPathTag here, otherwhise clip-path on
+ // So we have to add kClipPathTag here, otherwhise clip-path on
// clipPath will fail. (Already mailed SVG WG, waiting for a solution)
- clipPathTag.LocalName(),
+ kClipPathTag.LocalName(),
// Not listed in the definitions are the text content elements, though
// filter/clipper/masker on tspan/text/.. is allowed.
// (Already mailed SVG WG, waiting for a solution)
- textPathTag.LocalName(), tspanTag.LocalName(),
+ kTextPathTag.LocalName(), kTSpanTag.LocalName(),
// Not listed in the definitions is the foreignObject element, but
// clip-path is a supported attribute.
- foreignObjectTag.LocalName(),
+ kForeignObjectTag.LocalName(),
// Elements that we ignore, as it doesn't make any sense.
// defs, pattern, switch (FIXME: Mail SVG WG about these)
// symbol (is converted to a svg element, when referenced by use, we
@@ -89,8 +90,8 @@ static HashSet<AtomicString>& ClipperFilterMaskerTags() {
bool SVGResources::SupportsMarkers(const SVGElement& element) {
DEFINE_STATIC_LOCAL(HashSet<AtomicString>, tag_list,
({
- lineTag.LocalName(), pathTag.LocalName(),
- polygonTag.LocalName(), polylineTag.LocalName(),
+ kLineTag.LocalName(), kPathTag.LocalName(),
+ kPolygonTag.LocalName(), kPolylineTag.LocalName(),
}));
return tag_list.Contains(element.localName());
}
@@ -99,10 +100,10 @@ static HashSet<AtomicString>& FillAndStrokeTags() {
DEFINE_STATIC_LOCAL(
HashSet<AtomicString>, tag_list,
({
- circleTag.LocalName(), ellipseTag.LocalName(), lineTag.LocalName(),
- pathTag.LocalName(), polygonTag.LocalName(), polylineTag.LocalName(),
- rectTag.LocalName(), textTag.LocalName(), textPathTag.LocalName(),
- tspanTag.LocalName(),
+ kCircleTag.LocalName(), kEllipseTag.LocalName(), kLineTag.LocalName(),
+ kPathTag.LocalName(), kPolygonTag.LocalName(),
+ kPolylineTag.LocalName(), kRectTag.LocalName(), kTextTag.LocalName(),
+ kTextPathTag.LocalName(), kTSpanTag.LocalName(),
}));
return tag_list;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.cc b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.cc
index 9467fbf716a..75f374bfa86 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.cc
@@ -232,7 +232,8 @@ inline void AttributeListsIterator::UpdateCharacterData(
void SVGTextLayoutAttributesBuilder::FillCharacterDataMap(
const TextPosition& position) {
AttributeListsIterator attr_lists(position.element);
- for (unsigned i = 0; attr_lists.HasAttributes() && i < position.length; ++i) {
+ for (wtf_size_t i = 0; attr_lists.HasAttributes() && i < position.length;
+ ++i) {
SVGCharacterData& data =
character_data_map_.insert(position.start + i + 1, SVGCharacterData())
.stored_value->value;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.cc b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.cc
index 8a5581b38b1..0b629e8049e 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.cc
@@ -39,8 +39,7 @@ float SVGTextLayoutEngineSpacing::CalculateCSSSpacing(UChar current_character) {
return 0;
float spacing = font_.GetFontDescription().LetterSpacing();
- if (current_character && last_character &&
- font_.GetFontDescription().WordSpacing()) {
+ if (font_.GetFontDescription().WordSpacing()) {
if (Character::TreatAsSpace(current_character) &&
!Character::TreatAsSpace(last_character))
spacing += font_.GetFontDescription().WordSpacing();
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.cc b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.cc
index 236be0fde74..4c983227f59 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.cc
@@ -556,7 +556,7 @@ static unsigned LogicalOffsetInTextNode(
CollectTextBoxesInLogicalOrder(text_line_layout, text_boxes);
DCHECK(start_text_box);
- size_t index = text_boxes.Find(start_text_box);
+ wtf_size_t index = text_boxes.Find(start_text_box);
DCHECK_NE(index, kNotFound);
unsigned offset = fragment_offset;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.cc b/chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.cc
new file mode 100644
index 00000000000..a576fcbae17
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.cc
@@ -0,0 +1,40 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
+
+#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
+
+namespace blink {
+
+namespace {
+
+const HitTestLocation* InverseTransformLocationIfNeeded(
+ const HitTestLocation& location,
+ const AffineTransform& transform,
+ base::Optional<HitTestLocation>& storage) {
+ if (transform.IsIdentity())
+ return &location;
+ if (!transform.IsInvertible())
+ return nullptr;
+ const AffineTransform inverse = transform.Inverse();
+ FloatPoint transformed_point = inverse.MapPoint(location.TransformedPoint());
+ if (UNLIKELY(location.IsRectBasedTest())) {
+ storage.emplace(transformed_point,
+ inverse.MapQuad(location.TransformedRect()));
+ } else {
+ storage.emplace(transformed_point);
+ }
+ return &*storage;
+}
+
+} // namespace
+
+TransformedHitTestLocation::TransformedHitTestLocation(
+ const HitTestLocation& location,
+ const AffineTransform& transform)
+ : location_(
+ InverseTransformLocationIfNeeded(location, transform, storage_)) {}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h b/chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h
new file mode 100644
index 00000000000..07cfec0e896
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h
@@ -0,0 +1,48 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_TRANSFORMED_HIT_TEST_LOCATION_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_TRANSFORMED_HIT_TEST_LOCATION_H_
+
+#include "base/optional.h"
+#include "third_party/blink/renderer/core/layout/hit_test_location.h"
+
+namespace blink {
+
+class AffineTransform;
+
+// Helper class handling the application of a AffineTransform to a
+// HitTestLocation - producing a new, transformed, HitTestLocation if needed.
+//
+// Encapsulates logic to avoid creating/copying the HitTestLocation for example
+// if the AffineTransform is the identity.
+class TransformedHitTestLocation {
+ DISALLOW_NEW();
+
+ public:
+ // The AffineTransform passed is expected to be the "forward"
+ // transform. The inverse will computed and applied (as needed.)
+ //
+ // If the transform is singular, the bool operator will return
+ // false, in which case the object cannot (must not) be used.
+ TransformedHitTestLocation(const HitTestLocation&, const AffineTransform&);
+
+ const HitTestLocation* operator->() const {
+ DCHECK(location_);
+ return location_;
+ }
+ const HitTestLocation& operator*() const {
+ DCHECK(location_);
+ return *location_;
+ }
+ explicit operator bool() const { return location_; }
+
+ private:
+ base::Optional<HitTestLocation> storage_;
+ const HitTestLocation* location_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_TRANSFORMED_HIT_TEST_LOCATION_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm.h b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm.h
index 184533a01a6..6679dbf838c 100644
--- a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm.h
+++ b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm.h
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_TABLE_LAYOUT_ALGORITHM_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc
index 7110087f99b..f79f71c4310 100644
--- a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc
+++ b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.cc
@@ -281,7 +281,7 @@ void TableLayoutAlgorithmAuto::ComputeIntrinsicLogicalWidths(
bool scale_columns_for_self = ShouldScaleColumnsForSelf(table_);
float remaining_percent = 100;
- for (size_t i = 0; i < layout_struct_.size(); ++i) {
+ for (wtf_size_t i = 0; i < layout_struct_.size(); ++i) {
min_width += layout_struct_[i].effective_min_logical_width;
max_width += layout_struct_[i].effective_max_logical_width;
if (scale_columns_for_self) {
@@ -359,10 +359,10 @@ void TableLayoutAlgorithmAuto::ApplyPreferredLogicalWidthQuirks(
int TableLayoutAlgorithmAuto::CalcEffectiveLogicalWidth() {
int max_logical_width = 0;
- size_t n_eff_cols = layout_struct_.size();
+ wtf_size_t n_eff_cols = layout_struct_.size();
int spacing_in_row_direction = table_->HBorderSpacing();
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (wtf_size_t i = 0; i < n_eff_cols; ++i) {
layout_struct_[i].effective_logical_width = layout_struct_[i].logical_width;
layout_struct_[i].effective_min_logical_width =
layout_struct_[i].min_logical_width;
@@ -370,7 +370,7 @@ int TableLayoutAlgorithmAuto::CalcEffectiveLogicalWidth() {
layout_struct_[i].max_logical_width;
}
- for (size_t i = 0; i < span_cells_.size(); ++i) {
+ for (wtf_size_t i = 0; i < span_cells_.size(); ++i) {
LayoutTableCell* cell = span_cells_[i];
if (!cell)
break;
@@ -385,7 +385,7 @@ int TableLayoutAlgorithmAuto::CalcEffectiveLogicalWidth() {
unsigned eff_col =
table_->AbsoluteColumnToEffectiveColumn(cell->AbsoluteColumnIndex());
- size_t last_col = eff_col;
+ wtf_size_t last_col = eff_col;
int cell_min_logical_width =
(cell->MinPreferredLogicalWidth() + spacing_in_row_direction).ToInt();
int cell_max_logical_width =
@@ -658,7 +658,7 @@ void TableLayoutAlgorithmAuto::UpdateLayout() {
table_->BordersPaddingAndSpacingInRowDirection())
.ToInt();
int available = table_logical_width;
- size_t n_eff_cols = table_->NumEffectiveColumns();
+ unsigned n_eff_cols = table_->NumEffectiveColumns();
// FIXME: It is possible to be called without having properly updated our
// internal representation. This means that our preferred logical widths were
@@ -683,7 +683,7 @@ void TableLayoutAlgorithmAuto::UpdateLayout() {
unsigned num_auto_empty_cells_only = 0;
// fill up every cell with its minWidth
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (unsigned i = 0; i < n_eff_cols; ++i) {
int cell_logical_width = layout_struct_[i].effective_min_logical_width;
layout_struct_[i].computed_logical_width = cell_logical_width;
available -= cell_logical_width;
@@ -715,7 +715,7 @@ void TableLayoutAlgorithmAuto::UpdateLayout() {
// allocate width to percent cols
if (available > 0 && have_percent) {
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (unsigned i = 0; i < n_eff_cols; ++i) {
Length& logical_width = layout_struct_[i].effective_logical_width;
if (logical_width.IsPercentOrCalc()) {
int cell_logical_width =
@@ -751,7 +751,7 @@ void TableLayoutAlgorithmAuto::UpdateLayout() {
// then allocate width to fixed cols
if (available > 0) {
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (unsigned i = 0; i < n_eff_cols; ++i) {
Length& logical_width = layout_struct_[i].effective_logical_width;
if (logical_width.IsFixed() &&
logical_width.Value() > layout_struct_[i].computed_logical_width) {
@@ -806,7 +806,7 @@ void TableLayoutAlgorithmAuto::UpdateLayout() {
DCHECK_EQ(table_->EffectiveColumnPositions().size(), n_eff_cols + 1);
int pos = 0;
- for (size_t i = 0; i < n_eff_cols; ++i) {
+ for (unsigned i = 0; i < n_eff_cols; ++i) {
table_->SetEffectiveColumnPosition(i, pos);
pos += layout_struct_[i].computed_logical_width + table_->HBorderSpacing();
}
@@ -871,7 +871,7 @@ void TableLayoutAlgorithmAuto::DistributeWidthToColumns(int& available,
void TableLayoutAlgorithmAuto::ShrinkColumnWidth(const LengthType& length_type,
int& available) {
- size_t n_eff_cols = table_->NumEffectiveColumns();
+ unsigned n_eff_cols = table_->NumEffectiveColumns();
int logical_width_beyond_min = 0;
for (unsigned i = n_eff_cols; i;) {
--i;
diff --git a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h
index 7aca833f6eb..0169f1e1b49 100644
--- a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h
+++ b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_auto.h
@@ -22,8 +22,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_TABLE_LAYOUT_ALGORITHM_AUTO_H_
#include "third_party/blink/renderer/core/layout/table_layout_algorithm.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.cc b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.cc
index 66cba73d13a..c6cfd51d039 100644
--- a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.cc
+++ b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.cc
@@ -26,7 +26,7 @@
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
#include "third_party/blink/renderer/core/layout/layout_table_col.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
/*
The text below is from the CSS 2.1 specs.
diff --git a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.h b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.h
index 56660f8271f..d929c0201e7 100644
--- a/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.h
+++ b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.h
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_TABLE_LAYOUT_ALGORITHM_FIXED_H_
#include "third_party/blink/renderer/core/layout/table_layout_algorithm.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/text_autosizer.cc b/chromium/third_party/blink/renderer/core/layout/text_autosizer.cc
index 6f4dd575620..9ad78dab1af 100644
--- a/chromium/third_party/blink/renderer/core/layout/text_autosizer.cc
+++ b/chromium/third_party/blink/renderer/core/layout/text_autosizer.cc
@@ -449,6 +449,11 @@ float TextAutosizer::Inflate(LayoutObject* parent,
}
} else if (child->IsLayoutInline()) {
multiplier = Inflate(child, layouter, behavior, multiplier);
+ // If this LayoutInline is an anonymous inline that has multiplied
+ // children, apply the multiplifer to the parent too. We compute
+ // ::first-line style from the style of the parent block.
+ if (multiplier && child->IsAnonymous())
+ has_text_child = true;
} else if (child->IsLayoutBlock() && behavior == kDescendToInnerBlocks &&
!ClassifyBlock(child,
INDEPENDENT | EXPLICIT_WIDTH | SUPPRESSING)) {
@@ -671,7 +676,7 @@ void TextAutosizer::SetAllTextNeedsLayout(LayoutBlock* container) {
} else {
if (object->IsText()) {
object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kTextAutosizing);
+ layout_invalidation_reason::kTextAutosizing);
}
object = object->NextInPreOrder(container);
}
@@ -807,9 +812,9 @@ TextAutosizer::Fingerprint TextAutosizer::ComputeFingerprint(
data.packed_style_properties_ |=
(static_cast<unsigned>(style->Floating()) << 4);
data.packed_style_properties_ |=
- (static_cast<unsigned>(style->Display()) << 6);
- data.packed_style_properties_ |= (style->Width().GetType() << 11);
- // packedStyleProperties effectively using 15 bits now.
+ (static_cast<unsigned>(style->Display()) << 7);
+ data.packed_style_properties_ |= (style->Width().GetType() << 12);
+ // packedStyleProperties effectively using 16 bits now.
// consider for adding: writing mode, padding.
@@ -1158,7 +1163,7 @@ void TextAutosizer::ApplyMultiplier(LayoutObject* layout_object,
ToLayoutText(layout_object)->AutosizingMultiplerChanged();
DCHECK(!layouter || layout_object->IsDescendantOf(&layouter->Root()));
layout_object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kTextAutosizing, kMarkContainerChain,
+ layout_invalidation_reason::kTextAutosizing, kMarkContainerChain,
layouter);
layout_object->MarkContainerNeedsCollectInlines();
break;
diff --git a/chromium/third_party/blink/renderer/core/layout/text_autosizer.h b/chromium/third_party/blink/renderer/core/layout/text_autosizer.h
index 2940200d1bc..b549857b343 100644
--- a/chromium/third_party/blink/renderer/core/layout/text_autosizer.h
+++ b/chromium/third_party/blink/renderer/core/layout/text_autosizer.h
@@ -35,8 +35,8 @@
#include <memory>
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -60,9 +60,11 @@ class SubtreeLayoutScope;
class CORE_EXPORT TextAutosizer final
: public GarbageCollectedFinalized<TextAutosizer> {
public:
+ explicit TextAutosizer(const Document*);
~TextAutosizer();
+
static TextAutosizer* Create(const Document* document) {
- return new TextAutosizer(document);
+ return MakeGarbageCollected<TextAutosizer>(document);
}
// computed_size should include zoom.
@@ -296,8 +298,6 @@ class CORE_EXPORT TextAutosizer final
bool setting_enabled_;
};
- explicit TextAutosizer(const Document*);
-
void BeginLayout(LayoutBlock*, SubtreeLayoutScope*);
void EndLayout(LayoutBlock*);
void InflateAutoTable(LayoutTable*);
diff --git a/chromium/third_party/blink/renderer/core/layout/text_autosizer_test.cc b/chromium/third_party/blink/renderer/core/layout/text_autosizer_test.cc
index e0c52fa94fa..ff3514b6700 100644
--- a/chromium/third_party/blink/renderer/core/layout/text_autosizer_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/text_autosizer_test.cc
@@ -14,7 +14,9 @@
namespace blink {
class TextAutosizerClient : public EmptyChromeClient {
public:
- static TextAutosizerClient* Create() { return new TextAutosizerClient; }
+ static TextAutosizerClient* Create() {
+ return MakeGarbageCollected<TextAutosizerClient>();
+ }
float WindowToViewportScalar(const float value) const override {
return value * device_scale_factor_;
}
@@ -158,29 +160,29 @@ TEST_F(TextAutosizerTest, ParagraphWithChangingTextSizeAdjustment) {
EXPECT_FLOAT_EQ(
40.f, autosized_div->GetLayoutObject()->StyleRef().ComputedFontSize());
- autosized_div->setAttribute(HTMLNames::classAttr, "none");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ autosized_div->setAttribute(html_names::kClassAttr, "none");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(
16.f, autosized_div->GetLayoutObject()->StyleRef().SpecifiedFontSize());
EXPECT_FLOAT_EQ(
16.f, autosized_div->GetLayoutObject()->StyleRef().ComputedFontSize());
- autosized_div->setAttribute(HTMLNames::classAttr, "small");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ autosized_div->setAttribute(html_names::kClassAttr, "small");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(
16.f, autosized_div->GetLayoutObject()->StyleRef().SpecifiedFontSize());
EXPECT_FLOAT_EQ(
8.f, autosized_div->GetLayoutObject()->StyleRef().ComputedFontSize());
- autosized_div->setAttribute(HTMLNames::classAttr, "large");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ autosized_div->setAttribute(html_names::kClassAttr, "large");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(
16.f, autosized_div->GetLayoutObject()->StyleRef().SpecifiedFontSize());
EXPECT_FLOAT_EQ(
24.f, autosized_div->GetLayoutObject()->StyleRef().ComputedFontSize());
- autosized_div->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ autosized_div->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(
16.f, autosized_div->GetLayoutObject()->StyleRef().SpecifiedFontSize());
EXPECT_FLOAT_EQ(
@@ -414,7 +416,7 @@ TEST_F(TextAutosizerTest, ChangingAccessibilityFontScaleFactor) {
autosized->GetLayoutObject()->StyleRef().ComputedFontSize());
GetDocument().GetSettings()->SetAccessibilityFontScaleFactor(2);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(16.f,
autosized->GetLayoutObject()->StyleRef().SpecifiedFontSize());
@@ -473,7 +475,7 @@ TEST_F(TextAutosizerTest, TextSizeAdjustDoesNotDisableAccessibility) {
// Changing the accessibility font scale factor should change the adjusted
// size.
GetDocument().GetSettings()->SetAccessibilityFontScaleFactor(2);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(
16.f,
@@ -534,7 +536,7 @@ TEST_F(TextAutosizerTest, DeviceScaleAdjustmentWithViewport) {
GetDocument().GetSettings()->SetViewportMetaEnabled(true);
GetDocument().GetSettings()->SetDeviceScaleAdjustment(1.5f);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* autosized = GetDocument().getElementById("autosized");
EXPECT_FLOAT_EQ(16.f,
@@ -546,7 +548,7 @@ TEST_F(TextAutosizerTest, DeviceScaleAdjustmentWithViewport) {
autosized->GetLayoutObject()->StyleRef().ComputedFontSize());
GetDocument().GetSettings()->SetViewportMetaEnabled(false);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
autosized = GetDocument().getElementById("autosized");
EXPECT_FLOAT_EQ(16.f,
@@ -572,7 +574,7 @@ TEST_F(TextAutosizerTest, ChangingSuperClusterFirstText) {
<div id='shortText'>short blah blah</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* long_text_element = GetDocument().getElementById("longText");
long_text_element->SetInnerHTMLFromString(
@@ -588,7 +590,7 @@ TEST_F(TextAutosizerTest, ChangingSuperClusterFirstText) {
"qui officia deserunt"
" mollit anim id est laborum.",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject* long_text =
GetDocument().getElementById("longText")->GetLayoutObject();
@@ -617,7 +619,7 @@ TEST_F(TextAutosizerTest, ChangingSuperClusterSecondText) {
<div id='longText'>short blah blah</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* long_text_element = GetDocument().getElementById("longText");
long_text_element->SetInnerHTMLFromString(
@@ -633,7 +635,7 @@ TEST_F(TextAutosizerTest, ChangingSuperClusterSecondText) {
"qui officia deserunt"
" mollit anim id est laborum.",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject* long_text =
GetDocument().getElementById("longText")->GetLayoutObject();
@@ -662,7 +664,7 @@ TEST_F(TextAutosizerTest, AddingSuperCluster) {
</div>
<div id='container'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* container = GetDocument().getElementById("container");
container->SetInnerHTMLFromString(
@@ -680,7 +682,7 @@ TEST_F(TextAutosizerTest, AddingSuperCluster) {
" mollit anim id est laborum."
"</div>",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject* long_text =
GetDocument().getElementById("longText")->GetLayoutObject();
@@ -710,7 +712,7 @@ TEST_F(TextAutosizerTest, ChangingInheritedClusterTextInsideSuperCluster) {
<div class='cluster' id='shortText'>short blah blah</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* long_text_element = GetDocument().getElementById("longText");
long_text_element->SetInnerHTMLFromString(
@@ -726,7 +728,7 @@ TEST_F(TextAutosizerTest, ChangingInheritedClusterTextInsideSuperCluster) {
"qui officia deserunt"
" mollit anim id est laborum.",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject* long_text =
GetDocument().getElementById("longText")->GetLayoutObject();
@@ -776,7 +778,7 @@ TEST_F(TextAutosizerTest, AutosizeInnerContentOfRuby) {
</ruby>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ruby_inline = GetDocument().getElementById("rubyInline");
EXPECT_FLOAT_EQ(
@@ -826,15 +828,15 @@ TEST_F(TextAutosizerTest, ResizeAndGlyphOverflowChanged) {
" <span style='font-size:15px'>n</span>"
"</body>",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().GetSettings()->SetTextAutosizingWindowSizeOverride(
IntSize(640, 360));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().GetSettings()->SetTextAutosizingWindowSizeOverride(
IntSize(360, 640));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
TEST_F(TextAutosizerTest, narrowContentInsideNestedWideBlock) {
@@ -864,7 +866,7 @@ TEST_F(TextAutosizerTest, narrowContentInsideNestedWideBlock) {
" </div>"
"</body>",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* content = GetDocument().getElementById("content");
//(content width = 200px) / (window width = 320px) < 1.0f, multiplier = 1.0,
@@ -896,7 +898,7 @@ TEST_F(TextAutosizerTest, LayoutViewWidthProvider) {
" <div id='panel'></div>"
"</body>",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* content = GetDocument().getElementById("content");
// (specified font-size = 16px) * (viewport width = 800px) /
@@ -906,7 +908,7 @@ TEST_F(TextAutosizerTest, LayoutViewWidthProvider) {
GetDocument().getElementById("panel")->SetInnerHTMLFromString("insert text");
content->SetInnerHTMLFromString(content->InnerHTMLAsString());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// (specified font-size = 16px) * (viewport width = 800px) /
// (window width = 320px) = 40px.
@@ -939,7 +941,7 @@ TEST_F(TextAutosizerTest, MultiColumns) {
" <div> hello </div>"
"</body>",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = GetDocument().getElementById("target");
// (specified font-size = 16px) * ( thread flow layout width = 800px / 3) /
diff --git a/chromium/third_party/blink/renderer/core/layout/text_decoration_offset_base.h b/chromium/third_party/blink/renderer/core/layout/text_decoration_offset_base.h
index 7c2c9cc92d2..3d6f46530c5 100644
--- a/chromium/third_party/blink/renderer/core/layout/text_decoration_offset_base.h
+++ b/chromium/third_party/blink/renderer/core/layout/text_decoration_offset_base.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/traced_layout_object.cc b/chromium/third_party/blink/renderer/core/layout/traced_layout_object.cc
index 149111f0a20..68c51e86344 100644
--- a/chromium/third_party/blink/renderer/core/layout/traced_layout_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/traced_layout_object.cc
@@ -30,7 +30,7 @@ void DumpToTracedValue(const LayoutObject& object,
traced_value->SetString("htmlId", element.GetIdAttribute());
if (element.HasClass()) {
traced_value->BeginArray("classNames");
- for (size_t i = 0; i < element.ClassNames().size(); ++i)
+ for (wtf_size_t i = 0; i < element.ClassNames().size(); ++i)
traced_value->PushString(element.ClassNames()[i]);
traced_value->EndArray();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/visual_rect_mapping_test.cc b/chromium/third_party/blink/renderer/core/layout/visual_rect_mapping_test.cc
index ede3906bcba..d7de7b34acc 100644
--- a/chromium/third_party/blink/renderer/core/layout/visual_rect_mapping_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/visual_rect_mapping_test.cc
@@ -130,7 +130,7 @@ TEST_P(VisualRectMappingTest, LayoutText) {
auto* text = GetLayoutObjectByElementId("text")->SlowFirstChild();
container->SetScrollTop(LayoutUnit(50));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutRect original_rect(0, 60, 20, 80);
LayoutRect rect = original_rect;
@@ -164,7 +164,7 @@ TEST_P(VisualRectMappingTest, LayoutInline) {
LayoutObject* leaf = container->LastChild();
container->SetScrollTop(LayoutUnit(50));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutRect original_rect(0, 60, 20, 80);
LayoutRect rect = original_rect;
@@ -198,7 +198,7 @@ TEST_P(VisualRectMappingTest, LayoutView) {
SetChildFrameHTML(
"<style>body { margin: 0; }</style>"
"<span><img style='width: 20px; height: 100px'></span>text text text");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* frame_container =
ToLayoutBlock(GetLayoutObjectByElementId("frameContainer"));
@@ -210,7 +210,7 @@ TEST_P(VisualRectMappingTest, LayoutView) {
// rect is 13, so height should be clipped to (50 - 13) == 37.
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 47), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutRect original_rect(4, 60, 20, 80);
LayoutRect rect = original_rect;
@@ -246,7 +246,7 @@ TEST_P(VisualRectMappingTest, LayoutViewSubpixelRounding) {
left: 0.5px'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* frame_container =
ToLayoutBlock(GetLayoutObjectByElementId("frameContainer"));
@@ -273,7 +273,7 @@ TEST_P(VisualRectMappingTest, LayoutViewDisplayNone) {
SetChildFrameHTML(
"<style>body { margin: 0; }</style>"
"<div style='width:100px;height:100px;'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* frame_container =
ToLayoutBlock(GetLayoutObjectByElementId("frameContainer"));
@@ -285,7 +285,7 @@ TEST_P(VisualRectMappingTest, LayoutViewDisplayNone) {
// mapped rect is valid before display:none is set on the iframe.
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 47), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutRect original_rect(4, 60, 20, 80);
LayoutRect rect = original_rect;
@@ -294,7 +294,7 @@ TEST_P(VisualRectMappingTest, LayoutViewDisplayNone) {
Element* frame_element = GetDocument().getElementById("frame");
frame_element->SetInlineStyleProperty(CSSPropertyDisplay, "none");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
frame_body = ToLayoutBlock(ChildDocument().body()->GetLayoutObject());
EXPECT_EQ(nullptr, frame_body);
@@ -395,7 +395,7 @@ TEST_P(VisualRectMappingTest, ContainerOverflowScroll) {
EXPECT_EQ(LayoutUnit(), container->ScrollLeft());
container->SetScrollTop(LayoutUnit(7));
container->SetScrollLeft(LayoutUnit(8));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* target = ToLayoutBlock(GetLayoutObjectByElementId("target"));
LayoutRect target_local_visual_rect = target->LocalVisualRect();
@@ -458,7 +458,7 @@ TEST_P(VisualRectMappingTest, ContainerFlippedWritingModeAndOverflowScroll) {
container->SetScrollTop(LayoutUnit(7));
// Scroll to the right by 8 pixels.
container->SetScrollLeft(LayoutUnit(142));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* target = ToLayoutBlock(GetLayoutObjectByElementId("target"));
LayoutRect target_local_visual_rect = target->LocalVisualRect();
@@ -526,7 +526,7 @@ TEST_P(VisualRectMappingTest, ContainerOverflowHidden) {
EXPECT_EQ(LayoutUnit(), container->ScrollLeft());
container->SetScrollTop(LayoutUnit(27));
container->SetScrollLeft(LayoutUnit(28));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* target = ToLayoutBlock(GetLayoutObjectByElementId("target"));
LayoutRect target_local_visual_rect = target->LocalVisualRect();
@@ -563,7 +563,7 @@ TEST_P(VisualRectMappingTest, ContainerFlippedWritingModeAndOverflowHidden) {
EXPECT_EQ(LayoutUnit(150), container->ScrollLeft());
container->SetScrollTop(LayoutUnit(7));
container->SetScrollLeft(LayoutUnit(82)); // Scroll to the right by 8 pixels.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* target = ToLayoutBlock(GetLayoutObjectByElementId("target"));
LayoutRect target_local_visual_rect = target->LocalVisualRect();
@@ -608,7 +608,7 @@ TEST_P(VisualRectMappingTest, ContainerAndTargetDifferentFlippedWritingMode) {
container->SetScrollTop(LayoutUnit(7));
container->SetScrollLeft(
LayoutUnit(142)); // Scroll to the right by 8 pixels.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* target = ToLayoutBlock(GetLayoutObjectByElementId("target"));
LayoutRect target_local_visual_rect = target->LocalVisualRect();
@@ -653,7 +653,7 @@ TEST_P(VisualRectMappingTest,
LayoutBlock* scroller = ToLayoutBlock(GetLayoutObjectByElementId("scroller"));
scroller->SetScrollTop(LayoutUnit(77));
scroller->SetScrollLeft(LayoutUnit(88));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* normal_flow =
ToLayoutBlock(GetLayoutObjectByElementId("normal-flow"));
@@ -928,7 +928,7 @@ TEST_P(VisualRectMappingTest, PerspectivePlusScroll) {
LayoutBlock* container =
ToLayoutBlock(GetLayoutObjectByElementId("container"));
ToElement(container->GetNode())->scrollTo(0, 5);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutBlock* target = ToLayoutBlock(GetLayoutObjectByElementId("target"));
LayoutRect originalRect(0, 0, 100, 100);
@@ -959,7 +959,7 @@ TEST_P(VisualRectMappingTest, FixedContentsInIframe) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* fixed = ChildDocument().getElementById("fixed")->GetLayoutObject();
auto* root_view = fixed->View();
while (root_view->GetFrame()->OwnerLayoutObject())
@@ -971,7 +971,7 @@ TEST_P(VisualRectMappingTest, FixedContentsInIframe) {
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0, 50), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The fixed element should not scroll so the mapped visual rect should not
// have changed.
@@ -1005,7 +1005,7 @@ TEST_P(VisualRectMappingTest, FixedContentsWithScrollOffset) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 50),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The fixed element does not scroll but the ancestor does which changes the
// visual rect.
@@ -1033,7 +1033,7 @@ TEST_P(VisualRectMappingTest, FixedContentsUnderViewWithScrollOffset) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 50),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Results of mapping to ancestor are in absolute coordinates of the
// ancestor. Therefore a fixed-position element is (reverse) offset by scroll.
diff --git a/chromium/third_party/blink/renderer/core/loader/BUILD.gn b/chromium/third_party/blink/renderer/core/loader/BUILD.gn
index 7d118b1f513..5ea3adbbe9d 100644
--- a/chromium/third_party/blink/renderer/core/loader/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/loader/BUILD.gn
@@ -54,6 +54,8 @@ blink_core_sources("loader") {
"mixed_content_checker.h",
"modulescript/document_module_script_fetcher.cc",
"modulescript/document_module_script_fetcher.h",
+ "modulescript/installed_service_worker_module_script_fetcher.cc",
+ "modulescript/installed_service_worker_module_script_fetcher.h",
"modulescript/module_script_creation_params.h",
"modulescript/module_script_fetch_request.h",
"modulescript/module_script_fetcher.cc",
diff --git a/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.cc b/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.cc
index c3bc43524af..d3eaed46e86 100644
--- a/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.cc
+++ b/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.cc
@@ -56,17 +56,21 @@ const WebFeature kTextXmlFeatures[2][2] = {
// Helper function to decide what to do with with a given mime type. This takes
// - a mime type
-// - inputs that affect the decision (is_same_origin, is_worker_global_scope).
+// - inputs that affect the decision (is_same_origin, mime_type_check_mode).
//
// The return value determines whether this mime should be allowed or blocked.
// Additionally, warn returns whether we should log a console warning about
// expected future blocking of this resource. 'counter' determines which
-// Use counter should be used to count this.
+// Use counter should be used to count this. 'is_worker_global_scope' is used
+// for choosing 'counter' value.
bool AllowMimeTypeAsScript(const String& mime_type,
bool same_origin,
+ AllowedByNosniff::MimeTypeCheck mime_type_check_mode,
bool is_worker_global_scope,
bool& warn,
WebFeature& counter) {
+ using MimeTypeCheck = AllowedByNosniff::MimeTypeCheck;
+
// The common case: A proper JavaScript MIME type
if (MIMETypeRegistry::IsSupportedJavaScriptMIMEType(mime_type))
return true;
@@ -94,7 +98,7 @@ bool AllowMimeTypeAsScript(const String& mime_type,
// we still wish to accept them (or log them using UseCounter, or add a
// deprecation warning to the console).
- if (!is_worker_global_scope &&
+ if (mime_type_check_mode == MimeTypeCheck::kLax &&
mime_type.StartsWithIgnoringASCIICase("text/") &&
MIMETypeRegistry::IsLegacySupportedJavaScriptLanguage(
mime_type.Substring(5))) {
@@ -116,22 +120,25 @@ bool AllowMimeTypeAsScript(const String& mime_type,
// Depending on RuntimeEnabledFeatures, we'll allow, allow-but-warn, or block
// these types when we're in a worker.
- bool allow = !is_worker_global_scope ||
+ bool allow = mime_type_check_mode == MimeTypeCheck::kLax ||
!RuntimeEnabledFeatures::WorkerNosniffBlockEnabled();
- warn = allow && is_worker_global_scope &&
+ warn = allow && mime_type_check_mode == MimeTypeCheck::kStrict &&
RuntimeEnabledFeatures::WorkerNosniffWarnEnabled();
return allow;
}
-bool MimeTypeAsScriptImpl(ExecutionContext* execution_context,
- const ResourceResponse& response,
- bool is_worker_global_scope) {
+} // namespace
+
+bool AllowedByNosniff::MimeTypeAsScript(ExecutionContext* execution_context,
+ const ResourceResponse& response,
+ MimeTypeCheck mime_type_check_mode) {
// The content type is really only meaningful for the http:-family & data
// schemes.
bool is_http_family_or_data = response.Url().ProtocolIsInHTTPFamily() ||
response.Url().ProtocolIsData();
if (!is_http_family_or_data &&
- response.Url().LastPathComponent().EndsWith(".js")) {
+ (response.Url().LastPathComponent().EndsWith(".js") ||
+ response.Url().LastPathComponent().EndsWith(".mjs"))) {
return true;
}
@@ -139,7 +146,7 @@ bool MimeTypeAsScriptImpl(ExecutionContext* execution_context,
// Allowed by nosniff?
if (!(ParseContentTypeOptionsHeader(response.HttpHeaderField(
- HTTPNames::X_Content_Type_Options)) != kContentTypeOptionsNosniff ||
+ http_names::kXContentTypeOptions)) != kContentTypeOptionsNosniff ||
MIMETypeRegistry::IsSupportedJavaScriptMIMEType(mime_type))) {
execution_context->AddConsoleMessage(ConsoleMessage::Create(
kSecurityMessageSource, kErrorMessageLevel,
@@ -163,8 +170,9 @@ bool MimeTypeAsScriptImpl(ExecutionContext* execution_context,
const WebFeature kWebFeatureNone = WebFeature::kNumberOfFeatures;
bool warn = false;
WebFeature counter = kWebFeatureNone;
- bool allow = AllowMimeTypeAsScript(mime_type, same_origin,
- is_worker_global_scope, warn, counter);
+ bool allow = AllowMimeTypeAsScript(
+ mime_type, same_origin, mime_type_check_mode,
+ execution_context->IsWorkerGlobalScope(), warn, counter);
// These record usages for two MIME types (without subtypes), per same/cross
// origin.
@@ -191,20 +199,4 @@ bool MimeTypeAsScriptImpl(ExecutionContext* execution_context,
return allow;
}
-} // namespace
-
-bool AllowedByNosniff::MimeTypeAsScript(ExecutionContext* execution_context,
- const ResourceResponse& response) {
- return MimeTypeAsScriptImpl(execution_context, response,
- execution_context->IsWorkerGlobalScope());
-}
-
-bool AllowedByNosniff::MimeTypeAsScriptForTesting(
- ExecutionContext* execution_context,
- const ResourceResponse& response,
- bool is_worker_global_scope) {
- return MimeTypeAsScriptImpl(execution_context, response,
- is_worker_global_scope);
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.h b/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.h
index 757f0f8cb26..16b4b5ad649 100644
--- a/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.h
+++ b/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff.h
@@ -13,12 +13,11 @@ class ResourceResponse;
class CORE_EXPORT AllowedByNosniff {
public:
- static bool MimeTypeAsScript(ExecutionContext*, const ResourceResponse&);
+ enum class MimeTypeCheck { kStrict, kLax };
- // For testing:
- static bool MimeTypeAsScriptForTesting(ExecutionContext*,
- const ResourceResponse&,
- bool is_worker_global_scope);
+ static bool MimeTypeAsScript(ExecutionContext*,
+ const ResourceResponse&,
+ MimeTypeCheck mime_type_check_mode);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff_test.cc b/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff_test.cc
index 28421ee666d..60163924838 100644
--- a/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/allowed_by_nosniff_test.cc
@@ -14,6 +14,8 @@
namespace blink {
+using MimeTypeCheck = AllowedByNosniff::MimeTypeCheck;
+
class AllowedByNosniffTest : public testing::Test {
public:
void SetUp() override {
@@ -108,10 +110,10 @@ TEST_F(AllowedByNosniffTest, AllowedOrNot) {
RuntimeEnabledFeatures::SetWorkerNosniffBlockEnabled(false);
RuntimeEnabledFeatures::SetWorkerNosniffWarnEnabled(false);
size_t message_count = ConsoleMessageStoreSize();
- EXPECT_EQ(testcase.allowed,
- AllowedByNosniff::MimeTypeAsScript(doc(), response));
- EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScriptForTesting(
- doc(), response, true));
+ EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScript(
+ doc(), response, MimeTypeCheck::kLax));
+ EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScript(
+ doc(), response, MimeTypeCheck::kStrict));
EXPECT_EQ(ConsoleMessageStoreSize(), message_count + 2 * !testcase.allowed);
// Nosniff worker blocked: Workers follow the 'strict_allow' setting.
@@ -119,12 +121,12 @@ TEST_F(AllowedByNosniffTest, AllowedOrNot) {
RuntimeEnabledFeatures::SetWorkerNosniffBlockEnabled(true);
RuntimeEnabledFeatures::SetWorkerNosniffWarnEnabled(false);
message_count = ConsoleMessageStoreSize();
- EXPECT_EQ(testcase.allowed,
- AllowedByNosniff::MimeTypeAsScript(doc(), response));
+ EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScript(
+ doc(), response, MimeTypeCheck::kLax));
EXPECT_EQ(ConsoleMessageStoreSize(), message_count + !testcase.allowed);
- EXPECT_EQ(
- testcase.strict_allowed,
- AllowedByNosniff::MimeTypeAsScriptForTesting(doc(), response, true));
+ EXPECT_EQ(testcase.strict_allowed,
+ AllowedByNosniff::MimeTypeAsScript(doc(), response,
+ MimeTypeCheck::kStrict));
EXPECT_EQ(ConsoleMessageStoreSize(),
message_count + !testcase.allowed + !testcase.strict_allowed);
@@ -133,11 +135,11 @@ TEST_F(AllowedByNosniffTest, AllowedOrNot) {
RuntimeEnabledFeatures::SetWorkerNosniffBlockEnabled(false);
RuntimeEnabledFeatures::SetWorkerNosniffWarnEnabled(true);
message_count = ConsoleMessageStoreSize();
- EXPECT_EQ(testcase.allowed,
- AllowedByNosniff::MimeTypeAsScript(doc(), response));
+ EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScript(
+ doc(), response, MimeTypeCheck::kLax));
EXPECT_EQ(ConsoleMessageStoreSize(), message_count + !testcase.allowed);
- EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScriptForTesting(
- doc(), response, true));
+ EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScript(
+ doc(), response, MimeTypeCheck::kStrict));
EXPECT_EQ(ConsoleMessageStoreSize(),
message_count + !testcase.allowed + !testcase.strict_allowed);
}
@@ -184,7 +186,7 @@ TEST_F(AllowedByNosniffTest, Counters) {
ResourceResponse response(KURL(testcase.url));
response.SetHTTPHeaderField("Content-Type", testcase.mimetype);
- AllowedByNosniff::MimeTypeAsScript(doc(), response);
+ AllowedByNosniff::MimeTypeAsScript(doc(), response, MimeTypeCheck::kLax);
EXPECT_TRUE(UseCounter::IsCounted(*doc(), testcase.expected));
}
}
@@ -207,6 +209,11 @@ TEST_F(AllowedByNosniffTest, AllTheSchemes) {
{"chrome://dino/dino.css", false},
{"ftp://example.com/bla.js", true},
{"ftp://example.com/bla.txt", false},
+
+ {"file://home/potato.txt", false},
+ {"file://home/potato.js", true},
+ {"file://home/potato.mjs", true},
+ {"chrome://dino/dino.mjs", true},
};
for (auto& testcase : data) {
@@ -216,8 +223,8 @@ TEST_F(AllowedByNosniffTest, AllTheSchemes) {
ResourceResponse response(KURL(testcase.url));
response.SetHTTPHeaderField("Content-Type", "invalid");
response.SetHTTPHeaderField("X-Content-Type-Options", "nosniff");
- EXPECT_EQ(testcase.allowed,
- AllowedByNosniff::MimeTypeAsScript(doc(), response));
+ EXPECT_EQ(testcase.allowed, AllowedByNosniff::MimeTypeAsScript(
+ doc(), response, MimeTypeCheck::kLax));
}
}
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.cc b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.cc
index f0aa3cdf1ac..9cced5e52dc 100644
--- a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.cc
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.cc
@@ -89,7 +89,7 @@ void ApplicationCache::abort() {
}
const AtomicString& ApplicationCache::InterfaceName() const {
- return EventTargetNames::ApplicationCache;
+ return event_target_names::kApplicationCache;
}
ExecutionContext* ApplicationCache::GetExecutionContext() const {
@@ -100,24 +100,24 @@ const AtomicString& ApplicationCache::ToEventType(
ApplicationCacheHost::EventID id) {
switch (id) {
case ApplicationCacheHost::kCheckingEvent:
- return EventTypeNames::checking;
+ return event_type_names::kChecking;
case ApplicationCacheHost::kErrorEvent:
- return EventTypeNames::error;
+ return event_type_names::kError;
case ApplicationCacheHost::kNoupdateEvent:
- return EventTypeNames::noupdate;
+ return event_type_names::kNoupdate;
case ApplicationCacheHost::kDownloadingEvent:
- return EventTypeNames::downloading;
+ return event_type_names::kDownloading;
case ApplicationCacheHost::kProgressEvent:
- return EventTypeNames::progress;
+ return event_type_names::kProgress;
case ApplicationCacheHost::kUpdatereadyEvent:
- return EventTypeNames::updateready;
+ return event_type_names::kUpdateready;
case ApplicationCacheHost::kCachedEvent:
- return EventTypeNames::cached;
+ return event_type_names::kCached;
case ApplicationCacheHost::kObsoleteEvent:
- return EventTypeNames::obsolete;
+ return event_type_names::kObsolete;
}
NOTREACHED();
- return EventTypeNames::error;
+ return event_type_names::kError;
}
void ApplicationCache::RecordAPIUseType() const {
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.h b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.h
index 88bd1b95157..0112a5a8016 100644
--- a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.h
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.h
@@ -55,14 +55,14 @@ class ApplicationCache final : public EventTargetWithInlineData,
// Explicitly named attribute event listener helpers
- DEFINE_ATTRIBUTE_EVENT_LISTENER(checking);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(noupdate);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(downloading);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(updateready);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(cached);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(obsolete);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(checking, kChecking);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(noupdate, kNoupdate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(downloading, kDownloading);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(progress, kProgress);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(updateready, kUpdateready);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(cached, kCached);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(obsolete, kObsolete);
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
diff --git a/chromium/third_party/blink/renderer/core/loader/base_fetch_context.cc b/chromium/third_party/blink/renderer/core/loader/base_fetch_context.cc
index 02ac5cc691f..ceac85e10cf 100644
--- a/chromium/third_party/blink/renderer/core/loader/base_fetch_context.cc
+++ b/chromium/third_party/blink/renderer/core/loader/base_fetch_context.cc
@@ -5,8 +5,8 @@
#include "third_party/blink/renderer/core/loader/base_fetch_context.h"
#include "services/network/public/mojom/request_context_frame_type.mojom-blink.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -41,7 +41,7 @@ const char* GetDestinationFromContext(mojom::RequestContextType context) {
case mojom::RequestContextType::XML_HTTP_REQUEST:
case mojom::RequestContextType::SUBRESOURCE:
case mojom::RequestContextType::PREFETCH:
- return "\"\"";
+ return "";
case mojom::RequestContextType::CSP_REPORT:
return "report";
case mojom::RequestContextType::AUDIO:
@@ -118,12 +118,13 @@ void BaseFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request,
// no matter what now.
if (!request.DidSetHTTPReferrer()) {
String referrer_to_use = request.ReferrerString();
- ReferrerPolicy referrer_policy_to_use = request.GetReferrerPolicy();
+ network::mojom::ReferrerPolicy referrer_policy_to_use =
+ request.GetReferrerPolicy();
if (referrer_to_use == Referrer::ClientReferrerString())
referrer_to_use = GetFetchClientSettingsObject()->GetOutgoingReferrer();
- if (referrer_policy_to_use == kReferrerPolicyDefault) {
+ if (referrer_policy_to_use == network::mojom::ReferrerPolicy::kDefault) {
referrer_policy_to_use =
GetFetchClientSettingsObject()->GetReferrerPolicy();
}
@@ -150,6 +151,12 @@ void BaseFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request,
if (blink::RuntimeEnabledFeatures::SecMetadataEnabled()) {
const char* destination_value =
GetDestinationFromContext(request.GetRequestContext());
+
+ // If the request's destination is the empty string (e.g. `fetch()`), then
+ // we'll use the identifier "empty" instead.
+ if (strlen(destination_value) == 0)
+ destination_value = "empty";
+
// We'll handle adding the header to navigations outside of Blink.
if (strncmp(destination_value, "document", 8) != 0 &&
request.GetRequestContext() != mojom::RequestContextType::INTERNAL) {
@@ -160,7 +167,8 @@ void BaseFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request,
} else {
OriginAccessEntry access_entry(
request.Url().Protocol(), request.Url().Host(),
- network::cors::OriginAccessEntry::kAllowRegisterableDomains);
+ network::mojom::CorsOriginAccessMatchMode::
+ kAllowRegisterableDomains);
if (access_entry.MatchesOrigin(*GetSecurityOrigin()) ==
network::cors::OriginAccessEntry::kMatchesOrigin) {
site_value = "same-site";
@@ -318,14 +326,14 @@ BaseFetchContext::CanRequestInternal(
}
if (request_mode == network::mojom::FetchRequestMode::kSameOrigin &&
- CORS::CalculateCORSFlag(url, origin.get(), request_mode)) {
+ cors::CalculateCorsFlag(url, origin.get(), request_mode)) {
PrintAccessDeniedMessage(url);
return ResourceRequestBlockedReason::kOrigin;
}
// User Agent CSS stylesheets should only support loading images and should be
// restricted to data urls.
- if (options.initiator_info.name == FetchInitiatorTypeNames::uacss) {
+ if (options.initiator_info.name == fetch_initiator_type_names::kUacss) {
if (type == ResourceType::kImage && url.ProtocolIsData()) {
return base::nullopt;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/base_fetch_context.h b/chromium/third_party/blink/renderer/core/loader/base_fetch_context.h
index 568c033a073..59b0488157b 100644
--- a/chromium/third_party/blink/renderer/core/loader/base_fetch_context.h
+++ b/chromium/third_party/blink/renderer/core/loader/base_fetch_context.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_BASE_FETCH_CONTEXT_H_
#include "base/optional.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -15,7 +16,6 @@
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
namespace blink {
@@ -48,8 +48,6 @@ class CORE_EXPORT BaseFetchContext : public FetchContext {
void Trace(blink::Visitor*) override;
- virtual const FetchClientSettingsObject* GetFetchClientSettingsObject()
- const = 0;
virtual KURL GetSiteForCookies() const = 0;
virtual SubresourceFilter* GetSubresourceFilter() const = 0;
virtual PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints()
diff --git a/chromium/third_party/blink/renderer/core/loader/base_fetch_context_test.cc b/chromium/third_party/blink/renderer/core/loader/base_fetch_context_test.cc
index 6aa47b37e9d..afe9fc6fe50 100644
--- a/chromium/third_party/blink/renderer/core/loader/base_fetch_context_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/base_fetch_context_test.cc
@@ -47,7 +47,8 @@ class MockBaseFetchContext final : public BaseFetchContext {
execution_context->GetTaskRunner(blink::TaskType::kInternalTest)),
execution_context_(execution_context),
fetch_client_settings_object_(
- new FetchClientSettingsObjectImpl(*execution_context)) {}
+ MakeGarbageCollected<FetchClientSettingsObjectImpl>(
+ *execution_context)) {}
~MockBaseFetchContext() override = default;
// BaseFetchContext overrides:
@@ -127,10 +128,11 @@ class MockBaseFetchContext final : public BaseFetchContext {
class BaseFetchContextTest : public testing::Test {
protected:
void SetUp() override {
- execution_context_ = new NullExecutionContext();
+ execution_context_ = MakeGarbageCollected<NullExecutionContext>();
static_cast<NullExecutionContext*>(execution_context_.Get())
->SetUpSecurityContext();
- fetch_context_ = new MockBaseFetchContext(execution_context_);
+ fetch_context_ =
+ MakeGarbageCollected<MockBaseFetchContext>(execution_context_);
}
Persistent<ExecutionContext> execution_context_;
@@ -411,7 +413,7 @@ TEST_F(BaseFetchContextTest, UACSSTest) {
ResourceRequest resource_request(test_url);
resource_request.SetRequestorOrigin(fetch_context_->GetSecurityOrigin());
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::uacss;
+ options.initiator_info.name = fetch_initiator_type_names::kUacss;
EXPECT_EQ(ResourceRequestBlockedReason::kOther,
fetch_context_->CanRequest(
@@ -445,7 +447,7 @@ TEST_F(BaseFetchContextTest, UACSSTest_BypassCSP) {
ResourceRequest resource_request(data_url);
resource_request.SetRequestorOrigin(fetch_context_->GetSecurityOrigin());
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::uacss;
+ options.initiator_info.name = fetch_initiator_type_names::kUacss;
EXPECT_EQ(base::nullopt,
fetch_context_->CanRequest(
diff --git a/chromium/third_party/blink/renderer/core/loader/document_loader.cc b/chromium/third_party/blink/renderer/core/loader/document_loader.cc
index bf3326acc60..521ff8ebc0a 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/document_loader.cc
@@ -46,6 +46,7 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
+#include "third_party/blink/renderer/core/frame/intervention.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
@@ -116,33 +117,78 @@ DocumentLoader::DocumentLoader(
const ResourceRequest& req,
const SubstituteData& substitute_data,
ClientRedirectPolicy client_redirect_policy,
- const base::UnguessableToken& devtools_navigation_token)
+ const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType load_type,
+ WebNavigationType navigation_type,
+ std::unique_ptr<WebNavigationParams> navigation_params)
: frame_(frame),
fetcher_(FrameFetchContext::CreateFetcherFromDocumentLoader(this)),
original_request_(req),
substitute_data_(substitute_data),
request_(req),
- load_type_(WebFrameLoadType::kStandard),
+ load_type_(load_type),
is_client_redirect_(client_redirect_policy ==
ClientRedirectPolicy::kClientRedirect),
replaces_current_history_item_(false),
data_received_(false),
- navigation_type_(kWebNavigationTypeOther),
+ navigation_type_(navigation_type),
document_load_timing_(*this),
application_cache_host_(ApplicationCacheHost::Create(this)),
+ service_worker_network_provider_(
+ navigation_params
+ ? std::move(navigation_params->service_worker_network_provider)
+ : nullptr),
was_blocked_after_csp_(false),
state_(kNotStarted),
committed_data_buffer_(nullptr),
in_data_received_(false),
data_buffer_(SharedBuffer::Create()),
devtools_navigation_token_(devtools_navigation_token),
- had_sticky_activation_(false),
- had_transient_activation_(false),
+ had_sticky_activation_(navigation_params &&
+ navigation_params->is_user_activated),
+ had_transient_activation_(request_.HasUserGesture()),
use_counter_(frame_->GetChromeClient().IsSVGImageChromeClient()
? UseCounter::kSVGImageContext
: UseCounter::kDefaultContext) {
DCHECK(frame_);
+ WebNavigationTimings timings;
+ if (navigation_params)
+ timings = navigation_params->navigation_timings;
+ if (!timings.input_start.is_null())
+ document_load_timing_.SetInputStart(timings.input_start);
+ if (timings.navigation_start.is_null()) {
+ // If we don't have any navigation timings yet, it starts now.
+ document_load_timing_.SetNavigationStart(CurrentTimeTicks());
+ } else {
+ document_load_timing_.SetNavigationStart(timings.navigation_start);
+ if (!timings.redirect_start.is_null()) {
+ document_load_timing_.SetRedirectStart(timings.redirect_start);
+ document_load_timing_.SetRedirectEnd(timings.redirect_end);
+ }
+ if (!timings.fetch_start.is_null()) {
+ // If we started fetching, we should have started the navigation.
+ DCHECK(!timings.navigation_start.is_null());
+ document_load_timing_.SetFetchStart(timings.fetch_start);
+ }
+ }
+
+ if (navigation_params && navigation_params->source_location.has_value()) {
+ WebSourceLocation& location = navigation_params->source_location.value();
+ source_location_ = SourceLocation::Create(
+ location.url, location.line_number, location.column_number, nullptr);
+ }
+
+ // TODO(japhet): This is needed because the browser process DCHECKs if the
+ // first entry we commit in a new frame has replacement set. It's unclear
+ // whether the DCHECK is right, investigate removing this special case.
+ // TODO(dgozman): we should get rid of this boolean field, and make client
+ // responsible for it's own view of "replaces current item", based on the
+ // frame load type.
+ replaces_current_history_item_ =
+ load_type_ == WebFrameLoadType::kReplaceCurrentItem &&
+ (!frame_->Loader().Opener() || !request_.Url().IsEmpty());
+
// The document URL needs to be added to the head of the list as that is
// where the redirects originated.
if (is_client_redirect_)
@@ -221,7 +267,8 @@ Resource* DocumentLoader::StartPreload(ResourceType type,
break;
case ResourceType::kScript:
params.SetRequestContext(mojom::RequestContextType::SCRIPT);
- resource = ScriptResource::Fetch(params, Fetcher(), nullptr);
+ resource = ScriptResource::Fetch(params, Fetcher(), nullptr,
+ ScriptResource::kAllowStreaming);
break;
case ResourceType::kCSSStyleSheet:
resource = CSSStyleSheetResource::Fetch(params, Fetcher(), nullptr);
@@ -254,14 +301,6 @@ void DocumentLoader::SetServiceWorkerNetworkProvider(
service_worker_network_provider_ = std::move(provider);
}
-void DocumentLoader::SetSourceLocation(
- const WebSourceLocation& source_location) {
- std::unique_ptr<SourceLocation> location =
- SourceLocation::Create(source_location.url, source_location.line_number,
- source_location.column_number, nullptr);
- source_location_ = std::move(location);
-}
-
void DocumentLoader::ResetSourceLocation() {
source_location_ = nullptr;
}
@@ -275,7 +314,7 @@ void DocumentLoader::DispatchLinkHeaderPreloads(
LinkLoader::MediaPreloadPolicy media_policy) {
DCHECK_GE(state_, kCommitted);
LinkLoader::LoadLinksFromHeader(
- GetResponse().HttpHeaderField(HTTPNames::Link), GetResponse().Url(),
+ GetResponse().HttpHeaderField(http_names::kLink), GetResponse().Url(),
*frame_, frame_->GetDocument(), NetworkHintsInterfaceImpl(),
LinkLoader::kOnlyLoadResources, media_policy, viewport);
}
@@ -331,7 +370,7 @@ void DocumentLoader::UpdateForSameDocumentNavigation(
request_.SetURL(new_url);
SetReplacesCurrentHistoryItem(type != WebFrameLoadType::kStandard);
if (same_document_navigation_source == kSameDocumentNavigationHistoryApi) {
- request_.SetHTTPMethod(HTTPNames::GET);
+ request_.SetHTTPMethod(http_names::kGET);
request_.SetHTTPBody(nullptr);
}
ClearRedirectChain();
@@ -432,7 +471,7 @@ void DocumentLoader::NotifyFinished(Resource* resource) {
void DocumentLoader::LoadFailed(const ResourceError& error) {
if (!error.IsCancellation() && frame_->Owner())
- frame_->Owner()->RenderFallbackContent();
+ frame_->Owner()->RenderFallbackContent(frame_);
fetcher_->ClearResourcesFromPreviousFetcher();
WebHistoryCommitType history_commit_type = LoadTypeToCommitType(load_type_);
@@ -465,10 +504,6 @@ void DocumentLoader::SetUserActivated() {
had_sticky_activation_ = true;
}
-void DocumentLoader::SetHadTransientUserActivation() {
- had_transient_activation_ = true;
-}
-
const AtomicString& DocumentLoader::RequiredCSP() {
return GetFrameLoader().RequiredCSP();
}
@@ -561,7 +596,7 @@ bool DocumentLoader::ShouldContinueForResponse() const {
}
if (IsContentDispositionAttachment(
- response_.HttpHeaderField(HTTPNames::Content_Disposition))) {
+ response_.HttpHeaderField(http_names::kContentDisposition))) {
// The server wants us to download instead of replacing the page contents.
// Downloading is handled by the embedder, but we still get the initial
// response so that we can ignore it and clean up properly.
@@ -619,6 +654,12 @@ void DocumentLoader::ResponseReceived(
content_security_policy_ = ContentSecurityPolicy::Create();
content_security_policy_->SetOverrideURLForSelf(response.Url());
+
+ AtomicString mixed_content_header = response.HttpHeaderField("mixed-content");
+ if (EqualIgnoringASCIICase(mixed_content_header, "noupgrade")) {
+ frame_->GetDocument()->SetMixedAutoupgradeOptOut(true);
+ }
+
if (!frame_->GetSettings()->BypassCSP()) {
content_security_policy_->DidReceiveHeaders(
ContentSecurityPolicyResponseHeaders(response));
@@ -699,8 +740,8 @@ void DocumentLoader::ResponseReceived(
}
if (frame_->Owner() && response_.IsHTTP() &&
- !CORS::IsOkStatus(response_.HttpStatusCode()))
- frame_->Owner()->RenderFallbackContent();
+ !cors::IsOkStatus(response_.HttpStatusCode()))
+ frame_->Owner()->RenderFallbackContent(frame_);
}
void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
@@ -753,8 +794,9 @@ void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
if (request_.WasDiscarded())
frame_->GetDocument()->SetWasDiscarded(true);
frame_->GetDocument()->MaybeHandleHttpRefresh(
- response_.HttpHeaderField(HTTPNames::Refresh),
+ response_.HttpHeaderField(http_names::kRefresh),
Document::kHttpRefreshFromHeader);
+ ReportPreviewsIntervention();
}
void DocumentLoader::CommitData(const char* bytes, size_t length) {
@@ -933,7 +975,7 @@ void DocumentLoader::StartLoading() {
ResourceLoaderOptions options;
options.data_buffering_policy = kDoNotBufferData;
- options.initiator_info.name = FetchInitiatorTypeNames::document;
+ options.initiator_info.name = fetch_initiator_type_names::kDocument;
FetchParameters fetch_params(request_, options);
RawResource::FetchMainResource(fetch_params, Fetcher(), this,
substitute_data_);
@@ -966,14 +1008,14 @@ void DocumentLoader::DidInstallNewDocument(
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
- response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
+ response_.HttpHeaderField(http_names::kXDNSPrefetchControl);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
- response_.HttpHeaderField(HTTPNames::Content_Language);
+ response_.HttpHeaderField(http_names::kContentLanguage);
if (!header_content_language.IsEmpty()) {
- size_t comma_index = header_content_language.find(',');
+ wtf_size_t comma_index = header_content_language.find(',');
// kNotFound == -1 == don't truncate
header_content_language.Truncate(comma_index);
header_content_language =
@@ -983,14 +1025,19 @@ void DocumentLoader::DidInstallNewDocument(
}
String referrer_policy_header =
- response_.HttpHeaderField(HTTPNames::Referrer_Policy);
+ response_.HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
- if (response_.IsSignedExchangeInnerResponse())
+ if (response_.IsSignedExchangeInnerResponse()) {
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
+ UseCounter::Count(*document,
+ document->GetFrame()->IsMainFrame()
+ ? WebFeature::kSignedExchangeInnerResponseInMainFrame
+ : WebFeature::kSignedExchangeInnerResponseInSubFrame);
+ }
GetLocalFrameClient().DidCreateNewDocument();
}
@@ -1047,7 +1094,7 @@ void DocumentLoader::DidCommitNavigation(
interactive_detector->SetNavigationStartTime(GetTiming().NavigationStart());
TRACE_EVENT1("devtools.timeline", "CommitLoad", "data",
- InspectorCommitLoadEvent::Data(frame_));
+ inspector_commit_load_event::Data(frame_));
// Needs to run before dispatching preloads, as it may evict the memory cache.
probe::didCommitLoad(frame_, this);
@@ -1059,8 +1106,8 @@ void DocumentLoader::DidCommitNavigation(
frame_->GetPage()->DidCommitLoad(frame_);
GetUseCounter().DidCommitLoad(frame_);
- // Report legacy Symantec certificates after Page::DidCommitLoad, because the
- // latter clears the console.
+ // Report legacy Symantec certificates and TLS versions after
+ // Page::DidCommitLoad, because the latter clears the console.
if (response_.IsLegacySymantecCert()) {
UseCounter::Count(
this, frame_->Tree().Parent()
@@ -1069,6 +1116,14 @@ void DocumentLoader::DidCommitNavigation(
GetLocalFrameClient().ReportLegacySymantecCert(response_.Url(),
false /* did_fail */);
}
+
+ if (response_.IsLegacyTLSVersion()) {
+ UseCounter::Count(this,
+ frame_->Tree().Parent()
+ ? WebFeature::kLegacyTLSVersionInSubframeMainResource
+ : WebFeature::kLegacyTLSVersionInMainFrameResource);
+ GetLocalFrameClient().ReportLegacyTLSVersion(response_.Url());
+ }
}
// static
@@ -1087,6 +1142,29 @@ bool DocumentLoader::ShouldClearWindowName(
previous_security_origin);
}
+// Helper function: Merge the feature policy strings from HTTP headers and the
+// origin policy (if any).
+// Headers go first, which means that the per-page headers override the
+// origin policy features.
+void MergeFeaturesFromOriginPolicy(WTF::String& feature_policy,
+ const String& origin_policy_string) {
+ if (origin_policy_string.IsEmpty())
+ return;
+
+ std::unique_ptr<OriginPolicy> origin_policy = OriginPolicy::From(
+ StringUTF8Adaptor(origin_policy_string).AsStringPiece());
+ if (!origin_policy)
+ return;
+
+ for (const std::string& policy : origin_policy->GetFeaturePolicies()) {
+ if (!feature_policy.IsEmpty()) {
+ feature_policy.append(',');
+ }
+ feature_policy.append(
+ WTF::String::FromUTF8(policy.data(), policy.length()));
+ }
+}
+
void DocumentLoader::InstallNewDocument(
const KURL& url,
Document* owner_document,
@@ -1179,10 +1257,10 @@ void DocumentLoader::InstallNewDocument(
"ForceTouchEventFeatureDetectionForInspector");
}
OriginTrialContext::AddTokensFromHeader(
- document, response_.HttpHeaderField(HTTPNames::Origin_Trial));
+ document, response_.HttpHeaderField(http_names::kOriginTrial));
}
bool stale_while_revalidate_enabled =
- OriginTrials::StaleWhileRevalidateEnabled(document);
+ origin_trials::StaleWhileRevalidateEnabled(document);
fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled);
// If stale while revalidate is enabled via Origin Trials count it as such.
@@ -1204,8 +1282,10 @@ void DocumentLoader::InstallNewDocument(
// FeaturePolicy is reset in the browser process on commit, so this needs to
// be initialized and replicated to the browser process after commit messages
// are sent in didCommitNavigation().
- document->ApplyFeaturePolicyFromHeader(
- response_.HttpHeaderField(HTTPNames::Feature_Policy));
+ WTF::String feature_policy(
+ response_.HttpHeaderField(http_names::kFeaturePolicy));
+ MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy());
+ document->ApplyFeaturePolicyFromHeader(feature_policy);
GetFrameLoader().DispatchDidClearDocumentOfWindowObject();
}
@@ -1270,32 +1350,35 @@ void DocumentLoader::ResumeParser() {
}
}
-void DocumentLoader::UpdateNavigationTimings(
- base::TimeTicks navigation_start_time,
- base::TimeTicks redirect_start_time,
- base::TimeTicks redirect_end_time,
- base::TimeTicks fetch_start_time,
- base::TimeTicks input_start_time) {
- if (!input_start_time.is_null()) {
- GetTiming().SetInputStart(input_start_time);
- }
+void DocumentLoader::ReportPreviewsIntervention() const {
+ // Only send reports for main frames.
+ if (!frame_->IsMainFrame())
+ return;
+
+ WebURLRequest::PreviewsState previews_state = request_.GetPreviewsState();
- // If we don't have any navigation timings yet, just start the navigation.
- if (navigation_start_time.is_null()) {
- GetTiming().SetNavigationStart(CurrentTimeTicks());
+ // Verify that certain types are not on main frame requests.
+ DCHECK_NE(WebURLRequest::kClientLoFiAutoReload, previews_state);
+ DCHECK_NE(WebURLRequest::kLazyImageLoadDeferred, previews_state);
+
+ static_assert(WebURLRequest::kPreviewsStateLast ==
+ WebURLRequest::kLazyImageLoadDeferred,
+ "If a new Preview type is added, verify that the Intervention "
+ "Report should be sent (or not sent) for that type.");
+
+ // If the preview type is not unspecified, off, or no transform, it is a
+ // preview that needs to be reported.
+ if (previews_state == WebURLRequest::kPreviewsUnspecified ||
+ previews_state & WebURLRequest::kPreviewsOff ||
+ previews_state & WebURLRequest::kPreviewsNoTransform) {
return;
}
- GetTiming().SetNavigationStart(navigation_start_time);
- if (!redirect_start_time.is_null()) {
- GetTiming().SetRedirectStart(redirect_start_time);
- GetTiming().SetRedirectEnd(redirect_end_time);
- }
- if (!fetch_start_time.is_null()) {
- // If we started fetching, we should have started the navigation.
- DCHECK(!navigation_start_time.is_null());
- GetTiming().SetFetchStart(fetch_start_time);
- }
+ Intervention::GenerateReport(
+ frame_, "LitePageServed",
+ "Modified page load behavior on the page because the page was expected "
+ "to take a long amount of time to load. "
+ "https://www.chromestatus.com/feature/5148050062311424");
}
DEFINE_WEAK_IDENTIFIER_MAP(DocumentLoader);
diff --git a/chromium/third_party/blink/renderer/core/loader/document_loader.h b/chromium/third_party/blink/renderer/core/loader/document_loader.h
index a423cf8a157..5589b3963dc 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/document_loader.h
@@ -36,6 +36,7 @@
#include "third_party/blink/public/platform/web_loading_behavior_flag.h"
#include "third_party/blink/public/web/web_frame_load_type.h"
#include "third_party/blink/public/web/web_global_object_reuse_policy.h"
+#include "third_party/blink/public/web/web_navigation_params.h"
#include "third_party/blink/public/web/web_navigation_type.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -84,17 +85,14 @@ class CORE_EXPORT DocumentLoader
USING_GARBAGE_COLLECTED_MIXIN(DocumentLoader);
public:
- static DocumentLoader* Create(
- LocalFrame* frame,
- const ResourceRequest& request,
- const SubstituteData& data,
- ClientRedirectPolicy client_redirect_policy,
- const base::UnguessableToken& devtools_navigation_token) {
- DCHECK(frame);
-
- return new DocumentLoader(frame, request, data, client_redirect_policy,
- devtools_navigation_token);
- }
+ DocumentLoader(LocalFrame*,
+ const ResourceRequest&,
+ const SubstituteData&,
+ ClientRedirectPolicy,
+ const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType load_type,
+ WebNavigationType navigation_type,
+ std::unique_ptr<WebNavigationParams> navigation_params);
~DocumentLoader() override;
LocalFrame* GetFrame() const { return frame_; }
@@ -227,14 +225,12 @@ class CORE_EXPORT DocumentLoader
}
// Allows to specify the SourceLocation that triggered the navigation.
- void SetSourceLocation(const WebSourceLocation& source_location);
void ResetSourceLocation();
std::unique_ptr<SourceLocation> CopySourceLocation() const;
void LoadFailed(const ResourceError&);
void SetUserActivated();
- void SetHadTransientUserActivation();
const AtomicString& RequiredCSP();
@@ -267,25 +263,9 @@ class CORE_EXPORT DocumentLoader
return content_security_policy_.Get();
}
- // Updates navigation timings with provided values. This
- // should be called before WebLocalFrameClient::didCommitProvisionalLoad.
- // Calling it later may confuse users, because JavaScript may have run and
- // the user may have already recorded the original value.
- // Note: if |redirect_start_time| is null, redirect timings are not updated.
- void UpdateNavigationTimings(base::TimeTicks navigation_start_time,
- base::TimeTicks redirect_start_time,
- base::TimeTicks redirect_end_time,
- base::TimeTicks fetch_start_time,
- base::TimeTicks input_start_time);
UseCounter& GetUseCounter() { return use_counter_; }
protected:
- DocumentLoader(LocalFrame*,
- const ResourceRequest&,
- const SubstituteData&,
- ClientRedirectPolicy,
- const base::UnguessableToken& devtools_navigation_token);
-
static bool ShouldClearWindowName(
const LocalFrame&,
const SecurityOrigin* previous_security_origin,
@@ -362,6 +342,9 @@ class CORE_EXPORT DocumentLoader
// to the parser in a nested message loop.
void ProcessDataBuffer();
+ // Sends an intervention report if the page is being served as a preview.
+ void ReportPreviewsIntervention() const;
+
Member<LocalFrame> frame_;
Member<ResourceFetcher> fetcher_;
diff --git a/chromium/third_party/blink/renderer/core/loader/document_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/document_loader_test.cc
index fcd037d3b09..681c8372f8d 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_loader_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/document_loader_test.cc
@@ -7,6 +7,7 @@
#include <queue>
#include "base/auto_reset.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/common/frame/frame_owner_element_type.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url_loader_client.h"
#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
@@ -18,14 +19,14 @@
namespace blink {
-// TODO(dcheng): Ideally, enough of FrameTestHelpers would be in core/ that
+// TODO(dcheng): Ideally, enough of frame_test_helpers would be in core/ that
// placing a test for a core/ class in web/ wouldn't be necessary.
class DocumentLoaderTest : public testing::Test {
protected:
void SetUp() override {
web_view_helper_.Initialize();
- URLTestHelpers::RegisterMockedURLLoad(
- URLTestHelpers::ToKURL("https://example.com/foo.html"),
+ url_test_helpers::RegisterMockedURLLoad(
+ url_test_helpers::ToKURL("https://example.com/foo.html"),
test::CoreTestDataPath("foo.html"));
}
@@ -37,7 +38,7 @@ class DocumentLoaderTest : public testing::Test {
WebLocalFrameImpl* MainFrame() { return web_view_helper_.LocalMainFrame(); }
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
TEST_F(DocumentLoaderTest, SingleChunk) {
@@ -52,7 +53,7 @@ TEST_F(DocumentLoaderTest, SingleChunk) {
} delegate;
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(&delegate);
- FrameTestHelpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
+ frame_test_helpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr);
// TODO(dcheng): How should the test verify that the original callback is
@@ -76,7 +77,7 @@ TEST_F(DocumentLoaderTest, MultiChunkNoReentrancy) {
} delegate;
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(&delegate);
- FrameTestHelpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
+ frame_test_helpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr);
}
@@ -89,7 +90,7 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
// dataReceived() reentrantly.
// 3. The final chunk, which is dispatched normally at the top-level.
class ChildDelegate : public WebURLLoaderTestDelegate,
- public FrameTestHelpers::TestWebFrameClient {
+ public frame_test_helpers::TestWebFrameClient {
public:
// WebURLLoaderTestDelegate overrides:
void DidReceiveData(WebURLLoaderClient* original_client,
@@ -145,7 +146,7 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
bool served_reentrantly_ = false;
};
- class MainFrameClient : public FrameTestHelpers::TestWebFrameClient {
+ class MainFrameClient : public frame_test_helpers::TestWebFrameClient {
public:
explicit MainFrameClient(TestWebFrameClient& child_client)
: child_client_(child_client) {}
@@ -155,7 +156,8 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
const WebString& fallback_name,
WebSandboxFlags,
const ParsedFeaturePolicy&,
- const WebFrameOwnerProperties&) override {
+ const WebFrameOwnerProperties&,
+ FrameOwnerElementType) override {
return CreateLocalChild(*parent, scope, &child_client_);
}
@@ -169,12 +171,12 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
// This doesn't go through the mocked URL load path: it's just intended to
// setup a situation where didReceiveData() can be invoked reentrantly.
- FrameTestHelpers::LoadHTMLString(MainFrame(), "<iframe></iframe>",
- URLTestHelpers::ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(MainFrame(), "<iframe></iframe>",
+ url_test_helpers::ToKURL("about:blank"));
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(
&child_delegate);
- FrameTestHelpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
+ frame_test_helpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr);
EXPECT_TRUE(child_delegate.ServedReentrantly());
@@ -193,4 +195,33 @@ TEST_F(DocumentLoaderTest, isCommittedButEmpty) {
->IsCommittedButEmpty());
}
+TEST_F(DocumentLoaderTest, MixedContentOptOutSetIfHeaderReceived) {
+ WebURL url =
+ url_test_helpers::ToKURL("https://examplenoupgrade.com/foo.html");
+ WebURLResponse response(url);
+ response.SetHTTPStatusCode(200);
+ response.SetHTTPHeaderField("mixed-content", "noupgrade");
+ url_test_helpers::RegisterMockedURLLoadWithCustomResponse(
+ url, test::CoreTestDataPath("foo.html"), response);
+ WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(
+ "https://examplenoupgrade.com/foo.html");
+ EXPECT_TRUE(ToLocalFrame(web_view_impl->GetPage()->MainFrame())
+ ->Loader()
+ .GetDocumentLoader()
+ ->GetFrame()
+ ->GetDocument()
+ ->GetMixedAutoUpgradeOptOut());
+}
+
+TEST_F(DocumentLoaderTest, MixedContentOptOutNotSetIfNoHeaderReceived) {
+ WebViewImpl* web_view_impl =
+ web_view_helper_.InitializeAndLoad("https://example.com/foo.html");
+ EXPECT_FALSE(ToLocalFrame(web_view_impl->GetPage()->MainFrame())
+ ->Loader()
+ .GetDocumentLoader()
+ ->GetFrame()
+ ->GetDocument()
+ ->GetMixedAutoUpgradeOptOut());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/empty_clients.cc b/chromium/third_party/blink/renderer/core/loader/empty_clients.cc
index 69254e3ae8a..87915944910 100644
--- a/chromium/third_party/blink/renderer/core/loader/empty_clients.cc
+++ b/chromium/third_party/blink/renderer/core/loader/empty_clients.cc
@@ -34,7 +34,6 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_application_cache_host.h"
#include "third_party/blink/public/platform/web_media_player.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/forms/color_chooser.h"
@@ -60,7 +59,7 @@ class EmptyPopupMenu : public PopupMenu {
};
PopupMenu* EmptyChromeClient::OpenPopupMenu(LocalFrame&, HTMLSelectElement&) {
- return new EmptyPopupMenu();
+ return MakeGarbageCollected<EmptyPopupMenu>();
}
ColorChooser* EmptyChromeClient::OpenColorChooser(LocalFrame*,
@@ -95,22 +94,22 @@ String EmptyChromeClient::AcceptLanguages() {
return String();
}
-NavigationPolicy EmptyLocalFrameClient::DecidePolicyForNavigation(
+void EmptyLocalFrameClient::BeginNavigation(
const ResourceRequest&,
Document* origin_document,
DocumentLoader*,
WebNavigationType,
NavigationPolicy,
bool,
- bool,
+ WebFrameLoadType,
bool,
WebTriggeringEventInfo,
HTMLFormElement*,
ContentSecurityPolicyDisposition,
mojom::blink::BlobURLTokenPtr,
- base::TimeTicks) {
- return kNavigationPolicyIgnore;
-}
+ base::TimeTicks,
+ const String&,
+ mojom::blink::NavigationInitiatorPtr) {}
void EmptyLocalFrameClient::DispatchWillSendSubmitEvent(HTMLFormElement*) {}
@@ -120,13 +119,16 @@ DocumentLoader* EmptyLocalFrameClient::CreateDocumentLoader(
const SubstituteData& substitute_data,
ClientRedirectPolicy client_redirect_policy,
const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType load_type,
+ WebNavigationType navigation_type,
std::unique_ptr<WebNavigationParams> navigation_params,
std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) {
DCHECK(frame);
- return DocumentLoader::Create(frame, request, substitute_data,
- client_redirect_policy,
- devtools_navigation_token);
+ return MakeGarbageCollected<DocumentLoader>(
+ frame, request, substitute_data, client_redirect_policy,
+ devtools_navigation_token, load_type, navigation_type,
+ std::move(navigation_params));
}
LocalFrame* EmptyLocalFrameClient::CreateFrame(const AtomicString&,
@@ -175,10 +177,6 @@ EmptyLocalFrameClient::CreateServiceWorkerProvider() {
return nullptr;
}
-ContentSettingsClient& EmptyLocalFrameClient::GetContentSettingsClient() {
- return content_settings_client_;
-}
-
std::unique_ptr<WebApplicationCacheHost>
EmptyLocalFrameClient::CreateApplicationCacheHost(
WebApplicationCacheHostClient*) {
diff --git a/chromium/third_party/blink/renderer/core/loader/empty_clients.h b/chromium/third_party/blink/renderer/core/loader/empty_clients.h
index 5ab9ea7ab5e..a0592da644f 100644
--- a/chromium/third_party/blink/renderer/core/loader/empty_clients.h
+++ b/chromium/third_party/blink/renderer/core/loader/empty_clients.h
@@ -41,7 +41,6 @@
#include "third_party/blink/public/platform/web_spell_check_panel_host_client.h"
#include "third_party/blink/public/platform/web_url_loader.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/remote_frame_client.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
@@ -77,7 +76,9 @@ namespace blink {
class CORE_EXPORT EmptyChromeClient : public ChromeClient {
public:
- static EmptyChromeClient* Create() { return new EmptyChromeClient; }
+ static EmptyChromeClient* Create() {
+ return MakeGarbageCollected<EmptyChromeClient>();
+ }
~EmptyChromeClient() override = default;
void ChromeDestroyed() override {}
@@ -94,13 +95,6 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
void TakeFocus(WebFocusType) override {}
void FocusedNodeChanged(Node*, Node*) override {}
- Page* CreateWindow(LocalFrame*,
- const FrameLoadRequest&,
- const WebWindowFeatures&,
- NavigationPolicy,
- SandboxFlags) override {
- return nullptr;
- }
void Show(NavigationPolicy) override {}
void DidOverscroll(const FloatSize&,
@@ -117,7 +111,7 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
const WebDragData&,
WebDragOperationsMask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset) override {}
+ const gfx::Point& drag_image_offset) override {}
bool AcceptsLoadDrops() const override { return true; }
bool ShouldReportDetailedMessageForSource(LocalFrame&,
@@ -139,6 +133,15 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
void CloseWindowSoon() override {}
+ Page* CreateWindowDelegate(LocalFrame*,
+ const FrameLoadRequest&,
+ const WebWindowFeatures&,
+ NavigationPolicy,
+ SandboxFlags,
+ const SessionStorageNamespaceId&) override {
+ return nullptr;
+ }
+
bool OpenJavaScriptAlertDelegate(LocalFrame*, const String&) override {
return false;
}
@@ -177,8 +180,6 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
void PrintDelegate(LocalFrame*) override {}
- void EnumerateChosenDirectory(FileChooser*) override {}
-
ColorChooser* OpenColorChooser(LocalFrame*,
ColorChooserClient*,
const Color&) override;
@@ -225,7 +226,11 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
public:
- static EmptyLocalFrameClient* Create() { return new EmptyLocalFrameClient; }
+ static EmptyLocalFrameClient* Create() {
+ return MakeGarbageCollected<EmptyLocalFrameClient>();
+ }
+
+ EmptyLocalFrameClient() = default;
~EmptyLocalFrameClient() override = default;
bool HasWebView() const override { return true; } // mainly for assertions
@@ -251,10 +256,8 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
void DispatchDidHandleOnloadEvents() override {}
void DispatchWillCommitProvisionalLoad() override {}
- void DispatchDidStartProvisionalLoad(
- DocumentLoader*,
- ResourceRequest&,
- mojo::ScopedMessagePipeHandle navigation_initiator_handle) override {}
+ void DispatchDidStartProvisionalLoad(DocumentLoader*,
+ const ResourceRequest&) override {}
void DispatchDidReceiveTitle(const String&) override {}
void DispatchDidChangeIcons(IconType) override {}
void DispatchDidCommitLoad(HistoryItem*,
@@ -268,19 +271,21 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
void DispatchDidFinishLoad() override {}
void DispatchDidChangeThemeColor() override {}
- NavigationPolicy DecidePolicyForNavigation(const ResourceRequest&,
- Document* origin_document,
- DocumentLoader*,
- WebNavigationType,
- NavigationPolicy,
- bool,
- bool,
- bool,
- WebTriggeringEventInfo,
- HTMLFormElement*,
- ContentSecurityPolicyDisposition,
- mojom::blink::BlobURLTokenPtr,
- base::TimeTicks) override;
+ void BeginNavigation(const ResourceRequest&,
+ Document* origin_document,
+ DocumentLoader*,
+ WebNavigationType,
+ NavigationPolicy,
+ bool,
+ WebFrameLoadType,
+ bool,
+ WebTriggeringEventInfo,
+ HTMLFormElement*,
+ ContentSecurityPolicyDisposition,
+ mojom::blink::BlobURLTokenPtr,
+ base::TimeTicks,
+ const String&,
+ mojom::blink::NavigationInitiatorPtr) override;
void DispatchWillSendSubmitEvent(HTMLFormElement*) override;
@@ -300,6 +305,8 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
const SubstituteData&,
ClientRedirectPolicy,
const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType,
+ WebNavigationType,
std::unique_ptr<WebNavigationParams> navigation_params,
std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override;
void UpdateDocumentLoader(
@@ -360,7 +367,9 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
std::unique_ptr<WebServiceWorkerProvider> CreateServiceWorkerProvider()
override;
- ContentSettingsClient& GetContentSettingsClient() override;
+ WebContentSettingsClient* GetContentSettingsClient() override {
+ return nullptr;
+ }
std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
WebApplicationCacheHostClient*) override;
@@ -386,12 +395,9 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
Frame* FindFrame(const AtomicString& name) const override;
protected:
- EmptyLocalFrameClient() = default;
-
// Not owned
WebTextCheckClient* text_check_client_;
- ContentSettingsClient content_settings_client_;
service_manager::InterfaceProvider interface_provider_;
DISALLOW_COPY_AND_ASSIGN(EmptyLocalFrameClient);
diff --git a/chromium/third_party/blink/renderer/core/loader/form_submission.cc b/chromium/third_party/blink/renderer/core/loader/form_submission.cc
index a1693b1505e..77e931a2581 100644
--- a/chromium/third_party/blink/renderer/core/loader/form_submission.cc
+++ b/chromium/third_party/blink/renderer/core/loader/form_submission.cc
@@ -51,7 +51,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
static int64_t GenerateFormDataIdentifier() {
// Initialize to the current time to reduce the likelihood of generating
@@ -181,24 +181,26 @@ FormSubmission* FormSubmission::Create(HTMLFormElement* form,
copied_attributes.CopyFrom(attributes);
if (submit_button) {
AtomicString attribute_value;
- if (!(attribute_value = submit_button->FastGetAttribute(formactionAttr))
+ if (!(attribute_value = submit_button->FastGetAttribute(kFormactionAttr))
.IsNull())
copied_attributes.ParseAction(attribute_value);
- if (!(attribute_value = submit_button->FastGetAttribute(formenctypeAttr))
+ if (!(attribute_value = submit_button->FastGetAttribute(kFormenctypeAttr))
.IsNull())
copied_attributes.UpdateEncodingType(attribute_value);
- if (!(attribute_value = submit_button->FastGetAttribute(formmethodAttr))
+ if (!(attribute_value = submit_button->FastGetAttribute(kFormmethodAttr))
.IsNull())
copied_attributes.UpdateMethodType(attribute_value);
- if (!(attribute_value = submit_button->FastGetAttribute(formtargetAttr))
+ if (!(attribute_value = submit_button->FastGetAttribute(kFormtargetAttr))
.IsNull())
copied_attributes.SetTarget(attribute_value);
}
if (copied_attributes.Method() == kDialogMethod) {
- if (submit_button)
- return new FormSubmission(submit_button->ResultForDialogSubmit());
- return new FormSubmission("");
+ if (submit_button) {
+ return MakeGarbageCollected<FormSubmission>(
+ submit_button->ResultForDialogSubmit());
+ }
+ return MakeGarbageCollected<FormSubmission>("");
}
Document& document = form->GetDocument();
@@ -234,7 +236,9 @@ FormSubmission* FormSubmission::Create(HTMLFormElement* form,
copied_attributes.AcceptCharset(), document.Encoding());
FormData* dom_form_data =
FormData::Create(data_encoding.EncodingForFormSubmission());
- form->ConstructFormDataSet(submit_button, *dom_form_data);
+ bool entry_list_result =
+ form->ConstructEntryList(submit_button, *dom_form_data);
+ DCHECK(entry_list_result);
scoped_refptr<EncodedFormData> form_data;
String boundary;
@@ -259,9 +263,9 @@ FormSubmission* FormSubmission::Create(HTMLFormElement* form,
AtomicString target_or_base_target = copied_attributes.Target().IsEmpty()
? document.BaseTarget()
: copied_attributes.Target();
- return new FormSubmission(copied_attributes.Method(), action_url,
- target_or_base_target, encoding_type, form,
- std::move(form_data), boundary, event);
+ return MakeGarbageCollected<FormSubmission>(
+ copied_attributes.Method(), action_url, target_or_base_target,
+ encoding_type, form, std::move(form_data), boundary, event);
}
void FormSubmission::Trace(blink::Visitor* visitor) {
@@ -285,7 +289,7 @@ FrameLoadRequest FormSubmission::CreateFrameLoadRequest(
frame_request.SetFrameName(target_);
if (method_ == FormSubmission::kPostMethod) {
- frame_request.GetResourceRequest().SetHTTPMethod(HTTPNames::POST);
+ frame_request.GetResourceRequest().SetHTTPMethod(http_names::kPOST);
frame_request.GetResourceRequest().SetHTTPBody(form_data_);
// construct some user headers if necessary
diff --git a/chromium/third_party/blink/renderer/core/loader/form_submission.h b/chromium/third_party/blink/renderer/core/loader/form_submission.h
index 14ddd3ba497..3f9e3b86f2e 100644
--- a/chromium/third_party/blink/renderer/core/loader/form_submission.h
+++ b/chromium/third_party/blink/renderer/core/loader/form_submission.h
@@ -98,6 +98,18 @@ class FormSubmission : public GarbageCollectedFinalized<FormSubmission> {
const Attributes&,
Event*,
HTMLFormControlElement* submit_button);
+
+ FormSubmission(SubmitMethod,
+ const KURL& action,
+ const AtomicString& target,
+ const AtomicString& content_type,
+ HTMLFormElement*,
+ scoped_refptr<EncodedFormData>,
+ const String& boundary,
+ Event*);
+ // FormSubmission for DialogMethod
+ explicit FormSubmission(const String& result);
+
void Trace(blink::Visitor*);
FrameLoadRequest CreateFrameLoadRequest(Document* origin_document);
@@ -115,17 +127,6 @@ class FormSubmission : public GarbageCollectedFinalized<FormSubmission> {
const String& Result() const { return result_; }
private:
- FormSubmission(SubmitMethod,
- const KURL& action,
- const AtomicString& target,
- const AtomicString& content_type,
- HTMLFormElement*,
- scoped_refptr<EncodedFormData>,
- const String& boundary,
- Event*);
- // FormSubmission for DialogMethod
- explicit FormSubmission(const String& result);
-
// FIXME: Hold an instance of Attributes instead of individual members.
SubmitMethod method_;
KURL action_;
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.cc b/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.cc
index dacc48bd280..58bb8b7797d 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.cc
+++ b/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.cc
@@ -44,6 +44,7 @@
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_application_cache_host.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_effective_connection_type.h"
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "third_party/blink/public/platform/websocket_handshake_throttle.h"
@@ -54,7 +55,6 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/fileapi/public_url_manager.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
@@ -62,6 +62,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
+#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/html/imports/html_imports_controller.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -265,7 +266,8 @@ struct FrameFetchContext::FrozenState final
ResourceFetcher* FrameFetchContext::CreateFetcher(DocumentLoader* loader,
Document* document) {
- FrameFetchContext* context = new FrameFetchContext(loader, document);
+ FrameFetchContext* context =
+ MakeGarbageCollected<FrameFetchContext>(loader, document);
ResourceFetcher* fetcher = ResourceFetcher::Create(context);
if (loader && context->GetSettings()->GetSavePreviousDocumentResources() !=
@@ -292,7 +294,7 @@ FrameFetchContext::FrameFetchContext(DocumentLoader* loader, Document* document)
!GetSettings()->GetDataSaverHoldbackWebApi()) {
if (document_) {
fetch_client_settings_object_ =
- new FetchClientSettingsObjectImpl(*document_);
+ MakeGarbageCollected<FetchClientSettingsObjectImpl>(*document_);
}
DCHECK(GetFrame());
}
@@ -303,7 +305,7 @@ void FrameFetchContext::ProvideDocumentToContext(FetchContext& context,
CHECK(context.IsFrameFetchContext());
static_cast<FrameFetchContext&>(context).document_ = document;
static_cast<FrameFetchContext&>(context).fetch_client_settings_object_ =
- new FetchClientSettingsObjectImpl(*document);
+ MakeGarbageCollected<FetchClientSettingsObjectImpl>(*document);
}
FrameFetchContext::~FrameFetchContext() {
@@ -340,7 +342,7 @@ LocalFrame* FrameFetchContext::FrameOfImportsController() const {
scoped_refptr<base::SingleThreadTaskRunner>
FrameFetchContext::GetLoadingTaskRunner() {
if (IsDetached())
- return Platform::Current()->CurrentThread()->GetTaskRunner();
+ return Thread::Current()->GetTaskRunner();
return FetchContext::GetLoadingTaskRunner();
}
@@ -422,10 +424,10 @@ void FrameFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request,
// Reload should reflect the current data saver setting.
if (IsReloadLoadType(MasterDocumentLoader()->LoadType()))
- request.ClearHTTPHeaderField(HTTPNames::Save_Data);
+ request.ClearHTTPHeaderField(http_names::kSaveData);
if (save_data_enabled_)
- request.SetHTTPHeaderField(HTTPNames::Save_Data, "on");
+ request.SetHTTPHeaderField(http_names::kSaveData, "on");
if (GetLocalFrameClient()->GetPreviewsStateForFrame() &
WebURLRequest::kNoScriptOn) {
@@ -466,8 +468,8 @@ mojom::FetchCacheMode FrameFetchContext::ResourceRequestCachePolicy(
DCHECK(GetFrame());
if (type == ResourceType::kMainResource) {
const auto cache_mode = DetermineCacheMode(
- request.HttpMethod() == HTTPNames::POST ? RequestMethod::kIsPost
- : RequestMethod::kIsNotPost,
+ request.HttpMethod() == http_names::kPOST ? RequestMethod::kIsPost
+ : RequestMethod::kIsNotPost,
request.IsConditional() ? RequestType::kIsConditional
: RequestType::kIsNotConditional,
MainResourceType::kIsMainResource, MasterDocumentLoader()->LoadType());
@@ -517,7 +519,7 @@ void FrameFetchContext::DispatchDidChangeResourcePriority(
if (IsDetached())
return;
TRACE_EVENT1("devtools.timeline", "ResourceChangePriority", "data",
- InspectorChangeResourcePriorityEvent::Data(
+ inspector_change_resource_priority_event::Data(
MasterDocumentLoader(), identifier, load_priority));
probe::didChangeResourcePriority(GetFrame(), MasterDocumentLoader(),
identifier, load_priority);
@@ -634,7 +636,7 @@ void FrameFetchContext::DispatchDidReceiveResponse(
}
LinkLoader::LoadLinksFromHeader(
- response.HttpHeaderField(HTTPNames::Link), response.Url(), *GetFrame(),
+ response.HttpHeaderField(http_names::kLink), response.Url(), *GetFrame(),
document_, NetworkHintsInterfaceImpl(), resource_loading_policy,
LinkLoader::kLoadAll, nullptr);
@@ -649,6 +651,14 @@ void FrameFetchContext::DispatchDidReceiveResponse(
false /* did_fail */);
}
+ if (response.IsLegacyTLSVersion()) {
+ if (resource->GetType() != ResourceType::kMainResource) {
+ // Main resources are counted in DocumentLoader.
+ UseCounter::Count(GetFrame(), WebFeature::kLegacyTLSVersionInSubresource);
+ }
+ GetLocalFrameClient()->ReportLegacyTLSVersion(response.Url());
+ }
+
GetFrame()->Loader().Progress().IncrementProgress(identifier, response);
GetLocalFrameClient()->DispatchDidReceiveResponse(response);
DocumentLoader* document_loader = MasterDocumentLoader();
@@ -661,7 +671,7 @@ void FrameFetchContext::DispatchDidReceiveResponse(
void FrameFetchContext::DispatchDidReceiveData(unsigned long identifier,
const char* data,
- int data_length) {
+ size_t data_length) {
if (IsDetached())
return;
@@ -670,8 +680,9 @@ void FrameFetchContext::DispatchDidReceiveData(unsigned long identifier,
MasterDocumentLoader(), data, data_length);
}
-void FrameFetchContext::DispatchDidReceiveEncodedData(unsigned long identifier,
- int encoded_data_length) {
+void FrameFetchContext::DispatchDidReceiveEncodedData(
+ unsigned long identifier,
+ size_t encoded_data_length) {
if (IsDetached())
return;
probe::didReceiveEncodedDataLength(GetFrame()->GetDocument(),
@@ -720,14 +731,14 @@ void FrameFetchContext::DispatchDidFail(const KURL& url,
return;
if (DocumentLoader* loader = MasterDocumentLoader()) {
- if (NetworkUtils::IsCertificateTransparencyRequiredError(
+ if (network_utils::IsCertificateTransparencyRequiredError(
error.ErrorCode())) {
loader->GetUseCounter().Count(
WebFeature::kCertificateTransparencyRequiredErrorOnResourceLoad,
GetFrame());
}
- if (NetworkUtils::IsLegacySymantecCertError(error.ErrorCode())) {
+ if (network_utils::IsLegacySymantecCertError(error.ErrorCode())) {
loader->GetUseCounter().Count(
WebFeature::kDistrustedLegacySymantecSubresource, GetFrame());
GetLocalFrameClient()->ReportLegacySymantecCert(url, true /* did_fail */);
@@ -786,7 +797,7 @@ void FrameFetchContext::RecordLoadingActivity(
!request.Url().IsValid())
return;
V8DOMActivityLogger* activity_logger = nullptr;
- if (fetch_initiator_name == FetchInitiatorTypeNames::xmlhttprequest) {
+ if (fetch_initiator_name == fetch_initiator_type_names::kXmlhttprequest) {
activity_logger = V8DOMActivityLogger::CurrentActivityLogger();
} else {
activity_logger =
@@ -815,6 +826,12 @@ void FrameFetchContext::DidLoadResource(Resource* resource) {
document_->CheckCompleted();
}
+void FrameFetchContext::DidObserveLoadingBehavior(
+ WebLoadingBehaviorFlag behavior) {
+ if (document_loader_)
+ document_loader_->DidObserveLoadingBehavior(behavior);
+}
+
void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
// Normally, |document_| is cleared on Document shutdown. However, Documents
// for HTML imports will also not have a LocalFrame set: in that case, also
@@ -842,8 +859,9 @@ void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
bool FrameFetchContext::AllowImage(bool images_enabled, const KURL& url) const {
if (IsDetached())
return true;
-
- return GetContentSettingsClient()->AllowImage(images_enabled, url);
+ if (auto* settings_client = GetContentSettingsClient())
+ images_enabled = settings_client->AllowImage(images_enabled, url);
+ return images_enabled;
}
blink::mojom::ControllerServiceWorkerMode
@@ -1093,7 +1111,7 @@ MHTMLArchive* FrameFetchContext::Archive() const {
bool FrameFetchContext::AllowScriptFromSource(const KURL& url) const {
if (AllowScriptFromSourceWithoutNotifying(url))
return true;
- ContentSettingsClient* settings_client = GetContentSettingsClient();
+ WebContentSettingsClient* settings_client = GetContentSettingsClient();
if (settings_client)
settings_client->DidNotAllowScript();
return false;
@@ -1101,13 +1119,11 @@ bool FrameFetchContext::AllowScriptFromSource(const KURL& url) const {
bool FrameFetchContext::AllowScriptFromSourceWithoutNotifying(
const KURL& url) const {
- ContentSettingsClient* settings_client = GetContentSettingsClient();
Settings* settings = GetSettings();
- if (settings_client && !settings_client->AllowScriptFromSource(
- !settings || settings->GetScriptEnabled(), url)) {
- return false;
- }
- return true;
+ bool allow_script = !settings || settings->GetScriptEnabled();
+ if (auto* settings_client = GetContentSettingsClient())
+ allow_script = settings_client->AllowScriptFromSource(allow_script, url);
+ return allow_script;
}
bool FrameFetchContext::IsFirstPartyOrigin(const KURL& url) const {
@@ -1147,7 +1163,8 @@ bool FrameFetchContext::ShouldBypassMainWorldCSP() const {
if (IsDetached())
return false;
- return GetFrame()->GetScriptController().ShouldBypassMainWorldCSP();
+ return ContentSecurityPolicy::ShouldBypassMainWorld(
+ GetFrame()->GetDocument());
}
bool FrameFetchContext::IsSVGImageChromeClient() const {
@@ -1291,7 +1308,7 @@ void FrameFetchContext::AddConsoleMessage(ConsoleMessage* message) const {
GetFrame()->Console().AddMessage(message);
}
-ContentSettingsClient* FrameFetchContext::GetContentSettingsClient() const {
+WebContentSettingsClient* FrameFetchContext::GetContentSettingsClient() const {
if (IsDetached())
return nullptr;
return GetFrame()->GetContentSettingsClient();
@@ -1348,12 +1365,12 @@ void FrameFetchContext::ParseAndPersistClientHints(
document_loader_->GetClientHintsPreferences()
.UpdateFromAcceptClientHintsLifetimeHeader(
- response.HttpHeaderField(HTTPNames::Accept_CH_Lifetime),
+ response.HttpHeaderField(http_names::kAcceptCHLifetime),
response.Url(), &hints_context);
document_loader_->GetClientHintsPreferences()
.UpdateFromAcceptClientHintsHeader(
- response.HttpHeaderField(HTTPNames::Accept_CH), response.Url(),
+ response.HttpHeaderField(http_names::kAcceptCH), response.Url(),
&hints_context);
// Notify content settings client of persistent client hints.
@@ -1369,8 +1386,10 @@ void FrameFetchContext::ParseAndPersistClientHints(
return;
}
- GetContentSettingsClient()->PersistClientHints(
- enabled_client_hints, persist_duration, response.Url());
+ if (auto* settings_client = GetContentSettingsClient()) {
+ settings_client->PersistClientHints(enabled_client_hints, persist_duration,
+ response.Url());
+ }
}
std::unique_ptr<WebURLLoader> FrameFetchContext::CreateURLLoader(
@@ -1428,7 +1447,7 @@ FetchContext* FrameFetchContext::Detach() {
return this;
if (document_) {
- frozen_state_ = new FrozenState(
+ frozen_state_ = MakeGarbageCollected<FrozenState>(
Url(), GetParentSecurityOrigin(), GetAddressSpace(),
GetContentSecurityPolicy(), GetSiteForCookies(),
GetClientHintsPreferences(), GetDevicePixelRatio(), GetUserAgent(),
@@ -1437,13 +1456,15 @@ FetchContext* FrameFetchContext::Detach() {
document_->CreateFetchClientSettingsObjectSnapshot();
} else {
// Some getters are unavailable in this case.
- frozen_state_ = new FrozenState(
+ frozen_state_ = MakeGarbageCollected<FrozenState>(
NullURL(), GetParentSecurityOrigin(), GetAddressSpace(),
GetContentSecurityPolicy(), GetSiteForCookies(),
GetClientHintsPreferences(), GetDevicePixelRatio(), GetUserAgent(),
IsMainFrame(), IsSVGImageChromeClient());
- fetch_client_settings_object_ = new FetchClientSettingsObjectSnapshot(
- NullURL(), nullptr, kReferrerPolicyDefault, String());
+ fetch_client_settings_object_ =
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ NullURL(), nullptr, network::mojom::ReferrerPolicy::kDefault,
+ String(), HttpsState::kNone);
}
// This is needed to break a reference cycle in which off-heap
@@ -1462,7 +1483,7 @@ void FrameFetchContext::Trace(blink::Visitor* visitor) {
}
void FrameFetchContext::RecordDataUriWithOctothorpe() {
- CountDeprecation(WebFeature::kDataUriHasOctothorpe);
+ UseCounter::Count(GetFrame(), WebFeature::kDataUriHasOctothorpe);
}
ResourceLoadPriority FrameFetchContext::ModifyPriorityForExperiments(
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.h b/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.h
index 3192f284f82..42e367df9a2 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.h
+++ b/chromium/third_party/blink/renderer/core/loader/frame_fetch_context.h
@@ -50,7 +50,6 @@ n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
namespace blink {
class ClientHintsPreferences;
-class ContentSettingsClient;
class Document;
class DocumentLoader;
class LocalFrame;
@@ -58,6 +57,7 @@ class LocalFrameClient;
class ResourceError;
class ResourceResponse;
class Settings;
+class WebContentSettingsClient;
struct WebEnabledClientHints;
class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
@@ -74,6 +74,7 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
static void ProvideDocumentToContext(FetchContext&, Document*);
+ FrameFetchContext(DocumentLoader*, Document*);
~FrameFetchContext() override;
bool IsFrameFetchContext() override { return true; }
@@ -114,9 +115,9 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
ResourceResponseType) override;
void DispatchDidReceiveData(unsigned long identifier,
const char* data,
- int data_length) override;
+ size_t data_length) override;
void DispatchDidReceiveEncodedData(unsigned long identifier,
- int encoded_data_length) override;
+ size_t encoded_data_length) override;
void DispatchDidDownloadToBlob(unsigned long identifier,
BlobDataHandle*) override;
void DispatchDidFinishLoading(unsigned long identifier,
@@ -135,6 +136,7 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
ResourceType,
const AtomicString& fetch_initiator_name) override;
void DidLoadResource(Resource*) override;
+ void DidObserveLoadingBehavior(WebLoadingBehaviorFlag) override;
void AddResourceTiming(const ResourceTimingInfo&) override;
bool AllowImage(bool images_enabled, const KURL&) const override;
@@ -191,8 +193,6 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
static ResourceFetcher* CreateFetcher(DocumentLoader*, Document*);
- FrameFetchContext(DocumentLoader*, Document*);
-
// Convenient accessors below can be used to transparently access the
// relevant document loader or frame in either cases without null-checks.
//
@@ -243,7 +243,7 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
const ContentSecurityPolicy* GetContentSecurityPolicy() const override;
void AddConsoleMessage(ConsoleMessage*) const override;
- ContentSettingsClient* GetContentSettingsClient() const;
+ WebContentSettingsClient* GetContentSettingsClient() const;
Settings* GetSettings() const;
String GetUserAgent() const;
const ClientHintsPreferences GetClientHintsPreferences() const;
@@ -252,14 +252,14 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
const ClientHintsPreferences&,
const WebEnabledClientHints&) const;
// Checks if the origin requested persisting the client hints, and notifies
- // the |ContentSettingsClient| with the list of client hints and the
+ // the |WebContentSettingsClient| with the list of client hints and the
// persistence duration.
void ParseAndPersistClientHints(const ResourceResponse&);
void SetFirstPartyCookie(ResourceRequest&);
// Returns true if execution of scripts from the url are allowed. Compared to
// AllowScriptFromSource(), this method does not generate any
- // notification to the |ContentSettingsClient| that the execution of the
+ // notification to the |WebContentSettingsClient| that the execution of the
// script was blocked. This method should be called only when there is a need
// to check the settings, and where blocked setting doesn't really imply that
// JavaScript was blocked from being executed.
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc b/chromium/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc
index 9f22a8c2395..3703b8e444d 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc
@@ -77,9 +77,11 @@ using Checkpoint = testing::StrictMock<testing::MockFunction<void(int)>>;
class StubLocalFrameClientWithParent final : public EmptyLocalFrameClient {
public:
static StubLocalFrameClientWithParent* Create(Frame* parent) {
- return new StubLocalFrameClientWithParent(parent);
+ return MakeGarbageCollected<StubLocalFrameClientWithParent>(parent);
}
+ explicit StubLocalFrameClientWithParent(Frame* parent) : parent_(parent) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(parent_);
EmptyLocalFrameClient::Trace(visitor);
@@ -88,8 +90,6 @@ class StubLocalFrameClientWithParent final : public EmptyLocalFrameClient {
Frame* Parent() const override { return parent_.Get(); }
private:
- explicit StubLocalFrameClientWithParent(Frame* parent) : parent_(parent) {}
-
Member<Frame> parent_;
};
@@ -109,9 +109,7 @@ class FixedPolicySubresourceFilter : public WebDocumentSubresourceFilter {
FixedPolicySubresourceFilter(LoadPolicy policy,
int* filtered_load_counter,
bool is_associated_with_ad_subframe)
- : policy_(policy),
- filtered_load_counter_(filtered_load_counter),
- is_associated_with_ad_subframe_(is_associated_with_ad_subframe) {}
+ : policy_(policy), filtered_load_counter_(filtered_load_counter) {}
LoadPolicy GetLoadPolicy(const WebURL& resource_url,
mojom::RequestContextType) override {
@@ -126,14 +124,9 @@ class FixedPolicySubresourceFilter : public WebDocumentSubresourceFilter {
bool ShouldLogToConsole() override { return false; }
- bool GetIsAssociatedWithAdSubframe() const override {
- return is_associated_with_ad_subframe_;
- }
-
private:
const LoadPolicy policy_;
int* filtered_load_counter_;
- bool is_associated_with_ad_subframe_;
};
class FrameFetchContextTest : public testing::Test {
@@ -356,14 +349,14 @@ class FrameFetchContextModifyRequestTest : public FrameFetchContextTest {
EXPECT_EQ(
should_prefer ? String("1") : String(),
- resource_request.HttpHeaderField(HTTPNames::Upgrade_Insecure_Requests));
+ resource_request.HttpHeaderField(http_names::kUpgradeInsecureRequests));
// Calling modifyRequestForCSP more than once shouldn't affect the
// header.
if (should_prefer) {
fetch_context->ModifyRequestForCSP(resource_request);
EXPECT_EQ("1", resource_request.HttpHeaderField(
- HTTPNames::Upgrade_Insecure_Requests));
+ http_names::kUpgradeInsecureRequests));
}
}
@@ -395,7 +388,7 @@ class FrameFetchContextModifyRequestTest : public FrameFetchContextTest {
fetch_context->ModifyRequestForCSP(resource_request);
EXPECT_EQ(expected_required_csp,
- resource_request.HttpHeaderField(HTTPNames::Sec_Required_CSP));
+ resource_request.HttpHeaderField(http_names::kSecRequiredCSP));
}
void SetFrameOwnerBasedOnFrameType(
@@ -407,7 +400,7 @@ class FrameFetchContextModifyRequestTest : public FrameFetchContextTest {
return;
}
- iframe->setAttribute(HTMLNames::cspAttr, potential_value);
+ iframe->setAttribute(html_names::kCspAttr, potential_value);
document->GetFrame()->SetOwner(iframe);
}
@@ -848,7 +841,7 @@ TEST_F(FrameFetchContextTest, MainResourceCachePolicy) {
// Post
ResourceRequest post_request("http://www.example.com");
- post_request.SetHTTPMethod(HTTPNames::POST);
+ post_request.SetHTTPMethod(http_names::kPOST);
EXPECT_EQ(mojom::FetchCacheMode::kValidateCache,
fetch_context->ResourceRequestCachePolicy(
post_request, ResourceType::kMainResource,
@@ -871,7 +864,7 @@ TEST_F(FrameFetchContextTest, MainResourceCachePolicy) {
// Conditional request
document->Loader()->SetLoadType(WebFrameLoadType::kStandard);
ResourceRequest conditional("http://www.example.com");
- conditional.SetHTTPHeaderField(HTTPNames::If_Modified_Since, "foo");
+ conditional.SetHTTPHeaderField(http_names::kIfModifiedSince, "foo");
EXPECT_EQ(
mojom::FetchCacheMode::kValidateCache,
fetch_context->ResourceRequestCachePolicy(
@@ -955,7 +948,7 @@ TEST_F(FrameFetchContextTest, SubResourceCachePolicy) {
// Conditional request
document->Loader()->SetLoadType(WebFrameLoadType::kStandard);
ResourceRequest conditional("http://www.example.com/mock");
- conditional.SetHTTPHeaderField(HTTPNames::If_Modified_Since, "foo");
+ conditional.SetHTTPHeaderField(http_names::kIfModifiedSince, "foo");
EXPECT_EQ(mojom::FetchCacheMode::kValidateCache,
fetch_context->ResourceRequestCachePolicy(
conditional, ResourceType::kMock, FetchParameters::kNoDefer));
@@ -1187,17 +1180,6 @@ TEST_F(FrameFetchContextSubresourceFilterTest, WouldDisallow) {
EXPECT_EQ(0, GetFilteredLoadCallCount());
}
-// Tests that if a subresource is allowed as per subresource filter ruleset but
-// is fetched from a frame that is tagged as an ad, then the subresource should
-// be tagged as well.
-TEST_F(FrameFetchContextSubresourceFilterTest, AdTaggingBasedOnFrame) {
- SetFilterPolicy(WebDocumentSubresourceFilter::kAllow,
- true /* is_associated_with_ad_subframe */);
-
- EXPECT_EQ(base::nullopt, CanRequestAndVerifyIsAd(true));
- EXPECT_EQ(0, GetFilteredLoadCallCount());
-}
-
TEST_F(FrameFetchContextTest, AddAdditionalRequestHeadersWhenDetached) {
const KURL document_url("https://www2.example.com/fuga/hoge.html");
const String origin = "https://www2.example.com";
@@ -1207,15 +1189,16 @@ TEST_F(FrameFetchContextTest, AddAdditionalRequestHeadersWhenDetached) {
GetNetworkStateNotifier().SetSaveDataEnabledOverride(true);
document->SetSecurityOrigin(SecurityOrigin::Create(KURL(origin)));
document->SetURL(document_url);
- document->SetReferrerPolicy(kReferrerPolicyOrigin);
+ document->SetReferrerPolicy(network::mojom::ReferrerPolicy::kOrigin);
document->SetAddressSpace(mojom::IPAddressSpace::kPublic);
dummy_page_holder = nullptr;
fetch_context->AddAdditionalRequestHeaders(request, kFetchSubresource);
- EXPECT_EQ(origin, request.HttpHeaderField(HTTPNames::Origin));
- EXPECT_EQ(String(origin + "/"), request.HttpHeaderField(HTTPNames::Referer));
+ EXPECT_EQ(origin, request.HttpHeaderField(http_names::kOrigin));
+ EXPECT_EQ(String(origin + "/"),
+ request.HttpHeaderField(http_names::kReferer));
EXPECT_EQ(String(), request.HttpHeaderField("Save-Data"));
}
@@ -1253,7 +1236,7 @@ TEST_F(FrameFetchContextMockedLocalFrameClientTest,
fetch_context->PrepareRequest(request,
FetchContext::RedirectType::kNotForRedirect);
- EXPECT_EQ("hi", request.HttpHeaderField(HTTPNames::User_Agent));
+ EXPECT_EQ("hi", request.HttpHeaderField(http_names::kUserAgent));
}
TEST_F(FrameFetchContextTest, DispatchWillSendRequestWhenDetached) {
@@ -1340,12 +1323,12 @@ TEST_F(FrameFetchContextTest, RecordLoadingActivityWhenDetached) {
dummy_page_holder = nullptr;
- fetch_context->RecordLoadingActivity(request, ResourceType::kRaw,
- FetchInitiatorTypeNames::xmlhttprequest);
+ fetch_context->RecordLoadingActivity(
+ request, ResourceType::kRaw, fetch_initiator_type_names::kXmlhttprequest);
// Should not crash.
fetch_context->RecordLoadingActivity(request, ResourceType::kRaw,
- FetchInitiatorTypeNames::document);
+ fetch_initiator_type_names::kDocument);
// Should not crash.
}
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_load_request.h b/chromium/third_party/blink/renderer/core/loader/frame_load_request.h
index d4a9a59ce13..ddfcd07500f 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_load_request.h
+++ b/chromium/third_party/blink/renderer/core/loader/frame_load_request.h
@@ -92,6 +92,11 @@ struct CORE_EXPORT FrameLoadRequest {
should_set_opener_ = should_set_opener;
}
+ const AtomicString& HrefTranslate() const { return href_translate_; }
+ void SetHrefTranslate(const AtomicString& translate) {
+ href_translate_ = translate;
+ }
+
ContentSecurityPolicyDisposition ShouldCheckMainWorldContentSecurityPolicy()
const {
return should_check_main_world_content_security_policy_;
@@ -131,6 +136,7 @@ struct CORE_EXPORT FrameLoadRequest {
Member<Document> origin_document_;
ResourceRequest resource_request_;
AtomicString frame_name_;
+ AtomicString href_translate_;
ClientRedirectPolicy client_redirect_;
WebTriggeringEventInfo triggering_event_info_ =
WebTriggeringEventInfo::kNotFromEvent;
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_loader.cc b/chromium/third_party/blink/renderer/core/loader/frame_loader.cc
index 6e5badff0e7..0501516a6c7 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -46,6 +46,7 @@
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_mixed_content.h"
#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
#include "third_party/blink/public/platform/web_url_request.h"
@@ -59,7 +60,6 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h"
#include "third_party/blink/renderer/core/events/page_transition_event.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -116,7 +116,7 @@ using blink::WebURLRequest;
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
bool IsBackForwardLoadType(WebFrameLoadType type) {
return type == WebFrameLoadType::kBackForward;
@@ -230,14 +230,15 @@ void FrameLoader::Init() {
initial_request.SetFrameType(
frame_->IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
+ initial_request.SetHasUserGesture(
+ LocalFrame::HasTransientUserActivation(frame_));
- provisional_document_loader_ = Client()->CreateDocumentLoader(
- frame_, initial_request, SubstituteData(),
+ provisional_document_loader_ = CreateDocumentLoader(
+ initial_request, SubstituteData(),
ClientRedirectPolicy::kNotClientRedirect,
- base::UnguessableToken::Create(), nullptr /* navigation_params */,
+ base::UnguessableToken::Create(), WebFrameLoadType::kStandard,
+ kWebNavigationTypeOther, nullptr /* navigation_params */,
nullptr /* extra_data */);
- if (LocalFrame::HasTransientUserActivation(frame_))
- provisional_document_loader_->SetHadTransientUserActivation();
provisional_document_loader_->StartLoading();
frame_->GetDocument()->CancelParsing();
@@ -348,6 +349,8 @@ void FrameLoader::DispatchUnloadEvent() {
}
void FrameLoader::DidExplicitOpen() {
+ probe::lifecycleEvent(frame_, GetDocumentLoader(), "init",
+ CurrentTimeTicksInSeconds());
// Calling document.open counts as committing the first real document load.
if (!state_machine_.CommittedFirstRealDocumentLoad())
state_machine_.AdvanceTo(FrameLoaderStateMachine::kCommittedFirstRealLoad);
@@ -490,8 +493,10 @@ bool FrameLoader::AllowPlugins(ReasonForCallingAllowPlugins reason) {
return false;
Settings* settings = frame_->GetSettings();
bool allowed = settings && settings->GetPluginsEnabled();
- if (!allowed && reason == kAboutToInstantiatePlugin)
- frame_->GetContentSettingsClient()->DidNotAllowPlugins();
+ if (!allowed && reason == kAboutToInstantiatePlugin) {
+ if (auto* settings_client = frame_->GetContentSettingsClient())
+ settings_client->DidNotAllowPlugins();
+ }
return allowed;
}
@@ -623,15 +628,16 @@ void FrameLoader::SetReferrerForFrameRequest(FrameLoadRequest& frame_request) {
return;
// Always use the initiating document to generate the referrer. We need to
- // generateReferrer(), because we haven't enforced ReferrerPolicy or
- // https->http referrer suppression yet.
+ // generateReferrer(), because we haven't enforced
+ // network::mojom::ReferrerPolicy or https->http referrer suppression yet.
String referrer_to_use = request.ReferrerString();
- ReferrerPolicy referrer_policy_to_use = request.GetReferrerPolicy();
+ network::mojom::ReferrerPolicy referrer_policy_to_use =
+ request.GetReferrerPolicy();
if (referrer_to_use == Referrer::ClientReferrerString())
referrer_to_use = origin_document->OutgoingReferrer();
- if (referrer_policy_to_use == kReferrerPolicyDefault)
+ if (referrer_policy_to_use == network::mojom::ReferrerPolicy::kDefault)
referrer_policy_to_use = origin_document->GetReferrerPolicy();
Referrer referrer = SecurityPolicy::GenerateReferrer(
@@ -680,7 +686,7 @@ WebFrameLoadType FrameLoader::DetermineFrameLoadType(
return WebFrameLoadType::kReplaceCurrentItem;
if (resource_request.Url() == document_loader_->UrlForHistory()) {
- if (resource_request.HttpMethod() == HTTPNames::POST)
+ if (resource_request.HttpMethod() == http_names::kPOST)
return WebFrameLoadType::kStandard;
if (!origin_document)
return WebFrameLoadType::kReload;
@@ -731,7 +737,7 @@ bool FrameLoader::PrepareRequestForThisFrame(FrameLoadRequest& request) {
request.OriginDocument()->Url()) &&
(url.ProtocolIs("filesystem") ||
(url.ProtocolIsData() &&
- NetworkUtils::IsDataURLMimeTypeSupported(url)))) {
+ network_utils::IsDataURLMimeTypeSupported(url)))) {
frame_->GetDocument()->AddConsoleMessage(ConsoleMessage::Create(
kSecurityMessageSource, kErrorMessageLevel,
"Not allowed to navigate top frame to " + url.Protocol() +
@@ -790,7 +796,6 @@ void FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
CHECK(!IsBackForwardLoadType(frame_load_type));
DCHECK(passed_request.TriggeringEventInfo() !=
WebTriggeringEventInfo::kUnknown);
- DCHECK(policy != kNavigationPolicyHandledByClient);
DCHECK(frame_->GetDocument());
if (HTMLFrameOwnerElement* element = frame_->DeprecatedLocalOwner())
@@ -886,18 +891,15 @@ void FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
frame_->IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
- mojo::ScopedMessagePipeHandle navigation_initiator_handle;
+ mojom::blink::NavigationInitiatorPtr navigation_initiator;
if (origin_document && origin_document->GetContentSecurityPolicy()
->ExperimentalFeaturesEnabled()) {
WebContentSecurityPolicyList initiator_csp =
origin_document->GetContentSecurityPolicy()
->ExposeForNavigationalChecks();
resource_request.SetInitiatorCSP(initiator_csp);
- mojom::blink::NavigationInitiatorPtr navigation_initiator;
auto request = mojo::MakeRequest(&navigation_initiator);
origin_document->BindNavigationInitiatorRequest(std::move(request));
- navigation_initiator_handle =
- navigation_initiator.PassInterface().PassHandle();
}
// Record the latest requiredCSP value that will be used when sending this
@@ -939,55 +941,14 @@ void FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
LocalFrame::ConsumeTransientUserActivation(frame_);
}
- policy = Client()->DecidePolicyForNavigation(
+ Client()->BeginNavigation(
resource_request, origin_document, nullptr /* document_loader */,
- navigation_type, policy, has_transient_activation,
- frame_load_type == WebFrameLoadType::kReplaceCurrentItem,
+ navigation_type, policy, has_transient_activation, frame_load_type,
request.ClientRedirect() == ClientRedirectPolicy::kClientRedirect,
request.TriggeringEventInfo(), request.Form(),
request.ShouldCheckMainWorldContentSecurityPolicy(),
- request.GetBlobURLToken(), request.GetInputStartTime());
-
- // 'beforeunload' can be fired above, which can detach this frame from inside
- // the event handler.
- if (!frame_->GetPage())
- return;
-
- if (policy == kNavigationPolicyIgnore)
- return;
-
- if (policy == kNavigationPolicyCurrentTab) {
- CommitNavigation(resource_request, SubstituteData(),
- request.ClientRedirect(), base::UnguessableToken::Create(),
- frame_load_type, nullptr, nullptr, nullptr);
- return;
- }
-
- DCHECK(policy == kNavigationPolicyHandledByClient);
- if (!CancelProvisionalLoaderForNewNavigation(
- true /* cancel_scheduled_navigations */)) {
- return;
- }
-
- provisional_document_loader_ = CreateDocumentLoader(
- resource_request, SubstituteData(), request.ClientRedirect(),
- base::UnguessableToken::Create(), frame_load_type, navigation_type,
- nullptr /* navigation_params */, nullptr /* extra_data */);
-
- provisional_document_loader_->AppendRedirect(
- provisional_document_loader_->Url());
- frame_->GetFrameScheduler()->DidStartProvisionalLoad(frame_->IsMainFrame());
-
- // TODO(ananta):
- // We should get rid of the dependency on the DocumentLoader in consumers of
- // the DidStartProvisionalLoad() notification.
- Client()->DispatchDidStartProvisionalLoad(
- provisional_document_loader_, resource_request,
- std::move(navigation_initiator_handle));
- probe::didStartProvisionalLoad(frame_);
- virtual_time_pauser_.PauseVirtualTime();
- DCHECK(provisional_document_loader_);
- TakeObjectSnapshot();
+ request.GetBlobURLToken(), request.GetInputStartTime(),
+ request.HrefTranslate().GetString(), std::move(navigation_initiator));
}
void FrameLoader::CommitNavigation(
@@ -1078,8 +1039,7 @@ void FrameLoader::CommitNavigation(
frame_->GetFrameScheduler()->DidStartProvisionalLoad(frame_->IsMainFrame());
Client()->DispatchDidStartProvisionalLoad(provisional_document_loader_,
- resource_request,
- mojo::ScopedMessagePipeHandle());
+ resource_request);
probe::didStartProvisionalLoad(frame_);
virtual_time_pauser_.PauseVirtualTime();
@@ -1135,10 +1095,36 @@ mojom::CommitResult FrameLoader::CommitSameDocumentNavigation(
return mojom::CommitResult::Ok;
}
+bool FrameLoader::CreatePlaceholderDocumentLoader(
+ const ResourceRequest& resource_request,
+ ClientRedirectPolicy client_redirect_policy,
+ const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType frame_load_type,
+ WebNavigationType navigation_type,
+ std::unique_ptr<WebNavigationParams> navigation_params,
+ std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) {
+ if (!CancelProvisionalLoaderForNewNavigation(
+ true /* cancel_scheduled_navigations */)) {
+ return false;
+ }
+
+ provisional_document_loader_ = CreateDocumentLoader(
+ resource_request, SubstituteData(), client_redirect_policy,
+ devtools_navigation_token, frame_load_type, navigation_type,
+ std::move(navigation_params), std::move(extra_data));
+ provisional_document_loader_->AppendRedirect(
+ provisional_document_loader_->Url());
+ frame_->GetFrameScheduler()->DidStartProvisionalLoad(frame_->IsMainFrame());
+ probe::didStartProvisionalLoad(frame_);
+ virtual_time_pauser_.PauseVirtualTime();
+ TakeObjectSnapshot();
+ return true;
+}
+
SubstituteData FrameLoader::DefaultSubstituteDataForURL(const KURL& url) {
if (!ShouldTreatURLAsSrcdocDocument(url))
return SubstituteData();
- String srcdoc = frame_->DeprecatedLocalOwner()->FastGetAttribute(srcdocAttr);
+ String srcdoc = frame_->DeprecatedLocalOwner()->FastGetAttribute(kSrcdocAttr);
DCHECK(!srcdoc.IsNull());
CString encoded_srcdoc = srcdoc.Utf8();
return SubstituteData(
@@ -1204,6 +1190,11 @@ bool FrameLoader::PrepareForCommit() {
ThreadState::Current()->SchedulePageNavigationGCIfNeeded(ratio);
}
+ // Don't allow this frame to navigate anymore. This line is needed for
+ // navigation triggered from children's unload handlers. Blocking navigations
+ // triggered from this frame's unload handler is already covered in
+ // DispatchUnloadEvent().
+ FrameNavigationDisabler navigation_disabler(*frame_);
// Don't allow any new child frames to load in this frame: attaching a new
// child frame during or after detaching children results in an attached frame
// on a detached DOM tree, which is bad.
@@ -1416,7 +1407,7 @@ bool FrameLoader::ShouldPerformFragmentNavigation(bool is_form_submission,
// We don't do this if we are submitting a form with method other than "GET",
// explicitly reloading, currently displaying a frameset, or if the URL does
// not have a fragment.
- return DeprecatedEqualIgnoringCase(http_method, HTTPNames::GET) &&
+ return DeprecatedEqualIgnoringCase(http_method, http_names::kGET) &&
!IsReloadLoadType(load_type) &&
load_type != WebFrameLoadType::kBackForward &&
url.HasFragmentIdentifier() &&
@@ -1600,7 +1591,7 @@ bool FrameLoader::ShouldTreatURLAsSrcdocDocument(const KURL& url) const {
HTMLFrameOwnerElement* owner_element = frame_->DeprecatedLocalOwner();
if (!IsHTMLIFrameElement(owner_element))
return false;
- return owner_element->FastHasAttribute(srcdocAttr);
+ return owner_element->FastHasAttribute(kSrcdocAttr);
}
void FrameLoader::DispatchDocumentElementAvailable() {
@@ -1663,7 +1654,7 @@ void FrameLoader::ModifyRequestForCSP(ResourceRequest& resource_request,
if (!RequiredCSP().IsEmpty()) {
DCHECK(
ContentSecurityPolicy::IsValidCSPAttr(RequiredCSP().GetString(), ""));
- resource_request.SetHTTPHeaderField(HTTPNames::Sec_Required_CSP,
+ resource_request.SetHTTPHeaderField(http_names::kSecRequiredCSP,
RequiredCSP());
}
@@ -1673,12 +1664,12 @@ void FrameLoader::ModifyRequestForCSP(ResourceRequest& resource_request,
if (resource_request.GetFrameType() !=
network::mojom::RequestContextFrameType::kNone) {
// Early return if the request has already been upgraded.
- if (!resource_request.HttpHeaderField(HTTPNames::Upgrade_Insecure_Requests)
+ if (!resource_request.HttpHeaderField(http_names::kUpgradeInsecureRequests)
.IsNull()) {
return;
}
- resource_request.SetHTTPHeaderField(HTTPNames::Upgrade_Insecure_Requests,
+ resource_request.SetHTTPHeaderField(http_names::kUpgradeInsecureRequests,
"1");
}
@@ -1709,11 +1700,15 @@ void FrameLoader::UpgradeInsecureRequest(ResourceRequest& resource_request,
// correctly.
if (context != mojom::RequestContextType::UNSPECIFIED &&
resource_request.Url().ProtocolIs("http") &&
+ !origin_context->GetSecurityContext().GetMixedAutoUpgradeOptOut() &&
MixedContentChecker::ShouldAutoupgrade(
origin_context->Url(),
WebMixedContent::ContextTypeFromRequestContext(context, false))) {
if (origin_context->IsDocument()) {
Document* document = static_cast<Document*>(origin_context);
+ document->AddConsoleMessage(
+ MixedContentChecker::CreateConsoleMessageAboutFetchAutoupgrade(
+ origin_context->Url(), resource_request.Url()));
resource_request.SetUkmSourceId(document->UkmSourceID());
}
resource_request.SetIsAutomaticUpgrade(true);
@@ -1799,24 +1794,8 @@ DocumentLoader* FrameLoader::CreateDocumentLoader(
frame_, request,
substitute_data.IsValid() ? substitute_data
: DefaultSubstituteDataForURL(request.Url()),
- client_redirect_policy, devtools_navigation_token,
- std::move(navigation_params), std::move(extra_data));
-
- loader->SetLoadType(load_type);
- loader->SetNavigationType(navigation_type);
- if (request.HasUserGesture())
- loader->SetHadTransientUserActivation();
- // TODO(japhet): This is needed because the browser process DCHECKs if the
- // first entry we commit in a new frame has replacement set. It's unclear
- // whether the DCHECK is right, investigate removing this special case.
- bool replace_current_item =
- load_type == WebFrameLoadType::kReplaceCurrentItem &&
- (!Opener() || !request.Url().IsEmpty());
- // TODO(dgozman): we should get rid of this boolean field, and make client
- // responsible for it's own view of "replaces current item", based on the
- // frame load type.
- loader->SetReplacesCurrentHistoryItem(replace_current_item);
-
+ client_redirect_policy, devtools_navigation_token, load_type,
+ navigation_type, std::move(navigation_params), std::move(extra_data));
probe::lifecycleEvent(frame_, loader, "init", CurrentTimeTicksInSeconds());
return loader;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_loader.h b/chromium/third_party/blink/renderer/core/loader/frame_loader.h
index 3e0b3e3ee47..9cfcee46a44 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/frame_loader.h
@@ -132,6 +132,22 @@ class CORE_EXPORT FrameLoader final {
bool has_event,
std::unique_ptr<WebDocumentLoader::ExtraData> extra_data = nullptr);
+ // Called when the browser process is handling the navigation, to
+ // create a "placeholder" document loader and mark the frame as loading.
+ // This placeholder document loader will be later abandoned, and only
+ // lives temporarily so that the rest of Blink code knows the navigation
+ // is in place.
+ // See DocumentLoader::devtools_navigation_token_ for documentation on
+ // the token.
+ bool CreatePlaceholderDocumentLoader(
+ const ResourceRequest&,
+ ClientRedirectPolicy,
+ const base::UnguessableToken& devtools_navigation_token,
+ WebFrameLoadType,
+ WebNavigationType,
+ std::unique_ptr<WebNavigationParams>,
+ std::unique_ptr<WebDocumentLoader::ExtraData>);
+
// This runs the "stop document loading" algorithm in HTML:
// https://html.spec.whatwg.org/C/browsing-the-web.html#stop-document-loading
// Note, this function only cancels ongoing navigation handled through
diff --git a/chromium/third_party/blink/renderer/core/loader/history_item.cc b/chromium/third_party/blink/renderer/core/loader/history_item.cc
index 79521ab430c..13f2c97a366 100644
--- a/chromium/third_party/blink/renderer/core/loader/history_item.cc
+++ b/chromium/third_party/blink/renderer/core/loader/history_item.cc
@@ -170,7 +170,7 @@ ResourceRequest HistoryItem::GenerateResourceRequest(
request.SetHTTPReferrer(referrer_);
request.SetCacheMode(cache_mode);
if (form_data_) {
- request.SetHTTPMethod(HTTPNames::POST);
+ request.SetHTTPMethod(http_names::kPOST);
request.SetHTTPBody(form_data_);
request.SetHTTPContentType(form_content_type_);
request.SetHTTPOriginToMatchReferrerIfNeeded();
diff --git a/chromium/third_party/blink/renderer/core/loader/history_item.h b/chromium/third_party/blink/renderer/core/loader/history_item.h
index 89bb9165d07..e0de5d0d1ad 100644
--- a/chromium/third_party/blink/renderer/core/loader/history_item.h
+++ b/chromium/third_party/blink/renderer/core/loader/history_item.h
@@ -50,7 +50,9 @@ enum class FetchCacheMode : int32_t;
class CORE_EXPORT HistoryItem final
: public GarbageCollectedFinalized<HistoryItem> {
public:
- static HistoryItem* Create() { return new HistoryItem; }
+ static HistoryItem* Create() { return MakeGarbageCollected<HistoryItem>(); }
+
+ HistoryItem();
~HistoryItem();
const String& UrlString() const;
@@ -126,8 +128,6 @@ class CORE_EXPORT HistoryItem final
void Trace(blink::Visitor*);
private:
- HistoryItem();
-
String url_string_;
Referrer referrer_;
diff --git a/chromium/third_party/blink/renderer/core/loader/http_equiv.cc b/chromium/third_party/blink/renderer/core/loader/http_equiv.cc
index befb7aee35f..798c6c7f95c 100644
--- a/chromium/third_party/blink/renderer/core/loader/http_equiv.cc
+++ b/chromium/third_party/blink/renderer/core/loader/http_equiv.cc
@@ -4,10 +4,10 @@
#include "third_party/blink/renderer/core/loader/http_equiv.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/scriptable_document_parser.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -47,13 +47,12 @@ bool IsFirstPartyOrigin(Frame* frame, const KURL& url) {
// JavaScript was blocked from being executed.
bool AllowScriptFromSourceWithoutNotifying(
const KURL& url,
- ContentSettingsClient* settings_client,
+ WebContentSettingsClient* settings_client,
Settings* settings) {
- if (settings_client && !settings_client->AllowScriptFromSource(
- !settings || settings->GetScriptEnabled(), url)) {
- return false;
- }
- return true;
+ bool allow_script = !settings || settings->GetScriptEnabled();
+ if (settings_client)
+ allow_script = settings_client->AllowScriptFromSource(allow_script, url);
+ return allow_script;
}
// Notifies content settings client of persistent client hint headers.
@@ -78,8 +77,10 @@ void NotifyPersistentClientHintsToContentSettingsClient(Document& document) {
return;
}
- document.GetFrame()->GetContentSettingsClient()->PersistClientHints(
- enabled_client_hints, persist_duration, document.Url());
+ if (auto* settings_client = document.GetFrame()->GetContentSettingsClient()) {
+ settings_client->PersistClientHints(enabled_client_hints, persist_duration,
+ document.Url());
+ }
}
} // namespace
@@ -107,9 +108,9 @@ void HttpEquiv::Process(Document& document,
kSecurityMessageSource, kErrorMessageLevel,
"X-Frame-Options may only be set via an HTTP header sent along with a "
"document. It may not be set inside <meta>."));
- } else if (EqualIgnoringASCIICase(equiv, HTTPNames::Accept_CH)) {
+ } else if (EqualIgnoringASCIICase(equiv, http_names::kAcceptCH)) {
ProcessHttpEquivAcceptCH(document, content);
- } else if (EqualIgnoringASCIICase(equiv, HTTPNames::Accept_CH_Lifetime)) {
+ } else if (EqualIgnoringASCIICase(equiv, http_names::kAcceptCHLifetime)) {
ProcessHttpEquivAcceptCHLifetime(document, content);
} else if (EqualIgnoringASCIICase(equiv, "content-security-policy") ||
EqualIgnoringASCIICase(equiv,
@@ -118,7 +119,7 @@ void HttpEquiv::Process(Document& document,
ProcessHttpEquivContentSecurityPolicy(document, equiv, content);
else
document.GetContentSecurityPolicy()->ReportMetaOutsideHead(content);
- } else if (EqualIgnoringASCIICase(equiv, HTTPNames::Origin_Trial)) {
+ } else if (EqualIgnoringASCIICase(equiv, http_names::kOriginTrial)) {
if (in_document_head_element)
OriginTrialContext::FromOrCreate(&document)->AddToken(content);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/idleness_detector.cc b/chromium/third_party/blink/renderer/core/loader/idleness_detector.cc
index f8aa794a713..97145186485 100644
--- a/chromium/third_party/blink/renderer/core/loader/idleness_detector.cc
+++ b/chromium/third_party/blink/renderer/core/loader/idleness_detector.cc
@@ -39,7 +39,7 @@ void IdlenessDetector::DomContentLoadedEventFired() {
return;
if (!task_observer_added_) {
- Platform::Current()->CurrentThread()->AddTaskTimeObserver(this);
+ Thread::Current()->AddTaskTimeObserver(this);
task_observer_added_ = true;
}
@@ -187,7 +187,7 @@ void IdlenessDetector::Stop() {
network_quiet_timer_.Stop();
if (!task_observer_added_)
return;
- Platform::Current()->CurrentThread()->RemoveTaskTimeObserver(this);
+ Thread::Current()->RemoveTaskTimeObserver(this);
task_observer_added_ = false;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/image_loader.cc b/chromium/third_party/blink/renderer/core/loader/image_loader.cc
index 7a89b040705..da853f20609 100644
--- a/chromium/third_party/blink/renderer/core/loader/image_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/image_loader.cc
@@ -30,10 +30,15 @@
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/increment_load_event_delay_count.h"
+#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
+#include "third_party/blink/renderer/core/frame/frame_owner.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
@@ -75,8 +80,8 @@ bool GetAbsoluteDimensionValue(const AtomicString& attribute_value,
return false;
}
-bool IsLazyLoadingImageAllowed(const LocalFrame* frame,
- HTMLImageElement* html_image) {
+bool IsLazyLoadableImage(const LocalFrame* frame,
+ HTMLImageElement* html_image) {
// Minimum width or height attribute of the image to start lazyloading.
const unsigned kMinDimensionToLazyLoad = 10;
@@ -85,20 +90,39 @@ bool IsLazyLoadingImageAllowed(const LocalFrame* frame,
return false;
if (EqualIgnoringASCIICase(
- html_image->FastGetAttribute(HTMLNames::lazyloadAttr), "off"))
+ html_image->FastGetAttribute(html_names::kLazyloadAttr), "off") &&
+ !frame->GetDocument()->IsLazyLoadPolicyEnforced()) {
return false;
-
+ }
// Avoid lazyloading if width and height attributes are small. This
// heuristic helps avoid double fetching tracking pixels.
double width, height;
- if (GetAbsoluteDimensionValue(html_image->getAttribute(HTMLNames::widthAttr),
- &width) &&
- GetAbsoluteDimensionValue(html_image->getAttribute(HTMLNames::heightAttr),
- &height) &&
+ if (GetAbsoluteDimensionValue(
+ html_image->getAttribute(html_names::kWidthAttr), &width) &&
+ GetAbsoluteDimensionValue(
+ html_image->getAttribute(html_names::kHeightAttr), &height) &&
width <= kMinDimensionToLazyLoad && height <= kMinDimensionToLazyLoad) {
return false;
}
- return frame->IsLazyLoadingImageAllowed();
+ // Avoid lazyloading if width or height is specified in inline style and is
+ // small enough. This heuristic helps avoid double fetching tracking pixels.
+ if (const auto* property_set = html_image->InlineStyle()) {
+ const CSSValue* width = property_set->GetPropertyCSSValue(CSSPropertyWidth);
+ const CSSValue* height =
+ property_set->GetPropertyCSSValue(CSSPropertyHeight);
+ if (width && width->IsPrimitiveValue() && height &&
+ height->IsPrimitiveValue()) {
+ const CSSPrimitiveValue* width_prim = ToCSSPrimitiveValue(width);
+ const CSSPrimitiveValue* height_prim = ToCSSPrimitiveValue(height);
+ if (height_prim->IsPx() &&
+ (height_prim->GetDoubleValue() <= kMinDimensionToLazyLoad) &&
+ width_prim->IsPx() &&
+ (width_prim->GetDoubleValue() <= kMinDimensionToLazyLoad)) {
+ return false;
+ }
+ }
+ }
+ return true;
}
} // namespace
@@ -107,22 +131,20 @@ static ImageLoader::BypassMainWorldBehavior ShouldBypassMainWorldCSP(
ImageLoader* loader) {
DCHECK(loader);
DCHECK(loader->GetElement());
- if (loader->GetElement()->GetDocument().GetFrame() &&
- loader->GetElement()
- ->GetDocument()
- .GetFrame()
- ->GetScriptController()
- .ShouldBypassMainWorldCSP())
+ if (ContentSecurityPolicy::ShouldBypassMainWorld(
+ &loader->GetElement()->GetDocument())) {
return ImageLoader::kBypassMainWorldCSP;
+ }
return ImageLoader::kDoNotBypassMainWorldCSP;
}
class ImageLoader::Task {
public:
- static std::unique_ptr<Task> Create(ImageLoader* loader,
- const KURL& request_url,
- UpdateFromElementBehavior update_behavior,
- ReferrerPolicy referrer_policy) {
+ static std::unique_ptr<Task> Create(
+ ImageLoader* loader,
+ const KURL& request_url,
+ UpdateFromElementBehavior update_behavior,
+ network::mojom::ReferrerPolicy referrer_policy) {
return std::make_unique<Task>(loader, request_url, update_behavior,
referrer_policy);
}
@@ -130,7 +152,7 @@ class ImageLoader::Task {
Task(ImageLoader* loader,
const KURL& request_url,
UpdateFromElementBehavior update_behavior,
- ReferrerPolicy referrer_policy)
+ network::mojom::ReferrerPolicy referrer_policy)
: loader_(loader),
should_bypass_main_world_csp_(ShouldBypassMainWorldCSP(loader)),
update_behavior_(update_behavior),
@@ -182,7 +204,7 @@ class ImageLoader::Task {
BypassMainWorldBehavior should_bypass_main_world_csp_;
UpdateFromElementBehavior update_behavior_;
WeakPersistent<ScriptState> script_state_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
KURL request_url_;
base::WeakPtrFactory<Task> weak_factory_;
};
@@ -366,7 +388,7 @@ static void ConfigureRequest(
params.SetContentSecurityCheck(kDoNotCheckContentSecurityPolicy);
CrossOriginAttributeValue cross_origin = GetCrossOriginAttributeValue(
- element.FastGetAttribute(HTMLNames::crossoriginAttr));
+ element.FastGetAttribute(html_names::kCrossoriginAttr));
if (cross_origin != kCrossOriginAttributeNotSet) {
params.SetCrossOriginAccessControl(
element.GetDocument().GetSecurityOrigin(), cross_origin);
@@ -375,7 +397,7 @@ static void ConfigureRequest(
if (RuntimeEnabledFeatures::PriorityHintsEnabled()) {
mojom::FetchImportanceMode importance_mode =
GetFetchImportanceAttributeValue(
- element.FastGetAttribute(HTMLNames::importanceAttr));
+ element.FastGetAttribute(html_names::kImportanceAttr));
params.SetFetchImportanceMode(importance_mode);
}
@@ -411,7 +433,7 @@ inline void ImageLoader::ClearFailedLoadURL() {
inline void ImageLoader::EnqueueImageLoadingMicroTask(
const KURL& request_url,
UpdateFromElementBehavior update_behavior,
- ReferrerPolicy referrer_policy) {
+ network::mojom::ReferrerPolicy referrer_policy) {
std::unique_ptr<Task> task =
Task::Create(this, request_url, update_behavior, referrer_policy);
pending_task_ = task->GetWeakPtr();
@@ -438,11 +460,12 @@ void ImageLoader::UpdateImageState(ImageResourceContent* new_image_content) {
delay_until_image_notify_finished_ = nullptr;
}
-void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
- UpdateFromElementBehavior update_behavior,
- const KURL& url,
- ReferrerPolicy referrer_policy,
- UpdateType update_type) {
+void ImageLoader::DoUpdateFromElement(
+ BypassMainWorldBehavior bypass_behavior,
+ UpdateFromElementBehavior update_behavior,
+ const KURL& url,
+ network::mojom::ReferrerPolicy referrer_policy,
+ UpdateType update_type) {
// FIXME: According to
// http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content.html#the-img-element:the-img-element-55
// When "update image" is called due to environment changes and the load
@@ -477,7 +500,7 @@ void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
// Correct the RequestContext if necessary.
if (IsHTMLPictureElement(GetElement()->parentNode()) ||
- !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) {
+ !GetElement()->FastGetAttribute(html_names::kSrcsetAttr).IsNull()) {
resource_request.SetRequestContext(mojom::RequestContextType::IMAGE_SET);
} else if (IsHTMLObjectElement(GetElement())) {
resource_request.SetRequestContext(mojom::RequestContextType::OBJECT);
@@ -488,7 +511,7 @@ void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
bool page_is_being_dismissed =
document.PageDismissalEventBeingDispatched() != Document::kNoDismissal;
if (page_is_being_dismissed) {
- resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ resource_request.SetHTTPHeaderField(http_names::kCacheControl,
"max-age=0");
resource_request.SetKeepalive(true);
resource_request.SetRequestContext(mojom::RequestContextType::PING);
@@ -514,11 +537,15 @@ void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
if (frame->IsClientLoFiAllowed(params.GetResourceRequest())) {
params.SetClientLoFiPlaceholder();
} else if (auto* html_image = ToHTMLImageElementOrNull(GetElement())) {
- if (IsLazyLoadingImageAllowed(frame, html_image)) {
- params.SetLazyImagePlaceholder();
- lazy_image_load_state_ = LazyImageLoadState::kDeferred;
+ if (IsLazyLoadableImage(frame, html_image)) {
+ if (frame->GetDocument()->GetSettings()->GetLazyLoadEnabled() &&
+ frame->IsLazyLoadingImageAllowed()) {
+ params.SetLazyImagePlaceholder();
+ lazy_image_load_state_ = LazyImageLoadState::kDeferred;
+ }
+ if (!frame->Owner() || frame->Owner()->ShouldLazyLoadChildren())
+ LazyLoadImageObserver::StartTrackingVisibilityMetrics(html_image);
}
- LazyLoadImageObserver::StartTrackingVisibilityMetrics(html_image);
}
}
@@ -577,8 +604,9 @@ void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior,
image_resource->ResetAnimation();
}
-void ImageLoader::UpdateFromElement(UpdateFromElementBehavior update_behavior,
- ReferrerPolicy referrer_policy) {
+void ImageLoader::UpdateFromElement(
+ UpdateFromElementBehavior update_behavior,
+ network::mojom::ReferrerPolicy referrer_policy) {
AtomicString image_source_url = element_->ImageSourceURL();
suppress_error_events_ = (update_behavior == kUpdateSizeChanged);
last_base_element_url_ =
@@ -858,7 +886,7 @@ void ImageLoader::DispatchPendingLoadEvent(
void ImageLoader::DispatchPendingErrorEvent(
std::unique_ptr<IncrementLoadEventDelayCount> count) {
if (GetElement()->GetDocument().GetFrame())
- GetElement()->DispatchEvent(*Event::Create(EventTypeNames::error));
+ GetElement()->DispatchEvent(*Event::Create(event_type_names::kError));
// Checks Document's load event synchronously here for performance.
// This is safe because DispatchPendingErrorEvent() is called asynchronously.
@@ -888,15 +916,16 @@ ScriptPromise ImageLoader::Decode(ScriptState* script_state,
UseCounter::Count(GetElement()->GetDocument(), WebFeature::kImageDecodeAPI);
- auto* request =
- new DecodeRequest(this, ScriptPromiseResolver::Create(script_state));
+ auto* request = MakeGarbageCollected<DecodeRequest>(
+ this, ScriptPromiseResolver::Create(script_state));
Microtask::EnqueueMicrotask(
WTF::Bind(&DecodeRequest::ProcessForTask, WrapWeakPersistent(request)));
decode_requests_.push_back(request);
return request->promise();
}
-void ImageLoader::LoadDeferredImage(ReferrerPolicy referrer_policy) {
+void ImageLoader::LoadDeferredImage(
+ network::mojom::ReferrerPolicy referrer_policy) {
if (lazy_image_load_state_ != LazyImageLoadState::kDeferred)
return;
DCHECK(!image_complete_);
diff --git a/chromium/third_party/blink/renderer/core/loader/image_loader.h b/chromium/third_party/blink/renderer/core/loader/image_loader.h
index 21b5943d750..1cde362805b 100644
--- a/chromium/third_party/blink/renderer/core/loader/image_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/image_loader.h
@@ -78,7 +78,8 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
};
void UpdateFromElement(UpdateFromElementBehavior = kUpdateNormal,
- ReferrerPolicy = kReferrerPolicyDefault);
+ network::mojom::ReferrerPolicy =
+ network::mojom::ReferrerPolicy::kDefault);
void ElementDidMoveToNewDocument();
@@ -125,7 +126,7 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
ScriptPromise Decode(ScriptState*, ExceptionState&);
- void LoadDeferredImage(ReferrerPolicy);
+ void LoadDeferredImage(network::mojom::ReferrerPolicy);
protected:
void ImageChanged(ImageResourceContent*, CanDeferInvalidation) override;
@@ -152,11 +153,12 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
};
// Called from the task or from updateFromElement to initiate the load.
- void DoUpdateFromElement(BypassMainWorldBehavior,
- UpdateFromElementBehavior,
- const KURL&,
- ReferrerPolicy = kReferrerPolicyDefault,
- UpdateType = UpdateType::kAsync);
+ void DoUpdateFromElement(
+ BypassMainWorldBehavior,
+ UpdateFromElementBehavior,
+ const KURL&,
+ network::mojom::ReferrerPolicy = network::mojom::ReferrerPolicy::kDefault,
+ UpdateType = UpdateType::kAsync);
virtual void DispatchLoadEvent() = 0;
virtual void NoImageResourceToLoad() {}
@@ -181,7 +183,7 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
void CrossSiteOrCSPViolationOccurred(AtomicString);
void EnqueueImageLoadingMicroTask(const KURL&,
UpdateFromElementBehavior,
- ReferrerPolicy);
+ network::mojom::ReferrerPolicy);
KURL ImageSourceToKURL(AtomicString) const;
diff --git a/chromium/third_party/blink/renderer/core/loader/interactive_detector.cc b/chromium/third_party/blink/renderer/core/loader/interactive_detector.cc
index f70b9be7318..f5f99f49c47 100644
--- a/chromium/third_party/blink/renderer/core/loader/interactive_detector.cc
+++ b/chromium/third_party/blink/renderer/core/loader/interactive_detector.cc
@@ -33,8 +33,8 @@ InteractiveDetector* InteractiveDetector::From(Document& document) {
InteractiveDetector* detector =
Supplement<Document>::From<InteractiveDetector>(document);
if (!detector) {
- detector = new InteractiveDetector(document,
- new NetworkActivityChecker(&document));
+ detector = MakeGarbageCollected<InteractiveDetector>(
+ document, new NetworkActivityChecker(&document));
Supplement<Document>::ProvideTo(document, detector);
}
return detector;
diff --git a/chromium/third_party/blink/renderer/core/loader/interactive_detector.h b/chromium/third_party/blink/renderer/core/loader/interactive_detector.h
index ce88419ffcc..d13ce52c172 100644
--- a/chromium/third_party/blink/renderer/core/loader/interactive_detector.h
+++ b/chromium/third_party/blink/renderer/core/loader/interactive_detector.h
@@ -58,6 +58,8 @@ class CORE_EXPORT InteractiveDetector
// Exposed for tests. See crbug.com/810381. We must use a consistent address
// for the supplement name.
static const char* SupplementName();
+
+ explicit InteractiveDetector(Document&, NetworkActivityChecker*);
~InteractiveDetector() override = default;
// Calls to CurrentTimeTicksInSeconds is expensive, so we try not to call it
@@ -115,8 +117,6 @@ class CORE_EXPORT InteractiveDetector
private:
friend class InteractiveDetectorTest;
- explicit InteractiveDetector(Document&, NetworkActivityChecker*);
-
TimeTicks interactive_time_;
TimeTicks interactive_detection_time_;
diff --git a/chromium/third_party/blink/renderer/core/loader/interactive_detector_test.cc b/chromium/third_party/blink/renderer/core/loader/interactive_detector_test.cc
index 31a5a8505c6..9e5a3f47f79 100644
--- a/chromium/third_party/blink/renderer/core/loader/interactive_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/interactive_detector_test.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
namespace blink {
@@ -42,7 +43,7 @@ class InteractiveDetectorTest : public testing::Test {
Document* document = &dummy_page_holder_->GetDocument();
- detector_ = new InteractiveDetector(
+ detector_ = MakeGarbageCollected<InteractiveDetector>(
*document, new NetworkActivityCheckerForTest(document));
// By this time, the DummyPageHolder has created an InteractiveDetector, and
@@ -521,7 +522,7 @@ TEST_F(InteractiveDetectorTest, TaskLongerThan5sBlocksTTI) {
// Post a task with 6 seconds duration.
PostCrossThreadTask(
- *platform_->CurrentThread()->GetTaskRunner(), FROM_HERE,
+ *Thread::Current()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(&InteractiveDetectorTest::DummyTaskWithDuration,
CrossThreadUnretained(this), 6.0));
@@ -542,7 +543,7 @@ TEST_F(InteractiveDetectorTest, LongTaskAfterTTIDoesNothing) {
// Long task 1.
PostCrossThreadTask(
- *platform_->CurrentThread()->GetTaskRunner(), FROM_HERE,
+ *Thread::Current()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(&InteractiveDetectorTest::DummyTaskWithDuration,
CrossThreadUnretained(this), 0.1));
@@ -555,7 +556,7 @@ TEST_F(InteractiveDetectorTest, LongTaskAfterTTIDoesNothing) {
// Long task 2.
PostCrossThreadTask(
- *platform_->CurrentThread()->GetTaskRunner(), FROM_HERE,
+ *Thread::Current()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(&InteractiveDetectorTest::DummyTaskWithDuration,
CrossThreadUnretained(this), 0.1));
diff --git a/chromium/third_party/blink/renderer/core/loader/link_loader.cc b/chromium/third_party/blink/renderer/core/loader/link_loader.cc
index 4dde70755e9..6aee31d15ba 100644
--- a/chromium/third_party/blink/renderer/core/loader/link_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/link_loader.cc
@@ -99,10 +99,10 @@ LinkLoadParameters::LinkLoadParameters(const LinkHeader& header,
media(header.Media()),
nonce(header.Nonce()),
integrity(header.Integrity()),
- referrer_policy(kReferrerPolicyDefault),
+ referrer_policy(network::mojom::ReferrerPolicy::kDefault),
href(KURL(base_url, header.Url())),
- srcset(header.Srcset()),
- sizes(header.Imgsizes()) {}
+ image_srcset(header.ImageSrcset()),
+ image_sizes(header.ImageSizes()) {}
class LinkLoader::FinishObserver final
: public GarbageCollectedFinalized<ResourceFinishObserver>,
@@ -362,14 +362,14 @@ static Resource* PreloadIfNeeded(const LinkLoadParameters& params,
MediaValues* media_values = nullptr;
KURL url;
- if (resource_type == ResourceType::kImage && !params.srcset.IsEmpty() &&
+ if (resource_type == ResourceType::kImage && !params.image_srcset.IsEmpty() &&
RuntimeEnabledFeatures::PreloadImageSrcSetEnabled()) {
media_values = CreateMediaValues(document, viewport_description);
float source_size =
- SizesAttributeParser(media_values, params.sizes).length();
+ SizesAttributeParser(media_values, params.image_sizes).length();
ImageCandidate candidate = BestFitSourceForImageAttributes(
media_values->DevicePixelRatio(), source_size, params.href,
- params.srcset);
+ params.image_srcset);
url = base_url.IsNull() ? document.CompleteURL(candidate.ToString())
: KURL(base_url, candidate.ToString());
} else {
@@ -417,7 +417,7 @@ static Resource* PreloadIfNeeded(const LinkLoadParameters& params,
GetFetchImportanceAttributeValue(params.importance));
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::link;
+ options.initiator_info.name = fetch_initiator_type_names::kLink;
options.parser_disposition = parser_disposition;
FetchParameters link_fetch_params(resource_request, options);
link_fetch_params.SetCharset(document.Encoding());
@@ -577,7 +577,7 @@ static Resource* PrefetchIfNeeded(const LinkLoadParameters& params,
GetFetchImportanceAttributeValue(params.importance));
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::link;
+ options.initiator_info.name = fetch_initiator_type_names::kLink;
FetchParameters link_fetch_params(resource_request, options);
if (params.cross_origin != kCrossOriginAttributeNotSet) {
@@ -664,7 +664,7 @@ bool LinkLoader::LoadLink(
resource = PrefetchIfNeeded(params, document);
}
if (resource)
- finish_observer_ = new FinishObserver(this, resource);
+ finish_observer_ = MakeGarbageCollected<FinishObserver>(this, resource);
ModulePreloadIfNeeded(params, document, nullptr, this);
diff --git a/chromium/third_party/blink/renderer/core/loader/link_loader.h b/chromium/third_party/blink/renderer/core/loader/link_loader.h
index 30d226e5ddb..75674849d22 100644
--- a/chromium/third_party/blink/renderer/core/loader/link_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/link_loader.h
@@ -63,10 +63,10 @@ struct LinkLoadParameters {
const String& nonce,
const String& integrity,
const String& importance,
- const ReferrerPolicy& referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const KURL& href,
- const String& srcset,
- const String& sizes)
+ const String& image_srcset,
+ const String& image_sizes)
: rel(rel),
cross_origin(cross_origin),
type(type),
@@ -77,8 +77,8 @@ struct LinkLoadParameters {
importance(importance),
referrer_policy(referrer_policy),
href(href),
- srcset(srcset),
- sizes(sizes) {}
+ image_srcset(image_srcset),
+ image_sizes(image_sizes) {}
LinkLoadParameters(const LinkHeader&, const KURL& base_url);
LinkRelAttribute rel;
@@ -89,10 +89,10 @@ struct LinkLoadParameters {
String nonce;
String integrity;
String importance;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
KURL href;
- String srcset;
- String sizes;
+ String image_srcset;
+ String image_sizes;
};
// The LinkLoader can load link rel types icon, dns-prefetch, prefetch, and
@@ -103,8 +103,11 @@ class CORE_EXPORT LinkLoader final : public SingleModuleClient,
public:
static LinkLoader* Create(LinkLoaderClient* client) {
- return new LinkLoader(client, client->GetLoadingTaskRunner());
+ return MakeGarbageCollected<LinkLoader>(client,
+ client->GetLoadingTaskRunner());
}
+
+ LinkLoader(LinkLoaderClient*, scoped_refptr<base::SingleThreadTaskRunner>);
~LinkLoader() override;
// from PrerenderClient
@@ -150,7 +153,6 @@ class CORE_EXPORT LinkLoader final : public SingleModuleClient,
private:
class FinishObserver;
- LinkLoader(LinkLoaderClient*, scoped_refptr<base::SingleThreadTaskRunner>);
void NotifyFinished();
// SingleModuleClient implementation
diff --git a/chromium/third_party/blink/renderer/core/loader/link_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/link_loader_test.cc
index 31b35163477..6d777dd9e09 100644
--- a/chromium/third_party/blink/renderer/core/loader/link_loader_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/link_loader_test.cc
@@ -53,7 +53,7 @@ class MockLinkLoaderClient final
void DidSendDOMContentLoadedForLinkPrerender() override {}
scoped_refptr<base::SingleThreadTaskRunner> GetLoadingTaskRunner() override {
- return Platform::Current()->CurrentThread()->GetTaskRunner();
+ return Thread::Current()->GetTaskRunner();
}
private:
@@ -97,7 +97,7 @@ class LinkLoaderPreloadTestBase : public testing::Test {
mojom::RequestContextType context;
bool link_loader_should_load_value;
KURL load_url;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
};
LinkLoaderPreloadTestBase() {
@@ -119,7 +119,7 @@ class LinkLoaderPreloadTestBase : public testing::Test {
Persistent<MockLinkLoaderClient> loader_client =
MockLinkLoaderClient::Create(expected.link_loader_should_load_value);
LinkLoader* loader = LinkLoader::Create(loader_client.Get());
- URLTestHelpers::RegisterMockedErrorURLLoad(params.href);
+ url_test_helpers::RegisterMockedErrorURLLoad(params.href);
loader->LoadLink(params, dummy_page_holder_->GetDocument(),
NetworkHintsMock());
if (!expected.load_url.IsNull() &&
@@ -132,7 +132,8 @@ class LinkLoaderPreloadTestBase : public testing::Test {
EXPECT_EQ(expected.priority, resource->GetResourceRequest().Priority());
EXPECT_EQ(expected.context,
resource->GetResourceRequest().GetRequestContext());
- if (expected.referrer_policy != kReferrerPolicyDefault) {
+ if (expected.referrer_policy !=
+ network::mojom::ReferrerPolicy::kDefault) {
EXPECT_EQ(expected.referrer_policy,
resource->GetResourceRequest().GetReferrerPolicy());
}
@@ -188,12 +189,12 @@ TEST_P(LinkLoaderPreloadTest, Preload) {
LinkLoadParameters params(
LinkRelAttribute("preload"), kCrossOriginAttributeNotSet, String(),
test_case.as, String(), String(), String(), String(),
- kReferrerPolicyDefault, KURL(NullURL(), test_case.href), String(),
- String());
+ network::mojom::ReferrerPolicy::kDefault, KURL(NullURL(), test_case.href),
+ String(), String());
Expectations expectations = {
test_case.priority, test_case.context, test_case.expecting_load,
test_case.expecting_load ? params.href : NullURL(),
- kReferrerPolicyDefault};
+ network::mojom::ReferrerPolicy::kDefault};
TestPreload(params, expectations);
}
@@ -263,12 +264,12 @@ TEST_P(LinkLoaderPreloadMimeTypeTest, Preload) {
LinkLoadParameters params(
LinkRelAttribute("preload"), kCrossOriginAttributeNotSet, test_case.type,
test_case.as, String(), String(), String(), String(),
- kReferrerPolicyDefault, KURL(NullURL(), test_case.href), String(),
- String());
+ network::mojom::ReferrerPolicy::kDefault, KURL(NullURL(), test_case.href),
+ String(), String());
Expectations expectations = {
test_case.priority, test_case.context, test_case.expecting_load,
test_case.expecting_load ? params.href : NullURL(),
- kReferrerPolicyDefault};
+ network::mojom::ReferrerPolicy::kDefault};
TestPreload(params, expectations);
}
@@ -297,13 +298,13 @@ TEST_P(LinkLoaderPreloadMediaTest, Preload) {
LinkLoadParameters params(
LinkRelAttribute("preload"), kCrossOriginAttributeNotSet, "image/gif",
"image", test_case.media, String(), String(), String(),
- kReferrerPolicyDefault, KURL(NullURL(), "http://example.test/cat.gif"),
- String(), String());
+ network::mojom::ReferrerPolicy::kDefault,
+ KURL(NullURL(), "http://example.test/cat.gif"), String(), String());
Expectations expectations = {
test_case.priority, mojom::RequestContextType::IMAGE,
test_case.link_loader_should_load_value,
test_case.expecting_load ? params.href : NullURL(),
- kReferrerPolicyDefault};
+ network::mojom::ReferrerPolicy::kDefault};
TestPreload(params, expectations);
}
@@ -311,20 +312,21 @@ INSTANTIATE_TEST_CASE_P(LinkLoaderPreloadMediaTest,
LinkLoaderPreloadMediaTest,
testing::ValuesIn(kPreloadMediaTestParams));
-constexpr ReferrerPolicy kPreloadReferrerPolicyTestParams[] = {
- kReferrerPolicyOrigin,
- kReferrerPolicyOriginWhenCrossOrigin,
- kReferrerPolicySameOrigin,
- kReferrerPolicyStrictOrigin,
- kReferrerPolicyStrictOriginWhenCrossOrigin,
- kReferrerPolicyNever};
+constexpr network::mojom::ReferrerPolicy kPreloadReferrerPolicyTestParams[] = {
+ network::mojom::ReferrerPolicy::kOrigin,
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin,
+ network::mojom::ReferrerPolicy::kSameOrigin,
+ network::mojom::ReferrerPolicy::kStrictOrigin,
+ network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ network::mojom::ReferrerPolicy::kNever};
class LinkLoaderPreloadReferrerPolicyTest
: public LinkLoaderPreloadTestBase,
- public testing::WithParamInterface<ReferrerPolicy> {};
+ public testing::WithParamInterface<network::mojom::ReferrerPolicy> {};
TEST_P(LinkLoaderPreloadReferrerPolicyTest, Preload) {
- const ReferrerPolicy referrer_policy = GetParam();
+ const network::mojom::ReferrerPolicy referrer_policy = GetParam();
LinkLoadParameters params(
LinkRelAttribute("preload"), kCrossOriginAttributeNotSet, "image/gif",
"image", String(), String(), String(), String(), referrer_policy,
@@ -365,13 +367,13 @@ TEST_P(LinkLoaderPreloadNonceTest, Preload) {
LinkLoadParameters params(
LinkRelAttribute("preload"), kCrossOriginAttributeNotSet, String(),
"script", String(), test_case.nonce, String(), String(),
- kReferrerPolicyDefault, KURL(NullURL(), "http://example.test/cat.js"),
- String(), String());
+ network::mojom::ReferrerPolicy::kDefault,
+ KURL(NullURL(), "http://example.test/cat.js"), String(), String());
Expectations expectations = {
ResourceLoadPriority::kHigh, mojom::RequestContextType::SCRIPT,
test_case.expecting_load,
test_case.expecting_load ? params.href : NullURL(),
- kReferrerPolicyDefault};
+ network::mojom::ReferrerPolicy::kDefault};
TestPreload(params, expectations);
}
@@ -379,15 +381,15 @@ INSTANTIATE_TEST_CASE_P(LinkLoaderPreloadNonceTest,
LinkLoaderPreloadNonceTest,
testing::ValuesIn(kPreloadNonceTestParams));
-struct PreloadSrcsetTestParams {
+struct PreloadImageSrcsetTestParams {
const char* href;
- const char* srcset;
- const char* sizes;
+ const char* image_srcset;
+ const char* image_sizes;
float scale_factor;
const char* expected_url;
};
-constexpr PreloadSrcsetTestParams kPreloadSrcsetTestParams[] = {
+constexpr PreloadImageSrcsetTestParams kPreloadImageSrcsetTestParams[] = {
{"http://example.test/cat.gif",
"http://example.test/cat1x.gif 1x, http://example.test/cat2x.gif 2x",
nullptr, 1.0, "http://example.test/cat1x.gif"},
@@ -405,11 +407,11 @@ constexpr PreloadSrcsetTestParams kPreloadSrcsetTestParams[] = {
"http://example.test/cat200.gif"},
};
-class LinkLoaderPreloadSrcsetTest
+class LinkLoaderPreloadImageSrcsetTest
: public LinkLoaderPreloadTestBase,
- public testing::WithParamInterface<PreloadSrcsetTestParams> {};
+ public testing::WithParamInterface<PreloadImageSrcsetTestParams> {};
-TEST_P(LinkLoaderPreloadSrcsetTest, Preload) {
+TEST_P(LinkLoaderPreloadImageSrcsetTest, Preload) {
const auto& test_case = GetParam();
dummy_page_holder_->GetDocument().SetBaseURLOverride(
KURL("http://example.test/"));
@@ -417,43 +419,46 @@ TEST_P(LinkLoaderPreloadSrcsetTest, Preload) {
test_case.scale_factor);
LinkLoadParameters params(
LinkRelAttribute("preload"), kCrossOriginAttributeNotSet, "image/gif",
- "image", String(), String(), String(), String(), kReferrerPolicyDefault,
- KURL(NullURL(), test_case.href), test_case.srcset, test_case.sizes);
- Expectations expectations = {
- ResourceLoadPriority::kLow, mojom::RequestContextType::IMAGE, true,
- KURL(NullURL(), test_case.expected_url), kReferrerPolicyDefault};
+ "image", String(), String(), String(), String(),
+ network::mojom::ReferrerPolicy::kDefault, KURL(NullURL(), test_case.href),
+ test_case.image_srcset, test_case.image_sizes);
+ Expectations expectations = {ResourceLoadPriority::kLow,
+ mojom::RequestContextType::IMAGE, true,
+ KURL(NullURL(), test_case.expected_url),
+ network::mojom::ReferrerPolicy::kDefault};
TestPreload(params, expectations);
}
-INSTANTIATE_TEST_CASE_P(LinkLoaderPreloadSrcsetTest,
- LinkLoaderPreloadSrcsetTest,
- testing::ValuesIn(kPreloadSrcsetTestParams));
+INSTANTIATE_TEST_CASE_P(LinkLoaderPreloadImageSrcsetTest,
+ LinkLoaderPreloadImageSrcsetTest,
+ testing::ValuesIn(kPreloadImageSrcsetTestParams));
struct ModulePreloadTestParams {
const char* href;
const char* nonce;
const char* integrity;
CrossOriginAttributeValue cross_origin;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
bool expecting_load;
network::mojom::FetchCredentialsMode expected_credentials_mode;
};
constexpr ModulePreloadTestParams kModulePreloadTestParams[] = {
- {"", nullptr, nullptr, kCrossOriginAttributeNotSet, kReferrerPolicyDefault,
- false, network::mojom::FetchCredentialsMode::kSameOrigin},
- {"http://example.test/cat.js", nullptr, nullptr,
- kCrossOriginAttributeNotSet, kReferrerPolicyDefault, true,
+ {"", nullptr, nullptr, kCrossOriginAttributeNotSet,
+ network::mojom::ReferrerPolicy::kDefault, false,
network::mojom::FetchCredentialsMode::kSameOrigin},
{"http://example.test/cat.js", nullptr, nullptr,
- kCrossOriginAttributeAnonymous, kReferrerPolicyDefault, true,
- network::mojom::FetchCredentialsMode::kSameOrigin},
+ kCrossOriginAttributeNotSet, network::mojom::ReferrerPolicy::kDefault,
+ true, network::mojom::FetchCredentialsMode::kSameOrigin},
+ {"http://example.test/cat.js", nullptr, nullptr,
+ kCrossOriginAttributeAnonymous, network::mojom::ReferrerPolicy::kDefault,
+ true, network::mojom::FetchCredentialsMode::kSameOrigin},
{"http://example.test/cat.js", "nonce", nullptr,
- kCrossOriginAttributeNotSet, kReferrerPolicyNever, true,
+ kCrossOriginAttributeNotSet, network::mojom::ReferrerPolicy::kNever, true,
network::mojom::FetchCredentialsMode::kSameOrigin},
{"http://example.test/cat.js", nullptr, "sha384-abc",
- kCrossOriginAttributeNotSet, kReferrerPolicyDefault, true,
- network::mojom::FetchCredentialsMode::kSameOrigin}};
+ kCrossOriginAttributeNotSet, network::mojom::ReferrerPolicy::kDefault,
+ true, network::mojom::FetchCredentialsMode::kSameOrigin}};
class LinkLoaderModulePreloadTest
: public testing::TestWithParam<ModulePreloadTestParams> {};
@@ -507,7 +512,7 @@ TEST_P(LinkLoaderModulePreloadTest, ModulePreload) {
LinkRelAttribute("modulepreload"), test_case.cross_origin,
String() /* type */, String() /* as */, String() /* media */,
test_case.nonce, test_case.integrity, String(), test_case.referrer_policy,
- href_url, String() /* srcset */, String() /* sizes */);
+ href_url, String() /* image_srcset */, String() /* image_sizes */);
loader->LoadLink(params, dummy_page_holder->GetDocument(),
NetworkHintsMock());
ASSERT_EQ(test_case.expecting_load, modulator->fetched());
@@ -523,19 +528,21 @@ TEST(LinkLoaderTest, Prefetch) {
// TODO(yoav): Add support for type and media crbug.com/662687
const char* type;
const char* media;
- const ReferrerPolicy referrer_policy;
+ const network::mojom::ReferrerPolicy referrer_policy;
const bool link_loader_should_load_value;
const bool expecting_load;
- const ReferrerPolicy expected_referrer_policy;
+ const network::mojom::ReferrerPolicy expected_referrer_policy;
} cases[] = {
// Referrer Policy
- {"http://example.test/cat.jpg", "image/jpg", "", kReferrerPolicyOrigin,
- true, true, kReferrerPolicyOrigin},
{"http://example.test/cat.jpg", "image/jpg", "",
- kReferrerPolicyOriginWhenCrossOrigin, true, true,
- kReferrerPolicyOriginWhenCrossOrigin},
- {"http://example.test/cat.jpg", "image/jpg", "", kReferrerPolicyNever,
- true, true, kReferrerPolicyNever},
+ network::mojom::ReferrerPolicy::kOrigin, true, true,
+ network::mojom::ReferrerPolicy::kOrigin},
+ {"http://example.test/cat.jpg", "image/jpg", "",
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, true, true,
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin},
+ {"http://example.test/cat.jpg", "image/jpg", "",
+ network::mojom::ReferrerPolicy::kNever, true, true,
+ network::mojom::ReferrerPolicy::kNever},
};
// Test the cases with a single header
@@ -547,12 +554,12 @@ TEST(LinkLoaderTest, Prefetch) {
MockLinkLoaderClient::Create(test_case.link_loader_should_load_value);
LinkLoader* loader = LinkLoader::Create(loader_client.Get());
KURL href_url = KURL(NullURL(), test_case.href);
- URLTestHelpers::RegisterMockedErrorURLLoad(href_url);
- LinkLoadParameters params(LinkRelAttribute("prefetch"),
- kCrossOriginAttributeNotSet, test_case.type, "",
- test_case.media, "", "", String(),
- test_case.referrer_policy, href_url,
- String() /* srcset */, String() /* sizes */);
+ url_test_helpers::RegisterMockedErrorURLLoad(href_url);
+ LinkLoadParameters params(
+ LinkRelAttribute("prefetch"), kCrossOriginAttributeNotSet,
+ test_case.type, "", test_case.media, "", "", String(),
+ test_case.referrer_policy, href_url, String() /* image_srcset */,
+ String() /* image_sizes */);
loader->LoadLink(params, dummy_page_holder->GetDocument(),
NetworkHintsMock());
ASSERT_TRUE(dummy_page_holder->GetDocument().Fetcher());
@@ -563,7 +570,8 @@ TEST(LinkLoaderTest, Prefetch) {
EXPECT_FALSE(resource);
}
if (resource) {
- if (test_case.expected_referrer_policy != kReferrerPolicyDefault) {
+ if (test_case.expected_referrer_policy !=
+ network::mojom::ReferrerPolicy::kDefault) {
EXPECT_EQ(test_case.expected_referrer_policy,
resource->GetResourceRequest().GetReferrerPolicy());
}
@@ -596,11 +604,11 @@ TEST(LinkLoaderTest, DNSPrefetch) {
LinkLoader* loader = LinkLoader::Create(loader_client.Get());
KURL href_url = KURL(KURL(String("http://example.com")), test_case.href);
NetworkHintsMock network_hints;
- LinkLoadParameters params(LinkRelAttribute("dns-prefetch"),
- kCrossOriginAttributeNotSet, String(), String(),
- String(), String(), String(), String(),
- kReferrerPolicyDefault, href_url,
- String() /* srcset */, String() /* sizes */);
+ LinkLoadParameters params(
+ LinkRelAttribute("dns-prefetch"), kCrossOriginAttributeNotSet, String(),
+ String(), String(), String(), String(), String(),
+ network::mojom::ReferrerPolicy::kDefault, href_url,
+ String() /* image_srcset */, String() /* image_sizes */);
loader->LoadLink(params, dummy_page_holder->GetDocument(), network_hints);
EXPECT_FALSE(network_hints.DidPreconnect());
EXPECT_EQ(test_case.should_load, network_hints.DidDnsPrefetch());
@@ -632,11 +640,11 @@ TEST(LinkLoaderTest, Preconnect) {
LinkLoader* loader = LinkLoader::Create(loader_client.Get());
KURL href_url = KURL(KURL(String("http://example.com")), test_case.href);
NetworkHintsMock network_hints;
- LinkLoadParameters params(LinkRelAttribute("preconnect"),
- test_case.cross_origin, String(), String(),
- String(), String(), String(), String(),
- kReferrerPolicyDefault, href_url,
- String() /* srcset */, String() /* sizes */);
+ LinkLoadParameters params(
+ LinkRelAttribute("preconnect"), test_case.cross_origin, String(),
+ String(), String(), String(), String(), String(),
+ network::mojom::ReferrerPolicy::kDefault, href_url,
+ String() /* image_srcset */, String() /* image_sizes */);
loader->LoadLink(params, dummy_page_holder->GetDocument(), network_hints);
EXPECT_EQ(test_case.should_load, network_hints.DidPreconnect());
EXPECT_EQ(test_case.is_https, network_hints.IsHTTPS());
@@ -654,12 +662,12 @@ TEST(LinkLoaderTest, PreloadAndPrefetch) {
MockLinkLoaderClient::Create(true);
LinkLoader* loader = LinkLoader::Create(loader_client.Get());
KURL href_url = KURL(KURL(), "https://www.example.com/");
- URLTestHelpers::RegisterMockedErrorURLLoad(href_url);
- LinkLoadParameters params(LinkRelAttribute("preload prefetch"),
- kCrossOriginAttributeNotSet,
- "application/javascript", "script", "", "", "",
- String(), kReferrerPolicyDefault, href_url,
- String() /* srcset */, String() /* sizes */);
+ url_test_helpers::RegisterMockedErrorURLLoad(href_url);
+ LinkLoadParameters params(
+ LinkRelAttribute("preload prefetch"), kCrossOriginAttributeNotSet,
+ "application/javascript", "script", "", "", "", String(),
+ network::mojom::ReferrerPolicy::kDefault, href_url,
+ String() /* image_srcset */, String() /* image_sizes */);
loader->LoadLink(params, dummy_page_holder->GetDocument(),
NetworkHintsMock());
ASSERT_EQ(1, fetcher->CountPreloads());
diff --git a/chromium/third_party/blink/renderer/core/loader/long_task_detector.cc b/chromium/third_party/blink/renderer/core/loader/long_task_detector.cc
index f3aeca2a9e5..dc9f2876445 100644
--- a/chromium/third_party/blink/renderer/core/loader/long_task_detector.cc
+++ b/chromium/third_party/blink/renderer/core/loader/long_task_detector.cc
@@ -26,7 +26,7 @@ void LongTaskDetector::RegisterObserver(LongTaskObserver* observer) {
DCHECK(observer);
if (observers_.insert(observer).is_new_entry && observers_.size() == 1) {
// Number of observers just became non-zero.
- Platform::Current()->CurrentThread()->AddTaskTimeObserver(this);
+ Thread::Current()->AddTaskTimeObserver(this);
}
}
@@ -34,7 +34,7 @@ void LongTaskDetector::UnregisterObserver(LongTaskObserver* observer) {
DCHECK(IsMainThread());
observers_.erase(observer);
if (observers_.size() == 0) {
- Platform::Current()->CurrentThread()->RemoveTaskTimeObserver(this);
+ Thread::Current()->RemoveTaskTimeObserver(this);
}
}
diff --git a/chromium/third_party/blink/renderer/core/loader/long_task_detector_test.cc b/chromium/third_party/blink/renderer/core/loader/long_task_detector_test.cc
index 4e95f720841..453bf7c96f2 100644
--- a/chromium/third_party/blink/renderer/core/loader/long_task_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/long_task_detector_test.cc
@@ -6,8 +6,8 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -54,7 +54,7 @@ class LongTaskDetectorTest : public testing::Test {
void SimulateTask(base::TimeDelta duration) {
PostCrossThreadTask(
- *platform_->CurrentThread()->GetTaskRunner(), FROM_HERE,
+ *Thread::Current()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(&LongTaskDetectorTest::DummyTaskWithDuration,
CrossThreadUnretained(this), duration));
platform_->RunUntilIdle();
diff --git a/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.cc b/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.cc
index 4355ac7084b..1c148e0da03 100644
--- a/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.cc
+++ b/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.cc
@@ -33,12 +33,12 @@
#include "services/network/public/mojom/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "third_party/blink/public/platform/web_mixed_content.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/frame.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
@@ -148,15 +148,12 @@ const char* RequestContextName(mojom::RequestContextType context) {
return "resource";
}
-// TODO(nhiroki): Consider adding interfaces for Settings/WorkerSettings and
-// ContentSettingsClient/WorkerContentSettingsClient to avoid using C++
-// template.
-template <typename SettingsType, typename SettingsClientType>
+// TODO(nhiroki): Consider adding interfaces for Settings/WorkerSettings
+// to avoid using C++ template.
+template <typename SettingsType>
bool IsWebSocketAllowedImpl(const BaseFetchContext& fetch_context,
SecurityContext* security_context,
- const SecurityOrigin* security_origin,
SettingsType* settings,
- SettingsClientType* settings_client,
const KURL& url) {
fetch_context.CountUsage(WebFeature::kMixedContentPresent);
fetch_context.CountUsage(WebFeature::kMixedContentWebSocket);
@@ -174,10 +171,7 @@ bool IsWebSocketAllowedImpl(const BaseFetchContext& fetch_context,
settings->GetStrictMixedContentChecking();
if (strict_mode)
return false;
- bool allowed_per_settings =
- settings && settings->GetAllowRunningOfInsecureContent();
- return settings_client->AllowRunningInsecureContent(allowed_per_settings,
- security_origin, url);
+ return settings && settings->GetAllowRunningOfInsecureContent();
}
} // namespace
@@ -237,7 +231,7 @@ bool MixedContentChecker::IsMixedContent(const SecurityOrigin* security_origin,
// static
bool MixedContentChecker::IsMixedContent(
- const FetchClientSettingsObjectImpl& settings,
+ const FetchClientSettingsObject& settings,
const KURL& url) {
switch (settings.GetHttpsState()) {
case HttpsState::kNone:
@@ -378,7 +372,7 @@ bool MixedContentChecker::ShouldBlockFetch(
// Use the current local frame's client; the embedder doesn't distinguish
// mixed content signals from different frames on the same page.
LocalFrameClient* client = frame->Client();
- ContentSettingsClient* content_settings_client =
+ WebContentSettingsClient* content_settings_client =
frame->GetContentSettingsClient();
const SecurityOrigin* security_origin =
mixed_frame->GetSecurityContext()->GetSecurityOrigin();
@@ -405,14 +399,15 @@ bool MixedContentChecker::ShouldBlockFetch(
// launching external applications via URLs. http://crbug.com/318788 and
// https://crbug.com/393481
if (frame_type == network::mojom::RequestContextFrameType::kNested &&
- !SchemeRegistry::ShouldTreatURLSchemeAsCORSEnabled(url.Protocol()))
+ !SchemeRegistry::ShouldTreatURLSchemeAsCorsEnabled(url.Protocol()))
context_type = WebMixedContentContextType::kOptionallyBlockable;
switch (context_type) {
case WebMixedContentContextType::kOptionallyBlockable:
allowed = !strict_mode;
if (allowed) {
- content_settings_client->PassiveInsecureContentFound(url);
+ if (content_settings_client)
+ content_settings_client->PassiveInsecureContentFound(url);
client->DidDisplayInsecureContent();
}
break;
@@ -439,10 +434,13 @@ bool MixedContentChecker::ShouldBlockFetch(
!strict_mode && settings &&
(!settings->GetStrictlyBlockBlockableMixedContent() ||
settings->GetAllowRunningOfInsecureContent());
- allowed = should_ask_embedder &&
- content_settings_client->AllowRunningInsecureContent(
- settings && settings->GetAllowRunningOfInsecureContent(),
- security_origin, url);
+ if (should_ask_embedder) {
+ allowed = settings && settings->GetAllowRunningOfInsecureContent();
+ if (content_settings_client) {
+ allowed = content_settings_client->AllowRunningInsecureContent(
+ allowed, WebSecurityOrigin(security_origin), url);
+ }
+ }
if (allowed) {
client->DidRunInsecureContent(security_origin, url);
UseCounter::Count(frame, WebFeature::kMixedContentBlockableAllowed);
@@ -561,14 +559,18 @@ bool MixedContentChecker::IsWebSocketAllowed(
Settings* settings = mixed_frame->GetSettings();
// Use the current local frame's client; the embedder doesn't distinguish
// mixed content signals from different frames on the same page.
- ContentSettingsClient* content_settings_client =
+ WebContentSettingsClient* content_settings_client =
frame->GetContentSettingsClient();
SecurityContext* security_context = mixed_frame->GetSecurityContext();
const SecurityOrigin* security_origin = security_context->GetSecurityOrigin();
bool allowed = IsWebSocketAllowedImpl(frame_fetch_context, security_context,
- security_origin, settings,
- content_settings_client, url);
+ settings, url);
+ if (content_settings_client) {
+ allowed = content_settings_client->AllowRunningInsecureContent(
+ allowed, WebSecurityOrigin(security_origin), url);
+ }
+
if (allowed)
frame->Client()->DidRunInsecureContent(security_origin, url);
@@ -596,8 +598,12 @@ bool MixedContentChecker::IsWebSocketAllowed(
worker_fetch_context.GetSecurityOrigin();
bool allowed = IsWebSocketAllowedImpl(worker_fetch_context, security_context,
- security_origin, settings,
- content_settings_client, url);
+ settings, url);
+ if (content_settings_client) {
+ allowed = content_settings_client->AllowRunningInsecureContent(
+ allowed, security_origin, url);
+ }
+
if (allowed) {
worker_fetch_context.GetWebWorkerFetchContext()->DidRunInsecureContent(
WebSecurityOrigin(security_origin), url);
@@ -679,7 +685,7 @@ void MixedContentChecker::CheckMixedPrivatePublic(
return;
// Just count these for the moment, don't block them.
- if (NetworkUtils::IsReservedIPAddress(resource_ip_address) &&
+ if (network_utils::IsReservedIPAddress(resource_ip_address) &&
frame->GetDocument()->AddressSpace() == mojom::IPAddressSpace::kPublic) {
UseCounter::Count(frame->GetDocument(),
WebFeature::kMixedContentPrivateHostnameInPublicHostname);
@@ -762,6 +768,40 @@ void MixedContentChecker::MixedContentFound(
}
}
+// static
+ConsoleMessage* MixedContentChecker::CreateConsoleMessageAboutFetchAutoupgrade(
+ const KURL& main_resource_url,
+ const KURL& mixed_content_url) {
+ String message = String::Format(
+ "Mixed Content: The page at '%s' was loaded over HTTPS, but requested an "
+ "insecure element '%s'. As part of an experiment this request was "
+ "automatically upgraded to HTTPS, For more information see "
+ "https://chromium.googlesource.com/chromium/src/+/master/docs/security/"
+ "autougprade-mixed.md",
+ main_resource_url.ElidedString().Utf8().data(),
+ mixed_content_url.ElidedString().Utf8().data());
+ return ConsoleMessage::Create(kSecurityMessageSource, kWarningMessageLevel,
+ message);
+}
+
+// static
+ConsoleMessage*
+MixedContentChecker::CreateConsoleMessageAboutWebSocketAutoupgrade(
+ const KURL& main_resource_url,
+ const KURL& mixed_content_url) {
+ String message = String::Format(
+ "Mixed Content: The page at '%s' was loaded over HTTPS, but attempted "
+ "to connect to the insecure WebSocket endpoint '%s'. As part of an "
+ "experiment this request was automatically upgraded to HTTPS, For more "
+ "information see "
+ "https://chromium.googlesource.com/chromium/src/+/master/docs/security/"
+ "autougprade-mixed.md",
+ main_resource_url.ElidedString().Utf8().data(),
+ mixed_content_url.ElidedString().Utf8().data());
+ return ConsoleMessage::Create(kSecurityMessageSource, kWarningMessageLevel,
+ message);
+}
+
WebMixedContentContextType MixedContentChecker::ContextTypeForInspector(
LocalFrame* frame,
const ResourceRequest& request) {
@@ -777,7 +817,7 @@ WebMixedContentContextType MixedContentChecker::ContextTypeForInspector(
// subframe.
if (request.GetFrameType() ==
network::mojom::RequestContextFrameType::kNested &&
- !SchemeRegistry::ShouldTreatURLSchemeAsCORSEnabled(
+ !SchemeRegistry::ShouldTreatURLSchemeAsCorsEnabled(
request.Url().Protocol())) {
return WebMixedContentContextType::kOptionallyBlockable;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.h b/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.h
index 49fafcd1a7e..bede62aa0b0 100644
--- a/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.h
+++ b/chromium/third_party/blink/renderer/core/loader/mixed_content_checker.h
@@ -44,7 +44,7 @@
namespace blink {
class ConsoleMessage;
-class FetchClientSettingsObjectImpl;
+class FetchClientSettingsObject;
class Frame;
class FrameFetchContext;
class LocalFrame;
@@ -87,7 +87,7 @@ class CORE_EXPORT MixedContentChecker final {
static bool IsWebSocketAllowed(const WorkerFetchContext&, const KURL&);
static bool IsMixedContent(const SecurityOrigin*, const KURL&);
- static bool IsMixedContent(const FetchClientSettingsObjectImpl&, const KURL&);
+ static bool IsMixedContent(const FetchClientSettingsObject&, const KURL&);
static bool IsMixedFormAction(LocalFrame*,
const KURL&,
SecurityViolationReportingPolicy =
@@ -123,6 +123,14 @@ class CORE_EXPORT MixedContentChecker final {
bool had_redirect,
std::unique_ptr<SourceLocation>);
+ static ConsoleMessage* CreateConsoleMessageAboutFetchAutoupgrade(
+ const KURL& main_resource_url,
+ const KURL& mixed_content_url);
+
+ static ConsoleMessage* CreateConsoleMessageAboutWebSocketAutoupgrade(
+ const KURL& main_resource_url,
+ const KURL& mixed_content_url);
+
private:
FRIEND_TEST_ALL_PREFIXES(MixedContentCheckerTest, HandleCertificateError);
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.cc
index da5a8736d80..9b0da3f68a8 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.cc
@@ -27,7 +27,8 @@ void DocumentModuleScriptFetcher::Fetch(FetchParameters& fetch_params,
if (FetchIfLayeredAPI(fetch_params))
return;
- ScriptResource::Fetch(fetch_params, fetcher_, this);
+ ScriptResource::Fetch(fetch_params, fetcher_, this,
+ ScriptResource::kNoStreaming);
}
void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) {
@@ -43,8 +44,7 @@ void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) {
ModuleScriptCreationParams params(
script_resource->GetResponse().Url(), script_resource->SourceText(),
- script_resource->GetResourceRequest().GetFetchCredentialsMode(),
- script_resource->CalculateAccessControlStatus());
+ script_resource->GetResourceRequest().GetFetchCredentialsMode());
client_->NotifyFetchFinished(params, error_messages);
}
@@ -77,8 +77,7 @@ bool DocumentModuleScriptFetcher::FetchIfLayeredAPI(
ModuleScriptCreationParams params(
layered_api_url, ParkableString(source_text.ReleaseImpl()),
- fetch_params.GetResourceRequest().GetFetchCredentialsMode(),
- kSharableCrossOrigin);
+ fetch_params.GetResourceRequest().GetFetchCredentialsMode());
client_->NotifyFetchFinished(params, HeapVector<Member<ConsoleMessage>>());
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.cc
new file mode 100644
index 00000000000..a69982edbca
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.cc
@@ -0,0 +1,52 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.h"
+
+#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/workers/installed_scripts_manager.h"
+#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+
+InstalledServiceWorkerModuleScriptFetcher::
+ InstalledServiceWorkerModuleScriptFetcher(WorkerGlobalScope* global_scope)
+ : global_scope_(global_scope) {}
+
+void InstalledServiceWorkerModuleScriptFetcher::Fetch(
+ FetchParameters& fetch_params,
+ ModuleGraphLevel level,
+ ModuleScriptFetcher::Client* client) {
+ DCHECK(global_scope_->IsContextThread());
+ InstalledScriptsManager* installed_scripts_manager =
+ global_scope_->GetThread()->GetInstalledScriptsManager();
+ DCHECK(installed_scripts_manager);
+ DCHECK(installed_scripts_manager->IsScriptInstalled(fetch_params.Url()));
+
+ std::unique_ptr<InstalledScriptsManager::ScriptData> script =
+ installed_scripts_manager->GetScriptData(fetch_params.Url());
+
+ if (!script) {
+ HeapVector<Member<ConsoleMessage>> error_messages;
+ error_messages.push_back(ConsoleMessage::CreateForRequest(
+ kJSMessageSource, kErrorMessageLevel,
+ "Failed to load the script unexpectedly",
+ fetch_params.Url().GetString(), nullptr, 0));
+ client->NotifyFetchFinished(base::nullopt, error_messages);
+ return;
+ }
+
+ ModuleScriptCreationParams params(
+ fetch_params.Url(), ParkableString(script->TakeSourceText().Impl()),
+ fetch_params.GetResourceRequest().GetFetchCredentialsMode());
+ client->NotifyFetchFinished(params, HeapVector<Member<ConsoleMessage>>());
+}
+
+void InstalledServiceWorkerModuleScriptFetcher::Trace(blink::Visitor* visitor) {
+ ModuleScriptFetcher::Trace(visitor);
+ visitor->Trace(global_scope_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.h b/chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.h
new file mode 100644
index 00000000000..5788aaec6a1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.h
@@ -0,0 +1,43 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_INSTALLED_SERVICE_WORKER_MODULE_SCRIPT_FETCHER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_INSTALLED_SERVICE_WORKER_MODULE_SCRIPT_FETCHER_H_
+
+#include "third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.h"
+
+namespace blink {
+
+class WorkerGlobalScope;
+
+// InstalledServiceWorkerModuleScriptFetcher is an implementation of
+// ModuleScriptFetcher for retrieving an installed ServiceWorker script
+// from ServiceWorker's script storage.
+class CORE_EXPORT InstalledServiceWorkerModuleScriptFetcher final
+ : public GarbageCollectedFinalized<
+ InstalledServiceWorkerModuleScriptFetcher>,
+ public ModuleScriptFetcher {
+ USING_GARBAGE_COLLECTED_MIXIN(InstalledServiceWorkerModuleScriptFetcher);
+
+ public:
+ explicit InstalledServiceWorkerModuleScriptFetcher(WorkerGlobalScope*);
+
+ // Implements ModuleScriptFetcher.
+ void Fetch(FetchParameters&,
+ ModuleGraphLevel,
+ ModuleScriptFetcher::Client*) override;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ String DebugName() const override {
+ return "InstalledServiceWorkerModuleScriptFetcher";
+ }
+
+ const Member<WorkerGlobalScope> global_scope_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_WORKER_MODULE_SCRIPT_FETCHER_H_
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h
index a161709660c..bd4849de8d4 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h
@@ -9,7 +9,6 @@
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
#include "third_party/blink/renderer/platform/cross_thread_copier.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -21,22 +20,22 @@ class ModuleScriptCreationParams {
ModuleScriptCreationParams(
const KURL& response_url,
const ParkableString& source_text,
- network::mojom::FetchCredentialsMode fetch_credentials_mode,
- AccessControlStatus access_control_status)
+ network::mojom::FetchCredentialsMode fetch_credentials_mode)
: response_url_(response_url),
is_isolated_(false),
source_text_(source_text),
isolated_source_text_(),
- fetch_credentials_mode_(fetch_credentials_mode),
- access_control_status_(access_control_status) {}
+ fetch_credentials_mode_(fetch_credentials_mode) {}
~ModuleScriptCreationParams() = default;
ModuleScriptCreationParams IsolatedCopy() const {
- String isolated_source_text = GetSourceText().ToString().IsolatedCopy();
- return ModuleScriptCreationParams(
- GetResponseUrl().Copy(), isolated_source_text,
- GetFetchCredentialsMode(), GetAccessControlStatus());
+ String isolated_source_text =
+ isolated_source_text_ ? isolated_source_text_.IsolatedCopy()
+ : GetSourceText().ToString().IsolatedCopy();
+ return ModuleScriptCreationParams(GetResponseUrl().Copy(),
+ isolated_source_text,
+ GetFetchCredentialsMode());
}
const KURL& GetResponseUrl() const { return response_url_; }
@@ -51,9 +50,6 @@ class ModuleScriptCreationParams {
network::mojom::FetchCredentialsMode GetFetchCredentialsMode() const {
return fetch_credentials_mode_;
}
- AccessControlStatus GetAccessControlStatus() const {
- return access_control_status_;
- }
bool IsSafeToSendToAnotherThread() const {
return response_url_.IsSafeToSendToAnotherThread() && is_isolated_;
@@ -64,14 +60,12 @@ class ModuleScriptCreationParams {
ModuleScriptCreationParams(
const KURL& response_url,
const String& isolated_source_text,
- network::mojom::FetchCredentialsMode fetch_credentials_mode,
- AccessControlStatus access_control_status)
+ network::mojom::FetchCredentialsMode fetch_credentials_mode)
: response_url_(response_url),
is_isolated_(true),
source_text_(),
isolated_source_text_(isolated_source_text),
- fetch_credentials_mode_(fetch_credentials_mode),
- access_control_status_(access_control_status) {}
+ fetch_credentials_mode_(fetch_credentials_mode) {}
const KURL response_url_;
@@ -82,7 +76,6 @@ class ModuleScriptCreationParams {
mutable String isolated_source_text_;
const network::mojom::FetchCredentialsMode fetch_credentials_mode_;
- const AccessControlStatus access_control_status_;
};
// Creates a deep copy because |response_url_| and |source_text_| are not
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.cc
index 10634797e8d..dce66bc435f 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.cc
@@ -43,7 +43,7 @@ bool ModuleScriptFetcher::WasModuleLoadSuccessful(
const auto& response = resource->GetResponse();
// - response's status is not an ok status
- if (response.IsHTTP() && !CORS::IsOkStatus(response.HttpStatusCode())) {
+ if (response.IsHTTP() && !cors::IsOkStatus(response.HttpStatusCode())) {
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc
index 6c178a2750f..ef74f6b2702 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc
@@ -84,7 +84,7 @@ void ModuleScriptLoader::Fetch(
ModuleScriptCustomFetchType custom_fetch_type,
ModuleScriptLoaderRegistry* registry,
ModuleScriptLoaderClient* client) {
- ModuleScriptLoader* loader = new ModuleScriptLoader(
+ ModuleScriptLoader* loader = MakeGarbageCollected<ModuleScriptLoader>(
module_map_settings_object, module_request.Options(), registry, client);
registry->AddLoader(loader);
loader->FetchInternal(module_request, fetch_client_settings_object, level,
@@ -154,8 +154,9 @@ void ModuleScriptLoader::FetchInternal(
// [SMSR] "... its referrer policy to options's referrer policy." [spec text]
// Note: For now this is done below with SetHTTPReferrer()
- ReferrerPolicy referrer_policy = module_request.Options().GetReferrerPolicy();
- if (referrer_policy == kReferrerPolicyDefault)
+ network::mojom::ReferrerPolicy referrer_policy =
+ module_request.Options().GetReferrerPolicy();
+ if (referrer_policy == network::mojom::ReferrerPolicy::kDefault)
referrer_policy = fetch_client_settings_object->GetReferrerPolicy();
// Step 5. "... mode is "cors", ..."
@@ -239,9 +240,9 @@ void ModuleScriptLoader::NotifyFetchFinished(
// Step 10. "Let module script be the result of creating a module script given
// source text, module map settings object, response's url, and options."
// [spec text]
- module_script_ = ModuleScript::Create(
- params->GetSourceText(), modulator_, params->GetResponseUrl(),
- params->GetResponseUrl(), options_, params->GetAccessControlStatus());
+ module_script_ = ModuleScript::Create(params->GetSourceText(), modulator_,
+ params->GetResponseUrl(),
+ params->GetResponseUrl(), options_);
AdvanceState(State::kFinished);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.h b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.h
index c2e1d338a20..14c9d7ffb91 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.h
@@ -45,6 +45,10 @@ class CORE_EXPORT ModuleScriptLoader final
};
public:
+ ModuleScriptLoader(Modulator*,
+ const ScriptFetchOptions&,
+ ModuleScriptLoaderRegistry*,
+ ModuleScriptLoaderClient*);
~ModuleScriptLoader();
static void Fetch(
@@ -67,11 +71,6 @@ class CORE_EXPORT ModuleScriptLoader final
void Trace(blink::Visitor*) override;
private:
- ModuleScriptLoader(Modulator*,
- const ScriptFetchOptions&,
- ModuleScriptLoaderRegistry*,
- ModuleScriptLoaderClient*);
-
void FetchInternal(
const ModuleScriptFetchRequest&,
FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h
index 8ca0faea242..a2d9012c217 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_registry.h
@@ -18,13 +18,14 @@ class CORE_EXPORT ModuleScriptLoaderRegistry final
: public GarbageCollected<ModuleScriptLoaderRegistry> {
public:
static ModuleScriptLoaderRegistry* Create() {
- return new ModuleScriptLoaderRegistry;
+ return MakeGarbageCollected<ModuleScriptLoaderRegistry>();
}
- void Trace(blink::Visitor*);
- private:
ModuleScriptLoaderRegistry() = default;
+ void Trace(blink::Visitor*);
+
+ private:
friend class ModuleScriptLoader;
void AddLoader(ModuleScriptLoader*);
void ReleaseFinishedLoader(ModuleScriptLoader*);
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_test.cc
index d2c856fc69a..5f169e71011 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_test.cc
@@ -97,15 +97,14 @@ class ModuleScriptLoaderTestModulator final : public DummyModulator {
ModuleScriptFetcher* CreateModuleScriptFetcher(
ModuleScriptCustomFetchType custom_fetch_type) override {
auto* execution_context = ExecutionContext::From(script_state_);
- if (execution_context->IsWorkletGlobalScope()) {
+ if (auto* scope = DynamicTo<WorkletGlobalScope>(execution_context)) {
EXPECT_EQ(ModuleScriptCustomFetchType::kWorkletAddModule,
custom_fetch_type);
- auto* global_scope = ToWorkletGlobalScope(execution_context);
- return new WorkletModuleScriptFetcher(
- Fetcher(), global_scope->GetModuleResponsesMap());
+ return MakeGarbageCollected<WorkletModuleScriptFetcher>(
+ Fetcher(), scope->GetModuleResponsesMap());
}
EXPECT_EQ(ModuleScriptCustomFetchType::kNone, custom_fetch_type);
- return new DocumentModuleScriptFetcher(Fetcher());
+ return MakeGarbageCollected<DocumentModuleScriptFetcher>(Fetcher());
}
ResourceFetcher* Fetcher() const { return fetcher_.Get(); }
@@ -183,7 +182,8 @@ void ModuleScriptLoaderTest::InitializeForWorklet() {
reporting_proxy_ =
std::make_unique<MainThreadWorkletReportingProxy>(&GetDocument());
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- GetDocument().Url(), ScriptType::kModule, GetDocument().UserAgent(),
+ GetDocument().Url(), mojom::ScriptType::kModule,
+ GetDocument().UserAgent(), nullptr /* web_worker_fetch_context */,
Vector<CSPHeaderAndType>(), GetDocument().GetReferrerPolicy(),
GetDocument().GetSecurityOrigin(), GetDocument().IsSecureContext(),
GetDocument().GetHttpsState(), nullptr /* worker_clients */,
@@ -191,8 +191,8 @@ void ModuleScriptLoaderTest::InitializeForWorklet() {
OriginTrialContext::GetTokens(&GetDocument()).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap);
- global_scope_ = new WorkletGlobalScope(std::move(creation_params),
- *reporting_proxy_, &GetFrame());
+ global_scope_ = MakeGarbageCollected<WorkletGlobalScope>(
+ std::move(creation_params), *reporting_proxy_, &GetFrame());
global_scope_->ScriptController()->InitializeContextIfNeeded("Dummy Context",
NullURL());
modulator_ = new ModuleScriptLoaderTestModulator(
@@ -218,8 +218,10 @@ TEST_F(ModuleScriptLoaderTest, FetchDataURL) {
TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient;
TestFetchDataURL(ModuleScriptCustomFetchType::kNone, client);
- EXPECT_TRUE(client->WasNotifyFinished())
- << "ModuleScriptLoader should finish synchronously.";
+ // TODO(leszeks): This should finish synchronously, but currently due
+ // to the script resource/script streamer interaction, it does not.
+ RunUntilIdle();
+ EXPECT_TRUE(client->WasNotifyFinished());
ASSERT_TRUE(client->GetModuleScript());
EXPECT_FALSE(client->GetModuleScript()->HasEmptyRecord());
EXPECT_FALSE(client->GetModuleScript()->HasParseError());
@@ -273,8 +275,11 @@ TEST_F(ModuleScriptLoaderTest, InvalidSpecifier) {
TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient;
TestInvalidSpecifier(ModuleScriptCustomFetchType::kNone, client);
- EXPECT_TRUE(client->WasNotifyFinished())
- << "ModuleScriptLoader should finish synchronously.";
+ // TODO(leszeks): This should finish synchronously, but currently due
+ // to the script resource/script streamer interaction, it does not.
+ RunUntilIdle();
+ EXPECT_TRUE(client->WasNotifyFinished());
+
ASSERT_TRUE(client->GetModuleScript());
EXPECT_TRUE(client->GetModuleScript()->HasEmptyRecord());
EXPECT_TRUE(client->GetModuleScript()->HasParseError());
@@ -314,8 +319,10 @@ TEST_F(ModuleScriptLoaderTest, FetchInvalidURL) {
TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient;
TestFetchInvalidURL(ModuleScriptCustomFetchType::kNone, client);
- EXPECT_TRUE(client->WasNotifyFinished())
- << "ModuleScriptLoader should finish synchronously.";
+ // TODO(leszeks): This should finish synchronously, but currently due
+ // to the script resource/script streamer interaction, it does not.
+ RunUntilIdle();
+ EXPECT_TRUE(client->WasNotifyFinished());
EXPECT_FALSE(client->GetModuleScript());
}
@@ -336,7 +343,7 @@ void ModuleScriptLoaderTest::TestFetchURL(
ModuleScriptCustomFetchType custom_fetch_type,
TestModuleScriptLoaderClient* client) {
KURL url("https://example.test/module.js");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
url, test::CoreTestDataPath("module.js"), "text/javascript");
auto* fetch_client_settings_object =
GetDocument().CreateFetchClientSettingsObjectSnapshot();
@@ -356,6 +363,9 @@ TEST_F(ModuleScriptLoaderTest, FetchURL) {
EXPECT_FALSE(client->WasNotifyFinished())
<< "ModuleScriptLoader unexpectedly finished synchronously.";
platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests();
+ // TODO(leszeks): This should finish synchronously, but currently due
+ // to the script resource/script streamer interaction, it does not.
+ RunUntilIdle();
EXPECT_TRUE(client->WasNotifyFinished());
EXPECT_TRUE(client->GetModuleScript());
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.cc
index fee91a7c5fd..088b7b3b27d 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.cc
@@ -27,9 +27,9 @@ void ModuleTreeLinker::Fetch(
ModuleScriptCustomFetchType custom_fetch_type,
ModuleTreeLinkerRegistry* registry,
ModuleTreeClient* client) {
- ModuleTreeLinker* fetcher =
- new ModuleTreeLinker(fetch_client_settings_object, destination, modulator,
- custom_fetch_type, registry, client);
+ ModuleTreeLinker* fetcher = MakeGarbageCollected<ModuleTreeLinker>(
+ fetch_client_settings_object, destination, modulator, custom_fetch_type,
+ registry, client);
registry->AddFetcher(fetcher);
fetcher->FetchRoot(url, options);
DCHECK(fetcher->IsFetching());
@@ -44,9 +44,9 @@ void ModuleTreeLinker::FetchDescendantsForInlineScript(
ModuleTreeLinkerRegistry* registry,
ModuleTreeClient* client) {
DCHECK(module_script);
- ModuleTreeLinker* fetcher =
- new ModuleTreeLinker(fetch_client_settings_object, destination, modulator,
- custom_fetch_type, registry, client);
+ ModuleTreeLinker* fetcher = MakeGarbageCollected<ModuleTreeLinker>(
+ fetch_client_settings_object, destination, modulator, custom_fetch_type,
+ registry, client);
registry->AddFetcher(fetcher);
fetcher->FetchRootInline(module_script);
DCHECK(fetcher->IsFetching());
@@ -377,7 +377,7 @@ void ModuleTreeLinker::FetchDescendants(ModuleScript* module_script) {
//
// [FD] Step 7. These invocations of the internal module script graph fetching
// procedure should be performed in parallel to each other.
- for (size_t i = 0; i < urls.size(); ++i) {
+ for (wtf_size_t i = 0; i < urls.size(); ++i) {
// [FD] Step 7. ... perform the internal module script graph fetching
// procedure given url, fetch client settings object, destination, options,
// module script's settings object, visited set, module script's base URL,
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h
index e4dd03903b3..b4ed117ef38 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h
@@ -57,6 +57,13 @@ class CORE_EXPORT ModuleTreeLinker final : public SingleModuleClient {
ModuleTreeLinkerRegistry*,
ModuleTreeClient*);
+ ModuleTreeLinker(
+ FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
+ mojom::RequestContextType destination,
+ Modulator*,
+ ModuleScriptCustomFetchType,
+ ModuleTreeLinkerRegistry*,
+ ModuleTreeClient*);
~ModuleTreeLinker() override = default;
void Trace(blink::Visitor*) override;
@@ -66,14 +73,6 @@ class CORE_EXPORT ModuleTreeLinker final : public SingleModuleClient {
bool HasFinished() const { return state_ == State::kFinished; }
private:
- ModuleTreeLinker(
- FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
- mojom::RequestContextType destination,
- Modulator*,
- ModuleScriptCustomFetchType,
- ModuleTreeLinkerRegistry*,
- ModuleTreeClient*);
-
enum class State {
kInitial,
// Running fetch of the module script corresponding to the target node.
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_registry.h b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_registry.h
index b5f0b31ab5a..2867d9ca9ce 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_registry.h
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_registry.h
@@ -20,16 +20,17 @@ class CORE_EXPORT ModuleTreeLinkerRegistry
public NameClient {
public:
static ModuleTreeLinkerRegistry* Create() {
- return new ModuleTreeLinkerRegistry;
+ return MakeGarbageCollected<ModuleTreeLinkerRegistry>();
}
+
+ ModuleTreeLinkerRegistry() = default;
+
void Trace(blink::Visitor*);
const char* NameInHeapSnapshot() const override {
return "ModuleTreeLinkerRegistry";
}
private:
- ModuleTreeLinkerRegistry() = default;
-
friend class ModuleTreeLinker;
void AddFetcher(ModuleTreeLinker*);
void ReleaseFinishedFetcher(ModuleTreeLinker*);
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_test.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_test.cc
index 5b7d03ae927..36a57045c58 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker_test.cc
@@ -85,8 +85,8 @@ class ModuleTreeLinkerTestModulator final : public DummyModulator {
ScriptModule script_module = ScriptModule::Compile(
script_state_->GetIsolate(), source_text.ToString(), url, url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
auto* module_script = ModuleScript::CreateForTest(this, script_module, url);
auto result_request = dependency_module_requests_map_.insert(
script_module, dependency_module_requests);
@@ -201,7 +201,8 @@ class ModuleTreeLinkerTest : public PageTestBase {
void ModuleTreeLinkerTest::SetUp() {
PageTestBase::SetUp(IntSize(500, 500));
ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
- modulator_ = new ModuleTreeLinkerTestModulator(script_state);
+ modulator_ =
+ MakeGarbageCollected<ModuleTreeLinkerTestModulator>(script_state);
}
TEST_F(ModuleTreeLinkerTest, FetchTreeNoDeps) {
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.cc
index 092915a99d8..3e702d88131 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.cc
@@ -4,11 +4,11 @@
#include "third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
namespace blink {
@@ -33,7 +33,8 @@ void WorkerModuleScriptFetcher::Fetch(FetchParameters& fetch_params,
// Step 13.2. "Fetch request, and asynchronously wait to run the remaining
// steps as part of fetch's process response for the response response." [spec
// text]
- ScriptResource::Fetch(fetch_params, global_scope_->EnsureFetcher(), this);
+ ScriptResource::Fetch(fetch_params, global_scope_->EnsureFetcher(), this,
+ ScriptResource::kNoStreaming);
}
void WorkerModuleScriptFetcher::Trace(blink::Visitor* visitor) {
@@ -82,9 +83,10 @@ void WorkerModuleScriptFetcher::NotifyFinished(Resource* resource) {
// Step 13.5. "Set worker global scope's referrer policy to the result of
// parsing the `Referrer-Policy` header of response." [spec text]
const String referrer_policy_header =
- resource->GetResponse().HttpHeaderField(HTTPNames::Referrer_Policy);
+ resource->GetResponse().HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
SecurityPolicy::ReferrerPolicyFromHeaderValue(
referrer_policy_header, kDoNotSupportReferrerPolicyLegacyKeywords,
&referrer_policy);
@@ -98,8 +100,7 @@ void WorkerModuleScriptFetcher::NotifyFinished(Resource* resource) {
ModuleScriptCreationParams params(
script_resource->GetResponse().Url(), script_resource->SourceText(),
- script_resource->GetResourceRequest().GetFetchCredentialsMode(),
- script_resource->CalculateAccessControlStatus());
+ script_resource->GetResourceRequest().GetFetchCredentialsMode());
// Step 13.7. "Asynchronously complete the perform the fetch steps with
// response." [spec text]
diff --git a/chromium/third_party/blink/renderer/core/loader/modulescript/worklet_module_script_fetcher.cc b/chromium/third_party/blink/renderer/core/loader/modulescript/worklet_module_script_fetcher.cc
index b14d8929c2a..74b7850b18d 100644
--- a/chromium/third_party/blink/renderer/core/loader/modulescript/worklet_module_script_fetcher.cc
+++ b/chromium/third_party/blink/renderer/core/loader/modulescript/worklet_module_script_fetcher.cc
@@ -38,7 +38,8 @@ void WorkletModuleScriptFetcher::Fetch(FetchParameters& fetch_params,
// need to handle that case, maybe by having a way to restart fetches in a
// different global scope?
url_ = fetch_params.Url();
- ScriptResource::Fetch(fetch_params, fetcher_.Get(), this);
+ ScriptResource::Fetch(fetch_params, fetcher_.Get(), this,
+ ScriptResource::kNoStreaming);
}
void WorkletModuleScriptFetcher::NotifyFinished(Resource* resource) {
@@ -50,8 +51,7 @@ void WorkletModuleScriptFetcher::NotifyFinished(Resource* resource) {
if (WasModuleLoadSuccessful(script_resource, &error_messages)) {
params.emplace(
script_resource->GetResponse().Url(), script_resource->SourceText(),
- script_resource->GetResourceRequest().GetFetchCredentialsMode(),
- script_resource->CalculateAccessControlStatus());
+ script_resource->GetResourceRequest().GetFetchCredentialsMode());
}
// This will eventually notify |client| passed to
diff --git a/chromium/third_party/blink/renderer/core/loader/navigation_policy.cc b/chromium/third_party/blink/renderer/core/loader/navigation_policy.cc
index 887f7a82584..2d639491e71 100644
--- a/chromium/third_party/blink/renderer/core/loader/navigation_policy.cc
+++ b/chromium/third_party/blink/renderer/core/loader/navigation_policy.cc
@@ -194,7 +194,6 @@ NavigationPolicy NavigationPolicyForCreateWindow(
return user_policy;
}
-STATIC_ASSERT_ENUM(kWebNavigationPolicyIgnore, kNavigationPolicyIgnore);
STATIC_ASSERT_ENUM(kWebNavigationPolicyDownload, kNavigationPolicyDownload);
STATIC_ASSERT_ENUM(kWebNavigationPolicyCurrentTab, kNavigationPolicyCurrentTab);
STATIC_ASSERT_ENUM(kWebNavigationPolicyNewBackgroundTab,
@@ -203,7 +202,5 @@ STATIC_ASSERT_ENUM(kWebNavigationPolicyNewForegroundTab,
kNavigationPolicyNewForegroundTab);
STATIC_ASSERT_ENUM(kWebNavigationPolicyNewWindow, kNavigationPolicyNewWindow);
STATIC_ASSERT_ENUM(kWebNavigationPolicyNewPopup, kNavigationPolicyNewPopup);
-STATIC_ASSERT_ENUM(kWebNavigationPolicyHandledByClient,
- kNavigationPolicyHandledByClient);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/navigation_policy.h b/chromium/third_party/blink/renderer/core/loader/navigation_policy.h
index 3ac25806623..402caf760c1 100644
--- a/chromium/third_party/blink/renderer/core/loader/navigation_policy.h
+++ b/chromium/third_party/blink/renderer/core/loader/navigation_policy.h
@@ -39,14 +39,12 @@ class Event;
struct WebWindowFeatures;
enum NavigationPolicy {
- kNavigationPolicyIgnore,
kNavigationPolicyDownload,
kNavigationPolicyCurrentTab,
kNavigationPolicyNewBackgroundTab,
kNavigationPolicyNewForegroundTab,
kNavigationPolicyNewWindow,
kNavigationPolicyNewPopup,
- kNavigationPolicyHandledByClient,
};
// Returns a NavigationPolicy to use for starting a navigation
diff --git a/chromium/third_party/blink/renderer/core/loader/navigation_policy_test.cc b/chromium/third_party/blink/renderer/core/loader/navigation_policy_test.cc
index ee8e66d906a..a5df47b8d93 100644
--- a/chromium/third_party/blink/renderer/core/loader/navigation_policy_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/navigation_policy_test.cc
@@ -56,22 +56,22 @@ class NavigationPolicyTest : public testing::Test {
}
Event* GetEvent(int modifiers, WebMouseEvent::Button button) {
- MouseEventInit mouse_initializer;
+ MouseEventInit* mouse_initializer = MouseEventInit::Create();
if (button == WebMouseEvent::Button::kLeft)
- mouse_initializer.setButton(0);
+ mouse_initializer->setButton(0);
if (button == WebMouseEvent::Button::kMiddle)
- mouse_initializer.setButton(1);
+ mouse_initializer->setButton(1);
if (button == WebMouseEvent::Button::kRight)
- mouse_initializer.setButton(2);
+ mouse_initializer->setButton(2);
if (modifiers & WebInputEvent::kShiftKey)
- mouse_initializer.setShiftKey(true);
+ mouse_initializer->setShiftKey(true);
if (modifiers & WebInputEvent::kControlKey)
- mouse_initializer.setCtrlKey(true);
+ mouse_initializer->setCtrlKey(true);
if (modifiers & WebInputEvent::kAltKey)
- mouse_initializer.setAltKey(true);
+ mouse_initializer->setAltKey(true);
if (modifiers & WebInputEvent::kMetaKey)
- mouse_initializer.setMetaKey(true);
- return MouseEvent::Create(nullptr, EventTypeNames::click,
+ mouse_initializer->setMetaKey(true);
+ return MouseEvent::Create(nullptr, event_type_names::kClick,
mouse_initializer);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.cc b/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.cc
index 43038f14363..2f9ed7136aa 100644
--- a/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.cc
+++ b/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.cc
@@ -131,8 +131,25 @@ class ScheduledRedirect final : public ScheduledURLNavigation {
Document::HttpRefreshType http_refresh_type,
WebFrameLoadType frame_load_type,
base::TimeTicks input_timestamp) {
- return new ScheduledRedirect(delay, origin_document, url, http_refresh_type,
- frame_load_type, input_timestamp);
+ return MakeGarbageCollected<ScheduledRedirect>(
+ delay, origin_document, url, http_refresh_type, frame_load_type,
+ input_timestamp);
+ }
+
+ ScheduledRedirect(double delay,
+ Document* origin_document,
+ const KURL& url,
+ Document::HttpRefreshType http_refresh_type,
+ WebFrameLoadType frame_load_type,
+ base::TimeTicks input_timestamp)
+ : ScheduledURLNavigation(ToReason(http_refresh_type),
+ delay,
+ origin_document,
+ url,
+ frame_load_type,
+ false,
+ input_timestamp) {
+ ClearUserGesture();
}
bool ShouldStartTimer(LocalFrame* frame) override {
@@ -168,22 +185,6 @@ class ScheduledRedirect final : public ScheduledURLNavigation {
NOTREACHED();
return Reason::kMetaTagRefresh;
}
-
- ScheduledRedirect(double delay,
- Document* origin_document,
- const KURL& url,
- Document::HttpRefreshType http_refresh_type,
- WebFrameLoadType frame_load_type,
- base::TimeTicks input_timestamp)
- : ScheduledURLNavigation(ToReason(http_refresh_type),
- delay,
- origin_document,
- url,
- frame_load_type,
- false,
- input_timestamp) {
- ClearUserGesture();
- }
};
class ScheduledFrameNavigation final : public ScheduledURLNavigation {
@@ -192,11 +193,10 @@ class ScheduledFrameNavigation final : public ScheduledURLNavigation {
const KURL& url,
WebFrameLoadType frame_load_type,
base::TimeTicks input_timestamp) {
- return new ScheduledFrameNavigation(origin_document, url, frame_load_type,
- input_timestamp);
+ return MakeGarbageCollected<ScheduledFrameNavigation>(
+ origin_document, url, frame_load_type, input_timestamp);
}
- private:
ScheduledFrameNavigation(Document* origin_document,
const KURL& url,
WebFrameLoadType frame_load_type,
@@ -214,7 +214,17 @@ class ScheduledReload final : public ScheduledNavigation {
public:
static ScheduledReload* Create(LocalFrame* frame,
base::TimeTicks input_timestamp) {
- return new ScheduledReload(frame, input_timestamp);
+ return MakeGarbageCollected<ScheduledReload>(frame, input_timestamp);
+ }
+
+ explicit ScheduledReload(LocalFrame* frame, base::TimeTicks input_timestamp)
+ : ScheduledNavigation(Reason::kReload,
+ 0.0,
+ nullptr /*origin_document */,
+ true,
+ input_timestamp),
+ frame_(frame) {
+ DCHECK(frame->GetDocument());
}
void Fire(LocalFrame* frame) override {
@@ -238,32 +248,15 @@ class ScheduledReload final : public ScheduledNavigation {
}
private:
- explicit ScheduledReload(LocalFrame* frame, base::TimeTicks input_timestamp)
- : ScheduledNavigation(Reason::kReload,
- 0.0,
- nullptr /*origin_document */,
- true,
- input_timestamp),
- frame_(frame) {
- DCHECK(frame->GetDocument());
- }
-
Member<LocalFrame> frame_;
};
class ScheduledPageBlock final : public ScheduledNavigation {
public:
static ScheduledPageBlock* Create(Document* origin_document, int reason) {
- return new ScheduledPageBlock(origin_document, reason);
+ return MakeGarbageCollected<ScheduledPageBlock>(origin_document, reason);
}
- void Fire(LocalFrame* frame) override {
- frame->Client()->LoadErrorPage(reason_);
- }
-
- KURL Url() const override { return KURL(); }
-
- private:
ScheduledPageBlock(Document* origin_document, int reason)
: ScheduledNavigation(Reason::kPageBlock,
0.0,
@@ -272,6 +265,13 @@ class ScheduledPageBlock final : public ScheduledNavigation {
base::TimeTicks() /* input_timestamp */),
reason_(reason) {}
+ void Fire(LocalFrame* frame) override {
+ frame->Client()->LoadErrorPage(reason_);
+ }
+
+ KURL Url() const override { return KURL(); }
+
+ private:
int reason_;
};
@@ -281,8 +281,25 @@ class ScheduledFormSubmission final : public ScheduledNavigation {
FormSubmission* submission,
WebFrameLoadType frame_load_type,
base::TimeTicks input_timestamp) {
- return new ScheduledFormSubmission(document, submission, frame_load_type,
- input_timestamp);
+ return MakeGarbageCollected<ScheduledFormSubmission>(
+ document, submission, frame_load_type, input_timestamp);
+ }
+
+ ScheduledFormSubmission(Document* document,
+ FormSubmission* submission,
+ WebFrameLoadType frame_load_type,
+ base::TimeTicks input_timestamp)
+ : ScheduledNavigation(submission->Method() == FormSubmission::kGetMethod
+ ? Reason::kFormSubmissionGet
+ : Reason::kFormSubmissionPost,
+ 0,
+ document,
+ true,
+ input_timestamp),
+ submission_(submission),
+ frame_load_type_(frame_load_type) {
+ DCHECK_NE(submission->Method(), FormSubmission::kDialogMethod);
+ DCHECK(submission_->Form());
}
void Fire(LocalFrame* frame) override {
@@ -303,23 +320,6 @@ class ScheduledFormSubmission final : public ScheduledNavigation {
}
private:
- ScheduledFormSubmission(Document* document,
- FormSubmission* submission,
- WebFrameLoadType frame_load_type,
- base::TimeTicks input_timestamp)
- : ScheduledNavigation(submission->Method() == FormSubmission::kGetMethod
- ? Reason::kFormSubmissionGet
- : Reason::kFormSubmissionPost,
- 0,
- document,
- true,
- input_timestamp),
- submission_(submission),
- frame_load_type_(frame_load_type) {
- DCHECK_NE(submission->Method(), FormSubmission::kDialogMethod);
- DCHECK(submission_->Form());
- }
-
Member<FormSubmission> submission_;
WebFrameLoadType frame_load_type_;
};
diff --git a/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.h b/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.h
index 9cea5cdcb56..00acdcb7bb9 100644
--- a/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.h
+++ b/chromium/third_party/blink/renderer/core/loader/navigation_scheduler.h
@@ -41,7 +41,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
@@ -57,9 +57,10 @@ class CORE_EXPORT NavigationScheduler final
: public GarbageCollectedFinalized<NavigationScheduler> {
public:
static NavigationScheduler* Create(LocalFrame* frame) {
- return new NavigationScheduler(frame);
+ return MakeGarbageCollected<NavigationScheduler>(frame);
}
+ explicit NavigationScheduler(LocalFrame*);
~NavigationScheduler();
bool LocationChangePending();
@@ -77,8 +78,6 @@ class CORE_EXPORT NavigationScheduler final
void Trace(blink::Visitor*);
private:
- explicit NavigationScheduler(LocalFrame*);
-
bool ShouldScheduleReload() const;
bool ShouldScheduleNavigation(const KURL&) const;
diff --git a/chromium/third_party/blink/renderer/core/loader/ping_loader.cc b/chromium/third_party/blink/renderer/core/loader/ping_loader.cc
index 44f1c271f2e..fa66a5b8f23 100644
--- a/chromium/third_party/blink/renderer/core/loader/ping_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/ping_loader.cc
@@ -185,7 +185,7 @@ bool SendBeaconCommon(LocalFrame* frame,
}
ResourceRequest request(url);
- request.SetHTTPMethod(HTTPNames::POST);
+ request.SetHTTPMethod(http_names::kPOST);
request.SetKeepalive(true);
request.SetRequestContext(mojom::RequestContextType::BEACON);
beacon.Serialize(request);
@@ -196,7 +196,8 @@ bool SendBeaconCommon(LocalFrame* frame,
// Content-Type header, set corsMode to "no-cors".
// As we don't support requests with non CORS-safelisted Content-Type, the
// mode should always be "no-cors".
- params.MutableOptions().initiator_info.name = FetchInitiatorTypeNames::beacon;
+ params.MutableOptions().initiator_info.name =
+ fetch_initiator_type_names::kBeacon;
frame->Client()->DidDispatchPingLoader(request.Url());
Resource* resource =
@@ -214,18 +215,18 @@ void PingLoader::SendLinkAuditPing(LocalFrame* frame,
return;
ResourceRequest request(ping_url);
- request.SetHTTPMethod(HTTPNames::POST);
+ request.SetHTTPMethod(http_names::kPOST);
request.SetHTTPContentType("text/ping");
request.SetHTTPBody(EncodedFormData::Create("PING"));
- request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0");
- request.SetHTTPHeaderField(HTTPNames::Ping_To,
+ request.SetHTTPHeaderField(http_names::kCacheControl, "max-age=0");
+ request.SetHTTPHeaderField(http_names::kPingTo,
AtomicString(destination_url.GetString()));
scoped_refptr<const SecurityOrigin> ping_origin =
SecurityOrigin::Create(ping_url);
if (ProtocolIs(frame->GetDocument()->Url().GetString(), "http") ||
frame->GetDocument()->GetSecurityOrigin()->CanAccess(ping_origin.get())) {
request.SetHTTPHeaderField(
- HTTPNames::Ping_From,
+ http_names::kPingFrom,
AtomicString(frame->GetDocument()->Url().GetString()));
}
@@ -233,10 +234,11 @@ void PingLoader::SendLinkAuditPing(LocalFrame* frame,
// TODO(domfarolino): Add WPTs ensuring that pings do not have a referrer
// header.
request.SetReferrerString(Referrer::NoReferrer());
- request.SetReferrerPolicy(kReferrerPolicyNever);
+ request.SetReferrerPolicy(network::mojom::ReferrerPolicy::kNever);
request.SetRequestContext(mojom::RequestContextType::PING);
FetchParameters params(request);
- params.MutableOptions().initiator_info.name = FetchInitiatorTypeNames::ping;
+ params.MutableOptions().initiator_info.name =
+ fetch_initiator_type_names::kPing;
frame->Client()->DidDispatchPingLoader(request.Url());
RawResource::Fetch(params, frame->GetDocument()->Fetcher(), nullptr);
@@ -247,7 +249,7 @@ void PingLoader::SendViolationReport(LocalFrame* frame,
scoped_refptr<EncodedFormData> report,
ViolationReportType type) {
ResourceRequest request(report_url);
- request.SetHTTPMethod(HTTPNames::POST);
+ request.SetHTTPMethod(http_names::kPOST);
switch (type) {
case kContentSecurityPolicyViolationReport:
request.SetHTTPContentType("application/csp-report");
@@ -265,7 +267,7 @@ void PingLoader::SendViolationReport(LocalFrame* frame,
request.SetFetchRedirectMode(network::mojom::FetchRedirectMode::kError);
FetchParameters params(request);
params.MutableOptions().initiator_info.name =
- FetchInitiatorTypeNames::violationreport;
+ fetch_initiator_type_names::kViolationreport;
frame->Client()->DidDispatchPingLoader(request.Url());
RawResource::Fetch(params, frame->GetDocument()->Fetcher(), nullptr);
diff --git a/chromium/third_party/blink/renderer/core/loader/ping_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/ping_loader_test.cc
index fcac7553bfa..d1528a9941b 100644
--- a/chromium/third_party/blink/renderer/core/loader/ping_loader_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/ping_loader_test.cc
@@ -58,7 +58,7 @@ class PingLoaderTest : public PageTestBase {
const ResourceRequest& PingAndGetRequest(const KURL& ping_url) {
KURL destination_url("http://navigation.destination");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ping_url, test::CoreTestDataPath("bar.html"), "text/html");
PingLoader::SendLinkAuditPing(&GetFrame(), ping_url, destination_url);
const ResourceRequest& ping_request = client_->PingRequest();
@@ -108,7 +108,7 @@ TEST_F(PingLoaderTest, LinkAuditPingPriority) {
SetDocumentURL(KURL("http://localhost/foo.html"));
KURL ping_url("https://localhost/bar.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ping_url, test::CoreTestDataPath("bar.html"), "text/html");
PingLoader::SendLinkAuditPing(&GetFrame(), ping_url, destination_url);
Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests();
@@ -122,7 +122,7 @@ TEST_F(PingLoaderTest, ViolationPriority) {
SetDocumentURL(KURL("http://localhost/foo.html"));
KURL ping_url("https://localhost/bar.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ping_url, test::CoreTestDataPath("bar.html"), "text/html");
PingLoader::SendViolationReport(&GetFrame(), ping_url,
EncodedFormData::Create(),
@@ -138,7 +138,7 @@ TEST_F(PingLoaderTest, BeaconPriority) {
SetDocumentURL(KURL("https://localhost/foo.html"));
KURL ping_url("https://localhost/bar.html");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
ping_url, test::CoreTestDataPath("bar.html"), "text/html");
PingLoader::SendBeacon(&GetFrame(), ping_url, "hello");
Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests();
diff --git a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.cc b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.cc
index 7336bc8d3c8..a8ff441153f 100644
--- a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.cc
+++ b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.cc
@@ -5,6 +5,8 @@
#include "third_party/blink/renderer/core/loader/previews_resource_loading_hints.h"
#include "base/metrics/histogram_macros.h"
+#include "services/metrics/public/cpp/ukm_builders.h"
+#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -28,16 +30,25 @@ String GetConsoleLogStringForBlockedLoad(const KURL& url) {
// static
PreviewsResourceLoadingHints* PreviewsResourceLoadingHints::Create(
ExecutionContext& execution_context,
+ int64_t ukm_source_id,
const std::vector<WTF::String>& subresource_patterns_to_block) {
- return new PreviewsResourceLoadingHints(&execution_context,
- subresource_patterns_to_block);
+ return MakeGarbageCollected<PreviewsResourceLoadingHints>(
+ &execution_context, ukm_source_id, subresource_patterns_to_block);
}
PreviewsResourceLoadingHints::PreviewsResourceLoadingHints(
ExecutionContext* execution_context,
+ int64_t ukm_source_id,
const std::vector<WTF::String>& subresource_patterns_to_block)
: execution_context_(execution_context),
- subresource_patterns_to_block_(subresource_patterns_to_block) {}
+ ukm_source_id_(ukm_source_id),
+ subresource_patterns_to_block_(subresource_patterns_to_block) {
+ DCHECK_NE(ukm::kInvalidSourceId, ukm_source_id_);
+
+ subresource_patterns_to_block_usage_.assign(
+ subresource_patterns_to_block.size(), false);
+ blocked_resource_load_priority_counts_.fill(0);
+}
PreviewsResourceLoadingHints::~PreviewsResourceLoadingHints() = default;
@@ -51,14 +62,19 @@ bool PreviewsResourceLoadingHints::AllowLoad(
resource_url_string = resource_url_string.Left(resource_url.PathEnd());
bool allow_load = true;
+ int pattern_index = 0;
for (const WTF::String& subresource_pattern :
subresource_patterns_to_block_) {
// TODO(tbansal): https://crbug.com/856247. Add support for wildcard
// matching.
if (resource_url_string.Find(subresource_pattern) != kNotFound) {
allow_load = false;
+ subresource_patterns_to_block_usage_[pattern_index] = true;
+ blocked_resource_load_priority_counts_[static_cast<int>(
+ resource_load_priority)]++;
break;
}
+ pattern_index++;
}
UMA_HISTOGRAM_BOOLEAN("ResourceLoadingHints.ResourceLoadingBlocked",
@@ -91,4 +107,36 @@ void PreviewsResourceLoadingHints::Trace(blink::Visitor* visitor) {
visitor->Trace(execution_context_);
}
+void PreviewsResourceLoadingHints::RecordUKM(
+ ukm::UkmRecorder* ukm_recorder) const {
+ DCHECK(ukm_recorder);
+
+ size_t patterns_to_block_used_count = 0;
+ for (bool pattern_used : subresource_patterns_to_block_usage_) {
+ if (pattern_used) {
+ patterns_to_block_used_count++;
+ }
+ }
+
+ ukm::builders::PreviewsResourceLoadingHints(ukm_source_id_)
+ .Setpatterns_to_block_total(subresource_patterns_to_block_.size())
+ .Setpatterns_to_block_used(patterns_to_block_used_count)
+ .Setblocked_very_low_priority(
+ blocked_resource_load_priority_counts_[static_cast<int>(
+ ResourceLoadPriority::kVeryLow)])
+ .Setblocked_low_priority(
+ blocked_resource_load_priority_counts_[static_cast<int>(
+ ResourceLoadPriority::kLow)])
+ .Setblocked_medium_priority(
+ blocked_resource_load_priority_counts_[static_cast<int>(
+ ResourceLoadPriority::kMedium)])
+ .Setblocked_high_priority(
+ blocked_resource_load_priority_counts_[static_cast<int>(
+ ResourceLoadPriority::kHigh)])
+ .Setblocked_very_high_priority(
+ blocked_resource_load_priority_counts_[static_cast<int>(
+ ResourceLoadPriority::kVeryHigh)])
+ .Record(ukm_recorder);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.h b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.h
index 2e3ad881c20..2ad7cc24cf1 100644
--- a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.h
+++ b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.h
@@ -13,6 +13,10 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+namespace ukm {
+class UkmRecorder;
+}
+
namespace blink {
class ExecutionContext;
@@ -25,8 +29,13 @@ class CORE_EXPORT PreviewsResourceLoadingHints final
public:
static PreviewsResourceLoadingHints* Create(
ExecutionContext& execution_context,
+ int64_t ukm_source_id,
const std::vector<WTF::String>& subresource_patterns_to_block);
+ PreviewsResourceLoadingHints(
+ ExecutionContext* execution_context,
+ int64_t ukm_source_id,
+ const std::vector<WTF::String>& subresource_patterns_to_block);
~PreviewsResourceLoadingHints();
// Returns true if load of resource with URL |resource_url| and priority
@@ -36,15 +45,17 @@ class CORE_EXPORT PreviewsResourceLoadingHints final
virtual void Trace(blink::Visitor*);
- private:
- PreviewsResourceLoadingHints(
- ExecutionContext* execution_context,
- const std::vector<WTF::String>& subresource_patterns_to_block);
+ // Records UKM on the utilization of patterns to block during the document
+ // load. This is expected to be called once after the document finishes
+ // loading.
+ void RecordUKM(ukm::UkmRecorder* ukm_recorder) const;
+ private:
// Reports to console when loading of |resource_url| is blocked.
void ReportBlockedLoading(const KURL& resource_url) const;
Member<ExecutionContext> execution_context_;
+ const int64_t ukm_source_id_;
// |subresource_patterns_to_block_| is a collection of subresource patterns
// for resources whose loading should be blocked. Each pattern is a
@@ -52,6 +63,15 @@ class CORE_EXPORT PreviewsResourceLoadingHints final
// |subresource_patterns_to_block_|, then that subresource's loading could
// be blocked.
const std::vector<WTF::String> subresource_patterns_to_block_;
+
+ // |subresource_patterns_to_block_usage_| records whether the pattern located
+ // at the same index in |subresource_patterns_to_block_| was ever blocked.
+ mutable std::vector<bool> subresource_patterns_to_block_usage_;
+
+ // |blocked_resource_load_priority_counts_| records the total number of
+ // resources blocked at each ResourceLoadPriority.
+ mutable std::array<int, static_cast<int>(ResourceLoadPriority::kHighest) + 1>
+ blocked_resource_load_priority_counts_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.cc b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.cc
index 615b19b9b27..656866d0c57 100644
--- a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.cc
+++ b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.cc
@@ -37,8 +37,9 @@ void PreviewsResourceLoadingHintsReceiverImpl::SetResourceLoadingHints(
}
document_->Loader()->SetPreviewsResourceLoadingHints(
- PreviewsResourceLoadingHints::Create(*(document_.Get()),
- subresource_patterns_to_block));
+ PreviewsResourceLoadingHints::Create(
+ *(document_.Get()), resource_loading_hints->ukm_source_id,
+ subresource_patterns_to_block));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_test.cc b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_test.cc
index 15295e4e57d..4d5a001a2e6 100644
--- a/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_test.cc
@@ -8,10 +8,12 @@
#include <vector>
#include "base/test/metrics/histogram_tester.h"
+#include "components/ukm/test_ukm_recorder.h"
+#include "services/metrics/public/cpp/ukm_builders.h"
+#include "services/metrics/public/cpp/ukm_recorder.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
-#include "third_party/blink/renderer/core/loader/previews_resource_loading_hints.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
@@ -38,7 +40,8 @@ TEST_F(PreviewsResourceLoadingHintsTest, NoPatterns) {
std::vector<WTF::String> subresources_to_block;
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
- dummy_page_holder_->GetDocument(), subresources_to_block);
+ dummy_page_holder_->GetDocument(), ukm::UkmRecorder::GetNewSourceID(),
+ subresources_to_block);
EXPECT_TRUE(hints->AllowLoad(KURL("https://www.example.com/"),
ResourceLoadPriority::kHighest));
}
@@ -48,7 +51,8 @@ TEST_F(PreviewsResourceLoadingHintsTest, OnePattern) {
subresources_to_block.push_back("foo.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
- dummy_page_holder_->GetDocument(), subresources_to_block);
+ dummy_page_holder_->GetDocument(), ukm::UkmRecorder::GetNewSourceID(),
+ subresources_to_block);
const struct {
KURL url;
@@ -102,7 +106,8 @@ TEST_F(PreviewsResourceLoadingHintsTest, MultiplePatterns) {
subresources_to_block.push_back(".example2.com/baz.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
- dummy_page_holder_->GetDocument(), subresources_to_block);
+ dummy_page_holder_->GetDocument(), ukm::UkmRecorder::GetNewSourceID(),
+ subresources_to_block);
const struct {
KURL url;
@@ -132,7 +137,8 @@ TEST_F(PreviewsResourceLoadingHintsTest, OnePatternHistogramChecker) {
subresources_to_block.push_back("foo.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
- dummy_page_holder_->GetDocument(), subresources_to_block);
+ dummy_page_holder_->GetDocument(), ukm::UkmRecorder::GetNewSourceID(),
+ subresources_to_block);
const struct {
KURL url;
@@ -178,6 +184,84 @@ TEST_F(PreviewsResourceLoadingHintsTest, OnePatternHistogramChecker) {
}
}
+TEST_F(PreviewsResourceLoadingHintsTest, MultiplePatternUKMChecker) {
+ std::vector<WTF::String> subresources_to_block;
+ subresources_to_block.push_back(".example1.com/low_1.jpg");
+ subresources_to_block.push_back(".example1.com/very_low_1.jpg");
+ subresources_to_block.push_back(".example1.com/very_high_1.jpg");
+ subresources_to_block.push_back(".example1.com/medium_1_and_medium_4.jpg");
+ subresources_to_block.push_back(".example1.com/unused_1.jpg");
+ subresources_to_block.push_back(".example2.com/medium_2.jpg");
+ subresources_to_block.push_back(".example2.com/unused_2.jpg");
+ subresources_to_block.push_back(".example3.com/unused_3.jpg");
+ subresources_to_block.push_back(".example3.com/very_low_2_and_medium_3.jpg");
+
+ PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
+ dummy_page_holder_->GetDocument(), ukm::UkmRecorder::GetNewSourceID(),
+ subresources_to_block);
+
+ const struct {
+ KURL url;
+ ResourceLoadPriority resource_load_priority;
+ } resources_to_load[] = {
+ {KURL("https://www.example1.com/"), ResourceLoadPriority::kHigh},
+ {KURL("https://www.example1.com/foo.js"), ResourceLoadPriority::kLow},
+ {KURL("https://www.example1.com/very_low_1.jpg"),
+ ResourceLoadPriority::kVeryLow},
+ {KURL("https://www.example1.com/low_1.jpg"), ResourceLoadPriority::kLow},
+ {KURL("https://www.example1.com/very_high_1.jpg"),
+ ResourceLoadPriority::kVeryHigh},
+ {KURL("https://www.example1.com/pages/foo.jpg"),
+ ResourceLoadPriority::kVeryLow},
+ {KURL("https://www.example1.com/foobar.jpg"),
+ ResourceLoadPriority::kVeryHigh},
+ {KURL("https://www.example1.com/barfoo.jpg"),
+ ResourceLoadPriority::kVeryHigh},
+ {KURL("http://www.example1.com/foo.jpg"), ResourceLoadPriority::kLow},
+ {KURL("http://www.example1.com/medium_1_and_medium_4.jpg"),
+ ResourceLoadPriority::kMedium},
+ {KURL("http://www.example2.com/medium_2.jpg"),
+ ResourceLoadPriority::kMedium},
+ {KURL("http://www.example2.com/pages/baz.jpg"),
+ ResourceLoadPriority::kLow},
+ {KURL("http://www.example2.com/baz.html"),
+ ResourceLoadPriority::kVeryHigh},
+ {KURL("http://www.example3.com/very_low_2_and_medium_3.jpg"),
+ ResourceLoadPriority::kVeryLow},
+ {KURL("http://www.example3.com/very_low_2_and_medium_3.jpg"),
+ ResourceLoadPriority::kMedium},
+ {KURL("http://www.example1.com/medium_1_and_medium_4.jpg"),
+ ResourceLoadPriority::kMedium},
+ };
+
+ for (const auto& resource_to_load : resources_to_load) {
+ hints->AllowLoad(resource_to_load.url,
+ resource_to_load.resource_load_priority);
+ }
+
+ ukm::TestAutoSetUkmRecorder test_ukm_recorder;
+ hints->RecordUKM(&test_ukm_recorder);
+
+ using UkmEntry = ukm::builders::PreviewsResourceLoadingHints;
+ auto entries = test_ukm_recorder.GetEntriesByName(UkmEntry::kEntryName);
+ ASSERT_EQ(1u, entries.size());
+ const auto* entry = entries[0];
+ test_ukm_recorder.ExpectEntryMetric(
+ entry, UkmEntry::kpatterns_to_block_totalName, 9);
+ test_ukm_recorder.ExpectEntryMetric(entry,
+ UkmEntry::kpatterns_to_block_usedName, 6);
+ test_ukm_recorder.ExpectEntryMetric(
+ entry, UkmEntry::kblocked_very_low_priorityName, 2);
+ test_ukm_recorder.ExpectEntryMetric(entry,
+ UkmEntry::kblocked_low_priorityName, 1);
+ test_ukm_recorder.ExpectEntryMetric(
+ entry, UkmEntry::kblocked_medium_priorityName, 4);
+ test_ukm_recorder.ExpectEntryMetric(entry,
+ UkmEntry::kblocked_high_priorityName, 0);
+ test_ukm_recorder.ExpectEntryMetric(
+ entry, UkmEntry::kblocked_very_high_priorityName, 1);
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.cc b/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.cc
index ce87f91a464..6208a535de9 100644
--- a/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.cc
+++ b/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.cc
@@ -30,12 +30,12 @@
#include "third_party/blink/renderer/core/loader/private/prerender_handle.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/prerenderer_client.h"
#include "third_party/blink/renderer/platform/prerender.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
namespace blink {
@@ -61,7 +61,7 @@ PrerenderHandle* PrerenderHandle::Create(Document& document,
prerenderer_client->WillAddPrerender(prerender);
prerender->Add();
- return new PrerenderHandle(document, prerender);
+ return MakeGarbageCollected<PrerenderHandle>(document, prerender);
}
PrerenderHandle::PrerenderHandle(Document& document, Prerender* prerender)
diff --git a/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.h b/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.h
index edee2a3cc49..382c28f8271 100644
--- a/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.h
+++ b/chromium/third_party/blink/renderer/core/loader/private/prerender_handle.h
@@ -53,6 +53,7 @@ class PrerenderHandle final : public GarbageCollectedFinalized<PrerenderHandle>,
const KURL&,
unsigned prerender_rel_types);
+ PrerenderHandle(Document&, Prerender*);
virtual ~PrerenderHandle();
void Cancel();
@@ -65,8 +66,6 @@ class PrerenderHandle final : public GarbageCollectedFinalized<PrerenderHandle>,
EAGERLY_FINALIZE();
private:
- PrerenderHandle(Document&, Prerender*);
-
void Detach();
Member<Prerender> prerender_;
diff --git a/chromium/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc b/chromium/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc
index e50412bb0d6..be0ecb6b10d 100644
--- a/chromium/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/programmatic_scroll_test.cc
@@ -38,7 +38,7 @@ class ProgrammaticScrollTest : public testing::Test {
protected:
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -49,11 +49,12 @@ class ProgrammaticScrollTest : public testing::Test {
TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithScale) {
RegisterMockedHttpURLLoad("long_scroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html");
web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
FrameLoader& loader = web_view->MainFrameImpl()->GetFrame()->Loader();
loader.GetDocumentLoader()->SetLoadType(WebFrameLoadType::kBackForward);
@@ -81,11 +82,12 @@ TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithScale) {
TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithoutScale) {
RegisterMockedHttpURLLoad("long_scroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html");
web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
FrameLoader& loader = web_view->MainFrameImpl()->GetFrame()->Loader();
loader.GetDocumentLoader()->SetLoadType(WebFrameLoadType::kBackForward);
@@ -110,11 +112,12 @@ TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithoutScale) {
TEST_F(ProgrammaticScrollTest, SaveScrollStateClearsAnchor) {
RegisterMockedHttpURLLoad("long_scroll.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html");
web_view->Resize(WebSize(1000, 1000));
- web_view->UpdateAllLifecyclePhases();
+ web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
FrameLoader& loader = web_view->MainFrameImpl()->GetFrame()->Loader();
loader.GetDocumentLoader()->SetLoadType(WebFrameLoadType::kBackForward);
diff --git a/chromium/third_party/blink/renderer/core/loader/progress_tracker.cc b/chromium/third_party/blink/renderer/core/loader/progress_tracker.cc
index 1b3ea59783f..1e0088c45e1 100644
--- a/chromium/third_party/blink/renderer/core/loader/progress_tracker.cc
+++ b/chromium/third_party/blink/renderer/core/loader/progress_tracker.cc
@@ -66,7 +66,7 @@ struct ProgressItem {
};
ProgressTracker* ProgressTracker::Create(LocalFrame* frame) {
- return new ProgressTracker(frame);
+ return MakeGarbageCollected<ProgressTracker>(frame);
}
ProgressTracker::ProgressTracker(LocalFrame* frame)
@@ -165,7 +165,8 @@ void ProgressTracker::IncrementProgress(unsigned long identifier,
item->estimated_length = estimated_length;
}
-void ProgressTracker::IncrementProgress(unsigned long identifier, int length) {
+void ProgressTracker::IncrementProgress(unsigned long identifier,
+ size_t length) {
ProgressItem* item = progress_items_.at(identifier);
if (!item)
return;
diff --git a/chromium/third_party/blink/renderer/core/loader/progress_tracker.h b/chromium/third_party/blink/renderer/core/loader/progress_tracker.h
index f5c64eed4c5..4ff4e18d6d4 100644
--- a/chromium/third_party/blink/renderer/core/loader/progress_tracker.h
+++ b/chromium/third_party/blink/renderer/core/loader/progress_tracker.h
@@ -52,6 +52,7 @@ class CORE_EXPORT ProgressTracker final
public:
static ProgressTracker* Create(LocalFrame*);
+ explicit ProgressTracker(LocalFrame*);
~ProgressTracker();
void Trace(blink::Visitor*);
void Dispose();
@@ -66,12 +67,10 @@ class CORE_EXPORT ProgressTracker final
void WillStartLoading(unsigned long identifier, ResourceLoadPriority);
void IncrementProgress(unsigned long identifier, const ResourceResponse&);
- void IncrementProgress(unsigned long identifier, int);
+ void IncrementProgress(unsigned long identifier, size_t);
void CompleteProgress(unsigned long identifier);
private:
- explicit ProgressTracker(LocalFrame*);
-
LocalFrameClient* GetLocalFrameClient() const;
void MaybeSendProgress();
diff --git a/chromium/third_party/blink/renderer/core/loader/progress_tracker_test.cc b/chromium/third_party/blink/renderer/core/loader/progress_tracker_test.cc
index 4cbb6faa3a0..cb9ca792929 100644
--- a/chromium/third_party/blink/renderer/core/loader/progress_tracker_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/progress_tracker_test.cc
@@ -34,7 +34,7 @@ class ProgressTrackerTest : public PageTestBase {
}
void SetUp() override {
- client_ = new ProgressClient;
+ client_ = MakeGarbageCollected<ProgressClient>();
PageTestBase::SetupPageWithClients(nullptr, client_.Get());
}
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.cc b/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.cc
index 6b838b039a8..95ce0384ada 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.cc
@@ -61,7 +61,8 @@ CSSStyleSheetResource* CSSStyleSheetResource::CreateForTest(
ResourceLoaderOptions options;
TextResourceDecoderOptions decoder_options(
TextResourceDecoderOptions::kCSSContent, encoding);
- return new CSSStyleSheetResource(request, options, decoder_options);
+ return MakeGarbageCollected<CSSStyleSheetResource>(request, options,
+ decoder_options);
}
CSSStyleSheetResource::CSSStyleSheetResource(
@@ -92,10 +93,12 @@ void CSSStyleSheetResource::Trace(blink::Visitor* visitor) {
TextResource::Trace(visitor);
}
-ReferrerPolicy CSSStyleSheetResource::GetReferrerPolicy() const {
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+network::mojom::ReferrerPolicy CSSStyleSheetResource::GetReferrerPolicy()
+ const {
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
String referrer_policy_header =
- GetResponse().HttpHeaderField(HTTPNames::Referrer_Policy);
+ GetResponse().HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
SecurityPolicy::ReferrerPolicyFromHeaderValue(
referrer_policy_header, kDoNotSupportReferrerPolicyLegacyKeywords,
@@ -178,9 +181,7 @@ bool CSSStyleSheetResource::CanUseSheet(const CSSParserContext* parser_context,
parser_context->CountDeprecation(
WebFeature::kLocalCSSFileExtensionRejected);
}
- if (RuntimeEnabledFeatures::RequireCSSExtensionForFileEnabled()) {
- return false;
- }
+ return false;
}
}
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h
index a3b3ae4c85d..c149586609f 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h
@@ -50,6 +50,9 @@ class CORE_EXPORT CSSStyleSheetResource final : public TextResource {
static CSSStyleSheetResource* CreateForTest(const KURL&,
const WTF::TextEncoding&);
+ CSSStyleSheetResource(const ResourceRequest&,
+ const ResourceLoaderOptions&,
+ const TextResourceDecoderOptions&);
~CSSStyleSheetResource() override;
void Trace(blink::Visitor*) override;
@@ -57,7 +60,7 @@ class CORE_EXPORT CSSStyleSheetResource final : public TextResource {
MIMETypeCheck = MIMETypeCheck::kStrict) const;
StyleSheetContents* CreateParsedStyleSheetFromCache(const CSSParserContext*);
void SaveParsedStyleSheet(StyleSheetContents*);
- ReferrerPolicy GetReferrerPolicy() const;
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const;
private:
class CSSStyleSheetResourceFactory : public ResourceFactory {
@@ -70,12 +73,10 @@ class CORE_EXPORT CSSStyleSheetResource final : public TextResource {
const ResourceRequest& request,
const ResourceLoaderOptions& options,
const TextResourceDecoderOptions& decoder_options) const override {
- return new CSSStyleSheetResource(request, options, decoder_options);
+ return MakeGarbageCollected<CSSStyleSheetResource>(request, options,
+ decoder_options);
}
};
- CSSStyleSheetResource(const ResourceRequest&,
- const ResourceLoaderOptions&,
- const TextResourceDecoderOptions&);
bool CanUseSheet(const CSSParserContext*, MIMETypeCheck) const;
void NotifyFinished() override;
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/document_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/document_resource.h
index 4cc1c066df3..bee1015ed8f 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/document_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/document_resource.h
@@ -41,6 +41,11 @@ class CORE_EXPORT DocumentResource final : public TextResource {
static DocumentResource* FetchSVGDocument(FetchParameters&,
ResourceFetcher*,
ResourceClient*);
+
+ DocumentResource(const ResourceRequest&,
+ ResourceType,
+ const ResourceLoaderOptions&,
+ const TextResourceDecoderOptions&);
~DocumentResource() override;
void Trace(blink::Visitor*) override;
@@ -59,14 +64,10 @@ class CORE_EXPORT DocumentResource final : public TextResource {
const ResourceRequest& request,
const ResourceLoaderOptions& options,
const TextResourceDecoderOptions& decoder_options) const override {
- return new DocumentResource(request, ResourceType::kSVGDocument, options,
- decoder_options);
+ return MakeGarbageCollected<DocumentResource>(
+ request, ResourceType::kSVGDocument, options, decoder_options);
}
};
- DocumentResource(const ResourceRequest&,
- ResourceType,
- const ResourceLoaderOptions&,
- const TextResourceDecoderOptions&);
bool MimeTypeAllowed() const;
Document* CreateDocument(const KURL&);
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/font_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/font_resource.h
index 3f147ba08c9..d5f2b7cc6f7 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/font_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/font_resource.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
namespace blink {
@@ -47,6 +47,8 @@ class CORE_EXPORT FontResource final : public Resource {
static FontResource* Fetch(FetchParameters&,
ResourceFetcher*,
FontResourceClient*);
+
+ FontResource(const ResourceRequest&, const ResourceLoaderOptions&);
~FontResource() override;
void DidAddClient(ResourceClient*) override;
@@ -77,10 +79,9 @@ class CORE_EXPORT FontResource final : public Resource {
Resource* Create(const ResourceRequest& request,
const ResourceLoaderOptions& options) const override {
- return new FontResource(request, options);
+ return MakeGarbageCollected<FontResource>(request, options);
}
};
- FontResource(const ResourceRequest&, const ResourceLoaderOptions&);
void NotifyFinished() override;
void FontLoadShortLimitCallback();
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/font_resource_test.cc b/chromium/third_party/blink/renderer/core/loader/resource/font_resource_test.cc
index 66fe55ab2d8..89c8c163982 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/font_resource_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/font_resource_test.cc
@@ -41,7 +41,7 @@ TEST_F(FontResourceTest,
KURL url("http://127.0.0.1:8000/font.woff");
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::ETag, "1234567890");
+ response.SetHTTPHeaderField(http_names::kETag, "1234567890");
Platform::Current()->GetURLLoaderMockFactory()->RegisterURL(
url, WrappedResourceResponse(response), "");
@@ -120,7 +120,8 @@ TEST_F(FontResourceTest, CacheAwareFontLoading) {
// on future CSSFontFaceSrcValue::Fetch calls. This tests wants to ensure
// correct behavior in the case where we reuse a FontResource without it being
// a "cache hit" in ResourceFetcher's view.
- Persistent<MockFontResourceClient> client = new MockFontResourceClient;
+ Persistent<MockFontResourceClient> client =
+ MakeGarbageCollected<MockFontResourceClient>();
FontResource& resource = src_value->Fetch(&document, client);
fetcher->StartLoad(&resource);
@@ -141,7 +142,8 @@ TEST_F(FontResourceTest, CacheAwareFontLoading) {
EXPECT_FALSE(client->FontLoadLongLimitExceededCalled());
// Add client now, FontLoadShortLimitExceeded() should be called.
- Persistent<MockFontResourceClient> client2 = new MockFontResourceClient;
+ Persistent<MockFontResourceClient> client2 =
+ MakeGarbageCollected<MockFontResourceClient>();
FontResource& resource2 = src_value->Fetch(&document, client2);
EXPECT_EQ(&resource, &resource2);
EXPECT_TRUE(client2->FontLoadShortLimitExceededCalled());
@@ -152,7 +154,8 @@ TEST_F(FontResourceTest, CacheAwareFontLoading) {
EXPECT_TRUE(client->FontLoadLongLimitExceededCalled());
// Add client now, both callbacks should be called.
- Persistent<MockFontResourceClient> client3 = new MockFontResourceClient;
+ Persistent<MockFontResourceClient> client3 =
+ MakeGarbageCollected<MockFontResourceClient>();
FontResource& resource3 = src_value->Fetch(&document, client3);
EXPECT_EQ(&resource, &resource3);
EXPECT_TRUE(client3->FontLoadShortLimitExceededCalled());
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/image_resource.cc b/chromium/third_party/blink/renderer/core/loader/resource/image_resource.cc
index 24a661297de..913d8327b1d 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/image_resource.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/image_resource.cc
@@ -28,6 +28,7 @@
#include <memory>
#include <utility>
+#include "base/numerics/safe_conversions.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_info.h"
@@ -158,10 +159,10 @@ class ImageResource::ImageResourceFactory : public NonTextResourceFactory {
Resource* Create(const ResourceRequest& request,
const ResourceLoaderOptions& options) const override {
- return new ImageResource(request, options,
- ImageResourceContent::CreateNotStarted(),
- fetch_params_->GetImageRequestOptimization() ==
- FetchParameters::kAllowPlaceholder);
+ return MakeGarbageCollected<ImageResource>(
+ request, options, ImageResourceContent::CreateNotStarted(),
+ fetch_params_->GetImageRequestOptimization() ==
+ FetchParameters::kAllowPlaceholder);
}
private:
@@ -181,7 +182,8 @@ ImageResource* ImageResource::Fetch(FetchParameters& params,
// If the fetch originated from user agent CSS we should mark it as a user
// agent resource.
- if (params.Options().initiator_info.name == FetchInitiatorTypeNames::uacss)
+ if (params.Options().initiator_info.name ==
+ fetch_initiator_type_names::kUacss)
resource->FlagAsUserAgentResource();
return resource;
}
@@ -211,8 +213,8 @@ bool ImageResource::CanUseCacheValidator() const {
ImageResource* ImageResource::Create(const ResourceRequest& request) {
ResourceLoaderOptions options;
- return new ImageResource(request, options,
- ImageResourceContent::CreateNotStarted(), false);
+ return MakeGarbageCollected<ImageResource>(
+ request, options, ImageResourceContent::CreateNotStarted(), false);
}
ImageResource* ImageResource::CreateForTest(const KURL& url) {
@@ -231,8 +233,10 @@ ImageResource::ImageResource(const ResourceRequest& resource_request,
is_placeholder ? PlaceholderOption::kShowAndReloadPlaceholderAlways
: PlaceholderOption::kDoNotReloadPlaceholder) {
DCHECK(GetContent());
- RESOURCE_LOADING_DVLOG(1) << "new ImageResource(ResourceRequest) " << this;
- GetContent()->SetImageResourceInfo(new ImageResourceInfoImpl(this));
+ RESOURCE_LOADING_DVLOG(1)
+ << "MakeGarbageCollected<ImageResource>(ResourceRequest) " << this;
+ GetContent()->SetImageResourceInfo(
+ MakeGarbageCollected<ImageResourceInfoImpl>(this));
}
ImageResource::~ImageResource() {
@@ -294,8 +298,9 @@ void ImageResource::DestroyDecodedDataIfPossible() {
GetContent()->DestroyDecodedData();
if (GetContent()->HasImage() && !IsUnusedPreload() &&
GetContent()->IsRefetchableDataFromDiskCache()) {
- UMA_HISTOGRAM_MEMORY_KB("Memory.Renderer.EstimatedDroppableEncodedSize",
- EncodedSize() / 1024);
+ UMA_HISTOGRAM_MEMORY_KB(
+ "Memory.Renderer.EstimatedDroppableEncodedSize",
+ base::saturated_cast<base::Histogram::Sample>(EncodedSize() / 1024));
}
}
@@ -312,7 +317,7 @@ void ImageResource::AllClientsAndObserversRemoved() {
// after a conservative GC prevents resetAnimation() from upsetting ongoing
// animation updates (crbug.com/613709)
if (!ThreadHeap::WillObjectBeLazilySwept(this)) {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&ImageResourceContent::DoResetAnimation,
WrapWeakPersistent(GetContent())));
} else {
@@ -332,7 +337,7 @@ scoped_refptr<const SharedBuffer> ImageResource::ResourceBuffer() const {
void ImageResource::AppendData(const char* data, size_t length) {
v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(length);
if (multipart_parser_) {
- multipart_parser_->AppendData(data, length);
+ multipart_parser_->AppendData(data, SafeCast<wtf_size_t>(length));
} else {
Resource::AppendData(data, length);
@@ -480,7 +485,7 @@ void ImageResource::ResponseReceived(
DCHECK(!multipart_parser_);
// If there's no boundary, just handle the request normally.
if (response.IsMultipart() && !response.MultipartBoundary().IsEmpty()) {
- multipart_parser_ = new MultipartImageResourceParser(
+ multipart_parser_ = MakeGarbageCollected<MultipartImageResourceParser>(
response, response.MultipartBoundary(), this);
}
@@ -703,13 +708,13 @@ bool ImageResource::IsAccessAllowed(
ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin
does_current_frame_has_single_security_origin) const {
if (GetResponse().WasFetchedViaServiceWorker())
- return GetResponse().IsCORSSameOrigin();
+ return GetResponse().IsCorsSameOrigin();
if (does_current_frame_has_single_security_origin !=
ImageResourceInfo::kHasSingleSecurityOrigin)
return false;
- if (GetResponse().IsCORSSameOrigin())
+ if (GetResponse().IsCorsSameOrigin())
return true;
return security_origin->CanReadContent(GetResponse().Url());
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/image_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/image_resource.h
index 572ecac795e..f24eef1f2f0 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/image_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/image_resource.h
@@ -65,6 +65,10 @@ class CORE_EXPORT ImageResource final
static ImageResource* Create(const ResourceRequest&);
static ImageResource* CreateForTest(const KURL&);
+ ImageResource(const ResourceRequest&,
+ const ResourceLoaderOptions&,
+ ImageResourceContent*,
+ bool is_placeholder);
~ImageResource() override;
ImageResourceContent* GetContent();
@@ -120,11 +124,6 @@ class CORE_EXPORT ImageResource final
class ImageResourceInfoImpl;
class ImageResourceFactory;
- ImageResource(const ResourceRequest&,
- const ResourceLoaderOptions&,
- ImageResourceContent*,
- bool is_placeholder);
-
// Only for ImageResourceInfoImpl.
void DecodeError(bool all_data_received);
bool IsAccessAllowed(
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.cc b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.cc
index f3553d5979b..54714676cde 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.cc
@@ -77,7 +77,7 @@ int64_t EstimateOriginalImageSizeForPlaceholder(
if (response.HttpHeaderField("chrome-proxy-content-transform") ==
"empty-image") {
const String& str = response.HttpHeaderField("chrome-proxy");
- size_t index = str.Find("ofcl=");
+ wtf_size_t index = str.Find("ofcl=");
if (index != kNotFound) {
bool ok = false;
int bytes = str.Substring(index + (sizeof("ofcl=") - 1)).ToInt(&ok);
@@ -112,7 +112,8 @@ ImageResourceContent::ImageResourceContent(scoped_refptr<blink::Image> image)
ImageResourceContent* ImageResourceContent::CreateLoaded(
scoped_refptr<blink::Image> image) {
DCHECK(image);
- ImageResourceContent* content = new ImageResourceContent(std::move(image));
+ ImageResourceContent* content =
+ MakeGarbageCollected<ImageResourceContent>(std::move(image));
content->content_status_ = ResourceStatus::kCached;
return content;
}
@@ -292,10 +293,14 @@ void ImageResourceContent::NotifyObservers(
}
scoped_refptr<Image> ImageResourceContent::CreateImage(bool is_multipart) {
+ String content_dpr_value =
+ info_->GetResponse().HttpHeaderField(http_names::kContentDPR);
+ wtf_size_t comma = content_dpr_value.ReverseFind(',');
+ if (comma != kNotFound && comma < content_dpr_value.length() - 1) {
+ content_dpr_value = content_dpr_value.Substring(comma + 1);
+ }
device_pixel_ratio_header_value_ =
- info_->GetResponse()
- .HttpHeaderField(HTTPNames::Content_DPR)
- .ToFloat(&has_device_pixel_ratio_header_value_);
+ content_dpr_value.ToFloat(&has_device_pixel_ratio_header_value_);
if (!has_device_pixel_ratio_header_value_ ||
device_pixel_ratio_header_value_ <= 0.0) {
device_pixel_ratio_header_value_ = 1.0;
@@ -497,17 +502,18 @@ bool ImageResourceContent::IsAcceptableContentType() {
}
// Return true if the image content is well-compressed (and not full of
-// extraneous metadata). This is currently defined as no using more than 10 bits
-// per pixel of image data.
+// extraneous metadata). This is currently defined as no using more than 0.5
+// byte per pixel of image data with approximate header size(1KB) removed.
// TODO(crbug.com/838263): Support site-defined bit-per-pixel ratio through
// feature policy declarations.
bool ImageResourceContent::IsAcceptableCompressionRatio() {
uint64_t pixels = IntrinsicSize(kDoNotRespectImageOrientation).Area();
if (!pixels)
return true;
- long long resource_length = GetResponse().DecodedBodyLength();
+ DCHECK(image_);
+ double resource_length = GetResponse().ExpectedContentLength();
// Allow no more than 10 bits per compressed pixel
- return (double)resource_length / pixels <= 1.25;
+ return (resource_length - 1024) / pixels <= 0.5;
}
void ImageResourceContent::DecodedSizeChangedTo(const blink::Image* image,
@@ -537,12 +543,6 @@ bool ImageResourceContent::ShouldPauseAnimation(const blink::Image* image) {
return true;
}
-void ImageResourceContent::AnimationAdvanced(const blink::Image* image) {
- if (!image || image != image_)
- return;
- NotifyObservers(kDoNotNotifyFinish, CanDeferInvalidation::kYes);
-}
-
void ImageResourceContent::UpdateImageAnimationPolicy() {
if (!image_)
return;
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.h b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.h
index 0deab064089..a94b30ac7d6 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.h
@@ -49,7 +49,7 @@ class CORE_EXPORT ImageResourceContent final
// Used for loading.
// Returned content will be associated immediately later with ImageResource.
static ImageResourceContent* CreateNotStarted() {
- return new ImageResourceContent(nullptr);
+ return MakeGarbageCollected<ImageResourceContent>(nullptr);
}
// Creates ImageResourceContent from an already loaded image.
@@ -57,6 +57,8 @@ class CORE_EXPORT ImageResourceContent final
static ImageResourceContent* Fetch(FetchParameters&, ResourceFetcher*);
+ explicit ImageResourceContent(scoped_refptr<blink::Image> = nullptr);
+
// Returns the NullImage() if the image is not available yet.
blink::Image* GetImage() const;
bool HasImage() const { return image_.get(); }
@@ -183,12 +185,9 @@ class CORE_EXPORT ImageResourceContent final
private:
using CanDeferInvalidation = ImageResourceObserver::CanDeferInvalidation;
- explicit ImageResourceContent(scoped_refptr<blink::Image> = nullptr);
-
// ImageObserver
void DecodedSizeChangedTo(const blink::Image*, size_t new_size) override;
bool ShouldPauseAnimation(const blink::Image*) override;
- void AnimationAdvanced(const blink::Image*) override;
void Changed(const blink::Image*) override;
void AsyncLoadCompleted(const blink::Image*) override;
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_test.cc b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_test.cc
index d2b51d1fc32..ca251dbde27 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_test.cc
@@ -1412,7 +1412,7 @@ TEST(ImageResourceTest, FetchAllowPlaceholderPostRequest) {
KURL test_url(kTestURL);
ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
ResourceRequest resource_request(test_url);
- resource_request.SetHTTPMethod(HTTPNames::POST);
+ resource_request.SetHTTPMethod(http_names::kPOST);
FetchParameters params(resource_request);
params.SetAllowImagePlaceholder();
ImageResource* image_resource = ImageResource::Fetch(params, CreateFetcher());
@@ -1769,7 +1769,7 @@ TEST(ImageResourceTest,
const struct {
int status_code;
AtomicString content_range;
- size_t data_size;
+ uint32_t data_size;
} tests[] = {
{200, g_null_atom, sizeof(kBadImageData)},
{206, BuildContentRange(sizeof(kBadImageData), sizeof(kBadImageData)),
@@ -1851,7 +1851,7 @@ TEST(ImageResourceTest, PeriodicFlushTest) {
ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
platform;
- EmptyChromeClient* chrome_client = new EmptyChromeClient();
+ EmptyChromeClient* chrome_client = MakeGarbageCollected<EmptyChromeClient>();
Page::PageClients clients;
FillWithEmptyClients(clients);
clients.chrome_client = chrome_client;
@@ -1963,7 +1963,7 @@ TEST(ImageResourceTest, DeferredInvalidation) {
// Image animated.
static_cast<ImageObserver*>(image_resource->GetContent())
- ->AnimationAdvanced(image_resource->GetContent()->GetImage());
+ ->Changed(image_resource->GetContent()->GetImage());
EXPECT_EQ(obs->ImageChangedCount(), 3);
EXPECT_EQ(obs->Defer(), ImageResourceObserver::CanDeferInvalidation::kYes);
}
@@ -1993,7 +1993,7 @@ class ImageResourceCounterTest : public testing::Test {
// Mark it as coming from a UA stylesheet (if needed).
if (ua_resource) {
fetch_params.MutableOptions().initiator_info.name =
- FetchInitiatorTypeNames::uacss;
+ fetch_initiator_type_names::kUacss;
}
// Fetch the ImageResource.
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/link_fetch_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/link_fetch_resource.h
index c126818f4bd..0b190ff4b6b 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/link_fetch_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/link_fetch_resource.h
@@ -16,6 +16,10 @@ class ResourceFetcher;
class LinkFetchResource final : public Resource {
public:
static Resource* Fetch(ResourceType, FetchParameters&, ResourceFetcher*);
+
+ LinkFetchResource(const ResourceRequest&,
+ ResourceType,
+ const ResourceLoaderOptions&);
~LinkFetchResource() override;
private:
@@ -26,12 +30,10 @@ class LinkFetchResource final : public Resource {
Resource* Create(const ResourceRequest& request,
const ResourceLoaderOptions& options) const override {
- return new LinkFetchResource(request, GetType(), options);
+ return MakeGarbageCollected<LinkFetchResource>(request, GetType(),
+ options);
}
};
- LinkFetchResource(const ResourceRequest&,
- ResourceType,
- const ResourceLoaderOptions&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.cc b/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.cc
index 986a3aff30e..0b032bc99b3 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.cc
@@ -23,7 +23,8 @@ MultipartImageResourceParser::MultipartImageResourceParser(
boundary_.push_front("--", 2);
}
-void MultipartImageResourceParser::AppendData(const char* bytes, size_t size) {
+void MultipartImageResourceParser::AppendData(const char* bytes,
+ wtf_size_t size) {
DCHECK(!IsCancelled());
// m_sawLastBoundary means that we've already received the final boundary
// token. The server should stop sending us data at this point, but if it
@@ -34,7 +35,7 @@ void MultipartImageResourceParser::AppendData(const char* bytes, size_t size) {
if (is_parsing_top_) {
// Eat leading \r\n
- size_t pos = SkippableLength(data_, 0);
+ wtf_size_t pos = SkippableLength(data_, 0);
// +2 for "--"
if (data_.size() < boundary_.size() + 2 + pos) {
// We don't have enough data yet to make a boundary token. Just wait
@@ -65,11 +66,11 @@ void MultipartImageResourceParser::AppendData(const char* bytes, size_t size) {
return;
}
- size_t boundary_position;
+ wtf_size_t boundary_position;
while ((boundary_position = FindBoundary(data_, &boundary_)) != kNotFound) {
// Strip out trailing \r\n characters in the buffer preceding the boundary
// on the same lines as does Firefox.
- size_t data_size = boundary_position;
+ wtf_size_t data_size = boundary_position;
if (boundary_position > 0 && data_[boundary_position - 1] == '\n') {
data_size--;
if (boundary_position > 1 && data_[boundary_position - 2] == '\r') {
@@ -81,7 +82,7 @@ void MultipartImageResourceParser::AppendData(const char* bytes, size_t size) {
if (IsCancelled())
return;
}
- size_t boundary_end_position = boundary_position + boundary_.size();
+ wtf_size_t boundary_end_position = boundary_position + boundary_.size();
if (boundary_end_position < data_.size() &&
'-' == data_[boundary_end_position]) {
// This was the last boundary so we can stop processing.
@@ -106,7 +107,7 @@ void MultipartImageResourceParser::AppendData(const char* bytes, size_t size) {
// buffered to handle a boundary that may have been truncated. "+2" for CRLF,
// as we may ignore the last CRLF.
if (!is_parsing_headers_ && data_.size() > boundary_.size() + 2) {
- size_t send_length = data_.size() - boundary_.size() - 2;
+ wtf_size_t send_length = data_.size() - boundary_.size() - 2;
client_->MultipartDataReceived(data_.data(), send_length);
data_.EraseAt(0, send_length);
}
@@ -124,8 +125,9 @@ void MultipartImageResourceParser::Finish() {
saw_last_boundary_ = true;
}
-size_t MultipartImageResourceParser::SkippableLength(const Vector<char>& data,
- size_t pos) {
+wtf_size_t MultipartImageResourceParser::SkippableLength(
+ const Vector<char>& data,
+ wtf_size_t pos) {
if (data.size() >= pos + 2 && data[pos] == '\r' && data[pos + 1] == '\n')
return 2;
if (data.size() >= pos + 1 && data[pos] == '\n')
@@ -135,7 +137,7 @@ size_t MultipartImageResourceParser::SkippableLength(const Vector<char>& data,
bool MultipartImageResourceParser::ParseHeaders() {
// Eat leading \r\n
- size_t pos = SkippableLength(data_, 0);
+ wtf_size_t pos = SkippableLength(data_, 0);
// Create a ResourceResponse based on the original set of headers + the
// replacement headers. We only replace the same few headers that gecko does.
@@ -147,7 +149,7 @@ bool MultipartImageResourceParser::ParseHeaders() {
for (const auto& header : original_response_.HttpHeaderFields())
response.AddHTTPHeaderField(header.key, header.value);
- size_t end = 0;
+ wtf_size_t end = 0;
if (!ParseMultipartHeadersFromBody(data_.data() + pos, data_.size() - pos,
&response, &end))
return false;
@@ -159,14 +161,14 @@ bool MultipartImageResourceParser::ParseHeaders() {
// Boundaries are supposed to be preceeded with --, but it looks like gecko
// doesn't require the dashes to exist. See nsMultiMixedConv::FindToken.
-size_t MultipartImageResourceParser::FindBoundary(const Vector<char>& data,
- Vector<char>* boundary) {
+wtf_size_t MultipartImageResourceParser::FindBoundary(const Vector<char>& data,
+ Vector<char>* boundary) {
auto* it = std::search(data.data(), data.data() + data.size(),
boundary->data(), boundary->data() + boundary->size());
if (it == data.data() + data.size())
return kNotFound;
- size_t boundary_position = it - data.data();
+ wtf_size_t boundary_position = static_cast<wtf_size_t>(it - data.data());
// Back up over -- for backwards compat
// TODO(tc): Don't we only want to do this once? Gecko code doesn't seem to
// care.
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h b/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h
index 2452ac4ee5a..cfa2351b748 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h
@@ -64,26 +64,28 @@ class CORE_EXPORT MultipartImageResourceParser final
MultipartImageResourceParser(const ResourceResponse&,
const Vector<char>& boundary,
Client*);
- void AppendData(const char* bytes, size_t);
+ void AppendData(const char* bytes, wtf_size_t);
void Finish();
void Cancel() { is_cancelled_ = true; }
void Trace(blink::Visitor*);
- static size_t SkippableLengthForTest(const Vector<char>& data, size_t size) {
+ static wtf_size_t SkippableLengthForTest(const Vector<char>& data,
+ wtf_size_t size) {
return SkippableLength(data, size);
}
- static size_t FindBoundaryForTest(const Vector<char>& data,
- Vector<char>* boundary) {
+ static wtf_size_t FindBoundaryForTest(const Vector<char>& data,
+ Vector<char>* boundary) {
return FindBoundary(data, boundary);
}
private:
bool ParseHeaders();
bool IsCancelled() const { return is_cancelled_; }
- static size_t SkippableLength(const Vector<char>&, size_t);
+ static wtf_size_t SkippableLength(const Vector<char>&, wtf_size_t);
// This function updates |*boundary|.
- static size_t FindBoundary(const Vector<char>& data, Vector<char>* boundary);
+ static wtf_size_t FindBoundary(const Vector<char>& data,
+ Vector<char>* boundary);
const ResourceResponse original_response_;
Vector<char> boundary_;
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc b/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc
index f3b1ae57a60..599e76ae864 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser_test.cc
@@ -4,13 +4,14 @@
#include "third_party/blink/renderer/core/loader/resource/multipart_image_resource_parser.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
-
#include <stddef.h>
#include <stdint.h>
#include <string.h>
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
+
namespace blink {
namespace multipart_image_resource_parser_test {
@@ -30,7 +31,7 @@ class MockClient final : public GarbageCollectedFinalized<MockClient>,
data_.push_back(Vector<char>());
}
void MultipartDataReceived(const char* bytes, size_t size) override {
- data_.back().Append(bytes, size);
+ data_.back().Append(bytes, SafeCast<wtf_size_t>(size));
}
Vector<ResourceResponse> responses_;
@@ -40,8 +41,8 @@ class MockClient final : public GarbageCollectedFinalized<MockClient>,
TEST(MultipartResponseTest, SkippableLength) {
struct {
const char* input;
- const size_t position;
- const size_t expected;
+ const wtf_size_t position;
+ const wtf_size_t expected;
} line_tests[] = {
{"Line", 0, 0}, {"Line", 2, 0}, {"Line", 10, 0},
{"\r\nLine", 0, 2}, {"\nLine", 0, 1}, {"\n\nLine", 0, 1},
@@ -50,7 +51,8 @@ TEST(MultipartResponseTest, SkippableLength) {
};
for (size_t i = 0; i < arraysize(line_tests); ++i) {
Vector<char> input;
- input.Append(line_tests[i].input, strlen(line_tests[i].input));
+ input.Append(line_tests[i].input,
+ static_cast<wtf_size_t>(strlen(line_tests[i].input)));
EXPECT_EQ(line_tests[i].expected,
MultipartImageResourceParser::SkippableLengthForTest(
input, line_tests[i].position));
@@ -71,8 +73,9 @@ TEST(MultipartResponseTest, FindBoundary) {
for (size_t i = 0; i < arraysize(boundary_tests); ++i) {
Vector<char> boundary, data;
boundary.Append(boundary_tests[i].boundary,
- strlen(boundary_tests[i].boundary));
- data.Append(boundary_tests[i].data, strlen(boundary_tests[i].data));
+ static_cast<uint32_t>(strlen(boundary_tests[i].boundary)));
+ data.Append(boundary_tests[i].data,
+ static_cast<uint32_t>(strlen(boundary_tests[i].data)));
EXPECT_EQ(
boundary_tests[i].position,
MultipartImageResourceParser::FindBoundaryForTest(data, &boundary));
@@ -84,12 +87,13 @@ TEST(MultipartResponseTest, NoStartBoundary) {
response.SetMimeType("multipart/x-mixed-replace");
response.SetHTTPHeaderField("Foo", "Bar");
response.SetHTTPHeaderField("Content-type", "text/plain");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
const char kData[] =
"Content-type: text/plain\n\n"
"This is a sample response\n"
@@ -111,12 +115,13 @@ TEST(MultipartResponseTest, NoEndBoundary) {
response.SetMimeType("multipart/x-mixed-replace");
response.SetHTTPHeaderField("Foo", "Bar");
response.SetHTTPHeaderField("Content-type", "text/plain");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
const char kData[] =
"bound\nContent-type: text/plain\n\n"
"This is a sample response\n";
@@ -136,12 +141,13 @@ TEST(MultipartResponseTest, NoStartAndEndBoundary) {
response.SetMimeType("multipart/x-mixed-replace");
response.SetHTTPHeaderField("Foo", "Bar");
response.SetHTTPHeaderField("Content-type", "text/plain");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
const char kData[] =
"Content-type: text/plain\n\n"
"This is a sample response\n";
@@ -162,12 +168,13 @@ TEST(MultipartResponseTest, MalformedBoundary) {
response.SetMimeType("multipart/x-mixed-replace");
response.SetHTTPHeaderField("Foo", "Bar");
response.SetHTTPHeaderField("Content-type", "text/plain");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("--bound", 7);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
const char kData[] =
"--bound\n"
"Content-type: text/plain\n\n"
@@ -209,12 +216,13 @@ void VariousChunkSizesTest(const TestChunk chunks[],
ResourceResponse response(NullURL());
response.SetMimeType("multipart/x-mixed-replace");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
for (int i = 0; i < chunks_size; ++i) {
ASSERT_LT(chunks[i].start_position, chunks[i].end_position);
@@ -313,12 +321,13 @@ TEST(MultipartResponseTest, SmallChunk) {
ResourceResponse response(NullURL());
response.SetMimeType("multipart/x-mixed-replace");
response.SetHTTPHeaderField("Content-type", "text/plain");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
// Test chunks of size 1, 2, and 0.
const char kData[] =
@@ -348,12 +357,13 @@ TEST(MultipartResponseTest, MultipleBoundaries) {
// Test multiple boundaries back to back
ResourceResponse response(NullURL());
response.SetMimeType("multipart/x-mixed-replace");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
const char kData[] = "--bound\r\n\r\n--bound\r\n\r\nfoofoo--bound--";
parser->AppendData(kData, strlen(kData));
@@ -366,7 +376,7 @@ TEST(MultipartResponseTest, MultipleBoundaries) {
TEST(MultipartResponseTest, EatLeadingLF) {
ResourceResponse response(NullURL());
response.SetMimeType("multipart/x-mixed-replace");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
@@ -375,7 +385,8 @@ TEST(MultipartResponseTest, EatLeadingLF) {
"\n\n\n--bound\n\ncontent-type: 2\n\n"
"\n\n\n--bound\ncontent-type: 3\n\n";
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
for (size_t i = 0; i < strlen(kData); ++i)
parser->AppendData(&kData[i], 1);
@@ -396,7 +407,7 @@ TEST(MultipartResponseTest, EatLeadingLF) {
TEST(MultipartResponseTest, EatLeadingCRLF) {
ResourceResponse response(NullURL());
response.SetMimeType("multipart/x-mixed-replace");
- MockClient* client = new MockClient;
+ MockClient* client = MakeGarbageCollected<MockClient>();
Vector<char> boundary;
boundary.Append("bound", 5);
@@ -405,7 +416,8 @@ TEST(MultipartResponseTest, EatLeadingCRLF) {
"\r\n\r\n\r\n--bound\r\n\r\ncontent-type: 2\r\n\r\n"
"\r\n\r\n\r\n--bound\r\ncontent-type: 3\r\n\r\n";
MultipartImageResourceParser* parser =
- new MultipartImageResourceParser(response, boundary, client);
+ MakeGarbageCollected<MultipartImageResourceParser>(response, boundary,
+ client);
for (size_t i = 0; i < strlen(kData); ++i)
parser->AppendData(&kData[i], 1);
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/script_resource.cc b/chromium/third_party/blink/renderer/core/loader/resource/script_resource.cc
index 3662eb4ca32..c9b8aa9ad69 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/script_resource.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/script_resource.cc
@@ -42,6 +42,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/text_resource_decoder_options.h"
#include "third_party/blink/renderer/platform/loader/subresource_integrity.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
namespace blink {
@@ -71,13 +72,38 @@ bool IsRequestContextSupported(mojom::RequestContextType request_context) {
ScriptResource* ScriptResource::Fetch(FetchParameters& params,
ResourceFetcher* fetcher,
- ResourceClient* client) {
+ ResourceClient* client,
+ StreamingAllowed streaming_allowed) {
DCHECK_EQ(params.GetResourceRequest().GetFrameType(),
network::mojom::RequestContextFrameType::kNone);
DCHECK(IsRequestContextSupported(
params.GetResourceRequest().GetRequestContext()));
- return ToScriptResource(
+ ScriptResource* resource = ToScriptResource(
fetcher->RequestResource(params, ScriptResourceFactory(), client));
+
+ if (streaming_allowed == kAllowStreaming) {
+ // Start streaming the script as soon as we get it.
+ if (RuntimeEnabledFeatures::ScriptStreamingOnPreloadEnabled()) {
+ resource->StartStreaming(fetcher->Context().GetLoadingTaskRunner());
+ }
+ } else {
+ // Advance the |streaming_state_| to kStreamingNotAllowed by calling
+ // SetClientIsWaitingForFinished unless it is explicitly allowed.'
+ //
+ // Do this in a task rather than directly to make sure that we don't call
+ // the finished callbacks of other clients synchronously.
+
+ // TODO(leszeks): Previous behaviour, without script streaming, was to
+ // synchronously notify the given client, with the assumption that other
+ // clients were already finished. If this behaviour becomes necessary, we
+ // would have to either check that streaming wasn't started (if that would
+ // be a logic error), or cancel any existing streaming.
+ fetcher->Context().GetLoadingTaskRunner()->PostTask(
+ FROM_HERE, WTF::Bind(&ScriptResource::SetClientIsWaitingForFinished,
+ WrapWeakPersistent(resource)));
+ }
+
+ return resource;
}
ScriptResource::ScriptResource(
@@ -91,6 +117,11 @@ ScriptResource::ScriptResource(
ScriptResource::~ScriptResource() = default;
+void ScriptResource::Trace(blink::Visitor* visitor) {
+ visitor->Trace(streamer_);
+ TextResource::Trace(visitor);
+}
+
void ScriptResource::OnMemoryDump(WebMemoryDumpLevelOfDetail level_of_detail,
WebProcessMemoryDump* memory_dump) const {
Resource::OnMemoryDump(level_of_detail, memory_dump);
@@ -102,7 +133,7 @@ void ScriptResource::OnMemoryDump(WebMemoryDumpLevelOfDetail level_of_detail,
}
const ParkableString& ScriptResource::SourceText() {
- DCHECK(IsLoaded());
+ CHECK(IsFinishedInternal());
if (source_text_.IsNull() && Data()) {
String source_text = DecodedText();
@@ -114,13 +145,52 @@ const ParkableString& ScriptResource::SourceText() {
return source_text_;
}
+String ScriptResource::TextForInspector() const {
+ // If the resource buffer exists, we can safely return the decoded text.
+ if (ResourceBuffer())
+ return DecodedText();
+
+ // If there is no resource buffer, then we have three cases.
+ // TODO(crbug.com/865098): Simplify the below code and remove the CHECKs once
+ // the assumptions are confirmed.
+
+ if (IsLoaded()) {
+ if (!source_text_.IsNull()) {
+ // 1. We have finished loading, and have already decoded the buffer into
+ // the source text and cleared the resource buffer to save space.
+ return source_text_.ToString();
+ }
+
+ // 2. We have finished loading with no data received, so no streaming ever
+ // happened or streaming was suppressed. Note that the finished
+ // notification may not have come through yet because of task posting, so
+ // NotifyFinished may not have been called yet. Regardless, there was no
+ // data, so the text should be empty.
+ //
+ // TODO(crbug/909858) Currently this CHECK can occasionally fail, but this
+ // doesn't seem to cause real issues immediately. For now, we suppress the
+ // crashes on release builds by making this a DCHECK and continue baking the
+ // script streamer control (crbug/865098) on beta, while investigating the
+ // failure reason on canary.
+ DCHECK(!IsFinishedInternal() || !streamer_ ||
+ streamer_->StreamingSuppressedReason() ==
+ ScriptStreamer::kScriptTooSmall);
+ return "";
+ }
+
+ // 3. We haven't started loading, and actually haven't received any data yet
+ // at all to initialise the resource buffer, so the resource is empty.
+ return "";
+}
+
SingleCachedMetadataHandler* ScriptResource::CacheHandler() {
return static_cast<SingleCachedMetadataHandler*>(Resource::CacheHandler());
}
CachedMetadataHandler* ScriptResource::CreateCachedMetadataHandler(
std::unique_ptr<CachedMetadataSender> send_callback) {
- return new ScriptCachedMetadataHandler(Encoding(), std::move(send_callback));
+ return MakeGarbageCollected<ScriptCachedMetadataHandler>(
+ Encoding(), std::move(send_callback));
}
void ScriptResource::SetSerializedCachedMetadata(const char* data,
@@ -135,13 +205,25 @@ void ScriptResource::SetSerializedCachedMetadata(const char* data,
void ScriptResource::DestroyDecodedDataForFailedRevalidation() {
source_text_ = ParkableString();
+ // Make sure there's no streaming.
+ DCHECK(!streamer_);
+ DCHECK_EQ(streaming_state_, StreamingState::kStreamingNotAllowed);
SetDecodedSize(0);
}
-AccessControlStatus ScriptResource::CalculateAccessControlStatus() const {
- DCHECK_NE(GetResponse().GetType(), network::mojom::FetchResponseType::kError);
- return GetResponse().IsCORSSameOrigin() ? kSharableCrossOrigin
- : kOpaqueResource;
+void ScriptResource::SetRevalidatingRequest(const ResourceRequest& request) {
+ CHECK_EQ(streaming_state_, StreamingState::kFinishedNotificationSent);
+ if (streamer_) {
+ CHECK(streamer_->IsStreamingFinished());
+ streamer_ = nullptr;
+ }
+ // Revalidation requests don't actually load the current Resource, so disable
+ // streaming.
+ not_streaming_reason_ = ScriptStreamer::kRevalidate;
+ streaming_state_ = StreamingState::kStreamingNotAllowed;
+ CheckStreamingState();
+
+ TextResource::SetRevalidatingRequest(request);
}
bool ScriptResource::CanUseCacheValidator() const {
@@ -151,7 +233,197 @@ bool ScriptResource::CanUseCacheValidator() const {
if (HasClientsOrObservers())
return false;
+ // Do not revalidate until streaming is complete.
+ if (!IsFinishedInternal())
+ return false;
+
return Resource::CanUseCacheValidator();
}
+void ScriptResource::NotifyDataReceived(const char* data, size_t size) {
+ CheckStreamingState();
+ if (streamer_) {
+ DCHECK_EQ(streaming_state_, StreamingState::kStreaming);
+ streamer_->NotifyAppendData();
+ }
+ TextResource::NotifyDataReceived(data, size);
+}
+
+void ScriptResource::NotifyFinished() {
+ DCHECK(IsLoaded());
+ switch (streaming_state_) {
+ case StreamingState::kCanStartStreaming:
+ // Do nothing, expect either a StartStreaming() call to transition us to
+ // kStreaming, or an SetClientIsWaitingForFinished() call to transition us
+ // into kStreamingNotAllowed. These will then transition again since
+ // IsLoaded will be true.
+ break;
+ case StreamingState::kStreaming:
+ AdvanceStreamingState(StreamingState::kWaitingForStreamingToEnd);
+ DCHECK(streamer_);
+ streamer_->NotifyFinished();
+ // Don't call the base NotifyFinished until streaming finishes too (which
+ // might happen immediately in the above ScriptStreamer::NotifyFinished
+ // call)
+ break;
+ case StreamingState::kStreamingNotAllowed:
+ AdvanceStreamingState(StreamingState::kFinishedNotificationSent);
+ TextResource::NotifyFinished();
+ break;
+ case StreamingState::kWaitingForStreamingToEnd:
+ case StreamingState::kFinishedNotificationSent:
+ // Not possible.
+ CHECK(false);
+ break;
+ }
+}
+
+bool ScriptResource::IsFinishedInternal() const {
+ CheckStreamingState();
+ return streaming_state_ == StreamingState::kFinishedNotificationSent;
+}
+
+void ScriptResource::StreamingFinished() {
+ CHECK(streamer_);
+ CHECK_EQ(streaming_state_, StreamingState::kWaitingForStreamingToEnd);
+ AdvanceStreamingState(StreamingState::kFinishedNotificationSent);
+ TextResource::NotifyFinished();
+}
+
+bool ScriptResource::StartStreaming(
+ scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner) {
+ CheckStreamingState();
+
+ if (streamer_) {
+ return !streamer_->IsStreamingFinished();
+ }
+
+ if (streaming_state_ != StreamingState::kCanStartStreaming) {
+ return false;
+ }
+
+ // Don't bother streaming if there was an error, it won't work anyway.
+ if (ErrorOccurred()) {
+ return false;
+ }
+
+ CHECK(!IsCacheValidator());
+
+ streamer_ =
+ ScriptStreamer::Create(this, loading_task_runner, &not_streaming_reason_);
+ if (streamer_) {
+ AdvanceStreamingState(StreamingState::kStreaming);
+
+ // If there is any data already, send it to the streamer.
+ if (Data()) {
+ // Note that we don't need to iterate through the segments of the data, as
+ // the streamer will do that itself.
+ CHECK_GT(Data()->size(), 0u);
+ streamer_->NotifyAppendData();
+ }
+ // If the we're is already loaded, notify the streamer about that too.
+ if (IsLoaded()) {
+ AdvanceStreamingState(StreamingState::kWaitingForStreamingToEnd);
+
+ // Do this in a task rather than directly to make sure that we don't call
+ // the finished callback in the same stack as starting streaming -- this
+ // can cause issues with the client expecting to be not finished when
+ // starting streaming (e.g. ClassicPendingScript::IsReady == false), but
+ // ending up finished by the end of this method.
+ loading_task_runner->PostTask(FROM_HERE,
+ WTF::Bind(&ScriptStreamer::NotifyFinished,
+ WrapPersistent(streamer_.Get())));
+ }
+ }
+
+ CheckStreamingState();
+ return streamer_ && !streamer_->IsStreamingFinished();
+}
+
+void ScriptResource::SetClientIsWaitingForFinished() {
+ // No-op if streaming already started or finished.
+ CheckStreamingState();
+ if (streaming_state_ != StreamingState::kCanStartStreaming)
+ return;
+
+ AdvanceStreamingState(StreamingState::kStreamingNotAllowed);
+ not_streaming_reason_ = ScriptStreamer::kStreamingDisabled;
+ // Trigger the finished notification if needed.
+ if (IsLoaded()) {
+ AdvanceStreamingState(StreamingState::kFinishedNotificationSent);
+ TextResource::NotifyFinished();
+ }
+}
+
+ScriptStreamer* ScriptResource::TakeStreamer() {
+ CHECK(IsFinishedInternal());
+ if (!streamer_)
+ return nullptr;
+
+ ScriptStreamer* streamer = streamer_;
+ streamer_ = nullptr;
+ not_streaming_reason_ = ScriptStreamer::kSecondScriptResourceUse;
+ return streamer;
+}
+
+void ScriptResource::AdvanceStreamingState(StreamingState new_state) {
+ switch (streaming_state_) {
+ case StreamingState::kCanStartStreaming:
+ CHECK(new_state == StreamingState::kStreaming ||
+ new_state == StreamingState::kStreamingNotAllowed);
+ break;
+ case StreamingState::kStreaming:
+ CHECK(streamer_);
+ CHECK_EQ(new_state, StreamingState::kWaitingForStreamingToEnd);
+ break;
+ case StreamingState::kWaitingForStreamingToEnd:
+ CHECK(streamer_);
+ CHECK_EQ(new_state, StreamingState::kFinishedNotificationSent);
+ break;
+ case StreamingState::kStreamingNotAllowed:
+ CHECK_EQ(new_state, StreamingState::kFinishedNotificationSent);
+ break;
+ case StreamingState::kFinishedNotificationSent:
+ CHECK(false);
+ break;
+ }
+
+ streaming_state_ = new_state;
+ CheckStreamingState();
+}
+
+void ScriptResource::CheckStreamingState() const {
+ // TODO(leszeks): Eventually convert these CHECKs into DCHECKs once the logic
+ // is a bit more baked in.
+ switch (streaming_state_) {
+ case StreamingState::kCanStartStreaming:
+ CHECK(!streamer_);
+ break;
+ case StreamingState::kStreaming:
+ CHECK(streamer_);
+ CHECK(!streamer_->IsFinished());
+ // kStreaming can be entered both when loading (if streaming is started
+ // before load completes) or when loaded (if streaming is started after
+ // load completes). In the latter case, the state will almost immediately
+ // advance to kWaitingForStreamingToEnd.
+ CHECK(IsLoaded() || IsLoading());
+ break;
+ case StreamingState::kWaitingForStreamingToEnd:
+ CHECK(streamer_);
+ CHECK(!streamer_->IsFinished());
+ CHECK(IsLoaded());
+ break;
+ case StreamingState::kStreamingNotAllowed:
+ CHECK(!streamer_);
+ // TODO(leszeks): We could CHECK(!IsLoaded()) if not for the immediate
+ // kCanStartStreaming -> kStreamingNotAllowed -> kFinishedNotificationSent
+ // transition in SetClientIsWaitingForFinished when IsLoaded.
+ break;
+ case StreamingState::kFinishedNotificationSent:
+ CHECK(!streamer_ || streamer_->IsFinished());
+ CHECK(IsLoaded());
+ break;
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/script_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/script_resource.h
index 0c4d7eff2f7..6c4759b0aa4 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/script_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/script_resource.h
@@ -28,10 +28,10 @@
#include <memory>
+#include "third_party/blink/renderer/bindings/core/v8/script_streamer.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/loader/resource/text_resource.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
@@ -43,11 +43,34 @@ class FetchParameters;
class KURL;
class ResourceFetcher;
+// ScriptResource is a resource representing a JavaScript script. It is only
+// used for "classic" scripts, i.e. not modules.
+//
+// In addition to loading the script, a ScriptResource can optionally stream the
+// script to the JavaScript parser/compiler, using a ScriptStreamer. In this
+// case, clients of the ScriptResource will not receive the finished
+// notification until the streaming completes.
+//
+// See also:
+// https://docs.google.com/document/d/143GOPl_XVgLPFfO-31b_MdBcnjklLEX2OIg_6eN6fQ4
class CORE_EXPORT ScriptResource final : public TextResource {
public:
+ // For scripts fetched with kAllowStreaming, the ScriptResource expects users
+ // to call StartStreaming to start streaming the loaded data, and
+ // SetClientIsWaitingForFinished when they actually want the data to be
+ // available for execute. Note that StartStreaming can fail, so the client of
+ // an unfinished resource has to call SetClientIsWaitingForFinished to
+ // guarantee that it receives a finished callback.
+ //
+ // Scripts fetched with kNoStreaming will (asynchronously) call
+ // SetClientIsWaitingForFinished on the resource, so the user does not have to
+ // call it again. This is effectively the "legacy" behaviour.
+ enum StreamingAllowed { kNoStreaming, kAllowStreaming };
+
static ScriptResource* Fetch(FetchParameters&,
ResourceFetcher*,
- ResourceClient*);
+ ResourceClient*,
+ StreamingAllowed);
// Public for testing
static ScriptResource* CreateForTest(const KURL& url,
@@ -58,29 +81,107 @@ class CORE_EXPORT ScriptResource final : public TextResource {
ResourceLoaderOptions options;
TextResourceDecoderOptions decoder_options(
TextResourceDecoderOptions::kPlainTextContent, encoding);
- return new ScriptResource(request, options, decoder_options);
+ return MakeGarbageCollected<ScriptResource>(request, options,
+ decoder_options);
}
+ ScriptResource(const ResourceRequest&,
+ const ResourceLoaderOptions&,
+ const TextResourceDecoderOptions&);
~ScriptResource() override;
+ void Trace(blink::Visitor*) override;
+
void OnMemoryDump(WebMemoryDumpLevelOfDetail,
WebProcessMemoryDump*) const override;
- void DestroyDecodedDataForFailedRevalidation() override;
-
void SetSerializedCachedMetadata(const char*, size_t) override;
+ // Returns true if streaming was successfully started (or if an active
+ // streamer is already running)
+ //
+ // TODO(leszeks): This value is only used for work stealing, so make this
+ // function return void if work stealing is removed.
+ bool StartStreaming(
+ scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner);
+
+ // State that a client of the script resource will no longer try to start
+ // streaming, and is now waiting for the resource to call the client's finish
+ // callback (regardless of whether the resource is finished loading or
+ // finished streaming). Specifically, it causes the kCanStartStreaming to
+ // kStreamingNotAllowed transition. Streaming cannot be started after this is
+ // called.
+ //
+ // If the resource is already streaming, this will be a no-op, and the client
+ // will still only get the finished notification when the streaming completes.
+ //
+ // This function should never be called synchronously (except by
+ // NotifyFinished) as it can trigger all clients' finished callbacks, which in
+ // turn can invoke JavaScript execution.
+ //
+ // TODO(leszeks): Eventually Fetch (with streaming allowed) will be the only
+ // way of starting streaming, and SetClientIsWaitingForFinished will not be
+ // part of the public interface.
+ void SetClientIsWaitingForFinished();
+
+ // Called (only) by ScriptStreamer when streaming completes.
+ //
+ // This function should never be called synchronously as it can trigger all
+ // clients' finished callbacks, which in turn can invoke JavaScript execution.
+ void StreamingFinished();
+
const ParkableString& SourceText();
- AccessControlStatus CalculateAccessControlStatus() const;
+ // Get the resource's current text. This can return partial data, so should
+ // not be used outside of the inspector.
+ String TextForInspector() const;
SingleCachedMetadataHandler* CacheHandler();
+ // Gets the script streamer from the ScriptResource, clearing the resource's
+ // streamer so that it cannot be used twice.
+ ScriptStreamer* TakeStreamer();
+
+ ScriptStreamer::NotStreamingReason NoStreamerReason() const {
+ return not_streaming_reason_;
+ }
+
+ // Used in DCHECKs
+ bool HasStreamer() { return !!streamer_; }
+ bool HasFinishedStreamer() { return streamer_ && streamer_->IsFinished(); }
+
+ // Visible for tests.
+ void SetRevalidatingRequest(const ResourceRequest&) override;
+
protected:
CachedMetadataHandler* CreateCachedMetadataHandler(
std::unique_ptr<CachedMetadataSender> send_callback) override;
+ void DestroyDecodedDataForFailedRevalidation() override;
+
+ void NotifyDataReceived(const char* data, size_t size) override;
+
+ // ScriptResources are considered finished when either:
+ // 1. Loading + streaming completes, or
+ // 2. Loading completes + streaming was never started + someone called
+ // "SetClientIsWaitingForFinished" to block streaming from ever starting.
+ void NotifyFinished() override;
+ bool IsFinishedInternal() const override;
+
private:
+ // Valid state transitions:
+ //
+ // kCanStartStreaming -> kStreaming -> kWaitingForStreamingToEnd
+ // -> kFinishedNotificationSent
+ // kCanStartStreaming -> kStreamingNotAllowed -> kFinishedNotificationSent
+ enum class StreamingState {
+ kCanStartStreaming, // Streaming can be started.
+ kStreamingNotAllowed, // Streaming can no longer be started.
+ kStreaming, // Both loading the resource and streaming.
+ kWaitingForStreamingToEnd, // Resource loaded but streaming not complete.
+ kFinishedNotificationSent // Everything complete and finish sent.
+ };
+
class ScriptResourceFactory : public ResourceFactory {
public:
ScriptResourceFactory()
@@ -91,17 +192,23 @@ class CORE_EXPORT ScriptResource final : public TextResource {
const ResourceRequest& request,
const ResourceLoaderOptions& options,
const TextResourceDecoderOptions& decoder_options) const override {
- return new ScriptResource(request, options, decoder_options);
+ return MakeGarbageCollected<ScriptResource>(request, options,
+ decoder_options);
}
};
- ScriptResource(const ResourceRequest&,
- const ResourceLoaderOptions&,
- const TextResourceDecoderOptions&);
-
bool CanUseCacheValidator() const override;
+ void AdvanceStreamingState(StreamingState new_state);
+
+ // Check that invariants for the state hold.
+ void CheckStreamingState() const;
+
ParkableString source_text_;
+ Member<ScriptStreamer> streamer_;
+ ScriptStreamer::NotStreamingReason not_streaming_reason_ =
+ ScriptStreamer::kDidntTryToStartStreaming;
+ StreamingState streaming_state_ = StreamingState::kCanStartStreaming;
};
DEFINE_RESOURCE_TYPE_CASTS(Script);
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.h b/chromium/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.h
index c8ecf3d2e30..21c00df68c0 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.h
@@ -42,6 +42,10 @@ class XSLStyleSheetResource final : public TextResource {
ResourceFetcher*,
ResourceClient*);
+ XSLStyleSheetResource(const ResourceRequest&,
+ const ResourceLoaderOptions&,
+ const TextResourceDecoderOptions&);
+
const String& Sheet() const { return sheet_; }
private:
@@ -55,12 +59,10 @@ class XSLStyleSheetResource final : public TextResource {
const ResourceRequest& request,
const ResourceLoaderOptions& options,
const TextResourceDecoderOptions& decoder_options) const override {
- return new XSLStyleSheetResource(request, options, decoder_options);
+ return MakeGarbageCollected<XSLStyleSheetResource>(request, options,
+ decoder_options);
}
};
- XSLStyleSheetResource(const ResourceRequest&,
- const ResourceLoaderOptions&,
- const TextResourceDecoderOptions&);
void NotifyFinished() override;
diff --git a/chromium/third_party/blink/renderer/core/loader/subresource_filter.cc b/chromium/third_party/blink/renderer/core/loader/subresource_filter.cc
index b290e634ba6..1c7168a5ea3 100644
--- a/chromium/third_party/blink/renderer/core/loader/subresource_filter.cc
+++ b/chromium/third_party/blink/renderer/core/loader/subresource_filter.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -37,7 +38,8 @@ String GetErrorStringForDisallowedLoad(const KURL& url) {
SubresourceFilter* SubresourceFilter::Create(
ExecutionContext& execution_context,
std::unique_ptr<WebDocumentSubresourceFilter> filter) {
- return new SubresourceFilter(&execution_context, std::move(filter));
+ return MakeGarbageCollected<SubresourceFilter>(&execution_context,
+ std::move(filter));
}
SubresourceFilter::SubresourceFilter(
@@ -50,7 +52,7 @@ SubresourceFilter::SubresourceFilter(
// associated with an ad subframe.
if (auto* document = DynamicTo<Document>(execution_context_.Get())) {
auto* loader = document->Loader();
- if (subresource_filter_->GetIsAssociatedWithAdSubframe()) {
+ if (document->GetFrame()->IsAdSubframe()) {
ReportAdRequestId(loader->GetResponse().RequestId());
}
}
@@ -96,9 +98,6 @@ bool SubresourceFilter::AllowWebSocketConnection(const KURL& url) {
bool SubresourceFilter::IsAdResource(
const KURL& resource_url,
mojom::RequestContextType request_context) {
- if (subresource_filter_->GetIsAssociatedWithAdSubframe())
- return true;
-
WebDocumentSubresourceFilter::LoadPolicy load_policy;
if (last_resource_check_result_.first ==
std::make_pair(resource_url, request_context)) {
diff --git a/chromium/third_party/blink/renderer/core/loader/subresource_filter.h b/chromium/third_party/blink/renderer/core/loader/subresource_filter.h
index 5c164008a59..479e288e61e 100644
--- a/chromium/third_party/blink/renderer/core/loader/subresource_filter.h
+++ b/chromium/third_party/blink/renderer/core/loader/subresource_filter.h
@@ -29,6 +29,9 @@ class CORE_EXPORT SubresourceFilter final
static SubresourceFilter* Create(
ExecutionContext&,
std::unique_ptr<WebDocumentSubresourceFilter>);
+
+ SubresourceFilter(ExecutionContext*,
+ std::unique_ptr<WebDocumentSubresourceFilter>);
~SubresourceFilter();
bool AllowLoad(const KURL& resource_url,
@@ -44,9 +47,6 @@ class CORE_EXPORT SubresourceFilter final
virtual void Trace(blink::Visitor*);
private:
- SubresourceFilter(ExecutionContext*,
- std::unique_ptr<WebDocumentSubresourceFilter>);
-
void ReportLoad(const KURL& resource_url,
WebDocumentSubresourceFilter::LoadPolicy);
diff --git a/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.cc b/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.cc
index c8ab9c40012..eab35b220d9 100644
--- a/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.cc
+++ b/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.cc
@@ -65,7 +65,7 @@ SubresourceIntegrity::IntegrityFeatures SubresourceIntegrityHelper::GetFeatures(
ExecutionContext* execution_context) {
bool allow_signatures =
RuntimeEnabledFeatures::SignatureBasedIntegrityEnabledByRuntimeFlag() ||
- OriginTrials::SignatureBasedIntegrityEnabled(execution_context);
+ origin_trials::SignatureBasedIntegrityEnabled(execution_context);
return allow_signatures ? SubresourceIntegrity::IntegrityFeatures::kSignatures
: SubresourceIntegrity::IntegrityFeatures::kDefault;
}
diff --git a/chromium/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc b/chromium/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc
index 4cab247ffe8..ecd371321a1 100644
--- a/chromium/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc
+++ b/chromium/third_party/blink/renderer/core/loader/text_resource_decoder_builder.cc
@@ -119,7 +119,7 @@ std::unique_ptr<TextResourceDecoder> BuildTextResourceDecoderFor(
// could be an attack vector.
// FIXME: This might be too cautious for non-7bit-encodings and we may
// consider relaxing this later after testing.
- const bool use_hint_encoding =
+ bool use_hint_encoding =
frame && CanReferToParentFrameEncoding(frame, parent_frame);
std::unique_ptr<TextResourceDecoder> decoder;
@@ -134,9 +134,11 @@ std::unique_ptr<TextResourceDecoder> BuildTextResourceDecoderFor(
if (DOMImplementation::IsXMLMIMEType(mime_type)) {
decoder = TextResourceDecoder::Create(TextResourceDecoderOptions(
TextResourceDecoderOptions::kXMLContent, default_encoding));
+ use_hint_encoding = false;
} else if (DOMImplementation::IsJSONMIMEType(mime_type)) {
decoder = TextResourceDecoder::Create(TextResourceDecoderOptions(
TextResourceDecoderOptions::kJSONContent, default_encoding));
+ use_hint_encoding = false;
} else {
WTF::TextEncoding hint_encoding;
if (use_hint_encoding &&
diff --git a/chromium/third_party/blink/renderer/core/loader/text_track_loader.cc b/chromium/third_party/blink/renderer/core/loader/text_track_loader.cc
index 455329ba70d..4998ea7c414 100644
--- a/chromium/third_party/blink/renderer/core/loader/text_track_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/text_track_loader.cc
@@ -104,7 +104,7 @@ bool TextTrackLoader::Load(const KURL& url,
CancelLoad();
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::track;
+ options.initiator_info.name = fetch_initiator_type_names::kTrack;
// Let |request| be the result of creating a potential-CORS request
// given |URL|, "track", and |corsAttributeState|, and with the same-origin
diff --git a/chromium/third_party/blink/renderer/core/loader/text_track_loader.h b/chromium/third_party/blink/renderer/core/loader/text_track_loader.h
index c5da0c0797f..a10870f4d29 100644
--- a/chromium/third_party/blink/renderer/core/loader/text_track_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/text_track_loader.h
@@ -52,8 +52,10 @@ class TextTrackLoader final : public GarbageCollectedFinalized<TextTrackLoader>,
public:
static TextTrackLoader* Create(TextTrackLoaderClient& client,
Document& document) {
- return new TextTrackLoader(client, document);
+ return MakeGarbageCollected<TextTrackLoader>(client, document);
}
+
+ TextTrackLoader(TextTrackLoaderClient&, Document&);
~TextTrackLoader() override;
bool Load(const KURL&, CrossOriginAttributeValue);
@@ -76,8 +78,6 @@ class TextTrackLoader final : public GarbageCollectedFinalized<TextTrackLoader>,
void NewCuesParsed() override;
void FileFailedToParse() override;
- TextTrackLoader(TextTrackLoaderClient&, Document&);
-
void CueLoadTimerFired(TimerBase*);
void CorsPolicyPreventedLoad(const SecurityOrigin*, const KURL&);
diff --git a/chromium/third_party/blink/renderer/core/loader/threadable_loader.cc b/chromium/third_party/blink/renderer/core/loader/threadable_loader.cc
index d1bffb94f55..3da0485319b 100644
--- a/chromium/third_party/blink/renderer/core/loader/threadable_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/threadable_loader.cc
@@ -40,7 +40,6 @@
#include "third_party/blink/public/common/service_worker/service_worker_utils.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
-#include "third_party/blink/public/platform/web_cors.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -79,7 +78,7 @@ namespace {
// Fetch API Spec: https://fetch.spec.whatwg.org/#cors-preflight-fetch-0
AtomicString CreateAccessControlRequestHeadersHeader(
const HTTPHeaderMap& headers) {
- Vector<String> filtered_headers = CORS::CORSUnsafeRequestHeaderNames(headers);
+ Vector<String> filtered_headers = cors::CorsUnsafeRequestHeaderNames(headers);
if (!filtered_headers.size())
return g_null_atom;
@@ -105,6 +104,8 @@ AtomicString CreateAccessControlRequestHeadersHeader(
class ThreadableLoader::DetachedClient final
: public GarbageCollectedFinalized<DetachedClient>,
public ThreadableLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(DetachedClient);
+
public:
explicit DetachedClient(ThreadableLoader* loader)
: self_keep_alive_(this), loader_(loader) {}
@@ -115,7 +116,10 @@ class ThreadableLoader::DetachedClient final
}
void DidFail(const ResourceError&) override { self_keep_alive_.Clear(); }
void DidFailRedirectCheck() override { self_keep_alive_.Clear(); }
- void Trace(Visitor* visitor) { visitor->Trace(loader_); }
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(loader_);
+ ThreadableLoaderClient::Trace(visitor);
+ }
private:
SelfKeepAlive<DetachedClient> self_keep_alive_;
@@ -156,9 +160,9 @@ ThreadableLoader::CreateAccessControlPreflightRequest(
std::unique_ptr<ResourceRequest> preflight_request =
std::make_unique<ResourceRequest>(request_url);
- preflight_request->SetHTTPMethod(HTTPNames::OPTIONS);
- preflight_request->SetHTTPHeaderField(
- HTTPNames::Access_Control_Request_Method, request.HttpMethod());
+ preflight_request->SetHTTPMethod(http_names::kOPTIONS);
+ preflight_request->SetHTTPHeaderField(http_names::kAccessControlRequestMethod,
+ request.HttpMethod());
preflight_request->SetPriority(request.Priority());
preflight_request->SetRequestContext(request.GetRequestContext());
preflight_request->SetFetchCredentialsMode(
@@ -169,14 +173,14 @@ ThreadableLoader::CreateAccessControlPreflightRequest(
if (request.IsExternalRequest()) {
preflight_request->SetHTTPHeaderField(
- HTTPNames::Access_Control_Request_External, "true");
+ http_names::kAccessControlRequestExternal, "true");
}
const AtomicString request_headers =
CreateAccessControlRequestHeadersHeader(request.HttpHeaderFields());
if (request_headers != g_null_atom) {
preflight_request->SetHTTPHeaderField(
- HTTPNames::Access_Control_Request_Headers, request_headers);
+ http_names::kAccessControlRequestHeaders, request_headers);
}
if (origin)
@@ -199,7 +203,7 @@ ThreadableLoader::ThreadableLoader(
: client_(client),
execution_context_(execution_context),
resource_loader_options_(resource_loader_options),
- out_of_blink_cors_(RuntimeEnabledFeatures::OutOfBlinkCORSEnabled()),
+ out_of_blink_cors_(RuntimeEnabledFeatures::OutOfBlinkCorsEnabled()),
is_using_data_consumer_handle_(false),
async_(resource_loader_options.synchronous_policy ==
kRequestAsynchronously),
@@ -213,8 +217,8 @@ ThreadableLoader::ThreadableLoader(
redirect_mode_(network::mojom::FetchRedirectMode::kFollow),
override_referrer_(false) {
DCHECK(client);
- if (execution_context_->IsWorkerGlobalScope())
- ToWorkerGlobalScope(execution_context_)->EnsureFetcher();
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_))
+ scope->EnsureFetcher();
}
void ThreadableLoader::Start(const ResourceRequest& request) {
@@ -223,11 +227,11 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
DCHECK(async_ || request.HttpReferrer().IsEmpty());
bool cors_enabled =
- CORS::IsCORSEnabledRequestMode(request.GetFetchRequestMode());
+ cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode());
// kPreventPreflight can be used only when the CORS is enabled.
- DCHECK(request.CORSPreflightPolicy() ==
- network::mojom::CORSPreflightPolicy::kConsiderPreflight ||
+ DCHECK(request.CorsPreflightPolicy() ==
+ network::mojom::CorsPreflightPolicy::kConsiderPreflight ||
cors_enabled);
initial_request_url_ = request.Url();
@@ -238,10 +242,10 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
redirect_mode_ = request.GetFetchRedirectMode();
if (request.GetFetchRequestMode() ==
- network::mojom::FetchRequestMode::kNoCORS) {
- SECURITY_CHECK(WebCORS::IsNoCORSAllowedContext(request_context_));
+ network::mojom::FetchRequestMode::kNoCors) {
+ SECURITY_CHECK(cors::IsNoCorsAllowedContext(request_context_));
}
- cors_flag_ = CORS::CalculateCORSFlag(request.Url(), GetSecurityOrigin(),
+ cors_flag_ = cors::CalculateCorsFlag(request.Url(), GetSecurityOrigin(),
request.GetFetchRequestMode());
// The CORS flag variable is not yet used at the step in the spec that
@@ -251,8 +255,8 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
ThreadableLoaderClient* client = client_;
Clear();
client->DidFail(ResourceError(
- request.Url(), network::CORSErrorStatus(
- network::mojom::CORSError::kDisallowedByMode)));
+ request.Url(), network::CorsErrorStatus(
+ network::mojom::CorsError::kDisallowedByMode)));
return;
}
@@ -328,7 +332,7 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
return;
}
- if (CORS::IsCORSEnabledRequestMode(request.GetFetchRequestMode())) {
+ if (cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode())) {
// Save the request to fallback_request_for_service_worker to use when the
// service worker doesn't handle (call respondWith()) a CORS enabled
// request.
@@ -346,7 +350,7 @@ void ThreadableLoader::DispatchInitialRequest(ResourceRequest& request) {
return;
}
- DCHECK(CORS::IsCORSEnabledRequestMode(request.GetFetchRequestMode()) ||
+ DCHECK(cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode()) ||
request.IsExternalRequest());
MakeCrossOriginAccessRequest(request);
@@ -386,7 +390,7 @@ void ThreadableLoader::LoadPreflightRequest(
void ThreadableLoader::MakeCrossOriginAccessRequest(
const ResourceRequest& request) {
- DCHECK(CORS::IsCORSEnabledRequestMode(request.GetFetchRequestMode()) ||
+ DCHECK(cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode()) ||
request.IsExternalRequest());
DCHECK(client_);
DCHECK(!GetResource());
@@ -394,11 +398,11 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
// Cross-origin requests are only allowed certain registered schemes. We would
// catch this when checking response headers later, but there is no reason to
// send a request, preflighted or not, that's guaranteed to be denied.
- if (!SchemeRegistry::ShouldTreatURLSchemeAsCORSEnabled(
+ if (!SchemeRegistry::ShouldTreatURLSchemeAsCorsEnabled(
request.Url().Protocol())) {
DispatchDidFail(ResourceError(
- request.Url(), network::CORSErrorStatus(
- network::mojom::CORSError::kCORSDisabledScheme)));
+ request.Url(), network::CorsErrorStatus(
+ network::mojom::CorsError::kCorsDisabledScheme)));
return;
}
@@ -431,24 +435,24 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
}
if (request.GetFetchRequestMode() !=
- network::mojom::FetchRequestMode::kCORSWithForcedPreflight) {
- if (request.CORSPreflightPolicy() ==
- network::mojom::CORSPreflightPolicy::kPreventPreflight) {
+ network::mojom::FetchRequestMode::kCorsWithForcedPreflight) {
+ if (request.CorsPreflightPolicy() ==
+ network::mojom::CorsPreflightPolicy::kPreventPreflight) {
PrepareCrossOriginRequest(cross_origin_request);
LoadRequest(cross_origin_request, cross_origin_options);
return;
}
- DCHECK_EQ(request.CORSPreflightPolicy(),
- network::mojom::CORSPreflightPolicy::kConsiderPreflight);
+ DCHECK_EQ(request.CorsPreflightPolicy(),
+ network::mojom::CorsPreflightPolicy::kConsiderPreflight);
- // We use ContainsOnlyCORSSafelistedOrForbiddenHeaders() here since
+ // We use ContainsOnlyCorsSafelistedOrForbiddenHeaders() here since
// |request| may have been modified in the process of loading (not from
// the user's input). For example, referrer. We need to accept them. For
// security, we must reject forbidden headers/methods at the point we
// accept user's input. Not here.
- if (CORS::IsCORSSafelistedMethod(request.HttpMethod()) &&
- CORS::ContainsOnlyCORSSafelistedOrForbiddenHeaders(
+ if (cors::IsCorsSafelistedMethod(request.HttpMethod()) &&
+ cors::ContainsOnlyCorsSafelistedOrForbiddenHeaders(
request.HttpHeaderFields())) {
PrepareCrossOriginRequest(cross_origin_request);
LoadRequest(cross_origin_request, cross_origin_options);
@@ -462,10 +466,10 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
bool should_ignore_preflight_cache = false;
// Prevent use of the CORS preflight cache when instructed by the DevTools
// not to use caches.
- probe::shouldForceCORSPreflight(execution_context_,
+ probe::shouldForceCorsPreflight(execution_context_,
&should_ignore_preflight_cache);
if (should_ignore_preflight_cache ||
- !CORS::CheckIfRequestCanSkipPreflight(
+ !cors::CheckIfRequestCanSkipPreflight(
GetSecurityOrigin()->ToString(), cross_origin_request.Url(),
cross_origin_request.GetFetchCredentialsMode(),
cross_origin_request.HttpMethod(),
@@ -483,15 +487,7 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
LoadRequest(cross_origin_request, cross_origin_options);
}
-ThreadableLoader::~ThreadableLoader() {
- // |client_| is a raw pointer and having a non-null |client_| here probably
- // means UaF.
- // In the detached case, |this| is held by DetachedClient defined above, but
- // SelfKeepAlive in DetachedClient is forcibly cancelled on worker thread
- // termination. We can safely ignore this case.
- CHECK(!client_ || detached_);
- DCHECK(!GetResource());
-}
+ThreadableLoader::~ThreadableLoader() {}
void ThreadableLoader::SetTimeout(const TimeDelta& timeout) {
timeout_ = timeout;
@@ -536,7 +532,7 @@ void ThreadableLoader::Detach() {
if (!resource)
return;
detached_ = true;
- client_ = new DetachedClient(this);
+ client_ = MakeGarbageCollected<DetachedClient>(this);
}
void ThreadableLoader::SetDefersLoading(bool value) {
@@ -583,13 +579,13 @@ bool ThreadableLoader::RedirectReceived(
HandlePreflightFailure(
original_url,
- network::CORSErrorStatus(
- network::mojom::CORSError::kPreflightDisallowedRedirect));
+ network::CorsErrorStatus(
+ network::mojom::CorsError::kPreflightDisallowedRedirect));
return false;
}
if (cors_flag_) {
- if (const auto error_status = CORS::CheckAccess(
+ if (const auto error_status = cors::CheckAccess(
original_url, redirect_response.HttpStatusCode(),
redirect_response.HttpHeaderFields(),
new_request.GetFetchCredentialsMode(), *GetSecurityOrigin())) {
@@ -635,26 +631,26 @@ bool ThreadableLoader::RedirectReceived(
// Allow same origin requests to continue after allowing clients to audit
// the redirect.
if (!(cors_flag_ ||
- CORS::CalculateCORSFlag(new_url, GetSecurityOrigin(),
+ cors::CalculateCorsFlag(new_url, GetSecurityOrigin(),
new_request.GetFetchRequestMode()))) {
bool follow =
client_->WillFollowRedirect(new_url, redirect_response_to_pass);
- response_tainting_ = CORS::CalculateResponseTainting(
+ response_tainting_ = cors::CalculateResponseTainting(
new_url, new_request.GetFetchRequestMode(), GetSecurityOrigin(),
- CORSFlag::Unset);
+ CorsFlag::Unset);
return follow;
}
- probe::didReceiveCORSRedirectResponse(
+ probe::didReceiveCorsRedirectResponse(
execution_context_, resource->Identifier(),
GetDocument() && GetDocument()->GetFrame()
? GetDocument()->GetFrame()->Loader().GetDocumentLoader()
: nullptr,
redirect_response_to_pass, resource);
- if (auto error_status = CORS::CheckRedirectLocation(
+ if (auto error_status = cors::CheckRedirectLocation(
new_url, fetch_request_mode_, GetSecurityOrigin(),
- cors_flag_ ? CORSFlag::Set : CORSFlag::Unset)) {
+ cors_flag_ ? CorsFlag::Set : CorsFlag::Unset)) {
DispatchDidFail(ResourceError(original_url, *error_status));
return false;
}
@@ -766,8 +762,8 @@ void ThreadableLoader::DidDownloadToBlob(Resource* resource,
void ThreadableLoader::HandlePreflightResponse(
const ResourceResponse& response) {
- base::Optional<network::CORSErrorStatus> cors_error_status =
- CORS::CheckPreflightAccess(response.Url(), response.HttpStatusCode(),
+ base::Optional<network::CorsErrorStatus> cors_error_status =
+ cors::CheckPreflightAccess(response.Url(), response.HttpStatusCode(),
response.HttpHeaderFields(),
actual_request_.GetFetchCredentialsMode(),
*GetSecurityOrigin());
@@ -776,17 +772,17 @@ void ThreadableLoader::HandlePreflightResponse(
return;
}
- base::Optional<network::mojom::CORSError> preflight_error =
- CORS::CheckPreflight(response.HttpStatusCode());
+ base::Optional<network::mojom::CorsError> preflight_error =
+ cors::CheckPreflight(response.HttpStatusCode());
if (preflight_error) {
HandlePreflightFailure(response.Url(),
- network::CORSErrorStatus(*preflight_error));
+ network::CorsErrorStatus(*preflight_error));
return;
}
- base::Optional<network::CORSErrorStatus> error_status;
+ base::Optional<network::CorsErrorStatus> error_status;
if (actual_request_.IsExternalRequest()) {
- error_status = CORS::CheckExternalPreflight(response.HttpHeaderFields());
+ error_status = cors::CheckExternalPreflight(response.HttpHeaderFields());
if (error_status) {
HandlePreflightFailure(response.Url(), *error_status);
return;
@@ -794,7 +790,7 @@ void ThreadableLoader::HandlePreflightResponse(
}
String access_control_error_description;
- error_status = CORS::EnsurePreflightResultAndCacheOnSuccess(
+ error_status = cors::EnsurePreflightResultAndCacheOnSuccess(
response.HttpHeaderFields(), GetSecurityOrigin()->ToString(),
actual_request_.Url(), actual_request_.HttpMethod(),
actual_request_.HttpHeaderFields(),
@@ -863,11 +859,11 @@ void ThreadableLoader::ResponseReceived(
// We dispatch a CORS failure for the case.
// TODO(yhirano): This is probably not spec conformant. Fix it after
// https://github.com/w3c/preload/issues/100 is addressed.
- if (fetch_request_mode_ != network::mojom::FetchRequestMode::kNoCORS &&
+ if (fetch_request_mode_ != network::mojom::FetchRequestMode::kNoCors &&
response.GetType() == network::mojom::FetchResponseType::kOpaque) {
DispatchDidFail(ResourceError(
- response.Url(), network::CORSErrorStatus(
- network::mojom::CORSError::kInvalidResponse)));
+ response.Url(), network::CorsErrorStatus(
+ network::mojom::CorsError::kInvalidResponse)));
return;
}
@@ -890,7 +886,7 @@ void ThreadableLoader::ResponseReceived(
fallback_request_for_service_worker_ = ResourceRequest();
if (cors_flag_) {
- base::Optional<network::CORSErrorStatus> access_error = CORS::CheckAccess(
+ base::Optional<network::CorsErrorStatus> access_error = cors::CheckAccess(
response.Url(), response.HttpStatusCode(), response.HttpHeaderFields(),
fetch_credentials_mode_, *GetSecurityOrigin());
if (access_error) {
@@ -914,7 +910,7 @@ void ThreadableLoader::SetSerializedCachedMetadata(Resource*,
if (!actual_request_.IsNull())
return;
- client_->DidReceiveCachedMetadata(data, size);
+ client_->DidReceiveCachedMetadata(data, SafeCast<int>(size));
}
void ThreadableLoader::DataReceived(Resource* resource,
@@ -1012,7 +1008,7 @@ void ThreadableLoader::LoadActualRequest() {
void ThreadableLoader::HandlePreflightFailure(
const KURL& url,
- const network::CORSErrorStatus& error_status) {
+ const network::CorsErrorStatus& error_status) {
// Prevent NotifyFinished() from bypassing access check.
actual_request_ = ResourceRequest();
@@ -1020,9 +1016,9 @@ void ThreadableLoader::HandlePreflightFailure(
}
void ThreadableLoader::DispatchDidFail(const ResourceError& error) {
- if (!out_of_blink_cors_ && error.CORSErrorStatus()) {
- String message = CORS::GetErrorString(
- *error.CORSErrorStatus(), initial_request_url_, last_request_url_,
+ if (!out_of_blink_cors_ && error.CorsErrorStatus()) {
+ String message = cors::GetErrorString(
+ *error.CorsErrorStatus(), initial_request_url_, last_request_url_,
*GetSecurityOrigin(), ResourceType::kRaw,
resource_loader_options_.initiator_info.name);
execution_context_->AddConsoleMessage(ConsoleMessage::Create(
@@ -1040,7 +1036,7 @@ void ThreadableLoader::LoadRequest(
ResourceRequest& request,
ResourceLoaderOptions resource_loader_options) {
resource_loader_options.cors_handling_by_resource_fetcher =
- kDisableCORSHandlingByResourceFetcher;
+ kDisableCorsHandlingByResourceFetcher;
if (out_of_blink_cors_) {
if (request.GetFetchCredentialsMode() ==
@@ -1050,10 +1046,10 @@ void ThreadableLoader::LoadRequest(
}
} else {
if (actual_request_.IsNull()) {
- response_tainting_ = CORS::CalculateResponseTainting(
+ response_tainting_ = cors::CalculateResponseTainting(
request.Url(), request.GetFetchRequestMode(), GetSecurityOrigin(),
- cors_flag_ ? CORSFlag::Set : CORSFlag::Unset);
- request.SetAllowStoredCredentials(CORS::CalculateCredentialsFlag(
+ cors_flag_ ? CorsFlag::Set : CorsFlag::Unset);
+ request.SetAllowStoredCredentials(cors::CalculateCredentialsFlag(
request.GetFetchCredentialsMode(), response_tainting_));
} else {
request.SetAllowStoredCredentials(false);
@@ -1106,6 +1102,7 @@ Document* ThreadableLoader::GetDocument() const {
void ThreadableLoader::Trace(blink::Visitor* visitor) {
visitor->Trace(execution_context_);
+ visitor->Trace(client_);
RawResourceClient::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/threadable_loader.h b/chromium/third_party/blink/renderer/core/loader/threadable_loader.h
index 3b65f86a606..2929062fec0 100644
--- a/chromium/third_party/blink/renderer/core/loader/threadable_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/threadable_loader.h
@@ -89,10 +89,6 @@ class CORE_EXPORT ThreadableLoader final
// After any of these methods is called, the loader won't call any of the
// ThreadableLoaderClient methods.
//
- // A user must guarantee that the loading completes before the attached
- // client gets invalid. Also, a user must guarantee that the loading
- // completes before the ThreadableLoader is destructed.
- //
// When ThreadableLoader::Cancel() is called,
// ThreadableLoaderClient::DidFail() is called with a ResourceError
// with IsCancellation() returning true, if any of DidFinishLoading()
@@ -100,7 +96,7 @@ class CORE_EXPORT ThreadableLoader final
// called with a ResourceError with IsCancellation() returning true
// also for cancellation happened inside the loader.)
//
- // ThreadableLoaderClient methods may call cancel().
+ // ThreadableLoaderClient methods may call Cancel().
ThreadableLoader(ExecutionContext&,
ThreadableLoaderClient*,
const ResourceLoaderOptions&);
@@ -187,7 +183,7 @@ class CORE_EXPORT ThreadableLoader final
void LoadActualRequest();
// Clears actual_request_ and reports access control check failure to
// m_client.
- void HandlePreflightFailure(const KURL&, const network::CORSErrorStatus&);
+ void HandlePreflightFailure(const KURL&, const network::CorsErrorStatus&);
// Investigates the response for the preflight request. If successful,
// the actual request will be made later in NotifyFinished().
void HandlePreflightResponse(const ResourceResponse&);
@@ -211,7 +207,7 @@ class CORE_EXPORT ThreadableLoader final
// TODO(kinuko): Remove dependency to document.
Document* GetDocument() const;
- ThreadableLoaderClient* client_;
+ Member<ThreadableLoaderClient> client_;
Member<ExecutionContext> execution_context_;
TimeDelta timeout_;
@@ -220,7 +216,7 @@ class CORE_EXPORT ThreadableLoader final
// up-to-date values from them and this variable, and use it.
const ResourceLoaderOptions resource_loader_options_;
- // True when feature OutOfBlinkCORS is enabled (https://crbug.com/736308).
+ // True when feature OutOfBlinkCors is enabled (https://crbug.com/736308).
bool out_of_blink_cors_;
// Corresponds to the CORS flag in the Fetch spec.
diff --git a/chromium/third_party/blink/renderer/core/loader/threadable_loader_client.h b/chromium/third_party/blink/renderer/core/loader/threadable_loader_client.h
index 9eac59edaf5..87016048c35 100644
--- a/chromium/third_party/blink/renderer/core/loader/threadable_loader_client.h
+++ b/chromium/third_party/blink/renderer/core/loader/threadable_loader_client.h
@@ -46,7 +46,7 @@ class ResourceError;
class ResourceResponse;
class ResourceTimingInfo;
-class CORE_EXPORT ThreadableLoaderClient {
+class CORE_EXPORT ThreadableLoaderClient : public GarbageCollectedMixin {
public:
virtual void DidSendData(unsigned long long /*bytesSent*/,
unsigned long long /*totalBytesToBeSent*/) {}
diff --git a/chromium/third_party/blink/renderer/core/loader/threadable_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/threadable_loader_test.cc
index 0a576889547..ad8156f493f 100644
--- a/chromium/third_party/blink/renderer/core/loader/threadable_loader_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/threadable_loader_test.cc
@@ -53,12 +53,13 @@ using Checkpoint = testing::StrictMock<testing::MockFunction<void(int)>>;
constexpr char kFileName[] = "fox-null-terminated.html";
-class MockThreadableLoaderClient : public ThreadableLoaderClient {
+class MockThreadableLoaderClient final
+ : public GarbageCollectedFinalized<MockThreadableLoaderClient>,
+ public ThreadableLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(MockThreadableLoaderClient);
+
public:
- static std::unique_ptr<MockThreadableLoaderClient> Create() {
- return base::WrapUnique(
- new testing::StrictMock<MockThreadableLoaderClient>);
- }
+ MockThreadableLoaderClient() = default;
MOCK_METHOD2(DidSendData, void(unsigned long long, unsigned long long));
MOCK_METHOD3(DidReceiveResponseMock,
void(unsigned long,
@@ -77,9 +78,6 @@ class MockThreadableLoaderClient : public ThreadableLoaderClient {
MOCK_METHOD0(DidFailRedirectCheck, void());
MOCK_METHOD1(DidReceiveResourceTiming, void(const ResourceTimingInfo&));
MOCK_METHOD1(DidDownloadData, void(int));
-
- protected:
- MockThreadableLoaderClient() = default;
};
bool IsCancellation(const ResourceError& error) {
@@ -114,12 +112,12 @@ void UnregisterAllURLsAndClearMemoryCache() {
}
void SetUpSuccessURL() {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
SuccessURL(), test::CoreTestDataPath(kFileName), "text/html");
}
void SetUpErrorURL() {
- URLTestHelpers::RegisterMockedErrorURLLoad(ErrorURL());
+ url_test_helpers::RegisterMockedErrorURLLoad(ErrorURL());
}
void SetUpRedirectURL() {
@@ -135,7 +133,7 @@ void SetUpRedirectURL() {
response.AddHTTPHeaderField("Location", SuccessURL().GetString());
response.AddHTTPHeaderField("Access-Control-Allow-Origin", "http://fake.url");
- URLTestHelpers::RegisterMockedURLLoadWithCustomResponse(
+ url_test_helpers::RegisterMockedURLLoadWithCustomResponse(
url, test::CoreTestDataPath(kFileName), response);
}
@@ -152,7 +150,7 @@ void SetUpRedirectLoopURL() {
response.AddHTTPHeaderField("Location", RedirectLoopURL().GetString());
response.AddHTTPHeaderField("Access-Control-Allow-Origin", "http://fake.url");
- URLTestHelpers::RegisterMockedURLLoadWithCustomResponse(
+ url_test_helpers::RegisterMockedURLLoadWithCustomResponse(
url, test::CoreTestDataPath(kFileName), response);
}
@@ -179,8 +177,8 @@ class ThreadableLoaderTestHelper final {
void CreateLoader(ThreadableLoaderClient* client) {
ResourceLoaderOptions resource_loader_options;
- loader_ = new ThreadableLoader(GetDocument(), client,
- resource_loader_options);
+ loader_ = MakeGarbageCollected<ThreadableLoader>(GetDocument(), client,
+ resource_loader_options);
}
void StartLoader(const ResourceRequest& request) { loader_->Start(request); }
@@ -221,7 +219,7 @@ class ThreadableLoaderTest : public testing::Test {
void StartLoader(const KURL& url,
network::mojom::FetchRequestMode fetch_request_mode =
- network::mojom::FetchRequestMode::kNoCORS) {
+ network::mojom::FetchRequestMode::kNoCors) {
ResourceRequest request(url);
request.SetRequestContext(mojom::RequestContextType::OBJECT);
request.SetFetchRequestMode(fetch_request_mode);
@@ -242,19 +240,21 @@ class ThreadableLoaderTest : public testing::Test {
void CreateLoader() { helper_->CreateLoader(Client()); }
- MockThreadableLoaderClient* Client() const { return client_.get(); }
+ MockThreadableLoaderClient* Client() const { return client_.Get(); }
private:
void SetUp() override {
- client_ = MockThreadableLoaderClient::Create();
+ client_ = MakeGarbageCollected<MockThreadableLoaderClient>();
helper_->OnSetUp();
}
void TearDown() override {
helper_->OnTearDown();
- client_.reset();
+ client_ = nullptr;
+ // We need GC here to avoid gmock flakiness.
+ ThreadState::Current()->CollectAllGarbage();
}
- std::unique_ptr<MockThreadableLoaderClient> client_;
+ Persistent<MockThreadableLoaderClient> client_;
std::unique_ptr<ThreadableLoaderTestHelper> helper_;
};
@@ -473,8 +473,8 @@ TEST_F(ThreadableLoaderTest, DidFailInStart) {
EXPECT_CALL(
*Client(),
DidFail(ResourceError(
- ErrorURL(), network::CORSErrorStatus(
- network::mojom::CORSError::kDisallowedByMode))));
+ ErrorURL(), network::CorsErrorStatus(
+ network::mojom::CorsError::kDisallowedByMode))));
EXPECT_CALL(GetCheckpoint(), Call(2));
StartLoader(ErrorURL(), network::mojom::FetchRequestMode::kSameOrigin);
@@ -522,10 +522,10 @@ TEST_F(ThreadableLoaderTest, DidFailAccessControlCheck) {
EXPECT_CALL(*Client(),
DidFail(ResourceError(
SuccessURL(),
- network::CORSErrorStatus(
- network::mojom::CORSError::kMissingAllowOriginHeader))));
+ network::CorsErrorStatus(
+ network::mojom::CorsError::kMissingAllowOriginHeader))));
- StartLoader(SuccessURL(), network::mojom::FetchRequestMode::kCORS);
+ StartLoader(SuccessURL(), network::mojom::FetchRequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -592,7 +592,7 @@ TEST_F(ThreadableLoaderTest, DidFailRedirectCheck) {
EXPECT_CALL(GetCheckpoint(), Call(2));
EXPECT_CALL(*Client(), DidFailRedirectCheck());
- StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCORS);
+ StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -607,7 +607,7 @@ TEST_F(ThreadableLoaderTest, CancelInDidFailRedirectCheck) {
EXPECT_CALL(*Client(), DidFailRedirectCheck())
.WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::CancelLoader));
- StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCORS);
+ StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -622,7 +622,7 @@ TEST_F(ThreadableLoaderTest, ClearInDidFailRedirectCheck) {
EXPECT_CALL(*Client(), DidFailRedirectCheck())
.WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::ClearLoader));
- StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCORS);
+ StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -642,7 +642,7 @@ TEST_F(ThreadableLoaderTest, GetResponseSynchronously) {
// test is not saying that didFailAccessControlCheck should be dispatched
// synchronously, but is saying that even when a response is served
// synchronously it should not lead to a crash.
- StartLoader(KURL("about:blank"), network::mojom::FetchRequestMode::kCORS);
+ StartLoader(KURL("about:blank"), network::mojom::FetchRequestMode::kCors);
CallCheckpoint(2);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.cc b/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.cc
index a95f66ac0b1..2da7499c7b5 100644
--- a/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.cc
+++ b/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.cc
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
#include "third_party/blink/renderer/core/loader/subresource_filter.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h"
#include "third_party/blink/renderer/core/timing/worker_global_scope_performance.h"
#include "third_party/blink/renderer/core/workers/worker_clients.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
@@ -33,80 +34,36 @@
namespace blink {
-namespace {
-
-// WorkerFetchContextHolder is used to pass the WebWorkerFetchContext from the
-// main thread to the worker thread by attaching to the WorkerClients as a
-// Supplement.
-class WorkerFetchContextHolder final
- : public GarbageCollectedFinalized<WorkerFetchContextHolder>,
- public Supplement<WorkerClients> {
- USING_GARBAGE_COLLECTED_MIXIN(WorkerFetchContextHolder);
-
- public:
- static WorkerFetchContextHolder* From(WorkerClients& clients) {
- return Supplement<WorkerClients>::From<WorkerFetchContextHolder>(clients);
- }
- static const char kSupplementName[];
-
- explicit WorkerFetchContextHolder(
- std::unique_ptr<WebWorkerFetchContext> web_context)
- : web_context_(std::move(web_context)) {}
- virtual ~WorkerFetchContextHolder() = default;
-
- std::unique_ptr<WebWorkerFetchContext> TakeContext() {
- return std::move(web_context_);
- }
-
- void Trace(blink::Visitor* visitor) override {
- Supplement<WorkerClients>::Trace(visitor);
- }
-
- private:
- std::unique_ptr<WebWorkerFetchContext> web_context_;
-};
-
-} // namespace
-
-// static
-const char WorkerFetchContextHolder::kSupplementName[] =
- "WorkerFetchContextHolder";
-
WorkerFetchContext::~WorkerFetchContext() = default;
WorkerFetchContext* WorkerFetchContext::Create(
- WorkerOrWorkletGlobalScope& global_scope) {
- DCHECK(global_scope.IsContextThread());
- WorkerClients* worker_clients = global_scope.Clients();
- DCHECK(worker_clients);
- WorkerFetchContextHolder* holder =
- Supplement<WorkerClients>::From<WorkerFetchContextHolder>(
- *worker_clients);
- if (!holder)
+ WorkerOrWorkletGlobalScope& global_scope,
+ scoped_refptr<WebWorkerFetchContext> web_context,
+ SubresourceFilter* subresource_filter,
+ FetchClientSettingsObject* fetch_client_settings_object) {
+ if (!web_context)
return nullptr;
- std::unique_ptr<WebWorkerFetchContext> web_context = holder->TakeContext();
- DCHECK(web_context);
- return new WorkerFetchContext(global_scope, std::move(web_context));
+ return MakeGarbageCollected<WorkerFetchContext>(
+ global_scope, std::move(web_context), subresource_filter,
+ fetch_client_settings_object);
}
WorkerFetchContext::WorkerFetchContext(
WorkerOrWorkletGlobalScope& global_scope,
- std::unique_ptr<WebWorkerFetchContext> web_context)
+ scoped_refptr<WebWorkerFetchContext> web_context,
+ SubresourceFilter* subresource_filter,
+ FetchClientSettingsObject* fetch_client_settings_object)
: BaseFetchContext(global_scope.GetTaskRunner(TaskType::kInternalLoading)),
global_scope_(global_scope),
web_context_(std::move(web_context)),
- fetch_client_settings_object_(
- new FetchClientSettingsObjectImpl(*global_scope_)),
+ subresource_filter_(subresource_filter),
+ fetch_client_settings_object_(fetch_client_settings_object),
save_data_enabled_(GetNetworkStateNotifier().SaveDataEnabled()) {
- web_context_->InitializeOnWorkerThread();
- std::unique_ptr<blink::WebDocumentSubresourceFilter> web_filter =
- web_context_->TakeSubresourceFilter();
- if (web_filter) {
- subresource_filter_ =
- SubresourceFilter::Create(global_scope, std::move(web_filter));
- }
+ DCHECK(global_scope.IsContextThread());
+ DCHECK(web_context_);
}
-const FetchClientSettingsObjectImpl*
+
+const FetchClientSettingsObject*
WorkerFetchContext::GetFetchClientSettingsObject() const {
return fetch_client_settings_object_.Get();
}
@@ -265,18 +222,20 @@ std::unique_ptr<WebURLLoader> WorkerFetchContext::CreateURLLoader(
->CreateURLLoader(wrapped, CreateResourceLoadingTaskRunnerHandle());
}
- if (request.GetRequestContext() == mojom::RequestContextType::SCRIPT) {
- if (!script_loader_factory_)
- script_loader_factory_ = web_context_->CreateScriptLoaderFactory();
- if (script_loader_factory_) {
- return script_loader_factory_->CreateURLLoader(
+ // Use |script_loader_factory_| to load types SCRIPT (classic imported
+ // scripts) and SERVICE_WORKER (module main scripts and module imported
+ // scripts). Note that classic main scripts are also SERVICE_WORKER but loaded
+ // by the shadow page on the main thread, not here.
+ if (request.GetRequestContext() == mojom::RequestContextType::SCRIPT ||
+ request.GetRequestContext() ==
+ mojom::RequestContextType::SERVICE_WORKER) {
+ if (web_context_->GetScriptLoaderFactory()) {
+ return web_context_->GetScriptLoaderFactory()->CreateURLLoader(
wrapped, CreateResourceLoadingTaskRunnerHandle());
}
}
- if (!url_loader_factory_)
- url_loader_factory_ = web_context_->CreateURLLoaderFactory();
- return url_loader_factory_->CreateURLLoader(
+ return web_context_->GetURLLoaderFactory()->CreateURLLoader(
wrapped, CreateResourceLoadingTaskRunnerHandle());
}
@@ -313,7 +272,7 @@ void WorkerFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request,
return;
if (save_data_enabled_)
- request.SetHTTPHeaderField(HTTPNames::Save_Data, "on");
+ request.SetHTTPHeaderField(http_names::kSaveData, "on");
}
void WorkerFetchContext::DispatchWillSendRequest(
@@ -349,13 +308,13 @@ void WorkerFetchContext::DispatchDidReceiveResponse(
void WorkerFetchContext::DispatchDidReceiveData(unsigned long identifier,
const char* data,
- int data_length) {
+ size_t data_length) {
probe::didReceiveData(global_scope_, identifier, nullptr, data, data_length);
}
void WorkerFetchContext::DispatchDidReceiveEncodedData(
unsigned long identifier,
- int encoded_data_length) {
+ size_t encoded_data_length) {
probe::didReceiveEncodedDataLength(global_scope_, nullptr, identifier,
encoded_data_length);
}
@@ -377,7 +336,8 @@ void WorkerFetchContext::DispatchDidFail(const KURL& url,
int64_t encoded_data_length,
bool is_internal_request) {
probe::didFailLoading(global_scope_, identifier, nullptr, error);
- if (NetworkUtils::IsCertificateTransparencyRequiredError(error.ErrorCode())) {
+ if (network_utils::IsCertificateTransparencyRequiredError(
+ error.ErrorCode())) {
CountUsage(WebFeature::kCertificateTransparencyRequiredErrorOnResourceLoad);
}
}
@@ -387,7 +347,8 @@ void WorkerFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
// worklets.
if (global_scope_->IsWorkletGlobalScope())
return;
- WorkerGlobalScopePerformance::performance(*ToWorkerGlobalScope(global_scope_))
+ WorkerGlobalScopePerformance::performance(
+ To<WorkerGlobalScope>(*global_scope_))
->GenerateAndAddResourceTiming(info);
}
@@ -420,9 +381,8 @@ SecurityContext& WorkerFetchContext::GetSecurityContext() const {
}
WorkerSettings* WorkerFetchContext::GetWorkerSettings() const {
- if (!global_scope_->IsWorkerGlobalScope())
- return nullptr;
- return ToWorkerGlobalScope(global_scope_)->GetWorkerSettings();
+ auto* scope = DynamicTo<WorkerGlobalScope>(*global_scope_);
+ return scope ? scope->GetWorkerSettings() : nullptr;
}
WorkerContentSettingsClient*
@@ -437,15 +397,4 @@ void WorkerFetchContext::Trace(blink::Visitor* visitor) {
BaseFetchContext::Trace(visitor);
}
-void ProvideWorkerFetchContextToWorker(
- WorkerClients* clients,
- std::unique_ptr<WebWorkerFetchContext> web_context) {
- DCHECK(clients);
- // web_context should only be nullptr in unit tests.
- if (!web_context)
- return;
- WorkerFetchContextHolder::ProvideTo(
- *clients, new WorkerFetchContextHolder(std::move(web_context)));
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.h b/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.h
index 75037db49f9..a46ff5479ed 100644
--- a/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.h
+++ b/chromium/third_party/blink/renderer/core/loader/worker_fetch_context.h
@@ -11,7 +11,6 @@
#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/loader/base_fetch_context.h"
-#include "third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -19,27 +18,29 @@ namespace blink {
class Resource;
class SubresourceFilter;
class WebURLLoader;
-class WebURLLoaderFactory;
class WebWorkerFetchContext;
-class WorkerClients;
class WorkerContentSettingsClient;
class WorkerSettings;
class WorkerOrWorkletGlobalScope;
enum class ResourceType : uint8_t;
-CORE_EXPORT void ProvideWorkerFetchContextToWorker(
- WorkerClients*,
- std::unique_ptr<WebWorkerFetchContext>);
-
// The WorkerFetchContext is a FetchContext for workers (dedicated, shared and
// service workers) and threaded worklets (animation and audio worklets).
class WorkerFetchContext final : public BaseFetchContext {
public:
- static WorkerFetchContext* Create(WorkerOrWorkletGlobalScope&);
+ static WorkerFetchContext* Create(WorkerOrWorkletGlobalScope&,
+ scoped_refptr<WebWorkerFetchContext>,
+ SubresourceFilter*,
+ FetchClientSettingsObject*);
+
+ WorkerFetchContext(WorkerOrWorkletGlobalScope&,
+ scoped_refptr<WebWorkerFetchContext>,
+ SubresourceFilter*,
+ FetchClientSettingsObject*);
~WorkerFetchContext() override;
// BaseFetchContext implementation:
- const FetchClientSettingsObjectImpl* GetFetchClientSettingsObject()
+ const FetchClientSettingsObject* GetFetchClientSettingsObject()
const override;
KURL GetSiteForCookies() const override;
SubresourceFilter* GetSubresourceFilter() const override;
@@ -98,9 +99,9 @@ class WorkerFetchContext final : public BaseFetchContext {
ResourceResponseType) override;
void DispatchDidReceiveData(unsigned long identifier,
const char* data,
- int dataLength) override;
+ size_t data_length) override;
void DispatchDidReceiveEncodedData(unsigned long identifier,
- int encoded_data_length) override;
+ size_t encoded_data_length) override;
void DispatchDidFinishLoading(unsigned long identifier,
TimeTicks finish_time,
int64_t encoded_data_length,
@@ -131,26 +132,14 @@ class WorkerFetchContext final : public BaseFetchContext {
void Trace(blink::Visitor*) override;
private:
- WorkerFetchContext(WorkerOrWorkletGlobalScope&,
- std::unique_ptr<WebWorkerFetchContext>);
-
void SetFirstPartyCookie(ResourceRequest&);
const Member<WorkerOrWorkletGlobalScope> global_scope_;
- const std::unique_ptr<WebWorkerFetchContext> web_context_;
-
- // Responsible for regular loads from the worker (i.e., Fetch API).
- std::unique_ptr<WebURLLoaderFactory> url_loader_factory_;
-
- // Responsible for handling script loads in certian situations (i.e.,
- // script import from service workers, which invole special processing
- // to persist the script in storage). May be null, fallback to
- // url_loader_factory_ in that case.
- std::unique_ptr<WebURLLoaderFactory> script_loader_factory_;
+ const scoped_refptr<WebWorkerFetchContext> web_context_;
Member<SubresourceFilter> subresource_filter_;
- const Member<FetchClientSettingsObjectImpl> fetch_client_settings_object_;
+ const Member<FetchClientSettingsObject> fetch_client_settings_object_;
// The value of |save_data_enabled_| is read once per frame from
// NetworkStateNotifier, which is guarded by a mutex lock, and cached locally
diff --git a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.cc b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.cc
index 3bed37ca88c..5370cb6e8a9 100644
--- a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.cc
+++ b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.cc
@@ -38,6 +38,8 @@ BlinkTransferableMessage ToBlinkTransferableMessage(
message.stack_trace_debugger_id_second));
result.locked_agent_cluster_id = message.locked_agent_cluster_id;
result.ports.AppendRange(message.ports.begin(), message.ports.end());
+ result.message->GetStreamChannels().AppendRange(
+ message.stream_channels.begin(), message.stream_channels.end());
result.has_user_gesture = message.has_user_gesture;
if (message.user_activation) {
result.user_activation = mojom::blink::UserActivationSnapshot::New(
@@ -66,6 +68,8 @@ TransferableMessage ToTransferableMessage(BlinkTransferableMessage message) {
message.sender_stack_trace_id.debugger_id.second;
result.locked_agent_cluster_id = message.locked_agent_cluster_id;
result.ports.assign(message.ports.begin(), message.ports.end());
+ auto& stream_channels = message.message->GetStreamChannels();
+ result.stream_channels.assign(stream_channels.begin(), stream_channels.end());
result.has_user_gesture = message.has_user_gesture;
if (message.user_activation) {
result.user_activation = mojom::UserActivationSnapshot::New(
diff --git a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc
index 514714c6656..fe3e97c6561 100644
--- a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc
+++ b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc
@@ -65,19 +65,24 @@ bool StructTraits<blink::mojom::blink::TransferableMessage::DataView,
Read(blink::mojom::blink::TransferableMessage::DataView data,
blink::BlinkTransferableMessage* out) {
Vector<mojo::ScopedMessagePipeHandle> ports;
+ Vector<mojo::ScopedMessagePipeHandle> stream_channels;
blink::SerializedScriptValue::ArrayBufferContentsArray
array_buffer_contents_array;
Vector<SkBitmap> sk_bitmaps;
if (!data.ReadMessage(static_cast<blink::BlinkCloneableMessage*>(out)) ||
!data.ReadArrayBufferContentsArray(&array_buffer_contents_array) ||
!data.ReadImageBitmapContentsArray(&sk_bitmaps) ||
- !data.ReadPorts(&ports) || !data.ReadUserActivation(&out->user_activation)) {
+ !data.ReadPorts(&ports) || !data.ReadStreamChannels(&stream_channels) ||
+ !data.ReadUserActivation(&out->user_activation)) {
return false;
}
out->ports.ReserveInitialCapacity(ports.size());
out->ports.AppendRange(std::make_move_iterator(ports.begin()),
std::make_move_iterator(ports.end()));
+ out->message->GetStreamChannels().AppendRange(
+ std::make_move_iterator(stream_channels.begin()),
+ std::make_move_iterator(stream_channels.end()));
out->has_user_gesture = data.has_user_gesture();
out->message->SetArrayBufferContentsArray(
diff --git a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h
index 92e8bd82a0c..3194e3f118f 100644
--- a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h
+++ b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h
@@ -34,6 +34,16 @@ struct CORE_EXPORT
return result;
}
+ static Vector<mojo::ScopedMessagePipeHandle> stream_channels(
+ blink::BlinkTransferableMessage& input) {
+ Vector<mojo::ScopedMessagePipeHandle> result;
+ auto& stream_channels = input.message->GetStreamChannels();
+ result.ReserveInitialCapacity(stream_channels.size());
+ for (const auto& port : stream_channels)
+ result.push_back(port.ReleaseHandle());
+ return result;
+ }
+
static const blink::SerializedScriptValue::ArrayBufferContentsArray&
array_buffer_contents_array(const blink::BlinkCloneableMessage& input) {
return input.message->GetArrayBufferContentsArray();
diff --git a/chromium/third_party/blink/renderer/core/messaging/message_channel.h b/chromium/third_party/blink/renderer/core/messaging/message_channel.h
index 64b19f95a94..9e584a25b9d 100644
--- a/chromium/third_party/blink/renderer/core/messaging/message_channel.h
+++ b/chromium/third_party/blink/renderer/core/messaging/message_channel.h
@@ -41,17 +41,17 @@ class CORE_EXPORT MessageChannel final : public ScriptWrappable {
public:
static MessageChannel* Create(ExecutionContext* context) {
- return new MessageChannel(context);
+ return MakeGarbageCollected<MessageChannel>(context);
}
+ explicit MessageChannel(ExecutionContext*);
+
MessagePort* port1() const { return port1_; }
MessagePort* port2() const { return port2_; }
void Trace(blink::Visitor*) override;
private:
- explicit MessageChannel(ExecutionContext*);
-
Member<MessagePort> port1_;
Member<MessagePort> port2_;
};
diff --git a/chromium/third_party/blink/renderer/core/messaging/message_port.cc b/chromium/third_party/blink/renderer/core/messaging/message_port.cc
index ec7d6dcaa55..196ab5f6147 100644
--- a/chromium/third_party/blink/renderer/core/messaging/message_port.cc
+++ b/chromium/third_party/blink/renderer/core/messaging/message_port.cc
@@ -56,7 +56,7 @@ constexpr base::TimeDelta kYieldThreshold =
base::TimeDelta::FromMilliseconds(50);
MessagePort* MessagePort::Create(ExecutionContext& execution_context) {
- return new MessagePort(execution_context);
+ return MakeGarbageCollected<MessagePort>(execution_context);
}
MessagePort::MessagePort(ExecutionContext& execution_context)
@@ -71,15 +71,15 @@ void MessagePort::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void MessagePort::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
if (!IsEntangled())
return;
@@ -177,7 +177,7 @@ void MessagePort::Entangle(MessagePortChannel channel) {
}
const AtomicString& MessagePort::InterfaceName() const {
- return EventTargetNames::MessagePort;
+ return event_target_names::kMessagePort;
}
bool MessagePort::HasPendingActivity() const {
@@ -246,7 +246,7 @@ MessagePortArray* MessagePort::EntanglePorts(
// https://html.spec.whatwg.org/multipage/comms.html#message-ports
// |ports| should be an empty array, not null even when there is no ports.
wtf_size_t count = SafeCast<wtf_size_t>(channels.size());
- MessagePortArray* port_array = new MessagePortArray(count);
+ MessagePortArray* port_array = MakeGarbageCollected<MessagePortArray>(count);
for (wtf_size_t i = 0; i < count; ++i) {
MessagePort* port = MessagePort::Create(context);
port->Entangle(std::move(channels[i]));
@@ -290,9 +290,9 @@ bool MessagePort::Accept(mojo::Message* mojo_message) {
// WorkerGlobalScope::close() in Worker onmessage handler should prevent
// the next message from dispatching.
- if (GetExecutionContext()->IsWorkerGlobalScope() &&
- ToWorkerGlobalScope(GetExecutionContext())->IsClosing()) {
- return true;
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(GetExecutionContext())) {
+ if (scope->IsClosing())
+ return true;
}
Event* evt;
@@ -303,9 +303,9 @@ bool MessagePort::Accept(mojo::Message* mojo_message) {
*GetExecutionContext(), std::move(message.ports));
UserActivation* user_activation = nullptr;
if (message.user_activation) {
- user_activation =
- new UserActivation(message.user_activation->has_been_active,
- message.user_activation->was_active);
+ user_activation = MakeGarbageCollected<UserActivation>(
+ message.user_activation->has_been_active,
+ message.user_activation->was_active);
}
evt = MessageEvent::Create(ports, std::move(message.message),
user_activation);
diff --git a/chromium/third_party/blink/renderer/core/messaging/message_port.h b/chromium/third_party/blink/renderer/core/messaging/message_port.h
index c983d11a3e9..f04e8a05c6a 100644
--- a/chromium/third_party/blink/renderer/core/messaging/message_port.h
+++ b/chromium/third_party/blink/renderer/core/messaging/message_port.h
@@ -58,6 +58,8 @@ class CORE_EXPORT MessagePort : public EventTargetWithInlineData,
public:
static MessagePort* Create(ExecutionContext&);
+
+ explicit MessagePort(ExecutionContext&);
~MessagePort() override;
void postMessage(ScriptState*,
@@ -66,7 +68,7 @@ class CORE_EXPORT MessagePort : public EventTargetWithInlineData,
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
void start();
@@ -103,19 +105,19 @@ class CORE_EXPORT MessagePort : public EventTargetWithInlineData,
void ContextDestroyed(ExecutionContext*) override { close(); }
void setOnmessage(EventListener* listener) {
- SetAttributeEventListener(EventTypeNames::message, listener);
+ SetAttributeEventListener(event_type_names::kMessage, listener);
start();
}
EventListener* onmessage() {
- return GetAttributeEventListener(EventTypeNames::message);
+ return GetAttributeEventListener(event_type_names::kMessage);
}
void setOnmessageerror(EventListener* listener) {
- SetAttributeEventListener(EventTypeNames::messageerror, listener);
+ SetAttributeEventListener(event_type_names::kMessageerror, listener);
start();
}
EventListener* onmessageerror() {
- return GetAttributeEventListener(EventTypeNames::messageerror);
+ return GetAttributeEventListener(event_type_names::kMessageerror);
}
// A port starts out its life entangled, and remains entangled until it is
@@ -131,9 +133,6 @@ class CORE_EXPORT MessagePort : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
- protected:
- explicit MessagePort(ExecutionContext&);
-
private:
// mojo::MessageReceiver implementation.
bool Accept(mojo::Message*) override;
diff --git a/chromium/third_party/blink/renderer/core/messaging/message_port.idl b/chromium/third_party/blink/renderer/core/messaging/message_port.idl
index 78e26bf7d84..01d03add77c 100644
--- a/chromium/third_party/blink/renderer/core/messaging/message_port.idl
+++ b/chromium/third_party/blink/renderer/core/messaging/message_port.idl
@@ -32,8 +32,8 @@
Exposed=(Window,Worker,AudioWorklet),
Transferable
] interface MessagePort : EventTarget {
- [CallWith=ScriptState, RaisesException, Measure] void postMessage(any message, optional sequence<object> transfer = []);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException, Measure] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException, Measure] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException, Measure] void postMessage(any message, optional PostMessageOptions options);
[Measure] void start();
[Measure] void close();
diff --git a/chromium/third_party/blink/renderer/core/mojo/README.md b/chromium/third_party/blink/renderer/core/mojo/README.md
index f3b59983b31..c6fe75b0fa7 100644
--- a/chromium/third_party/blink/renderer/core/mojo/README.md
+++ b/chromium/third_party/blink/renderer/core/mojo/README.md
@@ -3,7 +3,7 @@ This document is a subset of the [Mojo documentation](/mojo/README.md).
The JavaScript system API exposes the capabilities to create message pipes, data
pipes, shared buffers and watchers. The API is defined using Web IDL. You could
-find the IDL files [here](https://cs.chromium.org/chromium/src/third_party/blink/Source/core/mojo/).
+find the IDL files [here](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/mojo/)
Please refer to the low-level [C system API](/mojo/public/c/system/README.md)
for more detailed documentation of equivalent methods.
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo.cc b/chromium/third_party/blink/renderer/core/mojo/mojo.cc
index 59701c14d51..2cb328250fd 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo.cc
@@ -26,7 +26,9 @@
namespace blink {
// static
-void Mojo::createMessagePipe(MojoCreateMessagePipeResult& result_dict) {
+MojoCreateMessagePipeResult* Mojo::createMessagePipe() {
+ MojoCreateMessagePipeResult* result_dict =
+ MojoCreateMessagePipeResult::Create();
MojoCreateMessagePipeOptions options = {0};
options.struct_size = sizeof(::MojoCreateMessagePipeOptions);
options.flags = MOJO_CREATE_MESSAGE_PIPE_FLAG_NONE;
@@ -34,54 +36,60 @@ void Mojo::createMessagePipe(MojoCreateMessagePipeResult& result_dict) {
mojo::ScopedMessagePipeHandle handle0, handle1;
MojoResult result = mojo::CreateMessagePipe(&options, &handle0, &handle1);
- result_dict.setResult(result);
+ result_dict->setResult(result);
if (result == MOJO_RESULT_OK) {
- result_dict.setHandle0(
+ result_dict->setHandle0(
MojoHandle::Create(mojo::ScopedHandle::From(std::move(handle0))));
- result_dict.setHandle1(
+ result_dict->setHandle1(
MojoHandle::Create(mojo::ScopedHandle::From(std::move(handle1))));
}
+ return result_dict;
}
// static
-void Mojo::createDataPipe(const MojoCreateDataPipeOptions& options_dict,
- MojoCreateDataPipeResult& result_dict) {
- if (!options_dict.hasElementNumBytes() ||
- !options_dict.hasCapacityNumBytes()) {
- result_dict.setResult(MOJO_RESULT_INVALID_ARGUMENT);
- return;
+MojoCreateDataPipeResult* Mojo::createDataPipe(
+ const MojoCreateDataPipeOptions* options_dict) {
+ MojoCreateDataPipeResult* result_dict = MojoCreateDataPipeResult::Create();
+
+ if (!options_dict->hasElementNumBytes() ||
+ !options_dict->hasCapacityNumBytes()) {
+ result_dict->setResult(MOJO_RESULT_INVALID_ARGUMENT);
+ return result_dict;
}
::MojoCreateDataPipeOptions options = {0};
options.struct_size = sizeof(options);
options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE;
- options.element_num_bytes = options_dict.elementNumBytes();
- options.capacity_num_bytes = options_dict.capacityNumBytes();
+ options.element_num_bytes = options_dict->elementNumBytes();
+ options.capacity_num_bytes = options_dict->capacityNumBytes();
mojo::ScopedDataPipeProducerHandle producer;
mojo::ScopedDataPipeConsumerHandle consumer;
MojoResult result = mojo::CreateDataPipe(&options, &producer, &consumer);
- result_dict.setResult(result);
+ result_dict->setResult(result);
if (result == MOJO_RESULT_OK) {
- result_dict.setProducer(
+ result_dict->setProducer(
MojoHandle::Create(mojo::ScopedHandle::From(std::move(producer))));
- result_dict.setConsumer(
+ result_dict->setConsumer(
MojoHandle::Create(mojo::ScopedHandle::From(std::move(consumer))));
}
+ return result_dict;
}
// static
-void Mojo::createSharedBuffer(unsigned num_bytes,
- MojoCreateSharedBufferResult& result_dict) {
+MojoCreateSharedBufferResult* Mojo::createSharedBuffer(unsigned num_bytes) {
+ MojoCreateSharedBufferResult* result_dict =
+ MojoCreateSharedBufferResult::Create();
MojoCreateSharedBufferOptions* options = nullptr;
mojo::Handle handle;
MojoResult result =
MojoCreateSharedBuffer(num_bytes, options, handle.mutable_value());
- result_dict.setResult(result);
+ result_dict->setResult(result);
if (result == MOJO_RESULT_OK) {
- result_dict.setHandle(MojoHandle::Create(mojo::MakeScopedHandle(handle)));
+ result_dict->setHandle(MojoHandle::Create(mojo::MakeScopedHandle(handle)));
}
+ return result_dict;
}
// static
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo.h b/chromium/third_party/blink/renderer/core/mojo/mojo.h
index d5c5ad4f177..a81831c93b0 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo.h
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo.h
@@ -46,11 +46,10 @@ class Mojo final : public ScriptWrappable {
static const MojoResult kResultBusy = MOJO_RESULT_BUSY;
static const MojoResult kResultShouldWait = MOJO_RESULT_SHOULD_WAIT;
- static void createMessagePipe(MojoCreateMessagePipeResult&);
- static void createDataPipe(const MojoCreateDataPipeOptions&,
- MojoCreateDataPipeResult&);
- static void createSharedBuffer(unsigned num_bytes,
- MojoCreateSharedBufferResult&);
+ static MojoCreateMessagePipeResult* createMessagePipe();
+ static MojoCreateDataPipeResult* createDataPipe(
+ const MojoCreateDataPipeOptions*);
+ static MojoCreateSharedBufferResult* createSharedBuffer(unsigned num_bytes);
static void bindInterface(ScriptState*,
const String& interface_name,
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc b/chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc
index 5410fba86d1..2a5047b84b8 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc
@@ -30,7 +30,7 @@ static const size_t kHandleVectorInlineCapacity = 4;
namespace blink {
MojoHandle* MojoHandle::Create(mojo::ScopedHandle handle) {
- return new MojoHandle(std::move(handle));
+ return MakeGarbageCollected<MojoHandle>(std::move(handle));
}
mojo::ScopedHandle MojoHandle::TakeHandle() {
@@ -45,7 +45,7 @@ void MojoHandle::close() {
}
MojoWatcher* MojoHandle::watch(ScriptState* script_state,
- const MojoHandleSignals& signals,
+ const MojoHandleSignals* signals,
V8MojoWatchCallback* callback) {
return MojoWatcher::Create(handle_.get(), signals, callback,
ExecutionContext::From(script_state));
@@ -77,21 +77,23 @@ MojoResult MojoHandle::writeMessage(
raw_handles.data(), raw_handles.size(), MOJO_WRITE_MESSAGE_FLAG_NONE);
}
-void MojoHandle::readMessage(const MojoReadMessageFlags& flags_dict,
- MojoReadMessageResult& result_dict) {
+MojoReadMessageResult* MojoHandle::readMessage(
+ const MojoReadMessageFlags* flags_dict) {
+ MojoReadMessageResult* result_dict = MojoReadMessageResult::Create();
+
mojo::ScopedMessageHandle message;
MojoResult result =
mojo::ReadMessageNew(mojo::MessagePipeHandle(handle_.get().value()),
&message, MOJO_READ_MESSAGE_FLAG_NONE);
if (result != MOJO_RESULT_OK) {
- result_dict.setResult(result);
- return;
+ result_dict->setResult(result);
+ return result_dict;
}
result = MojoSerializeMessage(message->value(), nullptr);
if (result != MOJO_RESULT_OK && result != MOJO_RESULT_FAILED_PRECONDITION) {
- result_dict.setResult(MOJO_RESULT_ABORTED);
- return;
+ result_dict->setResult(MOJO_RESULT_ABORTED);
+ return result_dict;
}
uint32_t num_bytes = 0, num_handles = 0;
@@ -106,8 +108,8 @@ void MojoHandle::readMessage(const MojoReadMessageFlags& flags_dict,
}
if (result != MOJO_RESULT_OK) {
- result_dict.setResult(MOJO_RESULT_ABORTED);
- return;
+ result_dict->setResult(MOJO_RESULT_ABORTED);
+ return result_dict;
}
DOMArrayBuffer* buffer =
@@ -116,22 +118,26 @@ void MojoHandle::readMessage(const MojoReadMessageFlags& flags_dict,
CHECK(buffer);
memcpy(buffer->Data(), bytes, num_bytes);
}
- result_dict.setBuffer(buffer);
+ result_dict->setBuffer(buffer);
HeapVector<Member<MojoHandle>> handles(num_handles);
for (uint32_t i = 0; i < num_handles; ++i) {
handles[i] = MojoHandle::Create(
mojo::MakeScopedHandle(mojo::Handle(raw_handles[i])));
}
- result_dict.setHandles(handles);
- result_dict.setResult(result);
+ result_dict->setHandles(handles);
+ result_dict->setResult(result);
+
+ return result_dict;
}
-void MojoHandle::writeData(const ArrayBufferOrArrayBufferView& buffer,
- const MojoWriteDataOptions& options_dict,
- MojoWriteDataResult& result_dict) {
+MojoWriteDataResult* MojoHandle::writeData(
+ const ArrayBufferOrArrayBufferView& buffer,
+ const MojoWriteDataOptions* options_dict) {
+ MojoWriteDataResult* result_dict = MojoWriteDataResult::Create();
+
MojoWriteDataFlags flags = MOJO_WRITE_DATA_FLAG_NONE;
- if (options_dict.allOrNone())
+ if (options_dict->allOrNone())
flags |= MOJO_WRITE_DATA_FLAG_ALL_OR_NONE;
const void* elements = nullptr;
@@ -151,26 +157,30 @@ void MojoHandle::writeData(const ArrayBufferOrArrayBufferView& buffer,
options.flags = flags;
MojoResult result =
MojoWriteData(handle_.get().value(), elements, &num_bytes, &options);
- result_dict.setResult(result);
- result_dict.setNumBytes(result == MOJO_RESULT_OK ? num_bytes : 0);
+ result_dict->setResult(result);
+ result_dict->setNumBytes(result == MOJO_RESULT_OK ? num_bytes : 0);
+ return result_dict;
}
-void MojoHandle::queryData(MojoReadDataResult& result_dict) {
+MojoReadDataResult* MojoHandle::queryData() const {
+ MojoReadDataResult* result_dict = MojoReadDataResult::Create();
uint32_t num_bytes = 0;
::MojoReadDataOptions options;
options.struct_size = sizeof(options);
options.flags = MOJO_READ_DATA_FLAG_QUERY;
MojoResult result =
MojoReadData(handle_.get().value(), &options, nullptr, &num_bytes);
- result_dict.setResult(result);
- result_dict.setNumBytes(num_bytes);
+ result_dict->setResult(result);
+ result_dict->setNumBytes(num_bytes);
+ return result_dict;
}
-void MojoHandle::discardData(unsigned num_bytes,
- const MojoDiscardDataOptions& options_dict,
- MojoReadDataResult& result_dict) {
+MojoReadDataResult* MojoHandle::discardData(
+ unsigned num_bytes,
+ const MojoDiscardDataOptions* options_dict) {
+ MojoReadDataResult* result_dict = MojoReadDataResult::Create();
MojoReadDataFlags flags = MOJO_READ_DATA_FLAG_DISCARD;
- if (options_dict.allOrNone())
+ if (options_dict->allOrNone())
flags |= MOJO_READ_DATA_FLAG_ALL_OR_NONE;
::MojoReadDataOptions options;
@@ -178,17 +188,19 @@ void MojoHandle::discardData(unsigned num_bytes,
options.flags = flags;
MojoResult result =
MojoReadData(handle_.get().value(), &options, nullptr, &num_bytes);
- result_dict.setResult(result);
- result_dict.setNumBytes(result == MOJO_RESULT_OK ? num_bytes : 0);
+ result_dict->setResult(result);
+ result_dict->setNumBytes(result == MOJO_RESULT_OK ? num_bytes : 0);
+ return result_dict;
}
-void MojoHandle::readData(ArrayBufferOrArrayBufferView& buffer,
- const MojoReadDataOptions& options_dict,
- MojoReadDataResult& result_dict) {
+MojoReadDataResult* MojoHandle::readData(
+ ArrayBufferOrArrayBufferView& buffer,
+ const MojoReadDataOptions* options_dict) const {
+ MojoReadDataResult* result_dict = MojoReadDataResult::Create();
MojoReadDataFlags flags = MOJO_READ_DATA_FLAG_NONE;
- if (options_dict.allOrNone())
+ if (options_dict->allOrNone())
flags |= MOJO_READ_DATA_FLAG_ALL_OR_NONE;
- if (options_dict.peek())
+ if (options_dict->peek())
flags |= MOJO_READ_DATA_FLAG_PEEK;
void* elements = nullptr;
@@ -208,17 +220,18 @@ void MojoHandle::readData(ArrayBufferOrArrayBufferView& buffer,
options.flags = flags;
MojoResult result =
MojoReadData(handle_.get().value(), &options, elements, &num_bytes);
- result_dict.setResult(result);
- result_dict.setNumBytes(result == MOJO_RESULT_OK ? num_bytes : 0);
+ result_dict->setResult(result);
+ result_dict->setNumBytes(result == MOJO_RESULT_OK ? num_bytes : 0);
+ return result_dict;
}
-void MojoHandle::mapBuffer(unsigned offset,
- unsigned num_bytes,
- MojoMapBufferResult& result_dict) {
+MojoMapBufferResult* MojoHandle::mapBuffer(unsigned offset,
+ unsigned num_bytes) {
+ MojoMapBufferResult* result_dict = MojoMapBufferResult::Create();
void* data = nullptr;
MojoResult result =
MojoMapBuffer(handle_.get().value(), offset, num_bytes, nullptr, &data);
- result_dict.setResult(result);
+ result_dict->setResult(result);
if (result == MOJO_RESULT_OK) {
WTF::ArrayBufferContents::DataHandle data_handle(
data, num_bytes,
@@ -229,25 +242,29 @@ void MojoHandle::mapBuffer(unsigned offset,
nullptr);
WTF::ArrayBufferContents contents(std::move(data_handle),
WTF::ArrayBufferContents::kNotShared);
- result_dict.setBuffer(DOMArrayBuffer::Create(contents));
+ result_dict->setBuffer(DOMArrayBuffer::Create(contents));
}
+ return result_dict;
}
-void MojoHandle::duplicateBufferHandle(
- const MojoDuplicateBufferHandleOptions& options_dict,
- MojoCreateSharedBufferResult& result_dict) {
+MojoCreateSharedBufferResult* MojoHandle::duplicateBufferHandle(
+ const MojoDuplicateBufferHandleOptions* options_dict) {
+ MojoCreateSharedBufferResult* result_dict =
+ MojoCreateSharedBufferResult::Create();
+
::MojoDuplicateBufferHandleOptions options = {
sizeof(options), MOJO_DUPLICATE_BUFFER_HANDLE_FLAG_NONE};
- if (options_dict.readOnly())
+ if (options_dict->readOnly())
options.flags |= MOJO_DUPLICATE_BUFFER_HANDLE_FLAG_READ_ONLY;
mojo::Handle handle;
MojoResult result = MojoDuplicateBufferHandle(handle_.get().value(), &options,
handle.mutable_value());
- result_dict.setResult(result);
+ result_dict->setResult(result);
if (result == MOJO_RESULT_OK) {
- result_dict.setHandle(MojoHandle::Create(mojo::MakeScopedHandle(handle)));
+ result_dict->setHandle(MojoHandle::Create(mojo::MakeScopedHandle(handle)));
}
+ return result_dict;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo_handle.h b/chromium/third_party/blink/renderer/core/mojo/mojo_handle.h
index 94a4c3e1caf..fb281a5527d 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo_handle.h
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo_handle.h
@@ -33,38 +33,35 @@ class CORE_EXPORT MojoHandle final : public ScriptWrappable {
public:
static MojoHandle* Create(mojo::ScopedHandle);
+ explicit MojoHandle(mojo::ScopedHandle);
+
mojo::ScopedHandle TakeHandle();
void close();
MojoWatcher* watch(ScriptState*,
- const MojoHandleSignals&,
+ const MojoHandleSignals*,
V8MojoWatchCallback*);
// MessagePipe handle.
MojoResult writeMessage(ArrayBufferOrArrayBufferView&,
const HeapVector<Member<MojoHandle>>&);
- void readMessage(const MojoReadMessageFlags&, MojoReadMessageResult&);
+ MojoReadMessageResult* readMessage(const MojoReadMessageFlags*);
// DataPipe handle.
- void writeData(const ArrayBufferOrArrayBufferView&,
- const MojoWriteDataOptions&,
- MojoWriteDataResult&);
- void queryData(MojoReadDataResult&);
- void discardData(unsigned num_bytes,
- const MojoDiscardDataOptions&,
- MojoReadDataResult&);
- void readData(ArrayBufferOrArrayBufferView&,
- const MojoReadDataOptions&,
- MojoReadDataResult&);
+ MojoWriteDataResult* writeData(const ArrayBufferOrArrayBufferView&,
+ const MojoWriteDataOptions*);
+ MojoReadDataResult* queryData() const;
+ MojoReadDataResult* discardData(unsigned num_bytes,
+ const MojoDiscardDataOptions*);
+ MojoReadDataResult* readData(ArrayBufferOrArrayBufferView&,
+ const MojoReadDataOptions*) const;
// SharedBuffer handle.
- void mapBuffer(unsigned offset, unsigned num_bytes, MojoMapBufferResult&);
- void duplicateBufferHandle(const MojoDuplicateBufferHandleOptions&,
- MojoCreateSharedBufferResult&);
+ MojoMapBufferResult* mapBuffer(unsigned offset, unsigned num_bytes);
+ MojoCreateSharedBufferResult* duplicateBufferHandle(
+ const MojoDuplicateBufferHandleOptions*);
private:
- explicit MojoHandle(mojo::ScopedHandle);
-
mojo::ScopedHandle handle_;
};
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc b/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc
index b62ee148954..aab35c5b038 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc
@@ -10,16 +10,16 @@
#include "third_party/blink/renderer/core/mojo/mojo_handle_signals.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
// static
MojoWatcher* MojoWatcher::Create(mojo::Handle handle,
- const MojoHandleSignals& signals_dict,
+ const MojoHandleSignals* signals_dict,
V8MojoWatchCallback* callback,
ExecutionContext* context) {
- MojoWatcher* watcher = new MojoWatcher(context, callback);
+ MojoWatcher* watcher = MakeGarbageCollected<MojoWatcher>(context, callback);
MojoResult result = watcher->Watch(handle, signals_dict);
// TODO(alokp): Consider raising an exception.
// Current clients expect to recieve the initial error returned by MojoWatch
@@ -71,13 +71,13 @@ MojoWatcher::MojoWatcher(ExecutionContext* context,
callback_(callback) {}
MojoResult MojoWatcher::Watch(mojo::Handle handle,
- const MojoHandleSignals& signals_dict) {
+ const MojoHandleSignals* signals_dict) {
::MojoHandleSignals signals = MOJO_HANDLE_SIGNAL_NONE;
- if (signals_dict.readable())
+ if (signals_dict->readable())
signals |= MOJO_HANDLE_SIGNAL_READABLE;
- if (signals_dict.writable())
+ if (signals_dict->writable())
signals |= MOJO_HANDLE_SIGNAL_WRITABLE;
- if (signals_dict.peerClosed())
+ if (signals_dict->peerClosed())
signals |= MOJO_HANDLE_SIGNAL_PEER_CLOSED;
MojoResult result =
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.h b/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.h
index 816853b79e3..f1a392c269e 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.h
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.h
@@ -26,9 +26,11 @@ class MojoWatcher final : public ScriptWrappable,
public:
static MojoWatcher* Create(mojo::Handle,
- const MojoHandleSignals&,
+ const MojoHandleSignals*,
V8MojoWatchCallback*,
ExecutionContext*);
+
+ MojoWatcher(ExecutionContext*, V8MojoWatchCallback*);
~MojoWatcher() override;
MojoResult cancel();
@@ -44,8 +46,7 @@ class MojoWatcher final : public ScriptWrappable,
private:
friend class V8MojoWatcher;
- MojoWatcher(ExecutionContext*, V8MojoWatchCallback*);
- MojoResult Watch(mojo::Handle, const MojoHandleSignals&);
+ MojoResult Watch(mojo::Handle, const MojoHandleSignals*);
MojoResult Arm(MojoResult* ready_result);
static void OnHandleReady(const MojoTrapEvent*);
diff --git a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.cc b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.cc
index dc8e2449101..396adfe4789 100644
--- a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.cc
@@ -37,7 +37,8 @@ MojoInterfaceInterceptor* MojoInterfaceInterceptor::Create(
return nullptr;
}
- return new MojoInterfaceInterceptor(context, interface_name, process_scope);
+ return MakeGarbageCollected<MojoInterfaceInterceptor>(context, interface_name,
+ process_scope);
}
MojoInterfaceInterceptor::~MojoInterfaceInterceptor() = default;
@@ -58,11 +59,11 @@ void MojoInterfaceInterceptor::start(ExceptionState& exception_state) {
StringUTF8Adaptor(interface_name_).AsStringPiece().as_string();
if (process_scope_) {
- service_manager::Identity identity(
+ service_manager::Connector* connector = Platform::Current()->GetConnector();
+ auto browser_service_filter = service_manager::ServiceFilter::ByName(
Platform::Current()->GetBrowserServiceName());
- service_manager::Connector::TestApi test_api(
- Platform::Current()->GetConnector());
- if (test_api.HasBinderOverride(identity, interface_name)) {
+ if (connector->HasBinderOverrideForTesting(browser_service_filter,
+ interface_name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidModificationError,
"Interface " + interface_name_ +
@@ -71,8 +72,8 @@ void MojoInterfaceInterceptor::start(ExceptionState& exception_state) {
}
started_ = true;
- test_api.OverrideBinderForTesting(
- identity, interface_name,
+ connector->OverrideBinderForTesting(
+ browser_service_filter, interface_name,
WTF::BindRepeating(&MojoInterfaceInterceptor::OnInterfaceRequest,
WrapWeakPersistent(this)));
return;
@@ -103,12 +104,12 @@ void MojoInterfaceInterceptor::stop() {
StringUTF8Adaptor(interface_name_).AsStringPiece().as_string();
if (process_scope_) {
- service_manager::Identity identity(
+ auto filter = service_manager::ServiceFilter::ByName(
Platform::Current()->GetBrowserServiceName());
service_manager::Connector::TestApi test_api(
Platform::Current()->GetConnector());
- DCHECK(test_api.HasBinderOverride(identity, interface_name));
- test_api.ClearBinderOverride(identity, interface_name);
+ DCHECK(test_api.HasBinderOverride(filter, interface_name));
+ test_api.ClearBinderOverride(filter, interface_name);
return;
}
@@ -125,7 +126,7 @@ void MojoInterfaceInterceptor::Trace(blink::Visitor* visitor) {
}
const AtomicString& MojoInterfaceInterceptor::InterfaceName() const {
- return EventTargetNames::MojoInterfaceInterceptor;
+ return event_target_names::kMojoInterfaceInterceptor;
}
ExecutionContext* MojoInterfaceInterceptor::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.h b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.h
index fcf51154fa7..140bbedb255 100644
--- a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.h
+++ b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.h
@@ -40,12 +40,16 @@ class MojoInterfaceInterceptor final
const String& interface_name,
const String& scope,
ExceptionState&);
+
+ MojoInterfaceInterceptor(ExecutionContext*,
+ const String& interface_name,
+ bool process_scope);
~MojoInterfaceInterceptor() override;
void start(ExceptionState&);
void stop();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(interfacerequest);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(interfacerequest, kInterfacerequest);
void Trace(blink::Visitor*) override;
@@ -60,10 +64,6 @@ class MojoInterfaceInterceptor final
void ContextDestroyed(ExecutionContext*) final;
private:
- MojoInterfaceInterceptor(ExecutionContext*,
- const String& interface_name,
- bool process_scope);
-
service_manager::InterfaceProvider* GetInterfaceProvider() const;
void OnInterfaceRequest(mojo::ScopedMessagePipeHandle);
void DispatchInterfaceRequestEvent(mojo::ScopedMessagePipeHandle);
diff --git a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.cc b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.cc
index 17e7e45e69a..70587940e03 100644
--- a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.cc
@@ -18,13 +18,13 @@ void MojoInterfaceRequestEvent::Trace(blink::Visitor* visitor) {
}
MojoInterfaceRequestEvent::MojoInterfaceRequestEvent(MojoHandle* handle)
- : Event(EventTypeNames::interfacerequest, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kInterfacerequest, Bubbles::kNo, Cancelable::kNo),
handle_(handle) {}
MojoInterfaceRequestEvent::MojoInterfaceRequestEvent(
const AtomicString& type,
- const MojoInterfaceRequestEventInit& initializer)
+ const MojoInterfaceRequestEventInit* initializer)
: Event(type, Bubbles::kNo, Cancelable::kNo),
- handle_(initializer.handle()) {}
+ handle_(initializer->handle()) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.h b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.h
index d0508252d7d..3015aa6808a 100644
--- a/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.h
+++ b/chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_request_event.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_MOJO_TEST_MOJO_INTERFACE_REQUEST_EVENT_H_
#include "third_party/blink/renderer/core/dom/events/event.h"
-#include "third_party/blink/renderer/core/event_names.h"
+#include "third_party/blink/renderer/core/event_interface_names.h"
namespace blink {
@@ -24,28 +24,28 @@ class MojoInterfaceRequestEvent final : public Event {
~MojoInterfaceRequestEvent() override;
static MojoInterfaceRequestEvent* Create(MojoHandle* handle) {
- return new MojoInterfaceRequestEvent(handle);
+ return MakeGarbageCollected<MojoInterfaceRequestEvent>(handle);
}
static MojoInterfaceRequestEvent* Create(
const AtomicString& type,
- const MojoInterfaceRequestEventInit& initializer) {
- return new MojoInterfaceRequestEvent(type, initializer);
+ const MojoInterfaceRequestEventInit* initializer) {
+ return MakeGarbageCollected<MojoInterfaceRequestEvent>(type, initializer);
}
+ explicit MojoInterfaceRequestEvent(MojoHandle*);
+ MojoInterfaceRequestEvent(const AtomicString& type,
+ const MojoInterfaceRequestEventInit*);
+
MojoHandle* handle() const { return handle_; }
const AtomicString& InterfaceName() const override {
- return EventNames::MojoInterfaceRequestEvent;
+ return event_interface_names::kMojoInterfaceRequestEvent;
}
void Trace(blink::Visitor*) override;
private:
- explicit MojoInterfaceRequestEvent(MojoHandle*);
- MojoInterfaceRequestEvent(const AtomicString& type,
- const MojoInterfaceRequestEventInit&);
-
Member<MojoHandle> handle_;
};
diff --git a/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS b/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS
index f0de60d9d38..ffa62011cfd 100644
--- a/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS
+++ b/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS
@@ -1,5 +1,4 @@
-junov@chromium.org
-xlai@chromium.org
+fserb@chromium.org
xidachen@chromium.org
# TEAM: paint-dev@chromium.org
diff --git a/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc b/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
index 0dab135f671..2cfce64c6d2 100644
--- a/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
+++ b/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
@@ -27,6 +27,7 @@
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
+#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/image-encoders/image_encoder_utils.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
@@ -34,14 +35,23 @@
namespace blink {
-OffscreenCanvas::OffscreenCanvas(const IntSize& size) : size_(size) {}
+OffscreenCanvas::OffscreenCanvas(const IntSize& size) : size_(size) {
+ UpdateMemoryUsage();
+}
OffscreenCanvas* OffscreenCanvas::Create(unsigned width, unsigned height) {
- return new OffscreenCanvas(
+ UMA_HISTOGRAM_BOOLEAN("Blink.OffscreenCanvas.NewOffscreenCanvas", true);
+ return MakeGarbageCollected<OffscreenCanvas>(
IntSize(clampTo<int>(width), clampTo<int>(height)));
}
-OffscreenCanvas::~OffscreenCanvas() = default;
+OffscreenCanvas::~OffscreenCanvas() {
+ CanvasRenderingContextHost::RecordCanvasSizeToUMA(
+ Size().Width(), Size().Height(),
+ CanvasRenderingContextHost::HostType::kOffscreenCanvasHost);
+ v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
+ -memory_usage_);
+}
void OffscreenCanvas::Commit(scoped_refptr<CanvasResource> canvas_resource,
const SkIRect& damage_rect) {
@@ -66,7 +76,7 @@ void OffscreenCanvas::Dispose() {
if (HasPlaceholderCanvas() && GetTopExecutionContext() &&
GetTopExecutionContext()->IsWorkerGlobalScope()) {
WorkerAnimationFrameProvider* animation_frame_provider =
- ToWorkerGlobalScope(GetTopExecutionContext())
+ To<WorkerGlobalScope>(GetTopExecutionContext())
->GetAnimationFrameProvider();
if (animation_frame_provider)
animation_frame_provider->DeregisterOffscreenCanvas(this);
@@ -78,7 +88,7 @@ void OffscreenCanvas::SetPlaceholderCanvasId(DOMNodeId canvas_id) {
if (GetTopExecutionContext() &&
GetTopExecutionContext()->IsWorkerGlobalScope()) {
WorkerAnimationFrameProvider* animation_frame_provider =
- ToWorkerGlobalScope(GetTopExecutionContext())
+ To<WorkerGlobalScope>(GetTopExecutionContext())
->GetAnimationFrameProvider();
if (animation_frame_provider)
animation_frame_provider->RegisterOffscreenCanvas(this);
@@ -107,6 +117,9 @@ void OffscreenCanvas::SetSize(const IntSize& size) {
origin_clean_ = true;
}
}
+ if (size != size_) {
+ UpdateMemoryUsage();
+ }
size_ = size;
if (frame_dispatcher_)
frame_dispatcher_->Reshape(size_);
@@ -116,6 +129,10 @@ void OffscreenCanvas::SetSize(const IntSize& size) {
context_->DidDraw();
}
+void OffscreenCanvas::RecordTransfer() {
+ UMA_HISTOGRAM_BOOLEAN("Blink.OffscreenCanvas.Transferred", true);
+}
+
void OffscreenCanvas::SetNeutered() {
DCHECK(!context_);
is_neutered_ = true;
@@ -138,12 +155,14 @@ ImageBitmap* OffscreenCanvas::transferToImageBitmap(
"OffscreenCanvas with no context");
return nullptr;
}
+
ImageBitmap* image = context_->TransferToImageBitmap(script_state);
if (!image) {
// Undocumented exception (not in spec)
exception_state.ThrowDOMException(DOMExceptionCode::kUnknownError,
"Out of memory");
}
+
return image;
}
@@ -177,7 +196,7 @@ ScriptPromise OffscreenCanvas::CreateImageBitmap(
ScriptState* script_state,
EventTarget&,
base::Optional<IntRect> crop_rect,
- const ImageBitmapOptions& options) {
+ const ImageBitmapOptions* options) {
return ImageBitmapSource::FulfillImageBitmap(
script_state,
IsPaintable() ? ImageBitmap::Create(this, crop_rect, options) : nullptr);
@@ -197,12 +216,18 @@ CanvasRenderingContext* OffscreenCanvas::GetCanvasRenderingContext(
CanvasRenderingContext::ContextTypeFromId(id);
// Unknown type.
- if (context_type == CanvasRenderingContext::kContextTypeCount ||
+ if (context_type == CanvasRenderingContext::kContextTypeUnknown ||
(context_type == CanvasRenderingContext::kContextXRPresent &&
- !OriginTrials::WebXREnabled(execution_context))) {
+ !origin_trials::WebXREnabled(execution_context))) {
return nullptr;
}
+ // Log the aliased context type used.
+ if (!context_) {
+ UMA_HISTOGRAM_ENUMERATION("Blink.OffscreenCanvas.ContextType",
+ context_type);
+ }
+
CanvasRenderingContextFactory* factory =
GetRenderingContextFactory(context_type);
if (!factory)
@@ -224,13 +249,13 @@ CanvasRenderingContext* OffscreenCanvas::GetCanvasRenderingContext(
OffscreenCanvas::ContextFactoryVector&
OffscreenCanvas::RenderingContextFactories() {
DEFINE_STATIC_LOCAL(ContextFactoryVector, context_factories,
- (CanvasRenderingContext::kContextTypeCount));
+ (CanvasRenderingContext::kMaxValue));
return context_factories;
}
CanvasRenderingContextFactory* OffscreenCanvas::GetRenderingContextFactory(
int type) {
- DCHECK_LT(type, CanvasRenderingContext::kContextTypeCount);
+ DCHECK_LE(type, CanvasRenderingContext::kMaxValue);
return RenderingContextFactories()[type].get();
}
@@ -238,7 +263,7 @@ void OffscreenCanvas::RegisterRenderingContextFactory(
std::unique_ptr<CanvasRenderingContextFactory> rendering_context_factory) {
CanvasRenderingContext::ContextType type =
rendering_context_factory->GetContextType();
- DCHECK_LT(type, CanvasRenderingContext::kContextTypeCount);
+ DCHECK_LE(type, CanvasRenderingContext::kMaxValue);
DCHECK(!RenderingContextFactories()[type]);
RenderingContextFactories()[type] = std::move(rendering_context_factory);
}
@@ -397,7 +422,21 @@ FontSelector* OffscreenCanvas::GetFontSelector() {
if (auto* document = DynamicTo<Document>(GetExecutionContext())) {
return document->GetStyleEngine().GetFontSelector();
}
- return ToWorkerGlobalScope(execution_context_)->GetFontSelector();
+ return To<WorkerGlobalScope>(GetExecutionContext())->GetFontSelector();
+}
+
+void OffscreenCanvas::UpdateMemoryUsage() {
+ int bytes_per_pixel = ColorParams().BytesPerPixel();
+
+ base::CheckedNumeric<int32_t> memory_usage_checked = bytes_per_pixel;
+ memory_usage_checked *= Size().Width();
+ memory_usage_checked *= Size().Height();
+ int32_t new_memory_usage =
+ memory_usage_checked.ValueOrDefault(std::numeric_limits<int32_t>::max());
+
+ v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
+ new_memory_usage - memory_usage_);
+ memory_usage_ = new_memory_usage;
}
void OffscreenCanvas::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h b/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h
index ef939251a60..d017fa1d2c8 100644
--- a/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h
+++ b/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h
@@ -47,6 +47,8 @@ class CORE_EXPORT OffscreenCanvas final
public:
static OffscreenCanvas* Create(unsigned width, unsigned height);
+
+ explicit OffscreenCanvas(const IntSize&);
~OffscreenCanvas() override;
void Dispose();
@@ -65,6 +67,7 @@ class CORE_EXPORT OffscreenCanvas final
const IntSize& Size() const override { return size_; }
void SetSize(const IntSize&);
+ void RecordTransfer();
void SetPlaceholderCanvasId(DOMNodeId canvas_id);
DOMNodeId PlaceholderCanvasId() const { return placeholder_canvas_id_; }
@@ -114,14 +117,15 @@ class CORE_EXPORT OffscreenCanvas final
// Partial CanvasResourceHost implementation
void NotifyGpuContextLost() override {}
void SetNeedsCompositingUpdate() override {}
- void UpdateMemoryUsage() override {} // TODO(crbug.com/842693): implement
+ // TODO(fserb): Merge this with HTMLCanvasElement::UpdateMemoryUsage
+ void UpdateMemoryUsage() override;
SkFilterQuality FilterQuality() const override {
return kLow_SkFilterQuality; // TODO(crbug.com/856654)
}
// EventTarget implementation
const AtomicString& InterfaceName() const final {
- return EventTargetNames::OffscreenCanvas;
+ return event_target_names::kOffscreenCanvas;
}
ExecutionContext* GetExecutionContext() const override {
return execution_context_.Get();
@@ -140,7 +144,7 @@ class CORE_EXPORT OffscreenCanvas final
ScriptPromise CreateImageBitmap(ScriptState*,
EventTarget&,
base::Optional<IntRect>,
- const ImageBitmapOptions&) final;
+ const ImageBitmapOptions*) final;
// CanvasImageSource implementation
scoped_refptr<Image> GetSourceImageForCanvas(SourceImageStatus*,
@@ -168,8 +172,9 @@ class CORE_EXPORT OffscreenCanvas final
void Trace(blink::Visitor*) override;
private:
+ int32_t memory_usage_ = 0;
+
friend class OffscreenCanvasTest;
- explicit OffscreenCanvas(const IntSize&);
using ContextFactoryVector =
Vector<std::unique_ptr<CanvasRenderingContextFactory>>;
static ContextFactoryVector& RenderingContextFactories();
diff --git a/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc b/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc
index de5e174a5c1..eedc5e1663c 100644
--- a/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc
+++ b/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc
@@ -108,7 +108,7 @@ OriginTrialContext* OriginTrialContext::FromOrCreate(
OriginTrialContext* origin_trials =
Supplement<ExecutionContext>::From<OriginTrialContext>(context);
if (!origin_trials) {
- origin_trials = new OriginTrialContext(
+ origin_trials = MakeGarbageCollected<OriginTrialContext>(
*context, TrialTokenValidator::Policy()
? std::make_unique<TrialTokenValidator>()
: nullptr);
@@ -238,8 +238,8 @@ bool OriginTrialContext::EnableTrialFromToken(const String& token) {
// to validate the token against the document context.
bool is_secure = false;
ExecutionContext* context = GetSupplementable();
- if (context->IsWorkletGlobalScope()) {
- is_secure = ToWorkletGlobalScope(context)->DocumentSecureContext();
+ if (auto* scope = DynamicTo<WorkletGlobalScope>(context)) {
+ is_secure = scope->DocumentSecureContext();
} else {
is_secure = context->IsSecureContext();
}
@@ -256,8 +256,8 @@ bool OriginTrialContext::EnableTrialFromToken(const String& token) {
}
const SecurityOrigin* origin;
- if (context->IsWorkletGlobalScope())
- origin = ToWorkletGlobalScope(context)->DocumentSecurityOrigin();
+ if (auto* scope = DynamicTo<WorkletGlobalScope>(context))
+ origin = scope->DocumentSecurityOrigin();
else
origin = context->GetSecurityOrigin();
@@ -274,7 +274,7 @@ bool OriginTrialContext::EnableTrialFromToken(const String& token) {
enabled_trials_.insert(trial_name);
// Also enable any trials implied by this trial
Vector<AtomicString> implied_trials =
- OriginTrials::GetImpliedTrials(trial_name);
+ origin_trials::GetImpliedTrials(trial_name);
for (const AtomicString& implied_trial_name : implied_trials) {
enabled_trials_.insert(implied_trial_name);
}
diff --git a/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc b/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc
index fbc748dc092..97b2df1eaa1 100644
--- a/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc
+++ b/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc
@@ -74,9 +74,9 @@ class OriginTrialContextTest : public testing::Test,
protected:
OriginTrialContextTest()
: ScopedOriginTrialsForTest(true),
- execution_context_(new NullExecutionContext()),
+ execution_context_(MakeGarbageCollected<NullExecutionContext>()),
token_validator_(new MockTokenValidator),
- origin_trial_context_(new OriginTrialContext(
+ origin_trial_context_(MakeGarbageCollected<OriginTrialContext>(
*execution_context_,
std::unique_ptr<MockTokenValidator>(token_validator_))),
histogram_tester_(new HistogramTester()) {}
diff --git a/chromium/third_party/blink/renderer/core/page/chrome_client.cc b/chromium/third_party/blink/renderer/core/page/chrome_client.cc
index 1ea9a2938bb..fa1e5f91ffb 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client.cc
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client.cc
@@ -79,9 +79,9 @@ void ChromeClient::SetWindowRectWithAdjustment(const IntRect& pending_rect,
SetWindowRect(window, frame);
}
-bool ChromeClient::CanOpenModalIfDuringPageDismissal(
+bool ChromeClient::CanOpenUIElementIfDuringPageDismissal(
Frame& main_frame,
- ChromeClient::DialogType dialog,
+ UIElementType ui_element_type,
const String& message) {
for (Frame* frame = &main_frame; frame;
frame = frame->Tree().TraverseNext()) {
@@ -91,17 +91,32 @@ bool ChromeClient::CanOpenModalIfDuringPageDismissal(
Document::PageDismissalType dismissal =
local_frame.GetDocument()->PageDismissalEventBeingDispatched();
if (dismissal != Document::kNoDismissal) {
- return ShouldOpenModalDialogDuringPageDismissal(local_frame, dialog,
- message, dismissal);
+ return ShouldOpenUIElementDuringPageDismissal(
+ local_frame, ui_element_type, message, dismissal);
}
}
return true;
}
+Page* ChromeClient::CreateWindow(
+ LocalFrame* frame,
+ const FrameLoadRequest& r,
+ const WebWindowFeatures& features,
+ NavigationPolicy navigation_policy,
+ SandboxFlags sandbox_flags,
+ const SessionStorageNamespaceId& session_storage_namespace_id) {
+ if (!CanOpenUIElementIfDuringPageDismissal(
+ frame->Tree().Top(), UIElementType::kPopup, g_empty_string)) {
+ return nullptr;
+ }
+
+ return CreateWindowDelegate(frame, r, features, navigation_policy,
+ sandbox_flags, session_storage_namespace_id);
+}
+
template <typename Delegate>
static bool OpenJavaScriptDialog(LocalFrame* frame,
const String& message,
- ChromeClient::DialogType dialog_type,
const Delegate& delegate) {
// Suspend pages in case the client method runs a new event loop that would
// otherwise cause the load to continue while we're in the middle of
@@ -117,34 +132,33 @@ bool ChromeClient::OpenBeforeUnloadConfirmPanel(const String& message,
LocalFrame* frame,
bool is_reload) {
DCHECK(frame);
- return OpenJavaScriptDialog(
- frame, message, ChromeClient::kHTMLDialog, [this, frame, is_reload]() {
- return OpenBeforeUnloadConfirmPanelDelegate(frame, is_reload);
- });
+ return OpenJavaScriptDialog(frame, message, [this, frame, is_reload]() {
+ return OpenBeforeUnloadConfirmPanelDelegate(frame, is_reload);
+ });
}
bool ChromeClient::OpenJavaScriptAlert(LocalFrame* frame,
const String& message) {
DCHECK(frame);
- if (!CanOpenModalIfDuringPageDismissal(frame->Tree().Top(),
- ChromeClient::kAlertDialog, message))
+ if (!CanOpenUIElementIfDuringPageDismissal(
+ frame->Tree().Top(), UIElementType::kAlertDialog, message)) {
return false;
- return OpenJavaScriptDialog(
- frame, message, ChromeClient::kAlertDialog, [this, frame, &message]() {
- return OpenJavaScriptAlertDelegate(frame, message);
- });
+ }
+ return OpenJavaScriptDialog(frame, message, [this, frame, &message]() {
+ return OpenJavaScriptAlertDelegate(frame, message);
+ });
}
bool ChromeClient::OpenJavaScriptConfirm(LocalFrame* frame,
const String& message) {
DCHECK(frame);
- if (!CanOpenModalIfDuringPageDismissal(frame->Tree().Top(),
- ChromeClient::kConfirmDialog, message))
+ if (!CanOpenUIElementIfDuringPageDismissal(
+ frame->Tree().Top(), UIElementType::kConfirmDialog, message)) {
return false;
- return OpenJavaScriptDialog(
- frame, message, ChromeClient::kConfirmDialog, [this, frame, &message]() {
- return OpenJavaScriptConfirmDelegate(frame, message);
- });
+ }
+ return OpenJavaScriptDialog(frame, message, [this, frame, &message]() {
+ return OpenJavaScriptConfirmDelegate(frame, message);
+ });
}
bool ChromeClient::OpenJavaScriptPrompt(LocalFrame* frame,
@@ -152,12 +166,12 @@ bool ChromeClient::OpenJavaScriptPrompt(LocalFrame* frame,
const String& default_value,
String& result) {
DCHECK(frame);
- if (!CanOpenModalIfDuringPageDismissal(frame->Tree().Top(),
- ChromeClient::kPromptDialog, prompt))
+ if (!CanOpenUIElementIfDuringPageDismissal(
+ frame->Tree().Top(), UIElementType::kPromptDialog, prompt)) {
return false;
+ }
return OpenJavaScriptDialog(
- frame, prompt, ChromeClient::kPromptDialog,
- [this, frame, &prompt, &default_value, &result]() {
+ frame, prompt, [this, frame, &prompt, &default_value, &result]() {
return OpenJavaScriptPromptDelegate(frame, prompt, default_value,
result);
});
@@ -229,8 +243,9 @@ void ChromeClient::ClearToolTip(LocalFrame& frame) {
}
bool ChromeClient::Print(LocalFrame* frame) {
- if (!CanOpenModalIfDuringPageDismissal(*frame->GetPage()->MainFrame(),
- ChromeClient::kPrintDialog, "")) {
+ if (!CanOpenUIElementIfDuringPageDismissal(*frame->GetPage()->MainFrame(),
+ UIElementType::kPrintDialog,
+ g_empty_string)) {
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/page/chrome_client.h b/chromium/third_party/blink/renderer/core/page/chrome_client.h
index 4a73f8db9b4..2d4ca195777 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client.h
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client.h
@@ -24,9 +24,11 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_CHROME_CLIENT_H_
#include <memory>
+
#include "base/gtest_prod_util.h"
#include "base/optional.h"
#include "cc/input/event_listener_properties.h"
+#include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h"
#include "third_party/blink/public/platform/blame_context.h"
#include "third_party/blink/public/platform/web_drag_operation.h"
#include "third_party/blink/public/platform/web_focus_type.h"
@@ -89,7 +91,6 @@ struct DateTimeChooserParameters;
struct FrameLoadRequest;
struct ViewportDescription;
struct WebCursorInfo;
-struct WebPoint;
struct WebScreenInfo;
struct WebWindowFeatures;
@@ -140,7 +141,7 @@ class CORE_EXPORT ChromeClient
const WebDragData&,
WebDragOperationsMask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset) = 0;
+ const gfx::Point& drag_image_offset) = 0;
virtual bool AcceptsLoadDrops() const = 0;
// The LocalFrame pointer provides the ChromeClient with context about which
@@ -149,11 +150,12 @@ class CORE_EXPORT ChromeClient
// created Page has its show method called.
// The FrameLoadRequest parameter is only for ChromeClient to check if the
// request could be fulfilled. The ChromeClient should not load the request.
- virtual Page* CreateWindow(LocalFrame*,
- const FrameLoadRequest&,
- const WebWindowFeatures&,
- NavigationPolicy,
- SandboxFlags) = 0;
+ Page* CreateWindow(LocalFrame*,
+ const FrameLoadRequest&,
+ const WebWindowFeatures&,
+ NavigationPolicy,
+ SandboxFlags,
+ const SessionStorageNamespaceId&);
virtual void Show(NavigationPolicy) = 0;
// All the parameters should be in viewport space. That is, if an event
@@ -217,6 +219,8 @@ class CORE_EXPORT ChromeClient
virtual void DispatchViewportPropertiesDidChange(
const ViewportDescription&) const {}
+ virtual bool DoubleTapToZoomEnabled() const { return false; }
+
virtual void ContentsSizeChanged(LocalFrame*, const IntSize&) const = 0;
virtual void PageScaleFactorChanged() const {}
virtual float ClampPageScaleFactorToLimits(float scale) const {
@@ -253,10 +257,6 @@ class CORE_EXPORT ChromeClient
virtual void OpenFileChooser(LocalFrame*, scoped_refptr<FileChooser>) = 0;
- // Asychronous request to enumerate all files in a directory chosen by the
- // user.
- virtual void EnumerateChosenDirectory(FileChooser*) = 0;
-
// Pass nullptr as the GraphicsLayer to detach the root layer.
// This sets the graphics layer for the LocalFrame's WebWidget, if it has
// one. Otherwise it sets it for the WebViewImpl.
@@ -274,7 +274,7 @@ class CORE_EXPORT ChromeClient
virtual void DetachCompositorAnimationTimeline(CompositorAnimationTimeline*,
LocalFrame* local_root) {}
- virtual void EnterFullscreen(LocalFrame&, const FullscreenOptions&) {}
+ virtual void EnterFullscreen(LocalFrame&, const FullscreenOptions*) {}
virtual void ExitFullscreen(LocalFrame&) {}
virtual void FullscreenElementChanged(Element* old_element,
Element* new_element) {}
@@ -307,19 +307,19 @@ class CORE_EXPORT ChromeClient
virtual String AcceptLanguages() = 0;
- enum DialogType {
+ enum class UIElementType {
kAlertDialog = 0,
kConfirmDialog = 1,
kPromptDialog = 2,
- kHTMLDialog = 3,
- kPrintDialog = 4
+ kPrintDialog = 3,
+ kPopup = 4
};
- virtual bool ShouldOpenModalDialogDuringPageDismissal(
+ virtual bool ShouldOpenUIElementDuringPageDismissal(
LocalFrame&,
- DialogType,
+ UIElementType,
const String&,
Document::PageDismissalType) const {
- return true;
+ return false;
}
virtual bool IsSVGImageChromeClient() const { return false; }
@@ -384,11 +384,17 @@ class CORE_EXPORT ChromeClient
const String& default_value,
String& result) = 0;
virtual void PrintDelegate(LocalFrame*) = 0;
+ virtual Page* CreateWindowDelegate(LocalFrame*,
+ const FrameLoadRequest&,
+ const WebWindowFeatures&,
+ NavigationPolicy,
+ SandboxFlags,
+ const SessionStorageNamespaceId&) = 0;
private:
- bool CanOpenModalIfDuringPageDismissal(Frame& main_frame,
- DialogType,
- const String& message);
+ bool CanOpenUIElementIfDuringPageDismissal(Frame& main_frame,
+ UIElementType,
+ const String& message);
void SetToolTip(LocalFrame&, const HitTestLocation&, const HitTestResult&);
WeakMember<Node> last_mouse_over_node_;
diff --git a/chromium/third_party/blink/renderer/core/page/chrome_client_impl.cc b/chromium/third_party/blink/renderer/core/page/chrome_client_impl.cc
index c34ed3622f3..c7b9280cc19 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client_impl.cc
@@ -97,8 +97,8 @@
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
@@ -109,18 +109,18 @@ namespace blink {
namespace {
-const char* DialogTypeToString(ChromeClient::DialogType dialog_type) {
- switch (dialog_type) {
- case ChromeClient::kAlertDialog:
+const char* UIElementTypeToString(ChromeClient::UIElementType ui_element_type) {
+ switch (ui_element_type) {
+ case ChromeClient::UIElementType::kAlertDialog:
return "alert";
- case ChromeClient::kConfirmDialog:
+ case ChromeClient::UIElementType::kConfirmDialog:
return "confirm";
- case ChromeClient::kPromptDialog:
+ case ChromeClient::UIElementType::kPromptDialog:
return "prompt";
- case ChromeClient::kPrintDialog:
+ case ChromeClient::UIElementType::kPrintDialog:
return "print";
- case ChromeClient::kHTMLDialog:
- NOTREACHED();
+ case ChromeClient::UIElementType::kPopup:
+ return "popup";
}
NOTREACHED();
return "";
@@ -211,7 +211,7 @@ void ChromeClientImpl::Focus(LocalFrame* calling_frame) {
bool ChromeClientImpl::CanTakeFocus(WebFocusType) {
// For now the browser can always take focus if we're not running layout
// tests.
- return !LayoutTestSupport::IsRunningLayoutTest();
+ return !WebTestSupport::IsRunningWebTest();
}
void ChromeClientImpl::TakeFocus(WebFocusType type) {
@@ -245,9 +245,10 @@ void ChromeClientImpl::StartDragging(LocalFrame* frame,
const WebDragData& drag_data,
WebDragOperationsMask mask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset) {
+ const gfx::Point& drag_image_offset) {
WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame);
- WebReferrerPolicy policy = web_frame->GetDocument().GetReferrerPolicy();
+ network::mojom::ReferrerPolicy policy =
+ web_frame->GetDocument().GetReferrerPolicy();
web_frame->LocalRootFrameWidget()->StartDragging(
policy, drag_data, mask, drag_image, drag_image_offset);
}
@@ -256,11 +257,13 @@ bool ChromeClientImpl::AcceptsLoadDrops() const {
return !web_view_->Client() || web_view_->Client()->AcceptsLoadDrops();
}
-Page* ChromeClientImpl::CreateWindow(LocalFrame* frame,
- const FrameLoadRequest& r,
- const WebWindowFeatures& features,
- NavigationPolicy navigation_policy,
- SandboxFlags sandbox_flags) {
+Page* ChromeClientImpl::CreateWindowDelegate(
+ LocalFrame* frame,
+ const FrameLoadRequest& r,
+ const WebWindowFeatures& features,
+ NavigationPolicy navigation_policy,
+ SandboxFlags sandbox_flags,
+ const SessionStorageNamespaceId& session_storage_namespace_id) {
if (!web_view_->Client())
return nullptr;
@@ -277,7 +280,8 @@ Page* ChromeClientImpl::CreateWindow(LocalFrame* frame,
WrappedResourceRequest(r.GetResourceRequest()), features, frame_name,
static_cast<WebNavigationPolicy>(navigation_policy),
r.GetShouldSetOpener() == kNeverSetOpener,
- static_cast<WebSandboxFlags>(sandbox_flags)));
+ static_cast<WebSandboxFlags>(sandbox_flags),
+ session_storage_namespace_id));
if (!new_view)
return nullptr;
return new_view->GetPage();
@@ -445,9 +449,9 @@ float ChromeClientImpl::WindowToViewportScalar(const float scalar_value) const {
}
WebScreenInfo ChromeClientImpl::GetScreenInfo() const {
- if (!web_view_->WidgetClient())
+ if (!web_view_->Client())
return {};
- return web_view_->WidgetClient()->GetScreenInfo();
+ return web_view_->Client()->GetScreenInfo();
}
base::Optional<IntRect> ChromeClientImpl::VisibleContentRectForPainting()
@@ -463,6 +467,10 @@ void ChromeClientImpl::ContentsSizeChanged(LocalFrame* frame,
webframe->DidChangeContentsSize(size);
}
+bool ChromeClientImpl::DoubleTapToZoomEnabled() const {
+ return web_view_->SettingsImpl()->DoubleTapToZoomEnabled();
+}
+
void ChromeClientImpl::PageScaleFactorChanged() const {
web_view_->PageScaleFactorChanged();
}
@@ -628,18 +636,6 @@ void ChromeClientImpl::DidCompleteFileChooser(FileChooser& chooser) {
DidCompleteFileChooser(*next_chooser);
}
-void ChromeClientImpl::EnumerateChosenDirectory(FileChooser* file_chooser) {
- WebViewClient* client = web_view_->Client();
- if (!client)
- return;
-
- DCHECK(file_chooser);
- DCHECK(file_chooser->Params().selected_files.size());
- if (client->EnumerateChosenDirectory(file_chooser->Params().selected_files[0],
- file_chooser))
- file_chooser->AddRef();
-}
-
Cursor ChromeClientImpl::LastSetCursorForTesting() const {
return last_set_mouse_cursor_for_testing_;
}
@@ -759,7 +755,7 @@ void ChromeClientImpl::DetachCompositorAnimationTimeline(
}
void ChromeClientImpl::EnterFullscreen(LocalFrame& frame,
- const FullscreenOptions& options) {
+ const FullscreenOptions* options) {
web_view_->EnterFullscreen(frame, options);
}
@@ -806,7 +802,7 @@ PopupMenu* ChromeClientImpl::OpenPopupMenu(LocalFrame& frame,
HTMLSelectElement& select) {
NotifyPopupOpeningObservers();
if (WebViewImpl::UseExternalPopupMenus())
- return new ExternalPopupMenu(frame, select, *web_view_);
+ return MakeGarbageCollected<ExternalPopupMenu>(frame, select, *web_view_);
DCHECK(RuntimeEnabledFeatures::PagePopupEnabled());
return InternalPopupMenu::Create(this, select);
@@ -839,16 +835,25 @@ void ChromeClientImpl::SetBrowserControlsShownRatio(float ratio) {
web_view_->GetBrowserControls().SetShownRatio(ratio);
}
-bool ChromeClientImpl::ShouldOpenModalDialogDuringPageDismissal(
+bool ChromeClientImpl::ShouldOpenUIElementDuringPageDismissal(
LocalFrame& frame,
- DialogType dialog_type,
+ UIElementType ui_element_type,
const String& dialog_message,
Document::PageDismissalType dismissal_type) const {
- String message = String("Blocked ") + DialogTypeToString(dialog_type) + "('" +
- dialog_message + "') during " +
- DismissalTypeToString(dismissal_type) + ".";
+ StringBuilder builder;
+ builder.Append("Blocked ");
+ builder.Append(UIElementTypeToString(ui_element_type));
+ if (dialog_message.length()) {
+ builder.Append("('");
+ builder.Append(dialog_message);
+ builder.Append("')");
+ }
+ builder.Append(" during ");
+ builder.Append(DismissalTypeToString(dismissal_type));
+ builder.Append(".");
+
WebLocalFrameImpl::FromFrame(frame)->AddMessageToConsole(
- WebConsoleMessage(WebConsoleMessage::kLevelError, message));
+ WebConsoleMessage(WebConsoleMessage::kLevelError, builder.ToString()));
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/page/chrome_client_impl.h b/chromium/third_party/blink/renderer/core/page/chrome_client_impl.h
index 9b6d78e6952..56efb15ca6b 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client_impl.h
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client_impl.h
@@ -71,13 +71,14 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
const WebDragData&,
WebDragOperationsMask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset) override;
+ const gfx::Point& drag_image_offset) override;
bool AcceptsLoadDrops() const override;
- Page* CreateWindow(LocalFrame*,
- const FrameLoadRequest&,
- const WebWindowFeatures&,
- NavigationPolicy,
- SandboxFlags) override;
+ Page* CreateWindowDelegate(LocalFrame*,
+ const FrameLoadRequest&,
+ const WebWindowFeatures&,
+ NavigationPolicy,
+ SandboxFlags,
+ const SessionStorageNamespaceId&) override;
void Show(NavigationPolicy) override;
void DidOverscroll(const FloatSize& overscroll_delta,
const FloatSize& accumulated_overscroll,
@@ -112,6 +113,7 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
WebScreenInfo GetScreenInfo() const override;
base::Optional<IntRect> VisibleContentRectForPainting() const override;
void ContentsSizeChanged(LocalFrame*, const IntSize&) const override;
+ bool DoubleTapToZoomEnabled() const override;
void PageScaleFactorChanged() const override;
float ClampPageScaleFactorToLimits(float scale) const override;
void MainFrameScrollOffsetChanged() const override;
@@ -129,7 +131,6 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
DateTimeChooserClient*,
const DateTimeChooserParameters&) override;
void OpenFileChooser(LocalFrame*, scoped_refptr<FileChooser>) override;
- void EnumerateChosenDirectory(FileChooser*) override;
void SetCursor(const Cursor&, LocalFrame*) override;
void SetCursorOverridden(bool) override;
Cursor LastSetCursorForTesting() const override;
@@ -160,7 +161,7 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
void DetachCompositorAnimationTimeline(CompositorAnimationTimeline*,
LocalFrame*) override;
- void EnterFullscreen(LocalFrame&, const FullscreenOptions&) override;
+ void EnterFullscreen(LocalFrame&, const FullscreenOptions*) override;
void ExitFullscreen(LocalFrame&) override;
void FullscreenElementChanged(Element* old_element,
Element* new_element) override;
@@ -194,9 +195,9 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
bool shrinks_layout) override;
void SetBrowserControlsShownRatio(float) override;
- bool ShouldOpenModalDialogDuringPageDismissal(
+ bool ShouldOpenUIElementDuringPageDismissal(
LocalFrame&,
- DialogType,
+ UIElementType,
const String& dialog_message,
Document::PageDismissalType) const override;
diff --git a/chromium/third_party/blink/renderer/core/page/chrome_client_impl_test.cc b/chromium/third_party/blink/renderer/core/page/chrome_client_impl_test.cc
index 00f9d73834f..ed4769d0e73 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client_impl_test.cc
@@ -44,6 +44,7 @@
#include "third_party/blink/renderer/core/html/forms/date_time_chooser_client.h"
#include "third_party/blink/renderer/core/html/forms/file_chooser.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
+#include "third_party/blink/renderer/core/html/forms/mock_file_chooser.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scoped_page_pauser.h"
@@ -54,7 +55,7 @@ namespace blink {
namespace {
-class TestWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class TestWebViewClient : public frame_test_helpers::TestWebViewClient {
public:
explicit TestWebViewClient(WebNavigationPolicy* target) : target_(target) {}
~TestWebViewClient() override = default;
@@ -67,7 +68,7 @@ class TestWebViewClient : public FrameTestHelpers::TestWebViewClient {
} // anonymous namespace
-class ViewCreatingClient : public FrameTestHelpers::TestWebViewClient {
+class ViewCreatingClient : public frame_test_helpers::TestWebViewClient {
public:
WebView* CreateView(WebLocalFrame* opener,
const WebURLRequest&,
@@ -75,12 +76,13 @@ class ViewCreatingClient : public FrameTestHelpers::TestWebViewClient {
const WebString& name,
WebNavigationPolicy,
bool,
- WebSandboxFlags) override {
+ WebSandboxFlags,
+ const SessionStorageNamespaceId&) override {
return web_view_helper_.InitializeWithOpener(opener);
}
private:
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
class CreateWindowTest : public testing::Test {
@@ -93,7 +95,7 @@ class CreateWindowTest : public testing::Test {
}
ViewCreatingClient web_view_client_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
WebViewImpl* web_view_;
WebLocalFrame* main_frame_;
Persistent<ChromeClientImpl> chrome_client_impl_;
@@ -106,7 +108,7 @@ TEST_F(CreateWindowTest, CreateWindowFromPausedPage) {
WebWindowFeatures features;
EXPECT_EQ(nullptr, chrome_client_impl_->CreateWindow(
frame, request, features,
- kNavigationPolicyNewForegroundTab, kSandboxNone));
+ kNavigationPolicyNewForegroundTab, kSandboxNone, ""));
}
class FakeColorChooserClient
@@ -197,15 +199,15 @@ class PagePopupSuppressionTest : public testing::Test {
chrome_client_impl_ =
ToChromeClientImpl(&web_view_->GetPage()->GetChromeClient());
LocalFrame* frame = helper_.LocalMainFrame()->GetFrame();
- color_chooser_client_ =
- new FakeColorChooserClient(frame->GetDocument()->documentElement());
- date_time_chooser_client_ =
- new FakeDateTimeChooserClient(frame->GetDocument()->documentElement());
+ color_chooser_client_ = MakeGarbageCollected<FakeColorChooserClient>(
+ frame->GetDocument()->documentElement());
+ date_time_chooser_client_ = MakeGarbageCollected<FakeDateTimeChooserClient>(
+ frame->GetDocument()->documentElement());
select_ = HTMLSelectElement::Create(*(frame->GetDocument()));
}
protected:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
WebViewImpl* web_view_;
Persistent<WebLocalFrameImpl> main_frame_;
Persistent<ChromeClientImpl> chrome_client_impl_;
@@ -240,14 +242,6 @@ TEST_F(PagePopupSuppressionTest, SuppressDateTimeChooser) {
EXPECT_TRUE(CanOpenDateTimeChooser());
}
-// A WebLocalFrameClient which makes FileChooser::OpenFileChooser() success.
-class FrameClientForFileChooser : public FrameTestHelpers::TestWebFrameClient {
- bool RunFileChooser(const WebFileChooserParams& params,
- WebFileChooserCompletion* chooser_completion) override {
- return true;
- }
-};
-
// A FileChooserClient which makes FileChooser::OpenFileChooser() success.
class MockFileChooserClient
: public GarbageCollectedFinalized<MockFileChooserClient>,
@@ -263,7 +257,7 @@ class MockFileChooserClient
private:
// FilesChosen() and WillOpenPopup() are never called in the test.
- void FilesChosen(const FileChooserFileInfoList&) override {}
+ void FilesChosen(FileChooserFileInfoList, const base::FilePath&) override {}
void WillOpenPopup() override {}
LocalFrame* FrameOrNull() const override { return frame_; }
@@ -274,30 +268,41 @@ class MockFileChooserClient
class FileChooserQueueTest : public testing::Test {
protected:
void SetUp() override {
- web_view_ = helper_.Initialize(&frame_client_);
+ web_view_ = helper_.Initialize();
chrome_client_impl_ =
ToChromeClientImpl(&web_view_->GetPage()->GetChromeClient());
}
- FrameTestHelpers::WebViewHelper helper_;
- FrameClientForFileChooser frame_client_;
+ frame_test_helpers::WebViewHelper helper_;
WebViewImpl* web_view_;
Persistent<ChromeClientImpl> chrome_client_impl_;
};
TEST_F(FileChooserQueueTest, DerefQueuedChooser) {
LocalFrame* frame = helper_.LocalMainFrame()->GetFrame();
- auto* client = new MockFileChooserClient(frame);
- WebFileChooserParams params;
- scoped_refptr<FileChooser> chooser1 = FileChooser::Create(client, params);
- scoped_refptr<FileChooser> chooser2 = FileChooser::Create(client, params);
+ base::RunLoop run_loop;
+ MockFileChooser chooser(&frame->GetInterfaceProvider(),
+ run_loop.QuitClosure());
+ auto* client1 = MakeGarbageCollected<MockFileChooserClient>(frame);
+ auto* client2 = MakeGarbageCollected<MockFileChooserClient>(frame);
+ mojom::blink::FileChooserParams params;
+ params.title = g_empty_string;
+ scoped_refptr<FileChooser> chooser1 = FileChooser::Create(client1, params);
+ scoped_refptr<FileChooser> chooser2 = FileChooser::Create(client2, params);
chrome_client_impl_->OpenFileChooser(frame, chooser1);
chrome_client_impl_->OpenFileChooser(frame, chooser2);
EXPECT_EQ(2u, chrome_client_impl_->file_chooser_queue_.size());
chooser2.reset();
- chrome_client_impl_->DidCompleteFileChooser(*chooser1);
+
+ // Kicks ChromeClientImpl::DidCompleteFileChooser() for chooser1.
+ run_loop.Run();
+ chooser.ResponseOnOpenFileChooser(FileChooserFileInfoList());
+
EXPECT_EQ(1u, chrome_client_impl_->file_chooser_queue_.size());
+
+ // Cleanup for the second OpenFileChooser request.
+ chooser.ResponseOnOpenFileChooser(FileChooserFileInfoList());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/chrome_client_test.cc b/chromium/third_party/blink/renderer/core/page/chrome_client_test.cc
index baf63b22199..6ecf7bdfb34 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client_test.cc
@@ -42,8 +42,8 @@ TEST_F(ChromeClientTest, SetToolTipFlood) {
HitTestLocation location(LayoutPoint(10, 20));
HitTestResult result(HitTestRequest(HitTestRequest::kMove), location);
Document* doc = Document::CreateForTest();
- Element* element = HTMLElement::Create(HTMLNames::divTag, *doc);
- element->setAttribute(HTMLNames::titleAttr, "tooltip");
+ Element* element = HTMLElement::Create(html_names::kDivTag, *doc);
+ element->setAttribute(html_names::kTitleAttr, "tooltip");
result.SetInnerNode(element);
client->SetToolTip(*doc->GetFrame(), location, result);
@@ -63,7 +63,7 @@ TEST_F(ChromeClientTest, SetToolTipFlood) {
EXPECT_EQ(String(), logger.ToolTipForLastSetToolTip());
logger.ClearToolTipForLastSetToolTip();
- element->setAttribute(HTMLNames::titleAttr, "updated");
+ element->setAttribute(html_names::kTitleAttr, "updated");
client->SetToolTip(*doc->GetFrame(), location, result);
// setToolTip(String,TextDirection) should be called because tooltip string
// is different from the last one.
@@ -76,24 +76,24 @@ TEST_F(ChromeClientTest, SetToolTipEmptyString) {
HitTestResult result(HitTestRequest(HitTestRequest::kMove), location);
auto& doc = *Document::CreateForTest();
auto& input_element = *HTMLInputElement::Create(doc, CreateElementFlags());
- input_element.setAttribute(HTMLNames::typeAttr, "file");
+ input_element.setAttribute(html_names::kTypeAttr, "file");
result.SetInnerNode(&input_element);
client->SetToolTip(*doc.GetFrame(), location, result);
EXPECT_EQ("<<NoFileChosenLabel>>", client->last_tool_tip_text_);
client->last_tool_tip_text_ = String();
- input_element.removeAttribute(HTMLNames::titleAttr);
+ input_element.removeAttribute(html_names::kTitleAttr);
client->SetToolTip(*doc.GetFrame(), location, result);
EXPECT_EQ("<<NoFileChosenLabel>>", client->last_tool_tip_text_);
client->last_tool_tip_text_ = String();
- input_element.setAttribute(HTMLNames::titleAttr, g_empty_atom);
+ input_element.setAttribute(html_names::kTitleAttr, g_empty_atom);
client->SetToolTip(*doc.GetFrame(), location, result);
EXPECT_EQ(g_empty_atom, client->last_tool_tip_text_);
client->last_tool_tip_text_ = String();
- input_element.setAttribute(HTMLNames::titleAttr, "test");
+ input_element.setAttribute(html_names::kTitleAttr, "test");
client->SetToolTip(*doc.GetFrame(), location, result);
EXPECT_EQ("test", client->last_tool_tip_text_);
}
diff --git a/chromium/third_party/blink/renderer/core/page/context_menu_controller.cc b/chromium/third_party/blink/renderer/core/page/context_menu_controller.cc
index 24833832a53..62b59a9f0c7 100644
--- a/chromium/third_party/blink/renderer/core/page/context_menu_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/context_menu_controller.cc
@@ -98,7 +98,7 @@ void ContextMenuController::DocumentDetached(Document* document) {
}
void ContextMenuController::HandleContextMenuEvent(MouseEvent* mouse_event) {
- DCHECK(mouse_event->type() == EventTypeNames::contextmenu);
+ DCHECK(mouse_event->type() == event_type_names::kContextmenu);
LocalFrame* frame = mouse_event->target()->ToNode()->GetDocument().GetFrame();
LayoutPoint location(mouse_event->AbsoluteLocation());
if (ShowContextMenu(frame, location, mouse_event->GetMenuSourceType()))
@@ -388,7 +388,7 @@ bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
data.selection_start_offset = range.StartOffset();
// TODO(crbug.com/850954): Remove redundant log after we identified the
// issue.
- DCHECK_GE(data.selection_start_offset, 0)
+ CHECK_GE(data.selection_start_offset, 0)
<< "Log issue against https://crbug.com/850954\n"
<< "data.selection_start_offset: " << data.selection_start_offset
<< "\nrange: [" << range.StartOffset() << ", " << range.EndOffset()
@@ -432,8 +432,7 @@ bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
WebContextMenuData::kCheckableMenuItemChecked;
}
- data.referrer_policy = static_cast<WebReferrerPolicy>(
- selected_frame->GetDocument()->GetReferrerPolicy());
+ data.referrer_policy = selected_frame->GetDocument()->GetReferrerPolicy();
if (menu_provider_) {
// Filter out custom menu elements and add them into the data.
@@ -446,24 +445,24 @@ bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
selected_frame->GetSecurityContext()->GetSecurityOrigin();
if (origin->CanReadContent(anchor->Url())) {
data.suggested_filename =
- anchor->FastGetAttribute(HTMLNames::downloadAttr);
+ anchor->FastGetAttribute(html_names::kDownloadAttr);
}
// If the anchor wants to suppress the referrer, update the referrerPolicy
// accordingly.
if (anchor->HasRel(kRelationNoReferrer))
- data.referrer_policy = kWebReferrerPolicyNever;
+ data.referrer_policy = network::mojom::ReferrerPolicy::kNever;
data.link_text = anchor->innerText();
}
// Find the input field type.
if (auto* input = ToHTMLInputElementOrNull(result.InnerNode())) {
- if (input->type() == InputTypeNames::password)
+ if (input->type() == input_type_names::kPassword)
data.input_field_type = WebContextMenuData::kInputFieldTypePassword;
- else if (input->type() == InputTypeNames::number)
+ else if (input->type() == input_type_names::kNumber)
data.input_field_type = WebContextMenuData::kInputFieldTypeNumber;
- else if (input->type() == InputTypeNames::tel)
+ else if (input->type() == input_type_names::kTel)
data.input_field_type = WebContextMenuData::kInputFieldTypeTelephone;
else if (input->IsTextField())
data.input_field_type = WebContextMenuData::kInputFieldTypePlainText;
diff --git a/chromium/third_party/blink/renderer/core/page/context_menu_controller_test.cc b/chromium/third_party/blink/renderer/core/page/context_menu_controller_test.cc
index 708b9388f88..4090b43d062 100644
--- a/chromium/third_party/blink/renderer/core/page/context_menu_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/context_menu_controller_test.cc
@@ -35,7 +35,7 @@ class MockWebMediaPlayerForContextMenu : public EmptyWebMediaPlayer {
}
};
-class TestWebFrameClientImpl : public FrameTestHelpers::TestWebFrameClient {
+class TestWebFrameClientImpl : public frame_test_helpers::TestWebFrameClient {
public:
void ShowContextMenu(const WebContextMenuData& data) override {
context_menu_data_ = data;
@@ -66,8 +66,9 @@ class ContextMenuControllerTest : public testing::Test {
web_view_helper_.Initialize(&web_frame_client_);
WebLocalFrameImpl* local_main_frame = web_view_helper_.LocalMainFrame();
- local_main_frame->ViewImpl()->Resize(WebSize(640, 480));
- local_main_frame->ViewImpl()->UpdateAllLifecyclePhases();
+ local_main_frame->ViewImpl()->MainFrameWidget()->Resize(WebSize(640, 480));
+ local_main_frame->ViewImpl()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
bool ShowContextMenu(const LayoutPoint& location, WebMenuSourceType source) {
@@ -97,7 +98,7 @@ class ContextMenuControllerTest : public testing::Test {
private:
TestWebFrameClientImpl web_frame_client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
TEST_F(ContextMenuControllerTest, VideoNotLoaded) {
diff --git a/chromium/third_party/blink/renderer/core/page/create_window.cc b/chromium/third_party/blink/renderer/core/page/create_window.cc
index 94645c02b03..cfc96f5cf57 100644
--- a/chromium/third_party/blink/renderer/core/page/create_window.cc
+++ b/chromium/third_party/blink/renderer/core/page/create_window.cc
@@ -26,12 +26,18 @@
#include "third_party/blink/renderer/core/page/create_window.h"
+#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/network/public/mojom/request_context_frame_type.mojom-blink.h"
+#include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h"
+#include "third_party/blink/public/common/features.h"
+#include "third_party/blink/public/common/frame/from_ad_state.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/public/web/web_view_client.h"
#include "third_party/blink/public/web/web_window_features.h"
+#include "third_party/blink/renderer/core/core_initializer.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/events/current_input_event.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
@@ -42,6 +48,7 @@
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
+#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
@@ -199,33 +206,17 @@ static Frame* ReuseExistingWindow(LocalFrame& active_frame,
return nullptr;
}
-enum class WindowOpenFromAdState {
- // This is used for a UMA histogram. Please never alter existing values, only
- // append new ones and make sure to update enums.xml.
- kAdScriptAndAdFrame = 0,
- kNonAdScriptAndAdFrame = 1,
- kAdScriptAndNonAdFrame = 2,
- kNonAdScriptAndNonAdFrame = 3,
- kMaxValue = kNonAdScriptAndNonAdFrame,
-};
-
static void MaybeLogWindowOpen(LocalFrame& opener_frame) {
AdTracker* ad_tracker = opener_frame.GetAdTracker();
- if (!ad_tracker) {
+ if (!ad_tracker)
return;
- }
bool is_ad_subframe = opener_frame.IsAdSubframe();
bool is_ad_script_in_stack = ad_tracker->IsAdScriptInStack();
+ FromAdState state =
+ blink::GetFromAdState(is_ad_subframe, is_ad_script_in_stack);
// Log to UMA.
- WindowOpenFromAdState state =
- is_ad_subframe ? (is_ad_script_in_stack
- ? WindowOpenFromAdState::kAdScriptAndAdFrame
- : WindowOpenFromAdState::kNonAdScriptAndAdFrame)
- : (is_ad_script_in_stack
- ? WindowOpenFromAdState::kAdScriptAndNonAdFrame
- : WindowOpenFromAdState::kNonAdScriptAndNonAdFrame);
UMA_HISTOGRAM_ENUMERATION("Blink.WindowOpen.FromAdState", state);
// Log to UKM.
@@ -258,8 +249,20 @@ static Frame* CreateNewWindow(LocalFrame& opener_frame,
? opener_frame.GetSecurityContext()->GetSandboxFlags()
: kSandboxNone;
+ SessionStorageNamespaceId new_namespace_id =
+ AllocateSessionStorageNamespaceId();
+
+ if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) {
+ // TODO(dmurph): Don't copy session storage when features.noopener is true:
+ // https://html.spec.whatwg.org/multipage/browsers.html#copy-session-storage
+ // https://crbug.com/771959
+ CoreInitializer::GetInstance().CloneSessionStorage(old_page,
+ new_namespace_id);
+ }
+
Page* page = old_page->GetChromeClient().CreateWindow(
- &opener_frame, request, features, policy, sandbox_flags);
+ &opener_frame, request, features, policy, sandbox_flags,
+ new_namespace_id);
if (!page)
return nullptr;
@@ -484,7 +487,8 @@ void CreateWindowForRequest(const FrameLoadRequest& request,
if (!new_frame)
return;
if (request.GetShouldSendReferrer() == kMaybeSendReferrer) {
- // TODO(japhet): Does ReferrerPolicy need to be proagated for RemoteFrames?
+ // TODO(japhet): Does network::mojom::ReferrerPolicy need to be proagated
+ // for RemoteFrames?
if (new_frame->IsLocalFrame())
ToLocalFrame(new_frame)->GetDocument()->SetReferrerPolicy(
opener_frame.GetDocument()->GetReferrerPolicy());
diff --git a/chromium/third_party/blink/renderer/core/page/drag_controller.cc b/chromium/third_party/blink/renderer/core/page/drag_controller.cc
index 7b0d5eb0c9f..d27010367a1 100644
--- a/chromium/third_party/blink/renderer/core/page/drag_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/drag_controller.cc
@@ -43,6 +43,7 @@
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/node.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
@@ -149,7 +150,7 @@ DragController::DragController(Page* page)
did_initiate_drag_(false) {}
DragController* DragController::Create(Page* page) {
- return new DragController(page);
+ return MakeGarbageCollected<DragController>(page);
}
static DocumentFragment* DocumentFragmentFromDragData(
@@ -207,9 +208,7 @@ bool DragController::DragIsMove(FrameSelection& selection,
!IsCopyKeyDown(drag_data);
}
-// FIXME: This method is poorly named. We're just clearing the selection from
-// the document this drag is exiting.
-void DragController::CancelDrag() {
+void DragController::ClearDragCaret() {
page_->GetDragCaret().Clear();
}
@@ -277,7 +276,7 @@ void DragController::PerformDrag(DragData* drag_data, LocalFrame& local_root) {
}
if (prevented_default) {
document_under_mouse_ = nullptr;
- CancelDrag();
+ ClearDragCaret();
return;
}
}
@@ -318,7 +317,7 @@ void DragController::MouseMovedIntoDocument(Document* new_document) {
// If we were over another document clear the selection
if (document_under_mouse_)
- CancelDrag();
+ ClearDragCaret();
document_under_mouse_ = new_document;
}
@@ -349,7 +348,7 @@ static HTMLInputElement* AsFileInput(Node* node) {
DCHECK(node);
for (; node; node = node->OwnerShadowHost()) {
if (IsHTMLInputElement(*node) &&
- ToHTMLInputElement(node)->type() == InputTypeNames::file)
+ ToHTMLInputElement(node)->type() == input_type_names::kFile)
return ToHTMLInputElement(node);
}
return nullptr;
@@ -1055,11 +1054,12 @@ static std::unique_ptr<DragImage> DragImageForImage(
image = svg_image.get();
}
- InterpolationQuality interpolation_quality =
- element->EnsureComputedStyle()->ImageRendering() ==
- EImageRendering::kPixelated
- ? kInterpolationNone
- : kInterpolationDefault;
+ InterpolationQuality interpolation_quality = kInterpolationDefault;
+ if (const ComputedStyle* style = element->GetComputedStyle()) {
+ if (style->ImageRendering() == EImageRendering::kPixelated)
+ interpolation_quality = kInterpolationNone;
+ }
+
RespectImageOrientationEnum should_respect_image_orientation =
LayoutObject::ShouldRespectImageOrientation(element->GetLayoutObject());
ImageOrientation orientation;
@@ -1300,7 +1300,7 @@ void DragController::DoSystemDrag(DragImage* image,
frame->View()->FrameToViewport(drag_location);
IntPoint adjusted_event_pos = frame->View()->FrameToViewport(event_pos);
IntSize offset_size(adjusted_event_pos - adjusted_drag_location);
- WebPoint offset_point(offset_size.Width(), offset_size.Height());
+ gfx::Point offset_point(offset_size.Width(), offset_size.Height());
WebDragData drag_data = data_transfer->GetDataObject()->ToWebDragData();
WebDragOperationsMask drag_operation_mask =
static_cast<WebDragOperationsMask>(data_transfer->SourceOperation());
@@ -1344,7 +1344,7 @@ bool DragController::IsCopyKeyDown(DragData* drag_data) {
DragState& DragController::GetDragState() {
if (!drag_state_)
- drag_state_ = new DragState;
+ drag_state_ = MakeGarbageCollected<DragState>();
return *drag_state_;
}
diff --git a/chromium/third_party/blink/renderer/core/page/drag_controller.h b/chromium/third_party/blink/renderer/core/page/drag_controller.h
index 8629b14de35..2a99d905c51 100644
--- a/chromium/third_party/blink/renderer/core/page/drag_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/drag_controller.h
@@ -55,6 +55,8 @@ class CORE_EXPORT DragController final
public:
static DragController* Create(Page*);
+ explicit DragController(Page*);
+
DragOperation DragEnteredOrUpdated(DragData*, LocalFrame& local_root);
void DragExited(DragData*, LocalFrame& local_root);
void PerformDrag(DragData*, LocalFrame& local_root);
@@ -90,8 +92,6 @@ class CORE_EXPORT DragController final
void Trace(blink::Visitor*);
private:
- explicit DragController(Page*);
-
DispatchEventResult DispatchTextInputEventFor(LocalFrame*, DragData*);
bool CanProcessDrag(DragData*, LocalFrame& local_root);
bool ConcludeEditDrag(DragData*);
@@ -102,7 +102,8 @@ class CORE_EXPORT DragController final
LocalFrame& local_root);
bool TryDHTMLDrag(DragData*, DragOperation&, LocalFrame& local_root);
DragOperation GetDragOperation(DragData*);
- void CancelDrag();
+ // Clear the selection from the document this drag is exiting.
+ void ClearDragCaret();
bool DragIsMove(FrameSelection&, DragData*);
bool IsCopyKeyDown(DragData*);
diff --git a/chromium/third_party/blink/renderer/core/page/drag_controller_test.cc b/chromium/third_party/blink/renderer/core/page/drag_controller_test.cc
index bdea264d4b1..9f2215d644c 100644
--- a/chromium/third_party/blink/renderer/core/page/drag_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/drag_controller_test.cc
@@ -32,13 +32,13 @@ class DragMockChromeClient : public EmptyChromeClient {
const WebDragData&,
WebDragOperationsMask,
const SkBitmap& drag_image,
- const WebPoint& drag_image_offset) override {
+ const gfx::Point& drag_image_offset) override {
last_drag_image_size = WebSize(drag_image.width(), drag_image.height());
last_drag_image_offset = drag_image_offset;
}
WebSize last_drag_image_size;
- WebPoint last_drag_image_offset;
+ gfx::Point last_drag_image_offset;
};
class DragControllerTest : public RenderingTest {
@@ -52,10 +52,6 @@ class DragControllerTest : public RenderingTest {
return *chrome_client_;
}
- void UpdateAllLifecyclePhases() {
- GetDocument().View()->UpdateAllLifecyclePhases();
- }
-
private:
Persistent<DragMockChromeClient> chrome_client_;
};
@@ -66,12 +62,12 @@ TEST_F(DragControllerTest, DragImageForSelectionUsesPageScaleFactor) {
"by page scale factor</div>");
GetFrame().GetPage()->GetVisualViewport().SetScale(1);
GetFrame().Selection().SelectAll();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const std::unique_ptr<DragImage> image1(
DragController::DragImageForSelection(GetFrame(), 0.75f));
GetFrame().GetPage()->GetVisualViewport().SetScale(2);
GetFrame().Selection().SelectAll();
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const std::unique_ptr<DragImage> image2(
DragController::DragImageForSelection(GetFrame(), 0.75f));
@@ -259,7 +255,7 @@ TEST_F(DragControllerTest, DragImageForSelectionClipsChildFrameToViewport) {
</style>
<div>abcdefg</div>
)HTML");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto& child_frame = *ToLocalFrame(GetFrame().Tree().FirstChild());
child_frame.Selection().SelectAll();
@@ -339,7 +335,7 @@ TEST_F(DragControllerTest,
)HTML");
const int page_scale_factor = 2;
GetFrame().GetPage()->SetPageScaleFactor(page_scale_factor);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto& child_frame = *ToLocalFrame(GetFrame().Tree().FirstChild());
child_frame.Selection().SelectAll();
@@ -483,9 +479,9 @@ TEST_F(DragControllerTest, DragLinkWithPageScaleFactor) {
// The offset is mapped using integers which can introduce rounding errors
// (see TODO in DragController::DoSystemDrag) so we accept values near our
// expectation until more precise offset mapping is available.
- EXPECT_NEAR(expected_offset.X(), GetChromeClient().last_drag_image_offset.x,
+ EXPECT_NEAR(expected_offset.X(), GetChromeClient().last_drag_image_offset.x(),
1);
- EXPECT_NEAR(expected_offset.Y(), GetChromeClient().last_drag_image_offset.y,
+ EXPECT_NEAR(expected_offset.Y(), GetChromeClient().last_drag_image_offset.y(),
1);
}
diff --git a/chromium/third_party/blink/renderer/core/page/focus_controller.cc b/chromium/third_party/blink/renderer/core/page/focus_controller.cc
index 3279eda239c..0f1ebb0a42c 100644
--- a/chromium/third_party/blink/renderer/core/page/focus_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/focus_controller.cc
@@ -26,6 +26,8 @@
#include "third_party/blink/renderer/core/page/focus_controller.h"
+#include <limits>
+
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/dom/container_node.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -58,12 +60,8 @@
#include "third_party/blink/renderer/core/page/slot_scoped_traversal.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
-#include <limits>
-
namespace blink {
-using namespace HTMLNames;
-
namespace {
// This class defines the navigation order.
@@ -358,9 +356,9 @@ inline void DispatchBlurEvent(const Document& document,
Element& focused_element) {
focused_element.DispatchBlurEvent(nullptr, kWebFocusTypePage);
if (focused_element == document.FocusedElement()) {
- focused_element.DispatchFocusOutEvent(EventTypeNames::focusout, nullptr);
+ focused_element.DispatchFocusOutEvent(event_type_names::kFocusout, nullptr);
if (focused_element == document.FocusedElement())
- focused_element.DispatchFocusOutEvent(EventTypeNames::DOMFocusOut,
+ focused_element.DispatchFocusOutEvent(event_type_names::kDOMFocusOut,
nullptr);
}
}
@@ -369,11 +367,12 @@ inline void DispatchFocusEvent(const Document& document,
Element& focused_element) {
focused_element.DispatchFocusEvent(nullptr, kWebFocusTypePage);
if (focused_element == document.FocusedElement()) {
- focused_element.DispatchFocusInEvent(EventTypeNames::focusin, nullptr,
+ focused_element.DispatchFocusInEvent(event_type_names::kFocusin, nullptr,
kWebFocusTypePage);
- if (focused_element == document.FocusedElement())
- focused_element.DispatchFocusInEvent(EventTypeNames::DOMFocusIn, nullptr,
- kWebFocusTypePage);
+ if (focused_element == document.FocusedElement()) {
+ focused_element.DispatchFocusInEvent(event_type_names::kDOMFocusIn,
+ nullptr, kWebFocusTypePage);
+ }
}
}
@@ -400,8 +399,8 @@ inline void DispatchEventsOnWindowAndFocusedElement(Document* document,
}
if (LocalDOMWindow* window = document->domWindow()) {
- window->DispatchEvent(
- *Event::Create(focused ? EventTypeNames::focus : EventTypeNames::blur));
+ window->DispatchEvent(*Event::Create(focused ? event_type_names::kFocus
+ : event_type_names::kBlur));
}
if (focused && document->FocusedElement()) {
Element* focused_element(document->FocusedElement());
@@ -768,7 +767,7 @@ FocusController::FocusController(Page* page)
is_emulating_focus_(false) {}
FocusController* FocusController::Create(Page* page) {
- return new FocusController(page);
+ return MakeGarbageCollected<FocusController>(page);
}
void FocusController::SetFocusedFrame(Frame* frame, bool notify_embedder) {
@@ -791,13 +790,14 @@ void FocusController::SetFocusedFrame(Frame* frame, bool notify_embedder) {
// states of both frames.
if (old_frame && old_frame->View()) {
old_frame->Selection().SetFrameIsFocused(false);
- old_frame->DomWindow()->DispatchEvent(*Event::Create(EventTypeNames::blur));
+ old_frame->DomWindow()->DispatchEvent(
+ *Event::Create(event_type_names::kBlur));
}
if (new_frame && new_frame->View() && IsFocused()) {
new_frame->Selection().SetFrameIsFocused(true);
new_frame->DomWindow()->DispatchEvent(
- *Event::Create(EventTypeNames::focus));
+ *Event::Create(event_type_names::kFocus));
}
is_changing_focused_frame_ = false;
@@ -843,10 +843,7 @@ void FocusController::FocusDocumentView(Frame* frame, bool notify_embedder) {
}
LocalFrame* FocusController::FocusedFrame() const {
- // TODO(alexmos): Strengthen this to DCHECK that whoever called this really
- // expected a LocalFrame. Refactor call sites so that the rare cases that
- // need to know about focused RemoteFrames use a separate accessor (to be
- // added).
+ // All callsites only care about *local* focused frames.
if (focused_frame_ && focused_frame_->IsRemoteFrame())
return nullptr;
return ToLocalFrame(focused_frame_.Get());
@@ -856,9 +853,10 @@ Frame* FocusController::FocusedOrMainFrame() const {
if (LocalFrame* frame = FocusedFrame())
return frame;
- // FIXME: This is a temporary hack to ensure that we return a LocalFrame, even
- // when the mainFrame is remote. FocusController needs to be refactored to
- // deal with RemoteFrames cross-process focus transfers.
+ // TODO(dcheng, alexmos): https://crbug.com/820786: This is a temporary hack
+ // to ensure that we return a LocalFrame, even when the mainFrame is remote.
+ // FocusController needs to be refactored to deal with RemoteFrames
+ // cross-process focus transfers.
for (Frame* frame = &page_->MainFrame()->Tree().Top(); frame;
frame = frame->Tree().TraverseNext()) {
if (frame->IsLocalFrame() && ToLocalFrame(frame)->IsLocalRoot())
@@ -868,6 +866,11 @@ Frame* FocusController::FocusedOrMainFrame() const {
return page_->MainFrame();
}
+void FocusController::FrameDetached(Frame* detached_frame) {
+ if (detached_frame == focused_frame_)
+ SetFocusedFrame(nullptr);
+}
+
HTMLFrameOwnerElement* FocusController::FocusedFrameOwnerElement(
LocalFrame& current_frame) const {
Frame* focused_frame = focused_frame_.Get();
diff --git a/chromium/third_party/blink/renderer/core/page/focus_controller.h b/chromium/third_party/blink/renderer/core/page/focus_controller.h
index 840b3d21a84..ab263394aaa 100644
--- a/chromium/third_party/blink/renderer/core/page/focus_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/focus_controller.h
@@ -57,11 +57,16 @@ class CORE_EXPORT FocusController final
static FocusController* Create(Page*);
+ explicit FocusController(Page*);
+
void SetFocusedFrame(Frame*, bool notify_embedder = true);
void FocusDocumentView(Frame*, bool notify_embedder = true);
LocalFrame* FocusedFrame() const;
Frame* FocusedOrMainFrame() const;
+ // Clears |focused_frame_| if it's been detached.
+ void FrameDetached(Frame* detached_frame);
+
// Finds the focused HTMLFrameOwnerElement, if any, in the provided frame.
// An HTMLFrameOwnerElement is considered focused if the frame it owns, or
// one of its descendant frames, is currently focused.
@@ -105,8 +110,6 @@ class CORE_EXPORT FocusController final
private:
using SkipList = HeapHashSet<Member<Node>>;
- explicit FocusController(Page*);
-
Element* FindFocusableElement(WebFocusType, Element&, OwnerMap&);
bool AdvanceFocus(WebFocusType,
diff --git a/chromium/third_party/blink/renderer/core/page/page.cc b/chromium/third_party/blink/renderer/core/page/page.cc
index 4277312bcad..bee3dcd9beb 100644
--- a/chromium/third_party/blink/renderer/core/page/page.cc
+++ b/chromium/third_party/blink/renderer/core/page/page.cc
@@ -89,12 +89,14 @@ void ResetPluginCache(bool reload_pages) {
// Set of all live pages; includes internal Page objects that are
// not observable from scripts.
static Page::PageSet& AllPages() {
- DEFINE_STATIC_LOCAL(Persistent<Page::PageSet>, pages, (new Page::PageSet));
+ DEFINE_STATIC_LOCAL(Persistent<Page::PageSet>, pages,
+ (MakeGarbageCollected<Page::PageSet>()));
return *pages;
}
Page::PageSet& Page::OrdinaryPages() {
- DEFINE_STATIC_LOCAL(Persistent<Page::PageSet>, pages, (new Page::PageSet));
+ DEFINE_STATIC_LOCAL(Persistent<Page::PageSet>, pages,
+ (MakeGarbageCollected<Page::PageSet>()));
return *pages;
}
@@ -122,10 +124,8 @@ float DeviceScaleFactorDeprecated(LocalFrame* frame) {
}
Page* Page::Create(PageClients& page_clients) {
- Page* page = new Page(page_clients);
- page->SetPageScheduler(
- Platform::Current()->CurrentThread()->Scheduler()->CreatePageScheduler(
- page));
+ Page* page = MakeGarbageCollected<Page>(page_clients);
+ page->SetPageScheduler(ThreadScheduler::Current()->CreatePageScheduler(page));
return page;
}
diff --git a/chromium/third_party/blink/renderer/core/page/page.h b/chromium/third_party/blink/renderer/core/page/page.h
index 8d2baa9630d..676f1c715ea 100644
--- a/chromium/third_party/blink/renderer/core/page/page.h
+++ b/chromium/third_party/blink/renderer/core/page/page.h
@@ -109,6 +109,7 @@ class CORE_EXPORT Page final : public GarbageCollectedFinalized<Page>,
// An "ordinary" page is a fully-featured page owned by a web view.
static Page* CreateOrdinary(PageClients&, Page* opener);
+ explicit Page(PageClients&);
~Page() override;
void CloseSoon();
@@ -320,8 +321,6 @@ class CORE_EXPORT Page final : public GarbageCollectedFinalized<Page>,
private:
friend class ScopedPagePauser;
- explicit Page(PageClients&);
-
void InitGroup();
// SettingsDelegate overrides.
diff --git a/chromium/third_party/blink/renderer/core/page/page_animator.cc b/chromium/third_party/blink/renderer/core/page/page_animator.cc
index 19099bd2b50..6482e12c2c4 100644
--- a/chromium/third_party/blink/renderer/core/page/page_animator.cc
+++ b/chromium/third_party/blink/renderer/core/page/page_animator.cc
@@ -23,7 +23,7 @@ PageAnimator::PageAnimator(Page& page)
updating_layout_and_style_for_painting_(false) {}
PageAnimator* PageAnimator::Create(Page& page) {
- return new PageAnimator(page);
+ return MakeGarbageCollected<PageAnimator>(page);
}
void PageAnimator::Trace(blink::Visitor* visitor) {
@@ -103,11 +103,13 @@ void PageAnimator::ScheduleVisualUpdate(LocalFrame* frame) {
page_->GetChromeClient().ScheduleAnimation(frame->View());
}
-void PageAnimator::UpdateAllLifecyclePhases(LocalFrame& root_frame) {
+void PageAnimator::UpdateAllLifecyclePhases(
+ LocalFrame& root_frame,
+ DocumentLifecycle::LifecycleUpdateReason reason) {
LocalFrameView* view = root_frame.View();
base::AutoReset<bool> servicing(&updating_layout_and_style_for_painting_,
true);
- view->UpdateAllLifecyclePhases();
+ view->UpdateAllLifecyclePhases(reason);
}
void PageAnimator::UpdateAllLifecyclePhasesExceptPaint(LocalFrame& root_frame) {
diff --git a/chromium/third_party/blink/renderer/core/page/page_animator.h b/chromium/third_party/blink/renderer/core/page/page_animator.h
index 3ee99c449a2..2f127f6615f 100644
--- a/chromium/third_party/blink/renderer/core/page/page_animator.h
+++ b/chromium/third_party/blink/renderer/core/page/page_animator.h
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/core/animation/animation_clock.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/dom/document_lifecycle.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
@@ -17,6 +18,9 @@ class Page;
class CORE_EXPORT PageAnimator final : public GarbageCollected<PageAnimator> {
public:
static PageAnimator* Create(Page&);
+
+ explicit PageAnimator(Page&);
+
void Trace(blink::Visitor*);
void ScheduleVisualUpdate(LocalFrame*);
void ServiceScriptedAnimations(
@@ -31,14 +35,14 @@ class CORE_EXPORT PageAnimator final : public GarbageCollected<PageAnimator> {
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool);
// See documents of methods with the same names in LocalFrameView class.
- void UpdateAllLifecyclePhases(LocalFrame& root_frame);
+ void UpdateAllLifecyclePhases(
+ LocalFrame& root_frame,
+ DocumentLifecycle::LifecycleUpdateReason reason);
void UpdateAllLifecyclePhasesExceptPaint(LocalFrame& root_frame);
void UpdateLifecycleToLayoutClean(LocalFrame& root_frame);
AnimationClock& Clock() { return animation_clock_; }
private:
- explicit PageAnimator(Page&);
-
Member<Page> page_;
bool servicing_animations_;
bool updating_layout_and_style_for_painting_;
diff --git a/chromium/third_party/blink/renderer/core/page/page_overlay_test.cc b/chromium/third_party/blink/renderer/core/page/page_overlay_test.cc
index 56b0ec222f5..08ce4c6159a 100644
--- a/chromium/third_party/blink/renderer/core/page/page_overlay_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/page_overlay_test.cc
@@ -6,6 +6,7 @@
#include <memory>
+#include "base/time/time.h"
#include "cc/paint/paint_canvas.h"
#include "cc/trees/layer_tree_host.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -38,14 +39,6 @@ static const int kViewportHeight = 600;
// These unit tests cover both PageOverlay and PageOverlayList.
-void EnableAcceleratedCompositing(WebSettings* settings) {
- settings->SetAcceleratedCompositingEnabled(true);
-}
-
-void DisableAcceleratedCompositing(WebSettings* settings) {
- settings->SetAcceleratedCompositingEnabled(false);
-}
-
// PageOverlay that paints a solid color.
class SolidColorOverlay : public PageOverlay::Delegate {
public:
@@ -69,19 +62,13 @@ class SolidColorOverlay : public PageOverlay::Delegate {
class PageOverlayTest : public testing::Test {
protected:
- enum CompositingMode { kAcceleratedCompositing, kUnacceleratedCompositing };
-
- void Initialize(CompositingMode compositing_mode) {
+ PageOverlayTest() {
helper_.Initialize(nullptr /* web_frame_client */,
nullptr /* web_view_client */,
- nullptr /* web_widget_client */,
- compositing_mode == kAcceleratedCompositing
- ? EnableAcceleratedCompositing
- : DisableAcceleratedCompositing);
+ nullptr /* web_widget_client */);
GetWebView()->Resize(WebSize(kViewportWidth, kViewportHeight));
- GetWebView()->UpdateAllLifecyclePhases();
- ASSERT_EQ(compositing_mode == kAcceleratedCompositing,
- GetWebView()->IsAcceleratedCompositingActive());
+ GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
WebViewImpl* GetWebView() const { return helper_.GetWebView(); }
@@ -96,14 +83,15 @@ class PageOverlayTest : public testing::Test {
content::LayerTreeView* layer_tree_view = helper_.GetLayerTreeView();
layer_tree_view->SetViewportSizeAndScale(
static_cast<gfx::Size>(size), /*device_scale_factor=*/1.f,
- layer_tree_view->layer_tree_host()->local_surface_id_from_parent());
+ layer_tree_view->layer_tree_host()
+ ->local_surface_id_allocation_from_parent());
}
template <typename OverlayType>
void RunPageOverlayTestWithAcceleratedCompositing();
private:
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
};
template <bool (*getter)(), void (*setter)(bool)>
@@ -125,39 +113,36 @@ class MockPageOverlayCanvas : public SkCanvas {
};
TEST_F(PageOverlayTest, PageOverlay_AcceleratedCompositing) {
- Initialize(kAcceleratedCompositing);
SetViewportSize(WebSize(kViewportWidth, kViewportHeight));
std::unique_ptr<PageOverlay> page_overlay = CreateSolidYellowOverlay();
page_overlay->Update();
- GetWebView()->UpdateAllLifecyclePhases();
+ GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+
+ GraphicsLayer* graphics_layer = page_overlay->GetGraphicsLayer();
+ WebRect rect(0, 0, kViewportWidth, kViewportHeight);
+
+ IntRect int_rect = rect;
+ graphics_layer->Paint(&int_rect);
// Ideally, we would get results from the compositor that showed that this
// page overlay actually winds up getting drawn on top of the rest.
// For now, we just check that the GraphicsLayer will draw the right thing.
-
MockPageOverlayCanvas canvas(kViewportWidth, kViewportHeight);
EXPECT_CALL(canvas, onDrawRect(_, _)).Times(AtLeast(0));
EXPECT_CALL(canvas,
onDrawRect(SkRect::MakeWH(kViewportWidth, kViewportHeight),
Property(&SkPaint::getColor, SK_ColorYELLOW)));
-
- GraphicsLayer* graphics_layer = page_overlay->GetGraphicsLayer();
- WebRect rect(0, 0, kViewportWidth, kViewportHeight);
-
- // Paint the layer with a null canvas to get a display list, and then
- // replay that onto the mock canvas for examination.
- IntRect int_rect = rect;
- graphics_layer->Paint(&int_rect);
canvas.drawPicture(
ToSkPicture(graphics_layer->CapturePaintRecord(), int_rect));
}
TEST_F(PageOverlayTest, PageOverlay_VisualRect) {
- Initialize(kAcceleratedCompositing);
std::unique_ptr<PageOverlay> page_overlay = CreateSolidYellowOverlay();
page_overlay->Update();
- GetWebView()->UpdateAllLifecyclePhases();
+ GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
EXPECT_EQ(LayoutRect(0, 0, kViewportWidth, kViewportHeight),
page_overlay->VisualRect());
}
diff --git a/chromium/third_party/blink/renderer/core/page/page_popup_controller.cc b/chromium/third_party/blink/renderer/core/page/page_popup_controller.cc
index 433aeea7661..fa7fceee5b1 100644
--- a/chromium/third_party/blink/renderer/core/page/page_popup_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/page_popup_controller.cc
@@ -45,7 +45,7 @@ PagePopupController::PagePopupController(PagePopup& popup,
PagePopupController* PagePopupController::Create(PagePopup& popup,
PagePopupClient* client) {
- return new PagePopupController(popup, client);
+ return MakeGarbageCollected<PagePopupController>(popup, client);
}
void PagePopupController::setValueAndClosePopup(int num_value,
diff --git a/chromium/third_party/blink/renderer/core/page/page_popup_controller.h b/chromium/third_party/blink/renderer/core/page/page_popup_controller.h
index dc4d5bff651..53653b68646 100644
--- a/chromium/third_party/blink/renderer/core/page/page_popup_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/page_popup_controller.h
@@ -46,6 +46,9 @@ class PagePopupController final : public ScriptWrappable {
public:
static PagePopupController* Create(PagePopup&, PagePopupClient*);
+
+ PagePopupController(PagePopup&, PagePopupClient*);
+
void setValueAndClosePopup(int num_value, const String& string_value);
void setValue(const String&);
void closePopup();
@@ -60,8 +63,6 @@ class PagePopupController final : public ScriptWrappable {
void setWindowRect(int x, int y, int width, int height);
private:
- PagePopupController(PagePopup&, PagePopupClient*);
-
PagePopup& popup_;
PagePopupClient* popup_client_;
};
diff --git a/chromium/third_party/blink/renderer/core/page/page_popup_supplement.cc b/chromium/third_party/blink/renderer/core/page/page_popup_supplement.cc
index 241ceea5a6c..c09b2ae77f9 100644
--- a/chromium/third_party/blink/renderer/core/page/page_popup_supplement.cc
+++ b/chromium/third_party/blink/renderer/core/page/page_popup_supplement.cc
@@ -63,7 +63,8 @@ void PagePopupSupplement::Install(LocalFrame& frame,
PagePopup& popup,
PagePopupClient* popup_client) {
DCHECK(popup_client);
- ProvideTo(frame, new PagePopupSupplement(frame, popup, popup_client));
+ ProvideTo(frame, MakeGarbageCollected<PagePopupSupplement>(frame, popup,
+ popup_client));
}
void PagePopupSupplement::Uninstall(LocalFrame& frame) {
diff --git a/chromium/third_party/blink/renderer/core/page/page_popup_supplement.h b/chromium/third_party/blink/renderer/core/page/page_popup_supplement.h
index f3136d9f5b7..c1511cbc6c7 100644
--- a/chromium/third_party/blink/renderer/core/page/page_popup_supplement.h
+++ b/chromium/third_party/blink/renderer/core/page/page_popup_supplement.h
@@ -55,10 +55,12 @@ class CORE_EXPORT PagePopupSupplement final
static void Uninstall(LocalFrame&);
PagePopupController* GetPagePopupController() const;
+
+ PagePopupSupplement(LocalFrame&, PagePopup&, PagePopupClient*);
+
void Trace(blink::Visitor*) override;
private:
- PagePopupSupplement(LocalFrame&, PagePopup&, PagePopupClient*);
void Dispose();
Member<PagePopupController> controller_;
diff --git a/chromium/third_party/blink/renderer/core/page/page_widget_delegate.cc b/chromium/third_party/blink/renderer/core/page/page_widget_delegate.cc
index 38de4207502..56f1a47f997 100644
--- a/chromium/third_party/blink/renderer/core/page/page_widget_delegate.cc
+++ b/chromium/third_party/blink/renderer/core/page/page_widget_delegate.cc
@@ -61,13 +61,15 @@ void PageWidgetDelegate::Animate(Page& page,
void PageWidgetDelegate::UpdateLifecycle(
Page& page,
LocalFrame& root,
- WebWidget::LifecycleUpdate requested_update) {
+ WebWidget::LifecycleUpdate requested_update,
+ WebWidget::LifecycleUpdateReason reason) {
if (requested_update == WebWidget::LifecycleUpdate::kLayout) {
page.Animator().UpdateLifecycleToLayoutClean(root);
} else if (requested_update == WebWidget::LifecycleUpdate::kPrePaint) {
page.Animator().UpdateAllLifecyclePhasesExceptPaint(root);
} else {
- page.Animator().UpdateAllLifecyclePhases(root);
+ page.Animator().UpdateAllLifecyclePhases(
+ root, static_cast<DocumentLifecycle::LifecycleUpdateReason>(reason));
}
}
@@ -179,7 +181,8 @@ WebInputEventResult PageWidgetDelegate::HandleInputEvent(
if (!root || !root->View())
return WebInputEventResult::kHandledSuppressed;
handler.HandleMouseMove(*root, static_cast<const WebMouseEvent&>(event),
- coalesced_event.GetCoalescedEventsPointers());
+ coalesced_event.GetCoalescedEventsPointers(),
+ coalesced_event.GetPredictedEventsPointers());
return WebInputEventResult::kHandledSystem;
case WebInputEvent::kMouseLeave:
if (!root || !root->View())
@@ -238,7 +241,8 @@ WebInputEventResult PageWidgetDelegate::HandleInputEvent(
return WebInputEventResult::kNotHandled;
return handler.HandlePointerEvent(
*root, static_cast<const WebPointerEvent&>(event),
- coalesced_event.GetCoalescedEventsPointers());
+ coalesced_event.GetCoalescedEventsPointers(),
+ coalesced_event.GetPredictedEventsPointers());
case WebInputEvent::kTouchStart:
case WebInputEvent::kTouchMove:
@@ -266,12 +270,14 @@ WebInputEventResult PageWidgetDelegate::HandleInputEvent(
void PageWidgetEventHandler::HandleMouseMove(
LocalFrame& main_frame,
const WebMouseEvent& event,
- const std::vector<const WebInputEvent*>& coalesced_events) {
+ const std::vector<const WebInputEvent*>& coalesced_events,
+ const std::vector<const WebInputEvent*>& predicted_events) {
WebMouseEvent transformed_event =
TransformWebMouseEvent(main_frame.View(), event);
main_frame.GetEventHandler().HandleMouseMoveEvent(
transformed_event,
- TransformWebMouseEventVector(main_frame.View(), coalesced_events));
+ TransformWebMouseEventVector(main_frame.View(), coalesced_events),
+ TransformWebMouseEventVector(main_frame.View(), predicted_events));
}
void PageWidgetEventHandler::HandleMouseLeave(LocalFrame& main_frame,
@@ -306,12 +312,14 @@ WebInputEventResult PageWidgetEventHandler::HandleMouseWheel(
WebInputEventResult PageWidgetEventHandler::HandlePointerEvent(
LocalFrame& main_frame,
const WebPointerEvent& event,
- const std::vector<const WebInputEvent*>& coalesced_events) {
+ const std::vector<const WebInputEvent*>& coalesced_events,
+ const std::vector<const WebInputEvent*>& predicted_events) {
WebPointerEvent transformed_event =
TransformWebPointerEvent(main_frame.View(), event);
return main_frame.GetEventHandler().HandlePointerEvent(
transformed_event,
- TransformWebPointerEventVector(main_frame.View(), coalesced_events));
+ TransformWebPointerEventVector(main_frame.View(), coalesced_events),
+ TransformWebPointerEventVector(main_frame.View(), predicted_events));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/page_widget_delegate.h b/chromium/third_party/blink/renderer/core/page/page_widget_delegate.h
index 778cff4de2e..9d6e0edc761 100644
--- a/chromium/third_party/blink/renderer/core/page/page_widget_delegate.h
+++ b/chromium/third_party/blink/renderer/core/page/page_widget_delegate.h
@@ -53,6 +53,7 @@ class CORE_EXPORT PageWidgetEventHandler {
public:
virtual void HandleMouseMove(LocalFrame& main_frame,
const WebMouseEvent&,
+ const std::vector<const WebInputEvent*>&,
const std::vector<const WebInputEvent*>&);
virtual void HandleMouseLeave(LocalFrame& main_frame, const WebMouseEvent&);
virtual void HandleMouseDown(LocalFrame& main_frame, const WebMouseEvent&);
@@ -65,6 +66,7 @@ class CORE_EXPORT PageWidgetEventHandler {
virtual WebInputEventResult HandlePointerEvent(
LocalFrame& main_frame,
const WebPointerEvent&,
+ const std::vector<const WebInputEvent*>&,
const std::vector<const WebInputEvent*>&);
virtual ~PageWidgetEventHandler() {}
};
@@ -80,7 +82,8 @@ class CORE_EXPORT PageWidgetDelegate {
// See comment of WebWidget::UpdateLifecycle.
static void UpdateLifecycle(Page&,
LocalFrame& root,
- WebWidget::LifecycleUpdate requested_update);
+ WebWidget::LifecycleUpdate requested_update,
+ WebWidget::LifecycleUpdateReason reason);
// See documents of methods with the same names in FrameView class.
static void PaintContent(Page&,
diff --git a/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc b/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc
index a75df5a4f84..7ab04592097 100644
--- a/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc
@@ -40,13 +40,13 @@ PointerLockController::PointerLockController(Page* page)
: page_(page), lock_pending_(false) {}
PointerLockController* PointerLockController::Create(Page* page) {
- return new PointerLockController(page);
+ return MakeGarbageCollected<PointerLockController>(page);
}
void PointerLockController::RequestPointerLock(Element* target) {
if (!target || !target->isConnected() ||
document_of_removed_element_while_waiting_for_unlock_) {
- EnqueueEvent(EventTypeNames::pointerlockerror, target);
+ EnqueueEvent(event_type_names::kPointerlockerror, target);
return;
}
@@ -64,23 +64,23 @@ void PointerLockController::RequestPointerLock(Element* target) {
kSecurityMessageSource, kErrorMessageLevel,
"Blocked pointer lock on an element because the element's frame is "
"sandboxed and the 'allow-pointer-lock' permission is not set."));
- EnqueueEvent(EventTypeNames::pointerlockerror, target);
+ EnqueueEvent(event_type_names::kPointerlockerror, target);
return;
}
if (element_) {
if (element_->GetDocument() != target->GetDocument()) {
- EnqueueEvent(EventTypeNames::pointerlockerror, target);
+ EnqueueEvent(event_type_names::kPointerlockerror, target);
return;
}
- EnqueueEvent(EventTypeNames::pointerlockchange, target);
+ EnqueueEvent(event_type_names::kPointerlockchange, target);
element_ = target;
} else if (page_->GetChromeClient().RequestPointerLock(
target->GetDocument().GetFrame())) {
lock_pending_ = true;
element_ = target;
} else {
- EnqueueEvent(EventTypeNames::pointerlockerror, target);
+ EnqueueEvent(event_type_names::kPointerlockerror, target);
}
}
@@ -116,18 +116,18 @@ Element* PointerLockController::GetElement() const {
}
void PointerLockController::DidAcquirePointerLock() {
- EnqueueEvent(EventTypeNames::pointerlockchange, element_.Get());
+ EnqueueEvent(event_type_names::kPointerlockchange, element_.Get());
lock_pending_ = false;
}
void PointerLockController::DidNotAcquirePointerLock() {
- EnqueueEvent(EventTypeNames::pointerlockerror, element_.Get());
+ EnqueueEvent(event_type_names::kPointerlockerror, element_.Get());
ClearElement();
}
void PointerLockController::DidLosePointerLock() {
EnqueueEvent(
- EventTypeNames::pointerlockchange,
+ event_type_names::kPointerlockchange,
element_ ? &element_->GetDocument()
: document_of_removed_element_while_waiting_for_unlock_.Get());
ClearElement();
@@ -137,22 +137,24 @@ void PointerLockController::DidLosePointerLock() {
void PointerLockController::DispatchLockedMouseEvent(
const WebMouseEvent& event,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
const AtomicString& event_type) {
if (!element_ || !element_->GetDocument().GetFrame())
return;
if (LocalFrame* frame = element_->GetDocument().GetFrame()) {
frame->GetEventHandler().HandleTargetedMouseEvent(
- element_, event, event_type, coalesced_events);
+ element_, event, event_type, coalesced_events, predicted_events);
// Event handlers may remove element.
if (!element_)
return;
// Create click events
- if (event_type == EventTypeNames::mouseup) {
+ if (event_type == event_type_names::kMouseup) {
frame->GetEventHandler().HandleTargetedMouseEvent(
- element_, event, EventTypeNames::click, Vector<WebMouseEvent>());
+ element_, event, event_type_names::kClick, Vector<WebMouseEvent>(),
+ Vector<WebMouseEvent>());
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.h b/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.h
index c0730a0183f..681c3e48466 100644
--- a/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/pointer_lock_controller.h
@@ -44,6 +44,8 @@ class CORE_EXPORT PointerLockController final
public:
static PointerLockController* Create(Page*);
+ explicit PointerLockController(Page*);
+
void RequestPointerLock(Element* target);
void RequestPointerUnlock();
void ElementRemoved(Element*);
@@ -56,12 +58,12 @@ class CORE_EXPORT PointerLockController final
void DidLosePointerLock();
void DispatchLockedMouseEvent(const WebMouseEvent&,
const Vector<WebMouseEvent>& coalesced_events,
+ const Vector<WebMouseEvent>& predicted_events,
const AtomicString& event_type);
void Trace(blink::Visitor*);
private:
- explicit PointerLockController(Page*);
void ClearElement();
void EnqueueEvent(const AtomicString& type, Element*);
void EnqueueEvent(const AtomicString& type, Document*);
diff --git a/chromium/third_party/blink/renderer/core/page/print_context.cc b/chromium/third_party/blink/renderer/core/page/print_context.cc
index 7facebace2c..358bebb64f8 100644
--- a/chromium/third_party/blink/renderer/core/page/print_context.cc
+++ b/chromium/third_party/blink/renderer/core/page/print_context.cc
@@ -206,7 +206,8 @@ void PrintContext::CollectLinkedDestinations(Node* node) {
if (!node->IsLink() || !node->IsElementNode())
return;
- const AtomicString& href = ToElement(node)->getAttribute(HTMLNames::hrefAttr);
+ const AtomicString& href =
+ ToElement(node)->getAttribute(html_names::kHrefAttr);
if (href.IsNull())
return;
KURL url = node->GetDocument().CompleteURL(href);
@@ -326,7 +327,9 @@ bool PrintContext::use_printing_layout() const {
}
ScopedPrintContext::ScopedPrintContext(LocalFrame* frame)
- : context_(new PrintContext(frame, /*use_printing_layout=*/true)) {}
+ : context_(
+ MakeGarbageCollected<PrintContext>(frame,
+ /*use_printing_layout=*/true)) {}
ScopedPrintContext::~ScopedPrintContext() {
context_->EndPrintMode();
diff --git a/chromium/third_party/blink/renderer/core/page/print_context_test.cc b/chromium/third_party/blink/renderer/core/page/print_context_test.cc
index 02bb3229c08..6633f491555 100644
--- a/chromium/third_party/blink/renderer/core/page/print_context_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/print_context_test.cc
@@ -72,21 +72,22 @@ class PrintContextTest : public PaintTestConfigurations, public RenderingTest {
void SetUp() override {
RenderingTest::SetUp();
- print_context_ = new PrintContext(GetDocument().GetFrame(),
- /*use_printing_layout=*/true);
+ print_context_ =
+ MakeGarbageCollected<PrintContext>(GetDocument().GetFrame(),
+ /*use_printing_layout=*/true);
}
PrintContext& GetPrintContext() { return *print_context_.Get(); }
void SetBodyInnerHTML(String body_content) {
- GetDocument().body()->setAttribute(HTMLNames::styleAttr, "margin: 0");
+ GetDocument().body()->setAttribute(html_names::kStyleAttr, "margin: 0");
GetDocument().body()->SetInnerHTMLFromString(body_content);
}
void PrintSinglePage(MockPageContextCanvas& canvas) {
IntRect page_rect(0, 0, kPageWidth, kPageHeight);
GetPrintContext().BeginPrintMode(page_rect.Width(), page_rect.Height());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintRecordBuilder builder;
GraphicsContext& context = builder.Context();
context.SetPrinting(true);
diff --git a/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.cc b/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.cc
index 7bbe818a611..e8328166cf7 100644
--- a/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.cc
+++ b/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.cc
@@ -42,8 +42,7 @@ ScopedPagePauser::ScopedPagePauser() {
return;
SetPaused(true);
- pause_handle_ =
- Platform::Current()->CurrentThread()->Scheduler()->PauseScheduler();
+ pause_handle_ = ThreadScheduler::Current()->PauseScheduler();
}
ScopedPagePauser::~ScopedPagePauser() {
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.cc b/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.cc
index 5228b1fda52..4ef6c82166d 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.cc
@@ -5,9 +5,9 @@
#include "third_party/blink/renderer/core/page/scrolling/overscroll_controller.h"
#include "cc/input/overscroll_behavior.h"
-#include "third_party/blink/renderer/core/computed_style_base_constants.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
+#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h"
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h b/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h
index 353cea550db..c914145af1c 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/overscroll_controller.h
@@ -25,9 +25,12 @@ class OverscrollController : public GarbageCollected<OverscrollController> {
public:
static OverscrollController* Create(const VisualViewport& visual_viewport,
ChromeClient& chrome_client) {
- return new OverscrollController(visual_viewport, chrome_client);
+ return MakeGarbageCollected<OverscrollController>(visual_viewport,
+ chrome_client);
}
+ OverscrollController(const VisualViewport&, ChromeClient&);
+
void ResetAccumulated(bool reset_x, bool reset_y);
// Reports unused scroll as overscroll to the content layer. The position
@@ -44,8 +47,6 @@ class OverscrollController : public GarbageCollected<OverscrollController> {
void Trace(blink::Visitor*);
private:
- OverscrollController(const VisualViewport&, ChromeClient&);
-
WeakMember<const VisualViewport> visual_viewport_;
WeakMember<ChromeClient> chrome_client_;
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.cc b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.cc
index 29446c84265..20099b81087 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/browser_controls.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/fullscreen/document_fullscreen.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
@@ -69,17 +70,16 @@ PaintLayerScrollableArea* GetScrollableArea(const Element& element) {
if (element.IsFrameOwnerElement()) {
const HTMLFrameOwnerElement* frame_owner =
ToHTMLFrameOwnerElement(&element);
- if (!frame_owner->ContentFrame())
+ EmbeddedContentView* content_view = frame_owner->OwnedEmbeddedContentView();
+ if (!content_view)
return nullptr;
- if (!frame_owner->ContentFrame()->IsLocalFrame())
+ if (!content_view->IsLocalFrameView())
return nullptr;
- LocalFrameView* frame_view =
- ToLocalFrameView(frame_owner->OwnedEmbeddedContentView());
+ LocalFrameView* frame_view = ToLocalFrameView(content_view);
- if (!frame_view)
- return nullptr;
+ DCHECK(frame_view);
return frame_view->LayoutViewport();
}
@@ -88,32 +88,15 @@ PaintLayerScrollableArea* GetScrollableArea(const Element& element) {
return ToLayoutBox(element.GetLayoutObject())->GetScrollableArea();
}
-bool ScrollsVerticalOverflow(LayoutView& layout_view) {
- DCHECK(layout_view.GetScrollableArea());
-
- if (layout_view.Size().IsZero() ||
- !layout_view.GetScrollableArea()->HasVerticalOverflow() ||
- !layout_view.ScrollsOverflowY())
- return false;
-
- ScrollbarMode h_mode;
- ScrollbarMode v_mode;
- layout_view.CalculateScrollbarModes(h_mode, v_mode);
-
- return v_mode != kScrollbarAlwaysOff;
-}
-
} // namespace
// static
RootScrollerController* RootScrollerController::Create(Document& document) {
- return new RootScrollerController(document);
+ return MakeGarbageCollected<RootScrollerController>(document);
}
RootScrollerController::RootScrollerController(Document& document)
- : document_(&document),
- effective_root_scroller_(&document),
- document_has_document_element_(false) {}
+ : document_(&document), effective_root_scroller_(&document) {}
void RootScrollerController::Trace(blink::Visitor* visitor) {
visitor->Trace(document_);
@@ -183,56 +166,47 @@ void RootScrollerController::RecomputeEffectiveRootScroller() {
if (!DocumentFullscreen::fullscreenElement(*document_)) {
bool root_scroller_valid =
root_scroller_ && IsValidRootScroller(*root_scroller_);
- if (root_scroller_valid)
+ if (root_scroller_valid) {
new_effective_root_scroller = root_scroller_;
- else if (implicit_root_scroller_)
+ } else if (implicit_root_scroller_) {
new_effective_root_scroller = implicit_root_scroller_;
+ UseCounter::Count(document_->GetFrame(),
+ WebFeature::kActivatedImplicitRootScroller);
+ }
}
- // TODO(bokan): This is a terrible hack but required because the viewport
- // apply scroll works on Elements rather than Nodes. If we're going from
- // !documentElement to documentElement, we can't early out even if the root
- // scroller didn't change since the global root scroller didn't have an
- // Element previously to put it's ViewportScrollCallback onto. We need this
- // to kick the global root scroller to recompute itself. We can remove this
- // if ScrollCustomization is moved to the Node rather than Element.
- bool old_has_document_element = document_has_document_element_;
- document_has_document_element_ = document_->documentElement();
-
- if (old_has_document_element || !document_has_document_element_) {
- if (effective_root_scroller_ == new_effective_root_scroller)
- return;
- }
+ if (effective_root_scroller_ == new_effective_root_scroller)
+ return;
Node* old_effective_root_scroller = effective_root_scroller_;
effective_root_scroller_ = new_effective_root_scroller;
- if (new_effective_root_scroller != old_effective_root_scroller) {
- if (LayoutBoxModelObject* new_obj =
- new_effective_root_scroller->GetLayoutBoxModelObject()) {
- if (new_obj->Layer()) {
- new_effective_root_scroller->GetLayoutBoxModelObject()
- ->Layer()
- ->SetNeedsCompositingInputsUpdate();
- }
- }
- if (old_effective_root_scroller) {
- if (LayoutBoxModelObject* old_obj =
- old_effective_root_scroller->GetLayoutBoxModelObject()) {
- if (old_obj->Layer()) {
- old_effective_root_scroller->GetLayoutBoxModelObject()
- ->Layer()
- ->SetNeedsCompositingInputsUpdate();
- }
- }
+ DCHECK(new_effective_root_scroller);
+ if (LayoutBoxModelObject* new_obj =
+ new_effective_root_scroller->GetLayoutBoxModelObject()) {
+ if (new_obj->Layer()) {
+ new_effective_root_scroller->GetLayoutBoxModelObject()
+ ->Layer()
+ ->SetNeedsCompositingInputsUpdate();
}
- if (auto* object = old_effective_root_scroller->GetLayoutObject())
- object->SetIsEffectiveRootScroller(false);
+ }
- if (auto* object = new_effective_root_scroller->GetLayoutObject())
- object->SetIsEffectiveRootScroller(true);
+ DCHECK(old_effective_root_scroller);
+ if (LayoutBoxModelObject* old_obj =
+ old_effective_root_scroller->GetLayoutBoxModelObject()) {
+ if (old_obj->Layer()) {
+ old_effective_root_scroller->GetLayoutBoxModelObject()
+ ->Layer()
+ ->SetNeedsCompositingInputsUpdate();
+ }
}
+ if (auto* object = old_effective_root_scroller->GetLayoutObject())
+ object->SetIsEffectiveRootScroller(false);
+
+ if (auto* object = new_effective_root_scroller->GetLayoutObject())
+ object->SetIsEffectiveRootScroller(true);
+
ApplyRootScrollerProperties(*old_effective_root_scroller);
ApplyRootScrollerProperties(*effective_root_scroller_);
@@ -318,7 +292,37 @@ bool RootScrollerController::IsValidImplicit(const Element& element) const {
if (!scrollable_area)
return false;
- return scrollable_area->ScrollsOverflow();
+ if (!scrollable_area->ScrollsOverflow())
+ return false;
+
+ // If any of the ancestors clip overflow, don't promote. Promoting a
+ // descendant of an overflow clip means it may not resize when the URL bar
+ // hides so we'd leave a portion of the page hidden/unreachable.
+ for (LayoutBox* ancestor = element.GetLayoutObject()->ContainingBlock();
+ ancestor; ancestor = ancestor->ContainingBlock()) {
+ // The LayoutView is allowed to have a clip (since its clip is resized by
+ // the URL bar movement). Test it for scrolling so that we only promote if
+ // we know we won't block scrolling the main document.
+ if (ancestor->IsLayoutView()) {
+ const ComputedStyle* style = ancestor->Style();
+ DCHECK(style);
+
+ PaintLayerScrollableArea* area = ancestor->GetScrollableArea();
+ DCHECK(area);
+
+ if ((style->ScrollsOverflowX() && area->HasHorizontalOverflow()) ||
+ (style->ScrollsOverflowY() && area->HasVerticalOverflow())) {
+ return false;
+ }
+ } else {
+ if (ancestor->ShouldClipOverflow() || ancestor->HasMask() ||
+ ancestor->HasClip() || ancestor->HasClipPath()) {
+ return false;
+ }
+ }
+ }
+
+ return true;
}
void RootScrollerController::ApplyRootScrollerProperties(Node& node) {
@@ -388,13 +392,7 @@ void RootScrollerController::ProcessImplicitCandidates() {
if (!document_->GetFrame()->IsMainFrame())
return;
- // If the main document has vertical scrolling, that's a good sign we
- // shouldn't implicitly promote anything.
- if (ScrollsVerticalOverflow(*document_->GetLayoutView()))
- return;
-
- Element* highest_z_element = nullptr;
- bool highest_is_ambiguous = false;
+ bool multiple_matches = false;
HeapHashSet<WeakMember<Element>> copy(implicit_candidates_);
for (auto& element : copy) {
@@ -404,36 +402,20 @@ void RootScrollerController::ProcessImplicitCandidates() {
continue;
}
- if (!highest_z_element) {
- highest_z_element = element;
- } else {
- int element_z = element->GetLayoutObject()->Style()->ZIndex();
- int highest_z = highest_z_element->GetLayoutObject()->Style()->ZIndex();
-
- if (element_z > highest_z) {
- highest_z_element = element;
- highest_is_ambiguous = false;
- } else if (element_z == highest_z) {
- highest_is_ambiguous = true;
- }
- }
+ if (implicit_root_scroller_)
+ multiple_matches = true;
+
+ implicit_root_scroller_ = element;
}
- if (highest_is_ambiguous)
+ // Only promote an implicit root scroller if we have a unique match.
+ if (multiple_matches)
implicit_root_scroller_ = nullptr;
- else
- implicit_root_scroller_ = highest_z_element;
}
PaintLayer* RootScrollerController::RootScrollerPaintLayer() const {
- return RootScrollerUtil::PaintLayerForRootScroller(effective_root_scroller_);
-}
-
-bool RootScrollerController::ScrollsViewport(const Element& element) const {
- if (effective_root_scroller_->IsDocumentNode())
- return element == document_->documentElement();
-
- return element == effective_root_scroller_.Get();
+ return root_scroller_util::PaintLayerForRootScroller(
+ effective_root_scroller_);
}
void RootScrollerController::ElementRemoved(const Element& element) {
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h
index cdffaa1200b..3ca6c592d3b 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h
@@ -42,6 +42,8 @@ class CORE_EXPORT RootScrollerController
// of this class need to be made aware of layout updates.
static RootScrollerController* Create(Document&);
+ RootScrollerController(Document&);
+
void Trace(blink::Visitor*);
// Sets the element that will be used as the root scroller. This can be
@@ -78,13 +80,6 @@ class CORE_EXPORT RootScrollerController
// scroller.
PaintLayer* RootScrollerPaintLayer() const;
- // Used to determine which Element should scroll the viewport. This is
- // needed since Blink's scrolling machinery works on Elements whereas the
- // document *Node* also scrolls so we need to designate an element one
- // Element as the viewport scroller. Sadly, this is *not* the
- // document.scrollingElement in general.
- bool ScrollsViewport(const Element&) const;
-
void ElementRemoved(const Element&);
// In the "implicit root scroller" mode, we might promote an element to
@@ -100,8 +95,6 @@ class CORE_EXPORT RootScrollerController
void PerformRootScrollerSelection();
private:
- RootScrollerController(Document&);
-
// Ensures the effective root scroller is currently valid and replaces it
// with the default if not.
void RecomputeEffectiveRootScroller();
@@ -162,8 +155,6 @@ class CORE_EXPORT RootScrollerController
HeapHashSet<WeakMember<Element>> implicit_candidates_;
WeakMember<Element> implicit_root_scroller_;
-
- bool document_has_document_element_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc
index 0b7f57bd274..8585499402e 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc
@@ -74,12 +74,12 @@ class RootScrollerTest : public testing::Test,
if (document.GetFrame()) {
LocalFrameView* root_view = document.GetFrame()->LocalFrameRoot().View();
if (root_view)
- root_view->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(root_view);
}
}
WebViewImpl* Initialize(const std::string& page_name,
- FrameTestHelpers::TestWebViewClient* client) {
+ frame_test_helpers::TestWebViewClient* client) {
return InitializeInternal(base_url_ + page_name, client);
}
@@ -102,7 +102,7 @@ class RootScrollerTest : public testing::Test,
}
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -113,7 +113,8 @@ class RootScrollerTest : public testing::Test,
void ExecuteScript(const WebString& code, WebLocalFrame& frame) {
frame.ExecuteScript(WebScriptSource(code));
- frame.View()->UpdateAllLifecyclePhases();
+ frame.View()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
RunPendingTasks();
}
@@ -175,8 +176,9 @@ class RootScrollerTest : public testing::Test,
return WebCoalescedInputEvent(event);
}
- WebViewImpl* InitializeInternal(const std::string& url,
- FrameTestHelpers::TestWebViewClient* client) {
+ WebViewImpl* InitializeInternal(
+ const std::string& url,
+ frame_test_helpers::TestWebViewClient* client) {
helper_.InitializeAndLoad(url, nullptr, client, nullptr,
&ConfigureSettings);
@@ -184,13 +186,18 @@ class RootScrollerTest : public testing::Test,
GetWebView()->ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
GetWebView()->GetBrowserControls().SetShownRatio(1);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
return GetWebView();
}
+ void UpdateAllLifecyclePhases(LocalFrameView* view) {
+ view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
std::string base_url_;
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
RuntimeEnabledFeatures::Backup features_backup_;
};
@@ -200,16 +207,9 @@ class RootScrollerTest : public testing::Test,
TEST_F(RootScrollerTest, TestDefaultRootScroller) {
Initialize("overflow-scrolling.html");
- RootScrollerController& controller =
- MainFrame()->GetDocument()->GetRootScrollerController();
-
ASSERT_EQ(nullptr, MainFrame()->GetDocument()->rootScroller());
-
EXPECT_EQ(MainFrame()->GetDocument(),
EffectiveRootScroller(MainFrame()->GetDocument()));
-
- Element* html_element = MainFrame()->GetDocument()->documentElement();
- EXPECT_TRUE(controller.ScrollsViewport(*html_element));
}
// Make sure that replacing the documentElement doesn't change the effective
@@ -218,7 +218,7 @@ TEST_F(RootScrollerTest, defaultEffectiveRootScrollerIsDocumentNode) {
Initialize("root-scroller.html");
Document* document = MainFrame()->GetDocument();
- Element* iframe = document->CreateRawElement(HTMLNames::iframeTag);
+ Element* iframe = document->CreateRawElement(html_names::kIFrameTag);
EXPECT_EQ(MainFrame()->GetDocument(),
EffectiveRootScroller(MainFrame()->GetDocument()));
@@ -229,13 +229,14 @@ TEST_F(RootScrollerTest, defaultEffectiveRootScrollerIsDocumentNode) {
nodes.push_back(NodeOrString::FromNode(iframe));
document->documentElement()->ReplaceWith(nodes, ASSERT_NO_EXCEPTION);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(MainFrame()->GetDocument(),
EffectiveRootScroller(MainFrame()->GetDocument()));
}
-class OverscrollTestWebViewClient : public FrameTestHelpers::TestWebViewClient {
+class OverscrollTestWebViewClient
+ : public frame_test_helpers::TestWebViewClient {
public:
MOCK_METHOD5(DidOverscroll,
void(const WebFloatSize&,
@@ -359,13 +360,13 @@ TEST_F(RootScrollerTest, TestRemoveRootScrollerFromDom) {
Element* container = MainFrame()->GetDocument()->getElementById("container");
SetAndSelectRootScroller(*MainFrame()->GetDocument(), container);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(container, MainFrame()->GetDocument()->rootScroller());
EXPECT_EQ(container, EffectiveRootScroller(MainFrame()->GetDocument()));
MainFrame()->GetDocument()->body()->RemoveChild(container);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(container, MainFrame()->GetDocument()->rootScroller());
EXPECT_NE(container, EffectiveRootScroller(MainFrame()->GetDocument()));
@@ -413,7 +414,7 @@ TEST_F(RootScrollerTest, TestRootScrollerBecomesInvalid) {
ExecuteScript(
"document.querySelector('#container').style.display = 'inline'");
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(container, MainFrame()->GetDocument()->rootScroller());
EXPECT_EQ(MainFrame()->GetDocument(),
@@ -433,7 +434,7 @@ TEST_F(RootScrollerTest, TestRootScrollerBecomesInvalid) {
EXPECT_EQ(container, EffectiveRootScroller(MainFrame()->GetDocument()));
ExecuteScript("document.querySelector('#container').style.width = '98%'");
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(container, MainFrame()->GetDocument()->rootScroller());
EXPECT_EQ(MainFrame()->GetDocument(),
@@ -540,13 +541,13 @@ TEST_F(RootScrollerTest, SetRootScrollerIframeUsesCorrectLayerAndCallback) {
const TopDocumentRootScrollerController& main_controller =
MainFrame()->GetDocument()->GetPage()->GlobalRootScrollerController();
- // No root scroller set, the documentElement should be the effective root
- // and the main LocalFrameView's scroll layer should be the layer to use.
+ // No root scroller set, the document node should be the global root and the
+ // main LocalFrameView's scroll layer should be the layer to use.
{
EXPECT_EQ(main_controller.RootScrollerLayer(),
MainFrameView()->LayoutViewport()->LayerForScrolling());
EXPECT_TRUE(main_controller.IsViewportScrollCallback(
- MainFrame()->GetDocument()->documentElement()->GetApplyScroll()));
+ MainFrame()->GetDocument()->GetApplyScroll()));
}
// Set a root scroller in the iframe. Since the main document didn't set a
@@ -557,7 +558,7 @@ TEST_F(RootScrollerTest, SetRootScrollerIframeUsesCorrectLayerAndCallback) {
EXPECT_EQ(main_controller.RootScrollerLayer(),
MainFrameView()->LayoutViewport()->LayerForScrolling());
EXPECT_TRUE(main_controller.IsViewportScrollCallback(
- MainFrame()->GetDocument()->documentElement()->GetApplyScroll()));
+ MainFrame()->GetDocument()->GetApplyScroll()));
}
// Setting the iframe as the root scroller in the main frame should now
@@ -571,14 +572,14 @@ TEST_F(RootScrollerTest, SetRootScrollerIframeUsesCorrectLayerAndCallback) {
EXPECT_EQ(main_controller.RootScrollerLayer(),
container_scroller->LayerForScrolling());
EXPECT_FALSE(main_controller.IsViewportScrollCallback(
- MainFrame()->GetDocument()->documentElement()->GetApplyScroll()));
+ MainFrame()->GetDocument()->GetApplyScroll()));
EXPECT_TRUE(
main_controller.IsViewportScrollCallback(container->GetApplyScroll()));
}
- // Unsetting the root scroller in the iframe should reset its effective
- // root scroller to the iframe's documentElement and thus the iframe's
- // documentElement becomes the global root scroller.
+ // Unsetting the root scroller in the iframe should reset its effective root
+ // scroller to the iframe's document node and thus it becomes the global root
+ // scroller.
{
SetAndSelectRootScroller(*iframe->contentDocument(), nullptr);
EXPECT_EQ(main_controller.RootScrollerLayer(), iframe->contentDocument()
@@ -588,23 +589,23 @@ TEST_F(RootScrollerTest, SetRootScrollerIframeUsesCorrectLayerAndCallback) {
EXPECT_FALSE(
main_controller.IsViewportScrollCallback(container->GetApplyScroll()));
EXPECT_FALSE(main_controller.IsViewportScrollCallback(
- MainFrame()->GetDocument()->documentElement()->GetApplyScroll()));
+ MainFrame()->GetDocument()->GetApplyScroll()));
EXPECT_TRUE(main_controller.IsViewportScrollCallback(
- iframe->contentDocument()->documentElement()->GetApplyScroll()));
+ iframe->contentDocument()->GetApplyScroll()));
}
// Finally, unsetting the main frame's root scroller should reset it to the
- // documentElement and corresponding layer.
+ // document node and corresponding layer.
{
SetAndSelectRootScroller(*MainFrame()->GetDocument(), nullptr);
EXPECT_EQ(main_controller.RootScrollerLayer(),
MainFrameView()->LayoutViewport()->LayerForScrolling());
EXPECT_TRUE(main_controller.IsViewportScrollCallback(
- MainFrame()->GetDocument()->documentElement()->GetApplyScroll()));
+ MainFrame()->GetDocument()->GetApplyScroll()));
EXPECT_FALSE(
main_controller.IsViewportScrollCallback(container->GetApplyScroll()));
EXPECT_FALSE(main_controller.IsViewportScrollCallback(
- iframe->contentDocument()->documentElement()->GetApplyScroll()));
+ iframe->contentDocument()->GetApplyScroll()));
}
}
@@ -613,22 +614,22 @@ TEST_F(RootScrollerTest, SetRootScrollerIframeUsesCorrectLayerAndCallback) {
TEST_F(RootScrollerTest, RemoveCurrentRootScroller) {
Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " margin: 0px;"
- " }"
- " #container {"
- " width: 100%;"
- " height: 100%;"
- " position: absolute;"
- " overflow: auto;"
- " }"
- "</style>"
- "<div id='container'></div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://www.test.com/");
+ frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " margin: 0px;"
+ " }"
+ " #container {"
+ " width: 100%;"
+ " height: 100%;"
+ " position: absolute;"
+ " overflow: auto;"
+ " }"
+ "</style>"
+ "<div id='container'></div>",
+ base_url);
RootScrollerController& controller =
MainFrame()->GetDocument()->GetRootScrollerController();
@@ -639,7 +640,7 @@ TEST_F(RootScrollerTest, RemoveCurrentRootScroller) {
{
MainFrame()->GetDocument()->setRootScroller(container, ASSERT_NO_EXCEPTION);
ASSERT_EQ(container, controller.Get());
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
ASSERT_EQ(container, controller.EffectiveRootScroller());
}
@@ -659,25 +660,25 @@ TEST_F(RootScrollerTest, RemoveCurrentRootScroller) {
TEST_F(RootScrollerTest, AlwaysCreateCompositedScrollingLayers) {
Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body {"
- " margin: 0px;"
- " }"
- " #container {"
- " width: 100%;"
- " height: 100%;"
- " position: absolute;"
- " overflow: auto;"
- " }"
- "</style>"
- "<div id='container'></div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://www.test.com/");
+ frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body {"
+ " margin: 0px;"
+ " }"
+ " #container {"
+ " width: 100%;"
+ " height: 100%;"
+ " position: absolute;"
+ " overflow: auto;"
+ " }"
+ "</style>"
+ "<div id='container'></div>",
+ base_url);
GetWebView()->ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
Element* container = MainFrame()->GetDocument()->getElementById("container");
@@ -740,7 +741,7 @@ TEST_F(RootScrollerTest, RemoteIFrame) {
Initialize("root-scroller-iframe.html");
// Initialization: Replace the iframe with a remote frame.
- MainWebFrame()->FirstChild()->Swap(FrameTestHelpers::CreateRemote());
+ MainWebFrame()->FirstChild()->Swap(frame_test_helpers::CreateRemote());
// Set the root scroller in the local main frame to the iframe (which is
// remote). Make sure we don't promote a remote frame to the root scroller.
@@ -750,7 +751,7 @@ TEST_F(RootScrollerTest, RemoteIFrame) {
EXPECT_EQ(iframe, MainFrame()->GetDocument()->rootScroller());
EXPECT_EQ(MainFrame()->GetDocument(),
EffectiveRootScroller(MainFrame()->GetDocument()));
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
}
}
@@ -767,12 +768,12 @@ TEST_F(RootScrollerTest, IFrameSwapToRemote) {
// Swap in a remote frame. Make sure we revert back to the document.
{
- MainWebFrame()->FirstChild()->Swap(FrameTestHelpers::CreateRemote());
- MainFrameView()->UpdateAllLifecyclePhases();
+ MainWebFrame()->FirstChild()->Swap(frame_test_helpers::CreateRemote());
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(MainFrame()->GetDocument(),
EffectiveRootScroller(MainFrame()->GetDocument()));
GetWebView()->ResizeWithBrowserControls(IntSize(400, 450), 50, 0, false);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(MainFrame()->GetDocument(),
EffectiveRootScroller(MainFrame()->GetDocument()));
}
@@ -796,14 +797,14 @@ TEST_F(RootScrollerTest, RemoteMainFrame) {
// Initialization: Set the main frame to be a RemoteFrame and add a local
// child.
{
- WebRemoteFrameImpl* remote_main_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrameImpl* remote_main_frame = frame_test_helpers::CreateRemote();
helper_.LocalMainFrame()->Swap(remote_main_frame);
remote_main_frame->SetReplicatedOrigin(
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
- local_frame = FrameTestHelpers::CreateLocalChild(*remote_main_frame);
+ local_frame = frame_test_helpers::CreateLocalChild(*remote_main_frame);
- FrameTestHelpers::LoadFrame(local_frame,
- base_url_ + "root-scroller-child.html");
+ frame_test_helpers::LoadFrame(local_frame,
+ base_url_ + "root-scroller-child.html");
widget = local_frame->FrameWidget();
widget->Resize(WebSize(400, 400));
}
@@ -857,23 +858,23 @@ TEST_F(RootScrollerTest, NonMainLocalRootLifecycle) {
// Setup a Local <- Remote <- Local frame hierarchy.
{
Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
- R"HTML(
+ WebURL base_url = url_test_helpers::ToKURL("http://www.test.com/");
+ frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
+ R"HTML(
<!DOCTYPE html>
<iframe></iframe>
)HTML",
- base_url);
- MainFrameView()->UpdateAllLifecyclePhases();
+ base_url);
+ UpdateAllLifecyclePhases(MainFrameView());
- WebRemoteFrameImpl* remote_frame = FrameTestHelpers::CreateRemote();
+ WebRemoteFrameImpl* remote_frame = frame_test_helpers::CreateRemote();
WebLocalFrameImpl* child =
ToWebLocalFrameImpl(helper_.LocalMainFrame()->FirstChild());
child->Swap(remote_frame);
remote_frame->SetReplicatedOrigin(
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
- non_main_local_root = FrameTestHelpers::CreateLocalChild(*remote_frame);
+ non_main_local_root = frame_test_helpers::CreateLocalChild(*remote_frame);
ASSERT_EQ(non_main_local_root->LocalRoot(), non_main_local_root);
ASSERT_TRUE(non_main_local_root->Parent());
}
@@ -881,10 +882,9 @@ TEST_F(RootScrollerTest, NonMainLocalRootLifecycle) {
const TopDocumentRootScrollerController& global_controller =
MainFrame()->GetDocument()->GetPage()->GlobalRootScrollerController();
- ASSERT_EQ(MainFrame()->GetDocument()->documentElement(),
- global_controller.GlobalRootScroller());
+ ASSERT_EQ(MainFrame()->GetDocument(), global_controller.GlobalRootScroller());
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
GraphicsLayer* scroll_layer = global_controller.RootScrollerLayer();
GraphicsLayer* container_layer = global_controller.RootContainerLayer();
@@ -895,11 +895,10 @@ TEST_F(RootScrollerTest, NonMainLocalRootLifecycle) {
// root do a complete lifecycle update.
helper_.LocalMainFrame()->GetFrameView()->SetNeedsLayout();
helper_.LocalMainFrame()->GetFrameView()->UpdateLifecycleToLayoutClean();
- non_main_local_root->GetFrameView()->UpdateAllLifecyclePhases();
- helper_.LocalMainFrame()->GetFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(non_main_local_root->GetFrameView());
+ UpdateAllLifecyclePhases(helper_.LocalMainFrame()->GetFrameView());
- EXPECT_EQ(MainFrame()->GetDocument()->documentElement(),
- global_controller.GlobalRootScroller());
+ EXPECT_EQ(MainFrame()->GetDocument(), global_controller.GlobalRootScroller());
EXPECT_EQ(global_controller.RootScrollerLayer(), scroll_layer);
EXPECT_EQ(global_controller.RootContainerLayer(), container_layer);
}
@@ -945,8 +944,7 @@ TEST_F(RootScrollerTest, DocumentElementHasNoLayoutObject) {
const TopDocumentRootScrollerController& global_controller =
MainFrame()->GetDocument()->GetPage()->GlobalRootScrollerController();
- EXPECT_EQ(MainFrame()->GetDocument()->documentElement(),
- global_controller.GlobalRootScroller());
+ EXPECT_EQ(MainFrame()->GetDocument(), global_controller.GlobalRootScroller());
EXPECT_EQ(MainFrameView()->LayoutViewport()->LayerForScrolling(),
global_controller.RootScrollerLayer());
}
@@ -987,7 +985,7 @@ TEST_F(RootScrollerTest, UseVisualViewportScrollbarsIframe) {
"document.getElementById('container').style.height = '200%';",
*child_web_frame);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
ScrollableArea* container_scroller = child_frame->View()->LayoutViewport();
@@ -1000,28 +998,28 @@ TEST_F(RootScrollerTest, UseVisualViewportScrollbarsIframe) {
TEST_F(RootScrollerTest, TopControlsAdjustmentAppliedToRootScroller) {
Initialize();
- WebURL base_url = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body, html {"
- " width: 100%;"
- " height: 100%;"
- " margin: 0px;"
- " }"
- " #container {"
- " width: 100%;"
- " height: 100%;"
- " overflow: auto;"
- " }"
- "</style>"
- "<div id='container'>"
- " <div style='height:1000px'>test</div>"
- "</div>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://www.test.com/");
+ frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<style>"
+ " body, html {"
+ " width: 100%;"
+ " height: 100%;"
+ " margin: 0px;"
+ " }"
+ " #container {"
+ " width: 100%;"
+ " height: 100%;"
+ " overflow: auto;"
+ " }"
+ "</style>"
+ "<div id='container'>"
+ " <div style='height:1000px'>test</div>"
+ "</div>",
+ base_url);
GetWebView()->ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
Element* container = MainFrame()->GetDocument()->getElementById("container");
SetAndSelectRootScroller(*MainFrame()->GetDocument(), container);
@@ -1061,7 +1059,7 @@ TEST_F(RootScrollerTest, RotationAnchoring) {
{
GetWebView()->ResizeWithBrowserControls(IntSize(250, 1000), 0, 0, true);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
Element* container =
MainFrame()->GetDocument()->getElementById("container");
@@ -1100,7 +1098,7 @@ TEST_F(RootScrollerTest, RotationAnchoring) {
// Now do a rotation resize.
GetWebView()->ResizeWithBrowserControls(IntSize(1000, 250), 50, 0, false);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
// The visual viewport should remain fully filled by the target.
DOMRect* rect = target->getBoundingClientRect();
@@ -1116,15 +1114,15 @@ TEST_F(RootScrollerTest, InvalidDefaultRootScroller) {
Document* document = MainFrame()->GetDocument();
- Element* br = document->CreateRawElement(HTMLNames::brTag);
+ Element* br = document->CreateRawElement(html_names::kBrTag);
document->ReplaceChild(br, document->documentElement());
- MainFrameView()->UpdateAllLifecyclePhases();
- Element* html = document->CreateRawElement(HTMLNames::htmlTag);
- Element* body = document->CreateRawElement(HTMLNames::bodyTag);
+ UpdateAllLifecyclePhases(MainFrameView());
+ Element* html = document->CreateRawElement(html_names::kHTMLTag);
+ Element* body = document->CreateRawElement(html_names::kBodyTag);
html->AppendChild(body);
body->AppendChild(br);
document->AppendChild(html);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
}
// Makes sure that when an iframe becomes the effective root scroller, its
@@ -1134,7 +1132,7 @@ TEST_F(RootScrollerTest, InvalidDefaultRootScroller) {
// resizes by the URL bar.
TEST_F(RootScrollerTest, IFrameRootScrollerGetsNonFixedLayoutSize) {
Initialize("root-scroller-iframe.html");
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
Document* document = MainFrame()->GetDocument();
HTMLFrameOwnerElement* iframe = ToHTMLFrameOwnerElement(
@@ -1158,7 +1156,7 @@ TEST_F(RootScrollerTest, IFrameRootScrollerGetsNonFixedLayoutSize) {
// size should remain the same.
{
GetWebView()->ResizeWithBrowserControls(IntSize(400, 450), 50, 0, false);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(IntSize(400, 400), iframe_view->GetLayoutSize());
EXPECT_EQ(IntSize(400, 450), iframe_view->Size());
}
@@ -1166,19 +1164,19 @@ TEST_F(RootScrollerTest, IFrameRootScrollerGetsNonFixedLayoutSize) {
// Simulate a rotation. This time the layout size should reflect the resize.
{
GetWebView()->ResizeWithBrowserControls(IntSize(450, 400), 50, 0, false);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(IntSize(450, 350), iframe_view->GetLayoutSize());
EXPECT_EQ(IntSize(450, 400), iframe_view->Size());
// "Un-rotate" for following tests.
GetWebView()->ResizeWithBrowserControls(IntSize(400, 450), 50, 0, false);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
}
// Show the URL bar again. The frame rect should match the viewport.
{
GetWebView()->ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(IntSize(400, 400), iframe_view->GetLayoutSize());
EXPECT_EQ(IntSize(400, 400), iframe_view->Size());
}
@@ -1187,7 +1185,7 @@ TEST_F(RootScrollerTest, IFrameRootScrollerGetsNonFixedLayoutSize) {
// tracking layout size by frame rect.
{
GetWebView()->ResizeWithBrowserControls(IntSize(400, 450), 50, 0, false);
- MainFrameView()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(MainFrameView());
EXPECT_EQ(IntSize(400, 400), iframe_view->GetLayoutSize());
EXPECT_EQ(IntSize(400, 450), iframe_view->Size());
SetAndSelectRootScroller(*document, nullptr);
@@ -1279,6 +1277,21 @@ TEST_F(RootScrollerSimTest, SetCausesNeedsBeginFrame) {
GetDocument().GetRootScrollerController().EffectiveRootScroller());
}
+// Test that the cached IsEffectiveRootScroller bit on LayoutObject is set
+// correctly when the Document is the effective root scroller. It becomes the
+// root scroller before Document has a LayoutView.
+TEST_F(RootScrollerSimTest, DocumentEffectiveSetsCachedBit) {
+ WebView().Resize(WebSize(800, 600));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ )HTML");
+ Compositor().BeginFrame();
+
+ EXPECT_TRUE(GetDocument().GetLayoutView()->IsEffectiveRootScroller());
+}
+
// Test that layout from outside a lifecycle wont select a new effective root
// scroller.
TEST_F(RootScrollerSimTest, NonLifecycleLayoutDoesntCauseReselection) {
@@ -1431,7 +1444,7 @@ TEST_F(RootScrollerSimTest, UsePaddingBoxForViewportFillingCondition) {
// Setting a border should cause the element to no longer be valid as its
// padding box doesn't fill the viewport exactly.
- container->setAttribute(HTMLNames::styleAttr, "border: 1px solid black");
+ container->setAttribute(html_names::kStyleAttr, "border: 1px solid black");
Compositor().BeginFrame();
EXPECT_EQ(&GetDocument(),
GetDocument().GetRootScrollerController().EffectiveRootScroller());
@@ -1576,6 +1589,9 @@ TEST_F(ImplicitRootScrollerSimTest, ImplicitRootScroller) {
width: 0px;
height: 0px;
}
+ html {
+ overflow: hidden;
+ }
body, html {
width: 100%;
height: 100%;
@@ -1589,17 +1605,9 @@ TEST_F(ImplicitRootScrollerSimTest, ImplicitRootScroller) {
width: 100%;
height: 100%;
}
- /* Makes sure the document doesn't have any overflow itself */
- #clip {
- overflow: hidden;
- width: 100%;
- height: 100%;
- }
</style>
- <div id="clip">
- <div id="container">
- <div id="spacer"></div>
- </div>
+ <div id="container">
+ <div id="spacer"></div>
</div>
)HTML");
Compositor().BeginFrame();
@@ -1755,13 +1763,32 @@ TEST_F(ImplicitRootScrollerSimTest, CandidateLosesLayoutBoxDontCrash) {
Element* container = GetDocument().getElementById("container");
// An overflowing box will be added to the implicit candidates list.
- container->setAttribute(HTMLNames::classAttr, "box");
+ container->setAttribute(html_names::kClassAttr, "box");
Compositor().BeginFrame();
// This will make change from a box to an inline. Ensure we don't crash when
// we reevaluate the candidates list.
- container->setAttribute(HTMLNames::classAttr, "nonbox");
+ container->setAttribute(html_names::kClassAttr, "nonbox");
+ Compositor().BeginFrame();
+}
+
+// Ensure that a plugin view being considered for implicit promotion doesn't
+// cause a crash. https://crbug.com/903440.
+TEST_F(ImplicitRootScrollerSimTest, ConsiderEmbedCrash) {
+ WebView().Resize(WebSize(800, 600));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <embed id="embed" height="1" src="data:video/mp4,">
+ <script>
+ embed.type = "JavaScript 1.5";
+ embed.src = "x";
+ </script>
+ )HTML");
Compositor().BeginFrame();
+ Element* embed = GetDocument().getElementById("embed");
+ GetDocument().GetRootScrollerController().ConsiderForImplicit(*embed);
}
// Test that a valid implicit root scroller wont be promoted/will be demoted if
@@ -1937,6 +1964,204 @@ TEST_F(ImplicitRootScrollerSimTest, ImplicitRootScrollerIframe) {
GetDocument().GetRootScrollerController().EffectiveRootScroller());
}
+// Tests use counter for implicit root scroller. Ensure it's not counted on a
+// page without an implicit root scroller.
+TEST_F(ImplicitRootScrollerSimTest, UseCounterNegative) {
+ WebView().Resize(WebSize(800, 600));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ div {
+ width: 100%;
+ height: 100%;
+ }
+ </style>
+ <div id="container"></div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ Element* container = GetDocument().getElementById("container");
+ ASSERT_NE(container,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+
+ EXPECT_FALSE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kActivatedImplicitRootScroller));
+
+ container->style()->setProperty(&GetDocument(), "height", "150%", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ EXPECT_FALSE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kActivatedImplicitRootScroller));
+}
+
+// Tests use counter for implicit root scroller. Ensure it's counted on a
+// page that loads with an implicit root scroller.
+TEST_F(ImplicitRootScrollerSimTest, UseCounterPositive) {
+ WebView().Resize(WebSize(800, 600));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ #container {
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ }
+ #spacer {
+ height: 2000px;
+ }
+ </style>
+ <div id="container">
+ <div id="spacer"></div>
+ </div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ Element* container = GetDocument().getElementById("container");
+ ASSERT_EQ(container,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+
+ EXPECT_TRUE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kActivatedImplicitRootScroller));
+
+ container->style()->setProperty(&GetDocument(), "height", "150%", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ ASSERT_NE(container,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+
+ EXPECT_TRUE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kActivatedImplicitRootScroller));
+}
+
+// Tests use counter for implicit root scroller. Ensure it's counted on a
+// page that loads without an implicit root scroller but later gets one.
+TEST_F(ImplicitRootScrollerSimTest, UseCounterPositiveAfterLoad) {
+ WebView().Resize(WebSize(800, 600));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ #container {
+ width: 100%;
+ height: 40%;
+ overflow: auto;
+ }
+ #spacer {
+ height: 2000px;
+ }
+ </style>
+ <div id="container">
+ <div id="spacer"></div>
+ </div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ Element* container = GetDocument().getElementById("container");
+ ASSERT_NE(container,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+
+ EXPECT_FALSE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kActivatedImplicitRootScroller));
+
+ container->style()->setProperty(&GetDocument(), "height", "100%", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ ASSERT_EQ(container,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+
+ EXPECT_TRUE(UseCounter::IsCounted(
+ GetDocument(), WebFeature::kActivatedImplicitRootScroller));
+}
+
+// Tests that if we have multiple valid candidates for implicit promotion, we
+// don't promote either.
+TEST_F(ImplicitRootScrollerSimTest, DontPromoteWhenMultipleAreValid) {
+ WebView().Resize(WebSize(800, 600));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ iframe {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ </style>
+ <iframe id="container"
+ srcdoc="<!DOCTYPE html><style>html {height: 300%;}</style>">
+ </iframe>
+ <iframe id="container2"
+ srcdoc="<!DOCTYPE html><style>html {height: 300%;}</style>">
+ </iframe>
+ )HTML");
+ // srcdoc iframe loads via posted tasks.
+ RunPendingTasks();
+ Compositor().BeginFrame();
+
+ // Since both iframes are valid candidates, neither should be promoted.
+ ASSERT_EQ(&GetDocument(),
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+
+ // Now make the second one invalid, that should cause the first to be
+ // promoted.
+ Element* container2 = GetDocument().getElementById("container2");
+ container2->style()->setProperty(&GetDocument(), "height", "95%", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ Element* container = GetDocument().getElementById("container");
+ ASSERT_EQ(container,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller());
+}
+
// Test that when a valid iframe becomes loaded and thus should be promoted, it
// becomes the root scroller, without needing an intervening layout.
TEST_F(ImplicitRootScrollerSimTest, IframeLoadedWithoutLayout) {
@@ -2159,6 +2384,9 @@ TEST_F(ImplicitRootScrollerSimTest, ContinuallyReevaluateImplicitPromotion) {
width: 0px;
height: 0px;
}
+ html {
+ overflow: hidden;
+ }
body, html {
width: 100%;
height: 100%;
@@ -2168,21 +2396,14 @@ TEST_F(ImplicitRootScrollerSimTest, ContinuallyReevaluateImplicitPromotion) {
width: 100%;
height: 100%;
}
- #clip {
- width: 100%;
- height: 100%;
- overflow: hidden;
- }
#parent {
width: 100%;
height: 100%;
}
</style>
- <div id="clip">
- <div id="parent">
- <div id="container">
- <div id="spacer"></div>
- </div>
+ <div id="parent">
+ <div id="container">
+ <div id="spacer"></div>
</div>
</div>
)HTML");
@@ -2391,11 +2612,186 @@ TEST_F(ImplicitRootScrollerSimTest, OverflowInMainDocumentRestrictsImplicit) {
ASSERT_NO_EXCEPTION);
Compositor().BeginFrame();
+ EXPECT_EQ(GetDocument(),
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe still shouldn't be promoted due to horizontal overflow in "
+ << "the main document.";
+
+ spacer->style()->setProperty(&GetDocument(), "width", "100%", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
EXPECT_EQ(GetDocument().getElementById("container"),
GetDocument().GetRootScrollerController().EffectiveRootScroller())
<< "Once vertical overflow is removed, the iframe should be promoted.";
}
+// Test that we overflow in the document allows promotion only so long as the
+// document isn't scrollable.
+TEST_F(ImplicitRootScrollerSimTest, OverflowHiddenDoesntRestrictImplicit) {
+ WebView().ResizeWithBrowserControls(IntSize(800, 600), 50, 0, true);
+ SimRequest main_request("https://example.com/test.html", "text/html");
+ SimRequest child_request("https://example.com/child.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ main_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ html {
+ overflow: hidden;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ #spacer {
+ position: absolute;
+ left: 0;
+ top: 0;
+ height: 150%;
+ width: 150%;
+ }
+ </style>
+ <iframe id="container" src="child.html">
+ </iframe>
+ <div id="spacer"></div>
+ )HTML");
+ child_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1000px;
+ }
+ </style>
+ )HTML");
+
+ Compositor().BeginFrame();
+ EXPECT_EQ(GetDocument().getElementById("container"),
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe should be promoted since document's overflow is hidden.";
+
+ Element* html = GetDocument().documentElement();
+ html->style()->setProperty(&GetDocument(), "overflow", "auto", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(GetDocument(),
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe should now be demoted since main document scrolls overflow.";
+
+ html->style()->setProperty(&GetDocument(), "overflow", "visible", String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(GetDocument(),
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe should remain demoted since overflow:visible on document "
+ << "allows scrolling.";
+}
+
+// Test that any non-document, clipping ancestor prevents implicit promotion.
+TEST_F(ImplicitRootScrollerSimTest, ClippingAncestorPreventsPromotion) {
+ WebView().ResizeWithBrowserControls(IntSize(800, 600), 50, 0, true);
+ SimRequest main_request("https://example.com/test.html", "text/html");
+ SimRequest child_request("https://example.com/child.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ main_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ html {
+ overflow: hidden;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ #ancestor {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ overflow: visible;
+ /* opacity ensures #ancestor doesn't get considered for root
+ * scroller promotion. */
+ opacity: 0.5;
+ }
+ #spacer {
+ height: 150%;
+ width: 150%;
+ }
+ </style>
+ <div id="ancestor">
+ <iframe id="container" src="child.html"></iframe>
+ <div id="spacer"></div>
+ </div>
+ )HTML");
+ child_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1000px;
+ }
+ </style>
+ )HTML");
+ Compositor().BeginFrame();
+
+ // Each of these style-value pairs should prevent promotion of the iframe.
+ std::vector<std::tuple<String, String>> test_cases = {
+ {"overflow", "scroll"},
+ {"overflow", "hidden"},
+ {"overflow", "auto"},
+ {"contain", "paint"},
+ {"-webkit-mask-image", "linear-gradient(black 25%, transparent 50%)"},
+ {"clip", "rect(10px, 290px, 190px, 10px"},
+ {"clip-path", "circle(40%)"}};
+
+ for (auto test_case : test_cases) {
+ String& style = std::get<0>(test_case);
+ String& style_val = std::get<1>(test_case);
+ Element* ancestor = GetDocument().getElementById("ancestor");
+ Element* iframe = GetDocument().getElementById("container");
+
+ ASSERT_EQ(iframe,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe should start off promoted.";
+
+ ancestor->style()->setProperty(&GetDocument(), style, style_val, String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(GetDocument(),
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe should be demoted since ancestor has " << style << ": "
+ << style_val;
+
+ ancestor->style()->setProperty(&GetDocument(), style, String(), String(),
+ ASSERT_NO_EXCEPTION);
+ Compositor().BeginFrame();
+ ASSERT_EQ(iframe,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "iframe should be promoted since ancestor removed " << style << ": "
+ << style_val;
+ }
+}
+
TEST_F(ImplicitRootScrollerSimTest, AppliedAtFractionalZoom) {
// Matches Pixel 2XL screen size of 412x671 at 3.5 DevicePixelRatio.
WebView().SetZoomFactorForDeviceScaleFactor(3.5f);
@@ -2464,142 +2860,315 @@ TEST_F(ImplicitRootScrollerSimTest, AppliedAtFractionalZoom) {
<< "<iframe> should remain promoted when URL bar is hidden";
}
-class RootScrollerHitTest : public RootScrollerTest {
+class RootScrollerHitTest : public RootScrollerSimTest {
public:
- void CheckHitTestAtBottomOfScreen() {
+ void CheckHitTestAtBottomOfScreen(Element* target) {
HideTopControlsWithMaximalScroll();
// Do a hit test at the very bottom of the screen. This should be outside
// the root scroller's LayoutBox since inert top controls won't resize the
// ICB but, since we expaned the clip, we should still be able to hit the
// target.
- WebPoint point(200, 445);
+ gfx::Point point(200, 445);
WebSize tap_area(20, 20);
- WebHitTestResult result =
- GetWebView()->HitTestResultForTap(point, tap_area);
+ WebHitTestResult result = WebView().HitTestResultForTap(point, tap_area);
Node* hit_node = result.GetNode().Unwrap<Node>();
- Element* target = MainFrame()->GetDocument()->getElementById("target");
- ASSERT_TRUE(target);
EXPECT_EQ(target, hit_node);
}
+ BrowserControls& GetBrowserControls() {
+ return GetDocument().GetPage()->GetBrowserControls();
+ }
+
private:
void HideTopControlsWithMaximalScroll() {
// Do a scroll gesture that hides the top controls and scrolls all the way
// to the bottom.
- GetWebView()->HandleInputEvent(
- GenerateTouchGestureEvent(WebInputEvent::kGestureScrollBegin));
ASSERT_EQ(1, GetBrowserControls().ShownRatio());
- GetWebView()->HandleInputEvent(
- GenerateTouchGestureEvent(WebInputEvent::kGestureScrollUpdate, 0,
- -GetBrowserControls().TopHeight()));
+ WebView().ApplyViewportChanges({gfx::ScrollOffset(), gfx::Vector2dF(), 1,
+ -1, cc::BrowserControlsState::kBoth});
ASSERT_EQ(0, GetBrowserControls().ShownRatio());
- GetWebView()->HandleInputEvent(GenerateTouchGestureEvent(
- WebInputEvent::kGestureScrollUpdate, 0, -100000));
- GetWebView()->HandleInputEvent(
- GenerateTouchGestureEvent(WebInputEvent::kGestureScrollEnd));
- GetWebView()->ResizeWithBrowserControls(IntSize(400, 450), 50, 0, false);
+
+ Node* scroller = GetDocument()
+ .GetPage()
+ ->GlobalRootScrollerController()
+ .GlobalRootScroller();
+ ScrollableArea* scrollable_area =
+ ToLayoutBox(scroller->GetLayoutObject())->GetScrollableArea();
+ scrollable_area->DidScroll(FloatPoint(0, 100000));
+
+ WebView().ResizeWithBrowserControls(IntSize(400, 450), 50, 0, false);
+
+ Compositor().BeginFrame();
}
};
// Test that hit testing in the area revealed at the bottom of the screen
// revealed by hiding the URL bar works properly when using a root scroller
// when the target and scroller are in the same PaintLayer.
-// TODO(chrishtr): fix this for root scrollers.
-TEST_F(RootScrollerHitTest, DISABLED_HitTestInAreaRevealedByURLBarSameLayer) {
+TEST_F(RootScrollerHitTest, HitTestInAreaRevealedByURLBarSameLayer) {
+ WebView().ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
+ GetBrowserControls().SetShownRatio(1);
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+
// Add a target at the bottom of the root scroller that's the size of the url
// bar. We'll test that hiding the URL bar appropriately adjusts clipping so
// that we can hit this target.
- Initialize();
- WebURL baseURL = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body, html {"
- " height: 100%;"
- " margin: 0px;"
- " }"
- " #spacer {"
- " height: 1000px;"
- " }"
- " #container {"
- " position: absolute;"
- " width: 100%;"
- " height: 100%;"
- " overflow: auto;"
- " }"
- " #target {"
- " width: 100%;"
- " height: 50px;"
- " }"
- "</style>"
- "<div id='container'>"
- " <div id='spacer'></div>"
- " <div id='target'></div>"
- "</div>",
- baseURL);
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ height: 100%;
+ margin: 0px;
+ }
+ #spacer {
+ height: 1000px;
+ }
+ #container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ }
+ #target {
+ width: 100%;
+ height: 50px;
+ }
+ </style>
+ <div id='container'>
+ <div id='spacer'></div>
+ <div id='target'></div>
+ </div>
+ )HTML");
- Document* document = MainFrame()->GetDocument();
- Element* container = document->getElementById("container");
- Element* target = document->getElementById("target");
- SetAndSelectRootScroller(*document, container);
+ Element* container = GetDocument().getElementById("container");
+ Element* target = GetDocument().getElementById("target");
+ GetDocument().setRootScroller(container, ASSERT_NO_EXCEPTION);
+
+ Compositor().BeginFrame();
// This test checks hit testing while the target is in the same PaintLayer as
// the root scroller.
ASSERT_EQ(ToLayoutBox(target->GetLayoutObject())->EnclosingLayer(),
ToLayoutBox(container->GetLayoutObject())->Layer());
- CheckHitTestAtBottomOfScreen();
+ CheckHitTestAtBottomOfScreen(target);
}
// Test that hit testing in the area revealed at the bottom of the screen
// revealed by hiding the URL bar works properly when using a root scroller
// when the target and scroller are in different PaintLayers.
TEST_F(RootScrollerHitTest, HitTestInAreaRevealedByURLBarDifferentLayer) {
+ WebView().ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
+ GetBrowserControls().SetShownRatio(1);
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+
// Add a target at the bottom of the root scroller that's the size of the url
// bar. We'll test that hiding the URL bar appropriately adjusts clipping so
// that we can hit this target.
- Initialize();
- WebURL baseURL = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<style>"
- " body, html {"
- " height: 100%;"
- " margin: 0px;"
- " }"
- " #spacer {"
- " height: 1000px;"
- " }"
- " #container {"
- " position: absolute;"
- " width: 100%;"
- " height: 100%;"
- " overflow: auto;"
- " }"
- " #target {"
- " width: 100%;"
- " height: 50px;"
- " will-change: transform;"
- " }"
- "</style>"
- "<div id='container'>"
- " <div id='spacer'></div>"
- " <div id='target'></div>"
- "</div>",
- baseURL);
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ height: 100%;
+ margin: 0px;
+ }
+ #spacer {
+ height: 1000px;
+ }
+ #container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ }
+ #target {
+ width: 100%;
+ height: 50px;
+ will-change: transform;
+ }
+ </style>
+ <div id='container'>
+ <div id='spacer'></div>
+ <div id='target'></div>
+ </div>
+ )HTML");
- Document* document = MainFrame()->GetDocument();
- Element* container = document->getElementById("container");
- Element* target = document->getElementById("target");
- SetAndSelectRootScroller(*document, container);
+ Element* container = GetDocument().getElementById("container");
+ Element* target = GetDocument().getElementById("target");
+ GetDocument().setRootScroller(container, ASSERT_NO_EXCEPTION);
+
+ Compositor().BeginFrame();
// Ensure the target and container weren't put into the same layer.
ASSERT_NE(ToLayoutBox(target->GetLayoutObject())->EnclosingLayer(),
ToLayoutBox(container->GetLayoutObject())->Layer());
- CheckHitTestAtBottomOfScreen();
+ CheckHitTestAtBottomOfScreen(target);
+}
+
+// Test that hit testing in the area revealed at the bottom of the screen
+// revealed by hiding the URL bar works properly when using a root scroller
+// inside an iframe, when the target and scroller are in different PaintLayers.
+TEST_F(RootScrollerHitTest, HitTestHideURLBarDifferentLayerIframe) {
+ WebView().ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
+ GetBrowserControls().SetShownRatio(1);
+ SimRequest main_request("https://example.com/test.html", "text/html");
+ SimRequest child_request("https://example.com/child.html", "text/html");
+
+ LoadURL("https://example.com/test.html");
+ main_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ </style>
+ <iframe id="container" src="child.html">
+ </iframe>
+ )HTML");
+
+ // Add a target at the bottom of the root scroller that's the size of the url
+ // bar. We'll test that hiding the URL bar appropriately adjusts clipping so
+ // that we can hit this target.
+ child_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ height: 100%;
+ margin: 0px;
+ }
+ #spacer {
+ height: 1000px;
+ }
+ #container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ }
+ #target {
+ width: 100%;
+ height: 50px;
+ will-change: transform;
+ }
+ </style>
+ <div id='container'>
+ <div id='spacer'></div>
+ <div id='target'></div>
+ </div>
+ )HTML");
+
+ Element* container = GetDocument().getElementById("container");
+ GetDocument().setRootScroller(container, ASSERT_NO_EXCEPTION);
+
+ Document* child_document =
+ ToHTMLFrameOwnerElement(container)->contentDocument();
+ Element* child_container = child_document->getElementById("container");
+ child_document->setRootScroller(child_container, ASSERT_NO_EXCEPTION);
+
+ Compositor().BeginFrame();
+
+ // Ensure the target and container weren't put into the same layer.
+ Element* target = child_document->getElementById("target");
+ ASSERT_NE(ToLayoutBox(target->GetLayoutObject())->EnclosingLayer(),
+ ToLayoutBox(child_container->GetLayoutObject())->Layer());
+
+ CheckHitTestAtBottomOfScreen(target);
+}
+
+// Test that hit testing in the area revealed at the bottom of the screen
+// revealed by hiding the URL bar works properly when using a root scroller
+// inside an iframe, when the target and scroller are in the same PaintLayer.
+TEST_F(RootScrollerHitTest, HitTestHideURLBarSameLayerIframe) {
+ WebView().ResizeWithBrowserControls(IntSize(400, 400), 50, 0, true);
+ GetBrowserControls().SetShownRatio(1);
+ SimRequest main_request("https://example.com/test.html", "text/html");
+ SimRequest child_request("https://example.com/child.html", "text/html");
+
+ LoadURL("https://example.com/test.html");
+ main_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ ::-webkit-scrollbar {
+ width: 0px;
+ height: 0px;
+ }
+ body, html {
+ width: 100%;
+ height: 100%;
+ margin: 0px;
+ }
+ iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ </style>
+ <iframe id="container" src="child.html">
+ </iframe>
+ )HTML");
+
+ // Add a target at the bottom of the root scroller that's the size of the url
+ // bar. We'll test that hiding the URL bar appropriately adjusts clipping so
+ // that we can hit this target.
+ child_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ height: 100%;
+ margin: 0px;
+ }
+ #spacer {
+ height: 1000px;
+ }
+ #container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ }
+ #target {
+ width: 100%;
+ height: 50px;
+ }
+ </style>
+ <div id='container'>
+ <div id='spacer'></div>
+ <div id='target'></div>
+ </div>
+ )HTML");
+
+ Element* container = GetDocument().getElementById("container");
+ GetDocument().setRootScroller(container, ASSERT_NO_EXCEPTION);
+
+ Document* child_document =
+ ToHTMLFrameOwnerElement(container)->contentDocument();
+ Element* child_container = child_document->getElementById("container");
+ child_document->setRootScroller(child_container, ASSERT_NO_EXCEPTION);
+
+ Compositor().BeginFrame();
+
+ // Ensure the target and container weren't put into the same layer.
+ Element* target = child_document->getElementById("target");
+ ASSERT_EQ(ToLayoutBox(target->GetLayoutObject())->EnclosingLayer(),
+ ToLayoutBox(child_container->GetLayoutObject())->Layer());
+
+ CheckHitTestAtBottomOfScreen(target);
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.cc b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.cc
index 9b77a62aeae..9b464e6daa3 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.cc
@@ -19,84 +19,19 @@
namespace blink {
-namespace RootScrollerUtil {
-
-ScrollableArea* ScrollableAreaForRootScroller(const Node* node) {
- if (!node)
- return nullptr;
-
- if (node->IsDocumentNode() || node == node->GetDocument().documentElement()) {
- if (!node->GetDocument().View())
- return nullptr;
-
- // For a FrameView, we use the layoutViewport rather than the
- // getScrollableArea() since that could be the RootFrameViewport. The
- // rootScroller's ScrollableArea will be swapped in as the layout viewport
- // in RootFrameViewport so we need to ensure we get the layout viewport.
- return node->GetDocument().View()->LayoutViewport();
- }
-
- DCHECK(node->IsElementNode());
- const Element* element = ToElement(node);
-
- if (!element->GetLayoutObject() || !element->GetLayoutObject()->IsBox())
- return nullptr;
-
- return ToLayoutBoxModelObject(element->GetLayoutObject())
- ->GetScrollableArea();
-}
+namespace root_scroller_util {
PaintLayer* PaintLayerForRootScroller(const Node* node) {
if (!node)
return nullptr;
- if (node->IsDocumentNode() || node == node->GetDocument().documentElement()) {
- if (!node->GetDocument().GetLayoutView())
- return nullptr;
-
- return node->GetDocument().GetLayoutView()->Layer();
- }
-
- DCHECK(node->IsElementNode());
- const Element* element = ToElement(node);
- if (!element->GetLayoutObject() || !element->GetLayoutObject()->IsBox())
+ if (!node->GetLayoutObject() || !node->GetLayoutObject()->IsBox())
return nullptr;
- LayoutBox* box = ToLayoutBox(element->GetLayoutObject());
+ LayoutBox* box = ToLayoutBox(node->GetLayoutObject());
return box->Layer();
}
-bool IsGlobal(const LayoutBox& box) {
- if (!box.GetNode() || !box.GetNode()->GetDocument().GetPage())
- return false;
-
- return box.GetNode() == box.GetDocument()
- .GetPage()
- ->GlobalRootScrollerController()
- .GlobalRootScroller();
-}
-
-bool IsGlobal(const PaintLayer& layer) {
- if (!layer.GetLayoutBox())
- return false;
-
- PaintLayer* root_scroller_layer =
- PaintLayerForRootScroller(layer.GetLayoutBox()
- ->GetDocument()
- .GetPage()
- ->GlobalRootScrollerController()
- .GlobalRootScroller());
-
- return &layer == root_scroller_layer;
-}
-
-bool IsGlobal(const Element* element) {
- return element->GetDocument()
- .GetPage()
- ->GlobalRootScrollerController()
- .GlobalRootScroller() == element;
-}
-
-} // namespace RootScrollerUtil
+} // namespace root_scroller_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.h b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.h
index e614ed73f93..9c444455687 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_util.h
@@ -7,29 +7,17 @@
namespace blink {
-class Element;
-class LayoutBox;
class Node;
class PaintLayer;
-class ScrollableArea;
-namespace RootScrollerUtil {
-
-// Returns the ScrollableArea that's associated with the root scroller Node.
-// For the <html> element and document Node this will be the FrameView or root
-// PaintLayerScrollableArea.
-ScrollableArea* ScrollableAreaForRootScroller(const Node*);
+namespace root_scroller_util {
// Returns the PaintLayer that'll be used as the root scrolling layer. For the
// <html> element and document Node, this returns the LayoutView's PaintLayer
// rather than <html>'s since scrolling is handled by LayoutView.
PaintLayer* PaintLayerForRootScroller(const Node*);
-bool IsGlobal(const LayoutBox&);
-bool IsGlobal(const PaintLayer&);
-bool IsGlobal(const Element*);
-
-} // namespace RootScrollerUtil
+} // namespace root_scroller_util
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.cc
index e47d0740308..c3101a92b5e 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.cc
@@ -4,51 +4,49 @@
#include "third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h"
+#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h"
namespace blink {
void ScrollCustomizationCallbacks::SetDistributeScroll(
- Element* element,
+ Node* node,
ScrollStateCallback* scroll_state_callback) {
- distribute_scroll_callbacks_.Set(element, scroll_state_callback);
+ distribute_scroll_callbacks_.Set(node, scroll_state_callback);
}
ScrollStateCallback* ScrollCustomizationCallbacks::GetDistributeScroll(
- Element* element) {
- auto it = distribute_scroll_callbacks_.find(element);
+ Node* node) {
+ auto it = distribute_scroll_callbacks_.find(node);
if (it == distribute_scroll_callbacks_.end())
return nullptr;
return it->value.Get();
}
void ScrollCustomizationCallbacks::SetApplyScroll(
- Element* element,
+ Node* node,
ScrollStateCallback* scroll_state_callback) {
- apply_scroll_callbacks_.Set(element, scroll_state_callback);
+ apply_scroll_callbacks_.Set(node, scroll_state_callback);
}
-void ScrollCustomizationCallbacks::RemoveApplyScroll(Element* element) {
- apply_scroll_callbacks_.erase(element);
+void ScrollCustomizationCallbacks::RemoveApplyScroll(Node* node) {
+ apply_scroll_callbacks_.erase(node);
}
-ScrollStateCallback* ScrollCustomizationCallbacks::GetApplyScroll(
- Element* element) {
- auto it = apply_scroll_callbacks_.find(element);
+ScrollStateCallback* ScrollCustomizationCallbacks::GetApplyScroll(Node* node) {
+ auto it = apply_scroll_callbacks_.find(node);
if (it == apply_scroll_callbacks_.end())
return nullptr;
return it->value.Get();
}
-bool ScrollCustomizationCallbacks::InScrollPhase(Element* element) const {
- return in_scrolling_phase_.Contains(element) &&
- in_scrolling_phase_.at(element);
+bool ScrollCustomizationCallbacks::InScrollPhase(Node* node) const {
+ return in_scrolling_phase_.Contains(node) && in_scrolling_phase_.at(node);
}
-void ScrollCustomizationCallbacks::SetInScrollPhase(Element* element,
- bool value) {
- DCHECK(element);
- in_scrolling_phase_.Set(element, value);
+void ScrollCustomizationCallbacks::SetInScrollPhase(Node* node, bool value) {
+ DCHECK(node);
+ in_scrolling_phase_.Set(node, value);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h
index 73c90ae9b41..f5ce11a250a 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h
@@ -7,25 +7,25 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
+class Node;
class ScrollStateCallback;
class CORE_EXPORT ScrollCustomizationCallbacks
: public GarbageCollected<ScrollCustomizationCallbacks> {
public:
ScrollCustomizationCallbacks() = default;
- void SetDistributeScroll(Element*, ScrollStateCallback*);
- ScrollStateCallback* GetDistributeScroll(Element*);
- void SetApplyScroll(Element*, ScrollStateCallback*);
- void RemoveApplyScroll(Element*);
- ScrollStateCallback* GetApplyScroll(Element*);
- bool InScrollPhase(Element*) const;
- void SetInScrollPhase(Element*, bool);
+ void SetDistributeScroll(Node*, ScrollStateCallback*);
+ ScrollStateCallback* GetDistributeScroll(Node*);
+ void SetApplyScroll(Node*, ScrollStateCallback*);
+ void RemoveApplyScroll(Node*);
+ ScrollStateCallback* GetApplyScroll(Node*);
+ bool InScrollPhase(Node*) const;
+ void SetInScrollPhase(Node*, bool);
void Trace(blink::Visitor* visitor) {
visitor->Trace(apply_scroll_callbacks_);
@@ -35,10 +35,10 @@ class CORE_EXPORT ScrollCustomizationCallbacks
private:
using ScrollStateCallbackList =
- HeapHashMap<WeakMember<Element>, Member<ScrollStateCallback>>;
+ HeapHashMap<WeakMember<Node>, Member<ScrollStateCallback>>;
ScrollStateCallbackList apply_scroll_callbacks_;
ScrollStateCallbackList distribute_scroll_callbacks_;
- HeapHashMap<WeakMember<Element>, bool> in_scrolling_phase_;
+ HeapHashMap<WeakMember<Node>, bool> in_scrolling_phase_;
DISALLOW_COPY_AND_ASSIGN(ScrollCustomizationCallbacks);
};
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc
index 51e08d0d92c..c866ff5d488 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc
@@ -36,8 +36,8 @@ TEST_F(ScrollIntoViewTest, InstantScroll) {
ASSERT_EQ(Window().scrollY(), 0);
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
arg.SetScrollIntoViewOptions(options);
content->scrollIntoView(arg);
@@ -153,9 +153,9 @@ TEST_F(ScrollIntoViewTest, SmoothScroll) {
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
- options.setBehavior("smooth");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
+ options->setBehavior("smooth");
arg.SetScrollIntoViewOptions(options);
Compositor().BeginFrame();
ASSERT_EQ(Window().scrollY(), 0);
@@ -188,9 +188,9 @@ TEST_F(ScrollIntoViewTest, NestedContainer) {
Element* container = GetDocument().getElementById("container");
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
- options.setBehavior("smooth");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
+ options->setBehavior("smooth");
arg.SetScrollIntoViewOptions(options);
Compositor().BeginFrame();
ASSERT_EQ(Window().scrollY(), 0);
@@ -241,9 +241,9 @@ TEST_F(ScrollIntoViewTest, NewScrollIntoViewAbortsCurrentAnimation) {
Element* content1 = GetDocument().getElementById("content1");
Element* content2 = GetDocument().getElementById("content2");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
- options.setBehavior("smooth");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
+ options->setBehavior("smooth");
arg.SetScrollIntoViewOptions(options);
Compositor().BeginFrame();
@@ -301,9 +301,9 @@ TEST_F(ScrollIntoViewTest, ScrollWindowAbortsCurrentAnimation) {
Element* container = GetDocument().getElementById("container");
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
- options.setBehavior("smooth");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
+ options->setBehavior("smooth");
arg.SetScrollIntoViewOptions(options);
Compositor().BeginFrame();
ASSERT_EQ(Window().scrollY(), 0);
@@ -317,10 +317,10 @@ TEST_F(ScrollIntoViewTest, ScrollWindowAbortsCurrentAnimation) {
ASSERT_EQ(Window().scrollY(), 299);
ASSERT_EQ(container->scrollTop(), 0);
- ScrollToOptions window_option;
- window_option.setLeft(0);
- window_option.setTop(0);
- window_option.setBehavior("smooth");
+ ScrollToOptions* window_option = ScrollToOptions::Create();
+ window_option->setLeft(0);
+ window_option->setTop(0);
+ window_option->setBehavior("smooth");
Window().scrollTo(window_option);
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
@@ -351,11 +351,11 @@ TEST_F(ScrollIntoViewTest, BlockAndInlineSettings) {
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg1, arg2, arg3, arg4;
- ScrollIntoViewOptions options;
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
ASSERT_EQ(Window().scrollY(), 0);
- options.setBlock("nearest");
- options.setInlinePosition("nearest");
+ options->setBlock("nearest");
+ options->setInlinePosition("nearest");
arg1.SetScrollIntoViewOptions(options);
content->scrollIntoView(arg1);
ASSERT_EQ(Window().scrollX(),
@@ -363,15 +363,15 @@ TEST_F(ScrollIntoViewTest, BlockAndInlineSettings) {
ASSERT_EQ(Window().scrollY(),
content->OffsetTop() + content_height - window_height);
- options.setBlock("start");
- options.setInlinePosition("start");
+ options->setBlock("start");
+ options->setInlinePosition("start");
arg2.SetScrollIntoViewOptions(options);
content->scrollIntoView(arg2);
ASSERT_EQ(Window().scrollX(), content->OffsetLeft());
ASSERT_EQ(Window().scrollY(), content->OffsetTop());
- options.setBlock("center");
- options.setInlinePosition("center");
+ options->setBlock("center");
+ options->setInlinePosition("center");
arg3.SetScrollIntoViewOptions(options);
content->scrollIntoView(arg3);
ASSERT_EQ(Window().scrollX(),
@@ -379,8 +379,8 @@ TEST_F(ScrollIntoViewTest, BlockAndInlineSettings) {
ASSERT_EQ(Window().scrollY(),
content->OffsetTop() + (content_height - window_height) / 2);
- options.setBlock("end");
- options.setInlinePosition("end");
+ options->setBlock("end");
+ options->setInlinePosition("end");
arg4.SetScrollIntoViewOptions(options);
content->scrollIntoView(arg4);
ASSERT_EQ(Window().scrollX(),
@@ -410,8 +410,8 @@ TEST_F(ScrollIntoViewTest, SmoothAndInstantInChain) {
Element* inner_container = GetDocument().getElementById("inner_container");
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
arg.SetScrollIntoViewOptions(options);
Compositor().BeginFrame();
ASSERT_EQ(Window().scrollY(), 0);
@@ -508,8 +508,8 @@ TEST_F(ScrollIntoViewTest, ApplyRootElementScrollBehaviorToViewport) {
Element* content = GetDocument().getElementById("content");
ScrollIntoViewOptionsOrBoolean arg;
- ScrollIntoViewOptions options;
- options.setBlock("start");
+ ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
+ options->setBlock("start");
arg.SetScrollIntoViewOptions(options);
Compositor().BeginFrame();
ASSERT_EQ(Window().scrollY(), 0);
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_metrics_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_metrics_test.cc
index d494dc29d89..0285f324cc2 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_metrics_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_metrics_test.cc
@@ -41,6 +41,10 @@ class ScrollMetricsTest : public SimTest {
public:
void SetUpHtml(const char*);
void Scroll(Element*, const WebGestureDevice);
+ void UpdateAllLifecyclePhases() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
};
class NonCompositedMainThreadScrollingReasonRecordTest
@@ -134,7 +138,7 @@ TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("box");
HistogramTester histogram_tester;
@@ -172,7 +176,7 @@ TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("box");
HistogramTester histogram_tester;
@@ -183,7 +187,7 @@ TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
EXPECT_WHEEL_TOTAL(2);
box->setAttribute("class", "composited translucent box");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_FALSE(ToLayoutBox(box->GetLayoutObject())
->GetScrollableArea()
@@ -206,7 +210,7 @@ TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("box");
HistogramTester histogram_tester;
@@ -217,7 +221,7 @@ TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
EXPECT_WHEEL_TOTAL(2);
box->setAttribute("class", "hidden translucent box");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
@@ -247,7 +251,7 @@ TEST_F(NonCompositedMainThreadScrollingReasonRecordTest, NestedScrollersTest) {
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("inner");
HistogramTester histogram_tester;
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.cc
index 593cc999311..24c03a97ca7 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.cc
@@ -13,41 +13,38 @@
namespace blink {
namespace {
-Element* ElementForId(DOMNodeId element_id) {
- Node* node = DOMNodeIds::NodeForId(element_id);
+Node* NodeForId(DOMNodeId node_id) {
+ Node* node = DOMNodeIds::NodeForId(node_id);
DCHECK(node);
- if (!node)
- return nullptr;
- DCHECK(node->IsElementNode());
- if (!node->IsElementNode())
- return nullptr;
- return static_cast<Element*>(node);
+ return node;
}
} // namespace
-ScrollState* ScrollState::Create(ScrollStateInit init) {
+ScrollState* ScrollState::Create(ScrollStateInit* init) {
std::unique_ptr<ScrollStateData> scroll_state_data =
std::make_unique<ScrollStateData>();
- scroll_state_data->delta_x = init.deltaX();
- scroll_state_data->delta_y = init.deltaY();
- scroll_state_data->delta_x_hint = init.deltaXHint();
- scroll_state_data->delta_y_hint = init.deltaYHint();
- scroll_state_data->position_x = init.positionX();
- scroll_state_data->position_y = init.positionY();
- scroll_state_data->velocity_x = init.velocityX();
- scroll_state_data->velocity_y = init.velocityY();
- scroll_state_data->is_beginning = init.isBeginning();
- scroll_state_data->is_in_inertial_phase = init.isInInertialPhase();
- scroll_state_data->is_ending = init.isEnding();
- scroll_state_data->from_user_input = init.fromUserInput();
- scroll_state_data->is_direct_manipulation = init.isDirectManipulation();
- scroll_state_data->delta_granularity = init.deltaGranularity();
- ScrollState* scroll_state = new ScrollState(std::move(scroll_state_data));
+ scroll_state_data->delta_x = init->deltaX();
+ scroll_state_data->delta_y = init->deltaY();
+ scroll_state_data->delta_x_hint = init->deltaXHint();
+ scroll_state_data->delta_y_hint = init->deltaYHint();
+ scroll_state_data->position_x = init->positionX();
+ scroll_state_data->position_y = init->positionY();
+ scroll_state_data->velocity_x = init->velocityX();
+ scroll_state_data->velocity_y = init->velocityY();
+ scroll_state_data->is_beginning = init->isBeginning();
+ scroll_state_data->is_in_inertial_phase = init->isInInertialPhase();
+ scroll_state_data->is_ending = init->isEnding();
+ scroll_state_data->from_user_input = init->fromUserInput();
+ scroll_state_data->is_direct_manipulation = init->isDirectManipulation();
+ scroll_state_data->delta_granularity = init->deltaGranularity();
+ ScrollState* scroll_state =
+ MakeGarbageCollected<ScrollState>(std::move(scroll_state_data));
return scroll_state;
}
ScrollState* ScrollState::Create(std::unique_ptr<ScrollStateData> data) {
- ScrollState* scroll_state = new ScrollState(std::move(data));
+ ScrollState* scroll_state =
+ MakeGarbageCollected<ScrollState>(std::move(data));
return scroll_state;
}
@@ -77,7 +74,7 @@ void ScrollState::distributeToScrollChainDescendant() {
if (!scroll_chain_.empty()) {
DOMNodeId descendant_id = scroll_chain_.front();
scroll_chain_.pop_front();
- ElementForId(descendant_id)->CallDistributeScroll(*this);
+ NodeForId(descendant_id)->CallDistributeScroll(*this);
}
}
@@ -93,18 +90,18 @@ void ScrollState::ConsumeDeltaNative(double x, double y) {
data_->delta_consumed_for_scroll_sequence = true;
}
-Element* ScrollState::CurrentNativeScrollingElement() {
+Node* ScrollState::CurrentNativeScrollingNode() {
if (data_->current_native_scrolling_element() == CompositorElementId()) {
- element_.Clear();
+ node_.Clear();
return nullptr;
}
- return element_;
+ return node_;
}
-void ScrollState::SetCurrentNativeScrollingElement(Element* element) {
- element_ = element;
+void ScrollState::SetCurrentNativeScrollingNode(Node* node) {
+ node_ = node;
data_->set_current_native_scrolling_element(
- CompositorElementIdFromDOMNodeId(DOMNodeIds::IdForNode(element)));
+ CompositorElementIdFromDOMNodeId(DOMNodeIds::IdForNode(node)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.h b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.h
index d677b04ee16..4f67b8aba91 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.h
@@ -9,7 +9,7 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
-#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/page/scrolling/scroll_state_init.h"
#include "third_party/blink/renderer/core/scroll/scroll_state_data.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -18,15 +18,14 @@
namespace blink {
-class Element;
-
class CORE_EXPORT ScrollState final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static ScrollState* Create(ScrollStateInit);
+ static ScrollState* Create(ScrollStateInit*);
static ScrollState* Create(std::unique_ptr<ScrollStateData>);
+ explicit ScrollState(std::unique_ptr<ScrollStateData>);
~ScrollState() override = default;
// Web exposed methods.
@@ -73,8 +72,8 @@ class CORE_EXPORT ScrollState final : public ScriptWrappable {
scroll_chain_ = scroll_chain;
}
- Element* CurrentNativeScrollingElement();
- void SetCurrentNativeScrollingElement(Element*);
+ Node* CurrentNativeScrollingNode();
+ void SetCurrentNativeScrollingNode(Node*);
bool DeltaConsumedForScrollSequence() const {
return data_->delta_consumed_for_scroll_sequence;
@@ -90,17 +89,16 @@ class CORE_EXPORT ScrollState final : public ScriptWrappable {
ScrollStateData* Data() const { return data_.get(); }
void Trace(blink::Visitor* visitor) override {
- visitor->Trace(element_);
+ visitor->Trace(node_);
ScriptWrappable::Trace(visitor);
}
private:
ScrollState() = delete;
- explicit ScrollState(std::unique_ptr<ScrollStateData>);
std::unique_ptr<ScrollStateData> data_;
std::deque<DOMNodeId> scroll_chain_;
- Member<Element> element_;
+ Member<Node> node_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h
index 0403a0d5275..daca9a264e5 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h
@@ -42,10 +42,15 @@ class ScrollStateCallbackV8Impl : public ScrollStateCallback {
V8ScrollStateCallback* callback,
const String& native_scroll_behavior) {
DCHECK(callback);
- return new ScrollStateCallbackV8Impl(
+ return MakeGarbageCollected<ScrollStateCallbackV8Impl>(
callback, ParseNativeScrollBehavior(native_scroll_behavior));
}
+ explicit ScrollStateCallbackV8Impl(
+ V8ScrollStateCallback* callback,
+ WebNativeScrollBehavior native_scroll_behavior)
+ : ScrollStateCallback(native_scroll_behavior),
+ callback_(ToV8PersistentCallbackFunction(callback)) {}
~ScrollStateCallbackV8Impl() override = default;
void Trace(blink::Visitor*) override;
@@ -56,12 +61,6 @@ class ScrollStateCallbackV8Impl : public ScrollStateCallback {
static WebNativeScrollBehavior ParseNativeScrollBehavior(
const String& native_scroll_behavior);
- explicit ScrollStateCallbackV8Impl(
- V8ScrollStateCallback* callback,
- WebNativeScrollBehavior native_scroll_behavior)
- : ScrollStateCallback(native_scroll_behavior),
- callback_(ToV8PersistentCallbackFunction(callback)) {}
-
Member<V8PersistentCallbackFunction<V8ScrollStateCallback>> callback_;
};
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_test.cc
index a829fa54005..1132a162fcd 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_test.cc
@@ -69,9 +69,9 @@ TEST_F(ScrollStateTest, CurrentNativeScrollingElement) {
ScrollState* scroll_state = CreateScrollState(0, 0, false, false);
Element* element =
Element::Create(QualifiedName::Null(), Document::CreateForTest());
- scroll_state->SetCurrentNativeScrollingElement(element);
+ scroll_state->SetCurrentNativeScrollingNode(element);
- EXPECT_EQ(element, scroll_state->CurrentNativeScrollingElement());
+ EXPECT_EQ(element, scroll_state->CurrentNativeScrollingNode());
}
TEST_F(ScrollStateTest, FullyConsumed) {
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc
index a8d929e09f8..e03839dd7c2 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc
@@ -41,6 +41,7 @@
#include "third_party/blink/renderer/core/frame/event_handler_registry.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/page_scale_constraints_set.h"
#include "third_party/blink/renderer/core/frame/settings.h"
@@ -59,6 +60,7 @@
#include "third_party/blink/renderer/platform/animation/compositor_animation_host.h"
#include "third_party/blink/renderer/platform/animation/compositor_animation_timeline.h"
#include "third_party/blink/renderer/platform/geometry/region.h"
+#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
@@ -90,7 +92,7 @@ cc::Layer* GraphicsLayerToCcLayer(blink::GraphicsLayer* layer) {
namespace blink {
ScrollingCoordinator* ScrollingCoordinator::Create(Page* page) {
- return new ScrollingCoordinator(page);
+ return MakeGarbageCollected<ScrollingCoordinator>(page);
}
ScrollingCoordinator::ScrollingCoordinator(Page* page) : page_(page) {}
@@ -190,7 +192,8 @@ void ScrollingCoordinator::UpdateAfterPaint(LocalFrameView* frame_view) {
return;
}
- SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.ScrollingCoordinator.UpdateTime");
+ SCOPED_UMA_AND_UKM_TIMER(frame_view->EnsureUkmAggregator(),
+ LocalFrameUkmAggregator::kScrollingCoordinator);
TRACE_EVENT0("input", "ScrollingCoordinator::UpdateAfterPaint");
// TODO(pdr): Move the scroll gesture region logic to use touch action rects.
@@ -254,44 +257,21 @@ static void ForAllGraphicsLayers(GraphicsLayer& layer,
// on the GraphicsLayer's paint chunks.
static void UpdateLayerTouchActionRects(GraphicsLayer& layer) {
DCHECK(RuntimeEnabledFeatures::PaintTouchActionRectsEnabled());
-
- // TODO(pdr): This will need to be moved to PaintArtifactCompositor (or later)
- // for SPV2 because composited layers are not known until then. The SPV2
- // implementation will iterate over the paint chunks in each composited layer
- // and will look almost the same as this function.
- DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
-
if (!layer.DrawsContent())
return;
- const auto& layer_state = layer.GetPropertyTreeState();
- Vector<HitTestRect> touch_action_rects_in_layer_space;
if (layer.Client().ShouldThrottleRendering()) {
- layer.CcLayer()->SetTouchActionRegion(
- HitTestRect::BuildRegion(touch_action_rects_in_layer_space));
+ layer.CcLayer()->SetTouchActionRegion(cc::TouchActionRegion());
return;
}
- for (const auto& chunk : layer.GetPaintController().PaintChunks()) {
- const auto* hit_test_data = chunk.GetHitTestData();
- if (!hit_test_data || hit_test_data->touch_action_rects.IsEmpty())
- continue;
- const auto& chunk_state = chunk.properties.GetPropertyTreeState();
- for (auto touch_action_rect : hit_test_data->touch_action_rects) {
- auto rect =
- FloatClipRect(FloatRect(PixelSnappedIntRect(touch_action_rect.rect)));
- if (!GeometryMapper::LocalToAncestorVisualRect(chunk_state, layer_state,
- rect)) {
- continue;
- }
- LayoutRect layout_rect = LayoutRect(rect.Rect());
- layout_rect.MoveBy(-layer.GetOffsetFromTransformNode());
- touch_action_rects_in_layer_space.emplace_back(
- HitTestRect(layout_rect, touch_action_rect.whitelisted_touch_action));
- }
- }
- layer.CcLayer()->SetTouchActionRegion(
- HitTestRect::BuildRegion(touch_action_rects_in_layer_space));
+ auto offset = layer.GetOffsetFromTransformNode();
+ gfx::Vector2dF layer_offset = gfx::Vector2dF(offset.X(), offset.Y());
+ PaintChunkSubset paint_chunks =
+ PaintChunkSubset(layer.GetPaintController().PaintChunks());
+ PaintArtifactCompositor::UpdateTouchActionRects(layer.CcLayer(), layer_offset,
+ layer.GetPropertyTreeState(),
+ paint_chunks);
}
static void ClearPositionConstraintExceptForLayer(GraphicsLayer* layer,
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h
index daf24d91036..a55c284d0fb 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h
@@ -82,6 +82,7 @@ class CORE_EXPORT ScrollingCoordinator final
static ScrollingCoordinator* Create(Page*);
+ explicit ScrollingCoordinator(Page*);
~ScrollingCoordinator();
void Trace(blink::Visitor*);
@@ -173,8 +174,6 @@ class CORE_EXPORT ScrollingCoordinator final
void Reset(LocalFrame*);
protected:
- explicit ScrollingCoordinator(Page*);
-
bool IsForRootLayer(ScrollableArea*) const;
bool IsForMainFrame(ScrollableArea*) const;
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
index 061120551b8..7e7b3bbdcf2 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
@@ -54,7 +54,10 @@
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/platform/geometry/int_point.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
+#include "third_party/blink/renderer/platform/graphics/test/fake_gles2_interface.h"
+#include "third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
@@ -74,7 +77,8 @@ class ScrollingCoordinatorTest : public testing::Test,
// macOS attaches main frame scrollbars to the VisualViewport so the
// VisualViewport layers need to be initialized.
- GetWebView()->UpdateAllLifecyclePhases();
+ GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
WebFrameWidgetBase* main_frame_widget =
GetWebView()->MainFrameImpl()->FrameWidgetImpl();
main_frame_widget->SetRootGraphicsLayer(GetWebView()
@@ -93,20 +97,21 @@ class ScrollingCoordinatorTest : public testing::Test,
}
void NavigateTo(const std::string& url) {
- FrameTestHelpers::LoadFrame(GetWebView()->MainFrameImpl(), url);
+ frame_test_helpers::LoadFrame(GetWebView()->MainFrameImpl(), url);
}
void LoadHTML(const std::string& html) {
- FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(), html,
- URLTestHelpers::ToKURL("about:blank"));
+ frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(), html,
+ url_test_helpers::ToKURL("about:blank"));
}
void ForceFullCompositingUpdate() {
- GetWebView()->UpdateAllLifecyclePhases();
+ GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -134,7 +139,7 @@ class ScrollingCoordinatorTest : public testing::Test,
settings->SetPreferCompositingToLCDTextEnabled(true);
}
- FrameTestHelpers::WebViewHelper helper_;
+ frame_test_helpers::WebViewHelper helper_;
};
INSTANTIATE_TEST_CASE_P(All, ScrollingCoordinatorTest, ::testing::Bool());
@@ -343,6 +348,23 @@ TEST_P(ScrollingCoordinatorTest, fastScrollingForFixedPosition) {
}
}
+// BlinkGenPropertyTrees (BGPT) changes where the sticky constraints are stored.
+// Without BGPT, sticky constraints are stored on cc::Layer (via
+// GraphicsLayer::SetStickyPositionConstraint). With BGPT, sticky constraints
+// are stored on transform property tree nodes.
+static cc::LayerStickyPositionConstraint GetStickyConstraint(Element* element) {
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
+ cc::Layer* layer = CcLayerFromElement(element);
+ DCHECK(layer);
+ return layer->sticky_position_constraint();
+ }
+
+ const auto* properties =
+ element->GetLayoutObject()->FirstFragment().PaintProperties();
+ DCHECK(properties);
+ return *properties->StickyTranslation()->GetStickyConstraint();
+}
+
TEST_P(ScrollingCoordinatorTest, fastScrollingForStickyPosition) {
RegisterMockedHttpURLLoad("sticky-position.html");
NavigateTo(base_url_ + "sticky-position.html");
@@ -356,11 +378,7 @@ TEST_P(ScrollingCoordinatorTest, fastScrollingForStickyPosition) {
Document* document = GetFrame()->GetDocument();
{
Element* element = document->getElementById("div-tl");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(constraint.is_anchored_top && constraint.is_anchored_left &&
!constraint.is_anchored_right &&
@@ -374,44 +392,28 @@ TEST_P(ScrollingCoordinatorTest, fastScrollingForStickyPosition) {
}
{
Element* element = document->getElementById("div-tr");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(constraint.is_anchored_top && !constraint.is_anchored_left &&
constraint.is_anchored_right && !constraint.is_anchored_bottom);
}
{
Element* element = document->getElementById("div-bl");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(!constraint.is_anchored_top && constraint.is_anchored_left &&
!constraint.is_anchored_right && constraint.is_anchored_bottom);
}
{
Element* element = document->getElementById("div-br");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(!constraint.is_anchored_top && !constraint.is_anchored_left &&
constraint.is_anchored_right && constraint.is_anchored_bottom);
}
{
Element* element = document->getElementById("span-tl");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(constraint.is_anchored_top && constraint.is_anchored_left &&
!constraint.is_anchored_right &&
@@ -419,11 +421,7 @@ TEST_P(ScrollingCoordinatorTest, fastScrollingForStickyPosition) {
}
{
Element* element = document->getElementById("span-tlbr");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(constraint.is_anchored_top && constraint.is_anchored_left &&
constraint.is_anchored_right && constraint.is_anchored_bottom);
@@ -434,11 +432,7 @@ TEST_P(ScrollingCoordinatorTest, fastScrollingForStickyPosition) {
}
{
Element* element = document->getElementById("composited-top");
- ASSERT_TRUE(element);
- cc::Layer* layer = CcLayerFromElement(element);
- ASSERT_TRUE(layer);
- cc::LayerStickyPositionConstraint constraint =
- layer->sticky_position_constraint();
+ auto constraint = GetStickyConstraint(element);
ASSERT_TRUE(constraint.is_sticky);
EXPECT_TRUE(constraint.is_anchored_top);
EXPECT_EQ(gfx::Rect(100, 110, 10, 10),
@@ -528,6 +522,20 @@ TEST_P(ScrollingCoordinatorTest, elementTouchEventHandlerPassive) {
EXPECT_TRUE(region.IsEmpty());
}
+TEST_P(ScrollingCoordinatorTest, TouchActionRectsOnImage) {
+ LoadHTML(R"HTML(
+ <img id="image" style="width: 100px; height: 100px; touch-action: none;">
+ )HTML");
+ ForceFullCompositingUpdate();
+
+ auto* layout_view = GetFrame()->View()->GetLayoutView();
+ auto* mapping = layout_view->Layer()->GetCompositedLayerMapping();
+ cc::Layer* cc_layer = mapping->ScrollingContentsLayer()->CcLayer();
+ cc::Region region = cc_layer->touch_action_region().GetRegionForTouchAction(
+ TouchAction::kTouchActionNone);
+ EXPECT_EQ(region.bounds(), gfx::Rect(8, 8, 100, 100));
+}
+
TEST_P(ScrollingCoordinatorTest, touchEventHandlerBoth) {
RegisterMockedHttpURLLoad("touch-event-handler-both.html");
NavigateTo(base_url_ + "touch-event-handler-both.html");
@@ -961,7 +969,7 @@ TEST_P(ScrollingCoordinatorTest, IframeWindowTouchHandler) {
R"(<iframe style="width: 275px; height: 250px;"></iframe>)");
WebLocalFrameImpl* child_frame =
ToWebLocalFrameImpl(GetWebView()->MainFrameImpl()->FirstChild());
- FrameTestHelpers::LoadHTMLString(child_frame, R"HTML(
+ frame_test_helpers::LoadHTMLString(child_frame, R"HTML(
<p style="margin: 1000px"> Hello </p>
<script>
window.addEventListener('touchstart', (e) => {
@@ -969,7 +977,7 @@ TEST_P(ScrollingCoordinatorTest, IframeWindowTouchHandler) {
}, {passive: false});
</script>
)HTML",
- URLTestHelpers::ToKURL("about:blank"));
+ url_test_helpers::ToKURL("about:blank"));
ForceFullCompositingUpdate();
PaintLayer* paint_layer_child_frame =
@@ -1057,7 +1065,7 @@ class ScrollingCoordinatorMockEventListener final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event*) final {}
+ void Invoke(ExecutionContext*, Event*) final {}
};
} // namespace
@@ -1083,10 +1091,10 @@ TEST_P(ScrollingCoordinatorTest, WindowTouchEventHandlerInvalidation) {
// Adding a blocking window event handler should create a touch action region.
auto* listener = new ScrollingCoordinatorMockEventListener();
- AddEventListenerOptions options;
- options.setPassive(false);
- AddEventListenerOptionsResolved resolved_options(options);
- GetFrame()->DomWindow()->addEventListener(EventTypeNames::touchstart,
+ AddEventListenerOptionsResolved* resolved_options =
+ AddEventListenerOptionsResolved::Create();
+ resolved_options->setPassive(false);
+ GetFrame()->DomWindow()->addEventListener(event_type_names::kTouchstart,
listener, resolved_options);
ForceFullCompositingUpdate();
region = cc_layer->touch_action_region().GetRegionForTouchAction(
@@ -1394,7 +1402,8 @@ TEST_P(ScrollingCoordinatorTest, CustomScrollbarShouldTriggerMainThreadScroll) {
Document* document = GetFrame()->GetDocument();
Element* container = document->getElementById("container");
Element* content = document->getElementById("content");
- DCHECK_EQ(container->getAttribute(HTMLNames::classAttr), "custom_scrollbar");
+ DCHECK_EQ(container->getAttribute(html_names::kClassAttr),
+ "custom_scrollbar");
DCHECK(container);
DCHECK(content);
@@ -1580,14 +1589,14 @@ TEST_P(ScrollingCoordinatorTest, FrameIsScrollableDidChange) {
// A change to background color should not change the frame's scrollability.
auto* background = GetFrame()->GetDocument()->getElementById("bg");
- background->removeAttribute(HTMLNames::styleAttr);
+ background->removeAttribute(html_names::kStyleAttr);
EXPECT_FALSE(GetFrame()->View()->FrameIsScrollableDidChange());
ForceFullCompositingUpdate();
// Making the frame not scroll should change the frame's scrollability.
auto* forcescroll = GetFrame()->GetDocument()->getElementById("forcescroll");
- forcescroll->removeAttribute(HTMLNames::styleAttr);
+ forcescroll->removeAttribute(html_names::kStyleAttr);
GetFrame()->View()->UpdateLifecycleToLayoutClean();
EXPECT_TRUE(GetFrame()->View()->FrameIsScrollableDidChange());
@@ -1617,13 +1626,13 @@ TEST_P(ScrollingCoordinatorTest, UpdateUMAMetricUpdated) {
// A change to background color should not cause a scrolling update.
auto* background = GetFrame()->GetDocument()->getElementById("bg");
- background->removeAttribute(HTMLNames::styleAttr);
+ background->removeAttribute(html_names::kStyleAttr);
ForceFullCompositingUpdate();
histogram_tester.ExpectTotalCount("Blink.ScrollingCoordinator.UpdateTime", 1);
// Removing a scrollable area should cause a scrolling update.
auto* scroller = GetFrame()->GetDocument()->getElementById("scroller");
- scroller->removeAttribute(HTMLNames::styleAttr);
+ scroller->removeAttribute(html_names::kStyleAttr);
ForceFullCompositingUpdate();
histogram_tester.ExpectTotalCount("Blink.ScrollingCoordinator.UpdateTime", 2);
}
@@ -1725,7 +1734,7 @@ TEST_P(NonCompositedMainThreadScrollingReasonTest, ClipPathTest) {
// Test ancestor with ClipPath
Element* element = document->body();
ASSERT_TRUE(element);
- element->setAttribute(HTMLNames::styleAttr,
+ element->setAttribute(html_names::kStyleAttr,
"clip-path:circle(115px at 20px 20px);");
Element* container = document->getElementById("scroller1");
ASSERT_TRUE(container);
@@ -1742,7 +1751,7 @@ TEST_P(NonCompositedMainThreadScrollingReasonTest, ClipPathTest) {
EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & clip_reason);
// Remove clip path from ancestor.
- element->removeAttribute(HTMLNames::styleAttr);
+ element->removeAttribute(html_names::kStyleAttr);
ForceFullCompositingUpdate();
EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() &
@@ -1752,7 +1761,7 @@ TEST_P(NonCompositedMainThreadScrollingReasonTest, ClipPathTest) {
// Test descendant with ClipPath
element = document->getElementById("content1");
ASSERT_TRUE(element);
- element->setAttribute(HTMLNames::styleAttr,
+ element->setAttribute(html_names::kStyleAttr,
"clip-path:circle(115px at 20px 20px);");
ForceFullCompositingUpdate();
EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() &
@@ -1760,7 +1769,7 @@ TEST_P(NonCompositedMainThreadScrollingReasonTest, ClipPathTest) {
EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & clip_reason);
// Remove clip path from descendant.
- element->removeAttribute(HTMLNames::styleAttr);
+ element->removeAttribute(html_names::kStyleAttr);
ForceFullCompositingUpdate();
EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() &
clip_reason);
@@ -1837,4 +1846,59 @@ TEST_P(NonCompositedMainThreadScrollingReasonTest,
ASSERT_TRUE(scrollable_area2->UsesCompositedScrolling());
}
+class ScrollingCoordinatorTestWithAcceleratedContext
+ : public ScrollingCoordinatorTest {
+ public:
+ ScrollingCoordinatorTestWithAcceleratedContext()
+ : ScrollingCoordinatorTest() {}
+
+ protected:
+ void SetUp() override {
+ auto factory = [](FakeGLES2Interface* gl, bool* gpu_compositing_disabled)
+ -> std::unique_ptr<WebGraphicsContext3DProvider> {
+ *gpu_compositing_disabled = false;
+ gl->SetIsContextLost(false);
+ return std::make_unique<FakeWebGraphicsContext3DProvider>(gl);
+ };
+ SharedGpuContext::SetContextProviderFactoryForTesting(
+ WTF::BindRepeating(factory, WTF::Unretained(&gl_)));
+ ScrollingCoordinatorTest::SetUp();
+ }
+
+ void TearDown() override {
+ SharedGpuContext::ResetForTesting();
+ ScrollingCoordinatorTest::TearDown();
+ }
+
+ private:
+ FakeGLES2Interface gl_;
+};
+
+INSTANTIATE_TEST_CASE_P(All,
+ ScrollingCoordinatorTestWithAcceleratedContext,
+ ::testing::Bool());
+
+TEST_P(ScrollingCoordinatorTestWithAcceleratedContext, CanvasTouchActionRects) {
+ LoadHTML(R"HTML(
+ <canvas id="canvas" style="touch-action: none; will-change: transform;">
+ <script>
+ var canvas = document.getElementById("canvas");
+ var ctx = canvas.getContext("2d");
+ canvas.width = 400;
+ canvas.height = 400;
+ ctx.fillStyle = 'lightgrey';
+ ctx.fillRect(0, 0, 400, 400);
+ </script>
+ )HTML");
+ ForceFullCompositingUpdate();
+
+ Element* canvas = GetFrame()->GetDocument()->getElementById("canvas");
+ auto* canvas_box = ToLayoutBox(canvas->GetLayoutObject());
+ auto* mapping = canvas_box->Layer()->GetCompositedLayerMapping();
+ cc::Layer* cc_layer = mapping->MainGraphicsLayer()->CcLayer();
+ cc::Region region = cc_layer->touch_action_region().GetRegionForTouchAction(
+ TouchAction::kTouchActionNone);
+ EXPECT_EQ(region.bounds(), gfx::Rect(0, 0, 400, 400));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc b/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc
index 939f7eb4505..0968175f9a3 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc
@@ -11,14 +11,14 @@
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/scroll/scroll_snap_data.h"
namespace blink {
namespace {
// This is experimentally determined and corresponds to the UA decided
// parameter as mentioned in spec.
-constexpr float kProximityRaio = 1.0 / 3.0;
+constexpr float kProximityRatio = 1.0 / 3.0;
} // namespace
// TODO(sunyunjia): Move the static functions to an anonymous namespace.
@@ -27,7 +27,7 @@ SnapCoordinator::SnapCoordinator() : snap_container_map_() {}
SnapCoordinator::~SnapCoordinator() = default;
SnapCoordinator* SnapCoordinator::Create() {
- return new SnapCoordinator();
+ return MakeGarbageCollected<SnapCoordinator>();
}
// Returns the scroll container that can be affected by this snap area.
@@ -157,7 +157,7 @@ void SnapCoordinator::UpdateSnapContainerData(const LayoutBox& snap_container) {
if (snap_container_data.scroll_snap_type().strictness ==
SnapStrictness::kProximity) {
LayoutSize size = container_rect.Size();
- size.Scale(kProximityRaio);
+ size.Scale(kProximityRatio);
gfx::ScrollOffset range(size.Width().ToFloat(), size.Height().ToFloat());
snap_container_data.set_proximity_range(range);
}
@@ -235,11 +235,9 @@ SnapAreaData SnapCoordinator::CalculateSnapAreaData(
return snap_area_data;
}
-base::Optional<FloatPoint> SnapCoordinator::GetSnapPositionForPoint(
+base::Optional<FloatPoint> SnapCoordinator::GetSnapPosition(
const LayoutBox& snap_container,
- const FloatPoint& point,
- bool did_scroll_x,
- bool did_scroll_y) {
+ const SnapSelectionStrategy& strategy) const {
auto iter = snap_container_map_.find(&snap_container);
if (iter == snap_container_map_.end())
return base::nullopt;
@@ -249,34 +247,60 @@ base::Optional<FloatPoint> SnapCoordinator::GetSnapPositionForPoint(
return base::nullopt;
gfx::ScrollOffset snap_position;
- if (data.FindSnapPosition(gfx::ScrollOffset(point.X(), point.Y()),
- did_scroll_x, did_scroll_y, &snap_position)) {
+ if (data.FindSnapPosition(strategy, &snap_position)) {
FloatPoint snap_point(snap_position.x(), snap_position.y());
return snap_point;
}
+
return base::nullopt;
}
-void SnapCoordinator::PerformSnapping(const LayoutBox& snap_container,
- bool did_scroll_x,
- bool did_scroll_y) {
+bool SnapCoordinator::SnapForEndPosition(const LayoutBox& snap_container,
+ bool scrolled_x,
+ bool scrolled_y) const {
ScrollableArea* scrollable_area = ScrollableAreaForSnapping(snap_container);
if (!scrollable_area)
- return;
+ return false;
+ FloatPoint current_position = scrollable_area->ScrollPosition();
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(
+ gfx::ScrollOffset(current_position), scrolled_x, scrolled_y);
+ return PerformSnapping(snap_container, *strategy);
+}
+bool SnapCoordinator::SnapForDirection(const LayoutBox& snap_container,
+ const ScrollOffset& delta) const {
+ ScrollableArea* scrollable_area = ScrollableAreaForSnapping(snap_container);
+ if (!scrollable_area)
+ return false;
FloatPoint current_position = scrollable_area->ScrollPosition();
- base::Optional<FloatPoint> snap_point = GetSnapPositionForPoint(
- snap_container, current_position, did_scroll_x, did_scroll_y);
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForDirection(
+ gfx::ScrollOffset(current_position),
+ gfx::ScrollOffset(delta.Width(), delta.Height()));
+ return PerformSnapping(snap_container, *strategy);
+}
+
+bool SnapCoordinator::PerformSnapping(
+ const LayoutBox& snap_container,
+ const SnapSelectionStrategy& strategy) const {
+ ScrollableArea* scrollable_area = ScrollableAreaForSnapping(snap_container);
+ if (!scrollable_area)
+ return false;
+
+ base::Optional<FloatPoint> snap_point =
+ GetSnapPosition(snap_container, strategy);
if (!snap_point.has_value())
- return;
+ return false;
scrollable_area->CancelScrollAnimation();
scrollable_area->CancelProgrammaticScrollAnimation();
- if (snap_point.value() != current_position) {
+ if (gfx::ScrollOffset(snap_point.value()) != strategy.current_position()) {
scrollable_area->SetScrollOffset(
scrollable_area->ScrollPositionToOffset(snap_point.value()),
kProgrammaticScroll, kScrollBehaviorSmooth);
}
+ return true;
}
void SnapCoordinator::SnapContainerDidChange(LayoutBox& snap_container,
@@ -308,30 +332,6 @@ base::Optional<SnapContainerData> SnapCoordinator::GetSnapContainerData(
return base::nullopt;
}
-bool SnapCoordinator::GetSnapFlingInfo(
- const LayoutBox& snap_container,
- const gfx::Vector2dF& natural_displacement,
- gfx::Vector2dF* out_initial_offset,
- gfx::Vector2dF* out_target_offset) {
- ScrollableArea* scrollable_area = ScrollableAreaForSnapping(snap_container);
- if (!scrollable_area)
- return false;
-
- FloatPoint current_position = scrollable_area->ScrollPosition();
- *out_initial_offset = gfx::Vector2dF(current_position);
- FloatPoint original_end =
- current_position +
- FloatPoint(natural_displacement.x(), natural_displacement.y());
- bool did_scroll_x = natural_displacement.x() != 0;
- bool did_scroll_y = natural_displacement.y() != 0;
- base::Optional<FloatPoint> snap_end = GetSnapPositionForPoint(
- snap_container, original_end, did_scroll_x, did_scroll_y);
- if (!snap_end.has_value())
- return false;
- *out_target_offset = gfx::Vector2dF(snap_end.value());
- return true;
-}
-
#ifndef NDEBUG
void SnapCoordinator::ShowSnapAreaMap() {
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h b/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h
index 2c3ad76aba9..d4e3b0e74f5 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.h
@@ -31,6 +31,8 @@ class CORE_EXPORT SnapCoordinator final
: public GarbageCollectedFinalized<SnapCoordinator> {
public:
static SnapCoordinator* Create();
+
+ explicit SnapCoordinator();
~SnapCoordinator();
void Trace(blink::Visitor* visitor) {}
@@ -51,21 +53,17 @@ class CORE_EXPORT SnapCoordinator final
void UpdateAllSnapContainerData();
void UpdateSnapContainerData(const LayoutBox&);
- // Called by ScrollManager::HandleGestureScrollEnd() to animate to the snap
- // position for the current scroll on the specific direction if there is
- // a valid snap position.
- void PerformSnapping(const LayoutBox& snap_container,
- bool did_scroll_x,
- bool did_scroll_y);
- base::Optional<FloatPoint> GetSnapPositionForPoint(
+ // SnapForEndPosition() and SnapForDirection() return true if snapping was
+ // performed, and false otherwise.
+ bool SnapForEndPosition(const LayoutBox& snap_container,
+ bool scrolled_x,
+ bool scrolled_y) const;
+ bool SnapForDirection(const LayoutBox& snap_container,
+ const ScrollOffset& delta) const;
+
+ base::Optional<FloatPoint> GetSnapPosition(
const LayoutBox& snap_container,
- const FloatPoint& natural_position,
- bool did_scroll_x,
- bool did_scroll_y);
- bool GetSnapFlingInfo(const LayoutBox& snap_container,
- const gfx::Vector2dF& natural_displacement,
- gfx::Vector2dF* out_initial_offset,
- gfx::Vector2dF* out_target_offset);
+ const SnapSelectionStrategy& strategy) const;
#ifndef NDEBUG
void ShowSnapAreaMap();
@@ -75,7 +73,8 @@ class CORE_EXPORT SnapCoordinator final
private:
friend class SnapCoordinatorTest;
- explicit SnapCoordinator();
+ bool PerformSnapping(const LayoutBox& snap_container,
+ const SnapSelectionStrategy& strategy) const;
HashMap<const LayoutBox*, SnapContainerData> snap_container_map_;
DISALLOW_COPY_AND_ASSIGN(SnapCoordinator);
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc
index 254d0794a92..3a0ae5ea341 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc
@@ -19,7 +19,7 @@
namespace blink {
-using HTMLNames::styleAttr;
+using html_names::kStyleAttr;
class SnapCoordinatorTest : public testing::Test {
protected:
@@ -110,7 +110,7 @@ class SnapCoordinatorTest : public testing::Test {
TEST_F(SnapCoordinatorTest, SimpleSnapElement) {
Element& snap_element = *GetDocument().getElementById("snap-element");
- snap_element.setAttribute(styleAttr, "scroll-snap-align: start;");
+ snap_element.setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
EXPECT_EQ(1U, SizeOfSnapAreas(SnapContainer()));
@@ -118,7 +118,7 @@ TEST_F(SnapCoordinatorTest, SimpleSnapElement) {
TEST_F(SnapCoordinatorTest, NestedSnapElement) {
Element& snap_element = *GetDocument().getElementById("nested-snap-element");
- snap_element.setAttribute(styleAttr, "scroll-snap-align: start;");
+ snap_element.setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
EXPECT_EQ(1U, SizeOfSnapAreas(SnapContainer()));
@@ -126,10 +126,10 @@ TEST_F(SnapCoordinatorTest, NestedSnapElement) {
TEST_F(SnapCoordinatorTest, NestedSnapElementCaptured) {
Element& snap_element = *GetDocument().getElementById("nested-snap-element");
- snap_element.setAttribute(styleAttr, "scroll-snap-align: start;");
+ snap_element.setAttribute(kStyleAttr, "scroll-snap-align: start;");
Element* intermediate = GetDocument().getElementById("intermediate");
- intermediate->setAttribute(styleAttr, "overflow: scroll;");
+ intermediate->setAttribute(kStyleAttr, "overflow: scroll;");
GetDocument().UpdateStyleAndLayout();
@@ -142,7 +142,7 @@ TEST_F(SnapCoordinatorTest, NestedSnapElementCaptured) {
TEST_F(SnapCoordinatorTest, PositionFixedSnapElement) {
Element& snap_element =
*GetDocument().getElementById("snap-element-fixed-position");
- snap_element.setAttribute(styleAttr, "scroll-snap-align: start;");
+ snap_element.setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
// Position fixed elements are contained in document and not its immediate
@@ -157,7 +157,7 @@ TEST_F(SnapCoordinatorTest, PositionFixedSnapElement) {
TEST_F(SnapCoordinatorTest, UpdateStyleForSnapElement) {
Element& snap_element = *GetDocument().getElementById("snap-element");
- snap_element.setAttribute(styleAttr, "scroll-snap-align: start;");
+ snap_element.setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
EXPECT_EQ(1U, SizeOfSnapAreas(SnapContainer()));
@@ -319,7 +319,7 @@ TEST_F(SnapCoordinatorTest, SnapDataCalculation) {
ScrollableArea* scrollable_area =
scroller_element->GetLayoutBox()->GetScrollableArea();
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr, "scroll-snap-align: start;");
+ area_element->setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
@@ -352,7 +352,7 @@ TEST_F(SnapCoordinatorTest, ScrolledSnapDataCalculation) {
scroller_element->scrollBy(20, 20);
EXPECT_EQ(FloatPoint(20, 20), scrollable_area->ScrollPosition());
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr, "scroll-snap-align: start;");
+ area_element->setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
@@ -409,7 +409,7 @@ TEST_F(SnapCoordinatorTest, ScrolledSnapDataCalculationOnViewport) {
body->scrollBy(20, 20);
EXPECT_EQ(FloatPoint(20, 20), scrollable_area->ScrollPosition());
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr, "scroll-snap-align: start;");
+ area_element->setAttribute(kStyleAttr, "scroll-snap-align: start;");
GetDocument().UpdateStyleAndLayout();
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
base::Optional<SnapContainerData> data =
@@ -438,12 +438,12 @@ TEST_F(SnapCoordinatorTest, ScrolledSnapDataCalculationOnViewport) {
TEST_F(SnapCoordinatorTest, SnapDataCalculationWithBoxModel) {
SetUpSingleSnapArea();
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr,
+ area_element->setAttribute(kStyleAttr,
"scroll-snap-align: start; margin: 2px; border: "
"9px solid; padding: 5px;");
Element* scroller_element = GetDocument().getElementById("scroller");
scroller_element->setAttribute(
- styleAttr, "margin: 3px; border: 10px solid; padding: 4px;");
+ kStyleAttr, "margin: 3px; border: 10px solid; padding: 4px;");
GetDocument().UpdateStyleAndLayout();
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
base::Optional<SnapContainerData> data =
@@ -483,7 +483,7 @@ TEST_F(SnapCoordinatorTest, SnapDataCalculationWithBoxModel) {
TEST_F(SnapCoordinatorTest, NegativeMarginSnapDataCalculation) {
SetUpSingleSnapArea();
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr,
+ area_element->setAttribute(kStyleAttr,
"scroll-snap-align: start; scroll-margin: -8px;");
GetDocument().UpdateStyleAndLayout();
Element* scroller_element = GetDocument().getElementById("scroller");
@@ -516,7 +516,7 @@ TEST_F(SnapCoordinatorTest, NegativeMarginSnapDataCalculation) {
TEST_F(SnapCoordinatorTest, AsymmetricalSnapDataCalculation) {
SetUpSingleSnapArea();
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr,
+ area_element->setAttribute(kStyleAttr,
R"HTML(
scroll-snap-align: center;
scroll-margin-top: 2px;
@@ -525,7 +525,7 @@ TEST_F(SnapCoordinatorTest, AsymmetricalSnapDataCalculation) {
scroll-margin-left: 8px;
)HTML");
Element* scroller_element = GetDocument().getElementById("scroller");
- scroller_element->setAttribute(styleAttr,
+ scroller_element->setAttribute(kStyleAttr,
R"HTML(
scroll-padding-top: 10px;
scroll-padding-right: 12px;
@@ -562,7 +562,7 @@ TEST_F(SnapCoordinatorTest, AsymmetricalSnapDataCalculation) {
TEST_F(SnapCoordinatorTest, ScaledSnapDataCalculation) {
SetUpSingleSnapArea();
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr,
+ area_element->setAttribute(kStyleAttr,
"scroll-snap-align: end; transform: scale(4, 4);");
GetDocument().UpdateStyleAndLayout();
Element* scroller_element = GetDocument().getElementById("scroller");
@@ -597,10 +597,10 @@ TEST_F(SnapCoordinatorTest, ScaledSnapDataCalculation) {
TEST_F(SnapCoordinatorTest, VerticalRlSnapDataCalculation) {
SetUpSingleSnapArea();
Element* area_element = GetDocument().getElementById("area");
- area_element->setAttribute(styleAttr,
+ area_element->setAttribute(kStyleAttr,
"scroll-snap-align: start; left: -200px;");
Element* scroller_element = GetDocument().getElementById("scroller");
- scroller_element->setAttribute(styleAttr, "writing-mode: vertical-rl;");
+ scroller_element->setAttribute(kStyleAttr, "writing-mode: vertical-rl;");
GetDocument().UpdateStyleAndLayout();
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
base::Optional<SnapContainerData> data =
@@ -631,72 +631,4 @@ TEST_F(SnapCoordinatorTest, VerticalRlSnapDataCalculation) {
EXPECT_EQ_AREA(expected_area, actual_container.at(0));
}
-// The following tests check GetSnapPositionForPoint().
-TEST_F(SnapCoordinatorTest, SnapsIfScrolledAndSnappingAxesMatch) {
- SetUpSingleSnapArea();
- Element* area_element = GetDocument().getElementById("area");
- Element* scroller_element = GetDocument().getElementById("scroller");
- area_element->setAttribute(styleAttr, "scroll-snap-align: start;");
- scroller_element->setAttribute(styleAttr, "scroll-snap-type: x mandatory");
- GetDocument().UpdateStyleAndLayout();
-
- SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
- LayoutBox* snap_container = scroller_element->GetLayoutBox();
- base::Optional<FloatPoint> snap_position =
- snap_coordinator->GetSnapPositionForPoint(
- *snap_container, FloatPoint(150, 150), true, false);
- EXPECT_TRUE(snap_position.has_value());
- EXPECT_EQ(200 - 8 - 10, snap_position.value().X());
- EXPECT_EQ(150, snap_position.value().Y());
-}
-
-TEST_F(SnapCoordinatorTest, DoesNotSnapOnNonSnappingAxis) {
- SetUpSingleSnapArea();
- Element* area_element = GetDocument().getElementById("area");
- Element* scroller_element = GetDocument().getElementById("scroller");
- area_element->setAttribute(styleAttr, "scroll-snap-align: start;");
- scroller_element->setAttribute(styleAttr, "scroll-snap-type: y mandatory");
- GetDocument().UpdateStyleAndLayout();
-
- SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
- LayoutBox* snap_container = scroller_element->GetLayoutBox();
- base::Optional<FloatPoint> snap_position =
- snap_coordinator->GetSnapPositionForPoint(
- *snap_container, FloatPoint(150, 150), true, false);
- EXPECT_FALSE(snap_position.has_value());
-}
-
-TEST_F(SnapCoordinatorTest, DoesNotSnapOnEmptyContainer) {
- SetUpSingleSnapArea();
- Element* area_element = GetDocument().getElementById("area");
- Element* scroller_element = GetDocument().getElementById("scroller");
- area_element->setAttribute(styleAttr, "scroll-snap-align: none;");
- scroller_element->setAttribute(styleAttr, "scroll-snap-type: x mandatory");
- GetDocument().UpdateStyleAndLayout();
-
- SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
- LayoutBox* snap_container = scroller_element->GetLayoutBox();
- base::Optional<FloatPoint> snap_position =
- snap_coordinator->GetSnapPositionForPoint(
- *snap_container, FloatPoint(150, 150), true, false);
- ;
- EXPECT_FALSE(snap_position.has_value());
-}
-
-TEST_F(SnapCoordinatorTest, DoesNotSnapOnNonSnapContainer) {
- SetUpSingleSnapArea();
- Element* area_element = GetDocument().getElementById("area");
- Element* scroller_element = GetDocument().getElementById("scroller");
- area_element->setAttribute(styleAttr, "scroll-snap-align: start;");
- scroller_element->setAttribute(styleAttr, "scroll-snap-type: none");
- GetDocument().UpdateStyleAndLayout();
-
- SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
- LayoutBox* snap_container = scroller_element->GetLayoutBox();
- base::Optional<FloatPoint> snap_position =
- snap_coordinator->GetSnapPositionForPoint(
- *snap_container, FloatPoint(150, 150), true, false);
- EXPECT_FALSE(snap_position.has_value());
-}
-
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.cc b/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.cc
index b439f2c092f..f834cd92ef2 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.cc
@@ -24,10 +24,22 @@
namespace blink {
+namespace {
+
+ScrollableArea* GetScrollableArea(Node* node) {
+ if (!node || !node->GetLayoutObject() ||
+ !node->GetLayoutObject()->IsBoxModelObject())
+ return nullptr;
+
+ return ToLayoutBoxModelObject(node->GetLayoutObject())->GetScrollableArea();
+}
+
+} // namespace
+
// static
TopDocumentRootScrollerController* TopDocumentRootScrollerController::Create(
Page& page) {
- return new TopDocumentRootScrollerController(page);
+ return MakeGarbageCollected<TopDocumentRootScrollerController>(page);
}
TopDocumentRootScrollerController::TopDocumentRootScrollerController(Page& page)
@@ -40,23 +52,34 @@ void TopDocumentRootScrollerController::Trace(blink::Visitor* visitor) {
}
void TopDocumentRootScrollerController::DidChangeRootScroller() {
- RecomputeGlobalRootScroller();
+ Node* target = FindGlobalRootScroller();
+ UpdateGlobalRootScroller(target);
}
void TopDocumentRootScrollerController::DidResizeViewport() {
- if (!GlobalRootScroller())
+ if (!GlobalRootScroller() || !GlobalRootScroller()->GetDocument().IsActive())
+ return;
+
+ if (!GlobalRootScroller()->GetLayoutObject())
return;
+ DCHECK(GlobalRootScroller()->GetLayoutObject()->IsBoxModelObject());
+
+ LayoutBoxModelObject* layout_object =
+ ToLayoutBoxModelObject(GlobalRootScroller()->GetLayoutObject());
+
// Top controls can resize the viewport without invalidating compositing or
// paint so we need to do that manually here.
- GlobalRootScroller()->SetNeedsCompositingUpdate();
+ if (layout_object->HasLayer()) {
+ layout_object->Layer()->SetNeedsCompositingInputsUpdate();
+ layout_object->Layer()->UpdateSelfPaintingLayer();
+ }
- if (GlobalRootScroller()->GetLayoutObject())
- GlobalRootScroller()->GetLayoutObject()->SetNeedsPaintPropertyUpdate();
+ layout_object->SetNeedsPaintPropertyUpdate();
}
ScrollableArea* TopDocumentRootScrollerController::RootScrollerArea() const {
- return RootScrollerUtil::ScrollableAreaForRootScroller(GlobalRootScroller());
+ return GetScrollableArea(GlobalRootScroller());
}
IntSize TopDocumentRootScrollerController::RootScrollerVisibleArea() const {
@@ -77,44 +100,33 @@ IntSize TopDocumentRootScrollerController::RootScrollerVisibleArea() const {
IntSize(0, browser_controls_adjustment);
}
-Element* TopDocumentRootScrollerController::FindGlobalRootScrollerElement() {
+Node* TopDocumentRootScrollerController::FindGlobalRootScroller() {
if (!TopDocument())
return nullptr;
- Node* effective_root_scroller =
+ Node* root_scroller =
&TopDocument()->GetRootScrollerController().EffectiveRootScroller();
- if (effective_root_scroller->IsDocumentNode())
- return TopDocument()->documentElement();
-
- DCHECK(effective_root_scroller->IsElementNode());
- Element* element = ToElement(effective_root_scroller);
-
- while (element && element->IsFrameOwnerElement()) {
- HTMLFrameOwnerElement* frame_owner = ToHTMLFrameOwnerElement(element);
+ while (root_scroller && root_scroller->IsFrameOwnerElement()) {
+ HTMLFrameOwnerElement* frame_owner = ToHTMLFrameOwnerElement(root_scroller);
DCHECK(frame_owner);
Document* iframe_document = frame_owner->contentDocument();
if (!iframe_document)
- return element;
+ return root_scroller;
- effective_root_scroller =
+ root_scroller =
&iframe_document->GetRootScrollerController().EffectiveRootScroller();
- if (effective_root_scroller->IsDocumentNode())
- return iframe_document->documentElement();
-
- element = ToElement(effective_root_scroller);
}
- return element;
+ return root_scroller;
}
-void SetNeedsCompositingUpdateOnAncestors(Element* element) {
- if (!element || !element->GetDocument().IsActive())
+void SetNeedsCompositingUpdateOnAncestors(Node* node) {
+ if (!node || !node->GetDocument().IsActive())
return;
- ScrollableArea* area =
- RootScrollerUtil::ScrollableAreaForRootScroller(element);
+ ScrollableArea* area = GetScrollableArea(node);
if (!area || !area->Layer())
return;
@@ -131,16 +143,15 @@ void SetNeedsCompositingUpdateOnAncestors(Element* element) {
}
}
-void TopDocumentRootScrollerController::RecomputeGlobalRootScroller() {
+void TopDocumentRootScrollerController::UpdateGlobalRootScroller(
+ Node* new_global_root_scroller) {
if (!viewport_apply_scroll_)
return;
- Element* target = FindGlobalRootScrollerElement();
- if (target == global_root_scroller_)
+ if (new_global_root_scroller == global_root_scroller_)
return;
- ScrollableArea* target_scroller =
- RootScrollerUtil::ScrollableAreaForRootScroller(target);
+ ScrollableArea* target_scroller = GetScrollableArea(new_global_root_scroller);
if (!target_scroller)
return;
@@ -151,24 +162,24 @@ void TopDocumentRootScrollerController::RecomputeGlobalRootScroller() {
// Use disable-native-scroll since the ViewportScrollCallback needs to
// apply scroll actions both before (BrowserControls) and after (overscroll)
// scrolling the element so it will apply scroll to the element itself.
- target->SetApplyScroll(viewport_apply_scroll_);
+ new_global_root_scroller->SetApplyScroll(viewport_apply_scroll_);
- Element* old_root_scroller = global_root_scroller_;
+ Node* old_root_scroller = global_root_scroller_;
- global_root_scroller_ = target;
+ global_root_scroller_ = new_global_root_scroller;
// Ideally, scroll customization would pass the current element to scroll to
// the apply scroll callback but this doesn't happen today so we set it
// through a back door here. This is also needed by the
- // ViewportScrollCallback to swap the target into the layout viewport
- // in RootFrameViewport.
+ // ViewportScrollCallback to swap the new global root scroller into the
+ // layout viewport in RootFrameViewport.
viewport_apply_scroll_->SetScroller(target_scroller);
SetNeedsCompositingUpdateOnAncestors(old_root_scroller);
- SetNeedsCompositingUpdateOnAncestors(target);
+ SetNeedsCompositingUpdateOnAncestors(new_global_root_scroller);
- if (ScrollableArea* area =
- RootScrollerUtil::ScrollableAreaForRootScroller(old_root_scroller)) {
+ UpdateCachedBits(old_root_scroller, new_global_root_scroller);
+ if (ScrollableArea* area = GetScrollableArea(old_root_scroller)) {
if (old_root_scroller->GetDocument().IsActive())
area->DidChangeGlobalRootScroller();
}
@@ -176,6 +187,19 @@ void TopDocumentRootScrollerController::RecomputeGlobalRootScroller() {
target_scroller->DidChangeGlobalRootScroller();
}
+void TopDocumentRootScrollerController::UpdateCachedBits(Node* old_global,
+ Node* new_global) {
+ if (old_global) {
+ if (LayoutObject* object = old_global->GetLayoutObject())
+ object->SetIsGlobalRootScroller(false);
+ }
+
+ if (new_global) {
+ if (LayoutObject* object = new_global->GetLayoutObject())
+ object->SetIsGlobalRootScroller(true);
+ }
+}
+
Document* TopDocumentRootScrollerController::TopDocument() const {
if (!page_ || !page_->MainFrame() || !page_->MainFrame()->IsLocalFrame())
return nullptr;
@@ -218,13 +242,17 @@ void TopDocumentRootScrollerController::DidDisposeScrollableArea(
}
void TopDocumentRootScrollerController::InitializeViewportScrollCallback(
- RootFrameViewport& root_frame_viewport) {
+ RootFrameViewport& root_frame_viewport,
+ Document& main_document) {
DCHECK(page_);
viewport_apply_scroll_ = ViewportScrollCallback::Create(
&page_->GetBrowserControls(), &page_->GetOverscrollController(),
root_frame_viewport);
- RecomputeGlobalRootScroller();
+ // Initialize global_root_scroller_ to the default; the main document node.
+ // We can't yet reliably compute this because the frame we're loading may not
+ // be swapped into the main frame yet so TopDocument returns nullptr.
+ UpdateGlobalRootScroller(&main_document);
}
bool TopDocumentRootScrollerController::IsViewportScrollCallback(
@@ -236,8 +264,7 @@ bool TopDocumentRootScrollerController::IsViewportScrollCallback(
}
GraphicsLayer* TopDocumentRootScrollerController::RootScrollerLayer() const {
- ScrollableArea* area =
- RootScrollerUtil::ScrollableAreaForRootScroller(global_root_scroller_);
+ ScrollableArea* area = GetScrollableArea(global_root_scroller_);
if (!area)
return nullptr;
@@ -252,17 +279,15 @@ GraphicsLayer* TopDocumentRootScrollerController::RootScrollerLayer() const {
}
GraphicsLayer* TopDocumentRootScrollerController::RootContainerLayer() const {
- ScrollableArea* area =
- RootScrollerUtil::ScrollableAreaForRootScroller(global_root_scroller_);
-
+ ScrollableArea* area = GetScrollableArea(global_root_scroller_);
return area ? area->LayerForContainer() : nullptr;
}
PaintLayer* TopDocumentRootScrollerController::RootScrollerPaintLayer() const {
- return RootScrollerUtil::PaintLayerForRootScroller(global_root_scroller_);
+ return root_scroller_util::PaintLayerForRootScroller(global_root_scroller_);
}
-Element* TopDocumentRootScrollerController::GlobalRootScroller() const {
+Node* TopDocumentRootScrollerController::GlobalRootScroller() const {
return global_root_scroller_.Get();
}
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h b/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h
index 72c8232f00a..3de80a3ab60 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h
@@ -12,8 +12,8 @@
namespace blink {
-class Element;
class LocalFrameView;
+class Node;
class Page;
class GraphicsLayer;
class PaintLayer;
@@ -24,8 +24,8 @@ class ViewportScrollCallback;
// This class manages the the page level aspects of the root scroller. That
// is, given all the iframes on a page and their individual root scrollers,
-// this class will determine which ultimate Element should be used as the root
-// scroller and ensures that Element is used to scroll browser controls and
+// this class will determine which ultimate Node should be used as the root
+// scroller and ensures that Node is used to scroll browser controls and
// provide overscroll effects. High level details are available in README.md.
// TODO(bokan): This class is currently OOPIF unaware. crbug.com/642378.
class CORE_EXPORT TopDocumentRootScrollerController
@@ -33,6 +33,8 @@ class CORE_EXPORT TopDocumentRootScrollerController
public:
static TopDocumentRootScrollerController* Create(Page&);
+ TopDocumentRootScrollerController(Page&);
+
void Trace(blink::Visitor*);
// This class needs to be informed of changes to compositing so that it can
@@ -46,7 +48,7 @@ class CORE_EXPORT TopDocumentRootScrollerController
// This method needs to be called to create a ViewportScrollCallback that
// will be used to apply viewport scrolling actions like browser controls
// movement and overscroll glow.
- void InitializeViewportScrollCallback(RootFrameViewport&);
+ void InitializeViewportScrollCallback(RootFrameViewport&, Document&);
// Returns true if the given ScrollStateCallback is the
// ViewportScrollCallback managed by this class.
@@ -63,10 +65,10 @@ class CORE_EXPORT TopDocumentRootScrollerController
PaintLayer* RootScrollerPaintLayer() const;
- // Returns the Element that's the global root scroller. See README.md for
- // the difference between this and the root scroller types in
+ // Returns the Node that's the global root scroller. See README.md for the
+ // difference between this and the root scroller types in
// RootScrollerController.
- Element* GlobalRootScroller() const;
+ Node* GlobalRootScroller() const;
// Called when the root scroller in any frames on the page has changed.
void DidChangeRootScroller();
@@ -74,7 +76,7 @@ class CORE_EXPORT TopDocumentRootScrollerController
void DidResizeViewport();
// Returns the ScrollableArea associated with the globalRootScroller(). Note,
- // this isn't necessarily the PLSA belonging to the root scroller Element's
+ // this isn't necessarily the PLSA belonging to the root scroller Node's
// LayoutBox. If the root scroller is the documentElement then we use the
// LocalFrameView (or LayoutView if root-layer-scrolls).
ScrollableArea* RootScrollerArea() const;
@@ -84,18 +86,19 @@ class CORE_EXPORT TopDocumentRootScrollerController
IntSize RootScrollerVisibleArea() const;
private:
- TopDocumentRootScrollerController(Page&);
+ // Calculates the Node that should be the globalRootScroller. On a simple
+ // page, this will simply the root frame's effectiveRootScroller but if the
+ // root scroller is set to an iframe, this will then descend into the iframe
+ // to find its effective root scroller.
+ Node* FindGlobalRootScroller();
- // Calculates the Element that should be the globalRootScroller. On a
- // simple page, this will simply the root frame's effectiveRootScroller but
- // if the root scroller is set to an iframe, this will then descend into
- // the iframe to find its effective root scroller.
- Element* FindGlobalRootScrollerElement();
+ // Should be called to set a new node as the global root scroller and that
+ // all appropriate state changes are made if it changes.
+ void UpdateGlobalRootScroller(Node* new_global_root_scroller);
- // Should be called to ensure the correct element is currently set as the
- // global root scroller and that all appropriate state changes are made if
- // it changes.
- void RecomputeGlobalRootScroller();
+ // Updates the is_global_root_scroller bits in all the necessary places when
+ // the global root scsroller changes.
+ void UpdateCachedBits(Node* old_global, Node* new_global);
Document* TopDocument() const;
@@ -104,11 +107,11 @@ class CORE_EXPORT TopDocumentRootScrollerController
// appropriate root scroller element.
Member<ViewportScrollCallback> viewport_apply_scroll_;
- // The page level root scroller. i.e. The actual element for which
- // scrolling should move browser controls and produce overscroll glow. Once an
+ // The page level root scroller. i.e. The actual node for which scrolling
+ // should move browser controls and produce overscroll glow. Once an
// m_viewportApplyScroll has been created, it will always be set on this
- // Element.
- WeakMember<Element> global_root_scroller_;
+ // Node.
+ WeakMember<Node> global_root_scroller_;
Member<Page> page_;
};
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.h b/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.h
index 858b81d288c..51e90792385 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.h
@@ -37,10 +37,15 @@ class ViewportScrollCallback : public ScrollStateCallback {
BrowserControls* browser_controls,
OverscrollController* overscroll_controller,
RootFrameViewport& root_frame_viewport) {
- return new ViewportScrollCallback(browser_controls, overscroll_controller,
- root_frame_viewport);
+ return MakeGarbageCollected<ViewportScrollCallback>(
+ browser_controls, overscroll_controller, root_frame_viewport);
}
+ // ViewportScrollCallback does not assume ownership of BrowserControls or of
+ // OverscrollController.
+ ViewportScrollCallback(BrowserControls*,
+ OverscrollController*,
+ RootFrameViewport&);
~ViewportScrollCallback() override;
void Invoke(ScrollState*) override;
@@ -49,12 +54,6 @@ class ViewportScrollCallback : public ScrollStateCallback {
void Trace(blink::Visitor*) override;
private:
- // ViewportScrollCallback does not assume ownership of BrowserControls or of
- // OverscrollController.
- ViewportScrollCallback(BrowserControls*,
- OverscrollController*,
- RootFrameViewport&);
-
bool ShouldScrollBrowserControls(const ScrollOffset&,
ScrollGranularity) const;
bool ScrollBrowserControls(ScrollState&);
diff --git a/chromium/third_party/blink/renderer/core/page/spatial_navigation.cc b/chromium/third_party/blink/renderer/core/page/spatial_navigation.cc
index f0791fbe51a..1f2aa290b65 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation.cc
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation.cc
@@ -46,10 +46,7 @@
namespace blink {
-using namespace HTMLNames;
-
static void DeflateIfOverlapped(LayoutRect&, LayoutRect&);
-static bool IsScrollableNode(const Node*);
FocusCandidate::FocusCandidate(Node* node, WebFocusType direction)
: visible_node(nullptr),
diff --git a/chromium/third_party/blink/renderer/core/page/spatial_navigation.h b/chromium/third_party/blink/renderer/core/page/spatial_navigation.h
index 31f5581e103..7fe916358b1 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation.h
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation.h
@@ -89,6 +89,7 @@ CORE_EXPORT bool IsOffscreenAfterFrameScroll(const Node*, WebFocusType);
bool ScrollInDirection(LocalFrame*, WebFocusType);
bool ScrollInDirection(Node* container, WebFocusType);
bool IsNavigableContainer(const Node*, WebFocusType);
+CORE_EXPORT bool IsScrollableNode(const Node* node);
CORE_EXPORT bool IsScrollableAreaOrDocument(const Node*);
CORE_EXPORT Node* ScrollableAreaOrDocumentOf(Node*);
bool CanScrollInDirection(const Node* container, WebFocusType);
diff --git a/chromium/third_party/blink/renderer/core/page/spatial_navigation_test.cc b/chromium/third_party/blink/renderer/core/page/spatial_navigation_test.cc
index 28a5f043190..ca2fdfb4ae1 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation_test.cc
@@ -59,6 +59,11 @@ class SpatialNavigationTest : public RenderingTest {
SearchOrigin(RootViewport(&GetFrame()), focus_node, kWebFocusTypeRight),
LeftSideOfVisualViewport());
}
+
+ void UpdateAllLifecyclePhases(LocalFrameView* frame_view) {
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
};
TEST_F(SpatialNavigationTest, RootFramesVisualViewport) {
@@ -105,7 +110,7 @@ TEST_F(SpatialNavigationTest, FindContainerWhenEnclosingContainerIsIframe) {
"<!DOCTYPE html>"
"<a>link</a>");
- ChildDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(ChildDocument().View());
Element* iframe = GetDocument().QuerySelector("iframe");
Element* link = ChildDocument().QuerySelector("a");
Node* enclosing_container = ScrollableAreaOrDocumentOf(link);
@@ -444,7 +449,7 @@ TEST_F(SpatialNavigationTest,
"<!DOCTYPE html>"
"<a id='link'>link</a>");
- ChildDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(ChildDocument().View());
Element* link = ChildDocument().QuerySelector("a");
Element* iframe = GetDocument().QuerySelector("iframe");
@@ -480,7 +485,7 @@ TEST_F(SpatialNavigationTest, DivsCanClipIframes) {
"<!DOCTYPE html>"
"<a>link</a>");
- ChildDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(ChildDocument().View());
Element* div = GetDocument().QuerySelector("div");
Element* iframe = GetDocument().QuerySelector("iframe");
Element* link = ChildDocument().QuerySelector("a");
@@ -523,7 +528,7 @@ TEST_F(SpatialNavigationTest, PartiallyVisibleIFrame) {
"</style>"
"<a id='child'>link</a>");
- ChildDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(ChildDocument().View());
Element* child_element = ChildDocument().getElementById("child");
Node* enclosing_container = ScrollableAreaOrDocumentOf(child_element);
EXPECT_EQ(enclosing_container, ChildDocument());
@@ -605,18 +610,18 @@ TEST_F(SpatialNavigationTest, TopOfPinchedViewport) {
}
TEST_F(SpatialNavigationTest, HasRemoteFrame) {
- FrameTestHelpers::WebViewHelper helper;
+ frame_test_helpers::WebViewHelper helper;
helper.InitializeAndLoad("about:blank", nullptr, nullptr, nullptr, nullptr);
WebViewImpl* webview = helper.GetWebView();
- WebURL base_url = URLTestHelpers::ToKURL("http://www.test.com/");
- FrameTestHelpers::LoadHTMLString(webview->MainFrameImpl(),
- "<!DOCTYPE html>"
- "<iframe id='iframe'></iframe>",
- base_url);
+ WebURL base_url = url_test_helpers::ToKURL("http://www.test.com/");
+ frame_test_helpers::LoadHTMLString(webview->MainFrameImpl(),
+ "<!DOCTYPE html>"
+ "<iframe id='iframe'></iframe>",
+ base_url);
webview->ResizeWithBrowserControls(IntSize(400, 400), 50, 0, false);
- webview->MainFrameImpl()->GetFrame()->View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases(webview->MainFrameImpl()->GetFrame()->View());
Element* iframe =
webview->MainFrameImpl()->GetFrame()->GetDocument()->getElementById(
@@ -624,7 +629,7 @@ TEST_F(SpatialNavigationTest, HasRemoteFrame) {
EXPECT_FALSE(HasRemoteFrame(iframe));
webview->MainFrameImpl()->FirstChild()->Swap(
- FrameTestHelpers::CreateRemote());
+ frame_test_helpers::CreateRemote());
EXPECT_TRUE(HasRemoteFrame(iframe));
}
diff --git a/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.cc b/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.cc
index c6623a50cb0..11f810af0a0 100644
--- a/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.cc
+++ b/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.cc
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/validation_message_overlay_delegate.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -44,7 +44,7 @@ ValidationMessageClientImpl::ValidationMessageClientImpl(Page& page)
: page_(&page), current_anchor_(nullptr) {}
ValidationMessageClientImpl* ValidationMessageClientImpl::Create(Page& page) {
- return new ValidationMessageClientImpl(page);
+ return MakeGarbageCollected<ValidationMessageClientImpl>(page);
}
ValidationMessageClientImpl::~ValidationMessageClientImpl() = default;
@@ -94,7 +94,7 @@ void ValidationMessageClientImpl::ShowValidationMessage(
}
void ValidationMessageClientImpl::HideValidationMessage(const Element& anchor) {
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
HideValidationMessageImmediately(anchor);
return;
}
@@ -140,7 +140,7 @@ void ValidationMessageClientImpl::DocumentDetached(const Document& document) {
void ValidationMessageClientImpl::CheckAnchorStatus(TimerBase*) {
DCHECK(current_anchor_);
- if ((!LayoutTestSupport::IsRunningLayoutTest() &&
+ if ((!WebTestSupport::IsRunningWebTest() &&
CurrentTimeTicks() >= finish_time_) ||
!CurrentView()) {
HideValidationMessage(*current_anchor_);
diff --git a/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.h b/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.h
index b2cce5b34d7..f328852ea77 100644
--- a/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.h
+++ b/chromium/third_party/blink/renderer/core/page/validation_message_client_impl.h
@@ -48,12 +48,13 @@ class ValidationMessageClientImpl final
public:
static ValidationMessageClientImpl* Create(Page&);
+
+ ValidationMessageClientImpl(Page&);
~ValidationMessageClientImpl() override;
void Trace(blink::Visitor*) override;
private:
- ValidationMessageClientImpl(Page&);
void CheckAnchorStatus(TimerBase*);
LocalFrameView* CurrentView();
void HideValidationMessageImmediately(const Element& anchor);
diff --git a/chromium/third_party/blink/renderer/core/page/validation_message_overlay_delegate.cc b/chromium/third_party/blink/renderer/core/page/validation_message_overlay_delegate.cc
index a013c09f835..79883bb529a 100644
--- a/chromium/third_party/blink/renderer/core/page/validation_message_overlay_delegate.cc
+++ b/chromium/third_party/blink/renderer/core/page/validation_message_overlay_delegate.cc
@@ -16,8 +16,8 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/page_popup_client.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -120,7 +120,8 @@ void ValidationMessageOverlayDelegate::UpdateFrameViewState(
// FindVisualRectNeedingUpdateScopeBase::CheckVisualRect().
FrameView().GetLayoutView()->SetSubtreeShouldCheckForPaintInvalidation();
- FrameView().UpdateAllLifecyclePhases();
+ FrameView().UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
void ValidationMessageOverlayDelegate::EnsurePage(const PageOverlay& overlay,
@@ -131,7 +132,7 @@ void ValidationMessageOverlayDelegate::EnsurePage(const PageOverlay& overlay,
// InspectorOverlayAgent?
Page::PageClients page_clients;
FillWithEmptyClients(page_clients);
- chrome_client_ = new ValidationMessageChromeClient(
+ chrome_client_ = MakeGarbageCollected<ValidationMessageChromeClient>(
main_page_->GetChromeClient(), anchor_->GetDocument().View(),
const_cast<PageOverlay&>(overlay));
page_clients.chrome_client = chrome_client_;
@@ -140,7 +141,6 @@ void ValidationMessageOverlayDelegate::EnsurePage(const PageOverlay& overlay,
page_->GetSettings().SetMinimumFontSize(main_settings.GetMinimumFontSize());
page_->GetSettings().SetMinimumLogicalFontSize(
main_settings.GetMinimumLogicalFontSize());
- page_->GetSettings().SetAcceleratedCompositingEnabled(false);
LocalFrame* frame =
LocalFrame::Create(EmptyLocalFrameClient::Create(), *page_, nullptr);
@@ -160,7 +160,7 @@ void ValidationMessageOverlayDelegate::EnsurePage(const PageOverlay& overlay,
frame->ForceSynchronousDocumentInstall("text/html", data);
Element& container = GetElementById("container");
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
container.SetInlineStyleProperty(CSSPropertyTransition, "none");
GetElementById("icon").SetInlineStyleProperty(CSSPropertyTransition,
"none");
@@ -170,7 +170,9 @@ void ValidationMessageOverlayDelegate::EnsurePage(const PageOverlay& overlay,
.SetInlineStyleProperty(CSSPropertyTransition, "none");
}
// Get the size to decide position later.
- FrameView().UpdateAllLifecyclePhases();
+ // TODO(schenney): This says get size, so we only need to update to layout.
+ FrameView().UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
bubble_size_ = container.VisibleBoundsInVisualViewport().Size();
// Add one because the content sometimes exceeds the exact width due to
// rounding errors.
@@ -178,8 +180,9 @@ void ValidationMessageOverlayDelegate::EnsurePage(const PageOverlay& overlay,
container.SetInlineStyleProperty(CSSPropertyMinWidth,
bubble_size_.Width() / zoom_factor,
CSSPrimitiveValue::UnitType::kPixels);
- container.setAttribute(HTMLNames::classAttr, "shown-initially");
- FrameView().UpdateAllLifecyclePhases();
+ container.setAttribute(html_names::kClassAttr, "shown-initially");
+ FrameView().UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kOther);
}
void ValidationMessageOverlayDelegate::WriteDocument(SharedBuffer* data) {
@@ -294,7 +297,7 @@ void ValidationMessageOverlayDelegate::AdjustBubblePosition(
GetElementById("inner-arrow-bottom")
.SetInlineStyleProperty(CSSPropertyLeft, arrow_x,
CSSPrimitiveValue::UnitType::kPixels);
- container.setAttribute(HTMLNames::classAttr, "shown-fully bottom-arrow");
+ container.setAttribute(html_names::kClassAttr, "shown-fully bottom-arrow");
container.SetInlineStyleProperty(
CSSPropertyTransformOrigin,
String::Format("%.2f%% bottom", arrow_anchor_percent));
@@ -305,7 +308,7 @@ void ValidationMessageOverlayDelegate::AdjustBubblePosition(
GetElementById("inner-arrow-top")
.SetInlineStyleProperty(CSSPropertyLeft, arrow_x,
CSSPrimitiveValue::UnitType::kPixels);
- container.setAttribute(HTMLNames::classAttr, "shown-fully");
+ container.setAttribute(html_names::kClassAttr, "shown-fully");
container.SetInlineStyleProperty(
CSSPropertyTransformOrigin,
String::Format("%.2f%% top", arrow_anchor_percent));
diff --git a/chromium/third_party/blink/renderer/core/page/viewport_description.cc b/chromium/third_party/blink/renderer/core/page/viewport_description.cc
index ee87f7d8daf..5d8a3c15cc8 100644
--- a/chromium/third_party/blink/renderer/core/page/viewport_description.cc
+++ b/chromium/third_party/blink/renderer/core/page/viewport_description.cc
@@ -30,6 +30,7 @@
#include "third_party/blink/renderer/core/page/viewport_description.h"
#include "build/build_config.h"
+#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
@@ -301,7 +302,9 @@ void ViewportDescription::ReportMobilePageStats(
}
bool ViewportDescription::MatchesHeuristicsForGpuRasterization() const {
- return IsSpecifiedByAuthor();
+ bool enable_viewport_restriction = base::FeatureList::IsEnabled(
+ features::kEnableGpuRasterizationViewportRestriction);
+ return !enable_viewport_restriction || IsSpecifiedByAuthor();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/viewport_description.h b/chromium/third_party/blink/renderer/core/page/viewport_description.h
index a0ed23ad0be..05d1aa071a4 100644
--- a/chromium/third_party/blink/renderer/core/page/viewport_description.h
+++ b/chromium/third_party/blink/renderer/core/page/viewport_description.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/page_scale_constraints.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/page/viewport_test.cc b/chromium/third_party/blink/renderer/core/page/viewport_test.cc
index 8451db595bf..66afb242ec9 100644
--- a/chromium/third_party/blink/renderer/core/page/viewport_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/viewport_test.cc
@@ -51,7 +51,7 @@
#include "third_party/blink/renderer/platform/geometry/int_point.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
@@ -72,13 +72,13 @@ class ViewportTest : public testing::Test {
}
void RegisterMockedHttpURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
void RegisterMockedChromeURLLoad(const std::string& file_name) {
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8(chrome_url_), test::CoreTestDataPath(),
WebString::FromUTF8(file_name));
}
@@ -118,7 +118,7 @@ static PageScaleConstraints RunViewportTest(Page* page,
TEST_F(ViewportTest, viewport1) {
RegisterMockedHttpURLLoad("viewport/viewport-1.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-1.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -137,7 +137,7 @@ TEST_F(ViewportTest, viewport1) {
TEST_F(ViewportTest, viewport2) {
RegisterMockedHttpURLLoad("viewport/viewport-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-2.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -156,7 +156,7 @@ TEST_F(ViewportTest, viewport2) {
TEST_F(ViewportTest, viewport3) {
RegisterMockedHttpURLLoad("viewport/viewport-3.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-3.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -175,7 +175,7 @@ TEST_F(ViewportTest, viewport3) {
TEST_F(ViewportTest, viewport4) {
RegisterMockedHttpURLLoad("viewport/viewport-4.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-4.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -194,7 +194,7 @@ TEST_F(ViewportTest, viewport4) {
TEST_F(ViewportTest, viewport5) {
RegisterMockedHttpURLLoad("viewport/viewport-5.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-5.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -213,7 +213,7 @@ TEST_F(ViewportTest, viewport5) {
TEST_F(ViewportTest, viewport6) {
RegisterMockedHttpURLLoad("viewport/viewport-6.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-6.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -232,7 +232,7 @@ TEST_F(ViewportTest, viewport6) {
TEST_F(ViewportTest, viewport7) {
RegisterMockedHttpURLLoad("viewport/viewport-7.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-7.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -251,7 +251,7 @@ TEST_F(ViewportTest, viewport7) {
TEST_F(ViewportTest, viewport8) {
RegisterMockedHttpURLLoad("viewport/viewport-8.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-8.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -270,7 +270,7 @@ TEST_F(ViewportTest, viewport8) {
TEST_F(ViewportTest, viewport9) {
RegisterMockedHttpURLLoad("viewport/viewport-9.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-9.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -289,7 +289,7 @@ TEST_F(ViewportTest, viewport9) {
TEST_F(ViewportTest, viewport10) {
RegisterMockedHttpURLLoad("viewport/viewport-10.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-10.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -308,7 +308,7 @@ TEST_F(ViewportTest, viewport10) {
TEST_F(ViewportTest, viewport11) {
RegisterMockedHttpURLLoad("viewport/viewport-11.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-11.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -327,7 +327,7 @@ TEST_F(ViewportTest, viewport11) {
TEST_F(ViewportTest, viewport12) {
RegisterMockedHttpURLLoad("viewport/viewport-12.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-12.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -346,7 +346,7 @@ TEST_F(ViewportTest, viewport12) {
TEST_F(ViewportTest, viewport13) {
RegisterMockedHttpURLLoad("viewport/viewport-13.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-13.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -365,7 +365,7 @@ TEST_F(ViewportTest, viewport13) {
TEST_F(ViewportTest, viewport14) {
RegisterMockedHttpURLLoad("viewport/viewport-14.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-14.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -384,7 +384,7 @@ TEST_F(ViewportTest, viewport14) {
TEST_F(ViewportTest, viewport15) {
RegisterMockedHttpURLLoad("viewport/viewport-15.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-15.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -403,7 +403,7 @@ TEST_F(ViewportTest, viewport15) {
TEST_F(ViewportTest, viewport16) {
RegisterMockedHttpURLLoad("viewport/viewport-16.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-16.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -422,7 +422,7 @@ TEST_F(ViewportTest, viewport16) {
TEST_F(ViewportTest, viewport17) {
RegisterMockedHttpURLLoad("viewport/viewport-17.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-17.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -441,7 +441,7 @@ TEST_F(ViewportTest, viewport17) {
TEST_F(ViewportTest, viewport18) {
RegisterMockedHttpURLLoad("viewport/viewport-18.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-18.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -460,7 +460,7 @@ TEST_F(ViewportTest, viewport18) {
TEST_F(ViewportTest, viewport19) {
RegisterMockedHttpURLLoad("viewport/viewport-19.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-19.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -479,7 +479,7 @@ TEST_F(ViewportTest, viewport19) {
TEST_F(ViewportTest, viewport20) {
RegisterMockedHttpURLLoad("viewport/viewport-20.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-20.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -498,7 +498,7 @@ TEST_F(ViewportTest, viewport20) {
TEST_F(ViewportTest, viewport21) {
RegisterMockedHttpURLLoad("viewport/viewport-21.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-21.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -517,7 +517,7 @@ TEST_F(ViewportTest, viewport21) {
TEST_F(ViewportTest, viewport22) {
RegisterMockedHttpURLLoad("viewport/viewport-22.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-22.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -536,7 +536,7 @@ TEST_F(ViewportTest, viewport22) {
TEST_F(ViewportTest, viewport23) {
RegisterMockedHttpURLLoad("viewport/viewport-23.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-23.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -555,7 +555,7 @@ TEST_F(ViewportTest, viewport23) {
TEST_F(ViewportTest, viewport24) {
RegisterMockedHttpURLLoad("viewport/viewport-24.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-24.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -574,7 +574,7 @@ TEST_F(ViewportTest, viewport24) {
TEST_F(ViewportTest, viewport25) {
RegisterMockedHttpURLLoad("viewport/viewport-25.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-25.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -593,7 +593,7 @@ TEST_F(ViewportTest, viewport25) {
TEST_F(ViewportTest, viewport26) {
RegisterMockedHttpURLLoad("viewport/viewport-26.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-26.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -612,7 +612,7 @@ TEST_F(ViewportTest, viewport26) {
TEST_F(ViewportTest, viewport27) {
RegisterMockedHttpURLLoad("viewport/viewport-27.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-27.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -631,7 +631,7 @@ TEST_F(ViewportTest, viewport27) {
TEST_F(ViewportTest, viewport28) {
RegisterMockedHttpURLLoad("viewport/viewport-28.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-28.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -650,7 +650,7 @@ TEST_F(ViewportTest, viewport28) {
TEST_F(ViewportTest, viewport29) {
RegisterMockedHttpURLLoad("viewport/viewport-29.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-29.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -669,7 +669,7 @@ TEST_F(ViewportTest, viewport29) {
TEST_F(ViewportTest, viewport30) {
RegisterMockedHttpURLLoad("viewport/viewport-30.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-30.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -688,7 +688,7 @@ TEST_F(ViewportTest, viewport30) {
TEST_F(ViewportTest, viewport31) {
RegisterMockedHttpURLLoad("viewport/viewport-31.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-31.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -707,7 +707,7 @@ TEST_F(ViewportTest, viewport31) {
TEST_F(ViewportTest, viewport32) {
RegisterMockedHttpURLLoad("viewport/viewport-32.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-32.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -726,7 +726,7 @@ TEST_F(ViewportTest, viewport32) {
TEST_F(ViewportTest, viewport33) {
RegisterMockedHttpURLLoad("viewport/viewport-33.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-33.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -745,7 +745,7 @@ TEST_F(ViewportTest, viewport33) {
TEST_F(ViewportTest, viewport34) {
RegisterMockedHttpURLLoad("viewport/viewport-34.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-34.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -764,7 +764,7 @@ TEST_F(ViewportTest, viewport34) {
TEST_F(ViewportTest, viewport35) {
RegisterMockedHttpURLLoad("viewport/viewport-35.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-35.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -783,7 +783,7 @@ TEST_F(ViewportTest, viewport35) {
TEST_F(ViewportTest, viewport36) {
RegisterMockedHttpURLLoad("viewport/viewport-36.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-36.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -802,7 +802,7 @@ TEST_F(ViewportTest, viewport36) {
TEST_F(ViewportTest, viewport37) {
RegisterMockedHttpURLLoad("viewport/viewport-37.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-37.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -821,7 +821,7 @@ TEST_F(ViewportTest, viewport37) {
TEST_F(ViewportTest, viewport38) {
RegisterMockedHttpURLLoad("viewport/viewport-38.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-38.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -840,7 +840,7 @@ TEST_F(ViewportTest, viewport38) {
TEST_F(ViewportTest, viewport39) {
RegisterMockedHttpURLLoad("viewport/viewport-39.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-39.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -859,7 +859,7 @@ TEST_F(ViewportTest, viewport39) {
TEST_F(ViewportTest, viewport40) {
RegisterMockedHttpURLLoad("viewport/viewport-40.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-40.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -878,7 +878,7 @@ TEST_F(ViewportTest, viewport40) {
TEST_F(ViewportTest, viewport41) {
RegisterMockedHttpURLLoad("viewport/viewport-41.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-41.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -897,7 +897,7 @@ TEST_F(ViewportTest, viewport41) {
TEST_F(ViewportTest, viewport42) {
RegisterMockedHttpURLLoad("viewport/viewport-42.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-42.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -916,7 +916,7 @@ TEST_F(ViewportTest, viewport42) {
TEST_F(ViewportTest, viewport43) {
RegisterMockedHttpURLLoad("viewport/viewport-43.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-43.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -935,7 +935,7 @@ TEST_F(ViewportTest, viewport43) {
TEST_F(ViewportTest, viewport44) {
RegisterMockedHttpURLLoad("viewport/viewport-44.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-44.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -954,7 +954,7 @@ TEST_F(ViewportTest, viewport44) {
TEST_F(ViewportTest, viewport45) {
RegisterMockedHttpURLLoad("viewport/viewport-45.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-45.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -973,7 +973,7 @@ TEST_F(ViewportTest, viewport45) {
TEST_F(ViewportTest, viewport46) {
RegisterMockedHttpURLLoad("viewport/viewport-46.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-46.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -992,7 +992,7 @@ TEST_F(ViewportTest, viewport46) {
TEST_F(ViewportTest, viewport47) {
RegisterMockedHttpURLLoad("viewport/viewport-47.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-47.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1011,7 +1011,7 @@ TEST_F(ViewportTest, viewport47) {
TEST_F(ViewportTest, viewport48) {
RegisterMockedHttpURLLoad("viewport/viewport-48.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-48.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1030,7 +1030,7 @@ TEST_F(ViewportTest, viewport48) {
TEST_F(ViewportTest, viewport49) {
RegisterMockedHttpURLLoad("viewport/viewport-49.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-49.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1049,7 +1049,7 @@ TEST_F(ViewportTest, viewport49) {
TEST_F(ViewportTest, viewport50) {
RegisterMockedHttpURLLoad("viewport/viewport-50.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-50.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1068,7 +1068,7 @@ TEST_F(ViewportTest, viewport50) {
TEST_F(ViewportTest, viewport51) {
RegisterMockedHttpURLLoad("viewport/viewport-51.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-51.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1087,7 +1087,7 @@ TEST_F(ViewportTest, viewport51) {
TEST_F(ViewportTest, viewport52) {
RegisterMockedHttpURLLoad("viewport/viewport-52.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-52.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1106,7 +1106,7 @@ TEST_F(ViewportTest, viewport52) {
TEST_F(ViewportTest, viewport53) {
RegisterMockedHttpURLLoad("viewport/viewport-53.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-53.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1125,7 +1125,7 @@ TEST_F(ViewportTest, viewport53) {
TEST_F(ViewportTest, viewport54) {
RegisterMockedHttpURLLoad("viewport/viewport-54.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-54.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1144,7 +1144,7 @@ TEST_F(ViewportTest, viewport54) {
TEST_F(ViewportTest, viewport55) {
RegisterMockedHttpURLLoad("viewport/viewport-55.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-55.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1163,7 +1163,7 @@ TEST_F(ViewportTest, viewport55) {
TEST_F(ViewportTest, viewport56) {
RegisterMockedHttpURLLoad("viewport/viewport-56.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-56.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1182,7 +1182,7 @@ TEST_F(ViewportTest, viewport56) {
TEST_F(ViewportTest, viewport57) {
RegisterMockedHttpURLLoad("viewport/viewport-57.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-57.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1201,7 +1201,7 @@ TEST_F(ViewportTest, viewport57) {
TEST_F(ViewportTest, viewport58) {
RegisterMockedHttpURLLoad("viewport/viewport-58.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-58.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1220,7 +1220,7 @@ TEST_F(ViewportTest, viewport58) {
TEST_F(ViewportTest, viewport59) {
RegisterMockedHttpURLLoad("viewport/viewport-59.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-59.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1239,7 +1239,7 @@ TEST_F(ViewportTest, viewport59) {
TEST_F(ViewportTest, viewport60) {
RegisterMockedHttpURLLoad("viewport/viewport-60.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-60.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1258,7 +1258,7 @@ TEST_F(ViewportTest, viewport60) {
TEST_F(ViewportTest, viewport61) {
RegisterMockedHttpURLLoad("viewport/viewport-61.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-61.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1277,7 +1277,7 @@ TEST_F(ViewportTest, viewport61) {
TEST_F(ViewportTest, viewport62) {
RegisterMockedHttpURLLoad("viewport/viewport-62.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-62.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1296,7 +1296,7 @@ TEST_F(ViewportTest, viewport62) {
TEST_F(ViewportTest, viewport63) {
RegisterMockedHttpURLLoad("viewport/viewport-63.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-63.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1315,7 +1315,7 @@ TEST_F(ViewportTest, viewport63) {
TEST_F(ViewportTest, viewport64) {
RegisterMockedHttpURLLoad("viewport/viewport-64.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-64.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1334,7 +1334,7 @@ TEST_F(ViewportTest, viewport64) {
TEST_F(ViewportTest, viewport65) {
RegisterMockedHttpURLLoad("viewport/viewport-65.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-65.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1353,7 +1353,7 @@ TEST_F(ViewportTest, viewport65) {
TEST_F(ViewportTest, viewport66) {
RegisterMockedHttpURLLoad("viewport/viewport-66.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-66.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1372,7 +1372,7 @@ TEST_F(ViewportTest, viewport66) {
TEST_F(ViewportTest, viewport67) {
RegisterMockedHttpURLLoad("viewport/viewport-67.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-67.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1391,7 +1391,7 @@ TEST_F(ViewportTest, viewport67) {
TEST_F(ViewportTest, viewport68) {
RegisterMockedHttpURLLoad("viewport/viewport-68.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-68.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1410,7 +1410,7 @@ TEST_F(ViewportTest, viewport68) {
TEST_F(ViewportTest, viewport69) {
RegisterMockedHttpURLLoad("viewport/viewport-69.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-69.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1429,7 +1429,7 @@ TEST_F(ViewportTest, viewport69) {
TEST_F(ViewportTest, viewport70) {
RegisterMockedHttpURLLoad("viewport/viewport-70.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-70.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1448,7 +1448,7 @@ TEST_F(ViewportTest, viewport70) {
TEST_F(ViewportTest, viewport71) {
RegisterMockedHttpURLLoad("viewport/viewport-71.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-71.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1467,7 +1467,7 @@ TEST_F(ViewportTest, viewport71) {
TEST_F(ViewportTest, viewport72) {
RegisterMockedHttpURLLoad("viewport/viewport-72.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-72.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1486,7 +1486,7 @@ TEST_F(ViewportTest, viewport72) {
TEST_F(ViewportTest, viewport73) {
RegisterMockedHttpURLLoad("viewport/viewport-73.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-73.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1505,7 +1505,7 @@ TEST_F(ViewportTest, viewport73) {
TEST_F(ViewportTest, viewport74) {
RegisterMockedHttpURLLoad("viewport/viewport-74.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-74.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1524,7 +1524,7 @@ TEST_F(ViewportTest, viewport74) {
TEST_F(ViewportTest, viewport75) {
RegisterMockedHttpURLLoad("viewport/viewport-75.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-75.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1543,7 +1543,7 @@ TEST_F(ViewportTest, viewport75) {
TEST_F(ViewportTest, viewport76) {
RegisterMockedHttpURLLoad("viewport/viewport-76.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-76.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1562,7 +1562,7 @@ TEST_F(ViewportTest, viewport76) {
TEST_F(ViewportTest, viewport77) {
RegisterMockedHttpURLLoad("viewport/viewport-77.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-77.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1581,7 +1581,7 @@ TEST_F(ViewportTest, viewport77) {
TEST_F(ViewportTest, viewport78) {
RegisterMockedHttpURLLoad("viewport/viewport-78.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-78.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1600,7 +1600,7 @@ TEST_F(ViewportTest, viewport78) {
TEST_F(ViewportTest, viewport79) {
RegisterMockedHttpURLLoad("viewport/viewport-79.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-79.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1619,7 +1619,7 @@ TEST_F(ViewportTest, viewport79) {
TEST_F(ViewportTest, viewport80) {
RegisterMockedHttpURLLoad("viewport/viewport-80.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-80.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1638,7 +1638,7 @@ TEST_F(ViewportTest, viewport80) {
TEST_F(ViewportTest, viewport81) {
RegisterMockedHttpURLLoad("viewport/viewport-81.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-81.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1657,7 +1657,7 @@ TEST_F(ViewportTest, viewport81) {
TEST_F(ViewportTest, viewport82) {
RegisterMockedHttpURLLoad("viewport/viewport-82.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-82.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1676,7 +1676,7 @@ TEST_F(ViewportTest, viewport82) {
TEST_F(ViewportTest, viewport83) {
RegisterMockedHttpURLLoad("viewport/viewport-83.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-83.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1695,7 +1695,7 @@ TEST_F(ViewportTest, viewport83) {
TEST_F(ViewportTest, viewport84) {
RegisterMockedHttpURLLoad("viewport/viewport-84.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-84.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1714,7 +1714,7 @@ TEST_F(ViewportTest, viewport84) {
TEST_F(ViewportTest, viewport85) {
RegisterMockedHttpURLLoad("viewport/viewport-85.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-85.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1733,7 +1733,7 @@ TEST_F(ViewportTest, viewport85) {
TEST_F(ViewportTest, viewport86) {
RegisterMockedHttpURLLoad("viewport/viewport-86.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-86.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1752,7 +1752,7 @@ TEST_F(ViewportTest, viewport86) {
TEST_F(ViewportTest, viewport87) {
RegisterMockedHttpURLLoad("viewport/viewport-87.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-87.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1771,7 +1771,7 @@ TEST_F(ViewportTest, viewport87) {
TEST_F(ViewportTest, viewport88) {
RegisterMockedHttpURLLoad("viewport/viewport-88.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-88.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1790,7 +1790,7 @@ TEST_F(ViewportTest, viewport88) {
TEST_F(ViewportTest, viewport90) {
RegisterMockedHttpURLLoad("viewport/viewport-90.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-90.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1809,7 +1809,7 @@ TEST_F(ViewportTest, viewport90) {
TEST_F(ViewportTest, viewport100) {
RegisterMockedHttpURLLoad("viewport/viewport-100.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-100.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1828,7 +1828,7 @@ TEST_F(ViewportTest, viewport100) {
TEST_F(ViewportTest, viewport101) {
RegisterMockedHttpURLLoad("viewport/viewport-101.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-101.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1847,7 +1847,7 @@ TEST_F(ViewportTest, viewport101) {
TEST_F(ViewportTest, viewport102) {
RegisterMockedHttpURLLoad("viewport/viewport-102.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-102.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1866,7 +1866,7 @@ TEST_F(ViewportTest, viewport102) {
TEST_F(ViewportTest, viewport103) {
RegisterMockedHttpURLLoad("viewport/viewport-103.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-103.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1885,7 +1885,7 @@ TEST_F(ViewportTest, viewport103) {
TEST_F(ViewportTest, viewport104) {
RegisterMockedHttpURLLoad("viewport/viewport-104.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-104.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1904,7 +1904,7 @@ TEST_F(ViewportTest, viewport104) {
TEST_F(ViewportTest, viewport105) {
RegisterMockedHttpURLLoad("viewport/viewport-105.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-105.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1923,7 +1923,7 @@ TEST_F(ViewportTest, viewport105) {
TEST_F(ViewportTest, viewport106) {
RegisterMockedHttpURLLoad("viewport/viewport-106.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-106.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1942,7 +1942,7 @@ TEST_F(ViewportTest, viewport106) {
TEST_F(ViewportTest, viewport107) {
RegisterMockedHttpURLLoad("viewport/viewport-107.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-107.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1961,7 +1961,7 @@ TEST_F(ViewportTest, viewport107) {
TEST_F(ViewportTest, viewport108) {
RegisterMockedHttpURLLoad("viewport/viewport-108.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-108.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1980,7 +1980,7 @@ TEST_F(ViewportTest, viewport108) {
TEST_F(ViewportTest, viewport109) {
RegisterMockedHttpURLLoad("viewport/viewport-109.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-109.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -1999,7 +1999,7 @@ TEST_F(ViewportTest, viewport109) {
TEST_F(ViewportTest, viewport110) {
RegisterMockedHttpURLLoad("viewport/viewport-110.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-110.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2018,7 +2018,7 @@ TEST_F(ViewportTest, viewport110) {
TEST_F(ViewportTest, viewport111) {
RegisterMockedHttpURLLoad("viewport/viewport-111.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-111.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2037,7 +2037,7 @@ TEST_F(ViewportTest, viewport111) {
TEST_F(ViewportTest, viewport112) {
RegisterMockedHttpURLLoad("viewport/viewport-112.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-112.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2056,7 +2056,7 @@ TEST_F(ViewportTest, viewport112) {
TEST_F(ViewportTest, viewport113) {
RegisterMockedHttpURLLoad("viewport/viewport-113.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-113.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2075,7 +2075,7 @@ TEST_F(ViewportTest, viewport113) {
TEST_F(ViewportTest, viewport114) {
RegisterMockedHttpURLLoad("viewport/viewport-114.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-114.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2094,7 +2094,7 @@ TEST_F(ViewportTest, viewport114) {
TEST_F(ViewportTest, viewport115) {
RegisterMockedHttpURLLoad("viewport/viewport-115.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-115.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2113,7 +2113,7 @@ TEST_F(ViewportTest, viewport115) {
TEST_F(ViewportTest, viewport116) {
RegisterMockedHttpURLLoad("viewport/viewport-116.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-116.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2132,7 +2132,7 @@ TEST_F(ViewportTest, viewport116) {
TEST_F(ViewportTest, viewport117) {
RegisterMockedHttpURLLoad("viewport/viewport-117.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-117.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2151,7 +2151,7 @@ TEST_F(ViewportTest, viewport117) {
TEST_F(ViewportTest, viewport118) {
RegisterMockedHttpURLLoad("viewport/viewport-118.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-118.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2170,7 +2170,7 @@ TEST_F(ViewportTest, viewport118) {
TEST_F(ViewportTest, viewport119) {
RegisterMockedHttpURLLoad("viewport/viewport-119.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-119.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2189,7 +2189,7 @@ TEST_F(ViewportTest, viewport119) {
TEST_F(ViewportTest, viewport120) {
RegisterMockedHttpURLLoad("viewport/viewport-120.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-120.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2208,7 +2208,7 @@ TEST_F(ViewportTest, viewport120) {
TEST_F(ViewportTest, viewport121) {
RegisterMockedHttpURLLoad("viewport/viewport-121.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-121.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2227,7 +2227,7 @@ TEST_F(ViewportTest, viewport121) {
TEST_F(ViewportTest, viewport122) {
RegisterMockedHttpURLLoad("viewport/viewport-122.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-122.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2246,7 +2246,7 @@ TEST_F(ViewportTest, viewport122) {
TEST_F(ViewportTest, viewport123) {
RegisterMockedHttpURLLoad("viewport/viewport-123.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-123.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2265,7 +2265,7 @@ TEST_F(ViewportTest, viewport123) {
TEST_F(ViewportTest, viewport124) {
RegisterMockedHttpURLLoad("viewport/viewport-124.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-124.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2284,7 +2284,7 @@ TEST_F(ViewportTest, viewport124) {
TEST_F(ViewportTest, viewport125) {
RegisterMockedHttpURLLoad("viewport/viewport-125.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-125.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2303,7 +2303,7 @@ TEST_F(ViewportTest, viewport125) {
TEST_F(ViewportTest, viewport126) {
RegisterMockedHttpURLLoad("viewport/viewport-126.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-126.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2322,7 +2322,7 @@ TEST_F(ViewportTest, viewport126) {
TEST_F(ViewportTest, viewport127) {
RegisterMockedHttpURLLoad("viewport/viewport-127.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-127.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2341,7 +2341,7 @@ TEST_F(ViewportTest, viewport127) {
TEST_F(ViewportTest, viewport129) {
RegisterMockedHttpURLLoad("viewport/viewport-129.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-129.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2360,7 +2360,7 @@ TEST_F(ViewportTest, viewport129) {
TEST_F(ViewportTest, viewport130) {
RegisterMockedHttpURLLoad("viewport/viewport-130.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-130.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2379,7 +2379,7 @@ TEST_F(ViewportTest, viewport130) {
TEST_F(ViewportTest, viewport131) {
RegisterMockedHttpURLLoad("viewport/viewport-131.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-131.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2398,7 +2398,7 @@ TEST_F(ViewportTest, viewport131) {
TEST_F(ViewportTest, viewport132) {
RegisterMockedHttpURLLoad("viewport/viewport-132.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-132.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2417,7 +2417,7 @@ TEST_F(ViewportTest, viewport132) {
TEST_F(ViewportTest, viewport133) {
RegisterMockedHttpURLLoad("viewport/viewport-133.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-133.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2436,7 +2436,7 @@ TEST_F(ViewportTest, viewport133) {
TEST_F(ViewportTest, viewport134) {
RegisterMockedHttpURLLoad("viewport/viewport-134.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-134.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2455,7 +2455,7 @@ TEST_F(ViewportTest, viewport134) {
TEST_F(ViewportTest, viewport135) {
RegisterMockedHttpURLLoad("viewport/viewport-135.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-135.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2474,7 +2474,7 @@ TEST_F(ViewportTest, viewport135) {
TEST_F(ViewportTest, viewport136) {
RegisterMockedHttpURLLoad("viewport/viewport-136.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-136.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2493,7 +2493,7 @@ TEST_F(ViewportTest, viewport136) {
TEST_F(ViewportTest, viewport137) {
RegisterMockedHttpURLLoad("viewport/viewport-137.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-137.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2512,7 +2512,7 @@ TEST_F(ViewportTest, viewport137) {
TEST_F(ViewportTest, viewport138) {
RegisterMockedHttpURLLoad("viewport/viewport-138.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-138.html",
nullptr, nullptr, nullptr,
SetViewportSettings);
@@ -2531,7 +2531,7 @@ TEST_F(ViewportTest, viewport138) {
TEST_F(ViewportTest, viewportLegacyHandheldFriendly) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-handheldfriendly.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-handheldfriendly.html", nullptr,
nullptr, nullptr, SetViewportSettings);
@@ -2557,7 +2557,7 @@ static void SetQuirkViewportSettings(WebSettings* settings) {
TEST_F(ViewportTest, viewportLegacyMergeQuirk1) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-merge-quirk-1.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-merge-quirk-1.html", nullptr,
nullptr, nullptr, SetQuirkViewportSettings);
@@ -2576,7 +2576,7 @@ TEST_F(ViewportTest, viewportLegacyMergeQuirk1) {
TEST_F(ViewportTest, viewportLegacyMergeQuirk2) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-merge-quirk-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-merge-quirk-2.html", nullptr,
nullptr, nullptr, SetQuirkViewportSettings);
@@ -2598,7 +2598,7 @@ TEST_F(ViewportTest, viewportLegacyMergeQuirk2) {
TEST_F(ViewportTest, viewportLegacyMobileOptimizedMetaWithoutContent) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-mobileoptimized.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-mobileoptimized.html", nullptr,
nullptr, nullptr, SetViewportSettings);
@@ -2618,7 +2618,7 @@ TEST_F(ViewportTest, viewportLegacyMobileOptimizedMetaWithoutContent) {
TEST_F(ViewportTest, viewportLegacyMobileOptimizedMetaWith0) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-mobileoptimized-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-mobileoptimized-2.html", nullptr,
nullptr, nullptr, SetViewportSettings);
@@ -2638,7 +2638,7 @@ TEST_F(ViewportTest, viewportLegacyMobileOptimizedMetaWith0) {
TEST_F(ViewportTest, viewportLegacyMobileOptimizedMetaWith400) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-mobileoptimized-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-mobileoptimized-2.html", nullptr,
nullptr, nullptr, SetViewportSettings);
@@ -2658,7 +2658,7 @@ TEST_F(ViewportTest, viewportLegacyMobileOptimizedMetaWith400) {
TEST_F(ViewportTest, viewportLegacyOrdering2) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-2.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2678,7 +2678,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering2) {
TEST_F(ViewportTest, viewportLegacyOrdering3) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-3.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-3.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2698,7 +2698,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering3) {
TEST_F(ViewportTest, viewportLegacyOrdering4) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-4.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-4.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2718,7 +2718,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering4) {
TEST_F(ViewportTest, viewportLegacyOrdering5) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-5.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-5.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2738,7 +2738,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering5) {
TEST_F(ViewportTest, viewportLegacyOrdering6) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-6.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-6.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2758,7 +2758,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering6) {
TEST_F(ViewportTest, viewportLegacyOrdering7) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-7.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-7.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2778,7 +2778,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering7) {
TEST_F(ViewportTest, viewportLegacyOrdering8) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-8.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-8.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2798,7 +2798,7 @@ TEST_F(ViewportTest, viewportLegacyOrdering8) {
TEST_F(ViewportTest, viewportLegacyEmptyAtViewportDoesntOverrideViewportMeta) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-ordering-10.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-ordering-10.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2812,7 +2812,7 @@ TEST_F(ViewportTest, viewportLegacyEmptyAtViewportDoesntOverrideViewportMeta) {
TEST_F(ViewportTest, viewportLegacyDefaultValueChangedByXHTMLMP) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-xhtmlmp.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-xhtmlmp.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2833,7 +2833,7 @@ TEST_F(ViewportTest,
RegisterMockedHttpURLLoad(
"viewport/viewport-legacy-xhtmlmp-misplaced-doctype.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-xhtmlmp-misplaced-doctype.html",
nullptr, nullptr, nullptr, SetViewportSettings);
@@ -2852,7 +2852,7 @@ TEST_F(ViewportTest,
TEST_F(ViewportTest, viewportLegacyXHTMLMPOrdering) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-xhtmlmp-ordering.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-xhtmlmp-ordering.html", nullptr,
nullptr, nullptr, SetViewportSettings);
@@ -2871,7 +2871,7 @@ TEST_F(ViewportTest, viewportLegacyXHTMLMPOrdering) {
TEST_F(ViewportTest, viewportLegacyXHTMLMPRemoveAndAdd) {
RegisterMockedHttpURLLoad("viewport/viewport-legacy-xhtmlmp.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-xhtmlmp.html", nullptr, nullptr,
nullptr, SetViewportSettings);
@@ -2916,12 +2916,13 @@ TEST_F(ViewportTest, viewportLimitsAdjustedForNoUserScale) {
RegisterMockedHttpURLLoad(
"viewport/viewport-limits-adjusted-for-no-user-scale.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-limits-adjusted-for-no-user-scale.html",
nullptr, nullptr, nullptr, SetViewportSettings);
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ web_view_helper.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
Page* page = web_view_helper.GetWebView()->GetPage();
PageScaleConstraints constraints = RunViewportTest(page, 10, 10);
@@ -2934,12 +2935,12 @@ TEST_F(ViewportTest, viewportLimitsAdjustedForUserScale) {
RegisterMockedHttpURLLoad(
"viewport/viewport-limits-adjusted-for-user-scale.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-limits-adjusted-for-user-scale.html",
nullptr, nullptr, nullptr, SetViewportSettings);
-
- web_view_helper.GetWebView()->UpdateAllLifecyclePhases();
+ web_view_helper.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
Page* page = web_view_helper.GetWebView()->GetPage();
PageScaleConstraints constraints = RunViewportTest(page, 10, 10);
@@ -2949,7 +2950,7 @@ TEST_F(ViewportTest, viewportLimitsAdjustedForUserScale) {
}
TEST_F(ViewportTest, viewportTriggersGpuRasterization) {
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
RegisterMockedHttpURLLoad(
"viewport/viewport-gpu-rasterization-disabled-without-viewport.html");
@@ -3029,7 +3030,7 @@ TEST_F(ViewportTest, viewportTriggersGpuRasterization) {
}
class ConsoleMessageWebFrameClient
- : public FrameTestHelpers::TestWebFrameClient {
+ : public frame_test_helpers::TestWebFrameClient {
public:
void DidAddMessageToConsole(const WebConsoleMessage& msg,
const WebString& source_name,
@@ -3046,7 +3047,7 @@ TEST_F(ViewportTest, viewportWarnings1) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-1.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-1.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3069,7 +3070,7 @@ TEST_F(ViewportTest, viewportWarnings2) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-2.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3096,7 +3097,7 @@ TEST_F(ViewportTest, viewportWarnings3) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-3.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-3.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3125,7 +3126,7 @@ TEST_F(ViewportTest, viewportWarnings4) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-4.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-4.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3154,7 +3155,7 @@ TEST_F(ViewportTest, viewportWarnings5) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-5.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-5.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3184,7 +3185,7 @@ TEST_F(ViewportTest, viewportWarnings6) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-6.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-6.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3212,7 +3213,7 @@ TEST_F(ViewportTest, viewportWarnings7) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-7.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-7.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3228,7 +3229,7 @@ TEST_F(ViewportTest, viewportWarnings8) {
RegisterMockedHttpURLLoad("viewport/viewport-warnings-8.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-warnings-8.html", &web_frame_client,
nullptr, nullptr, SetViewportSettings);
@@ -3239,7 +3240,7 @@ TEST_F(ViewportTest, viewportWarnings8) {
EXPECT_EQ(0U, web_frame_client.messages.size());
}
-class ViewportClient : public FrameTestHelpers::TestWebViewClient {
+class ViewportClient : public frame_test_helpers::TestWebViewClient {
public:
ViewportClient() : device_scale_factor_(1.f) {}
void ConvertWindowToViewport(WebFloatRect* rect) override {
@@ -3261,7 +3262,7 @@ TEST_F(ViewportTest, viewportUseZoomForDSF1) {
client.set_device_scale_factor(3);
RegisterMockedHttpURLLoad("viewport/viewport-legacy-merge-quirk-1.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-merge-quirk-1.html", nullptr,
&client, nullptr, SetQuirkViewportSettings);
@@ -3288,7 +3289,7 @@ TEST_F(ViewportTest, viewportUseZoomForDSF2) {
client.set_device_scale_factor(3);
RegisterMockedHttpURLLoad("viewport/viewport-legacy-merge-quirk-2.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(
base_url_ + "viewport/viewport-legacy-merge-quirk-2.html", nullptr,
&client, nullptr, SetQuirkViewportSettings);
@@ -3318,7 +3319,7 @@ TEST_F(ViewportTest, viewportUseZoomForDSF3) {
client.set_device_scale_factor(3);
RegisterMockedHttpURLLoad("viewport/viewport-48.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-48.html",
nullptr, &client, nullptr,
SetViewportSettings);
@@ -3343,7 +3344,7 @@ TEST_F(ViewportTest, viewportUseZoomForDSF4) {
client.set_device_scale_factor(3);
RegisterMockedHttpURLLoad("viewport/viewport-39.html");
- FrameTestHelpers::WebViewHelper web_view_helper;
+ frame_test_helpers::WebViewHelper web_view_helper;
web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-39.html",
nullptr, &client, nullptr,
SetViewportSettings);
diff --git a/chromium/third_party/blink/renderer/core/paint/BUILD.gn b/chromium/third_party/blink/renderer/core/paint/BUILD.gn
index e5bd01849d3..4a8d0dfea01 100644
--- a/chromium/third_party/blink/renderer/core/paint/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/paint/BUILD.gn
@@ -178,8 +178,8 @@ blink_core_sources("paint") {
"paint_result.h",
"paint_timing.cc",
"paint_timing.h",
- "paint_tracker.cc",
- "paint_tracker.h",
+ "paint_timing_detector.cc",
+ "paint_timing_detector.h",
"pre_paint_tree_walk.cc",
"pre_paint_tree_walk.h",
"replaced_painter.cc",
diff --git a/chromium/third_party/blink/renderer/core/paint/README.md b/chromium/third_party/blink/renderer/core/paint/README.md
index 970e193bac6..714aa95842a 100644
--- a/chromium/third_party/blink/renderer/core/paint/README.md
+++ b/chromium/third_party/blink/renderer/core/paint/README.md
@@ -102,7 +102,9 @@ are treated in different ways during painting:
concept.
* Visual rect: the bounding box of all pixels that will be painted by a
- display item client.
+ [display item client](../../platform/graphics/paint/README.md#display-items).
+ It's in the space of the containing transform property node (see [Building
+ paint property trees](#building-paint-property-trees)).
* Isolation nodes/boundary: In certain situations, it is possible to put in
place a barrier that isolates a subtree from being affected by its
@@ -376,125 +378,7 @@ Layerization | PLC/CLM | PLC/CLM |
cc property tree builder | on | off | off
```
-## PaintInvalidation (Deprecated by [PrePaint](#PrePaint))
-
-Paint invalidation marks anything that need to be painted differently from the
-original cached painting.
-
-Paint invalidation is a document cycle stage after compositing update and before
-paint. During the previous stages, objects are marked for needing paint
-invalidation checking if needed by style change, layout change, compositing
-change, etc. In paint invalidation stage, we traverse the layout tree in
-pre-order, crossing frame boundaries, for marked subtrees and objects and send
-the following information to `GraphicsLayer`s and `PaintController`s:
-
-* invalidated display item clients: must invalidate all display item clients
- that will generate different display items.
-
-* paint invalidation rects: must cover all areas that will generate different
- pixels. They are generated based on visual rects of invalidated display item
- clients.
-
-### `PaintInvalidationState`
-
-`PaintInvalidationState` is an optimization used during the paint invalidation
-phase. Before the paint invalidation tree walk, a root `PaintInvalidationState`
-is created for the root `LayoutView`. During the tree walk, one
-`PaintInvalidationState` is created for each visited object based on the
-`PaintInvalidationState` passed from the parent object. It tracks the following
-information to provide O(1) complexity access to them if possible:
-
-* Paint invalidation container: Since as indicated by the definitions in
- [Glossaries](#other-glossaries), the paint invalidation container for
- stacked objects can differ from normal objects, we have to track both
- separately. Here is an example:
-
- <div style="overflow: scroll">
- <div id=A style="position: absolute"></div>
- <div id=B></div>
- </div>
-
- If the scroller is composited (for high-DPI screens for example), it is the
- paint invalidation container for div B, but not A.
-
-* Paint offset and clip rect: if possible, `PaintInvalidationState`
- accumulates paint offsets and overflow clipping rects from the paint
- invalidation container to provide O(1) complexity to map a point or a rect
- in current object's local space to paint invalidation container's space.
- Because locations of objects are determined by their containing blocks, and
- the containing block for absolute-position objects differs from
- non-absolute, we track paint offsets and overflow clipping rects for
- absolute-position objects separately.
-
-In cases that accurate accumulation of paint offsets and clipping rects is
-impossible, we will fall back to slow-path using
-`LayoutObject::localToAncestorPoint()` or
-`LayoutObject::mapToVisualRectInAncestorSpace()`. This includes the following
-cases:
-
-* An object has transform related property, is multi-column or has flipped
- blocks writing-mode, causing we can't simply accumulate paint offset for
- mapping a local rect to paint invalidation container;
-
-* An object has has filter (including filter induced by reflection), which
- needs to expand visual rect for descendants, because currently we don't
- include and filter extents into visual overflow;
-
-* For a fixed-position object we calculate its offset using
- `LayoutObject::localToAncestorPoint()`, but map for its descendants in
- fast-path if no other things prevent us from doing this;
-
-* Because we track paint offset from the normal paint invalidation container
- only, if we are going to use
- `m_paintInvalidationContainerForStackedContents` and it's different from the
- normal paint invalidation container, we have to force slow-path because the
- accumulated paint offset is not usable;
-
-* We also stop to track paint offset and clipping rect for absolute-position
- objects when `m_paintInvalidationContainerForStackedContents` becomes
- different from `m_paintInvalidationContainer`.
-
-### Paint invalidation of texts
-
-Texts are painted by `InlineTextBoxPainter` using `InlineTextBox` as display
-item client. Text backgrounds and masks are painted by `InlineTextFlowPainter`
-using `InlineFlowBox` as display item client. We should invalidate these display
-item clients when their painting will change.
-
-`LayoutInline`s and `LayoutText`s are marked for full paint invalidation if
-needed when new style is set on them. During paint invalidation, we invalidate
-the `InlineFlowBox`s directly contained by the `LayoutInline` in
-`LayoutInline::InvalidateDisplayItemClients()` and `InlineTextBox`s contained by
-the `LayoutText` in `LayoutText::InvalidateDisplayItemClients()`. We don't need
-to traverse into the subtree of `InlineFlowBox`s in
-`LayoutInline::InvalidateDisplayItemClients()` because the descendant
-`InlineFlowBox`s and `InlineTextBox`s will be handled by their owning
-`LayoutInline`s and `LayoutText`s, respectively, when changed style is propagated.
-
-### Specialty of `::first-line`
-
-`::first-line` pseudo style dynamically applies to all `InlineBox`'s in the
-first line in the block having `::first-line` style. The actual applied style is
-computed from the `::first-line` style and other applicable styles.
-
-If the first line contains any `LayoutInline`, we compute the style from the
-`::first-line` style and the style of the `LayoutInline` and apply the computed
-style to the first line part of the `LayoutInline`. In Blink's style
-implementation, the combined first line style of `LayoutInline` is identified
-with `FIRST_LINE_INHERITED` pseudo ID.
-
-The normal paint invalidation of texts doesn't work for first line because
-* `ComputedStyle::VisualInvalidationDiff()` can't detect first line style
- changes;
-* The normal paint invalidation is based on whole LayoutObject's, not aware of
- the first line.
-
-We have a special path for first line style change: the style system informs the
-layout system when the computed first-line style changes through
-`LayoutObject::FirstLineStyleDidChange()`. When this happens, we invalidate all
-`InlineBox`es in the first line.
-
-## PrePaint (Slimming paint invalidation/v2 only)
+## PrePaint
[`PrePaintTreeWalk`](pre_paint_tree_walk.h)
During `InPrePaint` document lifecycle state, this class is called to walk the
@@ -626,12 +510,82 @@ for a much more detail about multicolumn/pagination.
### Paint invalidation
[`PaintInvalidator`](paint_invalidator.h)
-This class replaces [`PaintInvalidationState`] for SlimmingPaintInvalidation.
-The main difference is that in PaintInvalidator, visual rects and locations
-are computed by `GeometryMapper`(../../platform/graphics/paint/geometry_mapper.h),
-based on paint properties produced by `PaintPropertyTreeBuilder`.
+Paint invalidator marks anything that need to be painted differently from the
+original cached painting.
+
+During the document lifecycle stages prior to PrePaint, objects are marked for
+needing paint invalidation checking if needed by style change, layout change,
+compositing change, etc. In PrePaint stage, we traverse the layout tree in
+pre-order, crossing frame boundaries, for marked subtrees and objects and
+invalidate display item clients that will generate different display items.
+
+At the beginning of the PrePaint tree walk, a root `PaintInvalidatorContext`
+is created for the root `LayoutView`. During the tree walk, one
+`PaintInvalidatorContext` is created for each visited object based on the
+`PaintInvalidatorContext` passed from the parent object. It tracks the following
+information to provide O(1) complexity access to them if possible:
+
+* Paint invalidation container (Slimming Paint v1 only): Since as indicated by
+ the definitions in [Glossaries](#other-glossaries), the paint invalidation
+ container for stacked objects can differ from normal objects, we have to
+ track both separately. Here is an example:
+
+ <div style="overflow: scroll">
+ <div id=A style="position: absolute"></div>
+ <div id=B></div>
+ </div>
+
+ If the scroller is composited (for high-DPI screens for example), it is the
+ paint invalidation container for div B, but not A.
+
+* Painting layer: the layer which will initiate painting of the current
+ object. It's the same value as `LayoutObject::PaintingLayer()`.
+
+`PaintInvalidator`[PaintInvalidator.h] initializes `PaintInvalidatorContext`
+for the current object, then calls `LayoutObject::InvalidatePaint()` which
+calls the object's paint invalidator (e.g. `BoxPaintInvalidator`) to complete
+paint invalidation of the object.
+
+#### Paint invalidation of text
+
+Text is painted by `InlineTextBoxPainter` using `InlineTextBox` as display
+item client. Text backgrounds and masks are painted by `InlineTextFlowPainter`
+using `InlineFlowBox` as display item client. We should invalidate these display
+item clients when their painting will change.
+
+`LayoutInline`s and `LayoutText`s are marked for full paint invalidation if
+needed when new style is set on them. During paint invalidation, we invalidate
+the `InlineFlowBox`s directly contained by the `LayoutInline` in
+`LayoutInline::InvalidateDisplayItemClients()` and `InlineTextBox`s contained by
+the `LayoutText` in `LayoutText::InvalidateDisplayItemClients()`. We don't need
+to traverse into the subtree of `InlineFlowBox`s in
+`LayoutInline::InvalidateDisplayItemClients()` because the descendant
+`InlineFlowBox`s and `InlineTextBox`s will be handled by their owning
+`LayoutInline`s and `LayoutText`s, respectively, when changed style is
+propagated.
+
+#### Specialty of `::first-line`
+
+`::first-line` pseudo style dynamically applies to all `InlineBox`'s in the
+first line in the block having `::first-line` style. The actual applied style is
+computed from the `::first-line` style and other applicable styles.
+
+If the first line contains any `LayoutInline`, we compute the style from the
+`::first-line` style and the style of the `LayoutInline` and apply the computed
+style to the first line part of the `LayoutInline`. In Blink's style
+implementation, the combined first line style of `LayoutInline` is identified
+with `FIRST_LINE_INHERITED` pseudo ID.
+
+The normal paint invalidation of texts doesn't work for first line because
+* `ComputedStyle::VisualInvalidationDiff()` can't detect first line style
+ changes;
+* The normal paint invalidation is based on whole LayoutObject's, not aware of
+ the first line.
-TODO(wangxianzhu): Combine documentation of PaintInvalidation phase into here.
+We have a special path for first line style change: the style system informs the
+layout system when the computed first-line style changes through
+`LayoutObject::FirstLineStyleDidChange()`. When this happens, we invalidate all
+`InlineBox`es in the first line.
## Paint
diff --git a/chromium/third_party/blink/renderer/core/paint/background_image_geometry.cc b/chromium/third_party/blink/renderer/core/paint/background_image_geometry.cc
index 53351c425ad..7533c6b7600 100644
--- a/chromium/third_party/blink/renderer/core/paint/background_image_geometry.cc
+++ b/chromium/third_party/blink/renderer/core/paint/background_image_geometry.cc
@@ -15,7 +15,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/border_edge.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
@@ -44,6 +44,13 @@ bool FixedBackgroundPaintsInLocalCoordinates(
const LayoutView& view = ToLayoutView(obj);
+ // TODO(wangxianzhu): For SPv2, inline this function into
+ // FixedBackgroundPaintsInLocalCoordinates().
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ return view.GetBackgroundPaintLocation() !=
+ kBackgroundPaintInScrollingContents;
+ }
+
if (global_paint_flags & kGlobalPaintFlattenCompositingLayers)
return false;
@@ -368,9 +375,14 @@ LayoutRect FixedAttachmentPositioningArea(const LayoutBoxModelObject& obj,
// The LayoutView is the only object that can paint a fixed background into
// its scrolling contents layer, so it gets a special adjustment here.
if (obj.IsLayoutView()) {
- auto* mapping = obj.Layer()->GetCompositedLayerMapping();
- if (mapping && mapping->BackgroundPaintsOntoScrollingContentsLayer())
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ DCHECK_EQ(obj.GetBackgroundPaintLocation(),
+ kBackgroundPaintInScrollingContents);
rect.SetLocation(IntPoint(ToLayoutView(obj).ScrolledContentOffset()));
+ } else if (auto* mapping = obj.Layer()->GetCompositedLayerMapping()) {
+ if (mapping->BackgroundPaintsOntoScrollingContentsLayer())
+ rect.SetLocation(IntPoint(ToLayoutView(obj).ScrolledContentOffset()));
+ }
}
rect.MoveBy(AccumulatedScrollOffsetForFixedBackground(obj, container));
@@ -665,9 +677,12 @@ void BackgroundImageGeometry::ComputePositioningArea(
// Apply the adjustments.
snapped_dest_rect_ = unsnapped_dest_rect_;
snapped_dest_rect_.Contract(snapped_dest_adjust);
+ snapped_dest_rect_ = LayoutRect(PixelSnappedIntRect(snapped_dest_rect_));
unsnapped_dest_rect_.Contract(unsnapped_dest_adjust);
snapped_positioning_area = unsnapped_positioning_area;
snapped_positioning_area.Contract(snapped_box_outset);
+ snapped_positioning_area =
+ LayoutRect(PixelSnappedIntRect(snapped_positioning_area));
unsnapped_positioning_area.Contract(unsnapped_box_outset);
// Offset of the positioning area from the corner of the
@@ -738,12 +753,12 @@ void BackgroundImageGeometry::CalculateFillTileSize(
// an intrinsic ratio or size.
tile_size_.SetWidth(positioning_area_size.Width());
} else if (image_intrinsic_size.Height()) {
- LayoutUnit adjusted_width = image_intrinsic_size.Width() *
- tile_size_.Height() /
- image_intrinsic_size.Height();
+ float adjusted_width = image_intrinsic_size.Width().ToFloat() /
+ image_intrinsic_size.Height().ToFloat() *
+ tile_size_.Height().ToFloat();
if (image_intrinsic_size.Width() >= 1 && adjusted_width < 1)
- adjusted_width = LayoutUnit(1);
- tile_size_.SetWidth(adjusted_width);
+ adjusted_width = 1;
+ tile_size_.SetWidth(LayoutUnit(adjusted_width));
}
} else if (!layer_width.IsAuto() && layer_height.IsAuto()) {
if (image->ImageHasRelativeSize()) {
@@ -751,12 +766,12 @@ void BackgroundImageGeometry::CalculateFillTileSize(
// an intrinsic ratio or size.
tile_size_.SetHeight(positioning_area_size.Height());
} else if (image_intrinsic_size.Width()) {
- LayoutUnit adjusted_height = image_intrinsic_size.Height() *
- tile_size_.Width() /
- image_intrinsic_size.Width();
+ float adjusted_height = image_intrinsic_size.Height().ToFloat() /
+ image_intrinsic_size.Width().ToFloat() *
+ tile_size_.Width().ToFloat();
if (image_intrinsic_size.Height() >= 1 && adjusted_height < 1)
- adjusted_height = LayoutUnit(1);
- tile_size_.SetHeight(adjusted_height);
+ adjusted_height = 1;
+ tile_size_.SetHeight(LayoutUnit(adjusted_height));
}
} else if (layer_width.IsAuto() && layer_height.IsAuto()) {
// If both width and height are auto, use the image's intrinsic size.
diff --git a/chromium/third_party/blink/renderer/core/paint/block_painter.cc b/chromium/third_party/blink/renderer/core/paint/block_painter.cc
index fe5ceef86f8..193441f7626 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/block_painter.cc
@@ -39,7 +39,32 @@ void BlockPainter::Paint(const PaintInfo& paint_info) {
local_paint_info.phase = PaintPhase::kDescendantOutlinesOnly;
} else if (ShouldPaintSelfBlockBackground(original_phase)) {
local_paint_info.phase = PaintPhase::kSelfBlockBackgroundOnly;
- layout_block_.PaintObject(local_paint_info, paint_offset);
+ // With SlimmingPaintV2 we need to call PaintObject twice: once for the
+ // background painting that does not scroll, and a second time for the
+ // background painting that scrolls.
+ // Without SlimmingPaintV2, this happens as the main graphics layer
+ // paints the background, and then the scrolling contents graphics layer
+ // paints the background.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ auto paint_location = layout_block_.GetBackgroundPaintLocation();
+ if (!(paint_location & kBackgroundPaintInGraphicsLayer))
+ local_paint_info.SetSkipsBackground(true);
+ layout_block_.PaintObject(local_paint_info, paint_offset);
+ local_paint_info.SetSkipsBackground(false);
+
+ // Record the scroll hit test after the non-scrolling background so
+ // background squashing is not affected. Hit test order would be
+ // equivalent if this were immediately before the background.
+ PaintScrollHitTestDisplayItem(paint_info);
+
+ if (paint_location & kBackgroundPaintInScrollingContents) {
+ local_paint_info.SetIsPaintingScrollingBackground(true);
+ layout_block_.PaintObject(local_paint_info, paint_offset);
+ local_paint_info.SetIsPaintingScrollingBackground(false);
+ }
+ } else {
+ layout_block_.PaintObject(local_paint_info, paint_offset);
+ }
if (ShouldPaintDescendantBlockBackgrounds(original_phase))
local_paint_info.phase = PaintPhase::kDescendantBlockBackgroundsOnly;
}
@@ -201,30 +226,6 @@ void BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) {
}
}
-// TODO(pdr): Non-blocks also need to paint the hit test display item. Move this
-// to a more central place such as BoxPainter.
-void BlockPainter::RecordHitTestData(const PaintInfo& paint_info,
- const LayoutPoint& paint_offset) {
- // Hit test display items are only needed for compositing. This flag is used
- // for for printing and drag images which do not need hit testing.
- if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
- return;
-
- auto touch_action = layout_block_.EffectiveWhitelistedTouchAction();
- if (touch_action == TouchAction::kTouchActionAuto)
- return;
-
- // TODO(pdr): If we are painting the background into the scrolling contents
- // layer, we need to use the overflow rect instead of the border box rect. We
- // may want to move the call to RecordHitTestRect into
- // BoxPainter::PaintBoxDecorationBackgroundWithRect and share the logic
- // the background painting code already uses.
- auto rect = layout_block_.BorderBoxRect();
- rect.MoveBy(paint_offset);
- HitTestData::RecordHitTestRect(paint_info.context, layout_block_,
- HitTestRect(rect, touch_action));
-}
-
DISABLE_CFI_PERF
void BlockPainter::PaintObject(const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
@@ -251,21 +252,8 @@ void BlockPainter::PaintObject(const PaintInfo& paint_info,
// of the current object and non-self-painting descendants, or 2.
// kSelfBlockBackgroundOnly - Paint background of the current object only),
// paint those now. This is steps #1, 2, and 4 of the CSS spec (see above).
- if (ShouldPaintSelfBlockBackground(paint_phase)) {
- // Paint the background if we're visible and this block has a box decoration
- // (background, border, appearance, or box shadow).
- if (layout_block_.StyleRef().Visibility() == EVisibility::kVisible &&
- layout_block_.HasBoxDecorationBackground()) {
- layout_block_.PaintBoxDecorationBackground(paint_info, paint_offset);
- }
- if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled())
- RecordHitTestData(paint_info, paint_offset);
- // Record the scroll hit test after the background so background squashing
- // is not affected. Hit test order would be equivalent if this were
- // immediately before the background.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- PaintScrollHitTestDisplayItem(paint_info);
- }
+ if (ShouldPaintSelfBlockBackground(paint_phase))
+ layout_block_.PaintBoxDecorationBackground(paint_info, paint_offset);
// If we're in any phase except *just* the self (outline or background) or a
// mask, paint children now. This is step #5, 7, 8, and 9 of the CSS spec (see
diff --git a/chromium/third_party/blink/renderer/core/paint/block_painter.h b/chromium/third_party/blink/renderer/core/paint/block_painter.h
index 175e962d18c..e16f0be0a7a 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/block_painter.h
@@ -40,10 +40,6 @@ class BlockPainter {
// Paint scroll hit test placeholders in the correct paint order (see:
// ScrollHitTestDisplayItem.h).
void PaintScrollHitTestDisplayItem(const PaintInfo&);
- // Paint a hit test display item and record hit test data. This should be
- // called in the background paint phase even if there is no other painted
- // content.
- void RecordHitTestData(const PaintInfo&, const LayoutPoint& paint_offset);
void PaintBlockFlowContents(const PaintInfo&, const LayoutPoint&);
void PaintCarets(const PaintInfo&, const LayoutPoint& paint_offset);
diff --git a/chromium/third_party/blink/renderer/core/paint/block_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/block_painter_test.cc
index ea569aa7e3c..180c207955b 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/block_painter_test.cc
@@ -4,14 +4,18 @@
#include "third_party/blink/renderer/core/paint/block_painter.h"
-#include <gtest/gtest.h>
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_controller_paint_test.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_chunk.h"
#include "third_party/blink/renderer/platform/graphics/paint/scroll_hit_test_display_item.h"
+using testing::ElementsAre;
+
namespace blink {
using BlockPainterTest = PaintControllerPaintTest;
@@ -32,59 +36,72 @@ TEST_P(BlockPainterTest, ScrollHitTestProperties) {
</div>
)HTML");
- auto& container = *GetLayoutObjectByElementId("container");
+ auto& container = ToLayoutBlock(*GetLayoutObjectByElementId("container"));
auto& child = *GetLayoutObjectByElementId("child");
// The scroll hit test should be after the container background but before the
// scrolled contents.
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(container, kBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(child, kBackgroundType));
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(4u, paint_chunks.size());
- const auto& root_chunk = RootPaintController().PaintChunks()[0];
- EXPECT_EQ(GetLayoutView().Layer(), &root_chunk.id.client);
- const auto& container_chunk = RootPaintController().PaintChunks()[1];
- EXPECT_EQ(ToLayoutBoxModelObject(container).Layer(),
- &container_chunk.id.client);
- // The container's scroll hit test.
- const auto& scroll_hit_test_chunk = RootPaintController().PaintChunks()[2];
- EXPECT_EQ(&container, &scroll_hit_test_chunk.id.client);
- EXPECT_EQ(kScrollHitTestType, scroll_hit_test_chunk.id.type);
- // The scrolled contents.
- const auto& contents_chunk = RootPaintController().PaintChunks()[3];
- EXPECT_EQ(&container, &contents_chunk.id.client);
+ EXPECT_EQ(
+ kBackgroundPaintInGraphicsLayer | kBackgroundPaintInScrollingContents,
+ container.GetBackgroundPaintLocation());
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&container, kBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&container.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient(),
+ kBackgroundType),
+ IsSameId(&child, kBackgroundType)));
+
+ const auto& paint_chunks = RootPaintController().PaintChunks();
+ EXPECT_THAT(
+ paint_chunks,
+ ElementsAre(
+ IsPaintChunk(0, 1,
+ PaintChunk::Id(ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ GetLayoutView().FirstFragment().ContentsProperties()),
+ IsPaintChunk(1, 2,
+ PaintChunk::Id(*container.Layer(),
+ kNonScrollingBackgroundChunkType),
+ container.FirstFragment().LocalBorderBoxProperties()),
+ IsPaintChunk(2, 3, PaintChunk::Id(container, kScrollHitTestType),
+ container.FirstFragment().LocalBorderBoxProperties()),
+ IsPaintChunk(3, 5,
+ PaintChunk::Id(container, kScrollingBackgroundChunkType),
+ container.FirstFragment().ContentsProperties())));
// The document should not scroll so there should be no scroll offset
// transform.
- auto* root_transform = root_chunk.properties.Transform();
+ const auto* root_transform = paint_chunks[0].properties.Transform();
EXPECT_EQ(nullptr, root_transform->ScrollNode());
// The container's background chunk should not scroll and therefore should use
// the root transform. Its local transform is actually a paint offset
// transform.
- auto* container_transform = container_chunk.properties.Transform()->Parent();
- EXPECT_EQ(root_transform, container_transform);
+ const auto* container_transform = paint_chunks[1].properties.Transform();
+ EXPECT_EQ(root_transform, container_transform->Parent());
EXPECT_EQ(nullptr, container_transform->ScrollNode());
// The scroll hit test should not be scrolled and should not be clipped.
// Its local transform is actually a paint offset transform.
- auto* scroll_hit_test_transform =
- scroll_hit_test_chunk.properties.Transform()->Parent();
+ const auto& scroll_hit_test_chunk = paint_chunks[2];
+ const auto* scroll_hit_test_transform =
+ scroll_hit_test_chunk.properties.Transform();
EXPECT_EQ(nullptr, scroll_hit_test_transform->ScrollNode());
- EXPECT_EQ(root_transform, scroll_hit_test_transform);
- auto* scroll_hit_test_clip = scroll_hit_test_chunk.properties.Clip();
+ EXPECT_EQ(root_transform, scroll_hit_test_transform->Parent());
+ const auto* scroll_hit_test_clip = scroll_hit_test_chunk.properties.Clip();
EXPECT_EQ(FloatRect(0, 0, 800, 600), scroll_hit_test_clip->ClipRect().Rect());
// The scrolled contents should be scrolled and clipped.
- auto* contents_transform = contents_chunk.properties.Transform();
- auto* contents_scroll = contents_transform->ScrollNode();
+ const auto& contents_chunk = RootPaintController().PaintChunks()[3];
+ const auto* contents_transform = contents_chunk.properties.Transform();
+ const auto* contents_scroll = contents_transform->ScrollNode();
EXPECT_EQ(IntSize(200, 300), contents_scroll->ContentsSize());
EXPECT_EQ(IntRect(0, 0, 200, 200), contents_scroll->ContainerRect());
- auto* contents_clip = contents_chunk.properties.Clip();
+ const auto* contents_clip = contents_chunk.properties.Clip();
EXPECT_EQ(FloatRect(0, 0, 200, 200), contents_clip->ClipRect().Rect());
// The scroll hit test display item maintains a reference to a scroll offset
@@ -107,42 +124,52 @@ TEST_P(BlockPainterTest, FrameScrollHitTestProperties) {
<div id='child'></div>
)HTML");
- auto& html = *GetDocument().documentElement()->GetLayoutObject();
+ auto& html =
+ ToLayoutBlock(*GetDocument().documentElement()->GetLayoutObject());
auto& child = *GetLayoutObjectByElementId("child");
// The scroll hit test should be after the document background but before the
// scrolled contents.
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(GetLayoutView(), kScrollHitTestType),
- TestDisplayItem(child, kBackgroundType));
-
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(3u, paint_chunks.size());
- const auto& root_chunk = RootPaintController().PaintChunks()[0];
- EXPECT_EQ(GetLayoutView().Layer(), &root_chunk.id.client);
- const auto& scroll_hit_test_chunk = RootPaintController().PaintChunks()[1];
- EXPECT_EQ(&GetLayoutView(), &scroll_hit_test_chunk.id.client);
- EXPECT_EQ(kScrollHitTestType, scroll_hit_test_chunk.id.type);
- // The scrolled contents.
- const auto& contents_chunk = RootPaintController().PaintChunks()[2];
- EXPECT_EQ(ToLayoutBoxModelObject(html).Layer(), &contents_chunk.id.client);
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&GetLayoutView(), kScrollHitTestType),
+ IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&child, kBackgroundType)));
+
+ const auto& paint_chunks = RootPaintController().PaintChunks();
+ EXPECT_THAT(
+ paint_chunks,
+ ElementsAre(
+ IsPaintChunk(
+ 0, 1,
+ PaintChunk::Id(*GetLayoutView().Layer(),
+ DisplayItem::kLayerChunkBackground),
+ GetLayoutView().FirstFragment().LocalBorderBoxProperties()),
+ IsPaintChunk(1, 2,
+ PaintChunk::Id(ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ GetLayoutView().FirstFragment().ContentsProperties()),
+ IsPaintChunk(2, 3,
+ PaintChunk::Id(*html.Layer(),
+ kNonScrollingContentsBackgroundChunkType),
+ html.FirstFragment().ContentsProperties())));
// The scroll hit test should not be scrolled and should not be clipped.
- auto* scroll_hit_test_transform =
+ const auto& scroll_hit_test_chunk = RootPaintController().PaintChunks()[0];
+ const auto* scroll_hit_test_transform =
scroll_hit_test_chunk.properties.Transform();
EXPECT_EQ(nullptr, scroll_hit_test_transform->ScrollNode());
- auto* scroll_hit_test_clip = scroll_hit_test_chunk.properties.Clip();
+ const auto* scroll_hit_test_clip = scroll_hit_test_chunk.properties.Clip();
EXPECT_EQ(FloatRect(LayoutRect::InfiniteIntRect()),
scroll_hit_test_clip->ClipRect().Rect());
// The scrolled contents should be scrolled and clipped.
- auto* contents_transform = contents_chunk.properties.Transform();
- auto* contents_scroll = contents_transform->ScrollNode();
+ const auto& contents_chunk = RootPaintController().PaintChunks()[2];
+ const auto* contents_transform = contents_chunk.properties.Transform();
+ const auto* contents_scroll = contents_transform->ScrollNode();
EXPECT_EQ(IntSize(800, 2000), contents_scroll->ContentsSize());
EXPECT_EQ(IntRect(0, 0, 800, 600), contents_scroll->ContainerRect());
- auto* contents_clip = contents_chunk.properties.Clip();
+ const auto* contents_clip = contents_chunk.properties.Clip();
EXPECT_EQ(FloatRect(0, 0, 800, 600), contents_clip->ClipRect().Rect());
// The scroll hit test display item maintains a reference to a scroll offset
@@ -173,6 +200,7 @@ TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectsWithoutPaint) {
.touchActionNone { touch-action: none; }
#childVisible { width: 200px; height: 25px; }
#childHidden { width: 200px; height: 30px; visibility: hidden; }
+ #childDisplayNone { width: 200px; height: 30px; display: none; }
</style>
<div id='parent'>
<div id='childVisible'></div>
@@ -182,33 +210,92 @@ TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectsWithoutPaint) {
// Initially there should be no hit test display items because there is no
// touch action.
- auto* scrolling_client = GetLayoutView().Layer()->GraphicsLayerBacking();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType));
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType)));
// Add a touch action to parent and ensure that hit test display items are
- // created for both the parent and child.
+ // created for both the parent and the visible child.
auto* parent_element = GetElementById("parent");
- parent_element->setAttribute(HTMLNames::classAttr, "touchActionNone");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent_element->setAttribute(html_names::kClassAttr, "touchActionNone");
+ UpdateAllLifecyclePhasesForTest();
auto* parent = GetLayoutObjectByElementId("parent");
- auto* childVisible = GetLayoutObjectByElementId("childVisible");
- auto* childHidden = GetLayoutObjectByElementId("childHidden");
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*parent, DisplayItem::kHitTest),
- TestDisplayItem(*childVisible, DisplayItem::kHitTest),
- TestDisplayItem(*childHidden, DisplayItem::kHitTest));
+ auto* child_visible = GetLayoutObjectByElementId("childVisible");
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(parent, DisplayItem::kHitTest),
+ IsSameId(child_visible, DisplayItem::kHitTest)));
// Remove the touch action from parent and ensure no hit test display items
// are left.
- parent_element->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType));
+ parent_element->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType)));
+}
+
+TEST_F(BlockPainterTestWithPaintTouchAction,
+ TouchActionRectSubsequenceCaching) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ body { margin: 0; }
+ #touchaction {
+ width: 100px;
+ height: 100px;
+ touch-action: none;
+ }
+ #sibling {
+ width: 100px;
+ height: 100px;
+ background: blue;
+ }
+ </style>
+ <div id='touchaction'></div>
+ )HTML");
+
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
+ const auto* touchaction = GetLayoutObjectByElementId("touchaction");
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(touchaction, DisplayItem::kHitTest)));
+
+ const auto& hit_test_client = *touchaction->EnclosingLayer();
+ EXPECT_SUBSEQUENCE(hit_test_client, 1, 2);
+
+ PaintChunk::Id root_chunk_id(scrolling_client, kDocumentBackgroundType);
+ auto root_chunk_properties =
+ GetLayoutView().FirstFragment().ContentsProperties();
+
+ PaintChunk::Id hit_test_chunk_id(hit_test_client,
+ kNonScrollingBackgroundChunkType);
+ auto hit_test_chunk_properties = touchaction->EnclosingLayer()
+ ->GetLayoutObject()
+ .FirstFragment()
+ .ContentsProperties();
+ HitTestData hit_test_data;
+ hit_test_data.touch_action_rects.emplace_back(LayoutRect(0, 0, 100, 100));
+
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties),
+ IsPaintChunk(1, 2, hit_test_chunk_id,
+ hit_test_chunk_properties, hit_test_data)));
+
+ // Trigger a repaint with the whole HTML subsequence cached.
+ GetLayoutView().Layer()->SetNeedsRepaint();
+ EXPECT_TRUE(PaintWithoutCommit());
+ EXPECT_EQ(2, NumCachedNewItems());
+ CommitAndFinishCycle();
+
+ EXPECT_SUBSEQUENCE(hit_test_client, 1, 2);
+
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties),
+ IsPaintChunk(1, 2, hit_test_chunk_id,
+ hit_test_chunk_properties, hit_test_data)));
}
TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectPaintCaching) {
@@ -230,55 +317,104 @@ TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectPaintCaching) {
<div id='sibling'></div>
)HTML");
- auto* scrolling_client = GetLayoutView().Layer()->GraphicsLayerBacking();
- auto* touchaction_element = GetElementById("touchaction");
- auto* touchaction = touchaction_element->GetLayoutObject();
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
+ const auto* touchaction = GetLayoutObjectByElementId("touchaction");
auto* sibling_element = GetElementById("sibling");
- auto* sibling = sibling_element->GetLayoutObject();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*touchaction, DisplayItem::kHitTest),
- TestDisplayItem(*sibling, kBackgroundType));
-
- {
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(paint_chunks.size(), 2u);
- auto& background_chunk = paint_chunks[0];
- EXPECT_EQ(nullptr, background_chunk.GetHitTestData());
- auto& hit_test_chunk = paint_chunks[1];
- DCHECK(hit_test_chunk.GetHitTestData());
- EXPECT_EQ(1u, hit_test_chunk.GetHitTestData()->touch_action_rects.size());
- auto& touch_action_rect =
- hit_test_chunk.GetHitTestData()->touch_action_rects[0];
- EXPECT_EQ(LayoutRect(0, 0, 100, 100), touch_action_rect.rect);
- EXPECT_EQ(TouchAction::kTouchActionNone,
- touch_action_rect.whitelisted_touch_action);
- }
-
- sibling_element->setAttribute(HTMLNames::styleAttr, "background: green;");
+ const auto* sibling = sibling_element->GetLayoutObject();
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(touchaction, DisplayItem::kHitTest),
+ IsSameId(sibling, kBackgroundType)));
+
+ PaintChunk::Id root_chunk_id(scrolling_client, kDocumentBackgroundType);
+ auto root_chunk_properties =
+ GetLayoutView().FirstFragment().ContentsProperties();
+
+ PaintChunk::Id hit_test_chunk_id(*touchaction->EnclosingLayer(),
+ kNonScrollingBackgroundChunkType);
+ auto hit_test_chunk_properties = touchaction->EnclosingLayer()
+ ->GetLayoutObject()
+ .FirstFragment()
+ .ContentsProperties();
+ HitTestData hit_test_data;
+ hit_test_data.touch_action_rects.emplace_back(LayoutRect(0, 0, 100, 100));
+
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties),
+ IsPaintChunk(1, 3, hit_test_chunk_id,
+ hit_test_chunk_properties, hit_test_data)));
+
+ sibling_element->setAttribute(html_names::kStyleAttr, "background: green;");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(PaintWithoutCommit());
// Only the background display item of the sibling should be invalidated.
EXPECT_EQ(2, NumCachedNewItems());
CommitAndFinishCycle();
- {
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(paint_chunks.size(), 2u);
- auto& background_chunk = paint_chunks[0];
- EXPECT_EQ(nullptr, background_chunk.GetHitTestData());
- auto& hit_test_chunk = paint_chunks[1];
- DCHECK(hit_test_chunk.GetHitTestData());
- EXPECT_EQ(1u, hit_test_chunk.GetHitTestData()->touch_action_rects.size());
- auto& touch_action_rect =
- hit_test_chunk.GetHitTestData()->touch_action_rects[0];
- EXPECT_EQ(LayoutRect(0, 0, 100, 100), touch_action_rect.rect);
- EXPECT_EQ(TouchAction::kTouchActionNone,
- touch_action_rect.whitelisted_touch_action);
- }
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties),
+ IsPaintChunk(1, 3, hit_test_chunk_id,
+ hit_test_chunk_properties, hit_test_data)));
+}
+
+TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectScrollingContents) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ body { margin: 0; }
+ #scroller {
+ width: 100px;
+ height: 100px;
+ overflow: scroll;
+ touch-action: none;
+ will-change: transform;
+ background-color: blue;
+ }
+ #child {
+ width: 10px;
+ height: 400px;
+ }
+ </style>
+ <div id='scroller'>
+ <div id='child'></div>
+ </div>
+ )HTML");
+
+ const auto& root_client = GetLayoutView()
+ .GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
+ auto* scroller_element = GetElementById("scroller");
+ auto* scroller = ToLayoutBoxModelObject(scroller_element->GetLayoutObject());
+ const auto& scroller_client =
+ scroller->GetScrollableArea()->GetScrollingBackgroundDisplayItemClient();
+ auto* child_element = GetElementById("child");
+ auto* child = child_element->GetLayoutObject();
+ auto& non_scroller_paint_controller = RootPaintController();
+ auto& scroller_paint_controller = scroller->GetScrollableArea()
+ ->Layer()
+ ->GraphicsLayerBacking()
+ ->GetPaintController();
+ EXPECT_THAT(scroller_paint_controller.GetDisplayItemList(),
+ ElementsAre(IsSameId(&scroller_client, kBackgroundType),
+ IsSameId(&scroller_client, DisplayItem::kHitTest),
+ IsSameId(child, DisplayItem::kHitTest)));
+ HitTestData hit_test_data;
+ hit_test_data.touch_action_rects.emplace_back(LayoutRect(0, 0, 100, 400));
+ hit_test_data.touch_action_rects.emplace_back(LayoutRect(0, 0, 10, 400));
+ EXPECT_THAT(
+ scroller_paint_controller.PaintChunks(),
+ ElementsAre(IsPaintChunk(
+ 0, 3, PaintChunk::Id(*scroller, kScrollingBackgroundChunkType),
+ scroller->FirstFragment().ContentsProperties(), hit_test_data)));
+
+ EXPECT_THAT(non_scroller_paint_controller.GetDisplayItemList(),
+ ElementsAre(IsSameId(&root_client, kDocumentBackgroundType)));
+ EXPECT_THAT(non_scroller_paint_controller.PaintChunks(),
+ ElementsAre(IsPaintChunk(
+ 0, 1, PaintChunk::Id(root_client, kDocumentBackgroundType),
+ GetLayoutView().FirstFragment().ContentsProperties())));
}
TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectPaintChunkChanges) {
@@ -293,55 +429,51 @@ TEST_F(BlockPainterTestWithPaintTouchAction, TouchActionRectPaintChunkChanges) {
<div id='touchaction'></div>
)HTML");
- auto* scrolling_client = GetLayoutView().Layer()->GraphicsLayerBacking();
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
auto* touchaction_element = GetElementById("touchaction");
auto* touchaction = touchaction_element->GetLayoutObject();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType));
-
- {
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(paint_chunks.size(), 1u);
- EXPECT_EQ(nullptr, paint_chunks[0].GetHitTestData());
- }
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType)));
- touchaction_element->setAttribute(HTMLNames::styleAttr,
- "touch-action: none;");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*touchaction, DisplayItem::kHitTest));
-
- {
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(paint_chunks.size(), 2u);
- auto& background_chunk = paint_chunks[0];
- EXPECT_EQ(nullptr, background_chunk.GetHitTestData());
- auto& hit_test_chunk = paint_chunks[1];
- DCHECK(hit_test_chunk.GetHitTestData());
- EXPECT_EQ(1u, hit_test_chunk.GetHitTestData()->touch_action_rects.size());
- auto& touch_action_rect =
- hit_test_chunk.GetHitTestData()->touch_action_rects[0];
- EXPECT_EQ(LayoutRect(0, 0, 100, 100), touch_action_rect.rect);
- EXPECT_EQ(TouchAction::kTouchActionNone,
- touch_action_rect.whitelisted_touch_action);
- }
+ PaintChunk::Id root_chunk_id(scrolling_client, kDocumentBackgroundType);
+ auto root_chunk_properties =
+ GetLayoutView().FirstFragment().ContentsProperties();
- touchaction_element->removeAttribute(HTMLNames::styleAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType));
- {
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(paint_chunks.size(), 1u);
- EXPECT_EQ(nullptr, paint_chunks[0].GetHitTestData());
- }
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties)));
+
+ touchaction_element->setAttribute(html_names::kStyleAttr,
+ "touch-action: none;");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(touchaction, DisplayItem::kHitTest)));
+
+ PaintChunk::Id hit_test_chunk_id(*touchaction->EnclosingLayer(),
+ kNonScrollingBackgroundChunkType);
+ auto hit_test_chunk_properties = touchaction->EnclosingLayer()
+ ->GetLayoutObject()
+ .FirstFragment()
+ .ContentsProperties();
+ HitTestData hit_test_data;
+ hit_test_data.touch_action_rects.emplace_back(LayoutRect(0, 0, 100, 100));
+
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties),
+ IsPaintChunk(1, 2, hit_test_chunk_id,
+ hit_test_chunk_properties, hit_test_data)));
+
+ touchaction_element->removeAttribute(html_names::kStyleAttr);
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType)));
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_chunk_id, root_chunk_properties)));
}
namespace {
@@ -353,7 +485,7 @@ class BlockPainterMockEventListener final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event*) final {}
+ void Invoke(ExecutionContext*, Event*) final {}
};
} // namespace
@@ -372,32 +504,32 @@ TEST_F(BlockPainterTestWithPaintTouchAction, TouchHandlerRectsWithoutPaint) {
// Initially there should be no hit test display items because there are no
// event handlers.
- auto* scrolling_client = GetLayoutView().Layer()->GraphicsLayerBacking();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType));
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType)));
// Add an event listener to parent and ensure that hit test display items are
// created for both the parent and child.
BlockPainterMockEventListener* callback = new BlockPainterMockEventListener();
auto* parent_element = GetElementById("parent");
- parent_element->addEventListener(EventTypeNames::touchstart, callback);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent_element->addEventListener(event_type_names::kTouchstart, callback);
+ UpdateAllLifecyclePhasesForTest();
+
auto* parent = GetLayoutObjectByElementId("parent");
auto* child = GetLayoutObjectByElementId("child");
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*parent, DisplayItem::kHitTest),
- TestDisplayItem(*child, DisplayItem::kHitTest));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(parent, DisplayItem::kHitTest),
+ IsSameId(child, DisplayItem::kHitTest)));
// Remove the event handler from parent and ensure no hit test display items
// are left.
parent_element->RemoveAllEventListeners();
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType));
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType)));
}
TEST_F(BlockPainterTestWithPaintTouchAction,
@@ -414,24 +546,22 @@ TEST_F(BlockPainterTestWithPaintTouchAction,
</div>
)HTML");
- auto* scrolling_client = GetLayoutView().Layer()->GraphicsLayerBacking();
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
auto* parent = GetLayoutObjectByElementId("parent");
auto* child = GetLayoutObjectByElementId("child");
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*parent, DisplayItem::kHitTest),
- TestDisplayItem(*child, DisplayItem::kHitTest));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(parent, DisplayItem::kHitTest),
+ IsSameId(child, DisplayItem::kHitTest)));
auto* child_element = GetElementById("parent");
child_element->setAttribute("style", "background: blue;");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*parent, kBackgroundType),
- TestDisplayItem(*parent, DisplayItem::kHitTest),
- TestDisplayItem(*child, DisplayItem::kHitTest));
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(parent, kBackgroundType),
+ IsSameId(parent, DisplayItem::kHitTest),
+ IsSameId(child, DisplayItem::kHitTest)));
}
TEST_F(BlockPainterTestWithPaintTouchAction, ScrolledHitTestChunkProperties) {
@@ -456,28 +586,45 @@ TEST_F(BlockPainterTestWithPaintTouchAction, ScrolledHitTestChunkProperties) {
</div>
)HTML");
- auto* scrolling_client = GetLayoutView().Layer()->GraphicsLayerBacking();
- auto* scroller = GetLayoutObjectByElementId("scroller");
- auto* child = GetLayoutObjectByElementId("child");
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(*scrolling_client, kDocumentBackgroundType),
- TestDisplayItem(*scroller, DisplayItem::kHitTest),
- TestDisplayItem(*child, DisplayItem::kHitTest));
-
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(3u, paint_chunks.size());
-
- const auto& scroller_paint_chunk = RootPaintController().PaintChunks()[1];
- EXPECT_EQ(ToLayoutBoxModelObject(scroller)->Layer(),
- &scroller_paint_chunk.id.client);
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
+ const auto* scroller = ToLayoutBlock(GetLayoutObjectByElementId("scroller"));
+ const auto* child = GetLayoutObjectByElementId("child");
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&scrolling_client, kDocumentBackgroundType),
+ IsSameId(scroller, DisplayItem::kHitTest),
+ IsSameId(child, DisplayItem::kHitTest)));
+
+ HitTestData scroller_hit_test_data;
+ scroller_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 100, 100));
+ HitTestData scrolled_hit_test_data;
+ scrolled_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 200, 50));
+
+ const auto& paint_chunks = RootPaintController().PaintChunks();
+ EXPECT_THAT(
+ paint_chunks,
+ ElementsAre(
+ IsPaintChunk(
+ 0, 1, PaintChunk::Id(scrolling_client, kDocumentBackgroundType),
+ GetLayoutView().FirstFragment().ContentsProperties()),
+ IsPaintChunk(1, 2,
+ PaintChunk::Id(*scroller->Layer(),
+ kNonScrollingBackgroundChunkType),
+ scroller->FirstFragment().LocalBorderBoxProperties(),
+ scroller_hit_test_data),
+ IsPaintChunk(
+ 2, 3,
+ PaintChunk::Id(*scroller, kScrollingContentsBackgroundChunkType),
+ scroller->FirstFragment().ContentsProperties(),
+ scrolled_hit_test_data)));
+
+ const auto& scroller_paint_chunk = paint_chunks[1];
EXPECT_EQ(FloatRect(0, 0, 100, 100), scroller_paint_chunk.bounds);
// The hit test rect for the scroller itself should not be scrolled.
EXPECT_FALSE(scroller_paint_chunk.properties.Transform()->ScrollNode());
- const auto& scrolled_paint_chunk = RootPaintController().PaintChunks()[2];
- EXPECT_EQ(scroller, &scrolled_paint_chunk.id.client);
+ const auto& scrolled_paint_chunk = paint_chunks[2];
EXPECT_EQ(FloatRect(0, 0, 200, 50), scrolled_paint_chunk.bounds);
// The hit test rect for the scrolled contents should be scrolled.
EXPECT_TRUE(scrolled_paint_chunk.properties.Transform()->ScrollNode());
diff --git a/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.cc b/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.cc
index 268adbb68ee..7b320469781 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.cc
@@ -56,10 +56,14 @@ BoxModelObjectPainter::BoxModelObjectPainter(const LayoutBoxModelObject& box,
box_model_(box),
flow_box_(flow_box) {}
-bool BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- const LayoutBoxModelObject* box_model_,
- const PaintInfo& paint_info) {
+bool BoxModelObjectPainter::IsPaintingScrollingBackground(
+ const LayoutBoxModelObject* box_model_,
+ const PaintInfo& paint_info) {
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // TODO(wangxianzhu): For SPv2, remove this method and let callers use
+ // PaintInfo::IsPaintScrollingBackground() directly.
+ return paint_info.IsPaintingScrollingBackground();
+ }
return paint_info.PaintFlags() & kPaintLayerPaintingOverflowContents &&
!(paint_info.PaintFlags() &
kPaintLayerPaintingCompositingBackgroundPhase) &&
@@ -99,8 +103,7 @@ LayoutRect BoxModelObjectPainter::AdjustRectForScrolledContent(
LayoutRect scrolled_paint_rect = rect;
GraphicsContext& context = paint_info.context;
if (info.is_clipped_with_local_scrolling &&
- !IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &box_model_, paint_info)) {
+ !IsPaintingScrollingBackground(&box_model_, paint_info)) {
// Clip to the overflow area.
const LayoutBox& this_box = ToLayoutBox(box_model_);
// TODO(chrishtr): this should be pixel-snapped.
diff --git a/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.h b/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.h
index c1ff417c07f..73775e86982 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/box_model_object_painter.h
@@ -27,9 +27,8 @@ class BoxModelObjectPainter : public BoxPainterBase {
BoxModelObjectPainter(const LayoutBoxModelObject&,
const InlineFlowBox* = nullptr);
- static bool IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- const LayoutBoxModelObject*,
- const PaintInfo&);
+ static bool IsPaintingScrollingBackground(const LayoutBoxModelObject*,
+ const PaintInfo&);
protected:
LayoutRectOutsets ComputeBorders() const override;
diff --git a/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.cc b/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.cc
index 7b903f55bc8..a9618ef19d3 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.cc
@@ -15,6 +15,109 @@
namespace blink {
+bool BoxPaintInvalidator::HasEffectiveBackground() {
+ // The view can paint background not from the style.
+ if (box_.IsLayoutView())
+ return true;
+ return box_.StyleRef().HasBackground() && !box_.BackgroundTransfersToView();
+}
+
+// |width| is of the positioning area.
+static bool ShouldFullyInvalidateFillLayersOnWidthChange(
+ const FillLayer& layer) {
+ // Nobody will use multiple layers without wanting fancy positioning.
+ if (layer.Next())
+ return true;
+
+ // The layer properties checked below apply only when there is a valid image.
+ StyleImage* img = layer.GetImage();
+ if (!img || !img->CanRender())
+ return false;
+
+ if (layer.RepeatX() != EFillRepeat::kRepeatFill &&
+ layer.RepeatX() != EFillRepeat::kNoRepeatFill)
+ return true;
+
+ // TODO(alancutter): Make this work correctly for calc lengths.
+ if (layer.PositionX().IsPercentOrCalc() && !layer.PositionX().IsZero())
+ return true;
+
+ if (layer.BackgroundXOrigin() != BackgroundEdgeOrigin::kLeft)
+ return true;
+
+ EFillSizeType size_type = layer.SizeType();
+
+ if (size_type == EFillSizeType::kContain ||
+ size_type == EFillSizeType::kCover)
+ return true;
+
+ if (size_type == EFillSizeType::kSizeLength) {
+ // TODO(alancutter): Make this work correctly for calc lengths.
+ if (layer.SizeLength().Width().IsPercentOrCalc() &&
+ !layer.SizeLength().Width().IsZero())
+ return true;
+ if (img->IsGeneratedImage() && layer.SizeLength().Width().IsAuto())
+ return true;
+ } else if (img->UsesImageContainerSize()) {
+ return true;
+ }
+
+ return false;
+}
+
+// |height| is of the positioning area.
+static bool ShouldFullyInvalidateFillLayersOnHeightChange(
+ const FillLayer& layer) {
+ // Nobody will use multiple layers without wanting fancy positioning.
+ if (layer.Next())
+ return true;
+
+ // The layer properties checked below apply only when there is a valid image.
+ StyleImage* img = layer.GetImage();
+ if (!img || !img->CanRender())
+ return false;
+
+ if (layer.RepeatY() != EFillRepeat::kRepeatFill &&
+ layer.RepeatY() != EFillRepeat::kNoRepeatFill)
+ return true;
+
+ // TODO(alancutter): Make this work correctly for calc lengths.
+ if (layer.PositionY().IsPercentOrCalc() && !layer.PositionY().IsZero())
+ return true;
+
+ if (layer.BackgroundYOrigin() != BackgroundEdgeOrigin::kTop)
+ return true;
+
+ EFillSizeType size_type = layer.SizeType();
+
+ if (size_type == EFillSizeType::kContain ||
+ size_type == EFillSizeType::kCover)
+ return true;
+
+ if (size_type == EFillSizeType::kSizeLength) {
+ // TODO(alancutter): Make this work correctly for calc lengths.
+ if (layer.SizeLength().Height().IsPercentOrCalc() &&
+ !layer.SizeLength().Height().IsZero())
+ return true;
+ if (img->IsGeneratedImage() && layer.SizeLength().Height().IsAuto())
+ return true;
+ } else if (img->UsesImageContainerSize()) {
+ return true;
+ }
+
+ return false;
+}
+
+// old_size and new_size are the old and new sizes of the positioning area.
+bool ShouldFullyInvalidateFillLayersOnSizeChange(const FillLayer& layer,
+ const LayoutSize& old_size,
+ const LayoutSize& new_size) {
+ return (old_size.Width() != new_size.Width() &&
+ ShouldFullyInvalidateFillLayersOnWidthChange(layer)) ||
+ (old_size.Height() != new_size.Height() &&
+ ShouldFullyInvalidateFillLayersOnHeightChange(layer));
+}
+
PaintInvalidationReason BoxPaintInvalidator::ComputePaintInvalidationReason() {
PaintInvalidationReason reason =
ObjectPaintInvalidatorWithContext(box_, context_)
@@ -25,16 +128,11 @@ PaintInvalidationReason BoxPaintInvalidator::ComputePaintInvalidationReason() {
const ComputedStyle& style = box_.StyleRef();
- if ((style.BackgroundLayers().ThisOrNextLayersUseContentBox() ||
- style.MaskLayers().ThisOrNextLayersUseContentBox()) &&
- box_.PreviousPhysicalContentBoxRect() != box_.PhysicalContentBoxRect()) {
+ if (style.MaskLayers().AnyLayerUsesContentBox() &&
+ box_.PreviousPhysicalContentBoxRect() != box_.PhysicalContentBoxRect())
return PaintInvalidationReason::kGeometry;
- }
- LayoutSize old_border_box_size = box_.PreviousSize();
- LayoutSize new_border_box_size = box_.Size();
- bool border_box_changed = old_border_box_size != new_border_box_size;
- if (!border_box_changed &&
+ if (box_.PreviousSize() == box_.Size() &&
context_.old_visual_rect == context_.fragment_data->VisualRect())
return PaintInvalidationReason::kNone;
@@ -45,14 +143,13 @@ PaintInvalidationReason BoxPaintInvalidator::ComputePaintInvalidationReason() {
// - scale, rotate, skew etc. transforms,
// - visual (ink) overflows.
if (context_.old_visual_rect !=
- LayoutRect(context_.old_paint_offset, old_border_box_size) ||
+ LayoutRect(context_.old_paint_offset, box_.PreviousSize()) ||
context_.fragment_data->VisualRect() !=
- LayoutRect(context_.fragment_data->PaintOffset(),
- new_border_box_size)) {
+ LayoutRect(context_.fragment_data->PaintOffset(), box_.Size())) {
return PaintInvalidationReason::kGeometry;
}
- DCHECK(border_box_changed);
+ DCHECK_NE(box_.PreviousSize(), box_.Size());
// Incremental invalidation is not applicable if there is border in the
// direction of border box size change because we don't know the border
@@ -64,14 +161,7 @@ PaintInvalidationReason BoxPaintInvalidator::ComputePaintInvalidationReason() {
style.HasFilterInducingProperty() || style.HasMask() || style.ClipPath())
return PaintInvalidationReason::kGeometry;
- if (style.HasBorderRadius())
- return PaintInvalidationReason::kGeometry;
-
- if (old_border_box_size.Width() != new_border_box_size.Width() &&
- box_.MustInvalidateBackgroundOrBorderPaintOnWidthChange())
- return PaintInvalidationReason::kGeometry;
- if (old_border_box_size.Height() != new_border_box_size.Height() &&
- box_.MustInvalidateBackgroundOrBorderPaintOnHeightChange())
+ if (style.HasBorderRadius() || style.CanRenderBorderImage())
return PaintInvalidationReason::kGeometry;
// Needs to repaint frame boundaries.
@@ -82,25 +172,24 @@ PaintInvalidationReason BoxPaintInvalidator::ComputePaintInvalidationReason() {
if (box_.IsLayoutMultiColumnSet())
return PaintInvalidationReason::kGeometry;
+ // Background invalidation has been done during InvalidateBackground(), so
+ // we don't need to check background in this function.
+
return PaintInvalidationReason::kIncremental;
}
-bool BoxPaintInvalidator::BackgroundGeometryDependsOnLayoutOverflowRect()
- const {
- return !box_.IsDocumentElement() && !box_.BackgroundStolenForBeingBody() &&
- box_.StyleRef()
- .BackgroundLayers()
- .ThisOrNextLayersHaveLocalAttachment();
+bool BoxPaintInvalidator::BackgroundGeometryDependsOnLayoutOverflowRect() {
+ return HasEffectiveBackground() &&
+ box_.StyleRef().BackgroundLayers().AnyLayerHasLocalAttachmentImage();
}
-// Background positioning in layout overflow rect doesn't mean it will
-// paint onto the scrolling contents layer because some conditions prevent
-// it from that. We may also treat non-local solid color backgrounds as local
-// and paint onto the scrolling contents layer.
-// See PaintLayer::canPaintBackgroundOntoScrollingContentsLayer().
bool BoxPaintInvalidator::BackgroundPaintsOntoScrollingContentsLayer() {
- if (box_.IsDocumentElement() || box_.BackgroundStolenForBeingBody())
+ if (!HasEffectiveBackground())
return false;
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ return box_.GetBackgroundPaintLocation() &
+ kBackgroundPaintInScrollingContents;
+ }
if (!box_.HasLayer())
return false;
if (auto* mapping = box_.Layer()->GetCompositedLayerMapping())
@@ -108,48 +197,65 @@ bool BoxPaintInvalidator::BackgroundPaintsOntoScrollingContentsLayer() {
return false;
}
+bool BoxPaintInvalidator::BackgroundPaintsOntoMainGraphicsLayer() {
+ if (!HasEffectiveBackground())
+ return false;
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return box_.GetBackgroundPaintLocation() & kBackgroundPaintInGraphicsLayer;
+ if (!box_.HasLayer())
+ return true;
+ if (auto* mapping = box_.Layer()->GetCompositedLayerMapping())
+ return mapping->BackgroundPaintsOntoGraphicsLayer();
+ return true;
+}
+
bool BoxPaintInvalidator::ShouldFullyInvalidateBackgroundOnLayoutOverflowChange(
const LayoutRect& old_layout_overflow,
- const LayoutRect& new_layout_overflow) const {
+ const LayoutRect& new_layout_overflow) {
if (new_layout_overflow == old_layout_overflow)
return false;
- // TODO(pdr): This check can likely be removed because size changes are
- // caught below.
- if (new_layout_overflow.IsEmpty() || old_layout_overflow.IsEmpty())
- return true;
-
- if (new_layout_overflow.Location() != old_layout_overflow.Location()) {
- auto& layers = box_.StyleRef().BackgroundLayers();
- // The background should invalidate on most location changes but we can
- // avoid invalidation in a common case if the background is a single color
- // that fully covers the overflow area.
- // TODO(pdr): Check all background layers instead of skipping this if there
- // are multiple backgrounds.
- if (layers.Next() || layers.GetImage() ||
- layers.RepeatX() != EFillRepeat::kRepeatFill ||
- layers.RepeatY() != EFillRepeat::kRepeatFill)
- return true;
- }
+ if (!BackgroundGeometryDependsOnLayoutOverflowRect())
+ return false;
- if (new_layout_overflow.Width() != old_layout_overflow.Width() &&
- box_.MustInvalidateFillLayersPaintOnWidthChange(
- box_.StyleRef().BackgroundLayers()))
- return true;
- if (new_layout_overflow.Height() != old_layout_overflow.Height() &&
- box_.MustInvalidateFillLayersPaintOnHeightChange(
- box_.StyleRef().BackgroundLayers()))
+ // The background should invalidate on most location changes.
+ if (new_layout_overflow.Location() != old_layout_overflow.Location())
return true;
- return false;
+ return ShouldFullyInvalidateFillLayersOnSizeChange(
+ box_.StyleRef().BackgroundLayers(), old_layout_overflow.Size(),
+ new_layout_overflow.Size());
}
-bool BoxPaintInvalidator::ViewBackgroundShouldFullyInvalidate() const {
+BoxPaintInvalidator::BackgroundInvalidationType
+BoxPaintInvalidator::ComputeViewBackgroundInvalidation() {
DCHECK(box_.IsLayoutView());
- // Fixed attachment background is handled in LayoutView::layout().
- // TODO(wangxianzhu): Combine code for fixed-attachment background.
- if (box_.StyleRef().HasEntirelyFixedBackground())
- return false;
+
+ const auto& layout_view = ToLayoutView(box_);
+ auto new_background_rect = layout_view.BackgroundRect();
+ auto old_background_rect = layout_view.PreviousBackgroundRect();
+ layout_view.SetPreviousBackgroundRect(new_background_rect);
+
+ // BackgroundRect is the positioning area of all fixed attachment backgrounds,
+ // including the LayoutView's and descendants'.
+ bool background_location_changed =
+ new_background_rect.Location() != old_background_rect.Location();
+ bool background_size_changed =
+ new_background_rect.Size() != old_background_rect.Size();
+ if (background_location_changed || background_size_changed) {
+ for (auto* object :
+ layout_view.GetFrameView()->BackgroundAttachmentFixedObjects()) {
+ if (background_location_changed ||
+ ShouldFullyInvalidateFillLayersOnSizeChange(
+ object->StyleRef().BackgroundLayers(), old_background_rect.Size(),
+ new_background_rect.Size()))
+ object->SetBackgroundNeedsFullPaintInvalidation();
+ }
+ }
+
+ if (background_location_changed ||
+ layout_view.BackgroundNeedsFullPaintInvalidation())
+ return BackgroundInvalidationType::kFull;
// LayoutView's non-fixed-attachment background is positioned in the
// document element and needs to invalidate if the size changes.
@@ -163,20 +269,47 @@ bool BoxPaintInvalidator::ViewBackgroundShouldFullyInvalidate() const {
if (ShouldFullyInvalidateBackgroundOnLayoutOverflowChange(
document_background_box->PreviousPhysicalLayoutOverflowRect(),
document_background_box->PhysicalLayoutOverflowRect())) {
- return true;
+ return BackgroundInvalidationType::kFull;
}
}
}
}
- return false;
+
+ return background_size_changed ? BackgroundInvalidationType::kIncremental
+ : BackgroundInvalidationType::kNone;
}
BoxPaintInvalidator::BackgroundInvalidationType
-BoxPaintInvalidator::ComputeBackgroundInvalidation() {
- if (box_.BackgroundChangedSinceLastPaintInvalidation())
+BoxPaintInvalidator::ComputeBackgroundInvalidation(
+ bool& should_invalidate_all_layers) {
+ should_invalidate_all_layers = false;
+
+ // If background changed, we may paint the background on different graphics
+ // layer, so we need to fully invalidate the background on all layers.
+ if (box_.BackgroundNeedsFullPaintInvalidation()) {
+ if (box_.HasLayer() && box_.Layer()->GetCompositedLayerMapping() &&
+ box_.Layer()->GetCompositedLayerMapping()->ScrollingContentsLayer())
+ should_invalidate_all_layers = true;
+
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() &&
+ box_.FirstFragment().PaintProperties() &&
+ box_.FirstFragment().PaintProperties()->ScrollTranslation())
+ should_invalidate_all_layers = true;
+
+ return BackgroundInvalidationType::kFull;
+ }
+
+ if (!HasEffectiveBackground())
+ return BackgroundInvalidationType::kNone;
+
+ const auto& background_layers = box_.StyleRef().BackgroundLayers();
+ if (background_layers.AnyLayerHasDefaultAttachmentImage() &&
+ ShouldFullyInvalidateFillLayersOnSizeChange(
+ background_layers, box_.PreviousSize(), box_.Size()))
return BackgroundInvalidationType::kFull;
- if (box_.IsLayoutView() && ViewBackgroundShouldFullyInvalidate())
+ if (background_layers.AnyLayerUsesContentBox() &&
+ box_.PreviousPhysicalContentBoxRect() != box_.PhysicalContentBoxRect())
return BackgroundInvalidationType::kFull;
bool layout_overflow_change_causes_invalidation =
@@ -203,22 +336,30 @@ BoxPaintInvalidator::ComputeBackgroundInvalidation() {
}
void BoxPaintInvalidator::InvalidateBackground() {
- BackgroundInvalidationType background_invalidation_type =
- ComputeBackgroundInvalidation();
-
- if (BackgroundPaintsOntoScrollingContentsLayer()) {
- if (background_invalidation_type != BackgroundInvalidationType::kNone) {
- auto reason =
- background_invalidation_type == BackgroundInvalidationType::kFull
- ? PaintInvalidationReason::kBackgroundOnScrollingContentsLayer
- : PaintInvalidationReason::kIncremental;
- context_.painting_layer->SetNeedsRepaint();
- ObjectPaintInvalidator(box_).InvalidateDisplayItemClient(
- *box_.Layer()->GetCompositedLayerMapping()->ScrollingContentsLayer(),
- reason);
- }
- } else if (background_invalidation_type ==
- BackgroundInvalidationType::kFull) {
+ bool should_invalidate_all_layers;
+ auto background_invalidation_type =
+ ComputeBackgroundInvalidation(should_invalidate_all_layers);
+ if (box_.IsLayoutView()) {
+ background_invalidation_type = std::max(
+ background_invalidation_type, ComputeViewBackgroundInvalidation());
+ }
+
+ if (should_invalidate_all_layers ||
+ (BackgroundPaintsOntoScrollingContentsLayer() &&
+ background_invalidation_type != BackgroundInvalidationType::kNone)) {
+ auto reason =
+ background_invalidation_type == BackgroundInvalidationType::kFull
+ ? PaintInvalidationReason::kBackground
+ : PaintInvalidationReason::kIncremental;
+ context_.painting_layer->SetNeedsRepaint();
+ ObjectPaintInvalidator(box_).InvalidateDisplayItemClient(
+ box_.GetScrollableArea()->GetScrollingBackgroundDisplayItemClient(),
+ reason);
+ }
+
+ if (should_invalidate_all_layers ||
+ (BackgroundPaintsOntoMainGraphicsLayer() &&
+ background_invalidation_type == BackgroundInvalidationType::kFull)) {
box_.GetMutableForPainting()
.SetShouldDoFullPaintInvalidationWithoutGeometryChange(
PaintInvalidationReason::kBackground);
@@ -241,7 +382,7 @@ void BoxPaintInvalidator::InvalidatePaint() {
bool BoxPaintInvalidator::
NeedsToSavePreviousContentBoxRectOrLayoutOverflowRect() {
// The LayoutView depends on the document element's layout overflow rect (see:
- // ViewBackgroundShouldFullyInvalidate) and needs to invalidate before the
+ // ComputeViewBackgroundInvalidation) and needs to invalidate before the
// document element invalidates. There are few document elements so the
// previous layout overflow rect is always saved, rather than duplicating the
// logic save-if-needed logic for this special case.
@@ -265,8 +406,8 @@ bool BoxPaintInvalidator::
// Background and mask layers can depend on other boxes than border box. See
// crbug.com/490533
- if ((style.BackgroundLayers().ThisOrNextLayersUseContentBox() ||
- style.MaskLayers().ThisOrNextLayersUseContentBox()) &&
+ if ((style.BackgroundLayers().AnyLayerUsesContentBox() ||
+ style.MaskLayers().AnyLayerUsesContentBox()) &&
box_.ContentSize() != box_.Size())
return true;
if ((BackgroundGeometryDependsOnLayoutOverflowRect() ||
diff --git a/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.h
index 9cd71dc515f..2935f46bb40 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.h
@@ -30,15 +30,18 @@ class CORE_EXPORT BoxPaintInvalidator {
private:
friend class BoxPaintInvalidatorTest;
- bool BackgroundGeometryDependsOnLayoutOverflowRect() const;
+ bool HasEffectiveBackground();
+ bool BackgroundGeometryDependsOnLayoutOverflowRect();
bool BackgroundPaintsOntoScrollingContentsLayer();
+ bool BackgroundPaintsOntoMainGraphicsLayer();
bool ShouldFullyInvalidateBackgroundOnLayoutOverflowChange(
const LayoutRect& old_layout_overflow,
- const LayoutRect& new_layout_overflow) const;
- bool ViewBackgroundShouldFullyInvalidate() const;
+ const LayoutRect& new_layout_overflow);
enum BackgroundInvalidationType { kNone = 0, kIncremental, kFull };
- BackgroundInvalidationType ComputeBackgroundInvalidation();
+ BackgroundInvalidationType ComputeViewBackgroundInvalidation();
+ BackgroundInvalidationType ComputeBackgroundInvalidation(
+ bool& should_invalidate_all_layers);
void InvalidateBackground();
PaintInvalidationReason ComputePaintInvalidationReason();
diff --git a/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator_test.cc b/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator_test.cc
index fd7efdadda3..e4296ac8448 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_paint_invalidator_test.cc
@@ -44,7 +44,7 @@ class BoxPaintInvalidatorTest : public PaintControllerPaintTest {
void ExpectFullPaintInvalidationOnGeometryChange(const char* test_title) {
SCOPED_TRACE(test_title);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto& target = *GetDocument().getElementById("target");
auto& box = *ToLayoutBox(target.GetLayoutObject());
LayoutRect visual_rect = box.FirstFragment().VisualRect();
@@ -55,8 +55,8 @@ class BoxPaintInvalidatorTest : public PaintControllerPaintTest {
ComputePaintInvalidationReason(box, visual_rect, paint_offset));
target.setAttribute(
- HTMLNames::styleAttr,
- target.getAttribute(HTMLNames::styleAttr) + "; width: 200px");
+ html_names::kStyleAttr,
+ target.getAttribute(html_names::kStyleAttr) + "; width: 200px");
GetDocument().View()->UpdateLifecycleToLayoutClean();
// Simulate that PaintInvalidator updates visual rect.
box.GetMutableForPainting().SetVisualRect(
@@ -103,8 +103,8 @@ TEST_P(BoxPaintInvalidatorTest, ComputePaintInvalidationReasonPaintingNothing) {
auto& target = *GetDocument().getElementById("target");
auto& box = *ToLayoutBox(target.GetLayoutObject());
// Remove border.
- target.setAttribute(HTMLNames::classAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target.setAttribute(html_names::kClassAttr, "");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(box.PaintedOutputOfObjectHasNoEffectRegardlessOfSize());
LayoutRect visual_rect = box.FirstFragment().VisualRect();
@@ -121,7 +121,7 @@ TEST_P(BoxPaintInvalidatorTest, ComputePaintInvalidationReasonPaintingNothing) {
// Visual rect size change.
LayoutRect old_visual_rect = visual_rect;
- target.setAttribute(HTMLNames::styleAttr, "width: 200px");
+ target.setAttribute(html_names::kStyleAttr, "width: 200px");
GetDocument().View()->UpdateLifecycleToLayoutClean();
// Simulate that PaintInvalidator updates visual rect.
box.GetMutableForPainting().SetVisualRect(
@@ -137,9 +137,9 @@ TEST_P(BoxPaintInvalidatorTest, ComputePaintInvalidationReasonBasic) {
auto& target = *GetDocument().getElementById("target");
auto& box = *ToLayoutBox(target.GetLayoutObject());
// Remove border.
- target.setAttribute(HTMLNames::classAttr, "");
- target.setAttribute(HTMLNames::styleAttr, "background: blue");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target.setAttribute(html_names::kClassAttr, "");
+ target.setAttribute(html_names::kStyleAttr, "background: blue");
+ UpdateAllLifecyclePhasesForTest();
box.SetShouldCheckForPaintInvalidation();
LayoutRect visual_rect = box.FirstFragment().VisualRect();
@@ -152,7 +152,7 @@ TEST_P(BoxPaintInvalidatorTest, ComputePaintInvalidationReasonBasic) {
// Visual rect size change.
LayoutRect old_visual_rect = visual_rect;
- target.setAttribute(HTMLNames::styleAttr, "background: blue; width: 200px");
+ target.setAttribute(html_names::kStyleAttr, "background: blue; width: 200px");
GetDocument().View()->UpdateLifecycleToLayoutClean();
// Simulate that PaintInvalidator updates visual rect.
box.GetMutableForPainting().SetVisualRect(
@@ -189,26 +189,27 @@ TEST_P(BoxPaintInvalidatorTest, ComputePaintInvalidationReasonOtherCases) {
ExpectFullPaintInvalidationOnGeometryChange("With border");
// Clear border, set background.
- target.setAttribute(HTMLNames::classAttr, "background");
- target.setAttribute(HTMLNames::styleAttr, "border-radius: 5px");
+ target.setAttribute(html_names::kClassAttr, "background");
+ target.setAttribute(html_names::kStyleAttr, "border-radius: 5px");
ExpectFullPaintInvalidationOnGeometryChange("With border-radius");
- target.setAttribute(HTMLNames::styleAttr, "-webkit-mask: url(#)");
+ target.setAttribute(html_names::kStyleAttr, "-webkit-mask: url(#)");
ExpectFullPaintInvalidationOnGeometryChange("With mask");
- target.setAttribute(HTMLNames::styleAttr, "filter: blur(5px)");
+ target.setAttribute(html_names::kStyleAttr, "filter: blur(5px)");
ExpectFullPaintInvalidationOnGeometryChange("With filter");
- target.setAttribute(HTMLNames::styleAttr, "outline: 2px solid blue");
+ target.setAttribute(html_names::kStyleAttr, "outline: 2px solid blue");
ExpectFullPaintInvalidationOnGeometryChange("With outline");
- target.setAttribute(HTMLNames::styleAttr, "box-shadow: inset 3px 2px");
+ target.setAttribute(html_names::kStyleAttr, "box-shadow: inset 3px 2px");
ExpectFullPaintInvalidationOnGeometryChange("With box-shadow");
- target.setAttribute(HTMLNames::styleAttr, "-webkit-appearance: button");
+ target.setAttribute(html_names::kStyleAttr, "-webkit-appearance: button");
ExpectFullPaintInvalidationOnGeometryChange("With appearance");
- target.setAttribute(HTMLNames::styleAttr, "clip-path: circle(50% at 0 50%)");
+ target.setAttribute(html_names::kStyleAttr,
+ "clip-path: circle(50% at 0 50%)");
ExpectFullPaintInvalidationOnGeometryChange("With clip-path");
}
diff --git a/chromium/third_party/blink/renderer/core/paint/box_painter.cc b/chromium/third_party/blink/renderer/core/paint/box_painter.cc
index 8b2dced6687..7c6f1ce6709 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter.cc
@@ -19,15 +19,17 @@
#include "third_party/blink/renderer/core/paint/nine_piece_image_painter.h"
#include "third_party/blink/renderer/core/paint/object_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/scoped_paint_state.h"
#include "third_party/blink/renderer/core/paint/svg_foreign_object_painter.h"
#include "third_party/blink/renderer/core/paint/theme_painter.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/display_item_cache_skipper.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
namespace blink {
@@ -53,15 +55,14 @@ void BoxPainter::PaintChildren(const PaintInfo& paint_info) {
void BoxPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
LayoutRect paint_rect;
+ const DisplayItemClient* background_client = nullptr;
base::Optional<ScopedBoxContentsPaintState> contents_paint_state;
- if (BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &layout_box_, paint_info)) {
+ if (BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_box_,
+ paint_info)) {
// For the case where we are painting the background into the scrolling
// contents layer of a composited scroller we need to include the entire
// overflow rect.
paint_rect = layout_box_.PhysicalLayoutOverflowRect();
-
contents_paint_state.emplace(paint_info, paint_offset, layout_box_);
paint_rect.MoveBy(contents_paint_state->PaintOffset());
@@ -69,32 +70,45 @@ void BoxPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info,
// paint_rect so we expand the paint_rect by the border size when painting
// the background into the scrolling contents layer.
paint_rect.Expand(layout_box_.BorderBoxOutsets());
+
+ background_client = &layout_box_.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
} else {
paint_rect = layout_box_.BorderBoxRect();
paint_rect.MoveBy(paint_offset);
+ background_client = &layout_box_;
+ }
+
+ // Paint the background if we're visible and this block has a box decoration
+ // (background, border, appearance, or box shadow).
+ const ComputedStyle& style = layout_box_.StyleRef();
+ if (style.Visibility() == EVisibility::kVisible &&
+ layout_box_.HasBoxDecorationBackground()) {
+ PaintBoxDecorationBackgroundWithRect(
+ contents_paint_state ? contents_paint_state->GetPaintInfo()
+ : paint_info,
+ paint_rect, *background_client);
}
- PaintBoxDecorationBackgroundWithRect(
- contents_paint_state ? contents_paint_state->GetPaintInfo() : paint_info,
- paint_rect);
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled())
+ RecordHitTestData(paint_info, paint_rect, *background_client);
}
bool BoxPainter::BackgroundIsKnownToBeOpaque(const PaintInfo& paint_info) {
- LayoutRect bounds =
- BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &layout_box_, paint_info)
- ? layout_box_.LayoutOverflowRect()
- : layout_box_.SelfVisualOverflowRect();
+ LayoutRect bounds = BoxModelObjectPainter::IsPaintingScrollingBackground(
+ &layout_box_, paint_info)
+ ? layout_box_.LayoutOverflowRect()
+ : layout_box_.SelfVisualOverflowRect();
return layout_box_.BackgroundIsKnownToBeOpaqueInRect(bounds);
}
void BoxPainter::PaintBoxDecorationBackgroundWithRect(
const PaintInfo& paint_info,
- const LayoutRect& paint_rect) {
- bool painting_overflow_contents = BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &layout_box_, paint_info);
+ const LayoutRect& paint_rect,
+ const DisplayItemClient& background_client) {
+ bool painting_scrolling_background =
+ BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_box_,
+ paint_info);
const ComputedStyle& style = layout_box_.StyleRef();
base::Optional<DisplayItemCacheSkipper> cache_skipper;
@@ -110,18 +124,12 @@ void BoxPainter::PaintBoxDecorationBackgroundWithRect(
cache_skipper.emplace(paint_info.context);
}
- const DisplayItemClient& display_item_client =
- painting_overflow_contents ? static_cast<const DisplayItemClient&>(
- *layout_box_.Layer()
- ->GetCompositedLayerMapping()
- ->ScrollingContentsLayer())
- : layout_box_;
if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, display_item_client,
+ paint_info.context, background_client,
DisplayItem::kBoxDecorationBackground))
return;
- DrawingRecorder recorder(paint_info.context, display_item_client,
+ DrawingRecorder recorder(paint_info.context, background_client,
DisplayItem::kBoxDecorationBackground);
BoxDecorationData box_decoration_data(layout_box_);
GraphicsContextStateSaver state_saver(paint_info.context, false);
@@ -131,12 +139,17 @@ void BoxPainter::PaintBoxDecorationBackgroundWithRect(
BackgroundIsKnownToBeOpaque(paint_info))
recorder.SetKnownToBeOpaque();
+ const auto skip_background = layout_box_.BackgroundTransfersToView() ||
+ (paint_info.SkipRootBackground() &&
+ paint_info.PaintContainer() == &layout_box_);
+
bool needs_end_layer = false;
- if (!painting_overflow_contents) {
+ if (!painting_scrolling_background) {
// FIXME: Should eventually give the theme control over whether the box
// shadow should paint, since controls could have custom shadows of their
// own.
- BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style);
+ BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style, true,
+ true, skip_background);
if (BleedAvoidanceIsClipping(box_decoration_data.bleed_avoidance)) {
state_saver.Save();
@@ -158,10 +171,7 @@ void BoxPainter::PaintBoxDecorationBackgroundWithRect(
bool theme_painted =
box_decoration_data.has_appearance &&
!theme_painter.Paint(layout_box_, paint_info, snapped_paint_rect);
- bool should_paint_background =
- !theme_painted && (!paint_info.SkipRootBackground() ||
- paint_info.PaintContainer() != &layout_box_);
- if (should_paint_background) {
+ if (!theme_painted && !skip_background) {
PaintBackground(paint_info, paint_rect,
box_decoration_data.background_color,
box_decoration_data.bleed_avoidance);
@@ -173,7 +183,7 @@ void BoxPainter::PaintBoxDecorationBackgroundWithRect(
}
}
- if (!painting_overflow_contents) {
+ if (!painting_scrolling_background) {
BoxPainterBase::PaintInsetBoxShadowWithBorderRect(paint_info, paint_rect,
style);
@@ -200,9 +210,7 @@ void BoxPainter::PaintBackground(const PaintInfo& paint_info,
const LayoutRect& paint_rect,
const Color& background_color,
BackgroundBleedAvoidance bleed_avoidance) {
- if (layout_box_.IsDocumentElement())
- return;
- if (layout_box_.BackgroundStolenForBeingBody())
+ if (layout_box_.BackgroundTransfersToView())
return;
if (layout_box_.BackgroundIsKnownToBeObscured())
return;
@@ -245,4 +253,24 @@ void BoxPainter::PaintMaskImages(const PaintInfo& paint_info,
include_logical_right_edge);
}
+void BoxPainter::RecordHitTestData(const PaintInfo& paint_info,
+ const LayoutRect& paint_rect,
+ const DisplayItemClient& background_client) {
+ // Hit test display items are only needed for compositing. This flag is used
+ // for for printing and drag images which do not need hit testing.
+ if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
+ return;
+
+ // If an object is not visible, it does not participate in hit testing.
+ if (layout_box_.StyleRef().Visibility() != EVisibility::kVisible)
+ return;
+
+ auto touch_action = layout_box_.EffectiveWhitelistedTouchAction();
+ if (touch_action == TouchAction::kTouchActionAuto)
+ return;
+
+ HitTestDisplayItem::Record(paint_info.context, background_client,
+ HitTestRect(paint_rect, touch_action));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/box_painter.h b/chromium/third_party/blink/renderer/core/paint/box_painter.h
index 4045538d6f6..89f67ee8793 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter.h
@@ -15,6 +15,7 @@ namespace blink {
struct PaintInfo;
class Color;
+class DisplayItemClient;
class LayoutBox;
class LayoutPoint;
class LayoutRect;
@@ -32,8 +33,18 @@ class BoxPainter {
void PaintMask(const PaintInfo&, const LayoutPoint& paint_offset);
void PaintMaskImages(const PaintInfo&, const LayoutRect&);
- void PaintBoxDecorationBackgroundWithRect(const PaintInfo&,
- const LayoutRect&);
+ void PaintBoxDecorationBackgroundWithRect(
+ const PaintInfo&,
+ const LayoutRect&,
+ const DisplayItemClient& background_client);
+
+ // Paint a hit test display item and record hit test data. This should be
+ // called in the background paint phase even if there is no other painted
+ // content.
+ void RecordHitTestData(const PaintInfo&,
+ const LayoutRect& paint_rect,
+ const DisplayItemClient& background_client);
+
private:
bool BackgroundIsKnownToBeOpaque(const PaintInfo&);
void PaintBackground(const PaintInfo&,
diff --git a/chromium/third_party/blink/renderer/core/paint/box_painter_base.cc b/chromium/third_party/blink/renderer/core/paint/box_painter_base.cc
index 71efbe56c55..e0a47c38afa 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter_base.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter_base.cc
@@ -54,7 +54,8 @@ void BoxPainterBase::PaintNormalBoxShadow(const PaintInfo& info,
const LayoutRect& paint_rect,
const ComputedStyle& style,
bool include_logical_left_edge,
- bool include_logical_right_edge) {
+ bool include_logical_right_edge,
+ bool background_is_skipped) {
if (!style.BoxShadow())
return;
GraphicsContext& context = info.context;
@@ -64,8 +65,9 @@ void BoxPainterBase::PaintNormalBoxShadow(const PaintInfo& info,
bool has_border_radius = style.HasBorderRadius();
bool has_opaque_background =
+ !background_is_skipped &&
style.VisitedDependentColor(GetCSSPropertyBackgroundColor()).Alpha() ==
- 255;
+ 255;
GraphicsContextStateSaver state_saver(context, false);
@@ -425,15 +427,19 @@ inline bool PaintFastBottomLayer(Node* node,
// so snap to integers. This is particuarly important for sprite maps.
// Calculation up to this point, in LayoutUnits, can lead to small variations
// from integer size, so it is safe to round without introducing major issues.
- const FloatRect src_rect =
- FloatRect(RoundedIntRect(Image::ComputeSubsetForBackground(
- image_tile, dest_rect_for_subset, intrinsic_tile_size)));
+ const FloatRect unrounded_subset = Image::ComputeSubsetForBackground(
+ image_tile, dest_rect_for_subset, intrinsic_tile_size);
+ FloatRect src_rect = FloatRect(RoundedIntRect(unrounded_subset));
+
+ // If we have rounded the image size to 0, revert the rounding.
+ if (src_rect.IsEmpty())
+ src_rect = unrounded_subset;
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage",
"data",
- InspectorPaintImageEvent::Data(node, *info.image,
- FloatRect(image->Rect()),
- FloatRect(image_border.Rect())));
+ inspector_paint_image_event::Data(
+ node, *info.image, FloatRect(image->Rect()),
+ FloatRect(image_border.Rect())));
// Since there is no way for the developer to specify decode behavior, use
// kSync by default.
@@ -548,7 +554,7 @@ void PaintFillLayerBackground(GraphicsContext& context,
image) {
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage",
"data",
- InspectorPaintImageEvent::Data(
+ inspector_paint_image_event::Data(
node, *info.image, FloatRect(image->Rect()),
FloatRect(scrolled_paint_rect)));
context.DrawTiledImage(image,
diff --git a/chromium/third_party/blink/renderer/core/paint/box_painter_base.h b/chromium/third_party/blink/renderer/core/paint/box_painter_base.h
index f0cbcbda06f..fb43c43caae 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter_base.h
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter_base.h
@@ -67,7 +67,8 @@ class BoxPainterBase {
const LayoutRect&,
const ComputedStyle&,
bool include_logical_left_edge = true,
- bool include_logical_right_edge = true);
+ bool include_logical_right_edge = true,
+ bool background_is_skipped = true);
static void PaintInsetBoxShadowWithBorderRect(
const PaintInfo&,
diff --git a/chromium/third_party/blink/renderer/core/paint/box_reflection_utils.cc b/chromium/third_party/blink/renderer/core/paint/box_reflection_utils.cc
index 218e92a8914..520c388b6de 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_reflection_utils.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_reflection_utils.cc
@@ -10,10 +10,10 @@
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/box_reflection.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc b/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
index 35a6efa96c6..1806c4d07b5 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
@@ -68,13 +68,13 @@
#include "third_party/blink/renderer/core/paint/scrollable_area_painter.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/compositor_filter_operations.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/transforms/transform_state.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -82,30 +82,20 @@
namespace blink {
-using namespace HTMLNames;
-
-static IntRect ContentsRect(const LayoutObject& layout_object) {
+static LayoutRect ContentsRect(const LayoutObject& layout_object) {
if (!layout_object.IsBox())
- return IntRect();
- if (layout_object.IsCanvas()) {
- return PixelSnappedIntRect(
- ToLayoutHTMLCanvas(layout_object).ReplacedContentRect());
- }
- if (layout_object.IsVideo()) {
- return PixelSnappedIntRect(
- ToLayoutVideo(layout_object).ReplacedContentRect());
- }
-
- return PixelSnappedIntRect(
- ToLayoutBox(layout_object).PhysicalContentBoxRect());
+ return LayoutRect();
+ if (layout_object.IsLayoutReplaced())
+ return ToLayoutReplaced(layout_object).ReplacedContentRect();
+ return ToLayoutBox(layout_object).PhysicalContentBoxRect();
}
-static IntRect BackgroundRect(const LayoutObject& layout_object) {
+static LayoutRect BackgroundRect(const LayoutObject& layout_object) {
if (!layout_object.IsBox())
- return IntRect();
+ return LayoutRect();
const LayoutBox& box = ToLayoutBox(layout_object);
- return PixelSnappedIntRect(box.PhysicalBackgroundRect(kBackgroundClipRect));
+ return box.PhysicalBackgroundRect(kBackgroundClipRect);
}
static inline bool IsTextureLayerCanvas(const LayoutObject& layout_object) {
@@ -198,7 +188,6 @@ static FloatPoint StickyPositionOffsetForLayer(PaintLayer& layer) {
CompositedLayerMapping::CompositedLayerMapping(PaintLayer& layer)
: owning_layer_(layer),
- content_offset_in_compositing_layer_dirty_(false),
pending_update_scope_(kGraphicsLayerUpdateNone),
is_main_frame_layout_view_layer_(false),
scrolling_contents_are_empty_(false),
@@ -322,12 +311,6 @@ void CompositedLayerMapping::UpdateFilters() {
CompositorFilterOperations operations;
OwningLayer().UpdateCompositorFilterOperationsForFilter(operations);
- // If the image violates some feature policy optimized image policies, render
- // with inverted color.
- if (GetLayoutObject().IsLayoutImage() &&
- ToLayoutImage(GetLayoutObject()).ShouldInvertColor())
- operations.AppendInvertFilter(1.0f);
-
graphics_layer_->SetFilters(std::move(operations));
}
@@ -418,7 +401,7 @@ void CompositedLayerMapping::UpdateBackgroundPaintsOntoScrollingContentsLayer(
// it would be visually correct and we are using composited scrolling meaning
// we have a scrolling contents layer to paint it into.
BackgroundPaintLocation paint_location =
- owning_layer_.GetBackgroundPaintLocation();
+ GetLayoutObject().GetBackgroundPaintLocation();
bool should_paint_onto_scrolling_contents_layer =
paint_location & kBackgroundPaintInScrollingContents &&
owning_layer_.GetScrollableArea()->UsesCompositedScrolling();
@@ -444,6 +427,10 @@ void CompositedLayerMapping::UpdateBackgroundPaintsOntoScrollingContentsLayer(
}
void CompositedLayerMapping::UpdateContentsOpaque() {
+ // If there is a foreground layer, children paint into that layer and
+ // not graphics_layer_, and so don't contribute to the opaqueness of the
+ // latter.
+ bool should_check_children = !foreground_layer_.get();
if (IsTextureLayerCanvas(GetLayoutObject())) {
CanvasRenderingContext* context =
ToHTMLCanvasElement(GetLayoutObject().GetNode())->RenderingContext();
@@ -480,13 +467,14 @@ void CompositedLayerMapping::UpdateContentsOpaque() {
// this for solid color backgrounds the answer will be the same.
scrolling_contents_layer_->SetContentsOpaque(
owning_layer_.BackgroundIsKnownToBeOpaqueInRect(
- ToLayoutBox(GetLayoutObject()).PhysicalPaddingBoxRect()));
+ ToLayoutBox(GetLayoutObject()).PhysicalPaddingBoxRect(),
+ should_check_children));
- if (owning_layer_.GetBackgroundPaintLocation() &
+ if (GetLayoutObject().GetBackgroundPaintLocation() &
kBackgroundPaintInGraphicsLayer) {
graphics_layer_->SetContentsOpaque(
owning_layer_.BackgroundIsKnownToBeOpaqueInRect(
- CompositedBounds()));
+ CompositedBounds(), should_check_children));
} else {
// If we only paint the background onto the scrolling contents layer we
// are going to leave a hole in the m_graphicsLayer where the background
@@ -497,7 +485,8 @@ void CompositedLayerMapping::UpdateContentsOpaque() {
if (HasScrollingLayer())
scrolling_contents_layer_->SetContentsOpaque(false);
graphics_layer_->SetContentsOpaque(
- owning_layer_.BackgroundIsKnownToBeOpaqueInRect(CompositedBounds()));
+ owning_layer_.BackgroundIsKnownToBeOpaqueInRect(
+ CompositedBounds(), should_check_children));
}
}
}
@@ -506,10 +495,10 @@ void CompositedLayerMapping::UpdateRasterizationPolicy() {
bool transformed_rasterization_allowed =
!(owning_layer_.GetCompositingReasons() &
CompositingReason::kComboAllDirectReasons);
- graphics_layer_->ContentLayer()->SetTransformedRasterizationAllowed(
+ graphics_layer_->CcLayer()->SetTransformedRasterizationAllowed(
transformed_rasterization_allowed);
if (squashing_layer_)
- squashing_layer_->ContentLayer()->SetTransformedRasterizationAllowed(true);
+ squashing_layer_->CcLayer()->SetTransformedRasterizationAllowed(true);
}
void CompositedLayerMapping::UpdateCompositedBounds() {
@@ -518,7 +507,6 @@ void CompositedLayerMapping::UpdateCompositedBounds() {
// FIXME: if this is really needed for performance, it would be better to
// store it on Layer.
composited_bounds_ = owning_layer_.BoundingBoxForCompositing();
- content_offset_in_compositing_layer_dirty_ = true;
}
GraphicsLayer* CompositedLayerMapping::FrameContentsGraphicsLayer() const {
@@ -565,8 +553,8 @@ void CompositedLayerMapping::UpdateAfterPartResize() {
child_containment_layer_
? FloatPoint(child_containment_layer_->GetPosition())
: FloatPoint();
- document_layer->SetPosition(FloatPoint(FlooredIntPoint(
- FloatPoint(ContentsBox().Location()) - parent_position)));
+ document_layer->SetPosition(FloatPoint(RoundedIntSize(
+ ContentsBox().Location() - LayoutPoint(parent_position))));
}
}
}
@@ -1132,7 +1120,7 @@ void CompositedLayerMapping::UpdateSquashingLayerGeometry(
.InvalidatePaintIncludingNonCompositingDescendants();
TRACE_LAYER_INVALIDATION(layers[i].paint_layer,
- InspectorLayerInvalidationTrackingEvent::
+ inspector_layer_invalidation_tracking_event::
kSquashingLayerGeometryWasUpdated);
layers_needing_paint_invalidation.push_back(layers[i].paint_layer);
}
@@ -1218,8 +1206,6 @@ void CompositedLayerMapping::UpdateGraphicsLayerGeometry(
UpdateOverflowControlsHostLayerGeometry(compositing_stacking_context,
compositing_container,
graphics_layer_parent_location);
- UpdateContentsOffsetInCompositingLayer(
- snapped_offset_from_composited_ancestor, graphics_layer_parent_location);
UpdateStickyConstraints(GetLayoutObject().StyleRef());
UpdateSquashingLayerGeometry(
graphics_layer_parent_location, compositing_container,
@@ -1606,16 +1592,13 @@ void CompositedLayerMapping::UpdateChildContainmentLayerGeometry() {
void CompositedLayerMapping::UpdateChildTransformLayerGeometry() {
if (!child_transform_layer_)
return;
- const IntRect border_box =
- ToLayoutBox(owning_layer_.GetLayoutObject())
- .PixelSnappedBorderBoxRect(SubpixelAccumulation());
- child_transform_layer_->SetSize(gfx::Size(border_box.Size()));
- child_transform_layer_->SetOffsetFromLayoutObject(
- ToIntSize(border_box.Location()));
- IntPoint parent_location(
- child_transform_layer_->Parent()->OffsetFromLayoutObject());
- child_transform_layer_->SetPosition(
- FloatPoint(border_box.Location() - parent_location));
+
+ LayoutRect border_box =
+ ToLayoutBox(owning_layer_.GetLayoutObject()).BorderBoxRect();
+ border_box.Move(ContentOffsetInCompositingLayer());
+ child_transform_layer_->SetSize(gfx::Size(border_box.PixelSnappedSize()));
+ child_transform_layer_->SetOffsetFromLayoutObject(IntSize());
+ child_transform_layer_->SetPosition(FloatPoint(border_box.Location()));
}
void CompositedLayerMapping::UpdateMaskLayerGeometry() {
@@ -1913,59 +1896,6 @@ void CompositedLayerMapping::UpdateContentsRect() {
graphics_layer_->SetContentsRect(PixelSnappedIntRect(ContentsBox()));
}
-void CompositedLayerMapping::UpdateContentsOffsetInCompositingLayer(
- const IntPoint& snapped_offset_from_composited_ancestor,
- const IntPoint& graphics_layer_parent_location) {
- // m_graphicsLayer is positioned relative to our compositing ancestor
- // PaintLayer, but it's not positioned at the origin of m_owningLayer, it's
- // offset by m_contentBounds.location(). This is what
- // contentOffsetInCompositingLayer is meant to capture, roughly speaking
- // (ignoring rounding and subpixel accumulation).
- //
- // Our ancestor graphics layers in this CLM (m_graphicsLayer and potentially
- // m_ancestorClippingLayer) have pixel snapped, so if we don't adjust this
- // offset, we'll see accumulated rounding errors due to that snapping.
- //
- // In order to ensure that we account for this rounding, we compute
- // contentsOffsetInCompositingLayer in a somewhat roundabout way.
- //
- // our position = (desired position) - (inherited graphics layer offset).
- //
- // Precisely,
- // Offset = snappedOffsetFromCompositedAncestor -
- // offsetDueToAncestorGraphicsLayers (See code below)
- // = snappedOffsetFromCompositedAncestor -
- // (m_graphicsLayer->position() + graphicsLayerParentLocation)
- // = snappedOffsetFromCompositedAncestor -
- // (relativeCompositingBounds.location() -
- // graphicsLayerParentLocation +
- // graphicsLayerParentLocation)
- // (See updateMainGraphicsLayerGeometry)
- // = snappedOffsetFromCompositedAncestor -
- // relativeCompositingBounds.location()
- // = snappedOffsetFromCompositedAncestor -
- // (pixelSnappedIntRect(contentBounds.location()) +
- // snappedOffsetFromCompositedAncestor)
- // (See computeBoundsOfOwningLayer)
- // = -pixelSnappedIntRect(contentBounds.location())
- //
- // As you can see, we've ended up at the same spot
- // (-contentBounds.location()), but by subtracting off our ancestor graphics
- // layers positions, we can be sure we've accounted correctly for any pixel
- // snapping due to ancestor graphics layers.
- //
- // And drawing of composited children takes into account the subpixel
- // accumulation of this CLM already (through its own
- // graphicsLayerParentLocation it appears).
- FloatPoint offset_due_to_ancestor_graphics_layers =
- FloatPoint(graphics_layer_->GetPosition()) +
- graphics_layer_parent_location;
- content_offset_in_compositing_layer_ =
- LayoutSize(snapped_offset_from_composited_ancestor -
- offset_due_to_ancestor_graphics_layers);
- content_offset_in_compositing_layer_dirty_ = false;
-}
-
void CompositedLayerMapping::UpdateDrawsContent() {
bool in_overlay_fullscreen_video = false;
if (GetLayoutObject().IsVideo()) {
@@ -2958,12 +2888,12 @@ FloatPoint3D CompositedLayerMapping::ComputeTransformOrigin(
// Return the offset from the top-left of this compositing layer at which the
// LayoutObject's contents are painted.
LayoutSize CompositedLayerMapping::ContentOffsetInCompositingLayer() const {
- DCHECK(!content_offset_in_compositing_layer_dirty_);
- return content_offset_in_compositing_layer_;
+ return owning_layer_.SubpixelAccumulation() -
+ LayoutSize(graphics_layer_->OffsetFromLayoutObject());
}
LayoutRect CompositedLayerMapping::ContentsBox() const {
- LayoutRect contents_box = LayoutRect(ContentsRect(GetLayoutObject()));
+ LayoutRect contents_box = ContentsRect(GetLayoutObject());
contents_box.Move(ContentOffsetInCompositingLayer());
return contents_box;
}
@@ -3183,7 +3113,7 @@ void CompositedLayerMapping::DoPaintTask(
kPaintsIntoGroupedBacking) {
// FIXME: GraphicsLayers need a way to split for multicol.
PaintLayerPaintingInfo painting_info(
- paint_info.paint_layer, LayoutRect(dirty_rect), kGlobalPaintNormalPhase,
+ paint_info.paint_layer, CullRect(dirty_rect), kGlobalPaintNormalPhase,
paint_info.paint_layer->SubpixelAccumulation());
PaintLayerPainter(*paint_info.paint_layer)
.PaintLayerContents(context, painting_info, paint_layer_flags);
@@ -3196,7 +3126,7 @@ void CompositedLayerMapping::DoPaintTask(
}
} else {
PaintLayerPaintingInfo painting_info(
- paint_info.paint_layer, LayoutRect(dirty_rect), kGlobalPaintNormalPhase,
+ paint_info.paint_layer, CullRect(dirty_rect), kGlobalPaintNormalPhase,
paint_info.paint_layer->SubpixelAccumulation());
PaintLayerPainter(*paint_info.paint_layer)
.Paint(context, painting_info, paint_layer_flags);
@@ -3443,8 +3373,8 @@ void CompositedLayerMapping::PaintContents(
TRACE_EVENT1(
"devtools.timeline,rail", "Paint", "data",
- InspectorPaintEvent::Data(&owning_layer_.GetLayoutObject(),
- LayoutRect(interest_rect), graphics_layer));
+ inspector_paint_event::Data(&owning_layer_.GetLayoutObject(),
+ LayoutRect(interest_rect), graphics_layer));
PaintLayerFlags paint_layer_flags = 0;
if (graphics_layer_painting_phase & kGraphicsLayerPaintBackground)
@@ -3514,8 +3444,8 @@ void CompositedLayerMapping::PaintScrollableArea(
const IntRect& interest_rect) const {
// cull_rect is in the space of the containing scrollable area in which
// Scrollbar::Paint() will paint the scrollbar.
- CullRect cull_rect(CullRect(interest_rect),
- graphics_layer->OffsetFromLayoutObject());
+ CullRect cull_rect(interest_rect);
+ cull_rect.Move(graphics_layer->OffsetFromLayoutObject());
PaintLayerScrollableArea* scrollable_area = owning_layer_.GetScrollableArea();
if (graphics_layer == LayerForHorizontalScrollbar()) {
if (const Scrollbar* scrollbar = scrollable_area->HorizontalScrollbar())
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h b/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h
index 36c76840e91..c83e8cc41ff 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h
@@ -300,11 +300,18 @@ class CORE_EXPORT CompositedLayerMapping final : public GraphicsLayerClient {
// the background can scroll with the content). When the background is also
// opaque this allows us to composite the scroller even on low DPI as we can
// draw with subpixel anti-aliasing.
- bool BackgroundPaintsOntoScrollingContentsLayer() {
+ bool BackgroundPaintsOntoScrollingContentsLayer() const {
return background_paints_onto_scrolling_contents_layer_;
}
- bool DrawsBackgroundOntoContentLayer() {
+ // Returns true if the background paints onto the main graphics layer.
+ // In some situations, we may paint background on both the main graphics layer
+ // and the scrolling contents layer.
+ bool BackgroundPaintsOntoGraphicsLayer() const {
+ return background_paints_onto_graphics_layer_;
+ }
+
+ bool DrawsBackgroundOntoContentLayer() const {
return draws_background_onto_content_layer_;
}
@@ -455,9 +462,6 @@ class CORE_EXPORT CompositedLayerMapping final : public GraphicsLayerClient {
Color LayoutObjectBackgroundColor() const;
void UpdateBackgroundColor();
void UpdateContentsRect();
- void UpdateContentsOffsetInCompositingLayer(
- const IntPoint& snapped_offset_from_composited_ancestor,
- const IntPoint& graphics_layer_parent_location);
void UpdateAfterPartResize();
void UpdateCompositingReasons();
@@ -666,8 +670,6 @@ class CORE_EXPORT CompositedLayerMapping final : public GraphicsLayerClient {
LayoutRect composited_bounds_;
- LayoutSize content_offset_in_compositing_layer_;
-
// We keep track of the scrolling contents offset, so that when it changes we
// can notify the ScrollingCoordinator, which passes on main-thread scrolling
// updates to the compositor.
@@ -675,8 +677,6 @@ class CORE_EXPORT CompositedLayerMapping final : public GraphicsLayerClient {
const PaintLayer* clip_inheritance_ancestor_;
- unsigned content_offset_in_compositing_layer_dirty_ : 1;
-
unsigned pending_update_scope_ : 2;
unsigned is_main_frame_layout_view_layer_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc
index 5947a838062..7d2b078394a 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc
@@ -55,8 +55,17 @@ class CompositedLayerMappingTest : public RenderingTest {
RenderingTest::SetUp();
EnableCompositing();
}
+};
- void TearDown() override { RenderingTest::TearDown(); }
+// Tests the pre-BlinkGenPropertyTrees composited layer mapping code. With BGPT,
+// some layer updates are skipped (see: CLM::UpdateGraphicsLayerConfiguration
+// and CLM::UpdateStickyConstraints).
+class CompositedLayerMappingTestWithoutBGPT
+ : private ScopedBlinkGenPropertyTreesForTest,
+ public CompositedLayerMappingTest {
+ public:
+ CompositedLayerMappingTestWithoutBGPT()
+ : ScopedBlinkGenPropertyTreesForTest(false) {}
};
TEST_F(CompositedLayerMappingTest, SubpixelAccumulationChange) {
@@ -132,7 +141,7 @@ TEST_F(CompositedLayerMappingTest, SimpleInterestRect) {
"<div id='target' style='width: 200px; height: 200px; will-change: "
"transform'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -147,7 +156,7 @@ TEST_F(CompositedLayerMappingTest, TallLayerInterestRect) {
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -166,10 +175,10 @@ TEST_F(CompositedLayerMappingTest, TallCompositedScrolledLayerInterestRect) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 8000),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
@@ -184,10 +193,10 @@ TEST_F(CompositedLayerMappingTest, TallNonCompositedScrolledLayerInterestRect) {
<div style='width: 200px; height: 11000px;'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 8000),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintLayer* paint_layer = GetDocument().GetLayoutView()->Layer();
ASSERT_TRUE(paint_layer->GraphicsLayerBacking());
@@ -202,7 +211,7 @@ TEST_F(CompositedLayerMappingTest, TallLayerWholeDocumentInterestRect) {
GetDocument().GetSettings()->SetMainFrameClipsContent(false);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -223,10 +232,10 @@ TEST_F(CompositedLayerMappingTest, VerticalRightLeftWritingModeDocument) {
200px;'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(-5000, 0), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintLayer* paint_layer = GetDocument().GetLayoutView()->Layer();
ASSERT_TRUE(paint_layer->GraphicsLayerBacking());
@@ -243,7 +252,7 @@ TEST_F(CompositedLayerMappingTest, RotatedInterestRect) {
"<div id='target' style='width: 200px; height: 200px; will-change: "
"transform; transform: rotateZ(45deg)'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -257,7 +266,7 @@ TEST_F(CompositedLayerMappingTest, RotatedInterestRectNear90Degrees) {
"<div id='target' style='width: 10000px; height: 200px; will-change: "
"transform; transform: rotateY(89.9999deg)'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -304,7 +313,7 @@ TEST_F(CompositedLayerMappingTest, LargeScaleInterestRect) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -321,7 +330,7 @@ TEST_F(CompositedLayerMappingTest, PerspectiveInterestRect) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -338,7 +347,7 @@ TEST_F(CompositedLayerMappingTest, 3D90DegRotatedTallInterestRect) {
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform; transform: rotateY(90deg)'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -352,7 +361,7 @@ TEST_F(CompositedLayerMappingTest, 3D45DegRotatedTallInterestRect) {
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform; transform: rotateY(45deg)'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -366,7 +375,7 @@ TEST_F(CompositedLayerMappingTest, RotatedTallInterestRect) {
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform; transform: rotateZ(45deg)'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -380,7 +389,7 @@ TEST_F(CompositedLayerMappingTest, WideLayerInterestRect) {
"<div id='target' style='width: 10000px; height: 200px; will-change: "
"transform'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -397,7 +406,7 @@ TEST_F(CompositedLayerMappingTest, FixedPositionInterestRect) {
"<div id='target' style='width: 300px; height: 400px; will-change: "
"transform; position: fixed; top: 100px; left: 200px;'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -413,7 +422,7 @@ TEST_F(CompositedLayerMappingTest, LayerOffscreenInterestRect) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -433,7 +442,7 @@ TEST_F(CompositedLayerMappingTest, ScrollingLayerInterestRect) {
<div style='width: 100px; height: 10000px'></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -457,7 +466,7 @@ TEST_F(CompositedLayerMappingTest, ClippedBigLayer) {
transform'></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -467,7 +476,7 @@ TEST_F(CompositedLayerMappingTest, ClippedBigLayer) {
RecomputeInterestRect(paint_layer->GraphicsLayerBacking()));
}
-TEST_F(CompositedLayerMappingTest, ClippingMaskLayer) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT, ClippingMaskLayer) {
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
return;
@@ -481,7 +490,7 @@ TEST_F(CompositedLayerMappingTest, ClippingMaskLayer) {
SetBodyInnerHTML("<video id='video' src='x' style='" +
style_without_clipping + "'></video>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* video_element = GetDocument().getElementById("video");
GraphicsLayer* graphics_layer =
ToLayoutBoxModelObject(video_element->GetLayoutObject())
@@ -490,18 +499,18 @@ TEST_F(CompositedLayerMappingTest, ClippingMaskLayer) {
EXPECT_FALSE(graphics_layer->MaskLayer());
EXPECT_FALSE(graphics_layer->ContentsClippingMaskLayer());
- video_element->setAttribute(HTMLNames::styleAttr, style_with_border_radius);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ video_element->setAttribute(html_names::kStyleAttr, style_with_border_radius);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(graphics_layer->MaskLayer());
EXPECT_TRUE(graphics_layer->ContentsClippingMaskLayer());
- video_element->setAttribute(HTMLNames::styleAttr, style_with_clip_path);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ video_element->setAttribute(html_names::kStyleAttr, style_with_clip_path);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(graphics_layer->MaskLayer());
EXPECT_FALSE(graphics_layer->ContentsClippingMaskLayer());
- video_element->setAttribute(HTMLNames::styleAttr, style_without_clipping);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ video_element->setAttribute(html_names::kStyleAttr, style_without_clipping);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(graphics_layer->MaskLayer());
EXPECT_FALSE(graphics_layer->ContentsClippingMaskLayer());
}
@@ -514,7 +523,7 @@ TEST_F(CompositedLayerMappingTest, ScrollContentsFlattenForScroller) {
<div style='width: 1000px; height: 1000px;'>Foo</div>Foo</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
@@ -623,7 +632,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
<div id='div' style='width: 100px; height: 10000px'>Text</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GraphicsLayer* root_scrolling_layer =
GetDocument().GetLayoutView()->Layer()->GraphicsLayerBacking();
EXPECT_EQ(IntRect(0, 0, 800, 4600),
@@ -631,7 +640,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 300),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Still use the previous interest rect because the recomputed rect hasn't
// changed enough.
EXPECT_EQ(IntRect(0, 0, 800, 4900),
@@ -641,7 +650,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 600),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Use recomputed interest rect because it changed enough.
EXPECT_EQ(IntRect(0, 0, 800, 5200),
RecomputeInterestRect(root_scrolling_layer));
@@ -650,7 +659,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 5400),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 1400, 800, 8600),
RecomputeInterestRect(root_scrolling_layer));
EXPECT_EQ(IntRect(0, 1400, 800, 8600),
@@ -658,7 +667,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 9000),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Still use the previous interest rect because it contains the recomputed
// interest rect.
EXPECT_EQ(IntRect(0, 5000, 800, 5000),
@@ -669,7 +678,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 2000),
kProgrammaticScroll);
// Use recomputed interest rect because it changed enough.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 0, 800, 6600),
RecomputeInterestRect(root_scrolling_layer));
EXPECT_EQ(IntRect(0, 0, 800, 6600),
@@ -685,14 +694,14 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnShrunkenViewport) {
<div id='div' style='width: 100px; height: 10000px'>Text</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
GraphicsLayer* root_scrolling_layer =
GetDocument().GetLayoutView()->Layer()->GraphicsLayerBacking();
EXPECT_EQ(IntRect(0, 0, 800, 4600),
PreviousInterestRect(root_scrolling_layer));
GetDocument().View()->SetFrameRect(IntRect(0, 0, 800, 60));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Repaint required, so interest rect should be updated to shrunken size.
EXPECT_EQ(IntRect(0, 0, 800, 4060),
RecomputeInterestRect(root_scrolling_layer));
@@ -715,33 +724,33 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnScroll) {
</div
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* scroller = GetDocument().getElementById("scroller");
GraphicsLayer* scrolling_layer =
scroller->GetLayoutBox()->Layer()->GraphicsLayerBacking();
EXPECT_EQ(IntRect(0, 0, 400, 4400), PreviousInterestRect(scrolling_layer));
scroller->setScrollTop(300);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Still use the previous interest rect because the recomputed rect hasn't
// changed enough.
EXPECT_EQ(IntRect(0, 0, 400, 4700), RecomputeInterestRect(scrolling_layer));
EXPECT_EQ(IntRect(0, 0, 400, 4400), PreviousInterestRect(scrolling_layer));
scroller->setScrollTop(600);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Use recomputed interest rect because it changed enough.
EXPECT_EQ(IntRect(0, 0, 400, 5000), RecomputeInterestRect(scrolling_layer));
EXPECT_EQ(IntRect(0, 0, 400, 5000), PreviousInterestRect(scrolling_layer));
scroller->setScrollTop(5600);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 1600, 400, 8400),
RecomputeInterestRect(scrolling_layer));
EXPECT_EQ(IntRect(0, 1600, 400, 8400), PreviousInterestRect(scrolling_layer));
scroller->setScrollTop(9000);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Still use the previous interest rect because it contains the recomputed
// interest rect.
EXPECT_EQ(IntRect(0, 5000, 400, 5000),
@@ -750,7 +759,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectChangeOnScroll) {
scroller->setScrollTop(2000);
// Use recomputed interest rect because it changed enough.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 0, 400, 6400), RecomputeInterestRect(scrolling_layer));
EXPECT_EQ(IntRect(0, 0, 400, 6400), PreviousInterestRect(scrolling_layer));
}
@@ -771,22 +780,22 @@ TEST_F(CompositedLayerMappingTest,
</div
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* scroller = GetDocument().getElementById("scroller");
GraphicsLayer* scrolling_layer =
scroller->GetLayoutBox()->Layer()->GraphicsLayerBacking();
scroller->setScrollTop(5400);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
scroller->setScrollTop(9400);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 5400, 400, 4600),
RecomputeInterestRect(scrolling_layer));
EXPECT_EQ(IntRect(0, 5400, 400, 4600), PreviousInterestRect(scrolling_layer));
// Paint invalidation and repaint should change previous paint interest rect.
GetDocument().getElementById("content")->setTextContent("Change");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 5400, 400, 4600),
RecomputeInterestRect(scrolling_layer));
EXPECT_EQ(IntRect(0, 5400, 400, 4600), PreviousInterestRect(scrolling_layer));
@@ -868,7 +877,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectOfIframeInScrolledDiv) {
// Scroll 8000 pixels down to move the iframe into view.
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 8000.0), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* target = ChildDocument().getElementById("target");
ASSERT_TRUE(target);
@@ -894,12 +903,12 @@ TEST_F(CompositedLayerMappingTest, InterestRectOfScrolledIframe) {
"<style>body { margin: 0; } #target { width: 200px; "
"height: 8000px;}</style><div id=target></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Scroll 7500 pixels down to bring the scrollable area to the bottom.
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 7500.0), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(ChildDocument().View()->GetLayoutView()->HasLayer());
EXPECT_EQ(IntRect(0, 3500, 500, 4500),
@@ -927,13 +936,13 @@ TEST_F(CompositedLayerMappingTest, InterestRectOfIframeWithContentBoxOffset) {
"<style>body { margin: 0; } #target { width: 200px; "
"height: 8000px;}</style> <div id=target></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Scroll 3000 pixels down to bring the scrollable area to somewhere in the
// middle.
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 3000.0), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(ChildDocument().View()->GetLayoutView()->HasLayer());
EXPECT_EQ(IntRect(0, 0, 500, 7500),
@@ -965,7 +974,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectOfIframeWithFixedContents) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* fixed = ChildDocument().getElementById("fixed")->GetLayoutObject();
auto* graphics_layer = fixed->EnclosingLayer()->GraphicsLayerBacking(fixed);
@@ -975,7 +984,7 @@ TEST_F(CompositedLayerMappingTest, InterestRectOfIframeWithFixedContents) {
ChildDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 3000.0), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Because the fixed element does not scroll, the interest rect is unchanged.
EXPECT_EQ(IntRect(1000, 0, 4400, 300), RecomputeInterestRect(graphics_layer));
@@ -994,14 +1003,14 @@ TEST_F(CompositedLayerMappingTest, ScrolledFixedPositionInterestRect) {
<div id="forcescroll" style="height: 2000px;"></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* fixed = GetDocument().getElementById("fixed")->GetLayoutObject();
auto* graphics_layer = fixed->EnclosingLayer()->GraphicsLayerBacking(fixed);
EXPECT_EQ(IntRect(0, 500, 100, 4030), RecomputeInterestRect(graphics_layer));
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(0.0, 200.0), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Because the fixed element does not scroll, the interest rect is unchanged.
EXPECT_EQ(IntRect(0, 500, 100, 4030), RecomputeInterestRect(graphics_layer));
@@ -1044,7 +1053,7 @@ TEST_F(CompositedLayerMappingTest,
GetDocument().getElementById("negative-composited-child");
negative_composited_child->parentNode()->RemoveChild(
negative_composited_child);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
mapping = ToLayoutBlock(GetLayoutObjectByElementId("container"))
->Layer()
@@ -1071,7 +1080,7 @@ TEST_F(CompositedLayerMappingTest,
<div id="target"><div id="scrolled"></div></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* element = GetDocument().getElementById("target");
PaintLayer* paint_layer =
@@ -1086,8 +1095,8 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_TRUE(mapping->DecorationOutlineLayer());
// No decoration outline layer is created when not composited scrolling.
- element->setAttribute(HTMLNames::styleAttr, "overflow: visible;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ element->setAttribute(html_names::kStyleAttr, "overflow: visible;");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
@@ -1108,7 +1117,7 @@ TEST_F(CompositedLayerMappingTest,
<div id="scroller"><div id="scrolled"></div></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -1120,8 +1129,8 @@ TEST_F(CompositedLayerMappingTest,
// The decoration outline layer is created when composited scrolling
// with an outline drawn over the composited scrolling region.
- scroller->setAttribute(HTMLNames::styleAttr, "outline-offset: -2px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scroller->setAttribute(html_names::kStyleAttr, "outline-offset: -2px;");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
@@ -1131,8 +1140,8 @@ TEST_F(CompositedLayerMappingTest,
// The decoration outline layer is destroyed when the scrolling region
// will not be covered up by the outline.
- scroller->removeAttribute(HTMLNames::styleAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scroller->removeAttribute(html_names::kStyleAttr);
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
@@ -1146,23 +1155,21 @@ TEST_F(CompositedLayerMappingTest,
true);
SetBodyInnerHTML(R"HTML(
<div id='container' style='overflow: scroll; width: 300px; height:
- 300px; background: white; will-change: transform;'>
- <div style='background-color: blue; clip-path: circle(600px at 1000px 1000px);
- width: 2000px; height:
- 2000px;'></div>
+ 300px; background: white; will-change: transform;'>
+ <div style='background-color: blue; width: 2000px; height: 2000px;
+ clip-path: circle(600px at 1000px 1000px);'></div>
</div>
)HTML");
- PaintLayer* layer =
- ToLayoutBlock(GetLayoutObjectByElementId("container"))->Layer();
+ const auto* container = ToLayoutBox(GetLayoutObjectByElementId("container"));
EXPECT_EQ(kBackgroundPaintInScrollingContents,
- layer->GetBackgroundPaintLocation());
+ container->GetBackgroundPaintLocation());
// We currently don't use composited scrolling when the container has a
// border-radius so even though we can paint the background onto the scrolling
// contents layer we don't have a scrolling contents layer to paint into in
// this case.
- CompositedLayerMapping* mapping = layer->GetCompositedLayerMapping();
+ const auto* mapping = container->Layer()->GetCompositedLayerMapping();
EXPECT_FALSE(mapping->HasScrollingLayer());
EXPECT_FALSE(mapping->BackgroundPaintsOntoScrollingContentsLayer());
}
@@ -1177,35 +1184,35 @@ TEST_F(CompositedLayerMappingTest,
// direction to compensate. To make this a little clearer, for the first
// example here the layer positions are calculated as:
//
- // m_graphicsLayer x = left_pos - shadow_spread + shadow_x_offset
+ // graphics_layer_ x = left_pos - shadow_spread + shadow_x_offset
// = 50 - 10 - 10
// = 30
//
- // m_graphicsLayer y = top_pos - shadow_spread + shadow_y_offset
+ // graphics_layer_ y = top_pos - shadow_spread + shadow_y_offset
// = 50 - 10 + 0
// = 40
//
- // contents x = 50 - m_graphicsLayer x = 50 - 30 = 20
- // contents y = 50 - m_graphicsLayer y = 50 - 40 = 10
+ // contents x = 50 - graphics_layer_ x = 50 - 30 = 20
+ // contents y = 50 - graphics_layer_ y = 50 - 40 = 10
//
// The reason that perspective matters is that it affects which 'contents'
- // layer is offset; m_childTransformLayer when using perspective, or
- // m_scrollingLayer when there is no perspective.
+ // layer is offset; child_transform_layer_ when using perspective, or
+ // scrolling_layer_ when there is no perspective.
- SetBodyInnerHTML(
- "<div id='scroller' style='position: absolute; top: 50px; left: 50px; "
- "width: 400px; height: 245px; overflow: auto; will-change: transform; "
- "box-shadow: -10px 0 0 10px; perspective: 1px;'>"
- " <div style='position: absolute; top: 50px; bottom: 0; width: 200px; "
- "height: 200px;'></div>"
- "</div>"
-
- "<div id='scroller2' style='position: absolute; top: 400px; left: 50px; "
- "width: 400px; height: 245px; overflow: auto; will-change: transform; "
- "box-shadow: -10px 0 0 10px;'>"
- " <div style='position: absolute; top: 50px; bottom: 0; width: 200px; "
- "height: 200px;'></div>"
- "</div>");
+ SetBodyInnerHTML(R"HTML(
+ <div id='scroller' style='position: absolute; top: 50px; left: 50px;
+ width: 400px; height: 245px; overflow: auto; will-change: transform;
+ box-shadow: -10px 0 0 10px; perspective: 1px;'>
+ <div style='position: absolute; top: 50px; bottom: 0; width: 200px;
+ height: 200px;'></div>
+ </div>
+ <div id='scroller2' style='position: absolute; top: 400px; left: 50px;
+ width: 400px; height: 245px; overflow: auto; will-change: transform;
+ box-shadow: -10px 0 0 10px;'>
+ <div style='position: absolute; top: 50px; bottom: 0; width: 200px;
+ height: 200px;'></div>
+ </div>
+ )HTML");
CompositedLayerMapping* mapping =
ToLayoutBlock(GetLayoutObjectByElementId("scroller"))
@@ -1252,7 +1259,8 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_FLOAT_EQ(10, scrolling_layer2->GetPosition().y());
}
-TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClippingMaskLayerUpdates) {
SetBodyInnerHTML(R"HTML(
<style>
#ancestor { width: 100px; height: 100px; overflow: hidden; }
@@ -1262,7 +1270,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ancestor = GetDocument().getElementById("ancestor");
ASSERT_TRUE(ancestor);
@@ -1281,8 +1289,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
ASSERT_FALSE(child_paint_layer);
// Making the child conposited causes creation of an AncestorClippingLayer.
- child->setAttribute(HTMLNames::styleAttr, "will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ child->setAttribute(html_names::kStyleAttr, "will-change: transform");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
CompositedLayerMapping* child_mapping =
@@ -1294,8 +1302,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
// Adding border radius to the ancestor requires an
// ancestorClippingMaskLayer for the child
- ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 40px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "border-radius: 40px;");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1306,8 +1314,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
// Removing the border radius should remove the ancestorClippingMaskLayer
// for the child
- ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 0px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "border-radius: 0px;");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1317,13 +1325,13 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
// Add border radius back so we can test one more case
- ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 40px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "border-radius: 40px;");
+ UpdateAllLifecyclePhasesForTest();
// Now change the overflow to remove the need for an ancestor clip
// on the child
- ancestor->setAttribute(HTMLNames::styleAttr, "overflow: visible");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "overflow: visible");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1332,7 +1340,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClippingMaskLayerSiblingUpdates) {
SetBodyInnerHTML(R"HTML(
<style>
#ancestor { width: 200px; height: 200px; overflow: hidden; }
@@ -1346,7 +1355,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
<div id='child2'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ancestor = GetDocument().getElementById("ancestor");
ASSERT_TRUE(ancestor);
@@ -1377,8 +1386,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
ASSERT_FALSE(child2_mapping);
// Making child1 composited causes creation of an AncestorClippingLayer.
- child1->setAttribute(HTMLNames::styleAttr, "will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ child1->setAttribute(html_names::kStyleAttr, "will-change: transform");
+ UpdateAllLifecyclePhasesForTest();
child1_paint_layer =
ToLayoutBoxModelObject(child1->GetLayoutObject())->Layer();
ASSERT_TRUE(child1_paint_layer);
@@ -1395,8 +1404,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
// Adding border radius to the ancestor requires an
// ancestorClippingMaskLayer for child1
- ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 40px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "border-radius: 40px;");
+ UpdateAllLifecyclePhasesForTest();
child1_paint_layer =
ToLayoutBoxModelObject(child1->GetLayoutObject())->Layer();
ASSERT_TRUE(child1_paint_layer);
@@ -1413,8 +1422,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
// Making child2 composited causes creation of an AncestorClippingLayer
// and a mask layer.
- child2->setAttribute(HTMLNames::styleAttr, "will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ child2->setAttribute(html_names::kStyleAttr, "will-change: transform");
+ UpdateAllLifecyclePhasesForTest();
child1_paint_layer =
ToLayoutBoxModelObject(child1->GetLayoutObject())->Layer();
ASSERT_TRUE(child1_paint_layer);
@@ -1434,8 +1443,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
// Removing will-change: transform on child1 should result in the removal
// of all clipping and masking layers
- child1->setAttribute(HTMLNames::styleAttr, "will-change: none");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ child1->setAttribute(html_names::kStyleAttr, "will-change: none");
+ UpdateAllLifecyclePhasesForTest();
child1_paint_layer =
ToLayoutBoxModelObject(child1->GetLayoutObject())->Layer();
ASSERT_TRUE(child1_paint_layer);
@@ -1452,8 +1461,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
// Now change the overflow to remove the need for an ancestor clip
// on the children
- ancestor->setAttribute(HTMLNames::styleAttr, "overflow: visible");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "overflow: visible");
+ UpdateAllLifecyclePhasesForTest();
child1_paint_layer =
ToLayoutBoxModelObject(child1->GetLayoutObject())->Layer();
ASSERT_TRUE(child1_paint_layer);
@@ -1468,7 +1477,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerSiblingUpdates) {
EXPECT_FALSE(child2_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClippingMaskLayerGrandchildUpdates) {
SetBodyInnerHTML(R"HTML(
<style>
#ancestor { width: 200px; height: 200px; overflow: hidden; }
@@ -1483,7 +1493,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ancestor = GetDocument().getElementById("ancestor");
ASSERT_TRUE(ancestor);
@@ -1514,8 +1524,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
ASSERT_FALSE(grandchild_mapping);
// Making grandchild composited causes creation of an AncestorClippingLayer.
- grandchild->setAttribute(HTMLNames::styleAttr, "will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ grandchild->setAttribute(html_names::kStyleAttr, "will-change: transform");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1531,8 +1541,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
// Adding border radius to the ancestor requires an
// ancestorClippingMaskLayer for grandchild
- ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 40px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "border-radius: 40px;");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1549,9 +1559,9 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
// Moving the grandchild out of the clip region should result in removal
// of the mask layer. It also removes the grandchild from its own mapping
// because it is now squashed.
- grandchild->setAttribute(HTMLNames::styleAttr,
+ grandchild->setAttribute(html_names::kStyleAttr,
"left: 250px; will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1567,8 +1577,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
// Now change the overflow to remove the need for an ancestor clip
// on the children
- ancestor->setAttribute(HTMLNames::styleAttr, "overflow: visible");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ancestor->setAttribute(html_names::kStyleAttr, "overflow: visible");
+ UpdateAllLifecyclePhasesForTest();
child_paint_layer = ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
ASSERT_TRUE(child_paint_layer);
child_mapping = child_paint_layer->GetCompositedLayerMapping();
@@ -1581,7 +1591,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClippingMaskLayerGrandchildUpdates) {
EXPECT_FALSE(grandchild_mapping->AncestorClippingLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredByBorderRadius) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClipMaskRequiredByBorderRadius) {
// Verify that we create the mask layer when the child is contained within
// the rectangular clip but not contained within the rounded rect clip.
SetBodyInnerHTML(R"HTML(
@@ -1598,7 +1609,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredByBorderRadius) {
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ancestor = GetDocument().getElementById("ancestor");
ASSERT_TRUE(ancestor);
@@ -1623,7 +1634,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredByBorderRadius) {
EXPECT_TRUE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskNotRequiredByNestedBorderRadius) {
// This case has the child within all ancestors and does not require a
// mask.
@@ -1646,7 +1657,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1661,7 +1672,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskRequiredByParentBorderRadius) {
// This case has the child within the grandparent but not the parent, and does
// require a mask so that the parent will clip the corners.
@@ -1684,7 +1695,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1702,7 +1713,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_EQ(120, layer_size.height());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskNotRequiredByParentBorderRadius) {
// This case has the child within the grandparent but not the parent, and does
// not require a mask because the parent does not have border radius
@@ -1725,7 +1736,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1740,7 +1751,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskRequiredByGrandparentBorderRadius1) {
// This case has the child clipped by the grandparent border radius but not
// the parent, and requires a mask to clip to the grandparent. Although in
@@ -1765,7 +1776,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1783,7 +1794,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_EQ(120, layer_size.height());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskRequiredByGrandparentBorderRadius2) {
// Similar to the previous case, but here we really do need the mask.
SetBodyInnerHTML(R"HTML(
@@ -1805,7 +1816,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1823,7 +1834,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_EQ(160, layer_size.height());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskNotRequiredByBorderRadiusInside) {
// Verify that we do not create the mask layer when the child is contained
// within the rounded rect clip.
@@ -1841,7 +1852,7 @@ TEST_F(CompositedLayerMappingTest,
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ancestor = GetDocument().getElementById("ancestor");
ASSERT_TRUE(ancestor);
@@ -1866,7 +1877,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskNotRequiredByBorderRadiusOutside) {
// Verify that we do not create the mask layer when the child is outside
// the ancestors rectangular clip.
@@ -1884,7 +1895,7 @@ TEST_F(CompositedLayerMappingTest,
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* ancestor = GetDocument().getElementById("ancestor");
ASSERT_TRUE(ancestor);
@@ -1909,7 +1920,8 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToScaleUp) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClipMaskRequiredDueToScaleUp) {
// Verify that we include the mask when the untransformed child does not
// intersect the border radius but the transformed child does. Here the
// child is inside the parent and scaled to expand to be clipped.
@@ -1928,7 +1940,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToScaleUp) {
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1943,7 +1955,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToScaleUp) {
EXPECT_TRUE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClipMaskNotRequiredDueToScaleDown) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClipMaskNotRequiredDueToScaleDown) {
// Verify that we exclude the mask when the untransformed child does
// intersect the border radius but the transformed child does not. Here the
// child is bigger than the parent and scaled down such that it does not
@@ -1963,7 +1976,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskNotRequiredDueToScaleDown) {
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -1978,7 +1991,8 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskNotRequiredDueToScaleDown) {
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToTranslateInto) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClipMaskRequiredDueToTranslateInto) {
// Verify that we include the mask when the untransformed child does not
// intersect the border radius but the transformed child does. Here the
// child is outside the parent and translated to be clipped.
@@ -1997,7 +2011,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToTranslateInto) {
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -2012,7 +2026,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToTranslateInto) {
EXPECT_TRUE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskNotRequiredDueToTranslateOut) {
// Verify that we exclude the mask when the untransformed child does
// intersect the border radius but the transformed child does not. Here the
@@ -2032,7 +2046,7 @@ TEST_F(CompositedLayerMappingTest,
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -2047,7 +2061,8 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_FALSE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToRotation) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ AncestorClipMaskRequiredDueToRotation) {
// Verify that we include the mask when the untransformed child does not
// intersect the border radius but the transformed child does. Here the
// child is just within the mask-not-required area but when rotated requires
@@ -2067,7 +2082,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToRotation) {
<div id='child'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -2082,7 +2097,7 @@ TEST_F(CompositedLayerMappingTest, AncestorClipMaskRequiredDueToRotation) {
EXPECT_TRUE(child_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskRequiredByBorderRadiusWithCompositedDescendant) {
// This case has the child and grandchild within the ancestors and would
// in principle not need a mask, but does because we cannot efficiently
@@ -2106,7 +2121,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* parent = GetDocument().getElementById("parent");
ASSERT_TRUE(parent);
@@ -2121,7 +2136,7 @@ TEST_F(CompositedLayerMappingTest,
EXPECT_TRUE(parent_mapping->AncestorClippingMaskLayer());
}
-TEST_F(CompositedLayerMappingTest,
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
AncestorClipMaskGrandparentBorderRadiusCompositedDescendant) {
// This case has the child clipped by the grandparent border radius but not
// the parent, and does not itself require a mask to clip to the grandparent.
@@ -2150,7 +2165,7 @@ TEST_F(CompositedLayerMappingTest,
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
ASSERT_TRUE(child);
@@ -2232,7 +2247,7 @@ TEST_F(CompositedLayerMappingTest, StickyPositionNotSquashed) {
PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea();
scrollable_area->ScrollToAbsolutePosition(
FloatPoint(scrollable_area->ScrollPosition().Y(), 100));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Now that sticky2 and sticky3 overlap sticky1 they will be promoted, but
// they should not be squashed into the same layer because they scroll with
@@ -2275,7 +2290,7 @@ TEST_F(CompositedLayerMappingTest,
PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea();
scrollable_area->ScrollToAbsolutePosition(
FloatPoint(scrollable_area->ScrollPosition().Y(), 100));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// On the blink side, a sticky offset of (0, 100) should have been applied to
// the sticky element.
@@ -2323,7 +2338,7 @@ TEST_F(CompositedLayerMappingTest,
ASSERT_TRUE(scrollable_area);
scrollable_area->ScrollToAbsolutePosition(
FloatPoint(scrollable_area->ScrollPosition().Y(), 100));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FLOAT_EQ(0, main_graphics_layer->GetPosition().x());
EXPECT_FLOAT_EQ(100, main_graphics_layer->GetPosition().y());
@@ -2346,8 +2361,8 @@ TEST_F(CompositedLayerMappingTest,
GraphicsLayer* target_graphics_layer =
target_layer ? target_layer->GraphicsLayerBacking() : nullptr;
ASSERT_TRUE(target_graphics_layer);
- EXPECT_FALSE(target_graphics_layer->ContentLayer()
- ->transformed_rasterization_allowed());
+ EXPECT_FALSE(
+ target_graphics_layer->CcLayer()->transformed_rasterization_allowed());
}
{
LayoutObject* target = GetLayoutObjectByElementId("target2");
@@ -2356,8 +2371,8 @@ TEST_F(CompositedLayerMappingTest,
GraphicsLayer* target_graphics_layer =
target_layer ? target_layer->GraphicsLayerBacking() : nullptr;
ASSERT_TRUE(target_graphics_layer);
- EXPECT_FALSE(target_graphics_layer->ContentLayer()
- ->transformed_rasterization_allowed());
+ EXPECT_FALSE(
+ target_graphics_layer->CcLayer()->transformed_rasterization_allowed());
}
{
LayoutObject* target = GetLayoutObjectByElementId("target3");
@@ -2366,8 +2381,8 @@ TEST_F(CompositedLayerMappingTest,
GraphicsLayer* target_graphics_layer =
target_layer ? target_layer->GraphicsLayerBacking() : nullptr;
ASSERT_TRUE(target_graphics_layer);
- EXPECT_FALSE(target_graphics_layer->ContentLayer()
- ->transformed_rasterization_allowed());
+ EXPECT_FALSE(
+ target_graphics_layer->CcLayer()->transformed_rasterization_allowed());
}
}
@@ -2389,14 +2404,15 @@ TEST_F(CompositedLayerMappingTest, TransformedRasterizationForInlineTransform) {
GraphicsLayer* target_graphics_layer =
target_layer ? target_layer->GraphicsLayerBacking() : nullptr;
ASSERT_TRUE(target_graphics_layer);
- EXPECT_TRUE(target_graphics_layer->ContentLayer()
- ->transformed_rasterization_allowed());
+ EXPECT_TRUE(
+ target_graphics_layer->CcLayer()->transformed_rasterization_allowed());
}
// This tests that when the scroller becomes no longer scrollable if a sticky
// element is promoted for another reason we do remove its composited sticky
// constraint as it doesn't need to move on the compositor.
-TEST_F(CompositedLayerMappingTest, CompositedStickyConstraintRemovedAndAdded) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT,
+ CompositedStickyConstraintRemovedAndAdded) {
SetBodyInnerHTML(R"HTML(
<style>
.scroller { overflow: auto; height: 200px; }
@@ -2408,7 +2424,7 @@ TEST_F(CompositedLayerMappingTest, CompositedStickyConstraintRemovedAndAdded) {
<div id='spacer' style='height: 2000px;'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintLayer* sticky_layer =
ToLayoutBoxModelObject(GetLayoutObjectByElementId("sticky"))->Layer();
EXPECT_TRUE(sticky_layer->GraphicsLayerBacking()
@@ -2417,9 +2433,9 @@ TEST_F(CompositedLayerMappingTest, CompositedStickyConstraintRemovedAndAdded) {
.is_sticky);
// Make the scroller no longer scrollable.
- GetDocument().getElementById("spacer")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("spacer")->setAttribute(html_names::kStyleAttr,
"height: 0;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The sticky position element is composited due to a compositing trigger but
// should no longer have a sticky position constraint on the compositor.
@@ -2431,9 +2447,9 @@ TEST_F(CompositedLayerMappingTest, CompositedStickyConstraintRemovedAndAdded) {
.is_sticky);
// Make the scroller scrollable again.
- GetDocument().getElementById("spacer")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("spacer")->setAttribute(html_names::kStyleAttr,
"height: 2000px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
sticky_layer =
ToLayoutBoxModelObject(GetLayoutObjectByElementId("sticky"))->Layer();
@@ -2463,7 +2479,7 @@ TEST_F(CompositedLayerMappingTest, ScrollingContainerBoundsChange) {
</div
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* scrollerElement = GetDocument().getElementById("scroller");
LayoutBoxModelObject* scroller =
ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"));
@@ -2475,21 +2491,21 @@ TEST_F(CompositedLayerMappingTest, ScrollingContainerBoundsChange) {
EXPECT_EQ(100, scrolling_layer->scroll_container_bounds().height());
scrollerElement->setScrollTop(300);
- scrollerElement->setAttribute(HTMLNames::styleAttr, "max-height: 25px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scrollerElement->setAttribute(html_names::kStyleAttr, "max-height: 25px;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50, scrolling_layer->CurrentScrollOffset().y());
EXPECT_EQ(150, scrolling_layer->bounds().height());
EXPECT_EQ(25, scrolling_layer->scroll_container_bounds().height());
- scrollerElement->setAttribute(HTMLNames::styleAttr, "max-height: 300px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scrollerElement->setAttribute(html_names::kStyleAttr, "max-height: 300px;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(50, scrolling_layer->CurrentScrollOffset().y());
EXPECT_EQ(150, scrolling_layer->bounds().height());
EXPECT_EQ(100, scrolling_layer->scroll_container_bounds().height());
}
TEST_F(CompositedLayerMappingTest, MainFrameLayerBackgroundColor) {
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(Color::kWhite, GetDocument().View()->BaseBackgroundColor());
auto* view_layer =
GetDocument().GetLayoutView()->Layer()->GraphicsLayerBacking();
@@ -2497,9 +2513,9 @@ TEST_F(CompositedLayerMappingTest, MainFrameLayerBackgroundColor) {
Color base_background(255, 0, 0);
GetDocument().View()->SetBaseBackgroundColor(base_background);
- GetDocument().body()->setAttribute(HTMLNames::styleAttr,
+ GetDocument().body()->setAttribute(html_names::kStyleAttr,
"background: rgba(0, 255, 0, 0.5)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(base_background, GetDocument().View()->BaseBackgroundColor());
EXPECT_EQ(Color(127, 128, 0, 255), view_layer->BackgroundColor());
}
@@ -2524,8 +2540,8 @@ TEST_F(CompositedLayerMappingTest, ScrollingLayerBackgroundColor) {
EXPECT_EQ(Color::kTransparent, graphics_layer->BackgroundColor());
EXPECT_EQ(Color::kTransparent, scrolling_contents_layer->BackgroundColor());
- target->setAttribute(HTMLNames::classAttr, "color");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kClassAttr, "color");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(Color(0, 0, 255), graphics_layer->BackgroundColor());
EXPECT_EQ(Color(0, 0, 255), scrolling_contents_layer->BackgroundColor());
}
@@ -2545,7 +2561,7 @@ TEST_F(CompositedLayerMappingTest, ClipPathNoChildContainmentLayer) {
ASSERT_FALSE(mapping->ClippingLayer());
}
-TEST_F(CompositedLayerMappingTest, ForegroundLayerSizing) {
+TEST_F(CompositedLayerMappingTestWithoutBGPT, ForegroundLayerSizing) {
// This test verifies the foreground layer is sized to the clip rect.
SetBodyInnerHTML(R"HTML(
<div id='target' style='position:relative; z-index:0; width:100px;
@@ -2600,7 +2616,7 @@ TEST_F(CompositedLayerMappingTest, ScrollLayerSizingSubpixelAccumulation) {
<div id="space"></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* mapping = ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"))
->Layer()
->GetCompositedLayerMapping();
@@ -2634,7 +2650,7 @@ TEST_F(CompositedLayerMappingTest, SquashingScroll) {
GetDocument().View()->LayoutViewport()->ScrollBy(ScrollOffset(0, 25),
kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
LayoutPoint(),
@@ -2660,7 +2676,7 @@ TEST_F(CompositedLayerMappingTest, SquashingScrollInterestRect) {
GetDocument().View()->LayoutViewport()->ScrollBy(ScrollOffset(0, 5000),
kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(0, 1000, 200, 5000),
squashed->GroupedMapping()->SquashingLayer()->InterestRect());
@@ -2696,49 +2712,60 @@ transform'></div>
scroller_element->setScrollTop(300);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// 100px down from squashing's main graphics layer.
EXPECT_EQ(FloatPoint(0, 100),
squashed->GraphicsLayerBacking()->GetPosition());
}
-TEST_F(CompositedLayerMappingTest, ImageWithInvertFilterLayer) {
- SetBodyInnerHTML("<img id='image' style='will-change: transform;' src='x'>");
- ToLayoutImage(GetLayoutObjectByElementId("image"))
- ->UpdateShouldInvertColorForTest(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
- cc::FilterOperations filters;
- filters.Append(cc::FilterOperation::CreateInvertFilter(1.0f));
- EXPECT_EQ(filters, ToLayoutBoxModelObject(GetLayoutObjectByElementId("image"))
- ->Layer()
- ->GraphicsLayerBacking()
- ->CcLayer()
- ->filters());
-}
-
-TEST_F(CompositedLayerMappingTest, ImageWithInvertFilterLayerUpdated) {
- SetBodyInnerHTML("<img id='image' style='will-change: transform;' src='x'>");
- ToLayoutImage(GetLayoutObjectByElementId("image"))
- ->UpdateShouldInvertColorForTest(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
- cc::FilterOperations filters0, filters1;
- filters0.Append(cc::FilterOperation::CreateInvertFilter(1.0f));
- EXPECT_EQ(filters0,
- ToLayoutBoxModelObject(GetLayoutObjectByElementId("image"))
- ->Layer()
- ->GraphicsLayerBacking()
- ->CcLayer()
- ->filters());
- ToLayoutImage(GetLayoutObjectByElementId("image"))
- ->UpdateShouldInvertColorForTest(false);
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_EQ(filters1,
- ToLayoutBoxModelObject(GetLayoutObjectByElementId("image"))
- ->Layer()
- ->GraphicsLayerBacking()
- ->CcLayer()
- ->filters());
+TEST_F(CompositedLayerMappingTest, ContentsNotOpaqueWithForegroundLayer) {
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ SetHtmlInnerHTML(R"HTML(
+ <style>
+ div {
+ width: 100px;
+ height: 100px;
+ position: relative;
+ isolation: isolate;
+ }
+ </style>
+ <div id='target' style='will-change: transform'>
+ <div style='background: blue; z-index: -1; will-change: transform'></div>
+ <div style='background: blue'></div>
+ </div>
+ )HTML");
+ PaintLayer* target_layer =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("target"))->Layer();
+ CompositedLayerMapping* mapping = target_layer->GetCompositedLayerMapping();
+ EXPECT_TRUE(mapping->ForegroundLayer());
+ EXPECT_FALSE(mapping->MainGraphicsLayer()->ContentsOpaque());
+}
+
+TEST_F(CompositedLayerMappingTest, ContentsOpaque) {
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return;
+
+ SetHtmlInnerHTML(R"HTML(
+ <style>
+ div {
+ width: 100px;
+ height: 100px;
+ position: relative;
+ isolation: isolate;
+ }
+ </style>
+ <div id='target' style='will-change: transform'>
+ <div style='background: blue'></div>
+ </div>
+ )HTML");
+ PaintLayer* target_layer =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("target"))->Layer();
+ CompositedLayerMapping* mapping = target_layer->GetCompositedLayerMapping();
+ EXPECT_FALSE(mapping->ForegroundLayer());
+ EXPECT_TRUE(mapping->MainGraphicsLayer()->ContentsOpaque());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.cc
index 60fcf54f708..0c7bdf68294 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.cc
@@ -238,6 +238,9 @@ void CompositingInputsUpdater::UpdateRecursive(PaintLayer* layer,
layer->DirectCompositingReasons());
}
+ if (layer->GetLayoutObject().IsVideo())
+ info.is_under_video = true;
+
bool should_recurse =
layer->ChildNeedsCompositingInputsUpdate() || update_type == kForceUpdate;
@@ -289,46 +292,44 @@ void CompositingInputsUpdater::UpdateAncestorDependentCompositingInputs(
PaintLayer::AncestorDependentCompositingInputs properties;
LayoutBoxModelObject& layout_object = layer->GetLayoutObject();
- if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- // The final value for |unclipped_absolute_bounding_box| needs to be
- // in absolute, unscrolled space, without any scroll applied.
- properties.unclipped_absolute_bounding_box =
- EnclosingIntRect(geometry_map_.AbsoluteRect(
- FloatRect(layer->BoundingBoxForCompositingOverlapTest())));
-
- bool affected_by_scroll = root_layer_->GetScrollableArea() &&
- layer->IsAffectedByScrollOf(root_layer_);
-
- // At ths point, |unclipped_absolute_bounding_box| is in viewport space.
- // To convert to absolute space, add scroll offset for non-fixed layers.
- if (affected_by_scroll) {
- properties.unclipped_absolute_bounding_box.Move(
- RoundedIntSize(root_layer_->GetScrollableArea()->GetScrollOffset()));
- }
+ // The final value for |unclipped_absolute_bounding_box| needs to be
+ // in absolute, unscrolled space, without any scroll applied.
+ properties.unclipped_absolute_bounding_box =
+ EnclosingIntRect(geometry_map_.AbsoluteRect(
+ FloatRect(layer->BoundingBoxForCompositingOverlapTest())));
- ClipRect clip_rect;
- layer->Clipper(PaintLayer::kDoNotUseGeometryMapper)
- .CalculateBackgroundClipRect(
- ClipRectsContext(root_layer_,
- &root_layer_->GetLayoutObject().FirstFragment(),
- kAbsoluteClipRectsIgnoringViewportClip,
- kIgnorePlatformOverlayScrollbarSize,
- kIgnoreOverflowClipAndScroll),
- clip_rect);
- IntRect snapped_clip_rect = PixelSnappedIntRect(clip_rect.Rect());
- // |snapped_clip_rect| is in absolute space space, but with scroll applied.
- // To convert to absolute, unscrolled space, subtract scroll offsets for
- // fixed layers.
- if (root_layer_->GetScrollableArea() && !affected_by_scroll) {
- snapped_clip_rect.Move(
- RoundedIntSize(-root_layer_->GetScrollableArea()->GetScrollOffset()));
- }
+ bool affected_by_scroll = root_layer_->GetScrollableArea() &&
+ layer->IsAffectedByScrollOf(root_layer_);
- properties.clipped_absolute_bounding_box =
- properties.unclipped_absolute_bounding_box;
- properties.clipped_absolute_bounding_box.Intersect(snapped_clip_rect);
+ // At ths point, |unclipped_absolute_bounding_box| is in viewport space.
+ // To convert to absolute space, add scroll offset for non-fixed layers.
+ if (affected_by_scroll) {
+ properties.unclipped_absolute_bounding_box.Move(
+ RoundedIntSize(root_layer_->GetScrollableArea()->GetScrollOffset()));
}
+ ClipRect clip_rect;
+ layer->Clipper(PaintLayer::kDoNotUseGeometryMapper)
+ .CalculateBackgroundClipRect(
+ ClipRectsContext(root_layer_,
+ &root_layer_->GetLayoutObject().FirstFragment(),
+ kAbsoluteClipRectsIgnoringViewportClip,
+ kIgnorePlatformOverlayScrollbarSize,
+ kIgnoreOverflowClipAndScroll),
+ clip_rect);
+ IntRect snapped_clip_rect = PixelSnappedIntRect(clip_rect.Rect());
+ // |snapped_clip_rect| is in absolute space space, but with scroll applied.
+ // To convert to absolute, unscrolled space, subtract scroll offsets for
+ // fixed layers.
+ if (root_layer_->GetScrollableArea() && !affected_by_scroll) {
+ snapped_clip_rect.Move(
+ RoundedIntSize(-root_layer_->GetScrollableArea()->GetScrollOffset()));
+ }
+
+ properties.clipped_absolute_bounding_box =
+ properties.unclipped_absolute_bounding_box;
+ properties.clipped_absolute_bounding_box.Intersect(snapped_clip_rect);
+
const PaintLayer* parent = layer->Parent();
properties.opacity_ancestor =
parent->IsTransparent() ? parent : parent->OpacityAncestor();
@@ -360,6 +361,8 @@ void CompositingInputsUpdater::UpdateAncestorDependentCompositingInputs(
if (info.needs_reparent_scroll && layout_object.StyleRef().IsStacked())
properties.scroll_parent = info.scrolling_ancestor;
+ properties.is_under_video = info.is_under_video;
+
layer->UpdateAncestorDependentCompositingInputs(properties);
}
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.h b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.h
index 5303a1e9cc2..823f1569c12 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.h
@@ -61,6 +61,8 @@ class CompositingInputsUpdater {
bool needs_reparent_scroll = false;
bool needs_reparent_scroll_for_absolute = false;
bool needs_reparent_scroll_for_fixed = false;
+
+ bool is_under_video = false;
};
void UpdateRecursive(PaintLayer*, UpdateType, AncestorInfo);
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater_test.cc
index c979b7949e5..0f23c68dc3d 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater_test.cc
@@ -73,7 +73,7 @@ TEST_F(CompositingInputsUpdaterTest,
EXPECT_FALSE(sticky->Layer()->AncestorOverflowLayer()->GetScrollableArea());
EXPECT_EQ(sticky->Layer()->AncestorOverflowLayer(), outer_scroller->Layer());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Both scrollers must still have a layer.
EXPECT_TRUE(outer_scroller->Layer());
@@ -106,7 +106,7 @@ TEST_F(CompositingInputsUpdaterTest, UnclippedAndClippedRectsUnderScroll) {
->GetLayoutView()
->Layer()
->SetNeedsCompositingInputsUpdate();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(8, 8, 200, 200),
target->Layer()->ClippedAbsoluteBoundingBox());
EXPECT_EQ(IntRect(8, 8, 200, 200),
@@ -133,7 +133,7 @@ TEST_F(CompositingInputsUpdaterTest,
->Layer()
->SetNeedsCompositingInputsUpdate();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(8, 8, 200, 200),
target->Layer()->ClippedAbsoluteBoundingBox());
EXPECT_EQ(IntRect(8, 8, 200, 200),
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc
index 1e011f6df64..a4e6f781c8d 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc
@@ -135,15 +135,10 @@ CompositingLayerAssigner::GetReasonsPreventingSquashing(
const PaintLayer& squashing_layer =
squashing_state.most_recent_mapping->OwningLayer();
- // FIXME: this special case for video exists only to deal with corner cases
- // where a LayoutVideo does not report that it needs to be directly
- // composited. Video does not currently support sharing a backing, but this
- // could be generalized in the future. The following layout tests fail if we
- // permit the video to share a backing with other layers.
- //
- // compositing/video/video-controls-layer-creation.html
- if (layer->GetLayoutObject().IsVideo() ||
- squashing_layer.GetLayoutObject().IsVideo())
+ // Don't squash into or out of any thing underneath a video, including the
+ // user-agent shadow DOM for controls. This is is to work around a
+ // bug involving overflow clip of videos. See crbug.com/900602.
+ if (layer->IsUnderVideo() || squashing_layer.IsUnderVideo())
return SquashingDisallowedReason::kSquashingVideoIsDisallowed;
// Don't squash iframes, frames or plugins.
@@ -258,7 +253,8 @@ void CompositingLayerAssigner::UpdateSquashingAssignment(
// Issue a paint invalidation, since |layer| may have been added to an
// already-existing squashing layer.
TRACE_LAYER_INVALIDATION(
- layer, InspectorLayerInvalidationTrackingEvent::kAddedToSquashingLayer);
+ layer,
+ inspector_layer_invalidation_tracking_event::kAddedToSquashingLayer);
layers_needing_paint_invalidation.push_back(layer);
layers_changed_ = true;
} else if (composited_layer_update == kRemoveFromSquashingLayer) {
@@ -274,9 +270,9 @@ void CompositingLayerAssigner::UpdateSquashingAssignment(
// If we need to issue paint invalidations, do so now that we've removed it
// from a squashed layer.
- TRACE_LAYER_INVALIDATION(
- layer,
- InspectorLayerInvalidationTrackingEvent::kRemovedFromSquashingLayer);
+ TRACE_LAYER_INVALIDATION(layer,
+ inspector_layer_invalidation_tracking_event::
+ kRemovedFromSquashingLayer);
layers_needing_paint_invalidation.push_back(layer);
layers_changed_ = true;
@@ -308,7 +304,8 @@ void CompositingLayerAssigner::AssignLayersToBackingsInternal(
if (compositor_->AllocateOrClearCompositedLayerMapping(
layer, composited_layer_update)) {
TRACE_LAYER_INVALIDATION(
- layer, InspectorLayerInvalidationTrackingEvent::kNewCompositedLayer);
+ layer,
+ inspector_layer_invalidation_tracking_event::kNewCompositedLayer);
layers_needing_paint_invalidation.push_back(layer);
layers_changed_ = true;
if (ScrollingCoordinator* scrolling_coordinator =
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.cc
index 4c46a29c8de..d8f7858836e 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.cc
@@ -66,10 +66,15 @@ void CompositingLayerPropertyUpdater::Update(const LayoutObject& object) {
if (graphics_layer) {
if (!container_layer_state) {
container_layer_state = fragment_data.LocalBorderBoxProperties();
- if (const auto* properties = fragment_data.PaintProperties()) {
- // CSS clip should be applied within the layer.
- if (const auto* css_clip = properties->CssClip())
- container_layer_state->SetClip(css_clip->Parent());
+ // Before BlinkGenPropertyTrees, CSS clip could not be composited so
+ // we should avoid setting it on the layer itself.
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ if (const auto* properties = fragment_data.PaintProperties()) {
+ if (const auto* css_clip = properties->CssClip()) {
+ container_layer_state->SetClip(css_clip->Parent());
+ }
+ }
}
}
graphics_layer->SetLayerState(
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc
index 877168d3999..bc5808dac28 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h"
#include "third_party/blink/renderer/core/animation/scroll_timeline.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
@@ -94,9 +94,6 @@ CompositingReasonFinder::PotentialCompositingReasonsFromStyle(
!style.SubtreeWillChangeContents())
reasons |= CompositingReason::kWillChangeCompositingHint;
- if (style.HasInlineTransform())
- reasons |= CompositingReason::kInlineTransform;
-
if (style.UsedTransformStyle3D() == ETransformStyle3D::kPreserve3d)
reasons |= CompositingReason::kPreserve3DWith3DDescendants;
@@ -257,7 +254,8 @@ bool CompositingReasonFinder::RequiresCompositingForRootScroller(
const auto& settings = *layer.GetLayoutObject().GetDocument().GetSettings();
if (!settings.GetAcceleratedCompositingEnabled())
return false;
- return RootScrollerUtil::IsGlobal(layer);
+
+ return layer.GetLayoutObject().IsGlobalRootScroller();
}
bool CompositingReasonFinder::RequiresCompositingForScrollDependentPosition(
@@ -271,7 +269,7 @@ bool CompositingReasonFinder::RequiresCompositingForScrollDependentPosition(
(compositing_triggers_ & kViewportConstrainedPositionedTrigger)) &&
(!RuntimeEnabledFeatures::CompositeOpaqueFixedPositionEnabled() ||
!layer->BackgroundIsKnownToBeOpaqueInRect(
- LayoutRect(layer->BoundingBoxForCompositing())) ||
+ LayoutRect(layer->BoundingBoxForCompositing()), true) ||
layer->CompositesWithTransform() || layer->CompositesWithOpacity())) {
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc
index e02efa25f26..3dd6e2789a9 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc
@@ -205,23 +205,23 @@ TEST_F(CompositingReasonFinderTest, OnlyNonTransformedFixedLayersPromoted) {
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Change the parent to have a transform.
- parent->setAttribute(HTMLNames::styleAttr, "transform: translate(1px, 0);");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "transform: translate(1px, 0);");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState());
// Change the parent to have no transform again.
- parent->removeAttribute(HTMLNames::styleAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->removeAttribute(html_names::kStyleAttr);
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState());
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Apply a transform to the fixed directly.
- fixed->setAttribute(HTMLNames::styleAttr, "transform: translate(1px, 0);");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ fixed->setAttribute(html_names::kStyleAttr, "transform: translate(1px, 0);");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState());
@@ -253,23 +253,23 @@ TEST_F(CompositingReasonFinderTest, OnlyOpaqueFixedLayersPromoted) {
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Change the parent to be partially translucent.
- parent->setAttribute(HTMLNames::styleAttr, "opacity: 0.5;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "opacity: 0.5;");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState());
// Change the parent to be opaque again.
- parent->setAttribute(HTMLNames::styleAttr, "opacity: 1;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "opacity: 1;");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_EQ(kPaintsIntoOwnBacking, paint_layer->GetCompositingState());
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Make the fixed translucent.
- fixed->setAttribute(HTMLNames::styleAttr, "opacity: 0.5");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ fixed->setAttribute(html_names::kStyleAttr, "opacity: 0.5");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(fixed->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_EQ(kNotComposited, paint_layer->GetCompositingState());
@@ -402,7 +402,7 @@ TEST_F(CompositingReasonFinderTest, DontPromoteEmptyIframe) {
<!DOCTYPE html>
<iframe style="width:0; height:0; border: 0;" srcdoc="<!DOCTYPE html>"></iframe>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LocalFrame* child_frame =
ToLocalFrame(GetDocument().GetFrame()->Tree().FirstChild());
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc
index a861ecdfa27..1fa0a141872 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc
@@ -272,11 +272,18 @@ void CompositingRequirementsUpdater::UpdateRecursive(
CompositingReasons reasons_to_composite = CompositingReason::kNone;
CompositingReasons direct_reasons = CompositingReason::kNone;
- bool has_non_root_composited_scrolling_ancestor =
- layer->AncestorScrollingLayer() &&
- layer->AncestorScrollingLayer()->GetScrollableArea() &&
- layer->AncestorScrollingLayer()->NeedsCompositedScrolling() &&
- !layer->AncestorScrollingLayer()->IsRootLayer();
+ bool has_non_root_composited_scrolling_ancestor = false;
+ const PaintLayer* ancestor_scrolling_layer = layer->AncestorScrollingLayer();
+ while (ancestor_scrolling_layer &&
+ ancestor_scrolling_layer->GetScrollableArea()) {
+ if (ancestor_scrolling_layer->NeedsCompositedScrolling() &&
+ !ancestor_scrolling_layer->IsRootLayer()) {
+ has_non_root_composited_scrolling_ancestor = true;
+ break;
+ }
+ ancestor_scrolling_layer =
+ ancestor_scrolling_layer->AncestorScrollingLayer();
+ }
bool use_clipped_bounding_rect = !has_non_root_composited_scrolling_ancestor;
@@ -601,11 +608,6 @@ void CompositingRequirementsUpdater::UpdateRecursive(
will_be_composited_or_squashed = true;
}
- if (will_be_composited_or_squashed) {
- reasons_to_composite |= layer->PotentialCompositingReasonsFromStyle() &
- CompositingReason::kInlineTransform;
- }
-
if (will_be_composited_or_squashed &&
layer->GetLayoutObject().StyleRef().HasBlendMode()) {
current_recursion_data.has_unisolated_composited_blending_descendant_ =
@@ -624,12 +626,9 @@ void CompositingRequirementsUpdater::UpdateRecursive(
bool is_composited_clipping_layer =
can_be_composited && (reasons_to_composite &
CompositingReason::kClipsCompositingDescendants);
- bool is_composited_with_inline_transform =
- reasons_to_composite & CompositingReason::kInlineTransform;
if ((!child_recursion_data.testing_overlap_ &&
!is_composited_clipping_layer) ||
- layer->GetLayoutObject().StyleRef().HasCurrentTransformAnimation() ||
- is_composited_with_inline_transform)
+ layer->GetLayoutObject().StyleRef().HasCurrentTransformAnimation())
current_recursion_data.testing_overlap_ = false;
if (child_recursion_data.compositing_ancestor_ == layer)
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater_test.cc
index db1715411de..5d3bedb33f0 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater_test.cc
@@ -42,7 +42,7 @@ TEST_F(CompositingRequirementsUpdaterTest, FixedPosOverlap) {
GetDocument().View()->LayoutViewport()->ScrollBy(ScrollOffset(0, 100),
kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// No longer overlaps the first div.
EXPECT_EQ(CompositingReason::kNone, fixed->Layer()->GetCompositingReasons());
@@ -69,41 +69,14 @@ TEST_F(CompositingRequirementsUpdaterTest,
EXPECT_FALSE(target->GetCompositingReasons());
// Now make |target| self-painting.
- GetDocument().getElementById("target")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("target")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(CompositingReason::kOverlap, target->GetCompositingReasons());
}
TEST_F(CompositingRequirementsUpdaterTest,
- NoAssumedOverlapReasonForNonSelfPaintingLayer) {
- SetBodyInnerHTML(R"HTML(
- <style>
- #target {
- overflow: auto;
- width: 100px;
- height: 100px;
- }
- </style>
- <div style="position: relative; width: 500px; height: 300px;
- transform: translateZ(0)"></div>
- <div id=target></div>
- )HTML");
-
- PaintLayer* target =
- ToLayoutBoxModelObject(GetLayoutObjectByElementId("target"))->Layer();
- EXPECT_FALSE(target->GetCompositingReasons());
-
- // Now make |target| self-painting.
- GetDocument().getElementById("target")->setAttribute(HTMLNames::styleAttr,
- "position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_EQ(CompositingReason::kAssumedOverlap,
- target->GetCompositingReasons());
-}
-
-TEST_F(CompositingRequirementsUpdaterTest,
NoDescendantReasonForNonSelfPaintingLayer) {
SetBodyInnerHTML(R"HTML(
<style>
@@ -123,9 +96,9 @@ TEST_F(CompositingRequirementsUpdaterTest,
EXPECT_FALSE(target->GetCompositingReasons());
// Now make |target| self-painting.
- GetDocument().getElementById("target")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("target")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(CompositingReason::kClipsCompositingDescendants,
target->GetCompositingReasons());
}
@@ -160,9 +133,9 @@ TEST_F(CompositingRequirementsUpdaterTest,
GetDocument().View()->SetTracksPaintInvalidations(true);
- GetDocument().getElementById("target")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("target")->setAttribute(html_names::kStyleAttr,
"display: none");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(kNotComposited, squashed->GetCompositingState());
auto* tracking = GetDocument()
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc
index 936bc1c905f..993d3993c13 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc
@@ -73,7 +73,7 @@ TEST_F(PaintLayerCompositorTest,
// given animations separated only by a lifecycle update to
// CompositingInputsClean, they should both be started in the same lifecycle
// and as such grouped together.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(DocumentLifecycle::kPaintClean,
GetDocument().Lifecycle().GetState());
@@ -104,8 +104,8 @@ TEST_F(PaintLayerCompositorTest, UpdateDoesNotOrphanMainGraphicsLayer) {
// Force CompositedLayerMapping to update the internal layer hierarchy.
auto* box = GetDocument().getElementById("box");
- box->setAttribute(HTMLNames::styleAttr, "height: 1000px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ box->setAttribute(html_names::kStyleAttr, "height: 1000px;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(main_graphics_layer_parent, main_graphics_layer->Parent());
}
diff --git a/chromium/third_party/blink/renderer/core/paint/decoration_info.h b/chromium/third_party/blink/renderer/core/paint/decoration_info.h
index a3147cecdcd..6871a017ea9 100644
--- a/chromium/third_party/blink/renderer/core/paint/decoration_info.h
+++ b/chromium/third_party/blink/renderer/core/paint/decoration_info.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/document_marker_painter.cc b/chromium/third_party/blink/renderer/core/paint/document_marker_painter.cc
index 4777c420468..40063a379c1 100644
--- a/chromium/third_party/blink/renderer/core/paint/document_marker_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/document_marker_painter.cc
@@ -10,8 +10,8 @@
#include "third_party/blink/renderer/core/paint/text_paint_style.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc b/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc
index ff4358b75cc..c1f28b7d83a 100644
--- a/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc
@@ -36,13 +36,11 @@ void EllipsisBoxPainter::PaintEllipsis(const PaintInfo& paint_info,
box_origin.MoveBy(paint_offset);
GraphicsContext& context = paint_info.context;
- DisplayItem::Type display_item_type =
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase);
if (DrawingRecorder::UseCachedDrawingIfPossible(context, ellipsis_box_,
- display_item_type))
+ paint_info.phase))
return;
- DrawingRecorder recorder(context, ellipsis_box_, display_item_type);
+ DrawingRecorder recorder(context, ellipsis_box_, paint_info.phase);
LayoutRect box_rect(box_origin,
LayoutSize(ellipsis_box_.LogicalWidth(),
diff --git a/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.cc b/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.cc
index b957865f1fa..0d024b1f447 100644
--- a/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.cc
@@ -30,13 +30,10 @@ void EmbeddedContentPainter::PaintReplaced(const PaintInfo& paint_info,
paint_offset +
layout_embedded_content_.ReplacedContentRect().Location()));
- // Views don't support painting with a paint offset, but instead
- // offset themselves using the frame rect location. To paint Views at
- // our desired location, we need to apply paint offset as a transform, with
- // the frame rect neutralized.
IntSize view_paint_offset =
paint_location - embedded_content_view->FrameRect().Location();
- CullRect adjusted_cull_rect(paint_info.GetCullRect(), -view_paint_offset);
+ CullRect adjusted_cull_rect = paint_info.GetCullRect();
+ adjusted_cull_rect.Move(-view_paint_offset);
embedded_content_view->Paint(paint_info.context,
paint_info.GetGlobalPaintFlags(),
adjusted_cull_rect, view_paint_offset);
diff --git a/chromium/third_party/blink/renderer/core/paint/fieldset_painter.cc b/chromium/third_party/blink/renderer/core/paint/fieldset_painter.cc
index 5d762f2cd8c..744ebe0f011 100644
--- a/chromium/third_party/blink/renderer/core/paint/fieldset_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/fieldset_painter.cc
@@ -39,46 +39,50 @@ void FieldsetPainter::PaintBoxDecorationBackground(
return BoxPainter(layout_fieldset_)
.PaintBoxDecorationBackground(paint_info, paint_offset);
- if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, layout_fieldset_, paint_info.phase))
- return;
-
- FieldsetPaintInfo fieldset_paint_info =
- CreateFieldsetPaintInfo(layout_fieldset_, *legend);
- paint_rect.Contract(fieldset_paint_info.border_outsets);
-
- DrawingRecorder recorder(paint_info.context, layout_fieldset_,
- paint_info.phase);
- BoxDecorationData box_decoration_data(layout_fieldset_);
-
- BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect,
- layout_fieldset_.StyleRef());
- BackgroundImageGeometry geometry(layout_fieldset_);
- BoxModelObjectPainter(layout_fieldset_)
- .PaintFillLayers(paint_info, box_decoration_data.background_color,
- layout_fieldset_.StyleRef().BackgroundLayers(),
- paint_rect, geometry);
- BoxPainterBase::PaintInsetBoxShadowWithBorderRect(
- paint_info, paint_rect, layout_fieldset_.StyleRef());
-
- if (!box_decoration_data.has_border_decoration)
- return;
-
- // Create a clipping region around the legend and paint the border as normal
- GraphicsContext& graphics_context = paint_info.context;
- GraphicsContextStateSaver state_saver(graphics_context);
-
- LayoutRect legend_cutout_rect = fieldset_paint_info.legend_cutout_rect;
- legend_cutout_rect.MoveBy(paint_offset);
- graphics_context.ClipOut(PixelSnappedIntRect(legend_cutout_rect));
-
- Node* node = nullptr;
- const LayoutObject* layout_object = &layout_fieldset_;
- for (; layout_object && !node; layout_object = layout_object->Parent())
- node = layout_object->GeneratingNode();
- BoxPainterBase::PaintBorder(layout_fieldset_, layout_fieldset_.GetDocument(),
- node, paint_info, paint_rect,
- layout_fieldset_.StyleRef());
+ if (!DrawingRecorder::UseCachedDrawingIfPossible(
+ paint_info.context, layout_fieldset_, paint_info.phase)) {
+ FieldsetPaintInfo fieldset_paint_info =
+ CreateFieldsetPaintInfo(layout_fieldset_, *legend);
+ paint_rect.Contract(fieldset_paint_info.border_outsets);
+
+ DrawingRecorder recorder(paint_info.context, layout_fieldset_,
+ paint_info.phase);
+ BoxDecorationData box_decoration_data(layout_fieldset_);
+
+ BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect,
+ layout_fieldset_.StyleRef());
+ BackgroundImageGeometry geometry(layout_fieldset_);
+ BoxModelObjectPainter(layout_fieldset_)
+ .PaintFillLayers(paint_info, box_decoration_data.background_color,
+ layout_fieldset_.StyleRef().BackgroundLayers(),
+ paint_rect, geometry);
+ BoxPainterBase::PaintInsetBoxShadowWithBorderRect(
+ paint_info, paint_rect, layout_fieldset_.StyleRef());
+
+ if (box_decoration_data.has_border_decoration) {
+ // Create a clipping region around the legend and paint the border as
+ // normal
+ GraphicsContext& graphics_context = paint_info.context;
+ GraphicsContextStateSaver state_saver(graphics_context);
+
+ LayoutRect legend_cutout_rect = fieldset_paint_info.legend_cutout_rect;
+ legend_cutout_rect.MoveBy(paint_offset);
+ graphics_context.ClipOut(PixelSnappedIntRect(legend_cutout_rect));
+
+ Node* node = nullptr;
+ const LayoutObject* layout_object = &layout_fieldset_;
+ for (; layout_object && !node; layout_object = layout_object->Parent())
+ node = layout_object->GeneratingNode();
+ BoxPainterBase::PaintBorder(
+ layout_fieldset_, layout_fieldset_.GetDocument(), node, paint_info,
+ paint_rect, layout_fieldset_.StyleRef());
+ }
+ }
+
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled()) {
+ BoxPainter(layout_fieldset_)
+ .RecordHitTestData(paint_info, paint_rect, layout_fieldset_);
+ }
}
void FieldsetPainter::PaintMask(const PaintInfo& paint_info,
diff --git a/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.cc b/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.cc
index e8d7fb75428..3dd4e661ecc 100644
--- a/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.cc
+++ b/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.cc
@@ -33,6 +33,7 @@
#include "third_party/blink/renderer/core/svg/svg_filter_element.h"
#include "third_party/blink/renderer/core/svg/svg_length_context.h"
#include "third_party/blink/renderer/core/svg/svg_resource.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/compositor_filter_operations.h"
#include "third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.h"
#include "third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.h"
@@ -44,7 +45,6 @@
#include "third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h"
#include "third_party/blink/renderer/platform/graphics/filters/source_graphic.h"
#include "third_party/blink/renderer/platform/graphics/interpolation_space.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -305,14 +305,14 @@ CompositorFilterOperations FilterEffectBuilder::BuildFilterOperations(
Filter* reference_filter =
BuildReferenceFilter(reference_operation, nullptr);
if (reference_filter && reference_filter->LastEffect()) {
- PaintFilterBuilder::PopulateSourceGraphicImageFilters(
+ paint_filter_builder::PopulateSourceGraphicImageFilters(
reference_filter->GetSourceGraphic(), nullptr,
current_interpolation_space);
FilterEffect* filter_effect = reference_filter->LastEffect();
current_interpolation_space =
filter_effect->OperatingInterpolationSpace();
- auto paint_filter = PaintFilterBuilder::Build(
+ auto paint_filter = paint_filter_builder::Build(
filter_effect, current_interpolation_space);
if (!paint_filter)
continue;
@@ -385,7 +385,7 @@ CompositorFilterOperations FilterEffectBuilder::BuildFilterOperations(
// instead of calling this a "reference filter".
const auto& reflection = ToBoxReflectFilterOperation(*op).Reflection();
filters.AppendReferenceFilter(
- PaintFilterBuilder::BuildBoxReflectFilter(reflection, nullptr));
+ paint_filter_builder::BuildBoxReflectFilter(reflection, nullptr));
break;
}
case FilterOperation::NONE:
@@ -394,8 +394,9 @@ CompositorFilterOperations FilterEffectBuilder::BuildFilterOperations(
}
if (current_interpolation_space != kInterpolationSpaceSRGB) {
// Transform to device color space at the end of processing, if required.
- sk_sp<PaintFilter> filter = PaintFilterBuilder::TransformInterpolationSpace(
- nullptr, current_interpolation_space, kInterpolationSpaceSRGB);
+ sk_sp<PaintFilter> filter =
+ paint_filter_builder::TransformInterpolationSpace(
+ nullptr, current_interpolation_space, kInterpolationSpaceSRGB);
filters.AppendReferenceFilter(std::move(filter));
}
diff --git a/chromium/third_party/blink/renderer/core/paint/fragment_data.h b/chromium/third_party/blink/renderer/core/paint/fragment_data.h
index 3cbdc220f9e..e71fd303568 100644
--- a/chromium/third_party/blink/renderer/core/paint/fragment_data.h
+++ b/chromium/third_party/blink/renderer/core/paint/fragment_data.h
@@ -227,7 +227,7 @@ class CORE_EXPORT FragmentData {
void DestroyTail();
// Contains rare data that that is not needed on all fragments.
- struct RareData {
+ struct CORE_EXPORT RareData {
USING_FAST_MALLOC(RareData);
public:
diff --git a/chromium/third_party/blink/renderer/core/paint/frame_painter.cc b/chromium/third_party/blink/renderer/core/paint/frame_painter.cc
index 12b6df67135..52e06dff7a7 100644
--- a/chromium/third_party/blink/renderer/core/paint/frame_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/frame_painter.cc
@@ -68,7 +68,7 @@ void FramePainter::PaintContents(GraphicsContext& context,
FramePaintTiming frame_paint_timing(context, &GetFrameView().GetFrame());
TRACE_EVENT1(
"devtools.timeline,rail", "Paint", "data",
- InspectorPaintEvent::Data(layout_view, LayoutRect(rect), nullptr));
+ inspector_paint_event::Data(layout_view, LayoutRect(rect), nullptr));
bool is_top_level_painter = !in_paint_contents_;
in_paint_contents_ = true;
@@ -101,11 +101,11 @@ void FramePainter::PaintContents(GraphicsContext& context,
root_layer->GetLayoutObject().GetFrame());
context.SetDeviceScaleFactor(device_scale_factor);
- layer_painter.Paint(context, LayoutRect(rect), updated_global_paint_flags,
+ layer_painter.Paint(context, CullRect(rect), updated_global_paint_flags,
root_layer_paint_flags);
if (root_layer->ContainsDirtyOverlayScrollbars()) {
- layer_painter.PaintOverlayScrollbars(context, LayoutRect(rect),
+ layer_painter.PaintOverlayScrollbars(context, CullRect(rect),
updated_global_paint_flags);
}
diff --git a/chromium/third_party/blink/renderer/core/paint/frame_set_painter.cc b/chromium/third_party/blink/renderer/core/paint/frame_set_painter.cc
index 683c170db66..196fca5a046 100644
--- a/chromium/third_party/blink/renderer/core/paint/frame_set_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/frame_set_painter.cc
@@ -26,7 +26,7 @@ static Color BorderFillColor() {
void FrameSetPainter::PaintColumnBorder(const PaintInfo& paint_info,
const IntRect& border_rect) {
- if (!paint_info.GetCullRect().IntersectsCullRect(border_rect))
+ if (!paint_info.GetCullRect().Intersects(border_rect))
return;
// FIXME: We should do something clever when borders from distinct framesets
diff --git a/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.cc b/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.cc
index a5692927314..a9443b1220c 100644
--- a/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.cc
@@ -44,11 +44,11 @@ void HTMLCanvasPainter::PaintReplaced(const PaintInfo& paint_info,
canvas->RenderingContext()->IsComposited()) {
if (cc::Layer* layer = canvas->RenderingContext()->CcLayer()) {
IntRect pixel_snapped_rect = PixelSnappedIntRect(paint_rect);
- layer->SetBounds(static_cast<gfx::Size>(pixel_snapped_rect.Size()));
+ layer->SetOffsetToTransformParent(
+ gfx::Vector2dF(pixel_snapped_rect.X(), pixel_snapped_rect.Y()));
+ layer->SetBounds(gfx::Size(pixel_snapped_rect.Size()));
layer->SetIsDrawable(true);
- RecordForeignLayer(
- context, layout_html_canvas_, DisplayItem::kForeignLayerCanvas, layer,
- FloatPoint(pixel_snapped_rect.Location()), pixel_snapped_rect.Size());
+ RecordForeignLayer(context, DisplayItem::kForeignLayerCanvas, layer);
return;
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/html_canvas_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/html_canvas_painter_test.cc
index 5f9839a5747..0e4681dfc81 100644
--- a/chromium/third_party/blink/renderer/core/paint/html_canvas_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/html_canvas_painter_test.cc
@@ -98,7 +98,7 @@ TEST_P(HTMLCanvasPainterTestForSPv2, Canvas2DLayerAppearsInLayerTree) {
// Force the page to paint.
element->FinalizeFrame();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Fetch the layer associated with the <canvas>, and check that it was
// correctly configured in the layer tree.
diff --git a/chromium/third_party/blink/renderer/core/paint/image_element_timing.cc b/chromium/third_party/blink/renderer/core/paint/image_element_timing.cc
index 3fd6520fc57..346e103cf35 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_element_timing.cc
+++ b/chromium/third_party/blink/renderer/core/paint/image_element_timing.cc
@@ -16,6 +16,7 @@
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
+#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
@@ -50,12 +51,22 @@ void ImageElementTiming::NotifyImagePainted(const HTMLImageElement* element,
images_notified_.insert(layout_image);
- // Compute the viewport rect.
LocalFrame* frame = GetSupplementable()->GetFrame();
DCHECK(frame == layout_image->GetDocument().GetFrame());
if (!frame)
return;
+ // Skip the computations below if the element is not same origin.
+ if (!layout_image->CachedImage())
+ return;
+
+ const KURL& url = layout_image->CachedImage()->Url();
+ DCHECK(GetSupplementable()->document() == &layout_image->GetDocument());
+ if (!SecurityOrigin::AreSameSchemeHostPort(layout_image->GetDocument().Url(),
+ url))
+ return;
+
+ // Compute the viewport rect.
WebLayerTreeView* layerTreeView =
frame->GetChromeClient().GetWebLayerTreeView(frame);
if (!layerTreeView)
@@ -81,7 +92,7 @@ void ImageElementTiming::NotifyImagePainted(const HTMLImageElement* element,
visible_new_visual_rect.Intersect(viewport);
const AtomicString attr =
- element->FastGetAttribute(HTMLNames::elementtimingAttr);
+ element->FastGetAttribute(html_names::kElementtimingAttr);
// Do not create an entry if 'elementtiming' is not present or the image is
// below a certain size threshold.
if (attr.IsEmpty() &&
@@ -94,7 +105,7 @@ void ImageElementTiming::NotifyImagePainted(const HTMLImageElement* element,
// empty, use the ID. If empty, use 'img'.
AtomicString name = attr;
if (name.IsEmpty())
- name = element->FastGetAttribute(HTMLNames::idAttr);
+ name = element->FastGetAttribute(html_names::kIdAttr);
if (name.IsEmpty())
name = "img";
element_timings_.emplace_back(name, visible_new_visual_rect);
@@ -110,15 +121,29 @@ void ImageElementTiming::NotifyImagePainted(const HTMLImageElement* element,
void ImageElementTiming::ReportImagePaintSwapTime(WebLayerTreeView::SwapResult,
base::TimeTicks timestamp) {
- WindowPerformance* performance =
- DOMWindowPerformance::performance(*GetSupplementable());
- if (!performance || !performance->HasObserverFor(PerformanceEntry::kElement))
- return;
-
- for (const auto& element_timing : element_timings_) {
- performance->AddElementTiming(element_timing.name, element_timing.rect,
- timestamp);
+ Document* document = GetSupplementable()->document();
+ DCHECK(document);
+ const SecurityOrigin* current_origin = document->GetSecurityOrigin();
+ // It suffices to check the current origin against the parent origin since all
+ // origins stored in |element_timings_| have been checked against the current
+ // origin.
+ while (document &&
+ current_origin->IsSameSchemeHostPort(document->GetSecurityOrigin())) {
+ DCHECK(document->domWindow());
+ WindowPerformance* performance =
+ DOMWindowPerformance::performance(*document->domWindow());
+ if (performance &&
+ performance->HasObserverFor(PerformanceEntry::kElement)) {
+ for (const auto& element_timing : element_timings_) {
+ performance->AddElementTiming(element_timing.name, element_timing.rect,
+ timestamp);
+ }
+ }
+ // Provide the entry to the parent documents for as long as the origin check
+ // still holds.
+ document = document->ParentDocument();
}
+
element_timings_.clear();
}
diff --git a/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc b/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
index fdeee5f4f9d..f0b454af11e 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
+++ b/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
@@ -1,16 +1,21 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
#include "third_party/blink/renderer/core/paint/image_paint_timing_detector.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
+#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/layout_image.h"
+#include "third_party/blink/renderer/core/layout/layout_image_resource.h"
+#include "third_party/blink/renderer/core/layout/layout_video.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/layout/svg/layout_svg_image.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/style/style_fetched_image.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
@@ -18,6 +23,78 @@
namespace blink {
+namespace {
+String GetImageUrl(const LayoutObject& object) {
+ if (object.IsImage()) {
+ const ImageResourceContent* cached_image =
+ ToLayoutImage(&object)->CachedImage();
+ return cached_image ? cached_image->Url().StrippedForUseAsReferrer() : "";
+ }
+ if (object.IsVideo()) {
+ const ImageResourceContent* cached_image =
+ ToLayoutVideo(&object)->CachedImage();
+ return cached_image ? cached_image->Url().StrippedForUseAsReferrer() : "";
+ }
+ if (object.IsSVGImage()) {
+ const LayoutImageResource* image_resource =
+ ToLayoutSVGImage(&object)->ImageResource();
+ const ImageResourceContent* cached_image = image_resource->CachedImage();
+ return cached_image ? cached_image->Url().StrippedForUseAsReferrer() : "";
+ }
+ DCHECK(ImagePaintTimingDetector::HasContentfulBackgroundImage(object));
+ const ComputedStyle* style = object.Style();
+ StringBuilder concatenated_result;
+ for (const FillLayer* bg_layer = &style->BackgroundLayers(); bg_layer;
+ bg_layer = bg_layer->Next()) {
+ StyleImage* bg_image = bg_layer->GetImage();
+ if (!bg_image || !bg_image->IsImageResource())
+ continue;
+ const StyleFetchedImage* fetched_image = ToStyleFetchedImage(bg_image);
+ const String url = fetched_image->Url().StrippedForUseAsReferrer();
+ concatenated_result.Append(url.Utf8().data(), url.length());
+ }
+ return concatenated_result.ToString();
+}
+
+bool AttachedBackgroundImagesAllLoaded(const LayoutObject& object) {
+ DCHECK(ImagePaintTimingDetector::HasContentfulBackgroundImage(object));
+ const ComputedStyle* style = object.Style();
+ DCHECK(style);
+ for (const FillLayer* bg_layer = &style->BackgroundLayers(); bg_layer;
+ bg_layer = bg_layer->Next()) {
+ StyleImage* bg_image = bg_layer->GetImage();
+ // A layout object with background images is not loaded until all of the
+ // background images are loaded.
+ if (!bg_image || !bg_image->IsImageResource())
+ continue;
+ if (!bg_image->IsLoaded())
+ return false;
+ }
+ return true;
+}
+
+bool IsLoaded(const LayoutObject& object) {
+ if (object.IsImage()) {
+ const ImageResourceContent* cached_image =
+ ToLayoutImage(&object)->CachedImage();
+ return cached_image ? cached_image->IsLoaded() : false;
+ }
+ if (object.IsVideo()) {
+ const ImageResourceContent* cached_image =
+ ToLayoutVideo(&object)->CachedImage();
+ return cached_image ? cached_image->IsLoaded() : false;
+ }
+ if (object.IsSVGImage()) {
+ const LayoutImageResource* image_resource =
+ ToLayoutSVGImage(&object)->ImageResource();
+ const ImageResourceContent* cached_image = image_resource->CachedImage();
+ return cached_image ? cached_image->IsLoaded() : false;
+ }
+ DCHECK(ImagePaintTimingDetector::HasContentfulBackgroundImage(object));
+ return AttachedBackgroundImagesAllLoaded(object);
+}
+} // namespace
+
// Set a big enough limit for the number of nodes to ensure memory usage is
// capped. Exceeding such limit will deactivate the algorithm.
constexpr size_t kImageNodeNumberLimit = 5000;
@@ -57,57 +134,57 @@ void ImagePaintTimingDetector::PopulateTraceValue(
IdentifiersFactory::FrameId(&frame_view_->GetFrame()));
}
-IntRect ImagePaintTimingDetector::CalculateTransformedRect(
- LayoutRect& invalidated_rect,
- const PaintLayer& painting_layer) const {
- const auto* local_transform = painting_layer.GetLayoutObject()
- .FirstFragment()
- .LocalBorderBoxProperties()
- .Transform();
- const auto* ancestor_transform = painting_layer.GetLayoutObject()
- .View()
- ->FirstFragment()
- .LocalBorderBoxProperties()
- .Transform();
- FloatRect invalidated_rect_abs = FloatRect(invalidated_rect);
- if (invalidated_rect_abs.IsEmpty() || invalidated_rect_abs.IsZero())
- return IntRect();
- DCHECK(local_transform);
- DCHECK(ancestor_transform);
- GeometryMapper::SourceToDestinationRect(local_transform, ancestor_transform,
- invalidated_rect_abs);
- IntRect invalidated_rect_in_viewport = RoundedIntRect(invalidated_rect_abs);
- ScrollableArea* scrollable_area = frame_view_->GetScrollableArea();
- DCHECK(scrollable_area);
- IntRect viewport = scrollable_area->VisibleContentRect();
- invalidated_rect_in_viewport.Intersect(viewport);
- return invalidated_rect_in_viewport;
+void ImagePaintTimingDetector::OnLargestImagePaintDetected(
+ const ImageRecord& largest_image_record) {
+ largest_image_paint_ = largest_image_record.first_paint_time_after_loaded;
+ std::unique_ptr<TracedValue> value = TracedValue::Create();
+ PopulateTraceValue(*value, largest_image_record,
+ ++largest_image_candidate_index_max_);
+ TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
+ "loading", "LargestImagePaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
+ largest_image_record.first_paint_time_after_loaded, "data",
+ std::move(value));
+ frame_view_->GetPaintTimingDetector().DidChangePerformanceTiming();
+}
+
+void ImagePaintTimingDetector::OnLastImagePaintDetected(
+ const ImageRecord& last_image_record) {
+ last_image_paint_ = last_image_record.first_paint_time_after_loaded;
+ std::unique_ptr<TracedValue> value = TracedValue::Create();
+ PopulateTraceValue(*value, last_image_record,
+ ++last_image_candidate_index_max_);
+ TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
+ "loading", "LastImagePaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
+ last_image_record.first_paint_time_after_loaded, "data",
+ std::move(value));
+ frame_view_->GetPaintTimingDetector().DidChangePerformanceTiming();
}
void ImagePaintTimingDetector::Analyze() {
+ // These conditions represents the following scenarios:
+ // 1. candiate being nullptr: no loaded image is found.
+ // 2. candidate's first paint being null: largest/last image is still pending
+ // for timing. We discard the candidate and wait for the next analysis.
+ // 3. new candidate equals to old candidate: we don't need to update the
+ // result unless it's a new candidate.
ImageRecord* largest_image_record = FindLargestPaintCandidate();
- // In cases where largest/last image is still pending for timing, we discard
- // the result and wait for the next analysis.
+ bool new_candidate_detected = false;
if (largest_image_record &&
- !largest_image_record->first_paint_time_after_loaded.is_null()) {
- std::unique_ptr<TracedValue> value = TracedValue::Create();
- PopulateTraceValue(*value, *largest_image_record,
- ++largest_image_candidate_index_max_);
- TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
- "loading", "LargestImagePaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
- largest_image_record->first_paint_time_after_loaded, "data",
- std::move(value));
+ !largest_image_record->first_paint_time_after_loaded.is_null() &&
+ largest_image_record->first_paint_time_after_loaded !=
+ largest_image_paint_) {
+ new_candidate_detected = true;
+ OnLargestImagePaintDetected(*largest_image_record);
}
ImageRecord* last_image_record = FindLastPaintCandidate();
if (last_image_record &&
- !last_image_record->first_paint_time_after_loaded.is_null()) {
- std::unique_ptr<TracedValue> value = TracedValue::Create();
- PopulateTraceValue(*value, *last_image_record,
- ++last_image_candidate_index_max_);
- TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
- "loading", "LastImagePaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
- last_image_record->first_paint_time_after_loaded, "data",
- std::move(value));
+ !last_image_record->first_paint_time_after_loaded.is_null() &&
+ last_image_record->first_paint_time_after_loaded != last_image_paint_) {
+ new_candidate_detected = true;
+ OnLastImagePaintDetected(*last_image_record);
+ }
+ if (new_candidate_detected) {
+ frame_view_->GetPaintTimingDetector().DidChangePerformanceTiming();
}
}
@@ -136,6 +213,20 @@ void ImagePaintTimingDetector::NotifyNodeRemoved(DOMNodeId node_id) {
// bother to remove these records from largest_image_heap_ or
// latest_image_heap_, to reduce computation.
id_record_map_.erase(node_id);
+
+ if (id_record_map_.size() == 0) {
+ const bool largest_image_paint_invalidated =
+ largest_image_paint_ != base::TimeTicks();
+ const bool last_image_paint_invalidated =
+ last_image_paint_ != base::TimeTicks();
+ if (largest_image_paint_invalidated)
+ largest_image_paint_ = base::TimeTicks();
+ if (last_image_paint_invalidated)
+ last_image_paint_ = base::TimeTicks();
+ if (largest_image_paint_invalidated || last_image_paint_invalidated) {
+ frame_view_->GetPaintTimingDetector().DidChangePerformanceTiming();
+ }
+ }
}
}
@@ -166,9 +257,8 @@ void ImagePaintTimingDetector::ReportSwapTime(
base::TimeTicks timestamp) {
// The callback is safe from race-condition only when running on main-thread.
DCHECK(ThreadState::Current()->IsMainThread());
- // This callback is queued only when there are records in
- // records_pending_timing_.
- DCHECK_GT(records_pending_timing_.size(), 0UL);
+ // Not guranteed to be non-empty, because records can be removed between
+ // callback registration and invocation.
while (records_pending_timing_.size() > 0) {
DOMNodeId node_id = records_pending_timing_.front();
if (!id_record_map_.Contains(node_id)) {
@@ -185,6 +275,48 @@ void ImagePaintTimingDetector::ReportSwapTime(
Analyze();
}
+// In the context of FCP++, we define contentful background image as one that
+// satisfies all of the following conditions:
+// * has image reources attached to style of the object, i.e.,
+// { background-image: url('example.gif') }
+// * not attached to <body> or <html>
+//
+// static
+bool ImagePaintTimingDetector::HasContentfulBackgroundImage(
+ const LayoutObject& object) {
+ Node* node = object.GetNode();
+ if (!node)
+ return false;
+ // Background images attached to <body> or <html> are likely for background
+ // purpose, so we rule them out, according to the following rules:
+ // * Box model objects includes objects of box model, such as <div>, <body>,
+ // LayoutView, but not includes LayoutText.
+ // * BackgroundTransfersToView is true for the <body>, <html>, e.g., that
+ // have transferred their background to LayoutView.
+ // * LayoutView has the background transfered by <html> if <html> has
+ // background.
+ if (!object.IsBoxModelObject() ||
+ ToLayoutBoxModelObject(object).BackgroundTransfersToView())
+ return false;
+ if (object.IsLayoutView())
+ return false;
+ const ComputedStyle* style = object.Style();
+ if (!style)
+ return false;
+ if (!style->HasBackgroundImage())
+ return false;
+
+ for (const FillLayer* bg_layer = &style->BackgroundLayers(); bg_layer;
+ bg_layer = bg_layer->Next()) {
+ StyleImage* bg_image = bg_layer->GetImage();
+ // Rule out images that doesn't load any image resources, e.g., a gradient.
+ if (!bg_image || !bg_image->IsImageResource())
+ continue;
+ return true;
+ }
+ return false;
+}
+
void ImagePaintTimingDetector::RecordImage(const LayoutObject& object,
const PaintLayer& painting_layer) {
Node* node = object.GetNode();
@@ -194,57 +326,60 @@ void ImagePaintTimingDetector::RecordImage(const LayoutObject& object,
if (size_zero_ids_.Contains(node_id))
return;
- const LayoutImage* image = ToLayoutImage(&object);
- if (!id_record_map_.Contains(node_id)) {
- recorded_node_count_++;
- if (recorded_node_count_ < kImageNodeNumberLimit) {
- LayoutRect invalidated_rect = image->FirstFragment().VisualRect();
- // Do not record first size until invalidated_rect's size becomes
- // non-empty.
- if (invalidated_rect.IsEmpty())
- return;
- IntRect invalidated_rect_in_viewport =
- CalculateTransformedRect(invalidated_rect, painting_layer);
- int rect_size = invalidated_rect_in_viewport.Height() *
- invalidated_rect_in_viewport.Width();
- if (rect_size == 0) {
- // When rect_size == 0, it either means the image is size 0 or the image
- // is out of viewport. Either way, we don't track this image anymore, to
- // reduce computation.
- size_zero_ids_.insert(node_id);
- return;
- }
- std::unique_ptr<ImageRecord> record = std::make_unique<ImageRecord>();
- record->node_id = node_id;
- record->frame_index = frame_index_;
- record->first_size = rect_size;
- record->first_paint_index = ++first_paint_index_max_;
- ImageResourceContent* cachedImg = image->CachedImage();
- record->image_url =
- !cachedImg ? "" : cachedImg->Url().StrippedForUseAsReferrer();
- largest_image_heap_.push(record->AsWeakPtr());
- latest_image_heap_.push(record->AsWeakPtr());
- id_record_map_.insert(node_id, std::move(record));
- } else {
- // for assessing whether kImageNodeNumberLimit is large enough for all
- // normal cases
- TRACE_EVENT_INSTANT1("loading", "ImagePaintTimingDetector::OverNodeLimit",
- TRACE_EVENT_SCOPE_THREAD, "recorded_node_count",
- recorded_node_count_);
+ if (!id_record_map_.Contains(node_id) && is_recording_) {
+ LayoutRect invalidated_rect = object.FirstFragment().VisualRect();
+ // Before the image resource is loaded, <img> has size 0, so we do not
+ // record the first size until the invalidated rect's size becomes
+ // non-empty.
+ if (invalidated_rect.IsEmpty())
+ return;
+ uint64_t rect_size =
+ frame_view_->GetPaintTimingDetector().CalculateVisualSize(
+ invalidated_rect, painting_layer);
+ if (rect_size == 0) {
+ // When rect_size == 0, it either means the image is size 0 or the image
+ // is out of viewport. Either way, we don't track this image anymore, to
+ // reduce computation.
+ size_zero_ids_.insert(node_id);
+ return;
}
+ // Non-trivial image is found.
+ std::unique_ptr<ImageRecord> record = std::make_unique<ImageRecord>();
+ record->node_id = node_id;
+ record->image_url = GetImageUrl(object);
+ // Mind that first_size has to be assigned at the push of
+ // largest_image_heap_ since it's the sorting key.
+ record->first_size = rect_size;
+ largest_image_heap_.push(record->AsWeakPtr());
+ id_record_map_.insert(node_id, std::move(record));
+ if (id_record_map_.size() + size_zero_ids_.size() > kImageNodeNumberLimit)
+ Deactivate();
}
- if (id_record_map_.Contains(node_id) &&
- IsJustLoaded(image, *id_record_map_.at(node_id))) {
+ if (id_record_map_.Contains(node_id) && !id_record_map_.at(node_id)->loaded &&
+ IsLoaded(object)) {
+ // The image is just loaded.
records_pending_timing_.push(node_id);
- id_record_map_.at(node_id)->loaded = true;
+ ImageRecord* record = id_record_map_.at(node_id);
+ record->frame_index = frame_index_;
+ record->loaded = true;
+ // Latest image heap differs from largest image heap in that the former
+ // pushes a record when an image is loaded while the latter pushes when an
+ // image is attached to DOM. This causes last image paint to base its order
+ // on load time other than attachment time.
+ // Mind that first_paint_index has to be assigned at the push of
+ // latest_image_heap_ since it's the sorting key.
+ record->first_paint_index = ++first_paint_index_max_;
+ latest_image_heap_.push(record->AsWeakPtr());
}
}
-bool ImagePaintTimingDetector::IsJustLoaded(const LayoutImage* image,
- const ImageRecord& record) const {
- ImageResourceContent* cachedImg = image->CachedImage();
- return cachedImg && cachedImg->IsLoaded() && !record.loaded;
+void ImagePaintTimingDetector::Deactivate() {
+ TRACE_EVENT_INSTANT2("loading", "ImagePaintTimingDetector::OverNodeLimit",
+ TRACE_EVENT_SCOPE_THREAD, "recorded_node_count",
+ id_record_map_.size(), "size_zero_node_count",
+ size_zero_ids_.size());
+ is_recording_ = false;
}
ImageRecord* ImagePaintTimingDetector::FindLargestPaintCandidate() {
diff --git a/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.h b/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.h
index 0d933082422..9bcfd63aa45 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.h
+++ b/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.h
@@ -17,16 +17,14 @@
namespace blink {
class PaintLayer;
-class IntRect;
class LayoutObject;
class TracedValue;
class LocalFrameView;
-class LayoutImage;
class ImageRecord : public base::SupportsWeakPtr<ImageRecord> {
public:
DOMNodeId node_id = kInvalidDOMNodeId;
- double first_size = 0.0;
+ uint64_t first_size = 0;
// LastImagePaint uses the order of the first paints to determine the last
// image.
unsigned first_paint_index = 0;
@@ -64,29 +62,30 @@ class CORE_EXPORT ImagePaintTimingDetector final
friend class ImagePaintTimingDetectorTest;
public:
- ImagePaintTimingDetector(LocalFrameView* frame_view);
- void RecordImage(const LayoutObject& object,
- const PaintLayer& painting_layer);
+ ImagePaintTimingDetector(LocalFrameView*);
+ void RecordImage(const LayoutObject&, const PaintLayer&);
+ static bool HasContentfulBackgroundImage(const LayoutObject& object);
void OnPrePaintFinished();
void NotifyNodeRemoved(DOMNodeId);
+ base::TimeTicks LargestImagePaint() const { return largest_image_paint_; }
+ base::TimeTicks LastImagePaint() const { return last_image_paint_; }
void Trace(blink::Visitor*);
private:
ImageRecord* FindLargestPaintCandidate();
ImageRecord* FindLastPaintCandidate();
- void PopulateTraceValue(TracedValue& value,
+ void PopulateTraceValue(TracedValue&,
const ImageRecord& first_image_paint,
unsigned report_count) const;
- IntRect CalculateTransformedRect(LayoutRect& visual_rect,
- const PaintLayer& painting_layer) const;
// This is provided for unit test to force invoking swap promise callback.
void ReportSwapTime(unsigned max_frame_index_to_time,
WebLayerTreeView::SwapResult,
base::TimeTicks);
void RegisterNotifySwapTime();
- void InvokeCallback();
+ void OnLargestImagePaintDetected(const ImageRecord&);
+ void OnLastImagePaintDetected(const ImageRecord&);
+ void Deactivate();
- bool IsJustLoaded(const LayoutImage*, const ImageRecord&) const;
void Analyze();
base::RepeatingCallback<void(WebLayerTreeView::ReportTimeCallback)>
@@ -104,7 +103,6 @@ class CORE_EXPORT ImagePaintTimingDetector final
bool (*)(const base::WeakPtr<ImageRecord>&,
const base::WeakPtr<ImageRecord>&)>
latest_image_heap_;
- unsigned recorded_node_count_ = 0;
// Node-ids of records pending swap time are stored in this queue until they
// get a swap time.
@@ -121,6 +119,10 @@ class CORE_EXPORT ImagePaintTimingDetector final
unsigned frame_index_ = 1;
unsigned last_frame_index_queued_for_timing_ = 0;
+ bool is_recording_ = true;
+
+ base::TimeTicks largest_image_paint_;
+ base::TimeTicks last_image_paint_;
Member<LocalFrameView> frame_view_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc b/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc
index a48eaec6088..95ca64c2c98 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc
@@ -4,27 +4,42 @@
#include "third_party/blink/renderer/core/paint/image_paint_timing_detector.h"
#include "build/build_config.h"
+#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
-#include "third_party/blink/renderer/core/paint/paint_tracker.h"
+#include "third_party/blink/renderer/core/html/media/html_video_element.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/svg/svg_image_element.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
+#include "third_party/blink/renderer/platform/testing/wtf/scoped_mock_clock.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace blink {
-class ImagePaintTimingDetectorTest : public PageTestBase,
- private ScopedPaintTrackingForTest {
+class ImagePaintTimingDetectorTest
+ : public PageTestBase,
+ private ScopedFirstContentfulPaintPlusPlusForTest {
using CallbackQueue = std::queue<WebLayerTreeView::ReportTimeCallback>;
public:
- ImagePaintTimingDetectorTest() : ScopedPaintTrackingForTest(true){};
+ ImagePaintTimingDetectorTest()
+ : ScopedFirstContentfulPaintPlusPlusForTest(true),
+ base_url_("http://www.test.com/"){};
+
+ ~ImagePaintTimingDetectorTest() override {
+ Platform::Current()
+ ->GetURLLoaderMockFactory()
+ ->UnregisterAllURLsAndClearMemoryCache();
+ }
void SetUp() override {
PageTestBase::SetUp();
- GetPaintTracker()
+ GetPaintTimingDetector()
.GetImagePaintTimingDetector()
.notify_swap_time_override_for_testing_ =
base::BindRepeating(&ImagePaintTimingDetectorTest::FakeNotifySwapTime,
@@ -33,21 +48,41 @@ class ImagePaintTimingDetectorTest : public PageTestBase,
protected:
LocalFrameView& GetFrameView() { return *GetFrame().View(); }
- PaintTracker& GetPaintTracker() { return GetFrameView().GetPaintTracker(); }
+ PaintTimingDetector& GetPaintTimingDetector() {
+ return GetFrameView().GetPaintTimingDetector();
+ }
ImageRecord* FindLargestPaintCandidate() {
- return GetPaintTracker()
+ return GetPaintTimingDetector()
.GetImagePaintTimingDetector()
.FindLargestPaintCandidate();
}
ImageRecord* FindLastPaintCandidate() {
- return GetPaintTracker()
+ return GetPaintTimingDetector()
.GetImagePaintTimingDetector()
.FindLastPaintCandidate();
}
+ unsigned CountRecords() {
+ return GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ .id_record_map_.size();
+ }
+
+ TimeTicks LargestPaintStoredResult() {
+ return GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ .largest_image_paint_;
+ }
+
+ TimeTicks LastPaintStoredResult() {
+ return GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ .last_image_paint_;
+ }
+
void UpdateAllLifecyclePhasesAndInvokeCallbackIfAny() {
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
if (callback_queue_.size() > 0) {
InvokeCallback();
}
@@ -63,14 +98,35 @@ class ImagePaintTimingDetectorTest : public PageTestBase,
void SetImageAndPaint(AtomicString id, int width, int height) {
Element* element = GetDocument().getElementById(id);
// Set image and make it loaded.
- SetImageForTest(ToHTMLImageElement(element), width, height);
+ ImageResourceContent* content = CreateImageForTest(width, height);
+ ToHTMLImageElement(element)->SetImageForTest(content);
+ }
+
+ void SetVideoImageAndPaint(AtomicString id, int width, int height) {
+ Element* element = GetDocument().getElementById(id);
+ // Set image and make it loaded.
+ ImageResourceContent* content = CreateImageForTest(width, height);
+ ToHTMLVideoElement(element)->SetImageForTest(content);
+ }
+
+ void SetSVGImageAndPaint(AtomicString id, int width, int height) {
+ Element* element = GetDocument().getElementById(id);
+ // Set image and make it loaded.
+ ImageResourceContent* content = CreateImageForTest(width, height);
+ ToSVGImageElement(element)->SetImageForTest(content);
+ }
+
+ void RegisterMockedHttpURLLoad(const std::string& file_name) {
+ url_test_helpers::RegisterMockedURLLoadFromBase(
+ WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
+ WebString::FromUTF8(file_name));
}
private:
void FakeNotifySwapTime(WebLayerTreeView::ReportTimeCallback callback) {
callback_queue_.push(std::move(callback));
}
- void SetImageForTest(HTMLImageElement* image_element, int width, int height) {
+ ImageResourceContent* CreateImageForTest(int width, int height) {
sk_sp<SkColorSpace> src_rgb_color_space = SkColorSpace::MakeSRGB();
SkImageInfo raster_image_info =
SkImageInfo::MakeN32Premul(width, height, src_rgb_color_space);
@@ -79,17 +135,18 @@ class ImagePaintTimingDetectorTest : public PageTestBase,
ImageResourceContent* original_image_resource =
ImageResourceContent::CreateLoaded(
StaticBitmapImage::Create(image).get());
- image_element->SetImageForTest(original_image_resource);
+ return original_image_resource;
}
CallbackQueue callback_queue_;
+ std::string base_url_;
};
TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_NoImage) {
SetBodyInnerHTML(R"HTML(
<div></div>
)HTML");
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_FALSE(record);
}
@@ -102,10 +159,24 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_OneImage) {
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_EQ(record->first_size, 25);
+ EXPECT_EQ(record->first_size, 25ul);
EXPECT_TRUE(record->loaded);
}
+TEST_F(ImagePaintTimingDetectorTest,
+ IgnoreImageUntilInvalidatedRectSizeNonZero) {
+ SetBodyInnerHTML(R"HTML(
+ <img id="target"></img>
+ )HTML");
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ EXPECT_EQ(CountRecords(), 0u);
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ ImageRecord* record = FindLargestPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_EQ(CountRecords(), 1u);
+}
+
TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_Largest) {
SetBodyInnerHTML(R"HTML(
<img id="smaller"></img>
@@ -117,16 +188,16 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_Largest) {
ImageRecord* record;
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_EQ(record->first_size, 25);
+ EXPECT_EQ(record->first_size, 25ul);
SetImageAndPaint("larger", 9, 9);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
#if defined(OS_MACOSX)
- EXPECT_EQ(record->first_size, 90);
+ EXPECT_EQ(record->first_size, 90ul);
#else
- EXPECT_EQ(record->first_size, 81);
+ EXPECT_EQ(record->first_size, 81ul);
#endif
EXPECT_TRUE(record->loaded);
@@ -135,9 +206,9 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_Largest) {
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
#if defined(OS_MACOSX)
- EXPECT_EQ(record->first_size, 90);
+ EXPECT_EQ(record->first_size, 90ul);
#else
- EXPECT_EQ(record->first_size, 81);
+ EXPECT_EQ(record->first_size, 81ul);
#endif
EXPECT_TRUE(record->loaded);
}
@@ -170,55 +241,151 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_IgnoreTheRemoved) {
ImageRecord* record;
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
+ EXPECT_NE(LargestPaintStoredResult(), base::TimeTicks());
GetDocument().getElementById("parent")->RemoveChild(
GetDocument().getElementById("target"));
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
record = FindLargestPaintCandidate();
EXPECT_FALSE(record);
+ EXPECT_EQ(LargestPaintStoredResult(), base::TimeTicks());
}
TEST_F(ImagePaintTimingDetectorTest,
- LargestImagePaint_OneSwapPromiseForOneFrame) {
+ LargestImagePaint_NodeRemovedBetweenRegistrationAndInvocation) {
SetBodyInnerHTML(R"HTML(
<div id="parent">
- <img id="1"></img>
- <img id="2"></img>
+ <img id="target"></img>
</div>
)HTML");
- SetImageAndPaint("1", 5, 5);
- GetFrameView().UpdateAllLifecyclePhases();
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesForTest();
- SetImageAndPaint("2", 9, 9);
- GetFrameView().UpdateAllLifecyclePhases();
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("target"));
InvokeCallback();
+
+ ImageRecord* record;
+ record = FindLargestPaintCandidate();
+ EXPECT_FALSE(record);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_IgnoreReAttached) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ </div>
+ )HTML");
+ HTMLImageElement* image = HTMLImageElement::Create(GetDocument());
+ image->setAttribute("id", "target");
+ GetDocument().getElementById("parent")->AppendChild(image);
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
ImageRecord* record;
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
-#if defined(OS_MACOSX)
- EXPECT_EQ(record->first_size, 90);
-#else
- EXPECT_EQ(record->first_size, 81);
-#endif
- EXPECT_TRUE(record->first_paint_time_after_loaded.is_null());
+ GetDocument().getElementById("parent")->RemoveChild(image);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ record = FindLargestPaintCandidate();
+ EXPECT_FALSE(record);
+
+ GetDocument().getElementById("parent")->AppendChild(image);
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ record = FindLargestPaintCandidate();
+ EXPECT_TRUE(record);
+}
+
+// This test dipicts a situation when a smaller image has loaded, but a larger
+// image is loading. When we call analyze, the result will be empty because
+// we don't know when the largest image will finish loading. We wait until
+// next analysis to make the judgement again.
+// This bahavior is the same with Last Image Paint as well.
+TEST_F(ImagePaintTimingDetectorTest, DiscardAnalysisWhenLargestIsLoading) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img height="5" width="5" id="1"></img>
+ <img height="9" width="9" id="2"></img>
+ </div>
+ )HTML");
+ SetImageAndPaint("1", 5, 5);
+ UpdateAllLifecyclePhasesForTest();
+ ImageRecord* record;
+ InvokeCallback();
+ record = FindLargestPaintCandidate();
+ EXPECT_FALSE(record);
+
+ SetImageAndPaint("2", 9, 9);
+ UpdateAllLifecyclePhasesForTest();
InvokeCallback();
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
#if defined(OS_MACOSX)
- EXPECT_EQ(record->first_size, 90);
+ EXPECT_EQ(record->first_size, 90ul);
#else
- EXPECT_EQ(record->first_size, 81);
+ EXPECT_EQ(record->first_size, 81ul);
#endif
EXPECT_FALSE(record->first_paint_time_after_loaded.is_null());
}
+// This is to prove that a swap time is assigned only to nodes of the frame who
+// register the swap time. In other words, swap time A should match frame A;
+// swap time B should match frame B.
+TEST_F(ImagePaintTimingDetectorTest, MatchSwapTimeToNodesOfDifferentFrames) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img height="5" width="5" id="smaller"></img>
+ <img height="9" width="9" id="larger"></img>
+ </div>
+ )HTML");
+
+ SetImageAndPaint("larger", 9, 9);
+ UpdateAllLifecyclePhasesForTest();
+ SetImageAndPaint("smaller", 5, 5);
+ UpdateAllLifecyclePhasesForTest();
+ InvokeCallback();
+ // record1 is the larger.
+ ImageRecord* record1 = FindLargestPaintCandidate();
+ const base::TimeTicks record1Time = record1->first_paint_time_after_loaded;
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("larger"));
+ UpdateAllLifecyclePhasesForTest();
+ InvokeCallback();
+ // record2 is the smaller.
+ ImageRecord* record2 = FindLargestPaintCandidate();
+ EXPECT_NE(record1Time, record2->first_paint_time_after_loaded);
+}
+
+TEST_F(ImagePaintTimingDetectorTest,
+ LargestImagePaint_UpdateResultWhenLargestChanged) {
+ TimeTicks time1 = CurrentTimeTicks();
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img id="target1"></img>
+ <img id="target2"></img>
+ </div>
+ )HTML");
+ SetImageAndPaint("target1", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ TimeTicks time2 = CurrentTimeTicks();
+ TimeTicks result1 = LargestPaintStoredResult();
+ EXPECT_GE(result1, time1);
+ EXPECT_GE(time2, result1);
+
+ SetImageAndPaint("target2", 10, 10);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ TimeTicks time3 = CurrentTimeTicks();
+ TimeTicks result2 = LargestPaintStoredResult();
+ EXPECT_GE(result2, time2);
+ EXPECT_GE(time3, result2);
+}
+
TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_NoImage) {
SetBodyInnerHTML(R"HTML(
<div></div>
)HTML");
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ImageRecord* record = FindLastPaintCandidate();
EXPECT_FALSE(record);
}
@@ -233,46 +400,86 @@ TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_OneImage) {
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
ImageRecord* record = FindLastPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_GT(record->first_size, 0);
+ EXPECT_GT(record->first_size, 0ul);
EXPECT_TRUE(record->loaded);
}
TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_Last) {
+ WTF::ScopedMockClock clock;
SetBodyInnerHTML(R"HTML(
<div id="parent">
- <img id="1"></img>
- <img id="2"></img>
- <img id="3"></img>
+ <img height="10" width="10" id="1"></img>
+ <img height="5" width="5" id="2"></img>
+ <img height="7" width="7" id="3"></img>
</div>
)HTML");
- TimeTicks time1 = CurrentTimeTicks();
+ UpdateAllLifecyclePhasesForTest();
SetImageAndPaint("1", 10, 10);
- UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ UpdateAllLifecyclePhasesForTest();
+ clock.Advance(TimeDelta::FromSecondsD(1));
+ InvokeCallback();
+
ImageRecord* record;
record = FindLastPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_GE(record->first_paint_time_after_loaded, time1);
+ EXPECT_EQ(record->first_size, 100ul);
+ EXPECT_EQ(record->first_paint_time_after_loaded,
+ base::TimeTicks() + TimeDelta::FromSecondsD(1));
- TimeTicks time2 = CurrentTimeTicks();
SetImageAndPaint("2", 5, 5);
- UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ UpdateAllLifecyclePhasesForTest();
+ clock.Advance(TimeDelta::FromSecondsD(1));
+ InvokeCallback();
+
record = FindLastPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_GE(record->first_paint_time_after_loaded, time2);
+#if defined(OS_MACOSX)
+ EXPECT_EQ(record->first_size, 30ul);
+#else
+ EXPECT_EQ(record->first_size, 25ul);
+#endif
+ EXPECT_EQ(record->first_paint_time_after_loaded,
+ base::TimeTicks() + TimeDelta::FromSecondsD(2));
- TimeTicks time3 = CurrentTimeTicks();
SetImageAndPaint("3", 7, 7);
- UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ UpdateAllLifecyclePhasesForTest();
+ clock.Advance(TimeDelta::FromSecondsD(1));
+ // 6th s
+ InvokeCallback();
record = FindLastPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_GE(record->first_paint_time_after_loaded, time3);
+ EXPECT_GE(record->first_paint_time_after_loaded,
+ base::TimeTicks() + TimeDelta::FromSecondsD(3));
GetDocument().getElementById("parent")->RemoveChild(
GetDocument().getElementById("3"));
record = FindLastPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_GE(record->first_paint_time_after_loaded, time2);
- EXPECT_LE(record->first_paint_time_after_loaded, time3);
+ EXPECT_GE(record->first_paint_time_after_loaded,
+ base::TimeTicks() + TimeDelta::FromSecondsD(2));
+}
+
+TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_LastBasedOnLoadTime) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img height="5" width="5" id="1"></img>
+ </div>
+ )HTML");
+ Element* image = GetDocument().CreateRawElement(html_names::kImgTag);
+ image->setAttribute(html_names::kIdAttr, "2");
+ image->setAttribute(html_names::kHeightAttr, "10");
+ image->setAttribute(html_names::kWidthAttr, "10");
+ GetDocument().getElementById("parent")->appendChild(image);
+ SetImageAndPaint("2", 10, 10);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+
+ SetImageAndPaint("1", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+
+ ImageRecord* record;
+ record = FindLastPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_EQ(record->first_size, 25ul);
}
TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_IgnoreTheRemoved) {
@@ -319,19 +526,19 @@ TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_OneSwapPromiseForOneFrame) {
</div>
)HTML");
SetImageAndPaint("1", 5, 5);
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
SetImageAndPaint("2", 9, 9);
- GetFrameView().UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
InvokeCallback();
ImageRecord* record;
record = FindLastPaintCandidate();
EXPECT_TRUE(record);
#if defined(OS_MACOSX)
- EXPECT_EQ(record->first_size, 90);
+ EXPECT_EQ(record->first_size, 90ul);
#else
- EXPECT_EQ(record->first_size, 81);
+ EXPECT_EQ(record->first_size, 81ul);
#endif
EXPECT_TRUE(record->first_paint_time_after_loaded.is_null());
@@ -339,11 +546,141 @@ TEST_F(ImagePaintTimingDetectorTest, LastImagePaint_OneSwapPromiseForOneFrame) {
record = FindLastPaintCandidate();
EXPECT_TRUE(record);
#if defined(OS_MACOSX)
- EXPECT_EQ(record->first_size, 90);
+ EXPECT_EQ(record->first_size, 90ul);
#else
- EXPECT_EQ(record->first_size, 81);
+ EXPECT_EQ(record->first_size, 81ul);
#endif
EXPECT_FALSE(record->first_paint_time_after_loaded.is_null());
}
+TEST_F(ImagePaintTimingDetectorTest,
+ LastImagePaint_UpdateResultWhenLastChanged) {
+ TimeTicks time1 = CurrentTimeTicks();
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img id="target1"></img>
+ </div>
+ )HTML");
+ SetImageAndPaint("target1", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ TimeTicks time2 = CurrentTimeTicks();
+ TimeTicks result1 = LastPaintStoredResult();
+ EXPECT_GE(result1, time1);
+ EXPECT_GE(time2, result1);
+
+ Element* image = GetDocument().CreateRawElement(html_names::kImgTag);
+ image->setAttribute(html_names::kIdAttr, "target2");
+ GetDocument().getElementById("parent")->appendChild(image);
+ SetImageAndPaint("target2", 2, 2);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ TimeTicks time3 = CurrentTimeTicks();
+ TimeTicks result2 = LastPaintStoredResult();
+ EXPECT_GE(result2, time2);
+ EXPECT_GE(time3, result2);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, VideoImage) {
+ SetBodyInnerHTML(R"HTML(
+ <video id="target" poster="http://example.com/nonexistant.gif"></video>
+ )HTML");
+
+ SetVideoImageAndPaint("target", 5, 5);
+
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ ImageRecord* record = FindLastPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_GT(record->first_size, 0ul);
+ EXPECT_TRUE(record->loaded);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, VideoImage_ImageNotLoaded) {
+ SetBodyInnerHTML(R"HTML(
+ <video id="target" poster="http://example.com/nonexistant.gif"></video>
+ )HTML");
+
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ ImageRecord* record = FindLastPaintCandidate();
+ EXPECT_FALSE(record);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, SVGImage) {
+ SetBodyInnerHTML(R"HTML(
+ <svg>
+ <image id="target" width="10" height="10"
+ xlink:href="http://example.com/nonexistant.jpg"/>
+ </svg>
+ )HTML");
+
+ SetSVGImageAndPaint("target", 5, 5);
+
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ ImageRecord* record = FindLastPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_GT(record->first_size, 0ul);
+ EXPECT_TRUE(record->loaded);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, BackgroundImage) {
+ RegisterMockedHttpURLLoad("white-1x1.png");
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ div {
+ background-image: url('white-1x1.png');
+ }
+ </style>
+ <div>
+ place-holder
+ </div>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+ ImageRecord* record = FindLastPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_EQ(CountRecords(), 1u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreBody) {
+ RegisterMockedHttpURLLoad("white-1x1.png");
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ body {
+ background-image: url('white-1x1.png');
+ }
+ </style>
+ <body>
+ </body>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(CountRecords(), 0u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreHtml) {
+ RegisterMockedHttpURLLoad("white-1x1.png");
+ SetBodyInnerHTML(R"HTML(
+ <html>
+ <style>
+ html {
+ background-image: url('white-1x1.png');
+ }
+ </style>
+ </html>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(CountRecords(), 0u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreGradient) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ div {
+ background-image: linear-gradient(blue, yellow);
+ }
+ </style>
+ <div>
+ place-holder
+ </div>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(CountRecords(), 0u);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/image_painter.cc b/chromium/third_party/blink/renderer/core/paint/image_painter.cc
index f9eeb52ca2e..c8c341eac76 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/image_painter.cc
@@ -22,6 +22,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/display_item_cache_skipper.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/path.h"
+#include "third_party/blink/renderer/platform/graphics/placeholder_image.h"
#include "third_party/blink/renderer/platform/graphics/scoped_interpolation_quality.h"
namespace blink {
@@ -52,6 +53,8 @@ void ImagePainter::PaintAreaElementFocusRing(const PaintInfo& paint_info) {
// do it for an area within an image, so we don't call
// LayoutTheme::themeDrawsFocusRing here.
+ // We use EnsureComputedStyle() instead of GetComputedStyle() here because
+ // <area> is used and its style applied even if it has display:none.
const ComputedStyle& area_element_style = *area_element.EnsureComputedStyle();
// If the outline width is 0 we want to avoid drawing anything even if we
// don't use the value directly.
@@ -172,8 +175,8 @@ void ImagePainter::PaintIntoRect(GraphicsContext& context,
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage",
"data",
- InspectorPaintImageEvent::Data(layout_image_, src_rect,
- FloatRect(dest_rect)));
+ inspector_paint_image_event::Data(layout_image_, src_rect,
+ FloatRect(dest_rect)));
ScopedInterpolationQuality interpolation_quality_scope(
context, layout_image_.StyleRef().GetInterpolationQuality());
@@ -184,6 +187,17 @@ void ImagePainter::PaintIntoRect(GraphicsContext& context,
? ToHTMLImageElement(node)->GetDecodingModeForPainting(
image->paint_image_id())
: Image::kUnspecifiedDecode;
+
+ if (layout_image_.IsImagePolicyViolated()) {
+ // Does not set an observer for the placeholder image, setting it to null.
+ scoped_refptr<PlaceholderImage> placeholder_image =
+ PlaceholderImage::Create(nullptr, image->Size(),
+ image->Data() ? image->Data()->size() : 0);
+ placeholder_image->SetIconAndTextScaleFactor(
+ layout_image_.GetFrame()->PageZoomFactor());
+ image = std::move(placeholder_image);
+ }
+
context.DrawImage(
image.get(), decode_mode, FloatRect(pixel_snapped_dest_rect), &src_rect,
SkBlendMode::kSrcOver,
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.cc b/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.cc
index a5320c2361f..bd82f77257b 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
namespace blink {
@@ -56,7 +57,7 @@ void InlineFlowBoxPainter::Paint(const PaintInfo& paint_info,
inline_flow_box_.FlipForWritingMode(overflow_rect);
overflow_rect.MoveBy(paint_offset);
- if (!paint_info.GetCullRect().IntersectsCullRect(overflow_rect))
+ if (!paint_info.GetCullRect().Intersects(overflow_rect))
return;
if (paint_info.phase == PaintPhase::kMask) {
@@ -239,12 +240,10 @@ void InlineFlowBoxPainter::PaintMask(const PaintInfo& paint_info,
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, inline_flow_box_,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase)))
+ paint_info.context, inline_flow_box_, paint_info.phase))
return;
- DrawingRecorder recorder(
- paint_info.context, inline_flow_box_,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase));
+ DrawingRecorder recorder(paint_info.context, inline_flow_box_,
+ paint_info.phase);
LayoutRect paint_rect = AdjustedPaintRect(paint_offset);
@@ -337,11 +336,15 @@ void InlineFlowBoxPainter::RecordHitTestData(const PaintInfo& paint_info,
LayoutObject* layout_object =
LineLayoutAPIShim::LayoutObjectFrom(inline_flow_box_.GetLineLayoutItem());
+ // If an object is not visible, it does not participate in hit testing.
+ if (layout_object->StyleRef().Visibility() != EVisibility::kVisible)
+ return;
+
auto touch_action = layout_object->EffectiveWhitelistedTouchAction();
if (touch_action == TouchAction::kTouchActionAuto)
return;
- HitTestData::RecordHitTestRect(
+ HitTestDisplayItem::Record(
paint_info.context, inline_flow_box_,
HitTestRect(AdjustedPaintRect(paint_offset), touch_action));
}
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_painter.cc b/chromium/third_party/blink/renderer/core/paint/inline_painter.cc
index b7b15f77950..c410d15e3a8 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/inline_painter.cc
@@ -22,7 +22,7 @@ void InlinePainter::Paint(const PaintInfo& paint_info) {
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
// Inline box with self painting layer is painted in this code path.
- if (auto* block_flow = layout_inline_.EnclosingNGBlockFlow()) {
+ if (auto* block_flow = layout_inline_.ContainingNGBlockFlow()) {
if (auto* block_flow_fragment = block_flow->PaintFragment()) {
block_flow_fragment->PaintInlineBoxForDescendants(
local_paint_info, paint_offset, &layout_inline_);
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.cc b/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.cc
index f1cecb66571..d5abae00013 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.cc
@@ -77,7 +77,7 @@ static LineLayoutItem EnclosingUnderlineObject(
return current;
if (Node* node = current.GetNode()) {
- if (IsHTMLAnchorElement(node) || node->HasTagName(HTMLNames::fontTag))
+ if (IsHTMLAnchorElement(node) || node->HasTagName(html_names::kFontTag))
return current;
}
}
@@ -147,11 +147,9 @@ void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
base::Optional<DrawingRecorder> recorder;
if (paint_info.phase != PaintPhase::kTextClip) {
if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, inline_text_box_,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase)))
+ paint_info.context, inline_text_box_, paint_info.phase))
return;
- recorder.emplace(paint_info.context, inline_text_box_,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase));
+ recorder.emplace(paint_info.context, inline_text_box_, paint_info.phase);
}
GraphicsContext& context = paint_info.context;
diff --git a/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.cc b/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.cc
index a2bcd6715c6..b09c84aa9cb 100644
--- a/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.cc
+++ b/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.cc
@@ -59,7 +59,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "third_party/skia/include/core/SkMatrix44.h"
#include "ui/gfx/geometry/rect.h"
@@ -246,6 +246,13 @@ bool LinkHighlightImpl::ComputeHighlightLayerPathAndPosition(
content_layer_->SetPosition(bounding_rect.Location());
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
+ FloatPoint offset(current_graphics_layer_->GetOffsetFromTransformNode());
+ offset.MoveBy(bounding_rect.Location());
+ content_layer_->SetOffsetToTransformParent(
+ gfx::Vector2dF(offset.X(), offset.Y()));
+ }
+
return path_has_changed;
}
@@ -310,15 +317,14 @@ void LinkHighlightImpl::StartHighlightAnimationIfNeeded() {
curve->AddKeyframe(CompositorFloatKeyframe(
extra_duration_required.InSecondsF(), kStartOpacity, timing_function));
}
- // For layout tests we don't fade out.
+ // For web tests we don't fade out.
curve->AddKeyframe(CompositorFloatKeyframe(
(kFadeDuration + extra_duration_required).InSecondsF(),
- LayoutTestSupport::IsRunningLayoutTest() ? kStartOpacity : 0,
- timing_function));
+ WebTestSupport::IsRunningWebTest() ? kStartOpacity : 0, timing_function));
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
- CompositorKeyframeModel::Create(*curve, CompositorTargetProperty::OPACITY,
- 0, 0);
+ CompositorKeyframeModel::Create(
+ *curve, compositor_target_property::OPACITY, 0, 0);
content_layer_->SetIsDrawable(true);
compositor_animation_->AddKeyframeModel(std::move(keyframe_model));
@@ -348,6 +354,12 @@ class LinkHighlightDisplayItemClientForTracking : public DisplayItemClient {
};
void LinkHighlightImpl::UpdateGeometry() {
+ if (!node_ || !node_->GetLayoutObject()) {
+ ClearGraphicsLayerLinkHighlightPointer();
+ ReleaseResources();
+ return;
+ }
+
// To avoid unnecessary updates (e.g. other entities have requested animations
// from our WebViewImpl), only proceed if we actually requested an update.
if (!geometry_needs_update_)
@@ -355,28 +367,22 @@ void LinkHighlightImpl::UpdateGeometry() {
geometry_needs_update_ = false;
- bool has_layout_object = node_ && node_->GetLayoutObject();
- if (has_layout_object) {
- const LayoutBoxModelObject& paint_invalidation_container =
- node_->GetLayoutObject()->ContainerForPaintInvalidation();
- AttachLinkHighlightToCompositingLayer(paint_invalidation_container);
- if (ComputeHighlightLayerPathAndPosition(paint_invalidation_container)) {
- // We only need to invalidate the layer if the highlight size has changed,
- // otherwise we can just re-position the layer without needing to
- // repaint.
- content_layer_->SetNeedsDisplay();
-
- if (current_graphics_layer_) {
- gfx::Rect rect = gfx::ToEnclosingRect(
- gfx::RectF(Layer()->position(), gfx::SizeF(Layer()->bounds())));
- current_graphics_layer_->TrackRasterInvalidation(
- LinkHighlightDisplayItemClientForTracking(), IntRect(rect),
- PaintInvalidationReason::kFullLayer);
- }
+ const LayoutBoxModelObject& paint_invalidation_container =
+ node_->GetLayoutObject()->ContainerForPaintInvalidation();
+ AttachLinkHighlightToCompositingLayer(paint_invalidation_container);
+ if (ComputeHighlightLayerPathAndPosition(paint_invalidation_container)) {
+ // We only need to invalidate the layer if the highlight size has changed,
+ // otherwise we can just re-position the layer without needing to
+ // repaint.
+ content_layer_->SetNeedsDisplay();
+
+ if (current_graphics_layer_) {
+ gfx::Rect rect = gfx::ToEnclosingRect(
+ gfx::RectF(Layer()->position(), gfx::SizeF(Layer()->bounds())));
+ current_graphics_layer_->TrackRasterInvalidation(
+ LinkHighlightDisplayItemClientForTracking(), IntRect(rect),
+ PaintInvalidationReason::kFullLayer);
}
- } else {
- ClearGraphicsLayerLinkHighlightPointer();
- ReleaseResources();
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc b/chromium/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc
index 3282070f328..313cc562e8f 100644
--- a/chromium/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc
@@ -76,7 +76,7 @@ class LinkHighlightImplTest : public testing::Test,
}
void SetUp() override {
- WebURL url = URLTestHelpers::RegisterMockedURLLoadFromBase(
+ WebURL url = url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8("http://www.test.com/"), test::CoreTestDataPath(),
WebString::FromUTF8("test_touch_link_highlight.html"));
web_view_helper_.InitializeAndLoad(url.GetString().Utf8());
@@ -108,7 +108,12 @@ class LinkHighlightImplTest : public testing::Test,
return local_frame_view->GetPaintArtifactCompositorForTesting();
}
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ void UpdateAllLifecyclePhases() {
+ web_view_helper_.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
+ }
+
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
INSTANTIATE_TEST_CASE_P(All, LinkHighlightImplTest, testing::Bool());
@@ -118,7 +123,7 @@ TEST_P(LinkHighlightImplTest, verifyWebViewImplIntegration) {
int page_width = 640;
int page_height = 480;
web_view_impl->Resize(WebSize(page_width, page_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
WebGestureEvent touch_event(WebInputEvent::kGestureShowPress,
WebInputEvent::kNoModifiers,
@@ -171,7 +176,7 @@ TEST_P(LinkHighlightImplTest, resetDuringNodeRemoval) {
int page_width = 640;
int page_height = 480;
web_view_impl->Resize(WebSize(page_width, page_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
WebGestureEvent touch_event(WebInputEvent::kGestureShowPress,
WebInputEvent::kNoModifiers,
@@ -193,7 +198,7 @@ TEST_P(LinkHighlightImplTest, resetDuringNodeRemoval) {
EXPECT_TRUE(highlight_layer->GetLinkHighlights().at(0));
touch_node->remove(IGNORE_EXCEPTION_FOR_TESTING);
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(0U, highlight_layer->GetLinkHighlights().size());
}
@@ -204,7 +209,7 @@ TEST_P(LinkHighlightImplTest, resetLayerTreeView) {
int page_width = 640;
int page_height = 480;
web_view_impl->Resize(WebSize(page_width, page_height));
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
WebGestureEvent touch_event(WebInputEvent::kGestureShowPress,
WebInputEvent::kNoModifiers,
@@ -238,7 +243,7 @@ TEST_P(LinkHighlightImplTest, HighlightLayerEffectNode) {
web_view_impl->Resize(WebSize(page_width, page_height));
paint_artifact_compositor()->EnableExtraDataForTesting();
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
size_t layer_count_before_highlight = ContentLayerCount();
WebGestureEvent touch_event(WebInputEvent::kGestureShowPress,
@@ -272,7 +277,7 @@ TEST_P(LinkHighlightImplTest, HighlightLayerEffectNode) {
EXPECT_TRUE(highlight->effect()->RequiresCompositingForAnimation());
touch_node->remove(IGNORE_EXCEPTION_FOR_TESTING);
- web_view_impl->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
// Removing the highlight layer should drop the cc layer count by one.
EXPECT_EQ(layer_count_before_highlight, ContentLayerCount());
}
diff --git a/chromium/third_party/blink/renderer/core/paint/list_marker_painter.cc b/chromium/third_party/blink/renderer/core/paint/list_marker_painter.cc
index a8567658ffd..4653f90e542 100644
--- a/chromium/third_party/blink/renderer/core/paint/list_marker_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/list_marker_painter.cc
@@ -144,8 +144,8 @@ void ListMarkerPainter::Paint(const PaintInfo& paint_info) {
// Text is not arbitrary. We can judge whether it's RTL from the first
// character, and we only need to handle the direction RightToLeft for now.
bool text_needs_reversing =
- WTF::Unicode::Direction(layout_list_marker_.GetText()[0]) ==
- WTF::Unicode::kRightToLeft;
+ WTF::unicode::Direction(layout_list_marker_.GetText()[0]) ==
+ WTF::unicode::kRightToLeft;
StringBuilder reversed_text;
if (text_needs_reversing) {
unsigned length = layout_list_marker_.GetText().length();
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
index 23ee4bd5b2b..226cd35199c 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
@@ -33,6 +33,7 @@
#include "third_party/blink/renderer/core/paint/object_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/paint_phase.h"
#include "third_party/blink/renderer/core/paint/scoped_paint_state.h"
#include "third_party/blink/renderer/core/paint/scrollable_area_painter.h"
@@ -41,6 +42,7 @@
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/display_item_cache_skipper.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
namespace blink {
@@ -200,6 +202,10 @@ void NGBoxFragmentPainter::RecordHitTestData(const PaintInfo& paint_info,
if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
return;
+ // If an object is not visible, it does not participate in hit testing.
+ if (box_fragment_.Style().Visibility() != EVisibility::kVisible)
+ return;
+
const NGPhysicalFragment& physical_fragment = PhysicalFragment();
auto touch_action = physical_fragment.EffectiveWhitelistedTouchAction();
if (touch_action == TouchAction::kTouchActionAuto)
@@ -214,7 +220,7 @@ void NGBoxFragmentPainter::RecordHitTestData(const PaintInfo& paint_info,
if (physical_fragment.IsInline())
border_box.offset += box_fragment_.InlineOffsetToContainerBox();
border_box.offset += NGPhysicalOffset(paint_offset);
- HitTestData::RecordHitTestRect(
+ HitTestDisplayItem::Record(
paint_info.context, box_fragment_,
HitTestRect(border_box.ToLayoutRect(), touch_action));
}
@@ -314,17 +320,15 @@ void NGBoxFragmentPainter::PaintBlockFlowContents(
LayoutRect overflow_rect(box_fragment_.ChildrenInkOverflow());
overflow_rect.MoveBy(paint_offset);
- if (!paint_info.GetCullRect().IntersectsCullRect(overflow_rect))
+ if (!paint_info.GetCullRect().Intersects(overflow_rect))
return;
if (paint_info.phase == PaintPhase::kMask) {
if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, box_fragment_,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase)))
+ paint_info.context, box_fragment_, paint_info.phase))
return;
- DrawingRecorder recorder(
- paint_info.context, box_fragment_,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase));
+ DrawingRecorder recorder(paint_info.context, box_fragment_,
+ paint_info.phase);
PaintMask(paint_info, paint_offset);
return;
}
@@ -353,7 +357,7 @@ void NGBoxFragmentPainter::PaintInlineChild(const NGPaintFragment& child,
}
void NGBoxFragmentPainter::PaintBlockChildren(const PaintInfo& paint_info) {
- for (const auto& child : box_fragment_.Children()) {
+ for (const NGPaintFragment* child : box_fragment_.Children()) {
const NGPhysicalFragment& fragment = child->PhysicalFragment();
if (child->HasSelfPaintingLayer() || fragment.IsFloating())
continue;
@@ -371,9 +375,9 @@ void NGBoxFragmentPainter::PaintBlockChildren(const PaintInfo& paint_info) {
}
void NGBoxFragmentPainter::PaintFloatingChildren(
- const Vector<scoped_refptr<NGPaintFragment>>& children,
+ NGPaintFragment::ChildList children,
const PaintInfo& paint_info) {
- for (const auto& child : children) {
+ for (const NGPaintFragment* child : children) {
const NGPhysicalFragment& fragment = child->PhysicalFragment();
if (child->HasSelfPaintingLayer())
continue;
@@ -450,8 +454,7 @@ void NGBoxFragmentPainter::PaintBoxDecorationBackground(
LayoutRect paint_rect;
base::Optional<ScopedBoxContentsPaintState> contents_paint_state;
- if (IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- box_fragment_, paint_info)) {
+ if (IsPaintingScrollingBackground(box_fragment_, paint_info)) {
// For the case where we are painting the background into the scrolling
// contents layer of a composited scroller we need to include the entire
// overflow rect.
@@ -484,11 +487,9 @@ void NGBoxFragmentPainter::PaintBoxDecorationBackground(
bool NGBoxFragmentPainter::BackgroundIsKnownToBeOpaque(
const PaintInfo& paint_info) {
const LayoutBox& layout_box = ToLayoutBox(*box_fragment_.GetLayoutObject());
- LayoutRect bounds =
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- box_fragment_, paint_info)
- ? layout_box.LayoutOverflowRect()
- : layout_box.SelfVisualOverflowRect();
+ LayoutRect bounds = IsPaintingScrollingBackground(box_fragment_, paint_info)
+ ? layout_box.LayoutOverflowRect()
+ : layout_box.SelfVisualOverflowRect();
return layout_box.BackgroundIsKnownToBeOpaqueInRect(bounds);
}
@@ -501,8 +502,7 @@ void NGBoxFragmentPainter::PaintBoxDecorationBackgroundWithRect(
const LayoutBox& layout_box = ToLayoutBox(layout_object);
bool painting_overflow_contents =
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- box_fragment_, paint_info);
+ IsPaintingScrollingBackground(box_fragment_, paint_info);
const ComputedStyle& style = box_fragment_.Style();
base::Optional<DisplayItemCacheSkipper> cache_skipper;
@@ -519,11 +519,10 @@ void NGBoxFragmentPainter::PaintBoxDecorationBackgroundWithRect(
}
const DisplayItemClient& display_item_client =
- painting_overflow_contents ? static_cast<const DisplayItemClient&>(
- *layout_box.Layer()
- ->GetCompositedLayerMapping()
- ->ScrollingContentsLayer())
- : box_fragment_;
+ painting_overflow_contents
+ ? layout_box.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient()
+ : box_fragment_;
if (DrawingRecorder::UseCachedDrawingIfPossible(
paint_info.context, display_item_client,
DisplayItem::kBoxDecorationBackground))
@@ -544,7 +543,15 @@ void NGBoxFragmentPainter::PaintBoxDecorationBackgroundWithRect(
PaintNormalBoxShadow(paint_info, paint_rect, style, border_edges_.line_left,
border_edges_.line_right);
- if (BleedAvoidanceIsClipping(box_decoration_data.bleed_avoidance)) {
+ if (box_fragment_.HasSelfPaintingLayer() && layout_box.IsTableCell() &&
+ ToLayoutTableCell(layout_box).Table()->ShouldCollapseBorders()) {
+ // We have to clip here because the background would paint on top of the
+ // collapsed table borders otherwise, since this is a self-painting layer.
+ LayoutRect clip_rect = paint_rect;
+ clip_rect.Expand(ToLayoutTableCell(layout_box).BorderInsets());
+ state_saver.Save();
+ paint_info.context.Clip(PixelSnappedIntRect(clip_rect));
+ } else if (BleedAvoidanceIsClipping(box_decoration_data.bleed_avoidance)) {
state_saver.Save();
FloatRoundedRect border = style.GetRoundedBorderFor(
paint_rect, border_edges_.line_left, border_edges_.line_right);
@@ -611,9 +618,7 @@ void NGBoxFragmentPainter::PaintBackground(
BackgroundBleedAvoidance bleed_avoidance) {
const LayoutObject& layout_object = *box_fragment_.GetLayoutObject();
const LayoutBox& layout_box = ToLayoutBox(layout_object);
- if (layout_box.IsDocumentElement())
- return;
- if (layout_box.BackgroundStolenForBeingBody())
+ if (layout_box.BackgroundTransfersToView())
return;
if (layout_box.BackgroundIsKnownToBeObscured())
return;
@@ -698,10 +703,9 @@ void NGBoxFragmentPainter::PaintAllPhasesAtomically(
}
void NGBoxFragmentPainter::PaintLineBoxChildren(
- const Vector<scoped_refptr<NGPaintFragment>>& line_boxes,
+ NGPaintFragment::ChildList line_boxes,
const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
-
// Only paint during the foreground/selection phases.
if (paint_info.phase != PaintPhase::kForeground &&
paint_info.phase != PaintPhase::kSelection &&
@@ -725,7 +729,7 @@ void NGBoxFragmentPainter::PaintLineBoxChildren(
return;
// TODO(layout-dev): Early return if no line intersects cull rect.
- for (const auto& line : line_boxes) {
+ for (const NGPaintFragment* line : line_boxes) {
if (line->PhysicalFragment().IsFloatingOrOutOfFlowPositioned())
continue;
const LayoutPoint child_offset =
@@ -741,10 +745,10 @@ void NGBoxFragmentPainter::PaintLineBoxChildren(
}
void NGBoxFragmentPainter::PaintInlineChildren(
- const Vector<scoped_refptr<NGPaintFragment>>& inline_children,
+ NGPaintFragment::ChildList inline_children,
const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
- for (const auto& child : inline_children) {
+ for (const NGPaintFragment* child : inline_children) {
if (child->PhysicalFragment().IsFloating())
continue;
if (child->PhysicalFragment().IsAtomicInline()) {
@@ -756,7 +760,7 @@ void NGBoxFragmentPainter::PaintInlineChildren(
}
void NGBoxFragmentPainter::PaintInlineChildrenOutlines(
- const Vector<scoped_refptr<NGPaintFragment>>& line_boxes,
+ NGPaintFragment::ChildList line_boxes,
const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
// TODO(layout-dev): Implement.
@@ -797,11 +801,9 @@ void NGBoxFragmentPainter::PaintTextChild(const NGPaintFragment& text_fragment,
base::Optional<DrawingRecorder> recorder;
if (paint_info.phase != PaintPhase::kTextClip) {
if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, text_fragment,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase)))
+ paint_info.context, text_fragment, paint_info.phase))
return;
- recorder.emplace(paint_info.context, text_fragment,
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase));
+ recorder.emplace(paint_info.context, text_fragment, paint_info.phase);
}
const NGPhysicalTextFragment& physical_text_fragment =
@@ -848,10 +850,9 @@ void NGBoxFragmentPainter::PaintAtomicInline(const PaintInfo& paint_info) {
PaintAllPhasesAtomically(paint_info, is_self_painting);
}
-bool NGBoxFragmentPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- const NGPaintFragment& fragment,
- const PaintInfo& paint_info) {
+bool NGBoxFragmentPainter::IsPaintingScrollingBackground(
+ const NGPaintFragment& fragment,
+ const PaintInfo& paint_info) {
// TODO(layout-dev): Change paint_info.PaintContainer to accept fragments
// once LayoutNG supports scrolling containers.
return paint_info.PaintFlags() & kPaintLayerPaintingOverflowContents &&
@@ -916,8 +917,7 @@ LayoutRect NGBoxFragmentPainter::AdjustRectForScrolledContent(
// Clip to the overflow area.
if (info.is_clipped_with_local_scrolling &&
- !IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- box_fragment_, paint_info)) {
+ !IsPaintingScrollingBackground(box_fragment_, paint_info)) {
context.Clip(FloatRect(physical.OverflowClipRect(rect.Location())));
// Adjust the paint rect to reflect a scrolled content box with borders at
@@ -1170,12 +1170,14 @@ bool NGBoxFragmentPainter::HitTestChildBoxFragment(
bool NGBoxFragmentPainter::HitTestChildren(
HitTestResult& result,
- const Vector<scoped_refptr<NGPaintFragment>>& children,
+ NGPaintFragment::ChildList children,
const HitTestLocation& location_in_container,
const LayoutPoint& accumulated_offset,
HitTestAction action) {
- for (auto iter = children.rbegin(); iter != children.rend(); iter++) {
- const scoped_refptr<NGPaintFragment>& child = *iter;
+ Vector<NGPaintFragment*, 16> child_vector;
+ children.ToList(&child_vector);
+ for (unsigned i = child_vector.size(); i;) {
+ const NGPaintFragment* child = child_vector[--i];
const NGPhysicalOffset offset = child->Offset();
if (child->HasSelfPaintingLayer())
continue;
@@ -1206,8 +1208,7 @@ bool NGBoxFragmentPainter::HitTestChildren(
continue;
// Hit test culled inline boxes between |fragment| and its parent fragment.
- const NGPaintFragment* previous_sibling =
- std::next(iter) == children.rend() ? nullptr : std::next(iter)->get();
+ const NGPaintFragment* previous_sibling = i ? child_vector[i - 1] : nullptr;
if (HitTestCulledInlineAncestors(result, *child, previous_sibling,
location_in_container,
child_physical_offset))
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h
index 269fbdd14ad..440d6ad9892 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_border_edges.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/paint/box_painter_base.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -21,7 +22,6 @@ class HitTestLocation;
class HitTestRequest;
class HitTestResult;
class LayoutRect;
-class NGPaintFragment;
class NGPhysicalFragment;
class ScopedPaintState;
struct PaintInfo;
@@ -64,9 +64,7 @@ class NGBoxFragmentPainter : public BoxPainterBase {
const LayoutRect&) override;
private:
- bool IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- const NGPaintFragment&,
- const PaintInfo&);
+ bool IsPaintingScrollingBackground(const NGPaintFragment&, const PaintInfo&);
bool ShouldPaint(const ScopedPaintState&) const;
void PaintBoxDecorationBackground(const PaintInfo&,
@@ -78,16 +76,15 @@ class NGBoxFragmentPainter : public BoxPainterBase {
void PaintAllPhasesAtomically(const PaintInfo&,
bool is_self_painting);
void PaintBlockChildren(const PaintInfo&);
- void PaintLineBoxChildren(const Vector<scoped_refptr<NGPaintFragment>>&,
+ void PaintLineBoxChildren(NGPaintFragment::ChildList,
const PaintInfo&,
const LayoutPoint& paint_offset);
- void PaintInlineChildren(const Vector<scoped_refptr<NGPaintFragment>>&,
+ void PaintInlineChildren(NGPaintFragment::ChildList,
const PaintInfo&,
const LayoutPoint& paint_offset);
- void PaintInlineChildrenOutlines(
- const Vector<scoped_refptr<NGPaintFragment>>&,
- const PaintInfo&,
- const LayoutPoint& paint_offset);
+ void PaintInlineChildrenOutlines(NGPaintFragment::ChildList,
+ const PaintInfo&,
+ const LayoutPoint& paint_offset);
void PaintInlineChildBoxUsingLegacyFallback(const NGPhysicalFragment&,
const PaintInfo&);
void PaintBlockFlowContents(const PaintInfo&,
@@ -99,8 +96,7 @@ class NGBoxFragmentPainter : public BoxPainterBase {
void PaintTextChild(const NGPaintFragment&,
const PaintInfo&,
const LayoutPoint& paint_offset);
- void PaintFloatingChildren(const Vector<scoped_refptr<NGPaintFragment>>&,
- const PaintInfo&);
+ void PaintFloatingChildren(NGPaintFragment::ChildList, const PaintInfo&);
void PaintFloats(const PaintInfo&);
void PaintMask(const PaintInfo&, const LayoutPoint& paint_offset);
void PaintOverflowControlsIfNeeded(const PaintInfo&,
@@ -127,7 +123,7 @@ class NGBoxFragmentPainter : public BoxPainterBase {
// box in paint layer. Note that this includes scrolling offset when the
// container has 'overflow: scroll'.
bool HitTestChildren(HitTestResult&,
- const Vector<scoped_refptr<NGPaintFragment>>&,
+ NGPaintFragment::ChildList,
const HitTestLocation& location_in_container,
const LayoutPoint& physical_offset,
HitTestAction);
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc
index edcc67c4e24..603f9a6837d 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc
@@ -24,9 +24,9 @@ void NGFieldsetPainter::PaintBoxDecorationBackground(
const LayoutPoint paint_offset) {
const NGPaintFragment* legend = nullptr;
if (fieldset_.Children().size()) {
- const auto first_child = fieldset_.Children()[0];
- if (first_child->PhysicalFragment().IsRenderedLegend())
- legend = &(*first_child);
+ const auto& first_child = fieldset_.Children().front();
+ if (first_child.PhysicalFragment().IsRenderedLegend())
+ legend = &first_child;
}
// Paint the fieldset (background, other decorations, and) border, with the
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc
index 5881265aa5c..81a6fad320b 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc
@@ -34,6 +34,18 @@ namespace blink {
namespace {
+struct SameSizeAsNGPaintFragment : public RefCounted<NGPaintFragment>,
+ public DisplayItemClient,
+ public ImageResourceObserver {
+ void* pointers[6];
+ NGPhysicalOffset offsets[2];
+ LayoutRect rects[1];
+ unsigned flags;
+};
+
+static_assert(sizeof(NGPaintFragment) == sizeof(SameSizeAsNGPaintFragment),
+ "NGPaintFragment should stay small.");
+
NGLogicalRect ComputeLogicalRectFor(const NGPhysicalOffsetRect& physical_rect,
const NGPaintFragment& paint_fragment) {
const WritingMode writing_mode = paint_fragment.Style().GetWritingMode();
@@ -55,7 +67,7 @@ NGPhysicalOffsetRect ComputePhysicalRectFor(
paint_fragment.PhysicalFragment().ResolvedDirection();
const NGPhysicalSize outer_size = paint_fragment.Size();
const NGPhysicalSize physical_size =
- logical_rect.size.ConvertToPhysical(writing_mode);
+ ToNGPhysicalSize(logical_rect.size, writing_mode);
const NGPhysicalOffset physical_offset =
logical_rect.offset.ConvertToPhysical(writing_mode, text_direction,
outer_size, physical_size);
@@ -72,7 +84,7 @@ NGLogicalRect ExpandedSelectionRectForSoftLineBreakIfNeeded(
if (selection_status.line_break == SelectSoftLineBreak::kNotSelected)
return rect;
if (paint_fragment.GetLayoutObject()
- ->EnclosingNGBlockFlow()
+ ->ContainingNGBlockFlow()
->ShouldTruncateOverflowingText())
return rect;
// Copy from InlineTextBoxPainter::PaintSelection.
@@ -164,7 +176,57 @@ NGPaintFragment::NGPaintFragment(
DCHECK(physical_fragment_);
}
-NGPaintFragment::~NGPaintFragment() = default;
+NGPaintFragment::~NGPaintFragment() {
+ // The default destructor will deref |first_child_|, but because children are
+ // in a linked-list, it will call this destructor recursively. Remove children
+ // first non-recursively to avoid stack overflow when there are many chlidren.
+ RemoveChildren();
+}
+
+void NGPaintFragment::RemoveChildren() {
+ scoped_refptr<NGPaintFragment> child = std::move(first_child_);
+ DCHECK(!first_child_);
+ while (child) {
+ child = std::move(child->next_sibling_);
+ }
+}
+
+template <typename Traverse>
+NGPaintFragment& NGPaintFragment::List<Traverse>::front() const {
+ DCHECK(first_);
+ return *first_;
+}
+
+template <typename Traverse>
+NGPaintFragment& NGPaintFragment::List<Traverse>::back() const {
+ DCHECK(first_);
+ NGPaintFragment* last = first_;
+ for (NGPaintFragment* fragment : *this)
+ last = fragment;
+ return *last;
+}
+
+template <typename Traverse>
+wtf_size_t NGPaintFragment::List<Traverse>::size() const {
+ wtf_size_t size = 0;
+ for (NGPaintFragment* fragment : *this) {
+ ANALYZER_ALLOW_UNUSED(fragment);
+ ++size;
+ }
+ return size;
+}
+
+template <typename Traverse>
+void NGPaintFragment::List<Traverse>::ToList(
+ Vector<NGPaintFragment*, 16>* list) const {
+ if (UNLIKELY(!list->IsEmpty()))
+ list->Shrink(0);
+ if (IsEmpty())
+ return;
+ list->ReserveCapacity(size());
+ for (NGPaintFragment* fragment : *this)
+ list->push_back(fragment);
+}
void NGPaintFragment::SetShouldDoFullPaintInvalidation() {
if (LayoutObject* layout_object = GetLayoutObject())
@@ -183,17 +245,23 @@ scoped_refptr<NGPaintFragment> NGPaintFragment::CreateOrReuse(
// Re-using NGPaintFragment allows the paint system to identify objects.
if (previous_instance) {
DCHECK_EQ(previous_instance->parent_, parent);
+ DCHECK(!previous_instance->next_sibling_);
+// TODO(kojii): This fails some tests when reusing line box was enabled.
+// Investigate and re-enable.
+#if 0
// If the physical fragment was re-used, re-use the paint fragment as well.
if (&previous_instance->PhysicalFragment() == fragment.get()) {
previous_instance->offset_ = offset;
previous_instance->next_for_same_layout_object_ = nullptr;
+ previous_instance->is_dirty_inline_ = false;
// No need to re-populate children because NGPhysicalFragment is
// immutable and thus children should not have been changed.
*populate_children = false;
previous_instance->SetShouldDoFullPaintInvalidation();
return previous_instance;
}
+#endif
// If the LayoutObject are the same, the new paint fragment should have the
// same DisplayItemClient identity as the previous instance.
@@ -201,8 +269,9 @@ scoped_refptr<NGPaintFragment> NGPaintFragment::CreateOrReuse(
previous_instance->physical_fragment_ = std::move(fragment);
previous_instance->offset_ = offset;
previous_instance->next_for_same_layout_object_ = nullptr;
+ previous_instance->is_dirty_inline_ = false;
if (!*populate_children)
- previous_instance->children_.clear();
+ previous_instance->first_child_ = nullptr;
previous_instance->SetShouldDoFullPaintInvalidation();
return previous_instance;
}
@@ -233,6 +302,12 @@ scoped_refptr<NGPaintFragment> NGPaintFragment::Create(
return paint_fragment;
}
+NGPaintFragment::RareData& NGPaintFragment::EnsureRareData() {
+ if (!rare_data_)
+ rare_data_ = std::make_unique<RareData>();
+ return *rare_data_;
+}
+
void NGPaintFragment::UpdateFromCachedLayoutResult(
scoped_refptr<const NGPhysicalFragment> fragment,
NGPhysicalOffset offset) {
@@ -243,11 +318,14 @@ void NGPaintFragment::UpdateFromCachedLayoutResult(
// children do not change.
const NGPhysicalContainerFragment& container_fragment =
ToNGPhysicalContainerFragment(*fragment);
- DCHECK_EQ(Children().size(), container_fragment.Children().size());
- for (unsigned i = 0; i < container_fragment.Children().size(); i++) {
- DCHECK_EQ(Children()[i]->physical_fragment_.get(),
+ NGPaintFragment* child = FirstChild();
+ for (unsigned i = 0; i < container_fragment.Children().size();
+ i++, child = child->NextSibling()) {
+ DCHECK(child);
+ DCHECK_EQ(child->physical_fragment_.get(),
container_fragment.Children()[i].get());
}
+ DCHECK(!child);
#endif
DCHECK_EQ(physical_fragment_.get(), fragment.get());
@@ -257,16 +335,22 @@ void NGPaintFragment::UpdateFromCachedLayoutResult(
NGPaintFragment* NGPaintFragment::Last(const NGBreakToken& break_token) {
for (NGPaintFragment* fragment = this; fragment;
- fragment = fragment->next_fragmented_.get()) {
+ fragment = fragment->Next()) {
if (fragment->PhysicalFragment().BreakToken() == &break_token)
return fragment;
}
return nullptr;
}
+NGPaintFragment* NGPaintFragment::Next() {
+ if (!rare_data_)
+ return nullptr;
+ return rare_data_->next_fragmented_.get();
+}
+
NGPaintFragment* NGPaintFragment::Last() {
for (NGPaintFragment* fragment = this;;) {
- NGPaintFragment* next = fragment->next_fragmented_.get();
+ NGPaintFragment* next = fragment->Next();
if (!next)
return fragment;
fragment = next;
@@ -288,7 +372,8 @@ scoped_refptr<NGPaintFragment>* NGPaintFragment::Find(
if (!*fragment)
return fragment;
- scoped_refptr<NGPaintFragment>* next = &(*fragment)->next_fragmented_;
+ scoped_refptr<NGPaintFragment>* next =
+ &(*fragment)->EnsureRareData().next_fragmented_;
if ((*fragment)->PhysicalFragment().BreakToken() == break_token)
return next;
fragment = next;
@@ -297,7 +382,9 @@ scoped_refptr<NGPaintFragment>* NGPaintFragment::Find(
}
void NGPaintFragment::SetNext(scoped_refptr<NGPaintFragment> fragment) {
- next_fragmented_ = std::move(fragment);
+ if (!rare_data_ && !fragment)
+ return;
+ EnsureRareData().next_fragmented_ = std::move(fragment);
}
bool NGPaintFragment::IsDescendantOfNotSelf(
@@ -325,6 +412,18 @@ bool NGPaintFragment::ShouldClipOverflow() const {
ToNGPhysicalBoxFragment(*physical_fragment_).ShouldClipOverflow();
}
+LayoutRect NGPaintFragment::SelectionVisualRect() const {
+ if (!rare_data_)
+ return LayoutRect();
+ return rare_data_->selection_visual_rect_;
+}
+
+void NGPaintFragment::SetSelectionVisualRect(const LayoutRect& rect) {
+ if (!rare_data_ && rect.IsEmpty())
+ return;
+ EnsureRareData().selection_visual_rect_ = rect;
+}
+
LayoutRect NGPaintFragment::SelfInkOverflow() const {
return physical_fragment_->InkOverflow().ToLayoutRect();
}
@@ -341,20 +440,23 @@ void NGPaintFragment::PopulateDescendants(
DCHECK(fragment.IsContainer());
const NGPhysicalContainerFragment& container =
ToNGPhysicalContainerFragment(fragment);
- children_.ReserveCapacity(container.Children().size());
+ scoped_refptr<NGPaintFragment> previous_children = std::move(first_child_);
+ scoped_refptr<NGPaintFragment>* last_child_ptr = &first_child_;
bool children_are_inline =
!fragment.IsBox() || ToNGPhysicalBoxFragment(fragment).ChildrenInline();
- unsigned child_index = 0;
for (const NGLink& child_fragment : container.Children()) {
bool populate_children = child_fragment->IsContainer() &&
!child_fragment->IsBlockFormattingContextRoot();
- scoped_refptr<NGPaintFragment> child = CreateOrReuse(
- child_fragment.get(), child_fragment.Offset(), this,
- child_index < children_.size() ? std::move(children_[child_index])
- : nullptr,
- &populate_children);
+ scoped_refptr<NGPaintFragment> previous_child;
+ if (previous_children) {
+ previous_child = std::move(previous_children);
+ previous_children = std::move(previous_child->next_sibling_);
+ }
+ scoped_refptr<NGPaintFragment> child =
+ CreateOrReuse(child_fragment.get(), child_fragment.Offset(), this,
+ std::move(previous_child), &populate_children);
if (children_are_inline) {
if (!child_fragment->IsFloating() &&
@@ -373,15 +475,10 @@ void NGPaintFragment::PopulateDescendants(
}
}
- if (child_index < children_.size())
- children_[child_index] = std::move(child);
- else
- children_.push_back(std::move(child));
- ++child_index;
+ DCHECK(!*last_child_ptr);
+ *last_child_ptr = std::move(child);
+ last_child_ptr = &((*last_child_ptr)->next_sibling_);
}
-
- if (child_index < children_.size())
- children_.resize(child_index);
}
// Add to a linked list for each LayoutObject.
@@ -406,22 +503,16 @@ void NGPaintFragment::AssociateWithLayoutObject(
NGPaintFragment* NGPaintFragment::GetForInlineContainer(
const LayoutObject* layout_object) {
DCHECK(layout_object && layout_object->IsInline());
- // Search from its parent because |EnclosingNGBlockFlow| returns itself when
- // the LayoutObject is a box (i.e., atomic inline, including inline block and
- // replaced elements.)
- if (LayoutObject* parent = layout_object->Parent()) {
- if (LayoutBlockFlow* block_flow = parent->EnclosingNGBlockFlow()) {
- if (NGPaintFragment* fragment = block_flow->PaintFragment())
- return fragment;
-
- // TODO(kojii): IsLayoutFlowThread should probably be done in
- // EnclosingNGBlockFlow(), but there seem to be both expectations today.
- // This needs cleanup.
- if (block_flow->IsLayoutFlowThread()) {
- DCHECK(block_flow->Parent() &&
- block_flow->Parent()->IsLayoutBlockFlow());
- return ToLayoutBlockFlow(block_flow->Parent())->PaintFragment();
- }
+ if (LayoutBlockFlow* block_flow = layout_object->ContainingNGBlockFlow()) {
+ if (NGPaintFragment* fragment = block_flow->PaintFragment())
+ return fragment;
+
+ // TODO(kojii): IsLayoutFlowThread should probably be done in
+ // ContainingNGBlockFlow(), but there seem to be both expectations today.
+ // This needs cleanup.
+ if (block_flow->IsLayoutFlowThread()) {
+ DCHECK(block_flow->Parent() && block_flow->Parent()->IsLayoutBlockFlow());
+ return ToLayoutBlockFlow(block_flow->Parent())->PaintFragment();
}
}
return nullptr;
@@ -437,25 +528,20 @@ NGPaintFragment::FragmentRange NGPaintFragment::InlineFragmentsFor(
return FragmentRange(nullptr, false);
}
+const NGPaintFragment* NGPaintFragment::LastForSameLayoutObject() const {
+ return const_cast<NGPaintFragment*>(this)->LastForSameLayoutObject();
+}
+
+NGPaintFragment* NGPaintFragment::LastForSameLayoutObject() {
+ NGPaintFragment* fragment = this;
+ while (fragment->next_for_same_layout_object_)
+ fragment = fragment->next_for_same_layout_object_;
+ return fragment;
+}
+
void NGPaintFragment::DirtyLinesFromChangedChild(LayoutObject* child) {
- if (child->IsInline()) {
- LayoutBlockFlow* const block = child->EnclosingNGBlockFlow();
- if (block && block->PaintFragment())
- MarkLineBoxesDirtyFor(*child);
- }
- if (!child->IsInLayoutNGInlineFormattingContext())
- return;
- // We should rest first inline fragment for following tests:
- // * fast/dom/HTMLObjectElement/fallback-content-behaviour.html
- // * fast/dom/shadow/exposed-object-within-shadow.html
- // * fast/lists/inline-before-content-after-list-marker.html
- // * fast/lists/list-with-image-display-changed.html
- for (LayoutObject* runner = child; runner;
- runner = runner->NextInPreOrder(child)) {
- if (!runner->IsInLayoutNGInlineFormattingContext())
- continue;
- runner->SetFirstInlineFragment(nullptr);
- }
+ if (child->IsInline())
+ MarkLineBoxesDirtyFor(*child);
}
bool NGPaintFragment::FlippedLocalVisualRectFor(
@@ -483,11 +569,11 @@ bool NGPaintFragment::FlippedLocalVisualRectFor(
void NGPaintFragment::UpdateVisualRectForNonLayoutObjectChildren() {
// Scan direct children only beause line boxes are always direct children of
// the inline formatting context.
- for (auto& child : Children()) {
+ for (NGPaintFragment* child : Children()) {
if (!child->PhysicalFragment().IsLineBox())
continue;
LayoutRect union_of_children;
- for (const auto& descendant : child->Children())
+ for (const NGPaintFragment* descendant : child->Children())
union_of_children.Unite(descendant->VisualRect());
child->SetVisualRect(union_of_children);
}
@@ -512,7 +598,7 @@ void NGPaintFragment::PaintInlineBoxForDescendants(
const LayoutInline* layout_object,
NGPhysicalOffset offset) const {
DCHECK(layout_object);
- for (const auto& child : Children()) {
+ for (const NGPaintFragment* child : Children()) {
if (child->GetLayoutObject() == layout_object) {
NGInlineBoxFragmentPainter(*child).Paint(
paint_info, paint_offset + offset.ToLayoutPoint() /*, paint_offset*/);
@@ -536,43 +622,55 @@ const NGPaintFragment* NGPaintFragment::ContainerLineBox() const {
}
NGPaintFragment* NGPaintFragment::FirstLineBox() const {
- for (auto& child : children_) {
+ for (NGPaintFragment* child : Children()) {
if (child->PhysicalFragment().IsLineBox())
- return child.get();
+ return child;
}
return nullptr;
}
void NGPaintFragment::MarkLineBoxesDirtyFor(const LayoutObject& layout_object) {
DCHECK(layout_object.IsInline()) << layout_object;
- if (TryMarkLineBoxDirtyFor(layout_object))
- return;
+
// Since |layout_object| isn't in fragment tree, check preceding siblings.
// Note: Once we reuse lines below dirty lines, we should check next siblings.
for (LayoutObject* previous = layout_object.PreviousSibling(); previous;
previous = previous->PreviousSibling()) {
+ // If the previoius object had never been laid out, it should have already
+ // marked the line box dirty.
+ if (!previous->EverHadLayout())
+ return;
+
if (previous->IsFloatingOrOutOfFlowPositioned())
continue;
+
// |previous| may not be in inline formatting context, e.g. <object>.
- if (TryMarkLineBoxDirtyFor(*previous))
+ if (TryMarkLastLineBoxDirtyFor(*previous))
return;
}
- // There is no siblings, try parent.
+
+ // There is no siblings, try parent. If it's a non-atomic inline (e.g., span),
+ // mark dirty for it, but if it's an atomic inline (e.g., inline block), do
+ // not propagate across inline formatting context boundary.
const LayoutObject& parent = *layout_object.Parent();
- if (parent.IsInline())
+ if (parent.IsInline() && !parent.IsAtomicInlineLevel())
return MarkLineBoxesDirtyFor(parent);
- if (!parent.IsLayoutNGMixin())
- return;
- const LayoutBlockFlow& block = ToLayoutBlockFlow(parent);
- if (!block.PaintFragment()) {
- // We have not yet layout.
- return;
+
+ // The |layout_object| is inserted into an empty block.
+ // Mark the first line box dirty.
+ if (parent.IsLayoutNGMixin()) {
+ const LayoutBlockFlow& block = ToLayoutBlockFlow(parent);
+ if (NGPaintFragment* paint_fragment = block.PaintFragment()) {
+ if (NGPaintFragment* first_line = paint_fragment->FirstLineBox()) {
+ first_line->is_dirty_inline_ = true;
+ return;
+ }
+ }
}
- // We inserted |layout_object| into empty block.
- block.PaintFragment()->FirstLineBox()->is_dirty_inline_ = true;
}
-void NGPaintFragment::MarkLineBoxDirty() {
+void NGPaintFragment::MarkContainingLineBoxDirty() {
+ DCHECK(PhysicalFragment().IsInline() || PhysicalFragment().IsLineBox());
for (NGPaintFragment* fragment :
NGPaintFragmentTraversal::InclusiveAncestorsOf(*this)) {
if (fragment->is_dirty_inline_)
@@ -584,13 +682,27 @@ void NGPaintFragment::MarkLineBoxDirty() {
NOTREACHED() << this; // Should have a line box ancestor.
}
-bool NGPaintFragment::TryMarkLineBoxDirtyFor(
+bool NGPaintFragment::TryMarkFirstLineBoxDirtyFor(
+ const LayoutObject& layout_object) {
+ if (!layout_object.IsInLayoutNGInlineFormattingContext())
+ return false;
+ // Once we reuse lines below dirty lines, we should mark lines for all
+ // inline fragments.
+ if (NGPaintFragment* const fragment = layout_object.FirstInlineFragment()) {
+ fragment->MarkContainingLineBoxDirty();
+ return true;
+ }
+ return false;
+}
+
+bool NGPaintFragment::TryMarkLastLineBoxDirtyFor(
const LayoutObject& layout_object) {
+ if (!layout_object.IsInLayoutNGInlineFormattingContext())
+ return false;
// Once we reuse lines below dirty lines, we should mark lines for all
// inline fragments.
- NGPaintFragment* const first_fragment = layout_object.FirstInlineFragment();
- if (first_fragment) {
- first_fragment->MarkLineBoxDirty();
+ if (NGPaintFragment* const fragment = layout_object.FirstInlineFragment()) {
+ fragment->LastForSameLayoutObject()->MarkContainingLineBoxDirty();
return true;
}
return false;
@@ -600,7 +712,7 @@ void NGPaintFragment::SetShouldDoFullPaintInvalidationRecursively() {
if (LayoutObject* layout_object = GetLayoutObject())
layout_object->SetShouldDoFullPaintInvalidation();
- for (auto& child : children_)
+ for (NGPaintFragment* child : Children())
child->SetShouldDoFullPaintInvalidationRecursively();
}
@@ -660,14 +772,12 @@ PositionWithAffinity NGPaintFragment::PositionForPointInText(
if (text_fragment.IsAnonymousText())
return PositionWithAffinity();
const unsigned text_offset = text_fragment.TextOffsetForPoint(point);
+ const NGCaretPosition unadjusted_position{
+ this, NGCaretPositionType::kAtTextOffset, text_offset};
if (text_offset > text_fragment.StartOffset() &&
text_offset < text_fragment.EndOffset()) {
- const Position position = NGOffsetMapping::GetFor(GetLayoutObject())
- ->GetFirstPosition(text_offset);
- return PositionWithAffinity(position, TextAffinity::kDownstream);
+ return unadjusted_position.ToPositionInDOMTreeWithAffinity();
}
- const NGCaretPosition unadjusted_position{
- this, NGCaretPositionType::kAtTextOffset, text_offset};
return BidiAdjustment::AdjustForHitTest(unadjusted_position)
.ToPositionInDOMTreeWithAffinity();
}
@@ -693,7 +803,7 @@ PositionWithAffinity NGPaintFragment::PositionForPointInInlineLevelBox(
const NGPaintFragment* closest_child_after = nullptr;
LayoutUnit closest_child_after_inline_offset = LayoutUnit::Max();
- for (const auto& child : Children()) {
+ for (const NGPaintFragment* child : Children()) {
const LayoutUnit child_inline_min =
ChildLogicalOffsetInParent(*child).inline_offset;
const LayoutUnit child_inline_max =
@@ -708,14 +818,14 @@ PositionWithAffinity NGPaintFragment::PositionForPointInInlineLevelBox(
if (inline_point < child_inline_min) {
if (child_inline_min < closest_child_after_inline_offset) {
- closest_child_after = child.get();
+ closest_child_after = child;
closest_child_after_inline_offset = child_inline_min;
}
}
if (inline_point > child_inline_max) {
if (child_inline_max > closest_child_before_inline_offset) {
- closest_child_before = child.get();
+ closest_child_before = child;
closest_child_before_inline_offset = child_inline_max;
}
}
@@ -758,7 +868,7 @@ PositionWithAffinity NGPaintFragment::PositionForPointInInlineFormattingContext(
const NGPaintFragment* closest_line_after = nullptr;
LayoutUnit closest_line_after_block_offset = LayoutUnit::Max();
- for (const auto& child : Children()) {
+ for (const NGPaintFragment* child : Children()) {
if (!child->PhysicalFragment().IsLineBox() || child->Children().IsEmpty())
continue;
@@ -777,14 +887,14 @@ PositionWithAffinity NGPaintFragment::PositionForPointInInlineFormattingContext(
if (block_point < line_min) {
if (line_min < closest_line_after_block_offset) {
- closest_line_after = child.get();
+ closest_line_after = child;
closest_line_after_block_offset = line_min;
}
}
if (block_point >= line_max) {
if (line_max > closest_line_before_block_offset) {
- closest_line_before = child.get();
+ closest_line_before = child;
closest_line_before_block_offset = line_max;
}
}
@@ -874,30 +984,6 @@ bool NGPaintFragment::ShouldPaintDragCaret() const {
return ToLayoutBlock(GetLayoutObject())->ShouldPaintDragCaret();
}
-// ----
-
-NGPaintFragment& NGPaintFragment::FragmentRange::front() const {
- DCHECK(first_);
- return *first_;
-}
-
-NGPaintFragment& NGPaintFragment::FragmentRange::back() const {
- DCHECK(first_);
- NGPaintFragment* last = first_;
- for (NGPaintFragment* fragment : *this)
- last = fragment;
- return *last;
-}
-
-wtf_size_t NGPaintFragment::FragmentRange::size() const {
- wtf_size_t size = 0;
- for (NGPaintFragment* fragment : *this) {
- ANALYZER_ALLOW_UNUSED(fragment);
- ++size;
- }
- return size;
-}
-
String NGPaintFragment::DebugName() const {
StringBuilder name;
@@ -923,4 +1009,9 @@ String NGPaintFragment::DebugName() const {
return name.ToString();
}
+template class CORE_TEMPLATE_EXPORT
+ NGPaintFragment::List<NGPaintFragment::TraverseNextForSameLayoutObject>;
+template class CORE_TEMPLATE_EXPORT
+ NGPaintFragment::List<NGPaintFragment::TraverseNextSibling>;
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h
index 631db023f44..7d331af509f 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h
@@ -58,20 +58,81 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
NGPhysicalOffset offset);
// Next/last fragment for when this is fragmented.
- NGPaintFragment* Next() { return next_fragmented_.get(); }
+ NGPaintFragment* Next();
void SetNext(scoped_refptr<NGPaintFragment>);
NGPaintFragment* Last();
NGPaintFragment* Last(const NGBreakToken&);
static scoped_refptr<NGPaintFragment>* Find(scoped_refptr<NGPaintFragment>*,
const NGBreakToken*);
+ template <typename Traverse>
+ class List {
+ public:
+ explicit List(NGPaintFragment* first) : first_(first) {}
+
+ class iterator final
+ : public std::iterator<std::forward_iterator_tag, NGPaintFragment*> {
+ public:
+ explicit iterator(NGPaintFragment* first) : current_(first) {}
+
+ NGPaintFragment* operator*() const { return current_; }
+ NGPaintFragment* operator->() const { return current_; }
+ iterator& operator++() {
+ DCHECK(current_);
+ current_ = Traverse::Next(current_);
+ return *this;
+ }
+ bool operator==(const iterator& other) const {
+ return current_ == other.current_;
+ }
+ bool operator!=(const iterator& other) const {
+ return current_ != other.current_;
+ }
+
+ private:
+ NGPaintFragment* current_;
+ };
+
+ CORE_EXPORT iterator begin() const { return iterator(first_); }
+ CORE_EXPORT iterator end() const { return iterator(nullptr); }
+
+ // Returns the first |NGPaintFragment| in |FragmentRange| as STL container.
+ // It is error to call |front()| for empty range.
+ NGPaintFragment& front() const;
+
+ // Returns the last |NGPaintFragment| in |FragmentRange| as STL container.
+ // It is error to call |back()| for empty range.
+ // Note: The complexity of |back()| is O(n) where n is number of elements
+ // in this |FragmentRange|.
+ NGPaintFragment& back() const;
+
+ // Returns number of fragments in this range. The complexity is O(n) where n
+ // is number of elements.
+ wtf_size_t size() const;
+ CORE_EXPORT bool IsEmpty() const { return !first_; }
+
+ void ToList(Vector<NGPaintFragment*, 16>*) const;
+
+ private:
+ NGPaintFragment* first_;
+ };
+
+ class TraverseNextSibling {
+ public:
+ static NGPaintFragment* Next(NGPaintFragment* current) {
+ return current->next_sibling_.get();
+ }
+ };
+ using ChildList = List<TraverseNextSibling>;
+
// The parent NGPaintFragment. This is nullptr for a root; i.e., when parent
// is not for NGPaint. In the first phase, this means that this is a root of
// an inline formatting context.
NGPaintFragment* Parent() const { return parent_; }
- const Vector<scoped_refptr<NGPaintFragment>>& Children() const {
- return children_;
- }
+ NGPaintFragment* FirstChild() const { return first_child_.get(); }
+ NGPaintFragment* NextSibling() const { return next_sibling_.get(); }
+ ChildList Children() const { return ChildList(first_child_.get()); }
+
// Note, as the name implies, |IsDescendantOfNotSelf| returns false for the
// same object. This is different from |LayoutObject::IsDescendant| but is
// same as |Node::IsDescendant|.
@@ -109,10 +170,8 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
LayoutRect VisualRect() const override { return visual_rect_; }
void SetVisualRect(const LayoutRect& rect) { visual_rect_ = rect; }
- LayoutRect SelectionVisualRect() const { return selection_visual_rect_; }
- void SetSelectionVisualRect(const LayoutRect& rect) {
- selection_visual_rect_ = rect;
- }
+ LayoutRect SelectionVisualRect() const;
+ void SetSelectionVisualRect(const LayoutRect& rect);
// CSS ink overflow https://www.w3.org/TR/css-overflow-3/#ink
// Encloses all pixels painted by self + children.
@@ -171,15 +230,23 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
}
// Returns true when associated fragment of |layout_object| has line box.
- static bool TryMarkLineBoxDirtyFor(const LayoutObject& layout_object);
+ static bool TryMarkFirstLineBoxDirtyFor(const LayoutObject& layout_object);
+ static bool TryMarkLastLineBoxDirtyFor(const LayoutObject& layout_object);
// A range of fragments for |FragmentsFor()|.
- class CORE_EXPORT FragmentRange {
+ class TraverseNextForSameLayoutObject {
+ public:
+ static NGPaintFragment* Next(NGPaintFragment* current) {
+ return current->next_for_same_layout_object_;
+ }
+ };
+ class CORE_EXPORT FragmentRange
+ : public List<TraverseNextForSameLayoutObject> {
public:
explicit FragmentRange(
NGPaintFragment* first,
bool is_in_layout_ng_inline_formatting_context = true)
- : first_(first),
+ : List(first),
is_in_layout_ng_inline_formatting_context_(
is_in_layout_ng_inline_formatting_context) {}
@@ -187,50 +254,7 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
return is_in_layout_ng_inline_formatting_context_;
}
- bool IsEmpty() const { return !first_; }
-
- class iterator final
- : public std::iterator<std::forward_iterator_tag, NGPaintFragment*> {
- public:
- explicit iterator(NGPaintFragment* first) : current_(first) {}
-
- NGPaintFragment* operator*() const { return current_; }
- NGPaintFragment* operator->() const { return current_; }
- iterator& operator++() {
- CHECK(current_);
- current_ = current_->next_for_same_layout_object_;
- return *this;
- }
- bool operator==(const iterator& other) const {
- return current_ == other.current_;
- }
- bool operator!=(const iterator& other) const {
- return current_ != other.current_;
- }
-
- private:
- NGPaintFragment* current_;
- };
-
- iterator begin() const { return iterator(first_); }
- iterator end() const { return iterator(nullptr); }
-
- // Returns the first |NGPaintFragment| in |FragmentRange| as STL container.
- // It is error to call |front()| for empty range.
- NGPaintFragment& front() const;
-
- // Returns the last |NGPaintFragment| in |FragmentRange| as STL container.
- // It is error to call |back()| for empty range.
- // Note: The complexity of |back()| is O(n) where n is number of elements
- // in this |FragmentRange|.
- NGPaintFragment& back() const;
-
- // Returns number of fragments in this range. The complexity is O(n) where n
- // is number of elements.
- wtf_size_t size() const;
-
private:
- NGPaintFragment* first_;
bool is_in_layout_ng_inline_formatting_context_;
};
@@ -246,9 +270,22 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
// for a LayoutObject.
static FragmentRange InlineFragmentsFor(const LayoutObject*);
+ const NGPaintFragment* LastForSameLayoutObject() const;
+ NGPaintFragment* LastForSameLayoutObject();
+
// Called when lines containing |child| is dirty.
static void DirtyLinesFromChangedChild(LayoutObject* child);
+ // Mark this line box was changed, in order to re-use part of an inline
+ // formatting context.
+ void MarkLineBoxDirty() {
+ DCHECK(PhysicalFragment().IsLineBox());
+ is_dirty_inline_ = true;
+ }
+
+ // Mark the line box that contains this fragment dirty.
+ void MarkContainingLineBoxDirty();
+
// Computes LocalVisualRect for an inline LayoutObject in the
// LayoutObject::LocalVisualRect semantics; i.e., physical coordinates with
// flipped block-flow direction. See layout/README.md for the coordinate
@@ -272,6 +309,8 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
LayoutObject*,
HashMap<const LayoutObject*, NGPaintFragment*>* last_fragment_map);
+ void RemoveChildren();
+
// Helps for PositionForPoint() when |this| falls in different categories.
PositionWithAffinity PositionForPointInText(const NGPhysicalOffset&) const;
PositionWithAffinity PositionForPointInInlineFormattingContext(
@@ -282,10 +321,6 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
// Dirty line boxes containing |layout_object|.
static void MarkLineBoxesDirtyFor(const LayoutObject& layout_object);
- // Mark this line box was changed, in order to re-use part of an inline
- // formatting context.
- void MarkLineBoxDirty();
-
//
// Following fields are computed in the layout phase.
//
@@ -294,10 +329,21 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
NGPhysicalOffset offset_;
NGPaintFragment* parent_;
- Vector<scoped_refptr<NGPaintFragment>> children_;
+ scoped_refptr<NGPaintFragment> first_child_;
+ scoped_refptr<NGPaintFragment> next_sibling_;
+
+ struct RareData {
+ USING_FAST_MALLOC(RareData);
+
+ public:
+ // The next fragment for when this is fragmented.
+ scoped_refptr<NGPaintFragment> next_fragmented_;
- // The next fragment for when this is fragmented.
- scoped_refptr<NGPaintFragment> next_fragmented_;
+ // Used for invalidating selected fragment.
+ LayoutRect selection_visual_rect_;
+ };
+ RareData& EnsureRareData();
+ std::unique_ptr<RareData> rare_data_;
NGPaintFragment* next_for_same_layout_object_ = nullptr;
NGPhysicalOffset inline_offset_to_container_box_;
@@ -313,9 +359,13 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
//
LayoutRect visual_rect_;
- LayoutRect selection_visual_rect_;
};
+extern template class CORE_EXTERN_TEMPLATE_EXPORT
+ NGPaintFragment::List<NGPaintFragment::TraverseNextForSameLayoutObject>;
+extern template class CORE_EXTERN_TEMPLATE_EXPORT
+ NGPaintFragment::List<NGPaintFragment::TraverseNextSibling>;
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_PAINT_FRAGMENT_H_
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_test.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_test.cc
index 33781b44cb3..c1a1fe50234 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_test.cc
@@ -30,11 +30,18 @@ class NGPaintFragmentTest : public RenderingTest,
const NGPaintFragment* root = GetPaintFragmentByElementId(id);
EXPECT_TRUE(root);
EXPECT_GE(1u, root->Children().size());
- const NGPaintFragment& line_box = *root->Children()[0];
+ const NGPaintFragment& line_box = *root->FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentLineBox,
line_box.PhysicalFragment().Type());
return line_box;
}
+
+ Vector<NGPaintFragment*, 16> ToList(
+ const NGPaintFragment::ChildList& children) {
+ Vector<NGPaintFragment*, 16> list;
+ children.ToList(&list);
+ return list;
+ }
};
TEST_F(NGPaintFragmentTest, InlineFragmentsFor) {
@@ -76,17 +83,17 @@ TEST_F(NGPaintFragmentTest, InlineFragmentsFor) {
EXPECT_EQ(NGPhysicalOffset(LayoutUnit(60), LayoutUnit()),
results[0]->InlineOffsetToContainerBox());
EXPECT_EQ("789", ToNGPhysicalTextFragment(
- results[0]->Children()[0]->PhysicalFragment())
+ results[0]->FirstChild()->PhysicalFragment())
.Text());
EXPECT_EQ(NGPhysicalOffset(LayoutUnit(), LayoutUnit(10)),
results[1]->InlineOffsetToContainerBox());
EXPECT_EQ("123456789", ToNGPhysicalTextFragment(
- results[1]->Children()[0]->PhysicalFragment())
+ results[1]->FirstChild()->PhysicalFragment())
.Text());
EXPECT_EQ(NGPhysicalOffset(LayoutUnit(), LayoutUnit(20)),
results[2]->InlineOffsetToContainerBox());
EXPECT_EQ("123", ToNGPhysicalTextFragment(
- results[2]->Children()[0]->PhysicalFragment())
+ results[2]->FirstChild()->PhysicalFragment())
.Text());
}
@@ -104,25 +111,25 @@ TEST_F(NGPaintFragmentTest, InlineBox) {
)HTML");
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_EQ(2u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(2u, line1.Children().size());
// Inline boxes without box decorations (border, background, etc.) do not
// generate box fragments and that their child fragments are placed directly
// under the line box.
- const NGPaintFragment& outer_text = *line1.Children()[0];
+ const NGPaintFragment& outer_text = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
outer_text.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 0, 60, 10), outer_text.VisualRect());
- const NGPaintFragment& inner_text1 = *line1.Children()[1];
+ const NGPaintFragment& inner_text1 = *ToList(line1.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 0, 30, 10), inner_text1.VisualRect());
- const NGPaintFragment& line2 = *container->Children()[1];
+ const NGPaintFragment& line2 = *ToList(container->Children())[1];
EXPECT_EQ(1u, line2.Children().size());
- const NGPaintFragment& inner_text2 = *line2.Children()[0];
+ const NGPaintFragment& inner_text2 = *line2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 10, 30, 10), inner_text2.VisualRect());
@@ -143,34 +150,34 @@ TEST_F(NGPaintFragmentTest, InlineBoxWithDecorations) {
)HTML");
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_EQ(2u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(2u, line1.Children().size());
- const NGPaintFragment& outer_text = *line1.Children()[0];
+ const NGPaintFragment& outer_text = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
outer_text.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 0, 60, 10), outer_text.VisualRect());
// Inline boxes with box decorations generate box fragments.
- const NGPaintFragment& inline_box1 = *line1.Children()[1];
+ const NGPaintFragment& inline_box1 = *ToList(line1.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentBox,
inline_box1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 0, 30, 10), inline_box1.VisualRect());
EXPECT_EQ(1u, inline_box1.Children().size());
- const NGPaintFragment& inner_text1 = *inline_box1.Children()[0];
+ const NGPaintFragment& inner_text1 = *inline_box1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 0, 30, 10), inner_text1.VisualRect());
- const NGPaintFragment& line2 = *container->Children()[1];
+ const NGPaintFragment& line2 = *ToList(container->Children())[1];
EXPECT_EQ(1u, line2.Children().size());
- const NGPaintFragment& inline_box2 = *line2.Children()[0];
+ const NGPaintFragment& inline_box2 = *line2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentBox,
inline_box2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 10, 30, 10), inline_box2.VisualRect());
- const NGPaintFragment& inner_text2 = *inline_box2.Children()[0];
+ const NGPaintFragment& inner_text2 = *inline_box2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 10, 30, 10), inner_text2.VisualRect());
@@ -195,11 +202,11 @@ TEST_F(NGPaintFragmentTest, InlineBlock) {
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_TRUE(container);
EXPECT_EQ(1u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(3u, line1.Children().size());
// Test the outer text "12345".
- const NGPaintFragment& outer_text = *line1.Children()[0];
+ const NGPaintFragment& outer_text = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
outer_text.PhysicalFragment().Type());
EXPECT_EQ("12345 ", ToNGPhysicalTextFragment(outer_text.PhysicalFragment())
@@ -219,7 +226,7 @@ TEST_F(NGPaintFragmentTest, InlineBlock) {
EXPECT_EQ(&outer_text, *fragments.begin());
// Test the inline block "box1".
- const NGPaintFragment& box1 = *line1.Children()[1];
+ const NGPaintFragment& box1 = *ToList(line1.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentBox, box1.PhysicalFragment().Type());
EXPECT_EQ(NGPhysicalFragment::kAtomicInline,
box1.PhysicalFragment().BoxType());
@@ -240,8 +247,8 @@ TEST_F(NGPaintFragmentTest, InlineBlock) {
EXPECT_EQ(box1_inner->GetLayoutObject(), box1.GetLayoutObject());
// Test the text fragment inside of the inline block.
- const NGPaintFragment& inner_line_box = *box1_inner->Children()[0];
- const NGPaintFragment& inner_text = *inner_line_box.Children()[0];
+ const NGPaintFragment& inner_line_box = *box1_inner->FirstChild();
+ const NGPaintFragment& inner_text = *inner_line_box.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 0, 10, 10), inner_text.VisualRect());
@@ -256,7 +263,7 @@ TEST_F(NGPaintFragmentTest, InlineBlock) {
EXPECT_EQ(&inner_text, *fragments.begin());
// Test the inline block "box2".
- const NGPaintFragment& box2 = *line1.Children()[2];
+ const NGPaintFragment& box2 = *ToList(line1.Children())[2];
EXPECT_EQ(NGPhysicalFragment::kFragmentBox, box2.PhysicalFragment().Type());
EXPECT_EQ(NGPhysicalFragment::kAtomicInline,
box2.PhysicalFragment().BoxType());
@@ -264,7 +271,7 @@ TEST_F(NGPaintFragmentTest, InlineBlock) {
EXPECT_EQ(LayoutRect(), box2.SelectionVisualRect());
GetDocument().GetFrame()->Selection().SelectAll();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(0, 0, 60, 10), outer_text.VisualRect());
EXPECT_EQ(LayoutRect(0, 0, 60, 10), outer_text.SelectionVisualRect());
EXPECT_EQ(LayoutRect(60, 0, 10, 10), box1.VisualRect());
@@ -290,22 +297,22 @@ TEST_F(NGPaintFragmentTest, RelativeBlock) {
)HTML");
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_EQ(2u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(2u, line1.Children().size());
- const NGPaintFragment& outer_text = *line1.Children()[0];
+ const NGPaintFragment& outer_text = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
outer_text.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 10, 60, 10), outer_text.VisualRect());
- const NGPaintFragment& inner_text1 = *line1.Children()[1];
+ const NGPaintFragment& inner_text1 = *ToList(line1.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 10, 30, 10), inner_text1.VisualRect());
- const NGPaintFragment& line2 = *container->Children()[1];
+ const NGPaintFragment& line2 = *ToList(container->Children())[1];
EXPECT_EQ(1u, line2.Children().size());
- const NGPaintFragment& inner_text2 = *line2.Children()[0];
+ const NGPaintFragment& inner_text2 = *line2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 20, 30, 10), inner_text2.VisualRect());
@@ -326,33 +333,33 @@ TEST_F(NGPaintFragmentTest, RelativeInline) {
)HTML");
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_EQ(2u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(2u, line1.Children().size());
- const NGPaintFragment& outer_text = *line1.Children()[0];
+ const NGPaintFragment& outer_text = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
outer_text.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 0, 60, 10), outer_text.VisualRect());
- const NGPaintFragment& inline_box1 = *line1.Children()[1];
+ const NGPaintFragment& inline_box1 = *ToList(line1.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentBox,
inline_box1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 10, 30, 10), inline_box1.VisualRect());
EXPECT_EQ(1u, inline_box1.Children().size());
- const NGPaintFragment& inner_text1 = *inline_box1.Children()[0];
+ const NGPaintFragment& inner_text1 = *inline_box1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 10, 30, 10), inner_text1.VisualRect());
- const NGPaintFragment& line2 = *container->Children()[1];
+ const NGPaintFragment& line2 = *ToList(container->Children())[1];
EXPECT_EQ(1u, line2.Children().size());
- const NGPaintFragment& inline_box2 = *line2.Children()[0];
+ const NGPaintFragment& inline_box2 = *line2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentBox,
inline_box2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 20, 30, 10), inline_box2.VisualRect());
- const NGPaintFragment& inner_text2 = *inline_box2.Children()[0];
+ const NGPaintFragment& inner_text2 = *inline_box2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 20, 30, 10), inner_text2.VisualRect());
@@ -373,33 +380,33 @@ TEST_F(NGPaintFragmentTest, RelativeBlockAndInline) {
)HTML");
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_EQ(2u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(2u, line1.Children().size());
- const NGPaintFragment& outer_text = *line1.Children()[0];
+ const NGPaintFragment& outer_text = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
outer_text.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 10, 60, 10), outer_text.VisualRect());
- const NGPaintFragment& inline_box1 = *line1.Children()[1];
+ const NGPaintFragment& inline_box1 = *ToList(line1.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentBox,
inline_box1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 20, 30, 10), inline_box1.VisualRect());
EXPECT_EQ(1u, inline_box1.Children().size());
- const NGPaintFragment& inner_text1 = *inline_box1.Children()[0];
+ const NGPaintFragment& inner_text1 = *inline_box1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(60, 20, 30, 10), inner_text1.VisualRect());
- const NGPaintFragment& line2 = *container->Children()[1];
+ const NGPaintFragment& line2 = *ToList(container->Children())[1];
EXPECT_EQ(1u, line2.Children().size());
- const NGPaintFragment& inline_box2 = *line2.Children()[0];
+ const NGPaintFragment& inline_box2 = *line2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentBox,
inline_box2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 30, 30, 10), inline_box2.VisualRect());
- const NGPaintFragment& inner_text2 = *inline_box2.Children()[0];
+ const NGPaintFragment& inner_text2 = *inline_box2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText,
inner_text2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(0, 30, 30, 10), inner_text2.VisualRect());
@@ -426,32 +433,32 @@ TEST_F(NGPaintFragmentTest, FlippedBlock) {
)HTML");
const NGPaintFragment* container = GetPaintFragmentByElementId("container");
EXPECT_EQ(2u, container->Children().size());
- const NGPaintFragment& line1 = *container->Children()[0];
+ const NGPaintFragment& line1 = *container->FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentLineBox,
line1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(190, 0, 10, 100), line1.VisualRect());
EXPECT_EQ(1u, line1.Children().size());
- const NGPaintFragment& text1 = *line1.Children()[0];
+ const NGPaintFragment& text1 = *line1.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText, text1.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(190, 0, 10, 100), text1.VisualRect());
- const NGPaintFragment& line2 = *container->Children()[1];
+ const NGPaintFragment& line2 = *ToList(container->Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentLineBox,
line2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(180, 0, 10, 70), line2.VisualRect());
EXPECT_EQ(2u, line2.Children().size());
- const NGPaintFragment& text2 = *line2.Children()[0];
+ const NGPaintFragment& text2 = *line2.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText, text2.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(180, 0, 10, 40), text2.VisualRect());
- const NGPaintFragment& box = *line2.Children()[1];
+ const NGPaintFragment& box = *ToList(line2.Children())[1];
EXPECT_EQ(NGPhysicalFragment::kFragmentBox, box.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(180, 40, 10, 30), box.VisualRect());
EXPECT_EQ(1u, box.Children().size());
- const NGPaintFragment& text3 = *box.Children()[0];
+ const NGPaintFragment& text3 = *box.FirstChild();
EXPECT_EQ(NGPhysicalFragment::kFragmentText, text3.PhysicalFragment().Type());
EXPECT_EQ(LayoutRect(180, 40, 10, 30), text3.VisualRect());
}
@@ -463,9 +470,9 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveBr) {
Element& target = *GetDocument().getElementById("target");
target.remove();
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- EXPECT_FALSE(container.Children()[0]->IsDirty());
- EXPECT_TRUE(container.Children()[1]->IsDirty());
- EXPECT_FALSE(container.Children()[2]->IsDirty());
+ EXPECT_FALSE(container.FirstChild()->IsDirty());
+ EXPECT_TRUE(ToList(container.Children())[1]->IsDirty());
+ EXPECT_FALSE(ToList(container.Children())[2]->IsDirty());
}
TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveChild) {
@@ -475,9 +482,9 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveChild) {
Element& target = *GetDocument().getElementById("target");
target.remove();
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- EXPECT_TRUE(container.Children()[0]->IsDirty());
- EXPECT_TRUE(container.Children()[1]->IsDirty());
- EXPECT_FALSE(container.Children()[2]->IsDirty());
+ EXPECT_TRUE(container.FirstChild()->IsDirty());
+ EXPECT_TRUE(ToList(container.Children())[1]->IsDirty());
+ EXPECT_FALSE(ToList(container.Children())[2]->IsDirty());
}
TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveSpanWithBr) {
@@ -488,21 +495,26 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveSpanWithBr) {
Element& target = *GetDocument().getElementById("target");
target.remove();
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- EXPECT_FALSE(container.Children()[0]->IsDirty());
- EXPECT_TRUE(container.Children()[1]->IsDirty());
- EXPECT_FALSE(container.Children()[2]->IsDirty());
+ EXPECT_FALSE(container.FirstChild()->IsDirty());
+ EXPECT_TRUE(ToList(container.Children())[1]->IsDirty());
+ EXPECT_FALSE(ToList(container.Children())[2]->IsDirty());
}
-TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByInsertAtStart) {
+// "ByInsert" tests are disabled, because they require |UpdateStyleAndLayout()|
+// to update |IsDirty|, but NGPaintFragment maybe re-used during the layout. In
+// such case, the result is not deterministic.
+TEST_F(NGPaintFragmentTest, DISABLED_MarkLineBoxesDirtyByInsertAtStart) {
SetBodyInnerHTML(
"<div id=container>line 1<br><b id=target>line 2</b><br>line 3<br>"
"</div>");
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- const scoped_refptr<const NGPaintFragment> line1 = container.Children()[0];
+ const scoped_refptr<const NGPaintFragment> line1 = container.FirstChild();
ASSERT_TRUE(line1->PhysicalFragment().IsLineBox()) << line1;
- const scoped_refptr<const NGPaintFragment> line2 = container.Children()[1];
+ const scoped_refptr<const NGPaintFragment> line2 =
+ ToList(container.Children())[1];
ASSERT_TRUE(line2->PhysicalFragment().IsLineBox()) << line2;
- const scoped_refptr<const NGPaintFragment> line3 = container.Children()[2];
+ const scoped_refptr<const NGPaintFragment> line3 =
+ ToList(container.Children())[2];
ASSERT_TRUE(line3->PhysicalFragment().IsLineBox()) << line3;
Element& target = *GetDocument().getElementById("target");
target.parentNode()->insertBefore(Text::Create(GetDocument(), "XYZ"),
@@ -514,16 +526,21 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByInsertAtStart) {
EXPECT_FALSE(line3->IsDirty());
}
-TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByInsertAtLast) {
+// "ByInsert" tests are disabled, because they require |UpdateStyleAndLayout()|
+// to update |IsDirty|, but NGPaintFragment maybe re-used during the layout. In
+// such case, the result is not deterministic.
+TEST_F(NGPaintFragmentTest, DISABLED_MarkLineBoxesDirtyByInsertAtLast) {
SetBodyInnerHTML(
"<div id=container>line 1<br><b id=target>line 2</b><br>line 3<br>"
"</div>");
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- const scoped_refptr<const NGPaintFragment> line1 = container.Children()[0];
+ const scoped_refptr<const NGPaintFragment> line1 = container.FirstChild();
ASSERT_TRUE(line1->PhysicalFragment().IsLineBox()) << line1;
- const scoped_refptr<const NGPaintFragment> line2 = container.Children()[1];
+ const scoped_refptr<const NGPaintFragment> line2 =
+ ToList(container.Children())[1];
ASSERT_TRUE(line2->PhysicalFragment().IsLineBox()) << line2;
- const scoped_refptr<const NGPaintFragment> line3 = container.Children()[2];
+ const scoped_refptr<const NGPaintFragment> line3 =
+ ToList(container.Children())[2];
ASSERT_TRUE(line3->PhysicalFragment().IsLineBox()) << line3;
Element& target = *GetDocument().getElementById("target");
target.parentNode()->appendChild(Text::Create(GetDocument(), "XYZ"));
@@ -534,16 +551,21 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByInsertAtLast) {
EXPECT_TRUE(line3->IsDirty());
}
-TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByInsertAtMiddle) {
+// "ByInsert" tests are disabled, because they require |UpdateStyleAndLayout()|
+// to update |IsDirty|, but NGPaintFragment maybe re-used during the layout. In
+// such case, the result is not deterministic.
+TEST_F(NGPaintFragmentTest, DISABLED_MarkLineBoxesDirtyByInsertAtMiddle) {
SetBodyInnerHTML(
"<div id=container>line 1<br><b id=target>line 2</b><br>line 3<br>"
"</div>");
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- const scoped_refptr<const NGPaintFragment> line1 = container.Children()[0];
+ const scoped_refptr<const NGPaintFragment> line1 = container.FirstChild();
ASSERT_TRUE(line1->PhysicalFragment().IsLineBox()) << line1;
- const scoped_refptr<const NGPaintFragment> line2 = container.Children()[1];
+ const scoped_refptr<const NGPaintFragment> line2 =
+ ToList(container.Children())[1];
ASSERT_TRUE(line2->PhysicalFragment().IsLineBox()) << line2;
- const scoped_refptr<const NGPaintFragment> line3 = container.Children()[2];
+ const scoped_refptr<const NGPaintFragment> line3 =
+ ToList(container.Children())[2];
ASSERT_TRUE(line3->PhysicalFragment().IsLineBox()) << line3;
Element& target = *GetDocument().getElementById("target");
target.parentNode()->insertBefore(Text::Create(GetDocument(), "XYZ"),
@@ -562,9 +584,52 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByTextSetData) {
Element& target = *GetDocument().getElementById("target");
ToText(*target.firstChild()).setData("abc");
const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
- EXPECT_FALSE(container.Children()[0]->IsDirty());
- EXPECT_TRUE(container.Children()[1]->IsDirty());
- EXPECT_FALSE(container.Children()[2]->IsDirty());
+ auto lines = ToList(container.Children());
+ // TODO(kojii): Currently we don't optimzie for <br>. We can do this, then
+ // lines[0] should not be dirty.
+ EXPECT_TRUE(lines[0]->IsDirty());
+}
+
+TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyWrappedLine) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #container {
+ font-size: 10px;
+ width: 10ch;
+ }
+ </style>
+ <div id=container>
+ 1234567
+ 123456<span id="target">7</span>
+ </div>)HTML");
+ Element& target = *GetDocument().getElementById("target");
+ target.remove();
+
+ const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
+ const NGPaintFragment& line0 = *container.FirstChild();
+ const NGPaintFragment& line1 = *line0.NextSibling();
+ EXPECT_FALSE(line0.IsDirty());
+ EXPECT_TRUE(line1.IsDirty());
+}
+
+TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyInsideInlineBlock) {
+ SetBodyInnerHTML(R"HTML(
+ <div id=container>
+ <div id="inline-block" style="display: inline-block">
+ <span id="target">DELETE ME</span>
+ </div>
+ </div>)HTML");
+ Element& target = *GetDocument().getElementById("target");
+ target.remove();
+
+ const NGPaintFragment& container = *GetPaintFragmentByElementId("container");
+ const NGPaintFragment& line0 = *container.FirstChild();
+ EXPECT_FALSE(line0.IsDirty());
+
+ const NGPaintFragment& inline_block =
+ *GetPaintFragmentByElementId("inline-block");
+ const NGPaintFragment& inner_line0 = *inline_block.FirstChild();
+ EXPECT_TRUE(inner_line0.IsDirty());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.cc
index 1aa3e390965..c7473b2fe3f 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.cc
@@ -23,13 +23,13 @@ void CollectPaintFragments(const NGPaintFragment& container,
NGPhysicalOffset offset_to_container_box,
Filter& filter,
Vector<NGPaintFragmentWithContainerOffset>* result) {
- for (const auto& child : container.Children()) {
+ for (NGPaintFragment* child : container.Children()) {
NGPaintFragmentWithContainerOffset fragment_with_offset{
- child.get(), child->Offset() + offset_to_container_box};
- if (filter.IsCollectible(child.get())) {
+ child, child->Offset() + offset_to_container_box};
+ if (filter.IsCollectible(child)) {
result->push_back(fragment_with_offset);
}
- if (filter.IsTraverse(child.get())) {
+ if (filter.IsTraverse(child)) {
CollectPaintFragments(*child, fragment_with_offset.container_offset,
filter, result);
}
@@ -143,22 +143,19 @@ NGPaintFragmentTraversalContext NextSiblingOf(
return {fragment.parent, fragment.index + 1};
}
-unsigned IndexOfChild(const NGPaintFragment& parent,
- const NGPaintFragment& fragment) {
- const auto& children = parent.Children();
- const auto* it = std::find_if(
- children.begin(), children.end(),
- [&fragment](const auto& child) { return &fragment == child.get(); });
- DCHECK(it != children.end());
- return static_cast<unsigned>(std::distance(children.begin(), it));
+unsigned IndexOf(const Vector<NGPaintFragment*, 16>& fragments,
+ const NGPaintFragment& fragment) {
+ auto* const* it = std::find_if(
+ fragments.begin(), fragments.end(),
+ [&fragment](const auto& child) { return &fragment == child; });
+ DCHECK(it != fragments.end());
+ return static_cast<unsigned>(std::distance(fragments.begin(), it));
}
} // namespace
NGPaintFragmentTraversal::NGPaintFragmentTraversal(const NGPaintFragment& root)
- : root_(root) {
- Push(root, 0);
-}
+ : current_(root.FirstChild()), root_(root) {}
NGPaintFragmentTraversal::NGPaintFragmentTraversal(const NGPaintFragment& root,
const NGPaintFragment& start)
@@ -166,34 +163,19 @@ NGPaintFragmentTraversal::NGPaintFragmentTraversal(const NGPaintFragment& root,
MoveTo(start);
}
-void NGPaintFragmentTraversal::Push(const NGPaintFragment& parent,
- unsigned index) {
- stack_.push_back(ParentAndIndex{&parent, index});
- current_ = parent.Children()[index].get();
-}
-
-void NGPaintFragmentTraversal::Push(const NGPaintFragment& fragment) {
- const NGPaintFragment* parent = fragment.Parent();
- DCHECK(parent);
- Push(*parent, IndexOfChild(*parent, fragment));
-}
-
void NGPaintFragmentTraversal::MoveTo(const NGPaintFragment& fragment) {
DCHECK(fragment.IsDescendantOfNotSelf(root_));
-
- // Because we may not traverse all descendants of |root_|, just push the
- // specified fragment. Computing its ancestors up to |root_| is deferred to
- // |MoveToNextSiblingOrAncestor()|.
- stack_.resize(0);
- Push(fragment);
+ current_ = &fragment;
}
void NGPaintFragmentTraversal::MoveToNext() {
if (IsAtEnd())
return;
- if (!current_->Children().IsEmpty()) {
- Push(*current_, 0);
+ if (const NGPaintFragment* first_child = current_->FirstChild()) {
+ current_ = first_child;
+ if (UNLIKELY(!siblings_.IsEmpty()))
+ siblings_.Shrink(0);
return;
}
@@ -203,11 +185,12 @@ void NGPaintFragmentTraversal::MoveToNext() {
void NGPaintFragmentTraversal::MoveToNextSiblingOrAncestor() {
while (!IsAtEnd()) {
// Check if we have a next sibling.
- auto& stack_top = stack_.back();
- if (++stack_top.index < stack_top.parent->Children().size()) {
- current_ = stack_top.parent->Children()[stack_top.index].get();
+ if (const NGPaintFragment* next = current_->NextSibling()) {
+ current_ = next;
+ ++current_index_;
return;
}
+
MoveToParent();
}
}
@@ -215,39 +198,36 @@ void NGPaintFragmentTraversal::MoveToNextSiblingOrAncestor() {
void NGPaintFragmentTraversal::MoveToParent() {
if (IsAtEnd())
return;
- DCHECK(!stack_.IsEmpty());
- const NGPaintFragment& parent = *stack_.back().parent;
- stack_.pop_back();
- if (&parent == &root_) {
- DCHECK(stack_.IsEmpty());
+
+ current_ = current_->Parent();
+ if (current_ == &root_)
current_ = nullptr;
- return;
- }
- if (stack_.IsEmpty()) {
- // We might have started with |MoveTo()|, and thus computing parent stack
- // was deferred.
- Push(parent);
- return;
- }
- DCHECK_EQ(&parent,
- stack_.back().parent->Children()[stack_.back().index].get());
- current_ = &parent;
+ if (UNLIKELY(!siblings_.IsEmpty()))
+ siblings_.Shrink(0);
}
void NGPaintFragmentTraversal::MoveToPrevious() {
if (IsAtEnd())
return;
- DCHECK(!stack_.IsEmpty());
- auto& stack_top = stack_.back();
- if (stack_top.index == 0) {
+
+ if (siblings_.IsEmpty()) {
+ current_->Parent()->Children().ToList(&siblings_);
+ current_index_ = IndexOf(siblings_, *current_);
+ }
+
+ if (!current_index_) {
// There is no previous sibling of |current_|. We move to parent.
MoveToParent();
return;
}
- --stack_top.index;
- current_ = stack_top.parent->Children()[stack_top.index].get();
- while (!current_->Children().IsEmpty())
- Push(*current_, current_->Children().size() - 1);
+
+ current_ = siblings_[--current_index_];
+ while (current_->FirstChild()) {
+ current_->Children().ToList(&siblings_);
+ DCHECK(!siblings_.IsEmpty());
+ current_index_ = siblings_.size() - 1;
+ current_ = siblings_[current_index_];
+ }
}
NGPaintFragmentTraversal::AncestorRange
@@ -287,11 +267,11 @@ NGPaintFragment* NGPaintFragmentTraversal::PreviousLineOf(
NGPaintFragment* parent = line.Parent();
DCHECK(parent);
NGPaintFragment* previous_line = nullptr;
- for (const auto& sibling : parent->Children()) {
- if (sibling.get() == &line)
+ for (NGPaintFragment* sibling : parent->Children()) {
+ if (sibling == &line)
return previous_line;
if (sibling->PhysicalFragment().IsLineBox())
- previous_line = sibling.get();
+ previous_line = sibling;
}
NOTREACHED();
return nullptr;
@@ -300,15 +280,32 @@ NGPaintFragment* NGPaintFragmentTraversal::PreviousLineOf(
const NGPaintFragment* NGPaintFragmentTraversalContext::GetFragment() const {
if (!parent)
return nullptr;
- return parent->Children()[index].get();
+ return siblings[index];
+}
+
+NGPaintFragmentTraversalContext::NGPaintFragmentTraversalContext(
+ const NGPaintFragment* fragment) {
+ if (fragment) {
+ parent = fragment->Parent();
+ parent->Children().ToList(&siblings);
+ index = IndexOf(siblings, *fragment);
+ }
+}
+
+NGPaintFragmentTraversalContext::NGPaintFragmentTraversalContext(
+ const NGPaintFragment* parent,
+ unsigned index)
+ : parent(parent), index(index) {
+ DCHECK(parent);
+ parent->Children().ToList(&siblings);
+ DCHECK(index < siblings.size());
}
// static
NGPaintFragmentTraversalContext NGPaintFragmentTraversalContext::Create(
const NGPaintFragment* fragment) {
- if (!fragment)
- return NGPaintFragmentTraversalContext();
- return {fragment->Parent(), IndexOfChild(*fragment->Parent(), *fragment)};
+ return fragment ? NGPaintFragmentTraversalContext(fragment)
+ : NGPaintFragmentTraversalContext();
}
NGPaintFragmentTraversalContext NGPaintFragmentTraversal::PreviousInlineLeafOf(
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h
index 5a79444e1dd..377e5466038 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h
@@ -28,6 +28,12 @@ struct CORE_EXPORT NGPaintFragmentTraversalContext {
STACK_ALLOCATED();
public:
+ NGPaintFragmentTraversalContext() = default;
+ explicit NGPaintFragmentTraversalContext(const NGPaintFragment* fragment);
+ NGPaintFragmentTraversalContext(const NGPaintFragment* parent,
+ unsigned index);
+ // TODO(kojii): deprecated, prefer constructors to avoid unexpected
+ // instantiation.
static NGPaintFragmentTraversalContext Create(const NGPaintFragment*);
bool IsNull() const { return !parent; }
@@ -39,6 +45,7 @@ struct CORE_EXPORT NGPaintFragmentTraversalContext {
const NGPaintFragment* parent = nullptr;
unsigned index = 0;
+ Vector<NGPaintFragment*, 16> siblings;
};
// Utility class for traversing the paint fragment tree.
@@ -170,9 +177,6 @@ class CORE_EXPORT NGPaintFragmentTraversal {
const NGPaintFragmentTraversalContext&);
private:
- void Push(const NGPaintFragment& parent, unsigned index);
- void Push(const NGPaintFragment& fragment);
-
// |current_| holds a |NGPaintFragment| specified by |index|th child of
// |parent| of the last element of |stack_|.
const NGPaintFragment* current_ = nullptr;
@@ -181,18 +185,12 @@ class CORE_EXPORT NGPaintFragmentTraversal {
// from traversal. |current_| can't |root_|.
const NGPaintFragment& root_;
- // The stack of parent and its child index up to the root. Each stack entry
- // represents the current node, and thus
- // |stack_.back().parent->Children()[stack_.back().index] == current_|.
- //
- // Computing ancestors maybe deferred until |MoveToNextSiblingOrAncestor()|
- // when |Moveto()| is used. In that case, the |stack_| does not contain all
- // fragments to the |root_|.
- struct ParentAndIndex {
- const NGPaintFragment* parent;
- unsigned index;
- };
- Vector<ParentAndIndex, 4> stack_;
+ // Keep a list of siblings for MoveToPrevious().
+ // TODO(kojii): We could keep a stack of this to avoid repetitive
+ // constructions of the list when we move up/down levels. Also can consider
+ // sharing with NGPaintFragmentTraversalContext.
+ unsigned current_index_ = 0;
+ Vector<NGPaintFragment*, 16> siblings_;
DISALLOW_COPY_AND_ASSIGN(NGPaintFragmentTraversal);
};
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc
index e9a7f1b5242..79670ae17e1 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc
@@ -27,7 +27,7 @@ class NGPaintFragmentTraversalTest : public RenderingTest,
root_fragment_ = layout_block_flow_->PaintFragment();
}
- const Vector<scoped_refptr<NGPaintFragment>>& RootChildren() const {
+ const NGPaintFragment::ChildList RootChildren() const {
return root_fragment_->Children();
}
@@ -51,6 +51,13 @@ class NGPaintFragmentTraversalTest : public RenderingTest,
return results;
}
+ Vector<NGPaintFragment*, 16> ToList(
+ const NGPaintFragment::ChildList& children) {
+ Vector<NGPaintFragment*, 16> list;
+ children.ToList(&list);
+ return list;
+ }
+
LayoutBlockFlow* layout_block_flow_;
NGPaintFragment* root_fragment_;
};
@@ -65,14 +72,14 @@ TEST_F(NGPaintFragmentTraversalTest, MoveToNext) {
</div>
)HTML");
NGPaintFragmentTraversal traversal(*root_fragment_);
- NGPaintFragment* line0 = root_fragment_->Children()[0].get();
- NGPaintFragment* line1 = root_fragment_->Children()[1].get();
- NGPaintFragment* span = line0->Children()[1].get();
- NGPaintFragment* br = line0->Children()[2].get();
- EXPECT_THAT(ToDepthFirstList(&traversal),
- ElementsAreArray({line0, line0->Children()[0].get(), span,
- span->Children()[0].get(), br, line1,
- line1->Children()[0].get()}));
+ NGPaintFragment* line0 = root_fragment_->FirstChild();
+ NGPaintFragment* line1 = ToList(root_fragment_->Children())[1];
+ NGPaintFragment* span = ToList(line0->Children())[1];
+ NGPaintFragment* br = ToList(line0->Children())[2];
+ EXPECT_THAT(
+ ToDepthFirstList(&traversal),
+ ElementsAreArray({line0, line0->FirstChild(), span, span->FirstChild(),
+ br, line1, line1->FirstChild()}));
}
TEST_F(NGPaintFragmentTraversalTest, MoveToNextWithRoot) {
@@ -84,13 +91,13 @@ TEST_F(NGPaintFragmentTraversalTest, MoveToNextWithRoot) {
line1
</div>
)HTML");
- NGPaintFragment* line0 = root_fragment_->Children()[0].get();
- NGPaintFragment* span = line0->Children()[1].get();
- NGPaintFragment* br = line0->Children()[2].get();
+ NGPaintFragment* line0 = root_fragment_->FirstChild();
+ NGPaintFragment* span = ToList(line0->Children())[1];
+ NGPaintFragment* br = ToList(line0->Children())[2];
NGPaintFragmentTraversal traversal(*line0);
- EXPECT_THAT(ToDepthFirstList(&traversal),
- ElementsAreArray({line0->Children()[0].get(), span,
- span->Children()[0].get(), br}));
+ EXPECT_THAT(
+ ToDepthFirstList(&traversal),
+ ElementsAreArray({line0->FirstChild(), span, span->FirstChild(), br}));
}
TEST_F(NGPaintFragmentTraversalTest, MoveToPrevious) {
@@ -103,15 +110,15 @@ TEST_F(NGPaintFragmentTraversalTest, MoveToPrevious) {
</div>
)HTML");
NGPaintFragmentTraversal traversal(*root_fragment_);
- NGPaintFragment* line0 = root_fragment_->Children()[0].get();
- NGPaintFragment* line1 = root_fragment_->Children()[1].get();
- NGPaintFragment* span = line0->Children()[1].get();
- NGPaintFragment* br = line0->Children()[2].get();
- traversal.MoveTo(*line1->Children()[0].get());
- EXPECT_THAT(ToReverseDepthFirstList(&traversal),
- ElementsAreArray({line1->Children()[0].get(), line1, br,
- span->Children()[0].get(), span,
- line0->Children()[0].get(), line0}));
+ NGPaintFragment* line0 = root_fragment_->FirstChild();
+ NGPaintFragment* line1 = ToList(root_fragment_->Children())[1];
+ NGPaintFragment* span = ToList(line0->Children())[1];
+ NGPaintFragment* br = ToList(line0->Children())[2];
+ traversal.MoveTo(*line1->FirstChild());
+ EXPECT_THAT(
+ ToReverseDepthFirstList(&traversal),
+ ElementsAreArray({line1->FirstChild(), line1, br, span->FirstChild(),
+ span, line0->FirstChild(), line0}));
}
TEST_F(NGPaintFragmentTraversalTest, MoveToPreviousWithRoot) {
@@ -123,14 +130,14 @@ TEST_F(NGPaintFragmentTraversalTest, MoveToPreviousWithRoot) {
line1
</div>
)HTML");
- NGPaintFragment* line0 = root_fragment_->Children()[0].get();
- NGPaintFragment* span = line0->Children()[1].get();
- NGPaintFragment* br = line0->Children()[2].get();
+ NGPaintFragment* line0 = root_fragment_->FirstChild();
+ NGPaintFragment* span = ToList(line0->Children())[1];
+ NGPaintFragment* br = ToList(line0->Children())[2];
NGPaintFragmentTraversal traversal(*line0);
traversal.MoveTo(*br);
- EXPECT_THAT(ToReverseDepthFirstList(&traversal),
- ElementsAreArray({br, span->Children()[0].get(), span,
- line0->Children()[0].get()}));
+ EXPECT_THAT(
+ ToReverseDepthFirstList(&traversal),
+ ElementsAreArray({br, span->FirstChild(), span, line0->FirstChild()}));
}
TEST_F(NGPaintFragmentTraversalTest, MoveTo) {
@@ -143,15 +150,15 @@ TEST_F(NGPaintFragmentTraversalTest, MoveTo) {
</div>
)HTML");
NGPaintFragmentTraversal traversal(*root_fragment_);
- NGPaintFragment* line0 = root_fragment_->Children()[0].get();
- NGPaintFragment* line1 = root_fragment_->Children()[1].get();
- NGPaintFragment* span = line0->Children()[1].get();
- NGPaintFragment* br = line0->Children()[2].get();
+ NGPaintFragment* line0 = root_fragment_->FirstChild();
+ NGPaintFragment* line1 = ToList(root_fragment_->Children())[1];
+ NGPaintFragment* span = ToList(line0->Children())[1];
+ NGPaintFragment* br = ToList(line0->Children())[2];
traversal.MoveTo(*span);
EXPECT_EQ(span, &*traversal);
EXPECT_THAT(ToDepthFirstList(&traversal),
- ElementsAreArray({span, span->Children()[0].get(), br, line1,
- line1->Children()[0].get()}));
+ ElementsAreArray(
+ {span, span->FirstChild(), br, line1, line1->FirstChild()}));
}
TEST_F(NGPaintFragmentTraversalTest, MoveToWithRoot) {
@@ -163,31 +170,31 @@ TEST_F(NGPaintFragmentTraversalTest, MoveToWithRoot) {
line1
</div>
)HTML");
- NGPaintFragment* line0 = root_fragment_->Children()[0].get();
- NGPaintFragment* span = line0->Children()[1].get();
- NGPaintFragment* br = line0->Children()[2].get();
+ NGPaintFragment* line0 = root_fragment_->FirstChild();
+ NGPaintFragment* span = ToList(line0->Children())[1];
+ NGPaintFragment* br = ToList(line0->Children())[2];
NGPaintFragmentTraversal traversal(*line0);
traversal.MoveTo(*span);
EXPECT_EQ(span, &*traversal);
EXPECT_THAT(ToDepthFirstList(&traversal),
- ElementsAreArray({span, span->Children()[0].get(), br}));
+ ElementsAreArray({span, span->FirstChild(), br}));
}
TEST_F(NGPaintFragmentTraversalTest, PreviousLineOf) {
SetUpHtml("t", "<div id=t>foo<br>bar</div>");
ASSERT_EQ(2u, RootChildren().size());
- EXPECT_EQ(nullptr,
- NGPaintFragmentTraversal::PreviousLineOf(*RootChildren()[0]));
- EXPECT_EQ(RootChildren()[0].get(),
- NGPaintFragmentTraversal::PreviousLineOf(*RootChildren()[1]));
+ EXPECT_EQ(nullptr, NGPaintFragmentTraversal::PreviousLineOf(
+ *ToList(RootChildren())[0]));
+ EXPECT_EQ(ToList(RootChildren())[0], NGPaintFragmentTraversal::PreviousLineOf(
+ *ToList(RootChildren())[1]));
}
TEST_F(NGPaintFragmentTraversalTest, PreviousLineInListItem) {
SetUpHtml("t", "<ul><li id=t>foo</li></ul>");
ASSERT_EQ(2u, RootChildren().size());
- ASSERT_TRUE(RootChildren()[0]->PhysicalFragment().IsListMarker());
- EXPECT_EQ(nullptr,
- NGPaintFragmentTraversal::PreviousLineOf(*RootChildren()[1]));
+ ASSERT_TRUE(ToList(RootChildren())[0]->PhysicalFragment().IsListMarker());
+ EXPECT_EQ(nullptr, NGPaintFragmentTraversal::PreviousLineOf(
+ *ToList(RootChildren())[1]));
}
TEST_F(NGPaintFragmentTraversalTest, InlineDescendantsOf) {
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter_test.cc
index ccc822a59a5..8bbcb7b0c2b 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter_test.cc
@@ -19,6 +19,8 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+using testing::ElementsAre;
+
namespace blink {
class NGTextFragmentPainterTest : public PaintControllerPaintTest,
@@ -50,14 +52,14 @@ TEST_P(NGTextFragmentPainterTest, TestTextStyle) {
const NGPaintFragment& root_fragment = *block_flow.PaintFragment();
EXPECT_EQ(1u, root_fragment.Children().size());
- const NGPaintFragment& line_box_fragment = *root_fragment.Children()[0];
+ const NGPaintFragment& line_box_fragment = *root_fragment.FirstChild();
EXPECT_EQ(1u, line_box_fragment.Children().size());
- const NGPaintFragment& text_fragment = *line_box_fragment.Children()[0];
+ const NGPaintFragment& text_fragment = *line_box_fragment.FirstChild();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(text_fragment, kForegroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&text_fragment, kForegroundType)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc
index 86837c55665..d0588ee72f2 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/paint/ng/ng_text_painter.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
diff --git a/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid.cc b/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid.cc
index 3cf8407a9bf..5544a45b57c 100644
--- a/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid.cc
+++ b/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/nine_piece_image.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid_test.cc b/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid_test.cc
index ca9f272a56a..f4bc6c67e3b 100644
--- a/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/nine_piece_image_grid_test.cc
@@ -23,9 +23,6 @@ class NinePieceImageGridTest : public RenderingTest {
nullptr, nullptr, nullptr, nullptr, nullptr, cssvalue::kRepeating);
return StyleGeneratedImage::Create(*gradient);
}
-
- private:
- void SetUp() override { RenderingTest::SetUp(); }
};
TEST_F(NinePieceImageGridTest, NinePieceImagePainting_NoDrawables) {
diff --git a/chromium/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc b/chromium/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc
index aa56f62ea47..5c32e136170 100644
--- a/chromium/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/nine_piece_image_painter.cc
@@ -100,9 +100,9 @@ bool NinePieceImagePainter::Paint(GraphicsContext& graphics_context,
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage",
"data",
- InspectorPaintImageEvent::Data(node, *style_image,
- FloatRect(image->Rect()),
- FloatRect(border_image_rect)));
+ inspector_paint_image_event::Data(node, *style_image,
+ FloatRect(image->Rect()),
+ FloatRect(border_image_rect)));
ScopedInterpolationQuality interpolation_quality_scope(
graphics_context, style.GetInterpolationQuality());
diff --git a/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.cc b/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.cc
index 8592193d999..806caccaa65 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.cc
+++ b/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.cc
@@ -199,7 +199,7 @@ void ObjectPaintInvalidator::InvalidateDisplayItemClient(
TRACE_EVENT_INSTANT1(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"PaintInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data",
- InspectorPaintInvalidationTrackingEvent::Data(object_));
+ inspector_paint_invalidation_tracking_event::Data(object_));
}
client.Invalidate(reason);
@@ -336,7 +336,10 @@ PaintInvalidationReason ObjectPaintInvalidatorWithContext::InvalidateSelection(
if (full_invalidation)
return reason;
-
+ // We should invalidate LayoutSVGText always.
+ // See layout_selection.cc SetShouldInvalidateIfNeeded for more detail.
+ if (object_.IsSVGText())
+ return PaintInvalidationReason::kSelection;
const LayoutRect invalidation_rect =
UnionRect(new_selection_rect, old_selection_rect);
if (invalidation_rect.IsEmpty())
diff --git a/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc b/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc
index 88c8cfd8d3e..f538faee254 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc
@@ -116,7 +116,7 @@ TEST_F(ObjectPaintInvalidatorTest, TraverseFloatUnderCompositedInline) {
EXPECT_TRUE(composited_container_layer->NeedsRepaint());
EXPECT_FALSE(span_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Traversing from span should mark needsRepaint on correct layers for target.
EXPECT_FALSE(containing_block_layer->NeedsRepaint());
@@ -128,7 +128,7 @@ TEST_F(ObjectPaintInvalidatorTest, TraverseFloatUnderCompositedInline) {
EXPECT_TRUE(composited_container_layer->NeedsRepaint());
EXPECT_TRUE(span_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Traversing from compositedContainer should reach target.
GetDocument().View()->SetTracksPaintInvalidations(true);
@@ -286,7 +286,7 @@ TEST_F(ObjectPaintInvalidatorTest, InvalidatePaintRectangle) {
EXPECT_EQ(LayoutRect(18, 18, 80, 100),
target->PartialInvalidationVisualRect());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(), target->PartialInvalidationLocalRect());
EXPECT_EQ(LayoutRect(), target->PartialInvalidationVisualRect());
@@ -319,7 +319,7 @@ TEST_F(ObjectPaintInvalidatorTest, Selection) {
// Add selection.
GetDocument().View()->SetTracksPaintInvalidations(true);
GetDocument().GetFrame()->Selection().SelectAll();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* graphics_layer = GetLayoutView().Layer()->GraphicsLayerBacking();
const auto* invalidations =
&graphics_layer->GetRasterInvalidationTracking()->Invalidations();
@@ -332,7 +332,7 @@ TEST_F(ObjectPaintInvalidatorTest, Selection) {
// Simulate a change without full invalidation or selection change.
GetDocument().View()->SetTracksPaintInvalidations(true);
target->SetShouldCheckForPaintInvalidation();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(graphics_layer->GetRasterInvalidationTracking()
->Invalidations()
.IsEmpty());
@@ -342,7 +342,7 @@ TEST_F(ObjectPaintInvalidatorTest, Selection) {
// Remove selection.
GetDocument().View()->SetTracksPaintInvalidations(true);
GetDocument().GetFrame()->Selection().Clear();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
invalidations =
&graphics_layer->GetRasterInvalidationTracking()->Invalidations();
ASSERT_EQ(1u, invalidations->size());
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc
index d444cab326f..96048abd457 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc
@@ -6,6 +6,7 @@
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
+#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
namespace blink {
@@ -25,26 +26,34 @@ void SetUpHTML(PaintAndRasterInvalidationTest& test) {
height: 100px;
transform-origin: 0 0;
}
- .background {
+ .solid {
background: blue;
}
+ .gradient {
+ background-image: linear-gradient(blue, yellow);
+ }
+ .scroll {
+ overflow: scroll;
+ }
.solid-composited-scroller {
overflow: scroll;
will-change: transform;
background: blue;
}
- .local-background {
+ .local-attachment {
background-attachment: local;
- overflow: scroll;
- }
- .gradient {
- background-image: linear-gradient(blue, yellow);
}
.transform {
transform: scale(2);
}
+ .border {
+ border: 10px solid black;
+ }
+ .composited {
+ will-change: transform;
+ }
</style>
- <div id='target' class='background'></div>
+ <div id='target' class='solid'></div>
)HTML");
}
@@ -56,37 +65,50 @@ TEST_P(PaintAndRasterInvalidationTest, TrackingForTracing) {
<div id="target"></div>
)HTML");
auto* target = GetDocument().getElementById("target");
+ auto get_debug_info = [&]() -> std::string {
+ auto* cc_layer =
+ RuntimeEnabledFeatures::SlimmingPaintV2Enabled()
+ ? GetDocument()
+ .View()
+ ->GetPaintArtifactCompositorForTesting()
+ ->RootLayer()
+ ->children()[0]
+ .get()
+ : GetLayoutView().Layer()->GraphicsLayerBacking()->CcLayer();
+ return cc_layer->GetLayerClientForTesting()
+ ->TakeDebugInfo(cc_layer)
+ ->ToString();
+ };
{
// This is equivalent to enabling disabled-by-default-blink.invalidation
// for tracing.
ScopedPaintUnderInvalidationCheckingForTest checking(true);
- target->setAttribute(HTMLNames::styleAttr, "height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_THAT(GetCcLayerClient()->TakeDebugInfo(GetCcLayer())->ToString(),
- MatchesRegex(
- "\\{\"layer_name\":.*\"annotated_invalidation_rects\":\\["
- "\\{\"geometry_rect\":\\[8,108,100,100\\],"
- "\"reason\":\"incremental\","
- "\"client\":\"LayoutBlockFlow DIV id='target'\"\\}\\]\\}"));
-
- target->setAttribute(HTMLNames::styleAttr, "height: 200px; width: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_THAT(GetCcLayerClient()->TakeDebugInfo(GetCcLayer())->ToString(),
- MatchesRegex(
- "\\{\"layer_name\":.*\"annotated_invalidation_rects\":\\["
- "\\{\"geometry_rect\":\\[108,8,100,200\\],"
- "\"reason\":\"incremental\","
- "\"client\":\"LayoutBlockFlow DIV id='target'\"\\}\\]\\}"));
+ target->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(
+ get_debug_info(),
+ MatchesRegex(
+ "\\{\"layer_name\":.*\"annotated_invalidation_rects\":\\["
+ "\\{\"geometry_rect\":\\[8,108,100,100\\],"
+ "\"reason\":\"incremental\","
+ "\"client\":\"LayoutN?G?BlockFlow DIV id='target'\"\\}\\]\\}"));
+
+ target->setAttribute(html_names::kStyleAttr, "height: 200px; width: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_THAT(
+ get_debug_info(),
+ MatchesRegex(
+ "\\{\"layer_name\":.*\"annotated_invalidation_rects\":\\["
+ "\\{\"geometry_rect\":\\[108,8,100,200\\],"
+ "\"reason\":\"incremental\","
+ "\"client\":\"LayoutN?G?BlockFlow DIV id='target'\"\\}\\]\\}"));
}
- target->setAttribute(HTMLNames::styleAttr, "height: 300px; width: 300px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_EQ(std::string::npos, GetCcLayerClient()
- ->TakeDebugInfo(GetCcLayer())
- ->ToString()
- .find("invalidation_rects"));
+ target->setAttribute(html_names::kStyleAttr, "height: 300px; width: 300px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(std::string::npos, get_debug_info().find("invalidation_rects"));
}
TEST_P(PaintAndRasterInvalidationTest, IncrementalInvalidationExpand) {
@@ -95,8 +117,8 @@ TEST_P(PaintAndRasterInvalidationTest, IncrementalInvalidationExpand) {
auto* object = target->GetLayoutObject();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 100px; height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 100px; height: 200px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -114,8 +136,8 @@ TEST_P(PaintAndRasterInvalidationTest, IncrementalInvalidationShrink) {
auto* object = target->GetLayoutObject();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 20px; height: 80px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 20px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -133,8 +155,8 @@ TEST_P(PaintAndRasterInvalidationTest, IncrementalInvalidationMixed) {
auto* object = target->GetLayoutObject();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 100px; height: 80px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 100px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -152,8 +174,9 @@ TEST_P(PaintAndRasterInvalidationTest, SubpixelVisualRectChagne) {
auto* object = target->GetLayoutObject();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 100.6px; height: 70.3px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr,
+ "width: 100.6px; height: 70.3px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -165,8 +188,8 @@ TEST_P(PaintAndRasterInvalidationTest, SubpixelVisualRectChagne) {
GetDocument().View()->SetTracksPaintInvalidations(false);
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 50px; height: 100px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 50px; height: 100px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -182,12 +205,13 @@ TEST_P(PaintAndRasterInvalidationTest, SubpixelVisualRectChangeWithTransform) {
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
auto* object = target->GetLayoutObject();
- target->setAttribute(HTMLNames::classAttr, "background transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kClassAttr, "solid transform");
+ UpdateAllLifecyclePhasesForTest();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 100.6px; height: 70.3px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr,
+ "width: 100.6px; height: 70.3px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -199,8 +223,8 @@ TEST_P(PaintAndRasterInvalidationTest, SubpixelVisualRectChangeWithTransform) {
GetDocument().View()->SetTracksPaintInvalidations(false);
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 50px; height: 100px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 50px; height: 100px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{object, object->DebugName(),
@@ -219,9 +243,9 @@ TEST_P(PaintAndRasterInvalidationTest, SubpixelWithinPixelsChange) {
EXPECT_EQ(LayoutRect(0, 0, 50, 100), object->FirstFragment().VisualRect());
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"margin-top: 0.6px; width: 50px; height: 99.3px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(0, 0, 50, 100), object->FirstFragment().VisualRect());
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
@@ -230,9 +254,9 @@ TEST_P(PaintAndRasterInvalidationTest, SubpixelWithinPixelsChange) {
GetDocument().View()->SetTracksPaintInvalidations(false);
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"margin-top: 0.6px; width: 49.3px; height: 98.5px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(0, 0, 50, 100), object->FirstFragment().VisualRect());
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
@@ -245,13 +269,13 @@ TEST_P(PaintAndRasterInvalidationTest, ResizeRotated) {
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
auto* object = target->GetLayoutObject();
- target->setAttribute(HTMLNames::styleAttr, "transform: rotate(45deg)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "transform: rotate(45deg)");
+ UpdateAllLifecyclePhasesForTest();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"transform: rotate(45deg); width: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto expected_rect = EnclosingIntRect(
TransformationMatrix().Rotate(45).MapRect(FloatRect(50, 0, 150, 100)));
expected_rect.Intersect(IntRect(0, 0, 800, 600));
@@ -265,19 +289,19 @@ TEST_P(PaintAndRasterInvalidationTest, ResizeRotated) {
TEST_P(PaintAndRasterInvalidationTest, ResizeRotatedChild) {
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"transform: rotate(45deg); width: 200px");
target->SetInnerHTMLFromString(
"<div id=child style='width: 50px; height: 50px; background: "
"red'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* child = GetDocument().getElementById("child");
auto* child_object = child->GetLayoutObject();
GetDocument().View()->SetTracksPaintInvalidations(true);
- child->setAttribute(HTMLNames::styleAttr,
+ child->setAttribute(html_names::kStyleAttr,
"width: 100px; height: 50px; background: red");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto expected_rect = EnclosingIntRect(
TransformationMatrix().Rotate(45).MapRect(FloatRect(50, 0, 50, 50)));
expected_rect.Intersect(IntRect(0, 0, 800, 600));
@@ -289,66 +313,71 @@ TEST_P(PaintAndRasterInvalidationTest, ResizeRotatedChild) {
}
TEST_P(PaintAndRasterInvalidationTest, CompositedLayoutViewResize) {
- // TODO(crbug.com/732611): Fix SPv2 for scrolling contents layer.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::classAttr, "");
- target->setAttribute(HTMLNames::styleAttr, "height: 2000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kClassAttr, "");
+ target->setAttribute(html_names::kStyleAttr, "height: 2000px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ GetLayoutView().GetBackgroundPaintLocation());
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ const auto* mapping = GetLayoutView().Layer()->GetCompositedLayerMapping();
+ EXPECT_TRUE(mapping->BackgroundPaintsOntoScrollingContentsLayer());
+ EXPECT_FALSE(mapping->BackgroundPaintsOntoGraphicsLayer());
+ }
// Resize the content.
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "height: 3000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "height: 3000px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(
GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
- ViewScrollingContentsDisplayItemClient(),
- ViewScrollingContentsDisplayItemClient()->DebugName(),
+ &ViewScrollingBackgroundClient(),
+ ViewScrollingBackgroundClient().DebugName(),
IntRect(0, 2000, 800, 1000), PaintInvalidationReason::kIncremental}));
GetDocument().View()->SetTracksPaintInvalidations(false);
- // Resize the viewport. No paint invalidation.
+ // Resize the viewport. No invalidation.
GetDocument().View()->SetTracksPaintInvalidations(true);
GetDocument().View()->Resize(800, 1000);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
GetDocument().View()->SetTracksPaintInvalidations(false);
}
TEST_P(PaintAndRasterInvalidationTest, CompositedLayoutViewGradientResize) {
- // TODO(crbug.com/732611): Fix SPv2 for scrolling contents layer.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetUpHTML(*this);
- GetDocument().body()->setAttribute(HTMLNames::classAttr, "gradient");
+ GetDocument().body()->setAttribute(html_names::kClassAttr, "gradient");
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::classAttr, "");
- target->setAttribute(HTMLNames::styleAttr, "height: 2000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kClassAttr, "");
+ target->setAttribute(html_names::kStyleAttr, "height: 2000px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ GetLayoutView().GetBackgroundPaintLocation());
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ const auto* mapping = GetLayoutView().Layer()->GetCompositedLayerMapping();
+ EXPECT_TRUE(mapping->BackgroundPaintsOntoScrollingContentsLayer());
+ EXPECT_FALSE(mapping->BackgroundPaintsOntoGraphicsLayer());
+ }
// Resize the content.
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "height: 3000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "height: 3000px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(
GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
- ViewScrollingContentsDisplayItemClient(),
- ViewScrollingContentsDisplayItemClient()->DebugName(),
- IntRect(0, 0, 800, 3000),
- PaintInvalidationReason::kBackgroundOnScrollingContentsLayer}));
+ &ViewScrollingBackgroundClient(),
+ ViewScrollingBackgroundClient().DebugName(), IntRect(0, 0, 800, 3000),
+ PaintInvalidationReason::kBackground}));
GetDocument().View()->SetTracksPaintInvalidations(false);
- // Resize the viewport. No paint invalidation.
+ // Resize the viewport. No invalidation.
GetDocument().View()->SetTracksPaintInvalidations(true);
GetDocument().View()->Resize(800, 1000);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
GetDocument().View()->SetTracksPaintInvalidations(false);
}
@@ -368,32 +397,43 @@ TEST_P(PaintAndRasterInvalidationTest, NonCompositedLayoutViewResize) {
</style>
<div id='content' style='width: 200px; height: 200px'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* iframe = GetDocument().getElementById("iframe");
Element* content = ChildDocument().getElementById("content");
EXPECT_EQ(GetLayoutView(),
content->GetLayoutObject()->ContainerForPaintInvalidation());
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ content->GetLayoutObject()
+ ->View()
+ ->GetBackgroundPaintLocation());
// Resize the content.
GetDocument().View()->SetTracksPaintInvalidations(true);
- content->setAttribute(HTMLNames::styleAttr, "height: 500px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ content->setAttribute(html_names::kStyleAttr, "height: 500px");
+ UpdateAllLifecyclePhasesForTest();
// No invalidation because the changed part of layout overflow is clipped.
EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
GetDocument().View()->SetTracksPaintInvalidations(false);
// Resize the iframe.
GetDocument().View()->SetTracksPaintInvalidations(true);
- iframe->setAttribute(HTMLNames::styleAttr, "height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- // The iframe doesn't have anything visible by itself, so we only issue raster
- // invalidation for the frame contents.
- EXPECT_THAT(
- GetRasterInvalidationTracking()->Invalidations(),
- UnorderedElementsAre(RasterInvalidationInfo{
- content->GetLayoutObject()->View(),
- content->GetLayoutObject()->View()->DebugName(),
- IntRect(0, 100, 100, 100), PaintInvalidationReason::kIncremental}));
+ iframe->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // TODO(wangxianzhu): This is probably incorrect, but for now we assume
+ // any scrolling contents as composited during SPv2 painting. Perhaps we
+ // need some heuristic about composited scrolling during painting.
+ EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
+ } else {
+ // The iframe doesn't have anything visible by itself, so we only issue
+ // raster invalidation for the frame contents.
+ EXPECT_THAT(
+ GetRasterInvalidationTracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ content->GetLayoutObject()->View(),
+ content->GetLayoutObject()->View()->DebugName(),
+ IntRect(0, 100, 100, 100), PaintInvalidationReason::kIncremental}));
+ }
GetDocument().View()->SetTracksPaintInvalidations(false);
}
@@ -416,7 +456,7 @@ TEST_P(PaintAndRasterInvalidationTest, NonCompositedLayoutViewGradientResize) {
</style>
<div id='content' style='width: 200px; height: 200px'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Element* iframe = GetDocument().getElementById("iframe");
Element* content = ChildDocument().getElementById("content");
LayoutView* frame_layout_view = content->GetLayoutObject()->View();
@@ -425,46 +465,64 @@ TEST_P(PaintAndRasterInvalidationTest, NonCompositedLayoutViewGradientResize) {
// Resize the content.
GetDocument().View()->SetTracksPaintInvalidations(true);
- content->setAttribute(HTMLNames::styleAttr, "height: 500px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_THAT(
- GetRasterInvalidationTracking()->Invalidations(),
- UnorderedElementsAre(RasterInvalidationInfo{
- frame_layout_view, frame_layout_view->DebugName(),
- IntRect(0, 0, 100, 100), PaintInvalidationReason::kBackground}));
+ content->setAttribute(html_names::kStyleAttr, "height: 500px");
+ UpdateAllLifecyclePhasesForTest();
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // TODO(wangxianzhu): This is probably incorrect, but for now we assume
+ // any scrolling contents as composited during SPv2 painting. Perhaps we
+ // need some heuristic about composited scrolling during painting.
+ EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
+ } else {
+ EXPECT_THAT(
+ GetRasterInvalidationTracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ frame_layout_view, frame_layout_view->DebugName(),
+ IntRect(0, 0, 100, 100), PaintInvalidationReason::kBackground}));
+ }
GetDocument().View()->SetTracksPaintInvalidations(false);
// Resize the iframe.
GetDocument().View()->SetTracksPaintInvalidations(true);
- iframe->setAttribute(HTMLNames::styleAttr, "height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- // The iframe doesn't have anything visible by itself, so we only issue raster
- // invalidation for the frame contents.
- EXPECT_THAT(
- GetRasterInvalidationTracking()->Invalidations(),
- UnorderedElementsAre(RasterInvalidationInfo{
- frame_layout_view, frame_layout_view->DebugName(),
- IntRect(0, 0, 100, 200), PaintInvalidationReason::kGeometry}));
+ iframe->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // TODO(wangxianzhu): This is probably incorrect, but for now we assume
+ // any scrolling contents as composited during SPv2 painting. Perhaps we
+ // need some heuristic about composited scrolling during painting.
+ EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
+ } else {
+ // The iframe doesn't have anything visible by itself, so we only issue
+ // raster invalidation for the frame contents.
+ EXPECT_THAT(
+ GetRasterInvalidationTracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ frame_layout_view, frame_layout_view->DebugName(),
+ IntRect(0, 100, 100, 100), PaintInvalidationReason::kIncremental}));
+ }
GetDocument().View()->SetTracksPaintInvalidations(false);
}
TEST_P(PaintAndRasterInvalidationTest,
CompositedBackgroundAttachmentLocalResize) {
- // TODO(crbug.com/732611): Fix SPv2 for scrolling contents layer.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::classAttr, "background local-background");
- target->setAttribute(HTMLNames::styleAttr, "will-change: transform");
+ target->setAttribute(html_names::kClassAttr,
+ "solid composited scroll local-attachment border");
target->SetInnerHTMLFromString(
"<div id=child style='width: 500px; height: 500px'></div>",
ASSERT_NO_EXCEPTION);
Element* child = GetDocument().getElementById("child");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* target_obj = ToLayoutBoxModelObject(target->GetLayoutObject());
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ target_obj->GetBackgroundPaintLocation());
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ const auto* mapping = target_obj->Layer()->GetCompositedLayerMapping();
+ EXPECT_TRUE(mapping->BackgroundPaintsOntoScrollingContentsLayer());
+ EXPECT_FALSE(mapping->BackgroundPaintsOntoGraphicsLayer());
+ }
+
auto container_raster_invalidation_tracking =
[&]() -> const RasterInvalidationTracking* {
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
@@ -484,76 +542,99 @@ TEST_P(PaintAndRasterInvalidationTest,
// Resize the content.
GetDocument().View()->SetTracksPaintInvalidations(true);
- child->setAttribute(HTMLNames::styleAttr, "width: 500px; height: 1000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ child->setAttribute(html_names::kStyleAttr, "width: 500px; height: 1000px");
+ UpdateAllLifecyclePhasesForTest();
// No invalidation on the container layer.
EXPECT_FALSE(container_raster_invalidation_tracking()->HasInvalidations());
// Incremental invalidation of background on contents layer.
- const auto* client = target_obj->Layer()->GraphicsLayerBacking();
+ const auto& client = target_obj->GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
EXPECT_THAT(contents_raster_invalidation_tracking()->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
- client, client->DebugName(), IntRect(0, 500, 500, 500),
+ &client, client.DebugName(), IntRect(0, 500, 500, 500),
PaintInvalidationReason::kIncremental}));
GetDocument().View()->SetTracksPaintInvalidations(false);
// Resize the container.
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr,
- "will-change: transform; height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- // No invalidation for composited layer resize.
- EXPECT_FALSE(container_raster_invalidation_tracking()->HasInvalidations());
+ target->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ // Border invalidated in the container layer.
+ EXPECT_THAT(container_raster_invalidation_tracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ target_obj, target_obj->DebugName(), IntRect(0, 0, 70, 220),
+ PaintInvalidationReason::kGeometry}));
+ // No invalidation on scrolling contents for container resize.
EXPECT_FALSE(contents_raster_invalidation_tracking()->HasInvalidations());
GetDocument().View()->SetTracksPaintInvalidations(false);
}
TEST_P(PaintAndRasterInvalidationTest,
CompositedBackgroundAttachmentLocalGradientResize) {
- // TODO(crbug.com/732611): Fix SPv2 for scrolling contents layer.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::classAttr, "local-background gradient");
- target->setAttribute(HTMLNames::styleAttr, "will-change: transform");
+ target->setAttribute(html_names::kClassAttr,
+ "gradient composited scroll local-attachment border");
target->SetInnerHTMLFromString(
"<div id='child' style='width: 500px; height: 500px'></div>",
ASSERT_NO_EXCEPTION);
Element* child = GetDocument().getElementById("child");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
- // Resize the content.
- GetDocument().View()->SetTracksPaintInvalidations(true);
- child->setAttribute(HTMLNames::styleAttr, "width: 500px; height: 1000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
LayoutBoxModelObject* target_obj =
ToLayoutBoxModelObject(target->GetLayoutObject());
- GraphicsLayer* container_layer =
- target_obj->Layer()->GraphicsLayerBacking(target_obj);
- GraphicsLayer* contents_layer = target_obj->Layer()->GraphicsLayerBacking();
+ auto container_raster_invalidation_tracking =
+ [&]() -> const RasterInvalidationTracking* {
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return GetRasterInvalidationTracking(1);
+ return target_obj->Layer()
+ ->GraphicsLayerBacking(target_obj)
+ ->GetRasterInvalidationTracking();
+ };
+ auto contents_raster_invalidation_tracking =
+ [&]() -> const RasterInvalidationTracking* {
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ return GetRasterInvalidationTracking(2);
+ return target_obj->Layer()
+ ->GraphicsLayerBacking()
+ ->GetRasterInvalidationTracking();
+ };
+
+ // Resize the content.
+ GetDocument().View()->SetTracksPaintInvalidations(true);
+ child->setAttribute(html_names::kStyleAttr, "width: 500px; height: 1000px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ target_obj->GetBackgroundPaintLocation());
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ const auto* mapping = target_obj->Layer()->GetCompositedLayerMapping();
+ EXPECT_TRUE(mapping->BackgroundPaintsOntoScrollingContentsLayer());
+ EXPECT_FALSE(mapping->BackgroundPaintsOntoGraphicsLayer());
+ }
+
// No invalidation on the container layer.
- EXPECT_FALSE(
- container_layer->GetRasterInvalidationTracking()->HasInvalidations());
+ EXPECT_FALSE(container_raster_invalidation_tracking()->HasInvalidations());
// Full invalidation of background on contents layer because the gradient
// background is resized.
- EXPECT_THAT(
- contents_layer->GetRasterInvalidationTracking()->Invalidations(),
- UnorderedElementsAre(RasterInvalidationInfo{
- contents_layer, contents_layer->DebugName(), IntRect(0, 0, 500, 1000),
- PaintInvalidationReason::kBackgroundOnScrollingContentsLayer}));
+ const auto& client = target_obj->GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
+ EXPECT_THAT(contents_raster_invalidation_tracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ &client, client.DebugName(), IntRect(0, 0, 500, 1000),
+ PaintInvalidationReason::kBackground}));
GetDocument().View()->SetTracksPaintInvalidations(false);
// Resize the container.
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr,
- "will-change: transform; height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- // No explicit raster invalidation for composited layer resize.
- EXPECT_FALSE(
- container_layer->GetRasterInvalidationTracking()->HasInvalidations());
- EXPECT_FALSE(
- contents_layer->GetRasterInvalidationTracking()->HasInvalidations());
+ target->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ // Border invalidated in the container layer.
+ EXPECT_THAT(container_raster_invalidation_tracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ target_obj, target_obj->DebugName(), IntRect(0, 0, 70, 220),
+ PaintInvalidationReason::kGeometry}));
+ // No invalidation on scrolling contents for container resize.
+ EXPECT_FALSE(contents_raster_invalidation_tracking()->HasInvalidations());
GetDocument().View()->SetTracksPaintInvalidations(false);
}
@@ -562,60 +643,93 @@ TEST_P(PaintAndRasterInvalidationTest,
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
auto* object = target->GetLayoutObject();
- target->setAttribute(HTMLNames::classAttr, "background local-background");
+ target->setAttribute(html_names::kClassAttr, "solid local-attachment scroll");
target->SetInnerHTMLFromString(
"<div id=child style='width: 500px; height: 500px'></div>",
ASSERT_NO_EXCEPTION);
Element* child = GetDocument().getElementById("child");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_EQ(&GetLayoutView(),
- &target->GetLayoutObject()->ContainerForPaintInvalidation());
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(&GetLayoutView(), object->ContainerForPaintInvalidation());
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ ToLayoutBoxModelObject(object)->GetBackgroundPaintLocation());
// Resize the content.
GetDocument().View()->SetTracksPaintInvalidations(true);
- child->setAttribute(HTMLNames::styleAttr, "width: 500px; height: 1000px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ child->setAttribute(html_names::kStyleAttr, "width: 500px; height: 1000px");
+ UpdateAllLifecyclePhasesForTest();
// No invalidation because the changed part is invisible.
EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
// Resize the container.
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
- UnorderedElementsAre(RasterInvalidationInfo{
- object, object->DebugName(), IntRect(0, 100, 50, 100),
- PaintInvalidationReason::kIncremental}));
+ target->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // TODO(wangxianzhu): This is probably incorrect, but for now we assume
+ // any scrolling contents as composited during SPv2 painting. Perhaps we
+ // need some heuristic about composited scrolling during painting.
+ EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
+ } else {
+ EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ object, object->DebugName(), IntRect(0, 100, 50, 100),
+ PaintInvalidationReason::kIncremental}));
+ }
GetDocument().View()->SetTracksPaintInvalidations(false);
}
TEST_P(PaintAndRasterInvalidationTest, CompositedSolidBackgroundResize) {
- // TODO(crbug.com/732611): Fix SPv2 for scrolling contents layer.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
+ // To trigger background painting on both container and contents layer.
+ // Note that the test may need update when we change the background paint
+ // location rules.
+ SetPreferCompositingToLCDText(false);
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::classAttr, "solid-composited-scroller");
+ target->setAttribute(html_names::kClassAttr, "solid composited scroll");
target->SetInnerHTMLFromString("<div style='height: 500px'></div>",
ASSERT_NO_EXCEPTION);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Resize the scroller.
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 100px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 100px");
+ UpdateAllLifecyclePhasesForTest();
LayoutBoxModelObject* target_object =
ToLayoutBoxModelObject(target->GetLayoutObject());
- GraphicsLayer* scrolling_contents_layer =
- target_object->Layer()->GraphicsLayerBacking();
+ EXPECT_EQ(
+ kBackgroundPaintInScrollingContents | kBackgroundPaintInGraphicsLayer,
+ target_object->GetBackgroundPaintLocation());
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ const auto* mapping = target_object->Layer()->GetCompositedLayerMapping();
+ EXPECT_TRUE(mapping->BackgroundPaintsOntoScrollingContentsLayer());
+ EXPECT_TRUE(mapping->BackgroundPaintsOntoGraphicsLayer());
+ }
+
+ const auto* contents_raster_invalidation_tracking =
+ RuntimeEnabledFeatures::SlimmingPaintV2Enabled()
+ ? GetRasterInvalidationTracking(2)
+ : target_object->Layer()
+ ->GraphicsLayerBacking()
+ ->GetRasterInvalidationTracking();
+ const auto& client = target_object->GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
+ EXPECT_THAT(contents_raster_invalidation_tracking->Invalidations(),
+ UnorderedElementsAre(RasterInvalidationInfo{
+ &client, client.DebugName(), IntRect(50, 0, 50, 500),
+ PaintInvalidationReason::kIncremental}));
+ const auto* container_raster_invalidation_tracking =
+ RuntimeEnabledFeatures::SlimmingPaintV2Enabled()
+ ? GetRasterInvalidationTracking(1)
+ : target_object->Layer()
+ ->GraphicsLayerBacking(target_object)
+ ->GetRasterInvalidationTracking();
EXPECT_THAT(
- scrolling_contents_layer->GetRasterInvalidationTracking()
- ->Invalidations(),
+ container_raster_invalidation_tracking->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
- scrolling_contents_layer, scrolling_contents_layer->DebugName(),
- IntRect(50, 0, 50, 500), PaintInvalidationReason::kIncremental}));
+ target_object, target_object->DebugName(), IntRect(50, 0, 50, 100),
+ PaintInvalidationReason::kIncremental}));
GetDocument().View()->SetTracksPaintInvalidations(false);
}
@@ -641,7 +755,7 @@ TEST_P(PaintAndRasterInvalidationTest, RecalcOverflowInvalidatesBackground) {
<div id='container'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ScrollableArea* scrollable_area = GetDocument().View()->LayoutViewport();
ASSERT_EQ(scrollable_area->MaximumScrollOffset().Height(), 0);
@@ -649,7 +763,7 @@ TEST_P(PaintAndRasterInvalidationTest, RecalcOverflowInvalidatesBackground) {
GetDocument().GetLayoutView()->ShouldCheckForPaintInvalidation());
Element* container = GetDocument().getElementById("container");
- container->setAttribute(HTMLNames::styleAttr,
+ container->setAttribute(html_names::kStyleAttr,
"transform: translateY(1000px);");
GetDocument().UpdateStyleAndLayoutTree();
@@ -674,8 +788,8 @@ TEST_P(PaintAndRasterInvalidationTest,
EXPECT_EQ(LayoutRect(0, 0, 100, 100),
child_layout_view->FirstFragment().VisualRect());
- iframe->setAttribute(HTMLNames::styleAttr, "border: 20px solid blue");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ iframe->setAttribute(html_names::kStyleAttr, "border: 20px solid blue");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(GetDocument().GetLayoutView(),
&child_layout_view->ContainerForPaintInvalidation());
EXPECT_EQ(LayoutRect(0, 0, 100, 100),
@@ -683,10 +797,6 @@ TEST_P(PaintAndRasterInvalidationTest,
};
TEST_P(PaintAndRasterInvalidationTest, DelayedFullPaintInvalidation) {
- // TODO(crbug.com/732611): Fix SPv2 for scrolling contents layer.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0 }</style>
@@ -708,7 +818,7 @@ TEST_P(PaintAndRasterInvalidationTest, DelayedFullPaintInvalidation) {
EXPECT_TRUE(target->Parent()->ShouldCheckForPaintInvalidation());
GetDocument().View()->SetTracksPaintInvalidations(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
EXPECT_FALSE(target->ShouldDoFullPaintInvalidation());
EXPECT_TRUE(target->ShouldDelayFullPaintInvalidation());
@@ -722,7 +832,7 @@ TEST_P(PaintAndRasterInvalidationTest, DelayedFullPaintInvalidation) {
GetDocument().View()->SetTracksPaintInvalidations(true);
// Scroll target into view.
GetDocument().domWindow()->scrollTo(0, 4000);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(RasterInvalidationInfo{
target, target->DebugName(), IntRect(0, 4000, 100, 100),
@@ -761,7 +871,7 @@ TEST_P(PaintAndRasterInvalidationTest, SVGHiddenContainer) {
GetDocument().View()->SetTracksPaintInvalidations(true);
ToElement(mask_rect->GetNode())->setAttribute("x", "20");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(), mask_rect->FirstFragment().VisualRect());
EXPECT_EQ(LayoutRect(55, 66, 7, 8), real_rect->FirstFragment().VisualRect());
@@ -816,6 +926,10 @@ TEST_P(PaintAndRasterInvalidationTest, UpdateVisualRectWhenPrinting) {
FloatSize page_size(400, 200);
GetFrame().StartPrinting(page_size, page_size, 1);
GetDocument().View()->UpdateLifecyclePhasesForPrinting();
+ // In LayoutNG these may be different layout objects, so get them again
+ a = GetDocument().getElementById("a")->GetLayoutObject();
+ b = GetDocument().getElementById("b")->GetLayoutObject();
+ c = GetDocument().getElementById("c")->GetLayoutObject();
EXPECT_EQ(LayoutRect(0, 0, 150, 20), a->FirstFragment().VisualRect());
EXPECT_EQ(LayoutRect(150, 0, 150, 20), b->FirstFragment().VisualRect());
@@ -824,6 +938,9 @@ TEST_P(PaintAndRasterInvalidationTest, UpdateVisualRectWhenPrinting) {
GetFrame().EndPrinting();
GetDocument().View()->UpdateLifecyclePhasesForPrinting();
+ a = GetDocument().getElementById("a")->GetLayoutObject();
+ b = GetDocument().getElementById("b")->GetLayoutObject();
+ c = GetDocument().getElementById("c")->GetLayoutObject();
EXPECT_EQ(LayoutRect(0, 0, 150, 20), a->FirstFragment().VisualRect());
EXPECT_EQ(LayoutRect(150, 0, 150, 20), b->FirstFragment().VisualRect());
@@ -834,19 +951,19 @@ TEST_P(PaintAndRasterInvalidationTest, PaintPropertyChange) {
SetUpHTML(*this);
Element* target = GetDocument().getElementById("target");
auto* object = target->GetLayoutObject();
- target->setAttribute(HTMLNames::classAttr, "background transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kClassAttr, "solid transform");
+ UpdateAllLifecyclePhasesForTest();
auto* layer = ToLayoutBoxModelObject(object)->Layer();
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "transform: scale(3)");
+ target->setAttribute(html_names::kStyleAttr, "transform: scale(3)");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(layer->NeedsRepaint());
const auto* transform =
object->FirstFragment().PaintProperties()->Transform();
EXPECT_TRUE(transform->Changed(*transform->Parent()));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
UnorderedElementsAre(
RasterInvalidationInfo{
@@ -870,13 +987,12 @@ TEST_P(PaintAndRasterInvalidationTest, ResizeContainerOfFixedSizeSVG) {
Element* target = GetDocument().getElementById("target");
GetDocument().View()->SetTracksPaintInvalidations(true);
- target->setAttribute(HTMLNames::styleAttr, "width: 200px; height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "width: 200px; height: 200px");
+ UpdateAllLifecyclePhasesForTest();
// No raster invalidations because the resized-div doesn't paint anything by
// itself, and the svg is fixed sized.
- EXPECT_THAT(GetRasterInvalidationTracking()->Invalidations(),
- UnorderedElementsAre());
+ EXPECT_FALSE(GetRasterInvalidationTracking()->HasInvalidations());
// At least we don't invalidate paint of the SVG rect.
for (const auto& paint_invalidation :
*GetDocument().View()->TrackedObjectPaintInvalidations()) {
@@ -911,7 +1027,7 @@ TEST_P(PaintAndRasterInvalidationTest, ScrollingInvalidatesStickyOffset) {
const auto* inner = GetLayoutObjectByElementId("inner");
EXPECT_EQ(LayoutPoint(0, 0), inner->FirstFragment().PaintOffset());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(sticky->NeedsPaintPropertyUpdate());
EXPECT_EQ(LayoutPoint(0, 0), sticky->FirstFragment().PaintOffset());
@@ -968,8 +1084,8 @@ TEST_F(PaintInvalidatorCustomClientTest,
ResetInvalidationRecorded();
- target->setAttribute(HTMLNames::styleAttr, "opacity: 0.98");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "opacity: 0.98");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(InvalidationRecorded());
}
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.h b/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.h
index c5ba86ed439..fd4ee35e43e 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.h
@@ -5,7 +5,6 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_AND_RASTER_INVALIDATION_TEST_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_AND_RASTER_INVALIDATION_TEST_H_
-#include "cc/layers/picture_layer.h"
#include "third_party/blink/renderer/core/paint/paint_controller_paint_test.h"
#include "third_party/blink/renderer/platform/graphics/compositing/content_layer_client_impl.h"
#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
@@ -19,28 +18,21 @@ class PaintAndRasterInvalidationTest : public PaintControllerPaintTest {
: PaintControllerPaintTest(SingleChildLocalFrameClient::Create()) {}
protected:
- cc::Layer* GetCcLayer(size_t index = 0) const {
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- return GetDocument()
- .View()
- ->GetPaintArtifactCompositorForTesting()
- ->RootLayer()
- ->children()[index]
- .get();
- }
- return GetLayoutView().Layer()->GraphicsLayerBacking()->ContentLayer();
- }
-
- cc::LayerClient* GetCcLayerClient(size_t index = 0) const {
- return GetCcLayer(index)->GetLayerClientForTesting();
+ ContentLayerClientImpl* GetContentLayerClient(size_t index = 0) const {
+ DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+ const auto& clients = GetDocument()
+ .View()
+ ->GetPaintArtifactCompositorForTesting()
+ ->ContentLayerClientsForTesting();
+ return index < clients.size() ? clients[index].get() : nullptr;
}
const RasterInvalidationTracking* GetRasterInvalidationTracking(
size_t index = 0) const {
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- return static_cast<ContentLayerClientImpl*>(GetCcLayerClient(index))
- ->GetRasterInvalidator()
- .GetTracking();
+ if (auto* client = GetContentLayerClient(index))
+ return client->GetRasterInvalidator().GetTracking();
+ return nullptr;
}
return GetLayoutView()
.Layer()
@@ -61,8 +53,11 @@ class PaintAndRasterInvalidationTest : public PaintControllerPaintTest {
}
}
- const DisplayItemClient* ViewScrollingContentsDisplayItemClient() const {
- return GetLayoutView().Layer()->GraphicsLayerBacking();
+ void SetPreferCompositingToLCDText(bool enable) {
+ GetDocument()
+ .GetFrame()
+ ->GetSettings()
+ ->SetPreferCompositingToLCDTextEnabled(enable);
}
private:
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.cc
index f97a7e13108..40084431197 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.cc
@@ -9,12 +9,15 @@
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_layer_painter.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
+using testing::ElementsAre;
+
namespace blink {
INSTANTIATE_PAINT_TEST_CASE_P(PaintControllerPaintTest);
@@ -30,20 +33,21 @@ TEST_P(PaintControllerPaintTest, FullDocumentPaintingWithCaret) {
Element& div = *ToElement(GetDocument().body()->firstChild());
InlineTextBox& text_inline_box =
*ToLayoutText(div.firstChild()->GetLayoutObject())->FirstTextBox();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), kDocumentBackgroundType),
- TestDisplayItem(text_inline_box, kForegroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&text_inline_box, kForegroundType)));
div.focus();
- GetDocument().View()->UpdateAllLifecyclePhases();
-
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(), kDocumentBackgroundType),
- TestDisplayItem(text_inline_box, kForegroundType),
- TestDisplayItem(CaretDisplayItemClientForTesting(),
- DisplayItem::kCaret)); // New!
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&text_inline_box, kForegroundType),
+ // New!
+ IsSameId(&CaretDisplayItemClientForTesting(), DisplayItem::kCaret)));
}
TEST_P(PaintControllerPaintTest, InlineRelayout) {
@@ -54,26 +58,37 @@ TEST_P(PaintControllerPaintTest, InlineRelayout) {
LayoutBlock& div_block =
*ToLayoutBlock(GetDocument().body()->firstChild()->GetLayoutObject());
LayoutText& text = *ToLayoutText(div_block.FirstChild());
- InlineTextBox& first_text_box = *text.FirstTextBox();
+ DisplayItemClient& first_text_box =
+ text.FirstInlineFragment()
+ ? (DisplayItemClient&)*text.FirstInlineFragment()
+ : (DisplayItemClient&)*text.FirstTextBox();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), kDocumentBackgroundType),
- TestDisplayItem(first_text_box, kForegroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&first_text_box, kForegroundType)));
- div.setAttribute(HTMLNames::styleAttr, "width: 10px; height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div.setAttribute(html_names::kStyleAttr, "width: 10px; height: 200px");
+ UpdateAllLifecyclePhasesForTest();
LayoutText& new_text = *ToLayoutText(div_block.FirstChild());
- InlineTextBox& new_first_text_box = *new_text.FirstTextBox();
- InlineTextBox& second_text_box =
- *new_text.FirstTextBox()->NextForSameLayoutObject();
-
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(), kDocumentBackgroundType),
- TestDisplayItem(new_first_text_box, kForegroundType),
- TestDisplayItem(second_text_box, kForegroundType));
+ DisplayItemClient& new_first_text_box =
+ new_text.FirstInlineFragment()
+ ? (DisplayItemClient&)*new_text.FirstInlineFragment()
+ : (DisplayItemClient&)*text.FirstTextBox();
+ DisplayItemClient& second_text_box =
+ new_text.FirstInlineFragment()
+ ? (DisplayItemClient&)*NGPaintFragment::
+ TraverseNextForSameLayoutObject::Next(
+ new_text.FirstInlineFragment())
+ : (DisplayItemClient&)*new_text.FirstTextBox()
+ ->NextForSameLayoutObject();
+
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&new_first_text_box, kForegroundType),
+ IsSameId(&second_text_box, kForegroundType)));
}
TEST_P(PaintControllerPaintTest, ChunkIdClientCacheFlag) {
@@ -89,29 +104,11 @@ TEST_P(PaintControllerPaintTest, ChunkIdClientCacheFlag) {
LayoutObject& sub_div = *div.FirstChild();
LayoutObject& sub_div2 = *sub_div.NextSibling();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(), kDocumentBackgroundType),
- TestDisplayItem(sub_div, kBackgroundType),
- TestDisplayItem(sub_div2, kBackgroundType));
-
- // Verify that the background does not scroll.
- const PaintChunk& background_chunk = RootPaintController().PaintChunks()[0];
- auto* transform = background_chunk.properties.Transform();
- // TODO(crbug.com/732611): SPv2 invalidations are incorrect if there is
- // scrolling.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- EXPECT_FALSE(transform->ScrollNode());
- else
- EXPECT_TRUE(transform->ScrollNode());
-
- const EffectPaintPropertyNode* effect_node =
- div.FirstFragment().PaintProperties()->Effect();
- EXPECT_EQ(0.5f, effect_node->Opacity());
-
- const PaintChunk& chunk = RootPaintController().PaintChunks()[1];
- EXPECT_EQ(*div.Layer(), chunk.id.client);
- EXPECT_EQ(effect_node, chunk.properties.Effect());
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&sub_div, kBackgroundType),
+ IsSameId(&sub_div2, kBackgroundType)));
EXPECT_FALSE(div.Layer()->IsJustCreated());
// Client used by only paint chunks and non-cachaeable display items but not
@@ -131,10 +128,10 @@ TEST_P(PaintControllerPaintTest, CompositingNoFold) {
LayoutBlock& div = *ToLayoutBlock(GetLayoutObjectByElementId("div"));
LayoutObject& sub_div = *div.FirstChild();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), kDocumentBackgroundType),
- TestDisplayItem(sub_div, kBackgroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&sub_div, kBackgroundType)));
}
TEST_P(PaintControllerPaintTestForSPv2, FrameScrollingContents) {
@@ -151,24 +148,29 @@ TEST_P(PaintControllerPaintTestForSPv2, FrameScrollingContents) {
<div id='div4' style='top: 9000px; left: 9000px'></div>
)HTML");
- auto& div1 = *GetLayoutObjectByElementId("div1");
+ const auto& div1 = *GetLayoutObjectByElementId("div1");
+ const auto& div2 = *GetLayoutObjectByElementId("div2");
+ const auto& div3 = *GetLayoutObjectByElementId("div3");
+ const auto& div4 = *GetLayoutObjectByElementId("div4");
- // TODO(crbug.com/792577): Cull rect for frame scrolling contents is too
- // small?
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(GetLayoutView(), kScrollHitTestType),
- TestDisplayItem(div1, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&GetLayoutView(), kScrollHitTestType),
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&div1, kBackgroundType), IsSameId(&div2, kBackgroundType)));
GetDocument().View()->LayoutViewport()->SetScrollOffset(
ScrollOffset(5000, 5000), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
-
- // TODO(crbug.com/792577): Cull rect for frame scrolling contents is too
- // small?
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(GetLayoutView(), kScrollHitTestType));
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&GetLayoutView(), kScrollHitTestType),
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&div2, kBackgroundType), IsSameId(&div3, kBackgroundType),
+ IsSameId(&div4, kBackgroundType)));
}
TEST_P(PaintControllerPaintTestForSPv2, BlockScrollingNonLayeredContents) {
@@ -195,23 +197,25 @@ TEST_P(PaintControllerPaintTestForSPv2, BlockScrollingNonLayeredContents) {
auto& div4 = *GetLayoutObjectByElementId("div4");
// Initial cull rect: (0,0 4200x4200)
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(div1, kBackgroundType),
- TestDisplayItem(div2, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&div1, kBackgroundType), IsSameId(&div2, kBackgroundType)));
container.GetScrollableArea()->SetScrollOffset(ScrollOffset(5000, 5000),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Cull rect after scroll: (1000,1000 8100x8100)
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 5,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(div2, kBackgroundType),
- TestDisplayItem(div3, kBackgroundType),
- TestDisplayItem(div4, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&div2, kBackgroundType), IsSameId(&div3, kBackgroundType),
+ IsSameId(&div4, kBackgroundType)));
}
TEST_P(PaintControllerPaintTestForSPv2, ScrollHitTestOrder) {
@@ -236,12 +240,17 @@ TEST_P(PaintControllerPaintTestForSPv2, ScrollHitTestOrder) {
// The container's items should all be after the document's scroll hit test
// to ensure the container is hit before the document. Similarly, the child's
// items should all be after the container's scroll hit test.
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 5,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(GetLayoutView(), kScrollHitTestType),
- TestDisplayItem(container, kBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(child, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&GetLayoutView(), kScrollHitTestType),
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&container, kBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&container.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient(),
+ kBackgroundType),
+ IsSameId(&child, kBackgroundType)));
}
TEST_P(PaintControllerPaintTestForSPv2, NonStackingScrollHitTestOrder) {
@@ -276,13 +285,18 @@ TEST_P(PaintControllerPaintTestForSPv2, NonStackingScrollHitTestOrder) {
// testing should hit positive descendants, the container, and then negative
// descendants so the ScrollHitTest item should be immediately after the
// background.
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(neg_z_child, kBackgroundType),
- TestDisplayItem(container, kBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(child, kBackgroundType),
- TestDisplayItem(pos_z_child, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&neg_z_child, kBackgroundType),
+ IsSameId(&container, kBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&container.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient(),
+ kBackgroundType),
+ IsSameId(&child, kBackgroundType),
+ IsSameId(&pos_z_child, kBackgroundType)));
}
TEST_P(PaintControllerPaintTestForSPv2, StackingScrollHitTestOrder) {
@@ -315,13 +329,18 @@ TEST_P(PaintControllerPaintTestForSPv2, StackingScrollHitTestOrder) {
// Both positive and negative z-index descendants are painted after the
// background. The scroll hit test should be after the background but before
// the z-index descendants to ensure hit test order is correct.
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(container, kBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(neg_z_child, kBackgroundType),
- TestDisplayItem(child, kBackgroundType),
- TestDisplayItem(pos_z_child, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(&container, kBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&container.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient(),
+ kBackgroundType),
+ IsSameId(&neg_z_child, kBackgroundType),
+ IsSameId(&child, kBackgroundType),
+ IsSameId(&pos_z_child, kBackgroundType)));
}
TEST_P(PaintControllerPaintTestForSPv2,
@@ -353,12 +372,13 @@ TEST_P(PaintControllerPaintTestForSPv2,
// Even though container does not paint a background, the scroll hit test item
// should still be between the negative z-index child and the regular child.
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 5,
- TestDisplayItem(GetLayoutView(), kDocumentBackgroundType),
- TestDisplayItem(neg_z_child, kBackgroundType),
- TestDisplayItem(container, kScrollHitTestType),
- TestDisplayItem(child, kBackgroundType),
- TestDisplayItem(pos_z_child, kBackgroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&neg_z_child, kBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&child, kBackgroundType),
+ IsSameId(&pos_z_child, kBackgroundType)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.h b/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.h
index 9b284a22450..10a82a00786 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.h
@@ -47,8 +47,7 @@ class PaintControllerPaintTestBase : public RenderingTest {
GraphicsContext graphics_context(RootPaintController());
GetDocument().View()->Paint(
graphics_context, kGlobalPaintNormalPhase,
- interest_rect ? CullRect(*interest_rect)
- : CullRect(LayoutRect::InfiniteIntRect()));
+ interest_rect ? CullRect(*interest_rect) : CullRect::Infinite());
return true;
}
GetDocument().View()->Lifecycle().AdvanceTo(
@@ -65,13 +64,10 @@ class PaintControllerPaintTestBase : public RenderingTest {
return true;
}
- const DisplayItemClient& ViewBackgroundClient() {
- if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- // With SPv1, the document background uses the scrolling contents
- // layer as its DisplayItemClient.
- return *GetLayoutView().Layer()->GraphicsLayerBacking();
- }
- return GetLayoutView();
+ const DisplayItemClient& ViewScrollingBackgroundClient() {
+ return GetLayoutView()
+ .GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
}
void CommitAndFinishCycle() {
@@ -119,6 +115,11 @@ class PaintControllerPaintTestBase : public RenderingTest {
bool ClientCacheIsValid(const DisplayItemClient& client) {
return RootPaintController().ClientCacheIsValid(client);
}
+
+ using SubsequenceMarkers = PaintController::SubsequenceMarkers;
+ SubsequenceMarkers* GetSubsequenceMarkers(const DisplayItemClient& client) {
+ return RootPaintController().GetSubsequenceMarkers(client);
+ }
};
class PaintControllerPaintTest : public PaintTestConfigurations,
@@ -128,6 +129,29 @@ class PaintControllerPaintTest : public PaintTestConfigurations,
: PaintControllerPaintTestBase(local_frame_client) {}
};
+// Shorter names for frequently used display item types in core/ tests.
+const DisplayItem::Type kNonScrollingBackgroundChunkType =
+ DisplayItem::PaintPhaseToDrawingType(PaintPhase::kSelfBlockBackgroundOnly);
+const DisplayItem::Type kScrollingBackgroundChunkType =
+ DisplayItem::PaintPhaseToClipType(PaintPhase::kSelfBlockBackgroundOnly);
+const DisplayItem::Type kNonScrollingContentsBackgroundChunkType =
+ DisplayItem::PaintPhaseToDrawingType(
+ PaintPhase::kDescendantBlockBackgroundsOnly);
+const DisplayItem::Type kScrollingContentsBackgroundChunkType =
+ DisplayItem::PaintPhaseToClipType(
+ PaintPhase::kDescendantBlockBackgroundsOnly);
+
+#define EXPECT_SUBSEQUENCE(client, expected_start, expected_end) \
+ do { \
+ auto* subsequence = GetSubsequenceMarkers(client); \
+ ASSERT_NE(nullptr, subsequence); \
+ EXPECT_EQ(static_cast<size_t>(expected_start), subsequence->start); \
+ EXPECT_EQ(static_cast<size_t>(expected_end), subsequence->end); \
+ } while (false)
+
+#define EXPECT_NO_SUBSEQUENCE(client) \
+ EXPECT_EQ(nullptr, GetSubsequenceMarkers(client)
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_CONTROLLER_PAINT_TEST_H_
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_info.h b/chromium/third_party/blink/renderer/core/paint/paint_info.h
index 5ec583786b9..fa4838be50b 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_info.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_info.h
@@ -71,7 +71,8 @@ struct CORE_EXPORT PaintInfo {
fragment_logical_top_in_flow_thread),
paint_flags_(paint_flags),
global_paint_flags_(global_paint_flags),
- suppress_painting_descendants_(suppress_painting_descendants) {}
+ suppress_painting_descendants_(suppress_painting_descendants),
+ is_painting_scrolling_background_(false) {}
PaintInfo(GraphicsContext& new_context,
const PaintInfo& copy_other_fields_from)
@@ -84,12 +85,20 @@ struct CORE_EXPORT PaintInfo {
paint_flags_(copy_other_fields_from.paint_flags_),
global_paint_flags_(copy_other_fields_from.global_paint_flags_),
suppress_painting_descendants_(
- copy_other_fields_from.suppress_painting_descendants_) {}
+ copy_other_fields_from.suppress_painting_descendants_),
+ is_painting_scrolling_background_(false) {
+ // We should never pass is_painting_scrolling_background_ other PaintInfo.
+ DCHECK(!copy_other_fields_from.is_painting_scrolling_background_);
+ }
// Creates a PaintInfo for painting descendants. See comments about the paint
// phases in PaintPhase.h for details.
PaintInfo ForDescendants() const {
PaintInfo result(*this);
+
+ // We should never start to paint descendant when the flag is set.
+ DCHECK(!result.is_painting_scrolling_background_);
+
if (phase == PaintPhase::kDescendantOutlinesOnly)
result.phase = PaintPhase::kOutline;
else if (phase == PaintPhase::kDescendantBlockBackgroundsOnly)
@@ -104,9 +113,17 @@ struct CORE_EXPORT PaintInfo {
return paint_flags_ & kPaintLayerPaintingRenderingResourceSubtree;
}
+ // TODO(wangxianzhu): Rename this function to SkipBackground() for SPv2.
bool SkipRootBackground() const {
return paint_flags_ & kPaintLayerPaintingSkipRootBackground;
}
+ void SetSkipsBackground(bool b) {
+ DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+ if (b)
+ paint_flags_ |= kPaintLayerPaintingSkipRootBackground;
+ else
+ paint_flags_ &= ~kPaintLayerPaintingSkipRootBackground;
+ }
bool IsPrinting() const { return global_paint_flags_ & kGlobalPaintPrinting; }
@@ -128,19 +145,10 @@ struct CORE_EXPORT PaintInfo {
const CullRect& GetCullRect() const { return cull_rect_; }
- void ApplyInfiniteCullRect() {
- cull_rect_ = CullRect(LayoutRect::InfiniteIntRect());
- }
-
- void UpdateCullRect(const AffineTransform& local_to_parent_transform) {
- cull_rect_.UpdateCullRect(local_to_parent_transform);
- }
+ void ApplyInfiniteCullRect() { cull_rect_ = CullRect::Infinite(); }
- void UpdateCullRectForScrollingContents(
- const IntRect& overflow_clip_rect,
- const AffineTransform& local_to_parent_transform) {
- cull_rect_.UpdateForScrollingContents(overflow_clip_rect,
- local_to_parent_transform);
+ void TransformCullRect(const TransformPaintPropertyNode* transform) {
+ cull_rect_.ApplyTransform(transform);
}
// Returns the fragment of the current painting object matching the current
@@ -161,8 +169,17 @@ struct CORE_EXPORT PaintInfo {
fragment_logical_top_in_flow_thread_ = fragment_logical_top;
}
+ bool IsPaintingScrollingBackground() const {
+ DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+ return is_painting_scrolling_background_;
+ }
+ void SetIsPaintingScrollingBackground(bool b) {
+ DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+ is_painting_scrolling_background_ = b;
+ }
+
// FIXME: Introduce setters/getters at some point. Requires a lot of changes
- // throughout layout/.
+ // throughout paint/.
GraphicsContext& context;
PaintPhase phase;
@@ -176,13 +193,12 @@ struct CORE_EXPORT PaintInfo {
// which initiated the current painting, in the containing flow thread.
LayoutUnit fragment_logical_top_in_flow_thread_;
- const PaintLayerFlags paint_flags_;
+ PaintLayerFlags paint_flags_;
const GlobalPaintFlags global_paint_flags_;
const bool suppress_painting_descendants_;
- // TODO(chrishtr): temporary while we implement CullRect everywhere.
- friend class ScopedSVGPaintState;
- friend class SVGShapePainter;
+ // For SPv2 only.
+ bool is_painting_scrolling_background_;
};
Image::ImageDecodingMode GetImageDecodingMode(Node*);
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc b/chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc
index 7a9f4cab984..83e098a5dc3 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc
@@ -226,10 +226,8 @@ void PaintInvalidator::UpdatePaintingLayer(const LayoutObject& object,
context.painting_layer->SetNeedsPaintPhaseDescendantBlockBackgrounds();
} else if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled()) {
// Hit testing rects for touch action paint in the background phase.
- if (object.EffectiveWhitelistedTouchAction() !=
- TouchAction::kTouchActionAuto) {
+ if (object.HasEffectiveWhitelistedTouchAction())
context.painting_layer->SetNeedsPaintPhaseDescendantBlockBackgrounds();
- }
}
}
@@ -490,7 +488,9 @@ void PaintInvalidator::InvalidatePaint(
auto reason = static_cast<const DisplayItemClient&>(object)
.GetPaintInvalidationReason();
if (object.ShouldDelayFullPaintInvalidation() &&
- !IsFullPaintInvalidationReason(reason))
+ (!IsFullPaintInvalidationReason(reason) ||
+ // Delay invalidation if the client has never been painted.
+ reason == PaintInvalidationReason::kJustCreated))
pending_delayed_paint_invalidations_.push_back(&object);
if (object.SubtreeShouldDoFullPaintInvalidation()) {
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer.cc
index 134aa1e493e..90810d02437 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -48,8 +48,8 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/animation/scroll_timeline.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/pseudo_style_request.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -85,11 +85,11 @@
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/geometry/float_point_3d.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/compositor_filter_operations.h"
#include "third_party/blink/renderer/platform/graphics/filters/filter.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/transforms/transform_state.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
@@ -117,7 +117,7 @@ struct SameSizeAsPaintLayer : DisplayItemClient {
LayoutUnit layout_units[4];
IntSize size;
Persistent<PaintLayerScrollableArea> scrollable_area;
- LayoutRect previous_dirty_rect;
+ CullRect previous_cull_rect;
};
static_assert(sizeof(PaintLayer) == sizeof(SameSizeAsPaintLayer),
@@ -126,8 +126,6 @@ static_assert(sizeof(PaintLayer) == sizeof(SameSizeAsPaintLayer),
} // namespace
-using namespace HTMLNames;
-
PaintLayerRareData::PaintLayerRareData()
: enclosing_pagination_layer(nullptr),
potential_compositing_reasons_from_style(CompositingReason::kNone),
@@ -247,7 +245,7 @@ PaintLayerCompositor* PaintLayer::Compositor() const {
void PaintLayer::ContentChanged(ContentChangeType change_type) {
// updateLayerCompositingState will query compositingReasons for accelerated
// overflow scrolling. This is tripped by
- // LayoutTests/compositing/content-changed-chicken-egg.html
+ // web_tests/compositing/content-changed-chicken-egg.html
DisableCompositingQueryAsserts disabler;
if (Compositor()) {
@@ -282,15 +280,6 @@ bool PaintLayer::PaintsWithFilters() const {
GetCompositingState() != kPaintsIntoOwnBacking;
}
-bool PaintLayer::PaintsWithBackdropFilters() const {
- if (!GetLayoutObject().HasBackdropFilter())
- return false;
-
- // https://code.google.com/p/chromium/issues/detail?id=343759
- DisableCompositingQueryAsserts disabler;
- return !GetCompositedLayerMapping() ||
- GetCompositingState() != kPaintsIntoOwnBacking;
-}
LayoutSize PaintLayer::SubpixelAccumulation() const {
return rare_data_ ? rare_data_->subpixel_accumulation : LayoutSize();
@@ -1673,7 +1662,7 @@ bool PaintLayer::HasOverflowControls() const {
void PaintLayer::AppendSingleFragmentIgnoringPagination(
PaintLayerFragments& fragments,
const PaintLayer* root_layer,
- const LayoutRect* dirty_rect,
+ const CullRect* cull_rect,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior,
ShouldRespectOverflowClipType respect_overflow_clip,
const LayoutPoint* offset_from_root,
@@ -1685,7 +1674,7 @@ void PaintLayer::AppendSingleFragmentIgnoringPagination(
respect_overflow_clip, sub_pixel_accumulation);
Clipper(kUseGeometryMapper)
.CalculateRects(clip_rects_context, &GetLayoutObject().FirstFragment(),
- dirty_rect, fragment.layer_bounds,
+ cull_rect, fragment.layer_bounds,
fragment.background_rect, fragment.foreground_rect,
offset_from_root);
fragment.root_fragment_data = &root_layer->GetLayoutObject().FirstFragment();
@@ -1714,7 +1703,7 @@ bool PaintLayer::ShouldFragmentCompositedBounds(
void PaintLayer::CollectFragments(
PaintLayerFragments& fragments,
const PaintLayer* root_layer,
- const LayoutRect* dirty_rect,
+ const CullRect* cull_rect,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior,
ShouldRespectOverflowClipType respect_overflow_clip,
const LayoutPoint* offset_from_root,
@@ -1771,20 +1760,20 @@ void PaintLayer::CollectFragments(
overlay_scrollbar_clip_behavior, respect_overflow_clip,
sub_pixel_accumulation);
- base::Optional<LayoutRect> fragment_dirty_rect;
- if (dirty_rect) {
- // |dirty_rect| is in the coordinate space of |root_layer| (i.e. the
+ base::Optional<CullRect> fragment_cull_rect;
+ if (cull_rect) {
+ // |cull_rect| is in the coordinate space of |root_layer| (i.e. the
// space of |root_layer|'s first fragment). Map the rect to the space of
// the current root fragment.
- fragment_dirty_rect = *dirty_rect;
- first_root_fragment_data.MapRectToFragment(*root_fragment_data,
- *fragment_dirty_rect);
+ auto rect = cull_rect->Rect();
+ first_root_fragment_data.MapRectToFragment(*root_fragment_data, rect);
+ fragment_cull_rect.emplace(rect);
}
Clipper(kUseGeometryMapper)
.CalculateRects(
clip_rects_context, fragment_data,
- fragment_dirty_rect ? &*fragment_dirty_rect : nullptr,
+ fragment_cull_rect ? &*fragment_cull_rect : nullptr,
fragment.layer_bounds, fragment.background_rect,
fragment.foreground_rect,
offset_from_root_can_be_used ? offset_from_root : nullptr);
@@ -2509,7 +2498,8 @@ bool PaintLayer::HitTestClippedOutByClipPath(
float inverse_zoom = 1 / GetLayoutObject().StyleRef().EffectiveZoom();
point.Scale(inverse_zoom, inverse_zoom);
reference_box.Scale(inverse_zoom);
- return !clipper->HitTestClipContent(reference_box, point);
+ HitTestLocation location(point);
+ return !clipper->HitTestClipContent(reference_box, location);
}
bool PaintLayer::IntersectsDamageRect(
@@ -2755,25 +2745,6 @@ GraphicsLayer* PaintLayer::GraphicsLayerBacking(const LayoutObject* obj) const {
}
}
-BackgroundPaintLocation PaintLayer::GetBackgroundPaintLocation(
- uint32_t* reasons) const {
- BackgroundPaintLocation location;
- bool may_have_scrolling_layers_without_scrolling = IsRootLayer();
- if (!ScrollsOverflow() && !may_have_scrolling_layers_without_scrolling) {
- location = kBackgroundPaintInGraphicsLayer;
- } else {
- // If we care about LCD text, paint root backgrounds into scrolling contents
- // layer even if style suggests otherwise. (For non-root scrollers, we just
- // avoid compositing - see PLSA::ComputeNeedsCompositedScrolling.)
- DCHECK(Compositor());
- if (IsRootLayer() && !Compositor()->PreferCompositingToLCDTextEnabled())
- location = kBackgroundPaintInScrollingContents;
- else
- location = GetLayoutObject().GetBackgroundPaintLocation(reasons);
- }
- return location;
-}
-
void PaintLayer::EnsureCompositedLayerMapping() {
if (rare_data_ && rare_data_->composited_layer_mapping)
return;
@@ -2877,7 +2848,8 @@ bool PaintLayer::CompositesWithOpacity() const {
}
bool PaintLayer::BackgroundIsKnownToBeOpaqueInRect(
- const LayoutRect& local_rect) const {
+ const LayoutRect& local_rect,
+ bool should_check_children) const {
if (PaintsWithTransparency(kGlobalPaintNormalPhase))
return false;
@@ -2909,6 +2881,9 @@ bool PaintLayer::BackgroundIsKnownToBeOpaqueInRect(
if (GetLayoutObject().BackgroundIsKnownToBeOpaqueInRect(local_rect))
return true;
+ if (!should_check_children)
+ return false;
+
// We can't consult child layers if we clip, since they might cover
// parts of the rect that are clipped out.
if (GetLayoutObject().HasClipRelatedProperty())
@@ -2942,7 +2917,7 @@ bool PaintLayer::ChildBackgroundIsKnownToBeOpaqueInRect(
child_layer->ConvertToLayerCoords(this, child_offset);
child_local_rect.MoveBy(-child_offset);
- if (child_layer->BackgroundIsKnownToBeOpaqueInRect(child_local_rect))
+ if (child_layer->BackgroundIsKnownToBeOpaqueInRect(child_local_rect, true))
return true;
}
return false;
@@ -3089,15 +3064,8 @@ bool PaintLayer::AttemptDirectCompositingUpdate(
if (!rare_data_ || !rare_data_->composited_layer_mapping)
return false;
- // To cut off almost all the work in the compositing update for
- // this case, we treat inline transforms has having assumed overlap
- // (similar to how we treat animated transforms). Notice that we read
- // CompositingReasonInlineTransform from the m_compositingReasons, which
- // means that the inline transform actually triggered assumed overlap in
- // the overlap map.
- if (diff.TransformChanged() &&
- (!rare_data_ || !(rare_data_->compositing_reasons &
- CompositingReason::kInlineTransform)))
+ // If a transform changed, we can't use the fast path.
+ if (diff.TransformChanged())
return false;
// We composite transparent Layers differently from non-transparent
@@ -3173,7 +3141,8 @@ void PaintLayer::StyleDidChange(StyleDifference diff,
SetNeedsCompositingInputsUpdate();
}
- if (diff.NeedsLayout())
+ // HasAlphaChanged can affect whether a composited layer is opaque.
+ if (diff.NeedsLayout() || diff.HasAlphaChanged())
SetNeedsCompositingInputsUpdate();
// A scroller that changes background color might become opaque or not
@@ -3263,11 +3232,21 @@ void PaintLayer::UpdateCompositorFilterOperationsForFilter(
if (!operations.IsEmpty() && !filter_on_effect_node_dirty_ &&
reference_box == operations.ReferenceBox())
return;
-
operations =
FilterEffectBuilder(reference_box, zoom).BuildFilterOperations(filter);
}
+void PaintLayer::UpdateCompositorFilterOperationsForBackdropFilter(
+ CompositorFilterOperations& operations) const {
+ const auto& style = GetLayoutObject().StyleRef();
+ float zoom = style.EffectiveZoom();
+ auto filter = FilterOperationsIncludingReflection();
+ FloatRect reference_box = FilterReferenceBox(filter, zoom);
+ if (!operations.IsEmpty() && reference_box == operations.ReferenceBox())
+ return;
+ operations = CreateCompositorFilterOperationsForBackdropFilter();
+}
+
CompositorFilterOperations
PaintLayer::CreateCompositorFilterOperationsForBackdropFilter() const {
const auto& style = GetLayoutObject().StyleRef();
@@ -3279,8 +3258,10 @@ PaintLayer::CreateCompositorFilterOperationsForBackdropFilter() const {
PaintLayerResourceInfo& PaintLayer::EnsureResourceInfo() {
PaintLayerRareData& rare_data = EnsureRareData();
- if (!rare_data.resource_info)
- rare_data.resource_info = new PaintLayerResourceInfo(this);
+ if (!rare_data.resource_info) {
+ rare_data.resource_info =
+ MakeGarbageCollected<PaintLayerResourceInfo>(this);
+ }
return *rare_data.resource_info;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer.h b/chromium/third_party/blink/renderer/core/paint/paint_layer.h
index 43e1ef79a57..232b549fab4 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer.h
@@ -59,6 +59,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h"
#include "third_party/blink/renderer/core/paint/paint_result.h"
#include "third_party/blink/renderer/platform/graphics/compositing_reasons.h"
+#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/squashing_disallowed_reasons.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -292,10 +293,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void SetSizeHackForLayoutTreeAsText(const LayoutSize& size) { size_ = size; }
- // For LayoutTreeAsText
- LayoutRect RectIgnoringNeedsPositionUpdate() const {
- return LayoutRect(LocationInternal(), size_);
- }
#if DCHECK_IS_ON()
bool NeedsPositionUpdate() const { return needs_position_update_; }
#endif
@@ -531,12 +528,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
// Returns nullptr if this PaintLayer is not composited.
GraphicsLayer* GraphicsLayerBacking(const LayoutObject* = nullptr) const;
- // TODO(yigu): PaintLayerScrollableArea::computeNeedsCompositedScrolling
- // calls this method to obtain main thread scrolling reasons due to
- // background paint location. Once the cases get handled on compositor the
- // parameter "reasons" could be removed.
- BackgroundPaintLocation GetBackgroundPaintLocation(
- uint32_t* reasons = nullptr) const;
// NOTE: If you are using hasCompositedLayerMapping to determine the state of
// compositing for this layer, (and not just to do bookkeeping related to the
// mapping like, say, allocating or deallocating a mapping), then you may have
@@ -607,7 +598,10 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
// Returns true if background phase is painted opaque in the given rect.
// The query rect is given in local coordinates.
- bool BackgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const;
+ // if |should_check_children| is true, checks non-composited stacking children
+ // recursively to see if they paint opaquely over the rect.
+ bool BackgroundIsKnownToBeOpaqueInRect(const LayoutRect&,
+ bool should_check_children) const;
bool ContainsDirtyOverlayScrollbars() const {
return contains_dirty_overlay_scrollbars_;
@@ -624,6 +618,9 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void SetFilterOnEffectNodeDirty() { filter_on_effect_node_dirty_ = true; }
void ClearFilterOnEffectNodeDirty() { filter_on_effect_node_dirty_ = false; }
+ void UpdateCompositorFilterOperationsForBackdropFilter(
+ CompositorFilterOperations&) const;
+
void SetIsUnderSVGHiddenContainer(bool value) {
is_under_svg_hidden_container_ = value;
}
@@ -633,7 +630,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
const;
bool PaintsWithFilters() const;
- bool PaintsWithBackdropFilters() const;
FilterEffect* LastFilterEffect() const;
// Maps "forward" to determine which pixels in a destination rect are
@@ -758,6 +754,8 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
IntRect unclipped_absolute_bounding_box;
const LayoutBoxModelObject* clipping_container = nullptr;
+
+ bool is_under_video = false;
};
void SetNeedsCompositingInputsUpdate();
@@ -826,6 +824,9 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
const PaintLayer* MaskAncestor() const {
return GetAncestorDependentCompositingInputs().mask_ancestor;
}
+ bool IsUnderVideo() const {
+ return GetAncestorDependentCompositingInputs().is_under_video;
+ }
bool HasDescendantWithClipPath() const {
DCHECK(!needs_descendant_dependent_flags_update_);
return has_descendant_with_clip_path_;
@@ -917,7 +918,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void AppendSingleFragmentIgnoringPagination(
PaintLayerFragments&,
const PaintLayer* root_layer,
- const LayoutRect* dirty_rect,
+ const CullRect* cull_rect,
OverlayScrollbarClipBehavior = kIgnorePlatformOverlayScrollbarSize,
ShouldRespectOverflowClipType = kRespectOverflowClip,
const LayoutPoint* offset_from_root = nullptr,
@@ -926,7 +927,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void CollectFragments(
PaintLayerFragments&,
const PaintLayer* root_layer,
- const LayoutRect* dirty_rect,
+ const CullRect* cull_rect,
OverlayScrollbarClipBehavior = kIgnorePlatformOverlayScrollbarSize,
ShouldRespectOverflowClipType = kRespectOverflowClip,
const LayoutPoint* offset_from_root = nullptr,
@@ -965,12 +966,8 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
// shouldCreateSubsequence() in PaintLayerPainter.cpp for the cases we use
// subsequence when painting a PaintLayer.
- LayoutRect PreviousPaintDirtyRect() const {
- return previous_paint_dirty_rect_;
- }
- void SetPreviousPaintDirtyRect(const LayoutRect& rect) {
- previous_paint_dirty_rect_ = rect;
- }
+ CullRect PreviousCullRect() const { return previous_cull_rect_; }
+ void SetPreviousCullRect(const CullRect& rect) { previous_cull_rect_ = rect; }
PaintResult PreviousPaintResult() const {
return static_cast<PaintResult>(previous_paint_result_);
@@ -1341,7 +1338,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
std::unique_ptr<PaintLayerStackingNode> stacking_node_;
- LayoutRect previous_paint_dirty_rect_;
+ CullRect previous_cull_rect_;
std::unique_ptr<PaintLayerRareData> rare_data_;
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.cc
index d9408bf5d5c..5c2b8267cc7 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.cc
@@ -48,6 +48,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/page/scrolling/root_scroller_util.h"
#include "third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
@@ -270,7 +271,7 @@ LayoutRect PaintLayerClipper::LocalClipRect(
void PaintLayerClipper::CalculateRectsWithGeometryMapper(
const ClipRectsContext& context,
const FragmentData& fragment_data,
- const LayoutRect* paint_dirty_rect,
+ const CullRect* cull_rect,
LayoutRect& layer_bounds,
ClipRect& background_rect,
ClipRect& foreground_rect,
@@ -280,20 +281,24 @@ void PaintLayerClipper::CalculateRectsWithGeometryMapper(
layer_bounds.SetLocation(*offset_from_root);
} else {
layer_bounds.SetLocation(LayoutPoint(context.sub_pixel_accumulation));
- layer_bounds.MoveBy(fragment_data.PaintOffset());
- GeometryMapper::SourceToDestinationRect(
- fragment_data.PreTransform(),
- context.root_fragment->LocalBorderBoxProperties().Transform(),
- layer_bounds);
- layer_bounds.MoveBy(-context.root_fragment->PaintOffset());
+ if (&layer_ == context.root_layer) {
+ DCHECK_EQ(&fragment_data, context.root_fragment);
+ } else {
+ layer_bounds.MoveBy(fragment_data.PaintOffset());
+ GeometryMapper::SourceToDestinationRect(
+ fragment_data.PreTransform(),
+ context.root_fragment->LocalBorderBoxProperties().Transform(),
+ layer_bounds);
+ layer_bounds.MoveBy(-context.root_fragment->PaintOffset());
+ }
}
CalculateBackgroundClipRectWithGeometryMapper(
context, fragment_data, kRespectOverflowClip, background_rect);
foreground_rect.Reset();
- if (paint_dirty_rect)
- background_rect.Intersect(*paint_dirty_rect);
+ if (cull_rect)
+ background_rect.Intersect(LayoutRect(cull_rect->Rect()));
if (ShouldClipOverflow(context)) {
LayoutBoxModelObject& layout_object = layer_.GetLayoutObject();
@@ -312,7 +317,7 @@ void PaintLayerClipper::CalculateRectsWithGeometryMapper(
void PaintLayerClipper::CalculateRects(
const ClipRectsContext& context,
const FragmentData* fragment_data,
- const LayoutRect* paint_dirty_rect,
+ const CullRect* cull_rect,
LayoutRect& layer_bounds,
ClipRect& background_rect,
ClipRect& foreground_rect,
@@ -325,7 +330,7 @@ void PaintLayerClipper::CalculateRects(
// TODO(chrishtr): find the root cause of not having a fragment and fix it.
if (!fragment_data->HasLocalBorderBoxProperties())
return;
- CalculateRectsWithGeometryMapper(context, *fragment_data, paint_dirty_rect,
+ CalculateRectsWithGeometryMapper(context, *fragment_data, cull_rect,
layer_bounds, background_rect,
foreground_rect, offset_from_root);
return;
@@ -339,8 +344,8 @@ void PaintLayerClipper::CalculateRects(
CalculateBackgroundClipRect(context, background_rect);
background_rect.Move(context.sub_pixel_accumulation);
}
- if (paint_dirty_rect)
- background_rect.Intersect(*paint_dirty_rect);
+ if (cull_rect)
+ background_rect.Intersect(LayoutRect(cull_rect->Rect()));
foreground_rect = background_rect;
@@ -524,12 +529,12 @@ void PaintLayerClipper::InitializeCommonClipRectState(
LayoutRect PaintLayerClipper::LocalVisualRect(
const ClipRectsContext& context) const {
const LayoutObject& layout_object = layer_.GetLayoutObject();
- // The LayoutView is special since its overflow clipping rect may be larger
- // than its box rect (crbug.com/492871).
+ // The LayoutView or Global Root Scroller is special since its overflow
+ // clipping rect may be larger than its box rect (crbug.com/492871).
+ bool affected_by_url_bar = layout_object.IsGlobalRootScroller();
LayoutRect layer_bounds_with_visual_overflow =
- layout_object.IsLayoutView()
- ? ToLayoutView(layout_object).ViewRect()
- : ToLayoutBox(layout_object).VisualOverflowRect();
+ affected_by_url_bar ? layout_object.View()->ViewRect()
+ : ToLayoutBox(layout_object).VisualOverflowRect();
ToLayoutBox(layout_object)
.FlipForWritingMode(
// PaintLayer are in physical coordinates, so the overflow has to be
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.h
index 50bde01ed1e..dc5b2f7fd76 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.h
@@ -47,9 +47,8 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/paint/clip_rects_cache.h"
-
+#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
-
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -191,11 +190,11 @@ class CORE_EXPORT PaintLayerClipper {
// include subpixel accumualation. Otherwise it is set to the offset from
// |layer_| to |root_layer|, plus |context.sub_pixel_accumuation|.
// |fragment_data| is only used in kUseGeometryMapper mode.
- // If |paint_dirty_rect| is provided, intersects |background_rect|
- // and |foreground_rect| with it.
+ // If |cull_rect| is provided, intersects |background_rect| and
+ // |foreground_rect| with it.
void CalculateRects(const ClipRectsContext&,
const FragmentData*,
- const LayoutRect* paint_dirty_rect,
+ const CullRect* cull_rect,
LayoutRect& layer_bounds,
ClipRect& background_rect,
ClipRect& foreground_rect,
@@ -232,7 +231,7 @@ class CORE_EXPORT PaintLayerClipper {
ALWAYS_INLINE void CalculateRectsWithGeometryMapper(
const ClipRectsContext&,
const FragmentData&,
- const LayoutRect* paint_dirty_rect,
+ const CullRect* cull_rect,
LayoutRect& layer_bounds,
ClipRect& background_rect,
ClipRect& foreground_rect,
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper_test.cc
index df01f76103e..31723b02f8d 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_clipper_test.cc
@@ -10,8 +10,8 @@
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -20,12 +20,12 @@ class PaintLayerClipperTest : public RenderingTest {
PaintLayerClipperTest() : RenderingTest(EmptyLocalFrameClient::Create()) {}
void SetUp() override {
- LayoutTestSupport::SetMockThemeEnabledForTest(true);
+ WebTestSupport::SetMockThemeEnabledForTest(true);
RenderingTest::SetUp();
}
void TearDown() override {
- LayoutTestSupport::SetMockThemeEnabledForTest(false);
+ WebTestSupport::SetMockThemeEnabledForTest(false);
RenderingTest::TearDown();
}
};
@@ -877,10 +877,6 @@ TEST_F(PaintLayerClipperTest, ScrollbarClipBehaviorParent) {
PaintLayer* parent_paint_layer =
ToLayoutBoxModelObject(parent->GetLayoutObject())->Layer();
- Element* child = GetDocument().getElementById("child");
- PaintLayer* child_paint_layer =
- ToLayoutBoxModelObject(child->GetLayoutObject())->Layer();
-
ClipRectsContext context(
parent_paint_layer,
&parent_paint_layer->GetLayoutObject().FirstFragment(),
@@ -890,7 +886,7 @@ TEST_F(PaintLayerClipperTest, ScrollbarClipBehaviorParent) {
ClipRect background_rect, foreground_rect;
parent_paint_layer->Clipper(PaintLayer::kUseGeometryMapper)
.CalculateRects(context,
- &child_paint_layer->GetLayoutObject().FirstFragment(),
+ &parent_paint_layer->GetLayoutObject().FirstFragment(),
nullptr, layer_bounds, background_rect, foreground_rect);
// Only the foreground is clipped by the scrollbar size, because we
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.cc
index fe82fe74207..aaca470e4d1 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.cc
@@ -6,6 +6,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
@@ -38,12 +39,11 @@ static inline bool ShouldSuppressPaintingLayer(const PaintLayer& layer) {
}
void PaintLayerPainter::Paint(GraphicsContext& context,
- const LayoutRect& damage_rect,
+ const CullRect& cull_rect,
const GlobalPaintFlags global_paint_flags,
PaintLayerFlags paint_flags) {
- PaintLayerPaintingInfo painting_info(
- &paint_layer_, LayoutRect(EnclosingIntRect(damage_rect)),
- global_paint_flags, LayoutSize());
+ PaintLayerPaintingInfo painting_info(&paint_layer_, cull_rect,
+ global_paint_flags, LayoutSize());
if (!paint_layer_.PaintsIntoOwnOrGroupedBacking(global_paint_flags))
Paint(context, painting_info, paint_flags);
}
@@ -100,6 +100,12 @@ PaintResult PaintLayerPainter::Paint(
GraphicsContext& context,
const PaintLayerPaintingInfo& painting_info,
PaintLayerFlags paint_flags) {
+ if (paint_layer_.GetLayoutObject().PaintBlockedByDisplayLock())
+ return kFullyPainted;
+ // TODO(vmpstr): This should be called after paint succeeds, but due to
+ // multiple early outs this is more convenient. We should use RAII here.
+ paint_layer_.GetLayoutObject().NotifyDisplayLockDidPaint();
+
if (paint_layer_.GetLayoutObject().GetFrameView()->ShouldThrottleRendering())
return kFullyPainted;
@@ -195,41 +201,28 @@ static bool ShouldCreateSubsequence(const PaintLayer& paint_layer,
static bool ShouldRepaintSubsequence(
PaintLayer& paint_layer,
- const PaintLayerPaintingInfo& painting_info,
- ShouldRespectOverflowClipType respect_overflow_clip) {
- bool needs_repaint = false;
-
- // We should set shouldResetEmptyPaintPhaseFlags if some previously unpainted
- // objects may begin to be painted, causing a previously empty paint phase to
- // become non-empty.
-
+ const PaintLayerPaintingInfo& painting_info) {
// Repaint subsequence if the layer is marked for needing repaint.
- // We don't set needsResetEmptyPaintPhase here, but clear the empty paint
- // phase flags in PaintLayer::setNeedsPaintPhaseXXX(), to ensure that we won't
- // clear previousPaintPhaseXXXEmpty flags when unrelated things changed which
- // won't cause the paint phases to become non-empty.
if (paint_layer.NeedsRepaint())
- needs_repaint = true;
+ return true;
- // Repaint if previously the layer might be clipped by paintDirtyRect and
- // paintDirtyRect changes.
- if ((paint_layer.PreviousPaintResult() == kMayBeClippedByPaintDirtyRect ||
+ // Repaint if previously the layer may be clipped by cull rect, and cull rect
+ // changes.
+ if ((paint_layer.PreviousPaintResult() == kMayBeClippedByCullRect ||
// When PaintUnderInvalidationChecking is enabled, always repaint the
// subsequence when the paint rect changes because we will strictly match
// new and cached subsequences. Normally we can reuse the cached fully
// painted subsequence even if we would partially paint this time.
RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) &&
- paint_layer.PreviousPaintDirtyRect() != painting_info.paint_dirty_rect) {
- needs_repaint = true;
- }
- paint_layer.SetPreviousPaintDirtyRect(painting_info.paint_dirty_rect);
+ paint_layer.PreviousCullRect() != painting_info.cull_rect)
+ return true;
- return needs_repaint;
+ return false;
}
-static bool ShouldUseInfiniteDirtyRect(const GraphicsContext& context,
- const PaintLayer& layer,
- PaintLayerPaintingInfo& painting_info) {
+static bool ShouldUseInfiniteCullRect(const GraphicsContext& context,
+ const PaintLayer& layer,
+ PaintLayerPaintingInfo& painting_info) {
// Cull rects and clips can't be propagated across a filter which moves
// pixels, since the input of the filter may be outside the cull rect /
// clips yet still result in painted output.
@@ -247,12 +240,25 @@ static bool ShouldUseInfiniteDirtyRect(const GraphicsContext& context,
// 2) Complexity: Difficulty updating clips when ancestor transforms
// change.
// For these reasons, we use an infinite dirty rect here.
- if (layer.PaintsWithTransform(painting_info.GetGlobalPaintFlags())) {
- // The reasons don't apply for printing though, because when we enter and
- // leaving printing mode, full invalidations occur.
- return !context.Printing();
- }
+ if (layer.PaintsWithTransform(painting_info.GetGlobalPaintFlags()) &&
+ // The reasons don't apply for printing though, because when we enter and
+ // leaving printing mode, full invalidations occur.
+ !context.Printing())
+ return true;
+
+ return false;
+}
+static bool IsMainFrameNotClippingContents(const PaintLayer& layer) {
+ // If MainFrameClipsContent is false which means that WebPreferences::
+ // record_whole_document is true, we should not cull the scrolling contents
+ // of the main frame.
+ if (layer.GetLayoutObject().IsLayoutView()) {
+ const auto* frame = layer.GetLayoutObject().GetFrame();
+ if (frame && frame->IsMainFrame() &&
+ !frame->GetSettings()->GetMainFrameClipsContent())
+ return true;
+ }
return false;
}
@@ -262,44 +268,70 @@ void PaintLayerPainter::AdjustForPaintProperties(
PaintLayerFlags& paint_flags) {
const auto& first_fragment = paint_layer_.GetLayoutObject().FirstFragment();
- bool is_using_infinite_dirty_rect = painting_info.paint_dirty_rect ==
- LayoutRect(LayoutRect::InfiniteIntRect());
- bool should_use_infinite_dirty_rect =
- ShouldUseInfiniteDirtyRect(context, paint_layer_, painting_info);
- if (!is_using_infinite_dirty_rect && should_use_infinite_dirty_rect) {
- painting_info.paint_dirty_rect = LayoutRect(LayoutRect::InfiniteIntRect());
- is_using_infinite_dirty_rect = true;
+ bool is_main_frame_not_clipping_contents =
+ IsMainFrameNotClippingContents(paint_layer_);
+ bool should_use_infinite_cull_rect =
+ is_main_frame_not_clipping_contents ||
+ ShouldUseInfiniteCullRect(context, paint_layer_, painting_info);
+ if (should_use_infinite_cull_rect) {
+ painting_info.cull_rect = CullRect::Infinite();
+ // Avoid clipping during CollectFragments.
+ if (is_main_frame_not_clipping_contents)
+ paint_flags |= kPaintLayerPaintingOverflowContents;
}
if (painting_info.root_layer == &paint_layer_)
return;
- const auto& first_root_fragment =
- painting_info.root_layer->GetLayoutObject().FirstFragment();
- bool transform_changed =
- first_root_fragment.LocalBorderBoxProperties().Transform() !=
- first_fragment.LocalBorderBoxProperties().Transform();
-
- // Will use the current layer as the new root layer if the layer requires
- // infinite dirty rect or has different transform space from the current
- // root layer.
- if (!should_use_infinite_dirty_rect && !transform_changed)
- return;
-
- if (!is_using_infinite_dirty_rect && transform_changed) {
- // painting_info.paint_dirty_rect is currently in
- // |painting_info.root_layer|'s pixel-snapped border box space. We need to
- // adjust it into |paint_layer_|'s space.
- // This handles the following cases:
+ if (!should_use_infinite_cull_rect) {
+ // painting_info.cull_rect is currently in |painting_info.root_layer|'s
+ // pixel-snapped border box space. We need to adjust it into
+ // |paint_layer_|'s space. This handles the following cases:
// - The current layer has PaintOffsetTranslation;
// - The current layer's transform state escapes the root layers contents
// transform, e.g. a fixed-position layer;
// - Scroll offsets.
- first_root_fragment.MapRectToFragment(first_fragment,
- painting_info.paint_dirty_rect);
+ const auto& first_root_fragment =
+ painting_info.root_layer->GetLayoutObject().FirstFragment();
+ const auto* source_transform =
+ first_root_fragment.LocalBorderBoxProperties().Transform();
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() &&
+ IsMainFrameNotClippingContents(*painting_info.root_layer)) {
+ // Use PostScrollTranslation as the source transform to avoid clipping of
+ // the scrolling contents in CullRect::ApplyTransforms().
+ source_transform = first_root_fragment.PostScrollTranslation();
+ }
+ const auto* destination_transform =
+ first_fragment.LocalBorderBoxProperties().Transform();
+ if (source_transform == destination_transform)
+ return;
+
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ auto& cull_rect = painting_info.cull_rect;
+ // CullRect::ApplyTransforms() requires the cull rect in the source
+ // transform space. Convert cull_rect from the root layer's local space.
+ cull_rect.MoveBy(RoundedIntPoint(first_root_fragment.PaintOffset()));
+ base::Optional<CullRect> old_cull_rect;
+ if (!paint_layer_.NeedsRepaint()) {
+ old_cull_rect = paint_layer_.PreviousCullRect();
+ // Convert old_cull_rect into the layer's transform space.
+ old_cull_rect->MoveBy(RoundedIntPoint(first_fragment.PaintOffset()));
+ }
+ cull_rect.ApplyTransforms(source_transform, destination_transform,
+ old_cull_rect);
+ // Convert cull_rect from the layer's transform space to the layer's local
+ // space.
+ cull_rect.MoveBy(-RoundedIntPoint(first_fragment.PaintOffset()));
+ } else if (!painting_info.cull_rect.IsInfinite()) {
+ auto rect = painting_info.cull_rect.Rect();
+ first_root_fragment.MapRectToFragment(first_fragment, rect);
+ painting_info.cull_rect = CullRect(rect);
+ }
}
- // Make the current layer the new root layer.
+ // We reach here if the layer requires infinite cull rect or has different
+ // transform space from the current root layer. Use the current layer as
+ // the new root layer.
painting_info.root_layer = &paint_layer_;
// These flags no longer apply for the new root layer.
paint_flags &= ~kPaintLayerPaintingSkipRootBackground;
@@ -317,7 +349,9 @@ PaintResult PaintLayerPainter::PaintLayerContents(
GraphicsContext& context,
const PaintLayerPaintingInfo& painting_info_arg,
PaintLayerFlags paint_flags_arg) {
- PaintLayerFlags paint_flags = paint_flags_arg;
+ DCHECK(paint_layer_.IsSelfPaintingLayer() ||
+ paint_layer_.HasSelfPaintingLayerDescendant());
+
PaintResult result = kFullyPainted;
if (paint_layer_.GetLayoutObject().GetFrameView()->ShouldThrottleRendering())
@@ -331,12 +365,13 @@ PaintResult PaintLayerPainter::PaintLayerContents(
// TODO(crbug.com/848056): This can happen e.g. when we paint a filter
// referencing a SVG foreign object through feImage, especially when there
// is circular references. Should find a better solution.
- paint_layer_.SetPreviousPaintDirtyRect(LayoutRect());
- return kMayBeClippedByPaintDirtyRect;
+ paint_layer_.SetPreviousCullRect(CullRect());
+ return kMayBeClippedByCullRect;
}
- DCHECK(paint_layer_.IsSelfPaintingLayer() ||
- paint_layer_.HasSelfPaintingLayerDescendant());
+ PaintLayerFlags paint_flags = paint_flags_arg;
+ PaintLayerPaintingInfo painting_info = painting_info_arg;
+ AdjustForPaintProperties(context, painting_info, paint_flags);
bool is_self_painting_layer = paint_layer_.IsSelfPaintingLayer();
bool is_painting_overlay_scrollbars =
@@ -365,21 +400,17 @@ PaintResult PaintLayerPainter::PaintLayerContents(
LayoutSize subpixel_accumulation =
paint_layer_.GetCompositingState() == kPaintsIntoOwnBacking
? paint_layer_.SubpixelAccumulation()
- : painting_info_arg.sub_pixel_accumulation;
-
- PaintLayerPaintingInfo painting_info = painting_info_arg;
- AdjustForPaintProperties(context, painting_info, paint_flags);
+ : painting_info.sub_pixel_accumulation;
ShouldRespectOverflowClipType respect_overflow_clip =
ShouldRespectOverflowClip(paint_flags, paint_layer_.GetLayoutObject());
bool should_create_subsequence = ShouldCreateSubsequence(
- paint_layer_, context, painting_info_arg, paint_flags);
+ paint_layer_, context, painting_info, paint_flags);
base::Optional<SubsequenceRecorder> subsequence_recorder;
if (should_create_subsequence) {
- if (!ShouldRepaintSubsequence(paint_layer_, painting_info,
- respect_overflow_clip) &&
+ if (!ShouldRepaintSubsequence(paint_layer_, painting_info) &&
SubsequenceRecorder::UseCachedSubsequenceIfPossible(context,
paint_layer_)) {
return paint_layer_.PreviousPaintResult();
@@ -393,8 +424,8 @@ PaintResult PaintLayerPainter::PaintLayerContents(
offset_from_root.Move(subpixel_accumulation);
LayoutRect bounds = paint_layer_.PhysicalBoundingBox(offset_from_root);
- if (!painting_info.paint_dirty_rect.Contains(bounds))
- result = kMayBeClippedByPaintDirtyRect;
+ if (!LayoutRect(painting_info.cull_rect.Rect()).Contains(bounds))
+ result = kMayBeClippedByCullRect;
// These helpers output clip and compositing operations using a RAII pattern.
// Stack-allocated-varibles are destructed in the reverse order of
@@ -436,7 +467,7 @@ PaintResult PaintLayerPainter::PaintLayerContents(
// clipping container. This handles nested border radius by including
// all of them in the mask.
//
- // The paint rect is in this layer's space, so convert it to the clipper's
+ // The cull rect is in this layer's space, so convert it to the clipper's
// layer's space. The root_layer is also changed to the clipper's layer to
// simplify coordinate system adjustments. The change to root_layer must
// persist to correctly record the clips.
@@ -445,22 +476,24 @@ PaintResult PaintLayerPainter::PaintLayerContents(
local_painting_info.root_layer = paint_layer_for_fragments;
paint_layer_.ConvertToLayerCoords(local_painting_info.root_layer,
offset_to_clipper);
- local_painting_info.paint_dirty_rect.MoveBy(offset_to_clipper);
+ LayoutRect new_cull_rect(local_painting_info.cull_rect.Rect());
+ new_cull_rect.MoveBy(offset_to_clipper);
+ local_painting_info.cull_rect = CullRect(EnclosingIntRect(new_cull_rect));
// Overflow clip of the compositing container is irrelevant.
respect_overflow_clip = kIgnoreOverflowClip;
}
paint_layer_for_fragments->CollectFragments(
layer_fragments, local_painting_info.root_layer,
- &local_painting_info.paint_dirty_rect,
- kIgnorePlatformOverlayScrollbarSize, respect_overflow_clip,
- &offset_from_root, local_painting_info.sub_pixel_accumulation);
+ &local_painting_info.cull_rect, kIgnorePlatformOverlayScrollbarSize,
+ respect_overflow_clip, &offset_from_root,
+ local_painting_info.sub_pixel_accumulation);
// PaintLayer::CollectFragments depends on the paint dirty rect in
// complicated ways. For now, always assume a partially painted output
// for fragmented content.
if (layer_fragments.size() > 1)
- result = kMayBeClippedByPaintDirtyRect;
+ result = kMayBeClippedByCullRect;
if (paint_flags & kPaintLayerPaintingAncestorClippingMaskPhase) {
// Fragment offsets have been computed in the clipping container's
@@ -477,7 +510,7 @@ PaintResult PaintLayerPainter::PaintLayerContents(
should_paint_content = AtLeastOneFragmentIntersectsDamageRect(
layer_fragments, local_painting_info, paint_flags, offset_from_root);
if (!should_paint_content)
- result = kMayBeClippedByPaintDirtyRect;
+ result = kMayBeClippedByCullRect;
}
}
@@ -533,8 +566,8 @@ PaintResult PaintLayerPainter::PaintLayerContents(
paint_layer_, DisplayItem::kLayerChunkNegativeZOrderChildren);
}
if (PaintChildren(kNegativeZOrderChildren, context, painting_info,
- paint_flags) == kMayBeClippedByPaintDirtyRect)
- result = kMayBeClippedByPaintDirtyRect;
+ paint_flags) == kMayBeClippedByCullRect)
+ result = kMayBeClippedByCullRect;
}
if (should_paint_own_contents) {
@@ -555,9 +588,8 @@ PaintResult PaintLayerPainter::PaintLayerContents(
DisplayItem::kLayerChunkNormalFlowAndPositiveZOrderChildren);
}
if (PaintChildren(kNormalFlowChildren | kPositiveZOrderChildren, context,
- painting_info,
- paint_flags) == kMayBeClippedByPaintDirtyRect)
- result = kMayBeClippedByPaintDirtyRect;
+ painting_info, paint_flags) == kMayBeClippedByCullRect)
+ result = kMayBeClippedByCullRect;
}
if (should_paint_overlay_scrollbars) {
@@ -629,8 +661,8 @@ PaintResult PaintLayerPainter::PaintLayerContents(
}
}
- if (subsequence_recorder)
- paint_layer_.SetPreviousPaintResult(result);
+ paint_layer_.SetPreviousPaintResult(result);
+ paint_layer_.SetPreviousCullRect(local_painting_info.cull_rect);
return result;
}
@@ -698,8 +730,8 @@ PaintResult PaintLayerPainter::PaintChildren(
continue;
if (PaintLayerPainter(*child).Paint(context, painting_info, paint_flags) ==
- kMayBeClippedByPaintDirtyRect)
- result = kMayBeClippedByPaintDirtyRect;
+ kMayBeClippedByCullRect)
+ result = kMayBeClippedByCullRect;
}
return result;
@@ -947,14 +979,13 @@ void PaintLayerPainter::PaintChildClippingMaskForFragments(
void PaintLayerPainter::PaintOverlayScrollbars(
GraphicsContext& context,
- const LayoutRect& damage_rect,
+ const CullRect& cull_rect,
const GlobalPaintFlags paint_flags) {
if (!paint_layer_.ContainsDirtyOverlayScrollbars())
return;
- PaintLayerPaintingInfo painting_info(
- &paint_layer_, LayoutRect(EnclosingIntRect(damage_rect)), paint_flags,
- LayoutSize());
+ PaintLayerPaintingInfo painting_info(&paint_layer_, cull_rect, paint_flags,
+ LayoutSize());
Paint(context, painting_info, kPaintLayerPaintingOverlayScrollbars);
paint_layer_.SetContainsDirtyOverlayScrollbars(false);
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.h
index e1ca59231fb..4c39e007f2b 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_painter.h
@@ -13,6 +13,7 @@
namespace blink {
+class CullRect;
class ClipRect;
class ComputedStyle;
class DisplayItemClient;
@@ -30,11 +31,11 @@ class CORE_EXPORT PaintLayerPainter {
public:
PaintLayerPainter(PaintLayer& paint_layer) : paint_layer_(paint_layer) {}
- // The Paint() method paints the layers that intersect the damage rect from
+ // The Paint() method paints the layers that intersect the cull rect from
// back to front. paint() assumes that the caller will clip to the bounds of
// damageRect if necessary.
void Paint(GraphicsContext&,
- const LayoutRect& damage_rect,
+ const CullRect&,
const GlobalPaintFlags = kGlobalPaintNormalPhase,
PaintLayerFlags = 0);
// Paint() assumes that the caller will clip to the bounds of the painting
@@ -49,7 +50,7 @@ class CORE_EXPORT PaintLayerPainter {
PaintLayerFlags);
void PaintOverlayScrollbars(GraphicsContext&,
- const LayoutRect& damage_rect,
+ const CullRect&,
const GlobalPaintFlags);
// Returns true if the painted output of this PaintLayer and its children is
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_painter_test.cc
index 7c9d48f0e23..ccafe4bd544 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_painter_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
using testing::ElementsAre;
+using testing::UnorderedElementsAre;
namespace blink {
@@ -28,7 +29,7 @@ class PaintLayerPainterTest : public PaintControllerPaintTest {
PaintLayer* target_layer =
ToLayoutBox(GetLayoutObjectByElementId(element_name))->Layer();
- PaintLayerPaintingInfo painting_info(nullptr, LayoutRect(),
+ PaintLayerPaintingInfo painting_info(nullptr, CullRect(),
kGlobalPaintNormalPhase, LayoutSize());
bool invisible =
PaintLayerPainter(*target_layer)
@@ -80,36 +81,30 @@ TEST_P(PaintLayerPainterTest, CachedSubsequence) {
auto& content2 = *GetLayoutObjectByElementId("content2");
auto& filler2 = *GetLayoutObjectByElementId("filler2");
- const auto& view_display_item_client = ViewBackgroundClient();
- const auto& view_chunk_client =
- RuntimeEnabledFeatures::SlimmingPaintV2Enabled()
- ? *GetLayoutView().Layer()
- : view_display_item_client;
-
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 7,
- TestDisplayItem(view_display_item_client, kDocumentBackgroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(filler1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(filler2, kBackgroundType));
+ const auto& view_client = ViewScrollingBackgroundClient();
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&container1),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&content1),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&filler1),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&container2),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&content2),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&filler2),
+ kBackgroundType)));
auto* container1_layer = ToLayoutBoxModelObject(container1).Layer();
auto* filler1_layer = ToLayoutBoxModelObject(filler1).Layer();
auto* container2_layer = ToLayoutBoxModelObject(container2).Layer();
auto* filler2_layer = ToLayoutBoxModelObject(filler2).Layer();
- auto other_chunk_state = GetLayoutView().FirstFragment().ContentsProperties();
- auto view_chunk_state = other_chunk_state;
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- view_chunk_state =
- GetLayoutView().FirstFragment().LocalBorderBoxProperties();
- }
+ auto chunk_state = GetLayoutView().FirstFragment().ContentsProperties();
- auto view_chunk_type = RuntimeEnabledFeatures::SlimmingPaintV2Enabled()
- ? DisplayItem::kLayerChunkBackground
- : kDocumentBackgroundType;
+ auto view_chunk_type = kDocumentBackgroundType;
auto chunk_background_type = DisplayItem::kLayerChunkBackground;
auto chunk_foreground_type =
DisplayItem::kLayerChunkNormalFlowAndPositiveZOrderChildren;
@@ -119,43 +114,35 @@ TEST_P(PaintLayerPainterTest, CachedSubsequence) {
auto check_chunks = [&]() {
// Check that new paint chunks were forced for |container1| and
// |container2|.
- const auto& paint_chunks =
- RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(paint_chunks.size(), 7u);
- EXPECT_EQ(
- paint_chunks[0],
- PaintChunk(0, 1, PaintChunk::Id(view_chunk_client, view_chunk_type),
- view_chunk_state));
- EXPECT_EQ(paint_chunks[1], PaintChunk(1, 2,
- PaintChunk::Id(*container1_layer,
- chunk_background_type),
- other_chunk_state));
- EXPECT_EQ(paint_chunks[2], PaintChunk(2, 3,
- PaintChunk::Id(*container1_layer,
- chunk_foreground_type),
- other_chunk_state));
- EXPECT_EQ(
- paint_chunks[3],
- PaintChunk(3, 4, PaintChunk::Id(*filler1_layer, filler_chunk_type),
- other_chunk_state));
- EXPECT_EQ(paint_chunks[4], PaintChunk(4, 5,
- PaintChunk::Id(*container2_layer,
- chunk_background_type),
- other_chunk_state));
- EXPECT_EQ(paint_chunks[5], PaintChunk(5, 6,
- PaintChunk::Id(*container2_layer,
- chunk_foreground_type),
- other_chunk_state));
- EXPECT_EQ(
- paint_chunks[6],
- PaintChunk(6, 7, PaintChunk::Id(*filler2_layer, filler_chunk_type),
- other_chunk_state));
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(0, 1, PaintChunk::Id(view_client, view_chunk_type),
+ chunk_state),
+ IsPaintChunk(
+ 1, 2, PaintChunk::Id(*container1_layer, chunk_background_type),
+ chunk_state),
+ IsPaintChunk(
+ 2, 3, PaintChunk::Id(*container1_layer, chunk_foreground_type),
+ chunk_state),
+ IsPaintChunk(3, 4,
+ PaintChunk::Id(*filler1_layer, filler_chunk_type),
+ chunk_state),
+ IsPaintChunk(
+ 4, 5, PaintChunk::Id(*container2_layer, chunk_background_type),
+ chunk_state),
+ IsPaintChunk(
+ 5, 6, PaintChunk::Id(*container2_layer, chunk_foreground_type),
+ chunk_state),
+ IsPaintChunk(6, 7,
+ PaintChunk::Id(*filler2_layer, filler_chunk_type),
+ chunk_state)));
};
check_chunks();
ToHTMLElement(content1.GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
"position: absolute; width: 100px; height: 100px; "
"background-color: green");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
@@ -164,26 +151,27 @@ TEST_P(PaintLayerPainterTest, CachedSubsequence) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 7,
- TestDisplayItem(view_display_item_client, kDocumentBackgroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(filler1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(filler2, kBackgroundType));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&container1),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&content1),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&filler1),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&container2),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&content2),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromLayoutObject(&filler2),
+ kBackgroundType)));
// We should still have the paint chunks forced by the cached subsequences.
check_chunks();
}
-TEST_P(PaintLayerPainterTest, CachedSubsequenceOnInterestRectChange) {
- // TODO(wangxianzhu): SPv2 deals with interest rect differently, so disable
- // this test for SPv2 temporarily.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
+TEST_P(PaintLayerPainterTest, CachedSubsequenceOnCullRectChange) {
SetBodyInnerHTML(R"HTML(
<div id='container1' style='position: relative; z-index: 1;
width: 200px; height: 200px; background-color: blue'>
@@ -206,44 +194,42 @@ TEST_P(PaintLayerPainterTest, CachedSubsequenceOnInterestRectChange) {
)HTML");
InvalidateAll(RootPaintController());
- LayoutObject& container1 =
- *GetDocument().getElementById("container1")->GetLayoutObject();
- LayoutObject& content1 =
- *GetDocument().getElementById("content1")->GetLayoutObject();
- LayoutObject& container2 =
- *GetDocument().getElementById("container2")->GetLayoutObject();
- LayoutObject& content2a =
- *GetDocument().getElementById("content2a")->GetLayoutObject();
- LayoutObject& content2b =
- *GetDocument().getElementById("content2b")->GetLayoutObject();
- LayoutObject& container3 =
- *GetDocument().getElementById("container3")->GetLayoutObject();
- LayoutObject& content3 =
- *GetDocument().getElementById("content3")->GetLayoutObject();
+ DisplayItemClient& container1 =
+ *GetDisplayItemClientFromElementId("container1");
+ DisplayItemClient& content1 = *GetDisplayItemClientFromElementId("content1");
+ DisplayItemClient& container2 =
+ *GetDisplayItemClientFromElementId("container2");
+ DisplayItemClient& content2a =
+ *GetDisplayItemClientFromElementId("content2a");
+ DisplayItemClient& content2b =
+ *GetDisplayItemClientFromElementId("content2b");
+ DisplayItemClient& container3 =
+ *GetDisplayItemClientFromElementId("container3");
+ DisplayItemClient& content3 = *GetDisplayItemClientFromElementId("content3");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- IntRect interest_rect(0, 0, 400, 300);
- Paint(&interest_rect);
+ IntRect cull_rect(0, 0, 400, 300);
+ Paint(&cull_rect);
- const auto& background_display_item_client = ViewBackgroundClient();
+ const auto& background_display_item_client = ViewScrollingBackgroundClient();
// Container1 is fully in the interest rect;
// Container2 is partly (including its stacking chidren) in the interest rect;
// Content2b is out of the interest rect and output nothing;
// Container3 is partly in the interest rect.
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 7,
- TestDisplayItem(background_display_item_client, kDocumentBackgroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2a, kBackgroundType),
- TestDisplayItem(container3, kBackgroundType),
- TestDisplayItem(content3, kBackgroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&background_display_item_client,
+ kDocumentBackgroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2a, kBackgroundType),
+ IsSameId(&container3, kBackgroundType),
+ IsSameId(&content3, kBackgroundType)));
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- IntRect new_interest_rect(0, 100, 300, 1000);
- EXPECT_TRUE(PaintWithoutCommit(&new_interest_rect));
+ IntRect new_cull_rect(0, 100, 300, 1000);
+ EXPECT_TRUE(PaintWithoutCommit(&new_cull_rect));
// Container1 becomes partly in the interest rect, but uses cached subsequence
// because it was fully painted before;
@@ -255,18 +241,18 @@ TEST_P(PaintLayerPainterTest, CachedSubsequenceOnInterestRectChange) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(background_display_item_client, kDocumentBackgroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2a, kBackgroundType),
- TestDisplayItem(content2b, kBackgroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&background_display_item_client,
+ kDocumentBackgroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2a, kBackgroundType),
+ IsSameId(&content2b, kBackgroundType)));
}
TEST_P(PaintLayerPainterTest,
- CachedSubsequenceOnInterestRectChangeUnderInvalidationChecking) {
+ CachedSubsequenceOnCullRectChangeUnderInvalidationChecking) {
ScopedPaintUnderInvalidationCheckingForTest under_invalidation_checking(true);
SetBodyInnerHTML(R"HTML(
@@ -279,18 +265,18 @@ TEST_P(PaintLayerPainterTest,
// |target| will be fully painted.
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- IntRect interest_rect(0, 0, 400, 300);
- Paint(&interest_rect);
+ IntRect cull_rect(0, 0, 400, 300);
+ Paint(&cull_rect);
// |target| will be partially painted. Should not trigger under-invalidation
// checking DCHECKs.
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- IntRect new_interest_rect(0, 100, 300, 1000);
- Paint(&new_interest_rect);
+ IntRect new_cull_rect(0, 100, 300, 1000);
+ Paint(&new_cull_rect);
}
TEST_P(PaintLayerPainterTest,
- CachedSubsequenceOnStyleChangeWithInterestRectClipping) {
+ CachedSubsequenceOnStyleChangeWithCullRectClipping) {
SetBodyInnerHTML(R"HTML(
<div id='container1' style='position: relative; z-index: 1;
width: 200px; height: 200px; background-color: blue'>
@@ -304,45 +290,163 @@ TEST_P(PaintLayerPainterTest,
</div>
)HTML");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- // PaintResult of all subsequences will be MayBeClippedByPaintDirtyRect.
- IntRect interest_rect(0, 0, 50, 300);
- Paint(&interest_rect);
-
- LayoutObject& container1 =
- *GetDocument().getElementById("container1")->GetLayoutObject();
- LayoutObject& content1 =
- *GetDocument().getElementById("content1")->GetLayoutObject();
- LayoutObject& container2 =
- *GetDocument().getElementById("container2")->GetLayoutObject();
- LayoutObject& content2 =
- *GetDocument().getElementById("content2")->GetLayoutObject();
-
- const auto& background_display_item_client = ViewBackgroundClient();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 5,
- TestDisplayItem(background_display_item_client, kDocumentBackgroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType));
-
- ToHTMLElement(content1.GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ // PaintResult of all subsequences will be MayBeClippedByCullRect.
+ IntRect cull_rect(0, 0, 50, 300);
+ Paint(&cull_rect);
+
+ DisplayItemClient& container1 =
+ *GetDisplayItemClientFromElementId("container1");
+ DisplayItemClient& content1 = *GetDisplayItemClientFromElementId("content1");
+ DisplayItemClient& container2 =
+ *GetDisplayItemClientFromElementId("container2");
+ DisplayItemClient& content2 = *GetDisplayItemClientFromElementId("content2");
+
+ const auto& background_display_item_client = ViewScrollingBackgroundClient();
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&background_display_item_client,
+ kDocumentBackgroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType)));
+
+ ToHTMLElement(GetElementById("content1"))
+ ->setAttribute(html_names::kStyleAttr,
"position: absolute; width: 100px; height: 100px; "
"background-color: green");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- EXPECT_TRUE(PaintWithoutCommit(&interest_rect));
+ EXPECT_TRUE(PaintWithoutCommit(&cull_rect));
EXPECT_EQ(4, NumCachedNewItems());
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 5,
- TestDisplayItem(background_display_item_client, kDocumentBackgroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&background_display_item_client,
+ kDocumentBackgroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType)));
+}
+
+TEST_P(PaintLayerPainterTest, CachedSubsequenceRetainsPreviousPaintResult) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ html, body { height: 100%; margin: 0 }
+ ::-webkit-scrollbar { display:none }
+ </style>
+ <div id="target" style="height: 8000px; contain: paint">
+ <div id="content1" style="height: 100px; background: blue"></div>
+ <div style="height: 6000px"></div>
+ <div id="content2" style="height: 100px; background: blue"></div>
+ </div>
+ <div id="change" style="display: none"></div>
+ )HTML");
+
+ const auto* target_layer =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("target"))->Layer();
+ const auto* content1 = GetLayoutObjectByElementId("content1");
+ const auto* content2 = GetLayoutObjectByElementId("content2");
+ const auto& view_client = ViewScrollingBackgroundClient();
+ // |target| is partially painted.
+ EXPECT_EQ(kMayBeClippedByCullRect, target_layer->PreviousPaintResult());
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // SPv2 doesn't clip the cull rect by the scrolling contents rect, which
+ // doesn't affect painted results.
+ EXPECT_EQ(CullRect(IntRect(-4000, -4000, 8800, 8600)),
+ target_layer->PreviousCullRect());
+ // |content2| is out of the cull rect.
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(content1, kBackgroundType)));
+ // |target| created subsequence.
+ EXPECT_SUBSEQUENCE(*target_layer, 2, 3);
+ } else {
+ EXPECT_EQ(CullRect(IntRect(0, 0, 800, 4600)),
+ target_layer->PreviousCullRect());
+ // |content2| is out of the cull rect.
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(content1, kBackgroundType)));
+ // |target| created subsequence.
+ EXPECT_SUBSEQUENCE(*target_layer, 1, 2);
+ }
+
+ // Change something that triggers a repaint but |target| should use cached
+ // subsequence.
+ GetDocument().getElementById("change")->setAttribute(html_names::kStyleAttr,
+ "display: block");
+ GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
+ EXPECT_FALSE(target_layer->NeedsRepaint());
+ EXPECT_TRUE(PaintWithoutCommit());
+ EXPECT_EQ(2, NumCachedNewItems());
+ CommitAndFinishCycle();
+
+ // |target| is still partially painted.
+ EXPECT_EQ(kMayBeClippedByCullRect, target_layer->PreviousPaintResult());
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // SPv2 doens't clip the cull rect by the scrolling contents rect, which
+ // doesn't affect painted results.
+ EXPECT_EQ(CullRect(IntRect(-4000, -4000, 8800, 8600)),
+ target_layer->PreviousCullRect());
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(content1, kBackgroundType)));
+ // |target| still created subsequence (cached).
+ EXPECT_SUBSEQUENCE(*target_layer, 2, 3);
+ } else {
+ EXPECT_EQ(CullRect(IntRect(0, 0, 800, 4600)),
+ target_layer->PreviousCullRect());
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(content1, kBackgroundType)));
+ // |target| still created subsequence (cached).
+ EXPECT_SUBSEQUENCE(*target_layer, 1, 2);
+ }
+
+ // Scroll the view so that both |content1| and |content2| are in the interest
+ // rect.
+ GetLayoutView().GetScrollableArea()->SetScrollOffset(ScrollOffset(0, 3000),
+ kProgrammaticScroll);
+ GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
+ // Scrolling doesn't set NeedsRepaint flag. Change of paint dirty rect of
+ // a partially painted layer will trigger repaint.
+ EXPECT_FALSE(target_layer->NeedsRepaint());
+ EXPECT_TRUE(PaintWithoutCommit());
+ EXPECT_EQ(2, NumCachedNewItems());
+ CommitAndFinishCycle();
+
+ // |target| is still partially painted.
+ EXPECT_EQ(kMayBeClippedByCullRect, target_layer->PreviousPaintResult());
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // SPv2 doens't clip the cull rect by the scrolling contents rect, which
+ // doesn't affect painted results.
+ EXPECT_EQ(CullRect(IntRect(-4000, -1000, 8800, 8600)),
+ target_layer->PreviousCullRect());
+ // Painted result should include both |content1| and |content2|.
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(content1, kBackgroundType),
+ IsSameId(content2, kBackgroundType)));
+ // |target| still created subsequence (repainted).
+ EXPECT_SUBSEQUENCE(*target_layer, 2, 4);
+ } else {
+ EXPECT_EQ(CullRect(IntRect(0, 0, 800, 7600)),
+ target_layer->PreviousCullRect());
+ // Painted result should include both |content1| and |content2|.
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&view_client, kDocumentBackgroundType),
+ IsSameId(content1, kBackgroundType),
+ IsSameId(content2, kBackgroundType)));
+ // |target| still created subsequence (repainted).
+ EXPECT_SUBSEQUENCE(*target_layer, 1, 3);
+ }
}
TEST_P(PaintLayerPainterTest, PaintPhaseOutline) {
@@ -362,8 +466,8 @@ TEST_P(PaintLayerPainterTest, PaintPhaseOutline) {
LayoutObject& outline_div =
*GetDocument().getElementById("outline")->GetLayoutObject();
ToHTMLElement(outline_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_without_outline);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, style_without_outline);
+ UpdateAllLifecyclePhasesForTest();
LayoutBoxModelObject& self_painting_layer_object = *ToLayoutBoxModelObject(
GetDocument().getElementById("self-painting-layer")->GetLayoutObject());
@@ -383,9 +487,9 @@ TEST_P(PaintLayerPainterTest, PaintPhaseOutline) {
// Outline on the self-painting-layer node itself doesn't affect
// PaintPhaseDescendantOutlines.
ToHTMLElement(self_painting_layer_object.GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
"position: absolute; outline: 1px solid green");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(self_painting_layer.NeedsPaintPhaseDescendantOutlines());
EXPECT_FALSE(non_self_painting_layer.NeedsPaintPhaseDescendantOutlines());
EXPECT_TRUE(DisplayItemListContains(
@@ -395,7 +499,7 @@ TEST_P(PaintLayerPainterTest, PaintPhaseOutline) {
// needsPaintPhaseDescendantOutlines should be set when any descendant on the
// same layer has outline.
ToHTMLElement(outline_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_with_outline);
+ ->setAttribute(html_names::kStyleAttr, style_with_outline);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(self_painting_layer.NeedsPaintPhaseDescendantOutlines());
EXPECT_FALSE(non_self_painting_layer.NeedsPaintPhaseDescendantOutlines());
@@ -407,8 +511,8 @@ TEST_P(PaintLayerPainterTest, PaintPhaseOutline) {
// needsPaintPhaseDescendantOutlines should be reset when no outline is
// actually painted.
ToHTMLElement(outline_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_without_outline);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, style_without_outline);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(self_painting_layer.NeedsPaintPhaseDescendantOutlines());
}
@@ -429,8 +533,8 @@ TEST_P(PaintLayerPainterTest, PaintPhaseFloat) {
LayoutObject& float_div =
*GetDocument().getElementById("float")->GetLayoutObject();
ToHTMLElement(float_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_without_float);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, style_without_float);
+ UpdateAllLifecyclePhasesForTest();
LayoutBoxModelObject& self_painting_layer_object = *ToLayoutBoxModelObject(
GetDocument().getElementById("self-painting-layer")->GetLayoutObject());
@@ -450,7 +554,7 @@ TEST_P(PaintLayerPainterTest, PaintPhaseFloat) {
// needsPaintPhaseFloat should be set when any descendant on the same layer
// has float.
ToHTMLElement(float_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_with_float);
+ ->setAttribute(html_names::kStyleAttr, style_with_float);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(self_painting_layer.NeedsPaintPhaseFloat());
EXPECT_FALSE(non_self_painting_layer.NeedsPaintPhaseFloat());
@@ -462,8 +566,8 @@ TEST_P(PaintLayerPainterTest, PaintPhaseFloat) {
// needsPaintPhaseFloat should be reset when there is no float actually
// painted.
ToHTMLElement(float_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_without_float);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, style_without_float);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(self_painting_layer.NeedsPaintPhaseFloat());
}
@@ -478,7 +582,7 @@ TEST_P(PaintLayerPainterTest, PaintPhaseFloatUnderInlineLayer) {
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
LayoutObject& float_div =
*GetDocument().getElementById("float")->GetLayoutObject();
@@ -522,8 +626,8 @@ TEST_P(PaintLayerPainterTest, PaintPhaseBlockBackground) {
LayoutObject& background_div =
*GetDocument().getElementById("background")->GetLayoutObject();
ToHTMLElement(background_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_without_background);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, style_without_background);
+ UpdateAllLifecyclePhasesForTest();
LayoutBoxModelObject& self_painting_layer_object = *ToLayoutBoxModelObject(
GetDocument().getElementById("self-painting-layer")->GetLayoutObject());
@@ -544,9 +648,9 @@ TEST_P(PaintLayerPainterTest, PaintPhaseBlockBackground) {
// Background on the self-painting-layer node itself doesn't affect
// PaintPhaseDescendantBlockBackgrounds.
ToHTMLElement(self_painting_layer_object.GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
"position: absolute; background: green");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(self_painting_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
EXPECT_FALSE(
non_self_painting_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
@@ -557,7 +661,7 @@ TEST_P(PaintLayerPainterTest, PaintPhaseBlockBackground) {
// needsPaintPhaseDescendantBlockBackgrounds should be set when any descendant
// on the same layer has Background.
ToHTMLElement(background_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_with_background);
+ ->setAttribute(html_names::kStyleAttr, style_with_background);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(self_painting_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
EXPECT_FALSE(
@@ -570,8 +674,8 @@ TEST_P(PaintLayerPainterTest, PaintPhaseBlockBackground) {
// needsPaintPhaseDescendantBlockBackgrounds should be reset when no outline
// is actually painted.
ToHTMLElement(background_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, style_without_background);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, style_without_background);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(self_painting_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
}
@@ -599,8 +703,8 @@ TEST_P(PaintLayerPainterTest, PaintPhasesUpdateOnLayerAddition) {
EXPECT_TRUE(html_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
ToHTMLElement(layer_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr, "position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, "position: relative");
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(layer_div.HasLayer());
PaintLayer& layer = *layer_div.Layer();
ASSERT_TRUE(layer.IsSelfPaintingLayer());
@@ -635,9 +739,9 @@ TEST_P(PaintLayerPainterTest, PaintPhasesUpdateOnBecomingSelfPainting) {
ToHTMLElement(layer_div.GetNode())
->setAttribute(
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
"width: 100px; height: 100px; overflow: hidden; position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintLayer& layer = *layer_div.Layer();
ASSERT_TRUE(layer.IsSelfPaintingLayer());
EXPECT_TRUE(layer.NeedsPaintPhaseDescendantOutlines());
@@ -674,9 +778,9 @@ TEST_P(PaintLayerPainterTest, PaintPhasesUpdateOnBecomingNonSelfPainting) {
EXPECT_FALSE(html_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
ToHTMLElement(layer_div.GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
"width: 100px; height: 100px; overflow: hidden");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(layer.IsSelfPaintingLayer());
EXPECT_TRUE(html_layer.NeedsPaintPhaseDescendantOutlines());
EXPECT_TRUE(html_layer.NeedsPaintPhaseDescendantBlockBackgrounds());
@@ -721,9 +825,9 @@ TEST_P(PaintLayerPainterTest,
EXPECT_FALSE(layer.NeedsPaintPhaseDescendantBlockBackgrounds());
ToHTMLElement(table.GetNode())
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
"position: relative; border-collapse: collapse");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(layer.NeedsPaintPhaseDescendantBlockBackgrounds());
}
@@ -870,4 +974,303 @@ TEST_P(PaintLayerPainterTest,
ExpectPaintedOutputInvisible("target", false);
}
+using PaintLayerPainterTestSPv2 = PaintLayerPainterTest;
+
+INSTANTIATE_SPV2_TEST_CASE_P(PaintLayerPainterTestSPv2);
+
+TEST_P(PaintLayerPainterTestSPv2, SimpleCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target'
+ style='width: 200px; height: 200px; position: relative'>
+ </div>
+ )HTML");
+
+ EXPECT_EQ(IntRect(0, 0, 800, 600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, TallLayerCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target'
+ style='width: 200px; height: 10000px; position: relative'>
+ </div>
+ )HTML");
+
+ // Viewport rect (0, 0, 800, 600) expanded by 4000 for scrolling.
+ EXPECT_EQ(IntRect(-4000, -4000, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, WideLayerCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target'
+ style='width: 10000px; height: 200px; position: relative'>
+ </div>
+ )HTML");
+
+ // Same as TallLayerCullRect.
+ EXPECT_EQ(IntRect(-4000, -4000, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, TallScrolledLayerCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target' style='width: 200px; height: 10000px; position: relative'>
+ </div>
+ )HTML");
+
+ // Viewport rect (0, 0, 800, 600) expanded by 4000.
+ EXPECT_EQ(IntRect(-4000, -4000, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 6000),
+ kProgrammaticScroll);
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(IntRect(-4000, 2000, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 6500),
+ kProgrammaticScroll);
+ UpdateAllLifecyclePhasesForTest();
+ // Used the previous cull rect because the scroll amount is small.
+ EXPECT_EQ(IntRect(-4000, 2000, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 6600),
+ kProgrammaticScroll);
+ UpdateAllLifecyclePhasesForTest();
+ // Used new cull rect.
+ EXPECT_EQ(IntRect(-4000, 2600, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, WholeDocumentCullRect) {
+ GetDocument().GetSettings()->SetMainFrameClipsContent(false);
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ div { background: blue; }
+ ::-webkit-scrollbar { display: none; }
+ </style>
+ <div id='relative'
+ style='width: 200px; height: 10000px; position: relative'>
+ </div>
+ <div id='fixed' style='width: 200px; height: 200px; position: fixed'>
+ </div>
+ <div id='scroll' style='width: 200px; height: 200px; overflow: scroll'>
+ <div id='below-scroll' style='height: 5000px; position: relative'></div>
+ <div style='height: 200px'>Should not paint</div>
+ </div>
+ <div id='normal' style='width: 200px; height: 200px'></div>
+ )HTML");
+
+ // Viewport clipping is disabled.
+ EXPECT_TRUE(GetLayoutView().Layer()->PreviousCullRect().IsInfinite());
+ EXPECT_TRUE(
+ GetPaintLayerByElementId("relative")->PreviousCullRect().IsInfinite());
+ EXPECT_TRUE(
+ GetPaintLayerByElementId("fixed")->PreviousCullRect().IsInfinite());
+ EXPECT_TRUE(
+ GetPaintLayerByElementId("scroll")->PreviousCullRect().IsInfinite());
+
+ // Cull rect is normal for contents below scroll other than the viewport.
+ EXPECT_EQ(
+ IntRect(-4000, -4000, 8200, 8200),
+ GetPaintLayerByElementId("below-scroll")->PreviousCullRect().Rect());
+
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ UnorderedElementsAre(
+ IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(&ViewScrollingBackgroundClient(), kDocumentBackgroundType),
+ IsSameId(GetDisplayItemClientFromElementId("relative"),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromElementId("normal"),
+ kBackgroundType),
+ IsSameId(GetLayoutObjectByElementId("scroll"),
+ DisplayItem::kScrollHitTest),
+ IsSameId(GetDisplayItemClientFromElementId("scroll"),
+ kBackgroundType),
+ IsSameId(&ToLayoutBox(GetLayoutObjectByElementId("scroll"))
+ ->GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient(),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromElementId("below-scroll"),
+ kBackgroundType),
+ IsSameId(GetDisplayItemClientFromElementId("fixed"),
+ kBackgroundType)));
+}
+
+TEST_P(PaintLayerPainterTestSPv2, VerticalRightLeftWritingModeDocument) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ html { writing-mode: vertical-rl; }
+ body { margin: 0; }
+ </style>
+ <div id='target' style='width: 10000px; height: 200px; position: relative'>
+ </div>
+ )HTML");
+
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(
+ ScrollOffset(-5000, 0), kProgrammaticScroll);
+ UpdateAllLifecyclePhasesForTest();
+
+ // A scroll by -5000px is equivalent to a scroll by (10000 - 5000 - 800)px =
+ // 4200px in non-RTL mode. Expanding the resulting rect by 4000px in each
+ // direction yields this result.
+ EXPECT_EQ(IntRect(200, -4000, 8800, 8600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, ScaledCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 200px; height: 300px; overflow: scroll;
+ transform: scaleX(2) scaleY(0.5)'>
+ <div id='target' style='height: 400px; position: relative'></div>
+ </div>
+ )HTML");
+
+ // The scale doesn't affect the cull rect.
+ EXPECT_EQ(IntRect(-4000, -4000, 8200, 8300),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, ScaledAndRotatedCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 200px; height: 300px; overflow: scroll;
+ transform: scaleX(2) scaleY(0.5) rotateZ(45deg)'>
+ <div id='target' style='height: 400px; position: relative'></div>
+ </div>
+ )HTML");
+
+ // The scale and the rotation don't affect the cull rect.
+ EXPECT_EQ(IntRect(-4000, -4000, 8200, 8300),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, 3DRotated90DegreesCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 200px; height: 300px; overflow: scroll;
+ transform: rotateY(90deg)'>
+ <div id='target' style='height: 400px; position: relative'></div>
+ </div>
+ )HTML");
+
+ // It's rotated 90 degrees about the X axis, which means its visual content
+ // rect is empty, we fall back to the 4000px cull rect padding amount.
+ EXPECT_EQ(IntRect(-4000, -4000, 8200, 8300),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, 3DRotatedNear90DegreesCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 200px; height: 300px; overflow: scroll;
+ transform: rotateY(89.9999deg)'>
+ <div id='target' style='height: 400px; position: relative'></div>
+ </div>
+ )HTML");
+
+ // Because the layer is rotated to almost 90 degrees, floating-point error
+ // leads to a reverse-projected rect that is much much larger than the
+ // original layer size in certain dimensions. In such cases, we often fall
+ // back to the 4000px cull rect padding amount.
+ EXPECT_EQ(IntRect(-4000, -4000, 8200, 8300),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, PerspectiveCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target'
+ style='width: 100px; height: 100px; transform: perspective(1000px)'>
+ </div>
+ )HTML");
+
+ // Use infinite cull rect with perspective.
+ EXPECT_TRUE(
+ GetPaintLayerByElementId("target")->PreviousCullRect().IsInfinite());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, 3D45DegRotatedTallCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target'
+ style='width: 200px; height: 10000px; transform: rotateY(45deg)'>
+ </div>
+ )HTML");
+
+ // Use infinite cull rect with 3d transform.
+ EXPECT_TRUE(
+ GetPaintLayerByElementId("target")->PreviousCullRect().IsInfinite());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, FixedPositionCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='target' style='width: 1000px; height: 2000px;
+ position: fixed; top: 100px; left: 200px;'>
+ </div>
+ )HTML");
+
+ EXPECT_EQ(IntRect(0, 0, 800, 600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, LayerOffscreenNearCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 200px; height: 300px; overflow: scroll;
+ position: absolute; top: 3000px; left: 0px;'>
+ <div id='target' style='height: 500px; position: relative'></div>
+ </div>
+ )HTML");
+
+ EXPECT_EQ(IntRect(-4000, -4000, 8200, 8300),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, LayerOffscreenFarCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 200px; height: 300px; overflow: scroll;
+ position: absolute; top: 9000px'>
+ <div id='target' style='height: 500px; position: relative'></div>
+ </div>
+ )HTML");
+
+ // The layer is too far away from the viewport.
+ EXPECT_EQ(IntRect(),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, ScrollingLayerCullRect) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ div::-webkit-scrollbar { width: 5px; }
+ </style>
+ <div style='width: 200px; height: 200px; overflow: scroll'>
+ <div id='target'
+ style='width: 100px; height: 10000px; position: relative'>
+ </div>
+ </div>
+ )HTML");
+
+ // In screen space, the scroller is (8, 8, 195, 193) (because of overflow clip
+ // of 'target', scrollbar and root margin).
+ // Applying the viewport clip of the root has no effect because
+ // the clip is already small. Mapping it down into the graphics layer
+ // space yields (0, 0, 195, 193). This is then expanded by 4000px.
+ EXPECT_EQ(IntRect(-4000, -4000, 8195, 8193),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
+TEST_P(PaintLayerPainterTestSPv2, ClippedBigLayer) {
+ SetBodyInnerHTML(R"HTML(
+ <div style='width: 1px; height: 1px; overflow: hidden'>
+ <div id='target'
+ style='width: 10000px; height: 10000px; position: relative'>
+ </div>
+ </div>
+ )HTML");
+
+ // The viewport is not scrollable because of the clip, so the cull rect is
+ // just the viewport rect.
+ EXPECT_EQ(IntRect(0, 0, 800, 600),
+ GetPaintLayerByElementId("target")->PreviousCullRect().Rect());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_painting_info.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_painting_info.h
index 3c90598c7fe..bee6fa8e2eb 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_painting_info.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_painting_info.h
@@ -47,7 +47,7 @@
#include "base/logging.h"
#include "third_party/blink/renderer/core/paint/paint_phase.h"
-#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#if DCHECK_IS_ON()
@@ -88,20 +88,20 @@ struct PaintLayerPaintingInfo {
STACK_ALLOCATED();
public:
- PaintLayerPaintingInfo(PaintLayer* in_root_layer,
- const LayoutRect& in_dirty_rect,
+ PaintLayerPaintingInfo(PaintLayer* root_layer,
+ const CullRect& cull_rect,
GlobalPaintFlags global_paint_flags,
- const LayoutSize& in_sub_pixel_accumulation)
- : root_layer(in_root_layer),
- paint_dirty_rect(in_dirty_rect),
- sub_pixel_accumulation(in_sub_pixel_accumulation),
+ const LayoutSize& sub_pixel_accumulation)
+ : root_layer(root_layer),
+ cull_rect(cull_rect),
+ sub_pixel_accumulation(sub_pixel_accumulation),
global_paint_flags_(global_paint_flags) {}
GlobalPaintFlags GetGlobalPaintFlags() const { return global_paint_flags_; }
// TODO(jchaffraix): We should encapsulate all these fields.
const PaintLayer* root_layer;
- LayoutRect paint_dirty_rect; // relative to rootLayer;
+ CullRect cull_rect; // relative to rootLayer;
LayoutSize sub_pixel_accumulation;
private:
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc
index fe5b25522fa..5d9cb4586e2 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc
@@ -74,6 +74,7 @@
#include "third_party/blink/renderer/core/layout/layout_scrollbar_part.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
@@ -143,7 +144,8 @@ PaintLayerScrollableArea::PaintLayerScrollableArea(PaintLayer& layer)
scroll_anchor_(this),
non_composited_main_thread_scrolling_reasons_(0),
horizontal_scrollbar_previously_was_overlay_(false),
- vertical_scrollbar_previously_was_overlay_(false) {
+ vertical_scrollbar_previously_was_overlay_(false),
+ scrolling_background_display_item_client_(*this) {
Node* node = GetLayoutBox()->GetNode();
if (node && node->IsElementNode()) {
// We save and restore only the scrollOffset as the other scroll values are
@@ -231,6 +233,7 @@ bool PaintLayerScrollableArea::HasBeenDisposed() const {
void PaintLayerScrollableArea::Trace(blink::Visitor* visitor) {
visitor->Trace(scrollbar_manager_);
visitor->Trace(scroll_anchor_);
+ visitor->Trace(scrolling_background_display_item_client_);
ScrollableArea::Trace(visitor);
}
@@ -289,17 +292,6 @@ GraphicsLayer* PaintLayerScrollableArea::LayerForScrollCorner() const {
: nullptr;
}
-bool PaintLayerScrollableArea::ShouldUseIntegerScrollOffset() const {
- if (!HasBeenDisposed()) {
- Frame* frame = GetLayoutBox()->GetFrame();
- if (frame->GetSettings() &&
- !frame->GetSettings()->GetPreferCompositingToLCDTextEnabled())
- return true;
- }
-
- return ScrollableArea::ShouldUseIntegerScrollOffset();
-}
-
bool PaintLayerScrollableArea::IsActive() const {
Page* page = GetLayoutBox()->GetFrame()->GetPage();
return page && page->GetFocusController().IsActive();
@@ -427,7 +419,6 @@ void PaintLayerScrollableArea::UpdateScrollOffset(
if (HasBeenDisposed() || GetScrollOffset() == new_offset)
return;
- bool offset_was_zero = scroll_offset_.IsZero();
scroll_offset_ = new_offset;
LocalFrame* frame = GetLayoutBox()->GetFrame();
@@ -437,7 +428,7 @@ void PaintLayerScrollableArea::UpdateScrollOffset(
bool is_root_layer = Layer()->IsRootLayer();
TRACE_EVENT1("devtools.timeline", "ScrollLayer", "data",
- InspectorScrollLayerEvent::Data(GetLayoutBox()));
+ inspector_scroll_layer_event::Data(GetLayoutBox()));
// FIXME(420741): Resolve circular dependency between scroll offset and
// compositing state, and remove this disabler.
@@ -471,7 +462,7 @@ void PaintLayerScrollableArea::UpdateScrollOffset(
page->GetChromeClient().ClearToolTip(*frame);
}
- InvalidatePaintForScrollOffsetChange(offset_was_zero);
+ InvalidatePaintForScrollOffsetChange();
// The scrollOffsetTranslation paint property depends on the scroll offset.
// (see: PaintPropertyTreeBuilder::UpdateScrollAndScrollTranslation).
@@ -508,71 +499,55 @@ void PaintLayerScrollableArea::UpdateScrollOffset(
cache->HandleScrollPositionChanged(GetLayoutBox());
}
-void PaintLayerScrollableArea::InvalidatePaintForScrollOffsetChange(
- bool offset_was_zero) {
+void PaintLayerScrollableArea::InvalidatePaintForScrollOffsetChange() {
InvalidatePaintForStickyDescendants();
- bool requires_paint_invalidation = false;
-
- // "background-attachment: local" causes the background of this element to
- // change position due to scroll so a paint invalidation is needed.
- // TODO(pdr): This invalidation can be removed if the local background
- // attachment is painted into the scrolling contents.
- if (ScrollsOverflow() &&
- GetLayoutBox()->StyleRef().BackgroundLayers().Attachment() ==
- EFillAttachment::kLocal) {
- if (!UsesCompositedScrolling())
- requires_paint_invalidation = true;
-
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- GetLayoutBox()->SetShouldDoFullPaintInvalidation();
- return;
- }
- }
+ auto* box = GetLayoutBox();
+ auto* frame_view = box->GetFrameView();
+ frame_view->InvalidateBackgroundAttachmentFixedDescendantsOnScroll(*box);
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- // TODO(pdr): If this is the root frame, descendants with fixed background
- // attachments need to be invalidated.
-
- // A scroll offset translation is still needed for overflow:hidden and there
- // is an optimization to only create this translation node when scroll
- // offset is non-zero (see: NeedsScrollOrScrollTranslation in
- // PaintPropertyTreeBuilder.cpp). Because of this optimization, gaining or
- // losing scroll offset can change whether a property exists and we have to
- // invalidate paint to ensure this property gets picked up in BlockPainter.
- bool needs_repaint_for_overflow_hidden =
- !ScrollsOverflow() && (offset_was_zero || GetScrollOffset().IsZero());
- // An invalidation is needed to ensure the interest rect is recalculated
- // so newly-scrolled-to items are repainted. We may want to set a flag on
- // PaintLayer to just check for interest rect changes instead of doing a
- // full repaint.
- bool needs_repaint_for_interest_rect = true;
- if (needs_repaint_for_overflow_hidden || needs_repaint_for_interest_rect)
- Layer()->SetNeedsRepaint();
-
- return;
- }
-
- LocalFrameView* frame_view = GetLayoutBox()->GetFrameView();
- bool is_root_layer = Layer()->IsRootLayer();
- frame_view->InvalidateBackgroundAttachmentFixedDescendants(*GetLayoutBox());
-
- if (is_root_layer && frame_view->HasViewportConstrainedObjects() &&
+ if (box->IsLayoutView() && frame_view->HasViewportConstrainedObjects() &&
!frame_view->InvalidateViewportConstrainedObjects()) {
- requires_paint_invalidation = true;
- }
-
- if (requires_paint_invalidation) {
- GetLayoutBox()->SetShouldDoFullPaintInvalidation();
- GetLayoutBox()->SetSubtreeShouldCheckForPaintInvalidation();
- } else if (!UsesCompositedScrolling()) {
- // If any scrolling content might have ben clipped by a cull rect, then
- // that cull rect could be affected by scroll offset. For composited
- // scrollers, this will be taken care of by the interest rect computation
- // in CompositedLayerMapping.
- // TODO(chrishtr): replace this shortcut with interest rects.
+ box->SetShouldDoFullPaintInvalidation();
+ box->SetSubtreeShouldCheckForPaintInvalidation();
+ }
+
+ // TODO(chrishtr): remove this slow path once crbug.com/906885 is fixed.
+ // See also https://bugs.chromium.org/p/chromium/issues/detail?id=903287#c10.
+ if (Layer()->EnclosingPaginationLayer())
+ box->SetSubtreeShouldCheckForPaintInvalidation();
+
+ // If not composited, background always paints into the main graphics layer.
+ bool background_paint_in_graphics_layer = true;
+ bool background_paint_in_scrolling_contents = false;
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
+ UsesCompositedScrolling()) {
+ auto background_paint_location = box->GetBackgroundPaintLocation();
+ background_paint_in_graphics_layer =
+ background_paint_location & kBackgroundPaintInGraphicsLayer;
+ background_paint_in_scrolling_contents =
+ background_paint_location & kBackgroundPaintInScrollingContents;
+ }
+
+ // Both local attachment background painted in graphics layer and normal
+ // attachment background painted in scrolling contents require paint
+ // invalidation. Fixed attachment background has been dealt with in
+ // frame_view->InvalidateBackgroundAttachmentFixedDescendantsOnScroll().
+ auto background_layers = box->StyleRef().BackgroundLayers();
+ if ((background_layers.AnyLayerHasLocalAttachmentImage() &&
+ background_paint_in_graphics_layer) ||
+ (background_layers.AnyLayerHasDefaultAttachmentImage() &&
+ background_paint_in_scrolling_contents))
+ box->SetBackgroundNeedsFullPaintInvalidation();
+
+ // If any scrolling content might have been clipped by a cull rect, then
+ // that cull rect could be affected by scroll offset. For composited
+ // scrollers, this will be taken care of by the interest rect computation
+ // in CompositedLayerMapping.
+ // TODO(wangxianzhu): replace this shortcut with interest rects.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
+ !UsesCompositedScrolling())
Layer()->SetNeedsRepaint();
- }
}
IntSize PaintLayerScrollableArea::ScrollOffsetInt() const {
@@ -588,7 +563,7 @@ IntSize PaintLayerScrollableArea::MinimumScrollOffsetInt() const {
}
IntSize PaintLayerScrollableArea::MaximumScrollOffsetInt() const {
- if (!GetLayoutBox()->HasOverflowClip())
+ if (!GetLayoutBox() || !GetLayoutBox()->HasOverflowClip())
return ToIntSize(-ScrollOrigin());
IntSize content_size = ContentsSize();
@@ -834,7 +809,7 @@ int PaintLayerScrollableArea::PageStep(ScrollbarOrientation orientation) const {
}
LayoutBox* PaintLayerScrollableArea::GetLayoutBox() const {
- return layer_->GetLayoutBox();
+ return layer_ ? layer_->GetLayoutBox() : nullptr;
}
PaintLayer* PaintLayerScrollableArea::Layer() const {
@@ -984,9 +959,13 @@ void PaintLayerScrollableArea::UpdateAfterLayout() {
!GetLayoutBox()->IsHorizontalWritingMode())) {
GetLayoutBox()->SetPreferredLogicalWidthsDirty();
}
- // If the box is managed by LayoutNG, don't go here. We don't want to
- // re-enter the NG layout algorithm for this box from here.
- if (!IsManagedByLayoutNG(*GetLayoutBox())) {
+ if (IsManagedByLayoutNG(*GetLayoutBox())) {
+ // If the box is managed by LayoutNG, don't go here. We don't want to
+ // re-enter the NG layout algorithm for this box from here. Just update
+ // the rectangles, in case scrollbars were added or removed. LayoutNG
+ // has its own scrollbar change detection mechanism.
+ UpdateScrollDimensions();
+ } else {
if (PreventRelayoutScope::RelayoutIsPrevented()) {
// We're not doing re-layout right now, but we still want to
// add the scrollbar to the logical width now, to facilitate parent
@@ -998,7 +977,7 @@ void PaintLayerScrollableArea::UpdateAfterLayout() {
in_overflow_relayout_ = true;
SubtreeLayoutScope layout_scope(*GetLayoutBox());
layout_scope.SetNeedsLayout(
- GetLayoutBox(), LayoutInvalidationReason::kScrollbarChanged);
+ GetLayoutBox(), layout_invalidation_reason::kScrollbarChanged);
if (GetLayoutBox()->IsLayoutBlock()) {
LayoutBlock* block = ToLayoutBlock(GetLayoutBox());
block->ScrollbarsChanged(horizontal_scrollbar_should_change,
@@ -1260,7 +1239,7 @@ void PaintLayerScrollableArea::UpdateAfterOverflowRecalc() {
(GetLayoutBox()->HasAutoVerticalScrollbar() &&
vertical_scrollbar_should_change)) {
GetLayoutBox()->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kUnknown);
+ layout_invalidation_reason::kUnknown);
}
ClampScrollOffsetAfterOverflowChange();
@@ -1571,6 +1550,13 @@ bool PaintLayerScrollableArea::SetHasVerticalScrollbar(bool has_scrollbar) {
if (FreezeScrollbarsScope::ScrollbarsAreFrozen())
return false;
+ if (GetLayoutBox()->GetDocument().IsVerticalScrollEnforced()) {
+ // When the policy is enforced the contents of document cannot be scrolled.
+ // This would make rendering a scrollbar look strange
+ // (https://crbug.com/898151).
+ return false;
+ }
+
if (has_scrollbar == HasVerticalScrollbar())
return false;
@@ -1639,9 +1625,10 @@ void PaintLayerScrollableArea::SnapAfterScrollbarScrolling(
GetLayoutBox()->GetDocument().GetSnapCoordinator();
if (!snap_coordinator)
return;
- snap_coordinator->PerformSnapping(*GetLayoutBox(),
- orientation == kHorizontalScrollbar,
- orientation == kVerticalScrollbar);
+
+ snap_coordinator->SnapForEndPosition(*GetLayoutBox(),
+ orientation == kHorizontalScrollbar,
+ orientation == kVerticalScrollbar);
}
void PaintLayerScrollableArea::PositionOverflowControls() {
@@ -1983,7 +1970,9 @@ void PaintLayerScrollableArea::Resize(const IntPoint& pos,
bool is_box_sizing_border =
GetLayoutBox()->StyleRef().BoxSizing() == EBoxSizing::kBorderBox;
- EResize resize = GetLayoutBox()->StyleRef().Resize();
+ EResize resize =
+ ResolvedResize(GetLayoutBox()->StyleRef(),
+ GetLayoutBox()->ContainingBlock()->StyleRef());
if (resize != EResize::kVertical && difference.Width()) {
if (element->IsFormControlElement()) {
// Make implicit margins from the theme explicit (see
@@ -2057,6 +2046,18 @@ LayoutRect PaintLayerScrollableArea::ScrollIntoView(
if (!UserInputScrollable(kVerticalScrollbar))
new_scroll_offset.SetHeight(old_scroll_offset.Height());
}
+
+ FloatPoint end_point = ScrollOffsetToPosition(new_scroll_offset);
+ std::unique_ptr<SnapSelectionStrategy> strategy =
+ SnapSelectionStrategy::CreateForEndPosition(gfx::ScrollOffset(end_point),
+ true, true);
+ end_point = GetLayoutBox()
+ ->GetDocument()
+ .GetSnapCoordinator()
+ ->GetSnapPosition(*GetLayoutBox(), *strategy)
+ .value_or(end_point);
+ new_scroll_offset = ScrollPositionToOffset(end_point);
+
if (params.is_for_scroll_sequence) {
DCHECK(params.GetScrollType() == kProgrammaticScroll ||
params.GetScrollType() == kUserScroll);
@@ -2165,11 +2166,6 @@ void PaintLayerScrollableArea::UpdateCompositingLayersAfterScroll() {
kCompositingUpdateAfterGeometryChange);
}
- // Sticky constraints and paint property nodes need to be updated
- // to the new sticky locations.
- if (HasStickyDescendants())
- InvalidateAllStickyConstraints();
-
// If we have fixed elements and we scroll the root layer we might
// change compositing since the fixed elements might now overlap a
// composited layer.
@@ -2253,12 +2249,13 @@ bool PaintLayerScrollableArea::ComputeNeedsCompositedScrolling(
// TODO(flackr): Allow integer transforms as long as all of the ancestor
// transforms are also integer.
bool background_supports_lcd_text =
- layer->GetLayoutObject().StyleRef().IsStackingContext() &&
- layer->GetBackgroundPaintLocation(
+ GetLayoutBox()->StyleRef().IsStackingContext() &&
+ GetLayoutBox()->GetBackgroundPaintLocation(
&non_composited_main_thread_scrolling_reasons_) &
kBackgroundPaintInScrollingContents &&
layer->BackgroundIsKnownToBeOpaqueInRect(
- ToLayoutBox(layer->GetLayoutObject()).PhysicalPaddingBoxRect()) &&
+ ToLayoutBox(layer->GetLayoutObject()).PhysicalPaddingBoxRect(),
+ true) &&
!layer->CompositesWithTransform() && !layer->CompositesWithOpacity();
// TODO(crbug.com/839341): Remove ScrollTimeline check once we support
@@ -2276,7 +2273,8 @@ bool PaintLayerScrollableArea::ComputeNeedsCompositedScrolling(
MainThreadScrollingReason::kHasTransformAndLCDText;
}
if (!layer->BackgroundIsKnownToBeOpaqueInRect(
- ToLayoutBox(layer->GetLayoutObject()).PhysicalPaddingBoxRect())) {
+ ToLayoutBox(layer->GetLayoutObject()).PhysicalPaddingBoxRect(),
+ true)) {
non_composited_main_thread_scrolling_reasons_ |=
MainThreadScrollingReason::kBackgroundNotOpaqueInRectAndLCDText;
}
@@ -2322,9 +2320,7 @@ bool PaintLayerScrollableArea::VisualViewportSuppliesScrollbars() const {
const TopDocumentRootScrollerController& controller =
GetLayoutBox()->GetDocument().GetPage()->GlobalRootScrollerController();
-
- return RootScrollerUtil::ScrollableAreaForRootScroller(
- controller.GlobalRootScroller()) == this;
+ return controller.RootScrollerArea() == this;
}
bool PaintLayerScrollableArea::ScheduleAnimation() {
@@ -2500,7 +2496,7 @@ PaintLayerScrollableArea::PreventRelayoutScope::~PreventRelayoutScope() {
DCHECK(scrollable_area->NeedsRelayout());
LayoutBox* box = scrollable_area->GetLayoutBox();
layout_scope_->SetNeedsLayout(
- box, LayoutInvalidationReason::kScrollbarChanged);
+ box, layout_invalidation_reason::kScrollbarChanged);
if (box->IsLayoutBlock()) {
bool horizontal_scrollbar_changed =
scrollable_area->HasHorizontalScrollbar() !=
@@ -2547,9 +2543,10 @@ void PaintLayerScrollableArea::PreventRelayoutScope::ResetRelayoutNeeded() {
HeapVector<Member<PaintLayerScrollableArea>>&
PaintLayerScrollableArea::PreventRelayoutScope::NeedsRelayoutList() {
- DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<PaintLayerScrollableArea>>>,
- needs_relayout_list,
- (new HeapVector<Member<PaintLayerScrollableArea>>));
+ DEFINE_STATIC_LOCAL(
+ Persistent<HeapVector<Member<PaintLayerScrollableArea>>>,
+ needs_relayout_list,
+ (MakeGarbageCollected<HeapVector<Member<PaintLayerScrollableArea>>>()));
return *needs_relayout_list;
}
@@ -2586,9 +2583,10 @@ void PaintLayerScrollableArea::DelayScrollOffsetClampScope::
HeapVector<Member<PaintLayerScrollableArea>>&
PaintLayerScrollableArea::DelayScrollOffsetClampScope::NeedsClampList() {
- DEFINE_STATIC_LOCAL(Persistent<HeapVector<Member<PaintLayerScrollableArea>>>,
- needs_clamp_list,
- (new HeapVector<Member<PaintLayerScrollableArea>>));
+ DEFINE_STATIC_LOCAL(
+ Persistent<HeapVector<Member<PaintLayerScrollableArea>>>,
+ needs_clamp_list,
+ (MakeGarbageCollected<HeapVector<Member<PaintLayerScrollableArea>>>()));
return *needs_clamp_list;
}
@@ -2845,4 +2843,37 @@ CompositorElementId PaintLayerScrollableArea::GetCompositorElementId() const {
GetLayoutBox()->UniqueId(), CompositorElementIdNamespace::kScroll);
}
+LayoutRect
+PaintLayerScrollableArea::ScrollingBackgroundDisplayItemClient::VisualRect()
+ const {
+ const auto* box = scrollable_area_->GetLayoutBox();
+ auto overflow_clip_rect = box->OverflowClipRect(LayoutPoint());
+ auto scroll_size = scrollable_area_->overflow_rect_.Size();
+ // Ensure scrolling contents are at least as large as the scroll clip
+ scroll_size = scroll_size.ExpandedTo(overflow_clip_rect.Size());
+ LayoutRect result(overflow_clip_rect.Location(), scroll_size);
+ result.MoveBy(box->FirstFragment().PaintOffset());
+ result = LayoutRect(PixelSnappedIntRect(result));
+#if DCHECK_IS_ON()
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ DCHECK_EQ(result,
+ scrollable_area_->layer_->GraphicsLayerBacking()->VisualRect());
+ }
+#endif
+ return result;
+}
+
+String
+PaintLayerScrollableArea::ScrollingBackgroundDisplayItemClient::DebugName()
+ const {
+ return "Scrolling background of " +
+ scrollable_area_->GetLayoutBox()->DebugName();
+}
+
+bool PaintLayerScrollableArea::ScrollingBackgroundDisplayItemClient::
+ PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const {
+ return scrollable_area_->GetLayoutBox()
+ ->PaintedOutputOfObjectHasNoEffectRegardlessOfSize();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h
index ec116bef8a6..48def2b72e9 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h
@@ -244,9 +244,10 @@ class CORE_EXPORT PaintLayerScrollableArea final
// FIXME: We should pass in the LayoutBox but this opens a window
// for crashers during PaintLayer setup (see crbug.com/368062).
static PaintLayerScrollableArea* Create(PaintLayer& layer) {
- return new PaintLayerScrollableArea(layer);
+ return MakeGarbageCollected<PaintLayerScrollableArea>(layer);
}
+ explicit PaintLayerScrollableArea(PaintLayer&);
~PaintLayerScrollableArea() override;
void Dispose();
bool HasBeenDisposed() const override;
@@ -284,7 +285,6 @@ class CORE_EXPORT PaintLayerScrollableArea final
GraphicsLayer* LayerForScrollCorner() const override;
bool ShouldScrollOnMainThread() const override;
- bool ShouldUseIntegerScrollOffset() const override;
bool IsActive() const override;
bool IsScrollCornerVisible() const override;
IntRect ScrollCornerRect() const override;
@@ -548,9 +548,11 @@ class CORE_EXPORT PaintLayerScrollableArea final
void Trace(blink::Visitor*) override;
- private:
- explicit PaintLayerScrollableArea(PaintLayer&);
+ const DisplayItemClient& GetScrollingBackgroundDisplayItemClient() const {
+ return scrolling_background_display_item_client_;
+ }
+ private:
bool NeedsScrollbarReconstruction() const;
void ResetScrollOriginChanged() { scroll_origin_changed_ = false; }
@@ -562,7 +564,7 @@ class CORE_EXPORT PaintLayerScrollableArea final
void UpdateScrollbarProportions();
void UpdateScrollOffset(const ScrollOffset&, ScrollType) override;
- void InvalidatePaintForScrollOffsetChange(bool offset_was_zero);
+ void InvalidatePaintForScrollOffsetChange();
int VerticalScrollbarStart(int min_x, int max_x) const;
int HorizontalScrollbarStart(int min_x) const;
@@ -697,6 +699,27 @@ class CORE_EXPORT PaintLayerScrollableArea final
LayoutRect horizontal_scrollbar_visual_rect_;
LayoutRect vertical_scrollbar_visual_rect_;
LayoutRect scroll_corner_and_resizer_visual_rect_;
+
+ class ScrollingBackgroundDisplayItemClient : public DisplayItemClient {
+ DISALLOW_NEW();
+
+ public:
+ ScrollingBackgroundDisplayItemClient(
+ const PaintLayerScrollableArea& scrollable_area)
+ : scrollable_area_(&scrollable_area) {}
+
+ LayoutRect VisualRect() const override;
+ String DebugName() const override;
+ bool PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const override;
+
+ void Trace(Visitor* visitor) { visitor->Trace(scrollable_area_); }
+
+ private:
+ Member<const PaintLayerScrollableArea> scrollable_area_;
+ };
+
+ ScrollingBackgroundDisplayItemClient
+ scrolling_background_display_item_client_;
};
DEFINE_TYPE_CASTS(PaintLayerScrollableArea,
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc
index ea6ccd73737..5a3f1d6c312 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
+#include "third_party/blink/renderer/platform/testing/paint_test_configurations.h"
using testing::_;
@@ -30,13 +31,13 @@ class ScrollableAreaMockChromeClient : public EmptyChromeClient {
} // namespace {
-class PaintLayerScrollableAreaTest : public RenderingTest {
+class PaintLayerScrollableAreaTestBase : public RenderingTest {
public:
- PaintLayerScrollableAreaTest()
+ PaintLayerScrollableAreaTestBase()
: RenderingTest(EmptyLocalFrameClient::Create()),
chrome_client_(new ScrollableAreaMockChromeClient) {}
- ~PaintLayerScrollableAreaTest() override {
+ ~PaintLayerScrollableAreaTestBase() override {
testing::Mock::VerifyAndClearExpectations(&GetChromeClient());
}
@@ -45,9 +46,8 @@ class PaintLayerScrollableAreaTest : public RenderingTest {
}
BackgroundPaintLocation GetBackgroundPaintLocation(const char* element_id) {
- PaintLayer* paint_layer =
- ToLayoutBoxModelObject(GetLayoutObjectByElementId(element_id))->Layer();
- return paint_layer->GetBackgroundPaintLocation();
+ return ToLayoutBoxModelObject(GetLayoutObjectByElementId(element_id))
+ ->GetBackgroundPaintLocation();
}
private:
@@ -59,7 +59,13 @@ class PaintLayerScrollableAreaTest : public RenderingTest {
Persistent<ScrollableAreaMockChromeClient> chrome_client_;
};
-TEST_F(PaintLayerScrollableAreaTest,
+class PaintLayerScrollableAreaTest : public PaintLayerScrollableAreaTestBase,
+ public PaintTestConfigurations {};
+
+INSTANTIATE_PAINT_TEST_CASE_P(PaintLayerScrollableAreaTest);
+using PaintLayerScrollableAreaTestSPv1 = PaintLayerScrollableAreaTestBase;
+
+TEST_P(PaintLayerScrollableAreaTest,
CanPaintBackgroundOntoScrollingContentsLayer) {
GetDocument().GetFrame()->GetSettings()->SetPreferCompositingToLCDTextEnabled(
true);
@@ -152,6 +158,11 @@ TEST_F(PaintLayerScrollableAreaTest,
border: 5px solid rgba(0, 0, 0, 0.5);'>
<div class='spacer'></div>
</div>
+ <div id='scroller18' class='scroller'
+ style='background: white;
+ border: 5px dashed black;'>
+ <div class='spacer'></div>
+ </div>
)HTML");
// #scroller1 can paint background into scrolling contents layer even with a
@@ -246,9 +257,16 @@ TEST_F(PaintLayerScrollableAreaTest,
// be painted in the graphics layer to be under the translucent border.
EXPECT_EQ(kBackgroundPaintInGraphicsLayer,
GetBackgroundPaintLocation("scroller17"));
+
+ // #scroller18 can be painted in both layers because the background is a
+ // solid color, it must be because the dashed border reveals the background
+ // underneath it.
+ EXPECT_EQ(
+ kBackgroundPaintInGraphicsLayer | kBackgroundPaintInScrollingContents,
+ GetBackgroundPaintLocation("scroller18"));
}
-TEST_F(PaintLayerScrollableAreaTest, OpaqueContainedLayersPromoted) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, OpaqueContainedLayersPromoted) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px;
@@ -258,7 +276,6 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueContainedLayersPromoted) {
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -272,7 +289,7 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueContainedLayersPromoted) {
// Tests that we don't promote scrolling content which would not be contained.
// Promoting the scroller would also require promoting the positioned div
// which would lose subpixel anti-aliasing due to its transparent background.
-TEST_F(PaintLayerScrollableAreaTest, NonContainedLayersNotPromoted) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, NonContainedLayersNotPromoted) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px;
@@ -286,7 +303,6 @@ TEST_F(PaintLayerScrollableAreaTest, NonContainedLayersNotPromoted) {
<div id="scrolled"></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -296,7 +312,7 @@ TEST_F(PaintLayerScrollableAreaTest, NonContainedLayersNotPromoted) {
EXPECT_FALSE(paint_layer->GraphicsLayerBacking());
}
-TEST_F(PaintLayerScrollableAreaTest, TransparentLayersNotPromoted) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, TransparentLayersNotPromoted) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px; background:
@@ -306,7 +322,6 @@ TEST_F(PaintLayerScrollableAreaTest, TransparentLayersNotPromoted) {
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -316,7 +331,7 @@ TEST_F(PaintLayerScrollableAreaTest, TransparentLayersNotPromoted) {
EXPECT_FALSE(paint_layer->GraphicsLayerBacking());
}
-TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersDepromotedOnStyleChange) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, OpaqueLayersDepromotedOnStyleChange) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px; background:
@@ -325,7 +340,6 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersDepromotedOnStyleChange) {
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -335,16 +349,16 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersDepromotedOnStyleChange) {
// Change the background to transparent
scroller->setAttribute(
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
"background: rgba(255,255,255,0.5) local content-box;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
EXPECT_FALSE(paint_layer->GraphicsLayerBacking());
}
-TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersPromotedOnStyleChange) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, OpaqueLayersPromotedOnStyleChange) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px; background:
@@ -353,7 +367,6 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersPromotedOnStyleChange) {
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -362,9 +375,9 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersPromotedOnStyleChange) {
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
// Change the background to opaque
- scroller->setAttribute(HTMLNames::styleAttr,
+ scroller->setAttribute(html_names::kStyleAttr,
"background: white local content-box;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_TRUE(paint_layer->NeedsCompositedScrolling());
@@ -376,7 +389,8 @@ TEST_F(PaintLayerScrollableAreaTest, OpaqueLayersPromotedOnStyleChange) {
// Tests that a transform on the scroller or an ancestor will prevent promotion
// TODO(flackr): Allow integer transforms as long as all of the ancestor
// transforms are also integer.
-TEST_F(PaintLayerScrollableAreaTest, OnlyNonTransformedOpaqueLayersPromoted) {
+TEST_F(PaintLayerScrollableAreaTestSPv1,
+ OnlyNonTransformedOpaqueLayersPromoted) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px; background:
@@ -387,7 +401,6 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyNonTransformedOpaqueLayersPromoted) {
<div id="scroller"><div id="scrolled"></div></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* parent = GetDocument().getElementById("parent");
Element* scroller = GetDocument().getElementById("scroller");
@@ -400,16 +413,16 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyNonTransformedOpaqueLayersPromoted) {
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Change the parent to have a transform.
- parent->setAttribute(HTMLNames::styleAttr, "transform: translate(1px, 0);");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "transform: translate(1px, 0);");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
EXPECT_FALSE(paint_layer->GraphicsLayerBacking());
// Change the parent to have no transform again.
- parent->removeAttribute(HTMLNames::styleAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->removeAttribute(html_names::kStyleAttr);
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_TRUE(paint_layer->NeedsCompositedScrolling());
@@ -418,8 +431,9 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyNonTransformedOpaqueLayersPromoted) {
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Apply a transform to the scroller directly.
- scroller->setAttribute(HTMLNames::styleAttr, "transform: translate(1px, 0);");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scroller->setAttribute(html_names::kStyleAttr,
+ "transform: translate(1px, 0);");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
@@ -428,7 +442,7 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyNonTransformedOpaqueLayersPromoted) {
// Test that opacity applied to the scroller or an ancestor will cause the
// scrolling contents layer to not be promoted.
-TEST_F(PaintLayerScrollableAreaTest, OnlyOpaqueLayersPromoted) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, OnlyOpaqueLayersPromoted) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; height: 200px; width: 200px; background:
@@ -439,7 +453,6 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyOpaqueLayersPromoted) {
<div id="scroller"><div id="scrolled"></div></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* parent = GetDocument().getElementById("parent");
Element* scroller = GetDocument().getElementById("scroller");
@@ -452,16 +465,16 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyOpaqueLayersPromoted) {
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Change the parent to be partially translucent.
- parent->setAttribute(HTMLNames::styleAttr, "opacity: 0.5;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "opacity: 0.5;");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
EXPECT_FALSE(paint_layer->GraphicsLayerBacking());
// Change the parent to be opaque again.
- parent->setAttribute(HTMLNames::styleAttr, "opacity: 1;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ parent->setAttribute(html_names::kStyleAttr, "opacity: 1;");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_TRUE(paint_layer->NeedsCompositedScrolling());
@@ -470,8 +483,8 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyOpaqueLayersPromoted) {
EXPECT_TRUE(paint_layer->GraphicsLayerBacking()->ContentsOpaque());
// Make the scroller translucent.
- scroller->setAttribute(HTMLNames::styleAttr, "opacity: 0.5");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scroller->setAttribute(html_names::kStyleAttr, "opacity: 0.5");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
@@ -479,7 +492,7 @@ TEST_F(PaintLayerScrollableAreaTest, OnlyOpaqueLayersPromoted) {
}
// Test that <input> elements get promoted with "will-change:transform".
-TEST_F(PaintLayerScrollableAreaTest, InputElementPromotionTest) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, InputElementPromotionTest) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
@@ -487,7 +500,6 @@ TEST_F(PaintLayerScrollableAreaTest, InputElementPromotionTest) {
</style>
<input id='input' width=10 style='font-size:40pt;'/>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* element = GetDocument().getElementById("input");
PaintLayer* paint_layer =
@@ -495,14 +507,14 @@ TEST_F(PaintLayerScrollableAreaTest, InputElementPromotionTest) {
ASSERT_FALSE(paint_layer);
element->setAttribute("class", "composited");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
ASSERT_TRUE(paint_layer->HasCompositedLayerMapping());
}
// Test that <select> elements get promoted with "will-change:transform".
-TEST_F(PaintLayerScrollableAreaTest, SelectElementPromotionTest) {
+TEST_F(PaintLayerScrollableAreaTestSPv1, SelectElementPromotionTest) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
@@ -515,7 +527,6 @@ TEST_F(PaintLayerScrollableAreaTest, SelectElementPromotionTest) {
<option> value 4</option>
</select>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* element = GetDocument().getElementById("select");
PaintLayer* paint_layer =
@@ -525,14 +536,14 @@ TEST_F(PaintLayerScrollableAreaTest, SelectElementPromotionTest) {
ASSERT_TRUE(!paint_layer || !paint_layer->HasCompositedLayerMapping());
element->setAttribute("class", "composited");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
ASSERT_TRUE(paint_layer->HasCompositedLayerMapping());
}
// Ensure OverlayScrollbarColorTheme get updated when page load
-TEST_F(PaintLayerScrollableAreaTest, OverlayScrollbarColorThemeUpdated) {
+TEST_P(PaintLayerScrollableAreaTest, OverlayScrollbarColorThemeUpdated) {
SetBodyInnerHTML(R"HTML(
<style>
div { overflow: scroll; }
@@ -543,7 +554,6 @@ TEST_F(PaintLayerScrollableAreaTest, OverlayScrollbarColorThemeUpdated) {
<div id="white">b</div>
<div id="black">c</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* none = GetDocument().getElementById("none");
Element* white = GetDocument().getElementById("white");
@@ -570,7 +580,7 @@ TEST_F(PaintLayerScrollableAreaTest, OverlayScrollbarColorThemeUpdated) {
// Test that css clip applied to the scroller will cause the
// scrolling contents layer to not be promoted.
-TEST_F(PaintLayerScrollableAreaTest,
+TEST_F(PaintLayerScrollableAreaTestSPv1,
OnlyAutoClippedScrollingContentsLayerPromoted) {
SetBodyInnerHTML(R"HTML(
<style>
@@ -582,7 +592,6 @@ TEST_F(PaintLayerScrollableAreaTest,
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayer* paint_layer =
@@ -591,21 +600,21 @@ TEST_F(PaintLayerScrollableAreaTest,
EXPECT_TRUE(paint_layer->NeedsCompositedScrolling());
// Add clip to scroller.
- scroller->setAttribute(HTMLNames::classAttr, "clip");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scroller->setAttribute(html_names::kClassAttr, "clip");
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_FALSE(paint_layer->NeedsCompositedScrolling());
// Change the scroller to be auto clipped again.
scroller->removeAttribute("class");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
paint_layer = ToLayoutBoxModelObject(scroller->GetLayoutObject())->Layer();
ASSERT_TRUE(paint_layer);
EXPECT_TRUE(paint_layer->NeedsCompositedScrolling());
}
-TEST_F(PaintLayerScrollableAreaTest, HideTooltipWhenScrollPositionChanges) {
+TEST_P(PaintLayerScrollableAreaTest, HideTooltipWhenScrollPositionChanges) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { width: 100px; height: 100px; overflow: scroll; }
@@ -613,7 +622,6 @@ TEST_F(PaintLayerScrollableAreaTest, HideTooltipWhenScrollPositionChanges) {
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
Element* scroller = GetDocument().getElementById("scroller");
PaintLayerScrollableArea* scrollable_area =
@@ -633,7 +641,7 @@ TEST_F(PaintLayerScrollableAreaTest, HideTooltipWhenScrollPositionChanges) {
scrollable_area->SetScrollOffset(ScrollOffset(2, 2), kProgrammaticScroll);
}
-TEST_F(PaintLayerScrollableAreaTest, IncludeOverlayScrollbarsInVisibleWidth) {
+TEST_P(PaintLayerScrollableAreaTest, IncludeOverlayScrollbarsInVisibleWidth) {
ScopedOverlayScrollbarsForTest overlay_scrollbars(false);
SetBodyInnerHTML(R"HTML(
<style>
@@ -642,7 +650,7 @@ TEST_F(PaintLayerScrollableAreaTest, IncludeOverlayScrollbarsInVisibleWidth) {
</style>
<div id="scroller"><div id="scrolled"></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+
Element* scroller = GetDocument().getElementById("scroller");
ASSERT_TRUE(scroller);
PaintLayerScrollableArea* scrollable_area =
@@ -652,7 +660,7 @@ TEST_F(PaintLayerScrollableAreaTest, IncludeOverlayScrollbarsInVisibleWidth) {
EXPECT_EQ(scrollable_area->GetScrollOffset().Width(), 0);
}
-TEST_F(PaintLayerScrollableAreaTest, ShowAutoScrollbarsForVisibleContent) {
+TEST_P(PaintLayerScrollableAreaTest, ShowAutoScrollbarsForVisibleContent) {
ScopedOverlayScrollbarsForTest overlay_scrollbars(false);
SetBodyInnerHTML(R"HTML(
<style>
@@ -671,18 +679,18 @@ TEST_F(PaintLayerScrollableAreaTest, ShowAutoScrollbarsForVisibleContent) {
<div id='innerDiv'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+
Element* outer_div = GetDocument().getElementById("outerDiv");
ASSERT_TRUE(outer_div);
outer_div->GetLayoutObject()->SetNeedsLayout("test");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintLayerScrollableArea* scrollable_area =
ToLayoutBoxModelObject(outer_div->GetLayoutObject())->GetScrollableArea();
ASSERT_TRUE(scrollable_area);
EXPECT_TRUE(scrollable_area->HasVerticalScrollbar());
}
-TEST_F(PaintLayerScrollableAreaTest, FloatOverflowInRtlContainer) {
+TEST_P(PaintLayerScrollableAreaTest, FloatOverflowInRtlContainer) {
ScopedOverlayScrollbarsForTest overlay_scrollbars(false);
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
@@ -700,7 +708,7 @@ TEST_F(PaintLayerScrollableAreaTest, FloatOverflowInRtlContainer) {
</div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+
Element* container = GetDocument().getElementById("container");
ASSERT_TRUE(container);
PaintLayerScrollableArea* scrollable_area =
@@ -709,7 +717,7 @@ TEST_F(PaintLayerScrollableAreaTest, FloatOverflowInRtlContainer) {
EXPECT_FALSE(scrollable_area->HasHorizontalScrollbar());
}
-TEST_F(PaintLayerScrollableAreaTest, ScrollOriginInRtlContainer) {
+TEST_P(PaintLayerScrollableAreaTest, ScrollOriginInRtlContainer) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
@@ -728,7 +736,7 @@ TEST_F(PaintLayerScrollableAreaTest, ScrollOriginInRtlContainer) {
<div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+
Element* container = GetDocument().getElementById("container");
ASSERT_TRUE(container);
PaintLayerScrollableArea* scrollable_area =
@@ -737,10 +745,7 @@ TEST_F(PaintLayerScrollableAreaTest, ScrollOriginInRtlContainer) {
EXPECT_EQ(scrollable_area->ScrollOrigin().X(), 100);
}
-TEST_F(PaintLayerScrollableAreaTest,
- SlimmingPaintV2OverflowHiddenScrollOffsetInvalidation) {
- ScopedSlimmingPaintV2ForTest enabler(true);
-
+TEST_P(PaintLayerScrollableAreaTest, OverflowHiddenScrollOffsetInvalidation) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller {
@@ -753,7 +758,6 @@ TEST_F(PaintLayerScrollableAreaTest,
<div id='forceScroll' style='height: 2000px;'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
auto* scroller = GetLayoutObjectByElementId("scroller");
auto* scrollable_area = ToLayoutBoxModelObject(scroller)->GetScrollableArea();
@@ -769,7 +773,7 @@ TEST_F(PaintLayerScrollableAreaTest,
scrollable_area->SetScrollOffset(ScrollOffset(0, 1), kProgrammaticScroll);
EXPECT_TRUE(scroller->PaintingLayer()->NeedsRepaint());
EXPECT_TRUE(scroller->NeedsPaintPropertyUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// A scroll offset translation is needed when scroll offset is non-zero.
EXPECT_EQ(FloatSize(0, 1), scrollable_area->GetScrollOffset());
@@ -778,7 +782,7 @@ TEST_F(PaintLayerScrollableAreaTest,
// A property update is needed when scroll offset changes.
scrollable_area->SetScrollOffset(ScrollOffset(0, 2), kProgrammaticScroll);
EXPECT_TRUE(scroller->NeedsPaintPropertyUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// A scroll offset translation is still needed when scroll offset is non-zero.
EXPECT_EQ(FloatSize(0, 2), scrollable_area->GetScrollOffset());
@@ -789,16 +793,14 @@ TEST_F(PaintLayerScrollableAreaTest,
scrollable_area->SetScrollOffset(ScrollOffset(0, 0), kProgrammaticScroll);
EXPECT_TRUE(scroller->PaintingLayer()->NeedsRepaint());
EXPECT_TRUE(scroller->NeedsPaintPropertyUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// No scroll offset translation is needed when scroll offset is zero.
EXPECT_EQ(nullptr, properties->ScrollTranslation());
EXPECT_EQ(FloatSize(0, 0), scrollable_area->GetScrollOffset());
}
-TEST_F(PaintLayerScrollableAreaTest, SlimmingPaintV2ScrollDoesNotInvalidate) {
- ScopedSlimmingPaintV2ForTest enabler(true);
-
+TEST_P(PaintLayerScrollableAreaTest, ScrollDoesNotInvalidate) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller {
@@ -812,7 +814,6 @@ TEST_F(PaintLayerScrollableAreaTest, SlimmingPaintV2ScrollDoesNotInvalidate) {
<div id='forceScroll' style='height: 2000px;'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
auto* scroller = GetLayoutObjectByElementId("scroller");
auto* scrollable_area = ToLayoutBoxModelObject(scroller)->GetScrollableArea();
@@ -826,15 +827,13 @@ TEST_F(PaintLayerScrollableAreaTest, SlimmingPaintV2ScrollDoesNotInvalidate) {
scrollable_area->SetScrollOffset(ScrollOffset(0, 1), kProgrammaticScroll);
EXPECT_FALSE(scroller->ShouldDoFullPaintInvalidation());
EXPECT_TRUE(scroller->NeedsPaintPropertyUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatSize(0, 1), scrollable_area->GetScrollOffset());
EXPECT_NE(nullptr, properties->ScrollTranslation());
}
-TEST_F(PaintLayerScrollableAreaTest,
- SlimmingPaintV2ScrollWithLocalBackgroundAttachment) {
- ScopedSlimmingPaintV2ForTest enabler(true);
-
+TEST_P(PaintLayerScrollableAreaTest,
+ ScrollWithLocalAttachmentBackgroundInScrollingContents) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller {
@@ -849,23 +848,119 @@ TEST_F(PaintLayerScrollableAreaTest,
<div id='forceScroll' style='height: 2000px;'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
- auto* scroller = GetLayoutObjectByElementId("scroller");
- auto* scrollable_area = ToLayoutBoxModelObject(scroller)->GetScrollableArea();
+ auto* scroller = ToLayoutBox(GetLayoutObjectByElementId("scroller"));
+ auto* scrollable_area = scroller->GetScrollableArea();
+ EXPECT_EQ(kBackgroundPaintInScrollingContents,
+ scroller->GetBackgroundPaintLocation());
+
+ // Programmatically changing the scroll offset.
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 1), kProgrammaticScroll);
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // No invalidation because the background paints into scrolling contents.
+ EXPECT_FALSE(scroller->ShouldDoFullPaintInvalidation());
+ EXPECT_FALSE(scroller->BackgroundNeedsFullPaintInvalidation());
+ } else {
+ // Full invalidation because there is no separate scrolling contents layer.
+ EXPECT_TRUE(scroller->ShouldDoFullPaintInvalidation());
+ EXPECT_TRUE(scroller->BackgroundNeedsFullPaintInvalidation());
+ }
+ EXPECT_TRUE(scroller->NeedsPaintPropertyUpdate());
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ(FloatSize(0, 1), scrollable_area->GetScrollOffset());
+ const auto* properties = scroller->FirstFragment().PaintProperties();
+ EXPECT_NE(nullptr, properties->ScrollTranslation());
+}
+
+TEST_P(PaintLayerScrollableAreaTest,
+ ScrollWithLocalAttachmentBackgroundInMainLayer) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #scroller {
+ overflow: scroll;
+ height: 200px;
+ width: 200px;
+ border: 10px dashed black;
+ background: linear-gradient(black, white) local, yellow;
+ }
+ </style>
+ <div id='scroller'>
+ <div id='forceScroll' style='height: 2000px;'></div>
+ </div>
+ )HTML");
- // Programmatically changing the scroll offset should require paint
- // invalidation due to background attachment.
+ auto* scroller = ToLayoutBox(GetLayoutObjectByElementId("scroller"));
+ auto* scrollable_area = scroller->GetScrollableArea();
+ EXPECT_EQ(
+ kBackgroundPaintInGraphicsLayer | kBackgroundPaintInScrollingContents,
+ scroller->GetBackgroundPaintLocation());
+
+ // Programmatically changing the scroll offset.
scrollable_area->SetScrollOffset(ScrollOffset(0, 1), kProgrammaticScroll);
+ // No invalidation because the background paints into the main layer.
EXPECT_TRUE(scroller->ShouldDoFullPaintInvalidation());
+ EXPECT_TRUE(scroller->BackgroundNeedsFullPaintInvalidation());
EXPECT_TRUE(scroller->NeedsPaintPropertyUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatSize(0, 1), scrollable_area->GetScrollOffset());
const auto* properties = scroller->FirstFragment().PaintProperties();
EXPECT_NE(nullptr, properties->ScrollTranslation());
}
-TEST_F(PaintLayerScrollableAreaTest, HitTestOverlayScrollbars) {
+TEST_P(PaintLayerScrollableAreaTest, ViewScrollWithFixedAttachmentBackground) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ html, #fixed-background {
+ background: linear-gradient(black, white) fixed;
+ }
+ #fixed-background {
+ width: 200px;
+ height: 200px;
+ overflow: scroll;
+ }
+ </style>
+ <div id="fixed-background">
+ <div style="height: 3000px"></div>
+ </div>
+ <div style="height: 3000px"></div>
+ )HTML");
+
+ auto* fixed_background_div =
+ ToLayoutBox(GetLayoutObjectByElementId("fixed-background"));
+ auto* div_scrollable_area = fixed_background_div->GetScrollableArea();
+ auto* view_scrollable_area = GetLayoutView().GetScrollableArea();
+
+ // Programmatically changing the view's scroll offset. Should invalidate all
+ // objects with fixed attachment background.
+ view_scrollable_area->SetScrollOffset(ScrollOffset(0, 1),
+ kProgrammaticScroll);
+ EXPECT_TRUE(fixed_background_div->ShouldDoFullPaintInvalidation());
+ EXPECT_TRUE(fixed_background_div->BackgroundNeedsFullPaintInvalidation());
+ EXPECT_FALSE(fixed_background_div->NeedsPaintPropertyUpdate());
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ // In SPv2, we assume the view's fixed attachment background is composited
+ // at this time and doesn't need paint invalidation on view scroll.
+ EXPECT_FALSE(GetLayoutView().ShouldDoFullPaintInvalidation());
+ EXPECT_FALSE(GetLayoutView().BackgroundNeedsFullPaintInvalidation());
+ } else {
+ EXPECT_TRUE(GetLayoutView().ShouldDoFullPaintInvalidation());
+ EXPECT_TRUE(GetLayoutView().BackgroundNeedsFullPaintInvalidation());
+ }
+ EXPECT_TRUE(GetLayoutView().NeedsPaintPropertyUpdate());
+ UpdateAllLifecyclePhasesForTest();
+
+ // Programmatically changing the div's scroll offset. Should invalidate the
+ // scrolled div with fixed attachment background.
+ div_scrollable_area->SetScrollOffset(ScrollOffset(0, 1), kProgrammaticScroll);
+ EXPECT_TRUE(fixed_background_div->ShouldDoFullPaintInvalidation());
+ EXPECT_TRUE(fixed_background_div->BackgroundNeedsFullPaintInvalidation());
+ EXPECT_TRUE(fixed_background_div->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(GetLayoutView().ShouldDoFullPaintInvalidation());
+ EXPECT_FALSE(GetLayoutView().BackgroundNeedsFullPaintInvalidation());
+ EXPECT_TRUE(GetLayoutView().NeedsPaintPropertyUpdate());
+}
+
+TEST_P(PaintLayerScrollableAreaTest, HitTestOverlayScrollbars) {
SetBodyInnerHTML(R"HTML(
<style>
html, body {
@@ -883,7 +978,7 @@ TEST_F(PaintLayerScrollableAreaTest, HitTestOverlayScrollbars) {
</style>
<div id='scroller'><div id='scrolled'></div></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+
auto* scroller = GetLayoutObjectByElementId("scroller");
auto* scrollable_area = ToLayoutBoxModelObject(scroller)->GetScrollableArea();
@@ -911,7 +1006,7 @@ TEST_F(PaintLayerScrollableAreaTest, HitTestOverlayScrollbars) {
EXPECT_EQ(hit_result.GetScrollbar(), scrollable_area->HorizontalScrollbar());
}
-TEST_F(PaintLayerScrollableAreaTest, CompositedStickyDescendant) {
+TEST_P(PaintLayerScrollableAreaTest, CompositedStickyDescendant) {
SetBodyInnerHTML(R"HTML(
<div id=scroller style="overflow: scroll; width: 500px; height: 300px;
will-change: transform">
@@ -923,7 +1018,8 @@ TEST_F(PaintLayerScrollableAreaTest, CompositedStickyDescendant) {
auto* scroller =
ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"));
auto* scrollable_area = scroller->GetScrollableArea();
- EXPECT_EQ(kPaintsIntoOwnBacking, scroller->Layer()->GetCompositingState());
+ if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ EXPECT_EQ(kPaintsIntoOwnBacking, scroller->Layer()->GetCompositingState());
auto* sticky = ToLayoutBoxModelObject(GetLayoutObjectByElementId("sticky"));
EXPECT_EQ(FloatSize(0, 0), sticky->FirstFragment()
@@ -933,7 +1029,7 @@ TEST_F(PaintLayerScrollableAreaTest, CompositedStickyDescendant) {
.To2DTranslation());
scrollable_area->SetScrollOffset(ScrollOffset(0, 50), kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatSize(0, 50), sticky->FirstFragment()
.LocalBorderBoxProperties()
@@ -943,7 +1039,7 @@ TEST_F(PaintLayerScrollableAreaTest, CompositedStickyDescendant) {
}
// Delayed scroll offset clamping should not crash. https://crbug.com/842495
-TEST_F(PaintLayerScrollableAreaTest, IgnoreDelayedScrollOnDestroyedLayer) {
+TEST_P(PaintLayerScrollableAreaTest, IgnoreDelayedScrollOnDestroyedLayer) {
SetBodyInnerHTML(R"HTML(
<div id=scroller style="overflow: scroll; width: 200px; height: 200px;">
<div style="height: 1000px;"></div>
@@ -955,11 +1051,11 @@ TEST_F(PaintLayerScrollableAreaTest, IgnoreDelayedScrollOnDestroyedLayer) {
PaintLayerScrollableArea::DelayScrollOffsetClampScope::SetNeedsClamp(
scroller->GetLayoutBox()->GetScrollableArea());
scroller->SetInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
}
-TEST_F(PaintLayerScrollableAreaTest, ScrollbarMaximum) {
+TEST_P(PaintLayerScrollableAreaTest, ScrollbarMaximum) {
SetBodyInnerHTML(R"HTML(
<style>
#spacer {
@@ -987,7 +1083,7 @@ TEST_F(PaintLayerScrollableAreaTest, ScrollbarMaximum) {
Scrollbar* scrollbar = scrollable_area->VerticalScrollbar();
scrollable_area->ScrollBy(ScrollOffset(0, 1000), kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(scrollbar->CurrentPos(), scrollbar->Maximum());
}
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.cc
index a38e9efbc1d..fd5c1149ce0 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.cc
@@ -50,6 +50,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
@@ -129,8 +130,19 @@ void PaintLayerStackingNode::DirtyZOrderLists() {
void PaintLayerStackingNode::DirtyStackingContextZOrderLists(
PaintLayer* layer) {
if (PaintLayerStackingNode* stacking_node =
- AncestorStackingContextNode(layer))
+ AncestorStackingContextNode(layer)) {
+ // This invalidation code intentionally refers to stale state.
+ DisableCompositingQueryAsserts disabler;
+
+ // Changes of stacking may result in graphics layers changing size
+ // due to new contents painting into them.
+ PaintLayer* ancestor_layer = stacking_node->Layer();
+ if (auto* mapping = ancestor_layer->GetCompositedLayerMapping()) {
+ mapping->SetNeedsGraphicsLayerUpdate(kGraphicsLayerUpdateSubtree);
+ }
+
stacking_node->DirtyZOrderLists();
+ }
}
void PaintLayerStackingNode::RebuildZOrderLists() {
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_test.cc
index a56863c2650..115dc3c2ba2 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_test.cc
@@ -23,11 +23,6 @@ class PaintLayerTest : public PaintTestConfigurations, public RenderingTest {
RenderingTest::SetUp();
EnableCompositing();
}
-
- protected:
- PaintLayer* GetPaintLayerByElementId(const char* id) {
- return ToLayoutBoxModelObject(GetLayoutObjectByElementId(id))->Layer();
- }
};
INSTANTIATE_PAINT_TEST_CASE_P(PaintLayerTest);
@@ -255,7 +250,7 @@ TEST_P(PaintLayerTest, CompositedScrollingNoNeedsRepaint) {
EXPECT_EQ(LayoutPoint(-1000, -1000), content_layer->Location());
EXPECT_FALSE(content_layer->NeedsRepaint());
EXPECT_FALSE(scroll_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
TEST_P(PaintLayerTest, NonCompositedScrollingNeedsRepaint) {
@@ -285,7 +280,7 @@ TEST_P(PaintLayerTest, NonCompositedScrollingNeedsRepaint) {
EXPECT_EQ(LayoutPoint(-1000, -1000), content_layer->Location());
EXPECT_TRUE(scroll_layer->NeedsRepaint());
EXPECT_FALSE(content_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
TEST_P(PaintLayerTest, HasNonIsolatedDescendantWithBlendMode) {
@@ -324,9 +319,9 @@ TEST_P(PaintLayerTest, HasStickyPositionDescendant) {
EXPECT_TRUE(parent->HasStickyPositionDescendant());
EXPECT_FALSE(child->HasStickyPositionDescendant());
- GetDocument().getElementById("child")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(parent->HasStickyPositionDescendant());
EXPECT_FALSE(child->HasStickyPositionDescendant());
@@ -344,9 +339,9 @@ TEST_P(PaintLayerTest, HasFixedPositionDescendant) {
EXPECT_TRUE(parent->HasFixedPositionDescendant());
EXPECT_FALSE(child->HasFixedPositionDescendant());
- GetDocument().getElementById("child")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(parent->HasFixedPositionDescendant());
EXPECT_FALSE(child->HasFixedPositionDescendant());
@@ -371,9 +366,9 @@ TEST_P(PaintLayerTest, HasFixedAndStickyPositionDescendant) {
EXPECT_FALSE(child1->HasStickyPositionDescendant());
EXPECT_FALSE(child2->HasStickyPositionDescendant());
- GetDocument().getElementById("child1")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("child1")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(parent->HasFixedPositionDescendant());
EXPECT_FALSE(child1->HasFixedPositionDescendant());
@@ -382,9 +377,9 @@ TEST_P(PaintLayerTest, HasFixedAndStickyPositionDescendant) {
EXPECT_FALSE(child1->HasStickyPositionDescendant());
EXPECT_FALSE(child2->HasStickyPositionDescendant());
- GetDocument().getElementById("child2")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("child2")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(parent->HasFixedPositionDescendant());
EXPECT_FALSE(child1->HasFixedPositionDescendant());
@@ -406,16 +401,16 @@ TEST_P(PaintLayerTest, HasNonContainedAbsolutePositionDescendant) {
EXPECT_FALSE(parent->HasNonContainedAbsolutePositionDescendant());
EXPECT_FALSE(child->HasNonContainedAbsolutePositionDescendant());
- GetDocument().getElementById("child")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
"position: absolute");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(parent->HasNonContainedAbsolutePositionDescendant());
EXPECT_FALSE(child->HasNonContainedAbsolutePositionDescendant());
- GetDocument().getElementById("parent")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("parent")->setAttribute(html_names::kStyleAttr,
"position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(parent->HasNonContainedAbsolutePositionDescendant());
EXPECT_FALSE(child->HasNonContainedAbsolutePositionDescendant());
}
@@ -565,8 +560,8 @@ TEST_P(PaintLayerTest, SubsequenceCachingStackingContexts) {
GetDocument()
.getElementById("grandchild1")
- ->setAttribute(HTMLNames::styleAttr, "isolation: isolate");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, "isolation: isolate");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(parent->SupportsSubsequenceCaching());
EXPECT_FALSE(child1->SupportsSubsequenceCaching());
@@ -612,9 +607,9 @@ TEST_P(PaintLayerTest, NegativeZIndexChangeToPositive) {
EXPECT_TRUE(target->StackingNode()->HasNegativeZOrderList());
EXPECT_FALSE(target->StackingNode()->HasPositiveZOrderList());
- GetDocument().getElementById("child")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
"z-index: 1");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(target->StackingNode()->HasNegativeZOrderList());
EXPECT_TRUE(target->StackingNode()->HasPositiveZOrderList());
@@ -682,8 +677,8 @@ TEST_P(PaintLayerTest, Has3DTransformedDescendantChangeStyle) {
EXPECT_FALSE(child->Has3DTransformedDescendant());
GetDocument().getElementById("child")->setAttribute(
- HTMLNames::styleAttr, "transform: translateZ(1px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ html_names::kStyleAttr, "transform: translateZ(1px)");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(parent->Has3DTransformedDescendant());
EXPECT_FALSE(child->Has3DTransformedDescendant());
@@ -738,8 +733,8 @@ TEST_P(PaintLayerTest, DescendantDependentFlagsStopsAtThrottledFrames) {
// Move the child frame offscreen so it becomes available for throttling.
auto* iframe = ToHTMLIFrameElement(GetDocument().getElementById("iframe"));
- iframe->setAttribute(HTMLNames::styleAttr, "transform: translateY(5555px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ iframe->setAttribute(html_names::kStyleAttr, "transform: translateY(5555px)");
+ UpdateAllLifecyclePhasesForTest();
// Ensure intersection observer notifications get delivered.
test::RunPendingTasks();
EXPECT_FALSE(GetDocument().View()->IsHiddenForThrottling());
@@ -765,7 +760,7 @@ TEST_P(PaintLayerTest, DescendantDependentFlagsStopsAtThrottledFrames) {
// Also check that the rest of the lifecycle succeeds without crashing due
// to a stale m_needsDescendantDependentFlagsUpdate.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Still dirty, because the frame was throttled.
EXPECT_TRUE(ChildDocument()
@@ -775,7 +770,7 @@ TEST_P(PaintLayerTest, DescendantDependentFlagsStopsAtThrottledFrames) {
->needs_descendant_dependent_flags_update_);
}
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(ChildDocument()
.View()
->GetLayoutView()
@@ -808,7 +803,7 @@ TEST_P(PaintLayerTest, PaintInvalidationOnNonCompositedScroll) {
scroller->GetScrollableArea()->SetScrollOffset(ScrollOffset(0, 20),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(0, 30, 50, 10),
content_layer->FirstFragment().VisualRect());
EXPECT_EQ(LayoutRect(0, 30, 50, 5), content->FirstFragment().VisualRect());
@@ -837,7 +832,7 @@ TEST_P(PaintLayerTest, PaintInvalidationOnCompositedScroll) {
scroller->GetScrollableArea()->SetScrollOffset(ScrollOffset(0, 20),
kProgrammaticScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutRect(0, 30, 50, 10),
content_layer->FirstFragment().VisualRect());
EXPECT_EQ(LayoutRect(0, 30, 50, 5), content->FirstFragment().VisualRect());
@@ -1353,7 +1348,7 @@ TEST_P(PaintLayerTest, NeedsRepaintOnSelfPaintingStatusChange) {
// Removing column-width: 10px makes target layer no longer self-painting,
// and change its compositing container. The original compositing container
// span_layer should be marked NeedsRepaint.
- target_element->setAttribute(HTMLNames::styleAttr,
+ target_element->setAttribute(html_names::kStyleAttr,
"overflow: hidden; float: left");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(target_layer->IsSelfPaintingLayer());
@@ -1361,7 +1356,7 @@ TEST_P(PaintLayerTest, NeedsRepaintOnSelfPaintingStatusChange) {
EXPECT_TRUE(target_layer->NeedsRepaint());
EXPECT_TRUE(target_layer->CompositingContainer()->NeedsRepaint());
EXPECT_TRUE(span_layer->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
TEST_P(PaintLayerTest, NeedsRepaintOnRemovingStackedLayer) {
@@ -1381,15 +1376,15 @@ TEST_P(PaintLayerTest, NeedsRepaintOnRemovingStackedLayer) {
EXPECT_NE(body_layer, target_layer->CompositingContainer());
auto* old_compositing_container = target_layer->CompositingContainer();
- body->setAttribute(HTMLNames::styleAttr, "margin-top: 0");
- target_element->setAttribute(HTMLNames::styleAttr, "top: 0");
+ body->setAttribute(html_names::kStyleAttr, "margin-top: 0");
+ target_element->setAttribute(html_names::kStyleAttr, "top: 0");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(target_object->HasLayer());
EXPECT_TRUE(body_layer->NeedsRepaint());
EXPECT_TRUE(old_compositing_container->NeedsRepaint());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
TEST_P(PaintLayerTest, FrameViewContentSize) {
@@ -1488,7 +1483,7 @@ TEST_P(PaintLayerTest, SquashingOffsets) {
GetDocument().View()->LayoutViewport()->ScrollBy(ScrollOffset(0, 25),
kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
PaintLayer::MapPointInPaintInvalidationContainerToBacking(
squashed->GetLayoutObject(), point);
@@ -1742,4 +1737,46 @@ TEST_P(PaintLayerTest, HitTestFirstLetterPseudoElementDisplayContents) {
result.InnerPossiblyPseudoNode());
}
+TEST_P(PaintLayerTest, BackgroundIsKnownToBeOpaqueInRectChildren) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ div {
+ width: 100px;
+ height: 100px;
+ position: relative;
+ isolation: isolate;
+ }
+ </style>
+ <div id='target'>
+ <div style='background: blue'></div>
+ </div>
+ )HTML");
+
+ PaintLayer* target_layer = GetPaintLayerByElementId("target");
+ EXPECT_TRUE(target_layer->BackgroundIsKnownToBeOpaqueInRect(
+ LayoutRect(0, 0, 100, 100), true));
+ EXPECT_FALSE(target_layer->BackgroundIsKnownToBeOpaqueInRect(
+ LayoutRect(0, 0, 100, 100), false));
+}
+
+TEST_P(PaintLayerTest, ChangeAlphaNeedsCompositingInputs) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #target {
+ background: white;
+ width: 100px;
+ height: 100px;
+ position: relative;
+ }
+ </style>
+ <div id='target'>
+ </div>
+ )HTML");
+ PaintLayer* target = GetPaintLayerByElementId("target");
+ StyleDifference diff;
+ diff.SetHasAlphaChanged();
+ target->StyleDidChange(diff, target->GetLayoutObject().Style());
+ EXPECT_TRUE(target->NeedsCompositingInputsUpdate());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
index 5142a25165c..1c65f407cff 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
@@ -98,7 +98,7 @@ void VisualViewportPaintPropertyTreeBuilder::Update(
context.fixed_position.scroll = visual_viewport.GetScrollNode();
#if DCHECK_IS_ON()
- PaintPropertyTreePrinter::UpdateDebugNames(visual_viewport);
+ paint_property_tree_printer::UpdateDebugNames(visual_viewport);
#endif
}
@@ -142,7 +142,7 @@ class FragmentPaintPropertyTreeBuilder {
}
#if DCHECK_IS_ON()
if (properties_)
- PaintPropertyTreePrinter::UpdateDebugNames(object_, *properties_);
+ paint_property_tree_printer::UpdateDebugNames(object_, *properties_);
#endif
}
@@ -322,7 +322,8 @@ static bool NeedsIsolationNodes(const LayoutObject& object) {
// Layout view establishes isolation with the exception of local roots (since
// they are already essentially isolated).
- if (object.IsLayoutView()) {
+ if (RuntimeEnabledFeatures::LayoutViewIsolationNodesEnabled() &&
+ object.IsLayoutView()) {
const auto* parent_frame = object.GetFrame()->Tree().Parent();
return parent_frame && parent_frame->IsLocalFrame();
}
@@ -588,8 +589,14 @@ static CompositingReasons CompositingReasonsForTransform(const LayoutBox& box) {
if (CompositingReasonFinder::RequiresCompositingForTransform(box))
compositing_reasons |= CompositingReason::k3DTransform;
- if (CompositingReasonFinder::RequiresCompositingForTransformAnimation(style))
- compositing_reasons |= CompositingReason::kActiveTransformAnimation;
+ // Currently, we create transform nodes for an element whenever any property
+ // is being animated so that the existence of the effect node implies the
+ // existence of all nodes.
+ // TODO(flackr): Check for nodes for each KeyframeModel target
+ // property instead of creating all nodes and only create a transform node
+ // if needed, https://crbug.com/900241
+ compositing_reasons |=
+ CompositingReasonFinder::CompositingReasonsForAnimation(style);
if (style.HasWillChangeCompositingHint() &&
!style.SubtreeWillChangeContents())
@@ -681,7 +688,8 @@ void FragmentPaintPropertyTreeBuilder::UpdateTransform() {
? TransformPaintPropertyNode::BackfaceVisibility::kHidden
: TransformPaintPropertyNode::BackfaceVisibility::kVisible;
state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
- object_.UniqueId(), CompositorElementIdNamespace::kPrimary);
+ object_.UniqueId(),
+ CompositorElementIdNamespace::kPrimaryTransform);
}
OnUpdate(properties_->UpdateTransform(*context_.current.transform,
@@ -769,7 +777,13 @@ static bool NeedsEffect(const LayoutObject& object) {
if (style.Opacity() != 1.0f || style.HasWillChangeOpacityHint())
return true;
- if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation(style))
+ // Currently, we create effect nodes for an element whenever any property
+ // is being animated so that the existence of the effect node implies the
+ // existence of all nodes.
+ // TODO(flackr): Check for nodes for each KeyframeModel target
+ // property instead of creating all nodes and only create an effect node
+ // if needed, https://crbug.com/900241
+ if (CompositingReasonFinder::CompositingReasonsForAnimation(style))
return true;
if (object.StyleRef().HasMask())
@@ -883,13 +897,25 @@ void FragmentPaintPropertyTreeBuilder::UpdateEffect() {
// We may begin to composite our subtree prior to an animation starts,
// but a compositor element ID is only needed when an animation is
// current.
- if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation(
- style)) {
- state.direct_compositing_reasons =
- CompositingReason::kActiveOpacityAnimation;
+ //
+ // Currently, we use the existence of this id to check if effect nodes
+ // have been created for animations on this element.
+ // TODO(flackr): Check for nodes for each KeyframeModel target
+ // property instead of creating all nodes and create each type of
+ // node as needed, https://crbug.com/900241
+ state.direct_compositing_reasons =
+ CompositingReasonFinder::CompositingReasonsForAnimation(style);
+ if (state.direct_compositing_reasons) {
+ state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
+ object_.UniqueId(), CompositorElementIdNamespace::kPrimaryEffect);
+ } else {
+ // The effect node CompositorElementId is used to uniquely identify
+ // renderpasses so even if we don't need one for animations we still
+ // need to set an id. Using kPrimary avoids confusing cc::Animation
+ // into thinking the element has been composited for animations.
+ state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
+ object_.UniqueId(), CompositorElementIdNamespace::kPrimary);
}
- state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
- object_.UniqueId(), CompositorElementIdNamespace::kPrimary);
}
OnUpdate(properties_->UpdateEffect(*context_.current_effect,
std::move(state)));
@@ -984,15 +1010,18 @@ void FragmentPaintPropertyTreeBuilder::UpdateLinkHighlightEffect() {
}
static bool NeedsFilter(const LayoutObject& object) {
+ // Currently, we create filter nodes for an element whenever any property
+ // is being animated so that the existence of the effect node implies the
+ // existence of all animation nodes.
+ // TODO(flackr): Check for nodes for each KeyframeModel target
+ // property instead of creating all nodes and only create a filter node
+ // if needed, https://crbug.com/900241
// TODO(trchen): SVG caches filters in SVGResources. Implement it.
- if (object.IsBoxModelObject() && ToLayoutBoxModelObject(object).Layer() &&
- (object.StyleRef().HasFilter() || object.HasReflection() ||
- CompositingReasonFinder::RequiresCompositingForFilterAnimation(
- object.StyleRef())))
- return true;
- if (object.IsLayoutImage() && ToLayoutImage(object).ShouldInvertColor())
- return true;
- return false;
+ return (object.IsBoxModelObject() && ToLayoutBoxModelObject(object).Layer() &&
+ (object.StyleRef().HasFilter() || object.HasReflection() ||
+ object.HasBackdropFilter() ||
+ CompositingReasonFinder::CompositingReasonsForAnimation(
+ object.StyleRef())));
}
void FragmentPaintPropertyTreeBuilder::UpdateFilter() {
@@ -1005,23 +1034,15 @@ void FragmentPaintPropertyTreeBuilder::UpdateFilter() {
state.local_transform_space = context_.current.transform;
state.filters_origin = FloatPoint(context_.current.paint_offset);
- auto* layer = ToLayoutBoxModelObject(object_).Layer();
- if (layer) {
+ if (auto* layer = ToLayoutBoxModelObject(object_).Layer()) {
// Try to use the cached filter.
if (properties_->Filter())
state.filter = properties_->Filter()->Filter();
- if (object_.IsLayoutImage() &&
- ToLayoutImage(object_).ShouldInvertColor())
- state.filter.AppendInvertFilter(1.0f);
-
layer->UpdateCompositorFilterOperationsForFilter(state.filter);
+ layer->UpdateCompositorFilterOperationsForBackdropFilter(
+ state.backdrop_filter);
layer->ClearFilterOnEffectNodeDirty();
- } else {
- DCHECK(object_.IsLayoutImage() &&
- ToLayoutImage(object_).ShouldInvertColor());
- state.filter = CompositorFilterOperations();
- state.filter.AppendInvertFilter(1.0f);
}
// The CSS filter spec didn't specify how filters interact with overflow
@@ -1053,11 +1074,10 @@ void FragmentPaintPropertyTreeBuilder::UpdateFilter() {
// We may begin to composite our subtree prior to an animation starts,
// but a compositor element ID is only needed when an animation is
// current.
+ // TODO(flackr): Only set a compositing reason for filter animation
+ // once we no longer need to create all nodes, https://crbug.com/900241
state.direct_compositing_reasons =
- CompositingReasonFinder::RequiresCompositingForFilterAnimation(
- style)
- ? CompositingReason::kActiveFilterAnimation
- : CompositingReason::kNone;
+ CompositingReasonFinder::CompositingReasonsForAnimation(style);
DCHECK(!style.HasCurrentFilterAnimation() ||
state.direct_compositing_reasons != CompositingReason::kNone);
@@ -1227,10 +1247,7 @@ void FragmentPaintPropertyTreeBuilder::UpdateLocalBorderBoxContext() {
if (!NeedsPaintPropertyUpdate())
return;
- if (!object_.HasLayer() && !NeedsPaintOffsetTranslation(object_) &&
- !NeedsFilter(object_) && !NeedsOverflowClip(object_)) {
- fragment_data_.ClearLocalBorderBoxProperties();
- } else {
+ if (object_.HasLayer() || properties_) {
PropertyTreeState local_border_box =
PropertyTreeState(context_.current.transform, context_.current.clip,
context_.current_effect);
@@ -1240,6 +1257,8 @@ void FragmentPaintPropertyTreeBuilder::UpdateLocalBorderBoxContext() {
property_added_or_removed_ = true;
fragment_data_.SetLocalBorderBoxProperties(std::move(local_border_box));
+ } else {
+ fragment_data_.ClearLocalBorderBoxProperties();
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc
index 44122e77bcd..69b19f58c75 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc
@@ -126,7 +126,8 @@ TEST_P(PaintPropertyTreeBuilderTest, FixedPosition) {
transformed_scroll->setScrollTop(5);
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// target1 is a fixed-position element inside an absolute-position scrolling
// element. It should be attached under the viewport to skip scrolling and
@@ -212,7 +213,8 @@ TEST_P(PaintPropertyTreeBuilderTest, PositionAndScroll) {
Element* scroller = GetDocument().getElementById("scroller");
scroller->scrollTo(0, 100);
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
const ObjectPaintProperties* scroller_properties =
scroller->GetLayoutObject()->FirstFragment().PaintProperties();
EXPECT_EQ(TransformationMatrix().Translate(0, -100),
@@ -366,7 +368,7 @@ TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollVerticalRL) {
EXPECT_EQ(FloatRoundedRect(10, 10, 85, 85), overflow_clip->ClipRect());
scroller->GetScrollableArea()->ScrollBy(ScrollOffset(-100, 0), kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Only scroll_translation is affected by scrolling.
EXPECT_EQ(TransformationMatrix().Translate(-215, 0),
@@ -420,7 +422,7 @@ TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollRTL) {
EXPECT_EQ(FloatRoundedRect(25, 10, 85, 85), overflow_clip->ClipRect());
scroller->GetScrollableArea()->ScrollBy(ScrollOffset(-100, 0), kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Only scroll_translation is affected by scrolling.
EXPECT_EQ(TransformationMatrix().Translate(-215, 0),
@@ -478,7 +480,7 @@ TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollVerticalRLMulticol) {
ToLayoutBox(GetLayoutObjectByElementId("scroller"))
->GetScrollableArea()
->ScrollBy(ScrollOffset(-100, 200), kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
check_fragments();
}
@@ -488,7 +490,8 @@ TEST_P(PaintPropertyTreeBuilderTest, DocScrollingTraditional) {
GetDocument().domWindow()->scrollTo(0, 100);
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_EQ(TransformationMatrix(), DocPreTranslation()->Matrix());
EXPECT_EQ(
GetDocument().GetPage()->GetVisualViewport().GetScrollTranslationNode(),
@@ -558,8 +561,8 @@ TEST_P(PaintPropertyTreeBuilderTest, Perspective) {
inner->GetLayoutObject(),
GetDocument().View()->GetLayoutView());
- perspective->setAttribute(HTMLNames::styleAttr, "perspective: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ perspective->setAttribute(html_names::kStyleAttr, "perspective: 200px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix().ApplyPerspective(200),
perspective_properties->Perspective()->Matrix());
EXPECT_EQ(FloatPoint3D(250, 250, 0),
@@ -574,8 +577,9 @@ TEST_P(PaintPropertyTreeBuilderTest, Perspective) {
perspective_properties->Perspective()->Parent());
}
- perspective->setAttribute(HTMLNames::styleAttr, "perspective-origin: 5% 20%");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ perspective->setAttribute(html_names::kStyleAttr,
+ "perspective-origin: 5% 20%");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix().ApplyPerspective(100),
perspective_properties->Perspective()->Matrix());
EXPECT_EQ(FloatPoint3D(70, 160, 0),
@@ -625,17 +629,17 @@ TEST_P(PaintPropertyTreeBuilderTest, Transform) {
GetDocument().View()->GetLayoutView());
transform->setAttribute(
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
"margin-left: 50px; margin-top: 100px; width: 400px; height: 300px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr,
transform->GetLayoutObject()->FirstFragment().PaintProperties());
transform->setAttribute(
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
"margin-left: 50px; margin-top: 100px; width: 400px; height: 300px; "
"transform: translate3d(123px, 456px, 789px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix().Translate3d(123, 456, 789),
transform->GetLayoutObject()
->FirstFragment()
@@ -700,9 +704,12 @@ TEST_P(PaintPropertyTreeBuilderTest,
}
TEST_P(PaintPropertyTreeBuilderTest,
- OpacityAnimationDoesNotCreateTransformNode) {
+ OpacityAnimationCreatesTransformAndFilterNodes) {
LoadTestData("opacity-animation.html");
- EXPECT_EQ(nullptr, PaintPropertiesForElement("target")->Transform());
+ // TODO(flackr): Verify that after https://crbug.com/900241 is fixed we no
+ // longer create transform or filter nodes for opacity animations.
+ EXPECT_NE(nullptr, PaintPropertiesForElement("target")->Transform());
+ EXPECT_NE(nullptr, PaintPropertiesForElement("target")->Filter());
}
TEST_P(PaintPropertyTreeBuilderTest,
@@ -752,17 +759,17 @@ TEST_P(PaintPropertyTreeBuilderTest, WillChangeTransform) {
GetDocument().View()->GetLayoutView());
transform->setAttribute(
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
"margin-left: 50px; margin-top: 100px; width: 400px; height: 300px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr,
transform->GetLayoutObject()->FirstFragment().PaintProperties());
transform->setAttribute(
- HTMLNames::styleAttr,
+ html_names::kStyleAttr,
"margin-left: 50px; margin-top: 100px; width: 400px; height: 300px; "
"will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix(), transform->GetLayoutObject()
->FirstFragment()
.PaintProperties()
@@ -1061,7 +1068,7 @@ TEST_P(PaintPropertyTreeBuilderTest, EffectNodesAcrossHTMLSVGBoundary) {
TEST_P(PaintPropertyTreeBuilderTest, EffectNodesAcrossSVGHTMLBoundary) {
SetBodyInnerHTML(R"HTML(
<svg id='svgRootWithOpacity' style='opacity: 0.3;'>
- <foreignObject id='foreignObjectWithOpacity' opacity='0.4'>
+ <foreignObject id='foreignObjectWithOpacity' opacity='0.4' style='overflow: visible;'>
<body>
<span id='spanWithOpacity' style='opacity: 0.5'/>
</body>
@@ -1624,7 +1631,7 @@ TEST_P(PaintPropertyTreeBuilderTest, ControlClipInsideForeignObject) {
<div style='column-count:2;'>
<div style='columns: 2'>
<svg style='width: 500px; height: 500px;'>
- <foreignObject>
+ <foreignObject style='overflow: visible;'>
<input id='button' style='width:345px; height:123px'
value='some text'/>
</foreignObject>
@@ -1751,7 +1758,8 @@ TEST_P(PaintPropertyTreeBuilderTest, TransformNodesAcrossSubframes) {
)HTML");
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
LayoutObject* div_with_transform =
GetLayoutObjectByElementId("divWithTransform");
@@ -1812,6 +1820,9 @@ TEST_P(PaintPropertyTreeBuilderTest, TransformNodesAcrossSubframes) {
}
TEST_P(PaintPropertyTreeBuilderTest, FramesEstablishIsolation) {
+ if (!RuntimeEnabledFeatures::LayoutViewIsolationNodesEnabled())
+ return;
+
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -1842,7 +1853,8 @@ TEST_P(PaintPropertyTreeBuilderTest, FramesEstablishIsolation) {
)HTML");
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
LayoutObject* frame = ChildFrame().View()->GetLayoutView();
const auto& frame_contents_properties =
@@ -1899,9 +1911,10 @@ TEST_P(PaintPropertyTreeBuilderTest, FramesEstablishIsolation) {
// This causes a tree topology change which forces the subtree to be updated.
// However, isolation stops this recursion.
- GetDocument().getElementById("parent")->setAttribute(HTMLNames::classAttr,
+ GetDocument().getElementById("parent")->setAttribute(html_names::kClassAttr,
"transformed");
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// Verify that our clobbered state is still clobbered.
EXPECT_EQ(TransformationMatrix().Translate(123, 321),
@@ -1938,7 +1951,8 @@ TEST_P(PaintPropertyTreeBuilderTest, TransformNodesInTransformedSubframes) {
<div id='transform'></div>
)HTML");
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
// Assert that we have the following tree structure:
// ...
@@ -3251,8 +3265,8 @@ TEST_P(PaintPropertyTreeBuilderTest, CachedProperties) {
// Change transform of b. B's transform node should be a new node with the new
// value, and a and c's transform nodes should be unchanged (with c's parent
// adjusted).
- b->setAttribute(HTMLNames::styleAttr, "transform: translate(111px, 222px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ b->setAttribute(html_names::kStyleAttr, "transform: translate(111px, 222px)");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(a_properties,
a->GetLayoutObject()->FirstFragment().PaintProperties());
@@ -3280,8 +3294,8 @@ TEST_P(PaintPropertyTreeBuilderTest, CachedProperties) {
// Remove transform from b. B's transform node should be removed from the
// tree, and a and c's transform nodes should be unchanged (with c's parent
// adjusted).
- b->setAttribute(HTMLNames::styleAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ b->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(a_properties,
a->GetLayoutObject()->FirstFragment().PaintProperties());
@@ -3304,8 +3318,8 @@ TEST_P(PaintPropertyTreeBuilderTest, CachedProperties) {
// Re-add transform to b. B's transform node should be inserted into the tree,
// and a and c's transform nodes should be unchanged (with c's parent
// adjusted).
- b->setAttribute(HTMLNames::styleAttr, "transform: translate(4px, 5px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ b->setAttribute(html_names::kStyleAttr, "transform: translate(4px, 5px)");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(a_properties,
a->GetLayoutObject()->FirstFragment().PaintProperties());
@@ -3714,7 +3728,7 @@ TEST_P(PaintPropertyTreeBuilderTest, OverflowHiddenScrollProperties) {
Element* overflow_hidden = GetDocument().getElementById("overflowHidden");
overflow_hidden->setScrollTop(37);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const ObjectPaintProperties* overflow_hidden_scroll_properties =
overflow_hidden->GetLayoutObject()->FirstFragment().PaintProperties();
@@ -3747,7 +3761,7 @@ TEST_P(PaintPropertyTreeBuilderTest, FrameOverflowHiddenScrollProperties) {
GetDocument().domWindow()->scrollTo(0, 37);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix().Translate(0, -37),
DocScrollTranslation()->Matrix());
@@ -3796,7 +3810,7 @@ TEST_P(PaintPropertyTreeBuilderTest, NestedScrollProperties) {
Element* overflow_b = GetDocument().getElementById("overflowB");
overflow_b->setScrollTop(41);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const ObjectPaintProperties* overflow_a_scroll_properties =
overflow_a->GetLayoutObject()->FirstFragment().PaintProperties();
@@ -3892,7 +3906,7 @@ TEST_P(PaintPropertyTreeBuilderTest, PositionedScrollerIsNotNested) {
Element* fixed_overflow = GetDocument().getElementById("fixedOverflow");
fixed_overflow->setScrollTop(43);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The frame should scroll due to the "forceScroll" element.
EXPECT_NE(nullptr, DocScroll());
@@ -3983,7 +3997,7 @@ TEST_P(PaintPropertyTreeBuilderTest, NestedPositionedScrollProperties) {
Element* overflow_b = GetDocument().getElementById("overflowB");
overflow_b->setScrollTop(41);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const ObjectPaintProperties* overflow_a_scroll_properties =
overflow_a->GetLayoutObject()->FirstFragment().PaintProperties();
@@ -4111,7 +4125,7 @@ TEST_P(PaintPropertyTreeBuilderTest, PaintOffsetsUnderMultiColumnScrolled) {
LayoutObject* scroller = GetLayoutObjectByElementId("scroller");
ToLayoutBox(scroller)->GetScrollableArea()->ScrollBy(ScrollOffset(0, 300),
kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatSize(8, 8), scroller->FirstFragment()
.PaintProperties()
@@ -4202,7 +4216,7 @@ TEST_P(PaintPropertyTreeBuilderTest,
GetDocument().View()->LayoutViewport()->ScrollBy(ScrollOffset(0, 25),
kUserScroll);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_TRUE(multicol_container->FirstFragment().NextFragment());
ASSERT_FALSE(
@@ -4386,12 +4400,6 @@ TEST_P(PaintPropertyTreeBuilderTest,
}
TEST_P(PaintPropertyTreeBuilderTest, CompositedUnderMultiColumn) {
- // TODO(crbug.com/796768): Currently this test crashes for SPv2 when mapping
- // layer clip rects from one fragment to another. May need to adjust fragment
- // clip hierarchy to fix the crash.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0; }</style>
<div id='multicol' style='columns:3; column-fill:auto; column-gap: 0;
@@ -4430,31 +4438,32 @@ TEST_P(PaintPropertyTreeBuilderTest, CompositedUnderMultiColumn) {
EXPECT_EQ(LayoutPoint(100, 100), FragmentAt(composited, 0).PaintOffset());
EXPECT_EQ(LayoutPoint(100, -200),
FragmentAt(composited, 0).PaginationOffset());
- EXPECT_EQ(LayoutUnit(), FragmentAt(composited, 0).LogicalTopInFlowThread());
+ EXPECT_EQ(LayoutUnit(200),
+ FragmentAt(composited, 0).LogicalTopInFlowThread());
EXPECT_EQ(LayoutPoint(200, -100), FragmentAt(composited, 1).PaintOffset());
EXPECT_EQ(LayoutPoint(200, -400),
FragmentAt(composited, 1).PaginationOffset());
- EXPECT_EQ(LayoutUnit(200),
+ EXPECT_EQ(LayoutUnit(400),
FragmentAt(composited, 1).LogicalTopInFlowThread());
EXPECT_EQ(2u, NumFragments(non_composited_child));
EXPECT_EQ(LayoutPoint(100, 100),
FragmentAt(non_composited_child, 0).PaintOffset());
EXPECT_EQ(LayoutPoint(100, -200),
FragmentAt(non_composited_child, 0).PaginationOffset());
- EXPECT_EQ(LayoutUnit(),
+ EXPECT_EQ(LayoutUnit(200),
FragmentAt(non_composited_child, 0).LogicalTopInFlowThread());
EXPECT_EQ(LayoutPoint(200, -100),
FragmentAt(non_composited_child, 1).PaintOffset());
EXPECT_EQ(LayoutPoint(200, -400),
FragmentAt(non_composited_child, 1).PaginationOffset());
- EXPECT_EQ(LayoutUnit(200),
+ EXPECT_EQ(LayoutUnit(400),
FragmentAt(non_composited_child, 1).LogicalTopInFlowThread());
EXPECT_EQ(1u, NumFragments(composited_child));
EXPECT_EQ(LayoutPoint(200, 50),
FragmentAt(composited_child, 0).PaintOffset());
EXPECT_EQ(LayoutPoint(200, -400),
FragmentAt(composited_child, 0).PaginationOffset());
- EXPECT_EQ(LayoutUnit(),
+ EXPECT_EQ(LayoutUnit(400),
FragmentAt(composited_child, 0).LogicalTopInFlowThread());
} else {
// SPv1 forces single fragment for composited layers.
@@ -4482,12 +4491,6 @@ TEST_P(PaintPropertyTreeBuilderTest, CompositedUnderMultiColumn) {
}
TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedY) {
- // TODO(crbug.com/796768): Currently this test crashes for SPv2 when mapping
- // layer clip rects from one fragment to another. May need to adjust fragment
- // clip hierarchy to fix the crash.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<div id='paged' style='overflow: -webkit-paged-y; column-gap: 0;
width: 100px; height: 100px'>
@@ -4509,12 +4512,6 @@ TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedY) {
}
TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedYWithGap) {
- // TODO(crbug.com/796768): Currently this test crashes for SPv2 when mapping
- // layer clip rects from one fragment to another. May need to adjust fragment
- // clip hierarchy to fix the crash.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<div id='paged' style='overflow: -webkit-paged-y; column-gap: 10px;
width: 100px; height: 100px'>
@@ -4536,12 +4533,6 @@ TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedYWithGap) {
}
TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedX) {
- // TODO(crbug.com/796768): Currently this test crashes for SPv2 when mapping
- // layer clip rects from one fragment to another. May need to adjust fragment
- // clip hierarchy to fix the crash.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<div id='paged' style='overflow: -webkit-paged-x; column-gap: 0;
width: 100px; height: 100px'>
@@ -4563,12 +4554,6 @@ TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedX) {
}
TEST_P(PaintPropertyTreeBuilderTest, FragmentsInPagedYVerticalRL) {
- // TODO(crbug.com/796768): Currently this test crashes for SPv2 when mapping
- // layer clip rects from one fragment to another. May need to adjust fragment
- // clip hierarchy to fix the crash.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<div id='paged' style='overflow: -webkit-paged-y; column-gap: 0;
width: 100px; height: 100px; writing-mode: vertical-rl'>
@@ -4636,18 +4621,12 @@ TEST_P(PaintPropertyTreeBuilderTest, FrameUnderMulticol) {
)HTML");
// This should not crash on duplicated subsequences in the iframe.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// TODO(crbug.com/797779): Add code to verify fragments under the iframe.
}
TEST_P(PaintPropertyTreeBuilderTest, CompositedMulticolFrameUnderMulticol) {
- // TODO(crbug.com/796768): Currently this test crashes for SPv2 when mapping
- // layer clip rects from one fragment to another. May need to adjust fragment
- // clip hierarchy to fix the crash.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0 }</style>
<div style='columns: 3; column-gap: 0; column-fill: auto;
@@ -4666,7 +4645,7 @@ TEST_P(PaintPropertyTreeBuilderTest, CompositedMulticolFrameUnderMulticol) {
)HTML");
// This should not crash on duplicated subsequences in the iframe.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// TODO(crbug.com/797779): Add code to verify fragments under the iframe.
}
@@ -4692,8 +4671,8 @@ TEST_P(PaintPropertyTreeBuilderTest,
EXPECT_EQ(LayoutUnit(20), target->FirstFragment().LogicalTopInFlowThread());
Element* target_element = GetDocument().getElementById("target");
- target_element->setAttribute(HTMLNames::styleAttr, "position: absolute");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target_element->setAttribute(html_names::kStyleAttr, "position: absolute");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutPoint(0, 0), target->FirstFragment().PaginationOffset());
EXPECT_EQ(LayoutUnit(), target->FirstFragment().LogicalTopInFlowThread());
}
@@ -4851,8 +4830,8 @@ TEST_P(PaintPropertyTreeBuilderTest, ChangePositionUpdateDescendantProperties) {
descendant->FirstFragment().LocalBorderBoxProperties().Clip());
ToElement(ancestor->GetNode())
- ->setAttribute(HTMLNames::styleAttr, "position: static");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, "position: static");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(ancestor->FirstFragment().PaintProperties()->OverflowClip(),
descendant->FirstFragment().LocalBorderBoxProperties().Clip());
}
@@ -4877,6 +4856,9 @@ TEST_P(PaintPropertyTreeBuilderTest,
SetBodyInnerHTML("<div id='target' style='opacity: 0.5'></div");
const ObjectPaintProperties* properties = PaintPropertiesForElement("target");
EXPECT_TRUE(properties->Effect());
+ // TODO(flackr): Revisit whether effect ElementId should still exist when
+ // animations are no longer keyed off of the existence it:
+ // https://crbug.com/900241
EXPECT_NE(CompositorElementId(),
properties->Effect()->GetCompositorElementId());
}
@@ -5277,7 +5259,7 @@ TEST_P(PaintPropertyTreeBuilderTest, ScrollBoundsOffset) {
Element* scroller = GetDocument().getElementById("scroller");
scroller->setScrollTop(42);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const ObjectPaintProperties* scroll_properties =
scroller->GetLayoutObject()->FirstFragment().PaintProperties();
@@ -5306,18 +5288,18 @@ TEST_P(PaintPropertyTreeBuilderTest, ScrollBoundsOffset) {
// And the scroll node should not.
EXPECT_EQ(IntRect(0, 0, 100, 100), scroll_node->ContainerRect());
- scroller->setAttribute(HTMLNames::styleAttr, "border: 20px solid black;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ scroller->setAttribute(html_names::kStyleAttr, "border: 20px solid black;");
+ UpdateAllLifecyclePhasesForTest();
// The paint offset node should be offset by the margin.
EXPECT_EQ(FloatSize(7, 11),
paint_offset_translation->Matrix().To2DTranslation());
// The scroll node should be offset by the border.
EXPECT_EQ(IntRect(20, 20, 100, 100), scroll_node->ContainerRect());
- scroller->setAttribute(HTMLNames::styleAttr,
+ scroller->setAttribute(html_names::kStyleAttr,
"border: 20px solid black;"
"transform: translate(20px, 30px);");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The scroll node's offset should not include margin if it has already been
// included in a paint offset node.
EXPECT_EQ(IntRect(20, 20, 100, 100), scroll_node->ContainerRect());
@@ -5360,8 +5342,8 @@ TEST_P(PaintPropertyTreeBuilderTest, BackfaceHidden) {
EXPECT_EQ(nullptr, transform);
}
- ToElement(target->GetNode())->setAttribute(HTMLNames::styleAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ToElement(target->GetNode())->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(LayoutPoint(60, 50), target->FirstFragment().PaintOffset());
EXPECT_EQ(nullptr, target->FirstFragment().PaintProperties());
}
@@ -5436,7 +5418,7 @@ TEST_P(PaintPropertyTreeBuilderTest, ImageBorderRadius) {
TEST_P(PaintPropertyTreeBuilderTest, FrameClipWhenPrinting) {
SetBodyInnerHTML("<iframe></iframe>");
SetChildFrameHTML("");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// When not printing, both main and child frame views have content clip.
auto* const main_frame_doc = &GetDocument();
@@ -5458,7 +5440,7 @@ TEST_P(PaintPropertyTreeBuilderTest, FrameClipWhenPrinting) {
DocContentClip(child_frame_doc)->ClipRect().Rect());
GetFrame().EndPrinting();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// When only the child frame is printing, it should not have content clip but
// the main frame still have (which doesn't matter though).
@@ -5585,7 +5567,7 @@ TEST_P(PaintPropertyTreeBuilderTest,
EXPECT_FALSE(ToLayoutBoxModelObject(target)->Layer()->NeedsRepaint());
- opacity_element->setAttribute(HTMLNames::styleAttr, "opacity: 0.5");
+ opacity_element->setAttribute(html_names::kStyleAttr, "opacity: 0.5");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
// All paint chunks contained by the new opacity effect node need to be
@@ -5664,7 +5646,7 @@ TEST_P(PaintPropertyTreeBuilderTest, RootHasCompositedScrolling) {
// Remove scrolling from the root.
Element* force_scroll_element = GetDocument().getElementById("forceScroll");
- force_scroll_element->setAttribute(HTMLNames::styleAttr, "");
+ force_scroll_element->setAttribute(html_names::kStyleAttr, "");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
// TODO(crbug.com/732611): SPv2 invalidations are incorrect if there is
// scrolling.
@@ -5685,7 +5667,7 @@ TEST_P(PaintPropertyTreeBuilderTest, IframeDoesNotRequireCompositedScrolling) {
SetChildFrameHTML(R"HTML(
<div id='forceInnerScroll' style='height: 2000px'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
EXPECT_TRUE(DocScrollTranslation()->HasDirectCompositingReasons());
@@ -5776,12 +5758,12 @@ TEST_P(PaintPropertyTreeBuilderTest, ClipHitTestChangeDoesNotCauseFullRepaint) {
</html>
)HTML");
CHECK(GetDocument().GetPage()->GetScrollbarTheme().UsesOverlayScrollbars());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* child_layer = ToLayoutBox(GetLayoutObjectByElementId("child"))->Layer();
EXPECT_FALSE(child_layer->NeedsRepaint());
- GetDocument().body()->setAttribute(HTMLNames::classAttr, "noscrollbars");
+ GetDocument().body()->setAttribute(html_names::kClassAttr, "noscrollbars");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(child_layer->NeedsRepaint());
}
@@ -5801,7 +5783,7 @@ TEST_P(PaintPropertyTreeBuilderTest, ClipPathInheritanceWithoutMutation) {
child->FirstFragment().LocalBorderBoxProperties().Clip();
child->SetNeedsPaintPropertyUpdate();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* new_clip_state =
child->FirstFragment().LocalBorderBoxProperties().Clip();
@@ -5855,7 +5837,7 @@ TEST_P(PaintPropertyTreeBuilderTest, RepeatingFixedPositionInPagedMedia) {
<div id="normal" style="height: 1000px"></div>
)HTML");
GetDocument().domWindow()->scrollTo(0, 200);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* fixed = GetLayoutObjectByElementId("fixed");
EXPECT_FALSE(fixed->IsFixedPositionObjectInPagedMedia());
@@ -5872,6 +5854,9 @@ TEST_P(PaintPropertyTreeBuilderTest, RepeatingFixedPositionInPagedMedia) {
FloatSize page_size(300, 400);
GetFrame().StartPrinting(page_size, page_size, 1);
GetDocument().View()->UpdateLifecyclePhasesForPrinting();
+ fixed = GetLayoutObjectByElementId("fixed");
+ fixed_child = GetLayoutObjectByElementId("fixed-child");
+ normal = GetLayoutObjectByElementId("normal");
// "fixed" should create fragments to repeat in each printed page.
EXPECT_TRUE(fixed->IsFixedPositionObjectInPagedMedia());
@@ -5894,7 +5879,10 @@ TEST_P(PaintPropertyTreeBuilderTest, RepeatingFixedPositionInPagedMedia) {
EXPECT_EQ(1u, NumFragments(normal));
GetFrame().EndPrinting();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
+ fixed = GetLayoutObjectByElementId("fixed");
+ fixed_child = GetLayoutObjectByElementId("fixed-child");
+ normal = GetLayoutObjectByElementId("normal");
EXPECT_EQ(1u, NumFragments(fixed));
EXPECT_FALSE(fixed_child->IsFixedPositionObjectInPagedMedia());
EXPECT_EQ(1u, NumFragments(fixed_child));
@@ -5912,7 +5900,7 @@ TEST_P(PaintPropertyTreeBuilderTest,
<div id="normal" style="height: 1000px"></div>
)HTML");
GetDocument().domWindow()->scrollTo(0, 200);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* fixed = GetLayoutObjectByElementId("fixed");
EXPECT_FALSE(fixed->IsFixedPositionObjectInPagedMedia());
@@ -5925,6 +5913,8 @@ TEST_P(PaintPropertyTreeBuilderTest,
FloatSize page_size(300, 400);
GetFrame().StartPrinting(page_size, page_size, 1);
GetDocument().View()->UpdateLifecyclePhasesForPrinting();
+ fixed = GetLayoutObjectByElementId("fixed");
+ fixed_child = GetLayoutObjectByElementId("fixed-child");
// "fixed" should create fragments to repeat in each printed page.
EXPECT_TRUE(fixed->IsFixedPositionObjectInPagedMedia());
@@ -5952,7 +5942,9 @@ TEST_P(PaintPropertyTreeBuilderTest,
}
GetFrame().EndPrinting();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
+ fixed = GetLayoutObjectByElementId("fixed");
+ fixed_child = GetLayoutObjectByElementId("fixed-child");
EXPECT_EQ(1u, NumFragments(fixed));
EXPECT_FALSE(fixed_child->IsFixedPositionObjectInPagedMedia());
EXPECT_EQ(1u, NumFragments(fixed_child));
@@ -5993,6 +5985,9 @@ TEST_P(PaintPropertyTreeBuilderTest, RepeatingTableSectionInPagedMedia) {
FloatSize page_size(300, 400);
GetFrame().StartPrinting(page_size, page_size, 1);
GetDocument().View()->UpdateLifecyclePhasesForPrinting();
+ // In LayoutNG, these may be different objects
+ head = ToLayoutTableSection(GetLayoutObjectByElementId("head"));
+ foot = ToLayoutTableSection(GetLayoutObjectByElementId("foot"));
// "fixed" should create fragments to repeat in each printed page.
EXPECT_TRUE(head->IsRepeatingHeaderGroup());
@@ -6026,7 +6021,9 @@ TEST_P(PaintPropertyTreeBuilderTest, RepeatingTableSectionInPagedMedia) {
ASSERT_EQ(1u, NumFragments(&painting_layer_object));
GetFrame().EndPrinting();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
+ head = ToLayoutTableSection(GetLayoutObjectByElementId("head"));
+ foot = ToLayoutTableSection(GetLayoutObjectByElementId("foot"));
EXPECT_FALSE(head->IsRepeatingHeaderGroup());
EXPECT_EQ(1u, NumFragments(head));
EXPECT_EQ(1u, NumFragments(head->FirstRow()));
@@ -6037,72 +6034,6 @@ TEST_P(PaintPropertyTreeBuilderTest, RepeatingTableSectionInPagedMedia) {
EXPECT_EQ(1u, NumFragments(foot->FirstRow()->FirstCell()));
}
-TEST_P(PaintPropertyTreeBuilderTest, ImageWithInvertFilter) {
- SetBodyInnerHTML(R"HTML(
- <img id='img' src='x'>
- )HTML");
- ToLayoutImage(GetLayoutObjectByElementId("img"))
- ->UpdateShouldInvertColorForTest(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
- const auto* filters = PaintPropertiesForElement("img")->Filter();
- ASSERT_NE(nullptr, filters);
- CompositorFilterOperations filters_expect;
- filters_expect.AppendInvertFilter(1.0f);
- EXPECT_EQ(filters_expect, filters->Filter());
-}
-
-TEST_P(PaintPropertyTreeBuilderTest, ImageWithInvertFilterUpdated) {
- SetBodyInnerHTML(R"HTML(
- <img id='img' src='x'>
- )HTML");
-
- ToLayoutImage(GetLayoutObjectByElementId("img"))
- ->UpdateShouldInvertColorForTest(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
- const auto* filters = PaintPropertiesForElement("img")->Filter();
- ASSERT_NE(nullptr, filters);
- CompositorFilterOperations filters_expect;
- filters_expect.AppendInvertFilter(1.0f);
- EXPECT_EQ(filters_expect, filters->Filter());
- ToLayoutImage(GetLayoutObjectByElementId("img"))
- ->UpdateShouldInvertColorForTest(false);
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_FALSE(PaintPropertiesForElement("img"));
-}
-
-TEST_P(PaintPropertyTreeBuilderTest, LayeredImageWithInvertFilter) {
- SetBodyInnerHTML(R"HTML(
- <img id='img' style='position: relative;' src='x'>
- )HTML");
- ToLayoutImage(GetLayoutObjectByElementId("img"))
- ->UpdateShouldInvertColorForTest(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
- const auto* filters = PaintPropertiesForElement("img")->Filter();
- ASSERT_NE(nullptr, filters);
- CompositorFilterOperations filters_expect;
- filters_expect.AppendInvertFilter(1.0f);
- EXPECT_EQ(filters_expect, filters->Filter());
-}
-
-TEST_P(PaintPropertyTreeBuilderTest, LayeredImageWithInvertFilterUpdated) {
- SetBodyInnerHTML(R"HTML(
- <img id='img' style='position: relative;' src='x'>
- )HTML");
-
- ToLayoutImage(GetLayoutObjectByElementId("img"))
- ->UpdateShouldInvertColorForTest(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
- const auto* filters = PaintPropertiesForElement("img")->Filter();
- ASSERT_NE(nullptr, filters);
- CompositorFilterOperations filters_expect;
- filters_expect.AppendInvertFilter(1.0f);
- EXPECT_EQ(filters_expect, filters->Filter());
- ToLayoutImage(GetLayoutObjectByElementId("img"))
- ->UpdateShouldInvertColorForTest(false);
- GetDocument().View()->UpdateAllLifecyclePhases();
- EXPECT_FALSE(PaintPropertiesForElement("img"));
-}
-
TEST_P(PaintPropertyTreeBuilderTest,
FloatPaintOffsetInContainerWithScrollbars) {
SetBodyInnerHTML(R"HTML(
@@ -6191,8 +6122,8 @@ TEST_P(PaintPropertyTreeBuilderTest, ClipInvalidationForReplacedElement) {
}
GetDocument().getElementById("target")->setAttribute(
- HTMLNames::styleAttr, "padding: 1px 2px 3px 4px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ html_names::kStyleAttr, "padding: 1px 2px 3px 4px;");
+ UpdateAllLifecyclePhasesForTest();
{
const auto* properties = PaintPropertiesForElement("target");
@@ -6302,7 +6233,7 @@ TEST_P(PaintPropertyTreeBuilderTest, StickyConstraintChain) {
</div>
)HTML");
GetDocument().getElementById("scroller")->setScrollTop(50);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* outer_properties = PaintPropertiesForElement("outer");
ASSERT_TRUE(outer_properties && outer_properties->StickyTranslation());
@@ -6371,7 +6302,7 @@ TEST_P(PaintPropertyTreeBuilderTest, NonScrollableSticky) {
</div>
)HTML");
GetDocument().getElementById("scroller")->setScrollTop(50);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* outer_properties = PaintPropertiesForElement("outer");
ASSERT_TRUE(outer_properties && outer_properties->StickyTranslation());
@@ -6407,7 +6338,7 @@ TEST_P(PaintPropertyTreeBuilderTest, WillChangeOpacityInducesAnEffectNode) {
EXPECT_FLOAT_EQ(properties->Effect()->Opacity(), 1.f);
auto* div = GetDocument().getElementById("div");
- div->setAttribute(HTMLNames::classAttr, "transluscent");
+ div->setAttribute(html_names::kClassAttr, "transluscent");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(ToLayoutBox(div->GetLayoutObject())->Layer()->NeedsRepaint());
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc
index ea825229b7b..06c43070593 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc
@@ -163,7 +163,7 @@ void SetDebugName(const PropertyTreeNode* node,
} // namespace
-namespace PaintPropertyTreePrinter {
+namespace paint_property_tree_printer {
void UpdateDebugNames(const VisualViewport& viewport) {
viewport.GetPageScaleNode()->SetDebugName("VisualViewport Scale Node");
@@ -212,7 +212,7 @@ void UpdateDebugNames(const LayoutObject& object,
SetDebugName(properties.Scroll(), "Scroll", object);
}
-} // namespace PaintPropertyTreePrinter
+} // namespace paint_property_tree_printer
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.h b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.h
index e7341612aa2..9f289b5850a 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.h
@@ -17,12 +17,12 @@ class LayoutObject;
class ObjectPaintProperties;
class VisualViewport;
-namespace PaintPropertyTreePrinter {
+namespace paint_property_tree_printer {
void UpdateDebugNames(const VisualViewport&);
void UpdateDebugNames(const LayoutObject&, ObjectPaintProperties&);
-} // namespace PaintPropertyTreePrinter
+} // namespace paint_property_tree_printer
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer_test.cc b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer_test.cc
index 190f7f4743e..2702524bfc6 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer_test.cc
@@ -49,9 +49,10 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleEffectTree) {
SetBodyInnerHTML("<div style='opacity: 0.9;'>hello world</div>");
String effect_tree_as_string =
effectPropertyTreeAsString(*GetDocument().View());
- EXPECT_THAT(effect_tree_as_string.Ascii().data(),
- testing::MatchesRegex("root .*"
- " Effect \\(LayoutBlockFlow DIV\\) .*"));
+ EXPECT_THAT(
+ effect_tree_as_string.Ascii().data(),
+ testing::MatchesRegex("root .*"
+ " Effect \\(LayoutN?G?BlockFlow DIV\\) .*"));
}
TEST_P(PaintPropertyTreePrinterTest, SimpleScrollTree) {
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc
index 15c553caedc..9938a031839 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc
@@ -49,7 +49,7 @@ TEST_P(PaintPropertyTreeUpdateTest,
// TODO(pdr): The main thread scrolling setting should invalidate properties.
GetDocument().View()->SetNeedsPaintPropertyUpdate();
overflow_a->GetLayoutObject()->SetNeedsPaintPropertyUpdate();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(DocScroll()->ThreadedScrollingDisabled());
EXPECT_TRUE(overflow_a->GetLayoutObject()
@@ -111,7 +111,7 @@ TEST_P(PaintPropertyTreeUpdateTest,
// Removing a main thread scrolling reason should update the entire tree.
overflow_b->removeAttribute("class");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(DocScroll()->HasBackgroundAttachmentFixedDescendants());
EXPECT_FALSE(overflow_a->GetLayoutObject()
->FirstFragment()
@@ -127,8 +127,8 @@ TEST_P(PaintPropertyTreeUpdateTest,
->HasBackgroundAttachmentFixedDescendants());
// Adding a main thread scrolling reason should update the entire tree.
- overflow_b->setAttribute(HTMLNames::classAttr, "backgroundAttachmentFixed");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ overflow_b->setAttribute(html_names::kClassAttr, "backgroundAttachmentFixed");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(DocScroll()->HasBackgroundAttachmentFixedDescendants());
EXPECT_TRUE(overflow_a->GetLayoutObject()
->FirstFragment()
@@ -160,7 +160,7 @@ TEST_P(PaintPropertyTreeUpdateTest, ParentFrameMainThreadScrollReasons) {
SetChildFrameHTML(
"<style>body { margin: 0; }</style>"
"<div id='forceScroll' style='height: 8888px;'></div>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Document* parent = &GetDocument();
EXPECT_TRUE(DocScroll(parent)->HasBackgroundAttachmentFixedDescendants());
Document* child = &ChildDocument();
@@ -168,14 +168,14 @@ TEST_P(PaintPropertyTreeUpdateTest, ParentFrameMainThreadScrollReasons) {
// Removing a main thread scrolling reason should update the entire tree.
auto* fixed_background = GetDocument().getElementById("fixedBackground");
- fixed_background->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ fixed_background->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(DocScroll(parent)->HasBackgroundAttachmentFixedDescendants());
EXPECT_FALSE(DocScroll(child)->HasBackgroundAttachmentFixedDescendants());
// Adding a main thread scrolling reason should update the entire tree.
- fixed_background->setAttribute(HTMLNames::classAttr, "fixedBackground");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ fixed_background->setAttribute(html_names::kClassAttr, "fixedBackground");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(DocScroll(parent)->HasBackgroundAttachmentFixedDescendants());
EXPECT_TRUE(DocScroll(child)->HasBackgroundAttachmentFixedDescendants());
}
@@ -197,7 +197,7 @@ TEST_P(PaintPropertyTreeUpdateTest, ChildFrameMainThreadScrollReasons) {
<div id='fixedBackground' class='fixedBackground'></div>
<div id='forceScroll' style='height: 8888px;'></div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
Document* parent = &GetDocument();
EXPECT_FALSE(DocScroll(parent)->HasBackgroundAttachmentFixedDescendants());
@@ -206,14 +206,14 @@ TEST_P(PaintPropertyTreeUpdateTest, ChildFrameMainThreadScrollReasons) {
// Removing a main thread scrolling reason should update the entire tree.
auto* fixed_background = ChildDocument().getElementById("fixedBackground");
- fixed_background->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ fixed_background->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(DocScroll(parent)->HasBackgroundAttachmentFixedDescendants());
EXPECT_FALSE(DocScroll(child)->HasBackgroundAttachmentFixedDescendants());
// Adding a main thread scrolling reason should update the entire tree.
- fixed_background->setAttribute(HTMLNames::classAttr, "fixedBackground");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ fixed_background->setAttribute(html_names::kClassAttr, "fixedBackground");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(DocScroll(parent)->HasBackgroundAttachmentFixedDescendants());
EXPECT_TRUE(DocScroll(child)->HasBackgroundAttachmentFixedDescendants());
}
@@ -278,7 +278,7 @@ TEST_P(PaintPropertyTreeUpdateTest,
// Removing a main thread scrolling reason should update the entire tree.
overflow_b->removeAttribute("class");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(overflow_a->GetLayoutObject()
->FirstFragment()
.PaintProperties()
@@ -312,7 +312,8 @@ TEST_P(PaintPropertyTreeUpdateTest, DescendantNeedsUpdateAcrossFrames) {
"translate3d(4px, 5px, 6px); width: 100px; height: 200px'></div>");
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
LayoutObject* div_with_transform =
GetLayoutObjectByElementId("divWithTransform");
@@ -338,7 +339,8 @@ TEST_P(PaintPropertyTreeUpdateTest, DescendantNeedsUpdateAcrossFrames) {
EXPECT_FALSE(inner_div_with_transform->DescendantNeedsPaintPropertyUpdate());
// After a lifecycle update, no nodes should need a descendant update.
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_FALSE(
GetDocument().GetLayoutView()->DescendantNeedsPaintPropertyUpdate());
EXPECT_FALSE(div_with_transform->DescendantNeedsPaintPropertyUpdate());
@@ -351,7 +353,8 @@ TEST_P(PaintPropertyTreeUpdateTest, DescendantNeedsUpdateAcrossFrames) {
child_frame_view->SetNeedsPaintPropertyUpdate();
EXPECT_TRUE(
GetDocument().GetLayoutView()->DescendantNeedsPaintPropertyUpdate());
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_FALSE(
GetDocument().GetLayoutView()->DescendantNeedsPaintPropertyUpdate());
EXPECT_FALSE(GetDocument().GetLayoutView()->NeedsPaintPropertyUpdate());
@@ -364,13 +367,13 @@ TEST_P(PaintPropertyTreeUpdateTest, UpdatingFrameViewContentClip) {
SetBodyInnerHTML("hello world.");
EXPECT_EQ(FloatRoundedRect(0, 0, 800, 600), DocContentClip()->ClipRect());
GetDocument().View()->Resize(800, 599);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRoundedRect(0, 0, 800, 599), DocContentClip()->ClipRect());
GetDocument().View()->Resize(800, 600);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRoundedRect(0, 0, 800, 600), DocContentClip()->ClipRect());
GetDocument().View()->Resize(5, 5);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRoundedRect(0, 0, 5, 5), DocContentClip()->ClipRect());
}
@@ -392,8 +395,8 @@ TEST_P(PaintPropertyTreeUpdateTest, BuildingStopsAtThrottledFrames) {
// Move the child frame offscreen so it becomes available for throttling.
auto* iframe = ToHTMLIFrameElement(GetDocument().getElementById("iframe"));
- iframe->setAttribute(HTMLNames::styleAttr, "transform: translateY(5555px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ iframe->setAttribute(html_names::kStyleAttr, "transform: translateY(5555px)");
+ UpdateAllLifecyclePhasesForTest();
// Ensure intersection observer notifications get delivered.
test::RunPendingTasks();
EXPECT_FALSE(GetDocument().View()->IsHiddenForThrottling());
@@ -428,7 +431,7 @@ TEST_P(PaintPropertyTreeUpdateTest, BuildingStopsAtThrottledFrames) {
// A lifecycle update should update all properties except those with
// actively throttled descendants.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetDocument().GetLayoutView()->NeedsPaintPropertyUpdate());
EXPECT_FALSE(
GetDocument().GetLayoutView()->DescendantNeedsPaintPropertyUpdate());
@@ -443,7 +446,7 @@ TEST_P(PaintPropertyTreeUpdateTest, BuildingStopsAtThrottledFrames) {
EXPECT_FALSE(GetDocument().View()->ShouldThrottleRendering());
EXPECT_FALSE(ChildDocument().View()->ShouldThrottleRendering());
// Once unthrottled, a lifecycel update should update all properties.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(GetDocument().GetLayoutView()->NeedsPaintPropertyUpdate());
EXPECT_FALSE(
GetDocument().GetLayoutView()->DescendantNeedsPaintPropertyUpdate());
@@ -467,58 +470,58 @@ TEST_P(PaintPropertyTreeUpdateTest, ClipChangesUpdateOverflowClip) {
</div>
)HTML");
auto* div = GetDocument().getElementById("div");
- div->setAttribute(HTMLNames::styleAttr, "display:inline-block; width:7px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "display:inline-block; width:7px;");
+ UpdateAllLifecyclePhasesForTest();
auto* clip_properties =
div->GetLayoutObject()->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatRect(0, 0, 7, 0), clip_properties->ClipRect().Rect());
// Width changes should update the overflow clip.
- div->setAttribute(HTMLNames::styleAttr, "display:inline-block; width:7px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "display:inline-block; width:7px;");
+ UpdateAllLifecyclePhasesForTest();
clip_properties =
div->GetLayoutObject()->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatRect(0, 0, 7, 0), clip_properties->ClipRect().Rect());
- div->setAttribute(HTMLNames::styleAttr, "display:inline-block; width:9px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "display:inline-block; width:9px;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRect(0, 0, 9, 0), clip_properties->ClipRect().Rect());
// An inline block's overflow clip should be updated when padding changes,
// even if the border box remains unchanged.
- div->setAttribute(HTMLNames::styleAttr,
+ div->setAttribute(html_names::kStyleAttr,
"display:inline-block; width:7px; padding-right:3px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
clip_properties =
div->GetLayoutObject()->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatRect(0, 0, 10, 0), clip_properties->ClipRect().Rect());
- div->setAttribute(HTMLNames::styleAttr,
+ div->setAttribute(html_names::kStyleAttr,
"display:inline-block; width:8px; padding-right:2px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRect(0, 0, 10, 0), clip_properties->ClipRect().Rect());
- div->setAttribute(HTMLNames::styleAttr,
+ div->setAttribute(html_names::kStyleAttr,
"display:inline-block; width:8px;"
"padding-right:1px; padding-left:1px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRect(0, 0, 10, 0), clip_properties->ClipRect().Rect());
// An block's overflow clip should be updated when borders change.
- div->setAttribute(HTMLNames::styleAttr, "border-right:3px solid red;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "border-right:3px solid red;");
+ UpdateAllLifecyclePhasesForTest();
clip_properties =
div->GetLayoutObject()->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatRect(0, 0, 797, 0), clip_properties->ClipRect().Rect());
- div->setAttribute(HTMLNames::styleAttr, "border-right:5px solid red;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "border-right:5px solid red;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(FloatRect(0, 0, 795, 0), clip_properties->ClipRect().Rect());
// Removing overflow clip should remove the property.
- div->setAttribute(HTMLNames::styleAttr, "overflow:hidden;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "overflow:hidden;");
+ UpdateAllLifecyclePhasesForTest();
clip_properties =
div->GetLayoutObject()->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatRect(0, 0, 800, 0), clip_properties->ClipRect().Rect());
- div->setAttribute(HTMLNames::styleAttr, "overflow:visible;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "overflow:visible;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(!div->GetLayoutObject()->FirstFragment().PaintProperties() ||
!div->GetLayoutObject()
->FirstFragment()
@@ -536,14 +539,14 @@ TEST_P(PaintPropertyTreeUpdateTest, ContainPaintChangesUpdateOverflowClip) {
<div style='width: 100px; height: 100px'></div>
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto* div = GetDocument().getElementById("div");
auto* properties =
div->GetLayoutObject()->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatRect(0, 0, 7, 6), properties->ClipRect().Rect());
- div->setAttribute(HTMLNames::styleAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ div->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(!div->GetLayoutObject()->FirstFragment().PaintProperties() ||
!div->GetLayoutObject()
->FirstFragment()
@@ -556,8 +559,8 @@ TEST_P(PaintPropertyTreeUpdateTest, NoPaintPropertyUpdateOnBackgroundChange) {
SetBodyInnerHTML("<div id='div' style='background-color: blue'>DIV</div>");
auto* div = GetDocument().getElementById("div");
- GetDocument().View()->UpdateAllLifecyclePhases();
- div->setAttribute(HTMLNames::styleAttr, "background-color: green");
+ UpdateAllLifecyclePhasesForTest();
+ div->setAttribute(html_names::kStyleAttr, "background-color: green");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_FALSE(div->GetLayoutObject()->NeedsPaintPropertyUpdate());
}
@@ -576,14 +579,16 @@ TEST_P(PaintPropertyTreeUpdateTest,
"<div id='forceScroll' style='height: 3000px;'></div>");
LocalFrameView* frame_view = GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_EQ(nullptr, DocScroll());
Document* child_doc = &ChildDocument();
EXPECT_NE(nullptr, DocScroll(child_doc));
auto* iframe_container = GetDocument().getElementById("iframeContainer");
- iframe_container->setAttribute(HTMLNames::styleAttr, "visibility: hidden;");
- frame_view->UpdateAllLifecyclePhases();
+ iframe_container->setAttribute(html_names::kStyleAttr, "visibility: hidden;");
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
EXPECT_EQ(nullptr, DocScroll());
EXPECT_EQ(nullptr, DocScroll(child_doc));
@@ -599,8 +604,8 @@ TEST_P(PaintPropertyTreeUpdateTest,
EXPECT_TRUE(properties->Transform()->HasDirectCompositingReasons());
// Removing the animation should remove the transform node.
- target->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
// Ensure the paint properties object was cleared as it is no longer needed.
EXPECT_EQ(nullptr,
target->GetLayoutObject()->FirstFragment().PaintProperties());
@@ -616,8 +621,8 @@ TEST_P(PaintPropertyTreeUpdateTest,
EXPECT_TRUE(properties->Effect()->HasDirectCompositingReasons());
// Removing the animation should remove the effect node.
- target->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr,
target->GetLayoutObject()->FirstFragment().PaintProperties());
}
@@ -630,8 +635,8 @@ TEST_P(PaintPropertyTreeUpdateTest,
LoadTestData("transform-animation.html");
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::styleAttr, "transform: translateX(2em)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "transform: translateX(2em)");
+ UpdateAllLifecyclePhasesForTest();
const ObjectPaintProperties* properties =
target->GetLayoutObject()->FirstFragment().PaintProperties();
@@ -639,8 +644,8 @@ TEST_P(PaintPropertyTreeUpdateTest,
properties->Transform()->GetCompositorElementId());
// Remove the animation but keep the transform on the element.
- target->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(CompositorElementId(),
properties->Transform()->GetCompositorElementId());
}
@@ -653,16 +658,16 @@ TEST_P(PaintPropertyTreeUpdateTest,
LoadTestData("opacity-animation.html");
Element* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::styleAttr, "opacity: 0.2");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "opacity: 0.2");
+ UpdateAllLifecyclePhasesForTest();
const ObjectPaintProperties* properties =
target->GetLayoutObject()->FirstFragment().PaintProperties();
EXPECT_NE(CompositorElementId(),
properties->Effect()->GetCompositorElementId());
- target->removeAttribute(HTMLNames::classAttr);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->removeAttribute(html_names::kClassAttr);
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(CompositorElementId(),
properties->Effect()->GetCompositorElementId());
}
@@ -692,8 +697,8 @@ TEST_P(PaintPropertyTreeUpdateTest, PerspectiveOriginUpdatesOnSizeChanges) {
perspective->FirstFragment().PaintProperties()->Perspective()->Origin());
auto* contents = GetDocument().getElementById("contents");
- contents->setAttribute(HTMLNames::styleAttr, "height: 200px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ contents->setAttribute(html_names::kStyleAttr, "height: 200px;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
TransformationMatrix().ApplyPerspective(100),
perspective->FirstFragment().PaintProperties()->Perspective()->Matrix());
@@ -723,8 +728,9 @@ TEST_P(PaintPropertyTreeUpdateTest, TransformUpdatesOnRelativeLengthChanges) {
->Transform()
->Matrix());
- transform->setAttribute(HTMLNames::styleAttr, "width: 200px; height: 300px;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ transform->setAttribute(html_names::kStyleAttr,
+ "width: 200px; height: 300px;");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix().Translate3d(100, 150, 0),
transform_object->FirstFragment()
.PaintProperties()
@@ -757,8 +763,8 @@ TEST_P(PaintPropertyTreeUpdateTest, CSSClipDependingOnSize) {
FloatRect(45, 50, 105, 100),
clip->FirstFragment().PaintProperties()->CssClip()->ClipRect().Rect());
- outer->setAttribute(HTMLNames::styleAttr, "height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ outer->setAttribute(html_names::kStyleAttr, "height: 200px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
FloatRect(45, 50, 105, 200),
clip->FirstFragment().PaintProperties()->CssClip()->ClipRect().Rect());
@@ -781,8 +787,8 @@ TEST_P(PaintPropertyTreeUpdateTest, ScrollBoundsChange) {
EXPECT_EQ(IntSize(200, 200), scroll_node->ContentsSize());
GetDocument().getElementById("content")->setAttribute(
- HTMLNames::styleAttr, "width: 200px; height: 300px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ html_names::kStyleAttr, "width: 200px; height: 300px");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(scroll_node, container->FirstFragment()
.PaintProperties()
->ScrollTranslation()
@@ -827,11 +833,11 @@ TEST_P(PaintPropertyTreeUpdateTest, ScrollbarWidthChange) {
container->FirstFragment().PaintProperties()->OverflowClip();
EXPECT_EQ(FloatSize(80, 80), overflow_clip->ClipRect().Rect().Size());
- auto* new_style = GetDocument().CreateRawElement(HTMLNames::styleTag);
+ auto* new_style = GetDocument().CreateRawElement(html_names::kStyleTag);
new_style->setTextContent("::-webkit-scrollbar {width: 40px; height: 40px}");
GetDocument().body()->AppendChild(new_style);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(overflow_clip,
container->FirstFragment().PaintProperties()->OverflowClip());
EXPECT_EQ(FloatSize(60, 60), overflow_clip->ClipRect().Rect().Size());
@@ -849,8 +855,8 @@ TEST_P(PaintPropertyTreeUpdateTest, Preserve3DChange) {
EXPECT_TRUE(transform->FlattensInheritedTransform());
GetDocument().getElementById("parent")->setAttribute(
- HTMLNames::styleAttr, "transform-style: preserve-3d");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ html_names::kStyleAttr, "transform-style: preserve-3d");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(transform, child->FirstFragment().PaintProperties()->Transform());
EXPECT_FALSE(transform->FlattensInheritedTransform());
}
@@ -868,7 +874,7 @@ TEST_P(PaintPropertyTreeUpdateTest, MenuListControlClipChange) {
// Should not assert in FindPropertiesNeedingUpdate.
ToHTMLSelectElement(select->GetNode())->setSelectedIndex(1);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(nullptr, select->FirstFragment().PaintProperties()->OverflowClip());
}
@@ -883,9 +889,9 @@ TEST_P(PaintPropertyTreeUpdateTest, BoxAddRemoveMask) {
EXPECT_EQ(nullptr, PaintPropertiesForElement("target"));
auto* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"-webkit-mask: linear-gradient(red, blue)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* properties = PaintPropertiesForElement("target");
ASSERT_NE(nullptr, properties);
@@ -895,8 +901,8 @@ TEST_P(PaintPropertyTreeUpdateTest, BoxAddRemoveMask) {
ASSERT_NE(nullptr, mask_clip);
EXPECT_EQ(FloatRoundedRect(8, 8, 100, 100), mask_clip->ClipRect());
- target->setAttribute(HTMLNames::styleAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr, PaintPropertiesForElement("target"));
}
@@ -920,9 +926,9 @@ TEST_P(PaintPropertyTreeUpdateTest, MaskClipNodeBoxSizeChange) {
ASSERT_NE(nullptr, mask_clip);
EXPECT_EQ(FloatRoundedRect(8, 8, 100, 100), mask_clip->ClipRect());
- GetDocument().getElementById("target")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("target")->setAttribute(html_names::kStyleAttr,
"height: 200px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_EQ(mask_clip, properties->MaskClip());
EXPECT_EQ(FloatRoundedRect(8, 8, 100, 200), mask_clip->ClipRect());
@@ -935,9 +941,9 @@ TEST_P(PaintPropertyTreeUpdateTest, InlineAddRemoveMask) {
EXPECT_EQ(nullptr, PaintPropertiesForElement("target"));
auto* target = GetDocument().getElementById("target");
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"-webkit-mask: linear-gradient(red, blue)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* properties = PaintPropertiesForElement("target");
ASSERT_NE(nullptr, properties);
@@ -947,8 +953,8 @@ TEST_P(PaintPropertyTreeUpdateTest, InlineAddRemoveMask) {
ASSERT_NE(nullptr, mask_clip);
EXPECT_EQ(50, mask_clip->ClipRect().Rect().Width());
- target->setAttribute(HTMLNames::styleAttr, "");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr, PaintPropertiesForElement("target"));
}
@@ -965,9 +971,9 @@ TEST_P(PaintPropertyTreeUpdateTest, MaskClipNodeInlineBoundsChange) {
ASSERT_NE(nullptr, mask_clip);
EXPECT_EQ(50, mask_clip->ClipRect().Rect().Width());
- GetDocument().getElementById("img")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("img")->setAttribute(html_names::kStyleAttr,
"width: 100px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
ASSERT_EQ(mask_clip, properties->MaskClip());
EXPECT_EQ(100, mask_clip->ClipRect().Rect().Width());
@@ -988,7 +994,7 @@ TEST_P(PaintPropertyTreeUpdateTest, AddRemoveSVGMask) {
EXPECT_EQ(nullptr, PaintPropertiesForElement("rect"));
GetDocument().getElementById("rect")->setAttribute("mask", "url(#mask)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
const auto* properties = PaintPropertiesForElement("rect");
ASSERT_NE(nullptr, properties);
EXPECT_NE(nullptr, properties->Effect());
@@ -998,7 +1004,7 @@ TEST_P(PaintPropertyTreeUpdateTest, AddRemoveSVGMask) {
EXPECT_EQ(FloatRoundedRect(0, 100, 100, 100), mask_clip->ClipRect());
GetDocument().getElementById("rect")->removeAttribute("mask");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr, PaintPropertiesForElement("rect"));
}
@@ -1025,7 +1031,7 @@ TEST_P(PaintPropertyTreeUpdateTest, SVGMaskTargetBoundsChange) {
EXPECT_EQ(FloatRoundedRect(0, 50, 100, 150), mask_clip->ClipRect());
GetDocument().getElementById("rect")->setAttribute("width", "200");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(nullptr, properties->Effect());
EXPECT_NE(nullptr, properties->Mask());
EXPECT_EQ(FloatRoundedRect(0, 50, 100, 150), mask_clip->ClipRect());
@@ -1047,15 +1053,15 @@ TEST_P(PaintPropertyTreeUpdateTest, WillTransformChangeAboveFixed) {
fixed->FirstFragment().LocalBorderBoxProperties().Transform());
ToElement(container->GetNode())
- ->setAttribute(HTMLNames::styleAttr, "will-change: top");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, "will-change: top");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
GetLayoutView().FirstFragment().LocalBorderBoxProperties().Transform(),
fixed->FirstFragment().LocalBorderBoxProperties().Transform());
ToElement(container->GetNode())
- ->setAttribute(HTMLNames::styleAttr, "will-change: transform");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, "will-change: transform");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(container->FirstFragment().PaintProperties()->Transform(),
fixed->FirstFragment().LocalBorderBoxProperties().Transform());
}
@@ -1087,17 +1093,19 @@ TEST_P(PaintPropertyTreeUpdateTest, CompositingReasonForAnimation) {
ASSERT_TRUE(filter);
EXPECT_FALSE(filter->HasDirectCompositingReasons());
- target->setAttribute(HTMLNames::styleAttr, "transform: translateX(11px)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ target->setAttribute(html_names::kStyleAttr, "transform: translateX(11px)");
+ UpdateAllLifecyclePhasesForTest();
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
EXPECT_TRUE(transform->HasDirectCompositingReasons());
EXPECT_TRUE(transform->RequiresCompositingForAnimation());
}
- EXPECT_FALSE(filter->HasDirectCompositingReasons());
+ // TODO(flackr): After https://crbug.com/900241 is fixed the filter effect
+ // should no longer have direct compositing reasons due to the animation.
+ EXPECT_TRUE(filter->HasDirectCompositingReasons());
- target->setAttribute(HTMLNames::styleAttr,
+ target->setAttribute(html_names::kStyleAttr,
"transform: translateX(11px); filter: opacity(40%)");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// The transform animation still continues.
if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
EXPECT_TRUE(transform->HasDirectCompositingReasons());
@@ -1122,11 +1130,11 @@ TEST_P(PaintPropertyTreeUpdateTest, SVGViewportContainerOverflowChange) {
properties->OverflowClip()->ClipRect().Rect());
GetDocument().getElementById("target")->setAttribute("overflow", "visible");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr, PaintPropertiesForElement("target"));
GetDocument().getElementById("target")->setAttribute("overflow", "hidden");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
properties = PaintPropertiesForElement("target");
ASSERT_NE(nullptr, properties);
EXPECT_EQ(FloatRect(0, 0, 30, 40),
@@ -1148,11 +1156,11 @@ TEST_P(PaintPropertyTreeUpdateTest, SVGForeignObjectOverflowChange) {
properties->OverflowClip()->ClipRect().Rect());
GetDocument().getElementById("target")->setAttribute("overflow", "visible");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(nullptr, PaintPropertiesForElement("target"));
GetDocument().getElementById("target")->setAttribute("overflow", "hidden");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
properties = PaintPropertiesForElement("target");
ASSERT_NE(nullptr, properties);
EXPECT_EQ(FloatRect(10, 20, 30, 40),
@@ -1169,11 +1177,11 @@ TEST_P(PaintPropertyTreeBuilderTest, OmitOverflowClipOnSelectionChange) {
EXPECT_FALSE(PaintPropertiesForElement("target")->OverflowClip());
GetDocument().GetFrame()->Selection().SelectAll();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(PaintPropertiesForElement("target")->OverflowClip());
GetDocument().GetFrame()->Selection().Clear();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(PaintPropertiesForElement("target")->OverflowClip());
}
@@ -1190,11 +1198,11 @@ TEST_P(PaintPropertyTreeBuilderTest, OmitOverflowClipOnCaretChange) {
EXPECT_FALSE(PaintPropertiesForElement("target")->OverflowClip());
target->focus();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_TRUE(PaintPropertiesForElement("target")->OverflowClip());
target->blur();
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(PaintPropertiesForElement("target")->OverflowClip());
}
@@ -1227,8 +1235,8 @@ TEST_P(PaintPropertyTreeUpdateTest,
GetDocument()
.getElementById("container")
- ->setAttribute(HTMLNames::styleAttr, "width: 500px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ ->setAttribute(html_names::kStyleAttr, "width: 500px");
+ UpdateAllLifecyclePhasesForTest();
ASSERT_EQ(2u, NumFragments(flow_thread));
EXPECT_EQ(1000000, FragmentAt(flow_thread, 0)
.PaintProperties()
@@ -1265,9 +1273,9 @@ TEST_P(PaintPropertyTreeUpdateTest,
ASSERT_TRUE(props->Effect());
EXPECT_EQ(props->Effect()->BlendMode(), SkBlendMode::kDarken);
- blended_element->setAttribute(HTMLNames::styleAttr,
+ blended_element->setAttribute(html_names::kStyleAttr,
"mix-blend-mode: lighten;");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
props = blended_element->GetLayoutObject()->FirstFragment().PaintProperties();
ASSERT_TRUE(props->Effect());
@@ -1309,7 +1317,7 @@ TEST_P(PaintPropertyTreeUpdateTest, EnsureSnapContainerData) {
)HTML");
GetDocument().View()->Resize(300, 300);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto doc_snap_container_data = DocScroll()->GetSnapContainerData();
ASSERT_TRUE(doc_snap_container_data);
@@ -1340,13 +1348,13 @@ TEST_P(PaintPropertyTreeUpdateTest,
EXPECT_EQ(nullptr, effect_properties->Effect()->OutputClip());
auto* descendant = GetDocument().getElementById("descendant");
- descendant->setAttribute(HTMLNames::styleAttr, "position: relative");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ descendant->setAttribute(html_names::kStyleAttr, "position: relative");
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(clip_properties->OverflowClip(),
effect_properties->Effect()->OutputClip());
- descendant->setAttribute(HTMLNames::styleAttr, "position: absolute");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ descendant->setAttribute(html_names::kStyleAttr, "position: absolute");
+ UpdateAllLifecyclePhasesForTest();
// The effect's OutputClip is nullptr because of the absolute descendant.
EXPECT_EQ(nullptr, effect_properties->Effect()->OutputClip());
}
@@ -1384,7 +1392,7 @@ TEST_P(PaintPropertyTreeUpdateTest, ForwardReferencedSVGElementUpdate) {
GetDocument().getElementById("filter")->setAttribute("width", "20");
GetDocument().getElementById("svg2")->setAttribute("transform",
"translate(2)");
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_NE(nullptr, svg2_properties->Transform());
EXPECT_EQ(svg2_properties->PaintOffsetTranslation(),
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_result.h b/chromium/third_party/blink/renderer/core/paint/paint_result.h
index 5bad181944c..7f11d3ee920 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_result.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_result.h
@@ -12,12 +12,12 @@ enum PaintResult {
// The layer/object is fully painted. This includes cases that nothing needs
// painting regardless of the paint rect.
kFullyPainted,
- // Some part of the layer/object is out of the paint rect and may be not fully
- // painted. The results cannot be cached because they may change when paint
+ // Some part of the layer/object is out of the cull rect and may be not fully
+ // painted. The results cannot be cached because they may change when cull
// rect changes.
- kMayBeClippedByPaintDirtyRect,
+ kMayBeClippedByCullRect,
- kMaxPaintResult = kMayBeClippedByPaintDirtyRect,
+ kMaxPaintResult = kMayBeClippedByCullRect,
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing.cc b/chromium/third_party/blink/renderer/core/paint/paint_timing.cc
index b9963652687..5cd87b85cec 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_timing.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing.cc
@@ -47,7 +47,7 @@ const char PaintTiming::kSupplementName[] = "PaintTiming";
PaintTiming& PaintTiming::From(Document& document) {
PaintTiming* timing = Supplement<Document>::From<PaintTiming>(document);
if (!timing) {
- timing = new PaintTiming(document);
+ timing = MakeGarbageCollected<PaintTiming>(document);
ProvideTo(document, timing);
}
return *timing;
@@ -157,7 +157,7 @@ void PaintTiming::Trace(blink::Visitor* visitor) {
PaintTiming::PaintTiming(Document& document)
: Supplement<Document>(document),
- fmp_detector_(new FirstMeaningfulPaintDetector(this)) {}
+ fmp_detector_(MakeGarbageCollected<FirstMeaningfulPaintDetector>(this)) {}
LocalFrame* PaintTiming::GetFrame() const {
return GetSupplementable()->GetFrame();
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing.h b/chromium/third_party/blink/renderer/core/paint/paint_timing.h
index 7990b7b8e21..ea77cacbba4 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_timing.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing.h
@@ -35,6 +35,7 @@ class CORE_EXPORT PaintTiming final
public:
static const char kSupplementName[];
+ explicit PaintTiming(Document&);
virtual ~PaintTiming() = default;
static PaintTiming& From(Document&);
@@ -110,7 +111,6 @@ class CORE_EXPORT PaintTiming final
void Trace(blink::Visitor*) override;
private:
- explicit PaintTiming(Document&);
LocalFrame* GetFrame() const;
void NotifyPaintTimingChanged();
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc
new file mode 100644
index 00000000000..7b07edff362
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc
@@ -0,0 +1,95 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/loader/document_loader.h"
+#include "third_party/blink/renderer/core/paint/image_paint_timing_detector.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
+#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+
+namespace blink {
+
+PaintTimingDetector::PaintTimingDetector(LocalFrameView* frame_view)
+ : frame_view_(frame_view),
+ text_paint_timing_detector_(new TextPaintTimingDetector(frame_view)),
+ image_paint_timing_detector_(new ImagePaintTimingDetector(frame_view)){};
+
+void PaintTimingDetector::NotifyPrePaintFinished() {
+ text_paint_timing_detector_->OnPrePaintFinished();
+ image_paint_timing_detector_->OnPrePaintFinished();
+}
+
+void PaintTimingDetector::NotifyObjectPrePaint(
+ const LayoutObject& object,
+ const PaintLayer& painting_layer) {
+ // Todo(maxlg): incoperate iframe's statistics
+ if (!frame_view_->GetFrame().IsMainFrame())
+ return;
+
+ if (object.IsText()) {
+ text_paint_timing_detector_->RecordText(object, painting_layer);
+ }
+ if (object.IsImage() || object.IsVideo() || object.IsSVGImage() ||
+ ImagePaintTimingDetector::HasContentfulBackgroundImage(object)) {
+ image_paint_timing_detector_->RecordImage(object, painting_layer);
+ }
+ // Todo(maxlg): add other detectors here.
+}
+
+void PaintTimingDetector::NotifyNodeRemoved(const LayoutObject& object) {
+ if (!object.GetNode())
+ return;
+ text_paint_timing_detector_->NotifyNodeRemoved(
+ DOMNodeIds::IdForNode(object.GetNode()));
+ image_paint_timing_detector_->NotifyNodeRemoved(
+ DOMNodeIds::IdForNode(object.GetNode()));
+}
+
+void PaintTimingDetector::DidChangePerformanceTiming() {
+ Document* document = frame_view_->GetFrame().GetDocument();
+ if (!document)
+ return;
+ DocumentLoader* loader = document->Loader();
+ if (!loader)
+ return;
+ loader->DidChangePerformanceTiming();
+}
+
+uint64_t PaintTimingDetector::CalculateVisualSize(
+ const LayoutRect& invalidated_rect,
+ const PaintLayer& painting_layer) const {
+ // This case should be dealt with outside the function.
+ DCHECK(!invalidated_rect.IsEmpty());
+
+ // As Layout objects live in different transform spaces, the object's rect
+ // should be projected to the viewport's transform space.
+ IntRect visual_rect = SaturatedRect(EnclosedIntRect(invalidated_rect));
+ painting_layer.GetLayoutObject().FirstFragment().MapRectToFragment(
+ painting_layer.GetLayoutObject().View()->FirstFragment(), visual_rect);
+
+ // A visual rect means the part of the rect that's visible within
+ // the viewport. We define the size of it as visual size.
+ ScrollableArea* scrollable_area = frame_view_->GetScrollableArea();
+ DCHECK(scrollable_area);
+ IntRect viewport = scrollable_area->VisibleContentRect();
+ // Use saturated rect to avoid integer-overflow.
+ visual_rect.Intersect(SaturatedRect(viewport));
+ return visual_rect.Size().Area();
+}
+
+void PaintTimingDetector::Dispose() {
+ text_paint_timing_detector_->Dispose();
+}
+
+void PaintTimingDetector::Trace(Visitor* visitor) {
+ visitor->Trace(text_paint_timing_detector_);
+ visitor->Trace(image_paint_timing_detector_);
+ visitor->Trace(frame_view_);
+}
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_tracker.h b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h
index 25b52224581..4002f0873b2 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_tracker.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TRACKER_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TRACKER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_DETECTOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_DETECTOR_H_
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/member.h"
@@ -13,23 +13,28 @@ namespace blink {
class LayoutObject;
class LocalFrameView;
class PaintLayer;
+class LayoutRect;
class TextPaintTimingDetector;
class ImagePaintTimingDetector;
-// PaintTracker contains some of paint metric detectors, providing common
-// infrastructure for these detectors.
+// PaintTimingDetector contains some of paint metric detectors,
+// providing common infrastructure for these detectors.
//
// Users has to enable 'loading' trace category to enable the metrics.
//
// See also:
// https://docs.google.com/document/d/1DRVd4a2VU8-yyWftgOparZF-sf16daf0vfbsHuz2rws/edit
-class CORE_EXPORT PaintTracker : public GarbageCollected<PaintTracker> {
+class CORE_EXPORT PaintTimingDetector
+ : public GarbageCollected<PaintTimingDetector> {
public:
- PaintTracker(LocalFrameView*);
+ PaintTimingDetector(LocalFrameView*);
void NotifyObjectPrePaint(const LayoutObject& object,
const PaintLayer& painting_layer);
void NotifyNodeRemoved(const LayoutObject& object);
void NotifyPrePaintFinished();
+ void DidChangePerformanceTiming();
+ uint64_t CalculateVisualSize(const LayoutRect& invalidated_rect,
+ const PaintLayer& painting_layer) const;
void Dispose();
TextPaintTimingDetector& GetTextPaintTimingDetector() {
@@ -48,4 +53,4 @@ class CORE_EXPORT PaintTracker : public GarbageCollected<PaintTracker> {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TRACKER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_DETECTOR_H_
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_tracker.cc b/chromium/third_party/blink/renderer/core/paint/paint_tracker.cc
deleted file mode 100644
index a6bccff1c63..00000000000
--- a/chromium/third_party/blink/renderer/core/paint/paint_tracker.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-#include "third_party/blink/renderer/core/paint/paint_tracker.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/core/frame/local_frame_view.h"
-#include "third_party/blink/renderer/core/layout/layout_object.h"
-#include "third_party/blink/renderer/core/paint/image_paint_timing_detector.h"
-#include "third_party/blink/renderer/core/paint/paint_layer.h"
-#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
-
-namespace blink {
-
-PaintTracker::PaintTracker(LocalFrameView* frame_view)
- : frame_view_(frame_view),
- text_paint_timing_detector_(new TextPaintTimingDetector(frame_view)),
- image_paint_timing_detector_(new ImagePaintTimingDetector(frame_view)){};
-
-void PaintTracker::NotifyPrePaintFinished() {
- text_paint_timing_detector_->OnPrePaintFinished();
- image_paint_timing_detector_->OnPrePaintFinished();
-}
-
-void PaintTracker::NotifyObjectPrePaint(const LayoutObject& object,
- const PaintLayer& painting_layer) {
- // Todo(maxlg): incoperate iframe's statistics
- if (!frame_view_->GetFrame().IsMainFrame())
- return;
-
- if (object.IsText()) {
- text_paint_timing_detector_->RecordText(object, painting_layer);
- }
- if (object.IsImage()) {
- image_paint_timing_detector_->RecordImage(object, painting_layer);
- }
- // Todo(maxlg): add other detectors here.
-}
-
-void PaintTracker::NotifyNodeRemoved(const LayoutObject& object) {
- if (!object.GetNode())
- return;
- text_paint_timing_detector_->NotifyNodeRemoved(
- DOMNodeIds::IdForNode(object.GetNode()));
- image_paint_timing_detector_->NotifyNodeRemoved(
- DOMNodeIds::IdForNode(object.GetNode()));
-}
-
-void PaintTracker::Dispose() {
- text_paint_timing_detector_->Dispose();
-}
-
-void PaintTracker::Trace(Visitor* visitor) {
- visitor->Trace(text_paint_timing_detector_);
- visitor->Trace(image_paint_timing_detector_);
- visitor->Trace(frame_view_);
-}
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc b/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc
index 8948ebaed15..d535454c767 100644
--- a/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc
+++ b/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc
@@ -22,7 +22,7 @@
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_property_tree_printer.h"
-#include "third_party/blink/renderer/core/paint/paint_tracker.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
namespace blink {
@@ -133,8 +133,9 @@ void PrePaintTreeWalk::Walk(LocalFrameView& frame_view) {
if (RuntimeEnabledFeatures::JankTrackingEnabled())
frame_view.GetJankTracker().NotifyPrePaintFinished();
- if (RuntimeEnabledFeatures::PaintTrackingEnabled())
- frame_view.GetPaintTracker().NotifyPrePaintFinished();
+ if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
+ frame_view.GetPaintTimingDetector().NotifyPrePaintFinished();
+ }
context_storage_.pop_back();
}
@@ -158,7 +159,7 @@ bool HasBlockingTouchEventHandler(const LocalFrame& frame,
const auto* blocking = registry.EventHandlerTargets(
EventHandlerRegistry::kTouchStartOrMoveEventBlocking);
const auto* blocking_low_latency = registry.EventHandlerTargets(
- EventHandlerRegistry::kTouchStartOrMoveEventBlocking);
+ EventHandlerRegistry::kTouchStartOrMoveEventBlockingLowLatency);
return blocking->Contains(&target) || blocking_low_latency->Contains(&target);
}
@@ -327,9 +328,8 @@ void PrePaintTreeWalk::WalkInternal(const LayoutObject& object,
property_tree_builder.emplace(object, *context.tree_builder_context);
property_changed = property_tree_builder->UpdateForSelf();
- if (property_changed &&
- !context.tree_builder_context
- ->supports_composited_raster_invalidation) {
+ if (property_changed && !context.tree_builder_context
+ ->supports_composited_raster_invalidation) {
paint_invalidator_context.subtree_flags |=
PaintInvalidatorContext::kSubtreeFullInvalidation;
}
@@ -375,13 +375,20 @@ void PrePaintTreeWalk::WalkInternal(const LayoutObject& object,
object, paint_invalidator_context.old_visual_rect,
*paint_invalidator_context.painting_layer);
}
- if (RuntimeEnabledFeatures::PaintTrackingEnabled()) {
- object.GetFrameView()->GetPaintTracker().NotifyObjectPrePaint(
+ if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
+ object.GetFrameView()->GetPaintTimingDetector().NotifyObjectPrePaint(
object, *paint_invalidator_context.painting_layer);
}
}
void PrePaintTreeWalk::Walk(const LayoutObject& object) {
+ if (object.PrePaintBlockedByDisplayLock())
+ return;
+ // TODO(vmpstr): Technically we should do this after prepaint finishes, but
+ // due to a possible early out this is more convenient. We should change this
+ // to RAII.
+ object.NotifyDisplayLockDidPrePaint();
+
// We need to be careful not to have a reference to the parent context, since
// this reference will be to the context_storage_ memory which may be
// reallocated during this function call.
diff --git a/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk_test.cc b/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk_test.cc
index cca36abecfc..9e7fd97d66f 100644
--- a/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk_test.cc
@@ -77,8 +77,8 @@ TEST_P(PrePaintTreeWalkTest, PropertyTreesRebuiltWithBorderInvalidation) {
EXPECT_EQ(nullptr, transformed_properties->Transform());
// Cause a paint invalidation.
- transformed_element->setAttribute(HTMLNames::classAttr, "border");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ transformed_element->setAttribute(html_names::kClassAttr, "border");
+ UpdateAllLifecyclePhasesForTest();
// Should have changed back.
EXPECT_EQ(TransformationMatrix().Translate(100, 100),
@@ -92,7 +92,7 @@ TEST_P(PrePaintTreeWalkTest, PropertyTreesRebuiltWithFrameScroll) {
// Cause a scroll invalidation and ensure the translation is updated.
GetDocument().domWindow()->scrollTo(0, 100);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(TransformationMatrix().Translate(0, -100),
FrameScrollTranslation()->Matrix());
@@ -115,8 +115,8 @@ TEST_P(PrePaintTreeWalkTest, PropertyTreesRebuiltWithCSSTransformInvalidation) {
transformed_properties->Transform()->Matrix());
// Invalidate the CSS transform property.
- transformed_element->setAttribute(HTMLNames::classAttr, "transformB");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ transformed_element->setAttribute(html_names::kClassAttr, "transformB");
+ UpdateAllLifecyclePhasesForTest();
// The transform should have changed.
EXPECT_EQ(TransformationMatrix().Translate(200, 200),
@@ -138,8 +138,8 @@ TEST_P(PrePaintTreeWalkTest, PropertyTreesRebuiltWithOpacityInvalidation) {
EXPECT_EQ(0.9f, transparent_properties->Effect()->Opacity());
// Invalidate the opacity property.
- transparent_element->setAttribute(HTMLNames::classAttr, "opacityB");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ transparent_element->setAttribute(html_names::kClassAttr, "opacityB");
+ UpdateAllLifecyclePhasesForTest();
// The opacity should have changed.
EXPECT_EQ(0.4f, transparent_properties->Effect()->Opacity());
@@ -165,7 +165,7 @@ TEST_P(PrePaintTreeWalkTest, ClearSubsequenceCachingClipChange) {
EXPECT_FALSE(child_paint_layer->NeedsRepaint());
EXPECT_FALSE(child_paint_layer->NeedsPaintPhaseFloat());
- parent->setAttribute(HTMLNames::classAttr, "clip");
+ parent->setAttribute(html_names::kClassAttr, "clip");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(child_paint_layer->NeedsRepaint());
@@ -191,7 +191,7 @@ TEST_P(PrePaintTreeWalkTest, ClearSubsequenceCachingClipChange2DTransform) {
EXPECT_FALSE(child_paint_layer->NeedsRepaint());
EXPECT_FALSE(child_paint_layer->NeedsPaintPhaseFloat());
- parent->setAttribute(HTMLNames::classAttr, "clip");
+ parent->setAttribute(html_names::kClassAttr, "clip");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(child_paint_layer->NeedsRepaint());
@@ -220,7 +220,7 @@ TEST_P(PrePaintTreeWalkTest, ClearSubsequenceCachingClipChangePosAbs) {
// This changes clips for absolute-positioned descendants of "child" but not
// normal-position ones, which are already clipped to 50x50.
- parent->setAttribute(HTMLNames::classAttr, "clip");
+ parent->setAttribute(html_names::kClassAttr, "clip");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(child_paint_layer->NeedsRepaint());
@@ -249,7 +249,7 @@ TEST_P(PrePaintTreeWalkTest, ClearSubsequenceCachingClipChangePosFixed) {
// This changes clips for absolute-positioned descendants of "child" but not
// normal-position ones, which are already clipped to 50x50.
- parent->setAttribute(HTMLNames::classAttr, "clip");
+ parent->setAttribute(html_names::kClassAttr, "clip");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(child_paint_layer->NeedsRepaint());
@@ -274,7 +274,7 @@ TEST_P(PrePaintTreeWalkTest, VisualRectClipForceSubtree) {
auto* grandchild = GetLayoutObjectByElementId("grandchild");
GetDocument().getElementById("parent")->removeAttribute("style");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(200, grandchild->FirstFragment().VisualRect().Height());
}
@@ -295,11 +295,11 @@ TEST_P(PrePaintTreeWalkTest, ClipChangeHasRadius) {
auto* target = GetDocument().getElementById("target");
auto* target_object = ToLayoutBoxModelObject(target->GetLayoutObject());
- target->setAttribute(HTMLNames::styleAttr, "border-radius: 5px");
+ target->setAttribute(html_names::kStyleAttr, "border-radius: 5px");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(target_object->Layer()->NeedsRepaint());
// And should not trigger any assert failure.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
namespace {
@@ -311,7 +311,7 @@ class PrePaintTreeWalkMockEventListener final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event*) final {}
+ void Invoke(ExecutionContext*, Event*) final {}
};
} // namespace
@@ -326,7 +326,7 @@ TEST_P(PrePaintTreeWalkTest, InsideBlockingTouchEventHandlerUpdate) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto& ancestor = *GetLayoutObjectByElementId("ancestor");
auto& handler = *GetLayoutObjectByElementId("handler");
auto& descendant = *GetLayoutObjectByElementId("descendant");
@@ -346,7 +346,7 @@ TEST_P(PrePaintTreeWalkTest, InsideBlockingTouchEventHandlerUpdate) {
PrePaintTreeWalkMockEventListener* callback =
new PrePaintTreeWalkMockEventListener();
auto* handler_element = GetDocument().getElementById("handler");
- handler_element->addEventListener(EventTypeNames::touchstart, callback);
+ handler_element->addEventListener(event_type_names::kTouchstart, callback);
EXPECT_FALSE(ancestor.EffectiveWhitelistedTouchActionChanged());
EXPECT_TRUE(handler.EffectiveWhitelistedTouchActionChanged());
@@ -356,7 +356,7 @@ TEST_P(PrePaintTreeWalkTest, InsideBlockingTouchEventHandlerUpdate) {
EXPECT_FALSE(handler.DescendantEffectiveWhitelistedTouchActionChanged());
EXPECT_FALSE(descendant.DescendantEffectiveWhitelistedTouchActionChanged());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(ancestor.EffectiveWhitelistedTouchActionChanged());
EXPECT_FALSE(handler.EffectiveWhitelistedTouchActionChanged());
EXPECT_FALSE(descendant.EffectiveWhitelistedTouchActionChanged());
@@ -382,7 +382,7 @@ TEST_P(PrePaintTreeWalkTest, EffectiveTouchActionStyleUpdate) {
</div>
)HTML");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto& ancestor = *GetLayoutObjectByElementId("ancestor");
auto& touchaction = *GetLayoutObjectByElementId("touchaction");
auto& descendant = *GetLayoutObjectByElementId("descendant");
@@ -396,7 +396,7 @@ TEST_P(PrePaintTreeWalkTest, EffectiveTouchActionStyleUpdate) {
GetDocument()
.getElementById("touchaction")
- ->setAttribute(HTMLNames::classAttr, "touchaction");
+ ->setAttribute(html_names::kClassAttr, "touchaction");
GetDocument().View()->UpdateLifecycleToLayoutClean();
EXPECT_FALSE(ancestor.EffectiveWhitelistedTouchActionChanged());
EXPECT_TRUE(touchaction.EffectiveWhitelistedTouchActionChanged());
@@ -405,7 +405,7 @@ TEST_P(PrePaintTreeWalkTest, EffectiveTouchActionStyleUpdate) {
EXPECT_FALSE(touchaction.DescendantEffectiveWhitelistedTouchActionChanged());
EXPECT_FALSE(descendant.DescendantEffectiveWhitelistedTouchActionChanged());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(ancestor.EffectiveWhitelistedTouchActionChanged());
EXPECT_FALSE(touchaction.EffectiveWhitelistedTouchActionChanged());
EXPECT_FALSE(descendant.EffectiveWhitelistedTouchActionChanged());
@@ -424,10 +424,10 @@ TEST_P(PrePaintTreeWalkTest, ClipChangesDoNotCauseVisualRectUpdates) {
</div>
)HTML");
- GetDocument().getElementById("parent")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("parent")->setAttribute(html_names::kStyleAttr,
"border-radius: 5px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
auto& parent = *GetLayoutObjectByElementId("parent");
auto& child = *GetLayoutObjectByElementId("child");
@@ -442,10 +442,10 @@ TEST_P(PrePaintTreeWalkTest, ClipChangesDoNotCauseVisualRectUpdates) {
// Cause the child clip to change without changing paint property tree
// topology.
- GetDocument().getElementById("parent")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("parent")->setAttribute(html_names::kStyleAttr,
"border-radius: 6px");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(100, parent.FirstFragment().VisualRect().Width());
EXPECT_EQ(100, parent.FirstFragment().VisualRect().Height());
EXPECT_EQ(100, child.FirstFragment().VisualRect().Width());
diff --git a/chromium/third_party/blink/renderer/core/paint/replaced_painter.cc b/chromium/third_party/blink/renderer/core/paint/replaced_painter.cc
index 9e07504eb60..c94a14b0101 100644
--- a/chromium/third_party/blink/renderer/core/paint/replaced_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/replaced_painter.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/paint/object_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/scoped_paint_state.h"
#include "third_party/blink/renderer/core/paint/scrollable_area_painter.h"
#include "third_party/blink/renderer/core/paint/selection_painting_utils.h"
@@ -51,9 +52,7 @@ ScopedReplacedContentPaintState::ScopedReplacedContentPaintState(
if (content_transform && replaced.IsSVGRoot()) {
new_properties.SetTransform(content_transform);
adjusted_paint_info_.emplace(input_paint_info_);
- DCHECK(content_transform->Matrix().IsAffine());
- adjusted_paint_info_->UpdateCullRect(
- content_transform->Matrix().ToAffineTransform());
+ adjusted_paint_info_->TransformCullRect(content_transform);
property_changed = true;
}
@@ -65,14 +64,6 @@ ScopedReplacedContentPaintState::ScopedReplacedContentPaintState(
property_changed = true;
}
- // Check filter for optimized image policy violation highlights, which
- // may be applied locally.
- if (paint_properties->Filter() &&
- (!replaced.HasLayer() || !replaced.Layer()->IsSelfPaintingLayer())) {
- new_properties.SetEffect(paint_properties->Filter());
- property_changed = true;
- }
-
if (property_changed) {
chunk_properties_.emplace(input_paint_info_.context.GetPaintController(),
new_properties, replaced,
@@ -82,6 +73,15 @@ ScopedReplacedContentPaintState::ScopedReplacedContentPaintState(
} // anonymous namespace
+bool ReplacedPainter::ShouldPaintBoxDecorationBackground(
+ const PaintInfo& paint_info) {
+ // LayoutFrameSet paints everything in the foreground phase.
+ if (layout_replaced_.IsLayoutEmbeddedContent() &&
+ layout_replaced_.Parent()->IsFrameSet())
+ return paint_info.phase == PaintPhase::kForeground;
+ return ShouldPaintSelfBlockBackground(paint_info.phase);
+}
+
void ReplacedPainter::Paint(const PaintInfo& paint_info) {
// TODO(crbug.com/797779): For now embedded contents don't know whether
// they are painted in a fragmented context and may do something bad in a
@@ -102,16 +102,32 @@ void ReplacedPainter::Paint(const PaintInfo& paint_info) {
auto paint_offset = paint_state.PaintOffset();
LayoutRect border_rect(paint_offset, layout_replaced_.Size());
- if (ShouldPaintSelfBlockBackground(local_paint_info.phase)) {
- if (layout_replaced_.StyleRef().Visibility() == EVisibility::kVisible &&
- layout_replaced_.HasBoxDecorationBackground()) {
+ if (ShouldPaintBoxDecorationBackground(local_paint_info)) {
+ bool should_paint_background = false;
+ if (layout_replaced_.StyleRef().Visibility() == EVisibility::kVisible) {
+ if (layout_replaced_.HasBoxDecorationBackground())
+ should_paint_background = true;
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled() &&
+ layout_replaced_.HasEffectiveWhitelistedTouchAction()) {
+ should_paint_background = true;
+ }
+ }
+ if (should_paint_background) {
if (layout_replaced_.HasLayer() &&
layout_replaced_.Layer()->GetCompositingState() ==
kPaintsIntoOwnBacking &&
layout_replaced_.Layer()
->GetCompositedLayerMapping()
- ->DrawsBackgroundOntoContentLayer())
+ ->DrawsBackgroundOntoContentLayer()) {
+ // If the background paints into the content layer, we can skip painting
+ // the background but still need to paint the touch action rects.
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled()) {
+ BoxPainter(layout_replaced_)
+ .RecordHitTestData(local_paint_info, border_rect,
+ layout_replaced_);
+ }
return;
+ }
BoxPainter(layout_replaced_)
.PaintBoxDecorationBackground(local_paint_info, paint_offset);
@@ -146,18 +162,19 @@ void ReplacedPainter::Paint(const PaintInfo& paint_info) {
if (skip_clip || !layout_replaced_.PhysicalContentBoxRect().IsEmpty()) {
ScopedReplacedContentPaintState content_paint_state(paint_state,
layout_replaced_);
- if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled()) {
- RecordHitTestData(content_paint_state.GetPaintInfo(),
- content_paint_state.PaintOffset());
- }
layout_replaced_.PaintReplaced(content_paint_state.GetPaintInfo(),
content_paint_state.PaintOffset());
}
if (layout_replaced_.CanResize()) {
- ScrollableAreaPainter(*layout_replaced_.Layer()->GetScrollableArea())
- .PaintResizer(local_paint_info.context, RoundedIntPoint(paint_offset),
- local_paint_info.GetCullRect());
+ auto* scrollable_area = layout_replaced_.GetScrollableArea();
+ DCHECK(scrollable_area);
+ if (!scrollable_area->HasLayerForScrollCorner()) {
+ ScrollableAreaPainter(*scrollable_area)
+ .PaintResizer(local_paint_info.context, RoundedIntPoint(paint_offset),
+ local_paint_info.GetCullRect());
+ }
+ // Otherwise the resizer will be painted by the scroll corner layer.
}
// The selection tint never gets clipped by border-radius rounding, since we
@@ -184,26 +201,6 @@ void ReplacedPainter::Paint(const PaintInfo& paint_info) {
}
}
-void ReplacedPainter::RecordHitTestData(const PaintInfo& paint_info,
- const LayoutPoint& paint_offset) {
- // Hit test display items are only needed for compositing. This flag is used
- // for for printing and drag images which do not need hit testing.
- if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
- return;
-
- if (paint_info.phase != PaintPhase::kForeground)
- return;
-
- auto touch_action = layout_replaced_.EffectiveWhitelistedTouchAction();
- if (touch_action == TouchAction::kTouchActionAuto)
- return;
-
- auto rect = layout_replaced_.VisualOverflowRect();
- rect.MoveBy(paint_offset);
- HitTestData::RecordHitTestRect(paint_info.context, layout_replaced_,
- HitTestRect(rect, touch_action));
-}
-
bool ReplacedPainter::ShouldPaint(const ScopedPaintState& paint_state) const {
const auto& paint_info = paint_state.GetPaintInfo();
if (paint_info.phase != PaintPhase::kForeground &&
diff --git a/chromium/third_party/blink/renderer/core/paint/replaced_painter.h b/chromium/third_party/blink/renderer/core/paint/replaced_painter.h
index 6da46de130f..59a32561175 100644
--- a/chromium/third_party/blink/renderer/core/paint/replaced_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/replaced_painter.h
@@ -26,10 +26,8 @@ class ReplacedPainter {
bool ShouldPaint(const ScopedPaintState&) const;
private:
- // Paint a hit test display item and record hit test data. This should be
- // called in the background paint phase even if there is no other painted
- // content.
- void RecordHitTestData(const PaintInfo&, const LayoutPoint& paint_offset);
+ bool ShouldPaintBoxDecorationBackground(const PaintInfo&);
+
const LayoutReplaced& layout_replaced_;
};
diff --git a/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.cc b/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.cc
index 7884fe3e955..2f48a9aae32 100644
--- a/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.cc
+++ b/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.cc
@@ -32,9 +32,7 @@ void ScopedPaintState::AdjustForPaintOffsetTranslation(
}
adjusted_paint_info_.emplace(input_paint_info_);
- DCHECK(paint_offset_translation->Matrix().IsAffine());
- adjusted_paint_info_->UpdateCullRect(
- paint_offset_translation->Matrix().ToAffineTransform());
+ adjusted_paint_info_->TransformCullRect(paint_offset_translation);
}
void ScopedPaintState::FinishPaintOffsetTranslationAsDrawing() {
@@ -45,11 +43,7 @@ void ScopedPaintState::FinishPaintOffsetTranslationAsDrawing() {
}
void ScopedBoxContentsPaintState::AdjustForBoxContents(const LayoutBox& box) {
- DCHECK((input_paint_info_.phase != PaintPhase::kSelfBlockBackgroundOnly ||
- BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &box, input_paint_info_)) &&
- input_paint_info_.phase != PaintPhase::kSelfOutlineOnly &&
+ DCHECK(input_paint_info_.phase != PaintPhase::kSelfOutlineOnly &&
input_paint_info_.phase != PaintPhase::kMask);
if (!fragment_to_paint_ || !fragment_to_paint_->HasLocalBorderBoxProperties())
@@ -75,16 +69,17 @@ void ScopedBoxContentsPaintState::AdjustForBoxContents(const LayoutBox& box) {
// descendant objects' Paint() method, e.g. inline boxes.
paint_offset_ += box.ScrollOrigin();
+ // If a LayoutView is using infinite cull rect, we are painting with viewport
+ // clip disabled, so don't cull the scrolling contents. This is just for
+ // completeness because we always paint the whole scrolling background even
+ // with a smaller cull rect, and the scrolling document contents are under the
+ // layer of document element which will use infinite cull rect calculated in
+ // PaintLayerPainter::AdjustForPaintProperties().
+ if (box.IsLayoutView() && input_paint_info_.GetCullRect().IsInfinite())
+ return;
+
adjusted_paint_info_.emplace(input_paint_info_);
- DCHECK(scroll_translation->Matrix().IsAffine());
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
- adjusted_paint_info_->UpdateCullRectForScrollingContents(
- EnclosingIntRect(box.OverflowClipRect(paint_offset_)),
- scroll_translation->Matrix().ToAffineTransform());
- } else {
- adjusted_paint_info_->UpdateCullRect(
- scroll_translation->Matrix().ToAffineTransform());
- }
+ adjusted_paint_info_->TransformCullRect(scroll_translation);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.h b/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.h
index a19873d93cd..c2551fc99b1 100644
--- a/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.h
+++ b/chromium/third_party/blink/renderer/core/paint/scoped_paint_state.h
@@ -86,8 +86,7 @@ class ScopedPaintState {
bool LocalRectIntersectsCullRect(const LayoutRect& local_rect) const {
LayoutRect rect_in_paint_info_space = local_rect;
rect_in_paint_info_space.MoveBy(PaintOffset());
- return GetPaintInfo().GetCullRect().IntersectsCullRect(
- rect_in_paint_info_space);
+ return GetPaintInfo().GetCullRect().Intersects(rect_in_paint_info_space);
}
protected:
diff --git a/chromium/third_party/blink/renderer/core/paint/scoped_svg_paint_state.cc b/chromium/third_party/blink/renderer/core/paint/scoped_svg_paint_state.cc
index 553dc23786b..5c97cec87a4 100644
--- a/chromium/third_party/blink/renderer/core/paint/scoped_svg_paint_state.cc
+++ b/chromium/third_party/blink/renderer/core/paint/scoped_svg_paint_state.cc
@@ -177,7 +177,7 @@ bool ScopedSVGPaintState::ApplyFilterIfNecessary(SVGResources* resources) {
// Because we cache the filter contents and do not invalidate on paint
// invalidation rect changes, we need to paint the entire filter region
// so elements outside the initial paint (due to scrolling, etc) paint.
- filter_paint_info_->cull_rect_ = CullRect(LayoutRect::InfiniteIntRect());
+ filter_paint_info_->ApplyInfiniteCullRect();
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.cc b/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.cc
index 13aa91a200f..f2f01a0e491 100644
--- a/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.cc
@@ -36,7 +36,7 @@ void ScrollableAreaPainter::PaintResizer(GraphicsContext& context,
abs_rect.MoveBy(paint_offset);
if (const auto* resizer = GetScrollableArea().Resizer()) {
- if (!cull_rect.IntersectsCullRect(abs_rect))
+ if (!cull_rect.Intersects(abs_rect))
return;
ScrollbarPainter::PaintIntoRect(*resizer, context, paint_offset,
LayoutRect(abs_rect));
@@ -133,7 +133,8 @@ void ScrollableAreaPainter::PaintOverflowControls(
if (painting_overlay_controls)
adjusted_paint_offset = GetScrollableArea().CachedOverlayScrollbarOffset();
- CullRect adjusted_cull_rect(paint_info.GetCullRect(), -adjusted_paint_offset);
+ CullRect adjusted_cull_rect = paint_info.GetCullRect();
+ adjusted_cull_rect.MoveBy(-adjusted_paint_offset);
// Overlay scrollbars paint in a second pass through the layer tree so that
// they will paint on top of everything else. If this is the normal painting
// pass, paintingOverlayControls will be false, and we should just tell the
@@ -214,18 +215,18 @@ bool ScrollableAreaPainter::OverflowControlsIntersectRect(
GetScrollableArea().GetLayoutBox()->PixelSnappedBorderBoxRect(
GetScrollableArea().Layer()->SubpixelAccumulation());
- if (cull_rect.IntersectsCullRect(
+ if (cull_rect.Intersects(
GetScrollableArea().RectForHorizontalScrollbar(border_box)))
return true;
- if (cull_rect.IntersectsCullRect(
+ if (cull_rect.Intersects(
GetScrollableArea().RectForVerticalScrollbar(border_box)))
return true;
- if (cull_rect.IntersectsCullRect(GetScrollableArea().ScrollCornerRect()))
+ if (cull_rect.Intersects(GetScrollableArea().ScrollCornerRect()))
return true;
- if (cull_rect.IntersectsCullRect(GetScrollableArea().ResizerCornerRect(
+ if (cull_rect.Intersects(GetScrollableArea().ResizerCornerRect(
border_box, kResizerForPointer)))
return true;
@@ -242,7 +243,7 @@ void ScrollableAreaPainter::PaintScrollCorner(
abs_rect.MoveBy(paint_offset);
if (const auto* scroll_corner = GetScrollableArea().ScrollCorner()) {
- if (!adjusted_cull_rect.IntersectsCullRect(abs_rect))
+ if (!adjusted_cull_rect.Intersects(abs_rect))
return;
ScrollbarPainter::PaintIntoRect(*scroll_corner, context, paint_offset,
LayoutRect(abs_rect));
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_container_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_container_painter.cc
index b2b3450bab2..7abb5388cbc 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_container_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_container_painter.cc
@@ -45,9 +45,10 @@ void SVGContainerPainter::Paint(const PaintInfo& paint_info) {
// content, does this in PaintLayerPainter::PaintSingleFragment.
if (layout_svg_container_.StyleRef().HasTransform()) {
paint_info_before_filtering.ApplyInfiniteCullRect();
- } else {
- paint_info_before_filtering.UpdateCullRect(
- layout_svg_container_.LocalToSVGParentTransform());
+ } else if (const auto* properties =
+ layout_svg_container_.FirstFragment().PaintProperties()) {
+ if (const auto* transform = properties->Transform())
+ paint_info_before_filtering.TransformCullRect(transform);
}
ScopedSVGTransformState transform_state(
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.cc
index 738109459c7..4937fa5bcf4 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.cc
@@ -67,7 +67,7 @@ static void PaintFilteredContent(GraphicsContext& context,
DrawingRecorder recorder(context, object, DisplayItem::kSVGFilter);
sk_sp<PaintFilter> image_filter =
- PaintFilterBuilder::Build(effect, kInterpolationSpaceSRGB);
+ paint_filter_builder::Build(effect, kInterpolationSpaceSRGB);
context.Save();
// Clip drawing of filtered image to the minimum required paint rect.
@@ -153,8 +153,8 @@ void SVGFilterPainter::FinishEffect(
if (filter_data->state_ == FilterData::kRecordingContent) {
DCHECK(filter->GetSourceGraphic());
sk_sp<PaintRecord> content = recording_context.EndContent(bounds);
- PaintFilterBuilder::BuildSourceGraphic(filter->GetSourceGraphic(),
- std::move(content), bounds);
+ paint_filter_builder::BuildSourceGraphic(filter->GetSourceGraphic(),
+ std::move(content), bounds);
filter_data->state_ = FilterData::kReadyToPaint;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.cc
index 495ecd4a339..cb53167f8bf 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.cc
@@ -45,8 +45,7 @@ void SVGForeignObjectPainter::PaintLayer(const PaintInfo& paint_info) {
// cull rects under transform are intentionally reset to infinity,
// to improve cache invalidation performance in the pre-paint tree
// walk (see https://http://crrev.com/482854).
- LayoutRect(LayoutRect::InfiniteIntRect()),
- paint_info.GetGlobalPaintFlags(), LayoutSize());
+ CullRect::Infinite(), paint_info.GetGlobalPaintFlags(), LayoutSize());
PaintLayerPainter(*layout_svg_foreign_object_.Layer())
.Paint(paint_info.context, layer_painting_info, paint_info.PaintFlags());
}
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_image_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_image_painter.cc
index c387cfecba2..d077d2e646e 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_image_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_image_painter.cc
@@ -29,7 +29,7 @@ void SVGImagePainter::Paint(const PaintInfo& paint_info) {
.CullRectSkipsPainting(paint_info_before_filtering)) {
return;
}
- // Images cannot have children so do not call UpdateCullRect.
+ // Images cannot have children so do not call TransformCullRect.
ScopedSVGTransformState transform_state(
paint_info_before_filtering, layout_svg_image_,
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc
index 34e32f500a8..e93430f93d2 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc
@@ -93,15 +93,13 @@ void SVGInlineTextBoxPainter::Paint(const PaintInfo& paint_info,
if (!TextShouldBePainted(text_layout_object))
return;
- DisplayItem::Type display_item_type =
- DisplayItem::PaintPhaseToDrawingType(paint_info.phase);
if (!DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, svg_inline_text_box_, display_item_type)) {
+ paint_info.context, svg_inline_text_box_, paint_info.phase)) {
LayoutObject& parent_layout_object = ParentInlineLayoutObject();
const ComputedStyle& style = parent_layout_object.StyleRef();
DrawingRecorder recorder(paint_info.context, svg_inline_text_box_,
- display_item_type);
+ paint_info.phase);
InlineTextBoxPainter text_painter(svg_inline_text_box_);
const DocumentMarkerVector& markers_to_paint =
text_painter.ComputeMarkersToPaint();
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.cc
index e41966fb3df..d92f8d07706 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.cc
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/svg/layout_svg_model_object.h"
#include "third_party/blink/renderer/core/paint/object_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
-#include "third_party/blink/renderer/platform/graphics/paint/hit_test_data.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
namespace blink {
@@ -24,7 +24,7 @@ bool SVGModelObjectPainter::CullRectSkipsPainting(const PaintInfo& paint_info) {
if (layout_svg_model_object_.IsSVGHiddenContainer())
return false;
- return !paint_info.GetCullRect().IntersectsCullRect(
+ return !paint_info.GetCullRect().IntersectsTransformed(
layout_svg_model_object_.LocalToSVGParentTransform(),
layout_svg_model_object_.VisualRectInLocalSVGCoordinates());
}
@@ -44,8 +44,8 @@ void SVGModelObjectPainter::RecordHitTestData(
auto rect =
LayoutRect(layout_svg_model_object.VisualRectInLocalSVGCoordinates());
- HitTestData::RecordHitTestRect(paint_info.context, layout_svg_model_object,
- HitTestRect(rect, touch_action));
+ HitTestDisplayItem::Record(paint_info.context, layout_svg_model_object,
+ HitTestRect(rect, touch_action));
}
void SVGModelObjectPainter::PaintOutline(const PaintInfo& paint_info) {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.cc
index 05f9ec19ba9..edd2bf774eb 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.cc
@@ -53,7 +53,7 @@ void SVGShapePainter::Paint(const PaintInfo& paint_info) {
.CullRectSkipsPainting(paint_info_before_filtering)) {
return;
}
- // Shapes cannot have children so do not call UpdateCullRect.
+ // Shapes cannot have children so do not call TransformCullRect.
ScopedSVGTransformState transform_state(
paint_info_before_filtering, layout_svg_shape_,
@@ -249,7 +249,7 @@ void SVGShapePainter::PaintMarker(const PaintInfo& paint_info,
// It's expensive to track the transformed paint cull rect for each
// marker so just disable culling. The shape paint call will already
// be culled if it is outside the paint info cull rect.
- marker_paint_info.cull_rect_ = CullRect(LayoutRect::InfiniteIntRect());
+ marker_paint_info.ApplyInfiniteCullRect();
SVGContainerPainter(marker).Paint(marker_paint_info);
builder.EndRecording(*canvas);
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_text_painter.cc b/chromium/third_party/blink/renderer/core/paint/svg_text_painter.cc
index d0065f25c7a..d645002252b 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_text_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/svg_text_painter.cc
@@ -8,6 +8,7 @@
#include "third_party/blink/renderer/core/paint/block_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/scoped_svg_paint_state.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
namespace blink {
@@ -17,7 +18,11 @@ void SVGTextPainter::Paint(const PaintInfo& paint_info) {
return;
PaintInfo block_info(paint_info);
- block_info.UpdateCullRect(layout_svg_text_.LocalToSVGParentTransform());
+ if (const auto* properties =
+ layout_svg_text_.FirstFragment().PaintProperties()) {
+ if (const auto* transform = properties->Transform())
+ block_info.TransformCullRect(transform);
+ }
ScopedSVGTransformState transform_state(
block_info, layout_svg_text_,
layout_svg_text_.LocalToSVGParentTransform());
@@ -47,8 +52,8 @@ void SVGTextPainter::RecordHitTestData(const PaintInfo& paint_info) {
return;
auto rect = LayoutRect(layout_svg_text_.VisualRectInLocalSVGCoordinates());
- HitTestData::RecordHitTestRect(paint_info.context, layout_svg_text_,
- HitTestRect(rect, touch_action));
+ HitTestDisplayItem::Record(paint_info.context, layout_svg_text_,
+ HitTestRect(rect, touch_action));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/table_cell_painter.cc b/chromium/third_party/blink/renderer/core/paint/table_cell_painter.cc
index 02479d6a7c6..e655bdb0c9b 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_cell_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/table_cell_painter.cc
@@ -41,12 +41,12 @@ void TableCellPainter::PaintContainerBackgroundBehindCell(
void TableCellPainter::PaintBackground(const PaintInfo& paint_info,
const LayoutRect& paint_rect,
const LayoutObject& background_object) {
- if (layout_table_cell_.BackgroundStolenForBeingBody())
+ if (layout_table_cell_.BackgroundTransfersToView())
return;
Color c = background_object.ResolveColor(GetCSSPropertyBackgroundColor());
const FillLayer& bg_layer = background_object.StyleRef().BackgroundLayers();
- if (bg_layer.HasImage() || c.Alpha()) {
+ if (bg_layer.AnyLayerHasImage() || c.Alpha()) {
// We have to clip here because the background would paint
// on top of the borders otherwise. This only matters for cells and rows.
bool should_clip = background_object.HasLayer() &&
@@ -80,45 +80,48 @@ void TableCellPainter::PaintBoxDecorationBackground(
bool has_box_shadow = style.BoxShadow();
bool needs_to_paint_border =
style.HasBorderDecoration() && !table->ShouldCollapseBorders();
- if (!has_background && !has_box_shadow && !needs_to_paint_border)
- return;
-
- if (DrawingRecorder::UseCachedDrawingIfPossible(
- paint_info.context, layout_table_cell_,
- DisplayItem::kBoxDecorationBackground))
- return;
-
- // TODO(chrishtr): the pixel-snapping here is likely incorrect.
- DrawingRecorder recorder(paint_info.context, layout_table_cell_,
- DisplayItem::kBoxDecorationBackground);
-
- LayoutRect paint_rect = PaintRectNotIncludingVisualOverflow(paint_offset);
-
- if (has_box_shadow)
- BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style);
-
- if (has_background)
- PaintBackground(paint_info, paint_rect, layout_table_cell_);
-
- if (has_box_shadow) {
- // If the table collapses borders, the inner rect is the border box rect
- // inset by inner half widths of collapsed borders (which are returned
- // from the overriden BorderXXX() methods). Otherwise the following code is
- // equivalent to BoxPainterBase::PaintInsetBoxShadowWithBorderRect().
- auto inner_rect = paint_rect;
- inner_rect.ContractEdges(
- layout_table_cell_.BorderTop(), layout_table_cell_.BorderRight(),
- layout_table_cell_.BorderBottom(), layout_table_cell_.BorderLeft());
- BoxPainterBase::PaintInsetBoxShadowWithInnerRect(
- paint_info, inner_rect, layout_table_cell_.StyleRef());
+ if (has_background || has_box_shadow || needs_to_paint_border) {
+ if (!DrawingRecorder::UseCachedDrawingIfPossible(
+ paint_info.context, layout_table_cell_,
+ DisplayItem::kBoxDecorationBackground)) {
+ // TODO(chrishtr): the pixel-snapping here is likely incorrect.
+ DrawingRecorder recorder(paint_info.context, layout_table_cell_,
+ DisplayItem::kBoxDecorationBackground);
+
+ LayoutRect paint_rect = PaintRectNotIncludingVisualOverflow(paint_offset);
+
+ if (has_box_shadow)
+ BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style);
+
+ if (has_background)
+ PaintBackground(paint_info, paint_rect, layout_table_cell_);
+
+ if (has_box_shadow) {
+ // If the table collapses borders, the inner rect is the border box rect
+ // inset by inner half widths of collapsed borders (which are returned
+ // from the overriden BorderXXX() methods). Otherwise the following code
+ // is equivalent to BoxPainterBase::PaintInsetBoxShadowWithBorderRect().
+ auto inner_rect = paint_rect;
+ inner_rect.ContractEdges(
+ layout_table_cell_.BorderTop(), layout_table_cell_.BorderRight(),
+ layout_table_cell_.BorderBottom(), layout_table_cell_.BorderLeft());
+ BoxPainterBase::PaintInsetBoxShadowWithInnerRect(
+ paint_info, inner_rect, layout_table_cell_.StyleRef());
+ }
+
+ if (needs_to_paint_border) {
+ BoxPainterBase::PaintBorder(
+ layout_table_cell_, layout_table_cell_.GetDocument(),
+ layout_table_cell_.GeneratingNode(), paint_info, paint_rect, style);
+ }
+ }
}
- if (!needs_to_paint_border)
- return;
-
- BoxPainterBase::PaintBorder(
- layout_table_cell_, layout_table_cell_.GetDocument(),
- layout_table_cell_.GeneratingNode(), paint_info, paint_rect, style);
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled()) {
+ LayoutRect rect = PaintRectNotIncludingVisualOverflow(paint_offset);
+ BoxPainter(layout_table_cell_)
+ .RecordHitTestData(paint_info, rect, layout_table_cell_);
+ }
}
void TableCellPainter::PaintMask(const PaintInfo& paint_info,
diff --git a/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.cc b/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.cc
index 515292251b0..f1a16a2c0b5 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.cc
+++ b/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.cc
@@ -25,14 +25,14 @@ void TablePaintInvalidator::InvalidatePaint() {
context_.old_visual_rect != context_.fragment_data->VisualRect();
for (LayoutTableCol* col = table_.FirstColumn(); col;
col = col->NextColumn()) {
- // LayoutTableCol uses the table's localVisualRect(). Should check column
+ // LayoutTableCol uses the table's LocalVisualRect(). Should check column
// for paint invalidation when table's visual rect changed.
if (visual_rect_changed)
col->SetShouldCheckForPaintInvalidation();
- // This ensures that the backgroundChangedSinceLastPaintInvalidation flag
- // is up-to-date.
+ // This ensures that the BackgroundNeedsFullPaintInvalidation flag is
+ // up-to-date.
col->EnsureIsReadyForPaintInvalidation();
- if (col->BackgroundChangedSinceLastPaintInvalidation()) {
+ if (col->BackgroundNeedsFullPaintInvalidation()) {
has_col_changed_background = true;
break;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/table_painter.cc b/chromium/third_party/blink/renderer/core/paint/table_painter.cc
index 5508fb24de2..bde9eb4092b 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/table_painter.cc
@@ -52,37 +52,22 @@ void TablePainter::PaintObject(const PaintInfo& paint_info,
ObjectPainter(layout_table_).PaintOutline(paint_info, paint_offset);
}
-void TablePainter::RecordHitTestData(const PaintInfo& paint_info,
- const LayoutPoint& paint_offset) {
- // Hit test display items are only needed for compositing. This flag is used
- // for for printing and drag images which do not need hit testing.
- if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
- return;
-
- auto touch_action = layout_table_.EffectiveWhitelistedTouchAction();
- if (touch_action == TouchAction::kTouchActionAuto)
- return;
-
- auto rect = layout_table_.BorderBoxRect();
- rect.MoveBy(paint_offset);
- HitTestData::RecordHitTestRect(paint_info.context, layout_table_,
- HitTestRect(rect, touch_action));
-}
-
void TablePainter::PaintBoxDecorationBackground(
const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
- if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled())
- RecordHitTestData(paint_info, paint_offset);
-
- if (!layout_table_.HasBoxDecorationBackground() ||
- layout_table_.StyleRef().Visibility() != EVisibility::kVisible)
- return;
-
LayoutRect rect(paint_offset, layout_table_.Size());
layout_table_.SubtractCaptionRect(rect);
- BoxPainter(layout_table_)
- .PaintBoxDecorationBackgroundWithRect(paint_info, rect);
+
+ if (layout_table_.HasBoxDecorationBackground() &&
+ layout_table_.StyleRef().Visibility() == EVisibility::kVisible) {
+ BoxPainter(layout_table_)
+ .PaintBoxDecorationBackgroundWithRect(paint_info, rect, layout_table_);
+ }
+
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled()) {
+ BoxPainter(layout_table_)
+ .RecordHitTestData(paint_info, rect, layout_table_);
+ }
}
void TablePainter::PaintMask(const PaintInfo& paint_info,
diff --git a/chromium/third_party/blink/renderer/core/paint/table_painter.h b/chromium/third_party/blink/renderer/core/paint/table_painter.h
index 7578ce44655..3cea620b7dc 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_painter.h
@@ -26,10 +26,6 @@ class TablePainter {
private:
void PaintCollapsedBorders(const PaintInfo&);
- // Paint a hit test display item and record hit test data. This should be
- // called in the background paint phase even if there is no other painted
- // content.
- void RecordHitTestData(const PaintInfo&, const LayoutPoint& paint_offset);
const LayoutTable& layout_table_;
};
diff --git a/chromium/third_party/blink/renderer/core/paint/table_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/table_painter_test.cc
index 7075a87248b..200f2aca79f 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/table_painter_test.cc
@@ -11,6 +11,8 @@
// TableRowPainter and TableCellPainter. It's difficult to separate the tests
// into individual files because of dependencies among the painter classes.
+using testing::ElementsAre;
+
namespace blink {
using TablePainterTest = PaintControllerPaintTest;
@@ -37,19 +39,21 @@ TEST_P(TablePainterTest, Background) {
IntRect interest_rect(0, 0, 200, 200);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(row1, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row1, DisplayItem::kBoxDecorationBackground)));
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
interest_rect = IntRect(0, 300, 200, 1000);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(row2, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row2, DisplayItem::kBoxDecorationBackground)));
}
TEST_P(TablePainterTest, BackgroundWithCellSpacing) {
@@ -80,32 +84,35 @@ TEST_P(TablePainterTest, BackgroundWithCellSpacing) {
IntRect interest_rect(0, 200, 200, 150);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(row1, DisplayItem::kBoxDecorationBackground),
- TestDisplayItem(cell1, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row1, DisplayItem::kBoxDecorationBackground),
+ IsSameId(&cell1, DisplayItem::kBoxDecorationBackground)));
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
// Intersects the spacing only.
interest_rect = IntRect(0, 250, 100, 100);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(row1, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row1, DisplayItem::kBoxDecorationBackground)));
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
// Intersects cell2 only.
interest_rect = IntRect(0, 350, 200, 150);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(row2, DisplayItem::kBoxDecorationBackground),
- TestDisplayItem(cell2, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row2, DisplayItem::kBoxDecorationBackground),
+ IsSameId(&cell2, DisplayItem::kBoxDecorationBackground)));
}
TEST_P(TablePainterTest, BackgroundInSelfPaintingRow) {
@@ -133,32 +140,33 @@ TEST_P(TablePainterTest, BackgroundInSelfPaintingRow) {
IntRect interest_rect(200, 0, 200, 200);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(row, DisplayItem::kBoxDecorationBackground),
- TestDisplayItem(cell1, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row, DisplayItem::kBoxDecorationBackground),
+ IsSameId(&cell1, DisplayItem::kBoxDecorationBackground)));
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
// Intersects the spacing only.
interest_rect = IntRect(300, 0, 100, 100);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(ViewBackgroundClient(),
- DisplayItem::kDocumentBackground));
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground)));
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
// Intersects cell2 only.
interest_rect = IntRect(450, 0, 200, 200);
Paint(&interest_rect);
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(ViewBackgroundClient(),
- DisplayItem::kDocumentBackground),
- TestDisplayItem(row, DisplayItem::kBoxDecorationBackground),
- TestDisplayItem(cell2, DisplayItem::kBoxDecorationBackground));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&row, DisplayItem::kBoxDecorationBackground),
+ IsSameId(&cell2, DisplayItem::kBoxDecorationBackground)));
}
TEST_P(TablePainterTest, CollapsedBorderAndOverflow) {
@@ -183,13 +191,14 @@ TEST_P(TablePainterTest, CollapsedBorderAndOverflow) {
Paint(&interest_rect);
// We should paint all display items of cell.
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(ViewBackgroundClient(), DisplayItem::kDocumentBackground),
- TestDisplayItem(cell, DisplayItem::kBoxDecorationBackground),
- TestDisplayItem(*cell.Row(), DisplayItem::kTableCollapsedBorders),
- TestDisplayItem(cell, DisplayItem::PaintPhaseToDrawingType(
- PaintPhase::kSelfOutlineOnly)));
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ DisplayItem::kDocumentBackground),
+ IsSameId(&cell, DisplayItem::kBoxDecorationBackground),
+ IsSameId(cell.Row(), DisplayItem::kTableCollapsedBorders),
+ IsSameId(&cell, DisplayItem::PaintPhaseToDrawingType(
+ PaintPhase::kSelfOutlineOnly))));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/table_row_painter.cc b/chromium/third_party/blink/renderer/core/paint/table_row_painter.cc
index 30b2a0585aa..9ba2b745488 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_row_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/table_row_painter.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/paint/scoped_paint_state.h"
#include "third_party/blink/renderer/core/paint/table_cell_painter.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
namespace blink {
@@ -62,7 +63,7 @@ void TableRowPainter::HandleChangedPartialPaint(
dirtied_columns ==
layout_table_row_.Section()->FullTableEffectiveColumnSpan()
? kFullyPainted
- : kMayBeClippedByPaintDirtyRect;
+ : kMayBeClippedByCullRect;
layout_table_row_.GetMutableForPainting().UpdatePaintResult(
paint_result, paint_info.GetCullRect());
}
@@ -74,14 +75,18 @@ void TableRowPainter::RecordHitTestData(const PaintInfo& paint_info,
if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
return;
+ // If an object is not visible, it does not participate in hit testing.
+ if (layout_table_row_.StyleRef().Visibility() != EVisibility::kVisible)
+ return;
+
auto touch_action = layout_table_row_.EffectiveWhitelistedTouchAction();
if (touch_action == TouchAction::kTouchActionAuto)
return;
auto rect = layout_table_row_.BorderBoxRect();
rect.MoveBy(paint_offset);
- HitTestData::RecordHitTestRect(paint_info.context, layout_table_row_,
- HitTestRect(rect, touch_action));
+ HitTestDisplayItem::Record(paint_info.context, layout_table_row_,
+ HitTestRect(rect, touch_action));
}
void TableRowPainter::PaintBoxDecorationBackground(
diff --git a/chromium/third_party/blink/renderer/core/paint/table_section_painter.cc b/chromium/third_party/blink/renderer/core/paint/table_section_painter.cc
index a9a4b7d7707..78f6d2826a8 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_section_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/table_section_painter.cc
@@ -278,7 +278,7 @@ void TableSectionPainter::PaintBoxDecorationBackground(
dirtied_columns == layout_table_section_.FullTableEffectiveColumnSpan() &&
dirtied_rows == layout_table_section_.FullSectionRowSpan()
? kFullyPainted
- : kMayBeClippedByPaintDirtyRect;
+ : kMayBeClippedByCullRect;
layout_table_section_.GetMutableForPainting().UpdatePaintResult(
paint_result, paint_info.GetCullRect());
diff --git a/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc b/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
index 6d0cd0b73ea..88adcefd481 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
+++ b/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
@@ -52,45 +53,52 @@ void TextPaintTimingDetector::PopulateTraceValue(
IdentifiersFactory::FrameId(&frame_view_->GetFrame()));
}
-IntRect TextPaintTimingDetector::CalculateTransformedRect(
- LayoutRect& invalidated_rect,
- const PaintLayer& painting_layer) const {
- const auto* local_transform = painting_layer.GetLayoutObject()
- .FirstFragment()
- .LocalBorderBoxProperties()
- .Transform();
- const auto* ancestor_transform = painting_layer.GetLayoutObject()
- .View()
- ->FirstFragment()
- .LocalBorderBoxProperties()
- .Transform();
- FloatRect invalidated_rect_abs = FloatRect(invalidated_rect);
- if (invalidated_rect_abs.IsEmpty() || invalidated_rect_abs.IsZero())
- return IntRect();
- GeometryMapper::SourceToDestinationRect(local_transform, ancestor_transform,
- invalidated_rect_abs);
- IntRect invalidated_rect_in_viewport = RoundedIntRect(invalidated_rect_abs);
- invalidated_rect_in_viewport.Intersect(
- frame_view_->GetScrollableArea()->VisibleContentRect());
- return invalidated_rect_in_viewport;
-}
-
-void TextPaintTimingDetector::TimerFired(TimerBase* timer) {
- if (TextRecord* largest_text_first_paint = FindLargestPaintCandidate()) {
- std::unique_ptr<TracedValue> value = TracedValue::Create();
- PopulateTraceValue(*value, *largest_text_first_paint,
- largest_text_candidate_index_max_++);
- TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
- "loading", "LargestTextPaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
- largest_text_first_paint->first_paint_time, "data", std::move(value));
+void TextPaintTimingDetector::OnLargestTextDetected(
+ const TextRecord& largest_text_record) {
+ largest_text_paint_ = largest_text_record.first_paint_time;
+
+ std::unique_ptr<TracedValue> value = TracedValue::Create();
+ PopulateTraceValue(*value, largest_text_record,
+ largest_text_candidate_index_max_++);
+ TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
+ "loading", "LargestTextPaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
+ largest_text_paint_, "data", std::move(value));
+}
+
+void TextPaintTimingDetector::OnLastTextDetected(
+ const TextRecord& last_text_record) {
+ last_text_paint_ = last_text_record.first_paint_time;
+
+ std::unique_ptr<TracedValue> value = TracedValue::Create();
+ PopulateTraceValue(*value, last_text_record,
+ last_text_candidate_index_max_++);
+ TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
+ "loading", "LastTextPaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
+ last_text_paint_, "data", std::move(value));
+}
+
+void TextPaintTimingDetector::TimerFired(TimerBase* time) {
+ // Wrap Analyze method in TimerFired so that we can drop |time| for Analyze
+ // in testing.
+ Analyze();
+}
+
+void TextPaintTimingDetector::Analyze() {
+ TextRecord* largest_text_first_paint = FindLargestPaintCandidate();
+ bool new_candidate_detected = false;
+ if (largest_text_first_paint &&
+ largest_text_first_paint->first_paint_time != largest_text_paint_) {
+ OnLargestTextDetected(*largest_text_first_paint);
+ new_candidate_detected = true;
}
- if (TextRecord* last_text_first_paint = FindLastPaintCandidate()) {
- std::unique_ptr<TracedValue> value = TracedValue::Create();
- PopulateTraceValue(*value, *last_text_first_paint,
- last_text_candidate_index_max_++);
- TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
- "loading", "LastTextPaint::Candidate", TRACE_EVENT_SCOPE_THREAD,
- last_text_first_paint->first_paint_time, "data", std::move(value));
+ TextRecord* last_text_first_paint = FindLastPaintCandidate();
+ if (last_text_first_paint &&
+ last_text_first_paint->first_paint_time != last_text_paint_) {
+ OnLastTextDetected(*last_text_first_paint);
+ new_candidate_detected = true;
+ }
+ if (new_candidate_detected) {
+ frame_view_->GetPaintTimingDetector().DidChangePerformanceTiming();
}
}
@@ -109,11 +117,25 @@ void TextPaintTimingDetector::OnPrePaintFinished() {
}
void TextPaintTimingDetector::NotifyNodeRemoved(DOMNodeId node_id) {
- if (recorded_text_node_ids_.find(node_id) != recorded_text_node_ids_.end()) {
- // We assume that the removed node's id wouldn't be recycled, so we don't
- // bother to remove these records from largest_text_heap_ or
- // latest_text_heap_, to reduce computation.
- recorded_text_node_ids_.erase(node_id);
+ if (recorded_text_node_ids_.find(node_id) == recorded_text_node_ids_.end())
+ return;
+ // We assume that removed nodes' id would not be recycled, and it's expensive
+ // to remove records from largest_text_heap_ and latest_text_heap_, so we
+ // intentionally keep the records of removed nodes in largest_text_heap_ and
+ // latest_text_heap_.
+ recorded_text_node_ids_.erase(node_id);
+ if (recorded_text_node_ids_.size() == 0) {
+ const bool largest_text_paint_invalidated =
+ largest_text_paint_ != base::TimeTicks();
+ const bool last_text_paint_invalidated =
+ last_text_paint_ != base::TimeTicks();
+ if (largest_text_paint_invalidated)
+ largest_text_paint_ = base::TimeTicks();
+ if (last_text_paint_invalidated)
+ last_text_paint_ = base::TimeTicks();
+ if (largest_text_paint_invalidated || last_text_paint_invalidated) {
+ frame_view_->GetPaintTimingDetector().DidChangePerformanceTiming();
+ }
}
}
@@ -150,11 +172,15 @@ void TextPaintTimingDetector::ReportSwapTime(
void TextPaintTimingDetector::RecordText(const LayoutObject& object,
const PaintLayer& painting_layer) {
+ if (!is_recording_)
+ return;
Node* node = object.GetNode();
if (!node)
return;
DOMNodeId node_id = DOMNodeIds::IdForNode(node);
+ // This metric defines the size of a text by its first size. So it
+ // early-returns if the text has been recorded.
if (size_zero_node_ids_.find(node_id) != size_zero_node_ids_.end())
return;
if (recorded_text_node_ids_.find(node_id) != recorded_text_node_ids_.end())
@@ -162,34 +188,38 @@ void TextPaintTimingDetector::RecordText(const LayoutObject& object,
// When node_id is not found in recorded_text_node_ids_, this invalidation is
// the text's first invalidation.
- // We deactivate the algorithm if the number of nodes exceeds limitation.
- recorded_node_count_++;
- if (recorded_node_count_ > kTextNodeNumberLimit) {
- // for assessing whether kTextNodeNumberLimit is large enough for all
- // normal cases
- TRACE_EVENT_INSTANT1("loading", "TextPaintTimingDetector::OverNodeLimit",
- TRACE_EVENT_SCOPE_THREAD, "recorded_node_count",
- recorded_node_count_);
- return;
- }
+ uint64_t rect_size = 0;
LayoutRect invalidated_rect = object.FirstFragment().VisualRect();
- int rect_size = 0;
if (!invalidated_rect.IsEmpty()) {
- IntRect invalidated_rect_in_viewport =
- CalculateTransformedRect(invalidated_rect, painting_layer);
- rect_size = invalidated_rect_in_viewport.Height() *
- invalidated_rect_in_viewport.Width();
+ rect_size = frame_view_->GetPaintTimingDetector().CalculateVisualSize(
+ invalidated_rect, painting_layer);
}
- // When rect_size == 0, it either means invalidated_rect.IsEmpty() or
- // the text is size 0 or the text is out of viewport. Either way, we don't
- // record their time, to reduce computation.
+
+ // When rect_size == 0, it either means the text size is 0 or the text is out
+ // of viewport. In either case, we don't record their time for efficiency.
if (rect_size == 0) {
size_zero_node_ids_.insert(node_id);
} else {
+ // Non-trivial text is found.
TextRecord record = {node_id, rect_size, base::TimeTicks(),
ToLayoutText(&object)->GetText()};
texts_to_record_swap_time_.push_back(record);
}
+
+ if (recorded_text_node_ids_.size() + size_zero_node_ids_.size() +
+ texts_to_record_swap_time_.size() >=
+ kTextNodeNumberLimit) {
+ Deactivate();
+ }
+}
+
+void TextPaintTimingDetector::Deactivate() {
+ TRACE_EVENT_INSTANT2("loading", "TextPaintTimingDetector::OverNodeLimit",
+ TRACE_EVENT_SCOPE_THREAD, "recorded_node_count",
+ recorded_text_node_ids_.size(), "size_zero_node_count",
+ size_zero_node_ids_.size());
+ timer_.Stop();
+ is_recording_ = false;
}
TextRecord* TextPaintTimingDetector::FindLargestPaintCandidate() {
diff --git a/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.h b/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.h
index 2e518a09e03..d009f65a73c 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.h
+++ b/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.h
@@ -14,14 +14,13 @@
namespace blink {
class PaintLayer;
-class IntRect;
class LayoutObject;
class TracedValue;
class LocalFrameView;
struct TextRecord {
DOMNodeId node_id = kInvalidDOMNodeId;
- double first_size = 0.0;
+ uint64_t first_size = 0;
base::TimeTicks first_paint_time = base::TimeTicks();
String text = "";
};
@@ -62,19 +61,23 @@ class CORE_EXPORT TextPaintTimingDetector final
void OnPrePaintFinished();
void NotifyNodeRemoved(DOMNodeId);
void Dispose() { timer_.Stop(); }
+ base::TimeTicks LargestTextPaint() const { return largest_text_paint_; }
+ base::TimeTicks LastTextPaint() const { return last_text_paint_; }
void Trace(blink::Visitor*);
private:
void PopulateTraceValue(TracedValue& value,
const TextRecord& first_text_paint,
unsigned candidate_index) const;
- IntRect CalculateTransformedRect(LayoutRect& visual_rect,
- const PaintLayer& painting_layer) const;
void TimerFired(TimerBase*);
+ void Analyze();
void ReportSwapTime(WebLayerTreeView::SwapResult result,
base::TimeTicks timestamp);
void RegisterNotifySwapTime(ReportTimeCallback callback);
+ void OnLargestTextDetected(const TextRecord&);
+ void OnLastTextDetected(const TextRecord&);
+ void Deactivate();
HashSet<DOMNodeId> recorded_text_node_ids_;
HashSet<DOMNodeId> size_zero_node_ids_;
@@ -92,9 +95,12 @@ class CORE_EXPORT TextPaintTimingDetector final
// Make sure that at most one swap promise is ongoing.
bool awaiting_swap_promise_ = false;
- unsigned recorded_node_count_ = 0;
unsigned largest_text_candidate_index_max_ = 0;
unsigned last_text_candidate_index_max_ = 0;
+ bool is_recording_ = true;
+
+ base::TimeTicks largest_text_paint_;
+ base::TimeTicks last_text_paint_;
TaskRunnerTimer<TextPaintTimingDetector> timer_;
Member<LocalFrameView> frame_view_;
};
diff --git a/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc b/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
index 573d019dd72..2b2f395d437 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
@@ -3,32 +3,53 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
-#include "third_party/blink/renderer/core/paint/paint_tracker.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
-class TextPaintTimingDetectorTest : public RenderingTest {
+class TextPaintTimingDetectorTest
+ : public RenderingTest,
+ private ScopedFirstContentfulPaintPlusPlusForTest {
public:
- void SetUp() override {
- RenderingTest::SetUp();
- RuntimeEnabledFeatures::SetPaintTrackingEnabled(true);
- }
+ TextPaintTimingDetectorTest()
+ : ScopedFirstContentfulPaintPlusPlusForTest(true) {}
+ void SetUp() override { RenderingTest::SetUp(); }
protected:
LocalFrameView& GetFrameView() { return *GetFrame().View(); }
- PaintTracker& GetPaintTracker() { return GetFrameView().GetPaintTracker(); }
+ PaintTimingDetector& GetPaintTimingDetector() {
+ return GetFrameView().GetPaintTimingDetector();
+ }
+
+ TimeTicks LargestPaintStoredResult() {
+ return GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .largest_text_paint_;
+ }
+
+ TimeTicks LastPaintStoredResult() {
+ return GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .last_text_paint_;
+ }
void UpdateAllLifecyclePhasesAndSimulateSwapTime() {
- GetFrameView().UpdateAllLifecyclePhases();
+ GetFrameView().UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
TextPaintTimingDetector& detector =
- GetPaintTracker().GetTextPaintTimingDetector();
+ GetPaintTimingDetector().GetTextPaintTimingDetector();
if (detector.texts_to_record_swap_time_.size() > 0) {
detector.ReportSwapTime(WebLayerTreeView::SwapResult::kDidSwap,
CurrentTimeTicks());
}
}
+
+ void SimulateAnalyze() {
+ GetPaintTimingDetector().GetTextPaintTimingDetector().Analyze();
+ }
};
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_NoText) {
@@ -36,7 +57,7 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_NoText) {
<div></div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
EXPECT_FALSE(record);
@@ -47,7 +68,7 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_OneText) {
<div>The only text</div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
EXPECT_TRUE(record);
@@ -68,12 +89,40 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_LargestText) {
GetDocument().body()->AppendChild(tiny_text);
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
EXPECT_EQ(record->text, "a long-long-long text");
}
+TEST_F(TextPaintTimingDetectorTest, UpdateResultWhenCandidateChanged) {
+ TimeTicks time1 = CurrentTimeTicks();
+ SetBodyInnerHTML(R"HTML(
+ <div>small text</div>
+ )HTML");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ SimulateAnalyze();
+ TimeTicks time2 = CurrentTimeTicks();
+ TimeTicks first_largest = LargestPaintStoredResult();
+ TimeTicks first_last = LastPaintStoredResult();
+ EXPECT_GE(first_largest, time1);
+ EXPECT_GE(time2, first_largest);
+ EXPECT_GE(first_last, time1);
+ EXPECT_GE(time2, first_last);
+
+ Text* larger_text = GetDocument().createTextNode("a long-long-long text");
+ GetDocument().body()->AppendChild(larger_text);
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ SimulateAnalyze();
+ TimeTicks time3 = CurrentTimeTicks();
+ TimeTicks second_largest = LargestPaintStoredResult();
+ TimeTicks second_last = LastPaintStoredResult();
+ EXPECT_GE(second_largest, time2);
+ EXPECT_GE(time3, second_largest);
+ EXPECT_GE(second_last, time2);
+ EXPECT_GE(time3, second_last);
+}
+
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportFirstPaintTime) {
TimeTicks time1 = CurrentTimeTicks();
SetBodyInnerHTML(R"HTML(
@@ -85,15 +134,15 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportFirstPaintTime) {
UpdateAllLifecyclePhasesAndSimulateSwapTime();
TimeTicks time2 = CurrentTimeTicks();
- GetDocument().getElementById("b")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("b")->setAttribute(html_names::kStyleAttr,
AtomicString("height:50px"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- GetDocument().getElementById("b")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("b")->setAttribute(html_names::kStyleAttr,
AtomicString("height:100px"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
EXPECT_EQ(record->text, "a long-long-long-long moving text");
@@ -114,11 +163,12 @@ TEST_F(TextPaintTimingDetectorTest,
<div class='out'>text outside of viewport</div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- EXPECT_FALSE(GetPaintTracker()
+ EXPECT_FALSE(GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate());
- EXPECT_FALSE(
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate());
+ EXPECT_FALSE(GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate());
}
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_IgnoreRemovedText) {
@@ -129,13 +179,47 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_IgnoreRemovedText) {
</div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLargestPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_EQ(record->text,
+ "(large text)(large text)(large text)(large text)(large "
+ "text)(large text)");
+
GetDocument().getElementById("parent")->RemoveChild(
GetDocument().getElementById("earlyLargeText"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLargestPaintCandidate();
+ EXPECT_EQ(record->text, "small text");
+}
+
+TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportLastNullCandidate) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='parent'>
+ <div id='remove'>text</div>
+ </div>
+ )HTML");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ SimulateAnalyze();
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
- EXPECT_EQ(record->text, "small text");
+ EXPECT_TRUE(record);
+ EXPECT_EQ(record->text, "text");
+ EXPECT_NE(LargestPaintStoredResult(), base::TimeTicks());
+
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("remove"));
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ SimulateAnalyze();
+ record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLargestPaintCandidate();
+ EXPECT_FALSE(record);
+ EXPECT_EQ(LargestPaintStoredResult(), base::TimeTicks());
}
TEST_F(TextPaintTimingDetectorTest,
@@ -147,7 +231,7 @@ TEST_F(TextPaintTimingDetectorTest,
</div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
EXPECT_EQ(record->text, "short");
@@ -165,10 +249,10 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_CompareSizesAtFirstPaint) {
// viewport.
GetDocument()
.getElementById("shorteningText")
- ->setAttribute(HTMLNames::styleAttr,
+ ->setAttribute(html_names::kStyleAttr,
AtomicString("position:fixed;left:-10px"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record = GetPaintTracker()
+ TextRecord* record = GetPaintTimingDetector()
.GetTextPaintTimingDetector()
.FindLargestPaintCandidate();
EXPECT_EQ(record->text, "large-to-small text");
@@ -179,8 +263,9 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_NoText) {
<div></div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_FALSE(record);
}
@@ -189,8 +274,9 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_OneText) {
<div>The only text</div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_EQ(record->text, "The only text");
}
@@ -208,8 +294,9 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_LastText) {
GetDocument().body()->AppendChild(tiny_text);
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_EQ(record->text, "3rd text");
}
@@ -227,16 +314,17 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_ReportFirstPaintTime) {
UpdateAllLifecyclePhasesAndSimulateSwapTime();
TimeTicks time2 = CurrentTimeTicks();
- GetDocument().getElementById("b")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("b")->setAttribute(html_names::kStyleAttr,
AtomicString("height:50px"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- GetDocument().getElementById("b")->setAttribute(HTMLNames::styleAttr,
+ GetDocument().getElementById("b")->setAttribute(html_names::kStyleAttr,
AtomicString("height:100px"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_EQ(record->text, "latest text");
TimeTicks firing_time = record->first_paint_time;
EXPECT_GE(firing_time, time1);
@@ -257,8 +345,9 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_IgnoreRemovedText) {
GetDocument().body()->RemoveChild(GetDocument().body()->lastChild());
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- TextRecord* record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_EQ(record->text, "earliest text");
}
@@ -270,9 +359,9 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_StopRecordingOverNodeLimit) {
UpdateAllLifecyclePhasesAndSimulateSwapTime();
for (int i = 1; i <= 4999; i++) {
- Element* div = GetDocument().CreateRawElement(HTMLNames::divTag);
+ Element* div = GetDocument().CreateRawElement(html_names::kDivTag);
div->appendChild(GetDocument().createTextNode(WTF::String::Number(i)));
- div->setAttribute(HTMLNames::styleAttr,
+ div->setAttribute(html_names::kStyleAttr,
AtomicString("position:fixed;left:0px"));
GetDocument().body()->AppendChild(div);
}
@@ -284,16 +373,44 @@ TEST_F(TextPaintTimingDetectorTest, LastTextPaint_StopRecordingOverNodeLimit) {
text = GetDocument().createTextNode(WTF::String::Number(5000));
GetDocument().body()->AppendChild(text);
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_EQ(record->text, "5000");
text = GetDocument().createTextNode(WTF::String::Number(5001));
GetDocument().body()->AppendChild(text);
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- record =
- GetPaintTracker().GetTextPaintTimingDetector().FindLastPaintCandidate();
+ record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLastPaintCandidate();
EXPECT_EQ(record->text, "5000");
}
+TEST_F(TextPaintTimingDetectorTest, LastTextPaint_ReportLastNullCandidate) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='parent'>
+ <div id='remove'>text</div>
+ </div>
+ )HTML");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ SimulateAnalyze();
+ TextRecord* record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLargestPaintCandidate();
+ EXPECT_TRUE(record);
+ EXPECT_EQ(record->text, "text");
+ EXPECT_NE(LastPaintStoredResult(), base::TimeTicks());
+
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("remove"));
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ SimulateAnalyze();
+ record = GetPaintTimingDetector()
+ .GetTextPaintTimingDetector()
+ .FindLargestPaintCandidate();
+ EXPECT_FALSE(record);
+ EXPECT_EQ(LastPaintStoredResult(), base::TimeTicks());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/text_painter.cc b/chromium/third_party/blink/renderer/core/paint/text_painter.cc
index 65369c3d025..1e91b6dbe9c 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/text_painter.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/paint/text_painter.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
diff --git a/chromium/third_party/blink/renderer/core/paint/text_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/text_painter_test.cc
index 31319930c46..99a269a730d 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/text_painter_test.cc
@@ -7,7 +7,7 @@
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_text.h"
@@ -38,10 +38,13 @@ class TextPainterTest : public RenderingTest {
is_printing ? kGlobalPaintPrinting : kGlobalPaintNormalPhase, 0);
}
- private:
+ protected:
void SetUp() override {
RenderingTest::SetUp();
SetBodyInnerHTML("Hello world");
+ UpdateLayoutText();
+ }
+ void UpdateLayoutText() {
layout_text_ =
ToLayoutText(GetDocument().body()->firstChild()->GetLayoutObject());
ASSERT_TRUE(layout_text_);
@@ -55,7 +58,7 @@ class TextPainterTest : public RenderingTest {
TEST_F(TextPainterTest, TextPaintingStyle_Simple) {
GetDocument().body()->SetInlineStyleProperty(CSSPropertyColor, CSSValueBlue);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
TextPaintStyle text_style = TextPainter::TextPaintingStyle(
GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(),
@@ -79,7 +82,7 @@ TEST_F(TextPainterTest, TextPaintingStyle_AllProperties) {
CSSPrimitiveValue::UnitType::kPixels);
GetDocument().body()->SetInlineStyleProperty(CSSPropertyTextShadow,
"1px 2px 3px yellow");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
TextPaintStyle text_style = TextPainter::TextPaintingStyle(
GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(),
@@ -109,7 +112,7 @@ TEST_F(TextPainterTest, TextPaintingStyle_UsesTextAsClip) {
CSSPrimitiveValue::UnitType::kPixels);
GetDocument().body()->SetInlineStyleProperty(CSSPropertyTextShadow,
"1px 2px 3px yellow");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
TextPaintStyle text_style = TextPainter::TextPaintingStyle(
GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(),
@@ -134,7 +137,10 @@ TEST_F(TextPainterTest,
GetDocument().GetSettings()->SetShouldPrintBackgrounds(false);
FloatSize page_size(500, 800);
GetFrame().StartPrinting(page_size, page_size, 1);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
+ // In LayoutNG, printing currently forces layout tree reattachment,
+ // so we need to re-get layout_text_.
+ UpdateLayoutText();
TextPaintStyle text_style = TextPainter::TextPaintingStyle(
GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(),
@@ -157,6 +163,9 @@ TEST_F(TextPainterTest, TextPaintingStyle_ForceBackgroundToWhite_Darkened) {
FloatSize page_size(500, 800);
GetFrame().StartPrinting(page_size, page_size, 1);
GetDocument().View()->UpdateLifecyclePhasesForPrinting();
+ // In LayoutNG, printing currently forces layout tree reattachment,
+ // so we need to re-get layout_text_.
+ UpdateLayoutText();
TextPaintStyle text_style = TextPainter::TextPaintingStyle(
GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(),
diff --git a/chromium/third_party/blink/renderer/core/paint/theme_painter.cc b/chromium/third_party/blink/renderer/core/paint/theme_painter.cc
index bdf67c30e1b..b6eae64342d 100644
--- a/chromium/third_party/blink/renderer/core/paint/theme_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/theme_painter.cc
@@ -68,6 +68,7 @@ ThemePainter::ThemePainter() = default;
#define COUNT_APPEARANCE(doc, feature) \
UseCounter::Count(doc, WebFeature::kCSSValueAppearance##feature##Rendered)
+// Returns true; Needs CSS painting and/or PaintBorderOnly().
bool ThemePainter::Paint(const LayoutObject& o,
const PaintInfo& paint_info,
const IntRect& r) {
@@ -99,14 +100,14 @@ bool ThemePainter::Paint(const LayoutObject& o,
case kCheckboxPart: {
COUNT_APPEARANCE(doc, Checkbox);
auto* input = ToHTMLInputElementOrNull(node);
- if (!input || input->type() != InputTypeNames::checkbox)
+ if (!input || input->type() != input_type_names::kCheckbox)
COUNT_APPEARANCE(doc, CheckboxForOthers);
return PaintCheckbox(node, o.GetDocument(), style, paint_info, r);
}
case kRadioPart: {
COUNT_APPEARANCE(doc, Radio);
auto* input = ToHTMLInputElementOrNull(node);
- if (!input || input->type() != InputTypeNames::radio)
+ if (!input || input->type() != input_type_names::kRadio)
COUNT_APPEARANCE(doc, RadioForOthers);
return PaintRadio(node, o.GetDocument(), style, paint_info, r);
}
@@ -120,7 +121,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
case kSquareButtonPart: {
COUNT_APPEARANCE(doc, SquareButton);
auto* input = ToHTMLInputElementOrNull(node);
- if (!input || input->type() != InputTypeNames::color)
+ if (!input || input->type() != input_type_names::kColor)
COUNT_APPEARANCE(doc, SquareButtonForOthers);
return PaintButton(node, o.GetDocument(), style, paint_info, r);
}
@@ -148,14 +149,14 @@ bool ThemePainter::Paint(const LayoutObject& o,
case kSliderHorizontalPart: {
COUNT_APPEARANCE(doc, SliderHorizontal);
auto* input = ToHTMLInputElementOrNull(node);
- if (!input || input->type() != InputTypeNames::range)
+ if (!input || input->type() != input_type_names::kRange)
COUNT_APPEARANCE(doc, SliderHorizontalForOthers);
return PaintSliderTrack(o, paint_info, r);
}
case kSliderVerticalPart: {
COUNT_APPEARANCE(doc, SliderVertical);
auto* input = ToHTMLInputElementOrNull(node);
- if (!input || input->type() != InputTypeNames::range)
+ if (!input || input->type() != input_type_names::kRange)
COUNT_APPEARANCE(doc, SliderVerticalForOthers);
return PaintSliderTrack(o, paint_info, r);
}
@@ -163,7 +164,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
COUNT_APPEARANCE(doc, SliderThumbHorizontal);
auto* input =
ToHTMLInputElementOrNull(node ? node->OwnerShadowHost() : nullptr);
- if (!input || input->type() != InputTypeNames::range)
+ if (!input || input->type() != input_type_names::kRange)
COUNT_APPEARANCE(doc, SliderThumbHorizontalForOthers);
return PaintSliderThumb(node, style, paint_info, r);
}
@@ -171,7 +172,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
COUNT_APPEARANCE(doc, SliderThumbVertical);
auto* input =
ToHTMLInputElementOrNull(node ? node->OwnerShadowHost() : nullptr);
- if (!input || input->type() != InputTypeNames::range)
+ if (!input || input->type() != input_type_names::kRange)
COUNT_APPEARANCE(doc, SliderThumbVerticalForOthers);
return PaintSliderThumb(node, style, paint_info, r);
}
@@ -205,7 +206,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
case kSearchFieldPart: {
COUNT_APPEARANCE(doc, SearchField);
auto* input = ToHTMLInputElementOrNull(node);
- if (!input || input->type() != InputTypeNames::search)
+ if (!input || input->type() != input_type_names::kSearch)
COUNT_APPEARANCE(doc, SearchFieldForOthers);
return PaintSearchField(node, style, paint_info, r);
}
@@ -213,8 +214,8 @@ bool ThemePainter::Paint(const LayoutObject& o,
COUNT_APPEARANCE(doc, SearchCancel);
auto* element = ToElementOrNull(node);
if (!element || !element->OwnerShadowHost() ||
- element->FastGetAttribute(HTMLNames::idAttr) !=
- ShadowElementNames::SearchClearButton())
+ element->FastGetAttribute(html_names::kIdAttr) !=
+ shadow_element_names::SearchClearButton())
COUNT_APPEARANCE(doc, SearchCancelForOthers);
return PaintSearchFieldCancelButton(o, paint_info, r);
}
@@ -226,6 +227,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
return true;
}
+// Returns true; Needs CSS border painting.
bool ThemePainter::PaintBorderOnly(const Node* node,
const ComputedStyle& style,
const PaintInfo& paint_info,
@@ -237,7 +239,7 @@ bool ThemePainter::PaintBorderOnly(const Node* node,
UseCounter::Count(node->GetDocument(),
WebFeature::kCSSValueAppearanceTextFieldRendered);
if (auto* input = ToHTMLInputElementOrNull(node)) {
- if (input->type() == InputTypeNames::search) {
+ if (input->type() == input_type_names::kSearch) {
UseCounter::Count(
node->GetDocument(),
WebFeature::kCSSValueAppearanceTextFieldForSearch);
@@ -261,21 +263,30 @@ bool ThemePainter::PaintBorderOnly(const Node* node,
case kSearchFieldPart:
case kListboxPart:
return true;
- case kCheckboxPart:
- case kRadioPart:
- case kPushButtonPart:
- case kSquareButtonPart:
case kButtonPart:
+ case kCheckboxPart:
+ case kInnerSpinButtonPart:
case kMenulistPart:
- case kMeterPart:
case kProgressBarPart:
+ case kPushButtonPart:
+ case kRadioPart:
+ case kSearchFieldCancelButtonPart:
case kSliderHorizontalPart:
- case kSliderVerticalPart:
case kSliderThumbHorizontalPart:
case kSliderThumbVerticalPart:
- case kSearchFieldCancelButtonPart:
+ case kSliderVerticalPart:
+ case kSquareButtonPart:
+ // Supported appearance values don't need CSS border painting.
+ return false;
default:
- break;
+ if (node) {
+ UseCounter::Count(
+ node->GetDocument(),
+ WebFeature::kCSSValueAppearanceNoImplementationSkipBorder);
+ }
+ // TODO(tkent): Should do CSS border painting for non-supported
+ // appearance values.
+ return false;
}
return false;
@@ -326,7 +337,7 @@ void ThemePainter::PaintSliderTicks(const LayoutObject& o,
return;
HTMLInputElement* input = ToHTMLInputElement(node);
- if (input->type() != InputTypeNames::range ||
+ if (input->type() != input_type_names::kRange ||
!input->UserAgentShadowRoot()->HasChildren())
return;
@@ -345,7 +356,7 @@ void ThemePainter::PaintSliderTicks(const LayoutObject& o,
IntSize thumb_size;
LayoutObject* thumb_layout_object =
input->UserAgentShadowRoot()
- ->getElementById(ShadowElementNames::SliderThumb())
+ ->getElementById(shadow_element_names::SliderThumb())
->GetLayoutObject();
if (thumb_layout_object) {
const ComputedStyle& thumb_style = thumb_layout_object->StyleRef();
@@ -363,7 +374,7 @@ void ThemePainter::PaintSliderTicks(const LayoutObject& o,
IntRect track_bounds;
LayoutObject* track_layout_object =
input->UserAgentShadowRoot()
- ->getElementById(ShadowElementNames::SliderTrack())
+ ->getElementById(shadow_element_names::SliderTrack())
->GetLayoutObject();
// We can ignoring transforms because transform is handled by the graphics
// context.
diff --git a/chromium/third_party/blink/renderer/core/paint/theme_painter_default.cc b/chromium/third_party/blink/renderer/core/paint/theme_painter_default.cc
index ed220102bb9..d4f4e51b646 100644
--- a/chromium/third_party/blink/renderer/core/paint/theme_painter_default.cc
+++ b/chromium/third_party/blink/renderer/core/paint/theme_painter_default.cc
@@ -35,7 +35,7 @@
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -44,7 +44,7 @@ namespace {
const unsigned kDefaultButtonBackgroundColor = 0xffdddddd;
bool UseMockTheme() {
- return LayoutTestSupport::IsMockThemeEnabledForTest();
+ return WebTestSupport::IsMockThemeEnabledForTest();
}
WebThemeEngine::State GetWebThemeState(const Node* node) {
diff --git a/chromium/third_party/blink/renderer/core/paint/video_painter.cc b/chromium/third_party/blink/renderer/core/paint/video_painter.cc
index 97152a71e8b..4ae8687d6eb 100644
--- a/chromium/third_party/blink/renderer/core/paint/video_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/video_painter.cc
@@ -52,11 +52,11 @@ void VideoPainter::PaintReplaced(const PaintInfo& paint_info,
if (paint_with_foreign_layer) {
if (cc::Layer* layer = layout_video_.MediaElement()->CcLayer()) {
IntRect pixel_snapped_rect = PixelSnappedIntRect(content_rect);
- layer->SetBounds(static_cast<gfx::Size>(pixel_snapped_rect.Size()));
+ layer->SetOffsetToTransformParent(
+ gfx::Vector2dF(pixel_snapped_rect.X(), pixel_snapped_rect.Y()));
+ layer->SetBounds(gfx::Size(pixel_snapped_rect.Size()));
layer->SetIsDrawable(true);
- RecordForeignLayer(
- context, layout_video_, DisplayItem::kForeignLayerVideo, layer,
- FloatPoint(pixel_snapped_rect.Location()), pixel_snapped_rect.Size());
+ RecordForeignLayer(context, DisplayItem::kForeignLayerVideo, layer);
return;
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/video_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/video_painter_test.cc
index 998110e4ae1..7a445402b80 100644
--- a/chromium/third_party/blink/renderer/core/paint/video_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/video_painter_test.cc
@@ -26,7 +26,7 @@ class StubWebMediaPlayer : public EmptyWebMediaPlayer {
const cc::Layer* GetCcLayer() { return layer_.get(); }
// WebMediaPlayer
- LoadTiming Load(LoadType, const WebMediaPlayerSource&, CORSMode) override {
+ LoadTiming Load(LoadType, const WebMediaPlayerSource&, CorsMode) override {
network_state_ = kNetworkStateLoaded;
client_->NetworkStateChanged();
ready_state_ = kReadyStateHaveEnoughData;
@@ -88,7 +88,7 @@ TEST_F(VideoPainterTestForSPv2, VideoLayerAppearsInLayerTree) {
test::RunPendingTasks();
// Force the page to paint.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Fetch the layer associated with the <video>, and check that it was
// correctly configured in the layer tree.
diff --git a/chromium/third_party/blink/renderer/core/paint/view_painter.cc b/chromium/third_party/blink/renderer/core/paint/view_painter.cc
index eeef54c1fa2..c81a3325fb5 100644
--- a/chromium/third_party/blink/renderer/core/paint/view_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/view_painter.cc
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -31,38 +32,27 @@ void ViewPainter::Paint(const PaintInfo& paint_info) {
}
void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
- if (paint_info.SkipRootBackground())
+ if (layout_view_.StyleRef().Visibility() != EVisibility::kVisible)
return;
- // This function overrides background painting for the LayoutView.
- // View background painting is special in the following ways:
- // 1. The view paints background for the root element, the background
- // positioning respects the positioning and transformation of the root
- // element.
- // 2. CSS background-clip is ignored, the background layers always expand to
- // cover the whole canvas. None of the stacking context effects (except
- // transformation) on the root element affects the background.
- // 3. The main frame is also responsible for painting the user-agent-defined
- // base background color. Conceptually it should be painted by the embedder
- // but painting it here allows culling and pre-blending optimization when
- // possible.
-
- GraphicsContext& context = paint_info.context;
+ bool has_touch_action_rect =
+ RuntimeEnabledFeatures::PaintTouchActionRectsEnabled() &&
+ (layout_view_.HasEffectiveWhitelistedTouchAction());
+ if (!layout_view_.HasBoxDecorationBackground() && !has_touch_action_rect)
+ return;
// The background rect always includes at least the visible content size.
- IntRect background_rect(
- PixelSnappedIntRect(layout_view_.OverflowClipRect(LayoutPoint())));
+ IntRect background_rect(PixelSnappedIntRect(layout_view_.BackgroundRect()));
// When printing, paint the entire unclipped scrolling content area.
if (paint_info.IsPrinting())
background_rect.Unite(layout_view_.DocumentRect());
- const DisplayItemClient* display_item_client = &layout_view_;
+ const DisplayItemClient* background_client = &layout_view_;
base::Optional<ScopedPaintChunkProperties> scoped_scroll_property;
- if (BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &layout_view_, paint_info)) {
+ if (BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_view_,
+ paint_info)) {
// Layout overflow, combined with the visible content size.
auto document_rect = layout_view_.DocumentRect();
// DocumentRect is relative to ScrollOrigin. Add ScrollOrigin to let it be
@@ -70,26 +60,57 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
// object_paint_properties.h for details.
document_rect.MoveBy(layout_view_.ScrollOrigin());
background_rect.Unite(document_rect);
- display_item_client = layout_view_.Layer()->GraphicsLayerBacking();
+ background_client = &layout_view_.GetScrollableArea()
+ ->GetScrollingBackgroundDisplayItemClient();
scoped_scroll_property.emplace(
paint_info.context.GetPaintController(),
- layout_view_.FirstFragment().ContentsProperties(), *display_item_client,
+ layout_view_.FirstFragment().ContentsProperties(), *background_client,
DisplayItem::kDocumentBackground);
}
+ if (layout_view_.HasBoxDecorationBackground()) {
+ PaintBoxDecorationBackgroundInternal(paint_info, background_rect,
+ *background_client);
+ }
+ if (has_touch_action_rect) {
+ BoxPainter(layout_view_)
+ .RecordHitTestData(paint_info, LayoutRect(background_rect),
+ *background_client);
+ }
+}
+
+// This function handles background painting for the LayoutView.
+// View background painting is special in the following ways:
+// 1. The view paints background for the root element, the background
+// positioning respects the positioning and transformation of the root
+// element.
+// 2. CSS background-clip is ignored, the background layers always expand to
+// cover the whole canvas. None of the stacking context effects (except
+// transformation) on the root element affects the background.
+// 3. The main frame is also responsible for painting the user-agent-defined
+// base background color. Conceptually it should be painted by the embedder
+// but painting it here allows culling and pre-blending optimization when
+// possible.
+void ViewPainter::PaintBoxDecorationBackgroundInternal(
+ const PaintInfo& paint_info,
+ const IntRect& background_rect,
+ const DisplayItemClient& background_client) {
+ // TODO(pdr): Can this check be removed? It is not hit in any test.
+ if (paint_info.SkipRootBackground())
+ return;
+
+ GraphicsContext& context = paint_info.context;
if (DrawingRecorder::UseCachedDrawingIfPossible(
- context, *display_item_client, DisplayItem::kDocumentBackground))
+ context, background_client, DisplayItem::kDocumentBackground)) {
return;
+ }
+ DrawingRecorder recorder(context, background_client,
+ DisplayItem::kDocumentBackground);
const Document& document = layout_view_.GetDocument();
const LocalFrameView& frame_view = *layout_view_.GetFrameView();
- bool is_main_frame = document.IsInMainFrame();
- bool paints_base_background =
- is_main_frame && (frame_view.BaseBackgroundColor().Alpha() > 0);
- bool should_clear_canvas =
- paints_base_background &&
- (document.GetSettings() &&
- document.GetSettings()->GetShouldClearDocumentBackground());
+ bool paints_base_background = document.IsInMainFrame() &&
+ (frame_view.BaseBackgroundColor().Alpha() > 0);
Color base_background_color =
paints_base_background ? frame_view.BaseBackgroundColor() : Color();
Color root_background_color = layout_view_.StyleRef().VisitedDependentColor(
@@ -98,9 +119,6 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
document.documentElement() ? document.documentElement()->GetLayoutObject()
: nullptr;
- DrawingRecorder recorder(context, *display_item_client,
- DisplayItem::kDocumentBackground);
-
// Special handling for print economy mode.
bool force_background_to_white =
BoxModelObjectPainter::ShouldForceWhiteBackgroundForPrintEconomy(
@@ -109,7 +127,7 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
// If for any reason the view background is not transparent, paint white
// instead, otherwise keep transparent as is.
if (paints_base_background || root_background_color.Alpha() ||
- layout_view_.StyleRef().BackgroundLayers().GetImage())
+ layout_view_.StyleRef().BackgroundLayers().AnyLayerHasImage())
context.FillRect(background_rect, Color::kWhite, SkBlendMode::kSrc);
return;
}
@@ -130,9 +148,8 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
if (!root_object || !root_object->IsBox()) {
background_renderable = false;
} else if (root_object->HasLayer()) {
- if (BoxModelObjectPainter::
- IsPaintingBackgroundOfPaintContainerIntoScrollingContentsLayer(
- &layout_view_, paint_info)) {
+ if (BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_view_,
+ paint_info)) {
transform.Translate(layout_view_.ScrolledContentOffset().Width(),
layout_view_.ScrolledContentOffset().Height());
}
@@ -155,6 +172,10 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
}
}
+ bool should_clear_canvas =
+ paints_base_background &&
+ (document.GetSettings() &&
+ document.GetSettings()->GetShouldClearDocumentBackground());
if (!background_renderable) {
if (base_background_color.Alpha()) {
context.FillRect(
diff --git a/chromium/third_party/blink/renderer/core/paint/view_painter.h b/chromium/third_party/blink/renderer/core/paint/view_painter.h
index a5fcfbe03b1..36563c5a9c3 100644
--- a/chromium/third_party/blink/renderer/core/paint/view_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/view_painter.h
@@ -10,6 +10,8 @@
namespace blink {
struct PaintInfo;
+class DisplayItemClient;
+class IntRect;
class LayoutView;
class ViewPainter {
@@ -23,6 +25,11 @@ class ViewPainter {
private:
const LayoutView& layout_view_;
+
+ void PaintBoxDecorationBackgroundInternal(
+ const PaintInfo&,
+ const IntRect& background_rect,
+ const DisplayItemClient& background_client);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/view_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/view_painter_test.cc
index ce4b14e41ab..f217354b9a0 100644
--- a/chromium/third_party/blink/renderer/core/paint/view_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/view_painter_test.cc
@@ -5,10 +5,13 @@
#include "third_party/blink/renderer/core/paint/view_painter.h"
#include <gtest/gtest.h>
+#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_controller_paint_test.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
+using testing::ElementsAre;
+
namespace blink {
class ViewPainterTest : public PaintControllerPaintTest {
@@ -20,11 +23,6 @@ INSTANTIATE_PAINT_TEST_CASE_P(ViewPainterTest);
void ViewPainterTest::RunFixedBackgroundTest(
bool prefer_compositing_to_lcd_text) {
- // TODO(crbug.com/792577): Cull rect for frame scrolling contents is too
- // small.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
if (prefer_compositing_to_lcd_text) {
Settings* settings = GetDocument().GetFrame()->GetSettings();
settings->SetPreferCompositingToLCDTextEnabled(true);
@@ -47,42 +45,74 @@ void ViewPainterTest::RunFixedBackgroundTest(
ScrollOffset scroll_offset(200, 150);
layout_viewport->SetScrollOffset(scroll_offset, kUserScroll);
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
- CompositedLayerMapping* clm =
- GetLayoutView().Layer()->GetCompositedLayerMapping();
-
- // If we prefer compositing to LCD text, the fixed background should go in a
- // different layer from the scrolling content; otherwise, it should go in the
- // same layer (i.e., the scrolling contents layer).
- GraphicsLayer* layer_for_background;
- if (prefer_compositing_to_lcd_text) {
- layer_for_background = clm->MainGraphicsLayer();
+ const DisplayItem* background_display_item = nullptr;
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ const auto& display_items = RootPaintController().GetDisplayItemList();
+ if (prefer_compositing_to_lcd_text) {
+ EXPECT_THAT(
+ display_items,
+ ElementsAre(IsSameId(&GetLayoutView(), kDocumentBackgroundType),
+ IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(GetDocument().body()->GetLayoutObject(),
+ kBackgroundType)));
+ background_display_item = &display_items[0];
+ } else {
+ EXPECT_THAT(
+ display_items,
+ ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(GetDocument().body()->GetLayoutObject(),
+ kBackgroundType)));
+ background_display_item = &display_items[1];
+ }
} else {
- layer_for_background = clm->ScrollingContentsLayer();
+ // If we prefer compositing to LCD text, the fixed background should go in a
+ // different layer from the scrolling content; otherwise, it should go in
+ // the same layer (i.e., the scrolling contents layer).
+ if (prefer_compositing_to_lcd_text) {
+ const auto& display_items = GetLayoutView()
+ .Layer()
+ ->GraphicsLayerBacking(&GetLayoutView())
+ ->GetPaintController()
+ .GetDisplayItemList();
+ EXPECT_THAT(
+ display_items,
+ ElementsAre(IsSameId(&GetLayoutView(), kDocumentBackgroundType)));
+ background_display_item = &display_items[0];
+ } else {
+ const auto& display_items = RootPaintController().GetDisplayItemList();
+ EXPECT_THAT(display_items,
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(GetDocument().body()->GetLayoutObject(),
+ kBackgroundType)));
+ background_display_item = &display_items[0];
+ }
}
- const DisplayItemList& display_items =
- layer_for_background->GetPaintController().GetDisplayItemList();
- const DisplayItem& background = display_items[0];
- EXPECT_EQ(background.GetType(), kDocumentBackgroundType);
- DisplayItemClient* expected_client;
- if (!prefer_compositing_to_lcd_text)
- expected_client = GetLayoutView().Layer()->GraphicsLayerBacking();
- else
- expected_client = &GetLayoutView();
- EXPECT_EQ(&background.Client(), expected_client);
sk_sp<const PaintRecord> record =
- static_cast<const DrawingDisplayItem&>(background).GetPaintRecord();
+ static_cast<const DrawingDisplayItem*>(background_display_item)
+ ->GetPaintRecord();
ASSERT_EQ(record->size(), 2u);
cc::PaintOpBuffer::Iterator it(record.get());
ASSERT_EQ((*++it)->GetType(), cc::PaintOpType::DrawRect);
- // This is the dest_rect_ calculated by BackgroundImageGeometry. For a fixed
+ // This is the dest_rect_ calculated by BackgroundImageGeometry. For a fixed
// background in scrolling contents layer, its location is the scroll offset.
SkRect rect = static_cast<const cc::DrawRectOp*>(*it)->rect;
- ASSERT_EQ(prefer_compositing_to_lcd_text ? ScrollOffset() : scroll_offset,
- ScrollOffset(rect.fLeft, rect.fTop));
+ if (prefer_compositing_to_lcd_text) {
+ EXPECT_EQ(SkRect::MakeXYWH(0, 0, 800, 600), rect);
+ } else if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ EXPECT_EQ(SkRect::MakeXYWH(0, 0, 800, 600), rect);
+ } else {
+ EXPECT_EQ(SkRect::MakeXYWH(scroll_offset.Width(), scroll_offset.Height(),
+ 800, 600),
+ rect);
+ }
}
TEST_P(ViewPainterTest, DocumentFixedBackgroundLowDPI) {
@@ -94,32 +124,195 @@ TEST_P(ViewPainterTest, DocumentFixedBackgroundHighDPI) {
}
TEST_P(ViewPainterTest, DocumentBackgroundWithScroll) {
- // TODO(crbug.com/792577): Cull rect for frame scrolling contents is too
- // small.
- if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
- return;
-
- SetBodyInnerHTML("<div style='height: 5000px'></div>");
-
- const DisplayItemClient* background_item_client;
- const DisplayItemClient* background_chunk_client;
- background_item_client = GetLayoutView().Layer()->GraphicsLayerBacking();
- background_chunk_client = background_item_client;
-
- EXPECT_DISPLAY_LIST(
- RootPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(*background_item_client, kDocumentBackgroundType));
-
- const auto& chunks = RootPaintController().GetPaintArtifact().PaintChunks();
- EXPECT_EQ(1u, chunks.size());
- const auto& chunk = chunks[0];
- EXPECT_EQ(background_chunk_client, &chunk.id.client);
-
- const auto& tree_state = chunk.properties;
- EXPECT_EQ(&EffectPaintPropertyNode::Root(), tree_state.Effect());
- const auto* properties = GetLayoutView().FirstFragment().PaintProperties();
- EXPECT_EQ(properties->ScrollTranslation(), tree_state.Transform());
- EXPECT_EQ(properties->OverflowClip(), tree_state.Clip());
+ SetBodyInnerHTML(R"HTML(
+ <style>::-webkit-scrollbar { display: none }</style>
+ <div style='height: 5000px'></div>
+ )HTML");
+
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ EXPECT_THAT(
+ RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
+ IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType)));
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(
+ 0, 1,
+ PaintChunk::Id(*GetLayoutView().Layer(),
+ DisplayItem::kLayerChunkBackground),
+ GetLayoutView().FirstFragment().LocalBorderBoxProperties()),
+ IsPaintChunk(
+ 1, 2,
+ PaintChunk::Id(ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ GetLayoutView().FirstFragment().ContentsProperties())));
+ } else {
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType)));
+ EXPECT_THAT(RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(
+ 0, 1,
+ PaintChunk::Id(ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ GetLayoutView().FirstFragment().ContentsProperties())));
+ }
+}
+
+class ViewPainterTestWithPaintTouchAction
+ : public ViewPainterTest,
+ private ScopedPaintTouchActionRectsForTest {
+ public:
+ ViewPainterTestWithPaintTouchAction()
+ : ViewPainterTest(), ScopedPaintTouchActionRectsForTest(true) {}
+
+ void SetUp() override {
+ ViewPainterTest::SetUp();
+ Settings* settings = GetDocument().GetFrame()->GetSettings();
+ settings->SetPreferCompositingToLCDTextEnabled(true);
+ }
+};
+
+INSTANTIATE_PAINT_TEST_CASE_P(ViewPainterTestWithPaintTouchAction);
+
+TEST_P(ViewPainterTestWithPaintTouchAction, TouchActionRectScrollingContents) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ html {
+ background: lightblue;
+ touch-action: none;
+ }
+ body {
+ margin: 0;
+ }
+ </style>
+ <div id='forcescroll' style='width: 0; height: 3000px;'></div>
+ )HTML");
+
+ GetFrame().DomWindow()->scrollBy(0, 100);
+ UpdateAllLifecyclePhasesForTest();
+
+ const auto& scrolling_client = ViewScrollingBackgroundClient();
+ auto scrolling_properties =
+ GetLayoutView().FirstFragment().ContentsProperties();
+ HitTestData view_hit_test_data;
+ view_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 3000));
+
+ auto* html =
+ ToLayoutBlock(GetDocument().documentElement()->GetLayoutObject());
+ HitTestData html_hit_test_data;
+ html_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 3000));
+ html_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 3000));
+
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ HitTestData non_scrolling_hit_test_data;
+ non_scrolling_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 600));
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(
+ 0, 1,
+ PaintChunk::Id(*GetLayoutView().Layer(),
+ DisplayItem::kLayerChunkBackground),
+ GetLayoutView().FirstFragment().LocalBorderBoxProperties(),
+ non_scrolling_hit_test_data),
+ IsPaintChunk(
+ 1, 2,
+ PaintChunk::Id(GetLayoutView(), DisplayItem::kScrollHitTest),
+ GetLayoutView().FirstFragment().LocalBorderBoxProperties()),
+ IsPaintChunk(
+ 2, 4, PaintChunk::Id(scrolling_client, kDocumentBackgroundType),
+ scrolling_properties, view_hit_test_data),
+ IsPaintChunk(4, 7,
+ PaintChunk::Id(*html->Layer(),
+ kNonScrollingBackgroundChunkType),
+ scrolling_properties, html_hit_test_data)));
+ } else {
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(
+ 0, 2, PaintChunk::Id(scrolling_client, kDocumentBackgroundType),
+ scrolling_properties, view_hit_test_data),
+ IsPaintChunk(2, 5,
+ PaintChunk::Id(*html->Layer(),
+ kNonScrollingBackgroundChunkType),
+ scrolling_properties, html_hit_test_data)));
+ }
+}
+
+TEST_P(ViewPainterTestWithPaintTouchAction,
+ TouchActionRectNonScrollingContents) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ html {
+ background: radial-gradient(
+ circle at 100px 100px, blue, transparent 200px) fixed;
+ touch-action: none;
+ }
+ body {
+ margin: 0;
+ }
+ </style>
+ <div id='forcescroll' style='width: 0; height: 3000px;'></div>
+ )HTML");
+
+ GetFrame().DomWindow()->scrollBy(0, 100);
+ UpdateAllLifecyclePhasesForTest();
+
+ auto* view = &GetLayoutView();
+ auto non_scrolling_properties =
+ view->FirstFragment().LocalBorderBoxProperties();
+ HitTestData view_hit_test_data;
+ view_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 600));
+ auto* html =
+ ToLayoutBlock(GetDocument().documentElement()->GetLayoutObject());
+ auto scrolling_properties = view->FirstFragment().ContentsProperties();
+ HitTestData scrolling_hit_test_data;
+ scrolling_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 3000));
+ scrolling_hit_test_data.touch_action_rects.emplace_back(
+ LayoutRect(0, 0, 800, 3000));
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(0, 2,
+ PaintChunk::Id(*view->Layer(),
+ DisplayItem::kLayerChunkBackground),
+ non_scrolling_properties, view_hit_test_data),
+ IsPaintChunk(2, 3,
+ PaintChunk::Id(*view, DisplayItem::kScrollHitTest),
+ non_scrolling_properties),
+ IsPaintChunk(3, 6,
+ PaintChunk::Id(*html->Layer(),
+ kNonScrollingBackgroundChunkType),
+ scrolling_properties, scrolling_hit_test_data)));
+ } else {
+ auto& non_scrolling_paint_controller =
+ view->Layer()->GraphicsLayerBacking(view)->GetPaintController();
+ EXPECT_THAT(
+ non_scrolling_paint_controller.PaintChunks(),
+ ElementsAre(IsPaintChunk(
+ 0, 2,
+ PaintChunk::Id(*view->Layer(), kNonScrollingBackgroundChunkType),
+ non_scrolling_properties, view_hit_test_data)));
+ EXPECT_THAT(
+ RootPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(
+ 0, 3,
+ PaintChunk::Id(*html->Layer(), kNonScrollingBackgroundChunkType),
+ scrolling_properties, scrolling_hit_test_data)));
+ }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/probe/core_probes.cc b/chromium/third_party/blink/renderer/core/probe/core_probes.cc
index c45771cf2a9..e5592129a75 100644
--- a/chromium/third_party/blink/renderer/core/probe/core_probes.cc
+++ b/chromium/third_party/blink/renderer/core/probe/core_probes.cc
@@ -79,7 +79,7 @@ void AsyncTaskScheduled(ExecutionContext* context,
void* task) {
TRACE_EVENT_FLOW_BEGIN1("devtools.timeline.async", "AsyncTask",
TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task)),
- "data", InspectorAsyncTask::Data(name));
+ "data", inspector_async_task::Data(name));
if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context)))
debugger->AsyncTaskScheduled(name, AsyncId(task), true);
}
diff --git a/chromium/third_party/blink/renderer/core/probe/core_probes.json5 b/chromium/third_party/blink/renderer/core/probe/core_probes.json5
index ef19904db25..f295c86f873 100644
--- a/chromium/third_party/blink/renderer/core/probe/core_probes.json5
+++ b/chromium/third_party/blink/renderer/core/probe/core_probes.json5
@@ -123,7 +123,7 @@
"didFailLoading",
"didFinishLoading",
"didFinishXHR",
- "didReceiveCORSRedirectResponse",
+ "didReceiveCorsRedirectResponse",
"didReceiveData",
"didReceiveBlob",
"didReceiveEncodedDataLength",
@@ -139,7 +139,7 @@
"scriptImported",
"shouldBlockRequest",
"shouldBypassServiceWorker",
- "shouldForceCORSPreflight",
+ "shouldForceCorsPreflight",
"willDispatchEventSourceEvent",
"willLoadXHR",
"willSendEventSourceRequest",
@@ -208,17 +208,12 @@
"willSendRequest",
]
},
- InspectorWorkerAgent: {
- probes: [
- "didStartWorker",
- "shouldWaitForDebuggerOnWorkerStart",
- "workerTerminated",
- ]
- },
- InspectorSession: {
+ DevToolsSession: {
+ class: "DevToolsSession",
probes: [
"didStartProvisionalLoad",
"didFailProvisionalLoad",
+ "didCommitLoad",
]
},
}
diff --git a/chromium/third_party/blink/renderer/core/probe/core_probes.pidl b/chromium/third_party/blink/renderer/core/probe/core_probes.pidl
index 11322da0f75..8c9517e9a27 100644
--- a/chromium/third_party/blink/renderer/core/probe/core_probes.pidl
+++ b/chromium/third_party/blink/renderer/core/probe/core_probes.pidl
@@ -94,11 +94,11 @@ interface CoreProbes {
void willSendRequest([Keep] ExecutionContext*, unsigned long identifier, DocumentLoader*, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo&, ResourceType);
void markResourceAsCached(LocalFrame*, DocumentLoader*, unsigned long identifier);
void didReceiveResourceResponse(ExecutionContext*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, Resource*);
- void didReceiveData(ExecutionContext*, unsigned long identifier, DocumentLoader*, const char* data, int dataLength);
+ void didReceiveData(ExecutionContext*, unsigned long identifier, DocumentLoader*, const char* data, size_t dataLength);
void didReceiveBlob(ExecutionContext*, unsigned long identifier, DocumentLoader*, BlobDataHandle*);
- void didReceiveEncodedDataLength(ExecutionContext*, DocumentLoader* loader, unsigned long identifier, int encodedDataLength);
+ void didReceiveEncodedDataLength(ExecutionContext*, DocumentLoader* loader, unsigned long identifier, size_t encodedDataLength);
void didFinishLoading(ExecutionContext*, unsigned long identifier, DocumentLoader*, TimeTicks finishTime, int64_t encoded_data_length, int64_t decodedBodyLength, bool should_report_corb_blocking);
- void didReceiveCORSRedirectResponse(ExecutionContext*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, Resource*);
+ void didReceiveCorsRedirectResponse(ExecutionContext*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, Resource*);
void didFailLoading(ExecutionContext*, unsigned long identifier, DocumentLoader*, const ResourceError&);
void willSendEventSourceRequest(ExecutionContext*, ThreadableLoaderClient* eventSource);
void willDispatchEventSourceEvent(ExecutionContext*, unsigned long identifier, const AtomicString& eventName, const AtomicString& eventId, const String& data);
@@ -122,8 +122,6 @@ interface CoreProbes {
void frameStoppedLoading([Keep] LocalFrame*);
void frameScheduledNavigation([Keep] LocalFrame*, ScheduledNavigation*);
void frameClearedScheduledNavigation([Keep] LocalFrame*);
- void didStartWorker(ExecutionContext*, WorkerInspectorProxy* proxy, bool waitingForDebugger);
- void workerTerminated(ExecutionContext*, WorkerInspectorProxy* proxy);
void didCreateWebSocket([Keep] ExecutionContext*, unsigned long identifier, const KURL& requestURL, const String& protocol);
void willSendWebSocketHandshakeRequest([Keep] ExecutionContext*, unsigned long identifier, network::mojom::blink::WebSocketHandshakeRequest* request);
void didReceiveWebSocketHandshakeResponse([Keep] ExecutionContext*, unsigned long identifier, network::mojom::blink::WebSocketHandshakeRequest* request, network::mojom::blink::WebSocketHandshakeResponse* response);
@@ -153,8 +151,7 @@ interface CoreProbes {
V8Compile([Keep] ExecutionContext* context, const String& file_name, int line, int column);
ParseHTML(Document* document, HTMLDocumentParser* parser);
void forcePseudoState([Keep] Element* element, CSSSelector::PseudoType pseudoState, bool* result);
- void shouldWaitForDebuggerOnWorkerStart(ExecutionContext* context, bool* result);
- void shouldForceCORSPreflight(ExecutionContext*, bool* result);
+ void shouldForceCorsPreflight(ExecutionContext*, bool* result);
void shouldBlockRequest(ExecutionContext*, const KURL&, bool* result);
void shouldBypassServiceWorker(ExecutionContext* context, bool* result);
void consoleTimeStamp(ExecutionContext*, const String& title);
diff --git a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.cc b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.cc
index 33acd56e78e..831ac96a5de 100644
--- a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.cc
+++ b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.cc
@@ -17,11 +17,11 @@ namespace blink {
ResizeObserver* ResizeObserver::Create(Document& document,
V8ResizeObserverCallback* callback) {
- return new ResizeObserver(callback, document);
+ return MakeGarbageCollected<ResizeObserver>(callback, document);
}
ResizeObserver* ResizeObserver::Create(Document& document, Delegate* delegate) {
- return new ResizeObserver(delegate, document);
+ return MakeGarbageCollected<ResizeObserver>(delegate, document);
}
ResizeObserver::ResizeObserver(V8ResizeObserverCallback* callback,
@@ -50,7 +50,7 @@ void ResizeObserver::observe(Element* target) {
if (observer_map.Contains(this))
return; // Already registered.
- auto* observation = new ResizeObservation(target, this);
+ auto* observation = MakeGarbageCollected<ResizeObservation>(target, this);
observations_.insert(observation);
observer_map.Set(this, observation);
@@ -141,7 +141,8 @@ void ResizeObserver::DeliverObservations() {
content_rect.SetHeight(AdjustForAbsoluteZoom::AdjustLayoutUnit(
content_rect.Height(), style));
}
- auto* entry = new ResizeObserverEntry(observation->Target(), content_rect);
+ auto* entry = MakeGarbageCollected<ResizeObserverEntry>(
+ observation->Target(), content_rect);
entries.push_back(entry);
}
diff --git a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.h b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.h
index 1aaea12270c..384c9ca8f15 100644
--- a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.h
+++ b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.h
@@ -43,6 +43,8 @@ class CORE_EXPORT ResizeObserver final
static ResizeObserver* Create(Document&, V8ResizeObserverCallback*);
static ResizeObserver* Create(Document&, Delegate*);
+ ResizeObserver(V8ResizeObserverCallback*, Document&);
+ ResizeObserver(Delegate*, Document&);
~ResizeObserver() override = default;
// API methods
@@ -64,9 +66,6 @@ class CORE_EXPORT ResizeObserver final
void Trace(blink::Visitor*) override;
private:
- ResizeObserver(V8ResizeObserverCallback*, Document&);
- ResizeObserver(Delegate*, Document&);
-
using ObservationList = HeapLinkedHashSet<WeakMember<ResizeObservation>>;
// Either of |callback_| and |delegate_| should be non-null.
diff --git a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_test.cc b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_test.cc
index 1dfe3f98d21..1c02202fb10 100644
--- a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_test.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/resize_observer/resize_observer.h"
#include "third_party/blink/public/web/web_heap.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
@@ -14,7 +15,6 @@
#include "third_party/blink/renderer/core/testing/sim/sim_compositor.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -74,9 +74,9 @@ TEST_F(ResizeObserverUnitTest, ResizeObservationSize) {
Element* dom_target = GetDocument().getElementById("domTarget");
Element* svg_target = GetDocument().getElementById("svgTarget");
ResizeObservation* dom_observation =
- new ResizeObservation(dom_target, observer);
+ MakeGarbageCollected<ResizeObservation>(dom_target, observer);
ResizeObservation* svg_observation =
- new ResizeObservation(svg_target, observer);
+ MakeGarbageCollected<ResizeObservation>(svg_target, observer);
// Initial observation is out of sync
ASSERT_TRUE(dom_observation->ObservationSizeOutOfSync());
@@ -117,14 +117,16 @@ TEST_F(ResizeObserverUnitTest, TestMemoryLeaks) {
//
script_controller.ExecuteScriptInMainWorldAndReturnValue(
ScriptSourceCode("var ro = new ResizeObserver( entries => {});"), KURL(),
- kOpaqueResource, ScriptFetchOptions(),
+ SanitizeScriptErrors::kSanitize, ScriptFetchOptions(),
ScriptController::kExecuteScriptWhenScriptsDisabled);
ASSERT_EQ(observers.size(), 1U);
script_controller.ExecuteScriptInMainWorldAndReturnValue(
- ScriptSourceCode("ro = undefined;"), KURL(), kOpaqueResource,
- ScriptFetchOptions(),
+ ScriptSourceCode("ro = undefined;"), KURL(),
+ SanitizeScriptErrors::kSanitize, ScriptFetchOptions(),
ScriptController::kExecuteScriptWhenScriptsDisabled);
- V8GCController::CollectAllGarbageForTesting(v8::Isolate::GetCurrent());
+ V8GCController::CollectAllGarbageForTesting(
+ v8::Isolate::GetCurrent(),
+ v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
WebHeap::CollectAllGarbageForTesting();
ASSERT_EQ(observers.IsEmpty(), true);
@@ -136,17 +138,21 @@ TEST_F(ResizeObserverUnitTest, TestMemoryLeaks) {
"var el = document.createElement('div');"
"ro.observe(el);"
"ro = undefined;"),
- KURL(), kOpaqueResource, ScriptFetchOptions(),
+ KURL(), SanitizeScriptErrors::kSanitize, ScriptFetchOptions(),
ScriptController::kExecuteScriptWhenScriptsDisabled);
ASSERT_EQ(observers.size(), 1U);
- V8GCController::CollectAllGarbageForTesting(v8::Isolate::GetCurrent());
+ V8GCController::CollectAllGarbageForTesting(
+ v8::Isolate::GetCurrent(),
+ v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
WebHeap::CollectAllGarbageForTesting();
ASSERT_EQ(observers.size(), 1U);
script_controller.ExecuteScriptInMainWorldAndReturnValue(
- ScriptSourceCode("el = undefined;"), KURL(), kOpaqueResource,
- ScriptFetchOptions(),
+ ScriptSourceCode("el = undefined;"), KURL(),
+ SanitizeScriptErrors::kSanitize, ScriptFetchOptions(),
ScriptController::kExecuteScriptWhenScriptsDisabled);
- V8GCController::CollectAllGarbageForTesting(v8::Isolate::GetCurrent());
+ V8GCController::CollectAllGarbageForTesting(
+ v8::Isolate::GetCurrent(),
+ v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
WebHeap::CollectAllGarbageForTesting();
ASSERT_EQ(observers.IsEmpty(), true);
}
diff --git a/chromium/third_party/blink/renderer/core/scheduler/frame_throttling_test.cc b/chromium/third_party/blink/renderer/core/scheduler/frame_throttling_test.cc
index 1893df4cd73..2d91b4240da 100644
--- a/chromium/third_party/blink/renderer/core/scheduler/frame_throttling_test.cc
+++ b/chromium/third_party/blink/renderer/core/scheduler/frame_throttling_test.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/public/web/web_frame_content_dumper.h"
#include "third_party/blink/public/web/web_hit_test_result.h"
#include "third_party/blink/public/web/web_settings.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -26,7 +27,6 @@
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/testing/paint_test_configurations.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
@@ -35,7 +35,7 @@ using testing::_;
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// NOTE: This test uses <iframe sandbox> to create cross origin iframes.
@@ -75,6 +75,11 @@ class FrameThrottlingTest : public PaintTestConfigurations, public SimTest {
}
return result;
}
+
+ void UpdateAllLifecyclePhases() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
};
INSTANTIATE_PAINT_TEST_CASE_P(FrameThrottlingTest);
@@ -94,13 +99,13 @@ TEST_P(FrameThrottlingTest, ThrottleInvisibleFrames) {
EXPECT_FALSE(frame_document->View()->IsHiddenForThrottling());
// Moving the child fully outside the parent makes it invisible.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_FALSE(GetDocument().View()->IsHiddenForThrottling());
EXPECT_TRUE(frame_document->View()->IsHiddenForThrottling());
// A partially visible child is considered visible.
- frame_element->setAttribute(styleAttr,
+ frame_element->setAttribute(kStyleAttr,
"transform: translate(-50px, 0px, 0px)");
CompositeFrame();
EXPECT_FALSE(GetDocument().View()->IsHiddenForThrottling());
@@ -128,7 +133,7 @@ TEST_P(FrameThrottlingTest, HiddenSameOriginFramesAreNotThrottled) {
EXPECT_FALSE(inner_frame_document->View()->CanThrottleRendering());
// Hidden same origin frames are not throttled.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_FALSE(GetDocument().View()->CanThrottleRendering());
EXPECT_FALSE(frame_document->View()->CanThrottleRendering());
@@ -157,7 +162,7 @@ TEST_P(FrameThrottlingTest, HiddenCrossOriginFramesAreThrottled) {
EXPECT_FALSE(inner_frame_document->View()->CanThrottleRendering());
// Hidden cross origin frames are throttled.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_FALSE(GetDocument().View()->CanThrottleRendering());
EXPECT_FALSE(frame_document->View()->CanThrottleRendering());
@@ -185,7 +190,7 @@ TEST_P(FrameThrottlingTest, IntersectionObservationOverridesThrottling) {
GetDocument().Lifecycle());
// Hidden cross origin frames are throttled.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_FALSE(GetDocument().View()->CanThrottleRendering());
EXPECT_FALSE(frame_document->View()->CanThrottleRendering());
@@ -250,7 +255,7 @@ TEST_P(FrameThrottlingTest, HiddenCrossOriginZeroByZeroFramesAreNotThrottled) {
EXPECT_FALSE(inner_frame_document->View()->CanThrottleRendering());
// The frame is not throttled because its dimensions are 0x0.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_FALSE(GetDocument().View()->CanThrottleRendering());
EXPECT_FALSE(frame_document->View()->CanThrottleRendering());
@@ -268,7 +273,7 @@ TEST_P(FrameThrottlingTest, ThrottledLifecycleUpdate) {
auto* frame_document = frame_element->contentDocument();
// Enable throttling for the child frame.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(frame_document->View()->CanThrottleRendering());
EXPECT_EQ(DocumentLifecycle::kPaintClean,
@@ -279,13 +284,13 @@ TEST_P(FrameThrottlingTest, ThrottledLifecycleUpdate) {
// TODO(skyostil): these expectations are either wrong, or the test is
// not exercising the code correctly. PaintClean means the entire lifecycle
// ran.
- frame_element->setAttribute(widthAttr, "50");
+ frame_element->setAttribute(kWidthAttr, "50");
CompositeFrame();
EXPECT_EQ(DocumentLifecycle::kPaintClean,
frame_document->Lifecycle().GetState());
// A hit test will not force a complete lifecycle update.
- WebView().HitTestResultAt(WebPoint(0, 0));
+ WebView().HitTestResultAt(gfx::Point());
EXPECT_EQ(DocumentLifecycle::kPaintClean,
frame_document->Lifecycle().GetState());
}
@@ -300,13 +305,13 @@ TEST_P(FrameThrottlingTest, UnthrottlingFrameSchedulesAnimation) {
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
// First make the child hidden to enable throttling.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
EXPECT_FALSE(Compositor().NeedsBeginFrame());
// Then bring it back on-screen. This should schedule an animation update.
- frame_element->setAttribute(styleAttr, "");
+ frame_element->setAttribute(kStyleAttr, "");
CompositeFrame();
EXPECT_TRUE(Compositor().NeedsBeginFrame());
}
@@ -327,17 +332,17 @@ TEST_P(FrameThrottlingTest, MutatingThrottledFrameDoesNotCauseAnimation) {
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
// Move the frame offscreen to throttle it.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
// Mutating the throttled frame should not cause an animation to be scheduled.
frame_element->contentDocument()->documentElement()->setAttribute(
- styleAttr, "background: green");
+ kStyleAttr, "background: green");
EXPECT_FALSE(Compositor().NeedsBeginFrame());
// Move the frame back on screen to unthrottle it.
- frame_element->setAttribute(styleAttr, "");
+ frame_element->setAttribute(kStyleAttr, "");
EXPECT_TRUE(Compositor().NeedsBeginFrame());
// The first frame we composite after unthrottling won't contain the
@@ -364,12 +369,12 @@ TEST_P(FrameThrottlingTest, SynchronousLayoutInThrottledFrame) {
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
// Change the size of a div in the throttled frame.
auto* div_element = frame_element->contentDocument()->getElementById("div");
- div_element->setAttribute(styleAttr, "width: 50px");
+ div_element->setAttribute(kStyleAttr, "width: 50px");
// Querying the width of the div should do a synchronous layout update even
// though the frame is being throttled.
@@ -388,7 +393,7 @@ TEST_P(FrameThrottlingTest, UnthrottlingTriggersRepaint) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -427,7 +432,7 @@ TEST_P(FrameThrottlingTest, UnthrottlingTriggersRepaintInCompositedChild) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -457,14 +462,14 @@ TEST_P(FrameThrottlingTest, ChangeStyleInThrottledFrame) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
// Change the background color of the frame's contents from red to green.
- frame_element->contentDocument()->body()->setAttribute(styleAttr,
+ frame_element->contentDocument()->body()->setAttribute(kStyleAttr,
"background: green");
// Scroll down to unthrottle the frame.
@@ -541,7 +546,7 @@ TEST_P(FrameThrottlingTest, ThrottledFrameWithFocus) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -552,7 +557,7 @@ TEST_P(FrameThrottlingTest, ThrottledFrameWithFocus) {
EXPECT_FALSE(Compositor().HasSelection());
GetDocument().GetPage()->GetFocusController().SetFocusedFrame(
frame_element->contentDocument()->GetFrame());
- GetDocument().body()->setAttribute(styleAttr, "background: green");
+ GetDocument().body()->setAttribute(kStyleAttr, "background: green");
CompositeFrame();
EXPECT_FALSE(Compositor().HasSelection());
}
@@ -575,7 +580,7 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledFrame) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -583,11 +588,11 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledFrame) {
// Change style of the frame's content to make it in VisualUpdatePending
// state.
- frame_element->contentDocument()->body()->setAttribute(styleAttr,
+ frame_element->contentDocument()->body()->setAttribute(kStyleAttr,
"background: green");
// Change root frame's layout so that the next lifecycle update will call
// ScrollingCoordinator::UpdateAfterPaint().
- GetDocument().body()->setAttribute(styleAttr, "margin: 20px");
+ GetDocument().body()->setAttribute(kStyleAttr, "margin: 20px");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
frame_element->contentDocument()->Lifecycle().GetState());
@@ -596,7 +601,7 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledFrame) {
// This will call ScrollingCoordinator::UpdateAfterPaint() and should not
// cause assert failure about isAllowedToQueryCompositingState() in the
// throttled frame.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
test::RunPendingTasks();
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
frame_element->contentDocument()->Lifecycle().GetState());
@@ -607,7 +612,7 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledFrame) {
// Make the frame visible by changing its transform. This doesn't cause a
// layout, but should still unthrottle the frame.
- frame_element->setAttribute(styleAttr, "transform: translateY(0px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(0px)");
CompositeFrame();
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -639,7 +644,7 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledLayer) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -647,11 +652,11 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledLayer) {
// Change style of the frame's content to make it in VisualUpdatePending
// state.
- frame_element->contentDocument()->body()->setAttribute(styleAttr,
+ frame_element->contentDocument()->body()->setAttribute(kStyleAttr,
"background: green");
// Change root frame's layout so that the next lifecycle update will call
// ScrollingCoordinator::UpdateAfterPaint().
- GetDocument().body()->setAttribute(styleAttr, "margin: 20px");
+ GetDocument().body()->setAttribute(kStyleAttr, "margin: 20px");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
frame_element->contentDocument()->Lifecycle().GetState());
@@ -660,7 +665,7 @@ TEST_P(FrameThrottlingTest, ScrollingCoordinatorShouldSkipThrottledLayer) {
// This will call ScrollingCoordinator::UpdateAfterPaint() and should not
// cause an assert failure about isAllowedToQueryCompositingState() in the
// throttled frame.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
test::RunPendingTasks();
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
frame_element->contentDocument()->Lifecycle().GetState());
@@ -681,7 +686,7 @@ TEST_P(FrameThrottlingTest,
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -689,11 +694,11 @@ TEST_P(FrameThrottlingTest,
// Change style of the frame's content to make it in VisualUpdatePending
// state.
- frame_element->contentDocument()->body()->setAttribute(styleAttr,
+ frame_element->contentDocument()->body()->setAttribute(kStyleAttr,
"background: green");
// Change root frame's layout so that the next lifecycle update will call
// ScrollingCoordinator::UpdateAfterPaint().
- GetDocument().body()->setAttribute(styleAttr, "margin: 20px");
+ GetDocument().body()->setAttribute(kStyleAttr, "margin: 20px");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
frame_element->contentDocument()->Lifecycle().GetState());
@@ -708,7 +713,7 @@ TEST_P(FrameThrottlingTest,
// Make the frame visible by changing its transform. This doesn't cause a
// layout, but should still unthrottle the frame.
- frame_element->setAttribute(styleAttr, "transform: translateY(0px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(0px)");
CompositeFrame(); // Unthrottle the frame.
EXPECT_FALSE(
@@ -739,7 +744,7 @@ TEST_P(FrameThrottlingTest, UnthrottleByTransformingWithoutLayout) {
// Move the frame offscreen to throttle it.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -747,7 +752,7 @@ TEST_P(FrameThrottlingTest, UnthrottleByTransformingWithoutLayout) {
// Make the frame visible by changing its transform. This doesn't cause a
// layout, but should still unthrottle the frame.
- frame_element->setAttribute(styleAttr, "transform: translateY(0px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(0px)");
CompositeFrame();
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -777,7 +782,7 @@ TEST_P(FrameThrottlingTest, ThrottledTopLevelEventHandlerIgnored) {
)HTML");
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
DocumentLifecycle::AllowThrottlingScope throttling_scope(
GetDocument().Lifecycle());
CompositeFrame(); // Throttle the frame.
@@ -807,7 +812,7 @@ TEST_P(FrameThrottlingTest, ThrottledTopLevelEventHandlerIgnored) {
// Unthrottling the frame makes the touch handlers active again. Note that
// both handlers get combined into the same rectangle in the region, so
// there is only one rectangle in total.
- frame_element->setAttribute(styleAttr, "transform: translateY(0px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(0px)");
CompositeFrame(); // Unthrottle the frame.
CompositeFrame(); // Update touch handler regions.
EXPECT_EQ(1u, TouchHandlerRegionSize());
@@ -838,7 +843,7 @@ TEST_P(FrameThrottlingTest, ThrottledEventHandlerIgnored) {
)HTML");
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
DocumentLifecycle::AllowThrottlingScope throttling_scope(
GetDocument().Lifecycle());
CompositeFrame(); // Throttle the frame.
@@ -866,7 +871,7 @@ TEST_P(FrameThrottlingTest, ThrottledEventHandlerIgnored) {
EXPECT_EQ(0u, TouchHandlerRegionSize());
// Unthrottling the frame makes the touch handler active again.
- frame_element->setAttribute(styleAttr, "transform: translateY(0px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(0px)");
CompositeFrame(); // Unthrottle the frame.
CompositeFrame(); // Update touch handler regions.
EXPECT_EQ(1u, TouchHandlerRegionSize());
@@ -885,7 +890,7 @@ TEST_P(FrameThrottlingTest, DumpThrottledFrame) {
frame_resource.Complete("");
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -924,7 +929,7 @@ TEST_P(FrameThrottlingTest, PaintingViaGraphicsLayerIsThrottled) {
// graphics layer.
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr,
+ frame_element->setAttribute(kStyleAttr,
"transform: translateY(480px) translateZ(0px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -965,7 +970,7 @@ TEST_P(FrameThrottlingTest, ThrottleInnerCompositedLayer) {
EXPECT_EQ(7u, commands_not_throttled.DrawCount());
// Move the frame offscreen to throttle it.
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
CompositeFrame();
@@ -980,7 +985,7 @@ TEST_P(FrameThrottlingTest, ThrottleInnerCompositedLayer) {
EXPECT_EQ(5u, commands_throttled.DrawCount());
// Remove compositing trigger of inner_div.
- inner_div->setAttribute(styleAttr, "background: yellow; overflow: hidden");
+ inner_div->setAttribute(kStyleAttr, "background: yellow; overflow: hidden");
// Do an unthrottled style and layout update, simulating the situation
// triggered by script style/layout access.
GetDocument().View()->UpdateLifecycleToLayoutClean();
@@ -988,7 +993,7 @@ TEST_P(FrameThrottlingTest, ThrottleInnerCompositedLayer) {
// And a throttled full lifecycle update.
DocumentLifecycle::AllowThrottlingScope throttling_scope(
GetDocument().Lifecycle());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
// The inner div should still be composited because compositing update is
// throttled, though the inner_div's self-painting status has been updated.
@@ -1003,7 +1008,7 @@ TEST_P(FrameThrottlingTest, ThrottleInnerCompositedLayer) {
EXPECT_EQ(5u, commands_throttled1.DrawCount());
// Move the frame back on screen.
- frame_element->setAttribute(styleAttr, "");
+ frame_element->setAttribute(kStyleAttr, "");
CompositeFrame();
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -1034,7 +1039,7 @@ TEST_P(FrameThrottlingTest, ThrottleSubtreeAtomically) {
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
auto* child_frame_element = ToHTMLIFrameElement(
frame_element->contentDocument()->getElementById("child-frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
Compositor().BeginFrame();
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -1061,7 +1066,7 @@ TEST_P(FrameThrottlingTest, ThrottleSubtreeAtomically) {
child_frame_element->contentDocument()->View()->CanThrottleRendering());
// Move the frame back on screen but don't update throttling yet.
- frame_element->setAttribute(styleAttr, "transform: translateY(0px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(0px)");
Compositor().BeginFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
EXPECT_TRUE(
@@ -1102,7 +1107,7 @@ TEST_P(FrameThrottlingTest, SkipPaintingLayersInThrottledFrames) {
auto* frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -1149,7 +1154,7 @@ TEST_P(FrameThrottlingTest, SynchronousLayoutInAnimationFrameCallback) {
// Throttle the first frame.
auto* first_frame_element =
ToHTMLIFrameElement(GetDocument().getElementById("first"));
- first_frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ first_frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(
first_frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -1197,7 +1202,8 @@ TEST_P(FrameThrottlingTest, AllowOneAnimationFrame) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<v8::Value> result =
local_frame->GetScriptController().ExecuteScriptInMainWorldAndReturnValue(
- ScriptSourceCode("window.didRaf;"), KURL(), kOpaqueResource);
+ ScriptSourceCode("window.didRaf;"), KURL(),
+ SanitizeScriptErrors::kSanitize);
EXPECT_TRUE(result->IsTrue());
}
@@ -1217,25 +1223,26 @@ TEST_P(FrameThrottlingTest, UpdatePaintPropertiesOnUnthrottling) {
auto* inner_div_object = inner_div->GetLayoutObject();
EXPECT_FALSE(frame_document->View()->ShouldThrottleRendering());
- frame_element->setAttribute(HTMLNames::styleAttr,
+ frame_element->setAttribute(html_names::kStyleAttr,
"transform: translateY(1000px)");
CompositeFrame();
EXPECT_TRUE(frame_document->View()->CanThrottleRendering());
EXPECT_FALSE(inner_div_object->FirstFragment().PaintProperties());
// Mutating the throttled frame should not cause paint property update.
- inner_div->setAttribute(HTMLNames::styleAttr, "transform: translateY(20px)");
+ inner_div->setAttribute(html_names::kStyleAttr,
+ "transform: translateY(20px)");
EXPECT_FALSE(Compositor().NeedsBeginFrame());
EXPECT_TRUE(frame_document->View()->CanThrottleRendering());
{
DocumentLifecycle::AllowThrottlingScope throttling_scope(
GetDocument().Lifecycle());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
EXPECT_FALSE(inner_div_object->FirstFragment().PaintProperties());
// Move the frame back on screen to unthrottle it.
- frame_element->setAttribute(HTMLNames::styleAttr, "");
+ frame_element->setAttribute(html_names::kStyleAttr, "");
// The first update unthrottles the frame, the second actually update layout
// and paint properties etc.
CompositeFrame();
@@ -1266,7 +1273,7 @@ TEST_P(FrameThrottlingTest, DisplayNoneNotThrottled) {
EXPECT_TRUE(frame_document->View()->CanThrottleRendering());
// Setting display:none unthrottles the frame.
- frame_element->setAttribute(styleAttr, "display: none");
+ frame_element->setAttribute(kStyleAttr, "display: none");
CompositeFrame();
EXPECT_FALSE(frame_document->View()->CanThrottleRendering());
}
@@ -1289,7 +1296,7 @@ TEST_P(FrameThrottlingTest, DisplayNoneChildrenRemainThrottled) {
ToHTMLIFrameElement(GetDocument().getElementById("frame"));
auto* child_frame_element = ToHTMLIFrameElement(
frame_element->contentDocument()->getElementById("child-frame"));
- frame_element->setAttribute(styleAttr, "transform: translateY(480px)");
+ frame_element->setAttribute(kStyleAttr, "transform: translateY(480px)");
CompositeFrame();
EXPECT_TRUE(frame_element->contentDocument()->View()->CanThrottleRendering());
EXPECT_TRUE(
@@ -1297,7 +1304,7 @@ TEST_P(FrameThrottlingTest, DisplayNoneChildrenRemainThrottled) {
// Setting display:none for the parent frame unthrottles the parent but not
// the child. This behavior matches Safari.
- frame_element->setAttribute(styleAttr, "display: none");
+ frame_element->setAttribute(kStyleAttr, "display: none");
CompositeFrame();
EXPECT_FALSE(
frame_element->contentDocument()->View()->CanThrottleRendering());
@@ -1354,7 +1361,7 @@ TEST_P(FrameThrottlingTest, RebuildCompositedLayerTreeOnLayerRemoval) {
auto* sibling_clm = sibling_layer->GetCompositedLayerMapping();
ASSERT_TRUE(sibling_clm);
- scroller_element->setAttribute(styleAttr, "overflow:visible;");
+ scroller_element->setAttribute(kStyleAttr, "overflow:visible;");
EXPECT_EQ(DocumentLifecycle::kVisualUpdatePending,
frame_element->contentDocument()->Lifecycle().GetState());
@@ -1402,7 +1409,7 @@ TEST_P(FrameThrottlingTest, LifecycleUpdateAfterUnthrottledCompositingUpdate) {
EXPECT_TRUE(frame_document->View()->CanThrottleRendering());
EXPECT_FALSE(frame_document->View()->ShouldThrottleRendering());
- frame_document->getElementById("div")->setAttribute(styleAttr,
+ frame_document->getElementById("div")->setAttribute(kStyleAttr,
"will-change: transform");
GetDocument().View()->UpdateLifecycleToCompositingCleanPlusScrolling();
@@ -1411,7 +1418,7 @@ TEST_P(FrameThrottlingTest, LifecycleUpdateAfterUnthrottledCompositingUpdate) {
DocumentLifecycle::AllowThrottlingScope throttling_scope(
GetDocument().Lifecycle());
EXPECT_TRUE(frame_document->View()->ShouldThrottleRendering());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhases();
}
}
diff --git a/chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc b/chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc
index 08f198cdaec..4c9710559c2 100644
--- a/chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc
+++ b/chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc
@@ -44,9 +44,7 @@ TEST_F(DisableBackgroundThrottlingIsRespectedTest,
" f(5);"
"</script>)");
- Platform::Current()
- ->CurrentThread()
- ->Scheduler()
+ ThreadScheduler::Current()
->GetWebMainThreadSchedulerForTest()
->SetRendererBackgrounded(true);
@@ -75,9 +73,7 @@ TEST_F(BackgroundRendererThrottlingTest, BackgroundRenderersAreThrottled) {
" setTimeout(f, 10, 50);"
"</script>)");
- Platform::Current()
- ->CurrentThread()
- ->Scheduler()
+ ThreadScheduler::Current()
->GetWebMainThreadSchedulerForTest()
->SetRendererBackgrounded(true);
diff --git a/chromium/third_party/blink/renderer/core/script/classic_pending_script.cc b/chromium/third_party/blink/renderer/core/script/classic_pending_script.cc
index a97bc492a1c..8a92a60c654 100644
--- a/chromium/third_party/blink/renderer/core/script/classic_pending_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/classic_pending_script.cc
@@ -25,9 +25,11 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
#include "third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
+// <specdef href="https://html.spec.whatwg.org/#fetch-a-classic-script">
ClassicPendingScript* ClassicPendingScript::Fetch(
const KURL& url,
Document& element_document,
@@ -51,12 +53,15 @@ ClassicPendingScript* ClassicPendingScript::Fetch(
pending_script->intervened_ =
MaybeDisallowFetchForDocWrittenScript(params, element_document);
- // <spec
- // href="https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script"
- // step="2">Set request's client to settings object.</spec>
+ // <spec step="2">Set request's client to settings object.</spec>
//
// Note: |element_document| corresponds to the settings object.
- ScriptResource::Fetch(params, element_document.Fetcher(), pending_script);
+ //
+ // We allow streaming, as WatchForLoad() is always called when the script
+ // needs to execute and the ScriptResource is not finished, so
+ // SetClientIsWaitingForFinished is always set on the resource.
+ ScriptResource::Fetch(params, element_document.Fetcher(), pending_script,
+ ScriptResource::kAllowStreaming);
pending_script->CheckState();
return pending_script;
}
@@ -89,10 +94,7 @@ ClassicPendingScript::ClassicPendingScript(
is_external_(is_external),
ready_state_(is_external ? kWaitingForResource : kReady),
integrity_failure_(false),
- is_currently_streaming_(false),
- not_streamed_reason_(is_external
- ? ScriptStreamer::kDidntTryToStartStreaming
- : ScriptStreamer::kInlineScript) {
+ is_currently_streaming_(false) {
CHECK(GetElement());
MemoryCoordinator::Instance().RegisterClient(this);
}
@@ -103,7 +105,6 @@ NOINLINE void ClassicPendingScript::CheckState() const {
// TODO(hiroshige): Turn these CHECK()s into DCHECK() before going to beta.
CHECK(GetElement());
CHECK_EQ(is_external_, !!GetResource());
- CHECK(GetResource() || !streamer_);
}
namespace {
@@ -191,50 +192,25 @@ void ClassicPendingScript::DisposeInternal() {
MemoryCoordinator::Instance().UnregisterClient(this);
ClearResource();
integrity_failure_ = false;
- CancelStreaming();
}
-void ClassicPendingScript::StreamingFinished() {
- CheckState();
- DCHECK(streamer_); // Should only be called by ScriptStreamer.
- DCHECK(IsCurrentlyStreaming());
-
- if (ready_state_ == kWaitingForStreaming) {
- FinishWaitingForStreaming();
- } else if (ready_state_ == kReadyStreaming) {
- FinishReadyStreaming();
- } else {
- NOTREACHED();
+void ClassicPendingScript::WatchForLoad(PendingScriptClient* client) {
+ if (is_external_) {
+ // Once we are watching the ClassicPendingScript for load, we won't ever
+ // try to start streaming this resource via this ClassicPendingScript, so
+ // we mark the resource to instead get a finished notification when loading
+ // (rather than streaming) completes.
+ //
+ // Do this in a task rather than directly to make sure the IsReady state
+ // of PendingScript does not change during this call.
+ GetElement()
+ ->GetDocument()
+ .GetTaskRunner(TaskType::kNetworking)
+ ->PostTask(FROM_HERE,
+ WTF::Bind(&ScriptResource::SetClientIsWaitingForFinished,
+ WrapPersistent(ToScriptResource(GetResource()))));
}
-
- DCHECK(!IsCurrentlyStreaming());
-}
-
-void ClassicPendingScript::FinishWaitingForStreaming() {
- CheckState();
- DCHECK(GetResource());
- DCHECK_EQ(ready_state_, kWaitingForStreaming);
-
- bool error_occurred = GetResource()->ErrorOccurred() || integrity_failure_;
- AdvanceReadyState(error_occurred ? kErrorOccurred : kReady);
-}
-
-void ClassicPendingScript::FinishReadyStreaming() {
- CheckState();
- DCHECK(GetResource());
- DCHECK_EQ(ready_state_, kReadyStreaming);
- AdvanceReadyState(kReady);
-}
-
-void ClassicPendingScript::CancelStreaming() {
- if (!streamer_)
- return;
-
- streamer_->Cancel();
- streamer_ = nullptr;
- streamer_done_.Reset();
- is_currently_streaming_ = false;
- DCHECK(!IsCurrentlyStreaming());
+ PendingScript::WatchForLoad(client);
}
void ClassicPendingScript::NotifyFinished(Resource* resource) {
@@ -261,6 +237,7 @@ void ClassicPendingScript::NotifyFinished(Resource* resource) {
//
// See https://crbug.com/500701 for more information.
CheckState();
+ DCHECK(GetResource());
ScriptElementBase* element = GetElement();
if (element) {
SubresourceIntegrityHelper::DoReport(element->GetDocument(),
@@ -284,24 +261,11 @@ void ClassicPendingScript::NotifyFinished(Resource* resource) {
options_, cross_origin);
}
- // We are now waiting for script streaming to finish.
- // If there is no script streamer, this step completes immediately.
- AdvanceReadyState(kWaitingForStreaming);
- if (streamer_)
- streamer_->NotifyFinished();
- else
- FinishWaitingForStreaming();
-}
-
-void ClassicPendingScript::DataReceived(Resource* resource,
- const char*,
- size_t) {
- if (streamer_)
- streamer_->NotifyAppendData(ToScriptResource(resource));
+ bool error_occurred = GetResource()->ErrorOccurred() || integrity_failure_;
+ AdvanceReadyState(error_occurred ? kErrorOccurred : kReady);
}
void ClassicPendingScript::Trace(blink::Visitor* visitor) {
- visitor->Trace(streamer_);
ResourceClient::Trace(visitor);
MemoryCoordinatorClient::Trace(visitor);
PendingScript::Trace(visitor);
@@ -348,15 +312,16 @@ ClassicScript* ClassicPendingScript::GetSource(const KURL& document_url) const {
GetElement()->GetDocument());
}
- DCHECK(!streamer_);
- DCHECK_EQ(not_streamed_reason_, ScriptStreamer::kInlineScript);
- RecordStreamingHistogram(GetSchedulingType(), false, not_streamed_reason_);
+ DCHECK(!GetResource());
+ RecordStreamingHistogram(GetSchedulingType(), false,
+ ScriptStreamer::kInlineScript);
ScriptSourceCode source_code(source_text_for_inline_script_,
source_location_type_, cache_handler,
document_url, StartingPosition());
return ClassicScript::Create(source_code, base_url_for_inline_script_,
- options_, kSharableCrossOrigin);
+ options_,
+ SanitizeScriptErrors::kDoNotSanitize);
}
DCHECK(GetResource()->IsLoaded());
@@ -365,53 +330,42 @@ ClassicScript* ClassicPendingScript::GetSource(const KURL& document_url) const {
// If the MIME check fails, which is considered as load failure.
if (!AllowedByNosniff::MimeTypeAsScript(
GetElement()->GetDocument().ContextDocument(),
- resource->GetResponse())) {
+ resource->GetResponse(), AllowedByNosniff::MimeTypeCheck::kLax)) {
return nullptr;
}
// Check if we can use the script streamer.
bool streamer_ready = false;
- ScriptStreamer::NotStreamingReason not_streamed_reason = not_streamed_reason_;
- if (streamer_) {
+ ScriptStreamer::NotStreamingReason not_streamed_reason =
+ resource->NoStreamerReason();
+ ScriptStreamer* streamer = resource->TakeStreamer();
+ if (streamer) {
DCHECK_EQ(not_streamed_reason, ScriptStreamer::kInvalid);
- if (streamer_->StreamingSuppressed()) {
- not_streamed_reason = streamer_->StreamingSuppressedReason();
+ if (streamer->StreamingSuppressed()) {
+ not_streamed_reason = streamer->StreamingSuppressedReason();
} else if (ready_state_ == kErrorOccurred) {
not_streamed_reason = ScriptStreamer::kErrorOccurred;
- } else if (ready_state_ == kReadyStreaming) {
- not_streamed_reason = ScriptStreamer::kStreamerNotReadyOnGetSource;
} else {
// Streamer can be used to compile script.
- DCHECK_EQ(ready_state_, kReady);
+ CHECK_EQ(ready_state_, kReady);
+ not_streamed_reason = ScriptStreamer::kInvalid;
streamer_ready = true;
}
}
RecordStreamingHistogram(GetSchedulingType(), streamer_ready,
not_streamed_reason);
- ScriptSourceCode source_code(streamer_ready ? streamer_ : nullptr, resource,
+ ScriptSourceCode source_code(streamer_ready ? streamer : nullptr, resource,
not_streamed_reason);
// The base URL for external classic script is
- // "the URL from which the script was obtained" [spec text]
- // https://html.spec.whatwg.org/multipage/webappapis.html#concept-script-base-url
+ //
+ // <spec href="https://html.spec.whatwg.org/#concept-script-base-url">
+ // ... the URL from which the script was obtained, ...</spec>
const KURL& base_url = source_code.Url();
return ClassicScript::Create(source_code, base_url, options_,
- resource->CalculateAccessControlStatus());
-}
-
-void ClassicPendingScript::SetStreamer(ScriptStreamer* streamer) {
- DCHECK(streamer);
- DCHECK(!streamer_);
- DCHECK(!IsWatchingForLoad() || ready_state_ != kWaitingForResource);
- DCHECK(!streamer->IsFinished());
- DCHECK(ready_state_ == kWaitingForResource || ready_state_ == kReady);
-
- streamer_ = streamer;
- is_currently_streaming_ = true;
- if (streamer && ready_state_ == kReady)
- AdvanceReadyState(kReadyStreaming);
-
- CheckState();
+ resource->GetResponse().IsCorsSameOrigin()
+ ? SanitizeScriptErrors::kDoNotSanitize
+ : SanitizeScriptErrors::kSanitize);
}
bool ClassicPendingScript::IsReady() const {
@@ -422,21 +376,12 @@ bool ClassicPendingScript::IsReady() const {
void ClassicPendingScript::AdvanceReadyState(ReadyState new_ready_state) {
// We will allow exactly these state transitions:
//
- // kWaitingForResource -> kWaitingForStreaming -> [kReady, kErrorOccurred]
- // kReady -> kReadyStreaming -> kReady
+ // kWaitingForResource -> [kReady, kErrorOccurred]
switch (ready_state_) {
case kWaitingForResource:
- CHECK_EQ(new_ready_state, kWaitingForStreaming);
- break;
- case kWaitingForStreaming:
CHECK(new_ready_state == kReady || new_ready_state == kErrorOccurred);
break;
case kReady:
- CHECK_EQ(new_ready_state, kReadyStreaming);
- break;
- case kReadyStreaming:
- CHECK_EQ(new_ready_state, kReady);
- break;
case kErrorOccurred:
NOTREACHED();
break;
@@ -445,6 +390,8 @@ void ClassicPendingScript::AdvanceReadyState(ReadyState new_ready_state) {
bool old_is_ready = IsReady();
ready_state_ = new_ready_state;
+ ScriptResource* resource = ToScriptResource(GetResource());
+
// Did we transition into a 'ready' state?
if (IsReady() && !old_is_ready && IsWatchingForLoad())
PendingScriptFinished();
@@ -467,17 +414,16 @@ void ClassicPendingScript::AdvanceReadyState(ReadyState new_ready_state) {
// To help diagnose crbug.com/78426, we'll temporarily add some DCHECKs
// that are a subset of the DCHECKs below:
if (IsCurrentlyStreaming()) {
- DCHECK(streamer_);
- DCHECK(!streamer_->IsFinished());
+ DCHECK(resource->HasStreamer());
+ DCHECK(!resource->HasFinishedStreamer());
}
// IsCurrentlyStreaming should match what streamer_ thinks.
- DCHECK_EQ(IsCurrentlyStreaming(), streamer_ && !streamer_->IsFinished());
+ DCHECK_EQ(IsCurrentlyStreaming(),
+ resource->HasStreamer() && !resource->HasFinishedStreamer());
// IsCurrentlyStreaming should match the ready_state_.
DCHECK_EQ(IsCurrentlyStreaming(),
- ready_state_ == kReadyStreaming ||
- (streamer_ && (ready_state_ == kWaitingForResource ||
- ready_state_ == kWaitingForStreaming)));
+ resource->HasStreamer() && ready_state_ == kWaitingForResource);
// We can only have a streamer_done_ callback if we are actually streaming.
DCHECK(IsCurrentlyStreaming() || !streamer_done_);
}
@@ -503,27 +449,6 @@ bool ClassicPendingScript::StartStreamingIfPossible(
if (!document || !document->GetFrame())
return false;
- ScriptState* script_state = ToScriptStateForMainWorld(document->GetFrame());
- if (!script_state)
- return false;
-
- // To support streaming re-try, we'll clear the existing streamer if
- // it exists; it claims to be finished; but it's finished because streaming
- // has been suppressed.
- if (streamer_ && streamer_->StreamingSuppressed() &&
- streamer_->IsFinished()) {
- DCHECK_EQ(ready_state_, kReady);
- DCHECK(!streamer_done_);
- DCHECK(!IsCurrentlyStreaming());
- streamer_.Clear();
- }
-
- if (streamer_)
- return false;
-
- // The two checks above should imply that we're not presently streaming.
- DCHECK(!IsCurrentlyStreaming());
-
// Parser blocking scripts tend to do a lot of work in the 'finished'
// callbacks, while async + in-order scripts all do control-like activities
// (like posting new tasks). Use the 'control' queue only for control tasks.
@@ -532,17 +457,19 @@ bool ClassicPendingScript::StartStreamingIfPossible(
? TaskType::kNetworking
: TaskType::kNetworkingControl;
- DCHECK(!streamer_);
DCHECK(!IsCurrentlyStreaming());
DCHECK(!streamer_done_);
- ScriptStreamer::StartStreaming(this, document->GetTaskRunner(task_type),
- &not_streamed_reason_);
- DCHECK(streamer_ || not_streamed_reason_ != ScriptStreamer::kInvalid);
- bool success = streamer_ && !streamer_->IsStreamingFinished();
+
+ ReadyState ready_state_before_stream = ready_state_;
+ bool success = ToScriptResource(GetResource())
+ ->StartStreaming(document->GetTaskRunner(task_type));
+ // We have to make sure that the ready state is not changed by starting
+ // streaming, just in case we're relying on IsReady being false.
+ CHECK_EQ(ready_state_before_stream, ready_state_);
// If we have successfully started streaming, we are required to call the
// callback.
- DCHECK_EQ(success, IsCurrentlyStreaming());
+ is_currently_streaming_ = success;
if (success)
streamer_done_ = std::move(done);
return success;
diff --git a/chromium/third_party/blink/renderer/core/script/classic_pending_script.h b/chromium/third_party/blink/renderer/core/script/classic_pending_script.h
index 98777d193a5..45faa0a04e0 100644
--- a/chromium/third_party/blink/renderer/core/script/classic_pending_script.h
+++ b/chromium/third_party/blink/renderer/core/script/classic_pending_script.h
@@ -55,10 +55,12 @@ class CORE_EXPORT ClassicPendingScript final : public PendingScript,
void Trace(blink::Visitor*) override;
- blink::ScriptType GetScriptType() const override {
- return blink::ScriptType::kClassic;
+ mojom::ScriptType GetScriptType() const override {
+ return mojom::ScriptType::kClassic;
}
+ void WatchForLoad(PendingScriptClient*) override;
+
ClassicScript* GetSource(const KURL& document_url) const override;
bool IsReady() const override;
bool IsExternal() const override { return is_external_; }
@@ -75,12 +77,10 @@ class CORE_EXPORT ClassicPendingScript final : public PendingScript,
private:
// See AdvanceReadyState implementation for valid state transitions.
enum ReadyState {
- // These states are considered "not ready".
+ // This state is considered "not ready".
kWaitingForResource,
- kWaitingForStreaming,
// These states are considered "ready".
kReady,
- kReadyStreaming,
kErrorOccurred,
};
@@ -95,16 +95,11 @@ class CORE_EXPORT ClassicPendingScript final : public PendingScript,
// appropriate.
void AdvanceReadyState(ReadyState);
- // Handle the end of streaming.
- void FinishWaitingForStreaming();
- void FinishReadyStreaming();
- void CancelStreaming();
void CheckState() const override;
// ResourceClient
void NotifyFinished(Resource*) override;
String DebugName() const override { return "PendingScript"; }
- void DataReceived(Resource*, const char*, size_t) override;
static void RecordStreamingHistogram(
ScriptSchedulingType type,
@@ -134,7 +129,6 @@ class CORE_EXPORT ClassicPendingScript final : public PendingScript,
// The request is intervened by document.write() intervention.
bool intervened_ = false;
- Member<ScriptStreamer> streamer_;
base::OnceClosure streamer_done_;
// This flag tracks whether streamer_ is currently streaming. It is used
diff --git a/chromium/third_party/blink/renderer/core/script/classic_script.cc b/chromium/third_party/blink/renderer/core/script/classic_script.cc
index 6bd22938b41..82eba9ba22b 100644
--- a/chromium/third_party/blink/renderer/core/script/classic_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/classic_script.cc
@@ -17,7 +17,8 @@ void ClassicScript::Trace(blink::Visitor* visitor) {
void ClassicScript::RunScript(LocalFrame* frame,
const SecurityOrigin* security_origin) const {
frame->GetScriptController().ExecuteScriptInMainWorld(
- GetScriptSourceCode(), BaseURL(), access_control_status_, FetchOptions());
+ GetScriptSourceCode(), BaseURL(), sanitize_script_errors_,
+ FetchOptions());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/script/classic_script.h b/chromium/third_party/blink/renderer/core/script/classic_script.h
index 873272c0d98..b645f6bf413 100644
--- a/chromium/third_party/blink/renderer/core/script/classic_script.h
+++ b/chromium/third_party/blink/renderer/core/script/classic_script.h
@@ -5,11 +5,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_CLASSIC_SCRIPT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_CLASSIC_SCRIPT_H_
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/loader/resource/script_resource.h"
#include "third_party/blink/renderer/core/script/script.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h"
namespace blink {
@@ -19,9 +19,9 @@ class CORE_EXPORT ClassicScript final : public Script {
static ClassicScript* Create(const ScriptSourceCode& script_source_code,
const KURL& base_url,
const ScriptFetchOptions& fetch_options,
- AccessControlStatus access_control_status) {
+ SanitizeScriptErrors sanitize_script_errors) {
return new ClassicScript(script_source_code, base_url, fetch_options,
- access_control_status);
+ sanitize_script_errors);
}
void Trace(blink::Visitor*) override;
@@ -34,19 +34,21 @@ class CORE_EXPORT ClassicScript final : public Script {
ClassicScript(const ScriptSourceCode& script_source_code,
const KURL& base_url,
const ScriptFetchOptions& fetch_options,
- AccessControlStatus access_control_status)
+ SanitizeScriptErrors sanitize_script_errors)
: Script(fetch_options, base_url),
script_source_code_(script_source_code),
- access_control_status_(access_control_status) {}
+ sanitize_script_errors_(sanitize_script_errors) {}
- ScriptType GetScriptType() const override { return ScriptType::kClassic; }
+ mojom::ScriptType GetScriptType() const override {
+ return mojom::ScriptType::kClassic;
+ }
void RunScript(LocalFrame*, const SecurityOrigin*) const override;
String InlineSourceTextForCSP() const override {
return script_source_code_.Source().ToString();
}
const ScriptSourceCode script_source_code_;
- const AccessControlStatus access_control_status_;
+ const SanitizeScriptErrors sanitize_script_errors_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/script/document_modulator_impl.cc b/chromium/third_party/blink/renderer/core/script/document_modulator_impl.cc
index 5adaf1b7705..f8518d64bff 100644
--- a/chromium/third_party/blink/renderer/core/script/document_modulator_impl.cc
+++ b/chromium/third_party/blink/renderer/core/script/document_modulator_impl.cc
@@ -12,13 +12,14 @@ namespace blink {
ModulatorImplBase* DocumentModulatorImpl::Create(
ScriptState* script_state,
ResourceFetcher* resource_fetcher) {
- return new DocumentModulatorImpl(script_state, resource_fetcher);
+ return MakeGarbageCollected<DocumentModulatorImpl>(script_state,
+ resource_fetcher);
}
ModuleScriptFetcher* DocumentModulatorImpl::CreateModuleScriptFetcher(
ModuleScriptCustomFetchType custom_fetch_type) {
DCHECK_EQ(ModuleScriptCustomFetchType::kNone, custom_fetch_type);
- return new DocumentModuleScriptFetcher(fetcher_);
+ return MakeGarbageCollected<DocumentModuleScriptFetcher>(fetcher_);
}
void DocumentModulatorImpl::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/script/document_modulator_impl.h b/chromium/third_party/blink/renderer/core/script/document_modulator_impl.h
index ebadc196ca0..5c34db9ddd4 100644
--- a/chromium/third_party/blink/renderer/core/script/document_modulator_impl.h
+++ b/chromium/third_party/blink/renderer/core/script/document_modulator_impl.h
@@ -23,6 +23,8 @@ class DocumentModulatorImpl final : public ModulatorImplBase {
public:
static ModulatorImplBase* Create(ScriptState*, ResourceFetcher*);
+ DocumentModulatorImpl(ScriptState*, ResourceFetcher*);
+
// Implements Modulator.
ModuleScriptFetcher* CreateModuleScriptFetcher(
ModuleScriptCustomFetchType) override;
@@ -33,7 +35,6 @@ class DocumentModulatorImpl final : public ModulatorImplBase {
// Implements ModulatorImplBase.
bool IsDynamicImportForbidden(String* reason) override;
- DocumentModulatorImpl(ScriptState*, ResourceFetcher*);
Member<ResourceFetcher> fetcher_;
};
diff --git a/chromium/third_party/blink/renderer/core/script/document_write_intervention.cc b/chromium/third_party/blink/renderer/core/script/document_write_intervention.cc
index 6a35c53c8e0..ed287c4f29f 100644
--- a/chromium/third_party/blink/renderer/core/script/document_write_intervention.cc
+++ b/chromium/third_party/blink/renderer/core/script/document_write_intervention.cc
@@ -139,10 +139,10 @@ bool MaybeDisallowFetchForDocWrittenScript(FetchParameters& params,
// If the hosts didn't match, then see if the domains match. For example, if
// a script is served from static.example.com for a document served from
// www.example.com, we consider that a first party script and allow it.
- String request_domain = NetworkUtils::GetDomainAndRegistry(
- request_host, NetworkUtils::kIncludePrivateRegistries);
- String document_domain = NetworkUtils::GetDomainAndRegistry(
- document_host, NetworkUtils::kIncludePrivateRegistries);
+ String request_domain = network_utils::GetDomainAndRegistry(
+ request_host, network_utils::kIncludePrivateRegistries);
+ String document_domain = network_utils::GetDomainAndRegistry(
+ document_host, network_utils::kIncludePrivateRegistries);
// getDomainAndRegistry will return the empty string for domains that are
// already top-level, such as localhost. Thus we only compare domains if we
// get non-empty results back from getDomainAndRegistry.
@@ -219,7 +219,8 @@ void PossiblyFetchBlockedDocWriteScript(
resource->Url(), element_document.GetSecurityOrigin(), cross_origin,
resource->Encoding(), FetchParameters::kIdleLoad);
AddHeader(&params);
- ScriptResource::Fetch(params, element_document.Fetcher(), nullptr);
+ ScriptResource::Fetch(params, element_document.Fetcher(), nullptr,
+ ScriptResource::kNoStreaming);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.cc b/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.cc
index 887920c8773..f7353d1230e 100644
--- a/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.cc
@@ -45,7 +45,8 @@ class DynamicImportTreeClient final : public ModuleTreeClient {
};
// Implements steps 2.[5-8] of
-// https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability)
+// <specdef
+// href="https://html.spec.whatwg.org/#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability)">
void DynamicImportTreeClient::NotifyModuleTreeLoadFinished(
ModuleScript* module_script) {
// [nospec] Abort the steps if the browsing context is discarded.
@@ -59,75 +60,91 @@ void DynamicImportTreeClient::NotifyModuleTreeLoadFinished(
ScriptState::Scope scope(script_state);
v8::Isolate* isolate = script_state->GetIsolate();
- // Step 2.5. "If result is null, then:" [spec text]
+ // <spec step="2.5">If result is null, then:</spec>
if (!module_script) {
- // Step 2.5.1. "Let completion be Completion { [[Type]]: throw, [[Value]]: a
- // new TypeError, [[Target]]: empty }." [spec text]
+ // <spec step="2.5.1">Let completion be Completion { [[Type]]: throw,
+ // [[Value]]: a new TypeError, [[Target]]: empty }.</spec>
v8::Local<v8::Value> error = V8ThrowException::CreateTypeError(
isolate,
"Failed to fetch dynamically imported module: " + url_.GetString());
- // Step 2.5.2. "Perform FinishDynamicImport(referencingScriptOrModule,
- // specifier, promiseCapability, completion)." [spec text]
+ // <spec step="2.5.2">Perform FinishDynamicImport(referencingScriptOrModule,
+ // specifier, promiseCapability, completion).</spec>
promise_resolver_->Reject(error);
- // Step 2.5.3. "Abort these steps."
+ // <spec step="2.5.3">Return.</spec>
return;
}
- // Step 2.6. "Run the module script module script, with the rethrow errors
- // boolean set to true." [spec text]
+ // <spec step="2.6">Run the module script result, with the rethrow errors
+ // boolean set to true.</spec>
ScriptValue error = modulator_->ExecuteModule(
module_script, Modulator::CaptureEvalErrorFlag::kCapture);
- // Step 2.7. "If running the module script throws an exception, ..." [spec
- // text]
+ // <spec step="2.7">If running the module script throws an exception,
+ // ...</spec>
if (!error.IsEmpty()) {
- // "... then perform FinishDynamicImport(referencingScriptOrModule,
- // specifier, promiseCapability, the thrown exception completion)."
- // [spec text]
+ // <spec step="2.7">... then perform
+ // FinishDynamicImport(referencingScriptOrModule, specifier,
+ // promiseCapability, the thrown exception completion).</spec>
+ //
// Note: "the thrown exception completion" is |error|.
- // https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport
- // Step 1. "If completion is an abrupt completion, then perform !
- // Call(promiseCapability.[[Reject]], undefined, << completion.[[Value]]
- // >>)." [spec text]
+ //
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="1">If completion is an abrupt completion, then perform !
+ // Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]]
+ // »).</spec>
promise_resolver_->Reject(error);
return;
}
- // Step 2.8. "Otherwise, perform
+ // <spec step="2.8">Otherwise, perform
// FinishDynamicImport(referencingScriptOrModule, specifier,
- // promiseCapability, NormalCompletion(undefined))." [spec text]
- // https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport
- // Step 2.a. "Assert: completion is a normal completion and
- // completion.[[Value]] is undefined." [spec text]
+ // promiseCapability, NormalCompletion(undefined)).</spec>
+ //
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="2.1">Assert: completion is a normal completion and
+ // completion.[[Value]] is undefined.</spec>
DCHECK(error.IsEmpty());
- // Step 2.b. "Let moduleRecord be
- // !HostResolveImportedModule(referencingScriptOrModule, specifierString)."
- // [spec text]
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="2.2">Let moduleRecord be !
+ // HostResolveImportedModule(referencingScriptOrModule, specifier).</spec>
+ //
// Note: We skip invocation of ScriptModuleResolver here. The
// result of HostResolveImportedModule is guaranteed to be |module_script|.
ScriptModule record = module_script->Record();
DCHECK(!record.IsNull());
- // Step 2.c. "Assert: ModuleEvaluation has already been invoked on
- // moduleRecord and successfully completed." [spec text]
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="2.3">Assert: Evaluate has already been invoked on moduleRecord and
+ // successfully completed.</spec>
//
// Because |error| is empty, we are sure that ExecuteModule() above was
// successfully completed.
- // Step 2.d. "Let namespace be GetModuleNamespace(moduleRecord)." [spec text]
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="2.4">Let namespace be GetModuleNamespace(moduleRecord).</spec>
v8::Local<v8::Value> module_namespace = record.V8Namespace(isolate);
- // Step 2.e. "If namespace is an abrupt completion, perform
- // !Call(promiseCapability.[[Reject]], undefined, << namespace.[[Value]] >>)."
- // [spec text]
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="2.5">If namespace is an abrupt completion, perform !
+ // Call(promiseCapability.[[Reject]], undefined, « namespace.[[Value]]
+ // »).</spec>
+ //
// Note: Blink's implementation never allows |module_namespace| to be
// an abrupt completion.
- // Step 2.f "Otherwise, perform ! Call(promiseCapability.[[Resolve]],
- // undefined, << namespace.[[Value]] >>)." [spec text]
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="2.6">Otherwise, perform ! Call(promiseCapability.[[Resolve]],
+ // undefined, « namespace.[[Value]] »).</spec>
promise_resolver_->Resolve(module_namespace);
}
@@ -143,7 +160,8 @@ void DynamicModuleResolver::Trace(blink::Visitor* visitor) {
visitor->Trace(modulator_);
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability)
+// <specdef
+// href="https://html.spec.whatwg.org/#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability)">
void DynamicModuleResolver::ResolveDynamically(
const String& specifier,
const KURL& referrer_resource_url,
@@ -153,13 +171,13 @@ void DynamicModuleResolver::ResolveDynamically(
<< "ResolveDynamically should be called from V8 callback, within a valid "
"context.";
- // Step 1. "Let referencing script be
- // referencingScriptOrModule.[[HostDefined]]." [spec text]
+ // <spec step="1">Let referencing script be
+ // referencingScriptOrModule.[[HostDefined]].</spec>
- // Step 2. "Run the following steps in parallel:"
+ // <spec step="2">Run the following steps in parallel:</spec>
- // Step 2.1. "Let url be the result of resolving a module specifier
- // given referencing script and specifier." [spec text]
+ // <spec step="2.1">Let url be the result of resolving a module specifier
+ // given referencing script's base URL and specifier.</spec>
KURL base_url = referrer_info.BaseURL();
if (base_url.IsNull()) {
// ReferrerScriptInfo::BaseURL returns null if it should defer to referrer
@@ -177,30 +195,32 @@ void DynamicModuleResolver::ResolveDynamically(
KURL url = modulator_->ResolveModuleSpecifier(specifier, base_url);
if (!url.IsValid()) {
- // Step 2.2.1. "If the result is failure, then:" [spec text]
- // Step 2.2.2.1. "Let completion be Completion { [[Type]]: throw, [[Value]]:
- // a new TypeError, [[Target]]: empty }." [spec text]
+ // <spec step="2.2">If url is failure, then:</spec>
+ //
+ // <spec step="2.2.1">Let completion be Completion { [[Type]]: throw,
+ // [[Value]]: a new TypeError, [[Target]]: empty }.</spec>
v8::Isolate* isolate = modulator_->GetScriptState()->GetIsolate();
v8::Local<v8::Value> error = V8ThrowException::CreateTypeError(
isolate, "Failed to resolve module specifier '" + specifier + "'");
- // Step 2.2.2.2. "Perform FinishDynamicImport(referencingScriptOrModule,
- // specifier, promiseCapability, completion)" [spec text]
- // https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport
- // Step 1. "If completion is an abrupt completion, then perform
- // !Call(promiseCapability.[[Reject]], undefined, <<completion.[[Value]]>>).
- // " [spec text]
+ // <spec step="2.2.2">Perform FinishDynamicImport(referencingScriptOrModule,
+ // specifier, promiseCapability, completion).</spec>
+ //
+ // <spec
+ // href="https://tc39.github.io/proposal-dynamic-import/#sec-finishdynamicimport"
+ // step="1">If completion is an abrupt completion, then perform !
+ // Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]]
+ // »).</spec>
promise_resolver->Reject(error);
- // Step 2.2.2.3. "Abort these steps." [spec text]
+ // <spec step="2.2.3">Return.</spec>
return;
}
- // Step 2.3. "Let options be the descendant script fetch options for
- // referencing script's fetch options." [spec text]
+ // <spec step="2.3">Let options be the descendant script fetch options for
+ // referencing script's fetch options.</spec>
//
- // <spec
- // href="https://html.spec.whatwg.org/multipage/webappapis.html#descendant-script-fetch-options">
+ // <spec href="https://html.spec.whatwg.org/#descendant-script-fetch-options">
// For any given script fetch options options, the descendant script fetch
// options are a new script fetch options whose items all have the same
// values, except for the integrity metadata, which is instead the empty
@@ -210,9 +230,9 @@ void DynamicModuleResolver::ResolveDynamically(
referrer_info.CredentialsMode(),
referrer_info.GetReferrerPolicy());
- // Step 2.4. "Fetch a module script graph given url, settings object,
- // "script", and options. Wait until the algorithm asynchronously completes
- // with result."
+ // <spec step="2.4">Fetch a module script graph given url, referencing
+ // script's settings object, "script", and options. Wait until the algorithm
+ // asynchronously completes with result.</spec>
auto* tree_client =
DynamicImportTreeClient::Create(url, modulator_.Get(), promise_resolver);
// TODO(kouhei): ExecutionContext::From(modulator_->GetScriptState()) is
@@ -227,7 +247,7 @@ void DynamicModuleResolver::ResolveDynamically(
// Steps 2.[5-8] are implemented at
// DynamicImportTreeClient::NotifyModuleLoadFinished.
- // Step 3. "Return undefined." [spec text]
+ // <spec step="3">Return undefined.</spec>
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.h b/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.h
index 56a6567e810..a7878210853 100644
--- a/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.h
+++ b/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.h
@@ -26,9 +26,12 @@ class CORE_EXPORT DynamicModuleResolver final
void Trace(blink::Visitor*);
static DynamicModuleResolver* Create(Modulator* modulator) {
- return new DynamicModuleResolver(modulator);
+ return MakeGarbageCollected<DynamicModuleResolver>(modulator);
}
+ explicit DynamicModuleResolver(Modulator* modulator)
+ : modulator_(modulator) {}
+
// Implements "HostImportModuleDynamically" semantics.
// Should be called w/ a valid V8 context.
void ResolveDynamically(const String& specifier,
@@ -37,9 +40,6 @@ class CORE_EXPORT DynamicModuleResolver final
ScriptPromiseResolver*);
private:
- explicit DynamicModuleResolver(Modulator* modulator)
- : modulator_(modulator) {}
-
Member<Modulator> modulator_;
};
diff --git a/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver_test.cc b/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver_test.cc
index 24a02d8754e..46f86410254 100644
--- a/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/dynamic_module_resolver_test.cc
@@ -223,8 +223,8 @@ TEST(DynamicModuleResolverTest, ResolveSuccess) {
ScriptModule record = ScriptModule::Compile(
scope.GetIsolate(), "export const foo = 'hello';", TestReferrerURL(),
- TestReferrerURL(), ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ TestReferrerURL(), ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ModuleScript* module_script =
ModuleScript::CreateForTest(modulator, record, TestDependencyURL());
EXPECT_TRUE(record.Instantiate(scope.GetScriptState()).IsEmpty());
@@ -312,8 +312,8 @@ TEST(DynamicModuleResolverTest, ExceptionThrown) {
ScriptModule record = ScriptModule::Compile(
scope.GetIsolate(), "throw Error('bar')", TestReferrerURL(),
- TestReferrerURL(), ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ TestReferrerURL(), ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
ModuleScript* module_script =
ModuleScript::CreateForTest(modulator, record, TestDependencyURL());
EXPECT_TRUE(record.Instantiate(scope.GetScriptState()).IsEmpty());
@@ -352,7 +352,7 @@ TEST(DynamicModuleResolverTest, ResolveWithNullReferrerScriptSuccess) {
ScriptModule record = ScriptModule::Compile(
scope.GetIsolate(), "export const foo = 'hello';", TestDependencyURL(),
- TestDependencyURL(), ScriptFetchOptions(), kSharableCrossOrigin,
+ TestDependencyURL(), ScriptFetchOptions(),
TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
ModuleScript* module_script =
ModuleScript::CreateForTest(modulator, record, TestDependencyURL());
diff --git a/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.cc b/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.cc
index a591220218c..15af66c2727 100644
--- a/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.cc
+++ b/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.cc
@@ -24,7 +24,8 @@ const SecurityOrigin* FetchClientSettingsObjectImpl::GetSecurityOrigin() const {
return execution_context_->GetSecurityOrigin();
}
-ReferrerPolicy FetchClientSettingsObjectImpl::GetReferrerPolicy() const {
+network::mojom::ReferrerPolicy
+FetchClientSettingsObjectImpl::GetReferrerPolicy() const {
DCHECK(execution_context_->IsContextThread());
return execution_context_->GetReferrerPolicy();
}
diff --git a/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h b/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h
index 9ba47f01b3c..8ea794e2e87 100644
--- a/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h
+++ b/chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h
@@ -5,13 +5,13 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_FETCH_CLIENT_SETTINGS_OBJECT_IMPL_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_FETCH_CLIENT_SETTINGS_OBJECT_IMPL_H_
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h"
#include "third_party/blink/renderer/platform/loader/fetch/https_state.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -33,10 +33,10 @@ class CORE_EXPORT FetchClientSettingsObjectImpl final
const KURL& BaseURL() const override;
const SecurityOrigin* GetSecurityOrigin() const override;
- ReferrerPolicy GetReferrerPolicy() const override;
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const override;
const String GetOutgoingReferrer() const override;
- HttpsState GetHttpsState() const;
+ HttpsState GetHttpsState() const override;
void Trace(Visitor* visitor) override;
diff --git a/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.cc b/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.cc
index 008ee437a53..563c7e4a9ac 100644
--- a/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.cc
+++ b/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.cc
@@ -142,8 +142,6 @@ static KURL DocumentURLForScriptExecution(Document* document) {
} // namespace
-using namespace HTMLNames;
-
HTMLParserScriptRunner::HTMLParserScriptRunner(
HTMLParserReentryPermit* reentry_permit,
Document* document,
@@ -182,7 +180,7 @@ bool HTMLParserScriptRunner::IsParserBlockingScriptReady() {
// Corresponds to some steps of the "Otherwise" Clause of 'An end tag whose
// tag name is "script"'
-// https://html.spec.whatwg.org/multipage/parsing.html#scriptEndTag
+// <specdef href="https://html.spec.whatwg.org/#scriptEndTag">
void HTMLParserScriptRunner::
ExecutePendingParserBlockingScriptAndDispatchEvent() {
// Stop watching loads before executeScript to prevent recursion if the script
@@ -203,15 +201,13 @@ void HTMLParserScriptRunner::
return;
}
- // <spec step="B.1">Let the script be the pending
- // parsing-blocking script. There is no longer a pending parsing-blocking
- // script.</spec>
+ // <spec step="B.1">Let the script be the pending parsing-blocking script.
+ // There is no longer a pending parsing-blocking script.</spec>
parser_blocking_script_ = nullptr;
{
- // <spec step="B.7">Increment the parser's script
- // nesting level by one (it should be zero before this step, so this sets it
- // to one).</spec>
+ // <spec step="B.7">Increment the parser's script nesting level by one (it
+ // should be zero before this step, so this sets it to one).</spec>
HTMLParserReentryPermit::ScriptNestingLevelIncrementer
nesting_level_incrementer =
reentry_permit_->IncrementScriptNestingLevel();
@@ -228,10 +224,9 @@ void HTMLParserScriptRunner::
DCHECK(IsExecutingScript());
DoExecuteScript(pending_script, DocumentURLForScriptExecution(document_));
- // <spec step="B.9">Decrement the parser's script
- // nesting level by one. If the parser's script nesting level is zero (which
- // it always should be at this point), then set the parser pause flag to
- // false.</spec>
+ // <spec step="B.9">Decrement the parser's script nesting level by one. If
+ // the parser's script nesting level is zero (which it always should be at
+ // this point), then set the parser pause flag to false.</spec>
//
// This is implemented by ~ScriptNestingLevelIncrementer().
}
@@ -240,7 +235,10 @@ void HTMLParserScriptRunner::
}
// Should be correspond to
-// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block
+//
+// <specdef
+// href="https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block">
+//
// but currently does more than specced, because historically this and
// ExecutePendingParserBlockingScriptAndDispatchEvent() was the same method.
// TODO(hiroshige): Make this spec-conformant.
@@ -258,26 +256,27 @@ void HTMLParserScriptRunner::ExecutePendingDeferredScriptAndDispatchEvent(
}
{
- // <spec label="scriptEndTag" step="B.7">Increment the parser's script
- // nesting level by one (it should be zero before this step, so this sets it
- // to one).</spec>
+ // The following code corresponds to:
+ //
+ // <spec href="https://html.spec.whatwg.org/#scriptEndTag"
+ // step="B.7">Increment the parser's script nesting level by one (it should
+ // be zero before this step, so this sets it to one).</spec>
+ //
+ // but this shouldn't be executed here according to the
+ // #execute-the-script-block spec.
HTMLParserReentryPermit::ScriptNestingLevelIncrementer
nesting_level_incrementer =
reentry_permit_->IncrementScriptNestingLevel();
+ // <spec step="3">... increment the ignore-destructive-writes counter of the
+ // script element's node document. ...</spec>
+ //
+ // TODO(hiroshige): This is duplicated (also done in ExecuteScriptBlock())).
IgnoreDestructiveWriteCountIncrementer
ignore_destructive_write_count_incrementer(document_);
- // <spec label="scriptEndTag" step="B.8">Execute the script.</spec>
DCHECK(IsExecutingScript());
DoExecuteScript(pending_script, DocumentURLForScriptExecution(document_));
-
- // <spec label="scriptEndTag" step="B.9">Decrement the parser's script
- // nesting level by one. If the parser's script nesting level is zero (which
- // it always should be at this point), then set the parser pause flag to
- // false.</spec>
- //
- // This is implemented by ~ScriptNestingLevelIncrementer().
}
DCHECK(!IsExecutingScript());
@@ -303,8 +302,7 @@ void HTMLParserScriptRunner::PendingScriptFinished(
host_->NotifyScriptLoaded(pending_script);
}
-// 'An end tag whose tag name is "script"'
-// https://html.spec.whatwg.org/multipage/parsing.html#scriptEndTag
+// <specdef href="https://html.spec.whatwg.org/#scriptEndTag">
//
// Script handling lives outside the tree builder to keep each class simple.
void HTMLParserScriptRunner::ProcessScriptElement(
@@ -326,12 +324,14 @@ void HTMLParserScriptRunner::ProcessScriptElement(
if (HasParserBlockingScript()) {
// <spec step="A">If the script nesting level is not zero: ...</spec>
if (IsExecutingScript()) {
- // <spec step="A">... Set the parser pause flag to true, and abort the
- // processing of any nested invocations of the tokenizer, yielding control
- // back to the caller. (Tokenization will resume when the caller returns
- // to the "outer" tree construction stage.)</spec>
+ // <spec step="A">If the script nesting level is not zero:
//
- // TODO(hiroshige): set the parser pause flag to true here.
+ // Set the parser pause flag to true, and abort the processing of any
+ // nested invocations of the tokenizer, yielding control back to the
+ // caller. (Tokenization will resume when the caller returns to the
+ // "outer" tree construction stage.)</spec>
+ //
+ // <spec>... set the parser pause flag to ...</spec>
// Unwind to the outermost HTMLParserScriptRunner::processScriptElement
// before continuing parsing.
@@ -357,8 +357,9 @@ bool HTMLParserScriptRunner::HasParserBlockingScript() const {
return ParserBlockingScript();
}
-// The "Otherwise" Clause of 'An end tag whose tag name is "script"'
-// https://html.spec.whatwg.org/multipage/parsing.html#scriptEndTag
+// <specdef href="https://html.spec.whatwg.org/#scriptEndTag">
+//
+// <spec>An end tag whose tag name is "script" ...</spec>
void HTMLParserScriptRunner::ExecuteParsingBlockingScripts() {
// <spec step="B.3">If the parser's Document has a style sheet that is
// blocking scripts or the script's "ready to be parser-executed" flag is not
@@ -411,7 +412,7 @@ void HTMLParserScriptRunner::ExecuteScriptsWaitingForResources() {
ExecuteParsingBlockingScripts();
}
-// https://html.spec.whatwg.org/multipage/parsing.html#stop-parsing
+// <specdef href="https://html.spec.whatwg.org/#stop-parsing">
//
// <spec step="3">If the list of scripts that will execute when the document has
// finished parsing is not empty, run these substeps:</spec>
@@ -459,12 +460,12 @@ bool HTMLParserScriptRunner::ExecuteScriptsWaitingForParsing() {
return true;
}
-// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
void HTMLParserScriptRunner::RequestParsingBlockingScript(
ScriptLoader* script_loader) {
- // <spec step="25.B">... The element is the pending parsing-blocking script of
- // the Document of the parser that created the element. (There can only be one
- // such script per Document at a time.) ...</spec>
+ // <spec href="https://html.spec.whatwg.org/#prepare-a-script" step="26.B">...
+ // The element is the pending parsing-blocking script of the Document of the
+ // parser that created the element. (There can only be one such script per
+ // Document at a time.) ...</spec>
CHECK(!ParserBlockingScript());
parser_blocking_script_ =
script_loader->TakePendingScript(ScriptSchedulingType::kParserBlocking);
@@ -482,7 +483,6 @@ void HTMLParserScriptRunner::RequestParsingBlockingScript(
}
}
-// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
void HTMLParserScriptRunner::RequestDeferredScript(
ScriptLoader* script_loader) {
PendingScript* pending_script =
@@ -496,14 +496,17 @@ void HTMLParserScriptRunner::RequestDeferredScript(
DCHECK(pending_script->IsExternalOrModule());
- // <spec step="25.A">... Add the element to the end of the list of scripts
- // that will execute when the document has finished parsing associated with
- // the Document of the parser that created the element. ...</spec>
+ // <spec href="https://html.spec.whatwg.org/#prepare-a-script" step="26.A">...
+ // Add the element to the end of the list of scripts that will execute when
+ // the document has finished parsing associated with the Document of the
+ // parser that created the element. ...</spec>
scripts_to_execute_after_parsing_.push_back(pending_script);
}
// The initial steps for 'An end tag whose tag name is "script"'
-// https://html.spec.whatwg.org/multipage/parsing.html#scriptEndTag
+// <specdef href="https://html.spec.whatwg.org/#scriptEndTag">
+// <specdef label="prepare-a-script"
+// href="https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script">
void HTMLParserScriptRunner::ProcessScriptElementInternal(
Element* script,
const TextPosition& script_start_position) {
@@ -537,27 +540,24 @@ void HTMLParserScriptRunner::ProcessScriptElementInternal(
// invocation of the parser. ...</spec>
script_loader->PrepareScript(script_start_position);
- // [PS]
- // https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
if (!script_loader->WillBeParserExecuted())
return;
if (script_loader->WillExecuteWhenDocumentFinishedParsing()) {
- // [PS] Step 25.A.
RequestDeferredScript(script_loader);
} else if (script_loader->ReadyToBeParserExecuted()) {
- // <spec label="PS" step="25.E">... it's an HTML parser whose script
- // nesting level is not greater than one, ...</spec>
+ // <spec label="prepare-a-script" step="26.E">... it's an HTML parser
+ // whose script nesting level is not greater than one, ...</spec>
if (reentry_permit_->ScriptNestingLevel() == 1u) {
- // <spec label="PS" step="25.E">... The element is the pending
- // parsing-blocking script of the Document of the parser that created
- // the element. (There can only be one such script per Document at a
- // time.) ...</spec>
+ // <spec label="prepare-a-script" step="26.E">... The element is the
+ // pending parsing-blocking script of the Document of the parser that
+ // created the element. (There can only be one such script per Document
+ // at a time.) ...</spec>
CHECK(!parser_blocking_script_);
parser_blocking_script_ = script_loader->TakePendingScript(
ScriptSchedulingType::kParserBlockingInline);
} else {
- // <spec label="PS" step="25.F">Otherwise
+ // <spec label="prepare-a-script" step="26.F">Otherwise
//
// Immediately execute the script block, even if other scripts are
// already executing.</spec>
diff --git a/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.h b/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.h
index 3d49f8c6051..9f6a5674550 100644
--- a/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.h
+++ b/chromium/third_party/blink/renderer/core/script/html_parser_script_runner.h
@@ -63,8 +63,13 @@ class HTMLParserScriptRunner final
static HTMLParserScriptRunner* Create(HTMLParserReentryPermit* reentry_permit,
Document* document,
HTMLParserScriptRunnerHost* host) {
- return new HTMLParserScriptRunner(reentry_permit, document, host);
+ return MakeGarbageCollected<HTMLParserScriptRunner>(reentry_permit,
+ document, host);
}
+
+ HTMLParserScriptRunner(HTMLParserReentryPermit*,
+ Document*,
+ HTMLParserScriptRunnerHost*);
~HTMLParserScriptRunner() override;
// Invoked when the parser is detached.
@@ -102,10 +107,6 @@ class HTMLParserScriptRunner final
}
private:
- HTMLParserScriptRunner(HTMLParserReentryPermit*,
- Document*,
- HTMLParserScriptRunnerHost*);
-
// PendingScriptClient
void PendingScriptFinished(PendingScript*) override;
diff --git a/chromium/third_party/blink/renderer/core/script/layered_api.cc b/chromium/third_party/blink/renderer/core/script/layered_api.cc
index ccb19051c12..7b406f0fff6 100644
--- a/chromium/third_party/blink/renderer/core/script/layered_api.cc
+++ b/chromium/third_party/blink/renderer/core/script/layered_api.cc
@@ -6,7 +6,7 @@
#include "base/stl_util.h"
#include "third_party/blink/public/resources/grit/blink_resources.h"
-#include "third_party/blink/renderer/platform/media/resource_bundle_helper.h"
+#include "third_party/blink/renderer/platform/data_resource_helper.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -115,7 +115,7 @@ String GetSourceText(const KURL& url) {
if (resource_id < 0)
return String();
- return ResourceBundleHelper::GetResourceAsString(resource_id);
+ return GetResourceAsString(resource_id);
}
} // namespace layered_api
diff --git a/chromium/third_party/blink/renderer/core/script/modulator.cc b/chromium/third_party/blink/renderer/core/script/modulator.cc
index 69c0b52742f..dfaba2eac1d 100644
--- a/chromium/third_party/blink/renderer/core/script/modulator.cc
+++ b/chromium/third_party/blink/renderer/core/script/modulator.cc
@@ -43,20 +43,20 @@ Modulator* Modulator::From(ScriptState* script_state) {
// See comment in LocalDOMWindow::modulator_ for this workaround.
LocalDOMWindow* window = document->ExecutingWindow();
window->SetModulator(modulator);
- } else if (execution_context->IsWorkletGlobalScope()) {
+ } else if (auto* scope = DynamicTo<WorkletGlobalScope>(execution_context)) {
modulator = WorkletModulatorImpl::Create(script_state);
Modulator::SetModulator(script_state, modulator);
// See comment in WorkerOrWorkletGlobalScope::modulator_ for this
// workaround.
- ToWorkletGlobalScope(execution_context)->SetModulator(modulator);
- } else if (execution_context->IsWorkerGlobalScope()) {
+ scope->SetModulator(modulator);
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) {
modulator = WorkerModulatorImpl::Create(script_state);
Modulator::SetModulator(script_state, modulator);
// See comment in WorkerOrWorkletGlobalScope::modulator_ for this
// workaround.
- ToWorkerGlobalScope(execution_context)->SetModulator(modulator);
+ scope->SetModulator(modulator);
} else {
NOTREACHED();
}
diff --git a/chromium/third_party/blink/renderer/core/script/modulator.h b/chromium/third_party/blink/renderer/core/script/modulator.h
index 6b611f799b3..5bfa557f487 100644
--- a/chromium/third_party/blink/renderer/core/script/modulator.h
+++ b/chromium/third_party/blink/renderer/core/script/modulator.h
@@ -6,7 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_MODULATOR_H_
#include "base/single_thread_task_runner.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/platform/web_url_request.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_module.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/script/module_import_meta.h"
@@ -14,10 +16,8 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -80,7 +80,11 @@ enum class ModuleScriptCustomFetchType {
// Perform custom fetch steps for Worklet's addModule() function defined in
// the Worklet spec:
// https://drafts.css-houdini.org/worklets/#fetch-a-worklet-script
- kWorkletAddModule
+ kWorkletAddModule,
+
+ // Fetch a Service Worker's installed module script from the Service Worker's
+ // script storage.
+ kInstalledServiceWorker
};
// A Modulator is an interface for "environment settings object" concept for
diff --git a/chromium/third_party/blink/renderer/core/script/modulator_impl_base.cc b/chromium/third_party/blink/renderer/core/script/modulator_impl_base.cc
index a26c7388639..bbb206dcf4f 100644
--- a/chromium/third_party/blink/renderer/core/script/modulator_impl_base.cc
+++ b/chromium/third_party/blink/renderer/core/script/modulator_impl_base.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_script_fetch_request.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_tree_linker_registry.h"
@@ -44,10 +45,10 @@ bool ModulatorImplBase::IsScriptingDisabled() const {
return !GetExecutionContext()->CanExecuteScripts(kAboutToExecuteScript);
}
-// [fetch-a-module-script-tree]
-// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
-// [fetch-a-module-worker-script-tree]
-// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-worker-script-tree
+// <specdef label="fetch-a-module-script-tree"
+// href="https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree">
+// <specdef label="fetch-a-module-worker-script-tree"
+// href="https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-worker-script-tree">
void ModulatorImplBase::FetchTree(
const KURL& url,
FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
@@ -107,7 +108,7 @@ ModuleScript* ModulatorImplBase::GetFetchedModuleScript(const KURL& url) {
return map_->GetFetchedModuleScript(url);
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
+// <specdef href="https://html.spec.whatwg.org/#resolve-a-module-specifier">
KURL ModulatorImplBase::ResolveModuleSpecifier(const String& module_request,
const KURL& base_url,
String* failure_reason) {
@@ -130,8 +131,6 @@ KURL ModulatorImplBase::ResolveModuleSpecifier(const String& module_request,
// SOLIDUS (/), the two-character sequence U+002E FULL STOP, U+002F SOLIDUS
// (./), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP,
// U+002F SOLIDUS (../), return failure.</spec>
- //
- // (../), return failure and abort these steps." [spec text]
if (!module_request.StartsWith("/") && !module_request.StartsWith("./") &&
!module_request.StartsWith("../")) {
if (failure_reason) {
@@ -143,7 +142,7 @@ KURL ModulatorImplBase::ResolveModuleSpecifier(const String& module_request,
}
// <spec step="3">Return the result of applying the URL parser to specifier
- // with script's base URL as the base URL.</spec>
+ // with base URL as the base URL.</spec>
DCHECK(base_url.IsValid());
KURL absolute_url(base_url, module_request);
if (absolute_url.IsValid())
@@ -170,25 +169,32 @@ void ModulatorImplBase::ResolveDynamically(
GetScriptState()->GetIsolate(), reason));
return;
}
+ UseCounter::Count(GetExecutionContext(),
+ WebFeature::kDynamicImportModuleScript);
dynamic_module_resolver_->ResolveDynamically(specifier, referrer_url,
referrer_info, resolver);
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
+// <specdef href="https://html.spec.whatwg.org/#hostgetimportmetaproperties">
ModuleImportMeta ModulatorImplBase::HostGetImportMetaProperties(
ScriptModule record) const {
- // 1. Let module script be moduleRecord.[[HostDefined]]. [spec text]
+ // <spec step="1">Let module script be moduleRecord.[[HostDefined]].</spec>
ModuleScript* module_script = script_module_resolver_->GetHostDefined(record);
DCHECK(module_script);
- // 2. Let urlString be module script's base URL, serialized. [spec text]
+ // <spec step="2">Let urlString be module script's base URL,
+ // serialized.</spec>
String url_string = module_script->BaseURL().GetString();
- // 3. Return <<Record { [[Key]]: "url", [[Value]]: urlString }>>. [spec text]
+ // <spec step="3">Return « Record { [[Key]]: "url", [[Value]]: urlString }
+ // ».</spec>
return ModuleImportMeta(url_string);
}
ScriptValue ModulatorImplBase::InstantiateModule(ScriptModule script_module) {
+ UseCounter::Count(GetExecutionContext(),
+ WebFeature::kInstantiateModuleScript);
+
ScriptState::Scope scope(script_state_);
return script_module.Instantiate(script_state_);
}
@@ -208,63 +214,66 @@ ModulatorImplBase::ModuleRequestsFromScriptModule(ScriptModule script_module) {
return requests;
}
+// <specdef href="https://html.spec.whatwg.org/#run-a-module-script">
ScriptValue ModulatorImplBase::ExecuteModule(
const ModuleScript* module_script,
CaptureEvalErrorFlag capture_error) {
- // https://html.spec.whatwg.org/multipage/webappapis.html#run-a-module-script
+ // <spec step="1">If rethrow errors is not given, let it be false.</spec>
- // Step 1. "If rethrow errors is not given, let it be false." [spec text]
-
- // Step 2. "Let settings be the settings object of script." [spec text]
+ // <spec step="2">Let settings be the settings object of script.</spec>
+ //
// The settings object is |this|.
- // Step 3. "Check if we can run script with settings.
- // If this returns "do not run" then return." [spec text]
+ // <spec step="3">Check if we can run script with settings. If this returns
+ // "do not run" then return NormalCompletion(empty).</spec>
if (IsScriptingDisabled())
return ScriptValue();
- // Step 4. "Prepare to run script given settings." [spec text]
+ // <spec step="4">Prepare to run script given settings.</spec>
+ //
// This is placed here to also cover ScriptModule::ReportException().
ScriptState::Scope scope(script_state_);
- // Step 5. "Let evaluationStatus be null." [spec text]
+ // <spec step="5">Let evaluationStatus be null.</spec>
+ //
// |error| corresponds to "evaluationStatus of [[Type]]: throw".
ScriptValue error;
- // Step 6. "If script's error to rethrow is not null," [spec text]
+ // <spec step="6">If script's error to rethrow is not null, ...</spec>
if (module_script->HasErrorToRethrow()) {
- // Step 6. "then set evaluationStatus to Completion { [[Type]]: throw,
- // [[Value]]: script's error to rethrow, [[Target]]: empty }." [spec text]
+ // <spec step="6">... then set evaluationStatus to Completion { [[Type]]:
+ // throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.</spec>
error = module_script->CreateErrorToRethrow();
} else {
- // Step 7. "Otherwise:
+ // <spec step="7">Otherwise:</spec>
- // Step 7.1. "Let record be script's record. [spec text]
+ // <spec step="7.1">Let record be script's record.</spec>
const ScriptModule& record = module_script->Record();
CHECK(!record.IsNull());
- // Step 7.2. "Set evaluationStatus to record.Evaluate()." [spec text]
+ // <spec step="7.2">Set evaluationStatus to record.Evaluate(). ...</spec>
error = record.Evaluate(script_state_);
- // "If Evaluate fails to complete as a result of the user agent aborting the
- // running script, then set evaluationStatus to Completion { [[Type]]:
- // throw, [[Value]]: a new "QuotaExceededError" DOMException, [[Target]]:
- // empty }." [spec text]
+ // <spec step="7.2">... If Evaluate fails to complete as a result of the
+ // user agent aborting the running script, then set evaluationStatus to
+ // Completion { [[Type]]: throw, [[Value]]: a new "QuotaExceededError"
+ // DOMException, [[Target]]: empty }.</spec>
}
- // Step 8. "If evaluationStatus is an abrupt completion, then:" [spec text]
+ // <spec step="8">If evaluationStatus is an abrupt completion, then:</spec>
if (!error.IsEmpty()) {
- // Step 8.1. "If rethrow errors is true, rethrow the exception given by
- // evaluationStatus.[[Value]]." [spec text]
+ // <spec step="8.1">If rethrow errors is true, rethrow the exception given
+ // by evaluationStatus.[[Value]].</spec>
if (capture_error == CaptureEvalErrorFlag::kCapture)
return error;
- // Step 8.2. "Otherwise, report the exception given by
- // evaluationStatus.[[Value]] for script." [spec text]
+ // <spec step="8.2">Otherwise, report the exception given by
+ // evaluationStatus.[[Value]] for script.</spec>
ScriptModule::ReportException(script_state_, error.V8Value());
}
- // Step 9. "Clean up after running script with settings." [spec text]
+ // <spec step="9">Clean up after running script with settings.</spec>
+ //
// Implemented as the ScriptState::Scope destructor.
return ScriptValue();
}
diff --git a/chromium/third_party/blink/renderer/core/script/module_map.cc b/chromium/third_party/blink/renderer/core/script/module_map.cc
index c33f7fa0a48..4399cb898e8 100644
--- a/chromium/third_party/blink/renderer/core/script/module_map.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_map.cc
@@ -22,7 +22,11 @@ class ModuleMap::Entry final : public GarbageCollectedFinalized<Entry>,
USING_GARBAGE_COLLECTED_MIXIN(ModuleMap::Entry);
public:
- static Entry* Create(ModuleMap* map) { return new Entry(map); }
+ static Entry* Create(ModuleMap* map) {
+ return MakeGarbageCollected<Entry>(map);
+ }
+
+ explicit Entry(ModuleMap*);
~Entry() override {}
void Trace(blink::Visitor*) override;
@@ -35,8 +39,6 @@ class ModuleMap::Entry final : public GarbageCollectedFinalized<Entry>,
ModuleScript* GetModuleScript() const;
private:
- explicit Entry(ModuleMap*);
-
void DispatchFinishedNotificationAsync(SingleModuleClient*);
// Implements ModuleScriptLoaderClient
@@ -108,7 +110,7 @@ void ModuleMap::Trace(blink::Visitor* visitor) {
visitor->Trace(loader_registry_);
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
+// <specdef href="https://html.spec.whatwg.org/#fetch-a-single-module-script">
void ModuleMap::FetchSingleModuleScript(
const ModuleScriptFetchRequest& request,
FetchClientSettingsObjectSnapshot* fetch_client_settings_object,
@@ -139,7 +141,7 @@ void ModuleMap::FetchSingleModuleScript(
// <spec step="3">If moduleMap[url] exists, asynchronously complete this
// algorithm with moduleMap[url], and abort these steps.</spec>
//
- // <spec step="11">Set moduleMap[url] to module script, and asynchronously
+ // <spec step="12">Set moduleMap[url] to module script, and asynchronously
// complete this algorithm with module script.</spec>
if (client)
entry->AddClient(client);
diff --git a/chromium/third_party/blink/renderer/core/script/module_map.h b/chromium/third_party/blink/renderer/core/script/module_map.h
index ebf4a229cd9..5c5c341fa22 100644
--- a/chromium/third_party/blink/renderer/core/script/module_map.h
+++ b/chromium/third_party/blink/renderer/core/script/module_map.h
@@ -33,8 +33,11 @@ class CORE_EXPORT ModuleMap final : public GarbageCollected<ModuleMap>,
public:
static ModuleMap* Create(Modulator* modulator) {
- return new ModuleMap(modulator);
+ return MakeGarbageCollected<ModuleMap>(modulator);
}
+
+ explicit ModuleMap(Modulator*);
+
void Trace(blink::Visitor*);
const char* NameInHeapSnapshot() const override { return "ModuleMap"; }
@@ -54,8 +57,6 @@ class CORE_EXPORT ModuleMap final : public GarbageCollected<ModuleMap>,
Modulator* GetModulator() { return modulator_; }
private:
- explicit ModuleMap(Modulator*);
-
using MapImpl = HeapHashMap<KURL, TraceWrapperMember<Entry>>;
// A module map is a map of absolute URLs to map entry.
diff --git a/chromium/third_party/blink/renderer/core/script/module_map_test.cc b/chromium/third_party/blink/renderer/core/script/module_map_test.cc
index 4391d56fd2f..6b5f0054de8 100644
--- a/chromium/third_party/blink/renderer/core/script/module_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_map_test.cc
@@ -112,11 +112,10 @@ class ModuleMapTestModulator final : public DummyModulator {
void Fetch(FetchParameters& request,
ModuleGraphLevel,
ModuleScriptFetcher::Client* client) override {
- TestRequest* test_request = new TestRequest(
+ TestRequest* test_request = MakeGarbageCollected<TestRequest>(
ModuleScriptCreationParams(
request.Url(), ParkableString(String("").ReleaseImpl()),
- request.GetResourceRequest().GetFetchCredentialsMode(),
- kSharableCrossOrigin),
+ request.GetResourceRequest().GetFetchCredentialsMode()),
client);
modulator_->test_requests_.push_back(test_request);
}
@@ -132,7 +131,7 @@ class ModuleMapTestModulator final : public DummyModulator {
ModuleScriptFetcher* CreateModuleScriptFetcher(
ModuleScriptCustomFetchType) override {
- return new TestModuleScriptFetcher(this);
+ return MakeGarbageCollected<TestModuleScriptFetcher>(this);
}
Vector<ModuleRequest> ModuleRequestsFromScriptModule(ScriptModule) override {
@@ -140,7 +139,7 @@ class ModuleMapTestModulator final : public DummyModulator {
}
base::SingleThreadTaskRunner* TaskRunner() override {
- return Platform::Current()->CurrentThread()->GetTaskRunner().get();
+ return Thread::Current()->GetTaskRunner().get();
};
struct TestRequest final : public GarbageCollectedFinalized<TestRequest> {
@@ -198,8 +197,8 @@ void ModuleMapTest::SetUp() {
PageTestBase::SetUp(IntSize(500, 500));
GetDocument().SetURL(KURL("https://example.com"));
GetDocument().SetSecurityOrigin(SecurityOrigin::Create(GetDocument().Url()));
- modulator_ =
- new ModuleMapTestModulator(ToScriptStateForMainWorld(&GetFrame()));
+ modulator_ = MakeGarbageCollected<ModuleMapTestModulator>(
+ ToScriptStateForMainWorld(&GetFrame()));
map_ = ModuleMap::Create(modulator_);
}
diff --git a/chromium/third_party/blink/renderer/core/script/module_pending_script.h b/chromium/third_party/blink/renderer/core/script/module_pending_script.h
index 916b07376a3..518bafa16ab 100644
--- a/chromium/third_party/blink/renderer/core/script/module_pending_script.h
+++ b/chromium/third_party/blink/renderer/core/script/module_pending_script.h
@@ -24,8 +24,10 @@ class ModulePendingScript;
class ModulePendingScriptTreeClient final : public ModuleTreeClient {
public:
static ModulePendingScriptTreeClient* Create() {
- return new ModulePendingScriptTreeClient();
+ return MakeGarbageCollected<ModulePendingScriptTreeClient>();
}
+
+ ModulePendingScriptTreeClient();
~ModulePendingScriptTreeClient() override = default;
void SetPendingScript(ModulePendingScript* client);
@@ -35,8 +37,6 @@ class ModulePendingScriptTreeClient final : public ModuleTreeClient {
void Trace(blink::Visitor*) override;
private:
- ModulePendingScriptTreeClient();
-
// Implements ModuleTreeClient
void NotifyModuleTreeLoadFinished(ModuleScript*) override;
@@ -52,9 +52,13 @@ class CORE_EXPORT ModulePendingScript : public PendingScript {
static ModulePendingScript* Create(ScriptElementBase* element,
ModulePendingScriptTreeClient* client,
bool is_external) {
- return new ModulePendingScript(element, client, is_external);
+ return MakeGarbageCollected<ModulePendingScript>(element, client,
+ is_external);
}
+ ModulePendingScript(ScriptElementBase*,
+ ModulePendingScriptTreeClient*,
+ bool is_external);
~ModulePendingScript() override;
void NotifyModuleTreeLoadFinished();
@@ -66,12 +70,10 @@ class CORE_EXPORT ModulePendingScript : public PendingScript {
void Trace(blink::Visitor*) override;
private:
- ModulePendingScript(ScriptElementBase*,
- ModulePendingScriptTreeClient*,
- bool is_external);
-
// PendingScript
- ScriptType GetScriptType() const override { return ScriptType::kModule; }
+ mojom::ScriptType GetScriptType() const override {
+ return mojom::ScriptType::kModule;
+ }
Script* GetSource(const KURL& document_url) const override;
bool IsReady() const override { return ready_; }
bool IsExternal() const override { return is_external_; }
diff --git a/chromium/third_party/blink/renderer/core/script/module_script.cc b/chromium/third_party/blink/renderer/core/script/module_script.cc
index b344ffdb75e..9cd7bdd76cb 100644
--- a/chromium/third_party/blink/renderer/core/script/module_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_script.cc
@@ -11,13 +11,12 @@
namespace blink {
-// https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-module-script
+// <specdef href="https://html.spec.whatwg.org/#creating-a-module-script">
ModuleScript* ModuleScript::Create(const ParkableString& original_source_text,
Modulator* modulator,
const KURL& source_url,
const KURL& base_url,
const ScriptFetchOptions& options,
- AccessControlStatus access_control_status,
const TextPosition& start_position) {
// <spec step="1">If scripting is disabled for settings's responsible browsing
// context, then set source to the empty string.</spec>
@@ -40,9 +39,9 @@ ModuleScript* ModuleScript::Create(const ParkableString& original_source_text,
ExceptionState exception_state(isolate, ExceptionState::kExecutionContext,
"ModuleScript", "Create");
- ScriptModule result = ScriptModule::Compile(
- isolate, source_text.ToString(), source_url, base_url, options,
- access_control_status, start_position, exception_state);
+ ScriptModule result =
+ ScriptModule::Compile(isolate, source_text.ToString(), source_url,
+ base_url, options, start_position, exception_state);
// CreateInternal processes Steps 4 and 8-10.
//
@@ -72,7 +71,7 @@ ModuleScript* ModuleScript::Create(const ParkableString& original_source_text,
for (const auto& requested :
modulator->ModuleRequestsFromScriptModule(result)) {
// <spec step="9.1">Let url be the result of resolving a module specifier
- // given script and requested.</spec>
+ // given script's base URL and requested.</spec>
//
// <spec step="9.2">If url is failure, then:</spec>
String failure_reason;
@@ -107,7 +106,7 @@ ModuleScript* ModuleScript::CreateForTest(Modulator* modulator,
base_url, options, TextPosition::MinimumPosition());
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-module-script
+// <specdef href="https://html.spec.whatwg.org/#creating-a-module-script">
ModuleScript* ModuleScript::CreateInternal(const ParkableString& source_text,
Modulator* modulator,
ScriptModule result,
@@ -125,9 +124,9 @@ ModuleScript* ModuleScript::CreateInternal(const ParkableString& source_text,
// <spec step="5">Set script's fetch options to options.</spec>
//
// [nospec] |source_text| is saved for CSP checks.
- ModuleScript* module_script =
- new ModuleScript(modulator, result, source_url, base_url, options,
- source_text, start_position);
+ ModuleScript* module_script = MakeGarbageCollected<ModuleScript>(
+ modulator, result, source_url, base_url, options, source_text,
+ start_position);
// Step 7, a part of ParseModule(): Passing script as the last parameter
// here ensures result.[[HostDefined]] will be script.
diff --git a/chromium/third_party/blink/renderer/core/script/module_script.h b/chromium/third_party/blink/renderer/core/script/module_script.h
index 961507271f9..071d0cee791 100644
--- a/chromium/third_party/blink/renderer/core/script/module_script.h
+++ b/chromium/third_party/blink/renderer/core/script/module_script.h
@@ -32,7 +32,6 @@ class CORE_EXPORT ModuleScript final : public Script, public NameClient {
const KURL& source_url,
const KURL& base_url,
const ScriptFetchOptions&,
- AccessControlStatus,
const TextPosition& start_position = TextPosition::MinimumPosition());
// Mostly corresponds to Create() but accepts ScriptModule as the argument
@@ -43,6 +42,13 @@ class CORE_EXPORT ModuleScript final : public Script, public NameClient {
const KURL& base_url,
const ScriptFetchOptions& = ScriptFetchOptions());
+ ModuleScript(Modulator* settings_object,
+ ScriptModule record,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions&,
+ const ParkableString& source_text,
+ const TextPosition& start_position);
~ModuleScript() override = default;
ScriptModule Record() const;
@@ -66,14 +72,6 @@ class CORE_EXPORT ModuleScript final : public Script, public NameClient {
const char* NameInHeapSnapshot() const override { return "ModuleScript"; }
private:
- ModuleScript(Modulator* settings_object,
- ScriptModule record,
- const KURL& source_url,
- const KURL& base_url,
- const ScriptFetchOptions&,
- const ParkableString& source_text,
- const TextPosition& start_position);
-
static ModuleScript* CreateInternal(const ParkableString& source_text,
Modulator*,
ScriptModule,
@@ -82,7 +80,9 @@ class CORE_EXPORT ModuleScript final : public Script, public NameClient {
const ScriptFetchOptions&,
const TextPosition&);
- ScriptType GetScriptType() const override { return ScriptType::kModule; }
+ mojom::ScriptType GetScriptType() const override {
+ return mojom::ScriptType::kModule;
+ }
void RunScript(LocalFrame*, const SecurityOrigin*) const override;
String InlineSourceTextForCSP() const override;
diff --git a/chromium/third_party/blink/renderer/core/script/pending_script.cc b/chromium/third_party/blink/renderer/core/script/pending_script.cc
index 2a3901ed167..617d7c8d890 100644
--- a/chromium/third_party/blink/renderer/core/script/pending_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/pending_script.cc
@@ -124,7 +124,7 @@ void PendingScript::MarkParserBlockingLoadStartTime() {
parser_blocking_load_start_time_ = CurrentTimeTicks();
}
-// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block
+// <specdef href="https://html.spec.whatwg.org/#execute-the-script-block">
void PendingScript::ExecuteScriptBlock(const KURL& document_url) {
Document* context_document = element_->GetDocument().ContextDocument();
if (!context_document) {
@@ -139,7 +139,7 @@ void PendingScript::ExecuteScriptBlock(const KURL& document_url) {
}
if (OriginalContextDocument() != context_document) {
- if (GetScriptType() == ScriptType::kModule) {
+ if (GetScriptType() == mojom::ScriptType::kModule) {
// Do not execute module scripts if they are moved between documents.
Dispose();
return;
@@ -154,15 +154,19 @@ void PendingScript::ExecuteScriptBlock(const KURL& document_url) {
if (script && !IsExternal()) {
bool should_bypass_main_world_csp =
- frame->GetScriptController().ShouldBypassMainWorldCSP();
+ ContentSecurityPolicy::ShouldBypassMainWorld(&element_->GetDocument());
AtomicString nonce = element_->GetNonceForElement();
if (!should_bypass_main_world_csp &&
!element_->AllowInlineScriptForCSP(
nonce, StartingPosition().line_, script->InlineSourceTextForCSP(),
ContentSecurityPolicy::InlineType::kBlock)) {
- // Consider as if "the script's script is null" retrospectively,
- // if the CSP check fails, which is considered as load failure.
+ // Consider as if:
+ //
+ // <spec step="2">If the script's script is null, ...</spec>
+ //
+ // retrospectively, if the CSP check fails, which is considered as load
+ // failure.
script = nullptr;
}
}
@@ -183,6 +187,7 @@ void PendingScript::ExecuteScriptBlock(const KURL& document_url) {
parser_blocking_load_start_time, is_controlled_by_script_runner);
}
+// <specdef href="https://html.spec.whatwg.org/#execute-the-script-block">
void PendingScript::ExecuteScriptBlockInternal(
Script* script,
ScriptElementBase* element,
@@ -224,7 +229,7 @@ void PendingScript::ExecuteScriptBlockInternal(
// <spec step="3">If the script is from an external file, or the script's
// type is "module", ...</spec>
const bool needs_increment =
- is_external || script->GetScriptType() == ScriptType::kModule ||
+ is_external || script->GetScriptType() == mojom::ScriptType::kModule ||
is_imported_script;
// <spec step="3">... then increment the ignore-destructive-writes counter
// of the script element's node document. Let neutralized doc be that
@@ -240,29 +245,29 @@ void PendingScript::ExecuteScriptBlockInternal(
// <spec step="5">Switch on the script's type:</spec>
//
- // Step 5.A. "classic" [spec text]
+ // <spec step="5.A">"classic"</spec>
//
// <spec step="5.A.1">If the script element's root is not a shadow root,
// then set the script element's node document's currentScript attribute to
// the script element. Otherwise, set it to null.</spec>
//
- // Step 5.B. "module" [spec text]
+ // <spec step="5.B">"module"</spec>
//
// <spec step="5.B.1">Set the script element's node document's currentScript
// attribute to null.</spec>
ScriptElementBase* current_script = nullptr;
- if (script->GetScriptType() == ScriptType::kClassic)
+ if (script->GetScriptType() == mojom::ScriptType::kClassic)
current_script = element;
context_document->PushCurrentScript(current_script);
- // Step 5.A. "classic" [spec text]
+ // <spec step="5.A">"classic"</spec>
//
// <spec step="5.A.2">Run the classic script given by the script's
// script.</spec>
//
// Note: This is where the script is compiled and actually executed.
//
- // Step 5.B. "module" [spec text]
+ // <spec step="5.B">"module"</spec>
//
// <spec step="5.B.2">Run the module script given by the script's
// script.</spec>
diff --git a/chromium/third_party/blink/renderer/core/script/pending_script.h b/chromium/third_party/blink/renderer/core/script/pending_script.h
index d031cc77698..0ab981568b8 100644
--- a/chromium/third_party/blink/renderer/core/script/pending_script.h
+++ b/chromium/third_party/blink/renderer/core/script/pending_script.h
@@ -27,6 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_PENDING_SCRIPT_H_
#include "base/macros.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/web_scoped_virtual_time_pauser.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/script/script.h"
@@ -76,13 +77,13 @@ class CORE_EXPORT PendingScript
return parser_blocking_load_start_time_;
}
- void WatchForLoad(PendingScriptClient*);
+ virtual void WatchForLoad(PendingScriptClient*);
void StopWatchingForLoad();
void PendingScriptFinished();
ScriptElementBase* GetElement() const;
- virtual ScriptType GetScriptType() const = 0;
+ virtual mojom::ScriptType GetScriptType() const = 0;
virtual void Trace(blink::Visitor*);
const char* NameInHeapSnapshot() const override { return "PendingScript"; }
@@ -107,7 +108,7 @@ class CORE_EXPORT PendingScript
// Used for DCHECK()s.
bool IsExternalOrModule() const {
- return IsExternal() || GetScriptType() == ScriptType::kModule;
+ return IsExternal() || GetScriptType() == mojom::ScriptType::kModule;
}
void Dispose();
diff --git a/chromium/third_party/blink/renderer/core/script/script.h b/chromium/third_party/blink/renderer/core/script/script.h
index a807959fb97..7ef29600057 100644
--- a/chromium/third_party/blink/renderer/core/script/script.h
+++ b/chromium/third_party/blink/renderer/core/script/script.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_H_
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -16,10 +17,6 @@ namespace blink {
class LocalFrame;
class SecurityOrigin;
-// TODO(asamidoi, nhiroki): Remove this enum in favor of
-// blink::mojom::ScriptType.
-enum class ScriptType { kClassic, kModule };
-
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-script
class CORE_EXPORT Script : public GarbageCollectedFinalized<Script> {
public:
@@ -27,7 +24,7 @@ class CORE_EXPORT Script : public GarbageCollectedFinalized<Script> {
virtual ~Script() {}
- virtual ScriptType GetScriptType() const = 0;
+ virtual mojom::ScriptType GetScriptType() const = 0;
// https://html.spec.whatwg.org/multipage/webappapis.html#run-a-classic-script
// or
diff --git a/chromium/third_party/blink/renderer/core/script/script_loader.cc b/chromium/third_party/blink/renderer/core/script/script_loader.cc
index 894ccc3cd42..c058625bbcf 100644
--- a/chromium/third_party/blink/renderer/core/script/script_loader.cc
+++ b/chromium/third_party/blink/renderer/core/script/script_loader.cc
@@ -24,6 +24,7 @@
#include "third_party/blink/renderer/core/script/script_loader.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
@@ -49,7 +50,6 @@
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
@@ -69,10 +69,9 @@ ScriptLoader::ScriptLoader(ScriptElementBase* element,
: element_(element),
will_be_parser_executed_(false),
will_execute_when_document_finished_parsing_(false) {
- // <spec
- // href="https://html.spec.whatwg.org/multipage/scripting.html#already-started">
- // ... The cloning steps for script elements must set the "already started"
- // flag on the copy if it is set on the element being cloned.</spec>
+ // <spec href="https://html.spec.whatwg.org/#already-started">... The cloning
+ // steps for script elements must set the "already started" flag on the copy
+ // if it is set on the element being cloned.</spec>
//
// TODO(hiroshige): Cloning is implemented together with
// {HTML,SVG}ScriptElement::cloneElementWithoutAttributesAndChildren().
@@ -81,16 +80,14 @@ ScriptLoader::ScriptLoader(ScriptElementBase* element,
already_started_ = true;
if (parser_inserted) {
- // <spec
- // href="https://html.spec.whatwg.org/multipage/scripting.html#parser-inserted">
- // ... It is set by the HTML parser and the XML parser on script elements
- // they insert ...</spec>
+ // <spec href="https://html.spec.whatwg.org/#parser-inserted">... It is set
+ // by the HTML parser and the XML parser on script elements they insert
+ // ...</spec>
parser_inserted_ = true;
- // <spec
- // href="https://html.spec.whatwg.org/multipage/scripting.html#non-blocking">
- // ... It is unset by the HTML parser and the XML parser on script elements
- // they insert. ...</spec>
+ // <spec href="https://html.spec.whatwg.org/#non-blocking">... It is unset
+ // by the HTML parser and the XML parser on script elements they insert.
+ // ...</spec>
non_blocking_ = false;
}
}
@@ -122,12 +119,11 @@ void ScriptLoader::HandleSourceAttribute(const String& source_url) {
PrepareScript(); // FIXME: Provide a real starting line number here.
}
+// <specdef href="https://html.spec.whatwg.org/#non-blocking">
void ScriptLoader::HandleAsyncAttribute() {
- // <spec
- // href="https://html.spec.whatwg.org/multipage/scripting.html#non-blocking">
- // ... In addition, whenever a script element whose "non-blocking" flag is set
- // has an async content attribute added, the element's "non-blocking" flag
- // must be unset.</spec>
+ // <spec>... In addition, whenever a script element whose "non-blocking" flag
+ // is set has an async content attribute added, the element's "non-blocking"
+ // flag must be unset.</spec>
non_blocking_ = false;
}
@@ -169,19 +165,19 @@ bool IsValidClassicScriptTypeAndLanguage(
} // namespace
-// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
+// <specdef href="https://html.spec.whatwg.org/#prepare-a-script">
bool ScriptLoader::IsValidScriptTypeAndLanguage(
const String& type,
const String& language,
LegacyTypeSupport support_legacy_types,
- ScriptType& out_script_type) {
+ mojom::ScriptType& out_script_type) {
if (IsValidClassicScriptTypeAndLanguage(type, language,
support_legacy_types)) {
// <spec step="7">... If the script block's type string is a JavaScript MIME
// type essence match, the script's type is "classic". ...</spec>
//
// TODO(hiroshige): Annotate and/or cleanup this step.
- out_script_type = ScriptType::kClassic;
+ out_script_type = mojom::ScriptType::kClassic;
return true;
}
@@ -189,7 +185,7 @@ bool ScriptLoader::IsValidScriptTypeAndLanguage(
// <spec step="7">... If the script block's type string is an ASCII
// case-insensitive match for the string "module", the script's type is
// "module". ...</spec>
- out_script_type = ScriptType::kModule;
+ out_script_type = mojom::ScriptType::kModule;
return true;
}
@@ -198,8 +194,9 @@ bool ScriptLoader::IsValidScriptTypeAndLanguage(
return false;
}
-bool ScriptLoader::BlockForNoModule(ScriptType script_type, bool nomodule) {
- return nomodule && script_type == ScriptType::kClassic;
+bool ScriptLoader::BlockForNoModule(mojom::ScriptType script_type,
+ bool nomodule) {
+ return nomodule && script_type == mojom::ScriptType::kClassic;
}
// Corresponds to
@@ -225,7 +222,7 @@ network::mojom::FetchCredentialsMode ScriptLoader::ModuleScriptCredentialsMode(
// https://github.com/WICG/feature-policy/issues/135
bool ShouldBlockSyncScriptForFeaturePolicy(const ScriptElementBase* element,
- ScriptType script_type,
+ mojom::ScriptType script_type,
bool parser_inserted) {
if (element->GetDocument().GetFeaturePolicy()->IsFeatureEnabled(
mojom::FeaturePolicyFeature::kSyncScript)) {
@@ -233,7 +230,7 @@ bool ShouldBlockSyncScriptForFeaturePolicy(const ScriptElementBase* element,
}
// Module scripts never block parsing.
- if (script_type == ScriptType::kModule || !parser_inserted)
+ if (script_type == mojom::ScriptType::kModule || !parser_inserted)
return false;
if (!element->HasSourceAttribute())
@@ -241,7 +238,7 @@ bool ShouldBlockSyncScriptForFeaturePolicy(const ScriptElementBase* element,
return !element->DeferAttributeValue() && !element->AsyncAttributeValue();
}
-// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
+// <specdef href="https://html.spec.whatwg.org/#prepare-a-script">
bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
LegacyTypeSupport support_legacy_types) {
// <spec step="1">If the script element is marked as having "already started",
@@ -310,11 +307,9 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="11">If scripting is disabled for the script element, then
// return. The script is not executed.</spec>
//
- // <spec
- // href="https://html.spec.whatwg.org/multipage/webappapis.html#concept-n-noscript">
- // Scripting is disabled for a node if [the node's node document has no
- // browsing context], or if scripting is disabled in that browsing context.
- // </spec>
+ // <spec href="https://html.spec.whatwg.org/#concept-n-noscript">Scripting is
+ // disabled for a node if there is no such browsing context, or if scripting
+ // is disabled in that browsing context.</spec>
Document& element_document = element_->GetDocument();
// TODO(timothygu): Investigate if we could switch from ExecutingFrame() to
// ExecutingWindow().
@@ -379,7 +374,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="20">Let referrer policy be the current state of the element's
// referrerpolicy content attribute.</spec>
String referrerpolicy_attr = element_->ReferrerPolicyAttributeValue();
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
if (!referrerpolicy_attr.IsEmpty()) {
SecurityPolicy::ReferrerPolicyFromString(
referrerpolicy_attr, kDoNotSupportReferrerPolicyLegacyKeywords,
@@ -392,7 +388,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
ParserDisposition parser_state =
IsParserInserted() ? kParserInserted : kNotParserInserted;
- if (GetScriptType() == ScriptType::kModule)
+ if (GetScriptType() == mojom::ScriptType::kModule)
UseCounter::Count(*context_document, WebFeature::kPrepareModuleScript);
DCHECK(!prepared_pending_script_);
@@ -417,8 +413,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
ScriptFetchOptions options(nonce, integrity_metadata, integrity_attr,
parser_state, credentials_mode, referrer_policy);
- // <spec step="23">Let settings object be the element's node document's Window
- // object's environment settings object.</spec>
+ // <spec step="23">Let settings object be the element's node document's
+ // relevant settings object.</spec>
//
// Note: We use |element_document| as "settings object" in the steps below.
auto* settings_object =
@@ -460,7 +456,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
}
// <spec step="24.6">Switch on the script's type:</spec>
- if (GetScriptType() == ScriptType::kClassic) {
+ if (GetScriptType() == mojom::ScriptType::kClassic) {
// - "classic":
// <spec step="15">If the script element has a charset attribute, then let
@@ -511,7 +507,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="25">If the element does not have a src content attribute, run
// these substeps:</spec>
if (!element_->HasSourceAttribute()) {
- // <spec step="25.1">Let src be the value of the element's src
+ // <spec step="24.1">Let src be the value of the element's src
// attribute.</spec>
//
// This step is done later as ScriptElementBase::TextFromChildren():
@@ -529,8 +525,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="25.2">Switch on the script's type:</spec>
switch (GetScriptType()) {
- // Step 25.2.A. "classic" [spec text]
- case ScriptType::kClassic: {
+ // <spec step="25.2.A">"classic"</spec>
+ case mojom::ScriptType::kClassic: {
// <spec step="25.2.A.1">Let script be the result of creating a classic
// script using source text, settings object, base URL, and
// options.</spec>
@@ -556,8 +552,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
break;
}
- // Step 25.2.B. "module" [spec text]
- case ScriptType::kModule: {
+ // <spec step="25.2.B">"module"</spec>
+ case mojom::ScriptType::kModule: {
// <spec step="25.2.B.1">Let script be the result of creating a module
// script using source text, settings object, base URL, and
// options.</spec>
@@ -566,7 +562,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
ToScriptStateForMainWorld(context_document->GetFrame()));
ModuleScript* module_script = ModuleScript::Create(
ParkableString(element_->TextFromChildren().Impl()), modulator,
- source_url, base_url, options, kSharableCrossOrigin, position);
+ source_url, base_url, options, position);
// <spec step="25.2.B.2">If this returns null, set the script's script
// to null and return; the script is ready.</spec>
@@ -574,9 +570,9 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
return false;
// <spec step="25.2.B.3">Fetch the descendants of and instantiate
- // script, given the destination "script". When this asynchronously
- // completes, set the script's script to the result. At that time, the
- // script is ready.</spec>
+ // script, given settings object and the destination "script". When this
+ // asynchronously completes, set the script's script to the result. At
+ // that time, the script is ready.</spec>
auto* module_tree_client = ModulePendingScriptTreeClient::Create();
modulator->FetchDescendantsForInlineScript(
module_script, settings_object, mojom::RequestContextType::SCRIPT,
@@ -608,10 +604,10 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// If the script's type is "module", and the element has been flagged as
// "parser-inserted", and the element does not have an async attribute
// ...</spec>
- if ((GetScriptType() == ScriptType::kClassic &&
+ if ((GetScriptType() == mojom::ScriptType::kClassic &&
element_->HasSourceAttribute() && element_->DeferAttributeValue() &&
parser_inserted_ && !element_->AsyncAttributeValue()) ||
- (GetScriptType() == ScriptType::kModule && parser_inserted_ &&
+ (GetScriptType() == mojom::ScriptType::kModule && parser_inserted_ &&
!element_->AsyncAttributeValue())) {
// This clause is implemented by the caller-side of prepareScript():
// - HTMLParserScriptRunner::requestDeferredScript(), and
@@ -625,7 +621,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="26.B">If the script's type is "classic", and the element has a
// src attribute, and the element has been flagged as "parser-inserted", and
// the element does not have an async attribute ...</spec>
- if (GetScriptType() == ScriptType::kClassic &&
+ if (GetScriptType() == mojom::ScriptType::kClassic &&
element_->HasSourceAttribute() && parser_inserted_ &&
!element_->AsyncAttributeValue()) {
// This clause is implemented by the caller-side of prepareScript():
@@ -643,10 +639,10 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// If the script's type is "module", and the element does not have an async
// attribute, and the element does not have the "non-blocking" flag set
// ...</spec>
- if ((GetScriptType() == ScriptType::kClassic &&
+ if ((GetScriptType() == mojom::ScriptType::kClassic &&
element_->HasSourceAttribute() && !element_->AsyncAttributeValue() &&
!non_blocking_) ||
- (GetScriptType() == ScriptType::kModule &&
+ (GetScriptType() == mojom::ScriptType::kModule &&
!element_->AsyncAttributeValue() && !non_blocking_)) {
// <spec step="26.C">... Add the element to the end of the list of scripts
// that will execute in order as soon as possible associated with the node
@@ -670,9 +666,9 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// src attribute
//
// If the script's type is "module" ...</spec>
- if ((GetScriptType() == ScriptType::kClassic &&
+ if ((GetScriptType() == mojom::ScriptType::kClassic &&
element_->HasSourceAttribute()) ||
- GetScriptType() == ScriptType::kModule) {
+ GetScriptType() == mojom::ScriptType::kModule) {
// <spec step="26.D">... The element must be added to the set of scripts
// that will execute as soon as possible of the node document of the script
// element at the time the prepare a script algorithm started. When the
@@ -694,7 +690,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// The following clauses are executed only if the script's type is "classic"
// and the element doesn't have a src attribute.
- DCHECK_EQ(GetScriptType(), ScriptType::kClassic);
+ DCHECK_EQ(GetScriptType(), mojom::ScriptType::kClassic);
DCHECK(!is_external_script_);
// <spec step="26.E">If the element does not have a src attribute, and the
@@ -704,7 +700,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// or XML parser that created the script element has a style sheet that is
// blocking scripts ...</spec>
//
- // The last part "... has a style sheet that is blocking scripts"
+ // <spec step="26.E">... has a style sheet that is blocking scripts ...</spec>
+ //
// is implemented in Document::isScriptExecutionReady().
// Part of the condition check is done in
// HTMLParserScriptRunner::processScriptElementInternal().
@@ -756,14 +753,13 @@ void ScriptLoader::FetchClassicScript(const KURL& url,
resource_keep_alive_ = pending_script->GetResource();
}
+// <specdef href="https://html.spec.whatwg.org/#prepare-a-script">
void ScriptLoader::FetchModuleScriptTree(
const KURL& url,
FetchClientSettingsObjectSnapshot* settings_object,
Modulator* modulator,
const ScriptFetchOptions& options) {
- // <spec
- // href="https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script"
- // step="23.6.B">"module"
+ // <spec step="24.6.B">"module"
//
// Fetch a module script graph given url, settings object, "script", and
// options.</spec>
@@ -828,7 +824,7 @@ bool ScriptLoader::IgnoresLoadRequest() const {
!element_->IsConnected();
}
-// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
+// <specdef href="https://html.spec.whatwg.org/#prepare-a-script">
bool ScriptLoader::IsScriptForEventSupported() const {
// <spec step="14.1">Let for be the value of the for attribute.</spec>
String event_attribute = element_->EventAttributeValue();
@@ -837,8 +833,8 @@ bool ScriptLoader::IsScriptForEventSupported() const {
// <spec step="14">If the script element has an event attribute and a for
// attribute, and the script's type is "classic", then:</spec>
- if (GetScriptType() != ScriptType::kClassic || event_attribute.IsNull() ||
- for_attribute.IsNull())
+ if (GetScriptType() != mojom::ScriptType::kClassic ||
+ event_attribute.IsNull() || for_attribute.IsNull())
return true;
// <spec step="14.3">Strip leading and trailing ASCII whitespace from event
diff --git a/chromium/third_party/blink/renderer/core/script/script_loader.h b/chromium/third_party/blink/renderer/core/script/script_loader.h
index 0369a823956..95a3a3d70d6 100644
--- a/chromium/third_party/blink/renderer/core/script/script_loader.h
+++ b/chromium/third_party/blink/renderer/core/script/script_loader.h
@@ -21,6 +21,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_LOADER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_LOADER_H_
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_location_type.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -57,9 +58,11 @@ class CORE_EXPORT ScriptLoader final
static ScriptLoader* Create(ScriptElementBase* element,
bool created_by_parser,
bool is_evaluated) {
- return new ScriptLoader(element, created_by_parser, is_evaluated);
+ return MakeGarbageCollected<ScriptLoader>(element, created_by_parser,
+ is_evaluated);
}
+ ScriptLoader(ScriptElementBase*, bool created_by_parser, bool is_evaluated);
~ScriptLoader() override;
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override { return "ScriptLoader"; }
@@ -72,9 +75,9 @@ class CORE_EXPORT ScriptLoader final
const String& type_attribute_value,
const String& language_attribute_value,
LegacyTypeSupport support_legacy_types,
- ScriptType& out_script_type);
+ mojom::ScriptType& out_script_type);
- static bool BlockForNoModule(ScriptType, bool nomodule);
+ static bool BlockForNoModule(mojom::ScriptType, bool nomodule);
static network::mojom::FetchCredentialsMode ModuleScriptCredentialsMode(
CrossOriginAttributeValue);
@@ -97,7 +100,7 @@ class CORE_EXPORT ScriptLoader final
bool IsParserInserted() const { return parser_inserted_; }
bool AlreadyStarted() const { return already_started_; }
bool IsNonBlocking() const { return non_blocking_; }
- ScriptType GetScriptType() const { return script_type_; }
+ mojom::ScriptType GetScriptType() const { return script_type_; }
// Helper functions used by our parent classes.
void DidNotifySubtreeInsertionsToDocument();
@@ -112,9 +115,6 @@ class CORE_EXPORT ScriptLoader final
// crbug.com/721914 is fixed.
PendingScript* GetPendingScriptIfControlledByScriptRunnerForCrossDocMove();
- protected:
- ScriptLoader(ScriptElementBase*, bool created_by_parser, bool is_evaluated);
-
private:
bool IgnoresLoadRequest() const;
bool IsScriptForEventSupported() const;
@@ -169,7 +169,7 @@ class CORE_EXPORT ScriptLoader final
// <spec
// href="https://html.spec.whatwg.org/multipage/scripting.html#concept-script-type">
// ... It is determined when the script is prepared, ...</spec>
- ScriptType script_type_ = ScriptType::kClassic;
+ mojom::ScriptType script_type_ = mojom::ScriptType::kClassic;
// <spec
// href="https://html.spec.whatwg.org/multipage/scripting.html#concept-script-external">
diff --git a/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.cc b/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.cc
index 9d4802f89a2..9032ada8d4a 100644
--- a/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.cc
+++ b/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.cc
@@ -50,7 +50,8 @@ ModuleScript* ScriptModuleResolverImpl::GetHostDefined(
return it->value;
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-specifier)
+// <specdef
+// href="https://html.spec.whatwg.org/#hostresolveimportedmodule(referencingscriptormodule,-specifier)">
ScriptModule ScriptModuleResolverImpl::Resolve(
const String& specifier,
const ScriptModule& referrer,
@@ -58,32 +59,37 @@ ScriptModule ScriptModuleResolverImpl::Resolve(
DVLOG(1) << "ScriptModuleResolverImpl::resolve(specifier=\"" << specifier
<< ", referrer.hash=" << ScriptModuleHash::GetHash(referrer) << ")";
- // Step 1. Let referencing module script be referencingModule.[[HostDefined]].
+ // <spec step="1">Let referencing script be
+ // referencingScriptOrModule.[[HostDefined]].</spec>
ModuleScript* referrer_module = GetHostDefined(referrer);
- // Step 2. Let moduleMap be referencing module script's settings object's
- // module map. Note: Blink finds out "module script's settings object"
+ // <spec step="2">Let moduleMap be referencing script's settings object's
+ // module map.</spec>
+ //
+ // Note: Blink finds out "module script's settings object"
// (Modulator) from context where HostResolveImportedModule was called.
- // Step 3. Let url be the result of resolving a module specifier given
- // referencing module script and specifier.
+ // <spec step="3">Let url be the result of resolving a module specifier given
+ // referencing script's base URL and specifier.</spec>
KURL url = referrer_module->ResolveModuleSpecifier(specifier);
- // Step 4. Assert: url is never failure, because resolving a module specifier
- // must have been previously successful with these same two arguments.
+ // <spec step="4">Assert: url is never failure, because resolving a module
+ // specifier must have been previously successful with these same two
+ // arguments.</spec>
DCHECK(url.IsValid());
- // Step 5. Let resolved module script be moduleMap[url]. (This entry must
- // exist for us to have gotten to this point.)
+ // <spec step="5">Let resolved module script be moduleMap[url]. (This entry
+ // must exist for us to have gotten to this point.)</spec>
ModuleScript* module_script = modulator_->GetFetchedModuleScript(url);
- // Step 6. Assert: resolved module script is a module script (i.e., is not
- // null or "fetching").
- // Step 7. Assert: resolved module script's record is not null.
+ // <spec step="6">Assert: resolved module script is a module script (i.e., is
+ // not null or "fetching").</spec>
+ //
+ // <spec step="7">Assert: resolved module script's record is not null.</spec>
DCHECK(module_script);
CHECK(!module_script->Record().IsNull());
- // Step 8. Return resolved module script's module record.
+ // <spec step="8">Return resolved module script's record.</spec>
return module_script->Record();
}
diff --git a/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.h b/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.h
index db0d2bb386c..248e8ba799b 100644
--- a/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.h
+++ b/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl.h
@@ -28,17 +28,18 @@ class CORE_EXPORT ScriptModuleResolverImpl final
public:
static ScriptModuleResolverImpl* Create(Modulator* modulator,
ExecutionContext* execution_context) {
- return new ScriptModuleResolverImpl(modulator, execution_context);
+ return MakeGarbageCollected<ScriptModuleResolverImpl>(modulator,
+ execution_context);
}
- void Trace(blink::Visitor*) override;
- USING_GARBAGE_COLLECTED_MIXIN(ScriptModuleResolverImpl);
-
- private:
explicit ScriptModuleResolverImpl(Modulator* modulator,
ExecutionContext* execution_context)
: ContextLifecycleObserver(execution_context), modulator_(modulator) {}
+ void Trace(blink::Visitor*) override;
+ USING_GARBAGE_COLLECTED_MIXIN(ScriptModuleResolverImpl);
+
+ private:
// Implements ScriptModuleResolver:
void RegisterModuleScript(ModuleScript*) final;
diff --git a/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl_test.cc b/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl_test.cc
index 911117b1705..9fbfae71b0a 100644
--- a/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/script_module_resolver_impl_test.cc
@@ -75,8 +75,8 @@ ModuleScript* CreateReferrerModuleScript(Modulator* modulator,
KURL js_url("https://example.com/referrer.js");
ScriptModule referrer_record = ScriptModule::Compile(
scope.GetIsolate(), "import './target.js'; export const a = 42;", js_url,
- js_url, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ js_url, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
KURL referrer_url("https://example.com/referrer.js");
auto* referrer_module_script =
ModuleScript::CreateForTest(modulator, referrer_record, referrer_url);
@@ -89,8 +89,8 @@ ModuleScript* CreateTargetModuleScript(Modulator* modulator,
KURL js_url("https://example.com/target.js");
ScriptModule record = ScriptModule::Compile(
scope.GetIsolate(), "export const pi = 3.14;", js_url, js_url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
KURL url("https://example.com/target.js");
auto* module_script = ModuleScript::CreateForTest(modulator, record, url);
if (has_parse_error) {
diff --git a/chromium/third_party/blink/renderer/core/script/script_runner.h b/chromium/third_party/blink/renderer/core/script/script_runner.h
index e64c99b4dde..9a4608e4495 100644
--- a/chromium/third_party/blink/renderer/core/script/script_runner.h
+++ b/chromium/third_party/blink/renderer/core/script/script_runner.h
@@ -47,9 +47,11 @@ class CORE_EXPORT ScriptRunner final
public NameClient {
public:
static ScriptRunner* Create(Document* document) {
- return new ScriptRunner(document);
+ return MakeGarbageCollected<ScriptRunner>(document);
}
+ explicit ScriptRunner(Document*);
+
void QueueScriptForExecution(PendingScript*);
bool HasPendingScripts() const {
return !pending_in_order_scripts_.IsEmpty() ||
@@ -68,8 +70,6 @@ class CORE_EXPORT ScriptRunner final
private:
class Task;
- explicit ScriptRunner(Document*);
-
void MovePendingScript(ScriptRunner*, PendingScript*);
bool RemovePendingInOrderScript(PendingScript*);
void ScheduleReadyInOrderScripts();
diff --git a/chromium/third_party/blink/renderer/core/script/script_runner_test.cc b/chromium/third_party/blink/renderer/core/script/script_runner_test.cc
index e25af546c27..7fab1aa0bec 100644
--- a/chromium/third_party/blink/renderer/core/script/script_runner_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/script_runner_test.cc
@@ -33,9 +33,14 @@ class MockPendingScript : public PendingScript {
return Create(document, ScriptSchedulingType::kAsync);
}
+ MockPendingScript(ScriptElementBase* element,
+ ScriptSchedulingType scheduling_type)
+ : PendingScript(element, TextPosition()) {
+ SetSchedulingType(scheduling_type);
+ }
~MockPendingScript() override {}
- MOCK_CONST_METHOD0(GetScriptType, ScriptType());
+ MOCK_CONST_METHOD0(GetScriptType, mojom::ScriptType());
MOCK_CONST_METHOD1(CheckMIMETypeBeforeRunScript, bool(Document*));
MOCK_CONST_METHOD1(GetSource, Script*(const KURL&));
MOCK_CONST_METHOD0(IsExternal, bool());
@@ -85,19 +90,13 @@ class MockPendingScript : public PendingScript {
MOCK_CONST_METHOD0(CheckState, void());
private:
- MockPendingScript(ScriptElementBase* element,
- ScriptSchedulingType scheduling_type)
- : PendingScript(element, TextPosition()) {
- SetSchedulingType(scheduling_type);
- }
-
static MockPendingScript* Create(Document* document,
ScriptSchedulingType scheduling_type) {
MockScriptElementBase* element = MockScriptElementBase::Create();
EXPECT_CALL(*element, GetDocument())
.WillRepeatedly(testing::ReturnRef(*document));
MockPendingScript* pending_script =
- new MockPendingScript(element, scheduling_type);
+ MakeGarbageCollected<MockPendingScript>(element, scheduling_type);
EXPECT_CALL(*pending_script, IsExternal()).WillRepeatedly(Return(true));
return pending_script;
}
diff --git a/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.cc b/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.cc
index 3cba1547df4..09f3c14c895 100644
--- a/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.cc
+++ b/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.h"
+#include "third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.h"
#include "third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
@@ -14,7 +15,7 @@
namespace blink {
ModulatorImplBase* WorkerModulatorImpl::Create(ScriptState* script_state) {
- return new WorkerModulatorImpl(script_state);
+ return MakeGarbageCollected<WorkerModulatorImpl>(script_state);
}
WorkerModulatorImpl::WorkerModulatorImpl(ScriptState* script_state)
@@ -22,14 +23,17 @@ WorkerModulatorImpl::WorkerModulatorImpl(ScriptState* script_state)
ModuleScriptFetcher* WorkerModulatorImpl::CreateModuleScriptFetcher(
ModuleScriptCustomFetchType custom_fetch_type) {
- auto* global_scope = ToWorkerGlobalScope(GetExecutionContext());
+ auto* global_scope = To<WorkerGlobalScope>(GetExecutionContext());
switch (custom_fetch_type) {
case ModuleScriptCustomFetchType::kNone:
- return new DocumentModuleScriptFetcher(global_scope->EnsureFetcher());
+ return MakeGarbageCollected<DocumentModuleScriptFetcher>(
+ global_scope->EnsureFetcher());
case ModuleScriptCustomFetchType::kWorkerConstructor:
- return new WorkerModuleScriptFetcher(global_scope);
+ return MakeGarbageCollected<WorkerModuleScriptFetcher>(global_scope);
case ModuleScriptCustomFetchType::kWorkletAddModule:
break;
+ case ModuleScriptCustomFetchType::kInstalledServiceWorker:
+ return new InstalledServiceWorkerModuleScriptFetcher(global_scope);
}
NOTREACHED();
return nullptr;
diff --git a/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.h b/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.h
index 4a6f361064b..3d5c5ea6b33 100644
--- a/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.h
+++ b/chromium/third_party/blink/renderer/core/script/worker_modulator_impl.h
@@ -19,13 +19,13 @@ class WorkerModulatorImpl final : public ModulatorImplBase {
public:
static ModulatorImplBase* Create(ScriptState*);
+ explicit WorkerModulatorImpl(ScriptState*);
+
// Implements ModulatorImplBase.
ModuleScriptFetcher* CreateModuleScriptFetcher(
ModuleScriptCustomFetchType) override;
private:
- explicit WorkerModulatorImpl(ScriptState*);
-
// Implements ModulatorImplBase.
bool IsDynamicImportForbidden(String* reason) override;
};
diff --git a/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.cc b/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.cc
index bc678d809b6..cee9449e2a5 100644
--- a/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.cc
+++ b/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.cc
@@ -10,7 +10,7 @@
namespace blink {
ModulatorImplBase* WorkletModulatorImpl::Create(ScriptState* script_state) {
- return new WorkletModulatorImpl(script_state);
+ return MakeGarbageCollected<WorkletModulatorImpl>(script_state);
}
WorkletModulatorImpl::WorkletModulatorImpl(ScriptState* script_state)
@@ -20,9 +20,9 @@ ModuleScriptFetcher* WorkletModulatorImpl::CreateModuleScriptFetcher(
ModuleScriptCustomFetchType custom_fetch_type) {
DCHECK_EQ(ModuleScriptCustomFetchType::kWorkletAddModule, custom_fetch_type);
WorkletGlobalScope* global_scope =
- ToWorkletGlobalScope(GetExecutionContext());
- return new WorkletModuleScriptFetcher(global_scope->EnsureFetcher(),
- global_scope->GetModuleResponsesMap());
+ To<WorkletGlobalScope>(GetExecutionContext());
+ return MakeGarbageCollected<WorkletModuleScriptFetcher>(
+ global_scope->EnsureFetcher(), global_scope->GetModuleResponsesMap());
}
bool WorkletModulatorImpl::IsDynamicImportForbidden(String* reason) {
diff --git a/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.h b/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.h
index de313d80988..3996eafaae6 100644
--- a/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.h
+++ b/chromium/third_party/blink/renderer/core/script/worklet_modulator_impl.h
@@ -21,13 +21,13 @@ class WorkletModulatorImpl final : public ModulatorImplBase {
public:
static ModulatorImplBase* Create(ScriptState*);
+ explicit WorkletModulatorImpl(ScriptState*);
+
// Implements ModulatorImplBase.
ModuleScriptFetcher* CreateModuleScriptFetcher(
ModuleScriptCustomFetchType) override;
private:
- explicit WorkletModulatorImpl(ScriptState*);
-
// Implements ModulatorImplBase.
bool IsDynamicImportForbidden(String* reason) override;
};
diff --git a/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.cc b/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.cc
index d1e2c9a0aef..4b13772c642 100644
--- a/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.cc
+++ b/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.cc
@@ -13,10 +13,10 @@
namespace blink {
// Spec links:
-// [Parsing]
-// https://html.spec.whatwg.org/multipage/xhtml.html#parsing-xhtml-documents
-// [Prepare]
-// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
+// <specdef label="Parsing"
+// href="https://html.spec.whatwg.org/multipage/xhtml.html#parsing-xhtml-documents">
+// <specdef label="Prepare"
+// href="https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script">
XMLParserScriptRunner::XMLParserScriptRunner(XMLParserScriptRunnerHost* host)
: host_(host) {}
@@ -46,17 +46,18 @@ void XMLParserScriptRunner::PendingScriptFinished(
pending_script->StopWatchingForLoad();
- CHECK_EQ(pending_script->GetScriptType(), ScriptType::kClassic);
+ CHECK_EQ(pending_script->GetScriptType(), mojom::ScriptType::kClassic);
- // [Parsing] 4. Execute the pending parsing-blocking script. [spec text]
+ // <spec label="Parsing" step="4">Execute the pending parsing-blocking
+ // script.</spec>
pending_script->ExecuteScriptBlock(NullURL());
- // [Parsing] 5. There is no longer a pending parsing-blocking script. [spec
- // text]
+ // <spec label="Parsing" step="5">There is no longer a pending
+ // parsing-blocking script.</spec>
DCHECK(!parser_blocking_script_);
- // [Parsing] 3. Unblock this instance of the XML parser, such that tasks that
- // invoke it can again be run. [spec text]
+ // <spec label="Parsing" step="3">Unblock this instance of the XML parser,
+ // such that tasks that invoke it can again be run.</spec>
host_->NotifyScriptExecuted();
}
@@ -75,7 +76,7 @@ void XMLParserScriptRunner::ProcessScriptElement(
bool success = script_loader->PrepareScript(
script_start_position, ScriptLoader::kAllowLegacyTypeInTypeAttribute);
- if (script_loader->GetScriptType() != ScriptType::kClassic) {
+ if (script_loader->GetScriptType() != mojom::ScriptType::kClassic) {
// XMLDocumentParser does not support a module script, and thus ignores it.
success = false;
document.AddConsoleMessage(
@@ -90,10 +91,12 @@ void XMLParserScriptRunner::ProcessScriptElement(
// [Parsing] If this causes there to be a pending parsing-blocking script,
// then the user agent must run the following steps: [spec text]
if (script_loader->ReadyToBeParserExecuted()) {
- // [Prepare] 5th Clause, Step 24.
+ // <spec label="Prepare" step="26.E">... The parser will handle executing
+ // the script.</spec>
+ //
+ // <spec label="Parsing" step="4">Execute the pending parsing-blocking
+ // script.</spec>
//
- // [Parsing] 4. Execute the pending parsing-blocking script. [spec text]
-
// TODO(hiroshige): XMLParserScriptRunner doesn't check style sheet that
// is blocking scripts and thus the script is executed immediately here,
// and thus Steps 1-3 are skipped.
@@ -101,7 +104,7 @@ void XMLParserScriptRunner::ProcessScriptElement(
->TakePendingScript(ScriptSchedulingType::kParserBlockingInline)
->ExecuteScriptBlock(document.Url());
} else if (script_loader->WillBeParserExecuted()) {
- // <spec label="Prepare" step="25.B">... The element is the pending
+ // <spec label="Prepare" step="26.B">... The element is the pending
// parsing-blocking script of the Document of the parser that created the
// element. (There can only be one such script per Document at a time.)
// ...</spec>
@@ -109,15 +112,16 @@ void XMLParserScriptRunner::ProcessScriptElement(
script_loader->TakePendingScript(ScriptSchedulingType::kParserBlocking);
parser_blocking_script_->MarkParserBlockingLoadStartTime();
- // [Parsing] 1. Block this instance of the XML parser, such that the event
- // loop will not run tasks that invoke it. [spec text]
+ // <spec label="Parsing" step="1">Block this instance of the XML parser,
+ // such that the event loop will not run tasks that invoke it.</spec>
//
// This is done in XMLDocumentParser::EndElementNs().
- // [Parsing] 2. Spin the event loop until the parser's Document has no style
- // sheet that is blocking scripts and the pending parsing-blocking script's
- // "ready to be parser-executed" flag is set. [spec text]
- //
+ // <spec label="Parsing" step="2">Spin the event loop until the parser's
+ // Document has no style sheet that is blocking scripts and the pending
+ // parsing-blocking script's "ready to be parser-executed" flag is
+ // set.</spec>
+
// TODO(hiroshige): XMLParserScriptRunner doesn't check style sheet that
// is blocking scripts.
parser_blocking_script_->WatchForLoad(this);
diff --git a/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.h b/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.h
index ec6397a0247..69db30b585b 100644
--- a/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.h
+++ b/chromium/third_party/blink/renderer/core/script/xml_parser_script_runner.h
@@ -25,8 +25,10 @@ class XMLParserScriptRunner final
public:
static XMLParserScriptRunner* Create(XMLParserScriptRunnerHost* host) {
- return new XMLParserScriptRunner(host);
+ return MakeGarbageCollected<XMLParserScriptRunner>(host);
}
+
+ explicit XMLParserScriptRunner(XMLParserScriptRunnerHost*);
~XMLParserScriptRunner() override;
bool HasParserBlockingScript() const { return parser_blocking_script_; }
@@ -37,8 +39,6 @@ class XMLParserScriptRunner final
void Trace(Visitor*) override;
private:
- explicit XMLParserScriptRunner(XMLParserScriptRunnerHost*);
-
// from PendingScriptClient
void PendingScriptFinished(PendingScript*) override;
diff --git a/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.cc b/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.cc
index 76be7aa30e6..f57de0ae531 100644
--- a/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.cc
@@ -134,7 +134,8 @@ void ProgrammaticScrollAnimator::UpdateCompositorAnimations() {
!is_sequenced_scroll_) {
std::unique_ptr<CompositorKeyframeModel> animation =
CompositorKeyframeModel::Create(
- *animation_curve_, CompositorTargetProperty::SCROLL_OFFSET, 0, 0);
+ *animation_curve_, compositor_target_property::SCROLL_OFFSET, 0,
+ 0);
int animation_id = animation->Id();
int animation_group_id = animation->Group();
diff --git a/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h b/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h
index f85c44383f0..4e4b708f2a2 100644
--- a/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h
+++ b/chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h
@@ -28,9 +28,10 @@ class ProgrammaticScrollAnimator : public ScrollAnimatorCompositorCoordinator {
public:
static ProgrammaticScrollAnimator* Create(ScrollableArea* scrollable_area) {
- return new ProgrammaticScrollAnimator(scrollable_area);
+ return MakeGarbageCollected<ProgrammaticScrollAnimator>(scrollable_area);
}
+ explicit ProgrammaticScrollAnimator(ScrollableArea*);
~ProgrammaticScrollAnimator() override;
void ScrollToOffsetWithoutAnimation(const ScrollOffset&,
@@ -54,8 +55,6 @@ class ProgrammaticScrollAnimator : public ScrollAnimatorCompositorCoordinator {
void Trace(blink::Visitor*) override;
private:
- explicit ProgrammaticScrollAnimator(ScrollableArea*);
-
void NotifyOffsetChanged(const ScrollOffset&);
void AnimationFinished();
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc b/chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc
index f4ed1cbd064..45f9cffbb37 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc
@@ -57,7 +57,7 @@ ScrollAnimatorBase* ScrollAnimatorBase::Create(
ScrollableArea* scrollable_area) {
if (scrollable_area && scrollable_area->ScrollAnimatorEnabled())
return new ScrollAnimator(scrollable_area);
- return new ScrollAnimatorBase(scrollable_area);
+ return MakeGarbageCollected<ScrollAnimatorBase>(scrollable_area);
}
ScrollAnimator::ScrollAnimator(ScrollableArea* scrollable_area,
@@ -258,7 +258,7 @@ bool ScrollAnimator::SendAnimationToCompositor() {
std::unique_ptr<CompositorKeyframeModel> animation =
CompositorKeyframeModel::Create(
- *animation_curve_, CompositorTargetProperty::SCROLL_OFFSET, 0, 0);
+ *animation_curve_, compositor_target_property::SCROLL_OFFSET, 0, 0);
// Being here means that either there is an animation that needs
// to be sent to the compositor, or an animation that needs to
// be updated (a new scroll event before the previous animation
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.h b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.h
index 48470ab6789..4772d872f8b 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.h
@@ -55,6 +55,7 @@ class CORE_EXPORT ScrollAnimatorBase
public:
static ScrollAnimatorBase* Create(ScrollableArea*);
+ explicit ScrollAnimatorBase(ScrollableArea*);
~ScrollAnimatorBase() override;
virtual void Dispose() {}
@@ -114,8 +115,6 @@ class CORE_EXPORT ScrollAnimatorBase
void Trace(blink::Visitor*) override;
protected:
- explicit ScrollAnimatorBase(ScrollableArea*);
-
virtual void NotifyOffsetChanged();
Member<ScrollableArea> scrollable_area_;
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.cc b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.cc
index c462ba8da6b..26f4275454f 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.cc
@@ -284,7 +284,8 @@ void ScrollAnimatorCompositorCoordinator::UpdateCompositorAnimations() {
void ScrollAnimatorCompositorCoordinator::ScrollOffsetChanged(
const ScrollOffset& offset,
ScrollType scroll_type) {
- GetScrollableArea()->ScrollOffsetChanged(offset, scroll_type);
+ ScrollOffset clamped_offset = GetScrollableArea()->ClampScrollOffset(offset);
+ GetScrollableArea()->ScrollOffsetChanged(clamped_offset, scroll_type);
}
void ScrollAnimatorCompositorCoordinator::AdjustAnimationAndSetScrollOffset(
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.h b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.h
index de89825379d..199a27e8ff6 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.h
@@ -33,8 +33,8 @@
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/retain_ptr.h"
OBJC_CLASS BlinkScrollAnimationHelperDelegate;
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm
index 29f3f3e7411..d330dd85b71 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm
@@ -298,10 +298,7 @@ class BlinkScrollbarPartAnimationTimer {
public:
BlinkScrollbarPartAnimationTimer(BlinkScrollbarPartAnimation* animation,
CFTimeInterval duration)
- : timer_(Platform::Current()
- ->MainThread()
- ->Scheduler()
- ->CompositorTaskRunner(),
+ : timer_(ThreadScheduler::Current()->CompositorTaskRunner(),
this,
&BlinkScrollbarPartAnimationTimer::TimerFired),
start_time_(0.0),
@@ -693,10 +690,7 @@ ScrollAnimatorBase* ScrollAnimatorBase::Create(
ScrollAnimatorMac::ScrollAnimatorMac(blink::ScrollableArea* scrollable_area)
: ScrollAnimatorBase(scrollable_area),
- task_runner_(Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->CompositorTaskRunner()),
+ task_runner_(ThreadScheduler::Current()->CompositorTaskRunner()),
have_scrolled_since_page_load_(false),
needs_scroller_style_update_(false) {
scroll_animation_helper_delegate_.AdoptNS(
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_customization.cc b/chromium/third_party/blink/renderer/core/scroll/scroll_customization.cc
index 6199fc2f2c9..26a47e2abc2 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_customization.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_customization.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_customization.h"
namespace blink {
-namespace ScrollCustomization {
+namespace scroll_customization {
ScrollDirection GetScrollDirectionFromDeltas(double delta_x, double delta_y) {
// TODO(ekaramad, tdresser): Find out the right value for kEpsilon here (see
@@ -31,5 +31,5 @@ ScrollDirection GetScrollDirectionFromDeltas(double delta_x, double delta_y) {
return direction;
}
-} // namespace ScrollCustomization
+} // namespace scroll_customization
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_customization.h b/chromium/third_party/blink/renderer/core/scroll/scroll_customization.h
index 224ce4263df..26caa5edcbc 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_customization.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_customization.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/core_export.h"
namespace blink {
-namespace ScrollCustomization {
+namespace scroll_customization {
using ScrollDirection = uint8_t;
constexpr ScrollDirection kScrollDirectionNone = 0;
@@ -27,7 +27,7 @@ constexpr ScrollDirection kScrollDirectionAuto =
CORE_EXPORT ScrollDirection GetScrollDirectionFromDeltas(double delta_x,
double delta_y);
-} // namespace ScrollCustomization
+} // namespace scroll_customization
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SCROLL_SCROLL_CUSTOMIZATION_H_
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc b/chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc
index 64c22032262..f94fd517bca 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc
@@ -627,8 +627,8 @@ void ScrollableArea::ShowOverlayScrollbars() {
if (!fade_overlay_scrollbars_timer_) {
fade_overlay_scrollbars_timer_.reset(new TaskRunnerTimer<ScrollableArea>(
- Platform::Current()->MainThread()->Scheduler()->CompositorTaskRunner(),
- this, &ScrollableArea::FadeOverlayScrollbarsTimerFired));
+ ThreadScheduler::Current()->CompositorTaskRunner(), this,
+ &ScrollableArea::FadeOverlayScrollbarsTimerFired));
}
if (!scrollbar_captured_ && !mouse_over_scrollbar_) {
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollable_area.h b/chromium/third_party/blink/renderer/core/scroll/scrollable_area.h
index 2734d4bf383..d21fbe97de6 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollable_area.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollable_area.h
@@ -398,6 +398,8 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
virtual ScrollbarTheme& GetPageScrollbarTheme() const = 0;
+ float ScrollStep(ScrollGranularity, ScrollbarOrientation) const;
+
protected:
// Deduces the ScrollBehavior based on the element style and the parameter set
// by programmatic scroll into either instant or smooth scroll.
@@ -409,7 +411,6 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
ScrollbarOrientation ScrollbarOrientationFromDirection(
ScrollDirectionPhysical) const;
- float ScrollStep(ScrollGranularity, ScrollbarOrientation) const;
// Needed to let the animators call scrollOffsetChanged.
friend class ScrollAnimatorCompositorCoordinator;
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc b/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc
index 2f413654d7b..bc38b0a3b53 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc
@@ -162,7 +162,7 @@ void Scrollbar::SetProportion(int visible_size, int total_size) {
void Scrollbar::Paint(GraphicsContext& context,
const CullRect& cull_rect) const {
- if (!cull_rect.IntersectsCullRect(FrameRect()))
+ if (!cull_rect.Intersects(FrameRect()))
return;
GetTheme().Paint(*this, context, cull_rect);
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar.h
index e9e4737f7ca..6a1ca7c0d0a 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar.h
@@ -52,7 +52,8 @@ class CORE_EXPORT Scrollbar : public GarbageCollectedFinalized<Scrollbar>,
ScrollbarOrientation orientation,
ScrollbarControlSize size,
ChromeClient* chrome_client) {
- return new Scrollbar(scrollable_area, orientation, size, chrome_client);
+ return MakeGarbageCollected<Scrollbar>(scrollable_area, orientation, size,
+ chrome_client);
}
// Theme object ownership remains with the caller and it must outlive the
@@ -61,9 +62,15 @@ class CORE_EXPORT Scrollbar : public GarbageCollectedFinalized<Scrollbar>,
ScrollbarOrientation orientation,
ScrollbarControlSize size,
ScrollbarTheme* theme) {
- return new Scrollbar(scrollable_area, orientation, size, nullptr, theme);
+ return MakeGarbageCollected<Scrollbar>(scrollable_area, orientation, size,
+ nullptr, theme);
}
+ Scrollbar(ScrollableArea*,
+ ScrollbarOrientation,
+ ScrollbarControlSize,
+ ChromeClient* = nullptr,
+ ScrollbarTheme* = nullptr);
~Scrollbar() override;
int X() const { return frame_rect_.X(); }
@@ -197,12 +204,6 @@ class CORE_EXPORT Scrollbar : public GarbageCollectedFinalized<Scrollbar>,
virtual void Trace(blink::Visitor*);
protected:
- Scrollbar(ScrollableArea*,
- ScrollbarOrientation,
- ScrollbarControlSize,
- ChromeClient* = nullptr,
- ScrollbarTheme* = nullptr);
-
void AutoscrollTimerFired(TimerBase*);
void StartTimerIfNeeded(TimeDelta delay);
void StopTimerIfNeeded();
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_test_suite.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar_test_suite.h
index 0745314ac33..60b67639503 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_test_suite.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_test_suite.h
@@ -39,7 +39,9 @@ class MockScrollableArea : public GarbageCollectedFinalized<MockScrollableArea>,
USING_GARBAGE_COLLECTED_MIXIN(MockScrollableArea);
public:
- static MockScrollableArea* Create() { return new MockScrollableArea(); }
+ static MockScrollableArea* Create() {
+ return MakeGarbageCollected<MockScrollableArea>();
+ }
static MockScrollableArea* Create(const ScrollOffset& maximum_scroll_offset) {
MockScrollableArea* mock = Create();
@@ -47,6 +49,13 @@ class MockScrollableArea : public GarbageCollectedFinalized<MockScrollableArea>,
return mock;
}
+ explicit MockScrollableArea()
+ : maximum_scroll_offset_(ScrollOffset(0, 100)),
+ chrome_client_(MakeGarbageCollected<MockPlatformChromeClient>()) {}
+ explicit MockScrollableArea(const ScrollOffset& offset)
+ : maximum_scroll_offset_(offset),
+ chrome_client_(MakeGarbageCollected<MockPlatformChromeClient>()) {}
+
MOCK_CONST_METHOD0(VisualRectForScrollbarParts, LayoutRect());
MOCK_CONST_METHOD0(IsActive, bool());
MOCK_CONST_METHOD0(IsThrottled, bool());
@@ -109,14 +118,6 @@ class MockScrollableArea : public GarbageCollectedFinalized<MockScrollableArea>,
ScrollableArea::Trace(visitor);
}
- protected:
- explicit MockScrollableArea()
- : maximum_scroll_offset_(ScrollOffset(0, 100)),
- chrome_client_(new MockPlatformChromeClient()) {}
- explicit MockScrollableArea(const ScrollOffset& offset)
- : maximum_scroll_offset_(offset),
- chrome_client_(new MockPlatformChromeClient()) {}
-
private:
void SetMaximumScrollOffset(const ScrollOffset& maximum_scroll_offset) {
maximum_scroll_offset_ = maximum_scroll_offset;
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
index 80bc7e39309..008b4bfdda5 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
@@ -53,7 +53,7 @@ bool ScrollbarTheme::g_mock_scrollbars_enabled_ = false;
static inline bool ShouldPaintScrollbarPart(const IntRect& part_rect,
const CullRect& cull_rect) {
- return (!part_rect.IsEmpty()) || cull_rect.IntersectsCullRect(part_rect);
+ return (!part_rect.IsEmpty()) || cull_rect.Intersects(part_rect);
}
bool ScrollbarTheme::Paint(const Scrollbar& scrollbar,
@@ -291,8 +291,8 @@ int ScrollbarTheme::ThumbLength(const Scrollbar& scrollbar) {
int length = round(proportion * track_len);
length = std::max(length, MinimumThumbLength(scrollbar));
if (length > track_len)
- length = 0; // Once the thumb is below the track length, it just goes away
- // (to make more room for the track).
+ length = track_len; // Once the thumb is below the track length,
+ // it fills the track.
return length;
}
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc
index 0d3b2ee7430..d7f792f5117 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_aura.cc
@@ -41,15 +41,15 @@
#include "third_party/blink/renderer/platform/geometry/int_rect_outsets.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
namespace {
static bool UseMockTheme() {
- return LayoutTestSupport::IsRunningLayoutTest();
+ return WebTestSupport::IsRunningWebTest();
}
// Contains a flag indicating whether WebThemeEngine should paint a UI widget
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h
index a67a4e59bcc..16ff4a8c287 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h
@@ -30,7 +30,6 @@
#include "third_party/blink/renderer/core/scroll/ns_scroller_imp_details.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
-#include "third_party/blink/renderer/platform/scroll/web_scrollbar_theme_client.h"
typedef id ScrollbarPainter;
@@ -38,8 +37,7 @@ namespace blink {
class Pattern;
-class PLATFORM_EXPORT ScrollbarThemeMac : public ScrollbarTheme,
- public WebScrollbarThemeClient {
+class PLATFORM_EXPORT ScrollbarThemeMac : public ScrollbarTheme {
public:
ScrollbarThemeMac();
~ScrollbarThemeMac() override;
@@ -94,10 +92,15 @@ class PLATFORM_EXPORT ScrollbarThemeMac : public ScrollbarTheme,
float ThumbOpacity(const Scrollbar&) const override;
- void PreferencesChanged() override;
-
static NSScrollerStyle RecommendedScrollerStyle();
- static void SetJumpOnTrackClick(bool);
+
+ // See WebScrollbarTheme for parameters description.
+ static void UpdateScrollbarsWithNSDefaults(
+ float initial_button_delay,
+ float autoscroll_button_delay,
+ NSScrollerStyle preferred_scroller_style,
+ bool redraw,
+ bool jump_on_track_click);
protected:
int MaxOverlapBetweenPages() override { return 40; }
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm
index 7ec35a7f353..9aac70e0d61 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm
@@ -104,10 +104,16 @@
namespace blink {
+static float s_initial_button_delay = 0.5f;
+static float s_autoscroll_button_delay = 0.05f;
+static NSScrollerStyle s_preferred_scroller_style = NSScrollerStyleLegacy;
+static bool s_jump_on_track_click = false;
+
typedef HeapHashSet<WeakMember<Scrollbar>> ScrollbarSet;
static ScrollbarSet& GetScrollbarSet() {
- DEFINE_STATIC_LOCAL(Persistent<ScrollbarSet>, set, (new ScrollbarSet));
+ DEFINE_STATIC_LOCAL(Persistent<ScrollbarSet>, set,
+ (MakeGarbageCollected<ScrollbarSet>()));
return *set;
}
@@ -116,7 +122,7 @@ typedef HeapHashMap<WeakMember<Scrollbar>, RetainPtr<BlinkScrollbarObserver>>
static ScrollbarPainterMap& GetScrollbarPainterMap() {
DEFINE_STATIC_LOCAL(Persistent<ScrollbarPainterMap>, map,
- (new ScrollbarPainterMap));
+ (MakeGarbageCollected<ScrollbarPainterMap>()));
return *map;
}
@@ -130,7 +136,6 @@ static bool SupportsExpandedScrollbars() {
}
ScrollbarThemeMac::ScrollbarThemeMac() {
- WebScrollbarTheme::RegisterClient(*this);
}
ScrollbarTheme& ScrollbarTheme::NativeTheme() {
@@ -151,19 +156,18 @@ bool ScrollbarThemeMac::ShouldCenterOnThumb(const Scrollbar& scrollbar,
const WebMouseEvent& event) {
bool alt_key_pressed = event.GetModifiers() & WebInputEvent::kAltKey;
return (event.button == WebPointerProperties::Button::kLeft) &&
- (WebScrollbarTheme::JumpOnTrackClick() != alt_key_pressed);
+ (s_jump_on_track_click != alt_key_pressed);
}
ScrollbarThemeMac::~ScrollbarThemeMac() {
- WebScrollbarTheme::UnregisterClient(*this);
}
TimeDelta ScrollbarThemeMac::InitialAutoscrollTimerDelay() {
- return TimeDelta::FromSecondsD(WebScrollbarTheme::InitialButtonDelay());
+ return TimeDelta::FromSecondsD(s_initial_button_delay);
}
TimeDelta ScrollbarThemeMac::AutoscrollTimerDelay() {
- return TimeDelta::FromSecondsD(WebScrollbarTheme::AutoscrollButtonDelay());
+ return TimeDelta::FromSecondsD(s_autoscroll_button_delay);
}
bool ScrollbarThemeMac::ShouldDragDocumentInsteadOfThumb(
@@ -412,10 +416,22 @@ float ScrollbarThemeMac::ThumbOpacity(const Scrollbar& scrollbar) const {
return [scrollbar_painter knobAlpha];
}
-void ScrollbarThemeMac::PreferencesChanged() {
- for (const auto& scrollbar : GetScrollbarSet()) {
- scrollbar->StyleChanged();
- scrollbar->SetNeedsPaintInvalidation(kAllParts);
+// static
+void ScrollbarThemeMac::UpdateScrollbarsWithNSDefaults(
+ float initial_button_delay,
+ float autoscroll_button_delay,
+ NSScrollerStyle preferred_scroller_style,
+ bool redraw,
+ bool jump_on_track_click) {
+ s_initial_button_delay = initial_button_delay;
+ s_autoscroll_button_delay = autoscroll_button_delay;
+ s_preferred_scroller_style = preferred_scroller_style;
+ s_jump_on_track_click = jump_on_track_click;
+ if (redraw) {
+ for (const auto& scrollbar : GetScrollbarSet()) {
+ scrollbar->StyleChanged();
+ scrollbar->SetNeedsPaintInvalidation(kAllParts);
+ }
}
}
@@ -423,8 +439,7 @@ void ScrollbarThemeMac::PreferencesChanged() {
NSScrollerStyle ScrollbarThemeMac::RecommendedScrollerStyle() {
if (RuntimeEnabledFeatures::OverlayScrollbarsEnabled())
return NSScrollerStyleOverlay;
- return static_cast<NSScrollerStyle>(
- WebScrollbarTheme::PreferredScrollerStyle());
+ return s_preferred_scroller_style;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.cc b/chromium/third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.cc
index 0ed920fd269..4f56b7b7155 100644
--- a/chromium/third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.cc
@@ -16,8 +16,10 @@ void SequencedScroll::Trace(blink::Visitor* visitor) {
void SmoothScrollSequencer::QueueAnimation(ScrollableArea* scrollable,
ScrollOffset offset,
ScrollBehavior behavior) {
- if (scrollable->ClampScrollOffset(offset) != scrollable->GetScrollOffset())
- queue_.push_back(new SequencedScroll(scrollable, offset, behavior));
+ if (scrollable->ClampScrollOffset(offset) != scrollable->GetScrollOffset()) {
+ queue_.push_back(
+ MakeGarbageCollected<SequencedScroll>(scrollable, offset, behavior));
+ }
}
void SmoothScrollSequencer::RunQueuedAnimations() {
diff --git a/chromium/third_party/blink/renderer/core/scroll/web_scrollbar_theme.mm b/chromium/third_party/blink/renderer/core/scroll/web_scrollbar_theme.mm
index 86a570a40d9..55530f53f43 100644
--- a/chromium/third_party/blink/renderer/core/scroll/web_scrollbar_theme.mm
+++ b/chromium/third_party/blink/renderer/core/scroll/web_scrollbar_theme.mm
@@ -44,58 +44,16 @@ static_assert(static_cast<NSScrollerStyle>(kScrollerStyleOverlay) ==
NSScrollerStyleOverlay,
"ScrollerStyleOverlay must match NSScrollerStyleOverlay");
-typedef WTF::HashSet<WebScrollbarThemeClient*> ClientSet;
-
-static ClientSet& GetClientSet() {
- DEFINE_STATIC_LOCAL(ClientSet, set, ());
- return set;
-}
-
-static float s_initial_button_delay = 0.5f;
-static float s_autoscroll_button_delay = 0.05f;
-static ScrollerStyle s_preferred_scroller_style = kScrollerStyleLegacy;
-static bool s_jump_on_track_click = false;
-
void WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
float initial_button_delay,
float autoscroll_button_delay,
ScrollerStyle preferred_scroller_style,
bool redraw,
bool jump_on_track_click) {
- s_initial_button_delay = initial_button_delay;
- s_autoscroll_button_delay = autoscroll_button_delay;
- s_preferred_scroller_style = preferred_scroller_style;
- s_jump_on_track_click = jump_on_track_click;
-
- if (redraw && !GetClientSet().IsEmpty()) {
- for (auto* client : GetClientSet()) {
- client->PreferencesChanged();
- }
- }
-}
-
-float WebScrollbarTheme::InitialButtonDelay() {
- return s_initial_button_delay;
-}
-
-float WebScrollbarTheme::AutoscrollButtonDelay() {
- return s_autoscroll_button_delay;
-}
-
-ScrollerStyle WebScrollbarTheme::PreferredScrollerStyle() {
- return s_preferred_scroller_style;
-}
-
-bool WebScrollbarTheme::JumpOnTrackClick() {
- return s_jump_on_track_click;
-}
-
-void WebScrollbarTheme::RegisterClient(WebScrollbarThemeClient& client) {
- GetClientSet().insert(&client);
-}
-
-void WebScrollbarTheme::UnregisterClient(WebScrollbarThemeClient& client) {
- GetClientSet().erase(&client);
+ ScrollbarThemeMac::UpdateScrollbarsWithNSDefaults(
+ initial_button_delay, autoscroll_button_delay,
+ static_cast<NSScrollerStyle>(preferred_scroller_style), redraw,
+ jump_on_track_click);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/BUILD.gn b/chromium/third_party/blink/renderer/core/streams/BUILD.gn
index e4067c8e78f..4ddb512fda8 100644
--- a/chromium/third_party/blink/renderer/core/streams/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/streams/BUILD.gn
@@ -6,6 +6,8 @@ import("//third_party/blink/renderer/core/core.gni")
blink_core_sources("streams") {
sources = [
+ "readable_stream.cc",
+ "readable_stream.h",
"readable_stream_default_controller_wrapper.h",
"readable_stream_operations.cc",
"readable_stream_operations.h",
@@ -18,5 +20,7 @@ blink_core_sources("streams") {
"transform_stream_transformer.h",
"underlying_source_base.cc",
"underlying_source_base.h",
+ "writable_stream.cc",
+ "writable_stream.h",
]
}
diff --git a/chromium/third_party/blink/renderer/core/streams/CommonOperations.js b/chromium/third_party/blink/renderer/core/streams/CommonOperations.js
index f35f6d13ff6..266850799a4 100644
--- a/chromium/third_party/blink/renderer/core/streams/CommonOperations.js
+++ b/chromium/third_party/blink/renderer/core/streams/CommonOperations.js
@@ -23,8 +23,17 @@
const RangeError = global.RangeError;
const TypeError = global.TypeError;
+ const TypeError_prototype = TypeError.prototype;
const hasOwnProperty = v8.uncurryThis(global.Object.hasOwnProperty);
+ const getPrototypeOf = global.Object.getPrototypeOf.bind(global.Object);
+ const getOwnPropertyDescriptor =
+ global.Object.getOwnPropertyDescriptor.bind(global.Object);
+
+ const thenPromise = v8.uncurryThis(Promise.prototype.then);
+
+ const JSON_parse = global.JSON.parse.bind(global.JSON);
+ const JSON_stringify = global.JSON.stringify.bind(global.JSON);
function hasOwnPropertyNoThrow(x, property) {
// The cast of |x| to Boolean will eliminate undefined and null, which would
@@ -288,6 +297,252 @@
}
}
+ // Functions for transferable streams. See design doc
+ // https://docs.google.com/document/d/1_KuZzg5c3pncLJPFa8SuVm23AP4tft6mzPCL5at3I9M/edit
+
+ const kPull = 1;
+ const kCancel = 2;
+ const kChunk = 3;
+ const kClose = 4;
+ const kAbort = 5;
+ const kError = 6;
+
+ function isATypeError(object) {
+ // There doesn't appear to be a 100% reliable way to identify a TypeError
+ // from JS.
+ return getPrototypeOf(object) === TypeError_prototype;
+ }
+
+ function isADOMException(object) {
+ try {
+ callFunction(binding.DOMException_name_get, object);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ // We'd like to able to transfer TypeError exceptions, but we can't, so we
+ // hack around it. packReason() is guaranteed not to throw and the object
+ // produced is guaranteed to be serializable by postMessage().
+ function packReason(reason) {
+ switch (typeof reason) {
+ case 'string':
+ case 'number':
+ return {encoder: 'json', string: JSON_stringify(reason)};
+
+ case 'object':
+ try {
+ if (isATypeError(reason)) {
+ // "message" on TypeError is a normal property, meaning that if it
+ // is set, it is set on the object itself. We can take advantage of
+ // this to avoid executing user JavaScript in the case when the
+ // TypeError was generated internally.
+ let message;
+ const descriptor = getOwnPropertyDescriptor(reason, 'message');
+ if (descriptor) {
+ message = descriptor.value;
+ if (typeof message !== 'string') {
+ message = undefined;
+ }
+ }
+ return {encoder: 'typeerror', string: message};
+ }
+
+ if (isADOMException(reason)) {
+ const message =
+ callFunction(binding.DOMException_message_get, reason);
+ const name = callFunction(binding.DOMException_name_get, reason);
+ return {
+ encoder: 'domexception',
+ string: JSON_stringify({message, name})
+ };
+ }
+
+ // JSON_stringify() is lossy, but it will serialise things that
+ // postMessage() won't.
+ return {encoder: 'json', string: JSON_stringify(reason)};
+ } catch (e) {
+ return {encoder: 'typeerror', string: 'Cannot transfer message'};
+ }
+
+ default:
+ return {encoder: 'undefined', string: undefined};
+ }
+ }
+
+ function unpackReason(packedReason) {
+ const {encoder, string} = packedReason;
+ switch (encoder) {
+ case 'json':
+ return JSON_parse(string);
+
+ case 'typeerror':
+ return new TypeError(string);
+
+ case 'domexception':
+ const {message, name} = JSON_parse(string);
+ return new binding.DOMException(message, name);
+
+ case 'undefined':
+ return undefined;
+ }
+ }
+
+ function CreateCrossRealmTransformWritable(port) {
+ let backpressurePromise = v8.createPromise();
+
+ callFunction(binding.EventTarget_addEventListener, port, 'message', evt => {
+ const {type, value} = callFunction(binding.MessageEvent_data_get, evt);
+ // assert(type === kPull || type === kCancel || type === kError);
+ switch (type) {
+ case kPull:
+ // assert(backPressurePromise !== undefined);
+ resolvePromise(backpressurePromise);
+ backpressurePromise = undefined;
+ break;
+
+ case kCancel:
+ case kError:
+ binding.WritableStreamDefaultControllerErrorIfNeeded(
+ controller, unpackReason(value));
+ if (backpressurePromise !== undefined) {
+ resolvePromise(backpressurePromise);
+ backpressurePromise = undefined;
+ }
+ break;
+ }
+ });
+
+ callFunction(
+ binding.EventTarget_addEventListener, port, 'messageerror', () => {
+ const error = new binding.DOMException('chunk could not be cloned',
+ 'DataCloneError');
+ callFunction(binding.MessagePort_postMessage, port,
+ {type: kError, value: packReason(error)});
+ callFunction(binding.MessagePort_close, port);
+ binding.WritableStreamDefaultControllerErrorIfNeeded(controller,
+ error);
+ });
+
+ callFunction(binding.MessagePort_start, port);
+
+ function doWrite(chunk) {
+ backpressurePromise = v8.createPromise();
+ try {
+ callFunction(
+ binding.MessagePort_postMessage, port,
+ {type: kChunk, value: chunk});
+ } catch (e) {
+ callFunction(
+ binding.MessagePort_postMessage, port,
+ {type: kError, value: packReason(e)});
+ callFunction(binding.MessagePort_close, port);
+ throw e;
+ }
+ }
+
+ const stream = binding.CreateWritableStream(
+ () => undefined,
+ chunk => {
+ if (!backpressurePromise) {
+ return PromiseCall1(doWrite, null, chunk);
+ }
+ return thenPromise(backpressurePromise, () => doWrite(chunk));
+ },
+ () => {
+ callFunction(
+ binding.MessagePort_postMessage, port,
+ {type: kClose, value: undefined});
+ callFunction(binding.MessagePort_close, port);
+ return Promise_resolve();
+ },
+ reason => {
+ callFunction(
+ binding.MessagePort_postMessage, port,
+ {type: kAbort, value: packReason(reason)});
+ callFunction(binding.MessagePort_close, port);
+ return Promise_resolve();
+ });
+
+ const controller = binding.getWritableStreamController(stream);
+ return stream;
+ }
+
+ function CreateCrossRealmTransformReadable(port) {
+ let backpressurePromise = v8.createPromise();
+ let finished = false;
+
+ callFunction(binding.EventTarget_addEventListener, port, 'message', evt => {
+ const {type, value} = callFunction(binding.MessageEvent_data_get, evt);
+ // assert(type === kChunk || type === kClose || type === kAbort ||
+ // type=kError);
+ switch (type) {
+ case kChunk:
+ if (finished) {
+ return;
+ }
+ binding.ReadableStreamDefaultControllerEnqueue(controller, value);
+ resolvePromise(backpressurePromise);
+ backpressurePromise = v8.createPromise();
+ break;
+
+ case kClose:
+ if (finished) {
+ return;
+ }
+ finished = true;
+ binding.ReadableStreamDefaultControllerClose(controller);
+ callFunction(binding.MessagePort_close, port);
+ break;
+
+ case kAbort:
+ case kError:
+ if (finished) {
+ return;
+ }
+ finished = true;
+ binding.ReadableStreamDefaultControllerError(
+ controller, unpackReason(value));
+ callFunction(binding.MessagePort_close, port);
+ break;
+ }
+ });
+
+ callFunction(
+ binding.EventTarget_addEventListener, port, 'messageerror', () => {
+ const error = new binding.DOMException('chunk could not be cloned',
+ 'DataCloneError');
+ callFunction(binding.MessagePort_postMessage, port,
+ {type: kError, value: packReason(error)});
+ callFunction(binding.MessagePort_close, port);
+ binding.ReadableStreamDefaultControllerError(controller, error);
+ });
+
+ callFunction(binding.MessagePort_start, port);
+
+ const stream = binding.CreateReadableStream(
+ () => undefined,
+ () => {
+ callFunction(
+ binding.MessagePort_postMessage, port,
+ {type: kPull, value: undefined});
+ return backpressurePromise;
+ },
+ reason => {
+ finished = true;
+ callFunction(
+ binding.MessagePort_postMessage, port,
+ {type: kCancel, value: packReason(reason)});
+ callFunction(binding.MessagePort_close, port);
+ return Promise_resolve();
+ },
+ /* highWaterMark = */ 0);
+
+ const controller = binding.getReadableStreamController(stream);
+ return stream;
+ }
+
binding.streamOperations = {
_queue,
_queueTotalSize,
@@ -298,6 +553,8 @@
promiseState,
CreateAlgorithmFromUnderlyingMethod,
CreateAlgorithmFromUnderlyingMethodPassingController,
+ CreateCrossRealmTransformWritable,
+ CreateCrossRealmTransformReadable,
DequeueValue,
EnqueueValueWithSize,
PeekQueueValue,
diff --git a/chromium/third_party/blink/renderer/core/streams/CommonStrings.js b/chromium/third_party/blink/renderer/core/streams/CommonStrings.js
index 5caea9a90ce..72395d75113 100644
--- a/chromium/third_party/blink/renderer/core/streams/CommonStrings.js
+++ b/chromium/third_party/blink/renderer/core/streams/CommonStrings.js
@@ -9,6 +9,8 @@
'use strict';
binding.streamErrors = {
+ cannotTransferLockedStream: 'Cannot transfer a locked stream',
+ cannotTransferContext: 'Cannot transfer from this context',
illegalInvocation: 'Illegal invocation',
illegalConstructor: 'Illegal constructor',
invalidType: 'Invalid type is specified',
diff --git a/chromium/third_party/blink/renderer/core/streams/ReadableStream.js b/chromium/third_party/blink/renderer/core/streams/ReadableStream.js
index 159462bf22b..d28d8c076ed 100644
--- a/chromium/third_party/blink/renderer/core/streams/ReadableStream.js
+++ b/chromium/third_party/blink/renderer/core/streams/ReadableStream.js
@@ -35,6 +35,8 @@
const _readableStreamDefaultControllerBits = v8.createPrivateSymbol(
'bit field for [[started]], [[closeRequested]], [[pulling]], ' +
'[[pullAgain]]');
+ const internalReadableStreamSymbol = v8.createPrivateSymbol(
+ 'internal ReadableStream in exposed ReadableStream interface');
// Remove this once C++ code has been updated to use CreateReadableStream.
const _lockNotifyTarget = v8.createPrivateSymbol('[[lockNotifyTarget]]');
const _strategySizeAlgorithm = v8.createPrivateSymbol(
@@ -49,7 +51,6 @@
// it.
const BLINK_LOCK_NOTIFICATIONS = 0b10000;
- const defineProperty = global.Object.defineProperty;
const ObjectCreate = global.Object.create;
const callFunction = v8.uncurryThis(global.Function.prototype.call);
@@ -58,7 +59,6 @@
const TypeError = global.TypeError;
const RangeError = global.RangeError;
- const Boolean = global.Boolean;
const String = global.String;
const Promise = global.Promise;
@@ -77,6 +77,8 @@
CallOrNoop1,
CreateAlgorithmFromUnderlyingMethod,
CreateAlgorithmFromUnderlyingMethodPassingController,
+ CreateCrossRealmTransformReadable,
+ CreateCrossRealmTransformWritable,
DequeueValue,
EnqueueValueWithSize,
MakeSizeAlgorithmFromSizeFunction,
@@ -84,8 +86,6 @@
} = binding.streamOperations;
const streamErrors = binding.streamErrors;
- const errCancelLockedStream =
- 'Cannot cancel a readable stream that is locked to a reader';
const errEnqueueCloseRequestedStream =
'Cannot enqueue a chunk into a readable stream that is closed or ' +
'has been requested to be closed';
@@ -104,10 +104,6 @@
'Cannot enqueue a chunk into an errored readable stream';
const errCloseClosedStream = 'Cannot close a closed readable stream';
const errCloseErroredStream = 'Cannot close an errored readable stream';
- const errGetReaderNotByteStream =
- 'This readable stream does not support BYOB readers';
- const errGetReaderBadMode =
- 'Invalid reader mode given: expected undefined or "byob"';
const errReaderConstructorBadArgument =
'ReadableStreamReader constructor argument is not a readable stream';
const errReaderConstructorStreamAlreadyLocked =
@@ -120,15 +116,7 @@
'This readable stream reader has been released and cannot be used ' +
'to monitor the stream\'s state';
- const errCannotPipeLockedStream = 'Cannot pipe a locked stream';
- const errCannotPipeToALockedStream = 'Cannot pipe to a locked stream';
const errDestinationStreamClosed = 'Destination stream closed';
- const errPipeThroughUndefinedWritable =
- 'Failed to execute \'pipeThrough\' on \'ReadableStream\': parameter ' +
- '1\'s \'writable\' property is undefined.';
- const errPipeThroughUndefinedReadable =
- 'Failed to execute \'pipeThrough\' on \'ReadableStream\': parameter ' +
- '1\'s \'readable\' property is undefined.';
let useCounted = false;
@@ -171,95 +159,6 @@
this, underlyingSource, highWaterMark, sizeAlgorithm,
enableBlinkLockNotifications);
}
-
- get locked() {
- if (IsReadableStream(this) === false) {
- throw new TypeError(streamErrors.illegalInvocation);
- }
-
- return IsReadableStreamLocked(this);
- }
-
- cancel(reason) {
- if (IsReadableStream(this) === false) {
- return Promise_reject(new TypeError(streamErrors.illegalInvocation));
- }
-
- if (IsReadableStreamLocked(this) === true) {
- return Promise_reject(new TypeError(errCancelLockedStream));
- }
-
- return ReadableStreamCancel(this, reason);
- }
-
- getReader({mode} = {}) {
- if (IsReadableStream(this) === false) {
- throw new TypeError(streamErrors.illegalInvocation);
- }
-
- if (mode === undefined) {
- return AcquireReadableStreamDefaultReader(this);
- }
-
- mode = String(mode);
-
- if (mode === 'byob') {
- // TODO(ricea): When BYOB readers are supported:
- //
- // Return ? AcquireReadableStreamBYOBReader(this).
- throw new TypeError(errGetReaderNotByteStream);
- }
-
- throw new RangeError(errGetReaderBadMode);
- }
-
- pipeThrough({writable, readable}, options) {
- if (writable === undefined) {
- throw new TypeError(errPipeThroughUndefinedWritable);
- }
- if (readable === undefined) {
- throw new TypeError(errPipeThroughUndefinedReadable);
- }
- const promise = this.pipeTo(writable, options);
- if (v8.isPromise(promise)) {
- markPromiseAsHandled(promise);
- }
- return readable;
- }
-
- pipeTo(dest, {preventClose, preventAbort, preventCancel} = {}) {
- if (!IsReadableStream(this)) {
- return Promise_reject(new TypeError(streamErrors.illegalInvocation));
- }
-
- if (!binding.IsWritableStream(dest)) {
- // TODO(ricea): Think about having a better error message.
- return Promise_reject(new TypeError(streamErrors.illegalInvocation));
- }
-
- preventClose = Boolean(preventClose);
- preventAbort = Boolean(preventAbort);
- preventCancel = Boolean(preventCancel);
-
- if (IsReadableStreamLocked(this)) {
- return Promise_reject(new TypeError(errCannotPipeLockedStream));
- }
-
- if (binding.IsWritableStreamLocked(dest)) {
- return Promise_reject(new TypeError(errCannotPipeToALockedStream));
- }
-
- return ReadableStreamPipeTo(
- this, dest, preventClose, preventAbort, preventCancel);
- }
-
- tee() {
- if (IsReadableStream(this) === false) {
- throw new TypeError(streamErrors.illegalInvocation);
- }
-
- return ReadableStreamTee(this);
- }
}
const ReadableStream_prototype = ReadableStream.prototype;
@@ -709,6 +608,15 @@
class ReadableStreamDefaultReader {
constructor(stream) {
+ // |stream| here can be either an external ReadableStream (i.e.,
+ // IDL defined ReadableStream) or an internal ReadableStream (i.e.,
+ // the class defined in this file). In the former case, the
+ // internal stream is stored in [internalReadableStreamSymbol], so use it
+ // from now on.
+ if (stream[internalReadableStreamSymbol] !== undefined) {
+ stream = stream[internalReadableStreamSymbol];
+ }
+
if (IsReadableStream(stream) === false) {
throw new TypeError(errReaderConstructorBadArgument);
}
@@ -1127,6 +1035,34 @@
}
//
+ // Functions for transferable streams.
+ //
+
+ // The |port| which is passed to this function must be a MessagePort which is
+ // attached by a MessageChannel to the |port| that will be passed to
+ // ReadableStreamDeserialize.
+ function ReadableStreamSerialize(readable, port) {
+ // assert(IsReadableStream(readable),
+ // `! IsReadableStream(_readable_) is true`);
+ if (IsReadableStreamLocked(readable)) {
+ throw new TypeError(streamErrors.cannotTransferLockedStream);
+ }
+
+ if (!binding.MessagePort_postMessage) {
+ throw new TypeError(streamErrors.cannotTransferContext);
+ }
+
+ const writable = CreateCrossRealmTransformWritable(port);
+ const promise =
+ ReadableStreamPipeTo(readable, writable, false, false, false);
+ markPromiseAsHandled(promise);
+ }
+
+ function ReadableStreamDeserialize(port) {
+ return CreateCrossRealmTransformReadable(port);
+ }
+
+ //
// Internal functions. Not part of the standard.
//
@@ -1185,31 +1121,27 @@
return stream[_storedError];
}
+ // TODO(yhirano): Rename this to constructReadableStream.
+ function createReadableStream(underlyingSource, strategy) {
+ return new ReadableStream(underlyingSource, strategy);
+ }
+
+ // TODO(yhirano): Rename this to
+ // constructReadableStreamWithExternalController.
// TODO(ricea): Remove this once the C++ code switches to calling
// CreateReadableStream().
- function createReadableStreamWithExternalController(underlyingSource,
- strategy) {
+ function createReadableStreamWithExternalController(
+ underlyingSource, strategy) {
return new ReadableStream(
underlyingSource, strategy, createWithExternalControllerSentinel);
}
- //
- // Additions to the global
- //
-
- defineProperty(global, 'ReadableStream', {
- value: ReadableStream,
- enumerable: false,
- configurable: true,
- writable: true
- });
-
-
Object.assign(binding, {
//
// ReadableStream exports to Blink C++
//
AcquireReadableStreamDefaultReader,
+ createReadableStream,
createReadableStreamWithExternalController,
IsReadableStream,
IsReadableStreamDisturbed,
@@ -1219,7 +1151,12 @@
IsReadableStreamErrored,
IsReadableStreamDefaultReader,
ReadableStreamDefaultReaderRead,
+ ReadableStreamCancel,
ReadableStreamTee,
+ ReadableStreamPipeTo,
+ ReadableStreamSerialize,
+ ReadableStreamDeserialize,
+ internalReadableStreamSymbol,
//
// Controller exports to Blink C++
diff --git a/chromium/third_party/blink/renderer/core/streams/TransformStream.js b/chromium/third_party/blink/renderer/core/streams/TransformStream.js
index e8ec397c34c..cafce4170f1 100644
--- a/chromium/third_party/blink/renderer/core/streams/TransformStream.js
+++ b/chromium/third_party/blink/renderer/core/streams/TransformStream.js
@@ -35,7 +35,6 @@
// the global object may have been overwritten. See "V8 Extras Design Doc",
// section "Security Considerations".
// https://docs.google.com/document/d/1AT5-T0aHGp7Lt29vPWFr2-qG8r3l9CByyvKwEuA8Ec0/edit#heading=h.9yixony1a18r
- const defineProperty = global.Object.defineProperty;
const ObjectCreate = global.Object.create;
const TypeError = global.TypeError;
@@ -462,6 +461,19 @@
return CreateTransformStream(() => Promise_resolve(),
transformAlgorithm, flushAlgorithm);
}
+ function createTransformStream(
+ transformer, writableStrategy, readableStrategy) {
+ if (transformer === undefined) {
+ transformer = ObjectCreate(null);
+ }
+ if (writableStrategy === undefined) {
+ writableStrategy = ObjectCreate(null);
+ }
+ if (readableStrategy === undefined) {
+ readableStrategy = ObjectCreate(null);
+ }
+ return new TransformStream(transformer, writableStrategy, readableStrategy);
+ }
function getTransformStreamReadable(stream) {
return stream[_readable];
@@ -472,21 +484,11 @@
}
//
- // Additions to the global object
- //
-
- defineProperty(global, 'TransformStream', {
- value: TransformStream,
- enumerable: false,
- configurable: true,
- writable: true
- });
-
- //
// Exports to Blink
//
Object.assign(binding, {
createTransformStreamSimple,
+ createTransformStream,
TransformStreamDefaultControllerEnqueue,
getTransformStreamReadable,
getTransformStreamWritable
diff --git a/chromium/third_party/blink/renderer/core/streams/WritableStream.js b/chromium/third_party/blink/renderer/core/streams/WritableStream.js
index 3ee1c57e3ea..8c3a75160fd 100644
--- a/chromium/third_party/blink/renderer/core/streams/WritableStream.js
+++ b/chromium/third_party/blink/renderer/core/streams/WritableStream.js
@@ -43,6 +43,8 @@
const _strategySizeAlgorithm =
v8.createPrivateSymbol('[[strategySizeAlgorithm]]');
const _writeAlgorithm = v8.createPrivateSymbol('[[writeAlgorithm]]');
+ const internalWritableStreamSymbol = v8.createPrivateSymbol(
+ 'internal WritableStream in exposed WritableStream interface');
// Numeric encodings of stream states. Stored in the _stateAndFlags slot.
const WRITABLE = 0;
@@ -60,7 +62,6 @@
// the global object may have been overwritten. See "V8 Extras Design Doc",
// section "Security Considerations".
// https://docs.google.com/document/d/1AT5-T0aHGp7Lt29vPWFr2-qG8r3l9CByyvKwEuA8Ec0/edit#heading=h.9yixony1a18r
- const defineProperty = global.Object.defineProperty;
const ObjectCreate = global.Object.create;
const Function_call = v8.uncurryThis(global.Function.prototype.call);
@@ -92,13 +93,13 @@
PeekQueueValue,
ResetQueue,
ValidateAndNormalizeHighWaterMark,
+ CreateCrossRealmTransformReadable,
+ CreateCrossRealmTransformWritable,
CallOrNoop1,
} = binding.streamOperations;
// User-visible strings.
const streamErrors = binding.streamErrors;
- const errAbortLockedStream =
- 'Cannot abort a writable stream that is locked to a writer';
const errWriterLockReleasedPrefix =
'This writable stream writer has been released and cannot be ';
const errCloseCloseRequestedStream = 'Cannot close a writable stream that ' +
@@ -158,34 +159,14 @@
SetUpWritableStreamDefaultControllerFromUnderlyingSink(
this, underlyingSink, highWaterMark, sizeAlgorithm);
}
-
- get locked() {
- if (!IsWritableStream(this)) {
- throw new TypeError(streamErrors.illegalInvocation);
- }
- return IsWritableStreamLocked(this);
- }
-
- abort(reason) {
- if (!IsWritableStream(this)) {
- return Promise_reject(new TypeError(streamErrors.illegalInvocation));
- }
- if (IsWritableStreamLocked(this)) {
- return Promise_reject(new TypeError(errAbortLockedStream));
- }
- return WritableStreamAbort(this, reason);
- }
-
- getWriter() {
- if (!IsWritableStream(this)) {
- throw new TypeError(streamErrors.illegalInvocation);
- }
- return AcquireWritableStreamDefaultWriter(this);
- }
}
const WritableStream_prototype = WritableStream.prototype;
+ function createWritableStream(underlyingSink, strategy) {
+ return new WritableStream(underlyingSink, strategy);
+ }
+
// General Writable Stream Abstract Operations
function AcquireWritableStreamDefaultWriter(stream) {
@@ -487,6 +468,34 @@
}
}
+ //
+ // Functions for transferable streams.
+ //
+
+ // The |port| which is passed to this function must be a MessagePort which is
+ // attached by a MessageChannel to the |port| that will be passed to
+ // WritableStreamDeserialize.
+ function WritableStreamSerialize(writable, port) {
+ // assert(IsWritableStream(writable),
+ // `! IsWritableStream(_writable_) is true`);
+ if (IsWritableStreamLocked(writable)) {
+ throw new TypeError(streamErrors.cannotTransferLockedStream);
+ }
+
+ if (!binding.MessagePort_postMessage) {
+ throw new TypeError(streamErrors.cannotTransferContext);
+ }
+
+ const readable = CreateCrossRealmTransformReadable(port);
+ const promise =
+ binding.ReadableStreamPipeTo(readable, writable, false, false, false);
+ markPromiseAsHandled(promise);
+ }
+
+ function WritableStreamDeserialize(port) {
+ return CreateCrossRealmTransformWritable(port);
+ }
+
// Functions to expose internals for ReadableStream.pipeTo. These are not
// part of the standard.
function isWritableStreamErrored(stream) {
@@ -529,6 +538,14 @@
class WritableStreamDefaultWriter {
constructor(stream) {
+ // |stream| here can be either an external WritableStream (i.e.,
+ // IDL defined WritableStream) or an internal WritableStream (i.e.,
+ // the class defined in this file). In the former case, the
+ // internal stream is stored in [internalWritableStreamSymbol], so use it
+ // from now on.
+ if (stream[internalWritableStreamSymbol] !== undefined) {
+ stream = stream[internalWritableStreamSymbol];
+ }
if (!IsWritableStream(stream)) {
throw new TypeError(streamErrors.illegalConstructor);
}
@@ -1036,19 +1053,6 @@
WritableStreamStartErroring(stream, error);
}
- //
- // Additions to the global object
- //
-
- defineProperty(global, 'WritableStream', {
- value: WritableStream,
- enumerable: false,
- configurable: true,
- writable: true
- });
-
- // TODO(ricea): Exports to Blink
-
Object.assign(binding, {
// Exports for ReadableStream
AcquireWritableStreamDefaultWriter,
@@ -1067,11 +1071,20 @@
WritableStreamDefaultWriterWrite,
getWritableStreamStoredError,
+ // Exports for blink
+ createWritableStream,
+ internalWritableStreamSymbol,
+ WritableStreamSerialize,
+ WritableStreamDeserialize,
+
// Additional exports for TransformStream
CreateWritableStream,
WritableStream,
WritableStreamDefaultControllerErrorIfNeeded,
isWritableStreamErroring,
getWritableStreamController,
+
+ // Exports for CreateCrossRealmTransformWritable in CommonOperations.js
+ WritableStreamDefaultControllerClose,
});
});
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream.cc
new file mode 100644
index 00000000000..f71fefdabc0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream.cc
@@ -0,0 +1,517 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
+#include "third_party/blink/renderer/core/streams/retain_wrapper_during_construction.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
+
+namespace blink {
+
+class ReadableStream::NoopFunction : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> CreateFunction(ScriptState* script_state) {
+ auto* self = MakeGarbageCollected<NoopFunction>(script_state);
+ return self->BindToV8Function();
+ }
+ NoopFunction(ScriptState* script_state) : ScriptFunction(script_state) {}
+ ScriptValue Call(ScriptValue value) override { return value; }
+};
+
+void ReadableStream::Init(ScriptState* script_state,
+ ScriptValue underlying_source,
+ ScriptValue strategy,
+ ExceptionState& exception_state) {
+ ScriptValue value = ReadableStreamOperations::CreateReadableStream(
+ script_state, underlying_source, strategy, exception_state);
+ if (exception_state.HadException())
+ return;
+
+ DCHECK(value.IsObject());
+ InitWithInternalStream(script_state, value.V8Value().As<v8::Object>(),
+ exception_state);
+}
+
+void ReadableStream::InitWithInternalStream(ScriptState* script_state,
+ v8::Local<v8::Object> object,
+ ExceptionState& exception_state) {
+ DCHECK(ReadableStreamOperations::IsReadableStreamForDCheck(
+ script_state, ScriptValue(script_state, object)));
+ object_.Set(script_state->GetIsolate(), object);
+
+ v8::Isolate* isolate = script_state->GetIsolate();
+ v8::TryCatch block(isolate);
+ v8::Local<v8::Value> wrapper = ToV8(this, script_state);
+ if (wrapper.IsEmpty()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Local<v8::Object> bindings =
+ context->GetExtrasBindingObject().As<v8::Object>();
+ v8::Local<v8::Value> symbol_value;
+ if (!bindings->Get(context, V8String(isolate, "internalReadableStreamSymbol"))
+ .ToLocal(&symbol_value)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+
+ if (wrapper.As<v8::Object>()
+ ->Set(context, symbol_value.As<v8::Symbol>(), object)
+ .IsNothing()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+
+ // This is needed because sometimes a ReadableStream can be detached from
+ // the owner object such as Response.
+ if (!RetainWrapperDuringConstruction(this, script_state)) {
+ exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
+ "Cannot queue task to retain wrapper");
+ }
+}
+
+ReadableStream* ReadableStream::Create(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ return Create(
+ script_state,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+ReadableStream* ReadableStream::Create(ScriptState* script_state,
+ ScriptValue underlying_source,
+ ExceptionState& exception_state) {
+ return Create(
+ script_state, underlying_source,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+ReadableStream* ReadableStream::Create(ScriptState* script_state,
+ ScriptValue underlying_source,
+ ScriptValue strategy,
+ ExceptionState& exception_state) {
+ auto* stream = MakeGarbageCollected<ReadableStream>();
+ stream->Init(script_state, underlying_source, strategy, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ return stream;
+}
+
+ReadableStream* ReadableStream::CreateFromInternalStream(
+ ScriptState* script_state,
+ ScriptValue object,
+ ExceptionState& exception_state) {
+ DCHECK(object.IsObject());
+ return CreateFromInternalStream(
+ script_state, object.V8Value().As<v8::Object>(), exception_state);
+}
+
+ReadableStream* ReadableStream::CreateFromInternalStream(
+ ScriptState* script_state,
+ v8::Local<v8::Object> object,
+ ExceptionState& exception_state) {
+ auto* stream = MakeGarbageCollected<ReadableStream>();
+ stream->InitWithInternalStream(script_state, object, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ return stream;
+}
+
+ReadableStream* ReadableStream::CreateWithCountQueueingStrategy(
+ ScriptState* script_state,
+ UnderlyingSourceBase* underlying_source,
+ size_t high_water_mark) {
+ v8::TryCatch block(script_state->GetIsolate());
+ ScriptValue strategy =
+ ReadableStreamOperations::CreateCountQueuingStrategy(script_state, 0);
+ if (strategy.IsEmpty())
+ return nullptr;
+
+ ScriptValue value = ReadableStreamOperations::CreateReadableStream(
+ script_state, underlying_source, strategy);
+ if (value.IsEmpty())
+ return nullptr;
+
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kConstructionContext,
+ "ReadableStream");
+ DCHECK(value.V8Value()->IsObject());
+ auto* stream = CreateFromInternalStream(script_state, value, exception_state);
+ if (exception_state.HadException())
+ exception_state.ClearException();
+ return stream;
+}
+
+void ReadableStream::Trace(Visitor* visitor) {
+ visitor->Trace(object_);
+ ScriptWrappable::Trace(visitor);
+}
+
+ScriptPromise ReadableStream::cancel(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ return cancel(
+ script_state,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+bool ReadableStream::locked(ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ auto result = IsLocked(script_state, exception_state);
+
+ return !result || *result;
+}
+
+ScriptPromise ReadableStream::cancel(ScriptState* script_state,
+ ScriptValue reason,
+ ExceptionState& exception_state) {
+ if (locked(script_state, exception_state) &&
+ !exception_state.HadException()) {
+ exception_state.ThrowTypeError("Cannot cancel a locked stream");
+ }
+
+ if (exception_state.HadException())
+ return ScriptPromise();
+
+ return ReadableStreamOperations::Cancel(
+ script_state, GetInternalStream(script_state), reason, exception_state);
+}
+
+ScriptValue ReadableStream::getReader(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ return ReadableStreamOperations::GetReader(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+ScriptValue ReadableStream::getReader(ScriptState* script_state,
+ ScriptValue options,
+ ExceptionState& exception_state) {
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> mode;
+ v8::Local<v8::String> mode_string;
+ v8::Local<v8::Context> context = script_state->GetContext();
+ if (options.V8Value()->IsUndefined()) {
+ mode = v8::Undefined(script_state->GetIsolate());
+ } else {
+ v8::Local<v8::Object> v8_options;
+ if (!options.V8Value()->ToObject(context).ToLocal(&v8_options)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ if (!v8_options->Get(context, V8String(script_state->GetIsolate(), "mode"))
+ .ToLocal(&mode)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ }
+
+ if (!mode->ToString(context).ToLocal(&mode_string)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ if (ToCoreString(mode_string) == "byob") {
+ exception_state.ThrowTypeError("invalid mode");
+ return ScriptValue();
+ }
+ if (!mode->IsUndefined()) {
+ exception_state.ThrowRangeError("invalid mode");
+ return ScriptValue();
+ }
+ return ReadableStreamOperations::GetReader(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+ScriptValue ReadableStream::pipeThrough(ScriptState* script_state,
+ ScriptValue transform_stream,
+ ExceptionState& exception_state) {
+ return pipeThrough(
+ script_state, transform_stream,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+ScriptValue ReadableStream::pipeThrough(ScriptState* script_state,
+ ScriptValue transform_stream,
+ ScriptValue options,
+ ExceptionState& exception_state) {
+ v8::Local<v8::Value> pair_value = transform_stream.V8Value();
+ v8::Local<v8::Context> context = script_state->GetContext();
+
+ constexpr char kWritableIsUndefined[] =
+ "Failed to execute 'pipeThrough' on 'ReadableStream': "
+ "parameter 1's 'writable' property is undefined.";
+ constexpr char kReadableIsUndefined[] =
+ "Failed to execute 'pipeThrough' on 'ReadableStream': "
+ "parameter 1's 'readable' property is undefined.";
+
+ v8::Local<v8::Object> pair;
+ if (!pair_value->ToObject(context).ToLocal(&pair)) {
+ exception_state.ThrowTypeError(kWritableIsUndefined);
+ return ScriptValue();
+ }
+
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> writable, readable;
+ if (!pair->Get(context, V8String(script_state->GetIsolate(), "writable"))
+ .ToLocal(&writable)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ DCHECK(!block.HasCaught());
+
+ if (writable->IsUndefined()) {
+ exception_state.ThrowTypeError(kWritableIsUndefined);
+ return ScriptValue();
+ }
+
+ if (!pair->Get(context, V8String(script_state->GetIsolate(), "readable"))
+ .ToLocal(&readable)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ DCHECK(!block.HasCaught());
+
+ if (readable->IsUndefined()) {
+ exception_state.ThrowTypeError(kReadableIsUndefined);
+ return ScriptValue();
+ }
+
+ ScriptPromise promise =
+ pipeTo(script_state, ScriptValue(script_state, writable), options,
+ exception_state);
+ if (!exception_state.HadException()) {
+ // set promise.[[PromiseIsHandled]] to true.
+ // We don't have a primitive to do this, so let's attach a catch handler.
+ //
+ // ScriptPromise::Then(f, g) is a confusing interface, it is actually
+ // |promise.then(f).catch(g)|.
+ promise.Then(v8::Local<v8::Function>(),
+ NoopFunction::CreateFunction(script_state));
+ }
+ return ScriptValue(script_state, readable);
+}
+
+ScriptPromise ReadableStream::pipeTo(ScriptState* script_state,
+ ScriptValue destination,
+ ExceptionState& exception_state) {
+ return pipeTo(
+ script_state, destination,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+ScriptPromise ReadableStream::pipeTo(ScriptState* script_state,
+ ScriptValue destination_value,
+ ScriptValue options,
+ ExceptionState& exception_state) {
+ WritableStream* destination = V8WritableStream::ToImplWithTypeCheck(
+ script_state->GetIsolate(), destination_value.V8Value());
+
+ if (!destination) {
+ exception_state.ThrowTypeError("Illegal invocation");
+ return ScriptPromise();
+ }
+ if (locked(script_state, exception_state) &&
+ !exception_state.HadException()) {
+ exception_state.ThrowTypeError("Cannot pipe a locked stream");
+ return ScriptPromise();
+ }
+ if (exception_state.HadException())
+ return ScriptPromise();
+ if (destination->locked(script_state, exception_state) &&
+ !exception_state.HadException()) {
+ exception_state.ThrowTypeError("Cannot pipe to a locked stream");
+ return ScriptPromise();
+ }
+ if (exception_state.HadException())
+ return ScriptPromise();
+
+ return ReadableStreamOperations::PipeTo(
+ script_state, GetInternalStream(script_state),
+ destination->GetInternalStream(script_state), options, exception_state);
+}
+
+ScriptValue ReadableStream::tee(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ v8::Isolate* isolate = script_state->GetIsolate();
+ ReadableStream* branch1 = nullptr;
+ ReadableStream* branch2 = nullptr;
+
+ Tee(script_state, &branch1, &branch2, exception_state);
+
+ if (!branch1 || !branch2)
+ return ScriptValue();
+
+ DCHECK(!exception_state.HadException());
+
+ v8::TryCatch block(isolate);
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Local<v8::Array> array = v8::Array::New(isolate, 2);
+ v8::Local<v8::Object> global = context->Global();
+
+ v8::Local<v8::Value> v8_branch1 = ToV8(branch1, global, isolate);
+ if (v8_branch1.IsEmpty()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ v8::Local<v8::Value> v8_branch2 = ToV8(branch2, global, isolate);
+ if (v8_branch1.IsEmpty()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ if (array->Set(context, V8String(isolate, "0"), v8_branch1).IsNothing()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ if (array->Set(context, V8String(isolate, "1"), v8_branch2).IsNothing()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ return ScriptValue(script_state, array);
+}
+
+void ReadableStream::Tee(ScriptState* script_state,
+ ReadableStream** branch1,
+ ReadableStream** branch2,
+ ExceptionState& exception_state) {
+ v8::Local<v8::Context> context = script_state->GetContext();
+
+ if (locked(script_state, exception_state) &&
+ !exception_state.HadException()) {
+ exception_state.ThrowTypeError("The stream is already locked.");
+ }
+
+ if (exception_state.HadException())
+ return;
+
+ ScriptValue tee_result = ReadableStreamOperations::Tee(
+ script_state, GetInternalStream(script_state), exception_state);
+ if (tee_result.IsEmpty())
+ return;
+
+ DCHECK(!exception_state.HadException());
+ DCHECK(tee_result.V8Value()->IsArray());
+
+ v8::Local<v8::Array> branches = tee_result.V8Value().As<v8::Array>();
+ v8::Local<v8::Value> v8_branch1, v8_branch2;
+ v8::TryCatch block(script_state->GetIsolate());
+
+ if (!branches->Get(context, 0).ToLocal(&v8_branch1)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+ if (!branches->Get(context, 1).ToLocal(&v8_branch2)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+
+ DCHECK(v8_branch1->IsObject());
+ DCHECK(v8_branch2->IsObject());
+
+ ReadableStream* temp_branch1 = MakeGarbageCollected<ReadableStream>();
+ ReadableStream* temp_branch2 = MakeGarbageCollected<ReadableStream>();
+
+ temp_branch1->InitWithInternalStream(
+ script_state, v8_branch1.As<v8::Object>(), exception_state);
+ if (exception_state.HadException())
+ return;
+
+ temp_branch2->InitWithInternalStream(
+ script_state, v8_branch2.As<v8::Object>(), exception_state);
+ if (exception_state.HadException())
+ return;
+
+ *branch1 = temp_branch1;
+ *branch2 = temp_branch2;
+}
+
+base::Optional<bool> ReadableStream::IsLocked(
+ ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ return ReadableStreamOperations::IsLocked(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+base::Optional<bool> ReadableStream::IsDisturbed(
+ ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ return ReadableStreamOperations::IsDisturbed(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+base::Optional<bool> ReadableStream::IsReadable(
+ ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ return ReadableStreamOperations::IsReadable(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+base::Optional<bool> ReadableStream::IsClosed(
+ ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ return ReadableStreamOperations::IsClosed(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+base::Optional<bool> ReadableStream::IsErrored(
+ ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ return ReadableStreamOperations::IsErrored(
+ script_state, GetInternalStream(script_state), exception_state);
+}
+
+void ReadableStream::LockAndDisturb(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ ScriptState::Scope scope(script_state);
+
+ const base::Optional<bool> is_locked =
+ IsLocked(script_state, exception_state);
+ if (!is_locked || is_locked.value())
+ return;
+
+ ScriptValue reader = getReader(script_state, exception_state);
+ if (reader.IsEmpty())
+ return;
+
+ ReadableStreamOperations::DefaultReaderRead(script_state, reader);
+}
+
+void ReadableStream::Serialize(ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ ReadableStreamOperations::Serialize(
+ script_state, GetInternalStream(script_state), port, exception_state);
+}
+
+// static
+ReadableStream* ReadableStream::Deserialize(ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ // We need to execute V8 Extras JavaScript to create the new ReadableStream.
+ // We will not run author code.
+ v8::Isolate::AllowJavascriptExecutionScope allow_js(
+ script_state->GetIsolate());
+ ScriptValue internal_stream = ReadableStreamOperations::Deserialize(
+ script_state, port, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ return CreateFromInternalStream(script_state, internal_stream,
+ exception_state);
+}
+
+ScriptValue ReadableStream::GetInternalStream(ScriptState* script_state) const {
+ return ScriptValue(script_state,
+ object_.NewLocal(script_state->GetIsolate()));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream.h b/chromium/third_party/blink/renderer/core/streams/readable_stream.h
new file mode 100644
index 00000000000..7ba04529cf2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream.h
@@ -0,0 +1,128 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_READABLE_STREAM_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_READABLE_STREAM_H_
+
+#include "base/optional.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+class ExceptionState;
+class ScriptPromise;
+class ScriptState;
+class UnderlyingSourceBase;
+class MessagePort;
+
+// This is an implementation of the corresponding IDL interface.
+// Use TraceWrapperMember to hold a reference to an instance of this class.
+class CORE_EXPORT ReadableStream : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ // Call one of Init functions before using the instance.
+ ReadableStream() = default;
+ ~ReadableStream() override = default;
+
+ // If an error happens, |exception_state.HadException()| will be true, and
+ // |this| will not be usable after that.
+ void Init(ScriptState*,
+ ScriptValue underlying_source,
+ ScriptValue strategy,
+ ExceptionState& exception_state);
+ void InitWithInternalStream(ScriptState*,
+ v8::Local<v8::Object> object,
+ ExceptionState& exception_state);
+
+ // Create* functions call Init* internally and returns null when an error
+ // happens.
+ static ReadableStream* Create(ScriptState*, ExceptionState&);
+ static ReadableStream* Create(ScriptState*,
+ ScriptValue underlying_source,
+ ExceptionState&);
+ static ReadableStream* Create(ScriptState*,
+ ScriptValue underlying_source,
+ ScriptValue strategy,
+ ExceptionState&);
+ static ReadableStream* CreateFromInternalStream(ScriptState*,
+ v8::Local<v8::Object> object,
+ ExceptionState&);
+ static ReadableStream* CreateFromInternalStream(ScriptState*,
+ ScriptValue object,
+ ExceptionState&);
+ // This function doesn't take ExceptionState because the caller cannot have
+ // one. Returns null when an error happens.
+ static ReadableStream* CreateWithCountQueueingStrategy(
+ ScriptState*,
+ UnderlyingSourceBase* underlying_source,
+ size_t high_water_mark);
+
+ void Trace(Visitor* visitor) override;
+
+ // IDL defined functions
+ bool locked(ScriptState*, ExceptionState&) const;
+ ScriptPromise cancel(ScriptState*, ExceptionState&);
+ ScriptPromise cancel(ScriptState*, ScriptValue reason, ExceptionState&);
+ ScriptValue getReader(ScriptState*, ExceptionState&);
+ ScriptValue getReader(ScriptState*, ScriptValue options, ExceptionState&);
+ ScriptValue pipeThrough(ScriptState*,
+ ScriptValue transform_stream,
+ ExceptionState&);
+ ScriptValue pipeThrough(ScriptState*,
+ ScriptValue transform_stream,
+ ScriptValue options,
+ ExceptionState&);
+ ScriptPromise pipeTo(ScriptState*, ScriptValue destination, ExceptionState&);
+ ScriptPromise pipeTo(ScriptState*,
+ ScriptValue destination,
+ ScriptValue options,
+ ExceptionState&);
+ ScriptValue tee(ScriptState*, ExceptionState&);
+
+ void Tee(ScriptState*,
+ ReadableStream** branch1,
+ ReadableStream** branch2,
+ ExceptionState&);
+
+ base::Optional<bool> IsLocked(ScriptState*, ExceptionState&) const;
+ base::Optional<bool> IsDisturbed(ScriptState*, ExceptionState&) const;
+ base::Optional<bool> IsReadable(ScriptState*, ExceptionState&) const;
+ base::Optional<bool> IsClosed(ScriptState*, ExceptionState&) const;
+ base::Optional<bool> IsErrored(ScriptState*, ExceptionState&) const;
+
+ // Makes this stream locked and disturbed.
+ void LockAndDisturb(ScriptState*, ExceptionState&);
+
+ // Serialize this stream to |port|. The stream will be locked by this
+ // operation.
+ void Serialize(ScriptState*, MessagePort* port, ExceptionState&);
+
+ // Given a |port| which is entangled with a MessagePort that was previously
+ // passed to Serialize(), returns a new ReadableStream which behaves like it
+ // was the original.
+ static ReadableStream* Deserialize(ScriptState*,
+ MessagePort* port,
+ ExceptionState&);
+
+ ScriptValue GetInternalStream(ScriptState* script_state) const;
+
+ // In some cases we are known to fail to trace the stream correctly. In such
+ // cases |object_| will be silently gone. This function is for detecting the
+ // issue. Use this function at places where an actual crash happens. Do not
+ // use this function to write "just in case" code.
+ bool IsInternalStreamMissing() const { return object_.IsEmpty(); }
+
+ private:
+ class NoopFunction;
+
+ TraceWrapperV8Reference<v8::Object> object_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_READABLE_STREAM_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream.idl b/chromium/third_party/blink/renderer/core/streams/readable_stream.idl
new file mode 100644
index 00000000000..9fbe8e9fae9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream.idl
@@ -0,0 +1,25 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://streams.spec.whatwg.org/#rs-class
+[
+ Exposed=(Window,Worker,Worklet),
+ // TODO(yhirano): Remove CustomConstructor. See https://crbug.com/906476.
+ CustomConstructor(optional any underlyingSource, optional any strategy),
+ RaisesException=Constructor,
+ ConstructorCallWith=ScriptState
+] interface ReadableStream {
+ // As long as we use V8Extras, anything can raise an exception.
+ [RaisesException, CallWith=ScriptState, NotEnumerable] readonly attribute boolean locked;
+
+ // TODO(yhirano): function length is different from what's specced. Fix it.
+ [RaisesException, CallWith=ScriptState, NotEnumerable] Promise<any> cancel(
+ optional any reason);
+ [RaisesException, CallWith=ScriptState, NotEnumerable] any getReader(optional any mode);
+ [RaisesException, CallWith=ScriptState, NotEnumerable] any pipeThrough(
+ any transformStream, optional any options);
+ [RaisesException, CallWith=ScriptState, NotEnumerable] Promise<any> pipeTo(
+ any destination, optional any option);
+ [RaisesException, CallWith=ScriptState, NotEnumerable] any tee();
+};
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.cc
index 6f347b200a3..3012abf2d46 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.cc
@@ -7,10 +7,13 @@
#include <utility>
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_message_port.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h"
+#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -30,11 +33,9 @@ base::Optional<bool> BooleanOperationWithRethrow(
v8::TryCatch block(script_state->GetIsolate());
v8::Local<v8::Value> args[] = {value.V8Value()};
v8::Local<v8::Value> local_value;
- bool result_bool = false;
if (!V8ScriptRunner::CallExtra(script_state, operation, args)
- .ToLocal(&local_value) ||
- !local_value->BooleanValue(script_state->GetContext()).To(&result_bool)) {
+ .ToLocal(&local_value)) {
DCHECK(block.HasCaught() ||
script_state->GetIsolate()->IsExecutionTerminating());
exception_state.RethrowV8Exception(block.Exception());
@@ -42,7 +43,7 @@ base::Optional<bool> BooleanOperationWithRethrow(
}
DCHECK(!block.HasCaught());
- return result_bool;
+ return local_value->BooleanValue(script_state->GetIsolate());
}
// Performs |operation| on |value|, catching any exceptions. This is for use in
@@ -55,13 +56,11 @@ bool BooleanOperationForDCheck(ScriptState* script_state,
bool fallback_value) {
v8::Local<v8::Value> args[] = {value.V8Value()};
v8::Local<v8::Value> result_value;
- bool result_bool = false;
v8::TryCatch block(script_state->GetIsolate());
if (V8ScriptRunner::CallExtra(script_state, operation, args)
- .ToLocal(&result_value) &&
- result_value->BooleanValue(script_state->GetContext()).To(&result_bool)) {
+ .ToLocal(&result_value)) {
DCHECK(!block.HasCaught());
- return result_bool;
+ return result_value->BooleanValue(script_state->GetIsolate());
}
DCHECK(block.HasCaught() ||
script_state->GetIsolate()->IsExecutionTerminating());
@@ -93,6 +92,28 @@ ScriptValue ReadableStreamOperations::CreateReadableStream(
script_state, "createReadableStreamWithExternalController", args));
}
+ScriptValue ReadableStreamOperations::CreateReadableStream(
+ ScriptState* script_state,
+ ScriptValue underlying_source,
+ ScriptValue strategy,
+ ExceptionState& exception_state) {
+ ScriptState::Scope scope(script_state);
+
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> args[] = {underlying_source.V8Value(),
+ strategy.V8Value()};
+ v8::Local<v8::Value> result;
+
+ if (!V8ScriptRunner::CallExtra(script_state, "createReadableStream", args)
+ .ToLocal(&result)) {
+ DCHECK(block.HasCaught() ||
+ script_state->GetIsolate()->IsExecutionTerminating());
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ return ScriptValue(script_state, result);
+}
+
ScriptValue ReadableStreamOperations::CreateCountQueuingStrategy(
ScriptState* script_state,
size_t high_water_mark) {
@@ -226,42 +247,146 @@ ScriptPromise ReadableStreamOperations::DefaultReaderRead(
return ScriptPromise::Cast(script_state, maybe_result.ToLocalChecked());
}
-void ReadableStreamOperations::Tee(ScriptState* script_state,
- ScriptValue stream,
- ScriptValue* new_stream1,
- ScriptValue* new_stream2,
- ExceptionState& exception_state) {
+ScriptValue ReadableStreamOperations::Tee(ScriptState* script_state,
+ ScriptValue stream,
+ ExceptionState& exception_state) {
DCHECK(IsReadableStreamForDCheck(script_state, stream));
DCHECK(!IsLockedForDCheck(script_state, stream));
+ v8::TryCatch block(script_state->GetIsolate());
v8::Local<v8::Value> args[] = {stream.V8Value()};
+ v8::Local<v8::Value> result;
+ if (!V8ScriptRunner::CallExtra(script_state, "ReadableStreamTee", args)
+ .ToLocal(&result)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ return ScriptValue(script_state, result);
+}
+
+void ReadableStreamOperations::Serialize(ScriptState* script_state,
+ ScriptValue stream,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ DCHECK(port);
+ DCHECK(IsReadableStreamForDCheck(script_state, stream));
+ DCHECK(RuntimeEnabledFeatures::TransferableStreamsEnabled());
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> port_v8_value = ToV8(port, script_state);
+ DCHECK(!port_v8_value.IsEmpty());
+ v8::Local<v8::Value> args[] = {stream.V8Value(), port_v8_value};
+ ScriptValue result(
+ script_state,
+ V8ScriptRunner::CallExtra(script_state, "ReadableStreamSerialize", args));
+ if (block.HasCaught()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+ return;
+}
+
+ScriptValue ReadableStreamOperations::Deserialize(
+ ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ DCHECK(port);
+ DCHECK(RuntimeEnabledFeatures::TransferableStreamsEnabled());
+ auto* isolate = script_state->GetIsolate();
+ v8::TryCatch block(isolate);
+ v8::Local<v8::Value> port_v8 = ToV8(port, script_state);
+ DCHECK(!port_v8.IsEmpty());
+ v8::Local<v8::Value> args[] = {port_v8};
+ ScriptValue result(script_state,
+ V8ScriptRunner::CallExtra(
+ script_state, "ReadableStreamDeserialize", args));
+ if (block.HasCaught()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ if (result.IsEmpty()) {
+ DCHECK(isolate->IsExecutionTerminating());
+ return ScriptValue();
+ }
+ DCHECK(IsReadableStreamForDCheck(script_state, result));
+ return result;
+}
+ScriptPromise ReadableStreamOperations::Cancel(
+ ScriptState* script_state,
+ ScriptValue stream,
+ ScriptValue reason,
+ ExceptionState& exception_state) {
+ v8::Local<v8::Value> args[] = {stream.V8Value(), reason.V8Value()};
v8::TryCatch block(script_state->GetIsolate());
v8::Local<v8::Value> result;
- if (!V8ScriptRunner::CallExtra(script_state, "ReadableStreamTee", args)
+
+ if (!V8ScriptRunner::CallExtra(script_state, "ReadableStreamCancel", args)
.ToLocal(&result)) {
DCHECK(block.HasCaught() ||
script_state->GetIsolate()->IsExecutionTerminating());
exception_state.RethrowV8Exception(block.Exception());
- return;
+ return ScriptPromise();
}
+ return ScriptPromise(script_state, result);
+}
- DCHECK(result->IsArray());
- v8::Local<v8::Array> branches = result.As<v8::Array>();
- DCHECK_EQ(2u, branches->Length());
-
- ScriptValue result1(script_state,
- branches->Get(script_state->GetContext(), 0));
- DCHECK(!result1.IsEmpty());
- DCHECK(IsReadableStreamForDCheck(script_state, result1));
+ScriptPromise ReadableStreamOperations::PipeTo(
+ ScriptState* script_state,
+ ScriptValue stream,
+ ScriptValue destination,
+ ScriptValue options,
+ ExceptionState& exception_state) {
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> result;
+ v8::Isolate* isolate = script_state->GetIsolate();
+ v8::Local<v8::Boolean> prevent_close;
+ v8::Local<v8::Boolean> prevent_abort;
+ v8::Local<v8::Boolean> prevent_cancel;
+
+ if (options.IsUndefined()) {
+ // All values default to false.
+ prevent_close = v8::Boolean::New(isolate, false);
+ prevent_abort = v8::Boolean::New(isolate, false);
+ prevent_cancel = v8::Boolean::New(isolate, false);
+ } else {
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Local<v8::Object> v8_options;
+ if (!options.V8Value()->ToObject(context).ToLocal(&v8_options)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptPromise();
+ }
+ v8::Local<v8::Value> prevent_close_v, prevent_abort_v, prevent_cancel_v;
+ if (!v8_options->Get(context, V8String(isolate, "preventClose"))
+ .ToLocal(&prevent_close_v)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptPromise();
+ }
+ if (!v8_options->Get(context, V8String(isolate, "preventAbort"))
+ .ToLocal(&prevent_abort_v)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptPromise();
+ }
+ if (!v8_options->Get(context, V8String(isolate, "preventCancel"))
+ .ToLocal(&prevent_cancel_v)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptPromise();
+ }
+ prevent_close = prevent_close_v->ToBoolean(isolate);
+ prevent_abort = prevent_abort_v->ToBoolean(isolate);
+ prevent_cancel = prevent_cancel_v->ToBoolean(isolate);
+ }
- ScriptValue result2(script_state,
- branches->Get(script_state->GetContext(), 1));
- DCHECK(!result2.IsEmpty());
- DCHECK(IsReadableStreamForDCheck(script_state, result2));
+ v8::Local<v8::Value> args[] = {stream.V8Value(), destination.V8Value(),
+ prevent_close, prevent_abort, prevent_cancel};
+ if (!V8ScriptRunner::CallExtra(script_state, "ReadableStreamPipeTo", args)
+ .ToLocal(&result)) {
+ DCHECK(block.HasCaught() ||
+ script_state->GetIsolate()->IsExecutionTerminating());
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptPromise();
+ }
- *new_stream1 = std::move(result1);
- *new_stream2 = std::move(result2);
+ return ScriptPromise(script_state, result);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.h b/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.h
index d3665109766..7803eb7cee0 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.h
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_operations.h
@@ -14,6 +14,7 @@ namespace blink {
class UnderlyingSourceBase;
class ExceptionState;
+class MessagePort;
class ScriptState;
// This class has various methods for ReadableStream[Reader] implemented with
@@ -39,6 +40,7 @@ class CORE_EXPORT ReadableStreamOperations {
public:
// createReadableStreamWithExternalController
+ // Instantiates ReadableStream defined in the script and returns it.
// If the caller supplies an invalid strategy (e.g. one that returns
// negative sizes, or doesn't have appropriate properties), or an exception
// occurs for another reason, this will return an empty value.
@@ -46,6 +48,13 @@ class CORE_EXPORT ReadableStreamOperations {
UnderlyingSourceBase*,
ScriptValue strategy);
+ // createReadableStream
+ // Instantiates ReadableStream defined in the script and returns it.
+ static ScriptValue CreateReadableStream(ScriptState*,
+ ScriptValue underlying_source,
+ ScriptValue strategy,
+ ExceptionState& exception_state);
+
// createBuiltInCountQueuingStrategy
// If the constructor throws, this will return an empty value.
static ScriptValue CreateCountQueuingStrategy(ScriptState*,
@@ -121,13 +130,36 @@ class CORE_EXPORT ReadableStreamOperations {
// ReadableStreamTee
// This function assumes |IsReadableStream(stream)| and |!IsLocked(stream)|
- // Returns without setting new_stream1 or new_stream2 if an error occurs.
- // Exceptions are caught and rethrown on |exception_state|.
- static void Tee(ScriptState*,
- ScriptValue stream,
- ScriptValue* new_stream1,
- ScriptValue* new_stream2,
- ExceptionState&);
+ static ScriptValue Tee(ScriptState*, ScriptValue stream, ExceptionState&);
+
+ // ReadableStreamSerialize. The MessagePort passed in must be one half of a
+ // MessageChannel. The other half can later be passed to Deserialize to
+ // produce an equivalent ReadableStream in a different context.
+ static void Serialize(ScriptState*,
+ ScriptValue stream,
+ MessagePort* port,
+ ExceptionState&);
+
+ // ReadableStreamDeserialize returns a new ReadableStream in the current
+ // context given a MessagePort which is bound to one which was previously
+ // passed to Serialize().
+ static ScriptValue Deserialize(ScriptState*, MessagePort*, ExceptionState&);
+
+ // ReadableStreamCancel
+ // This function assumes |IsReadableStream(stream)|
+ static ScriptPromise Cancel(ScriptState*,
+ ScriptValue stream,
+ ScriptValue reason,
+ ExceptionState& exception_state);
+
+ // ReadableStreamPipeTo
+ // This function assumes |IsReadableStream(stream)|, |!IsLocked(stream)|,
+ // |IsWritableStream(destination)| and |!IsLocked(destination)|.
+ static ScriptPromise PipeTo(ScriptState*,
+ ScriptValue stream,
+ ScriptValue destination,
+ ScriptValue options,
+ ExceptionState& exception_state);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_operations_test.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_operations_test.cc
index 17abd6959d0..8ad8e81b3b4 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_operations_test.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_operations_test.cc
@@ -11,14 +11,19 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/messaging/message_channel.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/streams/readable_stream_default_controller_wrapper.h"
-#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
+#include "third_party/blink/renderer/core/streams/test_underlying_source.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "v8/include/v8.h"
namespace blink {
@@ -104,18 +109,6 @@ class ReaderFunction : public ScriptFunction {
Member<Iteration> iteration_;
};
-class TestUnderlyingSource final : public UnderlyingSourceBase {
- public:
- explicit TestUnderlyingSource(ScriptState* script_state)
- : UnderlyingSourceBase(script_state) {}
-
- // Just expose the controller methods for easy testing
- void Enqueue(ScriptValue value) { Controller()->Enqueue(value); }
- void Close() { Controller()->Close(); }
- void GetError(ScriptValue value) { Controller()->GetError(value); }
- double DesiredSize() { return Controller()->DesiredSize(); }
-};
-
TEST(ReadableStreamOperationsTest, IsReadableStream) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
@@ -138,8 +131,18 @@ TEST(ReadableStreamOperationsTest, IsReadableStream) {
.value_or(true));
ScriptValue stream = EvalWithPrintingError(&scope, "new ReadableStream()");
EXPECT_FALSE(stream.IsEmpty());
+ EXPECT_FALSE(ReadableStreamOperations::IsReadableStream(
+ scope.GetScriptState(), stream, ASSERT_NO_EXCEPTION)
+ .value_or(false));
+ ASSERT_TRUE(V8ReadableStream::HasInstance(stream.V8Value().As<v8::Object>(),
+ scope.GetIsolate()));
+
+ ScriptValue internal_stream =
+ V8ReadableStream::ToImpl(stream.V8Value().As<v8::Object>())
+ ->GetInternalStream(scope.GetScriptState());
+ ASSERT_FALSE(internal_stream.IsEmpty());
EXPECT_TRUE(ReadableStreamOperations::IsReadableStream(
- scope.GetScriptState(), stream, ASSERT_NO_EXCEPTION)
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION)
.value_or(false));
}
@@ -174,31 +177,36 @@ TEST(ReadableStreamOperationsTest, IsReadableStreamDefaultReaderInvalid) {
TEST(ReadableStreamOperationsTest, GetReader) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
- ScriptValue stream = EvalWithPrintingError(&scope, "new ReadableStream()");
- EXPECT_FALSE(stream.IsEmpty());
+ auto* stream =
+ ReadableStream::Create(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
- EXPECT_FALSE(ReadableStreamOperations::IsLocked(scope.GetScriptState(),
- stream, ASSERT_NO_EXCEPTION)
- .value_or(true));
+ ScriptValue internal_stream =
+ stream->GetInternalStream(scope.GetScriptState());
+ ASSERT_FALSE(internal_stream.IsEmpty());
+
+ EXPECT_EQ(ReadableStreamOperations::IsLocked(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
ScriptValue reader;
- reader = ReadableStreamOperations::GetReader(scope.GetScriptState(), stream,
- ASSERT_NO_EXCEPTION);
- EXPECT_TRUE(ReadableStreamOperations::IsLocked(scope.GetScriptState(), stream,
- ASSERT_NO_EXCEPTION)
- .value_or(false));
+ reader = ReadableStreamOperations::GetReader(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION);
ASSERT_FALSE(reader.IsEmpty());
+ EXPECT_EQ(ReadableStreamOperations::IsLocked(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
- EXPECT_FALSE(ReadableStreamOperations::IsReadableStream(
- scope.GetScriptState(), reader, ASSERT_NO_EXCEPTION)
- .value_or(true));
- EXPECT_TRUE(ReadableStreamOperations::IsReadableStreamDefaultReader(
- scope.GetScriptState(), reader, ASSERT_NO_EXCEPTION)
- .value_or(false));
+ EXPECT_EQ(ReadableStreamOperations::IsReadableStream(
+ scope.GetScriptState(), reader, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(ReadableStreamOperations::IsReadableStreamDefaultReader(
+ scope.GetScriptState(), reader, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
// Already locked!
DummyExceptionStateForTesting exception_state;
- reader = ReadableStreamOperations::GetReader(scope.GetScriptState(), stream,
- exception_state);
+ reader = ReadableStreamOperations::GetReader(
+ scope.GetScriptState(), internal_stream, exception_state);
EXPECT_TRUE(exception_state.HadException());
EXPECT_TRUE(reader.IsEmpty());
}
@@ -206,19 +214,21 @@ TEST(ReadableStreamOperationsTest, GetReader) {
TEST(ReadableStreamOperationsTest, IsDisturbed) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
- ScriptValue stream =
- EvalWithPrintingError(&scope, "stream = new ReadableStream()");
- EXPECT_FALSE(stream.IsEmpty());
+ auto* stream =
+ ReadableStream::Create(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
- EXPECT_FALSE(ReadableStreamOperations::IsDisturbed(
- scope.GetScriptState(), stream, ASSERT_NO_EXCEPTION)
- .value_or(true));
+ ScriptValue internal_stream =
+ stream->GetInternalStream(scope.GetScriptState());
+ EXPECT_EQ(ReadableStreamOperations::IsDisturbed(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
- ASSERT_FALSE(EvalWithPrintingError(&scope, "stream.cancel()").IsEmpty());
+ stream->cancel(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
- EXPECT_TRUE(ReadableStreamOperations::IsDisturbed(scope.GetScriptState(),
- stream, ASSERT_NO_EXCEPTION)
- .value_or(false));
+ EXPECT_EQ(ReadableStreamOperations::IsDisturbed(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
}
TEST(ReadableStreamOperationsTest, Read) {
@@ -346,15 +356,19 @@ TEST(ReadableStreamOperationsTest,
scope.GetScriptState(), 10);
ASSERT_FALSE(strategy.IsEmpty());
- ScriptValue stream = ReadableStreamOperations::CreateReadableStream(
+ ScriptValue internal_stream = ReadableStreamOperations::CreateReadableStream(
scope.GetScriptState(), underlying_source, strategy);
- ASSERT_FALSE(stream.IsEmpty());
+ ASSERT_FALSE(internal_stream.IsEmpty());
+
+ auto* stream = ReadableStream::CreateFromInternalStream(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
v8::Local<v8::Object> global = scope.GetScriptState()->GetContext()->Global();
ASSERT_TRUE(global
->Set(scope.GetContext(),
V8String(scope.GetIsolate(), "stream"),
- stream.V8Value())
+ ToV8(stream, scope.GetScriptState()))
.IsJust());
EXPECT_FALSE(underlying_source->HasPendingActivity());
@@ -373,87 +387,155 @@ TEST(ReadableStreamOperationsTest,
TEST(ReadableStreamOperationsTest, IsReadable) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
- ScriptValue readable = EvalWithPrintingError(&scope, "new ReadableStream()");
- ScriptValue closed = EvalWithPrintingError(
- &scope, "new ReadableStream({start: c => c.close()})");
- ScriptValue errored = EvalWithPrintingError(
- &scope, "new ReadableStream({start: c => c.error()})");
- ASSERT_FALSE(readable.IsEmpty());
- ASSERT_FALSE(closed.IsEmpty());
- ASSERT_FALSE(errored.IsEmpty());
-
- EXPECT_TRUE(ReadableStreamOperations::IsReadable(
- scope.GetScriptState(), readable, ASSERT_NO_EXCEPTION)
- .value_or(false));
- EXPECT_FALSE(ReadableStreamOperations::IsReadable(scope.GetScriptState(),
- closed, ASSERT_NO_EXCEPTION)
- .value_or(true));
- EXPECT_FALSE(ReadableStreamOperations::IsReadable(
- scope.GetScriptState(), errored, ASSERT_NO_EXCEPTION)
- .value_or(true));
+
+ auto* readable =
+ ReadableStream::Create(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(readable);
+
+ auto* closing_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* closed = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), closing_source, 0);
+ ASSERT_TRUE(closed);
+ closing_source->Close();
+
+ auto* erroring_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* errored = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), erroring_source, 0);
+ ASSERT_TRUE(errored);
+ erroring_source->SetError(
+ ScriptValue(scope.GetScriptState(), v8::Undefined(scope.GetIsolate())));
+
+ EXPECT_EQ(ReadableStreamOperations::IsReadable(
+ scope.GetScriptState(),
+ readable->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+ EXPECT_EQ(ReadableStreamOperations::IsReadable(
+ scope.GetScriptState(),
+ closed->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(ReadableStreamOperations::IsReadable(
+ scope.GetScriptState(),
+ errored->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
}
TEST(ReadableStreamOperationsTest, IsClosed) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
- ScriptValue readable = EvalWithPrintingError(&scope, "new ReadableStream()");
- ScriptValue closed = EvalWithPrintingError(
- &scope, "new ReadableStream({start: c => c.close()})");
- ScriptValue errored = EvalWithPrintingError(
- &scope, "new ReadableStream({start: c => c.error()})");
- ASSERT_FALSE(readable.IsEmpty());
- ASSERT_FALSE(closed.IsEmpty());
- ASSERT_FALSE(errored.IsEmpty());
-
- EXPECT_FALSE(ReadableStreamOperations::IsClosed(scope.GetScriptState(),
- readable, ASSERT_NO_EXCEPTION)
- .value_or(true));
- EXPECT_TRUE(ReadableStreamOperations::IsClosed(scope.GetScriptState(), closed,
- ASSERT_NO_EXCEPTION)
- .value_or(false));
- EXPECT_FALSE(ReadableStreamOperations::IsClosed(scope.GetScriptState(),
- errored, ASSERT_NO_EXCEPTION)
- .value_or(true));
+
+ ReadableStream* readable =
+ ReadableStream::Create(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(readable);
+
+ auto* closing_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* closed = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), closing_source, 0);
+ ASSERT_TRUE(closed);
+ closing_source->Close();
+
+ auto* erroring_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* errored = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), erroring_source, 0);
+ ASSERT_TRUE(errored);
+ erroring_source->SetError(
+ ScriptValue(scope.GetScriptState(), v8::Undefined(scope.GetIsolate())));
+
+ EXPECT_EQ(ReadableStreamOperations::IsClosed(
+ scope.GetScriptState(),
+ readable->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(ReadableStreamOperations::IsClosed(
+ scope.GetScriptState(),
+ closed->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+ EXPECT_EQ(ReadableStreamOperations::IsClosed(
+ scope.GetScriptState(),
+ errored->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
}
TEST(ReadableStreamOperationsTest, IsErrored) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
- ScriptValue readable = EvalWithPrintingError(&scope, "new ReadableStream()");
- ScriptValue closed = EvalWithPrintingError(
- &scope, "new ReadableStream({start: c => c.close()})");
- ScriptValue errored = EvalWithPrintingError(
- &scope, "new ReadableStream({start: c => c.error()})");
- ASSERT_FALSE(readable.IsEmpty());
- ASSERT_FALSE(closed.IsEmpty());
- ASSERT_FALSE(errored.IsEmpty());
-
- EXPECT_FALSE(ReadableStreamOperations::IsErrored(
- scope.GetScriptState(), readable, ASSERT_NO_EXCEPTION)
- .value_or(true));
- EXPECT_FALSE(ReadableStreamOperations::IsErrored(scope.GetScriptState(),
- closed, ASSERT_NO_EXCEPTION)
- .value_or(true));
- EXPECT_TRUE(ReadableStreamOperations::IsErrored(scope.GetScriptState(),
- errored, ASSERT_NO_EXCEPTION)
- .value_or(false));
+
+ auto* readable =
+ ReadableStream::Create(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(readable);
+
+ auto* closing_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ ReadableStream* closed = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), closing_source, 0);
+ ASSERT_TRUE(closed);
+ closing_source->Close();
+
+ auto* erroring_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* errored = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), erroring_source, 0);
+ ASSERT_TRUE(errored);
+ erroring_source->SetError(
+ ScriptValue(scope.GetScriptState(), v8::Undefined(scope.GetIsolate())));
+
+ EXPECT_EQ(ReadableStreamOperations::IsErrored(
+ scope.GetScriptState(),
+ readable->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(ReadableStreamOperations::IsErrored(
+ scope.GetScriptState(),
+ closed->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(ReadableStreamOperations::IsErrored(
+ scope.GetScriptState(),
+ errored->GetInternalStream(scope.GetScriptState()),
+ ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
}
TEST(ReadableStreamOperationsTest, Tee) {
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
+ v8::Local<v8::Context> context = scope.GetScriptState()->GetContext();
NonThrowableExceptionState exception_state;
- ScriptValue original =
- EvalWithPrintingError(&scope,
- "var controller;"
- "new ReadableStream({start: c => controller = c})");
- ASSERT_FALSE(original.IsEmpty());
- ScriptValue new1, new2;
- ReadableStreamOperations::Tee(scope.GetScriptState(), original, &new1, &new2,
- exception_state);
-
- ASSERT_FALSE(new1.IsEmpty());
- ASSERT_FALSE(new2.IsEmpty());
+ auto* source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), source, 0);
+ ASSERT_TRUE(stream);
+
+ ScriptValue result = ReadableStreamOperations::Tee(
+ scope.GetScriptState(), stream->GetInternalStream(scope.GetScriptState()),
+ exception_state);
+ ASSERT_FALSE(result.IsEmpty());
+ ASSERT_TRUE(result.IsObject());
+
+ v8::Local<v8::Value> v8_branch1, v8_branch2;
+ ASSERT_TRUE(
+ result.V8Value().As<v8::Object>()->Get(context, 0).ToLocal(&v8_branch1));
+ ASSERT_TRUE(
+ result.V8Value().As<v8::Object>()->Get(context, 1).ToLocal(&v8_branch2));
+
+ ScriptValue new1(scope.GetScriptState(), v8_branch1);
+ ScriptValue new2(scope.GetScriptState(), v8_branch2);
+
+ ASSERT_TRUE(ReadableStreamOperations::IsReadableStream(
+ scope.GetScriptState(), new1, ASSERT_NO_EXCEPTION)
+ .value_or(true));
+ ASSERT_TRUE(ReadableStreamOperations::IsReadableStream(
+ scope.GetScriptState(), new2, ASSERT_NO_EXCEPTION)
+ .value_or(true));
ScriptValue reader1 = ReadableStreamOperations::GetReader(
scope.GetScriptState(), new1, exception_state);
@@ -478,8 +560,8 @@ TEST(ReadableStreamOperationsTest, Tee) {
EXPECT_FALSE(it1->IsSet());
EXPECT_FALSE(it2->IsSet());
- ASSERT_FALSE(
- EvalWithPrintingError(&scope, "controller.enqueue('hello')").IsEmpty());
+ source->Enqueue(ScriptValue(scope.GetScriptState(),
+ V8String(scope.GetIsolate(), "hello")));
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
EXPECT_TRUE(it1->IsSet());
@@ -492,6 +574,48 @@ TEST(ReadableStreamOperationsTest, Tee) {
EXPECT_EQ("hello", it2->Value());
}
+TEST(ReadableStreamOperationsTest, Serialize) {
+ RuntimeEnabledFeatures::SetTransferableStreamsEnabled(true);
+
+ V8TestingScope scope;
+ TryCatchScope try_catch_scope(scope.GetIsolate());
+ auto* source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ scope.GetScriptState(), source, 0);
+ ASSERT_TRUE(stream);
+
+ source->Enqueue(ScriptValue(scope.GetScriptState(),
+ V8String(scope.GetIsolate(), "hello")));
+ ScriptValue internal_stream =
+ stream->GetInternalStream(scope.GetScriptState());
+ MessageChannel* channel = MessageChannel::Create(scope.GetExecutionContext());
+ ReadableStreamOperations::Serialize(scope.GetScriptState(), internal_stream,
+ channel->port1(), ASSERT_NO_EXCEPTION);
+ EXPECT_TRUE(ReadableStreamOperations::IsLocked(
+ scope.GetScriptState(), internal_stream, ASSERT_NO_EXCEPTION));
+ ScriptValue transferred = ReadableStreamOperations::Deserialize(
+ scope.GetScriptState(), channel->port2(), ASSERT_NO_EXCEPTION);
+ ASSERT_FALSE(transferred.IsEmpty());
+ ScriptValue reader = ReadableStreamOperations::GetReader(
+ scope.GetScriptState(), transferred, ASSERT_NO_EXCEPTION);
+ ASSERT_FALSE(reader.IsEmpty());
+ Iteration* it = new Iteration();
+ ReadableStreamOperations::DefaultReaderRead(scope.GetScriptState(), reader)
+ .Then(ReaderFunction::CreateFunction(scope.GetScriptState(), it),
+ ReadableStreamOperationsTestNotReached::CreateFunction(
+ scope.GetScriptState()));
+ // Let the message pass through the MessagePort.
+ test::RunPendingTasks();
+ // Let the Read promise resolve.
+ v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
+
+ EXPECT_TRUE(it->IsSet());
+ EXPECT_TRUE(it->IsValid());
+ EXPECT_FALSE(it->IsDone());
+ EXPECT_EQ("hello", it->Value());
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc
new file mode 100644
index 00000000000..6147c9603a6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc
@@ -0,0 +1,435 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.h"
+#include "third_party/blink/renderer/core/messaging/message_channel.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_default_controller_wrapper.h"
+#include "third_party/blink/renderer/core/streams/test_underlying_source.h"
+#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+namespace {
+
+// Web platform tests test ReadableStream more thoroughly from scripts.
+class ReadableStreamTest : public testing::Test {
+ public:
+ base::Optional<String> ReadAll(V8TestingScope& scope,
+ ReadableStream* stream) {
+ ScriptState* script_state = scope.GetScriptState();
+ v8::Isolate* isolate = script_state->GetIsolate();
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Local<v8::Value> v8_stream = ToV8(stream, context->Global(), isolate);
+ v8::Local<v8::Object> global = context->Global();
+
+ bool set_result = false;
+ if (!global->Set(context, V8String(isolate, "stream"), v8_stream)
+ .To(&set_result)) {
+ ADD_FAILURE();
+ return base::nullopt;
+ }
+
+ const char script[] =
+ R"JS(;
+result = undefined;
+async function readAll(stream) {
+ const reader = stream.getReader();
+ let temp = "";
+ while (true) {
+ const v = await reader.read();
+ if (v.done) {
+ result = temp;
+ return;
+ }
+ temp = temp + v.value;
+ }
+}
+readAll(stream);
+)JS";
+
+ if (EvalWithPrintingError(&scope, script).IsEmpty()) {
+ ADD_FAILURE();
+ return base::nullopt;
+ }
+
+ while (true) {
+ v8::Local<v8::Value> result;
+ if (!global->Get(context, V8String(isolate, "result")).ToLocal(&result)) {
+ ADD_FAILURE();
+ return base::nullopt;
+ }
+ if (!result->IsUndefined()) {
+ DCHECK(result->IsString());
+ return ToCoreString(result.As<v8::String>());
+ }
+
+ // Need to run the event loop for the Serialize test to pass messages
+ // through the MessagePort.
+ test::RunPendingTasks();
+
+ // Allow Promises to resolve.
+ v8::MicrotasksScope::PerformCheckpoint(isolate);
+ }
+ NOTREACHED();
+ return base::nullopt;
+ }
+};
+
+TEST_F(ReadableStreamTest, CreateWithoutArguments) {
+ V8TestingScope scope;
+
+ ReadableStream* stream =
+ ReadableStream::Create(scope.GetScriptState(), scope.GetExceptionState());
+ ASSERT_TRUE(stream);
+ ASSERT_FALSE(scope.GetExceptionState().HadException());
+}
+
+TEST_F(ReadableStreamTest, CreateWithUnderlyingSourceOnly) {
+ V8TestingScope scope;
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ ScriptValue js_underlying_source = ScriptValue(
+ scope.GetScriptState(),
+ ToV8(underlying_source, scope.GetScriptState()->GetContext()->Global(),
+ scope.GetScriptState()->GetIsolate()));
+
+ EXPECT_FALSE(underlying_source->IsStartCalled());
+
+ ReadableStream* stream = ReadableStream::Create(
+ scope.GetScriptState(), js_underlying_source, scope.GetExceptionState());
+
+ ASSERT_TRUE(stream);
+ ASSERT_FALSE(scope.GetExceptionState().HadException());
+ EXPECT_TRUE(underlying_source->IsStartCalled());
+}
+
+TEST_F(ReadableStreamTest, CreateWithFullArguments) {
+ V8TestingScope scope;
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ ScriptValue js_underlying_source = ScriptValue(
+ scope.GetScriptState(),
+ ToV8(underlying_source, scope.GetScriptState()->GetContext()->Global(),
+ scope.GetScriptState()->GetIsolate()));
+ ScriptValue js_empty_strategy = EvalWithPrintingError(&scope, "{}");
+ ASSERT_FALSE(js_empty_strategy.IsEmpty());
+ ReadableStream* stream =
+ ReadableStream::Create(scope.GetScriptState(), js_underlying_source,
+ js_empty_strategy, scope.GetExceptionState());
+ ASSERT_TRUE(stream);
+ ASSERT_FALSE(scope.GetExceptionState().HadException());
+ EXPECT_TRUE(underlying_source->IsStartCalled());
+}
+
+TEST_F(ReadableStreamTest, CreateWithPathologicalStrategy) {
+ V8TestingScope scope;
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
+ ScriptValue js_underlying_source = ScriptValue(
+ scope.GetScriptState(),
+ ToV8(underlying_source, scope.GetScriptState()->GetContext()->Global(),
+ scope.GetScriptState()->GetIsolate()));
+ ScriptValue js_pathological_strategy =
+ EvalWithPrintingError(&scope, "({get size() { throw Error('e'); }})");
+ ASSERT_FALSE(js_pathological_strategy.IsEmpty());
+
+ ReadableStream* stream = ReadableStream::Create(
+ scope.GetScriptState(), js_underlying_source, js_pathological_strategy,
+ scope.GetExceptionState());
+ ASSERT_FALSE(stream);
+ ASSERT_TRUE(scope.GetExceptionState().HadException());
+ EXPECT_FALSE(underlying_source->IsStartCalled());
+}
+
+// Testing getReader, locked, IsLocked and IsDisturbed.
+TEST_F(ReadableStreamTest, GetReader) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ ScriptValue js_underlying_source =
+ ScriptValue(script_state,
+ ToV8(underlying_source, script_state->GetContext()->Global(),
+ script_state->GetIsolate()));
+ ReadableStream* stream = ReadableStream::Create(
+ script_state, js_underlying_source, ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
+
+ EXPECT_EQ(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+
+ ScriptValue reader = stream->getReader(script_state, ASSERT_NO_EXCEPTION);
+
+ EXPECT_TRUE(stream->locked(script_state, ASSERT_NO_EXCEPTION));
+ EXPECT_EQ(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+ EXPECT_EQ(stream->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+
+ ASSERT_TRUE(reader.V8Value()->IsObject());
+ v8::Local<v8::Object> v8_reader = reader.V8Value().As<v8::Object>();
+
+ v8::Local<v8::Value> v8_read;
+ ASSERT_TRUE(v8_reader
+ ->Get(script_state->GetContext(),
+ V8String(script_state->GetIsolate(), "read"))
+ .ToLocal(&v8_read));
+ ASSERT_TRUE(v8_read->IsFunction());
+
+ EXPECT_EQ(stream->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+
+ v8::Local<v8::Value> v8_read_result;
+ v8::Local<v8::Value> args[] = {};
+ ASSERT_TRUE(v8_read.As<v8::Function>()
+ ->Call(script_state->GetContext(), v8_reader, 0, args)
+ .ToLocal(&v8_read_result));
+
+ EXPECT_EQ(stream->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+}
+
+TEST_F(ReadableStreamTest, Cancel) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ ScriptValue js_underlying_source =
+ ScriptValue(script_state,
+ ToV8(underlying_source, script_state->GetContext()->Global(),
+ script_state->GetIsolate()));
+ ReadableStream* stream = ReadableStream::Create(
+ script_state, js_underlying_source, ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
+
+ EXPECT_FALSE(underlying_source->IsCancelled());
+ EXPECT_FALSE(underlying_source->IsCancelledWithUndefined());
+ EXPECT_FALSE(underlying_source->IsCancelledWithNull());
+
+ stream->cancel(script_state, ASSERT_NO_EXCEPTION);
+
+ EXPECT_TRUE(underlying_source->IsCancelled());
+ EXPECT_TRUE(underlying_source->IsCancelledWithUndefined());
+ EXPECT_FALSE(underlying_source->IsCancelledWithNull());
+}
+
+TEST_F(ReadableStreamTest, CancelWithNull) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ ScriptValue js_underlying_source =
+ ScriptValue(script_state,
+ ToV8(underlying_source, script_state->GetContext()->Global(),
+ script_state->GetIsolate()));
+ ReadableStream* stream = ReadableStream::Create(
+ script_state, js_underlying_source, ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
+
+ EXPECT_FALSE(underlying_source->IsCancelled());
+ EXPECT_FALSE(underlying_source->IsCancelledWithUndefined());
+ EXPECT_FALSE(underlying_source->IsCancelledWithNull());
+
+ stream->cancel(
+ script_state,
+ ScriptValue(script_state, v8::Null(script_state->GetIsolate())),
+ ASSERT_NO_EXCEPTION);
+
+ EXPECT_TRUE(underlying_source->IsCancelled());
+ EXPECT_FALSE(underlying_source->IsCancelledWithUndefined());
+ EXPECT_TRUE(underlying_source->IsCancelledWithNull());
+}
+
+// TODO(yhirano): Write tests for pipeThrough and pipeTo.
+
+TEST_F(ReadableStreamTest, Tee) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ ScriptValue js_underlying_source =
+ ScriptValue(script_state,
+ ToV8(underlying_source, script_state->GetContext()->Global(),
+ script_state->GetIsolate()));
+ ReadableStream* stream = ReadableStream::Create(
+ script_state, js_underlying_source, ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
+
+ underlying_source->Enqueue(
+ ScriptValue(script_state, V8String(script_state->GetIsolate(), "hello")));
+ underlying_source->Enqueue(
+ ScriptValue(script_state, V8String(script_state->GetIsolate(), ", bye")));
+ underlying_source->Close();
+
+ ReadableStream* branch1 = nullptr;
+ ReadableStream* branch2 = nullptr;
+ stream->Tee(script_state, &branch1, &branch2, ASSERT_NO_EXCEPTION);
+
+ EXPECT_EQ(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+ EXPECT_EQ(stream->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+
+ ASSERT_TRUE(branch1);
+ ASSERT_TRUE(branch2);
+
+ EXPECT_EQ(branch1->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(branch1->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(branch2->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+ EXPECT_EQ(branch2->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+
+ auto result1 = ReadAll(scope, branch1);
+ ASSERT_TRUE(result1);
+ EXPECT_EQ(*result1, "hello, bye");
+
+ EXPECT_EQ(stream->IsDisturbed(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+
+ auto result2 = ReadAll(scope, branch2);
+ ASSERT_TRUE(result2);
+ EXPECT_EQ(*result2, "hello, bye");
+}
+
+TEST_F(ReadableStreamTest, Close) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+
+ ASSERT_TRUE(stream);
+
+ EXPECT_EQ(stream->IsReadable(script_state, exception_state),
+ base::make_optional(true));
+ EXPECT_EQ(stream->IsClosed(script_state, exception_state),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsErrored(script_state, exception_state),
+ base::make_optional(false));
+
+ underlying_source->Close();
+
+ EXPECT_EQ(stream->IsReadable(script_state, exception_state),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsClosed(script_state, exception_state),
+ base::make_optional(true));
+ EXPECT_EQ(stream->IsErrored(script_state, exception_state),
+ base::make_optional(false));
+}
+
+TEST_F(ReadableStreamTest, Error) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+
+ ASSERT_TRUE(stream);
+
+ EXPECT_EQ(stream->IsReadable(script_state, exception_state),
+ base::make_optional(true));
+ EXPECT_EQ(stream->IsClosed(script_state, exception_state),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsErrored(script_state, exception_state),
+ base::make_optional(false));
+
+ underlying_source->SetError(
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())));
+
+ EXPECT_EQ(stream->IsReadable(script_state, exception_state),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsClosed(script_state, exception_state),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsErrored(script_state, exception_state),
+ base::make_optional(true));
+}
+
+TEST_F(ReadableStreamTest, LockAndDisturb) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+ ExceptionState& exception_state = scope.GetExceptionState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+
+ ASSERT_TRUE(stream);
+
+ EXPECT_EQ(stream->IsLocked(script_state, exception_state),
+ base::make_optional(false));
+ EXPECT_EQ(stream->IsDisturbed(script_state, exception_state),
+ base::make_optional(false));
+
+ stream->LockAndDisturb(script_state, exception_state);
+ ASSERT_FALSE(exception_state.HadException());
+
+ EXPECT_EQ(stream->IsLocked(script_state, exception_state),
+ base::make_optional(true));
+ EXPECT_EQ(stream->IsDisturbed(script_state, exception_state),
+ base::make_optional(true));
+}
+
+TEST_F(ReadableStreamTest, Serialize) {
+ RuntimeEnabledFeatures::SetTransferableStreamsEnabled(true);
+
+ V8TestingScope scope;
+ auto* script_state = scope.GetScriptState();
+
+ auto* underlying_source =
+ MakeGarbageCollected<TestUnderlyingSource>(script_state);
+ auto* stream = ReadableStream::CreateWithCountQueueingStrategy(
+ script_state, underlying_source, 0);
+ ASSERT_TRUE(stream);
+
+ MessageChannel* channel = MessageChannel::Create(scope.GetExecutionContext());
+
+ stream->Serialize(script_state, channel->port1(), ASSERT_NO_EXCEPTION);
+ EXPECT_TRUE(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION));
+
+ auto* transferred = ReadableStream::Deserialize(
+ script_state, channel->port2(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(transferred);
+
+ underlying_source->Enqueue(
+ ScriptValue(script_state, V8String(script_state->GetIsolate(), "hello")));
+ underlying_source->Enqueue(
+ ScriptValue(script_state, V8String(script_state->GetIsolate(), ", bye")));
+ underlying_source->Close();
+
+ EXPECT_EQ(ReadAll(scope, transferred),
+ base::make_optional<String>("hello, bye"));
+}
+
+} // namespace
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/test_underlying_source.h b/chromium/third_party/blink/renderer/core/streams/test_underlying_source.h
new file mode 100644
index 00000000000..5bbd7dcede1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/test_underlying_source.h
@@ -0,0 +1,58 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TEST_UNDERLYING_SOURCE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TEST_UNDERLYING_SOURCE_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_default_controller_wrapper.h"
+#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+
+namespace blink {
+
+// This class is for testing.
+class TestUnderlyingSource final : public UnderlyingSourceBase {
+ public:
+ explicit TestUnderlyingSource(ScriptState* script_state)
+ : UnderlyingSourceBase(script_state) {}
+
+ // Just expose the controller methods for easy testing
+ void Enqueue(ScriptValue value) { Controller()->Enqueue(value); }
+ void Close() { Controller()->Close(); }
+ void SetError(ScriptValue value) { Controller()->GetError(value); }
+ double DesiredSize() { return Controller()->DesiredSize(); }
+
+ ScriptPromise Start(ScriptState* script_state) override {
+ DCHECK(!is_start_called_);
+ is_start_called_ = true;
+ return ScriptPromise::CastUndefined(script_state);
+ }
+ ScriptPromise Cancel(ScriptState* script_state, ScriptValue reason) override {
+ DCHECK(!is_cancelled_);
+ DCHECK(!is_cancelled_with_undefined_);
+ DCHECK(!is_cancelled_with_null_);
+
+ is_cancelled_ = true;
+ is_cancelled_with_undefined_ = reason.V8Value()->IsUndefined();
+ is_cancelled_with_null_ = reason.V8Value()->IsNull();
+ return ScriptPromise::CastUndefined(script_state);
+ }
+
+ bool IsStartCalled() const { return is_start_called_; }
+ bool IsCancelled() const { return is_cancelled_; }
+ bool IsCancelledWithUndefined() const { return is_cancelled_with_undefined_; }
+ bool IsCancelledWithNull() const { return is_cancelled_with_null_; }
+
+ private:
+ bool is_start_called_ = false;
+ bool is_cancelled_ = false;
+ bool is_cancelled_with_undefined_ = false;
+ bool is_cancelled_with_null_ = false;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TEST_UNDERLYING_SOURCE_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream.cc b/chromium/third_party/blink/renderer/core/streams/transform_stream.cc
index a117c44cfcf..066821136b1 100644
--- a/chromium/third_party/blink/renderer/core/streams/transform_stream.cc
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream.cc
@@ -9,8 +9,10 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/streams/transform_stream_default_controller.h"
#include "third_party/blink/renderer/core/streams/transform_stream_transformer.h"
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
@@ -123,6 +125,59 @@ TransformStream::TransformStream() = default;
TransformStream::~TransformStream() = default;
+TransformStream* TransformStream::Create(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ ScriptValue undefined(script_state,
+ v8::Undefined(script_state->GetIsolate()));
+ return Create(script_state, undefined, undefined, undefined, exception_state);
+}
+
+TransformStream* TransformStream::Create(
+ ScriptState* script_state,
+ ScriptValue transform_stream_transformer,
+ ExceptionState& exception_state) {
+ ScriptValue undefined(script_state,
+ v8::Undefined(script_state->GetIsolate()));
+ return Create(script_state, transform_stream_transformer, undefined,
+ undefined, exception_state);
+}
+
+TransformStream* TransformStream::Create(
+ ScriptState* script_state,
+ ScriptValue transform_stream_transformer,
+ ScriptValue writable_strategy,
+ ExceptionState& exception_state) {
+ ScriptValue undefined(script_state,
+ v8::Undefined(script_state->GetIsolate()));
+ return Create(script_state, transform_stream_transformer, writable_strategy,
+ undefined, exception_state);
+}
+
+TransformStream* TransformStream::Create(ScriptState* script_state,
+ ScriptValue transformer,
+ ScriptValue writable_strategy,
+ ScriptValue readable_strategy,
+ ExceptionState& exception_state) {
+ auto* ts = MakeGarbageCollected<TransformStream>();
+
+ v8::Local<v8::Value> args[] = {transformer.V8Value(),
+ writable_strategy.V8Value(),
+ readable_strategy.V8Value()};
+ v8::Local<v8::Value> stream;
+ {
+ v8::TryCatch block(script_state->GetIsolate());
+ if (!V8ScriptRunner::CallExtra(script_state, "createTransformStream", args)
+ .ToLocal(&stream)) {
+ DCHECK(block.HasCaught());
+ exception_state.RethrowV8Exception(block.Exception());
+ return nullptr;
+ }
+ }
+ DCHECK(stream->IsObject());
+ ts->InitInternal(script_state, stream.As<v8::Object>(), exception_state);
+ return ts->stream_.IsEmpty() ? nullptr : ts;
+}
+
void TransformStream::Init(TransformStreamTransformer* transformer,
ScriptState* script_state,
ExceptionState& exception_state) {
@@ -131,49 +186,62 @@ void TransformStream::Init(TransformStreamTransformer* transformer,
auto flush_algorithm = Algorithm::Create<FlushAlgorithm>(
transformer, script_state, exception_state);
v8::Local<v8::Value> args[] = {transform_algorithm, flush_algorithm};
- v8::TryCatch block(script_state->GetIsolate());
v8::Local<v8::Value> stream;
- if (!V8ScriptRunner::CallExtra(script_state, "createTransformStreamSimple",
- args)
- .ToLocal(&stream)) {
- DCHECK(block.HasCaught());
- exception_state.RethrowV8Exception(block.Exception());
- return;
+ {
+ v8::TryCatch block(script_state->GetIsolate());
+ if (!V8ScriptRunner::CallExtra(script_state, "createTransformStreamSimple",
+ args)
+ .ToLocal(&stream)) {
+ DCHECK(block.HasCaught());
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
}
- DCHECK(!block.HasCaught());
DCHECK(stream->IsObject());
- stream_.Set(script_state->GetIsolate(), stream);
-}
-
-ScriptValue TransformStream::Readable(ScriptState* script_state,
- ExceptionState& exception_state) const {
- return Accessor("getTransformStreamReadable", script_state, exception_state);
-}
-
-ScriptValue TransformStream::Writable(ScriptState* script_state,
- ExceptionState& exception_state) const {
- return Accessor("getTransformStreamWritable", script_state, exception_state);
+ InitInternal(script_state, stream.As<v8::Object>(), exception_state);
}
void TransformStream::Trace(Visitor* visitor) {
visitor->Trace(stream_);
+ visitor->Trace(readable_);
+ visitor->Trace(writable_);
+ ScriptWrappable::Trace(visitor);
}
-ScriptValue TransformStream::Accessor(const char* accessor_function_name,
- ScriptState* script_state,
- ExceptionState& exception_state) const {
- v8::Local<v8::Value> result;
- v8::Local<v8::Value> args[] = {stream_.NewLocal(script_state->GetIsolate())};
- DCHECK(args[0]->IsObject());
+void TransformStream::InitInternal(ScriptState* script_state,
+ v8::Local<v8::Object> stream,
+ ExceptionState& exception_state) {
+ v8::Local<v8::Value> readable, writable;
+ v8::Local<v8::Value> args[] = {stream};
v8::TryCatch block(script_state->GetIsolate());
- if (!V8ScriptRunner::CallExtra(script_state, accessor_function_name, args)
- .ToLocal(&result)) {
- DCHECK(block.HasCaught());
+ if (!V8ScriptRunner::CallExtra(script_state, "getTransformStreamReadable",
+ args)
+ .ToLocal(&readable)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+ if (!V8ScriptRunner::CallExtra(script_state, "getTransformStreamWritable",
+ args)
+ .ToLocal(&writable)) {
exception_state.RethrowV8Exception(block.Exception());
- return ScriptValue();
+ return;
}
- DCHECK(!block.HasCaught());
- return ScriptValue(script_state, result);
+
+ DCHECK(readable->IsObject());
+ readable_ = ReadableStream::CreateFromInternalStream(
+ script_state, readable.As<v8::Object>(), exception_state);
+
+ if (!readable_)
+ return;
+
+ DCHECK(writable->IsObject());
+ writable_ = WritableStream::CreateFromInternalStream(
+ script_state, writable.As<v8::Object>(), exception_state);
+
+ if (!writable_)
+ return;
+
+ stream_.Set(script_state->GetIsolate(), stream);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream.h b/chromium/third_party/blink/renderer/core/streams/transform_stream.h
index 1fb4cead703..45149039855 100644
--- a/chromium/third_party/blink/renderer/core/streams/transform_stream.h
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream.h
@@ -6,19 +6,24 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFORM_STREAM_H_
#include "base/macros.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/heap/member.h"
#include "v8/include/v8.h"
namespace blink {
class ExceptionState;
class ScriptState;
-class ScriptValue;
+class ReadableStream;
class TransformStreamTransformer;
class Visitor;
+class WritableStream;
// Creates and wraps a JavaScript TransformStream object with a transformation
// defined in C++. Provides access to the readable and writable streams.
@@ -30,20 +35,40 @@ class Visitor;
// two-stage construction. After calling the constructor, store the reference
// in a TraceWrapperMember before calling Init(). Init() must always be called
// before using the instance.
-class CORE_EXPORT TransformStream final
- : public GarbageCollectedFinalized<TransformStream> {
+class CORE_EXPORT TransformStream final : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
public:
TransformStream();
- ~TransformStream();
+ ~TransformStream() override;
+
+ // |Create| functions internally call Init().
+ static TransformStream* Create(ScriptState*, ExceptionState&);
+ static TransformStream* Create(ScriptState*,
+ ScriptValue transformer,
+ ExceptionState&);
+ static TransformStream* Create(ScriptState*,
+ ScriptValue transformer,
+ ScriptValue writable_strategy,
+ ExceptionState&);
+ static TransformStream* Create(ScriptState*,
+ ScriptValue transformer,
+ ScriptValue writable_strategy,
+ ScriptValue readable_strategy,
+ ExceptionState&);
// If HadException is true on return, the object is invalid and should be
// destroyed.
void Init(TransformStreamTransformer*, ScriptState*, ExceptionState&);
- ScriptValue Readable(ScriptState*, ExceptionState&) const;
- ScriptValue Writable(ScriptState*, ExceptionState&) const;
+ // IDL attributes
+ ReadableStream* readable() const { return readable_; }
+ WritableStream* writable() const { return writable_; }
+
+ ReadableStream* Readable() const { return readable_; }
+ WritableStream* Writable() const { return writable_; }
- void Trace(Visitor*);
+ void Trace(Visitor*) override;
private:
// These are class-scoped to avoid name clashes in jumbo builds.
@@ -51,12 +76,13 @@ class CORE_EXPORT TransformStream final
class FlushAlgorithm;
class TransformAlgorithm;
- // Common implementation for Readable() and Writable() accessors.
- ScriptValue Accessor(const char* accessor_function_name,
- ScriptState*,
- ExceptionState&) const;
+ void InitInternal(ScriptState*,
+ v8::Local<v8::Object> stream,
+ ExceptionState&);
TraceWrapperV8Reference<v8::Value> stream_;
+ TraceWrapperMember<ReadableStream> readable_;
+ TraceWrapperMember<WritableStream> writable_;
DISALLOW_COPY_AND_ASSIGN(TransformStream);
};
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream.idl b/chromium/third_party/blink/renderer/core/streams/transform_stream.idl
new file mode 100644
index 00000000000..31a44c7a440
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream.idl
@@ -0,0 +1,16 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://streams.spec.whatwg.org/#ts-class
+[
+ Exposed=(Window,Worker,Worklet),
+ Constructor(optional any transformer,
+ optional any writableStrategy,
+ optional any readableStrategy),
+ RaisesException=Constructor,
+ ConstructorCallWith=ScriptState
+] interface TransformStream {
+ [NotEnumerable] readonly attribute ReadableStream readable;
+ [NotEnumerable] readonly attribute WritableStream writable;
+};
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream_test.cc b/chromium/third_party/blink/renderer/core/streams/transform_stream_test.cc
index 26247670aed..26d78b97e3b 100644
--- a/chromium/third_party/blink/renderer/core/streams/transform_stream_test.cc
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream_test.cc
@@ -11,10 +11,13 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
#include "third_party/blink/renderer/core/streams/transform_stream_default_controller.h"
#include "third_party/blink/renderer/core/streams/transform_stream_transformer.h"
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/core/testing/garbage_collected_script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -29,7 +32,6 @@
namespace blink {
namespace {
-
using ::testing::_;
using ::testing::Mock;
@@ -53,20 +55,18 @@ class TransformStreamTest : public ::testing::Test {
// and copies them onto the global object so they can be accessed by Eval().
void CopyReadableAndWritableToGlobal(const V8TestingScope& scope) {
auto* script_state = scope.GetScriptState();
- ScriptValue readable =
- Stream()->Readable(script_state, ASSERT_NO_EXCEPTION);
- ScriptValue writable =
- Stream()->Writable(script_state, ASSERT_NO_EXCEPTION);
+ ReadableStream* readable = Stream()->Readable();
+ WritableStream* writable = Stream()->Writable();
v8::Local<v8::Object> global = script_state->GetContext()->Global();
EXPECT_TRUE(global
->Set(scope.GetContext(),
V8String(scope.GetIsolate(), "readable"),
- readable.V8Value())
+ ToV8(readable, script_state))
.IsJust());
EXPECT_TRUE(global
->Set(scope.GetContext(),
V8String(scope.GetIsolate(), "writable"),
- writable.V8Value())
+ ToV8(writable, script_state))
.IsJust());
}
@@ -87,7 +87,7 @@ class TransformStreamTest : public ::testing::Test {
: GarbageCollectedScriptWrappable("Holder"),
this_as_v8_value_(
ScriptValue(script_state, ToV8(this, script_state))),
- stream_(new TransformStream()) {}
+ stream_(MakeGarbageCollected<TransformStream>()) {}
// Destroy() must be called to break the reference cycle.
void Destroy() {
@@ -142,17 +142,10 @@ TEST_F(TransformStreamTest, Construct) {
TEST_F(TransformStreamTest, Accessors) {
V8TestingScope scope;
Init(new IdentityTransformer(), scope.GetScriptState(), ASSERT_NO_EXCEPTION);
- ScriptValue readable =
- Stream()->Readable(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
- ScriptValue writable =
- Stream()->Writable(scope.GetScriptState(), ASSERT_NO_EXCEPTION);
- EXPECT_TRUE(readable.IsObject());
- EXPECT_TRUE(writable.IsObject());
- EXPECT_TRUE(ReadableStreamOperations::IsReadableStream(
- scope.GetScriptState(), readable, ASSERT_NO_EXCEPTION)
- .value_or(false));
- // TODO(ricea): Check writable too once we have a wrapper for
- // IsWritableStream().
+ ReadableStream* readable = Stream()->Readable();
+ WritableStream* writable = Stream()->Writable();
+ EXPECT_TRUE(readable);
+ EXPECT_TRUE(writable);
}
TEST_F(TransformStreamTest, TransformIsCalled) {
@@ -313,9 +306,8 @@ TEST_F(TransformStreamTest, EnqueueFromTransform) {
"const writer = writable.getWriter();\n"
"writer.write('a');\n");
- ScriptValue readable = Stream()->Readable(script_state, ASSERT_NO_EXCEPTION);
- ScriptValue reader = ReadableStreamOperations::GetReader(
- script_state, readable, ASSERT_NO_EXCEPTION);
+ ReadableStream* readable = Stream()->Readable();
+ ScriptValue reader = readable->getReader(script_state, ASSERT_NO_EXCEPTION);
bool chunk_seen = false;
ReadableStreamOperations::DefaultReaderRead(script_state, reader)
.Then(ExpectChunkIsString::Create(script_state, "a", &chunk_seen),
@@ -355,9 +347,8 @@ TEST_F(TransformStreamTest, EnqueueFromFlush) {
"const writer = writable.getWriter();\n"
"writer.close();\n");
- ScriptValue readable = Stream()->Readable(script_state, ASSERT_NO_EXCEPTION);
- ScriptValue reader = ReadableStreamOperations::GetReader(
- script_state, readable, ASSERT_NO_EXCEPTION);
+ ReadableStream* readable = Stream()->Readable();
+ ScriptValue reader = readable->getReader(script_state, ASSERT_NO_EXCEPTION);
bool chunkSeen = false;
ReadableStreamOperations::DefaultReaderRead(script_state, reader)
.Then(ExpectChunkIsString::Create(script_state, "a", &chunkSeen),
@@ -388,9 +379,8 @@ TEST_F(TransformStreamTest, ThrowFromTransform) {
"const writer = writable.getWriter();\n"
"writer.write('a');\n");
- ScriptValue readable = Stream()->Readable(script_state, ASSERT_NO_EXCEPTION);
- ScriptValue reader = ReadableStreamOperations::GetReader(
- script_state, readable, ASSERT_NO_EXCEPTION);
+ ReadableStream* readable = Stream()->Readable();
+ ScriptValue reader = readable->getReader(script_state, ASSERT_NO_EXCEPTION);
bool readableTypeErrorThrown = false;
bool writableTypeErrorThrown = false;
ReadableStreamOperations::DefaultReaderRead(script_state, reader)
@@ -429,9 +419,8 @@ TEST_F(TransformStreamTest, ThrowFromFlush) {
"const writer = writable.getWriter();\n"
"writer.close();\n");
- ScriptValue readable = Stream()->Readable(script_state, ASSERT_NO_EXCEPTION);
- ScriptValue reader = ReadableStreamOperations::GetReader(
- script_state, readable, ASSERT_NO_EXCEPTION);
+ ReadableStream* readable = Stream()->Readable();
+ ScriptValue reader = readable->getReader(script_state, ASSERT_NO_EXCEPTION);
bool readableTypeErrorThrown = false;
bool writableTypeErrorThrown = false;
ReadableStreamOperations::DefaultReaderRead(script_state, reader)
@@ -447,56 +436,5 @@ TEST_F(TransformStreamTest, ThrowFromFlush) {
EXPECT_TRUE(writableTypeErrorThrown);
}
-// Verify that the JavaScript TransformStream object is kept alive by the C++
-// TransformStream object.
-TEST_F(TransformStreamTest, SurvivesGarbageCollectionWhenTraced) {
- auto page_holder = DummyPageHolder::Create();
- Persistent<ScriptState> script_state =
- ToScriptStateForMainWorld(page_holder->GetDocument().GetFrame());
- {
- ScriptState::Scope scope(script_state);
- Init(new IdentityTransformer(), script_state, ASSERT_NO_EXCEPTION);
- }
- Microtask::PerformCheckpoint(script_state->GetIsolate());
- script_state->GetIsolate()->RequestGarbageCollectionForTesting(
- v8::Isolate::kFullGarbageCollection);
- ScriptState::Scope scope(script_state);
- ScriptValue readable = Stream()->Readable(script_state, ASSERT_NO_EXCEPTION);
- EXPECT_TRUE(readable.IsObject());
- EXPECT_TRUE(ReadableStreamOperations::IsReadableStream(script_state, readable,
- ASSERT_NO_EXCEPTION)
- .value_or(false));
-}
-
-// Verify that JS TransformStream is collected when it is not reachable from V8.
-// TODO(ricea): Remove this test when unified garbage collection is introduced,
-// as it will fail.
-#if GTEST_HAS_DEATH_TEST
-#define MAYBE_IsGarbageCollectedWhenNotTraced IsGarbageCollectedWhenNotTraced
-#else
-#define MAYBE_IsGarbageCollectedWhenNotTraced \
- DISABLED_IsGarbageCollectedWhenNotTraced
-#endif
-TEST_F(TransformStreamTest, MAYBE_IsGarbageCollectedWhenNotTraced) {
- auto page_holder = DummyPageHolder::Create();
- Persistent<ScriptState> script_state =
- ToScriptStateForMainWorld(page_holder->GetDocument().GetFrame());
- {
- ScriptState::Scope scope(script_state);
- Init(new IdentityTransformer(), script_state, ASSERT_NO_EXCEPTION);
- }
- Persistent<TransformStream> stream = Stream();
- ClearHolder();
- Microtask::PerformCheckpoint(script_state->GetIsolate());
- script_state->GetIsolate()->RequestGarbageCollectionForTesting(
- v8::Isolate::kFullGarbageCollection);
- ScriptState::Scope scope(script_state);
- // This emits a warning that death tests are unsafe with threads, but it works
- // anyway. The crash message depends on whether DCHECK is enabled or not, so
- // the regex it is required to match is empty.
- EXPECT_DEATH(stream->Readable(script_state, ASSERT_NO_EXCEPTION), "");
-}
-
} // namespace
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/underlying_source_base.cc b/chromium/third_party/blink/renderer/core/streams/underlying_source_base.cc
index 0d5834660d4..3f7700e7eaa 100644
--- a/chromium/third_party/blink/renderer/core/streams/underlying_source_base.cc
+++ b/chromium/third_party/blink/renderer/core/streams/underlying_source_base.cc
@@ -18,7 +18,8 @@ ScriptPromise UnderlyingSourceBase::startWrapper(ScriptState* script_state,
// construct multiple streams).
DCHECK(!controller_);
- controller_ = new ReadableStreamDefaultControllerWrapper(js_controller);
+ controller_ = MakeGarbageCollected<ReadableStreamDefaultControllerWrapper>(
+ js_controller);
return Start(script_state);
}
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream.cc b/chromium/third_party/blink/renderer/core/streams/writable_stream.cc
new file mode 100644
index 00000000000..26ea2b2dd08
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream.cc
@@ -0,0 +1,256 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream.h"
+#include "third_party/blink/renderer/core/messaging/message_port.h"
+#include "third_party/blink/renderer/core/streams/retain_wrapper_during_construction.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+
+namespace blink {
+
+void WritableStream::Init(ScriptState* script_state,
+ ScriptValue underlying_sink,
+ ScriptValue strategy,
+ ExceptionState& exception_state) {
+ v8::Local<v8::Object> internal_stream;
+ v8::TryCatch block(script_state->GetIsolate());
+
+ if (!CreateInternalStream(script_state, underlying_sink.V8Value(),
+ strategy.V8Value())
+ .ToLocal(&internal_stream)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+
+ if (!InitInternal(script_state, internal_stream)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return;
+ }
+}
+
+WritableStream* WritableStream::Create(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ return Create(
+ script_state,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+WritableStream* WritableStream::Create(ScriptState* script_state,
+ ScriptValue underlying_sink,
+ ExceptionState& exception_state) {
+ return Create(
+ script_state, underlying_sink,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+WritableStream* WritableStream::Create(ScriptState* script_state,
+ ScriptValue underlying_sink,
+ ScriptValue strategy,
+ ExceptionState& exception_state) {
+ auto* stream = MakeGarbageCollected<WritableStream>();
+ stream->Init(script_state, underlying_sink, strategy, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+
+ return stream;
+}
+
+WritableStream* WritableStream::CreateFromInternalStream(
+ ScriptState* script_state,
+ v8::Local<v8::Object> internal_stream,
+ ExceptionState& exception_state) {
+ v8::TryCatch block(script_state->GetIsolate());
+ auto* stream = MakeGarbageCollected<WritableStream>();
+ if (!stream->InitInternal(script_state, internal_stream)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return nullptr;
+ }
+ return stream;
+}
+
+bool WritableStream::InitInternal(ScriptState* script_state,
+ v8::Local<v8::Object> internal_stream) {
+ v8::Isolate* isolate = script_state->GetIsolate();
+
+#if DCHECK_IS_ON()
+ v8::Local<v8::Value> args[] = {internal_stream};
+ v8::Local<v8::Value> result_value;
+
+ if (!V8ScriptRunner::CallExtra(script_state, "IsWritableStream", args)
+ .ToLocal(&result_value)) {
+ DLOG(FATAL) << "Failing to call IsWritableStream for DCHECK.";
+ return false;
+ }
+ DCHECK(result_value->BooleanValue(isolate));
+#endif // DCHECK_IS_ON()
+
+ internal_stream_.Set(isolate, internal_stream);
+
+ v8::Local<v8::Value> wrapper = ToV8(this, script_state);
+ if (wrapper.IsEmpty())
+ return false;
+
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Local<v8::Object> bindings =
+ context->GetExtrasBindingObject().As<v8::Object>();
+ v8::Local<v8::Value> symbol_value;
+ if (!bindings->Get(context, V8String(isolate, "internalWritableStreamSymbol"))
+ .ToLocal(&symbol_value)) {
+ return false;
+ }
+
+ if (wrapper.As<v8::Object>()
+ ->Set(context, symbol_value.As<v8::Symbol>(),
+ internal_stream_.NewLocal(isolate))
+ .IsNothing()) {
+ return false;
+ }
+
+ return RetainWrapperDuringConstruction(this, script_state);
+}
+
+v8::MaybeLocal<v8::Object> WritableStream::CreateInternalStream(
+ ScriptState* script_state,
+ v8::Local<v8::Value> underlying_sink,
+ v8::Local<v8::Value> strategy) {
+ v8::Local<v8::Value> args[] = {underlying_sink, strategy};
+ v8::Local<v8::Value> stream;
+
+ if (!V8ScriptRunner::CallExtra(script_state, "createWritableStream", args)
+ .ToLocal(&stream)) {
+ return v8::MaybeLocal<v8::Object>();
+ }
+
+ DCHECK(stream->IsObject());
+ return v8::MaybeLocal<v8::Object>(stream.As<v8::Object>());
+}
+
+void WritableStream::Trace(Visitor* visitor) {
+ visitor->Trace(internal_stream_);
+ ScriptWrappable::Trace(visitor);
+}
+
+bool WritableStream::locked(ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ auto result = IsLocked(script_state, exception_state);
+
+ return !result || *result;
+}
+
+ScriptPromise WritableStream::abort(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ return abort(
+ script_state,
+ ScriptValue(script_state, v8::Undefined(script_state->GetIsolate())),
+ exception_state);
+}
+
+ScriptPromise WritableStream::abort(ScriptState* script_state,
+ ScriptValue reason,
+ ExceptionState& exception_state) {
+ if (locked(script_state, exception_state) &&
+ !exception_state.HadException()) {
+ exception_state.ThrowTypeError("Cannot abort a locked stream");
+ }
+
+ v8::Local<v8::Value> args[] = {
+ internal_stream_.NewLocal(script_state->GetIsolate()), reason.V8Value()};
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> result;
+
+ if (!V8ScriptRunner::CallExtra(script_state, "WritableStreamAbort", args)
+ .ToLocal(&result)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptPromise();
+ }
+ return ScriptPromise(script_state, result);
+}
+
+ScriptValue WritableStream::getWriter(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> args[] = {
+ internal_stream_.NewLocal(script_state->GetIsolate())};
+ v8::Local<v8::Value> result;
+
+ if (!V8ScriptRunner::CallExtra(script_state,
+ "AcquireWritableStreamDefaultWriter", args)
+ .ToLocal(&result)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return ScriptValue();
+ }
+ return ScriptValue(script_state, result);
+}
+
+base::Optional<bool> WritableStream::IsLocked(
+ ScriptState* script_state,
+ ExceptionState& exception_state) const {
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> args[] = {
+ internal_stream_.NewLocal(script_state->GetIsolate())};
+ v8::Local<v8::Value> result_value;
+
+ if (!V8ScriptRunner::CallExtra(script_state, "IsWritableStreamLocked", args)
+ .ToLocal(&result_value)) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return base::nullopt;
+ }
+ return result_value->BooleanValue(script_state->GetIsolate());
+}
+
+void WritableStream::Serialize(ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ DCHECK(port);
+ DCHECK(RuntimeEnabledFeatures::TransferableStreamsEnabled());
+ v8::TryCatch block(script_state->GetIsolate());
+ v8::Local<v8::Value> port_v8_value = ToV8(port, script_state);
+ DCHECK(!port_v8_value.IsEmpty());
+ v8::Local<v8::Value> args[] = {ToV8(this, script_state), port_v8_value};
+ V8ScriptRunner::CallExtra(script_state, "WritableStreamSerialize", args);
+ if (block.HasCaught()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ }
+}
+
+// static
+WritableStream* WritableStream::Deserialize(ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ // We need to execute V8 Extras JavaScript to create the new WritableStream.
+ // We will not run author code.
+ auto* isolate = script_state->GetIsolate();
+ v8::Isolate::AllowJavascriptExecutionScope allow_js(isolate);
+ DCHECK(port);
+ DCHECK(RuntimeEnabledFeatures::TransferableStreamsEnabled());
+ v8::TryCatch block(isolate);
+ v8::Local<v8::Value> port_v8 = ToV8(port, script_state);
+ DCHECK(!port_v8.IsEmpty());
+ v8::Local<v8::Value> args[] = {port_v8};
+ ScriptValue internal_stream(
+ script_state, V8ScriptRunner::CallExtra(
+ script_state, "WritableStreamDeserialize", args));
+ if (block.HasCaught()) {
+ exception_state.RethrowV8Exception(block.Exception());
+ return nullptr;
+ }
+ DCHECK(!internal_stream.IsEmpty());
+ return CreateFromInternalStream(script_state, internal_stream,
+ exception_state);
+}
+
+ScriptValue WritableStream::GetInternalStream(ScriptState* script_state) const {
+ return ScriptValue(script_state,
+ internal_stream_.NewLocal(script_state->GetIsolate()));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream.h b/chromium/third_party/blink/renderer/core/streams/writable_stream.h
new file mode 100644
index 00000000000..c2326c72673
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream.h
@@ -0,0 +1,96 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_WRITABLE_STREAM_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_WRITABLE_STREAM_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+class MessagePort;
+
+// This is an implementation of the corresponding IDL interface.
+// Use TraceWrapperMember to hold a reference to an instance of this class.
+class CORE_EXPORT WritableStream : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ // Call one of Init functions before using the instance.
+ WritableStream() = default;
+ ~WritableStream() override = default;
+
+ // If an error happens, |exception_state.HadException()| will be true, and
+ // |this| will not be usable after that.
+ void Init(ScriptState*,
+ ScriptValue underlying_sink,
+ ScriptValue strategy,
+ ExceptionState& exception_state);
+
+ // Create* functions call Init* internally and return null when an error
+ // happens.
+ static WritableStream* Create(ScriptState*, ExceptionState&);
+ static WritableStream* Create(ScriptState*,
+ ScriptValue underlying_sink,
+ ExceptionState&);
+ static WritableStream* Create(ScriptState*,
+ ScriptValue underlying_sink,
+ ScriptValue strategy,
+ ExceptionState&);
+ static WritableStream* CreateFromInternalStream(
+ ScriptState* script_state,
+ ScriptValue internal_stream,
+ ExceptionState& exception_state) {
+ DCHECK(internal_stream.IsObject());
+ return CreateFromInternalStream(script_state,
+ internal_stream.V8Value().As<v8::Object>(),
+ exception_state);
+ }
+ static WritableStream* CreateFromInternalStream(
+ ScriptState*,
+ v8::Local<v8::Object> internal_stream,
+ ExceptionState&);
+
+ void Trace(Visitor* visitor) override;
+
+ // IDL defined functions
+ bool locked(ScriptState*, ExceptionState&) const;
+ ScriptPromise abort(ScriptState*, ExceptionState&);
+ ScriptPromise abort(ScriptState*, ScriptValue reason, ExceptionState&);
+ ScriptValue getWriter(ScriptState*, ExceptionState&);
+
+ base::Optional<bool> IsLocked(ScriptState*, ExceptionState&) const;
+
+ // Serialize this stream to |port|. The stream will be locked by this
+ // operation.
+ void Serialize(ScriptState*, MessagePort* port, ExceptionState&);
+
+ // Given a |port| which is entangled with a MessagePort that was previously
+ // passed to Serialize(), returns a new WritableStream which behaves like it
+ // was the original.
+ static WritableStream* Deserialize(ScriptState*,
+ MessagePort* port,
+ ExceptionState&);
+
+ ScriptValue GetInternalStream(ScriptState*) const;
+
+ private:
+ bool InitInternal(ScriptState*, v8::Local<v8::Object> internal_stream);
+
+ static v8::MaybeLocal<v8::Object> CreateInternalStream(
+ ScriptState* script_state,
+ v8::Local<v8::Value> underlying_sink,
+ v8::Local<v8::Value> strategy);
+
+ TraceWrapperV8Reference<v8::Object> internal_stream_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_WRITABLE_STREAM_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream.idl b/chromium/third_party/blink/renderer/core/streams/writable_stream.idl
new file mode 100644
index 00000000000..32593ecf4b8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream.idl
@@ -0,0 +1,19 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://streams.spec.whatwg.org/#ws-class
+[
+ Exposed=(Window,Worker,Worklet),
+ // TODO(yhirano): Remove CustomConstructor. See https://crbug.com/906476.
+ CustomConstructor(optional any underlyingSink, optional any strategy),
+ RaisesException=Constructor,
+ ConstructorCallWith=ScriptState
+] interface WritableStream {
+ // As long as we use V8Extras, anything can raise an exception.
+ [RaisesException, CallWith=ScriptState, NotEnumerable] readonly attribute boolean locked;
+
+ [RaisesException, CallWith=ScriptState, NotEnumerable] Promise<void> abort(
+ optional any reason);
+ [RaisesException, CallWith=ScriptState, NotEnumerable] any getWriter();
+};
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc b/chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc
new file mode 100644
index 00000000000..024a6d8a8c3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc
@@ -0,0 +1,111 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this sink code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/writable_stream.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_extras_test_utils.h"
+#include "third_party/blink/renderer/core/messaging/message_channel.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+namespace {
+
+// Web platform tests test WritableStream more thoroughly from scripts.
+class WritableStreamTest : public testing::Test {
+ public:
+};
+
+TEST_F(WritableStreamTest, CreateWithoutArguments) {
+ V8TestingScope scope;
+
+ WritableStream* stream =
+ WritableStream::Create(scope.GetScriptState(), scope.GetExceptionState());
+ ASSERT_TRUE(stream);
+ ASSERT_FALSE(scope.GetExceptionState().HadException());
+}
+
+// Testing getWriter, locked and IsLocked.
+TEST_F(WritableStreamTest, GetWriter) {
+ V8TestingScope scope;
+ ScriptState* script_state = scope.GetScriptState();
+
+ WritableStream* stream =
+ WritableStream::Create(script_state, ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
+
+ EXPECT_FALSE(stream->locked(script_state, ASSERT_NO_EXCEPTION));
+ EXPECT_EQ(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(false));
+
+ ScriptValue writer = stream->getWriter(script_state, ASSERT_NO_EXCEPTION);
+
+ EXPECT_TRUE(stream->locked(script_state, ASSERT_NO_EXCEPTION));
+ EXPECT_EQ(stream->IsLocked(script_state, ASSERT_NO_EXCEPTION),
+ base::make_optional(true));
+}
+
+TEST_F(WritableStreamTest, Serialize) {
+ ScopedTransferableStreamsForTest enable_transferable_streams(true);
+
+ V8TestingScope scope;
+ auto* script_state = scope.GetScriptState();
+
+ const char underlying_sink_script[] =
+ R"JS(
+const underlying_sink = {
+ write(chunk) {
+ result = chunk;
+ }
+};
+underlying_sink)JS";
+ ScriptValue underlying_sink =
+ EvalWithPrintingError(&scope, underlying_sink_script);
+ ASSERT_FALSE(underlying_sink.IsEmpty());
+ auto* stream = WritableStream::Create(script_state, underlying_sink,
+ ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(stream);
+
+ MessageChannel* channel = MessageChannel::Create(scope.GetExecutionContext());
+
+ stream->Serialize(script_state, channel->port1(), ASSERT_NO_EXCEPTION);
+ EXPECT_TRUE(stream->locked(script_state, ASSERT_NO_EXCEPTION));
+
+ auto* transferred = WritableStream::Deserialize(
+ script_state, channel->port2(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(transferred);
+
+ ScriptValue writer =
+ transferred->getWriter(script_state, ASSERT_NO_EXCEPTION);
+ v8::Local<v8::Context> context = script_state->GetContext();
+ v8::Isolate* isolate = script_state->GetIsolate();
+ v8::Local<v8::Object> global = context->Global();
+ ASSERT_TRUE(
+ global->Set(context, V8String(isolate, "writer"), writer.V8Value())
+ .FromMaybe(false));
+ EvalWithPrintingError(&scope, "writer.write('a')");
+ // Run the message loop to allow messages to be delivered.
+ test::RunPendingTasks();
+ // Allow Promises to resolve.
+ v8::MicrotasksScope::PerformCheckpoint(isolate);
+
+ v8::Local<v8::Value> result;
+ ASSERT_TRUE(
+ global->Get(context, V8String(isolate, "result")).ToLocal(&result));
+ ASSERT_TRUE(result->IsString());
+ EXPECT_EQ(ToCoreString(result.As<v8::String>()), "a");
+}
+
+} // namespace
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/style/BUILD.gn b/chromium/third_party/blink/renderer/core/style/BUILD.gn
index 5906f097d40..d127e27e05d 100644
--- a/chromium/third_party/blink/renderer/core/style/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/style/BUILD.gn
@@ -63,7 +63,6 @@ blink_core_sources("rendering") {
"shadow_list.cc",
"shadow_list.h",
"shape_clip_path_operation.h",
- "shape_value.cc",
"shape_value.h",
"style_content_alignment_data.h",
"style_difference.cc",
@@ -80,6 +79,8 @@ blink_core_sources("rendering") {
"style_image.h",
"style_inherited_variables.cc",
"style_inherited_variables.h",
+ "style_initial_data.cc",
+ "style_initial_data.h",
"style_non_inherited_variables.cc",
"style_non_inherited_variables.h",
"style_offset_rotation.h",
diff --git a/chromium/third_party/blink/renderer/core/style/ComputedStyle.md b/chromium/third_party/blink/renderer/core/style/ComputedStyle.md
index 96fcbd01f95..e0448f785be 100644
--- a/chromium/third_party/blink/renderer/core/style/ComputedStyle.md
+++ b/chromium/third_party/blink/renderer/core/style/ComputedStyle.md
@@ -13,18 +13,18 @@ The files that generate the code in ComputedStyleBase.{h,cpp} include:
## JSON files:
These files are inputs to the generator and tell the generator what shape our fields and functions take. This is a list of all the relevant JSON files (more detailed documentation can be found in the files themselves):
* [css_properties.json5](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/css/css_properties.json5): Contains information for all the CSS properties we support.
-* [computed_style_extra_fields.json5](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/css/computed_style_extra_fields.json5): Specifies fields in ComputedStyle that we would like to generate, but are not CSS properties.
-* [computed_style_diff_functions.json5](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/css/computed_style_diff_functions.json5): Specifies the fields we want to diff in the various diff functions in ComputedStyle. It is used to generate the various diffing functions on ComputedStyle.
+* [computed_style_extra_fields.json5](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/style/computed_style_extra_fields.json5): Specifies fields in ComputedStyle that we would like to generate, but are not CSS properties.
+* [computed_style_diff_functions.json5](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/style/computed_style_diff_functions.json5): Specifies the fields we want to diff in the various diff functions in ComputedStyle. It is used to generate the various diffing functions on ComputedStyle.
## Generator files:
These scripts generate the computed_style_base.{h,cc} files. This is a list of the relevant generator files (more detailed documentation can be found in the files themselves):
-* [make_computed_style_base.py](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/make_computed_style_base.py): Main file that handles the code generation logic. It consumes the JSON inputs provided and outputs fields and groups that encapsulate the structure of ComputedStyle.
+* [make_computed_style_base.py](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/core/style/make_computed_style_base.py): Main file that handles the code generation logic. It consumes the JSON inputs provided and outputs fields and groups that encapsulate the structure of ComputedStyle.
## Template files:
For each generate file, the Python script uses a Jinja template file to format the output:
-* [computed_style_base.h.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/templates/computed_style_base.h.tmpl): Header file with the field and group declarations.
-* [computed_style_base.cc.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/templates/computed_style_base.cc.tmpl): Implementation of various generated helper functions. Notably, contains implementation of functions that use ComputedStyle such as the diffing functions.
-* [computed_style_base_constants.h.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/templates/computed_style_base_constants.h.tmpl): Definitions of generated enums.
+* [computed_style_base.h.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.h.tmpl): Header file with the field and group declarations.
+* [computed_style_base.cc.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base.cc.tmpl): Implementation of various generated helper functions. Notably, contains implementation of functions that use ComputedStyle such as the diffing functions.
+* [computed_style_base_constants.h.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/core/style/templates/computed_style_base_constants.h.tmpl): Definitions of generated enums.
* [fields/*.tmpl](https://cs.chromium.org/chromium/src/third_party/blink/renderer/build/scripts/templates/fields/): These files contain various macros that help us generate accessors for the fields depending on their field_template.
# Understanding where to make changes:
diff --git a/chromium/third_party/blink/renderer/core/style/OWNERS b/chromium/third_party/blink/renderer/core/style/OWNERS
index 7d528afeb3b..070536afc22 100644
--- a/chromium/third_party/blink/renderer/core/style/OWNERS
+++ b/chromium/third_party/blink/renderer/core/style/OWNERS
@@ -1,9 +1,6 @@
+alancutter@chromium.org
andruud@chromium.org
ericwilligers@chromium.org
-shend@chromium.org
-
-# Also core owners
-alancutter@chromium.org
futhark@chromium.org
# COMPONENT: Blink>CSS
diff --git a/chromium/third_party/blink/renderer/core/style/basic_shapes.cc b/chromium/third_party/blink/renderer/core/style/basic_shapes.cc
index a0fc5c75bda..15053f5460d 100644
--- a/chromium/third_party/blink/renderer/core/style/basic_shapes.cc
+++ b/chromium/third_party/blink/renderer/core/style/basic_shapes.cc
@@ -31,8 +31,8 @@
#include "third_party/blink/renderer/core/css/basic_shape_functions.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/path.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/basic_shapes.h b/chromium/third_party/blink/renderer/core/style/basic_shapes.h
index ce888bf44a0..8fceef9f5fd 100644
--- a/chromium/third_party/blink/renderer/core/style/basic_shapes.h
+++ b/chromium/third_party/blink/renderer/core/style/basic_shapes.h
@@ -32,9 +32,9 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/length.h"
-#include "third_party/blink/renderer/platform/length_size.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/style/border_image_length.h b/chromium/third_party/blink/renderer/core/style/border_image_length.h
index 25a49181386..12ec360a327 100644
--- a/chromium/third_party/blink/renderer/core/style/border_image_length.h
+++ b/chromium/third_party/blink/renderer/core/style/border_image_length.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_BORDER_IMAGE_LENGTH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_BORDER_IMAGE_LENGTH_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/border_value.h b/chromium/third_party/blink/renderer/core/style/border_value.h
index e0b2d40a473..46ff11342c1 100644
--- a/chromium/third_party/blink/renderer/core/style/border_value.h
+++ b/chromium/third_party/blink/renderer/core/style/border_value.h
@@ -60,10 +60,6 @@ class BorderValue {
SetWidth(width);
}
- bool NonZero() const {
- return Width() && (style_ != static_cast<unsigned>(EBorderStyle::kNone));
- }
-
bool IsTransparent() const {
return !color_is_current_color_ && !color_.Alpha();
}
diff --git a/chromium/third_party/blink/renderer/core/style/cached_ua_style.h b/chromium/third_party/blink/renderer/core/style/cached_ua_style.h
index d9a108786c5..8d1ff0bb751 100644
--- a/chromium/third_party/blink/renderer/core/style/cached_ua_style.h
+++ b/chromium/third_party/blink/renderer/core/style/cached_ua_style.h
@@ -30,8 +30,8 @@
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/core/style/fill_layer.h"
#include "third_party/blink/renderer/core/style/nine_piece_image.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/length_size.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/computed_style.cc b/chromium/third_party/blink/renderer/core/style/computed_style.cc
index bc497a3c02b..2bf035fc166 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style.cc
+++ b/chromium/third_party/blink/renderer/core/style/computed_style.cc
@@ -60,9 +60,9 @@
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/font_selector.h"
#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/path.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
#include "third_party/blink/renderer/platform/text/capitalize.h"
#include "third_party/blink/renderer/platform/text/character.h"
#include "third_party/blink/renderer/platform/transforms/rotate_transform_operation.h"
@@ -206,8 +206,16 @@ StyleRecalcChange ComputedStyle::StylePropagationDiff(
return kReattach;
}
- if (old_style->ForceLegacyLayout() != new_style->ForceLegacyLayout())
- return kReattach;
+ if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
+ // LayoutNG needs an anonymous inline wrapper if ::first-line is applied.
+ // Also see |LayoutBlockFlow::NeedsAnonymousInlineWrapper()|.
+ if (new_style->HasPseudoStyle(kPseudoIdFirstLine) &&
+ !old_style->HasPseudoStyle(kPseudoIdFirstLine))
+ return kReattach;
+
+ if (old_style->ForceLegacyLayout() != new_style->ForceLegacyLayout())
+ return kReattach;
+ }
bool independent_equal = old_style->IndependentInheritedEqual(*new_style);
bool non_independent_equal =
@@ -407,10 +415,6 @@ bool ComputedStyle::operator==(const ComputedStyle& o) const {
return InheritedEqual(o) && NonInheritedEqual(o);
}
-bool ComputedStyle::IsStyleAvailable() const {
- return this != StyleResolver::StyleNotYetAvailable();
-}
-
const ComputedStyle* ComputedStyle::GetCachedPseudoStyle(PseudoId pid) const {
if (!cached_pseudo_styles_ || !cached_pseudo_styles_->size())
return nullptr;
@@ -536,8 +540,8 @@ StyleDifference ComputedStyle::VisualInvalidationDiff(
if (DiffNeedsPaintInvalidationSubtree(other))
diff.SetNeedsPaintInvalidationSubtree();
- else if (DiffNeedsPaintInvalidationObject(other))
- diff.SetNeedsPaintInvalidationObject();
+ else
+ AdjustDiffForNeedsPaintInvalidationObject(other, diff);
if (DiffNeedsVisualRectUpdate(other))
diff.SetNeedsVisualRectUpdate();
@@ -699,24 +703,46 @@ bool ComputedStyle::DiffNeedsPaintInvalidationSubtree(
return ComputedStyleBase::DiffNeedsPaintInvalidationSubtree(*this, other);
}
-bool ComputedStyle::DiffNeedsPaintInvalidationObject(
- const ComputedStyle& other) const {
- if (ComputedStyleBase::DiffNeedsPaintInvalidationObject(*this, other))
- return true;
+void ComputedStyle::AdjustDiffForNeedsPaintInvalidationObject(
+ const ComputedStyle& other,
+ StyleDifference& diff) const {
+ if (ComputedStyleBase::DiffNeedsPaintInvalidationObject(*this, other) ||
+ !BorderVisuallyEqual(other) || !RadiiEqual(other))
+ diff.SetNeedsPaintInvalidationObject();
- if (!BorderVisuallyEqual(other) || !RadiiEqual(other) ||
- !BackgroundVisuallyEqual(other))
- return true;
+ AdjustDiffForBackgroundVisuallyEqual(other, diff);
+
+ if (diff.NeedsPaintInvalidationObject())
+ return;
if (PaintImagesInternal()) {
for (const auto& image : *PaintImagesInternal()) {
DCHECK(image);
- if (DiffNeedsPaintInvalidationObjectForPaintImage(*image, other))
- return true;
+ if (DiffNeedsPaintInvalidationObjectForPaintImage(*image, other)) {
+ diff.SetNeedsPaintInvalidationObject();
+ return;
+ }
}
}
+}
- return false;
+void ComputedStyle::AdjustDiffForBackgroundVisuallyEqual(
+ const ComputedStyle& other,
+ StyleDifference& diff) const {
+ if (BackgroundColorInternal() != other.BackgroundColorInternal()) {
+ diff.SetNeedsPaintInvalidationObject();
+ if (BackgroundColorInternal().HasAlpha() !=
+ other.BackgroundColorInternal().HasAlpha()) {
+ diff.SetHasAlphaChanged();
+ return;
+ }
+ }
+ if (!BackgroundInternal().VisuallyEqual(other.BackgroundInternal())) {
+ diff.SetNeedsPaintInvalidationObject();
+ // Changes of background fill layers, such as images, may have
+ // changed alpha.
+ diff.SetHasAlphaChanged();
+ }
}
bool ComputedStyle::DiffNeedsPaintInvalidationObjectForPaintImage(
@@ -764,14 +790,18 @@ bool ComputedStyle::CustomPropertiesEqual(
const Vector<AtomicString>& properties,
const ComputedStyle& other) const {
// Short-circuit if neither of the styles have custom properties.
- if (!InheritedVariables() && !NonInheritedVariables() &&
- !other.InheritedVariables() && !other.NonInheritedVariables())
+ if (!HasVariables() && !other.HasVariables())
return true;
for (const AtomicString& property_name : properties) {
if (!DataEquivalent(GetVariable(property_name),
- other.GetVariable(property_name)))
+ other.GetVariable(property_name))) {
+ return false;
+ }
+ if (!DataEquivalent(GetRegisteredVariable(property_name),
+ other.GetRegisteredVariable(property_name))) {
return false;
+ }
}
return true;
@@ -853,7 +883,7 @@ void ComputedStyle::AddCursor(StyleImage* image,
bool hot_spot_specified,
const IntPoint& hot_spot) {
if (!CursorDataInternal())
- SetCursorDataInternal(new CursorList);
+ SetCursorDataInternal(MakeGarbageCollected<CursorList>());
MutableCursorDataInternal()->push_back(
CursorData(image, hot_spot_specified, hot_spot));
}
@@ -1278,21 +1308,6 @@ bool ComputedStyle::CanRenderBorderImage() const {
return border_image && border_image->CanRender() && border_image->IsLoaded();
}
-static bool AllLayersAreFixed(const FillLayer& layer) {
- for (const FillLayer* curr_layer = &layer; curr_layer;
- curr_layer = curr_layer->Next()) {
- if (!curr_layer->GetImage() ||
- curr_layer->Attachment() != EFillAttachment::kFixed)
- return false;
- }
-
- return true;
-}
-
-bool ComputedStyle::HasEntirelyFixedBackground() const {
- return AllLayersAreFixed(BackgroundLayers());
-}
-
const CounterDirectiveMap* ComputedStyle::GetCounterDirectives() const {
return CounterDirectivesInternal().get();
}
@@ -1634,6 +1649,15 @@ const Vector<AppliedTextDecoration>& ComputedStyle::AppliedTextDecorations()
return AppliedTextDecorationsInternal()->GetVector();
}
+static bool HasInitialVariables(const StyleInitialData* initial_data) {
+ return initial_data && initial_data->HasInitialVariables();
+}
+
+bool ComputedStyle::HasVariables() const {
+ return InheritedVariables() || NonInheritedVariables() ||
+ HasInitialVariables(InitialDataInternal().get());
+}
+
StyleInheritedVariables* ComputedStyle::InheritedVariables() const {
return InheritedVariablesInternal().get();
}
@@ -1660,6 +1684,10 @@ StyleNonInheritedVariables& ComputedStyle::MutableNonInheritedVariables() {
return *variables;
}
+void ComputedStyle::SetInitialData(scoped_refptr<StyleInitialData> data) {
+ MutableInitialDataInternal() = std::move(data);
+}
+
void ComputedStyle::SetVariable(const AtomicString& name,
scoped_refptr<CSSVariableData> value,
bool is_inherited_property) {
@@ -1705,7 +1733,36 @@ CSSVariableData* ComputedStyle::GetVariable(const AtomicString& name,
: nullptr;
}
+static const CSSValue* GetInitialRegisteredVariable(
+ const AtomicString& name,
+ const StyleInitialData* initial_data) {
+ if (!initial_data)
+ return nullptr;
+ return initial_data->GetInitialVariable(name);
+}
+
+const CSSValue* ComputedStyle::GetRegisteredVariable(
+ const AtomicString& name,
+ bool is_inherited_property) const {
+ const CSSValue* result =
+ GetNonInitialRegisteredVariable(name, is_inherited_property);
+ if (result)
+ return result;
+ return GetInitialRegisteredVariable(name, InitialDataInternal().get());
+}
+
const CSSValue* ComputedStyle::GetRegisteredVariable(
+ const AtomicString& name) const {
+ const CSSValue* result = GetNonInitialRegisteredVariable(name, false);
+ if (result)
+ return result;
+ result = GetNonInitialRegisteredVariable(name, true);
+ if (result)
+ return result;
+ return GetInitialRegisteredVariable(name, InitialDataInternal().get());
+}
+
+const CSSValue* ComputedStyle::GetNonInitialRegisteredVariable(
const AtomicString& name,
bool is_inherited_property) const {
if (is_inherited_property) {
@@ -1717,17 +1774,6 @@ const CSSValue* ComputedStyle::GetRegisteredVariable(
: nullptr;
}
-const CSSValue* ComputedStyle::GetRegisteredVariable(
- const AtomicString& name) const {
- // Registered custom properties are by default non-inheriting so check there
- // first.
- const CSSValue* result = GetRegisteredVariable(name, false);
- if (result) {
- return result;
- }
- return GetRegisteredVariable(name, true);
-}
-
bool ComputedStyle::SetFontDescription(const FontDescription& v) {
if (FontInternal().GetFontDescription() != v) {
SetFontInternal(Font(v));
diff --git a/chromium/third_party/blink/renderer/core/style/computed_style.h b/chromium/third_party/blink/renderer/core/style/computed_style.h
index f76bd21c97a..63263e883dd 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style.h
+++ b/chromium/third_party/blink/renderer/core/style/computed_style.h
@@ -27,13 +27,13 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_H_
#include <memory>
-#include "third_party/blink/renderer/core/computed_style_base.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/style_auto_color.h"
#include "third_party/blink/renderer/core/css/style_color.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/style/border_value.h"
+#include "third_party/blink/renderer/core/style/computed_style_base.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/style/computed_style_initial_values.h"
#include "third_party/blink/renderer/core/style/cursor_list.h"
@@ -41,12 +41,12 @@
#include "third_party/blink/renderer/core/style/svg_computed_style.h"
#include "third_party/blink/renderer/core/style/transform_origin.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect_outsets.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/geometry/length_box.h"
+#include "third_party/blink/renderer/platform/geometry/length_point.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
-#include "third_party/blink/renderer/platform/length.h"
-#include "third_party/blink/renderer/platform/length_box.h"
-#include "third_party/blink/renderer/platform/length_point.h"
-#include "third_party/blink/renderer/platform/length_size.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
@@ -81,6 +81,7 @@ class StyleContentAlignmentData;
class StyleDifference;
class StyleImage;
class StyleInheritedVariables;
+class StyleInitialData;
class StylePath;
class StyleResolver;
class StyleSelfAlignmentData;
@@ -88,7 +89,7 @@ class TransformationMatrix;
typedef Vector<scoped_refptr<ComputedStyle>, 4> PseudoStyleCache;
-namespace CSSLonghand {
+namespace css_longhand {
class BackgroundColor;
class BorderBottomColor;
@@ -110,7 +111,7 @@ class WebkitTextEmphasisColor;
class WebkitTextFillColor;
class WebkitTextStrokeColor;
-} // namespace CSSLonghand
+} // namespace css_longhand
// ComputedStyle stores the computed value [1] for every CSS property on an
// element and provides the interface between the style engine and the rest of
@@ -182,25 +183,25 @@ class ComputedStyle : public ComputedStyleBase,
// Accesses GetColor().
friend class ComputedStyleUtils;
// These get visited and unvisited colors separately.
- friend class CSSLonghand::BackgroundColor;
- friend class CSSLonghand::BorderBottomColor;
- friend class CSSLonghand::BorderLeftColor;
- friend class CSSLonghand::BorderRightColor;
- friend class CSSLonghand::BorderTopColor;
- friend class CSSLonghand::CaretColor;
- friend class CSSLonghand::Color;
- friend class CSSLonghand::ColumnRuleColor;
- friend class CSSLonghand::FloodColor;
- friend class CSSLonghand::Fill;
- friend class CSSLonghand::LightingColor;
- friend class CSSLonghand::OutlineColor;
- friend class CSSLonghand::StopColor;
- friend class CSSLonghand::Stroke;
- friend class CSSLonghand::TextDecorationColor;
- friend class CSSLonghand::WebkitTapHighlightColor;
- friend class CSSLonghand::WebkitTextEmphasisColor;
- friend class CSSLonghand::WebkitTextFillColor;
- friend class CSSLonghand::WebkitTextStrokeColor;
+ friend class css_longhand::BackgroundColor;
+ friend class css_longhand::BorderBottomColor;
+ friend class css_longhand::BorderLeftColor;
+ friend class css_longhand::BorderRightColor;
+ friend class css_longhand::BorderTopColor;
+ friend class css_longhand::CaretColor;
+ friend class css_longhand::Color;
+ friend class css_longhand::ColumnRuleColor;
+ friend class css_longhand::FloodColor;
+ friend class css_longhand::Fill;
+ friend class css_longhand::LightingColor;
+ friend class css_longhand::OutlineColor;
+ friend class css_longhand::StopColor;
+ friend class css_longhand::Stroke;
+ friend class css_longhand::TextDecorationColor;
+ friend class css_longhand::WebkitTapHighlightColor;
+ friend class css_longhand::WebkitTextEmphasisColor;
+ friend class css_longhand::WebkitTextFillColor;
+ friend class css_longhand::WebkitTextStrokeColor;
// Editing has to only reveal unvisited info.
friend class ApplyStyleCommand;
// Editing has to only reveal unvisited info.
@@ -370,11 +371,12 @@ class ComputedStyle : public ComputedStyleBase,
// background-image
- bool HasBackgroundImage() const { return BackgroundInternal().HasImage(); }
- bool HasFixedBackgroundImage() const {
- return BackgroundInternal().HasFixedImage();
+ bool HasBackgroundImage() const {
+ return BackgroundInternal().AnyLayerHasImage();
+ }
+ bool HasFixedAttachmentBackgroundImage() const {
+ return BackgroundInternal().AnyLayerHasFixedAttachmentImage();
}
- bool HasEntirelyFixedBackground() const;
// background-clip
EFillBox BackgroundClip() const {
@@ -1107,6 +1109,7 @@ class ComputedStyle : public ComputedStyleBase,
void ClearResetDirectives();
// Variables.
+ bool HasVariables() const;
CORE_EXPORT StyleInheritedVariables* InheritedVariables() const;
CORE_EXPORT StyleNonInheritedVariables* NonInheritedVariables() const;
@@ -1131,6 +1134,12 @@ class ComputedStyle : public ComputedStyleBase,
const CSSValue* GetRegisteredVariable(const AtomicString&) const;
+ // Like GetRegisteredVariable, but returns nullptr if the computed value
+ // for the specified variable is the initial value.
+ const CSSValue* GetNonInitialRegisteredVariable(
+ const AtomicString&,
+ bool is_inherited_property) const;
+
// Animations.
CSSAnimationData& AccessAnimations();
const CSSAnimationData* Animations() const {
@@ -1179,7 +1188,8 @@ class ComputedStyle : public ComputedStyleBase,
// Mask utility functions.
bool HasMask() const {
- return MaskInternal().HasImage() || MaskBoxImageInternal().HasImage();
+ return MaskInternal().AnyLayerHasImage() ||
+ MaskBoxImageInternal().HasImage();
}
StyleImage* MaskImage() const { return MaskInternal().GetImage(); }
FillLayer& AccessMaskLayers() { return MutableMaskInternal(); }
@@ -1696,10 +1706,9 @@ class ComputedStyle : public ComputedStyleBase,
return BorderImage().Outset() == o.BorderImage().Outset();
}
- bool BackgroundVisuallyEqual(const ComputedStyle& o) const {
- return BackgroundColorInternal() == o.BackgroundColorInternal() &&
- BackgroundInternal().VisuallyEqual(o.BackgroundInternal());
- }
+ CORE_EXPORT void AdjustDiffForBackgroundVisuallyEqual(
+ const ComputedStyle& o,
+ StyleDifference& diff) const;
void ResetBorder() {
ResetBorderImage();
@@ -1864,6 +1873,7 @@ class ComputedStyle : public ComputedStyleBase,
bool ContainsStyle() const { return Contain() & kContainsStyle; }
bool ContainsLayout() const { return Contain() & kContainsLayout; }
bool ContainsSize() const { return Contain() & kContainsSize; }
+ bool ContainsContent() const { return Contain() & kContainsContent; }
// Display utility functions.
bool IsDisplayReplacedType() const {
@@ -2236,8 +2246,6 @@ class ComputedStyle : public ComputedStyleBase,
bool HasAppearance() const { return Appearance() != kNoControlPart; }
// Other utility functions.
- bool IsStyleAvailable() const;
-
bool RequireTransformOrigin(ApplyTransformOrigin apply_origin,
ApplyMotionPath) const;
@@ -2502,7 +2510,8 @@ class ComputedStyle : public ComputedStyleBase,
const Document&,
const ComputedStyle& other) const;
bool DiffNeedsPaintInvalidationSubtree(const ComputedStyle& other) const;
- bool DiffNeedsPaintInvalidationObject(const ComputedStyle& other) const;
+ void AdjustDiffForNeedsPaintInvalidationObject(const ComputedStyle& other,
+ StyleDifference&) const;
bool DiffNeedsPaintInvalidationObjectForPaintImage(
const StyleImage&,
const ComputedStyle& other) const;
@@ -2520,6 +2529,8 @@ class ComputedStyle : public ComputedStyleBase,
StyleInheritedVariables& MutableInheritedVariables();
StyleNonInheritedVariables& MutableNonInheritedVariables();
+ void SetInitialData(scoped_refptr<StyleInitialData>);
+
PhysicalToLogical<const Length&> PhysicalMarginToLogical(
const ComputedStyle& other) const {
return PhysicalToLogical<const Length&>(
@@ -2590,6 +2601,8 @@ class ComputedStyle : public ComputedStyleBase,
FRIEND_TEST_ALL_PREFIXES(
ComputedStyleTest,
UpdatePropertySpecificDifferencesCompositingReasonsContainsPaint);
+ FRIEND_TEST_ALL_PREFIXES(ComputedStyleTest,
+ UpdatePropertySpecificDifferencesHasAlpha);
};
inline bool ComputedStyle::SetEffectiveZoom(float f) {
diff --git a/chromium/third_party/blink/renderer/core/style/computed_style_constants.h b/chromium/third_party/blink/renderer/core/style/computed_style_constants.h
index f47057902dc..1d31d5be27b 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style_constants.h
+++ b/chromium/third_party/blink/renderer/core/style/computed_style_constants.h
@@ -29,7 +29,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_COMPUTED_STYLE_CONSTANTS_H_
#include <cstddef>
-#include "third_party/blink/renderer/core/computed_style_base_constants.h"
+#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/computed_style_diff_functions.json5 b/chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5
index 4cae09bf50f..4cae09bf50f 100644
--- a/chromium/third_party/blink/renderer/core/css/computed_style_diff_functions.json5
+++ b/chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5
diff --git a/chromium/third_party/blink/renderer/core/css/computed_style_extra_fields.json5 b/chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
index 343ffb99431..2b3222c2948 100644
--- a/chromium/third_party/blink/renderer/core/css/computed_style_extra_fields.json5
+++ b/chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
@@ -227,7 +227,7 @@
name: "VerticalAlignLength",
field_template: "external",
default_value: "Length()",
- include_paths: ["third_party/blink/renderer/platform/length.h"],
+ include_paths: ["third_party/blink/renderer/platform/geometry/length.h"],
type_name: "Length",
field_group: "box",
getter: "GetVerticalAlignLength",
@@ -577,6 +577,17 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
+ name: "InitialData",
+ inherited: true,
+ field_template: "external",
+ type_name: "StyleInitialData",
+ include_paths: ["third_party/blink/renderer/core/style/style_initial_data.h"],
+ default_value: "nullptr",
+ wrapper_pointer_name: "scoped_refptr",
+ field_group: "*",
+ computed_style_custom_functions: ["getter", "setter"],
+ },
+ {
name: "Mask",
field_template: "external",
type_name: "FillLayer",
@@ -851,7 +862,7 @@
field_group: "*->will-change",
default_value: "Vector<CSSPropertyID>()",
include_paths: ["third_party/blink/renderer/platform/wtf/vector.h",
- "third_party/blink/renderer/core/css_property_names.h"],
+ "third_party/blink/renderer/core/css/css_property_names.h"],
},
{
name: "WillChangeContents",
diff --git a/chromium/third_party/blink/renderer/core/style/computed_style_test.cc b/chromium/third_party/blink/renderer/core/style/computed_style_test.cc
index 03e8b360ded..32bf62507b5 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style_test.cc
+++ b/chromium/third_party/blink/renderer/core/style/computed_style_test.cc
@@ -243,6 +243,39 @@ TEST(ComputedStyleTest,
EXPECT_TRUE(diff.CompositingReasonsChanged());
}
+TEST(ComputedStyleTest, UpdateBackgroundColorDifferencesHasAlpha) {
+ scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
+ scoped_refptr<ComputedStyle> other = ComputedStyle::Clone(*style);
+
+ StyleDifference diff;
+ style->AdjustDiffForBackgroundVisuallyEqual(*other, diff);
+ EXPECT_FALSE(diff.HasAlphaChanged());
+
+ style->SetBackgroundColor(StyleColor(Color(255, 255, 255, 255)));
+ other->SetBackgroundColor(StyleColor(Color(255, 255, 255, 128)));
+
+ EXPECT_FALSE(
+ style->VisitedDependentColor(GetCSSPropertyBackgroundColor()).HasAlpha());
+ EXPECT_TRUE(
+ other->VisitedDependentColor(GetCSSPropertyBackgroundColor()).HasAlpha());
+
+ style->AdjustDiffForBackgroundVisuallyEqual(*other, diff);
+ EXPECT_TRUE(diff.HasAlphaChanged());
+}
+
+TEST(ComputedStyleTest, UpdateBackgroundLayerDifferencesHasAlpha) {
+ scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
+ scoped_refptr<ComputedStyle> other = ComputedStyle::Clone(*style);
+
+ StyleDifference diff;
+ style->AdjustDiffForBackgroundVisuallyEqual(*other, diff);
+ EXPECT_FALSE(diff.HasAlphaChanged());
+
+ other->AccessBackgroundLayers().EnsureNext();
+ style->AdjustDiffForBackgroundVisuallyEqual(*other, diff);
+ EXPECT_TRUE(diff.HasAlphaChanged());
+}
+
TEST(ComputedStyleTest, HasOutlineWithCurrentColor) {
scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
EXPECT_FALSE(style->HasOutline());
diff --git a/chromium/third_party/blink/renderer/core/style/content_data.cc b/chromium/third_party/blink/renderer/core/style/content_data.cc
index e438579545d..71af0bcae23 100644
--- a/chromium/third_party/blink/renderer/core/style/content_data.cc
+++ b/chromium/third_party/blink/renderer/core/style/content_data.cc
@@ -35,11 +35,11 @@
namespace blink {
ContentData* ContentData::Create(StyleImage* image) {
- return new ImageContentData(image);
+ return MakeGarbageCollected<ImageContentData>(image);
}
ContentData* ContentData::Create(const String& text) {
- return new TextContentData(text);
+ return MakeGarbageCollected<TextContentData>(text);
}
ContentData* ContentData::Create(std::unique_ptr<CounterContent> counter) {
@@ -47,7 +47,7 @@ ContentData* ContentData::Create(std::unique_ptr<CounterContent> counter) {
}
ContentData* ContentData::Create(QuoteType quote) {
- return new QuoteContentData(quote);
+ return MakeGarbageCollected<QuoteContentData>(quote);
}
ContentData* ContentData::Clone() const {
@@ -90,7 +90,7 @@ LayoutObject* TextContentData::CreateLayoutObject(
PseudoElement& pseudo,
ComputedStyle& pseudo_style) const {
LayoutObject* layout_object =
- LayoutTextFragment::CreateAnonymous(pseudo, text_.Impl());
+ LayoutTextFragment::CreateAnonymous(pseudo_style, pseudo, text_.Impl());
layout_object->SetPseudoStyle(&pseudo_style);
return layout_object;
}
diff --git a/chromium/third_party/blink/renderer/core/style/content_data.h b/chromium/third_party/blink/renderer/core/style/content_data.h
index 90c56f3c03f..9dfcb0e9f53 100644
--- a/chromium/third_party/blink/renderer/core/style/content_data.h
+++ b/chromium/third_party/blink/renderer/core/style/content_data.h
@@ -78,6 +78,8 @@ class ImageContentData final : public ContentData {
friend class ContentData;
public:
+ ImageContentData(StyleImage* image) : image_(image) { DCHECK(image_); }
+
const StyleImage* GetImage() const { return image_.Get(); }
StyleImage* GetImage() { return image_.Get(); }
void SetImage(StyleImage* image) {
@@ -99,8 +101,6 @@ class ImageContentData final : public ContentData {
void Trace(blink::Visitor*) override;
private:
- ImageContentData(StyleImage* image) : image_(image) { DCHECK(image_); }
-
ContentData* CloneInternal() const override {
StyleImage* image = const_cast<StyleImage*>(this->GetImage());
return Create(image);
@@ -115,6 +115,8 @@ class TextContentData final : public ContentData {
friend class ContentData;
public:
+ TextContentData(const String& text) : text_(text) {}
+
const String& GetText() const { return text_; }
void SetText(const String& text) { text_ = text; }
@@ -129,8 +131,6 @@ class TextContentData final : public ContentData {
}
private:
- TextContentData(const String& text) : text_(text) {}
-
ContentData* CloneInternal() const override { return Create(GetText()); }
String text_;
@@ -177,6 +177,8 @@ class QuoteContentData final : public ContentData {
friend class ContentData;
public:
+ QuoteContentData(QuoteType quote) : quote_(quote) {}
+
QuoteType Quote() const { return quote_; }
void SetQuote(QuoteType quote) { quote_ = quote; }
@@ -191,8 +193,6 @@ class QuoteContentData final : public ContentData {
}
private:
- QuoteContentData(QuoteType quote) : quote_(quote) {}
-
ContentData* CloneInternal() const override { return Create(Quote()); }
QuoteType quote_;
diff --git a/chromium/third_party/blink/renderer/core/style/fill_layer.cc b/chromium/third_party/blink/renderer/core/style/fill_layer.cc
index 4d521a02746..55f513f1e4b 100644
--- a/chromium/third_party/blink/renderer/core/style/fill_layer.cc
+++ b/chromium/third_party/blink/renderer/core/style/fill_layer.cc
@@ -79,9 +79,12 @@ FillLayer::FillLayer(EFillLayerType type, bool use_initial_values)
blend_mode_set_(use_initial_values),
mask_source_type_set_(use_initial_values),
type_(static_cast<unsigned>(type)),
- this_or_next_layers_clip_max_(0),
- this_or_next_layers_use_content_box_(0),
- this_or_next_layers_have_local_attachment_(0),
+ layers_clip_max_(0),
+ any_layer_uses_content_box_(false),
+ any_layer_has_image_(false),
+ any_layer_has_local_attachment_image_(false),
+ any_layer_has_fixed_attachment_image_(false),
+ any_layer_has_default_attachment_image_(false),
cached_properties_computed_(false) {}
FillLayer::FillLayer(const FillLayer& o)
@@ -115,9 +118,12 @@ FillLayer::FillLayer(const FillLayer& o)
blend_mode_set_(o.blend_mode_set_),
mask_source_type_set_(o.mask_source_type_set_),
type_(o.type_),
- this_or_next_layers_clip_max_(0),
- this_or_next_layers_use_content_box_(0),
- this_or_next_layers_have_local_attachment_(0),
+ layers_clip_max_(0),
+ any_layer_uses_content_box_(false),
+ any_layer_has_image_(false),
+ any_layer_has_local_attachment_image_(false),
+ any_layer_has_fixed_attachment_image_(false),
+ any_layer_has_default_attachment_image_(false),
cached_properties_computed_(false) {}
FillLayer::~FillLayer() {
@@ -341,29 +347,38 @@ void FillLayer::CullEmptyLayers() {
}
}
-void FillLayer::ComputeCachedPropertiesIfNeeded() const {
- if (cached_properties_computed_)
- return;
- this_or_next_layers_clip_max_ = static_cast<unsigned>(Clip());
- this_or_next_layers_use_content_box_ =
+void FillLayer::ComputeCachedProperties() const {
+ DCHECK(!cached_properties_computed_);
+
+ layers_clip_max_ = static_cast<unsigned>(Clip());
+ any_layer_uses_content_box_ =
Clip() == EFillBox::kContent || Origin() == EFillBox::kContent;
- this_or_next_layers_have_local_attachment_ =
- Attachment() == EFillAttachment::kLocal;
+ any_layer_has_image_ = !!GetImage();
+ any_layer_has_local_attachment_image_ =
+ any_layer_has_image_ && Attachment() == EFillAttachment::kLocal;
+ any_layer_has_fixed_attachment_image_ =
+ any_layer_has_image_ && Attachment() == EFillAttachment::kFixed;
+ any_layer_has_default_attachment_image_ =
+ any_layer_has_image_ && Attachment() == EFillAttachment::kScroll;
cached_properties_computed_ = true;
if (next_) {
next_->ComputeCachedPropertiesIfNeeded();
- this_or_next_layers_clip_max_ = static_cast<unsigned>(EnclosingFillBox(
- ThisOrNextLayersClipMax(), next_->ThisOrNextLayersClipMax()));
- this_or_next_layers_use_content_box_ |=
- next_->this_or_next_layers_use_content_box_;
- this_or_next_layers_have_local_attachment_ |=
- next_->this_or_next_layers_have_local_attachment_;
+ layers_clip_max_ = static_cast<unsigned>(
+ EnclosingFillBox(LayersClipMax(), next_->LayersClipMax()));
+ any_layer_uses_content_box_ |= next_->any_layer_uses_content_box_;
+ any_layer_has_image_ |= next_->any_layer_has_image_;
+ any_layer_has_local_attachment_image_ |=
+ next_->any_layer_has_local_attachment_image_;
+ any_layer_has_fixed_attachment_image_ |=
+ next_->any_layer_has_fixed_attachment_image_;
+ any_layer_has_default_attachment_image_ |=
+ next_->any_layer_has_default_attachment_image_;
}
}
bool FillLayer::ClipOccludesNextLayers() const {
- return Clip() == ThisOrNextLayersClipMax();
+ return Clip() == LayersClipMax();
}
bool FillLayer::ImagesAreLoaded() const {
diff --git a/chromium/third_party/blink/renderer/core/style/fill_layer.h b/chromium/third_party/blink/renderer/core/style/fill_layer.h
index 27fc9a52a71..da0b2ce4746 100644
--- a/chromium/third_party/blink/renderer/core/style/fill_layer.h
+++ b/chromium/third_party/blink/renderer/core/style/fill_layer.h
@@ -29,10 +29,10 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/style/style_image.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
-#include "third_party/blink/renderer/platform/length.h"
-#include "third_party/blink/renderer/platform/length_size.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -217,19 +217,6 @@ class CORE_EXPORT FillLayer {
bool ImagesAreLoaded() const;
- bool HasImage() const {
- if (image_)
- return true;
- return next_ ? next_->HasImage() : false;
- }
-
- bool HasFixedImage() const {
- if (image_ &&
- static_cast<EFillAttachment>(attachment_) == EFillAttachment::kFixed)
- return true;
- return next_ ? next_->HasFixedImage() : false;
- }
-
bool ImageOccludesNextLayers(const Document&, const ComputedStyle&) const;
bool HasRepeatXY() const;
bool ClipOccludesNextLayers() const;
@@ -241,19 +228,30 @@ class CORE_EXPORT FillLayer {
static bool ImagesIdentical(const FillLayer*, const FillLayer*);
- EFillBox ThisOrNextLayersClipMax() const {
+ EFillBox LayersClipMax() const {
+ ComputeCachedPropertiesIfNeeded();
+ return static_cast<EFillBox>(layers_clip_max_);
+ }
+ bool AnyLayerUsesContentBox() const {
ComputeCachedPropertiesIfNeeded();
- return static_cast<EFillBox>(this_or_next_layers_clip_max_);
+ return any_layer_uses_content_box_;
}
- bool ThisOrNextLayersUseContentBox() const {
+ bool AnyLayerHasImage() const {
ComputeCachedPropertiesIfNeeded();
- return this_or_next_layers_use_content_box_;
+ return any_layer_has_image_;
}
- bool ThisOrNextLayersHaveLocalAttachment() const {
+ bool AnyLayerHasLocalAttachmentImage() const {
ComputeCachedPropertiesIfNeeded();
- return this_or_next_layers_have_local_attachment_;
+ return any_layer_has_local_attachment_image_;
+ }
+ bool AnyLayerHasFixedAttachmentImage() const {
+ ComputeCachedPropertiesIfNeeded();
+ return any_layer_has_fixed_attachment_image_;
+ }
+ bool AnyLayerHasDefaultAttachmentImage() const {
+ ComputeCachedPropertiesIfNeeded();
+ return any_layer_has_default_attachment_image_;
}
- void ComputeCachedPropertiesIfNeeded() const;
static EFillAttachment InitialFillAttachment(EFillLayerType) {
return EFillAttachment::kScroll;
@@ -304,6 +302,12 @@ class CORE_EXPORT FillLayer {
bool ImageTilesLayer() const;
bool LayerPropertiesEqual(const FillLayer&) const;
+ void ComputeCachedPropertiesIfNeeded() const {
+ if (!cached_properties_computed_)
+ ComputeCachedProperties();
+ }
+ void ComputeCachedProperties() const;
+
FillLayer* next_;
Persistent<StyleImage> image_;
@@ -341,12 +345,18 @@ class CORE_EXPORT FillLayer {
unsigned type_ : 1; // EFillLayerType
- // EFillBox, maximum m_clip value from this to bottom layer
- mutable unsigned this_or_next_layers_clip_max_ : 2;
+ // EFillBox, maximum clip_ value from this to bottom layer
+ mutable unsigned layers_clip_max_ : 2;
// True if any of this or subsequent layers has content-box clip or origin.
- mutable unsigned this_or_next_layers_use_content_box_ : 1;
- // True if any of this or subsequent layers has local attachment.
- mutable unsigned this_or_next_layers_have_local_attachment_ : 1;
+ mutable unsigned any_layer_uses_content_box_ : 1;
+ // True if any of this or subsequent layers has image.
+ mutable unsigned any_layer_has_image_ : 1;
+ // True if any of this or subsequent layers has local attachment image.
+ mutable unsigned any_layer_has_local_attachment_image_ : 1;
+ // True if any of this or subsequent layers has fixed attachment image.
+ mutable unsigned any_layer_has_fixed_attachment_image_ : 1;
+ // True if any of this or subsequent layers has default attachment image.
+ mutable unsigned any_layer_has_default_attachment_image_ : 1;
// Set once any of the above is accessed. The layers will be frozen
// thereafter.
mutable unsigned cached_properties_computed_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/style/filter_operation.cc b/chromium/third_party/blink/renderer/core/style/filter_operation.cc
index fda7fdecfbe..7c077b20a3e 100644
--- a/chromium/third_party/blink/renderer/core/style/filter_operation.cc
+++ b/chromium/third_party/blink/renderer/core/style/filter_operation.cc
@@ -27,11 +27,11 @@
#include "third_party/blink/renderer/core/svg/svg_resource.h"
#include "third_party/blink/renderer/platform/animation/animation_utilities.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.h"
#include "third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.h"
#include "third_party/blink/renderer/platform/graphics/filters/filter.h"
#include "third_party/blink/renderer/platform/graphics/filters/filter_effect.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/filter_operation.h b/chromium/third_party/blink/renderer/core/style/filter_operation.h
index 93a4fb6cdd1..bd8ae578dbe 100644
--- a/chromium/third_party/blink/renderer/core/style/filter_operation.h
+++ b/chromium/third_party/blink/renderer/core/style/filter_operation.h
@@ -30,10 +30,10 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/style/shadow_data.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/box_reflection.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -132,9 +132,11 @@ class CORE_EXPORT ReferenceFilterOperation : public FilterOperation {
public:
static ReferenceFilterOperation* Create(const AtomicString& url,
SVGResource* resource) {
- return new ReferenceFilterOperation(url, resource);
+ return MakeGarbageCollected<ReferenceFilterOperation>(url, resource);
}
+ ReferenceFilterOperation(const AtomicString& url, SVGResource*);
+
bool AffectsOpacity() const override { return true; }
bool MovesPixels() const override { return true; }
FloatRect MapRect(const FloatRect&) const override;
@@ -152,8 +154,6 @@ class CORE_EXPORT ReferenceFilterOperation : public FilterOperation {
void Trace(blink::Visitor*) override;
private:
- ReferenceFilterOperation(const AtomicString& url, SVGResource*);
-
FilterOperation* Blend(const FilterOperation* from,
double progress) const override {
NOTREACHED();
@@ -290,9 +290,12 @@ DEFINE_FILTER_OPERATION_TYPE_CASTS(BlurFilterOperation, BLUR);
class CORE_EXPORT DropShadowFilterOperation : public FilterOperation {
public:
static DropShadowFilterOperation* Create(const ShadowData& shadow) {
- return new DropShadowFilterOperation(shadow);
+ return MakeGarbageCollected<DropShadowFilterOperation>(shadow);
}
+ DropShadowFilterOperation(const ShadowData& shadow)
+ : FilterOperation(DROP_SHADOW), shadow_(shadow) {}
+
const ShadowData& Shadow() const { return shadow_; }
bool AffectsOpacity() const override { return true; }
@@ -310,9 +313,6 @@ class CORE_EXPORT DropShadowFilterOperation : public FilterOperation {
return shadow_ == other->shadow_;
}
- DropShadowFilterOperation(const ShadowData& shadow)
- : FilterOperation(DROP_SHADOW), shadow_(shadow) {}
-
ShadowData shadow_;
};
diff --git a/chromium/third_party/blink/renderer/core/style/filter_operations.h b/chromium/third_party/blink/renderer/core/style/filter_operations.h
index 171c1c8cc52..157ab4e6c6c 100644
--- a/chromium/third_party/blink/renderer/core/style/filter_operations.h
+++ b/chromium/third_party/blink/renderer/core/style/filter_operations.h
@@ -86,23 +86,22 @@ class FilterOperationsWrapper
: public GarbageCollected<FilterOperationsWrapper> {
public:
static FilterOperationsWrapper* Create() {
- return new FilterOperationsWrapper();
+ return MakeGarbageCollected<FilterOperationsWrapper>();
}
static FilterOperationsWrapper* Create(const FilterOperations& operations) {
- return new FilterOperationsWrapper(operations);
+ return MakeGarbageCollected<FilterOperationsWrapper>(operations);
}
+ FilterOperationsWrapper() = default;
+ explicit FilterOperationsWrapper(const FilterOperations& operations)
+ : operations_(operations) {}
+
const FilterOperations& Operations() const { return operations_; }
void Trace(blink::Visitor* visitor) { visitor->Trace(operations_); }
private:
- FilterOperationsWrapper() = default;
-
- explicit FilterOperationsWrapper(const FilterOperations& operations)
- : operations_(operations) {}
-
FilterOperations operations_;
};
diff --git a/chromium/third_party/blink/renderer/core/style/gap_length.h b/chromium/third_party/blink/renderer/core/style/gap_length.h
index b2a704c7ecb..a70a32243dc 100644
--- a/chromium/third_party/blink/renderer/core/style/gap_length.h
+++ b/chromium/third_party/blink/renderer/core/style/gap_length.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GAP_LENGTH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GAP_LENGTH_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/grid_length.h b/chromium/third_party/blink/renderer/core/style/grid_length.h
index 69ce48f9864..0e6d874f324 100644
--- a/chromium/third_party/blink/renderer/core/style/grid_length.h
+++ b/chromium/third_party/blink/renderer/core/style/grid_length.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_LENGTH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_LENGTH_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/nine_piece_image.h b/chromium/third_party/blink/renderer/core/style/nine_piece_image.h
index 69655a15a68..564b2bd4ed8 100644
--- a/chromium/third_party/blink/renderer/core/style/nine_piece_image.h
+++ b/chromium/third_party/blink/renderer/core/style/nine_piece_image.h
@@ -29,9 +29,9 @@
#include "third_party/blink/renderer/core/style/border_image_length_box.h"
#include "third_party/blink/renderer/core/style/data_ref.h"
#include "third_party/blink/renderer/core/style/style_image.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/length_box.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
-#include "third_party/blink/renderer/platform/length_box.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
diff --git a/chromium/third_party/blink/renderer/core/style/quad_length_value.h b/chromium/third_party/blink/renderer/core/style/quad_length_value.h
index 34b8911f304..53211ccf70e 100644
--- a/chromium/third_party/blink/renderer/core/style/quad_length_value.h
+++ b/chromium/third_party/blink/renderer/core/style/quad_length_value.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_QUAD_LENGTH_VALUE_H_
#include <memory>
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/shadow_data.h b/chromium/third_party/blink/renderer/core/style/shadow_data.h
index e29d0975fde..495b9acb7da 100644
--- a/chromium/third_party/blink/renderer/core/style/shadow_data.h
+++ b/chromium/third_party/blink/renderer/core/style/shadow_data.h
@@ -26,6 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_SHADOW_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_SHADOW_DATA_H_
+#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_rect_outsets.h"
@@ -36,7 +37,7 @@ enum ShadowStyle { kNormal, kInset };
// This class holds information about shadows for the text-shadow and box-shadow
// properties, as well as the drop-shadow(...) filter operation.
-class ShadowData {
+class CORE_EXPORT ShadowData {
USING_FAST_MALLOC(ShadowData);
public:
diff --git a/chromium/third_party/blink/renderer/core/style/shape_value.cc b/chromium/third_party/blink/renderer/core/style/shape_value.cc
deleted file mode 100644
index 8ead9fd3f94..00000000000
--- a/chromium/third_party/blink/renderer/core/style/shape_value.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/core/style/shape_value.h"
-
-#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
-
-namespace blink {
-
-bool ShapeValue::IsImageValid() const {
- if (!GetImage())
- return false;
- if (GetImage()->IsImageResource() || GetImage()->IsImageResourceSet())
- return GetImage()->CachedImage() && GetImage()->CachedImage()->HasImage();
- return GetImage()->IsGeneratedImage();
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/style/shape_value.h b/chromium/third_party/blink/renderer/core/style/shape_value.h
index c89b50f5cf0..8a7253e3205 100644
--- a/chromium/third_party/blink/renderer/core/style/shape_value.h
+++ b/chromium/third_party/blink/renderer/core/style/shape_value.h
@@ -49,22 +49,29 @@ class ShapeValue final : public GarbageCollectedFinalized<ShapeValue> {
static ShapeValue* CreateShapeValue(scoped_refptr<BasicShape> shape,
CSSBoxType css_box) {
- return new ShapeValue(std::move(shape), css_box);
+ return MakeGarbageCollected<ShapeValue>(std::move(shape), css_box);
}
static ShapeValue* CreateBoxShapeValue(CSSBoxType css_box) {
- return new ShapeValue(css_box);
+ return MakeGarbageCollected<ShapeValue>(css_box);
}
static ShapeValue* CreateImageValue(StyleImage* image) {
- return new ShapeValue(image);
+ return MakeGarbageCollected<ShapeValue>(image);
}
+ ShapeValue(scoped_refptr<BasicShape> shape, CSSBoxType css_box)
+ : type_(kShape), shape_(std::move(shape)), css_box_(css_box) {}
+ ShapeValue(ShapeValueType type)
+ : type_(type), css_box_(CSSBoxType::kMissing) {}
+ ShapeValue(StyleImage* image)
+ : type_(kImage), image_(image), css_box_(CSSBoxType::kContent) {}
+ ShapeValue(CSSBoxType css_box) : type_(kBox), css_box_(css_box) {}
+
ShapeValueType GetType() const { return type_; }
BasicShape* Shape() const { return shape_.get(); }
StyleImage* GetImage() const { return image_.Get(); }
- bool IsImageValid() const;
void SetImage(StyleImage* image) {
DCHECK_EQ(GetType(), kImage);
if (image_ != image)
@@ -77,14 +84,6 @@ class ShapeValue final : public GarbageCollectedFinalized<ShapeValue> {
virtual void Trace(blink::Visitor* visitor) { visitor->Trace(image_); }
private:
- ShapeValue(scoped_refptr<BasicShape> shape, CSSBoxType css_box)
- : type_(kShape), shape_(std::move(shape)), css_box_(css_box) {}
- ShapeValue(ShapeValueType type)
- : type_(type), css_box_(CSSBoxType::kMissing) {}
- ShapeValue(StyleImage* image)
- : type_(kImage), image_(image), css_box_(CSSBoxType::kContent) {}
- ShapeValue(CSSBoxType css_box) : type_(kBox), css_box_(css_box) {}
-
ShapeValueType type_;
scoped_refptr<BasicShape> shape_;
Member<StyleImage> image_;
diff --git a/chromium/third_party/blink/renderer/core/style/style_difference.h b/chromium/third_party/blink/renderer/core/style/style_difference.h
index 2d9e0133d95..e5a387a63c9 100644
--- a/chromium/third_party/blink/renderer/core/style/style_difference.h
+++ b/chromium/third_party/blink/renderer/core/style/style_difference.h
@@ -28,6 +28,8 @@ class StyleDifference {
kTextDecorationOrColorChanged = 1 << 6,
kBlendModeChanged = 1 << 7,
kMaskChanged = 1 << 8,
+ // Whether background-color changed alpha to or from 1.
+ kHasAlphaChanged = 1 << 9,
// If you add a value here, be sure to update kPropertyDifferenceCount.
};
@@ -152,6 +154,13 @@ class StyleDifference {
}
void SetMaskChanged() { property_specific_differences_ |= kMaskChanged; }
+ bool HasAlphaChanged() const {
+ return property_specific_differences_ & kHasAlphaChanged;
+ }
+ void SetHasAlphaChanged() {
+ property_specific_differences_ |= kHasAlphaChanged;
+ }
+
bool ScrollAnchorDisablingPropertyChanged() const {
return scroll_anchor_disabling_property_changed_;
}
@@ -162,7 +171,7 @@ class StyleDifference {
void SetCompositingReasonsChanged() { composited_reasons_changed_ = true; }
private:
- static constexpr int kPropertyDifferenceCount = 9;
+ static constexpr int kPropertyDifferenceCount = 10;
friend CORE_EXPORT std::ostream& operator<<(std::ostream&,
const StyleDifference&);
diff --git a/chromium/third_party/blink/renderer/core/style/style_fetched_image.cc b/chromium/third_party/blink/renderer/core/style/style_fetched_image.cc
index 68a9dc3b974..1c450e98feb 100644
--- a/chromium/third_party/blink/renderer/core/style/style_fetched_image.cc
+++ b/chromium/third_party/blink/renderer/core/style/style_fetched_image.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
+#include "third_party/blink/renderer/platform/graphics/placeholder_image.h"
namespace blink {
@@ -146,6 +147,11 @@ scoped_refptr<Image> StyleFetchedImage::GetImage(
const ComputedStyle& style,
const FloatSize& target_size) const {
Image* image = image_->GetImage();
+ if (image->IsPlaceholderImage()) {
+ static_cast<PlaceholderImage*>(image)->SetIconAndTextScaleFactor(
+ style.EffectiveZoom());
+ }
+
if (!image->IsSVGImage())
return image;
return SVGImageForContainer::Create(ToSVGImage(image), target_size,
diff --git a/chromium/third_party/blink/renderer/core/style/style_fetched_image.h b/chromium/third_party/blink/renderer/core/style/style_fetched_image.h
index 6bd9314e528..ccdf41f98d1 100644
--- a/chromium/third_party/blink/renderer/core/style/style_fetched_image.h
+++ b/chromium/third_party/blink/renderer/core/style/style_fetched_image.h
@@ -43,8 +43,13 @@ class StyleFetchedImage final : public StyleImage,
static StyleFetchedImage* Create(const Document& document,
FetchParameters& params,
bool is_lazyload_deferred) {
- return new StyleFetchedImage(document, params, is_lazyload_deferred);
+ return MakeGarbageCollected<StyleFetchedImage>(document, params,
+ is_lazyload_deferred);
}
+
+ StyleFetchedImage(const Document&,
+ FetchParameters&,
+ bool is_lazyload_deferred);
~StyleFetchedImage() override;
WrappedImagePtr Data() const override;
@@ -72,15 +77,13 @@ class StyleFetchedImage final : public StyleImage,
bool KnownToBeOpaque(const Document&, const ComputedStyle&) const override;
ImageResourceContent* CachedImage() const override;
+ const KURL& Url() const { return url_; }
+
void LoadDeferredImage(const Document& document);
void Trace(blink::Visitor*) override;
private:
- StyleFetchedImage(const Document&,
- FetchParameters&,
- bool is_lazyload_deferred);
-
bool IsEqual(const StyleImage&) const override;
void Dispose();
diff --git a/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.cc b/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.cc
index c9649cdb4d5..933cc71effd 100644
--- a/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.cc
+++ b/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.cc
@@ -29,6 +29,7 @@
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h"
+#include "third_party/blink/renderer/platform/graphics/placeholder_image.h"
namespace blink {
@@ -131,6 +132,11 @@ scoped_refptr<Image> StyleFetchedImageSet::GetImage(
const ComputedStyle& style,
const FloatSize& target_size) const {
Image* image = best_fit_image_->GetImage();
+ if (image->IsPlaceholderImage()) {
+ static_cast<PlaceholderImage*>(image)->SetIconAndTextScaleFactor(
+ style.EffectiveZoom());
+ }
+
if (!image->IsSVGImage())
return image;
return SVGImageForContainer::Create(ToSVGImage(image), target_size,
diff --git a/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.h b/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.h
index 3872da139e0..d032039b770 100644
--- a/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.h
+++ b/chromium/third_party/blink/renderer/core/style/style_fetched_image_set.h
@@ -50,8 +50,14 @@ class StyleFetchedImageSet final : public StyleImage,
float image_scale_factor,
CSSImageSetValue* value,
const KURL& url) {
- return new StyleFetchedImageSet(image, image_scale_factor, value, url);
+ return MakeGarbageCollected<StyleFetchedImageSet>(image, image_scale_factor,
+ value, url);
}
+
+ StyleFetchedImageSet(ImageResourceContent*,
+ float image_scale_factor,
+ CSSImageSetValue*,
+ const KURL&);
~StyleFetchedImageSet() override;
CSSValue* CssValue() const override;
@@ -83,11 +89,6 @@ class StyleFetchedImageSet final : public StyleImage,
void Trace(blink::Visitor*) override;
private:
- StyleFetchedImageSet(ImageResourceContent*,
- float image_scale_factor,
- CSSImageSetValue*,
- const KURL&);
-
bool IsEqual(const StyleImage& other) const override;
void Dispose();
diff --git a/chromium/third_party/blink/renderer/core/style/style_filter_data.h b/chromium/third_party/blink/renderer/core/style/style_filter_data.h
index 4a9afca7ee4..98b5b13aa52 100644
--- a/chromium/third_party/blink/renderer/core/style/style_filter_data.h
+++ b/chromium/third_party/blink/renderer/core/style/style_filter_data.h
@@ -33,9 +33,16 @@ namespace blink {
class StyleFilterData final : public GarbageCollected<StyleFilterData> {
public:
- static StyleFilterData* Create() { return new StyleFilterData; }
+ static StyleFilterData* Create() {
+ return MakeGarbageCollected<StyleFilterData>();
+ }
- StyleFilterData* Copy() const { return new StyleFilterData(*this); }
+ StyleFilterData();
+ explicit StyleFilterData(const StyleFilterData&);
+
+ StyleFilterData* Copy() const {
+ return MakeGarbageCollected<StyleFilterData>(*this);
+ }
bool operator==(const StyleFilterData&) const;
bool operator!=(const StyleFilterData& o) const { return !(*this == o); }
@@ -43,10 +50,6 @@ class StyleFilterData final : public GarbageCollected<StyleFilterData> {
void Trace(blink::Visitor* visitor) { visitor->Trace(operations_); }
FilterOperations operations_;
-
- private:
- StyleFilterData();
- explicit StyleFilterData(const StyleFilterData&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/style/style_generated_image.h b/chromium/third_party/blink/renderer/core/style/style_generated_image.h
index c155958dba7..f1046f26459 100644
--- a/chromium/third_party/blink/renderer/core/style/style_generated_image.h
+++ b/chromium/third_party/blink/renderer/core/style/style_generated_image.h
@@ -39,9 +39,11 @@ class ImageResourceObserver;
class CORE_EXPORT StyleGeneratedImage final : public StyleImage {
public:
static StyleGeneratedImage* Create(const CSSImageGeneratorValue& value) {
- return new StyleGeneratedImage(value);
+ return MakeGarbageCollected<StyleGeneratedImage>(value);
}
+ StyleGeneratedImage(const CSSImageGeneratorValue&);
+
WrappedImagePtr Data() const override { return image_generator_value_.Get(); }
CSSValue* CssValue() const override;
@@ -64,8 +66,6 @@ class CORE_EXPORT StyleGeneratedImage final : public StyleImage {
void Trace(blink::Visitor*) override;
private:
- StyleGeneratedImage(const CSSImageGeneratorValue&);
-
bool IsEqual(const StyleImage&) const override;
// TODO(sashab): Replace this with <const CSSImageGeneratorValue> once
diff --git a/chromium/third_party/blink/renderer/core/style/style_inherited_variables.cc b/chromium/third_party/blink/renderer/core/style/style_inherited_variables.cc
index 3c4be358bcd..deb2754cb96 100644
--- a/chromium/third_party/blink/renderer/core/style/style_inherited_variables.cc
+++ b/chromium/third_party/blink/renderer/core/style/style_inherited_variables.cc
@@ -31,19 +31,22 @@ bool StyleInheritedVariables::operator==(
}
StyleInheritedVariables::StyleInheritedVariables()
- : registered_data_(new HeapHashMap<AtomicString, Member<CSSValue>>),
+ : registered_data_(
+ MakeGarbageCollected<HeapHashMap<AtomicString, Member<CSSValue>>>()),
root_(nullptr),
needs_resolution_(false) {}
StyleInheritedVariables::StyleInheritedVariables(
StyleInheritedVariables& other) {
if (!other.root_) {
- registered_data_ = new HeapHashMap<AtomicString, Member<CSSValue>>;
+ registered_data_ =
+ MakeGarbageCollected<HeapHashMap<AtomicString, Member<CSSValue>>>();
root_ = &other;
} else {
data_ = other.data_;
- registered_data_ = new HeapHashMap<AtomicString, Member<CSSValue>>(
- *other.registered_data_);
+ registered_data_ =
+ MakeGarbageCollected<HeapHashMap<AtomicString, Member<CSSValue>>>(
+ *other.registered_data_);
root_ = other.root_;
}
needs_resolution_ = other.needs_resolution_;
diff --git a/chromium/third_party/blink/renderer/core/style/style_initial_data.cc b/chromium/third_party/blink/renderer/core/style/style_initial_data.cc
new file mode 100644
index 00000000000..62a6464dfcb
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/style/style_initial_data.cc
@@ -0,0 +1,41 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/style/style_initial_data.h"
+
+#include "third_party/blink/renderer/core/css/property_registry.h"
+#include "third_party/blink/renderer/core/style/data_equivalency.h"
+
+namespace blink {
+
+StyleInitialData::StyleInitialData(const PropertyRegistry& registry)
+ : variables_(MakeGarbageCollected<
+ HeapHashMap<AtomicString, Member<const CSSValue>>>()) {
+ for (const auto& entry : registry) {
+ const CSSValue* initial = entry.value->Initial();
+ if (!initial)
+ continue;
+ variables_->Set(entry.key, initial);
+ }
+}
+
+StyleInitialData::StyleInitialData(StyleInitialData& other)
+ : variables_(MakeGarbageCollected<
+ HeapHashMap<AtomicString, Member<const CSSValue>>>(
+ *other.variables_)) {}
+
+bool StyleInitialData::operator==(const StyleInitialData& other) const {
+ if (variables_->size() != other.variables_->size())
+ return false;
+
+ for (const auto& iter : *variables_) {
+ const CSSValue* other_value = other.variables_->at(iter.key);
+ if (iter.value != other_value)
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/style/style_initial_data.h b/chromium/third_party/blink/renderer/core/style/style_initial_data.h
new file mode 100644
index 00000000000..cdb8c212e5e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/style/style_initial_data.h
@@ -0,0 +1,53 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_INITIAL_DATA_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_INITIAL_DATA_H_
+
+#include "base/memory/ptr_util.h"
+#include "third_party/blink/renderer/core/css/css_value.h"
+#include "third_party/blink/renderer/platform/heap/persistent.h"
+#include "third_party/blink/renderer/platform/wtf/forward.h"
+#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+#include "third_party/blink/renderer/platform/wtf/text/atomic_string_hash.h"
+
+namespace blink {
+
+class PropertyRegistry;
+
+// Holds data stored on the initial ComputedStyle only.
+//
+// An instance of this class is created once, and then shared between all the
+// ComputedStyles that inherit (directly or indirectly) from the initial style.
+class CORE_EXPORT StyleInitialData : public RefCounted<StyleInitialData> {
+ public:
+ static scoped_refptr<StyleInitialData> Create(
+ const PropertyRegistry& registry) {
+ return base::AdoptRef(new StyleInitialData(registry));
+ }
+
+ bool operator==(const StyleInitialData& other) const;
+ bool operator!=(const StyleInitialData& other) const {
+ return !(*this == other);
+ }
+
+ bool HasInitialVariables() const { return variables_->size(); }
+
+ const CSSValue* GetInitialVariable(const AtomicString& name) const {
+ return variables_->at(name);
+ }
+
+ private:
+ StyleInitialData(const PropertyRegistry&);
+ StyleInitialData(StyleInitialData&);
+
+ // Initial values for all registered properties. This is set on
+ // the initial style, and then shared with all other styles that directly or
+ // indirectly inherit from that.
+ Persistent<HeapHashMap<AtomicString, Member<const CSSValue>>> variables_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_INITIAL_DATA_H_
diff --git a/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.cc b/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.cc
index e13afe9a298..ea34e3cad1e 100644
--- a/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.cc
+++ b/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.cc
@@ -40,14 +40,16 @@ void StyleNonInheritedVariables::RemoveVariable(const AtomicString& name) {
}
StyleNonInheritedVariables::StyleNonInheritedVariables()
- : registered_data_(new HeapHashMap<AtomicString, Member<CSSValue>>),
+ : registered_data_(
+ MakeGarbageCollected<HeapHashMap<AtomicString, Member<CSSValue>>>()),
needs_resolution_(false) {}
StyleNonInheritedVariables::StyleNonInheritedVariables(
StyleNonInheritedVariables& other) {
data_ = other.data_;
registered_data_ =
- new HeapHashMap<AtomicString, Member<CSSValue>>(*other.registered_data_);
+ MakeGarbageCollected<HeapHashMap<AtomicString, Member<CSSValue>>>(
+ *other.registered_data_);
needs_resolution_ = other.needs_resolution_;
}
diff --git a/chromium/third_party/blink/renderer/core/style/style_pending_image.h b/chromium/third_party/blink/renderer/core/style/style_pending_image.h
index 1ef61e41aa9..c7790609e75 100644
--- a/chromium/third_party/blink/renderer/core/style/style_pending_image.h
+++ b/chromium/third_party/blink/renderer/core/style/style_pending_image.h
@@ -44,7 +44,12 @@ class ImageResourceObserver;
class StylePendingImage final : public StyleImage {
public:
static StylePendingImage* Create(const CSSValue& value) {
- return new StylePendingImage(value);
+ return MakeGarbageCollected<StylePendingImage>(value);
+ }
+
+ explicit StylePendingImage(const CSSValue& value)
+ : value_(const_cast<CSSValue*>(&value)) {
+ is_pending_image_ = true;
}
WrappedImagePtr Data() const override { return value_.Get(); }
@@ -98,11 +103,6 @@ class StylePendingImage final : public StyleImage {
}
private:
- explicit StylePendingImage(const CSSValue& value)
- : value_(const_cast<CSSValue*>(&value)) {
- is_pending_image_ = true;
- }
-
bool IsEqual(const StyleImage& other) const override;
// TODO(sashab): Replace this with <const CSSValue> once Member<>
diff --git a/chromium/third_party/blink/renderer/core/style/style_reflection.h b/chromium/third_party/blink/renderer/core/style/style_reflection.h
index b720299ba5e..cb2de27864e 100644
--- a/chromium/third_party/blink/renderer/core/style/style_reflection.h
+++ b/chromium/third_party/blink/renderer/core/style/style_reflection.h
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/css/css_reflection_direction.h"
#include "third_party/blink/renderer/core/style/nine_piece_image.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/svg_computed_style.h b/chromium/third_party/blink/renderer/core/style/svg_computed_style.h
index 29f9d0c1246..3eb4bc6aad2 100644
--- a/chromium/third_party/blink/renderer/core/style/svg_computed_style.h
+++ b/chromium/third_party/blink/renderer/core/style/svg_computed_style.h
@@ -28,8 +28,8 @@
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/style/data_ref.h"
#include "third_party/blink/renderer/core/style/svg_computed_style_defs.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
diff --git a/chromium/third_party/blink/renderer/core/style/svg_computed_style_defs.h b/chromium/third_party/blink/renderer/core/style/svg_computed_style_defs.h
index 9c510af8400..5920c752054 100644
--- a/chromium/third_party/blink/renderer/core/style/svg_computed_style_defs.h
+++ b/chromium/third_party/blink/renderer/core/style/svg_computed_style_defs.h
@@ -31,8 +31,8 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/style/style_path.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/ref_vector.h"
diff --git a/chromium/third_party/blink/renderer/core/style/transform_origin.h b/chromium/third_party/blink/renderer/core/style/transform_origin.h
index 923f9c97f6e..db1ac806cfc 100644
--- a/chromium/third_party/blink/renderer/core/style/transform_origin.h
+++ b/chromium/third_party/blink/renderer/core/style/transform_origin.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_TRANSFORM_ORIGIN_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_TRANSFORM_ORIGIN_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/BUILD.gn b/chromium/third_party/blink/renderer/core/svg/BUILD.gn
index 37f9e033280..43c997e602c 100644
--- a/chromium/third_party/blink/renderer/core/svg/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/svg/BUILD.gn
@@ -113,6 +113,8 @@ blink_core_sources("svg") {
"svg_ellipse_element.h",
"svg_enumeration.cc",
"svg_enumeration.h",
+ "svg_enumeration_map.cc",
+ "svg_enumeration_map.h",
"svg_fe_blend_element.cc",
"svg_fe_blend_element.h",
"svg_fe_color_matrix_element.cc",
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.cc b/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.cc
index d5c29f46d4d..e9d898324ed 100644
--- a/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.cc
+++ b/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.cc
@@ -85,7 +85,7 @@ void SMILTimeContainer::Schedule(SVGSMILElement* animation,
Member<AnimationsLinkedHashSet>& scheduled =
attribute_map.insert(attribute_name, nullptr).stored_value->value;
if (!scheduled)
- scheduled = new AnimationsLinkedHashSet;
+ scheduled = MakeGarbageCollected<AnimationsLinkedHashSet>();
DCHECK(!scheduled->Contains(animation));
scheduled->insert(animation);
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.h b/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.h
index 231d376e6b4..eaee06b4402 100644
--- a/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.h
+++ b/chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.h
@@ -46,8 +46,10 @@ class SVGSVGElement;
class SMILTimeContainer : public GarbageCollectedFinalized<SMILTimeContainer> {
public:
static SMILTimeContainer* Create(SVGSVGElement& owner) {
- return new SMILTimeContainer(owner);
+ return MakeGarbageCollected<SMILTimeContainer>(owner);
}
+
+ explicit SMILTimeContainer(SVGSVGElement& owner);
~SMILTimeContainer();
void Schedule(SVGSMILElement*, SVGElement*, const QualifiedName&);
@@ -75,8 +77,6 @@ class SMILTimeContainer : public GarbageCollectedFinalized<SMILTimeContainer> {
void Trace(blink::Visitor*);
private:
- explicit SMILTimeContainer(SVGSVGElement& owner);
-
enum FrameSchedulingState {
// No frame scheduled.
kIdle,
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc b/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc
index c38da07146b..4325e7cc096 100644
--- a/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/core/svg/svg_uri_reference.h"
#include "third_party/blink/renderer/core/xlink_names.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -47,21 +48,20 @@ namespace blink {
class RepeatEvent final : public Event {
public:
static RepeatEvent* Create(const AtomicString& type, int repeat) {
- return new RepeatEvent(type, Bubbles::kNo, Cancelable::kNo, repeat);
+ return MakeGarbageCollected<RepeatEvent>(type, Bubbles::kNo,
+ Cancelable::kNo, repeat);
}
- ~RepeatEvent() override = default;
-
- int Repeat() const { return repeat_; }
-
- void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
-
- protected:
RepeatEvent(const AtomicString& type,
Bubbles bubbles,
Cancelable cancelable,
int repeat = -1)
: Event(type, bubbles, cancelable), repeat_(repeat) {}
+ ~RepeatEvent() override = default;
+
+ int Repeat() const { return repeat_; }
+
+ void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
private:
int repeat_;
@@ -105,7 +105,7 @@ class ConditionEventListener final : public EventListener {
animation_(animation),
condition_(condition) {}
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
Member<SVGSMILElement> animation_;
Member<SVGSMILElement::Condition> condition_;
@@ -119,7 +119,7 @@ bool ConditionEventListener::operator==(const EventListener& listener) const {
return false;
}
-void ConditionEventListener::handleEvent(ExecutionContext*, Event* event) {
+void ConditionEventListener::Invoke(ExecutionContext*, Event* event) {
if (!animation_)
return;
if (event->type() == "repeatn" &&
@@ -324,7 +324,7 @@ Node::InsertionNotificationRequest SVGSMILElement::InsertedInto(
// "If no attribute is present, the default begin value (an offset-value of 0)
// must be evaluated."
- if (!FastHasAttribute(SVGNames::beginAttr))
+ if (!FastHasAttribute(svg_names::kBeginAttr))
begin_times_.push_back(SMILTimeWithOrigin());
if (is_waiting_for_first_interval_)
@@ -508,10 +508,10 @@ void SVGSMILElement::ParseBeginOrEnd(const String& parse_string,
void SVGSMILElement::ParseAttribute(const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
const AtomicString& value = params.new_value;
- if (name == SVGNames::beginAttr) {
+ if (name == svg_names::kBeginAttr) {
if (!conditions_.IsEmpty()) {
ClearConditions();
- ParseBeginOrEnd(FastGetAttribute(SVGNames::endAttr), kEnd);
+ ParseBeginOrEnd(FastGetAttribute(svg_names::kEndAttr), kEnd);
}
ParseBeginOrEnd(value.GetString(), kBegin);
if (isConnected()) {
@@ -520,10 +520,10 @@ void SVGSMILElement::ParseAttribute(const AttributeModificationParams& params) {
BeginListChanged(Elapsed());
}
AnimationAttributeChanged();
- } else if (name == SVGNames::endAttr) {
+ } else if (name == svg_names::kEndAttr) {
if (!conditions_.IsEmpty()) {
ClearConditions();
- ParseBeginOrEnd(FastGetAttribute(SVGNames::beginAttr), kBegin);
+ ParseBeginOrEnd(FastGetAttribute(svg_names::kBeginAttr), kBegin);
}
ParseBeginOrEnd(value.GetString(), kEnd);
if (isConnected()) {
@@ -532,23 +532,23 @@ void SVGSMILElement::ParseAttribute(const AttributeModificationParams& params) {
EndListChanged(Elapsed());
}
AnimationAttributeChanged();
- } else if (name == SVGNames::onbeginAttr) {
- SetAttributeEventListener(EventTypeNames::beginEvent,
+ } else if (name == svg_names::kOnbeginAttr) {
+ SetAttributeEventListener(event_type_names::kBeginEvent,
CreateAttributeEventListener(this, name, value));
- } else if (name == SVGNames::onendAttr) {
- SetAttributeEventListener(EventTypeNames::endEvent,
+ } else if (name == svg_names::kOnendAttr) {
+ SetAttributeEventListener(event_type_names::kEndEvent,
CreateAttributeEventListener(this, name, value));
- } else if (name == SVGNames::onrepeatAttr) {
- SetAttributeEventListener(EventTypeNames::repeatEvent,
+ } else if (name == svg_names::kOnrepeatAttr) {
+ SetAttributeEventListener(event_type_names::kRepeatEvent,
CreateAttributeEventListener(this, name, value));
- } else if (name == SVGNames::restartAttr) {
+ } else if (name == svg_names::kRestartAttr) {
if (value == "never")
restart_ = kRestartNever;
else if (value == "whenNotActive")
restart_ = kRestartWhenNotActive;
else
restart_ = kRestartAlways;
- } else if (name == SVGNames::fillAttr) {
+ } else if (name == svg_names::kFillAttr) {
fill_ = value == "freeze" ? kFillFreeze : kFillRemove;
} else {
SVGElement::ParseAttribute(params);
@@ -556,18 +556,18 @@ void SVGSMILElement::ParseAttribute(const AttributeModificationParams& params) {
}
void SVGSMILElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::durAttr) {
+ if (attr_name == svg_names::kDurAttr) {
cached_dur_ = kInvalidCachedTime;
- } else if (attr_name == SVGNames::repeatDurAttr) {
+ } else if (attr_name == svg_names::kRepeatDurAttr) {
cached_repeat_dur_ = kInvalidCachedTime;
- } else if (attr_name == SVGNames::repeatCountAttr) {
+ } else if (attr_name == svg_names::kRepeatCountAttr) {
cached_repeat_count_ = kInvalidCachedTime;
- } else if (attr_name == SVGNames::minAttr) {
+ } else if (attr_name == svg_names::kMinAttr) {
cached_min_ = kInvalidCachedTime;
- } else if (attr_name == SVGNames::maxAttr) {
+ } else if (attr_name == svg_names::kMaxAttr) {
cached_max_ = kInvalidCachedTime;
- } else if (attr_name.Matches(SVGNames::hrefAttr) ||
- attr_name.Matches(XLinkNames::hrefAttr)) {
+ } else if (attr_name.Matches(svg_names::kHrefAttr) ||
+ attr_name.Matches(xlink_names::kHrefAttr)) {
// TODO(fs): Could be smarter here when 'href' is specified and 'xlink:href'
// is changed.
SVGElement::InvalidationGuard invalidation_guard(this);
@@ -647,7 +647,7 @@ bool SVGSMILElement::IsFrozen() const {
SMILTime SVGSMILElement::Dur() const {
if (cached_dur_ != kInvalidCachedTime)
return cached_dur_;
- const AtomicString& value = FastGetAttribute(SVGNames::durAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kDurAttr);
SMILTime clock_value = ParseClockValue(value);
return cached_dur_ = clock_value <= 0 ? SMILTime::Unresolved() : clock_value;
}
@@ -655,7 +655,7 @@ SMILTime SVGSMILElement::Dur() const {
SMILTime SVGSMILElement::RepeatDur() const {
if (cached_repeat_dur_ != kInvalidCachedTime)
return cached_repeat_dur_;
- const AtomicString& value = FastGetAttribute(SVGNames::repeatDurAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kRepeatDurAttr);
SMILTime clock_value = ParseClockValue(value);
cached_repeat_dur_ = clock_value <= 0 ? SMILTime::Unresolved() : clock_value;
return cached_repeat_dur_;
@@ -666,7 +666,7 @@ SMILTime SVGSMILElement::RepeatCount() const {
if (cached_repeat_count_ != kInvalidCachedTime)
return cached_repeat_count_;
SMILTime computed_repeat_count = SMILTime::Unresolved();
- const AtomicString& value = FastGetAttribute(SVGNames::repeatCountAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kRepeatCountAttr);
if (!value.IsNull()) {
DEFINE_STATIC_LOCAL(const AtomicString, indefinite_value, ("indefinite"));
if (value == indefinite_value) {
@@ -685,7 +685,7 @@ SMILTime SVGSMILElement::RepeatCount() const {
SMILTime SVGSMILElement::MaxValue() const {
if (cached_max_ != kInvalidCachedTime)
return cached_max_;
- const AtomicString& value = FastGetAttribute(SVGNames::maxAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kMaxAttr);
SMILTime result = ParseClockValue(value);
return cached_max_ = (result.IsUnresolved() || result <= 0)
? SMILTime::Indefinite()
@@ -695,7 +695,7 @@ SMILTime SVGSMILElement::MaxValue() const {
SMILTime SVGSMILElement::MinValue() const {
if (cached_min_ != kInvalidCachedTime)
return cached_min_;
- const AtomicString& value = FastGetAttribute(SVGNames::minAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kMinAttr);
SMILTime result = ParseClockValue(value);
return cached_min_ = (result.IsUnresolved() || result < 0) ? 0 : result;
}
@@ -1130,7 +1130,7 @@ bool SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
if (animation_is_contributing) {
if (old_active_state == kInactive ||
restarted_interval == kDidRestartInterval) {
- ScheduleEvent(EventTypeNames::beginEvent);
+ ScheduleEvent(event_type_names::kBeginEvent);
StartedActiveInterval();
}
@@ -1143,14 +1143,14 @@ bool SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
if ((old_active_state == kActive && GetActiveState() != kActive) ||
restarted_interval == kDidRestartInterval) {
- ScheduleEvent(EventTypeNames::endEvent);
+ ScheduleEvent(event_type_names::kEndEvent);
EndedActiveInterval();
}
// Triggering all the pending events if the animation timeline is changed.
if (seek_to_time) {
if (GetActiveState() == kInactive)
- ScheduleEvent(EventTypeNames::beginEvent);
+ ScheduleEvent(event_type_names::kBeginEvent);
if (repeat) {
for (unsigned repeat_event_count = 1; repeat_event_count < repeat;
@@ -1161,7 +1161,7 @@ bool SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
}
if (GetActiveState() == kInactive || GetActiveState() == kFrozen)
- ScheduleEvent(EventTypeNames::endEvent);
+ ScheduleEvent(event_type_names::kEndEvent);
}
next_progress_time_ = CalculateNextProgressTime(elapsed);
@@ -1232,7 +1232,7 @@ void SVGSMILElement::EndedActiveInterval() {
void SVGSMILElement::ScheduleRepeatEvents(unsigned count) {
repeat_event_count_list_.push_back(count);
- ScheduleEvent(EventTypeNames::repeatEvent);
+ ScheduleEvent(event_type_names::kRepeatEvent);
ScheduleEvent(AtomicString("repeatn"));
}
@@ -1244,9 +1244,10 @@ void SVGSMILElement::ScheduleEvent(const AtomicString& event_type) {
}
void SVGSMILElement::DispatchPendingEvent(const AtomicString& event_type) {
- DCHECK(event_type == EventTypeNames::endEvent ||
- event_type == EventTypeNames::beginEvent ||
- event_type == EventTypeNames::repeatEvent || event_type == "repeatn");
+ DCHECK(event_type == event_type_names::kEndEvent ||
+ event_type == event_type_names::kBeginEvent ||
+ event_type == event_type_names::kRepeatEvent ||
+ event_type == "repeatn");
if (event_type == "repeatn") {
unsigned repeat_event_count = repeat_event_count_list_.front();
repeat_event_count_list_.EraseAt(0);
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.h b/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.h
index b6545a42e20..ccca384b6ea 100644
--- a/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.h
@@ -192,8 +192,16 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
const AtomicString& name,
SMILTime offset,
int repeat = -1) {
- return new Condition(type, begin_or_end, base_id, name, offset, repeat);
+ return MakeGarbageCollected<Condition>(type, begin_or_end, base_id, name,
+ offset, repeat);
}
+
+ Condition(Type,
+ BeginOrEnd,
+ const AtomicString& base_id,
+ const AtomicString& name,
+ SMILTime offset,
+ int repeat);
~Condition();
void Trace(blink::Visitor*);
@@ -213,13 +221,6 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
void DisconnectEventBase(SVGSMILElement&);
private:
- Condition(Type,
- BeginOrEnd,
- const AtomicString& base_id,
- const AtomicString& name,
- SMILTime offset,
- int repeat);
-
Type type_;
BeginOrEnd begin_or_end_;
AtomicString base_id_;
@@ -298,11 +299,11 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
};
inline bool IsSVGSMILElement(const SVGElement& element) {
- return element.HasTagName(SVGNames::setTag) ||
- element.HasTagName(SVGNames::animateTag) ||
- element.HasTagName(SVGNames::animateMotionTag) ||
- element.HasTagName(SVGNames::animateTransformTag) ||
- element.HasTagName((SVGNames::discardTag));
+ return element.HasTagName(svg_names::kSetTag) ||
+ element.HasTagName(svg_names::kAnimateTag) ||
+ element.HasTagName(svg_names::kAnimateMotionTag) ||
+ element.HasTagName(svg_names::kAnimateTransformTag) ||
+ element.HasTagName((svg_names::kDiscardTag));
}
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGSMILElement);
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.cc b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.cc
index 5464eb85da9..73d1f564544 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.cc
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.cc
@@ -69,7 +69,8 @@ FEImage* FEImage::CreateWithImage(
Filter* filter,
scoped_refptr<Image> image,
SVGPreserveAspectRatio* preserve_aspect_ratio) {
- return new FEImage(filter, std::move(image), preserve_aspect_ratio);
+ return MakeGarbageCollected<FEImage>(filter, std::move(image),
+ preserve_aspect_ratio);
}
FEImage* FEImage::CreateWithIRIReference(
@@ -77,7 +78,8 @@ FEImage* FEImage::CreateWithIRIReference(
TreeScope& tree_scope,
const String& href,
SVGPreserveAspectRatio* preserve_aspect_ratio) {
- return new FEImage(filter, tree_scope, href, preserve_aspect_ratio);
+ return MakeGarbageCollected<FEImage>(filter, tree_scope, href,
+ preserve_aspect_ratio);
}
static FloatRect GetLayoutObjectRepaintRect(LayoutObject* layout_object) {
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.h b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.h
index 9628569647d..7e318cee9e9 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.h
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_fe_image.h
@@ -43,6 +43,9 @@ class FEImage final : public FilterEffect {
const String&,
SVGPreserveAspectRatio*);
+ FEImage(Filter*, scoped_refptr<Image>, SVGPreserveAspectRatio*);
+ FEImage(Filter*, TreeScope&, const String&, SVGPreserveAspectRatio*);
+
// feImage does not perform color interpolation of any kind, so doesn't
// depend on the value of color-interpolation-filters.
void SetOperatingInterpolationSpace(InterpolationSpace) override {}
@@ -54,8 +57,6 @@ class FEImage final : public FilterEffect {
private:
~FEImage() override = default;
- FEImage(Filter*, scoped_refptr<Image>, SVGPreserveAspectRatio*);
- FEImage(Filter*, TreeScope&, const String&, SVGPreserveAspectRatio*);
LayoutObject* ReferencedLayoutObject() const;
FilterEffectType GetFilterEffectType() const override {
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h
index e0bfa7826ee..f112e888ff8 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h
@@ -42,7 +42,11 @@ class SVGFilterElement;
class SVGFilterGraphNodeMap final
: public GarbageCollected<SVGFilterGraphNodeMap> {
public:
- static SVGFilterGraphNodeMap* Create() { return new SVGFilterGraphNodeMap; }
+ static SVGFilterGraphNodeMap* Create() {
+ return MakeGarbageCollected<SVGFilterGraphNodeMap>();
+ }
+
+ SVGFilterGraphNodeMap();
typedef HeapHashSet<Member<FilterEffect>> FilterEffectSet;
@@ -66,8 +70,6 @@ class SVGFilterGraphNodeMap final
void Trace(blink::Visitor*);
private:
- SVGFilterGraphNodeMap();
-
// The value is a list, which contains those filter effects,
// which depends on the key filter effect.
HeapHashMap<Member<FilterEffect>, FilterEffectSet> effect_references_;
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.cc b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.cc
index 2ed010aa064..59a27fd3ddb 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.cc
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.cc
@@ -53,6 +53,7 @@
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/image_observer.h"
@@ -62,7 +63,6 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
namespace blink {
@@ -680,7 +680,7 @@ void SVGImage::AdvanceAnimationForTesting() {
page_->Animator().ServiceScriptedAnimations(
base::TimeTicks() +
base::TimeDelta::FromSecondsD(root_element->getCurrentTime()));
- GetImageObserver()->AnimationAdvanced(this);
+ GetImageObserver()->Changed(this);
}
}
@@ -766,7 +766,6 @@ Image::SizeAvailability SVGImage::DataChanged(bool all_data_received) {
page = Page::Create(page_clients);
page->GetSettings().SetScriptEnabled(false);
page->GetSettings().SetPluginsEnabled(false);
- page->GetSettings().SetAcceleratedCompositingEnabled(false);
// Because this page is detached, it can't get default font settings
// from the embedder. Copy over font settings so we have sensible
@@ -791,7 +790,7 @@ Image::SizeAvailability SVGImage::DataChanged(bool all_data_received) {
{
TRACE_EVENT0("blink", "SVGImage::dataChanged::createFrame");
DCHECK(!frame_client_);
- frame_client_ = new SVGImageLocalFrameClient(this);
+ frame_client_ = MakeGarbageCollected<SVGImageLocalFrameClient>(this);
frame = LocalFrame::Create(frame_client_, *page, nullptr);
frame->SetView(LocalFrameView::Create(*frame));
frame->Init();
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc
index 2ffa6b17050..fe25613cd1d 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc
@@ -44,16 +44,13 @@ static constexpr TimeDelta kAnimationFrameDelay =
SVGImageChromeClient::SVGImageChromeClient(SVGImage* image)
: image_(image),
animation_timer_(std::make_unique<TaskRunnerTimer<SVGImageChromeClient>>(
- blink::Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->CompositorTaskRunner(),
+ ThreadScheduler::Current()->CompositorTaskRunner(),
this,
&SVGImageChromeClient::AnimationTimerFired)),
timeline_state_(kRunning) {}
SVGImageChromeClient* SVGImageChromeClient::Create(SVGImage* image) {
- return new SVGImageChromeClient(image);
+ return MakeGarbageCollected<SVGImageChromeClient>(image);
}
bool SVGImageChromeClient::IsSVGImageChromeClient() const {
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.h b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.h
index 059446061e1..a6177c2c389 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.h
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.h
@@ -43,6 +43,8 @@ class CORE_EXPORT SVGImageChromeClient final : public EmptyChromeClient {
public:
static SVGImageChromeClient* Create(SVGImage*);
+ explicit SVGImageChromeClient(SVGImage*);
+
bool IsSVGImageChromeClient() const override;
SVGImage* GetImage() const { return image_; }
@@ -54,8 +56,6 @@ class CORE_EXPORT SVGImageChromeClient final : public EmptyChromeClient {
bool IsSuspended() const { return timeline_state_ >= kSuspended; }
private:
- explicit SVGImageChromeClient(SVGImage*);
-
void ChromeDestroyed() override;
void InvalidateRect(const IntRect&) override;
void ScheduleAnimation(const LocalFrameView*) override;
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc
index 629d8d3d0df..c1d26a3b287 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc
@@ -33,7 +33,7 @@ class SVGImageTest : public testing::Test {
SVGImage& GetImage() { return *image_; }
void Load(const char* data, bool should_pause) {
- observer_ = new PauseControlImageObserver(should_pause);
+ observer_ = MakeGarbageCollected<PauseControlImageObserver>(should_pause);
image_ = SVGImage::Create(observer_);
image_->SetData(SharedBuffer::Create(data, strlen(data)), true);
}
@@ -62,7 +62,6 @@ class SVGImageTest : public testing::Test {
void DecodedSizeChangedTo(const Image*, size_t new_size) override {}
bool ShouldPauseAnimation(const Image*) override { return should_pause_; }
- void AnimationAdvanced(const Image*) override {}
void Changed(const Image*) override {}
diff --git a/chromium/third_party/blink/renderer/core/svg/linear_gradient_attributes.h b/chromium/third_party/blink/renderer/core/svg/linear_gradient_attributes.h
index 775fffaba5a..a4de407df19 100644
--- a/chromium/third_party/blink/renderer/core/svg/linear_gradient_attributes.h
+++ b/chromium/third_party/blink/renderer/core/svg/linear_gradient_attributes.h
@@ -95,9 +95,11 @@ class LinearGradientAttributesWrapper
: public GarbageCollectedFinalized<LinearGradientAttributesWrapper> {
public:
static LinearGradientAttributesWrapper* Create() {
- return new LinearGradientAttributesWrapper;
+ return MakeGarbageCollected<LinearGradientAttributesWrapper>();
}
+ LinearGradientAttributesWrapper() = default;
+
LinearGradientAttributes& Attributes() { return attributes_; }
void Set(const LinearGradientAttributes& attributes) {
attributes_ = attributes;
@@ -105,8 +107,6 @@ class LinearGradientAttributesWrapper
void Trace(blink::Visitor* visitor) { visitor->Trace(attributes_); }
private:
- LinearGradientAttributesWrapper() = default;
-
LinearGradientAttributes attributes_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/pattern_attributes.h b/chromium/third_party/blink/renderer/core/svg/pattern_attributes.h
index b19ea533a5c..85e7696b836 100644
--- a/chromium/third_party/blink/renderer/core/svg/pattern_attributes.h
+++ b/chromium/third_party/blink/renderer/core/svg/pattern_attributes.h
@@ -172,16 +172,16 @@ class PatternAttributesWrapper
: public GarbageCollected<PatternAttributesWrapper> {
public:
static PatternAttributesWrapper* Create() {
- return new PatternAttributesWrapper;
+ return MakeGarbageCollected<PatternAttributesWrapper>();
}
+ PatternAttributesWrapper() = default;
+
PatternAttributes& Attributes() { return attributes_; }
void Set(const PatternAttributes& attributes) { attributes_ = attributes; }
void Trace(blink::Visitor* visitor) { visitor->Trace(attributes_); }
private:
- PatternAttributesWrapper() = default;
-
PatternAttributes attributes_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.h b/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.h
index 2ecf29619a6..cd8948bb20a 100644
--- a/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.h
+++ b/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_PROPERTIES_SVG_ANIMATED_PROPERTY_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/qualified_name.h"
#include "third_party/blink/renderer/core/svg/properties/svg_property_info.h"
#include "third_party/blink/renderer/core/svg/properties/svg_property_tear_off.h"
diff --git a/chromium/third_party/blink/renderer/core/svg/radial_gradient_attributes.h b/chromium/third_party/blink/renderer/core/svg/radial_gradient_attributes.h
index 1fe61dd8cf6..747d1d3655a 100644
--- a/chromium/third_party/blink/renderer/core/svg/radial_gradient_attributes.h
+++ b/chromium/third_party/blink/renderer/core/svg/radial_gradient_attributes.h
@@ -117,9 +117,11 @@ class RadialGradientAttributesWrapper
: public GarbageCollectedFinalized<RadialGradientAttributesWrapper> {
public:
static RadialGradientAttributesWrapper* Create() {
- return new RadialGradientAttributesWrapper;
+ return MakeGarbageCollected<RadialGradientAttributesWrapper>();
}
+ RadialGradientAttributesWrapper() = default;
+
RadialGradientAttributes& Attributes() { return attributes_; }
void Set(const RadialGradientAttributes& attributes) {
attributes_ = attributes;
@@ -127,8 +129,6 @@ class RadialGradientAttributesWrapper
void Trace(blink::Visitor* visitor) { visitor->Trace(attributes_); }
private:
- RadialGradientAttributesWrapper() = default;
-
RadialGradientAttributes attributes_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_a_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_a_element.cc
index 14afe3d3752..3e252ea711c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_a_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_a_element.cc
@@ -47,12 +47,12 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
inline SVGAElement::SVGAElement(Document& document)
- : SVGGraphicsElement(SVGNames::aTag, document),
+ : SVGGraphicsElement(svg_names::kATag, document),
SVGURIReference(this),
- svg_target_(SVGAnimatedString::Create(this, SVGNames::targetAttr)) {
+ svg_target_(SVGAnimatedString::Create(this, svg_names::kTargetAttr)) {
AddToPropertyMap(svg_target_);
}
@@ -66,7 +66,7 @@ DEFINE_NODE_FACTORY(SVGAElement)
String SVGAElement::title() const {
// If the xlink:title is set (non-empty string), use it.
- const AtomicString& title = FastGetAttribute(XLinkNames::titleAttr);
+ const AtomicString& title = FastGetAttribute(xlink_names::kTitleAttr);
if (!title.IsEmpty())
return title;
@@ -126,7 +126,7 @@ void SVGAElement::DefaultEventHandler(Event& event) {
}
AtomicString target(svg_target_->CurrentValue()->Value());
- if (target.IsEmpty() && FastGetAttribute(XLinkNames::showAttr) == "new")
+ if (target.IsEmpty() && FastGetAttribute(xlink_names::kShowAttr) == "new")
target = AtomicString("_blank");
event.SetDefaultHandled();
@@ -172,7 +172,7 @@ bool SVGAElement::ShouldHaveFocusAppearance() const {
}
bool SVGAElement::IsURLAttribute(const Attribute& attribute) const {
- return attribute.GetName().LocalName() == hrefAttr ||
+ return attribute.GetName().LocalName() == kHrefAttr ||
SVGGraphicsElement::IsURLAttribute(attribute);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_angle.cc b/chromium/third_party/blink/renderer/core/svg/svg_angle.cc
index cccd5e46a7c..f6e5f5d4814 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_angle.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_angle.cc
@@ -22,6 +22,7 @@
#include "third_party/blink/renderer/core/svg/svg_angle.h"
#include "third_party/blink/renderer/core/svg/svg_animation_element.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg/svg_parser_utilities.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -29,23 +30,16 @@
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGMarkerOrientType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(kSVGMarkerOrientAuto, "auto"));
- entries.push_back(std::make_pair(kSVGMarkerOrientAngle, "angle"));
- entries.push_back(
- std::make_pair(kSVGMarkerOrientAutoStartReverse, "auto-start-reverse"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGMarkerOrientType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSVGMarkerOrientAuto, "auto"},
+ {kSVGMarkerOrientAngle, "angle"},
+ {kSVGMarkerOrientAutoStartReverse, "auto-start-reverse"},
+ };
+ static const SVGEnumerationMap entries(enum_items, kSVGMarkerOrientAngle);
return entries;
}
-template <>
-unsigned short GetMaxExposedEnumValue<SVGMarkerOrientType>() {
- return kSVGMarkerOrientAngle;
-}
-
SVGMarkerOrientEnumeration::SVGMarkerOrientEnumeration(SVGAngle* angle)
: SVGEnumeration<SVGMarkerOrientType>(kSVGMarkerOrientAngle),
angle_(angle) {}
@@ -109,8 +103,8 @@ void SVGAngle::Trace(blink::Visitor* visitor) {
}
SVGAngle* SVGAngle::Clone() const {
- return new SVGAngle(unit_type_, value_in_specified_units_,
- orient_type_->EnumValue());
+ return MakeGarbageCollected<SVGAngle>(unit_type_, value_in_specified_units_,
+ orient_type_->EnumValue());
}
float SVGAngle::Value() const {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_angle.h b/chromium/third_party/blink/renderer/core/svg/svg_angle.h
index 1ce89a2f040..0ceab5ed1d9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_angle.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_angle.h
@@ -38,19 +38,16 @@ enum SVGMarkerOrientType {
kSVGMarkerOrientAngle,
kSVGMarkerOrientAutoStartReverse
};
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGMarkerOrientType>();
-template <>
-unsigned short GetMaxExposedEnumValue<SVGMarkerOrientType>();
+DECLARE_SVG_ENUM_MAP(SVGMarkerOrientType);
class SVGMarkerOrientEnumeration final
: public SVGEnumeration<SVGMarkerOrientType> {
public:
static SVGMarkerOrientEnumeration* Create(SVGAngle* angle) {
- return new SVGMarkerOrientEnumeration(angle);
+ return MakeGarbageCollected<SVGMarkerOrientEnumeration>(angle);
}
+ SVGMarkerOrientEnumeration(SVGAngle*);
~SVGMarkerOrientEnumeration() override;
void Add(SVGPropertyBase*, SVGElement*) override;
@@ -66,8 +63,6 @@ class SVGMarkerOrientEnumeration final
void Trace(blink::Visitor*) override;
private:
- SVGMarkerOrientEnumeration(SVGAngle*);
-
void NotifyChange() override;
Member<SVGAngle> angle_;
@@ -86,8 +81,10 @@ class SVGAngle final : public SVGPropertyHelper<SVGAngle> {
kSvgAngletypeTurn = 5
};
- static SVGAngle* Create() { return new SVGAngle(); }
+ static SVGAngle* Create() { return MakeGarbageCollected<SVGAngle>(); }
+ SVGAngle();
+ SVGAngle(SVGAngleType, float, SVGMarkerOrientType);
~SVGAngle() override;
SVGAngleType UnitType() const { return unit_type_; }
@@ -142,9 +139,6 @@ class SVGAngle final : public SVGPropertyHelper<SVGAngle> {
void Trace(blink::Visitor*) override;
private:
- SVGAngle();
- SVGAngle(SVGAngleType, float, SVGMarkerOrientType);
-
void Assign(const SVGAngle&);
SVGAngleType unit_type_;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_angle_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_angle_tear_off.h
index 951cf98744a..991960bbea5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_angle_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_angle_tear_off.h
@@ -43,7 +43,8 @@ class SVGAngleTearOff final : public SVGPropertyTearOff<SVGAngle> {
static SVGAngleTearOff* Create(SVGAngle* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGAngleTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGAngleTearOff>(target, binding,
+ property_is_anim_val);
}
static SVGAngleTearOff* CreateDetached();
@@ -55,6 +56,9 @@ class SVGAngleTearOff final : public SVGPropertyTearOff<SVGAngle> {
kSvgAngletypeGrad = SVGAngle::kSvgAngletypeGrad
};
+ SVGAngleTearOff(SVGAngle*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
~SVGAngleTearOff() override;
unsigned short unitType() {
@@ -80,10 +84,6 @@ class SVGAngleTearOff final : public SVGPropertyTearOff<SVGAngle> {
void setValueAsString(const String&, ExceptionState&);
private:
- SVGAngleTearOff(SVGAngle*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
-
bool HasExposedAngleUnit() {
return Target()->UnitType() <= SVGAngle::kSvgAngletypeGrad;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animate_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_animate_element.cc
index a642c1cc0ac..c88b7c7abd1 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animate_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animate_element.cc
@@ -91,8 +91,8 @@ QualifiedName ConstructQualifiedName(const SVGElement& svg_element,
// "Animation elements treat attributeName='xlink:href' as being an alias
// for targetting the 'href' attribute."
// https://svgwg.org/svg2-draft/types.html#__svg__SVGURIReference__href
- if (resolved_attr_name == XLinkNames::hrefAttr)
- return SVGNames::hrefAttr;
+ if (resolved_attr_name == xlink_names::kHrefAttr)
+ return svg_names::kHrefAttr;
return resolved_attr_name;
}
@@ -108,19 +108,20 @@ SVGAnimateElement::SVGAnimateElement(const QualifiedName& tag_name,
attribute_type_(kAttributeTypeAuto) {}
SVGAnimateElement* SVGAnimateElement::Create(Document& document) {
- return new SVGAnimateElement(SVGNames::animateTag, document);
+ return MakeGarbageCollected<SVGAnimateElement>(svg_names::kAnimateTag,
+ document);
}
SVGAnimateElement::~SVGAnimateElement() = default;
bool SVGAnimateElement::IsSVGAnimationAttributeSettingJavaScriptURL(
const Attribute& attribute) const {
- if ((attribute.GetName() == SVGNames::fromAttr ||
- attribute.GetName() == SVGNames::toAttr) &&
+ if ((attribute.GetName() == svg_names::kFromAttr ||
+ attribute.GetName() == svg_names::kToAttr) &&
AttributeValueIsJavaScriptURL(attribute))
return true;
- if (attribute.GetName() == SVGNames::valuesAttr) {
+ if (attribute.GetName() == svg_names::kValuesAttr) {
Vector<String> parts;
if (!ParseValues(attribute.Value(), parts)) {
// Assume the worst.
@@ -140,7 +141,7 @@ Node::InsertionNotificationRequest SVGAnimateElement::InsertedInto(
SVGAnimationElement::InsertedInto(root_parent);
if (root_parent.isConnected()) {
SetAttributeName(ConstructQualifiedName(
- *this, FastGetAttribute(SVGNames::attributeNameAttr)));
+ *this, FastGetAttribute(svg_names::kAttributeNameAttr)));
}
return kInsertionDone;
}
@@ -153,12 +154,12 @@ void SVGAnimateElement::RemovedFrom(ContainerNode& root_parent) {
void SVGAnimateElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == SVGNames::attributeTypeAttr) {
+ if (params.name == svg_names::kAttributeTypeAttr) {
SetAttributeType(params.new_value);
AnimationAttributeChanged();
return;
}
- if (params.name == SVGNames::attributeNameAttr) {
+ if (params.name == svg_names::kAttributeNameAttr) {
SetAttributeName(ConstructQualifiedName(*this, params.new_value));
AnimationAttributeChanged();
return;
@@ -465,8 +466,8 @@ void SVGAnimateElement::ClearAnimatedType() {
target_element->EnsureAnimatedSMILStyleProperties();
if (property_set->RemoveProperty(css_property_id_)) {
target_element->SetNeedsStyleRecalc(
- kLocalStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kAnimation));
+ kLocalStyleChange, StyleChangeReasonForTracing::Create(
+ style_change_reason::kAnimation));
}
}
}
@@ -507,7 +508,7 @@ void SVGAnimateElement::ApplyResultsToTarget() {
.did_change) {
targetElement()->SetNeedsStyleRecalc(
kLocalStyleChange,
- StyleChangeReasonForTracing::Create(StyleChangeReason::kAnimation));
+ StyleChangeReasonForTracing::Create(style_change_reason::kAnimation));
}
}
if (IsAnimatingSVGDom()) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animate_element.h b/chromium/third_party/blink/renderer/core/svg/svg_animate_element.h
index 0a300c31b9e..796237f1dfa 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animate_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animate_element.h
@@ -25,7 +25,7 @@
#include <base/gtest_prod_util.h>
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/svg/svg_animation_element.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -41,6 +41,8 @@ class CORE_EXPORT SVGAnimateElement : public SVGAnimationElement {
public:
static SVGAnimateElement* Create(Document&);
+
+ SVGAnimateElement(const QualifiedName&, Document&);
~SVGAnimateElement() override;
void Trace(blink::Visitor*) override;
@@ -52,8 +54,6 @@ class CORE_EXPORT SVGAnimateElement : public SVGAnimationElement {
bool AnimatedPropertyTypeSupportsAddition();
protected:
- SVGAnimateElement(const QualifiedName&, Document&);
-
bool HasValidTarget() override;
void WillChangeAnimationTarget() final;
@@ -133,9 +133,9 @@ class CORE_EXPORT SVGAnimateElement : public SVGAnimationElement {
};
inline bool IsSVGAnimateElement(const SVGElement& element) {
- return element.HasTagName(SVGNames::animateTag) ||
- element.HasTagName(SVGNames::animateTransformTag) ||
- element.HasTagName(SVGNames::setTag);
+ return element.HasTagName(svg_names::kAnimateTag) ||
+ element.HasTagName(svg_names::kAnimateTransformTag) ||
+ element.HasTagName(svg_names::kSetTag);
}
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGAnimateElement);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animate_motion_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_animate_motion_element.cc
index 5467317ab2a..0c229b5e601 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animate_motion_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animate_motion_element.cc
@@ -57,7 +57,7 @@ bool TargetCanHaveMotionTransform(const SVGElement& target) {
}
inline SVGAnimateMotionElement::SVGAnimateMotionElement(Document& document)
- : SVGAnimationElement(SVGNames::animateMotionTag, document),
+ : SVGAnimationElement(svg_names::kAnimateMotionTag, document),
has_to_point_at_end_of_duration_(false) {
SetCalcMode(kCalcModePaced);
}
@@ -73,7 +73,7 @@ bool SVGAnimateMotionElement::HasValidTarget() {
void SVGAnimateMotionElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == SVGNames::pathAttr) {
+ if (params.name == svg_names::kPathAttr) {
path_ = Path();
BuildPathFromString(params.new_value, path_);
UpdateAnimationPath();
@@ -87,7 +87,7 @@ SVGAnimateMotionElement::RotateMode SVGAnimateMotionElement::GetRotateMode()
const {
DEFINE_STATIC_LOCAL(const AtomicString, auto_val, ("auto"));
DEFINE_STATIC_LOCAL(const AtomicString, auto_reverse, ("auto-reverse"));
- const AtomicString& rotate = getAttribute(SVGNames::rotateAttr);
+ const AtomicString& rotate = getAttribute(svg_names::kRotateAttr);
if (rotate == auto_val)
return kRotateAuto;
if (rotate == auto_reverse)
@@ -108,7 +108,7 @@ void SVGAnimateMotionElement::UpdateAnimationPath() {
}
}
- if (!found_m_path && FastHasAttribute(SVGNames::pathAttr))
+ if (!found_m_path && FastHasAttribute(svg_names::kPathAttr))
animation_path_ = path_;
UpdateAnimationMode();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animate_transform_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_animate_transform_element.cc
index 12ecd8caa71..4972e03e215 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animate_transform_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animate_transform_element.cc
@@ -30,7 +30,7 @@ namespace blink {
inline SVGAnimateTransformElement::SVGAnimateTransformElement(
Document& document)
- : SVGAnimateElement(SVGNames::animateTransformTag, document),
+ : SVGAnimateElement(svg_names::kAnimateTransformTag, document),
transform_type_(kSvgTransformUnknown) {}
DEFINE_NODE_FACTORY(SVGAnimateTransformElement)
@@ -67,7 +67,7 @@ SVGPropertyBase* SVGAnimateTransformElement::CreatePropertyForAnimation(
void SVGAnimateTransformElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == SVGNames::typeAttr) {
+ if (params.name == svg_names::kTypeAttr) {
transform_type_ = ParseTransformType(params.new_value);
if (transform_type_ == kSvgTransformMatrix)
transform_type_ = kSvgTransformUnknown;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.cc b/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.cc
index 47ddc36a7e5..2f69e0eb03c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.cc
@@ -36,11 +36,11 @@ namespace blink {
SVGAnimatedAngle::SVGAnimatedAngle(SVGElement* context_element)
: SVGAnimatedProperty<SVGAngle>(context_element,
- SVGNames::orientAttr,
+ svg_names::kOrientAttr,
SVGAngle::Create()),
orient_type_(SVGAnimatedEnumeration<SVGMarkerOrientType>::Create(
context_element,
- SVGNames::orientAttr,
+ svg_names::kOrientAttr,
BaseValue()->OrientType())) {}
SVGAnimatedAngle::~SVGAnimatedAngle() = default;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.h
index 3e8761e6faf..a7edb0aca21 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.h
@@ -45,9 +45,10 @@ class SVGAnimatedAngle final : public ScriptWrappable,
public:
static SVGAnimatedAngle* Create(SVGElement* context_element) {
- return new SVGAnimatedAngle(context_element);
+ return MakeGarbageCollected<SVGAnimatedAngle>(context_element);
}
+ explicit SVGAnimatedAngle(SVGElement* context_element);
~SVGAnimatedAngle() override;
SVGAnimatedEnumeration<SVGMarkerOrientType>* OrientType() {
@@ -63,9 +64,6 @@ class SVGAnimatedAngle final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
- protected:
- explicit SVGAnimatedAngle(SVGElement* context_element);
-
private:
Member<SVGAnimatedEnumeration<SVGMarkerOrientType>> orient_type_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.h
index 1220c930907..b7c06b10871 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.h
@@ -45,20 +45,20 @@ class SVGAnimatedBoolean final : public ScriptWrappable,
public:
static SVGAnimatedBoolean* Create(SVGElement* context_element,
const QualifiedName& attribute_name) {
- return new SVGAnimatedBoolean(context_element, attribute_name);
+ return MakeGarbageCollected<SVGAnimatedBoolean>(context_element,
+ attribute_name);
}
- void Trace(blink::Visitor* visitor) override {
- SVGAnimatedProperty<SVGBoolean>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- }
-
- protected:
SVGAnimatedBoolean(SVGElement* context_element,
const QualifiedName& attribute_name)
: SVGAnimatedProperty<SVGBoolean>(context_element,
attribute_name,
SVGBoolean::Create()) {}
+
+ void Trace(blink::Visitor* visitor) override {
+ SVGAnimatedProperty<SVGBoolean>::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_color.cc b/chromium/third_party/blink/renderer/core/svg/svg_animated_color.cc
index ea32f72178e..906aca80cf7 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_color.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_color.cc
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/core/svg/svg_animated_color.h"
+#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/svg/color_distance.h"
@@ -36,7 +37,8 @@ SVGColorProperty::SVGColorProperty(const String& color_string)
String SVGColorProperty::ValueAsString() const {
return style_color_.IsCurrentColor()
? "currentColor"
- : style_color_.GetColor().SerializedAsCSSComponentValue();
+ : cssvalue::CSSColorValue::SerializeAsCSSComponentValue(
+ style_color_.GetColor());
}
SVGPropertyBase* SVGColorProperty::CloneForAnimation(const String&) const {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_color.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_color.h
index 0747ef29358..f59a49d17f2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_color.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_color.h
@@ -44,9 +44,11 @@ class SVGAnimationElement;
class SVGColorProperty final : public SVGPropertyBase {
public:
static SVGColorProperty* Create(const String& color_string) {
- return new SVGColorProperty(color_string);
+ return MakeGarbageCollected<SVGColorProperty>(color_string);
}
+ explicit SVGColorProperty(const String&);
+
SVGPropertyBase* CloneForAnimation(const String&) const override;
String ValueAsString() const override;
@@ -64,8 +66,6 @@ class SVGColorProperty final : public SVGPropertyBase {
AnimatedPropertyType GetType() const override { return ClassType(); }
private:
- explicit SVGColorProperty(const String&);
-
StyleColor style_color_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.h
index b64f188d34c..cb8dfe6c45d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.h
@@ -42,7 +42,7 @@ class SVGAnimatedEnumeration : public SVGAnimatedEnumerationBase {
SVGElement* context_element,
const QualifiedName& attribute_name,
Enum initial_value) {
- return new SVGAnimatedEnumeration(
+ return MakeGarbageCollected<SVGAnimatedEnumeration>(
context_element, attribute_name,
SVGEnumeration<Enum>::Create(initial_value),
static_cast<unsigned>(initial_value));
@@ -52,11 +52,20 @@ class SVGAnimatedEnumeration : public SVGAnimatedEnumerationBase {
SVGElement* context_element,
const QualifiedName& attribute_name,
SVGEnumeration<Enum>* initial_value) {
- return new SVGAnimatedEnumeration(
+ return MakeGarbageCollected<SVGAnimatedEnumeration>(
context_element, attribute_name, initial_value,
static_cast<unsigned>(initial_value->EnumValue()));
}
+ SVGAnimatedEnumeration(SVGElement* context_element,
+ const QualifiedName& attribute_name,
+ SVGEnumeration<Enum>* initial_value,
+ unsigned initial_enum_value)
+ : SVGAnimatedEnumerationBase(context_element,
+ attribute_name,
+ initial_value,
+ initial_enum_value) {}
+
SVGEnumeration<Enum>* BaseValue() {
return static_cast<SVGEnumeration<Enum>*>(
SVGAnimatedEnumerationBase::BaseValue());
@@ -71,16 +80,6 @@ class SVGAnimatedEnumeration : public SVGAnimatedEnumerationBase {
return static_cast<const SVGEnumeration<Enum>*>(
SVGAnimatedEnumerationBase::CurrentValue());
}
-
- protected:
- SVGAnimatedEnumeration(SVGElement* context_element,
- const QualifiedName& attribute_name,
- SVGEnumeration<Enum>* initial_value,
- unsigned initial_enum_value)
- : SVGAnimatedEnumerationBase(context_element,
- attribute_name,
- initial_value,
- initial_enum_value) {}
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_href.cc b/chromium/third_party/blink/renderer/core/svg/svg_animated_href.cc
index 2cfdfe71a05..accfa5b6398 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_href.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_href.cc
@@ -12,7 +12,7 @@
namespace blink {
SVGAnimatedHref* SVGAnimatedHref::Create(SVGElement* context_element) {
- return new SVGAnimatedHref(context_element);
+ return MakeGarbageCollected<SVGAnimatedHref>(context_element);
}
void SVGAnimatedHref::Trace(blink::Visitor* visitor) {
@@ -21,9 +21,9 @@ void SVGAnimatedHref::Trace(blink::Visitor* visitor) {
}
SVGAnimatedHref::SVGAnimatedHref(SVGElement* context_element)
- : SVGAnimatedString(context_element, SVGNames::hrefAttr),
+ : SVGAnimatedString(context_element, svg_names::kHrefAttr),
xlink_href_(
- SVGAnimatedString::Create(context_element, XLinkNames::hrefAttr)) {}
+ SVGAnimatedString::Create(context_element, xlink_names::kHrefAttr)) {}
void SVGAnimatedHref::AddToPropertyMap(SVGElement* element) {
element->AddToPropertyMap(this);
@@ -31,8 +31,8 @@ void SVGAnimatedHref::AddToPropertyMap(SVGElement* element) {
}
bool SVGAnimatedHref::IsKnownAttribute(const QualifiedName& attr_name) {
- return attr_name.Matches(SVGNames::hrefAttr) ||
- attr_name.Matches(XLinkNames::hrefAttr);
+ return attr_name.Matches(svg_names::kHrefAttr) ||
+ attr_name.Matches(xlink_names::kHrefAttr);
}
SVGString* SVGAnimatedHref::CurrentValue() {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_href.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_href.h
index a1aae285c84..041276d6b8f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_href.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_href.h
@@ -21,6 +21,8 @@ class SVGAnimatedHref final : public SVGAnimatedString {
public:
static SVGAnimatedHref* Create(SVGElement* context_element);
+ explicit SVGAnimatedHref(SVGElement* context_element);
+
SVGString* CurrentValue();
const SVGString* CurrentValue() const;
@@ -38,8 +40,6 @@ class SVGAnimatedHref final : public SVGAnimatedString {
void Trace(blink::Visitor*) override;
private:
- explicit SVGAnimatedHref(SVGElement* context_element);
-
SVGAnimatedString* BackingString();
const SVGAnimatedString* BackingString() const;
bool UseXLink() const;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.h
index aed647f75b9..ab271dbb255 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.h
@@ -51,26 +51,16 @@ class SVGAnimatedInteger : public ScriptWrappable,
const QualifiedName& attribute_name,
int initial) {
SVGInteger* initial_value = SVGInteger::Create(initial);
- return new SVGAnimatedInteger(context_element, attribute_name,
- initial_value);
+ return MakeGarbageCollected<SVGAnimatedInteger>(
+ context_element, attribute_name, initial_value);
}
static SVGAnimatedInteger* Create(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGInteger* initial_value) {
- return new SVGAnimatedInteger(context_element, attribute_name,
- initial_value);
+ return MakeGarbageCollected<SVGAnimatedInteger>(
+ context_element, attribute_name, initial_value);
}
- void SynchronizeAttribute() override;
-
- void SetParentOptionalInteger(
- SVGAnimatedIntegerOptionalInteger* number_optional_integer) {
- parent_integer_optional_integer_ = number_optional_integer;
- }
-
- void Trace(blink::Visitor*) override;
-
- protected:
SVGAnimatedInteger(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGInteger* initial_value)
@@ -81,6 +71,16 @@ class SVGAnimatedInteger : public ScriptWrappable,
initial_value->Value()),
parent_integer_optional_integer_(nullptr) {}
+ void SynchronizeAttribute() override;
+
+ void SetParentOptionalInteger(
+ SVGAnimatedIntegerOptionalInteger* number_optional_integer) {
+ parent_integer_optional_integer_ = number_optional_integer;
+ }
+
+ void Trace(blink::Visitor*) override;
+
+ protected:
Member<SVGAnimatedIntegerOptionalInteger> parent_integer_optional_integer_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_integer_optional_integer.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_integer_optional_integer.h
index a7a095bcbe9..776c9a5644c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_integer_optional_integer.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_integer_optional_integer.h
@@ -53,10 +53,14 @@ class SVGAnimatedIntegerOptionalInteger
SVGElement* context_element,
const QualifiedName& attribute_name,
int initial_value) {
- return new SVGAnimatedIntegerOptionalInteger(context_element,
- attribute_name, initial_value);
+ return MakeGarbageCollected<SVGAnimatedIntegerOptionalInteger>(
+ context_element, attribute_name, initial_value);
}
+ SVGAnimatedIntegerOptionalInteger(SVGElement* context_element,
+ const QualifiedName& attribute_name,
+ int initial_value);
+
void SetAnimatedValue(SVGPropertyBase*) override;
bool NeedsSynchronizeAttribute() const override;
void AnimationEnded() override;
@@ -67,10 +71,6 @@ class SVGAnimatedIntegerOptionalInteger
void Trace(blink::Visitor*) override;
protected:
- SVGAnimatedIntegerOptionalInteger(SVGElement* context_element,
- const QualifiedName& attribute_name,
- int initial_value);
-
Member<SVGAnimatedInteger> first_integer_;
Member<SVGAnimatedInteger> second_integer_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_length.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_length.h
index 0f2cff3c3c4..587c23eeed6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_length.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_length.h
@@ -49,19 +49,10 @@ class SVGAnimatedLength : public ScriptWrappable,
SVGLengthMode mode,
SVGLength::Initial initial_value,
CSSPropertyID css_property_id = CSSPropertyInvalid) {
- return new SVGAnimatedLength(context_element, attribute_name, mode,
- initial_value, css_property_id);
+ return MakeGarbageCollected<SVGAnimatedLength>(
+ context_element, attribute_name, mode, initial_value, css_property_id);
}
- SVGParsingError AttributeChanged(const String&) override;
-
- const CSSValue& CssValue() const {
- return CurrentValue()->AsCSSPrimitiveValue();
- }
-
- void Trace(blink::Visitor*) override;
-
- protected:
SVGAnimatedLength(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGLengthMode mode,
@@ -72,6 +63,14 @@ class SVGAnimatedLength : public ScriptWrappable,
SVGLength::Create(initial_value, mode),
css_property_id,
static_cast<unsigned>(initial_value)) {}
+
+ SVGParsingError AttributeChanged(const String&) override;
+
+ const CSSValue& CssValue() const {
+ return CurrentValue()->AsCSSPrimitiveValue();
+ }
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.h
index 3738a2012b8..91905177f91 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.h
@@ -48,22 +48,21 @@ class SVGAnimatedLengthList final : public ScriptWrappable,
static SVGAnimatedLengthList* Create(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGLengthList* initial_value) {
- return new SVGAnimatedLengthList(context_element, attribute_name,
- initial_value);
+ return MakeGarbageCollected<SVGAnimatedLengthList>(
+ context_element, attribute_name, initial_value);
}
- void Trace(blink::Visitor* visitor) override {
- SVGAnimatedProperty<SVGLengthList>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- }
-
- protected:
SVGAnimatedLengthList(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGLengthList* initial_value)
: SVGAnimatedProperty<SVGLengthList>(context_element,
attribute_name,
initial_value) {}
+
+ void Trace(blink::Visitor* visitor) override {
+ SVGAnimatedProperty<SVGLengthList>::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_number.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_number.h
index cbf8d4b7f78..317ca37274f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_number.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_number.h
@@ -51,26 +51,16 @@ class SVGAnimatedNumber : public ScriptWrappable,
const QualifiedName& attribute_name,
float initial_number) {
SVGNumber* initial_value = SVGNumber::Create(initial_number);
- return new SVGAnimatedNumber(context_element, attribute_name,
- initial_value);
+ return MakeGarbageCollected<SVGAnimatedNumber>(
+ context_element, attribute_name, initial_value);
}
static SVGAnimatedNumber* Create(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGNumber* initial_value) {
- return new SVGAnimatedNumber(context_element, attribute_name,
- initial_value);
+ return MakeGarbageCollected<SVGAnimatedNumber>(
+ context_element, attribute_name, initial_value);
}
- void SynchronizeAttribute() override;
-
- void SetParentOptionalNumber(
- SVGAnimatedNumberOptionalNumber* number_optional_number) {
- parent_number_optional_number_ = number_optional_number;
- }
-
- void Trace(blink::Visitor*) override;
-
- protected:
SVGAnimatedNumber(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGNumber* initial_value)
@@ -82,6 +72,16 @@ class SVGAnimatedNumber : public ScriptWrappable,
static_cast<unsigned>(initial_value->Value())),
parent_number_optional_number_(nullptr) {}
+ void SynchronizeAttribute() override;
+
+ void SetParentOptionalNumber(
+ SVGAnimatedNumberOptionalNumber* number_optional_number) {
+ parent_number_optional_number_ = number_optional_number;
+ }
+
+ void Trace(blink::Visitor*) override;
+
+ protected:
Member<SVGAnimatedNumberOptionalNumber> parent_number_optional_number_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.h
index e06f6ac5a78..df7e2fe994e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.h
@@ -47,20 +47,20 @@ class SVGAnimatedNumberList final : public ScriptWrappable,
public:
static SVGAnimatedNumberList* Create(SVGElement* context_element,
const QualifiedName& attribute_name) {
- return new SVGAnimatedNumberList(context_element, attribute_name);
+ return MakeGarbageCollected<SVGAnimatedNumberList>(context_element,
+ attribute_name);
}
- void Trace(blink::Visitor* visitor) override {
- SVGAnimatedProperty<SVGNumberList>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- }
-
- protected:
SVGAnimatedNumberList(SVGElement* context_element,
const QualifiedName& attribute_name)
: SVGAnimatedProperty<SVGNumberList>(context_element,
attribute_name,
SVGNumberList::Create()) {}
+
+ void Trace(blink::Visitor* visitor) override {
+ SVGAnimatedProperty<SVGNumberList>::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_number_optional_number.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_number_optional_number.h
index 658b1462ac2..b8185ca5daa 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_number_optional_number.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_number_optional_number.h
@@ -53,10 +53,14 @@ class SVGAnimatedNumberOptionalNumber
SVGElement* context_element,
const QualifiedName& attribute_name,
float initial_value) {
- return new SVGAnimatedNumberOptionalNumber(context_element, attribute_name,
- initial_value);
+ return MakeGarbageCollected<SVGAnimatedNumberOptionalNumber>(
+ context_element, attribute_name, initial_value);
}
+ SVGAnimatedNumberOptionalNumber(SVGElement* context_element,
+ const QualifiedName& attribute_name,
+ float initial_value);
+
void SetAnimatedValue(SVGPropertyBase*) override;
bool NeedsSynchronizeAttribute() const override;
void AnimationEnded() override;
@@ -67,10 +71,6 @@ class SVGAnimatedNumberOptionalNumber
void Trace(blink::Visitor*) override;
protected:
- SVGAnimatedNumberOptionalNumber(SVGElement* context_element,
- const QualifiedName& attribute_name,
- float initial_value);
-
Member<SVGAnimatedNumber> first_number_;
Member<SVGAnimatedNumber> second_number_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_path.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_path.h
index 8e0dbee9fe7..8cb6a9b3b28 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_path.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_path.h
@@ -47,16 +47,15 @@ class SVGAnimatedPath final : public GarbageCollectedFinalized<SVGAnimatedPath>,
SVGElement* context_element,
const QualifiedName& attribute_name,
CSSPropertyID css_property_id = CSSPropertyInvalid) {
- return new SVGAnimatedPath(context_element, attribute_name,
- css_property_id);
+ return MakeGarbageCollected<SVGAnimatedPath>(
+ context_element, attribute_name, css_property_id);
}
- const CSSValue& CssValue() const;
-
- protected:
SVGAnimatedPath(SVGElement*,
const QualifiedName&,
CSSPropertyID = CSSPropertyInvalid);
+
+ const CSSValue& CssValue() const;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_point_list.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_point_list.h
index 903d3a0bdfa..26844d948a2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_point_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_point_list.h
@@ -47,11 +47,10 @@ class SVGAnimatedPointList final
const QualifiedName& attribute_name,
SVGPointList* initial_value,
CSSPropertyID css_property_id = CSSPropertyInvalid) {
- return new SVGAnimatedPointList(context_element, attribute_name,
- initial_value, css_property_id);
+ return MakeGarbageCollected<SVGAnimatedPointList>(
+ context_element, attribute_name, initial_value, css_property_id);
}
- protected:
SVGAnimatedPointList(SVGElement* context_element,
const QualifiedName& attribute_name,
SVGPointList* initial_value,
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.h
index 9a5a2708c06..c26839054c9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.h
@@ -47,21 +47,21 @@ class SVGAnimatedPreserveAspectRatio
static SVGAnimatedPreserveAspectRatio* Create(
SVGElement* context_element,
const QualifiedName& attribute_name) {
- return new SVGAnimatedPreserveAspectRatio(context_element, attribute_name);
+ return MakeGarbageCollected<SVGAnimatedPreserveAspectRatio>(context_element,
+ attribute_name);
}
- void Trace(blink::Visitor* visitor) override {
- SVGAnimatedProperty<SVGPreserveAspectRatio>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- }
-
- protected:
SVGAnimatedPreserveAspectRatio(SVGElement* context_element,
const QualifiedName& attribute_name)
: SVGAnimatedProperty<SVGPreserveAspectRatio>(
context_element,
attribute_name,
SVGPreserveAspectRatio::Create()) {}
+
+ void Trace(blink::Visitor* visitor) override {
+ SVGAnimatedProperty<SVGPreserveAspectRatio>::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.h
index c400d9c3840..ad95d13a810 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.h
@@ -45,20 +45,20 @@ class SVGAnimatedRect : public ScriptWrappable,
public:
static SVGAnimatedRect* Create(SVGElement* context_element,
const QualifiedName& attribute_name) {
- return new SVGAnimatedRect(context_element, attribute_name);
+ return MakeGarbageCollected<SVGAnimatedRect>(context_element,
+ attribute_name);
}
- void Trace(blink::Visitor* visitor) override {
- SVGAnimatedProperty<SVGRect>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- }
-
- protected:
SVGAnimatedRect(SVGElement* context_element,
const QualifiedName& attribute_name)
: SVGAnimatedProperty<SVGRect>(context_element,
attribute_name,
SVGRect::CreateInvalid()) {}
+
+ void Trace(blink::Visitor* visitor) override {
+ SVGAnimatedProperty<SVGRect>::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_string.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_string.h
index 13b213d5b6a..dc9399f2bce 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_string.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_string.h
@@ -45,21 +45,21 @@ class SVGAnimatedString : public ScriptWrappable,
public:
static SVGAnimatedString* Create(SVGElement* context_element,
const QualifiedName& attribute_name) {
- return new SVGAnimatedString(context_element, attribute_name);
+ return MakeGarbageCollected<SVGAnimatedString>(context_element,
+ attribute_name);
}
- virtual String baseVal();
- virtual void setBaseVal(const String&, ExceptionState&);
- virtual String animVal();
-
- void Trace(blink::Visitor*) override;
-
- protected:
SVGAnimatedString(SVGElement* context_element,
const QualifiedName& attribute_name)
: SVGAnimatedProperty<SVGString>(context_element,
attribute_name,
SVGString::Create()) {}
+
+ virtual String baseVal();
+ virtual void setBaseVal(const String&, ExceptionState&);
+ virtual String animVal();
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.h b/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.h
index e40b3dc092b..31bae649dd0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.h
@@ -50,16 +50,10 @@ class SVGAnimatedTransformList final
SVGElement* context_element,
const QualifiedName& attribute_name,
CSSPropertyID css_property_id = CSSPropertyInvalid) {
- return new SVGAnimatedTransformList(context_element, attribute_name,
- css_property_id);
+ return MakeGarbageCollected<SVGAnimatedTransformList>(
+ context_element, attribute_name, css_property_id);
}
- void Trace(blink::Visitor* visitor) override {
- SVGAnimatedProperty<SVGTransformList>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- }
-
- protected:
SVGAnimatedTransformList(SVGElement* context_element,
const QualifiedName& attribute_name,
CSSPropertyID css_property_id)
@@ -67,6 +61,11 @@ class SVGAnimatedTransformList final
attribute_name,
SVGTransformList::Create(),
css_property_id) {}
+
+ void Trace(blink::Visitor* visitor) override {
+ SVGAnimatedProperty<SVGTransformList>::Trace(visitor);
+ ScriptWrappable::Trace(visitor);
+ }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animation_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_animation_element.cc
index 1c8e310b5b1..6c4c0b34cd7 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animation_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animation_element.cc
@@ -40,7 +40,6 @@ SVGAnimationElement::SVGAnimationElement(const QualifiedName& tag_name,
animation_valid_(false),
calc_mode_(kCalcModeLinear),
animation_mode_(kNoAnimation) {
- DCHECK(RuntimeEnabledFeatures::SMILEnabled());
UseCounter::Count(document, WebFeature::kSVGAnimationElement);
}
@@ -156,7 +155,7 @@ static bool ParseKeySplines(const String& string,
void SVGAnimationElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
- if (name == SVGNames::valuesAttr) {
+ if (name == svg_names::kValuesAttr) {
if (!ParseValues(params.new_value, values_)) {
ReportAttributeParsingError(SVGParseStatus::kParsingFailed, name,
params.new_value);
@@ -166,7 +165,7 @@ void SVGAnimationElement::ParseAttribute(
return;
}
- if (name == SVGNames::keyTimesAttr) {
+ if (name == svg_names::kKeyTimesAttr) {
if (!ParseKeyTimes(params.new_value, key_times_, true)) {
ReportAttributeParsingError(SVGParseStatus::kParsingFailed, name,
params.new_value);
@@ -174,7 +173,7 @@ void SVGAnimationElement::ParseAttribute(
return;
}
- if (name == SVGNames::keyPointsAttr) {
+ if (name == svg_names::kKeyPointsAttr) {
if (IsSVGAnimateMotionElement(*this)) {
// This is specified to be an animateMotion attribute only but it is
// simpler to put it here where the other timing calculatations are.
@@ -186,7 +185,7 @@ void SVGAnimationElement::ParseAttribute(
return;
}
- if (name == SVGNames::keySplinesAttr) {
+ if (name == svg_names::kKeySplinesAttr) {
if (!ParseKeySplines(params.new_value, key_splines_)) {
ReportAttributeParsingError(SVGParseStatus::kParsingFailed, name,
params.new_value);
@@ -194,13 +193,13 @@ void SVGAnimationElement::ParseAttribute(
return;
}
- if (name == SVGNames::calcModeAttr) {
+ if (name == svg_names::kCalcModeAttr) {
SetCalcMode(params.new_value);
return;
}
- if (name == SVGNames::fromAttr || name == SVGNames::toAttr ||
- name == SVGNames::byAttr) {
+ if (name == svg_names::kFromAttr || name == svg_names::kToAttr ||
+ name == svg_names::kByAttr) {
UpdateAnimationMode();
return;
}
@@ -209,12 +208,12 @@ void SVGAnimationElement::ParseAttribute(
}
void SVGAnimationElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::valuesAttr || attr_name == SVGNames::byAttr ||
- attr_name == SVGNames::fromAttr || attr_name == SVGNames::toAttr ||
- attr_name == SVGNames::calcModeAttr ||
- attr_name == SVGNames::keySplinesAttr ||
- attr_name == SVGNames::keyPointsAttr ||
- attr_name == SVGNames::keyTimesAttr) {
+ if (attr_name == svg_names::kValuesAttr || attr_name == svg_names::kByAttr ||
+ attr_name == svg_names::kFromAttr || attr_name == svg_names::kToAttr ||
+ attr_name == svg_names::kCalcModeAttr ||
+ attr_name == svg_names::kKeySplinesAttr ||
+ attr_name == svg_names::kKeyPointsAttr ||
+ attr_name == svg_names::kKeyTimesAttr) {
AnimationAttributeChanged();
return;
}
@@ -272,7 +271,7 @@ void SVGAnimationElement::endElementAt(float offset) {
void SVGAnimationElement::UpdateAnimationMode() {
// http://www.w3.org/TR/2001/REC-smil-animation-20010904/#AnimFuncValues
- if (hasAttribute(SVGNames::valuesAttr))
+ if (hasAttribute(svg_names::kValuesAttr))
SetAnimationMode(kValuesAnimation);
else if (!ToValue().IsEmpty())
SetAnimationMode(FromValue().IsEmpty() ? kToAnimation : kFromToAnimation);
@@ -310,26 +309,26 @@ void SVGAnimationElement::SetCalcMode(const AtomicString& calc_mode) {
}
String SVGAnimationElement::ToValue() const {
- return FastGetAttribute(SVGNames::toAttr);
+ return FastGetAttribute(svg_names::kToAttr);
}
String SVGAnimationElement::ByValue() const {
- return FastGetAttribute(SVGNames::byAttr);
+ return FastGetAttribute(svg_names::kByAttr);
}
String SVGAnimationElement::FromValue() const {
- return FastGetAttribute(SVGNames::fromAttr);
+ return FastGetAttribute(svg_names::kFromAttr);
}
bool SVGAnimationElement::IsAdditive() {
DEFINE_STATIC_LOCAL(const AtomicString, sum, ("sum"));
- const AtomicString& value = FastGetAttribute(SVGNames::additiveAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kAdditiveAttr);
return value == sum || GetAnimationMode() == kByAnimation;
}
bool SVGAnimationElement::IsAccumulated() const {
DEFINE_STATIC_LOCAL(const AtomicString, sum, ("sum"));
- const AtomicString& value = FastGetAttribute(SVGNames::accumulateAttr);
+ const AtomicString& value = FastGetAttribute(svg_names::kAccumulateAttr);
return value == sum && GetAnimationMode() != kToAnimation;
}
@@ -524,7 +523,7 @@ void SVGAnimationElement::StartedActiveInterval() {
return;
// These validations are appropriate for all animation modes.
- if (FastHasAttribute(SVGNames::keyPointsAttr) &&
+ if (FastHasAttribute(svg_names::kKeyPointsAttr) &&
key_points_.size() != key_times_.size())
return;
@@ -533,11 +532,11 @@ void SVGAnimationElement::StartedActiveInterval() {
if (calc_mode == kCalcModeSpline) {
unsigned splines_count = key_splines_.size();
if (!splines_count ||
- (FastHasAttribute(SVGNames::keyPointsAttr) &&
+ (FastHasAttribute(svg_names::kKeyPointsAttr) &&
key_points_.size() - 1 != splines_count) ||
(animation_mode == kValuesAnimation &&
values_.size() - 1 != splines_count) ||
- (FastHasAttribute(SVGNames::keyTimesAttr) &&
+ (FastHasAttribute(svg_names::kKeyTimesAttr) &&
key_times_.size() - 1 != splines_count))
return;
}
@@ -550,8 +549,8 @@ void SVGAnimationElement::StartedActiveInterval() {
if ((animation_mode == kFromToAnimation ||
animation_mode == kFromByAnimation || animation_mode == kToAnimation ||
animation_mode == kByAnimation) &&
- (FastHasAttribute(SVGNames::keyPointsAttr) &&
- FastHasAttribute(SVGNames::keyTimesAttr) &&
+ (FastHasAttribute(svg_names::kKeyPointsAttr) &&
+ FastHasAttribute(svg_names::kKeyTimesAttr) &&
(key_times_.size() < 2 || key_times_.size() != key_points_.size())))
return;
if (animation_mode == kFromToAnimation) {
@@ -569,8 +568,8 @@ void SVGAnimationElement::StartedActiveInterval() {
animation_valid_ =
values_.size() >= 1 &&
(calc_mode == kCalcModePaced ||
- !FastHasAttribute(SVGNames::keyTimesAttr) ||
- FastHasAttribute(SVGNames::keyPointsAttr) ||
+ !FastHasAttribute(svg_names::kKeyTimesAttr) ||
+ FastHasAttribute(svg_names::kKeyPointsAttr) ||
(values_.size() == key_times_.size())) &&
(calc_mode == kCalcModeDiscrete || !key_times_.size() ||
key_times_.back() == 1) &&
@@ -578,7 +577,7 @@ void SVGAnimationElement::StartedActiveInterval() {
((key_splines_.size() &&
(key_splines_.size() == values_.size() - 1)) ||
key_splines_.size() == key_points_.size() - 1)) &&
- (!FastHasAttribute(SVGNames::keyPointsAttr) ||
+ (!FastHasAttribute(svg_names::kKeyPointsAttr) ||
(key_times_.size() > 1 && key_times_.size() == key_points_.size()));
if (animation_valid_)
animation_valid_ = CalculateToAtEndOfDurationValue(values_.back());
@@ -587,7 +586,7 @@ void SVGAnimationElement::StartedActiveInterval() {
} else if (animation_mode == kPathAnimation) {
animation_valid_ =
calc_mode == kCalcModePaced ||
- !FastHasAttribute(SVGNames::keyPointsAttr) ||
+ !FastHasAttribute(svg_names::kKeyPointsAttr) ||
(key_times_.size() > 1 && key_times_.size() == key_points_.size());
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animation_element.h b/chromium/third_party/blink/renderer/core/svg/svg_animation_element.h
index d9129f870e6..9c03ef7264c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animation_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animation_element.h
@@ -65,9 +65,9 @@ class CORE_EXPORT SVGAnimationElement : public SVGSMILElement {
void endElement() { endElementAt(0); }
void endElementAt(float offset);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(begin, beginEvent);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(end, endEvent);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(repeat, repeatEvent);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(begin, kBeginEvent);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(end, kEndEvent);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(repeat, kRepeatEvent);
virtual bool IsAdditive();
bool IsAccumulated() const;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animation_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_animation_element.idl
index 0eaf56fe27f..a56ef3dc1d6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animation_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animation_element.idl
@@ -26,7 +26,6 @@
// https://svgwg.org/specs/animations/#InterfaceSVGAnimationElement
-[RuntimeEnabled=SMIL]
interface SVGAnimationElement : SVGElement {
readonly attribute SVGElement targetElement;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_boolean.h b/chromium/third_party/blink/renderer/core/svg/svg_boolean.h
index 84cd9b11e0d..5a266f603b0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_boolean.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_boolean.h
@@ -43,9 +43,11 @@ class SVGBoolean final : public SVGPropertyHelper<SVGBoolean> {
typedef bool PrimitiveType;
static SVGBoolean* Create(bool value = false) {
- return new SVGBoolean(value);
+ return MakeGarbageCollected<SVGBoolean>(value);
}
+ SVGBoolean(bool value) : value_(value) {}
+
SVGBoolean* Clone() const { return Create(value_); }
String ValueAsString() const override;
@@ -67,8 +69,6 @@ class SVGBoolean final : public SVGPropertyHelper<SVGBoolean> {
static AnimatedPropertyType ClassType() { return kAnimatedBoolean; }
private:
- SVGBoolean(bool value) : value_(value) {}
-
bool value_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_circle_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_circle_element.cc
index 41d800695ed..317133f6ebe 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_circle_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_circle_element.cc
@@ -26,19 +26,19 @@
namespace blink {
inline SVGCircleElement::SVGCircleElement(Document& document)
- : SVGGeometryElement(SVGNames::circleTag, document),
+ : SVGGeometryElement(svg_names::kCircleTag, document),
cx_(SVGAnimatedLength::Create(this,
- SVGNames::cxAttr,
+ svg_names::kCxAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyCx)),
cy_(SVGAnimatedLength::Create(this,
- SVGNames::cyAttr,
+ svg_names::kCyAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyCy)),
r_(SVGAnimatedLength::Create(this,
- SVGNames::rAttr,
+ svg_names::kRAttr,
SVGLengthMode::kOther,
SVGLength::Initial::kUnitlessZero,
CSSPropertyR)) {
@@ -96,8 +96,8 @@ void SVGCircleElement::CollectStyleForPresentationAttribute(
}
void SVGCircleElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::rAttr || attr_name == SVGNames::cxAttr ||
- attr_name == SVGNames::cyAttr) {
+ if (attr_name == svg_names::kRAttr || attr_name == svg_names::kCxAttr ||
+ attr_name == svg_names::kCyAttr) {
UpdateRelativeLengthsInformation();
GeometryPresentationAttributeChanged(attr_name);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_clip_path_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_clip_path_element.cc
index 82b66e13d50..eb5fe77b7e0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_clip_path_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_clip_path_element.cc
@@ -26,11 +26,11 @@
namespace blink {
inline SVGClipPathElement::SVGClipPathElement(Document& document)
- : SVGGraphicsElement(SVGNames::clipPathTag, document),
+ : SVGGraphicsElement(svg_names::kClipPathTag, document),
clip_path_units_(
SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::clipPathUnitsAttr,
+ svg_names::kClipPathUnitsAttr,
SVGUnitTypes::kSvgUnitTypeUserspaceonuse)) {
AddToPropertyMap(clip_path_units_);
}
@@ -43,7 +43,7 @@ void SVGClipPathElement::Trace(blink::Visitor* visitor) {
DEFINE_NODE_FACTORY(SVGClipPathElement)
void SVGClipPathElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::clipPathUnitsAttr) {
+ if (attr_name == svg_names::kClipPathUnitsAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
LayoutSVGResourceContainer* layout_object =
@@ -62,9 +62,10 @@ void SVGClipPathElement::ChildrenChanged(const ChildrenChange& change) {
if (change.by_parser)
return;
- if (LayoutObject* object = GetLayoutObject())
+ if (LayoutObject* object = GetLayoutObject()) {
object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kChildChanged);
+ layout_invalidation_reason::kChildChanged);
+ }
}
LayoutObject* SVGClipPathElement::CreateLayoutObject(const ComputedStyle&) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.cc
index 2781cab9a1c..b9a59d421a2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.cc
@@ -20,7 +20,7 @@
#include "third_party/blink/renderer/core/svg/svg_component_transfer_function_element.h"
-#include "third_party/blink/renderer/core/dom/attribute.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg/svg_fe_component_transfer_element.h"
#include "third_party/blink/renderer/core/svg/svg_number_list.h"
#include "third_party/blink/renderer/core/svg_names.h"
@@ -28,19 +28,15 @@
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<ComponentTransferType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(
- std::make_pair(FECOMPONENTTRANSFER_TYPE_IDENTITY, "identity"));
- entries.push_back(std::make_pair(FECOMPONENTTRANSFER_TYPE_TABLE, "table"));
- entries.push_back(
- std::make_pair(FECOMPONENTTRANSFER_TYPE_DISCRETE, "discrete"));
- entries.push_back(
- std::make_pair(FECOMPONENTTRANSFER_TYPE_LINEAR, "linear"));
- entries.push_back(std::make_pair(FECOMPONENTTRANSFER_TYPE_GAMMA, "gamma"));
- }
+const SVGEnumerationMap& GetEnumerationMap<ComponentTransferType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {FECOMPONENTTRANSFER_TYPE_IDENTITY, "identity"},
+ {FECOMPONENTTRANSFER_TYPE_TABLE, "table"},
+ {FECOMPONENTTRANSFER_TYPE_DISCRETE, "discrete"},
+ {FECOMPONENTTRANSFER_TYPE_LINEAR, "linear"},
+ {FECOMPONENTTRANSFER_TYPE_GAMMA, "gamma"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
@@ -49,16 +45,16 @@ SVGComponentTransferFunctionElement::SVGComponentTransferFunctionElement(
Document& document)
: SVGElement(tag_name, document),
table_values_(
- SVGAnimatedNumberList::Create(this, SVGNames::tableValuesAttr)),
- slope_(SVGAnimatedNumber::Create(this, SVGNames::slopeAttr, 1)),
+ SVGAnimatedNumberList::Create(this, svg_names::kTableValuesAttr)),
+ slope_(SVGAnimatedNumber::Create(this, svg_names::kSlopeAttr, 1)),
intercept_(
- SVGAnimatedNumber::Create(this, SVGNames::interceptAttr, 0.0f)),
- amplitude_(SVGAnimatedNumber::Create(this, SVGNames::amplitudeAttr, 1)),
- exponent_(SVGAnimatedNumber::Create(this, SVGNames::exponentAttr, 1)),
- offset_(SVGAnimatedNumber::Create(this, SVGNames::offsetAttr, 0.0f)),
+ SVGAnimatedNumber::Create(this, svg_names::kInterceptAttr, 0.0f)),
+ amplitude_(SVGAnimatedNumber::Create(this, svg_names::kAmplitudeAttr, 1)),
+ exponent_(SVGAnimatedNumber::Create(this, svg_names::kExponentAttr, 1)),
+ offset_(SVGAnimatedNumber::Create(this, svg_names::kOffsetAttr, 0.0f)),
type_(SVGAnimatedEnumeration<ComponentTransferType>::Create(
this,
- SVGNames::typeAttr,
+ svg_names::kTypeAttr,
FECOMPONENTTRANSFER_TYPE_IDENTITY)) {
AddToPropertyMap(table_values_);
AddToPropertyMap(slope_);
@@ -82,13 +78,13 @@ void SVGComponentTransferFunctionElement::Trace(blink::Visitor* visitor) {
void SVGComponentTransferFunctionElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::typeAttr ||
- attr_name == SVGNames::tableValuesAttr ||
- attr_name == SVGNames::slopeAttr ||
- attr_name == SVGNames::interceptAttr ||
- attr_name == SVGNames::amplitudeAttr ||
- attr_name == SVGNames::exponentAttr ||
- attr_name == SVGNames::offsetAttr) {
+ if (attr_name == svg_names::kTypeAttr ||
+ attr_name == svg_names::kTableValuesAttr ||
+ attr_name == svg_names::kSlopeAttr ||
+ attr_name == svg_names::kInterceptAttr ||
+ attr_name == svg_names::kAmplitudeAttr ||
+ attr_name == svg_names::kExponentAttr ||
+ attr_name == svg_names::kOffsetAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
InvalidateFilterPrimitiveParent(*this);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.h b/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.h
index fdfd53e651b..1d1eeb8162e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_component_transfer_function_element.h
@@ -30,9 +30,7 @@
namespace blink {
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<ComponentTransferType>();
+DECLARE_SVG_ENUM_MAP(ComponentTransferType);
class SVGComponentTransferFunctionElement : public SVGElement {
DEFINE_WRAPPERTYPEINFO();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_defs_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_defs_element.cc
index 598a160f63f..7e8fbcf0c9b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_defs_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_defs_element.cc
@@ -26,7 +26,7 @@
namespace blink {
inline SVGDefsElement::SVGDefsElement(Document& document)
- : SVGGraphicsElement(SVGNames::defsTag, document) {}
+ : SVGGraphicsElement(svg_names::kDefsTag, document) {}
DEFINE_NODE_FACTORY(SVGDefsElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_desc_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_desc_element.cc
index fbab758166f..64364cd5506 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_desc_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_desc_element.cc
@@ -25,7 +25,7 @@
namespace blink {
inline SVGDescElement::SVGDescElement(Document& document)
- : SVGElement(SVGNames::descTag, document) {}
+ : SVGElement(svg_names::kDescTag, document) {}
DEFINE_NODE_FACTORY(SVGDescElement)
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_discard_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_discard_element.cc
index 3604e8db060..25456931c44 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_discard_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_discard_element.cc
@@ -35,8 +35,7 @@
namespace blink {
inline SVGDiscardElement::SVGDiscardElement(Document& document)
- : SVGSMILElement(SVGNames::discardTag, document) {
- DCHECK(RuntimeEnabledFeatures::SMILEnabled());
+ : SVGSMILElement(svg_names::kDiscardTag, document) {
}
DEFINE_NODE_FACTORY(SVGDiscardElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_discard_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_discard_element.idl
index a6db8fac1e3..be85d164920 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_discard_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_discard_element.idl
@@ -30,6 +30,5 @@
// https://svgwg.org/specs/animations/#InterfaceSVGDiscardElement
-[RuntimeEnabled=SMIL]
interface SVGDiscardElement : SVGElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_document_extensions.cc b/chromium/third_party/blink/renderer/core/svg/svg_document_extensions.cc
index 32838316fa3..4d1b965d5da 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_document_extensions.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_document_extensions.cc
@@ -43,7 +43,6 @@ void SVGDocumentExtensions::RemoveTimeContainer(SVGSVGElement* element) {
void SVGDocumentExtensions::AddWebAnimationsPendingSVGElement(
SVGElement& element) {
- DCHECK(RuntimeEnabledFeatures::WebAnimationsSVGEnabled());
web_animations_pending_svg_elements_.insert(&element);
}
@@ -54,12 +53,10 @@ void SVGDocumentExtensions::ServiceOnAnimationFrame(Document& document) {
}
void SVGDocumentExtensions::ServiceAnimations() {
- if (RuntimeEnabledFeatures::SMILEnabled()) {
- HeapVector<Member<SVGSVGElement>> time_containers;
- CopyToVector(time_containers_, time_containers);
- for (const auto& container : time_containers)
- container->TimeContainer()->ServiceAnimations();
- }
+ HeapVector<Member<SVGSVGElement>> time_containers;
+ CopyToVector(time_containers_, time_containers);
+ for (const auto& container : time_containers)
+ container->TimeContainer()->ServiceAnimations();
SVGElementSet web_animations_pending_svg_elements;
web_animations_pending_svg_elements.swap(
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_element.cc
index aab9d982f41..c4df89477b8 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_element.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -61,15 +62,15 @@
namespace blink {
-using namespace HTMLNames;
-using namespace SVGNames;
+using namespace html_names;
+using namespace svg_names;
SVGElement::SVGElement(const QualifiedName& tag_name,
Document& document,
ConstructionType construction_type)
: Element(tag_name, &document, construction_type),
svg_rare_data_(nullptr),
- class_name_(SVGAnimatedString::Create(this, HTMLNames::classAttr)) {
+ class_name_(SVGAnimatedString::Create(this, html_names::kClassAttr)) {
AddToPropertyMap(class_name_);
SetHasCustomStyleCallbacks();
}
@@ -119,7 +120,7 @@ void SVGElement::WillRecalcStyle(StyleRecalcChange change) {
SVGElementRareData* SVGElement::EnsureSVGRareData() {
if (!svg_rare_data_)
- svg_rare_data_ = new SVGElementRareData();
+ svg_rare_data_ = MakeGarbageCollected<SVGElementRareData>();
return svg_rare_data_.Get();
}
@@ -376,12 +377,12 @@ Node::InsertionNotificationRequest SVGElement::InsertedInto(
Element::InsertedInto(root_parent);
UpdateRelativeLengthsInformation();
- const AtomicString& nonce_value = FastGetAttribute(nonceAttr);
+ const AtomicString& nonce_value = FastGetAttribute(kNonceAttr);
if (!nonce_value.IsEmpty()) {
setNonce(nonce_value);
if (InActiveDocument() &&
GetDocument().GetContentSecurityPolicy()->HasHeaderDeliveredPolicy()) {
- setAttribute(nonceAttr, g_empty_atom);
+ setAttribute(kNonceAttr, g_empty_atom);
}
}
return kInsertionDone;
@@ -436,64 +437,64 @@ CSSPropertyID SVGElement::CssPropertyIdForSVGAttributeName(
// This is a list of all base CSS and SVG CSS properties which are exposed
// as SVG XML attributes
const QualifiedName* const attr_names[] = {
- &alignment_baselineAttr,
- &baseline_shiftAttr,
- &buffered_renderingAttr,
- &clipAttr,
- &clip_pathAttr,
- &clip_ruleAttr,
- &SVGNames::colorAttr,
- &color_interpolationAttr,
- &color_interpolation_filtersAttr,
- &color_renderingAttr,
- &cursorAttr,
- &SVGNames::directionAttr,
- &displayAttr,
- &dominant_baselineAttr,
- &fillAttr,
- &fill_opacityAttr,
- &fill_ruleAttr,
- &filterAttr,
- &flood_colorAttr,
- &flood_opacityAttr,
- &font_familyAttr,
- &font_sizeAttr,
- &font_stretchAttr,
- &font_styleAttr,
- &font_variantAttr,
- &font_weightAttr,
- &image_renderingAttr,
- &letter_spacingAttr,
- &lighting_colorAttr,
- &marker_endAttr,
- &marker_midAttr,
- &marker_startAttr,
- &maskAttr,
- &mask_typeAttr,
- &opacityAttr,
- &overflowAttr,
- &paint_orderAttr,
- &pointer_eventsAttr,
- &shape_renderingAttr,
- &stop_colorAttr,
- &stop_opacityAttr,
- &strokeAttr,
- &stroke_dasharrayAttr,
- &stroke_dashoffsetAttr,
- &stroke_linecapAttr,
- &stroke_linejoinAttr,
- &stroke_miterlimitAttr,
- &stroke_opacityAttr,
- &stroke_widthAttr,
- &text_anchorAttr,
- &text_decorationAttr,
- &text_renderingAttr,
- &transform_originAttr,
- &unicode_bidiAttr,
- &vector_effectAttr,
- &visibilityAttr,
- &word_spacingAttr,
- &writing_modeAttr,
+ &kAlignmentBaselineAttr,
+ &kBaselineShiftAttr,
+ &kBufferedRenderingAttr,
+ &kClipAttr,
+ &kClipPathAttr,
+ &kClipRuleAttr,
+ &svg_names::kColorAttr,
+ &kColorInterpolationAttr,
+ &kColorInterpolationFiltersAttr,
+ &kColorRenderingAttr,
+ &kCursorAttr,
+ &svg_names::kDirectionAttr,
+ &kDisplayAttr,
+ &kDominantBaselineAttr,
+ &kFillAttr,
+ &kFillOpacityAttr,
+ &kFillRuleAttr,
+ &kFilterAttr,
+ &kFloodColorAttr,
+ &kFloodOpacityAttr,
+ &kFontFamilyAttr,
+ &kFontSizeAttr,
+ &kFontStretchAttr,
+ &kFontStyleAttr,
+ &kFontVariantAttr,
+ &kFontWeightAttr,
+ &kImageRenderingAttr,
+ &kLetterSpacingAttr,
+ &kLightingColorAttr,
+ &kMarkerEndAttr,
+ &kMarkerMidAttr,
+ &kMarkerStartAttr,
+ &kMaskAttr,
+ &kMaskTypeAttr,
+ &kOpacityAttr,
+ &kOverflowAttr,
+ &kPaintOrderAttr,
+ &kPointerEventsAttr,
+ &kShapeRenderingAttr,
+ &kStopColorAttr,
+ &kStopOpacityAttr,
+ &kStrokeAttr,
+ &kStrokeDasharrayAttr,
+ &kStrokeDashoffsetAttr,
+ &kStrokeLinecapAttr,
+ &kStrokeLinejoinAttr,
+ &kStrokeMiterlimitAttr,
+ &kStrokeOpacityAttr,
+ &kStrokeWidthAttr,
+ &kTextAnchorAttr,
+ &kTextDecorationAttr,
+ &kTextRenderingAttr,
+ &kTransformOriginAttr,
+ &kUnicodeBidiAttr,
+ &kVectorEffectAttr,
+ &kVisibilityAttr,
+ &kWordSpacingAttr,
+ &kWritingModeAttr,
};
for (size_t i = 0; i < arraysize(attr_names); i++) {
CSSPropertyID property_id = cssPropertyID(attr_names[i]->LocalName());
@@ -575,10 +576,10 @@ void SVGElement::InvalidateRelativeLengthClients(
if (HasRelativeLengths() && layout_object->IsSVGResourceContainer()) {
ToLayoutSVGResourceContainer(layout_object)
->InvalidateCacheAndMarkForLayout(
- LayoutInvalidationReason::kSizeChanged, layout_scope);
+ layout_invalidation_reason::kSizeChanged, layout_scope);
} else if (SelfHasRelativeLengths()) {
layout_object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kUnknown, kMarkContainerChain,
+ layout_invalidation_reason::kUnknown, kMarkContainerChain,
layout_scope);
}
}
@@ -641,9 +642,9 @@ void SVGElement::RemoveInstanceMapping(SVGElement* instance) {
}
static HeapHashSet<WeakMember<SVGElement>>& EmptyInstances() {
- DEFINE_STATIC_LOCAL(Persistent<HeapHashSet<WeakMember<SVGElement>>>,
- empty_instances,
- (new HeapHashSet<WeakMember<SVGElement>>));
+ DEFINE_STATIC_LOCAL(
+ Persistent<HeapHashSet<WeakMember<SVGElement>>>, empty_instances,
+ (MakeGarbageCollected<HeapHashSet<WeakMember<SVGElement>>>()));
return *empty_instances;
}
@@ -725,59 +726,59 @@ AnimatedPropertyType SVGElement::AnimatedPropertyTypeForCSSAttribute(
const AnimatedPropertyType prop_type;
};
const AttrToTypeEntry attr_to_types[] = {
- {alignment_baselineAttr, kAnimatedString},
- {baseline_shiftAttr, kAnimatedString},
- {buffered_renderingAttr, kAnimatedString},
- {clip_pathAttr, kAnimatedString},
- {clip_ruleAttr, kAnimatedString},
- {SVGNames::colorAttr, kAnimatedColor},
- {color_interpolationAttr, kAnimatedString},
- {color_interpolation_filtersAttr, kAnimatedString},
- {color_renderingAttr, kAnimatedString},
- {cursorAttr, kAnimatedString},
- {displayAttr, kAnimatedString},
- {dominant_baselineAttr, kAnimatedString},
- {fillAttr, kAnimatedColor},
- {fill_opacityAttr, kAnimatedNumber},
- {fill_ruleAttr, kAnimatedString},
- {filterAttr, kAnimatedString},
- {flood_colorAttr, kAnimatedColor},
- {flood_opacityAttr, kAnimatedNumber},
- {font_familyAttr, kAnimatedString},
- {font_sizeAttr, kAnimatedLength},
- {font_stretchAttr, kAnimatedString},
- {font_styleAttr, kAnimatedString},
- {font_variantAttr, kAnimatedString},
- {font_weightAttr, kAnimatedString},
- {image_renderingAttr, kAnimatedString},
- {letter_spacingAttr, kAnimatedLength},
- {lighting_colorAttr, kAnimatedColor},
- {marker_endAttr, kAnimatedString},
- {marker_midAttr, kAnimatedString},
- {marker_startAttr, kAnimatedString},
- {maskAttr, kAnimatedString},
- {mask_typeAttr, kAnimatedString},
- {opacityAttr, kAnimatedNumber},
- {overflowAttr, kAnimatedString},
- {paint_orderAttr, kAnimatedString},
- {pointer_eventsAttr, kAnimatedString},
- {shape_renderingAttr, kAnimatedString},
- {stop_colorAttr, kAnimatedColor},
- {stop_opacityAttr, kAnimatedNumber},
- {strokeAttr, kAnimatedColor},
- {stroke_dasharrayAttr, kAnimatedLengthList},
- {stroke_dashoffsetAttr, kAnimatedLength},
- {stroke_linecapAttr, kAnimatedString},
- {stroke_linejoinAttr, kAnimatedString},
- {stroke_miterlimitAttr, kAnimatedNumber},
- {stroke_opacityAttr, kAnimatedNumber},
- {stroke_widthAttr, kAnimatedLength},
- {text_anchorAttr, kAnimatedString},
- {text_decorationAttr, kAnimatedString},
- {text_renderingAttr, kAnimatedString},
- {vector_effectAttr, kAnimatedString},
- {visibilityAttr, kAnimatedString},
- {word_spacingAttr, kAnimatedLength},
+ {kAlignmentBaselineAttr, kAnimatedString},
+ {kBaselineShiftAttr, kAnimatedString},
+ {kBufferedRenderingAttr, kAnimatedString},
+ {kClipPathAttr, kAnimatedString},
+ {kClipRuleAttr, kAnimatedString},
+ {svg_names::kColorAttr, kAnimatedColor},
+ {kColorInterpolationAttr, kAnimatedString},
+ {kColorInterpolationFiltersAttr, kAnimatedString},
+ {kColorRenderingAttr, kAnimatedString},
+ {kCursorAttr, kAnimatedString},
+ {kDisplayAttr, kAnimatedString},
+ {kDominantBaselineAttr, kAnimatedString},
+ {kFillAttr, kAnimatedColor},
+ {kFillOpacityAttr, kAnimatedNumber},
+ {kFillRuleAttr, kAnimatedString},
+ {kFilterAttr, kAnimatedString},
+ {kFloodColorAttr, kAnimatedColor},
+ {kFloodOpacityAttr, kAnimatedNumber},
+ {kFontFamilyAttr, kAnimatedString},
+ {kFontSizeAttr, kAnimatedLength},
+ {kFontStretchAttr, kAnimatedString},
+ {kFontStyleAttr, kAnimatedString},
+ {kFontVariantAttr, kAnimatedString},
+ {kFontWeightAttr, kAnimatedString},
+ {kImageRenderingAttr, kAnimatedString},
+ {kLetterSpacingAttr, kAnimatedLength},
+ {kLightingColorAttr, kAnimatedColor},
+ {kMarkerEndAttr, kAnimatedString},
+ {kMarkerMidAttr, kAnimatedString},
+ {kMarkerStartAttr, kAnimatedString},
+ {kMaskAttr, kAnimatedString},
+ {kMaskTypeAttr, kAnimatedString},
+ {kOpacityAttr, kAnimatedNumber},
+ {kOverflowAttr, kAnimatedString},
+ {kPaintOrderAttr, kAnimatedString},
+ {kPointerEventsAttr, kAnimatedString},
+ {kShapeRenderingAttr, kAnimatedString},
+ {kStopColorAttr, kAnimatedColor},
+ {kStopOpacityAttr, kAnimatedNumber},
+ {kStrokeAttr, kAnimatedColor},
+ {kStrokeDasharrayAttr, kAnimatedLengthList},
+ {kStrokeDashoffsetAttr, kAnimatedLength},
+ {kStrokeLinecapAttr, kAnimatedString},
+ {kStrokeLinejoinAttr, kAnimatedString},
+ {kStrokeMiterlimitAttr, kAnimatedNumber},
+ {kStrokeOpacityAttr, kAnimatedNumber},
+ {kStrokeWidthAttr, kAnimatedLength},
+ {kTextAnchorAttr, kAnimatedString},
+ {kTextDecorationAttr, kAnimatedString},
+ {kTextRenderingAttr, kAnimatedString},
+ {kVectorEffectAttr, kAnimatedString},
+ {kVisibilityAttr, kAnimatedString},
+ {kWordSpacingAttr, kAnimatedLength},
};
for (size_t i = 0; i < arraysize(attr_to_types); i++)
css_property_map.Set(attr_to_types[i].attr, attr_to_types[i].prop_type);
@@ -855,7 +856,7 @@ void SVGElement::AddedEventListener(
// Add event listener to all shadow tree DOM element instances
HeapHashSet<WeakMember<SVGElement>> instances;
CollectInstancesForSVGElement(this, instances);
- AddEventListenerOptionsResolved options = registered_listener.Options();
+ AddEventListenerOptionsResolved* options = registered_listener.Options();
EventListener* listener = registered_listener.Callback();
for (SVGElement* element : instances) {
bool result =
@@ -872,7 +873,7 @@ void SVGElement::RemovedEventListener(
// Remove event listener from all shadow tree DOM element instances
HeapHashSet<WeakMember<SVGElement>> instances;
CollectInstancesForSVGElement(this, instances);
- EventListenerOptions options = registered_listener.Options();
+ EventListenerOptions* options = registered_listener.Options();
const EventListener* listener = registered_listener.Callback();
for (SVGElement* shadow_tree_element : instances) {
DCHECK(shadow_tree_element);
@@ -883,13 +884,13 @@ void SVGElement::RemovedEventListener(
}
static bool HasLoadListener(Element* element) {
- if (element->HasEventListeners(EventTypeNames::load))
+ if (element->HasEventListeners(event_type_names::kLoad))
return true;
for (element = element->ParentOrShadowHostElement(); element;
element = element->ParentOrShadowHostElement()) {
EventListenerVector* entry =
- element->GetEventListeners(EventTypeNames::load);
+ element->GetEventListeners(event_type_names::kLoad);
if (!entry)
continue;
for (wtf_size_t i = 0; i < entry->size(); ++i) {
@@ -906,7 +907,7 @@ bool SVGElement::SendSVGLoadEventIfPossible() {
return false;
if ((IsStructurallyExternal() || IsSVGSVGElement(*this)) &&
HasLoadListener(this))
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
return true;
}
@@ -936,7 +937,7 @@ void SVGElement::SendSVGLoadEventToSelfAndAncestorChainIfPossible() {
void SVGElement::AttributeChanged(const AttributeModificationParams& params) {
Element::AttributeChanged(params);
- if (params.name == HTMLNames::idAttr) {
+ if (params.name == html_names::kIdAttr) {
RebuildAllIncomingReferences();
InvalidateInstances();
return;
@@ -945,7 +946,7 @@ void SVGElement::AttributeChanged(const AttributeModificationParams& params) {
// Changes to the style attribute are processed lazily (see
// Element::getAttribute() and related methods), so we don't want changes to
// the style attribute to result in extra work here.
- if (params.name == HTMLNames::styleAttr)
+ if (params.name == html_names::kStyleAttr)
return;
SvgAttributeBaseValChanged(params.name);
@@ -959,7 +960,7 @@ void SVGElement::SvgAttributeChanged(const QualifiedName& attr_name) {
return;
}
- if (attr_name == HTMLNames::classAttr) {
+ if (attr_name == html_names::kClassAttr) {
ClassAttributeChanged(AtomicString(class_name_->CurrentValue()->Value()));
InvalidateInstances();
return;
@@ -1035,10 +1036,8 @@ bool SVGElement::LayoutObjectIsNeeded(const ComputedStyle& style) const {
}
bool SVGElement::HasSVGParent() const {
- // Should we use the flat tree parent instead? If so, we should probably fix a
- // few other checks.
- return ParentOrShadowHostElement() &&
- ParentOrShadowHostElement()->IsSVGElement();
+ Element* parent = FlatTreeTraversal::ParentElement(*this);
+ return parent && parent->IsSVGElement();
}
MutableCSSPropertyValueSet* SVGElement::AnimatedSMILStyleProperties() const {
@@ -1071,10 +1070,10 @@ const ComputedStyle* SVGElement::EnsureComputedStyle(
}
bool SVGElement::HasFocusEventListeners() const {
- return HasEventListeners(EventTypeNames::focusin) ||
- HasEventListeners(EventTypeNames::focusout) ||
- HasEventListeners(EventTypeNames::focus) ||
- HasEventListeners(EventTypeNames::blur);
+ return HasEventListeners(event_type_names::kFocusin) ||
+ HasEventListeners(event_type_names::kFocusout) ||
+ HasEventListeners(event_type_names::kFocus) ||
+ HasEventListeners(event_type_names::kBlur);
}
void SVGElement::MarkForLayoutAndParentResourceInvalidation(
@@ -1133,100 +1132,100 @@ bool SVGElement::IsAnimatableAttribute(const QualifiedName& name) const {
// a race when dumping debug data for a layer.
DEFINE_THREAD_SAFE_STATIC_LOCAL(HashSet<QualifiedName>, animatable_attributes,
({
- SVGNames::amplitudeAttr,
- SVGNames::azimuthAttr,
- SVGNames::baseFrequencyAttr,
- SVGNames::biasAttr,
- SVGNames::clipPathUnitsAttr,
- SVGNames::cxAttr,
- SVGNames::cyAttr,
- SVGNames::diffuseConstantAttr,
- SVGNames::divisorAttr,
- SVGNames::dxAttr,
- SVGNames::dyAttr,
- SVGNames::edgeModeAttr,
- SVGNames::elevationAttr,
- SVGNames::exponentAttr,
- SVGNames::filterUnitsAttr,
- SVGNames::fxAttr,
- SVGNames::fyAttr,
- SVGNames::gradientTransformAttr,
- SVGNames::gradientUnitsAttr,
- SVGNames::heightAttr,
- SVGNames::hrefAttr,
- SVGNames::in2Attr,
- SVGNames::inAttr,
- SVGNames::interceptAttr,
- SVGNames::k1Attr,
- SVGNames::k2Attr,
- SVGNames::k3Attr,
- SVGNames::k4Attr,
- SVGNames::kernelMatrixAttr,
- SVGNames::kernelUnitLengthAttr,
- SVGNames::lengthAdjustAttr,
- SVGNames::limitingConeAngleAttr,
- SVGNames::markerHeightAttr,
- SVGNames::markerUnitsAttr,
- SVGNames::markerWidthAttr,
- SVGNames::maskContentUnitsAttr,
- SVGNames::maskUnitsAttr,
- SVGNames::methodAttr,
- SVGNames::modeAttr,
- SVGNames::numOctavesAttr,
- SVGNames::offsetAttr,
- SVGNames::operatorAttr,
- SVGNames::orderAttr,
- SVGNames::orientAttr,
- SVGNames::pathLengthAttr,
- SVGNames::patternContentUnitsAttr,
- SVGNames::patternTransformAttr,
- SVGNames::patternUnitsAttr,
- SVGNames::pointsAtXAttr,
- SVGNames::pointsAtYAttr,
- SVGNames::pointsAtZAttr,
- SVGNames::preserveAlphaAttr,
- SVGNames::preserveAspectRatioAttr,
- SVGNames::primitiveUnitsAttr,
- SVGNames::radiusAttr,
- SVGNames::rAttr,
- SVGNames::refXAttr,
- SVGNames::refYAttr,
- SVGNames::resultAttr,
- SVGNames::rotateAttr,
- SVGNames::rxAttr,
- SVGNames::ryAttr,
- SVGNames::scaleAttr,
- SVGNames::seedAttr,
- SVGNames::slopeAttr,
- SVGNames::spacingAttr,
- SVGNames::specularConstantAttr,
- SVGNames::specularExponentAttr,
- SVGNames::spreadMethodAttr,
- SVGNames::startOffsetAttr,
- SVGNames::stdDeviationAttr,
- SVGNames::stitchTilesAttr,
- SVGNames::surfaceScaleAttr,
- SVGNames::tableValuesAttr,
- SVGNames::targetAttr,
- SVGNames::targetXAttr,
- SVGNames::targetYAttr,
- SVGNames::transformAttr,
- SVGNames::typeAttr,
- SVGNames::valuesAttr,
- SVGNames::viewBoxAttr,
- SVGNames::widthAttr,
- SVGNames::x1Attr,
- SVGNames::x2Attr,
- SVGNames::xAttr,
- SVGNames::xChannelSelectorAttr,
- SVGNames::y1Attr,
- SVGNames::y2Attr,
- SVGNames::yAttr,
- SVGNames::yChannelSelectorAttr,
- SVGNames::zAttr,
+ svg_names::kAmplitudeAttr,
+ svg_names::kAzimuthAttr,
+ svg_names::kBaseFrequencyAttr,
+ svg_names::kBiasAttr,
+ svg_names::kClipPathUnitsAttr,
+ svg_names::kCxAttr,
+ svg_names::kCyAttr,
+ svg_names::kDiffuseConstantAttr,
+ svg_names::kDivisorAttr,
+ svg_names::kDxAttr,
+ svg_names::kDyAttr,
+ svg_names::kEdgeModeAttr,
+ svg_names::kElevationAttr,
+ svg_names::kExponentAttr,
+ svg_names::kFilterUnitsAttr,
+ svg_names::kFxAttr,
+ svg_names::kFyAttr,
+ svg_names::kGradientTransformAttr,
+ svg_names::kGradientUnitsAttr,
+ svg_names::kHeightAttr,
+ svg_names::kHrefAttr,
+ svg_names::kIn2Attr,
+ svg_names::kInAttr,
+ svg_names::kInterceptAttr,
+ svg_names::kK1Attr,
+ svg_names::kK2Attr,
+ svg_names::kK3Attr,
+ svg_names::kK4Attr,
+ svg_names::kKernelMatrixAttr,
+ svg_names::kKernelUnitLengthAttr,
+ svg_names::kLengthAdjustAttr,
+ svg_names::kLimitingConeAngleAttr,
+ svg_names::kMarkerHeightAttr,
+ svg_names::kMarkerUnitsAttr,
+ svg_names::kMarkerWidthAttr,
+ svg_names::kMaskContentUnitsAttr,
+ svg_names::kMaskUnitsAttr,
+ svg_names::kMethodAttr,
+ svg_names::kModeAttr,
+ svg_names::kNumOctavesAttr,
+ svg_names::kOffsetAttr,
+ svg_names::kOperatorAttr,
+ svg_names::kOrderAttr,
+ svg_names::kOrientAttr,
+ svg_names::kPathLengthAttr,
+ svg_names::kPatternContentUnitsAttr,
+ svg_names::kPatternTransformAttr,
+ svg_names::kPatternUnitsAttr,
+ svg_names::kPointsAtXAttr,
+ svg_names::kPointsAtYAttr,
+ svg_names::kPointsAtZAttr,
+ svg_names::kPreserveAlphaAttr,
+ svg_names::kPreserveAspectRatioAttr,
+ svg_names::kPrimitiveUnitsAttr,
+ svg_names::kRadiusAttr,
+ svg_names::kRAttr,
+ svg_names::kRefXAttr,
+ svg_names::kRefYAttr,
+ svg_names::kResultAttr,
+ svg_names::kRotateAttr,
+ svg_names::kRxAttr,
+ svg_names::kRyAttr,
+ svg_names::kScaleAttr,
+ svg_names::kSeedAttr,
+ svg_names::kSlopeAttr,
+ svg_names::kSpacingAttr,
+ svg_names::kSpecularConstantAttr,
+ svg_names::kSpecularExponentAttr,
+ svg_names::kSpreadMethodAttr,
+ svg_names::kStartOffsetAttr,
+ svg_names::kStdDeviationAttr,
+ svg_names::kStitchTilesAttr,
+ svg_names::kSurfaceScaleAttr,
+ svg_names::kTableValuesAttr,
+ svg_names::kTargetAttr,
+ svg_names::kTargetXAttr,
+ svg_names::kTargetYAttr,
+ svg_names::kTransformAttr,
+ svg_names::kTypeAttr,
+ svg_names::kValuesAttr,
+ svg_names::kViewBoxAttr,
+ svg_names::kWidthAttr,
+ svg_names::kX1Attr,
+ svg_names::kX2Attr,
+ svg_names::kXAttr,
+ svg_names::kXChannelSelectorAttr,
+ svg_names::kY1Attr,
+ svg_names::kY2Attr,
+ svg_names::kYAttr,
+ svg_names::kYChannelSelectorAttr,
+ svg_names::kZAttr,
}));
- if (name == classAttr)
+ if (name == kClassAttr)
return true;
return animatable_attributes.Contains(name);
@@ -1250,7 +1249,7 @@ SVGElementSet& SVGElement::GetDependencyTraversalVisitedSet() {
// This strong reference is safe, as it is guaranteed that this set will be
// emptied at the end of recursion in NotifyIncomingReferences.
DEFINE_STATIC_LOCAL(Persistent<SVGElementSet>, invalidating_dependencies,
- (new SVGElementSet));
+ (MakeGarbageCollected<SVGElementSet>()));
return *invalidating_dependencies;
}
@@ -1270,7 +1269,7 @@ void SVGElement::RebuildAllIncomingReferences() {
// Before rebuilding |sourceElement| ensure it was not removed from under
// us.
if (incoming_references.Contains(source_element))
- source_element->SvgAttributeChanged(SVGNames::hrefAttr);
+ source_element->SvgAttributeChanged(svg_names::kHrefAttr);
}
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_element_rare_data.cc b/chromium/third_party/blink/renderer/core/svg/svg_element_rare_data.cc
index c8e0334db2a..6f51b651723 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_element_rare_data.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_element_rare_data.cc
@@ -45,7 +45,7 @@ void SVGElementRareData::ClearOverriddenComputedStyle() {
SVGResourceClient& SVGElementRareData::EnsureSVGResourceClient(
SVGElement* element) {
if (!resource_client_)
- resource_client_ = new SVGElementResourceClient(element);
+ resource_client_ = MakeGarbageCollected<SVGElementResourceClient>(element);
return *resource_client_;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.cc
index a20bdbccaed..8815419a5f3 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.cc
@@ -26,24 +26,24 @@
namespace blink {
inline SVGEllipseElement::SVGEllipseElement(Document& document)
- : SVGGeometryElement(SVGNames::ellipseTag, document),
+ : SVGGeometryElement(svg_names::kEllipseTag, document),
cx_(SVGAnimatedLength::Create(this,
- SVGNames::cxAttr,
+ svg_names::kCxAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyCx)),
cy_(SVGAnimatedLength::Create(this,
- SVGNames::cyAttr,
+ svg_names::kCyAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyCy)),
rx_(SVGAnimatedLength::Create(this,
- SVGNames::rxAttr,
+ svg_names::kRxAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyRx)),
ry_(SVGAnimatedLength::Create(this,
- SVGNames::ryAttr,
+ svg_names::kRyAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyRy)) {
@@ -111,8 +111,8 @@ void SVGEllipseElement::CollectStyleForPresentationAttribute(
}
void SVGEllipseElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::cxAttr || attr_name == SVGNames::cyAttr ||
- attr_name == SVGNames::rxAttr || attr_name == SVGNames::ryAttr) {
+ if (attr_name == svg_names::kCxAttr || attr_name == svg_names::kCyAttr ||
+ attr_name == svg_names::kRxAttr || attr_name == svg_names::kRyAttr) {
UpdateRelativeLengthsInformation();
GeometryPresentationAttributeChanged(attr_name);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_enumeration.cc b/chromium/third_party/blink/renderer/core/svg/svg_enumeration.cc
index fc9d5518bf6..64e58a8dbc5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_enumeration.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_enumeration.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/svg/svg_enumeration.h"
#include "third_party/blink/renderer/core/svg/svg_animation_element.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
namespace blink {
@@ -46,10 +47,8 @@ SVGPropertyBase* SVGEnumerationBase::CloneForAnimation(
}
String SVGEnumerationBase::ValueAsString() const {
- for (const auto& entry : entries_) {
- if (value_ == entry.first)
- return entry.second;
- }
+ if (const char* enum_name = map_.NameFromValue(value_))
+ return String(enum_name);
DCHECK_LT(value_, MaxInternalEnumValue());
return g_empty_string;
@@ -61,17 +60,12 @@ void SVGEnumerationBase::SetValue(unsigned short value) {
}
SVGParsingError SVGEnumerationBase::SetValueAsString(const String& string) {
- for (const auto& entry : entries_) {
- if (string == entry.second) {
- // 0 corresponds to _UNKNOWN enumeration values, and should not be
- // settable.
- DCHECK(entry.first);
- value_ = entry.first;
- NotifyChange();
- return SVGParseStatus::kNoError;
- }
+ unsigned short value = map_.ValueFromName(string);
+ if (value) {
+ value_ = value;
+ NotifyChange();
+ return SVGParseStatus::kNoError;
}
-
NotifyChange();
return SVGParseStatus::kExpectedEnumeration;
}
@@ -104,4 +98,12 @@ float SVGEnumerationBase::CalculateDistance(SVGPropertyBase*, SVGElement*) {
return -1;
}
+unsigned short SVGEnumerationBase::MaxExposedEnumValue() const {
+ return map_.MaxExposedValue();
+}
+
+unsigned short SVGEnumerationBase::MaxInternalEnumValue() const {
+ return map_.ValueOfLast();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_enumeration.h b/chromium/third_party/blink/renderer/core/svg/svg_enumeration.h
index 4b4a0749312..9e70421b56e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_enumeration.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_enumeration.h
@@ -36,11 +36,10 @@
namespace blink {
+class SVGEnumerationMap;
+
class SVGEnumerationBase : public SVGPropertyBase {
public:
- typedef std::pair<unsigned short, String> StringEntry;
- typedef Vector<StringEntry> StringEntries;
-
// SVGEnumeration does not have a tear-off type.
typedef void TearOffType;
typedef unsigned short PrimitiveType;
@@ -72,13 +71,9 @@ class SVGEnumerationBase : public SVGPropertyBase {
static AnimatedPropertyType ClassType() { return kAnimatedEnumeration; }
AnimatedPropertyType GetType() const override { return ClassType(); }
- static unsigned short ValueOfLastEnum(const StringEntries& entries) {
- return entries.back().first;
- }
-
// This is the maximum value that is exposed as an IDL constant on the
// relevant interface.
- unsigned short MaxExposedEnumValue() const { return max_exposed_; }
+ unsigned short MaxExposedEnumValue() const;
void SetInitial(unsigned value) {
SetValue(static_cast<unsigned short>(value));
@@ -86,32 +81,26 @@ class SVGEnumerationBase : public SVGPropertyBase {
static constexpr int kInitialValueBits = 3;
protected:
- SVGEnumerationBase(unsigned short value,
- const StringEntries& entries,
- unsigned short max_exposed)
- : value_(value), max_exposed_(max_exposed), entries_(entries) {}
+ SVGEnumerationBase(unsigned short value, const SVGEnumerationMap& map)
+ : value_(value), map_(map) {}
// This is the maximum value of all the internal enumeration values.
- // This assumes that |m_entries| are sorted.
- unsigned short MaxInternalEnumValue() const {
- return ValueOfLastEnum(entries_);
- }
+ // This assumes that the map is sorted on the enumeration value.
+ unsigned short MaxInternalEnumValue() const;
// Used by SVGMarkerOrientEnumeration.
virtual void NotifyChange() {}
unsigned short value_;
- const unsigned short max_exposed_;
- const StringEntries& entries_;
+ const SVGEnumerationMap& map_;
};
-typedef SVGEnumerationBase::StringEntries SVGEnumerationStringEntries;
template <typename Enum>
-const SVGEnumerationStringEntries& GetStaticStringEntries();
-template <typename Enum>
-unsigned short GetMaxExposedEnumValue() {
- return SVGEnumerationBase::ValueOfLastEnum(GetStaticStringEntries<Enum>());
-}
+const SVGEnumerationMap& GetEnumerationMap();
+
+#define DECLARE_SVG_ENUM_MAP(cpp_enum_type) \
+ template <> \
+ const SVGEnumerationMap& GetEnumerationMap<cpp_enum_type>()
template <typename Enum>
class SVGEnumeration : public SVGEnumerationBase {
@@ -136,9 +125,7 @@ class SVGEnumeration : public SVGEnumerationBase {
protected:
explicit SVGEnumeration(Enum new_value)
- : SVGEnumerationBase(new_value,
- GetStaticStringEntries<Enum>(),
- GetMaxExposedEnumValue<Enum>()) {}
+ : SVGEnumerationBase(new_value, GetEnumerationMap<Enum>()) {}
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.cc b/chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.cc
new file mode 100644
index 00000000000..446efe950ad
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.cc
@@ -0,0 +1,19 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
+
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+unsigned short SVGEnumerationMap::ValueFromName(const String& name) const {
+ for (const Entry& entry : *this) {
+ if (name == entry.name)
+ return entry.value;
+ }
+ return 0;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.h b/chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.h
new file mode 100644
index 00000000000..6cecee9db33
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/svg/svg_enumeration_map.h
@@ -0,0 +1,63 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ENUMERATION_MAP_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ENUMERATION_MAP_H_
+
+#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/forward.h"
+
+namespace blink {
+
+// Helper class for SVG enumerations. Maps between name (string) and value.
+//
+// It is assumed that enumeration values are contiguous, non-zero and
+// starting at 1.
+//
+// For enumerations that have had new values added since SVG 1.1, the
+// |max_exposed_value| should be set to the last old value. From this also
+// follow that the new values should sort last - after the |max_exposed_value|.
+// (This is currently always the case in the spec too.)
+class SVGEnumerationMap {
+ public:
+ struct Entry {
+ const unsigned short value;
+ const char* const name;
+ };
+
+ template <unsigned entries_length>
+ constexpr SVGEnumerationMap(const Entry (&entries)[entries_length])
+ : SVGEnumerationMap(entries, entries[entries_length - 1].value) {}
+ template <unsigned entries_length>
+ constexpr SVGEnumerationMap(const Entry (&entries)[entries_length],
+ unsigned short max_exposed_value)
+ : entries_(entries),
+ num_entries_(entries_length),
+ max_exposed_value_(max_exposed_value) {}
+
+ const char* NameFromValue(unsigned short value) const {
+ DCHECK(value); // We should never store 0 (*_UNKNOWN) in the map.
+ DCHECK_LT(value - 1, num_entries_);
+ DCHECK_EQ(entries_[value - 1].value, value);
+ return entries_[value - 1].name;
+ }
+ unsigned short ValueFromName(const String&) const;
+
+ unsigned short ValueOfLast() const {
+ return entries_[num_entries_ - 1].value;
+ }
+ unsigned short MaxExposedValue() const { return max_exposed_value_; }
+
+ private:
+ const Entry* begin() const { return entries_; }
+ const Entry* end() const { return entries_ + num_entries_; }
+
+ const Entry* const entries_;
+ const unsigned short num_entries_;
+ const unsigned short max_exposed_value_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ENUMERATION_MAP_H_
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.cc
index 3f123235949..fba813e976d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.cc
@@ -21,6 +21,7 @@
#include "third_party/blink/renderer/core/svg/svg_fe_blend_element.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/graphics/filters/fe_blend.h"
@@ -56,53 +57,36 @@ static BlendMode ToBlendMode(SVGFEBlendElement::Mode mode) {
}
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGFEBlendElement::Mode>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(SVGFEBlendElement::kModeNormal, "normal"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeMultiply, "multiply"));
- entries.push_back(std::make_pair(SVGFEBlendElement::kModeScreen, "screen"));
- entries.push_back(std::make_pair(SVGFEBlendElement::kModeDarken, "darken"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeLighten, "lighten"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeOverlay, "overlay"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeColorDodge, "color-dodge"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeColorBurn, "color-burn"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeHardLight, "hard-light"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeSoftLight, "soft-light"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeDifference, "difference"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeExclusion, "exclusion"));
- entries.push_back(std::make_pair(SVGFEBlendElement::kModeHue, "hue"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeSaturation, "saturation"));
- entries.push_back(std::make_pair(SVGFEBlendElement::kModeColor, "color"));
- entries.push_back(
- std::make_pair(SVGFEBlendElement::kModeLuminosity, "luminosity"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGFEBlendElement::Mode>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {SVGFEBlendElement::kModeNormal, "normal"},
+ {SVGFEBlendElement::kModeMultiply, "multiply"},
+ {SVGFEBlendElement::kModeScreen, "screen"},
+ {SVGFEBlendElement::kModeDarken, "darken"},
+ {SVGFEBlendElement::kModeLighten, "lighten"},
+ {SVGFEBlendElement::kModeOverlay, "overlay"},
+ {SVGFEBlendElement::kModeColorDodge, "color-dodge"},
+ {SVGFEBlendElement::kModeColorBurn, "color-burn"},
+ {SVGFEBlendElement::kModeHardLight, "hard-light"},
+ {SVGFEBlendElement::kModeSoftLight, "soft-light"},
+ {SVGFEBlendElement::kModeDifference, "difference"},
+ {SVGFEBlendElement::kModeExclusion, "exclusion"},
+ {SVGFEBlendElement::kModeHue, "hue"},
+ {SVGFEBlendElement::kModeSaturation, "saturation"},
+ {SVGFEBlendElement::kModeColor, "color"},
+ {SVGFEBlendElement::kModeLuminosity, "luminosity"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
-template <>
-unsigned short GetMaxExposedEnumValue<SVGFEBlendElement::Mode>() {
- return SVGFEBlendElement::kModeLighten;
-}
-
inline SVGFEBlendElement::SVGFEBlendElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feBlendTag, document),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)),
- in2_(SVGAnimatedString::Create(this, SVGNames::in2Attr)),
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEBlendTag, document),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)),
+ in2_(SVGAnimatedString::Create(this, svg_names::kIn2Attr)),
mode_(SVGAnimatedEnumeration<Mode>::Create(
this,
- SVGNames::modeAttr,
+ svg_names::kModeAttr,
SVGFEBlendElement::kModeNormal)) {
AddToPropertyMap(in1_);
AddToPropertyMap(in2_);
@@ -122,7 +106,7 @@ bool SVGFEBlendElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FEBlend* blend = static_cast<FEBlend*>(effect);
- if (attr_name == SVGNames::modeAttr)
+ if (attr_name == svg_names::kModeAttr)
return blend->SetBlendMode(ToBlendMode(mode_->CurrentValue()->EnumValue()));
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
@@ -130,13 +114,13 @@ bool SVGFEBlendElement::SetFilterEffectAttribute(
}
void SVGFEBlendElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::modeAttr) {
+ if (attr_name == svg_names::kModeAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr || attr_name == SVGNames::in2Attr) {
+ if (attr_name == svg_names::kInAttr || attr_name == svg_names::kIn2Attr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.h
index 0ca38c0be5e..cc6cf833568 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.h
@@ -38,20 +38,17 @@ class SVGFEBlendElement final : public SVGFilterPrimitiveStandardAttributes {
kModeScreen = 3,
kModeDarken = 4,
kModeLighten = 5,
-
- // The following modes do not map to IDL constants on
- // SVGFEBlendElement.
- kModeOverlay,
- kModeColorDodge,
- kModeColorBurn,
- kModeHardLight,
- kModeSoftLight,
- kModeDifference,
- kModeExclusion,
- kModeHue,
- kModeSaturation,
- kModeColor,
- kModeLuminosity,
+ kModeOverlay = 6,
+ kModeColorDodge = 7,
+ kModeColorBurn = 8,
+ kModeHardLight = 9,
+ kModeSoftLight = 10,
+ kModeDifference = 11,
+ kModeExclusion = 12,
+ kModeHue = 13,
+ kModeSaturation = 14,
+ kModeColor = 15,
+ kModeLuminosity = 16,
};
DECLARE_NODE_FACTORY(SVGFEBlendElement);
@@ -74,11 +71,7 @@ class SVGFEBlendElement final : public SVGFilterPrimitiveStandardAttributes {
Member<SVGAnimatedEnumeration<Mode>> mode_;
};
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGFEBlendElement::Mode>();
-template <>
-unsigned short GetMaxExposedEnumValue<SVGFEBlendElement::Mode>();
+DECLARE_SVG_ENUM_MAP(SVGFEBlendElement::Mode);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.idl
index 88bc48c9c99..5f7487b76a7 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_blend_element.idl
@@ -36,6 +36,17 @@
[MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_SCREEN = 3;
[MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_DARKEN = 4;
[MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_LIGHTEN = 5;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_OVERLAY = 6;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_COLOR_DODGE = 7;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_COLOR_BURN = 8;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_HARD_LIGHT = 9;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_SOFT_LIGHT = 10;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_DIFFERENCE = 11;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_EXCLUSION = 12;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_HUE = 13;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_SATURATION = 14;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_COLOR = 15;
+ [MeasureAs=SVG1DOMFilter] const unsigned short SVG_FEBLEND_MODE_LUMINOSITY = 16;
[MeasureAs=SVG1DOMFilter] readonly attribute SVGAnimatedString in1;
[MeasureAs=SVG1DOMFilter] readonly attribute SVGAnimatedString in2;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.cc
index 1d4ec5d95b4..46cb2d95219 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.cc
@@ -21,32 +21,31 @@
#include "third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<ColorMatrixType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(FECOLORMATRIX_TYPE_MATRIX, "matrix"));
- entries.push_back(std::make_pair(FECOLORMATRIX_TYPE_SATURATE, "saturate"));
- entries.push_back(
- std::make_pair(FECOLORMATRIX_TYPE_HUEROTATE, "hueRotate"));
- entries.push_back(std::make_pair(FECOLORMATRIX_TYPE_LUMINANCETOALPHA,
- "luminanceToAlpha"));
- }
+const SVGEnumerationMap& GetEnumerationMap<ColorMatrixType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {FECOLORMATRIX_TYPE_MATRIX, "matrix"},
+ {FECOLORMATRIX_TYPE_SATURATE, "saturate"},
+ {FECOLORMATRIX_TYPE_HUEROTATE, "hueRotate"},
+ {FECOLORMATRIX_TYPE_LUMINANCETOALPHA, "luminanceToAlpha"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feColorMatrixTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEColorMatrixTag,
document),
- values_(SVGAnimatedNumberList::Create(this, SVGNames::valuesAttr)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)),
+ values_(SVGAnimatedNumberList::Create(this, svg_names::kValuesAttr)),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)),
type_(SVGAnimatedEnumeration<ColorMatrixType>::Create(
this,
- SVGNames::typeAttr,
+ svg_names::kTypeAttr,
FECOLORMATRIX_TYPE_MATRIX)) {
AddToPropertyMap(values_);
AddToPropertyMap(in1_);
@@ -66,9 +65,9 @@ bool SVGFEColorMatrixElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FEColorMatrix* color_matrix = static_cast<FEColorMatrix*>(effect);
- if (attr_name == SVGNames::typeAttr)
+ if (attr_name == svg_names::kTypeAttr)
return color_matrix->SetType(type_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::valuesAttr)
+ if (attr_name == svg_names::kValuesAttr)
return color_matrix->SetValues(values_->CurrentValue()->ToFloatVector());
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
@@ -77,13 +76,14 @@ bool SVGFEColorMatrixElement::SetFilterEffectAttribute(
void SVGFEColorMatrixElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::typeAttr || attr_name == SVGNames::valuesAttr) {
+ if (attr_name == svg_names::kTypeAttr ||
+ attr_name == svg_names::kValuesAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.h
index 6263a90f7e8..6342432ac8b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_color_matrix_element.h
@@ -29,8 +29,7 @@
namespace blink {
-template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<ColorMatrixType>();
+DECLARE_SVG_ENUM_MAP(ColorMatrixType);
class SVGFEColorMatrixElement final
: public SVGFilterPrimitiveStandardAttributes {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_component_transfer_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_component_transfer_element.cc
index 756642087e9..6255f1e907e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_component_transfer_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_component_transfer_element.cc
@@ -33,9 +33,9 @@ namespace blink {
inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(
Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feComponentTransferTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEComponentTransferTag,
document),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(in1_);
}
@@ -48,7 +48,7 @@ DEFINE_NODE_FACTORY(SVGFEComponentTransferElement)
void SVGFEComponentTransferElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.cc
index a86fdd0e2d7..68c63e6478d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.cc
@@ -21,43 +21,39 @@
#include "third_party/blink/renderer/core/svg/svg_fe_composite_element.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<CompositeOperationType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(FECOMPOSITE_OPERATOR_OVER, "over"));
- entries.push_back(std::make_pair(FECOMPOSITE_OPERATOR_IN, "in"));
- entries.push_back(std::make_pair(FECOMPOSITE_OPERATOR_OUT, "out"));
- entries.push_back(std::make_pair(FECOMPOSITE_OPERATOR_ATOP, "atop"));
- entries.push_back(std::make_pair(FECOMPOSITE_OPERATOR_XOR, "xor"));
- entries.push_back(
- std::make_pair(FECOMPOSITE_OPERATOR_ARITHMETIC, "arithmetic"));
- entries.push_back(std::make_pair(FECOMPOSITE_OPERATOR_LIGHTER, "lighter"));
- }
+const SVGEnumerationMap& GetEnumerationMap<CompositeOperationType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {FECOMPOSITE_OPERATOR_OVER, "over"},
+ {FECOMPOSITE_OPERATOR_IN, "in"},
+ {FECOMPOSITE_OPERATOR_OUT, "out"},
+ {FECOMPOSITE_OPERATOR_ATOP, "atop"},
+ {FECOMPOSITE_OPERATOR_XOR, "xor"},
+ {FECOMPOSITE_OPERATOR_ARITHMETIC, "arithmetic"},
+ {FECOMPOSITE_OPERATOR_LIGHTER, "lighter"},
+ };
+ static const SVGEnumerationMap entries(enum_items,
+ FECOMPOSITE_OPERATOR_ARITHMETIC);
return entries;
}
-template <>
-unsigned short GetMaxExposedEnumValue<CompositeOperationType>() {
- return FECOMPOSITE_OPERATOR_ARITHMETIC;
-}
-
inline SVGFECompositeElement::SVGFECompositeElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feCompositeTag, document),
- k1_(SVGAnimatedNumber::Create(this, SVGNames::k1Attr, 0.0f)),
- k2_(SVGAnimatedNumber::Create(this, SVGNames::k2Attr, 0.0f)),
- k3_(SVGAnimatedNumber::Create(this, SVGNames::k3Attr, 0.0f)),
- k4_(SVGAnimatedNumber::Create(this, SVGNames::k4Attr, 0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)),
- in2_(SVGAnimatedString::Create(this, SVGNames::in2Attr)),
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFECompositeTag,
+ document),
+ k1_(SVGAnimatedNumber::Create(this, svg_names::kK1Attr, 0.0f)),
+ k2_(SVGAnimatedNumber::Create(this, svg_names::kK2Attr, 0.0f)),
+ k3_(SVGAnimatedNumber::Create(this, svg_names::kK3Attr, 0.0f)),
+ k4_(SVGAnimatedNumber::Create(this, svg_names::kK4Attr, 0.0f)),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)),
+ in2_(SVGAnimatedString::Create(this, svg_names::kIn2Attr)),
svg_operator_(SVGAnimatedEnumeration<CompositeOperationType>::Create(
this,
- SVGNames::operatorAttr,
+ svg_names::kOperatorAttr,
FECOMPOSITE_OPERATOR_OVER)) {
AddToPropertyMap(k1_);
AddToPropertyMap(k2_);
@@ -85,15 +81,15 @@ bool SVGFECompositeElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FEComposite* composite = static_cast<FEComposite*>(effect);
- if (attr_name == SVGNames::operatorAttr)
+ if (attr_name == svg_names::kOperatorAttr)
return composite->SetOperation(svg_operator_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::k1Attr)
+ if (attr_name == svg_names::kK1Attr)
return composite->SetK1(k1_->CurrentValue()->Value());
- if (attr_name == SVGNames::k2Attr)
+ if (attr_name == svg_names::kK2Attr)
return composite->SetK2(k2_->CurrentValue()->Value());
- if (attr_name == SVGNames::k3Attr)
+ if (attr_name == svg_names::kK3Attr)
return composite->SetK3(k3_->CurrentValue()->Value());
- if (attr_name == SVGNames::k4Attr)
+ if (attr_name == svg_names::kK4Attr)
return composite->SetK4(k4_->CurrentValue()->Value());
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
@@ -102,15 +98,15 @@ bool SVGFECompositeElement::SetFilterEffectAttribute(
void SVGFECompositeElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::operatorAttr || attr_name == SVGNames::k1Attr ||
- attr_name == SVGNames::k2Attr || attr_name == SVGNames::k3Attr ||
- attr_name == SVGNames::k4Attr) {
+ if (attr_name == svg_names::kOperatorAttr ||
+ attr_name == svg_names::kK1Attr || attr_name == svg_names::kK2Attr ||
+ attr_name == svg_names::kK3Attr || attr_name == svg_names::kK4Attr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr || attr_name == SVGNames::in2Attr) {
+ if (attr_name == svg_names::kInAttr || attr_name == svg_names::kIn2Attr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.h
index 319cf54c665..e3f74eed510 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_composite_element.h
@@ -29,9 +29,7 @@
namespace blink {
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<CompositeOperationType>();
+DECLARE_SVG_ENUM_MAP(CompositeOperationType);
class SVGFECompositeElement final
: public SVGFilterPrimitiveStandardAttributes {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.cc
index 78cda0dfc92..e699329735a 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.cc
@@ -21,6 +21,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/geometry/int_point.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
@@ -28,30 +29,30 @@
namespace blink {
template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<EdgeModeType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(EDGEMODE_DUPLICATE, "duplicate"));
- entries.push_back(std::make_pair(EDGEMODE_WRAP, "wrap"));
- entries.push_back(std::make_pair(EDGEMODE_NONE, "none"));
- }
+const SVGEnumerationMap& GetEnumerationMap<EdgeModeType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {EDGEMODE_DUPLICATE, "duplicate"},
+ {EDGEMODE_WRAP, "wrap"},
+ {EDGEMODE_NONE, "none"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
class SVGAnimatedOrder : public SVGAnimatedIntegerOptionalInteger {
public:
static SVGAnimatedOrder* Create(SVGElement* context_element) {
- return new SVGAnimatedOrder(context_element);
+ return MakeGarbageCollected<SVGAnimatedOrder>(context_element);
}
- SVGParsingError AttributeChanged(const String&) override;
-
- protected:
SVGAnimatedOrder(SVGElement* context_element)
: SVGAnimatedIntegerOptionalInteger(context_element,
- SVGNames::orderAttr,
+ svg_names::kOrderAttr,
3) {}
+ SVGParsingError AttributeChanged(const String&) override;
+
+ protected:
static SVGParsingError CheckValue(SVGParsingError parse_status, int value) {
if (parse_status != SVGParseStatus::kNoError)
return parse_status;
@@ -75,26 +76,26 @@ SVGParsingError SVGAnimatedOrder::AttributeChanged(const String& value) {
inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(
Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feConvolveMatrixTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEConvolveMatrixTag,
document),
- bias_(SVGAnimatedNumber::Create(this, SVGNames::biasAttr, 0.0f)),
- divisor_(SVGAnimatedNumber::Create(this, SVGNames::divisorAttr, 1)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)),
+ bias_(SVGAnimatedNumber::Create(this, svg_names::kBiasAttr, 0.0f)),
+ divisor_(SVGAnimatedNumber::Create(this, svg_names::kDivisorAttr, 1)),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)),
edge_mode_(
SVGAnimatedEnumeration<EdgeModeType>::Create(this,
- SVGNames::edgeModeAttr,
+ svg_names::kEdgeModeAttr,
EDGEMODE_DUPLICATE)),
kernel_matrix_(
- SVGAnimatedNumberList::Create(this, SVGNames::kernelMatrixAttr)),
+ SVGAnimatedNumberList::Create(this, svg_names::kKernelMatrixAttr)),
kernel_unit_length_(SVGAnimatedNumberOptionalNumber::Create(
this,
- SVGNames::kernelUnitLengthAttr,
+ svg_names::kKernelUnitLengthAttr,
0.0f)),
order_(SVGAnimatedOrder::Create(this)),
preserve_alpha_(
- SVGAnimatedBoolean::Create(this, SVGNames::preserveAlphaAttr)),
- target_x_(SVGAnimatedInteger::Create(this, SVGNames::targetXAttr, 0)),
- target_y_(SVGAnimatedInteger::Create(this, SVGNames::targetYAttr, 0)) {
+ SVGAnimatedBoolean::Create(this, svg_names::kPreserveAlphaAttr)),
+ target_x_(SVGAnimatedInteger::Create(this, svg_names::kTargetXAttr, 0)),
+ target_y_(SVGAnimatedInteger::Create(this, svg_names::kTargetYAttr, 0)) {
AddToPropertyMap(preserve_alpha_);
AddToPropertyMap(divisor_);
AddToPropertyMap(bias_);
@@ -158,16 +159,17 @@ bool SVGFEConvolveMatrixElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FEConvolveMatrix* convolve_matrix = static_cast<FEConvolveMatrix*>(effect);
- if (attr_name == SVGNames::edgeModeAttr)
+ if (attr_name == svg_names::kEdgeModeAttr)
return convolve_matrix->SetEdgeMode(
edge_mode_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::divisorAttr)
+ if (attr_name == svg_names::kDivisorAttr)
return convolve_matrix->SetDivisor(ComputeDivisor());
- if (attr_name == SVGNames::biasAttr)
+ if (attr_name == svg_names::kBiasAttr)
return convolve_matrix->SetBias(bias_->CurrentValue()->Value());
- if (attr_name == SVGNames::targetXAttr || attr_name == SVGNames::targetYAttr)
+ if (attr_name == svg_names::kTargetXAttr ||
+ attr_name == svg_names::kTargetYAttr)
return convolve_matrix->SetTargetOffset(TargetPoint());
- if (attr_name == SVGNames::preserveAlphaAttr)
+ if (attr_name == svg_names::kPreserveAlphaAttr)
return convolve_matrix->SetPreserveAlpha(
preserve_alpha_->CurrentValue()->Value());
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
@@ -176,18 +178,19 @@ bool SVGFEConvolveMatrixElement::SetFilterEffectAttribute(
void SVGFEConvolveMatrixElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::edgeModeAttr ||
- attr_name == SVGNames::divisorAttr || attr_name == SVGNames::biasAttr ||
- attr_name == SVGNames::targetXAttr ||
- attr_name == SVGNames::targetYAttr ||
- attr_name == SVGNames::preserveAlphaAttr) {
+ if (attr_name == svg_names::kEdgeModeAttr ||
+ attr_name == svg_names::kDivisorAttr ||
+ attr_name == svg_names::kBiasAttr ||
+ attr_name == svg_names::kTargetXAttr ||
+ attr_name == svg_names::kTargetYAttr ||
+ attr_name == svg_names::kPreserveAlphaAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr || attr_name == SVGNames::orderAttr ||
- attr_name == SVGNames::kernelMatrixAttr) {
+ if (attr_name == svg_names::kInAttr || attr_name == svg_names::kOrderAttr ||
+ attr_name == svg_names::kKernelMatrixAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.h
index d87032740f3..2b633845a25 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_convolve_matrix_element.h
@@ -33,8 +33,7 @@
namespace blink {
-template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<EdgeModeType>();
+DECLARE_SVG_ENUM_MAP(EdgeModeType);
class SVGFEConvolveMatrixElement final
: public SVGFilterPrimitiveStandardAttributes {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_diffuse_lighting_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_diffuse_lighting_element.cc
index 737f65248af..ab43b2a009e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_diffuse_lighting_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_diffuse_lighting_element.cc
@@ -29,17 +29,17 @@ namespace blink {
inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(
Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feDiffuseLightingTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEDiffuseLightingTag,
document),
diffuse_constant_(
- SVGAnimatedNumber::Create(this, SVGNames::diffuseConstantAttr, 1)),
+ SVGAnimatedNumber::Create(this, svg_names::kDiffuseConstantAttr, 1)),
surface_scale_(
- SVGAnimatedNumber::Create(this, SVGNames::surfaceScaleAttr, 1)),
+ SVGAnimatedNumber::Create(this, svg_names::kSurfaceScaleAttr, 1)),
kernel_unit_length_(SVGAnimatedNumberOptionalNumber::Create(
this,
- SVGNames::kernelUnitLengthAttr,
+ svg_names::kKernelUnitLengthAttr,
0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(diffuse_constant_);
AddToPropertyMap(surface_scale_);
AddToPropertyMap(kernel_unit_length_);
@@ -61,15 +61,15 @@ bool SVGFEDiffuseLightingElement::SetFilterEffectAttribute(
const QualifiedName& attr_name) {
FEDiffuseLighting* diffuse_lighting = static_cast<FEDiffuseLighting*>(effect);
- if (attr_name == SVGNames::lighting_colorAttr) {
+ if (attr_name == svg_names::kLightingColorAttr) {
const ComputedStyle& style = ComputedStyleRef();
return diffuse_lighting->SetLightingColor(
style.VisitedDependentColor(GetCSSPropertyLightingColor()));
}
- if (attr_name == SVGNames::surfaceScaleAttr)
+ if (attr_name == svg_names::kSurfaceScaleAttr)
return diffuse_lighting->SetSurfaceScale(
surface_scale_->CurrentValue()->Value());
- if (attr_name == SVGNames::diffuseConstantAttr)
+ if (attr_name == svg_names::kDiffuseConstantAttr)
return diffuse_lighting->SetDiffuseConstant(
diffuse_constant_->CurrentValue()->Value());
@@ -81,25 +81,25 @@ bool SVGFEDiffuseLightingElement::SetFilterEffectAttribute(
DCHECK(light_element);
DCHECK(effect->GetFilter());
- if (attr_name == SVGNames::azimuthAttr)
+ if (attr_name == svg_names::kAzimuthAttr)
return light_source->SetAzimuth(
light_element->azimuth()->CurrentValue()->Value());
- if (attr_name == SVGNames::elevationAttr)
+ if (attr_name == svg_names::kElevationAttr)
return light_source->SetElevation(
light_element->elevation()->CurrentValue()->Value());
- if (attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::zAttr)
+ if (attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kZAttr)
return light_source->SetPosition(
effect->GetFilter()->Resolve3dPoint(light_element->GetPosition()));
- if (attr_name == SVGNames::pointsAtXAttr ||
- attr_name == SVGNames::pointsAtYAttr ||
- attr_name == SVGNames::pointsAtZAttr)
+ if (attr_name == svg_names::kPointsAtXAttr ||
+ attr_name == svg_names::kPointsAtYAttr ||
+ attr_name == svg_names::kPointsAtZAttr)
return light_source->SetPointsAt(
effect->GetFilter()->Resolve3dPoint(light_element->PointsAt()));
- if (attr_name == SVGNames::specularExponentAttr)
+ if (attr_name == svg_names::kSpecularExponentAttr)
return light_source->SetSpecularExponent(
light_element->specularExponent()->CurrentValue()->Value());
- if (attr_name == SVGNames::limitingConeAngleAttr)
+ if (attr_name == svg_names::kLimitingConeAngleAttr)
return light_source->SetLimitingConeAngle(
light_element->limitingConeAngle()->CurrentValue()->Value());
@@ -109,15 +109,15 @@ bool SVGFEDiffuseLightingElement::SetFilterEffectAttribute(
void SVGFEDiffuseLightingElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::surfaceScaleAttr ||
- attr_name == SVGNames::diffuseConstantAttr ||
- attr_name == SVGNames::lighting_colorAttr) {
+ if (attr_name == svg_names::kSurfaceScaleAttr ||
+ attr_name == svg_names::kDiffuseConstantAttr ||
+ attr_name == svg_names::kLightingColorAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.cc
index 653f37e208a..9ae2dddc0b5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.cc
@@ -20,37 +20,34 @@
#include "third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<ChannelSelectorType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(CHANNEL_R, "R"));
- entries.push_back(std::make_pair(CHANNEL_G, "G"));
- entries.push_back(std::make_pair(CHANNEL_B, "B"));
- entries.push_back(std::make_pair(CHANNEL_A, "A"));
- }
+const SVGEnumerationMap& GetEnumerationMap<ChannelSelectorType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {CHANNEL_R, "R"}, {CHANNEL_G, "G"}, {CHANNEL_B, "B"}, {CHANNEL_A, "A"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(
Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feDisplacementMapTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEDisplacementMapTag,
document),
- scale_(SVGAnimatedNumber::Create(this, SVGNames::scaleAttr, 0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)),
- in2_(SVGAnimatedString::Create(this, SVGNames::in2Attr)),
+ scale_(SVGAnimatedNumber::Create(this, svg_names::kScaleAttr, 0.0f)),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)),
+ in2_(SVGAnimatedString::Create(this, svg_names::kIn2Attr)),
x_channel_selector_(SVGAnimatedEnumeration<ChannelSelectorType>::Create(
this,
- SVGNames::xChannelSelectorAttr,
+ svg_names::kXChannelSelectorAttr,
CHANNEL_A)),
y_channel_selector_(SVGAnimatedEnumeration<ChannelSelectorType>::Create(
this,
- SVGNames::yChannelSelectorAttr,
+ svg_names::kYChannelSelectorAttr,
CHANNEL_A)) {
AddToPropertyMap(scale_);
AddToPropertyMap(in1_);
@@ -74,13 +71,13 @@ bool SVGFEDisplacementMapElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FEDisplacementMap* displacement_map = static_cast<FEDisplacementMap*>(effect);
- if (attr_name == SVGNames::xChannelSelectorAttr)
+ if (attr_name == svg_names::kXChannelSelectorAttr)
return displacement_map->SetXChannelSelector(
x_channel_selector_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::yChannelSelectorAttr)
+ if (attr_name == svg_names::kYChannelSelectorAttr)
return displacement_map->SetYChannelSelector(
y_channel_selector_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::scaleAttr)
+ if (attr_name == svg_names::kScaleAttr)
return displacement_map->SetScale(scale_->CurrentValue()->Value());
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
@@ -89,15 +86,15 @@ bool SVGFEDisplacementMapElement::SetFilterEffectAttribute(
void SVGFEDisplacementMapElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::xChannelSelectorAttr ||
- attr_name == SVGNames::yChannelSelectorAttr ||
- attr_name == SVGNames::scaleAttr) {
+ if (attr_name == svg_names::kXChannelSelectorAttr ||
+ attr_name == svg_names::kYChannelSelectorAttr ||
+ attr_name == svg_names::kScaleAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr || attr_name == SVGNames::in2Attr) {
+ if (attr_name == svg_names::kInAttr || attr_name == svg_names::kIn2Attr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h
index a2ea61a18fc..29175d2d618 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h
@@ -28,9 +28,7 @@
namespace blink {
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<ChannelSelectorType>();
+DECLARE_SVG_ENUM_MAP(ChannelSelectorType);
class SVGFEDisplacementMapElement final
: public SVGFilterPrimitiveStandardAttributes {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_distant_light_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_distant_light_element.cc
index 99645e252d2..f6b135f4747 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_distant_light_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_distant_light_element.cc
@@ -25,7 +25,7 @@
namespace blink {
inline SVGFEDistantLightElement::SVGFEDistantLightElement(Document& document)
- : SVGFELightElement(SVGNames::feDistantLightTag, document) {}
+ : SVGFELightElement(svg_names::kFEDistantLightTag, document) {}
DEFINE_NODE_FACTORY(SVGFEDistantLightElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_drop_shadow_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_drop_shadow_element.cc
index 64656ded04e..561173cc518 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_drop_shadow_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_drop_shadow_element.cc
@@ -29,14 +29,15 @@
namespace blink {
inline SVGFEDropShadowElement::SVGFEDropShadowElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feDropShadowTag, document),
- dx_(SVGAnimatedNumber::Create(this, SVGNames::dxAttr, 2)),
- dy_(SVGAnimatedNumber::Create(this, SVGNames::dyAttr, 2)),
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEDropShadowTag,
+ document),
+ dx_(SVGAnimatedNumber::Create(this, svg_names::kDxAttr, 2)),
+ dy_(SVGAnimatedNumber::Create(this, svg_names::kDyAttr, 2)),
std_deviation_(
SVGAnimatedNumberOptionalNumber::Create(this,
- SVGNames::stdDeviationAttr,
+ svg_names::kStdDeviationAttr,
2)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(dx_);
AddToPropertyMap(dy_);
AddToPropertyMap(std_deviation_);
@@ -65,12 +66,12 @@ bool SVGFEDropShadowElement::SetFilterEffectAttribute(
const ComputedStyle& style = ComputedStyleRef();
FEDropShadow* drop_shadow = static_cast<FEDropShadow*>(effect);
- if (attr_name == SVGNames::flood_colorAttr) {
+ if (attr_name == svg_names::kFloodColorAttr) {
drop_shadow->SetShadowColor(
style.VisitedDependentColor(GetCSSPropertyFloodColor()));
return true;
}
- if (attr_name == SVGNames::flood_opacityAttr) {
+ if (attr_name == svg_names::kFloodOpacityAttr) {
drop_shadow->SetShadowOpacity(style.SvgStyle().FloodOpacity());
return true;
}
@@ -80,9 +81,9 @@ bool SVGFEDropShadowElement::SetFilterEffectAttribute(
void SVGFEDropShadowElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::inAttr ||
- attr_name == SVGNames::stdDeviationAttr ||
- attr_name == SVGNames::dxAttr || attr_name == SVGNames::dyAttr) {
+ if (attr_name == svg_names::kInAttr ||
+ attr_name == svg_names::kStdDeviationAttr ||
+ attr_name == svg_names::kDxAttr || attr_name == svg_names::kDyAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_flood_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_flood_element.cc
index 318b3f46be5..3b436135fb6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_flood_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_flood_element.cc
@@ -29,7 +29,7 @@
namespace blink {
inline SVGFEFloodElement::SVGFEFloodElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feFloodTag, document) {}
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEFloodTag, document) {}
DEFINE_NODE_FACTORY(SVGFEFloodElement)
@@ -39,11 +39,11 @@ bool SVGFEFloodElement::SetFilterEffectAttribute(
const ComputedStyle& style = ComputedStyleRef();
FEFlood* flood = static_cast<FEFlood*>(effect);
- if (attr_name == SVGNames::flood_colorAttr) {
+ if (attr_name == svg_names::kFloodColorAttr) {
return flood->SetFloodColor(
style.VisitedDependentColor(GetCSSPropertyFloodColor()));
}
- if (attr_name == SVGNames::flood_opacityAttr)
+ if (attr_name == svg_names::kFloodOpacityAttr)
return flood->SetFloodOpacity(style.SvgStyle().FloodOpacity());
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_a_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_a_element.cc
index b725ce5c976..c7b40eebb7e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_a_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_a_element.cc
@@ -23,7 +23,7 @@
namespace blink {
inline SVGFEFuncAElement::SVGFEFuncAElement(Document& document)
- : SVGComponentTransferFunctionElement(SVGNames::feFuncATag, document) {}
+ : SVGComponentTransferFunctionElement(svg_names::kFEFuncATag, document) {}
DEFINE_NODE_FACTORY(SVGFEFuncAElement)
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_b_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_b_element.cc
index bcb4d9d35df..00f0835cb0f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_b_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_b_element.cc
@@ -23,7 +23,7 @@
namespace blink {
inline SVGFEFuncBElement::SVGFEFuncBElement(Document& document)
- : SVGComponentTransferFunctionElement(SVGNames::feFuncBTag, document) {}
+ : SVGComponentTransferFunctionElement(svg_names::kFEFuncBTag, document) {}
DEFINE_NODE_FACTORY(SVGFEFuncBElement)
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_g_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_g_element.cc
index 78bbcad47be..ab64f16e365 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_g_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_g_element.cc
@@ -23,7 +23,7 @@
namespace blink {
inline SVGFEFuncGElement::SVGFEFuncGElement(Document& document)
- : SVGComponentTransferFunctionElement(SVGNames::feFuncGTag, document) {}
+ : SVGComponentTransferFunctionElement(svg_names::kFEFuncGTag, document) {}
DEFINE_NODE_FACTORY(SVGFEFuncGElement)
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_r_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_r_element.cc
index 1f6aa0db6f1..1b3b77bc9ab 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_func_r_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_func_r_element.cc
@@ -23,7 +23,7 @@
namespace blink {
inline SVGFEFuncRElement::SVGFEFuncRElement(Document& document)
- : SVGComponentTransferFunctionElement(SVGNames::feFuncRTag, document) {}
+ : SVGComponentTransferFunctionElement(svg_names::kFEFuncRTag, document) {}
DEFINE_NODE_FACTORY(SVGFEFuncRElement)
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_gaussian_blur_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_gaussian_blur_element.cc
index 2c234c1354a..6bee7ecb4ca 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_gaussian_blur_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_gaussian_blur_element.cc
@@ -27,13 +27,13 @@
namespace blink {
inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feGaussianBlurTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEGaussianBlurTag,
document),
std_deviation_(
SVGAnimatedNumberOptionalNumber::Create(this,
- SVGNames::stdDeviationAttr,
+ svg_names::kStdDeviationAttr,
0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(std_deviation_);
AddToPropertyMap(in1_);
}
@@ -54,8 +54,8 @@ void SVGFEGaussianBlurElement::setStdDeviation(float x, float y) {
void SVGFEGaussianBlurElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::inAttr ||
- attr_name == SVGNames::stdDeviationAttr) {
+ if (attr_name == svg_names::kInAttr ||
+ attr_name == svg_names::kStdDeviationAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.cc
index 475a22e09c6..92106996649 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.cc
@@ -35,11 +35,11 @@
namespace blink {
inline SVGFEImageElement::SVGFEImageElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feImageTag, document),
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEImageTag, document),
SVGURIReference(this),
preserve_aspect_ratio_(SVGAnimatedPreserveAspectRatio::Create(
this,
- SVGNames::preserveAspectRatioAttr)) {
+ svg_names::kPreserveAspectRatioAttr)) {
AddToPropertyMap(preserve_aspect_ratio_);
}
@@ -108,7 +108,7 @@ void SVGFEImageElement::BuildPendingResource() {
}
void SVGFEImageElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::preserveAspectRatioAttr) {
+ if (attr_name == svg_names::kPreserveAspectRatioAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
@@ -162,4 +162,11 @@ FilterEffect* SVGFEImageElement::Build(SVGFilterBuilder*, Filter* filter) {
preserve_aspect_ratio_->CurrentValue());
}
+bool SVGFEImageElement::TaintsOrigin(bool inputs_taint_origin) const {
+ const SecurityOrigin* security_origin = GetDocument().GetSecurityOrigin();
+ if (cached_image_ && cached_image_->IsAccessAllowed(security_origin))
+ return inputs_taint_origin;
+ return true;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.h
index 759f6ad3cb2..2c9f4eb08bc 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.h
@@ -67,6 +67,7 @@ class SVGFEImageElement final : public SVGFilterPrimitiveStandardAttributes,
void BuildPendingResource() override;
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
+ bool TaintsOrigin(bool inputs_taint_origin) const override;
Member<SVGAnimatedPreserveAspectRatio> preserve_aspect_ratio_;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.cc
index fc0d2d72c43..3c9ae10456c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.cc
@@ -32,23 +32,23 @@ namespace blink {
SVGFELightElement::SVGFELightElement(const QualifiedName& tag_name,
Document& document)
: SVGElement(tag_name, document),
- azimuth_(SVGAnimatedNumber::Create(this, SVGNames::azimuthAttr, 0.0f)),
+ azimuth_(SVGAnimatedNumber::Create(this, svg_names::kAzimuthAttr, 0.0f)),
elevation_(
- SVGAnimatedNumber::Create(this, SVGNames::elevationAttr, 0.0f)),
- x_(SVGAnimatedNumber::Create(this, SVGNames::xAttr, 0.0f)),
- y_(SVGAnimatedNumber::Create(this, SVGNames::yAttr, 0.0f)),
- z_(SVGAnimatedNumber::Create(this, SVGNames::zAttr, 0.0f)),
+ SVGAnimatedNumber::Create(this, svg_names::kElevationAttr, 0.0f)),
+ x_(SVGAnimatedNumber::Create(this, svg_names::kXAttr, 0.0f)),
+ y_(SVGAnimatedNumber::Create(this, svg_names::kYAttr, 0.0f)),
+ z_(SVGAnimatedNumber::Create(this, svg_names::kZAttr, 0.0f)),
points_at_x_(
- SVGAnimatedNumber::Create(this, SVGNames::pointsAtXAttr, 0.0f)),
+ SVGAnimatedNumber::Create(this, svg_names::kPointsAtXAttr, 0.0f)),
points_at_y_(
- SVGAnimatedNumber::Create(this, SVGNames::pointsAtYAttr, 0.0f)),
+ SVGAnimatedNumber::Create(this, svg_names::kPointsAtYAttr, 0.0f)),
points_at_z_(
- SVGAnimatedNumber::Create(this, SVGNames::pointsAtZAttr, 0.0f)),
+ SVGAnimatedNumber::Create(this, svg_names::kPointsAtZAttr, 0.0f)),
specular_exponent_(
- SVGAnimatedNumber::Create(this, SVGNames::specularExponentAttr, 1)),
+ SVGAnimatedNumber::Create(this, svg_names::kSpecularExponentAttr, 1)),
limiting_cone_angle_(
SVGAnimatedNumber::Create(this,
- SVGNames::limitingConeAngleAttr,
+ svg_names::kLimitingConeAngleAttr,
0.0f)) {
AddToPropertyMap(azimuth_);
AddToPropertyMap(elevation_);
@@ -94,14 +94,15 @@ FloatPoint3D SVGFELightElement::PointsAt() const {
}
void SVGFELightElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::azimuthAttr ||
- attr_name == SVGNames::elevationAttr || attr_name == SVGNames::xAttr ||
- attr_name == SVGNames::yAttr || attr_name == SVGNames::zAttr ||
- attr_name == SVGNames::pointsAtXAttr ||
- attr_name == SVGNames::pointsAtYAttr ||
- attr_name == SVGNames::pointsAtZAttr ||
- attr_name == SVGNames::specularExponentAttr ||
- attr_name == SVGNames::limitingConeAngleAttr) {
+ if (attr_name == svg_names::kAzimuthAttr ||
+ attr_name == svg_names::kElevationAttr ||
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kZAttr ||
+ attr_name == svg_names::kPointsAtXAttr ||
+ attr_name == svg_names::kPointsAtYAttr ||
+ attr_name == svg_names::kPointsAtZAttr ||
+ attr_name == svg_names::kSpecularExponentAttr ||
+ attr_name == svg_names::kLimitingConeAngleAttr) {
ContainerNode* parent = parentNode();
if (!parent)
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.h
index 7ffddd7342b..aad4aad8f38 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_light_element.h
@@ -91,9 +91,9 @@ class SVGFELightElement : public SVGElement {
};
inline bool IsSVGFELightElement(const SVGElement& element) {
- return element.HasTagName(SVGNames::feDistantLightTag) ||
- element.HasTagName(SVGNames::fePointLightTag) ||
- element.HasTagName(SVGNames::feSpotLightTag);
+ return element.HasTagName(svg_names::kFEDistantLightTag) ||
+ element.HasTagName(svg_names::kFEPointLightTag) ||
+ element.HasTagName(svg_names::kFESpotLightTag);
}
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGFELightElement);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_element.cc
index c32f8ee387c..aa7b48e4a86 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_element.cc
@@ -29,7 +29,7 @@
namespace blink {
inline SVGFEMergeElement::SVGFEMergeElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feMergeTag, document) {}
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEMergeTag, document) {}
DEFINE_NODE_FACTORY(SVGFEMergeElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_node_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_node_element.cc
index 7662fc4bfe9..4f8b7b38df9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_node_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_merge_node_element.cc
@@ -25,8 +25,8 @@
namespace blink {
inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(Document& document)
- : SVGElement(SVGNames::feMergeNodeTag, document),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ : SVGElement(svg_names::kFEMergeNodeTag, document),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(in1_);
}
@@ -39,7 +39,7 @@ DEFINE_NODE_FACTORY(SVGFEMergeNodeElement)
void SVGFEMergeNodeElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
InvalidateFilterPrimitiveParent(*this);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.cc
index f67392902f7..15e75d0a099 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.cc
@@ -20,30 +20,31 @@
#include "third_party/blink/renderer/core/svg/svg_fe_morphology_element.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<MorphologyOperatorType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(FEMORPHOLOGY_OPERATOR_ERODE, "erode"));
- entries.push_back(std::make_pair(FEMORPHOLOGY_OPERATOR_DILATE, "dilate"));
- }
+const SVGEnumerationMap& GetEnumerationMap<MorphologyOperatorType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {FEMORPHOLOGY_OPERATOR_ERODE, "erode"},
+ {FEMORPHOLOGY_OPERATOR_DILATE, "dilate"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
inline SVGFEMorphologyElement::SVGFEMorphologyElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feMorphologyTag, document),
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEMorphologyTag,
+ document),
radius_(SVGAnimatedNumberOptionalNumber::Create(this,
- SVGNames::radiusAttr,
+ svg_names::kRadiusAttr,
0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)),
svg_operator_(SVGAnimatedEnumeration<MorphologyOperatorType>::Create(
this,
- SVGNames::operatorAttr,
+ svg_names::kOperatorAttr,
FEMORPHOLOGY_OPERATOR_ERODE)) {
AddToPropertyMap(radius_);
AddToPropertyMap(in1_);
@@ -63,10 +64,10 @@ bool SVGFEMorphologyElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FEMorphology* morphology = static_cast<FEMorphology*>(effect);
- if (attr_name == SVGNames::operatorAttr)
+ if (attr_name == svg_names::kOperatorAttr)
return morphology->SetMorphologyOperator(
svg_operator_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::radiusAttr) {
+ if (attr_name == svg_names::kRadiusAttr) {
// Both setRadius functions should be evaluated separately.
bool is_radius_x_changed =
morphology->SetRadiusX(radiusX()->CurrentValue()->Value());
@@ -80,14 +81,14 @@ bool SVGFEMorphologyElement::SetFilterEffectAttribute(
void SVGFEMorphologyElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::operatorAttr ||
- attr_name == SVGNames::radiusAttr) {
+ if (attr_name == svg_names::kOperatorAttr ||
+ attr_name == svg_names::kRadiusAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.h
index 21d55b3e085..53d796f640b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_morphology_element.h
@@ -28,9 +28,7 @@
namespace blink {
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<MorphologyOperatorType>();
+DECLARE_SVG_ENUM_MAP(MorphologyOperatorType);
class SVGFEMorphologyElement final
: public SVGFilterPrimitiveStandardAttributes {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_offset_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_offset_element.cc
index 05dd198c465..349fc64d492 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_offset_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_offset_element.cc
@@ -27,10 +27,10 @@
namespace blink {
inline SVGFEOffsetElement::SVGFEOffsetElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feOffsetTag, document),
- dx_(SVGAnimatedNumber::Create(this, SVGNames::dxAttr, 0.0f)),
- dy_(SVGAnimatedNumber::Create(this, SVGNames::dyAttr, 0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFEOffsetTag, document),
+ dx_(SVGAnimatedNumber::Create(this, svg_names::kDxAttr, 0.0f)),
+ dy_(SVGAnimatedNumber::Create(this, svg_names::kDyAttr, 0.0f)),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(dx_);
AddToPropertyMap(dy_);
AddToPropertyMap(in1_);
@@ -46,8 +46,8 @@ void SVGFEOffsetElement::Trace(blink::Visitor* visitor) {
DEFINE_NODE_FACTORY(SVGFEOffsetElement)
void SVGFEOffsetElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::inAttr || attr_name == SVGNames::dxAttr ||
- attr_name == SVGNames::dyAttr) {
+ if (attr_name == svg_names::kInAttr || attr_name == svg_names::kDxAttr ||
+ attr_name == svg_names::kDyAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_point_light_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_point_light_element.cc
index b6d7cd27ac7..4d2d8fefbcc 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_point_light_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_point_light_element.cc
@@ -26,7 +26,7 @@
namespace blink {
inline SVGFEPointLightElement::SVGFEPointLightElement(Document& document)
- : SVGFELightElement(SVGNames::fePointLightTag, document) {}
+ : SVGFELightElement(svg_names::kFEPointLightTag, document) {}
DEFINE_NODE_FACTORY(SVGFEPointLightElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_specular_lighting_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_specular_lighting_element.cc
index 3f56237449f..f2bda029e61 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_specular_lighting_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_specular_lighting_element.cc
@@ -31,19 +31,19 @@ namespace blink {
inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(
Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feSpecularLightingTag,
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFESpecularLightingTag,
document),
specular_constant_(
- SVGAnimatedNumber::Create(this, SVGNames::specularConstantAttr, 1)),
+ SVGAnimatedNumber::Create(this, svg_names::kSpecularConstantAttr, 1)),
specular_exponent_(
- SVGAnimatedNumber::Create(this, SVGNames::specularExponentAttr, 1)),
+ SVGAnimatedNumber::Create(this, svg_names::kSpecularExponentAttr, 1)),
surface_scale_(
- SVGAnimatedNumber::Create(this, SVGNames::surfaceScaleAttr, 1)),
+ SVGAnimatedNumber::Create(this, svg_names::kSurfaceScaleAttr, 1)),
kernel_unit_length_(SVGAnimatedNumberOptionalNumber::Create(
this,
- SVGNames::kernelUnitLengthAttr,
+ svg_names::kKernelUnitLengthAttr,
0.0f)),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(specular_constant_);
AddToPropertyMap(specular_exponent_);
AddToPropertyMap(surface_scale_);
@@ -68,18 +68,18 @@ bool SVGFESpecularLightingElement::SetFilterEffectAttribute(
FESpecularLighting* specular_lighting =
static_cast<FESpecularLighting*>(effect);
- if (attr_name == SVGNames::lighting_colorAttr) {
+ if (attr_name == svg_names::kLightingColorAttr) {
const ComputedStyle& style = ComputedStyleRef();
return specular_lighting->SetLightingColor(
style.VisitedDependentColor(GetCSSPropertyLightingColor()));
}
- if (attr_name == SVGNames::surfaceScaleAttr)
+ if (attr_name == svg_names::kSurfaceScaleAttr)
return specular_lighting->SetSurfaceScale(
surface_scale_->CurrentValue()->Value());
- if (attr_name == SVGNames::specularConstantAttr)
+ if (attr_name == svg_names::kSpecularConstantAttr)
return specular_lighting->SetSpecularConstant(
specular_constant_->CurrentValue()->Value());
- if (attr_name == SVGNames::specularExponentAttr)
+ if (attr_name == svg_names::kSpecularExponentAttr)
return specular_lighting->SetSpecularExponent(
specular_exponent_->CurrentValue()->Value());
@@ -90,25 +90,25 @@ bool SVGFESpecularLightingElement::SetFilterEffectAttribute(
DCHECK(light_element);
DCHECK(effect->GetFilter());
- if (attr_name == SVGNames::azimuthAttr)
+ if (attr_name == svg_names::kAzimuthAttr)
return light_source->SetAzimuth(
light_element->azimuth()->CurrentValue()->Value());
- if (attr_name == SVGNames::elevationAttr)
+ if (attr_name == svg_names::kElevationAttr)
return light_source->SetElevation(
light_element->elevation()->CurrentValue()->Value());
- if (attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::zAttr)
+ if (attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kZAttr)
return light_source->SetPosition(
effect->GetFilter()->Resolve3dPoint(light_element->GetPosition()));
- if (attr_name == SVGNames::pointsAtXAttr ||
- attr_name == SVGNames::pointsAtYAttr ||
- attr_name == SVGNames::pointsAtZAttr)
+ if (attr_name == svg_names::kPointsAtXAttr ||
+ attr_name == svg_names::kPointsAtYAttr ||
+ attr_name == svg_names::kPointsAtZAttr)
return light_source->SetPointsAt(
effect->GetFilter()->Resolve3dPoint(light_element->PointsAt()));
- if (attr_name == SVGNames::specularExponentAttr)
+ if (attr_name == svg_names::kSpecularExponentAttr)
return light_source->SetSpecularExponent(
light_element->specularExponent()->CurrentValue()->Value());
- if (attr_name == SVGNames::limitingConeAngleAttr)
+ if (attr_name == svg_names::kLimitingConeAngleAttr)
return light_source->SetLimitingConeAngle(
light_element->limitingConeAngle()->CurrentValue()->Value());
@@ -118,15 +118,15 @@ bool SVGFESpecularLightingElement::SetFilterEffectAttribute(
void SVGFESpecularLightingElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::surfaceScaleAttr ||
- attr_name == SVGNames::specularConstantAttr ||
- attr_name == SVGNames::specularExponentAttr) {
+ if (attr_name == svg_names::kSurfaceScaleAttr ||
+ attr_name == svg_names::kSpecularConstantAttr ||
+ attr_name == svg_names::kSpecularExponentAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
}
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_spot_light_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_spot_light_element.cc
index 7e63ff4e8aa..3d6be8223bf 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_spot_light_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_spot_light_element.cc
@@ -26,7 +26,7 @@
namespace blink {
inline SVGFESpotLightElement::SVGFESpotLightElement(Document& document)
- : SVGFELightElement(SVGNames::feSpotLightTag, document) {}
+ : SVGFELightElement(svg_names::kFESpotLightTag, document) {}
DEFINE_NODE_FACTORY(SVGFESpotLightElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_tile_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_tile_element.cc
index 0be047e2af6..aa39c46c9fe 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_tile_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_tile_element.cc
@@ -27,8 +27,8 @@
namespace blink {
inline SVGFETileElement::SVGFETileElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feTileTag, document),
- in1_(SVGAnimatedString::Create(this, SVGNames::inAttr)) {
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFETileTag, document),
+ in1_(SVGAnimatedString::Create(this, svg_names::kInAttr)) {
AddToPropertyMap(in1_);
}
@@ -40,7 +40,7 @@ void SVGFETileElement::Trace(blink::Visitor* visitor) {
DEFINE_NODE_FACTORY(SVGFETileElement)
void SVGFETileElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::inAttr) {
+ if (attr_name == svg_names::kInAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.cc
index 6ace7ca2b54..091ce6697dd 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.cc
@@ -20,49 +20,48 @@
#include "third_party/blink/renderer/core/svg/svg_fe_turbulence_element.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<SVGStitchOptions>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(kSvgStitchtypeStitch, "stitch"));
- entries.push_back(std::make_pair(kSvgStitchtypeNostitch, "noStitch"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGStitchOptions>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSvgStitchtypeStitch, "stitch"}, {kSvgStitchtypeNostitch, "noStitch"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<TurbulenceType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(
- std::make_pair(FETURBULENCE_TYPE_FRACTALNOISE, "fractalNoise"));
- entries.push_back(
- std::make_pair(FETURBULENCE_TYPE_TURBULENCE, "turbulence"));
- }
+const SVGEnumerationMap& GetEnumerationMap<TurbulenceType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {FETURBULENCE_TYPE_FRACTALNOISE, "fractalNoise"},
+ {FETURBULENCE_TYPE_TURBULENCE, "turbulence"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
inline SVGFETurbulenceElement::SVGFETurbulenceElement(Document& document)
- : SVGFilterPrimitiveStandardAttributes(SVGNames::feTurbulenceTag, document),
+ : SVGFilterPrimitiveStandardAttributes(svg_names::kFETurbulenceTag,
+ document),
base_frequency_(
SVGAnimatedNumberOptionalNumber::Create(this,
- SVGNames::baseFrequencyAttr,
+ svg_names::kBaseFrequencyAttr,
0.0f)),
- seed_(SVGAnimatedNumber::Create(this, SVGNames::seedAttr, 0.0f)),
+ seed_(SVGAnimatedNumber::Create(this, svg_names::kSeedAttr, 0.0f)),
stitch_tiles_(SVGAnimatedEnumeration<SVGStitchOptions>::Create(
this,
- SVGNames::stitchTilesAttr,
+ svg_names::kStitchTilesAttr,
kSvgStitchtypeNostitch)),
type_(SVGAnimatedEnumeration<TurbulenceType>::Create(
this,
- SVGNames::typeAttr,
+ svg_names::kTypeAttr,
FETURBULENCE_TYPE_TURBULENCE)),
num_octaves_(
- SVGAnimatedInteger::Create(this, SVGNames::numOctavesAttr, 1)) {
+ SVGAnimatedInteger::Create(this, svg_names::kNumOctavesAttr, 1)) {
AddToPropertyMap(base_frequency_);
AddToPropertyMap(seed_);
AddToPropertyMap(stitch_tiles_);
@@ -85,21 +84,21 @@ bool SVGFETurbulenceElement::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
FETurbulence* turbulence = static_cast<FETurbulence*>(effect);
- if (attr_name == SVGNames::typeAttr)
+ if (attr_name == svg_names::kTypeAttr)
return turbulence->SetType(type_->CurrentValue()->EnumValue());
- if (attr_name == SVGNames::stitchTilesAttr)
+ if (attr_name == svg_names::kStitchTilesAttr)
return turbulence->SetStitchTiles(
stitch_tiles_->CurrentValue()->EnumValue() == kSvgStitchtypeStitch);
- if (attr_name == SVGNames::baseFrequencyAttr) {
+ if (attr_name == svg_names::kBaseFrequencyAttr) {
bool base_frequency_x_changed = turbulence->SetBaseFrequencyX(
baseFrequencyX()->CurrentValue()->Value());
bool base_frequency_y_changed = turbulence->SetBaseFrequencyY(
baseFrequencyY()->CurrentValue()->Value());
return (base_frequency_x_changed || base_frequency_y_changed);
}
- if (attr_name == SVGNames::seedAttr)
+ if (attr_name == svg_names::kSeedAttr)
return turbulence->SetSeed(seed_->CurrentValue()->Value());
- if (attr_name == SVGNames::numOctavesAttr)
+ if (attr_name == svg_names::kNumOctavesAttr)
return turbulence->SetNumOctaves(num_octaves_->CurrentValue()->Value());
return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
@@ -108,11 +107,11 @@ bool SVGFETurbulenceElement::SetFilterEffectAttribute(
void SVGFETurbulenceElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::baseFrequencyAttr ||
- attr_name == SVGNames::numOctavesAttr ||
- attr_name == SVGNames::seedAttr ||
- attr_name == SVGNames::stitchTilesAttr ||
- attr_name == SVGNames::typeAttr) {
+ if (attr_name == svg_names::kBaseFrequencyAttr ||
+ attr_name == svg_names::kNumOctavesAttr ||
+ attr_name == svg_names::kSeedAttr ||
+ attr_name == svg_names::kStitchTilesAttr ||
+ attr_name == svg_names::kTypeAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
PrimitiveAttributeChanged(attr_name);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.h b/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.h
index 916dd74b8fa..3540909aac6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fe_turbulence_element.h
@@ -36,11 +36,9 @@ enum SVGStitchOptions {
kSvgStitchtypeStitch = 1,
kSvgStitchtypeNostitch = 2
};
-template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<SVGStitchOptions>();
+DECLARE_SVG_ENUM_MAP(SVGStitchOptions);
-template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<TurbulenceType>();
+DECLARE_SVG_ENUM_MAP(TurbulenceType);
class SVGFETurbulenceElement final
: public SVGFilterPrimitiveStandardAttributes {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_filter_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_filter_element.cc
index 137c33ff9df..8cc60f85e04 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_filter_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_filter_element.cc
@@ -30,36 +30,36 @@
namespace blink {
inline SVGFilterElement::SVGFilterElement(Document& document)
- : SVGElement(SVGNames::filterTag, document),
+ : SVGElement(svg_names::kFilterTag, document),
SVGURIReference(this),
// Spec: If the x/y attribute is not specified, the effect is as if a
// value of "-10%" were specified.
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercentMinus10)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercentMinus10)),
// Spec: If the width/height attribute is not specified, the effect is as
// if a value of "120%" were specified.
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent120)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent120)),
filter_units_(SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::filterUnitsAttr,
+ svg_names::kFilterUnitsAttr,
SVGUnitTypes::kSvgUnitTypeObjectboundingbox)),
primitive_units_(
SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::primitiveUnitsAttr,
+ svg_names::kPrimitiveUnitsAttr,
SVGUnitTypes::kSvgUnitTypeUserspaceonuse)) {
AddToPropertyMap(x_);
AddToPropertyMap(y_);
@@ -85,14 +85,14 @@ void SVGFilterElement::Trace(blink::Visitor* visitor) {
}
void SVGFilterElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- bool is_xywh = attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr ||
- attr_name == SVGNames::heightAttr;
+ bool is_xywh =
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr;
if (is_xywh)
UpdateRelativeLengthsInformation();
- if (is_xywh || attr_name == SVGNames::filterUnitsAttr ||
- attr_name == SVGNames::primitiveUnitsAttr) {
+ if (is_xywh || attr_name == svg_names::kFilterUnitsAttr ||
+ attr_name == svg_names::kPrimitiveUnitsAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
InvalidateFilterChain();
return;
@@ -132,9 +132,10 @@ void SVGFilterElement::ChildrenChanged(const ChildrenChange& change) {
if (change.by_parser)
return;
- if (LayoutObject* object = GetLayoutObject())
+ if (LayoutObject* object = GetLayoutObject()) {
object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kChildChanged);
+ layout_invalidation_reason::kChildChanged);
+ }
InvalidateFilterChain();
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.cc b/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.cc
index 0edfa01206f..20ee4603490 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.cc
@@ -38,24 +38,24 @@ SVGFilterPrimitiveStandardAttributes::SVGFilterPrimitiveStandardAttributes(
// Spec: If the x/y attribute is not specified, the effect is as if a
// value of "0%" were specified.
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent0)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent0)),
// Spec: If the width/height attribute is not specified, the effect is as
// if a value of "100%" were specified.
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent100)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent100)),
- result_(SVGAnimatedString::Create(this, SVGNames::resultAttr)) {
+ result_(SVGAnimatedString::Create(this, svg_names::kResultAttr)) {
AddToPropertyMap(x_);
AddToPropertyMap(y_);
AddToPropertyMap(width_);
@@ -75,7 +75,7 @@ void SVGFilterPrimitiveStandardAttributes::Trace(blink::Visitor* visitor) {
bool SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
FilterEffect* effect,
const QualifiedName& attr_name) {
- DCHECK(attr_name == SVGNames::color_interpolation_filtersAttr);
+ DCHECK(attr_name == svg_names::kColorInterpolationFiltersAttr);
DCHECK(GetLayoutObject());
EColorInterpolation color_interpolation =
GetLayoutObject()->StyleRef().SvgStyle().ColorInterpolationFilters();
@@ -89,9 +89,10 @@ bool SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
void SVGFilterPrimitiveStandardAttributes::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr ||
- attr_name == SVGNames::resultAttr) {
+ if (attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr ||
+ attr_name == svg_names::kHeightAttr ||
+ attr_name == svg_names::kResultAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_fit_to_view_box.cc b/chromium/third_party/blink/renderer/core/svg/svg_fit_to_view_box.cc
index 4fab93100d3..2b71a02216a 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_fit_to_view_box.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_fit_to_view_box.cc
@@ -32,14 +32,13 @@ namespace blink {
class SVGAnimatedViewBoxRect : public SVGAnimatedRect {
public:
static SVGAnimatedRect* Create(SVGElement* context_element) {
- return new SVGAnimatedViewBoxRect(context_element);
+ return MakeGarbageCollected<SVGAnimatedViewBoxRect>(context_element);
}
- SVGParsingError AttributeChanged(const String&) override;
-
- protected:
SVGAnimatedViewBoxRect(SVGElement* context_element)
- : SVGAnimatedRect(context_element, SVGNames::viewBoxAttr) {}
+ : SVGAnimatedRect(context_element, svg_names::kViewBoxAttr) {}
+
+ SVGParsingError AttributeChanged(const String&) override;
};
SVGParsingError SVGAnimatedViewBoxRect::AttributeChanged(const String& value) {
@@ -57,7 +56,7 @@ SVGFitToViewBox::SVGFitToViewBox(SVGElement* element)
: view_box_(SVGAnimatedViewBoxRect::Create(element)),
preserve_aspect_ratio_(SVGAnimatedPreserveAspectRatio::Create(
element,
- SVGNames::preserveAspectRatioAttr)) {
+ svg_names::kPreserveAspectRatioAttr)) {
DCHECK(element);
element->AddToPropertyMap(view_box_);
element->AddToPropertyMap(preserve_aspect_ratio_);
@@ -83,8 +82,8 @@ AffineTransform SVGFitToViewBox::ViewBoxToViewTransform(
}
bool SVGFitToViewBox::IsKnownAttribute(const QualifiedName& attr_name) {
- return attr_name == SVGNames::viewBoxAttr ||
- attr_name == SVGNames::preserveAspectRatioAttr;
+ return attr_name == svg_names::kViewBoxAttr ||
+ attr_name == svg_names::kPreserveAspectRatioAttr;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.cc
index 1356e6937df..96ba4d10177 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.cc
@@ -29,24 +29,24 @@
namespace blink {
inline SVGForeignObjectElement::SVGForeignObjectElement(Document& document)
- : SVGGraphicsElement(SVGNames::foreignObjectTag, document),
+ : SVGGraphicsElement(svg_names::kForeignObjectTag, document),
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyX)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyY)),
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyWidth)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyHeight)) {
@@ -94,9 +94,9 @@ void SVGForeignObjectElement::CollectStyleForPresentationAttribute(
void SVGForeignObjectElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
bool is_width_height_attribute =
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr;
+ attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr;
bool is_xy_attribute =
- attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr;
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr;
if (is_xy_attribute || is_width_height_attribute) {
SVGElement::InvalidationGuard invalidation_guard(this);
@@ -106,7 +106,7 @@ void SVGForeignObjectElement::SvgAttributeChanged(
kLocalStyleChange,
is_width_height_attribute
? StyleChangeReasonForTracing::Create(
- StyleChangeReason::kSVGContainerSizeChange)
+ style_change_reason::kSVGContainerSizeChange)
: StyleChangeReasonForTracing::FromAttribute(attr_name));
UpdateRelativeLengthsInformation();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_g_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_g_element.cc
index b13a737d2c4..3ecd67566fa 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_g_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_g_element.cc
@@ -28,7 +28,7 @@ namespace blink {
inline SVGGElement::SVGGElement(Document& document,
ConstructionType construction_type)
- : SVGGraphicsElement(SVGNames::gTag, document, construction_type) {}
+ : SVGGraphicsElement(svg_names::kGTag, document, construction_type) {}
DEFINE_NODE_FACTORY(SVGGElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.cc
index d5f452f6c46..a4fb066e0a4 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.cc
@@ -31,33 +31,32 @@
#include "third_party/blink/renderer/core/svg/svg_geometry_element.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/layout/hit_test_request.h"
-#include "third_party/blink/renderer/core/layout/pointer_events_hit_rules.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_path.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_shape.h"
+#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/svg/svg_point_tear_off.h"
#include "third_party/blink/renderer/core/svg_names.h"
+#include "third_party/blink/renderer/platform/graphics/stroke_data.h"
namespace blink {
class SVGAnimatedPathLength final : public SVGAnimatedNumber {
public:
static SVGAnimatedPathLength* Create(SVGGeometryElement* context_element) {
- return new SVGAnimatedPathLength(context_element);
+ return MakeGarbageCollected<SVGAnimatedPathLength>(context_element);
}
+ explicit SVGAnimatedPathLength(SVGGeometryElement* context_element)
+ : SVGAnimatedNumber(context_element,
+ svg_names::kPathLengthAttr,
+ SVGNumber::Create()) {}
+
SVGParsingError AttributeChanged(const String& value) override {
SVGParsingError parse_status = SVGAnimatedNumber::AttributeChanged(value);
if (parse_status == SVGParseStatus::kNoError && BaseValue()->Value() < 0)
parse_status = SVGParseStatus::kNegativeValue;
return parse_status;
}
-
- private:
- explicit SVGAnimatedPathLength(SVGGeometryElement* context_element)
- : SVGAnimatedNumber(context_element,
- SVGNames::pathLengthAttr,
- SVGNumber::Create()) {}
};
SVGGeometryElement::SVGGeometryElement(const QualifiedName& tag_name,
@@ -69,7 +68,7 @@ SVGGeometryElement::SVGGeometryElement(const QualifiedName& tag_name,
}
void SVGGeometryElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::pathLengthAttr) {
+ if (attr_name == svg_names::kPathLengthAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
if (LayoutObject* layout_object = GetLayoutObject())
MarkForLayoutAndParentResourceInvalidation(*layout_object);
@@ -89,17 +88,13 @@ bool SVGGeometryElement::isPointInFill(SVGPointTearOff* point) const {
// FIXME: Eventually we should support isPointInFill for display:none
// elements.
- if (!GetLayoutObject() || !GetLayoutObject()->IsSVGShape())
+ const LayoutObject* layout_object = GetLayoutObject();
+ if (!layout_object)
return false;
- HitTestRequest request(HitTestRequest::kReadOnly);
- PointerEventsHitRules hit_rules(
- PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request,
- GetLayoutObject()->StyleRef().PointerEvents());
- hit_rules.can_hit_stroke = false;
- HitTestLocation location(point->Target()->Value());
- return ToLayoutSVGShape(GetLayoutObject())
- ->NodeAtPointInternal(request, location, hit_rules);
+ // Path::Contains will reject points with a non-finite component.
+ WindRule fill_rule = layout_object->StyleRef().SvgStyle().FillRule();
+ return AsPath().Contains(point->Target()->Value(), fill_rule);
}
bool SVGGeometryElement::isPointInStroke(SVGPointTearOff* point) const {
@@ -107,17 +102,26 @@ bool SVGGeometryElement::isPointInStroke(SVGPointTearOff* point) const {
// FIXME: Eventually we should support isPointInStroke for display:none
// elements.
- if (!GetLayoutObject() || !GetLayoutObject()->IsSVGShape())
+ const LayoutObject* layout_object = GetLayoutObject();
+ if (!layout_object)
return false;
+ const LayoutSVGShape& layout_shape = ToLayoutSVGShape(*layout_object);
+
+ StrokeData stroke_data;
+ SVGLayoutSupport::ApplyStrokeStyleToStrokeData(
+ stroke_data, layout_shape.StyleRef(), layout_shape,
+ PathLengthScaleFactor());
- HitTestRequest request(HitTestRequest::kReadOnly);
- PointerEventsHitRules hit_rules(
- PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request,
- GetLayoutObject()->StyleRef().PointerEvents());
- hit_rules.can_hit_fill = false;
- HitTestLocation location(point->Target()->Value());
- return ToLayoutSVGShape(GetLayoutObject())
- ->NodeAtPointInternal(request, location, hit_rules);
+ Path path = AsPath();
+ FloatPoint local_point(point->Target()->Value());
+ if (layout_shape.HasNonScalingStroke()) {
+ const AffineTransform transform =
+ layout_shape.ComputeNonScalingStrokeTransform();
+ path.Transform(transform);
+ local_point = transform.MapPoint(local_point);
+ }
+ // Path::StrokeContains will reject points with a non-finite component.
+ return path.StrokeContains(local_point, stroke_data);
}
Path SVGGeometryElement::ToClipPath() const {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.cc
index 033e8c5177c..5f29ecaf0f8 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.cc
@@ -22,25 +22,24 @@
#include "third_party/blink/renderer/core/svg/svg_gradient_element.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/id_target_observer.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.h"
#include "third_party/blink/renderer/core/svg/gradient_attributes.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg/svg_stop_element.h"
#include "third_party/blink/renderer/core/svg/svg_transform_list.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGSpreadMethodType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(kSVGSpreadMethodPad, "pad"));
- entries.push_back(std::make_pair(kSVGSpreadMethodReflect, "reflect"));
- entries.push_back(std::make_pair(kSVGSpreadMethodRepeat, "repeat"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGSpreadMethodType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSVGSpreadMethodPad, "pad"},
+ {kSVGSpreadMethodReflect, "reflect"},
+ {kSVGSpreadMethodRepeat, "repeat"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
@@ -50,15 +49,15 @@ SVGGradientElement::SVGGradientElement(const QualifiedName& tag_name,
SVGURIReference(this),
gradient_transform_(
SVGAnimatedTransformList::Create(this,
- SVGNames::gradientTransformAttr,
+ svg_names::kGradientTransformAttr,
CSSPropertyTransform)),
spread_method_(SVGAnimatedEnumeration<SVGSpreadMethodType>::Create(
this,
- SVGNames::spreadMethodAttr,
+ svg_names::kSpreadMethodAttr,
kSVGSpreadMethodPad)),
gradient_units_(SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::gradientUnitsAttr,
+ svg_names::kGradientUnitsAttr,
SVGUnitTypes::kSvgUnitTypeObjectboundingbox)) {
AddToPropertyMap(gradient_transform_);
AddToPropertyMap(spread_method_);
@@ -82,7 +81,7 @@ void SVGGradientElement::BuildPendingResource() {
if (auto* gradient = ToSVGGradientElementOrNull(target))
AddReferenceTo(gradient);
- InvalidateGradient(LayoutInvalidationReason::kSvgResourceInvalidated);
+ InvalidateGradient(layout_invalidation_reason::kSvgResourceInvalidated);
}
void SVGGradientElement::ClearResourceReferences() {
@@ -94,7 +93,7 @@ void SVGGradientElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == SVGNames::gradientTransformAttr) {
+ if (name == svg_names::kGradientTransformAttr) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyTransform,
*gradient_transform_->CurrentValue()->CssValue());
@@ -104,17 +103,17 @@ void SVGGradientElement::CollectStyleForPresentationAttribute(
}
void SVGGradientElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::gradientTransformAttr) {
+ if (attr_name == svg_names::kGradientTransformAttr) {
InvalidateSVGPresentationAttributeStyle();
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::FromAttribute(attr_name));
}
- if (attr_name == SVGNames::gradientUnitsAttr ||
- attr_name == SVGNames::gradientTransformAttr ||
- attr_name == SVGNames::spreadMethodAttr) {
+ if (attr_name == svg_names::kGradientUnitsAttr ||
+ attr_name == svg_names::kGradientTransformAttr ||
+ attr_name == svg_names::kSpreadMethodAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
- InvalidateGradient(LayoutInvalidationReason::kAttributeChanged);
+ InvalidateGradient(layout_invalidation_reason::kAttributeChanged);
return;
}
@@ -147,7 +146,7 @@ void SVGGradientElement::ChildrenChanged(const ChildrenChange& change) {
if (change.by_parser)
return;
- InvalidateGradient(LayoutInvalidationReason::kChildChanged);
+ InvalidateGradient(layout_invalidation_reason::kChildChanged);
}
void SVGGradientElement::InvalidateGradient(
@@ -160,7 +159,7 @@ void SVGGradientElement::InvalidateDependentGradients() {
NotifyIncomingReferences([](SVGElement& element) {
if (auto* gradient = ToSVGGradientElementOrNull(element)) {
gradient->InvalidateGradient(
- LayoutInvalidationReason::kSvgResourceInvalidated);
+ layout_invalidation_reason::kSvgResourceInvalidated);
}
});
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.h b/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.h
index 2e6116e01cc..0376e5dfd46 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.h
@@ -41,9 +41,7 @@ enum SVGSpreadMethodType {
kSVGSpreadMethodReflect,
kSVGSpreadMethodRepeat
};
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGSpreadMethodType>();
+DECLARE_SVG_ENUM_MAP(SVGSpreadMethodType);
class SVGGradientElement : public SVGElement, public SVGURIReference {
DEFINE_WRAPPERTYPEINFO();
@@ -97,8 +95,8 @@ class SVGGradientElement : public SVGElement, public SVGURIReference {
};
inline bool IsSVGGradientElement(const SVGElement& element) {
- return element.HasTagName(SVGNames::radialGradientTag) ||
- element.HasTagName(SVGNames::linearGradientTag);
+ return element.HasTagName(svg_names::kRadialGradientTag) ||
+ element.HasTagName(svg_names::kLinearGradientTag);
}
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGGradientElement);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.cc
index 288eed1fcb0..bfca480f88b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.cc
@@ -37,7 +37,7 @@ SVGGraphicsElement::SVGGraphicsElement(const QualifiedName& tag_name,
: SVGElement(tag_name, document, construction_type),
SVGTests(this),
transform_(SVGAnimatedTransformList::Create(this,
- SVGNames::transformAttr,
+ svg_names::kTransformAttr,
CSSPropertyTransform)) {
AddToPropertyMap(transform_);
}
@@ -103,7 +103,7 @@ void SVGGraphicsElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == SVGNames::transformAttr) {
+ if (name == svg_names::kTransformAttr) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyTransform, *transform_->CurrentValue()->CssValue());
return;
@@ -124,7 +124,7 @@ void SVGGraphicsElement::SvgAttributeChanged(const QualifiedName& attr_name) {
return;
}
- if (attr_name == SVGNames::transformAttr) {
+ if (attr_name == svg_names::kTransformAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
InvalidateSVGPresentationAttributeStyle();
// TODO(fs): The InvalidationGuard will make sure all instances are
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_image_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_image_element.cc
index 31cb70339bd..2556bfc7f2b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_image_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_image_element.cc
@@ -21,8 +21,9 @@
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/media/media_element_parser_helpers.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -34,32 +35,32 @@
namespace blink {
inline SVGImageElement::SVGImageElement(Document& document)
- : SVGGraphicsElement(SVGNames::imageTag, document),
+ : SVGGraphicsElement(svg_names::kImageTag, document),
SVGURIReference(this),
is_default_overridden_intrinsic_size_(false),
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyX)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyY)),
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyWidth)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyHeight)),
preserve_aspect_ratio_(SVGAnimatedPreserveAspectRatio::Create(
this,
- SVGNames::preserveAspectRatioAttr)),
+ svg_names::kPreserveAspectRatioAttr)),
image_loader_(SVGImageLoader::Create(this)) {
AddToPropertyMap(x_);
AddToPropertyMap(y_);
@@ -67,8 +68,8 @@ inline SVGImageElement::SVGImageElement(Document& document)
AddToPropertyMap(height_);
AddToPropertyMap(preserve_aspect_ratio_);
- if (MediaElementParserHelpers::IsMediaElement(this) &&
- !MediaElementParserHelpers::IsUnsizedMediaEnabled(document)) {
+ if (media_element_parser_helpers::IsMediaElement(this) &&
+ !document.IsFeatureEnabled(mojom::FeaturePolicyFeature::kUnsizedMedia)) {
is_default_overridden_intrinsic_size_ = true;
overridden_intrinsic_size_ =
IntSize(LayoutReplaced::kDefaultWidth, LayoutReplaced::kDefaultHeight);
@@ -131,10 +132,10 @@ void SVGImageElement::CollectStyleForPresentationAttribute(
void SVGImageElement::SvgAttributeChanged(const QualifiedName& attr_name) {
bool is_length_attribute =
- attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr;
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr;
- if (is_length_attribute || attr_name == SVGNames::preserveAspectRatioAttr) {
+ if (is_length_attribute || attr_name == svg_names::kPreserveAspectRatioAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
if (is_length_attribute) {
@@ -168,15 +169,15 @@ void SVGImageElement::SvgAttributeChanged(const QualifiedName& attr_name) {
void SVGImageElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == SVGNames::decodingAttr) {
+ if (params.name == svg_names::kDecodingAttr) {
UseCounter::Count(GetDocument(), WebFeature::kImageDecodingAttribute);
decoding_mode_ = ParseImageDecodingMode(params.new_value);
- } else if (params.name == SVGNames::intrinsicsizeAttr &&
+ } else if (params.name == svg_names::kIntrinsicsizeAttr &&
RuntimeEnabledFeatures::
ExperimentalProductivityFeaturesEnabled()) {
String message;
bool intrinsic_size_changed =
- MediaElementParserHelpers::ParseIntrinsicSizeAttribute(
+ media_element_parser_helpers::ParseIntrinsicSizeAttribute(
params.new_value, this, &overridden_intrinsic_size_,
&is_default_overridden_intrinsic_size_, &message);
if (!message.IsEmpty()) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_image_element.h b/chromium/third_party/blink/renderer/core/svg/svg_image_element.h
index 711256cc38c..333eb0dd6a3 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_image_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_image_element.h
@@ -73,6 +73,10 @@ class CORE_EXPORT SVGImageElement final
return is_default_overridden_intrinsic_size_;
}
+ void SetImageForTest(ImageResourceContent* content) {
+ GetImageLoader().SetImageForTest(content);
+ }
+
private:
explicit SVGImageElement(Document&);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_image_loader.cc b/chromium/third_party/blink/renderer/core/svg/svg_image_loader.cc
index a7ce9fe9322..ed5b0f33c40 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_image_loader.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_image_loader.cc
@@ -29,7 +29,7 @@ SVGImageLoader::SVGImageLoader(SVGImageElement* node) : ImageLoader(node) {}
void SVGImageLoader::DispatchLoadEvent() {
if (GetContent()->ErrorOccurred()) {
- GetElement()->DispatchEvent(*Event::Create(EventTypeNames::error));
+ GetElement()->DispatchEvent(*Event::Create(event_type_names::kError));
} else {
SVGImageElement* image_element = ToSVGImageElement(GetElement());
image_element->SendSVGLoadEventToSelfAndAncestorChainIfPossible();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_image_loader.h b/chromium/third_party/blink/renderer/core/svg/svg_image_loader.h
index ef8ab6ba358..3b1381140e0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_image_loader.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_image_loader.h
@@ -29,11 +29,12 @@ class SVGImageElement;
class SVGImageLoader final : public ImageLoader {
public:
static SVGImageLoader* Create(SVGImageElement* element) {
- return new SVGImageLoader(element);
+ return MakeGarbageCollected<SVGImageLoader>(element);
}
- private:
explicit SVGImageLoader(SVGImageElement*);
+
+ private:
void DispatchLoadEvent() override;
String DebugName() const override { return "SVGImageLoader"; }
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_integer.cc b/chromium/third_party/blink/renderer/core/svg/svg_integer.cc
index e8f277eff7c..a160403c146 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_integer.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_integer.cc
@@ -79,7 +79,7 @@ void SVGInteger::CalculateAnimatedValue(SVGAnimationElement* animation_element,
animation_element->AnimateAdditiveNumber(
percentage, repeat_count, from_integer->Value(), to_integer->Value(),
to_at_end_of_duration_integer->Value(), animated_float);
- value_ = static_cast<int>(roundf(animated_float));
+ value_ = clampTo<int>(roundf(animated_float));
}
float SVGInteger::CalculateDistance(SVGPropertyBase* other, SVGElement*) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_integer.h b/chromium/third_party/blink/renderer/core/svg/svg_integer.h
index 2abffc47da1..0b4e7338c10 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_integer.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_integer.h
@@ -41,7 +41,11 @@ class SVGInteger final : public SVGPropertyHelper<SVGInteger> {
typedef void TearOffType;
typedef int PrimitiveType;
- static SVGInteger* Create(int value = 0) { return new SVGInteger(value); }
+ static SVGInteger* Create(int value = 0) {
+ return MakeGarbageCollected<SVGInteger>(value);
+ }
+
+ explicit SVGInteger(int);
virtual SVGInteger* Clone() const;
@@ -68,8 +72,6 @@ class SVGInteger final : public SVGPropertyHelper<SVGInteger> {
static constexpr int kInitialValueBits = 2;
protected:
- explicit SVGInteger(int);
-
int value_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_integer_optional_integer.h b/chromium/third_party/blink/renderer/core/svg/svg_integer_optional_integer.h
index 2caaf582355..50acdcdfed2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_integer_optional_integer.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_integer_optional_integer.h
@@ -45,9 +45,13 @@ class SVGIntegerOptionalInteger final : public SVGPropertyBase {
static SVGIntegerOptionalInteger* Create(SVGInteger* first_integer,
SVGInteger* second_integer) {
- return new SVGIntegerOptionalInteger(first_integer, second_integer);
+ return MakeGarbageCollected<SVGIntegerOptionalInteger>(first_integer,
+ second_integer);
}
+ SVGIntegerOptionalInteger(SVGInteger* first_integer,
+ SVGInteger* second_integer);
+
SVGIntegerOptionalInteger* Clone() const;
SVGPropertyBase* CloneForAnimation(const String&) const override;
@@ -78,9 +82,6 @@ class SVGIntegerOptionalInteger final : public SVGPropertyBase {
void Trace(blink::Visitor*) override;
protected:
- SVGIntegerOptionalInteger(SVGInteger* first_integer,
- SVGInteger* second_integer);
-
Member<SVGInteger> first_integer_;
Member<SVGInteger> second_integer_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length.cc b/chromium/third_party/blink/renderer/core/svg/svg_length.cc
index 8a82679b154..1297ba1791c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length.cc
@@ -51,7 +51,7 @@ void SVGLength::Trace(blink::Visitor* visitor) {
}
SVGLength* SVGLength::Clone() const {
- return new SVGLength(*this);
+ return MakeGarbageCollected<SVGLength>(*this);
}
SVGPropertyBase* SVGLength::CloneForAnimation(const String& value) const {
@@ -191,30 +191,30 @@ SVGLengthMode SVGLength::LengthModeForAnimatedLengthAttribute(
DEFINE_STATIC_LOCAL(LengthModeForLengthAttributeMap, length_mode_map, ());
if (length_mode_map.IsEmpty()) {
- length_mode_map.Set(SVGNames::xAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::yAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::cxAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::cyAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::dxAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::dyAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::frAttr, SVGLengthMode::kOther);
- length_mode_map.Set(SVGNames::fxAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::fyAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::rAttr, SVGLengthMode::kOther);
- length_mode_map.Set(SVGNames::rxAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::ryAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::widthAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::heightAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::x1Attr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::x2Attr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::y1Attr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::y2Attr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::refXAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::refYAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::markerWidthAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::markerHeightAttr, SVGLengthMode::kHeight);
- length_mode_map.Set(SVGNames::textLengthAttr, SVGLengthMode::kWidth);
- length_mode_map.Set(SVGNames::startOffsetAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kXAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kYAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kCxAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kCyAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kDxAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kDyAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kFrAttr, SVGLengthMode::kOther);
+ length_mode_map.Set(svg_names::kFxAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kFyAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kRAttr, SVGLengthMode::kOther);
+ length_mode_map.Set(svg_names::kRxAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kRyAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kWidthAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kHeightAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kX1Attr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kX2Attr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kY1Attr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kY2Attr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kRefXAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kRefYAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kMarkerWidthAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kMarkerHeightAttr, SVGLengthMode::kHeight);
+ length_mode_map.Set(svg_names::kTextLengthAttr, SVGLengthMode::kWidth);
+ length_mode_map.Set(svg_names::kStartOffsetAttr, SVGLengthMode::kWidth);
}
if (length_mode_map.Contains(attr_name))
@@ -228,9 +228,10 @@ bool SVGLength::NegativeValuesForbiddenForAnimatedLengthAttribute(
DEFINE_STATIC_LOCAL(
HashSet<QualifiedName>, no_negative_values_set,
({
- SVGNames::frAttr, SVGNames::rAttr, SVGNames::rxAttr, SVGNames::ryAttr,
- SVGNames::widthAttr, SVGNames::heightAttr, SVGNames::markerWidthAttr,
- SVGNames::markerHeightAttr, SVGNames::textLengthAttr,
+ svg_names::kFrAttr, svg_names::kRAttr, svg_names::kRxAttr,
+ svg_names::kRyAttr, svg_names::kWidthAttr, svg_names::kHeightAttr,
+ svg_names::kMarkerWidthAttr, svg_names::kMarkerHeightAttr,
+ svg_names::kTextLengthAttr,
}));
return no_negative_values_set.Contains(attr_name);
}
@@ -326,7 +327,7 @@ const CSSPrimitiveValue& CreateInitialCSSValue(
} // namespace
SVGLength* SVGLength::Create(Initial initial, SVGLengthMode mode) {
- return new SVGLength(CreateInitialCSSValue(initial), mode);
+ return MakeGarbageCollected<SVGLength>(CreateInitialCSSValue(initial), mode);
}
void SVGLength::SetInitial(unsigned initial_value) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length.h b/chromium/third_party/blink/renderer/core/svg/svg_length.h
index c757faa1bab..27b03f6a3f9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length.h
@@ -38,7 +38,7 @@ class SVGLength final : public SVGPropertyBase {
typedef SVGLengthTearOff TearOffType;
static SVGLength* Create(SVGLengthMode mode = SVGLengthMode::kOther) {
- return new SVGLength(mode);
+ return MakeGarbageCollected<SVGLength>(mode);
}
// Initial values for SVGLength properties. If adding a new initial value,
@@ -56,6 +56,11 @@ class SVGLength final : public SVGPropertyBase {
};
static constexpr int kInitialValueBits = 3;
static SVGLength* Create(Initial, SVGLengthMode);
+
+ explicit SVGLength(SVGLengthMode);
+ SVGLength(const CSSPrimitiveValue&, SVGLengthMode);
+ SVGLength(const SVGLength&);
+
void SetInitial(unsigned);
void Trace(blink::Visitor*) override;
@@ -133,10 +138,6 @@ class SVGLength final : public SVGPropertyBase {
AnimatedPropertyType GetType() const override { return ClassType(); }
private:
- explicit SVGLength(SVGLengthMode);
- SVGLength(const CSSPrimitiveValue&, SVGLengthMode);
- SVGLength(const SVGLength&);
-
Member<const CSSPrimitiveValue> value_;
unsigned unit_mode_ : 2;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_context.cc b/chromium/third_party/blink/renderer/core/svg/svg_length_context.cc
index ae0f267f3ea..06d9526f952 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_context.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_context.cc
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
#include "third_party/blink/renderer/platform/fonts/font_metrics.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_context.h b/chromium/third_party/blink/renderer/core/svg/svg_length_context.h
index 920e8426866..ba97426dd50 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_context.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_context.h
@@ -23,7 +23,7 @@
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/svg/svg_unit_types.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_list.h b/chromium/third_party/blink/renderer/core/svg/svg_length_list.h
index 8fe98b4edcc..e83176244b0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_list.h
@@ -45,9 +45,10 @@ class SVGLengthList final
typedef SVGLengthListTearOff TearOffType;
static SVGLengthList* Create(SVGLengthMode mode = SVGLengthMode::kOther) {
- return new SVGLengthList(mode);
+ return MakeGarbageCollected<SVGLengthList>(mode);
}
+ explicit SVGLengthList(SVGLengthMode);
~SVGLengthList() override;
SVGParsingError SetValueAsString(const String&);
@@ -72,8 +73,6 @@ class SVGLengthList final
AnimatedPropertyType GetType() const override { return ClassType(); }
private:
- explicit SVGLengthList(SVGLengthMode);
-
// Create SVGLength items used to adjust the list length
// when animation from/to lists are longer than this list.
SVGLength* CreatePaddingItem() const override;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_list_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_length_list_tear_off.h
index cd50f249b38..fac130c0fec 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_list_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_list_tear_off.h
@@ -45,10 +45,10 @@ class SVGLengthListTearOff final
SVGLengthList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGLengthListTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGLengthListTearOff>(target, binding,
+ property_is_anim_val);
}
- private:
SVGLengthListTearOff(SVGLengthList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.h
index 0181b86b45d..95f39325f3d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.h
@@ -58,10 +58,15 @@ class SVGLengthTearOff final : public SVGPropertyTearOff<SVGLength> {
static SVGLengthTearOff* Create(SVGLength* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGLengthTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGLengthTearOff>(target, binding,
+ property_is_anim_val);
}
static SVGLengthTearOff* CreateDetached();
+ SVGLengthTearOff(SVGLength*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
+
unsigned short unitType();
SVGLengthMode UnitMode();
float value(ExceptionState&);
@@ -76,11 +81,6 @@ class SVGLengthTearOff final : public SVGPropertyTearOff<SVGLength> {
void convertToSpecifiedUnits(unsigned short unit_type, ExceptionState&);
bool HasExposedLengthUnit();
-
- private:
- SVGLengthTearOff(SVGLength*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_line_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_line_element.cc
index 056d4ff06dd..b7bd1435de4 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_line_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_line_element.cc
@@ -26,21 +26,21 @@
namespace blink {
inline SVGLineElement::SVGLineElement(Document& document)
- : SVGGeometryElement(SVGNames::lineTag, document),
+ : SVGGeometryElement(svg_names::kLineTag, document),
x1_(SVGAnimatedLength::Create(this,
- SVGNames::x1Attr,
+ svg_names::kX1Attr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
y1_(SVGAnimatedLength::Create(this,
- SVGNames::y1Attr,
+ svg_names::kY1Attr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero)),
x2_(SVGAnimatedLength::Create(this,
- SVGNames::x2Attr,
+ svg_names::kX2Attr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
y2_(SVGAnimatedLength::Create(this,
- SVGNames::y2Attr,
+ svg_names::kY2Attr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero)) {
AddToPropertyMap(x1_);
@@ -72,8 +72,8 @@ Path SVGLineElement::AsPath() const {
}
void SVGLineElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::x1Attr || attr_name == SVGNames::y1Attr ||
- attr_name == SVGNames::x2Attr || attr_name == SVGNames::y2Attr) {
+ if (attr_name == svg_names::kX1Attr || attr_name == svg_names::kY1Attr ||
+ attr_name == svg_names::kX2Attr || attr_name == svg_names::kY2Attr) {
UpdateRelativeLengthsInformation();
GeometryAttributeChanged();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.cc
index 80a243db1e7..2345cb111cd 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.cc
@@ -30,25 +30,25 @@
namespace blink {
inline SVGLinearGradientElement::SVGLinearGradientElement(Document& document)
- : SVGGradientElement(SVGNames::linearGradientTag, document),
+ : SVGGradientElement(svg_names::kLinearGradientTag, document),
// Spec: If the x1|y1|y2 attribute is not specified, the effect is as if a
// value of "0%" were specified.
// Spec: If the x2 attribute is not specified, the effect is as if a value
// of "100%" were specified.
x1_(SVGAnimatedLength::Create(this,
- SVGNames::x1Attr,
+ svg_names::kX1Attr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent0)),
y1_(SVGAnimatedLength::Create(this,
- SVGNames::y1Attr,
+ svg_names::kY1Attr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent0)),
x2_(SVGAnimatedLength::Create(this,
- SVGNames::x2Attr,
+ svg_names::kX2Attr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent100)),
y2_(SVGAnimatedLength::Create(this,
- SVGNames::y2Attr,
+ svg_names::kY2Attr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent0)) {
AddToPropertyMap(x1_);
@@ -69,11 +69,11 @@ DEFINE_NODE_FACTORY(SVGLinearGradientElement)
void SVGLinearGradientElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::x1Attr || attr_name == SVGNames::x2Attr ||
- attr_name == SVGNames::y1Attr || attr_name == SVGNames::y2Attr) {
+ if (attr_name == svg_names::kX1Attr || attr_name == svg_names::kX2Attr ||
+ attr_name == svg_names::kY1Attr || attr_name == svg_names::kY2Attr) {
SVGElement::InvalidationGuard invalidation_guard(this);
UpdateRelativeLengthsInformation();
- InvalidateGradient(LayoutInvalidationReason::kAttributeChanged);
+ InvalidateGradient(layout_invalidation_reason::kAttributeChanged);
return;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_marker_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_marker_element.cc
index f4968f96318..e4675e246c8 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_marker_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_marker_element.cc
@@ -24,48 +24,46 @@
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_marker.h"
#include "third_party/blink/renderer/core/svg/svg_angle_tear_off.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGMarkerUnitsType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(
- std::make_pair(kSVGMarkerUnitsUserSpaceOnUse, "userSpaceOnUse"));
- entries.push_back(
- std::make_pair(kSVGMarkerUnitsStrokeWidth, "strokeWidth"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGMarkerUnitsType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSVGMarkerUnitsUserSpaceOnUse, "userSpaceOnUse"},
+ {kSVGMarkerUnitsStrokeWidth, "strokeWidth"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
inline SVGMarkerElement::SVGMarkerElement(Document& document)
- : SVGElement(SVGNames::markerTag, document),
+ : SVGElement(svg_names::kMarkerTag, document),
SVGFitToViewBox(this),
ref_x_(SVGAnimatedLength::Create(this,
- SVGNames::refXAttr,
+ svg_names::kRefXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
ref_y_(SVGAnimatedLength::Create(this,
- SVGNames::refYAttr,
+ svg_names::kRefYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero)),
// Spec: If the markerWidth/markerHeight attribute is not specified, the
// effect is as if a value of "3" were specified.
marker_width_(SVGAnimatedLength::Create(this,
- SVGNames::markerWidthAttr,
+ svg_names::kMarkerWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kNumber3)),
marker_height_(SVGAnimatedLength::Create(this,
- SVGNames::markerHeightAttr,
+ svg_names::kMarkerHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kNumber3)),
orient_angle_(SVGAnimatedAngle::Create(this)),
marker_units_(SVGAnimatedEnumeration<SVGMarkerUnitsType>::Create(
this,
- SVGNames::markerUnitsAttr,
+ svg_names::kMarkerUnitsAttr,
kSVGMarkerUnitsStrokeWidth)) {
AddToPropertyMap(ref_x_);
AddToPropertyMap(ref_y_);
@@ -98,16 +96,16 @@ AffineTransform SVGMarkerElement::ViewBoxToViewTransform(
void SVGMarkerElement::SvgAttributeChanged(const QualifiedName& attr_name) {
bool viewbox_attribute_changed = SVGFitToViewBox::IsKnownAttribute(attr_name);
- bool length_attribute_changed = attr_name == SVGNames::refXAttr ||
- attr_name == SVGNames::refYAttr ||
- attr_name == SVGNames::markerWidthAttr ||
- attr_name == SVGNames::markerHeightAttr;
+ bool length_attribute_changed = attr_name == svg_names::kRefXAttr ||
+ attr_name == svg_names::kRefYAttr ||
+ attr_name == svg_names::kMarkerWidthAttr ||
+ attr_name == svg_names::kMarkerHeightAttr;
if (length_attribute_changed)
UpdateRelativeLengthsInformation();
if (viewbox_attribute_changed || length_attribute_changed ||
- attr_name == SVGNames::markerUnitsAttr ||
- attr_name == SVGNames::orientAttr) {
+ attr_name == svg_names::kMarkerUnitsAttr ||
+ attr_name == svg_names::kOrientAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
auto* resource_container = ToLayoutSVGResourceContainer(GetLayoutObject());
if (resource_container) {
@@ -130,19 +128,20 @@ void SVGMarkerElement::ChildrenChanged(const ChildrenChange& change) {
if (change.by_parser)
return;
- if (LayoutObject* object = GetLayoutObject())
+ if (LayoutObject* object = GetLayoutObject()) {
object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kChildChanged);
+ layout_invalidation_reason::kChildChanged);
+ }
}
void SVGMarkerElement::setOrientToAuto() {
- setAttribute(SVGNames::orientAttr, "auto");
+ setAttribute(svg_names::kOrientAttr, "auto");
}
void SVGMarkerElement::setOrientToAngle(SVGAngleTearOff* angle) {
DCHECK(angle);
SVGAngle* target = angle->Target();
- setAttribute(SVGNames::orientAttr, AtomicString(target->ValueAsString()));
+ setAttribute(svg_names::kOrientAttr, AtomicString(target->ValueAsString()));
}
LayoutObject* SVGMarkerElement::CreateLayoutObject(const ComputedStyle&) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_marker_element.h b/chromium/third_party/blink/renderer/core/svg/svg_marker_element.h
index 453f1ab7ee9..e667e9f152e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_marker_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_marker_element.h
@@ -36,8 +36,7 @@ enum SVGMarkerUnitsType {
kSVGMarkerUnitsUserSpaceOnUse,
kSVGMarkerUnitsStrokeWidth
};
-template <>
-const SVGEnumerationStringEntries& GetStaticStringEntries<SVGMarkerUnitsType>();
+DECLARE_SVG_ENUM_MAP(SVGMarkerUnitsType);
class SVGMarkerElement final : public SVGElement, public SVGFitToViewBox {
DEFINE_WRAPPERTYPEINFO();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_mask_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_mask_element.cc
index 0d6cd764251..cac840f1d9d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_mask_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_mask_element.cc
@@ -29,40 +29,40 @@
namespace blink {
inline SVGMaskElement::SVGMaskElement(Document& document)
- : SVGElement(SVGNames::maskTag, document),
+ : SVGElement(svg_names::kMaskTag, document),
SVGTests(this),
// Spec: If the x/y attribute is not specified, the effect is as if a
// value of "-10%" were specified.
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercentMinus10,
CSSPropertyX)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercentMinus10,
CSSPropertyY)),
// Spec: If the width/height attribute is not specified, the effect is as
// if a value of "120%" were specified.
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent120,
CSSPropertyWidth)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent120,
CSSPropertyHeight)),
mask_units_(SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::maskUnitsAttr,
+ svg_names::kMaskUnitsAttr,
SVGUnitTypes::kSvgUnitTypeObjectboundingbox)),
mask_content_units_(
SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::maskContentUnitsAttr,
+ svg_names::kMaskContentUnitsAttr,
SVGUnitTypes::kSvgUnitTypeUserspaceonuse)) {
AddToPropertyMap(x_);
AddToPropertyMap(y_);
@@ -109,11 +109,11 @@ void SVGMaskElement::CollectStyleForPresentationAttribute(
void SVGMaskElement::SvgAttributeChanged(const QualifiedName& attr_name) {
bool is_length_attr =
- attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr;
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr;
- if (is_length_attr || attr_name == SVGNames::maskUnitsAttr ||
- attr_name == SVGNames::maskContentUnitsAttr ||
+ if (is_length_attr || attr_name == svg_names::kMaskUnitsAttr ||
+ attr_name == svg_names::kMaskContentUnitsAttr ||
SVGTests::IsKnownAttribute(attr_name)) {
SVGElement::InvalidationGuard invalidation_guard(this);
@@ -142,9 +142,10 @@ void SVGMaskElement::ChildrenChanged(const ChildrenChange& change) {
if (change.by_parser)
return;
- if (LayoutObject* object = GetLayoutObject())
+ if (LayoutObject* object = GetLayoutObject()) {
object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kChildChanged);
+ layout_invalidation_reason::kChildChanged);
+ }
}
LayoutObject* SVGMaskElement::CreateLayoutObject(const ComputedStyle&) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h
index aa78ee20ee0..8c735691f30 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_matrix_tear_off.h
@@ -51,13 +51,16 @@ class CORE_EXPORT SVGMatrixTearOff final : public ScriptWrappable {
public:
static SVGMatrixTearOff* Create(const AffineTransform& value) {
- return new SVGMatrixTearOff(value);
+ return MakeGarbageCollected<SVGMatrixTearOff>(value);
}
static SVGMatrixTearOff* Create(SVGTransformTearOff* target) {
- return new SVGMatrixTearOff(target);
+ return MakeGarbageCollected<SVGMatrixTearOff>(target);
}
+ explicit SVGMatrixTearOff(const AffineTransform&);
+ explicit SVGMatrixTearOff(SVGTransformTearOff*);
+
double a() { return Value().A(); }
double b() { return Value().B(); }
double c() { return Value().C(); }
@@ -91,9 +94,6 @@ class CORE_EXPORT SVGMatrixTearOff final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit SVGMatrixTearOff(const AffineTransform&);
- explicit SVGMatrixTearOff(SVGTransformTearOff*);
-
AffineTransform* MutableValue();
void CommitChange();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.cc
index 6caa0d60709..0fd9920e170 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.cc
@@ -25,7 +25,7 @@
namespace blink {
inline SVGMetadataElement::SVGMetadataElement(Document& document)
- : SVGElement(SVGNames::metadataTag, document) {}
+ : SVGElement(svg_names::kMetadataTag, document) {}
DEFINE_NODE_FACTORY(SVGMetadataElement)
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.cc
index 8256e3f48f1..b49d09d5f5c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.cc
@@ -28,8 +28,7 @@
namespace blink {
inline SVGMPathElement::SVGMPathElement(Document& document)
- : SVGElement(SVGNames::mpathTag, document), SVGURIReference(this) {
- DCHECK(RuntimeEnabledFeatures::SMILEnabled());
+ : SVGElement(svg_names::kMPathTag, document), SVGURIReference(this) {
}
void SVGMPathElement::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.idl
index c3933b2b691..7889bbb94ff 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.idl
@@ -25,7 +25,6 @@
// https://svgwg.org/specs/animations/#InterfaceSVGMPathElement
-[RuntimeEnabled=SMIL]
interface SVGMPathElement : SVGElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number.h b/chromium/third_party/blink/renderer/core/svg/svg_number.h
index 7cb5255ad9e..efd281a268c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number.h
@@ -44,7 +44,11 @@ class SVGNumber : public SVGPropertyHelper<SVGNumber> {
typedef SVGNumberTearOff TearOffType;
typedef float PrimitiveType;
- static SVGNumber* Create(float value = 0.0f) { return new SVGNumber(value); }
+ static SVGNumber* Create(float value = 0.0f) {
+ return MakeGarbageCollected<SVGNumber>(value);
+ }
+
+ explicit SVGNumber(float);
virtual SVGNumber* Clone() const;
@@ -71,8 +75,6 @@ class SVGNumber : public SVGPropertyHelper<SVGNumber> {
static constexpr int kInitialValueBits = 2;
protected:
- explicit SVGNumber(float);
-
template <typename CharType>
SVGParsingError Parse(const CharType*& ptr, const CharType* end);
@@ -88,14 +90,13 @@ DEFINE_SVG_PROPERTY_TYPE_CASTS(SVGNumber);
class SVGNumberAcceptPercentage final : public SVGNumber {
public:
static SVGNumberAcceptPercentage* Create(float value = 0) {
- return new SVGNumberAcceptPercentage(value);
+ return MakeGarbageCollected<SVGNumberAcceptPercentage>(value);
}
+ explicit SVGNumberAcceptPercentage(float);
+
SVGNumber* Clone() const override;
SVGParsingError SetValueAsString(const String&) override;
-
- private:
- explicit SVGNumberAcceptPercentage(float);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number_list.h b/chromium/third_party/blink/renderer/core/svg/svg_number_list.h
index ebf00bd2303..ca3c6c4332f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number_list.h
@@ -44,8 +44,11 @@ class SVGNumberList final
public:
typedef SVGNumberListTearOff TearOffType;
- static SVGNumberList* Create() { return new SVGNumberList(); }
+ static SVGNumberList* Create() {
+ return MakeGarbageCollected<SVGNumberList>();
+ }
+ SVGNumberList();
~SVGNumberList() override;
SVGParsingError SetValueAsString(const String&);
@@ -69,8 +72,6 @@ class SVGNumberList final
Vector<float> ToFloatVector() const;
private:
- SVGNumberList();
-
template <typename CharType>
SVGParsingError Parse(const CharType*& ptr, const CharType* end);
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number_list_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_number_list_tear_off.h
index dab0a184dd6..7e5878f3596 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number_list_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number_list_tear_off.h
@@ -45,10 +45,10 @@ class SVGNumberListTearOff final
SVGNumberList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGNumberListTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGNumberListTearOff>(target, binding,
+ property_is_anim_val);
}
- private:
SVGNumberListTearOff(SVGNumberList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number_optional_number.h b/chromium/third_party/blink/renderer/core/svg/svg_number_optional_number.h
index 07f8e51f55c..5224a522648 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number_optional_number.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number_optional_number.h
@@ -45,9 +45,12 @@ class SVGNumberOptionalNumber final : public SVGPropertyBase {
static SVGNumberOptionalNumber* Create(SVGNumber* first_number,
SVGNumber* second_number) {
- return new SVGNumberOptionalNumber(first_number, second_number);
+ return MakeGarbageCollected<SVGNumberOptionalNumber>(first_number,
+ second_number);
}
+ SVGNumberOptionalNumber(SVGNumber* first_number, SVGNumber* second_number);
+
SVGNumberOptionalNumber* Clone() const;
SVGPropertyBase* CloneForAnimation(const String&) const override;
@@ -78,8 +81,6 @@ class SVGNumberOptionalNumber final : public SVGPropertyBase {
void Trace(blink::Visitor*) override;
protected:
- SVGNumberOptionalNumber(SVGNumber* first_number, SVGNumber* second_number);
-
Member<SVGNumber> first_number_;
Member<SVGNumber> second_number_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_number_tear_off.h
index cdc90fcb7f6..7748b332636 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number_tear_off.h
@@ -43,17 +43,17 @@ class SVGNumberTearOff : public SVGPropertyTearOff<SVGNumber> {
static SVGNumberTearOff* Create(SVGNumber* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGNumberTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGNumberTearOff>(target, binding,
+ property_is_anim_val);
}
static SVGNumberTearOff* CreateDetached();
- void setValue(float, ExceptionState&);
- float value() { return Target()->Value(); }
-
- protected:
SVGNumberTearOff(SVGNumber*,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType);
+
+ void setValue(float, ExceptionState&);
+ float value() { return Target()->Value(); }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path.h b/chromium/third_party/blink/renderer/core/svg/svg_path.h
index c3b5d0aa0a8..696cc58d4a4 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path.h
@@ -42,11 +42,13 @@ class SVGPath final : public SVGPropertyBase {
public:
typedef void TearOffType;
- static SVGPath* Create() { return new SVGPath(); }
+ static SVGPath* Create() { return MakeGarbageCollected<SVGPath>(); }
static SVGPath* Create(cssvalue::CSSPathValue* path_value) {
- return new SVGPath(path_value);
+ return MakeGarbageCollected<SVGPath>(path_value);
}
+ SVGPath();
+ explicit SVGPath(cssvalue::CSSPathValue*);
~SVGPath() override;
const SVGPathByteStream& ByteStream() const {
@@ -77,9 +79,6 @@ class SVGPath final : public SVGPropertyBase {
void Trace(blink::Visitor*) override;
private:
- SVGPath();
- explicit SVGPath(cssvalue::CSSPathValue*);
-
Member<cssvalue::CSSPathValue> path_value_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_path_element.cc
index 1f96415490b..6b8cffd0da8 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_element.cc
@@ -29,8 +29,8 @@
namespace blink {
inline SVGPathElement::SVGPathElement(Document& document)
- : SVGGeometryElement(SVGNames::pathTag, document),
- path_(SVGAnimatedPath::Create(this, SVGNames::dAttr, CSSPropertyD)) {
+ : SVGGeometryElement(svg_names::kPathTag, document),
+ path_(SVGAnimatedPath::Create(this, svg_names::kDAttr, CSSPropertyD)) {
AddToPropertyMap(path_);
}
@@ -83,7 +83,7 @@ SVGPointTearOff* SVGPathElement::getPointAtLength(float length) {
}
void SVGPathElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::dAttr) {
+ if (attr_name == svg_names::kDAttr) {
InvalidateMPathDependencies();
GeometryPresentationAttributeChanged(attr_name);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_parser.h b/chromium/third_party/blink/renderer/core/svg/svg_path_parser.h
index b8cc12131be..32191f188d1 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_parser.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_parser.h
@@ -33,7 +33,7 @@ namespace blink {
class SVGPathConsumer;
-namespace SVGPathParser {
+namespace svg_path_parser {
template <typename SourceType, typename ConsumerType>
inline bool ParsePath(SourceType& source, ConsumerType& consumer) {
@@ -47,7 +47,7 @@ inline bool ParsePath(SourceType& source, ConsumerType& consumer) {
return true;
}
-} // namespace SVGPathParser
+} // namespace svg_path_parser
class SVGPathNormalizer {
STACK_ALLOCATED();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_parser_test.cc b/chromium/third_party/blink/renderer/core/svg/svg_path_parser_test.cc
index f4c64252802..231dbe7d212 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_parser_test.cc
@@ -16,7 +16,7 @@ bool ParsePath(const char* input, String& output) {
String input_string(input);
SVGPathStringSource source(input_string);
SVGPathStringBuilder builder;
- bool had_error = SVGPathParser::ParsePath(source, builder);
+ bool had_error = svg_path_parser::ParsePath(source, builder);
output = builder.Result();
// Coerce a null result to empty.
if (output.IsNull())
@@ -160,7 +160,7 @@ SVGParsingError ParsePathWithError(const char* input) {
String input_string(input);
SVGPathStringSource source(input_string);
SVGPathStringBuilder builder;
- SVGPathParser::ParsePath(source, builder);
+ svg_path_parser::ParsePath(source, builder);
return source.ParseError();
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.cc b/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.cc
index 223f7801ca5..befbe62ddcc 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.cc
@@ -26,12 +26,12 @@
namespace blink {
SVGPathStringSource::SVGPathStringSource(const String& string)
- : is8_bit_source_(string.Is8Bit()),
+ : is_8bit_source_(string.Is8Bit()),
previous_command_(kPathSegUnknown),
string_(string) {
DCHECK(!string.IsNull());
- if (is8_bit_source_) {
+ if (is_8bit_source_) {
current_.character8_ = string.Characters8();
end_.character8_ = current_.character8_ + string.length();
} else {
@@ -42,7 +42,7 @@ SVGPathStringSource::SVGPathStringSource(const String& string)
}
void SVGPathStringSource::EatWhitespace() {
- if (is8_bit_source_)
+ if (is_8bit_source_)
SkipOptionalSVGSpaces(current_.character8_, end_.character8_);
else
SkipOptionalSVGSpaces(current_.character16_, end_.character16_);
@@ -124,7 +124,7 @@ static bool MaybeImplicitCommand(unsigned lookahead,
void SVGPathStringSource::SetErrorMark(SVGParseStatus status) {
if (error_.Status() != SVGParseStatus::kNoError)
return;
- size_t locus = is8_bit_source_
+ size_t locus = is_8bit_source_
? current_.character8_ - string_.Characters8()
: current_.character16_ - string_.Characters16();
error_ = SVGParsingError(status, locus);
@@ -133,7 +133,7 @@ void SVGPathStringSource::SetErrorMark(SVGParseStatus status) {
float SVGPathStringSource::ParseNumberWithError() {
float number_value = 0;
bool error;
- if (is8_bit_source_)
+ if (is_8bit_source_)
error = !ParseNumber(current_.character8_, end_.character8_, number_value);
else
error =
@@ -146,7 +146,7 @@ float SVGPathStringSource::ParseNumberWithError() {
bool SVGPathStringSource::ParseArcFlagWithError() {
bool flag_value = false;
bool error;
- if (is8_bit_source_)
+ if (is_8bit_source_)
error = !ParseArcFlag(current_.character8_, end_.character8_, flag_value);
else
error = !ParseArcFlag(current_.character16_, end_.character16_, flag_value);
@@ -159,7 +159,7 @@ PathSegmentData SVGPathStringSource::ParseSegment() {
DCHECK(HasMoreData());
PathSegmentData segment;
unsigned lookahead =
- is8_bit_source_ ? *current_.character8_ : *current_.character16_;
+ is_8bit_source_ ? *current_.character8_ : *current_.character16_;
SVGPathSegType command = MapLetterToSegmentType(lookahead);
if (UNLIKELY(previous_command_ == kPathSegUnknown)) {
// First command has to be a moveto.
@@ -168,7 +168,7 @@ PathSegmentData SVGPathStringSource::ParseSegment() {
return segment;
}
// Consume command letter.
- if (is8_bit_source_)
+ if (is_8bit_source_)
current_.character8_++;
else
current_.character16_++;
@@ -181,7 +181,7 @@ PathSegmentData SVGPathStringSource::ParseSegment() {
}
} else {
// Valid explicit command.
- if (is8_bit_source_)
+ if (is_8bit_source_)
current_.character8_++;
else
current_.character16_++;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.h b/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.h
index a20acbe5463..ba18f114c6f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_string_source.h
@@ -36,7 +36,7 @@ class CORE_EXPORT SVGPathStringSource {
explicit SVGPathStringSource(const String&);
bool HasMoreData() const {
- if (is8_bit_source_)
+ if (is_8bit_source_)
return current_.character8_ < end_.character8_;
return current_.character16_ < end_.character16_;
}
@@ -50,7 +50,7 @@ class CORE_EXPORT SVGPathStringSource {
bool ParseArcFlagWithError();
void SetErrorMark(SVGParseStatus);
- bool is8_bit_source_;
+ bool is_8bit_source_;
union {
const LChar* character8_;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_utilities.cc b/chromium/third_party/blink/renderer/core/svg/svg_path_utilities.cc
index 4fb92cd2d88..37e46ea7d10 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_utilities.cc
@@ -34,7 +34,7 @@ bool BuildPathFromString(const String& d, Path& result) {
SVGPathBuilder builder(result);
SVGPathStringSource source(d);
- return SVGPathParser::ParsePath(source, builder);
+ return svg_path_parser::ParsePath(source, builder);
}
bool BuildPathFromByteStream(const SVGPathByteStream& stream, Path& result) {
@@ -43,7 +43,7 @@ bool BuildPathFromByteStream(const SVGPathByteStream& stream, Path& result) {
SVGPathBuilder builder(result);
SVGPathByteStreamSource source(stream);
- return SVGPathParser::ParsePath(source, builder);
+ return svg_path_parser::ParsePath(source, builder);
}
String BuildStringFromByteStream(const SVGPathByteStream& stream,
@@ -55,9 +55,9 @@ String BuildStringFromByteStream(const SVGPathByteStream& stream,
SVGPathByteStreamSource source(stream);
if (format == kTransformToAbsolute) {
SVGPathAbsolutizer absolutizer(&builder);
- SVGPathParser::ParsePath(source, absolutizer);
+ svg_path_parser::ParsePath(source, absolutizer);
} else {
- SVGPathParser::ParsePath(source, builder);
+ svg_path_parser::ParsePath(source, builder);
}
return builder.Result();
}
@@ -74,7 +74,7 @@ SVGParsingError BuildByteStreamFromString(const String& d,
SVGPathByteStreamBuilder builder(result);
SVGPathStringSource source(d);
- SVGPathParser::ParsePath(source, builder);
+ svg_path_parser::ParsePath(source, builder);
result.ShrinkToFit();
return source.ParseError();
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.cc
index 1ed75ec4aa9..c165ccb2a8a 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.cc
@@ -34,38 +34,38 @@
namespace blink {
inline SVGPatternElement::SVGPatternElement(Document& document)
- : SVGElement(SVGNames::patternTag, document),
+ : SVGElement(svg_names::kPatternTag, document),
SVGURIReference(this),
SVGTests(this),
SVGFitToViewBox(this),
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero)),
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero)),
pattern_transform_(
SVGAnimatedTransformList::Create(this,
- SVGNames::patternTransformAttr,
+ svg_names::kPatternTransformAttr,
CSSPropertyTransform)),
pattern_units_(SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::patternUnitsAttr,
+ svg_names::kPatternUnitsAttr,
SVGUnitTypes::kSvgUnitTypeObjectboundingbox)),
pattern_content_units_(
SVGAnimatedEnumeration<SVGUnitTypes::SVGUnitType>::Create(
this,
- SVGNames::patternContentUnitsAttr,
+ svg_names::kPatternContentUnitsAttr,
SVGUnitTypes::kSvgUnitTypeUserspaceonuse)) {
AddToPropertyMap(x_);
AddToPropertyMap(y_);
@@ -105,7 +105,7 @@ void SVGPatternElement::BuildPendingResource() {
if (resource_)
resource_->AddClient(EnsureSVGResourceClient());
- InvalidatePattern(LayoutInvalidationReason::kSvgResourceInvalidated);
+ InvalidatePattern(layout_invalidation_reason::kSvgResourceInvalidated);
if (auto* layout_object = GetLayoutObject())
SVGResourcesCache::ResourceReferenceChanged(*layout_object);
}
@@ -121,7 +121,7 @@ void SVGPatternElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name == SVGNames::patternTransformAttr) {
+ if (name == svg_names::kPatternTransformAttr) {
AddPropertyToPresentationAttributeStyle(
style, CSSPropertyTransform,
*pattern_transform_->CurrentValue()->CssValue());
@@ -132,18 +132,18 @@ void SVGPatternElement::CollectStyleForPresentationAttribute(
void SVGPatternElement::SvgAttributeChanged(const QualifiedName& attr_name) {
bool is_length_attr =
- attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr;
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr;
- if (attr_name == SVGNames::patternTransformAttr) {
+ if (attr_name == svg_names::kPatternTransformAttr) {
InvalidateSVGPresentationAttributeStyle();
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::FromAttribute(attr_name));
}
- if (is_length_attr || attr_name == SVGNames::patternUnitsAttr ||
- attr_name == SVGNames::patternContentUnitsAttr ||
- attr_name == SVGNames::patternTransformAttr ||
+ if (is_length_attr || attr_name == svg_names::kPatternUnitsAttr ||
+ attr_name == svg_names::kPatternContentUnitsAttr ||
+ attr_name == svg_names::kPatternTransformAttr ||
SVGFitToViewBox::IsKnownAttribute(attr_name) ||
SVGTests::IsKnownAttribute(attr_name)) {
SVGElement::InvalidationGuard invalidation_guard(this);
@@ -151,7 +151,7 @@ void SVGPatternElement::SvgAttributeChanged(const QualifiedName& attr_name) {
if (is_length_attr)
UpdateRelativeLengthsInformation();
- InvalidatePattern(LayoutInvalidationReason::kAttributeChanged);
+ InvalidatePattern(layout_invalidation_reason::kAttributeChanged);
return;
}
@@ -184,7 +184,7 @@ void SVGPatternElement::ChildrenChanged(const ChildrenChange& change) {
if (change.by_parser)
return;
- InvalidatePattern(LayoutInvalidationReason::kChildChanged);
+ InvalidatePattern(layout_invalidation_reason::kChildChanged);
}
void SVGPatternElement::InvalidatePattern(
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_point.h b/chromium/third_party/blink/renderer/core/svg/svg_point.h
index fc39e06ee5a..13c5246f692 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_point.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_point.h
@@ -44,12 +44,15 @@ class SVGPoint final : public SVGPropertyHelper<SVGPoint> {
public:
typedef SVGPointTearOff TearOffType;
- static SVGPoint* Create() { return new SVGPoint(); }
+ static SVGPoint* Create() { return MakeGarbageCollected<SVGPoint>(); }
static SVGPoint* Create(const FloatPoint& point) {
- return new SVGPoint(point);
+ return MakeGarbageCollected<SVGPoint>(point);
}
+ SVGPoint();
+ explicit SVGPoint(const FloatPoint&);
+
SVGPoint* Clone() const;
const FloatPoint& Value() const { return value_; }
@@ -79,9 +82,6 @@ class SVGPoint final : public SVGPropertyHelper<SVGPoint> {
static AnimatedPropertyType ClassType() { return kAnimatedPoint; }
private:
- SVGPoint();
- explicit SVGPoint(const FloatPoint&);
-
template <typename CharType>
SVGParsingError Parse(const CharType*& ptr, const CharType* end);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_point_list.h b/chromium/third_party/blink/renderer/core/svg/svg_point_list.h
index 98eae93939d..76a1973bc83 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_point_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_point_list.h
@@ -44,8 +44,9 @@ class SVGPointList final
public:
typedef SVGPointListTearOff TearOffType;
- static SVGPointList* Create() { return new SVGPointList(); }
+ static SVGPointList* Create() { return MakeGarbageCollected<SVGPointList>(); }
+ SVGPointList();
~SVGPointList() override;
SVGParsingError SetValueAsString(const String&);
@@ -67,8 +68,6 @@ class SVGPointList final
AnimatedPropertyType GetType() const override { return ClassType(); }
private:
- SVGPointList();
-
template <typename CharType>
SVGParsingError Parse(const CharType*& ptr, const CharType* end);
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_point_list_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_point_list_tear_off.h
index e29f06e308e..0dacaf36c61 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_point_list_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_point_list_tear_off.h
@@ -45,10 +45,10 @@ class SVGPointListTearOff final
SVGPointList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGPointListTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGPointListTearOff>(target, binding,
+ property_is_anim_val);
}
- private:
SVGPointListTearOff(SVGPointList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_point_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_point_tear_off.h
index 2caab949654..dcc63e148ff 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_point_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_point_tear_off.h
@@ -45,26 +45,26 @@ class SVGPointTearOff : public SVGPropertyTearOff<SVGPoint> {
static SVGPointTearOff* Create(SVGPoint* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGPointTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGPointTearOff>(target, binding,
+ property_is_anim_val);
}
static SVGPointTearOff* Create(SVGPoint* target,
SVGElement* context_element) {
- return new SVGPointTearOff(target, context_element);
+ return MakeGarbageCollected<SVGPointTearOff>(target, context_element);
}
static SVGPointTearOff* CreateDetached(const FloatPoint&);
+ SVGPointTearOff(SVGPoint*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
+ SVGPointTearOff(SVGPoint*, SVGElement*);
+
void setX(float, ExceptionState&);
void setY(float, ExceptionState&);
float x() { return Target()->X(); }
float y() { return Target()->Y(); }
SVGPointTearOff* matrixTransform(SVGMatrixTearOff*);
-
- protected:
- SVGPointTearOff(SVGPoint*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
- SVGPointTearOff(SVGPoint*, SVGElement*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_poly_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_poly_element.cc
index b1d40b4b03f..dacf9445c35 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_poly_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_poly_element.cc
@@ -29,7 +29,7 @@ SVGPolyElement::SVGPolyElement(const QualifiedName& tag_name,
Document& document)
: SVGGeometryElement(tag_name, document),
points_(SVGAnimatedPointList::Create(this,
- SVGNames::pointsAttr,
+ svg_names::kPointsAttr,
SVGPointList::Create())) {
AddToPropertyMap(points_);
}
@@ -59,7 +59,7 @@ Path SVGPolyElement::AsPathFromPoints() const {
}
void SVGPolyElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::pointsAttr) {
+ if (attr_name == svg_names::kPointsAttr) {
GeometryAttributeChanged();
return;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_poly_element.h b/chromium/third_party/blink/renderer/core/svg/svg_poly_element.h
index 37c66133615..87a146ced44 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_poly_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_poly_element.h
@@ -50,8 +50,8 @@ class SVGPolyElement : public SVGGeometryElement {
};
inline bool IsSVGPolyElement(const SVGElement& element) {
- return element.HasTagName(SVGNames::polygonTag) ||
- element.HasTagName(SVGNames::polylineTag);
+ return element.HasTagName(svg_names::kPolygonTag) ||
+ element.HasTagName(svg_names::kPolylineTag);
}
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGPolyElement);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.cc
index b2ba991e2c4..4149711d37c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.cc
@@ -25,7 +25,7 @@
namespace blink {
inline SVGPolygonElement::SVGPolygonElement(Document& document)
- : SVGPolyElement(SVGNames::polygonTag, document) {}
+ : SVGPolyElement(svg_names::kPolygonTag, document) {}
DEFINE_NODE_FACTORY(SVGPolygonElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.cc
index 5e355c9bc0f..1d2b1f18e03 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.cc
@@ -25,7 +25,7 @@
namespace blink {
SVGPolylineElement::SVGPolylineElement(Document& document)
- : SVGPolyElement(SVGNames::polylineTag, document) {}
+ : SVGPolyElement(svg_names::kPolylineTag, document) {}
DEFINE_NODE_FACTORY(SVGPolylineElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.h b/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.h
index 8aa69f0d98c..24750bea9ff 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.h
@@ -56,9 +56,11 @@ class SVGPreserveAspectRatio final
typedef SVGPreserveAspectRatioTearOff TearOffType;
static SVGPreserveAspectRatio* Create() {
- return new SVGPreserveAspectRatio();
+ return MakeGarbageCollected<SVGPreserveAspectRatio>();
}
+ SVGPreserveAspectRatio();
+
virtual SVGPreserveAspectRatio* Clone() const;
bool operator==(const SVGPreserveAspectRatio&) const;
@@ -106,8 +108,6 @@ class SVGPreserveAspectRatio final
void SetDefault();
private:
- SVGPreserveAspectRatio();
-
template <typename CharType>
SVGParsingError ParseInternal(const CharType*& ptr,
const CharType* end,
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio_tear_off.h
index a2b3d6d9600..240844fc1be 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio_tear_off.h
@@ -77,19 +77,18 @@ class SVGPreserveAspectRatioTearOff final
SVGPreserveAspectRatio* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGPreserveAspectRatioTearOff(target, binding,
- property_is_anim_val);
+ return MakeGarbageCollected<SVGPreserveAspectRatioTearOff>(
+ target, binding, property_is_anim_val);
}
+ SVGPreserveAspectRatioTearOff(SVGPreserveAspectRatio*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
+
void setAlign(unsigned short, ExceptionState&);
unsigned short align() { return Target()->Align(); }
void setMeetOrSlice(unsigned short, ExceptionState&);
unsigned short meetOrSlice() { return Target()->MeetOrSlice(); }
-
- private:
- SVGPreserveAspectRatioTearOff(SVGPreserveAspectRatio*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.cc
index c855caf7683..e5800f6be35 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.cc
@@ -29,33 +29,33 @@
namespace blink {
inline SVGRadialGradientElement::SVGRadialGradientElement(Document& document)
- : SVGGradientElement(SVGNames::radialGradientTag, document),
+ : SVGGradientElement(svg_names::kRadialGradientTag, document),
// Spec: If the cx/cy/r attribute is not specified, the effect is as if a
// value of "50%" were specified.
cx_(SVGAnimatedLength::Create(this,
- SVGNames::cxAttr,
+ svg_names::kCxAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent50)),
cy_(SVGAnimatedLength::Create(this,
- SVGNames::cyAttr,
+ svg_names::kCyAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent50)),
r_(SVGAnimatedLength::Create(this,
- SVGNames::rAttr,
+ svg_names::kRAttr,
SVGLengthMode::kOther,
SVGLength::Initial::kPercent50)),
fx_(SVGAnimatedLength::Create(this,
- SVGNames::fxAttr,
+ svg_names::kFxAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent50)),
fy_(SVGAnimatedLength::Create(this,
- SVGNames::fyAttr,
+ svg_names::kFyAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent50)),
// SVG2-Draft Spec: If the fr attribute is not specified, the effect is as
// if a value of "0%" were specified.
fr_(SVGAnimatedLength::Create(this,
- SVGNames::frAttr,
+ svg_names::kFrAttr,
SVGLengthMode::kOther,
SVGLength::Initial::kPercent0)) {
AddToPropertyMap(cx_);
@@ -80,12 +80,12 @@ DEFINE_NODE_FACTORY(SVGRadialGradientElement)
void SVGRadialGradientElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::cxAttr || attr_name == SVGNames::cyAttr ||
- attr_name == SVGNames::fxAttr || attr_name == SVGNames::fyAttr ||
- attr_name == SVGNames::rAttr || attr_name == SVGNames::frAttr) {
+ if (attr_name == svg_names::kCxAttr || attr_name == svg_names::kCyAttr ||
+ attr_name == svg_names::kFxAttr || attr_name == svg_names::kFyAttr ||
+ attr_name == svg_names::kRAttr || attr_name == svg_names::kFrAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
UpdateRelativeLengthsInformation();
- InvalidateGradient(LayoutInvalidationReason::kAttributeChanged);
+ InvalidateGradient(layout_invalidation_reason::kAttributeChanged);
return;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_rect.h b/chromium/third_party/blink/renderer/core/svg/svg_rect.h
index be77de53b23..de2a678a5fc 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_rect.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_rect.h
@@ -33,15 +33,20 @@ class SVGRect final : public SVGPropertyHelper<SVGRect> {
public:
typedef SVGRectTearOff TearOffType;
- static SVGRect* Create() { return new SVGRect(); }
+ static SVGRect* Create() { return MakeGarbageCollected<SVGRect>(); }
static SVGRect* CreateInvalid() {
- SVGRect* rect = new SVGRect();
+ SVGRect* rect = MakeGarbageCollected<SVGRect>();
rect->SetInvalid();
return rect;
}
- static SVGRect* Create(const FloatRect& rect) { return new SVGRect(rect); }
+ static SVGRect* Create(const FloatRect& rect) {
+ return MakeGarbageCollected<SVGRect>(rect);
+ }
+
+ SVGRect();
+ SVGRect(const FloatRect&);
SVGRect* Clone() const;
@@ -77,9 +82,6 @@ class SVGRect final : public SVGPropertyHelper<SVGRect> {
static AnimatedPropertyType ClassType() { return kAnimatedRect; }
private:
- SVGRect();
- SVGRect(const FloatRect&);
-
template <typename CharType>
SVGParsingError Parse(const CharType*& ptr, const CharType* end);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_rect_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_rect_element.cc
index ed62484c0f7..9bfa8676d0f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_rect_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_rect_element.cc
@@ -26,34 +26,34 @@
namespace blink {
inline SVGRectElement::SVGRectElement(Document& document)
- : SVGGeometryElement(SVGNames::rectTag, document),
+ : SVGGeometryElement(svg_names::kRectTag, document),
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyX)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyY)),
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyWidth)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyHeight)),
rx_(SVGAnimatedLength::Create(this,
- SVGNames::rxAttr,
+ svg_names::kRxAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyRx)),
ry_(SVGAnimatedLength::Create(this,
- SVGNames::ryAttr,
+ svg_names::kRyAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyRy)) {
@@ -139,9 +139,10 @@ void SVGRectElement::CollectStyleForPresentationAttribute(
}
void SVGRectElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr ||
- attr_name == SVGNames::rxAttr || attr_name == SVGNames::ryAttr) {
+ if (attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr ||
+ attr_name == svg_names::kHeightAttr || attr_name == svg_names::kRxAttr ||
+ attr_name == svg_names::kRyAttr) {
UpdateRelativeLengthsInformation();
GeometryPresentationAttributeChanged(attr_name);
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_rect_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_rect_tear_off.h
index dad272d61b5..36976210c43 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_rect_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_rect_tear_off.h
@@ -43,10 +43,15 @@ class SVGRectTearOff : public SVGPropertyTearOff<SVGRect> {
static SVGRectTearOff* Create(SVGRect* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGRectTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGRectTearOff>(target, binding,
+ property_is_anim_val);
}
static SVGRectTearOff* CreateDetached(const FloatRect&);
+ SVGRectTearOff(SVGRect*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
+
void setX(float, ExceptionState&);
void setY(float, ExceptionState&);
void setWidth(float, ExceptionState&);
@@ -55,11 +60,6 @@ class SVGRectTearOff : public SVGPropertyTearOff<SVGRect> {
float y() { return Target()->Y(); }
float width() { return Target()->Width(); }
float height() { return Target()->Height(); }
-
- private:
- SVGRectTearOff(SVGRect*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_resource.cc b/chromium/third_party/blink/renderer/core/svg/svg_resource.cc
index 7e633505609..bf7c8a10c7b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_resource.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_resource.cc
@@ -126,7 +126,7 @@ void ExternalSVGResource::Load(const Document& document) {
if (resource_document_)
return;
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::css;
+ options.initiator_info.name = fetch_initiator_type_names::kCSS;
FetchParameters params(ResourceRequest(url_), options);
params.MutableResourceRequest().SetFetchRequestMode(
network::mojom::FetchRequestMode::kSameOrigin);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_script_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_script_element.cc
index 0d76d329616..d6b017bf1d4 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_script_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_script_element.cc
@@ -35,21 +35,21 @@ namespace blink {
inline SVGScriptElement::SVGScriptElement(Document& document,
const CreateElementFlags flags)
- : SVGElement(SVGNames::scriptTag, document),
+ : SVGElement(svg_names::kScriptTag, document),
SVGURIReference(this),
loader_(InitializeScriptLoader(flags.IsCreatedByParser(),
flags.WasAlreadyStarted())) {}
SVGScriptElement* SVGScriptElement::Create(Document& document,
const CreateElementFlags flags) {
- return new SVGScriptElement(document, flags);
+ return MakeGarbageCollected<SVGScriptElement>(document, flags);
}
void SVGScriptElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == HTMLNames::onerrorAttr) {
+ if (params.name == html_names::kOnerrorAttr) {
SetAttributeEventListener(
- EventTypeNames::error,
+ event_type_names::kError,
CreateAttributeEventListener(
this, params.name, params.new_value,
JSEventHandler::HandlerType::kOnErrorEventHandler));
@@ -109,7 +109,7 @@ String SVGScriptElement::SourceAttributeValue() const {
}
String SVGScriptElement::TypeAttributeValue() const {
- return getAttribute(SVGNames::typeAttr).GetString();
+ return getAttribute(svg_names::kTypeAttr).GetString();
}
String SVGScriptElement::TextFromChildren() {
@@ -156,12 +156,12 @@ Element* SVGScriptElement::CloneWithoutAttributesAndChildren(
}
void SVGScriptElement::DispatchLoadEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
have_fired_load_ = true;
}
void SVGScriptElement::DispatchErrorEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
void SVGScriptElement::SetScriptElementForBinding(
@@ -172,8 +172,8 @@ void SVGScriptElement::SetScriptElementForBinding(
#if DCHECK_IS_ON()
bool SVGScriptElement::IsAnimatableAttribute(const QualifiedName& name) const {
- if (name == SVGNames::typeAttr || name == SVGNames::hrefAttr ||
- name == XLinkNames::hrefAttr)
+ if (name == svg_names::kTypeAttr || name == svg_names::kHrefAttr ||
+ name == xlink_names::kHrefAttr)
return false;
return SVGElement::IsAnimatableAttribute(name);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_script_element.h b/chromium/third_party/blink/renderer/core/svg/svg_script_element.h
index 157afbae070..4525f28fb1c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_script_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_script_element.h
@@ -41,6 +41,8 @@ class SVGScriptElement final : public SVGElement,
public:
static SVGScriptElement* Create(Document&, const CreateElementFlags);
+ SVGScriptElement(Document&, const CreateElementFlags);
+
ScriptLoader* Loader() const final { return loader_.Get(); }
#if DCHECK_IS_ON()
@@ -52,8 +54,6 @@ class SVGScriptElement final : public SVGElement,
void Trace(blink::Visitor*) override;
private:
- SVGScriptElement(Document&, const CreateElementFlags);
-
void ParseAttribute(const AttributeModificationParams&) override;
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void DidNotifySubtreeInsertionsToDocument() override;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_set_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_set_element.cc
index 9d5836e485f..8d889dafe45 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_set_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_set_element.cc
@@ -25,7 +25,7 @@
namespace blink {
inline SVGSetElement::SVGSetElement(Document& document)
- : SVGAnimateElement(SVGNames::setTag, document) {
+ : SVGAnimateElement(svg_names::kSetTag, document) {
SetAnimationMode(kToAnimation);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_static_string_list.h b/chromium/third_party/blink/renderer/core/svg/svg_static_string_list.h
index 1b3867c58b4..cf134e39937 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_static_string_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_static_string_list.h
@@ -51,10 +51,14 @@ class SVGStaticStringList final
template <char list_delimiter>
static SVGStaticStringList* Create(SVGElement* context_element,
const QualifiedName& attribute_name) {
- return new SVGStaticStringList(context_element, attribute_name,
- SVGStringList<list_delimiter>::Create());
+ return MakeGarbageCollected<SVGStaticStringList>(
+ context_element, attribute_name,
+ SVGStringList<list_delimiter>::Create());
}
+ SVGStaticStringList(SVGElement*,
+ const QualifiedName&,
+ SVGStringListBase* initial_value);
~SVGStaticStringList() override;
// SVGAnimatedPropertyBase:
@@ -73,10 +77,6 @@ class SVGStaticStringList final
void Trace(blink::Visitor*) override;
private:
- SVGStaticStringList(SVGElement*,
- const QualifiedName&,
- SVGStringListBase* initial_value);
-
Member<SVGStringListBase> value_;
Member<SVGStringListTearOff> tear_off_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_stop_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_stop_element.cc
index 214b3359f0e..03ecf0e995d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_stop_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_stop_element.cc
@@ -26,9 +26,9 @@
namespace blink {
inline SVGStopElement::SVGStopElement(Document& document)
- : SVGElement(SVGNames::stopTag, document),
+ : SVGElement(svg_names::kStopTag, document),
offset_(SVGAnimatedNumber::Create(this,
- SVGNames::offsetAttr,
+ svg_names::kOffsetAttr,
SVGNumberAcceptPercentage::Create())) {
AddToPropertyMap(offset_);
@@ -51,13 +51,13 @@ void InvalidateInstancesAndAncestorResources(SVGStopElement* stop_element) {
Element* parent = stop_element->parentElement();
if (auto* gradient = ToSVGGradientElementOrNull(parent))
- gradient->InvalidateGradient(LayoutInvalidationReason::kChildChanged);
+ gradient->InvalidateGradient(layout_invalidation_reason::kChildChanged);
}
} // namespace
void SVGStopElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::offsetAttr) {
+ if (attr_name == svg_names::kOffsetAttr) {
InvalidateInstancesAndAncestorResources(this);
return;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_string.h b/chromium/third_party/blink/renderer/core/svg/svg_string.h
index 143f7e0d461..2343bcc8a7c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_string.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_string.h
@@ -42,9 +42,14 @@ class SVGString final : public SVGPropertyBase {
typedef void TearOffType;
typedef String PrimitiveType;
- static SVGString* Create() { return new SVGString(); }
+ static SVGString* Create() { return MakeGarbageCollected<SVGString>(); }
- static SVGString* Create(const String& value) { return new SVGString(value); }
+ static SVGString* Create(const String& value) {
+ return MakeGarbageCollected<SVGString>(value);
+ }
+
+ SVGString() = default;
+ explicit SVGString(const String& value) : value_(value) {}
SVGString* Clone() const { return Create(value_); }
SVGPropertyBase* CloneForAnimation(const String& value) const override {
@@ -74,9 +79,6 @@ class SVGString final : public SVGPropertyBase {
AnimatedPropertyType GetType() const override { return ClassType(); }
private:
- SVGString() = default;
- explicit SVGString(const String& value) : value_(value) {}
-
String value_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_string_list_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_string_list_tear_off.h
index bf18847e41a..48d730e34bb 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_string_list_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_string_list_tear_off.h
@@ -44,9 +44,14 @@ class SVGStringListTearOff : public SVGPropertyTearOff<SVGStringListBase> {
SVGStringListBase* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGStringListTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGStringListTearOff>(target, binding,
+ property_is_anim_val);
}
+ SVGStringListTearOff(SVGStringListBase*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
+
// SVGStringList DOM interface:
// WebIDL requires "unsigned long" type which is uint32_t.
@@ -125,11 +130,6 @@ class SVGStringListTearOff : public SVGPropertyTearOff<SVGStringListBase> {
CommitChange();
return item;
}
-
- protected:
- SVGStringListTearOff(SVGStringListBase*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_style_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_style_element.cc
index 6c25bb52ae3..25f587b66f9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_style_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_style_element.cc
@@ -26,20 +26,21 @@
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/media_type_names.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
inline SVGStyleElement::SVGStyleElement(Document& document,
const CreateElementFlags flags)
- : SVGElement(SVGNames::styleTag, document),
+ : SVGElement(svg_names::kStyleTag, document),
StyleElement(&document, flags.IsCreatedByParser()) {}
SVGStyleElement::~SVGStyleElement() = default;
SVGStyleElement* SVGStyleElement::Create(Document& document,
const CreateElementFlags flags) {
- return new SVGStyleElement(document, flags);
+ return MakeGarbageCollected<SVGStyleElement>(document, flags);
}
bool SVGStyleElement::disabled() const {
@@ -56,34 +57,34 @@ void SVGStyleElement::setDisabled(bool set_disabled) {
const AtomicString& SVGStyleElement::type() const {
DEFINE_STATIC_LOCAL(const AtomicString, default_value, ("text/css"));
- const AtomicString& n = getAttribute(SVGNames::typeAttr);
+ const AtomicString& n = getAttribute(svg_names::kTypeAttr);
return n.IsNull() ? default_value : n;
}
void SVGStyleElement::setType(const AtomicString& type) {
- setAttribute(SVGNames::typeAttr, type);
+ setAttribute(svg_names::kTypeAttr, type);
}
const AtomicString& SVGStyleElement::media() const {
- const AtomicString& n = FastGetAttribute(SVGNames::mediaAttr);
- return n.IsNull() ? MediaTypeNames::all : n;
+ const AtomicString& n = FastGetAttribute(svg_names::kMediaAttr);
+ return n.IsNull() ? media_type_names::kAll : n;
}
void SVGStyleElement::setMedia(const AtomicString& media) {
- setAttribute(SVGNames::mediaAttr, media);
+ setAttribute(svg_names::kMediaAttr, media);
}
String SVGStyleElement::title() const {
- return FastGetAttribute(SVGNames::titleAttr);
+ return FastGetAttribute(svg_names::kTitleAttr);
}
void SVGStyleElement::setTitle(const AtomicString& title) {
- setAttribute(SVGNames::titleAttr, title);
+ setAttribute(svg_names::kTitleAttr, title);
}
void SVGStyleElement::ParseAttribute(
const AttributeModificationParams& params) {
- if (params.name == SVGNames::titleAttr) {
+ if (params.name == svg_names::kTitleAttr) {
if (sheet_ && IsInDocumentTree())
sheet_->SetTitle(params.new_value);
@@ -139,7 +140,7 @@ void SVGStyleElement::NotifyLoadedSheetAndAllCriticalSubresources(
}
void SVGStyleElement::DispatchPendingEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
void SVGStyleElement::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_style_element.h b/chromium/third_party/blink/renderer/core/svg/svg_style_element.h
index 763e0b14fe0..8fba25f8e55 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_style_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_style_element.h
@@ -33,6 +33,8 @@ class SVGStyleElement final : public SVGElement, public StyleElement {
public:
static SVGStyleElement* Create(Document&, const CreateElementFlags);
+
+ SVGStyleElement(Document&, const CreateElementFlags);
~SVGStyleElement() override;
using StyleElement::sheet;
@@ -54,8 +56,6 @@ class SVGStyleElement final : public SVGElement, public StyleElement {
void Trace(blink::Visitor*) override;
private:
- SVGStyleElement(Document&, const CreateElementFlags);
-
void ParseAttribute(const AttributeModificationParams&) override;
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_svg_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_svg_element.cc
index e80aac4a38a..ee1c8b05cd7 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_svg_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_svg_element.cc
@@ -54,7 +54,7 @@
#include "third_party/blink/renderer/core/svg/svg_view_spec.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -62,25 +62,25 @@
namespace blink {
inline SVGSVGElement::SVGSVGElement(Document& doc)
- : SVGGraphicsElement(SVGNames::svgTag, doc),
+ : SVGGraphicsElement(svg_names::kSVGTag, doc),
SVGFitToViewBox(this),
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyX)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyY)),
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kPercent100,
CSSPropertyWidth)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kPercent100,
CSSPropertyHeight)),
@@ -118,17 +118,16 @@ void SVGSVGElement::setCurrentScale(float scale) {
class SVGCurrentTranslateTearOff : public SVGPointTearOff {
public:
static SVGCurrentTranslateTearOff* Create(SVGSVGElement* context_element) {
- return new SVGCurrentTranslateTearOff(context_element);
+ return MakeGarbageCollected<SVGCurrentTranslateTearOff>(context_element);
}
+ SVGCurrentTranslateTearOff(SVGSVGElement* context_element)
+ : SVGPointTearOff(context_element->translation_, context_element) {}
+
void CommitChange() override {
DCHECK(ContextElement());
ToSVGSVGElement(ContextElement())->UpdateUserTransform();
}
-
- private:
- SVGCurrentTranslateTearOff(SVGSVGElement* context_element)
- : SVGPointTearOff(context_element->translation_, context_element) {}
};
SVGPointTearOff* SVGSVGElement::currentTranslateFromJavascript() {
@@ -141,9 +140,10 @@ void SVGSVGElement::SetCurrentTranslate(const FloatPoint& point) {
}
void SVGSVGElement::UpdateUserTransform() {
- if (LayoutObject* object = GetLayoutObject())
+ if (LayoutObject* object = GetLayoutObject()) {
object->SetNeedsLayoutAndFullPaintInvalidation(
- LayoutInvalidationReason::kUnknown);
+ layout_invalidation_reason::kUnknown);
+ }
}
bool SVGSVGElement::ZoomAndPanEnabled() const {
@@ -160,17 +160,17 @@ void SVGSVGElement::ParseAttribute(const AttributeModificationParams& params) {
bool set_listener = true;
// Only handle events if we're the outermost <svg> element
- if (name == HTMLNames::onunloadAttr) {
+ if (name == html_names::kOnunloadAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::unload,
+ event_type_names::kUnload,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == HTMLNames::onresizeAttr) {
+ } else if (name == html_names::kOnresizeAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::resize,
+ event_type_names::kResize,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == HTMLNames::onscrollAttr) {
+ } else if (name == html_names::kOnscrollAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::scroll,
+ event_type_names::kScroll,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
} else {
set_listener = false;
@@ -180,13 +180,13 @@ void SVGSVGElement::ParseAttribute(const AttributeModificationParams& params) {
return;
}
- if (name == HTMLNames::onabortAttr) {
+ if (name == html_names::kOnabortAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::abort,
+ event_type_names::kAbort,
CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
- } else if (name == HTMLNames::onerrorAttr) {
+ } else if (name == html_names::kOnerrorAttr) {
GetDocument().SetWindowAttributeEventListener(
- EventTypeNames::error,
+ event_type_names::kError,
CreateAttributeEventListener(
GetDocument().GetFrame(), name, value,
JSEventHandler::HandlerType::kOnErrorEventHandler));
@@ -197,7 +197,7 @@ void SVGSVGElement::ParseAttribute(const AttributeModificationParams& params) {
}
bool SVGSVGElement::IsPresentationAttribute(const QualifiedName& name) const {
- if ((name == SVGNames::widthAttr || name == SVGNames::heightAttr) &&
+ if ((name == svg_names::kWidthAttr || name == svg_names::kHeightAttr) &&
!IsOutermostSVGSVGElement())
return false;
return SVGGraphicsElement::IsPresentationAttribute(name);
@@ -205,7 +205,7 @@ bool SVGSVGElement::IsPresentationAttribute(const QualifiedName& name) const {
bool SVGSVGElement::IsPresentationAttributeWithSVGDOM(
const QualifiedName& attr_name) const {
- if (attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr)
+ if (attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr)
return false;
return SVGGraphicsElement::IsPresentationAttributeWithSVGDOM(attr_name);
}
@@ -239,9 +239,9 @@ void SVGSVGElement::CollectStyleForPresentationAttribute(
void SVGSVGElement::SvgAttributeChanged(const QualifiedName& attr_name) {
bool update_relative_lengths_or_view_box = false;
bool width_or_height_changed =
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr;
- if (width_or_height_changed || attr_name == SVGNames::xAttr ||
- attr_name == SVGNames::yAttr) {
+ attr_name == svg_names::kWidthAttr || attr_name == svg_names::kHeightAttr;
+ if (width_or_height_changed || attr_name == svg_names::kXAttr ||
+ attr_name == svg_names::kYAttr) {
update_relative_lengths_or_view_box = true;
UpdateRelativeLengthsInformation();
InvalidateRelativeLengthClients();
@@ -258,7 +258,7 @@ void SVGSVGElement::SvgAttributeChanged(const QualifiedName& attr_name) {
InvalidateSVGPresentationAttributeStyle();
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
- StyleChangeReason::kSVGContainerSizeChange));
+ style_change_reason::kSVGContainerSizeChange));
if (layout_object)
ToLayoutSVGRoot(layout_object)->IntrinsicSizingInfoChanged();
}
@@ -275,7 +275,7 @@ void SVGSVGElement::SvgAttributeChanged(const QualifiedName& attr_name) {
InvalidateRelativeLengthClients();
if (LayoutObject* object = GetLayoutObject()) {
object->SetNeedsTransformUpdate();
- if (attr_name == SVGNames::viewBoxAttr && object->IsSVGRoot())
+ if (attr_name == svg_names::kViewBoxAttr && object->IsSVGRoot())
ToLayoutSVGRoot(object)->IntrinsicSizingInfoChanged();
}
}
@@ -514,17 +514,15 @@ Node::InsertionNotificationRequest SVGSVGElement::InsertedInto(
if (root_parent.GetDocument().IsXMLDocument())
UseCounter::Count(GetDocument(), WebFeature::kSVGSVGElementInXMLDocument);
- if (RuntimeEnabledFeatures::SMILEnabled()) {
- GetDocument().AccessSVGExtensions().AddTimeContainer(this);
+ GetDocument().AccessSVGExtensions().AddTimeContainer(this);
- // Animations are started at the end of document parsing and after firing
- // the load event, but if we miss that train (deferred programmatic
- // element insertion for example) we need to initialize the time container
- // here.
- if (!GetDocument().Parsing() && GetDocument().LoadEventFinished() &&
- !TimeContainer()->IsStarted())
- TimeContainer()->Start();
- }
+ // Animations are started at the end of document parsing and after firing
+ // the load event, but if we miss that train (deferred programmatic
+ // element insertion for example) we need to initialize the time container
+ // here.
+ if (!GetDocument().Parsing() && GetDocument().LoadEventFinished() &&
+ !TimeContainer()->IsStarted())
+ TimeContainer()->Start();
}
return SVGGraphicsElement::InsertedInto(root_parent);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_svg_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_svg_element.idl
index 4cc98bb6e62..0643aed5a90 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_svg_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_svg_element.idl
@@ -59,11 +59,11 @@ interface SVGSVGElement : SVGGraphicsElement {
// SVG Animations
// https://svgwg.org/specs/animations/#InterfaceSVGSVGElement
- [MeasureAs=SVGSMILPausing, RuntimeEnabled=SMIL] void pauseAnimations();
- [MeasureAs=SVGSMILPausing, RuntimeEnabled=SMIL] void unpauseAnimations();
- [MeasureAs=SVGSMILPausing, RuntimeEnabled=SMIL] boolean animationsPaused();
- [MeasureAs=SVGSMILCurrentTime, RuntimeEnabled=SMIL] float getCurrentTime();
- [MeasureAs=SVGSMILCurrentTime, RuntimeEnabled=SMIL] void setCurrentTime(float seconds);
+ [MeasureAs=SVGSMILPausing] void pauseAnimations();
+ [MeasureAs=SVGSMILPausing] void unpauseAnimations();
+ [MeasureAs=SVGSMILPausing] boolean animationsPaused();
+ [MeasureAs=SVGSMILCurrentTime] float getCurrentTime();
+ [MeasureAs=SVGSMILCurrentTime] void setCurrentTime(float seconds);
};
SVGSVGElement implements SVGFitToViewBox;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_switch_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_switch_element.cc
index 4612379f922..7b516fcb941 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_switch_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_switch_element.cc
@@ -27,7 +27,7 @@
namespace blink {
inline SVGSwitchElement::SVGSwitchElement(Document& document)
- : SVGGraphicsElement(SVGNames::switchTag, document) {
+ : SVGGraphicsElement(svg_names::kSwitchTag, document) {
UseCounter::Count(document, WebFeature::kSVGSwitchElement);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.cc
index 3e6fd018caa..d13c35ebce5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.cc
@@ -26,7 +26,7 @@
namespace blink {
inline SVGSymbolElement::SVGSymbolElement(Document& document)
- : SVGElement(SVGNames::symbolTag, document), SVGFitToViewBox(this) {}
+ : SVGElement(svg_names::kSymbolTag, document), SVGFitToViewBox(this) {}
void SVGSymbolElement::Trace(blink::Visitor* visitor) {
SVGElement::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_tag_names.json5 b/chromium/third_party/blink/renderer/core/svg/svg_tag_names.json5
index 2591fb1930f..53fc167c31b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_tag_names.json5
+++ b/chromium/third_party/blink/renderer/core/svg/svg_tag_names.json5
@@ -12,35 +12,21 @@
{
name: "animate",
noTypeHelpers: true,
- runtimeEnabled: "SMIL",
},
{
name: "animateColor",
JSInterfaceName: "SVGElement",
interfaceName: "SVGUnknownElement",
noConstructor: true,
- runtimeEnabled: "SMIL",
- },
- {
- name: "animateMotion",
- runtimeEnabled: "SMIL",
- },
- {
- name: "animateTransform",
- runtimeEnabled: "SMIL",
- },
- {
- name: "set",
- runtimeEnabled: "SMIL",
},
+ "animateMotion",
+ "animateTransform",
+ "set",
"circle",
"clipPath",
"defs",
"desc",
- {
- name: "discard",
- runtimeEnabled: "SMIL",
- },
+ "discard",
"ellipse",
"feBlend",
"feColorMatrix",
@@ -79,7 +65,6 @@
{
name: "mpath",
interfaceName: "SVGMPathElement",
- runtimeEnabled: "SMIL",
},
"path",
"pattern",
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_tests.cc b/chromium/third_party/blink/renderer/core/svg/svg_tests.cc
index ca20e9174d6..dbbc2e9e5e7 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_tests.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_tests.cc
@@ -32,10 +32,10 @@ namespace blink {
SVGTests::SVGTests(SVGElement* context_element)
: required_extensions_(
SVGStaticStringList::Create<' '>(context_element,
- SVGNames::requiredExtensionsAttr)),
+ svg_names::kRequiredExtensionsAttr)),
system_language_(
SVGStaticStringList::Create<','>(context_element,
- SVGNames::systemLanguageAttr)) {
+ svg_names::kSystemLanguageAttr)) {
DCHECK(context_element);
context_element->AddToPropertyMap(required_extensions_);
@@ -98,8 +98,8 @@ bool SVGTests::IsValid() const {
}
bool SVGTests::IsKnownAttribute(const QualifiedName& attr_name) {
- return attr_name == SVGNames::requiredExtensionsAttr ||
- attr_name == SVGNames::systemLanguageAttr;
+ return attr_name == svg_names::kRequiredExtensionsAttr ||
+ attr_name == svg_names::kSystemLanguageAttr;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.cc
index 99abac1b520..307267cab67 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.cc
@@ -20,13 +20,14 @@
#include "third_party/blink/renderer/core/svg/svg_text_content_element.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/core/layout/svg/svg_text_query.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg/svg_point_tear_off.h"
#include "third_party/blink/renderer/core/svg/svg_rect_tear_off.h"
#include "third_party/blink/renderer/core/svg_names.h"
@@ -37,14 +38,12 @@
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGLengthAdjustType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(kSVGLengthAdjustSpacing, "spacing"));
- entries.push_back(
- std::make_pair(kSVGLengthAdjustSpacingAndGlyphs, "spacingAndGlyphs"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGLengthAdjustType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSVGLengthAdjustSpacing, "spacing"},
+ {kSVGLengthAdjustSpacingAndGlyphs, "spacingAndGlyphs"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
@@ -54,9 +53,15 @@ GetStaticStringEntries<SVGLengthAdjustType>() {
class SVGAnimatedTextLength final : public SVGAnimatedLength {
public:
static SVGAnimatedTextLength* Create(SVGTextContentElement* context_element) {
- return new SVGAnimatedTextLength(context_element);
+ return MakeGarbageCollected<SVGAnimatedTextLength>(context_element);
}
+ SVGAnimatedTextLength(SVGTextContentElement* context_element)
+ : SVGAnimatedLength(context_element,
+ svg_names::kTextLengthAttr,
+ SVGLengthMode::kWidth,
+ SVGLength::Initial::kUnitlessZero) {}
+
SVGLengthTearOff* baseVal() override {
SVGTextContentElement* text_content_element =
ToSVGTextContentElement(ContextElement());
@@ -67,13 +72,6 @@ class SVGAnimatedTextLength final : public SVGAnimatedLength {
return SVGAnimatedLength::baseVal();
}
-
- private:
- SVGAnimatedTextLength(SVGTextContentElement* context_element)
- : SVGAnimatedLength(context_element,
- SVGNames::textLengthAttr,
- SVGLengthMode::kWidth,
- SVGLength::Initial::kUnitlessZero) {}
};
SVGTextContentElement::SVGTextContentElement(const QualifiedName& tag_name,
@@ -83,7 +81,7 @@ SVGTextContentElement::SVGTextContentElement(const QualifiedName& tag_name,
text_length_is_specified_by_user_(false),
length_adjust_(SVGAnimatedEnumeration<SVGLengthAdjustType>::Create(
this,
- SVGNames::lengthAdjustAttr,
+ svg_names::kLengthAdjustAttr,
kSVGLengthAdjustSpacing)) {
AddToPropertyMap(text_length_);
AddToPropertyMap(length_adjust_);
@@ -224,7 +222,7 @@ void SVGTextContentElement::selectSubString(unsigned charnum,
bool SVGTextContentElement::IsPresentationAttribute(
const QualifiedName& name) const {
- if (name.Matches(XMLNames::spaceAttr))
+ if (name.Matches(xml_names::kSpaceAttr))
return true;
return SVGGraphicsElement::IsPresentationAttribute(name);
}
@@ -233,7 +231,7 @@ void SVGTextContentElement::CollectStyleForPresentationAttribute(
const QualifiedName& name,
const AtomicString& value,
MutableCSSPropertyValueSet* style) {
- if (name.Matches(XMLNames::spaceAttr)) {
+ if (name.Matches(xml_names::kSpaceAttr)) {
DEFINE_STATIC_LOCAL(const AtomicString, preserve_string, ("preserve"));
if (value == preserve_string) {
@@ -254,12 +252,12 @@ void SVGTextContentElement::CollectStyleForPresentationAttribute(
void SVGTextContentElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
- if (attr_name == SVGNames::textLengthAttr)
+ if (attr_name == svg_names::kTextLengthAttr)
text_length_is_specified_by_user_ = true;
- if (attr_name == SVGNames::textLengthAttr ||
- attr_name == SVGNames::lengthAdjustAttr ||
- attr_name == XMLNames::spaceAttr) {
+ if (attr_name == svg_names::kTextLengthAttr ||
+ attr_name == svg_names::kLengthAdjustAttr ||
+ attr_name == xml_names::kSpaceAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
if (LayoutObject* layout_object = GetLayoutObject())
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.h b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.h
index 6aeb290ea6e..e6b76611395 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.h
@@ -37,9 +37,7 @@ enum SVGLengthAdjustType {
kSVGLengthAdjustSpacing,
kSVGLengthAdjustSpacingAndGlyphs
};
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGLengthAdjustType>();
+DECLARE_SVG_ENUM_MAP(SVGLengthAdjustType);
class CORE_EXPORT SVGTextContentElement : public SVGGraphicsElement {
DEFINE_WRAPPERTYPEINFO();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_text_element.cc
index 49862d01f09..2a034fd29bf 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_element.cc
@@ -25,7 +25,7 @@
namespace blink {
inline SVGTextElement::SVGTextElement(Document& doc)
- : SVGTextPositioningElement(SVGNames::textTag, doc) {}
+ : SVGTextPositioningElement(svg_names::kTextTag, doc) {}
DEFINE_NODE_FACTORY(SVGTextElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.cc
index e0c5228c442..63f9cb629ef 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.cc
@@ -22,46 +22,44 @@
#include "third_party/blink/renderer/core/dom/id_target_observer.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_text_path.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGTextPathMethodType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(kSVGTextPathMethodAlign, "align"));
- entries.push_back(std::make_pair(kSVGTextPathMethodStretch, "stretch"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGTextPathMethodType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSVGTextPathMethodAlign, "align"},
+ {kSVGTextPathMethodStretch, "stretch"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGTextPathSpacingType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(kSVGTextPathSpacingAuto, "auto"));
- entries.push_back(std::make_pair(kSVGTextPathSpacingExact, "exact"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGTextPathSpacingType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {kSVGTextPathSpacingAuto, "auto"}, {kSVGTextPathSpacingExact, "exact"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
inline SVGTextPathElement::SVGTextPathElement(Document& document)
- : SVGTextContentElement(SVGNames::textPathTag, document),
+ : SVGTextContentElement(svg_names::kTextPathTag, document),
SVGURIReference(this),
start_offset_(
SVGAnimatedLength::Create(this,
- SVGNames::startOffsetAttr,
+ svg_names::kStartOffsetAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
method_(SVGAnimatedEnumeration<SVGTextPathMethodType>::Create(
this,
- SVGNames::methodAttr,
+ svg_names::kMethodAttr,
kSVGTextPathMethodAlign)),
spacing_(SVGAnimatedEnumeration<SVGTextPathSpacingType>::Create(
this,
- SVGNames::spacingAttr,
+ svg_names::kSpacingAttr,
kSVGTextPathSpacingExact)) {
AddToPropertyMap(start_offset_);
AddToPropertyMap(method_);
@@ -93,11 +91,12 @@ void SVGTextPathElement::SvgAttributeChanged(const QualifiedName& attr_name) {
return;
}
- if (attr_name == SVGNames::startOffsetAttr)
+ if (attr_name == svg_names::kStartOffsetAttr)
UpdateRelativeLengthsInformation();
- if (attr_name == SVGNames::startOffsetAttr ||
- attr_name == SVGNames::methodAttr || attr_name == SVGNames::spacingAttr) {
+ if (attr_name == svg_names::kStartOffsetAttr ||
+ attr_name == svg_names::kMethodAttr ||
+ attr_name == svg_names::kSpacingAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
if (LayoutObject* object = GetLayoutObject())
MarkForLayoutAndParentResourceInvalidation(*object);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.h b/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.h
index a1816bc891e..48a53d9510a 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.h
@@ -31,19 +31,14 @@ enum SVGTextPathMethodType {
kSVGTextPathMethodAlign,
kSVGTextPathMethodStretch
};
+DECLARE_SVG_ENUM_MAP(SVGTextPathMethodType);
enum SVGTextPathSpacingType {
kSVGTextPathSpacingUnknown = 0,
kSVGTextPathSpacingAuto,
kSVGTextPathSpacingExact
};
-
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGTextPathMethodType>();
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGTextPathSpacingType>();
+DECLARE_SVG_ENUM_MAP(SVGTextPathSpacingType);
class SVGTextPathElement final : public SVGTextContentElement,
public SVGURIReference {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.cc
index d529137a169..1d41c7a261c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.cc
@@ -33,21 +33,21 @@ SVGTextPositioningElement::SVGTextPositioningElement(
: SVGTextContentElement(tag_name, document),
x_(SVGAnimatedLengthList::Create(
this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthList::Create(SVGLengthMode::kWidth))),
y_(SVGAnimatedLengthList::Create(
this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthList::Create(SVGLengthMode::kHeight))),
dx_(SVGAnimatedLengthList::Create(
this,
- SVGNames::dxAttr,
+ svg_names::kDxAttr,
SVGLengthList::Create(SVGLengthMode::kWidth))),
dy_(SVGAnimatedLengthList::Create(
this,
- SVGNames::dyAttr,
+ svg_names::kDyAttr,
SVGLengthList::Create(SVGLengthMode::kHeight))),
- rotate_(SVGAnimatedNumberList::Create(this, SVGNames::rotateAttr)) {
+ rotate_(SVGAnimatedNumberList::Create(this, svg_names::kRotateAttr)) {
AddToPropertyMap(x_);
AddToPropertyMap(y_);
AddToPropertyMap(dx_);
@@ -67,13 +67,13 @@ void SVGTextPositioningElement::Trace(blink::Visitor* visitor) {
void SVGTextPositioningElement::SvgAttributeChanged(
const QualifiedName& attr_name) {
bool update_relative_lengths =
- attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::dxAttr || attr_name == SVGNames::dyAttr;
+ attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kDxAttr || attr_name == svg_names::kDyAttr;
if (update_relative_lengths)
UpdateRelativeLengthsInformation();
- if (update_relative_lengths || attr_name == SVGNames::rotateAttr) {
+ if (update_relative_lengths || attr_name == svg_names::kRotateAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
LayoutObject* layout_object = GetLayoutObject();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_title_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_title_element.cc
index c98d0599bfc..8609f51dace 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_title_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_title_element.cc
@@ -29,7 +29,7 @@
namespace blink {
inline SVGTitleElement::SVGTitleElement(Document& document)
- : SVGElement(SVGNames::titleTag, document),
+ : SVGElement(svg_names::kTitleTag, document),
ignore_title_updates_when_children_change_(false) {}
DEFINE_NODE_FACTORY(SVGTitleElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform.cc b/chromium/third_party/blink/renderer/core/svg/svg_transform.cc
index 8a5841959f2..0c8ca92dc36 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform.cc
@@ -51,7 +51,8 @@ SVGTransform::SVGTransform(SVGTransformType transform_type,
SVGTransform::~SVGTransform() = default;
SVGTransform* SVGTransform::Clone() const {
- return new SVGTransform(transform_type_, angle_, center_, matrix_);
+ return MakeGarbageCollected<SVGTransform>(transform_type_, angle_, center_,
+ matrix_);
}
SVGPropertyBase* SVGTransform::CloneForAnimation(const String&) const {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform.h b/chromium/third_party/blink/renderer/core/svg/svg_transform.h
index a304c587747..b356a94a8b6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform.h
@@ -50,18 +50,25 @@ class SVGTransform final : public SVGPropertyBase {
kConstructZeroTransform
};
- static SVGTransform* Create() { return new SVGTransform(); }
+ static SVGTransform* Create() { return MakeGarbageCollected<SVGTransform>(); }
static SVGTransform* Create(
SVGTransformType type,
ConstructionMode mode = kConstructIdentityTransform) {
- return new SVGTransform(type, mode);
+ return MakeGarbageCollected<SVGTransform>(type, mode);
}
static SVGTransform* Create(const AffineTransform& affine_transform) {
- return new SVGTransform(affine_transform);
+ return MakeGarbageCollected<SVGTransform>(affine_transform);
}
+ SVGTransform();
+ SVGTransform(SVGTransformType, ConstructionMode);
+ explicit SVGTransform(const AffineTransform&);
+ SVGTransform(SVGTransformType,
+ float,
+ const FloatPoint&,
+ const AffineTransform&);
~SVGTransform() override;
SVGTransform* Clone() const;
@@ -106,14 +113,6 @@ class SVGTransform final : public SVGPropertyBase {
AnimatedPropertyType GetType() const override { return ClassType(); }
private:
- SVGTransform();
- SVGTransform(SVGTransformType, ConstructionMode);
- explicit SVGTransform(const AffineTransform&);
- SVGTransform(SVGTransformType,
- float,
- const FloatPoint&,
- const AffineTransform&);
-
SVGTransformType transform_type_;
float angle_;
FloatPoint center_;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform_list.h b/chromium/third_party/blink/renderer/core/svg/svg_transform_list.h
index bad9ad5a722..561f8546d0e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform_list.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform_list.h
@@ -44,10 +44,13 @@ class SVGTransformList final
public:
typedef SVGTransformListTearOff TearOffType;
- static SVGTransformList* Create() { return new SVGTransformList(); }
+ static SVGTransformList* Create() {
+ return MakeGarbageCollected<SVGTransformList>();
+ }
static SVGTransformList* Create(SVGTransformType, const String&);
+ SVGTransformList();
~SVGTransformList() override;
SVGTransform* Consolidate();
@@ -77,8 +80,6 @@ class SVGTransformList final
const CSSValue* CssValue() const;
private:
- SVGTransformList();
-
template <typename CharType>
SVGParsingError ParseInternal(const CharType*& ptr, const CharType* end);
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform_list_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_transform_list_tear_off.h
index 4819715f240..70fcd0a606f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform_list_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform_list_tear_off.h
@@ -49,18 +49,17 @@ class SVGTransformListTearOff final
SVGTransformList* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGTransformListTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGTransformListTearOff>(target, binding,
+ property_is_anim_val);
}
+ SVGTransformListTearOff(SVGTransformList*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
~SVGTransformListTearOff() override;
SVGTransformTearOff* createSVGTransformFromMatrix(SVGMatrixTearOff*) const;
SVGTransformTearOff* consolidate(ExceptionState&);
-
- private:
- SVGTransformListTearOff(SVGTransformList*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform_tear_off.h b/chromium/third_party/blink/renderer/core/svg/svg_transform_tear_off.h
index c9901d9a6ad..2a2c695cc23 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform_tear_off.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform_tear_off.h
@@ -56,11 +56,15 @@ class SVGTransformTearOff final : public SVGPropertyTearOff<SVGTransform> {
SVGTransform* target,
SVGAnimatedPropertyBase* binding,
PropertyIsAnimValType property_is_anim_val) {
- return new SVGTransformTearOff(target, binding, property_is_anim_val);
+ return MakeGarbageCollected<SVGTransformTearOff>(target, binding,
+ property_is_anim_val);
}
static SVGTransformTearOff* CreateDetached();
static SVGTransformTearOff* Create(SVGMatrixTearOff*);
+ SVGTransformTearOff(SVGTransform*,
+ SVGAnimatedPropertyBase* binding,
+ PropertyIsAnimValType);
~SVGTransformTearOff() override;
unsigned short transformType() { return Target()->TransformType(); }
@@ -77,10 +81,6 @@ class SVGTransformTearOff final : public SVGPropertyTearOff<SVGTransform> {
void Trace(blink::Visitor*) override;
private:
- SVGTransformTearOff(SVGTransform*,
- SVGAnimatedPropertyBase* binding,
- PropertyIsAnimValType);
-
Member<SVGMatrixTearOff> matrix_tearoff_;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_tree_scope_resources.cc b/chromium/third_party/blink/renderer/core/svg/svg_tree_scope_resources.cc
index 4fbdf635b12..f4f4d4b74d5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_tree_scope_resources.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_tree_scope_resources.cc
@@ -21,7 +21,7 @@ LocalSVGResource* SVGTreeScopeResources::ResourceForId(const AtomicString& id) {
return nullptr;
auto& entry = resources_.insert(id, nullptr).stored_value->value;
if (!entry)
- entry = new LocalSVGResource(*tree_scope_, id);
+ entry = MakeGarbageCollected<LocalSVGResource>(*tree_scope_, id);
return entry;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.cc
index 1bc48d8d606..7b6047f2ba6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.cc
@@ -26,7 +26,7 @@
namespace blink {
inline SVGTSpanElement::SVGTSpanElement(Document& document)
- : SVGTextPositioningElement(SVGNames::tspanTag, document) {}
+ : SVGTextPositioningElement(svg_names::kTSpanTag, document) {}
DEFINE_NODE_FACTORY(SVGTSpanElement)
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_unit_types.cc b/chromium/third_party/blink/renderer/core/svg/svg_unit_types.cc
index 93f88967d0a..fa37657628d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_unit_types.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_unit_types.cc
@@ -30,18 +30,17 @@
#include "third_party/blink/renderer/core/svg/svg_unit_types.h"
+#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
+
namespace blink {
template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGUnitTypes::SVGUnitType>() {
- DEFINE_STATIC_LOCAL(SVGEnumerationStringEntries, entries, ());
- if (entries.IsEmpty()) {
- entries.push_back(std::make_pair(SVGUnitTypes::kSvgUnitTypeUserspaceonuse,
- "userSpaceOnUse"));
- entries.push_back(std::make_pair(
- SVGUnitTypes::kSvgUnitTypeObjectboundingbox, "objectBoundingBox"));
- }
+const SVGEnumerationMap& GetEnumerationMap<SVGUnitTypes::SVGUnitType>() {
+ static const SVGEnumerationMap::Entry enum_items[] = {
+ {SVGUnitTypes::kSvgUnitTypeUserspaceonuse, "userSpaceOnUse"},
+ {SVGUnitTypes::kSvgUnitTypeObjectboundingbox, "objectBoundingBox"},
+ };
+ static const SVGEnumerationMap entries(enum_items);
return entries;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_unit_types.h b/chromium/third_party/blink/renderer/core/svg/svg_unit_types.h
index 7abf0ef0c15..c15bba841fa 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_unit_types.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_unit_types.h
@@ -40,9 +40,7 @@ class SVGUnitTypes final : public ScriptWrappable {
SVGUnitTypes() = delete; // No instantiation.
};
-template <>
-const SVGEnumerationStringEntries&
-GetStaticStringEntries<SVGUnitTypes::SVGUnitType>();
+DECLARE_SVG_ENUM_MAP(SVGUnitTypes::SVGUnitType);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.cc b/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.cc
index e7a380160f8..bce67926c47 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.cc
@@ -61,9 +61,9 @@ bool SVGURIReference::IsKnownAttribute(const QualifiedName& attr_name) {
const AtomicString& SVGURIReference::LegacyHrefString(
const SVGElement& element) {
- if (element.hasAttribute(SVGNames::hrefAttr))
- return element.getAttribute(SVGNames::hrefAttr);
- return element.getAttribute(XLinkNames::hrefAttr);
+ if (element.hasAttribute(svg_names::kHrefAttr))
+ return element.getAttribute(svg_names::kHrefAttr);
+ return element.getAttribute(xlink_names::kHrefAttr);
}
KURL SVGURIReference::LegacyHrefURL(const Document& document) const {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_use_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_use_element.cc
index 8d2a8427c2c..93c756faa29 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_use_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_use_element.cc
@@ -49,24 +49,24 @@
namespace blink {
inline SVGUseElement::SVGUseElement(Document& document)
- : SVGGraphicsElement(SVGNames::useTag, document),
+ : SVGGraphicsElement(svg_names::kUseTag, document),
SVGURIReference(this),
x_(SVGAnimatedLength::Create(this,
- SVGNames::xAttr,
+ svg_names::kXAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero,
CSSPropertyX)),
y_(SVGAnimatedLength::Create(this,
- SVGNames::yAttr,
+ svg_names::kYAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero,
CSSPropertyY)),
width_(SVGAnimatedLength::Create(this,
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
SVGLengthMode::kWidth,
SVGLength::Initial::kUnitlessZero)),
height_(SVGAnimatedLength::Create(this,
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
SVGLengthMode::kHeight,
SVGLength::Initial::kUnitlessZero)),
element_url_is_local_(true),
@@ -82,7 +82,7 @@ inline SVGUseElement::SVGUseElement(Document& document)
SVGUseElement* SVGUseElement::Create(Document& document) {
// Always build a user agent #shadow-root for SVGUseElement.
- SVGUseElement* use = new SVGUseElement(document);
+ SVGUseElement* use = MakeGarbageCollected<SVGUseElement>(document);
use->AttachShadowRootInternal(ShadowRootType::kClosed);
return use;
}
@@ -150,12 +150,12 @@ static void TransferUseWidthAndHeightIfNeeded(
// width and/or height are not specified, the generated 'svg' element
// will use values of 100% for these attributes.
shadow_element.setAttribute(
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
use.width()->IsSpecified()
? AtomicString(use.width()->CurrentValue()->ValueAsString())
: hundred_percent_string);
shadow_element.setAttribute(
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
use.height()->IsSpecified()
? AtomicString(use.height()->CurrentValue()->ValueAsString())
: hundred_percent_string);
@@ -164,15 +164,15 @@ static void TransferUseWidthAndHeightIfNeeded(
// provided on the 'use' element, then these values will override the
// corresponding attributes on the 'svg' in the generated tree.
shadow_element.setAttribute(
- SVGNames::widthAttr,
+ svg_names::kWidthAttr,
use.width()->IsSpecified()
? AtomicString(use.width()->CurrentValue()->ValueAsString())
- : original_element.getAttribute(SVGNames::widthAttr));
+ : original_element.getAttribute(svg_names::kWidthAttr));
shadow_element.setAttribute(
- SVGNames::heightAttr,
+ svg_names::kHeightAttr,
use.height()->IsSpecified()
? AtomicString(use.height()->CurrentValue()->ValueAsString())
- : original_element.getAttribute(SVGNames::heightAttr));
+ : original_element.getAttribute(svg_names::kHeightAttr));
}
}
@@ -220,11 +220,12 @@ void SVGUseElement::UpdateTargetReference() {
}
void SVGUseElement::SvgAttributeChanged(const QualifiedName& attr_name) {
- if (attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr ||
- attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr) {
+ if (attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr ||
+ attr_name == svg_names::kWidthAttr ||
+ attr_name == svg_names::kHeightAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
- if (attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr) {
+ if (attr_name == svg_names::kXAttr || attr_name == svg_names::kYAttr) {
InvalidateSVGPresentationAttributeStyle();
SetNeedsStyleRecalc(
kLocalStyleChange,
@@ -264,17 +265,19 @@ static bool IsDisallowedElement(const Element& element) {
if (!element.IsSVGElement())
return true;
- DEFINE_STATIC_LOCAL(
- HashSet<QualifiedName>, allowed_element_tags,
- ({
- SVGNames::aTag, SVGNames::circleTag, SVGNames::descTag,
- SVGNames::ellipseTag, SVGNames::gTag, SVGNames::imageTag,
- SVGNames::lineTag, SVGNames::metadataTag, SVGNames::pathTag,
- SVGNames::polygonTag, SVGNames::polylineTag, SVGNames::rectTag,
- SVGNames::svgTag, SVGNames::switchTag, SVGNames::symbolTag,
- SVGNames::textTag, SVGNames::textPathTag, SVGNames::titleTag,
- SVGNames::tspanTag, SVGNames::useTag,
- }));
+ DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowed_element_tags,
+ ({
+ svg_names::kATag, svg_names::kCircleTag,
+ svg_names::kDescTag, svg_names::kEllipseTag,
+ svg_names::kGTag, svg_names::kImageTag,
+ svg_names::kLineTag, svg_names::kMetadataTag,
+ svg_names::kPathTag, svg_names::kPolygonTag,
+ svg_names::kPolylineTag, svg_names::kRectTag,
+ svg_names::kSVGTag, svg_names::kSwitchTag,
+ svg_names::kSymbolTag, svg_names::kTextTag,
+ svg_names::kTextPathTag, svg_names::kTitleTag,
+ svg_names::kTSpanTag, svg_names::kUseTag,
+ }));
return !allowed_element_tags.Contains<SVGAttributeHashTranslator>(
element.TagQName());
}
@@ -577,12 +580,12 @@ bool SVGUseElement::HasCycleUseReferencing(const ContainerNode& target_instance,
// xlink:href are transferred to the generated 'g' element.
static void RemoveAttributesFromReplacementElement(
SVGElement& replacement_element) {
- replacement_element.removeAttribute(SVGNames::xAttr);
- replacement_element.removeAttribute(SVGNames::yAttr);
- replacement_element.removeAttribute(SVGNames::widthAttr);
- replacement_element.removeAttribute(SVGNames::heightAttr);
- replacement_element.removeAttribute(SVGNames::hrefAttr);
- replacement_element.removeAttribute(XLinkNames::hrefAttr);
+ replacement_element.removeAttribute(svg_names::kXAttr);
+ replacement_element.removeAttribute(svg_names::kYAttr);
+ replacement_element.removeAttribute(svg_names::kWidthAttr);
+ replacement_element.removeAttribute(svg_names::kHeightAttr);
+ replacement_element.removeAttribute(svg_names::kHrefAttr);
+ replacement_element.removeAttribute(xlink_names::kHrefAttr);
}
void SVGUseElement::ExpandUseElementsInShadowTree() {
@@ -686,7 +689,7 @@ FloatRect SVGUseElement::GetBBox() {
void SVGUseElement::DispatchPendingEvent() {
DCHECK(IsStructurallyExternal());
DCHECK(have_fired_load_event_);
- DispatchEvent(*Event::Create(EventTypeNames::load));
+ DispatchEvent(*Event::Create(event_type_names::kLoad));
}
void SVGUseElement::NotifyFinished(Resource* resource) {
@@ -696,7 +699,7 @@ void SVGUseElement::NotifyFinished(Resource* resource) {
InvalidateShadowTree();
if (!ResourceIsValid()) {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
} else if (!resource->WasCanceled()) {
if (have_fired_load_event_)
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_use_element.h b/chromium/third_party/blink/renderer/core/svg/svg_use_element.h
index 5e853d81ea8..d7dc58afceb 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_use_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_use_element.h
@@ -40,6 +40,8 @@ class SVGUseElement final : public SVGGraphicsElement,
public:
static SVGUseElement* Create(Document&);
+
+ explicit SVGUseElement(Document&);
~SVGUseElement() override;
void InvalidateShadowTree();
@@ -62,8 +64,6 @@ class SVGUseElement final : public SVGGraphicsElement,
void Trace(blink::Visitor*) override;
private:
- explicit SVGUseElement(Document&);
-
void Dispose();
FloatRect GetBBox() override;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_view_element.cc b/chromium/third_party/blink/renderer/core/svg/svg_view_element.cc
index 0b75e9ad2ab..3406b2b94fe 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_view_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_view_element.cc
@@ -26,7 +26,7 @@
namespace blink {
inline SVGViewElement::SVGViewElement(Document& document)
- : SVGElement(SVGNames::viewTag, document), SVGFitToViewBox(this) {
+ : SVGElement(svg_names::kViewTag, document), SVGFitToViewBox(this) {
UseCounter::Count(document, WebFeature::kSVGViewElement);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_view_spec.cc b/chromium/third_party/blink/renderer/core/svg/svg_view_spec.cc
index 3fff52025ff..7e255936c37 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_view_spec.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_view_spec.cc
@@ -37,21 +37,21 @@ void SVGViewSpec::Trace(Visitor* visitor) {
}
SVGViewSpec* SVGViewSpec::CreateFromFragment(const String& fragment) {
- SVGViewSpec* view_spec = new SVGViewSpec();
+ SVGViewSpec* view_spec = MakeGarbageCollected<SVGViewSpec>();
if (!view_spec->ParseViewSpec(fragment))
return nullptr;
return view_spec;
}
SVGViewSpec* SVGViewSpec::CreateForViewElement(const SVGViewElement& view) {
- SVGViewSpec* view_spec = new SVGViewSpec();
+ SVGViewSpec* view_spec = MakeGarbageCollected<SVGViewSpec>();
if (view.HasValidViewBox())
view_spec->view_box_ = view.viewBox()->CurrentValue()->Clone();
if (view.preserveAspectRatio()->IsSpecified()) {
view_spec->preserve_aspect_ratio_ =
view.preserveAspectRatio()->CurrentValue()->Clone();
}
- if (view.hasAttribute(SVGNames::zoomAndPanAttr))
+ if (view.hasAttribute(svg_names::kZoomAndPanAttr))
view_spec->zoom_and_pan_ = view.zoomAndPan();
return view_spec;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_view_spec.h b/chromium/third_party/blink/renderer/core/svg/svg_view_spec.h
index ff9fa2a4b77..6b8dee6edc7 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_view_spec.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_view_spec.h
@@ -35,6 +35,8 @@ class SVGViewSpec final : public GarbageCollectedFinalized<SVGViewSpec> {
static SVGViewSpec* CreateFromFragment(const String&);
static SVGViewSpec* CreateForViewElement(const SVGViewElement&);
+ SVGViewSpec();
+
const SVGRect* ViewBox() const { return view_box_; }
const SVGPreserveAspectRatio* PreserveAspectRatio() const {
return preserve_aspect_ratio_;
@@ -45,8 +47,6 @@ class SVGViewSpec final : public GarbageCollectedFinalized<SVGViewSpec> {
void Trace(Visitor*);
private:
- SVGViewSpec();
-
bool ParseViewSpec(const String&);
template <typename CharType>
bool ParseViewSpecInternal(const CharType* ptr, const CharType* end);
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_zoom_and_pan.cc b/chromium/third_party/blink/renderer/core/svg/svg_zoom_and_pan.cc
index 5ae806fc7ea..967dff1231f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_zoom_and_pan.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_zoom_and_pan.cc
@@ -28,12 +28,12 @@ namespace blink {
SVGZoomAndPan::SVGZoomAndPan() : zoom_and_pan_(kSVGZoomAndPanMagnify) {}
bool SVGZoomAndPan::IsKnownAttribute(const QualifiedName& attr_name) {
- return attr_name == SVGNames::zoomAndPanAttr;
+ return attr_name == svg_names::kZoomAndPanAttr;
}
bool SVGZoomAndPan::ParseAttribute(const QualifiedName& name,
const AtomicString& value) {
- if (name != SVGNames::zoomAndPanAttr)
+ if (name != svg_names::kZoomAndPanAttr)
return false;
zoom_and_pan_ = kSVGZoomAndPanUnknown;
if (!value.IsEmpty()) {
diff --git a/chromium/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc b/chromium/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc
index 9f003f031bc..f046a182192 100644
--- a/chromium/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc
+++ b/chromium/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc
@@ -59,7 +59,7 @@ String ContentAfterPastingHTML(DummyPageHolder* page_holder,
HTMLElement* body = page_holder->GetDocument().body();
// Make the body editable, and put the caret in it.
- body->setAttribute(HTMLNames::contenteditableAttr, "true");
+ body->setAttribute(html_names::kContenteditableAttr, "true");
body->focus();
frame.GetDocument()->UpdateStyleAndLayout();
frame.Selection().SetSelectionAndEndTyping(
@@ -277,14 +277,14 @@ TEST(UnsafeSVGAttributeSanitizationTest, stringsShouldNotSupportAddition) {
SVGElement* target = SVGAElement::Create(*document);
SVGAnimateElement* element = SVGAnimateElement::Create(*document);
element->SetTargetElement(target);
- element->SetAttributeName(XLinkNames::hrefAttr);
+ element->SetAttributeName(xlink_names::kHrefAttr);
// Sanity check that xlink:href was identified as a "string" attribute
EXPECT_EQ(kAnimatedString, element->GetAnimatedPropertyType());
EXPECT_FALSE(element->AnimatedPropertyTypeSupportsAddition());
- element->SetAttributeName(SVGNames::hrefAttr);
+ element->SetAttributeName(svg_names::kHrefAttr);
// Sanity check that href was identified as a "string" attribute
EXPECT_EQ(kAnimatedString, element->GetAnimatedPropertyType());
@@ -295,10 +295,10 @@ TEST(UnsafeSVGAttributeSanitizationTest, stringsShouldNotSupportAddition) {
TEST(UnsafeSVGAttributeSanitizationTest,
stripScriptingAttributes_animateElement) {
Vector<Attribute> attributes;
- attributes.push_back(Attribute(XLinkNames::hrefAttr, "javascript:alert()"));
- attributes.push_back(Attribute(SVGNames::hrefAttr, "javascript:alert()"));
- attributes.push_back(Attribute(SVGNames::fromAttr, "/home"));
- attributes.push_back(Attribute(SVGNames::toAttr, "javascript:own3d()"));
+ attributes.push_back(Attribute(xlink_names::kHrefAttr, "javascript:alert()"));
+ attributes.push_back(Attribute(svg_names::kHrefAttr, "javascript:alert()"));
+ attributes.push_back(Attribute(svg_names::kFromAttr, "/home"));
+ attributes.push_back(Attribute(svg_names::kToAttr, "javascript:own3d()"));
Document* document = Document::CreateForTest();
Element* element = SVGAnimateElement::Create(*document);
@@ -306,20 +306,20 @@ TEST(UnsafeSVGAttributeSanitizationTest,
EXPECT_EQ(3ul, attributes.size())
<< "One of the attributes should have been stripped.";
- EXPECT_EQ(XLinkNames::hrefAttr, attributes[0].GetName())
+ EXPECT_EQ(xlink_names::kHrefAttr, attributes[0].GetName())
<< "The 'xlink:href' attribute should not have been stripped from "
"<animate> because it is not a URL attribute of <animate>.";
- EXPECT_EQ(SVGNames::hrefAttr, attributes[1].GetName())
+ EXPECT_EQ(svg_names::kHrefAttr, attributes[1].GetName())
<< "The 'href' attribute should not have been stripped from "
"<animate> because it is not a URL attribute of <animate>.";
- EXPECT_EQ(SVGNames::fromAttr, attributes[2].GetName())
+ EXPECT_EQ(svg_names::kFromAttr, attributes[2].GetName())
<< "The 'from' attribute should not have been strippef from <animate> "
"because its value is innocuous.";
}
TEST(UnsafeSVGAttributeSanitizationTest,
isJavaScriptURLAttribute_hrefContainingJavascriptURL) {
- Attribute attribute(SVGNames::hrefAttr, "javascript:alert()");
+ Attribute attribute(svg_names::kHrefAttr, "javascript:alert()");
Document* document = Document::CreateForTest();
Element* element = SVGAElement::Create(*document);
EXPECT_TRUE(element->IsJavaScriptURLAttribute(attribute))
@@ -329,7 +329,7 @@ TEST(UnsafeSVGAttributeSanitizationTest,
TEST(UnsafeSVGAttributeSanitizationTest,
isJavaScriptURLAttribute_xlinkHrefContainingJavascriptURL) {
- Attribute attribute(XLinkNames::hrefAttr, "javascript:alert()");
+ Attribute attribute(xlink_names::kHrefAttr, "javascript:alert()");
Document* document = Document::CreateForTest();
Element* element = SVGAElement::Create(*document);
EXPECT_TRUE(element->IsJavaScriptURLAttribute(attribute))
@@ -341,7 +341,7 @@ TEST(
UnsafeSVGAttributeSanitizationTest,
isJavaScriptURLAttribute_xlinkHrefContainingJavascriptURL_alternatePrefix) {
QualifiedName href_alternate_prefix("foo", "href",
- XLinkNames::xlinkNamespaceURI);
+ xlink_names::kNamespaceURI);
Attribute evil_attribute(href_alternate_prefix, "javascript:alert()");
Document* document = Document::CreateForTest();
Element* element = SVGAElement::Create(*document);
@@ -353,7 +353,7 @@ TEST(
TEST(UnsafeSVGAttributeSanitizationTest,
isSVGAnimationAttributeSettingJavaScriptURL_fromContainingJavaScriptURL) {
- Attribute evil_attribute(SVGNames::fromAttr, "javascript:alert()");
+ Attribute evil_attribute(svg_names::kFromAttr, "javascript:alert()");
Document* document = Document::CreateForTest();
Element* element = SVGAnimateElement::Create(*document);
EXPECT_TRUE(
@@ -364,7 +364,7 @@ TEST(UnsafeSVGAttributeSanitizationTest,
TEST(UnsafeSVGAttributeSanitizationTest,
isSVGAnimationAttributeSettingJavaScriptURL_toContainingJavaScripURL) {
- Attribute evil_attribute(SVGNames::toAttr, "javascript:window.close()");
+ Attribute evil_attribute(svg_names::kToAttr, "javascript:window.close()");
Document* document = Document::CreateForTest();
Element* element = SVGSetElement::Create(*document);
EXPECT_TRUE(
@@ -376,7 +376,7 @@ TEST(UnsafeSVGAttributeSanitizationTest,
TEST(
UnsafeSVGAttributeSanitizationTest,
isSVGAnimationAttributeSettingJavaScriptURL_valuesContainingJavaScriptURL) {
- Attribute evil_attribute(SVGNames::valuesAttr, "hi!; javascript:confirm()");
+ Attribute evil_attribute(svg_names::kValuesAttr, "hi!; javascript:confirm()");
Document* document = Document::CreateForTest();
Element* element = SVGAnimateElement::Create(*document);
element = SVGAnimateElement::Create(*document);
@@ -388,7 +388,7 @@ TEST(
TEST(UnsafeSVGAttributeSanitizationTest,
isSVGAnimationAttributeSettingJavaScriptURL_innocuousAnimationAttribute) {
- Attribute fine_attribute(SVGNames::fromAttr, "hello, world!");
+ Attribute fine_attribute(svg_names::kFromAttr, "hello, world!");
Document* document = Document::CreateForTest();
Element* element = SVGSetElement::Create(*document);
EXPECT_FALSE(
diff --git a/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.cc b/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.cc
index b85216bc812..845c060807e 100644
--- a/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.cc
+++ b/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.cc
@@ -73,7 +73,7 @@ void RenderingTest::SetUp() {
// This ensures that the minimal DOM tree gets attached
// correctly for tests that don't call setBodyInnerHTML.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Allow ASSERT_DEATH and EXPECT_DEATH for multiple threads.
testing::FLAGS_gtest_death_test_style = "threadsafe";
diff --git a/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.h b/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.h
index 2f2c44d9a99..fa88fc9226c 100644
--- a/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.h
+++ b/chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.h
@@ -14,19 +14,25 @@
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/core/testing/use_mock_scrollbar_settings.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
+class PaintLayer;
+
class SingleChildLocalFrameClient final : public EmptyLocalFrameClient {
public:
static SingleChildLocalFrameClient* Create() {
- return new SingleChildLocalFrameClient();
+ return MakeGarbageCollected<SingleChildLocalFrameClient>();
}
+ explicit SingleChildLocalFrameClient() = default;
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(child_);
EmptyLocalFrameClient::Trace(visitor);
@@ -40,17 +46,17 @@ class SingleChildLocalFrameClient final : public EmptyLocalFrameClient {
void DidDetachChild() { child_ = nullptr; }
private:
- explicit SingleChildLocalFrameClient() = default;
-
Member<LocalFrame> child_;
};
class LocalFrameClientWithParent final : public EmptyLocalFrameClient {
public:
static LocalFrameClientWithParent* Create(LocalFrame* parent) {
- return new LocalFrameClientWithParent(parent);
+ return MakeGarbageCollected<LocalFrameClientWithParent>(parent);
}
+ explicit LocalFrameClientWithParent(LocalFrame* parent) : parent_(parent) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(parent_);
EmptyLocalFrameClient::Trace(visitor);
@@ -62,8 +68,6 @@ class LocalFrameClientWithParent final : public EmptyLocalFrameClient {
LocalFrame* Top() const override { return parent_.Get(); }
private:
- explicit LocalFrameClientWithParent(LocalFrame* parent) : parent_(parent) {}
-
Member<LocalFrame> parent_;
};
@@ -98,10 +102,12 @@ class RenderingTest : public PageTestBase, public UseMockScrollbarSettings {
// Both enables compositing and runs the document lifecycle.
void EnableCompositing() {
+ // This Page is not actually being shown by a compositor, but we act like it
+ // will in order to test behaviour.
GetPage().GetSettings().SetAcceleratedCompositingEnabled(true);
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
LayoutObject* GetLayoutObjectByElementId(const char* id) const {
@@ -109,6 +115,22 @@ class RenderingTest : public PageTestBase, public UseMockScrollbarSettings {
return element ? element->GetLayoutObject() : nullptr;
}
+ PaintLayer* GetPaintLayerByElementId(const char* id) {
+ return ToLayoutBoxModelObject(GetLayoutObjectByElementId(id))->Layer();
+ }
+
+ DisplayItemClient* GetDisplayItemClientFromLayoutObject(
+ LayoutObject* obj) const {
+ LayoutNGBlockFlow* block_flow = ToLayoutNGBlockFlowOrNull(obj);
+ if (block_flow && block_flow->PaintFragment())
+ return block_flow->PaintFragment();
+ return obj;
+ }
+
+ DisplayItemClient* GetDisplayItemClientFromElementId(const char* id) const {
+ return GetDisplayItemClientFromLayoutObject(GetLayoutObjectByElementId(id));
+ }
+
private:
Persistent<LocalFrameClient> local_frame_client_;
};
diff --git a/chromium/third_party/blink/renderer/core/testing/data/composited_selection_bounds_vertical_rl.html b/chromium/third_party/blink/renderer/core/testing/data/composited_selection_bounds_vertical_rl.html
index 3ddfb245d34..3c252fb2e2d 100644
--- a/chromium/third_party/blink/renderer/core/testing/data/composited_selection_bounds_vertical_rl.html
+++ b/chromium/third_party/blink/renderer/core/testing/data/composited_selection_bounds_vertical_rl.html
@@ -1,3 +1,4 @@
+<!doctype html>
<style>
@font-face {
font-family: ahem;
diff --git a/chromium/third_party/blink/renderer/core/testing/data/longpress_image_contenteditable.html b/chromium/third_party/blink/renderer/core/testing/data/longpress_image_contenteditable.html
index b8d3622a6a6..371b400916b 100644
--- a/chromium/third_party/blink/renderer/core/testing/data/longpress_image_contenteditable.html
+++ b/chromium/third_party/blink/renderer/core/testing/data/longpress_image_contenteditable.html
@@ -9,7 +9,7 @@ span {
</head>
<body>
<div id="textbox" contenteditable="true">
-<img id="purpleimage" style="-webkit-logical-width:20px;-webkit-logical-height:100px;background-color:purple">
+<img id="purpleimage" style="inline-size:20px;block-size:100px;background-color:purple">
</div>
</body>
diff --git a/chromium/third_party/blink/renderer/core/testing/data/plugin_hidden_before_scroll.html b/chromium/third_party/blink/renderer/core/testing/data/plugin_hidden_before_scroll.html
new file mode 100644
index 00000000000..b3732ee5b28
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/data/plugin_hidden_before_scroll.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <style type="text/css">
+ body { margin: 0; padding: 0; }
+ </style>
+</head>
+<body>
+ <div style="width: 40px; height: 40px"></div>
+ <object id="plugin-hidden-before-scroll"
+ border=0
+ type="application/x-webkit-test-webplugin"
+ width="40"
+ height="40">
+ </object>
+ <div style="width: 40px; height: 40px"></div>
+</body>
+</html>
diff --git a/chromium/third_party/blink/renderer/core/testing/data/shifted_plugin_containing_page.html b/chromium/third_party/blink/renderer/core/testing/data/shifted_plugin_containing_page.html
new file mode 100644
index 00000000000..8040c78dc48
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/data/shifted_plugin_containing_page.html
@@ -0,0 +1,19 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <style type="text/css">
+ body { margin: 0; padding: 0; }
+ </style>
+</head>
+<body>
+ <div style="width: 200px; height: 100vh"></div>
+ <iframe
+ src="plugin_hidden_before_scroll.html"
+ id="iframe-with-plugin"
+ height="40"
+ width="40"
+ frameBorder="0">
+ </iframe>
+ <div style="width: 200px; height: 100vh"></div>
+</body>
+</html>
diff --git a/chromium/third_party/blink/renderer/core/testing/death_aware_script_wrappable.h b/chromium/third_party/blink/renderer/core/testing/death_aware_script_wrappable.h
index 266d3502c43..4105e8f726e 100644
--- a/chromium/third_party/blink/renderer/core/testing/death_aware_script_wrappable.h
+++ b/chromium/third_party/blink/renderer/core/testing/death_aware_script_wrappable.h
@@ -45,7 +45,7 @@ class DeathAwareScriptWrappable : public ScriptWrappable {
typedef TraceWrapperMember<DeathAwareScriptWrappable> Wrapper;
static DeathAwareScriptWrappable* Create() {
- return new DeathAwareScriptWrappable();
+ return MakeGarbageCollected<DeathAwareScriptWrappable>();
}
static bool HasDied() { return has_died_; }
@@ -54,6 +54,7 @@ class DeathAwareScriptWrappable : public ScriptWrappable {
instance_ = instance;
}
+ DeathAwareScriptWrappable() = default;
~DeathAwareScriptWrappable() override {
if (this == instance_) {
has_died_ = true;
@@ -86,8 +87,6 @@ class DeathAwareScriptWrappable : public ScriptWrappable {
}
private:
- DeathAwareScriptWrappable() = default;
-
Wrapper wrapped_dependency_;
HeapVector<Wrapper> wrapped_vector_dependency_;
HeapHashMap<Wrapper, Wrapper> wrapped_hash_map_dependency_;
diff --git a/chromium/third_party/blink/renderer/core/testing/dictionary_test.cc b/chromium/third_party/blink/renderer/core/testing/dictionary_test.cc
index a8f5e173e41..3f725f36690 100644
--- a/chromium/third_party/blink/renderer/core/testing/dictionary_test.cc
+++ b/chromium/third_party/blink/renderer/core/testing/dictionary_test.cc
@@ -39,124 +39,80 @@ DictionaryTest::DictionaryTest() : required_boolean_member_(false) {}
DictionaryTest::~DictionaryTest() = default;
-void DictionaryTest::set(const InternalDictionary& testing_dictionary) {
+void DictionaryTest::set(const InternalDictionary* testing_dictionary) {
Reset();
- if (testing_dictionary.hasLongMember())
- long_member_ = testing_dictionary.longMember();
- if (testing_dictionary.hasLongMemberWithClamp())
- long_member_with_clamp_ = testing_dictionary.longMemberWithClamp();
- if (testing_dictionary.hasLongMemberWithEnforceRange())
+ if (testing_dictionary->hasLongMember())
+ long_member_ = testing_dictionary->longMember();
+ if (testing_dictionary->hasLongMemberWithClamp())
+ long_member_with_clamp_ = testing_dictionary->longMemberWithClamp();
+ if (testing_dictionary->hasLongMemberWithEnforceRange()) {
long_member_with_enforce_range_ =
- testing_dictionary.longMemberWithEnforceRange();
- long_member_with_default_ = testing_dictionary.longMemberWithDefault();
- if (testing_dictionary.hasLongOrNullMember())
- long_or_null_member_ = testing_dictionary.longOrNullMember();
+ testing_dictionary->longMemberWithEnforceRange();
+ }
+ long_member_with_default_ = testing_dictionary->longMemberWithDefault();
+ if (testing_dictionary->hasLongOrNullMember())
+ long_or_null_member_ = testing_dictionary->longOrNullMember();
// |longOrNullMemberWithDefault| has a default value but can be null, so
// we need to check availability.
- if (testing_dictionary.hasLongOrNullMemberWithDefault())
+ if (testing_dictionary->hasLongOrNullMemberWithDefault()) {
long_or_null_member_with_default_ =
- testing_dictionary.longOrNullMemberWithDefault();
- if (testing_dictionary.hasBooleanMember())
- boolean_member_ = testing_dictionary.booleanMember();
- if (testing_dictionary.hasDoubleMember())
- double_member_ = testing_dictionary.doubleMember();
- if (testing_dictionary.hasUnrestrictedDoubleMember())
- unrestricted_double_member_ = testing_dictionary.unrestrictedDoubleMember();
- string_member_ = testing_dictionary.stringMember();
- string_member_with_default_ = testing_dictionary.stringMemberWithDefault();
- byte_string_member_ = testing_dictionary.byteStringMember();
- usv_string_member_ = testing_dictionary.usvStringMember();
- if (testing_dictionary.hasStringSequenceMember())
- string_sequence_member_ = testing_dictionary.stringSequenceMember();
+ testing_dictionary->longOrNullMemberWithDefault();
+ }
+ if (testing_dictionary->hasBooleanMember())
+ boolean_member_ = testing_dictionary->booleanMember();
+ if (testing_dictionary->hasDoubleMember())
+ double_member_ = testing_dictionary->doubleMember();
+ if (testing_dictionary->hasUnrestrictedDoubleMember()) {
+ unrestricted_double_member_ =
+ testing_dictionary->unrestrictedDoubleMember();
+ }
+ string_member_ = testing_dictionary->stringMember();
+ string_member_with_default_ = testing_dictionary->stringMemberWithDefault();
+ byte_string_member_ = testing_dictionary->byteStringMember();
+ usv_string_member_ = testing_dictionary->usvStringMember();
+ if (testing_dictionary->hasStringSequenceMember())
+ string_sequence_member_ = testing_dictionary->stringSequenceMember();
string_sequence_member_with_default_ =
- testing_dictionary.stringSequenceMemberWithDefault();
- if (testing_dictionary.hasStringSequenceOrNullMember())
+ testing_dictionary->stringSequenceMemberWithDefault();
+ if (testing_dictionary->hasStringSequenceOrNullMember()) {
string_sequence_or_null_member_ =
- testing_dictionary.stringSequenceOrNullMember();
- enum_member_ = testing_dictionary.enumMember();
- enum_member_with_default_ = testing_dictionary.enumMemberWithDefault();
- enum_or_null_member_ = testing_dictionary.enumOrNullMember();
- if (testing_dictionary.hasElementMember())
- element_member_ = testing_dictionary.elementMember();
- if (testing_dictionary.hasElementOrNullMember())
- element_or_null_member_ = testing_dictionary.elementOrNullMember();
- object_member_ = testing_dictionary.objectMember();
+ testing_dictionary->stringSequenceOrNullMember();
+ }
+ enum_member_ = testing_dictionary->enumMember();
+ enum_member_with_default_ = testing_dictionary->enumMemberWithDefault();
+ enum_or_null_member_ = testing_dictionary->enumOrNullMember();
+ if (testing_dictionary->hasElementMember())
+ element_member_ = testing_dictionary->elementMember();
+ if (testing_dictionary->hasElementOrNullMember())
+ element_or_null_member_ = testing_dictionary->elementOrNullMember();
+ object_member_ = testing_dictionary->objectMember();
object_or_null_member_with_default_ =
- testing_dictionary.objectOrNullMemberWithDefault();
- if (testing_dictionary.hasDoubleOrStringMember())
- double_or_string_member_ = testing_dictionary.doubleOrStringMember();
- if (testing_dictionary.hasDoubleOrStringSequenceMember())
+ testing_dictionary->objectOrNullMemberWithDefault();
+ if (testing_dictionary->hasDoubleOrStringMember())
+ double_or_string_member_ = testing_dictionary->doubleOrStringMember();
+ if (testing_dictionary->hasDoubleOrStringSequenceMember()) {
double_or_string_sequence_member_ =
- testing_dictionary.doubleOrStringSequenceMember();
- event_target_or_null_member_ = testing_dictionary.eventTargetOrNullMember();
- if (testing_dictionary.hasDictionaryMember()) {
+ testing_dictionary->doubleOrStringSequenceMember();
+ }
+ event_target_or_null_member_ = testing_dictionary->eventTargetOrNullMember();
+ if (testing_dictionary->hasDictionaryMember()) {
NonThrowableExceptionState exception_state;
dictionary_member_properties_ =
- testing_dictionary.dictionaryMember().GetOwnPropertiesAsStringHashMap(
+ testing_dictionary->dictionaryMember().GetOwnPropertiesAsStringHashMap(
exception_state);
}
- if (testing_dictionary.hasInternalEnumOrInternalEnumSequenceMember()) {
+ if (testing_dictionary->hasInternalEnumOrInternalEnumSequenceMember()) {
internal_enum_or_internal_enum_sequence_ =
- testing_dictionary.internalEnumOrInternalEnumSequenceMember();
+ testing_dictionary->internalEnumOrInternalEnumSequenceMember();
}
- any_member_ = testing_dictionary.anyMember();
- callback_function_member_ = testing_dictionary.callbackFunctionMember();
+ any_member_ = testing_dictionary->anyMember();
+ callback_function_member_ = testing_dictionary->callbackFunctionMember();
}
-void DictionaryTest::get(InternalDictionary& result) {
- if (long_member_)
- result.setLongMember(long_member_.value());
- if (long_member_with_clamp_)
- result.setLongMemberWithClamp(long_member_with_clamp_.value());
- if (long_member_with_enforce_range_) {
- result.setLongMemberWithEnforceRange(
- long_member_with_enforce_range_.value());
- }
- result.setLongMemberWithDefault(long_member_with_default_);
- if (long_or_null_member_)
- result.setLongOrNullMember(long_or_null_member_.value());
- if (long_or_null_member_with_default_) {
- result.setLongOrNullMemberWithDefault(
- long_or_null_member_with_default_.value());
- }
- if (boolean_member_)
- result.setBooleanMember(boolean_member_.value());
- if (double_member_)
- result.setDoubleMember(double_member_.value());
- if (unrestricted_double_member_)
- result.setUnrestrictedDoubleMember(unrestricted_double_member_.value());
- result.setStringMember(string_member_);
- result.setStringMemberWithDefault(string_member_with_default_);
- result.setByteStringMember(byte_string_member_);
- result.setUsvStringMember(usv_string_member_);
- if (string_sequence_member_)
- result.setStringSequenceMember(string_sequence_member_.value());
- result.setStringSequenceMemberWithDefault(
- string_sequence_member_with_default_);
- if (string_sequence_or_null_member_) {
- result.setStringSequenceOrNullMember(
- string_sequence_or_null_member_.value());
- }
- result.setEnumMember(enum_member_);
- result.setEnumMemberWithDefault(enum_member_with_default_);
- result.setEnumOrNullMember(enum_or_null_member_);
- if (element_member_)
- result.setElementMember(element_member_);
- if (element_or_null_member_.has_value())
- result.setElementOrNullMember(element_or_null_member_.value());
- result.setObjectMember(object_member_);
- result.setObjectOrNullMemberWithDefault(object_or_null_member_with_default_);
- if (!double_or_string_member_.IsNull())
- result.setDoubleOrStringMember(double_or_string_member_);
- if (double_or_string_sequence_member_) {
- result.setDoubleOrStringSequenceMember(
- double_or_string_sequence_member_.value());
- }
- result.setEventTargetOrNullMember(event_target_or_null_member_);
- result.setInternalEnumOrInternalEnumSequenceMember(
- internal_enum_or_internal_enum_sequence_);
- result.setAnyMember(any_member_);
- result.setCallbackFunctionMember(callback_function_member_);
+InternalDictionary* DictionaryTest::get() {
+ InternalDictionary* result = InternalDictionary::Create();
+ GetInternals(result);
+ return result;
}
ScriptValue DictionaryTest::getDictionaryMemberProperties(
@@ -171,34 +127,34 @@ ScriptValue DictionaryTest::getDictionaryMemberProperties(
return builder.GetScriptValue();
}
-void DictionaryTest::setDerived(const InternalDictionaryDerived& derived) {
- DCHECK(derived.hasRequiredBooleanMember());
+void DictionaryTest::setDerived(const InternalDictionaryDerived* derived) {
+ DCHECK(derived->hasRequiredBooleanMember());
set(derived);
- if (derived.hasDerivedStringMember())
- derived_string_member_ = derived.derivedStringMember();
+ if (derived->hasDerivedStringMember())
+ derived_string_member_ = derived->derivedStringMember();
derived_string_member_with_default_ =
- derived.derivedStringMemberWithDefault();
- required_boolean_member_ = derived.requiredBooleanMember();
+ derived->derivedStringMemberWithDefault();
+ required_boolean_member_ = derived->requiredBooleanMember();
}
-void DictionaryTest::getDerived(InternalDictionaryDerived& result) {
- get(result);
- result.setDerivedStringMember(derived_string_member_);
- result.setDerivedStringMemberWithDefault(derived_string_member_with_default_);
- result.setRequiredBooleanMember(required_boolean_member_);
+InternalDictionaryDerived* DictionaryTest::getDerived() {
+ InternalDictionaryDerived* result = InternalDictionaryDerived::Create();
+ GetDerivedInternals(result);
+ return result;
}
void DictionaryTest::setDerivedDerived(
- const InternalDictionaryDerivedDerived& derived) {
+ const InternalDictionaryDerivedDerived* derived) {
setDerived(derived);
- if (derived.hasDerivedDerivedStringMember())
- derived_derived_string_member_ = derived.derivedDerivedStringMember();
+ if (derived->hasDerivedDerivedStringMember())
+ derived_derived_string_member_ = derived->derivedDerivedStringMember();
}
-void DictionaryTest::getDerivedDerived(
- InternalDictionaryDerivedDerived& result) {
- getDerived(result);
- result.setDerivedDerivedStringMember(derived_derived_string_member_);
+InternalDictionaryDerivedDerived* DictionaryTest::getDerivedDerived() {
+ InternalDictionaryDerivedDerived* result =
+ InternalDictionaryDerivedDerived::Create();
+ GetDerivedDerivedInternals(result);
+ return result;
}
String DictionaryTest::stringFromIterable(
@@ -263,6 +219,79 @@ void DictionaryTest::Reset() {
callback_function_member_ = nullptr;
}
+void DictionaryTest::GetInternals(InternalDictionary* dict) {
+ DCHECK(dict);
+
+ if (long_member_)
+ dict->setLongMember(long_member_.value());
+ if (long_member_with_clamp_)
+ dict->setLongMemberWithClamp(long_member_with_clamp_.value());
+ if (long_member_with_enforce_range_) {
+ dict->setLongMemberWithEnforceRange(
+ long_member_with_enforce_range_.value());
+ }
+ dict->setLongMemberWithDefault(long_member_with_default_);
+ if (long_or_null_member_)
+ dict->setLongOrNullMember(long_or_null_member_.value());
+ if (long_or_null_member_with_default_) {
+ dict->setLongOrNullMemberWithDefault(
+ long_or_null_member_with_default_.value());
+ }
+ if (boolean_member_)
+ dict->setBooleanMember(boolean_member_.value());
+ if (double_member_)
+ dict->setDoubleMember(double_member_.value());
+ if (unrestricted_double_member_)
+ dict->setUnrestrictedDoubleMember(unrestricted_double_member_.value());
+ dict->setStringMember(string_member_);
+ dict->setStringMemberWithDefault(string_member_with_default_);
+ dict->setByteStringMember(byte_string_member_);
+ dict->setUsvStringMember(usv_string_member_);
+ if (string_sequence_member_)
+ dict->setStringSequenceMember(string_sequence_member_.value());
+ dict->setStringSequenceMemberWithDefault(
+ string_sequence_member_with_default_);
+ if (string_sequence_or_null_member_) {
+ dict->setStringSequenceOrNullMember(
+ string_sequence_or_null_member_.value());
+ }
+ dict->setEnumMember(enum_member_);
+ dict->setEnumMemberWithDefault(enum_member_with_default_);
+ dict->setEnumOrNullMember(enum_or_null_member_);
+ if (element_member_)
+ dict->setElementMember(element_member_);
+ if (element_or_null_member_.has_value())
+ dict->setElementOrNullMember(element_or_null_member_.value());
+ dict->setObjectMember(object_member_);
+ dict->setObjectOrNullMemberWithDefault(object_or_null_member_with_default_);
+ if (!double_or_string_member_.IsNull())
+ dict->setDoubleOrStringMember(double_or_string_member_);
+ if (double_or_string_sequence_member_) {
+ dict->setDoubleOrStringSequenceMember(
+ double_or_string_sequence_member_.value());
+ }
+ dict->setEventTargetOrNullMember(event_target_or_null_member_);
+ dict->setInternalEnumOrInternalEnumSequenceMember(
+ internal_enum_or_internal_enum_sequence_);
+ dict->setAnyMember(any_member_);
+ dict->setCallbackFunctionMember(callback_function_member_);
+}
+
+void DictionaryTest::GetDerivedInternals(InternalDictionaryDerived* dict) {
+ GetInternals(dict);
+
+ dict->setDerivedStringMember(derived_string_member_);
+ dict->setDerivedStringMemberWithDefault(derived_string_member_with_default_);
+ dict->setRequiredBooleanMember(required_boolean_member_);
+}
+
+void DictionaryTest::GetDerivedDerivedInternals(
+ InternalDictionaryDerivedDerived* dict) {
+ GetDerivedInternals(dict);
+
+ dict->setDerivedDerivedStringMember(derived_derived_string_member_);
+}
+
void DictionaryTest::Trace(blink::Visitor* visitor) {
visitor->Trace(element_member_);
visitor->Trace(element_or_null_member_);
diff --git a/chromium/third_party/blink/renderer/core/testing/dictionary_test.h b/chromium/third_party/blink/renderer/core/testing/dictionary_test.h
index eb66e37b4d1..12e47efa64f 100644
--- a/chromium/third_party/blink/renderer/core/testing/dictionary_test.h
+++ b/chromium/third_party/blink/renderer/core/testing/dictionary_test.h
@@ -27,22 +27,26 @@ class DictionaryTest : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DictionaryTest* Create() { return new DictionaryTest(); }
+ static DictionaryTest* Create() {
+ return MakeGarbageCollected<DictionaryTest>();
+ }
+
+ DictionaryTest();
~DictionaryTest() override;
// Stores all members into corresponding fields
- void set(const InternalDictionary&);
+ void set(const InternalDictionary*);
// Sets each member of the given TestDictionary from fields
- void get(InternalDictionary&);
+ InternalDictionary* get();
// Returns properties of the latest |dictionaryMember| which was set via
// set().
ScriptValue getDictionaryMemberProperties(ScriptState*);
- void setDerived(const InternalDictionaryDerived&);
- void getDerived(InternalDictionaryDerived&);
+ void setDerived(const InternalDictionaryDerived*);
+ InternalDictionaryDerived* getDerived();
- void setDerivedDerived(const InternalDictionaryDerivedDerived&);
- void getDerivedDerived(InternalDictionaryDerivedDerived&);
+ void setDerivedDerived(const InternalDictionaryDerivedDerived*);
+ InternalDictionaryDerivedDerived* getDerivedDerived();
String stringFromIterable(ScriptState*,
Dictionary iterable,
@@ -51,10 +55,12 @@ class DictionaryTest : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- DictionaryTest();
-
void Reset();
+ void GetInternals(InternalDictionary*);
+ void GetDerivedInternals(InternalDictionaryDerived*);
+ void GetDerivedDerivedInternals(InternalDictionaryDerivedDerived*);
+
// The reason to use base::Optional<T> is convenience; we use
// base::Optional<T> here to record whether the member field is set or not.
// Some members are not wrapped with Optional because:
diff --git a/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.cc b/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.cc
index 86938f58a2e..8c9bfdb5aab 100644
--- a/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.cc
+++ b/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.cc
@@ -64,9 +64,6 @@ DummyPageHolder::DummyPageHolder(
page_clients.chrome_client = page_clients_argument->chrome_client;
page_ = Page::Create(page_clients);
Settings& settings = page_->GetSettings();
- // FIXME: http://crbug.com/363843. This needs to find a better way to
- // not create graphics layers.
- settings.SetAcceleratedCompositingEnabled(false);
if (setting_overrider)
(*setting_overrider)(settings);
diff --git a/chromium/third_party/blink/renderer/core/exported/fake_web_plugin.cc b/chromium/third_party/blink/renderer/core/testing/fake_web_plugin.cc
index 9d45b4e2e48..8de79779f0c 100644
--- a/chromium/third_party/blink/renderer/core/exported/fake_web_plugin.cc
+++ b/chromium/third_party/blink/renderer/core/testing/fake_web_plugin.cc
@@ -28,7 +28,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/exported/fake_web_plugin.h"
+#include "third_party/blink/renderer/core/testing/fake_web_plugin.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/exported/fake_web_plugin.h b/chromium/third_party/blink/renderer/core/testing/fake_web_plugin.h
index 70b56534a8b..9866bd5ab1c 100644
--- a/chromium/third_party/blink/renderer/core/exported/fake_web_plugin.h
+++ b/chromium/third_party/blink/renderer/core/testing/fake_web_plugin.h
@@ -28,8 +28,8 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_FAKE_WEB_PLUGIN_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_FAKE_WEB_PLUGIN_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_FAKE_WEB_PLUGIN_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_FAKE_WEB_PLUGIN_H_
#include "third_party/blink/public/web/web_plugin.h"
@@ -53,7 +53,7 @@ class FakeWebPlugin : public WebPlugin {
bool Initialize(WebPluginContainer*) override;
void Destroy() override;
bool CanProcessDrag() const override { return false; }
- void UpdateAllLifecyclePhases() override {}
+ void UpdateAllLifecyclePhases(WebWidget::LifecycleUpdateReason) override {}
void Paint(cc::PaintCanvas*, const WebRect&) override {}
void UpdateGeometry(const WebRect& client_rect,
const WebRect& clip_rect,
@@ -89,4 +89,4 @@ class FakeWebPlugin : public WebPlugin {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_FAKE_WEB_PLUGIN_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_FAKE_WEB_PLUGIN_H_
diff --git a/chromium/third_party/blink/renderer/core/testing/gc_observation.cc b/chromium/third_party/blink/renderer/core/testing/gc_observation.cc
index b1bc1f36eac..afae82a356b 100644
--- a/chromium/third_party/blink/renderer/core/testing/gc_observation.cc
+++ b/chromium/third_party/blink/renderer/core/testing/gc_observation.cc
@@ -32,20 +32,10 @@
namespace blink {
-static void SetWeakCallbackForGCObservation(
- const v8::WeakCallbackInfo<GCObservation>& data) {
- data.GetParameter()->SetWasCollected();
-}
-
-void GCObservation::SetWasCollected() {
- DCHECK(!wasCollected());
- observed_.Clear();
- collected_ = true;
-}
-
GCObservation::GCObservation(v8::Local<v8::Value> observed_value)
- : observed_(v8::Isolate::GetCurrent(), observed_value), collected_(false) {
- observed_.SetWeak(this, SetWeakCallbackForGCObservation);
+ : observed_(v8::Isolate::GetCurrent(), observed_value) {
+ CHECK(!wasCollected());
+ observed_.SetPhantom();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/gc_observation.h b/chromium/third_party/blink/renderer/core/testing/gc_observation.h
index e5512a24ee1..63454ee9078 100644
--- a/chromium/third_party/blink/renderer/core/testing/gc_observation.h
+++ b/chromium/third_party/blink/renderer/core/testing/gc_observation.h
@@ -43,21 +43,19 @@ class GCObservation final : public ScriptWrappable {
public:
static GCObservation* Create(v8::Local<v8::Value> observed_value) {
- return new GCObservation(observed_value);
+ return MakeGarbageCollected<GCObservation>(observed_value);
}
+ explicit GCObservation(v8::Local<v8::Value>);
+
// Caution: It is only feasible to determine whether an object was
// "near death"; it may have been kept alive through a weak
// handle. After reaching near-death, having been collected is the
// common case.
- bool wasCollected() const { return collected_; }
- void SetWasCollected();
+ bool wasCollected() const { return observed_.IsEmpty(); }
private:
- explicit GCObservation(v8::Local<v8::Value>);
-
ScopedPersistent<v8::Value> observed_;
- bool collected_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/layer_rect.h b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.h
index e112ccf756e..a36c691267a 100644
--- a/chromium/third_party/blink/renderer/core/testing/layer_rect.h
+++ b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.h
@@ -28,8 +28,8 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_LAYER_RECT_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_LAYER_RECT_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_HIT_TEST_LAYER_RECT_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_HIT_TEST_LAYER_RECT_H_
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h"
@@ -39,49 +39,34 @@
namespace blink {
-class LayerRect final : public ScriptWrappable {
+// TODO(pdr): This is used for dumping touch_action_region for a given layer. It
+// would be useful to have the associated TouchAction for each HitTestLayerRect.
+class HitTestLayerRect final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static LayerRect* Create(Node* node,
- const String& layer_type,
- int node_offset_x,
- int node_offset_y,
- DOMRectReadOnly* rect) {
- return new LayerRect(node, layer_type, node_offset_x, node_offset_y, rect);
+ static HitTestLayerRect* Create(DOMRectReadOnly* layer_rect,
+ DOMRectReadOnly* hit_test_rect) {
+ return MakeGarbageCollected<HitTestLayerRect>(layer_rect, hit_test_rect);
}
- Node* layerAssociatedNode() const { return layer_associated_node_.Get(); }
- String layerType() const { return layer_type_; }
- int associatedNodeOffsetX() const { return associated_node_offset_x_; }
- int associatedNodeOffsetY() const { return associated_node_offset_y_; }
- DOMRectReadOnly* layerRelativeRect() const { return rect_.Get(); }
+ HitTestLayerRect(DOMRectReadOnly* layer_rect, DOMRectReadOnly* hit_test_rect)
+ : layer_rect_(layer_rect), hit_test_rect_(hit_test_rect) {}
+
+ DOMRectReadOnly* layerRect() const { return layer_rect_.Get(); }
+ DOMRectReadOnly* hitTestRect() const { return hit_test_rect_.Get(); }
void Trace(blink::Visitor* visitor) override {
- visitor->Trace(layer_associated_node_);
- visitor->Trace(rect_);
+ visitor->Trace(layer_rect_);
+ visitor->Trace(hit_test_rect_);
ScriptWrappable::Trace(visitor);
}
private:
- LayerRect(Node* node,
- const String& layer_name,
- int node_offset_x,
- int node_offset_y,
- DOMRectReadOnly* rect)
- : layer_associated_node_(node),
- layer_type_(layer_name),
- associated_node_offset_x_(node_offset_x),
- associated_node_offset_y_(node_offset_y),
- rect_(rect) {}
-
- Member<Node> layer_associated_node_;
- String layer_type_;
- int associated_node_offset_x_;
- int associated_node_offset_y_;
- Member<DOMRectReadOnly> rect_;
+ Member<DOMRectReadOnly> layer_rect_;
+ Member<DOMRectReadOnly> hit_test_rect_;
};
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_LAYER_RECT_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_HIT_TEST_LAYER_RECT_H_
diff --git a/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.idl b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.idl
new file mode 100644
index 00000000000..da6befb33c4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect.idl
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* Stores information about a hit test rect relative to a layer. */
+/* TODO(pdr): This is used for dumping touch_action_region. It would be useful
+ * to have the associated touch action for each HitTestLayerRect. */
+interface HitTestLayerRect {
+ readonly attribute DOMRectReadOnly layerRect;
+ readonly attribute DOMRectReadOnly hitTestRect;
+};
diff --git a/chromium/third_party/blink/renderer/core/testing/layer_rect_list.cc b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.cc
index f32a830a330..8e0056ec1d7 100644
--- a/chromium/third_party/blink/renderer/core/testing/layer_rect_list.cc
+++ b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.cc
@@ -28,37 +28,32 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/testing/layer_rect_list.h"
+#include "third_party/blink/renderer/core/testing/hit_test_layer_rect_list.h"
-#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h"
-#include "third_party/blink/renderer/core/testing/layer_rect.h"
+#include "third_party/blink/renderer/core/testing/hit_test_layer_rect.h"
namespace blink {
-LayerRectList::LayerRectList() = default;
+HitTestLayerRectList::HitTestLayerRectList() = default;
-unsigned LayerRectList::length() const {
+unsigned HitTestLayerRectList::length() const {
return list_.size();
}
-LayerRect* LayerRectList::item(unsigned index) {
+HitTestLayerRect* HitTestLayerRectList::item(unsigned index) {
if (index >= list_.size())
return nullptr;
return list_[index].Get();
}
-void LayerRectList::Append(Node* layer_root_node,
- const String& layer_type,
- int layer_offset_x,
- int layer_offset_y,
- DOMRectReadOnly* layer_relative_rect) {
- list_.push_back(LayerRect::Create(layer_root_node, layer_type, layer_offset_x,
- layer_offset_y, layer_relative_rect));
+void HitTestLayerRectList::Append(DOMRectReadOnly* layer_rect,
+ DOMRectReadOnly* hit_test_rect) {
+ list_.push_back(HitTestLayerRect::Create(layer_rect, hit_test_rect));
}
-void LayerRectList::Trace(blink::Visitor* visitor) {
+void HitTestLayerRectList::Trace(blink::Visitor* visitor) {
visitor->Trace(list_);
ScriptWrappable::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/testing/layer_rect_list.h b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.h
index 3625a7ea99b..5f8b9350b4b 100644
--- a/chromium/third_party/blink/renderer/core/testing/layer_rect_list.h
+++ b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.h
@@ -28,8 +28,8 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_LAYER_RECT_LIST_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_LAYER_RECT_LIST_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_HIT_TEST_LAYER_RECT_LIST_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_HIT_TEST_LAYER_RECT_LIST_H_
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -39,31 +39,28 @@
namespace blink {
class DOMRectReadOnly;
-class LayerRect;
-class Node;
+class HitTestLayerRect;
-class LayerRectList final : public ScriptWrappable {
+class HitTestLayerRectList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static LayerRectList* Create() { return new LayerRectList; }
+ static HitTestLayerRectList* Create() {
+ return MakeGarbageCollected<HitTestLayerRectList>();
+ }
+
+ HitTestLayerRectList();
unsigned length() const;
- LayerRect* item(unsigned index);
- void Append(Node* layer_associated_node,
- const String& layer_name,
- int layer_offset_x,
- int layer_offset_y,
- DOMRectReadOnly* layer_relative_rect);
+ HitTestLayerRect* item(unsigned index);
+ void Append(DOMRectReadOnly* layer_rect, DOMRectReadOnly* hit_test_rect);
void Trace(blink::Visitor*) override;
private:
- LayerRectList();
-
- HeapVector<Member<LayerRect>> list_;
+ HeapVector<Member<HitTestLayerRect>> list_;
};
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_LAYER_RECT_LIST_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_HIT_TEST_LAYER_RECT_LIST_H_
diff --git a/chromium/third_party/blink/renderer/core/testing/layer_rect_list.idl b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.idl
index 469a7603b07..8a1e9a00fff 100644
--- a/chromium/third_party/blink/renderer/core/testing/layer_rect_list.idl
+++ b/chromium/third_party/blink/renderer/core/testing/hit_test_layer_rect_list.idl
@@ -28,7 +28,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface LayerRectList {
+interface HitTestLayerRectList {
readonly attribute unsigned long length;
- getter LayerRect item(unsigned long index);
+ getter HitTestLayerRect item(unsigned long index);
};
diff --git a/chromium/third_party/blink/renderer/core/testing/internal_settings.cc b/chromium/third_party/blink/renderer/core/testing/internal_settings.cc
index 568aa56527d..d25a98c705e 100644
--- a/chromium/third_party/blink/renderer/core/testing/internal_settings.cc
+++ b/chromium/third_party/blink/renderer/core/testing/internal_settings.cc
@@ -110,7 +110,7 @@ void InternalSettings::Backup::RestoreTo(Settings* settings) {
InternalSettings* InternalSettings::From(Page& page) {
InternalSettings* supplement = Supplement<Page>::From<InternalSettings>(page);
if (!supplement) {
- supplement = new InternalSettings(page);
+ supplement = MakeGarbageCollected<InternalSettings>(page);
ProvideTo(page, supplement);
}
return supplement;
diff --git a/chromium/third_party/blink/renderer/core/testing/internal_settings.h b/chromium/third_party/blink/renderer/core/testing/internal_settings.h
index a1bef292b5d..84a6b178414 100644
--- a/chromium/third_party/blink/renderer/core/testing/internal_settings.h
+++ b/chromium/third_party/blink/renderer/core/testing/internal_settings.h
@@ -76,11 +76,13 @@ class InternalSettings final : public InternalSettingsGenerated,
};
static InternalSettings* Create(Page& page) {
- return new InternalSettings(page);
+ return MakeGarbageCollected<InternalSettings>(page);
}
static InternalSettings* From(Page&);
+ explicit InternalSettings(Page&);
~InternalSettings() override;
+
void ResetToConsistentState();
void setStandardFontFamily(const AtomicString& family,
@@ -145,8 +147,6 @@ class InternalSettings final : public InternalSettingsGenerated,
void SetPreloadLogging(bool, ExceptionState&);
private:
- explicit InternalSettings(Page&);
-
Settings* GetSettings() const;
Page* GetPage() const { return GetSupplementable(); }
diff --git a/chromium/third_party/blink/renderer/core/testing/internals.cc b/chromium/third_party/blink/renderer/core/testing/internals.cc
index 781deeae548..2e5b06872aa 100644
--- a/chromium/third_party/blink/renderer/core/testing/internals.cc
+++ b/chromium/third_party/blink/renderer/core/testing/internals.cc
@@ -43,10 +43,10 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/properties/css_unresolved_property.h"
#include "third_party/blink/renderer/core/css/select_rule_feature_set.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/dom_string_list.h"
@@ -136,10 +136,10 @@
#include "third_party/blink/renderer/core/testing/callback_function_test.h"
#include "third_party/blink/renderer/core/testing/dictionary_test.h"
#include "third_party/blink/renderer/core/testing/gc_observation.h"
+#include "third_party/blink/renderer/core/testing/hit_test_layer_rect.h"
+#include "third_party/blink/renderer/core/testing/hit_test_layer_rect_list.h"
#include "third_party/blink/renderer/core/testing/internal_runtime_flags.h"
#include "third_party/blink/renderer/core/testing/internal_settings.h"
-#include "third_party/blink/renderer/core/testing/layer_rect.h"
-#include "third_party/blink/renderer/core/testing/layer_rect_list.h"
#include "third_party/blink/renderer/core/testing/mock_hyphenation.h"
#include "third_party/blink/renderer/core/testing/origin_trials_test.h"
#include "third_party/blink/renderer/core/testing/record_test.h"
@@ -155,6 +155,7 @@
#include "third_party/blink/renderer/platform/cursor.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -462,7 +463,7 @@ int Internals::getResourcePriority(const String& url, Document* document) {
return static_cast<int>(ResourceLoadPriority::kUnresolved);
Resource* resource = document->Fetcher()->AllResources().at(
- URLTestHelpers::ToKURL(url.Utf8().data()));
+ url_test_helpers::ToKURL(url.Utf8().data()));
if (!resource)
return static_cast<int>(ResourceLoadPriority::kUnresolved);
@@ -476,7 +477,7 @@ String Internals::getResourceHeader(const String& url,
if (!document)
return String();
Resource* resource = document->Fetcher()->AllResources().at(
- URLTestHelpers::ToKURL(url.Utf8().data()));
+ url_test_helpers::ToKURL(url.Utf8().data()));
if (!resource)
return String();
return resource->GetResourceRequest().HttpHeaderField(header.Utf8().data());
@@ -547,7 +548,8 @@ void Internals::pauseAnimations(double pause_time,
if (!GetFrame())
return;
- GetFrame()->View()->UpdateAllLifecyclePhases();
+ GetFrame()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
GetFrame()->GetDocument()->Timeline().PauseAnimationsForTesting(pause_time);
}
@@ -687,7 +689,8 @@ Node* Internals::previousInFlatTree(Node* node,
String Internals::elementLayoutTreeAsText(Element* element,
ExceptionState& exception_state) {
DCHECK(element);
- element->GetDocument().View()->UpdateAllLifecyclePhases();
+ element->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
String representation = ExternalRepresentation(element);
if (representation.IsEmpty()) {
@@ -1322,16 +1325,18 @@ void Internals::setAutofilledValue(Element* element,
}
if (auto* input = ToHTMLInputElementOrNull(*element)) {
- input->DispatchScopedEvent(*Event::CreateBubble(EventTypeNames::keydown));
+ input->DispatchScopedEvent(
+ *Event::CreateBubble(event_type_names::kKeydown));
input->SetAutofillValue(value);
- input->DispatchScopedEvent(*Event::CreateBubble(EventTypeNames::keyup));
+ input->DispatchScopedEvent(*Event::CreateBubble(event_type_names::kKeyup));
}
if (auto* textarea = ToHTMLTextAreaElementOrNull(*element)) {
textarea->DispatchScopedEvent(
- *Event::CreateBubble(EventTypeNames::keydown));
+ *Event::CreateBubble(event_type_names::kKeydown));
textarea->SetAutofillValue(value);
- textarea->DispatchScopedEvent(*Event::CreateBubble(EventTypeNames::keyup));
+ textarea->DispatchScopedEvent(
+ *Event::CreateBubble(event_type_names::kKeyup));
}
if (auto* select = ToHTMLSelectElementOrNull(*element))
@@ -1860,37 +1865,36 @@ static void MergeRects(Vector<IntRect>& rects) {
}
}
-static void AccumulateLayerRectList(PaintLayerCompositor* compositor,
- GraphicsLayer* graphics_layer,
- LayerRectList* rects) {
+static void AccumulateTouchActionRectList(
+ PaintLayerCompositor* compositor,
+ GraphicsLayer* graphics_layer,
+ HitTestLayerRectList* hit_test_rects) {
const cc::TouchActionRegion& touch_action_region =
graphics_layer->CcLayer()->touch_action_region();
if (!touch_action_region.region().IsEmpty()) {
- Vector<IntRect> layer_rects;
- for (const gfx::Rect& rect : touch_action_region.region()) {
- layer_rects.push_back(IntRect(rect));
- }
- MergeRects(layer_rects);
- String layer_type;
- IntSize layer_offset;
- PaintLayer* paint_layer = FindLayerForGraphicsLayer(
- compositor->RootLayer(), graphics_layer, &layer_offset, &layer_type);
- Node* node =
- paint_layer ? paint_layer->GetLayoutObject().GetNode() : nullptr;
- for (const IntRect& layer_rect : layer_rects) {
- if (!layer_rect.IsEmpty()) {
- rects->Append(node, layer_type, layer_offset.Width(),
- layer_offset.Height(),
- DOMRectReadOnly::FromIntRect(layer_rect));
+ const auto& layer_position = graphics_layer->CcLayer()->position();
+ const auto& layer_bounds = graphics_layer->CcLayer()->bounds();
+ IntRect layer_rect(layer_position.x(), layer_position.y(),
+ layer_bounds.width(), layer_bounds.height());
+
+ Vector<IntRect> layer_hit_test_rects;
+ for (const gfx::Rect& hit_test_rect : touch_action_region.region())
+ layer_hit_test_rects.push_back(IntRect(hit_test_rect));
+ MergeRects(layer_hit_test_rects);
+
+ for (const IntRect& hit_test_rect : layer_hit_test_rects) {
+ if (!hit_test_rect.IsEmpty()) {
+ hit_test_rects->Append(DOMRectReadOnly::FromIntRect(layer_rect),
+ DOMRectReadOnly::FromIntRect(hit_test_rect));
}
}
}
for (GraphicsLayer* child_layer : graphics_layer->Children())
- AccumulateLayerRectList(compositor, child_layer, rects);
+ AccumulateTouchActionRectList(compositor, child_layer, hit_test_rects);
}
-LayerRectList* Internals::touchEventTargetLayerRects(
+HitTestLayerRectList* Internals::touchEventTargetLayerRects(
Document* document,
ExceptionState& exception_state) {
DCHECK(document);
@@ -1900,6 +1904,38 @@ LayerRectList* Internals::touchEventTargetLayerRects(
return nullptr;
}
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ auto* pac = document->View()->GetPaintArtifactCompositorForTesting();
+ pac->EnableExtraDataForTesting();
+ document->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+
+ const auto& content_layers = pac->GetExtraDataForTesting()->content_layers;
+
+ HitTestLayerRectList* hit_test_rects = HitTestLayerRectList::Create();
+ for (const auto& layer : content_layers) {
+ const cc::TouchActionRegion& touch_action_region =
+ layer->touch_action_region();
+ if (!touch_action_region.region().IsEmpty()) {
+ IntRect layer_rect(RoundedIntPoint(FloatPoint(layer->position())),
+ IntSize(layer->bounds()));
+
+ Vector<IntRect> layer_hit_test_rects;
+ for (const gfx::Rect& hit_test_rect : touch_action_region.region())
+ layer_hit_test_rects.push_back(IntRect(hit_test_rect));
+ MergeRects(layer_hit_test_rects);
+
+ for (const IntRect& hit_test_rect : layer_hit_test_rects) {
+ if (!hit_test_rect.IsEmpty()) {
+ hit_test_rects->Append(DOMRectReadOnly::FromIntRect(layer_rect),
+ DOMRectReadOnly::FromIntRect(hit_test_rect));
+ }
+ }
+ }
+ }
+ return hit_test_rects;
+ }
+
if (ScrollingCoordinator* scrolling_coordinator =
document->GetPage()->GetScrollingCoordinator()) {
FrameView* view = document->GetPage()->MainFrame()->View();
@@ -1917,9 +1953,9 @@ LayerRectList* Internals::touchEventTargetLayerRects(
// on layers outside the document hierarchy (e.g. when we replace the
// document with a video layer).
if (GraphicsLayer* root_layer = compositor->PaintRootGraphicsLayer()) {
- LayerRectList* rects = LayerRectList::Create();
- AccumulateLayerRectList(compositor, root_layer, rects);
- return rects;
+ HitTestLayerRectList* hit_test_rects = HitTestLayerRectList::Create();
+ AccumulateTouchActionRectList(compositor, root_layer, hit_test_rects);
+ return hit_test_rects;
}
}
}
@@ -1943,27 +1979,27 @@ bool Internals::executeCommand(Document* document,
}
AtomicString Internals::htmlNamespace() {
- return HTMLNames::xhtmlNamespaceURI;
+ return html_names::xhtmlNamespaceURI;
}
Vector<AtomicString> Internals::htmlTags() {
- Vector<AtomicString> tags(HTMLNames::HTMLTagsCount);
+ Vector<AtomicString> tags(html_names::kTagsCount);
std::unique_ptr<const HTMLQualifiedName* []> qualified_names =
- HTMLNames::getHTMLTags();
- for (wtf_size_t i = 0; i < HTMLNames::HTMLTagsCount; ++i)
+ html_names::GetTags();
+ for (wtf_size_t i = 0; i < html_names::kTagsCount; ++i)
tags[i] = qualified_names[i]->LocalName();
return tags;
}
AtomicString Internals::svgNamespace() {
- return SVGNames::svgNamespaceURI;
+ return svg_names::kNamespaceURI;
}
Vector<AtomicString> Internals::svgTags() {
- Vector<AtomicString> tags(SVGNames::SVGTagsCount);
+ Vector<AtomicString> tags(svg_names::kTagsCount);
std::unique_ptr<const SVGQualifiedName* []> qualified_names =
- SVGNames::getSVGTags();
- for (wtf_size_t i = 0; i < SVGNames::SVGTagsCount; ++i)
+ svg_names::GetTags();
+ for (wtf_size_t i = 0; i < svg_names::kTagsCount; ++i)
tags[i] = qualified_names[i]->LocalName();
return tags;
}
@@ -2124,7 +2160,8 @@ String Internals::elementLayerTreeAsText(
ExceptionState& exception_state) const {
DCHECK(element);
LocalFrameView* frame_view = element->GetDocument().View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
return elementLayerTreeAsText(element, 0, exception_state);
}
@@ -2133,7 +2170,8 @@ bool Internals::scrollsWithRespectTo(Element* element1,
Element* element2,
ExceptionState& exception_state) {
DCHECK(element1 && element2);
- element1->GetDocument().View()->UpdateAllLifecyclePhases();
+ element1->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
LayoutObject* layout_object1 = element1->GetLayoutObject();
LayoutObject* layout_object2 = element2->GetLayoutObject();
@@ -2178,7 +2216,8 @@ String Internals::layerTreeAsText(Document* document,
return String();
}
- document->View()->UpdateAllLifecyclePhases();
+ document->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
return document->GetFrame()->GetLayerTreeAsTextForTesting(flags);
}
@@ -2224,7 +2263,8 @@ String Internals::mainThreadScrollingReasons(
return String();
}
- document->GetFrame()->View()->UpdateAllLifecyclePhases();
+ document->GetFrame()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
return document->GetFrame()->View()->MainThreadScrollingReasonsAsText();
}
@@ -2253,7 +2293,8 @@ DOMRectList* Internals::nonFastScrollableRects(
// Update lifecycle to kPrePaintClean. This includes the compositing update
// and ScrollingCoordinator::UpdateAfterPaint, which computes the non-fast
// scrollable region.
- frame->View()->UpdateAllLifecyclePhases();
+ frame->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
GraphicsLayer* layer = frame->View()->LayoutViewport()->LayerForScrolling();
if (!layer)
@@ -2558,7 +2599,8 @@ void Internals::startTrackingRepaints(Document* document,
}
LocalFrameView* frame_view = document->View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
frame_view->SetTracksPaintInvalidations(true);
}
@@ -2572,7 +2614,8 @@ void Internals::stopTrackingRepaints(Document* document,
}
LocalFrameView* frame_view = document->View();
- frame_view->UpdateAllLifecyclePhases();
+ frame_view->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
frame_view->SetTracksPaintInvalidations(false);
}
@@ -2995,7 +3038,8 @@ void Internals::forceCompositingUpdate(Document* document,
return;
}
- document->GetFrame()->View()->UpdateAllLifecyclePhases();
+ document->GetFrame()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
void Internals::setZoomFactor(float factor) {
diff --git a/chromium/third_party/blink/renderer/core/testing/internals.h b/chromium/third_party/blink/renderer/core/testing/internals.h
index 090fb675a73..3d69d29d086 100644
--- a/chromium/third_party/blink/renderer/core/testing/internals.h
+++ b/chromium/third_party/blink/renderer/core/testing/internals.h
@@ -43,11 +43,11 @@ namespace blink {
class Animation;
class CallbackFunctionTest;
class CanvasRenderingContext;
+class DOMArrayBuffer;
+class DOMPoint;
class DOMRect;
class DOMRectList;
class DOMRectReadOnly;
-class DOMArrayBuffer;
-class DOMPoint;
class DOMWindow;
class DictionaryTest;
class Document;
@@ -56,15 +56,15 @@ class Element;
class ExceptionState;
class ExecutionContext;
class GCObservation;
-class HitTestLocation;
-class HitTestResult;
class HTMLInputElement;
class HTMLMediaElement;
class HTMLSelectElement;
class HTMLVideoElement;
+class HitTestLayerRectList;
+class HitTestLocation;
+class HitTestResult;
class InternalRuntimeFlags;
class InternalSettings;
-class LayerRectList;
class LocalDOMWindow;
class LocalFrame;
class Location;
@@ -73,15 +73,16 @@ class OriginTrialsTest;
class Page;
class Range;
class RecordTest;
+class ScrollState;
class SequenceTest;
class SerializedScriptValue;
class ShadowRoot;
+template <typename NodeType>
+class StaticNodeTypeList;
class StaticSelection;
class TypeConversions;
class UnionTypesTest;
-class ScrollState;
-template <typename NodeType>
-class StaticNodeTypeList;
+
using StaticNodeList = StaticNodeTypeList<Node>;
class Internals final : public ScriptWrappable {
@@ -89,11 +90,13 @@ class Internals final : public ScriptWrappable {
public:
static Internals* Create(ExecutionContext* context) {
- return new Internals(context);
+ return MakeGarbageCollected<Internals>(context);
}
static void ResetToConsistentState(Page*);
+ explicit Internals(ExecutionContext*);
+
String elementLayoutTreeAsText(Element*, ExceptionState&);
GCObservation* observeGC(ScriptValue);
@@ -283,7 +286,7 @@ class Internals final : public ScriptWrappable {
unsigned touchEndOrCancelEventHandlerCount(Document*) const;
unsigned pointerEventHandlerCount(Document*) const;
- LayerRectList* touchEventTargetLayerRects(Document*, ExceptionState&);
+ HitTestLayerRectList* touchEventTargetLayerRects(Document*, ExceptionState&);
bool executeCommand(Document*,
const String& name,
@@ -511,7 +514,7 @@ class Internals final : public ScriptWrappable {
// Schedule a forced Blink GC run (Oilpan) at the end of event loop.
// Note: This is designed to be only used from PerformanceTests/BlinkGC to
- // explicitly measure only Blink GC time. Normal LayoutTests should use
+ // explicitly measure only Blink GC time. Normal web tests should use
// gc() instead as it would trigger both Blink GC and V8 GC.
void forceBlinkGCWithoutV8GC();
@@ -596,7 +599,6 @@ class Internals final : public ScriptWrappable {
void addEmbedderCustomElementName(const AtomicString& name, ExceptionState&);
private:
- explicit Internals(ExecutionContext*);
Document* ContextDocument() const;
LocalFrame* GetFrame() const;
Vector<String> IconURLs(Document*, int icon_types_mask) const;
diff --git a/chromium/third_party/blink/renderer/core/testing/internals.idl b/chromium/third_party/blink/renderer/core/testing/internals.idl
index 15a61d05475..8c575f90721 100644
--- a/chromium/third_party/blink/renderer/core/testing/internals.idl
+++ b/chromium/third_party/blink/renderer/core/testing/internals.idl
@@ -159,7 +159,7 @@ enum EffectiveConnectionType {
unsigned long touchStartOrMoveEventHandlerCount(Document document);
unsigned long touchEndOrCancelEventHandlerCount(Document document);
unsigned long pointerEventHandlerCount(Document document);
- [RaisesException] LayerRectList touchEventTargetLayerRects(Document document);
+ [RaisesException] HitTestLayerRectList touchEventTargetLayerRects(Document document);
[RaisesException] boolean executeCommand(Document document, DOMString name, DOMString value);
@@ -362,7 +362,7 @@ enum EffectiveConnectionType {
// Returns a promise that is resolved when |feature| is counted on
// |document|'s UseCounter. When |feature| was already counted, it's
// immediately resolved.
- [CallWith=ScriptState] Promise<bool> observeUseCounter(Document document, unsigned long feature);
+ [CallWith=ScriptState] Promise<boolean> observeUseCounter(Document document, unsigned long feature);
readonly attribute unsigned long length;
getter long (unsigned long index);
diff --git a/chromium/third_party/blink/renderer/core/testing/layer_rect.idl b/chromium/third_party/blink/renderer/core/testing/layer_rect.idl
deleted file mode 100644
index 8556f4126e6..00000000000
--- a/chromium/third_party/blink/renderer/core/testing/layer_rect.idl
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-interface LayerRect {
- /* The node that most closely represents the layer in which the rect
- occurs. When a layer doesn't correspond directly to a node (eg.
- for layer squashing) this will the node representing an ancestor
- layer. */
- readonly attribute Node layerAssociatedNode;
- readonly attribute DOMString layerType;
- /* Offset of the associated node from the GraphicsLayer */
- readonly attribute long associatedNodeOffsetX;
- readonly attribute long associatedNodeOffsetY;
- /* Rectange in the GraphicsLayer co-ordinate space */
- readonly attribute DOMRectReadOnly layerRelativeRect;
-};
diff --git a/chromium/third_party/blink/renderer/core/testing/null_execution_context.cc b/chromium/third_party/blink/renderer/core/testing/null_execution_context.cc
index 4ca333d70f1..1fdf44f8e33 100644
--- a/chromium/third_party/blink/renderer/core/testing/null_execution_context.cc
+++ b/chromium/third_party/blink/renderer/core/testing/null_execution_context.cc
@@ -13,7 +13,9 @@
namespace blink {
NullExecutionContext::NullExecutionContext()
- : tasks_need_pause_(false), is_secure_context_(true) {}
+ : ExecutionContext(v8::Isolate::GetCurrent()),
+ tasks_need_pause_(false),
+ is_secure_context_(true) {}
void NullExecutionContext::SetIsSecureContext(bool is_secure_context) {
is_secure_context_ = is_secure_context;
@@ -38,7 +40,7 @@ FrameOrWorkerScheduler* NullExecutionContext::GetScheduler() {
scoped_refptr<base::SingleThreadTaskRunner> NullExecutionContext::GetTaskRunner(
TaskType) {
- return Platform::Current()->CurrentThread()->GetTaskRunner();
+ return Thread::Current()->GetTaskRunner();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/origin_trials_test.cc b/chromium/third_party/blink/renderer/core/testing/origin_trials_test.cc
index 856d93947e5..416cc3823a1 100644
--- a/chromium/third_party/blink/renderer/core/testing/origin_trials_test.cc
+++ b/chromium/third_party/blink/renderer/core/testing/origin_trials_test.cc
@@ -13,7 +13,7 @@ namespace blink {
bool OriginTrialsTest::throwingAttribute(ScriptState* script_state,
ExceptionState& exception_state) {
String error_message;
- if (!OriginTrials::OriginTrialsSampleAPIEnabled(
+ if (!origin_trials::OriginTrialsSampleAPIEnabled(
ExecutionContext::From(script_state))) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
diff --git a/chromium/third_party/blink/renderer/core/testing/origin_trials_test.h b/chromium/third_party/blink/renderer/core/testing/origin_trials_test.h
index 64438c25127..2fbac76057b 100644
--- a/chromium/third_party/blink/renderer/core/testing/origin_trials_test.h
+++ b/chromium/third_party/blink/renderer/core/testing/origin_trials_test.h
@@ -22,7 +22,11 @@ class OriginTrialsTest : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static OriginTrialsTest* Create() { return new OriginTrialsTest(); }
+ static OriginTrialsTest* Create() {
+ return MakeGarbageCollected<OriginTrialsTest>();
+ }
+
+ OriginTrialsTest() = default;
~OriginTrialsTest() override = default;
bool normalAttribute() { return true; }
@@ -32,13 +36,15 @@ class OriginTrialsTest : public ScriptWrappable {
static const unsigned short kConstant = 1;
bool throwingAttribute(ScriptState*, ExceptionState&);
- void getDictionaryMethod(OriginTrialsTestDictionary&) {}
- void checkDictionaryMethod(const OriginTrialsTestDictionary&) {}
+ OriginTrialsTestDictionary* getDictionaryMethod() {
+ return OriginTrialsTestDictionary::Create();
+ }
+ void checkDictionaryMethod(const OriginTrialsTestDictionary*) {}
bool unconditionalAttribute() { return true; }
static bool staticUnconditionalAttribute() { return true; }
bool unconditionalMethod() { return true; }
- void unconditionalDictionaryMethod(const OriginTrialsTestDictionary& dict) {}
+ void unconditionalDictionaryMethod(const OriginTrialsTestDictionary* dict) {}
static bool staticUnconditionalMethod() { return true; }
static const unsigned short kUnconditionalConstant = 99;
@@ -53,9 +59,6 @@ class OriginTrialsTest : public ScriptWrappable {
static bool secureStaticMethod() { return true; }
bool impliedAttribute() { return true; }
-
- private:
- OriginTrialsTest() = default;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/page_test_base.cc b/chromium/third_party/blink/renderer/core/testing/page_test_base.cc
index 54b3844a878..6f4e35bb4e0 100644
--- a/chromium/third_party/blink/renderer/core/testing/page_test_base.cc
+++ b/chromium/third_party/blink/renderer/core/testing/page_test_base.cc
@@ -88,8 +88,8 @@ void PageTestBase::LoadAhem(LocalFrame& frame) {
StringOrArrayBufferOrArrayBufferView buffer =
StringOrArrayBufferOrArrayBufferView::FromArrayBuffer(
DOMArrayBuffer::Create(shared_buffer));
- FontFace* ahem =
- FontFace::Create(&document, "Ahem", buffer, FontFaceDescriptors());
+ FontFace* ahem = FontFace::Create(&document, "Ahem", buffer,
+ FontFaceDescriptors::Create());
ScriptState* script_state = ToScriptStateForMainWorld(&frame);
DummyExceptionStateForTesting exception_state;
@@ -101,7 +101,7 @@ void PageTestBase::LoadAhem(LocalFrame& frame) {
void PageTestBase::SetBodyInnerHTML(const String& body_content) {
GetDocument().body()->SetInnerHTMLFromString(body_content,
ASSERT_NO_EXCEPTION);
- UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
void PageTestBase::SetBodyContent(const std::string& body_content) {
@@ -111,11 +111,12 @@ void PageTestBase::SetBodyContent(const std::string& body_content) {
void PageTestBase::SetHtmlInnerHTML(const std::string& html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
String::FromUTF8(html_content.c_str()));
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
}
-void PageTestBase::UpdateAllLifecyclePhases() {
- GetDocument().View()->UpdateAllLifecyclePhases();
+void PageTestBase::UpdateAllLifecyclePhasesForTest() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
}
StyleEngine& PageTestBase::GetStyleEngine() {
diff --git a/chromium/third_party/blink/renderer/core/testing/page_test_base.h b/chromium/third_party/blink/renderer/core/testing/page_test_base.h
index 0b1eb9c1eec..a88ee4874fd 100644
--- a/chromium/third_party/blink/renderer/core/testing/page_test_base.h
+++ b/chromium/third_party/blink/renderer/core/testing/page_test_base.h
@@ -44,7 +44,7 @@ class PageTestBase : public testing::Test {
PendingAnimations& GetPendingAnimations();
FocusController& GetFocusController() const;
- void UpdateAllLifecyclePhases();
+ void UpdateAllLifecyclePhasesForTest();
// Load the 'Ahem' font to the LocalFrame.
// The 'Ahem' font is the only font whose font metrics is consistent across
diff --git a/chromium/third_party/blink/renderer/core/testing/record_test.h b/chromium/third_party/blink/renderer/core/testing/record_test.h
index d3acf6afeef..cda756d87cb 100644
--- a/chromium/third_party/blink/renderer/core/testing/record_test.h
+++ b/chromium/third_party/blink/renderer/core/testing/record_test.h
@@ -21,7 +21,9 @@ class RecordTest final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static RecordTest* Create() { return new RecordTest; }
+ static RecordTest* Create() { return MakeGarbageCollected<RecordTest>(); }
+
+ RecordTest();
~RecordTest() override;
void setStringLongRecord(const Vector<std::pair<String, int32_t>>& arg);
@@ -55,8 +57,6 @@ class RecordTest final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- RecordTest();
-
Vector<std::pair<String, int32_t>> string_long_record_;
base::Optional<Vector<std::pair<String, int32_t>>>
nullable_string_long_record_;
diff --git a/chromium/third_party/blink/renderer/core/testing/sequence_test.h b/chromium/third_party/blink/renderer/core/testing/sequence_test.h
index 4a78d79ea0e..8a98f7e013b 100644
--- a/chromium/third_party/blink/renderer/core/testing/sequence_test.h
+++ b/chromium/third_party/blink/renderer/core/testing/sequence_test.h
@@ -19,7 +19,9 @@ class SequenceTest final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static SequenceTest* create() { return new SequenceTest; }
+ static SequenceTest* create() { return MakeGarbageCollected<SequenceTest>(); }
+
+ SequenceTest();
~SequenceTest() override;
Vector<Vector<String>> identityByteStringSequenceSequence(
@@ -38,8 +40,6 @@ class SequenceTest final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- SequenceTest();
-
HeapVector<Member<Element>> element_sequence_;
};
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.cc b/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.cc
index 7e27cd9689d..becc31a0700 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.cc
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.cc
@@ -38,12 +38,12 @@ void SimCompositor::SetWebView(WebViewImpl& web_view,
// SimCompositor starts with defer commits enabled, but uses synchronous
// compositing which does not use defer commits anyhow, it only uses it for
// reading deferred state in tests.
- web_view_->DeferCommitsForTesting();
+ web_view_->DeferMainFrameUpdateForTesting();
}
SimCanvas::Commands SimCompositor::BeginFrame(double time_delta_in_seconds) {
DCHECK(web_view_);
- DCHECK(!layer_tree_view_->layer_tree_host()->defer_commits());
+ DCHECK(!layer_tree_view_->layer_tree_host()->defer_main_frame_update());
DCHECK(layer_tree_view_->layer_tree_host()->RequestedMainFramePending());
DCHECK_GT(time_delta_in_seconds, 0);
@@ -75,6 +75,10 @@ SimCanvas::Commands SimCompositor::PaintFrame() {
return canvas.GetCommands();
}
+void SimCompositor::ApplyViewportChanges(const ApplyViewportChangesArgs& args) {
+ web_view_->ApplyViewportChanges(args);
+}
+
void SimCompositor::RequestNewLayerTreeFrameSink(
LayerTreeFrameSinkCallback callback) {
// Make a valid LayerTreeFrameSink so the compositor will generate begin main
@@ -86,7 +90,8 @@ void SimCompositor::BeginMainFrame(base::TimeTicks frame_time) {
// There is no WebWidget like RenderWidget would have..? So go right to the
// WebViewImpl.
web_view_->BeginFrame(last_frame_time_);
- web_view_->UpdateAllLifecyclePhases();
+ web_view_->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
*paint_commands_ = PaintFrame();
}
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.h
index dbcff4c0924..784300e12da 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.h
@@ -11,6 +11,7 @@
#include "content/test/stub_layer_tree_view_delegate.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/testing/sim/sim_canvas.h"
+#include "third_party/blink/renderer/platform/graphics/apply_viewport_changes.h"
namespace blink {
@@ -63,8 +64,8 @@ class SimCompositor final : public content::StubLayerTreeViewDelegate {
// Returns true if commits are deferred in the compositor. Since these tests
// use synchronous compositing through BeginFrame(), the deferred state has no
// real effect.
- bool DeferCommits() const {
- return layer_tree_view_->layer_tree_host()->defer_commits();
+ bool DeferMainFrameUpdate() const {
+ return layer_tree_view_->layer_tree_host()->defer_main_frame_update();
}
// Returns true if a selection is set on the compositor.
bool HasSelection() const {
@@ -76,8 +77,11 @@ class SimCompositor final : public content::StubLayerTreeViewDelegate {
return layer_tree_view_->layer_tree_host()->background_color();
}
+ base::TimeTicks LastFrameTime() const { return last_frame_time_; }
+
private:
// content::LayerTreeViewDelegate implementation.
+ void ApplyViewportChanges(const ApplyViewportChangesArgs& args) override;
void RequestNewLayerTreeFrameSink(
LayerTreeFrameSinkCallback callback) override;
void BeginMainFrame(base::TimeTicks frame_time) override;
@@ -91,7 +95,8 @@ class SimCompositor final : public content::StubLayerTreeViewDelegate {
content::LayerTreeView* layer_tree_view_ = nullptr;
- std::unique_ptr<cc::ScopedDeferCommits> scoped_defer_commits_;
+ std::unique_ptr<cc::ScopedDeferMainFrameUpdate>
+ scoped_defer_main_frame_update_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_test.cc b/chromium/third_party/blink/renderer/core/testing/sim/sim_test.cc
index 8a3e27e6829..ab8aff7cf46 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_test.cc
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_test.cc
@@ -12,8 +12,8 @@
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -30,7 +30,7 @@ SimTest::SimTest()
// updateScrollerStyleForNewRecommendedScrollerStyle which then does
// FrameView::scrollbarStyleChanged and will adjust the scrollbar existence
// in the middle of a test.
- LayoutTestSupport::SetMockThemeEnabledForTest(true);
+ WebTestSupport::SetMockThemeEnabledForTest(true);
ScrollbarTheme::SetMockScrollbarsEnabled(true);
// Threaded animations are usually enabled for blink. However these tests use
// synchronous compositing, which can not run threaded animations.
@@ -46,7 +46,7 @@ SimTest::~SimTest() {
test::RunPendingTasks();
Document::SetThreadedParsingEnabledForTesting(true);
- LayoutTestSupport::SetMockThemeEnabledForTest(false);
+ WebTestSupport::SetMockThemeEnabledForTest(false);
ScrollbarTheme::SetMockScrollbarsEnabled(false);
content::TestBlinkWebUnitTestSupport::SetThreadedAnimationEnabled(true);
WebCache::Clear();
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_test.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_test.h
index 6a4753c213c..1d446c0bdad 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_test.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_test.h
@@ -55,7 +55,7 @@ class SimTest : public testing::Test {
SimWebFrameClient web_frame_client_;
SimWebViewClient web_view_client_;
SimPage page_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
Vector<String> console_messages_;
};
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_web_frame_client.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_web_frame_client.h
index bc29eb3cbdb..c18530954fa 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_web_frame_client.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_web_frame_client.h
@@ -7,12 +7,13 @@
#include "third_party/blink/public/platform/web_effective_connection_type.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
+#include "third_party/blink/renderer/core/testing/fake_web_plugin.h"
namespace blink {
class SimTest;
-class SimWebFrameClient final : public FrameTestHelpers::TestWebFrameClient {
+class SimWebFrameClient final : public frame_test_helpers::TestWebFrameClient {
public:
explicit SimWebFrameClient(SimTest&);
@@ -26,6 +27,10 @@ class SimWebFrameClient final : public FrameTestHelpers::TestWebFrameClient {
void SetEffectiveConnectionTypeForTesting(
WebEffectiveConnectionType) override;
+ WebPlugin* CreatePlugin(const WebPluginParams& params) override {
+ return new FakeWebPlugin(params);
+ }
+
private:
SimTest* test_;
WebEffectiveConnectionType effective_connection_type_;
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.cc b/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.cc
index 45455831a7e..f4d26638ed2 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.cc
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.cc
@@ -9,7 +9,7 @@
namespace blink {
SimWebViewClient::SimWebViewClient(content::LayerTreeViewDelegate* delegate)
- : FrameTestHelpers::TestWebViewClient(delegate) {}
+ : frame_test_helpers::TestWebViewClient(delegate) {}
void SimWebViewClient::DidMeaningfulLayout(
WebMeaningfulLayout meaningful_layout) {
@@ -32,7 +32,8 @@ WebView* SimWebViewClient::CreateView(WebLocalFrame* opener,
const WebString& name,
WebNavigationPolicy,
bool,
- WebSandboxFlags) {
+ WebSandboxFlags,
+ const SessionStorageNamespaceId&) {
return web_view_helper_.InitializeWithOpener(opener);
}
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.h
index 75b6cfadd3c..c38e6a7b735 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_web_view_client.h
@@ -9,7 +9,7 @@
namespace blink {
-class SimWebViewClient final : public FrameTestHelpers::TestWebViewClient {
+class SimWebViewClient final : public frame_test_helpers::TestWebViewClient {
public:
explicit SimWebViewClient(content::LayerTreeViewDelegate* delegate);
@@ -30,7 +30,8 @@ class SimWebViewClient final : public FrameTestHelpers::TestWebViewClient {
const WebString& name,
WebNavigationPolicy,
bool,
- WebSandboxFlags) override;
+ WebSandboxFlags,
+ const SessionStorageNamespaceId&) override;
private:
// WebWidgetClient overrides.
@@ -40,7 +41,7 @@ class SimWebViewClient final : public FrameTestHelpers::TestWebViewClient {
int finished_parsing_layout_count_ = 0;
int finished_loading_layout_count_ = 0;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/static_selection.cc b/chromium/third_party/blink/renderer/core/testing/static_selection.cc
index b0185e6f130..276e06b9c35 100644
--- a/chromium/third_party/blink/renderer/core/testing/static_selection.cc
+++ b/chromium/third_party/blink/renderer/core/testing/static_selection.cc
@@ -11,7 +11,7 @@ namespace blink {
// static
StaticSelection* StaticSelection::FromSelectionInFlatTree(
const SelectionInFlatTree& seleciton) {
- return new StaticSelection(seleciton);
+ return MakeGarbageCollected<StaticSelection>(seleciton);
}
StaticSelection::StaticSelection(const SelectionInFlatTree& seleciton)
diff --git a/chromium/third_party/blink/renderer/core/testing/static_selection.h b/chromium/third_party/blink/renderer/core/testing/static_selection.h
index 9dbfafac129..93c1591c9f2 100644
--- a/chromium/third_party/blink/renderer/core/testing/static_selection.h
+++ b/chromium/third_party/blink/renderer/core/testing/static_selection.h
@@ -19,6 +19,8 @@ class StaticSelection final : public ScriptWrappable {
public:
static StaticSelection* FromSelectionInFlatTree(const SelectionInFlatTree&);
+ explicit StaticSelection(const SelectionInFlatTree&);
+
Node* anchorNode() const { return anchor_node_; }
unsigned anchorOffset() const { return anchor_offset_; }
Node* focusNode() const { return focus_node_; }
@@ -27,8 +29,6 @@ class StaticSelection final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit StaticSelection(const SelectionInFlatTree&);
-
const Member<Node> anchor_node_;
const unsigned anchor_offset_;
const Member<Node> focus_node_;
diff --git a/chromium/third_party/blink/renderer/core/testing/type_conversions.h b/chromium/third_party/blink/renderer/core/testing/type_conversions.h
index a9632d1e5d9..93e2c906277 100644
--- a/chromium/third_party/blink/renderer/core/testing/type_conversions.h
+++ b/chromium/third_party/blink/renderer/core/testing/type_conversions.h
@@ -35,7 +35,19 @@ class TypeConversions final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static TypeConversions* Create() { return new TypeConversions(); }
+ static TypeConversions* Create() {
+ return MakeGarbageCollected<TypeConversions>();
+ }
+
+ TypeConversions()
+ : long_(0),
+ unsigned_long_(0),
+ long_long_(0),
+ unsigned_long_long_(0),
+ byte_(0),
+ octet_(0),
+ short_(0),
+ unsigned_short_(0) {}
int32_t testLong() { return long_; }
void setTestLong(int32_t value) { long_ = value; }
@@ -69,16 +81,6 @@ class TypeConversions final : public ScriptWrappable {
}
private:
- TypeConversions()
- : long_(0),
- unsigned_long_(0),
- long_long_(0),
- unsigned_long_long_(0),
- byte_(0),
- octet_(0),
- short_(0),
- unsigned_short_(0) {}
-
int32_t long_;
uint32_t unsigned_long_;
int64_t long_long_;
diff --git a/chromium/third_party/blink/renderer/core/testing/union_types_test.h b/chromium/third_party/blink/renderer/core/testing/union_types_test.h
index 96f4c08fef5..7397c6d9ac2 100644
--- a/chromium/third_party/blink/renderer/core/testing/union_types_test.h
+++ b/chromium/third_party/blink/renderer/core/testing/union_types_test.h
@@ -17,7 +17,11 @@ class UnionTypesTest final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static UnionTypesTest* Create() { return new UnionTypesTest(); }
+ static UnionTypesTest* Create() {
+ return MakeGarbageCollected<UnionTypesTest>();
+ }
+
+ UnionTypesTest() : attribute_type_(kSpecificTypeNone) {}
~UnionTypesTest() override = default;
void doubleOrStringOrStringSequenceAttribute(DoubleOrStringOrStringSequence&);
@@ -35,8 +39,6 @@ class UnionTypesTest final : public ScriptWrappable {
const DoubleOrStringOrStringSequence&);
private:
- UnionTypesTest() : attribute_type_(kSpecificTypeNone) {}
-
enum AttributeSpecificType {
kSpecificTypeNone,
kSpecificTypeDouble,
diff --git a/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc b/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc
index 83591801d2f..71933f2ffab 100644
--- a/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc
+++ b/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc
@@ -38,27 +38,27 @@
#include "third_party/blink/renderer/platform/bindings/origin_trial_features.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
-namespace WebCoreTestSupport {
+namespace blink {
+
+namespace web_core_test_support {
namespace {
-blink::InstallOriginTrialFeaturesFunction
+InstallOriginTrialFeaturesFunction
s_original_install_origin_trial_features_function = nullptr;
-blink::InstallPendingOriginTrialFeatureFunction
+InstallPendingOriginTrialFeatureFunction
s_original_install_pending_origin_trial_feature_function = nullptr;
v8::Local<v8::Value> CreateInternalsObject(v8::Local<v8::Context> context) {
- blink::ScriptState* script_state = blink::ScriptState::From(context);
+ ScriptState* script_state = ScriptState::From(context);
v8::Local<v8::Object> global = script_state->GetContext()->Global();
- blink::ExecutionContext* execution_context =
- blink::ExecutionContext::From(script_state);
+ ExecutionContext* execution_context = ExecutionContext::From(script_state);
if (execution_context->IsDocument()) {
- return blink::ToV8(blink::Internals::Create(execution_context), global,
- script_state->GetIsolate());
+ return ToV8(Internals::Create(execution_context), global,
+ script_state->GetIsolate());
}
if (execution_context->IsWorkerGlobalScope()) {
- return blink::ToV8(blink::WorkerInternals::Create(), global,
- script_state->GetIsolate());
+ return ToV8(WorkerInternals::Create(), global, script_state->GetIsolate());
}
return v8::Local<v8::Value>();
}
@@ -68,8 +68,8 @@ v8::Local<v8::Value> CreateInternalsObject(v8::Local<v8::Context> context) {
void InjectInternalsObject(v8::Local<v8::Context> context) {
RegisterInstallOriginTrialFeaturesForTesting();
- blink::ScriptState* script_state = blink::ScriptState::From(context);
- blink::ScriptState::Scope scope(script_state);
+ ScriptState* script_state = ScriptState::From(context);
+ ScriptState::Scope scope(script_state);
v8::Local<v8::Object> global = script_state->GetContext()->Global();
v8::Local<v8::Value> internals = CreateInternalsObject(context);
if (internals.IsEmpty())
@@ -78,31 +78,28 @@ void InjectInternalsObject(v8::Local<v8::Context> context) {
global
->CreateDataProperty(
script_state->GetContext(),
- blink::V8AtomicString(script_state->GetIsolate(), "internals"),
- internals)
+ V8AtomicString(script_state->GetIsolate(), "internals"), internals)
.ToChecked();
}
void InstallOriginTrialFeaturesForTesting(
- const blink::WrapperTypeInfo* type,
- const blink::ScriptState* script_state,
+ const WrapperTypeInfo* type,
+ const ScriptState* script_state,
v8::Local<v8::Object> prototype_object,
v8::Local<v8::Function> interface_object) {
(*s_original_install_origin_trial_features_function)(
type, script_state, prototype_object, interface_object);
- blink::ExecutionContext* execution_context =
- blink::ExecutionContext::From(script_state);
+ ExecutionContext* execution_context = ExecutionContext::From(script_state);
- if (type == &blink::V8OriginTrialsTest::wrapperTypeInfo) {
- if (blink::OriginTrials::OriginTrialsSampleAPIEnabled(execution_context)) {
- blink::V8OriginTrialsTest::installOriginTrialsSampleAPI(
+ if (type == &V8OriginTrialsTest::wrapper_type_info) {
+ if (origin_trials::OriginTrialsSampleAPIEnabled(execution_context)) {
+ V8OriginTrialsTest::InstallOriginTrialsSampleAPI(
script_state->GetIsolate(), script_state->World(),
v8::Local<v8::Object>(), prototype_object, interface_object);
}
- if (blink::OriginTrials::OriginTrialsSampleAPIImpliedEnabled(
- execution_context)) {
- blink::V8OriginTrialsTest::installOriginTrialsSampleAPIImplied(
+ if (origin_trials::OriginTrialsSampleAPIImpliedEnabled(execution_context)) {
+ V8OriginTrialsTest::InstallOriginTrialsSampleAPIImplied(
script_state->GetIsolate(), script_state->World(),
v8::Local<v8::Object>(), prototype_object, interface_object);
}
@@ -114,46 +111,45 @@ void ResetInternalsObject(v8::Local<v8::Context> context) {
if (context.IsEmpty())
return;
- blink::ScriptState* script_state = blink::ScriptState::From(context);
- blink::ScriptState::Scope scope(script_state);
- blink::Document* document =
- blink::To<blink::Document>(blink::ExecutionContext::From(script_state));
+ ScriptState* script_state = ScriptState::From(context);
+ ScriptState::Scope scope(script_state);
+ Document* document = To<Document>(ExecutionContext::From(script_state));
DCHECK(document);
- blink::LocalFrame* frame = document->GetFrame();
+ LocalFrame* frame = document->GetFrame();
// Should the document have been detached, the page is assumed being destroyed
// (=> no reset required.)
if (!frame)
return;
- blink::Page* page = frame->GetPage();
+ Page* page = frame->GetPage();
DCHECK(page);
- blink::Internals::ResetToConsistentState(page);
- blink::InternalSettings::From(*page)->ResetToConsistentState();
+ Internals::ResetToConsistentState(page);
+ InternalSettings::From(*page)->ResetToConsistentState();
}
void InstallPendingOriginTrialFeatureForTesting(
const String& feature,
- const blink::ScriptState* script_state) {
+ const ScriptState* script_state) {
(*s_original_install_pending_origin_trial_feature_function)(feature,
script_state);
v8::Local<v8::Object> prototype_object;
v8::Local<v8::Function> interface_object;
- if (feature == blink::OriginTrials::kOriginTrialsSampleAPITrialName) {
+ if (feature == origin_trials::kOriginTrialsSampleAPITrialName) {
if (script_state->PerContextData()
->GetExistingConstructorAndPrototypeForType(
- &blink::V8OriginTrialsTest::wrapperTypeInfo, &prototype_object,
+ &V8OriginTrialsTest::wrapper_type_info, &prototype_object,
&interface_object)) {
- blink::V8OriginTrialsTest::installOriginTrialsSampleAPI(
+ V8OriginTrialsTest::InstallOriginTrialsSampleAPI(
script_state->GetIsolate(), script_state->World(),
v8::Local<v8::Object>(), prototype_object, interface_object);
}
return;
}
- if (feature == blink::OriginTrials::kOriginTrialsSampleAPIImpliedTrialName) {
+ if (feature == origin_trials::kOriginTrialsSampleAPIImpliedTrialName) {
if (script_state->PerContextData()
->GetExistingConstructorAndPrototypeForType(
- &blink::V8OriginTrialsTest::wrapperTypeInfo, &prototype_object,
+ &V8OriginTrialsTest::wrapper_type_info, &prototype_object,
&interface_object)) {
- blink::V8OriginTrialsTest::installOriginTrialsSampleAPIImplied(
+ V8OriginTrialsTest::InstallOriginTrialsSampleAPIImplied(
script_state->GetIsolate(), script_state->World(),
v8::Local<v8::Object>(), prototype_object, interface_object);
}
@@ -174,4 +170,6 @@ void RegisterInstallOriginTrialFeaturesForTesting() {
}
}
-} // namespace WebCoreTestSupport
+} // namespace web_core_test_support
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.h b/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.h
index 689f77a5e7d..8cfa066257a 100644
--- a/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.h
+++ b/chromium/third_party/blink/renderer/core/testing/v8/web_core_test_support.h
@@ -28,12 +28,16 @@
#include "v8/include/v8.h"
-namespace WebCoreTestSupport {
+namespace blink {
+
+namespace web_core_test_support {
void InjectInternalsObject(v8::Local<v8::Context>);
void ResetInternalsObject(v8::Local<v8::Context>);
void RegisterInstallOriginTrialFeaturesForTesting();
-} // namespace WebCoreTestSupport
+} // namespace web_core_test_support
+
+} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/core/testing/worker_internals.h b/chromium/third_party/blink/renderer/core/testing/worker_internals.h
index deb2f6c5ff1..72eaf5003bf 100644
--- a/chromium/third_party/blink/renderer/core/testing/worker_internals.h
+++ b/chromium/third_party/blink/renderer/core/testing/worker_internals.h
@@ -18,7 +18,11 @@ class WorkerInternals final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static WorkerInternals* Create() { return new WorkerInternals(); }
+ static WorkerInternals* Create() {
+ return MakeGarbageCollected<WorkerInternals>();
+ }
+
+ explicit WorkerInternals();
~WorkerInternals() override;
OriginTrialsTest* originTrialsTest() const;
@@ -26,9 +30,6 @@ class WorkerInternals final : public ScriptWrappable {
void countDeprecation(ScriptState*, uint32_t feature, ExceptionState&);
void collectGarbage(ScriptState*);
-
- private:
- explicit WorkerInternals();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/dom_window_performance.cc b/chromium/third_party/blink/renderer/core/timing/dom_window_performance.cc
index 1ffdf75af51..10ccb057ba0 100644
--- a/chromium/third_party/blink/renderer/core/timing/dom_window_performance.cc
+++ b/chromium/third_party/blink/renderer/core/timing/dom_window_performance.cc
@@ -25,7 +25,7 @@ DOMWindowPerformance& DOMWindowPerformance::From(LocalDOMWindow& window) {
DOMWindowPerformance* supplement =
Supplement<LocalDOMWindow>::From<DOMWindowPerformance>(window);
if (!supplement) {
- supplement = new DOMWindowPerformance(window);
+ supplement = MakeGarbageCollected<DOMWindowPerformance>(window);
ProvideTo(window, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/core/timing/dom_window_performance.h b/chromium/third_party/blink/renderer/core/timing/dom_window_performance.h
index 3712328d68a..f2e38badc9b 100644
--- a/chromium/third_party/blink/renderer/core/timing/dom_window_performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/dom_window_performance.h
@@ -26,11 +26,11 @@ class CORE_EXPORT DOMWindowPerformance final
static DOMWindowPerformance& From(LocalDOMWindow&);
static WindowPerformance* performance(LocalDOMWindow&);
+ explicit DOMWindowPerformance(LocalDOMWindow&);
+
void Trace(blink::Visitor*) override;
private:
- explicit DOMWindowPerformance(LocalDOMWindow&);
-
WindowPerformance* performance();
TraceWrapperMember<WindowPerformance> performance_;
diff --git a/chromium/third_party/blink/renderer/core/timing/event_timing.cc b/chromium/third_party/blink/renderer/core/timing/event_timing.cc
index 589c2fa5e14..bd694a31b2c 100644
--- a/chromium/third_party/blink/renderer/core/timing/event_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/event_timing.cc
@@ -37,7 +37,9 @@ void EventTiming::WillDispatchEvent(const Event& event) {
// dispatched.
if ((performance_->ShouldBufferEventTiming() &&
!performance_->IsEventTimingBufferFull()) ||
- performance_->HasObserverFor(PerformanceEntry::kEvent)) {
+ performance_->HasObserverFor(PerformanceEntry::kEvent)
+ || (performance_->HasObserverFor(PerformanceEntry::kFirstInput)
+ && !performance_->FirstInputDetected())) {
processing_start_ = CurrentTimeTicks();
finished_will_dispatch_event_ = true;
}
diff --git a/chromium/third_party/blink/renderer/core/timing/memory_info.h b/chromium/third_party/blink/renderer/core/timing/memory_info.h
index 06ae8afd8cc..ffd71db6c36 100644
--- a/chromium/third_party/blink/renderer/core/timing/memory_info.h
+++ b/chromium/third_party/blink/renderer/core/timing/memory_info.h
@@ -58,16 +58,16 @@ class CORE_EXPORT MemoryInfo final : public ScriptWrappable {
// and cached for a long period of time (20 minutes).
enum class Precision { Precise, Bucketized };
static MemoryInfo* Create(Precision precision) {
- return new MemoryInfo(precision);
+ return MakeGarbageCollected<MemoryInfo>(precision);
}
+ explicit MemoryInfo(Precision precision);
+
size_t totalJSHeapSize() const { return info_.total_js_heap_size; }
size_t usedJSHeapSize() const { return info_.used_js_heap_size; }
size_t jsHeapSizeLimit() const { return info_.js_heap_size_limit; }
private:
- explicit MemoryInfo(Precision precision);
-
HeapInfo info_;
};
diff --git a/chromium/third_party/blink/renderer/core/timing/performance.cc b/chromium/third_party/blink/renderer/core/timing/performance.cc
index f42b5c27968..777788c818e 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance.cc
@@ -32,6 +32,7 @@
#include "third_party/blink/renderer/core/timing/performance.h"
#include <algorithm>
+#include "base/metrics/histogram_macros.h"
#include "third_party/blink/renderer/bindings/core/v8/double_or_performance_mark_options.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_double_or_performance_measure_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
@@ -80,6 +81,92 @@ DOMHighResTimeStamp GetUnixAtZeroMonotonic() {
return unix_at_zero_monotonic;
}
+Performance::MeasureParameterType StringToNavigationTimingParameterType(
+ const String& s) {
+ // The following names come from performance_user_timing.cc.
+ if (s == "unloadEventStart")
+ return Performance::MeasureParameterType::kUnloadEventStart;
+ if (s == "unloadEventEnd")
+ return Performance::MeasureParameterType::kUnloadEventEnd;
+ if (s == "domInteractive")
+ return Performance::MeasureParameterType::kDomInteractive;
+ if (s == "domContentLoadedEventStart")
+ return Performance::MeasureParameterType::kDomContentLoadedEventStart;
+ if (s == "domContentLoadedEventEnd")
+ return Performance::MeasureParameterType::kDomContentLoadedEventEnd;
+ if (s == "domComplete")
+ return Performance::MeasureParameterType::kDomComplete;
+ if (s == "loadEventStart")
+ return Performance::MeasureParameterType::kLoadEventStart;
+ if (s == "loadEventEnd")
+ return Performance::MeasureParameterType::kLoadEventEnd;
+ if (s == "navigationStart")
+ return Performance::MeasureParameterType::kNavigationStart;
+ if (s == "redirectStart")
+ return Performance::MeasureParameterType::kRedirectStart;
+ if (s == "redirectEnd")
+ return Performance::MeasureParameterType::kRedirectEnd;
+ if (s == "fetchStart")
+ return Performance::MeasureParameterType::kFetchStart;
+ if (s == "domainLookupStart")
+ return Performance::MeasureParameterType::kDomainLookupStart;
+ if (s == "domainLookupEnd")
+ return Performance::MeasureParameterType::kDomainLookupEnd;
+ if (s == "connectStart")
+ return Performance::MeasureParameterType::kConnectStart;
+ if (s == "connectEnd")
+ return Performance::MeasureParameterType::kConnectEnd;
+ if (s == "secureConnectionStart")
+ return Performance::MeasureParameterType::kSecureConnectionStart;
+ if (s == "requestStart")
+ return Performance::MeasureParameterType::kRequestStart;
+ if (s == "responseStart")
+ return Performance::MeasureParameterType::kResponseStart;
+ if (s == "responseEnd")
+ return Performance::MeasureParameterType::kResponseEnd;
+ if (s == "domLoading")
+ return Performance::MeasureParameterType::kDomLoading;
+ return Performance::MeasureParameterType::kOther;
+}
+
+Performance::MeasureParameterType StartOrOptionsToParameterType(
+ const StringOrDoubleOrPerformanceMeasureOptions& start_or_options) {
+ if (start_or_options.IsString()) {
+ return StringToNavigationTimingParameterType(
+ start_or_options.GetAsString());
+ }
+ if (start_or_options.IsDouble())
+ return Performance::MeasureParameterType::kNumber;
+ if (start_or_options.IsPerformanceMeasureOptions())
+ return Performance::MeasureParameterType::kObjectObject;
+ // null and undefined are undistinguishable in
+ // StringOrDoubleOrPerformanceMeasureOptions.
+ return Performance::MeasureParameterType::kUndefinedOrNull;
+}
+
+Performance::MeasureParameterType EndToParameterType(
+ const StringOrDouble& end) {
+ if (end.IsString()) {
+ // When passing an object to |end|, the object will be implicitly converted
+ // as the following string.
+ if (end.GetAsString() == "[object Object]")
+ return Performance::MeasureParameterType::kObjectObject;
+ return StringToNavigationTimingParameterType(end.GetAsString());
+ }
+ if (end.IsDouble())
+ return Performance::MeasureParameterType::kNumber;
+ // null and undefined are undistinguishable in StringOrDouble.
+ return Performance::MeasureParameterType::kUndefinedOrNull;
+}
+
+void LogMeasureStartToUma(Performance::MeasureParameterType type) {
+ UMA_HISTOGRAM_ENUMERATION("Performance.MeasureParameter.StartMark", type);
+}
+
+void LogMeasureEndToUma(Performance::MeasureParameterType type) {
+ UMA_HISTOGRAM_ENUMERATION("Performance.MeasureParameter.EndMark", type);
+}
+
} // namespace
using PerformanceObserverVector = HeapVector<Member<PerformanceObserver>>;
@@ -103,7 +190,7 @@ Performance::Performance(
Performance::~Performance() = default;
const AtomicString& Performance::InterfaceName() const {
- return EventTargetNames::Performance;
+ return event_target_names::kPerformance;
}
PerformanceTiming* Performance::timing() const {
@@ -294,7 +381,7 @@ void Performance::clearResourceTimings() {
void Performance::setResourceTimingBufferSize(unsigned size) {
resource_timing_buffer_size_ = size;
if (IsResourceTimingBufferFull())
- DispatchEvent(*Event::Create(EventTypeNames::resourcetimingbufferfull));
+ DispatchEvent(*Event::Create(event_type_names::kResourcetimingbufferfull));
}
bool Performance::PassesTimingAllowCheck(
@@ -312,7 +399,7 @@ bool Performance::PassesTimingAllowCheck(
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
- ? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
+ ? response.HttpHeaderField(http_names::kTimingAllowOrigin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
@@ -475,7 +562,7 @@ void Performance::AddEventTimingBuffer(PerformanceEventTiming& entry) {
event_timing_buffer_.push_back(&entry);
if (IsEventTimingBufferFull())
- DispatchEvent(*Event::Create(EventTypeNames::eventtimingbufferfull));
+ DispatchEvent(*Event::Create(event_type_names::kEventtimingbufferfull));
}
unsigned Performance::EventTimingBufferSize() const {
@@ -489,7 +576,7 @@ void Performance::clearEventTimings() {
void Performance::setEventTimingBufferMaxSize(unsigned size) {
event_timing_buffer_max_size_ = size;
if (IsEventTimingBufferFull())
- DispatchEvent(*Event::Create(EventTypeNames::eventtimingbufferfull));
+ DispatchEvent(*Event::Create(event_type_names::kEventtimingbufferfull));
}
void Performance::AddFirstPaintTiming(TimeTicks start_time) {
@@ -503,7 +590,7 @@ void Performance::AddFirstContentfulPaintTiming(TimeTicks start_time) {
void Performance::AddPaintTiming(PerformancePaintTiming::PaintType type,
TimeTicks start_time) {
- PerformanceEntry* entry = new PerformancePaintTiming(
+ PerformanceEntry* entry = MakeGarbageCollected<PerformancePaintTiming>(
type, MonotonicTimeToDOMHighResTimeStamp(start_time));
// Always buffer First Paint & First Contentful Paint.
if (type == PerformancePaintTiming::PaintType::kFirstPaint)
@@ -517,7 +604,7 @@ void Performance::AddResourceTimingBuffer(PerformanceEntry& entry) {
resource_timing_buffer_.push_back(&entry);
if (IsResourceTimingBufferFull())
- DispatchEvent(*Event::Create(EventTypeNames::resourcetimingbufferfull));
+ DispatchEvent(*Event::Create(event_type_names::kResourcetimingbufferfull));
}
bool Performance::IsResourceTimingBufferFull() {
@@ -552,7 +639,7 @@ PerformanceMark* Performance::mark(ScriptState* script_state,
const AtomicString& mark_name,
ExceptionState& exception_state) {
DoubleOrPerformanceMarkOptions startOrOptions;
- return this->mark(script_state, mark_name, startOrOptions, exception_state);
+ return mark(script_state, mark_name, startOrOptions, exception_state);
}
PerformanceMark* Performance::mark(
@@ -560,36 +647,15 @@ PerformanceMark* Performance::mark(
const AtomicString& mark_name,
DoubleOrPerformanceMarkOptions& start_time_or_mark_options,
ExceptionState& exception_state) {
- if (!RuntimeEnabledFeatures::CustomUserTimingEnabled()) {
- DCHECK(start_time_or_mark_options.IsNull());
- }
-
if (!user_timing_)
user_timing_ = UserTiming::Create(*this);
-
- DOMHighResTimeStamp start = 0.0;
- if (start_time_or_mark_options.IsDouble()) {
- start = start_time_or_mark_options.GetAsDouble();
- } else if (start_time_or_mark_options.IsPerformanceMarkOptions() &&
- start_time_or_mark_options.GetAsPerformanceMarkOptions()
- .hasStartTime()) {
- start =
- start_time_or_mark_options.GetAsPerformanceMarkOptions().startTime();
- } else {
- start = now();
- }
-
- ScriptValue detail = ScriptValue::CreateNull(script_state);
- if (start_time_or_mark_options.IsPerformanceMarkOptions()) {
- detail = start_time_or_mark_options.GetAsPerformanceMarkOptions().detail();
- }
-
- // Pass in a null ScriptValue if the mark's detail doesn't exist.
PerformanceMark* performance_mark = user_timing_->Mark(
- script_state, mark_name, start, detail, exception_state);
+ script_state, mark_name, start_time_or_mark_options, exception_state);
if (performance_mark)
NotifyObserversOfEntry(*performance_mark);
- return performance_mark;
+ if (RuntimeEnabledFeatures::CustomUserTimingEnabled())
+ return performance_mark;
+ return nullptr;
}
void Performance::clearMarks(const AtomicString& mark_name) {
@@ -601,11 +667,12 @@ void Performance::clearMarks(const AtomicString& mark_name) {
PerformanceMeasure* Performance::measure(ScriptState* script_state,
const AtomicString& measure_name,
ExceptionState& exception_state) {
- return measureInternal(script_state, measure_name,
- NativeValueTraits<StringOrDouble>::NullValue(),
- NativeValueTraits<StringOrDouble>::NullValue(),
- ScriptValue::CreateNull(script_state),
- exception_state);
+ LogMeasureStartToUma(MeasureParameterType::kUnprovided);
+ LogMeasureEndToUma(MeasureParameterType::kUnprovided);
+ return MeasureInternal(
+ script_state, measure_name,
+ NativeValueTraits<StringOrDoubleOrPerformanceMeasureOptions>::NullValue(),
+ NativeValueTraits<StringOrDouble>::NullValue(), exception_state);
}
PerformanceMeasure* Performance::measure(
@@ -613,7 +680,9 @@ PerformanceMeasure* Performance::measure(
const AtomicString& measure_name,
const StringOrDoubleOrPerformanceMeasureOptions& start_or_options,
ExceptionState& exception_state) {
- return measureInternal(script_state, measure_name, start_or_options,
+ LogMeasureStartToUma(StartOrOptionsToParameterType(start_or_options));
+ LogMeasureEndToUma(MeasureParameterType::kUnprovided);
+ return MeasureInternal(script_state, measure_name, start_or_options,
NativeValueTraits<StringOrDouble>::NullValue(),
exception_state);
}
@@ -624,7 +693,9 @@ PerformanceMeasure* Performance::measure(
const StringOrDoubleOrPerformanceMeasureOptions& start_or_options,
const StringOrDouble& end,
ExceptionState& exception_state) {
- return measureInternal(script_state, measure_name, start_or_options, end,
+ LogMeasureStartToUma(StartOrOptionsToParameterType(start_or_options));
+ LogMeasureEndToUma(EndToParameterType(end));
+ return MeasureInternal(script_state, measure_name, start_or_options, end,
exception_state);
}
@@ -645,7 +716,7 @@ PerformanceMeasure* Performance::measure(
// When |end| is null in C++, we cannot tell whether |end| is null, undefined or
// empty in JS from StringOrDouble, so we need |end_is_empty| to help
// distinguish between (null or undefined) and empty.
-PerformanceMeasure* Performance::measureInternal(
+PerformanceMeasure* Performance::MeasureInternal(
ScriptState* script_state,
const AtomicString& measure_name,
const StringOrDoubleOrPerformanceMeasureOptions& start_or_options,
@@ -660,11 +731,11 @@ PerformanceMeasure* Performance::measureInternal(
"null.");
return nullptr;
}
- const PerformanceMeasureOptions& options =
+ const PerformanceMeasureOptions* options =
start_or_options.GetAsPerformanceMeasureOptions();
- return measureInternal(script_state, measure_name, options.startTime(),
- options.endTime(), options.detail(),
- exception_state);
+ return MeasureWithDetail(script_state, measure_name, options->startTime(),
+ options->endTime(), options->detail(),
+ exception_state);
} else {
StringOrDouble converted_start;
if (start_or_options.IsDouble()) {
@@ -677,11 +748,11 @@ PerformanceMeasure* Performance::measureInternal(
DCHECK(start_or_options.IsNull());
converted_start = NativeValueTraits<StringOrDouble>::NullValue();
}
- // We let |end| behaves the same whether it's empty, undefined or null in
+ // We let |end| behave the same whether it's empty, undefined or null in
// JS, as long as |end| is null in C++.
- return measureInternal(script_state, measure_name, converted_start, end,
- ScriptValue::CreateNull(script_state),
- exception_state);
+ return MeasureWithDetail(script_state, measure_name, converted_start, end,
+ ScriptValue::CreateNull(script_state),
+ exception_state);
}
} else {
// For consistency with UserTimingL2: the L2 API took |start| as a string,
@@ -711,14 +782,15 @@ PerformanceMeasure* Performance::measureInternal(
DCHECK(end.IsNull());
DCHECK(converted_end.IsNull());
}
- measureInternal(script_state, measure_name, converted_start, converted_end,
- ScriptValue::CreateNull(script_state), exception_state);
+ MeasureWithDetail(script_state, measure_name, converted_start,
+ converted_end, ScriptValue::CreateNull(script_state),
+ exception_state);
// Return nullptr to distinguish from L3.
return nullptr;
}
}
-PerformanceMeasure* Performance::measureInternal(
+PerformanceMeasure* Performance::MeasureWithDetail(
ScriptState* script_state,
const AtomicString& measure_name,
const StringOrDouble& start,
diff --git a/chromium/third_party/blink/renderer/core/timing/performance.h b/chromium/third_party/blink/renderer/core/timing/performance.h
index 70c8aaa3db9..96344f02a0b 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance.h
@@ -121,7 +121,8 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
void clearResourceTimings();
void setResourceTimingBufferSize(unsigned);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resourcetimingbufferfull);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resourcetimingbufferfull,
+ kResourcetimingbufferfull);
void AddLongTaskTiming(
TimeTicks start_time,
@@ -159,7 +160,8 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
unsigned EventTimingBufferSize() const;
void clearEventTimings();
void setEventTimingBufferMaxSize(unsigned);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(eventtimingbufferfull);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(eventtimingbufferfull,
+ kEventtimingbufferfull);
PerformanceMark* mark(ScriptState*,
const AtomicString& mark_name,
@@ -173,6 +175,42 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
void clearMarks(const AtomicString& mark_name);
+ // This enum is used to index different possible strings for for UMA enum
+ // histogram. New enum values can be added, but existing enums must never be
+ // renumbered or deleted and reused.
+ // This enum should be consistent with MeasureParameterType
+ // in tools/metrics/histograms/enums.xml.
+ enum class MeasureParameterType {
+ kObjectObject = 0,
+ // 1 to 8, 13 to 25 are navigation-timing types.
+ kUnloadEventStart = 1,
+ kUnloadEventEnd = 2,
+ kDomInteractive = 3,
+ kDomContentLoadedEventStart = 4,
+ kDomContentLoadedEventEnd = 5,
+ kDomComplete = 6,
+ kLoadEventStart = 7,
+ kLoadEventEnd = 8,
+ kOther = 9,
+ kUndefinedOrNull = 10,
+ kNumber = 11,
+ kUnprovided = 12,
+ kNavigationStart = 13,
+ kRedirectStart = 14,
+ kRedirectEnd = 15,
+ kFetchStart = 16,
+ kDomainLookupStart = 17,
+ kDomainLookupEnd = 18,
+ kConnectStart = 19,
+ kConnectEnd = 20,
+ kSecureConnectionStart = 21,
+ kRequestStart = 22,
+ kResponseStart = 23,
+ kResponseEnd = 24,
+ kDomLoading = 25,
+ kMaxValue = kDomLoading
+ };
+
PerformanceMeasure* measure(ScriptState*,
const AtomicString& measure_name,
ExceptionState&);
@@ -217,19 +255,19 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
void AddPaintTiming(PerformancePaintTiming::PaintType, TimeTicks start_time);
- PerformanceMeasure* measureInternal(
+ PerformanceMeasure* MeasureInternal(
ScriptState*,
const AtomicString& measure_name,
const StringOrDoubleOrPerformanceMeasureOptions& start,
const StringOrDouble& end,
ExceptionState&);
- PerformanceMeasure* measureInternal(ScriptState*,
- const AtomicString& measure_name,
- const StringOrDouble& start,
- const StringOrDouble& end,
- const ScriptValue& detail,
- ExceptionState&);
+ PerformanceMeasure* MeasureWithDetail(ScriptState*,
+ const AtomicString& measure_name,
+ const StringOrDouble& start,
+ const StringOrDouble& end,
+ const ScriptValue& detail,
+ ExceptionState&);
protected:
Performance(TimeTicks time_origin,
diff --git a/chromium/third_party/blink/renderer/core/timing/performance.idl b/chromium/third_party/blink/renderer/core/timing/performance.idl
index 58cc3685b19..ae021aaaaae 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance.idl
@@ -64,13 +64,19 @@ interface Performance : EventTarget {
// User Timing
// https://w3c.github.io/user-timing/#extensions-performance-interface
- [MeasureAs=UserTiming, CallWith=ScriptState, RaisesException] void mark(DOMString markName);
+ // We use the returned value for feature detection:
+ // * L2 API returns null.
+ // * L3 API returns the created entry.
+ [MeasureAs=UserTiming, CallWith=ScriptState, RaisesException] PerformanceMark? mark(DOMString markName);
[MeasureAs=UserTiming, CallWith=ScriptState, RuntimeEnabled=CustomUserTiming, RaisesException] PerformanceMark? mark(DOMString markName, (DOMHighResTimeStamp or PerformanceMarkOptions) startTimeOrPerformanceMarkOptions);
[MeasureAs=UserTiming] void clearMarks(optional DOMString markName = null);
// Doing either of the following requires enabling CustomUserTiming:
// * passing PerformanceMeasureOptions to |startOrOptions|
// * passing timestamps to |startOrOptions| or |end|
+ // We use the returned value for feature detection:
+ // * L2 API returns null.
+ // * L3 API returns the created entry.
// Custom User Timing (or User Timing L3) explainer:
// https://docs.google.com/document/d/1hltt8z9C4PaI5Qu1YMIp1wOGdbJPJPoJwBarEeCY6xQ/edit#heading=h.ejti6qhmjv0b
[MeasureAs=UserTiming, CallWith=ScriptState, RaisesException] PerformanceMeasure? measure(DOMString measureName, optional (DOMString or DOMHighResTimeStamp or PerformanceMeasureOptions)? startOrOptions, optional (DOMString or DOMHighResTimeStamp)? end);
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_element_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_element_timing.cc
index c892b0d8a74..a2917af0760 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_element_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_element_timing.cc
@@ -27,7 +27,7 @@ PerformanceElementTiming::PerformanceElementTiming(
PerformanceElementTiming::~PerformanceElementTiming() = default;
AtomicString PerformanceElementTiming::entryType() const {
- return PerformanceEntryNames::element;
+ return performance_entry_names::kElement;
}
PerformanceEntryType PerformanceElementTiming::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_entry.cc b/chromium/third_party/blink/renderer/core/timing/performance_entry.cc
index 6d444730f8e..86025870db1 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_entry.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_entry.cc
@@ -61,27 +61,27 @@ DOMHighResTimeStamp PerformanceEntry::duration() const {
PerformanceEntry::EntryType PerformanceEntry::ToEntryTypeEnum(
const AtomicString& entry_type) {
- if (entry_type == PerformanceEntryNames::longtask)
+ if (entry_type == performance_entry_names::kLongtask)
return kLongTask;
- if (entry_type == PerformanceEntryNames::mark)
+ if (entry_type == performance_entry_names::kMark)
return kMark;
- if (entry_type == PerformanceEntryNames::measure)
+ if (entry_type == performance_entry_names::kMeasure)
return kMeasure;
- if (entry_type == PerformanceEntryNames::resource)
+ if (entry_type == performance_entry_names::kResource)
return kResource;
- if (entry_type == PerformanceEntryNames::navigation)
+ if (entry_type == performance_entry_names::kNavigation)
return kNavigation;
- if (entry_type == PerformanceEntryNames::taskattribution)
+ if (entry_type == performance_entry_names::kTaskattribution)
return kTaskAttribution;
- if (entry_type == PerformanceEntryNames::paint)
+ if (entry_type == performance_entry_names::kPaint)
return kPaint;
- if (entry_type == PerformanceEntryNames::event)
+ if (entry_type == performance_entry_names::kEvent)
return kEvent;
- if (entry_type == PerformanceEntryNames::firstInput)
+ if (entry_type == performance_entry_names::kFirstInput)
return kFirstInput;
- if (entry_type == PerformanceEntryNames::element)
+ if (entry_type == performance_entry_names::kElement)
return kElement;
- if (entry_type == PerformanceEntryNames::layoutJank)
+ if (entry_type == performance_entry_names::kLayoutJank)
return kLayoutJank;
return kInvalid;
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_entry_names.json5 b/chromium/third_party/blink/renderer/core/timing/performance_entry_names.json5
index c2c29599e25..0ecf875333c 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_entry_names.json5
+++ b/chromium/third_party/blink/renderer/core/timing/performance_entry_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "PerformanceEntry",
+ namespace: "performance_entry_names",
export: "CORE_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_event_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_event_timing.cc
index a31aacdfc50..0fcd3902d96 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_event_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_event_timing.cc
@@ -19,17 +19,19 @@ PerformanceEventTiming* PerformanceEventTiming::Create(
// TODO(npm): enable this DCHECK once https://crbug.com/852846 is fixed.
// DCHECK_LE(start_time, processing_start);
DCHECK_LE(processing_start, processing_end);
- return new PerformanceEventTiming(event_type, PerformanceEntryNames::event,
- start_time, processing_start,
- processing_end, cancelable);
+ return MakeGarbageCollected<PerformanceEventTiming>(
+ event_type, performance_entry_names::kEvent, start_time, processing_start,
+ processing_end, cancelable);
}
// static
PerformanceEventTiming* PerformanceEventTiming::CreateFirstInputTiming(
PerformanceEventTiming* entry) {
- PerformanceEventTiming* first_input = new PerformanceEventTiming(
- entry->name(), PerformanceEntryNames::firstInput, entry->startTime(),
- entry->processingStart(), entry->processingEnd(), entry->cancelable());
+ PerformanceEventTiming* first_input =
+ MakeGarbageCollected<PerformanceEventTiming>(
+ entry->name(), performance_entry_names::kFirstInput,
+ entry->startTime(), entry->processingStart(), entry->processingEnd(),
+ entry->cancelable());
first_input->SetDuration(entry->duration());
return first_input;
}
@@ -50,7 +52,7 @@ PerformanceEventTiming::PerformanceEventTiming(
PerformanceEventTiming::~PerformanceEventTiming() = default;
PerformanceEntryType PerformanceEventTiming::EntryTypeEnum() const {
- return entry_type_ == PerformanceEntryNames::event
+ return entry_type_ == performance_entry_names::kEvent
? PerformanceEntry::EntryType::kEvent
: PerformanceEntry::EntryType::kFirstInput;
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_event_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_event_timing.h
index 5adb3198776..8680dc92b51 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_event_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_event_timing.h
@@ -25,6 +25,12 @@ class CORE_EXPORT PerformanceEventTiming final : public PerformanceEntry {
static PerformanceEventTiming* CreateFirstInputTiming(
PerformanceEventTiming* entry);
+ PerformanceEventTiming(const AtomicString& event_type,
+ const AtomicString& entry_type,
+ DOMHighResTimeStamp start_time,
+ DOMHighResTimeStamp processing_start,
+ DOMHighResTimeStamp processing_end,
+ bool cancelable);
~PerformanceEventTiming() override;
AtomicString entryType() const override { return entry_type_; }
@@ -42,12 +48,6 @@ class CORE_EXPORT PerformanceEventTiming final : public PerformanceEntry {
void Trace(blink::Visitor*) override;
private:
- PerformanceEventTiming(const AtomicString& event_type,
- const AtomicString& entry_type,
- DOMHighResTimeStamp start_time,
- DOMHighResTimeStamp processing_start,
- DOMHighResTimeStamp processing_end,
- bool cancelable);
AtomicString entry_type_;
DOMHighResTimeStamp processing_start_;
DOMHighResTimeStamp processing_end_;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_layout_jank.cc b/chromium/third_party/blink/renderer/core/timing/performance_layout_jank.cc
index 776c40254e5..46344267703 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_layout_jank.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_layout_jank.cc
@@ -21,7 +21,7 @@ PerformanceLayoutJank::PerformanceLayoutJank(double fraction)
PerformanceLayoutJank::~PerformanceLayoutJank() = default;
AtomicString PerformanceLayoutJank::entryType() const {
- return PerformanceEntryNames::layoutJank;
+ return performance_entry_names::kLayoutJank;
}
PerformanceEntryType PerformanceLayoutJank::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.cc
index 8db17dc3810..970b0f96917 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.cc
@@ -22,9 +22,9 @@ PerformanceLongTaskTiming* PerformanceLongTaskTiming::Create(
const String& frame_id,
const String& frame_name,
const SubTaskAttribution::EntriesVector& sub_task_attributions) {
- return new PerformanceLongTaskTiming(start_time, end_time, name, frame_src,
- frame_id, frame_name,
- sub_task_attributions);
+ return MakeGarbageCollected<PerformanceLongTaskTiming>(
+ start_time, end_time, name, frame_src, frame_id, frame_name,
+ sub_task_attributions);
}
PerformanceLongTaskTiming::PerformanceLongTaskTiming(
@@ -48,7 +48,7 @@ PerformanceLongTaskTiming::PerformanceLongTaskTiming(
} else {
// Only one possible task type exists currently: "script".
TaskAttributionTiming* attribution_entry =
- TaskAttributionTiming::Create("script", "iframe", culprit_frame_src,
+ TaskAttributionTiming::Create("unknown", "iframe", culprit_frame_src,
culprit_frame_id, culprit_frame_name);
attribution_.push_back(*attribution_entry);
}
@@ -57,7 +57,7 @@ PerformanceLongTaskTiming::PerformanceLongTaskTiming(
PerformanceLongTaskTiming::~PerformanceLongTaskTiming() = default;
AtomicString PerformanceLongTaskTiming::entryType() const {
- return PerformanceEntryNames::longtask;
+ return performance_entry_names::kLongtask;
}
PerformanceEntryType PerformanceLongTaskTiming::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.h
index 7d7750834d2..e903a1e7607 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_long_task_timing.h
@@ -29,14 +29,6 @@ class PerformanceLongTaskTiming final : public PerformanceEntry {
const String& frame_name,
const SubTaskAttribution::EntriesVector& sub_task_attributions);
- AtomicString entryType() const override;
- PerformanceEntryType EntryTypeEnum() const override;
-
- TaskAttributionVector attribution() const;
-
- void Trace(blink::Visitor*) override;
-
- private:
PerformanceLongTaskTiming(
double start_time,
double end_time,
@@ -45,6 +37,15 @@ class PerformanceLongTaskTiming final : public PerformanceEntry {
const String& frame_id,
const String& frame_name,
const SubTaskAttribution::EntriesVector& sub_task_attributions);
+
+ AtomicString entryType() const override;
+ PerformanceEntryType EntryTypeEnum() const override;
+
+ TaskAttributionVector attribution() const;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
~PerformanceLongTaskTiming() override;
void BuildJSONValue(V8ObjectBuilder&) const override;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_mark.cc b/chromium/third_party/blink/renderer/core/timing/performance_mark.cc
index 18e421e0155..c757a784baf 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_mark.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_mark.cc
@@ -23,7 +23,7 @@ PerformanceMark::PerformanceMark(ScriptState* script_state,
}
AtomicString PerformanceMark::entryType() const {
- return PerformanceEntryNames::mark;
+ return performance_entry_names::kMark;
}
PerformanceEntryType PerformanceMark::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_mark.h b/chromium/third_party/blink/renderer/core/timing/performance_mark.h
index fdd362f3bb3..a47201761c1 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_mark.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_mark.h
@@ -41,9 +41,15 @@ class CORE_EXPORT PerformanceMark final : public PerformanceEntry {
const AtomicString& name,
double start_time,
const ScriptValue& detail) {
- return new PerformanceMark(script_state, name, start_time, detail);
+ return MakeGarbageCollected<PerformanceMark>(script_state, name, start_time,
+ detail);
}
+ PerformanceMark(ScriptState*,
+ const AtomicString& name,
+ double start_time,
+ const ScriptValue& detail);
+
AtomicString entryType() const override;
PerformanceEntryType EntryTypeEnum() const override;
@@ -52,11 +58,6 @@ class CORE_EXPORT PerformanceMark final : public PerformanceEntry {
void Trace(blink::Visitor*) override;
private:
- PerformanceMark(ScriptState*,
- const AtomicString& name,
- double start_time,
- const ScriptValue& detail);
-
~PerformanceMark() override = default;
scoped_refptr<DOMWrapperWorld> world_;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_mark.idl b/chromium/third_party/blink/renderer/core/timing/performance_mark.idl
index 24439659dc5..2dd8d60f38f 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_mark.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_mark.idl
@@ -25,6 +25,7 @@
// https://w3c.github.io/user-timing/#performancemark
+[Exposed=(Window,Worker)]
interface PerformanceMark : PerformanceEntry {
[CallWith=ScriptState, RuntimeEnabled=CustomUserTiming] readonly attribute any detail;
};
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_measure.cc b/chromium/third_party/blink/renderer/core/timing/performance_measure.cc
index d31f4bed1fa..0a6c3db671e 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_measure.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_measure.cc
@@ -31,7 +31,7 @@ ScriptValue PerformanceMeasure::detail(ScriptState* script_state) const {
}
AtomicString PerformanceMeasure::entryType() const {
- return PerformanceEntryNames::measure;
+ return performance_entry_names::kMeasure;
}
PerformanceEntryType PerformanceMeasure::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_measure.h b/chromium/third_party/blink/renderer/core/timing/performance_measure.h
index 43ba5068dfd..e80be2a29dc 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_measure.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_measure.h
@@ -43,9 +43,16 @@ class PerformanceMeasure final : public PerformanceEntry {
double start_time,
double end_time,
const ScriptValue& detail) {
- return new PerformanceMeasure(script_state, name, start_time, end_time,
- detail);
+ return MakeGarbageCollected<PerformanceMeasure>(
+ script_state, name, start_time, end_time, detail);
}
+
+ PerformanceMeasure(ScriptState*,
+ const AtomicString& name,
+ double start_time,
+ double end_time,
+ const ScriptValue& detail);
+
ScriptValue detail(ScriptState*) const;
AtomicString entryType() const override;
@@ -56,11 +63,6 @@ class PerformanceMeasure final : public PerformanceEntry {
}
private:
- PerformanceMeasure(ScriptState*,
- const AtomicString& name,
- double start_time,
- double end_time,
- const ScriptValue& detail);
~PerformanceMeasure() override = default;
scoped_refptr<SerializedScriptValue> detail_;
};
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_measure.idl b/chromium/third_party/blink/renderer/core/timing/performance_measure.idl
index b9546a605f1..2ee528c54cf 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_measure.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_measure.idl
@@ -25,6 +25,7 @@
// https://w3c.github.io/user-timing/#performancemeasure
+[Exposed=(Window,Worker)]
interface PerformanceMeasure : PerformanceEntry {
[CallWith=ScriptState, RuntimeEnabled=CustomUserTiming] readonly attribute any detail;
};
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_navigation.h b/chromium/third_party/blink/renderer/core/timing/performance_navigation.h
index faac8cb508f..36c987c82d6 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_navigation.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_navigation.h
@@ -50,9 +50,11 @@ class CORE_EXPORT PerformanceNavigation final : public ScriptWrappable,
public:
static PerformanceNavigation* Create(LocalFrame* frame) {
- return new PerformanceNavigation(frame);
+ return MakeGarbageCollected<PerformanceNavigation>(frame);
}
+ explicit PerformanceNavigation(LocalFrame*);
+
enum PerformanceNavigationType {
kTypeNavigate,
kTypeReload,
@@ -66,9 +68,6 @@ class CORE_EXPORT PerformanceNavigation final : public ScriptWrappable,
ScriptValue toJSONForBinding(ScriptState*) const;
void Trace(blink::Visitor*) override;
-
- private:
- explicit PerformanceNavigation(LocalFrame*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.cc
index 607eb330e45..69bd24b4744 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.cc
@@ -36,7 +36,7 @@ PerformanceNavigationTiming::PerformanceNavigationTiming(
PerformanceNavigationTiming::~PerformanceNavigationTiming() = default;
AtomicString PerformanceNavigationTiming::entryType() const {
- return PerformanceEntryNames::navigation;
+ return performance_entry_names::kNavigation;
}
PerformanceEntryType PerformanceNavigationTiming::EntryTypeEnum() const {
@@ -119,7 +119,7 @@ AtomicString PerformanceNavigationTiming::GetNavigationType(
}
AtomicString PerformanceNavigationTiming::initiatorType() const {
- return PerformanceEntryNames::navigation;
+ return performance_entry_names::kNavigation;
}
bool PerformanceNavigationTiming::GetAllowRedirectDetails() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.idl b/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.idl
index 9a46252e916..10c89e787d8 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.idl
@@ -11,7 +11,6 @@ enum NavigationType {
"prerender"
};
[
- RuntimeEnabled=PerformanceNavigationTiming2,
Exposed=Window
] interface PerformanceNavigationTiming : PerformanceResourceTiming {
readonly attribute DOMHighResTimeStamp unloadEventStart;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_observer.cc b/chromium/third_party/blink/renderer/core/timing/performance_observer.cc
index 9df0dbb3857..669310693dc 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_observer.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_observer.cc
@@ -31,15 +31,13 @@ PerformanceObserver* PerformanceObserver::Create(
ExecutionContext* context = ExecutionContext::From(script_state);
if (window) {
UseCounter::Count(context, WebFeature::kPerformanceObserverForWindow);
- return new PerformanceObserver(
+ return MakeGarbageCollected<PerformanceObserver>(
context, DOMWindowPerformance::performance(*window), callback);
}
- if (context->IsWorkerGlobalScope()) {
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(context)) {
UseCounter::Count(context, WebFeature::kPerformanceObserverForWorker);
- return new PerformanceObserver(context,
- WorkerGlobalScopePerformance::performance(
- *ToWorkerGlobalScope(context)),
- callback);
+ return MakeGarbageCollected<PerformanceObserver>(
+ context, WorkerGlobalScopePerformance::performance(*scope), callback);
}
V8ThrowException::ThrowTypeError(
script_state->GetIsolate(),
@@ -62,7 +60,7 @@ PerformanceObserver::PerformanceObserver(
DCHECK(performance_);
}
-void PerformanceObserver::observe(const PerformanceObserverInit& observer_init,
+void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
ExceptionState& exception_state) {
if (!performance_) {
exception_state.ThrowTypeError(
@@ -71,8 +69,8 @@ void PerformanceObserver::observe(const PerformanceObserverInit& observer_init,
}
PerformanceEntryTypeMask entry_types = PerformanceEntry::kInvalid;
- if (observer_init.hasEntryTypes() && observer_init.entryTypes().size()) {
- const Vector<String>& sequence = observer_init.entryTypes();
+ if (observer_init->hasEntryTypes() && observer_init->entryTypes().size()) {
+ const Vector<String>& sequence = observer_init->entryTypes();
for (const auto& entry_type_string : sequence) {
entry_types |=
PerformanceEntry::ToEntryTypeEnum(AtomicString(entry_type_string));
@@ -131,7 +129,7 @@ void PerformanceObserver::Deliver() {
PerformanceEntryVector performance_entries;
performance_entries.swap(performance_entries_);
PerformanceObserverEntryList* entry_list =
- new PerformanceObserverEntryList(performance_entries);
+ MakeGarbageCollected<PerformanceObserverEntryList>(performance_entries);
callback_->InvokeAndReportException(this, entry_list, this);
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_observer.h b/chromium/third_party/blink/renderer/core/timing/performance_observer.h
index 6d884e91215..b23b07a7a4d 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_observer.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_observer.h
@@ -39,7 +39,11 @@ class CORE_EXPORT PerformanceObserver final
V8PerformanceObserverCallback*);
static void ResumeSuspendedObservers();
- void observe(const PerformanceObserverInit&, ExceptionState&);
+ PerformanceObserver(ExecutionContext*,
+ Performance*,
+ V8PerformanceObserverCallback*);
+
+ void observe(const PerformanceObserverInit*, ExceptionState&);
void disconnect();
PerformanceEntryVector takeRecords();
void EnqueuePerformanceEntry(PerformanceEntry&);
@@ -51,9 +55,6 @@ class CORE_EXPORT PerformanceObserver final
void Trace(blink::Visitor*) override;
private:
- PerformanceObserver(ExecutionContext*,
- Performance*,
- V8PerformanceObserverCallback*);
void Deliver();
bool ShouldBeSuspended() const;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_observer_test.cc b/chromium/third_party/blink/renderer/core/timing/performance_observer_test.cc
index f11acd44a65..d4e9fcc4f9e 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_observer_test.cc
@@ -33,10 +33,10 @@ class PerformanceObserverTest : public testing::Test {
void Initialize(ScriptState* script_state) {
v8::Local<v8::Function> callback =
v8::Function::New(script_state->GetContext(), nullptr).ToLocalChecked();
- base_ = new MockPerformance(script_state);
+ base_ = MakeGarbageCollected<MockPerformance>(script_state);
cb_ = V8PerformanceObserverCallback::Create(callback);
- observer_ = new PerformanceObserver(ExecutionContext::From(script_state),
- base_, cb_);
+ observer_ = MakeGarbageCollected<PerformanceObserver>(
+ ExecutionContext::From(script_state), base_, cb_);
}
bool IsRegistered() { return observer_->is_registered_; }
@@ -53,10 +53,10 @@ TEST_F(PerformanceObserverTest, Observe) {
Initialize(scope.GetScriptState());
NonThrowableExceptionState exception_state;
- PerformanceObserverInit options;
+ PerformanceObserverInit* options = PerformanceObserverInit::Create();
Vector<String> entry_type_vec;
entry_type_vec.push_back("mark");
- options.setEntryTypes(entry_type_vec);
+ options->setEntryTypes(entry_type_vec);
observer_->observe(options, exception_state);
EXPECT_TRUE(IsRegistered());
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_paint_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_paint_timing.cc
index d6d0ce5c1fd..7d74bbb6c9d 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_paint_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_paint_timing.cc
@@ -39,7 +39,7 @@ PerformancePaintTiming::PerformancePaintTiming(PaintType type,
PerformancePaintTiming::~PerformancePaintTiming() = default;
AtomicString PerformancePaintTiming::entryType() const {
- return PerformanceEntryNames::paint;
+ return performance_entry_names::kPaint;
}
PerformanceEntryType PerformancePaintTiming::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.cc
index 3a28e131a35..b80b0629e53 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.cc
@@ -55,8 +55,9 @@ PerformanceResourceTiming::PerformanceResourceTiming(
time_origin,
info.finish_time,
info.allow_negative_values)),
- initiator_type_(initiator_type.IsEmpty() ? FetchInitiatorTypeNames::other
- : initiator_type),
+ initiator_type_(initiator_type.IsEmpty()
+ ? fetch_initiator_type_names::kOther
+ : initiator_type),
alpn_negotiated_protocol_(
static_cast<String>(info.alpn_negotiated_protocol)),
connection_info_(static_cast<String>(info.connection_info)),
@@ -88,7 +89,7 @@ PerformanceResourceTiming::PerformanceResourceTiming(
PerformanceResourceTiming::~PerformanceResourceTiming() = default;
AtomicString PerformanceResourceTiming::entryType() const {
- return PerformanceEntryNames::resource;
+ return performance_entry_names::kResource;
}
PerformanceEntryType PerformanceResourceTiming::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.h
index 115bb6bcfa1..919c4167cea 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_resource_timing.h
@@ -49,12 +49,21 @@ class CORE_EXPORT PerformanceResourceTiming : public PerformanceEntry {
friend class PerformanceResourceTimingTest;
public:
+ // This constructor is for PerformanceNavigationTiming.
+ // Related doc: https://goo.gl/uNecAj.
+ PerformanceResourceTiming(const AtomicString& name,
+ TimeTicks time_origin,
+ const WebVector<WebServerTimingInfo>&);
+ PerformanceResourceTiming(const WebResourceTimingInfo&,
+ TimeTicks time_origin,
+ const AtomicString& initiator_type);
~PerformanceResourceTiming() override;
static PerformanceResourceTiming* Create(
const WebResourceTimingInfo& info,
TimeTicks time_origin,
const AtomicString& initiator_type = g_null_atom) {
- return new PerformanceResourceTiming(info, time_origin, initiator_type);
+ return MakeGarbageCollected<PerformanceResourceTiming>(info, time_origin,
+ initiator_type);
}
AtomicString entryType() const override;
@@ -85,21 +94,12 @@ class CORE_EXPORT PerformanceResourceTiming : public PerformanceEntry {
protected:
void BuildJSONValue(V8ObjectBuilder&) const override;
- // This constructor is for PerformanceNavigationTiming.
- // Related doc: https://goo.gl/uNecAj.
- PerformanceResourceTiming(const AtomicString& name,
- TimeTicks time_origin,
- const WebVector<WebServerTimingInfo>&);
virtual AtomicString AlpnNegotiatedProtocol() const;
virtual AtomicString ConnectionInfo() const;
TimeTicks TimeOrigin() const { return time_origin_; }
private:
- PerformanceResourceTiming(const WebResourceTimingInfo&,
- TimeTicks time_origin,
- const AtomicString& initiator_type);
-
static AtomicString GetNextHopProtocol(
const AtomicString& alpn_negotiated_protocol,
const AtomicString& connection_info);
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_server_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_server_timing.cc
index 9bc079fc244..291804f767c 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_server_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_server_timing.cc
@@ -31,7 +31,7 @@ WebVector<WebServerTimingInfo> PerformanceServerTiming::ParseServerTiming(
WebVector<WebServerTimingInfo> result;
const ResourceResponse& response = info.FinalResponse();
std::unique_ptr<ServerTimingHeaderVector> headers = ParseServerTimingHeader(
- response.HttpHeaderField(HTTPNames::Server_Timing));
+ response.HttpHeaderField(http_names::kServerTiming));
result.reserve(headers->size());
for (const auto& header : *headers) {
result.emplace_back(header->Name(), header->Duration(),
@@ -45,8 +45,8 @@ PerformanceServerTiming::FromParsedServerTiming(
const WebVector<WebServerTimingInfo>& entries) {
HeapVector<Member<PerformanceServerTiming>> result;
for (const auto& entry : entries) {
- result.push_back(new PerformanceServerTiming(entry.name, entry.duration,
- entry.description));
+ result.push_back(MakeGarbageCollected<PerformanceServerTiming>(
+ entry.name, entry.duration, entry.description));
}
return result;
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_server_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_server_timing.h
index 4f453bc00a7..d32262a3b03 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_server_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_server_timing.h
@@ -20,6 +20,9 @@ class CORE_EXPORT PerformanceServerTiming final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
+ PerformanceServerTiming(const String& name,
+ double duration,
+ const String& description);
~PerformanceServerTiming() override;
const String& name() const { return name_; }
@@ -34,10 +37,6 @@ class CORE_EXPORT PerformanceServerTiming final : public ScriptWrappable {
ScriptValue toJSONForBinding(ScriptState*) const;
private:
- PerformanceServerTiming(const String& name,
- double duration,
- const String& description);
-
const String name_;
double duration_;
const String description_;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_test.cc b/chromium/third_party/blink/renderer/core/timing/performance_test.cc
index 8ac8b6b8264..794d21431f0 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_test.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_test.cc
@@ -4,8 +4,11 @@
#include "third_party/blink/renderer/core/timing/window_performance.h"
+#include "base/test/metrics/histogram_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_double.h"
+#include "third_party/blink/renderer/bindings/core/v8/string_or_double_or_performance_measure_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_performance_observer_callback.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
@@ -45,15 +48,15 @@ class PerformanceTest : public PageTestBase {
void Initialize(ScriptState* script_state) {
v8::Local<v8::Function> callback =
v8::Function::New(script_state->GetContext(), nullptr).ToLocalChecked();
- base_ = new TestPerformance(script_state);
+ base_ = MakeGarbageCollected<TestPerformance>(script_state);
cb_ = V8PerformanceObserverCallback::Create(callback);
- observer_ = new PerformanceObserver(ExecutionContext::From(script_state),
- base_, cb_);
+ observer_ = MakeGarbageCollected<PerformanceObserver>(
+ ExecutionContext::From(script_state), base_, cb_);
}
void SetUp() override {
PageTestBase::SetUp();
- execution_context_ = new NullExecutionContext();
+ execution_context_ = MakeGarbageCollected<NullExecutionContext>();
}
ExecutionContext* GetExecutionContext() { return execution_context_.Get(); }
@@ -127,10 +130,10 @@ TEST_F(PerformanceTest, AddLongTaskTiming) {
// Make an observer for longtask
NonThrowableExceptionState exception_state;
- PerformanceObserverInit options;
+ PerformanceObserverInit* options = PerformanceObserverInit::Create();
Vector<String> entry_type_vec;
entry_type_vec.push_back("longtask");
- options.setEntryTypes(entry_type_vec);
+ options->setEntryTypes(entry_type_vec);
observer_->observe(options, exception_state);
EXPECT_TRUE(base_->HasPerformanceObserverFor(PerformanceEntry::kLongTask));
@@ -171,11 +174,105 @@ TEST_F(PerformanceTest, AllowsTimingRedirect) {
GetExecutionContext()));
// When cross-origin redirect opts in.
- redirect_chain.back().SetHTTPHeaderField(HTTPNames::Timing_Allow_Origin,
+ redirect_chain.back().SetHTTPHeaderField(http_names::kTimingAllowOrigin,
origin_domain);
EXPECT_TRUE(AllowsTimingRedirect(redirect_chain, final_response,
*security_origin.get(),
GetExecutionContext()));
}
+TEST_F(PerformanceTest, MeasureParameters_StartEndBothUnprovided) {
+ base::HistogramTester histograms;
+ V8TestingScope scope;
+ DummyExceptionStateForTesting exception_state;
+ Initialize(scope.GetScriptState());
+ base_->measure(scope.GetScriptState(), "name", exception_state);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
+ Performance::MeasureParameterType::kUnprovided,
+ 1);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
+ Performance::MeasureParameterType::kUnprovided,
+ 1);
+}
+
+TEST_F(PerformanceTest, MeasureParameters_StartProvidedEndUnprovided) {
+ base::HistogramTester histograms;
+ V8TestingScope scope;
+ DummyExceptionStateForTesting exception_state;
+ Initialize(scope.GetScriptState());
+ base_->measure(scope.GetScriptState(), "name",
+ StringOrDoubleOrPerformanceMeasureOptions::FromDouble(1.1),
+ exception_state);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
+ Performance::MeasureParameterType::kNumber, 1);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
+ Performance::MeasureParameterType::kUnprovided,
+ 1);
+}
+
+TEST_F(PerformanceTest, MeasureParameters_StartEndBothProvided) {
+ base::HistogramTester histograms;
+ V8TestingScope scope;
+ DummyExceptionStateForTesting exception_state;
+ Initialize(scope.GetScriptState());
+ base_->measure(scope.GetScriptState(), "name",
+ StringOrDoubleOrPerformanceMeasureOptions::FromDouble(1.1),
+ StringOrDouble::FromDouble(1.1), exception_state);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
+ Performance::MeasureParameterType::kNumber, 1);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
+ Performance::MeasureParameterType::kNumber, 1);
+}
+
+TEST_F(PerformanceTest, MeasureParameters_ObjectType) {
+ base::HistogramTester histograms;
+ V8TestingScope scope;
+ DummyExceptionStateForTesting exception_state;
+ Initialize(scope.GetScriptState());
+ base_->measure(
+ scope.GetScriptState(), "name",
+ StringOrDoubleOrPerformanceMeasureOptions::FromPerformanceMeasureOptions(
+ PerformanceMeasureOptions::Create()),
+ exception_state);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
+ Performance::MeasureParameterType::kObjectObject,
+ 1);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
+ Performance::MeasureParameterType::kUnprovided,
+ 1);
+}
+
+TEST_F(PerformanceTest, MeasureParameters_NavigationTiming) {
+ base::HistogramTester histograms;
+ V8TestingScope scope;
+ DummyExceptionStateForTesting exception_state;
+ Initialize(scope.GetScriptState());
+ base_->measure(
+ scope.GetScriptState(), "name",
+ StringOrDoubleOrPerformanceMeasureOptions::FromString("unloadEventStart"),
+ exception_state);
+ histograms.ExpectBucketCount(
+ "Performance.MeasureParameter.StartMark",
+ Performance::MeasureParameterType::kUnloadEventStart, 1);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
+ Performance::MeasureParameterType::kUnprovided,
+ 1);
+}
+
+TEST_F(PerformanceTest, MeasureParameters_Other) {
+ base::HistogramTester histograms;
+ V8TestingScope scope;
+ DummyExceptionStateForTesting exception_state;
+ Initialize(scope.GetScriptState());
+ base_->measure(
+ scope.GetScriptState(), "name",
+ StringOrDoubleOrPerformanceMeasureOptions::FromString("aRandomString"),
+ exception_state);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
+ Performance::MeasureParameterType::kOther, 1);
+ histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
+ Performance::MeasureParameterType::kUnprovided,
+ 1);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_timing.cc
index 4568efbdfd7..6df8d5123a4 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_timing.cc
@@ -40,7 +40,10 @@
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/interactive_detector.h"
+#include "third_party/blink/renderer/core/paint/image_paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/paint_timing.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
@@ -364,6 +367,42 @@ unsigned long long PerformanceTiming::FirstMeaningfulPaintCandidate() const {
timing->FirstMeaningfulPaintCandidate());
}
+unsigned long long PerformanceTiming::LargestImagePaint() const {
+ PaintTimingDetector* paint_timing_detector = GetPaintTimingDetector();
+ if (!paint_timing_detector)
+ return 0;
+
+ return MonotonicTimeToIntegerMilliseconds(
+ paint_timing_detector->GetImagePaintTimingDetector().LargestImagePaint());
+}
+
+unsigned long long PerformanceTiming::LastImagePaint() const {
+ PaintTimingDetector* paint_timing_detector = GetPaintTimingDetector();
+ if (!paint_timing_detector)
+ return 0;
+
+ return MonotonicTimeToIntegerMilliseconds(
+ paint_timing_detector->GetImagePaintTimingDetector().LastImagePaint());
+}
+
+unsigned long long PerformanceTiming::LargestTextPaint() const {
+ PaintTimingDetector* paint_timing_detector = GetPaintTimingDetector();
+ if (!paint_timing_detector)
+ return 0;
+
+ return MonotonicTimeToIntegerMilliseconds(
+ paint_timing_detector->GetTextPaintTimingDetector().LargestTextPaint());
+}
+
+unsigned long long PerformanceTiming::LastTextPaint() const {
+ PaintTimingDetector* paint_timing_detector = GetPaintTimingDetector();
+ if (!paint_timing_detector)
+ return 0;
+
+ return MonotonicTimeToIntegerMilliseconds(
+ paint_timing_detector->GetTextPaintTimingDetector().LastTextPaint());
+}
+
unsigned long long PerformanceTiming::PageInteractive() const {
InteractiveDetector* interactive_detector = GetInteractiveDetector();
if (!interactive_detector)
@@ -548,6 +587,17 @@ InteractiveDetector* PerformanceTiming::GetInteractiveDetector() const {
return InteractiveDetector::From(*document);
}
+PaintTimingDetector* PerformanceTiming::GetPaintTimingDetector() const {
+ if (!GetFrame())
+ return nullptr;
+
+ LocalFrameView* view = GetFrame()->View();
+ if (!view)
+ return nullptr;
+
+ return &view->GetPaintTimingDetector();
+}
+
ScriptValue PerformanceTiming::toJSONForBinding(
ScriptState* script_state) const {
V8ObjectBuilder result(script_state);
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_timing.h
index 143c07921dd..3fdb85a9478 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_timing.h
@@ -47,6 +47,7 @@ class DocumentTiming;
class InteractiveDetector;
class LocalFrame;
class PaintTiming;
+class PaintTimingDetector;
class ResourceLoadTiming;
class ScriptState;
class ScriptValue;
@@ -59,9 +60,11 @@ class CORE_EXPORT PerformanceTiming final : public ScriptWrappable,
public:
static PerformanceTiming* Create(LocalFrame* frame) {
- return new PerformanceTiming(frame);
+ return MakeGarbageCollected<PerformanceTiming>(frame);
}
+ explicit PerformanceTiming(LocalFrame*);
+
unsigned long long navigationStart() const;
unsigned long long inputStart() const;
unsigned long long unloadEventStart() const;
@@ -108,6 +111,16 @@ class CORE_EXPORT PerformanceTiming final : public ScriptWrappable,
// TODO(crbug.com/848639): This function is exposed as an experiment, and if
// not useful, this function can be removed.
unsigned long long FirstMeaningfulPaintCandidate() const;
+ // The time of the first paint after the largest image within viewport being
+ // fully loaded.
+ unsigned long long LargestImagePaint() const;
+ // The time of the first paint after the last image within viewport being
+ // fully loaded.
+ unsigned long long LastImagePaint() const;
+ // The time of the first paint of the largest text within viewport.
+ unsigned long long LargestTextPaint() const;
+ // The time of the first paint of the last text within viewport.
+ unsigned long long LastTextPaint() const;
// The first time the page is considered 'interactive'. This is determined
// using heuristics based on main thread and network activity.
unsigned long long PageInteractive() const;
@@ -145,12 +158,11 @@ class CORE_EXPORT PerformanceTiming final : public ScriptWrappable,
unsigned long long MonotonicTimeToIntegerMilliseconds(TimeTicks) const;
private:
- explicit PerformanceTiming(LocalFrame*);
-
const DocumentTiming* GetDocumentTiming() const;
const CSSTiming* CssTiming() const;
const DocumentParserTiming* GetDocumentParserTiming() const;
const PaintTiming* GetPaintTiming() const;
+ PaintTimingDetector* GetPaintTimingDetector() const;
DocumentLoader* GetDocumentLoader() const;
DocumentLoadTiming* GetDocumentLoadTiming() const;
ResourceLoadTiming* GetResourceLoadTiming() const;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_user_timing.cc b/chromium/third_party/blink/renderer/core/timing/performance_user_timing.cc
index 595cb53dc12..82e9b3a6295 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_user_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_user_timing.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/timing/performance_user_timing.h"
#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/renderer/bindings/core/v8/double_or_performance_mark_options.h"
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/core/timing/performance_mark.h"
#include "third_party/blink/renderer/core/timing/performance_measure.h"
@@ -99,11 +100,39 @@ static void ClearPeformanceEntries(PerformanceEntryMap& performance_entry_map,
performance_entry_map.erase(name);
}
-PerformanceMark* UserTiming::Mark(ScriptState* script_state,
- const AtomicString& mark_name,
- const DOMHighResTimeStamp& start_time,
- const ScriptValue& detail,
- ExceptionState& exception_state) {
+PerformanceMark* UserTiming::Mark(
+ ScriptState* script_state,
+ const AtomicString& mark_name,
+ DoubleOrPerformanceMarkOptions& start_time_or_mark_options,
+ ExceptionState& exception_state) {
+ if (!RuntimeEnabledFeatures::CustomUserTimingEnabled())
+ DCHECK(start_time_or_mark_options.IsNull());
+
+ DOMHighResTimeStamp start = 0.0;
+ if (start_time_or_mark_options.IsDouble()) {
+ start = start_time_or_mark_options.GetAsDouble();
+ } else if (start_time_or_mark_options.IsPerformanceMarkOptions() &&
+ start_time_or_mark_options.GetAsPerformanceMarkOptions()
+ ->hasStartTime()) {
+ start =
+ start_time_or_mark_options.GetAsPerformanceMarkOptions()->startTime();
+ } else {
+ start = performance_->now();
+ }
+
+ // Pass in a null ScriptValue if the mark's detail doesn't exist.
+ ScriptValue detail = ScriptValue::CreateNull(script_state);
+ if (start_time_or_mark_options.IsPerformanceMarkOptions())
+ detail = start_time_or_mark_options.GetAsPerformanceMarkOptions()->detail();
+
+ return MarkInternal(script_state, mark_name, start, detail, exception_state);
+}
+
+PerformanceMark* UserTiming::MarkInternal(ScriptState* script_state,
+ const AtomicString& mark_name,
+ const DOMHighResTimeStamp& start_time,
+ const ScriptValue& detail,
+ ExceptionState& exception_state) {
if (GetRestrictedKeyMap().Contains(mark_name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
@@ -201,11 +230,11 @@ PerformanceMeasure* UserTiming::Measure(ScriptState* script_state,
TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0(
"blink.user_timing", measure_name.Utf8().data(),
WTF::StringHash::GetHash(measure_name),
- TraceEvent::ToTraceTimestamp(start_time_monotonic));
+ trace_event::ToTraceTimestamp(start_time_monotonic));
TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0(
"blink.user_timing", measure_name.Utf8().data(),
WTF::StringHash::GetHash(measure_name),
- TraceEvent::ToTraceTimestamp(end_time_monotonic));
+ trace_event::ToTraceTimestamp(end_time_monotonic));
PerformanceMeasure* measure = PerformanceMeasure::Create(
script_state, measure_name, start_time, end_time, detail);
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_user_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_user_timing.h
index a824355d4dd..98e0b6728d3 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_user_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_user_timing.h
@@ -44,14 +44,17 @@ using PerformanceEntryMap = HeapHashMap<AtomicString, PerformanceEntryVector>;
class UserTiming final : public GarbageCollected<UserTiming> {
public:
static UserTiming* Create(Performance& performance) {
- return new UserTiming(performance);
+ return MakeGarbageCollected<UserTiming>(performance);
}
- PerformanceMark* Mark(ScriptState*,
- const AtomicString& mark_name,
- const DOMHighResTimeStamp& start_time,
- const ScriptValue& detail,
- ExceptionState&);
+ explicit UserTiming(Performance&);
+
+ PerformanceMark* Mark(
+ ScriptState* script_state,
+ const AtomicString& mark_name,
+ DoubleOrPerformanceMarkOptions& start_time_or_mark_options,
+ ExceptionState& exception_state);
+
void ClearMarks(const AtomicString& mark_name);
PerformanceMeasure* Measure(ScriptState*,
@@ -71,8 +74,11 @@ class UserTiming final : public GarbageCollected<UserTiming> {
void Trace(blink::Visitor*);
private:
- explicit UserTiming(Performance&);
-
+ PerformanceMark* MarkInternal(ScriptState*,
+ const AtomicString& mark_name,
+ const DOMHighResTimeStamp& start_time,
+ const ScriptValue& detail,
+ ExceptionState&);
double FindExistingMarkStartTime(const AtomicString& mark_name,
ExceptionState&);
double FindStartMarkOrTime(const StringOrDouble& start, ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.cc b/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.cc
index e52f954168f..3ed5fab503d 100644
--- a/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.cc
@@ -28,7 +28,7 @@ TaskAttributionTiming::TaskAttributionTiming(const AtomicString& name,
TaskAttributionTiming::~TaskAttributionTiming() = default;
AtomicString TaskAttributionTiming::entryType() const {
- return PerformanceEntryNames::taskattribution;
+ return performance_entry_names::kTaskattribution;
}
PerformanceEntryType TaskAttributionTiming::EntryTypeEnum() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.h b/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.h
index 835fdf73970..2d9b0fccf1b 100644
--- a/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/task_attribution_timing.h
@@ -25,9 +25,9 @@ class TaskAttributionTiming final : public PerformanceEntry {
double start_time,
double finish_time,
const String& script_url) {
- return new TaskAttributionTiming(type, container_type, container_src,
- container_id, container_name, start_time,
- finish_time, script_url);
+ return MakeGarbageCollected<TaskAttributionTiming>(
+ type, container_type, container_src, container_id, container_name,
+ start_time, finish_time, script_url);
}
// Used when the LongTaskV2 flag is disabled.
@@ -36,9 +36,9 @@ class TaskAttributionTiming final : public PerformanceEntry {
const String& container_src,
const String& container_id,
const String& container_name) {
- return new TaskAttributionTiming(type, container_type, container_src,
- container_id, container_name, 0.0, 0.0,
- g_empty_string);
+ return MakeGarbageCollected<TaskAttributionTiming>(
+ type, container_type, container_src, container_id, container_name, 0.0,
+ 0.0, g_empty_string);
}
AtomicString entryType() const override;
@@ -52,9 +52,6 @@ class TaskAttributionTiming final : public PerformanceEntry {
void Trace(blink::Visitor*) override;
- ~TaskAttributionTiming() override;
-
- private:
TaskAttributionTiming(const AtomicString& type,
const String& container_type,
const String& container_src,
@@ -63,6 +60,9 @@ class TaskAttributionTiming final : public PerformanceEntry {
double start_time,
double finish_time,
const String& script_url);
+ ~TaskAttributionTiming() override;
+
+ private:
void BuildJSONValue(V8ObjectBuilder&) const override;
String container_type_;
diff --git a/chromium/third_party/blink/renderer/core/timing/time_clamper.h b/chromium/third_party/blink/renderer/core/timing/time_clamper.h
index b1bfc222e4a..d8644eed218 100644
--- a/chromium/third_party/blink/renderer/core/timing/time_clamper.h
+++ b/chromium/third_party/blink/renderer/core/timing/time_clamper.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_TIME_CLAMPER_H_
#include "base/macros.h"
+#include "build/build_config.h"
#include "third_party/blink/renderer/core/core_export.h"
#include <stdint.h>
@@ -14,11 +15,17 @@ namespace blink {
class CORE_EXPORT TimeClamper {
public:
- static constexpr double kResolutionSeconds = 0.0001;
+// As site isolation is enabled on desktop platforms, we can safely provide
+// more timing resolution. Jittering is still enabled everywhere.
+#if defined(OS_ANDROID)
+ static constexpr double kResolutionSeconds = 100e-6;
+#else
+ static constexpr double kResolutionSeconds = 5e-6;
+#endif
TimeClamper();
- // Deterministically clamp the time value |time_seconds| to a 100us interval
+ // Deterministically clamp the time value |time_seconds| to a fixed interval
// to prevent timing attacks. See
// http://www.w3.org/TR/hr-time-2/#privacy-security.
//
diff --git a/chromium/third_party/blink/renderer/core/timing/window_performance.cc b/chromium/third_party/blink/renderer/core/timing/window_performance.cc
index 366a16c62b6..9004cc77168 100644
--- a/chromium/third_party/blink/renderer/core/timing/window_performance.cc
+++ b/chromium/third_party/blink/renderer/core/timing/window_performance.cc
@@ -173,16 +173,11 @@ MemoryInfo* WindowPerformance::memory() const {
}
bool WindowPerformance::shouldYield() const {
- return Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->ShouldYieldForHighPriorityWork();
+ return ThreadScheduler::Current()->ShouldYieldForHighPriorityWork();
}
PerformanceNavigationTiming*
WindowPerformance::CreateNavigationTimingInstance() {
- if (!RuntimeEnabledFeatures::PerformanceNavigationTiming2Enabled())
- return nullptr;
if (!GetFrame())
return nullptr;
const DocumentLoader* document_loader =
@@ -196,8 +191,8 @@ WindowPerformance::CreateNavigationTimingInstance() {
PerformanceServerTiming::ParseServerTiming(*info);
if (!server_timing.empty())
UseCounter::Count(GetFrame(), WebFeature::kPerformanceServerTiming);
- return new PerformanceNavigationTiming(GetFrame(), info, time_origin_,
- server_timing);
+ return MakeGarbageCollected<PerformanceNavigationTiming>(
+ GetFrame(), info, time_origin_, server_timing);
}
void WindowPerformance::UpdateLongTaskInstrumentation() {
@@ -325,9 +320,9 @@ void WindowPerformance::ReportLongTask(
culprit_dom_window->GetFrame()->DeprecatedLocalOwner();
AddLongTaskTiming(
start_time, end_time, attribution.first,
- GetFrameAttribute(frame_owner, HTMLNames::srcAttr, false),
- GetFrameAttribute(frame_owner, HTMLNames::idAttr, false),
- GetFrameAttribute(frame_owner, HTMLNames::nameAttr, true),
+ GetFrameAttribute(frame_owner, html_names::kSrcAttr, false),
+ GetFrameAttribute(frame_owner, html_names::kIdAttr, false),
+ GetFrameAttribute(frame_owner, html_names::kNameAttr, true),
IsSameOrigin(attribution.first) ? sub_task_attributions : empty_vector);
}
}
@@ -343,7 +338,7 @@ void WindowPerformance::RegisterEventTiming(const AtomicString& event_type,
TimeTicks processing_start,
TimeTicks processing_end,
bool cancelable) {
- DCHECK(OriginTrials::EventTimingEnabled(GetExecutionContext()));
+ DCHECK(origin_trials::EventTimingEnabled(GetExecutionContext()));
DCHECK(!start_time.is_null());
DCHECK(!processing_start.is_null());
@@ -373,7 +368,7 @@ void WindowPerformance::RegisterEventTiming(const AtomicString& event_type,
void WindowPerformance::ReportEventTimings(WebLayerTreeView::SwapResult result,
TimeTicks timestamp) {
- DCHECK(OriginTrials::EventTimingEnabled(GetExecutionContext()));
+ DCHECK(origin_trials::EventTimingEnabled(GetExecutionContext()));
DOMHighResTimeStamp end_time = MonotonicTimeToDOMHighResTimeStamp(timestamp);
for (const auto& entry : event_timings_) {
@@ -417,7 +412,7 @@ void WindowPerformance::AddElementTiming(const AtomicString& name,
void WindowPerformance::DispatchFirstInputTiming(
PerformanceEventTiming* entry) {
- DCHECK(OriginTrials::EventTimingEnabled(GetExecutionContext()));
+ DCHECK(origin_trials::EventTimingEnabled(GetExecutionContext()));
first_input_detected_ = true;
if (!entry)
diff --git a/chromium/third_party/blink/renderer/core/timing/window_performance.h b/chromium/third_party/blink/renderer/core/timing/window_performance.h
index d937e83cfb0..086795e57aa 100644
--- a/chromium/third_party/blink/renderer/core/timing/window_performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/window_performance.h
@@ -52,8 +52,10 @@ class CORE_EXPORT WindowPerformance final : public Performance,
public:
static WindowPerformance* Create(LocalDOMWindow* window) {
- return new WindowPerformance(window);
+ return MakeGarbageCollected<WindowPerformance>(window);
}
+
+ explicit WindowPerformance(LocalDOMWindow*);
~WindowPerformance() override;
ExecutionContext* GetExecutionContext() const override;
@@ -69,6 +71,8 @@ class CORE_EXPORT WindowPerformance final : public Performance,
bool ShouldBufferEventTiming();
+ bool FirstInputDetected() const { return first_input_detected_; }
+
// This method creates a PerformanceEventTiming and if needed creates a swap
// promise to calculate the |duration| attribute when such promise is
// resolved.
@@ -87,8 +91,6 @@ class CORE_EXPORT WindowPerformance final : public Performance,
void Trace(blink::Visitor*) override;
private:
- explicit WindowPerformance(LocalDOMWindow*);
-
PerformanceNavigationTiming* CreateNavigationTimingInstance() override;
static std::pair<AtomicString, DOMWindow*> SanitizedAttribution(
diff --git a/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.cc b/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.cc
index e62c1995c95..33c98128c77 100644
--- a/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.cc
+++ b/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.cc
@@ -48,7 +48,8 @@ WorkerGlobalScopePerformance& WorkerGlobalScopePerformance::From(
Supplement<WorkerGlobalScope>::From<WorkerGlobalScopePerformance>(
worker_global_scope);
if (!supplement) {
- supplement = new WorkerGlobalScopePerformance(worker_global_scope);
+ supplement =
+ MakeGarbageCollected<WorkerGlobalScopePerformance>(worker_global_scope);
ProvideTo(worker_global_scope, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.h b/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.h
index ee297ebab9a..2d1a86f87f2 100644
--- a/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.h
@@ -53,11 +53,11 @@ class CORE_EXPORT WorkerGlobalScopePerformance final
static WorkerPerformance* performance(WorkerGlobalScope&);
+ explicit WorkerGlobalScopePerformance(WorkerGlobalScope&);
+
void Trace(blink::Visitor*) override;
private:
- explicit WorkerGlobalScopePerformance(WorkerGlobalScope&);
-
WorkerPerformance* performance(WorkerGlobalScope*);
TraceWrapperMember<WorkerPerformance> performance_;
diff --git a/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.idl b/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.idl
index eded72d1a7d..bd18fd2ce01 100644
--- a/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.idl
+++ b/chromium/third_party/blink/renderer/core/timing/worker_global_scope_performance.idl
@@ -35,5 +35,5 @@
[
ImplementedAs=WorkerGlobalScopePerformance
] partial interface WorkerGlobalScope {
- readonly attribute WorkerPerformance performance;
+ [Replaceable] readonly attribute WorkerPerformance performance;
};
diff --git a/chromium/third_party/blink/renderer/core/timing/worker_performance.h b/chromium/third_party/blink/renderer/core/timing/worker_performance.h
index 04d1e1abe6a..25b65cd050d 100644
--- a/chromium/third_party/blink/renderer/core/timing/worker_performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/worker_performance.h
@@ -44,9 +44,11 @@ class WorkerGlobalScope;
class WorkerPerformance final : public Performance {
public:
static WorkerPerformance* Create(WorkerGlobalScope* context) {
- return new WorkerPerformance(context);
+ return MakeGarbageCollected<WorkerPerformance>(context);
}
+ explicit WorkerPerformance(WorkerGlobalScope*);
+
ExecutionContext* GetExecutionContext() const override {
return execution_context_;
}
@@ -54,8 +56,6 @@ class WorkerPerformance final : public Performance {
void Trace(blink::Visitor*) override;
private:
- explicit WorkerPerformance(WorkerGlobalScope*);
-
Member<ExecutionContext> execution_context_;
};
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_html.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_html.h
index 684c75ee573..ca102e4fe64 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_html.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_html.h
@@ -16,15 +16,15 @@ class CORE_EXPORT TrustedHTML final : public ScriptWrappable {
public:
static TrustedHTML* Create(const String& html) {
- return new TrustedHTML(html);
+ return MakeGarbageCollected<TrustedHTML>(html);
}
+ TrustedHTML(const String& html);
+
// TrustedHTML.idl
String toString() const;
private:
- TrustedHTML(const String& html);
-
const String html_;
};
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script.h
index 23b31353b57..3a5abb5ecd8 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script.h
@@ -16,15 +16,15 @@ class CORE_EXPORT TrustedScript final : public ScriptWrappable {
public:
static TrustedScript* Create(const String& script) {
- return new TrustedScript(script);
+ return MakeGarbageCollected<TrustedScript>(script);
}
+ TrustedScript(const String& script);
+
// TrustedScript.idl
String toString() const;
private:
- TrustedScript(const String& script);
-
const String script_;
};
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script_url.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script_url.h
index 0192ac9fe82..0ea47303791 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script_url.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_script_url.h
@@ -22,15 +22,15 @@ class CORE_EXPORT TrustedScriptURL final : public ScriptWrappable {
public:
static TrustedScriptURL* Create(const KURL& url) {
- return new TrustedScriptURL(url);
+ return MakeGarbageCollected<TrustedScriptURL>(url);
}
+ TrustedScriptURL(const KURL&);
+
// TrustedScriptURL.idl
String toString() const;
private:
- TrustedScriptURL(const KURL&);
-
KURL url_;
};
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc
index b632dfc3e2f..468f1ec5cf7 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.cc
@@ -14,33 +14,59 @@
namespace blink {
-TrustedTypePolicy::TrustedTypePolicy(
- const String& policy_name,
- const TrustedTypePolicyOptions& policy_options,
- bool exposed)
+TrustedTypePolicy::TrustedTypePolicy(const String& policy_name,
+ TrustedTypePolicyOptions* policy_options,
+ bool exposed)
: name_(policy_name), policy_options_(policy_options) {
- policy_options_.setExposed(exposed);
+ policy_options_->setExposed(exposed);
}
TrustedTypePolicy* TrustedTypePolicy::Create(
const String& policy_name,
- const TrustedTypePolicyOptions& policy_options,
+ TrustedTypePolicyOptions* policy_options,
bool exposed) {
- return new TrustedTypePolicy(policy_name, policy_options, exposed);
+ return MakeGarbageCollected<TrustedTypePolicy>(policy_name, policy_options,
+ exposed);
}
TrustedHTML* TrustedTypePolicy::createHTML(ScriptState* script_state,
const String& input,
ExceptionState& exception_state) {
- if (!policy_options_.createHTML()) {
+ return CreateHTML(script_state->GetIsolate(), input, exception_state);
+}
+
+TrustedScript* TrustedTypePolicy::createScript(
+ ScriptState* script_state,
+ const String& input,
+ ExceptionState& exception_state) {
+ return CreateScript(script_state->GetIsolate(), input, exception_state);
+}
+
+TrustedScriptURL* TrustedTypePolicy::createScriptURL(
+ ScriptState* script_state,
+ const String& input,
+ ExceptionState& exception_state) {
+ return CreateScriptURL(script_state->GetIsolate(), input, exception_state);
+}
+
+TrustedURL* TrustedTypePolicy::createURL(ScriptState* script_state,
+ const String& input,
+ ExceptionState& exception_state) {
+ return CreateURL(script_state->GetIsolate(), input, exception_state);
+}
+
+TrustedHTML* TrustedTypePolicy::CreateHTML(v8::Isolate* isolate,
+ const String& input,
+ ExceptionState& exception_state) {
+ if (!policy_options_->createHTML()) {
exception_state.ThrowTypeError(
"Policy " + name_ +
"'s TrustedTypePolicyOptions did not specify a 'createHTML' member.");
return nullptr;
}
- v8::TryCatch try_catch(script_state->GetIsolate());
+ v8::TryCatch try_catch(isolate);
String html;
- if (!policy_options_.createHTML()->Invoke(nullptr, input).To(&html)) {
+ if (!policy_options_->createHTML()->Invoke(nullptr, input).To(&html)) {
DCHECK(try_catch.HasCaught());
exception_state.RethrowV8Exception(try_catch.Exception());
return nullptr;
@@ -48,19 +74,19 @@ TrustedHTML* TrustedTypePolicy::createHTML(ScriptState* script_state,
return TrustedHTML::Create(html);
}
-TrustedScript* TrustedTypePolicy::createScript(
- ScriptState* script_state,
+TrustedScript* TrustedTypePolicy::CreateScript(
+ v8::Isolate* isolate,
const String& input,
ExceptionState& exception_state) {
- if (!policy_options_.createScript()) {
+ if (!policy_options_->createScript()) {
exception_state.ThrowTypeError(
"Policy " + name_ +
"'s TrustedTypePolicyOptions did not specify a 'createScript' member.");
return nullptr;
}
- v8::TryCatch try_catch(script_state->GetIsolate());
+ v8::TryCatch try_catch(isolate);
String script;
- if (!policy_options_.createScript()->Invoke(nullptr, input).To(&script)) {
+ if (!policy_options_->createScript()->Invoke(nullptr, input).To(&script)) {
DCHECK(try_catch.HasCaught());
exception_state.RethrowV8Exception(try_catch.Exception());
return nullptr;
@@ -68,19 +94,19 @@ TrustedScript* TrustedTypePolicy::createScript(
return TrustedScript::Create(script);
}
-TrustedScriptURL* TrustedTypePolicy::createScriptURL(
- ScriptState* script_state,
+TrustedScriptURL* TrustedTypePolicy::CreateScriptURL(
+ v8::Isolate* isolate,
const String& input,
ExceptionState& exception_state) {
- if (!policy_options_.createScriptURL()) {
+ if (!policy_options_->createScriptURL()) {
exception_state.ThrowTypeError("Policy " + name_ +
"'s TrustedTypePolicyOptions did not "
"specify a 'createScriptURL' member.");
return nullptr;
}
- v8::TryCatch try_catch(script_state->GetIsolate());
+ v8::TryCatch try_catch(isolate);
String script_url;
- if (!policy_options_.createScriptURL()
+ if (!policy_options_->createScriptURL()
->Invoke(nullptr, input)
.To(&script_url)) {
DCHECK(try_catch.HasCaught());
@@ -90,18 +116,18 @@ TrustedScriptURL* TrustedTypePolicy::createScriptURL(
return TrustedScriptURL::Create(KURL(script_url));
}
-TrustedURL* TrustedTypePolicy::createURL(ScriptState* script_state,
+TrustedURL* TrustedTypePolicy::CreateURL(v8::Isolate* isolate,
const String& input,
ExceptionState& exception_state) {
- if (!policy_options_.createURL()) {
+ if (!policy_options_->createURL()) {
exception_state.ThrowTypeError(
"Policy " + name_ +
"'s TrustedTypePolicyOptions did not specify a 'createURL' member.");
return nullptr;
}
- v8::TryCatch try_catch(script_state->GetIsolate());
+ v8::TryCatch try_catch(isolate);
String url;
- if (!policy_options_.createURL()->Invoke(nullptr, input).To(&url)) {
+ if (!policy_options_->createURL()->Invoke(nullptr, input).To(&url)) {
DCHECK(try_catch.HasCaught());
exception_state.RethrowV8Exception(try_catch.Exception());
return nullptr;
@@ -114,11 +140,12 @@ String TrustedTypePolicy::name() const {
}
bool TrustedTypePolicy::exposed() const {
- return policy_options_.exposed();
+ return policy_options_->exposed();
}
void TrustedTypePolicy::Trace(blink::Visitor* visitor) {
visitor->Trace(policy_options_);
ScriptWrappable::Trace(visitor);
}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.h
index 35b1e18dbf0..fcbbf061270 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.h
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "v8/include/v8.h"
namespace blink {
@@ -24,9 +25,22 @@ class CORE_EXPORT TrustedTypePolicy final : public ScriptWrappable {
public:
static TrustedTypePolicy* Create(const String& policy_name,
- const TrustedTypePolicyOptions&,
+ TrustedTypePolicyOptions*,
bool exposed);
+ TrustedTypePolicy(const String& policy_name,
+ TrustedTypePolicyOptions*,
+ bool exposed);
+
+ TrustedHTML* CreateHTML(v8::Isolate*, const String&, ExceptionState&);
+ TrustedScript* CreateScript(v8::Isolate*, const String&, ExceptionState&);
+ TrustedScriptURL* CreateScriptURL(v8::Isolate*,
+ const String&,
+ ExceptionState&);
+ TrustedURL* CreateURL(v8::Isolate*, const String&, ExceptionState&);
+
+ // IDL generates calls with ScriptState*, which contains the Isolate*.
+ // These methods all call the Isolate* variant.
TrustedHTML* createHTML(ScriptState*, const String&, ExceptionState&);
TrustedScript* createScript(ScriptState*, const String&, ExceptionState&);
TrustedScriptURL* createScriptURL(ScriptState*,
@@ -41,12 +55,8 @@ class CORE_EXPORT TrustedTypePolicy final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- TrustedTypePolicy(const String& policy_name,
- const TrustedTypePolicyOptions&,
- bool exposed);
-
String name_;
- TrustedTypePolicyOptions policy_options_;
+ Member<TrustedTypePolicyOptions> policy_options_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl
index fb1ac33b123..60f712be382 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy.idl
@@ -10,9 +10,9 @@ typedef (DOMString or TrustedHTML or TrustedScript or TrustedScriptURL or Truste
Exposed=Window,
RuntimeEnabled=TrustedDOMTypes
] interface TrustedTypePolicy {
- readonly attribute DOMString name;
- [CallWith=ScriptState, RaisesException] TrustedHTML createHTML(DOMString input);
- [CallWith=ScriptState, RaisesException] TrustedScript createScript(DOMString input);
- [CallWith=ScriptState, RaisesException] TrustedScriptURL createScriptURL(DOMString input);
- [CallWith=ScriptState, RaisesException] TrustedURL createURL(DOMString input);
+ [Unforgeable] readonly attribute DOMString name;
+ [CallWith=ScriptState, RaisesException, Unforgeable] TrustedHTML createHTML(DOMString input);
+ [CallWith=ScriptState, RaisesException, Unforgeable] TrustedScript createScript(DOMString input);
+ [CallWith=ScriptState, RaisesException, Unforgeable] TrustedScriptURL createScriptURL(DOMString input);
+ [CallWith=ScriptState, RaisesException, Unforgeable] TrustedURL createURL(DOMString input);
};
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc
index 5c7404ef905..5b9676c5605 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc
@@ -21,7 +21,7 @@ namespace blink {
TrustedTypePolicy* TrustedTypePolicyFactory::createPolicy(
const String& policy_name,
- const TrustedTypePolicyOptions& policy_options,
+ const TrustedTypePolicyOptions* policy_options,
bool exposed,
ExceptionState& exception_state) {
if (!GetFrame()
@@ -34,12 +34,18 @@ TrustedTypePolicy* TrustedTypePolicyFactory::createPolicy(
// TODO(orsibatiz): After policy naming rules are estabilished, check for the
// policy_name to be according to them.
if (policy_map_.Contains(policy_name)) {
- exception_state.ThrowTypeError("Policy with name" + policy_name +
+ exception_state.ThrowTypeError("Policy with name " + policy_name +
" already exists.");
return nullptr;
}
- TrustedTypePolicy* policy =
- TrustedTypePolicy::Create(policy_name, policy_options, exposed);
+ if (policy_name == "default" && !exposed) {
+ exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
+ "The default policy must be exposed.");
+ return nullptr;
+ }
+ TrustedTypePolicy* policy = TrustedTypePolicy::Create(
+ policy_name, const_cast<TrustedTypePolicyOptions*>(policy_options),
+ exposed);
policy_map_.insert(policy_name, policy);
return policy;
}
@@ -82,7 +88,7 @@ bool TrustedTypePolicyFactory::isHTML(ScriptState* script_state,
const WrapperTypeInfo* wrapper_type_info =
GetWrapperTypeInfoFromScriptValue(script_state, script_value);
return wrapper_type_info &&
- wrapper_type_info->Equals(&V8TrustedHTML::wrapperTypeInfo);
+ wrapper_type_info->Equals(&V8TrustedHTML::wrapper_type_info);
}
bool TrustedTypePolicyFactory::isScript(ScriptState* script_state,
@@ -90,7 +96,7 @@ bool TrustedTypePolicyFactory::isScript(ScriptState* script_state,
const WrapperTypeInfo* wrapper_type_info =
GetWrapperTypeInfoFromScriptValue(script_state, script_value);
return wrapper_type_info &&
- wrapper_type_info->Equals(&V8TrustedScript::wrapperTypeInfo);
+ wrapper_type_info->Equals(&V8TrustedScript::wrapper_type_info);
}
bool TrustedTypePolicyFactory::isScriptURL(ScriptState* script_state,
@@ -98,7 +104,7 @@ bool TrustedTypePolicyFactory::isScriptURL(ScriptState* script_state,
const WrapperTypeInfo* wrapper_type_info =
GetWrapperTypeInfoFromScriptValue(script_state, script_value);
return wrapper_type_info &&
- wrapper_type_info->Equals(&V8TrustedScriptURL::wrapperTypeInfo);
+ wrapper_type_info->Equals(&V8TrustedScriptURL::wrapper_type_info);
}
bool TrustedTypePolicyFactory::isURL(ScriptState* script_state,
@@ -106,7 +112,7 @@ bool TrustedTypePolicyFactory::isURL(ScriptState* script_state,
const WrapperTypeInfo* wrapper_type_info =
GetWrapperTypeInfoFromScriptValue(script_state, script_value);
return wrapper_type_info &&
- wrapper_type_info->Equals(&V8TrustedURL::wrapperTypeInfo);
+ wrapper_type_info->Equals(&V8TrustedURL::wrapper_type_info);
}
void TrustedTypePolicyFactory::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h
index 7ac03691166..88a6a37c249 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h
@@ -27,12 +27,14 @@ class CORE_EXPORT TrustedTypePolicyFactory final : public ScriptWrappable,
public:
static TrustedTypePolicyFactory* Create(LocalFrame* frame) {
- return new TrustedTypePolicyFactory(frame);
+ return MakeGarbageCollected<TrustedTypePolicyFactory>(frame);
}
+ explicit TrustedTypePolicyFactory(LocalFrame*);
+
// TrustedTypePolicyFactory.idl
TrustedTypePolicy* createPolicy(const String&,
- const TrustedTypePolicyOptions&,
+ const TrustedTypePolicyOptions*,
bool exposed,
ExceptionState&);
@@ -48,8 +50,6 @@ class CORE_EXPORT TrustedTypePolicyFactory final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
private:
- explicit TrustedTypePolicyFactory(LocalFrame*);
-
const WrapperTypeInfo* GetWrapperTypeInfoFromScriptValue(ScriptState*,
const ScriptValue&);
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl
index df5289de64b..2174192ee9b 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl
@@ -8,12 +8,12 @@
Exposed=Window,
RuntimeEnabled=TrustedDOMTypes
] interface TrustedTypePolicyFactory {
- [RaisesException] TrustedTypePolicy createPolicy(DOMString policyName, TrustedTypePolicyOptions policyOptions, optional boolean exposed = false);
- TrustedTypePolicy getExposedPolicy(DOMString policyName);
+ [RaisesException, Unforgeable] TrustedTypePolicy createPolicy(DOMString policyName, TrustedTypePolicyOptions policyOptions, optional boolean exposed = false);
+ [Unforgeable] TrustedTypePolicy getExposedPolicy(DOMString policyName);
// All the policy object names that have been created
- [Affects=Nothing] sequence<DOMString> getPolicyNames();
- [CallWith=ScriptState] boolean isHTML(object? checkedObject);
- [CallWith=ScriptState] boolean isScript(object? checkedObject);
- [CallWith=ScriptState] boolean isScriptURL(object? checkedObject);
- [CallWith=ScriptState] boolean isURL(object? checkedObject);
+ [Affects=Nothing, Unforgeable] sequence<DOMString> getPolicyNames();
+ [CallWith=ScriptState, Unforgeable] boolean isHTML(object? checkedObject);
+ [CallWith=ScriptState, Unforgeable] boolean isScript(object? checkedObject);
+ [CallWith=ScriptState, Unforgeable] boolean isScriptURL(object? checkedObject);
+ [CallWith=ScriptState, Unforgeable] boolean isURL(object? checkedObject);
};
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc
index 93ccd48e8a6..068d0750e15 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc
@@ -9,10 +9,14 @@
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script_url.h"
#include "third_party/blink/renderer/bindings/core/v8/usv_string_or_trusted_url.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_html.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_script.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_script_url.h"
+#include "third_party/blink/renderer/core/trustedtypes/trusted_type_policy.h"
+#include "third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_url.h"
namespace blink {
@@ -68,17 +72,34 @@ String GetStringFromTrustedHTML(StringOrTrustedHTML string_or_trusted_html,
RuntimeEnabledFeatures::TrustedDOMTypesEnabled());
DCHECK(!string_or_trusted_html.IsNull());
- if (!string_or_trusted_html.IsTrustedHTML() && doc &&
- doc->RequireTrustedTypes()) {
+ bool require_trusted_type = doc && doc->RequireTrustedTypes();
+ if (!require_trusted_type && string_or_trusted_html.IsString()) {
+ return string_or_trusted_html.GetAsString();
+ }
+
+ if (string_or_trusted_html.IsTrustedHTML()) {
+ return string_or_trusted_html.GetAsTrustedHTML()->toString();
+ }
+
+ TrustedTypePolicy* default_policy =
+ doc->ExecutingWindow()->trustedTypes()->getExposedPolicy("default");
+ if (!default_policy) {
exception_state.ThrowTypeError(
"This document requires `TrustedHTML` assignment.");
return g_empty_string;
}
- String markup = string_or_trusted_html.IsString()
- ? string_or_trusted_html.GetAsString()
- : string_or_trusted_html.GetAsTrustedHTML()->toString();
- return markup;
+ TrustedHTML* result = default_policy->CreateHTML(
+ ToIsolate(doc), string_or_trusted_html.GetAsString(), exception_state);
+ if (exception_state.HadException()) {
+ exception_state.ClearException();
+ exception_state.ThrowTypeError(
+ "This document requires `TrustedHTML` assignment and 'default' policy "
+ "failed to execute.");
+ return g_empty_string;
+ }
+
+ return result->toString();
}
String GetStringFromTrustedScript(
@@ -87,20 +108,56 @@ String GetStringFromTrustedScript(
ExceptionState& exception_state) {
DCHECK(string_or_trusted_script.IsString() ||
RuntimeEnabledFeatures::TrustedDOMTypesEnabled());
- DCHECK(!string_or_trusted_script.IsNull());
- if (!string_or_trusted_script.IsTrustedScript() && doc &&
- doc->RequireTrustedTypes()) {
+ // To remain compatible with legacy behaviour, HTMLElement uses extended IDL
+ // attributes to allow for nullable union of (DOMString or TrustedScript).
+ // Thus, this method is required to handle the case where
+ // string_or_trusted_script.IsNull(), unlike the various similar methods in
+ // this file.
+
+ bool require_trusted_type = doc && doc->RequireTrustedTypes();
+ if (!require_trusted_type) {
+ if (string_or_trusted_script.IsString()) {
+ return string_or_trusted_script.GetAsString();
+ }
+ if (string_or_trusted_script.IsNull()) {
+ return g_empty_string;
+ }
+ }
+
+ if (string_or_trusted_script.IsTrustedScript()) {
+ return string_or_trusted_script.GetAsTrustedScript()->toString();
+ }
+
+ DCHECK(require_trusted_type);
+ DCHECK(string_or_trusted_script.IsNull() ||
+ string_or_trusted_script.IsString());
+
+ TrustedTypePolicy* default_policy =
+ doc->ExecutingWindow()->trustedTypes()->getExposedPolicy("default");
+ if (!default_policy) {
exception_state.ThrowTypeError(
"This document requires `TrustedScript` assignment.");
return g_empty_string;
}
- String markup =
- string_or_trusted_script.IsString()
- ? string_or_trusted_script.GetAsString()
- : string_or_trusted_script.GetAsTrustedScript()->toString();
- return markup;
+ const String& string_value_or_empty =
+ string_or_trusted_script.IsNull()
+ ? g_empty_string
+ : string_or_trusted_script.GetAsString();
+ TrustedScript* result = default_policy->CreateScript(
+ ToIsolate(doc), string_value_or_empty, exception_state);
+ DCHECK_EQ(!result, exception_state.HadException());
+ if (exception_state.HadException()) {
+ exception_state.ClearException();
+ exception_state.ThrowTypeError(
+ "This document requires `TrustedScript` assignment and 'default' "
+ "policy "
+ "failed to execute.");
+ return g_empty_string;
+ }
+
+ return result->toString();
}
String GetStringFromTrustedScriptURL(
@@ -111,18 +168,37 @@ String GetStringFromTrustedScriptURL(
RuntimeEnabledFeatures::TrustedDOMTypesEnabled());
DCHECK(!string_or_trusted_script_url.IsNull());
- if (!string_or_trusted_script_url.IsTrustedScriptURL() && doc &&
- doc->RequireTrustedTypes()) {
+ bool require_trusted_type = doc && doc->RequireTrustedTypes();
+ if (!require_trusted_type && string_or_trusted_script_url.IsString()) {
+ return string_or_trusted_script_url.GetAsString();
+ }
+
+ if (string_or_trusted_script_url.IsTrustedScriptURL()) {
+ return string_or_trusted_script_url.GetAsTrustedScriptURL()->toString();
+ }
+
+ TrustedTypePolicy* default_policy =
+ doc->ExecutingWindow()->trustedTypes()->getExposedPolicy("default");
+ if (!default_policy) {
exception_state.ThrowTypeError(
"This document requires `TrustedScriptURL` assignment.");
return g_empty_string;
}
- String markup =
- string_or_trusted_script_url.IsString()
- ? string_or_trusted_script_url.GetAsString()
- : string_or_trusted_script_url.GetAsTrustedScriptURL()->toString();
- return markup;
+ TrustedScriptURL* result = default_policy->CreateScriptURL(
+ ToIsolate(doc), string_or_trusted_script_url.GetAsString(),
+ exception_state);
+
+ if (exception_state.HadException()) {
+ exception_state.ClearException();
+ exception_state.ThrowTypeError(
+ "This document requires `TrustedScriptURL` assignment and 'default' "
+ "policy "
+ "failed to execute.");
+ return g_empty_string;
+ }
+
+ return result->toString();
}
String GetStringFromTrustedURL(USVStringOrTrustedURL string_or_trusted_url,
@@ -132,16 +208,33 @@ String GetStringFromTrustedURL(USVStringOrTrustedURL string_or_trusted_url,
RuntimeEnabledFeatures::TrustedDOMTypesEnabled());
DCHECK(!string_or_trusted_url.IsNull());
- if (!string_or_trusted_url.IsTrustedURL() && doc &&
- doc->RequireTrustedTypes()) {
+ bool require_trusted_type = doc && doc->RequireTrustedTypes();
+ if (!require_trusted_type && string_or_trusted_url.IsUSVString()) {
+ return string_or_trusted_url.GetAsUSVString();
+ }
+
+ if (string_or_trusted_url.IsTrustedURL()) {
+ return string_or_trusted_url.GetAsTrustedURL()->toString();
+ }
+
+ TrustedTypePolicy* default_policy =
+ doc->ExecutingWindow()->trustedTypes()->getExposedPolicy("default");
+ if (!default_policy) {
exception_state.ThrowTypeError(
"This document requires `TrustedURL` assignment.");
return g_empty_string;
}
- String markup = string_or_trusted_url.IsUSVString()
- ? string_or_trusted_url.GetAsUSVString()
- : string_or_trusted_url.GetAsTrustedURL()->toString();
- return markup;
+ TrustedURL* result = default_policy->CreateURL(
+ ToIsolate(doc), string_or_trusted_url.GetAsUSVString(), exception_state);
+ if (exception_state.HadException()) {
+ exception_state.ClearException();
+ exception_state.ThrowTypeError(
+ "This document requires `TrustedURL` assignment and 'default' policy "
+ "failed to execute.");
+ return g_empty_string;
+ }
+
+ return result->toString();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util_test.cc b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util_test.cc
index 40d3c246abf..f17780dbc1b 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util_test.cc
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script_url.h"
#include "third_party/blink/renderer/bindings/core/v8/usv_string_or_trusted_url.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_html.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_script.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_script_url.h"
@@ -37,11 +38,14 @@ void GetStringFromTrustedTypeThrows(
void GetStringFromTrustedHTMLThrows(
const StringOrTrustedHTML& string_or_trusted_html) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
ASSERT_FALSE(exception_state.HadException());
- String s = GetStringFromTrustedHTML(string_or_trusted_html, document,
+ String s = GetStringFromTrustedHTML(string_or_trusted_html, &document,
exception_state);
EXPECT_TRUE(exception_state.HadException());
EXPECT_EQ(ESErrorType::kTypeError, exception_state.CodeAs<ESErrorType>());
@@ -50,11 +54,14 @@ void GetStringFromTrustedHTMLThrows(
void GetStringFromTrustedScriptThrows(
const StringOrTrustedScript& string_or_trusted_script) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
ASSERT_FALSE(exception_state.HadException());
- String s = GetStringFromTrustedScript(string_or_trusted_script, document,
+ String s = GetStringFromTrustedScript(string_or_trusted_script, &document,
exception_state);
EXPECT_TRUE(exception_state.HadException());
EXPECT_EQ(ESErrorType::kTypeError, exception_state.CodeAs<ESErrorType>());
@@ -63,12 +70,15 @@ void GetStringFromTrustedScriptThrows(
void GetStringFromTrustedScriptURLThrows(
const StringOrTrustedScriptURL& string_or_trusted_script_url) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
ASSERT_FALSE(exception_state.HadException());
String s = GetStringFromTrustedScriptURL(string_or_trusted_script_url,
- document, exception_state);
+ &document, exception_state);
EXPECT_TRUE(exception_state.HadException());
EXPECT_EQ(ESErrorType::kTypeError, exception_state.CodeAs<ESErrorType>());
exception_state.ClearException();
@@ -76,12 +86,15 @@ void GetStringFromTrustedScriptURLThrows(
void GetStringFromTrustedURLThrows(
const USVStringOrTrustedURL& string_or_trusted_url) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
ASSERT_FALSE(exception_state.HadException());
- String s =
- GetStringFromTrustedURL(string_or_trusted_url, document, exception_state);
+ String s = GetStringFromTrustedURL(string_or_trusted_url, &document,
+ exception_state);
EXPECT_TRUE(exception_state.HadException());
EXPECT_EQ(ESErrorType::kTypeError, exception_state.CodeAs<ESErrorType>());
exception_state.ClearException();
@@ -103,10 +116,13 @@ void GetStringFromTrustedTypeWorks(
void GetStringFromTrustedHTMLWorks(
const StringOrTrustedHTML& string_or_trusted_html,
String expected) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
- String s = GetStringFromTrustedHTML(string_or_trusted_html, document,
+ String s = GetStringFromTrustedHTML(string_or_trusted_html, &document,
exception_state);
ASSERT_EQ(s, expected);
}
@@ -114,10 +130,13 @@ void GetStringFromTrustedHTMLWorks(
void GetStringFromTrustedScriptWorks(
const StringOrTrustedScript& string_or_trusted_script,
String expected) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
- String s = GetStringFromTrustedScript(string_or_trusted_script, document,
+ String s = GetStringFromTrustedScript(string_or_trusted_script, &document,
exception_state);
ASSERT_EQ(s, expected);
}
@@ -125,22 +144,28 @@ void GetStringFromTrustedScriptWorks(
void GetStringFromTrustedScriptURLWorks(
const StringOrTrustedScriptURL& string_or_trusted_script_url,
String expected) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
String s = GetStringFromTrustedScriptURL(string_or_trusted_script_url,
- document, exception_state);
+ &document, exception_state);
ASSERT_EQ(s, expected);
}
void GetStringFromTrustedURLWorks(
const USVStringOrTrustedURL& string_or_trusted_url,
String expected) {
- Document* document = Document::CreateForTest();
- document->SetRequireTrustedTypes();
+ std::unique_ptr<DummyPageHolder> dummy_page_holder =
+ DummyPageHolder::Create(IntSize(800, 600));
+ Document& document = dummy_page_holder->GetDocument();
+ document.SetRequireTrustedTypes();
+ V8TestingScope scope;
DummyExceptionStateForTesting exception_state;
- String s =
- GetStringFromTrustedURL(string_or_trusted_url, document, exception_state);
+ String s = GetStringFromTrustedURL(string_or_trusted_url, &document,
+ exception_state);
ASSERT_EQ(s, expected);
}
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_url.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_url.h
index ce677ad814e..df18273aa9d 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_url.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_url.h
@@ -21,14 +21,16 @@ class CORE_EXPORT TrustedURL final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static TrustedURL* Create(const KURL& url) { return new TrustedURL(url); }
+ static TrustedURL* Create(const KURL& url) {
+ return MakeGarbageCollected<TrustedURL>(url);
+ }
+
+ TrustedURL(const KURL&);
// TrustedURL.idl
String toString() const;
private:
- TrustedURL(const KURL&);
-
KURL url_;
};
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h b/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h
index e07467790a2..382addc0478 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h
@@ -18,7 +18,7 @@ class CORE_EXPORT DOMArrayBuffer final : public DOMArrayBufferBase {
public:
static DOMArrayBuffer* Create(scoped_refptr<WTF::ArrayBuffer> buffer) {
- return new DOMArrayBuffer(std::move(buffer));
+ return MakeGarbageCollected<DOMArrayBuffer>(std::move(buffer));
}
static DOMArrayBuffer* Create(unsigned num_elements,
unsigned element_byte_size) {
@@ -37,6 +37,9 @@ class CORE_EXPORT DOMArrayBuffer final : public DOMArrayBufferBase {
static DOMArrayBuffer* CreateUninitializedOrNull(unsigned num_elements,
unsigned element_byte_size);
+ explicit DOMArrayBuffer(scoped_refptr<WTF::ArrayBuffer> buffer)
+ : DOMArrayBufferBase(std::move(buffer)) {}
+
DOMArrayBuffer* Slice(int begin, int end) const {
return Create(Buffer()->Slice(begin, end));
}
@@ -52,10 +55,6 @@ class CORE_EXPORT DOMArrayBuffer final : public DOMArrayBufferBase {
v8::Local<v8::Object> Wrap(v8::Isolate*,
v8::Local<v8::Object> creation_context) override;
-
- private:
- explicit DOMArrayBuffer(scoped_refptr<WTF::ArrayBuffer> buffer)
- : DOMArrayBufferBase(std::move(buffer)) {}
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc b/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc
index ab73dabef99..d74a335e245 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.cc
@@ -48,7 +48,7 @@ DOMDataView* DOMDataView::Create(DOMArrayBufferBase* buffer,
unsigned byte_length) {
scoped_refptr<DataView> data_view =
DataView::Create(buffer->Buffer(), byte_offset, byte_length);
- return new DOMDataView(data_view, buffer);
+ return MakeGarbageCollected<DOMDataView>(data_view, buffer);
}
v8::Local<v8::Object> DOMDataView::Wrap(
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.h b/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.h
index 57301ebf553..842ab16b9db 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.h
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/dom_data_view.h
@@ -20,13 +20,12 @@ class CORE_EXPORT DOMDataView final : public DOMArrayBufferView {
unsigned byte_offset,
unsigned byte_length);
- v8::Local<v8::Object> Wrap(v8::Isolate*,
- v8::Local<v8::Object> creation_context) override;
-
- private:
DOMDataView(scoped_refptr<WTF::ArrayBufferView> data_view,
DOMArrayBufferBase* dom_array_buffer)
: DOMArrayBufferView(std::move(data_view), dom_array_buffer) {}
+
+ v8::Local<v8::Object> Wrap(v8::Isolate*,
+ v8::Local<v8::Object> creation_context) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h b/chromium/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h
index ee351509be0..aa50e28521c 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/dom_shared_array_buffer.h
@@ -17,7 +17,7 @@ class CORE_EXPORT DOMSharedArrayBuffer final : public DOMArrayBufferBase {
public:
static DOMSharedArrayBuffer* Create(scoped_refptr<WTF::ArrayBuffer> buffer) {
DCHECK(buffer->IsShared());
- return new DOMSharedArrayBuffer(std::move(buffer));
+ return MakeGarbageCollected<DOMSharedArrayBuffer>(std::move(buffer));
}
static DOMSharedArrayBuffer* Create(unsigned num_elements,
unsigned element_byte_size) {
@@ -33,16 +33,15 @@ class CORE_EXPORT DOMSharedArrayBuffer final : public DOMArrayBufferBase {
return Create(WTF::ArrayBuffer::Create(contents));
}
+ explicit DOMSharedArrayBuffer(scoped_refptr<WTF::ArrayBuffer> buffer)
+ : DOMArrayBufferBase(std::move(buffer)) {}
+
bool ShareContentsWith(WTF::ArrayBufferContents& result) {
return Buffer()->ShareContentsWith(result);
}
v8::Local<v8::Object> Wrap(v8::Isolate*,
v8::Local<v8::Object> creation_context) override;
-
- private:
- explicit DOMSharedArrayBuffer(scoped_refptr<WTF::ArrayBuffer> buffer)
- : DOMArrayBufferBase(std::move(buffer)) {}
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/dom_typed_array.cc b/chromium/third_party/blink/renderer/core/typed_arrays/dom_typed_array.cc
index d4787d79d23..db878ac323e 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/dom_typed_array.cc
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/dom_typed_array.cc
@@ -72,7 +72,7 @@ template <typename WTFTypedArray, typename V8TypedArray>
const WrapperTypeInfo*
DOMTypedArray<WTFTypedArray, V8TypedArray>::GetWrapperTypeInfo() const {
return &DOMTypedArrayTraits<
- DOMTypedArray<WTFTypedArray, V8TypedArray>>::Type::wrapperTypeInfo;
+ DOMTypedArray<WTFTypedArray, V8TypedArray>>::Type::wrapper_type_info;
}
template class CORE_TEMPLATE_EXPORT
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h b/chromium/third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h
index 2e6cd3f880f..ae2828225ab 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/flexible_array_buffer_view.h
@@ -43,7 +43,7 @@ class CORE_EXPORT FlexibleArrayBufferView {
// FlexibleArrayBufferView object.
void* BaseAddressMaybeOnStack() const {
DCHECK(!IsEmpty());
- return IsFull() ? full_->BaseAddress() : small_data_;
+ return IsFull() ? full_->BaseAddressMaybeShared() : small_data_;
}
unsigned ByteOffset() const {
diff --git a/chromium/third_party/blink/renderer/core/url/dom_url.h b/chromium/third_party/blink/renderer/core/url/dom_url.h
index 7eed738beff..13432a8511a 100644
--- a/chromium/third_party/blink/renderer/core/url/dom_url.h
+++ b/chromium/third_party/blink/renderer/core/url/dom_url.h
@@ -46,14 +46,17 @@ class DOMURL final : public ScriptWrappable, public DOMURLUtils {
public:
static DOMURL* Create(const String& url, ExceptionState& exception_state) {
- return new DOMURL(url, BlankURL(), exception_state);
+ return MakeGarbageCollected<DOMURL>(url, BlankURL(), exception_state);
}
static DOMURL* Create(const String& url,
const String& base,
ExceptionState& exception_state) {
- return new DOMURL(url, KURL(NullURL(), base), exception_state);
+ return MakeGarbageCollected<DOMURL>(url, KURL(NullURL(), base),
+ exception_state);
}
+
+ DOMURL(const String& url, const KURL& base, ExceptionState&);
~DOMURL() override;
CORE_EXPORT static String CreatePublicURL(ExecutionContext*, URLRegistrable*);
@@ -74,7 +77,6 @@ class DOMURL final : public ScriptWrappable, public DOMURLUtils {
private:
friend class URLSearchParams;
- DOMURL(const String& url, const KURL& base, ExceptionState&);
void Update();
void UpdateSearchParams(const String&);
diff --git a/chromium/third_party/blink/renderer/core/url/url.idl b/chromium/third_party/blink/renderer/core/url/url.idl
index 7750ce23be6..58fd2eba88a 100644
--- a/chromium/third_party/blink/renderer/core/url/url.idl
+++ b/chromium/third_party/blink/renderer/core/url/url.idl
@@ -32,11 +32,6 @@
ImplementedAs=DOMURL,
RaisesException=Constructor
] interface URL {
- // TODO(foolip): Implement domainToASCII() and domainToUnicode().
- // crbug.com/493908
- // static USVString domainToASCII(USVString domain);
- // static USVString domainToUnicode(USVString domain);
-
stringifier attribute USVString href;
readonly attribute USVString origin;
diff --git a/chromium/third_party/blink/renderer/core/url/url_search_params.cc b/chromium/third_party/blink/renderer/core/url/url_search_params.cc
index 799fcd463f8..e29f88a5abd 100644
--- a/chromium/third_party/blink/renderer/core/url/url_search_params.cc
+++ b/chromium/third_party/blink/renderer/core/url/url_search_params.cc
@@ -58,8 +58,8 @@ URLSearchParams* URLSearchParams::Create(const URLSearchParamsInit& init,
if (init.IsUSVString()) {
const String& query_string = init.GetAsUSVString();
if (query_string.StartsWith('?'))
- return new URLSearchParams(query_string.Substring(1));
- return new URLSearchParams(query_string);
+ return MakeGarbageCollected<URLSearchParams>(query_string.Substring(1));
+ return MakeGarbageCollected<URLSearchParams>(query_string);
}
if (init.IsUSVStringUSVStringRecord()) {
return URLSearchParams::Create(init.GetAsUSVStringUSVStringRecord(),
@@ -71,12 +71,12 @@ URLSearchParams* URLSearchParams::Create(const URLSearchParamsInit& init,
}
DCHECK(init.IsNull());
- return new URLSearchParams(String());
+ return MakeGarbageCollected<URLSearchParams>(String());
}
URLSearchParams* URLSearchParams::Create(const Vector<Vector<String>>& init,
ExceptionState& exception_state) {
- URLSearchParams* instance = new URLSearchParams(String());
+ URLSearchParams* instance = MakeGarbageCollected<URLSearchParams>(String());
if (!init.size())
return instance;
for (unsigned i = 0; i < init.size(); ++i) {
@@ -101,7 +101,7 @@ URLSearchParams::URLSearchParams(const String& query_string, DOMURL* url_object)
URLSearchParams* URLSearchParams::Create(
const Vector<std::pair<String, String>>& init,
ExceptionState& exception_state) {
- URLSearchParams* instance = new URLSearchParams(String());
+ URLSearchParams* instance = MakeGarbageCollected<URLSearchParams>(String());
if (init.IsEmpty())
return instance;
for (const auto& item : init)
diff --git a/chromium/third_party/blink/renderer/core/url/url_search_params.h b/chromium/third_party/blink/renderer/core/url/url_search_params.h
index 8714f8fa773..9a60514708b 100644
--- a/chromium/third_party/blink/renderer/core/url/url_search_params.h
+++ b/chromium/third_party/blink/renderer/core/url/url_search_params.h
@@ -36,9 +36,10 @@ class CORE_EXPORT URLSearchParams final : public ScriptWrappable,
static URLSearchParams* Create(const String& query_string,
DOMURL* url_object = nullptr) {
- return new URLSearchParams(query_string, url_object);
+ return MakeGarbageCollected<URLSearchParams>(query_string, url_object);
}
+ explicit URLSearchParams(const String&, DOMURL* = nullptr);
~URLSearchParams() override;
// URLSearchParams interface methods
@@ -65,8 +66,6 @@ class CORE_EXPORT URLSearchParams final : public ScriptWrappable,
private:
FRIEND_TEST_ALL_PREFIXES(URLSearchParamsTest, EncodedFormData);
- explicit URLSearchParams(const String&, DOMURL* = nullptr);
-
void RunUpdateSteps();
IterationSource* StartIteration(ScriptState*, ExceptionState&) override;
void EncodeAsFormData(Vector<char>&) const;
diff --git a/chromium/third_party/blink/renderer/core/url/url_utils_read_only.idl b/chromium/third_party/blink/renderer/core/url/url_utils_read_only.idl
deleted file mode 100644
index 4b15bf8540c..00000000000
--- a/chromium/third_party/blink/renderer/core/url/url_utils_read_only.idl
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This interface was defined independently in the WHATWG URL spec, but has
-// been removed from it in
-// https://github.com/whatwg/url/commit/c2877946857bc904ecb8a5805abc423c82d9da98.
-// It's now inlined in the users. See crbug.com/699873.
-
-[
- NoInterfaceObject, // Always used on target of 'implements'
- Exposed=(Window,Worker)
-] interface URLUtilsReadOnly {
- stringifier readonly attribute USVString href;
- readonly attribute USVString origin;
-
- readonly attribute USVString protocol;
- readonly attribute USVString host;
- readonly attribute USVString hostname;
- readonly attribute USVString port;
- readonly attribute USVString pathname;
- readonly attribute USVString search;
- readonly attribute USVString hash;
-};
diff --git a/chromium/third_party/blink/renderer/core/workers/BUILD.gn b/chromium/third_party/blink/renderer/core/workers/BUILD.gn
index 3c36f4d8f1e..eef62db95d7 100644
--- a/chromium/third_party/blink/renderer/core/workers/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/workers/BUILD.gn
@@ -18,12 +18,17 @@ blink_core_sources("workers") {
"dedicated_worker_object_proxy.h",
"dedicated_worker_thread.cc",
"dedicated_worker_thread.h",
- "execution_context_worker_registry.cc",
- "execution_context_worker_registry.h",
"experimental/task.cc",
"experimental/task.h",
+ "experimental/task_worklet.cc",
+ "experimental/task_worklet.h",
+ "experimental/task_worklet_global_scope.cc",
+ "experimental/task_worklet_global_scope.h",
"experimental/thread_pool.cc",
"experimental/thread_pool.h",
+ "experimental/thread_pool_thread.cc",
+ "experimental/thread_pool_thread.h",
+ "experimental/window_task_worklet.h",
"experimental/worker_task_queue.cc",
"experimental/worker_task_queue.h",
"global_scope_creation_params.cc",
@@ -66,8 +71,6 @@ blink_core_sources("workers") {
"worker_content_settings_client.h",
"worker_global_scope.cc",
"worker_global_scope.h",
- "worker_inspector_proxy.cc",
- "worker_inspector_proxy.h",
"worker_location.h",
"worker_module_tree_client.cc",
"worker_module_tree_client.h",
diff --git a/chromium/third_party/blink/renderer/core/workers/abstract_worker.h b/chromium/third_party/blink/renderer/core/workers/abstract_worker.h
index baa93fa0c87..0806f823087 100644
--- a/chromium/third_party/blink/renderer/core/workers/abstract_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/abstract_worker.h
@@ -57,7 +57,7 @@ class CORE_EXPORT AbstractWorker : public EventTargetWithInlineData,
return ContextLifecycleObserver::GetExecutionContext();
}
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error, kError);
AbstractWorker(ExecutionContext*);
~AbstractWorker() override;
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
index a058c4ba3d8..9a26e641af3 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
@@ -8,6 +8,7 @@
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/dedicated_worker_factory.mojom-blink.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_layer_tree_view.h"
@@ -20,6 +21,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
+#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/messaging/post_message_options.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -33,6 +35,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
namespace blink {
@@ -56,7 +59,7 @@ ConnectToWorkerInterfaceProvider(
DedicatedWorker* DedicatedWorker::Create(ExecutionContext* context,
const String& url,
- const WorkerOptions& options,
+ const WorkerOptions* options,
ExceptionState& exception_state) {
DCHECK(context->IsContextThread());
UseCounter::Count(context, WebFeature::kWorkerStart);
@@ -76,7 +79,7 @@ DedicatedWorker* DedicatedWorker::Create(ExecutionContext* context,
// TODO(nhiroki): Remove this flag check once module loading for
// DedicatedWorker is enabled by default (https://crbug.com/680046).
- if (options.type() == "module" &&
+ if (options->type() == "module" &&
!RuntimeEnabledFeatures::ModuleDedicatedWorkerEnabled()) {
exception_state.ThrowTypeError(
"Module scripts are not supported on DedicatedWorker yet. You can try "
@@ -88,19 +91,20 @@ DedicatedWorker* DedicatedWorker::Create(ExecutionContext* context,
if (context->IsWorkerGlobalScope())
UseCounter::Count(context, WebFeature::kNestedDedicatedWorker);
- DedicatedWorker* worker =
- new DedicatedWorker(context, script_request_url, options);
+ DedicatedWorker* worker = MakeGarbageCollected<DedicatedWorker>(
+ context, script_request_url, options);
worker->Start();
return worker;
}
DedicatedWorker::DedicatedWorker(ExecutionContext* context,
const KURL& script_request_url,
- const WorkerOptions& options)
+ const WorkerOptions* options)
: AbstractWorker(context),
script_request_url_(script_request_url),
options_(options),
- context_proxy_(new DedicatedWorkerMessagingProxy(context, this)) {
+ context_proxy_(
+ MakeGarbageCollected<DedicatedWorkerMessagingProxy>(context, this)) {
DCHECK(context->IsContextThread());
DCHECK(script_request_url_.IsValid());
DCHECK(context_proxy_);
@@ -115,15 +119,15 @@ void DedicatedWorker::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void DedicatedWorker::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
DCHECK(GetExecutionContext()->IsContextThread());
@@ -163,43 +167,37 @@ void DedicatedWorker::Start() {
ThreadDebugger::From(ToIsolate(GetExecutionContext()))
->StoreCurrentStackTrace("Worker Created");
- // Step 13: "Obtain script by switching on the value of options's type
- // member:"
- if (options_.type() == "classic") {
- // "classic: Fetch a classic worker script given url, outside settings,
- // destination, and inside settings."
- network::mojom::FetchRequestMode fetch_request_mode =
- network::mojom::FetchRequestMode::kSameOrigin;
- network::mojom::FetchCredentialsMode fetch_credentials_mode =
- network::mojom::FetchCredentialsMode::kSameOrigin;
- classic_script_loader_ = WorkerClassicScriptLoader::Create();
+ if (RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled() ||
+ options_->type() == "module") {
+ // Specify empty source code here because scripts will be fetched on the
+ // worker thread.
+ auto* outside_settings_object =
+ GetExecutionContext()->CreateFetchClientSettingsObjectSnapshot();
+ context_proxy_->StartWorkerGlobalScope(
+ CreateGlobalScopeCreationParams(
+ script_request_url_, network::mojom::ReferrerPolicy::kDefault),
+ options_, script_request_url_, outside_settings_object, stack_id,
+ String() /* source_code */);
+ return;
+ }
+ if (options_->type() == "classic") {
+ // Legacy code path (to be deprecated, see https://crbug.com/835717):
+ // A worker thread will start after scripts are fetched on the current
+ // thread.
+ classic_script_loader_ = MakeGarbageCollected<WorkerClassicScriptLoader>();
classic_script_loader_->LoadTopLevelScriptAsynchronously(
*GetExecutionContext(), script_request_url_,
- mojom::RequestContextType::WORKER, fetch_request_mode,
- fetch_credentials_mode,
+ mojom::RequestContextType::WORKER,
+ network::mojom::FetchRequestMode::kSameOrigin,
+ network::mojom::FetchCredentialsMode::kSameOrigin,
GetExecutionContext()->GetSecurityContext().AddressSpace(),
+ GetExecutionContext()->IsWorkerGlobalScope(),
WTF::Bind(&DedicatedWorker::OnResponse, WrapPersistent(this)),
WTF::Bind(&DedicatedWorker::OnFinished, WrapPersistent(this),
stack_id));
return;
}
- if (options_.type() == "module") {
- // "module: Fetch a module worker script graph given url, outside settings,
- // destination, the value of the credentials member of options, and inside
- // settings."
- //
- // Specify empty source code here because module scripts will be fetched on
- // the worker thread as opposed to classic scripts that are fetched on the
- // main thread.
- auto* outside_settings_object =
- GetExecutionContext()->CreateFetchClientSettingsObjectSnapshot();
- context_proxy_->StartWorkerGlobalScope(
- CreateGlobalScopeCreationParams(script_request_url_), options_,
- script_request_url_, outside_settings_object, stack_id,
- String() /* source_code */);
- return;
- }
- NOTREACHED() << "Invalid type: " << options_.type();
+ NOTREACHED() << "Invalid type: " << options_->type();
}
void DedicatedWorker::terminate() {
@@ -245,7 +243,7 @@ bool DedicatedWorker::HasPendingActivity() const {
}
const String DedicatedWorker::Name() const {
- return options_.name();
+ return options_->name();
}
WorkerClients* DedicatedWorker::CreateWorkerClients() {
@@ -282,9 +280,10 @@ void DedicatedWorker::OnFinished(const v8_inspector::V8StackTraceId& stack_id) {
if (classic_script_loader_->Canceled()) {
// Do nothing.
} else if (classic_script_loader_->Failed()) {
- DispatchEvent(*Event::CreateCancelable(EventTypeNames::error));
+ DispatchEvent(*Event::CreateCancelable(event_type_names::kError));
} else {
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
if (!classic_script_loader_->GetReferrerPolicy().IsNull()) {
SecurityPolicy::ReferrerPolicyFromHeaderValue(
classic_script_loader_->GetReferrerPolicy(),
@@ -294,14 +293,11 @@ void DedicatedWorker::OnFinished(const v8_inspector::V8StackTraceId& stack_id) {
DCHECK(script_request_url_ == script_response_url ||
SecurityOrigin::AreSameSchemeHostPort(script_request_url_,
script_response_url));
- std::unique_ptr<GlobalScopeCreationParams> creation_params =
- CreateGlobalScopeCreationParams(script_response_url);
- creation_params->referrer_policy = referrer_policy;
auto* outside_settings_object =
GetExecutionContext()->CreateFetchClientSettingsObjectSnapshot();
context_proxy_->StartWorkerGlobalScope(
- std::move(creation_params), options_, script_response_url,
- outside_settings_object, stack_id,
+ CreateGlobalScopeCreationParams(script_response_url, referrer_policy),
+ options_, script_response_url, outside_settings_object, stack_id,
classic_script_loader_->SourceText());
probe::scriptImported(GetExecutionContext(),
classic_script_loader_->Identifier(),
@@ -311,32 +307,52 @@ void DedicatedWorker::OnFinished(const v8_inspector::V8StackTraceId& stack_id) {
}
std::unique_ptr<GlobalScopeCreationParams>
-DedicatedWorker::CreateGlobalScopeCreationParams(const KURL& script_url) {
- base::UnguessableToken devtools_worker_token;
+DedicatedWorker::CreateGlobalScopeCreationParams(
+ const KURL& script_url,
+ network::mojom::ReferrerPolicy referrer_policy) {
+ base::UnguessableToken parent_devtools_token;
std::unique_ptr<WorkerSettings> settings;
if (auto* document = DynamicTo<Document>(GetExecutionContext())) {
- devtools_worker_token = document->GetFrame()
- ? document->GetFrame()->GetDevToolsFrameToken()
- : base::UnguessableToken::Create();
+ if (document->GetFrame())
+ parent_devtools_token = document->GetFrame()->GetDevToolsFrameToken();
settings = std::make_unique<WorkerSettings>(document->GetSettings());
} else {
WorkerGlobalScope* worker_global_scope =
- ToWorkerGlobalScope(GetExecutionContext());
- devtools_worker_token = worker_global_scope->GetParentDevToolsToken();
+ To<WorkerGlobalScope>(GetExecutionContext());
+ parent_devtools_token =
+ worker_global_scope->GetThread()->GetDevToolsWorkerToken();
settings = WorkerSettings::Copy(worker_global_scope->GetWorkerSettings());
}
- ScriptType script_type = (options_.type() == "classic") ? ScriptType::kClassic
- : ScriptType::kModule;
+ mojom::ScriptType script_type = (options_->type() == "classic")
+ ? mojom::ScriptType::kClassic
+ : mojom::ScriptType::kModule;
+
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context;
+ if (auto* document = DynamicTo<Document>(GetExecutionContext())) {
+ LocalFrame* frame = document->GetFrame();
+ web_worker_fetch_context = frame->Client()->CreateWorkerFetchContext();
+ web_worker_fetch_context->SetApplicationCacheHostID(
+ GetExecutionContext()->Fetcher()->Context().ApplicationCacheHostID());
+ web_worker_fetch_context->SetIsOnSubframe(!frame->IsMainFrame());
+ } else if (auto* scope =
+ DynamicTo<WorkerGlobalScope>(GetExecutionContext())) {
+ web_worker_fetch_context =
+ static_cast<WorkerFetchContext&>(scope->Fetcher()->Context())
+ .GetWebWorkerFetchContext()
+ ->CloneForNestedWorker();
+ }
+
return std::make_unique<GlobalScopeCreationParams>(
script_url, script_type, GetExecutionContext()->UserAgent(),
+ std::move(web_worker_fetch_context),
GetExecutionContext()->GetContentSecurityPolicy()->Headers(),
- kReferrerPolicyDefault, GetExecutionContext()->GetSecurityOrigin(),
+ referrer_policy, GetExecutionContext()->GetSecurityOrigin(),
GetExecutionContext()->IsSecureContext(),
GetExecutionContext()->GetHttpsState(), CreateWorkerClients(),
GetExecutionContext()->GetSecurityContext().AddressSpace(),
OriginTrialContext::GetTokens(GetExecutionContext()).get(),
- devtools_worker_token, std::move(settings), kV8CacheOptionsDefault,
+ parent_devtools_token, std::move(settings), kV8CacheOptionsDefault,
nullptr /* worklet_module_responses_map */,
ConnectToWorkerInterfaceProvider(GetExecutionContext(),
SecurityOrigin::Create(script_url)),
@@ -346,11 +362,13 @@ DedicatedWorker::CreateGlobalScopeCreationParams(const KURL& script_url) {
}
const AtomicString& DedicatedWorker::InterfaceName() const {
- return EventTargetNames::Worker;
+ return event_target_names::kWorker;
}
void DedicatedWorker::Trace(blink::Visitor* visitor) {
visitor->Trace(context_proxy_);
+ visitor->Trace(options_);
+ visitor->Trace(classic_script_loader_);
AbstractWorker::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
index 042df39af3d..294f9bf904b 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
@@ -50,9 +50,12 @@ class CORE_EXPORT DedicatedWorker final
public:
static DedicatedWorker* Create(ExecutionContext*,
const String& url,
- const WorkerOptions&,
+ const WorkerOptions*,
ExceptionState&);
+ DedicatedWorker(ExecutionContext*,
+ const KURL& script_request_url,
+ const WorkerOptions*);
~DedicatedWorker() override;
void postMessage(ScriptState*,
@@ -61,7 +64,7 @@ class CORE_EXPORT DedicatedWorker final
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
void terminate();
BeginFrameProviderParams CreateBeginFrameProviderParams();
@@ -76,20 +79,17 @@ class CORE_EXPORT DedicatedWorker final
// Returns the name specified by WorkerOptions.
const String Name() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
void Trace(blink::Visitor*) override;
private:
- DedicatedWorker(ExecutionContext*,
- const KURL& script_request_url,
- const WorkerOptions&);
-
// Starts the worker.
void Start();
std::unique_ptr<GlobalScopeCreationParams> CreateGlobalScopeCreationParams(
- const KURL& script_url);
+ const KURL& script_url,
+ network::mojom::ReferrerPolicy);
WorkerClients* CreateWorkerClients();
@@ -101,10 +101,10 @@ class CORE_EXPORT DedicatedWorker final
const AtomicString& InterfaceName() const final;
const KURL script_request_url_;
- const WorkerOptions options_;
+ Member<const WorkerOptions> options_;
const Member<DedicatedWorkerMessagingProxy> context_proxy_;
- scoped_refptr<WorkerClassicScriptLoader> classic_script_loader_;
+ Member<WorkerClassicScriptLoader> classic_script_loader_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc
index 99558a9791d..08de75ba6b2 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc
@@ -62,7 +62,11 @@ DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(
DedicatedWorkerGlobalScope::~DedicatedWorkerGlobalScope() = default;
const AtomicString& DedicatedWorkerGlobalScope::InterfaceName() const {
- return EventTargetNames::DedicatedWorkerGlobalScope;
+ return event_target_names::kDedicatedWorkerGlobalScope;
+}
+
+bool DedicatedWorkerGlobalScope::IsNestedWorker() const {
+ return static_cast<DedicatedWorkerThread*>(GetThread())->IsNestedWorker();
}
// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
@@ -82,7 +86,7 @@ void DedicatedWorkerGlobalScope::ImportModuleScript(
FetchModuleScript(module_url_record, outside_settings_object, destination,
credentials_mode,
ModuleScriptCustomFetchType::kWorkerConstructor,
- new WorkerModuleTreeClient(modulator));
+ MakeGarbageCollected<WorkerModuleTreeClient>(modulator));
}
const String DedicatedWorkerGlobalScope::name() const {
@@ -93,15 +97,15 @@ void DedicatedWorkerGlobalScope::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void DedicatedWorkerGlobalScope::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
Transferables transferables;
scoped_refptr<SerializedScriptValue> serialized_message =
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h
index 02be7b949de..c73d796d278 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h
@@ -36,6 +36,7 @@
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -61,6 +62,7 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
const AtomicString& InterfaceName() const override;
// WorkerGlobalScope
+ bool IsNestedWorker() const override;
void ImportModuleScript(
const KURL& module_url_record,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -74,11 +76,11 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(messageerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(messageerror, kMessageerror);
void Trace(blink::Visitor*) override;
@@ -88,11 +90,12 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
const String name_;
};
-DEFINE_TYPE_CASTS(DedicatedWorkerGlobalScope,
- ExecutionContext,
- context,
- context->IsDedicatedWorkerGlobalScope(),
- context.IsDedicatedWorkerGlobalScope());
+template <>
+struct DowncastTraits<DedicatedWorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsDedicatedWorkerGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl
index 3e8c7eb18de..f6ce7838b35 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl
@@ -36,8 +36,8 @@
] interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
[Replaceable] readonly attribute DOMString name;
- [CallWith=ScriptState, RaisesException] void postMessage(any message, optional sequence<object> transfer = []);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, optional PostMessageOptions options);
void close();
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
index 532011572fc..f849cbac796 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
@@ -7,6 +7,7 @@
#include <memory>
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/events/error_event.h"
@@ -18,10 +19,9 @@
#include "third_party/blink/renderer/core/workers/dedicated_worker.h"
#include "third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.h"
#include "third_party/blink/renderer/core/workers/dedicated_worker_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_options.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
@@ -39,7 +39,7 @@ DedicatedWorkerMessagingProxy::~DedicatedWorkerMessagingProxy() = default;
void DedicatedWorkerMessagingProxy::StartWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
- const WorkerOptions& options,
+ const WorkerOptions* options,
const KURL& script_url,
FetchClientSettingsObjectSnapshot* outside_settings_object,
const v8_inspector::V8StackTraceId& stack_id,
@@ -55,15 +55,26 @@ void DedicatedWorkerMessagingProxy::StartWorkerGlobalScope(
std::move(creation_params),
CreateBackingThreadStartupData(ToIsolate(GetExecutionContext())));
- if (options.type() == "classic") {
- // Dedicated worker is origin-bound, so use kSharableCrossOrigin.
- GetWorkerThread()->EvaluateClassicScript(
- script_url, kSharableCrossOrigin, source_code,
- nullptr /* cached_meta_data */, stack_id);
- } else if (options.type() == "module") {
+ // Step 13: "Obtain script by switching on the value of options's type
+ // member:"
+ if (options->type() == "classic") {
+ // "classic: Fetch a classic worker script given url, outside settings,
+ // destination, and inside settings."
+ if (RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled()) {
+ GetWorkerThread()->ImportClassicScript(script_url,
+ outside_settings_object, stack_id);
+ } else {
+ // Legacy code path (to be deprecated, see https://crbug.com/835717):
+ GetWorkerThread()->EvaluateClassicScript(
+ script_url, source_code, nullptr /* cached_meta_data */, stack_id);
+ }
+ } else if (options->type() == "module") {
+ // "module: Fetch a module worker script graph given url, outside settings,
+ // destination, the value of the credentials member of options, and inside
+ // settings."
network::mojom::FetchCredentialsMode credentials_mode;
- bool result =
- Request::ParseCredentialsMode(options.credentials(), &credentials_mode);
+ bool result = Request::ParseCredentialsMode(options->credentials(),
+ &credentials_mode);
DCHECK(result);
GetWorkerThread()->ImportModuleScript(script_url, outside_settings_object,
credentials_mode);
@@ -174,6 +185,10 @@ void DedicatedWorkerMessagingProxy::DispatchErrorEvent(
CrossThreadBind(&DedicatedWorkerObjectProxy::ProcessUnhandledException,
CrossThreadUnretained(worker_object_proxy_.get()),
exception_id, CrossThreadUnretained(GetWorkerThread())));
+
+ // Propagate an unhandled error to the parent context.
+ const auto mute_script_errors = SanitizeScriptErrors::kDoNotSanitize;
+ GetExecutionContext()->DispatchErrorEvent(event, mute_script_errors);
}
void DedicatedWorkerMessagingProxy::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h
index 70416fe869a..4c1627943bc 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h
@@ -9,6 +9,7 @@
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/optional.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
@@ -16,7 +17,6 @@
#include "third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
namespace blink {
@@ -37,7 +37,7 @@ class CORE_EXPORT DedicatedWorkerMessagingProxy
// These methods should only be used on the parent context thread.
void StartWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams>,
- const WorkerOptions&,
+ const WorkerOptions*,
const KURL& script_url,
FetchClientSettingsObjectSnapshot* outside_settings_object,
const v8_inspector::V8StackTraceId&,
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc
index 88aa262cfa1..84d3d4a0b12 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc
@@ -48,7 +48,7 @@
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -76,7 +76,7 @@ void DedicatedWorkerObjectProxy::PostMessageToWorkerObject(
void DedicatedWorkerObjectProxy::ProcessMessageFromWorkerObject(
BlinkTransferableMessage message,
WorkerThread* worker_thread) {
- ToWorkerGlobalScope(worker_thread->GlobalScope())
+ To<WorkerGlobalScope>(worker_thread->GlobalScope())
->ReceiveMessagePausable(std::move(message));
}
@@ -84,7 +84,7 @@ void DedicatedWorkerObjectProxy::ProcessUnhandledException(
int exception_id,
WorkerThread* worker_thread) {
WorkerGlobalScope* global_scope =
- ToWorkerGlobalScope(worker_thread->GlobalScope());
+ To<WorkerGlobalScope>(worker_thread->GlobalScope());
global_scope->ExceptionUnhandled(exception_id);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
index a833d26cbcc..ab02737ead1 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
@@ -7,6 +7,7 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/events/message_event.h"
#include "third_party/blink/renderer/core/inspector/console_message_storage.h"
@@ -22,7 +23,6 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/core/workers/worker_thread_test_helper.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
@@ -30,9 +30,10 @@ namespace blink {
class DedicatedWorkerThreadForTest final : public DedicatedWorkerThread {
public:
- DedicatedWorkerThreadForTest(DedicatedWorkerObjectProxy& worker_object_proxy)
+ DedicatedWorkerThreadForTest(ExecutionContext* parent_execution_context,
+ DedicatedWorkerObjectProxy& worker_object_proxy)
: DedicatedWorkerThread("fake worker name",
- nullptr /* parent_execution_context*/,
+ parent_execution_context,
worker_object_proxy) {
worker_backing_thread_ = WorkerBackingThread::Create(
ThreadCreationParams(WebThreadType::kTestThread));
@@ -40,7 +41,7 @@ class DedicatedWorkerThreadForTest final : public DedicatedWorkerThread {
WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) override {
- auto* global_scope = new DedicatedWorkerGlobalScope(
+ auto* global_scope = MakeGarbageCollected<DedicatedWorkerGlobalScope>(
"fake worker name", std::move(creation_params), this, time_origin_);
// Initializing a global scope with a dummy creation params may emit warning
// messages (e.g., invalid CSP directives). Clear them here for tests that
@@ -133,8 +134,9 @@ class DedicatedWorkerMessagingProxyForTest
To<Document>(GetExecutionContext())->GetSettings());
InitializeWorkerThread(
std::make_unique<GlobalScopeCreationParams>(
- script_url, ScriptType::kClassic, "fake user agent", headers,
- kReferrerPolicyDefault, security_origin_.get(),
+ script_url, mojom::ScriptType::kClassic, "fake user agent",
+ nullptr /* web_worker_fetch_context */, headers,
+ network::mojom::ReferrerPolicy::kDefault, security_origin_.get(),
false /* starter_secure_context */,
CalculateHttpsState(security_origin_.get()),
nullptr /* worker_clients */, mojom::IPAddressSpace::kLocal,
@@ -144,9 +146,9 @@ class DedicatedWorkerMessagingProxyForTest
WorkerBackingThreadStartupData(
WorkerBackingThreadStartupData::HeapLimitMode::kDefault,
WorkerBackingThreadStartupData::AtomicsWaitMode::kAllow));
- GetWorkerThread()->EvaluateClassicScript(
- script_url, kOpaqueResource, source, nullptr /* cached_meta_data */,
- v8_inspector::V8StackTraceId());
+ GetWorkerThread()->EvaluateClassicScript(script_url, source,
+ nullptr /* cached_meta_data */,
+ v8_inspector::V8StackTraceId());
}
DedicatedWorkerThreadForTest* GetDedicatedWorkerThread() {
@@ -159,7 +161,8 @@ class DedicatedWorkerMessagingProxyForTest
private:
std::unique_ptr<WorkerThread> CreateWorkerThread() override {
- return std::make_unique<DedicatedWorkerThreadForTest>(WorkerObjectProxy());
+ return std::make_unique<DedicatedWorkerThreadForTest>(GetExecutionContext(),
+ WorkerObjectProxy());
}
scoped_refptr<const SecurityOrigin> security_origin_;
@@ -172,7 +175,8 @@ class DedicatedWorkerTest : public PageTestBase {
void SetUp() override {
PageTestBase::SetUp(IntSize());
worker_messaging_proxy_ =
- new DedicatedWorkerMessagingProxyForTest(&GetDocument());
+ MakeGarbageCollected<DedicatedWorkerMessagingProxyForTest>(
+ &GetDocument());
}
void TearDown() override {
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc
index 4bd6088f898..273c6da15f0 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc
@@ -59,7 +59,8 @@ DedicatedWorkerThread::DedicatedWorkerThread(
DedicatedWorkerObjectProxy& worker_object_proxy)
: WorkerThread(worker_object_proxy),
name_(name.IsolatedCopy()),
- worker_object_proxy_(worker_object_proxy) {
+ worker_object_proxy_(worker_object_proxy),
+ is_nested_worker_(parent_execution_context->IsWorkerGlobalScope()) {
FrameOrWorkerScheduler* scheduler =
parent_execution_context ? parent_execution_context->GetScheduler()
: nullptr;
@@ -76,8 +77,8 @@ void DedicatedWorkerThread::ClearWorkerBackingThread() {
WorkerOrWorkletGlobalScope* DedicatedWorkerThread::CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- return new DedicatedWorkerGlobalScope(name_, std::move(creation_params), this,
- time_origin_);
+ return MakeGarbageCollected<DedicatedWorkerGlobalScope>(
+ name_, std::move(creation_params), this, time_origin_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h
index 01466db33d7..b506d3f6802 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h
@@ -54,6 +54,8 @@ class CORE_EXPORT DedicatedWorkerThread : public WorkerThread {
return worker_object_proxy_;
}
+ bool IsNestedWorker() const { return is_nested_worker_; }
+
private:
friend class DedicatedWorkerThreadForTest;
@@ -70,6 +72,7 @@ class CORE_EXPORT DedicatedWorkerThread : public WorkerThread {
std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
const String name_;
DedicatedWorkerObjectProxy& worker_object_proxy_;
+ const bool is_nested_worker_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc b/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc
deleted file mode 100644
index af294e7f63b..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/workers/execution_context_worker_registry.h"
-
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-
-namespace blink {
-
-const char ExecutionContextWorkerRegistry::kSupplementName[] =
- "ExecutionContextWorkerRegistry";
-
-ExecutionContextWorkerRegistry::ExecutionContextWorkerRegistry(
- ExecutionContext& context)
- : Supplement<ExecutionContext>(context) {}
-
-ExecutionContextWorkerRegistry::~ExecutionContextWorkerRegistry() {
-}
-
-ExecutionContextWorkerRegistry* ExecutionContextWorkerRegistry::From(
- ExecutionContext& context) {
- DCHECK(context.IsContextThread());
- ExecutionContextWorkerRegistry* worker_registry =
- Supplement<ExecutionContext>::From<ExecutionContextWorkerRegistry>(
- context);
- if (!worker_registry) {
- worker_registry = new ExecutionContextWorkerRegistry(context);
- Supplement<ExecutionContext>::ProvideTo(context, worker_registry);
- }
- return worker_registry;
-}
-
-void ExecutionContextWorkerRegistry::AddWorkerInspectorProxy(
- WorkerInspectorProxy* proxy) {
- proxies_.insert(proxy);
-}
-
-void ExecutionContextWorkerRegistry::RemoveWorkerInspectorProxy(
- WorkerInspectorProxy* proxy) {
- proxies_.erase(proxy);
-}
-
-const HeapHashSet<Member<WorkerInspectorProxy>>&
-ExecutionContextWorkerRegistry::GetWorkerInspectorProxies() {
- return proxies_;
-}
-
-void ExecutionContextWorkerRegistry::Trace(Visitor* visitor) {
- visitor->Trace(proxies_);
- Supplement<ExecutionContext>::Trace(visitor);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h b/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h
deleted file mode 100644
index 391d9b786ac..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXECUTION_CONTEXT_WORKER_REGISTRY_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXECUTION_CONTEXT_WORKER_REGISTRY_H_
-
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-#include "third_party/blink/renderer/platform/supplementable.h"
-#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-
-namespace blink {
-
-// Tracks the WorkerInspectorProxy objects created by a given ExecutionContext.
-class ExecutionContextWorkerRegistry final
- : public GarbageCollectedFinalized<ExecutionContextWorkerRegistry>,
- public Supplement<ExecutionContext> {
- USING_GARBAGE_COLLECTED_MIXIN(ExecutionContextWorkerRegistry);
-
- public:
- static const char kSupplementName[];
-
- static ExecutionContextWorkerRegistry* From(ExecutionContext& context);
-
- ~ExecutionContextWorkerRegistry();
-
- void AddWorkerInspectorProxy(WorkerInspectorProxy* proxy);
- void RemoveWorkerInspectorProxy(WorkerInspectorProxy* proxy);
- const HeapHashSet<Member<WorkerInspectorProxy>>& GetWorkerInspectorProxies();
-
- void Trace(Visitor* visitor) override;
-
- private:
- explicit ExecutionContextWorkerRegistry(ExecutionContext& context);
-
- HeapHashSet<Member<WorkerInspectorProxy>> proxies_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXECUTION_CONTEXT_WORKER_REGISTRY_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/README.md b/chromium/third_party/blink/renderer/core/workers/experimental/README.md
index b6855f9f0e5..fbc340eb14b 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/README.md
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/README.md
@@ -1,9 +1,17 @@
This directory contains experimental APIs for farming tasks out to a pool of worker threads. Everything in this directory is still highly in flux, and is not anywhere near ready to ship.
thread_pool.{h,cc} contain a class that manages a pool of worker threads and can distribute work to them.
+thread_pool_thread.{h,cc} is a subclass of WorkerThread that these distirubted tasks run on.
worker_task_queue.{h,cc,idl} exposes two APIs:
* postFunction - a simple API for posting a task to a worker.
* postTask - an API for posting tasks that can specify other tasks as prerequisites and coordinates the transfer of return values of prerequisite tasks to dependent tasks
+task_worklet.{h,cc,idl}, task_worklet_global_scope.{h,cc,idl}, and window_task_worklet.{h,idl} exposes a similar API to
+WorkerTaskQueue, built on top of the Worklet API. In addition to implementing postTask() just like WorkerTaskQueue, it
+includes addModule() (inherited from Worklet) and a second variant of postTask(). Modules loaded via addModule() can call
+registerTask() to specify a name and class with a process() function, and this second variant of postTask() takes a task name
+instead of a function. If a task is registered with that given task name, its process() function will be called with the given
+parameters.
+
task.{h,cc,idl} exposes the simple wrapper object returned by postTask and provides the backend that runs tasks on the worker thread (for both postFunction and postTask) and tracks the relationships between tasks (for postTask).
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.cc b/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
index bed0ed56c7c..45d838463b1 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
@@ -4,61 +4,92 @@
#include "third_party/blink/renderer/core/workers/experimental/task.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_function.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_task.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/experimental/thread_pool.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
namespace blink {
-ThreadPoolTask::ThreadPoolTask(ThreadPool* thread_pool,
- v8::Isolate* isolate,
- const ScriptValue& function,
- const Vector<ScriptValue>& arguments,
- TaskType task_type)
+// worker_thread_ only.
+class TaskBase::AsyncFunctionCompleted : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
+ TaskBase* task,
+ State state) {
+ return (new AsyncFunctionCompleted(script_state, task, state))
+ ->BindToV8Function();
+ }
+
+ ScriptValue Call(ScriptValue v) override {
+ task_->TaskCompletedOnWorkerThread(v.V8Value(), state_);
+ return ScriptValue();
+ }
+
+ private:
+ AsyncFunctionCompleted(ScriptState* script_state, TaskBase* task, State state)
+ : ScriptFunction(script_state), task_(task), state_(state) {}
+ CrossThreadPersistent<TaskBase> task_;
+ const State state_;
+};
+
+TaskBase::TaskBase(TaskType task_type,
+ ScriptState* script_state,
+ const ScriptValue& function,
+ const String& function_name)
: task_type_(task_type),
- self_keep_alive_(base::AdoptRef(this)),
- arguments_(arguments.size()),
- weak_factory_(this) {
+ self_keep_alive_(this),
+ function_name_(function_name.IsolatedCopy()) {
DCHECK(IsMainThread());
DCHECK(task_type_ == TaskType::kUserInteraction ||
task_type_ == TaskType::kIdleTask);
-
// TODO(japhet): Handle serialization failures
- function_ = SerializedScriptValue::SerializeAndSwallowExceptions(
- isolate, function.V8Value()->ToString(isolate));
+ v8::Isolate* isolate = script_state->GetIsolate();
+ if (!function.IsEmpty()) {
+ function_ = SerializedScriptValue::SerializeAndSwallowExceptions(
+ isolate, function.V8Value()->ToString(isolate));
+ }
+}
- Vector<ThreadPoolTask*> prerequisites;
+void TaskBase::InitializeArgumentsOnMainThread(
+ ThreadPoolThreadProvider* thread_provider,
+ ScriptState* script_state,
+ const Vector<ScriptValue>& arguments) {
+ v8::Isolate* isolate = script_state->GetIsolate();
+ arguments_.resize(arguments.size());
+ HeapVector<Member<TaskBase>> prerequisites;
Vector<size_t> prerequisites_indices;
for (size_t i = 0; i < arguments_.size(); i++) {
// Normal case: if the argument isn't a Task, just serialize it.
- if (!V8Task::hasInstance(arguments[i].V8Value(), isolate)) {
+ if (!V8Task::HasInstance(arguments[i].V8Value(), isolate)) {
arguments_[i].serialized_value =
SerializedScriptValue::SerializeAndSwallowExceptions(
isolate, arguments[i].V8Value());
continue;
}
- ThreadPoolTask* prerequisite =
+ TaskBase* prerequisite =
ToScriptWrappable(arguments[i].V8Value().As<v8::Object>())
- ->ToImpl<Task>()
- ->GetThreadPoolTask();
+ ->ToImpl<Task>();
prerequisites.push_back(prerequisite);
prerequisites_indices.push_back(i);
}
- worker_thread_ = SelectThread(prerequisites, thread_pool);
+ worker_thread_ = SelectThread(prerequisites, thread_provider);
worker_thread_->IncrementTasksInProgressCount();
if (prerequisites.IsEmpty()) {
+ MutexLocker lock(mutex_);
MaybeStartTask();
return;
}
- // Prior to this point, other ThreadPoolTask instances don't have a reference
+ // Prior to this point, other Task instances don't have a reference
// to |this| yet, so no need to lock mutex_. RegisterDependencies() populates
// those references, so RegisterDependencies() and any logic thereafter must
// consider the potential for data races.
@@ -66,41 +97,32 @@ ThreadPoolTask::ThreadPoolTask(ThreadPool* thread_pool,
}
// static
-ThreadPoolThread* ThreadPoolTask::SelectThread(
- const Vector<ThreadPoolTask*>& prerequisites,
- ThreadPool* thread_pool) {
+ThreadPoolThread* TaskBase::SelectThread(
+ const HeapVector<Member<TaskBase>>& prerequisites,
+ ThreadPoolThreadProvider* thread_provider) {
DCHECK(IsMainThread());
- HashCountedSet<WorkerThread*> prerequisite_location_counts;
+ HashCountedSet<ThreadPoolThread*> prerequisite_location_counts;
size_t max_prerequisite_location_count = 0;
ThreadPoolThread* max_prerequisite_thread = nullptr;
- for (ThreadPoolTask* prerequisite : prerequisites) {
- // For prerequisites that are not yet complete, track which thread the task
- // will run on. Put this task on the thread where the most prerequisites
- // reside. This is slightly imprecise, because a task may complete before
- // registering dependent tasks below.
- if (ThreadPoolThread* thread = prerequisite->GetScheduledThread()) {
- prerequisite_location_counts.insert(thread);
- unsigned thread_count = prerequisite_location_counts.count(thread);
- if (thread_count > max_prerequisite_location_count) {
- max_prerequisite_location_count = thread_count;
- max_prerequisite_thread = thread;
- }
+ for (TaskBase* prerequisite : prerequisites) {
+ // Track which thread the prerequisites will run on. Put this task on the
+ // thread where the most prerequisites reside.
+ ThreadPoolThread* thread = prerequisite->worker_thread_;
+ prerequisite_location_counts.insert(thread);
+ unsigned thread_count = prerequisite_location_counts.count(thread);
+ if (thread_count > max_prerequisite_location_count) {
+ max_prerequisite_location_count = thread_count;
+ max_prerequisite_thread = thread;
}
}
return max_prerequisite_thread ? max_prerequisite_thread
- : thread_pool->GetLeastBusyThread();
-}
-
-ThreadPoolThread* ThreadPoolTask::GetScheduledThread() {
- DCHECK(IsMainThread());
- MutexLocker lock(mutex_);
- return HasFinished() ? nullptr : worker_thread_;
+ : thread_provider->GetLeastBusyThread();
}
// Should only be called from constructor. Split out in to a helper because
// clang appears to exempt constructors from thread safety analysis.
-void ThreadPoolTask::RegisterDependencies(
- const Vector<ThreadPoolTask*>& prerequisites,
+void TaskBase::RegisterDependencies(
+ const HeapVector<Member<TaskBase>>& prerequisites,
const Vector<size_t>& prerequisites_indices) {
DCHECK(IsMainThread());
{
@@ -109,35 +131,28 @@ void ThreadPoolTask::RegisterDependencies(
}
for (size_t i = 0; i < prerequisites.size(); i++) {
- ThreadPoolTask* prerequisite = prerequisites[i];
+ TaskBase* prerequisite = prerequisites[i];
size_t prerequisite_index = prerequisites_indices[i];
- scoped_refptr<SerializedScriptValue> result;
- State prerequisite_state = State::kPending;
{
MutexLocker lock(prerequisite->mutex_);
- prerequisite_state = prerequisite->state_;
- if (prerequisite->HasFinished()) {
- result = prerequisite->serialized_result_;
- } else {
- prerequisite->dependents_.insert(
- std::make_unique<Dependent>(this, prerequisite_index));
+ if (!prerequisite->HasFinished()) {
+ prerequisite->dependents_.emplace_back(
+ MakeGarbageCollected<Dependent>(this, prerequisite_index));
+ continue;
}
}
- // TODO(japhet): if a prerequisite failed, this task will be cancelled.
- // Should that throw an exception?
- if (prerequisite_state == State::kCompleted ||
- prerequisite_state == State::kFailed) {
- PrerequisiteFinished(prerequisite_index, v8::Local<v8::Value>(), result,
- prerequisite_state);
- }
+ PostCrossThreadTask(
+ *prerequisite->worker_thread_->GetTaskRunner(task_type_), FROM_HERE,
+ CrossThreadBind(&TaskBase::PassResultToDependentOnWorkerThread,
+ WrapCrossThreadPersistent(prerequisite),
+ prerequisite_index, WrapCrossThreadPersistent(this)));
}
}
-ThreadPoolTask::~ThreadPoolTask() {
+TaskBase::~TaskBase() {
DCHECK(IsMainThread());
- DCHECK(!resolver_);
DCHECK(HasFinished());
DCHECK(!function_);
DCHECK(arguments_.IsEmpty());
@@ -145,44 +160,71 @@ ThreadPoolTask::~ThreadPoolTask() {
DCHECK(dependents_.IsEmpty());
}
-void ThreadPoolTask::PrerequisiteFinished(
- size_t prerequisite_index,
- v8::Local<v8::Value> v8_result,
- scoped_refptr<SerializedScriptValue> result,
- State prerequisite_state) {
+scoped_refptr<SerializedScriptValue> TaskBase::GetSerializedResult() {
+ DCHECK(IsMainThread() || worker_thread_->IsCurrentThread());
+ MutexLocker lock(mutex_);
+ DCHECK(HasFinished());
+ if (!serialized_result_ && worker_thread_->IsCurrentThread()) {
+ DCHECK(v8_result_);
+ ScriptState::Scope scope(
+ worker_thread_->GlobalScope()->ScriptController()->GetScriptState());
+ v8::Isolate* isolate = ToIsolate(worker_thread_->GlobalScope());
+ serialized_result_ = SerializedScriptValue::SerializeAndSwallowExceptions(
+ isolate, v8_result_->GetResult(isolate));
+ }
+ return serialized_result_;
+}
+
+void TaskBase::PassResultToDependentOnWorkerThread(size_t dependent_index,
+ TaskBase* dependent) {
+ DCHECK(worker_thread_->IsCurrentThread());
+ bool failed = false;
+ {
+ MutexLocker lock(mutex_);
+ DCHECK(HasFinished());
+ failed = state_ == State::kFailed;
+ }
+
+ // Only serialize if the dependent needs the result on a different thread.
+ // Otherwise, use the unserialized result from v8.
+ scoped_refptr<SerializedScriptValue> serialized_result =
+ dependent->IsTargetThreadForArguments() ? nullptr : GetSerializedResult();
+ V8ResultHolder* v8_result =
+ dependent->IsTargetThreadForArguments() ? v8_result_.Get() : nullptr;
+ dependent->PrerequisiteFinished(dependent_index, v8_result, serialized_result,
+ failed);
+}
+
+void TaskBase::PrerequisiteFinished(
+ size_t index,
+ V8ResultHolder* v8_result,
+ scoped_refptr<SerializedScriptValue> serialized_result,
+ bool failed) {
+ DCHECK(v8_result || serialized_result);
+ DCHECK(!v8_result || !serialized_result);
+
MutexLocker lock(mutex_);
DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
- DCHECK(prerequisite_state == State::kCompleted ||
- prerequisite_state == State::kFailed);
DCHECK_GT(prerequisites_remaining_, 0u);
prerequisites_remaining_--;
- // If the result of the prerequisite doesn't need to move between threads,
- // save the deserialized v8::Value for later use.
- if (prerequisite_state == State::kFailed) {
+ if (failed)
AdvanceState(State::kCancelPending);
- } else if (worker_thread_->IsCurrentThread() && !v8_result.IsEmpty()) {
- arguments_[prerequisite_index].v8_value =
- std::make_unique<ScopedPersistent<v8::Value>>(
- ToIsolate(worker_thread_->GlobalScope()), v8_result);
- } else {
- arguments_[prerequisite_index].serialized_value = result;
- }
+ arguments_[index].v8_value = v8_result;
+ arguments_[index].serialized_value = serialized_result;
MaybeStartTask();
}
-void ThreadPoolTask::MaybeStartTask() {
+void TaskBase::MaybeStartTask() {
if (prerequisites_remaining_)
return;
DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
PostCrossThreadTask(*worker_thread_->GetTaskRunner(task_type_), FROM_HERE,
- CrossThreadBind(&ThreadPoolTask::StartTaskOnWorkerThread,
- CrossThreadUnretained(this)));
+ CrossThreadBind(&TaskBase::StartTaskOnWorkerThread,
+ WrapCrossThreadPersistent(this)));
}
-void ThreadPoolTask::StartTaskOnWorkerThread() {
+bool TaskBase::WillStartTaskOnWorkerThread() {
DCHECK(worker_thread_->IsCurrentThread());
-
- bool was_cancelled = false;
{
MutexLocker lock(mutex_);
DCHECK(!prerequisites_remaining_);
@@ -191,8 +233,7 @@ void ThreadPoolTask::StartTaskOnWorkerThread() {
AdvanceState(State::kStarted);
break;
case State::kCancelPending:
- was_cancelled = true;
- break;
+ return false;
case State::kStarted:
case State::kCompleted:
case State::kFailed:
@@ -200,66 +241,71 @@ void ThreadPoolTask::StartTaskOnWorkerThread() {
break;
}
}
+ return true;
+}
- WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
- v8::Isolate* isolate = ToIsolate(global_scope);
- ScriptState::Scope scope(global_scope->ScriptController()->GetScriptState());
-
- v8::TryCatch block(isolate);
- v8::Local<v8::Value> return_value;
- if (was_cancelled) {
- return_value = V8String(isolate, "Task aborted");
- } else {
- return_value = RunTaskOnWorkerThread(isolate);
- DCHECK_EQ(return_value.IsEmpty(), block.HasCaught());
- if (block.HasCaught())
- return_value = block.Exception()->ToString(isolate);
- }
-
- scoped_refptr<SerializedScriptValue> local_result =
- SerializedScriptValue::SerializeAndSwallowExceptions(isolate,
- return_value);
- State local_state =
- block.HasCaught() || was_cancelled ? State::kFailed : State::kCompleted;
-
+void TaskBase::TaskCompletedOnWorkerThread(v8::Local<v8::Value> v8_result,
+ State state) {
+ DCHECK(worker_thread_->IsCurrentThread());
+ v8_result_ =
+ new V8ResultHolder(ToIsolate(worker_thread_->GlobalScope()), v8_result);
function_ = nullptr;
arguments_.clear();
- HashSet<std::unique_ptr<Dependent>> dependents_to_notify;
+ Vector<CrossThreadPersistent<Dependent>> dependents_to_notify;
{
MutexLocker lock(mutex_);
- serialized_result_ = local_result;
- AdvanceState(local_state);
+ AdvanceState(state);
dependents_to_notify.swap(dependents_);
}
- for (auto& dependent : dependents_to_notify) {
- dependent->task->PrerequisiteFinished(dependent->index, return_value,
- local_result, local_state);
- }
+ for (auto& dependent : dependents_to_notify)
+ PassResultToDependentOnWorkerThread(dependent->index, dependent->task);
PostCrossThreadTask(
*worker_thread_->GetParentExecutionContextTaskRunners()->Get(
TaskType::kInternalWorker),
FROM_HERE,
- CrossThreadBind(&ThreadPoolTask::TaskCompleted,
- CrossThreadUnretained(this)));
- // TaskCompleted may delete |this| at any time after this point.
+ CrossThreadBind(&TaskBase::TaskCompleted, WrapCrossThreadPersistent(this),
+ state == State::kCompleted));
}
-v8::Local<v8::Value> ThreadPoolTask::RunTaskOnWorkerThread(
- v8::Isolate* isolate) {
+void TaskBase::RunTaskOnWorkerThread() {
DCHECK(worker_thread_->IsCurrentThread());
// No other thread should be touching function_ or arguments_ at this point,
// so no mutex needed while actually running the task.
+ WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
+ ScriptState::Scope scope(global_scope->ScriptController()->GetScriptState());
+ v8::Isolate* isolate = ToIsolate(global_scope);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
- String core_script =
- "(" + ToCoreString(function_->Deserialize(isolate).As<v8::String>()) +
- ")";
- v8::MaybeLocal<v8::Script> script = v8::Script::Compile(
- isolate->GetCurrentContext(), V8String(isolate, core_script));
- v8::Local<v8::Function> script_function =
- script.ToLocalChecked()->Run(context).ToLocalChecked().As<v8::Function>();
+
+ v8::Local<v8::Function> script_function;
+ v8::Local<v8::Value> receiver;
+ if (function_) {
+ String core_script =
+ "(" + ToCoreString(function_->Deserialize(isolate).As<v8::String>()) +
+ ")";
+ v8::MaybeLocal<v8::Script> script =
+ v8::Script::Compile(context, V8String(isolate, core_script));
+ script_function = script.ToLocalChecked()
+ ->Run(context)
+ .ToLocalChecked()
+ .As<v8::Function>();
+ receiver = script_function;
+ } else if (worker_thread_->IsWorklet()) {
+ TaskWorkletGlobalScope* task_worklet_global_scope =
+ static_cast<TaskWorkletGlobalScope*>(global_scope);
+ script_function = task_worklet_global_scope->GetProcessFunctionForName(
+ function_name_, isolate);
+ receiver =
+ task_worklet_global_scope->GetInstanceForName(function_name_, isolate);
+ }
+
+ if (script_function.IsEmpty()) {
+ TaskCompletedOnWorkerThread(V8String(isolate, "Invalid task"),
+ State::kFailed);
+ return;
+ }
Vector<v8::Local<v8::Value>> params(arguments_.size());
for (size_t i = 0; i < arguments_.size(); i++) {
@@ -267,78 +313,55 @@ v8::Local<v8::Value> ThreadPoolTask::RunTaskOnWorkerThread(
if (arguments_[i].serialized_value)
params[i] = arguments_[i].serialized_value->Deserialize(isolate);
else
- params[i] = arguments_[i].v8_value->NewLocal(isolate);
- }
-
- v8::MaybeLocal<v8::Value> ret = script_function->Call(
- context, script_function, params.size(), params.data());
-
- v8::Local<v8::Value> return_value;
- if (!ret.IsEmpty()) {
- return_value = ret.ToLocalChecked();
- if (return_value->IsPromise())
- return_value = return_value.As<v8::Promise>()->Result();
+ params[i] = arguments_[i].v8_value->GetResult(isolate);
}
- return return_value;
-}
-void ThreadPoolTask::TaskCompleted() {
- DCHECK(IsMainThread());
- bool rejected = false;
- {
- MutexLocker lock(mutex_);
- DCHECK(HasFinished());
- rejected = state_ == State::kFailed;
- }
- if (resolver_ && resolver_->GetScriptState()->ContextIsValid()) {
- ScriptState::Scope scope(resolver_->GetScriptState());
- ScriptValue value = GetResult(resolver_->GetScriptState());
- if (rejected)
- resolver_->Reject(v8::Exception::Error(value.V8Value().As<v8::String>()));
- else
- resolver_->Resolve(value);
+ v8::TryCatch block(isolate);
+ v8::MaybeLocal<v8::Value> ret =
+ script_function->Call(context, receiver, params.size(), params.data());
+ if (block.HasCaught()) {
+ TaskCompletedOnWorkerThread(block.Exception()->ToString(isolate),
+ State::kFailed);
+ return;
}
- resolver_ = nullptr;
- worker_thread_->DecrementTasksInProgressCount();
- self_keep_alive_.reset();
- // |this| may be deleted here.
-}
-ScriptValue ThreadPoolTask::GetResult(ScriptState* script_state) {
- DCHECK(IsMainThread());
- MutexLocker lock(mutex_);
- if (!HasFinished()) {
- DCHECK(!serialized_result_);
- DCHECK(deserialized_result_.IsEmpty());
- if (!resolver_)
- resolver_ = ScriptPromiseResolver::Create(script_state);
- return resolver_->Promise().GetScriptValue();
- }
- if (deserialized_result_.IsEmpty()) {
- ScriptState::Scope scope(script_state);
- deserialized_result_ = ScriptValue(
- script_state,
- serialized_result_->Deserialize(script_state->GetIsolate()));
+ DCHECK(!ret.IsEmpty());
+ v8::Local<v8::Value> return_value = ret.ToLocalChecked();
+ if (return_value->IsPromise()) {
+ v8::Local<v8::Promise> promise = return_value.As<v8::Promise>();
+ if (promise->State() == v8::Promise::kPending) {
+ // Wait for the promise to resolve before calling
+ // TaskCompletedOnWorkerThread.
+ ScriptState* script_state = ScriptState::Current(isolate);
+ ScriptPromise(script_state, promise)
+ .Then(AsyncFunctionCompleted::CreateFunction(script_state, this,
+ State::kCompleted),
+ AsyncFunctionCompleted::CreateFunction(script_state, this,
+ State::kFailed));
+ return;
+ }
+ return_value = promise->Result();
}
- return deserialized_result_;
+ TaskCompletedOnWorkerThread(return_value, State::kCompleted);
}
-void ThreadPoolTask::Cancel() {
+void TaskBase::TaskCompleted(bool was_successful) {
DCHECK(IsMainThread());
- MutexLocker lock(mutex_);
- if (state_ == State::kPending)
- AdvanceState(State::kCancelPending);
+ worker_thread_->DecrementTasksInProgressCount();
+ self_keep_alive_.Clear();
}
-void ThreadPoolTask::AdvanceState(State new_state) {
+void TaskBase::AdvanceState(State new_state) {
switch (new_state) {
case State::kPending:
- NOTREACHED() << "kPending should only be set via initialiation";
+ NOTREACHED() << "kPending should only be set via initialization";
break;
- case State::kCancelPending:
case State::kStarted:
DCHECK_EQ(State::kPending, state_);
break;
+ case State::kCancelPending:
+ DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
+ break;
case State::kCompleted:
DCHECK_EQ(State::kStarted, state_);
break;
@@ -349,4 +372,95 @@ void ThreadPoolTask::AdvanceState(State new_state) {
state_ = new_state;
}
+Vector<ScriptValue> GetResolverArgument(ScriptState* script_state, Task* task) {
+ v8::Isolate* isolate = script_state->GetIsolate();
+ return Vector<ScriptValue>({ScriptValue(
+ script_state,
+ ToV8(task, isolate->GetCurrentContext()->Global(), isolate))});
+}
+
+ScriptPromise Task::result(ScriptState* script_state) {
+ DCHECK(IsMainThread());
+ if (!resolve_task_) {
+ resolve_task_ =
+ MakeGarbageCollected<ResolveTask>(script_state, task_type_, this);
+ }
+ return resolve_task_->GetPromise();
+}
+
+void Task::cancel() {
+ DCHECK(IsMainThread());
+ MutexLocker lock(mutex_);
+ if (state_ == State::kPending)
+ AdvanceState(State::kCancelPending);
+}
+
+void Task::StartTaskOnWorkerThread() {
+ DCHECK(worker_thread_->IsCurrentThread());
+ if (!WillStartTaskOnWorkerThread()) {
+ WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
+ v8::Isolate* isolate = ToIsolate(global_scope);
+ ScriptState::Scope scope(
+ global_scope->ScriptController()->GetScriptState());
+ TaskCompletedOnWorkerThread(V8String(isolate, "Task aborted"),
+ State::kFailed);
+ return;
+ }
+
+ RunTaskOnWorkerThread();
+}
+
+void Task::Trace(Visitor* visitor) {
+ ScriptWrappable::Trace(visitor);
+ TaskBase::Trace(visitor);
+ visitor->Trace(resolve_task_);
+}
+
+ResolveTask::ResolveTask(ScriptState* script_state,
+ TaskType task_type,
+ Task* prerequisite)
+ : TaskBase(task_type, script_state, ScriptValue(), String()),
+ resolver_(ScriptPromiseResolver::Create(script_state)) {
+ DCHECK(IsMainThread());
+ // It's safe to pass a nullptr ThreadPoolThreadProivder here because it
+ // is only used to select a thread if there are no prerequisites, but a
+ // ResolveTask always has exactly one prerequisite.
+ InitializeArgumentsOnMainThread(
+ nullptr, script_state, GetResolverArgument(script_state, prerequisite));
+}
+
+void ResolveTask::StartTaskOnWorkerThread() {
+ // Just take the sole argument and use it as the return value that will be
+ // given to the promise resolver.
+ {
+ MutexLocker lock(mutex_);
+ serialized_result_ = arguments_[0].serialized_value;
+ }
+ TaskCompletedOnWorkerThread(
+ v8::Local<v8::Value>(),
+ WillStartTaskOnWorkerThread() ? State::kCompleted : State::kFailed);
+}
+
+void ResolveTask::TaskCompleted(bool was_successful) {
+ DCHECK(IsMainThread());
+
+ ScriptState* script_state = resolver_->GetScriptState();
+ if (!script_state->ContextIsValid())
+ return;
+ ScriptState::Scope scope(script_state);
+
+ v8::Local<v8::Value> value =
+ GetSerializedResult()->Deserialize(script_state->GetIsolate());
+ if (was_successful)
+ resolver_->Resolve(value);
+ else
+ resolver_->Reject(v8::Exception::Error(value.As<v8::String>()));
+ TaskBase::TaskCompleted(was_successful);
+}
+
+void ResolveTask::Trace(Visitor* visitor) {
+ TaskBase::Trace(visitor);
+ visitor->Trace(resolver_);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.h b/chromium/third_party/blink/renderer/core/workers/experimental/task.h
index c3b1c3742ee..5b04979d1c8 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.h
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task.h
@@ -6,98 +6,125 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_H_
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
-#include "third_party/blink/renderer/core/workers/experimental/thread_pool.h"
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
namespace blink {
+class ResolveTask;
class SerializedScriptValue;
-class Task;
// Runs |function| with |arguments| on a thread from the given ThreadPool.
// Scans |arguments| for Task objects, and registers those as dependencies,
// passing the result of those tasks in place of the Task arguments.
// All public functions are main-thread-only.
-// ThreadPoolTask keeps itself alive via a self scoped_refptr until the
+// TaskBase keeps itself alive via a SelfKeepAlive until the
// the task completes and reports itself done on the main thread via
-// TaskCompleted(). Other users (e.g. Task below) can keep the task
-// alive after completion.
-class ThreadPoolTask final : public RefCounted<ThreadPoolTask> {
+// TaskCompleted().
+class TaskBase : public GarbageCollectedMixin {
public:
- // Called on main thread
- ThreadPoolTask(ThreadPool*,
- v8::Isolate*,
- const ScriptValue& function,
- const Vector<ScriptValue>& arguments,
- TaskType);
- ~ThreadPoolTask();
- // Returns the result of this task, or a promise that will be resolved with
- // the result when it completes.
- ScriptValue GetResult(ScriptState*) LOCKS_EXCLUDED(mutex_);
- void Cancel() LOCKS_EXCLUDED(mutex_);
-
- base::WeakPtr<ThreadPoolTask> GetWeakPtr() {
- return weak_factory_.GetWeakPtr();
- }
+ virtual ~TaskBase();
+
+ protected:
+ virtual void StartTaskOnWorkerThread() LOCKS_EXCLUDED(mutex_) = 0;
+ virtual bool IsTargetThreadForArguments() = 0;
- private:
enum class State { kPending, kStarted, kCancelPending, kCompleted, kFailed };
- void StartTaskOnWorkerThread() LOCKS_EXCLUDED(mutex_);
- v8::Local<v8::Value> RunTaskOnWorkerThread(v8::Isolate*);
+ TaskBase(TaskType,
+ ScriptState*,
+ const ScriptValue& function,
+ const String& function_name);
+
+ void InitializeArgumentsOnMainThread(ThreadPoolThreadProvider*,
+ ScriptState*,
+ const Vector<ScriptValue>& arguments);
+
+ class AsyncFunctionCompleted;
+
+ // This caches the result after the task completes on the worker thread.
+ // We can't safely clear the ScopedPersistent from the main thread, so
+ // this wrappper allows us to hold a CrossThreadPersistent that arranges
+ // for GC on the worker thread.
+ class V8ResultHolder final
+ : public GarbageCollectedFinalized<V8ResultHolder> {
+ public:
+ V8ResultHolder(v8::Isolate* isolate, v8::Local<v8::Value> result)
+ : result_(isolate, result) {}
+ ~V8ResultHolder() = default;
+ v8::Local<v8::Value> GetResult(v8::Isolate* isolate) {
+ return result_.NewLocal(isolate);
+ }
+ void Trace(Visitor*) {}
+
+ private:
+ ScopedPersistent<v8::Value> result_;
+ };
+
+ bool WillStartTaskOnWorkerThread();
+ void RunTaskOnWorkerThread();
+ void TaskCompletedOnWorkerThread(v8::Local<v8::Value> v8_result, State)
+ LOCKS_EXCLUDED(mutex_);
+ void PassResultToDependentOnWorkerThread(size_t dependent_index, TaskBase*)
+ LOCKS_EXCLUDED(mutex_);
// Called on ANY thread (main thread, worker_thread_, or a sibling worker).
void MaybeStartTask() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- void PrerequisiteFinished(size_t prerequisite_index,
- v8::Local<v8::Value>,
+ void PrerequisiteFinished(size_t index,
+ V8ResultHolder*,
scoped_refptr<SerializedScriptValue>,
- State) LOCKS_EXCLUDED(mutex_);
+ bool failed) LOCKS_EXCLUDED(mutex_);
bool HasFinished() const EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
return state_ == State::kCompleted || state_ == State::kFailed;
}
void AdvanceState(State new_state) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ // Called on main thread or worker_thread_
+ scoped_refptr<SerializedScriptValue> GetSerializedResult()
+ LOCKS_EXCLUDED(mutex_);
+
// Called on main thread
static ThreadPoolThread* SelectThread(
- const Vector<ThreadPoolTask*>& prerequisites,
- ThreadPool*);
- ThreadPoolThread* GetScheduledThread() LOCKS_EXCLUDED(mutex_);
- void RegisterDependencies(const Vector<ThreadPoolTask*>& prerequisites,
+ const HeapVector<Member<TaskBase>>& prerequisites,
+ ThreadPoolThreadProvider*);
+ void RegisterDependencies(const HeapVector<Member<TaskBase>>& prerequisites,
const Vector<size_t>& prerequisite_indices)
LOCKS_EXCLUDED(mutex_);
- void TaskCompleted();
+ virtual void TaskCompleted(bool was_successful);
// worker_thread_ is selected in the constructor and not changed thereafter.
ThreadPoolThread* worker_thread_ = nullptr;
const TaskType task_type_;
// Main thread only
- scoped_refptr<ThreadPoolTask> self_keep_alive_;
- ScriptValue deserialized_result_;
- Persistent<ScriptPromiseResolver> resolver_;
+ SelfKeepAlive<TaskBase> self_keep_alive_;
// Created in constructor on the main thread, consumed and cleared on
// worker_thread_. Those steps can't overlap, so no mutex_ required.
scoped_refptr<SerializedScriptValue> function_;
+ const String function_name_;
// Created and populated with non-prerequiste parameters on the main thread.
// Each prerequisite writes its return value into arguments_ from its thread.
// If the prequisite and this have the same worker_thread_, there is no need
- // to serialize and deserialize the argument, so v8_argument will be populated
+ // to serialize and deserialize the argument, so v8_value will be populated
// with the v8::Value returned by the prerequisite.
// Consumed and cleared on worker_thread_.
// Only requires mutex_ when writing prerequisite results, at other times
// either the main thread or the worker_thread_ has sole access.
struct Argument {
scoped_refptr<SerializedScriptValue> serialized_value;
- std::unique_ptr<ScopedPersistent<v8::Value>> v8_value;
+ CrossThreadPersistent<V8ResultHolder> v8_value;
};
Vector<Argument> arguments_;
// Read on main thread, write on worker_thread_.
scoped_refptr<SerializedScriptValue> serialized_result_ GUARDED_BY(mutex_);
+ // Read/write on worker_thread_
+ CrossThreadPersistent<V8ResultHolder> v8_result_;
+
// Read/write on both main thread and worker_thread_.
State state_ GUARDED_BY(mutex_) = State::kPending;
@@ -106,40 +133,79 @@ class ThreadPoolTask final : public RefCounted<ThreadPoolTask> {
size_t prerequisites_remaining_ GUARDED_BY(mutex_) = 0u;
// Elements added from main thread. Cleared on completion on worker_thread_.
- // Each element in dependents_ is not yet in the kCompleted state and
- // therefore is guaranteed to be alive.
- struct Dependent {
+ // Each element in dependents_ is not yet in the kCompleted state.
+ struct Dependent final : public GarbageCollected<Dependent> {
public:
- Dependent(ThreadPoolTask* task, size_t index) : task(task), index(index) {}
- ThreadPoolTask* task;
+ Dependent(TaskBase* task, size_t index) : task(task), index(index) {
+ DCHECK(IsMainThread());
+ }
+ void Trace(Visitor* visitor) { visitor->Trace(task); }
+ Member<TaskBase> task;
+ // The index in the dependent's argument array where this result should go.
size_t index;
};
- HashSet<std::unique_ptr<Dependent>> dependents_ GUARDED_BY(mutex_);
+ Vector<CrossThreadPersistent<Dependent>> dependents_ GUARDED_BY(mutex_);
Mutex mutex_;
-
- base::WeakPtrFactory<ThreadPoolTask> weak_factory_;
};
-// This is a thin, v8-exposed wrapper around ThreadPoolTask that allows
-// ThreadPoolTask to avoid being GarbageCollected.
-class Task : public ScriptWrappable {
+// The variant of TaskBase that is exposed to JS.
+class Task final : public ScriptWrappable, public TaskBase {
DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(Task);
public:
- explicit Task(ThreadPoolTask* thread_pool_task)
- : thread_pool_task_(thread_pool_task) {}
- ~Task() override = default;
+ // Called on main thread
+ Task(ThreadPoolThreadProvider* thread_provider,
+ ScriptState* script_state,
+ const ScriptValue& function,
+ const Vector<ScriptValue>& arguments,
+ TaskType task_type)
+ : TaskBase(task_type, script_state, function, String()) {
+ InitializeArgumentsOnMainThread(thread_provider, script_state, arguments);
+ }
+ Task(ThreadPoolThreadProvider* thread_provider,
+ ScriptState* script_state,
+ const String& function_name,
+ const Vector<ScriptValue>& arguments,
+ TaskType task_type)
+ : TaskBase(task_type, script_state, ScriptValue(), function_name) {
+ InitializeArgumentsOnMainThread(thread_provider, script_state, arguments);
+ }
- ScriptValue result(ScriptState* script_state) {
- return thread_pool_task_->GetResult(script_state);
+ // Returns a promise that will be resolved with the result when it completes.
+ ScriptPromise result(ScriptState*);
+ void cancel() LOCKS_EXCLUDED(mutex_);
+
+ void StartTaskOnWorkerThread() override LOCKS_EXCLUDED(mutex_);
+ bool IsTargetThreadForArguments() override {
+ return worker_thread_->IsCurrentThread();
}
- void cancel() { thread_pool_task_->Cancel(); }
+ void Trace(Visitor*) override;
+
+ private:
+ Member<ResolveTask> resolve_task_;
+};
+
+// An internal TaskBase subclass that drives main thread promise resolution.
+// It registers itself as a dependent on the Task whose result is being
+// promised. When that Task completes, it runs a dummy script that just returns
+// the dependent's result as its own. It then eagerly serializes the result, and
+// overrides TaskCompleted() to actually resolve the promise.
+class ResolveTask final : public GarbageCollectedFinalized<ResolveTask>,
+ public TaskBase {
+ USING_GARBAGE_COLLECTED_MIXIN(ResolveTask);
- ThreadPoolTask* GetThreadPoolTask() const { return thread_pool_task_.get(); }
+ public:
+ ResolveTask(ScriptState*, TaskType, Task* prerequisite);
+ void StartTaskOnWorkerThread() override LOCKS_EXCLUDED(mutex_);
+ bool IsTargetThreadForArguments() override { return IsMainThread(); }
+ void TaskCompleted(bool was_successful) override;
+ ScriptPromise GetPromise() { return resolver_->Promise(); }
+ void Trace(Visitor*) override;
private:
- scoped_refptr<ThreadPoolTask> thread_pool_task_;
+ Member<ScriptPromiseResolver> resolver_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
index c0d2230a85c..b3a2bf74622 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
@@ -6,6 +6,6 @@
Exposed=Window,
RuntimeEnabled=WorkerTaskQueue
] interface Task {
- [CallWith=ScriptState] readonly attribute any result;
+ [CallWith=ScriptState] readonly attribute Promise<any> result;
void cancel();
};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc
new file mode 100644
index 00000000000..8cdafe2afa6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc
@@ -0,0 +1,121 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet.h"
+
+#include "third_party/blink/renderer/core/frame/local_dom_window.h"
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h"
+#include "third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h"
+#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+
+class TaskWorkletMessagingProxy final : public ThreadedWorkletMessagingProxy {
+ public:
+ TaskWorkletMessagingProxy(ExecutionContext* context)
+ : ThreadedWorkletMessagingProxy(context) {}
+ ~TaskWorkletMessagingProxy() override = default;
+
+ std::unique_ptr<WorkerThread> CreateWorkerThread() override {
+ return std::make_unique<ThreadPoolThread>(GetExecutionContext(),
+ WorkletObjectProxy(),
+ ThreadPoolThread::kWorklet);
+ }
+
+ ThreadPoolThread* GetWorkerThread() const {
+ return static_cast<ThreadPoolThread*>(
+ ThreadedMessagingProxyBase::GetWorkerThread());
+ }
+};
+
+const char TaskWorklet::kSupplementName[] = "TaskWorklet";
+
+TaskWorklet* TaskWorklet::From(LocalDOMWindow& window) {
+ TaskWorklet* task_worklet =
+ Supplement<LocalDOMWindow>::From<TaskWorklet>(window);
+ if (!task_worklet) {
+ task_worklet = new TaskWorklet(window.document());
+ Supplement<LocalDOMWindow>::ProvideTo(window, task_worklet);
+ }
+ return task_worklet;
+}
+
+static const size_t kMaxTaskWorkletThreads = 4;
+
+TaskWorklet::TaskWorklet(Document* document) : Worklet(document) {}
+
+Task* TaskWorklet::postTask(ScriptState* script_state,
+ const ScriptValue& function,
+ const Vector<ScriptValue>& arguments) {
+ DCHECK(function.IsFunction());
+ // TODO(japhet): Here and below: it's unclear what task type should be used,
+ // and whether the API should allow it to be configured. Using kIdleTask as a
+ // placeholder for now.
+ return new Task(this, script_state, function, arguments, TaskType::kIdleTask);
+}
+
+Task* TaskWorklet::postTask(ScriptState* script_state,
+ const String& function_name,
+ const Vector<ScriptValue>& arguments) {
+ return new Task(this, script_state, function_name, arguments,
+ TaskType::kIdleTask);
+}
+
+ThreadPoolThread* TaskWorklet::GetLeastBusyThread() {
+ DCHECK(IsMainThread());
+ ThreadPoolThread* least_busy_thread = nullptr;
+ size_t lowest_task_count = std::numeric_limits<std::size_t>::max();
+ for (auto& proxy : proxies_) {
+ ThreadPoolThread* current_thread =
+ static_cast<TaskWorkletMessagingProxy*>(proxy.Get())->GetWorkerThread();
+ size_t current_task_count = current_thread->GetTasksInProgressCount();
+ // If there's an idle thread, use it.
+ if (current_task_count == 0)
+ return current_thread;
+ if (current_task_count < lowest_task_count) {
+ least_busy_thread = current_thread;
+ lowest_task_count = current_task_count;
+ }
+ }
+ if (proxies_.size() == kMaxTaskWorkletThreads)
+ return least_busy_thread;
+ auto* proxy = static_cast<TaskWorkletMessagingProxy*>(CreateGlobalScope());
+ proxies_.push_back(proxy);
+ return proxy->GetWorkerThread();
+}
+
+// TODO(japhet): This causes all of the backing threads to be created when
+// addModule() is first called. Sort out lazy global scope creation.
+// Note that if the function variant of postTask() is called first, global
+// scopes will be created lazily; it's only module loading that needs upfront
+// global scope creation, presumably because we don't have a way to replay
+// module loads from WorkletModuleResponsesMap yet.
+bool TaskWorklet::NeedsToCreateGlobalScope() {
+ return GetNumberOfGlobalScopes() < kMaxTaskWorkletThreads;
+}
+
+WorkletGlobalScopeProxy* TaskWorklet::CreateGlobalScope() {
+ DCHECK_LT(GetNumberOfGlobalScopes(), kMaxTaskWorkletThreads);
+ TaskWorkletMessagingProxy* proxy =
+ new TaskWorkletMessagingProxy(GetExecutionContext());
+ proxy->Initialize(WorkerClients::Create(), ModuleResponsesMap(),
+ WorkerBackingThreadStartupData::CreateDefault());
+ return proxy;
+}
+
+// We select a global scope without this getting called.
+wtf_size_t TaskWorklet::SelectGlobalScope() {
+ NOTREACHED();
+ return 0u;
+}
+
+void TaskWorklet::Trace(blink::Visitor* visitor) {
+ Worklet::Trace(visitor);
+ Supplement<LocalDOMWindow>::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h
new file mode 100644
index 00000000000..49c367ab2e9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h
@@ -0,0 +1,49 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_H_
+
+#include "third_party/blink/renderer/core/workers/experimental/task.h"
+#include "third_party/blink/renderer/core/workers/worklet.h"
+#include "third_party/blink/renderer/platform/supplementable.h"
+
+namespace blink {
+class Document;
+class LocalDOMWindow;
+
+class TaskWorklet final : public Worklet,
+ public Supplement<LocalDOMWindow>,
+ public ThreadPoolThreadProvider {
+ DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(TaskWorklet);
+
+ public:
+ static const char kSupplementName[];
+ static TaskWorklet* From(LocalDOMWindow&);
+
+ Task* postTask(ScriptState*,
+ const ScriptValue& task,
+ const Vector<ScriptValue>& arguments);
+
+ Task* postTask(ScriptState*,
+ const String& function_name,
+ const Vector<ScriptValue>& arguments);
+
+ ThreadPoolThread* GetLeastBusyThread() override;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ explicit TaskWorklet(Document*);
+ ~TaskWorklet() override = default;
+
+ bool NeedsToCreateGlobalScope() final;
+ WorkletGlobalScopeProxy* CreateGlobalScope() final;
+ wtf_size_t SelectGlobalScope() final;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl
new file mode 100644
index 00000000000..cbf68ff0a57
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=WorkerTaskQueue,
+ SecureContext
+] interface TaskWorklet : Worklet {
+ [CallWith=ScriptState] Task postTask(CallbackFunctionTreatedAsScriptValue task, any... arguments);
+ [CallWith=ScriptState] Task postTask(USVString task, any... arguments);
+};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc
new file mode 100644
index 00000000000..efec929d9f6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc
@@ -0,0 +1,115 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_parser.h"
+#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+
+class TaskDefinition final : public GarbageCollectedFinalized<TaskDefinition> {
+ public:
+ TaskDefinition(v8::Isolate* isolate,
+ v8::Local<v8::Value> instance,
+ v8::Local<v8::Function> process)
+ : instance_(isolate, instance), process_(isolate, process) {}
+ ~TaskDefinition() = default;
+
+ v8::Local<v8::Value> InstanceLocal(v8::Isolate* isolate) {
+ return instance_.NewLocal(isolate);
+ }
+ v8::Local<v8::Function> ProcessLocal(v8::Isolate* isolate) {
+ return process_.NewLocal(isolate);
+ }
+
+ void Trace(blink::Visitor* visitor) {
+ visitor->Trace(instance_.Cast<v8::Value>());
+ visitor->Trace(process_.Cast<v8::Value>());
+ }
+
+ private:
+ // This object keeps the object and process function alive.
+ // It participates in wrapper tracing as it holds onto V8 wrappers.
+ TraceWrapperV8Reference<v8::Value> instance_;
+ TraceWrapperV8Reference<v8::Function> process_;
+};
+
+TaskWorkletGlobalScope::TaskWorkletGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params,
+ WorkerThread* thread)
+ : WorkletGlobalScope(std::move(creation_params),
+ thread->GetWorkerReportingProxy(),
+ thread) {}
+
+void TaskWorkletGlobalScope::Trace(blink::Visitor* visitor) {
+ WorkletGlobalScope::Trace(visitor);
+ visitor->Trace(task_definitions_);
+}
+
+void TaskWorkletGlobalScope::registerTask(const String& name,
+ const ScriptValue& constructor_value,
+ ExceptionState& exception_state) {
+ DCHECK(IsContextThread());
+ if (task_definitions_.Contains(name)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "A class with name:'" + name + "' is already registered.");
+ return;
+ }
+
+ if (name.IsEmpty()) {
+ exception_state.ThrowTypeError("The empty string is not a valid name.");
+ return;
+ }
+
+ v8::Isolate* isolate = ScriptController()->GetScriptState()->GetIsolate();
+ v8::Local<v8::Context> context = ScriptController()->GetContext();
+
+ DCHECK(constructor_value.V8Value()->IsFunction());
+ v8::Local<v8::Function> constructor =
+ v8::Local<v8::Function>::Cast(constructor_value.V8Value());
+
+ v8::Local<v8::Object> prototype;
+ if (!V8ObjectParser::ParsePrototype(context, constructor, &prototype,
+ &exception_state))
+ return;
+
+ v8::Local<v8::Function> process;
+ if (!V8ObjectParser::ParseFunction(context, prototype, "process", &process,
+ &exception_state))
+ return;
+
+ v8::Local<v8::Value> instance;
+ bool did_construct =
+ V8ScriptRunner::CallAsConstructor(isolate, constructor, this)
+ .ToLocal(&instance);
+ if (!did_construct) {
+ exception_state.ThrowTypeError("Failed to construct TaskProcessor");
+ return;
+ }
+
+ TaskDefinition* definition = new TaskDefinition(isolate, instance, process);
+ task_definitions_.Set(name, definition);
+}
+
+v8::Local<v8::Value> TaskWorkletGlobalScope::GetInstanceForName(
+ const String& name,
+ v8::Isolate* isolate) {
+ TaskDefinition* definition = task_definitions_.at(name);
+ return definition ? definition->InstanceLocal(isolate)
+ : v8::Local<v8::Value>();
+}
+
+v8::Local<v8::Function> TaskWorkletGlobalScope::GetProcessFunctionForName(
+ const String& name,
+ v8::Isolate* isolate) {
+ TaskDefinition* definition = task_definitions_.at(name);
+ return definition ? definition->ProcessLocal(isolate)
+ : v8::Local<v8::Function>();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h
new file mode 100644
index 00000000000..1e4ebb717e8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h
@@ -0,0 +1,38 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_GLOBAL_SCOPE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_GLOBAL_SCOPE_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+
+namespace blink {
+class ExceptionState;
+class TaskDefinition;
+
+class TaskWorkletGlobalScope : public WorkletGlobalScope {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ TaskWorkletGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
+ WorkerThread*);
+ ~TaskWorkletGlobalScope() override = default;
+ void Trace(blink::Visitor*) override;
+
+ void registerTask(const String& name,
+ const ScriptValue& constructor_value,
+ ExceptionState&);
+ v8::Local<v8::Value> GetInstanceForName(const String&, v8::Isolate*);
+ v8::Local<v8::Function> GetProcessFunctionForName(const String&,
+ v8::Isolate*);
+
+ private:
+ HeapHashMap<String, TraceWrapperMember<TaskDefinition>> task_definitions_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_GLOBAL_SCOPE_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl
new file mode 100644
index 00000000000..4e7caced021
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl
@@ -0,0 +1,10 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=WorkerTaskQueue,
+ Global=(Worklet,TaskWorklet)
+] interface TaskWorkletGlobalScope : WorkletGlobalScope {
+ [RaisesException] void registerTask(DOMString name, CallbackFunctionTreatedAsScriptValue taskConstructor);
+};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
index fd79626be2a..bf4e433a239 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
@@ -6,56 +6,15 @@
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/dedicated_worker_factory.mojom-blink.h"
-#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
-#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
-#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
-#include "third_party/blink/renderer/core/dom/abort_signal.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
-#include "third_party/blink/renderer/core/probe/core_probes.h"
-#include "third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h"
#include "third_party/blink/renderer/core/workers/threaded_object_proxy_base.h"
-#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_options.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
-#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
namespace blink {
-class ThreadPoolWorkerGlobalScope final : public WorkerGlobalScope {
- public:
- ThreadPoolWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params,
- WorkerThread* thread)
- : WorkerGlobalScope(std::move(creation_params),
- thread,
- CurrentTimeTicks()) {}
-
- ~ThreadPoolWorkerGlobalScope() override = default;
-
- // EventTarget
- const AtomicString& InterfaceName() const override {
- // TODO(japhet): Replaces this with
- // EventTargetNames::ThreadPoolWorkerGlobalScope.
- return EventTargetNames::DedicatedWorkerGlobalScope;
- }
-
- // WorkerGlobalScope
- void ImportModuleScript(
- const KURL& module_url_record,
- FetchClientSettingsObjectSnapshot* outside_settings_object,
- network::mojom::FetchCredentialsMode) override {
- // TODO(japhet): Consider whether modules should be supported.
- NOTREACHED();
- }
-
- void ExceptionThrown(ErrorEvent*) override {}
-};
-
class ThreadPoolObjectProxy final : public ThreadedObjectProxyBase {
public:
ThreadPoolObjectProxy(ThreadPoolMessagingProxy* messaging_proxy,
@@ -87,8 +46,8 @@ class ThreadPoolMessagingProxy final : public ThreadedMessagingProxyBase {
WorkerBackingThreadStartupData::CreateDefault());
}
std::unique_ptr<WorkerThread> CreateWorkerThread() override {
- return std::make_unique<ThreadPoolThread>(GetExecutionContext(),
- *object_proxy_.get());
+ return std::make_unique<ThreadPoolThread>(
+ GetExecutionContext(), *object_proxy_.get(), ThreadPoolThread::kWorker);
}
ThreadPoolThread* GetWorkerThread() const {
@@ -100,22 +59,6 @@ class ThreadPoolMessagingProxy final : public ThreadedMessagingProxyBase {
std::unique_ptr<ThreadPoolObjectProxy> object_proxy_;
};
-ThreadPoolThread::ThreadPoolThread(ExecutionContext* parent_execution_context,
- ThreadPoolObjectProxy& object_proxy)
- : WorkerThread(object_proxy) {
- FrameOrWorkerScheduler* scheduler =
- parent_execution_context ? parent_execution_context->GetScheduler()
- : nullptr;
- worker_backing_thread_ =
- WorkerBackingThread::Create(ThreadCreationParams(GetThreadType())
- .SetFrameOrWorkerScheduler(scheduler));
-}
-
-WorkerOrWorkletGlobalScope* ThreadPoolThread::CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- return new ThreadPoolWorkerGlobalScope(std::move(creation_params), this);
-}
-
service_manager::mojom::blink::InterfaceProviderPtrInfo
ConnectToWorkerInterfaceProviderForThreadPool(
ExecutionContext* execution_context,
@@ -165,12 +108,15 @@ ThreadPoolThread* ThreadPool::CreateNewThread() {
std::unique_ptr<WorkerSettings> settings =
std::make_unique<WorkerSettings>(GetFrame()->GetSettings());
+ // WebWorkerFetchContext is provided later in
+ // ThreadedMessagingProxyBase::InitializeWorkerThread().
proxy->StartWorker(std::make_unique<GlobalScopeCreationParams>(
- context->Url(), ScriptType::kClassic, context->UserAgent(),
- context->GetContentSecurityPolicy()->Headers(), kReferrerPolicyDefault,
- context->GetSecurityOrigin(), context->IsSecureContext(),
- context->GetHttpsState(), WorkerClients::Create(),
- context->GetSecurityContext().AddressSpace(),
+ context->Url(), mojom::ScriptType::kClassic, context->UserAgent(),
+ nullptr /* web_worker_fetch_context */,
+ context->GetContentSecurityPolicy()->Headers(),
+ network::mojom::ReferrerPolicy::kDefault, context->GetSecurityOrigin(),
+ context->IsSecureContext(), context->GetHttpsState(),
+ WorkerClients::Create(), context->GetSecurityContext().AddressSpace(),
OriginTrialContext::GetTokens(context).get(), devtools_worker_token,
std::move(settings), kV8CacheOptionsDefault,
nullptr /* worklet_module_responses_map */,
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
index af950edb7bf..ff651fa06cc 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
@@ -5,55 +5,17 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_H_
-#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
#include "third_party/blink/renderer/platform/supplementable.h"
namespace blink {
-
class Document;
class ThreadPoolMessagingProxy;
-class ThreadPoolObjectProxy;
-
-class ThreadPoolThread final : public WorkerThread {
- public:
- ThreadPoolThread(ExecutionContext*, ThreadPoolObjectProxy&);
- ~ThreadPoolThread() override = default;
-
- void IncrementTasksInProgressCount() {
- DCHECK(IsMainThread());
- tasks_in_progress_++;
- }
- void DecrementTasksInProgressCount() {
- DCHECK(IsMainThread());
- DCHECK_GT(tasks_in_progress_, 0u);
- tasks_in_progress_--;
- }
- size_t GetTasksInProgressCount() const {
- DCHECK(IsMainThread());
- return tasks_in_progress_;
- }
-
- private:
- WorkerBackingThread& GetWorkerBackingThread() override {
- return *worker_backing_thread_;
- }
- void ClearWorkerBackingThread() override { worker_backing_thread_ = nullptr; }
-
- WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params) override;
-
- WebThreadType GetThreadType() const override {
- // TODO(japhet): Replace with WebThreadType::kThreadPoolWorkerThread.
- return WebThreadType::kDedicatedWorkerThread;
- }
- std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
- size_t tasks_in_progress_ = 0;
-};
class ThreadPool final : public GarbageCollectedFinalized<ThreadPool>,
public Supplement<Document>,
- public ContextLifecycleObserver {
+ public ContextLifecycleObserver,
+ public ThreadPoolThreadProvider {
USING_GARBAGE_COLLECTED_MIXIN(ThreadPool);
EAGERLY_FINALIZE();
@@ -62,7 +24,7 @@ class ThreadPool final : public GarbageCollectedFinalized<ThreadPool>,
static ThreadPool* From(Document&);
~ThreadPool();
- ThreadPoolThread* GetLeastBusyThread();
+ ThreadPoolThread* GetLeastBusyThread() override;
void ContextDestroyed(ExecutionContext*) final;
void Trace(blink::Visitor*) final;
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc
new file mode 100644
index 00000000000..a6371c7adb4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc
@@ -0,0 +1,69 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
+
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/threaded_object_proxy_base.h"
+#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
+
+namespace blink {
+
+namespace {
+
+class ThreadPoolWorkerGlobalScope final : public WorkerGlobalScope {
+ public:
+ ThreadPoolWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params,
+ WorkerThread* thread)
+ : WorkerGlobalScope(std::move(creation_params),
+ thread,
+ CurrentTimeTicks()) {}
+
+ ~ThreadPoolWorkerGlobalScope() override = default;
+
+ // EventTarget
+ const AtomicString& InterfaceName() const override {
+ // TODO(japhet): Replaces this with
+ // EventTargetNames::ThreadPoolWorkerGlobalScope.
+ return event_target_names::kDedicatedWorkerGlobalScope;
+ }
+
+ // WorkerGlobalScope
+ void ImportModuleScript(
+ const KURL& module_url_record,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ network::mojom::FetchCredentialsMode) override {
+ // TODO(japhet): Consider whether modules should be supported.
+ NOTREACHED();
+ }
+
+ void ExceptionThrown(ErrorEvent*) override {}
+};
+
+} // anonymous namespace
+
+ThreadPoolThread::ThreadPoolThread(ExecutionContext* parent_execution_context,
+ ThreadedObjectProxyBase& object_proxy,
+ ThreadBackingPolicy backing_policy)
+ : WorkerThread(object_proxy), backing_policy_(backing_policy) {
+ DCHECK(parent_execution_context);
+ worker_backing_thread_ = WorkerBackingThread::Create(
+ ThreadCreationParams(GetThreadType())
+ .SetFrameOrWorkerScheduler(parent_execution_context->GetScheduler()));
+}
+
+WorkerOrWorkletGlobalScope* ThreadPoolThread::CreateWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params) {
+ if (backing_policy_ == kWorker)
+ return new ThreadPoolWorkerGlobalScope(std::move(creation_params), this);
+ return new TaskWorkletGlobalScope(std::move(creation_params), this);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h
new file mode 100644
index 00000000000..6c8871a0487
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h
@@ -0,0 +1,65 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_THREAD_H_
+
+#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+class ExecutionContext;
+class ThreadedObjectProxyBase;
+
+class ThreadPoolThread final : public WorkerThread {
+ public:
+ enum ThreadBackingPolicy { kWorker, kWorklet };
+
+ ThreadPoolThread(ExecutionContext*,
+ ThreadedObjectProxyBase&,
+ ThreadBackingPolicy);
+ ~ThreadPoolThread() override = default;
+
+ void IncrementTasksInProgressCount() {
+ DCHECK(IsMainThread());
+ tasks_in_progress_++;
+ }
+ void DecrementTasksInProgressCount() {
+ DCHECK(IsMainThread());
+ DCHECK_GT(tasks_in_progress_, 0u);
+ tasks_in_progress_--;
+ }
+ size_t GetTasksInProgressCount() const {
+ DCHECK(IsMainThread());
+ return tasks_in_progress_;
+ }
+
+ bool IsWorklet() const { return backing_policy_ == kWorklet; }
+
+ private:
+ WorkerBackingThread& GetWorkerBackingThread() override {
+ return *worker_backing_thread_;
+ }
+ void ClearWorkerBackingThread() override { worker_backing_thread_ = nullptr; }
+
+ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params) override;
+
+ WebThreadType GetThreadType() const override {
+ // TODO(japhet): Replace with WebThreadType::kThreadPoolWorkerThread.
+ return WebThreadType::kDedicatedWorkerThread;
+ }
+ std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
+ size_t tasks_in_progress_ = 0;
+ const ThreadBackingPolicy backing_policy_;
+};
+
+class ThreadPoolThreadProvider {
+ public:
+ virtual ThreadPoolThread* GetLeastBusyThread() = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h
new file mode 100644
index 00000000000..f4446c8c898
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h
@@ -0,0 +1,23 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WINDOW_TASK_WORKLET_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WINDOW_TASK_WORKLET_H_
+
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet.h"
+
+namespace blink {
+
+class WindowTaskWorklet {
+ STATIC_ONLY(WindowTaskWorklet);
+
+ public:
+ static TaskWorklet* taskWorklet(LocalDOMWindow& window) {
+ return TaskWorklet::From(window);
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WINDOW_TASK_WORKLET_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl
new file mode 100644
index 00000000000..626225faa7b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=WorkerTaskQueue,
+ ImplementedAs=WindowTaskWorklet,
+ SecureContext
+] partial interface Window {
+ [SameObject] readonly attribute TaskWorklet taskWorklet;
+};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
index faf398bfb77..45c42286143 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
@@ -39,23 +39,17 @@ WorkerTaskQueue::WorkerTaskQueue(Document* document, TaskType task_type)
ScriptPromise WorkerTaskQueue::postFunction(
ScriptState* script_state,
- const ScriptValue& task,
+ const ScriptValue& function,
AbortSignal* signal,
const Vector<ScriptValue>& arguments) {
DCHECK(document_->IsContextThread());
- DCHECK(task.IsFunction());
-
- ThreadPoolTask* thread_pool_task = new ThreadPoolTask(
- ThreadPool::From(*document_), script_state->GetIsolate(), task, arguments,
- task_type_);
- if (signal) {
- signal->AddAlgorithm(
- WTF::Bind(&ThreadPoolTask::Cancel, thread_pool_task->GetWeakPtr()));
- }
- ScriptValue value = thread_pool_task->GetResult(script_state);
- DCHECK(value.V8Value()->IsPromise());
+ DCHECK(function.IsFunction());
- return ScriptPromise(script_state, value.V8Value());
+ Task* task = new Task(ThreadPool::From(*document_), script_state, function,
+ arguments, task_type_);
+ if (signal)
+ signal->AddAlgorithm(WTF::Bind(&Task::cancel, WrapWeakPersistent(task)));
+ return task->result(script_state);
}
Task* WorkerTaskQueue::postTask(ScriptState* script_state,
@@ -63,11 +57,8 @@ Task* WorkerTaskQueue::postTask(ScriptState* script_state,
const Vector<ScriptValue>& arguments) {
DCHECK(document_->IsContextThread());
DCHECK(function.IsFunction());
-
- ThreadPoolTask* thread_pool_task = new ThreadPoolTask(
- ThreadPool::From(*document_), script_state->GetIsolate(), function,
- arguments, task_type_);
- return new Task(thread_pool_task);
+ return new Task(ThreadPool::From(*document_), script_state, function,
+ arguments, task_type_);
}
void WorkerTaskQueue::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
index 6eb29b67597..0872c73a929 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
@@ -30,12 +30,12 @@ class CORE_EXPORT WorkerTaskQueue : public ScriptWrappable {
~WorkerTaskQueue() override = default;
ScriptPromise postFunction(ScriptState*,
- const ScriptValue& task,
+ const ScriptValue& function,
AbortSignal*,
const Vector<ScriptValue>& arguments);
Task* postTask(ScriptState*,
- const ScriptValue& task,
+ const ScriptValue& function,
const Vector<ScriptValue>& arguments);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc
index d49696c4306..51b2c32b5e8 100644
--- a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc
+++ b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc
@@ -11,11 +11,11 @@ namespace blink {
GlobalScopeCreationParams::GlobalScopeCreationParams(
const KURL& script_url,
- // TODO(asamidoi): Replace ScriptType to mojom::ScriptType
- ScriptType script_type,
+ mojom::ScriptType script_type,
const String& user_agent,
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context,
const Vector<CSPHeaderAndType>& content_security_policy_parsed_headers,
- ReferrerPolicy referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const SecurityOrigin* starter_origin,
bool starter_secure_context,
HttpsState starter_https_state,
@@ -34,6 +34,7 @@ GlobalScopeCreationParams::GlobalScopeCreationParams(
: script_url(script_url.Copy()),
script_type(script_type),
user_agent(user_agent.IsolatedCopy()),
+ web_worker_fetch_context(std::move(web_worker_fetch_context)),
referrer_policy(referrer_policy),
starter_origin(starter_origin ? starter_origin->IsolatedCopy() : nullptr),
starter_secure_context(starter_secure_context),
diff --git a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h
index dc8b5a119c2..113e5d0773b 100644
--- a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h
+++ b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h
@@ -9,9 +9,12 @@
#include "base/macros.h"
#include "base/optional.h"
#include "base/unguessable_token.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
+#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -24,7 +27,6 @@
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_response_headers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -39,11 +41,11 @@ struct CORE_EXPORT GlobalScopeCreationParams final {
public:
GlobalScopeCreationParams(
const KURL& script_url,
- // TODO(asamidoi): Replace ScriptType to mojom::ScriptType
- ScriptType script_type,
+ mojom::ScriptType script_type,
const String& user_agent,
+ scoped_refptr<WebWorkerFetchContext>,
const Vector<CSPHeaderAndType>& content_security_policy_parsed_headers,
- ReferrerPolicy referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const SecurityOrigin*,
bool starter_secure_context,
HttpsState starter_https_state,
@@ -75,9 +77,11 @@ struct CORE_EXPORT GlobalScopeCreationParams final {
// workers.
KURL script_url;
- ScriptType script_type;
+ mojom::ScriptType script_type;
String user_agent;
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context;
+
// |content_security_policy_parsed_headers| and
// |content_security_policy_raw_headers| are mutually exclusive.
// |content_security_policy_parsed_headers| is an empty vector
@@ -86,7 +90,7 @@ struct CORE_EXPORT GlobalScopeCreationParams final {
base::Optional<ContentSecurityPolicyResponseHeaders>
content_security_policy_raw_headers;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
std::unique_ptr<Vector<String>> origin_trial_tokens;
// The SecurityOrigin of the Document creating a Worker/Worklet.
diff --git a/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc b/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc
index 4ce377db000..6e9e5b9d44a 100644
--- a/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc
+++ b/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc
@@ -27,13 +27,13 @@ InstalledScriptsManager::ScriptData::GetContentSecurityPolicyResponseHeaders() {
}
String InstalledScriptsManager::ScriptData::GetReferrerPolicy() {
- return headers_.Get(HTTPNames::Referrer_Policy);
+ return headers_.Get(http_names::kReferrerPolicy);
}
std::unique_ptr<Vector<String>>
InstalledScriptsManager::ScriptData::CreateOriginTrialTokens() {
return OriginTrialContext::ParseHeaderValue(
- headers_.Get(HTTPNames::Origin_Trial));
+ headers_.Get(http_names::kOriginTrial));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc b/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc
index 6771bef6856..4df15f6fadb 100644
--- a/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc
@@ -64,7 +64,8 @@ class MainThreadWorkletTest : public PageTestBase {
reporting_proxy_ =
std::make_unique<MainThreadWorkletReportingProxyForTest>(document);
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */,
document->GetContentSecurityPolicy()->Headers(),
document->GetReferrerPolicy(), document->GetSecurityOrigin(),
document->IsSecureContext(), document->GetHttpsState(),
@@ -72,8 +73,8 @@ class MainThreadWorkletTest : public PageTestBase {
OriginTrialContext::GetTokens(document).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap);
- global_scope_ = new WorkletGlobalScope(std::move(creation_params),
- *reporting_proxy_, &GetFrame());
+ global_scope_ = MakeGarbageCollected<WorkletGlobalScope>(
+ std::move(creation_params), *reporting_proxy_, &GetFrame());
EXPECT_TRUE(global_scope_->IsMainThreadWorkletGlobalScope());
EXPECT_FALSE(global_scope_->IsThreadedWorkletGlobalScope());
}
diff --git a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc
index 7b3da53d694..1fd643b3b02 100644
--- a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc
+++ b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc
@@ -17,11 +17,11 @@ ParentExecutionContextTaskRunners* ParentExecutionContextTaskRunners::Create(
ExecutionContext* context) {
DCHECK(context);
DCHECK(context->IsContextThread());
- return new ParentExecutionContextTaskRunners(context);
+ return MakeGarbageCollected<ParentExecutionContextTaskRunners>(context);
}
ParentExecutionContextTaskRunners* ParentExecutionContextTaskRunners::Create() {
- return new ParentExecutionContextTaskRunners(nullptr);
+ return MakeGarbageCollected<ParentExecutionContextTaskRunners>(nullptr);
}
ParentExecutionContextTaskRunners::ParentExecutionContextTaskRunners(
@@ -34,9 +34,8 @@ ParentExecutionContextTaskRunners::ParentExecutionContextTaskRunners(
TaskType::kInternalLoading, TaskType::kInternalTest,
TaskType::kInternalMedia, TaskType::kInternalInspector,
TaskType::kInternalWorker}) {
- auto task_runner =
- context ? context->GetTaskRunner(type)
- : Platform::Current()->CurrentThread()->GetTaskRunner();
+ auto task_runner = context ? context->GetTaskRunner(type)
+ : Thread::Current()->GetTaskRunner();
task_runners_.insert(type, std::move(task_runner));
}
}
@@ -54,7 +53,7 @@ void ParentExecutionContextTaskRunners::Trace(blink::Visitor* visitor) {
void ParentExecutionContextTaskRunners::ContextDestroyed(ExecutionContext*) {
MutexLocker lock(mutex_);
for (auto& entry : task_runners_)
- entry.value = Platform::Current()->CurrentThread()->GetTaskRunner();
+ entry.value = Thread::Current()->GetTaskRunner();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h
index 87f22db0c14..05adfb5d2b8 100644
--- a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h
+++ b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h
@@ -35,6 +35,10 @@ class CORE_EXPORT ParentExecutionContextTaskRunners final
// tests that don't have a parent frame.
static ParentExecutionContextTaskRunners* Create();
+ // ExecutionContext could be nullptr if the worker is not associated with a
+ // particular context.
+ explicit ParentExecutionContextTaskRunners(ExecutionContext*);
+
// Might return nullptr for unsupported task types. This can be called from
// any threads.
scoped_refptr<base::SingleThreadTaskRunner> Get(TaskType)
@@ -48,10 +52,6 @@ class CORE_EXPORT ParentExecutionContextTaskRunners final
WTF::IntHash<TaskType>,
TaskTypeTraits>;
- // ExecutionContext could be nullptr if the worker is not associated with a
- // particular context.
- explicit ParentExecutionContextTaskRunners(ExecutionContext*);
-
void ContextDestroyed(ExecutionContext*) LOCKS_EXCLUDED(mutex_) override;
Mutex mutex_;
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
index e222bdefae3..4433a999d5f 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
@@ -58,7 +58,7 @@ SharedWorker* SharedWorker::Create(ExecutionContext* context,
UseCounter::Count(context, WebFeature::kSharedWorkerStart);
- SharedWorker* worker = new SharedWorker(context);
+ SharedWorker* worker = MakeGarbageCollected<SharedWorker>(context);
MessageChannel* channel = MessageChannel::Create(context);
worker->port_ = channel->port1();
@@ -99,7 +99,7 @@ SharedWorker* SharedWorker::Create(ExecutionContext* context,
SharedWorker::~SharedWorker() = default;
const AtomicString& SharedWorker::InterfaceName() const {
- return EventTargetNames::SharedWorker;
+ return event_target_names::kSharedWorker;
}
bool SharedWorker::HasPendingActivity() const {
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker.h b/chromium/third_party/blink/renderer/core/workers/shared_worker.h
index 9b438d69eb7..3a1851ebd65 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker.h
@@ -54,6 +54,8 @@ class CORE_EXPORT SharedWorker final
const String& url,
const String& name,
ExceptionState&);
+
+ explicit SharedWorker(ExecutionContext*);
~SharedWorker() override;
MessagePort* port() const { return port_.Get(); }
@@ -68,8 +70,6 @@ class CORE_EXPORT SharedWorker final
void Trace(blink::Visitor*) override;
private:
- explicit SharedWorker(ExecutionContext*);
-
Member<MessagePort> port_;
bool is_being_connected_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc
index 5d4894caeca..262aeea034f 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc
@@ -15,10 +15,9 @@ SharedWorkerContentSettingsProxy::SharedWorkerContentSettingsProxy(
SharedWorkerContentSettingsProxy::~SharedWorkerContentSettingsProxy() = default;
bool SharedWorkerContentSettingsProxy::AllowIndexedDB(
- const WebString& name,
const WebSecurityOrigin& origin) {
bool result = false;
- GetService()->AllowIndexedDB(name, &result);
+ GetService()->AllowIndexedDB(&result);
return result;
}
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h
index 1fb2dccc283..f1a3f2eec1e 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h
@@ -22,7 +22,7 @@ class SharedWorkerContentSettingsProxy : public WebContentSettingsClient {
~SharedWorkerContentSettingsProxy() override;
// WebContentSettingsClient overrides.
- bool AllowIndexedDB(const WebString& name, const WebSecurityOrigin&) override;
+ bool AllowIndexedDB(const WebSecurityOrigin&) override;
bool RequestFileSystemAccessSync() override;
private:
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc
index 6ae503c2c98..c68d18e1b3d 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc
@@ -52,7 +52,7 @@ SharedWorkerGlobalScope::SharedWorkerGlobalScope(
SharedWorkerGlobalScope::~SharedWorkerGlobalScope() = default;
const AtomicString& SharedWorkerGlobalScope::InterfaceName() const {
- return EventTargetNames::SharedWorkerGlobalScope;
+ return event_target_names::kSharedWorkerGlobalScope;
}
// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
@@ -81,9 +81,10 @@ void SharedWorkerGlobalScope::ConnectPausable(MessagePortChannel channel) {
MessagePort* port = MessagePort::Create(*this);
port->Entangle(std::move(channel));
- MessageEvent* event = MessageEvent::Create(new MessagePortArray(1, port),
- String(), String(), port);
- event->initEvent(EventTypeNames::connect, false, false);
+ MessageEvent* event =
+ MessageEvent::Create(MakeGarbageCollected<MessagePortArray>(1, port),
+ String(), String(), port);
+ event->initEvent(event_type_names::kConnect, false, false);
DispatchEvent(*event);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h
index 9f51411a1f8..8b5a667f308 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h
@@ -64,7 +64,7 @@ class SharedWorkerGlobalScope final : public WorkerGlobalScope {
network::mojom::FetchCredentialsMode) override;
// Setters/Getters for attributes in SharedWorkerGlobalScope.idl
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect);
String name() const { return name_; }
void ConnectPausable(MessagePortChannel channel);
@@ -76,6 +76,14 @@ class SharedWorkerGlobalScope final : public WorkerGlobalScope {
const String name_;
};
+
+template <>
+struct DowncastTraits<SharedWorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsSharedWorkerGlobalScope();
+ }
+};
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_GLOBAL_SCOPE_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl
index 9b3d13b296d..c26b4c4af34 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl
@@ -34,7 +34,7 @@
Global=(Worker,SharedWorker),
Exposed=SharedWorker
] interface SharedWorkerGlobalScope : WorkerGlobalScope {
- readonly attribute DOMString name;
+ [Replaceable] readonly attribute DOMString name;
// TODO(foolip): readonly attribute ApplicationCache applicationCache;
void close();
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc
index 5433c7444d9..a1def054e31 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc
@@ -58,18 +58,6 @@ void SharedWorkerReportingProxy::ReportConsoleMessage(MessageSource,
// Not supported in SharedWorker.
}
-void SharedWorkerReportingProxy::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- DCHECK(!IsMainThread());
- PostCrossThreadTask(
- *parent_execution_context_task_runners_->Get(
- TaskType::kInternalInspector),
- FROM_HERE,
- CrossThreadBind(&WebSharedWorkerImpl::PostMessageToPageInspector,
- CrossThreadUnretained(worker_), session_id, message));
-}
-
void SharedWorkerReportingProxy::DidCloseWorkerGlobalScope() {
DCHECK(!IsMainThread());
PostCrossThreadTask(
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h
index 280e2da2ce5..ad84445fe28 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h
@@ -35,7 +35,6 @@ class SharedWorkerReportingProxy final
MessageLevel,
const String& message,
SourceLocation*) override;
- void PostMessageToPageInspector(int session_id, const WTF::String&) override;
void DidEvaluateClassicScript(bool success) override {}
void DidCloseWorkerGlobalScope() override;
void WillDestroyWorkerGlobalScope() override {}
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc
index a5c62bfc32c..58643083e14 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc
@@ -53,8 +53,8 @@ void SharedWorkerThread::ClearWorkerBackingThread() {
WorkerOrWorkletGlobalScope* SharedWorkerThread::CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- return new SharedWorkerGlobalScope(name_, std::move(creation_params), this,
- time_origin_);
+ return MakeGarbageCollected<SharedWorkerGlobalScope>(
+ name_, std::move(creation_params), this, time_origin_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc
index 79a53c6e7d0..124ee1e0c70 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc
@@ -10,13 +10,12 @@
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/core/frame/local_frame_client.h"
+#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/devtools_agent.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
-#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -31,7 +30,6 @@ static int g_live_messaging_proxy_count = 0;
ThreadedMessagingProxyBase::ThreadedMessagingProxyBase(
ExecutionContext* execution_context)
: execution_context_(execution_context),
- worker_inspector_proxy_(WorkerInspectorProxy::Create()),
parent_execution_context_task_runners_(
ParentExecutionContextTaskRunners::Create(execution_context_.Get())),
terminate_sync_load_event_(
@@ -53,7 +51,6 @@ int ThreadedMessagingProxyBase::ProxyCount() {
void ThreadedMessagingProxyBase::Trace(blink::Visitor* visitor) {
visitor->Trace(execution_context_);
- visitor->Trace(worker_inspector_proxy_);
}
void ThreadedMessagingProxyBase::InitializeWorkerThread(
@@ -63,44 +60,22 @@ void ThreadedMessagingProxyBase::InitializeWorkerThread(
KURL script_url = global_scope_creation_params->script_url.Copy();
- std::unique_ptr<WebWorkerFetchContext> web_worker_fetch_context;
- if (auto* document = DynamicTo<Document>(execution_context_.Get())) {
- LocalFrame* frame = document->GetFrame();
- web_worker_fetch_context = frame->Client()->CreateWorkerFetchContext();
- // |web_worker_fetch_context| is null in some unit tests.
- if (web_worker_fetch_context) {
- web_worker_fetch_context->SetApplicationCacheHostID(
- GetExecutionContext()->Fetcher()->Context().ApplicationCacheHostID());
- web_worker_fetch_context->SetIsOnSubframe(!frame->IsMainFrame());
- }
- } else if (execution_context_->IsWorkerGlobalScope()) {
- web_worker_fetch_context =
- static_cast<WorkerFetchContext&>(
- ToWorkerGlobalScope(execution_context_)->Fetcher()->Context())
- .GetWebWorkerFetchContext()
- ->CloneForNestedWorker();
- }
-
- if (web_worker_fetch_context) {
- web_worker_fetch_context->SetTerminateSyncLoadEvent(
- &terminate_sync_load_event_);
- ProvideWorkerFetchContextToWorker(
- global_scope_creation_params->worker_clients,
- std::move(web_worker_fetch_context));
+ if (global_scope_creation_params->web_worker_fetch_context) {
+ global_scope_creation_params->web_worker_fetch_context
+ ->SetTerminateSyncLoadEvent(&terminate_sync_load_event_);
}
worker_thread_ = CreateWorkerThread();
- worker_thread_->Start(
- std::move(global_scope_creation_params), thread_startup_data,
- GetWorkerInspectorProxy()->ShouldPauseOnWorkerStart(execution_context_),
- GetParentExecutionContextTaskRunners());
- GetWorkerInspectorProxy()->WorkerThreadCreated(execution_context_,
- GetWorkerThread(), script_url);
-
- if (execution_context_->IsWorkerGlobalScope()) {
- ToWorkerGlobalScope(execution_context_)
- ->GetThread()
- ->ChildThreadStartedOnWorkerThread(worker_thread_.get());
+
+ auto devtools_params = DevToolsAgent::WorkerThreadCreated(
+ execution_context_.Get(), worker_thread_.get(), script_url);
+
+ worker_thread_->Start(std::move(global_scope_creation_params),
+ thread_startup_data, std::move(devtools_params),
+ GetParentExecutionContextTaskRunners());
+
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_)) {
+ scope->GetThread()->ChildThreadStartedOnWorkerThread(worker_thread_.get());
}
}
@@ -145,12 +120,14 @@ void ThreadedMessagingProxyBase::WorkerThreadTerminated() {
// Worker/Worklet object may still exist, and it assumes that the proxy
// exists, too.
asked_to_terminate_ = true;
- WorkerThread* parent_thread =
- execution_context_->IsWorkerGlobalScope()
- ? ToWorkerGlobalScope(execution_context_)->GetThread()
- : nullptr;
+ WorkerThread* parent_thread = nullptr;
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_))
+ parent_thread = scope->GetThread();
std::unique_ptr<WorkerThread> child_thread = std::move(worker_thread_);
- worker_inspector_proxy_->WorkerThreadTerminated();
+ if (child_thread) {
+ DevToolsAgent::WorkerThreadTerminated(execution_context_.Get(),
+ child_thread.get());
+ }
// If the parent Worker/Worklet object was already destroyed, this will
// destroy |this|.
@@ -169,18 +146,11 @@ void ThreadedMessagingProxyBase::TerminateGlobalScope() {
terminate_sync_load_event_.Signal();
- if (worker_thread_)
- worker_thread_->Terminate();
-
- worker_inspector_proxy_->WorkerThreadTerminated();
-}
-
-void ThreadedMessagingProxyBase::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- DCHECK(IsParentContextThread());
- if (worker_inspector_proxy_)
- worker_inspector_proxy_->DispatchMessageFromWorker(session_id, message);
+ if (!worker_thread_)
+ return;
+ worker_thread_->Terminate();
+ DevToolsAgent::WorkerThreadTerminated(execution_context_.Get(),
+ worker_thread_.get());
}
ExecutionContext* ThreadedMessagingProxyBase::GetExecutionContext() const {
@@ -194,12 +164,6 @@ ThreadedMessagingProxyBase::GetParentExecutionContextTaskRunners() const {
return parent_execution_context_task_runners_;
}
-WorkerInspectorProxy* ThreadedMessagingProxyBase::GetWorkerInspectorProxy()
- const {
- DCHECK(IsParentContextThread());
- return worker_inspector_proxy_;
-}
-
WorkerThread* ThreadedMessagingProxyBase::GetWorkerThread() const {
DCHECK(IsParentContextThread());
return worker_thread_.get();
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h
index fa6c682bd40..d4b61b1cef5 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h
@@ -25,7 +25,6 @@ namespace blink {
class ExecutionContext;
class SourceLocation;
-class WorkerInspectorProxy;
struct GlobalScopeCreationParams;
// The base proxy class to talk to Worker/WorkletGlobalScope on a worker thread
@@ -60,7 +59,6 @@ class CORE_EXPORT ThreadedMessagingProxyBase
MessageLevel,
const String& message,
std::unique_ptr<SourceLocation>);
- void PostMessageToPageInspector(int session_id, const String&);
void WorkerThreadTerminated();
@@ -79,7 +77,6 @@ class CORE_EXPORT ThreadedMessagingProxyBase
ExecutionContext* GetExecutionContext() const;
ParentExecutionContextTaskRunners* GetParentExecutionContextTaskRunners()
const;
- WorkerInspectorProxy* GetWorkerInspectorProxy() const;
// May return nullptr after termination is requested.
WorkerThread* GetWorkerThread() const;
@@ -93,7 +90,6 @@ class CORE_EXPORT ThreadedMessagingProxyBase
virtual std::unique_ptr<WorkerThread> CreateWorkerThread() = 0;
Member<ExecutionContext> execution_context_;
- Member<WorkerInspectorProxy> worker_inspector_proxy_;
// Accessed cross-thread when worker thread posts tasks to the parent.
CrossThreadPersistent<ParentExecutionContextTaskRunners>
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc
index 7784a284c20..1730f2ef808 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
#include "third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -43,19 +43,6 @@ void ThreadedObjectProxyBase::ReportConsoleMessage(MessageSource source,
WTF::Passed(location->Clone())));
}
-void ThreadedObjectProxyBase::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- // The TaskType of Inspector tasks need to be Unthrottled because they need to
- // run even on a suspended page.
- PostCrossThreadTask(
- *GetParentExecutionContextTaskRunners()->Get(
- TaskType::kInternalInspector),
- FROM_HERE,
- CrossThreadBind(&ThreadedMessagingProxyBase::PostMessageToPageInspector,
- MessagingProxyWeakPtr(), session_id, message));
-}
-
void ThreadedObjectProxyBase::DidCloseWorkerGlobalScope() {
PostCrossThreadTask(
*GetParentExecutionContextTaskRunners()->Get(TaskType::kInternalDefault),
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h
index 69c7850a385..b8bbe9e0f27 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h
@@ -35,7 +35,6 @@ class CORE_EXPORT ThreadedObjectProxyBase : public WorkerReportingProxy {
MessageLevel,
const String& message,
SourceLocation*) override;
- void PostMessageToPageInspector(int session_id, const String&) override;
void DidCloseWorkerGlobalScope() override;
void DidTerminateWorkerThread() override;
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc
index 8be178d7e25..dc7d022c400 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h"
#include "base/single_thread_task_runner.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -19,13 +20,12 @@
#include "third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_clients.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#include "third_party/blink/renderer/core/workers/worklet_pending_tasks.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -35,7 +35,8 @@ ThreadedWorkletMessagingProxy::ThreadedWorkletMessagingProxy(
void ThreadedWorkletMessagingProxy::Initialize(
WorkerClients* worker_clients,
- WorkletModuleResponsesMap* module_responses_map) {
+ WorkletModuleResponsesMap* module_responses_map,
+ const base::Optional<WorkerBackingThreadStartupData>& thread_startup_data) {
DCHECK(IsMainThread());
if (AskedToTerminate())
return;
@@ -47,16 +48,14 @@ void ThreadedWorkletMessagingProxy::Initialize(
ContentSecurityPolicy* csp = document->GetContentSecurityPolicy();
DCHECK(csp);
- ProvideWorkerFetchContextToWorker(
- worker_clients,
- document->GetFrame()->Client()->CreateWorkerFetchContext());
ProvideContentSettingsClientToWorker(
worker_clients,
document->GetFrame()->Client()->CreateWorkerContentSettingsClient());
auto global_scope_creation_params =
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ document->GetFrame()->Client()->CreateWorkerFetchContext(),
csp->Headers(), document->GetReferrerPolicy(),
document->GetSecurityOrigin(), document->IsSecureContext(),
document->GetHttpsState(), worker_clients, document->AddressSpace(),
@@ -71,7 +70,7 @@ void ThreadedWorkletMessagingProxy::Initialize(
// Worklets share the pre-initialized backing thread so that we don't have to
// specify the backing thread startup data.
InitializeWorkerThread(std::move(global_scope_creation_params),
- base::nullopt);
+ thread_startup_data);
}
void ThreadedWorkletMessagingProxy::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h
index caad225d996..733b29f7f98 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h
@@ -32,7 +32,10 @@ class CORE_EXPORT ThreadedWorkletMessagingProxy
void WorkletObjectDestroyed() final;
void TerminateWorkletGlobalScope() final;
- void Initialize(WorkerClients*, WorkletModuleResponsesMap*);
+ void Initialize(
+ WorkerClients*,
+ WorkletModuleResponsesMap*,
+ const base::Optional<WorkerBackingThreadStartupData>& = base::nullopt);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc
index b98c1b5fa75..3a70d19ae1e 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc
@@ -33,11 +33,11 @@ void ThreadedWorkletObjectProxy::FetchAndInvokeScript(
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
WorkletPendingTasks* pending_tasks,
WorkerThread* worker_thread) {
- WorkletGlobalScope* global_scope =
- ToWorkletGlobalScope(worker_thread->GlobalScope());
+ auto* global_scope = To<WorkletGlobalScope>(worker_thread->GlobalScope());
global_scope->FetchAndInvokeScript(
module_url_record, credentials_mode,
- new FetchClientSettingsObjectSnapshot(std::move(outside_settings_object)),
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ std::move(outside_settings_object)),
std::move(outside_settings_task_runner), pending_tasks);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc
index 4b9d4854aed..052cdb7a446 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc
@@ -83,7 +83,7 @@ class ThreadedWorkletThreadForTest : public WorkerThread {
}
void TestSecurityOrigin() {
- WorkletGlobalScope* global_scope = ToWorkletGlobalScope(GlobalScope());
+ WorkletGlobalScope* global_scope = To<WorkletGlobalScope>(GlobalScope());
// The SecurityOrigin for a worklet should be a unique opaque origin, while
// the owner Document's SecurityOrigin shouldn't.
EXPECT_TRUE(global_scope->GetSecurityOrigin()->IsOpaque());
@@ -170,7 +170,7 @@ class ThreadedWorkletThreadForTest : public WorkerThread {
private:
WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) final {
- auto* global_scope = new WorkletGlobalScope(
+ auto* global_scope = MakeGarbageCollected<WorkletGlobalScope>(
std::move(creation_params), GetWorkerReportingProxy(), this);
EXPECT_FALSE(global_scope->IsMainThreadWorkletGlobalScope());
EXPECT_TRUE(global_scope->IsThreadedWorkletGlobalScope());
@@ -203,7 +203,8 @@ class ThreadedWorkletMessagingProxyForTest
std::unique_ptr<WorkerSettings> worker_settings = nullptr;
InitializeWorkerThread(
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */,
document->GetContentSecurityPolicy()->Headers(),
document->GetReferrerPolicy(), document->GetSecurityOrigin(),
document->IsSecureContext(), document->GetHttpsState(),
@@ -230,7 +231,8 @@ class ThreadedWorkletTest : public testing::Test {
document->SetURL(KURL("https://example.com/"));
document->UpdateSecurityOrigin(SecurityOrigin::Create(document->Url()));
messaging_proxy_ =
- new ThreadedWorkletMessagingProxyForTest(&page_->GetDocument());
+ MakeGarbageCollected<ThreadedWorkletMessagingProxyForTest>(
+ &page_->GetDocument());
ThreadedWorkletThreadForTest::EnsureSharedBackingThread();
}
diff --git a/chromium/third_party/blink/renderer/core/workers/worker.idl b/chromium/third_party/blink/renderer/core/workers/worker.idl
index 463f2518a88..3830550e27b 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker.idl
+++ b/chromium/third_party/blink/renderer/core/workers/worker.idl
@@ -31,14 +31,14 @@
ActiveScriptWrappable,
Constructor(DOMString scriptURL, optional WorkerOptions options),
ConstructorCallWith=ExecutionContext,
- Exposed(Window StableBlinkFeatures,DedicatedWorker NestedWorkers),
+ Exposed=(Window,DedicatedWorker),
RaisesException=Constructor,
ImplementedAs=DedicatedWorker
] interface Worker : EventTarget {
void terminate();
- [CallWith=ScriptState, RaisesException] void postMessage(any message, optional sequence<object> transfer=[]);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, optional PostMessageOptions options);
attribute EventHandler onmessage;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h b/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h
index 386e133fa34..2b954efeded 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h
@@ -32,10 +32,14 @@ class CORE_EXPORT WorkerAnimationFrameProvider
static WorkerAnimationFrameProvider* Create(
ExecutionContext* context,
const BeginFrameProviderParams& begin_frame_provider_params) {
- return new WorkerAnimationFrameProvider(context,
- begin_frame_provider_params);
+ return MakeGarbageCollected<WorkerAnimationFrameProvider>(
+ context, begin_frame_provider_params);
}
+ WorkerAnimationFrameProvider(
+ ExecutionContext* context,
+ const BeginFrameProviderParams& begin_frame_provider_params);
+
int RegisterCallback(FrameRequestCallbackCollection::FrameCallback* callback);
void CancelCallback(int id);
@@ -50,11 +54,6 @@ class CORE_EXPORT WorkerAnimationFrameProvider
static const int kInvalidCallbackId = -1;
- protected:
- WorkerAnimationFrameProvider(
- ExecutionContext* context,
- const BeginFrameProviderParams& begin_frame_provider_params);
-
private:
const std::unique_ptr<BeginFrameProvider> begin_frame_provider_;
DISALLOW_COPY_AND_ASSIGN(WorkerAnimationFrameProvider);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
index 4bc3d11ba02..c0cec745454 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
@@ -33,7 +33,6 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/html/parser/text_resource_decoder.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
-#include "third_party/blink/renderer/core/loader/allowed_by_nosniff.h"
#include "third_party/blink/renderer/core/loader/resource/script_resource.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
@@ -43,21 +42,14 @@
#include "third_party/blink/renderer/platform/network/content_security_policy_response_headers.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
WorkerClassicScriptLoader::WorkerClassicScriptLoader()
- : response_address_space_(mojom::IPAddressSpace::kPublic) {}
-
-WorkerClassicScriptLoader::~WorkerClassicScriptLoader() {
- // If |threadable_loader_| is still working, we have to cancel it here.
- // Otherwise DidFail() of the deleted |this| will be called from
- // ThreadableLoader::NotifyFinished() when the frame will be
- // destroyed.
- if (need_to_cancel_)
- Cancel();
-}
+ : response_address_space_(mojom::IPAddressSpace::kPublic),
+ mime_type_check_mode_(AllowedByNosniff::MimeTypeCheck::kStrict) {}
void WorkerClassicScriptLoader::LoadSynchronously(
ExecutionContext& execution_context,
@@ -67,8 +59,12 @@ void WorkerClassicScriptLoader::LoadSynchronously(
url_ = url;
execution_context_ = &execution_context;
+ // Impose strict MIME-type checks on importScripts(). See
+ // https://crbug.com/794548.
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kStrict;
+
ResourceRequest request(url);
- request.SetHTTPMethod(HTTPNames::GET);
+ request.SetHTTPMethod(http_names::kGET);
request.SetExternalRequestStateFromRequestorAddressSpace(
creation_address_space);
request.SetRequestContext(request_context);
@@ -80,7 +76,7 @@ void WorkerClassicScriptLoader::LoadSynchronously(
ParserDisposition::kNotParserInserted;
resource_loader_options.synchronous_policy = kRequestSynchronously;
- threadable_loader_ = new ThreadableLoader(
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
execution_context, this, resource_loader_options);
threadable_loader_->Start(request);
}
@@ -92,6 +88,7 @@ void WorkerClassicScriptLoader::LoadTopLevelScriptAsynchronously(
network::mojom::FetchRequestMode fetch_request_mode,
network::mojom::FetchCredentialsMode fetch_credentials_mode,
mojom::IPAddressSpace creation_address_space,
+ bool is_nested_worker,
base::OnceClosure response_callback,
base::OnceClosure finished_callback) {
DCHECK(response_callback || finished_callback);
@@ -101,24 +98,41 @@ void WorkerClassicScriptLoader::LoadTopLevelScriptAsynchronously(
execution_context_ = &execution_context;
forbid_cross_origin_redirects_ = true;
+ if (execution_context.IsDocument()) {
+ // For worker creation on a document, don't impose strict MIME-type checks
+ // on the top-level worker script for backward compatibility. Note that
+ // there is a plan to deprecate legacy mime types for workers. See
+ // https://crbug.com/794548.
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kLax;
+ } else {
+ DCHECK(execution_context.IsWorkerGlobalScope());
+ if (is_nested_worker) {
+ // For nested workers, impose the strict MIME-type checks because the
+ // feature is new (enabled by default in M69) and there is no backward
+ // compatibility issue.
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kStrict;
+ } else {
+ // For worker creation on a document with off-the-main-thread top-level
+ // worker classic script loading, don't impose strict MIME-type checks for
+ // backward compatibility.
+ // TODO(nhiroki): Always impose strict MIME-type checks on all web
+ // workers (https://crbug.com/794548).
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kLax;
+ }
+ }
+
ResourceRequest request(url);
- request.SetHTTPMethod(HTTPNames::GET);
+ request.SetHTTPMethod(http_names::kGET);
request.SetExternalRequestStateFromRequestorAddressSpace(
creation_address_space);
request.SetRequestContext(request_context);
request.SetFetchRequestMode(fetch_request_mode);
request.SetFetchCredentialsMode(fetch_credentials_mode);
- ResourceLoaderOptions resource_loader_options;
-
- // During create, callbacks may happen which could remove the last reference
- // to this object, while some of the callchain assumes that the client and
- // loader wouldn't be deleted within callbacks.
- // (E.g. see crbug.com/524694 for why we can't easily remove this protect)
- scoped_refptr<WorkerClassicScriptLoader> protect(this);
need_to_cancel_ = true;
- threadable_loader_ = new ThreadableLoader(
- execution_context, this, resource_loader_options);
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
+ execution_context, this, ResourceLoaderOptions());
threadable_loader_->Start(request);
if (failed_)
NotifyFinished();
@@ -138,7 +152,8 @@ void WorkerClassicScriptLoader::DidReceiveResponse(
NotifyError();
return;
}
- if (!AllowedByNosniff::MimeTypeAsScript(execution_context_, response)) {
+ if (!AllowedByNosniff::MimeTypeAsScript(execution_context_, response,
+ mime_type_check_mode_)) {
NotifyError();
return;
}
@@ -165,12 +180,12 @@ void WorkerClassicScriptLoader::DidReceiveResponse(
response_encoding_ = response.TextEncodingName();
app_cache_id_ = response.AppCacheID();
- referrer_policy_ = response.HttpHeaderField(HTTPNames::Referrer_Policy);
+ referrer_policy_ = response.HttpHeaderField(http_names::kReferrerPolicy);
ProcessContentSecurityPolicy(response);
origin_trial_tokens_ = OriginTrialContext::ParseHeaderValue(
- response.HttpHeaderField(HTTPNames::Origin_Trial));
+ response.HttpHeaderField(http_names::kOriginTrial));
- if (NetworkUtils::IsReservedIPAddress(response.RemoteIPAddress())) {
+ if (network_utils::IsReservedIPAddress(response.RemoteIPAddress())) {
response_address_space_ =
SecurityOrigin::Create(response_url_)->IsLocalhost()
? mojom::IPAddressSpace::kLocal
@@ -224,7 +239,16 @@ void WorkerClassicScriptLoader::DidFailRedirectCheck() {
NotifyError();
}
+void WorkerClassicScriptLoader::Trace(Visitor* visitor) {
+ visitor->Trace(threadable_loader_);
+ visitor->Trace(content_security_policy_);
+ visitor->Trace(execution_context_);
+ ThreadableLoaderClient::Trace(visitor);
+}
+
void WorkerClassicScriptLoader::Cancel() {
+ if (!need_to_cancel_)
+ return;
need_to_cancel_ = false;
if (threadable_loader_)
threadable_loader_->Cancel();
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
index b561a9633c6..55810312926 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
@@ -35,6 +35,7 @@
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
+#include "third_party/blink/renderer/core/loader/allowed_by_nosniff.h"
#include "third_party/blink/renderer/core/loader/threadable_loader.h"
#include "third_party/blink/renderer/core/loader/threadable_loader_client.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
@@ -52,14 +53,12 @@ class ExecutionContext;
class TextResourceDecoder;
class CORE_EXPORT WorkerClassicScriptLoader final
- : public RefCounted<WorkerClassicScriptLoader>,
+ : public GarbageCollectedFinalized<WorkerClassicScriptLoader>,
public ThreadableLoaderClient {
- USING_FAST_MALLOC(WorkerClassicScriptLoader);
+ USING_GARBAGE_COLLECTED_MIXIN(WorkerClassicScriptLoader);
public:
- static scoped_refptr<WorkerClassicScriptLoader> Create() {
- return base::AdoptRef(new WorkerClassicScriptLoader());
- }
+ WorkerClassicScriptLoader();
// For importScript().
void LoadSynchronously(ExecutionContext&,
@@ -75,6 +74,7 @@ class CORE_EXPORT WorkerClassicScriptLoader final
network::mojom::FetchRequestMode,
network::mojom::FetchCredentialsMode,
mojom::IPAddressSpace,
+ bool is_nested_worker,
base::OnceClosure response_callback,
base::OnceClosure finished_callback);
@@ -93,7 +93,6 @@ class CORE_EXPORT WorkerClassicScriptLoader final
std::unique_ptr<Vector<char>> ReleaseCachedMetadata() {
return std::move(cached_metadata_);
}
- const Vector<char>* CachedMetadata() const { return cached_metadata_.get(); }
ContentSecurityPolicy* GetContentSecurityPolicy() {
return content_security_policy_.Get();
@@ -119,12 +118,9 @@ class CORE_EXPORT WorkerClassicScriptLoader final
void DidFail(const ResourceError&) override;
void DidFailRedirectCheck() override;
- private:
- friend class WTF::RefCounted<WorkerClassicScriptLoader>;
-
- WorkerClassicScriptLoader();
- ~WorkerClassicScriptLoader() override;
+ void Trace(Visitor*) override;
+ private:
void NotifyError();
void NotifyFinished();
@@ -134,7 +130,7 @@ class CORE_EXPORT WorkerClassicScriptLoader final
base::OnceClosure response_callback_;
base::OnceClosure finished_callback_;
- Persistent<ThreadableLoader> threadable_loader_;
+ Member<ThreadableLoader> threadable_loader_;
String response_encoding_;
std::unique_ptr<TextResourceDecoder> decoder_;
StringBuilder source_text_;
@@ -151,11 +147,14 @@ class CORE_EXPORT WorkerClassicScriptLoader final
unsigned long identifier_ = 0;
long long app_cache_id_ = 0;
std::unique_ptr<Vector<char>> cached_metadata_;
- Persistent<ContentSecurityPolicy> content_security_policy_;
- Persistent<ExecutionContext> execution_context_;
+ Member<ContentSecurityPolicy> content_security_policy_;
+ Member<ExecutionContext> execution_context_;
mojom::IPAddressSpace response_address_space_;
std::unique_ptr<Vector<String>> origin_trial_tokens_;
String referrer_policy_;
+
+ // TODO(nhiroki): Move this to FetchClientSettingsObject.
+ AllowedByNosniff::MimeTypeCheck mime_type_check_mode_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_clients.h b/chromium/third_party/blink/renderer/core/workers/worker_clients.h
index 11f0154d23a..2f5ca1cb1be 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_clients.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_clients.h
@@ -47,14 +47,17 @@ class CORE_EXPORT WorkerClients final : public GarbageCollected<WorkerClients>,
USING_GARBAGE_COLLECTED_MIXIN(WorkerClients);
public:
- static WorkerClients* Create() { return new WorkerClients; }
+ static WorkerClients* Create() {
+ return MakeGarbageCollected<WorkerClients>();
+ }
+
+ WorkerClients() = default;
void Trace(blink::Visitor* visitor) override {
Supplementable<WorkerClients>::Trace(visitor);
}
private:
- WorkerClients() = default;
DISALLOW_COPY_AND_ASSIGN(WorkerClients);
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc
index 484c4f3ccdf..a255a36a4c8 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc
@@ -40,7 +40,7 @@ namespace blink {
WorkerContentSettingsClient* WorkerContentSettingsClient::Create(
std::unique_ptr<WebContentSettingsClient> client) {
- return new WorkerContentSettingsClient(std::move(client));
+ return MakeGarbageCollected<WorkerContentSettingsClient>(std::move(client));
}
WorkerContentSettingsClient::~WorkerContentSettingsClient() = default;
@@ -51,10 +51,10 @@ bool WorkerContentSettingsClient::RequestFileSystemAccessSync() {
return client_->RequestFileSystemAccessSync();
}
-bool WorkerContentSettingsClient::AllowIndexedDB(const WebString& name) {
+bool WorkerContentSettingsClient::AllowIndexedDB() {
if (!client_)
return true;
- return client_->AllowIndexedDB(name, WebSecurityOrigin());
+ return client_->AllowIndexedDB(WebSecurityOrigin());
}
bool WorkerContentSettingsClient::AllowScriptFromSource(
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h
index 4db0bf225e9..3a7f7f61abe 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h
@@ -42,7 +42,6 @@ namespace blink {
class ExecutionContext;
class KURL;
class SecurityOrigin;
-class WebString;
class CORE_EXPORT WorkerContentSettingsClient final
: public GarbageCollectedFinalized<WorkerContentSettingsClient>,
@@ -54,10 +53,13 @@ class CORE_EXPORT WorkerContentSettingsClient final
static WorkerContentSettingsClient* Create(
std::unique_ptr<WebContentSettingsClient>);
+
+ explicit WorkerContentSettingsClient(
+ std::unique_ptr<WebContentSettingsClient>);
virtual ~WorkerContentSettingsClient();
bool RequestFileSystemAccessSync();
- bool AllowIndexedDB(const WebString& name);
+ bool AllowIndexedDB();
bool AllowRunningInsecureContent(bool enabled_per_settings,
const SecurityOrigin*,
const KURL&);
@@ -74,9 +76,6 @@ class CORE_EXPORT WorkerContentSettingsClient final
}
private:
- explicit WorkerContentSettingsClient(
- std::unique_ptr<WebContentSettingsClient>);
-
std::unique_ptr<WebContentSettingsClient> client_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc
index 38df09470d3..78d29e65477 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc
@@ -69,6 +69,7 @@
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -145,7 +146,7 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls,
// Step 1: "If worker global scope's type is "module", throw a TypeError
// exception."
- if (script_type_ == ScriptType::kModule) {
+ if (script_type_ == mojom::ScriptType::kModule) {
exception_state.ThrowTypeError(
"Module scripts don't support importScripts().");
return;
@@ -200,10 +201,10 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls,
// importScripts always uses "no-cors", so simply checking the origin is
// enough.
// TODO(yhirano): Remove this ad-hoc logic and use the response type.
- const AccessControlStatus access_control_status =
+ const SanitizeScriptErrors sanitize_script_errors =
execution_context.GetSecurityOrigin()->CanReadContent(response_url)
- ? kSharableCrossOrigin
- : kOpaqueResource;
+ ? SanitizeScriptErrors::kDoNotSanitize
+ : SanitizeScriptErrors::kSanitize;
ErrorEvent* error_event = nullptr;
SingleCachedMetadataHandler* handler(
@@ -214,7 +215,7 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls,
ScriptController()->Evaluate(
ScriptSourceCode(source_code, ScriptSourceLocationType::kUnknown,
handler, response_url),
- access_control_status, &error_event, v8_cache_options_);
+ sanitize_script_errors, &error_event, v8_cache_options_);
if (error_event) {
ScriptController()->RethrowExceptionFromImportedScript(error_event,
exception_state);
@@ -252,8 +253,8 @@ WorkerGlobalScope::LoadScriptFromClassicScriptLoader(
String* out_source_code,
std::unique_ptr<Vector<char>>* out_cached_meta_data) {
ExecutionContext* execution_context = GetExecutionContext();
- scoped_refptr<WorkerClassicScriptLoader> classic_script_loader(
- WorkerClassicScriptLoader::Create());
+ WorkerClassicScriptLoader* classic_script_loader =
+ MakeGarbageCollected<WorkerClassicScriptLoader>();
classic_script_loader->LoadSynchronously(
*execution_context, script_url, mojom::RequestContextType::SCRIPT,
execution_context->GetSecurityContext().AddressSpace());
@@ -316,6 +317,16 @@ ExecutionContext* WorkerGlobalScope::GetExecutionContext() const {
void WorkerGlobalScope::TasksWereUnpaused() {
WorkerOrWorkletGlobalScope::TasksWereUnpaused();
+ // We cannot run the paused tasks right away, as there might be some other
+ // code that still needs to be run synchronously.
+ GetTaskRunner(TaskType::kInternalWorker)
+ ->PostTask(FROM_HERE, WTF::Bind(&WorkerGlobalScope::MaybeRunPausedTasks,
+ WrapWeakPersistent(this)));
+}
+
+void WorkerGlobalScope::MaybeRunPausedTasks() {
+ if (IsContextPaused())
+ return;
Vector<base::OnceClosure> calls;
paused_calls_.swap(calls);
for (auto& call : calls)
@@ -324,26 +335,116 @@ void WorkerGlobalScope::TasksWereUnpaused() {
void WorkerGlobalScope::EvaluateClassicScriptPausable(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id) {
if (IsContextPaused()) {
- AddPausedCall(WTF::Bind(
- &WorkerGlobalScope::EvaluateClassicScriptPausable,
- WrapWeakPersistent(this), script_url, access_control_status,
- source_code, WTF::Passed(std::move(cached_meta_data)), stack_id));
+ AddPausedCall(WTF::Bind(&WorkerGlobalScope::EvaluateClassicScriptPausable,
+ WrapWeakPersistent(this), script_url, source_code,
+ WTF::Passed(std::move(cached_meta_data)),
+ stack_id));
return;
}
ThreadDebugger* debugger = ThreadDebugger::From(GetThread()->GetIsolate());
if (debugger)
debugger->ExternalAsyncTaskStarted(stack_id);
- EvaluateClassicScript(script_url, access_control_status, source_code,
- std::move(cached_meta_data));
+ EvaluateClassicScript(script_url, source_code, std::move(cached_meta_data));
if (debugger)
debugger->ExternalAsyncTaskFinished(stack_id);
}
+// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
+void WorkerGlobalScope::ImportClassicScriptPausable(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+ if (IsContextPaused()) {
+ AddPausedCall(WTF::Bind(&WorkerGlobalScope::ImportClassicScriptPausable,
+ WrapWeakPersistent(this), script_url,
+ WrapPersistent(outside_settings_object), stack_id));
+ return;
+ }
+
+ // Step 12. "Fetch a classic worker script given url, outside settings,
+ // destination, and inside settings."
+ // TODO(nhiroki): Load a main script using |outside_settings_object|.
+ // (https://crbug.com/835717, https://crbug.com/880027)
+
+ // Step 12.1. "Set request's reserved client to inside settings."
+ // The browesr process takes care of this.
+
+ // Step 12.2. "Fetch request, and asynchronously wait to run the remaining
+ // steps as part of fetch's process response for the response response."
+ ExecutionContext* execution_context = GetExecutionContext();
+ WorkerClassicScriptLoader* classic_script_loader =
+ MakeGarbageCollected<WorkerClassicScriptLoader>();
+ classic_script_loader->LoadTopLevelScriptAsynchronously(
+ *execution_context, script_url, mojom::RequestContextType::WORKER,
+ network::mojom::FetchRequestMode::kSameOrigin,
+ network::mojom::FetchCredentialsMode::kSameOrigin,
+ GetSecurityContext().AddressSpace(), IsNestedWorker(),
+ WTF::Bind(&WorkerGlobalScope::DidReceiveResponseForClassicScript,
+ WrapWeakPersistent(this),
+ WrapPersistent(classic_script_loader)),
+ WTF::Bind(&WorkerGlobalScope::DidImportClassicScript,
+ WrapWeakPersistent(this), WrapPersistent(classic_script_loader),
+ stack_id));
+}
+
+void WorkerGlobalScope::DidReceiveResponseForClassicScript(
+ WorkerClassicScriptLoader* classic_script_loader) {
+ DCHECK(IsContextThread());
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+ probe::didReceiveScriptResponse(this, classic_script_loader->Identifier());
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
+void WorkerGlobalScope::DidImportClassicScript(
+ WorkerClassicScriptLoader* classic_script_loader,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ DCHECK(IsContextThread());
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+
+ // Step 12. "If the algorithm asynchronously completes with null, then:"
+ if (classic_script_loader->Failed()) {
+ // Step 12.1. "Queue a task to fire an event named error at worker."
+ // Step 12.2. "Run the environment discarding steps for inside settings."
+ // Step 12.3. "Return."
+ ExceptionThrown(ErrorEvent::Create(
+ "Failed to load a worker script: " + url_.GetString(),
+ SourceLocation::Capture(), nullptr /* world */));
+ return;
+ }
+
+ // Step 12.3. "Set worker global scope's url to response's url."
+ // Step 12.4. "Set worker global scope's HTTPS state to response's HTTPS
+ // state."
+ // These are done in the constructor of WorkerGlobalScope.
+
+ // Step 12.5. "Set worker global scope's referrer policy to the result of
+ // parsing the `Referrer-Policy` header of response."
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
+ if (!classic_script_loader->GetReferrerPolicy().IsNull()) {
+ SecurityPolicy::ReferrerPolicyFromHeaderValue(
+ classic_script_loader->GetReferrerPolicy(),
+ kDoNotSupportReferrerPolicyLegacyKeywords, &referrer_policy);
+ SetReferrerPolicy(referrer_policy);
+ }
+
+ // Step 13.6. "Execute the Initialize a global object's CSP list algorithm
+ // on worker global scope and response. [CSP]"
+ // This is done in the constructor of WorkerGlobalScope.
+
+ // Step 13.7. "Asynchronously complete the perform the fetch steps with
+ // response."
+
+ EvaluateClassicScriptPausable(
+ classic_script_loader->ResponseURL(), classic_script_loader->SourceText(),
+ classic_script_loader->ReleaseCachedMetadata(), stack_id);
+}
+
void WorkerGlobalScope::ImportModuleScriptPausable(
const KURL& module_url_record,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -372,9 +473,9 @@ void WorkerGlobalScope::ReceiveMessagePausable(
debugger->ExternalAsyncTaskStarted(message.sender_stack_trace_id);
UserActivation* user_activation = nullptr;
if (message.user_activation) {
- user_activation =
- new UserActivation(message.user_activation->has_been_active,
- message.user_activation->was_active);
+ user_activation = MakeGarbageCollected<UserActivation>(
+ message.user_activation->has_been_active,
+ message.user_activation->was_active);
}
DispatchEvent(*MessageEvent::Create(ports, std::move(message.message),
user_activation));
@@ -384,7 +485,6 @@ void WorkerGlobalScope::ReceiveMessagePausable(
void WorkerGlobalScope::EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data) {
DCHECK(IsContextThread());
@@ -395,10 +495,12 @@ void WorkerGlobalScope::EvaluateClassicScript(
ReportingProxy().WillEvaluateClassicScript(
source_code.length(),
cached_meta_data.get() ? cached_meta_data->size() : 0);
+ // Cross-origin workers are disallowed, so use
+ // SanitizeScriptErrors::kDoNotSanitize.
bool success = ScriptController()->Evaluate(
- ScriptSourceCode(source_code, ScriptSourceLocationType::kUnknown, handler,
- script_url),
- access_control_status, nullptr /* error_event */, v8_cache_options_);
+ ScriptSourceCode(source_code, handler, script_url),
+ SanitizeScriptErrors::kDoNotSanitize, nullptr /* error_event */,
+ v8_cache_options_);
ReportingProxy().DidEvaluateClassicScript(success);
}
@@ -410,9 +512,11 @@ WorkerGlobalScope::WorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
WorkerThread* thread,
base::TimeTicks time_origin)
- : WorkerOrWorkletGlobalScope(thread->GetIsolate(),
- creation_params->worker_clients,
- thread->GetWorkerReportingProxy()),
+ : WorkerOrWorkletGlobalScope(
+ thread->GetIsolate(),
+ creation_params->worker_clients,
+ std::move(creation_params->web_worker_fetch_context),
+ thread->GetWorkerReportingProxy()),
url_(creation_params->script_url),
script_type_(creation_params->script_type),
user_agent_(creation_params->user_agent),
@@ -448,9 +552,10 @@ WorkerGlobalScope::WorkerGlobalScope(
BindContentSecurityPolicyToExecutionContext();
SetWorkerSettings(std::move(creation_params->worker_settings));
- // For module scripts, referrer policy will be set after the top-level module
+ // Set the referrer policy here for workers whose script is fetched on the
+ // main thread. For off-the-main-thread fetches, it is instead set after the
// script is fetched.
- if (creation_params->script_type == ScriptType::kClassic)
+ if (IsScriptFetchedOnMainThread())
SetReferrerPolicy(creation_params->referrer_policy);
SetAddressSpace(creation_params->address_space);
@@ -530,6 +635,20 @@ void WorkerGlobalScope::SetWorkerSettings(
worker_settings_->GetGenericFontFamilySettings());
}
+bool WorkerGlobalScope::IsScriptFetchedOnMainThread() {
+ if (script_type_ == mojom::ScriptType::kModule)
+ return false;
+ // It's now supported only for dedicated workers to load top-level classic
+ // worker script off the main thread.
+ // TODO(nhiroki): Support loading top-level classic worker script off the main
+ // thread for shared workers and service workers.
+ if (IsDedicatedWorkerGlobalScope() &&
+ RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled()) {
+ return false;
+ }
+ return true;
+}
+
void WorkerGlobalScope::Trace(blink::Visitor* visitor) {
visitor->Trace(location_);
visitor->Trace(navigator_);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h
index 18c26947b21..8b45870c385 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h
@@ -31,6 +31,7 @@
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -38,7 +39,6 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/dom_timer_coordinator.h"
-#include "third_party/blink/renderer/core/frame/dom_window_base64.h"
#include "third_party/blink/renderer/core/messaging/blink_transferable_message.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/workers/worker_animation_frame_provider.h"
@@ -46,6 +46,7 @@
#include "third_party/blink/renderer/core/workers/worker_settings.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace service_manager {
class InterfaceProvider;
@@ -59,6 +60,7 @@ class FetchClientSettingsObjectSnapshot;
class FontFaceSet;
class OffscreenFontSelector;
class V8VoidFunction;
+class WorkerClassicScriptLoader;
class WorkerLocation;
class WorkerNavigator;
class WorkerThread;
@@ -67,8 +69,7 @@ struct GlobalScopeCreationParams;
class CORE_EXPORT WorkerGlobalScope
: public WorkerOrWorkletGlobalScope,
public ActiveScriptWrappable<WorkerGlobalScope>,
- public Supplementable<WorkerGlobalScope>,
- public DOMWindowBase64 {
+ public Supplementable<WorkerGlobalScope> {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(WorkerGlobalScope);
@@ -100,9 +101,9 @@ class CORE_EXPORT WorkerGlobalScope
String origin() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(rejectionhandled);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(unhandledrejection);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(rejectionhandled, kRejectionhandled);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(unhandledrejection, kUnhandledrejection);
// WorkerUtils
virtual void importScripts(const Vector<String>& urls, ExceptionState&);
@@ -140,10 +141,13 @@ class CORE_EXPORT WorkerGlobalScope
// so that WorkerGlobalScope can be paused.
void EvaluateClassicScriptPausable(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id);
+ void ImportClassicScriptPausable(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id);
void ImportModuleScriptPausable(
const KURL& module_url_record,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -169,6 +173,9 @@ class CORE_EXPORT WorkerGlobalScope
return animation_frame_provider_;
}
+ // Returns true when this is a nested worker.
+ virtual bool IsNestedWorker() const { return false; }
+
protected:
WorkerGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
WorkerThread*,
@@ -183,7 +190,6 @@ class CORE_EXPORT WorkerGlobalScope
// Evaluates the given top-level classic script.
virtual void EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data);
@@ -195,11 +201,22 @@ class CORE_EXPORT WorkerGlobalScope
void AddPausedCall(base::OnceClosure closure);
- ScriptType GetScriptType() const { return script_type_; }
+ void MaybeRunPausedTasks();
+
+ mojom::ScriptType GetScriptType() const { return script_type_; }
private:
void SetWorkerSettings(std::unique_ptr<WorkerSettings>);
+ // Returns true if this worker script is supposed to be fetched on the main
+ // thread and passed to the worker thread.
+ bool IsScriptFetchedOnMainThread();
+
+ void DidReceiveResponseForClassicScript(
+ WorkerClassicScriptLoader* classic_script_loader);
+ void DidImportClassicScript(WorkerClassicScriptLoader* classic_script_loader,
+ const v8_inspector::V8StackTraceId& stack_id);
+
// |kNotHandled| is used when the script was not in
// InstalledScriptsManager, which means it was not an installed script.
enum class LoadResult { kSuccess, kFailed, kNotHandled };
@@ -232,7 +249,7 @@ class CORE_EXPORT WorkerGlobalScope
void TasksWereUnpaused() override;
const KURL url_;
- const ScriptType script_type_;
+ const mojom::ScriptType script_type_;
const String user_agent_;
const base::UnguessableToken parent_devtools_token_;
const V8CacheOptions v8_cache_options_;
@@ -264,11 +281,12 @@ class CORE_EXPORT WorkerGlobalScope
Vector<base::OnceClosure> paused_calls_;
};
-DEFINE_TYPE_CASTS(WorkerGlobalScope,
- ExecutionContext,
- context,
- context->IsWorkerGlobalScope(),
- context.IsWorkerGlobalScope());
+template <>
+struct DowncastTraits<WorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsWorkerGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl
index 8ff553b78ca..5926174c80e 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl
+++ b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl
@@ -79,7 +79,6 @@
[RuntimeEnabled=OffscreenCanvasText] readonly attribute FontFaceSet fonts;
};
-WorkerGlobalScope implements WindowBase64;
-WorkerGlobalScope implements WindowTimers;
+WorkerGlobalScope implements WindowOrWorkerGlobalScope;
// TODO(fserb): this needs to be enabled once we get out of RuntimeEnabled.
//WorkerGlobalScope implements FontFaceSource;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc b/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc
deleted file mode 100644
index c06bfa4aa24..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc
+++ /dev/null
@@ -1,164 +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 "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-
-#include "base/location.h"
-#include "third_party/blink/renderer/core/frame/frame_console.h"
-#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
-#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-#include "third_party/blink/renderer/core/inspector/inspector_worker_agent.h"
-#include "third_party/blink/renderer/core/inspector/worker_inspector_controller.h"
-#include "third_party/blink/renderer/core/probe/core_probes.h"
-#include "third_party/blink/renderer/core/workers/execution_context_worker_registry.h"
-#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_thread.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-
-namespace blink {
-
-WorkerInspectorProxy::WorkerInspectorProxy()
- : worker_thread_(nullptr), execution_context_(nullptr) {}
-
-WorkerInspectorProxy* WorkerInspectorProxy::Create() {
- return new WorkerInspectorProxy();
-}
-
-WorkerInspectorProxy::~WorkerInspectorProxy() = default;
-
-const String& WorkerInspectorProxy::InspectorId() {
- if (inspector_id_.IsEmpty() && worker_thread_) {
- inspector_id_ = IdentifiersFactory::IdFromToken(
- worker_thread_->GetDevToolsWorkerToken());
- }
- return inspector_id_;
-}
-
-WorkerInspectorProxy::PauseOnWorkerStart
-WorkerInspectorProxy::ShouldPauseOnWorkerStart(
- ExecutionContext* execution_context) {
- bool result = false;
- probe::shouldWaitForDebuggerOnWorkerStart(execution_context, &result);
- return result ? PauseOnWorkerStart::kPause : PauseOnWorkerStart::kDontPause;
-}
-
-void WorkerInspectorProxy::WorkerThreadCreated(
- ExecutionContext* execution_context,
- WorkerThread* worker_thread,
- const KURL& url) {
- worker_thread_ = worker_thread;
- execution_context_ = execution_context;
- url_ = url.GetString();
- DCHECK(execution_context_);
- ExecutionContextWorkerRegistry::From(*execution_context_)
- ->AddWorkerInspectorProxy(this);
- // We expect everyone starting worker thread to synchronously ask for
- // ShouldPauseOnWorkerStart() right before.
- bool waiting_for_debugger = false;
- probe::shouldWaitForDebuggerOnWorkerStart(execution_context_,
- &waiting_for_debugger);
- probe::didStartWorker(execution_context_, this, waiting_for_debugger);
-}
-
-void WorkerInspectorProxy::WorkerThreadTerminated() {
- if (worker_thread_) {
- ExecutionContextWorkerRegistry::From(*execution_context_)
- ->RemoveWorkerInspectorProxy(this);
- probe::workerTerminated(execution_context_, this);
- }
-
- worker_thread_ = nullptr;
- page_inspectors_.clear();
- execution_context_ = nullptr;
-}
-
-void WorkerInspectorProxy::DispatchMessageFromWorker(int session_id,
- const String& message) {
- auto it = page_inspectors_.find(session_id);
- if (it != page_inspectors_.end())
- it->value->DispatchMessageFromWorker(this, session_id, message);
-}
-
-static void ConnectToWorkerGlobalScopeInspectorTask(WorkerThread* worker_thread,
- int session_id) {
- if (WorkerInspectorController* inspector =
- worker_thread->GetWorkerInspectorController()) {
- inspector->ConnectFrontend(session_id);
- }
-}
-
-void WorkerInspectorProxy::ConnectToInspector(
- int session_id,
- WorkerInspectorProxy::PageInspector* page_inspector) {
- if (!worker_thread_)
- return;
- DCHECK(page_inspectors_.find(session_id) == page_inspectors_.end());
- page_inspectors_.insert(session_id, page_inspector);
- PostCrossThreadTask(
- *worker_thread_->GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
- CrossThreadBind(ConnectToWorkerGlobalScopeInspectorTask,
- CrossThreadUnretained(worker_thread_), session_id));
-}
-
-static void DisconnectFromWorkerGlobalScopeInspectorTask(
- WorkerThread* worker_thread,
- int session_id) {
- if (WorkerInspectorController* inspector =
- worker_thread->GetWorkerInspectorController()) {
- inspector->DisconnectFrontend(session_id);
- }
-}
-
-void WorkerInspectorProxy::DisconnectFromInspector(
- int session_id,
- WorkerInspectorProxy::PageInspector* page_inspector) {
- DCHECK(page_inspectors_.at(session_id) == page_inspector);
- page_inspectors_.erase(session_id);
- if (worker_thread_) {
- PostCrossThreadTask(
- *worker_thread_->GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
- CrossThreadBind(DisconnectFromWorkerGlobalScopeInspectorTask,
- CrossThreadUnretained(worker_thread_), session_id));
- }
-}
-
-static void DispatchOnInspectorBackendTask(int session_id,
- const String& message,
- WorkerThread* worker_thread) {
- if (WorkerInspectorController* inspector =
- worker_thread->GetWorkerInspectorController()) {
- inspector->DispatchMessageFromFrontend(session_id, message);
- }
-}
-
-void WorkerInspectorProxy::SendMessageToInspector(int session_id,
- const String& message) {
- if (!worker_thread_)
- return;
-
- String method;
- protocol::UberDispatcher dispatcher(nullptr);
- dispatcher.parseCommand(protocol::StringUtil::parseJSON(message).get(),
- nullptr, &method);
-
- if (InspectorSession::ShouldInterruptForMethod(method)) {
- worker_thread_->GetInspectorTaskRunner()->AppendTask(
- CrossThreadBind(DispatchOnInspectorBackendTask, session_id, message,
- CrossThreadUnretained(worker_thread_)));
- } else {
- PostCrossThreadTask(
- *worker_thread_->GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
- CrossThreadBind(DispatchOnInspectorBackendTask, session_id, message,
- CrossThreadUnretained(worker_thread_)));
- }
-}
-
-void WorkerInspectorProxy::Trace(blink::Visitor* visitor) {
- visitor->Trace(execution_context_);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h b/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h
deleted file mode 100644
index c7e8848307e..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h
+++ /dev/null
@@ -1,72 +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 THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_INSPECTOR_PROXY_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_INSPECTOR_PROXY_H_
-
-#include "base/macros.h"
-#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/inspector/console_message.h"
-#include "third_party/blink/renderer/core/inspector/thread_debugger.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
-
-namespace blink {
-
-class ExecutionContext;
-class KURL;
-class WorkerThread;
-
-// A proxy for talking to the worker inspector on the worker thread.
-// All of these methods should be called on the main thread.
-class CORE_EXPORT WorkerInspectorProxy final
- : public GarbageCollectedFinalized<WorkerInspectorProxy> {
- public:
- enum class PauseOnWorkerStart { kPause, kDontPause };
-
- static WorkerInspectorProxy* Create();
-
- ~WorkerInspectorProxy();
- void Trace(blink::Visitor*);
-
- class CORE_EXPORT PageInspector {
- public:
- virtual ~PageInspector() = default;
- virtual void DispatchMessageFromWorker(WorkerInspectorProxy*,
- int session_id,
- const String& message) = 0;
- };
-
- // Returns whether WorkerThread should pause to run debugger tasks on its
- // startup.
- PauseOnWorkerStart ShouldPauseOnWorkerStart(ExecutionContext*);
-
- void WorkerThreadCreated(ExecutionContext*, WorkerThread*, const KURL&);
- void WorkerThreadTerminated();
- void DispatchMessageFromWorker(int session_id, const String&);
-
- void ConnectToInspector(int session_id,
- PageInspector*);
- void DisconnectFromInspector(int session_id, PageInspector*);
- void SendMessageToInspector(int session_id, const String& message);
-
- const String& Url() { return url_; }
- ExecutionContext* GetExecutionContext() { return execution_context_; }
- const String& InspectorId();
- WorkerThread* GetWorkerThread() { return worker_thread_; }
-
- private:
- WorkerInspectorProxy();
-
- WorkerThread* worker_thread_;
- Member<ExecutionContext> execution_context_;
- HashMap<int, PageInspector*> page_inspectors_;
- String url_;
- String inspector_id_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_INSPECTOR_PROXY_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_location.h b/chromium/third_party/blink/renderer/core/workers/worker_location.h
index 942fe74a499..d6918b61fb1 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_location.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_location.h
@@ -40,9 +40,11 @@ class WorkerLocation final : public ScriptWrappable,
public:
static WorkerLocation* Create(const KURL& url) {
- return new WorkerLocation(url);
+ return MakeGarbageCollected<WorkerLocation>(url);
}
+ explicit WorkerLocation(const KURL& url) : url_(url) {}
+
KURL Url() const override { return url_; }
String Input() const override {
NOTREACHED();
@@ -50,8 +52,6 @@ class WorkerLocation final : public ScriptWrappable,
}
private:
- explicit WorkerLocation(const KURL& url) : url_(url) {}
-
KURL url_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_location.idl b/chromium/third_party/blink/renderer/core/workers/worker_location.idl
index e271597c274..ffdf2ecdf30 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_location.idl
+++ b/chromium/third_party/blink/renderer/core/workers/worker_location.idl
@@ -31,6 +31,14 @@
[
Exposed=Worker
] interface WorkerLocation {
+ stringifier readonly attribute USVString href;
+ readonly attribute USVString origin;
+ readonly attribute USVString protocol;
+ readonly attribute USVString host;
+ readonly attribute USVString hostname;
+ readonly attribute USVString port;
+ readonly attribute USVString pathname;
+ readonly attribute USVString search;
+ readonly attribute USVString hash;
};
-WorkerLocation implements URLUtilsReadOnly;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc b/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc
index 1a6a79224a6..c68d2f9e8a7 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc
@@ -24,7 +24,7 @@ void WorkerModuleTreeClient::NotifyModuleTreeLoadFinished(
auto* execution_context =
ExecutionContext::From(modulator_->GetScriptState());
blink::WorkerReportingProxy& worker_reporting_proxy =
- ToWorkerGlobalScope(execution_context)->ReportingProxy();
+ To<WorkerGlobalScope>(execution_context)->ReportingProxy();
if (!module_script) {
// Step 12: "If the algorithm asynchronously completes with null, queue
@@ -41,6 +41,9 @@ void WorkerModuleTreeClient::NotifyModuleTreeLoadFinished(
// asynchronous completion, with script being the asynchronous completion
// value."
worker_reporting_proxy.WillEvaluateModuleScript();
+ // This |error| is always null because the second argument is |kReport|.
+ // TODO(nhiroki): Catch an error when an evaluation error happens.
+ // (https://crbug.com/680046)
ScriptValue error = modulator_->ExecuteModule(
module_script, Modulator::CaptureEvalErrorFlag::kReport);
worker_reporting_proxy.DidEvaluateModuleScript(error.IsEmpty());
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_navigator.h b/chromium/third_party/blink/renderer/core/workers/worker_navigator.h
index 203f006ce40..376f5995f97 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_navigator.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_navigator.h
@@ -50,8 +50,10 @@ class CORE_EXPORT WorkerNavigator final
public:
static WorkerNavigator* Create(const String& user_agent) {
- return new WorkerNavigator(user_agent);
+ return MakeGarbageCollected<WorkerNavigator>(user_agent);
}
+
+ explicit WorkerNavigator(const String&);
~WorkerNavigator() override;
String userAgent() const override;
@@ -59,8 +61,6 @@ class CORE_EXPORT WorkerNavigator final
void Trace(blink::Visitor*) override;
private:
- explicit WorkerNavigator(const String&);
-
String user_agent_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc
index 5a0ccabbfa2..4189e13ae0a 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc
@@ -5,13 +5,16 @@
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/dom/events/event_queue.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_script_fetch_request.h"
+#include "third_party/blink/renderer/core/loader/subresource_filter.h"
#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
@@ -23,8 +26,11 @@ namespace blink {
WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(
v8::Isolate* isolate,
WorkerClients* worker_clients,
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context,
WorkerReportingProxy& reporting_proxy)
- : worker_clients_(worker_clients),
+ : ExecutionContext(isolate),
+ worker_clients_(worker_clients),
+ web_worker_fetch_context_(std::move(web_worker_fetch_context)),
script_controller_(
WorkerOrWorkletScriptController::Create(this, isolate)),
reporting_proxy_(reporting_proxy),
@@ -93,22 +99,57 @@ void WorkerOrWorkletGlobalScope::CountDeprecation(WebFeature feature) {
ReportingProxy().CountDeprecation(feature);
}
+void WorkerOrWorkletGlobalScope::InitializeWebFetchContextIfNeeded() {
+ if (web_fetch_context_initialized_)
+ return;
+ web_fetch_context_initialized_ = true;
+
+ if (!web_worker_fetch_context_)
+ return;
+
+ DCHECK(!subresource_filter_);
+ web_worker_fetch_context_->InitializeOnWorkerThread();
+ std::unique_ptr<blink::WebDocumentSubresourceFilter> web_filter =
+ web_worker_fetch_context_->TakeSubresourceFilter();
+ if (web_filter) {
+ subresource_filter_ =
+ SubresourceFilter::Create(*this, std::move(web_filter));
+ }
+}
+
ResourceFetcher* WorkerOrWorkletGlobalScope::EnsureFetcher() {
DCHECK(IsContextThread());
- if (resource_fetcher_)
- return resource_fetcher_;
- WorkerFetchContext* fetch_context = WorkerFetchContext::Create(*this);
- resource_fetcher_ = ResourceFetcher::Create(fetch_context);
+ if (inside_settings_resource_fetcher_)
+ return inside_settings_resource_fetcher_;
+ inside_settings_resource_fetcher_ = CreateFetcherInternal(
+ MakeGarbageCollected<FetchClientSettingsObjectImpl>(*this));
+ return inside_settings_resource_fetcher_;
+}
+
+ResourceFetcher* WorkerOrWorkletGlobalScope::CreateFetcherInternal(
+ FetchClientSettingsObject* fetch_client_settings_object) {
+ DCHECK(IsContextThread());
+ InitializeWebFetchContextIfNeeded();
+ WorkerFetchContext* fetch_context = WorkerFetchContext::Create(
+ *this, web_worker_fetch_context_, subresource_filter_,
+ fetch_client_settings_object);
+ ResourceFetcher* resource_fetcher = ResourceFetcher::Create(fetch_context);
if (IsContextPaused())
- resource_fetcher_->SetDefersLoading(true);
- DCHECK(resource_fetcher_);
- return resource_fetcher_;
+ resource_fetcher->SetDefersLoading(true);
+ resource_fetchers_.insert(resource_fetcher);
+ return resource_fetcher;
}
ResourceFetcher* WorkerOrWorkletGlobalScope::Fetcher() const {
DCHECK(IsContextThread());
- DCHECK(resource_fetcher_);
- return resource_fetcher_;
+ DCHECK(inside_settings_resource_fetcher_);
+ return inside_settings_resource_fetcher_;
+}
+
+ResourceFetcher* WorkerOrWorkletGlobalScope::CreateOutsideSettingsFetcher(
+ FetchClientSettingsObject* fetch_client_settings_object) {
+ DCHECK(IsContextThread());
+ return CreateFetcherInternal(fetch_client_settings_object);
}
bool WorkerOrWorkletGlobalScope::IsJSExecutionForbidden() const {
@@ -132,9 +173,9 @@ void WorkerOrWorkletGlobalScope::Dispose() {
script_controller_->Dispose();
script_controller_.Clear();
- if (resource_fetcher_) {
- resource_fetcher_->StopFetching();
- resource_fetcher_->ClearContext();
+ for (ResourceFetcher* resource_fetcher : resource_fetchers_) {
+ resource_fetcher->StopFetching();
+ resource_fetcher->ClearContext();
}
}
@@ -192,7 +233,7 @@ void WorkerOrWorkletGlobalScope::FetchModuleScript(
// string."
ScriptFetchOptions options(nonce, IntegrityMetadataSet(), integrity_attribute,
parser_state, credentials_mode,
- kReferrerPolicyDefault);
+ network::mojom::ReferrerPolicy::kDefault);
Modulator* modulator = Modulator::From(ScriptController()->GetScriptState());
// Step 3. "Perform the internal module script graph fetching procedure ..."
@@ -202,18 +243,20 @@ void WorkerOrWorkletGlobalScope::FetchModuleScript(
void WorkerOrWorkletGlobalScope::TasksWerePaused() {
ExecutionContext::TasksWerePaused();
- if (resource_fetcher_)
- resource_fetcher_->SetDefersLoading(true);
+ for (ResourceFetcher* resource_fetcher : resource_fetchers_)
+ resource_fetcher->SetDefersLoading(true);
}
void WorkerOrWorkletGlobalScope::TasksWereUnpaused() {
ExecutionContext::TasksWereUnpaused();
- if (resource_fetcher_)
- resource_fetcher_->SetDefersLoading(false);
+ for (ResourceFetcher* resource_fetcher : resource_fetchers_)
+ resource_fetcher->SetDefersLoading(false);
}
void WorkerOrWorkletGlobalScope::Trace(blink::Visitor* visitor) {
- visitor->Trace(resource_fetcher_);
+ visitor->Trace(inside_settings_resource_fetcher_);
+ visitor->Trace(resource_fetchers_);
+ visitor->Trace(subresource_filter_);
visitor->Trace(script_controller_);
visitor->Trace(modulator_);
EventTargetWithInlineData::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h
index afc993d8520..83c26870289 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h
@@ -9,6 +9,7 @@
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
+#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/execution_context/security_context.h"
@@ -22,10 +23,13 @@
namespace blink {
+class FetchClientSettingsObject;
class FetchClientSettingsObjectSnapshot;
class Modulator;
class ModuleTreeClient;
class ResourceFetcher;
+class SubresourceFilter;
+class WebWorkerFetchContext;
class WorkerOrWorkletScriptController;
class WorkerReportingProxy;
class WorkerThread;
@@ -39,6 +43,7 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
WorkerOrWorkletGlobalScope(v8::Isolate*,
WorkerClients*,
+ scoped_refptr<WebWorkerFetchContext>,
WorkerReportingProxy&);
~WorkerOrWorkletGlobalScope() override;
@@ -89,6 +94,17 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
ResourceFetcher* Fetcher() const override;
ResourceFetcher* EnsureFetcher();
+ // ResourceFetcher for off-the-main-thread worker top-level script fetching,
+ // corresponding to "outside" fetch client's settings object.
+ // CreateOutsideSettingsFetcher() is called for each invocation of top-level
+ // script fetch, which can occur multiple times in worklets.
+ // TODO(hiroshige, nhiroki): Currently this outside ResourceFetcher and its
+ // WorkerFetchContext is mostly the copy of the insideSettings
+ // ResourceFetcher, and have dependencies to WorkerOrWorkletGlobalScope. Plumb
+ // more data to the outside ResourceFetcher to fix the behavior and reduce the
+ // dependencies.
+ ResourceFetcher* CreateOutsideSettingsFetcher(FetchClientSettingsObject*);
+
WorkerClients* Clients() const { return worker_clients_.Get(); }
WorkerOrWorkletScriptController* ScriptController() {
@@ -119,8 +135,34 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
void TasksWereUnpaused() override;
private:
+ void InitializeWebFetchContextIfNeeded();
+ ResourceFetcher* CreateFetcherInternal(FetchClientSettingsObject*);
+
+ bool web_fetch_context_initialized_ = false;
+
CrossThreadPersistent<WorkerClients> worker_clients_;
- Member<ResourceFetcher> resource_fetcher_;
+
+ Member<ResourceFetcher> inside_settings_resource_fetcher_;
+
+ // Keeps track of all ResourceFetchers (including
+ // |inside_settings_resource_fetcher_|) for disposing and pausing/unpausing.
+ HeapHashSet<WeakMember<ResourceFetcher>> resource_fetchers_;
+
+ // A WorkerOrWorkletGlobalScope has one WebWorkerFetchContext and one
+ // corresponding SubresourceFilter, which are shared by all
+ // WorkerFetchContexts of |this| global scope, i.e. those behind
+ // ResourceFetchers created by EnsureFetcher() and
+ // CreateOutsideSettingsFetcher().
+ // As all references to |web_worker_fetch_context_| are on the context
+ // thread, |web_worker_fetch_context_| is destructed on the context
+ // thread.
+ //
+ // TODO(crbug/903579): Consider putting WebWorkerFetchContext-originated
+ // things at a single place. Currently they are placed here and subclasses of
+ // WebWorkerFetchContext.
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context_;
+ Member<SubresourceFilter> subresource_filter_;
+
Member<WorkerOrWorkletScriptController> script_controller_;
WorkerReportingProxy& reporting_proxy_;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h b/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h
index c801c3efe45..c4a1f1c8adb 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h
@@ -60,7 +60,6 @@ class CORE_EXPORT WorkerReportingProxy {
MessageLevel,
const String& message,
SourceLocation*) {}
- virtual void PostMessageToPageInspector(int session_id, const String&) {}
// Invoked when the new WorkerGlobalScope is created on
// WorkerThread::InitializeOnWorkerThread.
@@ -76,6 +75,14 @@ class CORE_EXPORT WorkerReportingProxy {
// via ResourceLoader. Called before WillEvaluateClassicScript().
virtual void DidLoadInstalledScript() {}
+ // Invoked when it's failed to load the worker's main script from
+ // InstalledScriptsManager.
+ virtual void DidFailToLoadInstalledClassicScript() {}
+
+ // Invoked on failure to fetch the worker's module script (either from network
+ // or InstalledScriptsManager).
+ virtual void DidFailToFetchModuleScript() {}
+
// Invoked when the main classic script is about to be evaluated.
virtual void WillEvaluateClassicScript(size_t script_size,
size_t cached_metadata_size) {}
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread.cc b/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
index a231d079da2..dfe382cdefb 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
@@ -36,6 +36,7 @@
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/inspector/console_message_storage.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/inspector/worker_inspector_controller.h"
#include "third_party/blink/renderer/core/inspector/worker_thread_debugger.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
@@ -50,8 +51,8 @@
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
@@ -107,19 +108,6 @@ class WorkerThread::RefCountedWaitableEvent
DISALLOW_COPY_AND_ASSIGN(RefCountedWaitableEvent);
};
-WorkerThread::ScopedDebuggerTask::ScopedDebuggerTask(WorkerThread* thread)
- : thread_(thread) {
- MutexLocker lock(thread_->mutex_);
- DCHECK(thread_->IsCurrentThread());
- thread_->debugger_task_counter_++;
-}
-
-WorkerThread::ScopedDebuggerTask::~ScopedDebuggerTask() {
- MutexLocker lock(thread_->mutex_);
- DCHECK(thread_->IsCurrentThread());
- thread_->debugger_task_counter_--;
-}
-
WorkerThread::~WorkerThread() {
MutexLocker lock(ThreadSetMutex());
DCHECK(WorkerThreads().Contains(this));
@@ -136,12 +124,13 @@ WorkerThread::~WorkerThread() {
void WorkerThread::Start(
std::unique_ptr<GlobalScopeCreationParams> global_scope_creation_params,
const base::Optional<WorkerBackingThreadStartupData>& thread_startup_data,
- WorkerInspectorProxy::PauseOnWorkerStart pause_on_start,
+ std::unique_ptr<WorkerDevToolsParams> devtools_params,
ParentExecutionContextTaskRunners* parent_execution_context_task_runners) {
DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
DCHECK(!parent_execution_context_task_runners_);
parent_execution_context_task_runners_ =
parent_execution_context_task_runners;
+ devtools_worker_token_ = devtools_params->devtools_worker_token;
// Synchronously initialize the per-global-scope scheduler to prevent someone
// from posting a task to the thread before the scheduler is ready.
@@ -158,15 +147,14 @@ void WorkerThread::Start(
GetWorkerBackingThread().BackingThread().PostTask(
FROM_HERE,
- CrossThreadBind(&WorkerThread::InitializeOnWorkerThread,
- CrossThreadUnretained(this),
- WTF::Passed(std::move(global_scope_creation_params)),
- thread_startup_data, pause_on_start));
+ CrossThreadBind(
+ &WorkerThread::InitializeOnWorkerThread, CrossThreadUnretained(this),
+ WTF::Passed(std::move(global_scope_creation_params)),
+ thread_startup_data, WTF::Passed(std::move(devtools_params))));
}
void WorkerThread::EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
const String& source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id) {
@@ -174,11 +162,23 @@ void WorkerThread::EvaluateClassicScript(
PostCrossThreadTask(
*GetTaskRunner(TaskType::kInternalWorker), FROM_HERE,
CrossThreadBind(&WorkerThread::EvaluateClassicScriptOnWorkerThread,
- CrossThreadUnretained(this), script_url,
- access_control_status, source_code,
+ CrossThreadUnretained(this), script_url, source_code,
WTF::Passed(std::move(cached_meta_data)), stack_id));
}
+void WorkerThread::ImportClassicScript(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
+ PostCrossThreadTask(
+ *GetTaskRunner(TaskType::kInternalWorker), FROM_HERE,
+ CrossThreadBind(&WorkerThread::ImportClassicScriptOnWorkerThread,
+ CrossThreadUnretained(this), script_url,
+ WTF::Passed(outside_settings_object->CopyData()),
+ stack_id));
+}
+
void WorkerThread::ImportModuleScript(
const KURL& script_url,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -243,14 +243,14 @@ void WorkerThread::TerminateAllWorkersForTesting() {
thread->ClearWorkerBackingThread();
}
-void WorkerThread::WillProcessTask() {
+void WorkerThread::WillProcessTask(const base::PendingTask& pending_task) {
DCHECK(IsCurrentThread());
// No tasks should get executed after we have closed.
DCHECK(!GlobalScope()->IsClosing());
}
-void WorkerThread::DidProcessTask() {
+void WorkerThread::DidProcessTask(const base::PendingTask& pending_task) {
DCHECK(IsCurrentThread());
Microtask::PerformCheckpoint(GetIsolate());
GlobalScope()->ScriptController()->GetRejectedPromises()->ProcessQueue();
@@ -275,9 +275,16 @@ bool WorkerThread::IsCurrentThread() {
return GetWorkerBackingThread().BackingThread().IsCurrentThread();
}
-InspectorTaskRunner* WorkerThread::GetInspectorTaskRunner() {
- DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
- return inspector_task_runner_.get();
+void WorkerThread::DebuggerTaskStarted() {
+ MutexLocker lock(mutex_);
+ DCHECK(IsCurrentThread());
+ debugger_task_counter_++;
+}
+
+void WorkerThread::DebuggerTaskFinished() {
+ MutexLocker lock(mutex_);
+ DCHECK(IsCurrentThread());
+ debugger_task_counter_--;
}
WorkerOrWorkletGlobalScope* WorkerThread::GlobalScope() {
@@ -358,7 +365,6 @@ WorkerThread::WorkerThread(WorkerReportingProxy& worker_reporting_proxy)
: time_origin_(CurrentTimeTicks()),
worker_thread_id_(GetNextWorkerThreadId()),
forcible_termination_delay_(kForcibleTerminationDelay),
- devtools_worker_token_(base::UnguessableToken::Create()),
worker_reporting_proxy_(worker_reporting_proxy),
shutdown_event_(RefCountedWaitableEvent::Create()) {
MutexLocker lock(ThreadSetMutex());
@@ -414,20 +420,20 @@ void WorkerThread::InitializeSchedulerOnWorkerThread(
base::WaitableEvent* waitable_event) {
DCHECK(IsCurrentThread());
DCHECK(!worker_scheduler_);
- scheduler::WebThreadImplForWorkerScheduler& web_thread_for_worker =
- static_cast<scheduler::WebThreadImplForWorkerScheduler&>(
+ scheduler::WorkerThread& worker_thread =
+ static_cast<scheduler::WorkerThread&>(
GetWorkerBackingThread().BackingThread().PlatformThread());
worker_scheduler_ = std::make_unique<scheduler::WorkerScheduler>(
static_cast<scheduler::WorkerThreadScheduler*>(
- web_thread_for_worker.GetNonMainThreadScheduler()),
- web_thread_for_worker.worker_scheduler_proxy());
+ worker_thread.GetNonMainThreadScheduler()),
+ worker_thread.worker_scheduler_proxy());
waitable_event->Signal();
}
void WorkerThread::InitializeOnWorkerThread(
std::unique_ptr<GlobalScopeCreationParams> global_scope_creation_params,
const base::Optional<WorkerBackingThreadStartupData>& thread_startup_data,
- WorkerInspectorProxy::PauseOnWorkerStart pause_on_start) {
+ std::unique_ptr<WorkerDevToolsParams> devtools_params) {
DCHECK(IsCurrentThread());
{
MutexLocker lock(mutex_);
@@ -447,7 +453,9 @@ void WorkerThread::InitializeOnWorkerThread(
global_scope_ =
CreateWorkerGlobalScope(std::move(global_scope_creation_params));
worker_reporting_proxy_.DidCreateWorkerGlobalScope(GlobalScope());
- worker_inspector_controller_ = WorkerInspectorController::Create(this);
+
+ worker_inspector_controller_ = WorkerInspectorController::Create(
+ this, inspector_task_runner_, std::move(devtools_params));
// Since context initialization below may fail, we should notify debugger
// about the new worker thread separately, so that it can resolve it by id
@@ -483,25 +491,32 @@ void WorkerThread::InitializeOnWorkerThread(
// Otherwise, InspectorTaskRunner might interrupt isolate execution
// from another thread and try to resume "pause on start" before
// we even paused.
- if (pause_on_start == WorkerInspectorProxy::PauseOnWorkerStart::kPause) {
- WorkerThreadDebugger* debugger = WorkerThreadDebugger::From(GetIsolate());
- if (debugger)
- debugger->PauseWorkerOnStart(this);
- }
+ worker_inspector_controller_->WaitForDebuggerIfNeeded();
}
void WorkerThread::EvaluateClassicScriptOnWorkerThread(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id) {
- ToWorkerGlobalScope(GlobalScope())
- ->EvaluateClassicScriptPausable(script_url, access_control_status,
- std::move(source_code),
+ To<WorkerGlobalScope>(GlobalScope())
+ ->EvaluateClassicScriptPausable(script_url, std::move(source_code),
std::move(cached_meta_data), stack_id);
}
+void WorkerThread::ImportClassicScriptOnWorkerThread(
+ const KURL& script_url,
+ std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
+ outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ To<WorkerGlobalScope>(GlobalScope())
+ ->ImportClassicScriptPausable(
+ script_url,
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ std::move(outside_settings_object)),
+ stack_id);
+}
+
void WorkerThread::ImportModuleScriptOnWorkerThread(
const KURL& script_url,
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
@@ -510,11 +525,12 @@ void WorkerThread::ImportModuleScriptOnWorkerThread(
// Worklets have a different code path to import module scripts.
// TODO(nhiroki): Consider excluding this code path from WorkerThread like
// Worklets.
- ToWorkerGlobalScope(GlobalScope())
- ->ImportModuleScriptPausable(script_url,
- new FetchClientSettingsObjectSnapshot(
- std::move(outside_settings_object)),
- credentials_mode);
+ To<WorkerGlobalScope>(GlobalScope())
+ ->ImportModuleScriptPausable(
+ script_url,
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ std::move(outside_settings_object)),
+ credentials_mode);
}
void WorkerThread::PrepareForShutdownOnWorkerThread() {
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread.h b/chromium/third_party/blink/renderer/core/workers/worker_thread.h
index 36e197428fd..a7a03d2f5cd 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread.h
@@ -41,11 +41,10 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
@@ -63,6 +62,7 @@ class WorkerOrWorkletGlobalScope;
class WorkerReportingProxy;
struct CrossThreadFetchClientSettingsObjectData;
struct GlobalScopeCreationParams;
+struct WorkerDevToolsParams;
// WorkerThread is a kind of WorkerBackingThread client. Each worker mechanism
// can access the lower thread infrastructure via an implementation of this
@@ -101,17 +101,23 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
// (https://crbug.com/710364)
void Start(std::unique_ptr<GlobalScopeCreationParams>,
const base::Optional<WorkerBackingThreadStartupData>&,
- WorkerInspectorProxy::PauseOnWorkerStart,
+ std::unique_ptr<WorkerDevToolsParams>,
ParentExecutionContextTaskRunners*);
// Posts a task to evaluate a top-level classic script on the worker thread.
// Called on the main thread after Start().
void EvaluateClassicScript(const KURL& script_url,
- AccessControlStatus access_control_status,
const String& source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id);
+ // Posts a task to import a top-level classic script on the worker thread.
+ // Called on the main thread after start().
+ void ImportClassicScript(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id);
+
// Posts a task to import a top-level module script on the worker thread.
// Called on the main thread after start().
void ImportModuleScript(
@@ -140,8 +146,8 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
static void TerminateAllWorkersForTesting();
// Thread::TaskObserver.
- void WillProcessTask() override;
- void DidProcessTask() override;
+ void WillProcessTask(const base::PendingTask&) override;
+ void DidProcessTask(const base::PendingTask&) override;
virtual WorkerBackingThread& GetWorkerBackingThread() = 0;
virtual void ClearWorkerBackingThread() = 0;
@@ -156,19 +162,9 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
return worker_reporting_proxy_;
}
- // Only constructible on the main thread.
- class CORE_EXPORT ScopedDebuggerTask {
- STACK_ALLOCATED();
-
- public:
- explicit ScopedDebuggerTask(WorkerThread*);
- ~ScopedDebuggerTask();
-
- private:
- WorkerThread* thread_;
- DISALLOW_COPY_AND_ASSIGN(ScopedDebuggerTask);
- };
- InspectorTaskRunner* GetInspectorTaskRunner();
+ // Only callable on the parent thread.
+ void DebuggerTaskStarted();
+ void DebuggerTaskFinished();
// Callable on both the main thread and the worker thread.
const base::UnguessableToken& GetDevToolsWorkerToken() const {
@@ -290,14 +286,18 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
void InitializeOnWorkerThread(
std::unique_ptr<GlobalScopeCreationParams>,
const base::Optional<WorkerBackingThreadStartupData>&,
- WorkerInspectorProxy::PauseOnWorkerStart) LOCKS_EXCLUDED(mutex_);
+ std::unique_ptr<WorkerDevToolsParams>) LOCKS_EXCLUDED(mutex_);
void EvaluateClassicScriptOnWorkerThread(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id);
+ void ImportClassicScriptOnWorkerThread(
+ const KURL& script_url,
+ std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
+ outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id);
void ImportModuleScriptOnWorkerThread(
const KURL& script_url,
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
@@ -325,7 +325,7 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
TimeDelta forcible_termination_delay_;
scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
- const base::UnguessableToken devtools_worker_token_;
+ base::UnguessableToken devtools_worker_token_;
int debugger_task_counter_ GUARDED_BY(mutex_) = 0;
WorkerReportingProxy& worker_reporting_proxy_;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc b/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc
index 4c9c29a7ba5..05edaaf7074 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
@@ -65,8 +66,9 @@ void WaitForSignalTask(WorkerThread* worker_thread,
*worker_thread->GetParentExecutionContextTaskRunners()->Get(
TaskType::kInternalTest),
FROM_HERE, CrossThreadBind(&test::ExitRunLoop));
- WorkerThread::ScopedDebuggerTask debugger_task(worker_thread);
+ worker_thread->DebuggerTaskStarted();
waitable_event->Wait();
+ worker_thread->DebuggerTaskFinished();
}
void TerminateParentOfNestedWorker(WorkerThread* parent_thread,
@@ -387,8 +389,9 @@ TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) {
auto global_scope_creation_params =
std::make_unique<GlobalScopeCreationParams>(
- KURL("http://fake.url/"), ScriptType::kClassic, "fake user agent",
- headers, kReferrerPolicyDefault, security_origin_.get(),
+ KURL("http://fake.url/"), mojom::ScriptType::kClassic,
+ "fake user agent", nullptr /* web_worker_fetch_context */, headers,
+ network::mojom::ReferrerPolicy::kDefault, security_origin_.get(),
false /* starter_secure_context */,
CalculateHttpsState(security_origin_.get()), WorkerClients::Create(),
mojom::IPAddressSpace::kLocal, nullptr /* originTrialToken */,
@@ -396,11 +399,14 @@ TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) {
std::make_unique<WorkerSettings>(Settings::Create().get()),
kV8CacheOptionsDefault, nullptr /* worklet_module_responses_map */);
- // Specify PauseOnWorkerStart::kPause so that the worker thread can pause
+ // Set wait_for_debugger so that the worker thread can pause
// on initialization to run debugger tasks.
+ auto devtools_params = std::make_unique<WorkerDevToolsParams>();
+ devtools_params->wait_for_debugger = true;
+
worker_thread_->Start(std::move(global_scope_creation_params),
WorkerBackingThreadStartupData::CreateDefault(),
- WorkerInspectorProxy::PauseOnWorkerStart::kPause,
+ std::move(devtools_params),
ParentExecutionContextTaskRunners::Create());
// Used to wait for worker thread termination in a debugger task on the
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h b/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h
index b7a8348fb4f..590fb8729f1 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h
@@ -16,6 +16,7 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
@@ -27,7 +28,6 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
@@ -53,7 +53,7 @@ class FakeWorkerGlobalScope : public WorkerGlobalScope {
// EventTarget
const AtomicString& InterfaceName() const override {
- return EventTargetNames::DedicatedWorkerGlobalScope;
+ return event_target_names::kDedicatedWorkerGlobalScope;
}
// WorkerGlobalScope
@@ -91,8 +91,9 @@ class WorkerThreadForTest : public WorkerThread {
Vector<CSPHeaderAndType> headers{
{"contentSecurityPolicy", kContentSecurityPolicyHeaderTypeReport}};
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- script_url, ScriptType::kClassic, "fake user agent", headers,
- kReferrerPolicyDefault, security_origin,
+ script_url, mojom::ScriptType::kClassic, "fake user agent",
+ nullptr /* web_worker_fetch_context */, headers,
+ network::mojom::ReferrerPolicy::kDefault, security_origin,
false /* starter_secure_context */,
CalculateHttpsState(security_origin), worker_clients,
mojom::IPAddressSpace::kLocal, nullptr,
@@ -102,10 +103,9 @@ class WorkerThreadForTest : public WorkerThread {
Start(std::move(creation_params),
WorkerBackingThreadStartupData::CreateDefault(),
- WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
+ std::make_unique<WorkerDevToolsParams>(),
parent_execution_context_task_runners);
- EvaluateClassicScript(script_url, kOpaqueResource, source,
- nullptr /* cached_meta_data */,
+ EvaluateClassicScript(script_url, source, nullptr /* cached_meta_data */,
v8_inspector::V8StackTraceId());
}
@@ -120,7 +120,8 @@ class WorkerThreadForTest : public WorkerThread {
protected:
WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) override {
- return new FakeWorkerGlobalScope(std::move(creation_params), this);
+ return MakeGarbageCollected<FakeWorkerGlobalScope>(
+ std::move(creation_params), this);
}
private:
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet.cc b/chromium/third_party/blink/renderer/core/workers/worklet.cc
index 0e1999187fb..0739eea7373 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet.cc
@@ -37,7 +37,7 @@ Worklet::~Worklet() {
// https://drafts.css-houdini.org/worklets/#dom-worklet-addmodule
ScriptPromise Worklet::addModule(ScriptState* script_state,
const String& module_url,
- const WorkletOptions& options) {
+ const WorkletOptions* options) {
DCHECK(IsMainThread());
if (!GetExecutionContext()) {
return ScriptPromise::RejectWithDOMException(
@@ -67,7 +67,8 @@ ScriptPromise Worklet::addModule(ScriptState* script_state,
return promise;
}
- WorkletPendingTasks* pending_tasks = new WorkletPendingTasks(this, resolver);
+ WorkletPendingTasks* pending_tasks =
+ MakeGarbageCollected<WorkletPendingTasks>(this, resolver);
pending_tasks_set_.insert(pending_tasks);
// Step 5: "Return promise, and then continue running this algorithm in
@@ -78,7 +79,7 @@ ScriptPromise Worklet::addModule(ScriptState* script_state,
->GetTaskRunner(TaskType::kInternalLoading)
->PostTask(FROM_HERE,
WTF::Bind(&Worklet::FetchAndInvokeScript, WrapPersistent(this),
- module_url_record, options.credentials(),
+ module_url_record, options->credentials(),
WrapPersistent(pending_tasks)));
return promise;
}
@@ -164,7 +165,7 @@ void Worklet::FetchAndInvokeScript(const KURL& module_url_record,
}
}
-size_t Worklet::SelectGlobalScope() {
+wtf_size_t Worklet::SelectGlobalScope() {
DCHECK_EQ(GetNumberOfGlobalScopes(), 1u);
return 0u;
}
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet.h b/chromium/third_party/blink/renderer/core/workers/worklet.h
index 696843c15d5..1fe048cb334 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet.h
@@ -38,7 +38,7 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
// addModule() imports ES6 module scripts.
ScriptPromise addModule(ScriptState*,
const String& module_url,
- const WorkletOptions&);
+ const WorkletOptions*);
// ContextLifecycleObserver
void ContextDestroyed(ExecutionContext*) override;
@@ -58,12 +58,18 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
// Returns one of available global scopes.
WorkletGlobalScopeProxy* FindAvailableGlobalScope();
- size_t GetNumberOfGlobalScopes() const { return proxies_.size(); }
+ wtf_size_t GetNumberOfGlobalScopes() const { return proxies_.size(); }
WorkletModuleResponsesMap* ModuleResponsesMap() const {
return module_responses_map_.Get();
}
+ // "A Worklet has a list of the worklet's WorkletGlobalScopes. Initially this
+ // list is empty; it is populated when the user agent chooses to create its
+ // WorkletGlobalScope."
+ // https://drafts.css-houdini.org/worklets/#worklet-section
+ HeapVector<Member<WorkletGlobalScopeProxy>> proxies_;
+
private:
virtual void FetchAndInvokeScript(const KURL& module_url_record,
const String& credentials,
@@ -79,14 +85,7 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
// there are multiple global scopes, this function MUST be overriden. The
// default behavior is to return the global scope at index 0, which is for the
// case where there is only one global scope.
- virtual size_t SelectGlobalScope();
-
- // "A Worklet has a list of the worklet's WorkletGlobalScopes. Initially this
- // list is empty; it is populated when the user agent chooses to create its
- // WorkletGlobalScope."
- // https://drafts.css-houdini.org/worklets/#worklet-section
- HeapVector<Member<WorkletGlobalScopeProxy>> proxies_;
-
+ virtual wtf_size_t SelectGlobalScope();
// "A Worklet has a module responses map. This is a ordered map of module URLs
// to values that are a fetch responses. The map's entries are ordered based
// on their insertion order. Access to this map should be thread-safe."
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc
index fb879e45a87..88da265e145 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc
@@ -61,9 +61,11 @@ WorkletGlobalScope::WorkletGlobalScope(
ThreadType thread_type,
LocalFrame* frame,
WorkerThread* worker_thread)
- : WorkerOrWorkletGlobalScope(isolate,
- creation_params->worker_clients,
- reporting_proxy),
+ : WorkerOrWorkletGlobalScope(
+ isolate,
+ creation_params->worker_clients,
+ std::move(creation_params->web_worker_fetch_context),
+ reporting_proxy),
url_(creation_params->script_url),
user_agent_(creation_params->user_agent),
document_security_origin_(creation_params->starter_origin),
@@ -203,8 +205,9 @@ void WorkletGlobalScope::FetchAndInvokeScript(
// Step 3 to 5 are implemented in
// WorkletModuleTreeClient::NotifyModuleTreeLoadFinished.
- WorkletModuleTreeClient* client = new WorkletModuleTreeClient(
- modulator, std::move(outside_settings_task_runner), pending_tasks);
+ WorkletModuleTreeClient* client =
+ MakeGarbageCollected<WorkletModuleTreeClient>(
+ modulator, std::move(outside_settings_task_runner), pending_tasks);
// TODO(nhiroki): Specify an appropriate destination defined in each worklet
// spec (e.g., "paint worklet", "audio worklet").
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h
index 1bdbef81c7d..2b748a33752 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -180,11 +181,12 @@ class CORE_EXPORT WorkletGlobalScope
WorkerThread* worker_thread_;
};
-DEFINE_TYPE_CASTS(WorkletGlobalScope,
- ExecutionContext,
- context,
- context->IsWorkletGlobalScope(),
- context.IsWorkletGlobalScope());
+template <>
+struct DowncastTraits<WorkletGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsWorkletGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc
index 17152f5e186..940a822a3f3 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc
@@ -6,6 +6,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc
index 3e1bf3da7e3..880426c2298 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc
@@ -29,7 +29,7 @@ class WorkletModuleResponsesMapTest : public testing::Test {
auto* context =
MockFetchContext::Create(MockFetchContext::kShouldLoadNewResource);
fetcher_ = ResourceFetcher::Create(context);
- map_ = new WorkletModuleResponsesMap;
+ map_ = MakeGarbageCollected<WorkletModuleResponsesMap>();
}
void Fetch(const KURL& url, ClientImpl* client) {
@@ -39,7 +39,8 @@ class WorkletModuleResponsesMapTest : public testing::Test {
resource_request.SetRequestContext(mojom::RequestContextType::SCRIPT);
FetchParameters fetch_params(resource_request);
WorkletModuleScriptFetcher* module_fetcher =
- new WorkletModuleScriptFetcher(fetcher_.Get(), map_.Get());
+ MakeGarbageCollected<WorkletModuleScriptFetcher>(fetcher_.Get(),
+ map_.Get());
module_fetcher->Fetch(fetch_params, ModuleGraphLevel::kTopLevelModuleFetch,
client);
}
@@ -58,7 +59,7 @@ class WorkletModuleResponsesMapTest : public testing::Test {
TEST_F(WorkletModuleResponsesMapTest, Basic) {
const KURL kUrl("https://example.com/module.js");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
kUrl, test::CoreTestDataPath("module.js"), "text/javascript");
HeapVector<Member<ClientImpl>> clients;
@@ -89,7 +90,7 @@ TEST_F(WorkletModuleResponsesMapTest, Basic) {
TEST_F(WorkletModuleResponsesMapTest, Failure) {
const KURL kUrl("https://example.com/module.js");
- URLTestHelpers::RegisterMockedErrorURLLoad(kUrl);
+ url_test_helpers::RegisterMockedErrorURLLoad(kUrl);
HeapVector<Member<ClientImpl>> clients;
// An initial read call initiates a fetch request.
@@ -120,8 +121,8 @@ TEST_F(WorkletModuleResponsesMapTest, Failure) {
TEST_F(WorkletModuleResponsesMapTest, Isolation) {
const KURL kUrl1("https://example.com/module?1.js");
const KURL kUrl2("https://example.com/module?2.js");
- URLTestHelpers::RegisterMockedErrorURLLoad(kUrl1);
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedErrorURLLoad(kUrl1);
+ url_test_helpers::RegisterMockedURLLoad(
kUrl2, test::CoreTestDataPath("module.js"), "text/javascript");
HeapVector<Member<ClientImpl>> clients;
@@ -194,9 +195,9 @@ TEST_F(WorkletModuleResponsesMapTest, InvalidURL) {
TEST_F(WorkletModuleResponsesMapTest, Dispose) {
const KURL kUrl1("https://example.com/module?1.js");
const KURL kUrl2("https://example.com/module?2.js");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
kUrl1, test::CoreTestDataPath("module.js"), "text/javascript");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
kUrl2, test::CoreTestDataPath("module.js"), "text/javascript");
HeapVector<Member<ClientImpl>> clients;
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc b/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc
index fb2499b7d7f..e936e508405 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -58,7 +59,7 @@ void WorkletModuleTreeClient::NotifyModuleTreeLoadFinished(
ScriptValue error = modulator_->ExecuteModule(
module_script, Modulator::CaptureEvalErrorFlag::kReport);
- WorkletGlobalScope* global_scope = ToWorkletGlobalScope(
+ WorkletGlobalScope* global_scope = To<WorkletGlobalScope>(
ExecutionContext::From(modulator_->GetScriptState()));
global_scope->ReportingProxy().DidEvaluateModuleScript(error.IsEmpty());
diff --git a/chromium/third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc b/chromium/third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc
index 0a5b1213bdb..ab291a28ccd 100644
--- a/chromium/third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc
+++ b/chromium/third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/xml/document_xml_tree_viewer.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -12,7 +13,6 @@
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
namespace blink {
@@ -26,7 +26,7 @@ void TransformDocumentToXMLTreeView(Document& document) {
document.GetFrame()->GetScriptController().ExecuteScriptInIsolatedWorld(
IsolatedWorldId::kDocumentXMLTreeViewerWorldId,
ScriptSourceCode(script_string, ScriptSourceLocationType::kInternal),
- KURL(), kOpaqueResource);
+ KURL(), SanitizeScriptErrors::kSanitize);
Element* element = document.getElementById("xml-viewer-style");
if (element) {
diff --git a/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.cc b/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.cc
index e1a1491106c..a2538cc2ef7 100644
--- a/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.cc
+++ b/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.cc
@@ -42,7 +42,7 @@ DocumentXPathEvaluator& DocumentXPathEvaluator::From(Document& document) {
DocumentXPathEvaluator* cache =
Supplement<Document>::From<DocumentXPathEvaluator>(document);
if (!cache) {
- cache = new DocumentXPathEvaluator(document);
+ cache = MakeGarbageCollected<DocumentXPathEvaluator>(document);
Supplement<Document>::ProvideTo(document, cache);
}
return *cache;
diff --git a/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.h b/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.h
index 0c7a16a11ea..b4d89254077 100644
--- a/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.h
+++ b/chromium/third_party/blink/renderer/core/xml/document_xpath_evaluator.h
@@ -59,11 +59,10 @@ class DocumentXPathEvaluator final
const ScriptValue&,
ExceptionState&);
+ explicit DocumentXPathEvaluator(Document&);
void Trace(blink::Visitor*) override;
private:
- explicit DocumentXPathEvaluator(Document&);
-
Member<XPathEvaluator> xpath_evaluator_;
};
diff --git a/chromium/third_party/blink/renderer/core/xml/document_xslt.cc b/chromium/third_party/blink/renderer/core/xml/document_xslt.cc
index 73be34dc689..9b44551cab0 100644
--- a/chromium/third_party/blink/renderer/core/xml/document_xslt.cc
+++ b/chromium/third_party/blink/renderer/core/xml/document_xslt.cc
@@ -27,14 +27,18 @@ class DOMContentLoadedListener final
public:
static DOMContentLoadedListener* Create(ProcessingInstruction* pi) {
- return new DOMContentLoadedListener(pi);
+ return MakeGarbageCollected<DOMContentLoadedListener>(pi);
}
+ DOMContentLoadedListener(ProcessingInstruction* pi)
+ : EventListener(EventListener::kCPPEventListenerType),
+ processing_instruction_(pi) {}
+
bool operator==(const EventListener& rhs) const override {
return this == &rhs;
}
- void handleEvent(ExecutionContext* execution_context, Event* event) override {
+ void Invoke(ExecutionContext* execution_context, Event* event) override {
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
DCHECK_EQ(event->type(), "DOMContentLoaded");
@@ -65,10 +69,6 @@ class DOMContentLoadedListener final
}
private:
- DOMContentLoadedListener(ProcessingInstruction* pi)
- : EventListener(EventListener::kCPPEventListenerType),
- processing_instruction_(pi) {}
-
// If this event listener is attached to a ProcessingInstruction, keep a
// weak reference back to it. That ProcessingInstruction is responsible for
// detaching itself and clear out the reference.
@@ -124,7 +124,8 @@ bool DocumentXSLT::ProcessingInstructionInsertedIntoDocument(
return true;
DOMContentLoadedListener* listener = DOMContentLoadedListener::Create(pi);
- document.addEventListener(EventTypeNames::DOMContentLoaded, listener, false);
+ document.addEventListener(event_type_names::kDOMContentLoaded, listener,
+ false);
DCHECK(!pi->EventListenerForXSLT());
pi->SetEventListenerForXSLT(listener);
return true;
@@ -140,7 +141,7 @@ bool DocumentXSLT::ProcessingInstructionRemovedFromDocument(
return true;
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
- document.removeEventListener(EventTypeNames::DOMContentLoaded,
+ document.removeEventListener(event_type_names::kDOMContentLoaded,
pi->EventListenerForXSLT(), false);
pi->ClearEventListenerForXSLT();
return true;
@@ -168,7 +169,7 @@ bool DocumentXSLT::HasTransformSourceDocument(Document& document) {
DocumentXSLT& DocumentXSLT::From(Document& document) {
DocumentXSLT* supplement = Supplement<Document>::From<DocumentXSLT>(document);
if (!supplement) {
- supplement = new DocumentXSLT(document);
+ supplement = MakeGarbageCollected<DocumentXSLT>(document);
Supplement<Document>::ProvideTo(document, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/core/xml/document_xslt.h b/chromium/third_party/blink/renderer/core/xml/document_xslt.h
index 0c299fa9a54..8f9c2eac7db 100644
--- a/chromium/third_party/blink/renderer/core/xml/document_xslt.h
+++ b/chromium/third_party/blink/renderer/core/xml/document_xslt.h
@@ -44,11 +44,10 @@ class DocumentXSLT final : public GarbageCollected<DocumentXSLT>,
static bool SheetLoaded(Document&, ProcessingInstruction*);
static bool HasTransformSourceDocument(Document&);
+ explicit DocumentXSLT(Document&);
void Trace(blink::Visitor*) override;
private:
- explicit DocumentXSLT(Document&);
-
Member<Document> transform_source_document_;
DISALLOW_COPY_AND_ASSIGN(DocumentXSLT);
};
diff --git a/chromium/third_party/blink/renderer/core/xml/dom_parser.h b/chromium/third_party/blink/renderer/core/xml/dom_parser.h
index 868e1f9b4ec..3e08eb90dff 100644
--- a/chromium/third_party/blink/renderer/core/xml/dom_parser.h
+++ b/chromium/third_party/blink/renderer/core/xml/dom_parser.h
@@ -35,8 +35,11 @@ class DOMParser final : public ScriptWrappable {
public:
static DOMParser* Create(Document& document) {
- return new DOMParser(document);
+ return MakeGarbageCollected<DOMParser>(document);
}
+
+ explicit DOMParser(Document&);
+
Document* parseFromString(const StringOrTrustedHTML&,
const String& type,
ExceptionState& exception_state);
@@ -46,7 +49,6 @@ class DOMParser final : public ScriptWrappable {
private:
Document* parseFromStringInternal(const String&, const String& type);
- explicit DOMParser(Document&);
WeakMember<Document> context_document_;
};
diff --git a/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.cc b/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.cc
index e604a71701e..49c4723b17b 100644
--- a/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.cc
@@ -37,7 +37,7 @@ AtomicString NativeXPathNSResolver::lookupNamespaceURI(const String& prefix) {
// This is not done by Node::lookupNamespaceURI as per the DOM3 Core spec,
// but the XPath spec says that we should do it for XPathNSResolver.
if (prefix == "xml")
- return XMLNames::xmlNamespaceURI;
+ return xml_names::kNamespaceURI;
return node_ ? node_->lookupNamespaceURI(prefix) : g_null_atom;
}
diff --git a/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.h b/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.h
index e77baa3eaa0..921f11723e4 100644
--- a/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.h
+++ b/chromium/third_party/blink/renderer/core/xml/native_xpath_ns_resolver.h
@@ -36,16 +36,16 @@ class Node;
class NativeXPathNSResolver final : public XPathNSResolver {
public:
static NativeXPathNSResolver* Create(Node* node) {
- return new NativeXPathNSResolver(node);
+ return MakeGarbageCollected<NativeXPathNSResolver>(node);
}
+ explicit NativeXPathNSResolver(Node*);
+
AtomicString lookupNamespaceURI(const String& prefix) override;
void Trace(blink::Visitor*) override;
private:
- explicit NativeXPathNSResolver(Node*);
-
Member<Node> node_;
};
diff --git a/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc b/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc
index 4355615cb23..914c7d768e7 100644
--- a/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc
+++ b/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc
@@ -79,7 +79,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// FIXME: HTMLConstructionSite has a limit of 512, should these match?
static const unsigned kMaxXMLTreeDepth = 5000;
@@ -397,7 +397,10 @@ void XMLDocumentParser::end() {
if (parser_paused_)
return;
- if (saw_error_)
+ // StopParsing() calls InsertErrorMessageBlock() if there was a parsing
+ // error. Avoid showing the error message block twice.
+ // TODO(crbug.com/898775): Rationalize this.
+ if (saw_error_ && !IsStopped())
InsertErrorMessageBlock();
else
UpdateLeafTextNode();
@@ -449,8 +452,8 @@ bool XMLDocumentParser::ParseDocumentFragment(
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-xhtml-syntax.html#xml-fragment-parsing-algorithm
// For now we have a hack for script/style innerHTML support:
if (context_element &&
- (context_element->HasLocalName(scriptTag.LocalName()) ||
- context_element->HasLocalName(styleTag.LocalName()))) {
+ (context_element->HasLocalName(kScriptTag.LocalName()) ||
+ context_element->HasLocalName(kStyleTag.LocalName()))) {
fragment->ParserAppendChild(fragment->GetDocument().createTextNode(chunk));
return true;
}
@@ -487,7 +490,7 @@ static inline void SetAttributes(Element* element,
element->ParserSetAttributes(attribute_vector);
}
-static void SwitchEncoding(xmlParserCtxtPtr ctxt, bool is8_bit) {
+static void SwitchEncoding(xmlParserCtxtPtr ctxt, bool is_8bit) {
// Make sure we don't call xmlSwitchEncoding in an error state.
if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1))
return;
@@ -496,7 +499,7 @@ static void SwitchEncoding(xmlParserCtxtPtr ctxt, bool is8_bit) {
// resetting the encoding to UTF-16 before every chunk. Otherwise libxml
// will detect <?xml version="1.0" encoding="<encoding name>"?> blocks and
// switch encodings, causing the parse to fail.
- if (is8_bit) {
+ if (is_8bit) {
xmlSwitchEncoding(ctxt, XML_CHAR_ENCODING_8859_1);
return;
}
@@ -509,9 +512,9 @@ static void SwitchEncoding(xmlParserCtxtPtr ctxt, bool is8_bit) {
}
static void ParseChunk(xmlParserCtxtPtr ctxt, const String& chunk) {
- bool is8_bit = chunk.Is8Bit();
- SwitchEncoding(ctxt, is8_bit);
- if (is8_bit)
+ bool is_8bit = chunk.Is8Bit();
+ SwitchEncoding(ctxt, is_8bit);
+ if (is_8bit)
xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.Characters8()),
sizeof(LChar) * chunk.length(), 0);
else
@@ -599,7 +602,7 @@ static void* OpenFunc(const char* uri) {
XMLDocumentParserScope scope(nullptr);
// FIXME: We should restore the original global error handler as well.
ResourceLoaderOptions options;
- options.initiator_info.name = FetchInitiatorTypeNames::xml;
+ options.initiator_info.name = fetch_initiator_type_names::kXml;
FetchParameters params(ResourceRequest(url), options);
params.MutableResourceRequest().SetFetchRequestMode(
network::mojom::FetchRequestMode::kSameOrigin);
@@ -866,7 +869,7 @@ static inline void HandleNamespaceAttributes(
WTF::g_xmlns_with_colon + ToAtomicString(namespaces[i].prefix);
QualifiedName parsed_name = g_any_name;
- if (!Element::ParseAttributeName(parsed_name, XMLNSNames::xmlnsNamespaceURI,
+ if (!Element::ParseAttributeName(parsed_name, xmlns_names::kNamespaceURI,
namespace_q_name, exception_state))
return;
@@ -974,7 +977,7 @@ void XMLDocumentParser::StartElementNs(const AtomicString& local_name,
prefix_to_namespace_map_, exception_state);
AtomicString is;
for (const auto& attr : prefixed_attributes) {
- if (attr.GetName() == isAttr) {
+ if (attr.GetName() == kIsAttr) {
is = attr.Value();
break;
}
@@ -1346,11 +1349,11 @@ static size_t ConvertUTF16EntityToUTF8(const UChar* utf16_entity,
char* target,
size_t target_size) {
const char* original_target = target;
- WTF::Unicode::ConversionResult conversion_result =
- WTF::Unicode::ConvertUTF16ToUTF8(&utf16_entity,
+ WTF::unicode::ConversionResult conversion_result =
+ WTF::unicode::ConvertUTF16ToUTF8(&utf16_entity,
utf16_entity + number_of_code_units,
&target, target + target_size);
- if (conversion_result != WTF::Unicode::kConversionOK)
+ if (conversion_result != WTF::unicode::kConversionOK)
return 0;
DCHECK_GT(target, original_target);
@@ -1580,6 +1583,9 @@ TextPosition XMLDocumentParser::GetTextPosition() const {
}
void XMLDocumentParser::StopParsing() {
+ // See comment before InsertErrorMessageBlock() in XMLDocumentParser::end.
+ if (saw_error_)
+ InsertErrorMessageBlock();
DocumentParser::StopParsing();
if (Context())
xmlStopParser(Context());
diff --git a/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.h b/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.h
index cafbc0d6319..244a7495260 100644
--- a/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.h
+++ b/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.h
@@ -72,13 +72,17 @@ class XMLDocumentParser final : public ScriptableDocumentParser,
public:
static XMLDocumentParser* Create(Document& document, LocalFrameView* view) {
- return new XMLDocumentParser(document, view);
+ return MakeGarbageCollected<XMLDocumentParser>(document, view);
}
static XMLDocumentParser* Create(DocumentFragment* fragment,
Element* element,
ParserContentPolicy parser_content_policy) {
- return new XMLDocumentParser(fragment, element, parser_content_policy);
+ return MakeGarbageCollected<XMLDocumentParser>(fragment, element,
+ parser_content_policy);
}
+
+ explicit XMLDocumentParser(Document&, LocalFrameView* = nullptr);
+ XMLDocumentParser(DocumentFragment*, Element*, ParserContentPolicy);
~XMLDocumentParser() override;
void Trace(blink::Visitor*) override;
@@ -116,9 +120,6 @@ class XMLDocumentParser final : public ScriptableDocumentParser,
void SetScriptStartPosition(TextPosition);
private:
- explicit XMLDocumentParser(Document&, LocalFrameView* = nullptr);
- XMLDocumentParser(DocumentFragment*, Element*, ParserContentPolicy);
-
// From DocumentParser
void insert(const String&) override { NOTREACHED(); }
void Append(const String&) override;
diff --git a/chromium/third_party/blink/renderer/core/xml/parser/xml_errors.cc b/chromium/third_party/blink/renderer/core/xml/parser/xml_errors.cc
index 98c610ec54c..e44492705cb 100644
--- a/chromium/third_party/blink/renderer/core/xml/parser/xml_errors.cc
+++ b/chromium/third_party/blink/renderer/core/xml/parser/xml_errors.cc
@@ -38,7 +38,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
const int kMaxErrors = 25;
@@ -103,26 +103,26 @@ static inline Element* CreateXHTMLParserErrorHeader(
Vector<Attribute> report_attributes;
report_attributes.push_back(Attribute(
- styleAttr,
+ kStyleAttr,
"display: block; white-space: pre; border: 2px solid #c77; padding: 0 "
"1em 0 1em; margin: 1em; background-color: #fdd; color: black"));
report_element->ParserSetAttributes(report_attributes);
- Element* h3 = doc->CreateRawElement(h3Tag, flags);
+ Element* h3 = doc->CreateRawElement(kH3Tag, flags);
report_element->ParserAppendChild(h3);
h3->ParserAppendChild(
doc->createTextNode("This page contains the following errors:"));
- Element* fixed = doc->CreateRawElement(divTag, flags);
+ Element* fixed = doc->CreateRawElement(kDivTag, flags);
Vector<Attribute> fixed_attributes;
fixed_attributes.push_back(
- Attribute(styleAttr, "font-family:monospace;font-size:12px"));
+ Attribute(kStyleAttr, "font-family:monospace;font-size:12px"));
fixed->ParserSetAttributes(fixed_attributes);
report_element->ParserAppendChild(fixed);
fixed->ParserAppendChild(doc->createTextNode(error_messages));
- h3 = doc->CreateRawElement(h3Tag, flags);
+ h3 = doc->CreateRawElement(kH3Tag, flags);
report_element->ParserAppendChild(h3);
h3->ParserAppendChild(doc->createTextNode(
"Below is a rendering of the page up to the first error."));
@@ -139,22 +139,22 @@ void XMLErrors::InsertErrorMessageBlock() {
const CreateElementFlags flags = CreateElementFlags::ByParser();
Element* document_element = document_->documentElement();
if (!document_element) {
- Element* root_element = document_->CreateRawElement(htmlTag, flags);
- Element* body = document_->CreateRawElement(bodyTag, flags);
+ Element* root_element = document_->CreateRawElement(kHTMLTag, flags);
+ Element* body = document_->CreateRawElement(kBodyTag, flags);
root_element->ParserAppendChild(body);
document_->ParserAppendChild(root_element);
document_element = body;
- } else if (document_element->namespaceURI() == SVGNames::svgNamespaceURI) {
- Element* root_element = document_->CreateRawElement(htmlTag, flags);
- Element* head = document_->CreateRawElement(headTag, flags);
- Element* style = document_->CreateRawElement(styleTag, flags);
+ } else if (document_element->namespaceURI() == svg_names::kNamespaceURI) {
+ Element* root_element = document_->CreateRawElement(kHTMLTag, flags);
+ Element* head = document_->CreateRawElement(kHeadTag, flags);
+ Element* style = document_->CreateRawElement(kStyleTag, flags);
head->ParserAppendChild(style);
style->ParserAppendChild(
document_->createTextNode("html, body { height: 100% } parsererror + "
"svg { width: 100%; height: 100% }"));
style->FinishParsingChildren();
root_element->ParserAppendChild(head);
- Element* body = document_->CreateRawElement(bodyTag, flags);
+ Element* body = document_->CreateRawElement(kBodyTag, flags);
root_element->ParserAppendChild(body);
document_->ParserRemoveChild(*document_element);
@@ -171,8 +171,8 @@ void XMLErrors::InsertErrorMessageBlock() {
if (DocumentXSLT::HasTransformSourceDocument(*document_)) {
Vector<Attribute> attributes;
- attributes.push_back(Attribute(styleAttr, "white-space: normal"));
- Element* paragraph = document_->CreateRawElement(pTag, flags);
+ attributes.push_back(Attribute(kStyleAttr, "white-space: normal"));
+ Element* paragraph = document_->CreateRawElement(kPTag, flags);
paragraph->ParserSetAttributes(attributes);
paragraph->ParserAppendChild(document_->createTextNode(
"This document was created as the result of an XSL transformation. The "
diff --git a/chromium/third_party/blink/renderer/core/xml/xml_attribute_names.json5 b/chromium/third_party/blink/renderer/core/xml/xml_attribute_names.json5
index 6fa47033613..d3f81e9e00b 100644
--- a/chromium/third_party/blink/renderer/core/xml/xml_attribute_names.json5
+++ b/chromium/third_party/blink/renderer/core/xml/xml_attribute_names.json5
@@ -1,7 +1,6 @@
{
metadata: {
namespace: "XML",
- namespacePrefix: "xml",
namespaceURI: "http://www.w3.org/XML/1998/namespace",
},
diff --git a/chromium/third_party/blink/renderer/core/xml/xml_serializer.h b/chromium/third_party/blink/renderer/core/xml/xml_serializer.h
index 18f4860bfd0..754b42b0804 100644
--- a/chromium/third_party/blink/renderer/core/xml/xml_serializer.h
+++ b/chromium/third_party/blink/renderer/core/xml/xml_serializer.h
@@ -32,12 +32,13 @@ class XMLSerializer final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static XMLSerializer* Create() { return new XMLSerializer; }
+ static XMLSerializer* Create() {
+ return MakeGarbageCollected<XMLSerializer>();
+ }
- String serializeToString(Node*);
-
- private:
XMLSerializer() = default;
+
+ String serializeToString(Node*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_evaluator.h b/chromium/third_party/blink/renderer/core/xml/xpath_evaluator.h
index 709c95a6cd7..ecf02abc854 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_evaluator.h
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_evaluator.h
@@ -43,7 +43,11 @@ class XPathEvaluator final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static XPathEvaluator* Create() { return new XPathEvaluator; }
+ static XPathEvaluator* Create() {
+ return MakeGarbageCollected<XPathEvaluator>();
+ }
+
+ XPathEvaluator() = default;
XPathExpression* createExpression(const String& expression,
XPathNSResolver*,
@@ -55,9 +59,6 @@ class XPathEvaluator final : public ScriptWrappable {
unsigned short type,
const ScriptValue&,
ExceptionState&);
-
- private:
- XPathEvaluator() = default;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_expression.h b/chromium/third_party/blink/renderer/core/xml/xpath_expression.h
index cf2f0d181d9..0539ca6a623 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_expression.h
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_expression.h
@@ -46,11 +46,16 @@ class XPathExpression : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static XPathExpression* Create() { return new XPathExpression; }
+ static XPathExpression* Create() {
+ return MakeGarbageCollected<XPathExpression>();
+ }
static XPathExpression* CreateExpression(const String& expression,
XPathNSResolver*,
ExceptionState&);
+
+ XPathExpression();
+
XPathResult* evaluate(Node* context_node,
unsigned short type,
const ScriptValue&,
@@ -59,8 +64,6 @@ class XPathExpression : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- XPathExpression();
-
Member<xpath::Expression> top_expression_;
};
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_functions.cc b/chromium/third_party/blink/renderer/core/xml/xpath_functions.cc
index 601fb67ba86..833388cd3f1 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_functions.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_functions.cc
@@ -630,7 +630,7 @@ Value FunLang::Evaluate(EvaluationContext& context) const {
while (node) {
if (node->IsElementNode()) {
Element* element = ToElement(node);
- language_attribute = element->Attributes().Find(XMLNames::langAttr);
+ language_attribute = element->Attributes().Find(xml_names::kLangAttr);
}
if (language_attribute)
break;
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_grammar.y b/chromium/third_party/blink/renderer/core/xml/xpath_grammar.y
index 02f81a939e4..fcd33e5c16b 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_grammar.y
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_grammar.y
@@ -272,7 +272,7 @@ OptionalPredicateList:
PredicateList:
Predicate
{
- $$ = new blink::HeapVector<blink::Member<blink::xpath::Predicate>>;
+ $$ = blink::MakeGarbageCollected<blink::HeapVector<blink::Member<blink::xpath::Predicate>>>();
$$->push_back(new blink::xpath::Predicate($1));
}
|
@@ -356,7 +356,7 @@ FunctionCall:
ArgumentList:
Argument
{
- $$ = new blink::HeapVector<blink::Member<blink::xpath::Expression>>;
+ $$ = blink::MakeGarbageCollected<blink::HeapVector<blink::Member<blink::xpath::Expression>>>();
$$->push_back($1);
}
|
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_node_set.h b/chromium/third_party/blink/renderer/core/xml/xpath_node_set.h
index 0ac2f068f11..9fbd1ba1c00 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_node_set.h
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_node_set.h
@@ -36,8 +36,11 @@ namespace xpath {
class NodeSet final : public GarbageCollected<NodeSet> {
public:
- static NodeSet* Create() { return new NodeSet; }
+ static NodeSet* Create() { return MakeGarbageCollected<NodeSet>(); }
static NodeSet* Create(const NodeSet&);
+
+ NodeSet() : is_sorted_(true), subtrees_are_disjoint_(false) {}
+
void Trace(blink::Visitor* visitor) { visitor->Trace(nodes_); }
wtf_size_t size() const { return nodes_.size(); }
@@ -88,7 +91,6 @@ class NodeSet final : public GarbageCollected<NodeSet> {
void Reverse();
private:
- NodeSet() : is_sorted_(true), subtrees_are_disjoint_(false) {}
void TraversalSort() const;
bool is_sorted_;
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_parser.cc b/chromium/third_party/blink/renderer/core/xml/xpath_parser.cc
index 2d19a6922d8..f443f689951 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_parser.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_parser.cc
@@ -54,16 +54,16 @@ static XMLCat CharCat(UChar a_char) {
if (a_char == '.' || a_char == '-')
return kNameCont;
- WTF::Unicode::CharCategory category = WTF::Unicode::Category(a_char);
+ WTF::unicode::CharCategory category = WTF::unicode::Category(a_char);
if (category &
- (WTF::Unicode::kLetter_Uppercase | WTF::Unicode::kLetter_Lowercase |
- WTF::Unicode::kLetter_Other | WTF::Unicode::kLetter_Titlecase |
- WTF::Unicode::kNumber_Letter))
+ (WTF::unicode::kLetter_Uppercase | WTF::unicode::kLetter_Lowercase |
+ WTF::unicode::kLetter_Other | WTF::unicode::kLetter_Titlecase |
+ WTF::unicode::kNumber_Letter))
return kNameStart;
if (category &
- (WTF::Unicode::kMark_NonSpacing | WTF::Unicode::kMark_SpacingCombining |
- WTF::Unicode::kMark_Enclosing | WTF::Unicode::kLetter_Modifier |
- WTF::Unicode::kNumber_DecimalDigit))
+ (WTF::unicode::kMark_NonSpacing | WTF::unicode::kMark_SpacingCombining |
+ WTF::unicode::kMark_Enclosing | WTF::unicode::kLetter_Modifier |
+ WTF::unicode::kNumber_DecimalDigit))
return kNameCont;
return kNotPartOfName;
}
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_predicate.cc b/chromium/third_party/blink/renderer/core/xml/xpath_predicate.cc
index a6716549f95..fc0c0fb0e84 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_predicate.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_predicate.cc
@@ -268,7 +268,7 @@ bool Predicate::Evaluate(EvaluationContext& context) const {
// foo[3] means foo[position()=3]
if (result.IsNumber())
return EqTestOp(EqTestOp::kOpcodeEqual, CreateFunction("position"),
- new Number(result.ToNumber()))
+ MakeGarbageCollected<Number>(result.ToNumber()))
.Evaluate(context)
.ToBoolean();
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_result.h b/chromium/third_party/blink/renderer/core/xml/xpath_result.h
index b6854662fda..7fa3fc232dd 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_result.h
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_result.h
@@ -61,9 +61,11 @@ class XPathResult final : public ScriptWrappable {
static XPathResult* Create(xpath::EvaluationContext& context,
const xpath::Value& value) {
- return new XPathResult(context, value);
+ return MakeGarbageCollected<XPathResult>(context, value);
}
+ XPathResult(xpath::EvaluationContext&, const xpath::Value&);
+
void ConvertTo(unsigned short type, ExceptionState&);
unsigned short resultType() const;
@@ -83,7 +85,6 @@ class XPathResult final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- XPathResult(xpath::EvaluationContext&, const xpath::Value&);
xpath::NodeSet& GetNodeSet() { return *node_set_; }
xpath::Value value_;
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_step.cc b/chromium/third_party/blink/renderer/core/xml/xpath_step.cc
index 36543c413a0..1b0fe346701 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_step.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_step.cc
@@ -39,12 +39,12 @@ namespace blink {
namespace xpath {
Step::Step(Axis axis, const NodeTest& node_test)
- : axis_(axis), node_test_(new NodeTest(node_test)) {}
+ : axis_(axis), node_test_(MakeGarbageCollected<NodeTest>(node_test)) {}
Step::Step(Axis axis,
const NodeTest& node_test,
HeapVector<Member<Predicate>>& predicates)
- : axis_(axis), node_test_(new NodeTest(node_test)) {
+ : axis_(axis), node_test_(MakeGarbageCollected<NodeTest>(node_test)) {
predicates_.swap(predicates);
}
@@ -185,7 +185,7 @@ static inline bool NodeMatchesBasicTest(Node* node,
// In XPath land, namespace nodes are not accessible on the
// attribute axis.
- if (attr->namespaceURI() == XMLNSNames::xmlnsNamespaceURI)
+ if (attr->namespaceURI() == xmlns_names::kNamespaceURI)
return false;
if (name == g_star_atom)
@@ -389,7 +389,7 @@ void Step::NodesInAxis(EvaluationContext& evaluation_context,
GetNodeTest().NamespaceURI(), GetNodeTest().Data());
// In XPath land, namespace nodes are not accessible on the attribute
// axis.
- if (attr && attr->namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
+ if (attr && attr->namespaceURI() != xmlns_names::kNamespaceURI) {
// Still need to check merged predicates.
if (NodeMatches(evaluation_context, attr, kAttributeAxis,
GetNodeTest()))
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_value.h b/chromium/third_party/blink/renderer/core/xml/xpath_value.h
index 6d3e3aa00e3..b1361ae2eae 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_value.h
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_value.h
@@ -39,22 +39,17 @@ struct EvaluationContext;
class ValueData : public GarbageCollectedFinalized<ValueData> {
public:
- static ValueData* Create() { return new ValueData; }
+ static ValueData* Create() { return MakeGarbageCollected<ValueData>(); }
static ValueData* Create(const NodeSet& node_set) {
- return new ValueData(node_set);
+ return MakeGarbageCollected<ValueData>(node_set);
}
static ValueData* Create(NodeSet* node_set) {
- return new ValueData(node_set);
+ return MakeGarbageCollected<ValueData>(node_set);
}
static ValueData* Create(const String& string) {
- return new ValueData(string);
+ return MakeGarbageCollected<ValueData>(string);
}
- void Trace(blink::Visitor*);
- NodeSet& GetNodeSet() { return *node_set_; }
-
- String string_;
- private:
ValueData() : node_set_(NodeSet::Create()) {}
explicit ValueData(const NodeSet& node_set)
: node_set_(NodeSet::Create(node_set)) {}
@@ -62,6 +57,12 @@ class ValueData : public GarbageCollectedFinalized<ValueData> {
explicit ValueData(const String& string)
: string_(string), node_set_(NodeSet::Create()) {}
+ void Trace(blink::Visitor*);
+ NodeSet& GetNodeSet() { return *node_set_; }
+
+ String string_;
+
+ private:
Member<NodeSet> node_set_;
};
diff --git a/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet.h b/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet.h
index 5cdedcf9662..d59872e69d1 100644
--- a/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet.h
+++ b/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet.h
@@ -38,13 +38,14 @@ class XSLStyleSheet final : public StyleSheet {
const String& original_url,
const KURL& final_url) {
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
- return new XSLStyleSheet(parent_node, original_url, final_url, false);
+ return MakeGarbageCollected<XSLStyleSheet>(parent_node, original_url,
+ final_url, false);
}
static XSLStyleSheet* CreateEmbedded(ProcessingInstruction* parent_node,
const KURL& final_url) {
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
- return new XSLStyleSheet(parent_node, final_url.GetString(), final_url,
- true);
+ return MakeGarbageCollected<XSLStyleSheet>(
+ parent_node, final_url.GetString(), final_url, true);
}
// Taking an arbitrary node is unsafe, because owner node pointer can become
@@ -55,10 +56,22 @@ class XSLStyleSheet final : public StyleSheet {
const String& original_url,
const KURL& final_url) {
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
- return new XSLStyleSheet(document, stylesheet_root_node, original_url,
- final_url, false);
+ return MakeGarbageCollected<XSLStyleSheet>(document, stylesheet_root_node,
+ original_url, final_url, false);
}
+ XSLStyleSheet(Node* parent_node,
+ const String& original_url,
+ const KURL& final_url,
+ bool embedded);
+ XSLStyleSheet(Document* owner_document,
+ Node* style_sheet_root_node,
+ const String& original_url,
+ const KURL& final_url,
+ bool embedded);
+ XSLStyleSheet(XSLStyleSheet* parent_style_sheet,
+ const String& original_url,
+ const KURL& final_url);
~XSLStyleSheet() override;
bool ParseString(const String&);
@@ -94,19 +107,6 @@ class XSLStyleSheet final : public StyleSheet {
void Trace(blink::Visitor*) override;
private:
- XSLStyleSheet(Node* parent_node,
- const String& original_url,
- const KURL& final_url,
- bool embedded);
- XSLStyleSheet(Document* owner_document,
- Node* style_sheet_root_node,
- const String& original_url,
- const KURL& final_url,
- bool embedded);
- XSLStyleSheet(XSLStyleSheet* parent_style_sheet,
- const String& original_url,
- const KURL& final_url);
-
void LoadChildSheets();
void LoadChildSheet(const String& href);
diff --git a/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc b/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
index 59349d62453..3ddf37bc50a 100644
--- a/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
@@ -224,7 +224,7 @@ void XSLStyleSheet::LoadChildSheet(const String& href) {
const String& url_string = url.GetString();
ResourceLoaderOptions fetch_options;
- fetch_options.initiator_info.name = FetchInitiatorTypeNames::xml;
+ fetch_options.initiator_info.name = fetch_initiator_type_names::kXml;
FetchParameters params(
ResourceRequest(OwnerDocument()->CompleteURL(url_string)), fetch_options);
params.MutableResourceRequest().SetFetchRequestMode(
@@ -234,8 +234,8 @@ void XSLStyleSheet::LoadChildSheet(const String& href) {
if (!resource->Sheet())
return;
- XSLStyleSheet* style_sheet =
- new XSLStyleSheet(this, url_string, resource->GetResponse().Url());
+ XSLStyleSheet* style_sheet = MakeGarbageCollected<XSLStyleSheet>(
+ this, url_string, resource->GetResponse().Url());
children_.push_back(style_sheet);
style_sheet->ParseString(resource->Sheet());
CheckLoaded();
diff --git a/chromium/third_party/blink/renderer/core/xml/xslt_processor.h b/chromium/third_party/blink/renderer/core/xml/xslt_processor.h
index 34782352db8..acfaf8ca974 100644
--- a/chromium/third_party/blink/renderer/core/xml/xslt_processor.h
+++ b/chromium/third_party/blink/renderer/core/xml/xslt_processor.h
@@ -45,8 +45,10 @@ class XSLTProcessor final : public ScriptWrappable {
public:
static XSLTProcessor* Create(Document& document) {
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
- return new XSLTProcessor(document);
+ return MakeGarbageCollected<XSLTProcessor>(document);
}
+
+ XSLTProcessor(Document& document) : document_(&document) {}
~XSLTProcessor() override;
void SetXSLStyleSheet(XSLStyleSheet* style_sheet) {
@@ -88,8 +90,6 @@ class XSLTProcessor final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- XSLTProcessor(Document& document) : document_(&document) {}
-
Member<XSLStyleSheet> stylesheet_;
Member<Node> stylesheet_root_node_;
Member<Document> document_;
diff --git a/chromium/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc b/chromium/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc
index ba3d0f49383..47e5f3cd949 100644
--- a/chromium/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc
@@ -107,7 +107,7 @@ static xmlDocPtr DocLoaderFunc(const xmlChar* uri,
xmlFree(base);
ResourceLoaderOptions fetch_options;
- fetch_options.initiator_info.name = FetchInitiatorTypeNames::xml;
+ fetch_options.initiator_info.name = fetch_initiator_type_names::kXml;
FetchParameters params(ResourceRequest(url), fetch_options);
params.MutableResourceRequest().SetFetchRequestMode(
network::mojom::FetchRequestMode::kSameOrigin);
@@ -182,10 +182,10 @@ static int WriteToStringBuilder(void* context, const char* buffer, int len) {
UChar* buffer_u_char_end = buffer_u_char + len;
const char* string_current = buffer;
- WTF::Unicode::ConversionResult result = WTF::Unicode::ConvertUTF8ToUTF16(
+ WTF::unicode::ConversionResult result = WTF::unicode::ConvertUTF8ToUTF16(
&string_current, buffer + len, &buffer_u_char, buffer_u_char_end);
- if (result != WTF::Unicode::kConversionOK &&
- result != WTF::Unicode::kSourceExhausted) {
+ if (result != WTF::unicode::kConversionOK &&
+ result != WTF::unicode::kSourceExhausted) {
NOTREACHED();
return -1;
}
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
index 41126033d47..a5dbae754b1 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
@@ -28,7 +28,6 @@
#include "base/auto_reset.h"
#include "third_party/blink/public/common/blob/blob_utils.h"
#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
-#include "third_party/blink/public/platform/web_cors.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/array_buffer_or_array_buffer_view_or_blob_or_document_or_string_or_form_data_or_url_search_params.h"
#include "third_party/blink/renderer/bindings/core/v8/array_buffer_or_array_buffer_view_or_blob_or_usv_string.h"
@@ -69,7 +68,6 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
-#include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h"
#include "third_party/blink/renderer/platform/file_metadata.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
@@ -231,7 +229,14 @@ class XMLHttpRequest::BlobLoader final
public:
static BlobLoader* Create(XMLHttpRequest* xhr,
scoped_refptr<BlobDataHandle> handle) {
- return new BlobLoader(xhr, std::move(handle));
+ return MakeGarbageCollected<BlobLoader>(xhr, std::move(handle));
+ }
+
+ BlobLoader(XMLHttpRequest* xhr, scoped_refptr<BlobDataHandle> handle)
+ : xhr_(xhr),
+ loader_(
+ FileReaderLoader::Create(FileReaderLoader::kReadByClient, this)) {
+ loader_->Start(std::move(handle));
}
// FileReaderLoaderClient functions.
@@ -241,22 +246,13 @@ class XMLHttpRequest::BlobLoader final
xhr_->DidReceiveData(data, length);
}
void DidFinishLoading() override { xhr_->DidFinishLoadingFromBlob(); }
- void DidFail(FileError::ErrorCode error) override {
- xhr_->DidFailLoadingFromBlob();
- }
+ void DidFail(FileErrorCode error) override { xhr_->DidFailLoadingFromBlob(); }
void Cancel() { loader_->Cancel(); }
void Trace(blink::Visitor* visitor) { visitor->Trace(xhr_); }
private:
- BlobLoader(XMLHttpRequest* xhr, scoped_refptr<BlobDataHandle> handle)
- : xhr_(xhr),
- loader_(
- FileReaderLoader::Create(FileReaderLoader::kReadByClient, this)) {
- loader_->Start(std::move(handle));
- }
-
Member<XMLHttpRequest> xhr_;
std::unique_ptr<FileReaderLoader> loader_;
};
@@ -268,9 +264,10 @@ XMLHttpRequest* XMLHttpRequest::Create(ScriptState* script_state) {
XMLHttpRequest* xml_http_request =
world.IsIsolatedWorld()
- ? new XMLHttpRequest(context, isolate, true,
- world.IsolatedWorldSecurityOrigin())
- : new XMLHttpRequest(context, isolate, false, nullptr);
+ ? MakeGarbageCollected<XMLHttpRequest>(
+ context, isolate, true, world.IsolatedWorldSecurityOrigin())
+ : MakeGarbageCollected<XMLHttpRequest>(context, isolate, false,
+ nullptr);
xml_http_request->PauseIfNeeded();
return xml_http_request;
}
@@ -280,7 +277,7 @@ XMLHttpRequest* XMLHttpRequest::Create(ExecutionContext* context) {
CHECK(isolate);
XMLHttpRequest* xml_http_request =
- new XMLHttpRequest(context, isolate, false, nullptr);
+ MakeGarbageCollected<XMLHttpRequest>(context, isolate, false, nullptr);
xml_http_request->PauseIfNeeded();
return xml_http_request;
}
@@ -394,8 +391,12 @@ Document* XMLHttpRequest::responseXML(ExceptionState& exception_state) {
return nullptr;
response_document_->SetContent(response_text_.Flatten(isolate_));
- if (!response_document_->WellFormed())
+ if (!response_document_->WellFormed()) {
response_document_ = nullptr;
+ } else {
+ response_document_->OverrideLastModified(
+ response_.HttpHeaderField(http_names::kLastModified));
+ }
parsed_response_ = true;
}
@@ -561,7 +562,7 @@ void XMLHttpRequest::TrackProgress(long long length) {
ChangeState(kLoading);
if (async_) {
// readyStateChange event is fired as well.
- DispatchProgressEventFromSnapshot(EventTypeNames::progress);
+ DispatchProgressEventFromSnapshot(event_type_names::kProgress);
}
}
@@ -578,9 +579,9 @@ void XMLHttpRequest::DispatchReadyStateChangeEvent() {
ScopedEventDispatchProtect protect(&event_dispatch_recursion_level_);
if (async_ || (state_ <= kOpened || state_ == kDone)) {
- TRACE_EVENT1(
- "devtools.timeline", "XHRReadyStateChange", "data",
- InspectorXhrReadyStateChangeEvent::Data(GetExecutionContext(), this));
+ TRACE_EVENT1("devtools.timeline", "XHRReadyStateChange", "data",
+ inspector_xhr_ready_state_change_event::Data(
+ GetExecutionContext(), this));
XMLHttpRequestProgressEventThrottle::DeferredEventAction action =
XMLHttpRequestProgressEventThrottle::kIgnore;
if (state_ == kDone) {
@@ -590,14 +591,14 @@ void XMLHttpRequest::DispatchReadyStateChangeEvent() {
action = XMLHttpRequestProgressEventThrottle::kFlush;
}
progress_event_throttle_->DispatchReadyStateChangeEvent(
- Event::Create(EventTypeNames::readystatechange), action);
+ Event::Create(event_type_names::kReadystatechange), action);
}
if (state_ == kDone && !error_) {
TRACE_EVENT1("devtools.timeline", "XHRLoad", "data",
- InspectorXhrLoadEvent::Data(GetExecutionContext(), this));
- DispatchProgressEventFromSnapshot(EventTypeNames::load);
- DispatchProgressEventFromSnapshot(EventTypeNames::loadend);
+ inspector_xhr_load_event::Data(GetExecutionContext(), this));
+ DispatchProgressEventFromSnapshot(event_type_names::kLoad);
+ DispatchProgressEventFromSnapshot(event_type_names::kLoadend);
}
}
@@ -744,10 +745,10 @@ bool XMLHttpRequest::InitSend(ExceptionState& exception_state) {
if (!async_) {
if (GetExecutionContext()->IsDocument() &&
- !GetDocument()->IsFeatureEnabled(mojom::FeaturePolicyFeature::kSyncXHR,
- ReportOptions::kReportOnFailure)) {
- LogConsoleError(GetExecutionContext(),
- "Synchronous requests are disabled by Feature Policy.");
+ !GetDocument()->IsFeatureEnabled(
+ mojom::FeaturePolicyFeature::kSyncXHR,
+ ReportOptions::kReportOnFailure,
+ "Synchronous requests are disabled by Feature Policy.")) {
HandleNetworkError();
ThrowForLoadFailureIfNeeded(exception_state, String());
return false;
@@ -809,7 +810,7 @@ void XMLHttpRequest::send(
}
bool XMLHttpRequest::AreMethodAndURLValidForSend() {
- return method_ != HTTPNames::GET && method_ != HTTPNames::HEAD &&
+ return method_ != http_names::kGET && method_ != http_names::kHEAD &&
url_.ProtocolIsInHTTPFamily();
}
@@ -868,7 +869,7 @@ void XMLHttpRequest::send(Blob* body, ExceptionState& exception_state) {
if (!HasContentTypeRequestHeader()) {
const String& blob_type = FetchUtils::NormalizeHeaderValue(body->type());
if (!blob_type.IsEmpty() && ParsedContentType(blob_type).IsValid()) {
- SetRequestHeaderInternal(HTTPNames::Content_Type,
+ SetRequestHeaderInternal(http_names::kContentType,
AtomicString(blob_type));
}
}
@@ -906,7 +907,7 @@ void XMLHttpRequest::send(FormData* body, ExceptionState& exception_state) {
AtomicString content_type =
AtomicString("multipart/form-data; boundary=") +
FetchUtils::NormalizeHeaderValue(http_body->Boundary().data());
- SetRequestHeaderInternal(HTTPNames::Content_Type, content_type);
+ SetRequestHeaderInternal(http_names::kContentType, content_type);
}
}
@@ -993,7 +994,7 @@ void XMLHttpRequest::ThrowForLoadFailureIfNeeded(
void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
ExceptionState& exception_state) {
// Only GET request is supported for blob URL.
- if (url_.ProtocolIs("blob") && method_ != HTTPNames::GET) {
+ if (url_.ProtocolIs("blob") && method_ != http_names::kGET) {
HandleNetworkError();
if (!async_) {
@@ -1015,7 +1016,7 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
bool upload_events = false;
if (async_) {
probe::AsyncTaskScheduled(&execution_context, "XMLHttpRequest.send", this);
- DispatchProgressEvent(EventTypeNames::loadstart, 0, 0);
+ DispatchProgressEvent(event_type_names::kLoadstart, 0, 0);
// Event handler could have invalidated this send operation,
// (re)setting the send flag and/or initiating another send
// operation; leave quietly if so.
@@ -1024,7 +1025,7 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
if (http_body && upload_) {
upload_events = upload_->HasEventListeners();
upload_->DispatchEvent(
- *ProgressEvent::Create(EventTypeNames::loadstart, false, 0, 0));
+ *ProgressEvent::Create(event_type_names::kLoadstart, false, 0, 0));
// See above.
if (!send_flag_ || loader_)
return;
@@ -1042,16 +1043,16 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
// in case the upload listeners are added after the request is started.
upload_events_allowed_ =
same_origin_request_ || upload_events ||
- !CORS::IsCORSSafelistedMethod(method_) ||
- !CORS::ContainsOnlyCORSSafelistedHeaders(request_headers_);
+ !cors::IsCorsSafelistedMethod(method_) ||
+ !cors::ContainsOnlyCorsSafelistedHeaders(request_headers_);
ResourceRequest request(url_);
request.SetRequestorOrigin(GetSecurityOrigin());
request.SetHTTPMethod(method_);
request.SetRequestContext(mojom::RequestContextType::XML_HTTP_REQUEST);
request.SetFetchRequestMode(
- upload_events ? network::mojom::FetchRequestMode::kCORSWithForcedPreflight
- : network::mojom::FetchRequestMode::kCORS);
+ upload_events ? network::mojom::FetchRequestMode::kCorsWithForcedPreflight
+ : network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(
with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
: network::mojom::FetchCredentialsMode::kSameOrigin);
@@ -1063,8 +1064,8 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
request_headers_, with_credentials_);
if (http_body) {
- DCHECK_NE(method_, HTTPNames::GET);
- DCHECK_NE(method_, HTTPNames::HEAD);
+ DCHECK_NE(method_, http_names::kGET);
+ DCHECK_NE(method_, http_names::kHEAD);
request.SetHTTPBody(std::move(http_body));
}
@@ -1073,7 +1074,7 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
ResourceLoaderOptions resource_loader_options;
resource_loader_options.initiator_info.name =
- FetchInitiatorTypeNames::xmlhttprequest;
+ fetch_initiator_type_names::kXmlhttprequest;
if (blob_url_loader_factory_) {
resource_loader_options.url_loader_factory = base::MakeRefCounted<
base::RefCountedData<network::mojom::blink::URLLoaderFactoryPtr>>(
@@ -1133,8 +1134,8 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
resource_loader_options.synchronous_policy = kRequestSynchronously;
}
- loader_ = new ThreadableLoader(execution_context, this,
- resource_loader_options);
+ loader_ = MakeGarbageCollected<ThreadableLoader>(execution_context, this,
+ resource_loader_options);
loader_->SetTimeout(timeout_);
loader_->Start(request);
@@ -1166,7 +1167,7 @@ void XMLHttpRequest::abort() {
if ((state_ == kOpened && send_flag_) || state_ == kHeadersReceived ||
state_ == kLoading) {
DCHECK(!loader_);
- HandleRequestError(DOMExceptionCode::kNoError, EventTypeNames::abort,
+ HandleRequestError(DOMExceptionCode::kNoError, event_type_names::kAbort,
received_length, expected_length);
}
}
@@ -1284,7 +1285,7 @@ void XMLHttpRequest::DispatchProgressEvent(const AtomicString& type,
ExecutionContext* context = GetExecutionContext();
probe::AsyncTask async_task(
- context, this, type == EventTypeNames::loadend ? nullptr : "progress",
+ context, this, type == event_type_names::kLoadend ? nullptr : "progress",
async_);
progress_event_throttle_->DispatchProgressEvent(type, length_computable,
loaded, total);
@@ -1306,7 +1307,7 @@ void XMLHttpRequest::HandleNetworkError() {
if (!InternalAbort())
return;
- HandleRequestError(DOMExceptionCode::kNetworkError, EventTypeNames::error,
+ HandleRequestError(DOMExceptionCode::kNetworkError, event_type_names::kError,
received_length, expected_length);
}
@@ -1323,7 +1324,7 @@ void XMLHttpRequest::HandleDidCancel() {
pending_abort_event_ = PostCancellableTask(
*GetExecutionContext()->GetTaskRunner(TaskType::kNetworking), FROM_HERE,
WTF::Bind(&XMLHttpRequest::HandleRequestError, WrapPersistent(this),
- DOMExceptionCode::kAbortError, EventTypeNames::abort,
+ DOMExceptionCode::kAbortError, event_type_names::kAbort,
received_length, expected_length));
}
@@ -1360,10 +1361,10 @@ void XMLHttpRequest::HandleRequestError(DOMExceptionCode exception_code,
// false|, when |handleRequestError| is called after |internalAbort()|. This
// is safe, however, as |this| will be kept alive from a strong ref
// |Event::m_target|.
- DispatchProgressEvent(EventTypeNames::progress, received_length,
+ DispatchProgressEvent(event_type_names::kProgress, received_length,
expected_length);
DispatchProgressEvent(type, received_length, expected_length);
- DispatchProgressEvent(EventTypeNames::loadend, received_length,
+ DispatchProgressEvent(event_type_names::kLoadend, received_length,
expected_length);
}
@@ -1414,7 +1415,7 @@ void XMLHttpRequest::setRequestHeader(const AtomicString& name,
// "5. Terminate these steps if |name| is a forbidden header name."
// No script (privileged or not) can set unsafe headers.
- if (CORS::IsForbiddenHeaderName(name)) {
+ if (cors::IsForbiddenHeaderName(name)) {
LogConsoleError(GetExecutionContext(),
"Refused to set unsafe header \"" + name + "\"");
return;
@@ -1436,7 +1437,7 @@ void XMLHttpRequest::SetRequestHeaderInternal(const AtomicString& name,
}
bool XMLHttpRequest::HasContentTypeRequestHeader() const {
- return request_headers_.Find(HTTPNames::Content_Type) !=
+ return request_headers_.Find(http_names::kContentType) !=
request_headers_.end();
}
@@ -1447,10 +1448,10 @@ String XMLHttpRequest::getAllResponseHeaders() const {
StringBuilder string_builder;
WebHTTPHeaderSet access_control_expose_header_set =
- WebCORS::ExtractCorsExposedHeaderNamesList(
+ cors::ExtractCorsExposedHeaderNamesList(
with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
: network::mojom::FetchCredentialsMode::kSameOrigin,
- WrappedResourceResponse(response_));
+ response_);
HTTPHeaderMap::const_iterator end = response_.HttpHeaderFields().end();
for (HTTPHeaderMap::const_iterator it = response_.HttpHeaderFields().begin();
@@ -1465,7 +1466,7 @@ String XMLHttpRequest::getAllResponseHeaders() const {
continue;
if (!same_origin_request_ &&
- !WebCORS::IsOnAccessControlResponseHeaderWhitelist(it->key) &&
+ !cors::IsOnAccessControlResponseHeaderWhitelist(it->key) &&
access_control_expose_header_set.find(it->key.Ascii().data()) ==
access_control_expose_header_set.end())
continue;
@@ -1495,13 +1496,13 @@ const AtomicString& XMLHttpRequest::getResponseHeader(
}
WebHTTPHeaderSet access_control_expose_header_set =
- WebCORS::ExtractCorsExposedHeaderNamesList(
+ cors::ExtractCorsExposedHeaderNamesList(
with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
: network::mojom::FetchCredentialsMode::kSameOrigin,
- WrappedResourceResponse(response_));
+ response_);
if (!same_origin_request_ &&
- !WebCORS::IsOnAccessControlResponseHeaderWhitelist(name) &&
+ !cors::IsOnAccessControlResponseHeaderWhitelist(name) &&
access_control_expose_header_set.find(name.Ascii().data()) ==
access_control_expose_header_set.end()) {
LogConsoleError(GetExecutionContext(),
@@ -1517,9 +1518,10 @@ AtomicString XMLHttpRequest::FinalResponseMIMEType() const {
if (!overridden_type.IsEmpty())
return overridden_type;
- if (response_.IsHTTP())
+ if (response_.IsHTTP()) {
return ExtractMIMETypeFromMediaType(
- response_.HttpHeaderField(HTTPNames::Content_Type));
+ response_.HttpHeaderField(http_names::kContentType));
+ }
return response_.MimeType();
}
@@ -1545,14 +1547,14 @@ void XMLHttpRequest::UpdateContentTypeAndCharset(
const String& charset) {
// http://xhr.spec.whatwg.org/#the-send()-method step 4's concilliation of
// "charset=" in any author-provided Content-Type: request header.
- String content_type = request_headers_.Get(HTTPNames::Content_Type);
+ String content_type = request_headers_.Get(http_names::kContentType);
if (content_type.IsNull()) {
- SetRequestHeaderInternal(HTTPNames::Content_Type, default_content_type);
+ SetRequestHeaderInternal(http_names::kContentType, default_content_type);
return;
}
String original_content_type = content_type;
ReplaceCharsetInMediaType(content_type, charset);
- request_headers_.Set(HTTPNames::Content_Type, AtomicString(content_type));
+ request_headers_.Set(http_names::kContentType, AtomicString(content_type));
if (original_content_type != content_type) {
UseCounter::Count(GetExecutionContext(), WebFeature::kReplaceCharsetInXHR);
@@ -1725,7 +1727,7 @@ void XMLHttpRequest::EndLoading() {
return;
if (GetDocument() && GetDocument()->GetFrame() &&
- GetDocument()->GetFrame()->GetPage() && CORS::IsOkStatus(status()))
+ GetDocument()->GetFrame()->GetPage() && cors::IsOkStatus(status()))
GetDocument()->GetFrame()->GetPage()->GetChromeClient().AjaxSucceeded(
GetDocument()->GetFrame());
}
@@ -1744,9 +1746,10 @@ void XMLHttpRequest::DidSendData(unsigned long long bytes_sent,
if (bytes_sent == total_bytes_to_be_sent && !upload_complete_) {
upload_complete_ = true;
- if (upload_events_allowed_)
- upload_->DispatchEventAndLoadEnd(EventTypeNames::load, true, bytes_sent,
- total_bytes_to_be_sent);
+ if (upload_events_allowed_) {
+ upload_->DispatchEventAndLoadEnd(event_type_names::kLoad, true,
+ bytes_sent, total_bytes_to_be_sent);
+ }
}
}
@@ -1945,8 +1948,9 @@ void XMLHttpRequest::HandleDidTimeout() {
if (!InternalAbort())
return;
- HandleRequestError(DOMExceptionCode::kTimeoutError, EventTypeNames::timeout,
- received_length, expected_length);
+ HandleRequestError(DOMExceptionCode::kTimeoutError,
+ event_type_names::kTimeout, received_length,
+ expected_length);
}
void XMLHttpRequest::Pause() {
@@ -1978,7 +1982,7 @@ bool XMLHttpRequest::HasPendingActivity() const {
}
const AtomicString& XMLHttpRequest::InterfaceName() const {
- return EventTargetNames::XMLHttpRequest;
+ return event_target_names::kXMLHttpRequest;
}
ExecutionContext* XMLHttpRequest::GetExecutionContext() const {
@@ -2013,6 +2017,7 @@ void XMLHttpRequest::Trace(blink::Visitor* visitor) {
visitor->Trace(blob_loader_);
visitor->Trace(response_text_);
XMLHttpRequestEventTarget::Trace(visitor);
+ ThreadableLoaderClient::Trace(visitor);
DocumentParserClient::Trace(visitor);
PausableObject::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h
index 023d910962c..813044ebc4a 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h
@@ -41,7 +41,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/network/http_header_map.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
@@ -70,22 +70,21 @@ class WebDataConsumerHandle;
class XMLHttpRequestUpload;
class XMLHttpRequest final : public XMLHttpRequestEventTarget,
- private ThreadableLoaderClient,
+ public ThreadableLoaderClient,
public DocumentParserClient,
public ActiveScriptWrappable<XMLHttpRequest>,
public PausableObject {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(XMLHttpRequest);
- // In some cases hasPendingActivity doesn't work correctly, i.e.,
- // doesn't keep |this| alive. We need to cancel the loader in such cases,
- // which is why we need this pre-finalizer.
- // TODO(yhirano): Remove this pre-finalizer when the bug is fixed.
- USING_PRE_FINALIZER(XMLHttpRequest, Dispose);
-
public:
static XMLHttpRequest* Create(ScriptState*);
static XMLHttpRequest* Create(ExecutionContext*);
+
+ XMLHttpRequest(ExecutionContext*,
+ v8::Isolate*,
+ bool is_isolated_world,
+ scoped_refptr<SecurityOrigin>);
~XMLHttpRequest() override;
// These exact numeric values are important because JS expects them.
@@ -152,7 +151,9 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget,
Document* responseXML(ExceptionState&);
Blob* ResponseBlob();
DOMArrayBuffer* ResponseArrayBuffer();
- unsigned timeout() const { return timeout_.InMilliseconds(); }
+ unsigned timeout() const {
+ return static_cast<unsigned>(timeout_.InMilliseconds());
+ }
void setTimeout(unsigned timeout, ExceptionState&);
ResponseTypeCode GetResponseTypeCode() const { return response_type_code_; }
String responseType();
@@ -166,17 +167,13 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget,
XMLHttpRequestUpload* upload();
bool IsAsync() { return async_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange, kReadystatechange);
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override { return "XMLHttpRequest"; }
private:
class BlobLoader;
- XMLHttpRequest(ExecutionContext*,
- v8::Isolate*,
- bool is_isolated_world,
- scoped_refptr<SecurityOrigin>);
Document* GetDocument() const;
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_event_target.h b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_event_target.h
index b63ed8f166e..94e90770461 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_event_target.h
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_event_target.h
@@ -40,13 +40,13 @@ class XMLHttpRequestEventTarget : public EventTargetWithInlineData {
DEFINE_WRAPPERTYPEINFO();
public:
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(timeout);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(load, kLoad);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend, kLoadend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart, kLoadstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(progress, kProgress);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(timeout, kTimeout);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc
index f85ae3421c2..ca7c69fe881 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc
@@ -69,7 +69,7 @@ void XMLHttpRequestProgressEventThrottle::DeferredEvent::Clear() {
Event* XMLHttpRequestProgressEventThrottle::DeferredEvent::Take() {
DCHECK(is_set_);
- Event* event = ProgressEvent::Create(EventTypeNames::progress,
+ Event* event = ProgressEvent::Create(event_type_names::kProgress,
length_computable_, loaded_, total_);
Clear();
return event;
@@ -94,7 +94,7 @@ void XMLHttpRequestProgressEventThrottle::DispatchProgressEvent(
unsigned long long total) {
// Given that ResourceDispatcher doesn't deliver an event when suspended,
// we don't have to worry about event dispatching while suspended.
- if (type != EventTypeNames::progress) {
+ if (type != event_type_names::kProgress) {
target_->DispatchEvent(
*ProgressEvent::Create(type, length_computable, loaded, total));
return;
@@ -104,7 +104,7 @@ void XMLHttpRequestProgressEventThrottle::DispatchProgressEvent(
deferred_.Set(length_computable, loaded, total);
} else {
DispatchProgressProgressEvent(ProgressEvent::Create(
- EventTypeNames::progress, length_computable, loaded, total));
+ event_type_names::kProgress, length_computable, loaded, total));
StartOneShot(kMinimumProgressEventDispatchingInterval, FROM_HERE);
}
}
@@ -143,11 +143,11 @@ void XMLHttpRequestProgressEventThrottle::DispatchProgressProgressEvent(
if (target_->readyState() == XMLHttpRequest::kLoading &&
has_dispatched_progress_progress_event_) {
TRACE_EVENT1("devtools.timeline", "XHRReadyStateChange", "data",
- InspectorXhrReadyStateChangeEvent::Data(
+ inspector_xhr_ready_state_change_event::Data(
target_->GetExecutionContext(), target_));
probe::AsyncTask async_task(target_->GetExecutionContext(), target_,
"progress", target_->IsAsync());
- target_->DispatchEvent(*Event::Create(EventTypeNames::readystatechange));
+ target_->DispatchEvent(*Event::Create(event_type_names::kReadystatechange));
}
if (target_->readyState() != state)
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.h b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.h
index 3da84ad8bc9..d96f80546dc 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.h
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.h
@@ -54,8 +54,11 @@ class XMLHttpRequestProgressEventThrottle final
public:
static XMLHttpRequestProgressEventThrottle* Create(
XMLHttpRequest* event_target) {
- return new XMLHttpRequestProgressEventThrottle(event_target);
+ return MakeGarbageCollected<XMLHttpRequestProgressEventThrottle>(
+ event_target);
}
+
+ explicit XMLHttpRequestProgressEventThrottle(XMLHttpRequest*);
~XMLHttpRequestProgressEventThrottle() override;
enum DeferredEventAction {
@@ -90,8 +93,6 @@ class XMLHttpRequestProgressEventThrottle final
void Trace(blink::Visitor*);
private:
- explicit XMLHttpRequestProgressEventThrottle(XMLHttpRequest*);
-
// Dispatches a "progress" progress event and usually a readyStateChange
// event as well.
void DispatchProgressProgressEvent(Event*);
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.cc b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.cc
index 7eef081acea..8c764dff5ba 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.cc
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.cc
@@ -39,7 +39,7 @@ XMLHttpRequestUpload::XMLHttpRequestUpload(XMLHttpRequest* xml_http_request)
last_total_bytes_to_be_sent_(0) {}
const AtomicString& XMLHttpRequestUpload::InterfaceName() const {
- return EventTargetNames::XMLHttpRequestUpload;
+ return event_target_names::kXMLHttpRequestUpload;
}
ExecutionContext* XMLHttpRequestUpload::GetExecutionContext() const {
@@ -53,7 +53,7 @@ void XMLHttpRequestUpload::DispatchProgressEvent(
last_total_bytes_to_be_sent_ = total_bytes_to_be_sent;
probe::AsyncTask async_task(GetExecutionContext(), xml_http_request_,
"progress", xml_http_request_->IsAsync());
- DispatchEvent(*ProgressEvent::Create(EventTypeNames::progress, true,
+ DispatchEvent(*ProgressEvent::Create(event_type_names::kProgress, true,
bytes_sent, total_bytes_to_be_sent));
}
@@ -62,13 +62,14 @@ void XMLHttpRequestUpload::DispatchEventAndLoadEnd(
bool length_computable,
unsigned long long bytes_sent,
unsigned long long total) {
- DCHECK(type == EventTypeNames::load || type == EventTypeNames::abort ||
- type == EventTypeNames::error || type == EventTypeNames::timeout);
+ DCHECK(type == event_type_names::kLoad || type == event_type_names::kAbort ||
+ type == event_type_names::kError ||
+ type == event_type_names::kTimeout);
probe::AsyncTask async_task(GetExecutionContext(), xml_http_request_, "event",
xml_http_request_->IsAsync());
DispatchEvent(
*ProgressEvent::Create(type, length_computable, bytes_sent, total));
- DispatchEvent(*ProgressEvent::Create(EventTypeNames::loadend,
+ DispatchEvent(*ProgressEvent::Create(event_type_names::kLoadend,
length_computable, bytes_sent, total));
}
@@ -77,7 +78,7 @@ void XMLHttpRequestUpload::HandleRequestError(const AtomicString& type) {
last_bytes_sent_ <= last_total_bytes_to_be_sent_;
probe::AsyncTask async_task(GetExecutionContext(), xml_http_request_, "error",
xml_http_request_->IsAsync());
- DispatchEvent(*ProgressEvent::Create(EventTypeNames::progress,
+ DispatchEvent(*ProgressEvent::Create(event_type_names::kProgress,
length_computable, last_bytes_sent_,
last_total_bytes_to_be_sent_));
DispatchEventAndLoadEnd(type, length_computable, last_bytes_sent_,
diff --git a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.h b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.h
index 25d6c5235ce..c47e24d9096 100644
--- a/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.h
+++ b/chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_upload.h
@@ -42,9 +42,11 @@ class XMLHttpRequestUpload final : public XMLHttpRequestEventTarget {
public:
static XMLHttpRequestUpload* Create(XMLHttpRequest* xml_http_request) {
- return new XMLHttpRequestUpload(xml_http_request);
+ return MakeGarbageCollected<XMLHttpRequestUpload>(xml_http_request);
}
+ explicit XMLHttpRequestUpload(XMLHttpRequest*);
+
XMLHttpRequest* XmlHttpRequest() const { return xml_http_request_; }
const AtomicString& InterfaceName() const override;
@@ -61,8 +63,6 @@ class XMLHttpRequestUpload final : public XMLHttpRequestEventTarget {
void Trace(blink::Visitor*) override;
private:
- explicit XMLHttpRequestUpload(XMLHttpRequest*);
-
Member<XMLHttpRequest> xml_http_request_;
// Last progress event values; used when issuing the
diff --git a/chromium/third_party/blink/renderer/devtools/BUILD.gn b/chromium/third_party/blink/renderer/devtools/BUILD.gn
index 60a39098d76..4437d101415 100644
--- a/chromium/third_party/blink/renderer/devtools/BUILD.gn
+++ b/chromium/third_party/blink/renderer/devtools/BUILD.gn
@@ -87,8 +87,6 @@ all_devtools_files = [
"front_end/bindings_test_runner/module.json",
"front_end/bindings_test_runner/PersistenceTestRunner.js",
"front_end/bindings_test_runner/OverridesTestRunner.js",
- "front_end/browser_console/BrowserConsole.js",
- "front_end/browser_console/module.json",
"front_end/browser_debugger/DOMBreakpointsSidebarPane.js",
"front_end/browser_debugger/EventListenerBreakpointsSidebarPane.js",
"front_end/browser_debugger/ObjectEventListenersSidebarPane.js",
@@ -662,6 +660,8 @@ all_devtools_files = [
"front_end/source_frame/xmlView.css",
"front_end/source_frame/XMLView.js",
"front_end/sources/AddSourceMapURLDialog.js",
+ "front_end/sources/breakpointEditDialog.css",
+ "front_end/sources/BreakpointEditDialog.js",
"front_end/sources/callStackSidebarPane.css",
"front_end/sources/CallStackSidebarPane.js",
"front_end/sources/CSSPlugin.js",
@@ -1026,7 +1026,6 @@ generated_applications = [
generated_non_autostart_non_remote_modules = [
"$resources_out_dir/animation/animation_module.js",
"$resources_out_dir/audits2/audits2_module.js",
- "$resources_out_dir/browser_console/browser_console_module.js",
"$resources_out_dir/browser_debugger/browser_debugger_module.js",
"$resources_out_dir/changes/changes_module.js",
"$resources_out_dir/protocol_monitor/protocol_monitor_module.js",
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/Images/whatsnew.png b/chromium/third_party/blink/renderer/devtools/front_end/Images/whatsnew.png
index b5121c3e878..47735c156da 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/Images/whatsnew.png
+++ b/chromium/third_party/blink/renderer/devtools/front_end/Images/whatsnew.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/Runtime.js b/chromium/third_party/blink/renderer/devtools/front_end/Runtime.js
index 5e6e5f1a0eb..46698e7727e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/Runtime.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/Runtime.js
@@ -66,8 +66,6 @@ var Runtime = class { // eslint-disable-line
for (let i = 0; i < descriptors.length; ++i)
this._registerModule(descriptors[i]);
-
- Runtime._runtimeReadyPromiseCallback();
}
/**
@@ -237,8 +235,8 @@ var Runtime = class { // eslint-disable-line
/**
* @return {!Promise}
*/
- static async runtimeReady() {
- return Runtime._runtimeReadyPromise;
+ static async appStarted() {
+ return Runtime._appStartedPromise;
}
/**
@@ -289,7 +287,8 @@ var Runtime = class { // eslint-disable-line
}
self.runtime = new Runtime(moduleDescriptors);
if (coreModuleNames)
- return /** @type {!Promise<undefined>} */ (self.runtime._loadAutoStartModules(coreModuleNames));
+ await self.runtime._loadAutoStartModules(coreModuleNames);
+ Runtime._appStartedPromiseCallback();
}
/**
@@ -309,7 +308,7 @@ var Runtime = class { // eslint-disable-line
* @return {?string}
*/
static queryParam(name) {
- return Runtime._queryParamsObject[name] || null;
+ return Runtime._queryParamsObject.get(name);
}
/**
@@ -564,12 +563,8 @@ var Runtime = class { // eslint-disable-line
}
};
-/**
- * @type {!Object.<string, string>}
- */
-Runtime._queryParamsObject = {
- __proto__: null
-};
+/** @type {!URLSearchParams} */
+Runtime._queryParamsObject = new URLSearchParams(Runtime.queryParamsString());
Runtime._instanceSymbol = Symbol('instance');
@@ -1069,26 +1064,12 @@ Runtime.Experiment = class {
}
};
-{
- (function parseQueryParameters() {
- const queryParams = Runtime.queryParamsString();
- if (!queryParams)
- return;
- const params = queryParams.substring(1).split('&');
- for (let i = 0; i < params.length; ++i) {
- const pair = params[i].split('=');
- const name = pair.shift();
- Runtime._queryParamsObject[name] = pair.join('=');
- }
- })();
-}
-
// This must be constructed after the query parameters have been parsed.
Runtime.experiments = new Runtime.ExperimentsSupport();
/** @type {Function} */
-Runtime._runtimeReadyPromiseCallback;
-Runtime._runtimeReadyPromise = new Promise(fulfil => Runtime._runtimeReadyPromiseCallback = fulfil);
+Runtime._appStartedPromiseCallback;
+Runtime._appStartedPromise = new Promise(fulfil => Runtime._appStartedPromiseCallback = fulfil);
/**
* @type {?string}
*/
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/Tests.js b/chromium/third_party/blink/renderer/devtools/front_end/Tests.js
index 574c67c8e39..6fa4ef30d9c 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/Tests.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/Tests.js
@@ -565,7 +565,7 @@
this._waitForTargets(2, callback.bind(this));
function callback() {
- Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
+ Protocol.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
}
};
@@ -591,6 +591,15 @@
}
};
+ TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
+ this.takeControl();
+ this.showPanel('network').then(() => {
+ if (!document.querySelector('#network-container'))
+ this.fail('unable to find #network-container');
+ this.releaseControl();
+ });
+ };
+
TestSuite.prototype.enableTouchEmulation = function() {
const deviceModeModel = new Emulation.DeviceModeModel(function() {});
deviceModeModel._target = SDK.targetManager.mainTarget();
@@ -1169,7 +1178,7 @@
browserContextIds.push(browserContextId);
const {targetId} = await targetAgent.invoke_createTarget({url: 'about:blank', browserContextId});
- await targetAgent.invoke_attachToTarget({targetId});
+ await targetAgent.invoke_attachToTarget({targetId, flatten: true});
const target = SDK.targetManager.targets().find(target => target.id() === targetId);
const pageAgent = target.pageAgent();
@@ -1278,6 +1287,14 @@
});
await testCase(baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=Bar');
+ await SDK.targetManager.mainTarget().runtimeAgent().invoke_evaluate({
+ expression: `fetch("/set-cookie?devtools-test-cookie=same-site-cookie;SameSite=Lax",
+ {credentials: 'include'})`,
+ awaitPromise: true
+ });
+ await testCase(
+ baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie');
+
this.releaseControl();
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js b/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js
index f0c0a2e4ec1..0706be5c305 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js
@@ -507,7 +507,9 @@ Accessibility.AXRelatedNodeElement = class {
if (this._deferredNode) {
valueElement = createElement('span');
element.appendChild(valueElement);
- Common.Linkifier.linkify(this._deferredNode).then(linkfied => valueElement.appendChild(linkfied));
+ this._deferredNode.resolvePromise().then(node => {
+ Common.Linkifier.linkify(node).then(linkfied => valueElement.appendChild(linkfied));
+ });
} else if (this._idref) {
element.classList.add('invalid');
valueElement = Accessibility.AXNodePropertyTreeElement.createExclamationMark(ls`No node with this ID.`);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityStrings.js b/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityStrings.js
index 50d31b2f74c..a6f573bebe9 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityStrings.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityStrings.js
@@ -14,6 +14,10 @@ Accessibility.AccessibilityStrings.AXAttributes = {
description: 'If true, this element\'s user-entered value does not conform to validation requirement.',
group: 'AXGlobalStates'
},
+ 'editable': {name: 'Editable', description: 'If and how this element can be edited.'},
+ 'focusable': {name: 'Focusable', description: 'If true, this element can recieve focus.'},
+ 'focused': {name: 'Focused', description: 'If true, this element currently has focus.'},
+ 'settable': {name: 'Can set value', description: 'Whether the value of this element can be set.'},
'live': {
name: 'Live region',
description: 'Whether and what priority of live updates may be expected for this element.',
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/animation/animationTimeline.css b/chromium/third_party/blink/renderer/devtools/front_end/animation/animationTimeline.css
index 703fb866819..37f109c646e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/animation/animationTimeline.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/animation/animationTimeline.css
@@ -97,7 +97,7 @@ circle.animation-keyframe-point {
display: flex;
background-color: var(--toolbar-bg-color);
border-bottom: var(--divider-border);
- flex: 0 0;
+ flex: 0 0 auto;
}
.animation-timeline-toolbar {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js
index 29d10ccfd4f..a0b90cbf450 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js
@@ -123,6 +123,10 @@ ApplicationTestRunner.addCacheEntry = function(cacheName, requestUrl, responseTe
return TestRunner.callFunctionInPageAsync('addCacheEntry', [cacheName, requestUrl, responseText]);
};
+ApplicationTestRunner.addCacheEntryWithNoCorsRequest = function(cacheName, requestUrl) {
+ return TestRunner.callFunctionInPageAsync('addCacheEntryWithNoCorsRequest', [cacheName, requestUrl]);
+};
+
ApplicationTestRunner.deleteCache = function(cacheName) {
return TestRunner.callFunctionInPageAsync('deleteCache', [cacheName]);
};
@@ -159,6 +163,13 @@ TestRunner.deprecatedInitAsync(`
}).catch(onCacheStorageError);
}
+ function addCacheEntryWithNoCorsRequest(cacheName, requestUrl) {
+ return caches.open(cacheName).then(async function(cache) {
+ let request = new Request(requestUrl, {mode: 'no-cors'});
+ return cache.put(request, await fetch(request));
+ }).catch(onCacheStorageError);
+ }
+
function deleteCache(cacheName) {
return caches.delete(cacheName).then(function(success) {
if (!success)
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js
index b7f4d2f7b74..f83e6d9df15 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js
@@ -25,7 +25,8 @@ ApplicationTestRunner.postToServiceWorker = function(scope, message) {
ApplicationTestRunner.waitForServiceWorker = function(callback) {
function isRightTarget(target) {
- return TestRunner.isDedicatedWorker(target) && TestRunner.isServiceWorker(target.parentTarget());
+ return target.type() === SDK.Target.Type.Worker && target.parentTarget() &&
+ target.parentTarget().type() === SDK.Target.Type.ServiceWorker;
}
SDK.targetManager.observeTargets({
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2Panel.js b/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2Panel.js
index 109d719b702..3ccfd560b32 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2Panel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2Panel.js
@@ -137,9 +137,7 @@ Audits2.Audits2Panel = class extends UI.Panel {
const reportContainer = this._auditResultsElement.createChild('div', 'lh-vars lh-root lh-devtools');
const dom = new DOM(/** @type {!Document} */ (this._auditResultsElement.ownerDocument));
- const detailsRenderer = new Audits2.DetailsRenderer(dom);
- const categoryRenderer = new CategoryRenderer(dom, detailsRenderer);
- const renderer = new Audits2.ReportRenderer(dom, categoryRenderer);
+ const renderer = new Audits2.ReportRenderer(dom);
const templatesHTML = Runtime.cachedResources['audits2/lighthouse/templates.html'];
const templatesDOM = new DOMParser().parseFromString(templatesHTML, 'text/html');
@@ -149,6 +147,7 @@ Audits2.Audits2Panel = class extends UI.Panel {
renderer.setTemplateContext(templatesDOM);
const el = renderer.renderReport(lighthouseResult, reportContainer);
Audits2.ReportRenderer.addViewTraceButton(el, artifacts);
+ Audits2.ReportRenderer.linkifyNodeDetails(el);
this._cachedRenderedReports.set(lighthouseResult, reportContainer);
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ProtocolService.js b/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ProtocolService.js
index 3d3e6759cc2..92ec440c3cd 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ProtocolService.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ProtocolService.js
@@ -5,7 +5,7 @@
Audits2.ProtocolService = class extends Common.Object {
constructor() {
super();
- /** @type {?Protocol.InspectorBackend.Connection} */
+ /** @type {?Protocol.Connection} */
this._rawConnection = null;
/** @type {?Services.ServiceManager.Service} */
this._backend = null;
@@ -19,7 +19,7 @@ Audits2.ProtocolService = class extends Common.Object {
* @return {!Promise<undefined>}
*/
attach() {
- return InspectorMain.interceptMainConnection(this._dispatchProtocolMessage.bind(this)).then(rawConnection => {
+ return SDK.interceptMainConnection(this._dispatchProtocolMessage.bind(this)).then(rawConnection => {
this._rawConnection = rawConnection;
});
}
@@ -53,7 +53,7 @@ Audits2.ProtocolService = class extends Common.Object {
}
/**
- * @param {string} message
+ * @param {!Object|string} message
*/
_dispatchProtocolMessage(message) {
this._send('dispatchProtocolMessage', {message: message});
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ReportRenderer.js b/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ReportRenderer.js
index b8752401657..24030c45944 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ReportRenderer.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/audits2/Audits2ReportRenderer.js
@@ -25,66 +25,44 @@ Audits2.ReportRenderer = class extends ReportRenderer {
Timeline.TimelinePanel.instance().loadFromEvents(defaultPassTrace.traceEvents);
}
}
-};
-class ReportUIFeatures {
/**
- * @param {!ReportRenderer.ReportJSON} report
+ * @param {!Element} el
*/
- initFeatures(report) {
- }
-}
-
-
-Audits2.DetailsRenderer = class extends DetailsRenderer {
- /**
- * @param {!DOM} dom
- */
- constructor(dom) {
- super(dom);
- this._onLoadPromise = null;
- }
-
- /**
- * @override
- * @param {!DetailsRenderer.NodeDetailsJSON} item
- * @return {!Element}
- */
- renderNode(item) {
- const element = super.renderNode(item);
- this._replaceWithDeferredNodeBlock(element, item);
- return element;
- }
-
- /**
- * @param {!Element} origElement
- * @param {!DetailsRenderer.NodeDetailsJSON} detailsItem
- */
- async _replaceWithDeferredNodeBlock(origElement, detailsItem) {
+ static async linkifyNodeDetails(el) {
const mainTarget = SDK.targetManager.mainTarget();
- if (!this._onLoadPromise) {
- const resourceTreeModel = mainTarget.model(SDK.ResourceTreeModel);
- this._onLoadPromise = resourceTreeModel.once(SDK.ResourceTreeModel.Events.Load);
- }
-
- await this._onLoadPromise;
+ const resourceTreeModel = mainTarget.model(SDK.ResourceTreeModel);
+ await resourceTreeModel.once(SDK.ResourceTreeModel.Events.Load);
const domModel = mainTarget.model(SDK.DOMModel);
- if (!detailsItem.path)
- return;
- const nodeId = await domModel.pushNodeByPathToFrontend(detailsItem.path);
+ for (const origElement of el.getElementsByClassName('lh-node')) {
+ /** @type {!DetailsRenderer.NodeDetailsJSON} */
+ const detailsItem = origElement.dataset;
+ if (!detailsItem.path)
+ continue;
- if (!nodeId)
- return;
- const node = domModel.nodeForId(nodeId);
- if (!node)
- return;
+ const nodeId = await domModel.pushNodeByPathToFrontend(detailsItem.path);
- const element =
- await Common.Linkifier.linkify(node, /** @type {!Common.Linkifier.Options} */ ({title: detailsItem.snippet}));
- origElement.title = '';
- origElement.textContent = '';
- origElement.appendChild(element);
+ if (!nodeId)
+ continue;
+ const node = domModel.nodeForId(nodeId);
+ if (!node)
+ continue;
+
+ const element =
+ await Common.Linkifier.linkify(node, /** @type {!Common.Linkifier.Options} */ ({title: detailsItem.snippet}));
+ origElement.title = '';
+ origElement.textContent = '';
+ origElement.appendChild(element);
+ }
}
};
+
+class ReportUIFeatures {
+ /**
+ * @param {!ReportRenderer.ReportJSON} report
+ */
+ initFeatures(report) {
+ }
+}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/audits2/module.json b/chromium/third_party/blink/renderer/devtools/front_end/audits2/module.json
index a99df715f71..b1f07d06d19 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/audits2/module.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/audits2/module.json
@@ -6,7 +6,8 @@
"id": "audits2",
"title": "Audits",
"order": 90,
- "className": "Audits2.Audits2Panel"
+ "className": "Audits2.Audits2Panel",
+ "tags": "lighthouse, pwa"
}
],
"dependencies": [
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/audits2_worker/Audits2Service.js b/chromium/third_party/blink/renderer/devtools/front_end/audits2_worker/Audits2Service.js
index be445dd56db..9d0bfb1a674 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/audits2_worker/Audits2Service.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/audits2_worker/Audits2Service.js
@@ -48,7 +48,7 @@ var Audits2Service = class { // eslint-disable-line
});
return Promise.resolve()
- .then(_ => self.runLighthouseInWorker(this, params.url, {flags: params.flags}, params.categoryIDs))
+ .then(_ => self.runLighthouseInWorker(this, params.url, params.flags, params.categoryIDs))
.then(/** @type {!ReportRenderer.RunnerResult} */ result => {
// Keep all artifacts on the result, no trimming
return result;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js b/chromium/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js
index 7a43e3c6881..22527be29ac 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js
@@ -439,6 +439,10 @@ Bindings.BreakpointManager.Breakpoint = class {
}
_updateBreakpoint() {
+ if (this._uiLocations.size === 0 && this._defaultUILocation)
+ this._breakpointManager._uiLocationRemoved(this, this._defaultUILocation);
+ if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved)
+ this._breakpointManager._uiLocationAdded(this, this._defaultUILocation);
const modelBreakpoints = this._modelBreakpoints.valuesArray();
for (let i = 0; i < modelBreakpoints.length; ++i)
modelBreakpoints[i]._scheduleUpdateInDebugger();
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js b/chromium/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js
index 846be51b0a1..44c4d83c6df 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js
@@ -211,8 +211,10 @@ Bindings.CompilerScriptMapping = class {
const sourceMap = /** @type {!SDK.SourceMap} */ (event.data.sourceMap);
this._removeStubUISourceCode(script);
- if (Bindings.blackboxManager.isBlackboxedURL(script.sourceURL, script.isContentScript()))
+ if (Bindings.blackboxManager.isBlackboxedURL(script.sourceURL, script.isContentScript())) {
+ this._sourceMapAttachedForTest(sourceMap);
return;
+ }
this._populateSourceMapSources(script, sourceMap);
this._sourceMapAttachedForTest(sourceMap);
@@ -228,9 +230,11 @@ Bindings.CompilerScriptMapping = class {
const bindings = script.isContentScript() ? this._contentScriptsBindings : this._regularBindings;
for (const sourceURL of sourceMap.sourceURLs()) {
const binding = bindings.get(sourceURL);
- binding.removeSourceMap(sourceMap, frameId);
- if (!binding._uiSourceCode)
- bindings.delete(sourceURL);
+ if (binding) {
+ binding.removeSourceMap(sourceMap, frameId);
+ if (!binding._uiSourceCode)
+ bindings.delete(sourceURL);
+ }
}
this._debuggerWorkspaceBinding.updateLocations(script);
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/browser_console/BrowserConsole.js b/chromium/third_party/blink/renderer/devtools/front_end/browser_console/BrowserConsole.js
deleted file mode 100644
index a98df127fc4..00000000000
--- a/chromium/third_party/blink/renderer/devtools/front_end/browser_console/BrowserConsole.js
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/**
- * @implements {Common.Renderer}
- * @implements {UI.ContextMenu.Provider}
- */
-BrowserConsole.BrowserConsole = class {
- /**
- * @override
- * @param {!Event} event
- * @param {!UI.ContextMenu} contextMenu
- * @param {!Object} object
- */
- appendApplicableItems(event, contextMenu, object) {
- const consoleMessage = /** @type {!SDK.ConsoleMessage} */ (object);
- const request = SDK.NetworkLog.requestForConsoleMessage(consoleMessage);
- if (request && SDK.NetworkManager.canReplayRequest(request)) {
- contextMenu.debugSection().appendItem(
- Common.UIString('Replay XHR'), SDK.NetworkManager.replayRequest.bind(null, request));
- }
- }
-
- /**
- * @override
- * @param {!Object} object
- * @param {!Common.Renderer.Options} options
- * @return {!Promise.<?Node>}
- */
- render(object, options) {
- const consoleMessage = /** @type {!SDK.ConsoleMessage} */ (object);
- const request = SDK.NetworkLog.requestForConsoleMessage(consoleMessage);
- let messageElement = null;
- if (request) {
- messageElement = createElement('span');
- if (consoleMessage.level === SDK.ConsoleMessage.MessageLevel.Error) {
- messageElement.createTextChild(request.requestMethod + ' ');
- messageElement.appendChild(Components.Linkifier.linkifyRevealable(request, request.url(), request.url()));
- if (request.failed)
- messageElement.createTextChildren(' ', request.localizedFailDescription);
- if (request.statusCode !== 0)
- messageElement.createTextChildren(' ', String(request.statusCode));
- if (request.statusText)
- messageElement.createTextChildren(' (', request.statusText, ')');
- } else {
- const fragment = Console.ConsoleViewMessage.linkifyWithCustomLinkifier(
- consoleMessage.messageText,
- title => Components.Linkifier.linkifyRevealable(
- /** @type {!SDK.NetworkRequest} */ (request), title, request.url()));
- messageElement.appendChild(fragment);
- }
- }
- return Promise.resolve(/** @type {?Node} */ (messageElement));
- }
-};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/browser_console/module.json b/chromium/third_party/blink/renderer/devtools/front_end/browser_console/module.json
deleted file mode 100644
index 7dbf71b37a0..00000000000
--- a/chromium/third_party/blink/renderer/devtools/front_end/browser_console/module.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "extensions": [
- {
- "type": "@UI.ContextMenu.Provider",
- "contextTypes": [
- "SDK.ConsoleMessage"
- ],
- "className": "BrowserConsole.BrowserConsole"
- },
- {
- "type": "@Common.Renderer",
- "contextTypes": [
- "SDK.ConsoleMessage"
- ],
- "source": "network",
- "className": "BrowserConsole.BrowserConsole"
- }
- ],
- "dependencies": [
- "browser_sdk",
- "console"
- ],
- "scripts": [
- "BrowserConsole.js"
- ]
-}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/cm/README.md b/chromium/third_party/blink/renderer/devtools/front_end/cm/README.md
index 68f53037d54..cd6130f90b5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/cm/README.md
+++ b/chromium/third_party/blink/renderer/devtools/front_end/cm/README.md
@@ -14,7 +14,7 @@ construction. This is needed to support in web workers.
## Testing
DevTools wrap CodeMirror via `CodeMirrorTextEditor.js` and `cmdevtools.css` files.
-Although there are a couple of automated tests (LayoutTests/inspector/editor/) to verify overall sanity of the setup, a manual testing is mandatory before
+Although there are a couple of automated tests (web_tests/inspector/editor/) to verify overall sanity of the setup, a manual testing is mandatory before
landing a roll. Here is a rough testing scenario outline:
1. Create a new snippet and type in a small function with a few nested for-loops. (The author suggests a bubble-sort). Make sure that:
* Words `function`, `for`, `var` are highlighted
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/common/ModuleExtensionInterfaces.js b/chromium/third_party/blink/renderer/devtools/front_end/common/ModuleExtensionInterfaces.js
index cdc0dd3b146..6d88d494a99 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/common/ModuleExtensionInterfaces.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/common/ModuleExtensionInterfaces.js
@@ -5,37 +5,6 @@
/**
* @interface
*/
-Common.Renderer = function() {};
-
-Common.Renderer.prototype = {
- /**
- * @param {!Object} object
- * @param {!Common.Renderer.Options} options
- * @return {!Promise.<?Node>}
- */
- render(object, options) {}
-};
-
-/**
- * @param {?Object} object
- * @param {!Common.Renderer.Options=} options
- * @return {!Promise.<?Node>}
- */
-Common.Renderer.render = function(object, options) {
- if (!object)
- return Promise.reject(new Error('Can\'t render ' + object));
- return self.runtime.extension(Common.Renderer, object)
- .instance()
- .then(renderer => renderer.render(object, options || {}));
-};
-
-/** @typedef {!{title: (string|!Element|undefined), expanded: (boolean|undefined),
- * editable: (boolean|undefined) }} */
-Common.Renderer.Options;
-
-/**
- * @interface
- */
Common.Revealer = function() {};
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/common/ResourceType.js b/chromium/third_party/blink/renderer/devtools/front_end/common/ResourceType.js
index ebc106c12ec..5366548b7f5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/common/ResourceType.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/common/ResourceType.js
@@ -79,6 +79,19 @@ Common.ResourceType = class {
}
/**
+ * @param {string} name
+ * @return {?Common.ResourceType}
+ */
+ static fromName(name) {
+ for (const resourceTypeId in Common.resourceTypes) {
+ const resourceType = Common.resourceTypes[resourceTypeId];
+ if (resourceType.name() === name)
+ return resourceType;
+ }
+ return null;
+ }
+
+ /**
* @param {string} url
* @return {string|undefined}
*/
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js b/chromium/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js
index 9ad19488ade..05753751de3 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js
@@ -35,7 +35,7 @@ Components.JSPresentationUtils = {};
* @param {!Components.Linkifier} linkifier
* @param {!Protocol.Runtime.StackTrace=} stackTrace
* @param {function()=} contentUpdated
- * @return {!Element}
+ * @return {{element: !Element, links: !Array<!Element>}}
*/
Components.JSPresentationUtils.buildStackTracePreviewContents = function(
target, linkifier, stackTrace, contentUpdated) {
@@ -44,6 +44,8 @@ Components.JSPresentationUtils.buildStackTracePreviewContents = function(
const shadowRoot = UI.createShadowRootWithCoreStyles(element, 'components/jsUtils.css');
const contentElement = shadowRoot.createChild('table', 'stack-preview-container');
let totalHiddenCallFramesCount = 0;
+ /** @type {!Array<!Element>} */
+ const links = [];
/**
* @param {!Protocol.Runtime.StackTrace} stackTrace
@@ -65,6 +67,7 @@ Components.JSPresentationUtils.buildStackTracePreviewContents = function(
}
row.createChild('td').textContent = ' @ ';
row.createChild('td').appendChild(link);
+ links.push(link);
}
contentElement.appendChild(row);
}
@@ -94,7 +97,7 @@ Components.JSPresentationUtils.buildStackTracePreviewContents = function(
}
if (!stackTrace)
- return element;
+ return {element, links};
appendStackTrace(stackTrace);
@@ -132,5 +135,5 @@ Components.JSPresentationUtils.buildStackTracePreviewContents = function(
}, false);
}
- return element;
+ return {element, links};
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/components/Linkifier.js b/chromium/third_party/blink/renderer/devtools/front_end/components/Linkifier.js
index 61f6cbf431d..c4845c3a860 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/components/Linkifier.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/components/Linkifier.js
@@ -402,10 +402,18 @@ Components.Linkifier = class {
revealable: null,
fallback: null
};
- if (!preventClick)
- link.addEventListener('click', Components.Linkifier._handleClick, false);
- else
+ if (!preventClick) {
+ link.addEventListener('click', event => {
+ if (Components.Linkifier._handleClick(event))
+ event.consume(true);
+ }, false);
+ link.addEventListener('keydown', event => {
+ if (isEnterKey(event) && Components.Linkifier._handleClick(event))
+ event.consume(true);
+ }, false);
+ } else {
link.classList.add('devtools-link-prevent-click');
+ }
return link;
}
@@ -486,15 +494,18 @@ Components.Linkifier = class {
/**
* @param {!Event} event
+ * @return {boolean}
*/
static _handleClick(event) {
const link = /** @type {!Element} */ (event.currentTarget);
- event.consume(true);
if (UI.isBeingEdited(/** @type {!Node} */ (event.target)) || link.hasSelection())
- return;
+ return false;
const actions = Components.Linkifier._linkActions(link);
- if (actions.length)
+ if (actions.length) {
actions[0].handler.call(null);
+ return true;
+ }
+ return false;
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js
index 56afa11c4f4..6ff70fcfda7 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js
@@ -107,13 +107,12 @@ Console.ConsoleContextSelector = class {
}
let targetDepth = 0;
while (target.parentTarget()) {
- if (target.parentTarget().hasJSCapability()) {
- targetDepth++;
- } else {
+ if (target.parentTarget().type() === SDK.Target.Type.ServiceWorker) {
// Special casing service workers to be top-level.
targetDepth = 0;
break;
}
+ targetDepth++;
target = target.parentTarget();
}
depth += targetDepth;
@@ -153,7 +152,7 @@ Console.ConsoleContextSelector = class {
_executionContextCreated(executionContext) {
// FIXME(413886): We never want to show execution context for the main thread of shadow page in service/shared worker frontend.
// This check could be removed once we do not send this context to frontend.
- if (!executionContext.target().hasJSCapability())
+ if (executionContext.target().type() === SDK.Target.Type.ServiceWorker)
return;
this._items.insertWithComparator(executionContext, executionContext.runtimeModel.executionContextComparator());
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js
index 182b9780cd1..bf930bf1564 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js
@@ -163,6 +163,7 @@ Console.ConsolePin = class extends Common.Object {
this._editor.setText(trimmedText);
this._committedExpression = trimmedText;
pinPane._savePins();
+ this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity, Infinity));
});
});
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js
index 08f4030a53c..ef800623754 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js
@@ -20,6 +20,10 @@ Console.ConsolePrompt = class extends UI.Widget {
this._innerPreviewElement = this._eagerPreviewElement.createChild('div', 'console-eager-inner-preview');
this._eagerPreviewElement.appendChild(UI.Icon.create('smallicon-command-result', 'preview-result-icon'));
+ const editorContainerElement = this.element.createChild('div', 'console-prompt-editor-container');
+ if (this._isBelowPromptEnabled)
+ this.element.appendChild(this._eagerPreviewElement);
+
this._eagerEvalSetting = Common.settings.moduleSetting('consoleEagerEval');
this._eagerEvalSetting.addChangeListener(this._eagerSettingChanged.bind(this));
this._eagerPreviewElement.classList.toggle('hidden', !this._eagerEvalSetting.get());
@@ -50,11 +54,9 @@ Console.ConsolePrompt = class extends UI.Widget {
UI.GlassPane.AnchorBehavior.PreferBottom
}));
this._editor.widget().element.addEventListener('keydown', this._editorKeyDown.bind(this), true);
- this._editor.widget().show(this.element);
+ this._editor.widget().show(editorContainerElement);
this._editor.addEventListener(UI.TextEditor.Events.TextChanged, this._onTextChanged, this);
this._editor.addEventListener(UI.TextEditor.Events.SuggestionChanged, this._onTextChanged, this);
- if (this._isBelowPromptEnabled)
- this.element.appendChild(this._eagerPreviewElement);
this.setText(this._initialText);
delete this._initialText;
@@ -239,6 +241,8 @@ Console.ConsolePrompt = class extends UI.Widget {
event.consume(true);
+ // Since we prevent default, manually emulate the native "scroll on key input" behavior.
+ this.element.scrollIntoView();
this.clearAutocomplete();
const str = this.text();
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js
index 02091ddf93d..0579fff41ce 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js
@@ -679,8 +679,11 @@ Console.ConsoleView = class extends UI.VBox {
Common.UIString('Copy visible styled selection'), this._viewport.copyWithStyles.bind(this._viewport));
}
- if (consoleMessage)
- contextMenu.appendApplicableItems(consoleMessage);
+ if (consoleMessage) {
+ const request = SDK.NetworkLog.requestForConsoleMessage(consoleMessage);
+ if (request && SDK.NetworkManager.canReplayRequest(request))
+ contextMenu.debugSection().appendItem(ls`Replay XHR`, SDK.NetworkManager.replayRequest.bind(null, request));
+ }
contextMenu.show();
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js
index 7ab961e9b90..19a988e3162 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js
@@ -45,8 +45,8 @@ Console.ConsoleViewMessage = class {
this._repeatCount = 1;
this._closeGroupDecorationCount = 0;
this._nestingLevel = nestingLevel;
- /** @type {!Array<!ObjectUI.ObjectPropertiesSection>} */
- this._focusableChildren = [];
+ /** @type {!Array<{element: !Element, selectFirst: function()}>} */
+ this._selectableChildren = [];
/** @type {?DataGrid.DataGrid} */
this._dataGrid = null;
@@ -68,16 +68,6 @@ Console.ConsoleViewMessage = class {
}
/**
- * @return {!Promise<!Element>}
- */
- async completeElementForTest() {
- const element = this.toMessageElement();
- if (this._completeElementForTestPromise)
- await this._completeElementForTestPromise;
- return element;
- }
-
- /**
* @override
*/
wasShown() {
@@ -141,7 +131,7 @@ Console.ConsoleViewMessage = class {
if (table)
table = this._parameterToRemoteObject(table);
if (!table || !table.preview)
- return formattedMessage;
+ return this._buildMessage();
const rawValueColumnSymbol = Symbol('rawValueColumn');
const columnNames = [];
@@ -250,23 +240,9 @@ Console.ConsoleViewMessage = class {
}
}
} else {
- let rendered = false;
- this._completeElementForTestPromise = null;
- for (const extension of self.runtime.extensions(Common.Renderer, this._message)) {
- if (extension.descriptor()['source'] === this._message.source) {
- messageElement = createElement('span');
- let callback;
- this._completeElementForTestPromise = new Promise(fulfill => callback = fulfill);
- extension.instance().then(renderer => {
- renderer.render(this._message)
- .then(element => messageElement.appendChild(element || this._format([messageText])))
- .then(callback);
- });
- rendered = true;
- break;
- }
- }
- if (!rendered) {
+ if (this._message.source === SDK.ConsoleMessage.MessageSource.Network) {
+ messageElement = this._formatAsNetworkRequest() || this._format([messageText]);
+ } else {
const messageInParameters =
this._message.parameters && messageText === /** @type {string} */ (this._message.parameters[0]);
if (this._message.source === SDK.ConsoleMessage.MessageSource.Violation)
@@ -297,6 +273,40 @@ Console.ConsoleViewMessage = class {
/**
* @return {?Element}
*/
+ _formatAsNetworkRequest() {
+ const request = SDK.NetworkLog.requestForConsoleMessage(this._message);
+ if (!request)
+ return null;
+ const messageElement = createElement('span');
+ if (this._message.level === SDK.ConsoleMessage.MessageLevel.Error) {
+ messageElement.createTextChild(request.requestMethod + ' ');
+ const linkElement = Components.Linkifier.linkifyRevealable(request, request.url(), request.url());
+ // Focus is handled by the viewport.
+ linkElement.tabIndex = -1;
+ this._selectableChildren.push({element: linkElement, selectFirst: () => linkElement.focus()});
+ messageElement.appendChild(linkElement);
+ if (request.failed)
+ messageElement.createTextChildren(' ', request.localizedFailDescription);
+ if (request.statusCode !== 0)
+ messageElement.createTextChildren(' ', String(request.statusCode));
+ if (request.statusText)
+ messageElement.createTextChildren(' (', request.statusText, ')');
+ } else {
+ const fragment = this._linkifyWithCustomLinkifier(this._message.messageText, title => {
+ const linkElement = Components.Linkifier.linkifyRevealable(
+ /** @type {!SDK.NetworkRequest} */ (request), title, request.url());
+ linkElement.tabIndex = -1;
+ this._selectableChildren.push({element: linkElement, selectFirst: () => linkElement.focus()});
+ return linkElement;
+ });
+ messageElement.appendChild(fragment);
+ }
+ return messageElement;
+ }
+
+ /**
+ * @return {?Element}
+ */
_buildMessageAnchor() {
let anchorElement = null;
if (this._message.scriptId) {
@@ -380,7 +390,11 @@ Console.ConsoleViewMessage = class {
const stackTraceElement = contentElement.createChild('div');
const stackTracePreview = Components.JSPresentationUtils.buildStackTracePreviewContents(
this._message.runtimeModel().target(), this._linkifier, this._message.stackTrace);
- stackTraceElement.appendChild(stackTracePreview);
+ stackTraceElement.appendChild(stackTracePreview.element);
+ for (const linkElement of stackTracePreview.links) {
+ linkElement.tabIndex = -1;
+ this._selectableChildren.push({element: linkElement, selectFirst: () => linkElement.focus()});
+ }
stackTraceElement.classList.add('hidden');
this._expandTrace = expand => {
icon.setIconType(expand ? 'smallicon-triangle-down' : 'smallicon-triangle-right');
@@ -495,7 +509,7 @@ Console.ConsoleViewMessage = class {
for (let i = 0; i < parameters.length; ++i) {
// Inline strings when formatting.
if (shouldFormatMessage && parameters[i].type === 'string')
- formattedResult.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(parameters[i].description));
+ formattedResult.appendChild(this._linkifyStringAsFragment(parameters[i].description));
else
formattedResult.appendChild(this._formatParameter(parameters[i], false, true));
if (i < parameters.length - 1)
@@ -610,7 +624,8 @@ Console.ConsoleViewMessage = class {
const section = new ObjectUI.ObjectPropertiesSection(obj, titleElement, this._linkifier);
section.element.classList.add('console-view-object-properties-section');
section.enableContextMenu();
- this._focusableChildren.push(section);
+ section.setShowSelectionOnKeyboardFocus(true, true);
+ this._selectableChildren.push(section);
return section.element;
}
@@ -673,18 +688,20 @@ Console.ConsoleViewMessage = class {
const domModel = remoteObject.runtimeModel().target().model(SDK.DOMModel);
if (!domModel)
return result;
- domModel.pushObjectAsNodeToFrontend(remoteObject).then(node => {
+ domModel.pushObjectAsNodeToFrontend(remoteObject).then(async node => {
if (!node) {
result.appendChild(this._formatParameterAsObject(remoteObject, false));
return;
}
- Common.Renderer.render(node).then(rendererNode => {
- if (rendererNode)
- result.appendChild(rendererNode);
- else
- result.appendChild(this._formatParameterAsObject(remoteObject, false));
- this._formattedParameterAsNodeForTest();
- });
+ const renderResult = await UI.Renderer.render(/** @type {!Object} */ (node));
+ if (renderResult) {
+ if (renderResult.tree)
+ this._selectableChildren.push(renderResult.tree);
+ result.appendChild(renderResult.node);
+ } else {
+ result.appendChild(this._formatParameterAsObject(remoteObject, false));
+ }
+ this._formattedParameterAsNodeForTest();
});
return result;
@@ -699,7 +716,7 @@ Console.ConsoleViewMessage = class {
*/
_formatParameterAsString(output) {
const span = createElement('span');
- span.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(output.description || ''));
+ span.appendChild(this._linkifyStringAsFragment(output.description || ''));
const result = createElement('span');
result.createChild('span', 'object-value-string-quote').textContent = '"';
@@ -715,8 +732,7 @@ Console.ConsoleViewMessage = class {
_formatParameterAsError(output) {
const result = createElement('span');
const errorSpan = this._tryFormatAsError(output.description || '');
- result.appendChild(
- errorSpan ? errorSpan : Console.ConsoleViewMessage._linkifyStringAsFragment(output.description || ''));
+ result.appendChild(errorSpan ? errorSpan : this._linkifyStringAsFragment(output.description || ''));
return result;
}
@@ -869,13 +885,13 @@ Console.ConsoleViewMessage = class {
if (typeof b === 'undefined')
return a;
if (!currentStyle) {
- a.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(String(b)));
+ a.appendChild(this._linkifyStringAsFragment(String(b)));
return a;
}
const lines = String(b).split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
- const lineFragment = Console.ConsoleViewMessage._linkifyStringAsFragment(line);
+ const lineFragment = this._linkifyStringAsFragment(line);
const wrapper = createElement('span');
wrapper.style.setProperty('contain', 'paint');
wrapper.style.setProperty('display', 'inline-block');
@@ -1041,9 +1057,9 @@ Console.ConsoleViewMessage = class {
* @return {number}
*/
_focusedChildIndex() {
- if (!this._focusableChildren.length)
+ if (!this._selectableChildren.length)
return -1;
- return this._focusableChildren.findIndex(child => child.element.hasFocus());
+ return this._selectableChildren.findIndex(child => child.element.hasFocus());
}
/**
@@ -1070,7 +1086,7 @@ Console.ConsoleViewMessage = class {
return true;
}
}
- if (!this._focusableChildren.length)
+ if (!this._selectableChildren.length)
return false;
if (event.key === 'ArrowLeft') {
@@ -1078,46 +1094,63 @@ Console.ConsoleViewMessage = class {
return true;
}
if (event.key === 'ArrowRight') {
- if (isWrapperFocused) {
- this._focusChild(0);
+ if (isWrapperFocused && this._selectNearestVisibleChild(0))
return true;
- }
}
if (event.key === 'ArrowUp') {
- if (focusedChildIndex === 0) {
+ const firstVisibleChild = this._nearestVisibleChild(0);
+ if (this._selectableChildren[focusedChildIndex] === firstVisibleChild && firstVisibleChild) {
this._element.focus();
return true;
- } else if (focusedChildIndex > 0) {
- this._focusChild(focusedChildIndex - 1);
+ } else if (this._selectNearestVisibleChild(focusedChildIndex - 1, true /* backwards */)) {
return true;
}
}
if (event.key === 'ArrowDown') {
- if (isWrapperFocused) {
- this._focusChild(0);
+ if (isWrapperFocused && this._selectNearestVisibleChild(0))
return true;
- } else if (focusedChildIndex < this._focusableChildren.length - 1) {
- this._focusChild(focusedChildIndex + 1);
+ if (!isWrapperFocused && this._selectNearestVisibleChild(focusedChildIndex + 1))
return true;
- }
}
return false;
}
/**
- * @param {number} index
+ * @param {number} fromIndex
+ * @param {boolean=} backwards
+ * @return {boolean}
*/
- _focusChild(index) {
- const section = this._focusableChildren[index];
- if (!section.objectTreeElement().selected)
- section.objectTreeElement().select();
- section.focus();
+ _selectNearestVisibleChild(fromIndex, backwards) {
+ const nearestChild = this._nearestVisibleChild(fromIndex, backwards);
+ if (nearestChild) {
+ nearestChild.selectFirst();
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @param {number} fromIndex
+ * @param {boolean=} backwards
+ * @return {?{element: !Element, selectFirst: function()}}
+ */
+ _nearestVisibleChild(fromIndex, backwards) {
+ const childCount = this._selectableChildren.length;
+ if (fromIndex < 0 || fromIndex >= childCount)
+ return null;
+ const direction = backwards ? -1 : 1;
+ let index = fromIndex;
+
+ while (!this._selectableChildren[index].element.offsetParent) {
+ index += direction;
+ if (index < 0 || index >= childCount)
+ return null;
+ }
+ return this._selectableChildren[index];
}
focusLastChildOrSelf() {
- if (this._focusableChildren.length)
- this._focusChild(this._focusableChildren.length - 1);
- else if (this._element)
+ if (this._element && !this._selectNearestVisibleChild(this._selectableChildren.length - 1, true /* backwards */))
this._element.focus();
}
@@ -1443,15 +1476,17 @@ Console.ConsoleViewMessage = class {
const formattedResult = createElement('span');
let start = 0;
for (let i = 0; i < links.length; ++i) {
- formattedResult.appendChild(
- Console.ConsoleViewMessage._linkifyStringAsFragment(string.substring(start, links[i].positionLeft)));
- formattedResult.appendChild(this._linkifier.linkifyScriptLocation(
- debuggerModel.target(), null, links[i].url, links[i].lineNumber, links[i].columnNumber));
+ formattedResult.appendChild(this._linkifyStringAsFragment(string.substring(start, links[i].positionLeft)));
+ const scriptLocationLink = this._linkifier.linkifyScriptLocation(
+ debuggerModel.target(), null, links[i].url, links[i].lineNumber, links[i].columnNumber);
+ scriptLocationLink.tabIndex = -1;
+ this._selectableChildren.push({element: scriptLocationLink, selectFirst: () => scriptLocationLink.focus()});
+ formattedResult.appendChild(scriptLocationLink);
start = links[i].positionRight;
}
if (start !== string.length)
- formattedResult.appendChild(Console.ConsoleViewMessage._linkifyStringAsFragment(string.substring(start)));
+ formattedResult.appendChild(this._linkifyStringAsFragment(string.substring(start)));
return formattedResult;
@@ -1476,12 +1511,14 @@ Console.ConsoleViewMessage = class {
* @param {function(string,string,number=,number=):!Node} linkifier
* @return {!DocumentFragment}
*/
- static linkifyWithCustomLinkifier(string, linkifier) {
+ _linkifyWithCustomLinkifier(string, linkifier) {
if (string.length > Console.ConsoleViewMessage._MaxTokenizableStringLength)
return UI.createExpandableText(string, Console.ConsoleViewMessage._LongStringVisibleLength);
const container = createDocumentFragment();
- const tokens = this._tokenizeMessageText(string);
+ const tokens = Console.ConsoleViewMessage._tokenizeMessageText(string);
for (const token of tokens) {
+ if (!token.text)
+ continue;
switch (token.type) {
case 'url': {
const realURL = (token.text.startsWith('www.') ? 'http://' + token.text : token.text);
@@ -1506,9 +1543,12 @@ Console.ConsoleViewMessage = class {
* @param {string} string
* @return {!DocumentFragment}
*/
- static _linkifyStringAsFragment(string) {
- return Console.ConsoleViewMessage.linkifyWithCustomLinkifier(string, (text, url, lineNumber, columnNumber) => {
- return Components.Linkifier.linkifyURL(url, {text, lineNumber, columnNumber});
+ _linkifyStringAsFragment(string) {
+ return this._linkifyWithCustomLinkifier(string, (text, url, lineNumber, columnNumber) => {
+ const linkElement = Components.Linkifier.linkifyURL(url, {text, lineNumber, columnNumber});
+ linkElement.tabIndex = -1;
+ this._selectableChildren.push({element: linkElement, selectFirst: () => linkElement.focus()});
+ return linkElement;
});
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js
index f1ea217ef04..5b93a99f516 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js
@@ -127,11 +127,14 @@ Console.ConsoleViewport = class {
const renderedIndex = this._renderedItems.findIndex(item => item.element().isSelfOrAncestor(event.target));
if (renderedIndex !== -1)
this._virtualSelectedIndex = this._firstActiveIndex + renderedIndex;
+ let focusLastChild = false;
// Make default selection when moving from external (e.g. prompt) to the container.
if (this._virtualSelectedIndex === -1 && this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)) &&
- event.target === this._contentElement)
+ event.target === this._contentElement) {
+ focusLastChild = true;
this._virtualSelectedIndex = this._itemCount - 1;
- this._updateFocusedItem();
+ }
+ this._updateFocusedItem(focusLastChild);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console/consoleView.css b/chromium/third_party/blink/renderer/devtools/front_end/console/consoleView.css
index 58ba9435ccf..1bebaf91a5e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console/consoleView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console/consoleView.css
@@ -88,7 +88,10 @@
clear: right;
position: relative;
margin: 0 22px 0 20px;
- min-height: 18px; /* Sync with ConsoleViewMessage.js */
+}
+
+.console-prompt-editor-container {
+ min-height: 21px;
}
.console-message,
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js
index aea6002d6e4..d4d78c8a50e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js
@@ -20,14 +20,6 @@ ConsoleTestRunner.dumpConsoleMessages = function(printOriginatingCommand, dumpCl
ConsoleTestRunner.dumpConsoleMessagesIntoArray(printOriginatingCommand, dumpClassNames, formatter));
};
-ConsoleTestRunner.renderCompleteMessages = async function() {
- const consoleView = Console.ConsoleView.instance();
- if (consoleView._needsFullUpdate)
- consoleView._updateMessageList();
- const viewMessages = consoleView._visibleViewMessages;
- await Promise.all(viewMessages.map(uiMessage => uiMessage.completeElementForTest()));
-};
-
/**
* @param {boolean=} printOriginatingCommand
* @param {boolean=} dumpClassNames
@@ -536,7 +528,7 @@ ConsoleTestRunner.waitForConsoleMessages = function(expectedCount, callback) {
*/
ConsoleTestRunner.waitForConsoleMessagesPromise = async function(expectedCount) {
await new Promise(fulfill => ConsoleTestRunner.waitForConsoleMessages(expectedCount, fulfill));
- return ConsoleTestRunner.renderCompleteMessages();
+ return ConsoleTestRunner.waitForPendingViewportUpdates();
};
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/coverage/coverageView.css b/chromium/third_party/blink/renderer/devtools/front_end/coverage/coverageView.css
index 816ef2abd6f..7efd15d3bc9 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/coverage/coverageView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/coverage/coverageView.css
@@ -11,7 +11,7 @@
.coverage-toolbar-container {
display: flex;
border-bottom: 1px solid #ccc;
- flex: 0 0;
+ flex: 0 0 auto;
}
.coverage-toolbar {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/devtools_app.json b/chromium/third_party/blink/renderer/devtools/front_end/devtools_app.json
index 02e578e0178..40f67e9ee0d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/devtools_app.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/devtools_app.json
@@ -7,7 +7,6 @@
{ "name": "accessibility", "type": "remote" },
{ "name": "animation" },
{ "name": "audits2" },
- { "name": "browser_console" },
{ "name": "browser_debugger" },
{ "name": "cookie_table" },
{ "name": "devices" },
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js b/chromium/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js
index 4489c397916..1319616f3ac 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js
@@ -1166,30 +1166,34 @@
}
function installBackwardsCompatibility() {
- if (window.location.href.indexOf('/remote/') === -1)
+ const majorVersion = getRemoteMajorVersion();
+ if (!majorVersion)
return;
- // Support for legacy (<M65) frontends.
- /** @type {(!function(number, number):Element|undefined)} */
- ShadowRoot.prototype.__originalShadowRootElementFromPoint;
+ /** @type {!Array<string>} */
+ const styleRules = [];
- if (!ShadowRoot.prototype.__originalShadowRootElementFromPoint) {
- ShadowRoot.prototype.__originalShadowRootElementFromPoint = ShadowRoot.prototype.elementFromPoint;
- /**
- * @param {number} x
- * @param {number} y
- * @return {Element}
- */
- ShadowRoot.prototype.elementFromPoint = function(x, y) {
- const originalResult = ShadowRoot.prototype.__originalShadowRootElementFromPoint.apply(this, arguments);
- if (this.host && originalResult === this.host)
- return null;
- return originalResult;
- };
+ if (majorVersion <= 66) {
+ /** @type {(!function(number, number):Element|undefined)} */
+ ShadowRoot.prototype.__originalShadowRootElementFromPoint;
+
+ if (!ShadowRoot.prototype.__originalShadowRootElementFromPoint) {
+ ShadowRoot.prototype.__originalShadowRootElementFromPoint = ShadowRoot.prototype.elementFromPoint;
+ /**
+ * @param {number} x
+ * @param {number} y
+ * @return {Element}
+ */
+ ShadowRoot.prototype.elementFromPoint = function(x, y) {
+ const originalResult = ShadowRoot.prototype.__originalShadowRootElementFromPoint.apply(this, arguments);
+ if (this.host && originalResult === this.host)
+ return null;
+ return originalResult;
+ };
+ }
}
- // Support for legacy (<M53) frontends.
- if (!window.KeyboardEvent.prototype.hasOwnProperty('keyIdentifier')) {
+ if (majorVersion <= 53) {
Object.defineProperty(window.KeyboardEvent.prototype, 'keyIdentifier', {
/**
* @return {string}
@@ -1201,63 +1205,112 @@
});
}
- // Support for legacy (<M50) frontends.
- installObjectObserve();
+ if (majorVersion <= 50)
+ installObjectObserve();
- /**
- * @param {string} property
- * @return {!CSSValue|null}
- * @this {CSSStyleDeclaration}
- */
- function getValue(property) {
- // Note that |property| comes from another context, so we can't use === here.
- // eslint-disable-next-line eqeqeq
- if (property == 'padding-left') {
- return /** @type {!CSSValue} */ ({
- /**
- * @return {number}
- * @this {!{__paddingLeft: number}}
- */
- getFloatValue: function() {
- return this.__paddingLeft;
- },
- __paddingLeft: parseFloat(this.paddingLeft)
- });
+ if (majorVersion <= 45) {
+ /**
+ * @param {string} property
+ * @return {!CSSValue|null}
+ * @this {CSSStyleDeclaration}
+ */
+ function getValue(property) {
+ // Note that |property| comes from another context, so we can't use === here.
+ // eslint-disable-next-line eqeqeq
+ if (property == 'padding-left') {
+ return /** @type {!CSSValue} */ ({
+ /**
+ * @return {number}
+ * @this {!{__paddingLeft: number}}
+ */
+ getFloatValue: function() {
+ return this.__paddingLeft;
+ },
+ __paddingLeft: parseFloat(this.paddingLeft)
+ });
+ }
+ throw new Error('getPropertyCSSValue is undefined');
}
- throw new Error('getPropertyCSSValue is undefined');
+
+ window.CSSStyleDeclaration.prototype.getPropertyCSSValue = getValue;
+
+ function CSSPrimitiveValue() {
+ }
+ CSSPrimitiveValue.CSS_PX = 5;
+ window.CSSPrimitiveValue = CSSPrimitiveValue;
}
- // Support for legacy (<M41) frontends.
- window.CSSStyleDeclaration.prototype.getPropertyCSSValue = getValue;
+ if (majorVersion <= 45)
+ styleRules.push('* { min-width: 0; min-height: 0; }');
- function CSSPrimitiveValue() {
+ if (majorVersion <= 51) {
+ // Support for quirky border-image behavior (<M51), see:
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=559258
+ styleRules.push('.cm-breakpoint .CodeMirror-linenumber { border-style: solid !important; }');
+ styleRules.push(
+ '.cm-breakpoint.cm-breakpoint-conditional .CodeMirror-linenumber { border-style: solid !important; }');
+ }
+ if (majorVersion <= 71) {
+ styleRules.push(
+ '.coverage-toolbar-container, .animation-timeline-toolbar-container, .computed-properties { flex-basis: auto; }');
}
- CSSPrimitiveValue.CSS_PX = 5;
- window.CSSPrimitiveValue = CSSPrimitiveValue;
- // Support for legacy (<M44) frontends.
- const styleElement = window.document.createElement('style');
- styleElement.type = 'text/css';
- styleElement.textContent = 'html /deep/ * { min-width: 0; min-height: 0; }';
+ if (majorVersion <= 50)
+ Event.prototype.deepPath = undefined;
+
+ if (majorVersion <= 54) {
+ window.FileError = /** @type {!function (new: FileError) : ?} */ ({
+ NOT_FOUND_ERR: DOMException.NOT_FOUND_ERR,
+ ABORT_ERR: DOMException.ABORT_ERR,
+ INVALID_MODIFICATION_ERR: DOMException.INVALID_MODIFICATION_ERR,
+ NOT_READABLE_ERR: 0 // No matching DOMException, so code will be 0.
+ });
+ }
- // Support for quirky border-image behavior (<M51), see:
- // https://bugs.chromium.org/p/chromium/issues/detail?id=559258
- styleElement.textContent +=
- '\nhtml /deep/ .cm-breakpoint .CodeMirror-linenumber { border-style: solid !important; }';
- styleElement.textContent +=
- '\nhtml /deep/ .cm-breakpoint.cm-breakpoint-conditional .CodeMirror-linenumber { border-style: solid !important; }';
- window.document.head.appendChild(styleElement);
+ installExtraStyleRules(styleRules);
+ }
+
+ /**
+ * @return {?number}
+ */
+ function getRemoteMajorVersion() {
+ try {
+ const remoteVersion = new URLSearchParams(window.location.href).get('remoteVersion');
+ if (!remoteVersion)
+ return null;
+ const majorVersion = parseInt(remoteVersion.split('.')[0], 10);
+ return majorVersion;
+ } catch (e) {
+ return null;
+ }
+ }
- // Support for legacy (<M49) frontends.
- Event.prototype.deepPath = undefined;
+ /**
+ * @param {!Array<string>} styleRules
+ */
+ function installExtraStyleRules(styleRules) {
+ if (!styleRules.length)
+ return;
+ const styleText = styleRules.join('\n');
+ document.head.appendChild(createStyleElement(styleText));
+
+ const origCreateShadowRoot = HTMLElement.prototype.createShadowRoot;
+ HTMLElement.prototype.createShadowRoot = function(...args) {
+ const shadowRoot = origCreateShadowRoot.call(this, ...args);
+ shadowRoot.appendChild(createStyleElement(styleText));
+ return shadowRoot;
+ };
+ }
- // Support for legacy (<53) frontends.
- window.FileError = /** @type {!function (new: FileError) : ?} */ ({
- NOT_FOUND_ERR: DOMException.NOT_FOUND_ERR,
- ABORT_ERR: DOMException.ABORT_ERR,
- INVALID_MODIFICATION_ERR: DOMException.INVALID_MODIFICATION_ERR,
- NOT_READABLE_ERR: 0 // No matching DOMException, so code will be 0.
- });
+ /**
+ * @param {string} styleText
+ * @return {!Element}
+ */
+ function createStyleElement(styleText) {
+ const style = document.createElement('style');
+ style.type = 'text/css';
+ style.textContent = styleText;
+ return style;
}
function windowLoaded() {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js b/chromium/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js
index d37015d5b19..bd58374ecf5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js
@@ -42,6 +42,46 @@ Elements.DOMPath.cssPath = function(node, optimized) {
/**
* @param {!SDK.DOMNode} node
+ * @return {boolean}
+ */
+Elements.DOMPath.canGetJSPath = function(node) {
+ let wp = node;
+ while (wp) {
+ if (wp.ancestorShadowRoot() && wp.ancestorShadowRoot().shadowRootType() !== SDK.DOMNode.ShadowRootTypes.Open)
+ return false;
+ wp = wp.ancestorShadowHost();
+ }
+ return true;
+};
+
+/**
+ * @param {!SDK.DOMNode} node
+ * @param {boolean=} optimized
+ * @return {string}
+ */
+Elements.DOMPath.jsPath = function(node, optimized) {
+ if (node.nodeType() !== Node.ELEMENT_NODE)
+ return '';
+
+ const path = [];
+ let wp = node;
+ while (wp) {
+ path.push(Elements.DOMPath.cssPath(wp, optimized));
+ wp = wp.ancestorShadowHost();
+ }
+ path.reverse();
+ let result = '';
+ for (let i = 0; i < path.length; ++i) {
+ if (i)
+ result += `.shadowRoot.querySelector('${path[i]}')`;
+ else
+ result += `document.querySelector('${path[i]}')`;
+ }
+ return result;
+};
+
+/**
+ * @param {!SDK.DOMNode} node
* @param {boolean} optimized
* @param {boolean} isTargetNode
* @return {?Elements.DOMPath.Step}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js b/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js
index 7ae9081d399..c29c85c3a99 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js
@@ -932,14 +932,10 @@ Elements.ElementsActionDelegate = class {
treeOutline.toggleEditAsHTML(node);
return true;
case 'elements.undo':
- if (UI.isEditing())
- return false;
SDK.domModelUndoStack.undo();
Elements.ElementsPanel.instance()._stylesWidget.forceUpdate();
return true;
case 'elements.redo':
- if (UI.isEditing())
- return false;
SDK.domModelUndoStack.redo();
Elements.ElementsPanel.instance()._stylesWidget.forceUpdate();
return true;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js b/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js
index 852b49f74ff..be96605f59d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js
@@ -338,10 +338,8 @@ Elements.ElementsTreeElement = class extends UI.TreeElement {
onselect(selectedByUser) {
this.treeOutline.suppressRevealAndSelect = true;
this.treeOutline.selectDOMNode(this._node, selectedByUser);
- if (selectedByUser) {
- this._node.highlight();
+ if (selectedByUser)
Host.userMetrics.actionTaken(Host.UserMetrics.Action.ChangeInspectedNodeInElementsPanel);
- }
this._createSelection();
this._createHint();
this.treeOutline.suppressRevealAndSelect = false;
@@ -519,8 +517,11 @@ Elements.ElementsTreeElement = class extends UI.TreeElement {
Common.UIString('Copy outerHTML'), treeOutline.performCopyOrCut.bind(treeOutline, false, this._node));
menuItem.setShortcut(createShortcut('V', modifier));
}
- if (this._node.nodeType() === Node.ELEMENT_NODE)
+ if (this._node.nodeType() === Node.ELEMENT_NODE) {
section.appendItem(Common.UIString('Copy selector'), this._copyCSSPath.bind(this));
+ section.appendItem(
+ Common.UIString('Copy JS path'), this._copyJSPath.bind(this), !Elements.DOMPath.canGetJSPath(this._node));
+ }
if (!isShadowRoot)
section.appendItem(Common.UIString('Copy XPath'), this._copyXPath.bind(this));
if (!isShadowRoot) {
@@ -1620,6 +1621,10 @@ Elements.ElementsTreeElement = class extends UI.TreeElement {
InspectorFrontendHost.copyText(Elements.DOMPath.cssPath(this._node, true));
}
+ _copyJSPath() {
+ InspectorFrontendHost.copyText(Elements.DOMPath.jsPath(this._node, true));
+ }
+
_copyXPath() {
InspectorFrontendHost.copyText(Elements.DOMPath.xPath(this._node, true));
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js b/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js
index f93b5c293a8..083d3089f1c 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js
@@ -50,6 +50,8 @@ Elements.ElementsTreeOutline = class extends UI.TreeOutline {
if (hideGutter)
this._element.classList.add('elements-hide-gutter');
UI.ARIAUtils.setAccessibleName(this._element, Common.UIString('Page DOM'));
+ this._element.addEventListener('focusin', this._onfocusin.bind(this), false);
+ this._element.addEventListener('focusout', this._onfocusout.bind(this), false);
this._element.addEventListener('mousedown', this._onmousedown.bind(this), false);
this._element.addEventListener('mousemove', this._onmousemove.bind(this), false);
this._element.addEventListener('mouseleave', this._onmouseleave.bind(this), false);
@@ -541,6 +543,24 @@ Elements.ElementsTreeOutline = class extends UI.TreeOutline {
};
}
+ /**
+ * @param {!Event} event
+ */
+ _onfocusin(event) {
+ const listItem = event.target.enclosingNodeOrSelfWithNodeName('li');
+ if (!listItem || !listItem.treeElement || !listItem.treeElement.selected)
+ return;
+ if (event.relatedTarget)
+ this._highlightTreeElement(/** @type {!UI.TreeElement} */ (listItem.treeElement), true /* showInfo */);
+ }
+
+ /**
+ * @param {!Event} event
+ */
+ _onfocusout(event) {
+ SDK.OverlayModel.hideDOMNodeHighlight();
+ }
+
_onmousedown(event) {
const element = this._treeElementFromEvent(event);
@@ -574,16 +594,23 @@ Elements.ElementsTreeOutline = class extends UI.TreeOutline {
return;
this.setHoverEffect(element);
+ this._highlightTreeElement(
+ /** @type {!UI.TreeElement} */ (element), !UI.KeyboardShortcut.eventHasCtrlOrMeta(event));
+ }
+ /**
+ * @param {!UI.TreeElement} element
+ * @param {boolean} showInfo
+ */
+ _highlightTreeElement(element, showInfo) {
if (element instanceof Elements.ElementsTreeElement) {
- element.node().domModel().overlayModel().highlightDOMNodeWithConfig(
- element.node().id, {mode: 'all', showInfo: !UI.KeyboardShortcut.eventHasCtrlOrMeta(event)});
+ element.node().domModel().overlayModel().highlightDOMNodeWithConfig(element.node().id, {mode: 'all', showInfo});
return;
}
if (element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement) {
element.domModel().overlayModel().highlightDOMNodeWithConfig(
- undefined, {mode: 'all', showInfo: !UI.KeyboardShortcut.eventHasCtrlOrMeta(event)}, element.backendNodeId());
+ undefined, {mode: 'all', showInfo}, element.backendNodeId());
}
}
@@ -1203,7 +1230,8 @@ Elements.ElementsTreeOutline = class extends UI.TreeOutline {
visibleChildren.push(beforePseudoElement);
if (node.childNodeCount()) {
- let children = node.children();
+ // Children may be stale when the outline is not wired to receive DOMModel updates.
+ let children = node.children() || [];
if (!this._showHTMLCommentsSetting.get())
children = children.filter(n => n.nodeType() !== Node.COMMENT_NODE);
visibleChildren = visibleChildren.concat(children);
@@ -1532,19 +1560,19 @@ Elements.ElementsTreeOutline.UpdateRecord = class {
};
/**
- * @implements {Common.Renderer}
+ * @implements {UI.Renderer}
*/
Elements.ElementsTreeOutline.Renderer = class {
/**
* @override
* @param {!Object} object
- * @return {!Promise.<?Node>}
+ * @return {!Promise<?{node: !Node, tree: ?UI.TreeOutline}>}
*/
render(object) {
return new Promise(renderPromise);
/**
- * @param {function(!Element)} resolve
+ * @param {function(!{node: !Node, tree: ?UI.TreeOutline})} resolve
* @param {function(!Error)} reject
*/
function renderPromise(resolve, reject) {
@@ -1564,13 +1592,14 @@ Elements.ElementsTreeOutline.Renderer = class {
reject(new Error('Could not resolve node.'));
return;
}
- const treeOutline = new Elements.ElementsTreeOutline(false, false, true /* hideGutter */);
+ const treeOutline = new Elements.ElementsTreeOutline(false, true /* selectEnabled */, true /* hideGutter */);
treeOutline.rootDOMNode = node;
if (!treeOutline.firstChild().isExpandable())
treeOutline._element.classList.add('single-node');
treeOutline.setVisible(true);
treeOutline.element.treeElementForTest = treeOutline.firstChild();
- resolve(treeOutline.element);
+ treeOutline.setShowSelectionOnKeyboardFocus(true, true);
+ resolve({node: treeOutline.element, tree: treeOutline});
}
}
}
@@ -1639,7 +1668,6 @@ Elements.ElementsTreeOutline.ShortcutTreeElement = class extends UI.TreeElement
onselect(selectedByUser) {
if (!selectedByUser)
return true;
- this._nodeShortcut.deferredNode.highlight();
this._nodeShortcut.deferredNode.resolve(resolved.bind(this));
/**
* @param {?SDK.DOMNode} node
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js b/chromium/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js
index 70de8d434a7..29a567d7ce5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js
@@ -130,20 +130,7 @@ Elements.StylePropertyTreeElement = class extends UI.TreeElement {
const swatch = InlineEditor.ColorSwatch.create();
swatch.setColor(color);
swatch.setFormat(Common.Color.detectColorFormat(swatch.color()));
- const swatchIcon = new Elements.ColorSwatchPopoverIcon(this, swatchPopoverHelper, swatch);
-
- /**
- * @param {?SDK.CSSModel.ContrastInfo} contrastInfo
- */
- function computedCallback(contrastInfo) {
- swatchIcon.setContrastInfo(contrastInfo);
- }
-
- if (Runtime.experiments.isEnabled('colorContrastRatio') && this.property.name === 'color' &&
- this._parentPane.cssModel() && this.node()) {
- const cssModel = this._parentPane.cssModel();
- cssModel.backgroundColorsPromise(this.node().id).then(computedCallback);
- }
+ this._addColorContrastInfo(new Elements.ColorSwatchPopoverIcon(this, swatchPopoverHelper, swatch));
return swatch;
}
@@ -175,11 +162,23 @@ Elements.StylePropertyTreeElement = class extends UI.TreeElement {
swatch.setColor(color);
swatch.setFormat(Common.Color.detectColorFormat(swatch.color()));
swatch.setText(text, computedValue);
- new Elements.ColorSwatchPopoverIcon(this, swatchPopoverHelper, swatch);
+ this._addColorContrastInfo(new Elements.ColorSwatchPopoverIcon(this, swatchPopoverHelper, swatch));
return swatch;
}
/**
+ * @param {!Elements.ColorSwatchPopoverIcon} swatchIcon
+ */
+ async _addColorContrastInfo(swatchIcon) {
+ if (!Runtime.experiments.isEnabled('colorContrastRatio') || this.property.name !== 'color' ||
+ !this._parentPane.cssModel() || !this.node())
+ return;
+ const cssModel = this._parentPane.cssModel();
+ const contrastInfo = await cssModel.backgroundColorsPromise(this.node().id);
+ swatchIcon.setContrastInfo(contrastInfo);
+ }
+
+ /**
* @return {string}
*/
renderedPropertyText() {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/elementsTreeOutline.css b/chromium/third_party/blink/renderer/devtools/front_end/elements/elementsTreeOutline.css
index 6e254e769d8..775a2cc3144 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/elementsTreeOutline.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/elementsTreeOutline.css
@@ -34,7 +34,7 @@
white-space: pre;
}
-.elements-disclosure li.selected .selected-hint:before {
+.elements-disclosure .elements-tree-outline:not(.hide-selection-when-blurred) li.selected .selected-hint:before {
opacity: 0.6;
color: var(--selection-inactive-fg-color);
}
@@ -91,13 +91,21 @@
.elements-disclosure li.selected .selection {
display: block;
+}
+
+.elements-disclosure .elements-tree-outline:not(.hide-selection-when-blurred) .selection {
background-color: var(--selection-inactive-bg-color);
}
+.elements-disclosure .elements-tree-outline.hide-selection-when-blurred li.selected:focus[data-keyboard-focus="true"] .selection {
+ background: rgba(0, 0, 0, 0.08);
+ border-radius: 2px;
+}
+
.elements-disclosure ol {
list-style-type: none;
/** Keep it in sync with ElementsTreeElements.updateDecorators **/
- -webkit-padding-start: 12px;
+ padding-inline-start: 12px;
margin: 0;
}
@@ -122,19 +130,19 @@
padding-left: 2px;
}
-.elements-disclosure ol li.selected:focus {
+.elements-disclosure .elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus {
color: var(--selection-fg-color);
}
-.elements-disclosure ol li.parent.selected:focus::before {
+.elements-disclosure .elements-tree-outline:not(.hide-selection-when-blurred) li.parent.selected:focus::before {
background-color: var(--selection-fg-color);
}
-.elements-disclosure ol li.selected:focus * {
+.elements-disclosure .elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus * {
color: inherit;
}
-.elements-disclosure ol li.selected:focus .selection {
+.elements-disclosure .elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus .selection {
background-color: var(--selection-bg-color);
}
@@ -299,10 +307,10 @@ ol:hover > li > .elements-tree-shortcut-link {
display: none;
}
-ol li.selected:focus .webkit-html-tag-name,
-ol li.selected:focus .webkit-html-close-tag-name,
-ol li.selected:focus .webkit-html-attribute-value,
-ol li.selected:focus .devtools-link {
+.elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus .webkit-html-tag-name,
+.elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus .webkit-html-close-tag-name,
+.elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus .webkit-html-attribute-value,
+.elements-tree-outline:not(.hide-selection-when-blurred) li.selected:focus .devtools-link {
color: var(--selection-fg-color);
}
@@ -339,7 +347,7 @@ li.selected {
li.hovered:not(.always-parent) + ol.children, .elements-tree-outline ol.shadow-root, li.selected:not(.always-parent) + ol.children {
margin-left: 5px;
- -webkit-padding-start: 6px;
+ padding-inline-start: 6px;
border-width: 1px;
border-left-style: solid;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/module.json b/chromium/third_party/blink/renderer/devtools/front_end/elements/module.json
index 6cffd5fed7f..d4996e0def5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/module.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/module.json
@@ -18,7 +18,7 @@
"className": "Elements.ElementsPanel.ContextMenuProvider"
},
{
- "type": "@Common.Renderer",
+ "type": "@UI.Renderer",
"contextTypes": [
"SDK.DOMNode",
"SDK.DeferredDOMNode"
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements/stylesSectionTree.css b/chromium/third_party/blink/renderer/devtools/front_end/elements/stylesSectionTree.css
index 43bd7e06d37..b80c7fe3235 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements/stylesSectionTree.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements/stylesSectionTree.css
@@ -89,7 +89,7 @@
ol:not(.tree-outline) {
display: none;
margin: 0;
- -webkit-padding-start: 12px;
+ padding-inline-start: 12px;
list-style: none;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js
index 762563e96a6..7195398b961 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js
@@ -93,6 +93,14 @@ ElementsTestRunner.findNode = async function(matchFunction, callback) {
};
/**
+ * @param {function(!Element): boolean} matchFunction
+ * @param {!Promise}
+ */
+ElementsTestRunner.findNodePromise = function(matchFunction) {
+ return new Promise(resolve => ElementsTestRunner.findNode(matchFunction, resolve));
+};
+
+/**
* @param {!EventListeners.EventListenersView} eventListenersView
* @param {function():void} callback
* @param {boolean=} force
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js b/chromium/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js
index 1f1a885b4ce..fa58d122a76 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js
@@ -277,15 +277,15 @@ Extensions.ExtensionSidebarPane = class extends UI.SimpleView {
return;
}
this._objectPropertiesView.element.removeChildren();
- Common.Renderer
- .render(object, {
- title: title,
- expanded: true,
- editable: false,
- })
- .then(element => {
- this._objectPropertiesView.element.appendChild(element);
- callback();
- });
+ UI.Renderer.render(object, {title, editable: false}).then(result => {
+ if (!result) {
+ callback();
+ return;
+ }
+ if (result.tree && result.tree.firstChild())
+ result.tree.firstChild().expand();
+ this._objectPropertiesView.element.appendChild(result.node);
+ callback();
+ });
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js b/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js
index 14cf5cd5e33..07a39899227 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js
@@ -163,6 +163,7 @@ HARImporter.HAREntry = class extends HARImporter.HARBase {
if (data['_initiator'])
this._initiator = new HARImporter.HARInitiator(data['_initiator']);
this._priority = HARImporter.HARBase._optionalString(data['_priority']);
+ this._resourceType = HARImporter.HARBase._optionalString(data['_resourceType']);
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js b/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js
index 081ac1a7bc0..aa982f445b7 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js
@@ -116,12 +116,7 @@ HARImporter.Importer = class {
// Meta data.
request.setRemoteAddress(entry.serverIPAddress || '', 80); // Har does not support port numbers.
- let resourceType = (pageLoad && pageLoad.mainRequest === request) ?
- Common.resourceTypes.Document :
- Common.ResourceType.fromMimeType(entry.response.content.mimeType);
- if (!resourceType)
- resourceType = Common.ResourceType.fromURL(entry.request.url) || Common.resourceTypes.Other;
- request.setResourceType(resourceType);
+ request.setResourceType(HARImporter.Importer._getResourceType(request, entry, pageLoad));
const priority = entry.customAsString('priority');
if (Protocol.Network.ResourcePriority.hasOwnProperty(priority))
@@ -132,6 +127,34 @@ HARImporter.Importer = class {
/**
* @param {!SDK.NetworkRequest} request
+ * @param {!HARImporter.HAREntry} entry
+ * @param {?SDK.NetworkLog.PageLoad} pageLoad
+ * @return {!Common.ResourceType}
+ */
+ static _getResourceType(request, entry, pageLoad) {
+ const customResourceTypeName = entry.customAsString('resourceType');
+ if (customResourceTypeName) {
+ const customResourceType = Common.ResourceType.fromName(customResourceTypeName);
+ if (customResourceType)
+ return customResourceType;
+ }
+
+ if (pageLoad && pageLoad.mainRequest === request)
+ return Common.resourceTypes.Document;
+
+ const resourceTypeFromMime = Common.ResourceType.fromMimeType(entry.response.content.mimeType);
+ if (resourceTypeFromMime !== Common.resourceTypes.Other)
+ return resourceTypeFromMime;
+
+ const resourceTypeFromUrl = Common.ResourceType.fromURL(entry.request.url);
+ if (resourceTypeFromUrl)
+ return resourceTypeFromUrl;
+
+ return Common.resourceTypes.Other;
+ }
+
+ /**
+ * @param {!SDK.NetworkRequest} request
* @param {number} issueTime
* @param {number} entryTotalDuration
* @param {!HARImporter.HARTimings} timings
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js
index ba2379884cf..91193f4f3cd 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js
@@ -716,9 +716,9 @@ HeapProfilerTestRunner._profileViewRefresh = function() {
HeapProfilerTestRunner.startSamplingHeapProfiler = async function() {
if (!UI.context.flavor(SDK.HeapProfilerModel))
await new Promise(resolve => UI.context.addFlavorChangeListener(SDK.HeapProfilerModel, resolve));
- Profiler.SamplingHeapProfileType.instance.startRecordingProfile();
+ Profiler.SamplingHeapProfileType.instance._startRecordingProfile();
};
HeapProfilerTestRunner.stopSamplingHeapProfiler = function() {
- Profiler.SamplingHeapProfileType.instance.stopRecordingProfile();
+ Profiler.SamplingHeapProfileType.instance._stopRecordingProfile();
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js b/chromium/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js
index 8c67f784b0e..eda95dc235d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js
@@ -1282,18 +1282,6 @@ HeapSnapshotWorker.HeapSnapshot = class {
}
/**
- * @param {function(!HeapSnapshotWorker.HeapSnapshotNode)} action
- * @param {boolean=} userRootsOnly
- */
- forEachRoot(action, userRootsOnly) {
- for (let iter = this.rootNode().edges(); iter.hasNext(); iter.next()) {
- const node = iter.edge.node();
- if (!userRootsOnly || this.isUserRoot(node))
- action(node);
- }
- }
-
- /**
* @param {function(!HeapSnapshotWorker.HeapSnapshotNode,!HeapSnapshotWorker.HeapSnapshotEdge):boolean=} filter
*/
calculateDistances(filter) {
@@ -1306,24 +1294,20 @@ HeapSnapshotWorker.HeapSnapshot = class {
const nodesToVisit = new Uint32Array(this.nodeCount);
let nodesToVisitLength = 0;
- /**
- * @param {number} distance
- * @param {!HeapSnapshotWorker.HeapSnapshotNode} node
- */
- function enqueueNode(distance, node) {
- const ordinal = node.ordinal();
- if (distances[ordinal] !== noDistance)
- return;
- distances[ordinal] = distance;
- nodesToVisit[nodesToVisitLength++] = node.nodeIndex;
+ // BFS for user root objects.
+ for (let iter = this.rootNode().edges(); iter.hasNext(); iter.next()) {
+ const node = iter.edge.node();
+ if (this.isUserRoot(node)) {
+ distances[node.ordinal()] = 1;
+ nodesToVisit[nodesToVisitLength++] = node.nodeIndex;
+ }
}
-
- this.forEachRoot(enqueueNode.bind(null, 1), true);
this._bfs(nodesToVisit, nodesToVisitLength, distances, filter);
- // bfs for the rest of objects
- nodesToVisitLength = 0;
- this.forEachRoot(enqueueNode.bind(null, HeapSnapshotModel.baseSystemDistance), false);
+ // BFS for objects not reached from user roots.
+ distances[this.rootNode().ordinal()] = HeapSnapshotModel.baseSystemDistance;
+ nodesToVisit[0] = this.rootNode().nodeIndex;
+ nodesToVisitLength = 1;
this._bfs(nodesToVisit, nodesToVisitLength, distances, filter);
}
@@ -2583,60 +2567,6 @@ HeapSnapshotWorker.JSHeapSnapshot = class extends HeapSnapshotWorker.HeapSnapsho
/**
* @override
- * @param {function(!HeapSnapshotWorker.HeapSnapshotNode)} action
- * @param {boolean=} userRootsOnly
- */
- forEachRoot(action, userRootsOnly) {
- /**
- * @param {!HeapSnapshotWorker.HeapSnapshotNode} node
- * @param {string} name
- * @return {?HeapSnapshotWorker.HeapSnapshotNode}
- */
- function getChildNodeByName(node, name) {
- for (let iter = node.edges(); iter.hasNext(); iter.next()) {
- const child = iter.edge.node();
- if (child.name() === name)
- return child;
- }
- return null;
- }
-
- const visitedNodes = {};
- /**
- * @param {!HeapSnapshotWorker.HeapSnapshotNode} node
- */
- function doAction(node) {
- const ordinal = node.ordinal();
- if (!visitedNodes[ordinal]) {
- action(node);
- visitedNodes[ordinal] = true;
- }
- }
-
- const gcRoots = getChildNodeByName(this.rootNode(), '(GC roots)');
- if (!gcRoots)
- return;
-
- if (userRootsOnly) {
- for (let iter = this.rootNode().edges(); iter.hasNext(); iter.next()) {
- const node = iter.edge.node();
- if (this.isUserRoot(node))
- doAction(node);
- }
- } else {
- for (let iter = gcRoots.edges(); iter.hasNext(); iter.next()) {
- const subRoot = iter.edge.node();
- for (let iter2 = subRoot.edges(); iter2.hasNext(); iter2.next())
- doAction(iter2.edge.node());
- doAction(subRoot);
- }
- for (let iter = this.rootNode().edges(); iter.hasNext(); iter.next())
- doAction(iter.edge.node());
- }
- }
-
- /**
- * @override
* @return {?{map: !Uint32Array, flag: number}}
*/
userObjectsMapAndFlag() {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/help/ReleaseNoteText.js b/chromium/third_party/blink/renderer/devtools/front_end/help/ReleaseNoteText.js
index 4b043754231..9e9640e0d03 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/help/ReleaseNoteText.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/help/ReleaseNoteText.js
@@ -13,6 +13,36 @@ const commandMenuShortcut = Host.isMac() ? 'Command + Shift + P' : 'Control + Sh
/** @type {!Array<!Help.ReleaseNote>} */
Help.releaseNoteText = [
{
+ version: 14,
+ header: 'Highlights from the Chrome 72 update',
+ highlights: [
+ {
+ title: 'Visualize performance metrics',
+ subtitle:
+ 'Performance metrics like DOMContentLoaded and First Meaningful Paint are now marked in the Timings section of the Performance panel.',
+ link: 'https://developers.google.com/web/updates/2018/11/devtools#metrics',
+ },
+ {
+ title: 'Highlight text nodes',
+ subtitle: 'Hover over a text node in the DOM Tree to highlight it in the viewport.',
+ link: 'https://developers.google.com/web/updates/2018/11/devtools#highlight',
+ },
+ {
+ title: 'Copy JS path',
+ subtitle:
+ 'Right-click a DOM node and select "Copy" > "Copy JS path" to quickly get a JavaScript expression that points to that node.',
+ link: 'https://developers.google.com/web/updates/2018/11/devtools#copy',
+ },
+ {
+ title: 'Audits panel updates',
+ subtitle:
+ 'A new audit that lists detected JS libraries and new keywords for accessing the Audits panel from the Command Menu.',
+ link: 'https://developers.google.com/web/updates/2018/11/devtools#audits',
+ },
+ ],
+ link: 'https://developers.google.com/web/updates/2018/11/devtools',
+ },
+ {
version: 13,
header: 'Highlights from the Chrome 71 update',
highlights: [
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js b/chromium/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js
index f9e71dddf44..622a509a7cb 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js
@@ -95,6 +95,7 @@ Host.UserMetrics.Action = {
Audits2Finished: 30,
ShowedThirdPartyBadges: 31,
Audits2ViewTrace: 32,
+ FilmStripStartedRecording: 33,
};
Host.UserMetrics._PanelCodes = {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js b/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js
index 4666c816957..7f8e3a0011d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js
@@ -6,18 +6,15 @@
* @implements {Common.Runnable}
*/
InspectorMain.InspectorMain = class extends Common.Object {
- constructor() {
- super();
- /** @type {!Protocol.InspectorBackend.Connection} */
- this._mainConnection;
- }
-
/**
* @override
*/
run() {
- this._connectAndCreateMainTarget();
- InspectorFrontendHost.connectionReady();
+ SDK.initMainConnection(() => {
+ const type = Runtime.queryParam('v8only') ? SDK.Target.Type.Node : SDK.Target.Type.Frame;
+ const target = SDK.targetManager.createTarget('main', Common.UIString('Main'), type, null);
+ target.runtimeAgent().runIfWaitingForDebugger();
+ }, Components.TargetDetachedDialog.webSocketConnectionLost);
new InspectorMain.InspectedNodeRevealer();
new InspectorMain.SourcesPanelIndicator();
@@ -29,54 +26,6 @@ InspectorMain.InspectorMain = class extends Common.Object {
SDK.ResourceTreeModel.reloadAllPages(hard);
});
}
-
- _connectAndCreateMainTarget() {
- const isNodeJS = !!Runtime.queryParam('v8only');
- const target = SDK.targetManager.createTarget(
- 'main', Common.UIString('Main'), this._capabilitiesForMainTarget(), this._createMainConnection.bind(this), null,
- isNodeJS);
- target.runtimeAgent().runIfWaitingForDebugger();
- }
-
- /**
- * @return {number}
- */
- _capabilitiesForMainTarget() {
- if (Runtime.queryParam('v8only'))
- return SDK.Target.Capability.JS;
- return SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | SDK.Target.Capability.DeviceEmulation |
- SDK.Target.Capability.Emulation | SDK.Target.Capability.Input | SDK.Target.Capability.JS |
- SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.ScreenCapture |
- SDK.Target.Capability.Security | SDK.Target.Capability.Target | SDK.Target.Capability.Tracing |
- SDK.Target.Capability.Inspector;
- }
-
- /**
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- * @return {!Protocol.InspectorBackend.Connection}
- */
- _createMainConnection(params) {
- this._mainConnection =
- SDK.createMainConnection(params, () => Components.TargetDetachedDialog.webSocketConnectionLost());
- return this._mainConnection;
- }
-
- /**
- * @param {function(string)} onMessage
- * @return {!Promise<!Protocol.InspectorBackend.Connection>}
- */
- _interceptMainConnection(onMessage) {
- const params = {onMessage: onMessage, onDisconnect: this._connectAndCreateMainTarget.bind(this)};
- return this._mainConnection.disconnect().then(this._createMainConnection.bind(this, params));
- }
-};
-
-/**
- * @param {function(string)} onMessage
- * @return {!Promise<!Protocol.InspectorBackend.Connection>}
- */
-InspectorMain.interceptMainConnection = function(onMessage) {
- return self.runtime.sharedInstance(InspectorMain.InspectorMain)._interceptMainConnection(onMessage);
};
/**
@@ -211,14 +160,14 @@ InspectorMain.BackendSettingsSync = class {
this._emulatePageFocusSetting = Common.settings.moduleSetting('emulatePageFocus');
this._emulatePageFocusSetting.addChangeListener(this._update, this);
- SDK.targetManager.observeTargets(this, SDK.Target.Capability.Browser);
+ SDK.targetManager.observeTargets(this);
}
/**
* @param {!SDK.Target} target
*/
_updateTarget(target) {
- if (target.parentTarget())
+ if (target.type() !== SDK.Target.Type.Frame || target.parentTarget())
return;
target.pageAgent().setAdBlockingEnabled(this._adBlockEnabledSetting.get());
target.emulationAgent().setFocusEmulationEnabled(this._emulatePageFocusSetting.get());
@@ -229,7 +178,8 @@ InspectorMain.BackendSettingsSync = class {
}
_update() {
- SDK.targetManager.targets(SDK.Target.Capability.Browser).forEach(this._updateTarget, this);
+ for (const target of SDK.targetManager.targets())
+ this._updateTarget(target);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js b/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js
index 5e7700f0c86..4ccb6721c34 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js
@@ -49,6 +49,9 @@ InspectorMain.RenderingOptionsView = class extends UI.VBox {
Common.UIString(
'Highlights elements (teal) that can slow down scrolling, including touch & wheel event handlers and other main-thread scrolling situations.'),
Common.moduleSetting('showScrollBottleneckRects'));
+ this._appendCheckbox(
+ Common.UIString('Hit-test borders'), Common.UIString('Shows borders around hit-test regions'),
+ Common.moduleSetting('showHitTestBorders'));
this.contentElement.createChild('div').classList.add('panel-section-separator');
const mediaSetting = Common.moduleSetting('emulatedCSSMedia');
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RequestAppBannerActionDelegate.js b/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RequestAppBannerActionDelegate.js
index 87925840567..9dc8491bba6 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RequestAppBannerActionDelegate.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/inspector_main/RequestAppBannerActionDelegate.js
@@ -14,7 +14,7 @@ InspectorMain.RequestAppBannerActionDelegate = class {
*/
handleAction(context, actionId) {
const target = SDK.targetManager.mainTarget();
- if (target && target.hasBrowserCapability()) {
+ if (target && target.type() === SDK.Target.Type.Frame) {
target.pageAgent().requestAppBanner();
Common.console.show();
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/js_main/JsMain.js b/chromium/third_party/blink/renderer/devtools/front_end/js_main/JsMain.js
index 59a109da113..4aef7186d81 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/js_main/JsMain.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/js_main/JsMain.js
@@ -11,17 +11,9 @@ JsMain.JsMain = class extends Common.Object {
*/
run() {
Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSDirectly);
- const target = SDK.targetManager.createTarget(
- 'main', Common.UIString('Main'), SDK.Target.Capability.JS, this._createMainConnection.bind(this), null, true /* isNodeJS */);
- target.runtimeAgent().runIfWaitingForDebugger();
- InspectorFrontendHost.connectionReady();
- }
-
- /**
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- * @return {!Protocol.InspectorBackend.Connection}
- */
- _createMainConnection(params) {
- return SDK.createMainConnection(params, () => Components.TargetDetachedDialog.webSocketConnectionLost());
+ SDK.initMainConnection(() => {
+ const target = SDK.targetManager.createTarget('main', ls`Main`, SDK.Target.Type.Node, null);
+ target.runtimeAgent().runIfWaitingForDebugger();
+ }, Components.TargetDetachedDialog.webSocketConnectionLost);
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/layer_viewer/layerDetailsView.css b/chromium/third_party/blink/renderer/devtools/front_end/layer_viewer/layerDetailsView.css
index a36c0e464dc..2e620dd7196 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/layer_viewer/layerDetailsView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/layer_viewer/layerDetailsView.css
@@ -18,9 +18,9 @@ table td:first-child {
ul {
list-style: none;
- -webkit-padding-start: 0;
- -webkit-margin-before: 0;
- -webkit-margin-after: 0;
+ padding-inline-start: 0;
+ margin-block-start: 0;
+ margin-block-end: 0;
}
a {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js b/chromium/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js
index 52740f0f283..30e04f1af74 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
- * @implements {SDK.TargetManager.Observer}
+ * @implements {SDK.SDKModelObserver<!SDK.RuntimeModel>}
* @unrestricted
*/
Main.ExecutionContextSelector = class {
@@ -11,7 +11,6 @@ Main.ExecutionContextSelector = class {
* @param {!UI.Context} context
*/
constructor(targetManager, context) {
- targetManager.observeTargets(this, SDK.Target.Capability.JS);
context.addFlavorChangeListener(SDK.ExecutionContext, this._executionContextChanged, this);
context.addFlavorChangeListener(SDK.Target, this._targetChanged, this);
@@ -24,13 +23,14 @@ Main.ExecutionContextSelector = class {
this);
this._targetManager = targetManager;
this._context = context;
+ targetManager.observeModels(SDK.RuntimeModel, this);
}
/**
* @override
- * @param {!SDK.Target} target
+ * @param {!SDK.RuntimeModel} runtimeModel
*/
- targetAdded(target) {
+ modelAdded(runtimeModel) {
// Defer selecting default target since we need all clients to get their
// targetAdded notifications first.
setImmediate(deferred.bind(this));
@@ -41,22 +41,22 @@ Main.ExecutionContextSelector = class {
function deferred() {
// We always want the second context for the service worker targets.
if (!this._context.flavor(SDK.Target))
- this._context.setFlavor(SDK.Target, target);
+ this._context.setFlavor(SDK.Target, runtimeModel.target());
}
}
/**
* @override
- * @param {!SDK.Target} target
+ * @param {!SDK.RuntimeModel} runtimeModel
*/
- targetRemoved(target) {
+ modelRemoved(runtimeModel) {
const currentExecutionContext = this._context.flavor(SDK.ExecutionContext);
- if (currentExecutionContext && currentExecutionContext.target() === target)
+ if (currentExecutionContext && currentExecutionContext.runtimeModel === runtimeModel)
this._currentExecutionContextGone();
- const targets = this._targetManager.targets(SDK.Target.Capability.JS);
- if (this._context.flavor(SDK.Target) === target && targets.length)
- this._context.setFlavor(SDK.Target, targets[0]);
+ const models = this._targetManager.models(SDK.RuntimeModel);
+ if (this._context.flavor(SDK.Target) === runtimeModel.target() && models.length)
+ this._context.setFlavor(SDK.Target, models[0].target());
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/main/Main.js b/chromium/third_party/blink/renderer/devtools/front_end/main/Main.js
index 7b3c363f4e2..d22ecf4e2da 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/main/Main.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/main/Main.js
@@ -60,7 +60,7 @@ Main.Main = class {
async _loaded() {
console.timeStamp('Main._loaded');
- await Runtime.runtimeReady();
+ await Runtime.appStarted();
Runtime.setPlatform(Host.platform());
InspectorFrontendHost.getPreferences(this._gotPreferences.bind(this));
}
@@ -117,6 +117,7 @@ Main.Main = class {
Runtime.experiments.register('oopifInlineDOM', 'OOPIF: inline DOM ', true);
Runtime.experiments.register('pinnedExpressions', 'Pinned expressions in Console', true);
Runtime.experiments.register('protocolMonitor', 'Protocol Monitor');
+ Runtime.experiments.register('samplingHeapProfilerTimeline', 'Sampling heap profiler timeline', true);
Runtime.experiments.register('sourceDiff', 'Source diff');
Runtime.experiments.register('sourcesPrettyPrint', 'Automatically pretty print in the Sources Panel');
Runtime.experiments.register(
@@ -128,7 +129,6 @@ Main.Main = class {
Runtime.experiments.register('timelineEventInitiators', 'Timeline: event initiators');
Runtime.experiments.register('timelineFlowEvents', 'Timeline: flow events', true);
Runtime.experiments.register('timelineInvalidationTracking', 'Timeline: invalidation tracking', true);
- Runtime.experiments.register('timelinePaintTimingMarkers', 'Timeline: paint timing markers', true);
Runtime.experiments.register('timelineShowAllEvents', 'Timeline: show all events', true);
Runtime.experiments.register('timelineTracingJSProfile', 'Timeline: tracing based JS profiler', true);
Runtime.experiments.register('timelineV8RuntimeCallStats', 'Timeline: V8 Runtime Call Stats on Timeline', true);
@@ -560,7 +560,7 @@ Main.Main.MainMenuItem = class {
}
if (Components.dockController.dockSide() === Components.DockController.State.Undocked &&
- SDK.targetManager.mainTarget() && SDK.targetManager.mainTarget().hasBrowserCapability())
+ SDK.targetManager.mainTarget() && SDK.targetManager.mainTarget().type() === SDK.Target.Type.Frame)
contextMenu.defaultSection().appendAction('inspector_main.focus-debuggee', Common.UIString('Focus debuggee'));
contextMenu.defaultSection().appendAction(
@@ -614,7 +614,7 @@ Main.Main.PauseListener = class {
*/
Main.sendOverProtocol = function(method, params) {
return new Promise((resolve, reject) => {
- Protocol.InspectorBackend.sendRawMessageForTesting(method, params, (err, ...results) => {
+ Protocol.test.sendRawMessage(method, params, (err, ...results) => {
if (err)
return reject(err);
return resolve(results);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js
index 37dd4d477f0..fce1e91853f 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js
@@ -40,13 +40,17 @@ Network.NetworkItemView = class extends UI.TabbedPane {
this._resourceViewTabSetting = Common.settings.createSetting('resourceViewTab', 'preview');
this._headersView = new Network.RequestHeadersView(request);
- this.appendTab(Network.NetworkItemView.Tabs.Headers, Common.UIString('Headers'), this._headersView);
+ this.appendTab(
+ Network.NetworkItemView.Tabs.Headers, Common.UIString('Headers'), this._headersView,
+ Common.UIString('Headers and request body'));
this.addEventListener(UI.TabbedPane.Events.TabSelected, this._tabSelected, this);
if (request.resourceType() === Common.resourceTypes.WebSocket) {
const frameView = new Network.ResourceWebSocketFrameView(request);
- this.appendTab(Network.NetworkItemView.Tabs.WsFrames, Common.UIString('Frames'), frameView);
+ this.appendTab(
+ Network.NetworkItemView.Tabs.WsFrames, Common.UIString('Frames'), frameView,
+ Common.UIString('WebSocket frames'));
} else if (request.mimeType === 'text/event-stream') {
this.appendTab(
Network.NetworkItemView.Tabs.EventSource, Common.UIString('EventStream'),
@@ -54,24 +58,30 @@ Network.NetworkItemView = class extends UI.TabbedPane {
} else {
this._responseView = new Network.RequestResponseView(request);
const previewView = new Network.RequestPreviewView(request);
- this.appendTab(Network.NetworkItemView.Tabs.Preview, Common.UIString('Preview'), previewView);
+ this.appendTab(
+ Network.NetworkItemView.Tabs.Preview, Common.UIString('Preview'), previewView,
+ Common.UIString('Response preview'));
if (request.signedExchangeInfo() && request.signedExchangeInfo().errors &&
request.signedExchangeInfo().errors.length) {
const icon = UI.Icon.create('smallicon-error');
icon.title = Common.UIString('SignedExchange error');
this.setTabIcon(Network.NetworkItemView.Tabs.Preview, icon);
}
- this.appendTab(Network.NetworkItemView.Tabs.Response, Common.UIString('Response'), this._responseView);
+ this.appendTab(
+ Network.NetworkItemView.Tabs.Response, Common.UIString('Response'), this._responseView,
+ Common.UIString('Raw response data'));
}
if (request.requestCookies || request.responseCookies) {
this._cookiesView = new Network.RequestCookiesView(request);
- this.appendTab(Network.NetworkItemView.Tabs.Cookies, Common.UIString('Cookies'), this._cookiesView);
+ this.appendTab(
+ Network.NetworkItemView.Tabs.Cookies, Common.UIString('Cookies'), this._cookiesView,
+ Common.UIString('Request and response cookies'));
}
this.appendTab(
Network.NetworkItemView.Tabs.Timing, Common.UIString('Timing'),
- new Network.RequestTimingView(request, calculator));
+ new Network.RequestTimingView(request, calculator), Common.UIString('Request and response timeline'));
this._request = request;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js
index 5c804456216..20a28059eab 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js
@@ -592,20 +592,31 @@ Network.NetworkLogView = class extends UI.VBox {
this._hideRecordingHint();
this._recordingHint = this.element.createChild('div', 'network-status-pane fill');
const hintText = this._recordingHint.createChild('div', 'recording-hint');
- const reloadShortcutNode = this._recordingHint.createChild('b');
- reloadShortcutNode.textContent = UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0].name;
+
+ let reloadShortcutNode = null;
+ const reloadShortcutDescriptor = UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0];
+ if (reloadShortcutDescriptor) {
+ reloadShortcutNode = this._recordingHint.createChild('b');
+ reloadShortcutNode.textContent = reloadShortcutDescriptor.name;
+ }
if (this._recording) {
const recordingText = hintText.createChild('span');
recordingText.textContent = Common.UIString('Recording network activity\u2026');
- hintText.createChild('br');
- hintText.appendChild(
- UI.formatLocalized('Perform a request or hit %s to record the reload.', [reloadShortcutNode]));
+ if (reloadShortcutNode) {
+ hintText.createChild('br');
+ hintText.appendChild(
+ UI.formatLocalized('Perform a request or hit %s to record the reload.', [reloadShortcutNode]));
+ }
} else {
const recordNode = hintText.createChild('b');
recordNode.textContent = UI.shortcutRegistry.shortcutTitleForAction('network.toggle-recording');
- hintText.appendChild(UI.formatLocalized(
- 'Record (%s) or reload (%s) to display network activity.', [recordNode, reloadShortcutNode]));
+ if (reloadShortcutNode) {
+ hintText.appendChild(UI.formatLocalized(
+ 'Record (%s) or reload (%s) to display network activity.', [recordNode, reloadShortcutNode]));
+ } else {
+ hintText.appendChild(UI.formatLocalized('Record (%s) to display network activity.', [recordNode]));
+ }
}
}
@@ -747,14 +758,14 @@ Network.NetworkLogView = class extends UI.VBox {
appendChunk(Common.UIString('Finish: %s', Number.secondsToString(maxTime - baseTime)));
if (this._mainRequestDOMContentLoadedTime !== -1 && this._mainRequestDOMContentLoadedTime > baseTime) {
appendChunk(separator);
- const domContentLoadedText = Common.UIString(
- 'DOMContentLoaded: %s', Number.secondsToString(this._mainRequestDOMContentLoadedTime - baseTime));
- appendChunk(domContentLoadedText).classList.add('summary-blue');
+ const domContentLoadedText =
+ ls`DOMContentLoaded: ${Number.secondsToString(this._mainRequestDOMContentLoadedTime - baseTime)}`;
+ appendChunk(domContentLoadedText).classList.add('summary-dcl-event');
}
if (this._mainRequestLoadTime !== -1) {
appendChunk(separator);
- const loadText = Common.UIString('Load: %s', Number.secondsToString(this._mainRequestLoadTime - baseTime));
- appendChunk(loadText).classList.add('summary-red');
+ const loadText = ls`Load: ${Number.secondsToString(this._mainRequestLoadTime - baseTime)}`;
+ appendChunk(loadText).classList.add('summary-load-event');
}
}
summaryBar.title = text;
@@ -849,7 +860,7 @@ Network.NetworkLogView = class extends UI.VBox {
const time = /** @type {number} */ (event.data.loadTime);
if (time) {
this._mainRequestLoadTime = time;
- this._columns.addEventDividers([time], 'network-red-divider');
+ this._columns.addEventDividers([time], 'network-load-divider');
}
}
@@ -862,7 +873,7 @@ Network.NetworkLogView = class extends UI.VBox {
const data = /** @type {number} */ (event.data);
if (data) {
this._mainRequestDOMContentLoadedTime = data;
- this._columns.addEventDividers([data], 'network-blue-divider');
+ this._columns.addEventDividers([data], 'network-dcl-divider');
}
}
@@ -1174,7 +1185,7 @@ Network.NetworkLogView = class extends UI.VBox {
}
footerSection.appendItem(Common.UIString('Copy all as HAR'), this._copyAll.bind(this));
- contextMenu.saveSection().appendItem(Common.UIString('Save as HAR with content'), this._exportAll.bind(this));
+ contextMenu.saveSection().appendItem(Common.UIString('Save all as HAR with content'), this._exportAll.bind(this));
contextMenu.editSection().appendItem(Common.UIString('Clear browser cache'), this._clearBrowserCache.bind(this));
contextMenu.editSection().appendItem(
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js
index 4f2d5ba67dd..938940e45c5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js
@@ -549,7 +549,7 @@ Network.NetworkLogViewColumns = class {
const content = Components.JSPresentationUtils.buildStackTracePreviewContents(
manager ? manager.target() : null, this._popupLinkifier, initiator.stack,
() => popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent));
- popover.contentElement.appendChild(content);
+ popover.contentElement.appendChild(content.element);
return Promise.resolve(true);
},
hide: this._popupLinkifier.reset.bind(this._popupLinkifier)
@@ -564,11 +564,11 @@ Network.NetworkLogViewColumns = class {
// TODO(allada) Remove this and pass in the color.
let color = 'transparent';
switch (className) {
- case 'network-blue-divider':
- color = 'hsla(240, 100%, 80%, 0.7)';
+ case 'network-dcl-divider':
+ color = '#0867CB';
break;
- case 'network-red-divider':
- color = 'rgba(255, 0, 0, 0.5)';
+ case 'network-load-divider':
+ color = '#B31412';
break;
default:
return;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js
index 0c9f5ca0705..bcaad0e5ba4 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js
@@ -242,7 +242,7 @@ Network.NetworkOverview = class extends PerfUI.TimelineOverviewBase {
const height = this.element.offsetHeight;
context.lineWidth = 1;
context.beginPath();
- context.strokeStyle = '#8080FF'; // Keep in sync with .network-blue-divider CSS rule.
+ context.strokeStyle = '#0867CB'; // Keep in sync with .summary-dcl-event CSS rule.
for (let i = this._domContentLoadedEvents.length - 1; i >= 0; --i) {
const x = Math.round(calculator.computePosition(this._domContentLoadedEvents[i])) + 0.5;
context.moveTo(x, 0);
@@ -251,7 +251,7 @@ Network.NetworkOverview = class extends PerfUI.TimelineOverviewBase {
context.stroke();
context.beginPath();
- context.strokeStyle = '#FF8080'; // Keep in sync with .network-red-divider CSS rule.
+ context.strokeStyle = '#B31412'; // Keep in sync with .summary-load-event CSS rule.
for (let i = this._loadEvents.length - 1; i >= 0; --i) {
const x = Math.round(calculator.computePosition(this._loadEvents[i])) + 0.5;
context.moveTo(x, 0);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js
index 06013d284b8..03ead615c26 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js
@@ -368,10 +368,13 @@ Network.NetworkPanel = class extends UI.Panel {
}
_resetFilmStripView() {
+ const reloadShortcutDescriptor = UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0];
+
this._filmStripView.reset();
- this._filmStripView.setStatusText(Common.UIString(
- 'Hit %s to reload and capture filmstrip.',
- UI.shortcutRegistry.shortcutDescriptorsForAction('inspector_main.reload')[0].name));
+ if (reloadShortcutDescriptor) {
+ this._filmStripView.setStatusText(
+ Common.UIString('Hit %s to reload and capture filmstrip.', reloadShortcutDescriptor.name));
+ }
}
/**
@@ -662,6 +665,8 @@ Network.NetworkPanel.FilmStripRecorder = class {
this._tracingModel.dispose();
this._tracingModel = new SDK.TracingModel(new Bindings.TempFileBackingStorage());
this._tracingManager.start(this, '-*,disabled-by-default-devtools.screenshot', '');
+
+ Host.userMetrics.actionTaken(Host.UserMetrics.Action.FilmStripStartedRecording);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/RequestHTMLView.js b/chromium/third_party/blink/renderer/devtools/front_end/network/RequestHTMLView.js
index 6108fd709d4..e2b85ba9af8 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/RequestHTMLView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/RequestHTMLView.js
@@ -63,7 +63,7 @@ Network.RequestHTMLView = class extends UI.VBox {
const iframe = createElement('iframe');
iframe.className = 'html-preview-frame';
iframe.setAttribute('sandbox', ''); // Forbid to run JavaScript and set unique origin.
- iframe.setAttribute('src', this._dataURL);
+ iframe.setAttribute('src', encodeURI(this._dataURL));
iframe.setAttribute('tabIndex', -1);
this.contentElement.appendChild(iframe);
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js b/chromium/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js
index a0ad048b942..ae4dd41f4df 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js
@@ -71,7 +71,7 @@ Network.RequestPreviewView = class extends Network.RequestResponseView {
return jsonView;
const dataURL = Common.ContentProvider.contentAsDataURL(
- contentData.content, this.request.mimeType, contentData.encoded, contentData.encoded ? 'utf-8' : null);
+ contentData.content, this.request.mimeType, contentData.encoded, this.request.charset());
return dataURL ? new Network.RequestHTMLView(dataURL) : null;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js b/chromium/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js
index 526b4c5dac0..42e8b4115cb 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js
@@ -81,6 +81,7 @@ Network.ResourceWebSocketFrameView = class extends UI.VBox {
const mainContainer = new UI.VBox();
mainContainer.element.appendChild(this._mainToolbar.element);
this._dataGrid.asWidget().show(mainContainer.element);
+ mainContainer.setMinimumSize(0, 72);
this._splitWidget.setMainWidget(mainContainer);
this._frameEmptyWidget = new UI.EmptyWidget(Common.UIString('Select frame to browse its content.'));
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/network/networkLogView.css b/chromium/third_party/blink/renderer/devtools/front_end/network/networkLogView.css
index b7240de3d0a..2a1d831bf0a 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/network/networkLogView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/network/networkLogView.css
@@ -264,8 +264,8 @@
color: grey;
}
-.network-summary-bar .summary-red {
- color: red;
+.network-summary-bar .summary-load-event {
+ color: #B31412;
}
.network-frame-divider {
@@ -279,11 +279,11 @@
overflow: hidden;
}
-.network-summary-bar .summary-blue {
- color: blue;
+.network-summary-bar .summary-dcl-event {
+ color: #0867CB;
}
-.-theme-with-dark-background .network-summary-bar .summary-blue {
+.-theme-with-dark-background .network-summary-bar .summary-dcl-event {
color: #03A9F4;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js b/chromium/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js
index 3a2cb44d46d..b1bb51a8c02 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js
@@ -11,11 +11,10 @@ NodeMain.NodeMain = class extends Common.Object {
*/
run() {
Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSFromFrontend);
- const target = SDK.targetManager.createTarget(
- 'main', Common.UIString('Main'), SDK.Target.Capability.Target, params => new SDK.MainConnection(params), null,
- false /* isNodeJS */);
- target.setInspectedURL('Node.js');
- InspectorFrontendHost.connectionReady();
+ SDK.initMainConnection(() => {
+ const target = SDK.targetManager.createTarget('main', Common.UIString('Main'), SDK.Target.Type.Browser, null);
+ target.setInspectedURL('Node.js');
+ }, Components.TargetDetachedDialog.webSocketConnectionLost);
}
};
@@ -31,15 +30,16 @@ NodeMain.NodeChildTargetManager = class extends SDK.SDKModel {
this._targetManager = parentTarget.targetManager();
this._parentTarget = parentTarget;
this._targetAgent = parentTarget.targetAgent();
- /** @type {!Map<string, !SDK.ChildConnection>} */
- this._childConnections = new Map();
+ /** @type {!Map<string, !SDK.Target>} */
+ this._childTargets = new Map();
parentTarget.registerTargetDispatcher(this);
this._targetAgent.setDiscoverTargets(true);
- InspectorFrontendHost.setDevicesUpdatesEnabled(true);
InspectorFrontendHost.events.addEventListener(
InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this);
+ InspectorFrontendHost.setDevicesUpdatesEnabled(false);
+ InspectorFrontendHost.setDevicesUpdatesEnabled(true);
}
/**
@@ -64,7 +64,7 @@ NodeMain.NodeChildTargetManager = class extends SDK.SDKModel {
InspectorFrontendHost.events.removeEventListener(
InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this);
- for (const sessionId of this._childConnections.keys())
+ for (const sessionId of this._childTargets.keys())
this.detachedFromTarget(sessionId, undefined);
}
@@ -74,7 +74,7 @@ NodeMain.NodeChildTargetManager = class extends SDK.SDKModel {
*/
targetCreated(targetInfo) {
if (targetInfo.type === 'node' && !targetInfo.attached)
- this._targetAgent.attachToTarget(targetInfo.targetId);
+ this._targetAgent.attachToTarget(targetInfo.targetId, true /* flatten */);
}
/**
@@ -98,9 +98,10 @@ NodeMain.NodeChildTargetManager = class extends SDK.SDKModel {
* @param {boolean} waitingForDebugger
*/
attachedToTarget(sessionId, targetInfo, waitingForDebugger) {
+ const name = ls`Node.js: ${targetInfo.url}`;
const target = this._targetManager.createTarget(
- targetInfo.targetId, Common.UIString('Node.js: %s', targetInfo.url), SDK.Target.Capability.JS,
- this._createChildConnection.bind(this, this._targetAgent, sessionId), this._parentTarget, true /* isNodeJS */);
+ targetInfo.targetId, name, SDK.Target.Type.Node, this._parentTarget, sessionId);
+ this._childTargets.set(sessionId, target);
target.runtimeAgent().runIfWaitingForDebugger();
}
@@ -110,8 +111,8 @@ NodeMain.NodeChildTargetManager = class extends SDK.SDKModel {
* @param {string=} childTargetId
*/
detachedFromTarget(sessionId, childTargetId) {
- this._childConnections.get(sessionId).onDisconnect.call(null, 'target terminated');
- this._childConnections.delete(sessionId);
+ this._childTargets.get(sessionId).dispose('target terminated');
+ this._childTargets.delete(sessionId);
}
/**
@@ -121,21 +122,7 @@ NodeMain.NodeChildTargetManager = class extends SDK.SDKModel {
* @param {string=} childTargetId
*/
receivedMessageFromTarget(sessionId, message, childTargetId) {
- const connection = this._childConnections.get(sessionId);
- if (connection)
- connection.onMessage.call(null, message);
- }
-
- /**
- * @param {!Protocol.TargetAgent} agent
- * @param {string} sessionId
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- * @return {!Protocol.InspectorBackend.Connection}
- */
- _createChildConnection(agent, sessionId, params) {
- const connection = new SDK.ChildConnection(agent, sessionId, params);
- this._childConnections.set(sessionId, connection);
- return connection;
+ // We use flatten protocol.
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js b/chromium/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js
index 937a945abd5..6a561df771c 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js
@@ -28,7 +28,7 @@ ObjectUI.CustomPreviewSection = class {
return;
}
- if (customPreview.hasBody) {
+ if (customPreview.hasBody || customPreview.bodyGetterId) {
this._header.classList.add('custom-expandable-section-header');
this._header.addEventListener('click', this._onClick.bind(this), false);
this._expandIcon = UI.Icon.create('smallicon-triangle-right', 'custom-expand-icon');
@@ -180,10 +180,16 @@ ObjectUI.CustomPreviewSection = class {
}
const customPreview = this._object.customPreview();
- const args = [{objectId: customPreview.bindRemoteObjectFunctionId}, {objectId: customPreview.formatterObjectId}];
- if (customPreview.configObjectId)
- args.push({objectId: customPreview.configObjectId});
- this._object.callFunctionJSON(load, args).then(onBodyLoaded.bind(this));
+ if (customPreview.bindRemoteObjectFunctionId && customPreview.formatterObjectId) {
+ // Support for V8 version < 7.3.
+ const args = [{objectId: customPreview.bindRemoteObjectFunctionId}, {objectId: customPreview.formatterObjectId}];
+ if (customPreview.configObjectId)
+ args.push({objectId: customPreview.configObjectId});
+ this._object.callFunctionJSON(load, args).then(onBodyLoaded.bind(this));
+ } else if (customPreview.bodyGetterId) {
+ this._object.callFunctionJSON(bodyGetter => bodyGetter(), [{objectId: customPreview.bodyGetterId}])
+ .then(onBodyLoaded.bind(this));
+ }
/**
* @param {*} bodyJsonML
@@ -217,7 +223,8 @@ ObjectUI.CustomPreviewComponent = class {
}
expandIfPossible() {
- if (this._object.customPreview().hasBody && this._customPreviewSection)
+ if ((this._object.customPreview().hasBody || this._object.customPreview().bodyGetterId) &&
+ this._customPreviewSection)
this._customPreviewSection._loadBody();
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js b/chromium/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js
index 7e80eb4432b..745339d1ae9 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js
@@ -1381,14 +1381,14 @@ ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol = Symbol('cac
ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId = Symbol('treeOutlineId');
/**
- * @implements {Common.Renderer}
+ * @implements {UI.Renderer}
*/
ObjectUI.ObjectPropertiesSection.Renderer = class {
/**
* @override
* @param {!Object} object
- * @param {!Common.Renderer.Options=} options
- * @return {!Promise<?Node>}
+ * @param {!UI.Renderer.Options=} options
+ * @return {!Promise<?{node: !Node, tree: ?UI.TreeOutline}>}
*/
render(object, options) {
if (!(object instanceof SDK.RemoteObject))
@@ -1398,9 +1398,8 @@ ObjectUI.ObjectPropertiesSection.Renderer = class {
const section = new ObjectUI.ObjectPropertiesSection(object, title);
if (!title)
section.titleLessMode();
- if (options.expanded)
- section.expand();
section.editable = !!options.editable;
- return Promise.resolve(section.element);
+ return Promise.resolve(
+ /** @type {?{node: !Node, tree: ?UI.TreeOutline}} */ ({node: section.element, tree: section}));
}
}; \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/object_ui/module.json b/chromium/third_party/blink/renderer/devtools/front_end/object_ui/module.json
index d56753b9a10..e2d12364e3d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/object_ui/module.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/object_ui/module.json
@@ -1,7 +1,7 @@
{
"extensions": [
{
- "type": "@Common.Renderer",
+ "type": "@UI.Renderer",
"contextTypes": [
"SDK.RemoteObject"
],
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js b/chromium/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js
index 86f2a163a4a..575aa140b1a 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js
@@ -127,8 +127,10 @@ PerfUI.FlameChart = class extends UI.VBox {
this._highlightedEntryIndex = -1;
this._selectedEntryIndex = -1;
this._rawTimelineDataLength = 0;
- /** @type {!Map<string,!Map<string,number>>} */
+ /** @type {!Map<string, !Map<string,number>>} */
this._textWidth = new Map();
+ /** @type {!Map<number, !{x: number, width: number}>} */
+ this._markerPositions = new Map();
this._lastMouseOffsetX = 0;
this._selectedGroup = -1;
@@ -343,13 +345,7 @@ PerfUI.FlameChart = class extends UI.VBox {
}
_updateHighlight() {
- const inDividersBar = this._lastMouseOffsetY < PerfUI.FlameChart.HeaderHeight;
- this._highlightedMarkerIndex = inDividersBar ? this._markerIndexAtPosition(this._lastMouseOffsetX) : -1;
- this._updateMarkerHighlight();
-
- const entryIndex = this._highlightedMarkerIndex === -1 ?
- this._coordinatesToEntryIndex(this._lastMouseOffsetX, this._lastMouseOffsetY) :
- -1;
+ const entryIndex = this._coordinatesToEntryIndex(this._lastMouseOffsetX, this._lastMouseOffsetY);
if (entryIndex === -1) {
this.hideHighlight();
const group =
@@ -570,48 +566,45 @@ PerfUI.FlameChart = class extends UI.VBox {
const offsetFromLevel = y - this._visibleLevelOffsets[cursorLevel];
if (offsetFromLevel > this._levelHeight(cursorLevel))
return -1;
+
+ // Check markers first.
+ for (const [index, pos] of this._markerPositions) {
+ if (timelineData.entryLevels[index] !== cursorLevel)
+ continue;
+ if (pos.x <= x && x < pos.x + pos.width)
+ return /** @type {number} */ (index);
+ }
+
+ // Check regular entries.
const entryStartTimes = timelineData.entryStartTimes;
- const entryTotalTimes = timelineData.entryTotalTimes;
- const entryIndexes = this._timelineLevels[cursorLevel];
- if (!entryIndexes || !entryIndexes.length)
+ const entriesOnLevel = this._timelineLevels[cursorLevel];
+ if (!entriesOnLevel || !entriesOnLevel.length)
return -1;
- /**
- * @param {number} time
- * @param {number} entryIndex
- * @return {number}
- */
- function comparator(time, entryIndex) {
- return time - entryStartTimes[entryIndex];
- }
const cursorTime = this._chartViewport.pixelToTime(x);
- const indexOnLevel = Math.max(entryIndexes.upperBound(cursorTime, comparator) - 1, 0);
+ const indexOnLevel = Math.max(
+ entriesOnLevel.upperBound(cursorTime, (time, entryIndex) => time - entryStartTimes[entryIndex]) - 1, 0);
/**
* @this {PerfUI.FlameChart}
- * @param {number} entryIndex
+ * @param {number|undefined} entryIndex
* @return {boolean}
*/
function checkEntryHit(entryIndex) {
if (entryIndex === undefined)
return false;
const startTime = entryStartTimes[entryIndex];
+ const duration = timelineData.entryTotalTimes[entryIndex];
const startX = this._chartViewport.timeToPosition(startTime);
- const duration = entryTotalTimes[entryIndex];
- if (isNaN(duration)) {
- const dx = startX - x;
- const dy = this._levelHeight(cursorLevel) / 2 - offsetFromLevel;
- return dx * dx + dy * dy < this._markerRadius * this._markerRadius;
- }
const endX = this._chartViewport.timeToPosition(startTime + duration);
- const /** @const */ barThresholdPx = 3;
+ const barThresholdPx = 3;
return startX - barThresholdPx < x && x < endX + barThresholdPx;
}
- let entryIndex = entryIndexes[indexOnLevel];
+ let entryIndex = entriesOnLevel[indexOnLevel];
if (checkEntryHit.call(this, entryIndex))
return entryIndex;
- entryIndex = entryIndexes[indexOnLevel + 1];
+ entryIndex = entriesOnLevel[indexOnLevel + 1];
if (checkEntryHit.call(this, entryIndex))
return entryIndex;
return -1;
@@ -711,6 +704,7 @@ PerfUI.FlameChart = class extends UI.VBox {
const minTextWidth = 2 * textPadding + UI.measureTextWidth(context, '\u2026');
const minTextWidthDuration = this._chartViewport.pixelToTimeOffset(minTextWidth);
const minVisibleBarLevel = Math.max(this._visibleLevelOffsets.upperBound(top) - 1, 0);
+ this._markerPositions.clear();
/** @type {!Map<string, !Array<number>>} */
const colorBuckets = new Map();
@@ -729,10 +723,11 @@ PerfUI.FlameChart = class extends UI.VBox {
let lastDrawOffset = Infinity;
for (let entryIndexOnLevel = rightIndexOnLevel; entryIndexOnLevel >= 0; --entryIndexOnLevel) {
const entryIndex = levelIndexes[entryIndexOnLevel];
- let duration = entryTotalTimes[entryIndex];
- if (isNaN(duration))
+ const duration = entryTotalTimes[entryIndex];
+ if (isNaN(duration)) {
markerIndices.push(entryIndex);
- duration = duration || 0;
+ continue;
+ }
if (duration >= minTextWidthDuration || this._forceDecorationCache[entryIndex])
titleIndices.push(entryIndex);
@@ -771,51 +766,57 @@ PerfUI.FlameChart = class extends UI.VBox {
});
context.restore();
- const colors = colorBuckets.keysArray();
- // We don't use for-of here because it's slow.
- for (let c = 0; c < colors.length; ++c) {
- const color = colors[c];
- const indexes = colorBuckets.get(color);
+ for (const [color, indexes] of colorBuckets) {
context.beginPath();
for (let i = 0; i < indexes.length; ++i) {
const entryIndex = indexes[i];
+ const duration = entryTotalTimes[entryIndex];
+ if (isNaN(duration))
+ continue;
const entryStartTime = entryStartTimes[entryIndex];
const barX = this._timeToPositionClipped(entryStartTime);
- const duration = entryTotalTimes[entryIndex];
const barLevel = entryLevels[entryIndex];
const barHeight = this._levelHeight(barLevel);
const barY = this._levelToOffset(barLevel);
- if (isNaN(duration)) {
- context.moveTo(barX + this._markerRadius, barY + barHeight / 2);
- context.arc(barX, barY + barHeight / 2, this._markerRadius, 0, Math.PI * 2);
- continue;
- }
const barRight = this._timeToPositionClipped(entryStartTime + duration);
const barWidth = Math.max(barRight - barX, 1);
- if (color)
- context.rect(barX, barY, barWidth - 0.4, barHeight - 1);
+ context.rect(barX, barY, barWidth - 0.4, barHeight - 1);
}
- if (!color)
- continue;
context.fillStyle = color;
context.fill();
}
}
+ context.textBaseline = 'alphabetic';
context.beginPath();
- for (let m = 0; m < markerIndices.length; ++m) {
+ let lastMarkerLevel = -1;
+ let lastMarkerX = -Infinity;
+ // Markers are sorted top to bottom, right to left.
+ for (let m = markerIndices.length - 1; m >= 0; --m) {
const entryIndex = markerIndices[m];
+ const title = this._dataProvider.entryTitle(entryIndex);
+ if (!title)
+ continue;
const entryStartTime = entryStartTimes[entryIndex];
- const barX = this._timeToPositionClipped(entryStartTime);
- const barLevel = entryLevels[entryIndex];
- const y = this._levelToOffset(barLevel) + this._levelHeight(barLevel) / 2;
- context.moveTo(barX + this._markerRadius, y);
- context.arc(barX, y, this._markerRadius, 0, Math.PI * 2);
+ const level = entryLevels[entryIndex];
+ if (lastMarkerLevel !== level)
+ lastMarkerX = -Infinity;
+ const x = Math.max(this._chartViewport.timeToPosition(entryStartTime), lastMarkerX);
+ const y = this._levelToOffset(level);
+ const h = this._levelHeight(level);
+ const padding = 4;
+ const width = Math.ceil(UI.measureTextWidth(context, title)) + 2 * padding;
+ lastMarkerX = x + width + 1;
+ lastMarkerLevel = level;
+ this._markerPositions.set(entryIndex, {x, width});
+ context.fillStyle = this._dataProvider.entryColor(entryIndex);
+ context.fillRect(x, y, width, h - 1);
+ context.fillStyle = 'white';
+ context.fillText(title, x + padding, y + h - this._textBaseline);
}
context.strokeStyle = 'rgba(0, 0, 0, 0.2)';
context.stroke();
- context.textBaseline = 'alphabetic';
for (let i = 0; i < titleIndices.length; ++i) {
const entryIndex = titleIndices[i];
const entryStartTime = entryStartTimes[entryIndex];
@@ -1591,19 +1592,30 @@ PerfUI.FlameChart = class extends UI.VBox {
* @param {number} entryIndex
*/
_updateElementPosition(element, entryIndex) {
- const /** @const */ elementMinWidthPx = 2;
- if (element.parentElement)
- element.remove();
+ const elementMinWidthPx = 2;
+ element.classList.add('hidden');
if (entryIndex === -1)
return;
const timelineData = this._timelineData();
const startTime = timelineData.entryStartTimes[entryIndex];
- const endTime = startTime + (timelineData.entryTotalTimes[entryIndex] || 0);
- let barX = this._timeToPositionClipped(startTime);
- const barRight = this._timeToPositionClipped(endTime);
- if (barRight === 0 || barX === this._offsetWidth)
+ const duration = timelineData.entryTotalTimes[entryIndex];
+ let barX = 0;
+ let barWidth = 0;
+ let visible = true;
+ if (Number.isNaN(duration)) {
+ const position = this._markerPositions.get(entryIndex);
+ if (position) {
+ barX = position.x;
+ barWidth = position.width;
+ } else {
+ visible = false;
+ }
+ } else {
+ barX = this._chartViewport.timeToPosition(startTime);
+ barWidth = duration * this._chartViewport.timeToPixel();
+ }
+ if (barX + barWidth <= 0 || barX >= this._offsetWidth)
return;
- let barWidth = barRight - barX;
const barCenter = barX + barWidth / 2;
barWidth = Math.max(barWidth, elementMinWidthPx);
barX = barCenter - barWidth / 2;
@@ -1615,6 +1627,7 @@ PerfUI.FlameChart = class extends UI.VBox {
style.top = barY + 'px';
style.width = barWidth + 'px';
style.height = barHeight - 1 + 'px';
+ element.classList.toggle('hidden', !visible);
this._viewportElement.appendChild(element);
}
@@ -1911,7 +1924,7 @@ PerfUI.FlameChartMarker.prototype = {
color() {},
/**
- * @return {string}
+ * @return {?string}
*/
title() {},
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js b/chromium/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js
index fd819d27304..f8930c7477e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js
@@ -14,7 +14,7 @@ PerformanceMonitor.PerformanceMonitor = class extends UI.HBox {
/** @type {!Array<!{timestamp: number, metrics: !Map<string, number>}>} */
this._metricsBuffer = [];
/** @const */
- this._pixelsPerMs = 20 / 1000;
+ this._pixelsPerMs = 10 / 1000;
/** @const */
this._pollIntervalMs = 500;
/** @const */
@@ -144,8 +144,9 @@ PerformanceMonitor.PerformanceMonitor = class extends UI.HBox {
* @param {!CanvasRenderingContext2D} ctx
*/
_drawHorizontalGrid(ctx) {
+ const labelDistanceSeconds = 10;
const lightGray = UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.02)', UI.ThemeSupport.ColorUsage.Foreground);
- ctx.font = '9px ' + Host.fontFamily();
+ ctx.font = '10px ' + Host.fontFamily();
ctx.fillStyle = UI.themeSupport.patchColorText('rgba(0, 0, 0, 0.3)', UI.ThemeSupport.ColorUsage.Foreground);
const currentTime = Date.now() / 1000;
for (let sec = Math.ceil(currentTime);; --sec) {
@@ -155,9 +156,9 @@ PerformanceMonitor.PerformanceMonitor = class extends UI.HBox {
ctx.beginPath();
ctx.moveTo(Math.round(x) + 0.5, 0);
ctx.lineTo(Math.round(x) + 0.5, this._height);
- if (sec >= 0 && sec % 5 === 0)
+ if (sec >= 0 && sec % labelDistanceSeconds === 0)
ctx.fillText(new Date(sec * 1000).toLocaleTimeString(), Math.round(x) + 4, 12);
- ctx.strokeStyle = sec % 5 ? lightGray : this._gridColor;
+ ctx.strokeStyle = sec % labelDistanceSeconds ? lightGray : this._gridColor;
ctx.stroke();
}
}
@@ -517,13 +518,19 @@ PerformanceMonitor.PerformanceMonitor.MetricIndicator = class {
* @return {string}
*/
static _formatNumber(value, info) {
+ if (!PerformanceMonitor.PerformanceMonitor.MetricIndicator._numberFormatter) {
+ PerformanceMonitor.PerformanceMonitor.MetricIndicator._numberFormatter =
+ new Intl.NumberFormat('en-US', {maximumFractionDigits: 1});
+ PerformanceMonitor.PerformanceMonitor.MetricIndicator._percentFormatter =
+ new Intl.NumberFormat('en-US', {maximumFractionDigits: 1, style: 'percent'});
+ }
switch (info.format) {
case PerformanceMonitor.PerformanceMonitor.Format.Percent:
- return value.toLocaleString('en-US', {maximumFractionDigits: 1, style: 'percent'});
+ return PerformanceMonitor.PerformanceMonitor.MetricIndicator._percentFormatter.format(value);
case PerformanceMonitor.PerformanceMonitor.Format.Bytes:
return Number.bytesToString(value);
default:
- return value.toLocaleString('en-US', {maximumFractionDigits: 1});
+ return PerformanceMonitor.PerformanceMonitor.MetricIndicator._numberFormatter.format(value);
}
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js b/chromium/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js
index 68feae279ac..bc64a00630f 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js
@@ -166,6 +166,8 @@ Persistence.Automapping = class {
if (networkSourceCode[Persistence.Automapping._processingPromise] ||
networkSourceCode[Persistence.Automapping._status])
return;
+ if (networkSourceCode.url().startsWith('wasm://'))
+ return;
const createBindingPromise =
this._createBinding(networkSourceCode).then(validateStatus.bind(this)).then(onStatus.bind(this));
networkSourceCode[Persistence.Automapping._processingPromise] = createBindingPromise;
@@ -217,7 +219,7 @@ Persistence.Automapping = class {
const target = Bindings.NetworkProject.targetForUISourceCode(status.network);
let isValid = false;
- if (target && target.isNodeJS()) {
+ if (target && target.type() === SDK.Target.Type.Node) {
const rewrappedNetworkContent =
Persistence.Persistence.rewrapNodeJSContent(status.fileSystem, fileSystemContent, networkContent);
isValid = fileSystemContent === rewrappedNetworkContent;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js b/chromium/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js
index 14accb96faf..fac5b9958a8 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js
@@ -178,7 +178,7 @@ Persistence.Persistence = class extends Common.Object {
}
const target = Bindings.NetworkProject.targetForUISourceCode(binding.network);
- if (target.isNodeJS()) {
+ if (target.type() === SDK.Target.Type.Node) {
const newContent = uiSourceCode.workingCopy();
other.requestContent().then(() => {
const nodeJSContent = Persistence.Persistence.rewrapNodeJSContent(other, other.workingCopy(), newContent);
@@ -221,7 +221,7 @@ Persistence.Persistence = class extends Common.Object {
return;
const other = binding.network === uiSourceCode ? binding.fileSystem : binding.network;
const target = Bindings.NetworkProject.targetForUISourceCode(binding.network);
- if (target.isNodeJS()) {
+ if (target.type() === SDK.Target.Type.Node) {
other.requestContent().then(currentContent => {
const nodeJSContent = Persistence.Persistence.rewrapNodeJSContent(other, currentContent, newContent);
setContent.call(this, nodeJSContent);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js b/chromium/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js
index 8307698bea7..53ebe75e759 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js
@@ -20,7 +20,9 @@ Persistence.PersistenceActions.ContextMenuProvider = class {
async function saveAs() {
if (contentProvider instanceof Workspace.UISourceCode)
/** @type {!Workspace.UISourceCode} */ (contentProvider).commitWorkingCopy();
- const content = await contentProvider.requestContent();
+ let content = await contentProvider.requestContent();
+ if (await contentProvider.contentEncoded())
+ content = window.atob(content);
const url = contentProvider.contentURL();
Workspace.fileManager.save(url, /** @type {string} */ (content), true);
Workspace.fileManager.close(url);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js b/chromium/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js
index 59308118e36..7f9c03df371 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js
@@ -78,6 +78,9 @@ Persistence.WorkspaceSettingsTab = class extends UI.VBox {
* @param {!Persistence.PlatformFileSystem} fileSystem
*/
_addItem(fileSystem) {
+ // Support managing only instances of IsolatedFileSystem.
+ if (!(fileSystem instanceof Persistence.IsolatedFileSystem))
+ return;
const networkPersistenceProject = Persistence.networkPersistenceManager.project();
if (networkPersistenceProject &&
Persistence.isolatedFileSystemManager.fileSystem(networkPersistenceProject.fileSystemPath()) === fileSystem)
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js b/chromium/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js
index 5b9025df6ae..a901ccf0174 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js
@@ -34,10 +34,11 @@ Profiler.CPUProfileView = class extends Profiler.ProfileView {
constructor(profileHeader) {
super();
this._profileHeader = profileHeader;
- this.profile = profileHeader.profileModel();
- this.adjustedTotal = this.profile.profileHead.total;
- this.adjustedTotal -= this.profile.idleNode ? this.profile.idleNode.total : 0;
this.initialize(new Profiler.CPUProfileView.NodeFormatter(this));
+ const profile = profileHeader.profileModel();
+ this.adjustedTotal = profile.profileHead.total;
+ this.adjustedTotal -= profile.idleNode ? profile.idleNode.total : 0;
+ this.setProfile(profile);
}
/**
@@ -47,7 +48,7 @@ Profiler.CPUProfileView = class extends Profiler.ProfileView {
super.wasShown();
const lineLevelProfile = PerfUI.LineLevelProfile.instance();
lineLevelProfile.reset();
- lineLevelProfile.appendCPUProfile(this.profile);
+ lineLevelProfile.appendCPUProfile(this._profileHeader.profileModel());
}
/**
@@ -70,7 +71,8 @@ Profiler.CPUProfileView = class extends Profiler.ProfileView {
* @return {!PerfUI.FlameChartDataProvider}
*/
createFlameChartDataProvider() {
- return new Profiler.CPUFlameChartDataProvider(this.profile, this._profileHeader._cpuProfilerModel);
+ return new Profiler.CPUFlameChartDataProvider(
+ this._profileHeader.profileModel(), this._profileHeader._cpuProfilerModel);
}
};
@@ -121,10 +123,10 @@ Profiler.CPUProfileType = class extends Profiler.ProfileType {
*/
buttonClicked() {
if (this._recording) {
- this.stopRecordingProfile();
+ this._stopRecordingProfile();
return false;
} else {
- this.startRecordingProfile();
+ this._startRecordingProfile();
return true;
}
}
@@ -148,7 +150,7 @@ Profiler.CPUProfileType = class extends Profiler.ProfileType {
this.addProfile(profile);
}
- startRecordingProfile() {
+ _startRecordingProfile() {
const cpuProfilerModel = UI.context.flavor(SDK.CPUProfilerModel);
if (this.profileBeingRecorded() || !cpuProfilerModel)
return;
@@ -162,7 +164,7 @@ Profiler.CPUProfileType = class extends Profiler.ProfileType {
Host.userMetrics.actionTaken(Host.UserMetrics.Action.ProfilesCPUProfileTaken);
}
- async stopRecordingProfile() {
+ async _stopRecordingProfile() {
this._recording = false;
if (!this.profileBeingRecorded() || !this.profileBeingRecorded()._cpuProfilerModel)
return;
@@ -193,7 +195,7 @@ Profiler.CPUProfileType = class extends Profiler.ProfileType {
* @override
*/
profileBeingRecordedRemoved() {
- this.stopRecordingProfile();
+ this._stopRecordingProfile();
}
};
@@ -272,7 +274,7 @@ Profiler.CPUProfileView.NodeFormatter = class {
* @return {string}
*/
formatPercent(value, node) {
- return node.profileNode === this._profileView.profile.idleNode ? '' : Common.UIString('%.2f\xa0%%', value);
+ return node.profileNode === this._profileView.profile().idleNode ? '' : Common.UIString('%.2f\xa0%%', value);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js b/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js
index 56604554831..3c220b1d759 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js
@@ -1,6 +1,7 @@
// 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.
+
/**
* @implements {UI.Searchable}
* @unrestricted
@@ -11,18 +12,110 @@ Profiler.HeapProfileView = class extends Profiler.ProfileView {
*/
constructor(profileHeader) {
super();
+
this._profileHeader = profileHeader;
- this.profile = new Profiler.SamplingHeapProfileModel(profileHeader._profile || profileHeader.protocolProfile());
- this.adjustedTotal = this.profile.total;
+ this._profileType = profileHeader.profileType();
const views = [
Profiler.ProfileView.ViewTypes.Flame, Profiler.ProfileView.ViewTypes.Heavy, Profiler.ProfileView.ViewTypes.Tree
];
- const isNativeProfile = [
- Profiler.SamplingNativeHeapProfileType.TypeId, Profiler.SamplingNativeHeapSnapshotType.TypeId
- ].includes(profileHeader.profileType().id);
+
+ const isNativeProfile = this._profileType.id === Profiler.SamplingNativeHeapProfileType.TypeId ||
+ this._profileType.id === Profiler.SamplingNativeHeapSnapshotType.TypeId;
if (isNativeProfile)
views.push(Profiler.ProfileView.ViewTypes.Text);
+
this.initialize(new Profiler.HeapProfileView.NodeFormatter(this), views);
+ const profile = new Profiler.SamplingHeapProfileModel(profileHeader._profile || profileHeader.protocolProfile());
+ this.adjustedTotal = profile.total;
+ this.setProfile(profile);
+
+ this._selectedSizeText = new UI.ToolbarText();
+
+ if (Runtime.experiments.isEnabled('samplingHeapProfilerTimeline')) {
+ this._timelineOverview = new Profiler.HeapTimelineOverview();
+ this._timelineOverview.addEventListener(
+ Profiler.HeapTimelineOverview.IdsRangeChanged, this._onIdsRangeChanged.bind(this));
+ this._timelineOverview.show(this.element, this.element.firstChild);
+ this._timelineOverview.start();
+
+ this._profileType.addEventListener(
+ Profiler.SamplingHeapProfileType.Events.StatsUpdate, this._onStatsUpdate, this);
+ this._profileType.once(Profiler.ProfileType.Events.ProfileComplete).then(() => {
+ this._profileType.removeEventListener(
+ Profiler.SamplingHeapProfileType.Events.StatsUpdate, this._onStatsUpdate, this);
+ this._timelineOverview.stop();
+ this._timelineOverview.updateGrid();
+ });
+ }
+ }
+
+ /**
+ * @override
+ * @return {!Array<!UI.ToolbarItem>}
+ */
+ syncToolbarItems() {
+ return [...super.syncToolbarItems(), this._selectedSizeText];
+ }
+
+ /**
+ * @param {!Common.Event} event
+ */
+ _onIdsRangeChanged(event) {
+ const minId = /** @type {number} */ (event.data.minId);
+ const maxId = /** @type {number} */ (event.data.maxId);
+ this._selectedSizeText.setText(ls`Selected size: ${Number.bytesToString(event.data.size)}`);
+ this._setSelectionRange(minId, maxId);
+ }
+
+ /**
+ * @param {number} minId
+ * @param {number} maxId
+ */
+ _setSelectionRange(minId, maxId) {
+ const profile = new Profiler.SamplingHeapProfileModel(
+ this._profileHeader._profile || this._profileHeader.protocolProfile(), minId, maxId);
+ this.adjustedTotal = profile.total;
+ this.setProfile(profile);
+ }
+
+ /**
+ * @param {!Common.Event} event
+ */
+ _onStatsUpdate(event) {
+ const profile = event.data;
+
+ if (!this._totalTime) {
+ this._timestamps = [];
+ this._sizes = [];
+ this._max = [];
+ this._ordinals = [];
+ this._totalTime = 30000;
+ this._lastOrdinal = 0;
+ }
+
+ this._sizes.fill(0);
+ this._sizes.push(0);
+ this._timestamps.push(Date.now());
+ this._ordinals.push(this._lastOrdinal + 1);
+ this._lastOrdinal = profile.samples.reduce((res, sample) => Math.max(res, sample.ordinal), this._lastOrdinal);
+ for (const sample of profile.samples) {
+ const bucket = this._ordinals.upperBound(sample.ordinal) - 1;
+ this._sizes[bucket] += sample.size;
+ }
+ this._max.push(this._sizes.peekLast());
+
+ if (this._timestamps.peekLast() - this._timestamps[0] > this._totalTime)
+ this._totalTime *= 2;
+
+ const samples = /** @type {!Profiler.HeapTimelineOverview.Samples} */ ({
+ sizes: this._sizes,
+ max: this._max,
+ ids: this._ordinals,
+ timestamps: this._timestamps,
+ totalTime: this._totalTime
+ });
+
+ this._timelineOverview.setSamples(samples);
}
/**
@@ -45,7 +138,8 @@ Profiler.HeapProfileView = class extends Profiler.ProfileView {
* @return {!PerfUI.FlameChartDataProvider}
*/
createFlameChartDataProvider() {
- return new Profiler.HeapFlameChartDataProvider(this.profile, this._profileHeader.heapProfilerModel());
+ return new Profiler.HeapFlameChartDataProvider(
+ /** @type {!Profiler.SamplingHeapProfileModel} */ (this.profile()), this._profileHeader.heapProfilerModel());
}
/**
@@ -58,10 +152,10 @@ Profiler.HeapProfileView = class extends Profiler.ProfileView {
`Report Version: 7\n` +
`App Version: ${/Chrom\S*/.exec(navigator.appVersion)[0] || 'Unknown'}\n` +
`Node Weight: 1 KiB\n` +
- `Total Size: ${Math.round(this.profile.root.total / 1024)} KiB\n` +
+ `Total Size: ${Math.round(this.profile().root.total / 1024)} KiB\n` +
`----\n\nCall graph:\n`;
- const sortedChildren = this.profile.root.children.sort((a, b) => b.total - a.total);
- const modules = this.profile.modules.map(
+ const sortedChildren = this.profile().root.children.sort((a, b) => b.total - a.total);
+ const modules = this.profile().modules.map(
m => Object.assign({address: BigInt(m.baseAddress), endAddress: BigInt(m.baseAddress) + BigInt(m.size)}, m));
modules.sort((m1, m2) => m1.address > m2.address ? 1 : m1.address < m2.address ? -1 : 0);
for (const child of sortedChildren)
@@ -121,6 +215,10 @@ Profiler.HeapProfileView = class extends Profiler.ProfileView {
* @unrestricted
*/
Profiler.SamplingHeapProfileTypeBase = class extends Profiler.ProfileType {
+ /**
+ * @param {string} typeId
+ * @param {string} description
+ */
constructor(typeId, description) {
super(typeId, description);
this._recording = false;
@@ -151,7 +249,7 @@ Profiler.SamplingHeapProfileTypeBase = class extends Profiler.ProfileType {
}
get buttonTooltip() {
- return this._recording ? Common.UIString('Stop heap profiling') : Common.UIString('Start heap profiling');
+ return this._recording ? ls`Stop heap profiling` : ls`Start heap profiling`;
}
/**
@@ -159,37 +257,36 @@ Profiler.SamplingHeapProfileTypeBase = class extends Profiler.ProfileType {
* @return {boolean}
*/
buttonClicked() {
- const wasRecording = this._recording;
- if (wasRecording)
- this.stopRecordingProfile();
+ if (this._recording)
+ this._stopRecordingProfile();
else
- this.startRecordingProfile();
- return !wasRecording;
+ this._startRecordingProfile();
+ return this._recording;
}
- startRecordingProfile() {
+ _startRecordingProfile() {
const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel);
if (this.profileBeingRecorded() || !heapProfilerModel)
return;
- const profile = new Profiler.SamplingHeapProfileHeader(heapProfilerModel, this);
- this.setProfileBeingRecorded(profile);
- this.addProfile(profile);
- profile.updateStatus(Common.UIString('Recording\u2026'));
+ const profileHeader = new Profiler.SamplingHeapProfileHeader(heapProfilerModel, this);
+ this.setProfileBeingRecorded(profileHeader);
+ this.addProfile(profileHeader);
+ profileHeader.updateStatus(ls`Recording\u2026`);
const icon = UI.Icon.create('smallicon-warning');
- icon.title = Common.UIString('Heap profiler is recording');
+ icon.title = ls`Heap profiler is recording`;
UI.inspectorView.setPanelIcon('heap_profiler', icon);
this._recording = true;
this._startSampling();
}
- async stopRecordingProfile() {
+ async _stopRecordingProfile() {
this._recording = false;
if (!this.profileBeingRecorded() || !this.profileBeingRecorded().heapProfilerModel())
return;
- this.profileBeingRecorded().updateStatus(Common.UIString('Stopping\u2026'));
+ this.profileBeingRecorded().updateStatus(ls`Stopping\u2026`);
const profile = await this._stopSampling();
const recordedProfile = this.profileBeingRecorded();
if (recordedProfile) {
@@ -215,7 +312,7 @@ Profiler.SamplingHeapProfileTypeBase = class extends Profiler.ProfileType {
* @override
*/
profileBeingRecordedRemoved() {
- this.stopRecordingProfile();
+ this._stopRecordingProfile();
}
_startSampling() {
@@ -230,7 +327,6 @@ Profiler.SamplingHeapProfileTypeBase = class extends Profiler.ProfileType {
}
};
-
/**
* @unrestricted
*/
@@ -238,6 +334,8 @@ Profiler.SamplingHeapProfileType = class extends Profiler.SamplingHeapProfileTyp
constructor() {
super(Profiler.SamplingHeapProfileType.TypeId, ls`Allocation sampling`);
Profiler.SamplingHeapProfileType.instance = this;
+ this._updateTimer = null;
+ this._updateIntervalMs = 200;
}
get treeItemTitle() {
@@ -252,9 +350,19 @@ Profiler.SamplingHeapProfileType = class extends Profiler.SamplingHeapProfileTyp
/**
* @override
+ * @return {boolean}
+ */
+ hasTemporaryView() {
+ return Runtime.experiments.isEnabled('samplingHeapProfilerTimeline');
+ }
+
+ /**
+ * @override
*/
_startSampling() {
this.profileBeingRecorded().heapProfilerModel().startSampling();
+ if (Runtime.experiments.isEnabled('samplingHeapProfilerTimeline'))
+ this._updateTimer = setTimeout(this._updateStats.bind(this), this._updateIntervalMs);
}
/**
@@ -262,12 +370,29 @@ Profiler.SamplingHeapProfileType = class extends Profiler.SamplingHeapProfileTyp
* return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
*/
_stopSampling() {
+ clearTimeout(this._updateTimer);
+ this._updateTimer = null;
+ this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.RecordingStopped);
return this.profileBeingRecorded().heapProfilerModel().stopSampling();
}
+
+ async _updateStats() {
+ const profile = await this.profileBeingRecorded().heapProfilerModel().getSamplingProfile();
+ if (!this._updateTimer)
+ return;
+ this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.StatsUpdate, profile);
+ this._updateTimer = setTimeout(this._updateStats.bind(this), this._updateIntervalMs);
+ }
};
Profiler.SamplingHeapProfileType.TypeId = 'SamplingHeap';
+/** @enum {symbol} */
+Profiler.SamplingHeapProfileType.Events = {
+ RecordingStopped: Symbol('RecordingStopped'),
+ StatsUpdate: Symbol('StatsUpdate')
+};
+
/**
* @unrestricted
*/
@@ -426,6 +551,8 @@ Profiler.SamplingHeapProfileHeader = class extends Profiler.WritableProfileHeade
heapProfilerModel && heapProfilerModel.debuggerModel(), type,
title || Common.UIString('Profile %d', type.nextProfileUid()));
this._heapProfilerModel = heapProfilerModel;
+ this._protocolProfile =
+ /** @type {!Protocol.HeapProfiler.SamplingHeapProfile} */ ({head: {callFrame: {}, children: []}});
}
/**
@@ -478,29 +605,61 @@ Profiler.SamplingHeapProfileNode = class extends SDK.ProfileNode {
Profiler.SamplingHeapProfileModel = class extends SDK.ProfileTreeModel {
/**
* @param {!Protocol.HeapProfiler.SamplingHeapProfile} profile
+ * @param {number=} minOrdinal
+ * @param {number=} maxOrdinal
*/
- constructor(profile) {
+ constructor(profile, minOrdinal, maxOrdinal) {
super();
- this.initialize(translateProfileTree(profile.head));
this.modules = profile.modules || [];
+ /** @type {?Map<number, number>} */
+ let nodeIdToSizeMap = null;
+ if (minOrdinal || maxOrdinal) {
+ nodeIdToSizeMap = new Map();
+ minOrdinal = minOrdinal || 0;
+ maxOrdinal = maxOrdinal || Infinity;
+ for (const sample of profile.samples) {
+ if (sample.ordinal < minOrdinal || sample.ordinal > maxOrdinal)
+ continue;
+ const size = nodeIdToSizeMap.get(sample.nodeId) || 0;
+ nodeIdToSizeMap.set(sample.nodeId, size + sample.size);
+ }
+ }
+
+ this.initialize(translateProfileTree(profile.head));
+
/**
* @param {!Protocol.HeapProfiler.SamplingHeapProfileNode} root
* @return {!Profiler.SamplingHeapProfileNode}
*/
function translateProfileTree(root) {
const resultRoot = new Profiler.SamplingHeapProfileNode(root);
- const targetNodeStack = [resultRoot];
const sourceNodeStack = [root];
+ const targetNodeStack = [resultRoot];
while (sourceNodeStack.length) {
const sourceNode = sourceNodeStack.pop();
- const parentNode = targetNodeStack.pop();
- parentNode.children = sourceNode.children.map(child => new Profiler.SamplingHeapProfileNode(child));
- sourceNodeStack.push.apply(sourceNodeStack, sourceNode.children);
- targetNodeStack.push.apply(targetNodeStack, parentNode.children);
+ const targetNode = targetNodeStack.pop();
+ targetNode.children = sourceNode.children.map(child => {
+ const targetChild = new Profiler.SamplingHeapProfileNode(child);
+ if (nodeIdToSizeMap)
+ targetChild.self = nodeIdToSizeMap.get(child.id) || 0;
+ return targetChild;
+ });
+ sourceNodeStack.pushAll(sourceNode.children);
+ targetNodeStack.pushAll(targetNode.children);
}
+ pruneEmptyBranches(resultRoot);
return resultRoot;
}
+
+ /**
+ * @param {!SDK.ProfileNode} node
+ * @return {boolean}
+ */
+ function pruneEmptyBranches(node) {
+ node.children = node.children.filter(pruneEmptyBranches);
+ return !!(node.children.length || node.self);
+ }
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js b/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js
index 482e79554c3..c33e9506279 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js
@@ -180,6 +180,7 @@ Profiler.HeapSnapshotView = class extends UI.SimpleView {
Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate, this._onHeapStatsUpdate, this);
profileType.addEventListener(
Profiler.TrackingHeapSnapshotProfileType.TrackingStopped, this._onStopTracking, this);
+ this._trackingOverviewGrid.start();
}
}
@@ -188,6 +189,8 @@ Profiler.HeapSnapshotView = class extends UI.SimpleView {
Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate, this._onHeapStatsUpdate, this);
this._profile.profileType().removeEventListener(
Profiler.TrackingHeapSnapshotProfileType.TrackingStopped, this._onStopTracking, this);
+ if (this._trackingOverviewGrid)
+ this._trackingOverviewGrid.stop();
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js b/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js
index 6b3826573eb..e60c72bfab1 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js
@@ -29,12 +29,27 @@ Profiler.HeapTimelineOverview = class extends UI.VBox {
this._profileSamples = new Profiler.HeapTimelineOverview.Samples();
}
+ start() {
+ this._running = true;
+ const drawFrame = () => {
+ this.update();
+ if (this._running)
+ this.element.window().requestAnimationFrame(drawFrame);
+ };
+ drawFrame();
+ }
+
+ stop() {
+ this._running = false;
+ }
+
/**
* @param {!Profiler.HeapTimelineOverview.Samples} samples
*/
setSamples(samples) {
this._profileSamples = samples;
- this.update();
+ if (!this._running)
+ this.update();
}
/**
@@ -49,7 +64,6 @@ Profiler.HeapTimelineOverview = class extends UI.VBox {
const topSizes = profileSamples.max;
const timestamps = profileSamples.timestamps;
const startTime = timestamps[0];
- const endTime = timestamps[timestamps.length - 1];
const scaleFactor = this._xScale.nextScale(width / profileSamples.totalTime);
let maxSize = 0;
@@ -93,14 +107,16 @@ Profiler.HeapTimelineOverview = class extends UI.VBox {
const context = this._overviewCanvas.getContext('2d');
context.scale(window.devicePixelRatio, window.devicePixelRatio);
- context.beginPath();
- context.lineWidth = 2;
- context.strokeStyle = 'rgba(192, 192, 192, 0.6)';
- const currentX = (endTime - startTime) * scaleFactor;
- context.moveTo(currentX, height - 1);
- context.lineTo(currentX, 0);
- context.stroke();
- context.closePath();
+ if (this._running) {
+ context.beginPath();
+ context.lineWidth = 2;
+ context.strokeStyle = 'rgba(192, 192, 192, 0.6)';
+ const currentX = (Date.now() - startTime) * scaleFactor;
+ context.moveTo(currentX, height - 1);
+ context.lineTo(currentX, 0);
+ context.stroke();
+ context.closePath();
+ }
let gridY;
let gridValue;
@@ -204,30 +220,23 @@ Profiler.HeapTimelineOverview = class extends UI.VBox {
this._updateGridTimerId = 0;
this._updateBoundaries();
const ids = this._profileSamples.ids;
+ if (!ids.length)
+ return;
const timestamps = this._profileSamples.timestamps;
const sizes = this._profileSamples.sizes;
const startTime = timestamps[0];
const totalTime = this._profileSamples.totalTime;
const timeLeft = startTime + totalTime * this._windowLeft;
const timeRight = startTime + totalTime * this._windowRight;
- let minId = 0;
- let maxId = ids[ids.length - 1] + 1;
+ const minIndex = timestamps.lowerBound(timeLeft);
+ const maxIndex = timestamps.upperBound(timeRight);
let size = 0;
- for (let i = 0; i < timestamps.length; ++i) {
- if (!timestamps[i])
- continue;
- if (timestamps[i] > timeRight)
- break;
- maxId = ids[i];
- if (timestamps[i] < timeLeft) {
- minId = ids[i];
- continue;
- }
+ for (let i = minIndex; i < maxIndex; ++i)
size += sizes[i];
- }
+ const minId = minIndex < ids.length ? ids[minIndex] : Infinity;
+ const maxId = maxIndex < ids.length ? ids[maxIndex] : Infinity;
- this.dispatchEventToListeners(
- Profiler.HeapTimelineOverview.IdsRangeChanged, {minId: minId, maxId: maxId, size: size});
+ this.dispatchEventToListeners(Profiler.HeapTimelineOverview.IdsRangeChanged, {minId, maxId, size});
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js b/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js
index c61e126719b..ab3c2e8183d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js
@@ -1,6 +1,7 @@
// 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.
+
/**
* @implements {UI.Searchable}
* @unrestricted
@@ -9,6 +10,8 @@ Profiler.ProfileView = class extends UI.SimpleView {
constructor() {
super(Common.UIString('Profile'));
+ this._profile = null;
+
this._searchableView = new UI.SearchableView(this);
this._searchableView.setPlaceholder(Common.UIString('Find by cost (>50ms), name or file'));
this._searchableView.show(this.element);
@@ -62,6 +65,24 @@ Profiler.ProfileView = class extends UI.SimpleView {
}
/**
+ * @param {!SDK.ProfileTreeModel} profile
+ */
+ setProfile(profile) {
+ this._profile = profile;
+ this._bottomUpProfileDataGridTree = null;
+ this._topDownProfileDataGridTree = null;
+ this._changeView();
+ this.refresh();
+ }
+
+ /**
+ * @return {?SDK.ProfileTreeModel}
+ */
+ profile() {
+ return this._profile;
+ }
+
+ /**
* @param {!Profiler.ProfileDataGridNode.Formatter} nodeFormatter
* @param {!Array<string>=} viewTypes
* @protected
@@ -122,7 +143,7 @@ Profiler.ProfileView = class extends UI.SimpleView {
/**
* @override
- * @return {!Array.<!UI.ToolbarItem>}
+ * @return {!Array<!UI.ToolbarItem>}
*/
syncToolbarItems() {
return [this.viewSelectComboBox, this.focusButton, this.excludeButton, this.resetButton];
@@ -134,7 +155,7 @@ Profiler.ProfileView = class extends UI.SimpleView {
_getBottomUpProfileDataGridTree() {
if (!this._bottomUpProfileDataGridTree) {
this._bottomUpProfileDataGridTree = new Profiler.BottomUpProfileDataGridTree(
- this._nodeFormatter, this._searchableView, this.profile.root, this.adjustedTotal);
+ this._nodeFormatter, this._searchableView, this._profile.root, this.adjustedTotal);
}
return this._bottomUpProfileDataGridTree;
}
@@ -145,7 +166,7 @@ Profiler.ProfileView = class extends UI.SimpleView {
_getTopDownProfileDataGridTree() {
if (!this._topDownProfileDataGridTree) {
this._topDownProfileDataGridTree = new Profiler.TopDownProfileDataGridTree(
- this._nodeFormatter, this._searchableView, this.profile.root, this.adjustedTotal);
+ this._nodeFormatter, this._searchableView, this._profile.root, this.adjustedTotal);
}
return this._topDownProfileDataGridTree;
}
@@ -158,6 +179,8 @@ Profiler.ProfileView = class extends UI.SimpleView {
}
refresh() {
+ if (!this.profileDataGridTree)
+ return;
const selectedProfileNode = this.dataGrid.selectedNode ? this.dataGrid.selectedNode.profileNode : null;
this.dataGrid.rootNode().removeChildren();
@@ -288,7 +311,7 @@ Profiler.ProfileView = class extends UI.SimpleView {
}
_changeView() {
- if (!this.profile)
+ if (!this._profile)
return;
this._searchableView.closeSearch();
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js b/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js
index d7d5ffe0aec..eb7ffe825b1 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js
@@ -328,8 +328,7 @@ Profiler.ProfilesPanel = class extends UI.PanelWithSidebar {
if (i !== -1)
this._profileToView.splice(i, 1);
- const profileType = profile.profileType();
- const typeId = profileType.id;
+ const typeId = profile.profileType().id;
const sectionIsEmpty = this._typeIdToSidebarSection[typeId].removeProfileHeader(profile);
// No other item will be selected if there aren't any other profiles, so
@@ -410,11 +409,7 @@ Profiler.ProfilesPanel = class extends UI.PanelWithSidebar {
* @return {number}
*/
_indexOfViewForProfile(profile) {
- for (let i = 0; i < this._profileToView.length; i++) {
- if (this._profileToView[i].profile === profile)
- return i;
- }
- return -1;
+ return this._profileToView.findIndex(item => item.profile === profile);
}
closeVisibleView() {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/profiler/heapProfiler.css b/chromium/third_party/blink/renderer/devtools/front_end/profiler/heapProfiler.css
index c5f604461b5..7e5ce499e7f 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/profiler/heapProfiler.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/profiler/heapProfiler.css
@@ -70,7 +70,7 @@
flex: auto;
}
-.heap-snapshot-view .heap-tracking-overview {
+.profile-view .heap-tracking-overview {
flex: 0 0 80px;
height: 80px;
}
@@ -145,7 +145,7 @@
opacity: 0.6;
}
-#heap-recording-view .heap-snapshot-view {
+#heap-recording-view .profile-view {
top: 80px;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js b/chromium/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js
index c8f591949f7..93c140d0d0f 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js
@@ -36,8 +36,10 @@ Protocol.Error = Symbol('Protocol.Error');
*/
Protocol.InspectorBackend = class {
constructor() {
- this._agentPrototypes = {};
- this._dispatcherPrototypes = {};
+ /** @type {!Map<string, !Protocol.InspectorBackend._AgentPrototype>} */
+ this._agentPrototypes = new Map();
+ /** @type {!Map<string, !Protocol.InspectorBackend._DispatcherPrototype>} */
+ this._dispatcherPrototypes = new Map();
this._initialized = false;
}
@@ -90,12 +92,12 @@ Protocol.InspectorBackend = class {
* @return {!Protocol.InspectorBackend._AgentPrototype}
*/
_agentPrototype(domain) {
- if (!this._agentPrototypes[domain]) {
- this._agentPrototypes[domain] = new Protocol.InspectorBackend._AgentPrototype(domain);
+ if (!this._agentPrototypes.has(domain)) {
+ this._agentPrototypes.set(domain, new Protocol.InspectorBackend._AgentPrototype(domain));
this._addAgentGetterMethodToProtocolTargetPrototype(domain);
}
- return this._agentPrototypes[domain];
+ return this._agentPrototypes.get(domain);
}
/**
@@ -103,9 +105,9 @@ Protocol.InspectorBackend = class {
* @return {!Protocol.InspectorBackend._DispatcherPrototype}
*/
_dispatcherPrototype(domain) {
- if (!this._dispatcherPrototypes[domain])
- this._dispatcherPrototypes[domain] = new Protocol.InspectorBackend._DispatcherPrototype();
- return this._dispatcherPrototypes[domain];
+ if (!this._dispatcherPrototypes.has(domain))
+ this._dispatcherPrototypes.set(domain, new Protocol.InspectorBackend._DispatcherPrototype());
+ return this._dispatcherPrototypes.get(domain);
}
/**
@@ -173,167 +175,176 @@ Protocol.InspectorBackend = class {
}
};
-Protocol.InspectorBackend._ConnectionClosedErrorCode = -32000;
-Protocol.InspectorBackend.DevToolsStubErrorCode = -32015;
-
+Protocol.DevToolsStubErrorCode = -32015;
Protocol.inspectorBackend = new Protocol.InspectorBackend();
/**
- * @unrestricted
+ * @interface
*/
-Protocol.InspectorBackend.Connection = class {
+Protocol.Connection = function() {};
+
+Protocol.Connection.prototype = {
/**
- * @param {string} domain
- * @param {!Protocol.InspectorBackend.Connection.MessageObject} messageObject
+ * @param {function((!Object|string))} onMessage
*/
- sendMessage(domain, messageObject) {
- this.sendRawMessage(JSON.stringify(messageObject));
- }
+ setOnMessage(onMessage) {},
+
+ /**
+ * @param {function(string)} onDisconnect
+ */
+ setOnDisconnect(onDisconnect) {},
/**
* @param {string} message
*/
- sendRawMessage(message) {}
+ sendRawMessage(message) {},
/**
* @return {!Promise}
*/
- disconnect() {}
+ disconnect() {},
};
-/**
- * @typedef {!{
- * id: number,
- * method: string,
- * params: (!Object|undefined)
- * }}
- */
-Protocol.InspectorBackend.Connection.MessageObject;
+Protocol.test = {
+ /**
+ * This will get called for every protocol message.
+ * Protocol.test.dumpProtocol = console.log
+ * @type {?function(string)}
+ */
+ dumpProtocol: null,
-/**
- * @typedef {!{
- * onMessage: function((!Object|string)),
- * onDisconnect: function(string)
- * }}
- */
-Protocol.InspectorBackend.Connection.Params;
+ /**
+ * Runs a function when no protocol activity is present.
+ * Protocol.test.deprecatedRunAfterPendingDispatches(() => console.log('done'))
+ * @type {?function(function()=)}
+ */
+ deprecatedRunAfterPendingDispatches: null,
+
+ /**
+ * Sends a raw message over main connection.
+ * Protocol.test.sendRawMessage('Page.enable', {}, console.log)
+ */
+ sendRawMessage: null,
+
+ /**
+ * Set to true to not log any errors.
+ */
+ suppressRequestErrors: false,
+
+ /**
+ * Set to get notified about any messages sent over protocol.
+ * @type {?function({domain: string, method: string, params: !Object, id: number})}
+ */
+ onMessageSent: null,
+
+ /**
+ * Set to get notified about any messages received over protocol.
+ * @type {?function(!Object)}
+ */
+ onMessageReceived: null,
+};
/**
- * @typedef {function(!Protocol.InspectorBackend.Connection.Params):!Protocol.InspectorBackend.Connection}
+ * @param {function():!Protocol.Connection} factory
*/
-Protocol.InspectorBackend.Connection.Factory;
+Protocol.Connection.setFactory = function(factory) {
+ Protocol.Connection._factory = factory;
+};
+
+
+/** @type {function():!Protocol.Connection} */
+Protocol.Connection._factory;
/**
- * @unrestricted
+ * Takes error and result.
+ * @typedef {function(?Object, ?Object)}
*/
-Protocol.TargetBase = class extends Common.Object {
- /**
- * @param {!Protocol.InspectorBackend.Connection.Factory} connectionFactory
- * @param {boolean} isNodeJS
- */
- constructor(connectionFactory, isNodeJS) {
- super();
- this._connection =
- connectionFactory({onMessage: this._onMessage.bind(this), onDisconnect: this._onDisconnect.bind(this)});
+Protocol._Callback;
+
+// TODO(dgozman): we are not reporting generic errors in tests, but we should
+// instead report them and just have some expected errors in test expectations.
+Protocol._GenericError = -32000;
+Protocol._ConnectionClosedErrorCode = -32001;
+
+Protocol.SessionRouter = class {
+ constructor() {
+ this._connection = Protocol.Connection._factory();
this._lastMessageId = 1;
this._pendingResponsesCount = 0;
- this._agents = {};
- this._dispatchers = {};
- this._callbacks = {};
- this._initialize(Protocol.inspectorBackend._agentPrototypes, Protocol.inspectorBackend._dispatcherPrototypes);
this._domainToLogger = new Map();
- if (!Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches) {
- Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches =
- this._deprecatedRunAfterPendingDispatches.bind(this);
- }
- if (!Protocol.InspectorBackend.sendRawMessageForTesting)
- Protocol.InspectorBackend.sendRawMessageForTesting = this._sendRawMessageForTesting.bind(this);
- this._isNodeJS = isNodeJS;
+
+ /** @type {!Map<string, {target: !Protocol.TargetBase, callbacks: !Map<number, !Protocol._Callback>}>} */
+ this._sessions = new Map();
+
+ /** @type {!Array<function()>} */
+ this._pendingScripts = [];
+
+ Protocol.test.deprecatedRunAfterPendingDispatches = this._deprecatedRunAfterPendingDispatches.bind(this);
+ Protocol.test.sendRawMessage = this._sendRawMessageForTesting.bind(this);
+
+ this._connection.setOnMessage(this._onMessage.bind(this));
+
+ this._connection.setOnDisconnect(reason => {
+ const session = this._sessions.get('');
+ if (session)
+ session.target.dispose(reason);
+ });
}
/**
- * @param {!Object.<string, !Protocol.InspectorBackend._AgentPrototype>} agentPrototypes
- * @param {!Object.<string, !Protocol.InspectorBackend._DispatcherPrototype>} dispatcherPrototypes
+ * @param {!Protocol.TargetBase} target
+ * @param {string} sessionId
*/
- _initialize(agentPrototypes, dispatcherPrototypes) {
- for (const domain in agentPrototypes) {
- this._agents[domain] = Object.create(agentPrototypes[domain]);
- this._agents[domain].setTarget(this);
- }
-
- for (const domain in dispatcherPrototypes) {
- this._dispatchers[domain] = Object.create(dispatcherPrototypes[domain]);
- this._dispatchers[domain].initialize();
- }
+ registerSession(target, sessionId) {
+ this._sessions.set(sessionId, {target, callbacks: new Map()});
}
/**
- * @return {number}
+ * @param {string} sessionId
*/
- _nextMessageId() {
- return this._lastMessageId++;
+ unregisterSession(sessionId) {
+ const session = this._sessions.get(sessionId);
+ for (const callback of session.callbacks.values())
+ Protocol.SessionRouter.dispatchConnectionError(callback);
+ this._sessions.delete(sessionId);
}
/**
- * @param {string} domain
- * @return {!Protocol.InspectorBackend._AgentPrototype}
+ * @return {number}
*/
- _agent(domain) {
- return this._agents[domain];
+ _nextMessageId() {
+ return this._lastMessageId++;
}
/**
+ * @param {string} sessionId
* @param {string} domain
* @param {string} method
* @param {?Object} params
- * @param {?function(*)} callback
+ * @param {!Protocol._Callback} callback
*/
- _wrapCallbackAndSendMessageObject(domain, method, params, callback) {
- if (!this._connection) {
- if (callback)
- this._dispatchConnectionErrorResponse(domain, method, callback);
- return;
- }
-
+ sendMessage(sessionId, domain, method, params, callback) {
const messageObject = {};
const messageId = this._nextMessageId();
messageObject.id = messageId;
messageObject.method = method;
if (params)
messageObject.params = params;
+ if (sessionId)
+ messageObject.sessionId = sessionId;
- const wrappedCallback = this._wrap(callback, domain, method);
+ if (Protocol.test.dumpProtocol)
+ Protocol.test.dumpProtocol('frontend: ' + JSON.stringify(messageObject));
- if (Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages)
- this._dumpProtocolMessage('frontend: ' + JSON.stringify(messageObject), '[FE] ' + domain);
- if (this.hasEventListeners(Protocol.TargetBase.Events.MessageSent)) {
- this.dispatchEventToListeners(
- Protocol.TargetBase.Events.MessageSent,
- {domain, method, params: JSON.parse(JSON.stringify(params)), id: messageId});
+ if (Protocol.test.onMessageSent) {
+ const paramsObject = JSON.parse(JSON.stringify(params || {}));
+ Protocol.test.onMessageSent({domain, method, params: /** @type {!Object} */ (paramsObject), id: messageId});
}
- this._connection.sendMessage(domain, messageObject);
++this._pendingResponsesCount;
- this._callbacks[messageId] = wrappedCallback;
- }
-
- /**
- * @param {?function(*)} callback
- * @param {string} method
- * @param {string} domain
- * @return {function(*)}
- */
- _wrap(callback, domain, method) {
- if (!callback)
- callback = function() {};
-
- callback.methodName = method;
- callback.domain = domain;
- if (Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
- callback.sendRequestTime = Date.now();
-
- return callback;
+ this._sessions.get(sessionId).callbacks.set(messageId, callback);
+ this._connection.sendRawMessage(JSON.stringify(messageObject));
}
/**
@@ -343,47 +354,45 @@ Protocol.TargetBase = class extends Common.Object {
*/
_sendRawMessageForTesting(method, params, callback) {
const domain = method.split('.')[0];
- this._wrapCallbackAndSendMessageObject(domain, method, params, callback);
+ this.sendMessage('', domain, method, params, callback || (() => {}));
}
/**
* @param {!Object|string} message
*/
_onMessage(message) {
- if (Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages) {
- this._dumpProtocolMessage(
- 'backend: ' + ((typeof message === 'string') ? message : JSON.stringify(message)), 'Backend');
- }
- if (this.hasEventListeners(Protocol.TargetBase.Events.MessageReceived)) {
- this.dispatchEventToListeners(Protocol.TargetBase.Events.MessageReceived, {
- message: JSON.parse((typeof message === 'string') ? message : JSON.stringify(message)),
- });
- }
+ if (Protocol.test.dumpProtocol)
+ Protocol.test.dumpProtocol('backend: ' + ((typeof message === 'string') ? message : JSON.stringify(message)));
+ if (Protocol.test.onMessageReceived) {
+ const messageObjectCopy = JSON.parse((typeof message === 'string') ? message : JSON.stringify(message));
+ Protocol.test.onMessageReceived(/** @type {!Object} */ (messageObjectCopy));
+ }
const messageObject = /** @type {!Object} */ ((typeof message === 'string') ? JSON.parse(message) : message);
- Protocol.NodeURL.patch(this, messageObject);
+ const sessionId = messageObject.sessionId || '';
+ const session = this._sessions.get(sessionId);
+ if (!session) {
+ Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message with wrong session id', messageObject);
+ return;
+ }
+
+ if (session.target._needsNodeJSPatching)
+ Protocol.NodeURL.patch(messageObject);
if ('id' in messageObject) { // just a response for some request
- const callback = this._callbacks[messageObject.id];
+ const callback = session.callbacks.get(messageObject.id);
+ session.callbacks.delete(messageObject.id);
if (!callback) {
Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message with wrong id', messageObject);
return;
}
- const timingLabel = 'time-stats: ' + callback.methodName;
- if (Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
- Protocol.InspectorBackend._timeLogger.time(timingLabel);
-
- this._agent(callback.domain).dispatchResponse(messageObject, callback.methodName, callback);
+ callback(messageObject.error, messageObject.result);
--this._pendingResponsesCount;
- delete this._callbacks[messageObject.id];
-
- if (Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
- Protocol.InspectorBackend._timeLogger.timeEnd(timingLabel);
- if (this._scripts && !this._pendingResponsesCount)
+ if (this._pendingScripts.length && !this._pendingResponsesCount)
this._deprecatedRunAfterPendingDispatches();
} else {
if (!('method' in messageObject)) {
@@ -393,135 +402,115 @@ Protocol.TargetBase = class extends Common.Object {
const method = messageObject.method.split('.');
const domainName = method[0];
- if (!(domainName in this._dispatchers)) {
+ if (!(domainName in session.target._dispatchers)) {
Protocol.InspectorBackend.reportProtocolError(
`Protocol Error: the message ${messageObject.method} is for non-existing domain '${domainName}'`,
messageObject);
return;
}
- this._dispatchers[domainName].dispatch(method[1], messageObject);
+ session.target._dispatchers[domainName].dispatch(method[1], messageObject);
}
}
/**
- * @param {string} domain
- * @param {!Object} dispatcher
- */
- registerDispatcher(domain, dispatcher) {
- if (!this._dispatchers[domain])
- return;
-
- this._dispatchers[domain].addDomainDispatcher(dispatcher);
- }
-
- /**
* @param {function()=} script
*/
_deprecatedRunAfterPendingDispatches(script) {
- if (!this._scripts)
- this._scripts = [];
-
if (script)
- this._scripts.push(script);
+ this._pendingScripts.push(script);
// Execute all promises.
- setTimeout(function() {
+ setTimeout(() => {
if (!this._pendingResponsesCount)
this._executeAfterPendingDispatches();
else
this._deprecatedRunAfterPendingDispatches();
- }.bind(this), 0);
+ }, 0);
}
_executeAfterPendingDispatches() {
if (!this._pendingResponsesCount) {
- const scripts = this._scripts;
- this._scripts = [];
+ const scripts = this._pendingScripts;
+ this._pendingScripts = [];
for (let id = 0; id < scripts.length; ++id)
- scripts[id].call(this);
+ scripts[id]();
}
}
/**
- * @param {string} message
- * @param {string} context
+ * @param {!Protocol._Callback} callback
*/
- _dumpProtocolMessage(message, context) {
- if (!this._domainToLogger.get(context))
- this._domainToLogger.set(context, console.context ? console.context(context) : console);
- const logger = this._domainToLogger.get(context);
- logger.log(message);
+ static dispatchConnectionError(callback) {
+ const error = {
+ message: 'Connection is closed, can\'t dispatch pending call',
+ code: Protocol._ConnectionClosedErrorCode,
+ data: null
+ };
+ setTimeout(() => callback(error, null), 0);
}
+};
+/**
+ * @unrestricted
+ */
+Protocol.TargetBase = class {
/**
- * @param {string} reason
+ * @param {boolean} needsNodeJSPatching
+ * @param {?Protocol.TargetBase} parentTarget
+ * @param {string} sessionId
*/
- _onDisconnect(reason) {
- this._connection = null;
- this._runPendingCallbacks();
- this.dispose();
- }
+ constructor(needsNodeJSPatching, parentTarget, sessionId) {
+ this._needsNodeJSPatching = needsNodeJSPatching;
+ this._sessionId = sessionId;
- /**
- * @protected
- */
- dispose() {
- }
+ this._router = parentTarget ? parentTarget._router : new Protocol.SessionRouter();
+ this._router.registerSession(this, this._sessionId);
- /**
- * @return {boolean}
- */
- isDisposed() {
- return !this._connection;
- }
+ this._agents = {};
+ for (const [domain, agentPrototype] of Protocol.inspectorBackend._agentPrototypes) {
+ this._agents[domain] = Object.create(/** @type {!Protocol.InspectorBackend._AgentPrototype} */ (agentPrototype));
+ this._agents[domain]._target = this;
+ }
- _runPendingCallbacks() {
- const keys = Object.keys(this._callbacks).map(function(num) {
- return parseInt(num, 10);
- });
- for (let i = 0; i < keys.length; ++i) {
- const callback = this._callbacks[keys[i]];
- this._dispatchConnectionErrorResponse(callback.domain, callback.methodName, callback);
+ this._dispatchers = {};
+ for (const [domain, dispatcherPrototype] of Protocol.inspectorBackend._dispatcherPrototypes) {
+ this._dispatchers[domain] =
+ Object.create(/** @type {!Protocol.InspectorBackend._DispatcherPrototype} */ (dispatcherPrototype));
+ this._dispatchers[domain]._dispatchers = [];
}
- this._callbacks = {};
}
/**
* @param {string} domain
- * @param {string} methodName
- * @param {function(*)} callback
+ * @param {!Object} dispatcher
*/
- _dispatchConnectionErrorResponse(domain, methodName, callback) {
- const error = {
- message: 'Connection is closed, can\'t dispatch pending ' + methodName,
- code: Protocol.InspectorBackend._ConnectionClosedErrorCode,
- data: null
- };
- const messageObject = {error: error};
- setTimeout(
- Protocol.InspectorBackend._AgentPrototype.prototype.dispatchResponse.bind(
- this._agent(domain), messageObject, methodName, callback),
- 0);
+ registerDispatcher(domain, dispatcher) {
+ if (!this._dispatchers[domain])
+ return;
+ this._dispatchers[domain].addDomainDispatcher(dispatcher);
+ }
+
+ /**
+ * @param {string} reason
+ */
+ dispose(reason) {
+ this._router.unregisterSession(this._sessionId);
+ this._router = null;
}
/**
* @return {boolean}
*/
- isNodeJS() {
- return this._isNodeJS;
+ isDisposed() {
+ return !this._router;
}
markAsNodeJSForTest() {
- this._isNodeJS = true;
+ this._needsNodeJSPatching = true;
}
};
-Protocol.TargetBase.Events = {
- MessageSent: Symbol('MessageSent'),
- MessageReceived: Symbol('MessageReceived')
-};
-
/**
* @unrestricted
*/
@@ -536,13 +525,6 @@ Protocol.InspectorBackend._AgentPrototype = class {
}
/**
- * @param {!Protocol.TargetBase} target
- */
- setTarget(target) {
- this._target = target;
- }
-
- /**
* @param {string} methodName
* @param {!Array.<!Object>} signature
* @param {!Array.<string>} replyArgs
@@ -646,14 +628,24 @@ Protocol.InspectorBackend._AgentPrototype = class {
return Promise.resolve(null);
return new Promise(resolve => {
- this._target._wrapCallbackAndSendMessageObject(this._domain, method, params, (error, result) => {
+ const callback = (error, result) => {
+ if (error && !Protocol.test.suppressRequestErrors && error.code !== Protocol.DevToolsStubErrorCode &&
+ error.code !== Protocol._GenericError && error.code !== Protocol._ConnectionClosedErrorCode)
+ console.error('Request ' + method + ' failed. ' + JSON.stringify(error));
+
+
if (error) {
resolve(null);
return;
}
const args = this._replyArgs[method];
resolve(result && args.length ? result[args[0]] : undefined);
- });
+ };
+
+ if (!this._target._router)
+ Protocol.SessionRouter.dispatchConnectionError(callback);
+ else
+ this._target._router.sendMessage(this._target._sessionId, this._domain, method, params, callback);
});
}
@@ -664,30 +656,24 @@ Protocol.InspectorBackend._AgentPrototype = class {
*/
_invoke(method, request) {
return new Promise(fulfill => {
- this._target._wrapCallbackAndSendMessageObject(this._domain, method, request, (error, result) => {
+ const callback = (error, result) => {
+ if (error && !Protocol.test.suppressRequestErrors && error.code !== Protocol.DevToolsStubErrorCode &&
+ error.code !== Protocol._GenericError && error.code !== Protocol._ConnectionClosedErrorCode)
+ console.error('Request ' + method + ' failed. ' + JSON.stringify(error));
+
+
if (!result)
result = {};
if (error)
result[Protocol.Error] = error.message;
fulfill(result);
- });
- });
- }
+ };
- /**
- * @param {!Object} messageObject
- * @param {string} methodName
- * @param {function(?Protocol.Error, ?Object)} callback
- */
- dispatchResponse(messageObject, methodName, callback) {
- if (messageObject.error && messageObject.error.code !== Protocol.InspectorBackend._ConnectionClosedErrorCode &&
- messageObject.error.code !== Protocol.InspectorBackend.DevToolsStubErrorCode &&
- !Protocol.InspectorBackend.Options.suppressRequestErrors) {
- const id =
- Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages ? ' with id = ' + messageObject.id : '';
- console.error('Request ' + methodName + id + ' failed. ' + JSON.stringify(messageObject.error));
- }
- callback(messageObject.error, messageObject.result);
+ if (!this._target._router)
+ Protocol.SessionRouter.dispatchConnectionError(callback);
+ else
+ this._target._router.sendMessage(this._target._sessionId, this._domain, method, request, callback);
+ });
}
};
@@ -707,10 +693,6 @@ Protocol.InspectorBackend._DispatcherPrototype = class {
this._eventArgs[eventName] = params;
}
- initialize() {
- this._dispatchers = [];
- }
-
/**
* @param {!Object} dispatcher
*/
@@ -739,25 +721,10 @@ Protocol.InspectorBackend._DispatcherPrototype = class {
params.push(messageObject.params[paramNames[i]]);
}
- const timingLabel = 'time-stats: ' + messageObject.method;
- if (Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
- Protocol.InspectorBackend._timeLogger.time(timingLabel);
-
for (let index = 0; index < this._dispatchers.length; ++index) {
const dispatcher = this._dispatchers[index];
if (functionName in dispatcher)
dispatcher[functionName].apply(dispatcher, params);
}
-
- if (Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
- Protocol.InspectorBackend._timeLogger.timeEnd(timingLabel);
}
};
-
-Protocol.InspectorBackend.Options = {
- dumpInspectorTimeStats: false,
- dumpInspectorProtocolMessages: false,
- suppressRequestErrors: false
-};
-
-Protocol.InspectorBackend._timeLogger = console.context ? console.context('Protocol timing') : console;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js b/chromium/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js
index b4234cb34da..e69d057cff2 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js
@@ -4,12 +4,10 @@
Protocol.NodeURL = class {
/**
- * @param {!Protocol.TargetBase} target
* @param {!Object} object
*/
- static patch(target, object) {
- if (target.isNodeJS())
- process(object, '');
+ static patch(object) {
+ process(object, '');
/**
* @param {!Object} object
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js b/chromium/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js
index 540000ca01f..b7208303b3e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js
@@ -6,7 +6,6 @@ ProtocolMonitor.ProtocolMonitor = class extends UI.VBox {
constructor() {
super(true);
this._nodes = [];
- this._recordingListeners = null;
this._started = false;
this._startTime = 0;
this._nodeForId = {};
@@ -151,22 +150,16 @@ ProtocolMonitor.ProtocolMonitor = class extends UI.VBox {
* @param {boolean} recording
*/
_setRecording(recording) {
- if (this._recordingListeners) {
- Common.EventTarget.removeEventListeners(this._recordingListeners);
- this._recordingListeners = null;
- }
-
if (recording) {
- this._recordingListeners = [
- SDK.targetManager.mainTarget().addEventListener(
- Protocol.TargetBase.Events.MessageReceived, this._messageRecieved, this),
- SDK.targetManager.mainTarget().addEventListener(Protocol.TargetBase.Events.MessageSent, this._messageSent, this)
- ];
+ Protocol.test.onMessageSent = this._messageSent.bind(this);
+ Protocol.test.onMessageReceived = this._messageRecieved.bind(this);
+ } else {
+ Protocol.test.onMessageSent = null;
+ Protocol.test.onMessageReceived = null;
}
}
- _messageRecieved(event) {
- const message = event.data.message;
+ _messageRecieved(message) {
if ('id' in message) {
const node = this._nodeForId[message.id];
if (!node)
@@ -189,8 +182,7 @@ ProtocolMonitor.ProtocolMonitor = class extends UI.VBox {
this._dataGrid.insertChild(node);
}
- _messageSent(event) {
- const message = event.data;
+ _messageSent(message) {
const node = new ProtocolMonitor.ProtocolMonitor.ProtocolNode({
method: message.method,
direction: 'sent',
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js b/chromium/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js
index 6057f5882e9..58cef467d77 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js
@@ -159,7 +159,7 @@ Resources.AppManifestView = class extends UI.VBox {
*/
_addToHomescreen(event) {
const target = SDK.targetManager.mainTarget();
- if (target && target.hasBrowserCapability()) {
+ if (target && target.type() === SDK.Target.Type.Frame) {
target.pageAgent().requestAppBanner();
Common.console.show();
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js b/chromium/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js
index 0872cfaf833..89ff44d6393 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js
@@ -36,6 +36,11 @@ Resources.ClearStorageView = class extends UI.ThrottledWidget {
const quota = this._reportView.appendSection(Common.UIString('Usage'));
this._quotaRow = quota.appendRow();
+ const learnMoreRow = quota.appendRow();
+ const learnMore = UI.XLink.create(
+ 'https://developers.google.com/web/tools/chrome-devtools/progressive-web-apps#opaque-responses',
+ ls`Learn more`);
+ learnMoreRow.appendChild(learnMore);
this._quotaUsage = null;
this._pieChart = new PerfUI.PieChart(110, Number.bytesToString, true);
this._pieChartLegend = createElement('div');
@@ -44,6 +49,10 @@ Resources.ClearStorageView = class extends UI.ThrottledWidget {
usageBreakdownRow.appendChild(this._pieChart.element);
usageBreakdownRow.appendChild(this._pieChartLegend);
+ const clearButtonSection = this._reportView.appendSection('', 'clear-storage-button').appendRow();
+ this._clearButton = UI.createTextButton(ls`Clear site data`, this._clear.bind(this));
+ clearButtonSection.appendChild(this._clearButton);
+
const application = this._reportView.appendSection(Common.UIString('Application'));
this._appendItem(application, Common.UIString('Unregister service workers'), 'service_workers');
@@ -57,11 +66,7 @@ Resources.ClearStorageView = class extends UI.ThrottledWidget {
this._appendItem(caches, Common.UIString('Cache storage'), 'cache_storage');
this._appendItem(caches, Common.UIString('Application cache'), 'appcache');
- SDK.targetManager.observeTargets(this, SDK.Target.Capability.Browser);
- const footer = this._reportView.appendSection('', 'clear-storage-button').appendRow();
- this._clearButton = UI.createTextButton(
- Common.UIString('Clear site data'), this._clear.bind(this), Common.UIString('Clear site data'));
- footer.appendChild(this._clearButton);
+ SDK.targetManager.observeTargets(this);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js b/chromium/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js
index 65ec8edfceb..c102c67324a 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js
@@ -223,13 +223,9 @@ Resources.IDBDataView = class extends UI.SimpleView {
this._pageForwardButton.addEventListener(UI.ToolbarButton.Events.Click, this._pageForwardButtonClicked, this);
editorToolbar.appendToolbarItem(this._pageForwardButton);
- this._keyInputElement = UI.createInput('toolbar-input');
- editorToolbar.appendToolbarItem(new UI.ToolbarItem(this._keyInputElement));
- this._keyInputElement.placeholder = Common.UIString('Start from key');
- this._keyInputElement.addEventListener('paste', this._keyInputChanged.bind(this), false);
- this._keyInputElement.addEventListener('cut', this._keyInputChanged.bind(this), false);
- this._keyInputElement.addEventListener('keypress', this._keyInputChanged.bind(this), false);
- this._keyInputElement.addEventListener('keydown', this._keyInputChanged.bind(this), false);
+ this._keyInput = new UI.ToolbarInput(ls`Start from key`, 0.5);
+ this._keyInput.addEventListener(UI.ToolbarInput.Event.TextChanged, this._updateData.bind(this, false));
+ editorToolbar.appendToolbarItem(this._keyInput);
editorToolbar.appendToolbarItem(this._needsRefresh);
}
@@ -250,10 +246,6 @@ Resources.IDBDataView = class extends UI.SimpleView {
this._updateData(false);
}
- _keyInputChanged() {
- window.setTimeout(this._updateData.bind(this, false), 0);
- }
-
refreshData() {
this._updateData(true);
}
@@ -292,7 +284,7 @@ Resources.IDBDataView = class extends UI.SimpleView {
* @param {boolean} force
*/
_updateData(force) {
- const key = this._parseKey(this._keyInputElement.value);
+ const key = this._parseKey(this._keyInput.value());
const pageSize = this._pageSize;
let skipCount = this._skipCount;
let selected = this._dataGrid.selectedNode ? this._dataGrid.selectedNode.data['number'] : 0;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js b/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js
index 642804df148..1b43324e8df 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js
@@ -98,6 +98,7 @@ Resources.ServiceWorkerCacheView = class extends UI.SimpleView {
_createDataGrid() {
const columns = /** @type {!Array<!DataGrid.DataGrid.ColumnDescriptor>} */ ([
{id: 'path', title: Common.UIString('Path'), weight: 4, sortable: true},
+ {id: 'responseType', title: ls`Response-Type`, weight: 1, align: DataGrid.DataGrid.Align.Right, sortable: true},
{id: 'contentType', title: Common.UIString('Content-Type'), weight: 1, sortable: true}, {
id: 'contentLength',
title: Common.UIString('Content-Length'),
@@ -214,7 +215,7 @@ Resources.ServiceWorkerCacheView = class extends UI.SimpleView {
for (const entry of entries) {
let node = oldEntries.get(entry.requestURL);
if (!node || node.data.responseTime !== entry.responseTime) {
- node = new Resources.ServiceWorkerCacheView.DataGridNode(this._createRequest(entry));
+ node = new Resources.ServiceWorkerCacheView.DataGridNode(this._createRequest(entry), entry.responseType);
node.selectable = true;
}
rootNode.appendChild(node);
@@ -335,13 +336,15 @@ Resources.ServiceWorkerCacheView._RESPONSE_CACHE_SIZE = 10;
Resources.ServiceWorkerCacheView.DataGridNode = class extends DataGrid.DataGridNode {
/**
* @param {!SDK.NetworkRequest} request
+ * @param {!Protocol.CacheStorage.CachedResponseType} responseType
*/
- constructor(request) {
+ constructor(request, responseType) {
super(request);
this._path = Common.ParsedURL.extractPath(request.url());
if (!this._path)
this._path = request.url();
this._request = request;
+ this._responseType = responseType;
}
/**
@@ -352,14 +355,22 @@ Resources.ServiceWorkerCacheView.DataGridNode = class extends DataGrid.DataGridN
createCell(columnId) {
const cell = this.createTD(columnId);
let value;
- if (columnId === 'path')
+ if (columnId === 'path') {
value = this._path;
- else if (columnId === 'contentType')
+ } else if (columnId === 'responseType') {
+ if (this._responseType === 'opaqueResponse')
+ value = 'opaque';
+ else if (this._responseType === 'opaqueRedirect')
+ value = 'opaqueredirect';
+ else
+ value = this._responseType;
+ } else if (columnId === 'contentType') {
value = this._request.mimeType;
- else if (columnId === 'contentLength')
+ } else if (columnId === 'contentLength') {
value = (this._request.resourceSize | 0).toLocaleString('en-US');
- else if (columnId === 'responseTime')
+ } else if (columnId === 'responseTime') {
value = new Date(this._request.endTime * 1000).toLocaleString();
+ }
DataGrid.DataGrid.setElementText(cell, value || '', true);
return cell;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js b/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js
index 6e9691ffe1f..c0ef89cb815 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js
@@ -34,6 +34,8 @@ Resources.ServiceWorkersView = class extends UI.VBox {
this._otherSWFilter.setAttribute('role', 'switch');
this._otherSWFilter.setAttribute('aria-checked', false);
this._otherSWFilter.addEventListener('keydown', event => {
+ if (event.target !== this._otherSWFilter)
+ return;
if (isEnterKey(event) || event.keyCode === UI.KeyboardShortcut.Keys.Space.code)
this._toggleFilter();
});
@@ -534,12 +536,14 @@ Resources.ServiceWorkersView.Section = class {
*/
_updateClientInfo(element, targetInfo) {
if (targetInfo.type !== 'page' && targetInfo.type === 'iframe') {
- element.createTextChild(Common.UIString('Worker: %s', targetInfo.url));
+ const clientString = element.createChild('span', 'service-worker-client-string');
+ clientString.createTextChild(ls`Worker: ` + targetInfo.url);
return;
}
element.removeChildren();
- element.createTextChild(targetInfo.url);
- const focusLabel = element.createChild('label', 'link');
+ const clientString = element.createChild('span', 'service-worker-client-string');
+ clientString.createTextChild(targetInfo.url);
+ const focusLabel = element.createChild('label', 'link service-worker-client-focus-link');
focusLabel.createTextChild('focus');
focusLabel.addEventListener('click', this._activateTarget.bind(this, targetInfo.targetId), true);
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/clearStorageView.css b/chromium/third_party/blink/renderer/devtools/front_end/resources/clearStorageView.css
index abbed68132e..9cb3cf5061a 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/clearStorageView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/clearStorageView.css
@@ -10,7 +10,7 @@
}
.clear-storage-button .report-row {
- margin: 0 0 0 20px;
+ margin: 0 0 0 17px;
display: flex;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/module.json b/chromium/third_party/blink/renderer/devtools/front_end/resources/module.json
index a7034611092..9a0157046b4 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/module.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/module.json
@@ -6,7 +6,8 @@
"id": "resources",
"title": "Application",
"order": 70,
- "className": "Resources.ResourcesPanel"
+ "className": "Resources.ResourcesPanel",
+ "tags": "pwa"
},
{
"type": "@Common.Revealer",
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/resources/serviceWorkersView.css b/chromium/third_party/blink/renderer/devtools/front_end/resources/serviceWorkersView.css
index b18d04c89c8..e10e38f2b8a 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/resources/serviceWorkersView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/resources/serviceWorkersView.css
@@ -107,6 +107,22 @@
min-width: 80px;
}
+.report-field-value-filename,
+.service-worker-client-string {
+ max-width: 400px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.service-worker-client {
+ display: flex;
+}
+
+.service-worker-client-focus-link {
+ flex: none;
+ margin-right: 5px;
+}
+
.service-worker-notification-editor.source-code {
/** Simulate CodeMirror that is shown above */
padding: 4px;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js
index 559e26aa151..2af3af65392 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js
@@ -17,20 +17,20 @@ SDK.ChildTargetManager = class extends SDK.SDKModel {
/** @type {!Map<string, !Protocol.Target.TargetInfo>} */
this._targetInfos = new Map();
- /** @type {!Map<string, !SDK.ChildConnection>} */
- this._childConnections = new Map();
+ /** @type {!Map<string, !SDK.Target>} */
+ this._childTargets = new Map();
parentTarget.registerTargetDispatcher(this);
- this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true});
+ this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true, flatten: true});
- if (!parentTarget.parentTarget()) {
+ if (!parentTarget.parentTarget() && !Host.isUnderTest()) {
this._targetAgent.setDiscoverTargets(true);
this._targetAgent.setRemoteLocations([{host: 'localhost', port: 9229}]);
}
}
/**
- * @param {function({target: !SDK.Target, waitingForDebugger: boolean})=} attachCallback
+ * @param {function({target: !SDK.Target, waitingForDebugger: boolean}):!Promise=} attachCallback
*/
static install(attachCallback) {
SDK.ChildTargetManager._attachCallback = attachCallback;
@@ -42,7 +42,7 @@ SDK.ChildTargetManager = class extends SDK.SDKModel {
* @return {!Promise}
*/
suspendModel() {
- return this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false});
+ return this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false, flatten: true});
}
/**
@@ -50,37 +50,18 @@ SDK.ChildTargetManager = class extends SDK.SDKModel {
* @return {!Promise}
*/
resumeModel() {
- return this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true});
+ return this._targetAgent.invoke_setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true, flatten: true});
}
/**
* @override
*/
dispose() {
- for (const sessionId of this._childConnections.keys())
+ for (const sessionId of this._childTargets.keys())
this.detachedFromTarget(sessionId, undefined);
}
/**
- * @param {string} type
- * @return {number}
- */
- _capabilitiesForType(type) {
- if (type === 'worker') {
- return SDK.Target.Capability.JS | SDK.Target.Capability.Log | SDK.Target.Capability.Network |
- SDK.Target.Capability.Target;
- }
- if (type === 'service_worker')
- return SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target;
- if (type === 'iframe') {
- return SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | SDK.Target.Capability.JS |
- SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target |
- SDK.Target.Capability.Tracing | SDK.Target.Capability.Emulation | SDK.Target.Capability.Input;
- }
- return 0;
- }
-
- /**
* @override
* @param {!Protocol.Target.TargetInfo} targetInfo
*/
@@ -134,13 +115,26 @@ SDK.ChildTargetManager = class extends SDK.SDKModel {
targetName = parsedURL ? parsedURL.lastPathComponentWithFragment() :
'#' + (++SDK.ChildTargetManager._lastAnonymousTargetId);
}
- const target = this._targetManager.createTarget(
- targetInfo.targetId, targetName, this._capabilitiesForType(targetInfo.type),
- this._createChildConnection.bind(this, this._targetAgent, sessionId), this._parentTarget, false /* isNodeJS */);
- if (SDK.ChildTargetManager._attachCallback)
- SDK.ChildTargetManager._attachCallback({target, waitingForDebugger});
- target.runtimeAgent().runIfWaitingForDebugger();
+ let type = SDK.Target.Type.Browser;
+ if (targetInfo.type === 'iframe')
+ type = SDK.Target.Type.Frame;
+ else if (targetInfo.type === 'worker')
+ type = SDK.Target.Type.Worker;
+ else if (targetInfo.type === 'service_worker')
+ type = SDK.Target.Type.ServiceWorker;
+
+ const target =
+ this._targetManager.createTarget(targetInfo.targetId, targetName, type, this._parentTarget, sessionId);
+ this._childTargets.set(sessionId, target);
+
+ if (SDK.ChildTargetManager._attachCallback) {
+ SDK.ChildTargetManager._attachCallback({target, waitingForDebugger}).then(() => {
+ target.runtimeAgent().runIfWaitingForDebugger();
+ });
+ } else {
+ target.runtimeAgent().runIfWaitingForDebugger();
+ }
}
/**
@@ -149,8 +143,8 @@ SDK.ChildTargetManager = class extends SDK.SDKModel {
* @param {string=} childTargetId
*/
detachedFromTarget(sessionId, childTargetId) {
- this._childConnections.get(sessionId).onDisconnect.call(null, 'target terminated');
- this._childConnections.delete(sessionId);
+ this._childTargets.get(sessionId).dispose('target terminated');
+ this._childTargets.delete(sessionId);
}
/**
@@ -160,21 +154,7 @@ SDK.ChildTargetManager = class extends SDK.SDKModel {
* @param {string=} childTargetId
*/
receivedMessageFromTarget(sessionId, message, childTargetId) {
- const connection = this._childConnections.get(sessionId);
- if (connection)
- connection.onMessage.call(null, message);
- }
-
- /**
- * @param {!Protocol.TargetAgent} agent
- * @param {string} sessionId
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- * @return {!Protocol.InspectorBackend.Connection}
- */
- _createChildConnection(agent, sessionId, params) {
- const connection = new SDK.ChildConnection(agent, sessionId, params);
- this._childConnections.set(sessionId, connection);
- return connection;
+ // We use flatten protocol.
}
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/Connections.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/Connections.js
index 112423b791f..7bd231e8c56 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/Connections.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/Connections.js
@@ -3,17 +3,14 @@
// found in the LICENSE file.
/**
- * @unrestricted
+ * @implements {Protocol.Connection}
*/
-SDK.MainConnection = class extends Protocol.InspectorBackend.Connection {
- /**
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- */
- constructor(params) {
- super();
- this._onMessage = params.onMessage;
- this._onDisconnect = params.onDisconnect;
- this._disconnected = false;
+SDK.MainConnection = class {
+ constructor() {
+ this._onMessage = null;
+ this._onDisconnect = null;
+ this._messageBuffer = '';
+ this._messageSize = 0;
this._eventListeners = [
InspectorFrontendHost.events.addEventListener(
InspectorFrontendHostAPI.Events.DispatchMessage, this._dispatchMessage, this),
@@ -24,10 +21,26 @@ SDK.MainConnection = class extends Protocol.InspectorBackend.Connection {
/**
* @override
+ * @param {function((!Object|string))} onMessage
+ */
+ setOnMessage(onMessage) {
+ this._onMessage = onMessage;
+ }
+
+ /**
+ * @override
+ * @param {function(string)} onDisconnect
+ */
+ setOnDisconnect(onDisconnect) {
+ this._onDisconnect = onDisconnect;
+ }
+
+ /**
+ * @override
* @param {string} message
*/
sendRawMessage(message) {
- if (!this._disconnected)
+ if (this._onMessage)
InspectorFrontendHost.sendMessageToBackend(message);
}
@@ -35,7 +48,8 @@ SDK.MainConnection = class extends Protocol.InspectorBackend.Connection {
* @param {!Common.Event} event
*/
_dispatchMessage(event) {
- this._onMessage.call(null, /** @type {string} */ (event.data));
+ if (this._onMessage)
+ this._onMessage.call(null, /** @type {string} */ (event.data));
}
/**
@@ -65,12 +79,12 @@ SDK.MainConnection = class extends Protocol.InspectorBackend.Connection {
Common.EventTarget.removeEventListeners(this._eventListeners);
this._onDisconnect = null;
this._onMessage = null;
- this._disconnected = true;
let fulfill;
const promise = new Promise(f => fulfill = f);
InspectorFrontendHost.reattach(() => {
- onDisconnect.call(null, 'force disconnect');
+ if (onDisconnect)
+ onDisconnect.call(null, 'force disconnect');
fulfill();
});
return promise;
@@ -78,28 +92,46 @@ SDK.MainConnection = class extends Protocol.InspectorBackend.Connection {
};
/**
- * @unrestricted
+ * @implements {Protocol.Connection}
*/
-SDK.WebSocketConnection = class extends Protocol.InspectorBackend.Connection {
+SDK.WebSocketConnection = class {
/**
* @param {string} url
* @param {function()} onWebSocketDisconnect
- * @param {!Protocol.InspectorBackend.Connection.Params} params
*/
- constructor(url, onWebSocketDisconnect, params) {
- super();
+ constructor(url, onWebSocketDisconnect) {
this._socket = new WebSocket(url);
this._socket.onerror = this._onError.bind(this);
this._socket.onopen = this._onOpen.bind(this);
- this._socket.onmessage = messageEvent => params.onMessage.call(null, /** @type {string} */ (messageEvent.data));
+ this._socket.onmessage = messageEvent => {
+ if (this._onMessage)
+ this._onMessage.call(null, /** @type {string} */ (messageEvent.data));
+ };
this._socket.onclose = this._onClose.bind(this);
- this._onDisconnect = params.onDisconnect;
+ this._onMessage = null;
+ this._onDisconnect = null;
this._onWebSocketDisconnect = onWebSocketDisconnect;
this._connected = false;
this._messages = [];
}
+ /**
+ * @override
+ * @param {function((!Object|string))} onMessage
+ */
+ setOnMessage(onMessage) {
+ this._onMessage = onMessage;
+ }
+
+ /**
+ * @override
+ * @param {function(string)} onDisconnect
+ */
+ setOnDisconnect(onDisconnect) {
+ this._onDisconnect = onDisconnect;
+ }
+
_onError() {
this._onWebSocketDisconnect.call(null);
// This is called if error occurred while connecting.
@@ -153,7 +185,8 @@ SDK.WebSocketConnection = class extends Protocol.InspectorBackend.Connection {
let fulfill;
const promise = new Promise(f => fulfill = f);
this._close(() => {
- this._onDisconnect.call(null, 'force disconnect');
+ if (this._onDisconnect)
+ this._onDisconnect.call(null, 'force disconnect');
fulfill();
});
return promise;
@@ -161,16 +194,28 @@ SDK.WebSocketConnection = class extends Protocol.InspectorBackend.Connection {
};
/**
- * @unrestricted
+ * @implements {Protocol.Connection}
*/
-SDK.StubConnection = class extends Protocol.InspectorBackend.Connection {
+SDK.StubConnection = class {
+ constructor() {
+ this._onMessage = null;
+ this._onDisconnect = null;
+ }
+
/**
- * @param {!Protocol.InspectorBackend.Connection.Params} params
+ * @override
+ * @param {function((!Object|string))} onMessage
*/
- constructor(params) {
- super();
- this._onMessage = params.onMessage;
- this._onDisconnect = params.onDisconnect;
+ setOnMessage(onMessage) {
+ this._onMessage = onMessage;
+ }
+
+ /**
+ * @override
+ * @param {function(string)} onDisconnect
+ */
+ setOnDisconnect(onDisconnect) {
+ this._onDisconnect = onDisconnect;
}
/**
@@ -188,10 +233,11 @@ SDK.StubConnection = class extends Protocol.InspectorBackend.Connection {
const messageObject = JSON.parse(message);
const error = {
message: 'This is a stub connection, can\'t dispatch message.',
- code: Protocol.InspectorBackend.DevToolsStubErrorCode,
+ code: Protocol.DevToolsStubErrorCode,
data: messageObject
};
- this._onMessage.call(null, {id: messageObject.id, error: error});
+ if (this._onMessage)
+ this._onMessage.call(null, {id: messageObject.id, error: error});
}
/**
@@ -199,59 +245,60 @@ SDK.StubConnection = class extends Protocol.InspectorBackend.Connection {
* @return {!Promise}
*/
disconnect() {
- this._onDisconnect.call(null, 'force disconnect');
+ if (this._onDisconnect)
+ this._onDisconnect.call(null, 'force disconnect');
this._onDisconnect = null;
this._onMessage = null;
return Promise.resolve();
}
};
-SDK.ChildConnection = class extends Protocol.InspectorBackend.Connection {
- /**
- * @param {!Protocol.TargetAgent} agent
- * @param {string} sessionId
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- */
- constructor(agent, sessionId, params) {
- super();
- this._agent = agent;
- this._sessionId = sessionId;
- this.onMessage = params.onMessage;
- this.onDisconnect = params.onDisconnect;
- }
-
- /**
- * @override
- * @param {string} message
- */
- sendRawMessage(message) {
- this._agent.sendMessageToTarget(message, this._sessionId);
- }
-
- /**
- * @override
- * @return {!Promise}
- */
- disconnect() {
- throw 'Not implemented';
- }
+/**
+ * @param {function()} createMainTarget
+ * @param {function()} websocketConnectionLost
+ */
+SDK.initMainConnection = function(createMainTarget, websocketConnectionLost) {
+ SDK._websocketConnectionLost = websocketConnectionLost;
+ SDK._createMainTarget = createMainTarget;
+ Protocol.Connection.setFactory(SDK._createMainConnection);
+ SDK._createMainTarget();
+ InspectorFrontendHost.connectionReady();
};
/**
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- * @param {function()} connectionLostCallback
- * @return {!Protocol.InspectorBackend.Connection}
+ * @return {!Protocol.Connection}
*/
-SDK.createMainConnection = function(params, connectionLostCallback) {
+SDK._createMainConnection = function() {
const wsParam = Runtime.queryParam('ws');
const wssParam = Runtime.queryParam('wss');
-
if (wsParam || wssParam) {
const ws = wsParam ? `ws://${wsParam}` : `wss://${wssParam}`;
- return new SDK.WebSocketConnection(ws, connectionLostCallback, params);
+ SDK._mainConnection = new SDK.WebSocketConnection(ws, SDK._websocketConnectionLost);
+ } else if (InspectorFrontendHost.isHostedMode()) {
+ SDK._mainConnection = new SDK.StubConnection();
+ } else {
+ SDK._mainConnection = new SDK.MainConnection();
}
+ return SDK._mainConnection;
+};
+
+/** @type {!Protocol.Connection} */
+SDK._mainConnection;
- if (InspectorFrontendHost.isHostedMode())
- return new SDK.StubConnection(params);
- return new SDK.MainConnection(params);
+/** @type {function()} */
+SDK._createMainTarget;
+
+/** @type {function()} */
+SDK._websocketConnectionLost;
+
+/**
+ * @param {function((!Object|string))} onMessage
+ * @return {!Promise<!Protocol.Connection>}
+ */
+SDK.interceptMainConnection = async function(onMessage) {
+ await SDK._mainConnection.disconnect();
+ const connection = SDK._createMainConnection();
+ connection.setOnMessage(onMessage);
+ connection.setOnDisconnect(SDK._createMainTarget);
+ return connection;
};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js
index 65be108c064..eebd73a792d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js
@@ -1594,9 +1594,11 @@ SDK.DOMModel = class extends SDK.SDKModel {
* @param {boolean} includeUserAgentShadowDOM
* @return {!Promise<?SDK.DOMNode>}
*/
- nodeForLocation(x, y, includeUserAgentShadowDOM) {
- return this._agent.getNodeForLocation(x, y, includeUserAgentShadowDOM)
- .then(nodeId => nodeId ? this.nodeForId(nodeId) : null);
+ async nodeForLocation(x, y, includeUserAgentShadowDOM) {
+ const response = await this._agent.invoke_getNodeForLocation({x, y, includeUserAgentShadowDOM});
+ if (response[Protocol.Error] || !response.nodeId)
+ return null;
+ return this.nodeForId(response.nodeId);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js
index ac6ec6fe0f9..d77ced84d19 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js
@@ -136,6 +136,14 @@ SDK.DebuggerModel = class extends SDK.SDKModel {
return;
SDK.DebuggerModel._debuggerIdToModel.set(debuggerId, this);
this._debuggerId = debuggerId;
+ this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerIsReadyToPause, this);
+ }
+
+ /**
+ * @return {boolean}
+ */
+ isReadyToPause() {
+ return !!this._debuggerId;
}
/**
@@ -220,6 +228,9 @@ SDK.DebuggerModel = class extends SDK.SDKModel {
}
scheduleStepIntoAsync() {
+ // Node v8.x does not support breakOnAsyncCall flag but supports old style schdeuleStepIntoAsync.
+ // End-of-life of Node 8.x is around December 2019.
+ this._agent.scheduleStepIntoAsync();
this._agent.invoke_stepInto({breakOnAsyncCall: true});
}
@@ -252,7 +263,7 @@ SDK.DebuggerModel = class extends SDK.SDKModel {
async setBreakpointByURL(url, lineNumber, columnNumber, condition) {
// Convert file url to node-js path.
let urlRegex;
- if (this.target().isNodeJS()) {
+ if (this.target().type() === SDK.Target.Type.Node) {
const platformPath = Common.ParsedURL.urlToPlatformPath(url, Host.isWin());
urlRegex = `${platformPath.escapeForRegExp()}|${url.escapeForRegExp()}`;
}
@@ -929,7 +940,8 @@ SDK.DebuggerModel.Events = {
DiscardedAnonymousScriptSource: Symbol('DiscardedAnonymousScriptSource'),
GlobalObjectCleared: Symbol('GlobalObjectCleared'),
CallFrameSelected: Symbol('CallFrameSelected'),
- ConsoleCommandEvaluatedInSelectedCallFrame: Symbol('ConsoleCommandEvaluatedInSelectedCallFrame')
+ ConsoleCommandEvaluatedInSelectedCallFrame: Symbol('ConsoleCommandEvaluatedInSelectedCallFrame'),
+ DebuggerIsReadyToPause: Symbol('DebuggerIsReadyToPause'),
};
/** @enum {string} */
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js
index e39b3fe5eb7..6bc75d286b2 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js
@@ -169,7 +169,8 @@ SDK.HARLog.Entry = class {
// IPv6 address should not have square brackets per (https://tools.ietf.org/html/rfc2373#section-2.2).
serverIPAddress: ipAddress.replace(/\[\]/g, ''),
_initiator: exportedInitiator,
- _priority: harEntry._request.priority()
+ _priority: harEntry._request.priority(),
+ _resourceType: harEntry._request.resourceType().name()
};
// Chrome specific.
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js
index 7de66309643..60c222e8e70 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js
@@ -45,10 +45,16 @@ SDK.HeapProfilerModel = class extends SDK.SDKModel {
* @return {!Promise<?Protocol.HeapProfiler.SamplingHeapProfile>}
*/
stopSampling() {
- this._isRecording = false;
return this._heapProfilerAgent.stopSampling();
}
+ /**
+ * @return {!Promise<?Protocol.HeapProfiler.SamplingHeapProfile>}
+ */
+ getSamplingProfile() {
+ return this._heapProfilerAgent.getSamplingProfile();
+ }
+
startNativeSampling() {
const defaultSamplingIntervalInBytes = 65536;
this._memoryAgent.startSampling(defaultSamplingIntervalInBytes);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js
index a9b236a71cf..6790512da8e 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js
@@ -886,7 +886,7 @@ SDK.NetworkDispatcher = class {
};
/**
- * @implements {SDK.TargetManager.Observer}
+ * @implements {SDK.SDKModelObserver<!SDK.NetworkManager>}
* @unrestricted
*/
SDK.MultitargetNetworkManager = class extends Common.Object {
@@ -911,7 +911,7 @@ SDK.MultitargetNetworkManager = class extends Common.Object {
/** @type {!Multimap<!SDK.MultitargetNetworkManager.RequestInterceptor, !SDK.MultitargetNetworkManager.InterceptionPattern>} */
this._urlsForRequestInterceptor = new Multimap();
- SDK.targetManager.observeTargets(this, SDK.Target.Capability.Network);
+ SDK.targetManager.observeModels(SDK.NetworkManager, this);
}
/**
@@ -929,10 +929,10 @@ SDK.MultitargetNetworkManager = class extends Common.Object {
/**
* @override
- * @param {!SDK.Target} target
+ * @param {!SDK.NetworkManager} networkManager
*/
- targetAdded(target) {
- const networkAgent = target.networkAgent();
+ modelAdded(networkManager) {
+ const networkAgent = networkManager.target().networkAgent();
if (this._extraHeaders)
networkAgent.setExtraHTTPHeaders(this._extraHeaders);
if (this._currentUserAgent())
@@ -948,16 +948,16 @@ SDK.MultitargetNetworkManager = class extends Common.Object {
/**
* @override
- * @param {!SDK.Target} target
+ * @param {!SDK.NetworkManager} networkManager
*/
- targetRemoved(target) {
+ modelRemoved(networkManager) {
for (const entry of this._inflightMainResourceRequests) {
const manager = SDK.NetworkManager.forRequest(/** @type {!SDK.NetworkRequest} */ (entry[1]));
- if (manager.target() !== target)
+ if (manager !== networkManager)
continue;
this._inflightMainResourceRequests.delete(/** @type {string} */ (entry[0]));
}
- this._agents.delete(target.networkAgent());
+ this._agents.delete(networkManager.target().networkAgent());
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js
index a00645cc6ad..b5e422346a1 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js
@@ -1151,12 +1151,13 @@ SDK.NetworkRequest = class extends Common.Object {
async populateImageSource(image) {
const {content, encoded} = await this.contentData();
let imageSrc = Common.ContentProvider.contentAsDataURL(content, this._mimeType, encoded);
- if (imageSrc === null) {
+ if (imageSrc === null && !this._failed) {
const cacheControl = this.responseHeaderValue('cache-control') || '';
if (!cacheControl.includes('no-cache'))
imageSrc = this._url;
}
- image.src = imageSrc;
+ if (imageSrc !== null)
+ image.src = imageSrc;
}
/**
@@ -1244,6 +1245,24 @@ SDK.NetworkRequest = class extends Common.Object {
this._backendRequestId = requestId;
this._requestId = requestId;
}
+
+ /**
+ * @return {?string}
+ */
+ charset() {
+ const contentTypeHeader = this.responseHeaderValue('content-type');
+ if (!contentTypeHeader)
+ return null;
+
+ const responseCharsets = contentTypeHeader.replace(/ /g, '')
+ .split(';')
+ .filter(parameter => parameter.toLowerCase().startsWith('charset='))
+ .map(parameter => parameter.slice('charset='.length));
+ if (responseCharsets.length)
+ return responseCharsets[0];
+
+ return null;
+ }
};
/** @enum {symbol} */
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js
index e2ca71a5876..ad2bd2d2014 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js
@@ -58,6 +58,13 @@ SDK.OverlayModel = class extends SDK.SDKModel {
() => this._overlayAgent.setShowScrollBottleneckRects(this._showScrollBottleneckRectsSetting.get()));
if (this._showScrollBottleneckRectsSetting.get())
this._overlayAgent.setShowScrollBottleneckRects(true);
+
+ this._showHitTestBordersSetting = Common.moduleSetting('showHitTestBorders');
+ this._showHitTestBordersSetting.addChangeListener(
+ () => this._overlayAgent.setShowHitTestBorders(this._showHitTestBordersSetting.get()));
+ if (this._showHitTestBordersSetting.get())
+ this._overlayAgent.setShowHitTestBorders(true);
+
if (target.suspended())
this._overlayAgent.setSuspended(true);
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js
index a8da06aef2c..3262081af36 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js
@@ -695,10 +695,12 @@ SDK.ExecutionContext = class {
*/
function targetWeight(target) {
if (!target.parentTarget())
+ return 5;
+ if (target.type() === SDK.Target.Type.Frame)
return 4;
- if (target.hasBrowserCapability())
+ if (target.type() === SDK.Target.Type.ServiceWorker)
return 3;
- if (target.hasJSCapability())
+ if (target.type() === SDK.Target.Type.Worker)
return 2;
return 1;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js
index bbe4f76f2cb..4a6e9084e55 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js
@@ -580,7 +580,7 @@ SDK.ServiceWorkerContextNamer = class {
const parent = target.parentTarget();
if (!parent || parent.parentTarget() !== this._target)
return null;
- return parent.id();
+ return parent.type() === SDK.Target.Type.ServiceWorker ? parent.id() : null;
}
_updateAllContextLabels() {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/Target.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/Target.js
index 9ed9f30a07a..96473067591 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/Target.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/Target.js
@@ -12,18 +12,46 @@ SDK.Target = class extends Protocol.TargetBase {
* @param {!SDK.TargetManager} targetManager
* @param {string} id
* @param {string} name
- * @param {number} capabilitiesMask
- * @param {!Protocol.InspectorBackend.Connection.Factory} connectionFactory
+ * @param {!SDK.Target.Type} type
* @param {?SDK.Target} parentTarget
+ * @param {string} sessionId
* @param {boolean} suspended
- * @param {boolean} isNodeJS
*/
- constructor(targetManager, id, name, capabilitiesMask, connectionFactory, parentTarget, suspended, isNodeJS) {
- super(connectionFactory, isNodeJS);
+ constructor(targetManager, id, name, type, parentTarget, sessionId, suspended) {
+ const needsNodeJSPatching = type === SDK.Target.Type.Node;
+ super(needsNodeJSPatching, parentTarget, sessionId);
this._targetManager = targetManager;
this._name = name;
this._inspectedURL = '';
- this._capabilitiesMask = capabilitiesMask;
+ this._capabilitiesMask = 0;
+ switch (type) {
+ case SDK.Target.Type.Frame:
+ this._capabilitiesMask = SDK.Target.Capability.Browser | SDK.Target.Capability.DOM | SDK.Target.Capability.JS |
+ SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target |
+ SDK.Target.Capability.Tracing | SDK.Target.Capability.Emulation | SDK.Target.Capability.Input;
+ if (!parentTarget) {
+ this._capabilitiesMask |= SDK.Target.Capability.DeviceEmulation | SDK.Target.Capability.ScreenCapture |
+ SDK.Target.Capability.Security | SDK.Target.Capability.Inspector;
+ }
+ break;
+ case SDK.Target.Type.ServiceWorker:
+ this._capabilitiesMask =
+ SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target;
+ if (!parentTarget)
+ this._capabilitiesMask |= SDK.Target.Capability.Browser | SDK.Target.Capability.Inspector;
+ break;
+ case SDK.Target.Type.Worker:
+ this._capabilitiesMask = SDK.Target.Capability.JS | SDK.Target.Capability.Log | SDK.Target.Capability.Network |
+ SDK.Target.Capability.Target;
+ break;
+ case SDK.Target.Type.Node:
+ this._capabilitiesMask = SDK.Target.Capability.JS;
+ break;
+ case SDK.Target.Type.Browser:
+ this._capabilitiesMask = SDK.Target.Capability.Target;
+ break;
+ }
+ this._type = type;
this._parentTarget = parentTarget;
this._id = id;
this._modelByConstructor = new Map();
@@ -58,6 +86,21 @@ SDK.Target = class extends Protocol.TargetBase {
}
/**
+ * @return {!SDK.Target.Type}
+ */
+ type() {
+ return this._type;
+ }
+
+ /**
+ * @override
+ */
+ markAsNodeJSForTest() {
+ super.markAsNodeJSForTest();
+ this._type = SDK.Target.Type.Node;
+ }
+
+ /**
* @return {!SDK.TargetManager}
*/
targetManager() {
@@ -69,6 +112,8 @@ SDK.Target = class extends Protocol.TargetBase {
* @return {boolean}
*/
hasAllCapabilities(capabilitiesMask) {
+ // TODO(dgozman): get rid of this method, once we never observe targets with
+ // capability mask.
return (this._capabilitiesMask & capabilitiesMask) === capabilitiesMask;
}
@@ -77,49 +122,8 @@ SDK.Target = class extends Protocol.TargetBase {
* @return {string}
*/
decorateLabel(label) {
- return !this.hasBrowserCapability() ? '\u2699 ' + label : label;
- }
-
- /**
- * @return {boolean}
- */
- hasBrowserCapability() {
- return this.hasAllCapabilities(SDK.Target.Capability.Browser);
- }
-
- /**
- * @return {boolean}
- */
- hasJSCapability() {
- return this.hasAllCapabilities(SDK.Target.Capability.JS);
- }
-
- /**
- * @return {boolean}
- */
- hasLogCapability() {
- return this.hasAllCapabilities(SDK.Target.Capability.Log);
- }
-
- /**
- * @return {boolean}
- */
- hasNetworkCapability() {
- return this.hasAllCapabilities(SDK.Target.Capability.Network);
- }
-
- /**
- * @return {boolean}
- */
- hasTargetCapability() {
- return this.hasAllCapabilities(SDK.Target.Capability.Target);
- }
-
- /**
- * @return {boolean}
- */
- hasDOMCapability() {
- return this.hasAllCapabilities(SDK.Target.Capability.DOM);
+ return (this._type === SDK.Target.Type.Worker || this._type === SDK.Target.Type.ServiceWorker) ? '\u2699 ' + label :
+ label;
}
/**
@@ -131,8 +135,10 @@ SDK.Target = class extends Protocol.TargetBase {
/**
* @override
+ * @param {string} reason
*/
- dispose() {
+ dispose(reason) {
+ super.dispose(reason);
this._targetManager.removeTarget(this);
for (const model of this._modelByConstructor.valuesArray())
model.dispose();
@@ -241,8 +247,17 @@ SDK.Target.Capability = {
DeviceEmulation: 1 << 12,
None: 0,
+};
- AllForTests: (1 << 13) - 1
+/**
+ * @enum {string}
+ */
+SDK.Target.Type = {
+ Frame: 'frame',
+ ServiceWorker: 'service-worker',
+ Worker: 'worker',
+ Node: 'node',
+ Browser: 'browser',
};
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js
index bf2bad76d02..976eba20150 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js
@@ -11,7 +11,6 @@ SDK.TargetManager = class extends Common.Object {
this._targets = [];
/** @type {!Array.<!SDK.TargetManager.Observer>} */
this._observers = [];
- this._observerCapabiliesMaskSymbol = Symbol('observerCapabilitiesMask');
/** @type {!Multimap<symbol, !{modelClass: !Function, thisObject: (!Object|undefined), listener: function(!Common.Event)}>} */
this._modelListeners = new Multimap();
/** @type {!Multimap<function(new:SDK.SDKModel, !SDK.Target), !SDK.SDKModelObserver>} */
@@ -150,13 +149,12 @@ SDK.TargetManager = class extends Common.Object {
/**
* @param {!SDK.TargetManager.Observer} targetObserver
- * @param {number=} capabilitiesMask
*/
- observeTargets(targetObserver, capabilitiesMask) {
- if (this._observerCapabiliesMaskSymbol in targetObserver)
+ observeTargets(targetObserver) {
+ if (this._observers.indexOf(targetObserver) !== -1)
throw new Error('Observer can only be registered once');
- targetObserver[this._observerCapabiliesMaskSymbol] = capabilitiesMask || 0;
- this.targets(capabilitiesMask).forEach(targetObserver.targetAdded.bind(targetObserver));
+ for (const target of this._targets)
+ targetObserver.targetAdded(target);
this._observers.push(targetObserver);
}
@@ -164,28 +162,25 @@ SDK.TargetManager = class extends Common.Object {
* @param {!SDK.TargetManager.Observer} targetObserver
*/
unobserveTargets(targetObserver) {
- delete targetObserver[this._observerCapabiliesMaskSymbol];
this._observers.remove(targetObserver);
}
/**
* @param {string} id
* @param {string} name
- * @param {number} capabilitiesMask
- * @param {!Protocol.InspectorBackend.Connection.Factory} connectionFactory
+ * @param {!SDK.Target.Type} type
* @param {?SDK.Target} parentTarget
- * @param {boolean} isNodeJS
+ * @param {string=} sessionId
* @return {!SDK.Target}
*/
- createTarget(id, name, capabilitiesMask, connectionFactory, parentTarget, isNodeJS) {
- const target =
- new SDK.Target(this, id, name, capabilitiesMask, connectionFactory, parentTarget, this._isSuspended, isNodeJS);
+ createTarget(id, name, type, parentTarget, sessionId) {
+ const target = new SDK.Target(this, id, name, type, parentTarget, sessionId || '', this._isSuspended);
target.createModels(new Set(this._modelObservers.keysArray()));
this._targets.push(target);
- const copy = this._observersForTarget(target);
- for (let i = 0; i < copy.length; ++i)
- copy[i].targetAdded(target);
+ const copy = this._observers.slice(0);
+ for (const observer of copy)
+ observer.targetAdded(target);
for (const modelClass of target.models().keys())
this.modelAdded(target, modelClass, target.models().get(modelClass));
@@ -203,15 +198,6 @@ SDK.TargetManager = class extends Common.Object {
/**
* @param {!SDK.Target} target
- * @return {!Array<!SDK.TargetManager.Observer>}
- */
- _observersForTarget(target) {
- return this._observers.filter(
- observer => target.hasAllCapabilities(observer[this._observerCapabiliesMaskSymbol] || 0));
- }
-
- /**
- * @param {!SDK.Target} target
*/
removeTarget(target) {
if (!this._targets.includes(target))
@@ -221,9 +207,9 @@ SDK.TargetManager = class extends Common.Object {
for (const modelClass of target.models().keys())
this._modelRemoved(target, modelClass, target.models().get(modelClass));
- const copy = this._observersForTarget(target);
- for (let i = 0; i < copy.length; ++i)
- copy[i].targetRemoved(target);
+ const copy = this._observers.slice(0);
+ for (const observer of copy)
+ observer.targetRemoved(target);
for (const key of this._modelListeners.keysArray()) {
for (const info of this._modelListeners.get(key)) {
@@ -235,14 +221,10 @@ SDK.TargetManager = class extends Common.Object {
}
/**
- * @param {number=} capabilitiesMask
* @return {!Array.<!SDK.Target>}
*/
- targets(capabilitiesMask) {
- if (!capabilitiesMask)
- return this._targets.slice();
- else
- return this._targets.filter(target => target.hasAllCapabilities(capabilitiesMask || 0));
+ targets() {
+ return this._targets.slice();
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk/module.json b/chromium/third_party/blink/renderer/devtools/front_end/sdk/module.json
index 89048fb52ac..2ece8d277b6 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk/module.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk/module.json
@@ -189,6 +189,24 @@
{
"type": "setting",
"category": "Rendering",
+ "settingName": "showHitTestBorders",
+ "settingType": "boolean",
+ "storageType": "session",
+ "options": [
+ {
+ "value": true,
+ "title": "Show hit-test borders"
+ },
+ {
+ "value": false,
+ "title": "Hide hit-test borders"
+ }
+ ],
+ "defaultValue": false
+ },
+ {
+ "type": "setting",
+ "category": "Rendering",
"settingName": "emulatedCSSMedia",
"settingType": "enum",
"storageType": "session",
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js
index d062f78d520..bc5263a36b2 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js
@@ -13,23 +13,12 @@ function nextId(prefix) {
return (prefix || '') + ++id;
}
-SDKTestRunner.connectToPage = function(targetName, pageMock, makeMainTarget) {
- const mockTarget = SDK.targetManager.createTarget(
- nextId('mock-target-'), targetName, pageMock.capabilities(), params => pageMock.createConnection(params));
-
- if (makeMainTarget) {
- SDK.targetManager._targets = SDK.targetManager._targets.filter(target => target !== mockTarget);
- SDK.targetManager._targets.unshift(mockTarget);
- }
-
- return mockTarget;
-};
-
SDKTestRunner.PageMock = class {
constructor(url) {
this._url = url;
- this._capabilities = SDK.Target.Capability.DOM | SDK.Target.Capability.JS | SDK.Target.Capability.Browser;
+ this._type = SDK.Target.Type.Frame;
this._enabledDomains = new Set();
+ this._children = new Map();
this._mainFrame =
{id: nextId(), loaderId: nextId(), mimeType: 'text/html', securityOrigin: this._url, url: this._url};
@@ -49,18 +38,50 @@ SDKTestRunner.PageMock = class {
};
}
- capabilities() {
- return this._capabilities;
+ turnIntoWorker() {
+ this._type = SDK.Target.Type.Worker;
}
- disableDOMCapability() {
- this._capabilities = this._capabilities & ~SDK.Target.Capability.DOM;
+ connectAsMainTarget(targetName) {
+ Bindings.debuggerWorkspaceBinding._resetForTest(TestRunner.mainTarget);
+ Bindings.resourceMapping._resetForTest(TestRunner.mainTarget);
+ this._enabledDomains.clear();
+ SDK.targetManager._targets = [];
+
+ const oldFactory = Protocol.Connection._factory;
+ Protocol.Connection._factory = () => {
+ this._connection = new MockPageConnection(this);
+ return this._connection;
+ };
+ const target = SDK.targetManager.createTarget(nextId('mock-target-'), targetName, this._type, null);
+ Protocol.Connection._factory = oldFactory;
+
+ this._target = target;
+ return target;
}
- createConnection(params) {
+ connectAsChildTarget(targetName, parentMock) {
this._enabledDomains.clear();
- this._connection = new MockPageConnection(this, params);
- return this._connection;
+ this._sessionId = nextId('mock-target-');
+ this._root = parentMock._root || parentMock;
+ this._root._children.set(this._sessionId, this);
+ const target =
+ SDK.targetManager.createTarget(this._sessionId, targetName, this._type, parentMock._target, this._sessionId);
+ this._target = target;
+ return target;
+ }
+
+ disconnect() {
+ if (this._root) {
+ this._root._children.delete(this._sessionId);
+ this._target.dispose();
+ this._root = null;
+ this._sessionId = null;
+ } else {
+ this._connection.disconnect();
+ this._connection = null;
+ }
+ this._target = null;
}
evalScript(url, content, isContentScript) {
@@ -71,6 +92,7 @@ SDKTestRunner.PageMock = class {
if (!context) {
context = this._createExecutionContext(this._mainFrame, isContentScript);
+ this._executionContexts.push(context);
this._fireEvent('Runtime.executionContextCreated', {context: context});
}
@@ -98,6 +120,14 @@ SDKTestRunner.PageMock = class {
this._fireEvent('Debugger.scriptParsed', script);
}
+ removeContentScripts() {
+ const index = this._executionContexts.findIndex(context => !context.auxData.isDefault);
+ if (index !== -1) {
+ this._fireEvent('Runtime.executionContextDestroyed', {executionContextId: this._executionContexts[index].id});
+ this._executionContexts.splice(index, 1);
+ }
+ }
+
reload() {
this._fireEvent('Page.frameStartedLoading', {frameId: this._mainFrame.id});
@@ -124,13 +154,6 @@ SDKTestRunner.PageMock = class {
this._fireEvent('Page.domContentEventFired', {timestamp: Date.now() / 1000});
}
- close() {
- if (this._connection) {
- this._connection.disconnect();
- this._connection = null;
- }
- }
-
_createExecutionContext(frame, isContentScript) {
return {
id: nextId(),
@@ -138,7 +161,7 @@ SDKTestRunner.PageMock = class {
auxData: {isDefault: !isContentScript, frameId: frame.id},
origin: frame.securityOrigin,
- name: ''
+ name: isContentScript ? 'content-script-context' : ''
};
}
@@ -185,26 +208,36 @@ SDKTestRunner.PageMock = class {
const domain = methodName.split('.')[0];
if (domain === 'Page')
- return !!(this._capabilities & SDK.Target.Capability.DOM);
+ return this._type === SDK.Target.Type.Frame;
return true;
}
- _dispatch(id, methodName, params) {
+ _dispatch(sessionId, id, methodName, params) {
+ if (sessionId) {
+ const child = this._children.get(sessionId);
+ if (child)
+ child._dispatch('', id, methodName, params);
+ return;
+ }
+
const handler = (this._isSupportedDomain(methodName) ? this._dispatchMap[methodName] : null);
if (handler)
return handler.call(this, id, params);
this._sendResponse(
- id, undefined,
- {message: 'Can\'t handle command ' + methodName, code: Protocol.InspectorBackend.DevToolsStubErrorCode});
+ id, undefined, {message: 'Can\'t handle command ' + methodName, code: Protocol.DevToolsStubErrorCode});
}
_sendResponse(id, result, error) {
const message = {id: id, result: result, error: error};
-
- this._connection.sendMessageToDevTools(message);
+ if (this._root) {
+ message.sessionId = this._sessionId;
+ this._root._connection.sendMessageToDevTools(message);
+ } else {
+ this._connection.sendMessageToDevTools(message);
+ }
}
_fireEvent(methodName, params) {
@@ -214,24 +247,35 @@ SDKTestRunner.PageMock = class {
return;
const message = {method: methodName, params: params};
-
- this._connection.sendMessageToDevTools(message);
+ if (this._root) {
+ message.sessionId = this._sessionId;
+ this._root._connection.sendMessageToDevTools(message);
+ } else {
+ this._connection.sendMessageToDevTools(message);
+ }
}
};
MockPageConnection = class {
- constructor(page, params) {
+ constructor(page) {
this._page = page;
- this._onMessage = params.onMessage;
- this._onDisconnect = params.onDisconnect;
+ }
+
+ setOnMessage(onMessage) {
+ this._onMessage = onMessage;
+ }
+
+ setOnDisconnect(onDisconnect) {
+ this._onDisconnect = onDisconnect;
}
sendMessageToDevTools(message) {
setTimeout(() => this._onMessage.call(null, JSON.stringify(message)), 0);
}
- sendMessage(domain, message) {
- this._page._dispatch(message.id, message.method, message.params);
+ sendRawMessage(messageString) {
+ const message = JSON.parse(messageString);
+ this._page._dispatch(message.sessionId, message.id, message.method, message.params || {});
}
disconnect() {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/search/searchResultsPane.css b/chromium/third_party/blink/renderer/devtools/front_end/search/searchResultsPane.css
index 5e2a66234b9..829dc110610 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/search/searchResultsPane.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/search/searchResultsPane.css
@@ -110,6 +110,7 @@ ol.children.expanded {
.search-match-link {
overflow: hidden;
text-overflow: ellipsis;
+ margin-left: 9px;
}
.search-result-qualifier {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js b/chromium/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js
index 44f890f37f7..833df59f21d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js
@@ -15,6 +15,7 @@ Security.SecurityPanel = class extends UI.PanelWithSidebar {
title.textContent = Common.UIString('Overview');
this._sidebarMainViewElement = new Security.SecurityPanelSidebarTreeElement(
title, this._setVisibleView.bind(this, this._mainView), 'security-main-view-sidebar-tree-item', 'lock-icon');
+ this._sidebarMainViewElement.tooltip = title.textContent;
this._sidebarTree = new Security.SecurityPanelSidebarTree(this._sidebarMainViewElement, this.showOrigin.bind(this));
this.panelSidebarElement().appendChild(this._sidebarTree.element);
@@ -445,6 +446,7 @@ Security.SecurityPanelSidebarTree = class extends UI.TreeOutlineInShadow {
const originElement = new Security.SecurityPanelSidebarTreeElement(
Security.SecurityPanel.createHighlightedUrl(origin, securityState), this._showOriginInPanel.bind(this, origin),
'security-sidebar-tree-item', 'security-property');
+ originElement.tooltip = origin;
this._elementsByOrigin.set(origin, originElement);
this.updateOrigin(origin, securityState);
}
@@ -649,6 +651,12 @@ Security.SecurityMainView = class extends UI.VBox {
text.appendChild(Security.SecurityPanel.createCertificateViewerButtonForCert(
Common.UIString('View certificate'), explanation.certificate));
}
+
+ if (explanation.recommendations && explanation.recommendations.length) {
+ const recommendationList = text.createChild('ul', 'security-explanation-recommendations');
+ for (const recommendation of explanation.recommendations)
+ recommendationList.createChild('li').textContent = recommendation;
+ }
return text;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/security/mainView.css b/chromium/third_party/blink/renderer/devtools/front_end/security/mainView.css
index 03a8f32c049..4979fb3c38d 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/security/mainView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/security/mainView.css
@@ -87,7 +87,6 @@
background: #fff;
border-color: rgb(217, 217, 217);
- color: rgba(0, 0, 0, 36);
}
.security-summary-secure .triangle-pointer,
@@ -96,11 +95,6 @@
color: #0b8043;
}
-.security-summary-neutral .triangle-pointer,
-.security-summary-neutral .security-summary-text {
- color: rgb(253, 177, 48);
-}
-
.security-summary-insecure .triangle-pointer,
.security-summary-insecure .security-summary-text,
.security-explanation-title-neutral,
@@ -132,7 +126,7 @@
display: flex;
white-space: nowrap;
border: none;
- color: #8c8c8c;
+ color: rgb(90, 90, 90);
}
.security-explanation-text {
@@ -153,7 +147,7 @@
}
.security-explanation-title {
- color: rgb(90, 90, 90);
+ color: rgb(48, 57, 66);
margin-top: 1px;
margin-bottom: 8px;
}
@@ -173,3 +167,11 @@
.security-mixed-content {
margin-top: 8px;
}
+
+.security-explanation-recommendations {
+ padding-inline-start: 16px;
+}
+
+.security-explanation-recommendations > li {
+ margin-bottom: 4px;
+}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/source_frame/xmlTree.css b/chromium/third_party/blink/renderer/devtools/front_end/source_frame/xmlTree.css
index cd810c2e063..e65786761b7 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/source_frame/xmlTree.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/source_frame/xmlTree.css
@@ -8,11 +8,11 @@
list-style: none;
padding: 0;
margin: 0;
- -webkit-padding-start: 16px;
+ padding-inline-start: 16px;
}
ol.tree-outline {
- -webkit-padding-start: 0;
+ padding-inline-start: 0;
}
.tree-outline li {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js b/chromium/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js
new file mode 100644
index 00000000000..7e34fd60680
--- /dev/null
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2018 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+Sources.BreakpointEditDialog = class extends UI.Widget {
+ /**
+ * @param {number} editorLineNumber
+ * @param {string} oldCondition
+ * @param {function({committed: boolean, condition: string})} onFinish
+ */
+ constructor(editorLineNumber, oldCondition, onFinish) {
+ super(true);
+ this.registerRequiredCSS('sources/breakpointEditDialog.css');
+ this._onFinish = onFinish;
+ this._finished = false;
+ /** @type {?UI.TextEditor} */
+ this._editor = null;
+
+ const labelElement = this.contentElement.createChild('label', 'source-frame-breakpoint-message');
+ labelElement.htmlFor = 'source-frame-breakpoint-condition';
+ labelElement.createTextChild(
+ Common.UIString('The breakpoint on line %d will stop only if this expression is true:', editorLineNumber + 1));
+
+ self.runtime.extension(UI.TextEditorFactory).instance().then(factory => {
+ this._editor =
+ factory.createEditor({lineNumbers: false, lineWrapping: true, mimeType: 'javascript', autoHeight: true});
+ this._editor.configureAutocomplete(ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor));
+ if (oldCondition)
+ this._editor.setText(oldCondition);
+ this._editor.widget().show(this.contentElement);
+ this._editor.widget().element.id = 'source-frame-breakpoint-condition';
+ this._editor.setSelection(this._editor.fullRange());
+ this._editor.widget().focus();
+ this._editor.widget().element.addEventListener('keydown', this._onKeyDown.bind(this), true);
+ this._editor.widget().element.addEventListener('blur', event => {
+ if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this._editor.widget().element))
+ this._finishEditing(true);
+ }, true);
+ });
+ }
+
+ /**
+ * @param {boolean} committed
+ */
+ _finishEditing(committed) {
+ if (this._finished)
+ return;
+ this._finished = true;
+ this._editor.widget().detach();
+ const condition = this._editor.text();
+ this._onFinish({committed, condition});
+ }
+
+ /**
+ * @param {!Event} event
+ */
+ async _onKeyDown(event) {
+ if (isEnterKey(event) && !event.shiftKey) {
+ event.consume(true);
+ const expression = this._editor.text();
+ if (event.ctrlKey || await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(expression))
+ this._finishEditing(true);
+ else
+ this._editor.newlineAndIndent();
+ }
+ if (isEscKey(event))
+ this._finishEditing(false);
+ }
+};
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js b/chromium/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js
index 341ce045ea3..11e54def1a8 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js
@@ -634,63 +634,22 @@ Sources.DebuggerPlugin = class extends Sources.UISourceCodeFrame.Plugin {
* @param {?{lineNumber: number, columnNumber: number}} location
*/
async _editBreakpointCondition(editorLineNumber, breakpoint, location) {
- const conditionElement = createElementWithClass('div', 'source-frame-breakpoint-condition');
-
- const labelElement = conditionElement.createChild('label', 'source-frame-breakpoint-message');
- labelElement.htmlFor = 'source-frame-breakpoint-condition';
- labelElement.createTextChild(
- Common.UIString('The breakpoint on line %d will stop only if this expression is true:', editorLineNumber + 1));
-
-
- this._textEditor.addDecoration(conditionElement, editorLineNumber);
-
- /** @type {!UI.TextEditorFactory} */
- const factory = await self.runtime.extension(UI.TextEditorFactory).instance();
- const editor =
- factory.createEditor({lineNumbers: false, lineWrapping: true, mimeType: 'javascript', autoHeight: true});
- editor.widget().show(conditionElement);
- if (breakpoint)
- editor.setText(breakpoint.condition());
- editor.setSelection(editor.fullRange());
- editor.configureAutocomplete(ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(editor));
- editor.widget().element.addEventListener('keydown', async event => {
- if (isEnterKey(event) && !event.shiftKey) {
- event.consume(true);
- const expression = editor.text();
- if (event.ctrlKey || await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(expression))
- finishEditing.call(this, true);
- else
- editor.newlineAndIndent();
- }
- if (isEscKey(event))
- finishEditing.call(this, false);
- }, true);
- editor.widget().focus();
- editor.widget().element.id = 'source-frame-breakpoint-condition';
- editor.widget().element.addEventListener('blur', event => {
- if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(editor.widget().element))
- finishEditing.call(this, true);
- }, true);
- let finished = false;
- /**
- * @this {Sources.DebuggerPlugin}
- */
- function finishEditing(committed) {
- if (finished)
+ const oldCondition = breakpoint ? breakpoint.condition() : '';
+ const decorationElement = createElement('div');
+ const dialog = new Sources.BreakpointEditDialog(editorLineNumber, oldCondition, result => {
+ dialog.detach();
+ this._textEditor.removeDecoration(decorationElement, editorLineNumber);
+ if (!result.committed)
return;
- finished = true;
- editor.widget().detach();
- this._textEditor.removeDecoration(/** @type {!Element} */ (conditionElement), editorLineNumber);
- if (!committed)
- return;
-
if (breakpoint)
- breakpoint.setCondition(editor.text().trim());
+ breakpoint.setCondition(result.condition);
else if (location)
- this._setBreakpoint(location.lineNumber, location.columnNumber, editor.text().trim(), true);
+ this._setBreakpoint(location.lineNumber, location.columnNumber, result.condition, true);
else
- this._createNewBreakpoint(editorLineNumber, editor.text().trim(), true);
- }
+ this._createNewBreakpoint(editorLineNumber, result.condition, true);
+ });
+ this._textEditor.addDecoration(decorationElement, editorLineNumber);
+ dialog.show(decorationElement);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js b/chromium/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js
index 668372bba1f..a2016cac9e2 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js
@@ -527,7 +527,8 @@ Sources.NavigatorView = class extends UI.VBox {
if (!targetNode) {
targetNode = new Sources.NavigatorGroupTreeNode(
this, project, 'target:' + target.id(),
- !target.hasBrowserCapability() ? Sources.NavigatorView.Types.Worker : Sources.NavigatorView.Types.Frame,
+ target.type() === SDK.Target.Type.Frame ? Sources.NavigatorView.Types.Frame :
+ Sources.NavigatorView.Types.Worker,
target.name());
this._rootNode.appendChild(targetNode);
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/breakpointEditDialog.css b/chromium/third_party/blink/renderer/devtools/front_end/sources/breakpointEditDialog.css
new file mode 100644
index 00000000000..4555060cf55
--- /dev/null
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/breakpointEditDialog.css
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2018 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+:host {
+ z-index: 30;
+ padding: 4px;
+ background-color: #e6e6e6;
+ border-radius: 7px;
+ border: 2px solid #bababa;
+ width: 90%;
+ pointer-events: auto;
+}
+
+.source-frame-breakpoint-message {
+ background-color: transparent;
+ font-weight: normal;
+ text-align: left;
+ text-shadow: none;
+ color: rgb(85, 85, 85);
+ cursor: default;
+ margin: 0 0 2px 0;
+}
+
+#source-frame-breakpoint-condition {
+ margin: 0;
+ border: 1px inset rgb(190, 190, 190) !important;
+ width: 100%;
+ box-shadow: none !important;
+ outline: none !important;
+ background: white;
+}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/javaScriptBreakpointsSidebarPane.css b/chromium/third_party/blink/renderer/devtools/front_end/sources/javaScriptBreakpointsSidebarPane.css
index 301b8be4449..8a2f7817492 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sources/javaScriptBreakpointsSidebarPane.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/javaScriptBreakpointsSidebarPane.css
@@ -25,6 +25,7 @@
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
+ margin-left: 22px;
}
.breakpoints-list-deactivated {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/module.json b/chromium/third_party/blink/renderer/devtools/front_end/sources/module.json
index 451a843622c..472a8670feb 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sources/module.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/module.json
@@ -27,7 +27,7 @@
"toggledIconClass": "largeicon-resume",
"className": "Sources.SourcesPanel.RevealingActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel",
+ "Sources.SourcesView",
"UI.ShortcutRegistry.ForwardedShortcut"
],
"options": [
@@ -137,7 +137,7 @@
"title": "Run snippet",
"iconClass": "largeicon-play",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -158,7 +158,7 @@
"toggledIconClass": "largeicon-activate-breakpoints",
"className": "Sources.SourcesPanel.DebuggingActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"options": [
{
@@ -560,7 +560,7 @@
"actionId": "sources.jump-to-previous-location",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -573,7 +573,7 @@
"actionId": "sources.jump-to-next-location",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -586,7 +586,7 @@
"actionId": "sources.close-editor-tab",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -599,7 +599,7 @@
"actionId": "sources.go-to-line",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -612,7 +612,7 @@
"actionId": "sources.go-to-member",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -658,7 +658,7 @@
"actionId": "sources.save",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -676,7 +676,7 @@
"actionId": "sources.save-all",
"className": "Sources.SourcesView.ActionDelegate",
"contextTypes": [
- "Sources.SourcesPanel"
+ "Sources.SourcesView"
],
"bindings": [
{
@@ -834,6 +834,7 @@
],
"scripts": [
"AddSourceMapURLDialog.js",
+ "BreakpointEditDialog.js",
"CallStackSidebarPane.js",
"DebuggerPausedMessage.js",
"SimpleHistoryManager.js",
@@ -867,6 +868,7 @@
"ScriptOriginPlugin.js"
],
"resources": [
+ "breakpointEditDialog.css",
"callStackSidebarPane.css",
"debuggerPausedMessage.css",
"javaScriptBreakpointsSidebarPane.css",
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources/sourcesView.css b/chromium/third_party/blink/renderer/devtools/front_end/sources/sourcesView.css
index 42b8ab26914..8fe79b5786f 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sources/sourcesView.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources/sourcesView.css
@@ -59,35 +59,6 @@
background-color: #444;
}
-.source-frame-breakpoint-condition {
- z-index: 30;
- padding: 4px;
- background-color: #e6e6e6;
- border-radius: 7px;
- border: 2px solid #bababa;
- width: 90%;
- pointer-events: auto;
-}
-
-.source-frame-breakpoint-message {
- background-color: transparent;
- font-weight: normal;
- text-align: left;
- text-shadow: none;
- color: rgb(85, 85, 85);
- cursor: default;
- margin: 0 0 2px 0;
-}
-
-#source-frame-breakpoint-condition {
- margin: 0;
- border: 1px inset rgb(190, 190, 190) !important;
- width: 100%;
- box-shadow: none !important;
- outline: none !important;
- background: white;
-}
-
@-webkit-keyframes source-frame-value-update-highlight-animation {
from {
background-color: inherit;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js
index 8ea7e66bfd3..0c423a99706 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js
@@ -698,17 +698,17 @@ SourcesTestRunner.evaluateOnCurrentCallFrame = function(code) {
return TestRunner.debuggerModel.evaluateOnSelectedCallFrame({expression: code, objectGroup: 'console'});
};
-SourcesTestRunner.waitDebuggerPluginBreakpoints = function(sourceFrame) {
- return waitUpdate().then(checkIfReady);
+SourcesTestRunner.waitDebuggerPluginDecorations = function(sourceFrame) {
+ return TestRunner.addSnifferPromise(Sources.DebuggerPlugin.prototype, '_breakpointDecorationsUpdatedForTest');
+};
- async function waitUpdate() {
- await TestRunner.addSnifferPromise(Sources.DebuggerPlugin.prototype, '_breakpointDecorationsUpdatedForTest');
- }
+SourcesTestRunner.waitDebuggerPluginBreakpoints = function(sourceFrame) {
+ return SourcesTestRunner.waitDebuggerPluginDecorations().then(checkIfReady);
function checkIfReady() {
for (const {breakpoint} of Bindings.breakpointManager.allBreakpointLocations()) {
if (breakpoint._uiLocations.size === 0 && breakpoint.enabled())
- return waitUpdate().then(checkIfReady);
+ return SourcesTestRunner.waitDebuggerPluginDecorations().then(checkIfReady);
}
return Promise.resolve();
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js b/chromium/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js
index 38f6d191791..53d51db56b2 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js
@@ -13,7 +13,7 @@
self.testRunner;
/**
- * Only tests in /LayoutTests/http/tests/devtools/startup/ need to call
+ * Only tests in web_tests/http/tests/devtools/startup/ need to call
* this method because these tests need certain activities to be exercised
* in the inspected page prior to the DevTools session.
* @param {string} path
@@ -504,9 +504,7 @@ TestRunner.check = function(passCondition, failureText) {
* @param {!Function} callback
*/
TestRunner.deprecatedRunAfterPendingDispatches = function(callback) {
- const targets = SDK.targetManager.targets();
- const promises = targets.map(target => new Promise(resolve => target._deprecatedRunAfterPendingDispatches(resolve)));
- Promise.all(promises).then(TestRunner.safeWrap(callback));
+ Protocol.test.deprecatedRunAfterPendingDispatches(callback);
};
/**
@@ -641,11 +639,7 @@ TestRunner.markStep = function(title) {
};
TestRunner.startDumpingProtocolMessages = function() {
- // TODO(chenwilliam): stop abusing Closure interface which is why
- // we need to opt out of type checking here
- const untypedConnection = /** @type {*} */ (Protocol.InspectorBackend.Connection);
- untypedConnection.prototype._dumpProtocolMessage = self.testRunner.logToStderr.bind(self.testRunner);
- Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages = 1;
+ Protocol.test.dumpProtocol = self.testRunner.logToStderr.bind(self.testRunner);
};
/**
@@ -1221,37 +1215,6 @@ TestRunner.dumpLoadedModules = function(relativeTo) {
};
/**
- * @param {!SDK.Target} target
- * @return {boolean}
- */
-TestRunner.isDedicatedWorker = function(target) {
- return target && !target.hasBrowserCapability() && target.hasJSCapability() && target.hasLogCapability();
-};
-
-/**
- * @param {!SDK.Target} target
- * @return {boolean}
- */
-TestRunner.isServiceWorker = function(target) {
- return target && !target.hasBrowserCapability() && !target.hasJSCapability() && target.hasNetworkCapability() &&
- target.hasTargetCapability();
-};
-
-/**
- * @param {!SDK.Target} target
- * @return {string}
- */
-TestRunner.describeTargetType = function(target) {
- if (TestRunner.isDedicatedWorker(target))
- return 'worker';
- if (TestRunner.isServiceWorker(target))
- return 'service-worker';
- if (!target.parentTarget())
- return 'page';
- return 'frame';
-};
-
-/**
* @param {string} urlSuffix
* @param {!Workspace.projectTypes=} projectType
* @return {!Promise}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js b/chromium/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js
index 601007786a1..65317dd75f5 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js
@@ -162,7 +162,6 @@ TextEditor.CodeMirrorTextEditor = class extends UI.VBox {
this._codeMirror.on('changes', this._changes.bind(this));
this._codeMirror.on('beforeSelectionChange', this._beforeSelectionChange.bind(this));
- this._codeMirror.on('keyHandled', this._onKeyHandled.bind(this));
this.element.style.overflow = 'hidden';
this._codeMirrorElement.classList.add('source-code');
@@ -374,10 +373,6 @@ TextEditor.CodeMirrorTextEditor = class extends UI.VBox {
return this;
}
- _onKeyHandled() {
- UI.shortcutRegistry.dismissPendingShortcutAction();
- }
-
/**
* @param {number} lineNumber
* @param {number} lineLength
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js
index 0de9b0ab89d..197a54c4469 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js
@@ -57,6 +57,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
this._headerLevel2 = this._buildGroupStyle({padding: 2, nestingLevel: 1, collapsible: false});
this._staticHeader = this._buildGroupStyle({collapsible: false});
this._framesHeader = this._buildGroupStyle({useFirstLineForOverview: true});
+ this._timingsHeader = this._buildGroupStyle({shareHeaderLine: true, useFirstLineForOverview: true});
this._screenshotsHeader =
this._buildGroupStyle({useFirstLineForOverview: true, nestingLevel: 1, collapsible: false, itemsHeight: 150});
this._interactionsHeaderLevel1 = this._buildGroupStyle({useFirstLineForOverview: true});
@@ -115,8 +116,9 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
return event.name + ':' + event.args['step'];
if (event._blackboxRoot)
return Common.UIString('Blackboxed');
+ if (this._performanceModel.timelineModel().isMarkerEvent(event))
+ return Timeline.TimelineUIUtils.markerShortTitle(event);
const name = Timeline.TimelineUIUtils.eventStyle(event).title;
- // TODO(yurys): support event dividers
const detailsText =
Timeline.TimelineUIUtils.buildDetailsTextForTraceEvent(event, this._model.targetByEvent(event));
if (event.name === TimelineModel.TimelineModel.RecordType.JSFrame && detailsText)
@@ -235,7 +237,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
}
_processInspectorTrace() {
- this._appendFrameBars();
+ this._appendFrames();
this._appendInteractionRecords();
const eventEntryType = Timeline.TimelineFlameChartDataProvider.EntryType.Event;
@@ -246,7 +248,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
return 0;
case TimelineModel.TimelineModel.TrackType.Animation:
return 1;
- case TimelineModel.TimelineModel.TrackType.UserTiming:
+ case TimelineModel.TimelineModel.TrackType.Timings:
return 2;
case TimelineModel.TimelineModel.TrackType.Console:
return 3;
@@ -278,9 +280,12 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
track, ls`Animation`, track.asyncEvents, this._interactionsHeaderLevel2, eventEntryType,
false /* selectable */);
break;
- case TimelineModel.TimelineModel.TrackType.UserTiming:
+ case TimelineModel.TimelineModel.TrackType.Timings:
+ const group = this._appendHeader(ls`Timings`, this._timingsHeader, true /* selectable */);
+ group._track = track;
+ this._appendPageMetrics();
this._appendAsyncEventsGroup(
- track, ls`User Timing`, track.asyncEvents, this._headerLevel1, eventEntryType, true /* selectable */);
+ track, null, track.asyncEvents, this._timingsHeader, eventEntryType, true /* selectable */);
break;
case TimelineModel.TimelineModel.TrackType.Console:
this._appendAsyncEventsGroup(
@@ -401,10 +406,9 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
group = this._appendHeader(title, style, selectable);
group._track = track;
}
- const markerEventsFilter = Timeline.TimelineUIUtils.paintEventsFilter();
for (let i = 0; i < events.length; ++i) {
const e = events[i];
- if (!isExtension && TimelineModel.TimelineModel.isMarkerEvent(e) && markerEventsFilter.accept(e)) {
+ if (!isExtension && this._performanceModel.timelineModel().isMarkerEvent(e)) {
this._markers.push(new Timeline.TimelineFlameChartMarker(
e.startTime, e.startTime - this._model.minimumRecordTime(),
Timeline.TimelineUIUtils.markerStyleForEvent(e)));
@@ -438,7 +442,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
const index = this._appendEvent(e, level);
if (openEvents.length)
this._entryParent[index] = openEvents.peekLast();
- if (!isExtension && TimelineModel.TimelineModel.isMarkerEvent(e))
+ if (!isExtension && this._performanceModel.timelineModel().isMarkerEvent(e))
this._timelineData.entryTotalTimes[this._entryData.length] = undefined;
maxStackDepth = Math.max(maxStackDepth, openEvents.length + 1);
@@ -472,7 +476,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
/**
* @param {?TimelineModel.TimelineModel.Track} track
- * @param {string} header
+ * @param {?string} header
* @param {!Array<!SDK.TracingModel.AsyncEvent>} events
* @param {!PerfUI.FlameChart.GroupStyle} style
* @param {!Timeline.TimelineFlameChartDataProvider.EntryType} entryType
@@ -488,7 +492,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
const asyncEvent = events[i];
if (!this._performanceModel.isVisible(asyncEvent))
continue;
- if (!group) {
+ if (!group && header) {
group = this._appendHeader(header, style, selectable);
if (selectable)
group._track = track;
@@ -522,13 +526,37 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
this._entryTypeByLevel[this._currentLevel++] = Timeline.TimelineFlameChartDataProvider.EntryType.InteractionRecord;
}
- _appendFrameBars() {
+ _appendPageMetrics() {
+ this._entryTypeByLevel[this._currentLevel] = Timeline.TimelineFlameChartDataProvider.EntryType.Event;
+
+ /** @type {!Array<!SDK.TracingModel.Event>} */
+ const metricEvents = [];
+ for (const track of this._model.tracks()) {
+ for (const event of track.events) {
+ if (!this._performanceModel.timelineModel().isMarkerEvent(event))
+ continue;
+ metricEvents.push(event);
+ }
+ }
+
+ metricEvents.stableSort(SDK.TracingModel.Event.compareStartTime);
+ const totalTimes = this._timelineData.entryTotalTimes;
+ for (const event of metricEvents) {
+ this._appendEvent(event, this._currentLevel);
+ totalTimes[totalTimes.length - 1] = Number.NaN;
+ }
+
+ ++this._currentLevel;
+ }
+
+ _appendFrames() {
const screenshots = this._performanceModel.filmStripModel().frames();
const hasFilmStrip = !!screenshots.length;
this._framesHeader.collapsible = hasFilmStrip;
this._appendHeader(Common.UIString('Frames'), this._framesHeader, false /* selectable */);
this._frameGroup = this._timelineData.groups.peekLast();
const style = Timeline.TimelineUIUtils.markerStyleForFrame();
+
this._entryTypeByLevel[this._currentLevel] = Timeline.TimelineFlameChartDataProvider.EntryType.Frame;
for (const frame of this._performanceModel.frames()) {
this._markers.push(new Timeline.TimelineFlameChartMarker(
@@ -536,6 +564,7 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
this._appendFrame(frame);
}
++this._currentLevel;
+
if (!hasFilmStrip)
return;
this._appendHeader('', this._screenshotsHeader, false /* selectable */);
@@ -583,7 +612,10 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
'%s (self %s)', Number.millisToString(totalTime, true), Number.millisToString(selfTime, true)) :
Number.millisToString(totalTime, true);
}
- title = this.entryTitle(entryIndex);
+ if (this._performanceModel.timelineModel().isMarkerEvent(event))
+ title = Timeline.TimelineUIUtils.eventTitle(event);
+ else
+ title = this.entryTitle(entryIndex);
warning = Timeline.TimelineUIUtils.eventWarning(event);
} else if (type === Timeline.TimelineFlameChartDataProvider.EntryType.Frame) {
const frame = /** @type {!TimelineModel.TimelineFrame} */ (this._entryData[entryIndex]);
@@ -632,6 +664,8 @@ Timeline.TimelineFlameChartDataProvider = class extends Common.Object {
const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]);
if (this._model.isGenericTrace())
return this._genericTraceEventColor(event);
+ if (this._performanceModel.timelineModel().isMarkerEvent(event))
+ return Timeline.TimelineUIUtils.markerStyleForEvent(event).color;
if (!SDK.TracingModel.isAsyncPhase(event.phase))
return this._colorForEvent(event);
if (event.hasCategory(TimelineModel.TimelineModel.Category.Console) ||
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js
index 0abf8b041aa..afaea6a44ad 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js
@@ -463,11 +463,13 @@ Timeline.TimelineFlameChartMarker = class {
/**
* @override
- * @return {string}
+ * @return {?string}
*/
title() {
+ if (this._style.lowPriority)
+ return null;
const startTime = Number.millisToString(this._startOffset);
- return Common.UIString('%s at %s', this._style.title, startTime);
+ return ls`${this._style.title} at ${startTime}`;
}
/**
@@ -482,23 +484,14 @@ Timeline.TimelineFlameChartMarker = class {
if (this._style.lowPriority && pixelsPerMillisecond < lowPriorityVisibilityThresholdInPixelsPerMs)
return;
- context.save();
-
- if (!this._style.lowPriority) {
- context.strokeStyle = this._style.color;
- context.lineWidth = 2;
- context.beginPath();
- context.moveTo(x, 0);
- context.lineTo(x, height);
- context.stroke();
- }
+ context.save();
if (this._style.tall) {
context.strokeStyle = this._style.color;
context.lineWidth = this._style.lineWidth;
context.translate(this._style.lineWidth < 1 || (this._style.lineWidth & 1) ? 0.5 : 0, 0.5);
context.beginPath();
- context.moveTo(x, height);
+ context.moveTo(x, 0);
context.setLineDash(this._style.dashStyle);
context.lineTo(x, context.canvas.height);
context.stroke();
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js
index 920d3442256..8318111afaf 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js
@@ -746,12 +746,9 @@ Timeline.TimelinePanel = class extends UI.Panel {
const markers = new Map();
const recordTypes = TimelineModel.TimelineModel.RecordType;
const zeroTime = timelineModel.minimumRecordTime();
- const filter = Timeline.TimelineUIUtils.paintEventsFilter();
for (const event of timelineModel.timeMarkerEvents()) {
if (event.name === recordTypes.TimeStamp || event.name === recordTypes.ConsoleTime)
continue;
- if (!filter.accept(event))
- continue;
markers.set(event.startTime, Timeline.TimelineUIUtils.createEventDivider(event, zeroTime));
}
this._overviewPane.setMarkers(markers);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js
index 9e7c3642c72..5334c9e60ec 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js
@@ -110,19 +110,17 @@ Timeline.TimelineUIUtils = class {
eventStyles[recordTypes.ParseScriptOnBackground] =
new Timeline.TimelineRecordStyle(Common.UIString('Parse Script'), categories['scripting']);
eventStyles[recordTypes.FrameStartedLoading] =
- new Timeline.TimelineRecordStyle(Common.UIString('Frame Started Loading'), categories['loading'], true);
+ new Timeline.TimelineRecordStyle(ls`Frame Started Loading`, categories['loading'], true);
eventStyles[recordTypes.MarkLoad] =
- new Timeline.TimelineRecordStyle(Common.UIString('Load event'), categories['scripting'], true);
+ new Timeline.TimelineRecordStyle(ls`Onload Event`, categories['scripting'], true);
eventStyles[recordTypes.MarkDOMContent] =
- new Timeline.TimelineRecordStyle(Common.UIString('DOMContentLoaded event'), categories['scripting'], true);
+ new Timeline.TimelineRecordStyle(ls`DOMContentLoaded Event`, categories['scripting'], true);
eventStyles[recordTypes.MarkFirstPaint] =
- new Timeline.TimelineRecordStyle(Common.UIString('First paint'), categories['painting'], true);
+ new Timeline.TimelineRecordStyle(ls`First Paint`, categories['painting'], true);
eventStyles[recordTypes.MarkFCP] =
- new Timeline.TimelineRecordStyle(Common.UIString('First contentful paint'), categories['rendering'], true);
+ new Timeline.TimelineRecordStyle(ls`First Contentful Paint`, categories['rendering'], true);
eventStyles[recordTypes.MarkFMP] =
- new Timeline.TimelineRecordStyle(Common.UIString('First meaningful paint'), categories['rendering'], true);
- eventStyles[recordTypes.MarkFMPCandidate] =
- new Timeline.TimelineRecordStyle(Common.UIString('Meaningful paint candidate'), categories['rendering'], true);
+ new Timeline.TimelineRecordStyle(ls`First Meaningful Paint`, categories['rendering'], true);
eventStyles[recordTypes.TimeStamp] =
new Timeline.TimelineRecordStyle(Common.UIString('Timestamp'), categories['scripting']);
eventStyles[recordTypes.ConsoleTime] =
@@ -792,8 +790,9 @@ Timeline.TimelineUIUtils = class {
let relatedNodeLabel;
const contentHelper = new Timeline.TimelineDetailsContentHelper(model.targetByEvent(event), linkifier);
- contentHelper.addSection(
- Timeline.TimelineUIUtils.eventTitle(event), Timeline.TimelineUIUtils.eventStyle(event).category.color);
+ const color = model.isMarkerEvent(event) ? Timeline.TimelineUIUtils.markerStyleForEvent(event).color :
+ Timeline.TimelineUIUtils.eventStyle(event).category.color;
+ contentHelper.addSection(Timeline.TimelineUIUtils.eventTitle(event), color);
const eventData = event.args['data'];
const timelineData = TimelineModel.TimelineData.forEvent(event);
@@ -805,9 +804,9 @@ Timeline.TimelineUIUtils = class {
if (event.name === recordTypes.JSFrame && eventData['deoptReason'])
contentHelper.appendWarningRow(event, TimelineModel.TimelineModel.WarningType.V8Deopt);
- if (detailed) {
- contentHelper.appendTextRow(Common.UIString('Total Time'), Number.millisToString(event.duration || 0, true));
- contentHelper.appendTextRow(Common.UIString('Self Time'), Number.millisToString(event.selfTime, true));
+ if (detailed && !Number.isNaN(event.duration + 0)) {
+ contentHelper.appendTextRow(ls`Total Time`, Number.millisToString(event.duration, true));
+ contentHelper.appendTextRow(ls`Self Time`, Number.millisToString(event.selfTime, true));
}
if (model.isGenericTrace()) {
@@ -826,26 +825,26 @@ Timeline.TimelineUIUtils = class {
case recordTypes.MajorGC:
case recordTypes.MinorGC:
const delta = event.args['usedHeapSizeBefore'] - event.args['usedHeapSizeAfter'];
- contentHelper.appendTextRow(Common.UIString('Collected'), Number.bytesToString(delta));
+ contentHelper.appendTextRow(ls`Collected`, Number.bytesToString(delta));
break;
case recordTypes.JSFrame:
case recordTypes.FunctionCall:
const detailsNode =
Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event, model.targetByEvent(event), linkifier);
if (detailsNode)
- contentHelper.appendElementRow(Common.UIString('Function'), detailsNode);
+ contentHelper.appendElementRow(ls`Function`, detailsNode);
break;
case recordTypes.TimerFire:
case recordTypes.TimerInstall:
case recordTypes.TimerRemove:
- contentHelper.appendTextRow(Common.UIString('Timer ID'), eventData['timerId']);
+ contentHelper.appendTextRow(ls`Timer ID`, eventData['timerId']);
if (event.name === recordTypes.TimerInstall) {
- contentHelper.appendTextRow(Common.UIString('Timeout'), Number.millisToString(eventData['timeout']));
- contentHelper.appendTextRow(Common.UIString('Repeats'), !eventData['singleShot']);
+ contentHelper.appendTextRow(ls`Timeout`, Number.millisToString(eventData['timeout']));
+ contentHelper.appendTextRow(ls`Repeats`, !eventData['singleShot']);
}
break;
case recordTypes.FireAnimationFrame:
- contentHelper.appendTextRow(Common.UIString('Callback ID'), eventData['id']);
+ contentHelper.appendTextRow(ls`Callback ID`, eventData['id']);
break;
case recordTypes.ResourceSendRequest:
case recordTypes.ResourceReceiveResponse:
@@ -853,101 +852,87 @@ Timeline.TimelineUIUtils = class {
case recordTypes.ResourceFinish:
url = timelineData.url;
if (url)
- contentHelper.appendElementRow(Common.UIString('Resource'), Components.Linkifier.linkifyURL(url));
+ contentHelper.appendElementRow(ls`Resource`, Components.Linkifier.linkifyURL(url));
if (eventData['requestMethod'])
- contentHelper.appendTextRow(Common.UIString('Request Method'), eventData['requestMethod']);
+ contentHelper.appendTextRow(ls`Request Method`, eventData['requestMethod']);
if (typeof eventData['statusCode'] === 'number')
- contentHelper.appendTextRow(Common.UIString('Status Code'), eventData['statusCode']);
+ contentHelper.appendTextRow(ls`Status Code`, eventData['statusCode']);
if (eventData['mimeType'])
- contentHelper.appendTextRow(Common.UIString('MIME Type'), eventData['mimeType']);
+ contentHelper.appendTextRow(ls`MIME Type`, eventData['mimeType']);
if ('priority' in eventData) {
const priority = PerfUI.uiLabelForNetworkPriority(eventData['priority']);
- contentHelper.appendTextRow(Common.UIString('Priority'), priority);
- }
- if (eventData['encodedDataLength']) {
- contentHelper.appendTextRow(
- Common.UIString('Encoded Data'), Common.UIString('%d Bytes', eventData['encodedDataLength']));
- }
- if (eventData['decodedBodyLength']) {
- contentHelper.appendTextRow(
- Common.UIString('Decoded Body'), Common.UIString('%d Bytes', eventData['decodedBodyLength']));
+ contentHelper.appendTextRow(ls`Priority`, priority);
}
+ if (eventData['encodedDataLength'])
+ contentHelper.appendTextRow(ls`Encoded Data`, ls`${eventData['encodedDataLength']} Bytes`);
+ if (eventData['decodedBodyLength'])
+ contentHelper.appendTextRow(ls`Decoded Body`, ls`${eventData['decodedBodyLength']} Bytes`);
break;
case recordTypes.CompileModule:
- contentHelper.appendLocationRow(Common.UIString('Module'), event.args['fileName'], 0);
+ contentHelper.appendLocationRow(ls`Module`, event.args['fileName'], 0);
break;
case recordTypes.CompileScript:
url = eventData && eventData['url'];
- if (url) {
- contentHelper.appendLocationRow(
- Common.UIString('Script'), url, eventData['lineNumber'], eventData['columnNumber']);
- }
- contentHelper.appendTextRow(Common.UIString('Streamed'), Common.UIString('%s', eventData['streamed']));
+ if (url)
+ contentHelper.appendLocationRow(ls`Script`, url, eventData['lineNumber'], eventData['columnNumber']);
+ contentHelper.appendTextRow(ls`Streamed`, eventData['streamed']);
const cacheProduceOptions = eventData && eventData['cacheProduceOptions'];
if (cacheProduceOptions) {
- contentHelper.appendTextRow(
- Common.UIString('Cache Produce Options'), Common.UIString('%s', cacheProduceOptions));
- contentHelper.appendTextRow(
- Common.UIString('Produced Cache Size'), Common.UIString('%d', eventData['producedCacheSize']));
+ contentHelper.appendTextRow(ls`Cache Produce Options`, cacheProduceOptions);
+ contentHelper.appendTextRow(ls`Produced Cache Size`, eventData['producedCacheSize']);
}
const cacheConsumeOptions = eventData && eventData['cacheConsumeOptions'];
if (cacheConsumeOptions) {
- contentHelper.appendTextRow(
- Common.UIString('Cache Consume Options'), Common.UIString('%s', cacheConsumeOptions));
- contentHelper.appendTextRow(
- Common.UIString('Consumed Cache Size'), Common.UIString('%d', eventData['consumedCacheSize']));
- contentHelper.appendTextRow(
- Common.UIString('Cache Rejected'), Common.UIString('%s', eventData['cacheRejected']));
+ contentHelper.appendTextRow(ls`Cache Consume Options`, cacheConsumeOptions);
+ contentHelper.appendTextRow(ls`Consumed Cache Size`, eventData['consumedCacheSize']);
+ contentHelper.appendTextRow(ls`Cache Rejected`, eventData['cacheRejected']);
}
break;
case recordTypes.EvaluateScript:
url = eventData && eventData['url'];
- if (url) {
- contentHelper.appendLocationRow(
- Common.UIString('Script'), url, eventData['lineNumber'], eventData['columnNumber']);
- }
+ if (url)
+ contentHelper.appendLocationRow(ls`Script`, url, eventData['lineNumber'], eventData['columnNumber']);
break;
case recordTypes.Paint:
const clip = eventData['clip'];
- contentHelper.appendTextRow(Common.UIString('Location'), Common.UIString('(%d, %d)', clip[0], clip[1]));
+ contentHelper.appendTextRow(ls`Location`, ls`(${clip[0]}, ${clip[1]})`);
const clipWidth = Timeline.TimelineUIUtils.quadWidth(clip);
const clipHeight = Timeline.TimelineUIUtils.quadHeight(clip);
- contentHelper.appendTextRow(Common.UIString('Dimensions'), Common.UIString('%d × %d', clipWidth, clipHeight));
- // Fall-through intended.
+ contentHelper.appendTextRow(ls`Dimensions`, ls`${clipWidth} × ${clipHeight}`);
+ // Fall-through intended.
case recordTypes.PaintSetup:
case recordTypes.Rasterize:
case recordTypes.ScrollLayer:
- relatedNodeLabel = Common.UIString('Layer Root');
+ relatedNodeLabel = ls`Layer Root`;
break;
case recordTypes.PaintImage:
case recordTypes.DecodeLazyPixelRef:
case recordTypes.DecodeImage:
case recordTypes.ResizeImage:
case recordTypes.DrawLazyPixelRef:
- relatedNodeLabel = Common.UIString('Owner Element');
+ relatedNodeLabel = ls`Owner Element`;
url = timelineData.url;
if (url)
- contentHelper.appendElementRow(Common.UIString('Image URL'), Components.Linkifier.linkifyURL(url));
+ contentHelper.appendElementRow(ls`Image URL`, Components.Linkifier.linkifyURL(url));
break;
case recordTypes.ParseAuthorStyleSheet:
url = eventData['styleSheetUrl'];
if (url)
- contentHelper.appendElementRow(Common.UIString('Stylesheet URL'), Components.Linkifier.linkifyURL(url));
+ contentHelper.appendElementRow(ls`Stylesheet URL`, Components.Linkifier.linkifyURL(url));
break;
case recordTypes.UpdateLayoutTree: // We don't want to see default details.
case recordTypes.RecalculateStyles:
- contentHelper.appendTextRow(Common.UIString('Elements Affected'), event.args['elementCount']);
+ contentHelper.appendTextRow(ls`Elements Affected`, event.args['elementCount']);
break;
case recordTypes.Layout:
const beginData = event.args['beginData'];
contentHelper.appendTextRow(
- Common.UIString('Nodes That Need Layout'),
- Common.UIString('%s of %s', beginData['dirtyObjects'], beginData['totalObjects']));
- relatedNodeLabel = Common.UIString('Layout root');
+ ls`Nodes That Need Layout`, ls`${beginData['dirtyObjects']} of ${beginData['totalObjects']}`);
+ relatedNodeLabel = ls`Layout root`;
break;
case recordTypes.ConsoleTime:
- contentHelper.appendTextRow(Common.UIString('Message'), event.name);
+ contentHelper.appendTextRow(ls`Message`, event.name);
break;
case recordTypes.WebSocketCreate:
case recordTypes.WebSocketSendHandshakeRequest:
@@ -955,18 +940,18 @@ Timeline.TimelineUIUtils = class {
case recordTypes.WebSocketDestroy:
const initiatorData = initiator ? initiator.args['data'] : eventData;
if (typeof initiatorData['webSocketURL'] !== 'undefined')
- contentHelper.appendTextRow(Common.UIString('URL'), initiatorData['webSocketURL']);
+ contentHelper.appendTextRow(ls`URL`, initiatorData['webSocketURL']);
if (typeof initiatorData['webSocketProtocol'] !== 'undefined')
- contentHelper.appendTextRow(Common.UIString('WebSocket Protocol'), initiatorData['webSocketProtocol']);
+ contentHelper.appendTextRow(ls`WebSocket Protocol`, initiatorData['webSocketProtocol']);
if (typeof eventData['message'] !== 'undefined')
- contentHelper.appendTextRow(Common.UIString('Message'), eventData['message']);
+ contentHelper.appendTextRow(ls`Message`, eventData['message']);
break;
case recordTypes.EmbedderCallback:
- contentHelper.appendTextRow(Common.UIString('Callback Function'), eventData['callbackName']);
+ contentHelper.appendTextRow(ls`Callback Function`, eventData['callbackName']);
break;
case recordTypes.Animation:
if (event.phase === SDK.TracingModel.Phase.NestableAsyncInstant)
- contentHelper.appendTextRow(Common.UIString('State'), eventData['state']);
+ contentHelper.appendTextRow(ls`State`, eventData['state']);
break;
case recordTypes.ParseHTML: {
const beginData = event.args['beginData'];
@@ -974,29 +959,41 @@ Timeline.TimelineUIUtils = class {
const endLine = event.args['endData'] ? event.args['endData']['endLine'] - 1 : undefined;
url = beginData['url'];
if (url)
- contentHelper.appendLocationRange(Common.UIString('Range'), url, startLine, endLine);
+ contentHelper.appendLocationRange(ls`Range`, url, startLine, endLine);
break;
}
case recordTypes.FireIdleCallback:
- contentHelper.appendTextRow(
- Common.UIString('Allotted Time'), Number.millisToString(eventData['allottedMilliseconds']));
- contentHelper.appendTextRow(Common.UIString('Invoked by Timeout'), eventData['timedOut']);
- // Fall-through intended.
+ contentHelper.appendTextRow(ls`Allotted Time`, Number.millisToString(eventData['allottedMilliseconds']));
+ contentHelper.appendTextRow(ls`Invoked by Timeout`, eventData['timedOut']);
+ // Fall-through intended.
case recordTypes.RequestIdleCallback:
case recordTypes.CancelIdleCallback:
- contentHelper.appendTextRow(Common.UIString('Callback ID'), eventData['id']);
+ contentHelper.appendTextRow(ls`Callback ID`, eventData['id']);
break;
case recordTypes.EventDispatch:
- contentHelper.appendTextRow(Common.UIString('Type'), eventData['type']);
+ contentHelper.appendTextRow(ls`Type`, eventData['type']);
+ break;
+
+ case recordTypes.MarkFCP:
+ case recordTypes.MarkFMP:
+ case recordTypes.MarkLoad:
+ case recordTypes.MarkDOMContent:
+ contentHelper.appendTextRow(
+ ls`Timestamp`, Number.preciseMillisToString(event.startTime - model.minimumRecordTime(), 1));
+ const learnMoreLink = UI.XLink.create(
+ 'https://developers.google.com/web/fundamentals/performance/user-centric-performance-metrics#user-centric_performance_metrics',
+ ls`Learn more`);
+ const linkDiv = UI.html`<div>${learnMoreLink} about page performance metrics.</div>`;
+ contentHelper.appendElementRow(ls`Details`, linkDiv);
break;
default: {
const detailsNode =
Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event, model.targetByEvent(event), linkifier);
if (detailsNode)
- contentHelper.appendElementRow(Common.UIString('Details'), detailsNode);
+ contentHelper.appendElementRow(ls`Details`, detailsNode);
break;
}
}
@@ -1006,18 +1003,17 @@ Timeline.TimelineUIUtils = class {
if (timelineData.timeWaitingForMainThread) {
contentHelper.appendTextRow(
- Common.UIString('Time Waiting for Main Thread'),
- Number.millisToString(timelineData.timeWaitingForMainThread, true));
+ ls`Time Waiting for Main Thread`, Number.millisToString(timelineData.timeWaitingForMainThread, true));
}
const relatedNode = relatedNodesMap && relatedNodesMap.get(timelineData.backendNodeId);
if (relatedNode) {
const nodeSpan = await Common.Linkifier.linkify(relatedNode);
- contentHelper.appendElementRow(relatedNodeLabel || Common.UIString('Related Node'), nodeSpan);
+ contentHelper.appendElementRow(relatedNodeLabel || ls`Related Node`, nodeSpan);
}
if (event[Timeline.TimelineUIUtils._previewElementSymbol]) {
- contentHelper.addSection(Common.UIString('Preview'));
+ contentHelper.addSection(ls`Preview`);
contentHelper.appendElementRow('', event[Timeline.TimelineUIUtils._previewElementSymbol]);
}
@@ -1028,7 +1024,7 @@ Timeline.TimelineUIUtils = class {
const stats = {};
const showPieChart = detailed && Timeline.TimelineUIUtils._aggregatedStatsForTraceEvent(stats, model, event);
if (showPieChart) {
- contentHelper.addSection(Common.UIString('Aggregated Time'));
+ contentHelper.addSection(ls`Aggregated Time`);
const pieChart = Timeline.TimelineUIUtils.generatePieChart(
stats, Timeline.TimelineUIUtils.eventStyle(event).category, event.selfTime);
contentHelper.appendElementRow('', pieChart);
@@ -1529,17 +1525,6 @@ Timeline.TimelineUIUtils = class {
}
/**
- * @return {!TimelineModel.TimelineModelFilter}
- */
- static paintEventsFilter() {
- const recordTypes = TimelineModel.TimelineModel.RecordType;
- return new TimelineModel.TimelineInvisibleEventsFilter(
- !Runtime.experiments.isEnabled('timelinePaintTimingMarkers') ?
- [recordTypes.MarkFCP, recordTypes.MarkFMP, recordTypes.MarkFMPCandidate] :
- []);
- }
-
- /**
* @return {!Object.<string, !Timeline.TimelineCategory>}
*/
static categories() {
@@ -1746,10 +1731,31 @@ Timeline.TimelineUIUtils = class {
/**
* @param {!SDK.TracingModel.Event} event
+ * @return {?string}
+ */
+ static markerShortTitle(event) {
+ const recordTypes = TimelineModel.TimelineModel.RecordType;
+ switch (event.name) {
+ case recordTypes.MarkDOMContent:
+ return ls`DCL`;
+ case recordTypes.MarkLoad:
+ return ls`L`;
+ case recordTypes.MarkFirstPaint:
+ return ls`FP`;
+ case recordTypes.MarkFCP:
+ return ls`FCP`;
+ case recordTypes.MarkFMP:
+ return ls`FMP`;
+ }
+ return null;
+ }
+
+ /**
+ * @param {!SDK.TracingModel.Event} event
* @return {!Timeline.TimelineMarkerStyle}
*/
static markerStyleForEvent(event) {
- const tallMarkerDashStyle = [10, 5];
+ const tallMarkerDashStyle = [6, 4];
const title = Timeline.TimelineUIUtils.eventTitle(event);
if (event.hasCategory(TimelineModel.TimelineModel.Category.Console) ||
@@ -1772,11 +1778,11 @@ Timeline.TimelineUIUtils = class {
tall = true;
break;
case recordTypes.MarkDOMContent:
- color = 'blue';
+ color = '#0867CB';
tall = true;
break;
case recordTypes.MarkLoad:
- color = 'red';
+ color = '#B31412';
tall = true;
break;
case recordTypes.MarkFirstPaint:
@@ -1784,15 +1790,11 @@ Timeline.TimelineUIUtils = class {
tall = true;
break;
case recordTypes.MarkFCP:
- color = 'hsl(160, 43%, 58%)';
- tall = true;
- break;
- case recordTypes.MarkFMPCandidate:
- color = 'hsl(146, 57%, 40%)';
+ color = '#208043';
tall = true;
break;
case recordTypes.MarkFMP:
- color = 'hsl(144, 100%, 21%)';
+ color = '#14522B';
tall = true;
break;
case recordTypes.TimeStamp:
@@ -2359,9 +2361,9 @@ Timeline.TimelineDetailsContentHelper = class {
parentElement.classList.add('timeline-details-stack-values');
const stackTraceElement =
parentElement.createChild('div', 'timeline-details-view-row-value timeline-details-view-row-stack-trace');
- const callFrameElem =
+ const callFrameContents =
Components.JSPresentationUtils.buildStackTracePreviewContents(this._target, this._linkifier, stackTrace);
- stackTraceElement.appendChild(callFrameElem);
+ stackTraceElement.appendChild(callFrameContents.element);
}
/**
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js b/chromium/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js
index 332ace621d7..1b0efac5fbb 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js
@@ -88,19 +88,19 @@ TimelineModel.TimelineModel = class {
* @param {!SDK.TracingModel.Event} event
* @return {boolean}
*/
- static isMarkerEvent(event) {
+ isMarkerEvent(event) {
const recordTypes = TimelineModel.TimelineModel.RecordType;
switch (event.name) {
- case recordTypes.FrameStartedLoading:
case recordTypes.TimeStamp:
+ return true;
case recordTypes.MarkFirstPaint:
case recordTypes.MarkFCP:
case recordTypes.MarkFMP:
- case recordTypes.MarkFMPCandidate:
- return true;
+ // TODO(alph): There are duplicate FMP events coming from the backend. Keep the one having 'data' property.
+ return this._mainFrame && event.args.frame === this._mainFrame.frameId && !!event.args.data;
case recordTypes.MarkDOMContent:
case recordTypes.MarkLoad:
- return event.args['data']['isMainFrame'];
+ return !!event.args['data']['isMainFrame'];
default:
return false;
}
@@ -541,7 +541,7 @@ TimelineModel.TimelineModel = class {
track.tasks.push(event);
eventStack.push(event);
}
- if (TimelineModel.TimelineModel.isMarkerEvent(event))
+ if (this.isMarkerEvent(event))
this._timeMarkerEvents.push(event);
track.events.push(event);
@@ -599,7 +599,7 @@ TimelineModel.TimelineModel = class {
}
if (asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) {
- group(TimelineModel.TimelineModel.TrackType.UserTiming).push(asyncEvent);
+ group(TimelineModel.TimelineModel.TrackType.Timings).push(asyncEvent);
continue;
}
@@ -685,6 +685,10 @@ TimelineModel.TimelineModel = class {
pageFrameId = TimelineModel.TimelineData.forEvent(eventStack.peekLast()).frameId;
timelineData.frameId = pageFrameId || (this._mainFrame && this._mainFrame.frameId) || '';
this._asyncEventTracker.processEvent(event);
+
+ if (this.isMarkerEvent(event))
+ this._ensureNamedTrack(TimelineModel.TimelineModel.TrackType.Timings);
+
switch (event.name) {
case recordTypes.ResourceSendRequest:
case recordTypes.WebSocketCreate:
@@ -1215,7 +1219,6 @@ TimelineModel.TimelineModel.RecordType = {
MarkFirstPaint: 'MarkFirstPaint',
MarkFCP: 'firstContentfulPaint',
MarkFMP: 'firstMeaningfulPaint',
- MarkFMPCandidate: 'firstMeaningfulPaintCandidate',
TimeStamp: 'TimeStamp',
ConsoleTime: 'ConsoleTime',
@@ -1396,7 +1399,7 @@ TimelineModel.TimelineModel.TrackType = {
Worker: Symbol('Worker'),
Input: Symbol('Input'),
Animation: Symbol('Animation'),
- UserTiming: Symbol('UserTiming'),
+ Timings: Symbol('Timings'),
Console: Symbol('Console'),
Raster: Symbol('Raster'),
GPU: Symbol('GPU'),
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js b/chromium/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js
index 0178835dbff..648ca00c381 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js
@@ -118,36 +118,18 @@ UI.ShortcutRegistry = class {
* @param {string} domKey
* @param {!KeyboardEvent=} event
*/
- handleKey(key, domKey, event) {
+ async handleKey(key, domKey, event) {
const keyModifiers = key >> 8;
const actions = this._applicableActions(key);
- if (!actions.length)
+ if (!actions.length || isPossiblyInputKey())
return;
- if (UI.Dialog.hasInstance()) {
- if (event && !isPossiblyInputKey())
- event.consume(true);
+ if (event)
+ event.consume(true);
+ if (UI.Dialog.hasInstance())
return;
- }
-
- if (!isPossiblyInputKey()) {
- if (event)
- event.consume(true);
- processNextAction.call(this, false);
- } else {
- this._pendingActionTimer = setTimeout(processNextAction.bind(this, false), 0);
- }
-
- /**
- * @param {boolean} handled
- * @this {UI.ShortcutRegistry}
- */
- function processNextAction(handled) {
- delete this._pendingActionTimer;
- const action = actions.shift();
- if (!action || handled)
+ for (const action of actions) {
+ if (await action.execute())
return;
-
- action.execute().then(processNextAction.bind(this));
}
/**
@@ -203,18 +185,10 @@ UI.ShortcutRegistry = class {
this._defaultKeyToActions.set(String(descriptor.key), actionId);
}
- dismissPendingShortcutAction() {
- if (this._pendingActionTimer) {
- clearTimeout(this._pendingActionTimer);
- delete this._pendingActionTimer;
- }
- }
-
/**
* @param {!Document} document
*/
_registerBindings(document) {
- document.addEventListener('input', this.dismissPendingShortcutAction.bind(this), true);
const extensions = self.runtime.extensions('action');
extensions.forEach(registerExtension, this);
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js b/chromium/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js
index 9c2761c2ef7..7531b84bb83 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js
@@ -2045,3 +2045,32 @@ UI.createExpandableText = function(text, maxLength) {
});
return fragment;
};
+
+/**
+ * @interface
+ */
+UI.Renderer = function() {};
+
+UI.Renderer.prototype = {
+ /**
+ * @param {!Object} object
+ * @param {!UI.Renderer.Options=} options
+ * @return {!Promise<?{node: !Node, tree: ?UI.TreeOutline}>}
+ */
+ render(object, options) {}
+};
+
+/**
+ * @param {?Object} object
+ * @param {!UI.Renderer.Options=} options
+ * @return {!Promise<?{node: !Node, tree: ?UI.TreeOutline}>}
+ */
+UI.Renderer.render = async function(object, options) {
+ if (!object)
+ throw new Error('Can\'t render ' + object);
+ const renderer = await self.runtime.extension(UI.Renderer, object).instance();
+ return renderer ? renderer.render(object, options || {}) : null;
+};
+
+/** @typedef {!{title: (string|!Element|undefined), editable: (boolean|undefined) }} */
+UI.Renderer.Options;
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/ui/textPrompt.css b/chromium/third_party/blink/renderer/devtools/front_end/ui/textPrompt.css
index 7194f1cc897..5fb0dd61738 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/ui/textPrompt.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/ui/textPrompt.css
@@ -61,3 +61,7 @@
.text-prompt-editing ::content br {
display: none;
}
+
+:host-context(:not(:focus-within)) ::content ::selection {
+ background: transparent;
+}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.css b/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.css
index b83ae08c0b7..d8610f5cc42 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.css
+++ b/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.css
@@ -5,7 +5,7 @@
*/
:host {
- flex: 1 1;
+ flex: 1 1 auto;
padding: 2px 0 0 0;
}
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js b/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js
index 3f5c34745ac..cb4ed7cdd78 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js
@@ -43,6 +43,7 @@ UI.TreeOutline = class extends Common.Object {
this.contentElement = this._rootElement._childrenListNode;
this.contentElement.addEventListener('keydown', this._treeKeyDown.bind(this), false);
+ this._preventTabOrder = false;
this._showSelectionOnKeyboardFocus = false;
this._focusable = true;
this.setFocusable(this._focusable);
@@ -54,9 +55,11 @@ UI.TreeOutline = class extends Common.Object {
/**
* @param {boolean} show
+ * @param {boolean=} preventTabOrder
*/
- setShowSelectionOnKeyboardFocus(show) {
+ setShowSelectionOnKeyboardFocus(show, preventTabOrder) {
this.contentElement.classList.toggle('hide-selection-when-blurred', show);
+ this._preventTabOrder = !!preventTabOrder;
this._showSelectionOnKeyboardFocus = show;
}
@@ -225,7 +228,7 @@ UI.TreeOutline = class extends Common.Object {
/**
* @return {boolean}
*/
- _selectFirst() {
+ selectFirst() {
let first = this.firstChild();
while (first && !first.selectable)
first = first.traverseNextTreeElement(true);
@@ -276,7 +279,7 @@ UI.TreeOutline = class extends Common.Object {
} else if (event.keyCode === UI.KeyboardShortcut.Keys.Space.code) {
handled = this.selectedTreeElement.onspace();
} else if (event.key === 'Home') {
- handled = this._selectFirst();
+ handled = this.selectFirst();
} else if (event.key === 'End') {
handled = this._selectLast();
}
@@ -936,7 +939,7 @@ UI.TreeElement = class {
* @return {boolean}
*/
collapseOrAscend(altKey) {
- if (this.expanded) {
+ if (this.expanded && this._collapsible) {
if (altKey)
this.collapseRecursively();
else
@@ -1035,8 +1038,11 @@ UI.TreeElement = class {
* @return {boolean}
*/
select(omitFocus, selectedByUser) {
- if (!this.treeOutline || !this.selectable || this.selected)
+ if (!this.treeOutline || !this.selectable || this.selected) {
+ if (!omitFocus)
+ this.listItemElement.focus();
return false;
+ }
// Wait to deselect this element so that focus only changes once
const lastSelected = this.treeOutline.selectedTreeElement;
this.treeOutline.selectedTreeElement = null;
@@ -1044,6 +1050,8 @@ UI.TreeElement = class {
if (this.treeOutline._rootElement === this) {
if (lastSelected)
lastSelected.deselect();
+ if (!omitFocus)
+ this.listItemElement.focus();
return false;
}
@@ -1067,7 +1075,7 @@ UI.TreeElement = class {
*/
_setFocusable(focusable) {
if (focusable) {
- this._listItemNode.setAttribute('tabIndex', 0);
+ this._listItemNode.setAttribute('tabIndex', this.treeOutline && this.treeOutline._preventTabOrder ? -1 : 0);
this._listItemNode.addEventListener('focus', this._boundOnFocus, false);
this._listItemNode.addEventListener('blur', this._boundOnBlur, false);
} else {
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/worker_app.json b/chromium/third_party/blink/renderer/devtools/front_end/worker_app.json
index bb5c7d438ff..5975d54503f 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/worker_app.json
+++ b/chromium/third_party/blink/renderer/devtools/front_end/worker_app.json
@@ -3,7 +3,6 @@
{ "name": "mobile_throttling", "type": "autostart" },
{ "name": "worker_main", "type": "autostart" },
- { "name": "browser_console" },
{ "name": "browser_debugger" },
{ "name": "cookie_table" },
{ "name": "elements" },
diff --git a/chromium/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js b/chromium/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js
index 71cf0ca5c0f..c9971425a15 100644
--- a/chromium/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js
+++ b/chromium/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js
@@ -10,29 +10,21 @@ WorkerMain.WorkerMain = class extends Common.Object {
* @override
*/
run() {
- const capabilities = SDK.Target.Capability.Browser | SDK.Target.Capability.Log | SDK.Target.Capability.Network |
- SDK.Target.Capability.Target | SDK.Target.Capability.Inspector;
- SDK.targetManager.createTarget(
- 'main', Common.UIString('Main'), capabilities, this._createMainConnection.bind(this), null, false /* isNodeJS */);
- InspectorFrontendHost.connectionReady();
+ SDK.initMainConnection(() => {
+ SDK.targetManager.createTarget('main', ls`Main`, SDK.Target.Type.ServiceWorker, null);
+ }, Components.TargetDetachedDialog.webSocketConnectionLost);
new MobileThrottling.NetworkPanelIndicator();
}
-
- /**
- * @param {!Protocol.InspectorBackend.Connection.Params} params
- * @return {!Protocol.InspectorBackend.Connection}
- */
- _createMainConnection(params) {
- return SDK.createMainConnection(params, () => Components.TargetDetachedDialog.webSocketConnectionLost());
- }
};
-SDK.ChildTargetManager.install(({target, waitingForDebugger}) => {
- const parentTarget = target.parentTarget();
+SDK.ChildTargetManager.install(async ({target, waitingForDebugger}) => {
// Only pause the new worker if debugging SW - we are going through the pause on start checkbox.
- if (!parentTarget.parentTarget() && waitingForDebugger) {
- const debuggerModel = target.model(SDK.DebuggerModel);
- if (debuggerModel)
- debuggerModel.pause();
- }
+ if (target.parentTarget().type() !== SDK.Target.Type.ServiceWorker || !waitingForDebugger)
+ return;
+ const debuggerModel = target.model(SDK.DebuggerModel);
+ if (!debuggerModel)
+ return;
+ if (!debuggerModel.isReadyToPause())
+ await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause);
+ debuggerModel.pause();
});
diff --git a/chromium/third_party/blink/renderer/devtools/readme.md b/chromium/third_party/blink/renderer/devtools/readme.md
index a18a1f08cf7..12f7aa175a4 100644
--- a/chromium/third_party/blink/renderer/devtools/readme.md
+++ b/chromium/third_party/blink/renderer/devtools/readme.md
@@ -91,7 +91,7 @@ npm test -- -f --child-processes=16
npm test -- --time-out-ms=6000000 <test_path>
```
-> **Tip**: [Learn about the test harness flags](https://chromium.googlesource.com/chromium/src/+/master/docs/testing/layout_tests.md#Test-Harness-Options)
+> **Tip**: [Learn about the test harness flags](https://chromium.googlesource.com/chromium/src/+/master/docs/testing/web_tests.md#Test-Harness-Options)
#### `--fetch-content-shell`
```
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/build/code_generator_frontend.py b/chromium/third_party/blink/renderer/devtools/scripts/build/code_generator_frontend.py
index 12226dc5542..8b00f700568 100755
--- a/chromium/third_party/blink/renderer/devtools/scripts/build/code_generator_frontend.py
+++ b/chromium/third_party/blink/renderer/devtools/scripts/build/code_generator_frontend.py
@@ -79,6 +79,8 @@ class RawTypes(object):
return "boolean"
elif json_type == "string":
return "string"
+ elif json_type == "binary":
+ return "string"
elif json_type == "array":
return "object"
elif json_type == "object":
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/build/generate_devtools_grd.py b/chromium/third_party/blink/renderer/devtools/scripts/build/generate_devtools_grd.py
index 9f6076bf668..e9a31102161 100755
--- a/chromium/third_party/blink/renderer/devtools/scripts/build/generate_devtools_grd.py
+++ b/chromium/third_party/blink/renderer/devtools/scripts/build/generate_devtools_grd.py
@@ -54,7 +54,7 @@ kGrdTemplate = '''<?xml version="1.0" encoding="UTF-8"?>
</outputs>
<release seq="1">
<includes>
- <include name="COMPRESSED_PROTOCOL_JSON" file="${compressed_protocol_file}" use_base_dir="false" type="BINDATA" />
+ <include name="COMPRESSED_PROTOCOL_JSON" file="${compressed_protocol_file}" use_base_dir="false" type="BINDATA" skip_in_resource_map = "true"/>
</includes>
</release>
</grit>
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/build/generate_protocol_externs.py b/chromium/third_party/blink/renderer/devtools/scripts/build/generate_protocol_externs.py
index 5babdfd8ade..492ee41007a 100755
--- a/chromium/third_party/blink/renderer/devtools/scripts/build/generate_protocol_externs.py
+++ b/chromium/third_party/blink/renderer/devtools/scripts/build/generate_protocol_externs.py
@@ -46,6 +46,7 @@ import pdl # pylint: disable=F0401
type_traits = {
"any": "*",
"string": "string",
+ "binary": "string",
"integer": "number",
"number": "number",
"boolean": "boolean",
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/compile_frontend.py b/chromium/third_party/blink/renderer/devtools/scripts/compile_frontend.py
index 223b0142263..da85cb71bc9 100755
--- a/chromium/third_party/blink/renderer/devtools/scripts/compile_frontend.py
+++ b/chromium/third_party/blink/renderer/devtools/scripts/compile_frontend.py
@@ -216,7 +216,7 @@ def find_java():
if match:
major = int(match.group(1))
minor = int(match.group(2))
- is_ok = major >= required_major and minor >= required_minor
+ is_ok = major > required_major or major == required_major and minor >= required_minor
if is_ok:
exec_command = [java_path, '-Xms1024m', '-server', '-XX:+TieredCompilation']
check_server_proc = popen(exec_command + ['-version'])
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/extract_module/extract_module.js b/chromium/third_party/blink/renderer/devtools/scripts/extract_module/extract_module.js
index eddfff186a5..6a8cdd8a709 100644
--- a/chromium/third_party/blink/renderer/devtools/scripts/extract_module/extract_module.js
+++ b/chromium/third_party/blink/renderer/devtools/scripts/extract_module/extract_module.js
@@ -385,9 +385,9 @@ function mapIdentifiers(identifiersByFile, cssFilesMapping) {
function renameIdentifiers(identifierMap) {
walkSync('front_end', write, true);
- walkSync('../../LayoutTests/http/tests/devtools', write, false);
- walkSync('../../LayoutTests/http/tests/inspector-protocol', write, false);
- walkSync('../../LayoutTests/inspector-protocol', write, false);
+ walkSync('../../web_tests/http/tests/devtools', write, false);
+ walkSync('../../web_tests/http/tests/inspector-protocol', write, false);
+ walkSync('../../web_tests/inspector-protocol', write, false);
function walkSync(currentDirPath, process, json) {
fs.readdirSync(currentDirPath).forEach(function(name) {
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/npm_test.js b/chromium/third_party/blink/renderer/devtools/scripts/npm_test.js
index 29432b6ac14..113faa8f16a 100644
--- a/chromium/third_party/blink/renderer/devtools/scripts/npm_test.js
+++ b/chromium/third_party/blink/renderer/devtools/scripts/npm_test.js
@@ -223,7 +223,6 @@ function getContentShellBinaryPath(dirPath) {
function runTests(buildDirectoryPath, useDebugDevtools) {
var testArgs = getInspectorTests().concat([
- '--no-pixel-tests',
'--build-directory',
buildDirectoryPath,
'--target',
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/README.md b/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/README.md
new file mode 100644
index 00000000000..0b5c1e85490
--- /dev/null
+++ b/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/README.md
@@ -0,0 +1,9 @@
+# Running Old Devtools
+
+This package launches your current version of Chromium, and an old version of Chromium.
+It then opens the DevTools of the old Chromium inside the new Chromium. This can be
+used to test devtools_compatibility.js. Remember to recompile after making changes
+to devtools_compatibility.js.
+
+## Usage
+First run `npm install` in this directory. Then run `node index.js <revision_number>`.
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/index.js b/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/index.js
new file mode 100644
index 00000000000..1a91738075c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/index.js
@@ -0,0 +1,68 @@
+const path = require('path');
+const fs = require('fs');
+const puppeteer = require('puppeteer');
+const childProcess = require('child_process');
+const CHROMIUM_DEFAULT_PATH = path.resolve(__dirname, '..', '..', '..', '..', '..', '..', 'out', 'Release', 'chrome');
+
+(async function() {
+ const targetRevision = process.argv[2];
+ if (!targetRevision || String(parseInt(targetRevision, 10)) !== targetRevision) {
+ console.log('The first argument should be a Chromium revision number, like 338865');
+ return;
+ }
+ const info = await downloadChrome(targetRevision);
+ childProcess.exec(`${info.executablePath} --remote-debugging-port=9227 --user-data-dir=user-data-dir about:blank`);
+ const browser = await puppeteer.launch({
+ executablePath: process.env.CHROMIUM_PATH || CHROMIUM_DEFAULT_PATH,
+ dumpio: true,
+ defaultViewport: null,
+ ignoreDefaultArgs: true,
+ args: puppeteer.defaultArgs({
+ headless: false,
+ args: ['--no-default-browser-check', `--custom-devtools-frontend=http://localhost:9227/devtools/`],
+ userDataDir: 'debugging-user-data-dir'
+ }).filter(x => !x.startsWith('--enable-automation'))
+ });
+ const page = (await browser.pages())[0];
+ await page.goto('http://localhost:9227');
+ const chromeVersion = await page.evaluate(async () => {
+ const data = await fetch('json/version');
+ const json = await data.json();
+ const userAgent = json['User-Agent'];
+ const start = userAgent.indexOf('Chrome/') + 'Chrome/'.length;
+ return userAgent.substring(start, userAgent.indexOf(' ', start));
+ });
+ console.log(`Launched Chromium ${chromeVersion}`);
+ await page.bringToFront();
+ await page.waitForSelector('a');
+ const realURL = await page.evaluate(() => document.querySelector('a').href);
+
+ const url = `chrome-devtools://devtools/custom/${realURL.substring('http://localhost:9227/devtools/'.length)}&remoteVersion=${chromeVersion}`;
+
+ await page.goto(url);
+})();
+
+async function downloadChrome(revision) {
+ const fetcher = puppeteer.createBrowserFetcher();
+ let progressBar = null;
+ let lastDownloadedBytes = 0;
+ return await fetcher.download(revision, (downloadedBytes, totalBytes) => {
+ if (!progressBar) {
+ const ProgressBar = require('progress');
+ progressBar = new ProgressBar(`Downloading Chromium r${revision} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {
+ complete: '=',
+ incomplete: ' ',
+ width: 20,
+ total: totalBytes,
+ });
+ }
+ const delta = downloadedBytes - lastDownloadedBytes;
+ lastDownloadedBytes = downloadedBytes;
+ progressBar.tick(delta);
+ });
+}
+
+function toMegabytes(bytes) {
+ const mb = bytes / 1024 / 1024;
+ return `${Math.round(mb * 10) / 10} Mb`;
+} \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/package.json b/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/package.json
new file mode 100644
index 00000000000..0dc45f4d9d4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/devtools/scripts/run_old_devtools/package.json
@@ -0,0 +1,10 @@
+{
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js"
+ },
+ "dependencies": {
+ "progress": "^2.0.1",
+ "puppeteer": "^1.9.0"
+ }
+}
diff --git a/chromium/third_party/blink/renderer/modules/BUILD.gn b/chromium/third_party/blink/renderer/modules/BUILD.gn
index 7af1d24e4be..051ab3a286f 100644
--- a/chromium/third_party/blink/renderer/modules/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/BUILD.gn
@@ -102,6 +102,7 @@ target("jumbo_" + modules_target_type, "modules") {
"//third_party/blink/renderer/modules/cache_storage",
"//third_party/blink/renderer/modules/canvas",
"//third_party/blink/renderer/modules/clipboard",
+ "//third_party/blink/renderer/modules/contacts_picker",
"//third_party/blink/renderer/modules/cookie_store",
"//third_party/blink/renderer/modules/credentialmanager",
"//third_party/blink/renderer/modules/crypto",
@@ -163,6 +164,7 @@ target("jumbo_" + modules_target_type, "modules") {
"//third_party/blink/renderer/modules/webshare",
"//third_party/blink/renderer/modules/websockets",
"//third_party/blink/renderer/modules/webusb",
+ "//third_party/blink/renderer/modules/worklet",
"//third_party/blink/renderer/modules/xr",
"//third_party/icu",
"//third_party/webrtc/pc:libjingle_peerconnection",
@@ -194,7 +196,10 @@ jumbo_source_set("modules_testing") {
"peerconnection/adapters/test/mock_ice_transport_adapter.h",
"peerconnection/adapters/test/mock_ice_transport_adapter_cross_thread_factory.h",
"peerconnection/adapters/test/mock_p2p_quic_packet_transport.h",
+ "peerconnection/adapters/test/mock_p2p_quic_stream.h",
+ "peerconnection/adapters/test/mock_p2p_quic_stream_delegate.h",
"peerconnection/adapters/test/mock_p2p_quic_transport.h",
+ "peerconnection/adapters/test/mock_p2p_quic_transport_delegate.h",
"peerconnection/adapters/test/mock_p2p_quic_transport_factory.h",
"peerconnection/testing/internals_rtc_certificate.cc",
"peerconnection/testing/internals_rtc_certificate.h",
@@ -247,7 +252,6 @@ jumbo_source_set("unit_tests") {
"accessibility/testing/accessibility_test.cc",
"accessibility/testing/accessibility_test.h",
"animationworklet/animation_worklet_global_scope_test.cc",
- "animationworklet/animation_worklet_thread_test.cc",
"animationworklet/worklet_animation_test.cc",
"background_fetch/background_fetch_icon_loader_test.cc",
"background_fetch/background_fetch_manager_test.cc",
@@ -259,6 +263,7 @@ jumbo_source_set("unit_tests") {
"credentialmanager/credentials_container_test.cc",
"credentialmanager/password_credential_test.cc",
"csspaint/paint_rendering_context_2d_test.cc",
+ "csspaint/paint_worklet_global_scope_test.cc",
"csspaint/paint_worklet_test.cc",
"device_orientation/device_motion_event_pump_unittest.cc",
"device_orientation/device_orientation_event_pump_unittest.cc",
@@ -266,13 +271,20 @@ jumbo_source_set("unit_tests") {
"eventsource/event_source_parser_test.cc",
"filesystem/dom_file_system_base_test.cc",
"filesystem/file_writer_test.cc",
+ "indexeddb/idb_factory_test.cc",
"indexeddb/idb_key_path_test.cc",
"indexeddb/idb_request_test.cc",
"indexeddb/idb_test_helper.cc",
"indexeddb/idb_transaction_test.cc",
"indexeddb/idb_value_wrapping_test.cc",
+ "indexeddb/mock_web_idb_callbacks.cc",
+ "indexeddb/mock_web_idb_callbacks.h",
"indexeddb/mock_web_idb_database.cc",
"indexeddb/mock_web_idb_database.h",
+ "indexeddb/mock_web_idb_factory.cc",
+ "indexeddb/mock_web_idb_factory.h",
+ "indexeddb/web_idb_cursor_impl_unittest.cc",
+ "indexeddb/web_idb_database_impl_unittest.cc",
"manifest/image_resource_type_converters_test.cc",
"media_controls/elements/media_control_animated_arrow_container_element_test.cc",
"media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc",
@@ -304,11 +316,15 @@ jumbo_source_set("unit_tests") {
"payments/payment_test_helper.cc",
"payments/payment_test_helper.h",
"payments/payments_validators_test.cc",
+ "peerconnection/adapters/p2p_quic_stream_unittest.cc",
"peerconnection/adapters/p2p_quic_transport_test.cc",
+ "peerconnection/byte_buffer_queue_test.cc",
+ "peerconnection/call_setup_state_tracker_unittest.cc",
"peerconnection/rtc_data_channel_test.cc",
"peerconnection/rtc_ice_transport_test.cc",
"peerconnection/rtc_ice_transport_test.h",
"peerconnection/rtc_peer_connection_test.cc",
+ "peerconnection/rtc_quic_stream_test.cc",
"peerconnection/rtc_quic_transport_test.cc",
"peerconnection/rtc_quic_transport_test.h",
"picture_in_picture/html_video_element_picture_in_picture_test.cc",
@@ -339,6 +355,7 @@ jumbo_source_set("unit_tests") {
"webdatabase/quota_tracker_test.cc",
"websockets/dom_websocket_test.cc",
"websockets/websocket_channel_impl_test.cc",
+ "worklet/animation_and_paint_worklet_thread_test.cc",
]
configs += [
@@ -364,4 +381,14 @@ jumbo_source_set("unit_tests") {
"//third_party/webrtc/rtc_base:rtc_base",
"//v8",
]
+
+ data_deps = [
+ ":accessibility_unittests_data",
+ ]
+}
+
+group("accessibility_unittests_data") {
+ data = [
+ "accessibility/testing/data/",
+ ]
}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc
index b5cbf790b05..99cd4415844 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/accessibility_object_model_test.cc
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
+namespace test {
namespace {
@@ -400,4 +401,5 @@ TEST_F(AccessibilityObjectModelTest, LabeledBy) {
} // namespace
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.cc
index 7b1d31b4173..d1a3eeed414 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.cc
@@ -23,12 +23,6 @@ STATIC_ASSERT_ENUM(kWebAXOrientationVertical,
STATIC_ASSERT_ENUM(kWebAXOrientationHorizontal,
kAccessibilityOrientationHorizontal);
-STATIC_ASSERT_ENUM(kWebAXTextStyleNone, kTextStyleNone);
-STATIC_ASSERT_ENUM(kWebAXTextStyleBold, kTextStyleBold);
-STATIC_ASSERT_ENUM(kWebAXTextStyleItalic, kTextStyleItalic);
-STATIC_ASSERT_ENUM(kWebAXTextStyleUnderline, kTextStyleUnderline);
-STATIC_ASSERT_ENUM(kWebAXTextStyleLineThrough, kTextStyleLineThrough);
-
STATIC_ASSERT_ENUM(WebAXStringAttribute::kAriaKeyShortcuts,
AXStringAttribute::kAriaKeyShortcuts);
STATIC_ASSERT_ENUM(WebAXStringAttribute::kAriaRoleDescription,
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.h
index 1619d789722..5d07839c30c 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_enums.h
@@ -34,14 +34,6 @@ enum AccessibilitySelectedState {
kSelectedStateTrue,
};
-enum TextStyle {
- kTextStyleNone = 0,
- kTextStyleBold = 1 << 0,
- kTextStyleItalic = 1 << 1,
- kTextStyleUnderline = 1 << 2,
- kTextStyleLineThrough = 1 << 3
-};
-
enum class AXBoolAttribute {
kAriaBusy,
};
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.cc
index 3a1dde79006..4883a3e4f71 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.cc
@@ -37,8 +37,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXImageMapLink::AXImageMapLink(HTMLAreaElement* area,
AXObjectCacheImpl& ax_object_cache)
: AXNodeObject(area, ax_object_cache) {}
@@ -47,7 +45,7 @@ AXImageMapLink::~AXImageMapLink() = default;
AXImageMapLink* AXImageMapLink::Create(HTMLAreaElement* area,
AXObjectCacheImpl& ax_object_cache) {
- return new AXImageMapLink(area, ax_object_cache);
+ return MakeGarbageCollected<AXImageMapLink>(area, ax_object_cache);
}
HTMLMapElement* AXImageMapLink::MapElement() const {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.h
index 0f6fe6d99b6..009521a2f61 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_image_map_link.h
@@ -39,11 +39,9 @@ namespace blink {
class AXObjectCacheImpl;
class AXImageMapLink final : public AXNodeObject {
- private:
- explicit AXImageMapLink(HTMLAreaElement*, AXObjectCacheImpl&);
-
public:
static AXImageMapLink* Create(HTMLAreaElement*, AXObjectCacheImpl&);
+ explicit AXImageMapLink(HTMLAreaElement*, AXObjectCacheImpl&);
~AXImageMapLink() override;
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.cc
index cc2f3aaa45f..2a7d7bafc10 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.cc
@@ -34,12 +34,10 @@
#include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h"
#include "third_party/blink/renderer/modules/accessibility/ax_position.h"
#include "third_party/blink/renderer/modules/accessibility/ax_range.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
-using namespace HTMLNames;
-
AXInlineTextBox::AXInlineTextBox(
scoped_refptr<AbstractInlineTextBox> inline_text_box,
AXObjectCacheImpl& ax_object_cache)
@@ -48,7 +46,8 @@ AXInlineTextBox::AXInlineTextBox(
AXInlineTextBox* AXInlineTextBox::Create(
scoped_refptr<AbstractInlineTextBox> inline_text_box,
AXObjectCacheImpl& ax_object_cache) {
- return new AXInlineTextBox(std::move(inline_text_box), ax_object_cache);
+ return MakeGarbageCollected<AXInlineTextBox>(std::move(inline_text_box),
+ ax_object_cache);
}
void AXInlineTextBox::Init() {}
@@ -113,7 +112,8 @@ void AXInlineTextBox::TextCharacterOffsets(Vector<int>& offsets) const {
}
void AXInlineTextBox::GetWordBoundaries(Vector<AXRange>& words) const {
- if (!inline_text_box_ || inline_text_box_->GetText().ContainsOnlyWhitespace())
+ if (!inline_text_box_ ||
+ inline_text_box_->GetText().ContainsOnlyWhitespaceOrEmpty())
return;
Vector<AbstractInlineTextBox::WordBoundaries> boundaries;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h
index 8d0dfdb5c68..7ca785d7268 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h
@@ -39,13 +39,12 @@ class Node;
class AXObjectCacheImpl;
class AXInlineTextBox final : public AXObject {
- private:
- AXInlineTextBox(scoped_refptr<AbstractInlineTextBox>, AXObjectCacheImpl&);
-
public:
static AXInlineTextBox* Create(scoped_refptr<AbstractInlineTextBox>,
AXObjectCacheImpl&);
+ AXInlineTextBox(scoped_refptr<AbstractInlineTextBox>, AXObjectCacheImpl&);
+
protected:
void Init() override;
void Detach() override;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc
index c61588ea1d9..2b21d5cfb33 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/modules/accessibility/ax_layout_object.h"
#include "third_party/blink/renderer/core/aom/accessible_node.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
@@ -83,6 +83,7 @@
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
+#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h"
#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h"
#include "third_party/blink/renderer/core/loader/progress_tracker.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -110,104 +111,7 @@ using blink::WebLocalizedString;
namespace blink {
-using namespace HTMLNames;
-
-static inline LayoutObject* FirstChildInContinuation(
- const LayoutInline& layout_object) {
- LayoutBoxModelObject* r = layout_object.Continuation();
-
- while (r) {
- if (r->IsLayoutBlock())
- return r;
- if (LayoutObject* child = r->SlowFirstChild())
- return child;
- r = ToLayoutInline(r)->Continuation();
- }
-
- return nullptr;
-}
-
-static inline bool IsInlineWithContinuation(LayoutObject* object) {
- if (!object->IsBoxModelObject())
- return false;
-
- LayoutBoxModelObject* layout_object = ToLayoutBoxModelObject(object);
- if (!layout_object->IsLayoutInline())
- return false;
-
- return ToLayoutInline(layout_object)->Continuation();
-}
-
-static inline LayoutObject* FirstChildConsideringContinuation(
- LayoutObject* layout_object) {
- if (layout_object->IsLayoutNGListMarker()) {
- // We don't care tree structure of list marker.
- return nullptr;
- }
- LayoutObject* first_child = layout_object->SlowFirstChild();
-
- // CSS first-letter pseudo element is handled as continuation. Returning it
- // will result in duplicated elements.
- if (first_child && first_child->IsText() &&
- ToLayoutText(first_child)->IsTextFragment() &&
- ToLayoutTextFragment(first_child)->GetFirstLetterPseudoElement())
- return nullptr;
-
- if (!first_child && IsInlineWithContinuation(layout_object))
- first_child = FirstChildInContinuation(ToLayoutInline(*layout_object));
-
- return first_child;
-}
-
-static inline LayoutInline* StartOfContinuations(LayoutObject* r) {
- if (r->IsInlineElementContinuation()) {
- return ToLayoutInline(r->GetNode()->GetLayoutObject());
- }
-
- // Blocks with a previous continuation always have a next continuation
- if (r->IsLayoutBlockFlow() &&
- ToLayoutBlockFlow(r)->InlineElementContinuation())
- return ToLayoutInline(ToLayoutBlockFlow(r)
- ->InlineElementContinuation()
- ->GetNode()
- ->GetLayoutObject());
-
- return nullptr;
-}
-
-static inline LayoutObject* EndOfContinuations(LayoutObject* layout_object) {
- LayoutObject* prev = layout_object;
- LayoutObject* cur = layout_object;
-
- if (!cur->IsLayoutInline() && !cur->IsLayoutBlockFlow())
- return layout_object;
-
- while (cur) {
- prev = cur;
- if (cur->IsLayoutInline()) {
- cur = ToLayoutInline(cur)->InlineElementContinuation();
- DCHECK(cur || !ToLayoutInline(prev)->Continuation());
- } else {
- cur = ToLayoutBlockFlow(cur)->InlineElementContinuation();
- }
- }
-
- return prev;
-}
-
-static inline bool LastChildHasContinuation(LayoutObject* layout_object) {
- LayoutObject* last_child = layout_object->SlowLastChild();
- return last_child && IsInlineWithContinuation(last_child);
-}
-
-static LayoutBoxModelObject* NextContinuation(LayoutObject* layout_object) {
- DCHECK(layout_object);
- if (layout_object->IsLayoutInline() && !layout_object->IsAtomicInlineLevel())
- return ToLayoutInline(layout_object)->Continuation();
- if (layout_object->IsLayoutBlockFlow())
- return ToLayoutBlockFlow(layout_object)->InlineElementContinuation();
- return nullptr;
-}
+using namespace html_names;
AXLayoutObject::AXLayoutObject(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache)
@@ -222,7 +126,7 @@ AXLayoutObject::AXLayoutObject(LayoutObject* layout_object,
AXLayoutObject* AXLayoutObject::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXLayoutObject(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXLayoutObject>(layout_object, ax_object_cache);
}
AXLayoutObject::~AXLayoutObject() {
@@ -357,10 +261,17 @@ ax::mojom::Role AXLayoutObject::DetermineAccessibilityRole() {
Node* AXLayoutObject::GetNodeOrContainingBlockNode() const {
if (IsDetached())
return nullptr;
- if (GetLayoutObject()->IsAnonymousBlock() &&
- GetLayoutObject()->ContainingBlock()) {
- return GetLayoutObject()->ContainingBlock()->GetNode();
+
+ if (layout_object_->IsListMarker())
+ return ToLayoutListMarker(layout_object_)->ListItem()->GetNode();
+
+ if (layout_object_->IsLayoutNGListMarker())
+ return ToLayoutNGListMarker(layout_object_)->ListItem()->GetNode();
+
+ if (layout_object_->IsAnonymousBlock() && layout_object_->ContainingBlock()) {
+ return layout_object_->ContainingBlock()->GetNode();
}
+
return GetNode();
}
@@ -394,6 +305,19 @@ static bool IsLinkable(const AXObject& object) {
object.GetLayoutObject()->IsText();
}
+bool AXLayoutObject::IsDefault() const {
+ if (IsDetached())
+ return false;
+
+ // Checks for any kind of disabled, including aria-disabled.
+ if (Restriction() == kDisabled || RoleValue() != ax::mojom::Role::kButton)
+ return false;
+
+ // Will only match :default pseudo class if it's the first default button in
+ // a form.
+ return GetElement()->MatchesDefaultPseudoClass();
+}
+
// Requires layoutObject to be present because it relies on style
// user-modify. Don't move this logic to AXNodeObject.
bool AXLayoutObject::IsEditable() const {
@@ -422,6 +346,9 @@ bool AXLayoutObject::IsEditable() const {
if (GetLayoutObject()->IsTextControl())
return true;
+ // Contrary to Firefox, we mark editable all auto-generated content, such as
+ // list bullets and soft line breaks, that are contained within an editable
+ // container.
if (HasEditableStyle(*node))
return true;
@@ -464,6 +391,9 @@ bool AXLayoutObject::IsRichlyEditable() const {
return !EqualIgnoringASCIICase("false", editable);
}
+ // Contrary to Firefox, we mark richly editable all auto-generated content,
+ // such as list bullets and soft line breaks, that are contained within a
+ // richly editable container.
if (HasRichlyEditableStyle(*node))
return true;
@@ -674,12 +604,18 @@ bool AXLayoutObject::ComputeAccessibilityIsIgnored(
if (layout_object_->IsAnonymousBlock() && !IsEditable())
return true;
+ // Ignore continuations, since those are essentially duplicate copies
+ // of inline nodes with blocks inside.
+ if (layout_object_->IsElementContinuation())
+ return true;
+
// If this element is within a parent that cannot have children, it should not
// be exposed.
if (IsDescendantOfLeafNode()) {
- if (ignored_reasons)
+ if (ignored_reasons) {
ignored_reasons->push_back(
IgnoredReason(kAXAncestorIsLeafNode, LeafNodeAncestor()));
+ }
return true;
}
@@ -692,11 +628,12 @@ bool AXLayoutObject::ComputeAccessibilityIsIgnored(
if (HasInheritedPresentationalRole()) {
if (ignored_reasons) {
const AXObject* inherits_from = InheritsPresentationalRoleFrom();
- if (inherits_from == this)
+ if (inherits_from == this) {
ignored_reasons->push_back(IgnoredReason(kAXPresentational));
- else
+ } else {
ignored_reasons->push_back(
IgnoredReason(kAXInheritsPresentation, inherits_from));
+ }
}
return true;
}
@@ -779,7 +716,7 @@ bool AXLayoutObject::ComputeAccessibilityIsIgnored(
// Header and footer tags may also be exposed as landmark roles but not
// always.
if (GetNode() &&
- (GetNode()->HasTagName(headerTag) || GetNode()->HasTagName(footerTag)))
+ (GetNode()->HasTagName(kHeaderTag) || GetNode()->HasTagName(kFooterTag)))
return false;
// all controls are accessible
@@ -885,8 +822,8 @@ bool AXLayoutObject::ComputeAccessibilityIsIgnored(
// These checks are simplified in the interest of execution speed;
// for example, any element having an alt attribute will make it
// not ignored, rather than just images.
- if (HasAriaAttribute(GetElement()) || !GetAttribute(altAttr).IsEmpty() ||
- !GetAttribute(titleAttr).IsEmpty())
+ if (HasAriaAttribute(GetElement()) || !GetAttribute(kAltAttr).IsEmpty() ||
+ !GetAttribute(kTitleAttr).IsEmpty())
return false;
// <span> tags are inline tags and not meant to convey information if they
@@ -940,7 +877,7 @@ bool AXLayoutObject::ComputeAccessibilityIsIgnored(
bool AXLayoutObject::HasAriaCellRole(Element* elem) const {
DCHECK(elem);
- const AtomicString& aria_role_str = elem->FastGetAttribute(roleAttr);
+ const AtomicString& aria_role_str = elem->FastGetAttribute(kRoleAttr);
if (aria_role_str.IsEmpty())
return false;
@@ -962,7 +899,7 @@ bool AXLayoutObject::CanIgnoreSpaceNextTo(LayoutObject* layout,
LayoutText* layout_text = ToLayoutText(layout);
if (layout_text->HasEmptyText())
return false;
- if (layout_text->GetText().Impl()->ContainsOnlyWhitespace())
+ if (layout_text->GetText().Impl()->ContainsOnlyWhitespaceOrEmpty())
return true;
auto adjacent_char =
is_after ? layout_text->FirstCharacterAfterWhitespaceCollapsing()
@@ -1058,7 +995,7 @@ const AtomicString& AXLayoutObject::AccessKey() const {
return g_null_atom;
if (!node->IsElementNode())
return g_null_atom;
- return ToElement(node)->getAttribute(accesskeyAttr);
+ return ToElement(node)->getAttribute(kAccesskeyAttr);
}
RGBA32 AXLayoutObject::ComputeBackgroundColor() const {
@@ -1145,7 +1082,7 @@ String AXLayoutObject::ImageDataUrl(const IntSize& max_size) const {
if (!node)
return String();
- ImageBitmapOptions options;
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
ImageBitmap* image_bitmap = nullptr;
Document* document = &node->GetDocument();
if (auto* image = ToHTMLImageElementOrNull(node)) {
@@ -1308,7 +1245,11 @@ int AXLayoutObject::TextLength() const {
return GetText().length();
}
-TextStyle AXLayoutObject::GetTextStyle() const {
+static unsigned TextStyleFlag(ax::mojom::TextStyle text_style_enum) {
+ return static_cast<unsigned>(1 << static_cast<int>(text_style_enum));
+}
+
+int32_t AXLayoutObject::GetTextStyle() const {
if (!GetLayoutObject())
return AXNodeObject::GetTextStyle();
@@ -1316,17 +1257,17 @@ TextStyle AXLayoutObject::GetTextStyle() const {
if (!style)
return AXNodeObject::GetTextStyle();
- unsigned text_style = kTextStyleNone;
+ int32_t text_style = 0;
if (style->GetFontWeight() == BoldWeightValue())
- text_style |= kTextStyleBold;
+ text_style |= TextStyleFlag(ax::mojom::TextStyle::kBold);
if (style->GetFontDescription().Style() == ItalicSlopeValue())
- text_style |= kTextStyleItalic;
+ text_style |= TextStyleFlag(ax::mojom::TextStyle::kItalic);
if (style->GetTextDecoration() == TextDecoration::kUnderline)
- text_style |= kTextStyleUnderline;
+ text_style |= TextStyleFlag(ax::mojom::TextStyle::kUnderline);
if (style->GetTextDecoration() == TextDecoration::kLineThrough)
- text_style |= kTextStyleLineThrough;
+ text_style |= TextStyleFlag(ax::mojom::TextStyle::kLineThrough);
- return static_cast<TextStyle>(text_style);
+ return text_style;
}
KURL AXLayoutObject::Url() const {
@@ -1368,7 +1309,7 @@ void AXLayoutObject::LoadInlineTextBoxes() {
static bool ShouldUseLayoutNG(const LayoutObject& layout_object) {
return (layout_object.IsLayoutInline() || layout_object.IsText()) &&
- layout_object.EnclosingNGBlockFlow();
+ layout_object.ContainingNGBlockFlow();
}
// Note: |NextOnLineInternalNG()| returns null when fragment for |layout_object|
@@ -1534,7 +1475,7 @@ String AXLayoutObject::StringValue() const {
if (selected_index >= 0 &&
static_cast<size_t>(selected_index) < list_items.size()) {
const AtomicString& overridden_description =
- list_items[selected_index]->FastGetAttribute(aria_labelAttr);
+ list_items[selected_index]->FastGetAttribute(kAriaLabelAttr);
if (!overridden_description.IsNull())
return overridden_description;
}
@@ -1562,12 +1503,12 @@ String AXLayoutObject::StringValue() const {
// buttons which will return their name.
// https://html.spec.whatwg.org/multipage/forms.html#dom-input-value
if (const auto* input = ToHTMLInputElementOrNull(GetNode())) {
- if (input->type() != InputTypeNames::button &&
- input->type() != InputTypeNames::checkbox &&
- input->type() != InputTypeNames::image &&
- input->type() != InputTypeNames::radio &&
- input->type() != InputTypeNames::reset &&
- input->type() != InputTypeNames::submit) {
+ if (input->type() != input_type_names::kButton &&
+ input->type() != input_type_names::kCheckbox &&
+ input->type() != input_type_names::kImage &&
+ input->type() != input_type_names::kRadio &&
+ input->type() != input_type_names::kReset &&
+ input->type() != input_type_names::kSubmit) {
return input->value();
}
}
@@ -1694,24 +1635,24 @@ ax::mojom::HasPopup AXLayoutObject::HasPopup() const {
// a future version of WAI-ARIA. After that we will re-implement them
// following new spec.
bool AXLayoutObject::SupportsARIADragging() const {
- const AtomicString& grabbed = GetAttribute(aria_grabbedAttr);
+ const AtomicString& grabbed = GetAttribute(kAriaGrabbedAttr);
return EqualIgnoringASCIICase(grabbed, "true") ||
EqualIgnoringASCIICase(grabbed, "false");
}
bool AXLayoutObject::SupportsARIADropping() const {
- const AtomicString& drop_effect = GetAttribute(aria_dropeffectAttr);
+ const AtomicString& drop_effect = GetAttribute(kAriaDropeffectAttr);
return !drop_effect.IsEmpty();
}
bool AXLayoutObject::SupportsARIAFlowTo() const {
- return !GetAttribute(aria_flowtoAttr).IsEmpty();
+ return !GetAttribute(kAriaFlowtoAttr).IsEmpty();
}
bool AXLayoutObject::SupportsARIAOwns() const {
if (!layout_object_)
return false;
- const AtomicString& aria_owns = GetAttribute(aria_ownsAttr);
+ const AtomicString& aria_owns = GetAttribute(kAriaOwnsAttr);
return !aria_owns.IsEmpty();
}
@@ -1830,6 +1771,235 @@ AXObject* AXLayoutObject::ElementAccessibilityHitTest(
}
//
+// Low-level accessibility tree exploration, only for use within the
+// accessibility module.
+//
+// LAYOUT TREE WALKING ALGORITHM
+//
+// The fundamental types of elements in the Blink layout tree are block
+// elements and inline elements. It can get a little confusing when
+// an inline element has both inline and block children, for example:
+//
+// <a href="#">
+// Before Block
+// <div>
+// In Block
+// </div>
+// Outside Block
+// </a>
+//
+// Blink wants to maintain the invariant that all of the children of a node
+// are either all block or all inline, so it creates three anonymous blocks:
+//
+// #1 LayoutBlockFlow (anonymous)
+// #2 LayoutInline A continuation=#4
+// #3 LayoutText "Before Block"
+// #4 LayoutBlockFlow (anonymous) continuation=#8
+// #5 LayoutBlockFlow DIV
+// #6 LayoutText "In Block"
+// #7 LayoutBlockFlow (anonymous)
+// #8 LayoutInline A is_continuation
+// #9 LayoutText "Outside Block"
+//
+// For a good explanation of why this is done, see this blog entry. It's
+// describing WebKit in 2007, but the fundamentals haven't changed much.
+//
+// https://webkit.org/blog/115/webcore-rendering-ii-blocks-and-inlines/
+//
+// Now, it's important to understand that we couldn't just use the layout
+// tree as the accessibility tree as-is, because the div is no longer
+// inside the link! In fact, the link has been split into two different
+// nodes, #2 and #8. Luckily, the layout tree contains continuations to
+// help us untangle situations like this.
+//
+// Here's the algorithm we use to walk the layout tree in order to build
+// the accessibility tree:
+//
+// 1. When computing the first child or next sibling of a node, skip over any
+// LayoutObjects that are continuations.
+//
+// 2. When computing the next sibling of a node and there are no more siblings
+// in the layout tree, see if the parent node has a continuation, and if
+// so follow it and make that the next sibling.
+//
+// 3. When computing the first child of a node that has a continuation but
+// no children in the layout tree, the continuation is the first child.
+//
+// The end result is this tree, which we use as the basis for the
+// accessibility tree.
+//
+// #1 LayoutBlockFlow (anonymous)
+// #2 LayoutInline A
+// #3 LayoutText "Before Block"
+// #4 LayoutBlockFlow (anonymous)
+// #5 LayoutBlockFlow DIV
+// #6 LayoutText "In Block"
+// #8 LayoutInline A is_continuation
+// #9 LayoutText "Outside Block"
+// #7 LayoutBlockFlow (anonymous)
+//
+// This algorithm results in an accessibility tree that preserves containment
+// (i.e. the contents of the link in the example above are descendants of the
+// link node) while including all of the rich layout detail from the layout
+// tree.
+//
+// There are just a couple of other corner cases to walking the layout tree:
+//
+// * Walk tables in table order (thead, tbody, tfoot), which may not match
+// layout order.
+// * Skip CSS first-letter nodes.
+//
+
+// Given a layout object, return the start of the continuation chain.
+static inline LayoutInline* StartOfContinuations(LayoutObject* layout_object) {
+ // See LAYOUT TREE WALKING ALGORITHM, above, for more context as to why
+ // we need to do this.
+
+ // For inline elements, if it's a continuation, the start of the chain
+ // is always the primary layout object associated with the node.
+ if (layout_object->IsInlineElementContinuation())
+ return ToLayoutInline(layout_object->GetNode()->GetLayoutObject());
+
+ // Blocks with a previous continuation always have a next continuation,
+ // so we can get the next continuation and do the same trick to get
+ // the primary layout object associated with the node.
+ if (layout_object->IsLayoutBlockFlow() &&
+ ToLayoutBlockFlow(layout_object)->InlineElementContinuation()) {
+ LayoutInline* result = ToLayoutInline(ToLayoutBlockFlow(layout_object)
+ ->InlineElementContinuation()
+ ->GetNode()
+ ->GetLayoutObject());
+ DCHECK_NE(result, layout_object);
+ return result;
+ }
+
+ return nullptr;
+}
+
+// See LAYOUT TREE WALKING ALGORITHM, above, for details.
+static inline LayoutObject* ParentLayoutObject(LayoutObject* layout_object) {
+ if (!layout_object)
+ return nullptr;
+
+ // If the node is a continuation, the parent is the start of the continuation
+ // chain. See LAYOUT TREE WALKING ALGORITHM, above, for more context as to
+ // why we need to do this.
+ LayoutObject* start_of_conts = StartOfContinuations(layout_object);
+ if (start_of_conts)
+ return start_of_conts;
+
+ // Otherwise just return the parent in the layout tree.
+ return layout_object->Parent();
+}
+
+// See LAYOUT TREE WALKING ALGORITHM, above, for details.
+// Return true if this layout object is the continuation of some other
+// layout object.
+static bool IsContinuation(LayoutObject* layout_object) {
+ if (layout_object->IsElementContinuation())
+ return true;
+
+ if (layout_object->IsAnonymousBlock() && layout_object->IsLayoutBlockFlow() &&
+ ToLayoutBlockFlow(layout_object)->Continuation())
+ return true;
+
+ return false;
+}
+
+// See LAYOUT TREE WALKING ALGORITHM, above, for details.
+// Return the continuation of this layout object, or nullptr if it doesn't
+// have one.
+LayoutObject* GetContinuation(LayoutObject* layout_object) {
+ if (layout_object->IsLayoutInline())
+ return ToLayoutInline(layout_object)->Continuation();
+
+ if (layout_object->IsLayoutBlockFlow())
+ return ToLayoutBlockFlow(layout_object)->Continuation();
+
+ return nullptr;
+}
+
+// See LAYOUT TREE WALKING ALGORITHM, above, for details.
+AXObject* AXLayoutObject::RawFirstChild() const {
+ if (!layout_object_)
+ return nullptr;
+
+ // Walk sections of a table (thead, tbody, tfoot) in visual order.
+ // Note: always call RecalcSectionsIfNeeded() before accessing
+ // the sections of a LayoutTable.
+ if (layout_object_->IsTable()) {
+ LayoutTable* table = ToLayoutTable(layout_object_);
+ table->RecalcSectionsIfNeeded();
+ return AXObjectCache().GetOrCreate(table->TopSection());
+ }
+
+ if (layout_object_->IsLayoutNGListMarker()) {
+ // We don't care tree structure of list marker.
+ return nullptr;
+ }
+
+ LayoutObject* first_child = layout_object_->SlowFirstChild();
+
+ // CSS first-letter pseudo element is handled as continuation. Returning it
+ // will result in duplicated elements.
+ if (first_child && first_child->IsText() &&
+ ToLayoutText(first_child)->IsTextFragment() &&
+ ToLayoutTextFragment(first_child)->GetFirstLetterPseudoElement())
+ return nullptr;
+
+ // Skip over continuations.
+ while (first_child && IsContinuation(first_child))
+ first_child = first_child->NextSibling();
+
+ // If there's a first child that's not a continuation, return that.
+ if (first_child)
+ return AXObjectCache().GetOrCreate(first_child);
+
+ // Finally check if this object has no children but it has a continuation
+ // itself - and if so, it's the first child.
+ LayoutObject* continuation = GetContinuation(layout_object_);
+ if (continuation)
+ return AXObjectCache().GetOrCreate(continuation);
+
+ return nullptr;
+}
+
+// See LAYOUT TREE WALKING ALGORITHM, above, for details.
+AXObject* AXLayoutObject::RawNextSibling() const {
+ if (!layout_object_)
+ return nullptr;
+
+ // Walk sections of a table (thead, tbody, tfoot) in visual order.
+ if (layout_object_->IsTableSection()) {
+ LayoutTableSection* section = ToLayoutTableSection(layout_object_);
+ return AXObjectCache().GetOrCreate(
+ section->Table()->SectionBelow(section, kSkipEmptySections));
+ }
+
+ // If it's not a continuation, just get the next sibling from the
+ // layout tree, skipping over continuations.
+ if (!IsContinuation(layout_object_)) {
+ LayoutObject* next_sibling = layout_object_->NextSibling();
+ while (next_sibling && IsContinuation(next_sibling))
+ next_sibling = next_sibling->NextSibling();
+
+ if (next_sibling)
+ return AXObjectCache().GetOrCreate(next_sibling);
+ }
+
+ // If we've run out of siblings, check to see if the parent of this
+ // object has a continuation, and if so, follow it.
+ LayoutObject* parent = layout_object_->Parent();
+ if (parent) {
+ LayoutObject* continuation = GetContinuation(parent);
+ if (continuation)
+ return AXObjectCache().GetOrCreate(continuation);
+ }
+
+ return nullptr;
+}
+
+//
// High-level accessibility tree access.
//
@@ -1849,9 +2019,9 @@ AXObject* AXLayoutObject::ComputeParent() const {
return parent;
}
- LayoutObject* parent_obj = LayoutParentObject();
- if (parent_obj)
- return AXObjectCache().GetOrCreate(parent_obj);
+ LayoutObject* parent_layout_obj = ParentLayoutObject(layout_object_);
+ if (parent_layout_obj)
+ return AXObjectCache().GetOrCreate(parent_layout_obj);
// A WebArea's parent should be the page popup owner, if any, otherwise null.
if (IsWebArea()) {
@@ -1877,9 +2047,9 @@ AXObject* AXLayoutObject::ComputeParentIfExists() const {
return parent;
}
- LayoutObject* parent_obj = LayoutParentObject();
- if (parent_obj)
- return AXObjectCache().Get(parent_obj);
+ LayoutObject* parent_layout_obj = ParentLayoutObject(layout_object_);
+ if (parent_layout_obj)
+ return AXObjectCache().Get(parent_layout_obj);
// A WebArea's parent should be the page popup owner, if any, otherwise null.
if (IsWebArea()) {
@@ -1890,95 +2060,6 @@ AXObject* AXLayoutObject::ComputeParentIfExists() const {
return nullptr;
}
-//
-// Low-level accessibility tree exploration, only for use within the
-// accessibility module.
-//
-
-AXObject* AXLayoutObject::RawFirstChild() const {
- if (!layout_object_)
- return nullptr;
-
- // Walk sections of a table (thead, tbody, tfoot) in visual order.
- // Note: always call RecalcSectionsIfNeeded() before accessing
- // the sections of a LayoutTable.
- if (layout_object_->IsTable()) {
- LayoutTable* table = ToLayoutTable(layout_object_);
- table->RecalcSectionsIfNeeded();
- return AXObjectCache().GetOrCreate(table->TopSection());
- }
-
- LayoutObject* first_child = FirstChildConsideringContinuation(layout_object_);
-
- if (!first_child)
- return nullptr;
-
- return AXObjectCache().GetOrCreate(first_child);
-}
-
-AXObject* AXLayoutObject::RawNextSibling() const {
- if (!layout_object_)
- return nullptr;
-
- // Walk sections of a table (thead, tbody, tfoot) in visual order.
- if (layout_object_->IsTableSection()) {
- LayoutTableSection* section = ToLayoutTableSection(layout_object_);
- return AXObjectCache().GetOrCreate(
- section->Table()->SectionBelow(section, kSkipEmptySections));
- }
-
- LayoutObject* next_sibling = nullptr;
-
- LayoutInline* inline_continuation =
- layout_object_->IsLayoutBlockFlow()
- ? ToLayoutBlockFlow(layout_object_)->InlineElementContinuation()
- : nullptr;
- if (inline_continuation) {
- // Case 1: node is a block and has an inline continuation. Next sibling is
- // the inline continuation's first child.
- next_sibling = FirstChildConsideringContinuation(inline_continuation);
- } else if (layout_object_->IsAnonymousBlock() &&
- LastChildHasContinuation(layout_object_)) {
- // Case 2: Anonymous block parent of the start of a continuation - skip all
- // the way to after the parent of the end, since everything in between will
- // be linked up via the continuation.
- LayoutObject* last_parent =
- EndOfContinuations(ToLayoutBlock(layout_object_)->LastChild())
- ->Parent();
- while (LastChildHasContinuation(last_parent))
- last_parent = EndOfContinuations(last_parent->SlowLastChild())->Parent();
- next_sibling = last_parent->NextSibling();
- } else if (LayoutObject* ns = layout_object_->NextSibling()) {
- // Case 3: node has an actual next sibling
- next_sibling = ns;
- } else if (IsInlineWithContinuation(layout_object_)) {
- // Case 4: node is an inline with a continuation. Next sibling is the next
- // sibling of the end of the continuation chain.
- next_sibling = EndOfContinuations(layout_object_)->NextSibling();
- } else if (layout_object_->Parent() &&
- IsInlineWithContinuation(layout_object_->Parent())) {
- // Case 5: node has no next sibling, and its parent is an inline with a
- // continuation.
- LayoutObject* continuation =
- ToLayoutInline(layout_object_->Parent())->Continuation();
-
- if (continuation->IsLayoutBlock()) {
- // Case 5a: continuation is a block - in this case the block itself is the
- // next sibling.
- next_sibling = continuation;
- } else {
- // Case 5b: continuation is an inline - in this case the inline's first
- // child is the next sibling.
- next_sibling = FirstChildConsideringContinuation(continuation);
- }
- }
-
- if (!next_sibling)
- return nullptr;
-
- return AXObjectCache().GetOrCreate(next_sibling);
-}
-
void AXLayoutObject::AddChildren() {
if (IsDetached())
return;
@@ -2378,7 +2459,8 @@ static VisiblePosition ToVisiblePosition(AXObject* obj, int offset) {
if (!parent)
return VisiblePosition();
- VisiblePosition node_position = blink::VisiblePositionBeforeNode(*node);
+ VisiblePosition node_position =
+ CreateVisiblePosition(blink::PositionBeforeNode(*node));
int node_index = blink::IndexForVisiblePosition(node_position, parent);
return blink::VisiblePositionForIndex(node_index + offset, parent);
}
@@ -2399,7 +2481,7 @@ bool AXLayoutObject::OnNativeSetSelectionAction(const AXSelection& selection) {
if (anchor_object->GetLayoutObject()->GetNode() &&
anchor_object->GetLayoutObject()->GetNode()->DispatchEvent(
- *Event::CreateCancelableBubble(EventTypeNames::selectstart)) !=
+ *Event::CreateCancelableBubble(event_type_names::kSelectstart)) !=
DispatchEventResult::kNotCanceled)
return false;
@@ -2558,10 +2640,7 @@ void AXLayoutObject::HandleAriaExpandedChanged() {
void AXLayoutObject::HandleAutofillStateChanged(bool is_available) {
if (is_autofill_available_ != is_available) {
is_autofill_available_ = is_available;
- // Reusing the value change event in order to invalidate, even though the
- // value did not necessarily change.
- // TODO(dmazzoni) change to using a MarkDirty() API.
- AXObjectCache().PostNotification(this, ax::mojom::Event::kValueChanged);
+ AXObjectCache().MarkAXObjectDirty(this, false);
}
}
@@ -2817,7 +2896,7 @@ bool AXLayoutObject::IsDataTable() const {
valid_cell_count++;
// Any <th> tag -> treat as data table.
- if (cell_node->HasTagName(thTag))
+ if (cell_node->HasTagName(kThTag))
return true;
// In this case, the developer explicitly assigned a "data" table
@@ -2826,7 +2905,7 @@ bool AXLayoutObject::IsDataTable() const {
HTMLTableCellElement& cell_element = ToHTMLTableCellElement(*cell_node);
if (!cell_element.Headers().IsEmpty() ||
!cell_element.Abbr().IsEmpty() || !cell_element.Axis().IsEmpty() ||
- !cell_element.FastGetAttribute(scopeAttr).IsEmpty())
+ !cell_element.FastGetAttribute(kScopeAttr).IsEmpty())
return true;
}
@@ -3061,9 +3140,9 @@ static ax::mojom::Role DecideRoleFromSibling(LayoutTableCell* sibling_cell) {
return ax::mojom::Role::kCell;
if (Node* sibling_node = sibling_cell->GetNode()) {
- if (sibling_node->HasTagName(thTag))
+ if (sibling_node->HasTagName(kThTag))
return ax::mojom::Role::kColumnHeader;
- if (sibling_node->HasTagName(tdTag))
+ if (sibling_node->HasTagName(kTdTag))
return ax::mojom::Role::kRowHeader;
}
@@ -3101,10 +3180,10 @@ ax::mojom::Role AXLayoutObject::DetermineTableCellRole() const {
if (!parent->IsTableRowLikeRole())
return ax::mojom::Role::kGenericContainer;
- if (!GetNode() || !GetNode()->HasTagName(thTag))
+ if (!GetNode() || !GetNode()->HasTagName(kThTag))
return ax::mojom::Role::kCell;
- const AtomicString& scope = GetAttribute(scopeAttr);
+ const AtomicString& scope = GetAttribute(kScopeAttr);
if (EqualIgnoringASCIICase(scope, "row") ||
EqualIgnoringASCIICase(scope, "rowgroup"))
return ax::mojom::Role::kRowHeader;
@@ -3298,57 +3377,6 @@ AXObject* AXLayoutObject::AccessibilityImageMapHitTest(
return nullptr;
}
-LayoutObject* AXLayoutObject::LayoutParentObject() const {
- if (!layout_object_)
- return nullptr;
-
- LayoutObject* start_of_conts = layout_object_->IsLayoutBlockFlow()
- ? StartOfContinuations(layout_object_)
- : nullptr;
- if (start_of_conts) {
- // Case 1: node is a block and is an inline's continuation. Parent
- // is the start of the continuation chain.
- return start_of_conts;
- }
-
- LayoutObject* parent = layout_object_->Parent();
- start_of_conts = parent && parent->IsLayoutInline()
- ? StartOfContinuations(parent)
- : nullptr;
- if (start_of_conts) {
- // Case 2: node's parent is an inline which is some node's continuation;
- // parent is the earliest node in the continuation chain.
- return start_of_conts;
- }
-
- LayoutObject* first_child = parent ? parent->SlowFirstChild() : nullptr;
- if (first_child && first_child->GetNode()) {
- // Case 3: The first sibling is the beginning of a continuation chain. Find
- // the origin of that continuation. Get the node's layoutObject and follow
- // that continuation chain until the first child is found.
- for (LayoutObject* node_layout_first_child =
- first_child->GetNode()->GetLayoutObject();
- node_layout_first_child != first_child;
- node_layout_first_child = first_child->GetNode()->GetLayoutObject()) {
- for (LayoutObject* conts_test = node_layout_first_child; conts_test;
- conts_test = NextContinuation(conts_test)) {
- if (conts_test == first_child) {
- parent = node_layout_first_child->Parent();
- break;
- }
- }
- LayoutObject* new_first_child = parent->SlowFirstChild();
- if (first_child == new_first_child)
- break;
- first_child = new_first_child;
- if (!first_child->GetNode())
- break;
- }
- }
-
- return parent;
-}
-
bool AXLayoutObject::IsSVGImage() const {
return RemoteSVGRootElement();
}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.h
index 45384248ffa..9e1d6adb678 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_layout_object.h
@@ -45,11 +45,10 @@ class LocalFrameView;
class Node;
class MODULES_EXPORT AXLayoutObject : public AXNodeObject {
- protected:
- AXLayoutObject(LayoutObject*, AXObjectCacheImpl&);
-
public:
static AXLayoutObject* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXLayoutObject(LayoutObject*, AXObjectCacheImpl&);
~AXLayoutObject() override;
// Public, overridden from AXObject.
@@ -81,6 +80,7 @@ class MODULES_EXPORT AXLayoutObject : public AXNodeObject {
// Check object role or purpose.
bool IsAutofillAvailable() override { return is_autofill_available_; }
+ bool IsDefault() const override;
bool IsEditable() const override;
bool IsRichlyEditable() const override;
bool IsLinked() const override;
@@ -110,7 +110,7 @@ class MODULES_EXPORT AXLayoutObject : public AXNodeObject {
ax::mojom::TextDirection GetTextDirection() const final;
ax::mojom::TextPosition GetTextPosition() const final;
int TextLength() const override;
- TextStyle GetTextStyle() const final;
+ int32_t GetTextStyle() const final;
KURL Url() const override;
// Inline text boxes.
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_list.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_list.cc
index 98d081036a6..7ccdb8644df 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_list.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_list.cc
@@ -34,7 +34,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
AXList::AXList(LayoutObject* layout_object, AXObjectCacheImpl& ax_object_cache)
: AXLayoutObject(layout_object, ax_object_cache) {}
@@ -43,7 +43,7 @@ AXList::~AXList() = default;
AXList* AXList::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXList(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXList>(layout_object, ax_object_cache);
}
bool AXList::ComputeAccessibilityIsIgnored(
@@ -56,7 +56,7 @@ bool AXList::IsDescriptionList() const {
return false;
Node* node = layout_object_->GetNode();
- return node && node->HasTagName(dlTag);
+ return node && node->HasTagName(kDlTag);
}
ax::mojom::Role AXList::RoleValue() const {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_list.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_list.h
index f2211e18772..e568dd5fcad 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_list.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_list.h
@@ -37,11 +37,10 @@ namespace blink {
class AXObjectCacheImpl;
class AXList final : public AXLayoutObject {
- private:
- AXList(LayoutObject*, AXObjectCacheImpl&);
-
public:
static AXList* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXList(LayoutObject*, AXObjectCacheImpl&);
~AXList() override;
bool IsList() const override { return true; }
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.cc
index 083bad904a2..cb0e3c222d3 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.cc
@@ -35,8 +35,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXListBox::AXListBox(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache)
: AXLayoutObject(layout_object, ax_object_cache), active_index_(-1) {
@@ -47,7 +45,7 @@ AXListBox::~AXListBox() = default;
AXListBox* AXListBox::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXListBox(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXListBox>(layout_object, ax_object_cache);
}
ax::mojom::Role AXListBox::DetermineAccessibilityRole() {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.h
index c4ddb67784e..49eb8136be2 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box.h
@@ -37,11 +37,10 @@ namespace blink {
class AXObjectCacheImpl;
class AXListBox final : public AXLayoutObject {
- private:
- AXListBox(LayoutObject*, AXObjectCacheImpl&);
-
public:
static AXListBox* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXListBox(LayoutObject*, AXObjectCacheImpl&);
~AXListBox() override;
ax::mojom::Role DetermineAccessibilityRole() final;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.cc
index de06a56fd1c..3bac4993b99 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.cc
@@ -36,8 +36,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXListBoxOption::AXListBoxOption(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache)
: AXLayoutObject(layout_object, ax_object_cache) {}
@@ -46,7 +44,7 @@ AXListBoxOption::~AXListBoxOption() = default;
AXListBoxOption* AXListBoxOption::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXListBoxOption(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXListBoxOption>(layout_object, ax_object_cache);
}
ax::mojom::Role AXListBoxOption::DetermineAccessibilityRole() {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.h
index 07ed3c8f526..2ca3638df3e 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_list_box_option.h
@@ -39,11 +39,10 @@ class AXObjectCacheImpl;
class HTMLSelectElement;
class AXListBoxOption final : public AXLayoutObject {
- private:
- AXListBoxOption(LayoutObject*, AXObjectCacheImpl&);
-
public:
static AXListBoxOption* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXListBoxOption(LayoutObject*, AXObjectCacheImpl&);
~AXListBoxOption() override;
bool IsAXListBoxOption() const override { return true; }
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc
index 4bc852fd8ee..3f809473685 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.cc
@@ -38,7 +38,6 @@
namespace blink {
using blink::WebLocalizedString;
-using namespace HTMLNames;
static inline String QueryString(WebLocalizedString::Name name) {
return Locale::DefaultLocale().QueryString(name);
@@ -310,7 +309,8 @@ AXMediaControlsContainer::AXMediaControlsContainer(
AXObject* AXMediaControlsContainer::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXMediaControlsContainer(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXMediaControlsContainer>(layout_object,
+ ax_object_cache);
}
String AXMediaControlsContainer::TextAlternative(
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.h
index fc7c71c0424..17f5f96ec85 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_media_controls.h
@@ -101,6 +101,8 @@ class AccessibilityMediaVolumeSlider final : public AXSlider {
class AXMediaControlsContainer final : public AccessibilityMediaControl {
public:
static AXObject* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXMediaControlsContainer(LayoutObject*, AXObjectCacheImpl&);
~AXMediaControlsContainer() override = default;
ax::mojom::Role RoleValue() const override {
@@ -118,7 +120,6 @@ class AXMediaControlsContainer final : public AccessibilityMediaControl {
AXObjectVector* description_objects) const override;
private:
- AXMediaControlsContainer(LayoutObject*, AXObjectCacheImpl&);
bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const override;
DISALLOW_COPY_AND_ASSIGN(AXMediaControlsContainer);
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.cc
index 1f294af0880..db72843ea71 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.cc
@@ -38,7 +38,7 @@ AXMenuList::AXMenuList(LayoutMenuList* layout_object,
AXMenuList* AXMenuList::Create(LayoutMenuList* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXMenuList(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXMenuList>(layout_object, ax_object_cache);
}
ax::mojom::Role AXMenuList::DetermineAccessibilityRole() {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.h
index a54dc3177da..88c9315ec8e 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list.h
@@ -38,6 +38,8 @@ class AXMenuList final : public AXLayoutObject {
public:
static AXMenuList* Create(LayoutMenuList* layout_object, AXObjectCacheImpl&);
+ AXMenuList(LayoutMenuList*, AXObjectCacheImpl&);
+
AccessibilityExpanded IsExpanded() const final;
bool OnNativeClickAction() override;
void ClearChildren() override;
@@ -49,8 +51,6 @@ class AXMenuList final : public AXLayoutObject {
private:
friend class AXMenuListOption;
- AXMenuList(LayoutMenuList*, AXObjectCacheImpl&);
-
bool IsMenuList() const override { return true; }
ax::mojom::Role DetermineAccessibilityRole() final;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc
index 57b987bbdcd..cdd53f2cd8b 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc
@@ -34,8 +34,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXMenuListOption::AXMenuListOption(HTMLOptionElement* element,
AXObjectCacheImpl& ax_object_cache)
: AXMockObject(ax_object_cache), element_(element) {}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.h
index cfb60cb8751..e1e9eab2e69 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.h
@@ -38,15 +38,16 @@ class AXMenuListOption final : public AXMockObject {
public:
static AXMenuListOption* Create(HTMLOptionElement* element,
AXObjectCacheImpl& ax_object_cache) {
- return new AXMenuListOption(element, ax_object_cache);
+ return MakeGarbageCollected<AXMenuListOption>(element, ax_object_cache);
}
+
+ AXMenuListOption(HTMLOptionElement*, AXObjectCacheImpl&);
~AXMenuListOption() override;
int PosInSet() const override;
int SetSize() const override;
private:
- AXMenuListOption(HTMLOptionElement*, AXObjectCacheImpl&);
void Trace(blink::Visitor*) override;
bool IsMenuListOption() const override { return true; }
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc
index a1bf9c85429..3ee18b67150 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc
@@ -31,8 +31,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXMenuListPopup::AXMenuListPopup(AXObjectCacheImpl& ax_object_cache)
: AXMockObject(ax_object_cache), active_index_(-1) {}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.h
index 2625784fa6c..a92348a9834 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.h
@@ -38,9 +38,11 @@ class HTMLElement;
class AXMenuListPopup final : public AXMockObject {
public:
static AXMenuListPopup* Create(AXObjectCacheImpl& ax_object_cache) {
- return new AXMenuListPopup(ax_object_cache);
+ return MakeGarbageCollected<AXMenuListPopup>(ax_object_cache);
}
+ explicit AXMenuListPopup(AXObjectCacheImpl&);
+
AXRestriction Restriction() const override;
bool IsOffScreen() const override;
@@ -51,8 +53,6 @@ class AXMenuListPopup final : public AXMockObject {
void UpdateChildrenIfNecessary() override;
private:
- explicit AXMenuListPopup(AXObjectCacheImpl&);
-
bool IsMenuListPopup() const override { return true; }
ax::mojom::Role RoleValue() const override {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
index a73d98400e9..8db0b0c092c 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -80,7 +80,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// In ARIA 1.1, default value of aria-level was changed to 2.
const int kDefaultHeadingLevel = 2;
@@ -93,7 +93,7 @@ AXNodeObject::AXNodeObject(Node* node, AXObjectCacheImpl& ax_object_cache)
AXNodeObject* AXNodeObject::Create(Node* node,
AXObjectCacheImpl& ax_object_cache) {
- return new AXNodeObject(node, ax_object_cache);
+ return MakeGarbageCollected<AXNodeObject>(node, ax_object_cache);
}
AXNodeObject::~AXNodeObject() {
@@ -258,16 +258,16 @@ const AXObject* AXNodeObject::InheritsPresentationalRoleFrom() const {
static HashSet<QualifiedName>& GetLandmarkRolesNotAllowed() {
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, landmark_roles_not_allowed, ());
if (landmark_roles_not_allowed.IsEmpty()) {
- landmark_roles_not_allowed.insert(articleTag);
- landmark_roles_not_allowed.insert(asideTag);
- landmark_roles_not_allowed.insert(navTag);
- landmark_roles_not_allowed.insert(sectionTag);
- landmark_roles_not_allowed.insert(blockquoteTag);
- landmark_roles_not_allowed.insert(detailsTag);
- landmark_roles_not_allowed.insert(fieldsetTag);
- landmark_roles_not_allowed.insert(figureTag);
- landmark_roles_not_allowed.insert(tdTag);
- landmark_roles_not_allowed.insert(mainTag);
+ landmark_roles_not_allowed.insert(kArticleTag);
+ landmark_roles_not_allowed.insert(kAsideTag);
+ landmark_roles_not_allowed.insert(kNavTag);
+ landmark_roles_not_allowed.insert(kSectionTag);
+ landmark_roles_not_allowed.insert(kBlockquoteTag);
+ landmark_roles_not_allowed.insert(kDetailsTag);
+ landmark_roles_not_allowed.insert(kFieldsetTag);
+ landmark_roles_not_allowed.insert(kFigureTag);
+ landmark_roles_not_allowed.insert(kTdTag);
+ landmark_roles_not_allowed.insert(kMainTag);
}
return landmark_roles_not_allowed;
}
@@ -295,13 +295,13 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
if (!GetNode())
return ax::mojom::Role::kUnknown;
- // |HTMLAnchorElement| sets isLink only when it has hrefAttr.
+ // |HTMLAnchorElement| sets isLink only when it has kHrefAttr.
if (GetNode()->IsLink())
return ax::mojom::Role::kLink;
if (IsHTMLAnchorElement(*GetNode())) {
// We assume that an anchor element is LinkRole if it has event listners
- // even though it doesn't have hrefAttr.
+ // even though it doesn't have kHrefAttr.
if (IsClickable())
return ax::mojom::Role::kLink;
return ax::mojom::Role::kAnchor;
@@ -326,7 +326,7 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
const AtomicString& type = input->type();
if (input->DataList())
return ax::mojom::Role::kTextFieldWithComboBox;
- if (type == InputTypeNames::button) {
+ if (type == input_type_names::kButton) {
if ((GetNode()->parentNode() &&
IsHTMLMenuElement(GetNode()->parentNode())) ||
(ParentObject() &&
@@ -334,7 +334,7 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
return ax::mojom::Role::kMenuItem;
return ButtonRoleType();
}
- if (type == InputTypeNames::checkbox) {
+ if (type == input_type_names::kCheckbox) {
if ((GetNode()->parentNode() &&
IsHTMLMenuElement(GetNode()->parentNode())) ||
(ParentObject() &&
@@ -342,15 +342,15 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
return ax::mojom::Role::kMenuItemCheckBox;
return ax::mojom::Role::kCheckBox;
}
- if (type == InputTypeNames::date)
+ if (type == input_type_names::kDate)
return ax::mojom::Role::kDate;
- if (type == InputTypeNames::datetime ||
- type == InputTypeNames::datetime_local ||
- type == InputTypeNames::month || type == InputTypeNames::week)
+ if (type == input_type_names::kDatetime ||
+ type == input_type_names::kDatetimeLocal ||
+ type == input_type_names::kMonth || type == input_type_names::kWeek)
return ax::mojom::Role::kDateTime;
- if (type == InputTypeNames::file)
+ if (type == input_type_names::kFile)
return ax::mojom::Role::kButton;
- if (type == InputTypeNames::radio) {
+ if (type == input_type_names::kRadio) {
if ((GetNode()->parentNode() &&
IsHTMLMenuElement(GetNode()->parentNode())) ||
(ParentObject() &&
@@ -358,15 +358,15 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
return ax::mojom::Role::kMenuItemRadio;
return ax::mojom::Role::kRadioButton;
}
- if (type == InputTypeNames::number)
+ if (type == input_type_names::kNumber)
return ax::mojom::Role::kSpinButton;
if (input->IsTextButton())
return ButtonRoleType();
- if (type == InputTypeNames::range)
+ if (type == input_type_names::kRange)
return ax::mojom::Role::kSlider;
- if (type == InputTypeNames::color)
+ if (type == input_type_names::kColor)
return ax::mojom::Role::kColorWell;
- if (type == InputTypeNames::time)
+ if (type == input_type_names::kTime)
return ax::mojom::Role::kInputTime;
return ax::mojom::Role::kTextField;
}
@@ -421,53 +421,53 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
if (IsHTMLVideoElement(*GetNode()))
return ax::mojom::Role::kVideo;
- if (GetNode()->HasTagName(ddTag))
+ if (GetNode()->HasTagName(kDdTag))
return ax::mojom::Role::kDescriptionListDetail;
- if (GetNode()->HasTagName(dtTag))
+ if (GetNode()->HasTagName(kDtTag))
return ax::mojom::Role::kDescriptionListTerm;
if (GetNode()->nodeName() == "math")
return ax::mojom::Role::kMath;
- if (GetNode()->HasTagName(rpTag) || GetNode()->HasTagName(rtTag))
+ if (GetNode()->HasTagName(kRpTag) || GetNode()->HasTagName(kRtTag))
return ax::mojom::Role::kAnnotation;
if (IsHTMLFormElement(*GetNode()))
return ax::mojom::Role::kForm;
- if (GetNode()->HasTagName(abbrTag))
+ if (GetNode()->HasTagName(kAbbrTag))
return ax::mojom::Role::kAbbr;
- if (GetNode()->HasTagName(articleTag))
+ if (GetNode()->HasTagName(kArticleTag))
return ax::mojom::Role::kArticle;
- if (GetNode()->HasTagName(delTag))
+ if (GetNode()->HasTagName(kDelTag))
return ax::mojom::Role::kContentDeletion;
- if (GetNode()->HasTagName(insTag))
+ if (GetNode()->HasTagName(kInsTag))
return ax::mojom::Role::kContentInsertion;
- if (GetNode()->HasTagName(mainTag))
+ if (GetNode()->HasTagName(kMainTag))
return ax::mojom::Role::kMain;
- if (GetNode()->HasTagName(markTag))
+ if (GetNode()->HasTagName(kMarkTag))
return ax::mojom::Role::kMark;
- if (GetNode()->HasTagName(navTag))
+ if (GetNode()->HasTagName(kNavTag))
return ax::mojom::Role::kNavigation;
- if (GetNode()->HasTagName(asideTag))
+ if (GetNode()->HasTagName(kAsideTag))
return ax::mojom::Role::kComplementary;
- if (GetNode()->HasTagName(preTag))
+ if (GetNode()->HasTagName(kPreTag))
return ax::mojom::Role::kPre;
- if (GetNode()->HasTagName(sectionTag))
+ if (GetNode()->HasTagName(kSectionTag))
return ax::mojom::Role::kRegion;
// TODO(accessibility): http://crbug.com/873118
- if (GetNode()->HasTagName(addressTag))
+ if (GetNode()->HasTagName(kAddressTag))
return ax::mojom::Role::kContentInfo;
if (IsHTMLDialogElement(*GetNode()))
@@ -490,28 +490,28 @@ ax::mojom::Role AXNodeObject::NativeRoleIgnoringAria() const {
// There should only be one banner/contentInfo per page. If header/footer are
// being used within an article or section then it should not be exposed as
// whole page's banner/contentInfo but as a generic container role.
- if (GetNode()->HasTagName(headerTag)) {
+ if (GetNode()->HasTagName(kHeaderTag)) {
if (IsDescendantOfElementType(GetLandmarkRolesNotAllowed()))
return ax::mojom::Role::kGenericContainer;
return ax::mojom::Role::kBanner;
}
- if (GetNode()->HasTagName(footerTag)) {
+ if (GetNode()->HasTagName(kFooterTag)) {
if (IsDescendantOfElementType(GetLandmarkRolesNotAllowed()))
return ax::mojom::Role::kGenericContainer;
return ax::mojom::Role::kFooter;
}
- if (GetNode()->HasTagName(blockquoteTag))
+ if (GetNode()->HasTagName(kBlockquoteTag))
return ax::mojom::Role::kBlockquote;
- if (GetNode()->HasTagName(captionTag))
+ if (GetNode()->HasTagName(kCaptionTag))
return ax::mojom::Role::kCaption;
- if (GetNode()->HasTagName(figcaptionTag))
+ if (GetNode()->HasTagName(kFigcaptionTag))
return ax::mojom::Role::kFigcaption;
- if (GetNode()->HasTagName(figureTag))
+ if (GetNode()->HasTagName(kFigureTag))
return ax::mojom::Role::kFigure;
if (GetNode()->nodeName() == "TIME")
@@ -602,7 +602,7 @@ bool AXNodeObject::IsMultiline() const {
// also return true if an ancestor is editable.
bool AXNodeObject::HasContentEditableAttributeSet() const {
const AtomicString& content_editable_value =
- GetAttribute(contenteditableAttr);
+ GetAttribute(kContenteditableAttr);
if (content_editable_value.IsNull())
return false;
// Both "true" (case-insensitive) and the empty string count as true.
@@ -697,10 +697,10 @@ Element* AXNodeObject::MouseButtonListener() const {
for (Element* element = ToElement(node); element;
element = element->parentElement()) {
- if (element->HasEventListeners(EventTypeNames::click) ||
- element->HasEventListeners(EventTypeNames::mousedown) ||
- element->HasEventListeners(EventTypeNames::mouseup) ||
- element->HasEventListeners(EventTypeNames::DOMActivate))
+ if (element->HasEventListeners(event_type_names::kClick) ||
+ element->HasEventListeners(event_type_names::kMousedown) ||
+ element->HasEventListeners(event_type_names::kMouseup) ||
+ element->HasEventListeners(event_type_names::kDOMActivate))
return element;
}
@@ -786,7 +786,7 @@ bool AXNodeObject::IsImageButton() const {
bool AXNodeObject::IsInputImage() const {
Node* node = this->GetNode();
if (RoleValue() == ax::mojom::Role::kButton && IsHTMLInputElement(node))
- return ToHTMLInputElement(*node).type() == InputTypeNames::image;
+ return ToHTMLInputElement(*node).type() == input_type_names::kImage;
return false;
}
@@ -854,8 +854,8 @@ bool AXNodeObject::IsMultiSelectable() const {
bool AXNodeObject::IsNativeCheckboxOrRadio() const {
if (const auto* input = ToHTMLInputElementOrNull(GetNode())) {
- return input->type() == InputTypeNames::checkbox ||
- input->type() == InputTypeNames::radio;
+ return input->type() == input_type_names::kCheckbox ||
+ input->type() == input_type_names::kRadio;
}
return false;
}
@@ -872,7 +872,7 @@ bool AXNodeObject::IsNativeImage() const {
return true;
if (const auto* input = ToHTMLInputElementOrNull(*node))
- return input->type() == InputTypeNames::image;
+ return input->type() == input_type_names::kImage;
return false;
}
@@ -914,7 +914,7 @@ bool AXNodeObject::IsPasswordField() const {
aria_role != ax::mojom::Role::kUnknown)
return false;
- return ToHTMLInputElement(node)->type() == InputTypeNames::password;
+ return ToHTMLInputElement(node)->type() == input_type_names::kPassword;
}
bool AXNodeObject::IsProgressIndicator() const {
@@ -935,13 +935,13 @@ bool AXNodeObject::IsSpinButton() const {
bool AXNodeObject::IsNativeSlider() const {
if (const auto* input = ToHTMLInputElementOrNull(GetNode()))
- return input->type() == InputTypeNames::range;
+ return input->type() == input_type_names::kRange;
return false;
}
bool AXNodeObject::IsNativeSpinButton() const {
if (const auto* input = ToHTMLInputElementOrNull(GetNode()))
- return input->type() == InputTypeNames::number;
+ return input->type() == input_type_names::kNumber;
return false;
}
@@ -959,10 +959,10 @@ bool AXNodeObject::IsClickable() const {
// Note: we can't call |node->WillRespondToMouseClickEvents()| because that
// triggers a style recalc and can delete this.
- if (node->HasEventListeners(EventTypeNames::mouseup) ||
- node->HasEventListeners(EventTypeNames::mousedown) ||
- node->HasEventListeners(EventTypeNames::click) ||
- node->HasEventListeners(EventTypeNames::DOMActivate)) {
+ if (node->HasEventListeners(event_type_names::kMouseup) ||
+ node->HasEventListeners(event_type_names::kMousedown) ||
+ node->HasEventListeners(event_type_names::kClick) ||
+ node->HasEventListeners(event_type_names::kDOMActivate)) {
return true;
}
@@ -1037,7 +1037,7 @@ AccessibilityExpanded AXNodeObject::IsExpanded() const {
if (GetNode() && IsHTMLSummaryElement(*GetNode())) {
if (GetNode()->parentNode() &&
IsHTMLDetailsElement(GetNode()->parentNode()))
- return ToElement(GetNode()->parentNode())->hasAttribute(openAttr)
+ return ToElement(GetNode()->parentNode())->hasAttribute(kOpenAttr)
? kExpandedExpanded
: kExpandedCollapsed;
}
@@ -1068,7 +1068,7 @@ bool AXNodeObject::IsModal() const {
bool AXNodeObject::IsRequired() const {
Node* n = this->GetNode();
if (n && (n->IsElementNode() && ToElement(n)->IsFormControlElement()) &&
- HasAttribute(requiredAttr))
+ HasAttribute(kRequiredAttr))
return ToHTMLFormControlElement(n)->IsRequired();
if (AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kRequired))
@@ -1102,22 +1102,22 @@ int AXNodeObject::HeadingLevel() const {
return 0;
HTMLElement& element = ToHTMLElement(*node);
- if (element.HasTagName(h1Tag))
+ if (element.HasTagName(kH1Tag))
return 1;
- if (element.HasTagName(h2Tag))
+ if (element.HasTagName(kH2Tag))
return 2;
- if (element.HasTagName(h3Tag))
+ if (element.HasTagName(kH3Tag))
return 3;
- if (element.HasTagName(h4Tag))
+ if (element.HasTagName(kH4Tag))
return 4;
- if (element.HasTagName(h5Tag))
+ if (element.HasTagName(kH5Tag))
return 5;
- if (element.HasTagName(h6Tag))
+ if (element.HasTagName(kH6Tag))
return 6;
if (RoleValue() == ax::mojom::Role::kHeading)
@@ -1320,7 +1320,7 @@ AXObject::AXObjectVector AXNodeObject::RadioButtonsInGroup() const {
HeapVector<Member<HTMLInputElement>>
AXNodeObject::FindAllRadioButtonsWithSameName(HTMLInputElement* radio_button) {
HeapVector<Member<HTMLInputElement>> all_radio_buttons;
- if (!radio_button || radio_button->type() != InputTypeNames::radio)
+ if (!radio_button || radio_button->type() != input_type_names::kRadio)
return all_radio_buttons;
constexpr bool kTraverseForward = true;
@@ -1366,7 +1366,7 @@ RGBA32 AXNodeObject::ColorValue() const {
return AXObject::ColorValue();
HTMLInputElement* input = ToHTMLInputElement(GetNode());
- const AtomicString& type = input->getAttribute(typeAttr);
+ const AtomicString& type = input->getAttribute(kTypeAttr);
if (!EqualIgnoringASCIICase(type, "color"))
return AXObject::ColorValue();
@@ -1692,7 +1692,7 @@ String AXNodeObject::StringValue() const {
if (selected_index >= 0 &&
static_cast<wtf_size_t>(selected_index) < list_items.size()) {
const AtomicString& overridden_description =
- list_items[selected_index]->FastGetAttribute(aria_labelAttr);
+ list_items[selected_index]->FastGetAttribute(kAriaLabelAttr);
if (!overridden_description.IsNull())
return overridden_description;
}
@@ -1710,12 +1710,12 @@ String AXNodeObject::StringValue() const {
// buttons which will return their name.
// https://html.spec.whatwg.org/multipage/forms.html#dom-input-value
if (const auto* input = ToHTMLInputElementOrNull(node)) {
- if (input->type() != InputTypeNames::button &&
- input->type() != InputTypeNames::checkbox &&
- input->type() != InputTypeNames::image &&
- input->type() != InputTypeNames::radio &&
- input->type() != InputTypeNames::reset &&
- input->type() != InputTypeNames::submit) {
+ if (input->type() != input_type_names::kButton &&
+ input->type() != input_type_names::kCheckbox &&
+ input->type() != input_type_names::kImage &&
+ input->type() != input_type_names::kRadio &&
+ input->type() != input_type_names::kReset &&
+ input->type() != input_type_names::kSubmit) {
return input->value();
}
}
@@ -1871,10 +1871,10 @@ String AXNodeObject::TextAlternative(bool recursive,
// Step 2H from: http://www.w3.org/TR/accname-aam-1.1
name_from = ax::mojom::NameFrom::kTitle;
if (name_sources) {
- name_sources->push_back(NameSource(found_text_alternative, titleAttr));
+ name_sources->push_back(NameSource(found_text_alternative, kTitleAttr));
name_sources->back().type = name_from;
}
- const AtomicString& title = GetAttribute(titleAttr);
+ const AtomicString& title = GetAttribute(kTitleAttr);
if (!title.IsEmpty()) {
text_alternative = title;
name_from = ax::mojom::NameFrom::kTitle;
@@ -1976,17 +1976,24 @@ String AXNodeObject::TextFromDescendants(AXObjectSet& visited,
children.push_back(owned_child);
for (AXObject* child : children) {
+ // If a child is a continuation, we should ignore attributes like
+ // hidden and presentational. See LAYOUT TREE WALKING ALGORITHM in
+ // ax_layout_object.cc for more information on continuations.
+ bool is_continuation = child->GetLayoutObject() &&
+ child->GetLayoutObject()->IsElementContinuation();
+
// Don't recurse into children that are explicitly marked as aria-hidden.
// Note that we don't call isInertOrAriaHidden because that would return
// true if any ancestor is hidden, but we need to be able to compute the
// accessible name of object inside hidden subtrees (for example, if
// aria-labelledby points to an object that's hidden).
- if (child->AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kHidden))
+ if (!is_continuation &&
+ child->AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kHidden))
continue;
ax::mojom::NameFrom child_name_from = ax::mojom::NameFrom::kUninitialized;
String result;
- if (child->IsPresentational()) {
+ if (!is_continuation && child->IsPresentational()) {
result = child->TextFromDescendants(visited, true);
} else {
result =
@@ -2446,7 +2453,7 @@ bool AXNodeObject::OnNativeFocusAction() {
// using AOM. To be extra safe, exclude objects that are clickable themselves.
// This won't prevent anyone from having a click handler on the object's
// container.
- if (!IsClickable() && element->FastHasAttribute(idAttr) &&
+ if (!IsClickable() && element->FastHasAttribute(kIdAttr) &&
CanBeActiveDescendant()) {
return OnNativeClickAction();
}
@@ -2552,7 +2559,9 @@ void AXNodeObject::SelectedOptions(AXObjectVector& options) const {
if (IsHTMLSelectElement(GetNode())) {
HTMLSelectElement* select = ToHTMLSelectElement(GetNode());
for (auto* const option : *select->selectedOptions()) {
- options.push_back(AXObjectCache().GetOrCreate(option));
+ AXObject* ax_option = AXObjectCache().GetOrCreate(option);
+ if (ax_option)
+ options.push_back(ax_option);
}
return;
}
@@ -2641,11 +2650,11 @@ void AXNodeObject::ComputeAriaOwnsChildren(
return;
}
- if (!HasAttribute(aria_ownsAttr))
+ if (!HasAttribute(kAriaOwnsAttr))
return;
// Case 3: aria-owns attribute
- TokenVectorFromAttribute(id_vector, aria_ownsAttr);
+ TokenVectorFromAttribute(id_vector, kAriaOwnsAttr);
AXObjectCache().UpdateAriaOwns(this, id_vector, owned_children);
}
@@ -2691,8 +2700,8 @@ String AXNodeObject::NativeTextAlternative(
++label_index) {
Element* label = labels->item(label_index);
if (name_sources) {
- if (!label->getAttribute(forAttr).IsEmpty() &&
- label->getAttribute(forAttr) == html_element->GetIdAttribute()) {
+ if (!label->getAttribute(kForAttr).IsEmpty() &&
+ label->getAttribute(kForAttr) == html_element->GetIdAttribute()) {
name_sources->back().native_source = kAXTextFromNativeHTMLLabelFor;
} else {
name_sources->back().native_source =
@@ -2724,7 +2733,7 @@ String AXNodeObject::NativeTextAlternative(
// value attribue
name_from = ax::mojom::NameFrom::kValue;
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, valueAttr));
+ name_sources->push_back(NameSource(*found_text_alternative, kValueAttr));
name_sources->back().type = name_from;
}
String value = input_element->value();
@@ -2765,14 +2774,14 @@ String AXNodeObject::NativeTextAlternative(
// 5.3 input type="image"
if (input_element &&
- input_element->getAttribute(typeAttr) == InputTypeNames::image) {
+ input_element->getAttribute(kTypeAttr) == input_type_names::kImage) {
// alt attr
- const AtomicString& alt = input_element->getAttribute(altAttr);
+ const AtomicString& alt = input_element->getAttribute(kAltAttr);
const bool is_empty = alt.IsEmpty() && !alt.IsNull();
name_from = is_empty ? ax::mojom::NameFrom::kAttributeExplicitlyEmpty
: ax::mojom::NameFrom::kAttribute;
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, altAttr));
+ name_sources->push_back(NameSource(*found_text_alternative, kAltAttr));
name_sources->back().type = name_from;
}
if (!alt.IsNull()) {
@@ -2789,7 +2798,7 @@ String AXNodeObject::NativeTextAlternative(
// value attr
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, valueAttr));
+ name_sources->push_back(NameSource(*found_text_alternative, kValueAttr));
name_sources->back().type = name_from;
}
name_from = ax::mojom::NameFrom::kAttribute;
@@ -2807,11 +2816,11 @@ String AXNodeObject::NativeTextAlternative(
// title attr
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, titleAttr));
+ name_sources->push_back(NameSource(*found_text_alternative, kTitleAttr));
name_sources->back().type = name_from;
}
name_from = ax::mojom::NameFrom::kTitle;
- const AtomicString& title = input_element->getAttribute(titleAttr);
+ const AtomicString& title = input_element->getAttribute(kTitleAttr);
if (!title.IsNull()) {
text_alternative = title;
if (name_sources) {
@@ -2829,9 +2838,9 @@ String AXNodeObject::NativeTextAlternative(
text_alternative = input_element->GetLocale().QueryString(
WebLocalizedString::kSubmitButtonDefaultLabel);
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, typeAttr));
+ name_sources->push_back(NameSource(*found_text_alternative, kTypeAttr));
NameSource& source = name_sources->back();
- source.attribute_value = input_element->getAttribute(typeAttr);
+ source.attribute_value = input_element->getAttribute(kTypeAttr);
source.type = name_from;
source.text = text_alternative;
*found_text_alternative = true;
@@ -2846,7 +2855,7 @@ String AXNodeObject::NativeTextAlternative(
name_from = ax::mojom::NameFrom::kPlaceholder;
if (name_sources) {
name_sources->push_back(
- NameSource(*found_text_alternative, placeholderAttr));
+ NameSource(*found_text_alternative, kPlaceholderAttr));
NameSource& source = name_sources->back();
source.type = name_from;
}
@@ -2857,7 +2866,7 @@ String AXNodeObject::NativeTextAlternative(
NameSource& source = name_sources->back();
source.text = text_alternative;
source.attribute_value =
- html_element->FastGetAttribute(placeholderAttr);
+ html_element->FastGetAttribute(kPlaceholderAttr);
*found_text_alternative = true;
} else {
return text_alternative;
@@ -2870,7 +2879,7 @@ String AXNodeObject::NativeTextAlternative(
name_from = ax::mojom::NameFrom::kPlaceholder;
if (name_sources) {
name_sources->push_back(
- NameSource(*found_text_alternative, aria_placeholderAttr));
+ NameSource(*found_text_alternative, kAriaPlaceholderAttr));
NameSource& source = name_sources->back();
source.type = name_from;
}
@@ -2892,7 +2901,7 @@ String AXNodeObject::NativeTextAlternative(
}
// 5.7 figure and figcaption Elements
- if (GetNode()->HasTagName(figureTag)) {
+ if (GetNode()->HasTagName(kFigureTag)) {
// figcaption
name_from = ax::mojom::NameFrom::kRelatedElement;
if (name_sources) {
@@ -2902,7 +2911,7 @@ String AXNodeObject::NativeTextAlternative(
}
Element* figcaption = nullptr;
for (Element& element : ElementTraversal::DescendantsOf(*(GetNode()))) {
- if (element.HasTagName(figcaptionTag)) {
+ if (element.HasTagName(kFigcaptionTag)) {
figcaption = &element;
break;
}
@@ -2914,8 +2923,9 @@ String AXNodeObject::NativeTextAlternative(
RecursiveTextAlternative(*figcaption_ax_object, false, visited);
if (related_objects) {
- local_related_objects.push_back(new NameSourceRelatedObject(
- figcaption_ax_object, text_alternative));
+ local_related_objects.push_back(
+ MakeGarbageCollected<NameSourceRelatedObject>(
+ figcaption_ax_object, text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
@@ -2937,12 +2947,12 @@ String AXNodeObject::NativeTextAlternative(
if (IsHTMLImageElement(GetNode()) || IsHTMLAreaElement(GetNode()) ||
(GetLayoutObject() && GetLayoutObject()->IsSVGImage())) {
// alt
- const AtomicString& alt = GetAttribute(altAttr);
+ const AtomicString& alt = GetAttribute(kAltAttr);
const bool is_empty = alt.IsEmpty() && !alt.IsNull();
name_from = is_empty ? ax::mojom::NameFrom::kAttributeExplicitlyEmpty
: ax::mojom::NameFrom::kAttribute;
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, altAttr));
+ name_sources->push_back(NameSource(*found_text_alternative, kAltAttr));
name_sources->back().type = name_from;
}
if (!alt.IsNull()) {
@@ -2976,7 +2986,8 @@ String AXNodeObject::NativeTextAlternative(
RecursiveTextAlternative(*caption_ax_object, false, visited);
if (related_objects) {
local_related_objects.push_back(
- new NameSourceRelatedObject(caption_ax_object, text_alternative));
+ MakeGarbageCollected<NameSourceRelatedObject>(caption_ax_object,
+ text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
@@ -2995,10 +3006,11 @@ String AXNodeObject::NativeTextAlternative(
// summary
name_from = ax::mojom::NameFrom::kAttribute;
if (name_sources) {
- name_sources->push_back(NameSource(*found_text_alternative, summaryAttr));
+ name_sources->push_back(
+ NameSource(*found_text_alternative, kSummaryAttr));
name_sources->back().type = name_from;
}
- const AtomicString& summary = GetAttribute(summaryAttr);
+ const AtomicString& summary = GetAttribute(kSummaryAttr);
if (!summary.IsNull()) {
text_alternative = summary;
if (name_sources) {
@@ -3024,7 +3036,7 @@ String AXNodeObject::NativeTextAlternative(
}
DCHECK(GetNode()->IsContainerNode());
Element* title = ElementTraversal::FirstChild(
- ToContainerNode(*(GetNode())), HasTagName(SVGNames::titleTag));
+ ToContainerNode(*(GetNode())), HasTagName(svg_names::kTitleTag));
if (title) {
AXObject* title_ax_object = AXObjectCache().GetOrCreate(title);
@@ -3033,7 +3045,8 @@ String AXNodeObject::NativeTextAlternative(
RecursiveTextAlternative(*title_ax_object, false, visited);
if (related_objects) {
local_related_objects.push_back(
- new NameSourceRelatedObject(title_ax_object, text_alternative));
+ MakeGarbageCollected<NameSourceRelatedObject>(title_ax_object,
+ text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
@@ -3067,7 +3080,8 @@ String AXNodeObject::NativeTextAlternative(
if (related_objects) {
local_related_objects.push_back(
- new NameSourceRelatedObject(legend_ax_object, text_alternative));
+ MakeGarbageCollected<NameSourceRelatedObject>(legend_ax_object,
+ text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
@@ -3091,7 +3105,7 @@ String AXNodeObject::NativeTextAlternative(
name_from = ax::mojom::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(
- NameSource(found_text_alternative, aria_labelAttr));
+ NameSource(found_text_alternative, kAriaLabelAttr));
name_sources->back().type = name_from;
}
if (Element* document_element = document->documentElement()) {
@@ -3126,7 +3140,8 @@ String AXNodeObject::NativeTextAlternative(
if (title_ax_object) {
if (related_objects) {
local_related_objects.push_back(
- new NameSourceRelatedObject(title_ax_object, text_alternative));
+ MakeGarbageCollected<NameSourceRelatedObject>(title_ax_object,
+ text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
@@ -3198,7 +3213,7 @@ String AXNodeObject::Description(ax::mojom::NameFrom name_from,
description_from = ax::mojom::DescriptionFrom::kRelatedElement;
if (description_sources) {
description_sources->push_back(
- DescriptionSource(found_description, aria_describedbyAttr));
+ DescriptionSource(found_description, kAriaDescribedbyAttr));
description_sources->back().type = description_from;
}
@@ -3226,7 +3241,7 @@ String AXNodeObject::Description(ax::mojom::NameFrom name_from,
// aria-describedby overrides any other accessible description, from:
// http://rawgit.com/w3c/aria/master/html-aam/html-aam.html
- const AtomicString& aria_describedby = GetAttribute(aria_describedbyAttr);
+ const AtomicString& aria_describedby = GetAttribute(kAriaDescribedbyAttr);
if (!aria_describedby.IsNull()) {
if (description_sources)
description_sources->back().attribute_value = aria_describedby;
@@ -3258,7 +3273,7 @@ String AXNodeObject::Description(ax::mojom::NameFrom name_from,
description_from = ax::mojom::DescriptionFrom::kAttribute;
if (description_sources) {
description_sources->push_back(
- DescriptionSource(found_description, valueAttr));
+ DescriptionSource(found_description, kValueAttr));
description_sources->back().type = description_from;
}
String value = input_element->value();
@@ -3294,9 +3309,11 @@ String AXNodeObject::Description(ax::mojom::NameFrom name_from,
AXObjectSet visited;
description =
RecursiveTextAlternative(*caption_ax_object, false, visited);
- if (related_objects)
+ if (related_objects) {
related_objects->push_back(
- new NameSourceRelatedObject(caption_ax_object, description));
+ MakeGarbageCollected<NameSourceRelatedObject>(caption_ax_object,
+ description));
+ }
if (description_sources) {
DescriptionSource& source = description_sources->back();
@@ -3339,10 +3356,10 @@ String AXNodeObject::Description(ax::mojom::NameFrom name_from,
description_from = ax::mojom::DescriptionFrom::kAttribute;
if (description_sources) {
description_sources->push_back(
- DescriptionSource(found_description, titleAttr));
+ DescriptionSource(found_description, kTitleAttr));
description_sources->back().type = description_from;
}
- const AtomicString& title = GetAttribute(titleAttr);
+ const AtomicString& title = GetAttribute(kTitleAttr);
if (!title.IsEmpty()) {
description = title;
if (description_sources) {
@@ -3360,10 +3377,10 @@ String AXNodeObject::Description(ax::mojom::NameFrom name_from,
description_from = ax::mojom::DescriptionFrom::kAttribute;
if (description_sources) {
description_sources->push_back(
- DescriptionSource(found_description, aria_helpAttr));
+ DescriptionSource(found_description, kAriaHelpAttr));
description_sources->back().type = description_from;
}
- const AtomicString& help = GetAttribute(aria_helpAttr);
+ const AtomicString& help = GetAttribute(kAriaHelpAttr);
if (!help.IsEmpty()) {
description = help;
if (description_sources) {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.h
index 400c2b91aa1..b3768b6c445 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_node_object.h
@@ -41,11 +41,9 @@ class HTMLLabelElement;
class Node;
class MODULES_EXPORT AXNodeObject : public AXObject {
- protected:
- AXNodeObject(Node*, AXObjectCacheImpl&);
-
public:
static AXNodeObject* Create(Node*, AXObjectCacheImpl&);
+ AXNodeObject(Node*, AXObjectCacheImpl&);
~AXNodeObject() override;
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_object.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_object.cc
index 25aaa69a578..74d530e7748 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_object.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -68,7 +68,7 @@ using blink::WebLocalizedString;
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -440,16 +440,17 @@ static ARIARoleMap* CreateARIARoleMap() {
static Vector<AtomicString>* CreateRoleNameVector() {
Vector<AtomicString>* role_name_vector =
new Vector<AtomicString>(base::size(kInternalRoles));
- for (size_t i = 0; i < base::size(kInternalRoles); i++)
+ for (wtf_size_t i = 0; i < base::size(kInternalRoles); i++)
(*role_name_vector)[i] = g_null_atom;
- for (size_t i = 0; i < base::size(kRoles); ++i) {
- (*role_name_vector)[static_cast<size_t>(kRoles[i].webcore_role)] =
+ for (wtf_size_t i = 0; i < base::size(kRoles); ++i) {
+ (*role_name_vector)[static_cast<wtf_size_t>(kRoles[i].webcore_role)] =
AtomicString(kRoles[i].aria_role);
}
- for (size_t i = 0; i < base::size(kReverseRoles); ++i) {
- (*role_name_vector)[static_cast<size_t>(kReverseRoles[i].webcore_role)] =
+ for (wtf_size_t i = 0; i < base::size(kReverseRoles); ++i) {
+ (*role_name_vector)[static_cast<wtf_size_t>(
+ kReverseRoles[i].webcore_role)] =
AtomicString(kReverseRoles[i].aria_role);
}
@@ -459,8 +460,8 @@ static Vector<AtomicString>* CreateRoleNameVector() {
static Vector<AtomicString>* CreateInternalRoleNameVector() {
Vector<AtomicString>* internal_role_name_vector =
new Vector<AtomicString>(base::size(kInternalRoles));
- for (size_t i = 0; i < base::size(kInternalRoles); i++) {
- (*internal_role_name_vector)[static_cast<size_t>(
+ for (wtf_size_t i = 0; i < base::size(kInternalRoles); i++) {
+ (*internal_role_name_vector)[static_cast<wtf_size_t>(
kInternalRoles[i].webcore_role)] =
AtomicString(kInternalRoles[i].internal_role_name);
}
@@ -756,7 +757,7 @@ bool AXObject::IsNativeCheckboxInMixedState(const Node* node) {
const HTMLInputElement* input = ToHTMLInputElement(node);
const auto inputType = input->type();
- if (inputType != InputTypeNames::checkbox)
+ if (inputType != input_type_names::kCheckbox)
return false;
return input->ShouldAppearIndeterminate();
}
@@ -938,9 +939,14 @@ AXObjectInclusion AXObject::AccessibilityPlatformIncludesObject() const {
AXObjectInclusion AXObject::DefaultObjectInclusion(
IgnoredReasons* ignored_reasons) const {
if (IsInertOrAriaHidden()) {
- if (ignored_reasons)
- ComputeIsInertOrAriaHidden(ignored_reasons);
- return kIgnoreObject;
+ // Keep focusable elements that are aria-hidden in tree, so that they can
+ // still fire events such as focus and value changes.
+ const Element* elem = GetElement();
+ if (!elem || !elem->SupportsFocus() || elem->IsInert()) {
+ if (ignored_reasons)
+ ComputeIsInertOrAriaHidden(ignored_reasons);
+ return kIgnoreObject;
+ }
}
return AccessibilityPlatformIncludesObject();
@@ -1002,6 +1008,10 @@ bool AXObject::ComputeIsInertOrAriaHidden(
return false;
}
+bool AXObject::IsVisible() const {
+ return !IsInertOrAriaHidden();
+}
+
bool AXObject::IsDescendantOfLeafNode() const {
UpdateCachedAttributeValuesIfNeeded();
return cached_is_descendant_of_leaf_node_;
@@ -1039,7 +1049,7 @@ const AXObject* AXObject::InertRoot() const {
? ToElement(node)
: FlatTreeTraversal::ParentElement(*node);
while (element) {
- if (element->hasAttribute(inertAttr))
+ if (element->hasAttribute(kInertAttr))
return AXObjectCache().GetOrCreate(element);
element = FlatTreeTraversal::ParentElement(*element);
}
@@ -1086,10 +1096,11 @@ bool AXObject::DispatchEventToAOMEventListeners(Event& event) {
// that if it didn't previously exist it won't be part of the event path.
AccessibleNode* target = GetAccessibleNode();
if (!target) {
- Element* element = GetElement();
- if (element)
+ if (Element* element = GetElement())
target = element->accessibleNode();
}
+ if (!target)
+ return false;
event.SetTarget(target);
// Capturing phase.
@@ -1197,7 +1208,7 @@ bool AXObject::CanReceiveAccessibilityFocus() const {
return true;
// aria-activedescendant focus
- return elem->FastHasAttribute(idAttr) && CanBeActiveDescendant();
+ return elem->FastHasAttribute(kIdAttr) && CanBeActiveDescendant();
}
bool AXObject::CanSetValueAttribute() const {
@@ -1516,7 +1527,7 @@ String AXObject::AriaTextAlternative(bool recursive,
if (HasAOMProperty(AOMRelationListProperty::kLabeledBy, elements)) {
if (name_sources) {
name_sources->push_back(
- NameSource(*found_text_alternative, aria_labelledbyAttr));
+ NameSource(*found_text_alternative, kAriaLabelledbyAttr));
name_sources->back().type = name_from;
}
@@ -1543,9 +1554,9 @@ String AXObject::AriaTextAlternative(bool recursive,
} else {
// Now check ARIA attribute
const QualifiedName& attr =
- HasAttribute(aria_labeledbyAttr) && !HasAttribute(aria_labelledbyAttr)
- ? aria_labeledbyAttr
- : aria_labelledbyAttr;
+ HasAttribute(kAriaLabeledbyAttr) && !HasAttribute(kAriaLabelledbyAttr)
+ ? kAriaLabeledbyAttr
+ : kAriaLabelledbyAttr;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, attr));
@@ -1589,7 +1600,7 @@ String AXObject::AriaTextAlternative(bool recursive,
name_from = ax::mojom::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(
- NameSource(*found_text_alternative, aria_labelAttr));
+ NameSource(*found_text_alternative, kAriaLabelAttr));
name_sources->back().type = name_from;
}
const AtomicString& aria_label =
@@ -1628,7 +1639,7 @@ String AXObject::TextFromElements(
String result = RecursiveTextAlternative(
*ax_element, in_aria_labelledby_traversal, visited);
local_related_objects.push_back(
- new NameSourceRelatedObject(ax_element, result));
+ MakeGarbageCollected<NameSourceRelatedObject>(ax_element, result));
if (!result.IsEmpty()) {
if (!accumulated_text.IsEmpty())
accumulated_text.Append(' ');
@@ -1675,9 +1686,9 @@ void AXObject::AriaLabelledbyElementVector(
HeapVector<Member<Element>>& elements,
Vector<String>& ids) const {
// Try both spellings, but prefer aria-labelledby, which is the official spec.
- ElementsFromAttribute(elements, aria_labelledbyAttr, ids);
+ ElementsFromAttribute(elements, kAriaLabelledbyAttr, ids);
if (!ids.size())
- ElementsFromAttribute(elements, aria_labeledbyAttr, ids);
+ ElementsFromAttribute(elements, kAriaLabeledbyAttr, ids);
}
String AXObject::TextFromAriaLabelledby(AXObjectSet& visited,
@@ -1692,7 +1703,7 @@ String AXObject::TextFromAriaDescribedby(AXRelatedObjectVector* related_objects,
Vector<String>& ids) const {
AXObjectSet visited;
HeapVector<Member<Element>> elements;
- ElementsFromAttribute(elements, aria_describedbyAttr, ids);
+ ElementsFromAttribute(elements, kAriaDescribedbyAttr, ids);
return TextFromElements(true, visited, elements, related_objects);
}
@@ -1896,7 +1907,7 @@ int AXObject::IndexInParent() const {
return 0;
const AXObjectVector& siblings = ParentObjectUnignored()->Children();
- size_t index = siblings.Find(this);
+ wtf_size_t index = siblings.Find(this);
return (index == kNotFound) ? 0 : static_cast<int>(index);
}
@@ -2338,7 +2349,7 @@ AtomicString AXObject::Language() const {
// 2. The list of languages the browser sends in the [Accept-Language] header.
// 3. The browser's default language.
- const AtomicString& lang = GetAttribute(langAttr);
+ const AtomicString& lang = GetAttribute(kLangAttr);
if (!lang.IsEmpty())
return lang;
@@ -2893,7 +2904,8 @@ LayoutRect AXObject::GetBoundsInFrameCoordinates() const {
//
bool AXObject::RequestDecrementAction() {
- Event* event = Event::CreateCancelable(EventTypeNames::accessibledecrement);
+ Event* event =
+ Event::CreateCancelable(event_type_names::kAccessibledecrement);
if (DispatchEventToAOMEventListeners(*event))
return true;
@@ -2901,7 +2913,7 @@ bool AXObject::RequestDecrementAction() {
}
bool AXObject::RequestClickAction() {
- Event* event = Event::CreateCancelable(EventTypeNames::accessibleclick);
+ Event* event = Event::CreateCancelable(event_type_names::kAccessibleclick);
if (DispatchEventToAOMEventListeners(*event))
return true;
@@ -2933,7 +2945,7 @@ bool AXObject::OnNativeClickAction() {
}
bool AXObject::RequestFocusAction() {
- Event* event = Event::CreateCancelable(EventTypeNames::accessiblefocus);
+ Event* event = Event::CreateCancelable(event_type_names::kAccessiblefocus);
if (DispatchEventToAOMEventListeners(*event))
return true;
@@ -2941,7 +2953,8 @@ bool AXObject::RequestFocusAction() {
}
bool AXObject::RequestIncrementAction() {
- Event* event = Event::CreateCancelable(EventTypeNames::accessibleincrement);
+ Event* event =
+ Event::CreateCancelable(event_type_names::kAccessibleincrement);
if (DispatchEventToAOMEventListeners(*event))
return true;
@@ -2954,7 +2967,7 @@ bool AXObject::RequestScrollToGlobalPointAction(const IntPoint& point) {
bool AXObject::RequestScrollToMakeVisibleAction() {
Event* event =
- Event::CreateCancelable(EventTypeNames::accessiblescrollintoview);
+ Event::CreateCancelable(event_type_names::kAccessiblescrollintoview);
if (DispatchEventToAOMEventListeners(*event))
return true;
@@ -2983,7 +2996,8 @@ bool AXObject::RequestSetValueAction(const String& value) {
}
bool AXObject::RequestShowContextMenuAction() {
- Event* event = Event::CreateCancelable(EventTypeNames::accessiblecontextmenu);
+ Event* event =
+ Event::CreateCancelable(event_type_names::kAccessiblecontextmenu);
if (DispatchEventToAOMEventListeners(*event))
return true;
@@ -3450,7 +3464,7 @@ ax::mojom::Role AXObject::ButtonRoleType() const {
const AtomicString& AXObject::RoleName(ax::mojom::Role role) {
static const Vector<AtomicString>* role_name_vector = CreateRoleNameVector();
- return role_name_vector->at(static_cast<size_t>(role));
+ return role_name_vector->at(static_cast<wtf_size_t>(role));
}
// static
@@ -3458,7 +3472,7 @@ const AtomicString& AXObject::InternalRoleName(ax::mojom::Role role) {
static const Vector<AtomicString>* internal_role_name_vector =
CreateInternalRoleNameVector();
- return internal_role_name_vector->at(static_cast<size_t>(role));
+ return internal_role_name_vector->at(static_cast<wtf_size_t>(role));
}
// static
@@ -3503,6 +3517,13 @@ const AXObject* AXObject::LowestCommonAncestor(const AXObject& first,
return common_ancestor;
}
+String AXObject::ToString() const {
+ return AXObject::InternalRoleName(RoleValue())
+ .GetString()
+ .EncodeForDebugging() +
+ ": " + ComputedName().EncodeForDebugging();
+}
+
VisiblePosition AXObject::VisiblePositionForIndex(int) const {
return VisiblePosition();
}
@@ -3558,8 +3579,7 @@ bool operator>=(const AXObject& first, const AXObject& second) {
}
std::ostream& operator<<(std::ostream& stream, const AXObject& obj) {
- return stream << AXObject::InternalRoleName(obj.RoleValue()) << ": "
- << obj.ComputedName();
+ return stream << obj.ToString().Utf8().data();
}
void AXObject::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_object.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_object.h
index 34a1c79bd49..88cb1e84c82 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_object.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -49,6 +49,7 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "ui/accessibility/ax_enums.mojom-blink.h"
@@ -472,6 +473,7 @@ class MODULES_EXPORT AXObject : public GarbageCollectedFinalized<AXObject> {
return RoleValue() == ax::mojom::Role::kColorWell;
}
virtual bool IsControl() const { return false; }
+ virtual bool IsDefault() const { return false; }
virtual bool IsEmbeddedObject() const { return false; }
virtual bool IsFieldset() const { return false; }
virtual bool IsHeading() const { return false; }
@@ -551,7 +553,7 @@ class MODULES_EXPORT AXObject : public GarbageCollectedFinalized<AXObject> {
// Is the object selected because selection is following focus?
virtual bool IsSelectedFromFocus() const { return false; }
virtual bool IsSelectedOptionActive() const { return false; }
- virtual bool IsVisible() const { return true; }
+ virtual bool IsVisible() const;
virtual bool IsVisited() const { return false; }
// Check whether certain properties can be modified.
@@ -685,7 +687,10 @@ class MODULES_EXPORT AXObject : public GarbageCollectedFinalized<AXObject> {
return ax::mojom::TextPosition::kNone;
}
virtual int TextLength() const { return 0; }
- virtual TextStyle GetTextStyle() const { return kTextStyleNone; }
+
+ // Bitmask from ax::mojom::TextStyle.
+ virtual int32_t GetTextStyle() const { return 0; }
+
virtual AXObjectVector RadioButtonsInGroup() const {
return AXObjectVector();
}
@@ -1004,6 +1009,9 @@ class MODULES_EXPORT AXObject : public GarbageCollectedFinalized<AXObject> {
int* index_in_ancestor1,
int* index_in_ancestor2);
+ // Returns a string representation of this object.
+ String ToString() const;
+
protected:
AXID id_;
AXObjectVector children_;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
index 1f7c45f7ce8..a2b707ddda3 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -86,11 +86,11 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
// static
AXObjectCache* AXObjectCacheImpl::Create(Document& document) {
- return new AXObjectCacheImpl(document);
+ return MakeGarbageCollected<AXObjectCacheImpl>(document);
}
AXObjectCacheImpl::AXObjectCacheImpl(Document& document)
@@ -295,7 +295,7 @@ static bool NodeHasRole(Node* node, const String& role) {
return false;
// TODO(accessibility) support role strings with multiple roles.
- return EqualIgnoringASCIICase(ToElement(node)->getAttribute(roleAttr), role);
+ return EqualIgnoringASCIICase(ToElement(node)->getAttribute(kRoleAttr), role);
}
AXObject* AXObjectCacheImpl::CreateFromRenderer(LayoutObject* layout_object) {
@@ -318,7 +318,7 @@ AXObject* AXObjectCacheImpl::CreateFromRenderer(LayoutObject* layout_object) {
return AXListBoxOption::Create(layout_object, *this);
if (IsHTMLInputElement(node) &&
- ToHTMLInputElement(node)->type() == InputTypeNames::radio)
+ ToHTMLInputElement(node)->type() == input_type_names::kRadio)
return AXRadioInput::Create(layout_object, *this);
if (layout_object->IsSVGRoot())
@@ -362,7 +362,8 @@ AXObject* AXObjectCacheImpl::GetOrCreate(AccessibleNode* accessible_node) {
if (AXObject* obj = Get(accessible_node))
return obj;
- AXObject* new_obj = new AXVirtualObject(*this, accessible_node);
+ AXObject* new_obj =
+ MakeGarbageCollected<AXVirtualObject>(*this, accessible_node);
const AXID ax_id = GetOrCreateAXID(new_obj);
accessible_node_mapping_.Set(accessible_node, ax_id);
@@ -680,6 +681,22 @@ void AXObjectCacheImpl::TextChanged(AXObject* obj,
PostNotification(obj, ax::mojom::Event::kTextChanged);
}
+void AXObjectCacheImpl::FocusableChanged(Element* element) {
+ AXObject* obj = GetOrCreate(element);
+ if (!obj)
+ return;
+
+ if (obj->AriaHiddenRoot()) {
+ // Elements that are hidden but focusable are not ignored. Therefore, if a
+ // hidden element's focusable state changes, it's ignored state must be
+ // recomputed.
+ ChildrenChanged(element->parentNode());
+ } else {
+ // Refresh the focusable state on the exposed object.
+ MarkAXObjectDirty(obj, false);
+ }
+}
+
void AXObjectCacheImpl::DocumentTitleChanged() {
PostNotification(Root(), ax::mojom::Event::kDocumentTitleChanged);
}
@@ -717,20 +734,22 @@ void AXObjectCacheImpl::ChildrenChanged(Node* node) {
ChildrenChanged(Get(node), node);
}
-void AXObjectCacheImpl::ChildrenChanged(LayoutObject* layout_object) {
+// Return a node for the current layout object or ancestor layout object.
+Node* GetClosestNodeForLayoutObject(LayoutObject* layout_object) {
if (!layout_object)
- return;
+ return nullptr;
Node* node = layout_object->GetNode();
- LayoutObject* parent = layout_object->Parent();
- while (!node && parent) {
- node = layout_object->GetNode();
- parent = parent->Parent();
- }
+ return node ? node : GetClosestNodeForLayoutObject(layout_object->Parent());
+}
- if (!node)
+void AXObjectCacheImpl::ChildrenChanged(LayoutObject* layout_object) {
+ if (!layout_object)
return;
- if (node->GetDocument().NeedsLayoutTreeUpdateForNode(*node)) {
+ Node* node = GetClosestNodeForLayoutObject(layout_object);
+
+ if (node && (node->GetDocument().NeedsLayoutTreeUpdateForNode(*node) ||
+ node->NeedsDistributionRecalc())) {
nodes_changed_during_layout_.push_back(node);
return;
}
@@ -744,7 +763,8 @@ void AXObjectCacheImpl::ChildrenChanged(AccessibleNode* accessible_node) {
return;
Element* element = accessible_node->element();
if (element &&
- element->GetDocument().NeedsLayoutTreeUpdateForNode(*element)) {
+ (element->GetDocument().NeedsLayoutTreeUpdateForNode(*element) ||
+ element->NeedsDistributionRecalc())) {
nodes_changed_during_layout_.push_back(element);
return;
}
@@ -765,16 +785,28 @@ void AXObjectCacheImpl::ChildrenChanged(AXObject* obj, Node* optional_node) {
void AXObjectCacheImpl::ProcessUpdatesAfterLayout(Document& document) {
if (document.Lifecycle().GetState() < DocumentLifecycle::kLayoutClean)
return;
-
- HeapVector<Member<Node>> remaining_nodes;
- for (auto node : nodes_changed_during_layout_) {
+ VectorOf<Node> old_nodes_changed_during_layout;
+ nodes_changed_during_layout_.swap(old_nodes_changed_during_layout);
+ for (auto node : old_nodes_changed_during_layout) {
if (node->GetDocument() != document) {
- remaining_nodes.push_back(node);
+ nodes_changed_during_layout_.push_back(node);
continue;
}
ChildrenChanged(Get(node), node);
}
- nodes_changed_during_layout_.swap(remaining_nodes);
+
+ AttributesChangedVector old_attributes_changed_during_layout;
+ attributes_changed_during_layout_.swap(old_attributes_changed_during_layout);
+ for (auto pair : old_attributes_changed_during_layout) {
+ auto attribute_name = pair.first;
+ auto element = pair.second;
+ if (element->GetDocument() != document) {
+ attributes_changed_during_layout_.push_back(
+ std::make_pair(attribute_name, element));
+ continue;
+ }
+ HandleAttributeChanged(attribute_name, element);
+ }
}
void AXObjectCacheImpl::NotificationPostTimerFired(TimerBase*) {
@@ -911,7 +943,7 @@ void AXObjectCacheImpl::HandleLayoutComplete(LayoutObject* layout_object) {
}
void AXObjectCacheImpl::HandleClicked(Node* node) {
- if (AXObject* obj = GetOrCreate(node))
+ if (AXObject* obj = Get(node))
PostNotification(obj, ax::mojom::Event::kClicked);
}
@@ -979,12 +1011,8 @@ void AXObjectCacheImpl::HandlePossibleRoleChange(Node* node) {
if (!node)
return; // Virtual AOM node.
- AXObject* obj = Get(node);
- if (!obj && IsHTMLSelectElement(node))
- obj = GetOrCreate(node);
-
// Invalidate the current object and make the parent reconsider its children.
- if (obj) {
+ if (AXObject* obj = Get(node)) {
// Save parent for later use.
AXObject* parent = obj->ParentObject();
@@ -1010,40 +1038,54 @@ void AXObjectCacheImpl::HandlePossibleRoleChange(Node* node) {
void AXObjectCacheImpl::HandleAttributeChanged(const QualifiedName& attr_name,
Element* element) {
- if (attr_name == roleAttr || attr_name == typeAttr || attr_name == sizeAttr ||
- attr_name == aria_haspopupAttr)
+ if (!element)
+ return;
+
+ if (element->GetDocument().NeedsLayoutTreeUpdateForNode(*element) ||
+ element->NeedsDistributionRecalc()) {
+ attributes_changed_during_layout_.push_back(
+ std::make_pair(attr_name, element));
+ return;
+ }
+
+ if (attr_name == kRoleAttr || attr_name == kTypeAttr ||
+ attr_name == kSizeAttr || attr_name == kAriaHaspopupAttr)
HandlePossibleRoleChange(element);
- else if (attr_name == altAttr || attr_name == titleAttr)
+ else if (attr_name == kAltAttr || attr_name == kTitleAttr)
TextChanged(element);
- else if (attr_name == forAttr && IsHTMLLabelElement(*element))
+ else if (attr_name == kForAttr && IsHTMLLabelElement(*element))
LabelChanged(element);
- else if (attr_name == idAttr)
+ else if (attr_name == kIdAttr)
MaybeNewRelationTarget(element, Get(element));
+ else if (attr_name == kTabindexAttr)
+ FocusableChanged(element);
+ else if (attr_name == kDisabledAttr)
+ MarkAXObjectDirty(Get(element), false);
if (!attr_name.LocalName().StartsWith("aria-"))
return;
// Perform updates specific to each attribute.
- if (attr_name == aria_activedescendantAttr)
+ if (attr_name == kAriaActivedescendantAttr)
HandleActiveDescendantChanged(element);
- else if (attr_name == aria_valuenowAttr || attr_name == aria_valuetextAttr)
+ else if (attr_name == kAriaValuenowAttr || attr_name == kAriaValuetextAttr)
PostNotification(element, ax::mojom::Event::kValueChanged);
- else if (attr_name == aria_labelAttr || attr_name == aria_labeledbyAttr ||
- attr_name == aria_labelledbyAttr)
+ else if (attr_name == kAriaLabelAttr || attr_name == kAriaLabeledbyAttr ||
+ attr_name == kAriaLabelledbyAttr)
TextChanged(element);
- else if (attr_name == aria_describedbyAttr)
+ else if (attr_name == kAriaDescribedbyAttr)
TextChanged(element); // TODO do we need a DescriptionChanged() ?
- else if (attr_name == aria_checkedAttr || attr_name == aria_pressedAttr)
+ else if (attr_name == kAriaCheckedAttr || attr_name == kAriaPressedAttr)
CheckedStateChanged(element);
- else if (attr_name == aria_selectedAttr)
+ else if (attr_name == kAriaSelectedAttr)
HandleAriaSelectedChanged(element);
- else if (attr_name == aria_expandedAttr)
+ else if (attr_name == kAriaExpandedAttr)
HandleAriaExpandedChange(element);
- else if (attr_name == aria_hiddenAttr)
+ else if (attr_name == kAriaHiddenAttr)
ChildrenChanged(element->parentNode());
- else if (attr_name == aria_invalidAttr)
+ else if (attr_name == kAriaInvalidAttr)
PostNotification(element, ax::mojom::Event::kInvalidStatusChanged);
- else if (attr_name == aria_ownsAttr)
+ else if (attr_name == kAriaOwnsAttr)
ChildrenChanged(element);
else
PostNotification(element, ax::mojom::Event::kAriaAttributeChanged);
@@ -1402,6 +1444,7 @@ void AXObjectCacheImpl::Trace(blink::Visitor* visitor) {
visitor->Trace(objects_);
visitor->Trace(notifications_to_post_);
visitor->Trace(nodes_changed_during_layout_);
+ visitor->Trace(attributes_changed_during_layout_);
AXObjectCache::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h
index cd015ac7347..9e12cae261f 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h
@@ -97,6 +97,7 @@ class MODULES_EXPORT AXObjectCacheImpl
// changed.
void TextChanged(LayoutObject*) override;
void TextChanged(AXObject*, Node* optional_node = nullptr);
+ void FocusableChanged(Element* element);
void DocumentTitleChanged() override;
// Called when a node has just been attached, so we can make sure we have the
// right subclass of AXObject.
@@ -295,7 +296,9 @@ class MODULES_EXPORT AXObjectCacheImpl
mojom::blink::PermissionServicePtr permission_service_;
mojo::Binding<mojom::blink::PermissionObserver> permission_observer_binding_;
- HeapVector<Member<Node>> nodes_changed_during_layout_;
+ VectorOf<Node> nodes_changed_during_layout_;
+ typedef VectorOfPairs<QualifiedName, Element> AttributesChangedVector;
+ AttributesChangedVector attributes_changed_during_layout_;
DISALLOW_COPY_AND_ASSIGN(AXObjectCacheImpl);
};
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_test.cc
index 11763332dd6..669e007b415 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_cache_test.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h"
namespace blink {
+namespace test {
// TODO(nektar): Break test up into multiple tests.
TEST_F(AccessibilityTest, IsARIAWidget) {
@@ -55,4 +56,5 @@ TEST_F(AccessibilityTest, IsARIAWidget) {
*root->getElementById("focusable-parent")));
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_test.cc
index ed63425c53b..9f433bcadfb 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_object_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_object_test.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h"
namespace blink {
+namespace test {
TEST_F(AccessibilityTest, IsDescendantOf) {
SetBodyInnerHTML(R"HTML(<button id="button">button</button>)HTML");
@@ -164,4 +165,5 @@ TEST_F(AccessibilityTest, AXObjectInOrderTraversalIterator) {
EXPECT_EQ(GetAXObjectCache().InOrderTraversalBegin(), iter);
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_position.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_position.cc
index dd812d09eed..c3d9cafbd5c 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_position.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_position.cc
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/modules/accessibility/ax_layout_object.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -247,8 +248,12 @@ const AXPosition AXPosition::FromPosition(
*document, *node_after_position,
ToContainerNodeOrNull(container_node), adjustment_behavior);
if (previous_child) {
- return CreatePositionAfterObject(*previous_child,
- adjustment_behavior);
+ // |CreatePositionAfterObject| cannot be used here because it will
+ // try to create a position before the object that comes after
+ // |previous_child|, which in this case is the ignored object
+ // itself.
+ return CreateLastPositionInObject(*previous_child,
+ adjustment_behavior);
}
return CreateFirstPositionInObject(*container, adjustment_behavior);
@@ -343,6 +348,15 @@ int AXPosition::MaxTextOffset() const {
return TextIterator::RangeLength(first_position, last_position);
}
+TextAffinity AXPosition::Affinity() const {
+ if (!IsTextPosition()) {
+ NOTREACHED() << *this << " should be a text position.";
+ return TextAffinity::kDownstream;
+ }
+
+ return affinity_;
+}
+
bool AXPosition::IsValid() const {
if (!container_object_ || container_object_->IsDetached())
return false;
@@ -472,10 +486,10 @@ const AXPosition AXPosition::AsUnignoredPosition(
// container's unignored parent.
//
// 3. The container object is ignored and this is an "after children"
- // position. Find the next object in the tree and recurse.
+ // position. Find the previous or the next object in the tree and recurse.
//
// 4. The child after a tree position is ignored, but the container object is
- // not. Return an "after children" position.
+ // not. Return a "before children" or an "after children" position.
const AXObject* container = container_object_;
const AXObject* child = ChildAfterTreePosition();
@@ -521,8 +535,14 @@ const AXPosition AXPosition::AsUnignoredPosition(
}
// Case 4.
- if (child && child->AccessibilityIsIgnored())
- return CreateLastPositionInObject(*container);
+ if (child && child->AccessibilityIsIgnored()) {
+ switch (adjustment_behavior) {
+ case AXPositionAdjustmentBehavior::kMoveRight:
+ return CreateLastPositionInObject(*container);
+ case AXPositionAdjustmentBehavior::kMoveLeft:
+ return CreateFirstPositionInObject(*container);
+ }
+ }
// The position is not ignored.
return *this;
@@ -583,8 +603,8 @@ const AXPosition AXPosition::AsValidDOMPosition(
"node should have an associated layout object.";
const Node* container_node =
ToAXLayoutObject(container)->GetNodeOrContainingBlockNode();
- DCHECK(container_node)
- << "All anonymous layout objects should have a containing block element.";
+ DCHECK(container_node) << "All anonymous layout objects and list markers "
+ "should have a containing block element.";
DCHECK(!container->IsDetached());
auto& ax_object_cache_impl = container->AXObjectCache();
const AXObject* new_container =
@@ -594,7 +614,14 @@ const AXPosition AXPosition::AsValidDOMPosition(
if (new_container == container->ParentObjectUnignored()) {
position.text_offset_or_child_index_ = container->IndexInParent();
} else {
- position.text_offset_or_child_index_ = 0;
+ switch (adjustment_behavior) {
+ case AXPositionAdjustmentBehavior::kMoveRight:
+ position.text_offset_or_child_index_ = new_container->ChildCount();
+ break;
+ case AXPositionAdjustmentBehavior::kMoveLeft:
+ position.text_offset_or_child_index_ = 0;
+ break;
+ }
}
DCHECK(position.IsValid());
return position.AsValidDOMPosition(adjustment_behavior);
@@ -607,7 +634,8 @@ const PositionWithAffinity AXPosition::ToPositionWithAffinity(
return {};
const Node* container_node = adjusted_position.container_object_->GetNode();
- DCHECK(container_node);
+ DCHECK(container_node) << "AX positions that are valid DOM positions should "
+ "always be connected to their DOM nodes.";
if (!adjusted_position.IsTextPosition()) {
// AX positions that are unumbiguously at the start or end of a container,
// should convert to the corresponding DOM positions at the start or end of
@@ -675,6 +703,26 @@ const PositionWithAffinity AXPosition::ToPositionWithAffinity(
return PositionWithAffinity(range.EndPosition(), affinity_);
}
+String AXPosition::ToString() const {
+ if (!IsValid())
+ return "Invalid AXPosition";
+
+ StringBuilder builder;
+ if (IsTextPosition()) {
+ builder.Append("AX text position in ");
+ builder.Append(container_object_->ToString());
+ builder.Append(", ");
+ builder.Append(String::Format("%d", TextOffset()));
+ return builder.ToString();
+ }
+
+ builder.Append("AX object anchored position in ");
+ builder.Append(container_object_->ToString());
+ builder.Append(", ");
+ builder.Append(String::Format("%d", ChildIndex()));
+ return builder.ToString();
+}
+
// static
const AXObject* AXPosition::FindNeighboringUnignoredObject(
const Document& document,
@@ -805,15 +853,7 @@ bool operator>=(const AXPosition& a, const AXPosition& b) {
}
std::ostream& operator<<(std::ostream& ostream, const AXPosition& position) {
- if (!position.IsValid())
- return ostream << "Invalid AXPosition";
- if (position.IsTextPosition()) {
- return ostream << "AX text position in " << *position.ContainerObject()
- << ", " << position.TextOffset();
- }
- return ostream << "AX object anchored position in "
- << *position.ContainerObject() << ", "
- << position.ChildIndex();
+ return ostream << position.ToString().Utf8().data();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_position.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_position.h
index a2447816857..d1861e25862 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_position.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_position.h
@@ -5,15 +5,17 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_POSITION_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_POSITION_H_
-#include <base/logging.h>
#include <stdint.h>
+
#include <ostream>
+#include <base/logging.h>
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/editing/text_affinity.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -107,7 +109,8 @@ class MODULES_EXPORT AXPosition final {
// When the same character offset could correspond to two possible caret
// positions, upstream means it's on the previous line rather than the next
// line.
- TextAffinity Affinity() const { return affinity_; }
+ // Only valid for text positions.
+ TextAffinity Affinity() const;
// Verifies if the anchor is present and if it's set to a live object with a
// connected node.
@@ -145,6 +148,9 @@ class MODULES_EXPORT AXPosition final {
const AXPositionAdjustmentBehavior =
AXPositionAdjustmentBehavior::kMoveLeft) const;
+ // Returns a string representation of this object.
+ String ToString() const;
+
private:
// Only used by static Create... methods.
explicit AXPosition(const AXObject& container);
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_position_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_position_test.cc
index 90d30a05e25..2ebc65a39b8 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_position_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_position_test.cc
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
+namespace test {
namespace {
@@ -872,6 +873,9 @@ TEST_F(AccessibilityTest, FromPositionInARIAHidden) {
ASSERT_NE(nullptr, ax_container);
ASSERT_EQ(ax::mojom::Role::kMain, ax_container->RoleValue());
ASSERT_EQ(2, ax_container->ChildCount());
+ const AXObject* ax_before = GetAXObjectByElementId("before");
+ ASSERT_NE(nullptr, ax_before);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_before->RoleValue());
const AXObject* ax_after = GetAXObjectByElementId("after");
ASSERT_NE(nullptr, ax_after);
ASSERT_EQ(ax::mojom::Role::kParagraph, ax_after->RoleValue());
@@ -884,14 +888,23 @@ TEST_F(AccessibilityTest, FromPositionInARIAHidden) {
const auto positions = {position_first, position_before, position_after};
for (const auto& position : positions) {
+ //
+ // |kMoveLeft| will create "after children" positions that are anchored to
+ // the paragraph before the element that is aria-hidden.
+ //
+ // |kMoveRight| will create positions that are anchored to the paragraph
+ // after the element that is aria-hidden.
+ //
+
const auto ax_position_left =
AXPosition::FromPosition(position, TextAffinity::kDownstream,
AXPositionAdjustmentBehavior::kMoveLeft);
EXPECT_TRUE(ax_position_left.IsValid());
EXPECT_FALSE(ax_position_left.IsTextPosition());
- EXPECT_EQ(ax_container, ax_position_left.ContainerObject());
+ EXPECT_EQ(ax_before, ax_position_left.ContainerObject());
EXPECT_EQ(1, ax_position_left.ChildIndex());
- EXPECT_EQ(ax_after, ax_position_left.ChildAfterTreePosition());
+ // This is an "after children" position.
+ EXPECT_EQ(nullptr, ax_position_left.ChildAfterTreePosition());
const auto ax_position_right =
AXPosition::FromPosition(position, TextAffinity::kDownstream,
@@ -1393,4 +1406,5 @@ TEST_F(AccessibilityTest, DISABLED_PositionInVirtualAOMNode) {
EXPECT_EQ(ax_after, ax_position_after_from_dom.ChildAfterTreePosition());
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.cc
index 3e8c77033fd..3bece0982c3 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.cc
@@ -28,8 +28,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXProgressIndicator::AXProgressIndicator(LayoutProgress* layout_object,
AXObjectCacheImpl& ax_object_cache)
: AXLayoutObject(layout_object, ax_object_cache) {}
@@ -37,7 +35,8 @@ AXProgressIndicator::AXProgressIndicator(LayoutProgress* layout_object,
AXProgressIndicator* AXProgressIndicator::Create(
LayoutProgress* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXProgressIndicator(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXProgressIndicator>(layout_object,
+ ax_object_cache);
}
ax::mojom::Role AXProgressIndicator::DetermineAccessibilityRole() {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.h
index c4e2ab9aaa7..ea8a77967c2 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_progress_indicator.h
@@ -34,6 +34,8 @@ class AXProgressIndicator final : public AXLayoutObject {
public:
static AXProgressIndicator* Create(LayoutProgress*, AXObjectCacheImpl&);
+ AXProgressIndicator(LayoutProgress*, AXObjectCacheImpl&);
+
private:
ax::mojom::Role DetermineAccessibilityRole() final;
@@ -43,8 +45,6 @@ class AXProgressIndicator final : public AXLayoutObject {
bool MaxValueForRange(float* out_value) const override;
bool MinValueForRange(float* out_value) const override;
- AXProgressIndicator(LayoutProgress*, AXObjectCacheImpl&);
-
HTMLProgressElement* GetProgressElement() const;
bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const override;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.cc
index dd1c41a885f..895015bb955 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.cc
@@ -13,8 +13,6 @@
namespace blink {
-using namespace HTMLNames;
-
AXRadioInput::AXRadioInput(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache)
: AXLayoutObject(layout_object, ax_object_cache) {
@@ -28,7 +26,7 @@ AXRadioInput::AXRadioInput(LayoutObject* layout_object,
AXRadioInput* AXRadioInput::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXRadioInput(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXRadioInput>(layout_object, ax_object_cache);
}
void AXRadioInput::UpdatePosAndSetSize(int position) {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.h
index 69d69637356..869e7683492 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_radio_input.h
@@ -16,6 +16,8 @@ class HTMLInputElement;
class AXRadioInput final : public AXLayoutObject {
public:
static AXRadioInput* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXRadioInput(LayoutObject*, AXObjectCacheImpl&);
~AXRadioInput() override = default;
bool IsAXRadioInput() const override { return true; }
@@ -28,7 +30,6 @@ class AXRadioInput final : public AXLayoutObject {
int SetSize() const final;
private:
- AXRadioInput(LayoutObject*, AXObjectCacheImpl&);
bool CalculatePosInSet();
int CountFromFirstElement() const;
HTMLInputElement* GetInputElement() const;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_range.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_range.cc
index 2e71132ef3e..650e566a595 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_range.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_range.cc
@@ -70,6 +70,12 @@ AXRange AXRange::RangeOfContents(const AXObject& container) {
AXPosition::CreateLastPositionInObject(container));
}
+String AXRange::ToString() const {
+ if (!IsValid())
+ return "Invalid AXRange";
+ return "AXRange from " + Start().ToString() + " to " + End().ToString();
+}
+
bool operator==(const AXRange& a, const AXRange& b) {
DCHECK(a.IsValid() && b.IsValid());
return a.Start() == b.Start() && a.End() == b.End();
@@ -80,9 +86,7 @@ bool operator!=(const AXRange& a, const AXRange& b) {
}
std::ostream& operator<<(std::ostream& ostream, const AXRange& range) {
- if (!range.IsValid())
- return ostream << "Invalid AXRange";
- return ostream << "AXRange from " << range.Start() << " to " << range.End();
+ return ostream << range.ToString().Utf8().data();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_range.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_range.h
index a5cb18249e9..b5cd3b71230 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_range.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_range.h
@@ -5,13 +5,15 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_RANGE_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_RANGE_H_
-#include <base/logging.h>
#include <stdint.h>
+
#include <ostream>
+#include <base/logging.h>
#include "third_party/blink/renderer/modules/accessibility/ax_position.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -44,6 +46,9 @@ class MODULES_EXPORT AXRange final {
// Creates an |AXRange| encompassing the contents of the given |AXObject|.
static AXRange RangeOfContents(const AXObject&);
+ // Returns a string representation of this object.
+ String ToString() const;
+
private:
AXPosition start_;
AXPosition end_;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_range_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_range_test.cc
index 25ade2647a9..2fef56e470a 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_range_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_range_test.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h"
namespace blink {
+namespace test {
TEST_F(AccessibilityTest, CommonAncestorContainerOfRange) {
SetBodyInnerHTML(R"HTML(<input id='input' type='text' value='value'>"
@@ -79,4 +80,5 @@ TEST_F(AccessibilityTest, RangeOfContents) {
paragraph_range.End());
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.cc
index f0b89089f9c..71e240e746c 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.cc
@@ -4,8 +4,11 @@
#include "third_party/blink/renderer/modules/accessibility/ax_selection.h"
-#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/dom/node.h"
+#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
+#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/set_selection_options.h"
@@ -15,6 +18,22 @@
namespace blink {
+namespace {
+
+DispatchEventResult DispatchSelectStart(Node* node) {
+ if (!node)
+ return DispatchEventResult::kNotCanceled;
+
+ return node->DispatchEvent(
+ *Event::CreateCancelableBubble(event_type_names::kSelectstart));
+}
+
+} // namespace
+
+//
+// AXSelection::Builder
+//
+
AXSelection::Builder& AXSelection::Builder::SetBase(const AXPosition& base) {
DCHECK(base.IsValid());
selection_.base_ = base;
@@ -71,8 +90,41 @@ const AXSelection AXSelection::Builder::Build() {
return selection_;
}
+//
+// AXSelection
+//
+
// static
-const AXSelection AXSelection::FromSelection(
+void AXSelection::ClearCurrentSelection(Document& document) {
+ LocalFrame* frame = document.GetFrame();
+ if (!frame)
+ return;
+
+ FrameSelection& frame_selection = frame->Selection();
+ if (!frame_selection.IsAvailable())
+ return;
+
+ frame_selection.Clear();
+}
+
+// static
+AXSelection AXSelection::FromCurrentSelection(
+ const Document& document,
+ const AXSelectionBehavior selection_behavior) {
+ LocalFrame* frame = document.GetFrame();
+ if (!frame)
+ return {};
+
+ FrameSelection& frame_selection = frame->Selection();
+ if (!frame_selection.IsAvailable())
+ return {};
+
+ return FromSelection(frame_selection.GetSelectionInDOMTree(),
+ selection_behavior);
+}
+
+// static
+AXSelection AXSelection::FromSelection(
const SelectionInDOMTree& selection,
const AXSelectionBehavior selection_behavior) {
if (selection.IsNone())
@@ -181,30 +233,84 @@ const SelectionInDOMTree AXSelection::AsSelection(
SelectionInDOMTree::Builder selection_builder;
selection_builder.SetBaseAndExtent(dom_base.GetPosition(),
dom_extent.GetPosition());
- selection_builder.SetAffinity(extent_.Affinity());
+ if (extent_.IsTextPosition())
+ selection_builder.SetAffinity(extent_.Affinity());
return selection_builder.Build();
}
-void AXSelection::Select(const AXSelectionBehavior selection_behavior) {
+bool AXSelection::Select(const AXSelectionBehavior selection_behavior) {
if (!IsValid()) {
- NOTREACHED();
- return;
+ NOTREACHED() << "Trying to select an invalid accessibility selection.";
+ return false;
}
const SelectionInDOMTree selection = AsSelection(selection_behavior);
DCHECK(selection.AssertValid());
Document* document = selection.Base().GetDocument();
if (!document) {
- NOTREACHED();
- return;
+ NOTREACHED() << "Valid DOM selections should have an attached document.";
+ return false;
}
+
LocalFrame* frame = document->GetFrame();
if (!frame) {
NOTREACHED();
- return;
+ return false;
}
+
FrameSelection& frame_selection = frame->Selection();
- frame_selection.SetSelection(selection, SetSelectionOptions());
+ if (!frame_selection.IsAvailable())
+ return false;
+
+ // See the following section in the Selection API Specification:
+ // https://w3c.github.io/selection-api/#selectstart-event
+ if (DispatchSelectStart(selection.Extent().ComputeContainerNode()) !=
+ DispatchEventResult::kNotCanceled) {
+ return false;
+ }
+
+ SetSelectionOptions::Builder options_builder;
+ options_builder.SetIsDirectional(true)
+ .SetShouldCloseTyping(true)
+ .SetShouldClearTypingStyle(true)
+ .SetSetSelectionBy(SetSelectionBy::kUser);
+ frame_selection.ClearDocumentCachedRange();
+ frame_selection.SetSelection(selection, options_builder.Build());
+
+ // Cache the newly created document range. This doesn't affect the already
+ // applied selection. Note that DOM's |Range| object has a start and an end
+ // container that need to be in DOM order. See the DOM specification for more
+ // information: https://dom.spec.whatwg.org/#interface-range
+ Range* range = Range::Create(*document);
+ if (selection.Extent().IsNull()) {
+ DCHECK(selection.Base().IsNotNull())
+ << "AX selections converted to DOM selections should have at least one "
+ "endpoint non-null.\n"
+ << *this << '\n'
+ << selection;
+ range->setStart(selection.Base().ComputeContainerNode(),
+ selection.Base().ComputeOffsetInContainerNode());
+ range->setEnd(selection.Base().ComputeContainerNode(),
+ selection.Base().ComputeOffsetInContainerNode());
+ } else if (selection.Base() < selection.Extent()) {
+ range->setStart(selection.Base().ComputeContainerNode(),
+ selection.Base().ComputeOffsetInContainerNode());
+ range->setEnd(selection.Extent().ComputeContainerNode(),
+ selection.Extent().ComputeOffsetInContainerNode());
+ } else {
+ range->setStart(selection.Extent().ComputeContainerNode(),
+ selection.Extent().ComputeOffsetInContainerNode());
+ range->setEnd(selection.Base().ComputeContainerNode(),
+ selection.Base().ComputeOffsetInContainerNode());
+ }
+ frame_selection.CacheRangeOfDocument(range);
+ return true;
+}
+
+String AXSelection::ToString() const {
+ if (!IsValid())
+ return "Invalid AXSelection";
+ return "AXSelection from " + Base().ToString() + " to " + Extent().ToString();
}
bool operator==(const AXSelection& a, const AXSelection& b) {
@@ -217,10 +323,7 @@ bool operator!=(const AXSelection& a, const AXSelection& b) {
}
std::ostream& operator<<(std::ostream& ostream, const AXSelection& selection) {
- if (!selection.IsValid())
- return ostream << "Invalid AXSelection";
- return ostream << "AXSelection from " << selection.Base() << " to "
- << selection.Extent();
+ return ostream << selection.ToString().Utf8().data();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.h
index fbcecc8843c..ca3d8a96f10 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_selection.h
@@ -5,14 +5,17 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_SELECTION_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_AX_SELECTION_H_
-#include <base/logging.h>
#include <stdint.h>
+
#include <ostream>
+#include <base/logging.h>
+#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/modules/accessibility/ax_position.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -20,6 +23,11 @@ namespace blink {
// accessibility tree but not in the DOM tree, determines whether setting the
// selection will shrink or extend the |AXSelection| to encompass endpoints that
// are in the DOM.
+// Conversely, if a DOM selection is converted to an |AXSelection| via the
+// |AsSelection| method, but the endpoints of the DOM selection are not present
+// in the accessibility tree, e.g. they are aria-hidden, determines whether the
+// conversion will shrink or extend the DOM selection to encompass endpoints
+// that are in the accessibility tree.
enum class AXSelectionBehavior {
kShrinkToValidDOMRange,
kExtendToValidDOMRange
@@ -31,7 +39,13 @@ class MODULES_EXPORT AXSelection final {
public:
class Builder;
- static const AXSelection FromSelection(
+ static void ClearCurrentSelection(Document&);
+
+ static AXSelection FromCurrentSelection(
+ const Document&,
+ const AXSelectionBehavior = AXSelectionBehavior::kExtendToValidDOMRange);
+
+ static AXSelection FromSelection(
const SelectionInDOMTree&,
const AXSelectionBehavior = AXSelectionBehavior::kExtendToValidDOMRange);
@@ -52,10 +66,15 @@ class MODULES_EXPORT AXSelection final {
const AXSelectionBehavior =
AXSelectionBehavior::kExtendToValidDOMRange) const;
- // Tries to set the DOM selection to this.
- void Select(
+ // Tries to set the DOM selection to this. Returns |false| if the selection
+ // has been cancelled via the "selectionstart" event or if the selection could
+ // not be set for any other reason.
+ bool Select(
const AXSelectionBehavior = AXSelectionBehavior::kExtendToValidDOMRange);
+ // Returns a string representation of this object.
+ String ToString() const;
+
private:
AXSelection();
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
index bcabc2dc064..3477e1d4159 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
@@ -4,32 +4,204 @@
#include "third_party/blink/renderer/modules/accessibility/ax_selection.h"
+#include <string>
+
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/node.h"
+#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
+#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object.h"
#include "third_party/blink/renderer/modules/accessibility/ax_position.h"
#include "third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
+namespace test {
//
// Basic tests.
//
+TEST_F(AccessibilitySelectionTest, FromCurrentSelection) {
+ GetPage().GetSettings().SetScriptEnabled(true);
+ SetBodyInnerHTML(R"HTML(
+ <p id="paragraph1">Hello.</p>
+ <p id="paragraph2">How are you?</p>
+ )HTML");
+
+ ASSERT_FALSE(AXSelection::FromCurrentSelection(GetDocument()).IsValid());
+
+ Element* const script_element =
+ GetDocument().CreateRawElement(html_names::kScriptTag);
+ ASSERT_NE(nullptr, script_element);
+ script_element->setTextContent(R"SCRIPT(
+ let text1 = document.querySelectorAll('p')[0].firstChild;
+ let paragraph2 = document.querySelectorAll('p')[1];
+ let range = document.createRange();
+ range.setStart(text1, 3);
+ range.setEnd(paragraph2, 1);
+ let selection = getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ )SCRIPT");
+ GetDocument().body()->AppendChild(script_element);
+ UpdateAllLifecyclePhasesForTest();
+
+ const AXObject* ax_static_text_1 =
+ GetAXObjectByElementId("paragraph1")->FirstChild();
+ ASSERT_NE(nullptr, ax_static_text_1);
+ ASSERT_EQ(ax::mojom::Role::kStaticText, ax_static_text_1->RoleValue());
+ const AXObject* ax_paragraph_2 = GetAXObjectByElementId("paragraph2");
+ ASSERT_NE(nullptr, ax_paragraph_2);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_paragraph_2->RoleValue());
+
+ const auto ax_selection = AXSelection::FromCurrentSelection(GetDocument());
+ ASSERT_TRUE(ax_selection.IsValid());
+
+ EXPECT_TRUE(ax_selection.Base().IsTextPosition());
+ EXPECT_EQ(ax_static_text_1, ax_selection.Base().ContainerObject());
+ EXPECT_EQ(3, ax_selection.Base().TextOffset());
+
+ EXPECT_FALSE(ax_selection.Extent().IsTextPosition());
+ EXPECT_EQ(ax_paragraph_2, ax_selection.Extent().ContainerObject());
+ EXPECT_EQ(1, ax_selection.Extent().ChildIndex());
+
+ EXPECT_EQ(
+ "++<Paragraph>\n"
+ "++++<StaticText: Hel^lo.>\n"
+ "++<Paragraph>\n"
+ "++++<StaticText: How are you?>\n|",
+ GetSelectionText(ax_selection));
+}
+
+TEST_F(AccessibilitySelectionTest, ClearCurrentSelection) {
+ GetPage().GetSettings().SetScriptEnabled(true);
+ SetBodyInnerHTML(R"HTML(
+ <p>Hello.</p>
+ <p>How are you?</p>
+ )HTML");
+
+ Element* const script_element =
+ GetDocument().CreateRawElement(html_names::kScriptTag);
+ ASSERT_NE(nullptr, script_element);
+ script_element->setTextContent(R"SCRIPT(
+ let text1 = document.querySelectorAll('p')[0].firstChild;
+ let paragraph2 = document.querySelectorAll('p')[1];
+ let range = document.createRange();
+ range.setStart(text1, 3);
+ range.setEnd(paragraph2, 1);
+ let selection = getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ )SCRIPT");
+ GetDocument().body()->AppendChild(script_element);
+ UpdateAllLifecyclePhasesForTest();
+
+ SelectionInDOMTree selection = Selection().GetSelectionInDOMTree();
+ ASSERT_FALSE(selection.IsNone());
+
+ AXSelection::ClearCurrentSelection(GetDocument());
+ selection = Selection().GetSelectionInDOMTree();
+ EXPECT_TRUE(selection.IsNone());
+
+ const auto ax_selection = AXSelection::FromCurrentSelection(GetDocument());
+ EXPECT_FALSE(ax_selection.IsValid());
+ EXPECT_EQ("", GetSelectionText(ax_selection));
+}
+
+TEST_F(AccessibilitySelectionTest, CancelSelect) {
+ GetPage().GetSettings().SetScriptEnabled(true);
+ SetBodyInnerHTML(R"HTML(
+ <p id="paragraph1">Hello.</p>
+ <p id="paragraph2">How are you?</p>
+ )HTML");
+
+ Element* const script_element =
+ GetDocument().CreateRawElement(html_names::kScriptTag);
+ ASSERT_NE(nullptr, script_element);
+ script_element->setTextContent(R"SCRIPT(
+ document.addEventListener("selectstart", (e) => {
+ e.preventDefault();
+ }, false);
+ )SCRIPT");
+ GetDocument().body()->AppendChild(script_element);
+ UpdateAllLifecyclePhasesForTest();
+
+ const AXObject* ax_static_text_1 =
+ GetAXObjectByElementId("paragraph1")->FirstChild();
+ ASSERT_NE(nullptr, ax_static_text_1);
+ ASSERT_EQ(ax::mojom::Role::kStaticText, ax_static_text_1->RoleValue());
+ const AXObject* ax_paragraph_2 = GetAXObjectByElementId("paragraph2");
+ ASSERT_NE(nullptr, ax_paragraph_2);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_paragraph_2->RoleValue());
+
+ AXSelection::Builder builder;
+ AXSelection ax_selection =
+ builder
+ .SetBase(AXPosition::CreatePositionInTextObject(*ax_static_text_1, 3))
+ .SetExtent(AXPosition::CreateLastPositionInObject(*ax_paragraph_2))
+ .Build();
+
+ EXPECT_FALSE(ax_selection.Select()) << "The operation has been cancelled.";
+ EXPECT_TRUE(Selection().GetSelectionInDOMTree().IsNone());
+ EXPECT_FALSE(AXSelection::FromCurrentSelection(GetDocument()).IsValid());
+
+ GetDocument().RemoveAllEventListeners();
+
+ EXPECT_TRUE(ax_selection.Select()) << "The operation should now go through.";
+ EXPECT_FALSE(Selection().GetSelectionInDOMTree().IsNone());
+ EXPECT_EQ(
+ "++<Paragraph>\n"
+ "++++<StaticText: Hel^lo.>\n"
+ "++<Paragraph>\n"
+ "++++<StaticText: How are you?>\n|",
+ GetSelectionText(AXSelection::FromCurrentSelection(GetDocument())));
+}
+
+TEST_F(AccessibilitySelectionTest, DocumentRangeMatchesSelection) {
+ SetBodyInnerHTML(R"HTML(
+ <p id="paragraph1">Hello.</p>
+ <p id="paragraph2">How are you?</p>
+ )HTML");
+
+ const AXObject* ax_static_text_1 =
+ GetAXObjectByElementId("paragraph1")->FirstChild();
+ ASSERT_NE(nullptr, ax_static_text_1);
+ ASSERT_EQ(ax::mojom::Role::kStaticText, ax_static_text_1->RoleValue());
+ const AXObject* ax_paragraph_2 = GetAXObjectByElementId("paragraph2");
+ ASSERT_NE(nullptr, ax_paragraph_2);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_paragraph_2->RoleValue());
+
+ AXSelection::Builder builder;
+ AXSelection ax_selection =
+ builder
+ .SetBase(AXPosition::CreatePositionInTextObject(*ax_static_text_1, 3))
+ .SetExtent(AXPosition::CreateLastPositionInObject(*ax_paragraph_2))
+ .Build();
+ EXPECT_TRUE(ax_selection.Select());
+ ASSERT_FALSE(Selection().GetSelectionInDOMTree().IsNone());
+ ASSERT_NE(nullptr, Selection().DocumentCachedRange());
+ EXPECT_EQ(String("lo.\n How are you?"),
+ Selection().DocumentCachedRange()->toString());
+}
+
TEST_F(AccessibilitySelectionTest, SetSelectionInText) {
- SetBodyInnerHTML(R"HTML(<p id='paragraph'>Hello</p>)HTML");
+ SetBodyInnerHTML(R"HTML(<p id="paragraph">Hello</p>)HTML");
- const Node* text = GetElementById("paragraph")->firstChild();
+ const Node* text = GetDocument().QuerySelector("p")->firstChild();
ASSERT_NE(nullptr, text);
ASSERT_TRUE(text->IsTextNode());
const AXObject* ax_static_text =
GetAXObjectByElementId("paragraph")->FirstChild();
ASSERT_NE(nullptr, ax_static_text);
+ ASSERT_EQ(ax::mojom::Role::kStaticText, ax_static_text->RoleValue());
const auto ax_base =
AXPosition::CreatePositionInTextObject(*ax_static_text, 3);
@@ -43,20 +215,23 @@ TEST_F(AccessibilitySelectionTest, SetSelectionInText) {
EXPECT_EQ(3, dom_selection.Base().OffsetInContainerNode());
EXPECT_EQ(text, dom_selection.Extent().AnchorNode());
EXPECT_EQ(5, dom_selection.Extent().OffsetInContainerNode());
- EXPECT_EQ("<Paragraph: ><StaticText: Hel^lo|>",
- GetSelectionText(ax_selection));
+ EXPECT_EQ(
+ "++<Paragraph>\n"
+ "++++<StaticText: Hel^lo|>\n",
+ GetSelectionText(ax_selection));
}
TEST_F(AccessibilitySelectionTest, SetSelectionInTextWithWhiteSpace) {
- SetBodyInnerHTML(R"HTML(<p id='paragraph'> Hello</p>)HTML");
+ SetBodyInnerHTML(R"HTML(<p id="paragraph"> Hello</p>)HTML");
- const Node* text = GetElementById("paragraph")->firstChild();
+ const Node* text = GetDocument().QuerySelector("p")->firstChild();
ASSERT_NE(nullptr, text);
ASSERT_TRUE(text->IsTextNode());
const AXObject* ax_static_text =
GetAXObjectByElementId("paragraph")->FirstChild();
ASSERT_NE(nullptr, ax_static_text);
+ ASSERT_EQ(ax::mojom::Role::kStaticText, ax_static_text->RoleValue());
const auto ax_base =
AXPosition::CreatePositionInTextObject(*ax_static_text, 3);
@@ -70,66 +245,207 @@ TEST_F(AccessibilitySelectionTest, SetSelectionInTextWithWhiteSpace) {
EXPECT_EQ(8, dom_selection.Base().OffsetInContainerNode());
EXPECT_EQ(text, dom_selection.Extent().AnchorNode());
EXPECT_EQ(10, dom_selection.Extent().OffsetInContainerNode());
- EXPECT_EQ("<Paragraph: ><StaticText: Hel^lo|>",
- GetSelectionText(ax_selection));
+ EXPECT_EQ(
+ "++<Paragraph>\n"
+ "++++<StaticText: Hel^lo|>\n",
+ GetSelectionText(ax_selection));
}
//
// Get selection tests.
// Retrieving a selection with endpoints which have no corresponding objects in
-// the accessibility tree, e.g. which are aria-hidden, should shring
-// |AXSelection| to valid endpoints.
+// the accessibility tree, e.g. which are aria-hidden, should shrink or extend
+// the |AXSelection| to valid endpoints.
//
TEST_F(AccessibilitySelectionTest, SetSelectionInARIAHidden) {
- SetSelectionText(R"HTML(
- <div role="main">
- <p>Before aria-hidden.</p>
- ^<p aria-hidden="true">Aria-hidden 1.</p>
- <p>In the middle of aria-hidden.</p>
- <p aria-hidden="true">Aria-hidden 2.</p>|
- <p>After aria-hidden.</p>
+ SetBodyInnerHTML(R"HTML(
+ <div id="main" role="main">
+ <p id="beforeHidden">Before aria-hidden.</p>
+ <p id="hidden1" aria-hidden="true">Aria-hidden 1.</p>
+ <p id="betweenHidden">In between two aria-hidden elements.</p>
+ <p id="hidden2" aria-hidden="true">Aria-hidden 2.</p>
+ <p id="afterHidden">After aria-hidden.</p>
</div>
)HTML");
- const SelectionInDOMTree selection =
- GetFrame().Selection().GetSelectionInDOMTree();
+ const Node* hidden_1 = GetElementById("hidden1");
+ ASSERT_NE(nullptr, hidden_1);
+ const Node* hidden_2 = GetElementById("hidden2");
+ ASSERT_NE(nullptr, hidden_2);
+
+ const AXObject* ax_main = GetAXObjectByElementId("main");
+ ASSERT_NE(nullptr, ax_main);
+ ASSERT_EQ(ax::mojom::Role::kMain, ax_main->RoleValue());
+ const AXObject* ax_before = GetAXObjectByElementId("beforeHidden");
+ ASSERT_NE(nullptr, ax_before);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_before->RoleValue());
+ const AXObject* ax_between = GetAXObjectByElementId("betweenHidden");
+ ASSERT_NE(nullptr, ax_between);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_between->RoleValue());
+ const AXObject* ax_after = GetAXObjectByElementId("afterHidden");
+ ASSERT_NE(nullptr, ax_after);
+ ASSERT_EQ(ax::mojom::Role::kParagraph, ax_after->RoleValue());
+
+ ASSERT_NE(nullptr, GetAXObjectByElementId("hidden1"));
+ ASSERT_TRUE(GetAXObjectByElementId("hidden1")->AccessibilityIsIgnored());
+ ASSERT_NE(nullptr, GetAXObjectByElementId("hidden2"));
+ ASSERT_TRUE(GetAXObjectByElementId("hidden2")->AccessibilityIsIgnored());
+
+ const auto hidden_1_first = Position::FirstPositionInNode(*hidden_1);
+ const auto hidden_2_first = Position::FirstPositionInNode(*hidden_2);
+ const auto selection = SelectionInDOMTree::Builder()
+ .SetBaseAndExtent(hidden_1_first, hidden_2_first)
+ .Build();
const auto ax_selection_shrink = AXSelection::FromSelection(
selection, AXSelectionBehavior::kShrinkToValidDOMRange);
- EXPECT_EQ("", GetSelectionText(ax_selection_shrink));
-
const auto ax_selection_extend = AXSelection::FromSelection(
selection, AXSelectionBehavior::kExtendToValidDOMRange);
- EXPECT_EQ("", GetSelectionText(ax_selection_extend));
+
+ // The shrunk selection should encompass only the |AXObject| between the two
+ // aria-hidden elements and nothing else. This means that its anchor should be
+ // before and its focus after the |AXObject| in question.
+ ASSERT_FALSE(ax_selection_shrink.Base().IsTextPosition());
+ EXPECT_EQ(ax_main, ax_selection_shrink.Base().ContainerObject());
+ EXPECT_EQ(ax_between->IndexInParent(),
+ ax_selection_shrink.Base().ChildIndex());
+ ASSERT_FALSE(ax_selection_shrink.Extent().IsTextPosition());
+ EXPECT_EQ(ax_between, ax_selection_shrink.Extent().ContainerObject());
+ EXPECT_EQ(1, ax_selection_shrink.Extent().ChildIndex());
+
+ // The extended selection should start after the children of the paragraph
+ // before the first aria-hidden element and end right before the paragraph
+ // after the last aria-hidden element.
+ EXPECT_FALSE(ax_selection_extend.Base().IsTextPosition());
+ EXPECT_EQ(ax_before, ax_selection_extend.Base().ContainerObject());
+ EXPECT_EQ(1, ax_selection_extend.Base().ChildIndex());
+ EXPECT_FALSE(ax_selection_extend.Extent().IsTextPosition());
+ EXPECT_EQ(ax_main, ax_selection_extend.Extent().ContainerObject());
+ EXPECT_EQ(ax_after->IndexInParent(),
+ ax_selection_extend.Extent().ChildIndex());
+
+ // Even though the two AX selections have different anchors and foci, the text
+ // selected in the accessibility tree should not differ, because any
+ // differences in the equivalent DOM selections concern elements that are
+ // aria-hidden. However, the AX selections should still differ if converted to
+ // DOM selections.
+ const std::string selection_text(
+ "++<Main>\n"
+ "++++<Paragraph>\n"
+ "++++++<StaticText: Before aria-hidden.>\n"
+ "^++++<Paragraph>\n"
+ "++++++<StaticText: In between two aria-hidden elements.>\n"
+ "|++++<Paragraph>\n"
+ "++++++<StaticText: After aria-hidden.>\n");
+ EXPECT_EQ(selection_text, GetSelectionText(ax_selection_shrink));
+ EXPECT_EQ(selection_text, GetSelectionText(ax_selection_extend));
}
//
// Set selection tests.
// Setting the selection from an |AXSelection| that has endpoints which are not
-// present in the layout tree should shring the selection to visible endpoints.
+// present in the layout tree should shrink or extend the selection to visible
+// endpoints.
//
TEST_F(AccessibilitySelectionTest, SetSelectionAroundListBullet) {
- SetSelectionText(R"HTML(
+ SetBodyInnerHTML(R"HTML(
<div role="main">
<ul>
- ^<li>Item 1.</li>
- <li>Item 2.</li>|
+ <li id="item1">Item 1.</li>
+ <li id="item2">Item 2.</li>
</ul>
</div>
)HTML");
- const SelectionInDOMTree selection =
- GetFrame().Selection().GetSelectionInDOMTree();
+ const Node* item_1 = GetElementById("item1");
+ ASSERT_NE(nullptr, item_1);
+ ASSERT_FALSE(item_1->IsTextNode());
+ const Node* item_2 = GetElementById("item2");
+ ASSERT_NE(nullptr, item_2);
+ ASSERT_FALSE(item_2->IsTextNode());
+ const Node* text_2 = item_2->firstChild();
+ ASSERT_NE(nullptr, text_2);
+ ASSERT_TRUE(text_2->IsTextNode());
- const auto ax_selection_shrink = AXSelection::FromSelection(
- selection, AXSelectionBehavior::kShrinkToValidDOMRange);
- EXPECT_EQ("", GetSelectionText(ax_selection_shrink));
+ const AXObject* ax_item_1 = GetAXObjectByElementId("item1");
+ ASSERT_NE(nullptr, ax_item_1);
+ ASSERT_EQ(ax::mojom::Role::kListItem, ax_item_1->RoleValue());
+ const AXObject* ax_bullet_1 = ax_item_1->FirstChild();
+ ASSERT_NE(nullptr, ax_bullet_1);
+ ASSERT_EQ(ax::mojom::Role::kListMarker, ax_bullet_1->RoleValue());
+ const AXObject* ax_item_2 = GetAXObjectByElementId("item2");
+ ASSERT_NE(nullptr, ax_item_2);
+ ASSERT_EQ(ax::mojom::Role::kListItem, ax_item_2->RoleValue());
+ const AXObject* ax_text_2 = ax_item_2->LastChild();
+ ASSERT_NE(nullptr, ax_text_2);
+ ASSERT_EQ(ax::mojom::Role::kStaticText, ax_text_2->RoleValue());
- const auto ax_selection_extend = AXSelection::FromSelection(
- selection, AXSelectionBehavior::kExtendToValidDOMRange);
- EXPECT_EQ("", GetSelectionText(ax_selection_extend));
+ AXSelection::Builder builder;
+ AXSelection ax_selection =
+ builder.SetBase(AXPosition::CreateFirstPositionInObject(*ax_bullet_1))
+ .SetExtent(AXPosition::CreateLastPositionInObject(*ax_text_2))
+ .Build();
+
+ // The list bullet is not included in the DOM tree. Shrinking the
+ // |AXSelection| should skip over it by creating an anchor before the first
+ // child of the first <li>, i.e. the text node containing the text "Item 1.".
+ // This should be further optimized to a "before children" position at the
+ // first <li>.
+ ax_selection.Select(AXSelectionBehavior::kShrinkToValidDOMRange);
+ const SelectionInDOMTree shrunk_selection =
+ Selection().GetSelectionInDOMTree();
+
+ EXPECT_EQ(item_1, shrunk_selection.Base().AnchorNode());
+ EXPECT_TRUE(shrunk_selection.Base().IsBeforeChildren());
+ ASSERT_TRUE(shrunk_selection.Extent().IsOffsetInAnchor());
+ EXPECT_EQ(text_2, shrunk_selection.Extent().AnchorNode());
+ EXPECT_EQ(7, shrunk_selection.Extent().OffsetInContainerNode());
+
+ // The list bullet is not included in the DOM tree. Extending the
+ // |AXSelection| should move the anchor to before the first <li>.
+ ax_selection.Select(AXSelectionBehavior::kExtendToValidDOMRange);
+ const SelectionInDOMTree extended_selection =
+ Selection().GetSelectionInDOMTree();
+
+ ASSERT_TRUE(extended_selection.Base().IsOffsetInAnchor());
+ EXPECT_EQ(item_1->parentNode(), extended_selection.Base().AnchorNode());
+ EXPECT_EQ(static_cast<int>(item_1->NodeIndex()),
+ extended_selection.Base().OffsetInContainerNode());
+ ASSERT_TRUE(extended_selection.Extent().IsOffsetInAnchor());
+ EXPECT_EQ(text_2, extended_selection.Extent().AnchorNode());
+ EXPECT_EQ(7, extended_selection.Extent().OffsetInContainerNode());
+
+ // The |AXSelection| should remain unaffected by any shrinking and should
+ // include both list bullets.
+ EXPECT_EQ(
+ "++<Main>\n"
+ "++++<List>\n"
+ "++++++<ListItem>\n"
+ "++++++++<ListMarker: \xE2\x80\xA2 >\n"
+ "++++++++<StaticText: Item 1.>\n"
+ "++++++<ListItem>\n"
+ "++++++++<ListMarker: \xE2\x80\xA2 >\n"
+ "++++++++<StaticText: Item 2.|>\n",
+ GetSelectionText(ax_selection));
+}
+
+//
+// Declarative tests.
+//
+
+TEST_F(AccessibilitySelectionTest, ARIAHidden) {
+ RunSelectionTest("aria-hidden");
+}
+
+TEST_F(AccessibilitySelectionTest, List) {
+ RunSelectionTest("list");
+}
+
+TEST_F(AccessibilitySelectionTest, table) {
+ RunSelectionTest("table");
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.cc
index aa00ce8b023..67c10706124 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.cc
@@ -36,15 +36,13 @@
namespace blink {
-using namespace HTMLNames;
-
AXSlider::AXSlider(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache)
: AXLayoutObject(layout_object, ax_object_cache) {}
AXSlider* AXSlider::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXSlider(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXSlider>(layout_object, ax_object_cache);
}
ax::mojom::Role AXSlider::DetermineAccessibilityRole() {
@@ -131,7 +129,7 @@ AXSliderThumb::AXSliderThumb(AXObjectCacheImpl& ax_object_cache)
: AXMockObject(ax_object_cache) {}
AXSliderThumb* AXSliderThumb::Create(AXObjectCacheImpl& ax_object_cache) {
- return new AXSliderThumb(ax_object_cache);
+ return MakeGarbageCollected<AXSliderThumb>(ax_object_cache);
}
LayoutObject* AXSliderThumb::LayoutObjectForRelativeBounds() const {
@@ -144,7 +142,7 @@ LayoutObject* AXSliderThumb::LayoutObjectForRelativeBounds() const {
Element* thumb_element =
ToElement(slider_layout_object->GetNode())
->UserAgentShadowRoot()
- ->getElementById(ShadowElementNames::SliderThumb());
+ ->getElementById(shadow_element_names::SliderThumb());
DCHECK(thumb_element);
return thumb_element->GetLayoutObject();
}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.h
index ab68e7145a8..e149ee11359 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_slider.h
@@ -41,10 +41,9 @@ class HTMLInputElement;
class AXSlider : public AXLayoutObject {
public:
static AXSlider* Create(LayoutObject*, AXObjectCacheImpl&);
- ~AXSlider() override = default;
- protected:
AXSlider(LayoutObject*, AXObjectCacheImpl&);
+ ~AXSlider() override = default;
private:
HTMLInputElement* GetInputElement() const;
@@ -65,6 +64,8 @@ class AXSlider : public AXLayoutObject {
class AXSliderThumb final : public AXMockObject {
public:
static AXSliderThumb* Create(AXObjectCacheImpl&);
+
+ explicit AXSliderThumb(AXObjectCacheImpl&);
~AXSliderThumb() override = default;
ax::mojom::Role RoleValue() const override {
@@ -72,8 +73,6 @@ class AXSliderThumb final : public AXMockObject {
}
private:
- explicit AXSliderThumb(AXObjectCacheImpl&);
-
bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const override;
LayoutObject* LayoutObjectForRelativeBounds() const override;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc
index 4f30248e597..4119492a961 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_sparse_attribute_setter.cc
@@ -7,7 +7,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
class BoolAttributeSetter : public AXSparseAttributeSetter {
public:
@@ -118,28 +118,28 @@ AXSparseAttributeSetterMap& GetSparseAttributeSetterMap() {
ax_sparse_attribute_setter_map, ());
if (ax_sparse_attribute_setter_map.IsEmpty()) {
ax_sparse_attribute_setter_map.Set(
- aria_activedescendantAttr,
+ kAriaActivedescendantAttr,
new ObjectAttributeSetter(AXObjectAttribute::kAriaActiveDescendant));
ax_sparse_attribute_setter_map.Set(
- aria_controlsAttr, new ObjectVectorAttributeSetter(
+ kAriaControlsAttr, new ObjectVectorAttributeSetter(
AXObjectVectorAttribute::kAriaControls));
ax_sparse_attribute_setter_map.Set(
- aria_flowtoAttr,
+ kAriaFlowtoAttr,
new ObjectVectorAttributeSetter(AXObjectVectorAttribute::kAriaFlowTo));
ax_sparse_attribute_setter_map.Set(
- aria_detailsAttr,
+ kAriaDetailsAttr,
new ObjectAttributeSetter(AXObjectAttribute::kAriaDetails));
ax_sparse_attribute_setter_map.Set(
- aria_errormessageAttr,
+ kAriaErrormessageAttr,
new ObjectAttributeSetter(AXObjectAttribute::kAriaErrorMessage));
ax_sparse_attribute_setter_map.Set(
- aria_keyshortcutsAttr,
+ kAriaKeyshortcutsAttr,
new StringAttributeSetter(AXStringAttribute::kAriaKeyShortcuts));
ax_sparse_attribute_setter_map.Set(
- aria_roledescriptionAttr,
+ kAriaRoledescriptionAttr,
new StringAttributeSetter(AXStringAttribute::kAriaRoleDescription));
ax_sparse_attribute_setter_map.Set(
- aria_busyAttr, new BoolAttributeSetter(AXBoolAttribute::kAriaBusy));
+ kAriaBusyAttr, new BoolAttributeSetter(AXBoolAttribute::kAriaBusy));
}
return ax_sparse_attribute_setter_map;
}
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.cc b/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.cc
index db5d34482cb..20e1b7f5b8f 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.cc
@@ -40,7 +40,7 @@ AXSVGRoot::~AXSVGRoot() = default;
AXSVGRoot* AXSVGRoot::Create(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache) {
- return new AXSVGRoot(layout_object, ax_object_cache);
+ return MakeGarbageCollected<AXSVGRoot>(layout_object, ax_object_cache);
}
void AXSVGRoot::SetParent(AXObject* parent) {
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.h b/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.h
index 1427cb631f7..a039739536d 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/ax_svg_root.h
@@ -37,11 +37,10 @@ namespace blink {
class AXObjectCacheImpl;
class AXSVGRoot final : public AXLayoutObject {
- protected:
- AXSVGRoot(LayoutObject*, AXObjectCacheImpl&);
-
public:
static AXSVGRoot* Create(LayoutObject*, AXObjectCacheImpl&);
+
+ AXSVGRoot(LayoutObject*, AXObjectCacheImpl&);
~AXSVGRoot() override;
void SetParent(AXObject*) override;
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc b/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
index 55321ce8943..eedef03b104 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h"
#include <memory>
-#include "third_party/blink/renderer/core/accessibility/ax_context.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -36,7 +35,7 @@ using protocol::Accessibility::AXValue;
using protocol::Maybe;
using protocol::Response;
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -153,6 +152,28 @@ void FillGlobalStates(AXObject& ax_object,
CreateValue(ax_object.AriaInvalidValue(), AXValueTypeEnum::String)));
break;
}
+
+ if (ax_object.CanSetFocusAttribute()) {
+ properties.addItem(CreateProperty(
+ AXPropertyNameEnum::Focusable,
+ CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
+ }
+ if (ax_object.IsFocused()) {
+ properties.addItem(CreateProperty(
+ AXPropertyNameEnum::Focused,
+ CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
+ }
+ if (ax_object.IsEditable()) {
+ properties.addItem(CreateProperty(
+ AXPropertyNameEnum::Editable,
+ CreateValue(ax_object.IsRichlyEditable() ? "richtext" : "plaintext",
+ AXValueTypeEnum::Token)));
+ }
+ if (ax_object.CanSetValueAttribute()) {
+ properties.addItem(CreateProperty(
+ AXPropertyNameEnum::Settable,
+ CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
+ }
}
bool RoleAllowsModal(ax::mojom::Role role) {
@@ -216,7 +237,7 @@ void FillWidgetProperties(AXObject& ax_object,
}
int hierarchical_level = ax_object.HierarchicalLevel();
if (hierarchical_level > 0 ||
- ax_object.HasAttribute(HTMLNames::aria_levelAttr)) {
+ ax_object.HasAttribute(html_names::kAriaLevelAttr)) {
properties.addItem(CreateProperty(AXPropertyNameEnum::Level,
CreateValue(hierarchical_level)));
}
@@ -434,11 +455,11 @@ class SparseAttributeAXPropertyAdapter
case AXObjectVectorAttribute::kAriaControls:
properties_.addItem(
CreateRelatedNodeListProperty(AXPropertyNameEnum::Controls, objects,
- aria_controlsAttr, *ax_object_));
+ kAriaControlsAttr, *ax_object_));
break;
case AXObjectVectorAttribute::kAriaFlowTo:
properties_.addItem(CreateRelatedNodeListProperty(
- AXPropertyNameEnum::Flowto, objects, aria_flowtoAttr, *ax_object_));
+ AXPropertyNameEnum::Flowto, objects, kAriaFlowtoAttr, *ax_object_));
break;
}
}
@@ -451,14 +472,14 @@ void FillRelationships(AXObject& ax_object,
if (!results.IsEmpty()) {
properties.addItem(
CreateRelatedNodeListProperty(AXPropertyNameEnum::Describedby, results,
- aria_describedbyAttr, ax_object));
+ kAriaDescribedbyAttr, ax_object));
}
results.clear();
ax_object.AriaOwnsElements(results);
if (!results.IsEmpty()) {
properties.addItem(CreateRelatedNodeListProperty(
- AXPropertyNameEnum::Owns, results, aria_ownsAttr, ax_object));
+ AXPropertyNameEnum::Owns, results, kAriaOwnsAttr, ax_object));
}
results.clear();
}
@@ -477,10 +498,22 @@ std::unique_ptr<AXValue> CreateRoleNameValue(ax::mojom::Role role) {
} // namespace
+using EnabledAgentsMultimap =
+ HeapHashMap<WeakMember<LocalFrame>,
+ HeapHashSet<Member<InspectorAccessibilityAgent>>>;
+
+EnabledAgentsMultimap& EnabledAgents() {
+ DEFINE_STATIC_LOCAL(Persistent<EnabledAgentsMultimap>, enabled_agents,
+ (MakeGarbageCollected<EnabledAgentsMultimap>()));
+ return *enabled_agents;
+}
+
InspectorAccessibilityAgent::InspectorAccessibilityAgent(
InspectedFrames* inspected_frames,
InspectorDOMAgent* dom_agent)
- : inspected_frames_(inspected_frames), dom_agent_(dom_agent) {}
+ : inspected_frames_(inspected_frames),
+ dom_agent_(dom_agent),
+ enabled_(&agent_state_, /*default_value=*/false) {}
Response InspectorAccessibilityAgent::getPartialAXTree(
Maybe<int> dom_node_id,
@@ -808,6 +841,55 @@ void InspectorAccessibilityAgent::AddChildren(
}
}
+void InspectorAccessibilityAgent::EnableAndReset() {
+ enabled_.Set(true);
+ LocalFrame* frame = inspected_frames_->Root();
+ if (!EnabledAgents().Contains(frame)) {
+ EnabledAgents().Set(frame,
+ HeapHashSet<Member<InspectorAccessibilityAgent>>());
+ }
+ EnabledAgents().find(frame)->value.insert(this);
+ CreateAXContext();
+}
+
+protocol::Response InspectorAccessibilityAgent::enable() {
+ if (!enabled_.Get())
+ EnableAndReset();
+ return Response::OK();
+}
+
+protocol::Response InspectorAccessibilityAgent::disable() {
+ if (!enabled_.Get())
+ return Response::OK();
+ enabled_.Set(false);
+ context_ = nullptr;
+ LocalFrame* frame = inspected_frames_->Root();
+ DCHECK(EnabledAgents().Contains(frame));
+ auto it = EnabledAgents().find(frame);
+ it->value.erase(this);
+ if (it->value.IsEmpty())
+ EnabledAgents().erase(frame);
+ return Response::OK();
+}
+
+void InspectorAccessibilityAgent::Restore() {
+ if (enabled_.Get())
+ EnableAndReset();
+}
+
+void InspectorAccessibilityAgent::ProvideTo(LocalFrame* frame) {
+ if (!EnabledAgents().Contains(frame))
+ return;
+ for (InspectorAccessibilityAgent* agent : EnabledAgents().find(frame)->value)
+ agent->CreateAXContext();
+}
+
+void InspectorAccessibilityAgent::CreateAXContext() {
+ Document* document = inspected_frames_->Root()->GetDocument();
+ if (document)
+ context_ = std::make_unique<AXContext>(*document);
+}
+
void InspectorAccessibilityAgent::Trace(blink::Visitor* visitor) {
visitor->Trace(inspected_frames_);
visitor->Trace(dom_agent_);
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h b/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h
index c28a394523d..09049685842 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_INSPECTOR_ACCESSIBILITY_AGENT_H_
#include "base/macros.h"
+#include "third_party/blink/renderer/core/accessibility/ax_context.h"
#include "third_party/blink/renderer/core/inspector/inspector_base_agent.h"
#include "third_party/blink/renderer/core/inspector/protocol/Accessibility.h"
#include "third_party/blink/renderer/modules/modules_export.h"
@@ -16,6 +17,7 @@ class AXObject;
class AXObjectCacheImpl;
class InspectorDOMAgent;
class InspectedFrames;
+class LocalFrame;
using protocol::Accessibility::AXNode;
using protocol::Accessibility::AXNodeId;
@@ -25,10 +27,16 @@ class MODULES_EXPORT InspectorAccessibilityAgent
public:
InspectorAccessibilityAgent(InspectedFrames*, InspectorDOMAgent*);
+ static void ProvideTo(LocalFrame* frame);
+ void CreateAXContext();
+
// Base agent methods.
void Trace(blink::Visitor*) override;
+ void Restore() override;
// Protocol methods.
+ protocol::Response enable() override;
+ protocol::Response disable() override;
protocol::Response getPartialAXTree(
protocol::Maybe<int> dom_node_id,
protocol::Maybe<int> backend_node_id,
@@ -41,6 +49,9 @@ class MODULES_EXPORT InspectorAccessibilityAgent
override;
private:
+ // Unconditionally enables the agent, even if |enabled_.Get()==true|.
+ // For idempotence, call enable().
+ void EnableAndReset();
std::unique_ptr<AXNode> BuildObjectForIgnoredNode(
Node* dom_node,
AXObject*,
@@ -91,6 +102,8 @@ class MODULES_EXPORT InspectorAccessibilityAgent
Member<InspectedFrames> inspected_frames_;
Member<InspectorDOMAgent> dom_agent_;
+ InspectorAgentState::Boolean enabled_;
+ std::unique_ptr<AXContext> context_;
DISALLOW_COPY_AND_ASSIGN(InspectorAccessibilityAgent);
};
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/inspector_type_builder_helper.cc b/chromium/third_party/blink/renderer/modules/accessibility/inspector_type_builder_helper.cc
index 91169601a87..8b01f01ed88 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/inspector_type_builder_helper.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/inspector_type_builder_helper.cc
@@ -11,7 +11,7 @@
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
using namespace protocol::Accessibility;
std::unique_ptr<AXProperty> CreateProperty(const String& name,
@@ -214,8 +214,8 @@ std::unique_ptr<AXValueSource> CreateValueSource(NameSource& name_source) {
std::unique_ptr<AXValueSource> value_source =
AXValueSource::create().setType(type).build();
if (!name_source.related_objects.IsEmpty()) {
- if (name_source.attribute == aria_labelledbyAttr ||
- name_source.attribute == aria_labeledbyAttr) {
+ if (name_source.attribute == kAriaLabelledbyAttr ||
+ name_source.attribute == kAriaLabeledbyAttr) {
std::unique_ptr<AXValue> attribute_value = CreateRelatedNodeListValue(
name_source.related_objects, AXValueTypeEnum::IdrefList);
if (!name_source.attribute_value.IsNull())
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc
index 13950c5ba70..ad3e0e871fc 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc
@@ -4,22 +4,39 @@
#include "third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h"
+#include <algorithm>
+#include <iterator>
+#include <vector>
+
+#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/dom/character_data.h"
#include "third_party/blink/renderer/core/dom/container_node.h"
#include "third_party/blink/renderer/core/dom/node.h"
+#include "third_party/blink/renderer/core/editing/frame_selection.h"
+#include "third_party/blink/renderer/core/editing/position.h"
+#include "third_party/blink/renderer/core/editing/selection_template.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h"
#include "third_party/blink/renderer/modules/accessibility/ax_position.h"
#include "third_party/blink/renderer/modules/accessibility/ax_selection.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/shared_buffer.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
+namespace test {
namespace {
+constexpr char kSelectionTestsRelativePath[] = "selection/";
+constexpr char kTestFileSuffix[] = ".html";
+constexpr char kAXTestExpectationSuffix[] = "-ax.txt";
+
// Serialize accessibility subtree to selection text.
// Adds a '^' at the selection anchor offset and a '|' at the focus offset.
class AXSelectionSerializer final {
@@ -27,12 +44,14 @@ class AXSelectionSerializer final {
public:
explicit AXSelectionSerializer(const AXSelection& selection)
- : selection_(selection) {}
+ : tree_level_(0), selection_(selection) {}
+ ~AXSelectionSerializer() = default;
std::string Serialize(const AXObject& subtree) {
if (!selection_.IsValid())
return {};
SerializeSubtree(subtree);
+ DCHECK_EQ(tree_level_, 0);
return builder_.ToString().Utf8().data();
}
@@ -41,7 +60,7 @@ class AXSelectionSerializer final {
builder_.Append('<');
builder_.Append(AXObject::InternalRoleName(text_object.RoleValue()));
builder_.Append(": ");
- const String name = text_object.ComputedName() + '>';
+ const String name = text_object.ComputedName() + ">\n";
const AXObject& base_container = *selection_.Base().ContainerObject();
const AXObject& extent_container = *selection_.Extent().ContainerObject();
@@ -103,9 +122,14 @@ class AXSelectionSerializer final {
void HandleObject(const AXObject& object) {
builder_.Append('<');
builder_.Append(AXObject::InternalRoleName(object.RoleValue()));
- builder_.Append(": ");
- builder_.Append(object.ComputedName());
- builder_.Append('>');
+
+ String name = object.ComputedName();
+ if (name.length()) {
+ builder_.Append(": ");
+ builder_.Append(name);
+ }
+
+ builder_.Append(">\n");
SerializeSubtree(object);
}
@@ -125,116 +149,165 @@ class AXSelectionSerializer final {
}
void SerializeSubtree(const AXObject& subtree) {
- for (const Member<AXObject>& child : subtree.Children()) {
- if (!child)
- continue;
+ if (subtree.ChildCount() == 0)
+ return;
+ for (const AXObject* child : subtree.Children()) {
+ DCHECK(child);
const auto position = AXPosition::CreatePositionBeforeObject(*child);
HandleSelection(position);
+ ++tree_level_;
+ builder_.Append(
+ String::FromUTF8(std::string(tree_level_ * 2, '+').c_str()));
if (position.IsTextPosition()) {
HandleTextObject(*child);
} else {
HandleObject(*child);
}
+ --tree_level_;
}
HandleSelection(AXPosition::CreateLastPositionInObject(subtree));
}
StringBuilder builder_;
+ int tree_level_;
AXSelection selection_;
};
// Deserializes an HTML snippet with or without selection markers to an
-// accessibility tree. A '^' could be present at the selection anchor offset and
-// a '|' at the focus offset. If multiple markers are present, the deserializer
-// will DCHECK. If there are no markers, no selection will be made. We don't
-// allow '^' and '|' markers to appear in anything other than the contents of an
-// HTML node, e.g. they are not permitted in aria-labels.
+// |AXSelection| object. A '^' could be present at the selection anchor offset
+// and a '|' at the focus offset. If multiple markers are present, the
+// deserializer will return multiple |AXSelection| objects. If there are
+// multiple markers, the first '|' in DOM order will be matched with the first
+// '^' marker, the second '|' with the second '^', and so on. If there are more
+// '|'s than '^'s or vice versa, the deserializer will DCHECK. If there are no
+// markers, no |AXSelection| objects will be returned. We don't allow '^' and
+// '|' markers to appear in anything other than the contents of an HTML node,
+// e.g. they are not permitted in aria-labels.
class AXSelectionDeserializer final {
STACK_ALLOCATED();
public:
- AXSelectionDeserializer(AXObjectCacheImpl& cache)
- : ax_object_cache_(&cache), base_(), extent_() {}
+ explicit AXSelectionDeserializer(AXObjectCacheImpl& cache)
+ : ax_object_cache_(&cache),
+ anchors_(MakeGarbageCollected<VectorOfPairs<Node, int>>()),
+ foci_(MakeGarbageCollected<VectorOfPairs<Node, int>>()) {}
~AXSelectionDeserializer() = default;
// Creates an accessibility tree rooted at the given HTML element from the
- // provided HTML snippet, selects the part of the tree indicated by the
- // selection markers in the snippet if present, and returns the tree's root.
- const AXSelection Deserialize(const std::string& html_snippet,
- HTMLElement& element) {
+ // provided HTML snippet and returns |AXSelection| objects that can select the
+ // parts of the tree indicated by the selection markers in the snippet.
+ const Vector<AXSelection> Deserialize(const std::string& html_snippet,
+ HTMLElement& element) {
element.SetInnerHTMLFromString(String::FromUTF8(html_snippet.c_str()));
+ element.GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
AXObject* root = ax_object_cache_->GetOrCreate(&element);
- if (!root)
- return AXSelection::Builder().Build();
+ if (!root || root->IsDetached())
+ return {};
FindSelectionMarkers(*root);
- if (base_ && extent_) {
+ DCHECK((foci_->size() == 1 && anchors_->size() == 0) ||
+ anchors_->size() == foci_->size())
+ << "There should be an equal number of '^'s and '|'s in the HTML that "
+ "is being deserialized, or if caret placement is required, only a "
+ "single '|'.";
+ if (foci_->IsEmpty())
+ return {};
+
+ Vector<AXSelection> ax_selections;
+ if (anchors_->IsEmpty()) {
+ // Handle the case when there is just a single '|' marker representing the
+ // position of the caret.
+ DCHECK(foci_->at(0).first);
+ const Position caret(foci_->at(0).first, foci_->at(0).second);
+ const auto ax_caret = AXPosition::FromPosition(caret);
AXSelection::Builder builder;
- AXSelection ax_selection =
- builder.SetBase(base_).SetExtent(extent_).Build();
- ax_selection.Select();
- return ax_selection;
+ ax_selections.push_back(
+ builder.SetBase(ax_caret).SetExtent(ax_caret).Build());
+ return ax_selections;
}
- return AXSelection::Builder().Build();
+ for (size_t i = 0; i < foci_->size(); ++i) {
+ DCHECK(anchors_->at(i).first);
+ const Position base(*anchors_->at(i).first, anchors_->at(i).second);
+ const auto ax_base = AXPosition::FromPosition(base);
+
+ DCHECK(foci_->at(i).first);
+ const Position extent(*foci_->at(i).first, foci_->at(i).second);
+ const auto ax_extent = AXPosition::FromPosition(extent);
+ AXSelection::Builder builder;
+ ax_selections.push_back(
+ builder.SetBase(ax_base).SetExtent(ax_extent).Build());
+ }
+
+ return ax_selections;
}
private:
void HandleCharacterData(const AXObject& text_object) {
CharacterData* const node = ToCharacterData(text_object.GetNode());
- int base_offset = -1;
- int extent_offset = -1;
+ Vector<int> base_offsets;
+ Vector<int> extent_offsets;
+ unsigned number_of_markers = 0;
StringBuilder builder;
for (unsigned i = 0; i < node->length(); ++i) {
const UChar character = node->data()[i];
if (character == '^') {
- DCHECK_EQ(base_offset, -1) << "Only one '^' is allowed " << text_object;
- base_offset = static_cast<int>(i);
+ base_offsets.push_back(static_cast<int>(i - number_of_markers));
+ ++number_of_markers;
continue;
}
+
if (character == '|') {
- DCHECK_EQ(extent_offset, -1)
- << "Only one '|' is allowed " << text_object;
- extent_offset = static_cast<int>(i);
+ extent_offsets.push_back(static_cast<int>(i - number_of_markers));
+ ++number_of_markers;
continue;
}
+
builder.Append(character);
}
- LOG(ERROR) << "Nektar\n" << base_offset << extent_offset;
- if (base_offset == -1 && extent_offset == -1)
+ if (base_offsets.IsEmpty() && extent_offsets.IsEmpty())
return;
- // Remove the markers, otherwise they would be duplicated if the AX
- // selection is re-serialized.
+ // Remove the markers, otherwise they would be duplicated if the AXSelection
+ // is re-serialized.
node->setData(builder.ToString());
+ node->GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
- if (node->length() == 0) {
+ //
+ // Non-text selection.
+ //
+
+ if (node->ContainsOnlyWhitespaceOrEmpty()) {
// Since the text object contains only selection markers, this indicates
// that this is a request for a non-text selection.
- if (base_offset >= 0)
- base_ = AXPosition::CreatePositionBeforeObject(text_object);
- if (extent_offset >= 0)
- extent_ = AXPosition::CreatePositionBeforeObject(text_object);
-
- ContainerNode* const parent_node = node->parentNode();
- DCHECK(parent_node);
- parent_node->removeChild(node);
+ Node* const parent = node->ParentOrShadowHostNode();
+ int index_in_parent = static_cast<int>(node->NodeIndex());
+
+ for (size_t i = 0; i < base_offsets.size(); ++i)
+ anchors_->emplace_back(parent, index_in_parent);
+
+ for (size_t i = 0; i < extent_offsets.size(); ++i)
+ foci_->emplace_back(parent, index_in_parent);
+
return;
}
- if (base_offset >= 0)
- base_ = AXPosition::CreatePositionInTextObject(text_object, base_offset);
- if (extent_offset >= 0) {
- extent_ =
- AXPosition::CreatePositionInTextObject(text_object, extent_offset);
- }
+ //
+ // Text selection.
+ //
+
+ for (int base_offset : base_offsets)
+ anchors_->emplace_back(node, base_offset);
+ for (int extent_offset : extent_offsets)
+ foci_->emplace_back(node, extent_offset);
}
void HandleObject(const AXObject& object) {
- for (const Member<AXObject>& child : object.Children()) {
- if (!child)
- continue;
+ for (const AXObject* child : object.Children()) {
+ DCHECK(child);
FindSelectionMarkers(*child);
}
}
@@ -243,14 +316,19 @@ class AXSelectionDeserializer final {
const Node* node = root.GetNode();
if (node && node->IsCharacterDataNode()) {
HandleCharacterData(root);
+ // |root| will need to be detached and replaced with an updated AXObject.
return;
}
HandleObject(root);
}
- Member<AXObjectCacheImpl> const ax_object_cache_;
- AXPosition base_;
- AXPosition extent_;
+ Persistent<AXObjectCacheImpl> const ax_object_cache_;
+
+ // Pairs of anchor nodes + anchor offsets.
+ Persistent<VectorOfPairs<Node, int>> anchors_;
+
+ // Pairs of focus nodes + focus offsets.
+ Persistent<VectorOfPairs<Node, int>> foci_;
};
} // namespace
@@ -259,10 +337,17 @@ AccessibilitySelectionTest::AccessibilitySelectionTest(
LocalFrameClient* local_frame_client)
: AccessibilityTest(local_frame_client) {}
+std::string AccessibilitySelectionTest::GetCurrentSelectionText() const {
+ const SelectionInDOMTree selection =
+ GetFrame().Selection().GetSelectionInDOMTree();
+ const auto ax_selection = AXSelection::FromSelection(selection);
+ return GetSelectionText(ax_selection);
+}
+
std::string AccessibilitySelectionTest::GetSelectionText(
const AXSelection& selection) const {
const AXObject* root = GetAXRootObject();
- if (!root)
+ if (!root || root->IsDetached())
return {};
return AXSelectionSerializer(selection).Serialize(*root);
}
@@ -273,20 +358,76 @@ std::string AccessibilitySelectionTest::GetSelectionText(
return AXSelectionSerializer(selection).Serialize(subtree);
}
-const AXSelection AccessibilitySelectionTest::SetSelectionText(
+AXSelection AccessibilitySelectionTest::SetSelectionText(
const std::string& selection_text) const {
HTMLElement* body = GetDocument().body();
if (!body)
return AXSelection::Builder().Build();
- return AXSelectionDeserializer(GetAXObjectCache())
- .Deserialize(selection_text, *body);
+ const Vector<AXSelection> ax_selections =
+ AXSelectionDeserializer(GetAXObjectCache())
+ .Deserialize(selection_text, *body);
+ if (ax_selections.IsEmpty())
+ return AXSelection::Builder().Build();
+ return ax_selections.front();
}
-const AXSelection AccessibilitySelectionTest::SetSelectionText(
+AXSelection AccessibilitySelectionTest::SetSelectionText(
const std::string& selection_text,
HTMLElement& element) const {
- return AXSelectionDeserializer(GetAXObjectCache())
- .Deserialize(selection_text, element);
+ const Vector<AXSelection> ax_selections =
+ AXSelectionDeserializer(GetAXObjectCache())
+ .Deserialize(selection_text, element);
+ if (ax_selections.IsEmpty())
+ return AXSelection::Builder().Build();
+ return ax_selections.front();
+}
+
+void AccessibilitySelectionTest::RunSelectionTest(
+ const std::string& test_name) const {
+ static const std::string separator_line = '\n' + std::string(80, '=') + '\n';
+ const String relative_path = String::FromUTF8(kSelectionTestsRelativePath) +
+ String::FromUTF8(test_name.c_str());
+ const String test_path = AccessibilityTestDataPath(relative_path);
+
+ const String test_file = test_path + String::FromUTF8(kTestFileSuffix);
+ scoped_refptr<SharedBuffer> test_file_buffer = ReadFromFile(test_file);
+ auto test_file_chars = test_file_buffer->CopyAs<std::vector<char>>();
+ std::string test_file_contents;
+ std::copy(test_file_chars.begin(), test_file_chars.end(),
+ std::back_inserter(test_file_contents));
+ ASSERT_FALSE(test_file_contents.empty())
+ << "Test file cannot be empty.\n"
+ << test_file.Utf8().data()
+ << "\nDid you forget to add a data dependency to the BUILD file?";
+
+ const String ax_file = test_path + String::FromUTF8(kAXTestExpectationSuffix);
+ scoped_refptr<SharedBuffer> ax_file_buffer = ReadFromFile(ax_file);
+ auto ax_file_chars = ax_file_buffer->CopyAs<std::vector<char>>();
+ std::string ax_file_contents;
+ std::copy(ax_file_chars.begin(), ax_file_chars.end(),
+ std::back_inserter(ax_file_contents));
+ ASSERT_FALSE(ax_file_contents.empty())
+ << "Expectations file cannot be empty.\n"
+ << ax_file.Utf8().data()
+ << "\nDid you forget to add a data dependency to the BUILD file?";
+
+ HTMLElement* body = GetDocument().body();
+ ASSERT_NE(nullptr, body);
+ Vector<AXSelection> ax_selections =
+ AXSelectionDeserializer(GetAXObjectCache())
+ .Deserialize(test_file_contents, *body);
+ std::string actual_ax_file_contents;
+
+ for (auto& ax_selection : ax_selections) {
+ ax_selection.Select();
+ actual_ax_file_contents += separator_line;
+ actual_ax_file_contents += ax_selection.ToString().Utf8().data();
+ actual_ax_file_contents += separator_line;
+ actual_ax_file_contents += GetCurrentSelectionText();
+ }
+
+ EXPECT_EQ(ax_file_contents, actual_ax_file_contents);
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h
index 0ee6a45a9e3..a95a3362e1d 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.h
@@ -16,6 +16,8 @@ class AXObject;
class AXSelection;
class LocalFrameClient;
+namespace test {
+
// Makes writing and debugging selection tests easier.
class AccessibilitySelectionTest : public AccessibilityTest {
USING_FAST_MALLOC(AccessibilitySelectionTest);
@@ -24,25 +26,41 @@ class AccessibilitySelectionTest : public AccessibilityTest {
AccessibilitySelectionTest(LocalFrameClient* local_frame_client = nullptr);
protected:
- // Gets the inner HTML of the accessibility tree and annotates it with markers
- // indicating the anchor and focus of |selection|.
+ // Gets a text representation of the accessibility tree that is currently
+ // selected and annotates it with markers indicating the anchor and focus of
+ // |selection|.
+ std::string GetCurrentSelectionText() const;
+
+ // Gets a text representation of the accessibility tree encompassing
+ // |selection| and annotates it with markers indicating the anchor and focus
+ // of |selection|.
std::string GetSelectionText(const AXSelection& selection) const;
- // Gets the inner HTML of the accessibility subtree rooted at |subtree| and
- // annotates it with markers indicating the anchor and focus of |selection|.
+ // Gets a text representation of the accessibility subtree rooted at |subtree|
+ // and encompassing |selection|, and annotates it with markers indicating the
+ // anchor and focus of |selection|.
std::string GetSelectionText(const AXSelection& selection,
const AXObject& subtree) const;
// Sets |selection_text| as inner HTML of the document body and returns the
- // root of the accessibility tree at body.
- const AXSelection SetSelectionText(const std::string& selection_text) const;
+ // resulting |AXSelection|. If there are multiple selection markers, returns
+ // only the first selection.
+ AXSelection SetSelectionText(const std::string& selection_text) const;
+
+ // Sets |selection_text| as inner HTML of |element| and returns the resulting
+ // |AXSelection|. If there are multiple selection markers, returns only the
+ // first selection.
+ AXSelection SetSelectionText(const std::string& selection_text,
+ HTMLElement& element) const;
+
+ // Compares two HTML files containing a DOM selection and the equivalent
+ // accessibility selection.
+ void RunSelectionTest(const std::string& test_name) const;
- // Sets |selection_text| as inner HTML of |element| and returns the root of
- // the accessibility subtree at |element|.
- const AXSelection SetSelectionText(const std::string& selection_text,
- HTMLElement& element) const;
+ private:
};
+} // namespace test
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_TESTING_ACCESSIBILITY_SELECTION_TEST_H_
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.cc b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.cc
index 4cbf314bec5..09fab64048f 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.cc
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h"
namespace blink {
+namespace test {
AccessibilityTest::AccessibilityTest(LocalFrameClient* local_frame_client)
: RenderingTest(local_frame_client) {}
@@ -56,11 +57,12 @@ std::ostringstream& AccessibilityTest::PrintAXTreeHelper(
stream << std::string(level * 2, '+');
stream << *root << std::endl;
- for (const Member<AXObject> child : root->Children()) {
+ for (const AXObject* child : root->Children()) {
DCHECK(child);
- PrintAXTreeHelper(stream, child.Get(), level + 1);
+ PrintAXTreeHelper(stream, child, level + 1);
}
return stream;
}
+} // namespace test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h
index 2b2a4542e80..6e9186776d7 100644
--- a/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h
@@ -19,6 +19,8 @@ class AXObject;
class AXObjectCacheImpl;
class LocalFrameClient;
+namespace test {
+
class AccessibilityTest : public RenderingTest {
USING_FAST_MALLOC(AccessibilityTest);
@@ -47,6 +49,7 @@ class AccessibilityTest : public RenderingTest {
std::unique_ptr<AXContext> ax_context_;
};
+} // namespace test
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_ACCESSIBILITY_TESTING_ACCESSIBILITY_TEST_H_
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden-ax.txt b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden-ax.txt
new file mode 100644
index 00000000000..a3ac8395a1e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden-ax.txt
@@ -0,0 +1,11 @@
+
+================================================================================
+AXSelection from AX object anchored position in "Main": "", 1 to AX object anchored position in "Main": "", 2
+================================================================================
+++<Main>
+++++<Paragraph>
+++++++<StaticText: Before aria-hidden.>
+^++++<Paragraph>
+++++++<StaticText: In the middle of aria-hidden.>
+|++++<Paragraph>
+++++++<StaticText: After aria-hidden.>
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden.html b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden.html
new file mode 100644
index 00000000000..88f9d7a64aa
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/aria-hidden.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+ <body>
+ <div role="main">
+ <p>Before aria-hidden.</p>
+ ^<p aria-hidden="true">Aria-hidden 1.</p>
+ <p>In the middle of aria-hidden.</p>
+ <p aria-hidden="true">Aria-hidden 2.</p>|
+ <p>After aria-hidden.</p>
+ </div>
+ </body>
+</html>
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list-ax.txt b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list-ax.txt
new file mode 100644
index 00000000000..cdb8cd6db46
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list-ax.txt
@@ -0,0 +1,47 @@
+
+================================================================================
+AXSelection from AX object anchored position in "List": "", 1 to AX object anchored position in "List": "", 3
+================================================================================
+++<List>
+++++<ListItem>
+++++++<ListMarker: 1. >
+++++++<StaticText: tic>
+^++++<ListItem>
+++++++<ListMarker: 2. >
+++++++<StaticText: tac>
+++++<ListItem>
+++++++<ListMarker: 3. >
+++++++<StaticText: toe>
+|++<List>
+++++<ListItem>
+++++++<StaticText: tic>
+++++<StaticText: >
+++++<ListItem>
+++++++<StaticText: tac>
+++++<StaticText: >
+++++<ListItem>
+++++++<StaticText: toe>
+
+================================================================================
+AXSelection from AX object anchored position in "WebArea": "", 1 to AX object anchored position in "WebArea": "", 2
+================================================================================
+++<List>
+++++<ListItem>
+++++++<ListMarker: 1. >
+++++++<StaticText: tic>
+++++<ListItem>
+++++++<ListMarker: 2. >
+++++++<StaticText: tac>
+++++<ListItem>
+++++++<ListMarker: 3. >
+++++++<StaticText: toe>
+^++<List>
+++++<ListItem>
+++++++<StaticText: tic>
+++++<StaticText: >
+++++<ListItem>
+++++++<StaticText: tac>
+++++<StaticText: >
+++++<ListItem>
+++++++<StaticText: toe>
+| \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list.html b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list.html
new file mode 100644
index 00000000000..b89da32a8b1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/list.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html>
+ <style type="text/css">
+ .inlineList li {
+ display: inline;
+ }
+ </style>
+ <body>
+ <ol>
+ <li>tic</li>
+ ^<li>tac</li>
+ <li>toe</li>|
+ </ol>
+ ^<ul class="inlineList">
+ <li>tic</li>
+ <li>tac</li>
+ <li>toe</li>
+ </ul>|
+ </body>
+</html>
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table-ax.txt b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table-ax.txt
new file mode 100644
index 00000000000..670a7cbf4ee
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table-ax.txt
@@ -0,0 +1,100 @@
+
+================================================================================
+AXSelection from AX text position in "StaticText": "Sum", 0 to AX text position in "StaticText": "Subtraction", 11
+================================================================================
+++<Table>
+++++<Row>
+++++++<ColumnHeader: Sum>
+^++++++++<StaticText: ^Sum>
+++++++<ColumnHeader: Subtraction>
+++++++++<StaticText: Subtraction|>
+++++<Row>
+++++++<Cell: 10>
+++++++++<StaticText: 10>
+++++++<Cell: 7>
+++++++++<StaticText: 7>
+++++<Row>
+++++++<Cell: 2>
+++++++++<StaticText: 2>
+++++++<Cell: 4>
+++++++++<StaticText: 4>
+++++<Row>
+++++++<Cell: 12>
+++++++++<StaticText: 12>
+++++++<Cell: 3>
+++++++++<StaticText: 3>
+
+================================================================================
+AXSelection from AX text position in "StaticText": "7", 1 to AX text position in "StaticText": "10", 0
+================================================================================
+++<Table>
+++++<Row>
+++++++<ColumnHeader: Sum>
+++++++++<StaticText: Sum>
+++++++<ColumnHeader: Subtraction>
+++++++++<StaticText: Subtraction>
+++++<Row>
+++++++<Cell: 10>
+|++++++++<StaticText: |10>
+++++++<Cell: 7>
+++++++++<StaticText: 7^>
+++++<Row>
+++++++<Cell: 2>
+++++++++<StaticText: 2>
+++++++<Cell: 4>
+++++++++<StaticText: 4>
+++++<Row>
+++++++<Cell: 12>
+++++++++<StaticText: 12>
+++++++<Cell: 3>
+++++++++<StaticText: 3>
+
+================================================================================
+AXSelection from AX text position in "StaticText": "2", 1 to AX text position in "StaticText": "4", 0
+================================================================================
+++<Table>
+++++<Row>
+++++++<ColumnHeader: Sum>
+++++++++<StaticText: Sum>
+++++++<ColumnHeader: Subtraction>
+++++++++<StaticText: Subtraction>
+++++<Row>
+++++++<Cell: 10>
+++++++++<StaticText: 10>
+++++++<Cell: 7>
+++++++++<StaticText: 7>
+++++<Row>
+++++++<Cell: 2>
+++++++++<StaticText: 2^>
+++++++<Cell: 4>
+|++++++++<StaticText: |4>
+++++<Row>
+++++++<Cell: 12>
+++++++++<StaticText: 12>
+++++++<Cell: 3>
+++++++++<StaticText: 3>
+
+================================================================================
+AXSelection from AX text position in "StaticText": "12", 0 to AX text position in "StaticText": "3", 1
+================================================================================
+++<Table>
+++++<Row>
+++++++<ColumnHeader: Sum>
+++++++++<StaticText: Sum>
+++++++<ColumnHeader: Subtraction>
+++++++++<StaticText: Subtraction>
+++++<Row>
+++++++<Cell: 10>
+++++++++<StaticText: 10>
+++++++<Cell: 7>
+++++++++<StaticText: 7>
+++++<Row>
+++++++<Cell: 2>
+++++++++<StaticText: 2>
+++++++<Cell: 4>
+++++++++<StaticText: 4>
+++++<Row>
+++++++<Cell: 12>
+^++++++++<StaticText: ^12>
+++++++<Cell: 3>
+++++++++<StaticText: 3|>
diff --git a/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table.html b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table.html
new file mode 100644
index 00000000000..8159422e498
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/accessibility/testing/data/selection/table.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html>
+ <body>
+ <table border="1">
+ <thead>
+ <tr>
+ <th>^Sum</th>
+ <th>Subtraction|</th>
+ </tr>
+ </thead>
+ <tfoot>
+ <tr>
+ <td>^12</td>
+ <td>3|</td>
+ </tr>
+ </tfoot>
+ <tbody>
+ <tr>
+ <td>|10</td>
+ <td>7^</td>
+ </tr>
+ <tr>
+ <td>2^</td>
+ <td>|4</td>
+ </tr>
+ </tbody>
+ </table>
+ </body>
+</html>
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/BUILD.gn b/chromium/third_party/blink/renderer/modules/animationworklet/BUILD.gn
index ddde73a9135..ba9105360e6 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/BUILD.gn
@@ -14,8 +14,6 @@ blink_modules_sources("animationworklet") {
"animation_worklet_messaging_proxy.h",
"animation_worklet_proxy_client.cc",
"animation_worklet_proxy_client.h",
- "animation_worklet_thread.cc",
- "animation_worklet_thread.h",
"animator.cc",
"animator.h",
"animator_definition.cc",
@@ -28,5 +26,7 @@ blink_modules_sources("animationworklet") {
"worklet_animation.h",
"worklet_animation_options.cc",
"worklet_animation_options.h",
+ "worklet_group_effect_proxy.cc",
+ "worklet_group_effect_proxy.h",
]
}
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/DEPS b/chromium/third_party/blink/renderer/modules/animationworklet/DEPS
index c7f499dc34e..c02c28629d3 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/DEPS
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/DEPS
@@ -3,4 +3,5 @@ include_rules = [
"+third_party/blink/renderer/modules/animationworklet",
"+third_party/blink/renderer/modules/event_target_modules.h",
"+third_party/blink/renderer/modules/modules_export.h",
+ "+third_party/blink/renderer/modules/worklet",
]
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/README.md b/chromium/third_party/blink/renderer/modules/animationworklet/README.md
index 020d089932b..b9078bcfff7 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/README.md
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/README.md
@@ -75,6 +75,6 @@ updates from compositor (this is not yet in place).
## Testing
Layout tests that cover web-exposed API for Animation Worklet are tested in
-[`LayoutTests/virtual/threaded/fast/animationworklet/`](../../../LayoutTests/virtual/threaded/fast/animationworklet/).
+[`web_tests/virtual/threaded/fast/animationworklet/`](../../../web_tests/virtual/threaded/fast/animationworklet/).
There are unit tests covering animation worklet and global scope in [`modules/animationworklet`](.).
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet.cc b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet.cc
index 2722b7d0e25..d6e0a464357 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet.cc
@@ -11,7 +11,6 @@
#include "third_party/blink/renderer/core/workers/worker_clients.h"
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.h"
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h"
-#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h"
base::AtomicSequenceNumber g_next_worklet_id;
@@ -36,7 +35,6 @@ bool AnimationWorklet::NeedsToCreateGlobalScope() {
WorkletGlobalScopeProxy* AnimationWorklet::CreateGlobalScope() {
DCHECK(NeedsToCreateGlobalScope());
- AnimationWorkletThread::EnsureSharedBackingThread();
Document* document = To<Document>(GetExecutionContext());
AnimationWorkletProxyClient* proxy_client =
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.cc b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.cc
index c7912c97333..b20356e4a65 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.cc
@@ -4,6 +4,8 @@
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h"
+#include "base/metrics/histogram_macros.h"
+#include "base/timer/elapsed_timer.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_object_parser.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
@@ -15,6 +17,7 @@
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -25,8 +28,7 @@ void UpdateAnimation(Animator* animator,
WorkletAnimationId id,
double current_time,
AnimationWorkletDispatcherOutput* result) {
- AnimationWorkletDispatcherOutput::AnimationState animation_output(
- id, base::nullopt);
+ AnimationWorkletDispatcherOutput::AnimationState animation_output(id);
if (animator->Animate(script_state, current_time, &animation_output)) {
result->animations.push_back(std::move(animation_output));
}
@@ -66,9 +68,10 @@ void AnimationWorkletGlobalScope::Dispose() {
Animator* AnimationWorkletGlobalScope::CreateAnimatorFor(
int animation_id,
const String& name,
- WorkletAnimationOptions* options) {
+ WorkletAnimationOptions* options,
+ int num_effects) {
DCHECK(!animators_.at(animation_id));
- Animator* animator = CreateInstance(name, options);
+ Animator* animator = CreateInstance(name, options, num_effects);
if (!animator)
return nullptr;
animators_.Set(animation_id, animator);
@@ -78,6 +81,7 @@ Animator* AnimationWorkletGlobalScope::CreateAnimatorFor(
std::unique_ptr<AnimationWorkletOutput> AnimationWorkletGlobalScope::Mutate(
const AnimationWorkletInput& mutator_input) {
+ base::ElapsedTimer timer;
DCHECK(IsContextThread());
ScriptState* script_state = ScriptController()->GetScriptState();
@@ -99,7 +103,8 @@ std::unique_ptr<AnimationWorkletOutput> AnimationWorkletGlobalScope::Mutate(
WorkletAnimationOptions* options =
static_cast<WorkletAnimationOptions*>(animation.options.get());
- Animator* animator = CreateAnimatorFor(id, name, options);
+ Animator* animator =
+ CreateAnimatorFor(id, name, options, animation.num_effects);
if (!animator)
continue;
@@ -121,12 +126,20 @@ std::unique_ptr<AnimationWorkletOutput> AnimationWorkletGlobalScope::Mutate(
for (const auto& worklet_animation_id : mutator_input.peeked_animations) {
int id = worklet_animation_id.animation_id;
Animator* animator = animators_.at(id);
+ if (!animator)
+ continue;
- result->animations.emplace_back(
- worklet_animation_id,
- animator ? animator->GetLastLocalTime() : base::nullopt);
+ AnimationWorkletDispatcherOutput::AnimationState animation_output(
+ worklet_animation_id);
+ animation_output.local_times = animator->GetLocalTimes();
+ result->animations.push_back(animation_output);
}
+ UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
+ "Animation.AnimationWorklet.GlobalScope.MutateDuration", timer.Elapsed(),
+ base::TimeDelta::FromMicroseconds(1),
+ base::TimeDelta::FromMilliseconds(100), 50);
+
return result;
}
@@ -185,7 +198,8 @@ void AnimationWorkletGlobalScope::registerAnimator(
Animator* AnimationWorkletGlobalScope::CreateInstance(
const String& name,
- WorkletAnimationOptions* options) {
+ WorkletAnimationOptions* options,
+ int num_effects) {
DCHECK(IsContextThread());
AnimatorDefinition* definition = animator_definitions_.at(name);
if (!definition)
@@ -206,7 +220,7 @@ Animator* AnimationWorkletGlobalScope::CreateInstance(
.ToLocal(&instance))
return nullptr;
- return new Animator(isolate, definition, instance);
+ return new Animator(isolate, definition, instance, num_effects);
}
AnimatorDefinition* AnimationWorkletGlobalScope::FindDefinitionForTest(
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h
index c0ee79bc731..395ce9a9888 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutators_state.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -56,10 +57,12 @@ class MODULES_EXPORT AnimationWorkletGlobalScope : public WorkletGlobalScope {
void RegisterWithProxyClientIfNeeded();
Animator* CreateInstance(const String& name,
- WorkletAnimationOptions* options);
+ WorkletAnimationOptions* options,
+ int num_effects);
Animator* CreateAnimatorFor(int animation_id,
const String& name,
- WorkletAnimationOptions* options);
+ WorkletAnimationOptions* options,
+ int num_effects);
typedef HeapHashMap<String, TraceWrapperMember<AnimatorDefinition>>
DefinitionMap;
DefinitionMap animator_definitions_;
@@ -70,11 +73,12 @@ class MODULES_EXPORT AnimationWorkletGlobalScope : public WorkletGlobalScope {
bool registered_ = false;
};
-DEFINE_TYPE_CASTS(AnimationWorkletGlobalScope,
- ExecutionContext,
- context,
- context->IsAnimationWorkletGlobalScope(),
- context.IsAnimationWorkletGlobalScope());
+template <>
+struct DowncastTraits<AnimationWorkletGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsAnimationWorkletGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope_test.cc b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope_test.cc
index 1b5aea328ee..b168b93001b 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope_test.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope_test.cc
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
@@ -21,12 +22,11 @@
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet.h"
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h"
-#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h"
#include "third_party/blink/renderer/modules/animationworklet/animator.h"
#include "third_party/blink/renderer/modules/animationworklet/animator_definition.h"
+#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
@@ -57,7 +57,6 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
AnimationWorkletGlobalScopeTest() = default;
void SetUp() override {
- AnimationWorkletThread::EnsureSharedBackingThread();
PageTestBase::SetUp(IntSize());
Document* document = &GetDocument();
document->SetURL(KURL("https://example.com/"));
@@ -65,14 +64,12 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
reporting_proxy_ = std::make_unique<WorkerReportingProxy>();
}
- void TearDown() override {
- AnimationWorkletThread::ClearSharedBackingThread();
- }
-
- std::unique_ptr<AnimationWorkletThread> CreateAnimationWorkletThread(
+ std::unique_ptr<AnimationAndPaintWorkletThread>
+ CreateAnimationAndPaintWorkletThread(
AnimationWorkletProxyClient* proxy_client) {
- std::unique_ptr<AnimationWorkletThread> thread =
- AnimationWorkletThread::Create(*reporting_proxy_);
+ std::unique_ptr<AnimationAndPaintWorkletThread> thread =
+ AnimationAndPaintWorkletThread::CreateForAnimationWorklet(
+ *reporting_proxy_);
WorkerClients* clients = WorkerClients::Create();
if (proxy_client)
@@ -81,14 +78,15 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
Document* document = &GetDocument();
thread->Start(
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
- Vector<CSPHeaderAndType>(), document->GetReferrerPolicy(),
- document->GetSecurityOrigin(), document->IsSecureContext(),
- document->GetHttpsState(), clients, document->AddressSpace(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */, Vector<CSPHeaderAndType>(),
+ document->GetReferrerPolicy(), document->GetSecurityOrigin(),
+ document->IsSecureContext(), document->GetHttpsState(), clients,
+ document->AddressSpace(),
OriginTrialContext::GetTokens(document).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap),
- base::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
+ base::nullopt, std::make_unique<WorkerDevToolsParams>(),
ParentExecutionContextTaskRunners::Create());
return thread;
}
@@ -99,7 +97,7 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
// the worklet once the task completion is signaled.
void RunTestOnWorkletThread(TestCalback callback) {
std::unique_ptr<WorkerThread> worklet =
- CreateAnimationWorkletThread(nullptr);
+ CreateAnimationAndPaintWorkletThread(nullptr);
WaitableEvent waitable_event;
PostCrossThreadTask(
*worklet->GetTaskRunner(TaskType::kInternalTest), FROM_HERE,
@@ -116,7 +114,7 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
WorkerThread* thread,
WaitableEvent* waitable_event) {
ASSERT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAnimationWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AnimationWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
ASSERT_TRUE(script_state);
@@ -130,7 +128,7 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
void RunBasicParsingTestOnWorklet(WorkerThread* thread,
WaitableEvent* waitable_event) {
ASSERT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAnimationWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AnimationWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
ASSERT_TRUE(script_state);
@@ -175,7 +173,7 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
void RunConstructAndAnimateTestOnWorklet(WorkerThread* thread,
WaitableEvent* waitable_event) {
ASSERT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAnimationWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AnimationWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
ASSERT_TRUE(script_state);
@@ -222,7 +220,7 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
cc::WorkletAnimationId animation_id = {1, 1};
AnimationWorkletInput state;
state.added_and_updated_animations.emplace_back(animation_id, "test", 5000,
- nullptr);
+ nullptr, 1);
std::unique_ptr<AnimationWorkletOutput> output =
global_scope->Mutate(state);
@@ -258,29 +256,30 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
ASSERT_TRUE(isolate);
ScriptState::Scope scope(script_state);
- global_scope->ScriptController()->Evaluate(ScriptSourceCode(
- R"JS(
+ global_scope->ScriptController()->Evaluate(
+ ScriptSourceCode(
+ R"JS(
registerAnimator('test', class {
animate (currentTime, effect) {
effect.localTime = 123;
}
});
)JS"),
- kSharableCrossOrigin);
+ SanitizeScriptErrors::kDoNotSanitize);
// Passing a new input state with a new animation id should cause the
// worklet to create and animate an animator.
cc::WorkletAnimationId animation_id = {1, 1};
AnimationWorkletInput state;
state.added_and_updated_animations.emplace_back(animation_id, "test", 5000,
- nullptr);
+ nullptr, 1);
std::unique_ptr<AnimationWorkletOutput> output =
global_scope->Mutate(state);
EXPECT_TRUE(output);
EXPECT_EQ(output->animations.size(), 1ul);
- EXPECT_EQ(output->animations[0].local_time,
+ EXPECT_EQ(output->animations[0].local_times[0],
WTF::TimeDelta::FromMillisecondsD(123));
waitable_event->Signal();
@@ -304,15 +303,16 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
EXPECT_EQ(global_scope->GetAnimatorsSizeForTest(), 0u);
ScriptState::Scope scope(script_state);
- global_scope->ScriptController()->Evaluate(ScriptSourceCode(
- R"JS(
+ global_scope->ScriptController()->Evaluate(
+ ScriptSourceCode(
+ R"JS(
registerAnimator('test', class {
animate (currentTime, effect) {
effect.localTime = 123;
}
});
)JS"),
- kSharableCrossOrigin);
+ SanitizeScriptErrors::kDoNotSanitize);
cc::WorkletAnimationId animation_id = {1, 1};
AnimationWorkletInput state;
@@ -329,7 +329,7 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
EXPECT_EQ(global_scope->GetAnimatorsSizeForTest(), 0u);
state.added_and_updated_animations.push_back(
- {animation_id, "test", 5000, nullptr});
+ {animation_id, "test", 5000, nullptr, 1});
EXPECT_EQ(state.added_and_updated_animations.size(), 1u);
global_scope->Mutate(state);
EXPECT_EQ(global_scope->GetAnimatorsSizeForTest(), 1u);
@@ -353,20 +353,21 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
EXPECT_EQ(global_scope->GetAnimatorsSizeForTest(), 0u);
ScriptState::Scope scope(script_state);
- global_scope->ScriptController()->Evaluate(ScriptSourceCode(
- R"JS(
+ global_scope->ScriptController()->Evaluate(
+ ScriptSourceCode(
+ R"JS(
registerAnimator('test', class {
animate (currentTime, effect) {
effect.localTime = 123;
}
});
)JS"),
- kSharableCrossOrigin);
+ SanitizeScriptErrors::kDoNotSanitize);
cc::WorkletAnimationId animation_id = {1, 1};
AnimationWorkletInput state;
state.added_and_updated_animations.push_back(
- {animation_id, "test", 5000, nullptr});
+ {animation_id, "test", 5000, nullptr, 1});
EXPECT_EQ(state.added_and_updated_animations.size(), 1u);
global_scope->Mutate(state);
EXPECT_EQ(global_scope->GetAnimatorsSizeForTest(), 1u);
@@ -398,8 +399,8 @@ class AnimationWorkletGlobalScopeTest : public PageTestBase {
const KURL js_url("https://example.com/worklet.js");
ScriptModule module = ScriptModule::Compile(
script_state->GetIsolate(), source_code, js_url, js_url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
EXPECT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(script_state);
EXPECT_TRUE(exception.IsEmpty());
@@ -440,7 +441,7 @@ TEST_F(AnimationWorkletGlobalScopeTest,
MockAnimationWorkletProxyClient* proxy_client =
new MockAnimationWorkletProxyClient();
std::unique_ptr<WorkerThread> worklet =
- CreateAnimationWorkletThread(proxy_client);
+ CreateAnimationAndPaintWorkletThread(proxy_client);
// Animation worklet global scope (AWGS) should not register itself upon
// creation.
EXPECT_FALSE(proxy_client->did_set_global_scope());
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.cc b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.cc
index ab0cd3764d2..f7f6ff6a8c2 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_messaging_proxy.h"
#include "third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h"
-#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h"
+#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
namespace blink {
@@ -21,7 +21,8 @@ AnimationWorkletMessagingProxy::~AnimationWorkletMessagingProxy() = default;
std::unique_ptr<WorkerThread>
AnimationWorkletMessagingProxy::CreateWorkerThread() {
- return AnimationWorkletThread::Create(WorkletObjectProxy());
+ return AnimationAndPaintWorkletThread::CreateForAnimationWorklet(
+ WorkletObjectProxy());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.cc b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.cc
deleted file mode 100644
index 6f0476646ec..00000000000
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.cc
+++ /dev/null
@@ -1,72 +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 "third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h"
-
-#include "base/memory/ptr_util.h"
-#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
-#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
-#include "third_party/blink/renderer/core/workers/worklet_thread_holder.h"
-#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
-
-namespace blink {
-
-std::unique_ptr<AnimationWorkletThread> AnimationWorkletThread::Create(
- WorkerReportingProxy& worker_reporting_proxy) {
- TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("animation-worklet"),
- "AnimationWorkletThread::create");
- DCHECK(IsMainThread());
- return base::WrapUnique(new AnimationWorkletThread(worker_reporting_proxy));
-}
-
-template class WorkletThreadHolder<AnimationWorkletThread>;
-
-AnimationWorkletThread::AnimationWorkletThread(
- WorkerReportingProxy& worker_reporting_proxy)
- : WorkerThread(worker_reporting_proxy) {}
-
-AnimationWorkletThread::~AnimationWorkletThread() = default;
-
-WorkerBackingThread& AnimationWorkletThread::GetWorkerBackingThread() {
- return *WorkletThreadHolder<AnimationWorkletThread>::GetInstance()
- ->GetThread();
-}
-
-static void CollectAllGarbageOnThread(WaitableEvent* done_event) {
- blink::ThreadState::Current()->CollectAllGarbage();
- done_event->Signal();
-}
-
-void AnimationWorkletThread::CollectAllGarbage() {
- DCHECK(IsMainThread());
- WaitableEvent done_event;
- auto* holder = WorkletThreadHolder<AnimationWorkletThread>::GetInstance();
- if (!holder)
- return;
- holder->GetThread()->BackingThread().PostTask(
- FROM_HERE, CrossThreadBind(&CollectAllGarbageOnThread,
- CrossThreadUnretained(&done_event)));
- done_event.Wait();
-}
-
-void AnimationWorkletThread::EnsureSharedBackingThread() {
- WorkletThreadHolder<AnimationWorkletThread>::EnsureInstance(
- ThreadCreationParams(WebThreadType::kAnimationWorkletThread));
-}
-
-void AnimationWorkletThread::ClearSharedBackingThread() {
- WorkletThreadHolder<AnimationWorkletThread>::ClearInstance();
-}
-
-WorkerOrWorkletGlobalScope* AnimationWorkletThread::CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("animation-worklet"),
- "AnimationWorkletThread::CreateWorkerGlobalScope");
- return AnimationWorkletGlobalScope::Create(std::move(creation_params), this);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h b/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h
deleted file mode 100644
index 622a77127cf..00000000000
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h
+++ /dev/null
@@ -1,50 +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 THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_ANIMATION_WORKLET_THREAD_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_ANIMATION_WORKLET_THREAD_H_
-
-#include <memory>
-#include "third_party/blink/renderer/core/workers/worker_thread.h"
-#include "third_party/blink/renderer/modules/modules_export.h"
-
-namespace blink {
-
-class WorkerReportingProxy;
-
-// Represents the shared backing thread that is used by all animation worklets
-// and participates in the Blink garbage collection process.
-class MODULES_EXPORT AnimationWorkletThread final : public WorkerThread {
- public:
- static std::unique_ptr<AnimationWorkletThread> Create(
- WorkerReportingProxy&);
- ~AnimationWorkletThread() override;
-
- WorkerBackingThread& GetWorkerBackingThread() override;
-
- // The backing thread is cleared by ClearSharedBackingThread().
- void ClearWorkerBackingThread() override {}
-
- // This may block the main thread.
- static void CollectAllGarbage();
-
- static void EnsureSharedBackingThread();
- static void ClearSharedBackingThread();
-
- private:
- explicit AnimationWorkletThread(WorkerReportingProxy&);
-
- WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams>) final;
-
- bool IsOwningBackingThread() const override { return false; }
-
- WebThreadType GetThreadType() const override {
- return WebThreadType::kAnimationWorkletThread;
- }
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_ANIMATION_WORKLET_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animator.cc b/chromium/third_party/blink/renderer/modules/animationworklet/animator.cc
index 5faecda350b..a8c3fe6100d 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animator.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animator.cc
@@ -15,16 +15,19 @@ namespace blink {
Animator::Animator(v8::Isolate* isolate,
AnimatorDefinition* definition,
- v8::Local<v8::Value> instance)
+ v8::Local<v8::Value> instance,
+ int num_effects)
: definition_(definition),
instance_(isolate, instance),
- effect_(new EffectProxy()) {}
+ group_effect_(new WorkletGroupEffectProxy(num_effects)) {
+ DCHECK_GE(num_effects, 1);
+}
Animator::~Animator() = default;
void Animator::Trace(blink::Visitor* visitor) {
visitor->Trace(definition_);
- visitor->Trace(effect_);
+ visitor->Trace(group_effect_);
visitor->Trace(instance_);
}
@@ -46,8 +49,14 @@ bool Animator::Animate(
// Prepare arguments (i.e., current time and effect) and pass them to animate
// callback.
- v8::Local<v8::Value> v8_effect =
- ToV8(effect_, script_state->GetContext()->Global(), isolate);
+ v8::Local<v8::Value> v8_effect;
+ if (group_effect_->getChildren().size() == 1) {
+ v8_effect = ToV8(group_effect_->getChildren()[0],
+ script_state->GetContext()->Global(), isolate);
+ } else {
+ v8_effect =
+ ToV8(group_effect_, script_state->GetContext()->Global(), isolate);
+ }
v8::Local<v8::Value> v8_current_time =
ToV8(current_time, script_state->GetContext()->Global(), isolate);
@@ -62,8 +71,17 @@ bool Animator::Animate(
if (block.HasCaught())
return false;
- output->local_time = effect_->local_time();
+ output->local_times = GetLocalTimes();
return true;
}
+std::vector<base::Optional<TimeDelta>> Animator::GetLocalTimes() const {
+ std::vector<base::Optional<TimeDelta>> local_times;
+ local_times.reserve(group_effect_->getChildren().size());
+ for (const auto& effect : group_effect_->getChildren()) {
+ local_times.push_back(effect->local_time());
+ }
+ return local_times;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animator.h b/chromium/third_party/blink/renderer/modules/animationworklet/animator.h
index c37bf14d182..73e8e8c01c3 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animator.h
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/animator.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_ANIMATOR_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_ANIMATOR_H_
-#include "third_party/blink/renderer/modules/animationworklet/effect_proxy.h"
+#include "third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.h"
#include "third_party/blink/renderer/platform/bindings/name_client.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
@@ -25,7 +25,10 @@ class ScriptState;
class Animator final : public GarbageCollectedFinalized<Animator>,
public NameClient {
public:
- Animator(v8::Isolate*, AnimatorDefinition*, v8::Local<v8::Value> instance);
+ Animator(v8::Isolate*,
+ AnimatorDefinition*,
+ v8::Local<v8::Value> instance,
+ int num_effects);
~Animator();
void Trace(blink::Visitor*);
const char* NameInHeapSnapshot() const override { return "Animator"; }
@@ -36,9 +39,7 @@ class Animator final : public GarbageCollectedFinalized<Animator>,
bool Animate(ScriptState*,
double current_time,
AnimationWorkletDispatcherOutput::AnimationState*);
- base::Optional<TimeDelta> GetLastLocalTime() const {
- return effect_->local_time();
- }
+ std::vector<base::Optional<TimeDelta>> GetLocalTimes() const;
private:
// This object keeps the definition object, and animator instance alive.
@@ -46,7 +47,7 @@ class Animator final : public GarbageCollectedFinalized<Animator>,
TraceWrapperMember<AnimatorDefinition> definition_;
TraceWrapperV8Reference<v8::Value> instance_;
- Member<EffectProxy> effect_;
+ Member<WorkletGroupEffectProxy> group_effect_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.cc b/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.cc
index b3756c49021..21c490310a4 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.cc
@@ -45,7 +45,8 @@ CSSAnimationWorklet& CSSAnimationWorklet::From(LocalDOMWindow& window) {
CSSAnimationWorklet* supplement =
Supplement<LocalDOMWindow>::From<CSSAnimationWorklet>(window);
if (!supplement) {
- supplement = new CSSAnimationWorklet(window.GetFrame()->GetDocument());
+ supplement = MakeGarbageCollected<CSSAnimationWorklet>(
+ window.GetFrame()->GetDocument());
ProvideTo(window, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.h b/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.h
index 3593675cf88..f628f3fed92 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.h
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/css_animation_worklet.h
@@ -27,6 +27,8 @@ class MODULES_EXPORT CSSAnimationWorklet final
static AnimationWorklet* animationWorklet(ScriptState*);
+ explicit CSSAnimationWorklet(Document*);
+
void ContextDestroyed(ExecutionContext*) override;
void Trace(blink::Visitor*) override;
@@ -34,8 +36,6 @@ class MODULES_EXPORT CSSAnimationWorklet final
private:
static CSSAnimationWorklet& From(LocalDOMWindow&);
- explicit CSSAnimationWorklet(Document*);
-
Member<AnimationWorklet> animation_worklet_;
};
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc
index 0ce6e7feb26..1cb3c988cef 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc
@@ -136,26 +136,56 @@ base::Optional<CompositorElementId> GetCompositorScrollElementId(
// web concepts of 'block' and 'inline' direction into absolute vertical or
// horizontal directions.
//
+// This implements a subset of the conversions documented in
+// https://drafts.csswg.org/css-writing-modes-3/#logical-to-physical
+//
// TODO(smcgruer): If the writing mode of a scroller changes, we have to update
// any related cc::ScrollTimeline somehow.
CompositorScrollTimeline::ScrollDirection ConvertOrientation(
ScrollTimeline::ScrollDirection orientation,
- bool is_horizontal_writing_mode) {
- switch (orientation) {
- case ScrollTimeline::Block:
- return is_horizontal_writing_mode ? CompositorScrollTimeline::Vertical
- : CompositorScrollTimeline::Horizontal;
- case ScrollTimeline::Inline:
- return is_horizontal_writing_mode ? CompositorScrollTimeline::Horizontal
- : CompositorScrollTimeline::Vertical;
- case ScrollTimeline::Horizontal:
- return CompositorScrollTimeline::Horizontal;
- case ScrollTimeline::Vertical:
- return CompositorScrollTimeline::Vertical;
- default:
- NOTREACHED();
- return CompositorScrollTimeline::Vertical;
+ const ComputedStyle* style) {
+ // Easy cases; physical is always physical.
+ if (orientation == ScrollTimeline::Horizontal)
+ return CompositorScrollTimeline::ScrollRight;
+ if (orientation == ScrollTimeline::Vertical)
+ return CompositorScrollTimeline::ScrollDown;
+
+ // Harder cases; first work out which axis is which, and then for each check
+ // which edge we start at.
+
+ // writing-mode: horizontal-tb
+ bool is_horizontal_writing_mode =
+ style ? style->IsHorizontalWritingMode() : true;
+ // writing-mode: vertical-lr
+ bool is_flipped_lines_writing_mode =
+ style ? style->IsFlippedLinesWritingMode() : false;
+ // direction: ltr;
+ bool is_ltr_direction = style ? style->IsLeftToRightDirection() : true;
+
+ if (orientation == ScrollTimeline::Block) {
+ if (is_horizontal_writing_mode) {
+ // For horizontal writing mode, block is vertical. The starting edge is
+ // always the top.
+ return CompositorScrollTimeline::ScrollDown;
+ }
+ // For vertical writing mode, the block axis is horizontal. The starting
+ // edge depends on if we are lr or rl.
+ return is_flipped_lines_writing_mode ? CompositorScrollTimeline::ScrollRight
+ : CompositorScrollTimeline::ScrollLeft;
+ }
+
+ DCHECK_EQ(orientation, ScrollTimeline::Inline);
+ if (is_horizontal_writing_mode) {
+ // For horizontal writing mode, inline is horizontal. The starting edge
+ // depends on the directionality.
+ return is_ltr_direction ? CompositorScrollTimeline::ScrollRight
+ : CompositorScrollTimeline::ScrollLeft;
}
+ // For vertical writing mode, inline is vertical. The starting edge still
+ // depends on the directionality; whether it is vertical-lr or vertical-rl
+ // does not matter.
+ return is_ltr_direction ? CompositorScrollTimeline::ScrollDown
+ : CompositorScrollTimeline::ScrollUp;
}
// Converts a blink::ScrollTimeline into a cc::ScrollTimeline.
@@ -177,15 +207,32 @@ std::unique_ptr<CompositorScrollTimeline> ToCompositorScrollTimeline(
DCHECK(time_range.IsDouble());
// TODO(smcgruer): If the scroll source later gets a LayoutBox (e.g. was
- // display:none and now isn't), we need to update the compositor with the
- // writing mode to get the correct ScrollDirection conversion.
+ // display:none and now isn't), we need to update the compositor to have the
+ // correct orientation and start/end offset information.
LayoutBox* box = scroll_source->GetLayoutBox();
- CompositorScrollTimeline::ScrollDirection orientation =
- ConvertOrientation(scroll_timeline->GetOrientation(),
- box ? box->IsHorizontalWritingMode() : true);
- return std::make_unique<CompositorScrollTimeline>(element_id, orientation,
- time_range.GetAsDouble());
+ CompositorScrollTimeline::ScrollDirection orientation = ConvertOrientation(
+ scroll_timeline->GetOrientation(), box ? box->Style() : nullptr);
+
+ base::Optional<double> start_scroll_offset;
+ base::Optional<double> end_scroll_offset;
+ if (box) {
+ double current_offset;
+ double max_offset;
+ scroll_timeline->GetCurrentAndMaxOffset(box, current_offset, max_offset);
+
+ double resolved_start_scroll_offset = 0;
+ double resolved_end_scroll_offset = max_offset;
+ scroll_timeline->ResolveScrollStartAndEnd(box, max_offset,
+ resolved_start_scroll_offset,
+ resolved_end_scroll_offset);
+ start_scroll_offset = resolved_start_scroll_offset;
+ end_scroll_offset = resolved_end_scroll_offset;
+ }
+
+ return std::make_unique<CompositorScrollTimeline>(
+ element_id, orientation, start_scroll_offset, end_scroll_offset,
+ time_range.GetAsDouble());
}
void StartEffectOnCompositor(CompositorAnimation* animation,
@@ -262,9 +309,9 @@ WorkletAnimation* WorkletAnimation::Create(
AnimationTimeline* animation_timeline =
ConvertAnimationTimeline(document, timeline);
- WorkletAnimation* animation =
- new WorkletAnimation(id, animator_name, document, keyframe_effects,
- animation_timeline, std::move(options));
+ WorkletAnimation* animation = MakeGarbageCollected<WorkletAnimation>(
+ id, animator_name, document, keyframe_effects, animation_timeline,
+ std::move(options));
return animation;
}
@@ -291,6 +338,7 @@ WorkletAnimation::WorkletAnimation(
for (auto& effect : effects_) {
AnimationEffect* target_effect = effect;
target_effect->Attach(this);
+ local_times_.push_back(base::nullopt);
}
if (timeline_->IsScrollTimeline())
@@ -320,9 +368,12 @@ void WorkletAnimation::play(ExceptionState& exception_state) {
for (auto& effect : effects_) {
Element* target = effect->target();
DCHECK(target);
+ // TODO(yigu): Currently we have to keep a set of worklet animations in
+ // ElementAnimations so that the compositor knows that there are active
+ // worklet animations running. Ideally, this should be done via the regular
+ // Animation path, i.e., unify the logic between the two Animations.
+ // https://crbug.com/896249.
target->EnsureElementAnimations().GetWorkletAnimations().insert(this);
- // TODO(majidvp): This should be removed once worklet animation correctly
- // updates its effect timing. https://crbug.com/814851.
target->SetNeedsAnimationStyleRecalc();
}
}
@@ -338,7 +389,7 @@ void WorkletAnimation::cancel() {
DestroyCompositorAnimation();
}
- local_time_ = base::nullopt;
+ local_times_.Fill(base::nullopt);
start_time_ = base::nullopt;
running_on_main_thread_ = false;
// TODO(yigu): Because this animation has been detached and will not receive
@@ -354,9 +405,12 @@ void WorkletAnimation::cancel() {
for (auto& effect : effects_) {
Element* target = effect->target();
DCHECK(target);
+ // TODO(yigu): Currently we have to keep a set of worklet animations in
+ // ElementAnimations so that the compositor knows that there are active
+ // worklet animations running. Ideally, this should be done via the regular
+ // Animation path, i.e., unify the logic between the two Animations.
+ // https://crbug.com/896249.
target->EnsureElementAnimations().GetWorkletAnimations().erase(this);
- // TODO(majidvp): This should be removed once worklet animation correctly
- // updates its effect timing. https://crbug.com/814851.
target->SetNeedsAnimationStyleRecalc();
}
}
@@ -379,19 +433,15 @@ void WorkletAnimation::Update(TimingUpdateReason reason) {
if (play_state_ != Animation::kRunning)
return;
- if (!start_time_)
+ // ScrollTimeline animation doesn't require start_time_ to be set.
+ if (!start_time_ && !timeline_->IsScrollTimeline())
return;
- // TODO(crbug.com/756539): For now we use 0 as inherited time for compositor
- // worklet animations. Will need to get the inherited time from worklet
- // context.
- double inherited_time_seconds = 0;
-
- if (local_time_)
- inherited_time_seconds = local_time_->InSecondsF();
-
- for (auto& effect : effects_)
- effect->UpdateInheritedTime(inherited_time_seconds, reason);
+ DCHECK_EQ(effects_.size(), local_times_.size());
+ for (wtf_size_t i = 0; i < effects_.size(); ++i) {
+ effects_[i]->UpdateInheritedTime(
+ local_times_[i] ? local_times_[i]->InSecondsF() : NullValue(), reason);
+ }
}
bool WorkletAnimation::CheckCanStart(String* failure_message) {
@@ -419,16 +469,13 @@ void WorkletAnimation::UpdateCompositingState() {
DCHECK(play_state_ != Animation::kIdle && play_state_ != Animation::kUnset);
if (play_state_ == Animation::kPending) {
+#if DCHECK_IS_ON()
String warning_message;
DCHECK(CheckCanStart(&warning_message));
DCHECK(warning_message.IsEmpty());
- if (StartOnCompositor(&warning_message)) {
+#endif // DCHECK_IS_ON()
+ if (StartOnCompositor())
return;
- }
- String message = "The animation cannot be accelerated. Reason: ";
- message = message + warning_message;
- document_->AddConsoleMessage(ConsoleMessage::Create(
- kOtherMessageSource, kWarningMessageLevel, message));
StartOnMain();
} else if (play_state_ == Animation::kRunning) {
// TODO(majidvp): If keyframes have changed then it may be possible to now
@@ -452,13 +499,10 @@ void WorkletAnimation::StartOnMain() {
SetPlayState(Animation::kRunning);
}
-bool WorkletAnimation::StartOnCompositor(String* failure_message) {
+bool WorkletAnimation::StartOnCompositor() {
DCHECK(IsMainThread());
if (effects_.size() > 1) {
// Compositor doesn't support multiple effects but they can be run via main.
- *failure_message =
- "Multiple effects with composited properties are not currently "
- "supported on compositor";
return false;
}
@@ -466,10 +510,8 @@ bool WorkletAnimation::StartOnCompositor(String* failure_message) {
// TODO(crbug.com/836393): This should not be possible but it is currently
// happening and needs to be investigated/fixed.
- if (!target.GetComputedStyle()) {
- *failure_message = "The target element does not have style";
+ if (!target.GetComputedStyle())
return false;
- }
// CheckCanStartAnimationOnCompositor requires that the property-specific
// keyframe groups have been created. To ensure this we manually snapshot the
// frames in the target effect.
@@ -484,14 +526,11 @@ bool WorkletAnimation::StartOnCompositor(String* failure_message) {
if (!failure_code.Ok()) {
SetPlayState(Animation::kIdle);
- *failure_message = failure_code.reason;
return false;
}
- if (!CheckElementComposited(target)) {
- *failure_message = "The target element is not composited";
+ if (!CheckElementComposited(target))
return false;
- }
if (!compositor_animation_) {
compositor_animation_ = CompositorAnimation::CreateWorkletAnimation(
@@ -532,9 +571,28 @@ void WorkletAnimation::UpdateOnCompositor() {
}
if (timeline_->IsScrollTimeline()) {
- Element* scroll_source = ToScrollTimeline(timeline_)->scrollSource();
- compositor_animation_->UpdateScrollTimelineId(
- GetCompositorScrollElementId(*scroll_source));
+ Node* scroll_source = ToScrollTimeline(timeline_)->ResolvedScrollSource();
+ LayoutBox* box = scroll_source->GetLayoutBox();
+
+ base::Optional<double> start_scroll_offset;
+ base::Optional<double> end_scroll_offset;
+ if (box) {
+ double current_offset;
+ double max_offset;
+ ToScrollTimeline(timeline_)->GetCurrentAndMaxOffset(box, current_offset,
+ max_offset);
+
+ double resolved_start_scroll_offset = 0;
+ double resolved_end_scroll_offset = max_offset;
+ ToScrollTimeline(timeline_)->ResolveScrollStartAndEnd(
+ box, max_offset, resolved_start_scroll_offset,
+ resolved_end_scroll_offset);
+ start_scroll_offset = resolved_start_scroll_offset;
+ end_scroll_offset = resolved_end_scroll_offset;
+ }
+ compositor_animation_->UpdateScrollTimeline(
+ GetCompositorScrollElementId(*scroll_source), start_scroll_offset,
+ end_scroll_offset);
}
}
@@ -561,6 +619,17 @@ bool WorkletAnimation::IsActiveAnimation() const {
return IsActive(play_state_);
}
+base::Optional<double> WorkletAnimation::CurrentTime() const {
+ bool is_null;
+ double timeline_time = timeline_->currentTime(is_null);
+ if (is_null)
+ return base::nullopt;
+ if (timeline_->IsScrollTimeline())
+ return timeline_time;
+ DCHECK(start_time_);
+ return timeline_time - start_time_->InSecondsF();
+}
+
void WorkletAnimation::UpdateInputState(
AnimationWorkletDispatcherInput* input_state) {
if (!running_on_main_thread_) {
@@ -571,20 +640,23 @@ void WorkletAnimation::UpdateInputState(
bool was_active = IsActive(last_play_state_);
bool is_active = IsActive(play_state_);
- DCHECK(start_time_);
+ // ScrollTimeline animation doesn't require start_time_ to be set.
+ DCHECK(start_time_ || timeline_->IsScrollTimeline());
DCHECK(last_current_time_ || !was_active);
- bool is_null;
- double current_time = timeline_->currentTime(is_null);
+ double current_time =
+ CurrentTime().value_or(std::numeric_limits<double>::quiet_NaN());
bool did_time_change =
!last_current_time_ || current_time != last_current_time_->InSecondsF();
+ // TODO(yigu): If current_time becomes newly unresolved and last_current_time_
+ // is resolved, we apply the last current time to the animation if the scroll
+ // timeline becomes newly inactive. See https://crbug.com/906050.
last_current_time_ = base::TimeDelta::FromSecondsD(current_time);
-
if (!was_active && is_active) {
input_state->Add(
{id_,
std::string(animator_name_.Ascii().data(), animator_name_.length()),
- current_time, CloneOptions()});
+ current_time, CloneOptions(), effects_.size()});
} else if (was_active && is_active) {
// Skip if the input time is not changed.
if (did_time_change)
@@ -598,7 +670,13 @@ void WorkletAnimation::UpdateInputState(
void WorkletAnimation::SetOutputState(
const AnimationWorkletOutput::AnimationState& state) {
DCHECK(state.worklet_animation_id == id_);
- local_time_ = state.local_time;
+ // The local times for composited effects, i.e. not running on main, are
+ // peeked and set via the main thread. If an animator is not ready upon
+ // peeking state.local_times will be empty.
+ DCHECK(local_times_.size() == state.local_times.size() ||
+ !running_on_main_thread_);
+ for (wtf_size_t i = 0; i < state.local_times.size(); ++i)
+ local_times_[i] = state.local_times[i];
}
void WorkletAnimation::Dispose() {
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.h b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.h
index c8c6d5a22da..e680957199f 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.h
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation.h
@@ -62,6 +62,12 @@ class MODULES_EXPORT WorkletAnimation : public WorkletAnimationBase,
scoped_refptr<SerializedScriptValue>,
ExceptionState&);
+ WorkletAnimation(WorkletAnimationId id,
+ const String& animator_name,
+ Document&,
+ const HeapVector<Member<KeyframeEffect>>&,
+ AnimationTimeline*,
+ scoped_refptr<SerializedScriptValue>);
~WorkletAnimation() override = default;
AnimationTimeline* timeline() { return timeline_; }
@@ -119,19 +125,12 @@ class MODULES_EXPORT WorkletAnimation : public WorkletAnimationBase,
void Trace(blink::Visitor*) override;
private:
- WorkletAnimation(WorkletAnimationId id,
- const String& animator_name,
- Document&,
- const HeapVector<Member<KeyframeEffect>>&,
- AnimationTimeline*,
- scoped_refptr<SerializedScriptValue>);
void DestroyCompositorAnimation();
// Attempts to start the animation on the compositor side, returning true if
// it succeeds or false otherwise. If false is returned and the animation
- // cannot be started on main and failure_message was non-null, failure_message
- // may be filled with an error description.
- bool StartOnCompositor(String* failure_message);
+ // cannot be started on main.
+ bool StartOnCompositor();
void StartOnMain();
bool CheckCanStart(String* failure_message);
void SetStartTimeToNow();
@@ -146,6 +145,7 @@ class MODULES_EXPORT WorkletAnimation : public WorkletAnimationBase,
void SetPlayState(const Animation::AnimationPlayState& state) {
play_state_ = state;
}
+ base::Optional<double> CurrentTime() const;
unsigned sequence_number_;
@@ -156,7 +156,7 @@ class MODULES_EXPORT WorkletAnimation : public WorkletAnimationBase,
Animation::AnimationPlayState last_play_state_;
// Start time in ms.
base::Optional<base::TimeDelta> start_time_;
- base::Optional<base::TimeDelta> local_time_;
+ Vector<base::Optional<base::TimeDelta>> local_times_;
// We use this to skip updating if current time has not changed since last
// update.
base::Optional<base::TimeDelta> last_current_time_;
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation_test.cc b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation_test.cc
index 225c0807761..e9239db8c4b 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation_test.cc
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_animation_test.cc
@@ -10,7 +10,9 @@
#include "third_party/blink/renderer/core/animation/element_animations.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect_model.h"
+#include "third_party/blink/renderer/core/animation/scroll_timeline.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
@@ -39,12 +41,16 @@ KeyframeEffect* CreateKeyframeEffect(Element* element) {
return KeyframeEffect::Create(element, CreateEffectModel(), timing);
}
-WorkletAnimation* CreateWorkletAnimation(ScriptState* script_state,
- Element* element) {
+WorkletAnimation* CreateWorkletAnimation(
+ ScriptState* script_state,
+ Element* element,
+ ScrollTimeline* scroll_timeline = nullptr) {
AnimationEffectOrAnimationEffectSequence effects;
AnimationEffect* effect = CreateKeyframeEffect(element);
effects.SetAnimationEffect(effect);
DocumentTimelineOrScrollTimeline timeline;
+ if (scroll_timeline)
+ timeline.SetScrollTimeline(scroll_timeline);
scoped_refptr<SerializedScriptValue> options;
ScriptState::Scope scope(script_state);
@@ -95,4 +101,84 @@ TEST_F(WorkletAnimationTest, StyleHasCurrentAnimation) {
EXPECT_EQ(true, style->HasCurrentOpacityAnimation());
}
+TEST_F(WorkletAnimationTest,
+ CurrentTimeFromDocumentTimelineIsOffsetByStartTime) {
+ GetDocument().GetAnimationClock().ResetTimeForTesting();
+ double error = base::TimeDelta::FromMicrosecondsD(1).InMillisecondsF();
+ WorkletAnimationId id = worklet_animation_->GetWorkletAnimationId();
+ base::TimeTicks first_ticks =
+ base::TimeTicks() + base::TimeDelta::FromMillisecondsD(111);
+ base::TimeTicks second_ticks =
+ base::TimeTicks() + base::TimeDelta::FromMillisecondsD(111 + 123.4);
+
+ GetDocument().GetAnimationClock().UpdateTime(first_ticks);
+ DummyExceptionStateForTesting exception_state;
+ worklet_animation_->play(exception_state);
+ worklet_animation_->UpdateCompositingState();
+
+ std::unique_ptr<AnimationWorkletDispatcherInput> state =
+ std::make_unique<AnimationWorkletDispatcherInput>();
+ worklet_animation_->UpdateInputState(state.get());
+ // First state request sets the start time and thus current time should be 0.
+ std::unique_ptr<AnimationWorkletInput> input =
+ state->TakeWorkletState(id.scope_id);
+ EXPECT_NEAR(0, input->added_and_updated_animations[0].current_time, error);
+ state.reset(new AnimationWorkletDispatcherInput);
+ GetDocument().GetAnimationClock().UpdateTime(second_ticks);
+ worklet_animation_->UpdateInputState(state.get());
+ input = state->TakeWorkletState(id.scope_id);
+ EXPECT_NEAR(123.4, input->updated_animations[0].current_time, error);
+}
+
+TEST_F(WorkletAnimationTest,
+ CurrentTimeFromScrollTimelineNotOffsetByStartTime) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #scroller { overflow: scroll; width: 100px; height: 100px; }
+ #spacer { width: 200px; height: 200px; }
+ </style>
+ <div id='scroller'>
+ <div id ='spacer'></div>
+ </div>
+ )HTML");
+
+ LayoutBoxModelObject* scroller =
+ ToLayoutBoxModelObject(GetLayoutObjectByElementId("scroller"));
+ ASSERT_TRUE(scroller);
+ ASSERT_TRUE(scroller->HasOverflowClip());
+ PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea();
+ ASSERT_TRUE(scrollable_area);
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 20), kProgrammaticScroll);
+ ScrollTimelineOptions* options = ScrollTimelineOptions::Create();
+ DoubleOrScrollTimelineAutoKeyword time_range =
+ DoubleOrScrollTimelineAutoKeyword::FromDouble(100);
+ options->setTimeRange(time_range);
+ options->setScrollSource(GetElementById("scroller"));
+ ScrollTimeline* scroll_timeline =
+ ScrollTimeline::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+ WorkletAnimation* worklet_animation =
+ CreateWorkletAnimation(GetScriptState(), element_, scroll_timeline);
+ WorkletAnimationId id = worklet_animation->GetWorkletAnimationId();
+
+ DummyExceptionStateForTesting exception_state;
+ worklet_animation->play(exception_state);
+ worklet_animation->UpdateCompositingState();
+
+ double error = base::TimeDelta::FromMicrosecondsD(1).InMillisecondsF();
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 40), kProgrammaticScroll);
+ std::unique_ptr<AnimationWorkletDispatcherInput> state =
+ std::make_unique<AnimationWorkletDispatcherInput>();
+ worklet_animation->UpdateInputState(state.get());
+ std::unique_ptr<AnimationWorkletInput> input =
+ state->TakeWorkletState(id.scope_id);
+
+ EXPECT_NEAR(40, input->added_and_updated_animations[0].current_time, error);
+ state.reset(new AnimationWorkletDispatcherInput);
+
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 70), kProgrammaticScroll);
+ worklet_animation->UpdateInputState(state.get());
+ input = state->TakeWorkletState(id.scope_id);
+ EXPECT_NEAR(70, input->updated_animations[0].current_time, error);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.cc b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.cc
new file mode 100644
index 00000000000..65b1e04e784
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.cc
@@ -0,0 +1,20 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.h"
+
+namespace blink {
+
+WorkletGroupEffectProxy::WorkletGroupEffectProxy(int num_effects)
+ : effects_(num_effects) {
+ for (int i = 0; i < num_effects; ++i)
+ effects_[i] = MakeGarbageCollected<EffectProxy>();
+}
+
+void WorkletGroupEffectProxy::Trace(blink::Visitor* visitor) {
+ visitor->Trace(effects_);
+ ScriptWrappable::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.h b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.h
new file mode 100644
index 00000000000..388534ca7b6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.h
@@ -0,0 +1,29 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_WORKLET_GROUP_EFFECT_PROXY_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_WORKLET_GROUP_EFFECT_PROXY_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/modules/animationworklet/effect_proxy.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+
+namespace blink {
+
+class MODULES_EXPORT WorkletGroupEffectProxy : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ explicit WorkletGroupEffectProxy(int num_effects);
+ HeapVector<Member<EffectProxy>>& getChildren() { return effects_; }
+ void Trace(blink::Visitor*) override;
+
+ private:
+ HeapVector<Member<EffectProxy>> effects_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_ANIMATIONWORKLET_WORKLET_GROUP_EFFECT_PROXY_H_
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl
new file mode 100644
index 00000000000..b2fd1ed91f9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/animationworklet/worklet_group_effect_proxy.idl
@@ -0,0 +1,9 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+[
+ Exposed=AnimationWorklet,
+ OriginTrialEnabled=AnimationWorklet
+] interface WorkletGroupEffectProxy {
+ sequence<EffectProxy> getChildren();
+};
diff --git a/chromium/third_party/blink/renderer/modules/app_banner/app_banner_controller.cc b/chromium/third_party/blink/renderer/modules/app_banner/app_banner_controller.cc
index 818b31ea2d8..83b52ef173c 100644
--- a/chromium/third_party/blink/renderer/modules/app_banner/app_banner_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/app_banner/app_banner_controller.cc
@@ -43,9 +43,9 @@ void AppBannerController::BannerPromptRequest(
mojom::AppBannerPromptReply reply =
frame_->DomWindow()->DispatchEvent(*BeforeInstallPromptEvent::Create(
- EventTypeNames::beforeinstallprompt, *frame_, std::move(service_ptr),
- std::move(event_request), platforms, require_gesture)) ==
- DispatchEventResult::kNotCanceled
+ event_type_names::kBeforeinstallprompt, *frame_,
+ std::move(service_ptr), std::move(event_request), platforms,
+ require_gesture)) == DispatchEventResult::kNotCanceled
? mojom::AppBannerPromptReply::NONE
: mojom::AppBannerPromptReply::CANCEL;
diff --git a/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.cc b/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.cc
index bd1c1a095ed..6a09b2fefe5 100644
--- a/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.cc
+++ b/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.cc
@@ -36,13 +36,13 @@ BeforeInstallPromptEvent::BeforeInstallPromptEvent(
BeforeInstallPromptEvent::BeforeInstallPromptEvent(
ExecutionContext* execution_context,
const AtomicString& name,
- const BeforeInstallPromptEventInit& init)
+ const BeforeInstallPromptEventInit* init)
: Event(name, init),
ContextClient(execution_context),
binding_(this),
require_gesture_(true) {
- if (init.hasPlatforms())
- platforms_ = init.platforms();
+ if (init->hasPlatforms())
+ platforms_ = init->platforms();
}
BeforeInstallPromptEvent::~BeforeInstallPromptEvent() = default;
@@ -97,7 +97,7 @@ ScriptPromise BeforeInstallPromptEvent::prompt(ScriptState* script_state) {
}
const AtomicString& BeforeInstallPromptEvent::InterfaceName() const {
- return EventNames::BeforeInstallPromptEvent;
+ return event_interface_names::kBeforeInstallPromptEvent;
}
void BeforeInstallPromptEvent::preventDefault() {
@@ -114,16 +114,16 @@ bool BeforeInstallPromptEvent::HasPendingActivity() const {
}
void BeforeInstallPromptEvent::BannerAccepted(const String& platform) {
- AppBannerPromptResult result;
- result.setPlatform(platform);
- result.setOutcome("accepted");
+ AppBannerPromptResult* result = AppBannerPromptResult::Create();
+ result->setPlatform(platform);
+ result->setOutcome("accepted");
user_choice_->Resolve(result);
}
void BeforeInstallPromptEvent::BannerDismissed() {
- AppBannerPromptResult result;
- result.setPlatform(g_empty_atom);
- result.setOutcome("dismissed");
+ AppBannerPromptResult* result = AppBannerPromptResult::Create();
+ result->setPlatform(g_empty_atom);
+ result->setOutcome("dismissed");
user_choice_->Resolve(result);
}
diff --git a/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.h b/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.h
index 58fb4e91f19..0d1a7eafacb 100644
--- a/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.h
+++ b/chromium/third_party/blink/renderer/modules/app_banner/before_install_prompt_event.h
@@ -23,7 +23,7 @@ class BeforeInstallPromptEventInit;
using UserChoiceProperty =
ScriptPromiseProperty<Member<BeforeInstallPromptEvent>,
- AppBannerPromptResult,
+ Member<AppBannerPromptResult>,
ToV8UndefinedGenerator>;
class BeforeInstallPromptEvent final
@@ -53,7 +53,7 @@ class BeforeInstallPromptEvent final
static BeforeInstallPromptEvent* Create(
ExecutionContext* execution_context,
const AtomicString& name,
- const BeforeInstallPromptEventInit& init) {
+ const BeforeInstallPromptEventInit* init) {
return new BeforeInstallPromptEvent(execution_context, name, init);
}
@@ -80,7 +80,7 @@ class BeforeInstallPromptEvent final
bool require_gesture);
BeforeInstallPromptEvent(ExecutionContext*,
const AtomicString& name,
- const BeforeInstallPromptEventInit&);
+ const BeforeInstallPromptEventInit*);
// mojom::blink::AppBannerEvent methods:
void BannerAccepted(const String& platform) override;
@@ -100,9 +100,9 @@ DEFINE_TYPE_CASTS(BeforeInstallPromptEvent,
Event,
event,
event->InterfaceName() ==
- EventNames::BeforeInstallPromptEvent,
+ event_interface_names::kBeforeInstallPromptEvent,
event.InterfaceName() ==
- EventNames::BeforeInstallPromptEvent);
+ event_interface_names::kBeforeInstallPromptEvent);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/app_banner/dom_window_installation.h b/chromium/third_party/blink/renderer/modules/app_banner/dom_window_installation.h
index 0a5a3631679..828487545d1 100644
--- a/chromium/third_party/blink/renderer/modules/app_banner/dom_window_installation.h
+++ b/chromium/third_party/blink/renderer/modules/app_banner/dom_window_installation.h
@@ -12,8 +12,9 @@ namespace blink {
class DOMWindowInstallation {
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(appinstalled);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(beforeinstallprompt);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(appinstalled, kAppinstalled);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(beforeinstallprompt,
+ kBeforeinstallprompt);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/BUILD.gn b/chromium/third_party/blink/renderer/modules/audio_output_devices/BUILD.gn
index b3ab4a3ab50..97d26c8da7e 100644
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/audio_output_devices/BUILD.gn
@@ -6,10 +6,6 @@ import("//third_party/blink/renderer/modules/modules.gni")
blink_modules_sources("audio_output_devices") {
sources = [
- "audio_output_device_client.cc",
- "audio_output_device_client.h",
- "audio_output_device_client_impl.cc",
- "audio_output_device_client_impl.h",
"html_media_element_audio_output_device.cc",
"html_media_element_audio_output_device.h",
"set_sink_id_callbacks.cc",
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.cc b/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.cc
deleted file mode 100644
index fde89244bde..00000000000
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.cc
+++ /dev/null
@@ -1,36 +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 "third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h"
-
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-
-namespace blink {
-
-AudioOutputDeviceClient::AudioOutputDeviceClient(LocalFrame& frame)
- : Supplement<LocalFrame>(frame) {}
-
-const char AudioOutputDeviceClient::kSupplementName[] =
- "AudioOutputDeviceClient";
-
-AudioOutputDeviceClient* AudioOutputDeviceClient::From(Document& document) {
- if (!document.GetFrame())
- return nullptr;
-
- return Supplement<LocalFrame>::From<AudioOutputDeviceClient>(
- document.GetFrame());
-}
-
-void ProvideAudioOutputDeviceClientTo(LocalFrame& frame,
- AudioOutputDeviceClient* client) {
- Supplement<LocalFrame>::ProvideTo(frame, client);
-}
-
-void AudioOutputDeviceClient::Trace(blink::Visitor* visitor) {
- Supplement<LocalFrame>::Trace(visitor);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h b/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h
deleted file mode 100644
index ac712d54519..00000000000
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_AUDIO_OUTPUT_DEVICES_AUDIO_OUTPUT_DEVICE_CLIENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_AUDIO_OUTPUT_DEVICES_AUDIO_OUTPUT_DEVICE_CLIENT_H_
-
-#include <memory>
-#include "third_party/blink/public/platform/web_set_sink_id_callbacks.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/modules/modules_export.h"
-#include "third_party/blink/renderer/platform/supplementable.h"
-
-namespace blink {
-
-class Document;
-class WebString;
-
-class MODULES_EXPORT AudioOutputDeviceClient : public Supplement<LocalFrame> {
- public:
- static const char kSupplementName[];
-
- explicit AudioOutputDeviceClient(LocalFrame&);
- virtual ~AudioOutputDeviceClient() = default;
-
- // Checks that a given sink exists and has permissions to be used from the
- // origin of the current frame.
- virtual void CheckIfAudioSinkExistsAndIsAuthorized(
- Document&,
- const WebString& sink_id,
- std::unique_ptr<WebSetSinkIdCallbacks>) = 0;
-
- void Trace(blink::Visitor*) override;
-
- // Supplement requirements.
- static AudioOutputDeviceClient* From(Document&);
-};
-
-MODULES_EXPORT void ProvideAudioOutputDeviceClientTo(LocalFrame&,
- AudioOutputDeviceClient*);
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_AUDIO_OUTPUT_DEVICES_AUDIO_OUTPUT_DEVICE_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.cc b/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.cc
deleted file mode 100644
index 26012a3ae68..00000000000
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.cc
+++ /dev/null
@@ -1,30 +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 "third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.h"
-
-#include <memory>
-#include "third_party/blink/public/web/web_local_frame_client.h"
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
-
-namespace blink {
-
-AudioOutputDeviceClientImpl::AudioOutputDeviceClientImpl(LocalFrame& frame)
- : AudioOutputDeviceClient(frame) {}
-
-AudioOutputDeviceClientImpl::~AudioOutputDeviceClientImpl() = default;
-
-void AudioOutputDeviceClientImpl::CheckIfAudioSinkExistsAndIsAuthorized(
- Document& document,
- const WebString& sink_id,
- std::unique_ptr<WebSetSinkIdCallbacks> callbacks) {
- WebLocalFrameImpl* web_frame =
- WebLocalFrameImpl::FromFrame(document.GetFrame());
- web_frame->Client()->CheckIfAudioSinkExistsAndIsAuthorized(
- sink_id, callbacks.release());
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.h b/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.h
deleted file mode 100644
index 6d42f29402d..00000000000
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_AUDIO_OUTPUT_DEVICES_AUDIO_OUTPUT_DEVICE_CLIENT_IMPL_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_AUDIO_OUTPUT_DEVICES_AUDIO_OUTPUT_DEVICE_CLIENT_IMPL_H_
-
-#include <memory>
-#include "third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h"
-#include "third_party/blink/renderer/modules/modules_export.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-
-namespace blink {
-
-class MODULES_EXPORT AudioOutputDeviceClientImpl
- : public GarbageCollectedFinalized<AudioOutputDeviceClientImpl>,
- public AudioOutputDeviceClient {
- USING_GARBAGE_COLLECTED_MIXIN(AudioOutputDeviceClientImpl);
- WTF_MAKE_NONCOPYABLE(AudioOutputDeviceClientImpl);
-
- public:
- explicit AudioOutputDeviceClientImpl(LocalFrame&);
-
- ~AudioOutputDeviceClientImpl() override;
-
- // AudioOutputDeviceClient implementation.
- void CheckIfAudioSinkExistsAndIsAuthorized(
- Document&,
- const WebString& sink_id,
- std::unique_ptr<WebSetSinkIdCallbacks>) override;
-
- // GarbageCollectedFinalized implementation.
- void Trace(blink::Visitor* visitor) override {
- AudioOutputDeviceClient::Trace(visitor);
- }
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_AUDIO_OUTPUT_DEVICES_AUDIO_OUTPUT_DEVICE_CLIENT_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.cc b/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.cc
index 76e72a8ea2c..369c1242759 100644
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.cc
+++ b/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.cc
@@ -8,11 +8,12 @@
#include <utility>
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/web/web_local_frame_client.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/modules/audio_output_devices/set_sink_id_callbacks.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
@@ -74,23 +75,26 @@ void SetSinkIdResolver::TimerFired(TimerBase* timer) {
if (web_media_player) {
// Using release() to transfer ownership because |webMediaPlayer| is a
// platform object that takes raw pointers.
- web_media_player->SetSinkId(sink_id_,
- callbacks.release());
- } else {
- auto& document = *To<Document>(context);
- if (AudioOutputDeviceClient* client =
- AudioOutputDeviceClient::From(document)) {
- client->CheckIfAudioSinkExistsAndIsAuthorized(document, sink_id_,
- std::move(callbacks));
- } else {
- // The context has been detached. Impossible to get a security origin to
- // check.
- DCHECK(context->IsContextDestroyed());
- Reject(DOMException::Create(
- DOMExceptionCode::kSecurityError,
- "Impossible to authorize device for detached context"));
- }
+ web_media_player->SetSinkId(sink_id_, std::move(callbacks));
+ return;
}
+
+ if (!context) {
+ // Detached contexts shouldn't be playing audio. Note that despite this
+ // explicit Reject(), any associated JS callbacks will never be called
+ // because the context is already detached...
+ Reject(DOMException::Create(
+ DOMExceptionCode::kSecurityError,
+ "Impossible to authorize device for detached context"));
+ return;
+ }
+
+ // This is associated with an HTML element, so the context must be a Document.
+ auto& document = To<Document>(*context);
+ WebLocalFrameImpl* web_frame =
+ WebLocalFrameImpl::FromFrame(document.GetFrame());
+ web_frame->Client()->CheckIfAudioSinkExistsAndIsAuthorized(
+ sink_id_, std::move(callbacks));
}
void SetSinkIdResolver::Trace(blink::Visitor* visitor) {
@@ -100,8 +104,7 @@ void SetSinkIdResolver::Trace(blink::Visitor* visitor) {
} // namespace
-HTMLMediaElementAudioOutputDevice::HTMLMediaElementAudioOutputDevice()
- : sink_id_("") {}
+HTMLMediaElementAudioOutputDevice::HTMLMediaElementAudioOutputDevice() {}
String HTMLMediaElementAudioOutputDevice::sinkId(HTMLMediaElement& element) {
HTMLMediaElementAudioOutputDevice& aod_element =
@@ -137,7 +140,7 @@ HTMLMediaElementAudioOutputDevice& HTMLMediaElementAudioOutputDevice::From(
Supplement<HTMLMediaElement>::From<HTMLMediaElementAudioOutputDevice>(
element);
if (!supplement) {
- supplement = new HTMLMediaElementAudioOutputDevice();
+ supplement = MakeGarbageCollected<HTMLMediaElementAudioOutputDevice>();
ProvideTo(element, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.h b/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.h
index 3920b7781f1..1e155cf2d92 100644
--- a/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.h
+++ b/chromium/third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.h
@@ -25,6 +25,8 @@ class MODULES_EXPORT HTMLMediaElementAudioOutputDevice final
public:
static const char kSupplementName[];
+ HTMLMediaElementAudioOutputDevice();
+
void Trace(blink::Visitor*) override;
static String sinkId(HTMLMediaElement&);
static ScriptPromise setSinkId(ScriptState*,
@@ -34,8 +36,6 @@ class MODULES_EXPORT HTMLMediaElementAudioOutputDevice final
void setSinkId(const String&);
private:
- HTMLMediaElementAudioOutputDevice();
-
String sink_id_;
};
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn b/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn
index 9b7f031e89c..5dec3654ced 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn
@@ -20,8 +20,6 @@ blink_modules_sources("background_fetch") {
"background_fetch_record.h",
"background_fetch_registration.cc",
"background_fetch_registration.h",
- "background_fetch_settled_fetch.cc",
- "background_fetch_settled_fetch.h",
"background_fetch_type_converters.cc",
"background_fetch_type_converters.h",
"background_fetch_update_ui_event.cc",
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc
index 022104ceead..fba9ac808ae 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc
@@ -6,8 +6,6 @@
#include <utility>
#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_options.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h"
@@ -49,26 +47,26 @@ void BackgroundFetchBridge::GetIconDisplaySize(
void BackgroundFetchBridge::MatchRequests(
const String& developer_id,
const String& unique_id,
- base::Optional<WebServiceWorkerRequest> request_to_match,
+ mojom::blink::FetchAPIRequestPtr request_to_match,
mojom::blink::QueryParamsPtr cache_query_params,
bool match_all,
mojom::blink::BackgroundFetchService::MatchRequestsCallback callback) {
GetService()->MatchRequests(
- GetSupplementable()->WebRegistration()->RegistrationId(), developer_id,
- unique_id, std::move(request_to_match), std::move(cache_query_params),
- match_all, std::move(callback));
+ GetSupplementable()->RegistrationId(), developer_id, unique_id,
+ std::move(request_to_match), std::move(cache_query_params), match_all,
+ std::move(callback));
}
void BackgroundFetchBridge::Fetch(
const String& developer_id,
- Vector<WebServiceWorkerRequest> requests,
+ Vector<mojom::blink::FetchAPIRequestPtr> requests,
mojom::blink::BackgroundFetchOptionsPtr options,
const SkBitmap& icon,
mojom::blink::BackgroundFetchUkmDataPtr ukm_data,
RegistrationCallback callback) {
GetService()->Fetch(
- GetSupplementable()->WebRegistration()->RegistrationId(), developer_id,
- std::move(requests), std::move(options), icon, std::move(ukm_data),
+ GetSupplementable()->RegistrationId(), developer_id, std::move(requests),
+ std::move(options), icon, std::move(ukm_data),
WTF::Bind(&BackgroundFetchBridge::DidGetRegistration,
WrapPersistent(this), WTF::Passed(std::move(callback))));
}
@@ -76,8 +74,8 @@ void BackgroundFetchBridge::Fetch(
void BackgroundFetchBridge::Abort(const String& developer_id,
const String& unique_id,
AbortCallback callback) {
- GetService()->Abort(GetSupplementable()->WebRegistration()->RegistrationId(),
- developer_id, unique_id, std::move(callback));
+ GetService()->Abort(GetSupplementable()->RegistrationId(), developer_id,
+ unique_id, std::move(callback));
}
void BackgroundFetchBridge::UpdateUI(const String& developer_id,
@@ -91,15 +89,14 @@ void BackgroundFetchBridge::UpdateUI(const String& developer_id,
return;
}
- GetService()->UpdateUI(
- GetSupplementable()->WebRegistration()->RegistrationId(), developer_id,
- unique_id, title, icon, std::move(callback));
+ GetService()->UpdateUI(GetSupplementable()->RegistrationId(), developer_id,
+ unique_id, title, icon, std::move(callback));
}
void BackgroundFetchBridge::GetRegistration(const String& developer_id,
RegistrationCallback callback) {
GetService()->GetRegistration(
- GetSupplementable()->WebRegistration()->RegistrationId(), developer_id,
+ GetSupplementable()->RegistrationId(), developer_id,
WTF::Bind(&BackgroundFetchBridge::DidGetRegistration,
WrapPersistent(this), WTF::Passed(std::move(callback))));
}
@@ -121,9 +118,8 @@ void BackgroundFetchBridge::DidGetRegistration(
}
void BackgroundFetchBridge::GetDeveloperIds(GetDeveloperIdsCallback callback) {
- GetService()->GetDeveloperIds(
- GetSupplementable()->WebRegistration()->RegistrationId(),
- std::move(callback));
+ GetService()->GetDeveloperIds(GetSupplementable()->RegistrationId(),
+ std::move(callback));
}
void BackgroundFetchBridge::AddRegistrationObserver(
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h
index f295ce6d1c7..1ca427abf8f 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h
@@ -17,7 +17,6 @@
namespace blink {
class BackgroundFetchRegistration;
-class WebServiceWorkerRequest;
// The bridge is responsible for establishing and maintaining the Mojo
// connection to the BackgroundFetchService. It's keyed on an active Service
@@ -51,7 +50,7 @@ class BackgroundFetchBridge final
// for the sequence of |requests|. The |callback| will be invoked when the
// registration has been created.
void Fetch(const String& developer_id,
- Vector<WebServiceWorkerRequest> requests,
+ Vector<mojom::blink::FetchAPIRequestPtr> requests,
mojom::blink::BackgroundFetchOptionsPtr options,
const SkBitmap& icon,
mojom::blink::BackgroundFetchUkmDataPtr ukm_data,
@@ -69,7 +68,7 @@ class BackgroundFetchBridge final
void MatchRequests(
const String& developer_id,
const String& unique_id,
- base::Optional<WebServiceWorkerRequest> request_to_match,
+ mojom::blink::FetchAPIRequestPtr request_to_match,
mojom::blink::QueryParamsPtr cache_query_params,
bool match_all,
mojom::blink::BackgroundFetchService::MatchRequestsCallback callback);
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc
index 0dfa3935bd9..a6e899abb96 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc
@@ -6,16 +6,16 @@
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h"
-#include "third_party/blink/renderer/modules/event_modules_names.h"
+#include "third_party/blink/renderer/modules/event_interface_modules_names.h"
namespace blink {
BackgroundFetchEvent::BackgroundFetchEvent(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer,
+ const BackgroundFetchEventInit* initializer,
WaitUntilObserver* observer)
: ExtendableEvent(type, initializer, observer),
- registration_(initializer.registration()) {}
+ registration_(initializer->registration()) {}
BackgroundFetchEvent::~BackgroundFetchEvent() = default;
@@ -24,7 +24,7 @@ BackgroundFetchRegistration* BackgroundFetchEvent::registration() const {
}
const AtomicString& BackgroundFetchEvent::InterfaceName() const {
- return EventNames::BackgroundFetchEvent;
+ return event_interface_names::kBackgroundFetchEvent;
}
void BackgroundFetchEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h
index 9656152cdd4..5712e9f7dd7 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h
@@ -23,13 +23,13 @@ class MODULES_EXPORT BackgroundFetchEvent : public ExtendableEvent {
public:
static BackgroundFetchEvent* Create(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer) {
+ const BackgroundFetchEventInit* initializer) {
return new BackgroundFetchEvent(type, initializer, nullptr /* observer */);
}
static BackgroundFetchEvent* Create(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer,
+ const BackgroundFetchEventInit* initializer,
WaitUntilObserver* observer) {
return new BackgroundFetchEvent(type, initializer, observer);
}
@@ -46,7 +46,7 @@ class MODULES_EXPORT BackgroundFetchEvent : public ExtendableEvent {
protected:
BackgroundFetchEvent(const AtomicString& type,
- const BackgroundFetchEventInit& initializer,
+ const BackgroundFetchEventInit* initializer,
WaitUntilObserver* observer);
// Corresponds to the 'registration' attribute in the idl.
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc
index 813131fc695..efae8f56d97 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc
@@ -22,6 +22,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/string_impl.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -47,10 +48,11 @@ BackgroundFetchIconLoader::~BackgroundFetchIconLoader() {
DCHECK(stopped_ || icon_callback_.is_null());
}
-void BackgroundFetchIconLoader::Start(BackgroundFetchBridge* bridge,
- ExecutionContext* execution_context,
- HeapVector<ManifestImageResource> icons,
- IconCallback icon_callback) {
+void BackgroundFetchIconLoader::Start(
+ BackgroundFetchBridge* bridge,
+ ExecutionContext* execution_context,
+ HeapVector<Member<ManifestImageResource>> icons,
+ IconCallback icon_callback) {
DCHECK(!stopped_);
DCHECK_GE(icons.size(), 1u);
DCHECK(bridge);
@@ -95,13 +97,13 @@ void BackgroundFetchIconLoader::DidGetIconDisplaySizeIfSoLoadIcon(
resource_request.SetPriority(ResourceLoadPriority::kMedium);
resource_request.SetKeepalive(true);
resource_request.SetFetchRequestMode(
- network::mojom::FetchRequestMode::kNoCORS);
+ network::mojom::FetchRequestMode::kNoCors);
resource_request.SetFetchCredentialsMode(
network::mojom::FetchCredentialsMode::kInclude);
resource_request.SetSkipServiceWorker(true);
- threadable_loader_ =
- new ThreadableLoader(*execution_context, this, resource_loader_options);
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
+ *execution_context, this, resource_loader_options);
threadable_loader_->SetTimeout(
TimeDelta::FromMilliseconds(kIconFetchTimeoutInMs));
threadable_loader_->Start(resource_request);
@@ -113,7 +115,7 @@ KURL BackgroundFetchIconLoader::PickBestIconForDisplay(
for (auto& icon : icons_) {
// Update the src of |icon| to include the base URL in case relative paths
// were used.
- icon.setSrc(execution_context->CompleteURL(icon.src()));
+ icon->setSrc(execution_context->CompleteURL(icon->src()));
Manifest::ImageResource candidate_icon =
blink::ConvertManifestImageResource(icon);
// Provide default values for 'purpose' and 'sizes' if they are missing.
@@ -160,9 +162,9 @@ void BackgroundFetchIconLoader::DidFinishLoading(
}
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- Platform::Current()->CurrentThread()->GetTaskRunner();
+ Thread::Current()->GetTaskRunner();
- BackgroundScheduler::PostOnBackgroundThread(
+ background_scheduler::PostOnBackgroundThread(
FROM_HERE,
CrossThreadBind(
&BackgroundFetchIconLoader::DecodeAndResizeImageOnBackgroundThread,
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h
index 180699c417d..77005a6dd86 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h
@@ -23,6 +23,8 @@ struct WebSize;
class MODULES_EXPORT BackgroundFetchIconLoader final
: public GarbageCollectedFinalized<BackgroundFetchIconLoader>,
public ThreadableLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(BackgroundFetchIconLoader);
+
public:
// The bitmap may be empty if the request failed or the image data could not
// be decoded. The int64_t returned is the scale of the ideal to chosen icon,
@@ -37,7 +39,7 @@ class MODULES_EXPORT BackgroundFetchIconLoader final
// data, and passes the bitmap to the given callback.
void Start(BackgroundFetchBridge* bridge,
ExecutionContext* execution_context,
- HeapVector<ManifestImageResource> icons,
+ HeapVector<Member<ManifestImageResource>> icons,
IconCallback icon_callback);
// Cancels the pending load, if there is one. The |icon_callback_| will not
@@ -50,9 +52,10 @@ class MODULES_EXPORT BackgroundFetchIconLoader final
void DidFail(const ResourceError& error) override;
void DidFailRedirectCheck() override;
- void Trace(blink::Visitor* visitor) {
+ void Trace(blink::Visitor* visitor) override {
visitor->Trace(threadable_loader_);
visitor->Trace(icons_);
+ ThreadableLoaderClient::Trace(visitor);
}
private:
@@ -81,7 +84,7 @@ class MODULES_EXPORT BackgroundFetchIconLoader final
// Called when the image has been decoded and resized on a background thread.
void DidFinishDecoding();
- HeapVector<ManifestImageResource> icons_;
+ HeapVector<Member<ManifestImageResource>> icons_;
IconCallback icon_callback_;
Member<ThreadableLoader> threadable_loader_;
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc
index 76709846e49..13acb071646 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc
@@ -55,7 +55,7 @@ class BackgroundFetchIconLoaderTest : public PageTestBase {
// Registers a mocked URL.
WebURL RegisterMockedURL(const String& file_name) {
- WebURL registered_url = URLTestHelpers::RegisterMockedURLLoadFromBase(
+ WebURL registered_url = url_test_helpers::RegisterMockedURLLoadFromBase(
kBackgroundFetchImageLoaderBaseUrl,
test::CoreTestDataPath(kBackgroundFetchImageLoaderBaseDir), file_name,
"image/png");
@@ -77,17 +77,17 @@ class BackgroundFetchIconLoaderTest : public PageTestBase {
std::move(quit_closure).Run();
}
- ManifestImageResource CreateTestIcon(const String& url_str,
- const String& size) {
- ManifestImageResource icon;
- icon.setSrc(url_str);
- icon.setType("image/png");
- icon.setSizes(size);
- icon.setPurpose("any");
+ ManifestImageResource* CreateTestIcon(const String& url_str,
+ const String& size) {
+ ManifestImageResource* icon = ManifestImageResource::Create();
+ icon->setSrc(url_str);
+ icon->setType("image/png");
+ icon->setSizes(size);
+ icon->setPurpose("any");
return icon;
}
- KURL PickRightIcon(HeapVector<ManifestImageResource> icons,
+ KURL PickRightIcon(HeapVector<Member<ManifestImageResource>> icons,
const WebSize& ideal_display_size) {
loader_->icons_ = std::move(icons);
loader_->icon_display_size_pixels_ = ideal_display_size;
@@ -100,12 +100,12 @@ class BackgroundFetchIconLoaderTest : public PageTestBase {
base::OnceClosure quit_closure,
const String& sizes = "500x500",
const String& purpose = "ANY") {
- ManifestImageResource icon;
- icon.setSrc(url.GetString());
- icon.setType("image/png");
- icon.setSizes(sizes);
- icon.setPurpose(purpose);
- HeapVector<ManifestImageResource> icons(1, icon);
+ ManifestImageResource* icon = ManifestImageResource::Create();
+ icon->setSrc(url.GetString());
+ icon->setType("image/png");
+ icon->setSizes(sizes);
+ icon->setPurpose(purpose);
+ HeapVector<Member<ManifestImageResource>> icons(1, icon);
loader_->icons_ = std::move(icons);
loader_->DidGetIconDisplaySizeIfSoLoadIcon(
GetContext(),
@@ -146,7 +146,7 @@ TEST_F(BackgroundFetchIconLoaderTest, SuccessTest) {
}
TEST_F(BackgroundFetchIconLoaderTest, PickIconRelativePath) {
- HeapVector<ManifestImageResource> icons;
+ HeapVector<Member<ManifestImageResource>> icons;
icons.push_back(
CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500, "500x500"));
@@ -156,7 +156,7 @@ TEST_F(BackgroundFetchIconLoaderTest, PickIconRelativePath) {
}
TEST_F(BackgroundFetchIconLoaderTest, PickIconFullPath) {
- HeapVector<ManifestImageResource> icons;
+ HeapVector<Member<ManifestImageResource>> icons;
icons.push_back(CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500FullPath,
"500x500"));
@@ -166,14 +166,14 @@ TEST_F(BackgroundFetchIconLoaderTest, PickIconFullPath) {
}
TEST_F(BackgroundFetchIconLoaderTest, PickRightIcon) {
- ManifestImageResource icon0 =
+ ManifestImageResource* icon0 =
CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500, "500x500");
- ManifestImageResource icon1 =
+ ManifestImageResource* icon1 =
CreateTestIcon(kBackgroundFetchImageLoaderIcon48x48, "48x48");
- ManifestImageResource icon2 =
+ ManifestImageResource* icon2 =
CreateTestIcon(kBackgroundFetchImageLoaderIcon3000x2000, "3000x2000");
- HeapVector<ManifestImageResource> icons;
+ HeapVector<Member<ManifestImageResource>> icons;
icons.push_back(icon0);
icons.push_back(icon1);
icons.push_back(icon2);
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc
index 58d84e020b7..bb8c162e3c5 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc
@@ -4,12 +4,14 @@
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h"
+#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_macros.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
#include "third_party/blink/renderer/bindings/core/v8/request_or_usv_string.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/request_or_usv_string_or_request_or_usv_string_sequence.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
+#include "third_party/blink/renderer/core/fetch/body.h"
+#include "third_party/blink/renderer/core/fetch/body_stream_buffer.h"
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
@@ -23,6 +25,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
+#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
@@ -93,7 +96,6 @@ bool ShouldBlockDanglingMarkup(const KURL& request_url) {
}
bool ShouldBlockGateWayAttacks(ExecutionContext* execution_context,
- const WebServiceWorkerRequest& web_request,
const KURL& request_url) {
if (RuntimeEnabledFeatures::CorsRFC1918Enabled()) {
mojom::IPAddressSpace requestor_space =
@@ -103,7 +105,7 @@ bool ShouldBlockGateWayAttacks(ExecutionContext* execution_context,
// all this up to //net and //content in order to have any real impact on
// gateway attacks. That turns out to be a TON of work (crbug.com/378566).
mojom::IPAddressSpace target_space = mojom::IPAddressSpace::kPublic;
- if (NetworkUtils::IsReservedIPAddress(request_url.Host()))
+ if (network_utils::IsReservedIPAddress(request_url.Host()))
target_space = mojom::IPAddressSpace::kPrivate;
if (SecurityOrigin::Create(request_url)->IsLocalhost())
target_space = mojom::IPAddressSpace::kLocal;
@@ -116,6 +118,37 @@ bool ShouldBlockGateWayAttacks(ExecutionContext* execution_context,
return false;
}
+scoped_refptr<BlobDataHandle> ExtractBlobHandle(
+ Request* request,
+ ExceptionState& exception_state) {
+ DCHECK(request);
+
+ if (!RuntimeEnabledFeatures::BackgroundFetchUploadsEnabled())
+ return nullptr;
+
+ if (request->IsBodyLocked(exception_state) == Body::BodyLocked::kLocked ||
+ request->IsBodyUsed(exception_state) == Body::BodyUsed::kUsed) {
+ DCHECK(!exception_state.HadException());
+ exception_state.ThrowTypeError("Request body is already used");
+ return nullptr;
+ }
+
+ if (exception_state.HadException())
+ return nullptr;
+
+ BodyStreamBuffer* buffer = request->BodyBuffer();
+ if (!buffer)
+ return nullptr;
+
+ auto blob_handle = buffer->DrainAsBlobDataHandle(
+ BytesConsumer::BlobSizePolicy::kDisallowBlobWithInvalidSize,
+ exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+
+ return blob_handle;
+}
+
} // namespace
BackgroundFetchManager::BackgroundFetchManager(
@@ -130,7 +163,7 @@ ScriptPromise BackgroundFetchManager::fetch(
ScriptState* script_state,
const String& id,
const RequestOrUSVStringOrRequestOrUSVStringSequence& requests,
- const BackgroundFetchOptions& options,
+ const BackgroundFetchOptions* options,
ExceptionState& exception_state) {
if (!registration_->active()) {
return ScriptPromise::Reject(
@@ -141,8 +174,9 @@ ScriptPromise BackgroundFetchManager::fetch(
}
bool has_requests_with_body;
- Vector<WebServiceWorkerRequest> web_requests = CreateWebRequestVector(
- script_state, requests, exception_state, &has_requests_with_body);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(script_state, requests, exception_state,
+ &has_requests_with_body);
if (exception_state.HadException())
return ScriptPromise();
@@ -150,8 +184,8 @@ ScriptPromise BackgroundFetchManager::fetch(
UMA_HISTOGRAM_BOOLEAN("BackgroundFetch.HasRequestsWithBody",
has_requests_with_body);
- // TODO(crbug.com/789854): Stop bailing here once we support uploads.
- if (has_requests_with_body) {
+ if (has_requests_with_body &&
+ !RuntimeEnabledFeatures::BackgroundFetchUploadsEnabled()) {
return ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
@@ -170,8 +204,8 @@ ScriptPromise BackgroundFetchManager::fetch(
// all its security checks) are implemented in the Network Service, such that
// the Download Service in the browser process can use it without having to
// spin up a renderer process.
- for (const WebServiceWorkerRequest& web_request : web_requests) {
- KURL request_url(web_request.Url());
+ for (const mojom::blink::FetchAPIRequestPtr& request : fetch_api_requests) {
+ KURL request_url(request->url);
if (!request_url.IsValid()) {
return RejectWithTypeError(script_state, request_url,
@@ -181,7 +215,7 @@ ScriptPromise BackgroundFetchManager::fetch(
// https://wicg.github.io/background-fetch/#dom-backgroundfetchmanager-fetch
// ""If |internalRequest|’s mode is "no-cors", then return a promise
// rejected with a TypeError.""
- if (web_request.Mode() == network::mojom::FetchRequestMode::kNoCORS) {
+ if (request->mode == network::mojom::FetchRequestMode::kNoCors) {
return RejectWithTypeError(script_state, request_url,
"the request mode must not be no-cors");
}
@@ -214,8 +248,7 @@ ScriptPromise BackgroundFetchManager::fetch(
"it contains dangling markup");
}
- if (ShouldBlockGateWayAttacks(execution_context, web_request,
- request_url)) {
+ if (ShouldBlockGateWayAttacks(execution_context, request_url)) {
return RejectWithTypeError(script_state, request_url,
"Requestor IP address space doesn't match the "
"target address space.");
@@ -224,7 +257,7 @@ ScriptPromise BackgroundFetchManager::fetch(
kurls.insert(request_url);
}
- const bool has_duplicate_requests = kurls.size() != web_requests.size();
+ const bool has_duplicate_requests = kurls.size() != fetch_api_requests.size();
UMA_HISTOGRAM_BOOLEAN("BackgroundFetch.HasDuplicateRequests",
has_duplicate_requests);
@@ -250,26 +283,27 @@ ScriptPromise BackgroundFetchManager::fetch(
// Inability to load them should not be fatal to the fetch.
mojom::blink::BackgroundFetchOptionsPtr options_ptr =
mojom::blink::BackgroundFetchOptions::From(options);
- if (options.icons().size()) {
+ if (options->icons().size()) {
BackgroundFetchIconLoader* loader = new BackgroundFetchIconLoader();
loaders_.push_back(loader);
loader->Start(
- bridge_.Get(), execution_context, options.icons(),
+ bridge_.Get(), execution_context, options->icons(),
WTF::Bind(&BackgroundFetchManager::DidLoadIcons, WrapPersistent(this),
- id, WTF::Passed(std::move(web_requests)),
+ id, WTF::Passed(std::move(fetch_api_requests)),
std::move(options_ptr), WrapPersistent(resolver),
WrapWeakPersistent(loader)));
return promise;
}
- DidLoadIcons(id, std::move(web_requests), std::move(options_ptr), resolver,
- nullptr, SkBitmap(), -1 /* ideal_to_chosen_icon_size */);
+ DidLoadIcons(id, std::move(fetch_api_requests), std::move(options_ptr),
+ resolver, nullptr, SkBitmap(),
+ -1 /* ideal_to_chosen_icon_size */);
return promise;
}
void BackgroundFetchManager::DidLoadIcons(
const String& id,
- Vector<WebServiceWorkerRequest> web_requests,
+ Vector<mojom::blink::FetchAPIRequestPtr> requests,
mojom::blink::BackgroundFetchOptionsPtr options,
ScriptPromiseResolver* resolver,
BackgroundFetchIconLoader* loader,
@@ -281,8 +315,7 @@ void BackgroundFetchManager::DidLoadIcons(
auto ukm_data = mojom::blink::BackgroundFetchUkmData::New();
ukm_data->ideal_to_chosen_icon_size = ideal_to_chosen_icon_size;
bridge_->Fetch(
- id, std::move(web_requests), std::move(options), icon,
- std::move(ukm_data),
+ id, std::move(requests), std::move(options), icon, std::move(ukm_data),
WTF::Bind(&BackgroundFetchManager::DidFetch, WrapPersistent(this),
WrapPersistent(resolver), base::Time::Now()));
}
@@ -371,14 +404,15 @@ ScriptPromise BackgroundFetchManager::get(ScriptState* script_state,
}
// static
-Vector<WebServiceWorkerRequest> BackgroundFetchManager::CreateWebRequestVector(
+Vector<mojom::blink::FetchAPIRequestPtr>
+BackgroundFetchManager::CreateFetchAPIRequestVector(
ScriptState* script_state,
const RequestOrUSVStringOrRequestOrUSVStringSequence& requests,
ExceptionState& exception_state,
bool* has_requests_with_body) {
DCHECK(has_requests_with_body);
- Vector<WebServiceWorkerRequest> web_requests;
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests;
*has_requests_with_body = false;
if (requests.IsRequestOrUSVStringSequence()) {
@@ -388,10 +422,10 @@ Vector<WebServiceWorkerRequest> BackgroundFetchManager::CreateWebRequestVector(
// Throw a TypeError when the developer has passed an empty sequence.
if (!request_vector.size()) {
exception_state.ThrowTypeError(kEmptyRequestSequenceErrorMessage);
- return Vector<WebServiceWorkerRequest>();
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
}
- web_requests.resize(request_vector.size());
+ fetch_api_requests.resize(request_vector.size());
for (wtf_size_t i = 0; i < request_vector.size(); ++i) {
const RequestOrUSVString& request_or_url = request_vector[i];
@@ -403,17 +437,20 @@ Vector<WebServiceWorkerRequest> BackgroundFetchManager::CreateWebRequestVector(
request = Request::Create(script_state, request_or_url.GetAsUSVString(),
exception_state);
if (exception_state.HadException())
- return Vector<WebServiceWorkerRequest>();
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
} else {
exception_state.ThrowTypeError(kNullRequestErrorMessage);
- return Vector<WebServiceWorkerRequest>();
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
}
DCHECK(request);
*has_requests_with_body |= request->HasBody();
// TODO(crbug.com/774054): Set blob data handle when adding support for
// requests with body.
- request->PopulateWebServiceWorkerRequest(web_requests[i]);
+ fetch_api_requests[i] = request->CreateFetchAPIRequest();
+ fetch_api_requests[i]->blob = ExtractBlobHandle(request, exception_state);
+ if (exception_state.HadException())
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
}
} else if (requests.IsRequest()) {
auto* request = requests.GetAsRequest();
@@ -423,24 +460,28 @@ Vector<WebServiceWorkerRequest> BackgroundFetchManager::CreateWebRequestVector(
// requests with body.
*has_requests_with_body = request->HasBody();
- web_requests.resize(1);
- request->PopulateWebServiceWorkerRequest(web_requests[0]);
+ fetch_api_requests.resize(1);
+ fetch_api_requests[0] = request->CreateFetchAPIRequest();
+ fetch_api_requests[0]->blob =
+ ExtractBlobHandle(requests.GetAsRequest(), exception_state);
+ if (exception_state.HadException())
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
} else if (requests.IsUSVString()) {
Request* request = Request::Create(script_state, requests.GetAsUSVString(),
exception_state);
if (exception_state.HadException())
- return Vector<WebServiceWorkerRequest>();
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
DCHECK(request);
*has_requests_with_body = request->HasBody();
- web_requests.resize(1);
- request->PopulateWebServiceWorkerRequest(web_requests[0]);
+ fetch_api_requests.resize(1);
+ fetch_api_requests[0] = request->CreateFetchAPIRequest();
} else {
exception_state.ThrowTypeError(kNullRequestErrorMessage);
- return Vector<WebServiceWorkerRequest>();
+ return Vector<mojom::blink::FetchAPIRequestPtr>();
}
- return web_requests;
+ return fetch_api_requests;
}
void BackgroundFetchManager::DidGetRegistration(
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h
index c850731ac69..7001f931e7c 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h
@@ -28,7 +28,6 @@ class RequestOrUSVStringOrRequestOrUSVStringSequence;
class ScriptPromiseResolver;
class ScriptState;
class ServiceWorkerRegistration;
-class WebServiceWorkerRequest;
// Implementation of the BackgroundFetchManager JavaScript object, accessible
// by developers through ServiceWorkerRegistration.backgroundFetch.
@@ -50,7 +49,7 @@ class MODULES_EXPORT BackgroundFetchManager final
ScriptState* script_state,
const String& id,
const RequestOrUSVStringOrRequestOrUSVStringSequence& requests,
- const BackgroundFetchOptions& options,
+ const BackgroundFetchOptions* options,
ExceptionState& exception_state);
ScriptPromise get(ScriptState* script_state, const String& id);
ScriptPromise getIds(ScriptState* script_state);
@@ -65,17 +64,17 @@ class MODULES_EXPORT BackgroundFetchManager final
explicit BackgroundFetchManager(ServiceWorkerRegistration* registration);
- // Creates a vector of WebServiceWorkerRequest objects for the given set of
- // |requests|, which can be either Request objects or URL strings.
+ // Creates a vector of mojom::blink::FetchAPIRequestPtr objects for the given
+ // set of |requests|, which can be either Request objects or URL strings.
// |has_requests_with_body| will be set if any of the |requests| has a body.
- static Vector<WebServiceWorkerRequest> CreateWebRequestVector(
+ static Vector<mojom::blink::FetchAPIRequestPtr> CreateFetchAPIRequestVector(
ScriptState* script_state,
const RequestOrUSVStringOrRequestOrUSVStringSequence& requests,
ExceptionState& exception_state,
bool* has_requests_with_body);
void DidLoadIcons(const String& id,
- Vector<WebServiceWorkerRequest> web_requests,
+ Vector<mojom::blink::FetchAPIRequestPtr> requests,
mojom::blink::BackgroundFetchOptionsPtr options,
ScriptPromiseResolver* resolver,
BackgroundFetchIconLoader* loader,
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc
index 688658b3fa0..01592306e7f 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
#include "third_party/blink/renderer/bindings/core/v8/request_or_usv_string.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
@@ -14,19 +13,20 @@
#include "third_party/blink/renderer/core/fetch/request_init.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/blob/blob_data.h"
namespace blink {
class BackgroundFetchManagerTest : public testing::Test {
protected:
- // Creates a vector of WebServiceWorkerRequest entries for the given
- // |requests| based on the |scope|. Proxied in the fixture to reduce the
- // number of friend declarations necessary in the BackgroundFetchManager.
- Vector<WebServiceWorkerRequest> CreateWebRequestVector(
+ // Creates a vector of FetchAPIRequestPtr entries for the given |requests|
+ // based on the |scope|. Proxied in the fixture to reduce the number of friend
+ // declarations necessary in the BackgroundFetchManager.
+ Vector<mojom::blink::FetchAPIRequestPtr> CreateFetchAPIRequestVector(
V8TestingScope& scope,
const RequestOrUSVStringOrRequestOrUSVStringSequence& requests) {
bool has_requests_with_body;
- return BackgroundFetchManager::CreateWebRequestVector(
+ return BackgroundFetchManager::CreateFetchAPIRequestVector(
scope.GetScriptState(), requests, scope.GetExceptionState(),
&has_requests_with_body);
}
@@ -37,8 +37,8 @@ TEST_F(BackgroundFetchManagerTest, NullValue) {
RequestOrUSVStringOrRequestOrUSVStringSequence requests;
- Vector<WebServiceWorkerRequest> web_requests =
- CreateWebRequestVector(scope, requests);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
ASSERT_TRUE(scope.GetExceptionState().HadException());
EXPECT_EQ(scope.GetExceptionState().CodeAs<ESErrorType>(),
ESErrorType::kTypeError);
@@ -53,15 +53,13 @@ TEST_F(BackgroundFetchManagerTest, SingleUSVString) {
RequestOrUSVStringOrRequestOrUSVStringSequence::FromUSVString(
image_url.GetString());
- Vector<WebServiceWorkerRequest> web_requests =
- CreateWebRequestVector(scope, requests);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
ASSERT_FALSE(scope.GetExceptionState().HadException());
- ASSERT_EQ(web_requests.size(), 1u);
-
- WebServiceWorkerRequest& web_request = web_requests[0];
- EXPECT_EQ(web_request.Url(), WebURL(image_url));
- EXPECT_EQ(web_request.Method(), "GET");
+ ASSERT_EQ(fetch_api_requests.size(), 1u);
+ EXPECT_EQ(fetch_api_requests[0]->url, image_url);
+ EXPECT_EQ(fetch_api_requests[0]->method, "GET");
}
TEST_F(BackgroundFetchManagerTest, SingleRequest) {
@@ -69,8 +67,8 @@ TEST_F(BackgroundFetchManagerTest, SingleRequest) {
KURL image_url("https://www.example.com/my_image.png");
- RequestInit request_init;
- request_init.setMethod("POST");
+ RequestInit* request_init = RequestInit::Create();
+ request_init->setMethod("POST");
Request* request =
Request::Create(scope.GetScriptState(), image_url.GetString(),
request_init, scope.GetExceptionState());
@@ -80,15 +78,13 @@ TEST_F(BackgroundFetchManagerTest, SingleRequest) {
RequestOrUSVStringOrRequestOrUSVStringSequence requests =
RequestOrUSVStringOrRequestOrUSVStringSequence::FromRequest(request);
- Vector<WebServiceWorkerRequest> web_requests =
- CreateWebRequestVector(scope, requests);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
ASSERT_FALSE(scope.GetExceptionState().HadException());
- ASSERT_EQ(web_requests.size(), 1u);
-
- WebServiceWorkerRequest& web_request = web_requests[0];
- EXPECT_EQ(web_request.Url(), WebURL(image_url));
- EXPECT_EQ(web_request.Method(), "POST");
+ ASSERT_EQ(fetch_api_requests.size(), 1u);
+ EXPECT_EQ(fetch_api_requests[0]->url, image_url);
+ EXPECT_EQ(fetch_api_requests[0]->method, "POST");
}
TEST_F(BackgroundFetchManagerTest, Sequence) {
@@ -103,8 +99,8 @@ TEST_F(BackgroundFetchManagerTest, Sequence) {
RequestOrUSVString icon_request =
RequestOrUSVString::FromUSVString(icon_url.GetString());
- RequestInit request_init;
- request_init.setMethod("DELETE");
+ RequestInit* request_init = RequestInit::Create();
+ request_init->setMethod("DELETE");
Request* request =
Request::Create(scope.GetScriptState(), cat_video_url.GetString(),
request_init, scope.GetExceptionState());
@@ -123,19 +119,19 @@ TEST_F(BackgroundFetchManagerTest, Sequence) {
RequestOrUSVStringOrRequestOrUSVStringSequence::
FromRequestOrUSVStringSequence(request_sequence);
- Vector<WebServiceWorkerRequest> web_requests =
- CreateWebRequestVector(scope, requests);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
ASSERT_FALSE(scope.GetExceptionState().HadException());
- ASSERT_EQ(web_requests.size(), 3u);
- EXPECT_EQ(web_requests[0].Url(), WebURL(image_url));
- EXPECT_EQ(web_requests[0].Method(), "GET");
+ ASSERT_EQ(fetch_api_requests.size(), 3u);
+ EXPECT_EQ(fetch_api_requests[0]->url, image_url);
+ EXPECT_EQ(fetch_api_requests[0]->method, "GET");
- EXPECT_EQ(web_requests[1].Url(), WebURL(icon_url));
- EXPECT_EQ(web_requests[1].Method(), "GET");
+ EXPECT_EQ(fetch_api_requests[1]->url, icon_url);
+ EXPECT_EQ(fetch_api_requests[1]->method, "GET");
- EXPECT_EQ(web_requests[2].Url(), WebURL(cat_video_url));
- EXPECT_EQ(web_requests[2].Method(), "DELETE");
+ EXPECT_EQ(fetch_api_requests[2]->url, cat_video_url);
+ EXPECT_EQ(fetch_api_requests[2]->method, "DELETE");
}
TEST_F(BackgroundFetchManagerTest, SequenceEmpty) {
@@ -146,8 +142,8 @@ TEST_F(BackgroundFetchManagerTest, SequenceEmpty) {
RequestOrUSVStringOrRequestOrUSVStringSequence::
FromRequestOrUSVStringSequence(request_sequence);
- Vector<WebServiceWorkerRequest> web_requests =
- CreateWebRequestVector(scope, requests);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
ASSERT_TRUE(scope.GetExceptionState().HadException());
EXPECT_EQ(scope.GetExceptionState().CodeAs<ESErrorType>(),
ESErrorType::kTypeError);
@@ -170,11 +166,56 @@ TEST_F(BackgroundFetchManagerTest, SequenceWithNullValue) {
RequestOrUSVStringOrRequestOrUSVStringSequence::
FromRequestOrUSVStringSequence(request_sequence);
- Vector<WebServiceWorkerRequest> web_requests =
- CreateWebRequestVector(scope, requests);
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
ASSERT_TRUE(scope.GetExceptionState().HadException());
EXPECT_EQ(scope.GetExceptionState().CodeAs<ESErrorType>(),
ESErrorType::kTypeError);
}
+TEST_F(BackgroundFetchManagerTest, BlobsExtracted) {
+ V8TestingScope scope;
+
+ KURL image_url("https://www.example.com/my_image.png");
+ KURL icon_url("https://www.example.com/my_icon.jpg");
+
+ // Create first request with a body.
+ String body_text = "cat_pic";
+ RequestInit* request_init = RequestInit::Create();
+ request_init->setMethod("POST");
+ request_init->setBody(blink::ScriptValue(
+ scope.GetScriptState(), ToV8(body_text, scope.GetScriptState())));
+ Request* image_request =
+ Request::Create(scope.GetScriptState(), image_url.GetString(),
+ request_init, scope.GetExceptionState());
+ ASSERT_FALSE(scope.GetExceptionState().HadException());
+ ASSERT_TRUE(image_request);
+ ASSERT_TRUE(image_request->HasBody());
+
+ // Create second request without a body.
+ RequestOrUSVString icon_request =
+ RequestOrUSVString::FromUSVString(icon_url.GetString());
+
+ // Create a request sequence with both requests.
+ HeapVector<RequestOrUSVString> request_sequence;
+ request_sequence.push_back(RequestOrUSVString::FromRequest(image_request));
+ request_sequence.push_back(icon_request);
+
+ RequestOrUSVStringOrRequestOrUSVStringSequence requests =
+ RequestOrUSVStringOrRequestOrUSVStringSequence::
+ FromRequestOrUSVStringSequence(request_sequence);
+
+ // Extract the blobs.
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests =
+ CreateFetchAPIRequestVector(scope, requests);
+ ASSERT_FALSE(scope.GetExceptionState().HadException());
+
+ ASSERT_EQ(fetch_api_requests.size(), 2u);
+
+ ASSERT_TRUE(fetch_api_requests[0]->blob);
+ EXPECT_EQ(fetch_api_requests[0]->blob->size(), body_text.length());
+
+ EXPECT_FALSE(fetch_api_requests[1]->blob);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc
index a7dd3a6581b..ce168cd3a8e 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc
@@ -3,32 +3,60 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_record.h"
-
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/core/fetch/response.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
BackgroundFetchRecord::BackgroundFetchRecord(Request* request,
- Response* response)
- : request_(request), response_(response) {
+ ScriptState* script_state)
+ : request_(request), script_state_(script_state) {
DCHECK(request_);
+ DCHECK(script_state_);
+ response_ready_property_ =
+ new ResponseReadyProperty(ExecutionContext::From(script_state), this,
+ ResponseReadyProperty::kResponseReady);
}
BackgroundFetchRecord::~BackgroundFetchRecord() = default;
-ScriptPromise BackgroundFetchRecord::responseReady(ScriptState* script_state) {
- if (!response_ready_property_) {
- response_ready_property_ =
- new ResponseReadyProperty(ExecutionContext::From(script_state), this,
- ResponseReadyProperty::kResponseReady);
+void BackgroundFetchRecord::ResolveResponseReadyProperty(Response* response) {
+ if (!response_ready_property_ ||
+ response_ready_property_->GetState() !=
+ ScriptPromisePropertyBase::State::kPending) {
+ return;
}
- if (!response_) {
- response_ = Response::Create(ExecutionContext::From(script_state),
- nullptr /* FetchResponseData */);
+
+ switch (record_state_) {
+ case State::kPending:
+ return;
+ case State::kAborted:
+ response_ready_property_->Reject(DOMException::Create(
+ DOMExceptionCode::kAbortError,
+ "The fetch was aborted before the record was processed."));
+ return;
+ case State::kSettled:
+ if (response) {
+ response_ready_property_->Resolve(response);
+ return;
+ }
+
+ if (!script_state_->ContextIsValid())
+ return;
+
+ // TODO(crbug.com/875201):Per https://wicg.github.io/background-fetch/
+ // #background-fetch-response-exposed, this should be resolved with a
+ // TypeError. Figure out a way to do so.
+ // Rejecting this with a TypeError here doesn't work because the
+ // RejectedType is a DOMException. Update this with the correct error
+ // once confirmed, or change the RejectedType.
+ response_ready_property_->Reject(DOMException::Create(
+ DOMExceptionCode::kUnknownError, "The response is not available."));
}
- DCHECK(response_);
- response_ready_property_->Resolve(response_);
+}
+
+ScriptPromise BackgroundFetchRecord::responseReady(ScriptState* script_state) {
return response_ready_property_->Promise(script_state->World());
}
@@ -36,10 +64,34 @@ Request* BackgroundFetchRecord::request() const {
return request_;
}
+void BackgroundFetchRecord::UpdateState(
+ BackgroundFetchRecord::State updated_state) {
+ DCHECK_EQ(record_state_, State::kPending);
+
+ record_state_ = updated_state;
+ ResolveResponseReadyProperty(/* updated_response = */ nullptr);
+}
+
+void BackgroundFetchRecord::SetResponseAndUpdateState(
+ mojom::blink::FetchAPIResponsePtr& response) {
+ DCHECK(record_state_ == State::kPending);
+ DCHECK(!response.is_null());
+
+ if (!script_state_->ContextIsValid())
+ return;
+ record_state_ = State::kSettled;
+
+ ResolveResponseReadyProperty(Response::Create(script_state_, *response));
+}
+
+bool BackgroundFetchRecord::IsRecordPending() {
+ return record_state_ == State::kPending;
+}
+
void BackgroundFetchRecord::Trace(blink::Visitor* visitor) {
visitor->Trace(request_);
- visitor->Trace(response_);
visitor->Trace(response_ready_property_);
+ visitor->Trace(script_state_);
ScriptWrappable::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h
index 4ff0a63b6cf..673a3093933 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_RECORD_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_RECORD_H_
+#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_property.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
@@ -16,18 +17,37 @@ namespace blink {
class Request;
class Response;
+class ScriptState;
class MODULES_EXPORT BackgroundFetchRecord final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- explicit BackgroundFetchRecord(Request* request,
- Response* response = nullptr);
+ // The record can be in one of these states. |kSettled| can mean success or
+ // failure based on whether or not there's a valid response to settle the
+ // responseReady promise with.
+ enum class State {
+ kPending,
+ kAborted,
+ kSettled,
+ };
+
+ BackgroundFetchRecord(Request* request, ScriptState* script_state);
~BackgroundFetchRecord() override;
Request* request() const;
ScriptPromise responseReady(ScriptState* script_state);
+ // Updates |record_state_| from kPending to kAborted or kSettled. Must be
+ // called when |record_state_| is kPending.
+ void UpdateState(State updated_state);
+
+ // Resolve the responseReady promise with |response|, and update
+ // |record_state_|. Must be called when |record_state_| is kPending.
+ // Must not be called with a null response;
+ void SetResponseAndUpdateState(mojom::blink::FetchAPIResponsePtr& response);
+
+ bool IsRecordPending();
void Trace(blink::Visitor* visitor) override;
private:
@@ -35,9 +55,22 @@ class MODULES_EXPORT BackgroundFetchRecord final : public ScriptWrappable {
ScriptPromiseProperty<Member<BackgroundFetchRecord>,
Member<Response>,
Member<DOMException>>;
+
+ // Resolves a pending |response_read_property_| with |response|, if it's not
+ // null.
+ // If |response| is null, we do nothing if the record isn't final yet. If
+ // |record_state_| is State::kSettled in this case, we reject the promise.
+ // This is because the record will not be updated with a valid |response|.
+ void ResolveResponseReadyProperty(Response* response);
+
Member<Request> request_;
- Member<Response> response_;
Member<ResponseReadyProperty> response_ready_property_;
+
+ // Since BackgroundFetchRecord can only be accessed from the world that
+ // created it, there's no danger of ScriptState leaking across worlds.
+ Member<ScriptState> script_state_;
+
+ State record_state_ = State::kPending;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc
index e425272b6d7..282e58cc60d 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc
@@ -13,13 +13,13 @@
#include "third_party/blink/renderer/core/fetch/response.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_record.h"
-#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h"
#include "third_party/blink/renderer/modules/cache_storage/cache.h"
#include "third_party/blink/renderer/modules/cache_storage/cache_query_options.h"
#include "third_party/blink/renderer/modules/event_target_modules_names.h"
#include "third_party/blink/renderer/modules/manifest/image_resource.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
namespace blink {
@@ -88,12 +88,14 @@ void BackgroundFetchRegistration::OnProgress(
result_ = result;
failure_reason_ = failure_reason;
+ // TODO(crbug.com/875201): Update records in |records_|.
+
ExecutionContext* context = GetExecutionContext();
if (!context || context->IsContextDestroyed())
return;
DCHECK(context->IsContextThread());
- DispatchEvent(*Event::Create(EventTypeNames::progress));
+ DispatchEvent(*Event::Create(event_type_names::kProgress));
}
void BackgroundFetchRegistration::OnRecordsUnavailable() {
@@ -125,7 +127,7 @@ bool BackgroundFetchRegistration::recordsAvailable() const {
}
const AtomicString& BackgroundFetchRegistration::InterfaceName() const {
- return EventTargetNames::BackgroundFetchRegistration;
+ return event_target_names::kBackgroundFetchRegistration;
}
ExecutionContext* BackgroundFetchRegistration::GetExecutionContext() const {
@@ -149,7 +151,7 @@ ScriptPromise BackgroundFetchRegistration::abort(ScriptState* script_state) {
ScriptPromise BackgroundFetchRegistration::match(
ScriptState* script_state,
const RequestOrUSVString& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
return MatchImpl(
script_state, base::make_optional<RequestOrUSVString>(request),
@@ -167,7 +169,7 @@ ScriptPromise BackgroundFetchRegistration::matchAll(
ScriptPromise BackgroundFetchRegistration::matchAll(
ScriptState* script_state,
const RequestOrUSVString& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
return MatchImpl(
script_state, base::make_optional<RequestOrUSVString>(request),
@@ -182,7 +184,8 @@ ScriptPromise BackgroundFetchRegistration::MatchImpl(
bool match_all) {
// TODO(crbug.com/875201): Update this check once we support access to active
// fetches.
- if (result_ == mojom::BackgroundFetchResult::UNSET) {
+ if (result_ == mojom::BackgroundFetchResult::UNSET &&
+ !RuntimeEnabledFeatures::BackgroundFetchAccessActiveFetchesEnabled()) {
return ScriptPromise::RejectWithDOMException(
script_state,
DOMException::Create(
@@ -203,28 +206,25 @@ ScriptPromise BackgroundFetchRegistration::MatchImpl(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- // Convert |request| to WebServiceWorkerRequest.
- base::Optional<WebServiceWorkerRequest> optional_request;
+ // Convert |request| to mojom::blink::FetchAPIRequestPtr.
+ mojom::blink::FetchAPIRequestPtr request_to_match;
if (request.has_value()) {
- WebServiceWorkerRequest request_to_match;
if (request->IsRequest()) {
- request->GetAsRequest()->PopulateWebServiceWorkerRequest(
- request_to_match);
+ request_to_match = request->GetAsRequest()->CreateFetchAPIRequest();
} else {
Request* new_request = Request::Create(
script_state, request->GetAsUSVString(), exception_state);
if (exception_state.HadException())
return ScriptPromise();
- new_request->PopulateWebServiceWorkerRequest(request_to_match);
+ request_to_match = new_request->CreateFetchAPIRequest();
}
- optional_request = request_to_match;
}
DCHECK(registration_);
BackgroundFetchBridge::From(registration_)
->MatchRequests(
- developer_id_, unique_id_, optional_request,
+ developer_id_, unique_id_, std::move(request_to_match),
std::move(cache_query_params), match_all,
WTF::Bind(&BackgroundFetchRegistration::DidGetMatchingRequests,
WrapPersistent(this), WrapPersistent(resolver), match_all));
@@ -235,21 +235,29 @@ void BackgroundFetchRegistration::DidGetMatchingRequests(
ScriptPromiseResolver* resolver,
bool return_all,
Vector<mojom::blink::BackgroundFetchSettledFetchPtr> settled_fetches) {
+ DCHECK(resolver);
+
ScriptState* script_state = resolver->GetScriptState();
// Do not remove this, |scope| is needed for calling ToV8()
ScriptState::Scope scope(script_state);
HeapVector<Member<BackgroundFetchRecord>> to_return;
to_return.ReserveInitialCapacity(settled_fetches.size());
- for (const auto& fetch : settled_fetches) {
- if (fetch->response->response_type ==
- network::mojom::FetchResponseType::kError) {
- // Resolve with undefined.
- resolver->Resolve();
- return;
+ for (auto& fetch : settled_fetches) {
+ // If there isn't a record for this fetch in records_ already, create one.
+ auto iter = records_.find(fetch->request->url);
+ BackgroundFetchRecord* record = nullptr;
+ if (iter == records_.end()) {
+ Request* request = Request::Create(script_state, *(fetch->request));
+ auto* new_record = new BackgroundFetchRecord(request, script_state);
+ DCHECK(new_record);
+ records_.Set(request->url(), new_record);
+
+ record = new_record;
+ } else {
+ record = iter->value;
}
- BackgroundFetchRecord* record = new BackgroundFetchRecord(
- Request::Create(script_state, fetch->request),
- Response::Create(script_state, *fetch->response));
+
+ UpdateRecord(record, fetch->response);
to_return.push_back(record);
}
@@ -267,6 +275,37 @@ void BackgroundFetchRegistration::DidGetMatchingRequests(
resolver->Resolve(to_return);
}
+void BackgroundFetchRegistration::UpdateRecord(
+ BackgroundFetchRecord* record,
+ mojom::blink::FetchAPIResponsePtr& response) {
+ DCHECK(record);
+
+ if (!record->IsRecordPending())
+ return;
+
+ // Per the spec, resolve with a valid response, if there is one available,
+ // even if the fetch has been aborted.
+ if (!response.is_null()) {
+ record->SetResponseAndUpdateState(response);
+ return;
+ }
+
+ if (IsAborted()) {
+ record->UpdateState(BackgroundFetchRecord::State::kAborted);
+ return;
+ }
+
+ if (result_ != mojom::blink::BackgroundFetchResult::UNSET)
+ record->UpdateState(BackgroundFetchRecord::State::kSettled);
+}
+
+bool BackgroundFetchRegistration::IsAborted() {
+ return failure_reason_ ==
+ mojom::BackgroundFetchFailureReason::CANCELLED_FROM_UI ||
+ failure_reason_ ==
+ mojom::BackgroundFetchFailureReason::CANCELLED_BY_DEVELOPER;
+}
+
void BackgroundFetchRegistration::DidAbort(
ScriptPromiseResolver* resolver,
mojom::blink::BackgroundFetchError error) {
@@ -333,6 +372,7 @@ void BackgroundFetchRegistration::Dispose() {
void BackgroundFetchRegistration::Trace(Visitor* visitor) {
visitor->Trace(registration_);
+ visitor->Trace(records_);
EventTargetWithInlineData::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h
index bb2adb7c16e..715709c42f2 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h
@@ -12,10 +12,12 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl_hash.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
+class BackgroundFetchRecord;
class CacheQueryOptions;
class ScriptPromiseResolver;
class ScriptState;
@@ -67,13 +69,13 @@ class BackgroundFetchRegistration final
String id() const;
ScriptPromise match(ScriptState* script_state,
const RequestOrUSVString& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state);
ScriptPromise matchAll(ScriptState* scrip_state,
ExceptionState& exception_state);
ScriptPromise matchAll(ScriptState* script_state,
const RequestOrUSVString& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state);
unsigned long long uploadTotal() const;
@@ -86,7 +88,7 @@ class BackgroundFetchRegistration final
const String& unique_id() const { return unique_id_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(progress, kProgress);
ScriptPromise abort(ScriptState* script_state);
@@ -111,8 +113,18 @@ class BackgroundFetchRegistration final
bool return_all,
Vector<mojom::blink::BackgroundFetchSettledFetchPtr> settled_fetches);
+ // Updates the |record| with a |response|, if one is available, else marks
+ // the |record|'s request as aborted or failed.
+ void UpdateRecord(BackgroundFetchRecord* record,
+ mojom::blink::FetchAPIResponsePtr& response);
+
+ bool IsAborted();
+
Member<ServiceWorkerRegistration> registration_;
+ // TODO(crbug.com/774054): Update the key once we support duplicate requests.
+ HeapHashMap<KURL, Member<BackgroundFetchRecord>> records_;
+
// Corresponds to IDL 'id' attribute. Not unique - an active registration can
// have the same |developer_id_| as one or more inactive registrations.
String developer_id_;
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.cc
deleted file mode 100644
index 14ee67bc281..00000000000
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.cc
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h"
-
-#include "third_party/blink/renderer/core/fetch/response.h"
-
-namespace blink {
-
-BackgroundFetchSettledFetch::BackgroundFetchSettledFetch(Request* request,
- Response* response)
- : BackgroundFetchFetch(request), response_(response) {}
-
-Response* BackgroundFetchSettledFetch::response() const {
- return response_;
-}
-
-void BackgroundFetchSettledFetch::Trace(blink::Visitor* visitor) {
- visitor->Trace(response_);
- BackgroundFetchFetch::Trace(visitor);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h
deleted file mode 100644
index 49831fedcb0..00000000000
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_FETCH_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_FETCH_H_
-
-#include "third_party/blink/renderer/modules/background_fetch/background_fetch_fetch.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-
-namespace blink {
-
-class Request;
-class Response;
-
-// Interface for providing developers access to the Request/Response pairs when
-// a background fetch has settled, either through the `backgroundfetchsuccess`
-// event in case of success, or `backgroundfetchfail` in case of failure.
-class BackgroundFetchSettledFetch final : public BackgroundFetchFetch {
- DEFINE_WRAPPERTYPEINFO();
-
- public:
- static BackgroundFetchSettledFetch* Create(Request* request,
- Response* response) {
- return new BackgroundFetchSettledFetch(request, response);
- }
-
- // Web Exposed attribute defined in the IDL file.
- Response* response() const;
-
- void Trace(blink::Visitor* visitor) override;
-
- private:
- BackgroundFetchSettledFetch(Request* request, Response* response);
-
- Member<Response> response_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_FETCH_H_
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.idl
deleted file mode 100644
index 8bee778bbfe..00000000000
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.idl
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// https://wicg.github.io/background-fetch/#backgroundfetchsettledfetch
-
-[
- Constructor(Request request, Response response),
- Exposed=ServiceWorker,
- OriginTrialEnabled=BackgroundFetch
-] interface BackgroundFetchSettledFetch : BackgroundFetchFetch {
- readonly attribute Response? response;
-};
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc
index 385b64a2999..ccde3bb86c0 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc
@@ -26,24 +26,24 @@ TypeConverter<blink::BackgroundFetchRegistration*,
mojo_registration->result, mojo_registration->failure_reason);
}
-blink::mojom::blink::BackgroundFetchOptionsPtr TypeConverter<
- blink::mojom::blink::BackgroundFetchOptionsPtr,
- blink::BackgroundFetchOptions>::Convert(const blink::BackgroundFetchOptions&
- options) {
+blink::mojom::blink::BackgroundFetchOptionsPtr
+TypeConverter<blink::mojom::blink::BackgroundFetchOptionsPtr,
+ const blink::BackgroundFetchOptions*>::
+ Convert(const blink::BackgroundFetchOptions* options) {
blink::mojom::blink::BackgroundFetchOptionsPtr mojo_options =
blink::mojom::blink::BackgroundFetchOptions::New();
WTF::Vector<blink::mojom::blink::ManifestImageResourcePtr> mojo_icons;
- mojo_icons.ReserveInitialCapacity(options.icons().size());
+ mojo_icons.ReserveInitialCapacity(options->icons().size());
- for (const auto& icon : options.icons()) {
+ for (auto& icon : options->icons()) {
mojo_icons.push_back(
- blink::mojom::blink::ManifestImageResource::From(icon));
+ blink::mojom::blink::ManifestImageResource::From(icon.Get()));
}
mojo_options->icons = std::move(mojo_icons);
- mojo_options->download_total = options.downloadTotal();
- mojo_options->title = options.hasTitle() ? options.title() : "";
+ mojo_options->download_total = options->downloadTotal();
+ mojo_options->title = options->hasTitle() ? options->title() : "";
return mojo_options;
}
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h
index 3ee7d587555..08aa085da9d 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h
@@ -24,9 +24,9 @@ struct TypeConverter<blink::BackgroundFetchRegistration*,
template <>
struct TypeConverter<blink::mojom::blink::BackgroundFetchOptionsPtr,
- blink::BackgroundFetchOptions> {
+ const blink::BackgroundFetchOptions*> {
static blink::mojom::blink::BackgroundFetchOptionsPtr Convert(
- const blink::BackgroundFetchOptions& options);
+ const blink::BackgroundFetchOptions* options);
};
} // namespace mojo
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc
index 824f86a52dd..0ba564868a6 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc
@@ -13,21 +13,21 @@
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h"
-#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h"
#include "third_party/blink/renderer/modules/background_fetch/background_fetch_ui_options.h"
-#include "third_party/blink/renderer/modules/event_modules_names.h"
+#include "third_party/blink/renderer/modules/event_interface_modules_names.h"
+#include "third_party/blink/renderer/modules/service_worker/wait_until_observer.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
BackgroundFetchUpdateUIEvent::BackgroundFetchUpdateUIEvent(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer)
+ const BackgroundFetchEventInit* initializer)
: BackgroundFetchEvent(type, initializer, nullptr /* observer */) {}
BackgroundFetchUpdateUIEvent::BackgroundFetchUpdateUIEvent(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer,
+ const BackgroundFetchEventInit* initializer,
WaitUntilObserver* observer,
ServiceWorkerRegistration* registration)
: BackgroundFetchEvent(type, initializer, observer),
@@ -43,13 +43,20 @@ void BackgroundFetchUpdateUIEvent::Trace(blink::Visitor* visitor) {
ScriptPromise BackgroundFetchUpdateUIEvent::updateUI(
ScriptState* script_state,
- const BackgroundFetchUIOptions& ui_options) {
+ const BackgroundFetchUIOptions* ui_options) {
+ if (observer_ && !observer_->IsEventActive(script_state)) {
+ // Return a rejected promise as the event is no longer active.
+ return ScriptPromise::RejectWithDOMException(
+ script_state,
+ DOMException::Create(DOMExceptionCode::kInvalidStateError,
+ "ExtendableEvent is no longer active."));
+ }
if (update_ui_called_) {
// Return a rejected promise as this method should only be called once.
- return ScriptPromise::Reject(
+ return ScriptPromise::RejectWithDOMException(
script_state,
- V8ThrowException::CreateTypeError(script_state->GetIsolate(),
- "updateUI may only be called once."));
+ DOMException::Create(DOMExceptionCode::kInvalidStateError,
+ "updateUI may only be called once."));
}
update_ui_called_ = true;
@@ -63,7 +70,7 @@ ScriptPromise BackgroundFetchUpdateUIEvent::updateUI(
}
DCHECK(!registration_->unique_id().IsEmpty());
- if (!ui_options.hasTitle() && ui_options.icons().IsEmpty()) {
+ if (!ui_options->hasTitle() && ui_options->icons().IsEmpty()) {
// Nothing to update, just return a resolved promise.
return ScriptPromise::CastUndefined(script_state);
}
@@ -71,18 +78,18 @@ ScriptPromise BackgroundFetchUpdateUIEvent::updateUI(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- if (ui_options.icons().IsEmpty()) {
- DidGetIcon(resolver, ui_options.title(), SkBitmap(),
+ if (ui_options->icons().IsEmpty()) {
+ DidGetIcon(resolver, ui_options->title(), SkBitmap(),
-1 /* ideal_to_chosen_icon_size */);
} else {
DCHECK(!loader_);
loader_ = new BackgroundFetchIconLoader();
DCHECK(loader_);
loader_->Start(BackgroundFetchBridge::From(service_worker_registration_),
- ExecutionContext::From(script_state), ui_options.icons(),
+ ExecutionContext::From(script_state), ui_options->icons(),
WTF::Bind(&BackgroundFetchUpdateUIEvent::DidGetIcon,
WrapPersistent(this), WrapPersistent(resolver),
- ui_options.title()));
+ ui_options->title()));
}
return promise;
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h
index e6090c44a29..c6baa7f2029 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h
@@ -29,13 +29,13 @@ class MODULES_EXPORT BackgroundFetchUpdateUIEvent final
public:
static BackgroundFetchUpdateUIEvent* Create(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer) {
+ const BackgroundFetchEventInit* initializer) {
return new BackgroundFetchUpdateUIEvent(type, initializer);
}
static BackgroundFetchUpdateUIEvent* Create(
const AtomicString& type,
- const BackgroundFetchEventInit& initializer,
+ const BackgroundFetchEventInit* initializer,
WaitUntilObserver* observer,
ServiceWorkerRegistration* registration) {
return new BackgroundFetchUpdateUIEvent(type, initializer, observer,
@@ -46,16 +46,16 @@ class MODULES_EXPORT BackgroundFetchUpdateUIEvent final
// Web Exposed method defined in the IDL file.
ScriptPromise updateUI(ScriptState* script_state,
- const BackgroundFetchUIOptions& ui_options);
+ const BackgroundFetchUIOptions* ui_options);
void Trace(blink::Visitor* visitor) override;
private:
BackgroundFetchUpdateUIEvent(const AtomicString& type,
- const BackgroundFetchEventInit& initializer);
+ const BackgroundFetchEventInit* initializer);
BackgroundFetchUpdateUIEvent(const AtomicString& type,
- const BackgroundFetchEventInit& init,
+ const BackgroundFetchEventInit* init,
WaitUntilObserver* observer,
ServiceWorkerRegistration* registration);
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h
index eca44d20b60..b1b4b6e0214 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h
@@ -14,10 +14,14 @@ class ServiceWorkerGlobalScopeBackgroundFetch {
STATIC_ONLY(ServiceWorkerGlobalScopeBackgroundFetch);
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchsuccess);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchfail);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchabort);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchclick);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchsuccess,
+ kBackgroundfetchsuccess);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchfail,
+ kBackgroundfetchfail);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchabort,
+ kBackgroundfetchabort);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchclick,
+ kBackgroundfetchclick);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.cc b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.cc
index 173eddac96e..802173ff1ea 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.cc
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.cc
@@ -27,7 +27,8 @@ ServiceWorkerRegistrationBackgroundFetch::From(
ServiceWorkerRegistrationBackgroundFetch>(registration);
if (!supplement) {
- supplement = new ServiceWorkerRegistrationBackgroundFetch(&registration);
+ supplement = MakeGarbageCollected<ServiceWorkerRegistrationBackgroundFetch>(
+ &registration);
ProvideTo(registration, supplement);
}
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.h b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.h
index bcb9929b839..0fd6893beb7 100644
--- a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.h
+++ b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_registration_background_fetch.h
@@ -24,6 +24,8 @@ class ServiceWorkerRegistrationBackgroundFetch final
public:
static const char kSupplementName[];
+ explicit ServiceWorkerRegistrationBackgroundFetch(
+ ServiceWorkerRegistration* registration);
virtual ~ServiceWorkerRegistrationBackgroundFetch();
static ServiceWorkerRegistrationBackgroundFetch& From(
@@ -36,9 +38,6 @@ class ServiceWorkerRegistrationBackgroundFetch final
void Trace(blink::Visitor* visitor) override;
private:
- explicit ServiceWorkerRegistrationBackgroundFetch(
- ServiceWorkerRegistration* registration);
-
Member<ServiceWorkerRegistration> registration_;
Member<BackgroundFetchManager> background_fetch_manager_;
};
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/OWNERS b/chromium/third_party/blink/renderer/modules/background_sync/OWNERS
index a97cadfaa3d..7f3d55bab8a 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/background_sync/OWNERS
@@ -1,4 +1,5 @@
iclelland@chromium.org
jkarlin@chromium.org
+peter@chromium.org
# COMPONENT: Blink>BackgroundSync
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/service_worker_global_scope_sync.h b/chromium/third_party/blink/renderer/modules/background_sync/service_worker_global_scope_sync.h
index 6a50145d1e2..be2c50f91fa 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/service_worker_global_scope_sync.h
+++ b/chromium/third_party/blink/renderer/modules/background_sync/service_worker_global_scope_sync.h
@@ -11,7 +11,7 @@ namespace blink {
class ServiceWorkerGlobalScopeSync {
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(sync);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(sync, kSync);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.cc b/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.cc
index afdd17ea00d..0ceffbf01e8 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.cc
@@ -24,7 +24,8 @@ ServiceWorkerRegistrationSync& ServiceWorkerRegistrationSync::From(
Supplement<ServiceWorkerRegistration>::From<
ServiceWorkerRegistrationSync>(registration);
if (!supplement) {
- supplement = new ServiceWorkerRegistrationSync(&registration);
+ supplement =
+ MakeGarbageCollected<ServiceWorkerRegistrationSync>(&registration);
ProvideTo(registration, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.h b/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.h
index d8a67c0b7a0..c26e17e9b26 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.h
+++ b/chromium/third_party/blink/renderer/modules/background_sync/service_worker_registration_sync.h
@@ -23,6 +23,7 @@ class ServiceWorkerRegistrationSync final
public:
static const char kSupplementName[];
+ explicit ServiceWorkerRegistrationSync(ServiceWorkerRegistration*);
virtual ~ServiceWorkerRegistrationSync();
static ServiceWorkerRegistrationSync& From(ServiceWorkerRegistration&);
@@ -32,8 +33,6 @@ class ServiceWorkerRegistrationSync final
void Trace(blink::Visitor*) override;
private:
- explicit ServiceWorkerRegistrationSync(ServiceWorkerRegistration*);
-
Member<ServiceWorkerRegistration> registration_;
Member<SyncManager> sync_manager_;
};
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/sync_event.cc b/chromium/third_party/blink/renderer/modules/background_sync/sync_event.cc
index 0051bf94661..bf5d209fa06 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/sync_event.cc
+++ b/chromium/third_party/blink/renderer/modules/background_sync/sync_event.cc
@@ -10,20 +10,20 @@ SyncEvent::SyncEvent(const AtomicString& type,
const String& tag,
bool last_chance,
WaitUntilObserver* observer)
- : ExtendableEvent(type, ExtendableEventInit(), observer),
+ : ExtendableEvent(type, ExtendableEventInit::Create(), observer),
tag_(tag),
last_chance_(last_chance) {}
-SyncEvent::SyncEvent(const AtomicString& type, const SyncEventInit& init)
+SyncEvent::SyncEvent(const AtomicString& type, const SyncEventInit* init)
: ExtendableEvent(type, init) {
- tag_ = init.tag();
- last_chance_ = init.lastChance();
+ tag_ = init->tag();
+ last_chance_ = init->lastChance();
}
SyncEvent::~SyncEvent() = default;
const AtomicString& SyncEvent::InterfaceName() const {
- return EventNames::SyncEvent;
+ return event_interface_names::kSyncEvent;
}
String SyncEvent::tag() {
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/sync_event.h b/chromium/third_party/blink/renderer/modules/background_sync/sync_event.h
index 478a25dc517..604bdec0d54 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/sync_event.h
+++ b/chromium/third_party/blink/renderer/modules/background_sync/sync_event.h
@@ -22,13 +22,15 @@ class MODULES_EXPORT SyncEvent final : public ExtendableEvent {
const String& tag,
bool last_chance,
WaitUntilObserver* observer) {
- return new SyncEvent(type, tag, last_chance, observer);
+ return MakeGarbageCollected<SyncEvent>(type, tag, last_chance, observer);
}
static SyncEvent* Create(const AtomicString& type,
- const SyncEventInit& init) {
- return new SyncEvent(type, init);
+ const SyncEventInit* init) {
+ return MakeGarbageCollected<SyncEvent>(type, init);
}
+ SyncEvent(const AtomicString& type, const String&, bool, WaitUntilObserver*);
+ SyncEvent(const AtomicString& type, const SyncEventInit*);
~SyncEvent() override;
const AtomicString& InterfaceName() const override;
@@ -39,9 +41,6 @@ class MODULES_EXPORT SyncEvent final : public ExtendableEvent {
void Trace(blink::Visitor*) override;
private:
- SyncEvent(const AtomicString& type, const String&, bool, WaitUntilObserver*);
- SyncEvent(const AtomicString& type, const SyncEventInit&);
-
String tag_;
bool last_chance_;
};
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.cc b/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.cc
index 18ce0431d10..079117f2c6b 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.cc
@@ -25,28 +25,24 @@ SyncManager::SyncManager(ServiceWorkerRegistration* registration)
ScriptPromise SyncManager::registerFunction(ScriptState* script_state,
const String& tag) {
- // TODO(jkarlin): Wait for the registration to become active instead of
- // rejecting. See crbug.com/542437.
- if (!registration_->active())
+ if (!registration_->active()) {
return ScriptPromise::RejectWithDOMException(
script_state,
- DOMException::Create(DOMExceptionCode::kAbortError,
+ DOMException::Create(DOMExceptionCode::kInvalidStateError,
"Registration failed - no active Service Worker"));
+ }
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
mojom::blink::SyncRegistrationPtr sync_registration =
mojom::blink::SyncRegistration::New();
- sync_registration->id = SyncManager::kUnregisteredSyncID;
sync_registration->tag = tag;
- sync_registration->network_state =
- blink::mojom::BackgroundSyncNetworkState::ONLINE;
GetBackgroundSyncServicePtr()->Register(
- std::move(sync_registration),
- registration_->WebRegistration()->RegistrationId(),
- WTF::Bind(SyncManager::RegisterCallback, WrapPersistent(resolver)));
+ std::move(sync_registration), registration_->RegistrationId(),
+ WTF::Bind(&SyncManager::RegisterCallback, WrapPersistent(this),
+ WrapPersistent(resolver)));
return promise;
}
@@ -56,7 +52,7 @@ ScriptPromise SyncManager::getTags(ScriptState* script_state) {
ScriptPromise promise = resolver->Promise();
GetBackgroundSyncServicePtr()->GetRegistrations(
- registration_->WebRegistration()->RegistrationId(),
+ registration_->RegistrationId(),
WTF::Bind(&SyncManager::GetRegistrationsCallback,
WrapPersistent(resolver)));
@@ -72,7 +68,6 @@ SyncManager::GetBackgroundSyncServicePtr() {
return background_sync_service_;
}
-// static
void SyncManager::RegisterCallback(ScriptPromiseResolver* resolver,
mojom::blink::BackgroundSyncError error,
mojom::blink::SyncRegistrationPtr options) {
@@ -84,6 +79,10 @@ void SyncManager::RegisterCallback(ScriptPromiseResolver* resolver,
return;
}
resolver->Resolve();
+ // Let the service know that the registration promise is resolved so that
+ // it can fire the event.
+ GetBackgroundSyncServicePtr()->DidResolveRegistration(
+ registration_->RegistrationId(), options->tag);
break;
case mojom::blink::BackgroundSyncError::NOT_FOUND:
NOTREACHED();
@@ -99,8 +98,8 @@ void SyncManager::RegisterCallback(ScriptPromiseResolver* resolver,
"window or registration tag too long."));
break;
case mojom::blink::BackgroundSyncError::PERMISSION_DENIED:
- resolver->Reject(DOMException::Create(
- DOMExceptionCode::kPermissionDeniedError, "Permission denied."));
+ resolver->Reject(DOMException::Create(DOMExceptionCode::kNotAllowedError,
+ "Permission denied."));
break;
case mojom::blink::BackgroundSyncError::NO_SERVICE_WORKER:
resolver->Reject(DOMException::Create(DOMExceptionCode::kUnknownError,
diff --git a/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.h b/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.h
index 432c605e361..dd37db136c4 100644
--- a/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.h
+++ b/chromium/third_party/blink/renderer/modules/background_sync/sync_manager.h
@@ -22,9 +22,11 @@ class SyncManager final : public ScriptWrappable {
public:
static SyncManager* Create(ServiceWorkerRegistration* registration) {
- return new SyncManager(registration);
+ return MakeGarbageCollected<SyncManager>(registration);
}
+ explicit SyncManager(ServiceWorkerRegistration*);
+
ScriptPromise registerFunction(ScriptState*, const String& tag);
ScriptPromise getTags(ScriptState*);
@@ -33,17 +35,15 @@ class SyncManager final : public ScriptWrappable {
enum { kUnregisteredSyncID = -1 };
private:
- explicit SyncManager(ServiceWorkerRegistration*);
-
// Returns an initialized BackgroundSyncServicePtr. A connection with the
// the browser's BackgroundSyncService is created the first time this method
// is called.
const mojom::blink::BackgroundSyncServicePtr& GetBackgroundSyncServicePtr();
// Callbacks
- static void RegisterCallback(ScriptPromiseResolver*,
- mojom::blink::BackgroundSyncError,
- mojom::blink::SyncRegistrationPtr options);
+ void RegisterCallback(ScriptPromiseResolver*,
+ mojom::blink::BackgroundSyncError,
+ mojom::blink::SyncRegistrationPtr options);
static void GetRegistrationsCallback(
ScriptPromiseResolver*,
mojom::blink::BackgroundSyncError,
diff --git a/chromium/third_party/blink/renderer/modules/badging/README.md b/chromium/third_party/blink/renderer/modules/badging/README.md
index ad293263220..69de88b73cb 100644
--- a/chromium/third_party/blink/renderer/modules/badging/README.md
+++ b/chromium/third_party/blink/renderer/modules/badging/README.md
@@ -19,6 +19,6 @@ and exposes two static methods:
### Testing
-`LayoutTests/badging/*.html` tests that the API accepts/rejects the appropriate
+`web_tests/badging/*.html` tests that the API accepts/rejects the appropriate
inputs (with a mock Mojo service). Testing at other layers will be added
during implementation.
diff --git a/chromium/third_party/blink/renderer/modules/battery/battery_manager.cc b/chromium/third_party/blink/renderer/modules/battery/battery_manager.cc
index 7f4e94f96ce..b47d0a6f5e5 100644
--- a/chromium/third_party/blink/renderer/modules/battery/battery_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/battery/battery_manager.cc
@@ -74,13 +74,13 @@ void BatteryManager::DidUpdateData() {
return;
if (battery_status_.Charging() != old_status.Charging())
- DispatchEvent(*Event::Create(EventTypeNames::chargingchange));
+ DispatchEvent(*Event::Create(event_type_names::kChargingchange));
if (battery_status_.charging_time() != old_status.charging_time())
- DispatchEvent(*Event::Create(EventTypeNames::chargingtimechange));
+ DispatchEvent(*Event::Create(event_type_names::kChargingtimechange));
if (battery_status_.discharging_time() != old_status.discharging_time())
- DispatchEvent(*Event::Create(EventTypeNames::dischargingtimechange));
+ DispatchEvent(*Event::Create(event_type_names::kDischargingtimechange));
if (battery_status_.Level() != old_status.Level())
- DispatchEvent(*Event::Create(EventTypeNames::levelchange));
+ DispatchEvent(*Event::Create(event_type_names::kLevelchange));
}
void BatteryManager::RegisterWithDispatcher() {
diff --git a/chromium/third_party/blink/renderer/modules/battery/battery_manager.h b/chromium/third_party/blink/renderer/modules/battery/battery_manager.h
index 478606eb068..93b1acfaf6f 100644
--- a/chromium/third_party/blink/renderer/modules/battery/battery_manager.h
+++ b/chromium/third_party/blink/renderer/modules/battery/battery_manager.h
@@ -33,7 +33,7 @@ class BatteryManager final : public EventTargetWithInlineData,
// EventTarget implementation.
const WTF::AtomicString& InterfaceName() const override {
- return EventTargetNames::BatteryManager;
+ return event_target_names::kBatteryManager;
}
ExecutionContext* GetExecutionContext() const override {
return ContextLifecycleObserver::GetExecutionContext();
@@ -44,10 +44,11 @@ class BatteryManager final : public EventTargetWithInlineData,
double dischargingTime();
double level();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(chargingchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(chargingtimechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dischargingtimechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(levelchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(chargingchange, kChargingchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(chargingtimechange, kChargingtimechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(dischargingtimechange,
+ kDischargingtimechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(levelchange, kLevelchange);
// Inherited from PlatformEventController.
void DidUpdateData() override;
diff --git a/chromium/third_party/blink/renderer/modules/battery/navigator_battery.cc b/chromium/third_party/blink/renderer/modules/battery/navigator_battery.cc
index 3a80ad95c17..5825ea62e74 100644
--- a/chromium/third_party/blink/renderer/modules/battery/navigator_battery.cc
+++ b/chromium/third_party/blink/renderer/modules/battery/navigator_battery.cc
@@ -46,7 +46,7 @@ NavigatorBattery& NavigatorBattery::From(Navigator& navigator) {
NavigatorBattery* supplement =
Supplement<Navigator>::From<NavigatorBattery>(navigator);
if (!supplement) {
- supplement = new NavigatorBattery(navigator);
+ supplement = MakeGarbageCollected<NavigatorBattery>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/battery/navigator_battery.h b/chromium/third_party/blink/renderer/modules/battery/navigator_battery.h
index c72858412d5..e8aa9027444 100644
--- a/chromium/third_party/blink/renderer/modules/battery/navigator_battery.h
+++ b/chromium/third_party/blink/renderer/modules/battery/navigator_battery.h
@@ -27,11 +27,11 @@ class NavigatorBattery final : public GarbageCollected<NavigatorBattery>,
static ScriptPromise getBattery(ScriptState*, Navigator&);
ScriptPromise getBattery(ScriptState*);
+ explicit NavigatorBattery(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorBattery(Navigator&);
-
Member<BatteryManager> battery_manager_;
};
diff --git a/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.cc b/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.cc
index 6de7d1a5a72..463a511b813 100644
--- a/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.cc
+++ b/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.cc
@@ -34,7 +34,7 @@ NavigatorBeacon& NavigatorBeacon::From(Navigator& navigator) {
NavigatorBeacon* supplement =
Supplement<Navigator>::From<NavigatorBeacon>(navigator);
if (!supplement) {
- supplement = new NavigatorBeacon(navigator);
+ supplement = MakeGarbageCollected<NavigatorBeacon>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -88,7 +88,7 @@ bool NavigatorBeacon::SendBeaconImpl(
data.GetAsArrayBufferView().View());
} else if (data.IsBlob()) {
Blob* blob = data.GetAsBlob();
- if (!CORS::IsCORSSafelistedContentType(blob->type())) {
+ if (!cors::IsCorsSafelistedContentType(blob->type())) {
UseCounter::Count(context,
WebFeature::kSendBeaconWithNonSimpleContentType);
if (RuntimeEnabledFeatures::
diff --git a/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.h b/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.h
index 8b460562219..57ba79dcb88 100644
--- a/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.h
+++ b/chromium/third_party/blink/renderer/modules/beacon/navigator_beacon.h
@@ -24,6 +24,8 @@ class NavigatorBeacon final : public GarbageCollectedFinalized<NavigatorBeacon>,
static const char kSupplementName[];
static NavigatorBeacon& From(Navigator&);
+
+ explicit NavigatorBeacon(Navigator&);
virtual ~NavigatorBeacon();
static bool sendBeacon(ScriptState*,
@@ -35,8 +37,6 @@ class NavigatorBeacon final : public GarbageCollectedFinalized<NavigatorBeacon>,
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorBeacon(Navigator&);
-
bool SendBeaconImpl(ScriptState*,
const String&,
const ArrayBufferViewOrBlobOrStringOrFormData&,
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/README.md b/chromium/third_party/blink/renderer/modules/bluetooth/README.md
index 3177908d611..6e6299cb079 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/README.md
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/README.md
@@ -34,9 +34,9 @@ Web Bluetooth implementation details are tested at several layers:
* `out/Release/content_unittests --gtest_filter="*Bluetooth*"`
* Trusted Web Bluetooth code (browser process) tests
(as opposed to untrusted renderer process).
-* `LayoutTests/bluetooth/*/*.html`
+* `web_tests/bluetooth/*/*.html`
* `blink/tools/run_layout_tests.sh bluetooth`
- * Layout tests in `LayoutTests/bluetooth/` rely on
+ * Layout tests in `web_tests/bluetooth/` rely on
fake Bluetooth implementation classes constructed in
`content/shell/browser/layout_test/layout_test_bluetooth_adapter_provider`.
These tests span JavaScript binding to the `device/bluetooth` platform
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.cc b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.cc
index a875e13ae06..594f207e606 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.cc
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.cc
@@ -23,6 +23,7 @@
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_uuid.h"
#include "third_party/blink/renderer/modules/bluetooth/request_device_options.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -36,23 +37,24 @@ const char kDeviceNameTooLong[] =
} // namespace
static void CanonicalizeFilter(
- const BluetoothLEScanFilterInit& filter,
+ const BluetoothLEScanFilterInit* filter,
mojom::blink::WebBluetoothLeScanFilterPtr& canonicalized_filter,
ExceptionState& exception_state) {
- if (!(filter.hasServices() || filter.hasName() || filter.hasNamePrefix())) {
+ if (!(filter->hasServices() || filter->hasName() ||
+ filter->hasNamePrefix())) {
exception_state.ThrowTypeError(
"A filter must restrict the devices in some way.");
return;
}
- if (filter.hasServices()) {
- if (filter.services().size() == 0) {
+ if (filter->hasServices()) {
+ if (filter->services().size() == 0) {
exception_state.ThrowTypeError(
"'services', if present, must contain at least one service.");
return;
}
canonicalized_filter->services.emplace();
- for (const StringOrUnsignedLong& service : filter.services()) {
+ for (const StringOrUnsignedLong& service : filter->services()) {
const String& validated_service =
BluetoothUUID::getService(service, exception_state);
if (exception_state.HadException())
@@ -61,45 +63,45 @@ static void CanonicalizeFilter(
}
}
- if (filter.hasName()) {
- size_t name_length = filter.name().Utf8().length();
+ if (filter->hasName()) {
+ size_t name_length = filter->name().Utf8().length();
if (name_length > kMaxDeviceNameLength) {
exception_state.ThrowTypeError(kDeviceNameTooLong);
return;
}
- canonicalized_filter->name = filter.name();
+ canonicalized_filter->name = filter->name();
}
- if (filter.hasNamePrefix()) {
- size_t name_prefix_length = filter.namePrefix().Utf8().length();
+ if (filter->hasNamePrefix()) {
+ size_t name_prefix_length = filter->namePrefix().Utf8().length();
if (name_prefix_length > kMaxDeviceNameLength) {
exception_state.ThrowTypeError(kDeviceNameTooLong);
return;
}
- if (filter.namePrefix().length() == 0) {
+ if (filter->namePrefix().length() == 0) {
exception_state.ThrowTypeError(
"'namePrefix', if present, must me non-empty.");
return;
}
- canonicalized_filter->name_prefix = filter.namePrefix();
+ canonicalized_filter->name_prefix = filter->namePrefix();
}
}
static void ConvertRequestDeviceOptions(
- const RequestDeviceOptions& options,
+ const RequestDeviceOptions* options,
mojom::blink::WebBluetoothRequestDeviceOptionsPtr& result,
ExceptionState& exception_state) {
- if (!(options.hasFilters() ^ options.acceptAllDevices())) {
+ if (!(options->hasFilters() ^ options->acceptAllDevices())) {
exception_state.ThrowTypeError(
"Either 'filters' should be present or 'acceptAllDevices' should be "
"true, but not both.");
return;
}
- result->accept_all_devices = options.acceptAllDevices();
+ result->accept_all_devices = options->acceptAllDevices();
- if (options.hasFilters()) {
- if (options.filters().IsEmpty()) {
+ if (options->hasFilters()) {
+ if (options->filters().IsEmpty()) {
exception_state.ThrowTypeError(
"'filters' member must be non-empty to find any devices.");
return;
@@ -107,7 +109,7 @@ static void ConvertRequestDeviceOptions(
result->filters.emplace();
- for (const BluetoothLEScanFilterInit& filter : options.filters()) {
+ for (const BluetoothLEScanFilterInit* filter : options->filters()) {
auto canonicalized_filter = mojom::blink::WebBluetoothLeScanFilter::New();
CanonicalizeFilter(filter, canonicalized_filter, exception_state);
@@ -119,9 +121,9 @@ static void ConvertRequestDeviceOptions(
}
}
- if (options.hasOptionalServices()) {
+ if (options->hasOptionalServices()) {
for (const StringOrUnsignedLong& optional_service :
- options.optionalServices()) {
+ options->optionalServices()) {
const String& validated_optional_service =
BluetoothUUID::getService(optional_service, exception_state);
if (exception_state.HadException())
@@ -150,7 +152,7 @@ void Bluetooth::RequestDeviceCallback(
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
ScriptPromise Bluetooth::requestDevice(ScriptState* script_state,
- const RequestDeviceOptions& options,
+ const RequestDeviceOptions* options,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.h b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.h
index de184e50e43..835ba811ac5 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.h
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth.h
@@ -26,7 +26,7 @@ class Bluetooth final : public ScriptWrappable {
// IDL exposed interface:
ScriptPromise requestDevice(ScriptState*,
- const RequestDeviceOptions&,
+ const RequestDeviceOptions*,
ExceptionState&);
mojom::blink::WebBluetoothService* Service() { return service_.get(); }
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.cc b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.cc
index 0707a4f3a49..dbc56440ff9 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.cc
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.cc
@@ -79,11 +79,12 @@ bool BluetoothDevice::IsValidDescriptor(const String& descriptor_instance_id) {
void BluetoothDevice::ClearAttributeInstanceMapAndFireEvent() {
attribute_instance_map_->Clear();
- DispatchEvent(*Event::CreateBubble(EventTypeNames::gattserverdisconnected));
+ DispatchEvent(
+ *Event::CreateBubble(event_type_names::kGattserverdisconnected));
}
const WTF::AtomicString& BluetoothDevice::InterfaceName() const {
- return EventTargetNames::BluetoothDevice;
+ return event_target_names::kBluetoothDevice;
}
ExecutionContext* BluetoothDevice::GetExecutionContext() const {
@@ -103,7 +104,7 @@ void BluetoothDevice::AddedEventListener(
RegisteredEventListener& registered_listener) {
EventTargetWithInlineData::AddedEventListener(event_type,
registered_listener);
- if (event_type == EventTypeNames::gattserverdisconnected) {
+ if (event_type == event_type_names::kGattserverdisconnected) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kGATTServerDisconnectedEvent);
}
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.h b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.h
index 32bacfaa2e0..e0ad24c33bd 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.h
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_device.h
@@ -89,7 +89,8 @@ class BluetoothDevice final : public EventTargetWithInlineData,
String name() { return device_->name; }
BluetoothRemoteGATTServer* gatt() { return gatt_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(gattserverdisconnected);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(gattserverdisconnected,
+ kGattserverdisconnected);
protected:
// EventTarget overrides:
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc
index af626a26b23..5a771115df3 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.cc
@@ -56,7 +56,7 @@ void BluetoothRemoteGATTCharacteristic::RemoteCharacteristicValueChanged(
if (!GetGatt()->connected())
return;
this->SetValue(BluetoothRemoteGATTUtils::ConvertWTFVectorToDataView(value));
- DispatchEvent(*Event::Create(EventTypeNames::characteristicvaluechanged));
+ DispatchEvent(*Event::Create(event_type_names::kCharacteristicvaluechanged));
}
void BluetoothRemoteGATTCharacteristic::ContextDestroyed(ExecutionContext*) {
@@ -69,7 +69,7 @@ void BluetoothRemoteGATTCharacteristic::Dispose() {
const WTF::AtomicString& BluetoothRemoteGATTCharacteristic::InterfaceName()
const {
- return EventTargetNames::BluetoothRemoteGATTCharacteristic;
+ return event_target_names::kBluetoothRemoteGATTCharacteristic;
}
ExecutionContext* BluetoothRemoteGATTCharacteristic::GetExecutionContext()
@@ -111,7 +111,8 @@ void BluetoothRemoteGATTCharacteristic::ReadValueCallback(
DOMDataView* dom_data_view =
BluetoothRemoteGATTUtils::ConvertWTFVectorToDataView(value.value());
SetValue(dom_data_view);
- DispatchEvent(*Event::Create(EventTypeNames::characteristicvaluechanged));
+ DispatchEvent(
+ *Event::Create(event_type_names::kCharacteristicvaluechanged));
resolver->Resolve(dom_data_view);
} else {
resolver->Reject(BluetoothError::CreateDOMException(result));
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h
index 8a9c2b440e7..07ec2d39453 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h
@@ -97,7 +97,8 @@ class BluetoothRemoteGATTCharacteristic final
ScriptPromise startNotifications(ScriptState*);
ScriptPromise stopNotifications(ScriptState*);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(characteristicvaluechanged);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(characteristicvaluechanged,
+ kCharacteristicvaluechanged);
protected:
// EventTarget overrides.
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.cc b/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.cc
index dd624549710..207382be36d 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.cc
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.cc
@@ -13,7 +13,7 @@ NavigatorBluetooth& NavigatorBluetooth::From(Navigator& navigator) {
NavigatorBluetooth* supplement =
Supplement<Navigator>::From<NavigatorBluetooth>(navigator);
if (!supplement) {
- supplement = new NavigatorBluetooth(navigator);
+ supplement = MakeGarbageCollected<NavigatorBluetooth>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.h b/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.h
index 6226aa30f8e..83b7518af91 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.h
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/navigator_bluetooth.h
@@ -30,11 +30,11 @@ class NavigatorBluetooth final : public GarbageCollected<NavigatorBluetooth>,
// IDL exposed interface:
Bluetooth* bluetooth();
+ explicit NavigatorBluetooth(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorBluetooth(Navigator&);
-
Member<Bluetooth> bluetooth_;
};
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/README.md b/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/README.md
index 702a23f06c7..9f1f483cc2f 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/README.md
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/README.md
@@ -25,7 +25,7 @@ arguments, `--no_of_files`, `--input_dir`, and `--output_dir`.
## Setup
This fuzzer depends on files in:
-* `//src/third_party/WebKit/LayoutTests/resources`
+* `//src/third_party/blink/web_tests/resources`
* `//src/testing/clusterfuzz/common`
To ease development a setup.py script is included to copy over the necessary
diff --git a/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py b/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py
index 416f6bd06c8..3bd4809c8a1 100644
--- a/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py
+++ b/chromium/third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/setup.py
@@ -22,9 +22,9 @@ import sys
SRC_PATH = os.path.join(
os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)
LAYOUT_TESTS_RESOURCES_PATH = os.path.join(
- SRC_PATH, 'third_party', 'WebKit', 'LayoutTests', 'resources')
+ SRC_PATH, 'third_party', 'blink', 'web_tests', 'resources')
WEB_PLATFORM_TESTS_RESOURCES_PATH = os.path.join(
- SRC_PATH, 'third_party', 'WebKit', 'LayoutTests', 'external', 'wpt',
+ SRC_PATH, 'third_party', 'blink', 'web_tests', 'external', 'wpt',
'bluetooth', 'resources')
COMMON_FUZZER_RESOURCES_PATH = os.path.join(
SRC_PATH, 'testing', 'clusterfuzz', 'common')
diff --git a/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.cc b/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.cc
index 7a4a0efb5a3..6c666280f97 100644
--- a/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.cc
+++ b/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.cc
@@ -78,11 +78,11 @@ void BroadcastChannel::close() {
}
const AtomicString& BroadcastChannel::InterfaceName() const {
- return EventTargetNames::BroadcastChannel;
+ return event_target_names::kBroadcastChannel;
}
bool BroadcastChannel::HasPendingActivity() const {
- return binding_.is_bound() && HasEventListeners(EventTypeNames::message);
+ return binding_.is_bound() && HasEventListeners(event_type_names::kMessage);
}
void BroadcastChannel::ContextDestroyed(ExecutionContext*) {
diff --git a/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.h b/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.h
index bc42e8b09c1..052a1f063c5 100644
--- a/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.h
+++ b/chromium/third_party/blink/renderer/modules/broadcastchannel/broadcast_channel.h
@@ -36,8 +36,8 @@ class BroadcastChannel final : public EventTargetWithInlineData,
String name() const { return name_; }
void postMessage(const ScriptValue&, ExceptionState&);
void close();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(messageerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(messageerror, kMessageerror);
// EventTarget:
const AtomicString& InterfaceName() const override;
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/DEPS b/chromium/third_party/blink/renderer/modules/cache_storage/DEPS
index ba54022a2c0..c4508fff0c8 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/DEPS
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/DEPS
@@ -1,6 +1,5 @@
include_rules = [
"+mojo/public/cpp/bindings",
- "+services/network/public/mojom",
"-third_party/blink/renderer/modules",
"+third_party/blink/renderer/modules/cache_storage",
"+third_party/blink/renderer/modules/event_modules.h",
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/cache.cc b/chromium/third_party/blink/renderer/modules/cache_storage/cache.cc
index c5758cd913d..95e252a1639 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/cache.cc
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/cache.cc
@@ -10,7 +10,6 @@
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "third_party/blink/public/common/cache_storage/cache_storage_utils.h"
#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_response.h"
#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
@@ -64,12 +63,11 @@ bool VaryHeaderContainsAsterisk(const Response* response) {
bool ShouldGenerateV8CodeCache(ScriptState* script_state,
const Response* response) {
- if (!RuntimeEnabledFeatures::PWAFullCodeCacheEnabled())
- return false;
ExecutionContext* context = ExecutionContext::From(script_state);
- if (!context->IsServiceWorkerGlobalScope())
+ auto* global_scope = DynamicTo<ServiceWorkerGlobalScope>(context);
+ if (!global_scope)
return false;
- if (!ToServiceWorkerGlobalScope(context)->IsInstalling())
+ if (!global_scope->IsInstalling())
return false;
if (!MIMETypeRegistry::IsSupportedJavaScriptMIMEType(
response->InternalMIMEType())) {
@@ -190,12 +188,15 @@ class Cache::BarrierCallbackForPut final
if (--number_of_remaining_operations_ != 0)
return;
MaybeReportInstalledScripts();
+ // Make sure to bind the Cache object to keep the mojo interface pointer
+ // alive during the operation. Otherwise GC might prevent the callback
+ // from ever being executed.
cache_->cache_ptr_->Batch(
std::move(batch_operations_),
RuntimeEnabledFeatures::CacheStorageAddAllRejectsDuplicatesEnabled(),
WTF::Bind(
[](const String& method_name, ScriptPromiseResolver* resolver,
- TimeTicks start_time,
+ TimeTicks start_time, Cache* _,
mojom::blink::CacheStorageVerboseErrorPtr error) {
ExecutionContext* context = resolver->GetExecutionContext();
if (!context || context->IsContextDestroyed())
@@ -234,7 +235,8 @@ class Cache::BarrierCallbackForPut final
CacheStorageError::CreateException(error->value, message));
}
},
- method_name_, WrapPersistent(resolver_.Get()), TimeTicks::Now()));
+ method_name_, WrapPersistent(resolver_.Get()), TimeTicks::Now(),
+ WrapPersistent(cache_.Get())));
}
void OnError(const String& error_message) {
@@ -275,10 +277,9 @@ class Cache::BarrierCallbackForPut final
// execution context and it's in installation phase.
void MaybeReportInstalledScripts() {
ExecutionContext* context = resolver_->GetExecutionContext();
- if (!context || !context->IsServiceWorkerGlobalScope())
+ auto* global_scope = DynamicTo<ServiceWorkerGlobalScope>(context);
+ if (!global_scope)
return;
- ServiceWorkerGlobalScope* global_scope =
- ToServiceWorkerGlobalScope(context);
if (!global_scope->IsInstalling())
return;
@@ -319,7 +320,7 @@ class Cache::BlobHandleCallbackForPut final
Request* request,
Response* response)
: index_(index), barrier_callback_(barrier_callback) {
- request->PopulateWebServiceWorkerRequest(web_request_);
+ fetch_api_request_ = request->CreateFetchAPIRequest();
fetch_api_response_ = response->PopulateFetchAPIResponse();
}
~BlobHandleCallbackForPut() override = default;
@@ -329,7 +330,7 @@ class Cache::BlobHandleCallbackForPut final
mojom::blink::BatchOperationPtr batch_operation =
mojom::blink::BatchOperation::New();
batch_operation->operation_type = mojom::blink::OperationType::kPut;
- batch_operation->request = web_request_;
+ batch_operation->request = std::move(fetch_api_request_);
batch_operation->response = std::move(fetch_api_response_);
batch_operation->response->blob = handle;
barrier_callback_->OnSuccess(index_, std::move(batch_operation));
@@ -350,7 +351,7 @@ class Cache::BlobHandleCallbackForPut final
const wtf_size_t index_;
Member<BarrierCallbackForPut> barrier_callback_;
- WebServiceWorkerRequest web_request_;
+ mojom::blink::FetchAPIRequestPtr fetch_api_request_;
mojom::blink::FetchAPIResponsePtr fetch_api_response_;
};
@@ -369,7 +370,7 @@ class Cache::CodeCacheHandleCallbackForPut final
index_(index),
barrier_callback_(barrier_callback),
mime_type_(response->InternalMIMEType()) {
- request->PopulateWebServiceWorkerRequest(web_request_);
+ fetch_api_request_ = request->CreateFetchAPIRequest();
fetch_api_response_ = response->PopulateFetchAPIResponse();
}
~CodeCacheHandleCallbackForPut() override = default;
@@ -378,7 +379,7 @@ class Cache::CodeCacheHandleCallbackForPut final
mojom::blink::BatchOperationPtr batch_operation =
mojom::blink::BatchOperation::New();
batch_operation->operation_type = mojom::blink::OperationType::kPut;
- batch_operation->request = web_request_;
+ batch_operation->request = std::move(fetch_api_request_);
batch_operation->response = std::move(fetch_api_response_);
std::unique_ptr<BlobData> blob_data = BlobData::Create();
@@ -399,7 +400,7 @@ class Cache::CodeCacheHandleCallbackForPut final
script_state_,
text_decoder->Decode(static_cast<const char*>(array_buffer->Data()),
array_buffer->ByteLength()),
- web_request_.Url().GetString(), text_decoder->Encoding(),
+ batch_operation->request->url.GetString(), text_decoder->Encoding(),
batch_operation->response->response_type ==
network::mojom::FetchResponseType::kOpaque
? V8CodeCache::OpaqueMode::kOpaque
@@ -436,7 +437,7 @@ class Cache::CodeCacheHandleCallbackForPut final
Member<BarrierCallbackForPut> barrier_callback_;
const String mime_type_;
- WebServiceWorkerRequest web_request_;
+ mojom::blink::FetchAPIRequestPtr fetch_api_request_;
mojom::blink::FetchAPIResponsePtr fetch_api_response_;
};
@@ -448,7 +449,7 @@ Cache* Cache::Create(
ScriptPromise Cache::match(ScriptState* script_state,
const RequestInfo& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
DCHECK(!request.IsNull());
if (request.IsRequest())
@@ -462,12 +463,12 @@ ScriptPromise Cache::match(ScriptState* script_state,
ScriptPromise Cache::matchAll(ScriptState* script_state,
ExceptionState& exception_state) {
- return MatchAllImpl(script_state, nullptr, CacheQueryOptions());
+ return MatchAllImpl(script_state, nullptr, CacheQueryOptions::Create());
}
ScriptPromise Cache::matchAll(ScriptState* script_state,
const RequestInfo& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
DCHECK(!request.IsNull());
if (request.IsRequest())
@@ -516,7 +517,7 @@ ScriptPromise Cache::addAll(ScriptState* script_state,
ScriptPromise Cache::Delete(ScriptState* script_state,
const RequestInfo& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
DCHECK(!request.IsNull());
if (request.IsRequest())
@@ -548,12 +549,12 @@ ScriptPromise Cache::put(ScriptState* script_state,
}
ScriptPromise Cache::keys(ScriptState* script_state, ExceptionState&) {
- return KeysImpl(script_state, nullptr, CacheQueryOptions());
+ return KeysImpl(script_state, nullptr, CacheQueryOptions::Create());
}
ScriptPromise Cache::keys(ScriptState* script_state,
const RequestInfo& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
DCHECK(!request.IsNull());
if (request.IsRequest())
@@ -567,12 +568,12 @@ ScriptPromise Cache::keys(ScriptState* script_state,
// static
mojom::blink::QueryParamsPtr Cache::ToQueryParams(
- const CacheQueryOptions& options) {
+ const CacheQueryOptions* options) {
mojom::blink::QueryParamsPtr query_params = mojom::blink::QueryParams::New();
- query_params->ignore_search = options.ignoreSearch();
- query_params->ignore_method = options.ignoreMethod();
- query_params->ignore_vary = options.ignoreVary();
- query_params->cache_name = options.cacheName();
+ query_params->ignore_search = options->ignoreSearch();
+ query_params->ignore_method = options->ignoreMethod();
+ query_params->ignore_vary = options->ignoreVary();
+ query_params->cache_name = options->cacheName();
return query_params;
}
@@ -589,22 +590,22 @@ void Cache::Trace(blink::Visitor* visitor) {
ScriptPromise Cache::MatchImpl(ScriptState* script_state,
const Request* request,
- const CacheQueryOptions& options) {
- WebServiceWorkerRequest web_request;
- request->PopulateWebServiceWorkerRequest(web_request);
-
+ const CacheQueryOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
const ScriptPromise promise = resolver->Promise();
- if (request->method() != HTTPNames::GET && !options.ignoreMethod()) {
+ if (request->method() != http_names::kGET && !options->ignoreMethod()) {
resolver->Resolve();
return promise;
}
+ // Make sure to bind the Cache object to keep the mojo interface pointer
+ // alive during the operation. Otherwise GC might prevent the callback
+ // from ever being executed.
cache_ptr_->Match(
- web_request, ToQueryParams(options),
+ request->CreateFetchAPIRequest(), ToQueryParams(options),
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options, Cache* _,
mojom::blink::MatchResultPtr result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
@@ -623,7 +624,7 @@ ScriptPromise Cache::MatchImpl(ScriptState* script_state,
TimeDelta elapsed = TimeTicks::Now() - start_time;
UMA_HISTOGRAM_LONG_TIMES("ServiceWorkerCache.Cache.Match2",
elapsed);
- if (options.hasIgnoreSearch() && options.ignoreSearch()) {
+ if (options->hasIgnoreSearch() && options->ignoreSearch()) {
UMA_HISTOGRAM_LONG_TIMES(
"ServiceWorkerCache.Cache.Match2.IgnoreSearchEnabled",
elapsed);
@@ -637,32 +638,36 @@ ScriptPromise Cache::MatchImpl(ScriptState* script_state,
*result->get_response()));
}
},
- WrapPersistent(resolver), TimeTicks::Now(), options));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(options),
+ WrapPersistent(this)));
return promise;
}
ScriptPromise Cache::MatchAllImpl(ScriptState* script_state,
const Request* request,
- const CacheQueryOptions& options) {
- base::Optional<WebServiceWorkerRequest> web_request;
+ const CacheQueryOptions* options) {
+ mojom::blink::FetchAPIRequestPtr fetch_api_request;
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
const ScriptPromise promise = resolver->Promise();
if (request) {
- request->PopulateWebServiceWorkerRequest(web_request.emplace());
+ fetch_api_request = request->CreateFetchAPIRequest();
- if (request->method() != HTTPNames::GET && !options.ignoreMethod()) {
+ if (request->method() != http_names::kGET && !options->ignoreMethod()) {
resolver->Resolve(HeapVector<Member<Response>>());
return promise;
}
}
+ // Make sure to bind the Cache object to keep the mojo interface pointer
+ // alive during the operation. Otherwise GC might prevent the callback
+ // from ever being executed.
cache_ptr_->MatchAll(
- web_request, ToQueryParams(options),
+ std::move(fetch_api_request), ToQueryParams(options),
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options, Cache* _,
mojom::blink::MatchAllResultPtr result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
@@ -674,7 +679,7 @@ ScriptPromise Cache::MatchAllImpl(ScriptState* script_state,
TimeDelta elapsed = TimeTicks::Now() - start_time;
UMA_HISTOGRAM_LONG_TIMES("ServiceWorkerCache.Cache.MatchAll2",
elapsed);
- if (options.hasIgnoreSearch() && options.ignoreSearch()) {
+ if (options->hasIgnoreSearch() && options->ignoreSearch()) {
UMA_HISTOGRAM_LONG_TIMES(
"ServiceWorkerCache.Cache.MatchAll2.IgnoreSearchEnabled",
elapsed);
@@ -693,7 +698,8 @@ ScriptPromise Cache::MatchAllImpl(ScriptState* script_state,
resolver->Resolve(responses);
}
},
- WrapPersistent(resolver), TimeTicks::Now(), options));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(options),
+ WrapPersistent(this)));
return promise;
}
@@ -716,7 +722,7 @@ ScriptPromise Cache::AddAllImpl(ScriptState* script_state,
"Add/AddAll does not support schemes "
"other than \"http\" or \"https\""));
}
- if (requests[i]->method() != HTTPNames::GET) {
+ if (requests[i]->method() != http_names::kGET) {
return ScriptPromise::Reject(
script_state,
V8ThrowException::CreateTypeError(
@@ -725,8 +731,8 @@ ScriptPromise Cache::AddAllImpl(ScriptState* script_state,
}
request_infos[i].SetRequest(requests[i]);
- promises[i] = scoped_fetcher_->Fetch(script_state, request_infos[i],
- RequestInit(), exception_state);
+ promises[i] = scoped_fetcher_->Fetch(
+ script_state, request_infos[i], RequestInit::Create(), exception_state);
}
return ScriptPromise::All(script_state, promises)
@@ -736,10 +742,10 @@ ScriptPromise Cache::AddAllImpl(ScriptState* script_state,
ScriptPromise Cache::DeleteImpl(ScriptState* script_state,
const Request* request,
- const CacheQueryOptions& options) {
+ const CacheQueryOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
const ScriptPromise promise = resolver->Promise();
- if (request->method() != HTTPNames::GET && !options.ignoreMethod()) {
+ if (request->method() != http_names::kGET && !options->ignoreMethod()) {
resolver->Resolve(false);
return promise;
}
@@ -748,15 +754,18 @@ ScriptPromise Cache::DeleteImpl(ScriptState* script_state,
batch_operations.push_back(mojom::blink::BatchOperation::New());
auto& operation = batch_operations.back();
operation->operation_type = mojom::blink::OperationType::kDelete;
- request->PopulateWebServiceWorkerRequest(operation->request);
+ operation->request = request->CreateFetchAPIRequest();
operation->match_params = ToQueryParams(options);
+ // Make sure to bind the Cache object to keep the mojo interface pointer
+ // alive during the operation. Otherwise GC might prevent the callback
+ // from ever being executed.
cache_ptr_->Batch(
std::move(batch_operations),
RuntimeEnabledFeatures::CacheStorageAddAllRejectsDuplicatesEnabled(),
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options, Cache* _,
mojom::blink::CacheStorageVerboseErrorPtr error) {
ExecutionContext* context = resolver->GetExecutionContext();
if (!context || context->IsContextDestroyed())
@@ -782,7 +791,7 @@ ScriptPromise Cache::DeleteImpl(ScriptState* script_state,
TimeDelta elapsed = TimeTicks::Now() - start_time;
UMA_HISTOGRAM_LONG_TIMES("ServiceWorkerCache.Cache.Delete",
elapsed);
- if (options.hasIgnoreSearch() && options.ignoreSearch()) {
+ if (options->hasIgnoreSearch() && options->ignoreSearch()) {
UMA_HISTOGRAM_LONG_TIMES(
"ServiceWorkerCache.Cache.Delete.IgnoreSearchEnabled",
elapsed);
@@ -799,7 +808,8 @@ ScriptPromise Cache::DeleteImpl(ScriptState* script_state,
kJSMessageSource, kWarningMessageLevel, message));
}
},
- WrapPersistent(resolver), TimeTicks::Now(), options));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(options),
+ WrapPersistent(this)));
return promise;
}
@@ -820,7 +830,7 @@ ScriptPromise Cache::PutImpl(ScriptState* script_state,
"' is unsupported");
return promise;
}
- if (requests[i]->method() != HTTPNames::GET) {
+ if (requests[i]->method() != http_names::kGET) {
barrier_callback->OnError("Request method '" + requests[i]->method() +
"' is unsupported");
return promise;
@@ -884,7 +894,7 @@ ScriptPromise Cache::PutImpl(ScriptState* script_state,
mojom::blink::BatchOperationPtr batch_operation =
mojom::blink::BatchOperation::New();
batch_operation->operation_type = mojom::blink::OperationType::kPut;
- requests[i]->PopulateWebServiceWorkerRequest(batch_operation->request);
+ batch_operation->request = requests[i]->CreateFetchAPIRequest();
batch_operation->response = responses[i]->PopulateFetchAPIResponse();
barrier_callback->OnSuccess(i, std::move(batch_operation));
}
@@ -894,25 +904,28 @@ ScriptPromise Cache::PutImpl(ScriptState* script_state,
ScriptPromise Cache::KeysImpl(ScriptState* script_state,
const Request* request,
- const CacheQueryOptions& options) {
- base::Optional<WebServiceWorkerRequest> web_request;
+ const CacheQueryOptions* options) {
+ mojom::blink::FetchAPIRequestPtr fetch_api_request;
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
const ScriptPromise promise = resolver->Promise();
if (request) {
- request->PopulateWebServiceWorkerRequest(web_request.emplace());
+ fetch_api_request = request->CreateFetchAPIRequest();
- if (request->method() != HTTPNames::GET && !options.ignoreMethod()) {
+ if (request->method() != http_names::kGET && !options->ignoreMethod()) {
resolver->Resolve(HeapVector<Member<Response>>());
return promise;
}
}
+ // Make sure to bind the Cache object to keep the mojo interface pointer
+ // alive during the operation. Otherwise GC might prevent the callback
+ // from ever being executed.
cache_ptr_->Keys(
- web_request, ToQueryParams(options),
+ std::move(fetch_api_request), ToQueryParams(options),
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options, Cache* _,
mojom::blink::CacheKeysResultPtr result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
@@ -924,7 +937,7 @@ ScriptPromise Cache::KeysImpl(ScriptState* script_state,
TimeDelta elapsed = TimeTicks::Now() - start_time;
UMA_HISTOGRAM_LONG_TIMES("ServiceWorkerCache.Cache.Keys2",
elapsed);
- if (options.hasIgnoreSearch() && options.ignoreSearch()) {
+ if (options->hasIgnoreSearch() && options->ignoreSearch()) {
UMA_HISTOGRAM_TIMES(
"ServiceWorkerCache.Cache.Keys2.IgnoreSearchEnabled",
elapsed);
@@ -938,12 +951,13 @@ ScriptPromise Cache::KeysImpl(ScriptState* script_state,
requests.ReserveInitialCapacity(result->get_keys().size());
for (auto& request : result->get_keys()) {
requests.push_back(
- Request::Create(resolver->GetScriptState(), request));
+ Request::Create(resolver->GetScriptState(), *request));
}
resolver->Resolve(requests);
}
},
- WrapPersistent(resolver), TimeTicks::Now(), options));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(options),
+ WrapPersistent(this)));
return promise;
}
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/cache.h b/chromium/third_party/blink/renderer/modules/cache_storage/cache.h
index ed03b363274..935145ffef9 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/cache.h
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/cache.h
@@ -37,12 +37,12 @@ class MODULES_EXPORT Cache final : public ScriptWrappable {
// From Cache.idl:
ScriptPromise match(ScriptState*,
const RequestInfo&,
- const CacheQueryOptions&,
+ const CacheQueryOptions*,
ExceptionState&);
ScriptPromise matchAll(ScriptState*, ExceptionState&);
ScriptPromise matchAll(ScriptState*,
const RequestInfo&,
- const CacheQueryOptions&,
+ const CacheQueryOptions*,
ExceptionState&);
ScriptPromise add(ScriptState*, const RequestInfo&, ExceptionState&);
ScriptPromise addAll(ScriptState*,
@@ -50,7 +50,7 @@ class MODULES_EXPORT Cache final : public ScriptWrappable {
ExceptionState&);
ScriptPromise Delete(ScriptState*,
const RequestInfo&,
- const CacheQueryOptions&,
+ const CacheQueryOptions*,
ExceptionState&);
ScriptPromise put(ScriptState*,
const RequestInfo&,
@@ -59,10 +59,10 @@ class MODULES_EXPORT Cache final : public ScriptWrappable {
ScriptPromise keys(ScriptState*, ExceptionState&);
ScriptPromise keys(ScriptState*,
const RequestInfo&,
- const CacheQueryOptions&,
+ const CacheQueryOptions*,
ExceptionState&);
- static mojom::blink::QueryParamsPtr ToQueryParams(const CacheQueryOptions&);
+ static mojom::blink::QueryParamsPtr ToQueryParams(const CacheQueryOptions*);
void Trace(blink::Visitor*) override;
@@ -77,17 +77,17 @@ class MODULES_EXPORT Cache final : public ScriptWrappable {
ScriptPromise MatchImpl(ScriptState*,
const Request*,
- const CacheQueryOptions&);
+ const CacheQueryOptions*);
ScriptPromise MatchAllImpl(ScriptState*,
const Request*,
- const CacheQueryOptions&);
+ const CacheQueryOptions*);
ScriptPromise AddAllImpl(ScriptState*,
const String& method_name,
const HeapVector<Member<Request>>&,
ExceptionState&);
ScriptPromise DeleteImpl(ScriptState*,
const Request*,
- const CacheQueryOptions&);
+ const CacheQueryOptions*);
ScriptPromise PutImpl(ScriptState*,
const String& method_name,
const HeapVector<Member<Request>>&,
@@ -95,7 +95,7 @@ class MODULES_EXPORT Cache final : public ScriptWrappable {
ExceptionState&);
ScriptPromise KeysImpl(ScriptState*,
const Request*,
- const CacheQueryOptions&);
+ const CacheQueryOptions*);
Member<GlobalFetch::ScopedFetcher> scoped_fetcher_;
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.cc b/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.cc
index e8efc430dc8..6206905ea0b 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.cc
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.cc
@@ -32,12 +32,15 @@ ScriptPromise CacheStorage::open(ScriptState* script_state,
const String& cache_name) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
+ // Make sure to bind the CacheStorage object to keep the mojo interface
+ // pointer alive during the operation. Otherwise GC might prevent the
+ // callback from ever being executed.
cache_storage_ptr_->Open(
cache_name,
WTF::Bind(
[](ScriptPromiseResolver* resolver,
GlobalFetch::ScopedFetcher* fetcher, TimeTicks start_time,
- mojom::blink::OpenResultPtr result) {
+ CacheStorage* _, mojom::blink::OpenResultPtr result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
return;
@@ -60,7 +63,7 @@ ScriptPromise CacheStorage::open(ScriptState* script_state,
}
},
WrapPersistent(resolver), WrapPersistent(scoped_fetcher_.Get()),
- TimeTicks::Now()));
+ TimeTicks::Now(), WrapPersistent(this)));
return resolver->Promise();
}
@@ -69,11 +72,14 @@ ScriptPromise CacheStorage::has(ScriptState* script_state,
const String& cache_name) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
+ // Make sure to bind the CacheStorage object to keep the mojo interface
+ // pointer alive during the operation. Otherwise GC might prevent the
+ // callback from ever being executed.
cache_storage_ptr_->Has(
cache_name,
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- mojom::blink::CacheStorageError result) {
+ CacheStorage* _, mojom::blink::CacheStorageError result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
return;
@@ -91,7 +97,7 @@ ScriptPromise CacheStorage::has(ScriptState* script_state,
break;
}
},
- WrapPersistent(resolver), TimeTicks::Now()));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(this)));
return resolver->Promise();
}
@@ -100,11 +106,14 @@ ScriptPromise CacheStorage::Delete(ScriptState* script_state,
const String& cache_name) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
+ // Make sure to bind the CacheStorage object to keep the mojo interface
+ // pointer alive during the operation. Otherwise GC might prevent the
+ // callback from ever being executed.
cache_storage_ptr_->Delete(
cache_name,
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- mojom::blink::CacheStorageError result) {
+ CacheStorage* _, mojom::blink::CacheStorageError result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
return;
@@ -123,7 +132,7 @@ ScriptPromise CacheStorage::Delete(ScriptState* script_state,
break;
}
},
- WrapPersistent(resolver), TimeTicks::Now()));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(this)));
return resolver->Promise();
}
@@ -131,8 +140,11 @@ ScriptPromise CacheStorage::Delete(ScriptState* script_state,
ScriptPromise CacheStorage::keys(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
+ // Make sure to bind the CacheStorage object to keep the mojo interface
+ // pointer alive during the operation. Otherwise GC might prevent the
+ // callback from ever being executed.
cache_storage_ptr_->Keys(WTF::Bind(
- [](ScriptPromiseResolver* resolver, TimeTicks start_time,
+ [](ScriptPromiseResolver* resolver, TimeTicks start_time, CacheStorage* _,
const Vector<String>& keys) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
@@ -141,14 +153,14 @@ ScriptPromise CacheStorage::keys(ScriptState* script_state) {
TimeTicks::Now() - start_time);
resolver->Resolve(keys);
},
- WrapPersistent(resolver), TimeTicks::Now()));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(this)));
return resolver->Promise();
}
ScriptPromise CacheStorage::match(ScriptState* script_state,
const RequestInfo& request,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options,
ExceptionState& exception_state) {
DCHECK(!request.IsNull());
@@ -163,23 +175,23 @@ ScriptPromise CacheStorage::match(ScriptState* script_state,
ScriptPromise CacheStorage::MatchImpl(ScriptState* script_state,
const Request* request,
- const CacheQueryOptions& options) {
- WebServiceWorkerRequest web_request;
- request->PopulateWebServiceWorkerRequest(web_request);
-
+ const CacheQueryOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
const ScriptPromise promise = resolver->Promise();
- if (request->method() != HTTPNames::GET && !options.ignoreMethod()) {
+ if (request->method() != http_names::kGET && !options->ignoreMethod()) {
resolver->Resolve();
return promise;
}
+ // Make sure to bind the CacheStorage object to keep the mojo interface
+ // pointer alive during the operation. Otherwise GC might prevent the
+ // callback from ever being executed.
cache_storage_ptr_->Match(
- web_request, Cache::ToQueryParams(options),
+ request->CreateFetchAPIRequest(), Cache::ToQueryParams(options),
WTF::Bind(
[](ScriptPromiseResolver* resolver, TimeTicks start_time,
- const CacheQueryOptions& options,
+ const CacheQueryOptions* options, CacheStorage* _,
mojom::blink::MatchResultPtr result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed())
@@ -200,7 +212,7 @@ ScriptPromise CacheStorage::MatchImpl(ScriptState* script_state,
TimeDelta elapsed = TimeTicks::Now() - start_time;
UMA_HISTOGRAM_LONG_TIMES("ServiceWorkerCache.CacheStorage.Match2",
elapsed);
- if (options.hasIgnoreSearch() && options.ignoreSearch()) {
+ if (options->hasIgnoreSearch() && options->ignoreSearch()) {
UMA_HISTOGRAM_LONG_TIMES(
"ServiceWorkerCache.CacheStorage.Match2."
"IgnoreSearchEnabled",
@@ -216,7 +228,8 @@ ScriptPromise CacheStorage::MatchImpl(ScriptState* script_state,
*result->get_response()));
}
},
- WrapPersistent(resolver), TimeTicks::Now(), options));
+ WrapPersistent(resolver), TimeTicks::Now(), WrapPersistent(options),
+ WrapPersistent(this)));
return promise;
}
@@ -226,8 +239,7 @@ CacheStorage::CacheStorage(ExecutionContext* context,
: scoped_fetcher_(fetcher) {
// Service workers may already have a CacheStoragePtr provided as an
// optimization.
- if (context->IsServiceWorkerGlobalScope()) {
- auto* service_worker = ToServiceWorkerGlobalScope(context);
+ if (auto* service_worker = DynamicTo<ServiceWorkerGlobalScope>(context)) {
mojom::blink::CacheStoragePtrInfo info = service_worker->TakeCacheStorage();
if (info) {
cache_storage_ptr_ = RevocableInterfacePtr<mojom::blink::CacheStorage>(
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.h b/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.h
index f12e522ae38..86c96236673 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.h
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/cache_storage.h
@@ -33,7 +33,7 @@ class CacheStorage final : public ScriptWrappable {
ScriptPromise keys(ScriptState*);
ScriptPromise match(ScriptState*,
const RequestInfo&,
- const CacheQueryOptions&,
+ const CacheQueryOptions*,
ExceptionState&);
void Trace(blink::Visitor*) override;
@@ -42,7 +42,7 @@ class CacheStorage final : public ScriptWrappable {
CacheStorage(ExecutionContext*, GlobalFetch::ScopedFetcher*);
ScriptPromise MatchImpl(ScriptState*,
const Request*,
- const CacheQueryOptions&);
+ const CacheQueryOptions*);
Member<GlobalFetch::ScopedFetcher> scoped_fetcher_;
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/cache_test.cc b/chromium/third_party/blink/renderer/modules/cache_storage/cache_test.cc
index e3fe6e8fc93..349032c5205 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/cache_test.cc
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/cache_test.cc
@@ -54,11 +54,11 @@ class ScopedFetcherForTests final
USING_GARBAGE_COLLECTED_MIXIN(ScopedFetcherForTests);
public:
- static ScopedFetcherForTests* Create() { return new ScopedFetcherForTests; }
+ static ScopedFetcherForTests* Create() { return new ScopedFetcherForTests(); }
ScriptPromise Fetch(ScriptState* script_state,
const RequestInfo& request_info,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&) override {
++fetch_count_;
if (expected_url_) {
@@ -138,34 +138,34 @@ class ErrorCacheForTests : public mojom::blink::CacheStorageCache {
expected_batch_operations_ = expected_batch_operations;
}
- void Match(const WebServiceWorkerRequest& request,
+ void Match(mojom::blink::FetchAPIRequestPtr fetch_api_request,
mojom::blink::QueryParamsPtr query_params,
MatchCallback callback) override {
last_error_web_cache_method_called_ = "dispatchMatch";
- CheckUrlIfProvided(request.Url());
+ CheckUrlIfProvided(fetch_api_request->url);
CheckQueryParamsIfProvided(query_params);
mojom::blink::MatchResultPtr result = mojom::blink::MatchResult::New();
result->set_status(error_);
std::move(callback).Run(std::move(result));
}
- void MatchAll(const base::Optional<WebServiceWorkerRequest>& request,
+ void MatchAll(mojom::blink::FetchAPIRequestPtr fetch_api_request,
mojom::blink::QueryParamsPtr query_params,
MatchAllCallback callback) override {
last_error_web_cache_method_called_ = "dispatchMatchAll";
- if (request)
- CheckUrlIfProvided(request->Url());
+ if (fetch_api_request)
+ CheckUrlIfProvided(fetch_api_request->url);
CheckQueryParamsIfProvided(query_params);
mojom::blink::MatchAllResultPtr result =
mojom::blink::MatchAllResult::New();
result->set_status(error_);
std::move(callback).Run(std::move(result));
}
- void Keys(const base::Optional<WebServiceWorkerRequest>& request,
+ void Keys(mojom::blink::FetchAPIRequestPtr fetch_api_request,
mojom::blink::QueryParamsPtr query_params,
KeysCallback callback) override {
last_error_web_cache_method_called_ = "dispatchKeys";
- if (request && !request->Url().IsEmpty()) {
- CheckUrlIfProvided(request->Url());
+ if (fetch_api_request && !fetch_api_request->url.IsEmpty()) {
+ CheckUrlIfProvided(fetch_api_request->url);
CheckQueryParamsIfProvided(query_params);
}
mojom::blink::CacheKeysResultPtr result =
@@ -208,8 +208,8 @@ class ErrorCacheForTests : public mojom::blink::CacheStorageCache {
EXPECT_EQ(expected_batch_operations[i]->operation_type,
batch_operations[i]->operation_type);
const String expected_request_url =
- KURL(expected_batch_operations[i]->request.Url());
- EXPECT_EQ(expected_request_url, KURL(batch_operations[i]->request.Url()));
+ expected_batch_operations[i]->request->url;
+ EXPECT_EQ(expected_request_url, batch_operations[i]->request->url);
if (expected_batch_operations[i]->response) {
ASSERT_EQ(expected_batch_operations[i]->response->url_list.size(),
batch_operations[i]->response->url_list.size());
@@ -392,7 +392,7 @@ TEST_F(CacheStorageTest, Basics) {
const String url = "http://www.cachetest.org/";
- CacheQueryOptions options;
+ CacheQueryOptions* options = CacheQueryOptions::Create();
ScriptPromise match_promise = cache->match(
GetScriptState(), StringToRequestInfo(url), options, exception_state);
EXPECT_EQ(kNotImplementedString, GetRejectString(match_promise));
@@ -438,9 +438,9 @@ TEST_F(CacheStorageTest, BasicArguments) {
expected_query_params->cache_name = "this is a cache name";
test_cache()->SetExpectedQueryParams(&expected_query_params);
- CacheQueryOptions options;
- options.setIgnoreVary(1);
- options.setCacheName(expected_query_params->cache_name);
+ CacheQueryOptions* options = CacheQueryOptions::Create();
+ options->setIgnoreVary(1);
+ options->setCacheName(expected_query_params->cache_name);
Request* request = NewRequestFromUrl(url);
DCHECK(request);
@@ -508,8 +508,8 @@ TEST_F(CacheStorageTest, BatchOperationArguments) {
expected_query_params->cache_name = "this is another cache name";
test_cache()->SetExpectedQueryParams(&expected_query_params);
- CacheQueryOptions options;
- options.setCacheName(expected_query_params->cache_name);
+ CacheQueryOptions* options = CacheQueryOptions::Create();
+ options->setCacheName(expected_query_params->cache_name);
const String url = "http://batch.operations.test/";
Request* request = NewRequestFromUrl(url);
@@ -526,7 +526,7 @@ TEST_F(CacheStorageTest, BatchOperationArguments) {
expected_delete_operations.push_back(mojom::blink::BatchOperation::New());
auto& delete_operation = expected_delete_operations.back();
delete_operation->operation_type = mojom::blink::OperationType::kDelete;
- request->PopulateWebServiceWorkerRequest(delete_operation->request);
+ delete_operation->request = request->CreateFetchAPIRequest();
delete_operation->match_params = expected_query_params->Clone();
}
test_cache()->SetExpectedBatchOperations(&expected_delete_operations);
@@ -549,7 +549,7 @@ TEST_F(CacheStorageTest, BatchOperationArguments) {
expected_put_operations.push_back(mojom::blink::BatchOperation::New());
auto& put_operation = expected_put_operations.back();
put_operation->operation_type = mojom::blink::OperationType::kPut;
- request->PopulateWebServiceWorkerRequest(put_operation->request);
+ put_operation->request = request->CreateFetchAPIRequest();
put_operation->response = response->PopulateFetchAPIResponse();
}
test_cache()->SetExpectedBatchOperations(&expected_put_operations);
@@ -578,7 +578,7 @@ class MatchTestCache : public NotImplementedErrorCache {
: response_(std::move(response)) {}
// From WebServiceWorkerCache:
- void Match(const WebServiceWorkerRequest& request,
+ void Match(mojom::blink::FetchAPIRequestPtr fetch_api_request,
mojom::blink::QueryParamsPtr query_params,
MatchCallback callback) override {
mojom::blink::MatchResultPtr result = mojom::blink::MatchResult::New();
@@ -606,7 +606,7 @@ TEST_F(CacheStorageTest, MatchResponseTest) {
Cache* cache = CreateCache(
fetcher, std::make_unique<MatchTestCache>(std::move(fetch_api_response)));
- CacheQueryOptions options;
+ CacheQueryOptions* options = CacheQueryOptions::Create();
ScriptPromise result =
cache->match(GetScriptState(), StringToRequestInfo(request_url), options,
@@ -620,20 +620,20 @@ TEST_F(CacheStorageTest, MatchResponseTest) {
class KeysTestCache : public NotImplementedErrorCache {
public:
- KeysTestCache(Vector<WebServiceWorkerRequest>& requests)
- : requests_(requests) {}
+ KeysTestCache(Vector<mojom::blink::FetchAPIRequestPtr> requests)
+ : requests_(std::move(requests)) {}
- void Keys(const base::Optional<WebServiceWorkerRequest>& request,
+ void Keys(mojom::blink::FetchAPIRequestPtr fetch_api_request,
mojom::blink::QueryParamsPtr query_params,
KeysCallback callback) override {
mojom::blink::CacheKeysResultPtr result =
mojom::blink::CacheKeysResult::New();
- result->set_keys(requests_);
+ result->set_keys(std::move(requests_));
std::move(callback).Run(std::move(result));
}
private:
- Vector<WebServiceWorkerRequest>& requests_;
+ Vector<mojom::blink::FetchAPIRequestPtr> requests_;
};
TEST_F(CacheStorageTest, KeysResponseTest) {
@@ -647,14 +647,16 @@ TEST_F(CacheStorageTest, KeysResponseTest) {
expected_urls[0] = url1;
expected_urls[1] = url2;
- Vector<WebServiceWorkerRequest> web_requests(size_t(2));
- web_requests[0].SetURL(KURL(url1));
- web_requests[0].SetMethod("GET");
- web_requests[1].SetURL(KURL(url2));
- web_requests[1].SetMethod("GET");
+ Vector<mojom::blink::FetchAPIRequestPtr> fetch_api_requests(size_t(2));
+ fetch_api_requests[0] = mojom::blink::FetchAPIRequest::New();
+ fetch_api_requests[0]->url = KURL(url1);
+ fetch_api_requests[0]->method = String("GET");
+ fetch_api_requests[1] = mojom::blink::FetchAPIRequest::New();
+ fetch_api_requests[1]->url = KURL(url2);
+ fetch_api_requests[1]->method = String("GET");
- Cache* cache =
- CreateCache(fetcher, std::make_unique<KeysTestCache>(web_requests));
+ Cache* cache = CreateCache(
+ fetcher, std::make_unique<KeysTestCache>(std::move(fetch_api_requests)));
ScriptPromise result = cache->keys(GetScriptState(), exception_state);
ScriptValue script_value = GetResolveValue(result);
@@ -677,7 +679,7 @@ class MatchAllAndBatchTestCache : public NotImplementedErrorCache {
MatchAllAndBatchTestCache(Vector<mojom::blink::FetchAPIResponsePtr> responses)
: responses_(std::move(responses)) {}
- void MatchAll(const base::Optional<WebServiceWorkerRequest>& request,
+ void MatchAll(mojom::blink::FetchAPIRequestPtr fetch_api_request,
mojom::blink::QueryParamsPtr query_params,
MatchAllCallback callback) override {
mojom::blink::MatchAllResultPtr result =
@@ -723,7 +725,7 @@ TEST_F(CacheStorageTest, MatchAllAndBatchResponseTest) {
CreateCache(fetcher, std::make_unique<MatchAllAndBatchTestCache>(
std::move(fetch_api_responses)));
- CacheQueryOptions options;
+ CacheQueryOptions* options = CacheQueryOptions::Create();
ScriptPromise result =
cache->matchAll(GetScriptState(), StringToRequestInfo("http://some.url/"),
options, exception_state);
@@ -765,9 +767,10 @@ TEST_F(CacheStorageTest, Add) {
Request* request = NewRequestFromUrl(url);
Response* response = Response::Create(
GetScriptState(),
- new BodyStreamBuffer(GetScriptState(), new FormDataBytesConsumer(content),
+ new BodyStreamBuffer(GetScriptState(),
+ MakeGarbageCollected<FormDataBytesConsumer>(content),
nullptr),
- content_type, ResponseInit(), exception_state);
+ content_type, ResponseInit::Create(), exception_state);
fetcher->SetResponse(response);
Vector<mojom::blink::BatchOperationPtr> expected_put_operations(size_t(1));
@@ -776,7 +779,7 @@ TEST_F(CacheStorageTest, Add) {
mojom::blink::BatchOperation::New();
put_operation->operation_type = mojom::blink::OperationType::kPut;
- request->PopulateWebServiceWorkerRequest(put_operation->request);
+ put_operation->request = request->CreateFetchAPIRequest();
put_operation->response = response->PopulateFetchAPIResponse();
expected_put_operations[0] = std::move(put_operation);
}
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc b/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc
index dec003076ee..ce51f53cd90 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.cc
@@ -9,10 +9,9 @@
#include <utility>
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_response.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_string.h"
@@ -33,8 +32,6 @@
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
-#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
-#include "third_party/blink/renderer/platform/wtf/text/base64.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -43,6 +40,7 @@ using blink::protocol::Array;
using ProtocolCache = blink::protocol::CacheStorage::Cache;
using blink::protocol::CacheStorage::Cache;
using blink::protocol::CacheStorage::CachedResponse;
+using blink::protocol::CacheStorage::CachedResponseType;
using blink::protocol::CacheStorage::DataEntry;
using blink::protocol::CacheStorage::Header;
// Renaming Response since there is another blink::Response.
@@ -172,6 +170,26 @@ CString CacheStorageErrorString(mojom::blink::CacheStorageError error) {
return "";
}
+CachedResponseType ResponseTypeToString(
+ network::mojom::FetchResponseType type) {
+ switch (type) {
+ case network::mojom::FetchResponseType::kBasic:
+ return protocol::CacheStorage::CachedResponseTypeEnum::Basic;
+ case network::mojom::FetchResponseType::kCors:
+ return protocol::CacheStorage::CachedResponseTypeEnum::Cors;
+ case network::mojom::FetchResponseType::kDefault:
+ return protocol::CacheStorage::CachedResponseTypeEnum::Default;
+ case network::mojom::FetchResponseType::kError:
+ return protocol::CacheStorage::CachedResponseTypeEnum::Error;
+ case network::mojom::FetchResponseType::kOpaque:
+ return protocol::CacheStorage::CachedResponseTypeEnum::OpaqueResponse;
+ case network::mojom::FetchResponseType::kOpaqueRedirect:
+ return protocol::CacheStorage::CachedResponseTypeEnum::OpaqueRedirect;
+ }
+ NOTREACHED();
+ return "";
+}
+
struct DataRequestParams {
String cache_name;
int skip_count;
@@ -185,6 +203,7 @@ struct RequestResponse {
int response_status;
String response_status_text;
double response_time;
+ network::mojom::FetchResponseType response_type;
HTTPHeaderMap response_headers;
};
@@ -200,13 +219,13 @@ class ResponsesAccumulator : public RefCounted<ResponsesAccumulator> {
cache_ptr_(std::move(cache_ptr)),
callback_(std::move(callback)) {}
- void Dispatch(const Vector<WebServiceWorkerRequest>& requests) {
+ void Dispatch(Vector<mojom::blink::FetchAPIRequestPtr> requests) {
for (const auto& request : requests) {
cache_ptr_->Match(
- request, mojom::blink::QueryParams::New(),
+ request.Clone(), mojom::blink::QueryParams::New(),
WTF::Bind(
[](scoped_refptr<ResponsesAccumulator> accumulator,
- WebServiceWorkerRequest request,
+ mojom::blink::FetchAPIRequestPtr request,
mojom::blink::MatchResultPtr result) {
if (result->is_status()) {
accumulator->SendFailure(result->get_status());
@@ -215,23 +234,28 @@ class ResponsesAccumulator : public RefCounted<ResponsesAccumulator> {
result->get_response());
}
},
- scoped_refptr<ResponsesAccumulator>(this), request));
+ scoped_refptr<ResponsesAccumulator>(this), request.Clone()));
}
}
void AddRequestResponsePair(
- const WebServiceWorkerRequest& request,
+ const mojom::blink::FetchAPIRequestPtr& request,
const mojom::blink::FetchAPIResponsePtr& response) {
DCHECK_GT(num_responses_left_, 0);
RequestResponse& request_response =
responses_.at(responses_.size() - num_responses_left_);
- request_response.request_url = request.Url().GetString();
- request_response.request_method = request.Method();
- request_response.request_headers = request.Headers();
+ request_response.request_url = request->url.GetString();
+ request_response.request_method = request->method;
+ for (const auto& header : request->headers) {
+ request_response.request_headers.Set(AtomicString(header.key),
+ AtomicString(header.value));
+ }
+
request_response.response_status = response->status_code;
request_response.response_status_text = response->status_text;
request_response.response_time = response->response_time.ToDoubleT();
+ request_response.response_type = response->response_type;
for (const auto& header : response->headers) {
request_response.response_headers.Set(AtomicString(header.key),
AtomicString(header.value));
@@ -264,6 +288,8 @@ class ResponsesAccumulator : public RefCounted<ResponsesAccumulator> {
.setResponseStatus(request_response.response_status)
.setResponseStatusText(request_response.response_status_text)
.setResponseTime(request_response.response_time)
+ .setResponseType(
+ ResponseTypeToString(request_response.response_type))
.setResponseHeaders(
SerializeHeaders(request_response.response_headers))
.build();
@@ -313,8 +339,7 @@ class GetCacheKeysForRequestData {
void Dispatch(std::unique_ptr<GetCacheKeysForRequestData> self) {
cache_ptr_->Keys(
- base::Optional<WebServiceWorkerRequest>(),
- mojom::blink::QueryParams::New(),
+ nullptr /* request */, mojom::blink::QueryParams::New(),
WTF::Bind(
[](DataRequestParams params,
std::unique_ptr<GetCacheKeysForRequestData> self,
@@ -326,8 +351,7 @@ class GetCacheKeysForRequestData {
params.cache_name.Utf8().data(),
CacheStorageErrorString(result->get_status()).data())));
} else {
- auto& requests = result->get_keys();
- if (requests.IsEmpty()) {
+ if (result->get_keys().IsEmpty()) {
std::unique_ptr<Array<DataEntry>> array =
Array<DataEntry>::create();
self->callback_->sendSuccess(std::move(array), false);
@@ -335,9 +359,10 @@ class GetCacheKeysForRequestData {
}
scoped_refptr<ResponsesAccumulator> accumulator =
base::AdoptRef(new ResponsesAccumulator(
- requests.size(), params, std::move(self->cache_ptr_),
+ result->get_keys().size(), params,
+ std::move(self->cache_ptr_),
std::move(self->callback_)));
- accumulator->Dispatch(result->get_keys());
+ accumulator->Dispatch(std::move(result->get_keys()));
}
},
params_, std::move(self)));
@@ -365,14 +390,13 @@ class CachedResponseFileReaderLoaderClient final
void DidFinishLoading() override {
std::unique_ptr<CachedResponse> response =
CachedResponse::create()
- .setBody(
- Base64Encode(data_->Data(), SafeCast<unsigned>(data_->size())))
+ .setBody(protocol::Binary::fromSharedBuffer(data_))
.build();
callback_->sendSuccess(std::move(response));
dispose();
}
- void DidFail(FileError::ErrorCode error) override {
+ void DidFail(FileErrorCode error) override {
callback_->sendFailure(ProtocolResponse::Error(String::Format(
"Unable to read the cached response, error code: %d", error)));
dispose();
@@ -551,8 +575,9 @@ void InspectorCacheStorageAgent::deleteEntry(
batch_operations.push_back(mojom::blink::BatchOperation::New());
auto& operation = batch_operations.back();
operation->operation_type = mojom::blink::OperationType::kDelete;
- operation->request.SetURL(KURL(request));
- operation->request.SetMethod("GET");
+ operation->request = mojom::blink::FetchAPIRequest::New();
+ operation->request->url = KURL(request);
+ operation->request->method = String("GET");
mojom::blink::CacheStorageCacheAssociatedPtr cache_ptr;
cache_ptr.Bind(std::move(result->get_cache()));
@@ -592,11 +617,11 @@ void InspectorCacheStorageAgent::requestCachedResponse(
callback->sendFailure(response);
return;
}
- WebServiceWorkerRequest request;
- request.SetURL(KURL(request_url));
- request.SetMethod("GET");
+ auto request = mojom::blink::FetchAPIRequest::New();
+ request->url = KURL(request_url);
+ request->method = String("GET");
cache_storage->Match(
- request, mojom::blink::QueryParams::New(),
+ std::move(request), mojom::blink::QueryParams::New(),
WTF::Bind(
[](std::unique_ptr<RequestCachedResponseCallback> callback,
mojom::blink::MatchResultPtr result) {
@@ -608,8 +633,9 @@ void InspectorCacheStorageAgent::requestCachedResponse(
std::unique_ptr<protocol::DictionaryValue> headers =
protocol::DictionaryValue::create();
if (!result->get_response()->blob) {
- callback->sendSuccess(
- CachedResponse::create().setBody("").build());
+ callback->sendSuccess(CachedResponse::create()
+ .setBody(protocol::Binary())
+ .build());
return;
}
CachedResponseFileReaderLoaderClient::Load(
diff --git a/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.h b/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.h
index 85e6f87c4a4..e0bba936a7f 100644
--- a/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.h
+++ b/chromium/third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.h
@@ -24,9 +24,10 @@ class MODULES_EXPORT InspectorCacheStorageAgent final
using CachesMap = HashMap<String, mojom::blink::CacheStoragePtr>;
static InspectorCacheStorageAgent* Create(InspectedFrames* frames) {
- return new InspectorCacheStorageAgent(frames);
+ return MakeGarbageCollected<InspectorCacheStorageAgent>(frames);
}
+ explicit InspectorCacheStorageAgent(InspectedFrames*);
~InspectorCacheStorageAgent() override;
void Trace(blink::Visitor*) override;
@@ -47,8 +48,6 @@ class MODULES_EXPORT InspectorCacheStorageAgent final
std::unique_ptr<RequestCachedResponseCallback>) override;
private:
- explicit InspectorCacheStorageAgent(InspectedFrames*);
-
Member<InspectedFrames> frames_;
CachesMap caches_;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/OWNERS b/chromium/third_party/blink/renderer/modules/canvas/OWNERS
index 0a9e139f0c3..0513b2b4930 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/canvas/OWNERS
@@ -1,5 +1,4 @@
fserb@chromium.org
-junov@chromium.org
# canvas, imagebitmap
senorblanco@chromium.org
# lowLatency
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc
index 5bd0cdfee88..30075bc6b02 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc
@@ -4,35 +4,23 @@
#include "third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h"
-#include "base/numerics/checked_math.h"
+#include <algorithm>
+#include <cmath>
+#include <memory>
+
+#include "base/metrics/histogram_functions.h"
#include "third_party/blink/renderer/core/css/cssom/css_url_image_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
-#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/core/html/canvas/text_metrics.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
-#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
-#include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h"
-#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h"
-#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
-#include "third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h"
-#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/graphics/image.h"
-#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
-#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/graphics/stroke_data.h"
-#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -582,7 +570,7 @@ void BaseRenderingContext2D::setTransform(double m11,
transform(fm11, fm12, fm21, fm22, fdx, fdy);
}
-void BaseRenderingContext2D::setTransform(DOMMatrix2DInit& transform,
+void BaseRenderingContext2D::setTransform(DOMMatrix2DInit* transform,
ExceptionState& exception_state) {
DOMMatrixReadOnly* m =
DOMMatrixReadOnly::fromMatrix2D(transform, exception_state);
@@ -650,8 +638,8 @@ void BaseRenderingContext2D::DrawPathInternal(
SkPath sk_path = path.GetSkPath();
FloatRect bounds = path.BoundingRect();
- if (isnan(bounds.X()) || isnan(bounds.Y()) || isnan(bounds.Width()) ||
- isnan(bounds.Height()))
+ if (std::isnan(bounds.X()) || std::isnan(bounds.Y()) ||
+ std::isnan(bounds.Width()) || std::isnan(bounds.Height()))
return;
sk_path.setFillType(fill_type);
@@ -1180,76 +1168,7 @@ void BaseRenderingContext2D::drawImage(ScriptState* script_state,
if (!DrawingCanvas())
return;
- TimeTicks start_time;
- base::Optional<CustomCountHistogram> timer;
- if (!IsPaint2D()) {
- start_time = WTF::CurrentTimeTicks();
- if (CanCreateCanvas2dResourceProvider() && IsAccelerated()) {
- if (image_source->IsVideoElement()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_video_gpu,
- ("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_video_gpu);
- } else if (image_source->IsCanvasElement()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_canvas_gpu,
- ("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_canvas_gpu);
- } else if (image_source->IsSVGSource()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_svggpu,
- ("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_svggpu);
- } else if (image_source->IsImageBitmap()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_image_bitmap_gpu,
- ("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_image_bitmap_gpu);
- } else if (image_source->IsOffscreenCanvas()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu,
- ("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_offscreencanvas_gpu);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_others_gpu,
- ("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_others_gpu);
- }
- } else {
- if (image_source->IsVideoElement()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_video_cpu,
- ("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_video_cpu);
- } else if (image_source->IsCanvasElement()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_canvas_cpu,
- ("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_canvas_cpu);
- } else if (image_source->IsSVGSource()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_svgcpu,
- ("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_svgcpu);
- } else if (image_source->IsImageBitmap()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_image_bitmap_cpu,
- ("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_image_bitmap_cpu);
- } else if (image_source->IsOffscreenCanvas()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu,
- ("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_offscreencanvas_cpu);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_others_cpu,
- ("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_others_cpu);
- }
- }
- }
+ base::TimeTicks start_time = base::TimeTicks::Now();
scoped_refptr<Image> image;
FloatSize default_object_size(Width(), Height());
@@ -1312,21 +1231,21 @@ void BaseRenderingContext2D::drawImage(ScriptState* script_state,
// Heuristic for disabling acceleration based on anticipated texture upload
// overhead.
- // See comments in CanvasHeuristicParameters.h for explanation.
+ // See comments in canvas_heuristic_parameters.h for explanation.
if (CanCreateCanvas2dResourceProvider() && IsAccelerated() &&
!image_source->IsAccelerated()) {
float src_area = src_rect.Width() * src_rect.Height();
if (src_area >
- CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) {
+ canvas_heuristic_parameters::kDrawImageTextureUploadHardSizeLimit) {
this->DisableAcceleration();
- } else if (src_area > CanvasHeuristicParameters::
+ } else if (src_area > canvas_heuristic_parameters::
kDrawImageTextureUploadSoftSizeLimit) {
SkRect bounds = dst_rect;
SkMatrix ctm = DrawingCanvas()->getTotalMatrix();
ctm.mapRect(&bounds);
float dst_area = dst_rect.Width() * dst_rect.Height();
if (src_area >
- dst_area * CanvasHeuristicParameters::
+ dst_area * canvas_heuristic_parameters::
kDrawImageTextureUploadSoftSizeLimitScaleThreshold) {
this->DisableAcceleration();
}
@@ -1354,10 +1273,56 @@ void BaseRenderingContext2D::drawImage(ScriptState* script_state,
: CanvasRenderingContext2DState::kNonOpaqueImage);
ValidateStateStack();
-
+ bool source_is_canvas = false;
if (!IsPaint2D()) {
- DCHECK(!start_time.is_null());
- timer->CountMicroseconds(WTF::CurrentTimeTicks() - start_time);
+ std::string image_source_name;
+ if (image_source->IsCanvasElement()) {
+ image_source_name = "Canvas";
+ source_is_canvas = true;
+ } else if (image_source->IsCSSImageValue()) {
+ image_source_name = "CssImage";
+ } else if (image_source->IsImageElement()) {
+ image_source_name = "ImageElement";
+ } else if (image_source->IsImageBitmap()) {
+ image_source_name = "ImageBitmap";
+ } else if (image_source->IsOffscreenCanvas()) {
+ image_source_name = "OffscreenCanvas";
+ source_is_canvas = true;
+ } else if (image_source->IsSVGSource()) {
+ image_source_name = "SVG";
+ } else if (image_source->IsVideoElement()) {
+ image_source_name = "Video";
+ } else { // Unknown source.
+ image_source_name = "Unknown";
+ }
+
+ std::string duration_histogram_name =
+ "Blink.Canvas.DrawImage.Duration." + image_source_name;
+ std::string size_histogram_name =
+ "Blink.Canvas.DrawImage.SqrtNumberOfPixels." + image_source_name;
+
+ if (CanCreateCanvas2dResourceProvider() && IsAccelerated()) {
+ if (source_is_canvas)
+ size_histogram_name.append(".GPU");
+ duration_histogram_name.append(".GPU");
+ } else {
+ if (source_is_canvas)
+ size_histogram_name.append(".CPU");
+ duration_histogram_name.append(".CPU");
+ }
+
+ base::TimeDelta elapsed = TimeTicks::Now() - start_time;
+ base::UmaHistogramMicrosecondsTimes(duration_histogram_name, elapsed);
+
+ float sqrt_pixels_float =
+ std::sqrt(dst_rect.Width()) * std::sqrt(dst_rect.Height());
+ // If sqrt_pixels_float overflows as int CheckedNumeric will store it
+ // as invalid, then ValueOrDefault will return the maximum int.
+ base::CheckedNumeric<int> sqrt_pixels = sqrt_pixels_float;
+ base::UmaHistogramCustomCounts(
+ size_histogram_name,
+ sqrt_pixels.ValueOrDefault(std::numeric_limits<int>::max()), 1, 5000,
+ 50);
}
}
@@ -1534,12 +1499,12 @@ bool BaseRenderingContext2D::ComputeDirtyRect(
return true;
}
-ImageDataColorSettings
+ImageDataColorSettings*
BaseRenderingContext2D::GetColorSettingsAsImageDataColorSettings() const {
- ImageDataColorSettings color_settings;
- color_settings.setColorSpace(ColorSpaceAsString());
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
+ color_settings->setColorSpace(ColorSpaceAsString());
if (PixelFormat() == kF16CanvasPixelFormat)
- color_settings.setStorageFormat(kFloat32ArrayStorageFormatName);
+ color_settings->setStorageFormat(kFloat32ArrayStorageFormatName);
return color_settings;
}
@@ -1547,9 +1512,9 @@ ImageData* BaseRenderingContext2D::createImageData(
ImageData* image_data,
ExceptionState& exception_state) const {
ImageData* result = nullptr;
- ImageDataColorSettings color_settings =
+ ImageDataColorSettings* color_settings =
GetColorSettingsAsImageDataColorSettings();
- result = ImageData::Create(image_data->Size(), &color_settings);
+ result = ImageData::Create(image_data->Size(), color_settings);
if (!result)
exception_state.ThrowRangeError("Out of memory at ImageData creation");
return result;
@@ -1568,9 +1533,9 @@ ImageData* BaseRenderingContext2D::createImageData(
IntSize size(abs(sw), abs(sh));
ImageData* result = nullptr;
- ImageDataColorSettings color_settings =
+ ImageDataColorSettings* color_settings =
GetColorSettingsAsImageDataColorSettings();
- result = ImageData::Create(size, &color_settings);
+ result = ImageData::Create(size, color_settings);
if (!result)
exception_state.ThrowRangeError("Out of memory at ImageData creation");
@@ -1580,7 +1545,7 @@ ImageData* BaseRenderingContext2D::createImageData(
ImageData* BaseRenderingContext2D::createImageData(
unsigned width,
unsigned height,
- ImageDataColorSettings& color_settings,
+ ImageDataColorSettings* color_settings,
ExceptionState& exception_state) const {
return ImageData::CreateImageData(width, height, color_settings,
exception_state);
@@ -1591,8 +1556,8 @@ ImageData* BaseRenderingContext2D::createImageData(
unsigned width,
unsigned height,
ExceptionState& exception_state) const {
- ImageDataColorSettings color_settings;
- return ImageData::CreateImageData(data_array, width, height, color_settings,
+ return ImageData::CreateImageData(data_array, width, height,
+ ImageDataColorSettings::Create(),
exception_state);
}
@@ -1600,7 +1565,7 @@ ImageData* BaseRenderingContext2D::createImageData(
ImageDataArray& data_array,
unsigned width,
unsigned height,
- ImageDataColorSettings& color_settings,
+ ImageDataColorSettings* color_settings,
ExceptionState& exception_state) const {
return ImageData::CreateImageData(data_array, width, height, color_settings,
exception_state);
@@ -1617,6 +1582,8 @@ ImageData* BaseRenderingContext2D::getImageData(
return nullptr;
}
+ base::TimeTicks start_time = base::TimeTicks::Now();
+
usage_counters_.num_get_image_data_calls++;
usage_counters_.area_get_image_data_calls += sw * sh;
if (!OriginClean()) {
@@ -1653,28 +1620,14 @@ ImageData* BaseRenderingContext2D::getImageData(
exception_state.ThrowRangeError("Out of memory at ImageData creation");
return nullptr;
}
- base::Optional<ScopedUsHistogramTimer> timer;
- if (!IsPaint2D()) {
- if (CanCreateCanvas2dResourceProvider() && IsAccelerated()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_gpu,
- ("Blink.Canvas.GetImageData.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_gpu);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_cpu,
- ("Blink.Canvas.GetImageData.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_cpu);
- }
- }
IntRect image_data_rect(sx, sy, sw, sh);
bool hasResourceProvider = CanCreateCanvas2dResourceProvider();
- ImageDataColorSettings color_settings =
+ ImageDataColorSettings* color_settings =
GetColorSettingsAsImageDataColorSettings();
if (!hasResourceProvider || isContextLost()) {
ImageData* result =
- ImageData::Create(image_data_rect.Size(), &color_settings);
+ ImageData::Create(image_data_rect.Size(), color_settings);
if (!result)
exception_state.ThrowRangeError("Out of memory at ImageData creation");
return result;
@@ -1702,20 +1655,49 @@ ImageData* BaseRenderingContext2D::getImageData(
// Convert pixels to proper storage format if needed
if (PixelFormat() != kRGBA8CanvasPixelFormat) {
ImageDataStorageFormat storage_format =
- ImageData::GetImageDataStorageFormat(color_settings.storageFormat());
+ ImageData::GetImageDataStorageFormat(color_settings->storageFormat());
DOMArrayBufferView* array_buffer_view =
ImageData::ConvertPixelsFromCanvasPixelFormatToImageDataStorageFormat(
contents, PixelFormat(), storage_format);
return ImageData::Create(image_data_rect.Size(),
NotShared<DOMArrayBufferView>(array_buffer_view),
- &color_settings);
+ color_settings);
}
DOMArrayBuffer* array_buffer = DOMArrayBuffer::Create(contents);
- return ImageData::Create(
+
+ ImageData* imageData = ImageData::Create(
image_data_rect.Size(),
NotShared<DOMUint8ClampedArray>(DOMUint8ClampedArray::Create(
array_buffer, 0, array_buffer->ByteLength())),
- &color_settings);
+ color_settings);
+
+ if (!IsPaint2D()) {
+ int scaled_time = getScaledElapsedTime(
+ image_data_rect.Width(), image_data_rect.Height(), start_time);
+ if (CanCreateCanvas2dResourceProvider() && IsAccelerated()) {
+ base::UmaHistogramCounts1000(
+ "Blink.Canvas.GetImageDataScaledDuration.GPU", scaled_time);
+ } else {
+ base::UmaHistogramCounts1000(
+ "Blink.Canvas.GetImageDataScaledDuration.CPU", scaled_time);
+ }
+ }
+
+ return imageData;
+}
+
+int BaseRenderingContext2D::getScaledElapsedTime(float width,
+ float height,
+ base::TimeTicks start_time) {
+ base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time;
+ float sqrt_pixels = std::sqrt(width) * std::sqrt(height);
+ float scaled_time_float = elapsed_time.InMicrosecondsF() * 10.0f /
+ (sqrt_pixels == 0 ? 1.0f : sqrt_pixels);
+
+ // If scaled_time_float overflows as integer, CheckedNumeric will store it
+ // as invalid, then ValueOrDefault will return the maximum int.
+ base::CheckedNumeric<int> checked_scaled_time = scaled_time_float;
+ return checked_scaled_time.ValueOrDefault(std::numeric_limits<int>::max());
}
void BaseRenderingContext2D::putImageData(ImageData* data,
@@ -1737,6 +1719,7 @@ void BaseRenderingContext2D::putImageData(ImageData* data,
if (!base::CheckMul(dirty_width, dirty_height).IsValid<int>()) {
return;
}
+ base::TimeTicks start_time = base::TimeTicks::Now();
usage_counters_.num_put_image_data_calls++;
usage_counters_.area_put_image_data_calls += dirty_width * dirty_height;
@@ -1768,21 +1751,6 @@ void BaseRenderingContext2D::putImageData(ImageData* data,
if (dest_rect.IsEmpty())
return;
- base::Optional<ScopedUsHistogramTimer> timer;
- if (!IsPaint2D()) {
- if (hasResourceProvider && IsAccelerated()) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_gpu,
- ("Blink.Canvas.PutImageData.GPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_gpu);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram, scoped_us_counter_cpu,
- ("Blink.Canvas.PutImageData.CPU", 0, 10000000, 50));
- timer.emplace(scoped_us_counter_cpu);
- }
- }
-
IntRect source_rect(dest_rect);
source_rect.Move(-dest_offset);
@@ -1813,6 +1781,19 @@ void BaseRenderingContext2D::putImageData(ImageData* data,
PutByteArray(data->data()->Data(), IntSize(data->width(), data->height()),
source_rect, IntPoint(dest_offset));
}
+
+ if (!IsPaint2D()) {
+ int scaled_time =
+ getScaledElapsedTime(dest_rect.Width(), dest_rect.Height(), start_time);
+ if (CanCreateCanvas2dResourceProvider() && IsAccelerated()) {
+ base::UmaHistogramCounts1000(
+ "Blink.Canvas.PutImageDataScaledDuration.GPU", scaled_time);
+ } else {
+ base::UmaHistogramCounts1000(
+ "Blink.Canvas.PutImageDataScaledDuration.CPU", scaled_time);
+ }
+ }
+
DidDraw(dest_rect);
}
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h
index 695f9bc16ad..e1aaadb27a8 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h
@@ -8,19 +8,12 @@
#include "third_party/blink/renderer/bindings/modules/v8/canvas_image_source.h"
#include "third_party/blink/renderer/bindings/modules/v8/string_or_canvas_gradient_or_canvas_pattern.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix.h"
-#include "third_party/blink/renderer/core/geometry/dom_matrix_2d_init.h"
#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.h"
-#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h"
-#include "third_party/blink/renderer/platform/graphics/color_behavior.h"
-#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
-#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
-#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
-#include "third_party/skia/include/effects/SkComposeImageFilter.h"
namespace blink {
class CanvasImageSource;
@@ -103,7 +96,7 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
double m22,
double dx,
double dy);
- void setTransform(DOMMatrix2DInit&, ExceptionState&);
+ void setTransform(DOMMatrix2DInit*, ExceptionState&);
DOMMatrix* getTransform();
void resetTransform();
@@ -189,7 +182,7 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
ImageData* createImageData(int width, int height, ExceptionState&) const;
ImageData* createImageData(unsigned,
unsigned,
- ImageDataColorSettings&,
+ ImageDataColorSettings*,
ExceptionState&) const;
ImageData* createImageData(ImageDataArray&,
unsigned,
@@ -198,7 +191,7 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
ImageData* createImageData(ImageDataArray&,
unsigned,
unsigned,
- ImageDataColorSettings&,
+ ImageDataColorSettings*,
ExceptionState&) const;
ImageData* getImageData(int sx, int sy, int sw, int sh, ExceptionState&);
@@ -330,7 +323,7 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
SkIRect*);
template <typename DrawFunc, typename ContainsFunc>
- bool Draw(const DrawFunc&,
+ void Draw(const DrawFunc&,
const ContainsFunc&,
const SkRect& bounds,
CanvasRenderingContext2DState::PaintType,
@@ -370,7 +363,7 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
mutable UsageCounters usage_counters_;
- virtual void NeedsFinalizeFrame(){};
+ virtual void NeedsFinalizeFrame() {}
float GetFontBaseline(const SimpleFontData&) const;
@@ -424,7 +417,7 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
// such as tainting from a filter applied to the canvas.
void SetOriginTaintedByContent();
- ImageDataColorSettings GetColorSettingsAsImageDataColorSettings() const;
+ ImageDataColorSettings* GetColorSettingsAsImageDataColorSettings() const;
void PutByteArray(const unsigned char* source,
const IntSize& source_size,
@@ -435,30 +428,26 @@ class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin,
return false;
}
+ int getScaledElapsedTime(float width,
+ float height,
+ base::TimeTicks start_time);
+
bool origin_tainted_by_content_;
};
template <typename DrawFunc, typename ContainsFunc>
-bool BaseRenderingContext2D::Draw(
+void BaseRenderingContext2D::Draw(
const DrawFunc& draw_func,
const ContainsFunc& draw_covers_clip_bounds,
const SkRect& bounds,
CanvasRenderingContext2DState::PaintType paint_type,
CanvasRenderingContext2DState::ImageType image_type) {
if (!GetState().IsTransformInvertible())
- return false;
+ return;
SkIRect clip_bounds;
if (!DrawingCanvas() || !DrawingCanvas()->getDeviceClipBounds(&clip_bounds))
- return false;
-
- // If gradient size is zero, then paint nothing.
- CanvasStyle* style = GetState().Style(paint_type);
- if (style) {
- CanvasGradient* gradient = style->GetCanvasGradient();
- if (gradient && gradient->IsZeroSize())
- return false;
- }
+ return;
if (IsFullCanvasCompositeMode(GetState().GlobalComposite()) ||
StateHasFilter()) {
@@ -482,7 +471,6 @@ bool BaseRenderingContext2D::Draw(
DidDraw(dirty_rect);
}
}
- return true;
}
template <typename DrawFunc>
@@ -502,6 +490,7 @@ void BaseRenderingContext2D::CompositedDraw(
PaintFlags shadow_flags =
*GetState().GetFlags(paint_type, kDrawShadowOnly, image_type);
int save_count = c->getSaveCount();
+ c->save();
if (filter) {
PaintFlags foreground_flags =
*GetState().GetFlags(paint_type, kDrawForegroundOnly, image_type);
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.cc
index 208ab1d939e..a7d066cbb25 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.cc
@@ -33,14 +33,26 @@
namespace blink {
CanvasGradient::CanvasGradient(const FloatPoint& p0, const FloatPoint& p1)
- : gradient_(Gradient::CreateLinear(p0, p1)), is_zero_size_(p0 == p1) {}
+ : gradient_(
+ Gradient::CreateLinear(p0,
+ p1,
+ kSpreadMethodPad,
+ Gradient::ColorInterpolation::kUnpremultiplied,
+ Gradient::DegenerateHandling::kDisallow)) {}
CanvasGradient::CanvasGradient(const FloatPoint& p0,
float r0,
const FloatPoint& p1,
float r1)
- : gradient_(Gradient::CreateRadial(p0, r0, p1, r1)),
- is_zero_size_(p0 == p1 && r0 == r1) {}
+ : gradient_(
+ Gradient::CreateRadial(p0,
+ r0,
+ p1,
+ r1,
+ 1,
+ kSpreadMethodPad,
+ Gradient::ColorInterpolation::kUnpremultiplied,
+ Gradient::DegenerateHandling::kDisallow)) {}
void CanvasGradient::addColorStop(float value,
const String& color_string,
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h
index 4defd92846e..593501dcd37 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h
@@ -42,30 +42,27 @@ class MODULES_EXPORT CanvasGradient final : public ScriptWrappable {
public:
static CanvasGradient* Create(const FloatPoint& p0, const FloatPoint& p1) {
- return new CanvasGradient(p0, p1);
+ return MakeGarbageCollected<CanvasGradient>(p0, p1);
}
static CanvasGradient* Create(const FloatPoint& p0,
float r0,
const FloatPoint& p1,
float r1) {
- return new CanvasGradient(p0, r0, p1, r1);
+ return MakeGarbageCollected<CanvasGradient>(p0, r0, p1, r1);
}
- Gradient* GetGradient() const { return gradient_.get(); }
-
- void addColorStop(float value, const String& color, ExceptionState&);
-
- bool IsZeroSize() const { return is_zero_size_; }
-
- private:
CanvasGradient(const FloatPoint& p0, const FloatPoint& p1);
CanvasGradient(const FloatPoint& p0,
float r0,
const FloatPoint& p1,
float r1);
+ Gradient* GetGradient() const { return gradient_.get(); }
+
+ void addColorStop(float value, const String& color, ExceptionState&);
+
+ private:
scoped_refptr<Gradient> gradient_;
- const bool is_zero_size_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.cc
index 8ada2295747..4a9fb007e87 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.cc
@@ -59,7 +59,7 @@ CanvasPattern::CanvasPattern(scoped_refptr<Image> image,
: pattern_(Pattern::CreateImagePattern(std::move(image), repeat)),
origin_clean_(origin_clean) {}
-void CanvasPattern::setTransform(DOMMatrix2DInit& transform,
+void CanvasPattern::setTransform(DOMMatrix2DInit* transform,
ExceptionState& exception_state) {
DOMMatrixReadOnly* m =
DOMMatrixReadOnly::fromMatrix2D(transform, exception_state);
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h
index 88906031216..97b0dc06c05 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h
@@ -27,9 +27,9 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_CANVAS_CANVAS2D_CANVAS_PATTERN_H_
#include "third_party/blink/renderer/core/geometry/dom_matrix_2d_init.h"
-#include "third_party/blink/renderer/core/svg/svg_matrix_tear_off.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/graphics/pattern.h"
+#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -47,19 +47,20 @@ class CanvasPattern final : public ScriptWrappable {
static CanvasPattern* Create(scoped_refptr<Image> image,
Pattern::RepeatMode repeat,
bool origin_clean) {
- return new CanvasPattern(std::move(image), repeat, origin_clean);
+ return MakeGarbageCollected<CanvasPattern>(std::move(image), repeat,
+ origin_clean);
}
+ CanvasPattern(scoped_refptr<Image>, Pattern::RepeatMode, bool origin_clean);
+
Pattern* GetPattern() const { return pattern_.get(); }
const AffineTransform& GetTransform() const { return pattern_transform_; }
bool OriginClean() const { return origin_clean_; }
- void setTransform(DOMMatrix2DInit&, ExceptionState&);
+ void setTransform(DOMMatrix2DInit*, ExceptionState&);
private:
- CanvasPattern(scoped_refptr<Image>, Pattern::RepeatMode, bool origin_clean);
-
scoped_refptr<Pattern> pattern_;
AffineTransform pattern_transform_;
bool origin_clean_;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc
index 3674c02711f..9d14c1309e7 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.cc
@@ -39,10 +39,10 @@
#include "third_party/blink/renderer/bindings/modules/v8/rendering_context.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/css/css_font_selector.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/frame/settings.h"
@@ -228,7 +228,7 @@ void CanvasRenderingContext2D::Trace(blink::Visitor* visitor) {
void CanvasRenderingContext2D::DispatchContextLostEvent(TimerBase*) {
if (canvas() && ContextLostRestoredEventsEnabled()) {
- Event* event = Event::CreateCancelable(EventTypeNames::contextlost);
+ Event* event = Event::CreateCancelable(event_type_names::kContextlost);
canvas()->DispatchEvent(*event);
if (event->defaultPrevented()) {
context_restorable_ = false;
@@ -273,7 +273,7 @@ void CanvasRenderingContext2D::DispatchContextRestoredEvent(TimerBase*) {
Reset();
context_lost_mode_ = kNotLostContext;
if (ContextLostRestoredEventsEnabled()) {
- Event* event(Event::Create(EventTypeNames::contextrestored));
+ Event* event(Event::Create(event_type_names::kContextrestored));
canvas()->DispatchEvent(*event);
}
}
@@ -557,8 +557,9 @@ void CanvasRenderingContext2D::setFont(const String& new_font) {
ModifiableState().SetUnparsedFont(new_font_safe_copy);
}
-void CanvasRenderingContext2D::DidProcessTask() {
- CanvasRenderingContext::DidProcessTask();
+void CanvasRenderingContext2D::DidProcessTask(
+ const base::PendingTask& pending_task) {
+ CanvasRenderingContext::DidProcessTask(pending_task);
// This should be the only place where canvas() needs to be checked for
// nullness because the circular refence with HTMLCanvasElement means the
// canvas and the context keep each other alive. As long as the pair is
@@ -926,11 +927,14 @@ cc::Layer* CanvasRenderingContext2D::CcLayer() const {
return IsPaintable() ? canvas()->GetCanvas2DLayerBridge()->Layer() : nullptr;
}
-void CanvasRenderingContext2D::getContextAttributes(
- CanvasRenderingContext2DSettings& settings) const {
- settings.setAlpha(CreationAttributes().alpha);
- settings.setColorSpace(ColorSpaceAsString());
- settings.setPixelFormat(PixelFormatAsString());
+CanvasRenderingContext2DSettings*
+CanvasRenderingContext2D::getContextAttributes() const {
+ CanvasRenderingContext2DSettings* settings =
+ CanvasRenderingContext2DSettings::Create();
+ settings->setAlpha(CreationAttributes().alpha);
+ settings->setColorSpace(ColorSpaceAsString());
+ settings->setPixelFormat(PixelFormatAsString());
+ return settings;
}
void CanvasRenderingContext2D::drawFocusIfNeeded(Element* element) {
@@ -1018,16 +1022,16 @@ void CanvasRenderingContext2D::UpdateElementAccessibility(const Path& path,
ax_object_cache->SetCanvasObjectBounds(canvas(), element, element_rect);
}
-void CanvasRenderingContext2D::addHitRegion(const HitRegionOptions& options,
+void CanvasRenderingContext2D::addHitRegion(const HitRegionOptions* options,
ExceptionState& exception_state) {
- if (options.id().IsEmpty() && !options.control()) {
+ if (options->id().IsEmpty() && !options->control()) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
"Both id and control are null.");
return;
}
- if (options.control() &&
- !canvas()->IsSupportedInteractiveCanvasFallback(*options.control())) {
+ if (options->control() &&
+ !canvas()->IsSupportedInteractiveCanvasFallback(*options->control())) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
"The control is neither null nor a "
"supported interactive canvas fallback "
@@ -1035,7 +1039,7 @@ void CanvasRenderingContext2D::addHitRegion(const HitRegionOptions& options,
return;
}
- Path hit_region_path = options.path() ? options.path()->GetPath() : path_;
+ Path hit_region_path = options->path() ? options->path()->GetPath() : path_;
cc::PaintCanvas* c = DrawingCanvas();
@@ -1060,8 +1064,8 @@ void CanvasRenderingContext2D::addHitRegion(const HitRegionOptions& options,
hit_region_manager_ = HitRegionManager::Create();
// Remove previous region (with id or control)
- hit_region_manager_->RemoveHitRegionById(options.id());
- hit_region_manager_->RemoveHitRegionByControl(options.control());
+ hit_region_manager_->RemoveHitRegionById(options->id());
+ hit_region_manager_->RemoveHitRegionByControl(options->control());
HitRegion* hit_region = HitRegion::Create(hit_region_path, options);
Element* element = hit_region->Control();
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h
index 5a34779343e..14777dae85d 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h
@@ -81,14 +81,16 @@ class MODULES_EXPORT CanvasRenderingContext2D final
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attrs) override {
DCHECK(!host->IsOffscreenCanvas());
- return new CanvasRenderingContext2D(static_cast<HTMLCanvasElement*>(host),
- attrs);
+ return MakeGarbageCollected<CanvasRenderingContext2D>(
+ static_cast<HTMLCanvasElement*>(host), attrs);
}
CanvasRenderingContext::ContextType GetContextType() const override {
return CanvasRenderingContext::kContext2d;
}
};
+ CanvasRenderingContext2D(HTMLCanvasElement*,
+ const CanvasContextCreationAttributesCore&);
~CanvasRenderingContext2D() override;
HTMLCanvasElement* canvas() const {
@@ -124,12 +126,12 @@ class MODULES_EXPORT CanvasRenderingContext2D final
void strokeText(const String& text, double x, double y, double max_width);
TextMetrics* measureText(const String& text);
- void getContextAttributes(CanvasRenderingContext2DSettings&) const;
+ CanvasRenderingContext2DSettings* getContextAttributes() const;
void drawFocusIfNeeded(Element*);
void drawFocusIfNeeded(Path2D*, Element*);
- void addHitRegion(const HitRegionOptions&, ExceptionState&);
+ void addHitRegion(const HitRegionOptions*, ExceptionState&);
void removeHitRegion(const String& id);
void clearHitRegions();
HitRegion* HitRegionAtPoint(const FloatPoint&);
@@ -141,7 +143,7 @@ class MODULES_EXPORT CanvasRenderingContext2D final
void RestoreCanvasMatrixClipStack(cc::PaintCanvas*) const override;
// TaskObserver implementation
- void DidProcessTask() final;
+ void DidProcessTask(const base::PendingTask&) final;
void StyleDidChange(const ComputedStyle* old_style,
const ComputedStyle& new_style) override;
@@ -213,8 +215,6 @@ class MODULES_EXPORT CanvasRenderingContext2D final
private:
friend class CanvasRenderingContext2DAutoRestoreSkCanvas;
- CanvasRenderingContext2D(HTMLCanvasElement*,
- const CanvasContextCreationAttributesCore&);
void DispatchContextLostEvent(TimerBase*);
void DispatchContextRestoredEvent(TimerBase*);
void TryRestoreContextEvent(TimerBase*);
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_api_test.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_api_test.cc
index 23d92874005..2986a4d30c5 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_api_test.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_api_test.cc
@@ -63,7 +63,7 @@ void CanvasRenderingContext2DAPITest::SetUp() {
PageTestBase::SetUp();
GetDocument().documentElement()->SetInnerHTMLFromString(
"<body><canvas id='c'></canvas></body>");
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
canvas_element_ = ToHTMLCanvasElement(GetDocument().getElementById("c"));
}
@@ -333,8 +333,8 @@ TEST_F(CanvasRenderingContext2DAPITest, AccessibilityRectTestForAddHitRegion) {
static_cast<CanvasRenderingContext2D*>(canvas->RenderingContext());
NonThrowableExceptionState exception_state;
- HitRegionOptions options;
- options.setControl(button_element);
+ HitRegionOptions* options = HitRegionOptions::Create();
+ options->setControl(button_element);
context->beginPath();
context->rect(10, 10, 40, 40);
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc
index c71b69a3b18..fd6dd2a495d 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc
@@ -308,7 +308,7 @@ sk_sp<PaintFilter> CanvasRenderingContext2DState::GetFilterForOffscreenCanvas(
if (last_effect) {
// TODO(chrishtr): Taint the origin if needed. crbug.com/792506.
resolved_filter_ =
- PaintFilterBuilder::Build(last_effect, kInterpolationSpaceSRGB);
+ paint_filter_builder::Build(last_effect, kInterpolationSpaceSRGB);
}
return resolved_filter_;
@@ -359,10 +359,11 @@ sk_sp<PaintFilter> CanvasRenderingContext2DState::GetFilter(
1.0f, // Deliberately ignore zoom on the canvas element.
&fill_flags_for_filter, &stroke_flags_for_filter);
- if (FilterEffect* last_effect = filter_effect_builder.BuildFilterEffect(
- filter_style->Filter(), !context->OriginClean())) {
+ FilterEffect* last_effect = filter_effect_builder.BuildFilterEffect(
+ filter_style->Filter(), !context->OriginClean());
+ if (last_effect) {
resolved_filter_ =
- PaintFilterBuilder::Build(last_effect, kInterpolationSpaceSRGB);
+ paint_filter_builder::Build(last_effect, kInterpolationSpaceSRGB);
if (resolved_filter_) {
context->UpdateFilterReferences(filter_style->Filter());
if (last_effect->OriginTainted())
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h
index 292a085b77b..0a69b639042 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h
@@ -31,15 +31,18 @@ class CanvasRenderingContext2DState final
public:
static CanvasRenderingContext2DState* Create() {
- return new CanvasRenderingContext2DState;
+ return MakeGarbageCollected<CanvasRenderingContext2DState>();
}
+ enum ClipListCopyMode { kCopyClipList, kDontCopyClipList };
+
+ CanvasRenderingContext2DState();
+ CanvasRenderingContext2DState(const CanvasRenderingContext2DState&,
+ ClipListCopyMode);
~CanvasRenderingContext2DState() override;
void Trace(blink::Visitor*) override;
- enum ClipListCopyMode { kCopyClipList, kDontCopyClipList };
-
enum PaintType {
kFillPaintType,
kStrokePaintType,
@@ -193,10 +196,6 @@ class CanvasRenderingContext2DState final
const PaintFlags* GetFlags(PaintType, ShadowMode, ImageType = kNoImage) const;
private:
- CanvasRenderingContext2DState();
- CanvasRenderingContext2DState(const CanvasRenderingContext2DState&,
- ClipListCopyMode);
-
void UpdateLineDash() const;
void UpdateStrokeStyle() const;
void UpdateFillStyle() const;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc
index a1cb3e79b7c..a96eb474894 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_test.cc
@@ -147,7 +147,9 @@ class CanvasRenderingContext2DTest : public PageTestBase {
class WrapGradients final : public GarbageCollectedFinalized<WrapGradients> {
public:
- static WrapGradients* Create() { return new WrapGradients; }
+ static WrapGradients* Create() {
+ return MakeGarbageCollected<WrapGradients>();
+ }
void Trace(blink::Visitor* visitor) {
visitor->Trace(opaque_gradient_);
@@ -544,12 +546,12 @@ TEST_F(CanvasRenderingContext2DTest, detectOverdrawWithCompositeOperations) {
}
TEST_F(CanvasRenderingContext2DTest, ImageResourceLifetime) {
- auto* canvas =
- ToHTMLCanvasElement(GetDocument().CreateRawElement(HTMLNames::canvasTag));
+ auto* canvas = ToHTMLCanvasElement(
+ GetDocument().CreateRawElement(html_names::kCanvasTag));
canvas->SetSize(IntSize(40, 40));
ImageBitmap* image_bitmap_derived = nullptr;
{
- const ImageBitmapOptions default_options;
+ const ImageBitmapOptions* default_options = ImageBitmapOptions::Create();
base::Optional<IntRect> crop_rect =
IntRect(0, 0, canvas->width(), canvas->height());
ImageBitmap* image_bitmap_from_canvas =
@@ -644,7 +646,8 @@ TEST_F(CanvasRenderingContext2DTest, CanvasDisposedBeforeContext) {
// This is the only method that is callable after DetachHost
// Test passes by not crashing.
- Context2d()->DidProcessTask();
+ base::PendingTask dummy_pending_task(FROM_HERE, base::Closure());
+ Context2d()->DidProcessTask(dummy_pending_task);
// Test passes by not crashing during teardown
}
@@ -666,6 +669,8 @@ TEST_F(CanvasRenderingContext2DTest, ContextDisposedBeforeCanvas) {
TEST_F(CanvasRenderingContext2DTest, MAYBE_GetImageDataDisablesAcceleration) {
ScopedCanvas2dFixedRenderingModeForTest canvas_2d_fixed_rendering_mode(false);
+ // This Page is not actually being shown by a compositor, but we act like it
+ // will in order to test behaviour.
GetPage().GetSettings().SetAcceleratedCompositingEnabled(true);
CreateContext(kNonOpaque);
IntSize size(300, 300);
@@ -680,7 +685,7 @@ TEST_F(CanvasRenderingContext2DTest, MAYBE_GetImageDataDisablesAcceleration) {
DummyExceptionStateForTesting exception_state;
for (int i = 0;
- i < CanvasHeuristicParameters::kGPUReadbackMinSuccessiveFrames - 1;
+ i < canvas_heuristic_parameters::kGPUReadbackMinSuccessiveFrames - 1;
i++) {
Context2d()->getImageData(0, 0, 1, 1, exception_state);
CanvasElement().FinalizeFrame();
@@ -695,7 +700,7 @@ TEST_F(CanvasRenderingContext2DTest, MAYBE_GetImageDataDisablesAcceleration) {
CanvasElement().FinalizeFrame();
EXPECT_FALSE(exception_state.HadException());
- if (CanvasHeuristicParameters::kGPUReadbackForcesNoAcceleration) {
+ if (canvas_heuristic_parameters::kGPUReadbackForcesNoAcceleration) {
EXPECT_FALSE(CanvasElement().GetCanvas2DLayerBridge()->IsAccelerated());
EXPECT_EQ(0u, GetGlobalAcceleratedContextCount());
EXPECT_EQ(0, GetGlobalGPUMemoryUsage());
@@ -926,8 +931,8 @@ TEST_F(CanvasRenderingContext2DTest, ImageBitmapColorSpaceConversion) {
conversion_iterator <= kColorSpaceConversion_Last;
conversion_iterator++) {
// Color convert using ImageBitmap
- ImageBitmapOptions options;
- options.setColorSpaceConversion(
+ ImageBitmapOptions* options = ImageBitmapOptions::Create();
+ options->setColorSpaceConversion(
ColorCorrectionTestUtils::ColorSpaceConversionToString(
static_cast<ColorSpaceConversion>(conversion_iterator)));
ImageBitmap* image_bitmap = ImageBitmap::Create(canvas, crop_rect, options);
@@ -988,9 +993,10 @@ enum class CanvasColorSpaceSettings : uint8_t {
void TestPutImageDataOnCanvasWithColorSpaceSettings(
HTMLCanvasElement& canvas_element,
CanvasColorSpaceSettings canvas_colorspace_setting) {
- unsigned num_image_data_color_spaces = 3;
+ unsigned num_image_data_color_spaces = 4;
CanvasColorSpace image_data_color_spaces[] = {
- kSRGBCanvasColorSpace, kRec2020CanvasColorSpace, kP3CanvasColorSpace,
+ kSRGBCanvasColorSpace, kLinearRGBCanvasColorSpace,
+ kRec2020CanvasColorSpace, kP3CanvasColorSpace,
};
unsigned num_image_data_storage_formats = 3;
@@ -1000,22 +1006,25 @@ void TestPutImageDataOnCanvasWithColorSpaceSettings(
};
CanvasColorSpace canvas_color_spaces[] = {
- kSRGBCanvasColorSpace, kSRGBCanvasColorSpace, kRec2020CanvasColorSpace,
+ kSRGBCanvasColorSpace, kSRGBCanvasColorSpace,
+ kLinearRGBCanvasColorSpace, kRec2020CanvasColorSpace,
kP3CanvasColorSpace,
};
String canvas_color_space_names[] = {
kSRGBCanvasColorSpaceName, kSRGBCanvasColorSpaceName,
- kRec2020CanvasColorSpaceName, kP3CanvasColorSpaceName};
+ kLinearRGBCanvasColorSpaceName, kRec2020CanvasColorSpaceName,
+ kP3CanvasColorSpaceName};
CanvasPixelFormat canvas_pixel_formats[] = {
kRGBA8CanvasPixelFormat, kF16CanvasPixelFormat, kF16CanvasPixelFormat,
- kF16CanvasPixelFormat,
+ kF16CanvasPixelFormat, kF16CanvasPixelFormat,
};
String canvas_pixel_format_names[] = {
kRGBA8CanvasPixelFormatName, kF16CanvasPixelFormatName,
- kF16CanvasPixelFormatName, kF16CanvasPixelFormatName};
+ kF16CanvasPixelFormatName, kF16CanvasPixelFormatName,
+ kF16CanvasPixelFormatName};
// Source pixels in RGBA32
uint8_t u8_pixels[] = {255, 0, 0, 255, // Red
@@ -1046,7 +1055,7 @@ void TestPutImageDataOnCanvasWithColorSpaceSettings(
EXPECT_EQ(data_length, data_f32->length());
ImageData* image_data = nullptr;
- ImageDataColorSettings color_settings;
+ ImageDataColorSettings* color_settings = ImageDataColorSettings::Create();
int num_pixels = data_length / 4;
// At most four bytes are needed for Float32 output per color component.
@@ -1056,29 +1065,29 @@ void TestPutImageDataOnCanvasWithColorSpaceSettings(
// Loop through different possible combinations of image data color space and
// storage formats and create the respective test image data objects.
for (unsigned i = 0; i < num_image_data_color_spaces; i++) {
- color_settings.setColorSpace(
+ color_settings->setColorSpace(
ImageData::CanvasColorSpaceName(image_data_color_spaces[i]));
for (unsigned j = 0; j < num_image_data_storage_formats; j++) {
switch (image_data_storage_formats[j]) {
case kUint8ClampedArrayStorageFormat:
data_array = static_cast<DOMArrayBufferView*>(data_u8);
- color_settings.setStorageFormat(kUint8ClampedArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint8ClampedArrayStorageFormatName);
break;
case kUint16ArrayStorageFormat:
data_array = static_cast<DOMArrayBufferView*>(data_u16);
- color_settings.setStorageFormat(kUint16ArrayStorageFormatName);
+ color_settings->setStorageFormat(kUint16ArrayStorageFormatName);
break;
case kFloat32ArrayStorageFormat:
data_array = static_cast<DOMArrayBufferView*>(data_f32);
- color_settings.setStorageFormat(kFloat32ArrayStorageFormatName);
+ color_settings->setStorageFormat(kFloat32ArrayStorageFormatName);
break;
default:
NOTREACHED();
}
image_data =
- ImageData::CreateForTest(IntSize(2, 2), data_array, &color_settings);
+ ImageData::CreateForTest(IntSize(2, 2), data_array, color_settings);
unsigned k = (unsigned)(canvas_colorspace_setting);
// Convert the original data used to create ImageData to the
@@ -1163,6 +1172,8 @@ class CanvasRenderingContext2DTestWithTestingPlatform
// In these cases, the element should request a compositing update.
TEST_F(CanvasRenderingContext2DTestWithTestingPlatform,
ElementRequestsCompositingUpdateOnHibernateAndWakeUp) {
+ // This Page is not actually being shown by a compositor, but we act like it
+ // will in order to test behaviour.
GetPage().GetSettings().SetAcceleratedCompositingEnabled(true);
CreateContext(kNonOpaque);
IntSize size(300, 300);
@@ -1182,7 +1193,7 @@ TEST_F(CanvasRenderingContext2DTestWithTestingPlatform,
EXPECT_TRUE(CanvasElement().GetLayoutBoxModelObject());
PaintLayer* layer = CanvasElement().GetLayoutBoxModelObject()->Layer();
EXPECT_TRUE(layer);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Hide element to trigger hibernation (if enabled).
GetDocument().GetPage()->SetVisibilityState(
@@ -1194,7 +1205,7 @@ TEST_F(CanvasRenderingContext2DTestWithTestingPlatform,
EXPECT_EQ(!!CANVAS2D_HIBERNATION_ENABLED,
!CanvasElement().ResourceProvider());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(layer->NeedsCompositingInputsUpdate());
// Wake up again, which should request a compositing update synchronously.
@@ -1221,7 +1232,7 @@ TEST_F(CanvasRenderingContext2DTestWithTestingPlatform,
EXPECT_TRUE(CanvasElement().GetLayoutBoxModelObject());
PaintLayer* layer = CanvasElement().GetLayoutBoxModelObject()->Layer();
EXPECT_TRUE(layer);
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
// Hide element to trigger hibernation (if enabled).
GetDocument().GetPage()->SetVisibilityState(
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.cc
index 41e05dc1ba2..8ef083779c9 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.cc
@@ -29,9 +29,9 @@
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.h"
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h"
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.cc b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.cc
index 1ab9abdf56b..fc1ba5beebd 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.cc
@@ -8,11 +8,11 @@
namespace blink {
-HitRegion::HitRegion(const Path& path, const HitRegionOptions& options)
- : id_(options.id().IsEmpty() ? String() : options.id()),
- control_(options.control()),
+HitRegion::HitRegion(const Path& path, const HitRegionOptions* options)
+ : id_(options->id().IsEmpty() ? String() : options->id()),
+ control_(options->control()),
path_(path) {
- if (options.fillRule() != "evenodd")
+ if (options->fillRule() != "evenodd")
fill_rule_ = RULE_NONZERO;
else
fill_rule_ = RULE_EVENODD;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h
index 74fe458c91c..5ee1df4cc72 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h
@@ -16,10 +16,11 @@ namespace blink {
class HitRegion final : public GarbageCollectedFinalized<HitRegion> {
public:
- static HitRegion* Create(const Path& path, const HitRegionOptions& options) {
- return new HitRegion(path, options);
+ static HitRegion* Create(const Path& path, const HitRegionOptions* options) {
+ return MakeGarbageCollected<HitRegion>(path, options);
}
+ HitRegion(const Path&, const HitRegionOptions*);
virtual ~HitRegion() = default;
void RemovePixels(const Path&);
@@ -33,8 +34,6 @@ class HitRegion final : public GarbageCollectedFinalized<HitRegion> {
void Trace(blink::Visitor*);
private:
- HitRegion(const Path&, const HitRegionOptions&);
-
String id_;
Member<Element> control_;
Path path_;
@@ -45,7 +44,11 @@ class HitRegionManager final : public GarbageCollected<HitRegionManager> {
WTF_MAKE_NONCOPYABLE(HitRegionManager);
public:
- static HitRegionManager* Create() { return new HitRegionManager; }
+ static HitRegionManager* Create() {
+ return MakeGarbageCollected<HitRegionManager>();
+ }
+
+ HitRegionManager() = default;
void AddHitRegion(HitRegion*);
@@ -64,8 +67,6 @@ class HitRegionManager final : public GarbageCollected<HitRegionManager> {
void Trace(blink::Visitor*);
private:
- HitRegionManager() = default;
-
typedef HeapListHashSet<Member<HitRegion>> HitRegionList;
typedef HitRegionList::const_reverse_iterator HitRegionIterator;
typedef HeapHashMap<String, Member<HitRegion>> HitRegionIdMap;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h
index a0cd0e0d391..84eb2b04d07 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h
@@ -31,7 +31,6 @@
#include "third_party/blink/renderer/bindings/modules/v8/path_2d_or_string.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix_2d_init.h"
-#include "third_party/blink/renderer/core/svg/svg_matrix_tear_off.h"
#include "third_party/blink/renderer/core/svg/svg_path_utilities.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
@@ -40,6 +39,8 @@
namespace blink {
+class ExceptionState;
+
class MODULES_EXPORT Path2D final : public ScriptWrappable, public CanvasPath {
DEFINE_WRAPPERTYPEINFO();
WTF_MAKE_NONCOPYABLE(Path2D);
@@ -48,42 +49,36 @@ class MODULES_EXPORT Path2D final : public ScriptWrappable, public CanvasPath {
static Path2D* Create(Path2DOrString pathorstring) {
DCHECK(!pathorstring.IsNull());
if (pathorstring.IsPath2D())
- return new Path2D(pathorstring.GetAsPath2D());
+ return MakeGarbageCollected<Path2D>(pathorstring.GetAsPath2D());
if (pathorstring.IsString())
- return new Path2D(pathorstring.GetAsString());
+ return MakeGarbageCollected<Path2D>(pathorstring.GetAsString());
NOTREACHED();
return nullptr;
}
- static Path2D* Create() { return new Path2D; }
- static Path2D* Create(const Path& path) { return new Path2D(path); }
+ static Path2D* Create() { return MakeGarbageCollected<Path2D>(); }
+ static Path2D* Create(const Path& path) {
+ return MakeGarbageCollected<Path2D>(path);
+ }
const Path& GetPath() const { return path_; }
- void addPath(Path2D* path) {
- DOMMatrix2DInit transform;
- addPath(path, transform);
+ void addPath(Path2D* path,
+ DOMMatrix2DInit* transform,
+ ExceptionState& exception_state) {
+ DOMMatrixReadOnly* matrix =
+ DOMMatrixReadOnly::fromMatrix2D(transform, exception_state);
+ if (!matrix)
+ return;
+ path_.AddPath(path->GetPath(), matrix->GetAffineTransform());
}
- void addPath(Path2D* path, DOMMatrix2DInit& transform) {
- Path src = path->GetPath();
- DOMMatrixReadOnly* m = nullptr;
- m = DOMMatrixReadOnly::fromMatrix2D(transform);
- path_.AddPath(
- src, m ? m->GetAffineTransform() : AffineTransform(1, 0, 0, 1, 0, 0));
- }
-
- ~Path2D() override = default;
-
- private:
Path2D() : CanvasPath() {}
-
Path2D(const Path& path) : CanvasPath(path) {}
-
Path2D(Path2D* path) : CanvasPath(path->GetPath()) {}
-
Path2D(const String& path_data) : CanvasPath() {
BuildPathFromString(path_data, path_);
}
+ ~Path2D() override = default;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.idl b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.idl
index 44642f2ca57..f2b4429f236 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.idl
+++ b/chromium/third_party/blink/renderer/modules/canvas/canvas2d/path_2d.idl
@@ -32,8 +32,7 @@
Constructor(optional (Path2D or DOMString) path),
Exposed(Worker OffscreenCanvas, Window StableBlinkFeatures, PaintWorklet StableBlinkFeatures)
] interface Path2D {
-
- void addPath(Path2D path, optional DOMMatrix2DInit transform);
+ [RaisesException] void addPath(Path2D path, optional DOMMatrix2DInit transform);
};
Path2D implements CanvasPath;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc
index 295058409b4..fa11d4bf074 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc
@@ -10,20 +10,20 @@
namespace blink {
CanvasContextCreationAttributesCore ToCanvasContextCreationAttributes(
- const CanvasContextCreationAttributesModule& attrs) {
+ const CanvasContextCreationAttributesModule* attrs) {
CanvasContextCreationAttributesCore result;
- result.alpha = attrs.alpha();
- result.antialias = attrs.antialias();
- result.color_space = attrs.colorSpace();
- result.depth = attrs.depth();
+ result.alpha = attrs->alpha();
+ result.antialias = attrs->antialias();
+ result.color_space = attrs->colorSpace();
+ result.depth = attrs->depth();
result.fail_if_major_performance_caveat =
- attrs.failIfMajorPerformanceCaveat();
- result.low_latency = attrs.lowLatency();
- result.pixel_format = attrs.pixelFormat();
- result.premultiplied_alpha = attrs.premultipliedAlpha();
- result.preserve_drawing_buffer = attrs.preserveDrawingBuffer();
- result.stencil = attrs.stencil();
- result.compatible_xr_device = attrs.compatibleXRDevice();
+ attrs->failIfMajorPerformanceCaveat();
+ result.low_latency = attrs->lowLatency();
+ result.pixel_format = attrs->pixelFormat();
+ result.premultiplied_alpha = attrs->premultipliedAlpha();
+ result.preserve_drawing_buffer = attrs->preserveDrawingBuffer();
+ result.stencil = attrs->stencil();
+ result.compatible_xr_device = attrs->compatibleXRDevice();
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h
index f5b34ccd4cf..6170778e2fc 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h
@@ -11,7 +11,7 @@ class CanvasContextCreationAttributesCore;
class CanvasContextCreationAttributesModule;
CanvasContextCreationAttributesCore ToCanvasContextCreationAttributes(
- const CanvasContextCreationAttributesModule&);
+ const CanvasContextCreationAttributesModule*);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.cc b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.cc
index cded2b9122e..69fb8891f52 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.cc
@@ -9,13 +9,14 @@
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
#include "third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h"
#include "third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.h"
+#include "third_party/blink/renderer/platform/histogram.h"
namespace blink {
void HTMLCanvasElementModule::getContext(
HTMLCanvasElement& canvas,
const String& type,
- const CanvasContextCreationAttributesModule& attributes,
+ const CanvasContextCreationAttributesModule* attributes,
ExceptionState& exception_state,
RenderingContext& result) {
if (canvas.SurfaceLayerBridge() && !canvas.LowLatencyEnabled()) {
@@ -37,16 +38,20 @@ void HTMLCanvasElementModule::getContext(
OffscreenCanvas* HTMLCanvasElementModule::transferControlToOffscreen(
HTMLCanvasElement& canvas,
ExceptionState& exception_state) {
+ OffscreenCanvas* offscreen_canvas = nullptr;
if (canvas.SurfaceLayerBridge()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Cannot transfer control from a canvas for more than one time.");
- return nullptr;
+ } else {
+ canvas.CreateLayer();
+ offscreen_canvas =
+ TransferControlToOffscreenInternal(canvas, exception_state);
}
- canvas.CreateLayer();
-
- return TransferControlToOffscreenInternal(canvas, exception_state);
+ UMA_HISTOGRAM_BOOLEAN("Blink.OffscreenCanvas.TransferControlToOffscreen",
+ bool(offscreen_canvas));
+ return offscreen_canvas;
}
OffscreenCanvas* HTMLCanvasElementModule::TransferControlToOffscreenInternal(
@@ -61,9 +66,9 @@ OffscreenCanvas* HTMLCanvasElementModule::TransferControlToOffscreenInternal(
OffscreenCanvas* offscreen_canvas =
OffscreenCanvas::Create(canvas.width(), canvas.height());
- int canvas_id = DOMNodeIds::IdForNode(&canvas);
+ DOMNodeId canvas_id = DOMNodeIds::IdForNode(&canvas);
offscreen_canvas->SetPlaceholderCanvasId(canvas_id);
- canvas.RegisterPlaceholder(canvas_id);
+ canvas.RegisterPlaceholder(static_cast<int>(canvas_id));
SurfaceLayerBridge* bridge = canvas.SurfaceLayerBridge();
if (bridge) {
diff --git a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.h b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.h
index b96423a8ffa..2752cff6ec0 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/htmlcanvas/html_canvas_element_module.h
@@ -23,7 +23,7 @@ class MODULES_EXPORT HTMLCanvasElementModule {
public:
static void getContext(HTMLCanvasElement&,
const String&,
- const CanvasContextCreationAttributesModule&,
+ const CanvasContextCreationAttributesModule*,
ExceptionState&,
RenderingContext&);
static OffscreenCanvas* transferControlToOffscreen(HTMLCanvasElement&,
diff --git a/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc b/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc
index f65cafdf570..f4ce8d80151 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc
@@ -38,7 +38,7 @@ void ImageBitmapRenderingContext::transferFromImageBitmap(
CanvasRenderingContext* ImageBitmapRenderingContext::Factory::Create(
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attrs) {
- return new ImageBitmapRenderingContext(host, attrs);
+ return MakeGarbageCollected<ImageBitmapRenderingContext>(host, attrs);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h b/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h
index 18cd0bf347f..177b3221b1d 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h
@@ -34,6 +34,9 @@ class MODULES_EXPORT ImageBitmapRenderingContext final
}
};
+ ImageBitmapRenderingContext(CanvasRenderingContextHost*,
+ const CanvasContextCreationAttributesCore&);
+
// Script API
void transferFromImageBitmap(ImageBitmap*, ExceptionState&);
@@ -45,10 +48,6 @@ class MODULES_EXPORT ImageBitmapRenderingContext final
void SetCanvasGetContextResult(RenderingContext&) final;
~ImageBitmapRenderingContext() override;
-
- private:
- ImageBitmapRenderingContext(CanvasRenderingContextHost*,
- const CanvasContextCreationAttributesCore&);
};
DEFINE_TYPE_CASTS(ImageBitmapRenderingContext,
diff --git a/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc b/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc
index 7a3daced159..19586d8f23f 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc
@@ -18,8 +18,8 @@ ImageBitmapRenderingContextBase::ImageBitmapRenderingContextBase(
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attrs)
: CanvasRenderingContext(host, attrs),
- image_layer_bridge_(
- new ImageLayerBridge(attrs.alpha ? kNonOpaque : kOpaque)) {}
+ image_layer_bridge_(MakeGarbageCollected<ImageLayerBridge>(
+ attrs.alpha ? kNonOpaque : kOpaque)) {}
ImageBitmapRenderingContextBase::~ImageBitmapRenderingContextBase() = default;
diff --git a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.cc b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.cc
index 4db8f9b06bd..b9646e38983 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.cc
@@ -16,7 +16,7 @@ void OffscreenCanvasModule::getContext(
ExecutionContext* execution_context,
OffscreenCanvas& offscreen_canvas,
const String& id,
- const CanvasContextCreationAttributesModule& attributes,
+ const CanvasContextCreationAttributesModule* attributes,
ExceptionState& exception_state,
OffscreenRenderingContext& result) {
if (offscreen_canvas.IsNeutered()) {
diff --git a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.h b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.h
index 9f26f6ed460..c574a5805b0 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.h
@@ -23,7 +23,7 @@ class MODULES_EXPORT OffscreenCanvasModule {
static void getContext(ExecutionContext*,
OffscreenCanvas&,
const String&,
- const CanvasContextCreationAttributesModule&,
+ const CanvasContextCreationAttributesModule*,
ExceptionState&,
OffscreenRenderingContext&);
};
diff --git a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
index 37e47045d2b..930608c0eaf 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
+++ b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
@@ -41,7 +41,7 @@ OffscreenCanvasRenderingContext2D::OffscreenCanvasRenderingContext2D(
}
dirty_rect_for_commit_.setEmpty();
WorkerSettings* worker_settings =
- ToWorkerGlobalScope(execution_context)->GetWorkerSettings();
+ To<WorkerGlobalScope>(execution_context)->GetWorkerSettings();
if (worker_settings && worker_settings->DisableReadingFromCanvas())
canvas->SetDisableReadingFromCanvasTrue();
}
diff --git a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h
index 20a4a78dc59..ce33c788092 100644
--- a/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h
+++ b/chromium/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h
@@ -33,7 +33,7 @@ class MODULES_EXPORT OffscreenCanvasRenderingContext2D final
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attrs) override {
DCHECK(host->IsOffscreenCanvas());
- return new OffscreenCanvasRenderingContext2D(
+ return MakeGarbageCollected<OffscreenCanvasRenderingContext2D>(
static_cast<OffscreenCanvas*>(host), attrs);
}
@@ -42,6 +42,10 @@ class MODULES_EXPORT OffscreenCanvasRenderingContext2D final
}
};
+ OffscreenCanvasRenderingContext2D(
+ OffscreenCanvas*,
+ const CanvasContextCreationAttributesCore& attrs);
+
OffscreenCanvas* offscreenCanvasForBinding() const {
DCHECK(!Host() || Host()->IsOffscreenCanvas());
return static_cast<OffscreenCanvas*>(Host());
@@ -116,10 +120,6 @@ class MODULES_EXPORT OffscreenCanvasRenderingContext2D final
void PushFrame() override;
protected:
- OffscreenCanvasRenderingContext2D(
- OffscreenCanvas*,
- const CanvasContextCreationAttributesCore& attrs);
-
void NeedsFinalizeFrame() override {
CanvasRenderingContext::NeedsFinalizeFrame();
}
diff --git a/chromium/third_party/blink/renderer/modules/clipboard/clipboard.cc b/chromium/third_party/blink/renderer/modules/clipboard/clipboard.cc
index 9e046cded53..457b37b183f 100644
--- a/chromium/third_party/blink/renderer/modules/clipboard/clipboard.cc
+++ b/chromium/third_party/blink/renderer/modules/clipboard/clipboard.cc
@@ -30,7 +30,7 @@ ScriptPromise Clipboard::writeText(ScriptState* script_state,
}
const AtomicString& Clipboard::InterfaceName() const {
- return EventTargetNames::Clipboard;
+ return event_target_names::kClipboard;
}
ExecutionContext* Clipboard::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc b/chromium/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc
index 27c7198ff1f..1378ca96d53 100644
--- a/chromium/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc
+++ b/chromium/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc
@@ -21,6 +21,7 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/modules/permissions/permission_utils.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
// And now, a brief note about clipboard permissions.
//
diff --git a/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.cc b/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.cc
index 85082625977..dd69ceed67d 100644
--- a/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.cc
+++ b/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.cc
@@ -18,7 +18,7 @@ Clipboard* NavigatorClipboard::clipboard(ScriptState* script_state,
NavigatorClipboard* supplement =
Supplement<Navigator>::From<NavigatorClipboard>(navigator);
if (!supplement) {
- supplement = new NavigatorClipboard(navigator);
+ supplement = MakeGarbageCollected<NavigatorClipboard>(navigator);
ProvideTo(navigator, supplement);
}
diff --git a/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.h b/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.h
index 3171101f11b..2fd6aeb8435 100644
--- a/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.h
+++ b/chromium/third_party/blink/renderer/modules/clipboard/navigator_clipboard.h
@@ -25,11 +25,11 @@ class NavigatorClipboard final : public GarbageCollected<NavigatorClipboard>,
static const char kSupplementName[];
static Clipboard* clipboard(ScriptState*, Navigator&);
+ explicit NavigatorClipboard(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorClipboard(Navigator&);
-
Member<Clipboard> clipboard_;
};
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/BUILD.gn b/chromium/third_party/blink/renderer/modules/contacts_picker/BUILD.gn
new file mode 100644
index 00000000000..d16f3e4282a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/BUILD.gn
@@ -0,0 +1,16 @@
+# Copyright 2018 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/blink/renderer/modules/modules.gni")
+
+blink_modules_sources("contacts_picker") {
+ sources = [
+ "contact_info.cc",
+ "contact_info.h",
+ "contacts_manager.cc",
+ "contacts_manager.h",
+ "navigator_contacts.cc",
+ "navigator_contacts.h",
+ ]
+}
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/DEPS b/chromium/third_party/blink/renderer/modules/contacts_picker/DEPS
new file mode 100644
index 00000000000..b618045e287
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/DEPS
@@ -0,0 +1,4 @@
+include_rules = [
+ "-third_party/blink/renderer/modules",
+ "+third_party/blink/renderer/modules/contacts_picker",
+]
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/OWNERS b/chromium/third_party/blink/renderer/modules/contacts_picker/OWNERS
new file mode 100644
index 00000000000..a74a53fbba0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/OWNERS
@@ -0,0 +1,5 @@
+finnur@chromium.org
+peter@chromium.org
+
+# TEAM: platform-capabilities@chromium.org
+# COMPONENT: Blink>Contacts
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/README.md b/chromium/third_party/blink/renderer/modules/contacts_picker/README.md
new file mode 100644
index 00000000000..5afd8bf173d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/README.md
@@ -0,0 +1,3 @@
+# Contacts Picker
+
+This directory contains the implementation of [the Contacts Picker API](https://github.com/beverloo/contact-api).
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.cc b/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.cc
new file mode 100644
index 00000000000..4da19fbcf59
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.cc
@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/contacts_picker/contact_info.h"
+
+namespace blink {
+
+ContactInfo::ContactInfo(base::Optional<Vector<String>> name,
+ base::Optional<Vector<String>> email,
+ base::Optional<Vector<String>> tel)
+ : name_(std::move(name)), email_(std::move(email)), tel_(std::move(tel)) {}
+
+ContactInfo::~ContactInfo() = default;
+
+const Vector<String> ContactInfo::name(bool& is_null) const {
+ is_null = name_.has_value();
+ return is_null ? Vector<String>() : name_.value();
+}
+
+const Vector<String> ContactInfo::email(bool& is_null) const {
+ is_null = email_.has_value();
+ return is_null ? Vector<String>() : email_.value();
+}
+
+const Vector<String> ContactInfo::tel(bool& is_null) const {
+ is_null = tel_.has_value();
+ return is_null ? Vector<String>() : tel_.value();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.h b/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.h
new file mode 100644
index 00000000000..69fc36158b7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.h
@@ -0,0 +1,38 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_CONTACT_INFO_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_CONTACT_INFO_H_
+
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/heap/thread_state.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+// Represents an individual Contact in the Contacts Picker.
+class ContactInfo final : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ ContactInfo(base::Optional<Vector<String>> name,
+ base::Optional<Vector<String>> email,
+ base::Optional<Vector<String>> tel);
+ ~ContactInfo() override;
+
+ // Web-exposed attributes defined in the IDL file.
+ const Vector<String> name(bool& is_null) const;
+ const Vector<String> email(bool& is_null) const;
+ const Vector<String> tel(bool& is_null) const;
+
+ private:
+ base::Optional<Vector<String>> name_;
+ base::Optional<Vector<String>> email_;
+ base::Optional<Vector<String>> tel_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_CONTACT_INFO_H_
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.idl b/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.idl
new file mode 100644
index 00000000000..b9a5c45cf8a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contact_info.idl
@@ -0,0 +1,15 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://github.com/beverloo/contact-api
+
+[
+ SecureContext,
+ Exposed=Window,
+ RuntimeEnabled=ContactsManager
+] interface ContactInfo {
+ readonly attribute FrozenArray<DOMString>? name;
+ readonly attribute FrozenArray<DOMString>? email;
+ readonly attribute FrozenArray<DOMString>? tel;
+};
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.cc b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.cc
new file mode 100644
index 00000000000..ff5e8964abb
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.cc
@@ -0,0 +1,24 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/contacts_picker/contacts_manager.h"
+
+#include "third_party/blink/renderer/core/dom/dom_exception.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/heap/visitor.h"
+
+namespace blink {
+
+ContactsManager::ContactsManager() = default;
+ContactsManager::~ContactsManager() = default;
+
+ScriptPromise ContactsManager::select(ScriptState* script_state,
+ ContactsSelectOptions* options) {
+ return ScriptPromise::RejectWithDOMException(
+ script_state,
+ DOMException::Create(DOMExceptionCode::kNotSupportedError,
+ "ContactsManager::select is not yet implemented"));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.h b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.h
new file mode 100644
index 00000000000..607c85db4cb
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.h
@@ -0,0 +1,32 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_CONTACTS_MANAGER_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_CONTACTS_MANAGER_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
+#include "third_party/blink/renderer/modules/contacts_picker/contacts_select_options.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/heap/thread_state.h"
+
+namespace blink {
+
+class ScriptState;
+
+// Represents an the ContactManager, providing access to Contacts.
+class ContactsManager final : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ ContactsManager();
+ ~ContactsManager() override;
+
+ // Web-exposed function defined in the IDL file.
+ ScriptPromise select(ScriptState* script_state,
+ ContactsSelectOptions* options);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_CONTACTS_MANAGER_H_
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl
new file mode 100644
index 00000000000..06c67e76a8d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_manager.idl
@@ -0,0 +1,13 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://github.com/beverloo/contact-api
+
+[
+ Exposed=Window,
+ SecureContext,
+ RuntimeEnabled=ContactsManager
+] interface ContactsManager {
+ [CallWith=ScriptState] Promise<FrozenArray<ContactInfo>> select(ContactsSelectOptions options);
+};
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_select_options.idl b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_select_options.idl
new file mode 100644
index 00000000000..9acfe325810
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/contacts_select_options.idl
@@ -0,0 +1,12 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://github.com/beverloo/contact-api
+
+enum ContactProperty { "email", "name", "tel" };
+
+dictionary ContactsSelectOptions {
+ sequence<ContactProperty> properties;
+ boolean multiple = false;
+};
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.cc b/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.cc
new file mode 100644
index 00000000000..006c354a17c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.cc
@@ -0,0 +1,46 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/contacts_picker/navigator_contacts.h"
+
+#include "third_party/blink/renderer/core/frame/navigator.h"
+#include "third_party/blink/renderer/platform/heap/visitor.h"
+
+namespace blink {
+
+// static
+const char NavigatorContacts::kSupplementName[] = "NavigatorContacts";
+
+// static
+NavigatorContacts& NavigatorContacts::From(Navigator& navigator) {
+ NavigatorContacts* supplement =
+ Supplement<Navigator>::From<NavigatorContacts>(navigator);
+ if (!supplement) {
+ supplement = new NavigatorContacts(navigator);
+ ProvideTo(navigator, supplement);
+ }
+ return *supplement;
+}
+
+// static
+ContactsManager* NavigatorContacts::contacts(Navigator& navigator) {
+ // TODO(finnur): Return null when navigator is detached?
+ return NavigatorContacts::From(navigator).contacts();
+}
+
+ContactsManager* NavigatorContacts::contacts() {
+ if (!contacts_manager_)
+ contacts_manager_ = new ContactsManager();
+ return contacts_manager_;
+}
+
+void NavigatorContacts::Trace(Visitor* visitor) {
+ visitor->Trace(contacts_manager_);
+ Supplement<Navigator>::Trace(visitor);
+}
+
+NavigatorContacts::NavigatorContacts(Navigator& navigator)
+ : Supplement<Navigator>(navigator) {}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.h b/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.h
new file mode 100644
index 00000000000..b5b16b03628
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.h
@@ -0,0 +1,40 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_NAVIGATOR_CONTACTS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_NAVIGATOR_CONTACTS_H_
+
+#include "third_party/blink/renderer/modules/contacts_picker/contacts_manager.h"
+#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
+#include "third_party/blink/renderer/platform/supplementable.h"
+
+namespace blink {
+
+class Navigator;
+
+// Represents a supplement to Navigator, implementing the Contacts Selector.
+class NavigatorContacts final : public GarbageCollected<NavigatorContacts>,
+ public Supplement<Navigator> {
+ USING_GARBAGE_COLLECTED_MIXIN(NavigatorContacts);
+
+ public:
+ static const char kSupplementName[];
+
+ static NavigatorContacts& From(Navigator& navigator);
+
+ // Web Exposed attribute defined in the IDL file.
+ static ContactsManager* contacts(Navigator& navigator);
+ ContactsManager* contacts();
+
+ void Trace(Visitor* visitor) override;
+
+ private:
+ explicit NavigatorContacts(Navigator& navigator);
+
+ Member<ContactsManager> contacts_manager_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CONTACTS_PICKER_NAVIGATOR_CONTACTS_H_
diff --git a/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl b/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl
new file mode 100644
index 00000000000..bb47e9c72ef
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/contacts_picker/navigator_contacts.idl
@@ -0,0 +1,12 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://github.com/beverloo/contact-api
+
+[
+ Exposed=Window,
+ ImplementedAs=NavigatorContacts
+] partial interface Navigator {
+ [SecureContext, RuntimeEnabled=ContactsManager] readonly attribute ContactsManager contacts;
+};
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/DEPS b/chromium/third_party/blink/renderer/modules/cookie_store/DEPS
index 9ab1bbf8075..74bc32f09ab 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/DEPS
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/DEPS
@@ -1,4 +1,3 @@
include_rules = [
"+mojo/public/cpp/bindings/binding.h",
- "+services/network/public/mojom/restricted_cookie_manager.mojom-blink.h",
]
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.cc b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.cc
index c91e99e779b..b10c99b4184 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.cc
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.cc
@@ -16,7 +16,7 @@ namespace blink {
CookieChangeEvent::~CookieChangeEvent() = default;
const AtomicString& CookieChangeEvent::InterfaceName() const {
- return EventNames::CookieChangeEvent;
+ return event_interface_names::kCookieChangeEvent;
}
void CookieChangeEvent::Trace(blink::Visitor* visitor) {
@@ -28,19 +28,19 @@ void CookieChangeEvent::Trace(blink::Visitor* visitor) {
CookieChangeEvent::CookieChangeEvent() = default;
CookieChangeEvent::CookieChangeEvent(const AtomicString& type,
- HeapVector<CookieListItem> changed,
- HeapVector<CookieListItem> deleted)
+ HeapVector<Member<CookieListItem>> changed,
+ HeapVector<Member<CookieListItem>> deleted)
: Event(type, Bubbles::kNo, Cancelable::kNo),
changed_(std::move(changed)),
deleted_(std::move(deleted)) {}
CookieChangeEvent::CookieChangeEvent(const AtomicString& type,
- const CookieChangeEventInit& initializer)
+ const CookieChangeEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasChanged())
- changed_ = initializer.changed();
- if (initializer.hasDeleted())
- deleted_ = initializer.deleted();
+ if (initializer->hasChanged())
+ changed_ = initializer->changed();
+ if (initializer->hasDeleted())
+ deleted_ = initializer->deleted();
}
namespace {
@@ -61,48 +61,52 @@ String ToCookieListItemSameSite(network::mojom::CookieSameSite same_site) {
} // namespace
// static
-void CookieChangeEvent::ToCookieListItem(
+CookieListItem* CookieChangeEvent::ToCookieListItem(
const WebCanonicalCookie& canonical_cookie,
- bool is_deleted, // True for the information from a cookie deletion event.
- CookieListItem& list_item) {
- list_item.setName(canonical_cookie.Name());
- list_item.setPath(canonical_cookie.Path());
- list_item.setSecure(canonical_cookie.IsSecure());
- list_item.setSameSite(ToCookieListItemSameSite(canonical_cookie.SameSite()));
+ bool is_deleted) {
+ CookieListItem* list_item = CookieListItem::Create();
+
+ list_item->setName(canonical_cookie.Name());
+ list_item->setPath(canonical_cookie.Path());
+ list_item->setSecure(canonical_cookie.IsSecure());
+ list_item->setSameSite(ToCookieListItemSameSite(canonical_cookie.SameSite()));
// The domain of host-only cookies is the host name, without a dot (.) prefix.
String cookie_domain = canonical_cookie.Domain();
if (cookie_domain.StartsWith("."))
- list_item.setDomain(cookie_domain.Substring(1));
+ list_item->setDomain(cookie_domain.Substring(1));
if (!is_deleted) {
- list_item.setValue(canonical_cookie.Value());
+ list_item->setValue(canonical_cookie.Value());
if (!canonical_cookie.ExpiryDate().is_null()) {
- list_item.setExpires(ConvertSecondsToDOMTimeStamp(
+ list_item->setExpires(ConvertSecondsToDOMTimeStamp(
canonical_cookie.ExpiryDate().ToDoubleT()));
}
}
+ return list_item;
}
// static
void CookieChangeEvent::ToEventInfo(
const WebCanonicalCookie& backend_cookie,
::network::mojom::CookieChangeCause change_cause,
- HeapVector<CookieListItem>& changed,
- HeapVector<CookieListItem>& deleted) {
+ HeapVector<Member<CookieListItem>>& changed,
+ HeapVector<Member<CookieListItem>>& deleted) {
switch (change_cause) {
case ::network::mojom::CookieChangeCause::INSERTED:
case ::network::mojom::CookieChangeCause::EXPLICIT: {
- CookieListItem& cookie = changed.emplace_back();
- ToCookieListItem(backend_cookie, false /* is_deleted */, cookie);
+ CookieListItem* cookie =
+ ToCookieListItem(backend_cookie, false /* is_deleted */);
+ changed.push_back(cookie);
break;
}
case ::network::mojom::CookieChangeCause::UNKNOWN_DELETION:
case ::network::mojom::CookieChangeCause::EXPIRED:
case ::network::mojom::CookieChangeCause::EVICTED:
case ::network::mojom::CookieChangeCause::EXPIRED_OVERWRITE: {
- CookieListItem& cookie = deleted.emplace_back();
- ToCookieListItem(backend_cookie, true /* is_deleted */, cookie);
+ CookieListItem* cookie =
+ ToCookieListItem(backend_cookie, true /* is_deleted */);
+ deleted.push_back(cookie);
break;
}
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.h b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.h
index 0778a306812..910e49a78ac 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.h
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_change_event.h
@@ -27,21 +27,21 @@ class CookieChangeEvent final : public Event {
// The caller is expected to create HeapVectors and std::move() them into this
// method.
static CookieChangeEvent* Create(const AtomicString& type,
- HeapVector<CookieListItem> changed,
- HeapVector<CookieListItem> deleted) {
+ HeapVector<Member<CookieListItem>> changed,
+ HeapVector<Member<CookieListItem>> deleted) {
return new CookieChangeEvent(type, std::move(changed), std::move(deleted));
}
// Used by JavaScript, via the V8 bindings.
static CookieChangeEvent* Create(const AtomicString& type,
- const CookieChangeEventInit& initializer) {
+ const CookieChangeEventInit* initializer) {
return new CookieChangeEvent(type, initializer);
}
~CookieChangeEvent() override;
- const HeapVector<CookieListItem>& changed() const { return changed_; }
- const HeapVector<CookieListItem>& deleted() const { return deleted_; }
+ const HeapVector<Member<CookieListItem>>& changed() const { return changed_; }
+ const HeapVector<Member<CookieListItem>>& deleted() const { return deleted_; }
// Event
const AtomicString& InterfaceName() const override;
@@ -49,27 +49,26 @@ class CookieChangeEvent final : public Event {
// GarbageCollected
void Trace(blink::Visitor*) override;
- static void ToCookieListItem(
+ static CookieListItem* ToCookieListItem(
const WebCanonicalCookie& canonical_cookie,
- bool is_deleted, // True for information from a cookie deletion event.
- CookieListItem& cookie);
+ bool is_deleted); // True for information from a cookie deletion event.
// Helper for converting backend event information into a CookieChangeEvent.
static void ToEventInfo(const WebCanonicalCookie& cookie,
::network::mojom::CookieChangeCause cause,
- HeapVector<CookieListItem>& changed,
- HeapVector<CookieListItem>& deleted);
+ HeapVector<Member<CookieListItem>>& changed,
+ HeapVector<Member<CookieListItem>>& deleted);
private:
CookieChangeEvent();
CookieChangeEvent(const AtomicString& type,
- HeapVector<CookieListItem> changed,
- HeapVector<CookieListItem> deleted);
+ HeapVector<Member<CookieListItem>> changed,
+ HeapVector<Member<CookieListItem>> deleted);
CookieChangeEvent(const AtomicString& type,
- const CookieChangeEventInit& initializer);
+ const CookieChangeEventInit* initializer);
- HeapVector<CookieListItem> changed_;
- HeapVector<CookieListItem> deleted_;
+ HeapVector<Member<CookieListItem>> changed_;
+ HeapVector<Member<CookieListItem>> deleted_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.cc b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.cc
index d3a45bab3ea..0f5e5a02ae5 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.cc
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.cc
@@ -36,23 +36,23 @@ namespace {
// Returns null if and only if an exception is thrown.
network::mojom::blink::CookieManagerGetOptionsPtr ToBackendOptions(
- const CookieStoreGetOptions& options,
+ const CookieStoreGetOptions* options,
ExceptionState& exception_state) {
auto backend_options = network::mojom::blink::CookieManagerGetOptions::New();
// TODO(crbug.com/729800): Handle the url option.
- if (options.matchType() == "starts-with") {
+ if (options->matchType() == "starts-with") {
backend_options->match_type =
network::mojom::blink::CookieMatchType::STARTS_WITH;
} else {
- DCHECK_EQ(options.matchType(), WTF::String("equals"));
+ DCHECK_EQ(options->matchType(), WTF::String("equals"));
backend_options->match_type =
network::mojom::blink::CookieMatchType::EQUALS;
}
- if (options.hasName()) {
- backend_options->name = options.name();
+ if (options->hasName()) {
+ backend_options->name = options->name();
} else {
// No name provided. Use a filter that matches all cookies. This overrides
// a user-provided matchType.
@@ -67,34 +67,34 @@ network::mojom::blink::CookieManagerGetOptionsPtr ToBackendOptions(
// Returns no value if and only if an exception is thrown.
base::Optional<WebCanonicalCookie> ToWebCanonicalCookie(
const KURL& cookie_url,
- const CookieStoreSetExtraOptions& options,
+ const CookieStoreSetExtraOptions* options,
ExceptionState& exception_state) {
- const String& name = options.name();
- const String& value = options.value();
+ const String& name = options->name();
+ const String& value = options->value();
if (name.IsEmpty() && value.Contains('=')) {
exception_state.ThrowTypeError(
"Cookie value cannot contain '=' if the name is empty");
return base::nullopt;
}
- WTF::Time expires = options.hasExpires()
- ? WTF::Time::FromJavaTime(options.expires())
+ WTF::Time expires = options->hasExpires()
+ ? WTF::Time::FromJavaTime(options->expires())
: WTF::Time();
String cookie_url_host = cookie_url.Host();
String domain;
- if (options.hasDomain()) {
+ if (options->hasDomain()) {
// The leading dot (".") from the domain attribute is stripped in the
// Set-Cookie header, for compatibility. This API doesn't have compatibility
// constraints, so reject the edge case outright.
- if (options.domain().StartsWith(".")) {
+ if (options->domain().StartsWith(".")) {
exception_state.ThrowTypeError("Cookie domain cannot start with \".\"");
return base::nullopt;
}
- domain = String(".") + options.domain();
+ domain = String(".") + options->domain();
if (!cookie_url_host.EndsWith(domain) &&
- cookie_url_host != options.domain()) {
+ cookie_url_host != options->domain()) {
exception_state.ThrowTypeError(
"Cookie domain must domain-match current host");
return base::nullopt;
@@ -109,24 +109,24 @@ base::Optional<WebCanonicalCookie> ToWebCanonicalCookie(
// 2) Only secure origins can set the "secure" option to true.
DCHECK(SecurityOrigin::IsSecure(cookie_url));
- const bool secure = options.secure();
+ const bool secure = options->secure();
if (!secure && (name.StartsWith("__Secure-") || name.StartsWith("__Host-"))) {
exception_state.ThrowTypeError(
"__Secure- and __Host- cookies must be secure");
}
network::mojom::CookieSameSite same_site;
- if (options.sameSite() == "strict") {
+ if (options->sameSite() == "strict") {
same_site = network::mojom::CookieSameSite::STRICT_MODE;
- } else if (options.sameSite() == "lax") {
+ } else if (options->sameSite() == "lax") {
same_site = network::mojom::CookieSameSite::LAX_MODE;
} else {
- DCHECK_EQ(options.sameSite(), "unrestricted");
+ DCHECK_EQ(options->sameSite(), "unrestricted");
same_site = network::mojom::CookieSameSite::NO_RESTRICTION;
}
return WebCanonicalCookie::Create(
- name, value, domain, options.path(), WTF::Time() /*creation*/, expires,
+ name, value, domain, options->path(), WTF::Time() /*creation*/, expires,
WTF::Time() /*last_access*/, secure, false /*http_only*/, same_site,
WebCanonicalCookie::kDefaultPriority);
}
@@ -134,30 +134,30 @@ base::Optional<WebCanonicalCookie> ToWebCanonicalCookie(
// Returns null if and only if an exception is thrown.
blink::mojom::blink::CookieChangeSubscriptionPtr ToBackendSubscription(
const KURL& default_cookie_url,
- const CookieStoreGetOptions& subscription,
+ const CookieStoreGetOptions* subscription,
ExceptionState& exception_state) {
auto backend_subscription =
blink::mojom::blink::CookieChangeSubscription::New();
- if (subscription.hasURL()) {
- KURL subscription_url(default_cookie_url, subscription.url());
+ if (subscription->hasURL()) {
+ KURL subscription_url(default_cookie_url, subscription->url());
// TODO(crbug.com/729800): Check that the URL is under default_cookie_url.
backend_subscription->url = subscription_url;
} else {
backend_subscription->url = default_cookie_url;
}
- if (subscription.matchType() == "starts-with") {
+ if (subscription->matchType() == "starts-with") {
backend_subscription->match_type =
network::mojom::blink::CookieMatchType::STARTS_WITH;
} else {
- DCHECK_EQ(subscription.matchType(), WTF::String("equals"));
+ DCHECK_EQ(subscription->matchType(), WTF::String("equals"));
backend_subscription->match_type =
network::mojom::blink::CookieMatchType::EQUALS;
}
- if (subscription.hasName()) {
- backend_subscription->name = subscription.name();
+ if (subscription->hasName()) {
+ backend_subscription->name = subscription->name();
} else {
// No name provided. Use a filter that matches all cookies. This overrides
// a user-provided matchType.
@@ -169,27 +169,29 @@ blink::mojom::blink::CookieChangeSubscriptionPtr ToBackendSubscription(
return backend_subscription;
}
-void ToCookieChangeSubscription(
- const blink::mojom::blink::CookieChangeSubscription& backend_subscription,
- CookieStoreGetOptions& subscription) {
- subscription.setURL(backend_subscription.url);
+CookieStoreGetOptions* ToCookieChangeSubscription(
+ const blink::mojom::blink::CookieChangeSubscription& backend_subscription) {
+ CookieStoreGetOptions* subscription = CookieStoreGetOptions::Create();
+ subscription->setURL(backend_subscription.url);
if (backend_subscription.match_type !=
network::mojom::blink::CookieMatchType::STARTS_WITH ||
!backend_subscription.name.IsEmpty()) {
- subscription.setName(backend_subscription.name);
+ subscription->setName(backend_subscription.name);
}
switch (backend_subscription.match_type) {
case network::mojom::blink::CookieMatchType::STARTS_WITH:
- subscription.setMatchType(WTF::String("starts-with"));
+ subscription->setMatchType(WTF::String("starts-with"));
break;
case network::mojom::blink::CookieMatchType::EQUALS:
- subscription.setMatchType(WTF::String("equals"));
+ subscription->setMatchType(WTF::String("equals"));
break;
}
- subscription.setURL(backend_subscription.url);
+ subscription->setURL(backend_subscription.url);
+
+ return subscription;
}
const KURL& DefaultCookieURL(ExecutionContext* execution_context) {
@@ -198,9 +200,7 @@ const KURL& DefaultCookieURL(ExecutionContext* execution_context) {
if (auto* document = DynamicTo<Document>(execution_context))
return document->CookieURL();
- DCHECK(execution_context->IsServiceWorkerGlobalScope());
- ServiceWorkerGlobalScope* scope =
- ToServiceWorkerGlobalScope(execution_context);
+ auto* scope = To<ServiceWorkerGlobalScope>(execution_context);
return scope->Url();
}
@@ -210,9 +210,7 @@ KURL DefaultSiteForCookies(ExecutionContext* execution_context) {
if (auto* document = DynamicTo<Document>(execution_context))
return document->SiteForCookies();
- DCHECK(execution_context->IsServiceWorkerGlobalScope());
- ServiceWorkerGlobalScope* scope =
- ToServiceWorkerGlobalScope(execution_context);
+ auto* scope = To<ServiceWorkerGlobalScope>(execution_context);
return scope->Url();
}
@@ -223,13 +221,13 @@ CookieStore::~CookieStore() = default;
ScriptPromise CookieStore::getAll(ScriptState* script_state,
const String& name,
ExceptionState& exception_state) {
- CookieStoreGetOptions options;
- options.setName(name);
+ CookieStoreGetOptions* options = CookieStoreGetOptions::Create();
+ options->setName(name);
return getAll(script_state, options, exception_state);
}
ScriptPromise CookieStore::getAll(ScriptState* script_state,
- const CookieStoreGetOptions& options,
+ const CookieStoreGetOptions* options,
ExceptionState& exception_state) {
UseCounter::Count(CurrentExecutionContext(script_state->GetIsolate()),
WebFeature::kCookieStoreAPI);
@@ -241,13 +239,13 @@ ScriptPromise CookieStore::getAll(ScriptState* script_state,
ScriptPromise CookieStore::get(ScriptState* script_state,
const String& name,
ExceptionState& exception_state) {
- CookieStoreGetOptions options;
- options.setName(name);
+ CookieStoreGetOptions* options = CookieStoreGetOptions::Create();
+ options->setName(name);
return get(script_state, options, exception_state);
}
ScriptPromise CookieStore::get(ScriptState* script_state,
- const CookieStoreGetOptions& options,
+ const CookieStoreGetOptions* options,
ExceptionState& exception_state) {
UseCounter::Count(CurrentExecutionContext(script_state->GetIsolate()),
WebFeature::kCookieStoreAPI);
@@ -259,22 +257,23 @@ ScriptPromise CookieStore::get(ScriptState* script_state,
ScriptPromise CookieStore::set(ScriptState* script_state,
const String& name,
const String& value,
- const CookieStoreSetOptions& options,
+ const CookieStoreSetOptions* options,
ExceptionState& exception_state) {
- CookieStoreSetExtraOptions set_options;
- set_options.setName(name);
- set_options.setValue(value);
- if (options.hasExpires())
- set_options.setExpires(options.expires());
- set_options.setDomain(options.domain());
- set_options.setPath(options.path());
- set_options.setSecure(options.secure());
- set_options.setSameSite(options.sameSite());
+ CookieStoreSetExtraOptions* set_options =
+ CookieStoreSetExtraOptions::Create();
+ set_options->setName(name);
+ set_options->setValue(value);
+ if (options->hasExpires())
+ set_options->setExpires(options->expires());
+ set_options->setDomain(options->domain());
+ set_options->setPath(options->path());
+ set_options->setSecure(options->secure());
+ set_options->setSameSite(options->sameSite());
return set(script_state, set_options, exception_state);
}
ScriptPromise CookieStore::set(ScriptState* script_state,
- const CookieStoreSetExtraOptions& options,
+ const CookieStoreSetExtraOptions* options,
ExceptionState& exception_state) {
UseCounter::Count(CurrentExecutionContext(script_state->GetIsolate()),
WebFeature::kCookieStoreAPI);
@@ -288,40 +287,40 @@ ScriptPromise CookieStore::Delete(ScriptState* script_state,
UseCounter::Count(CurrentExecutionContext(script_state->GetIsolate()),
WebFeature::kCookieStoreAPI);
- CookieStoreSetExtraOptions set_options;
- set_options.setName(name);
- set_options.setValue(g_empty_string);
- set_options.setExpires(0);
+ CookieStoreSetExtraOptions* set_options =
+ CookieStoreSetExtraOptions::Create();
+ set_options->setName(name);
+ set_options->setValue(g_empty_string);
+ set_options->setExpires(0);
return DoWrite(script_state, set_options, exception_state);
}
ScriptPromise CookieStore::Delete(ScriptState* script_state,
- const CookieStoreDeleteOptions& options,
+ const CookieStoreDeleteOptions* options,
ExceptionState& exception_state) {
- CookieStoreSetExtraOptions set_options;
- set_options.setName(options.name());
- set_options.setValue(g_empty_string);
- set_options.setExpires(0);
- set_options.setDomain(options.domain());
- set_options.setPath(options.path());
- set_options.setSecure(true);
- set_options.setSameSite("strict");
+ CookieStoreSetExtraOptions* set_options =
+ CookieStoreSetExtraOptions::Create();
+ set_options->setName(options->name());
+ set_options->setValue(g_empty_string);
+ set_options->setExpires(0);
+ set_options->setDomain(options->domain());
+ set_options->setPath(options->path());
+ set_options->setSecure(true);
+ set_options->setSameSite("strict");
return DoWrite(script_state, set_options, exception_state);
}
ScriptPromise CookieStore::subscribeToChanges(
ScriptState* script_state,
- const HeapVector<CookieStoreGetOptions>& subscriptions,
+ const HeapVector<Member<CookieStoreGetOptions>>& subscriptions,
ExceptionState& exception_state) {
- DCHECK(GetExecutionContext()->IsServiceWorkerGlobalScope());
-
UseCounter::Count(CurrentExecutionContext(script_state->GetIsolate()),
WebFeature::kCookieStoreAPI);
Vector<blink::mojom::blink::CookieChangeSubscriptionPtr>
backend_subscriptions;
backend_subscriptions.ReserveInitialCapacity(subscriptions.size());
- for (const CookieStoreGetOptions& subscription : subscriptions) {
+ for (const CookieStoreGetOptions* subscription : subscriptions) {
blink::mojom::blink::CookieChangeSubscriptionPtr backend_subscription =
ToBackendSubscription(default_cookie_url_, subscription,
exception_state);
@@ -338,8 +337,7 @@ ScriptPromise CookieStore::subscribeToChanges(
return ScriptPromise();
}
- ServiceWorkerGlobalScope* scope =
- ToServiceWorkerGlobalScope(GetExecutionContext());
+ auto* scope = To<ServiceWorkerGlobalScope>(GetExecutionContext());
if (!scope->IsInstalling()) {
exception_state.ThrowTypeError("Outside the installation phase");
@@ -348,7 +346,7 @@ ScriptPromise CookieStore::subscribeToChanges(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
int64_t service_worker_registration_id =
- scope->registration()->WebRegistration()->RegistrationId();
+ scope->registration()->RegistrationId();
subscription_backend_->AppendSubscriptions(
service_worker_registration_id, std::move(backend_subscriptions),
WTF::Bind(&CookieStore::OnSubscribeToCookieChangesResult,
@@ -359,8 +357,6 @@ ScriptPromise CookieStore::subscribeToChanges(
ScriptPromise CookieStore::getChangeSubscriptions(
ScriptState* script_state,
ExceptionState& exception_state) {
- DCHECK(GetExecutionContext()->IsServiceWorkerGlobalScope());
-
UseCounter::Count(CurrentExecutionContext(script_state->GetIsolate()),
WebFeature::kCookieStoreAPI);
@@ -371,10 +367,9 @@ ScriptPromise CookieStore::getChangeSubscriptions(
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
- ServiceWorkerGlobalScope* scope =
- ToServiceWorkerGlobalScope(GetExecutionContext());
+ auto* scope = To<ServiceWorkerGlobalScope>(GetExecutionContext());
int64_t service_worker_registration_id =
- scope->registration()->WebRegistration()->RegistrationId();
+ scope->registration()->RegistrationId();
subscription_backend_->GetSubscriptions(
service_worker_registration_id,
WTF::Bind(&CookieStore::OnGetCookieChangeSubscriptionResult,
@@ -388,7 +383,7 @@ void CookieStore::ContextDestroyed(ExecutionContext* execution_context) {
}
const AtomicString& CookieStore::InterfaceName() const {
- return EventTargetNames::CookieStore;
+ return event_target_names::kCookieStore;
}
ExecutionContext* CookieStore::GetExecutionContext() const {
@@ -404,7 +399,7 @@ void CookieStore::RemoveAllEventListeners() {
void CookieStore::OnCookieChange(
const WebCanonicalCookie& backend_cookie,
network::mojom::blink::CookieChangeCause change_cause) {
- HeapVector<CookieListItem> changed, deleted;
+ HeapVector<Member<CookieListItem>> changed, deleted;
CookieChangeEvent::ToEventInfo(backend_cookie, change_cause, changed,
deleted);
if (changed.IsEmpty() && deleted.IsEmpty()) {
@@ -412,7 +407,7 @@ void CookieStore::OnCookieChange(
return;
}
DispatchEvent(*CookieChangeEvent::Create(
- EventTypeNames::change, std::move(changed), std::move(deleted)));
+ event_type_names::kChange, std::move(changed), std::move(deleted)));
}
void CookieStore::AddedEventListener(
@@ -447,7 +442,7 @@ CookieStore::CookieStore(
ScriptPromise CookieStore::DoRead(
ScriptState* script_state,
- const CookieStoreGetOptions& options,
+ const CookieStoreGetOptions* options,
DoReadBackendResultConverter backend_result_converter,
ExceptionState& exception_state) {
network::mojom::blink::CookieManagerGetOptionsPtr backend_options =
@@ -479,12 +474,11 @@ void CookieStore::GetAllForUrlToGetAllResult(
if (!script_state->ContextIsValid())
return;
- HeapVector<CookieListItem> cookies;
+ HeapVector<Member<CookieListItem>> cookies;
cookies.ReserveInitialCapacity(backend_cookies.size());
for (const auto& backend_cookie : backend_cookies) {
- CookieListItem& cookie = cookies.emplace_back();
- CookieChangeEvent::ToCookieListItem(backend_cookie, false /* is_deleted */,
- cookie);
+ cookies.push_back(CookieChangeEvent::ToCookieListItem(
+ backend_cookie, false /* is_deleted */));
}
resolver->Resolve(std::move(cookies));
@@ -504,14 +498,13 @@ void CookieStore::GetAllForUrlToGetResult(
}
const auto& backend_cookie = backend_cookies.front();
- CookieListItem cookie;
- CookieChangeEvent::ToCookieListItem(backend_cookie, false /* is_deleted */,
- cookie);
+ CookieListItem* cookie = CookieChangeEvent::ToCookieListItem(
+ backend_cookie, false /* is_deleted */);
resolver->Resolve(cookie);
}
ScriptPromise CookieStore::DoWrite(ScriptState* script_state,
- const CookieStoreSetExtraOptions& options,
+ const CookieStoreSetExtraOptions* options,
ExceptionState& exception_state) {
base::Optional<WebCanonicalCookie> canonical_cookie =
ToWebCanonicalCookie(default_cookie_url_, options, exception_state);
@@ -584,11 +577,12 @@ void CookieStore::OnGetCookieChangeSubscriptionResult(
return;
}
- HeapVector<CookieStoreGetOptions> subscriptions;
+ HeapVector<Member<CookieStoreGetOptions>> subscriptions;
subscriptions.ReserveInitialCapacity(backend_result.size());
for (const auto& backend_subscription : backend_result) {
- CookieStoreGetOptions& subscription = subscriptions.emplace_back();
- ToCookieChangeSubscription(*backend_subscription, subscription);
+ CookieStoreGetOptions* subscription =
+ ToCookieChangeSubscription(*backend_subscription);
+ subscriptions.push_back(subscription);
}
resolver->Resolve(std::move(subscriptions));
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.h b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.h
index 3344bb5233d..3eb76bf3fd9 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.h
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/cookie_store.h
@@ -47,28 +47,28 @@ class CookieStore final : public EventTargetWithInlineData,
ScriptPromise getAll(ScriptState*, const String& name, ExceptionState&);
ScriptPromise getAll(ScriptState*,
- const CookieStoreGetOptions&,
+ const CookieStoreGetOptions*,
ExceptionState&);
ScriptPromise get(ScriptState*, const String& name, ExceptionState&);
ScriptPromise get(ScriptState*,
- const CookieStoreGetOptions&,
+ const CookieStoreGetOptions*,
ExceptionState&);
ScriptPromise set(ScriptState*,
- const CookieStoreSetExtraOptions&,
+ const CookieStoreSetExtraOptions*,
ExceptionState&);
ScriptPromise set(ScriptState*,
const String& name,
const String& value,
- const CookieStoreSetOptions&,
+ const CookieStoreSetOptions*,
ExceptionState&);
ScriptPromise Delete(ScriptState*, const String& name, ExceptionState&);
ScriptPromise Delete(ScriptState*,
- const CookieStoreDeleteOptions&,
+ const CookieStoreDeleteOptions*,
ExceptionState&);
ScriptPromise subscribeToChanges(
ScriptState*,
- const HeapVector<CookieStoreGetOptions>& subscriptions,
+ const HeapVector<Member<CookieStoreGetOptions>>& subscriptions,
ExceptionState&);
ScriptPromise getChangeSubscriptions(ScriptState*, ExceptionState&);
@@ -82,7 +82,7 @@ class CookieStore final : public EventTargetWithInlineData,
void ContextDestroyed(ExecutionContext*) override;
// EventTargetWithInlineData
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
void RemoveAllEventListeners() override;
@@ -113,7 +113,7 @@ class CookieStore final : public EventTargetWithInlineData,
// captured in the DoReadBackendResultConverter argument, which should point
// to one of the static methods below.
ScriptPromise DoRead(ScriptState*,
- const CookieStoreGetOptions&,
+ const CookieStoreGetOptions*,
DoReadBackendResultConverter,
ExceptionState&);
@@ -131,7 +131,7 @@ class CookieStore final : public EventTargetWithInlineData,
// Common code in CookieStore::delete and CookieStore::set.
ScriptPromise DoWrite(ScriptState*,
- const CookieStoreSetExtraOptions&,
+ const CookieStoreSetExtraOptions*,
ExceptionState&);
static void OnSetCanonicalCookieResult(ScriptPromiseResolver*,
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.cc b/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.cc
index 8b26aba04b2..98eba76c95d 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.cc
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.cc
@@ -17,7 +17,7 @@ namespace blink {
ExtendableCookieChangeEvent::~ExtendableCookieChangeEvent() = default;
const AtomicString& ExtendableCookieChangeEvent::InterfaceName() const {
- return EventNames::ExtendableCookieChangeEvent;
+ return event_interface_names::kExtendableCookieChangeEvent;
}
void ExtendableCookieChangeEvent::Trace(blink::Visitor* visitor) {
@@ -28,21 +28,21 @@ void ExtendableCookieChangeEvent::Trace(blink::Visitor* visitor) {
ExtendableCookieChangeEvent::ExtendableCookieChangeEvent(
const AtomicString& type,
- HeapVector<CookieListItem> changed,
- HeapVector<CookieListItem> deleted,
+ HeapVector<Member<CookieListItem>> changed,
+ HeapVector<Member<CookieListItem>> deleted,
WaitUntilObserver* wait_until_observer)
- : ExtendableEvent(type, ExtendableEventInit(), wait_until_observer),
+ : ExtendableEvent(type, ExtendableEventInit::Create(), wait_until_observer),
changed_(std::move(changed)),
deleted_(std::move(deleted)) {}
ExtendableCookieChangeEvent::ExtendableCookieChangeEvent(
const AtomicString& type,
- const ExtendableCookieChangeEventInit& initializer)
+ const ExtendableCookieChangeEventInit* initializer)
: ExtendableEvent(type, initializer) {
- if (initializer.hasChanged())
- changed_ = initializer.changed();
- if (initializer.hasDeleted())
- deleted_ = initializer.deleted();
+ if (initializer->hasChanged())
+ changed_ = initializer->changed();
+ if (initializer->hasDeleted())
+ deleted_ = initializer->deleted();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.h b/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.h
index c0fb5e615d9..2fe473392b8 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.h
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/extendable_cookie_change_event.h
@@ -27,24 +27,31 @@ class ExtendableCookieChangeEvent final : public ExtendableEvent {
// method.
static ExtendableCookieChangeEvent* Create(
const AtomicString& type,
- HeapVector<CookieListItem> changed,
- HeapVector<CookieListItem> deleted,
+ HeapVector<Member<CookieListItem>> changed,
+ HeapVector<Member<CookieListItem>> deleted,
WaitUntilObserver* wait_until_observer) {
- return new ExtendableCookieChangeEvent(
+ return MakeGarbageCollected<ExtendableCookieChangeEvent>(
type, std::move(changed), std::move(deleted), wait_until_observer);
}
// Used by JavaScript, via the V8 bindings.
static ExtendableCookieChangeEvent* Create(
const AtomicString& type,
- const ExtendableCookieChangeEventInit& initializer) {
- return new ExtendableCookieChangeEvent(type, initializer);
+ const ExtendableCookieChangeEventInit* initializer) {
+ return MakeGarbageCollected<ExtendableCookieChangeEvent>(type, initializer);
}
+ ExtendableCookieChangeEvent(const AtomicString& type,
+ HeapVector<Member<CookieListItem>> changed,
+ HeapVector<Member<CookieListItem>> deleted,
+ WaitUntilObserver*);
+ ExtendableCookieChangeEvent(
+ const AtomicString& type,
+ const ExtendableCookieChangeEventInit* initializer);
~ExtendableCookieChangeEvent() override;
- const HeapVector<CookieListItem>& changed() const { return changed_; }
- const HeapVector<CookieListItem>& deleted() const { return deleted_; }
+ const HeapVector<Member<CookieListItem>>& changed() const { return changed_; }
+ const HeapVector<Member<CookieListItem>>& deleted() const { return deleted_; }
// Event
const AtomicString& InterfaceName() const override;
@@ -53,16 +60,9 @@ class ExtendableCookieChangeEvent final : public ExtendableEvent {
void Trace(blink::Visitor*) override;
private:
- ExtendableCookieChangeEvent(const AtomicString& type,
- HeapVector<CookieListItem> changed,
- HeapVector<CookieListItem> deleted,
- WaitUntilObserver*);
- ExtendableCookieChangeEvent(
- const AtomicString& type,
- const ExtendableCookieChangeEventInit& initializer);
- HeapVector<CookieListItem> changed_;
- HeapVector<CookieListItem> deleted_;
+ HeapVector<Member<CookieListItem>> changed_;
+ HeapVector<Member<CookieListItem>> deleted_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/global_cookie_store_impl.h b/chromium/third_party/blink/renderer/modules/cookie_store/global_cookie_store_impl.h
index fa8c46e84e9..ec85f113d2a 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/global_cookie_store_impl.h
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/global_cookie_store_impl.h
@@ -27,12 +27,15 @@ class GlobalCookieStoreImpl final
GlobalCookieStoreImpl* supplement =
Supplement<T>::template From<GlobalCookieStoreImpl>(supplementable);
if (!supplement) {
- supplement = new GlobalCookieStoreImpl(supplementable);
+ supplement = MakeGarbageCollected<GlobalCookieStoreImpl>(supplementable);
Supplement<T>::ProvideTo(supplementable, supplement);
}
return *supplement;
}
+ explicit GlobalCookieStoreImpl(T& supplementable)
+ : Supplement<T>(supplementable) {}
+
CookieStore* GetCookieStore(T& scope) {
if (!cookie_store_) {
ExecutionContext* execution_context = scope.GetExecutionContext();
@@ -55,9 +58,6 @@ class GlobalCookieStoreImpl final
}
private:
- explicit GlobalCookieStoreImpl(T& supplementable)
- : Supplement<T>(supplementable) {}
-
Member<CookieStore> cookie_store_;
};
diff --git a/chromium/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.h b/chromium/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.h
index cf1224ed366..1c44f1b2dd6 100644
--- a/chromium/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.h
+++ b/chromium/third_party/blink/renderer/modules/cookie_store/service_worker_global_scope_cookie_store.h
@@ -20,7 +20,7 @@ class ServiceWorkerGlobalScopeCookieStore {
public:
static CookieStore* cookieStore(ServiceWorkerGlobalScope&);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cookiechange);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cookiechange, kCookiechange);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/OWNERS b/chromium/third_party/blink/renderer/modules/credentialmanager/OWNERS
index d58a4f627ae..8e0914e13b2 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/OWNERS
@@ -1,9 +1,9 @@
-engedy@chromium.org
mkwst@chromium.org
vasilii@chromium.org
+file://device/fido/OWNERS
per-file *_type_converter*.*=set noparent
per-file *_type_converter*.*=file://ipc/SECURITY_OWNERS
-# COMPONENT: Blink>SecurityFeature>CredentialManagement
# TEAM: identity-dev@chromium.org
+# COMPONENT: Blink>SecurityFeature>CredentialManagement
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_inputs.idl b/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_inputs.idl
index 6e7920cb723..da8f02e322c 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_inputs.idl
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_inputs.idl
@@ -9,4 +9,6 @@ dictionary AuthenticationExtensionsClientInputs {
USVString appid;
CableRegistrationData cableRegistration;
sequence<CableAuthenticationData> cableAuthentication;
-}; \ No newline at end of file
+ // https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-client-to-authenticator-protocol-v2.0-rd-20180702.html#sctn-hmac-secret-extension
+ boolean hmacCreateSecret;
+};
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_outputs.idl b/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_outputs.idl
index fbd15407784..582d38e7b16 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_outputs.idl
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/authentication_extensions_client_outputs.idl
@@ -6,4 +6,6 @@
dictionary AuthenticationExtensionsClientOutputs {
boolean appid;
+ // https://fidoalliance.org/specs/fido-v2.0-rd-20180702/fido-client-to-authenticator-protocol-v2.0-rd-20180702.html#sctn-hmac-secret-extension
+ boolean hmacCreateSecret;
};
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.cc
index 2f3eb1f6f5a..532dfed6988 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.cc
@@ -276,45 +276,45 @@ AuthenticatorAttachment TypeConverter<AuthenticatorAttachment, String>::Convert(
// static
AuthenticatorSelectionCriteriaPtr
TypeConverter<AuthenticatorSelectionCriteriaPtr,
- blink::AuthenticatorSelectionCriteria>::
- Convert(const blink::AuthenticatorSelectionCriteria& criteria) {
+ blink::AuthenticatorSelectionCriteria*>::
+ Convert(const blink::AuthenticatorSelectionCriteria* criteria) {
auto mojo_criteria =
blink::mojom::blink::AuthenticatorSelectionCriteria::New();
mojo_criteria->authenticator_attachment =
- ConvertTo<AuthenticatorAttachment>(criteria.authenticatorAttachment());
- mojo_criteria->require_resident_key = criteria.requireResidentKey();
+ ConvertTo<AuthenticatorAttachment>(criteria->authenticatorAttachment());
+ mojo_criteria->require_resident_key = criteria->requireResidentKey();
mojo_criteria->user_verification =
- ConvertTo<UserVerificationRequirement>(criteria.userVerification());
+ ConvertTo<UserVerificationRequirement>(criteria->userVerification());
return mojo_criteria;
}
// static
PublicKeyCredentialUserEntityPtr
TypeConverter<PublicKeyCredentialUserEntityPtr,
- blink::PublicKeyCredentialUserEntity>::
- Convert(const blink::PublicKeyCredentialUserEntity& user) {
+ blink::PublicKeyCredentialUserEntity*>::
+ Convert(const blink::PublicKeyCredentialUserEntity* user) {
auto entity = PublicKeyCredentialUserEntity::New();
- entity->id = ConvertTo<Vector<uint8_t>>(user.id());
- entity->name = user.name();
- if (user.hasIcon()) {
- entity->icon = blink::KURL(blink::KURL(), user.icon());
+ entity->id = ConvertTo<Vector<uint8_t>>(user->id());
+ entity->name = user->name();
+ if (user->hasIcon()) {
+ entity->icon = blink::KURL(blink::KURL(), user->icon());
}
- entity->display_name = user.displayName();
+ entity->display_name = user->displayName();
return entity;
}
// static
PublicKeyCredentialRpEntityPtr
TypeConverter<PublicKeyCredentialRpEntityPtr,
- blink::PublicKeyCredentialRpEntity>::
- Convert(const blink::PublicKeyCredentialRpEntity& rp) {
+ blink::PublicKeyCredentialRpEntity*>::
+ Convert(const blink::PublicKeyCredentialRpEntity* rp) {
auto entity = PublicKeyCredentialRpEntity::New();
- if (rp.hasId()) {
- entity->id = rp.id();
+ if (rp->hasId()) {
+ entity->id = rp->id();
}
- entity->name = rp.name();
- if (rp.hasIcon()) {
- entity->icon = blink::KURL(blink::KURL(), rp.icon());
+ entity->name = rp->name();
+ if (rp->hasIcon()) {
+ entity->icon = blink::KURL(blink::KURL(), rp->icon());
}
return entity;
}
@@ -322,14 +322,15 @@ TypeConverter<PublicKeyCredentialRpEntityPtr,
// static
PublicKeyCredentialDescriptorPtr
TypeConverter<PublicKeyCredentialDescriptorPtr,
- blink::PublicKeyCredentialDescriptor>::
- Convert(const blink::PublicKeyCredentialDescriptor& descriptor) {
+ blink::PublicKeyCredentialDescriptor*>::
+ Convert(const blink::PublicKeyCredentialDescriptor* descriptor) {
auto mojo_descriptor = PublicKeyCredentialDescriptor::New();
- mojo_descriptor->type = ConvertTo<PublicKeyCredentialType>(descriptor.type());
- mojo_descriptor->id = ConvertTo<Vector<uint8_t>>(descriptor.id());
- if (descriptor.hasTransports()) {
- for (const auto& transport : descriptor.transports()) {
+ mojo_descriptor->type =
+ ConvertTo<PublicKeyCredentialType>(descriptor->type());
+ mojo_descriptor->id = ConvertTo<Vector<uint8_t>>(descriptor->id());
+ if (descriptor->hasTransports() && !descriptor->transports().IsEmpty()) {
+ for (const auto& transport : descriptor->transports()) {
mojo_descriptor->transports.push_back(
ConvertTo<AuthenticatorTransport>(transport));
}
@@ -345,35 +346,36 @@ TypeConverter<PublicKeyCredentialDescriptorPtr,
// static
PublicKeyCredentialParametersPtr
TypeConverter<PublicKeyCredentialParametersPtr,
- blink::PublicKeyCredentialParameters>::
- Convert(const blink::PublicKeyCredentialParameters& parameter) {
+ blink::PublicKeyCredentialParameters*>::
+ Convert(const blink::PublicKeyCredentialParameters* parameter) {
auto mojo_parameter = PublicKeyCredentialParameters::New();
- mojo_parameter->type = ConvertTo<PublicKeyCredentialType>(parameter.type());
+ mojo_parameter->type = ConvertTo<PublicKeyCredentialType>(parameter->type());
// A COSEAlgorithmIdentifier's value is a number identifying a cryptographic
// algorithm. Values are registered in the IANA COSE Algorithms registry.
// https://www.iana.org/assignments/cose/cose.xhtml#algorithms
- mojo_parameter->algorithm_identifier = parameter.alg();
+ mojo_parameter->algorithm_identifier = parameter->alg();
return mojo_parameter;
}
// static
PublicKeyCredentialCreationOptionsPtr
TypeConverter<PublicKeyCredentialCreationOptionsPtr,
- blink::PublicKeyCredentialCreationOptions>::
- Convert(const blink::PublicKeyCredentialCreationOptions& options) {
+ blink::PublicKeyCredentialCreationOptions*>::
+ Convert(const blink::PublicKeyCredentialCreationOptions* options) {
auto mojo_options =
blink::mojom::blink::PublicKeyCredentialCreationOptions::New();
- mojo_options->relying_party = PublicKeyCredentialRpEntity::From(options.rp());
- mojo_options->user = PublicKeyCredentialUserEntity::From(options.user());
+ mojo_options->relying_party =
+ PublicKeyCredentialRpEntity::From(options->rp());
+ mojo_options->user = PublicKeyCredentialUserEntity::From(options->user());
if (!mojo_options->relying_party | !mojo_options->user) {
return nullptr;
}
- mojo_options->challenge = ConvertTo<Vector<uint8_t>>(options.challenge());
+ mojo_options->challenge = ConvertTo<Vector<uint8_t>>(options->challenge());
// Step 4 of https://w3c.github.io/webauthn/#createCredential
- if (options.hasTimeout()) {
- mojo_options->adjusted_timeout = AdjustTimeout(options.timeout());
+ if (options->hasTimeout()) {
+ mojo_options->adjusted_timeout = AdjustTimeout(options->timeout());
} else {
mojo_options->adjusted_timeout = kAdjustedTimeoutUpper;
}
@@ -381,30 +383,30 @@ TypeConverter<PublicKeyCredentialCreationOptionsPtr,
// Steps 8 and 9 of
// https://www.w3.org/TR/2017/WD-webauthn-20170505/#createCredential
Vector<PublicKeyCredentialParametersPtr> parameters;
- for (const auto& parameter : options.pubKeyCredParams()) {
+ for (auto& parameter : options->pubKeyCredParams()) {
PublicKeyCredentialParametersPtr normalized_parameter =
- PublicKeyCredentialParameters::From(parameter);
+ PublicKeyCredentialParameters::From(parameter.Get());
if (normalized_parameter) {
parameters.push_back(std::move(normalized_parameter));
}
}
- if (parameters.IsEmpty() && options.hasPubKeyCredParams()) {
+ if (parameters.IsEmpty() && options->hasPubKeyCredParams()) {
return nullptr;
}
mojo_options->public_key_parameters = std::move(parameters);
- if (options.hasAuthenticatorSelection()) {
+ if (options->hasAuthenticatorSelection()) {
mojo_options->authenticator_selection =
- AuthenticatorSelectionCriteria::From(options.authenticatorSelection());
+ AuthenticatorSelectionCriteria::From(options->authenticatorSelection());
}
- if (options.hasExcludeCredentials()) {
+ if (options->hasExcludeCredentials()) {
// Adds the excludeCredentials members
- for (const auto descriptor : options.excludeCredentials()) {
+ for (auto& descriptor : options->excludeCredentials()) {
PublicKeyCredentialDescriptorPtr mojo_descriptor =
- PublicKeyCredentialDescriptor::From(descriptor);
+ PublicKeyCredentialDescriptor::From(descriptor.Get());
if (mojo_descriptor) {
mojo_options->exclude_credentials.push_back(std::move(mojo_descriptor));
}
@@ -413,8 +415,8 @@ TypeConverter<PublicKeyCredentialCreationOptionsPtr,
mojo_options->attestation =
blink::mojom::AttestationConveyancePreference::NONE;
- if (options.hasAttestation()) {
- const auto& attestation = options.attestation();
+ if (options->hasAttestation()) {
+ const auto& attestation = options->attestation();
if (attestation == "none") {
// Default value.
} else if (attestation == "indirect") {
@@ -431,15 +433,18 @@ TypeConverter<PublicKeyCredentialCreationOptionsPtr,
}
}
- if (options.hasExtensions()) {
- const auto& extensions = options.extensions();
- if (extensions.hasCableRegistration()) {
+ if (options->hasExtensions()) {
+ auto* extensions = options->extensions();
+ if (extensions->hasCableRegistration()) {
CableRegistrationPtr mojo_cable =
- CableRegistration::From(extensions.cableRegistration());
+ CableRegistration::From(extensions->cableRegistration());
if (mojo_cable) {
mojo_options->cable_registration_data = std::move(mojo_cable);
}
}
+ if (extensions->hasHmacCreateSecret()) {
+ mojo_options->hmac_create_secret = extensions->hmacCreateSecret();
+ }
}
return mojo_options;
@@ -447,14 +452,14 @@ TypeConverter<PublicKeyCredentialCreationOptionsPtr,
// static
CableAuthenticationPtr
-TypeConverter<CableAuthenticationPtr, blink::CableAuthenticationData>::Convert(
- const blink::CableAuthenticationData& data) {
+TypeConverter<CableAuthenticationPtr, blink::CableAuthenticationData*>::Convert(
+ const blink::CableAuthenticationData* data) {
auto entity = CableAuthentication::New();
- entity->version = data.version();
- entity->client_eid = ConvertFixedSizeArray(data.clientEid(), 16);
+ entity->version = data->version();
+ entity->client_eid = ConvertFixedSizeArray(data->clientEid(), 16);
entity->authenticator_eid =
- ConvertFixedSizeArray(data.authenticatorEid(), 16);
- entity->session_pre_key = ConvertFixedSizeArray(data.sessionPreKey(), 32);
+ ConvertFixedSizeArray(data->authenticatorEid(), 16);
+ entity->session_pre_key = ConvertFixedSizeArray(data->sessionPreKey(), 32);
if (entity->client_eid.IsEmpty() || entity->authenticator_eid.IsEmpty() ||
entity->session_pre_key.IsEmpty()) {
return nullptr;
@@ -464,12 +469,12 @@ TypeConverter<CableAuthenticationPtr, blink::CableAuthenticationData>::Convert(
// static
CableRegistrationPtr
-TypeConverter<CableRegistrationPtr, blink::CableRegistrationData>::Convert(
- const blink::CableRegistrationData& data) {
+TypeConverter<CableRegistrationPtr, blink::CableRegistrationData*>::Convert(
+ const blink::CableRegistrationData* data) {
auto entity = CableRegistration::New();
- entity->versions = data.versions();
+ entity->versions = data->versions();
entity->relying_party_public_key =
- ConvertFixedSizeArray(data.rpPublicKey(), 65);
+ ConvertFixedSizeArray(data->rpPublicKey(), 65);
if (entity->relying_party_public_key.IsEmpty()) {
return nullptr;
}
@@ -479,25 +484,25 @@ TypeConverter<CableRegistrationPtr, blink::CableRegistrationData>::Convert(
// static
PublicKeyCredentialRequestOptionsPtr
TypeConverter<PublicKeyCredentialRequestOptionsPtr,
- blink::PublicKeyCredentialRequestOptions>::
- Convert(const blink::PublicKeyCredentialRequestOptions& options) {
+ blink::PublicKeyCredentialRequestOptions*>::
+ Convert(const blink::PublicKeyCredentialRequestOptions* options) {
auto mojo_options =
blink::mojom::blink::PublicKeyCredentialRequestOptions::New();
- mojo_options->challenge = ConvertTo<Vector<uint8_t>>(options.challenge());
+ mojo_options->challenge = ConvertTo<Vector<uint8_t>>(options->challenge());
- if (options.hasTimeout()) {
- mojo_options->adjusted_timeout = AdjustTimeout(options.timeout());
+ if (options->hasTimeout()) {
+ mojo_options->adjusted_timeout = AdjustTimeout(options->timeout());
} else {
mojo_options->adjusted_timeout = kAdjustedTimeoutUpper;
}
- mojo_options->relying_party_id = options.rpId();
+ mojo_options->relying_party_id = options->rpId();
- if (options.hasAllowCredentials()) {
+ if (options->hasAllowCredentials()) {
// Adds the allowList members
- for (auto descriptor : options.allowCredentials()) {
+ for (auto descriptor : options->allowCredentials()) {
PublicKeyCredentialDescriptorPtr mojo_descriptor =
- PublicKeyCredentialDescriptor::From(descriptor);
+ PublicKeyCredentialDescriptor::From(descriptor.Get());
if (mojo_descriptor) {
mojo_options->allow_credentials.push_back(std::move(mojo_descriptor));
}
@@ -505,17 +510,18 @@ TypeConverter<PublicKeyCredentialRequestOptionsPtr,
}
mojo_options->user_verification =
- ConvertTo<UserVerificationRequirement>(options.userVerification());
+ ConvertTo<UserVerificationRequirement>(options->userVerification());
- if (options.hasExtensions()) {
- const auto& extensions = options.extensions();
- if (extensions.hasAppid()) {
- mojo_options->appid = extensions.appid();
+ if (options->hasExtensions()) {
+ auto* extensions = options->extensions();
+ if (extensions->hasAppid()) {
+ mojo_options->appid = extensions->appid();
}
- if (extensions.hasCableAuthentication()) {
+ if (extensions->hasCableAuthentication()) {
Vector<CableAuthenticationPtr> mojo_data;
- for (const auto& data : extensions.cableAuthentication()) {
- CableAuthenticationPtr mojo_cable = CableAuthentication::From(data);
+ for (auto& data : extensions->cableAuthentication()) {
+ CableAuthenticationPtr mojo_cable =
+ CableAuthentication::From(data.Get());
if (mojo_cable) {
mojo_data.push_back(std::move(mojo_cable));
}
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.h b/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.h
index 7da3e65c514..dd94aab4a77 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.h
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/credential_manager_type_converters.h
@@ -90,65 +90,65 @@ struct TypeConverter<blink::mojom::blink::AuthenticatorAttachment, String> {
template <>
struct TypeConverter<blink::mojom::blink::AuthenticatorSelectionCriteriaPtr,
- blink::AuthenticatorSelectionCriteria> {
+ blink::AuthenticatorSelectionCriteria*> {
static blink::mojom::blink::AuthenticatorSelectionCriteriaPtr Convert(
- const blink::AuthenticatorSelectionCriteria&);
+ const blink::AuthenticatorSelectionCriteria*);
};
template <>
struct TypeConverter<blink::mojom::blink::PublicKeyCredentialUserEntityPtr,
- blink::PublicKeyCredentialUserEntity> {
+ blink::PublicKeyCredentialUserEntity*> {
static blink::mojom::blink::PublicKeyCredentialUserEntityPtr Convert(
- const blink::PublicKeyCredentialUserEntity&);
+ const blink::PublicKeyCredentialUserEntity*);
};
template <>
struct TypeConverter<blink::mojom::blink::PublicKeyCredentialRpEntityPtr,
- blink::PublicKeyCredentialRpEntity> {
+ blink::PublicKeyCredentialRpEntity*> {
static blink::mojom::blink::PublicKeyCredentialRpEntityPtr Convert(
- const blink::PublicKeyCredentialRpEntity&);
+ const blink::PublicKeyCredentialRpEntity*);
};
template <>
struct TypeConverter<blink::mojom::blink::PublicKeyCredentialDescriptorPtr,
- blink::PublicKeyCredentialDescriptor> {
+ blink::PublicKeyCredentialDescriptor*> {
static blink::mojom::blink::PublicKeyCredentialDescriptorPtr Convert(
- const blink::PublicKeyCredentialDescriptor&);
+ const blink::PublicKeyCredentialDescriptor*);
};
template <>
struct TypeConverter<blink::mojom::blink::PublicKeyCredentialParametersPtr,
- blink::PublicKeyCredentialParameters> {
+ blink::PublicKeyCredentialParameters*> {
static blink::mojom::blink::PublicKeyCredentialParametersPtr Convert(
- const blink::PublicKeyCredentialParameters&);
+ const blink::PublicKeyCredentialParameters*);
};
template <>
struct TypeConverter<blink::mojom::blink::PublicKeyCredentialCreationOptionsPtr,
- blink::PublicKeyCredentialCreationOptions> {
+ blink::PublicKeyCredentialCreationOptions*> {
static blink::mojom::blink::PublicKeyCredentialCreationOptionsPtr Convert(
- const blink::PublicKeyCredentialCreationOptions&);
+ const blink::PublicKeyCredentialCreationOptions*);
};
template <>
struct TypeConverter<blink::mojom::blink::CableAuthenticationPtr,
- blink::CableAuthenticationData> {
+ blink::CableAuthenticationData*> {
static blink::mojom::blink::CableAuthenticationPtr Convert(
- const blink::CableAuthenticationData&);
+ const blink::CableAuthenticationData*);
};
template <>
struct TypeConverter<blink::mojom::blink::CableRegistrationPtr,
- blink::CableRegistrationData> {
+ blink::CableRegistrationData*> {
static blink::mojom::blink::CableRegistrationPtr Convert(
- const blink::CableRegistrationData&);
+ const blink::CableRegistrationData*);
};
template <>
struct TypeConverter<blink::mojom::blink::PublicKeyCredentialRequestOptionsPtr,
- blink::PublicKeyCredentialRequestOptions> {
+ blink::PublicKeyCredentialRequestOptions*> {
static blink::mojom::blink::PublicKeyCredentialRequestOptionsPtr Convert(
- const blink::PublicKeyCredentialRequestOptions&);
+ const blink::PublicKeyCredentialRequestOptions*);
};
} // namespace mojo
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.cc
index 4daa0598c63..a2e73b6710e 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.cc
@@ -54,6 +54,8 @@ using MojoPublicKeyCredentialRequestOptions =
mojom::blink::PublicKeyCredentialRequestOptions;
using mojom::blink::GetAssertionAuthenticatorResponsePtr;
+constexpr char kCryptotokenOrigin[] =
+ "chrome-extension://kmendfapggjehodndflmmgagdbamhnfd";
enum class RequiredOriginType { kSecure, kSecureAndSameWithAncestors };
bool IsSameOriginWithAncestors(const Frame* frame) {
@@ -133,6 +135,13 @@ bool CheckPublicKeySecurityRequirements(ScriptPromiseResolver* resolver,
return false;
}
+ auto cryptotoken_origin = SecurityOrigin::Create(KURL(kCryptotokenOrigin));
+ if (cryptotoken_origin->IsSameSchemeHostPort(origin)) {
+ // Allow CryptoToken U2F extension to assert any origin, as cryptotoken
+ // handles origin checking separately.
+ return true;
+ }
+
if (origin->Protocol() != url::kHttpScheme &&
origin->Protocol() != url::kHttpsScheme) {
resolver->Reject(DOMException::Create(
@@ -156,7 +165,7 @@ bool CheckPublicKeySecurityRequirements(ScriptPromiseResolver* resolver,
// for the IP address check.
OriginAccessEntry access_entry(
origin->Protocol(), effective_domain,
- network::cors::OriginAccessEntry::MatchMode::kAllowSubdomains);
+ network::mojom::CorsOriginAccessMatchMode::kAllowSubdomains);
if (effective_domain.IsEmpty() || access_entry.HostIsIPAddress()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kSecurityError,
@@ -170,7 +179,7 @@ bool CheckPublicKeySecurityRequirements(ScriptPromiseResolver* resolver,
if (!relying_party_id.IsNull()) {
OriginAccessEntry access_entry(
origin->Protocol(), relying_party_id,
- network::cors::OriginAccessEntry::kAllowSubdomains);
+ network::mojom::CorsOriginAccessMatchMode::kAllowSubdomains);
if (relying_party_id.IsEmpty() ||
access_entry.MatchesDomain(*origin) !=
network::cors::OriginAccessEntry::kMatchesOrigin) {
@@ -342,9 +351,15 @@ void OnMakePublicKeyCredentialComplete(
AuthenticatorAttestationResponse* authenticator_response =
AuthenticatorAttestationResponse::Create(
client_data_buffer, attestation_buffer, credential->transports);
+
+ AuthenticationExtensionsClientOutputs* extension_outputs =
+ AuthenticationExtensionsClientOutputs::Create();
+ if (credential->echo_hmac_create_secret) {
+ extension_outputs->setHmacCreateSecret(credential->hmac_create_secret);
+ }
resolver->Resolve(PublicKeyCredential::Create(credential->info->id, raw_id,
authenticator_response,
- {} /* extensions_outputs */));
+ extension_outputs));
} else {
DCHECK(!credential);
resolver->Reject(CredentialManagerErrorToDOMException(
@@ -384,9 +399,10 @@ void OnGetAssertionComplete(
AuthenticatorAssertionResponse::Create(client_data_buffer,
authenticator_buffer,
signature_buffer, user_handle);
- AuthenticationExtensionsClientOutputs extension_outputs;
+ AuthenticationExtensionsClientOutputs* extension_outputs =
+ AuthenticationExtensionsClientOutputs::Create();
if (credential->echo_appid_extension) {
- extension_outputs.setAppid(credential->appid_extension);
+ extension_outputs->setAppid(credential->appid_extension);
}
resolver->Resolve(PublicKeyCredential::Create(credential->info->id, raw_id,
authenticator_response,
@@ -408,7 +424,7 @@ CredentialsContainer::CredentialsContainer() = default;
ScriptPromise CredentialsContainer::get(
ScriptState* script_state,
- const CredentialRequestOptions& options) {
+ const CredentialRequestOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -416,17 +432,17 @@ ScriptPromise CredentialsContainer::get(
if (!CheckSecurityRequirementsBeforeRequest(resolver, required_origin_type))
return promise;
- if (options.hasPublicKey()) {
+ if (options->hasPublicKey()) {
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerGetPublicKeyCredential);
- const String& relying_party_id = options.publicKey().rpId();
+ const String& relying_party_id = options->publicKey()->rpId();
if (!CheckPublicKeySecurityRequirements(resolver, relying_party_id))
return promise;
- if (options.publicKey().hasExtensions()) {
- if (options.publicKey().extensions().hasAppid()) {
- const auto& appid = options.publicKey().extensions().appid();
+ if (options->publicKey()->hasExtensions()) {
+ if (options->publicKey()->extensions()->hasAppid()) {
+ const auto& appid = options->publicKey()->extensions()->appid();
if (!appid.IsEmpty()) {
KURL appid_url(appid);
if (!appid_url.IsValid()) {
@@ -438,7 +454,7 @@ ScriptPromise CredentialsContainer::get(
}
}
}
- if (options.publicKey().extensions().hasCableRegistration()) {
+ if (options->publicKey()->extensions()->hasCableRegistration()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError,
"The 'cableRegistration' extension is only valid when creating "
@@ -448,7 +464,7 @@ ScriptPromise CredentialsContainer::get(
}
auto mojo_options =
- MojoPublicKeyCredentialRequestOptions::From(options.publicKey());
+ MojoPublicKeyCredentialRequestOptions::From(options->publicKey());
if (mojo_options) {
if (!mojo_options->relying_party_id) {
mojo_options->relying_party_id = resolver->GetFrame()
@@ -472,8 +488,8 @@ ScriptPromise CredentialsContainer::get(
}
Vector<KURL> providers;
- if (options.hasFederated() && options.federated().hasProviders()) {
- for (const auto& string : options.federated().providers()) {
+ if (options->hasFederated() && options->federated()->hasProviders()) {
+ for (const auto& string : options->federated()->providers()) {
KURL url = KURL(NullURL(), string);
if (url.IsValid())
providers.push_back(std::move(url));
@@ -481,16 +497,16 @@ ScriptPromise CredentialsContainer::get(
}
CredentialMediationRequirement requirement;
- if (options.mediation() == "silent") {
+ if (options->mediation() == "silent") {
UseCounter::Count(ExecutionContext::From(script_state),
WebFeature::kCredentialManagerGetMediationSilent);
requirement = CredentialMediationRequirement::kSilent;
- } else if (options.mediation() == "optional") {
+ } else if (options->mediation() == "optional") {
UseCounter::Count(ExecutionContext::From(script_state),
WebFeature::kCredentialManagerGetMediationOptional);
requirement = CredentialMediationRequirement::kOptional;
} else {
- DCHECK_EQ("required", options.mediation());
+ DCHECK_EQ("required", options->mediation());
UseCounter::Count(ExecutionContext::From(script_state),
WebFeature::kCredentialManagerGetMediationRequired);
requirement = CredentialMediationRequirement::kRequired;
@@ -499,7 +515,7 @@ ScriptPromise CredentialsContainer::get(
auto* credential_manager =
CredentialManagerProxy::From(script_state)->CredentialManager();
credential_manager->Get(
- requirement, options.password(), std::move(providers),
+ requirement, options->password(), std::move(providers),
WTF::Bind(&OnGetComplete,
WTF::Passed(std::make_unique<ScopedPromiseResolver>(resolver)),
required_origin_type));
@@ -545,20 +561,20 @@ ScriptPromise CredentialsContainer::store(ScriptState* script_state,
ScriptPromise CredentialsContainer::create(
ScriptState* script_state,
- const CredentialCreationOptions& options,
+ const CredentialCreationOptions* options,
ExceptionState& exception_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
auto required_origin_type =
- options.hasPublicKey() ? RequiredOriginType::kSecureAndSameWithAncestors
- : RequiredOriginType::kSecure;
+ options->hasPublicKey() ? RequiredOriginType::kSecureAndSameWithAncestors
+ : RequiredOriginType::kSecure;
if (!CheckSecurityRequirementsBeforeRequest(resolver, required_origin_type))
return promise;
- if ((options.hasPassword() + options.hasFederated() +
- options.hasPublicKey()) != 1) {
+ if ((options->hasPassword() + options->hasFederated() +
+ options->hasPublicKey()) != 1) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError,
"Only exactly one of 'password', 'federated', and 'publicKey' "
@@ -566,28 +582,28 @@ ScriptPromise CredentialsContainer::create(
return promise;
}
- if (options.hasPassword()) {
+ if (options->hasPassword()) {
resolver->Resolve(
- options.password().IsPasswordCredentialData()
+ options->password().IsPasswordCredentialData()
? PasswordCredential::Create(
- options.password().GetAsPasswordCredentialData(),
+ options->password().GetAsPasswordCredentialData(),
exception_state)
: PasswordCredential::Create(
- options.password().GetAsHTMLFormElement(), exception_state));
- } else if (options.hasFederated()) {
+ options->password().GetAsHTMLFormElement(), exception_state));
+ } else if (options->hasFederated()) {
resolver->Resolve(
- FederatedCredential::Create(options.federated(), exception_state));
+ FederatedCredential::Create(options->federated(), exception_state));
} else {
- DCHECK(options.hasPublicKey());
+ DCHECK(options->hasPublicKey());
UseCounter::Count(resolver->GetExecutionContext(),
WebFeature::kCredentialManagerCreatePublicKeyCredential);
- const String& relying_party_id = options.publicKey().rp().id();
+ const String& relying_party_id = options->publicKey()->rp()->id();
if (!CheckPublicKeySecurityRequirements(resolver, relying_party_id))
return promise;
- if (options.publicKey().hasExtensions()) {
- if (options.publicKey().extensions().hasAppid()) {
+ if (options->publicKey()->hasExtensions()) {
+ if (options->publicKey()->extensions()->hasAppid()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError,
"The 'appid' extension is only valid when requesting an assertion "
@@ -595,7 +611,7 @@ ScriptPromise CredentialsContainer::create(
"legacy FIDO U2F API."));
return promise;
}
- if (options.publicKey().extensions().hasCableAuthentication()) {
+ if (options->publicKey()->extensions()->hasCableAuthentication()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError,
"The 'cableAuthentication' extension is only valid when requesting "
@@ -605,7 +621,7 @@ ScriptPromise CredentialsContainer::create(
}
auto mojo_options =
- MojoPublicKeyCredentialCreationOptions::From(options.publicKey());
+ MojoPublicKeyCredentialCreationOptions::From(options->publicKey());
if (mojo_options) {
if (!mojo_options->relying_party->id) {
mojo_options->relying_party->id = resolver->GetFrame()
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.h b/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.h
index ca4ec1dda90..0c82cc68361 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.h
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container.h
@@ -25,10 +25,10 @@ class MODULES_EXPORT CredentialsContainer final : public ScriptWrappable {
static CredentialsContainer* Create();
// CredentialsContainer.idl
- ScriptPromise get(ScriptState*, const CredentialRequestOptions&);
+ ScriptPromise get(ScriptState*, const CredentialRequestOptions*);
ScriptPromise store(ScriptState*, Credential* = nullptr);
ScriptPromise create(ScriptState*,
- const CredentialCreationOptions&,
+ const CredentialCreationOptions*,
ExceptionState&);
ScriptPromise preventSilentAccess(ScriptState*);
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container_test.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container_test.cc
index 2f86f686c2f..518f8890719 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container_test.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/credentials_container_test.cc
@@ -128,11 +128,13 @@ TEST(CredentialsContainerTest, PendingGetRequest_NoGCCycles) {
CredentialManagerTestingContext context(&mock_credential_manager);
document_observer.Observe(context.GetDocument());
CredentialsContainer::Create()->get(context.GetScriptState(),
- CredentialRequestOptions());
+ CredentialRequestOptions::Create());
mock_credential_manager.WaitForCallToGet();
}
- V8GCController::CollectAllGarbageForTesting(v8::Isolate::GetCurrent());
+ V8GCController::CollectAllGarbageForTesting(
+ v8::Isolate::GetCurrent(),
+ v8::EmbedderHeapTracer::EmbedderStackState::kEmpty);
ThreadState::Current()->CollectAllGarbage();
ASSERT_TRUE(document_observer.WasCollected());
@@ -150,7 +152,7 @@ TEST(CredentialsContainerTest,
auto* proxy = CredentialManagerProxy::From(*context.GetDocument());
auto promise = CredentialsContainer::Create()->get(
- context.GetScriptState(), CredentialRequestOptions());
+ context.GetScriptState(), CredentialRequestOptions::Create());
mock_credential_manager.WaitForCallToGet();
context.GetDocument()->Shutdown();
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.cc
index 8aeba5de70f..f6443fa41ef 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.cc
@@ -14,21 +14,22 @@ constexpr char kFederatedCredentialType[] = "federated";
}
FederatedCredential* FederatedCredential::Create(
- const FederatedCredentialInit& data,
+ const FederatedCredentialInit* data,
ExceptionState& exception_state) {
- if (data.id().IsEmpty())
+ if (data->id().IsEmpty())
exception_state.ThrowTypeError("'id' must not be empty.");
- if (data.provider().IsEmpty())
+ if (data->provider().IsEmpty())
exception_state.ThrowTypeError("'provider' must not be empty.");
- KURL icon_url = ParseStringAsURLOrThrow(data.iconURL(), exception_state);
- KURL provider_url = ParseStringAsURLOrThrow(data.provider(), exception_state);
+ KURL icon_url = ParseStringAsURLOrThrow(data->iconURL(), exception_state);
+ KURL provider_url =
+ ParseStringAsURLOrThrow(data->provider(), exception_state);
if (exception_state.HadException())
return nullptr;
- return new FederatedCredential(
- data.id(), SecurityOrigin::Create(provider_url), data.name(), icon_url);
+ return MakeGarbageCollected<FederatedCredential>(
+ data->id(), SecurityOrigin::Create(provider_url), data->name(), icon_url);
}
FederatedCredential* FederatedCredential::Create(
@@ -36,7 +37,8 @@ FederatedCredential* FederatedCredential::Create(
scoped_refptr<const SecurityOrigin> provider,
const String& name,
const KURL& icon_url) {
- return new FederatedCredential(id, provider, name, icon_url);
+ return MakeGarbageCollected<FederatedCredential>(id, provider, name,
+ icon_url);
}
FederatedCredential::FederatedCredential(
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.h b/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.h
index 6a053862b27..9ef5820db1c 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.h
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/federated_credential.h
@@ -20,7 +20,7 @@ class MODULES_EXPORT FederatedCredential final : public Credential {
DEFINE_WRAPPERTYPEINFO();
public:
- static FederatedCredential* Create(const FederatedCredentialInit&,
+ static FederatedCredential* Create(const FederatedCredentialInit*,
ExceptionState&);
static FederatedCredential* Create(
const String& id,
@@ -28,6 +28,11 @@ class MODULES_EXPORT FederatedCredential final : public Credential {
const String& name,
const KURL& icon_url);
+ FederatedCredential(const String& id,
+ scoped_refptr<const SecurityOrigin> provider,
+ const String& name,
+ const KURL& icon_url);
+
scoped_refptr<const SecurityOrigin> GetProviderAsOrigin() const {
return provider_;
}
@@ -49,11 +54,6 @@ class MODULES_EXPORT FederatedCredential final : public Credential {
}
private:
- FederatedCredential(const String& id,
- scoped_refptr<const SecurityOrigin> provider,
- const String& name,
- const KURL& icon_url);
-
const scoped_refptr<const SecurityOrigin> provider_;
const String name_;
const KURL icon_url_;
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.cc
index 8051c1c017f..2e82e83612c 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.cc
@@ -19,7 +19,7 @@ NavigatorCredentials& NavigatorCredentials::From(Navigator& navigator) {
NavigatorCredentials* supplement =
Supplement<Navigator>::From<NavigatorCredentials>(navigator);
if (!supplement) {
- supplement = new NavigatorCredentials(navigator);
+ supplement = MakeGarbageCollected<NavigatorCredentials>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.h b/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.h
index 0e0920e6fc2..00d267b425c 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.h
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/navigator_credentials.h
@@ -26,10 +26,11 @@ class NavigatorCredentials final
// NavigatorCredentials.idl
static CredentialsContainer* credentials(Navigator&);
+ explicit NavigatorCredentials(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorCredentials(Navigator&);
CredentialsContainer* credentials();
Member<CredentialsContainer> credentials_container_;
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.cc
index e73605633c4..a06539b5e81 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.cc
@@ -20,30 +20,32 @@ constexpr char kPasswordCredentialType[] = "password";
// https://w3c.github.io/webappsec-credential-management/#construct-passwordcredential-data
PasswordCredential* PasswordCredential::Create(
- const PasswordCredentialData& data,
+ const PasswordCredentialData* data,
ExceptionState& exception_state) {
- if (data.id().IsEmpty())
+ if (data->id().IsEmpty())
exception_state.ThrowTypeError("'id' must not be empty.");
- if (data.password().IsEmpty())
+ if (data->password().IsEmpty())
exception_state.ThrowTypeError("'password' must not be empty.");
- KURL icon_url = ParseStringAsURLOrThrow(data.iconURL(), exception_state);
+ KURL icon_url = ParseStringAsURLOrThrow(data->iconURL(), exception_state);
if (exception_state.HadException())
return nullptr;
- return new PasswordCredential(data.id(), data.password(), data.name(),
- icon_url);
+ return MakeGarbageCollected<PasswordCredential>(data->id(), data->password(),
+ data->name(), icon_url);
}
-// https://w3c.github.im/webappsec-credential-management/#construct-passwordcredential-form
+// https://w3c.github.io/webappsec-credential-management/#construct-passwordcredential-form
PasswordCredential* PasswordCredential::Create(
HTMLFormElement* form,
ExceptionState& exception_state) {
// Extract data from the form, then use the extracted |form_data| object's
// value to populate |data|.
- FormData* form_data = FormData::Create(form);
- PasswordCredentialData data;
+ FormData* form_data = FormData::Create(form, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ PasswordCredentialData* data = PasswordCredentialData::Create();
for (ListedElement* submittable_element : form->ListedElements()) {
// The "form data set" contains an entry for a |submittable_element| only if
// it has a non-empty `name` attribute.
@@ -57,19 +59,19 @@ PasswordCredential* PasswordCredential::Create(
Vector<String> autofill_tokens;
ToHTMLElement(submittable_element)
- ->FastGetAttribute(HTMLNames::autocompleteAttr)
+ ->FastGetAttribute(html_names::kAutocompleteAttr)
.GetString()
.DeprecatedLower()
.Split(' ', autofill_tokens);
for (const auto& token : autofill_tokens) {
if (token == "current-password" || token == "new-password") {
- data.setPassword(value.GetAsUSVString());
+ data->setPassword(value.GetAsUSVString());
} else if (token == "photo") {
- data.setIconURL(value.GetAsUSVString());
+ data->setIconURL(value.GetAsUSVString());
} else if (token == "name" || token == "nickname") {
- data.setName(value.GetAsUSVString());
+ data->setName(value.GetAsUSVString());
} else if (token == "username") {
- data.setId(value.GetAsUSVString());
+ data->setId(value.GetAsUSVString());
}
}
}
@@ -82,7 +84,7 @@ PasswordCredential* PasswordCredential::Create(const String& id,
const String& password,
const String& name,
const KURL& icon_url) {
- return new PasswordCredential(id, password, name, icon_url);
+ return MakeGarbageCollected<PasswordCredential>(id, password, name, icon_url);
}
PasswordCredential::PasswordCredential(const String& id,
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.h b/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.h
index d595219f4e6..168609d985b 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.h
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/password_credential.h
@@ -20,7 +20,7 @@ class MODULES_EXPORT PasswordCredential final : public Credential {
DEFINE_WRAPPERTYPEINFO();
public:
- static PasswordCredential* Create(const PasswordCredentialData&,
+ static PasswordCredential* Create(const PasswordCredentialData*,
ExceptionState&);
static PasswordCredential* Create(HTMLFormElement*, ExceptionState&);
static PasswordCredential* Create(const String& id,
@@ -28,6 +28,11 @@ class MODULES_EXPORT PasswordCredential final : public Credential {
const String& name,
const KURL& icon_url);
+ PasswordCredential(const String& id,
+ const String& password,
+ const String& name,
+ const KURL& icon);
+
// Credential:
bool IsPasswordCredential() const override;
@@ -37,11 +42,6 @@ class MODULES_EXPORT PasswordCredential final : public Credential {
const KURL& iconURL() const { return icon_url_; }
private:
- PasswordCredential(const String& id,
- const String& password,
- const String& name,
- const KURL& icon);
-
const String password_;
const String name_;
const KURL icon_url_;
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.cc b/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.cc
index e219eb6b405..42d7ab42587 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.cc
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/modules/credentialmanager/credential_manager_proxy.h"
#include "third_party/blink/renderer/modules/credentialmanager/scoped_promise_resolver.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -28,15 +29,16 @@ PublicKeyCredential* PublicKeyCredential::Create(
const String& id,
DOMArrayBuffer* raw_id,
AuthenticatorResponse* response,
- const AuthenticationExtensionsClientOutputs& extension_outputs) {
- return new PublicKeyCredential(id, raw_id, response, extension_outputs);
+ const AuthenticationExtensionsClientOutputs* extension_outputs) {
+ return MakeGarbageCollected<PublicKeyCredential>(id, raw_id, response,
+ extension_outputs);
}
PublicKeyCredential::PublicKeyCredential(
const String& id,
DOMArrayBuffer* raw_id,
AuthenticatorResponse* response,
- const AuthenticationExtensionsClientOutputs& extension_outputs)
+ const AuthenticationExtensionsClientOutputs* extension_outputs)
: Credential(id, kPublicKeyCredentialType),
raw_id_(raw_id),
response_(response),
@@ -64,14 +66,16 @@ PublicKeyCredential::isUserVerifyingPlatformAuthenticatorAvailable(
return promise;
}
-void PublicKeyCredential::getClientExtensionResults(
- AuthenticationExtensionsClientOutputs& result) const {
- result = extension_outputs_;
+AuthenticationExtensionsClientOutputs*
+PublicKeyCredential::getClientExtensionResults() const {
+ return const_cast<AuthenticationExtensionsClientOutputs*>(
+ extension_outputs_.Get());
}
void PublicKeyCredential::Trace(blink::Visitor* visitor) {
visitor->Trace(raw_id_);
visitor->Trace(response_);
+ visitor->Trace(extension_outputs_);
Credential::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.h b/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.h
index ed3ab41c4db..a358b2cda98 100644
--- a/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.h
+++ b/chromium/third_party/blink/renderer/modules/credentialmanager/public_key_credential.h
@@ -26,28 +26,28 @@ class MODULES_EXPORT PublicKeyCredential final : public Credential {
const String& id,
DOMArrayBuffer* raw_id,
AuthenticatorResponse*,
- const AuthenticationExtensionsClientOutputs&);
+ const AuthenticationExtensionsClientOutputs*);
+
+ explicit PublicKeyCredential(
+ const String& id,
+ DOMArrayBuffer* raw_id,
+ AuthenticatorResponse*,
+ const AuthenticationExtensionsClientOutputs* extension_outputs);
DOMArrayBuffer* rawId() const { return raw_id_.Get(); }
AuthenticatorResponse* response() const { return response_.Get(); }
static ScriptPromise isUserVerifyingPlatformAuthenticatorAvailable(
ScriptState*);
- void getClientExtensionResults(AuthenticationExtensionsClientOutputs&) const;
+ AuthenticationExtensionsClientOutputs* getClientExtensionResults() const;
// Credential:
void Trace(blink::Visitor*) override;
bool IsPublicKeyCredential() const override;
private:
- explicit PublicKeyCredential(
- const String& id,
- DOMArrayBuffer* raw_id,
- AuthenticatorResponse*,
- const AuthenticationExtensionsClientOutputs& extension_outputs);
-
const Member<DOMArrayBuffer> raw_id_;
const Member<AuthenticatorResponse> response_;
- AuthenticationExtensionsClientOutputs extension_outputs_;
+ Member<const AuthenticationExtensionsClientOutputs> extension_outputs_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc b/chromium/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc
index 50a9a6f06dc..91e9cb555e8 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/crypto/crypto_result_impl.cc
@@ -181,12 +181,16 @@ void CryptoResultImpl::CompleteWithJson(const char* utf8_data,
return;
ScriptState* script_state = resolver_->GetScriptState();
+ v8::Isolate* isolate = script_state->GetIsolate();
ScriptState::Scope scope(script_state);
+ // Crashes if longer than v8::String::kMaxLength.
v8::Local<v8::String> json_string =
- V8StringFromUtf8(script_state->GetIsolate(), utf8_data, length);
+ v8::String::NewFromUtf8(isolate, utf8_data, v8::NewStringType::kNormal,
+ length)
+ .ToLocalChecked();
- v8::TryCatch exception_catcher(script_state->GetIsolate());
+ v8::TryCatch exception_catcher(isolate);
v8::Local<v8::Value> json_dictionary;
if (v8::JSON::Parse(script_state->GetContext(), json_string)
.ToLocal(&json_dictionary))
diff --git a/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.cc b/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.cc
index 3d2058d6f33..36dac7d01dc 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.cc
+++ b/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.cc
@@ -44,7 +44,7 @@ DOMWindowCrypto& DOMWindowCrypto::From(LocalDOMWindow& window) {
DOMWindowCrypto* supplement =
Supplement<LocalDOMWindow>::From<DOMWindowCrypto>(window);
if (!supplement) {
- supplement = new DOMWindowCrypto(window);
+ supplement = MakeGarbageCollected<DOMWindowCrypto>(window);
ProvideTo(window, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.h b/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.h
index 9a6d809242d..1aa1433523b 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.h
+++ b/chromium/third_party/blink/renderer/modules/crypto/dom_window_crypto.h
@@ -48,13 +48,14 @@ class DOMWindowCrypto final : public GarbageCollected<DOMWindowCrypto>,
static DOMWindowCrypto& From(LocalDOMWindow&);
static Crypto* crypto(LocalDOMWindow&);
+
+ explicit DOMWindowCrypto(LocalDOMWindow&);
+
Crypto* crypto() const;
void Trace(blink::Visitor*) override;
private:
- explicit DOMWindowCrypto(LocalDOMWindow&);
-
mutable Member<Crypto> crypto_;
};
diff --git a/chromium/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc b/chromium/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc
index ab0355a47e7..d2b2e118d7e 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc
+++ b/chromium/third_party/blink/renderer/modules/crypto/normalize_algorithm.cc
@@ -137,7 +137,7 @@ bool VerifyAlgorithmNameMappings(const AlgorithmNameMapping* begin,
return false;
String str(it->algorithm_name,
static_cast<unsigned>(it->algorithm_name_length));
- if (!str.ContainsOnlyASCII())
+ if (!str.ContainsOnlyASCIIOrEmpty())
return false;
if (str.UpperASCII() != str)
return false;
diff --git a/chromium/third_party/blink/renderer/modules/crypto/subtle_crypto.h b/chromium/third_party/blink/renderer/modules/crypto/subtle_crypto.h
index f5935cfb5bb..87185e6c5bb 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/subtle_crypto.h
+++ b/chromium/third_party/blink/renderer/modules/crypto/subtle_crypto.h
@@ -50,7 +50,9 @@ class SubtleCrypto final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static SubtleCrypto* Create() { return new SubtleCrypto(); }
+ static SubtleCrypto* Create() { return MakeGarbageCollected<SubtleCrypto>(); }
+
+ SubtleCrypto();
ScriptPromise encrypt(ScriptState*,
const AlgorithmIdentifier&,
@@ -111,9 +113,6 @@ class SubtleCrypto final : public ScriptWrappable {
const AlgorithmIdentifier&,
bool extractable,
const Vector<String>&);
-
- private:
- SubtleCrypto();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.cc b/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.cc
index 271f8fff7ab..bec0df05d5a 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.cc
+++ b/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.cc
@@ -45,7 +45,7 @@ WorkerGlobalScopeCrypto& WorkerGlobalScopeCrypto::From(
WorkerGlobalScopeCrypto* supplement =
Supplement<WorkerGlobalScope>::From<WorkerGlobalScopeCrypto>(context);
if (!supplement) {
- supplement = new WorkerGlobalScopeCrypto;
+ supplement = MakeGarbageCollected<WorkerGlobalScopeCrypto>();
ProvideTo(context, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.h b/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.h
index fa768d60546..a18c59312e3 100644
--- a/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.h
+++ b/chromium/third_party/blink/renderer/modules/crypto/worker_global_scope_crypto.h
@@ -52,11 +52,11 @@ class WorkerGlobalScopeCrypto final
static Crypto* crypto(Supplementable<WorkerGlobalScope>&);
Crypto* crypto() const;
+ WorkerGlobalScopeCrypto();
+
void Trace(blink::Visitor*) override;
private:
- WorkerGlobalScopeCrypto();
-
mutable Member<Crypto> crypto_;
};
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/BUILD.gn b/chromium/third_party/blink/renderer/modules/csspaint/BUILD.gn
index 9cd50f82315..fe5e78782e5 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/csspaint/BUILD.gn
@@ -23,7 +23,11 @@ blink_modules_sources("csspaint") {
"paint_worklet_global_scope.h",
"paint_worklet_global_scope_proxy.cc",
"paint_worklet_global_scope_proxy.h",
+ "paint_worklet_messaging_proxy.cc",
+ "paint_worklet_messaging_proxy.h",
"paint_worklet_pending_generator_registry.cc",
"paint_worklet_pending_generator_registry.h",
+ "paint_worklet_proxy_client.cc",
+ "paint_worklet_proxy_client.h",
]
}
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/DEPS b/chromium/third_party/blink/renderer/modules/csspaint/DEPS
index 6281a008ed3..25a8971a4af 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/DEPS
+++ b/chromium/third_party/blink/renderer/modules/csspaint/DEPS
@@ -3,4 +3,5 @@ include_rules = [
"+third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h",
"+third_party/blink/renderer/modules/csspaint",
"+third_party/blink/renderer/modules/modules_export.h",
+ "+third_party/blink/renderer/modules/worklet",
]
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/README.md b/chromium/third_party/blink/renderer/modules/csspaint/README.md
index 26614d50b05..8f5fa0b4ea6 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/README.md
+++ b/chromium/third_party/blink/renderer/modules/csspaint/README.md
@@ -58,5 +58,5 @@ paint.
## Testing
-Tests live [here](../../../LayoutTests/csspaint/).
+Tests live [here](../../../web_tests/csspaint/).
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc
index ffd88e09052..e27b374024f 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.cc
@@ -21,13 +21,12 @@ namespace blink {
namespace {
-FloatSize GetSpecifiedSize(const IntSize& size, float zoom) {
+FloatSize GetSpecifiedSize(const FloatSize& size, float zoom) {
float un_zoom_factor = 1 / zoom;
auto un_zoom_fn = [un_zoom_factor](float a) -> float {
return a * un_zoom_factor;
};
- return FloatSize(un_zoom_fn(static_cast<float>(size.Width())),
- un_zoom_fn(static_cast<float>(size.Height())));
+ return FloatSize(un_zoom_fn(size.Width()), un_zoom_fn(size.Height()));
}
} // namespace
@@ -39,8 +38,8 @@ CSSPaintDefinition* CSSPaintDefinition::Create(
const Vector<CSSPropertyID>& native_invalidation_properties,
const Vector<AtomicString>& custom_invalidation_properties,
const Vector<CSSSyntaxDescriptor>& input_argument_types,
- const PaintRenderingContext2DSettings& context_settings) {
- return new CSSPaintDefinition(
+ const PaintRenderingContext2DSettings* context_settings) {
+ return MakeGarbageCollected<CSSPaintDefinition>(
script_state, constructor, paint, native_invalidation_properties,
custom_invalidation_properties, input_argument_types, context_settings);
}
@@ -52,7 +51,7 @@ CSSPaintDefinition::CSSPaintDefinition(
const Vector<CSSPropertyID>& native_invalidation_properties,
const Vector<AtomicString>& custom_invalidation_properties,
const Vector<CSSSyntaxDescriptor>& input_argument_types,
- const PaintRenderingContext2DSettings& context_settings)
+ const PaintRenderingContext2DSettings* context_settings)
: script_state_(script_state),
constructor_(script_state->GetIsolate(), constructor),
paint_(script_state->GetIsolate(), paint),
@@ -67,7 +66,7 @@ CSSPaintDefinition::~CSSPaintDefinition() = default;
scoped_refptr<Image> CSSPaintDefinition::Paint(
const ImageResourceObserver& client,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector* paint_arguments) {
// TODO: Break dependency on LayoutObject. Passing the Node should work.
const LayoutObject& layout_object = static_cast<const LayoutObject&>(client);
@@ -89,15 +88,16 @@ scoped_refptr<Image> CSSPaintDefinition::Paint(
DCHECK(layout_object.GetNode());
CanvasColorParams color_params;
- if (!context_settings_.alpha()) {
+ if (!context_settings_->alpha()) {
color_params.SetOpacityMode(kOpaque);
}
+ // Do subpixel snapping for the |container_size|.
PaintRenderingContext2D* rendering_context = PaintRenderingContext2D::Create(
- container_size, color_params, context_settings_, zoom);
+ RoundedIntSize(container_size), color_params, context_settings_, zoom);
PaintSize* paint_size = PaintSize::Create(specified_size);
StylePropertyMapReadOnly* style_map =
- new PrepopulatedComputedStylePropertyMap(
+ MakeGarbageCollected<PrepopulatedComputedStylePropertyMap>(
layout_object.GetDocument(), layout_object.StyleRef(),
layout_object.GetNode(), native_invalidation_properties_,
custom_invalidation_properties_);
@@ -131,7 +131,7 @@ scoped_refptr<Image> CSSPaintDefinition::Paint(
}
return PaintGeneratedImage::Create(rendering_context->GetRecord(),
- FloatSize(container_size));
+ container_size);
}
void CSSPaintDefinition::MaybeCreatePaintInstance() {
@@ -157,6 +157,7 @@ void CSSPaintDefinition::Trace(Visitor* visitor) {
visitor->Trace(constructor_.Cast<v8::Value>());
visitor->Trace(paint_.Cast<v8::Value>());
visitor->Trace(instance_);
+ visitor->Trace(context_settings_);
visitor->Trace(script_state_);
}
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.h b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.h
index 4622a7b84a1..c282c561b1b 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_definition.h
@@ -5,15 +5,15 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_CSS_PAINT_DEFINITION_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_CSS_PAINT_DEFINITION_H_
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_settings.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/name_client.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
-#include "third_party/blink/renderer/platform/geometry/int_size.h"
+#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "v8/include/v8.h"
@@ -37,7 +37,16 @@ class MODULES_EXPORT CSSPaintDefinition final
const Vector<CSSPropertyID>&,
const Vector<AtomicString>& custom_invalidation_properties,
const Vector<CSSSyntaxDescriptor>& input_argument_types,
- const PaintRenderingContext2DSettings&);
+ const PaintRenderingContext2DSettings*);
+
+ CSSPaintDefinition(
+ ScriptState*,
+ v8::Local<v8::Function> constructor,
+ v8::Local<v8::Function> paint,
+ const Vector<CSSPropertyID>& native_invalidation_properties,
+ const Vector<AtomicString>& custom_invalidation_properties,
+ const Vector<CSSSyntaxDescriptor>& input_argument_types,
+ const PaintRenderingContext2DSettings*);
virtual ~CSSPaintDefinition();
// Invokes the javascript 'paint' callback on an instance of the javascript
@@ -47,9 +56,9 @@ class MODULES_EXPORT CSSPaintDefinition final
// This may return a nullptr (representing an invalid image) if javascript
// throws an error.
//
- // The |container_size| is the container size with subpixel snapping.
+ // The |container_size| is without subpixel snapping.
scoped_refptr<Image> Paint(const ImageResourceObserver&,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector*);
const Vector<CSSPropertyID>& NativeInvalidationProperties() const {
return native_invalidation_properties_;
@@ -60,13 +69,16 @@ class MODULES_EXPORT CSSPaintDefinition final
const Vector<CSSSyntaxDescriptor>& InputArgumentTypes() const {
return input_argument_types_;
}
- const PaintRenderingContext2DSettings& GetPaintRenderingContext2DSettings()
+ const PaintRenderingContext2DSettings* GetPaintRenderingContext2DSettings()
const {
return context_settings_;
}
ScriptState* GetScriptState() const { return script_state_; }
+ v8::Local<v8::Function> ConstructorForTesting(v8::Isolate* isolate) {
+ return constructor_.NewLocal(isolate);
+ }
v8::Local<v8::Function> PaintFunctionForTesting(v8::Isolate* isolate) {
return paint_.NewLocal(isolate);
}
@@ -77,15 +89,6 @@ class MODULES_EXPORT CSSPaintDefinition final
}
private:
- CSSPaintDefinition(
- ScriptState*,
- v8::Local<v8::Function> constructor,
- v8::Local<v8::Function> paint,
- const Vector<CSSPropertyID>& native_invalidation_properties,
- const Vector<AtomicString>& custom_invalidation_properties,
- const Vector<CSSSyntaxDescriptor>& input_argument_types,
- const PaintRenderingContext2DSettings&);
-
void MaybeCreatePaintInstance();
Member<ScriptState> script_state_;
@@ -105,7 +108,7 @@ class MODULES_EXPORT CSSPaintDefinition final
Vector<AtomicString> custom_invalidation_properties_;
// Input argument types, if applicable.
Vector<CSSSyntaxDescriptor> input_argument_types_;
- PaintRenderingContext2DSettings context_settings_;
+ Member<const PaintRenderingContext2DSettings> context_settings_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc
index 6ede956cba9..b088fc61bf3 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.cc
@@ -22,9 +22,11 @@ CSSPaintImageGenerator* CSSPaintImageGeneratorImpl::Create(
DCHECK(paint_worklet);
CSSPaintImageGeneratorImpl* generator;
if (paint_worklet->GetDocumentDefinitionMap().Contains(name)) {
- generator = new CSSPaintImageGeneratorImpl(paint_worklet, name);
+ generator =
+ MakeGarbageCollected<CSSPaintImageGeneratorImpl>(paint_worklet, name);
} else {
- generator = new CSSPaintImageGeneratorImpl(observer, paint_worklet, name);
+ generator = MakeGarbageCollected<CSSPaintImageGeneratorImpl>(
+ observer, paint_worklet, name);
paint_worklet->AddPendingGenerator(name, generator);
}
@@ -51,7 +53,7 @@ void CSSPaintImageGeneratorImpl::NotifyGeneratorReady() {
scoped_refptr<Image> CSSPaintImageGeneratorImpl::Paint(
const ImageResourceObserver& observer,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector* data) {
return paint_worklet_->Paint(name_, observer, container_size, data);
}
@@ -107,7 +109,7 @@ bool CSSPaintImageGeneratorImpl::HasAlpha() const {
DocumentPaintDefinition* definition;
if (!GetValidDocumentDefinition(definition))
return false;
- return definition->GetPaintRenderingContext2DSettings().alpha();
+ return definition->GetPaintRenderingContext2DSettings()->alpha();
}
const Vector<CSSSyntaxDescriptor>&
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h
index 0ef758380e0..6fa7f01c307 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/scoped_persistent.h"
-#include "third_party/blink/renderer/platform/geometry/int_size.h"
+#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "v8/include/v8.h"
@@ -27,11 +27,14 @@ class MODULES_EXPORT CSSPaintImageGeneratorImpl final
static CSSPaintImageGenerator* Create(const String& name,
const Document&,
Observer*);
+
+ CSSPaintImageGeneratorImpl(Observer*, PaintWorklet*, const String&);
+ CSSPaintImageGeneratorImpl(PaintWorklet*, const String&);
~CSSPaintImageGeneratorImpl() override;
- // The |container_size| is the container size with subpixel snapping.
+ // The |container_size| is without subpixel snapping.
scoped_refptr<Image> Paint(const ImageResourceObserver&,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector*) final;
const Vector<CSSPropertyID>& NativeInvalidationProperties() const final;
const Vector<AtomicString>& CustomInvalidationProperties() const final;
@@ -52,9 +55,6 @@ class MODULES_EXPORT CSSPaintImageGeneratorImpl final
void Trace(blink::Visitor*) override;
private:
- CSSPaintImageGeneratorImpl(Observer*, PaintWorklet*, const String&);
- CSSPaintImageGeneratorImpl(PaintWorklet*, const String&);
-
bool HasDocumentDefinition() const;
// This function first checks whether the document definition with |name_|
// exists or not. If it does exist, the function fetches the document
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc b/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc
index 89395f1aaf6..ebddd9afe4c 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.cc
@@ -15,8 +15,8 @@ DocumentPaintDefinition::~DocumentPaintDefinition() = default;
bool DocumentPaintDefinition::RegisterAdditionalPaintDefinition(
const CSSPaintDefinition& other) {
- if (GetPaintRenderingContext2DSettings().alpha() !=
- other.GetPaintRenderingContext2DSettings().alpha() ||
+ if (GetPaintRenderingContext2DSettings()->alpha() !=
+ other.GetPaintRenderingContext2DSettings()->alpha() ||
NativeInvalidationProperties() != other.NativeInvalidationProperties() ||
CustomInvalidationProperties() != other.CustomInvalidationProperties() ||
InputArgumentTypes() != other.InputArgumentTypes())
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.h b/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.h
index 3ff2730611e..894b52e3a4c 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/document_paint_definition.h
@@ -38,7 +38,8 @@ class DocumentPaintDefinition final
const Vector<CSSSyntaxDescriptor>& InputArgumentTypes() const {
return paint_definition_->InputArgumentTypes();
}
- PaintRenderingContext2DSettings GetPaintRenderingContext2DSettings() const {
+ const PaintRenderingContext2DSettings* GetPaintRenderingContext2DSettings()
+ const {
return paint_definition_->GetPaintRenderingContext2DSettings();
}
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.cc
index 085161d5550..890529308fc 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.cc
@@ -12,7 +12,7 @@ namespace blink {
PaintRenderingContext2D::PaintRenderingContext2D(
const IntSize& container_size,
const CanvasColorParams& color_params,
- const PaintRenderingContext2DSettings& context_settings,
+ const PaintRenderingContext2DSettings* context_settings,
float zoom)
: container_size_(container_size),
color_params_(color_params),
@@ -23,8 +23,8 @@ PaintRenderingContext2D::PaintRenderingContext2D(
clip_antialiasing_ = kAntiAliased;
ModifiableState().SetShouldAntialias(true);
- Canvas()->clear(context_settings.alpha() ? SK_ColorTRANSPARENT
- : SK_ColorBLACK);
+ Canvas()->clear(context_settings->alpha() ? SK_ColorTRANSPARENT
+ : SK_ColorBLACK);
did_record_draw_commands_in_paint_recorder_ = true;
Canvas()->scale(zoom, zoom);
}
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.h b/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.h
index a23889682d7..ddfbde175a4 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.h
@@ -28,13 +28,19 @@ class MODULES_EXPORT PaintRenderingContext2D : public ScriptWrappable,
static PaintRenderingContext2D* Create(
const IntSize& container_size,
const CanvasColorParams& color_params,
- const PaintRenderingContext2DSettings& context_settings,
+ const PaintRenderingContext2DSettings* context_settings,
float zoom) {
- return new PaintRenderingContext2D(container_size, color_params,
- context_settings, zoom);
+ return MakeGarbageCollected<PaintRenderingContext2D>(
+ container_size, color_params, context_settings, zoom);
}
+ PaintRenderingContext2D(const IntSize& container_size,
+ const CanvasColorParams&,
+ const PaintRenderingContext2DSettings*,
+ float zoom);
+
void Trace(blink::Visitor* visitor) override {
+ visitor->Trace(context_settings_);
ScriptWrappable::Trace(visitor);
BaseRenderingContext2D::Trace(visitor);
}
@@ -73,7 +79,7 @@ class MODULES_EXPORT PaintRenderingContext2D : public ScriptWrappable,
void ValidateStateStack() const final;
- bool HasAlpha() const final { return context_settings_.alpha(); }
+ bool HasAlpha() const final { return context_settings_->alpha(); }
// PaintRenderingContext2D cannot lose it's context.
bool isContextLost() const final { return false; }
@@ -90,11 +96,6 @@ class MODULES_EXPORT PaintRenderingContext2D : public ScriptWrappable,
void WillOverwriteCanvas() override;
private:
- PaintRenderingContext2D(const IntSize& container_size,
- const CanvasColorParams&,
- const PaintRenderingContext2DSettings&,
- float zoom);
-
void InitializePaintRecorder();
cc::PaintCanvas* Canvas() const;
@@ -102,7 +103,7 @@ class MODULES_EXPORT PaintRenderingContext2D : public ScriptWrappable,
sk_sp<PaintRecord> previous_frame_;
IntSize container_size_;
const CanvasColorParams& color_params_;
- PaintRenderingContext2DSettings context_settings_;
+ Member<const PaintRenderingContext2DSettings> context_settings_;
bool did_record_draw_commands_in_paint_recorder_;
float effective_zoom_;
};
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_test.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_test.cc
index 0bddc0fd094..116fd8262c7 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_test.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d_test.cc
@@ -21,8 +21,9 @@ class PaintRenderingContext2DTest : public testing::Test {
};
void PaintRenderingContext2DTest::SetUp() {
- PaintRenderingContext2DSettings context_settings;
- context_settings.setAlpha(false);
+ PaintRenderingContext2DSettings* context_settings =
+ PaintRenderingContext2DSettings::Create();
+ context_settings->setAlpha(false);
ctx_ = PaintRenderingContext2D::Create(
IntSize(kWidth, kHeight), CanvasColorParams(), context_settings, kZoom);
}
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_size.h b/chromium/third_party/blink/renderer/modules/csspaint/paint_size.h
index 40f9c4689d7..283cb805838 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_size.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_size.h
@@ -16,15 +16,17 @@ class PaintSize : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static PaintSize* Create(FloatSize size) { return new PaintSize(size); }
+ static PaintSize* Create(FloatSize size) {
+ return MakeGarbageCollected<PaintSize>(size);
+ }
+
+ explicit PaintSize(FloatSize size) : size_(size) {}
~PaintSize() override = default;
float width() const { return size_.Width(); }
float height() const { return size_.Height(); }
private:
- explicit PaintSize(FloatSize size) : size_(size) {}
-
FloatSize size_;
};
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.cc
index b668a6f2623..62ef724e5d4 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.cc
@@ -11,11 +11,13 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h"
#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h"
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.h"
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
namespace blink {
-const size_t PaintWorklet::kNumGlobalScopes = 2u;
+const wtf_size_t PaintWorklet::kNumGlobalScopes = 2u;
const size_t kMaxPaintCountToSwitch = 30u;
DocumentPaintDefinition* const kInvalidDocumentPaintDefinition = nullptr;
@@ -32,7 +34,7 @@ PaintWorklet* PaintWorklet::From(LocalDOMWindow& window) {
// static
PaintWorklet* PaintWorklet::Create(LocalFrame* frame) {
- return new PaintWorklet(frame);
+ return MakeGarbageCollected<PaintWorklet>(frame);
}
PaintWorklet::PaintWorklet(LocalFrame* frame)
@@ -52,7 +54,7 @@ void PaintWorklet::AddPendingGenerator(const String& name,
// calls (rand(kMaxPaintCountToSwitch)).
// This approach ensures non-deterministic of global scope selecting, and that
// there is a max of one switching within one frame.
-size_t PaintWorklet::SelectGlobalScope() {
+wtf_size_t PaintWorklet::SelectGlobalScope() {
size_t current_paint_frame_count = GetFrame()->View()->PaintFrameCount();
// Whether a new frame starts or not.
bool frame_changed = current_paint_frame_count != active_frame_count_;
@@ -82,14 +84,17 @@ int PaintWorklet::GetPaintsBeforeSwitching() {
return base::RandInt(0, kMaxPaintCountToSwitch - 1);
}
-size_t PaintWorklet::SelectNewGlobalScope() {
- return static_cast<size_t>(base::RandGenerator(kNumGlobalScopes));
+wtf_size_t PaintWorklet::SelectNewGlobalScope() {
+ return static_cast<wtf_size_t>(base::RandGenerator(kNumGlobalScopes));
}
scoped_refptr<Image> PaintWorklet::Paint(const String& name,
const ImageResourceObserver& observer,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector* data) {
+ if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled())
+ return nullptr;
+
if (!document_definition_map_.Contains(name))
return nullptr;
@@ -123,9 +128,20 @@ bool PaintWorklet::NeedsToCreateGlobalScope() {
WorkletGlobalScopeProxy* PaintWorklet::CreateGlobalScope() {
DCHECK(NeedsToCreateGlobalScope());
- return new PaintWorkletGlobalScopeProxy(
- To<Document>(GetExecutionContext())->GetFrame(), ModuleResponsesMap(),
- pending_generator_registry_, GetNumberOfGlobalScopes() + 1);
+ if (!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) {
+ return MakeGarbageCollected<PaintWorkletGlobalScopeProxy>(
+ To<Document>(GetExecutionContext())->GetFrame(), ModuleResponsesMap(),
+ pending_generator_registry_, GetNumberOfGlobalScopes() + 1);
+ }
+
+ PaintWorkletProxyClient* proxy_client = PaintWorkletProxyClient::Create();
+ WorkerClients* worker_clients = WorkerClients::Create();
+ ProvidePaintWorkletProxyClientTo(worker_clients, proxy_client);
+
+ PaintWorkletMessagingProxy* proxy =
+ new PaintWorkletMessagingProxy(GetExecutionContext());
+ proxy->Initialize(worker_clients, ModuleResponsesMap());
+ return proxy;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.h b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.h
index aa6459aa17a..791459e8440 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet.h
@@ -29,17 +29,18 @@ class MODULES_EXPORT PaintWorklet : public Worklet,
static const char kSupplementName[];
// At this moment, paint worklet allows at most two global scopes at any time.
- static const size_t kNumGlobalScopes;
+ static const wtf_size_t kNumGlobalScopes;
static PaintWorklet* From(LocalDOMWindow&);
static PaintWorklet* Create(LocalFrame*);
+ explicit PaintWorklet(LocalFrame*);
~PaintWorklet() override;
void AddPendingGenerator(const String& name, CSSPaintImageGeneratorImpl*);
- // The |container_size| is the container size with subpixel snapping.
+ // The |container_size| is without subpixel snapping.
scoped_refptr<Image> Paint(const String& name,
const ImageResourceObserver&,
- const IntSize& container_size,
+ const FloatSize& container_size,
const CSSStyleValueVector*);
typedef HeapHashMap<String, Member<DocumentPaintDefinition>>
@@ -50,12 +51,10 @@ class MODULES_EXPORT PaintWorklet : public Worklet,
void Trace(blink::Visitor*) override;
protected:
- explicit PaintWorklet(LocalFrame*);
-
// Since paint worklet has more than one global scope, we MUST override this
// function and provide our own selection logic.
- size_t SelectGlobalScope() final;
- size_t GetActiveGlobalScopeForTesting() { return active_global_scope_; }
+ wtf_size_t SelectGlobalScope() final;
+ wtf_size_t GetActiveGlobalScopeForTesting() { return active_global_scope_; }
private:
friend class PaintWorkletTest;
@@ -68,7 +67,7 @@ class MODULES_EXPORT PaintWorklet : public Worklet,
// global scopes.
virtual int GetPaintsBeforeSwitching();
// This function calculates the next global scope to switch to.
- virtual size_t SelectNewGlobalScope();
+ virtual wtf_size_t SelectNewGlobalScope();
Member<PaintWorkletPendingGeneratorRegistry> pending_generator_registry_;
DocumentDefinitionMap document_definition_map_;
@@ -77,7 +76,7 @@ class MODULES_EXPORT PaintWorklet : public Worklet,
// tell when we begin painting on a new frame.
size_t active_frame_count_ = 0u;
// The current global scope being used for painting.
- size_t active_global_scope_ = 0u;
+ wtf_size_t active_global_scope_ = 0u;
// The number of paint calls remaining before Paint will select a new global
// scope. SelectGlobalScope resets this at the beginning of each frame.
int paints_before_switching_global_scope_;
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc
index 7e2bbcf3193..fd6e0bad961 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.cc
@@ -9,18 +9,20 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_object_parser.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_paint_rendering_context_2d_settings.h"
+#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
-#include "third_party/blink/renderer/core/css_property_names.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h"
#include "third_party/blink/renderer/modules/csspaint/css_paint_image_generator_impl.h"
#include "third_party/blink/renderer/modules/csspaint/css_paint_worklet.h"
#include "third_party/blink/renderer/modules/csspaint/paint_worklet.h"
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
namespace blink {
@@ -63,10 +65,9 @@ bool ParseInputArguments(v8::Local<v8::Context> context,
return true;
}
-bool ParsePaintRenderingContext2DSettings(
+PaintRenderingContext2DSettings* ParsePaintRenderingContext2DSettings(
v8::Local<v8::Context> context,
v8::Local<v8::Function> constructor,
- PaintRenderingContext2DSettings* context_settings,
ExceptionState* exception_state) {
v8::Isolate* isolate = context->GetIsolate();
v8::TryCatch block(isolate);
@@ -75,13 +76,14 @@ bool ParsePaintRenderingContext2DSettings(
if (!constructor->Get(context, V8AtomicString(isolate, "contextOptions"))
.ToLocal(&context_settings_value)) {
exception_state->RethrowV8Exception(block.Exception());
- return false;
+ return nullptr;
}
- V8PaintRenderingContext2DSettings::ToImpl(
- isolate, context_settings_value, *context_settings, *exception_state);
+ auto* context_settings =
+ NativeValueTraits<PaintRenderingContext2DSettings>::NativeValue(
+ isolate, context_settings_value, *exception_state);
if (exception_state->HadException())
- return false;
- return true;
+ return nullptr;
+ return context_settings;
}
} // namespace
@@ -93,9 +95,10 @@ PaintWorkletGlobalScope* PaintWorkletGlobalScope::Create(
WorkerReportingProxy& reporting_proxy,
PaintWorkletPendingGeneratorRegistry* pending_generator_registry,
size_t global_scope_number) {
- auto* global_scope =
- new PaintWorkletGlobalScope(frame, std::move(creation_params),
- reporting_proxy, pending_generator_registry);
+ DCHECK(!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled());
+ auto* global_scope = MakeGarbageCollected<PaintWorkletGlobalScope>(
+ frame, std::move(creation_params), reporting_proxy,
+ pending_generator_registry);
String context_name("PaintWorklet #");
context_name.append(String::Number(global_scope_number));
global_scope->ScriptController()->InitializeContextIfNeeded(context_name,
@@ -106,6 +109,15 @@ PaintWorkletGlobalScope* PaintWorkletGlobalScope::Create(
return global_scope;
}
+// static
+PaintWorkletGlobalScope* PaintWorkletGlobalScope::Create(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params,
+ WorkerThread* thread) {
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled());
+ return MakeGarbageCollected<PaintWorkletGlobalScope>(
+ std::move(creation_params), thread);
+}
+
PaintWorkletGlobalScope::PaintWorkletGlobalScope(
LocalFrame* frame,
std::unique_ptr<GlobalScopeCreationParams> creation_params,
@@ -114,12 +126,26 @@ PaintWorkletGlobalScope::PaintWorkletGlobalScope(
: WorkletGlobalScope(std::move(creation_params), reporting_proxy, frame),
pending_generator_registry_(pending_generator_registry) {}
+PaintWorkletGlobalScope::PaintWorkletGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params,
+ WorkerThread* thread)
+ : WorkletGlobalScope(std::move(creation_params),
+ thread->GetWorkerReportingProxy(),
+ thread) {}
+
PaintWorkletGlobalScope::~PaintWorkletGlobalScope() = default;
void PaintWorkletGlobalScope::Dispose() {
- MainThreadDebugger::Instance()->ContextWillBeDestroyed(
- ScriptController()->GetScriptState());
- pending_generator_registry_ = nullptr;
+ DCHECK(IsContextThread());
+ if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) {
+ if (PaintWorkletProxyClient* proxy_client =
+ PaintWorkletProxyClient::From(Clients()))
+ proxy_client->Dispose();
+ } else {
+ MainThreadDebugger::Instance()->ContextWillBeDestroyed(
+ ScriptController()->GetScriptState());
+ pending_generator_registry_ = nullptr;
+ }
WorkletGlobalScope::Dispose();
}
@@ -127,6 +153,8 @@ void PaintWorkletGlobalScope::registerPaint(
const String& name,
const ScriptValue& constructor_value,
ExceptionState& exception_state) {
+ RegisterWithProxyClientIfNeeded();
+
if (name.IsEmpty()) {
exception_state.ThrowTypeError("The empty string is not a valid name.");
return;
@@ -161,9 +189,10 @@ void PaintWorkletGlobalScope::registerPaint(
&exception_state))
return;
- PaintRenderingContext2DSettings context_settings;
- if (!ParsePaintRenderingContext2DSettings(
- context, constructor, &context_settings, &exception_state))
+ PaintRenderingContext2DSettings* context_settings =
+ ParsePaintRenderingContext2DSettings(context, constructor,
+ &exception_state);
+ if (!context_settings)
return;
v8::Local<v8::Object> prototype;
@@ -184,34 +213,36 @@ void PaintWorkletGlobalScope::registerPaint(
// TODO(xidachen): the following steps should be done with a postTask when
// we move PaintWorklet off main thread.
- PaintWorklet* paint_worklet =
- PaintWorklet::From(*GetFrame()->GetDocument()->domWindow());
- PaintWorklet::DocumentDefinitionMap& document_definition_map =
- paint_worklet->GetDocumentDefinitionMap();
- if (document_definition_map.Contains(name)) {
- DocumentPaintDefinition* existing_document_definition =
- document_definition_map.at(name);
- if (existing_document_definition == kInvalidDocumentPaintDefinition)
- return;
- if (!existing_document_definition->RegisterAdditionalPaintDefinition(
- *definition)) {
- document_definition_map.Set(name, kInvalidDocumentPaintDefinition);
- exception_state.ThrowDOMException(
- DOMExceptionCode::kNotSupportedError,
- "A class with name:'" + name +
- "' was registered with a different definition.");
- return;
+ if (!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) {
+ PaintWorklet* paint_worklet =
+ PaintWorklet::From(*GetFrame()->GetDocument()->domWindow());
+ PaintWorklet::DocumentDefinitionMap& document_definition_map =
+ paint_worklet->GetDocumentDefinitionMap();
+ if (document_definition_map.Contains(name)) {
+ DocumentPaintDefinition* existing_document_definition =
+ document_definition_map.at(name);
+ if (existing_document_definition == kInvalidDocumentPaintDefinition)
+ return;
+ if (!existing_document_definition->RegisterAdditionalPaintDefinition(
+ *definition)) {
+ document_definition_map.Set(name, kInvalidDocumentPaintDefinition);
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "A class with name:'" + name +
+ "' was registered with a different definition.");
+ return;
+ }
+ // Notify the generator ready only when register paint is called the
+ // second time with the same |name| (i.e. there is already a document
+ // definition associated with |name|
+ if (existing_document_definition->GetRegisteredDefinitionCount() ==
+ PaintWorklet::kNumGlobalScopes)
+ pending_generator_registry_->NotifyGeneratorReady(name);
+ } else {
+ DocumentPaintDefinition* document_definition =
+ MakeGarbageCollected<DocumentPaintDefinition>(definition);
+ document_definition_map.Set(name, document_definition);
}
- // Notify the generator ready only when register paint is called the second
- // time with the same |name| (i.e. there is already a document definition
- // associated with |name|
- if (existing_document_definition->GetRegisteredDefinitionCount() ==
- PaintWorklet::kNumGlobalScopes)
- pending_generator_registry_->NotifyGeneratorReady(name);
- } else {
- DocumentPaintDefinition* document_definition =
- new DocumentPaintDefinition(definition);
- document_definition_map.Set(name, document_definition);
}
}
@@ -221,7 +252,11 @@ CSSPaintDefinition* PaintWorkletGlobalScope::FindDefinition(
}
double PaintWorkletGlobalScope::devicePixelRatio() const {
- return GetFrame()->DevicePixelRatio();
+ // TODO(smcgruer): Implement |devicePixelRatio| for worklet-thread bound
+ // PaintWorkletGlobalScope.
+ return RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()
+ ? 1.0
+ : GetFrame()->DevicePixelRatio();
}
void PaintWorkletGlobalScope::Trace(blink::Visitor* visitor) {
@@ -230,4 +265,15 @@ void PaintWorkletGlobalScope::Trace(blink::Visitor* visitor) {
WorkletGlobalScope::Trace(visitor);
}
+void PaintWorkletGlobalScope::RegisterWithProxyClientIfNeeded() {
+ if (registered_ || !RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled())
+ return;
+
+ if (PaintWorkletProxyClient* proxy_client =
+ PaintWorkletProxyClient::From(Clients())) {
+ proxy_client->SetGlobalScope(this);
+ registered_ = true;
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h
index 6bd200d8dde..958840fc5a2 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -23,12 +24,25 @@ class MODULES_EXPORT PaintWorkletGlobalScope final : public WorkletGlobalScope {
USING_GARBAGE_COLLECTED_MIXIN(PaintWorkletGlobalScope);
public:
+ // Creates a main-thread bound PaintWorkletGlobalScope.
static PaintWorkletGlobalScope* Create(
LocalFrame*,
std::unique_ptr<GlobalScopeCreationParams>,
WorkerReportingProxy&,
PaintWorkletPendingGeneratorRegistry*,
size_t global_scope_number);
+
+ // Creates an worklet-thread bound PaintWorkletGlobalScope.
+ static PaintWorkletGlobalScope* Create(
+ std::unique_ptr<GlobalScopeCreationParams>,
+ WorkerThread*);
+
+ PaintWorkletGlobalScope(LocalFrame*,
+ std::unique_ptr<GlobalScopeCreationParams>,
+ WorkerReportingProxy&,
+ PaintWorkletPendingGeneratorRegistry*);
+ PaintWorkletGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
+ WorkerThread*);
~PaintWorkletGlobalScope() override;
void Dispose() final;
@@ -43,10 +57,9 @@ class MODULES_EXPORT PaintWorkletGlobalScope final : public WorkletGlobalScope {
void Trace(blink::Visitor*) override;
private:
- PaintWorkletGlobalScope(LocalFrame*,
- std::unique_ptr<GlobalScopeCreationParams>,
- WorkerReportingProxy&,
- PaintWorkletPendingGeneratorRegistry*);
+ // Registers the global scope with a proxy client, if not already done. Only
+ // used for worklet-thread bound PaintWorkletGlobalScopes.
+ void RegisterWithProxyClientIfNeeded();
// The implementation of the "paint definition" concept:
// https://drafts.css-houdini.org/css-paint-api/#paint-definition
@@ -54,14 +67,24 @@ class MODULES_EXPORT PaintWorkletGlobalScope final : public WorkletGlobalScope {
DefinitionMap;
DefinitionMap paint_definitions_;
- Member<PaintWorkletPendingGeneratorRegistry> pending_generator_registry_;
+ // Only used for main-thread bound PaintWorkletGlobalScopes.
+ // TODO(smcgruer): Move elsewhere for worklet-thread bound
+ // PaintWorkletGlobalScope.
+ Member<PaintWorkletPendingGeneratorRegistry> pending_generator_registry_ =
+ nullptr;
+
+ // Tracks whether this PaintWorkletGlobalScope has been registered with a
+ // PaintWorkletProxyClient. Only used in worklet-thread bound
+ // PaintWorkletGlobalScopes.
+ bool registered_ = false;
};
-DEFINE_TYPE_CASTS(PaintWorkletGlobalScope,
- ExecutionContext,
- context,
- context->IsPaintWorkletGlobalScope(),
- context.IsPaintWorkletGlobalScope());
+template <>
+struct DowncastTraits<PaintWorkletGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsPaintWorkletGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.cc
index d4c9ec466ab..833e8272875 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_proxy.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -36,13 +37,12 @@ PaintWorkletGlobalScopeProxy::PaintWorkletGlobalScopeProxy(
std::make_unique<MainThreadWorkletReportingProxy>(document);
WorkerClients* worker_clients = WorkerClients::Create();
- ProvideWorkerFetchContextToWorker(
- worker_clients, frame->Client()->CreateWorkerFetchContext());
ProvideContentSettingsClientToWorker(
worker_clients, frame->Client()->CreateWorkerContentSettingsClient());
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ frame->Client()->CreateWorkerFetchContext(),
document->GetContentSecurityPolicy()->Headers(),
document->GetReferrerPolicy(), document->GetSecurityOrigin(),
document->IsSecureContext(), document->GetHttpsState(), worker_clients,
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc
new file mode 100644
index 00000000000..8efc3188a48
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope_test.cc
@@ -0,0 +1,183 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
+#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
+#include "third_party/blink/renderer/core/script/script.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
+#include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h"
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h"
+#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
+
+namespace blink {
+namespace {
+
+class MockPaintWorkletProxyClient : public PaintWorkletProxyClient {
+ public:
+ MockPaintWorkletProxyClient()
+ : PaintWorkletProxyClient(), did_set_global_scope_(false) {}
+ void SetGlobalScope(WorkletGlobalScope*) override {
+ did_set_global_scope_ = true;
+ }
+ bool did_set_global_scope() { return did_set_global_scope_; }
+
+ private:
+ bool did_set_global_scope_;
+};
+
+} // namespace
+
+// TODO(smcgruer): Extract a common base class between this and
+// AnimationWorkletGlobalScope.
+class PaintWorkletGlobalScopeTest : public PageTestBase {
+ public:
+ PaintWorkletGlobalScopeTest() = default;
+
+ void SetUp() override {
+ PageTestBase::SetUp(IntSize());
+ Document* document = &GetDocument();
+ document->SetURL(KURL("https://example.com/"));
+ document->UpdateSecurityOrigin(SecurityOrigin::Create(document->Url()));
+ reporting_proxy_ = std::make_unique<WorkerReportingProxy>();
+ }
+
+ std::unique_ptr<AnimationAndPaintWorkletThread>
+ CreateAnimationAndPaintWorkletThread(PaintWorkletProxyClient* proxy_client) {
+ std::unique_ptr<AnimationAndPaintWorkletThread> thread =
+ AnimationAndPaintWorkletThread::CreateForPaintWorklet(
+ *reporting_proxy_);
+
+ WorkerClients* clients = WorkerClients::Create();
+ if (proxy_client)
+ ProvidePaintWorkletProxyClientTo(clients, proxy_client);
+
+ Document* document = &GetDocument();
+ thread->Start(
+ std::make_unique<GlobalScopeCreationParams>(
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */, Vector<CSPHeaderAndType>(),
+ document->GetReferrerPolicy(), document->GetSecurityOrigin(),
+ document->IsSecureContext(), document->GetHttpsState(), clients,
+ document->AddressSpace(),
+ OriginTrialContext::GetTokens(document).get(),
+ base::UnguessableToken::Create(), nullptr /* worker_settings */,
+ kV8CacheOptionsDefault, new WorkletModuleResponsesMap),
+ base::nullopt, std::make_unique<WorkerDevToolsParams>(),
+ ParentExecutionContextTaskRunners::Create());
+ return thread;
+ }
+
+ using TestCalback = void (PaintWorkletGlobalScopeTest::*)(WorkerThread*,
+ WaitableEvent*);
+
+ // Create a new paint worklet and run the callback task on it. Terminate the
+ // worklet once the task completion is signaled.
+ void RunTestOnWorkletThread(TestCalback callback) {
+ std::unique_ptr<WorkerThread> worklet =
+ CreateAnimationAndPaintWorkletThread(nullptr);
+ WaitableEvent waitable_event;
+ PostCrossThreadTask(
+ *worklet->GetTaskRunner(TaskType::kInternalTest), FROM_HERE,
+ CrossThreadBind(callback, CrossThreadUnretained(this),
+ CrossThreadUnretained(worklet.get()),
+ CrossThreadUnretained(&waitable_event)));
+ waitable_event.Wait();
+
+ worklet->Terminate();
+ worklet->WaitForShutdownForTesting();
+ }
+
+ void RunScriptOnWorklet(String source_code,
+ WorkerThread* thread,
+ WaitableEvent* waitable_event) {
+ ASSERT_TRUE(thread->IsCurrentThread());
+ auto* global_scope = To<PaintWorkletGlobalScope>(thread->GlobalScope());
+ ScriptState* script_state =
+ global_scope->ScriptController()->GetScriptState();
+ ASSERT_TRUE(script_state);
+ v8::Isolate* isolate = script_state->GetIsolate();
+ ASSERT_TRUE(isolate);
+ ScriptState::Scope scope(script_state);
+ ASSERT_TRUE(EvaluateScriptModule(global_scope, source_code));
+ waitable_event->Signal();
+ }
+
+ void RunBasicParsingTestOnWorklet(WorkerThread* thread,
+ WaitableEvent* waitable_event) {
+ ASSERT_TRUE(thread->IsCurrentThread());
+ auto* global_scope = To<PaintWorkletGlobalScope>(thread->GlobalScope());
+ ScriptState* script_state =
+ global_scope->ScriptController()->GetScriptState();
+ ASSERT_TRUE(script_state);
+ v8::Isolate* isolate = script_state->GetIsolate();
+ ASSERT_TRUE(isolate);
+
+ ScriptState::Scope scope(script_state);
+
+ {
+ // registerPaint() with a valid class definition should define an
+ // animator.
+ String source_code =
+ R"JS(
+ registerPaint('test', class {
+ constructor () {}
+ paint (ctx, size) {}
+ });
+ )JS";
+ ASSERT_TRUE(EvaluateScriptModule(global_scope, source_code));
+
+ CSSPaintDefinition* definition = global_scope->FindDefinition("test");
+ ASSERT_TRUE(definition);
+
+ EXPECT_TRUE(definition->ConstructorForTesting(isolate)->IsFunction());
+ EXPECT_TRUE(definition->PaintFunctionForTesting(isolate)->IsFunction());
+ }
+
+ {
+ // registerPaint() with a null class definition should fail to define
+ // an painter.
+ String source_code = "registerPaint('null', null);";
+ ASSERT_FALSE(EvaluateScriptModule(global_scope, source_code));
+ EXPECT_FALSE(global_scope->FindDefinition("null"));
+ }
+
+ EXPECT_FALSE(global_scope->FindDefinition("non-existent"));
+
+ waitable_event->Signal();
+ }
+
+ private:
+ bool EvaluateScriptModule(PaintWorkletGlobalScope* global_scope,
+ const String& source_code) {
+ ScriptState* script_state =
+ global_scope->ScriptController()->GetScriptState();
+ EXPECT_TRUE(script_state);
+ const KURL js_url("https://example.com/worklet.js");
+ ScriptModule module = ScriptModule::Compile(
+ script_state->GetIsolate(), source_code, js_url, js_url,
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
+ EXPECT_FALSE(module.IsNull());
+ ScriptValue exception = module.Instantiate(script_state);
+ EXPECT_TRUE(exception.IsEmpty());
+ ScriptValue value = module.Evaluate(script_state);
+ return value.IsEmpty();
+ }
+
+ std::unique_ptr<WorkerReportingProxy> reporting_proxy_;
+};
+
+TEST_F(PaintWorkletGlobalScopeTest, BasicParsing) {
+ ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
+ RunTestOnWorkletThread(
+ &PaintWorkletGlobalScopeTest::RunBasicParsingTestOnWorklet);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.cc
new file mode 100644
index 00000000000..17c2f4c6907
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.cc
@@ -0,0 +1,27 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.h"
+
+#include "third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h"
+#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
+
+namespace blink {
+
+PaintWorkletMessagingProxy::PaintWorkletMessagingProxy(
+ ExecutionContext* execution_context)
+ : ThreadedWorkletMessagingProxy(execution_context) {}
+
+void PaintWorkletMessagingProxy::Trace(blink::Visitor* visitor) {
+ ThreadedWorkletMessagingProxy::Trace(visitor);
+}
+
+PaintWorkletMessagingProxy::~PaintWorkletMessagingProxy() = default;
+
+std::unique_ptr<WorkerThread> PaintWorkletMessagingProxy::CreateWorkerThread() {
+ return AnimationAndPaintWorkletThread::CreateForPaintWorklet(
+ WorkletObjectProxy());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.h b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.h
new file mode 100644
index 00000000000..7ffb584f2d5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_messaging_proxy.h
@@ -0,0 +1,34 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_WORKLET_MESSAGING_PROXY_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_WORKLET_MESSAGING_PROXY_H_
+
+#include <memory>
+#include "third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h"
+
+namespace blink {
+
+class ExecutionContext;
+class WorkerThread;
+
+// Acts as a proxy for worklet-thread bound PaintWorkletGlobalScopes. The logic
+// to actually proxy an off thread global scope is implemented in the parent.
+// The main contribution of this class is to create an appropriate worklet
+// thread type as part of the the worklet initialization process.
+class PaintWorkletMessagingProxy final : public ThreadedWorkletMessagingProxy {
+ public:
+ explicit PaintWorkletMessagingProxy(ExecutionContext*);
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ ~PaintWorkletMessagingProxy() override;
+
+ std::unique_ptr<WorkerThread> CreateWorkerThread() override;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_OFF_THREAD_PAINT_WORKLET_MESSAGING_PROXY_H_
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.cc
index 6aa143838b6..0243f55a685 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_pending_generator_registry.cc
@@ -26,7 +26,7 @@ void PaintWorkletPendingGeneratorRegistry::AddPendingGenerator(
Member<GeneratorHashSet>& set =
pending_generators_.insert(name, nullptr).stored_value->value;
if (!set)
- set = new GeneratorHashSet;
+ set = MakeGarbageCollected<GeneratorHashSet>();
set->insert(generator);
}
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc
new file mode 100644
index 00000000000..a46565a9c5c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.cc
@@ -0,0 +1,69 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h"
+
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/frame/web_frame_widget_base.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/modules/csspaint/css_paint_definition.h"
+#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/graphics/image.h"
+
+namespace blink {
+
+const char PaintWorkletProxyClient::kSupplementName[] =
+ "PaintWorkletProxyClient";
+
+// static
+PaintWorkletProxyClient* PaintWorkletProxyClient::Create() {
+ return new PaintWorkletProxyClient;
+}
+
+PaintWorkletProxyClient::PaintWorkletProxyClient()
+ : state_(RunState::kUninitialized) {
+ DCHECK(IsMainThread());
+}
+
+void PaintWorkletProxyClient::Trace(blink::Visitor* visitor) {
+ Supplement<WorkerClients>::Trace(visitor);
+}
+
+void PaintWorkletProxyClient::SetGlobalScope(WorkletGlobalScope* global_scope) {
+ DCHECK(global_scope);
+ DCHECK(global_scope->IsContextThread());
+ if (state_ == RunState::kDisposed)
+ return;
+ DCHECK(state_ == RunState::kUninitialized);
+
+ global_scope_ = static_cast<PaintWorkletGlobalScope*>(global_scope);
+ state_ = RunState::kWorking;
+}
+
+void PaintWorkletProxyClient::Dispose() {
+ if (state_ == RunState::kWorking) {
+ DCHECK(global_scope_);
+ DCHECK(global_scope_->IsContextThread());
+
+ // At worklet scope termination break the reference cycle between
+ // PaintWorkletGlobalScope and PaintWorkletProxyClient.
+ global_scope_ = nullptr;
+ }
+
+ DCHECK(state_ != RunState::kDisposed);
+ state_ = RunState::kDisposed;
+}
+
+// static
+PaintWorkletProxyClient* PaintWorkletProxyClient::From(WorkerClients* clients) {
+ return Supplement<WorkerClients>::From<PaintWorkletProxyClient>(clients);
+}
+
+void ProvidePaintWorkletProxyClientTo(WorkerClients* clients,
+ PaintWorkletProxyClient* client) {
+ clients->ProvideSupplement(client);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h
new file mode 100644
index 00000000000..78248601c42
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_proxy_client.h
@@ -0,0 +1,59 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_WORKLET_PROXY_CLIENT_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_WORKLET_PROXY_CLIENT_H_
+
+#include "base/macros.h"
+#include "base/single_thread_task_runner.h"
+#include "third_party/blink/renderer/core/workers/worker_clients.h"
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace blink {
+
+class WorkletGlobalScope;
+
+// Mediates between a worklet-thread bound PaintWorkletGlobalScope and its
+// associated dispatchers. A PaintWorkletProxyClient is associated with a single
+// global scope and one dispatcher to the compositor thread.
+//
+// This is constructed on the main thread but it is used in the worklet backing
+// thread.
+//
+// TODO(smcgruer): Add the dispatcher logic.
+class MODULES_EXPORT PaintWorkletProxyClient
+ : public GarbageCollectedFinalized<PaintWorkletProxyClient>,
+ public Supplement<WorkerClients> {
+ USING_GARBAGE_COLLECTED_MIXIN(PaintWorkletProxyClient);
+ DISALLOW_COPY_AND_ASSIGN(PaintWorkletProxyClient);
+
+ public:
+ static const char kSupplementName[];
+
+ static PaintWorkletProxyClient* Create();
+ virtual ~PaintWorkletProxyClient() = default;
+
+ void Trace(blink::Visitor*) override;
+
+ virtual void SetGlobalScope(WorkletGlobalScope*);
+ void Dispose();
+
+ static PaintWorkletProxyClient* From(WorkerClients*);
+
+ protected:
+ PaintWorkletProxyClient();
+
+ private:
+ CrossThreadPersistent<PaintWorkletGlobalScope> global_scope_;
+
+ enum RunState { kUninitialized, kWorking, kDisposed } state_;
+};
+
+void MODULES_EXPORT ProvidePaintWorkletProxyClientTo(WorkerClients*,
+ PaintWorkletProxyClient*);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_WORKLET_PROXY_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc
index a58249d1bd6..3d6790bba79 100644
--- a/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc
+++ b/chromium/third_party/blink/renderer/modules/csspaint/paint_worklet_test.cc
@@ -23,13 +23,13 @@ class TestPaintWorklet : public PaintWorklet {
public:
explicit TestPaintWorklet(LocalFrame* frame) : PaintWorklet(frame) {}
- void SetPaintsToSwitch(size_t num) { paints_to_switch_ = num; }
+ void SetPaintsToSwitch(int num) { paints_to_switch_ = num; }
int GetPaintsBeforeSwitching() override { return paints_to_switch_; }
// We always switch to another global scope so that we can tell how often it
// was switched in the test.
- size_t SelectNewGlobalScope() override {
+ wtf_size_t SelectNewGlobalScope() override {
return (GetActiveGlobalScopeForTesting() + 1) %
PaintWorklet::kNumGlobalScopes;
}
@@ -37,15 +37,15 @@ class TestPaintWorklet : public PaintWorklet {
size_t GetActiveGlobalScope() { return GetActiveGlobalScopeForTesting(); }
private:
- size_t paints_to_switch_;
+ int paints_to_switch_;
};
class PaintWorkletTest : public PageTestBase {
public:
void SetUp() override {
PageTestBase::SetUp(IntSize());
- test_paint_worklet_ =
- new TestPaintWorklet(GetDocument().domWindow()->GetFrame());
+ test_paint_worklet_ = MakeGarbageCollected<TestPaintWorklet>(
+ GetDocument().domWindow()->GetFrame());
proxy_ = test_paint_worklet_->CreateGlobalScope();
}
@@ -66,10 +66,11 @@ class PaintWorkletTest : public PageTestBase {
// Helper function used in GlobalScopeSelection test.
void ExpectSwitchGlobalScope(bool expect_switch_within_frame,
size_t num_paint_calls,
- size_t paint_cnt_to_switch,
+ int paint_cnt_to_switch,
size_t expected_num_paints_before_switch,
TestPaintWorklet* paint_worklet_to_test) {
- paint_worklet_to_test->GetFrame()->View()->UpdateAllLifecyclePhases();
+ paint_worklet_to_test->GetFrame()->View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
paint_worklet_to_test->SetPaintsToSwitch(paint_cnt_to_switch);
size_t previously_selected_global_scope =
paint_worklet_to_test->GetActiveGlobalScope();
@@ -103,43 +104,6 @@ class PaintWorkletTest : public PageTestBase {
Persistent<TestPaintWorklet> test_paint_worklet_;
};
-TEST_F(PaintWorkletTest, GarbageCollectionOfCSSPaintDefinition) {
- PaintWorkletGlobalScope* global_scope = GetProxy()->global_scope();
- global_scope->ScriptController()->Evaluate(
- ScriptSourceCode("registerPaint('foo', class { paint() { } });"),
- kSharableCrossOrigin);
-
- CSSPaintDefinition* definition = global_scope->FindDefinition("foo");
- DCHECK(definition);
-
- v8::Isolate* isolate =
- global_scope->ScriptController()->GetScriptState()->GetIsolate();
- DCHECK(isolate);
-
- // Set our ScopedPersistent to the paint function, and make weak.
- ScopedPersistent<v8::Function> handle;
- {
- v8::HandleScope handle_scope(isolate);
- handle.Set(isolate, definition->PaintFunctionForTesting(isolate));
- handle.SetPhantom();
- }
- DCHECK(!handle.IsEmpty());
- DCHECK(handle.IsWeak());
-
- // Run a GC, persistent shouldn't have been collected yet.
- ThreadState::Current()->CollectAllGarbage();
- V8GCController::CollectAllGarbageForTesting(isolate);
- DCHECK(!handle.IsEmpty());
-
- // Delete the page & associated objects.
- Terminate();
-
- // Run a GC, the persistent should have been collected.
- ThreadState::Current()->CollectAllGarbage();
- V8GCController::CollectAllGarbageForTesting(isolate);
- DCHECK(handle.IsEmpty());
-}
-
// This is a crash test for crbug.com/803026. At some point, we shipped the
// CSSPaintAPI without shipping the CSSPaintAPIArguments, the result of it is
// that the |paint_arguments| in the CSSPaintDefinition::Paint() becomes
@@ -149,7 +113,7 @@ TEST_F(PaintWorkletTest, PaintWithNullPaintArguments) {
PaintWorkletGlobalScope* global_scope = GetProxy()->global_scope();
global_scope->ScriptController()->Evaluate(
ScriptSourceCode("registerPaint('foo', class { paint() { } });"),
- kSharableCrossOrigin);
+ SanitizeScriptErrors::kDoNotSanitize);
CSSPaintDefinition* definition = global_scope->FindDefinition("foo");
ASSERT_TRUE(definition);
@@ -157,7 +121,7 @@ TEST_F(PaintWorkletTest, PaintWithNullPaintArguments) {
ImageResourceObserver* observer = GetImageResourceObserver();
ASSERT_TRUE(observer);
- const IntSize container_size(100, 100);
+ const FloatSize container_size(100, 100);
scoped_refptr<Image> image =
definition->Paint(*observer, container_size, nullptr);
EXPECT_NE(image, nullptr);
@@ -171,7 +135,7 @@ TEST_F(PaintWorkletTest, SinglyRegisteredDocumentDefinitionNotUsed) {
PaintWorkletGlobalScope* global_scope = GetProxy()->global_scope();
global_scope->ScriptController()->Evaluate(
ScriptSourceCode("registerPaint('foo', class { paint() { } });"),
- kSharableCrossOrigin);
+ SanitizeScriptErrors::kDoNotSanitize);
CSSPaintImageGeneratorImpl* generator =
static_cast<CSSPaintImageGeneratorImpl*>(
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc
index 51d85df91b4..8d66a6deb6c 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.cc
@@ -24,40 +24,42 @@
*/
#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_acceleration_init.h"
namespace blink {
-DeviceAcceleration::DeviceAcceleration(
- DeviceMotionData::Acceleration* acceleration)
- : acceleration_(acceleration) {}
+DeviceAcceleration* DeviceAcceleration::Create(double x, double y, double z) {
+ return MakeGarbageCollected<DeviceAcceleration>(x, y, z);
+}
-void DeviceAcceleration::Trace(blink::Visitor* visitor) {
- visitor->Trace(acceleration_);
- ScriptWrappable::Trace(visitor);
+DeviceAcceleration* DeviceAcceleration::Create(
+ const DeviceAccelerationInit* init) {
+ double x = init->hasX() ? init->x() : NAN;
+ double y = init->hasY() ? init->y() : NAN;
+ double z = init->hasZ() ? init->z() : NAN;
+ return DeviceAcceleration::Create(x, y, z);
}
-double DeviceAcceleration::x(bool& is_null) const {
- if (acceleration_->CanProvideX())
- return acceleration_->X();
+DeviceAcceleration::DeviceAcceleration(double x, double y, double z)
+ : x_(x), y_(y), z_(z) {}
- is_null = true;
- return 0;
+bool DeviceAcceleration::HasAccelerationData() const {
+ return !std::isnan(x_) || !std::isnan(y_) || !std::isnan(z_);
}
-double DeviceAcceleration::y(bool& is_null) const {
- if (acceleration_->CanProvideY())
- return acceleration_->Y();
+double DeviceAcceleration::x(bool& is_null) const {
+ is_null = std::isnan(x_);
+ return x_;
+}
- is_null = true;
- return 0;
+double DeviceAcceleration::y(bool& is_null) const {
+ is_null = std::isnan(y_);
+ return y_;
}
double DeviceAcceleration::z(bool& is_null) const {
- if (acceleration_->CanProvideZ())
- return acceleration_->Z();
-
- is_null = true;
- return 0;
+ is_null = std::isnan(z_);
+ return z_;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.h
index b01d26459a0..e24568a029c 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_acceleration.h
@@ -27,29 +27,33 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ACCELERATION_H_
#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
-class DeviceAcceleration final : public ScriptWrappable {
+class DeviceAccelerationInit;
+
+class MODULES_EXPORT DeviceAcceleration final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DeviceAcceleration* Create(
- DeviceMotionData::Acceleration* acceleration) {
- return new DeviceAcceleration(acceleration);
- }
- void Trace(blink::Visitor*) override;
+ static DeviceAcceleration* Create(double x, double y, double z);
+ static DeviceAcceleration* Create(const DeviceAccelerationInit*);
+
+ DeviceAcceleration(double x, double y, double z);
+
+ bool HasAccelerationData() const;
double x(bool& is_null) const;
double y(bool& is_null) const;
double z(bool& is_null) const;
private:
- explicit DeviceAcceleration(DeviceMotionData::Acceleration*);
-
- Member<DeviceMotionData::Acceleration> acceleration_;
+ const double x_;
+ const double y_;
+ const double z_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.cc
index 4e4431be7aa..02db4ebdfda 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.cc
@@ -30,7 +30,7 @@ DeviceMotionController& DeviceMotionController::From(Document& document) {
DeviceMotionController* controller =
Supplement<Document>::From<DeviceMotionController>(document);
if (!controller) {
- controller = new DeviceMotionController(document);
+ controller = MakeGarbageCollected<DeviceMotionController>(document);
ProvideTo(document, controller);
}
return *controller;
@@ -90,7 +90,8 @@ void DeviceMotionController::RegisterWithDispatcher() {
return;
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
frame->GetTaskRunner(TaskType::kSensor);
- motion_event_pump_ = new DeviceMotionEventPump(task_runner);
+ motion_event_pump_ =
+ MakeGarbageCollected<DeviceMotionEventPump>(task_runner);
}
motion_event_pump_->SetController(this);
}
@@ -102,7 +103,7 @@ void DeviceMotionController::UnregisterWithDispatcher() {
Event* DeviceMotionController::LastEvent() const {
return DeviceMotionEvent::Create(
- EventTypeNames::devicemotion,
+ event_type_names::kDevicemotion,
motion_event_pump_ ? motion_event_pump_->LatestDeviceMotionData()
: nullptr);
}
@@ -113,7 +114,7 @@ bool DeviceMotionController::IsNullEvent(Event* event) const {
}
const AtomicString& DeviceMotionController::EventTypeName() const {
- return EventTypeNames::devicemotion;
+ return event_type_names::kDevicemotion;
}
void DeviceMotionController::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.h
index e8b62cca1e1..003d47e399a 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_controller.h
@@ -22,6 +22,7 @@ class MODULES_EXPORT DeviceMotionController final
public:
static const char kSupplementName[];
+ explicit DeviceMotionController(Document&);
~DeviceMotionController() override;
static DeviceMotionController& From(Document&);
@@ -33,8 +34,6 @@ class MODULES_EXPORT DeviceMotionController final
void Trace(blink::Visitor*) override;
private:
- explicit DeviceMotionController(Document&);
-
// Inherited from PlatformEventController.
void RegisterWithDispatcher() override;
void UnregisterWithDispatcher() override;
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc
index a1fa2dcd2f5..b44ce0f5720 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.cc
@@ -24,113 +24,46 @@
*/
#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h"
-
+#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h"
#include "third_party/blink/renderer/modules/device_orientation/device_acceleration_init.h"
#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_init.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h"
#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.h"
namespace blink {
-DeviceMotionData::Acceleration* DeviceMotionData::Acceleration::Create(
- bool can_provide_x,
- double x,
- bool can_provide_y,
- double y,
- bool can_provide_z,
- double z) {
- return new DeviceMotionData::Acceleration(can_provide_x, x, can_provide_y, y,
- can_provide_z, z);
-}
-
-DeviceMotionData::Acceleration* DeviceMotionData::Acceleration::Create(
- const DeviceAccelerationInit& init) {
- return new DeviceMotionData::Acceleration(
- init.hasX(), init.hasX() ? init.x() : 0, init.hasY(),
- init.hasY() ? init.y() : 0, init.hasZ(), init.hasZ() ? init.z() : 0);
-}
-
-DeviceMotionData::Acceleration::Acceleration(bool can_provide_x,
- double x,
- bool can_provide_y,
- double y,
- bool can_provide_z,
- double z)
- : x_(x),
- y_(y),
- z_(z),
- can_provide_x_(can_provide_x),
- can_provide_y_(can_provide_y),
- can_provide_z_(can_provide_z)
-
-{}
-
-DeviceMotionData::RotationRate* DeviceMotionData::RotationRate::Create(
- bool can_provide_alpha,
- double alpha,
- bool can_provide_beta,
- double beta,
- bool can_provide_gamma,
- double gamma) {
- return new DeviceMotionData::RotationRate(can_provide_alpha, alpha,
- can_provide_beta, beta,
- can_provide_gamma, gamma);
-}
-
-DeviceMotionData::RotationRate* DeviceMotionData::RotationRate::Create(
- const DeviceRotationRateInit& init) {
- return new DeviceMotionData::RotationRate(
- init.hasAlpha(), init.hasAlpha() ? init.alpha() : 0, init.hasBeta(),
- init.hasBeta() ? init.beta() : 0, init.hasGamma(),
- init.hasGamma() ? init.gamma() : 0);
-}
-
-DeviceMotionData::RotationRate::RotationRate(bool can_provide_alpha,
- double alpha,
- bool can_provide_beta,
- double beta,
- bool can_provide_gamma,
- double gamma)
- : alpha_(alpha),
- beta_(beta),
- gamma_(gamma),
- can_provide_alpha_(can_provide_alpha),
- can_provide_beta_(can_provide_beta),
- can_provide_gamma_(can_provide_gamma) {}
-
-DeviceMotionData* DeviceMotionData::Create() {
- return new DeviceMotionData;
-}
-
DeviceMotionData* DeviceMotionData::Create(
- Acceleration* acceleration,
- Acceleration* acceleration_including_gravity,
- RotationRate* rotation_rate,
+ DeviceAcceleration* acceleration,
+ DeviceAcceleration* acceleration_including_gravity,
+ DeviceRotationRate* rotation_rate,
double interval) {
- return new DeviceMotionData(acceleration, acceleration_including_gravity,
- rotation_rate, interval);
+ return MakeGarbageCollected<DeviceMotionData>(
+ acceleration, acceleration_including_gravity, rotation_rate, interval);
}
-DeviceMotionData* DeviceMotionData::Create(const DeviceMotionEventInit& init) {
+DeviceMotionData* DeviceMotionData::Create(const DeviceMotionEventInit* init) {
return DeviceMotionData::Create(
- init.hasAcceleration()
- ? DeviceMotionData::Acceleration::Create(init.acceleration())
+ init->hasAcceleration() ? DeviceAcceleration::Create(init->acceleration())
+ : nullptr,
+ init->hasAccelerationIncludingGravity()
+ ? DeviceAcceleration::Create(init->accelerationIncludingGravity())
: nullptr,
- init.hasAccelerationIncludingGravity()
- ? DeviceMotionData::Acceleration::Create(
- init.accelerationIncludingGravity())
- : nullptr,
- init.hasRotationRate()
- ? DeviceMotionData::RotationRate::Create(init.rotationRate())
- : nullptr,
- init.interval());
+ init->hasRotationRate() ? DeviceRotationRate::Create(init->rotationRate())
+ : nullptr,
+ init->interval());
+}
+
+DeviceMotionData* DeviceMotionData::Create() {
+ return MakeGarbageCollected<DeviceMotionData>();
}
DeviceMotionData::DeviceMotionData() : interval_(0) {}
-DeviceMotionData::DeviceMotionData(Acceleration* acceleration,
- Acceleration* acceleration_including_gravity,
- RotationRate* rotation_rate,
- double interval)
+DeviceMotionData::DeviceMotionData(
+ DeviceAcceleration* acceleration,
+ DeviceAcceleration* acceleration_including_gravity,
+ DeviceRotationRate* rotation_rate,
+ double interval)
: acceleration_(acceleration),
acceleration_including_gravity_(acceleration_including_gravity),
rotation_rate_(rotation_rate),
@@ -144,18 +77,12 @@ void DeviceMotionData::Trace(blink::Visitor* visitor) {
bool DeviceMotionData::CanProvideEventData() const {
const bool has_acceleration =
- acceleration_ &&
- (acceleration_->CanProvideX() || acceleration_->CanProvideY() ||
- acceleration_->CanProvideZ());
+ acceleration_ && acceleration_->HasAccelerationData();
const bool has_acceleration_including_gravity =
acceleration_including_gravity_ &&
- (acceleration_including_gravity_->CanProvideX() ||
- acceleration_including_gravity_->CanProvideY() ||
- acceleration_including_gravity_->CanProvideZ());
+ acceleration_including_gravity_->HasAccelerationData();
const bool has_rotation_rate =
- rotation_rate_ &&
- (rotation_rate_->CanProvideAlpha() || rotation_rate_->CanProvideBeta() ||
- rotation_rate_->CanProvideGamma());
+ rotation_rate_ && rotation_rate_->HasRotationData();
return has_acceleration || has_acceleration_including_gravity ||
has_rotation_rate;
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.h
index aeece03e6ad..57e84537a76 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_data.h
@@ -31,115 +31,43 @@
namespace blink {
-class DeviceAccelerationInit;
+class DeviceAcceleration;
+class DeviceRotationRate;
class DeviceMotionEventInit;
-class DeviceRotationRateInit;
class MODULES_EXPORT DeviceMotionData final
: public GarbageCollected<DeviceMotionData> {
public:
- class Acceleration final
- : public GarbageCollected<DeviceMotionData::Acceleration> {
- public:
- static Acceleration* Create(bool can_provide_x,
- double x,
- bool can_provide_y,
- double y,
- bool can_provide_z,
- double z);
- static Acceleration* Create(const DeviceAccelerationInit&);
- void Trace(blink::Visitor* visitor) {}
-
- bool CanProvideX() const { return can_provide_x_; }
- bool CanProvideY() const { return can_provide_y_; }
- bool CanProvideZ() const { return can_provide_z_; }
-
- double X() const { return x_; }
- double Y() const { return y_; }
- double Z() const { return z_; }
-
- private:
- Acceleration(bool can_provide_x,
- double x,
- bool can_provide_y,
- double y,
- bool can_provide_z,
- double z);
-
- double x_;
- double y_;
- double z_;
-
- bool can_provide_x_;
- bool can_provide_y_;
- bool can_provide_z_;
- };
-
- class RotationRate final
- : public GarbageCollected<DeviceMotionData::RotationRate> {
- public:
- static RotationRate* Create(bool can_provide_alpha,
- double alpha,
- bool can_provide_beta,
- double beta,
- bool can_provide_gamma,
- double gamma);
- static RotationRate* Create(const DeviceRotationRateInit&);
- void Trace(blink::Visitor* visitor) {}
-
- bool CanProvideAlpha() const { return can_provide_alpha_; }
- bool CanProvideBeta() const { return can_provide_beta_; }
- bool CanProvideGamma() const { return can_provide_gamma_; }
-
- double Alpha() const { return alpha_; }
- double Beta() const { return beta_; }
- double Gamma() const { return gamma_; }
-
- private:
- RotationRate(bool can_provide_alpha,
- double alpha,
- bool can_provide_beta,
- double beta,
- bool can_provide_gamma,
- double gamma);
-
- double alpha_;
- double beta_;
- double gamma_;
+ static DeviceMotionData* Create();
+ static DeviceMotionData* Create(
+ DeviceAcceleration*,
+ DeviceAcceleration* acceleration_including_gravity,
+ DeviceRotationRate*,
+ double interval);
+ static DeviceMotionData* Create(const DeviceMotionEventInit*);
- bool can_provide_alpha_;
- bool can_provide_beta_;
- bool can_provide_gamma_;
- };
+ DeviceMotionData();
+ DeviceMotionData(DeviceAcceleration*,
+ DeviceAcceleration* acceleration_including_gravity,
+ DeviceRotationRate*,
+ double interval);
- static DeviceMotionData* Create();
- static DeviceMotionData* Create(Acceleration*,
- Acceleration* acceleration_including_gravity,
- RotationRate*,
- double interval);
- static DeviceMotionData* Create(const DeviceMotionEventInit&);
void Trace(blink::Visitor*);
- Acceleration* GetAcceleration() const { return acceleration_.Get(); }
- Acceleration* GetAccelerationIncludingGravity() const {
+ DeviceAcceleration* GetAcceleration() const { return acceleration_.Get(); }
+ DeviceAcceleration* GetAccelerationIncludingGravity() const {
return acceleration_including_gravity_.Get();
}
- RotationRate* GetRotationRate() const { return rotation_rate_.Get(); }
+ DeviceRotationRate* GetRotationRate() const { return rotation_rate_.Get(); }
double Interval() const { return interval_; }
bool CanProvideEventData() const;
private:
- DeviceMotionData();
- DeviceMotionData(Acceleration*,
- Acceleration* acceleration_including_gravity,
- RotationRate*,
- double interval);
-
- Member<Acceleration> acceleration_;
- Member<Acceleration> acceleration_including_gravity_;
- Member<RotationRate> rotation_rate_;
+ Member<DeviceAcceleration> acceleration_;
+ Member<DeviceAcceleration> acceleration_including_gravity_;
+ Member<DeviceRotationRate> rotation_rate_;
double interval_;
};
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc
index 20cb5953ab0..ff7f834bc9e 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.cc
@@ -38,7 +38,7 @@ DeviceMotionEvent::DeviceMotionEvent()
: device_motion_data_(DeviceMotionData::Create()) {}
DeviceMotionEvent::DeviceMotionEvent(const AtomicString& event_type,
- const DeviceMotionEventInit& initializer)
+ const DeviceMotionEventInit* initializer)
: Event(event_type, initializer),
device_motion_data_(DeviceMotionData::Create(initializer)) {}
@@ -48,36 +48,15 @@ DeviceMotionEvent::DeviceMotionEvent(const AtomicString& event_type,
device_motion_data_(device_motion_data) {}
DeviceAcceleration* DeviceMotionEvent::acceleration() {
- if (!device_motion_data_->GetAcceleration())
- return nullptr;
-
- if (!acceleration_)
- acceleration_ =
- DeviceAcceleration::Create(device_motion_data_->GetAcceleration());
-
- return acceleration_.Get();
+ return device_motion_data_->GetAcceleration();
}
DeviceAcceleration* DeviceMotionEvent::accelerationIncludingGravity() {
- if (!device_motion_data_->GetAccelerationIncludingGravity())
- return nullptr;
-
- if (!acceleration_including_gravity_)
- acceleration_including_gravity_ = DeviceAcceleration::Create(
- device_motion_data_->GetAccelerationIncludingGravity());
-
- return acceleration_including_gravity_.Get();
+ return device_motion_data_->GetAccelerationIncludingGravity();
}
DeviceRotationRate* DeviceMotionEvent::rotationRate() {
- if (!device_motion_data_->GetRotationRate())
- return nullptr;
-
- if (!rotation_rate_)
- rotation_rate_ =
- DeviceRotationRate::Create(device_motion_data_->GetRotationRate());
-
- return rotation_rate_.Get();
+ return device_motion_data_->GetRotationRate();
}
double DeviceMotionEvent::interval() const {
@@ -85,14 +64,11 @@ double DeviceMotionEvent::interval() const {
}
const AtomicString& DeviceMotionEvent::InterfaceName() const {
- return EventNames::DeviceMotionEvent;
+ return event_interface_names::kDeviceMotionEvent;
}
void DeviceMotionEvent::Trace(blink::Visitor* visitor) {
visitor->Trace(device_motion_data_);
- visitor->Trace(acceleration_);
- visitor->Trace(acceleration_including_gravity_);
- visitor->Trace(rotation_rate_);
Event::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.h
index 34d51516263..adcc872fa52 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event.h
@@ -40,15 +40,22 @@ class DeviceMotionEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ DeviceMotionEvent();
+ DeviceMotionEvent(const AtomicString&, const DeviceMotionEventInit*);
+ DeviceMotionEvent(const AtomicString& event_type, const DeviceMotionData*);
~DeviceMotionEvent() override;
- static DeviceMotionEvent* Create() { return new DeviceMotionEvent; }
+
+ static DeviceMotionEvent* Create() {
+ return MakeGarbageCollected<DeviceMotionEvent>();
+ }
static DeviceMotionEvent* Create(const AtomicString& event_type,
- const DeviceMotionEventInit& initializer) {
- return new DeviceMotionEvent(event_type, initializer);
+ const DeviceMotionEventInit* initializer) {
+ return MakeGarbageCollected<DeviceMotionEvent>(event_type, initializer);
}
static DeviceMotionEvent* Create(const AtomicString& event_type,
const DeviceMotionData* device_motion_data) {
- return new DeviceMotionEvent(event_type, device_motion_data);
+ return MakeGarbageCollected<DeviceMotionEvent>(event_type,
+ device_motion_data);
}
const DeviceMotionData* GetDeviceMotionData() const {
@@ -65,21 +72,16 @@ class DeviceMotionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- DeviceMotionEvent();
- DeviceMotionEvent(const AtomicString&, const DeviceMotionEventInit&);
- DeviceMotionEvent(const AtomicString& event_type, const DeviceMotionData*);
-
Member<const DeviceMotionData> device_motion_data_;
- Member<DeviceAcceleration> acceleration_;
- Member<DeviceAcceleration> acceleration_including_gravity_;
- Member<DeviceRotationRate> rotation_rate_;
};
DEFINE_TYPE_CASTS(DeviceMotionEvent,
Event,
event,
- event->InterfaceName() == EventNames::DeviceMotionEvent,
- event.InterfaceName() == EventNames::DeviceMotionEvent);
+ event->InterfaceName() ==
+ event_interface_names::kDeviceMotionEvent,
+ event.InterfaceName() ==
+ event_interface_names::kDeviceMotionEvent);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl
index 5995c967fc1..8e5e65c43dc 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_init.idl
@@ -5,8 +5,8 @@
// https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion
dictionary DeviceMotionEventInit : EventInit {
- DeviceAccelerationInit? acceleration;
- DeviceAccelerationInit? accelerationIncludingGravity;
- DeviceRotationRateInit? rotationRate;
+ DeviceAccelerationInit acceleration;
+ DeviceAccelerationInit accelerationIncludingGravity;
+ DeviceRotationRateInit rotationRate;
double interval = 0;
};
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc
index 47deaede78a..29eae4818b0 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.cc
@@ -10,8 +10,10 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/platform_event_controller.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h"
#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h"
#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h"
#include "ui/gfx/geometry/angle_conversions.h"
namespace {
@@ -121,56 +123,43 @@ bool DeviceMotionEventPump::SensorsReadyOrErrored() const {
}
DeviceMotionData* DeviceMotionEventPump::GetDataFromSharedMemory() {
- DeviceMotionData::Acceleration* acceleration = nullptr;
- DeviceMotionData::Acceleration* acceleration_including_gravity = nullptr;
- DeviceMotionData::RotationRate* rotation_rate = nullptr;
+ DeviceAcceleration* acceleration = nullptr;
+ DeviceAcceleration* acceleration_including_gravity = nullptr;
+ DeviceRotationRate* rotation_rate = nullptr;
if (accelerometer_.SensorReadingCouldBeRead()) {
if (accelerometer_.reading.timestamp() == 0.0)
return nullptr;
- acceleration_including_gravity = DeviceMotionData::Acceleration::Create(
- !std::isnan(accelerometer_.reading.accel.x.value()),
- accelerometer_.reading.accel.x,
- !std::isnan(accelerometer_.reading.accel.y.value()),
- accelerometer_.reading.accel.y,
- !std::isnan(accelerometer_.reading.accel.z.value()),
+ acceleration_including_gravity = DeviceAcceleration::Create(
+ accelerometer_.reading.accel.x, accelerometer_.reading.accel.y,
accelerometer_.reading.accel.z);
} else {
- acceleration_including_gravity = DeviceMotionData::Acceleration::Create(
- false, 0.0, false, 0.0, false, 0.0);
+ acceleration_including_gravity = DeviceAcceleration::Create(NAN, NAN, NAN);
}
if (linear_acceleration_sensor_.SensorReadingCouldBeRead()) {
if (linear_acceleration_sensor_.reading.timestamp() == 0.0)
return nullptr;
- acceleration = DeviceMotionData::Acceleration::Create(
- !std::isnan(linear_acceleration_sensor_.reading.accel.x.value()),
- linear_acceleration_sensor_.reading.accel.x,
- !std::isnan(linear_acceleration_sensor_.reading.accel.y.value()),
- linear_acceleration_sensor_.reading.accel.y,
- !std::isnan(linear_acceleration_sensor_.reading.accel.z.value()),
- linear_acceleration_sensor_.reading.accel.z);
+ acceleration =
+ DeviceAcceleration::Create(linear_acceleration_sensor_.reading.accel.x,
+ linear_acceleration_sensor_.reading.accel.y,
+ linear_acceleration_sensor_.reading.accel.z);
} else {
- acceleration = DeviceMotionData::Acceleration::Create(false, 0.0, false,
- 0.0, false, 0.0);
+ acceleration = DeviceAcceleration::Create(NAN, NAN, NAN);
}
if (gyroscope_.SensorReadingCouldBeRead()) {
if (gyroscope_.reading.timestamp() == 0.0)
return nullptr;
- rotation_rate = DeviceMotionData::RotationRate::Create(
- !std::isnan(gyroscope_.reading.gyro.x.value()),
- gfx::RadToDeg(gyroscope_.reading.gyro.x),
- !std::isnan(gyroscope_.reading.gyro.y.value()),
- gfx::RadToDeg(gyroscope_.reading.gyro.y),
- !std::isnan(gyroscope_.reading.gyro.z.value()),
- gfx::RadToDeg(gyroscope_.reading.gyro.z));
+ rotation_rate =
+ DeviceRotationRate::Create(gfx::RadToDeg(gyroscope_.reading.gyro.x),
+ gfx::RadToDeg(gyroscope_.reading.gyro.y),
+ gfx::RadToDeg(gyroscope_.reading.gyro.z));
} else {
- rotation_rate = DeviceMotionData::RotationRate::Create(false, 0.0, false,
- 0.0, false, 0.0);
+ rotation_rate = DeviceRotationRate::Create(NAN, NAN, NAN);
}
// The device orientation spec states that interval should be in
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc
index 3001690cdc5..e20cbf83a7e 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_motion_event_pump_unittest.cc
@@ -11,8 +11,10 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/renderer/core/frame/platform_event_controller.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_acceleration.h"
#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h"
#include "third_party/blink/renderer/modules/device_orientation/device_motion_event_pump.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "ui/gfx/geometry/angle_conversions.h"
@@ -74,15 +76,15 @@ class DeviceMotionEventPumpTest : public testing::Test {
void SetUp() override {
device::mojom::SensorProviderPtrInfo sensor_provider_ptr_info;
sensor_provider_.Bind(mojo::MakeRequest(&sensor_provider_ptr_info));
- auto* motion_pump =
- new DeviceMotionEventPump(base::ThreadTaskRunnerHandle::Get());
+ auto* motion_pump = MakeGarbageCollected<DeviceMotionEventPump>(
+ base::ThreadTaskRunnerHandle::Get());
motion_pump->SetSensorProviderForTesting(
device::mojom::blink::SensorProviderPtr(
device::mojom::blink::SensorProviderPtrInfo(
sensor_provider_ptr_info.PassHandle(),
device::mojom::SensorProvider::Version_)));
- controller_ = new MockDeviceMotionController(motion_pump);
+ controller_ = MakeGarbageCollected<MockDeviceMotionController>(motion_pump);
ExpectAllThreeSensorsStateToBe(
DeviceMotionEventPump::SensorState::NOT_INITIALIZED);
@@ -224,26 +226,34 @@ TEST_F(DeviceMotionEventPumpTest, AllSensorsAreActive) {
const DeviceMotionData* received_data = controller()->data();
EXPECT_TRUE(controller()->did_change_device_motion());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideX());
- EXPECT_EQ(1, received_data->GetAccelerationIncludingGravity()->X());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideY());
- EXPECT_EQ(2, received_data->GetAccelerationIncludingGravity()->Y());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideZ());
- EXPECT_EQ(3, received_data->GetAccelerationIncludingGravity()->Z());
-
- EXPECT_TRUE(received_data->GetAcceleration()->CanProvideX());
- EXPECT_EQ(4, received_data->GetAcceleration()->X());
- EXPECT_TRUE(received_data->GetAcceleration()->CanProvideY());
- EXPECT_EQ(5, received_data->GetAcceleration()->Y());
- EXPECT_TRUE(received_data->GetAcceleration()->CanProvideZ());
- EXPECT_EQ(6, received_data->GetAcceleration()->Z());
-
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideAlpha());
- EXPECT_EQ(gfx::RadToDeg(7.0), received_data->GetRotationRate()->Alpha());
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideBeta());
- EXPECT_EQ(gfx::RadToDeg(8.0), received_data->GetRotationRate()->Beta());
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideGamma());
- EXPECT_EQ(gfx::RadToDeg(9.0), received_data->GetRotationRate()->Gamma());
+ bool is_null;
+ EXPECT_TRUE(
+ received_data->GetAccelerationIncludingGravity()->HasAccelerationData());
+ EXPECT_EQ(1, received_data->GetAccelerationIncludingGravity()->x(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(2, received_data->GetAccelerationIncludingGravity()->y(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(3, received_data->GetAccelerationIncludingGravity()->z(is_null));
+ EXPECT_FALSE(is_null);
+
+ EXPECT_TRUE(received_data->GetAcceleration()->HasAccelerationData());
+ EXPECT_EQ(4, received_data->GetAcceleration()->x(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(5, received_data->GetAcceleration()->y(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(6, received_data->GetAcceleration()->z(is_null));
+ EXPECT_FALSE(is_null);
+
+ EXPECT_TRUE(received_data->GetRotationRate()->HasRotationData());
+ EXPECT_EQ(gfx::RadToDeg(7.0),
+ received_data->GetRotationRate()->alpha(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(gfx::RadToDeg(8.0),
+ received_data->GetRotationRate()->beta(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(gfx::RadToDeg(9.0),
+ received_data->GetRotationRate()->gamma(is_null));
+ EXPECT_FALSE(is_null);
controller()->motion_pump()->Stop();
@@ -270,23 +280,33 @@ TEST_F(DeviceMotionEventPumpTest, TwoSensorsAreActive) {
const DeviceMotionData* received_data = controller()->data();
EXPECT_TRUE(controller()->did_change_device_motion());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideX());
- EXPECT_EQ(1, received_data->GetAccelerationIncludingGravity()->X());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideY());
- EXPECT_EQ(2, received_data->GetAccelerationIncludingGravity()->Y());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideZ());
- EXPECT_EQ(3, received_data->GetAccelerationIncludingGravity()->Z());
-
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideX());
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideY());
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideZ());
-
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideAlpha());
- EXPECT_EQ(gfx::RadToDeg(7.0), received_data->GetRotationRate()->Alpha());
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideBeta());
- EXPECT_EQ(gfx::RadToDeg(8.0), received_data->GetRotationRate()->Beta());
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideGamma());
- EXPECT_EQ(gfx::RadToDeg(9.0), received_data->GetRotationRate()->Gamma());
+ bool is_null;
+ EXPECT_TRUE(
+ received_data->GetAccelerationIncludingGravity()->HasAccelerationData());
+ EXPECT_EQ(1, received_data->GetAccelerationIncludingGravity()->x(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(2, received_data->GetAccelerationIncludingGravity()->y(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(3, received_data->GetAccelerationIncludingGravity()->z(is_null));
+ EXPECT_FALSE(is_null);
+
+ received_data->GetAcceleration()->x(is_null);
+ EXPECT_TRUE(is_null);
+ received_data->GetAcceleration()->y(is_null);
+ EXPECT_TRUE(is_null);
+ received_data->GetAcceleration()->z(is_null);
+ EXPECT_TRUE(is_null);
+
+ EXPECT_TRUE(received_data->GetRotationRate()->HasRotationData());
+ EXPECT_EQ(gfx::RadToDeg(7.0),
+ received_data->GetRotationRate()->alpha(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(gfx::RadToDeg(8.0),
+ received_data->GetRotationRate()->beta(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(gfx::RadToDeg(9.0),
+ received_data->GetRotationRate()->gamma(is_null));
+ EXPECT_FALSE(is_null);
controller()->motion_pump()->Stop();
@@ -312,23 +332,30 @@ TEST_F(DeviceMotionEventPumpTest, SomeSensorDataFieldsNotAvailable) {
const DeviceMotionData* received_data = controller()->data();
EXPECT_TRUE(controller()->did_change_device_motion());
- EXPECT_FALSE(received_data->GetAccelerationIncludingGravity()->CanProvideX());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideY());
- EXPECT_EQ(2, received_data->GetAccelerationIncludingGravity()->Y());
- EXPECT_TRUE(received_data->GetAccelerationIncludingGravity()->CanProvideZ());
- EXPECT_EQ(3, received_data->GetAccelerationIncludingGravity()->Z());
-
- EXPECT_TRUE(received_data->GetAcceleration()->CanProvideX());
- EXPECT_EQ(4, received_data->GetAcceleration()->X());
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideY());
- EXPECT_TRUE(received_data->GetAcceleration()->CanProvideZ());
- EXPECT_EQ(6, received_data->GetAcceleration()->Z());
-
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideAlpha());
- EXPECT_EQ(gfx::RadToDeg(7.0), received_data->GetRotationRate()->Alpha());
- EXPECT_TRUE(received_data->GetRotationRate()->CanProvideBeta());
- EXPECT_EQ(gfx::RadToDeg(8.0), received_data->GetRotationRate()->Beta());
- EXPECT_FALSE(received_data->GetRotationRate()->CanProvideGamma());
+ bool is_null;
+ received_data->GetAccelerationIncludingGravity()->x(is_null);
+ EXPECT_TRUE(is_null);
+ EXPECT_EQ(2, received_data->GetAccelerationIncludingGravity()->y(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(3, received_data->GetAccelerationIncludingGravity()->z(is_null));
+ EXPECT_FALSE(is_null);
+
+ EXPECT_EQ(4, received_data->GetAcceleration()->x(is_null));
+ EXPECT_FALSE(is_null);
+ received_data->GetAcceleration()->y(is_null);
+ EXPECT_TRUE(is_null);
+ EXPECT_EQ(6, received_data->GetAcceleration()->z(is_null));
+ EXPECT_FALSE(is_null);
+
+ EXPECT_TRUE(received_data->GetAcceleration()->HasAccelerationData());
+ EXPECT_EQ(gfx::RadToDeg(7.0),
+ received_data->GetRotationRate()->alpha(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(gfx::RadToDeg(8.0),
+ received_data->GetRotationRate()->beta(is_null));
+ EXPECT_FALSE(is_null);
+ received_data->GetRotationRate()->gamma(is_null);
+ EXPECT_TRUE(is_null);
controller()->motion_pump()->Stop();
@@ -353,17 +380,12 @@ TEST_F(DeviceMotionEventPumpTest, FireAllNullEvent) {
const DeviceMotionData* received_data = controller()->data();
EXPECT_TRUE(controller()->did_change_device_motion());
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideX());
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideY());
- EXPECT_FALSE(received_data->GetAcceleration()->CanProvideZ());
+ EXPECT_FALSE(received_data->GetAcceleration()->HasAccelerationData());
- EXPECT_FALSE(received_data->GetAccelerationIncludingGravity()->CanProvideX());
- EXPECT_FALSE(received_data->GetAccelerationIncludingGravity()->CanProvideY());
- EXPECT_FALSE(received_data->GetAccelerationIncludingGravity()->CanProvideZ());
+ EXPECT_FALSE(
+ received_data->GetAccelerationIncludingGravity()->HasAccelerationData());
- EXPECT_FALSE(received_data->GetRotationRate()->CanProvideAlpha());
- EXPECT_FALSE(received_data->GetRotationRate()->CanProvideBeta());
- EXPECT_FALSE(received_data->GetRotationRate()->CanProvideGamma());
+ EXPECT_FALSE(received_data->GetRotationRate()->HasRotationData());
controller()->motion_pump()->Stop();
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.cc
index d671f10e015..da94bcb06f2 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.cc
@@ -25,7 +25,8 @@ DeviceOrientationAbsoluteController& DeviceOrientationAbsoluteController::From(
DeviceOrientationAbsoluteController* controller =
Supplement<Document>::From<DeviceOrientationAbsoluteController>(document);
if (!controller) {
- controller = new DeviceOrientationAbsoluteController(document);
+ controller =
+ MakeGarbageCollected<DeviceOrientationAbsoluteController>(document);
Supplement<Document>::ProvideTo(document, controller);
}
return *controller;
@@ -67,7 +68,7 @@ void DeviceOrientationAbsoluteController::DidAddEventListener(
}
const AtomicString& DeviceOrientationAbsoluteController::EventTypeName() const {
- return EventTypeNames::deviceorientationabsolute;
+ return event_type_names::kDeviceorientationabsolute;
}
void DeviceOrientationAbsoluteController::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.h
index e8e2e28d0ed..a717cc6ddbc 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_absolute_controller.h
@@ -15,6 +15,7 @@ class MODULES_EXPORT DeviceOrientationAbsoluteController final
public:
static const char kSupplementName[];
+ explicit DeviceOrientationAbsoluteController(Document&);
~DeviceOrientationAbsoluteController() override;
static DeviceOrientationAbsoluteController& From(Document&);
@@ -29,8 +30,6 @@ class MODULES_EXPORT DeviceOrientationAbsoluteController final
// Inherited from PlatformEventController.
void RegisterWithDispatcher() override;
- explicit DeviceOrientationAbsoluteController(Document&);
-
// Inherited from DeviceOrientationController.
const AtomicString& EventTypeName() const override;
};
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.cc
index 8e132701f9a..739f01a883a 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.cc
@@ -41,7 +41,7 @@ DeviceOrientationController& DeviceOrientationController::From(
DeviceOrientationController* controller =
Supplement<Document>::From<DeviceOrientationController>(document);
if (!controller) {
- controller = new DeviceOrientationController(document);
+ controller = MakeGarbageCollected<DeviceOrientationController>(document);
ProvideTo(document, controller);
}
return *controller;
@@ -122,7 +122,7 @@ bool DeviceOrientationController::IsNullEvent(Event* event) const {
}
const AtomicString& DeviceOrientationController::EventTypeName() const {
- return EventTypeNames::deviceorientation;
+ return event_type_names::kDeviceorientation;
}
void DeviceOrientationController::SetOverride(
@@ -156,7 +156,7 @@ void DeviceOrientationController::RegisterWithOrientationEventPump(
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
frame->GetTaskRunner(TaskType::kSensor);
orientation_event_pump_ =
- new DeviceOrientationEventPump(task_runner, absolute);
+ MakeGarbageCollected<DeviceOrientationEventPump>(task_runner, absolute);
}
orientation_event_pump_->AddController(this);
}
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.h
index 3985fdec55c..33384b290e4 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_controller.h
@@ -23,6 +23,7 @@ class MODULES_EXPORT DeviceOrientationController
public:
static const char kSupplementName[];
+ explicit DeviceOrientationController(Document&);
~DeviceOrientationController() override;
static DeviceOrientationController& From(Document&);
@@ -42,7 +43,6 @@ class MODULES_EXPORT DeviceOrientationController
const AtomicString& event_name);
protected:
- explicit DeviceOrientationController(Document&);
void RegisterWithOrientationEventPump(bool absolute);
Member<DeviceOrientationEventPump> orientation_event_pump_;
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.cc
index f8c415301c4..0040a58a4c1 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.cc
@@ -30,7 +30,7 @@
namespace blink {
DeviceOrientationData* DeviceOrientationData::Create() {
- return new DeviceOrientationData;
+ return MakeGarbageCollected<DeviceOrientationData>();
}
DeviceOrientationData* DeviceOrientationData::Create(
@@ -38,21 +38,22 @@ DeviceOrientationData* DeviceOrientationData::Create(
const base::Optional<double>& beta,
const base::Optional<double>& gamma,
bool absolute) {
- return new DeviceOrientationData(alpha, beta, gamma, absolute);
+ return MakeGarbageCollected<DeviceOrientationData>(alpha, beta, gamma,
+ absolute);
}
DeviceOrientationData* DeviceOrientationData::Create(
- const DeviceOrientationEventInit& init) {
+ const DeviceOrientationEventInit* init) {
base::Optional<double> alpha;
base::Optional<double> beta;
base::Optional<double> gamma;
- if (init.hasAlpha())
- alpha = init.alpha();
- if (init.hasBeta())
- beta = init.beta();
- if (init.hasGamma())
- gamma = init.gamma();
- return DeviceOrientationData::Create(alpha, beta, gamma, init.absolute());
+ if (init->hasAlpha())
+ alpha = init->alpha();
+ if (init->hasBeta())
+ beta = init->beta();
+ if (init->hasGamma())
+ gamma = init->gamma();
+ return DeviceOrientationData::Create(alpha, beta, gamma, init->absolute());
}
DeviceOrientationData::DeviceOrientationData() : absolute_(false) {}
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.h
index cba97f33d1c..bb591ef1727 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_data.h
@@ -42,7 +42,14 @@ class MODULES_EXPORT DeviceOrientationData final
const base::Optional<double>& beta,
const base::Optional<double>& gamma,
bool absolute);
- static DeviceOrientationData* Create(const DeviceOrientationEventInit&);
+ static DeviceOrientationData* Create(const DeviceOrientationEventInit*);
+
+ DeviceOrientationData();
+ DeviceOrientationData(const base::Optional<double>& alpha,
+ const base::Optional<double>& beta,
+ const base::Optional<double>& gamma,
+ bool absolute);
+
void Trace(blink::Visitor* visitor) {}
double Alpha() const;
@@ -56,12 +63,6 @@ class MODULES_EXPORT DeviceOrientationData final
bool CanProvideEventData() const;
private:
- DeviceOrientationData();
- DeviceOrientationData(const base::Optional<double>& alpha,
- const base::Optional<double>& beta,
- const base::Optional<double>& gamma,
- bool absolute);
-
base::Optional<double> alpha_;
base::Optional<double> beta_;
base::Optional<double> gamma_;
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.cc
index a8d9b3006a9..acdb49f7df7 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.cc
@@ -37,7 +37,7 @@ DeviceOrientationEvent::DeviceOrientationEvent()
DeviceOrientationEvent::DeviceOrientationEvent(
const AtomicString& event_type,
- const DeviceOrientationEventInit& initializer)
+ const DeviceOrientationEventInit* initializer)
: Event(event_type, initializer),
orientation_(DeviceOrientationData::Create(initializer)) {}
@@ -76,7 +76,7 @@ bool DeviceOrientationEvent::absolute() const {
}
const AtomicString& DeviceOrientationEvent::InterfaceName() const {
- return EventNames::DeviceOrientationEvent;
+ return event_interface_names::kDeviceOrientationEvent;
}
void DeviceOrientationEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.h
index b382094aefe..43a95fd1897 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event.h
@@ -38,16 +38,26 @@ class DeviceOrientationEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ DeviceOrientationEvent();
+ DeviceOrientationEvent(const AtomicString&,
+ const DeviceOrientationEventInit*);
+ DeviceOrientationEvent(const AtomicString& event_type,
+ DeviceOrientationData*);
~DeviceOrientationEvent() override;
- static DeviceOrientationEvent* Create() { return new DeviceOrientationEvent; }
+
+ static DeviceOrientationEvent* Create() {
+ return MakeGarbageCollected<DeviceOrientationEvent>();
+ }
static DeviceOrientationEvent* Create(
const AtomicString& event_type,
- const DeviceOrientationEventInit& initializer) {
- return new DeviceOrientationEvent(event_type, initializer);
+ const DeviceOrientationEventInit* initializer) {
+ return MakeGarbageCollected<DeviceOrientationEvent>(event_type,
+ initializer);
}
static DeviceOrientationEvent* Create(const AtomicString& event_type,
DeviceOrientationData* orientation) {
- return new DeviceOrientationEvent(event_type, orientation);
+ return MakeGarbageCollected<DeviceOrientationEvent>(event_type,
+ orientation);
}
DeviceOrientationData* Orientation() const { return orientation_.Get(); }
@@ -62,20 +72,16 @@ class DeviceOrientationEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- DeviceOrientationEvent();
- DeviceOrientationEvent(const AtomicString&,
- const DeviceOrientationEventInit&);
- DeviceOrientationEvent(const AtomicString& event_type,
- DeviceOrientationData*);
-
Member<DeviceOrientationData> orientation_;
};
DEFINE_TYPE_CASTS(DeviceOrientationEvent,
Event,
event,
- event->InterfaceName() == EventNames::DeviceOrientationEvent,
- event.InterfaceName() == EventNames::DeviceOrientationEvent);
+ event->InterfaceName() ==
+ event_interface_names::kDeviceOrientationEvent,
+ event.InterfaceName() ==
+ event_interface_names::kDeviceOrientationEvent);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event_pump_unittest.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event_pump_unittest.cc
index 64c5535d345..f6d10172a78 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event_pump_unittest.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_event_pump_unittest.cc
@@ -87,7 +87,7 @@ class DeviceOrientationEventPumpTest : public testing::Test {
void SetUp() override {
device::mojom::SensorProviderPtrInfo sensor_provider_ptr_info;
sensor_provider_.Bind(mojo::MakeRequest(&sensor_provider_ptr_info));
- auto* orientation_pump = new DeviceOrientationEventPump(
+ auto* orientation_pump = MakeGarbageCollected<DeviceOrientationEventPump>(
base::ThreadTaskRunnerHandle::Get(), false /* absolute */);
orientation_pump->SetSensorProviderForTesting(
device::mojom::blink::SensorProviderPtr(
@@ -95,7 +95,8 @@ class DeviceOrientationEventPumpTest : public testing::Test {
sensor_provider_ptr_info.PassHandle(),
device::mojom::SensorProvider::Version_)));
- controller_ = new MockDeviceOrientationController(orientation_pump);
+ controller_ =
+ MakeGarbageCollected<MockDeviceOrientationController>(orientation_pump);
ExpectRelativeOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::NOT_INITIALIZED);
@@ -726,15 +727,16 @@ class DeviceAbsoluteOrientationEventPumpTest : public testing::Test {
void SetUp() override {
device::mojom::SensorProviderPtrInfo sensor_provider_ptr_info;
sensor_provider_.Bind(mojo::MakeRequest(&sensor_provider_ptr_info));
- auto* absolute_orientation_pump = new DeviceOrientationEventPump(
- base::ThreadTaskRunnerHandle::Get(), true /* absolute */);
+ auto* absolute_orientation_pump =
+ MakeGarbageCollected<DeviceOrientationEventPump>(
+ base::ThreadTaskRunnerHandle::Get(), true /* absolute */);
absolute_orientation_pump->SetSensorProviderForTesting(
device::mojom::blink::SensorProviderPtr(
device::mojom::blink::SensorProviderPtrInfo(
sensor_provider_ptr_info.PassHandle(),
device::mojom::SensorProvider::Version_)));
- controller_ =
- new MockDeviceOrientationController(absolute_orientation_pump);
+ controller_ = MakeGarbageCollected<MockDeviceOrientationController>(
+ absolute_orientation_pump);
ExpectAbsoluteOrientationSensorStateToBe(
DeviceOrientationEventPump::SensorState::NOT_INITIALIZED);
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc
index 217e50af7f3..03708151def 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_orientation_inspector_agent.cc
@@ -20,8 +20,8 @@ DeviceOrientationInspectorAgent::~DeviceOrientationInspectorAgent() = default;
DeviceOrientationInspectorAgent::DeviceOrientationInspectorAgent(
InspectedFrames* inspected_frames)
: inspected_frames_(inspected_frames),
- sensor_agent_(
- new SensorInspectorAgent(inspected_frames->Root()->GetDocument())),
+ sensor_agent_(MakeGarbageCollected<SensorInspectorAgent>(
+ inspected_frames->Root()->GetDocument())),
enabled_(&agent_state_, /*default_value=*/false),
alpha_(&agent_state_, /*default_value=*/0.0),
beta_(&agent_state_, /*default_value=*/0.0),
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc b/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc
index dfe199841c1..4c2d754291d 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.cc
@@ -24,40 +24,44 @@
*/
#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h"
+#include "third_party/blink/renderer/modules/device_orientation/device_rotation_rate_init.h"
namespace blink {
-DeviceRotationRate::DeviceRotationRate(
- DeviceMotionData::RotationRate* rotation_rate)
- : rotation_rate_(rotation_rate) {}
+DeviceRotationRate* DeviceRotationRate::Create(double alpha,
+ double beta,
+ double gamma) {
+ return MakeGarbageCollected<DeviceRotationRate>(alpha, beta, gamma);
+}
-void DeviceRotationRate::Trace(blink::Visitor* visitor) {
- visitor->Trace(rotation_rate_);
- ScriptWrappable::Trace(visitor);
+DeviceRotationRate* DeviceRotationRate::Create(
+ const DeviceRotationRateInit* init) {
+ double alpha = init->hasAlpha() ? init->alpha() : NAN;
+ double beta = init->hasBeta() ? init->beta() : NAN;
+ double gamma = init->hasGamma() ? init->gamma() : NAN;
+ return DeviceRotationRate::Create(alpha, beta, gamma);
}
-double DeviceRotationRate::alpha(bool& is_null) const {
- if (rotation_rate_->CanProvideAlpha())
- return rotation_rate_->Alpha();
+DeviceRotationRate::DeviceRotationRate(double alpha, double beta, double gamma)
+ : alpha_(alpha), beta_(beta), gamma_(gamma) {}
- is_null = true;
- return 0;
+bool DeviceRotationRate::HasRotationData() const {
+ return !std::isnan(alpha_) || !std::isnan(beta_) || !std::isnan(gamma_);
}
-double DeviceRotationRate::beta(bool& is_null) const {
- if (rotation_rate_->CanProvideBeta())
- return rotation_rate_->Beta();
+double DeviceRotationRate::alpha(bool& is_null) const {
+ is_null = std::isnan(alpha_);
+ return alpha_;
+}
- is_null = true;
- return 0;
+double DeviceRotationRate::beta(bool& is_null) const {
+ is_null = std::isnan(beta_);
+ return beta_;
}
double DeviceRotationRate::gamma(bool& is_null) const {
- if (rotation_rate_->CanProvideGamma())
- return rotation_rate_->Gamma();
-
- is_null = true;
- return 0;
+ is_null = std::isnan(gamma_);
+ return gamma_;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h b/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h
index 7b52ea89f7b..8bd90aaa77f 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/device_rotation_rate.h
@@ -27,29 +27,33 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DEVICE_ROTATION_RATE_H_
#include "third_party/blink/renderer/modules/device_orientation/device_motion_data.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
-class DeviceRotationRate final : public ScriptWrappable {
+class DeviceRotationRateInit;
+
+class MODULES_EXPORT DeviceRotationRate final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DeviceRotationRate* Create(
- DeviceMotionData::RotationRate* rotation_rate) {
- return new DeviceRotationRate(rotation_rate);
- }
- void Trace(blink::Visitor*) override;
+ static DeviceRotationRate* Create(double alpha, double beta, double gamma);
+ static DeviceRotationRate* Create(const DeviceRotationRateInit*);
+
+ DeviceRotationRate(double alpha, double beta, double gamma);
+
+ bool HasRotationData() const;
double alpha(bool& is_null) const;
double beta(bool& is_null) const;
double gamma(bool& is_null) const;
private:
- explicit DeviceRotationRate(DeviceMotionData::RotationRate*);
-
- Member<DeviceMotionData::RotationRate> rotation_rate_;
+ const double alpha_;
+ const double beta_;
+ const double gamma_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_motion.h b/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_motion.h
index f2cde9c5408..84f657bfe89 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_motion.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_motion.h
@@ -11,7 +11,7 @@ namespace blink {
class DOMWindowDeviceMotion {
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(devicemotion);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(devicemotion, kDevicemotion);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_orientation.h b/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_orientation.h
index 61780005196..8273c298857 100644
--- a/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_orientation.h
+++ b/chromium/third_party/blink/renderer/modules/device_orientation/dom_window_device_orientation.h
@@ -11,8 +11,9 @@ namespace blink {
class DOMWindowDeviceOrientation {
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(deviceorientation);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(deviceorientationabsolute);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(deviceorientation, kDeviceorientation);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(deviceorientationabsolute,
+ kDeviceorientationabsolute);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/document_metadata/copyless_paste_extractor.cc b/chromium/third_party/blink/renderer/modules/document_metadata/copyless_paste_extractor.cc
index 0c91daa2cbb..e9020e79760 100644
--- a/chromium/third_party/blink/renderer/modules/document_metadata/copyless_paste_extractor.cc
+++ b/chromium/third_party/blink/renderer/modules/document_metadata/copyless_paste_extractor.cc
@@ -45,7 +45,7 @@ constexpr int kMaxDepth = 4;
// Some strings are very long, and we don't currently use those, so limit string
// length to something reasonable to avoid undue pressure on Icing. Note that
// App Indexing supports strings up to length 20k.
-constexpr int kMaxStringLength = 200;
+constexpr wtf_size_t kMaxStringLength = 200;
// Enforced by App Indexing, so stop processing early if possible.
constexpr wtf_size_t kMaxNumFields = 20;
// Enforced by App Indexing, so stop processing early if possible.
@@ -231,7 +231,7 @@ void extractTopLevelEntity(const JSONObject& val, Vector<EntityPtr>& entities) {
void extractEntitiesFromArray(const JSONArray& arr,
Vector<EntityPtr>& entities) {
- for (size_t i = 0; i < arr.size(); ++i) {
+ for (wtf_size_t i = 0; i < arr.size(); ++i) {
const JSONValue* val = arr.at(i);
if (val->GetType() == JSONValue::ValueType::kTypeObject) {
extractTopLevelEntity(*(JSONObject::Cast(val)), entities);
@@ -255,8 +255,8 @@ enum ExtractionStatus { kOK, kEmpty, kParseFailure, kWrongType, kCount };
ExtractionStatus extractMetadata(const Element& root,
Vector<EntityPtr>& entities) {
for (Element& element : ElementTraversal::DescendantsOf(root)) {
- if (element.HasTagName(HTMLNames::scriptTag) &&
- element.getAttribute(HTMLNames::typeAttr) == "application/ld+json") {
+ if (element.HasTagName(html_names::kScriptTag) &&
+ element.getAttribute(html_names::kTypeAttr) == "application/ld+json") {
std::unique_ptr<JSONValue> json = ParseJSON(element.textContent());
if (!json) {
LOG(ERROR) << "Failed to parse json.";
diff --git a/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.cc b/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.cc
index 932f8b9a0d9..5885674aee4 100644
--- a/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.cc
+++ b/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.cc
@@ -49,7 +49,7 @@ NavigatorDoNotTrack& NavigatorDoNotTrack::From(Navigator& navigator) {
NavigatorDoNotTrack* supplement =
Supplement<Navigator>::From<NavigatorDoNotTrack>(navigator);
if (!supplement) {
- supplement = new NavigatorDoNotTrack(navigator);
+ supplement = MakeGarbageCollected<NavigatorDoNotTrack>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.h b/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.h
index ce5549f0fca..832bd96b95a 100644
--- a/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.h
+++ b/chromium/third_party/blink/renderer/modules/donottrack/navigator_do_not_track.h
@@ -52,10 +52,9 @@ class NavigatorDoNotTrack final : public GarbageCollected<NavigatorDoNotTrack>,
String doNotTrack();
- void Trace(blink::Visitor*) override;
-
- private:
explicit NavigatorDoNotTrack(Navigator&);
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encoding/encoding.cc b/chromium/third_party/blink/renderer/modules/encoding/encoding.cc
index 70c1473f79c..fea5721df7d 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/encoding.cc
+++ b/chromium/third_party/blink/renderer/modules/encoding/encoding.cc
@@ -6,7 +6,7 @@
namespace blink {
-namespace Encoding {
+namespace encoding {
bool IsASCIIWhiteSpace(UChar c) {
// From Encoding Standard:
@@ -15,6 +15,6 @@ bool IsASCIIWhiteSpace(UChar c) {
return c == 0x09 || c == 0x0A || c == 0x0C || c == 0x0D || c == 0x20;
}
-} // namespace Encoding
+} // namespace encoding
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encoding/encoding.h b/chromium/third_party/blink/renderer/modules/encoding/encoding.h
index 084d96f82bb..0c9b0efc28e 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/encoding.h
+++ b/chromium/third_party/blink/renderer/modules/encoding/encoding.h
@@ -9,13 +9,13 @@
namespace blink {
-namespace Encoding {
+namespace encoding {
// The Encoding Standard has a definition of whitespace that differs from
// WTF::isWhiteSpace() (it excludes vertical tab).
bool IsASCIIWhiteSpace(UChar);
-} // namespace Encoding
+} // namespace encoding
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_decoder.cc b/chromium/third_party/blink/renderer/modules/encoding/text_decoder.cc
index ac02608357b..12da076d1f8 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_decoder.cc
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_decoder.cc
@@ -40,10 +40,10 @@
namespace blink {
TextDecoder* TextDecoder::Create(const String& label,
- const TextDecoderOptions& options,
+ const TextDecoderOptions* options,
ExceptionState& exception_state) {
WTF::TextEncoding encoding(
- label.StripWhiteSpace(&Encoding::IsASCIIWhiteSpace));
+ label.StripWhiteSpace(&encoding::IsASCIIWhiteSpace));
// The replacement encoding is not valid, but the Encoding API also
// rejects aliases of the replacement encoding.
if (!encoding.IsValid() || !strcasecmp(encoding.GetName(), "replacement")) {
@@ -52,7 +52,8 @@ TextDecoder* TextDecoder::Create(const String& label,
return nullptr;
}
- return new TextDecoder(encoding, options.fatal(), options.ignoreBOM());
+ return MakeGarbageCollected<TextDecoder>(encoding, options->fatal(),
+ options->ignoreBOM());
}
TextDecoder::TextDecoder(const WTF::TextEncoding& encoding,
@@ -77,29 +78,30 @@ String TextDecoder::encoding() const {
}
String TextDecoder::decode(const BufferSource& input,
- const TextDecodeOptions& options,
+ const TextDecodeOptions* options,
ExceptionState& exception_state) {
+ DCHECK(options);
DCHECK(!input.IsNull());
if (input.IsArrayBufferView()) {
const char* start = static_cast<const char*>(
input.GetAsArrayBufferView().View()->BaseAddress());
- size_t length = input.GetAsArrayBufferView().View()->byteLength();
+ uint32_t length = input.GetAsArrayBufferView().View()->byteLength();
return decode(start, length, options, exception_state);
}
DCHECK(input.IsArrayBuffer());
const char* start =
static_cast<const char*>(input.GetAsArrayBuffer()->Data());
- size_t length = input.GetAsArrayBuffer()->ByteLength();
+ uint32_t length = input.GetAsArrayBuffer()->ByteLength();
return decode(start, length, options, exception_state);
}
String TextDecoder::decode(const char* start,
- size_t length,
- const TextDecodeOptions& options,
+ uint32_t length,
+ const TextDecodeOptions* options,
ExceptionState& exception_state) {
- WTF::FlushBehavior flush =
- options.stream() ? WTF::FlushBehavior::kDoNotFlush
- : WTF::FlushBehavior::kDataEOF;
+ DCHECK(options);
+ WTF::FlushBehavior flush = options->stream() ? WTF::FlushBehavior::kDoNotFlush
+ : WTF::FlushBehavior::kDataEOF;
bool saw_error = false;
String s = codec_->Decode(start, length, flush, fatal_, saw_error);
@@ -124,7 +126,7 @@ String TextDecoder::decode(const char* start,
}
String TextDecoder::decode(ExceptionState& exception_state) {
- TextDecodeOptions options;
+ TextDecodeOptions* options = TextDecodeOptions::Create();
return decode(nullptr, 0, options, exception_state);
}
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_decoder.h b/chromium/third_party/blink/renderer/modules/encoding/text_decoder.h
index 1c887c612f2..cbad582e339 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_decoder.h
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_decoder.h
@@ -52,23 +52,23 @@ class TextDecoder final : public ScriptWrappable {
public:
static TextDecoder* Create(const String& label,
- const TextDecoderOptions&,
+ const TextDecoderOptions*,
ExceptionState&);
+
+ TextDecoder(const WTF::TextEncoding&, bool fatal, bool ignore_bom);
~TextDecoder() override;
// Implement the IDL
String encoding() const;
bool fatal() const { return fatal_; }
bool ignoreBOM() const { return ignore_bom_; }
- String decode(const BufferSource&, const TextDecodeOptions&, ExceptionState&);
+ String decode(const BufferSource&, const TextDecodeOptions*, ExceptionState&);
String decode(ExceptionState&);
private:
- TextDecoder(const WTF::TextEncoding&, bool fatal, bool ignore_bom);
-
String decode(const char* start,
- size_t length,
- const TextDecodeOptions&,
+ uint32_t length,
+ const TextDecodeOptions*,
ExceptionState&);
WTF::TextEncoding encoding_;
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.cc b/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.cc
index 2c0fe8dcd47..62e5dba4060 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.cc
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.cc
@@ -60,7 +60,7 @@ class TextDecoderStream::Transformer final : public TransformStreamTransformer {
return;
}
const char* start = static_cast<const char*>(view->BaseAddress());
- size_t length = view->byteLength();
+ uint32_t length = view->byteLength();
DecodeAndEnqueue(start, length, WTF::FlushBehavior::kDoNotFlush,
controller, exception_state);
return;
@@ -74,7 +74,7 @@ class TextDecoderStream::Transformer final : public TransformStreamTransformer {
return;
}
const char* start = static_cast<const char*>(array_buffer->Data());
- size_t length = array_buffer->ByteLength();
+ uint32_t length = array_buffer->ByteLength();
DecodeAndEnqueue(start, length, WTF::FlushBehavior::kDoNotFlush, controller,
exception_state);
}
@@ -95,7 +95,7 @@ class TextDecoderStream::Transformer final : public TransformStreamTransformer {
// Implements the second part of "decode and enqueue a chunk" as well as the
// "flush and enqueue" algorithm.
void DecodeAndEnqueue(const char* start,
- size_t length,
+ uint32_t length,
WTF::FlushBehavior flush,
TransformStreamDefaultController* controller,
ExceptionState& exception_state) {
@@ -144,10 +144,10 @@ class TextDecoderStream::Transformer final : public TransformStreamTransformer {
TextDecoderStream* TextDecoderStream::Create(ScriptState* script_state,
const String& label,
- const TextDecoderOptions& options,
+ const TextDecoderOptions* options,
ExceptionState& exception_state) {
WTF::TextEncoding encoding(
- label.StripWhiteSpace(&Encoding::IsASCIIWhiteSpace));
+ label.StripWhiteSpace(&encoding::IsASCIIWhiteSpace));
// The replacement encoding is not valid, but the Encoding API also
// rejects aliases of the replacement encoding.
if (!encoding.IsValid() ||
@@ -167,14 +167,12 @@ String TextDecoderStream::encoding() const {
return String(encoding_.GetName()).LowerASCII();
}
-ScriptValue TextDecoderStream::readable(ScriptState* script_state,
- ExceptionState& exception_state) const {
- return transform_->Readable(script_state, exception_state);
+ReadableStream* TextDecoderStream::readable() const {
+ return transform_->Readable();
}
-ScriptValue TextDecoderStream::writable(ScriptState* script_state,
- ExceptionState& exception_state) const {
- return transform_->Writable(script_state, exception_state);
+WritableStream* TextDecoderStream::writable() const {
+ return transform_->Writable();
}
void TextDecoderStream::Trace(Visitor* visitor) {
@@ -184,12 +182,12 @@ void TextDecoderStream::Trace(Visitor* visitor) {
TextDecoderStream::TextDecoderStream(ScriptState* script_state,
const WTF::TextEncoding& encoding,
- const TextDecoderOptions& options,
+ const TextDecoderOptions* options,
ExceptionState& exception_state)
- : transform_(new TransformStream()),
+ : transform_(MakeGarbageCollected<TransformStream>()),
encoding_(encoding),
- fatal_(options.fatal()),
- ignore_bom_(options.ignoreBOM()) {
+ fatal_(options->fatal()),
+ ignore_bom_(options->ignoreBOM()) {
if (!RetainWrapperDuringConstruction(this, script_state)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Cannot queue task to retain wrapper");
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.h b/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.h
index 5bf4d10fd40..bbfa4d4bee4 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.h
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.h
@@ -15,9 +15,11 @@
namespace blink {
class ExceptionState;
+class ReadableStream;
class ScriptState;
class TextDecoderOptions;
class Visitor;
+class WritableStream;
// Implements the TextDecoderStream interface as specified at
// https://encoding.spec.whatwg.org/#interface-textdecoderstream.
@@ -30,7 +32,7 @@ class TextDecoderStream final : public ScriptWrappable {
public:
static TextDecoderStream* Create(ScriptState*,
const String& label,
- const TextDecoderOptions&,
+ const TextDecoderOptions*,
ExceptionState&);
~TextDecoderStream() override;
@@ -38,8 +40,8 @@ class TextDecoderStream final : public ScriptWrappable {
String encoding() const;
bool fatal() const { return fatal_; }
bool ignoreBOM() const { return ignore_bom_; }
- ScriptValue readable(ScriptState*, ExceptionState&) const;
- ScriptValue writable(ScriptState*, ExceptionState&) const;
+ ReadableStream* readable() const;
+ WritableStream* writable() const;
void Trace(Visitor* visitor) override;
@@ -48,7 +50,7 @@ class TextDecoderStream final : public ScriptWrappable {
TextDecoderStream(ScriptState*,
const WTF::TextEncoding&,
- const TextDecoderOptions&,
+ const TextDecoderOptions*,
ExceptionState&);
const TraceWrapperMember<TransformStream> transform_;
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.idl b/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.idl
index cf5600ceb1e..9fe584233f6 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.idl
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_decoder_stream.idl
@@ -14,6 +14,6 @@
readonly attribute DOMString encoding;
readonly attribute boolean fatal;
readonly attribute boolean ignoreBOM;
- [CallWith=ScriptState, RaisesException] readonly attribute any readable;
- [CallWith=ScriptState, RaisesException] readonly attribute any writable;
+ readonly attribute ReadableStream readable;
+ readonly attribute WritableStream writable;
};
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_encoder.cc b/chromium/third_party/blink/renderer/modules/encoding/text_encoder.cc
index 3f9161f58db..85279a225d1 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_encoder.cc
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_encoder.cc
@@ -41,7 +41,7 @@ namespace blink {
TextEncoder* TextEncoder::Create(ExecutionContext* context,
ExceptionState& exception_state) {
WTF::TextEncoding encoding("UTF-8");
- return new TextEncoder(encoding);
+ return MakeGarbageCollected<TextEncoder>(encoding);
}
TextEncoder::TextEncoder(const WTF::TextEncoding& encoding)
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_encoder.h b/chromium/third_party/blink/renderer/modules/encoding/text_encoder.h
index 0892f75d950..76e502c2c04 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_encoder.h
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_encoder.h
@@ -49,6 +49,8 @@ class TextEncoder final : public ScriptWrappable {
public:
static TextEncoder* Create(ExecutionContext*, ExceptionState&);
+
+ TextEncoder(const WTF::TextEncoding&);
~TextEncoder() override;
// Implement the IDL
@@ -56,8 +58,6 @@ class TextEncoder final : public ScriptWrappable {
NotShared<DOMUint8Array> encode(const String&);
private:
- TextEncoder(const WTF::TextEncoding&);
-
WTF::TextEncoding encoding_;
std::unique_ptr<WTF::TextCodec> codec_;
};
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc b/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc
index 1c5aa8fa6e4..cedf987bc8c 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.cc
@@ -101,8 +101,8 @@ class TextEncoderStream::Transformer final : public TransformStreamTransformer {
static DOMUint8Array* CreateDOMUint8ArrayFromTwoCStringsConcatenated(
const CString& string1,
const CString& string2) {
- const size_t length1 = string1.length();
- const size_t length2 = string2.length();
+ const wtf_size_t length1 = string1.length();
+ const wtf_size_t length2 = string2.length();
DOMUint8Array* const array = DOMUint8Array::Create(length1 + length2);
if (length1 > 0)
memcpy(array->Data(), string1.data(), length1);
@@ -144,8 +144,8 @@ class TextEncoderStream::Transformer final : public TransformStreamTransformer {
}
// Third argument is ignored, as above.
- *result =
- encoder_->Encode(begin, end - begin, WTF::kEntitiesForUnencodables);
+ *result = encoder_->Encode(begin, static_cast<wtf_size_t>(end - begin),
+ WTF::kEntitiesForUnencodables);
DCHECK_NE(result->length(), 0u);
return true;
}
@@ -170,14 +170,12 @@ String TextEncoderStream::encoding() const {
return "utf-8";
}
-ScriptValue TextEncoderStream::readable(ScriptState* script_state,
- ExceptionState& exception_state) const {
- return transform_->Readable(script_state, exception_state);
+ReadableStream* TextEncoderStream::readable() const {
+ return transform_->Readable();
}
-ScriptValue TextEncoderStream::writable(ScriptState* script_state,
- ExceptionState& exception_state) const {
- return transform_->Writable(script_state, exception_state);
+WritableStream* TextEncoderStream::writable() const {
+ return transform_->Writable();
}
void TextEncoderStream::Trace(Visitor* visitor) {
@@ -187,7 +185,7 @@ void TextEncoderStream::Trace(Visitor* visitor) {
TextEncoderStream::TextEncoderStream(ScriptState* script_state,
ExceptionState& exception_state)
- : transform_(new TransformStream()) {
+ : transform_(MakeGarbageCollected<TransformStream>()) {
if (!RetainWrapperDuringConstruction(this, script_state)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Cannot queue task to retain wrapper");
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.h b/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.h
index 2aa28ddc7a4..1e34400212f 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.h
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.h
@@ -14,7 +14,9 @@
namespace blink {
class ExceptionState;
+class ReadableStream;
class ScriptState;
+class WritableStream;
class Visitor;
// Implements the TextDecoderStream interface as specified at
@@ -31,8 +33,8 @@ class TextEncoderStream final : public ScriptWrappable {
// From text_encoder_stream.idl
String encoding() const;
- ScriptValue readable(ScriptState*, ExceptionState&) const;
- ScriptValue writable(ScriptState*, ExceptionState&) const;
+ ReadableStream* readable() const;
+ WritableStream* writable() const;
void Trace(Visitor* visitor) override;
diff --git a/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.idl b/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.idl
index 98ee518e622..73f60a89316 100644
--- a/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.idl
+++ b/chromium/third_party/blink/renderer/modules/encoding/text_encoder_stream.idl
@@ -12,6 +12,6 @@
RuntimeEnabled=EncodingStreams
] interface TextEncoderStream {
readonly attribute DOMString encoding;
- [CallWith=ScriptState, RaisesException] readonly attribute any readable;
- [CallWith=ScriptState, RaisesException] readonly attribute any writable;
+ readonly attribute ReadableStream readable;
+ readonly attribute WritableStream writable;
};
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.cc
index 29e135167f6..a87909649fd 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.cc
@@ -115,4 +115,34 @@ String EncryptedMediaUtils::ConvertKeyStatusToString(
return "internal-error";
}
+// static
+WebMediaKeySystemConfiguration::Requirement
+EncryptedMediaUtils::ConvertToMediaKeysRequirement(const String& requirement) {
+ if (requirement == "required")
+ return WebMediaKeySystemConfiguration::Requirement::kRequired;
+ if (requirement == "optional")
+ return WebMediaKeySystemConfiguration::Requirement::kOptional;
+ if (requirement == "not-allowed")
+ return WebMediaKeySystemConfiguration::Requirement::kNotAllowed;
+
+ NOTREACHED();
+ return WebMediaKeySystemConfiguration::Requirement::kOptional;
+}
+
+// static
+String EncryptedMediaUtils::ConvertMediaKeysRequirementToString(
+ WebMediaKeySystemConfiguration::Requirement requirement) {
+ switch (requirement) {
+ case WebMediaKeySystemConfiguration::Requirement::kRequired:
+ return "required";
+ case WebMediaKeySystemConfiguration::Requirement::kOptional:
+ return "optional";
+ case WebMediaKeySystemConfiguration::Requirement::kNotAllowed:
+ return "not-allowed";
+ }
+
+ NOTREACHED();
+ return "not-allowed";
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.h
index 6c2e811beb8..2a13fbc24be 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.h
@@ -7,6 +7,7 @@
#include "third_party/blink/public/platform/web_encrypted_media_key_information.h"
#include "third_party/blink/public/platform/web_encrypted_media_types.h"
+#include "third_party/blink/public/platform/web_media_key_system_configuration.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -26,6 +27,11 @@ class EncryptedMediaUtils {
static String ConvertKeyStatusToString(
const WebEncryptedMediaKeyInformation::KeyStatus);
+
+ static WebMediaKeySystemConfiguration::Requirement
+ ConvertToMediaKeysRequirement(const String&);
+ static String ConvertMediaKeysRequirementToString(
+ WebMediaKeySystemConfiguration::Requirement);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc
index a4b9f87d5a8..256e30be550 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc
@@ -32,12 +32,13 @@ class SetMediaKeysHandler : public ScriptPromiseResolver {
public:
static ScriptPromise Create(ScriptState*, HTMLMediaElement&, MediaKeys*);
+
+ SetMediaKeysHandler(ScriptState*, HTMLMediaElement&, MediaKeys*);
~SetMediaKeysHandler() override;
void Trace(blink::Visitor*) override;
private:
- SetMediaKeysHandler(ScriptState*, HTMLMediaElement&, MediaKeys*);
void TimerFired(TimerBase*);
void ClearExistingMediaKeys();
@@ -129,8 +130,8 @@ class SetContentDecryptionModuleResult final
ScriptPromise SetMediaKeysHandler::Create(ScriptState* script_state,
HTMLMediaElement& element,
MediaKeys* media_keys) {
- SetMediaKeysHandler* handler =
- new SetMediaKeysHandler(script_state, element, media_keys);
+ SetMediaKeysHandler* handler = MakeGarbageCollected<SetMediaKeysHandler>(
+ script_state, element, media_keys);
handler->PauseIfNeeded();
handler->KeepAliveWhilePending();
return handler->Promise();
@@ -200,8 +201,8 @@ void SetMediaKeysHandler::ClearExistingMediaKeys() {
FailureCallback failure_callback =
WTF::Bind(&SetMediaKeysHandler::ClearFailed, WrapPersistent(this));
ContentDecryptionModuleResult* result =
- new SetContentDecryptionModuleResult(std::move(success_callback),
- std::move(failure_callback));
+ MakeGarbageCollected<SetContentDecryptionModuleResult>(
+ std::move(success_callback), std::move(failure_callback));
media_player->SetContentDecryptionModule(nullptr, result->Result());
// Don't do anything more until |result| is resolved (or rejected).
@@ -231,8 +232,8 @@ void SetMediaKeysHandler::SetNewMediaKeys() {
FailureCallback failure_callback =
WTF::Bind(&SetMediaKeysHandler::SetFailed, WrapPersistent(this));
ContentDecryptionModuleResult* result =
- new SetContentDecryptionModuleResult(std::move(success_callback),
- std::move(failure_callback));
+ MakeGarbageCollected<SetContentDecryptionModuleResult>(
+ std::move(success_callback), std::move(failure_callback));
element_->GetWebMediaPlayer()->SetContentDecryptionModule(
new_media_keys_->ContentDecryptionModule(), result->Result());
@@ -343,7 +344,7 @@ HTMLMediaElementEncryptedMedia& HTMLMediaElementEncryptedMedia::From(
Supplement<HTMLMediaElement>::From<HTMLMediaElementEncryptedMedia>(
element);
if (!supplement) {
- supplement = new HTMLMediaElementEncryptedMedia(element);
+ supplement = MakeGarbageCollected<HTMLMediaElementEncryptedMedia>(element);
ProvideTo(element, supplement);
}
return *supplement;
@@ -392,14 +393,14 @@ ScriptPromise HTMLMediaElementEncryptedMedia::setMediaKeys(
static Event* CreateEncryptedEvent(WebEncryptedMediaInitDataType init_data_type,
const unsigned char* init_data,
unsigned init_data_length) {
- MediaEncryptedEventInit initializer;
- initializer.setInitDataType(
+ MediaEncryptedEventInit* initializer = MediaEncryptedEventInit::Create();
+ initializer->setInitDataType(
EncryptedMediaUtils::ConvertFromInitDataType(init_data_type));
- initializer.setInitData(DOMArrayBuffer::Create(init_data, init_data_length));
- initializer.setBubbles(false);
- initializer.setCancelable(false);
+ initializer->setInitData(DOMArrayBuffer::Create(init_data, init_data_length));
+ initializer->setBubbles(false);
+ initializer->setCancelable(false);
- return MediaEncryptedEvent::Create(EventTypeNames::encrypted, initializer);
+ return MediaEncryptedEvent::Create(event_type_names::kEncrypted, initializer);
}
void HTMLMediaElementEncryptedMedia::Encrypted(
@@ -409,8 +410,7 @@ void HTMLMediaElementEncryptedMedia::Encrypted(
DVLOG(EME_LOG_LEVEL) << __func__;
Event* event;
- if (media_element_->IsMediaDataCORSSameOrigin(
- media_element_->GetExecutionContext()->GetSecurityOrigin())) {
+ if (media_element_->IsMediaDataCorsSameOrigin()) {
event = CreateEncryptedEvent(init_data_type, init_data, init_data_length);
} else {
// Current page is not allowed to see content from the media file,
@@ -442,7 +442,7 @@ void HTMLMediaElementEncryptedMedia::DidBlockPlaybackWaitingForKey() {
// 2. If the media element's waiting for key value is false, queue a task
// to fire a simple event named waitingforkey at the media element.
if (!is_waiting_for_key_) {
- Event* event = Event::Create(EventTypeNames::waitingforkey);
+ Event* event = Event::Create(event_type_names::kWaitingforkey);
event->SetTarget(media_element_);
media_element_->ScheduleEvent(event);
}
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h
index 883af21942d..0da6cb1777f 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h
@@ -36,8 +36,8 @@ class MODULES_EXPORT HTMLMediaElementEncryptedMedia final
static ScriptPromise setMediaKeys(ScriptState*,
HTMLMediaElement&,
MediaKeys*);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(encrypted);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(waitingforkey);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(encrypted, kEncrypted);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(waitingforkey, kWaitingforkey);
// WebMediaPlayerEncryptedMediaClient methods
void Encrypted(WebEncryptedMediaInitDataType,
@@ -49,6 +49,7 @@ class MODULES_EXPORT HTMLMediaElementEncryptedMedia final
static HTMLMediaElementEncryptedMedia& From(HTMLMediaElement&);
+ HTMLMediaElementEncryptedMedia(HTMLMediaElement&);
~HTMLMediaElementEncryptedMedia();
void Trace(blink::Visitor*) override;
@@ -56,8 +57,6 @@ class MODULES_EXPORT HTMLMediaElementEncryptedMedia final
private:
friend class SetMediaKeysHandler;
- HTMLMediaElementEncryptedMedia(HTMLMediaElement&);
-
// EventTarget
bool SetAttributeEventListener(const AtomicString& event_type,
EventListener*);
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.cc
index b072a352eab..95f874b2561 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.cc
@@ -31,15 +31,15 @@ namespace blink {
MediaEncryptedEvent::MediaEncryptedEvent(
const AtomicString& type,
- const MediaEncryptedEventInit& initializer)
+ const MediaEncryptedEventInit* initializer)
: Event(type, initializer),
- init_data_type_(initializer.initDataType()),
- init_data_(initializer.initData()) {}
+ init_data_type_(initializer->initDataType()),
+ init_data_(initializer->initData()) {}
MediaEncryptedEvent::~MediaEncryptedEvent() = default;
const AtomicString& MediaEncryptedEvent::InterfaceName() const {
- return EventNames::MediaEncryptedEvent;
+ return event_interface_names::kMediaEncryptedEvent;
}
void MediaEncryptedEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.h
index 5127a1c9ba1..86e897c5e02 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_encrypted_event.h
@@ -35,12 +35,14 @@ class MediaEncryptedEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ MediaEncryptedEvent(const AtomicString& type,
+ const MediaEncryptedEventInit* initializer);
~MediaEncryptedEvent() override;
static MediaEncryptedEvent* Create(
const AtomicString& type,
- const MediaEncryptedEventInit& initializer) {
- return new MediaEncryptedEvent(type, initializer);
+ const MediaEncryptedEventInit* initializer) {
+ return MakeGarbageCollected<MediaEncryptedEvent>(type, initializer);
}
const AtomicString& InterfaceName() const override;
@@ -51,9 +53,6 @@ class MediaEncryptedEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- MediaEncryptedEvent(const AtomicString& type,
- const MediaEncryptedEventInit& initializer);
-
String init_data_type_;
Member<DOMArrayBuffer> init_data_;
};
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.cc
index da682203e8d..17d630d79ac 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.cc
@@ -33,18 +33,18 @@ MediaKeyMessageEvent::MediaKeyMessageEvent() = default;
MediaKeyMessageEvent::MediaKeyMessageEvent(
const AtomicString& type,
- const MediaKeyMessageEventInit& initializer)
+ const MediaKeyMessageEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasMessageType())
- message_type_ = initializer.messageType();
- if (initializer.hasMessage())
- message_ = initializer.message();
+ if (initializer->hasMessageType())
+ message_type_ = initializer->messageType();
+ if (initializer->hasMessage())
+ message_ = initializer->message();
}
MediaKeyMessageEvent::~MediaKeyMessageEvent() = default;
const AtomicString& MediaKeyMessageEvent::InterfaceName() const {
- return EventNames::MediaKeyMessageEvent;
+ return event_interface_names::kMediaKeyMessageEvent;
}
void MediaKeyMessageEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.h
index 70a1ebb457e..95540f07f2f 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_message_event.h
@@ -38,14 +38,19 @@ class MediaKeyMessageEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ MediaKeyMessageEvent();
+ MediaKeyMessageEvent(const AtomicString& type,
+ const MediaKeyMessageEventInit* initializer);
~MediaKeyMessageEvent() override;
- static MediaKeyMessageEvent* Create() { return new MediaKeyMessageEvent; }
+ static MediaKeyMessageEvent* Create() {
+ return MakeGarbageCollected<MediaKeyMessageEvent>();
+ }
static MediaKeyMessageEvent* Create(
const AtomicString& type,
- const MediaKeyMessageEventInit& initializer) {
- return new MediaKeyMessageEvent(type, initializer);
+ const MediaKeyMessageEventInit* initializer) {
+ return MakeGarbageCollected<MediaKeyMessageEvent>(type, initializer);
}
const AtomicString& InterfaceName() const override;
@@ -56,10 +61,6 @@ class MediaKeyMessageEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- MediaKeyMessageEvent();
- MediaKeyMessageEvent(const AtomicString& type,
- const MediaKeyMessageEventInit& initializer);
-
String message_type_;
Member<DOMArrayBuffer> message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc
index 482abd90ebb..e478c4d1a33 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.cc
@@ -54,6 +54,7 @@
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#define MEDIA_KEY_SESSION_LOG_LEVEL 3
@@ -72,7 +73,7 @@ static bool IsValidSessionId(const String& session_id) {
(session_id.length() > MaxSessionIdLength))
return false;
- if (!session_id.ContainsOnlyASCII())
+ if (!session_id.ContainsOnlyASCIIOrEmpty())
return false;
// Check that the sessionId only contains alphanumeric characters.
@@ -155,17 +156,17 @@ class MediaKeySession::PendingAction final
DOMArrayBuffer* init_data) {
DCHECK(result);
DCHECK(init_data);
- return new PendingAction(kGenerateRequest, result, init_data_type,
- init_data, String());
+ return MakeGarbageCollected<PendingAction>(
+ kGenerateRequest, result, init_data_type, init_data, String());
}
static PendingAction* CreatePendingLoadRequest(
ContentDecryptionModuleResult* result,
const String& session_id) {
DCHECK(result);
- return new PendingAction(kLoad, result,
- WebEncryptedMediaInitDataType::kUnknown, nullptr,
- session_id);
+ return MakeGarbageCollected<PendingAction>(
+ kLoad, result, WebEncryptedMediaInitDataType::kUnknown, nullptr,
+ session_id);
}
static PendingAction* CreatePendingUpdate(
@@ -173,35 +174,27 @@ class MediaKeySession::PendingAction final
DOMArrayBuffer* data) {
DCHECK(result);
DCHECK(data);
- return new PendingAction(kUpdate, result,
- WebEncryptedMediaInitDataType::kUnknown, data,
- String());
+ return MakeGarbageCollected<PendingAction>(
+ kUpdate, result, WebEncryptedMediaInitDataType::kUnknown, data,
+ String());
}
static PendingAction* CreatePendingClose(
ContentDecryptionModuleResult* result) {
DCHECK(result);
- return new PendingAction(kClose, result,
- WebEncryptedMediaInitDataType::kUnknown, nullptr,
- String());
+ return MakeGarbageCollected<PendingAction>(
+ kClose, result, WebEncryptedMediaInitDataType::kUnknown, nullptr,
+ String());
}
static PendingAction* CreatePendingRemove(
ContentDecryptionModuleResult* result) {
DCHECK(result);
- return new PendingAction(kRemove, result,
- WebEncryptedMediaInitDataType::kUnknown, nullptr,
- String());
+ return MakeGarbageCollected<PendingAction>(
+ kRemove, result, WebEncryptedMediaInitDataType::kUnknown, nullptr,
+ String());
}
- ~PendingAction() = default;
-
- void Trace(blink::Visitor* visitor) {
- visitor->Trace(result_);
- visitor->Trace(data_);
- }
-
- private:
PendingAction(Type type,
ContentDecryptionModuleResult* result,
WebEncryptedMediaInitDataType init_data_type,
@@ -212,7 +205,14 @@ class MediaKeySession::PendingAction final
init_data_type_(init_data_type),
data_(data),
string_data_(string_data) {}
+ ~PendingAction() = default;
+
+ void Trace(blink::Visitor* visitor) {
+ visitor->Trace(result_);
+ visitor->Trace(data_);
+ }
+ private:
const Type type_;
const Member<ContentDecryptionModuleResult> result_;
const WebEncryptedMediaInitDataType init_data_type_;
@@ -341,7 +341,8 @@ MediaKeySession* MediaKeySession::Create(
ScriptState* script_state,
MediaKeys* media_keys,
WebEncryptedMediaSessionType session_type) {
- return new MediaKeySession(script_state, media_keys, session_type);
+ return MakeGarbageCollected<MediaKeySession>(script_state, media_keys,
+ session_type);
}
MediaKeySession::MediaKeySession(ScriptState* script_state,
@@ -353,10 +354,10 @@ MediaKeySession::MediaKeySession(ScriptState* script_state,
media_keys_(media_keys),
session_type_(session_type),
expiration_(std::numeric_limits<double>::quiet_NaN()),
- key_statuses_map_(new MediaKeyStatusMap()),
+ key_statuses_map_(MakeGarbageCollected<MediaKeyStatusMap>()),
is_uninitialized_(true),
is_callable_(false),
- is_closed_(false),
+ is_closing_or_closed_(false),
closed_promise_(new ClosedPromise(ExecutionContext::From(script_state),
this,
ClosedPromise::kClosed)),
@@ -439,9 +440,9 @@ ScriptPromise MediaKeySession::generateRequest(
// Generates a request based on the initData. When this method is invoked,
// the user agent must run the following steps:
- // 1. If this object is closed, return a promise rejected with an
- // InvalidStateError.
- if (is_closed_)
+ // 1. If this object's closing or closed value is true, return a promise
+ // rejected with an InvalidStateError.
+ if (is_closing_or_closed_)
return CreateRejectedPromiseAlreadyClosed(script_state);
// 2. If this object's uninitialized value is false, return a promise
@@ -496,8 +497,9 @@ ScriptPromise MediaKeySession::generateRequest(
// (Done in constructor.)
// 9. Let promise be a new promise.
- NewSessionResultPromise* result = new NewSessionResultPromise(
- script_state, this, "MediaKeySession", "generateRequest");
+ NewSessionResultPromise* result =
+ MakeGarbageCollected<NewSessionResultPromise>(
+ script_state, this, "MediaKeySession", "generateRequest");
ScriptPromise promise = result->Promise();
// 10. Run the following steps asynchronously (done in generateRequestTask())
@@ -555,9 +557,9 @@ ScriptPromise MediaKeySession::load(ScriptState* script_state,
// Loads the data stored for the specified session into this object. When
// this method is invoked, the user agent must run the following steps:
- // 1. If this object is closed, return a promise rejected with an
- // InvalidStateError.
- if (is_closed_)
+ // 1. If this object's closing or closed value is true, return a promise
+ // rejected with an InvalidStateError.
+ if (is_closing_or_closed_)
return CreateRejectedPromiseAlreadyClosed(script_state);
// 2. If this object's uninitialized value is false, return a promise
@@ -591,8 +593,9 @@ ScriptPromise MediaKeySession::load(ScriptState* script_state,
// (Available as getExecutionContext()->getSecurityOrigin() anytime.)
// 7. Let promise be a new promise.
- LoadSessionResultPromise* result = new LoadSessionResultPromise(
- script_state, this, "MediaKeySession", "load");
+ LoadSessionResultPromise* result =
+ MakeGarbageCollected<LoadSessionResultPromise>(script_state, this,
+ "MediaKeySession", "load");
ScriptPromise promise = result->Promise();
// 8. Run the following steps asynchronously (done in loadTask())
@@ -687,9 +690,9 @@ ScriptPromise MediaKeySession::update(ScriptState* script_state,
// Provides messages, including licenses, to the CDM. When this method is
// invoked, the user agent must run the following steps:
- // 1. If this object is closed, return a promise rejected with an
- // InvalidStateError.
- if (is_closed_)
+ // 1. If this object's closing or closed value is true, return a promise
+ // rejected with an InvalidStateError.
+ if (is_closing_or_closed_)
return CreateRejectedPromiseAlreadyClosed(script_state);
// 2. If this object's callable value is false, return a promise
@@ -711,8 +714,8 @@ ScriptPromise MediaKeySession::update(ScriptState* script_state,
DOMArrayBuffer::Create(response.Data(), response.ByteLength());
// 5. Let promise be a new promise.
- SimpleResultPromise* result =
- new SimpleResultPromise(script_state, this, "MediaKeySession", "update");
+ SimpleResultPromise* result = MakeGarbageCollected<SimpleResultPromise>(
+ script_state, this, "MediaKeySession", "update");
ScriptPromise promise = result->Promise();
// 6. Run the following steps asynchronously (done in updateTask())
@@ -746,21 +749,24 @@ ScriptPromise MediaKeySession::close(ScriptState* script_state) {
// Persisted data should not be released or cleared.
// When this method is invoked, the user agent must run the following steps:
- // 1. Let session be the associated MediaKeySession object.
- // 2. If session is closed, return a resolved promise.
- if (is_closed_)
+ // 1. If this object's closing or closed value is true, return a resolved
+ // promise.
+ if (is_closing_or_closed_)
return ScriptPromise::CastUndefined(script_state);
- // 3. If session's callable value is false, return a promise rejected with
- // an InvalidStateError.
+ // 2. If this object's callable value is false, return a promise rejected
+ // with an InvalidStateError.
if (!is_callable_)
return CreateRejectedPromiseNotCallable(script_state);
- // 4. Let promise be a new promise.
- SimpleResultPromise* result =
- new SimpleResultPromise(script_state, this, "MediaKeySession", "close");
+ // 3. Let promise be a new promise.
+ SimpleResultPromise* result = MakeGarbageCollected<SimpleResultPromise>(
+ script_state, this, "MediaKeySession", "close");
ScriptPromise promise = result->Promise();
+ // 4. Set this object's closing or closed value to true.
+ is_closing_or_closed_ = true;
+
// 5. Run the following steps in parallel (done in closeTask()).
pending_actions_.push_back(PendingAction::CreatePendingClose(result));
if (!action_timer_.IsActive())
@@ -787,9 +793,9 @@ ScriptPromise MediaKeySession::remove(ScriptState* script_state) {
// Removes stored session data associated with this object. When this
// method is invoked, the user agent must run the following steps:
- // 1. If this object is closed, return a promise rejected with an
- // InvalidStateError.
- if (is_closed_)
+ // 1. If this object's closing or closed value is true, return a promise
+ // rejected with an InvalidStateError.
+ if (is_closing_or_closed_)
return CreateRejectedPromiseAlreadyClosed(script_state);
// 2. If this object's callable value is false, return a promise rejected
@@ -798,8 +804,8 @@ ScriptPromise MediaKeySession::remove(ScriptState* script_state) {
return CreateRejectedPromiseNotCallable(script_state);
// 3. Let promise be a new promise.
- SimpleResultPromise* result =
- new SimpleResultPromise(script_state, this, "MediaKeySession", "remove");
+ SimpleResultPromise* result = MakeGarbageCollected<SimpleResultPromise>(
+ script_state, this, "MediaKeySession", "remove");
ScriptPromise promise = result->Promise();
// 4. Run the following steps asynchronously (done in removeTask()).
@@ -875,30 +881,30 @@ void MediaKeySession::Message(MessageType message_type,
// -> messageType = the specified message type
// -> message = the specified message
- MediaKeyMessageEventInit init;
+ MediaKeyMessageEventInit* init = MediaKeyMessageEventInit::Create();
switch (message_type) {
case WebContentDecryptionModuleSession::Client::MessageType::
kLicenseRequest:
- init.setMessageType("license-request");
+ init->setMessageType("license-request");
break;
case WebContentDecryptionModuleSession::Client::MessageType::
kLicenseRenewal:
- init.setMessageType("license-renewal");
+ init->setMessageType("license-renewal");
break;
case WebContentDecryptionModuleSession::Client::MessageType::
kLicenseRelease:
- init.setMessageType("license-release");
+ init->setMessageType("license-release");
break;
case WebContentDecryptionModuleSession::Client::MessageType::
kIndividualizationRequest:
- init.setMessageType("individualization-request");
+ init->setMessageType("individualization-request");
break;
}
- init.setMessage(DOMArrayBuffer::Create(static_cast<const void*>(message),
- message_length));
+ init->setMessage(DOMArrayBuffer::Create(static_cast<const void*>(message),
+ SafeCast<uint32_t>(message_length)));
MediaKeyMessageEvent* event =
- MediaKeyMessageEvent::Create(EventTypeNames::message, init);
+ MediaKeyMessageEvent::Create(event_type_names::kMessage, init);
event->SetTarget(this);
async_event_queue_->EnqueueEvent(FROM_HERE, *event);
}
@@ -908,29 +914,23 @@ void MediaKeySession::Close() {
// From http://w3c.github.io/encrypted-media/#session-closed
// 1. Let session be the associated MediaKeySession object.
- // 2. If session's session type is "persistent-usage-record", execute the
- // following steps in parallel:
- // 1. Let cdm be the CDM instance represented by session's cdm instance
- // value.
- // 2. Use cdm to store session's record of key usage, if it exists.
- // ("persistent-usage-record" not supported by Chrome.)
-
- // 3. Run the Update Key Statuses algorithm on the session, providing an
- // empty sequence.
+ // 2. Let promise be the session's closed attribute.
+ // 3. If promise is resolved, abort these steps.
+ if (closed_promise_->GetState() == ScriptPromisePropertyBase::kResolved)
+ return;
+
+ // 4. Set the session's closing or closed value to true.
+ is_closing_or_closed_ = true;
+
+ // 5. Run the Update Key Statuses algorithm on the session, providing
+ // an empty sequence.
KeysStatusesChange(WebVector<WebEncryptedMediaKeyInformation>(), false);
- // 4. Run the Update Expiration algorithm on the session, providing NaN.
+ // 6. Run the Update Expiration algorithm on the session, providing NaN.
ExpirationChanged(std::numeric_limits<double>::quiet_NaN());
- // 5. Let promise be the closed attribute of the session.
- // 6. Resolve promise.
- closed_promise_->Resolve(ToV8UndefinedGenerator());
-
- // After this algorithm has run, event handlers for the events queued by
- // this algorithm will be executed, but no further events can be queued.
- // As a result, no messages can be sent by the CDM as a result of closing
- // the session.
- is_closed_ = true;
+ // 7. Resolve promise.
+ closed_promise_->ResolveWithUndefined();
}
void MediaKeySession::ExpirationChanged(double updated_expiry_time_in_ms) {
@@ -983,7 +983,7 @@ void MediaKeySession::KeysStatusesChange(
// 5. Queue a task to fire a simple event named keystatuseschange
// at the session.
- Event* event = Event::Create(EventTypeNames::keystatuseschange);
+ Event* event = Event::Create(event_type_names::kKeystatuseschange);
event->SetTarget(this);
async_event_queue_->EnqueueEvent(FROM_HERE, *event);
@@ -996,7 +996,7 @@ void MediaKeySession::KeysStatusesChange(
}
const AtomicString& MediaKeySession::InterfaceName() const {
- return EventTargetNames::MediaKeySession;
+ return event_target_names::kMediaKeySession;
}
ExecutionContext* MediaKeySession::GetExecutionContext() const {
@@ -1012,16 +1012,19 @@ bool MediaKeySession::HasPendingActivity() const {
<< (async_event_queue_->HasPendingEvents()
? " async_event_queue_->HasPendingEvents()"
: "")
- << ((media_keys_ && !is_closed_) ? " media_keys_ && !is_closed_" : "");
+ << ((media_keys_ && !is_closing_or_closed_)
+ ? " media_keys_ && !is_closing_or_closed_"
+ : "");
return !pending_actions_.IsEmpty() ||
- async_event_queue_->HasPendingEvents() || (media_keys_ && !is_closed_);
+ async_event_queue_->HasPendingEvents() ||
+ (media_keys_ && !is_closing_or_closed_);
}
void MediaKeySession::ContextDestroyed(ExecutionContext*) {
// Stop the CDM from firing any more events for this session.
session_.reset();
- is_closed_ = true;
+ is_closing_or_closed_ = true;
action_timer_.Stop();
pending_actions_.clear();
}
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.h
index caaca9ca862..d4d44c2c5e9 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_session.h
@@ -75,14 +75,15 @@ class MediaKeySession final
MediaKeys*,
WebEncryptedMediaSessionType);
+ MediaKeySession(ScriptState*, MediaKeys*, WebEncryptedMediaSessionType);
~MediaKeySession() override;
String sessionId() const;
double expiration() const { return expiration_; }
ScriptPromise closed(ScriptState*);
MediaKeyStatusMap* keyStatuses();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keystatuseschange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(keystatuseschange, kKeystatuseschange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
ScriptPromise generateRequest(ScriptState*,
const String& init_data_type,
@@ -109,7 +110,6 @@ class MediaKeySession final
friend class NewSessionResultPromise;
friend class LoadSessionResultPromise;
- MediaKeySession(ScriptState*, MediaKeys*, WebEncryptedMediaSessionType);
void Dispose();
void ActionTimerFired(TimerBase*);
@@ -149,7 +149,7 @@ class MediaKeySession final
// Session states.
bool is_uninitialized_;
bool is_callable_;
- bool is_closed_; // Is the CDM finished with this session?
+ bool is_closing_or_closed_;
// Keep track of the closed promise.
typedef ScriptPromiseProperty<Member<MediaKeySession>,
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.cc
index 6b9fe84ea87..8c930dcd365 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.cc
@@ -21,9 +21,12 @@ class MediaKeyStatusMap::MapEntry final
: public GarbageCollectedFinalized<MediaKeyStatusMap::MapEntry> {
public:
static MapEntry* Create(WebData key_id, const String& status) {
- return new MapEntry(key_id, status);
+ return MakeGarbageCollected<MapEntry>(key_id, status);
}
+ MapEntry(WebData key_id, const String& status)
+ : key_id_(DOMArrayBuffer::Create(scoped_refptr<SharedBuffer>(key_id))),
+ status_(status) {}
virtual ~MapEntry() = default;
DOMArrayBuffer* KeyId() const { return key_id_.Get(); }
@@ -60,10 +63,6 @@ class MediaKeyStatusMap::MapEntry final
virtual void Trace(blink::Visitor* visitor) { visitor->Trace(key_id_); }
private:
- MapEntry(WebData key_id, const String& status)
- : key_id_(DOMArrayBuffer::Create(scoped_refptr<SharedBuffer>(key_id))),
- status_(status) {}
-
const Member<DOMArrayBuffer> key_id_;
const String status_;
};
@@ -100,7 +99,7 @@ class MapIterationSource final
// m_map is stored just for keeping it alive. It needs to be kept
// alive while JavaScript holds the iterator to it.
const Member<const MediaKeyStatusMap> map_;
- size_t current_;
+ uint32_t current_;
};
void MediaKeyStatusMap::Clear() {
@@ -110,20 +109,20 @@ void MediaKeyStatusMap::Clear() {
void MediaKeyStatusMap::AddEntry(WebData key_id, const String& status) {
// Insert new entry into sorted list.
MapEntry* entry = MapEntry::Create(key_id, status);
- size_t index = 0;
+ uint32_t index = 0;
while (index < entries_.size() &&
MapEntry::CompareLessThan(entries_[index], entry))
++index;
entries_.insert(index, entry);
}
-const MediaKeyStatusMap::MapEntry& MediaKeyStatusMap::at(size_t index) const {
+const MediaKeyStatusMap::MapEntry& MediaKeyStatusMap::at(uint32_t index) const {
DCHECK_LT(index, entries_.size());
return *entries_.at(index);
}
-size_t MediaKeyStatusMap::IndexOf(const DOMArrayPiece& key) const {
- for (size_t index = 0; index < entries_.size(); ++index) {
+uint32_t MediaKeyStatusMap::IndexOf(const DOMArrayPiece& key) const {
+ for (uint32_t index = 0; index < entries_.size(); ++index) {
auto* const current = entries_.at(index)->KeyId();
if (key == *current)
return index;
@@ -131,17 +130,17 @@ size_t MediaKeyStatusMap::IndexOf(const DOMArrayPiece& key) const {
// Not found, so return an index outside the valid range. The caller
// must ensure this value is not exposed outside this class.
- return std::numeric_limits<size_t>::max();
+ return std::numeric_limits<uint32_t>::max();
}
bool MediaKeyStatusMap::has(const ArrayBufferOrArrayBufferView& key_id) {
- size_t index = IndexOf(key_id);
+ uint32_t index = IndexOf(key_id);
return index < entries_.size();
}
ScriptValue MediaKeyStatusMap::get(ScriptState* script_state,
const ArrayBufferOrArrayBufferView& key_id) {
- size_t index = IndexOf(key_id);
+ uint32_t index = IndexOf(key_id);
if (index >= entries_.size())
return ScriptValue(script_state, v8::Undefined(script_state->GetIsolate()));
return ScriptValue::From(script_state, at(index).Status());
@@ -149,7 +148,7 @@ ScriptValue MediaKeyStatusMap::get(ScriptState* script_state,
PairIterable<ArrayBufferOrArrayBufferView, String>::IterationSource*
MediaKeyStatusMap::StartIteration(ScriptState*, ExceptionState&) {
- return new MapIterationSource(this);
+ return MakeGarbageCollected<MapIterationSource>(this);
}
void MediaKeyStatusMap::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.h
index b0fc6f89a25..345c5f2f8e9 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_status_map.h
@@ -39,10 +39,10 @@ class MediaKeyStatusMap final
void Clear();
void AddEntry(WebData key_id, const String& status);
- const MapEntry& at(size_t) const;
+ const MapEntry& at(uint32_t) const;
// IDL attributes / methods
- size_t size() const { return entries_.size(); }
+ uint32_t size() const { return entries_.size(); }
bool has(const ArrayBufferOrArrayBufferView& key_id);
ScriptValue get(ScriptState*, const ArrayBufferOrArrayBufferView& key_id);
@@ -52,7 +52,7 @@ class MediaKeyStatusMap final
// PairIterable<> implementation.
IterationSource* StartIteration(ScriptState*, ExceptionState&) override;
- size_t IndexOf(const DOMArrayPiece& key_id) const;
+ uint32_t IndexOf(const DOMArrayPiece& key_id) const;
MediaKeyStatusMapType entries_;
};
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.cc
index bc8cdb23881..2f518b1a5d1 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.cc
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/timer.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -70,30 +71,32 @@ class NewCdmResultPromise : public ContentDecryptionModuleResultPromise {
// NavigatorRequestMediaKeySystemAccess.
static Vector<String> ConvertInitDataTypes(
const WebVector<WebEncryptedMediaInitDataType>& init_data_types) {
- Vector<String> result(init_data_types.size());
- for (size_t i = 0; i < init_data_types.size(); i++)
+ Vector<String> result(SafeCast<wtf_size_t>(init_data_types.size()));
+ for (wtf_size_t i = 0; i < result.size(); i++)
result[i] =
EncryptedMediaUtils::ConvertFromInitDataType(init_data_types[i]);
return result;
}
-static HeapVector<MediaKeySystemMediaCapability> ConvertCapabilities(
+static HeapVector<Member<MediaKeySystemMediaCapability>> ConvertCapabilities(
const WebVector<WebMediaKeySystemMediaCapability>& capabilities) {
- HeapVector<MediaKeySystemMediaCapability> result(capabilities.size());
- for (size_t i = 0; i < capabilities.size(); i++) {
- MediaKeySystemMediaCapability capability;
- capability.setContentType(capabilities[i].content_type);
- capability.setRobustness(capabilities[i].robustness);
+ HeapVector<Member<MediaKeySystemMediaCapability>> result(
+ SafeCast<wtf_size_t>(capabilities.size()));
+ for (wtf_size_t i = 0; i < result.size(); i++) {
+ MediaKeySystemMediaCapability* capability =
+ MediaKeySystemMediaCapability::Create();
+ capability->setContentType(capabilities[i].content_type);
+ capability->setRobustness(capabilities[i].robustness);
switch (capabilities[i].encryption_scheme) {
case WebMediaKeySystemMediaCapability::EncryptionScheme::kNotSpecified:
- capability.setEncryptionSchemeToNull();
+ capability->setEncryptionSchemeToNull();
break;
case WebMediaKeySystemMediaCapability::EncryptionScheme::kCenc:
- capability.setEncryptionScheme("cenc");
+ capability->setEncryptionScheme("cenc");
break;
case WebMediaKeySystemMediaCapability::EncryptionScheme::kCbcs:
- capability.setEncryptionScheme("cbcs");
+ capability->setEncryptionScheme("cbcs");
break;
}
@@ -102,25 +105,10 @@ static HeapVector<MediaKeySystemMediaCapability> ConvertCapabilities(
return result;
}
-static String ConvertMediaKeysRequirement(
- WebMediaKeySystemConfiguration::Requirement requirement) {
- switch (requirement) {
- case WebMediaKeySystemConfiguration::Requirement::kRequired:
- return "required";
- case WebMediaKeySystemConfiguration::Requirement::kOptional:
- return "optional";
- case WebMediaKeySystemConfiguration::Requirement::kNotAllowed:
- return "not-allowed";
- }
-
- NOTREACHED();
- return "not-allowed";
-}
-
static Vector<String> ConvertSessionTypes(
const WebVector<WebEncryptedMediaSessionType>& session_types) {
- Vector<String> result(session_types.size());
- for (size_t i = 0; i < session_types.size(); i++)
+ Vector<String> result(SafeCast<wtf_size_t>(session_types.size()));
+ for (wtf_size_t i = 0; i < result.size(); i++)
result[i] = EncryptedMediaUtils::ConvertFromSessionType(session_types[i]);
return result;
}
@@ -128,38 +116,39 @@ static Vector<String> ConvertSessionTypes(
} // namespace
MediaKeySystemAccess::MediaKeySystemAccess(
- const String& key_system,
std::unique_ptr<WebContentDecryptionModuleAccess> access)
- : key_system_(key_system), access_(std::move(access)) {}
+ : access_(std::move(access)) {}
MediaKeySystemAccess::~MediaKeySystemAccess() = default;
-void MediaKeySystemAccess::getConfiguration(
- MediaKeySystemConfiguration& result) {
+MediaKeySystemConfiguration* MediaKeySystemAccess::getConfiguration() const {
WebMediaKeySystemConfiguration configuration = access_->GetConfiguration();
-
+ MediaKeySystemConfiguration* result = MediaKeySystemConfiguration::Create();
// |initDataTypes|, |audioCapabilities|, and |videoCapabilities| can only be
// empty if they were not present in the requested configuration.
if (!configuration.init_data_types.IsEmpty())
- result.setInitDataTypes(
+ result->setInitDataTypes(
ConvertInitDataTypes(configuration.init_data_types));
if (!configuration.audio_capabilities.IsEmpty())
- result.setAudioCapabilities(
+ result->setAudioCapabilities(
ConvertCapabilities(configuration.audio_capabilities));
if (!configuration.video_capabilities.IsEmpty())
- result.setVideoCapabilities(
+ result->setVideoCapabilities(
ConvertCapabilities(configuration.video_capabilities));
// |distinctiveIdentifier|, |persistentState|, and |sessionTypes| are always
// set by requestMediaKeySystemAccess().
- result.setDistinctiveIdentifier(
- ConvertMediaKeysRequirement(configuration.distinctive_identifier));
- result.setPersistentState(
- ConvertMediaKeysRequirement(configuration.persistent_state));
- result.setSessionTypes(ConvertSessionTypes(configuration.session_types));
+ result->setDistinctiveIdentifier(
+ EncryptedMediaUtils::ConvertMediaKeysRequirementToString(
+ configuration.distinctive_identifier));
+ result->setPersistentState(
+ EncryptedMediaUtils::ConvertMediaKeysRequirementToString(
+ configuration.persistent_state));
+ result->setSessionTypes(ConvertSessionTypes(configuration.session_types));
// |label| will (and should) be a null string if it was not set.
- result.setLabel(configuration.label);
+ result->setLabel(configuration.label);
+ return result;
}
ScriptPromise MediaKeySystemAccess::createMediaKeys(ScriptState* script_state) {
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.h
index 82e699bdbfa..eb17819ab69 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.h
@@ -18,16 +18,15 @@ class MediaKeySystemAccess final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- MediaKeySystemAccess(const String& key_system,
- std::unique_ptr<WebContentDecryptionModuleAccess>);
+ explicit MediaKeySystemAccess(
+ std::unique_ptr<WebContentDecryptionModuleAccess>);
~MediaKeySystemAccess() override;
- const String& keySystem() const { return key_system_; }
- void getConfiguration(MediaKeySystemConfiguration& result);
+ String keySystem() const { return access_->GetKeySystem(); }
+ MediaKeySystemConfiguration* getConfiguration() const;
ScriptPromise createMediaKeys(ScriptState*);
private:
- const String key_system_;
std::unique_ptr<WebContentDecryptionModuleAccess> access_;
};
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc
index 110d58bb9c0..343c0d003db 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc
@@ -77,30 +77,30 @@ class MediaKeys::PendingAction final
DOMArrayBuffer* server_certificate) {
DCHECK(result);
DCHECK(server_certificate);
- return new PendingAction(Type::kSetServerCertificate, result,
- server_certificate, String());
+ return MakeGarbageCollected<PendingAction>(
+ Type::kSetServerCertificate, result, server_certificate, String());
}
static PendingAction* CreatePendingGetStatusForPolicy(
ContentDecryptionModuleResult* result,
const String& min_hdcp_version) {
DCHECK(result);
- return new PendingAction(Type::kGetStatusForPolicy, result, nullptr,
- min_hdcp_version);
+ return MakeGarbageCollected<PendingAction>(
+ Type::kGetStatusForPolicy, result, nullptr, min_hdcp_version);
}
- void Trace(blink::Visitor* visitor) {
- visitor->Trace(result_);
- visitor->Trace(data_);
- }
-
- private:
PendingAction(Type type,
ContentDecryptionModuleResult* result,
DOMArrayBuffer* data,
const String& string_data)
: type_(type), result_(result), data_(data), string_data_(string_data) {}
+ void Trace(blink::Visitor* visitor) {
+ visitor->Trace(result_);
+ visitor->Trace(data_);
+ }
+
+ private:
const Type type_;
const Member<ContentDecryptionModuleResult> result_;
const Member<DOMArrayBuffer> data_;
@@ -204,7 +204,8 @@ MediaKeys* MediaKeys::Create(
ExecutionContext* context,
const WebVector<WebEncryptedMediaSessionType>& supported_session_types,
std::unique_ptr<WebContentDecryptionModule> cdm) {
- return new MediaKeys(context, supported_session_types, std::move(cdm));
+ return MakeGarbageCollected<MediaKeys>(context, supported_session_types,
+ std::move(cdm));
}
MediaKeys::MediaKeys(
@@ -303,8 +304,9 @@ ScriptPromise MediaKeys::setServerCertificate(
server_certificate.Data(), server_certificate.ByteLength());
// 4. Let promise be a new promise.
- SetCertificateResultPromise* result = new SetCertificateResultPromise(
- script_state, this, "MediaKeys", "setServerCertificate");
+ SetCertificateResultPromise* result =
+ MakeGarbageCollected<SetCertificateResultPromise>(
+ script_state, this, "MediaKeys", "setServerCertificate");
ScriptPromise promise = result->Promise();
// 5. Run the following steps asynchronously. See SetServerCertificateTask().
@@ -338,14 +340,15 @@ void MediaKeys::SetServerCertificateTask(
ScriptPromise MediaKeys::getStatusForPolicy(
ScriptState* script_state,
- const MediaKeysPolicy& media_keys_policy) {
+ const MediaKeysPolicy* media_keys_policy) {
// TODO(xhwang): Pass MediaKeysPolicy classes all the way to Chromium when
// we have more than one policy to check.
- String min_hdcp_version = media_keys_policy.minHdcpVersion();
+ String min_hdcp_version = media_keys_policy->minHdcpVersion();
// Let promise be a new promise.
- GetStatusForPolicyResultPromise* result = new GetStatusForPolicyResultPromise(
- script_state, this, "MediaKeys", "getStatusForPolicy");
+ GetStatusForPolicyResultPromise* result =
+ MakeGarbageCollected<GetStatusForPolicyResultPromise>(
+ script_state, this, "MediaKeys", "getStatusForPolicy");
ScriptPromise promise = result->Promise();
// Run the following steps asynchronously. See GetStatusForPolicyTask().
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.h
index d01f25741a7..63bc4a6ad83 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys.h
@@ -63,6 +63,11 @@ class MediaKeys : public ScriptWrappable,
ExecutionContext*,
const WebVector<WebEncryptedMediaSessionType>& supported_session_types,
std::unique_ptr<WebContentDecryptionModule>);
+
+ MediaKeys(
+ ExecutionContext*,
+ const WebVector<WebEncryptedMediaSessionType>& supported_session_types,
+ std::unique_ptr<WebContentDecryptionModule>);
~MediaKeys() override;
MediaKeySession* createSession(ScriptState*,
@@ -72,7 +77,7 @@ class MediaKeys : public ScriptWrappable,
ScriptPromise setServerCertificate(ScriptState*,
const DOMArrayPiece& server_certificate);
- ScriptPromise getStatusForPolicy(ScriptState*, const MediaKeysPolicy&);
+ ScriptPromise getStatusForPolicy(ScriptState*, const MediaKeysPolicy*);
// Indicates that the provided HTMLMediaElement wants to use this object.
// Returns true if no other HTMLMediaElement currently references this
@@ -103,10 +108,6 @@ class MediaKeys : public ScriptWrappable,
bool HasPendingActivity() const final;
private:
- MediaKeys(
- ExecutionContext*,
- const WebVector<WebEncryptedMediaSessionType>& supported_session_types,
- std::unique_ptr<WebContentDecryptionModule>);
class PendingAction;
void SetServerCertificateTask(DOMArrayBuffer* server_certificate,
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.cc
index 959fa7196eb..db835f6bb53 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.cc
@@ -25,7 +25,8 @@ WebEncryptedMediaClient* MediaKeysController::EncryptedMediaClient(
}
void MediaKeysController::ProvideMediaKeysTo(Page& page) {
- MediaKeysController::ProvideTo(page, new MediaKeysController());
+ MediaKeysController::ProvideTo(page,
+ MakeGarbageCollected<MediaKeysController>());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h
index d72a1d37543..84679be99f3 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h
@@ -28,12 +28,11 @@ class MODULES_EXPORT MediaKeysController final
return Supplement<Page>::From<MediaKeysController>(page);
}
+ MediaKeysController();
+
void Trace(blink::Visitor* visitor) override {
Supplement<Page>::Trace(visitor);
}
-
- private:
- MediaKeysController();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.cc
index 68eab6d565a..c948f26aebc 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.cc
@@ -14,7 +14,7 @@ namespace blink {
ScriptPromise MediaKeysGetStatusForPolicy::getStatusForPolicy(
ScriptState* script_state,
MediaKeys& media_keys,
- const MediaKeysPolicy& media_keys_policy) {
+ const MediaKeysPolicy* media_keys_policy) {
DVLOG(1) << __func__;
return media_keys.getStatusForPolicy(script_state, media_keys_policy);
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.h
index 420c90ed220..57b1e568b0d 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/media_keys_get_status_for_policy.h
@@ -17,7 +17,7 @@ class MediaKeysGetStatusForPolicy {
public:
static ScriptPromise getStatusForPolicy(ScriptState*,
MediaKeys&,
- const MediaKeysPolicy&);
+ const MediaKeysPolicy*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.cc b/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.cc
index 9f9702555d5..9ac6db76044 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.cc
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.cc
@@ -47,7 +47,7 @@ const char kEncryptedMediaFeaturePolicyConsoleWarning[] =
static WebVector<WebEncryptedMediaInitDataType> ConvertInitDataTypes(
const Vector<String>& init_data_types) {
WebVector<WebEncryptedMediaInitDataType> result(init_data_types.size());
- for (size_t i = 0; i < init_data_types.size(); ++i)
+ for (wtf_size_t i = 0; i < init_data_types.size(); ++i)
result[i] = EncryptedMediaUtils::ConvertToInitDataType(init_data_types[i]);
return result;
}
@@ -64,10 +64,10 @@ ConvertEncryptionScheme(const String& encryption_scheme) {
}
static WebVector<WebMediaKeySystemMediaCapability> ConvertCapabilities(
- const HeapVector<MediaKeySystemMediaCapability>& capabilities) {
+ const HeapVector<Member<MediaKeySystemMediaCapability>>& capabilities) {
WebVector<WebMediaKeySystemMediaCapability> result(capabilities.size());
- for (size_t i = 0; i < capabilities.size(); ++i) {
- const WebString& content_type = capabilities[i].contentType();
+ for (wtf_size_t i = 0; i < capabilities.size(); ++i) {
+ const WebString& content_type = capabilities[i]->contentType();
result[i].content_type = content_type;
ParsedContentType type(content_type);
if (type.IsValid() && !type.GetParameters().HasDuplicatedNames()) {
@@ -82,7 +82,7 @@ static WebVector<WebMediaKeySystemMediaCapability> ConvertCapabilities(
if (type.GetParameters().ParameterCount() == 1u)
result[i].codecs = type.ParameterValueForName("codecs");
}
- result[i].robustness = capabilities[i].robustness();
+ result[i].robustness = capabilities[i]->robustness();
// From
// https://github.com/WICG/encrypted-media-encryption-scheme/blob/master/explainer.md
@@ -91,31 +91,17 @@ static WebVector<WebMediaKeySystemMediaCapability> ConvertCapabilities(
// Applications which ignore this feature by leaving encryptionScheme null
// get the same user agent behavior they did before this feature existed."
result[i].encryption_scheme =
- capabilities[i].hasEncryptionScheme()
- ? ConvertEncryptionScheme(capabilities[i].encryptionScheme())
+ capabilities[i]->hasEncryptionScheme()
+ ? ConvertEncryptionScheme(capabilities[i]->encryptionScheme())
: WebMediaKeySystemMediaCapability::EncryptionScheme::kNotSpecified;
}
return result;
}
-static WebMediaKeySystemConfiguration::Requirement ConvertMediaKeysRequirement(
- const String& requirement) {
- if (requirement == "required")
- return WebMediaKeySystemConfiguration::Requirement::kRequired;
- if (requirement == "optional")
- return WebMediaKeySystemConfiguration::Requirement::kOptional;
- if (requirement == "not-allowed")
- return WebMediaKeySystemConfiguration::Requirement::kNotAllowed;
-
- // Everything else gets the default value.
- NOTREACHED();
- return WebMediaKeySystemConfiguration::Requirement::kOptional;
-}
-
static WebVector<WebEncryptedMediaSessionType> ConvertSessionTypes(
const Vector<String>& session_types) {
WebVector<WebEncryptedMediaSessionType> result(session_types.size());
- for (size_t i = 0; i < session_types.size(); ++i)
+ for (wtf_size_t i = 0; i < session_types.size(); ++i)
result[i] = EncryptedMediaUtils::ConvertToSessionType(session_types[i]);
return result;
}
@@ -129,7 +115,8 @@ class MediaKeySystemAccessInitializer final : public EncryptedMediaRequest {
MediaKeySystemAccessInitializer(
ScriptState*,
const String& key_system,
- const HeapVector<MediaKeySystemConfiguration>& supported_configurations);
+ const HeapVector<Member<MediaKeySystemConfiguration>>&
+ supported_configurations);
~MediaKeySystemAccessInitializer() override = default;
// EncryptedMediaRequest implementation.
@@ -166,35 +153,38 @@ class MediaKeySystemAccessInitializer final : public EncryptedMediaRequest {
MediaKeySystemAccessInitializer::MediaKeySystemAccessInitializer(
ScriptState* script_state,
const String& key_system,
- const HeapVector<MediaKeySystemConfiguration>& supported_configurations)
+ const HeapVector<Member<MediaKeySystemConfiguration>>&
+ supported_configurations)
: resolver_(ScriptPromiseResolver::Create(script_state)),
key_system_(key_system),
supported_configurations_(supported_configurations.size()) {
- for (size_t i = 0; i < supported_configurations.size(); ++i) {
- const MediaKeySystemConfiguration& config = supported_configurations[i];
+ for (wtf_size_t i = 0; i < supported_configurations.size(); ++i) {
+ const MediaKeySystemConfiguration* config = supported_configurations[i];
WebMediaKeySystemConfiguration web_config;
- DCHECK(config.hasInitDataTypes());
- web_config.init_data_types = ConvertInitDataTypes(config.initDataTypes());
+ DCHECK(config->hasInitDataTypes());
+ web_config.init_data_types = ConvertInitDataTypes(config->initDataTypes());
- DCHECK(config.hasAudioCapabilities());
+ DCHECK(config->hasAudioCapabilities());
web_config.audio_capabilities =
- ConvertCapabilities(config.audioCapabilities());
+ ConvertCapabilities(config->audioCapabilities());
- DCHECK(config.hasVideoCapabilities());
+ DCHECK(config->hasVideoCapabilities());
web_config.video_capabilities =
- ConvertCapabilities(config.videoCapabilities());
+ ConvertCapabilities(config->videoCapabilities());
- DCHECK(config.hasDistinctiveIdentifier());
+ DCHECK(config->hasDistinctiveIdentifier());
web_config.distinctive_identifier =
- ConvertMediaKeysRequirement(config.distinctiveIdentifier());
+ EncryptedMediaUtils::ConvertToMediaKeysRequirement(
+ config->distinctiveIdentifier());
- DCHECK(config.hasPersistentState());
+ DCHECK(config->hasPersistentState());
web_config.persistent_state =
- ConvertMediaKeysRequirement(config.persistentState());
+ EncryptedMediaUtils::ConvertToMediaKeysRequirement(
+ config->persistentState());
- if (config.hasSessionTypes()) {
- web_config.session_types = ConvertSessionTypes(config.sessionTypes());
+ if (config->hasSessionTypes()) {
+ web_config.session_types = ConvertSessionTypes(config->sessionTypes());
} else {
// From the spec
// (http://w3c.github.io/encrypted-media/#idl-def-mediakeysystemconfiguration):
@@ -208,7 +198,7 @@ MediaKeySystemAccessInitializer::MediaKeySystemAccessInitializer(
}
// If |label| is not present, it will be a null string.
- web_config.label = config.label();
+ web_config.label = config->label();
supported_configurations_[i] = web_config;
}
@@ -228,7 +218,7 @@ void MediaKeySystemAccessInitializer::RequestSucceeded(
return;
resolver_->Resolve(
- new MediaKeySystemAccess(key_system_, base::WrapUnique(access)));
+ MakeGarbageCollected<MediaKeySystemAccess>(base::WrapUnique(access)));
resolver_.Clear();
}
@@ -296,7 +286,8 @@ ScriptPromise NavigatorRequestMediaKeySystemAccess::requestMediaKeySystemAccess(
ScriptState* script_state,
Navigator& navigator,
const String& key_system,
- const HeapVector<MediaKeySystemConfiguration>& supported_configurations) {
+ const HeapVector<Member<MediaKeySystemConfiguration>>&
+ supported_configurations) {
DVLOG(3) << __func__;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
diff --git a/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.h b/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.h
index 9096edd811d..cce5d48f045 100644
--- a/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.h
+++ b/chromium/third_party/blink/renderer/modules/encryptedmedia/navigator_request_media_key_system_access.h
@@ -22,7 +22,8 @@ class NavigatorRequestMediaKeySystemAccess {
ScriptState*,
Navigator&,
const String& key_system,
- const HeapVector<MediaKeySystemConfiguration>& supported_configurations);
+ const HeapVector<Member<MediaKeySystemConfiguration>>&
+ supported_configurations);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/event_modules.h b/chromium/third_party/blink/renderer/modules/event_modules.h
index df2229c5334..2aa905288f2 100644
--- a/chromium/third_party/blink/renderer/modules/event_modules.h
+++ b/chromium/third_party/blink/renderer/modules/event_modules.h
@@ -6,6 +6,6 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_EVENT_MODULES_H_
#include "third_party/blink/renderer/core/dom/events/event.h"
-#include "third_party/blink/renderer/modules/event_modules_names.h"
+#include "third_party/blink/renderer/modules/event_interface_modules_names.h"
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_EVENT_MODULES_H_
diff --git a/chromium/third_party/blink/renderer/modules/event_target_modules.h b/chromium/third_party/blink/renderer/modules/event_target_modules.h
index 30c153bc14b..f5679b90c4c 100644
--- a/chromium/third_party/blink/renderer/modules/event_target_modules.h
+++ b/chromium/third_party/blink/renderer/modules/event_target_modules.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_EVENT_TARGET_MODULES_H_
#include "third_party/blink/renderer/core/dom/events/event_target.h"
-#include "third_party/blink/renderer/modules/event_modules_names.h"
+#include "third_party/blink/renderer/modules/event_interface_modules_names.h"
#include "third_party/blink/renderer/modules/event_target_modules_names.h"
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_EVENT_TARGET_MODULES_H_
diff --git a/chromium/third_party/blink/renderer/modules/event_target_modules_names.json5 b/chromium/third_party/blink/renderer/modules/event_target_modules_names.json5
index dc4b6094fd4..3f5aec4821b 100644
--- a/chromium/third_party/blink/renderer/modules/event_target_modules_names.json5
+++ b/chromium/third_party/blink/renderer/modules/event_target_modules_names.json5
@@ -1,71 +1,75 @@
{
metadata: {
- namespace: "EventTarget",
+ namespace: "event_target_names",
suffix: "Modules",
},
+ # You don't need to specify ImplementedAs even though an interface name and
+ # its C++ class name don't match. You need to specify ImplementedAs only if
+ # you'd like to change recorded names in ActivityLogger.
data: [
- "modules/background_fetch/BackgroundFetchRegistration",
- "modules/battery/BatteryManager",
- "modules/bluetooth/BluetoothDevice",
- "modules/bluetooth/BluetoothRemoteGATTCharacteristic",
- "modules/cookiestore/CookieStore",
- "modules/encryptedmedia/MediaKeySession",
- "modules/filesystem/FileWriter",
- "modules/imagecapture/ImageCapture",
- "modules/indexeddb/IDBDatabase",
- "modules/indexeddb/IDBOpenDBRequest",
- "modules/indexeddb/IDBRequest",
- "modules/indexeddb/IDBTransaction",
- "modules/mediarecorder/MediaRecorder",
- "modules/mediasource/MediaSource",
- "modules/mediasource/SourceBuffer",
- "modules/mediasource/SourceBufferList",
- "modules/mediastream/MediaDevices",
- "modules/mediastream/MediaStream",
- "modules/mediastream/MediaStreamTrack",
- "modules/mediastream/RTCDTMFSender",
- "modules/mediastream/RTCDataChannel",
- "modules/mediastream/RTCPeerConnection",
- "modules/netinfo/NetworkInformation",
- "modules/notifications/Notification",
- "modules/payments/PaymentRequest",
- "modules/peerconnection/RTCIceTransport",
- "modules/peerconnection/RTCQuicStream",
- "modules/peerconnection/RTCQuicTransport",
- "modules/permissions/PermissionStatus",
- "modules/picture_in_picture/HTMLVideoElementPictureInPicture",
- "modules/picture_in_picture/PictureInPictureWindow",
- "modules/presentation/PresentationAvailability",
- "modules/presentation/PresentationConnection",
- "modules/presentation/PresentationConnectionList",
- "modules/presentation/PresentationRequest",
- "modules/remoteplayback/RemotePlayback",
- "modules/screen_orientation/ScreenOrientation",
- "modules/sensor/Sensor",
- "modules/serial/Serial",
- "modules/service_worker/ServiceWorker",
- "modules/service_worker/ServiceWorkerContainer",
- "modules/service_worker/ServiceWorkerGlobalScope",
- "modules/service_worker/ServiceWorkerRegistration",
- "modules/speech/SpeechRecognition",
- "modules/speech/SpeechSynthesis",
- "modules/speech/SpeechSynthesisUtterance",
- "modules/vr/VRDisplay",
- "modules/wake_lock/WakeLock",
- "modules/wake_lock/WakeLockRequest",
- "modules/webaudio/AudioContext",
- "modules/webaudio/AudioNode",
- "modules/webmidi/MIDIAccess",
- "modules/webmidi/MIDIInput",
- "modules/webmidi/MIDIPort",
- "modules/xr/XR",
- "modules/xr/XRCoordinateSystem",
- "modules/xr/XRSession",
+ "BackgroundFetchRegistration",
+ "BatteryManager",
+ "BluetoothDevice",
+ "BluetoothRemoteGATTCharacteristic",
+ "CookieStore",
+ "MediaKeySession",
+ "FileWriter",
+ "ImageCapture",
+ "IDBDatabase",
+ "IDBOpenDBRequest",
+ "IDBRequest",
+ "IDBTransaction",
+ "MediaRecorder",
+ "MediaSource",
+ "SourceBuffer",
+ "SourceBufferList",
+ "MediaDevices",
+ "MediaStream",
+ "MediaStreamTrack",
+ "RTCDTMFSender",
+ "RTCDataChannel",
+ "RTCDtlsTransport",
+ "RTCPeerConnection",
+ "NetworkInformation",
+ "Notification",
+ "PaymentRequest",
+ "RTCIceTransport",
+ "RTCQuicStream",
+ "RTCQuicTransport",
+ "PermissionStatus",
+ "HTMLVideoElementPictureInPicture",
+ "PictureInPictureWindow",
+ "PresentationAvailability",
+ "PresentationConnection",
+ "PresentationConnectionList",
+ "PresentationRequest",
+ "RemotePlayback",
+ "ScreenOrientation",
+ "Sensor",
+ "Serial",
+ "ServiceWorker",
+ "ServiceWorkerContainer",
+ "ServiceWorkerGlobalScope",
+ "ServiceWorkerRegistration",
+ "SpeechRecognition",
+ "SpeechSynthesis",
+ "SpeechSynthesisUtterance",
+ "VRDisplay",
+ "WakeLock",
+ "WakeLockRequest",
+ "AudioContext",
+ "AudioNode",
+ "MIDIAccess",
+ "MIDIInput",
+ "MIDIPort",
+ "XR",
+ "XRCoordinateSystem",
+ "XRSession",
{
- name: "modules/websockets/WebSocket",
+ name: "WebSocket",
ImplementedAs: "DOMWebSocket",
},
- "modules/webusb/USB",
+ "USB",
],
}
diff --git a/chromium/third_party/blink/renderer/modules/eventsource/event_source.cc b/chromium/third_party/blink/renderer/modules/eventsource/event_source.cc
index 90eff457dd4..0b27bcaeb16 100644
--- a/chromium/third_party/blink/renderer/modules/eventsource/event_source.cc
+++ b/chromium/third_party/blink/renderer/modules/eventsource/event_source.cc
@@ -64,11 +64,11 @@ const unsigned long long EventSource::kDefaultReconnectDelay = 3000;
inline EventSource::EventSource(ExecutionContext* context,
const KURL& url,
- const EventSourceInit& event_source_init)
+ const EventSourceInit* event_source_init)
: ContextLifecycleObserver(context),
url_(url),
current_url_(url),
- with_credentials_(event_source_init.withCredentials()),
+ with_credentials_(event_source_init->withCredentials()),
state_(kConnecting),
connect_timer_(context->GetTaskRunner(TaskType::kRemoteEvent),
this,
@@ -77,7 +77,7 @@ inline EventSource::EventSource(ExecutionContext* context,
EventSource* EventSource::Create(ExecutionContext* context,
const String& url,
- const EventSourceInit& event_source_init,
+ const EventSourceInit* event_source_init,
ExceptionState& exception_state) {
UseCounter::Count(context, IsA<Document>(context)
? WebFeature::kEventSourceDocument
@@ -98,7 +98,8 @@ EventSource* EventSource::Create(ExecutionContext* context,
return nullptr;
}
- EventSource* source = new EventSource(context, full_url, event_source_init);
+ EventSource* source =
+ MakeGarbageCollected<EventSource>(context, full_url, event_source_init);
source->ScheduleInitialConnect();
return source;
@@ -123,19 +124,19 @@ void EventSource::Connect() {
ExecutionContext& execution_context = *this->GetExecutionContext();
ResourceRequest request(current_url_);
- request.SetHTTPMethod(HTTPNames::GET);
- request.SetHTTPHeaderField(HTTPNames::Accept, "text/event-stream");
- request.SetHTTPHeaderField(HTTPNames::Cache_Control, "no-cache");
+ request.SetHTTPMethod(http_names::kGET);
+ request.SetHTTPHeaderField(http_names::kAccept, "text/event-stream");
+ request.SetHTTPHeaderField(http_names::kCacheControl, "no-cache");
request.SetRequestContext(mojom::RequestContextType::EVENT_SOURCE);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCORS);
+ request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
request.SetFetchCredentialsMode(
with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
: network::mojom::FetchCredentialsMode::kSameOrigin);
request.SetCacheMode(blink::mojom::FetchCacheMode::kNoStore);
request.SetExternalRequestStateFromRequestorAddressSpace(
execution_context.GetSecurityContext().AddressSpace());
- request.SetCORSPreflightPolicy(
- network::mojom::CORSPreflightPolicy::kPreventPreflight);
+ request.SetCorsPreflightPolicy(
+ network::mojom::CorsPreflightPolicy::kPreventPreflight);
if (parser_ && !parser_->LastEventId().IsEmpty()) {
// HTTP headers are Latin-1 byte strings, but the Last-Event-ID header is
// encoded as UTF-8.
@@ -143,7 +144,7 @@ void EventSource::Connect() {
// setHTTPHeaderField's arguments.
CString last_event_id_utf8 = parser_->LastEventId().Utf8();
request.SetHTTPHeaderField(
- HTTPNames::Last_Event_ID,
+ http_names::kLastEventID,
AtomicString(reinterpret_cast<const LChar*>(last_event_id_utf8.data()),
last_event_id_utf8.length()));
}
@@ -152,8 +153,8 @@ void EventSource::Connect() {
resource_loader_options.data_buffering_policy = kDoNotBufferData;
probe::willSendEventSourceRequest(&execution_context, this);
- loader_ =
- new ThreadableLoader(execution_context, this, resource_loader_options);
+ loader_ = MakeGarbageCollected<ThreadableLoader>(execution_context, this,
+ resource_loader_options);
loader_->Start(request);
}
@@ -168,7 +169,7 @@ void EventSource::ScheduleReconnect() {
state_ = kConnecting;
connect_timer_.StartOneShot(TimeDelta::FromMilliseconds(reconnect_delay_),
FROM_HERE);
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
void EventSource::ConnectTimerFired(TimerBase*) {
@@ -211,7 +212,7 @@ void EventSource::close() {
}
const AtomicString& EventSource::InterfaceName() const {
- return EventTargetNames::EventSource;
+ return event_target_names::kEventSource;
}
ExecutionContext* EventSource::GetExecutionContext() const {
@@ -268,8 +269,8 @@ void EventSource::DidReceiveResponse(
// The new parser takes over the event ID.
last_event_id = parser_->LastEventId();
}
- parser_ = new EventSourceParser(last_event_id, this);
- DispatchEvent(*Event::Create(EventTypeNames::open));
+ parser_ = MakeGarbageCollected<EventSourceParser>(last_event_id, this);
+ DispatchEvent(*Event::Create(event_type_names::kOpen));
} else {
loader_->Cancel();
}
@@ -343,7 +344,7 @@ void EventSource::AbortConnectionAttempt() {
state_ = kClosed;
NetworkRequestEnded();
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
void EventSource::ContextDestroyed(ExecutionContext*) {
@@ -358,6 +359,7 @@ void EventSource::Trace(blink::Visitor* visitor) {
visitor->Trace(parser_);
visitor->Trace(loader_);
EventTargetWithInlineData::Trace(visitor);
+ ThreadableLoaderClient::Trace(visitor);
ContextLifecycleObserver::Trace(visitor);
EventSourceParser::Client::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/eventsource/event_source.h b/chromium/third_party/blink/renderer/modules/eventsource/event_source.h
index f31cee8c42f..d3ac4b4d8b5 100644
--- a/chromium/third_party/blink/renderer/modules/eventsource/event_source.h
+++ b/chromium/third_party/blink/renderer/modules/eventsource/event_source.h
@@ -53,7 +53,7 @@ class ResourceResponse;
class MODULES_EXPORT EventSource final
: public EventTargetWithInlineData,
- private ThreadableLoaderClient,
+ public ThreadableLoaderClient,
public ActiveScriptWrappable<EventSource>,
public ContextLifecycleObserver,
public EventSourceParser::Client {
@@ -63,8 +63,10 @@ class MODULES_EXPORT EventSource final
public:
static EventSource* Create(ExecutionContext*,
const String& url,
- const EventSourceInit&,
+ const EventSourceInit*,
ExceptionState&);
+
+ EventSource(ExecutionContext*, const KURL&, const EventSourceInit*);
~EventSource() override;
static const unsigned long long kDefaultReconnectDelay;
@@ -76,9 +78,9 @@ class MODULES_EXPORT EventSource final
State readyState() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(open);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(open, kOpen);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
void close();
@@ -100,8 +102,6 @@ class MODULES_EXPORT EventSource final
void Trace(blink::Visitor*) override;
private:
- EventSource(ExecutionContext*, const KURL&, const EventSourceInit&);
-
void DidReceiveResponse(unsigned long,
const ResourceResponse&,
std::unique_ptr<WebDataConsumerHandle>) override;
diff --git a/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser.cc b/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser.cc
index 39b80f10bec..6f1506f1188 100644
--- a/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser.cc
+++ b/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser.cc
@@ -70,8 +70,8 @@ void EventSourceParser::ParseLine() {
DCHECK_EQ(data_[data_.size() - 1], '\n');
String data = FromUTF8(data_.data(), data_.size() - 1);
client_->OnMessageEvent(
- event_type_.IsEmpty() ? EventTypeNames::message : event_type_, data,
- last_event_id_);
+ event_type_.IsEmpty() ? event_type_names::kMessage : event_type_,
+ data, last_event_id_);
data_.clear();
}
event_type_ = g_null_atom;
diff --git a/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser_test.cc b/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser_test.cc
index 2370a04f252..ab1db0f3b3e 100644
--- a/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser_test.cc
+++ b/chromium/third_party/blink/renderer/modules/eventsource/event_source_parser_test.cc
@@ -92,7 +92,8 @@ class EventSourceParserTest : public testing::Test {
using Type = EventOrReconnectionTimeSetting::Type;
EventSourceParserTest()
: client_(new Client),
- parser_(new EventSourceParser(AtomicString(), client_)) {}
+ parser_(
+ MakeGarbageCollected<EventSourceParser>(AtomicString(), client_)) {}
~EventSourceParserTest() override = default;
void Enqueue(const char* data) {
@@ -133,7 +134,7 @@ TEST_F(EventSourceParserTest, DispatchSimpleMessageEvent) {
}
TEST_F(EventSourceParserTest, ConstructWithLastEventId) {
- parser_ = new EventSourceParser("hoge", client_);
+ parser_ = MakeGarbageCollected<EventSourceParser>("hoge", client_);
EXPECT_EQ("hoge", Parser()->LastEventId());
Enqueue("data:hello\n\n");
@@ -376,7 +377,8 @@ TEST_F(EventSourceParserTest, InvalidUTF8Sequence) {
TEST(EventSourceParserStoppingTest, StopWhileParsing) {
StoppingClient* client = new StoppingClient();
- EventSourceParser* parser = new EventSourceParser(AtomicString(), client);
+ EventSourceParser* parser =
+ MakeGarbageCollected<EventSourceParser>(AtomicString(), client);
client->SetParser(parser);
const char kInput[] = "data:hello\nid:99\n\nid:44\ndata:bye\n\n";
diff --git a/chromium/third_party/blink/renderer/modules/exported/BUILD.gn b/chromium/third_party/blink/renderer/modules/exported/BUILD.gn
index e3030b08a39..bfc6251ccf7 100644
--- a/chromium/third_party/blink/renderer/modules/exported/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/exported/BUILD.gn
@@ -5,6 +5,7 @@ import("//third_party/blink/renderer/modules/modules.gni")
blink_modules_sources("exported") {
sources = [
+ "indexed_db_key_builder.cc",
"web_apply_constraints_request.cc",
"web_ax_context.cc",
"web_ax_object.cc",
@@ -16,7 +17,6 @@ blink_modules_sources("exported") {
"web_idb_key.cc",
"web_idb_key_range.cc",
"web_idb_value.cc",
- "web_media_stream_registry.cc",
"web_storage_event_dispatcher_impl.cc",
"web_user_media_request.cc",
]
diff --git a/chromium/third_party/blink/renderer/modules/exported/indexed_db_key_builder.cc b/chromium/third_party/blink/renderer/modules/exported/indexed_db_key_builder.cc
new file mode 100644
index 00000000000..8c2b8985925
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/exported/indexed_db_key_builder.cc
@@ -0,0 +1,201 @@
+// Copyright (c) 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+
+#include <stddef.h>
+
+#include <algorithm>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "third_party/blink/public/common/indexeddb/indexeddb_key_range.h"
+#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_path.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+
+namespace blink {
+
+namespace {
+
+IndexedDBKey::KeyArray CopyKeyArray(WebIDBKeyArrayView array) {
+ IndexedDBKey::KeyArray result;
+ const size_t array_size = array.size();
+ result.reserve(array_size);
+ for (size_t i = 0; i < array_size; ++i)
+ result.emplace_back(IndexedDBKeyBuilder::Build(array[i]));
+ return result;
+}
+
+std::vector<base::string16> CopyArray(const WebVector<WebString>& array) {
+ std::vector<base::string16> result;
+ result.reserve(array.size());
+ for (const WebString& element : array)
+ result.emplace_back(element.Utf16());
+ return result;
+}
+
+} // anonymous namespace
+
+// static
+IndexedDBKey IndexedDBKeyBuilder::Build(WebIDBKeyView key) {
+ switch (key.KeyType()) {
+ case kWebIDBKeyTypeArray:
+ return IndexedDBKey(CopyKeyArray(key.ArrayView()));
+ case kWebIDBKeyTypeBinary: {
+ const WebData data = key.Binary();
+ std::string key_string;
+ key_string.reserve(data.size());
+
+ data.ForEachSegment([&key_string](const char* segment,
+ size_t segment_size,
+ size_t segment_offset) {
+ key_string.append(segment, segment_size);
+ return true;
+ });
+ return IndexedDBKey(std::move(key_string));
+ }
+ case kWebIDBKeyTypeString:
+ return IndexedDBKey(key.String().Utf16());
+ case kWebIDBKeyTypeDate:
+ return IndexedDBKey(key.Date(), kWebIDBKeyTypeDate);
+ case kWebIDBKeyTypeNumber:
+ return IndexedDBKey(key.Number(), kWebIDBKeyTypeNumber);
+ case kWebIDBKeyTypeNull:
+ case kWebIDBKeyTypeInvalid:
+ return IndexedDBKey(key.KeyType());
+ case kWebIDBKeyTypeMin:
+ NOTREACHED();
+ return IndexedDBKey();
+ }
+}
+
+// static
+WebIDBKey WebIDBKeyBuilder::Build(const WebIDBKeyView& key) {
+ switch (key.KeyType()) {
+ case kWebIDBKeyTypeArray: {
+ const WebIDBKeyArrayView& array = key.ArrayView();
+ WebVector<WebIDBKey> web_idb_keys;
+ const size_t array_size = array.size();
+ web_idb_keys.reserve(array_size);
+ for (size_t i = 0; i < array_size; ++i)
+ web_idb_keys.emplace_back(Build(array[i]));
+ return WebIDBKey::CreateArray(std::move(web_idb_keys));
+ }
+ case kWebIDBKeyTypeBinary: {
+ const WebData data = key.Binary();
+ return WebIDBKey::CreateBinary(data);
+ }
+ case kWebIDBKeyTypeString:
+ return WebIDBKey::CreateString(key.String());
+ case kWebIDBKeyTypeDate:
+ return WebIDBKey::CreateDate(key.Date());
+ case kWebIDBKeyTypeNumber:
+ return WebIDBKey::CreateNumber(key.Number());
+ case kWebIDBKeyTypeInvalid:
+ return WebIDBKey::CreateInvalid();
+ case kWebIDBKeyTypeNull:
+ return WebIDBKey::CreateNull();
+ case kWebIDBKeyTypeMin:
+ NOTREACHED();
+ return WebIDBKey::CreateInvalid();
+ }
+}
+
+// static
+WebIDBKey WebIDBKeyBuilder::Build(const IndexedDBKey& key) {
+ switch (key.type()) {
+ case kWebIDBKeyTypeArray: {
+ const IndexedDBKey::KeyArray& array = key.array();
+ WebVector<WebIDBKey> web_idb_keys;
+ web_idb_keys.reserve(array.size());
+ for (const IndexedDBKey& array_element : array)
+ web_idb_keys.emplace_back(Build(array_element));
+ return WebIDBKey::CreateArray(std::move(web_idb_keys));
+ }
+ case kWebIDBKeyTypeBinary: {
+ const std::string& str = key.binary();
+ const WebData& data = WebData(str.c_str(), str.length());
+ return WebIDBKey::CreateBinary(data);
+ }
+ case kWebIDBKeyTypeString:
+ return WebIDBKey::CreateString(WebString::FromUTF16(key.string()));
+ case kWebIDBKeyTypeDate:
+ return WebIDBKey::CreateDate(key.date());
+ case kWebIDBKeyTypeNumber:
+ return WebIDBKey::CreateNumber(key.number());
+ case kWebIDBKeyTypeInvalid:
+ return WebIDBKey::CreateInvalid();
+ case kWebIDBKeyTypeNull:
+ return WebIDBKey::CreateNull();
+ case kWebIDBKeyTypeMin:
+ NOTREACHED();
+ return WebIDBKey::CreateInvalid();
+ }
+}
+
+// static
+IndexedDBKeyRange IndexedDBKeyRangeBuilder::Build(
+ const WebIDBKeyRange& key_range) {
+ return IndexedDBKeyRange(IndexedDBKeyBuilder::Build(key_range.Lower()),
+ IndexedDBKeyBuilder::Build(key_range.Upper()),
+ key_range.LowerOpen(), key_range.UpperOpen());
+}
+
+// static
+IndexedDBKeyRange IndexedDBKeyRangeBuilder::Build(WebIDBKeyView key) {
+ return IndexedDBKeyRange(IndexedDBKeyBuilder::Build(key),
+ IndexedDBKeyBuilder::Build(key),
+ false /* lower_open */, false /* upper_open */);
+}
+
+// static
+WebIDBKeyRange WebIDBKeyRangeBuilder::Build(WebIDBKeyView key) {
+ return WebIDBKeyRange(WebIDBKeyBuilder::Build(key),
+ WebIDBKeyBuilder::Build(key), false /* lower_open */,
+ false /* upper_open */);
+}
+
+// static
+WebIDBKeyRange WebIDBKeyRangeBuilder::Build(
+ const IndexedDBKeyRange& key_range) {
+ return WebIDBKeyRange(WebIDBKeyBuilder::Build(key_range.lower()),
+ WebIDBKeyBuilder::Build(key_range.upper()),
+ key_range.lower_open(), key_range.upper_open());
+}
+
+// static
+IndexedDBKeyPath IndexedDBKeyPathBuilder::Build(const WebIDBKeyPath& key_path) {
+ switch (key_path.KeyPathType()) {
+ case kWebIDBKeyPathTypeString:
+ return IndexedDBKeyPath(key_path.String().Utf16());
+ case kWebIDBKeyPathTypeArray:
+ return IndexedDBKeyPath(CopyArray(key_path.Array()));
+ case kWebIDBKeyPathTypeNull:
+ return IndexedDBKeyPath();
+ }
+}
+
+// static
+WebIDBKeyPath WebIDBKeyPathBuilder::Build(const IndexedDBKeyPath& key_path) {
+ switch (key_path.type()) {
+ case kWebIDBKeyPathTypeString:
+ return WebIDBKeyPath::Create(WebString::FromUTF16(key_path.string()));
+ case kWebIDBKeyPathTypeArray: {
+ WebVector<WebString> key_path_vector(key_path.array().size());
+ for (const auto& item : key_path.array())
+ key_path_vector.emplace_back(WebString::FromUTF16(item));
+ return WebIDBKeyPath::Create(key_path_vector);
+ }
+ case kWebIDBKeyPathTypeNull:
+ return WebIDBKeyPath::CreateNull();
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_ax_object.cc b/chromium/third_party/blink/renderer/modules/exported/web_ax_object.cc
index 4f763635342..4c2310dcaa8 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_ax_object.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_ax_object.cc
@@ -266,6 +266,13 @@ bool WebAXObject::IsControl() const {
return private_->IsControl();
}
+bool WebAXObject::IsDefault() const {
+ if (IsDetached())
+ return false;
+
+ return private_->IsDefault();
+}
+
WebAXRestriction WebAXObject::Restriction() const {
if (IsDetached())
return kWebAXRestrictionNone;
@@ -890,11 +897,11 @@ ax::mojom::TextPosition WebAXObject::GetTextPosition() const {
return private_->GetTextPosition();
}
-WebAXTextStyle WebAXObject::TextStyle() const {
+int WebAXObject::TextStyle() const {
if (IsDetached())
- return kWebAXTextStyleNone;
+ return 0;
- return static_cast<WebAXTextStyle>(private_->GetTextStyle());
+ return private_->GetTextStyle();
}
WebURL WebAXObject::Url() const {
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_dom_file_system.cc b/chromium/third_party/blink/renderer/modules/exported/web_dom_file_system.cc
index fed359691e4..3e72aa04ad7 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_dom_file_system.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_dom_file_system.cc
@@ -45,7 +45,7 @@
namespace blink {
WebDOMFileSystem WebDOMFileSystem::FromV8Value(v8::Local<v8::Value> value) {
- if (!V8DOMFileSystem::hasInstance(value, v8::Isolate::GetCurrent()))
+ if (!V8DOMFileSystem::HasInstance(value, v8::Isolate::GetCurrent()))
return WebDOMFileSystem();
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
DOMFileSystem* dom_file_system = V8DOMFileSystem::ToImpl(object);
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_dom_media_stream_track.cc b/chromium/third_party/blink/renderer/modules/exported/web_dom_media_stream_track.cc
index 71cd927f295..7c396a4c3c8 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_dom_media_stream_track.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_dom_media_stream_track.cc
@@ -40,7 +40,7 @@ WebDOMMediaStreamTrack::WebDOMMediaStreamTrack(MediaStreamTrack* track)
WebDOMMediaStreamTrack WebDOMMediaStreamTrack::FromV8Value(
v8::Local<v8::Value> value) {
- if (V8MediaStreamTrack::hasInstance(value, v8::Isolate::GetCurrent())) {
+ if (V8MediaStreamTrack::HasInstance(value, v8::Isolate::GetCurrent())) {
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
return WebDOMMediaStreamTrack(V8MediaStreamTrack::ToImpl(object));
}
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc b/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
index cd9cda55dd5..5bcb80cdff8 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
@@ -32,6 +32,7 @@
#include <memory>
#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider.h"
@@ -46,6 +47,7 @@
#include "third_party/blink/renderer/core/execution_context/security_context.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
@@ -55,7 +57,6 @@
#include "third_party/blink/renderer/core/workers/worker_classic_script_loader.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db_client.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.h"
@@ -65,10 +66,8 @@
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/substitute_data.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
-#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
@@ -123,7 +122,6 @@ WebEmbeddedWorkerImpl::WebEmbeddedWorkerImpl(
interface_provider_info)
: worker_context_client_(std::move(client)),
content_settings_client_(std::move(content_settings_client)),
- worker_inspector_proxy_(WorkerInspectorProxy::Create()),
pause_after_download_state_(kDontPauseAfterDownload),
waiting_for_debugger_state_(kNotWaitingForDebugger),
cache_storage_info_(std::move(cache_storage_info)),
@@ -169,7 +167,7 @@ void WebEmbeddedWorkerImpl::StartWorkerContext(
// https://crbug.com/590714
KURL script_url = worker_start_data_.script_url;
worker_start_data_.address_space = mojom::IPAddressSpace::kPublic;
- if (NetworkUtils::IsReservedIPAddress(script_url.Host()))
+ if (network_utils::IsReservedIPAddress(script_url.Host()))
worker_start_data_.address_space = mojom::IPAddressSpace::kPrivate;
if (SecurityOrigin::Create(script_url)->IsLocalhost())
worker_start_data_.address_space = mojom::IPAddressSpace::kLocal;
@@ -231,7 +229,8 @@ void WebEmbeddedWorkerImpl::TerminateWorkerContext() {
return;
}
worker_thread_->Terminate();
- worker_inspector_proxy_->WorkerThreadTerminated();
+ DevToolsAgent::WorkerThreadTerminated(shadow_page_->GetDocument(),
+ worker_thread_.get());
}
void WebEmbeddedWorkerImpl::ResumeAfterDownload() {
@@ -280,11 +279,6 @@ void WebEmbeddedWorkerImpl::BindDevToolsAgent(
std::move(devtools_agent_request)));
}
-void WebEmbeddedWorkerImpl::PostMessageToPageInspector(int session_id,
- const String& message) {
- worker_inspector_proxy_->DispatchMessageFromWorker(session_id, message);
-}
-
std::unique_ptr<WebApplicationCacheHost>
WebEmbeddedWorkerImpl::CreateApplicationCacheHost(
WebApplicationCacheHostClient*) {
@@ -310,16 +304,24 @@ void WebEmbeddedWorkerImpl::OnShadowPageInitialized() {
return;
}
+ // If this is a module service worker, start the worker thread now. The worker
+ // thread will fetch the script.
+ if (worker_start_data_.script_type == mojom::ScriptType::kModule) {
+ StartWorkerThread();
+ return;
+ }
+
// Note: We only get here if this is a new (i.e., not installed) service
// worker.
DCHECK(!main_script_loader_);
- main_script_loader_ = WorkerClassicScriptLoader::Create();
+ main_script_loader_ = MakeGarbageCollected<WorkerClassicScriptLoader>();
main_script_loader_->LoadTopLevelScriptAsynchronously(
*shadow_page_->GetDocument(), worker_start_data_.script_url,
mojom::RequestContextType::SERVICE_WORKER,
network::mojom::FetchRequestMode::kSameOrigin,
network::mojom::FetchCredentialsMode::kSameOrigin,
- worker_start_data_.address_space, base::OnceClosure(),
+ worker_start_data_.address_space, false /* is_nested_worker */,
+ base::OnceClosure(),
Bind(&WebEmbeddedWorkerImpl::OnScriptLoaderFinished,
WTF::Unretained(this)));
// Do nothing here since OnScriptLoaderFinished() might have been already
@@ -374,17 +376,13 @@ void WebEmbeddedWorkerImpl::StartWorkerThread() {
ProvideContentSettingsClientToWorker(worker_clients,
std::move(content_settings_client_));
ProvideServiceWorkerGlobalScopeClientToWorker(
- worker_clients,
- new ServiceWorkerGlobalScopeClient(*worker_context_client_));
+ worker_clients, MakeGarbageCollected<ServiceWorkerGlobalScopeClient>(
+ *worker_context_client_));
- std::unique_ptr<WebWorkerFetchContext> web_worker_fetch_context =
+ // |web_worker_fetch_context| is null in some unit tests.
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context =
worker_context_client_->CreateServiceWorkerFetchContext(
shadow_page_->DocumentLoader()->GetServiceWorkerNetworkProvider());
- // |web_worker_fetch_context| is null in some unit tests.
- if (web_worker_fetch_context) {
- ProvideWorkerFetchContextToWorker(worker_clients,
- std::move(web_worker_fetch_context));
- }
std::unique_ptr<WorkerSettings> worker_settings =
std::make_unique<WorkerSettings>(document->GetSettings());
@@ -393,28 +391,21 @@ void WebEmbeddedWorkerImpl::StartWorkerThread() {
String source_code;
std::unique_ptr<Vector<char>> cached_meta_data;
- // TODO(https://crbug.com/824647): Use blink::mojom::ScriptType everywhere
- // and deprecate blink::ScriptType.
- // Remove this line after removed all blink::ScriptType.
- ScriptType script_type =
- (worker_start_data_.script_type == mojom::ScriptType::kModule)
- ? ScriptType::kModule
- : ScriptType::kClassic;
-
// |main_script_loader_| isn't created if the InstalledScriptsManager had the
// script.
if (main_script_loader_) {
ContentSecurityPolicy* content_security_policy =
main_script_loader_->GetContentSecurityPolicy();
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
if (!main_script_loader_->GetReferrerPolicy().IsNull()) {
SecurityPolicy::ReferrerPolicyFromHeaderValue(
main_script_loader_->GetReferrerPolicy(),
kDoNotSupportReferrerPolicyLegacyKeywords, &referrer_policy);
}
global_scope_creation_params = std::make_unique<GlobalScopeCreationParams>(
- worker_start_data_.script_url, script_type,
- worker_start_data_.user_agent,
+ worker_start_data_.script_url, worker_start_data_.script_type,
+ worker_start_data_.user_agent, std::move(web_worker_fetch_context),
content_security_policy ? content_security_policy->Headers()
: Vector<CSPHeaderAndType>(),
referrer_policy, starter_origin, starter_secure_context,
@@ -432,10 +423,11 @@ void WebEmbeddedWorkerImpl::StartWorkerThread() {
// We don't have to set ContentSecurityPolicy and ReferrerPolicy. They're
// served by the installed scripts manager on the worker thread.
global_scope_creation_params = std::make_unique<GlobalScopeCreationParams>(
- worker_start_data_.script_url, script_type,
- worker_start_data_.user_agent, Vector<CSPHeaderAndType>(),
- kReferrerPolicyDefault, starter_origin, starter_secure_context,
- starter_https_state, worker_clients, worker_start_data_.address_space,
+ worker_start_data_.script_url, worker_start_data_.script_type,
+ worker_start_data_.user_agent, std::move(web_worker_fetch_context),
+ Vector<CSPHeaderAndType>(), network::mojom::ReferrerPolicy::kDefault,
+ starter_origin, starter_secure_context, starter_https_state,
+ worker_clients, worker_start_data_.address_space,
nullptr /* OriginTrialTokens */, devtools_worker_token_,
std::move(worker_settings),
static_cast<V8CacheOptions>(worker_start_data_.v8_cache_options),
@@ -443,38 +435,35 @@ void WebEmbeddedWorkerImpl::StartWorkerThread() {
std::move(interface_provider_info_));
}
- if (RuntimeEnabledFeatures::ServiceWorkerScriptFullCodeCacheEnabled()) {
- global_scope_creation_params->v8_cache_options =
- kV8CacheOptionsFullCodeWithoutHeatCheck;
- }
+ // Generate the full code cache in the first execution of the script.
+ global_scope_creation_params->v8_cache_options =
+ kV8CacheOptionsFullCodeWithoutHeatCheck;
worker_thread_ = std::make_unique<ServiceWorkerThread>(
ServiceWorkerGlobalScopeProxy::Create(*this, *worker_context_client_),
std::move(installed_scripts_manager_), std::move(cache_storage_info_));
+ auto devtools_params = DevToolsAgent::WorkerThreadCreated(
+ document, worker_thread_.get(), worker_start_data_.script_url);
+
// We have a dummy document here for loading but it doesn't really represent
// the document/frame of associated document(s) for this worker. Here we
// populate the task runners with default task runners of the main thread.
- worker_thread_->Start(
- std::move(global_scope_creation_params),
- WorkerBackingThreadStartupData::CreateDefault(),
- worker_inspector_proxy_->ShouldPauseOnWorkerStart(document),
- ParentExecutionContextTaskRunners::Create());
-
- worker_inspector_proxy_->WorkerThreadCreated(document, worker_thread_.get(),
- worker_start_data_.script_url);
+ worker_thread_->Start(std::move(global_scope_creation_params),
+ WorkerBackingThreadStartupData::CreateDefault(),
+ std::move(devtools_params),
+ ParentExecutionContextTaskRunners::Create());
// > Switching on job’s worker type, run these substeps with the following
// > options:
// https://w3c.github.io/ServiceWorker/#update-algorithm
- if (script_type == ScriptType::kClassic) {
+ if (worker_start_data_.script_type == mojom::ScriptType::kClassic) {
// > "classic": Fetch a classic worker script given job’s serialized script
// > url, job’s client, "serviceworker", and the to-be-created environment
// > settings object for this service worker.
- // Service worker is origin-bound, so use kSharableCrossOrigin.
worker_thread_->EvaluateClassicScript(
- worker_start_data_.script_url, kSharableCrossOrigin, source_code,
- std::move(cached_meta_data), v8_inspector::V8StackTraceId());
+ worker_start_data_.script_url, source_code, std::move(cached_meta_data),
+ v8_inspector::V8StackTraceId());
} else {
// > "module": Fetch a module worker script graph given job’s serialized
// > script url, job’s client, "serviceworker", "omit", and the
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h b/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
index 7c73402d511..4c6dee13232 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
+++ b/chromium/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
@@ -48,7 +48,6 @@ namespace blink {
class ServiceWorkerInstalledScriptsManager;
class WorkerClassicScriptLoader;
-class WorkerInspectorProxy;
class WorkerThread;
class MODULES_EXPORT WebEmbeddedWorkerImpl final
@@ -74,8 +73,6 @@ class MODULES_EXPORT WebEmbeddedWorkerImpl final
mojo::ScopedInterfaceEndpointHandle devtools_agent_host_ptr_info,
mojo::ScopedInterfaceEndpointHandle devtools_agent_request) override;
- void PostMessageToPageInspector(int session_id, const WTF::String&);
-
// WorkerShadowPage::Client overrides.
std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
WebApplicationCacheHostClient*) override;
@@ -104,10 +101,9 @@ class MODULES_EXPORT WebEmbeddedWorkerImpl final
std::unique_ptr<ServiceWorkerContentSettingsProxy> content_settings_client_;
// Kept around only while main script loading is ongoing.
- scoped_refptr<WorkerClassicScriptLoader> main_script_loader_;
+ Persistent<WorkerClassicScriptLoader> main_script_loader_;
std::unique_ptr<WorkerThread> worker_thread_;
- Persistent<WorkerInspectorProxy> worker_inspector_proxy_;
std::unique_ptr<WorkerShadowPage> shadow_page_;
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_idb_key.cc b/chromium/third_party/blink/renderer/modules/exported/web_idb_key.cc
index 600bfce5080..2d0dbfd23e6 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_idb_key.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_idb_key.cc
@@ -68,6 +68,23 @@ double WebIDBKeyView::Number() const {
return private_->Number();
}
+size_t WebIDBKeyView::SizeEstimate() const {
+ // TODO(cmp): Ensure |private_| can never be null.
+ //
+ // SizeEstimate() can be called when |private_| is null. That happens if and
+ // only if the |WebIDBKey| instance is created using WebIDBKey::CreateNull().
+ //
+ // Eventually, WebIDBKey::CreateNull() will change so that case will lead to
+ // a non-null |private_|. At that time, this null check can change to a
+ // DCHECK that |private_| is not null and the special null case handling can
+ // be removed.
+ if (this->IsNull()) {
+ return IDBKey::kIDBKeyOverheadSize;
+ }
+
+ return private_->SizeEstimate();
+}
+
WebIDBKey WebIDBKey::CreateArray(WebVector<WebIDBKey> array) {
IDBKey::KeyArray keys;
keys.ReserveCapacity(SafeCast<wtf_size_t>(array.size()));
@@ -105,6 +122,10 @@ WebIDBKey& WebIDBKey::operator=(WebIDBKey&&) noexcept = default;
WebIDBKey::~WebIDBKey() noexcept = default;
+std::unique_ptr<IDBKey> WebIDBKey::ReleaseIdbKey() noexcept {
+ return std::move(private_);
+}
+
WebIDBKey::WebIDBKey(std::unique_ptr<IDBKey> idb_key) noexcept
: private_(std::move(idb_key)) {}
WebIDBKey& WebIDBKey::operator=(std::unique_ptr<IDBKey> idb_key) noexcept {
@@ -112,4 +133,11 @@ WebIDBKey& WebIDBKey::operator=(std::unique_ptr<IDBKey> idb_key) noexcept {
return *this;
}
+WebIDBKey::WebIDBKey(const WebIDBKey& rkey)
+ : private_(IDBKey::Clone(rkey.private_)) {}
+WebIDBKey& WebIDBKey::operator=(const WebIDBKey& rkey) {
+ private_ = IDBKey::Clone(rkey.private_);
+ return *this;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_idb_value.cc b/chromium/third_party/blink/renderer/modules/exported/web_idb_value.cc
index 760124d0606..11ea6453954 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_idb_value.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_idb_value.cc
@@ -38,6 +38,13 @@ WebVector<WebBlobInfo> WebIDBValue::BlobInfoForTesting() const {
return private_->BlobInfo();
}
+std::unique_ptr<IDBValue> WebIDBValue::ReleaseIdbValue() noexcept {
+#if DCHECK_IS_ON()
+ ReleaseIdbValueOwnership();
+#endif // DCHECK_IS_ON()
+ return std::move(private_);
+}
+
#if DCHECK_IS_ON()
void WebIDBValue::ReleaseIdbValueOwnership() {
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_media_stream_registry.cc b/chromium/third_party/blink/renderer/modules/exported/web_media_stream_registry.cc
deleted file mode 100644
index d463018f0d3..00000000000
--- a/chromium/third_party/blink/renderer/modules/exported/web_media_stream_registry.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/public/web/web_media_stream_registry.h"
-
-#include "third_party/blink/public/platform/web_media_stream.h"
-#include "third_party/blink/public/platform/web_string.h"
-#include "third_party/blink/public/platform/web_url.h"
-#include "third_party/blink/renderer/modules/mediastream/media_stream_registry.h"
-#include "third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-
-namespace blink {
-
-WebMediaStream WebMediaStreamRegistry::LookupMediaStreamDescriptor(
- const WebURL& url) {
- return WebMediaStream(
- MediaStreamRegistry::Registry().LookupMediaStreamDescriptor(
- KURL(url).GetString()));
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/exported/web_testing_support.cc b/chromium/third_party/blink/renderer/modules/exported/web_testing_support.cc
index e7b057abe3f..458c765300e 100644
--- a/chromium/third_party/blink/renderer/modules/exported/web_testing_support.cc
+++ b/chromium/third_party/blink/renderer/modules/exported/web_testing_support.cc
@@ -33,20 +33,20 @@
namespace blink {
void WebTestingSupport::InjectInternalsObject(WebLocalFrame* frame) {
- V8InternalsPartial::initialize();
+ V8InternalsPartial::Initialize();
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
- WebCoreTestSupport::InjectInternalsObject(frame->MainWorldScriptContext());
+ web_core_test_support::InjectInternalsObject(frame->MainWorldScriptContext());
}
void WebTestingSupport::ResetInternalsObject(WebLocalFrame* frame) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
- WebCoreTestSupport::ResetInternalsObject(frame->MainWorldScriptContext());
+ web_core_test_support::ResetInternalsObject(frame->MainWorldScriptContext());
}
void WebTestingSupport::InjectInternalsObject(v8::Local<v8::Context> context) {
- V8InternalsPartial::initialize();
+ V8InternalsPartial::Initialize();
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
- WebCoreTestSupport::InjectInternalsObject(context);
+ web_core_test_support::InjectInternalsObject(context);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.cc b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.cc
index 67f5133bf60..c110604a034 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.cc
@@ -46,7 +46,7 @@ DirectoryReader* DirectoryEntry::createReader() {
}
void DirectoryEntry::getFile(const String& path,
- const FileSystemFlags& options,
+ const FileSystemFlags* options,
V8EntryCallback* success_callback,
V8ErrorCallback* error_callback) {
file_system_->GetFile(
@@ -56,7 +56,7 @@ void DirectoryEntry::getFile(const String& path,
}
void DirectoryEntry::getDirectory(const String& path,
- const FileSystemFlags& options,
+ const FileSystemFlags* options,
V8EntryCallback* success_callback,
V8ErrorCallback* error_callback) {
file_system_->GetDirectory(
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.h b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.h
index 431a92e772f..147f9dc50e7 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry.h
@@ -51,26 +51,26 @@ class MODULES_EXPORT DirectoryEntry final : public Entry {
public:
static DirectoryEntry* Create(DOMFileSystemBase* file_system,
const String& full_path) {
- return new DirectoryEntry(file_system, full_path);
+ return MakeGarbageCollected<DirectoryEntry>(file_system, full_path);
}
+
+ DirectoryEntry(DOMFileSystemBase*, const String& full_path);
+
bool isDirectory() const override { return true; }
DirectoryReader* createReader();
void getFile(const String& path,
- const FileSystemFlags&,
+ const FileSystemFlags*,
V8EntryCallback* = nullptr,
V8ErrorCallback* = nullptr);
void getDirectory(const String& path,
- const FileSystemFlags&,
+ const FileSystemFlags*,
V8EntryCallback* = nullptr,
V8ErrorCallback* = nullptr);
void removeRecursively(V8VoidCallback* success_callback = nullptr,
V8ErrorCallback* = nullptr) const;
void Trace(blink::Visitor*) override;
-
- private:
- DirectoryEntry(DOMFileSystemBase*, const String& full_path);
};
DEFINE_TYPE_CASTS(DirectoryEntry,
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.cc b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.cc
index 1c59373eca3..ccafe8a06a6 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.cc
@@ -48,7 +48,7 @@ DirectoryReaderSync* DirectoryEntrySync::createReader() {
}
FileEntrySync* DirectoryEntrySync::getFile(const String& path,
- const FileSystemFlags& options,
+ const FileSystemFlags* options,
ExceptionState& exception_state) {
EntryCallbacksSyncHelper* sync_helper = EntryCallbacksSyncHelper::Create();
file_system_->GetFile(this, path, options, sync_helper->GetSuccessCallback(),
@@ -60,7 +60,7 @@ FileEntrySync* DirectoryEntrySync::getFile(const String& path,
DirectoryEntrySync* DirectoryEntrySync::getDirectory(
const String& path,
- const FileSystemFlags& options,
+ const FileSystemFlags* options,
ExceptionState& exception_state) {
EntryCallbacksSyncHelper* sync_helper = EntryCallbacksSyncHelper::Create();
file_system_->GetDirectory(
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.h b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.h
index 279ac7a9668..2be21443358 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_entry_sync.h
@@ -47,23 +47,23 @@ class DirectoryEntrySync final : public EntrySync {
public:
static DirectoryEntrySync* Create(DOMFileSystemBase* file_system,
const String& full_path) {
- return new DirectoryEntrySync(file_system, full_path);
+ return MakeGarbageCollected<DirectoryEntrySync>(file_system, full_path);
}
+
+ DirectoryEntrySync(DOMFileSystemBase*, const String& full_path);
+
bool isDirectory() const override { return true; }
DirectoryReaderSync* createReader();
FileEntrySync* getFile(const String& path,
- const FileSystemFlags&,
+ const FileSystemFlags*,
ExceptionState&);
DirectoryEntrySync* getDirectory(const String& path,
- const FileSystemFlags&,
+ const FileSystemFlags*,
ExceptionState&);
void removeRecursively(ExceptionState&);
void Trace(blink::Visitor*) override;
-
- private:
- DirectoryEntrySync(DOMFileSystemBase*, const String& full_path);
};
DEFINE_TYPE_CASTS(DirectoryEntrySync,
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.cc b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.cc
index e234149591b..9c02bf90eda 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.cc
@@ -51,9 +51,11 @@ class DirectoryReader::EntriesCallbackHelper final
: public EntriesCallbacks::OnDidGetEntriesCallback {
public:
static EntriesCallbackHelper* Create(DirectoryReader* reader) {
- return new EntriesCallbackHelper(reader);
+ return MakeGarbageCollected<EntriesCallbackHelper>(reader);
}
+ explicit EntriesCallbackHelper(DirectoryReader* reader) : reader_(reader) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(reader_);
EntriesCallbacks::OnDidGetEntriesCallback::Trace(visitor);
@@ -64,8 +66,6 @@ class DirectoryReader::EntriesCallbackHelper final
}
private:
- explicit EntriesCallbackHelper(DirectoryReader* reader) : reader_(reader) {}
-
// FIXME: This Member keeps the reader alive until all of the readDirectory
// results are received. crbug.com/350285
Member<DirectoryReader> reader_;
@@ -74,9 +74,11 @@ class DirectoryReader::EntriesCallbackHelper final
class DirectoryReader::ErrorCallbackHelper final : public ErrorCallbackBase {
public:
static ErrorCallbackHelper* Create(DirectoryReader* reader) {
- return new ErrorCallbackHelper(reader);
+ return MakeGarbageCollected<ErrorCallbackHelper>(reader);
}
+ explicit ErrorCallbackHelper(DirectoryReader* reader) : reader_(reader) {}
+
void Invoke(base::File::Error error) override { reader_->OnError(error); }
void Trace(blink::Visitor* visitor) override {
@@ -85,8 +87,6 @@ class DirectoryReader::ErrorCallbackHelper final : public ErrorCallbackBase {
}
private:
- explicit ErrorCallbackHelper(DirectoryReader* reader) : reader_(reader) {}
-
Member<DirectoryReader> reader_;
};
@@ -118,7 +118,8 @@ void DirectoryReader::readEntries(V8EntriesCallback* entries_callback,
}
if (!has_more_entries_ || !entries_.IsEmpty()) {
- EntryHeapVector* entries = new EntryHeapVector(std::move(entries_));
+ EntryHeapVector* entries =
+ MakeGarbageCollected<EntryHeapVector>(std::move(entries_));
DOMFileSystem::ScheduleCallback(
Filesystem()->GetExecutionContext(),
WTF::Bind(
@@ -147,7 +148,7 @@ void DirectoryReader::OnError(base::File::Error error) {
entries_callback_ = nullptr;
if (auto* error_callback = error_callback_.Release()) {
error_callback->InvokeAndReportException(
- nullptr, FileError::CreateDOMException(error_));
+ nullptr, file_error::CreateDOMException(error_));
}
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.h b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.h
index aa741253d1d..6668cd08c52 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader.h
@@ -46,9 +46,10 @@ class DirectoryReader : public DirectoryReaderBase {
public:
static DirectoryReader* Create(DOMFileSystemBase* file_system,
const String& full_path) {
- return new DirectoryReader(file_system, full_path);
+ return MakeGarbageCollected<DirectoryReader>(file_system, full_path);
}
+ DirectoryReader(DOMFileSystemBase*, const String& full_path);
~DirectoryReader() override = default;
void readEntries(V8EntriesCallback*, V8ErrorCallback* = nullptr);
@@ -63,8 +64,6 @@ class DirectoryReader : public DirectoryReaderBase {
class EntriesCallbackHelper;
class ErrorCallbackHelper;
- DirectoryReader(DOMFileSystemBase*, const String& full_path);
-
void AddEntries(const EntryHeapVector& entries);
void OnError(base::File::Error error);
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.cc b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.cc
index 1e7d48d50cb..e6b6c9e8099 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.cc
@@ -43,9 +43,12 @@ class DirectoryReaderSync::EntriesCallbackHelper final
: public EntriesCallbacks::OnDidGetEntriesCallback {
public:
static EntriesCallbackHelper* Create(DirectoryReaderSync* reader) {
- return new EntriesCallbackHelper(reader);
+ return MakeGarbageCollected<EntriesCallbackHelper>(reader);
}
+ explicit EntriesCallbackHelper(DirectoryReaderSync* reader)
+ : reader_(reader) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(reader_);
EntriesCallbacks::OnDidGetEntriesCallback::Trace(visitor);
@@ -60,9 +63,6 @@ class DirectoryReaderSync::EntriesCallbackHelper final
}
private:
- explicit EntriesCallbackHelper(DirectoryReaderSync* reader)
- : reader_(reader) {}
-
Member<DirectoryReaderSync> reader_;
};
@@ -70,9 +70,11 @@ class DirectoryReaderSync::ErrorCallbackHelper final
: public ErrorCallbackBase {
public:
static ErrorCallbackHelper* Create(DirectoryReaderSync* reader) {
- return new ErrorCallbackHelper(reader);
+ return MakeGarbageCollected<ErrorCallbackHelper>(reader);
}
+ explicit ErrorCallbackHelper(DirectoryReaderSync* reader) : reader_(reader) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(reader_);
ErrorCallbackBase::Trace(visitor);
@@ -83,8 +85,6 @@ class DirectoryReaderSync::ErrorCallbackHelper final
}
private:
- explicit ErrorCallbackHelper(DirectoryReaderSync* reader) : reader_(reader) {}
-
Member<DirectoryReaderSync> reader_;
};
@@ -104,7 +104,7 @@ EntrySyncHeapVector DirectoryReaderSync::readEntries(
DCHECK(!has_more_entries_);
if (error_code_ != base::File::FILE_OK) {
- FileError::ThrowDOMException(exception_state, error_code_);
+ file_error::ThrowDOMException(exception_state, error_code_);
return EntrySyncHeapVector();
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.h b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.h
index 92b1bedab3f..fa23b1f4f0a 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/directory_reader_sync.h
@@ -49,9 +49,10 @@ class DirectoryReaderSync : public DirectoryReaderBase {
public:
static DirectoryReaderSync* Create(DOMFileSystemBase* file_system,
const String& full_path) {
- return new DirectoryReaderSync(file_system, full_path);
+ return MakeGarbageCollected<DirectoryReaderSync>(file_system, full_path);
}
+ DirectoryReaderSync(DOMFileSystemBase*, const String& full_path);
~DirectoryReaderSync() override = default;
EntrySyncHeapVector readEntries(ExceptionState&);
@@ -62,8 +63,6 @@ class DirectoryReaderSync : public DirectoryReaderBase {
class EntriesCallbackHelper;
class ErrorCallbackHelper;
- DirectoryReaderSync(DOMFileSystemBase*, const String& full_path);
-
bool has_called_read_directory_ = false;
EntrySyncHeapVector entries_;
base::File::Error error_code_ = base::File::FILE_OK;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.cc b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.cc
index 9d079872924..edc4917e7a5 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.cc
@@ -66,7 +66,7 @@ DOMFileSystem* DOMFileSystem::Create(ExecutionContext* context,
const String& name,
mojom::blink::FileSystemType type,
const KURL& root_url) {
- return new DOMFileSystem(context, name, type, root_url);
+ return MakeGarbageCollected<DOMFileSystem>(context, name, type, root_url);
}
DOMFileSystem* DOMFileSystem::CreateIsolatedFileSystem(
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.h b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.h
index 465c3f5776e..e41488c1c12 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system.h
@@ -62,6 +62,11 @@ class MODULES_EXPORT DOMFileSystem final
static DOMFileSystem* CreateIsolatedFileSystem(ExecutionContext*,
const String& filesystem_id);
+ DOMFileSystem(ExecutionContext*,
+ const String& name,
+ mojom::blink::FileSystemType,
+ const KURL& root_url);
+
DirectoryEntry* root() const;
// DOMFileSystemBase overrides.
@@ -91,11 +96,6 @@ class MODULES_EXPORT DOMFileSystem final
void Trace(blink::Visitor*) override;
private:
- DOMFileSystem(ExecutionContext*,
- const String& name,
- mojom::blink::FileSystemType,
- const KURL& root_url);
-
static String TaskNameForInstrumentation() { return "FileSystem"; }
int number_of_pending_callbacks_;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc
index 98e1a6566c8..351e387d486 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc
@@ -375,7 +375,7 @@ void DOMFileSystemBase::GetParent(
void DOMFileSystemBase::GetFile(
const EntryBase* entry,
const String& path,
- const FileSystemFlags& flags,
+ const FileSystemFlags* flags,
EntryCallbacks::OnDidGetEntryCallback* success_callback,
ErrorCallbackBase* error_callback,
SynchronousType synchronous_type) {
@@ -390,11 +390,11 @@ void DOMFileSystemBase::GetFile(
const KURL& url = CreateFileSystemURL(absolute_path);
FileSystemDispatcher& dispatcher = FileSystemDispatcher::From(context_);
- if (flags.createFlag()) {
+ if (flags->createFlag()) {
if (synchronous_type == kSynchronous)
- dispatcher.CreateFileSync(url, flags.exclusive(), std::move(callbacks));
+ dispatcher.CreateFileSync(url, flags->exclusive(), std::move(callbacks));
else
- dispatcher.CreateFile(url, flags.exclusive(), std::move(callbacks));
+ dispatcher.CreateFile(url, flags->exclusive(), std::move(callbacks));
} else {
if (synchronous_type == kSynchronous) {
dispatcher.ExistsSync(url, /*is_directory=*/false, std::move(callbacks));
@@ -407,7 +407,7 @@ void DOMFileSystemBase::GetFile(
void DOMFileSystemBase::GetDirectory(
const EntryBase* entry,
const String& path,
- const FileSystemFlags& flags,
+ const FileSystemFlags* flags,
EntryCallbacks::OnDidGetEntryCallback* success_callback,
ErrorCallbackBase* error_callback,
SynchronousType synchronous_type) {
@@ -422,12 +422,12 @@ void DOMFileSystemBase::GetDirectory(
const KURL& url = CreateFileSystemURL(absolute_path);
FileSystemDispatcher& dispatcher = FileSystemDispatcher::From(context_);
- if (flags.createFlag()) {
+ if (flags->createFlag()) {
if (synchronous_type == kSynchronous) {
- dispatcher.CreateDirectorySync(url, flags.exclusive(),
+ dispatcher.CreateDirectorySync(url, flags->exclusive(),
/*recursive=*/false, std::move(callbacks));
} else {
- dispatcher.CreateDirectory(url, flags.exclusive(), /*recursive=*/false,
+ dispatcher.CreateDirectory(url, flags->exclusive(), /*recursive=*/false,
std::move(callbacks));
}
} else {
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h
index 83452e2aa1b..4e19500fd7b 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h
@@ -135,13 +135,13 @@ class MODULES_EXPORT DOMFileSystemBase : public ScriptWrappable {
ErrorCallbackBase*);
void GetFile(const EntryBase*,
const String& path,
- const FileSystemFlags&,
+ const FileSystemFlags*,
EntryCallbacks::OnDidGetEntryCallback*,
ErrorCallbackBase*,
SynchronousType = kAsynchronous);
void GetDirectory(const EntryBase*,
const String& path,
- const FileSystemFlags&,
+ const FileSystemFlags*,
EntryCallbacks::OnDidGetEntryCallback*,
ErrorCallbackBase*,
SynchronousType = kAsynchronous);
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.cc b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.cc
index 1d1b6e1008c..ef664f7d585 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.cc
@@ -50,8 +50,9 @@ namespace blink {
class FileWriterBase;
DOMFileSystemSync* DOMFileSystemSync::Create(DOMFileSystemBase* file_system) {
- return new DOMFileSystemSync(file_system->context_, file_system->name(),
- file_system->GetType(), file_system->RootURL());
+ return MakeGarbageCollected<DOMFileSystemSync>(
+ file_system->context_, file_system->name(), file_system->GetType(),
+ file_system->RootURL());
}
DOMFileSystemSync::DOMFileSystemSync(ExecutionContext* context,
@@ -143,7 +144,7 @@ File* DOMFileSystemSync::CreateFile(const FileEntrySync* file_entry,
file_system_url, CreateFileHelper::Create(result, file_entry->name(),
file_system_url, GetType()));
if (result->failed_) {
- FileError::ThrowDOMException(
+ file_error::ThrowDOMException(
exception_state, result->error_,
"Could not create '" + file_entry->name() + "'.");
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.h b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.h
index 228b3e0b211..c6d715a23d1 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_file_system_sync.h
@@ -50,11 +50,16 @@ class DOMFileSystemSync final : public DOMFileSystemBase {
const String& name,
mojom::blink::FileSystemType type,
const KURL& root_url) {
- return new DOMFileSystemSync(context, name, type, root_url);
+ return MakeGarbageCollected<DOMFileSystemSync>(context, name, type,
+ root_url);
}
static DOMFileSystemSync* Create(DOMFileSystemBase*);
+ DOMFileSystemSync(ExecutionContext*,
+ const String& name,
+ mojom::blink::FileSystemType,
+ const KURL& root_url);
~DOMFileSystemSync() override;
void ReportError(ErrorCallbackBase*, base::File::Error error) override;
@@ -67,10 +72,6 @@ class DOMFileSystemSync final : public DOMFileSystemBase {
void Trace(blink::Visitor*) override;
private:
- DOMFileSystemSync(ExecutionContext*,
- const String& name,
- mojom::blink::FileSystemType,
- const KURL& root_url);
Member<DirectoryEntrySync> root_entry_;
};
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.cc b/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.cc
index 52b1e87c04d..1d57b05b460 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.cc
@@ -156,15 +156,15 @@ mojom::blink::ChooseFileSystemEntryType ConvertChooserType(const String& input,
}
Vector<mojom::blink::ChooseFileSystemEntryAcceptsOptionPtr> ConvertAccepts(
- const HeapVector<ChooseFileSystemEntriesOptionsAccepts>& accepts) {
+ const HeapVector<Member<ChooseFileSystemEntriesOptionsAccepts>>& accepts) {
Vector<mojom::blink::ChooseFileSystemEntryAcceptsOptionPtr> result;
result.ReserveInitialCapacity(accepts.size());
for (const auto& a : accepts) {
result.emplace_back(
blink::mojom::blink::ChooseFileSystemEntryAcceptsOption::New(
- a.hasDescription() ? a.description() : g_empty_string,
- a.hasMimeTypes() ? a.mimeTypes() : Vector<String>(),
- a.hasExtensions() ? a.extensions() : Vector<String>()));
+ a->hasDescription() ? a->description() : g_empty_string,
+ a->hasMimeTypes() ? a->mimeTypes() : Vector<String>(),
+ a->hasExtensions() ? a->extensions() : Vector<String>()));
}
return result;
}
@@ -179,13 +179,16 @@ ScriptPromise CreateFileHandle(ScriptState* script_state,
// TODO(mek): Try to create handle directly rather than having to do more
// IPCs to get the actual entries.
if (is_directory) {
- fs->GetDirectory(fs->root(), entry->base_name, FileSystemFlags(),
- new EntryCallbacks::OnDidGetEntryPromiseImpl(new_resolver),
- new PromiseErrorCallback(new_resolver));
+ fs->GetDirectory(
+ fs->root(), entry->base_name, FileSystemFlags::Create(),
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(
+ new_resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(new_resolver));
} else {
- fs->GetFile(fs->root(), entry->base_name, FileSystemFlags(),
- new EntryCallbacks::OnDidGetEntryPromiseImpl(new_resolver),
- new PromiseErrorCallback(new_resolver));
+ fs->GetFile(fs->root(), entry->base_name, FileSystemFlags::Create(),
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(
+ new_resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(new_resolver));
}
return result;
}
@@ -195,7 +198,7 @@ ScriptPromise CreateFileHandle(ScriptState* script_state,
ScriptPromise DOMWindowFileSystem::chooseFileSystemEntries(
ScriptState* script_state,
LocalDOMWindow& window,
- const ChooseFileSystemEntriesOptions& options) {
+ const ChooseFileSystemEntriesOptions* options) {
if (!base::FeatureList::IsEnabled(blink::features::kWritableFilesAPI)) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kAbortError));
@@ -221,27 +224,27 @@ ScriptPromise DOMWindowFileSystem::chooseFileSystemEntries(
}
Vector<mojom::blink::ChooseFileSystemEntryAcceptsOptionPtr> accepts;
- if (options.hasAccepts())
- accepts = ConvertAccepts(options.accepts());
+ if (options->hasAccepts())
+ accepts = ConvertAccepts(options->accepts());
auto* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise result = resolver->Promise();
FileSystemDispatcher::From(document).GetFileSystemManager().ChooseEntry(
- ConvertChooserType(options.type(), options.multiple()),
- std::move(accepts), !options.excludeAcceptAllOption(),
+ ConvertChooserType(options->type(), options->multiple()),
+ std::move(accepts), !options->excludeAcceptAllOption(),
WTF::Bind(
[](ScriptPromiseResolver* resolver,
- const ChooseFileSystemEntriesOptions& options,
+ const ChooseFileSystemEntriesOptions* options,
base::File::Error result,
Vector<mojom::blink::FileSystemEntryPtr> entries) {
if (result != base::File::FILE_OK) {
- resolver->Reject(FileError::CreateDOMException(result));
+ resolver->Reject(file_error::CreateDOMException(result));
return;
}
- bool is_directory = options.type() == "openDirectory";
+ bool is_directory = options->type() == "openDirectory";
ScriptState* script_state = resolver->GetScriptState();
ScriptState::Scope scope(script_state);
- if (options.multiple()) {
+ if (options->multiple()) {
Vector<ScriptPromise> result;
result.ReserveInitialCapacity(entries.size());
for (const auto& entry : entries) {
@@ -257,7 +260,7 @@ ScriptPromise DOMWindowFileSystem::chooseFileSystemEntries(
.GetScriptValue());
}
},
- WrapPersistent(resolver), options));
+ WrapPersistent(resolver), WrapPersistent(options)));
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.h b/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.h
index 8d4264d1f39..20449641f8e 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dom_window_file_system.h
@@ -64,7 +64,7 @@ class DOMWindowFileSystem {
static ScriptPromise chooseFileSystemEntries(
ScriptState*,
LocalDOMWindow&,
- const ChooseFileSystemEntriesOptions&);
+ const ChooseFileSystemEntriesOptions*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.cc b/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.cc
index 5e4df3b4843..5add202946d 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.cc
@@ -76,7 +76,7 @@ void DraggedIsolatedFileSystemImpl::PrepareForDataObject(
DataObject* data_object) {
DCHECK(IsMainThread());
DraggedIsolatedFileSystemImpl* file_system =
- new DraggedIsolatedFileSystemImpl();
+ MakeGarbageCollected<DraggedIsolatedFileSystemImpl>();
ProvideTo(*data_object, file_system);
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.h b/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.h
index 5cd991da882..e524f907a06 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.h
@@ -57,13 +57,13 @@ class DraggedIsolatedFileSystemImpl final
static DraggedIsolatedFileSystemImpl* From(DataObject*);
+ DraggedIsolatedFileSystemImpl() = default;
+
void Trace(blink::Visitor*) override;
static void PrepareForDataObject(DataObject*);
private:
- DraggedIsolatedFileSystemImpl() = default;
-
HeapHashMap<String, Member<DOMFileSystem>> filesystems_;
};
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/entry.h b/chromium/third_party/blink/renderer/modules/filesystem/entry.h
index 03744f9d32a..4f2dc22f711 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/entry.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/entry.h
@@ -48,6 +48,8 @@ class MODULES_EXPORT Entry : public EntryBase {
DEFINE_WRAPPERTYPEINFO();
public:
+ Entry(DOMFileSystemBase*, const String& full_path);
+
DOMFileSystem* filesystem() const {
return static_cast<DOMFileSystem*>(file_system_.Get());
}
@@ -75,9 +77,6 @@ class MODULES_EXPORT Entry : public EntryBase {
String toURL(ScriptState*) const;
void Trace(blink::Visitor*) override;
-
- protected:
- Entry(DOMFileSystemBase*, const String& full_path);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/entry_base.cc b/chromium/third_party/blink/renderer/modules/filesystem/entry_base.cc
index b2e0c94926e..19609d9468e 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/entry_base.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/entry_base.cc
@@ -59,9 +59,10 @@ String EntryBase::toURL() const {
FileSystemBaseHandle* EntryBase::asFileSystemHandle() const {
if (isFile())
- return new FileSystemFileHandle(filesystem(), fullPath());
+ return MakeGarbageCollected<FileSystemFileHandle>(filesystem(), fullPath());
DCHECK(isDirectory());
- return new FileSystemDirectoryHandle(filesystem(), fullPath());
+ return MakeGarbageCollected<FileSystemDirectoryHandle>(filesystem(),
+ fullPath());
}
void EntryBase::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_entry.h b/chromium/third_party/blink/renderer/modules/filesystem/file_entry.h
index 17ca61ed9c4..46263735dee 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_entry.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_entry.h
@@ -47,18 +47,17 @@ class MODULES_EXPORT FileEntry final : public Entry {
public:
static FileEntry* Create(DOMFileSystemBase* file_system,
const String& full_path) {
- return new FileEntry(file_system, full_path);
+ return MakeGarbageCollected<FileEntry>(file_system, full_path);
}
+ FileEntry(DOMFileSystemBase*, const String& full_path);
+
void createWriter(V8FileWriterCallback*, V8ErrorCallback* = nullptr);
void file(V8FileCallback*, V8ErrorCallback* = nullptr);
bool isFile() const override { return true; }
void Trace(blink::Visitor*) override;
-
- private:
- FileEntry(DOMFileSystemBase*, const String& full_path);
};
DEFINE_TYPE_CASTS(FileEntry, Entry, entry, entry->isFile(), entry.isFile());
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_entry_sync.h b/chromium/third_party/blink/renderer/modules/filesystem/file_entry_sync.h
index 08be0b6c399..90fe339de26 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_entry_sync.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_entry_sync.h
@@ -47,18 +47,17 @@ class FileEntrySync final : public EntrySync {
public:
static FileEntrySync* Create(DOMFileSystemBase* file_system,
const String& full_path) {
- return new FileEntrySync(file_system, full_path);
+ return MakeGarbageCollected<FileEntrySync>(file_system, full_path);
}
+ FileEntrySync(DOMFileSystemBase*, const String& full_path);
+
bool isFile() const override { return true; }
File* file(ExceptionState&);
FileWriterSync* createWriter(ExceptionState&);
void Trace(blink::Visitor*) override;
-
- private:
- FileEntrySync(DOMFileSystemBase*, const String& full_path);
};
DEFINE_TYPE_CASTS(FileEntrySync,
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_base_handle.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_system_base_handle.cc
index 1fcaa2f115c..c6c2d0525e3 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_base_handle.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_base_handle.cc
@@ -19,8 +19,9 @@ ScriptPromise FileSystemBaseHandle::getParent(ScriptState* script_state) {
auto* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise result = resolver->Promise();
filesystem()->GetParent(
- this, new EntryCallbacks::OnDidGetEntryPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ this,
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
@@ -29,9 +30,10 @@ ScriptPromise FileSystemBaseHandle::moveTo(ScriptState* script_state,
const String& name) {
auto* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise result = resolver->Promise();
- filesystem()->Move(this, parent, name,
- new EntryCallbacks::OnDidGetEntryPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ filesystem()->Move(
+ this, parent, name,
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
@@ -40,9 +42,10 @@ ScriptPromise FileSystemBaseHandle::copyTo(ScriptState* script_state,
const String& name) {
auto* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise result = resolver->Promise();
- filesystem()->Copy(this, parent, name,
- new EntryCallbacks::OnDidGetEntryPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ filesystem()->Copy(
+ this, parent, name,
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
@@ -51,7 +54,7 @@ ScriptPromise FileSystemBaseHandle::remove(ScriptState* script_state) {
ScriptPromise result = resolver->Promise();
filesystem()->Remove(this,
new VoidCallbacks::OnDidSucceedPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc
index 06bde35238c..3095d62e35a 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc
@@ -111,7 +111,7 @@ ScriptErrorCallback* ScriptErrorCallback::Wrap(V8ErrorCallback* callback) {
// and checking during invoke().
if (!callback)
return nullptr;
- return new ScriptErrorCallback(callback);
+ return MakeGarbageCollected<ScriptErrorCallback>(callback);
}
void ScriptErrorCallback::Trace(blink::Visitor* visitor) {
@@ -121,7 +121,7 @@ void ScriptErrorCallback::Trace(blink::Visitor* visitor) {
void ScriptErrorCallback::Invoke(base::File::Error error) {
callback_->InvokeAndReportException(nullptr,
- FileError::CreateDOMException(error));
+ file_error::CreateDOMException(error));
};
ScriptErrorCallback::ScriptErrorCallback(V8ErrorCallback* callback)
@@ -138,7 +138,7 @@ void PromiseErrorCallback::Trace(Visitor* visitor) {
}
void PromiseErrorCallback::Invoke(base::File::Error error) {
- resolver_->Reject(FileError::CreateDOMException(error));
+ resolver_->Reject(file_error::CreateDOMException(error));
}
// EntryCallbacks -------------------------------------------------------------
@@ -223,7 +223,7 @@ EntriesCallbacks::EntriesCallbacks(OnDidGetEntriesCallback* success_callback,
success_callback_(success_callback),
directory_reader_(directory_reader),
base_path_(base_path),
- entries_(new HeapVector<Member<Entry>>()) {
+ entries_(MakeGarbageCollected<HeapVector<Member<Entry>>>()) {
DCHECK(directory_reader_);
}
@@ -240,7 +240,8 @@ void EntriesCallbacks::DidReadDirectoryEntry(const String& name,
void EntriesCallbacks::DidReadDirectoryEntries(bool has_more) {
directory_reader_->SetHasMoreEntries(has_more);
- EntryHeapVector* entries = new EntryHeapVector(std::move(*entries_));
+ EntryHeapVector* entries =
+ MakeGarbageCollected<EntryHeapVector>(std::move(*entries_));
if (!success_callback_)
return;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h b/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h
index 04ab209a9d8..5654f88342a 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h
@@ -108,13 +108,14 @@ class FileSystemCallbacksBase : public AsyncFileSystemCallbacks {
class ScriptErrorCallback final : public ErrorCallbackBase {
public:
static ScriptErrorCallback* Wrap(V8ErrorCallback*);
+
+ explicit ScriptErrorCallback(V8ErrorCallback*);
~ScriptErrorCallback() override {}
void Trace(blink::Visitor*) override;
void Invoke(base::File::Error error) override;
private:
- explicit ScriptErrorCallback(V8ErrorCallback*);
Member<V8PersistentCallbackInterface<V8ErrorCallback>> callback_;
};
@@ -144,15 +145,17 @@ class EntryCallbacks final : public FileSystemCallbacksBase {
class OnDidGetEntryV8Impl : public OnDidGetEntryCallback {
public:
static OnDidGetEntryV8Impl* Create(V8EntryCallback* callback) {
- return callback ? new OnDidGetEntryV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnDidGetEntryV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess(Entry*) override;
- private:
OnDidGetEntryV8Impl(V8EntryCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess(Entry*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8EntryCallback>> callback_;
};
@@ -237,15 +240,18 @@ class FileSystemCallbacks final : public FileSystemCallbacksBase {
class OnDidOpenFileSystemV8Impl : public OnDidOpenFileSystemCallback {
public:
static OnDidOpenFileSystemV8Impl* Create(V8FileSystemCallback* callback) {
- return callback ? new OnDidOpenFileSystemV8Impl(callback) : nullptr;
+ return callback
+ ? MakeGarbageCollected<OnDidOpenFileSystemV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess(DOMFileSystem*) override;
- private:
OnDidOpenFileSystemV8Impl(V8FileSystemCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess(DOMFileSystem*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8FileSystemCallback>> callback_;
};
@@ -311,15 +317,17 @@ class MetadataCallbacks final : public FileSystemCallbacksBase {
class OnDidReadMetadataV8Impl : public OnDidReadMetadataCallback {
public:
static OnDidReadMetadataV8Impl* Create(V8MetadataCallback* callback) {
- return callback ? new OnDidReadMetadataV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnDidReadMetadataV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess(Metadata*) override;
- private:
OnDidReadMetadataV8Impl(V8MetadataCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess(Metadata*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8MetadataCallback>> callback_;
};
@@ -354,15 +362,18 @@ class FileWriterCallbacks final : public FileSystemCallbacksBase {
class OnDidCreateFileWriterV8Impl : public OnDidCreateFileWriterCallback {
public:
static OnDidCreateFileWriterV8Impl* Create(V8FileWriterCallback* callback) {
- return callback ? new OnDidCreateFileWriterV8Impl(callback) : nullptr;
+ return callback
+ ? MakeGarbageCollected<OnDidCreateFileWriterV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess(FileWriterBase*) override;
- private:
OnDidCreateFileWriterV8Impl(V8FileWriterCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess(FileWriterBase*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8FileWriterCallback>> callback_;
};
@@ -398,15 +409,18 @@ class SnapshotFileCallback final : public FileSystemCallbacksBase {
class OnDidCreateSnapshotFileV8Impl : public OnDidCreateSnapshotFileCallback {
public:
static OnDidCreateSnapshotFileV8Impl* Create(V8FileCallback* callback) {
- return callback ? new OnDidCreateSnapshotFileV8Impl(callback) : nullptr;
+ return callback
+ ? MakeGarbageCollected<OnDidCreateSnapshotFileV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess(File*) override;
- private:
OnDidCreateSnapshotFileV8Impl(V8FileCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess(File*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8FileCallback>> callback_;
};
@@ -448,15 +462,17 @@ class VoidCallbacks final : public FileSystemCallbacksBase {
class OnDidSucceedV8Impl : public OnDidSucceedCallback {
public:
static OnDidSucceedV8Impl* Create(V8VoidCallback* callback) {
- return callback ? new OnDidSucceedV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnDidSucceedV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess(ExecutionContext* dummy_arg_for_sync_helper) override;
- private:
OnDidSucceedV8Impl(V8VoidCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess(ExecutionContext* dummy_arg_for_sync_helper) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8VoidCallback>> callback_;
};
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.cc
index 4bc2d834eda..2afc8215e5f 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.cc
@@ -20,35 +20,37 @@ FileSystemDirectoryHandle::FileSystemDirectoryHandle(
ScriptPromise FileSystemDirectoryHandle::getFile(
ScriptState* script_state,
const String& name,
- const FileSystemGetFileOptions& options) {
- FileSystemFlags flags;
- flags.setCreateFlag(options.create());
+ const FileSystemGetFileOptions* options) {
+ FileSystemFlags* flags = FileSystemFlags::Create();
+ flags->setCreateFlag(options->create());
auto* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise result = resolver->Promise();
- filesystem()->GetFile(this, name, flags,
- new EntryCallbacks::OnDidGetEntryPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ filesystem()->GetFile(
+ this, name, flags,
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
ScriptPromise FileSystemDirectoryHandle::getDirectory(
ScriptState* script_state,
const String& name,
- const FileSystemGetDirectoryOptions& options) {
- FileSystemFlags flags;
- flags.setCreateFlag(options.create());
+ const FileSystemGetDirectoryOptions* options) {
+ FileSystemFlags* flags = FileSystemFlags::Create();
+ flags->setCreateFlag(options->create());
auto* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise result = resolver->Promise();
filesystem()->GetDirectory(
- this, name, flags, new EntryCallbacks::OnDidGetEntryPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ this, name, flags,
+ MakeGarbageCollected<EntryCallbacks::OnDidGetEntryPromiseImpl>(resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
// static
ScriptPromise FileSystemDirectoryHandle::getSystemDirectory(
ScriptState* script_state,
- const GetSystemDirectoryOptions& options) {
+ const GetSystemDirectoryOptions* options) {
auto* context = ExecutionContext::From(script_state);
auto* resolver = ScriptPromiseResolver::Create(script_state);
@@ -58,7 +60,7 @@ ScriptPromise FileSystemDirectoryHandle::getSystemDirectory(
context, mojom::blink::FileSystemType::kTemporary, /*size=*/0,
FileSystemCallbacks::Create(
new FileSystemCallbacks::OnDidOpenFileSystemPromiseImpl(resolver),
- new PromiseErrorCallback(resolver), context,
+ MakeGarbageCollected<PromiseErrorCallback>(resolver), context,
mojom::blink::FileSystemType::kTemporary),
LocalFileSystem::kAsynchronous);
return result;
@@ -94,7 +96,7 @@ ScriptPromise FileSystemDirectoryHandle::removeRecursively(
ScriptPromise result = resolver->Promise();
filesystem()->RemoveRecursively(
this, new VoidCallbacks::OnDidSucceedPromiseImpl(resolver),
- new PromiseErrorCallback(resolver));
+ MakeGarbageCollected<PromiseErrorCallback>(resolver));
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.h b/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.h
index 3dfc770d4b0..92290a45fcf 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_handle.h
@@ -22,16 +22,16 @@ class FileSystemDirectoryHandle : public FileSystemBaseHandle {
bool isDirectory() const override { return true; }
ScriptPromise getFile(ScriptState*,
const String& name,
- const FileSystemGetFileOptions&);
+ const FileSystemGetFileOptions*);
ScriptPromise getDirectory(ScriptState*,
const String& name,
- const FileSystemGetDirectoryOptions&);
+ const FileSystemGetDirectoryOptions*);
ScriptValue getEntries(ScriptState*);
ScriptPromise removeRecursively(ScriptState*);
static ScriptPromise getSystemDirectory(
ScriptState*,
- const GetSystemDirectoryOptions& options);
+ const GetSystemDirectoryOptions* options);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_iterator.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_iterator.cc
index d7fa8b6cebe..4633c667983 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_iterator.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_directory_iterator.cc
@@ -55,19 +55,21 @@ FileSystemDirectoryIterator::FileSystemDirectoryIterator(
DOMFileSystemBase* file_system,
const String& full_path)
: DirectoryReaderBase(file_system, full_path) {
- Filesystem()->ReadDirectory(this, full_path_, new EntriesCallbackHelper(this),
- new ErrorCallbackHelper(this));
+ Filesystem()->ReadDirectory(this, full_path_,
+ MakeGarbageCollected<EntriesCallbackHelper>(this),
+ MakeGarbageCollected<ErrorCallbackHelper>(this));
}
ScriptPromise FileSystemDirectoryIterator::next(ScriptState* script_state) {
if (error_ != base::File::FILE_OK) {
return ScriptPromise::RejectWithDOMException(
- script_state, FileError::CreateDOMException(error_));
+ script_state, file_error::CreateDOMException(error_));
}
if (!entries_.IsEmpty()) {
- FileSystemDirectoryIteratorEntry result;
- result.setValue(entries_.TakeFirst()->asFileSystemHandle());
+ FileSystemDirectoryIteratorEntry* result =
+ FileSystemDirectoryIteratorEntry::Create();
+ result->setValue(entries_.TakeFirst()->asFileSystemHandle());
return ScriptPromise::Cast(script_state, ToV8(result, script_state));
}
@@ -77,8 +79,9 @@ ScriptPromise FileSystemDirectoryIterator::next(ScriptState* script_state) {
return pending_next_->Promise();
}
- FileSystemDirectoryIteratorEntry result;
- result.setDone(true);
+ FileSystemDirectoryIteratorEntry* result =
+ FileSystemDirectoryIteratorEntry::Create();
+ result->setDone(true);
return ScriptPromise::Cast(script_state, ToV8(result, script_state));
}
@@ -102,7 +105,7 @@ void FileSystemDirectoryIterator::AddEntries(const EntryHeapVector& entries) {
void FileSystemDirectoryIterator::OnError(base::File::Error error) {
error_ = error;
if (pending_next_) {
- pending_next_->Reject(FileError::CreateDOMException(error));
+ pending_next_->Reject(file_error::CreateDOMException(error));
pending_next_ = nullptr;
}
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_file_handle.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_system_file_handle.cc
index 9bf62daa4fc..95e9823fce2 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_file_handle.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_file_handle.cc
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/modules/filesystem/file_system_callbacks.h"
#include "third_party/blink/renderer/modules/filesystem/file_system_dispatcher.h"
#include "third_party/blink/renderer/modules/filesystem/file_system_writer.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -50,9 +51,10 @@ ScriptPromise FileSystemFileHandle::createWriter(ScriptState* script_state) {
[](ScriptPromiseResolver* resolver, base::File::Error result,
mojom::blink::FileWriterPtr writer) {
if (result == base::File::FILE_OK) {
- resolver->Resolve(new FileSystemWriter(std::move(writer)));
+ resolver->Resolve(MakeGarbageCollected<FileSystemWriter>(
+ std::move(writer)));
} else {
- resolver->Reject(FileError::CreateDOMException(result));
+ resolver->Reject(file_error::CreateDOMException(result));
}
},
WrapPersistent(resolver)));
@@ -64,12 +66,13 @@ ScriptPromise FileSystemFileHandle::getFile(ScriptState* script_state) {
ScriptPromise result = resolver->Promise();
KURL file_system_url = filesystem()->CreateFileSystemURL(this);
FileSystemDispatcher::From(ExecutionContext::From(script_state))
- .CreateSnapshotFile(file_system_url,
- SnapshotFileCallback::Create(
- filesystem(), name(), file_system_url,
- new OnDidCreateSnapshotFilePromise(resolver),
- new PromiseErrorCallback(resolver),
- ExecutionContext::From(script_state)));
+ .CreateSnapshotFile(
+ file_system_url,
+ SnapshotFileCallback::Create(
+ filesystem(), name(), file_system_url,
+ new OnDidCreateSnapshotFilePromise(resolver),
+ MakeGarbageCollected<PromiseErrorCallback>(resolver),
+ ExecutionContext::From(script_state)));
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.cc
index 89ec9b3f123..9a0dcd3f2bc 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.cc
@@ -6,12 +6,13 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_blob.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_readable_stream.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/fetch/fetch_data_loader.h"
#include "third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/fileapi/file_error.h"
-#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
+#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -26,18 +27,18 @@ ScriptPromise FileSystemWriter::write(ScriptState* script_state,
ScriptValue data,
ExceptionState& exception_state) {
v8::Isolate* isolate = script_state->GetIsolate();
- if (V8Blob::hasInstance(data.V8Value(), isolate)) {
+ if (V8Blob::HasInstance(data.V8Value(), isolate)) {
Blob* blob = V8Blob::ToImpl(data.V8Value().As<v8::Object>());
return WriteBlob(script_state, position, blob);
}
- if (!ReadableStreamOperations::IsReadableStream(script_state, data,
- exception_state)
- .value_or(false)) {
+ if (!V8ReadableStream::HasInstance(data.V8Value(), isolate)) {
if (!exception_state.HadException())
exception_state.ThrowTypeError("data should be a Blob or ReadableStream");
return ScriptPromise();
}
- return WriteStream(script_state, position, data, exception_state);
+ return WriteStream(script_state, position,
+ V8ReadableStream::ToImpl(data.V8Value().As<v8::Object>()),
+ exception_state);
}
ScriptPromise FileSystemWriter::WriteBlob(ScriptState* script_state,
@@ -92,7 +93,7 @@ class FileSystemWriter::StreamWriterClient
DCHECK(writer_->pending_operation_);
did_complete_ = true;
writer_->pending_operation_->Reject(
- FileError::CreateDOMException(base::File::FILE_ERROR_FAILED));
+ file_error::CreateDOMException(base::File::FILE_ERROR_FAILED));
Reset();
}
@@ -104,7 +105,7 @@ class FileSystemWriter::StreamWriterClient
DCHECK(writer_->pending_operation_);
did_complete_ = true;
writer_->pending_operation_->Reject(
- FileError::CreateDOMException(base::File::FILE_ERROR_ABORT));
+ file_error::CreateDOMException(base::File::FILE_ERROR_ABORT));
Reset();
}
@@ -116,7 +117,7 @@ class FileSystemWriter::StreamWriterClient
did_complete_ = true;
if (result != base::File::FILE_OK) {
writer_->pending_operation_->Reject(
- FileError::CreateDOMException(result));
+ file_error::CreateDOMException(result));
} else {
DCHECK(did_finish_writing_to_pipe_);
writer_->pending_operation_->Resolve();
@@ -143,7 +144,7 @@ class FileSystemWriter::StreamWriterClient
ScriptPromise FileSystemWriter::WriteStream(ScriptState* script_state,
uint64_t position,
- ScriptValue stream,
+ ReadableStream* stream,
ExceptionState& exception_state) {
if (!writer_ || pending_operation_) {
return ScriptPromise::RejectWithDOMException(
@@ -152,11 +153,11 @@ ScriptPromise FileSystemWriter::WriteStream(ScriptState* script_state,
}
DCHECK(!stream_loader_);
- auto reader = ReadableStreamOperations::GetReader(script_state, stream,
- exception_state);
+ auto reader = stream->getReader(script_state, exception_state);
if (exception_state.HadException())
return ScriptPromise();
- auto* consumer = new ReadableStreamBytesConsumer(script_state, reader);
+ auto* consumer =
+ MakeGarbageCollected<ReadableStreamBytesConsumer>(script_state, reader);
stream_loader_ = FetchDataLoader::CreateLoaderAsDataPipe(
ExecutionContext::From(script_state)
@@ -207,7 +208,7 @@ void FileSystemWriter::WriteComplete(base::File::Error result,
if (result == base::File::FILE_OK) {
pending_operation_->Resolve();
} else {
- pending_operation_->Reject(FileError::CreateDOMException(result));
+ pending_operation_->Reject(file_error::CreateDOMException(result));
}
pending_operation_ = nullptr;
}
@@ -217,7 +218,7 @@ void FileSystemWriter::TruncateComplete(base::File::Error result) {
if (result == base::File::FILE_OK) {
pending_operation_->Resolve();
} else {
- pending_operation_->Reject(FileError::CreateDOMException(result));
+ pending_operation_->Reject(file_error::CreateDOMException(result));
}
pending_operation_ = nullptr;
}
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.h b/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.h
index 6fa00725759..a0e417fb724 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_system_writer.h
@@ -14,6 +14,7 @@ namespace blink {
class Blob;
class ExceptionState;
class FetchDataLoader;
+class ReadableStream;
class ScriptPromise;
class ScriptPromiseResolver;
class ScriptState;
@@ -40,7 +41,7 @@ class FileSystemWriter final : public ScriptWrappable {
ScriptPromise WriteBlob(ScriptState*, uint64_t position, Blob*);
ScriptPromise WriteStream(ScriptState*,
uint64_t position,
- ScriptValue stream,
+ ReadableStream* stream,
ExceptionState&);
void WriteComplete(base::File::Error result, uint64_t bytes_written);
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_writer.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_writer.cc
index 5ad31e6b662..94dbe810812 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_writer.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_writer.cc
@@ -33,6 +33,7 @@
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/renderer/core/events/progress_event.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
+#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/modules/filesystem/file_system_dispatcher.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -44,7 +45,7 @@ static const int kMaxRecursionDepth = 3;
static const double kProgressNotificationIntervalMS = 50;
FileWriter* FileWriter::Create(ExecutionContext* context) {
- return new FileWriter(context);
+ return MakeGarbageCollected<FileWriter>(context);
}
FileWriter::FileWriter(ExecutionContext* context)
@@ -65,7 +66,7 @@ FileWriter::~FileWriter() {
}
const AtomicString& FileWriter::InterfaceName() const {
- return EventTargetNames::FileWriter;
+ return event_target_names::kFileWriter;
}
void FileWriter::ContextDestroyed(ExecutionContext*) {
@@ -83,11 +84,11 @@ void FileWriter::write(Blob* data, ExceptionState& exception_state) {
DCHECK(data);
DCHECK_EQ(truncate_length_, -1);
if (ready_state_ == kWriting) {
- SetError(FileError::kInvalidStateErr, exception_state);
+ SetError(FileErrorCode::kInvalidStateErr, exception_state);
return;
}
if (recursion_depth_ > kMaxRecursionDepth) {
- SetError(FileError::kSecurityErr, exception_state);
+ SetError(FileErrorCode::kSecurityErr, exception_state);
return;
}
@@ -104,14 +105,14 @@ void FileWriter::write(Blob* data, ExceptionState& exception_state) {
} else
DoOperation(kOperationWrite);
- FireEvent(EventTypeNames::writestart);
+ FireEvent(event_type_names::kWritestart);
}
void FileWriter::seek(long long position, ExceptionState& exception_state) {
if (!GetExecutionContext())
return;
if (ready_state_ == kWriting) {
- SetError(FileError::kInvalidStateErr, exception_state);
+ SetError(FileErrorCode::kInvalidStateErr, exception_state);
return;
}
@@ -125,11 +126,11 @@ void FileWriter::truncate(long long position, ExceptionState& exception_state) {
return;
DCHECK_EQ(truncate_length_, -1);
if (ready_state_ == kWriting || position < 0) {
- SetError(FileError::kInvalidStateErr, exception_state);
+ SetError(FileErrorCode::kInvalidStateErr, exception_state);
return;
}
if (recursion_depth_ > kMaxRecursionDepth) {
- SetError(FileError::kSecurityErr, exception_state);
+ SetError(FileErrorCode::kSecurityErr, exception_state);
return;
}
@@ -145,7 +146,7 @@ void FileWriter::truncate(long long position, ExceptionState& exception_state) {
queued_operation_ = kOperationTruncate;
} else
DoOperation(kOperationTruncate);
- FireEvent(EventTypeNames::writestart);
+ FireEvent(event_type_names::kWritestart);
}
void FileWriter::abort(ExceptionState& exception_state) {
@@ -187,7 +188,7 @@ void FileWriter::DidWriteImpl(int64_t bytes, bool complete) {
(now - last_progress_notification_time_ms_ >
kProgressNotificationIntervalMS)) {
last_progress_notification_time_ms_ = now;
- FireEvent(EventTypeNames::progress);
+ FireEvent(event_type_names::kProgress);
}
if (complete) {
@@ -295,14 +296,15 @@ void FileWriter::SignalCompletion(base::File::Error error) {
ready_state_ = kDone;
truncate_length_ = -1;
if (error != base::File::FILE_OK) {
- error_ = FileError::CreateDOMException(error);
+ error_ = file_error::CreateDOMException(error);
if (base::File::FILE_ERROR_ABORT == error)
- FireEvent(EventTypeNames::abort);
+ FireEvent(event_type_names::kAbort);
else
- FireEvent(EventTypeNames::error);
- } else
- FireEvent(EventTypeNames::write);
- FireEvent(EventTypeNames::writeend);
+ FireEvent(event_type_names::kError);
+ } else {
+ FireEvent(event_type_names::kWrite);
+ }
+ FireEvent(event_type_names::kWriteend);
probe::AsyncTaskCanceled(GetExecutionContext(), this);
}
@@ -316,11 +318,11 @@ void FileWriter::FireEvent(const AtomicString& type) {
DCHECK_GE(recursion_depth_, 0);
}
-void FileWriter::SetError(FileError::ErrorCode error_code,
+void FileWriter::SetError(FileErrorCode error_code,
ExceptionState& exception_state) {
- DCHECK(error_code);
- FileError::ThrowDOMException(exception_state, error_code);
- error_ = FileError::CreateDOMException(error_code);
+ DCHECK_NE(error_code, FileErrorCode::kOK);
+ file_error::ThrowDOMException(exception_state, error_code);
+ error_ = file_error::CreateDOMException(error_code);
}
void FileWriter::Dispose() {
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_writer.h b/chromium/third_party/blink/renderer/modules/filesystem/file_writer.h
index 69c38d342df..64842401600 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_writer.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_writer.h
@@ -34,7 +34,6 @@
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/filesystem/file_writer_base.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -42,8 +41,10 @@
namespace blink {
class Blob;
+class DOMException;
class ExceptionState;
class ExecutionContext;
+enum class FileErrorCode;
class FileWriter final : public EventTargetWithInlineData,
public FileWriterBase,
@@ -55,6 +56,8 @@ class FileWriter final : public EventTargetWithInlineData,
public:
static FileWriter* Create(ExecutionContext*);
+
+ explicit FileWriter(ExecutionContext*);
~FileWriter() override;
enum ReadyState { kInit = 0, kWriting = 1, kDone = 2 };
@@ -88,12 +91,12 @@ class FileWriter final : public EventTargetWithInlineData,
return ContextLifecycleObserver::GetExecutionContext();
}
- DEFINE_ATTRIBUTE_EVENT_LISTENER(writestart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(write);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(writeend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(writestart, kWritestart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(progress, kProgress);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(write, kWrite);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(writeend, kWriteend);
void Trace(blink::Visitor*) override;
@@ -105,8 +108,6 @@ class FileWriter final : public EventTargetWithInlineData,
kOperationAbort
};
- explicit FileWriter(ExecutionContext*);
-
void CompleteAbort();
void DoOperation(Operation);
@@ -115,7 +116,7 @@ class FileWriter final : public EventTargetWithInlineData,
void FireEvent(const AtomicString& type);
- void SetError(FileError::ErrorCode, ExceptionState&);
+ void SetError(FileErrorCode, ExceptionState&);
void Dispose();
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.cc b/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.cc
index e9c20b16cc1..702cd3cf6f2 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.cc
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/modules/filesystem/file_system_dispatcher.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -45,7 +46,7 @@ void FileWriterSync::write(Blob* data, ExceptionState& exception_state) {
Write(position(), data->Uuid());
DCHECK(complete_);
if (error_) {
- FileError::ThrowDOMException(exception_state, error_);
+ file_error::ThrowDOMException(exception_state, error_);
return;
}
SetPosition(position() + data->size());
@@ -63,14 +64,14 @@ void FileWriterSync::truncate(long long offset,
DCHECK(complete_);
if (offset < 0) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
- FileError::kInvalidStateErrorMessage);
+ file_error::kInvalidStateErrorMessage);
return;
}
PrepareForWrite();
Truncate(offset);
DCHECK(complete_);
if (error_) {
- FileError::ThrowDOMException(exception_state, error_);
+ file_error::ThrowDOMException(exception_state, error_);
return;
}
if (offset < position())
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.h b/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.h
index 656160699d8..fff8ede6c2a 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/file_writer_sync.h
@@ -50,8 +50,10 @@ class FileWriterSync final : public ScriptWrappable,
public:
static FileWriterSync* Create(ExecutionContext* context) {
- return new FileWriterSync(context);
+ return MakeGarbageCollected<FileWriterSync>(context);
}
+
+ explicit FileWriterSync(ExecutionContext* context);
~FileWriterSync() override;
void Trace(blink::Visitor*) override;
@@ -70,7 +72,6 @@ class FileWriterSync final : public ScriptWrappable,
void DoCancel() override;
private:
- explicit FileWriterSync(ExecutionContext* context);
void PrepareForWrite();
base::File::Error error_;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/local_file_system.cc b/chromium/third_party/blink/renderer/modules/filesystem/local_file_system.cc
index c14ff58d913..b08ad890d0e 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/local_file_system.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/local_file_system.cc
@@ -206,7 +206,7 @@ LocalFileSystem* LocalFileSystem::From(ExecutionContext& context) {
return file_system;
}
- WorkerClients* clients = ToWorkerGlobalScope(context).Clients();
+ WorkerClients* clients = To<WorkerGlobalScope>(context).Clients();
DCHECK(clients);
LocalFileSystem* file_system =
Supplement<WorkerClients>::From<LocalFileSystem>(clients);
@@ -216,13 +216,15 @@ LocalFileSystem* LocalFileSystem::From(ExecutionContext& context) {
void ProvideLocalFileSystemTo(LocalFrame& frame,
std::unique_ptr<FileSystemClient> client) {
- frame.ProvideSupplement(new LocalFileSystem(frame, std::move(client)));
+ frame.ProvideSupplement(
+ MakeGarbageCollected<LocalFileSystem>(frame, std::move(client)));
}
void ProvideLocalFileSystemToWorker(WorkerClients* worker_clients,
std::unique_ptr<FileSystemClient> client) {
- Supplement<WorkerClients>::ProvideTo(
- *worker_clients, new LocalFileSystem(*worker_clients, std::move(client)));
+ Supplement<WorkerClients>::ProvideTo(*worker_clients,
+ MakeGarbageCollected<LocalFileSystem>(
+ *worker_clients, std::move(client)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/local_file_system_client.cc b/chromium/third_party/blink/renderer/modules/filesystem/local_file_system_client.cc
index ab6d6ec45b5..98d9354e832 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/local_file_system_client.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/local_file_system_client.cc
@@ -33,8 +33,8 @@
#include <memory>
#include "base/memory/ptr_util.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
@@ -60,8 +60,7 @@ bool LocalFileSystemClient::RequestFileSystemAccessSync(
return false;
}
- DCHECK(context->IsWorkerGlobalScope());
- return WorkerContentSettingsClient::From(*ToWorkerGlobalScope(context))
+ return WorkerContentSettingsClient::From(*To<WorkerGlobalScope>(context))
->RequestFileSystemAccessSync();
}
@@ -76,10 +75,11 @@ void LocalFileSystemClient::RequestFileSystemAccessAsync(
return;
}
- DCHECK(document->GetFrame());
- document->GetFrame()
- ->GetContentSettingsClient()
- ->RequestFileSystemAccessAsync(std::move(callbacks));
+ if (auto* client = document->GetFrame()->GetContentSettingsClient()) {
+ client->RequestFileSystemAccessAsync(std::move(callbacks));
+ } else {
+ callbacks->OnAllowed();
+ }
}
LocalFileSystemClient::LocalFileSystemClient() = default;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/metadata.h b/chromium/third_party/blink/renderer/modules/filesystem/metadata.h
index 93a6ee2ba0f..8bff4aee445 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/metadata.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/metadata.h
@@ -42,13 +42,16 @@ class Metadata final : public ScriptWrappable {
public:
static Metadata* Create(const FileMetadata& platform_metadata) {
- return new Metadata(platform_metadata);
+ return MakeGarbageCollected<Metadata>(platform_metadata);
}
static Metadata* Create(Metadata* metadata) {
- return new Metadata(metadata->platform_metadata_);
+ return MakeGarbageCollected<Metadata>(metadata->platform_metadata_);
}
+ explicit Metadata(const FileMetadata& platform_metadata)
+ : platform_metadata_(platform_metadata) {}
+
// Return Epoch time in milliseconds for Date.
double modificationTime() const {
return platform_metadata_.modification_time;
@@ -58,9 +61,6 @@ class Metadata final : public ScriptWrappable {
}
private:
- explicit Metadata(const FileMetadata& platform_metadata)
- : platform_metadata_(platform_metadata) {}
-
FileMetadata platform_metadata_;
};
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h b/chromium/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h
index c01ed1c6d63..805ce4c2114 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h
+++ b/chromium/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h
@@ -45,19 +45,23 @@ class DOMFileSystemCallbacksSyncHelper final
DOMFileSystemCallbacksSyncHelper<SuccessCallback, CallbackArg>> {
public:
static DOMFileSystemCallbacksSyncHelper* Create() {
- return new DOMFileSystemCallbacksSyncHelper();
+ return MakeGarbageCollected<DOMFileSystemCallbacksSyncHelper>();
}
+ DOMFileSystemCallbacksSyncHelper() = default;
+
void Trace(blink::Visitor* visitor) { visitor->Trace(result_); }
SuccessCallback* GetSuccessCallback() {
return new SuccessCallbackImpl(this);
}
- ErrorCallbackBase* GetErrorCallback() { return new ErrorCallbackImpl(this); }
+ ErrorCallbackBase* GetErrorCallback() {
+ return MakeGarbageCollected<ErrorCallbackImpl>(this);
+ }
CallbackArg* GetResultOrThrow(ExceptionState& exception_state) {
if (error_code_ != base::File::FILE_OK) {
- FileError::ThrowDOMException(exception_state, error_code_);
+ file_error::ThrowDOMException(exception_state, error_code_);
return nullptr;
}
@@ -86,6 +90,9 @@ class DOMFileSystemCallbacksSyncHelper final
class ErrorCallbackImpl final : public ErrorCallbackBase {
public:
+ explicit ErrorCallbackImpl(DOMFileSystemCallbacksSyncHelper* helper)
+ : helper_(helper) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(helper_);
ErrorCallbackBase::Trace(visitor);
@@ -96,15 +103,11 @@ class DOMFileSystemCallbacksSyncHelper final
}
private:
- explicit ErrorCallbackImpl(DOMFileSystemCallbacksSyncHelper* helper)
- : helper_(helper) {}
Member<DOMFileSystemCallbacksSyncHelper> helper_;
friend class DOMFileSystemCallbacksSyncHelper;
};
- DOMFileSystemCallbacksSyncHelper() = default;
-
Member<CallbackArg> result_;
base::File::Error error_code_ = base::File::FILE_OK;
diff --git a/chromium/third_party/blink/renderer/modules/filesystem/worker_global_scope_file_system.cc b/chromium/third_party/blink/renderer/modules/filesystem/worker_global_scope_file_system.cc
index 713954c0e53..deb97585efa 100644
--- a/chromium/third_party/blink/renderer/modules/filesystem/worker_global_scope_file_system.cc
+++ b/chromium/third_party/blink/renderer/modules/filesystem/worker_global_scope_file_system.cc
@@ -86,7 +86,7 @@ DOMFileSystemSync* WorkerGlobalScopeFileSystem::webkitRequestFileSystemSync(
ExceptionState& exception_state) {
ExecutionContext* secure_context = worker.GetExecutionContext();
if (!secure_context->GetSecurityOrigin()->CanAccessFileSystem()) {
- exception_state.ThrowSecurityError(FileError::kSecurityErrorMessage);
+ exception_state.ThrowSecurityError(file_error::kSecurityErrorMessage);
return nullptr;
} else if (secure_context->GetSecurityOrigin()->IsLocal()) {
UseCounter::Count(secure_context, WebFeature::kFileAccessedFileSystem);
@@ -155,7 +155,7 @@ EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(
ExecutionContext* secure_context = worker.GetExecutionContext();
if (!secure_context->GetSecurityOrigin()->CanAccessFileSystem() ||
!secure_context->GetSecurityOrigin()->CanRequest(completed_url)) {
- exception_state.ThrowSecurityError(FileError::kSecurityErrorMessage);
+ exception_state.ThrowSecurityError(file_error::kSecurityErrorMessage);
return nullptr;
} else if (secure_context->GetSecurityOrigin()->IsLocal()) {
UseCounter::Count(secure_context, WebFeature::kFileAccessedFileSystem);
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/BUILD.gn b/chromium/third_party/blink/renderer/modules/gamepad/BUILD.gn
index 2545e1c57c2..e50e5a69392 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/gamepad/BUILD.gn
@@ -8,8 +8,12 @@ blink_modules_sources("gamepad") {
sources = [
"gamepad.cc",
"gamepad.h",
+ "gamepad_axis_event.cc",
+ "gamepad_axis_event.h",
"gamepad_button.cc",
"gamepad_button.h",
+ "gamepad_button_event.cc",
+ "gamepad_button_event.h",
"gamepad_dispatcher.cc",
"gamepad_dispatcher.h",
"gamepad_event.cc",
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad.h
index e4141d5422b..0d60c72d6a3 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad.h
@@ -42,7 +42,9 @@ class Gamepad final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static Gamepad* Create() { return new Gamepad; }
+ static Gamepad* Create() { return MakeGarbageCollected<Gamepad>(); }
+
+ Gamepad();
~Gamepad() override;
typedef Vector<double> DoubleVector;
@@ -87,8 +89,6 @@ class Gamepad final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- Gamepad();
-
String id_;
unsigned index_;
bool connected_;
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.cc b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.cc
new file mode 100644
index 00000000000..f573067deae
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.cc
@@ -0,0 +1,34 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/gamepad/gamepad_axis_event.h"
+
+namespace blink {
+
+GamepadAxisEvent::GamepadAxisEvent(const AtomicString& type,
+ Bubbles bubbles,
+ Cancelable cancelable,
+ Gamepad* gamepad,
+ uint32_t axis,
+ double value)
+ : GamepadEvent(type, bubbles, cancelable, gamepad),
+ axis_(axis),
+ value_(value) {}
+
+GamepadAxisEvent::GamepadAxisEvent(const AtomicString& type,
+ const GamepadAxisEventInit* initializer)
+ : GamepadEvent(type, initializer) {
+ if (initializer->hasAxis())
+ axis_ = initializer->axis();
+ if (initializer->hasValue())
+ value_ = initializer->value();
+}
+
+GamepadAxisEvent::~GamepadAxisEvent() = default;
+
+const AtomicString& GamepadAxisEvent::InterfaceName() const {
+ return event_interface_names::kGamepadAxisEvent;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.h
new file mode 100644
index 00000000000..09edeea4d67
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.h
@@ -0,0 +1,53 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_GAMEPAD_AXIS_EVENT_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_GAMEPAD_AXIS_EVENT_H_
+
+#include "third_party/blink/renderer/modules/gamepad/gamepad.h"
+#include "third_party/blink/renderer/modules/gamepad/gamepad_axis_event_init.h"
+#include "third_party/blink/renderer/modules/gamepad/gamepad_event.h"
+
+namespace blink {
+
+class GamepadAxisEvent final : public GamepadEvent {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ static GamepadAxisEvent* Create(const AtomicString& type,
+ Bubbles bubbles,
+ Cancelable cancelable,
+ Gamepad* gamepad,
+ uint32_t axis,
+ double value) {
+ return new GamepadAxisEvent(type, bubbles, cancelable, gamepad, axis,
+ value);
+ }
+ static GamepadAxisEvent* Create(const AtomicString& type,
+ const GamepadAxisEventInit* initializer) {
+ return new GamepadAxisEvent(type, initializer);
+ }
+ ~GamepadAxisEvent() override;
+
+ uint32_t getAxis() const { return axis_; }
+ double getValue() const { return value_; }
+
+ const AtomicString& InterfaceName() const override;
+
+ private:
+ GamepadAxisEvent(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ Gamepad*,
+ uint32_t axis,
+ double value);
+ GamepadAxisEvent(const AtomicString&, const GamepadAxisEventInit*);
+
+ uint32_t axis_ = 0;
+ double value_ = 0.0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_GAMEPAD_AXIS_EVENT_H_
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.idl b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.idl
new file mode 100644
index 00000000000..044b4b8e73e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event.idl
@@ -0,0 +1,14 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Non-standard gamepad axis event.
+// https://docs.google.com/document/d/1rnQ1gU0iwPXbO7OvKS6KO9gyfpSdSQvKhK9_OkzUuKE
+
+[
+ RuntimeEnabled=GamepadButtonAxisEvents,
+ Constructor(DOMString type, optional GamepadAxisEventInit eventInitDict)
+] interface GamepadAxisEvent : GamepadEvent {
+ [ImplementedAs=getAxis] readonly attribute unsigned long axis;
+ [ImplementedAs=getValue] readonly attribute double value;
+};
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event_init.idl b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event_init.idl
new file mode 100644
index 00000000000..7c92561411e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_axis_event_init.idl
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Initialization dictionary type for GamepadAxisEvent.
+// https://docs.google.com/document/d/1rnQ1gU0iwPXbO7OvKS6KO9gyfpSdSQvKhK9_OkzUuKE
+
+dictionary GamepadAxisEventInit : GamepadEventInit {
+ unsigned long axis;
+ double value;
+};
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.cc b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.cc
index 914930fd1cc..d60d596ca5f 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.cc
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.cc
@@ -7,7 +7,7 @@
namespace blink {
GamepadButton* GamepadButton::Create() {
- return new GamepadButton();
+ return MakeGarbageCollected<GamepadButton>();
}
GamepadButton::GamepadButton() : value_(0.), pressed_(false), touched_(false) {}
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.h
index ed9ee1f21dd..c2838e00009 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button.h
@@ -18,6 +18,8 @@ class GamepadButton final : public ScriptWrappable {
public:
static GamepadButton* Create();
+ GamepadButton();
+
double value() const { return value_; }
void SetValue(double val) { value_ = val; }
@@ -31,7 +33,6 @@ class GamepadButton final : public ScriptWrappable {
void UpdateValuesFrom(const device::GamepadButton&);
private:
- GamepadButton();
double value_;
bool pressed_;
bool touched_;
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.cc b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.cc
new file mode 100644
index 00000000000..ceb65fbdae4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.cc
@@ -0,0 +1,35 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/gamepad/gamepad_button_event.h"
+
+namespace blink {
+
+GamepadButtonEvent::GamepadButtonEvent(const AtomicString& type,
+ Bubbles bubbles,
+ Cancelable cancelable,
+ Gamepad* gamepad,
+ uint32_t button,
+ double value)
+ : GamepadEvent(type, bubbles, cancelable, gamepad),
+ button_(button),
+ value_(value) {}
+
+GamepadButtonEvent::GamepadButtonEvent(
+ const AtomicString& type,
+ const GamepadButtonEventInit* initializer)
+ : GamepadEvent(type, initializer) {
+ if (initializer->hasButton())
+ button_ = initializer->button();
+ if (initializer->hasValue())
+ value_ = initializer->value();
+}
+
+GamepadButtonEvent::~GamepadButtonEvent() = default;
+
+const AtomicString& GamepadButtonEvent::InterfaceName() const {
+ return event_interface_names::kGamepadButtonEvent;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.h
new file mode 100644
index 00000000000..0ad4ac9455a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.h
@@ -0,0 +1,54 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_GAMEPAD_BUTTON_EVENT_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_GAMEPAD_BUTTON_EVENT_H_
+
+#include "third_party/blink/renderer/modules/gamepad/gamepad.h"
+#include "third_party/blink/renderer/modules/gamepad/gamepad_button.h"
+#include "third_party/blink/renderer/modules/gamepad/gamepad_button_event_init.h"
+#include "third_party/blink/renderer/modules/gamepad/gamepad_event.h"
+
+namespace blink {
+
+class GamepadButtonEvent final : public GamepadEvent {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ static GamepadButtonEvent* Create(const AtomicString& type,
+ Bubbles bubbles,
+ Cancelable cancelable,
+ Gamepad* gamepad,
+ uint32_t button,
+ double value) {
+ return new GamepadButtonEvent(type, bubbles, cancelable, gamepad, button,
+ value);
+ }
+ static GamepadButtonEvent* Create(const AtomicString& type,
+ const GamepadButtonEventInit* initializer) {
+ return new GamepadButtonEvent(type, initializer);
+ }
+ ~GamepadButtonEvent() override;
+
+ uint32_t getButton() const { return button_; }
+ double getValue() const { return value_; }
+
+ const AtomicString& InterfaceName() const override;
+
+ private:
+ GamepadButtonEvent(const AtomicString& type,
+ Bubbles,
+ Cancelable,
+ Gamepad*,
+ uint32_t button,
+ double value);
+ GamepadButtonEvent(const AtomicString&, const GamepadButtonEventInit*);
+
+ uint32_t button_ = 0;
+ double value_ = 0.0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_GAMEPAD_GAMEPAD_BUTTON_EVENT_H_
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.idl b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.idl
new file mode 100644
index 00000000000..21ac8cf4c1a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event.idl
@@ -0,0 +1,14 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Non-standard gamepad button event.
+// https://docs.google.com/document/d/1rnQ1gU0iwPXbO7OvKS6KO9gyfpSdSQvKhK9_OkzUuKE
+
+[
+ RuntimeEnabled=GamepadButtonAxisEvents,
+ Constructor(DOMString type, optional GamepadButtonEventInit eventInitDict)
+] interface GamepadButtonEvent : GamepadEvent {
+ [ImplementedAs=getButton] readonly attribute unsigned long button;
+ [ImplementedAs=getValue] readonly attribute double value;
+};
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event_init.idl b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event_init.idl
new file mode 100644
index 00000000000..0f423aa89c4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_button_event_init.idl
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Initialization dictionary type for GamepadButtonEvent.
+// https://docs.google.com/document/d/1rnQ1gU0iwPXbO7OvKS6KO9gyfpSdSQvKhK9_OkzUuKE
+
+dictionary GamepadButtonEventInit : GamepadEventInit {
+ unsigned long button;
+ double value;
+};
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.cc b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.cc
index d2a2a356b5e..2c304003c39 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.cc
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.cc
@@ -13,16 +13,16 @@ GamepadEvent::GamepadEvent(const AtomicString& type,
: Event(type, bubbles, cancelable), gamepad_(gamepad) {}
GamepadEvent::GamepadEvent(const AtomicString& type,
- const GamepadEventInit& initializer)
+ const GamepadEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasGamepad())
- gamepad_ = initializer.gamepad();
+ if (initializer->hasGamepad())
+ gamepad_ = initializer->gamepad();
}
GamepadEvent::~GamepadEvent() = default;
const AtomicString& GamepadEvent::InterfaceName() const {
- return EventNames::GamepadEvent;
+ return event_interface_names::kGamepadEvent;
}
void GamepadEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.h
index c647d852d16..e581f005fd8 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_event.h
@@ -11,7 +11,7 @@
namespace blink {
-class GamepadEvent final : public Event {
+class GamepadEvent : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
@@ -19,12 +19,16 @@ class GamepadEvent final : public Event {
Bubbles bubbles,
Cancelable cancelable,
Gamepad* gamepad) {
- return new GamepadEvent(type, bubbles, cancelable, gamepad);
+ return MakeGarbageCollected<GamepadEvent>(type, bubbles, cancelable,
+ gamepad);
}
static GamepadEvent* Create(const AtomicString& type,
- const GamepadEventInit& initializer) {
- return new GamepadEvent(type, initializer);
+ const GamepadEventInit* initializer) {
+ return MakeGarbageCollected<GamepadEvent>(type, initializer);
}
+
+ GamepadEvent(const AtomicString& type, Bubbles, Cancelable, Gamepad*);
+ GamepadEvent(const AtomicString&, const GamepadEventInit*);
~GamepadEvent() override;
Gamepad* getGamepad() const { return gamepad_.Get(); }
@@ -34,9 +38,6 @@ class GamepadEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- GamepadEvent(const AtomicString& type, Bubbles, Cancelable, Gamepad*);
- GamepadEvent(const AtomicString&, const GamepadEventInit&);
-
Member<Gamepad> gamepad_;
};
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc
index 9b353880ce5..723626dac92 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.cc
@@ -53,7 +53,7 @@ namespace blink {
// static
GamepadHapticActuator* GamepadHapticActuator::Create(int pad_index) {
- return new GamepadHapticActuator(
+ return MakeGarbageCollected<GamepadHapticActuator>(
pad_index, device::GamepadHapticActuatorType::kDualRumble);
}
@@ -82,19 +82,19 @@ void GamepadHapticActuator::SetType(device::GamepadHapticActuatorType type) {
ScriptPromise GamepadHapticActuator::playEffect(
ScriptState* script_state,
const String& type,
- const GamepadEffectParameters& params) {
+ const GamepadEffectParameters* params) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
- if (params.duration() < 0.0 || params.startDelay() < 0.0 ||
- params.strongMagnitude() < 0.0 || params.strongMagnitude() > 1.0 ||
- params.weakMagnitude() < 0.0 || params.weakMagnitude() > 1.0) {
+ if (params->duration() < 0.0 || params->startDelay() < 0.0 ||
+ params->strongMagnitude() < 0.0 || params->strongMagnitude() > 1.0 ||
+ params->weakMagnitude() < 0.0 || params->weakMagnitude() > 1.0) {
ScriptPromise promise = resolver->Promise();
resolver->Resolve(kGamepadHapticsResultInvalidParameter);
return promise;
}
// Limit the total effect duration.
- double effect_duration = params.duration() + params.startDelay();
+ double effect_duration = params->duration() + params->startDelay();
if (effect_duration >
device::GamepadHapticActuator::kMaxEffectDurationMillis) {
ScriptPromise promise = resolver->Promise();
@@ -108,8 +108,8 @@ ScriptPromise GamepadHapticActuator::playEffect(
GamepadDispatcher::Instance().PlayVibrationEffectOnce(
pad_index_, EffectTypeFromString(type),
device::mojom::blink::GamepadEffectParameters::New(
- params.duration(), params.startDelay(), params.strongMagnitude(),
- params.weakMagnitude()),
+ params->duration(), params->startDelay(), params->strongMagnitude(),
+ params->weakMagnitude()),
std::move(callback));
return resolver->Promise();
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h
index 0eee49d7485..57fe1468134 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_haptic_actuator.h
@@ -22,6 +22,8 @@ class GamepadHapticActuator final : public ScriptWrappable {
public:
static GamepadHapticActuator* Create(int pad_index);
+
+ GamepadHapticActuator(int pad_index, device::GamepadHapticActuatorType);
~GamepadHapticActuator() override;
const String& type() const { return type_; }
@@ -29,15 +31,13 @@ class GamepadHapticActuator final : public ScriptWrappable {
ScriptPromise playEffect(ScriptState*,
const String&,
- const GamepadEffectParameters&);
+ const GamepadEffectParameters*);
ScriptPromise reset(ScriptState*);
void Trace(blink::Visitor*) override;
private:
- GamepadHapticActuator(int pad_index, device::GamepadHapticActuatorType);
-
void OnPlayEffectCompleted(ScriptPromiseResolver*,
device::mojom::GamepadHapticsResult);
void OnResetCompleted(ScriptPromiseResolver*,
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_list.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_list.h
index f9038138747..631abecf597 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_list.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_list.h
@@ -37,7 +37,9 @@ class GamepadList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static GamepadList* Create() { return new GamepadList(); }
+ static GamepadList* Create() { return MakeGarbageCollected<GamepadList>(); }
+
+ GamepadList();
void Set(unsigned index, Gamepad*);
Gamepad* item(unsigned index);
@@ -46,7 +48,6 @@ class GamepadList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- GamepadList();
Member<Gamepad> items_[device::Gamepads::kItemsLengthCap];
};
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_pose.h b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_pose.h
index 2247967543c..4bf4f6c4fed 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/gamepad_pose.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/gamepad_pose.h
@@ -17,7 +17,9 @@ class GamepadPose final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static GamepadPose* Create() { return new GamepadPose(); }
+ static GamepadPose* Create() { return MakeGarbageCollected<GamepadPose>(); }
+
+ GamepadPose();
bool hasOrientation() const { return has_orientation_; }
bool hasPosition() const { return has_position_; }
@@ -34,8 +36,6 @@ class GamepadPose final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- GamepadPose();
-
bool has_orientation_;
bool has_position_;
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.cc b/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.cc
index 66209e12b2f..3f027a1ad5a 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.cc
+++ b/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.cc
@@ -150,9 +150,9 @@ static void SampleGamepads(ListType* into,
bool hide_xr_gamepad = false;
if (web_gamepad.is_xr) {
bool webxr_enabled =
- (context && OriginTrials::WebXRGamepadSupportEnabled(context) &&
- OriginTrials::WebXREnabled(context));
- bool webvr_enabled = (context && OriginTrials::WebVREnabled(context));
+ (context && origin_trials::WebXRGamepadSupportEnabled(context) &&
+ origin_trials::WebXREnabled(context));
+ bool webvr_enabled = (context && origin_trials::WebVREnabled(context));
if (!webxr_enabled && !webvr_enabled) {
// If neither WebXR nor WebVR are enabled, we should not expose XR-
@@ -189,7 +189,7 @@ NavigatorGamepad& NavigatorGamepad::From(Navigator& navigator) {
NavigatorGamepad* supplement =
Supplement<Navigator>::From<NavigatorGamepad>(navigator);
if (!supplement) {
- supplement = new NavigatorGamepad(navigator);
+ supplement = MakeGarbageCollected<NavigatorGamepad>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -260,8 +260,8 @@ void NavigatorGamepad::DispatchOneEvent() {
Gamepad* gamepad = pending_events_.TakeFirst();
const AtomicString& event_name = gamepad->connected()
- ? EventTypeNames::gamepadconnected
- : EventTypeNames::gamepaddisconnected;
+ ? event_type_names::kGamepadconnected
+ : event_type_names::kGamepaddisconnected;
DomWindow()->DispatchEvent(*GamepadEvent::Create(
event_name, Event::Bubbles::kNo, Event::Cancelable::kYes, gamepad));
@@ -315,8 +315,8 @@ bool NavigatorGamepad::HasLastData() {
}
static bool IsGamepadEvent(const AtomicString& event_type) {
- return event_type == EventTypeNames::gamepadconnected ||
- event_type == EventTypeNames::gamepaddisconnected;
+ return event_type == event_type_names::kGamepadconnected ||
+ event_type == event_type_names::kGamepaddisconnected;
}
void NavigatorGamepad::DidAddEventListener(LocalDOMWindow*,
@@ -337,8 +337,8 @@ void NavigatorGamepad::DidAddEventListener(LocalDOMWindow*,
void NavigatorGamepad::DidRemoveEventListener(LocalDOMWindow* window,
const AtomicString& event_type) {
if (IsGamepadEvent(event_type) &&
- !window->HasEventListeners(EventTypeNames::gamepadconnected) &&
- !window->HasEventListeners(EventTypeNames::gamepaddisconnected)) {
+ !window->HasEventListeners(event_type_names::kGamepadconnected) &&
+ !window->HasEventListeners(event_type_names::kGamepaddisconnected)) {
DidRemoveGamepadEventListeners();
}
}
diff --git a/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.h b/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.h
index a71aa760e07..3e03be576e8 100644
--- a/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.h
+++ b/chromium/third_party/blink/renderer/modules/gamepad/navigator_gamepad.h
@@ -56,6 +56,8 @@ class MODULES_EXPORT NavigatorGamepad final
static NavigatorGamepad* From(Document&);
static NavigatorGamepad& From(Navigator&);
+
+ explicit NavigatorGamepad(Navigator&);
~NavigatorGamepad() override;
static GamepadList* getGamepads(Navigator&);
@@ -64,8 +66,6 @@ class MODULES_EXPORT NavigatorGamepad final
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorGamepad(Navigator&);
-
void DispatchOneEvent();
void DidRemoveGamepadEventListeners();
bool StartUpdatingIfAttached();
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.cc b/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.cc
index ce8d3a7f3cf..907b2befe96 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.cc
+++ b/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.cc
@@ -17,7 +17,7 @@ namespace blink {
GeoNotifier::GeoNotifier(Geolocation* geolocation,
V8PositionCallback* success_callback,
V8PositionErrorCallback* error_callback,
- const PositionOptions& options)
+ const PositionOptions* options)
: geolocation_(geolocation),
success_callback_(success_callback),
error_callback_(error_callback),
@@ -33,11 +33,12 @@ GeoNotifier::GeoNotifier(Geolocation* geolocation,
DEFINE_STATIC_LOCAL(CustomCountHistogram, timeout_histogram,
("Geolocation.Timeout", 0,
1000 * 60 * 10 /* 10 minute max */, 20 /* buckets */));
- timeout_histogram.Count(options_.timeout());
+ timeout_histogram.Count(options_->timeout());
}
void GeoNotifier::Trace(blink::Visitor* visitor) {
visitor->Trace(geolocation_);
+ visitor->Trace(options_);
visitor->Trace(success_callback_);
visitor->Trace(error_callback_);
visitor->Trace(timer_);
@@ -72,7 +73,7 @@ void GeoNotifier::RunErrorCallback(PositionError* error) {
}
void GeoNotifier::StartTimer() {
- timer_->StartOneShot(TimeDelta::FromMilliseconds(options_.timeout()),
+ timer_->StartOneShot(TimeDelta::FromMilliseconds(options_->timeout()),
FROM_HERE);
}
@@ -138,7 +139,7 @@ void GeoNotifier::TimerFired(TimerBase*) {
DEFINE_STATIC_LOCAL(CustomCountHistogram, timeout_expired_histogram,
("Geolocation.TimeoutExpired", 0,
1000 * 60 * 10 /* 10 minute max */, 20 /* buckets */));
- timeout_expired_histogram.Count(options_.timeout());
+ timeout_expired_histogram.Count(options_->timeout());
geolocation_->RequestTimedOut(this);
}
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.h b/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.h
index b50ede3a0f5..de5c1b8f408 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.h
+++ b/chromium/third_party/blink/renderer/modules/geolocation/geo_notifier.h
@@ -26,15 +26,20 @@ class GeoNotifier final : public GarbageCollectedFinalized<GeoNotifier>,
static GeoNotifier* Create(Geolocation* geolocation,
V8PositionCallback* position_callback,
V8PositionErrorCallback* position_error_callback,
- const PositionOptions& options) {
- return new GeoNotifier(geolocation, position_callback,
- position_error_callback, options);
+ const PositionOptions* options) {
+ return MakeGarbageCollected<GeoNotifier>(geolocation, position_callback,
+ position_error_callback, options);
}
+
+ GeoNotifier(Geolocation*,
+ V8PositionCallback*,
+ V8PositionErrorCallback*,
+ const PositionOptions*);
~GeoNotifier() = default;
void Trace(blink::Visitor*);
const char* NameInHeapSnapshot() const override { return "GeoNotifier"; }
- const PositionOptions& Options() const { return options_; }
+ const PositionOptions* Options() const { return options_; }
// Sets the given error as the fatal error if there isn't one yet.
// Starts the timer with an interval of 0.
@@ -64,9 +69,15 @@ class GeoNotifier final : public GarbageCollectedFinalized<GeoNotifier>,
scoped_refptr<base::SingleThreadTaskRunner> web_task_runner,
GeoNotifier* notifier,
void (GeoNotifier::*member_func)(TimerBase*)) {
- return new Timer(web_task_runner, notifier, member_func);
+ return MakeGarbageCollected<Timer>(web_task_runner, notifier,
+ member_func);
}
+ explicit Timer(scoped_refptr<base::SingleThreadTaskRunner> web_task_runner,
+ GeoNotifier* notifier,
+ void (GeoNotifier::*member_func)(TimerBase*))
+ : timer_(web_task_runner, notifier, member_func), notifier_(notifier) {}
+
void Trace(blink::Visitor*);
// TimerBase-compatible API
@@ -75,20 +86,10 @@ class GeoNotifier final : public GarbageCollectedFinalized<GeoNotifier>,
bool IsActive() const { return timer_.IsActive(); }
private:
- explicit Timer(scoped_refptr<base::SingleThreadTaskRunner> web_task_runner,
- GeoNotifier* notifier,
- void (GeoNotifier::*member_func)(TimerBase*))
- : timer_(web_task_runner, notifier, member_func), notifier_(notifier) {}
-
TaskRunnerTimer<GeoNotifier> timer_;
Member<GeoNotifier> notifier_;
};
- GeoNotifier(Geolocation*,
- V8PositionCallback*,
- V8PositionErrorCallback*,
- const PositionOptions&);
-
// Runs the error callback if there is a fatal error. Otherwise, if a
// cached position must be used, registers itself for receiving one.
// Otherwise, the notifier has expired, and its error callback is run.
@@ -97,7 +98,7 @@ class GeoNotifier final : public GarbageCollectedFinalized<GeoNotifier>,
Member<Geolocation> geolocation_;
TraceWrapperMember<V8PositionCallback> success_callback_;
TraceWrapperMember<V8PositionErrorCallback> error_callback_;
- const PositionOptions options_;
+ Member<const PositionOptions> options_;
Member<Timer> timer_;
Member<PositionError> fatal_error_;
bool use_cached_position_;
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/geolocation.cc b/chromium/third_party/blink/renderer/modules/geolocation/geolocation.cc
index 87bd0323537..dff776ceef6 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/geolocation.cc
+++ b/chromium/third_party/blink/renderer/modules/geolocation/geolocation.cc
@@ -99,14 +99,14 @@ static void ReportGeolocationViolation(Document* doc) {
} // namespace
Geolocation* Geolocation::Create(ExecutionContext* context) {
- Geolocation* geolocation = new Geolocation(context);
+ Geolocation* geolocation = MakeGarbageCollected<Geolocation>(context);
return geolocation;
}
Geolocation::Geolocation(ExecutionContext* context)
: ContextLifecycleObserver(context),
PageVisibilityObserver(GetDocument()->GetPage()),
- watchers_(new GeolocationWatchers()) {}
+ watchers_(MakeGarbageCollected<GeolocationWatchers>()) {}
Geolocation::~Geolocation() = default;
@@ -178,7 +178,7 @@ void Geolocation::RecordOriginTypeAccess() const {
void Geolocation::getCurrentPosition(V8PositionCallback* success_callback,
V8PositionErrorCallback* error_callback,
- const PositionOptions& options) {
+ const PositionOptions* options) {
if (!GetFrame())
return;
@@ -194,7 +194,7 @@ void Geolocation::getCurrentPosition(V8PositionCallback* success_callback,
int Geolocation::watchPosition(V8PositionCallback* success_callback,
V8PositionErrorCallback* error_callback,
- const PositionOptions& options) {
+ const PositionOptions* options) {
if (!GetFrame())
return 0;
@@ -227,11 +227,9 @@ void Geolocation::StartRequest(GeoNotifier* notifier) {
if (!GetDocument()->IsFeatureEnabled(
mojom::FeaturePolicyFeature::kGeolocation,
- ReportOptions::kReportOnFailure)) {
+ ReportOptions::kReportOnFailure, kFeaturePolicyConsoleWarning)) {
UseCounter::Count(GetDocument(),
WebFeature::kGeolocationDisabledByFeaturePolicy);
- GetDocument()->AddConsoleMessage(ConsoleMessage::Create(
- kJSMessageSource, kErrorMessageLevel, kFeaturePolicyConsoleWarning));
notifier->SetFatalError(PositionError::Create(
PositionError::kPermissionDenied, kFeaturePolicyErrorMessage));
return;
@@ -242,7 +240,7 @@ void Geolocation::StartRequest(GeoNotifier* notifier) {
if (HaveSuitableCachedPosition(notifier->Options())) {
notifier->SetUseCachedPosition();
} else {
- if (notifier->Options().timeout() > 0)
+ if (notifier->Options()->timeout() > 0)
StartUpdating(notifier);
notifier->StartTimer();
}
@@ -269,7 +267,7 @@ void Geolocation::RequestUsesCachedPosition(GeoNotifier* notifier) {
if (one_shots_.Contains(notifier)) {
one_shots_.erase(notifier);
} else if (watchers_->Contains(notifier)) {
- if (notifier->Options().timeout() > 0)
+ if (notifier->Options()->timeout() > 0)
StartUpdating(notifier);
notifier->StartTimer();
}
@@ -295,15 +293,15 @@ bool Geolocation::DoesOwnNotifier(GeoNotifier* notifier) const {
watchers_being_invoked_.Contains(notifier);
}
-bool Geolocation::HaveSuitableCachedPosition(const PositionOptions& options) {
+bool Geolocation::HaveSuitableCachedPosition(const PositionOptions* options) {
if (!last_position_)
return false;
- if (!options.maximumAge())
+ if (!options->maximumAge())
return false;
DOMTimeStamp current_time_millis =
ConvertSecondsToDOMTimeStamp(CurrentTime());
return last_position_->timestamp() >
- current_time_millis - options.maximumAge();
+ current_time_millis - options->maximumAge();
}
void Geolocation::clearWatch(int watch_id) {
@@ -435,7 +433,7 @@ void Geolocation::PositionChanged() {
void Geolocation::StartUpdating(GeoNotifier* notifier) {
updating_ = true;
- if (notifier->Options().enableHighAccuracy() && !enable_high_accuracy_) {
+ if (notifier->Options()->enableHighAccuracy() && !enable_high_accuracy_) {
enable_high_accuracy_ = true;
if (geolocation_)
geolocation_->SetHighAccuracy(true);
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/geolocation.h b/chromium/third_party/blink/renderer/modules/geolocation/geolocation.h
index 9a59a4e3f32..50f7b26dd21 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/geolocation.h
+++ b/chromium/third_party/blink/renderer/modules/geolocation/geolocation.h
@@ -60,6 +60,8 @@ class MODULES_EXPORT Geolocation final
public:
static Geolocation* Create(ExecutionContext*);
+
+ explicit Geolocation(ExecutionContext*);
~Geolocation() override;
void Trace(blink::Visitor*) override;
@@ -73,13 +75,13 @@ class MODULES_EXPORT Geolocation final
// constraints of the options.
void getCurrentPosition(V8PositionCallback*,
V8PositionErrorCallback* = nullptr,
- const PositionOptions& = PositionOptions());
+ const PositionOptions* = PositionOptions::Create());
// Creates a watcher that will be notified whenever a new position is
// available that meets the constraints of the options.
int watchPosition(V8PositionCallback*,
V8PositionErrorCallback* = nullptr,
- const PositionOptions& = PositionOptions());
+ const PositionOptions* = PositionOptions::Create());
// Removes all references to the watcher, it will not be updated again.
void clearWatch(int watch_id);
@@ -153,8 +155,6 @@ class MODULES_EXPORT Geolocation final
void ClearWithoutTimerCheck() { BaseClass::clear(); }
};
- explicit Geolocation(ExecutionContext*);
-
bool HasListeners() const {
return !one_shots_.IsEmpty() || !watchers_->IsEmpty();
}
@@ -184,7 +184,7 @@ class MODULES_EXPORT Geolocation final
// obtained.
void StartRequest(GeoNotifier*);
- bool HaveSuitableCachedPosition(const PositionOptions&);
+ bool HaveSuitableCachedPosition(const PositionOptions*);
// Record whether the origin trying to access Geolocation would be allowed
// to access a feature that can only be accessed by secure origins.
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/geolocation_error.h b/chromium/third_party/blink/renderer/modules/geolocation/geolocation_error.h
index 1601dfead1c..da1cfdff8c7 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/geolocation_error.h
+++ b/chromium/third_party/blink/renderer/modules/geolocation/geolocation_error.h
@@ -35,17 +35,18 @@ class GeolocationError : public GarbageCollectedFinalized<GeolocationError> {
enum ErrorCode { kPermissionDenied, kPositionUnavailable };
static GeolocationError* Create(ErrorCode code, const String& message) {
- return new GeolocationError(code, message);
+ return MakeGarbageCollected<GeolocationError>(code, message);
}
+
+ GeolocationError(ErrorCode code, const String& message)
+ : code_(code), message_(message) {}
+
void Trace(blink::Visitor* visitor) {}
ErrorCode Code() const { return code_; }
const String& Message() const { return message_; }
private:
- GeolocationError(ErrorCode code, const String& message)
- : code_(code), message_(message) {}
-
ErrorCode code_;
String message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/geoposition.h b/chromium/third_party/blink/renderer/modules/geolocation/geoposition.h
index cbb5c44e949..02b867b8f9a 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/geoposition.h
+++ b/chromium/third_party/blink/renderer/modules/geolocation/geoposition.h
@@ -40,7 +40,12 @@ class Geoposition final : public ScriptWrappable {
public:
static Geoposition* Create(Coordinates* coordinates, DOMTimeStamp timestamp) {
- return new Geoposition(coordinates, timestamp);
+ return MakeGarbageCollected<Geoposition>(coordinates, timestamp);
+ }
+
+ Geoposition(Coordinates* coordinates, DOMTimeStamp timestamp)
+ : coordinates_(coordinates), timestamp_(timestamp) {
+ DCHECK(coordinates_);
}
void Trace(blink::Visitor* visitor) override {
@@ -52,11 +57,6 @@ class Geoposition final : public ScriptWrappable {
Coordinates* coords() const { return coordinates_; }
private:
- Geoposition(Coordinates* coordinates, DOMTimeStamp timestamp)
- : coordinates_(coordinates), timestamp_(timestamp) {
- DCHECK(coordinates_);
- }
-
Member<Coordinates> coordinates_;
DOMTimeStamp timestamp_;
};
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.cc b/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.cc
index 78a4ea18706..352f21e5946 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.cc
+++ b/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.cc
@@ -40,7 +40,7 @@ NavigatorGeolocation& NavigatorGeolocation::From(Navigator& navigator) {
NavigatorGeolocation* supplement =
Supplement<Navigator>::From<NavigatorGeolocation>(navigator);
if (!supplement) {
- supplement = new NavigatorGeolocation(navigator);
+ supplement = MakeGarbageCollected<NavigatorGeolocation>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.h b/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.h
index 00f39e269c7..1f1c1366ccc 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.h
+++ b/chromium/third_party/blink/renderer/modules/geolocation/navigator_geolocation.h
@@ -44,14 +44,14 @@ class NavigatorGeolocation final
static Geolocation* geolocation(Navigator&);
Geolocation* geolocation();
+ explicit NavigatorGeolocation(Navigator&);
+
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override {
return "NavigatorGeolocation";
}
private:
- explicit NavigatorGeolocation(Navigator&);
-
TraceWrapperMember<Geolocation> geolocation_;
};
diff --git a/chromium/third_party/blink/renderer/modules/geolocation/position_error.h b/chromium/third_party/blink/renderer/modules/geolocation/position_error.h
index f25efd13f0e..ae30a3ab56d 100644
--- a/chromium/third_party/blink/renderer/modules/geolocation/position_error.h
+++ b/chromium/third_party/blink/renderer/modules/geolocation/position_error.h
@@ -43,18 +43,18 @@ class PositionError final : public ScriptWrappable {
};
static PositionError* Create(ErrorCode code, const String& message) {
- return new PositionError(code, message);
+ return MakeGarbageCollected<PositionError>(code, message);
}
+ PositionError(ErrorCode code, const String& message)
+ : code_(code), message_(message), is_fatal_(false) {}
+
ErrorCode code() const { return code_; }
const String& message() const { return message_; }
void SetIsFatal(bool is_fatal) { is_fatal_ = is_fatal; }
bool IsFatal() const { return is_fatal_; }
private:
- PositionError(ErrorCode code, const String& message)
- : code_(code), message_(message), is_fatal_(false) {}
-
ErrorCode code_;
String message_;
// Whether the error is fatal, such that no request can ever obtain a good
diff --git a/chromium/third_party/blink/renderer/modules/imagecapture/README.md b/chromium/third_party/blink/renderer/modules/imagecapture/README.md
index 79853bb3d18..6a92c9f8bbf 100644
--- a/chromium/third_party/blink/renderer/modules/imagecapture/README.md
+++ b/chromium/third_party/blink/renderer/modules/imagecapture/README.md
@@ -123,10 +123,10 @@ of modifying it can only be seen after taking a picture.
## Testing
-Image Capture layout tests are located in [LayoutTests/imagecapture],
-[LayoutTests/fast/imagecapture] and [LayoutTests/external/mediacapture-image].
+Image Capture layout tests are located in [web_tests/imagecapture],
+[web_tests/fast/imagecapture] and [web_tests/external/mediacapture-image].
-[LayoutTests/imagecapture]: https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/imagecapture
-[LayoutTests/fast/imagecapture]: https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/fast/imagecapture/
-[LayoutTests/external/mediacapture-image]: https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/external/wpt/mediacapture-image/
+[web_tests/imagecapture]: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/web_tests/imagecapture
+[web_tests/fast/imagecapture]: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/web_tests/fast/imagecapture/
+[web_tests/external/mediacapture-image]: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/web_tests/external/wpt/mediacapture-image/
diff --git a/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.cc b/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.cc
index 6cb4156980d..b82bf3a86c7 100644
--- a/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.cc
+++ b/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.cc
@@ -94,7 +94,7 @@ ImageCapture* ImageCapture::Create(ExecutionContext* context,
return nullptr;
}
- return new ImageCapture(context, track);
+ return MakeGarbageCollected<ImageCapture>(context, track);
}
ImageCapture::~ImageCapture() {
@@ -105,7 +105,7 @@ ImageCapture::~ImageCapture() {
}
const AtomicString& ImageCapture::InterfaceName() const {
- return EventTargetNames::ImageCapture;
+ return event_target_names::kImageCapture;
}
ExecutionContext* ImageCapture::GetExecutionContext() const {
@@ -175,7 +175,7 @@ ScriptPromise ImageCapture::getPhotoSettings(ScriptState* script_state) {
}
ScriptPromise ImageCapture::setOptions(ScriptState* script_state,
- const PhotoSettings& photo_settings,
+ const PhotoSettings* photo_settings,
bool trigger_take_photo /* = false */) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -197,9 +197,9 @@ ScriptPromise ImageCapture::setOptions(ScriptState* script_state,
// TODO(mcasas): should be using a mojo::StructTraits instead.
auto settings = media::mojom::blink::PhotoSettings::New();
- settings->has_height = photo_settings.hasImageHeight();
+ settings->has_height = photo_settings->hasImageHeight();
if (settings->has_height) {
- const double height = photo_settings.imageHeight();
+ const double height = photo_settings->imageHeight();
if (photo_capabilities_ &&
(height < photo_capabilities_->imageHeight()->min() ||
height > photo_capabilities_->imageHeight()->max())) {
@@ -210,9 +210,9 @@ ScriptPromise ImageCapture::setOptions(ScriptState* script_state,
}
settings->height = height;
}
- settings->has_width = photo_settings.hasImageWidth();
+ settings->has_width = photo_settings->hasImageWidth();
if (settings->has_width) {
- const double width = photo_settings.imageWidth();
+ const double width = photo_settings->imageWidth();
if (photo_capabilities_ &&
(width < photo_capabilities_->imageWidth()->min() ||
width > photo_capabilities_->imageWidth()->max())) {
@@ -224,7 +224,7 @@ ScriptPromise ImageCapture::setOptions(ScriptState* script_state,
settings->width = width;
}
- settings->has_red_eye_reduction = photo_settings.hasRedEyeReduction();
+ settings->has_red_eye_reduction = photo_settings->hasRedEyeReduction();
if (settings->has_red_eye_reduction) {
if (photo_capabilities_ &&
!photo_capabilities_->IsRedEyeReductionControllable()) {
@@ -233,12 +233,12 @@ ScriptPromise ImageCapture::setOptions(ScriptState* script_state,
"redEyeReduction is not controllable."));
return promise;
}
- settings->red_eye_reduction = photo_settings.redEyeReduction();
+ settings->red_eye_reduction = photo_settings->redEyeReduction();
}
- settings->has_fill_light_mode = photo_settings.hasFillLightMode();
+ settings->has_fill_light_mode = photo_settings->hasFillLightMode();
if (settings->has_fill_light_mode) {
- const String fill_light_mode = photo_settings.fillLightMode();
+ const String fill_light_mode = photo_settings->fillLightMode();
if (photo_capabilities_ && photo_capabilities_->fillLightMode().Find(
fill_light_mode) == kNotFound) {
resolver->Reject(DOMException::Create(
@@ -285,7 +285,7 @@ ScriptPromise ImageCapture::takePhoto(ScriptState* script_state) {
}
ScriptPromise ImageCapture::takePhoto(ScriptState* script_state,
- const PhotoSettings& photo_settings) {
+ const PhotoSettings* photo_settings) {
return setOptions(script_state, photo_settings,
true /* trigger_take_photo */);
}
@@ -321,7 +321,7 @@ ScriptPromise ImageCapture::grabFrame(ScriptState* script_state) {
return promise;
}
-MediaTrackCapabilities& ImageCapture::GetMediaTrackCapabilities() {
+MediaTrackCapabilities* ImageCapture::GetMediaTrackCapabilities() const {
return capabilities_;
}
@@ -329,7 +329,7 @@ MediaTrackCapabilities& ImageCapture::GetMediaTrackCapabilities() {
// inside the method, https://crbug.com/708723.
void ImageCapture::SetMediaTrackConstraints(
ScriptPromiseResolver* resolver,
- const HeapVector<MediaTrackConstraintSet>& constraints_vector) {
+ const HeapVector<Member<MediaTrackConstraintSet>>& constraints_vector) {
DCHECK_GT(constraints_vector.size(), 0u);
if (!service_) {
resolver->Reject(DOMException::Create(DOMExceptionCode::kNotFoundError,
@@ -337,243 +337,246 @@ void ImageCapture::SetMediaTrackConstraints(
return;
}
// TODO(mcasas): add support more than one single advanced constraint.
- auto constraints = constraints_vector[0];
-
- if ((constraints.hasWhiteBalanceMode() &&
- !capabilities_.hasWhiteBalanceMode()) ||
- (constraints.hasExposureMode() && !capabilities_.hasExposureMode()) ||
- (constraints.hasFocusMode() && !capabilities_.hasFocusMode()) ||
- (constraints.hasExposureCompensation() &&
- !capabilities_.hasExposureCompensation()) ||
- (constraints.hasExposureTime() && !capabilities_.hasExposureTime()) ||
- (constraints.hasColorTemperature() &&
- !capabilities_.hasColorTemperature()) ||
- (constraints.hasIso() && !capabilities_.hasIso()) ||
- (constraints.hasBrightness() && !capabilities_.hasBrightness()) ||
- (constraints.hasContrast() && !capabilities_.hasContrast()) ||
- (constraints.hasSaturation() && !capabilities_.hasSaturation()) ||
- (constraints.hasSharpness() && !capabilities_.hasSharpness()) ||
- (constraints.hasFocusDistance() && !capabilities_.hasFocusDistance()) ||
- (constraints.hasZoom() && !capabilities_.hasZoom()) ||
- (constraints.hasTorch() && !capabilities_.hasTorch())) {
+ const MediaTrackConstraintSet* constraints = constraints_vector[0];
+
+ if ((constraints->hasWhiteBalanceMode() &&
+ !capabilities_->hasWhiteBalanceMode()) ||
+ (constraints->hasExposureMode() && !capabilities_->hasExposureMode()) ||
+ (constraints->hasFocusMode() && !capabilities_->hasFocusMode()) ||
+ (constraints->hasExposureCompensation() &&
+ !capabilities_->hasExposureCompensation()) ||
+ (constraints->hasExposureTime() && !capabilities_->hasExposureTime()) ||
+ (constraints->hasColorTemperature() &&
+ !capabilities_->hasColorTemperature()) ||
+ (constraints->hasIso() && !capabilities_->hasIso()) ||
+ (constraints->hasBrightness() && !capabilities_->hasBrightness()) ||
+ (constraints->hasContrast() && !capabilities_->hasContrast()) ||
+ (constraints->hasSaturation() && !capabilities_->hasSaturation()) ||
+ (constraints->hasSharpness() && !capabilities_->hasSharpness()) ||
+ (constraints->hasFocusDistance() && !capabilities_->hasFocusDistance()) ||
+ (constraints->hasZoom() && !capabilities_->hasZoom()) ||
+ (constraints->hasTorch() && !capabilities_->hasTorch())) {
resolver->Reject(DOMException::Create(DOMExceptionCode::kNotSupportedError,
"Unsupported constraint(s)"));
return;
}
auto settings = media::mojom::blink::PhotoSettings::New();
- MediaTrackConstraintSet temp_constraints = current_constraints_;
+ MediaTrackConstraintSet* temp_constraints = current_constraints_;
// TODO(mcasas): support other Mode types beyond simple string i.e. the
// equivalents of "sequence<DOMString>"" or "ConstrainDOMStringParameters".
- settings->has_white_balance_mode = constraints.hasWhiteBalanceMode() &&
- constraints.whiteBalanceMode().IsString();
+ settings->has_white_balance_mode = constraints->hasWhiteBalanceMode() &&
+ constraints->whiteBalanceMode().IsString();
if (settings->has_white_balance_mode) {
const auto white_balance_mode =
- constraints.whiteBalanceMode().GetAsString();
- if (capabilities_.whiteBalanceMode().Find(white_balance_mode) ==
+ constraints->whiteBalanceMode().GetAsString();
+ if (capabilities_->whiteBalanceMode().Find(white_balance_mode) ==
kNotFound) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"Unsupported whiteBalanceMode."));
return;
}
- temp_constraints.setWhiteBalanceMode(constraints.whiteBalanceMode());
+ temp_constraints->setWhiteBalanceMode(constraints->whiteBalanceMode());
settings->white_balance_mode = ParseMeteringMode(white_balance_mode);
}
settings->has_exposure_mode =
- constraints.hasExposureMode() && constraints.exposureMode().IsString();
+ constraints->hasExposureMode() && constraints->exposureMode().IsString();
if (settings->has_exposure_mode) {
- const auto exposure_mode = constraints.exposureMode().GetAsString();
- if (capabilities_.exposureMode().Find(exposure_mode) == kNotFound) {
+ const auto exposure_mode = constraints->exposureMode().GetAsString();
+ if (capabilities_->exposureMode().Find(exposure_mode) == kNotFound) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError, "Unsupported exposureMode."));
return;
}
- temp_constraints.setExposureMode(constraints.exposureMode());
+ temp_constraints->setExposureMode(constraints->exposureMode());
settings->exposure_mode = ParseMeteringMode(exposure_mode);
}
settings->has_focus_mode =
- constraints.hasFocusMode() && constraints.focusMode().IsString();
+ constraints->hasFocusMode() && constraints->focusMode().IsString();
if (settings->has_focus_mode) {
- const auto focus_mode = constraints.focusMode().GetAsString();
- if (capabilities_.focusMode().Find(focus_mode) == kNotFound) {
+ const auto focus_mode = constraints->focusMode().GetAsString();
+ if (capabilities_->focusMode().Find(focus_mode) == kNotFound) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError, "Unsupported focusMode."));
return;
}
- temp_constraints.setFocusMode(constraints.focusMode());
+ temp_constraints->setFocusMode(constraints->focusMode());
settings->focus_mode = ParseMeteringMode(focus_mode);
}
// TODO(mcasas): support ConstrainPoint2DParameters.
- if (constraints.hasPointsOfInterest() &&
- constraints.pointsOfInterest().IsPoint2DSequence()) {
+ if (constraints->hasPointsOfInterest() &&
+ constraints->pointsOfInterest().IsPoint2DSequence()) {
for (const auto& point :
- constraints.pointsOfInterest().GetAsPoint2DSequence()) {
+ constraints->pointsOfInterest().GetAsPoint2DSequence()) {
auto mojo_point = media::mojom::blink::Point2D::New();
- mojo_point->x = point.x();
- mojo_point->y = point.y();
+ mojo_point->x = point->x();
+ mojo_point->y = point->y();
settings->points_of_interest.push_back(std::move(mojo_point));
}
- temp_constraints.setPointsOfInterest(constraints.pointsOfInterest());
+ temp_constraints->setPointsOfInterest(constraints->pointsOfInterest());
}
// TODO(mcasas): support ConstrainDoubleRange where applicable.
settings->has_exposure_compensation =
- constraints.hasExposureCompensation() &&
- constraints.exposureCompensation().IsDouble();
+ constraints->hasExposureCompensation() &&
+ constraints->exposureCompensation().IsDouble();
if (settings->has_exposure_compensation) {
const auto exposure_compensation =
- constraints.exposureCompensation().GetAsDouble();
- if (exposure_compensation < capabilities_.exposureCompensation()->min() ||
- exposure_compensation > capabilities_.exposureCompensation()->max()) {
+ constraints->exposureCompensation().GetAsDouble();
+ if (exposure_compensation < capabilities_->exposureCompensation()->min() ||
+ exposure_compensation > capabilities_->exposureCompensation()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"exposureCompensation setting out of range"));
return;
}
- temp_constraints.setExposureCompensation(
- constraints.exposureCompensation());
+ temp_constraints->setExposureCompensation(
+ constraints->exposureCompensation());
settings->exposure_compensation = exposure_compensation;
}
+
settings->has_exposure_time =
- constraints.hasExposureTime() && constraints.exposureTime().IsDouble();
+ constraints->hasExposureTime() && constraints->exposureTime().IsDouble();
if (settings->has_exposure_time) {
- const auto exposure_time = constraints.exposureTime().GetAsDouble();
- if (exposure_time < capabilities_.exposureTime()->min() ||
- exposure_time > capabilities_.exposureTime()->max()) {
+ const auto exposure_time = constraints->exposureTime().GetAsDouble();
+ if (exposure_time < capabilities_->exposureTime()->min() ||
+ exposure_time > capabilities_->exposureTime()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"exposureTime setting out of range"));
return;
}
- temp_constraints.setExposureTime(constraints.exposureTime());
+ temp_constraints->setExposureTime(constraints->exposureTime());
settings->exposure_time = exposure_time;
}
- settings->has_color_temperature = constraints.hasColorTemperature() &&
- constraints.colorTemperature().IsDouble();
+ settings->has_color_temperature = constraints->hasColorTemperature() &&
+ constraints->colorTemperature().IsDouble();
if (settings->has_color_temperature) {
- const auto color_temperature = constraints.colorTemperature().GetAsDouble();
- if (color_temperature < capabilities_.colorTemperature()->min() ||
- color_temperature > capabilities_.colorTemperature()->max()) {
+ const auto color_temperature =
+ constraints->colorTemperature().GetAsDouble();
+ if (color_temperature < capabilities_->colorTemperature()->min() ||
+ color_temperature > capabilities_->colorTemperature()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"colorTemperature setting out of range"));
return;
}
- temp_constraints.setColorTemperature(constraints.colorTemperature());
+ temp_constraints->setColorTemperature(constraints->colorTemperature());
settings->color_temperature = color_temperature;
}
- settings->has_iso = constraints.hasIso() && constraints.iso().IsDouble();
+ settings->has_iso = constraints->hasIso() && constraints->iso().IsDouble();
if (settings->has_iso) {
- const auto iso = constraints.iso().GetAsDouble();
- if (iso < capabilities_.iso()->min() || iso > capabilities_.iso()->max()) {
+ const auto iso = constraints->iso().GetAsDouble();
+ if (iso < capabilities_->iso()->min() ||
+ iso > capabilities_->iso()->max()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError, "iso setting out of range"));
return;
}
- temp_constraints.setIso(constraints.iso());
+ temp_constraints->setIso(constraints->iso());
settings->iso = iso;
}
settings->has_brightness =
- constraints.hasBrightness() && constraints.brightness().IsDouble();
+ constraints->hasBrightness() && constraints->brightness().IsDouble();
if (settings->has_brightness) {
- const auto brightness = constraints.brightness().GetAsDouble();
- if (brightness < capabilities_.brightness()->min() ||
- brightness > capabilities_.brightness()->max()) {
+ const auto brightness = constraints->brightness().GetAsDouble();
+ if (brightness < capabilities_->brightness()->min() ||
+ brightness > capabilities_->brightness()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"brightness setting out of range"));
return;
}
- temp_constraints.setBrightness(constraints.brightness());
+ temp_constraints->setBrightness(constraints->brightness());
settings->brightness = brightness;
}
settings->has_contrast =
- constraints.hasContrast() && constraints.contrast().IsDouble();
+ constraints->hasContrast() && constraints->contrast().IsDouble();
if (settings->has_contrast) {
- const auto contrast = constraints.contrast().GetAsDouble();
- if (contrast < capabilities_.contrast()->min() ||
- contrast > capabilities_.contrast()->max()) {
+ const auto contrast = constraints->contrast().GetAsDouble();
+ if (contrast < capabilities_->contrast()->min() ||
+ contrast > capabilities_->contrast()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"contrast setting out of range"));
return;
}
- temp_constraints.setContrast(constraints.contrast());
+ temp_constraints->setContrast(constraints->contrast());
settings->contrast = contrast;
}
settings->has_saturation =
- constraints.hasSaturation() && constraints.saturation().IsDouble();
+ constraints->hasSaturation() && constraints->saturation().IsDouble();
if (settings->has_saturation) {
- const auto saturation = constraints.saturation().GetAsDouble();
- if (saturation < capabilities_.saturation()->min() ||
- saturation > capabilities_.saturation()->max()) {
+ const auto saturation = constraints->saturation().GetAsDouble();
+ if (saturation < capabilities_->saturation()->min() ||
+ saturation > capabilities_->saturation()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"saturation setting out of range"));
return;
}
- temp_constraints.setSaturation(constraints.saturation());
+ temp_constraints->setSaturation(constraints->saturation());
settings->saturation = saturation;
}
settings->has_sharpness =
- constraints.hasSharpness() && constraints.sharpness().IsDouble();
+ constraints->hasSharpness() && constraints->sharpness().IsDouble();
if (settings->has_sharpness) {
- const auto sharpness = constraints.sharpness().GetAsDouble();
- if (sharpness < capabilities_.sharpness()->min() ||
- sharpness > capabilities_.sharpness()->max()) {
+ const auto sharpness = constraints->sharpness().GetAsDouble();
+ if (sharpness < capabilities_->sharpness()->min() ||
+ sharpness > capabilities_->sharpness()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"sharpness setting out of range"));
return;
}
- temp_constraints.setSharpness(constraints.sharpness());
+ temp_constraints->setSharpness(constraints->sharpness());
settings->sharpness = sharpness;
}
- settings->has_focus_distance =
- constraints.hasFocusDistance() && constraints.focusDistance().IsDouble();
+ settings->has_focus_distance = constraints->hasFocusDistance() &&
+ constraints->focusDistance().IsDouble();
if (settings->has_focus_distance) {
- const auto focus_distance = constraints.focusDistance().GetAsDouble();
- if (focus_distance < capabilities_.focusDistance()->min() ||
- focus_distance > capabilities_.focusDistance()->max()) {
+ const auto focus_distance = constraints->focusDistance().GetAsDouble();
+ if (focus_distance < capabilities_->focusDistance()->min() ||
+ focus_distance > capabilities_->focusDistance()->max()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kNotSupportedError,
"focusDistance setting out of range"));
return;
}
- temp_constraints.setFocusDistance(constraints.focusDistance());
+ temp_constraints->setFocusDistance(constraints->focusDistance());
settings->focus_distance = focus_distance;
}
- settings->has_zoom = constraints.hasZoom() && constraints.zoom().IsDouble();
+ settings->has_zoom = constraints->hasZoom() && constraints->zoom().IsDouble();
if (settings->has_zoom) {
- const auto zoom = constraints.zoom().GetAsDouble();
- if (zoom < capabilities_.zoom()->min() ||
- zoom > capabilities_.zoom()->max()) {
+ const auto zoom = constraints->zoom().GetAsDouble();
+ if (zoom < capabilities_->zoom()->min() ||
+ zoom > capabilities_->zoom()->max()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError, "zoom setting out of range"));
return;
}
- temp_constraints.setZoom(constraints.zoom());
+ temp_constraints->setZoom(constraints->zoom());
settings->zoom = zoom;
}
// TODO(mcasas): support ConstrainBooleanParameters where applicable.
settings->has_torch =
- constraints.hasTorch() && constraints.torch().IsBoolean();
+ constraints->hasTorch() && constraints->torch().IsBoolean();
if (settings->has_torch) {
- const auto torch = constraints.torch().GetAsBoolean();
- if (torch && !capabilities_.torch()) {
+ const auto torch = constraints->torch().GetAsBoolean();
+ if (torch && !capabilities_->torch()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError, "torch not supported"));
return;
}
- temp_constraints.setTorch(constraints.torch());
+ temp_constraints->setTorch(constraints->torch());
settings->torch = torch;
}
@@ -587,61 +590,66 @@ void ImageCapture::SetMediaTrackConstraints(
WrapPersistent(resolver), false /* trigger_take_photo */));
}
-const MediaTrackConstraintSet& ImageCapture::GetMediaTrackConstraints() const {
+const MediaTrackConstraintSet* ImageCapture::GetMediaTrackConstraints() const {
return current_constraints_;
}
void ImageCapture::ClearMediaTrackConstraints() {
- current_constraints_ = MediaTrackConstraintSet();
+ current_constraints_ = MediaTrackConstraintSet::Create();
// TODO(mcasas): Clear also any PhotoSettings that the device might have got
// configured, for that we need to know a "default" state of the device; take
// a snapshot upon first opening. https://crbug.com/700607.
}
-void ImageCapture::GetMediaTrackSettings(MediaTrackSettings& settings) const {
+void ImageCapture::GetMediaTrackSettings(MediaTrackSettings* settings) const {
// Merge any present |settings_| members into |settings|.
- if (settings_.hasWhiteBalanceMode())
- settings.setWhiteBalanceMode(settings_.whiteBalanceMode());
- if (settings_.hasExposureMode())
- settings.setExposureMode(settings_.exposureMode());
- if (settings_.hasFocusMode())
- settings.setFocusMode(settings_.focusMode());
-
- if (settings_.hasPointsOfInterest() &&
- !settings_.pointsOfInterest().IsEmpty()) {
- settings.setPointsOfInterest(settings_.pointsOfInterest());
- }
-
- if (settings_.hasExposureCompensation())
- settings.setExposureCompensation(settings_.exposureCompensation());
- if (settings_.hasExposureTime())
- settings.setExposureTime(settings_.exposureTime());
- if (settings_.hasColorTemperature())
- settings.setColorTemperature(settings_.colorTemperature());
- if (settings_.hasIso())
- settings.setIso(settings_.iso());
-
- if (settings_.hasBrightness())
- settings.setBrightness(settings_.brightness());
- if (settings_.hasContrast())
- settings.setContrast(settings_.contrast());
- if (settings_.hasSaturation())
- settings.setSaturation(settings_.saturation());
- if (settings_.hasSharpness())
- settings.setSharpness(settings_.sharpness());
-
- if (settings_.hasFocusDistance())
- settings.setFocusDistance(settings_.focusDistance());
- if (settings_.hasZoom())
- settings.setZoom(settings_.zoom());
- if (settings_.hasTorch())
- settings.setTorch(settings_.torch());
+ if (settings_->hasWhiteBalanceMode())
+ settings->setWhiteBalanceMode(settings_->whiteBalanceMode());
+ if (settings_->hasExposureMode())
+ settings->setExposureMode(settings_->exposureMode());
+ if (settings_->hasFocusMode())
+ settings->setFocusMode(settings_->focusMode());
+
+ if (settings_->hasPointsOfInterest() &&
+ !settings_->pointsOfInterest().IsEmpty()) {
+ settings->setPointsOfInterest(settings_->pointsOfInterest());
+ }
+
+ if (settings_->hasExposureCompensation())
+ settings->setExposureCompensation(settings_->exposureCompensation());
+ if (settings_->hasExposureTime())
+ settings->setExposureTime(settings_->exposureTime());
+ if (settings_->hasColorTemperature())
+ settings->setColorTemperature(settings_->colorTemperature());
+ if (settings_->hasIso())
+ settings->setIso(settings_->iso());
+
+ if (settings_->hasBrightness())
+ settings->setBrightness(settings_->brightness());
+ if (settings_->hasContrast())
+ settings->setContrast(settings_->contrast());
+ if (settings_->hasSaturation())
+ settings->setSaturation(settings_->saturation());
+ if (settings_->hasSharpness())
+ settings->setSharpness(settings_->sharpness());
+
+ if (settings_->hasFocusDistance())
+ settings->setFocusDistance(settings_->focusDistance());
+ if (settings_->hasZoom())
+ settings->setZoom(settings_->zoom());
+ if (settings_->hasTorch())
+ settings->setTorch(settings_->torch());
}
ImageCapture::ImageCapture(ExecutionContext* context, MediaStreamTrack* track)
- : ContextLifecycleObserver(context), stream_track_(track) {
+ : ContextLifecycleObserver(context),
+ stream_track_(track),
+ capabilities_(MediaTrackCapabilities::Create()),
+ settings_(MediaTrackSettings::Create()),
+ current_constraints_(MediaTrackConstraintSet::Create()),
+ photo_settings_(PhotoSettings::Create()) {
DCHECK(stream_track_);
DCHECK(!service_.is_bound());
@@ -676,9 +684,9 @@ void ImageCapture::OnMojoGetPhotoState(
return;
}
- photo_settings_ = PhotoSettings();
- photo_settings_.setImageHeight(photo_state->height->current);
- photo_settings_.setImageWidth(photo_state->width->current);
+ photo_settings_ = PhotoSettings::Create();
+ photo_settings_->setImageHeight(photo_state->height->current);
+ photo_settings_->setImageWidth(photo_state->width->current);
// TODO(mcasas): collect the remaining two entries https://crbug.com/732521.
photo_capabilities_ = PhotoCapabilities::Create();
@@ -761,8 +769,9 @@ void ImageCapture::UpdateMediaTrackCapabilities(
for (const auto& supported_mode : photo_state->supported_white_balance_modes)
supported_white_balance_modes.push_back(ToString(supported_mode));
if (!supported_white_balance_modes.IsEmpty()) {
- capabilities_.setWhiteBalanceMode(std::move(supported_white_balance_modes));
- settings_.setWhiteBalanceMode(
+ capabilities_->setWhiteBalanceMode(
+ std::move(supported_white_balance_modes));
+ settings_->setWhiteBalanceMode(
ToString(photo_state->current_white_balance_mode));
}
@@ -772,8 +781,8 @@ void ImageCapture::UpdateMediaTrackCapabilities(
for (const auto& supported_mode : photo_state->supported_exposure_modes)
supported_exposure_modes.push_back(ToString(supported_mode));
if (!supported_exposure_modes.IsEmpty()) {
- capabilities_.setExposureMode(std::move(supported_exposure_modes));
- settings_.setExposureMode(ToString(photo_state->current_exposure_mode));
+ capabilities_->setExposureMode(std::move(supported_exposure_modes));
+ settings_->setExposureMode(ToString(photo_state->current_exposure_mode));
}
WTF::Vector<WTF::String> supported_focus_modes;
@@ -782,82 +791,82 @@ void ImageCapture::UpdateMediaTrackCapabilities(
for (const auto& supported_mode : photo_state->supported_focus_modes)
supported_focus_modes.push_back(ToString(supported_mode));
if (!supported_focus_modes.IsEmpty()) {
- capabilities_.setFocusMode(std::move(supported_focus_modes));
- settings_.setFocusMode(ToString(photo_state->current_focus_mode));
+ capabilities_->setFocusMode(std::move(supported_focus_modes));
+ settings_->setFocusMode(ToString(photo_state->current_focus_mode));
}
- HeapVector<Point2D> current_points_of_interest;
+ HeapVector<Member<Point2D>> current_points_of_interest;
if (!photo_state->points_of_interest.IsEmpty()) {
for (const auto& point : photo_state->points_of_interest) {
- Point2D web_point;
- web_point.setX(point->x);
- web_point.setY(point->y);
- current_points_of_interest.push_back(mojo::Clone(web_point));
+ Point2D* web_point = Point2D::Create();
+ web_point->setX(point->x);
+ web_point->setY(point->y);
+ current_points_of_interest.push_back(web_point);
}
}
- settings_.setPointsOfInterest(std::move(current_points_of_interest));
+ settings_->setPointsOfInterest(current_points_of_interest);
// TODO(mcasas): Remove the explicit MediaSettingsRange::create() when
// mojo::StructTraits supports garbage-collected mappings,
// https://crbug.com/700180.
if (photo_state->exposure_compensation->max !=
photo_state->exposure_compensation->min) {
- capabilities_.setExposureCompensation(
+ capabilities_->setExposureCompensation(
MediaSettingsRange::Create(*photo_state->exposure_compensation));
- settings_.setExposureCompensation(
+ settings_->setExposureCompensation(
photo_state->exposure_compensation->current);
}
if (photo_state->exposure_time->max != photo_state->exposure_time->min) {
- capabilities_.setExposureTime(
+ capabilities_->setExposureTime(
MediaSettingsRange::Create(*photo_state->exposure_time));
- settings_.setExposureTime(photo_state->exposure_time->current);
+ settings_->setExposureTime(photo_state->exposure_time->current);
}
if (photo_state->color_temperature->max !=
photo_state->color_temperature->min) {
- capabilities_.setColorTemperature(
+ capabilities_->setColorTemperature(
MediaSettingsRange::Create(*photo_state->color_temperature));
- settings_.setColorTemperature(photo_state->color_temperature->current);
+ settings_->setColorTemperature(photo_state->color_temperature->current);
}
if (photo_state->iso->max != photo_state->iso->min) {
- capabilities_.setIso(MediaSettingsRange::Create(*photo_state->iso));
- settings_.setIso(photo_state->iso->current);
+ capabilities_->setIso(MediaSettingsRange::Create(*photo_state->iso));
+ settings_->setIso(photo_state->iso->current);
}
if (photo_state->brightness->max != photo_state->brightness->min) {
- capabilities_.setBrightness(
+ capabilities_->setBrightness(
MediaSettingsRange::Create(*photo_state->brightness));
- settings_.setBrightness(photo_state->brightness->current);
+ settings_->setBrightness(photo_state->brightness->current);
}
if (photo_state->contrast->max != photo_state->contrast->min) {
- capabilities_.setContrast(
+ capabilities_->setContrast(
MediaSettingsRange::Create(*photo_state->contrast));
- settings_.setContrast(photo_state->contrast->current);
+ settings_->setContrast(photo_state->contrast->current);
}
if (photo_state->saturation->max != photo_state->saturation->min) {
- capabilities_.setSaturation(
+ capabilities_->setSaturation(
MediaSettingsRange::Create(*photo_state->saturation));
- settings_.setSaturation(photo_state->saturation->current);
+ settings_->setSaturation(photo_state->saturation->current);
}
if (photo_state->sharpness->max != photo_state->sharpness->min) {
- capabilities_.setSharpness(
+ capabilities_->setSharpness(
MediaSettingsRange::Create(*photo_state->sharpness));
- settings_.setSharpness(photo_state->sharpness->current);
+ settings_->setSharpness(photo_state->sharpness->current);
}
if (photo_state->focus_distance->max != photo_state->focus_distance->min) {
- capabilities_.setFocusDistance(
+ capabilities_->setFocusDistance(
MediaSettingsRange::Create(*photo_state->focus_distance));
- settings_.setFocusDistance(photo_state->focus_distance->current);
+ settings_->setFocusDistance(photo_state->focus_distance->current);
}
if (photo_state->zoom->max != photo_state->zoom->min) {
- capabilities_.setZoom(MediaSettingsRange::Create(*photo_state->zoom));
- settings_.setZoom(photo_state->zoom->current);
+ capabilities_->setZoom(MediaSettingsRange::Create(*photo_state->zoom));
+ settings_->setZoom(photo_state->zoom->current);
}
if (photo_state->supports_torch)
- capabilities_.setTorch(photo_state->supports_torch);
+ capabilities_->setTorch(photo_state->supports_torch);
if (photo_state->supports_torch)
- settings_.setTorch(photo_state->torch);
+ settings_->setTorch(photo_state->torch);
}
void ImageCapture::OnServiceConnectionError() {
@@ -889,6 +898,7 @@ void ImageCapture::Trace(blink::Visitor* visitor) {
visitor->Trace(stream_track_);
visitor->Trace(capabilities_);
visitor->Trace(settings_);
+ visitor->Trace(photo_settings_);
visitor->Trace(current_constraints_);
visitor->Trace(photo_capabilities_);
visitor->Trace(service_requests_);
diff --git a/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.h b/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.h
index 2b2362c4be2..a88b8689e75 100644
--- a/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.h
+++ b/chromium/third_party/blink/renderer/modules/imagecapture/image_capture.h
@@ -40,6 +40,8 @@ class MODULES_EXPORT ImageCapture final
static ImageCapture* Create(ExecutionContext*,
MediaStreamTrack*,
ExceptionState&);
+
+ ImageCapture(ExecutionContext*, MediaStreamTrack*);
~ImageCapture() override;
// EventTarget implementation.
@@ -58,20 +60,21 @@ class MODULES_EXPORT ImageCapture final
ScriptPromise getPhotoSettings(ScriptState*);
ScriptPromise setOptions(ScriptState*,
- const PhotoSettings&,
+ const PhotoSettings*,
bool trigger_take_photo = false);
ScriptPromise takePhoto(ScriptState*);
- ScriptPromise takePhoto(ScriptState*, const PhotoSettings&);
+ ScriptPromise takePhoto(ScriptState*, const PhotoSettings*);
ScriptPromise grabFrame(ScriptState*);
- MediaTrackCapabilities& GetMediaTrackCapabilities();
- void SetMediaTrackConstraints(ScriptPromiseResolver*,
- const HeapVector<MediaTrackConstraintSet>&);
- const MediaTrackConstraintSet& GetMediaTrackConstraints() const;
+ MediaTrackCapabilities* GetMediaTrackCapabilities() const;
+ void SetMediaTrackConstraints(
+ ScriptPromiseResolver*,
+ const HeapVector<Member<MediaTrackConstraintSet>>&);
+ const MediaTrackConstraintSet* GetMediaTrackConstraints() const;
void ClearMediaTrackConstraints();
- void GetMediaTrackSettings(MediaTrackSettings&) const;
+ void GetMediaTrackSettings(MediaTrackSettings*) const;
void Trace(blink::Visitor*) override;
@@ -79,8 +82,6 @@ class MODULES_EXPORT ImageCapture final
using PromiseResolverFunction =
base::OnceCallback<void(ScriptPromiseResolver*)>;
- ImageCapture(ExecutionContext*, MediaStreamTrack*);
-
void OnMojoGetPhotoState(ScriptPromiseResolver*,
PromiseResolverFunction,
bool trigger_take_photo,
@@ -101,10 +102,10 @@ class MODULES_EXPORT ImageCapture final
std::unique_ptr<WebImageCaptureFrameGrabber> frame_grabber_;
media::mojom::blink::ImageCapturePtr service_;
- MediaTrackCapabilities capabilities_;
- MediaTrackSettings settings_;
- MediaTrackConstraintSet current_constraints_;
- PhotoSettings photo_settings_;
+ Member<MediaTrackCapabilities> capabilities_;
+ Member<MediaTrackSettings> settings_;
+ Member<MediaTrackConstraintSet> current_constraints_;
+ Member<PhotoSettings> photo_settings_;
Member<PhotoCapabilities> photo_capabilities_;
diff --git a/chromium/third_party/blink/renderer/modules/imagecapture/media_settings_range.h b/chromium/third_party/blink/renderer/modules/imagecapture/media_settings_range.h
index 0fbb640f1d3..5cc23e0d568 100644
--- a/chromium/third_party/blink/renderer/modules/imagecapture/media_settings_range.h
+++ b/chromium/third_party/blink/renderer/modules/imagecapture/media_settings_range.h
@@ -15,7 +15,7 @@ class MediaSettingsRange final : public ScriptWrappable {
public:
static MediaSettingsRange* Create(double max, double min, double step) {
- return new MediaSettingsRange(max, min, step);
+ return MakeGarbageCollected<MediaSettingsRange>(max, min, step);
}
static MediaSettingsRange* Create(media::mojom::blink::RangePtr range) {
return MediaSettingsRange::Create(*range);
@@ -24,14 +24,14 @@ class MediaSettingsRange final : public ScriptWrappable {
return MediaSettingsRange::Create(range.max, range.min, range.step);
}
+ MediaSettingsRange(double max, double min, double step)
+ : max_(max), min_(min), step_(step) {}
+
double max() const { return max_; }
double min() const { return min_; }
double step() const { return step_; }
private:
- MediaSettingsRange(double max, double min, double step)
- : max_(max), min_(min), step_(step) {}
-
double max_;
double min_;
double step_;
diff --git a/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.cc b/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.cc
index db1f481b2ef..7da6e62e34e 100644
--- a/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.cc
+++ b/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.cc
@@ -8,7 +8,7 @@ namespace blink {
// static
PhotoCapabilities* PhotoCapabilities::Create() {
- return new PhotoCapabilities();
+ return MakeGarbageCollected<PhotoCapabilities>();
}
Vector<String> PhotoCapabilities::fillLightMode() const {
diff --git a/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.h b/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.h
index 334c0a3352a..802b653b8fe 100644
--- a/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.h
+++ b/chromium/third_party/blink/renderer/modules/imagecapture/photo_capabilities.h
@@ -18,6 +18,8 @@ class PhotoCapabilities final : public ScriptWrappable {
public:
static PhotoCapabilities* Create();
+
+ PhotoCapabilities() = default;
~PhotoCapabilities() override = default;
MediaSettingsRange* imageHeight() const { return image_height_; }
@@ -41,8 +43,6 @@ class PhotoCapabilities final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- PhotoCapabilities() = default;
-
Member<MediaSettingsRange> image_height_;
Member<MediaSettingsRange> image_width_;
Vector<media::mojom::blink::FillLightMode> fill_light_modes_;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/BUILD.gn b/chromium/third_party/blink/renderer/modules/indexeddb/BUILD.gn
index b16dcc0321f..624dbe229fb 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/BUILD.gn
@@ -58,13 +58,34 @@ blink_modules_sources("indexeddb") {
"idb_version_change_event.cc",
"idb_version_change_event.h",
"indexed_db.h",
+ "indexed_db_blink_mojom_traits.cc",
+ "indexed_db_blink_mojom_traits.h",
+ "indexed_db_callbacks_impl.cc",
+ "indexed_db_callbacks_impl.h",
"indexed_db_client.cc",
"indexed_db_client.h",
+ "indexed_db_database_callbacks_impl.cc",
+ "indexed_db_database_callbacks_impl.h",
+ "indexed_db_dispatcher.cc",
+ "indexed_db_dispatcher.h",
"inspector_indexed_db_agent.cc",
"inspector_indexed_db_agent.h",
"web_idb_callbacks_impl.cc",
"web_idb_callbacks_impl.h",
+ "web_idb_cursor.h",
+ "web_idb_cursor_impl.cc",
+ "web_idb_cursor_impl.h",
+ "web_idb_database.h",
"web_idb_database_callbacks_impl.cc",
"web_idb_database_callbacks_impl.h",
+ "web_idb_database_impl.cc",
+ "web_idb_database_impl.h",
+ "web_idb_factory.h",
+ "web_idb_factory_impl.cc",
+ "web_idb_factory_impl.h",
+ ]
+
+ public_deps = [
+ "//third_party/blink/public/mojom:mojom_modules_blink",
]
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/OWNERS b/chromium/third_party/blink/renderer/modules/indexeddb/OWNERS
index a740487227f..4d50d635c42 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/OWNERS
@@ -1,4 +1,9 @@
file://content/browser/indexed_db/OWNERS
+per-file *_mojom_traits*.*=set noparent
+per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS
+per-file *.typemap=set noparent
+per-file *.typemap=file://ipc/SECURITY_OWNERS
+
# TEAM: storage-dev@chromium.org
# COMPONENT: Blink>Storage>IndexedDB
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.cc
index 6b1c2550246..777f8d0a6f7 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.cc
@@ -36,11 +36,11 @@
namespace blink {
IDBAny* IDBAny::CreateUndefined() {
- return new IDBAny(kUndefinedType);
+ return MakeGarbageCollected<IDBAny>(kUndefinedType);
}
IDBAny* IDBAny::CreateNull() {
- return new IDBAny(kNullType);
+ return MakeGarbageCollected<IDBAny>(kNullType);
}
IDBAny::IDBAny(Type type) : type_(type) {
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.h
index 4c2cbf561b9..38dc88f7921 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_any.h
@@ -59,24 +59,23 @@ class MODULES_EXPORT IDBAny : public GarbageCollectedFinalized<IDBAny> {
static IDBAny* CreateNull();
template <typename T>
static IDBAny* Create(T* idb_object) {
- return new IDBAny(idb_object);
+ return MakeGarbageCollected<IDBAny>(idb_object);
}
static IDBAny* Create(DOMStringList* dom_string_list) {
- return new IDBAny(dom_string_list);
+ return MakeGarbageCollected<IDBAny>(dom_string_list);
+ }
+ static IDBAny* Create(int64_t value) {
+ return MakeGarbageCollected<IDBAny>(value);
}
- static IDBAny* Create(int64_t value) { return new IDBAny(value); }
static IDBAny* Create(std::unique_ptr<IDBKey> key) {
- return new IDBAny(std::move(key));
+ return MakeGarbageCollected<IDBAny>(std::move(key));
}
static IDBAny* Create(std::unique_ptr<IDBValue> value) {
- return new IDBAny(std::move(value));
+ return MakeGarbageCollected<IDBAny>(std::move(value));
}
static IDBAny* Create(Vector<std::unique_ptr<IDBValue>> values) {
- return new IDBAny(std::move(values));
+ return MakeGarbageCollected<IDBAny>(std::move(values));
}
- ~IDBAny();
- void Trace(blink::Visitor*);
- void ContextWillBeDestroyed();
enum Type {
kUndefinedType = 0,
@@ -91,6 +90,19 @@ class MODULES_EXPORT IDBAny : public GarbageCollectedFinalized<IDBAny> {
kIDBValueArrayType
};
+ explicit IDBAny(Type);
+ explicit IDBAny(DOMStringList*);
+ explicit IDBAny(IDBCursor*);
+ explicit IDBAny(IDBDatabase*);
+ explicit IDBAny(std::unique_ptr<IDBKey>);
+ explicit IDBAny(Vector<std::unique_ptr<IDBValue>>);
+ explicit IDBAny(std::unique_ptr<IDBValue>);
+ explicit IDBAny(int64_t);
+ ~IDBAny();
+
+ void Trace(blink::Visitor*);
+ void ContextWillBeDestroyed();
+
Type GetType() const { return type_; }
// Use type() to figure out which one of these you're allowed to call.
DOMStringList* DomStringList() const;
@@ -103,15 +115,6 @@ class MODULES_EXPORT IDBAny : public GarbageCollectedFinalized<IDBAny> {
const IDBKey* Key() const;
private:
- explicit IDBAny(Type);
- explicit IDBAny(DOMStringList*);
- explicit IDBAny(IDBCursor*);
- explicit IDBAny(IDBDatabase*);
- explicit IDBAny(std::unique_ptr<IDBKey>);
- explicit IDBAny(Vector<std::unique_ptr<IDBValue>>);
- explicit IDBAny(std::unique_ptr<IDBValue>);
- explicit IDBAny(int64_t);
-
const Type type_;
// Only one of the following should ever be in use at any given time.
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.cc
index 0a815c75f30..07bad6af1d3 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.cc
@@ -27,7 +27,6 @@
#include <limits>
#include <memory>
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h"
#include "third_party/blink/renderer/bindings/modules/v8/to_v8_for_modules.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h"
@@ -38,6 +37,7 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_object_store.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_tracing.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_private_property.h"
@@ -48,16 +48,16 @@ using blink::WebIDBDatabase;
namespace blink {
IDBCursor* IDBCursor::Create(std::unique_ptr<WebIDBCursor> backend,
- WebIDBCursorDirection direction,
+ mojom::IDBCursorDirection direction,
IDBRequest* request,
const Source& source,
IDBTransaction* transaction) {
- return new IDBCursor(std::move(backend), direction, request, source,
- transaction);
+ return MakeGarbageCollected<IDBCursor>(std::move(backend), direction, request,
+ source, transaction);
}
IDBCursor::IDBCursor(std::unique_ptr<WebIDBCursor> backend,
- WebIDBCursorDirection direction,
+ mojom::IDBCursorDirection direction,
IDBRequest* request,
const Source& source,
IDBTransaction* transaction)
@@ -130,7 +130,7 @@ IDBRequest* IDBCursor::update(ScriptState* script_state,
}
IDBObjectStore* object_store = EffectiveObjectStore();
- return object_store->DoPut(script_state, kWebIDBPutModeCursorUpdate,
+ return object_store->DoPut(script_state, mojom::IDBPutMode::CursorUpdate,
IDBRequest::Source::FromIDBCursor(this), value,
IdbPrimaryKey(), exception_state);
}
@@ -231,8 +231,8 @@ void IDBCursor::continuePrimaryKey(ScriptState* script_state,
return;
}
- if (direction_ != kWebIDBCursorDirectionNext &&
- direction_ != kWebIDBCursorDirectionPrev) {
+ if (direction_ != mojom::IDBCursorDirection::Next &&
+ direction_ != mojom::IDBCursorDirection::Prev) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The cursor's direction is not 'next' or 'prev'.");
@@ -283,8 +283,8 @@ void IDBCursor::Continue(std::unique_ptr<IDBKey> key,
if (key) {
DCHECK(key_);
- if (direction_ == kWebIDBCursorDirectionNext ||
- direction_ == kWebIDBCursorDirectionNextNoDuplicate) {
+ if (direction_ == mojom::IDBCursorDirection::Next ||
+ direction_ == mojom::IDBCursorDirection::NextNoDuplicate) {
const bool ok = key_->IsLessThan(key.get()) ||
(primary_key && key_->IsEqual(key.get()) &&
current_primary_key->IsLessThan(primary_key.get()));
@@ -483,38 +483,38 @@ bool IDBCursor::IsDeleted() const {
return source_.GetAsIDBIndex()->IsDeleted();
}
-WebIDBCursorDirection IDBCursor::StringToDirection(
+mojom::IDBCursorDirection IDBCursor::StringToDirection(
const String& direction_string) {
- if (direction_string == IndexedDBNames::next)
- return kWebIDBCursorDirectionNext;
- if (direction_string == IndexedDBNames::nextunique)
- return kWebIDBCursorDirectionNextNoDuplicate;
- if (direction_string == IndexedDBNames::prev)
- return kWebIDBCursorDirectionPrev;
- if (direction_string == IndexedDBNames::prevunique)
- return kWebIDBCursorDirectionPrevNoDuplicate;
+ if (direction_string == indexed_db_names::kNext)
+ return mojom::IDBCursorDirection::Next;
+ if (direction_string == indexed_db_names::kNextunique)
+ return mojom::IDBCursorDirection::NextNoDuplicate;
+ if (direction_string == indexed_db_names::kPrev)
+ return mojom::IDBCursorDirection::Prev;
+ if (direction_string == indexed_db_names::kPrevunique)
+ return mojom::IDBCursorDirection::PrevNoDuplicate;
NOTREACHED();
- return kWebIDBCursorDirectionNext;
+ return mojom::IDBCursorDirection::Next;
}
const String& IDBCursor::direction() const {
switch (direction_) {
- case kWebIDBCursorDirectionNext:
- return IndexedDBNames::next;
+ case mojom::IDBCursorDirection::Next:
+ return indexed_db_names::kNext;
- case kWebIDBCursorDirectionNextNoDuplicate:
- return IndexedDBNames::nextunique;
+ case mojom::IDBCursorDirection::NextNoDuplicate:
+ return indexed_db_names::kNextunique;
- case kWebIDBCursorDirectionPrev:
- return IndexedDBNames::prev;
+ case mojom::IDBCursorDirection::Prev:
+ return indexed_db_names::kPrev;
- case kWebIDBCursorDirectionPrevNoDuplicate:
- return IndexedDBNames::prevunique;
+ case mojom::IDBCursorDirection::PrevNoDuplicate:
+ return indexed_db_names::kPrevunique;
default:
NOTREACHED();
- return IndexedDBNames::next;
+ return indexed_db_names::kNext;
}
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.h
index 64cec7cd8dc..5c3306dae41 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor.h
@@ -29,12 +29,12 @@
#include <memory>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/modules/v8/idb_object_store_or_idb_index.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/compiler.h"
@@ -51,14 +51,21 @@ class IDBCursor : public ScriptWrappable {
public:
using Source = IDBObjectStoreOrIDBIndex;
- static WebIDBCursorDirection StringToDirection(const String& mode_string);
+ static mojom::IDBCursorDirection StringToDirection(const String& mode_string);
static IDBCursor* Create(std::unique_ptr<WebIDBCursor>,
- WebIDBCursorDirection,
+ mojom::IDBCursorDirection,
IDBRequest*,
const Source&,
IDBTransaction*);
+
+ IDBCursor(std::unique_ptr<WebIDBCursor>,
+ mojom::IDBCursorDirection,
+ IDBRequest*,
+ const Source&,
+ IDBTransaction*);
~IDBCursor() override;
+
void Trace(blink::Visitor*) override;
void ContextWillBeDestroyed() { backend_.reset(); }
@@ -101,19 +108,12 @@ class IDBCursor : public ScriptWrappable {
virtual bool IsKeyCursor() const { return true; }
virtual bool IsCursorWithValue() const { return false; }
- protected:
- IDBCursor(std::unique_ptr<WebIDBCursor>,
- WebIDBCursorDirection,
- IDBRequest*,
- const Source&,
- IDBTransaction*);
-
private:
IDBObjectStore* EffectiveObjectStore() const;
std::unique_ptr<WebIDBCursor> backend_;
Member<IDBRequest> request_;
- const WebIDBCursorDirection direction_;
+ const mojom::IDBCursorDirection direction_;
Source source_;
Member<IDBTransaction> transaction_;
bool got_value_ = false;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.cc
index 9f91be73c1b..b9bad7823eb 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.cc
@@ -34,16 +34,16 @@ namespace blink {
IDBCursorWithValue* IDBCursorWithValue::Create(
std::unique_ptr<WebIDBCursor> backend,
- WebIDBCursorDirection direction,
+ mojom::IDBCursorDirection direction,
IDBRequest* request,
const Source& source,
IDBTransaction* transaction) {
- return new IDBCursorWithValue(std::move(backend), direction, request, source,
- transaction);
+ return MakeGarbageCollected<IDBCursorWithValue>(std::move(backend), direction,
+ request, source, transaction);
}
IDBCursorWithValue::IDBCursorWithValue(std::unique_ptr<WebIDBCursor> backend,
- WebIDBCursorDirection direction,
+ mojom::IDBCursorDirection direction,
IDBRequest* request,
const Source& source,
IDBTransaction* transaction)
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.h
index 91223d4d4d5..4c0deb78197 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_cursor_with_value.h
@@ -28,9 +28,9 @@
#include <memory>
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_cursor.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
namespace blink {
@@ -42,10 +42,16 @@ class IDBCursorWithValue final : public IDBCursor {
public:
static IDBCursorWithValue* Create(std::unique_ptr<WebIDBCursor>,
- WebIDBCursorDirection,
+ mojom::IDBCursorDirection,
IDBRequest*,
const Source&,
IDBTransaction*);
+
+ IDBCursorWithValue(std::unique_ptr<WebIDBCursor>,
+ mojom::IDBCursorDirection,
+ IDBRequest*,
+ const Source&,
+ IDBTransaction*);
~IDBCursorWithValue() override;
// The value attribute defined in the IDL is simply implemented in IDBCursor
@@ -54,13 +60,6 @@ class IDBCursorWithValue final : public IDBCursor {
bool IsKeyCursor() const override { return false; }
bool IsCursorWithValue() const override { return true; }
-
- private:
- IDBCursorWithValue(std::unique_ptr<WebIDBCursor>,
- WebIDBCursorDirection,
- IDBRequest*,
- const Source&,
- IDBTransaction*);
};
DEFINE_TYPE_CASTS(IDBCursorWithValue,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.cc
index db3a230190b..c8764dc38ca 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.cc
@@ -49,7 +49,6 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include <limits>
@@ -100,7 +99,8 @@ IDBDatabase* IDBDatabase::Create(ExecutionContext* context,
std::unique_ptr<WebIDBDatabase> database,
IDBDatabaseCallbacks* callbacks,
v8::Isolate* isolate) {
- return new IDBDatabase(context, std::move(database), callbacks, isolate);
+ return MakeGarbageCollected<IDBDatabase>(context, std::move(database),
+ callbacks, isolate);
}
IDBDatabase::IDBDatabase(ExecutionContext* context,
@@ -208,7 +208,7 @@ void IDBDatabase::OnChanges(
IDBTransaction* transaction = nullptr;
auto it = transactions.find(map_entry.first);
if (it != transactions.end()) {
- const std::pair<int64_t, std::vector<int64_t>>& obs_txn = it->second;
+ const std::pair<int64_t, WebVector<int64_t>>& obs_txn = it->second;
HashSet<String> stores;
for (int64_t store_id : obs_txn.second) {
stores.insert(metadata_.object_stores.at(store_id)->name);
@@ -248,7 +248,7 @@ int32_t IDBDatabase::AddObserver(
bool include_transaction,
bool no_records,
bool values,
- const std::bitset<kWebIDBOperationTypeCount>& operation_types) {
+ std::bitset<blink::kIDBOperationTypeCount> operation_types) {
int32_t observer_id = NextObserverId();
observers_.Set(observer_id, observer);
Backend()->AddObserver(transaction_id, observer_id, include_transaction,
@@ -419,9 +419,9 @@ IDBTransaction* IDBDatabase::transaction(
object_store_ids.push_back(object_store_id);
}
- WebIDBTransactionMode mode = IDBTransaction::StringToMode(mode_string);
- if (mode != kWebIDBTransactionModeReadOnly &&
- mode != kWebIDBTransactionModeReadWrite) {
+ mojom::IDBTransactionMode mode = IDBTransaction::StringToMode(mode_string);
+ if (mode != mojom::IDBTransactionMode::ReadOnly &&
+ mode != mojom::IDBTransactionMode::ReadWrite) {
exception_state.ThrowTypeError(
"The mode provided ('" + mode_string +
"') is not one of 'readonly' or 'readwrite'.");
@@ -439,7 +439,7 @@ void IDBDatabase::ForceClose() {
for (const auto& it : transactions_)
it.value->abort(IGNORE_EXCEPTION_FOR_TESTING);
this->close();
- EnqueueEvent(Event::Create(EventTypeNames::close));
+ EnqueueEvent(Event::Create(event_type_names::kClose));
}
void IDBDatabase::close() {
@@ -493,7 +493,7 @@ void IDBDatabase::OnVersionChange(int64_t old_version, int64_t new_version) {
new_version_nullable = new_version;
}
EnqueueEvent(IDBVersionChangeEvent::Create(
- EventTypeNames::versionchange, old_version, new_version_nullable));
+ event_type_names::kVersionchange, old_version, new_version_nullable));
}
void IDBDatabase::EnqueueEvent(Event* event) {
@@ -506,12 +506,12 @@ DispatchEventResult IDBDatabase::DispatchEventInternal(Event& event) {
IDB_TRACE("IDBDatabase::dispatchEvent");
if (!GetExecutionContext())
return DispatchEventResult::kCanceledBeforeDispatch;
- DCHECK(event.type() == EventTypeNames::versionchange ||
- event.type() == EventTypeNames::close);
+ DCHECK(event.type() == event_type_names::kVersionchange ||
+ event.type() == event_type_names::kClose);
DispatchEventResult dispatch_result =
EventTarget::DispatchEventInternal(event);
- if (event.type() == EventTypeNames::versionchange && !close_pending_ &&
+ if (event.type() == event_type_names::kVersionchange && !close_pending_ &&
backend_)
backend_->VersionChangeIgnored();
return dispatch_result;
@@ -590,7 +590,7 @@ void IDBDatabase::ContextDestroyed(ExecutionContext*) {
}
const AtomicString& IDBDatabase::InterfaceName() const {
- return EventTargetNames::IDBDatabase;
+ return event_target_names::kIDBDatabase;
}
ExecutionContext* IDBDatabase::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.h
index 90c1175dff3..1e2f20782d1 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database.h
@@ -29,7 +29,6 @@
#include <memory>
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_string_sequence.h"
@@ -43,6 +42,7 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_object_store_parameters.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
@@ -68,7 +68,13 @@ class MODULES_EXPORT IDBDatabase final
std::unique_ptr<WebIDBDatabase>,
IDBDatabaseCallbacks*,
v8::Isolate*);
+
+ IDBDatabase(ExecutionContext*,
+ std::unique_ptr<WebIDBDatabase>,
+ IDBDatabaseCallbacks*,
+ v8::Isolate*);
~IDBDatabase() override;
+
void Trace(blink::Visitor*) override;
// Overwrites the database metadata, including object store and index
@@ -81,13 +87,12 @@ class MODULES_EXPORT IDBDatabase final
void TransactionCreated(IDBTransaction*);
void TransactionFinished(const IDBTransaction*);
const String& GetObjectStoreName(int64_t object_store_id) const;
- int32_t AddObserver(
- IDBObserver*,
- int64_t transaction_id,
- bool include_transaction,
- bool no_records,
- bool values,
- const std::bitset<kWebIDBOperationTypeCount>& operation_types);
+ int32_t AddObserver(IDBObserver*,
+ int64_t transaction_id,
+ bool include_transaction,
+ bool no_records,
+ bool values,
+ std::bitset<kIDBOperationTypeCount> operation_types);
void RemoveObservers(const Vector<int32_t>& observer_ids);
// Implement the IDL
@@ -96,10 +101,10 @@ class MODULES_EXPORT IDBDatabase final
DOMStringList* objectStoreNames() const;
IDBObjectStore* createObjectStore(const String& name,
- const IDBObjectStoreParameters& options,
+ const IDBObjectStoreParameters* options,
ExceptionState& exception_state) {
- return createObjectStore(name, IDBKeyPath(options.keyPath()),
- options.autoIncrement(), exception_state);
+ return createObjectStore(name, IDBKeyPath(options->keyPath()),
+ options->autoIncrement(), exception_state);
}
IDBTransaction* transaction(ScriptState*,
const StringOrStringSequence& store_names,
@@ -108,10 +113,10 @@ class MODULES_EXPORT IDBDatabase final
void deleteObjectStore(const String& name, ExceptionState&);
void close();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(versionchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(versionchange, kVersionchange);
// IDBDatabaseCallbacks
void OnVersionChange(int64_t old_version, int64_t new_version);
@@ -175,11 +180,6 @@ class MODULES_EXPORT IDBDatabase final
DispatchEventResult DispatchEventInternal(Event&) override;
private:
- IDBDatabase(ExecutionContext*,
- std::unique_ptr<WebIDBDatabase>,
- IDBDatabaseCallbacks*,
- v8::Isolate*);
-
IDBObjectStore* createObjectStore(const String& name,
const IDBKeyPath&,
bool auto_increment,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.cc
index f607a9164a1..7fa1f036ed7 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.cc
@@ -33,7 +33,7 @@
namespace blink {
IDBDatabaseCallbacks* IDBDatabaseCallbacks::Create() {
- return new IDBDatabaseCallbacks();
+ return MakeGarbageCollected<IDBDatabaseCallbacks>();
}
IDBDatabaseCallbacks::IDBDatabaseCallbacks() : database_(nullptr) {}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.h
index d9d363284f2..2a4a0c30890 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.h
@@ -43,6 +43,8 @@ class MODULES_EXPORT IDBDatabaseCallbacks
: public GarbageCollectedFinalized<IDBDatabaseCallbacks> {
public:
static IDBDatabaseCallbacks* Create();
+
+ IDBDatabaseCallbacks();
virtual ~IDBDatabaseCallbacks();
void Trace(blink::Visitor*);
@@ -65,10 +67,6 @@ class MODULES_EXPORT IDBDatabaseCallbacks
void DetachWebCallbacks();
void WebCallbacksDestroyed();
- protected:
- // Exposed to subclasses for unit tests.
- IDBDatabaseCallbacks();
-
private:
// The initial IDBOpenDBRequest, final IDBDatabase, and/or
// WebIDBDatabaseCallbacks have strong references to an IDBDatabaseCallbacks
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_info.idl b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_info.idl
new file mode 100644
index 00000000000..81b3c0fb09f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_database_info.idl
@@ -0,0 +1,10 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Spec pull-request for addition:
+// https://github.com/w3c/IndexedDB/pull/240/commits
+dictionary IDBDatabaseInfo {
+ DOMString name;
+ unsigned long long version;
+};
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.cc
index 3f70fecdb98..45b8196e6fc 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.cc
@@ -29,32 +29,158 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_factory.h"
#include <memory>
+#include <utility>
+
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+#include "third_party/blink/public/platform/interface_provider.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_factory.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_name_and_version.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/modules/indexed_db_names.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_database.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_database_callbacks.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_database_info.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_tracing.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db_client.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_factory.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
+namespace {
+
+class WebIDBGetDBNamesCallbacksImpl : public WebIDBCallbacks {
+ public:
+ // static
+ static std::unique_ptr<WebIDBGetDBNamesCallbacksImpl> Create(
+ ScriptPromiseResolver* promise_resolver) {
+ return base::WrapUnique(
+ new WebIDBGetDBNamesCallbacksImpl(promise_resolver));
+ }
+
+ WebIDBGetDBNamesCallbacksImpl(ScriptPromiseResolver* promise_resolver)
+ : promise_resolver_(promise_resolver) {
+ probe::AsyncTaskScheduled(
+ ExecutionContext::From(promise_resolver_->GetScriptState()),
+ indexed_db_names::kIndexedDB, this);
+ }
+
+ ~WebIDBGetDBNamesCallbacksImpl() override {
+ if (promise_resolver_) {
+ probe::AsyncTaskCanceled(
+ ExecutionContext::From(promise_resolver_->GetScriptState()), this);
+ promise_resolver_->Reject(
+ DOMException::Create(DOMExceptionCode::kUnknownError,
+ "An unexpected shutdown occured before the "
+ "databases() promise could be resolved"));
+ }
+ }
+
+ void OnError(const WebIDBDatabaseError& error) override {
+ if (!promise_resolver_)
+ return;
+
+ probe::AsyncTask async_task(
+ ExecutionContext::From(promise_resolver_->GetScriptState()), this,
+ "error");
+ promise_resolver_->Reject(
+ DOMException::Create(DOMExceptionCode::kUnknownError,
+ "The databases() promise was rejected."));
+ promise_resolver_.Clear();
+ }
+
+ void OnSuccess(const WebVector<WebIDBNameAndVersion>&
+ web_database_name_and_version_list) override {
+ if (!promise_resolver_)
+ return;
+
+ HeapVector<Member<IDBDatabaseInfo>> database_name_and_version_list;
+ for (size_t i = 0; i < web_database_name_and_version_list.size(); ++i) {
+ IDBDatabaseInfo* idb_info = IDBDatabaseInfo::Create();
+ idb_info->setName(web_database_name_and_version_list[i].name);
+ idb_info->setVersion(web_database_name_and_version_list[i].version);
+ database_name_and_version_list.push_back(idb_info);
+ }
+ probe::AsyncTask async_task(
+ ExecutionContext::From(promise_resolver_->GetScriptState()), this,
+ "success");
+ promise_resolver_->Resolve(database_name_and_version_list);
+ promise_resolver_.Clear();
+ }
+
+ void OnSuccess(const WebVector<WebString>&) override { NOTREACHED(); }
+
+ void OnSuccess(WebIDBCursor* cursor,
+ WebIDBKey key,
+ WebIDBKey primary_key,
+ WebIDBValue value) override {
+ NOTREACHED();
+ }
+
+ void OnSuccess(WebIDBDatabase* backend,
+ const WebIDBMetadata& metadata) override {
+ NOTREACHED();
+ }
+
+ void OnSuccess(WebIDBKey key) override { NOTREACHED(); }
+
+ void OnSuccess(WebIDBValue value) override { NOTREACHED(); }
+
+ void OnSuccess(WebVector<WebIDBValue> values) override { NOTREACHED(); }
+
+ void OnSuccess(long long value) override { NOTREACHED(); }
+
+ void OnSuccess() override { NOTREACHED(); }
+
+ void OnSuccess(WebIDBKey key,
+ WebIDBKey primary_key,
+ WebIDBValue value) override {
+ NOTREACHED();
+ }
+
+ void OnBlocked(long long old_version) override { NOTREACHED(); }
+
+ void OnUpgradeNeeded(long long old_version,
+ WebIDBDatabase* database,
+ const WebIDBMetadata& metadata,
+ mojom::IDBDataLoss data_loss,
+ WebString data_loss_message) override {
+ NOTREACHED();
+ }
+
+ void Detach() override { NOTREACHED(); }
+
+ private:
+ Persistent<ScriptPromiseResolver> promise_resolver_;
+};
+
+} // namespace
+
static const char kPermissionDeniedErrorMessage[] =
"The user denied permission to access the database.";
IDBFactory::IDBFactory() = default;
+IDBFactory::IDBFactory(std::unique_ptr<WebIDBFactory> web_idb_factory)
+ : web_idb_factory_(std::move(web_idb_factory)) {}
+
static bool IsContextValid(ExecutionContext* context) {
DCHECK(IsA<Document>(context) || context->IsWorkerGlobalScope());
if (auto* document = DynamicTo<Document>(context))
@@ -63,11 +189,39 @@ static bool IsContextValid(ExecutionContext* context) {
}
WebIDBFactory* IDBFactory::GetFactory() {
- if (!web_idb_factory_)
- web_idb_factory_ = Platform::Current()->CreateIdbFactory();
+ if (!web_idb_factory_) {
+ mojom::blink::IDBFactoryPtrInfo web_idb_factory_host_info;
+ Platform::Current()->GetInterfaceProvider()->GetInterface(
+ mojo::MakeRequest(&web_idb_factory_host_info));
+ web_idb_factory_ = std::make_unique<WebIDBFactoryImpl>(
+ std::move(web_idb_factory_host_info));
+ }
return web_idb_factory_.get();
}
+ScriptPromise IDBFactory::GetDatabaseInfo(ScriptState* script_state,
+ ExceptionState& exception_state) {
+ ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
+
+ if (!ExecutionContext::From(script_state)
+ ->GetSecurityOrigin()
+ ->CanAccessDatabase()) {
+ exception_state.ThrowSecurityError(
+ "Access to the IndexedDB API is denied in this context.");
+ resolver->Reject();
+ return resolver->Promise();
+ }
+
+ GetFactory()->GetDatabaseInfo(
+ WebIDBGetDBNamesCallbacksImpl::Create(resolver).release(),
+ WebSecurityOrigin(
+ ExecutionContext::From(script_state)->GetSecurityOrigin()),
+ ExecutionContext::From(script_state)
+ ->GetTaskRunner(TaskType::kInternalIndexedDB));
+ ScriptPromise promise = resolver->Promise();
+ return promise;
+}
+
IDBRequest* IDBFactory::GetDatabaseNames(ScriptState* script_state,
ExceptionState& exception_state) {
IDB_TRACE("IDBFactory::getDatabaseNamesRequestSetup");
@@ -91,8 +245,7 @@ IDBRequest* IDBFactory::GetDatabaseNames(ScriptState* script_state,
}
if (!IndexedDBClient::From(ExecutionContext::From(script_state))
- ->AllowIndexedDB(ExecutionContext::From(script_state),
- "Database Listing")) {
+ ->AllowIndexedDB(ExecutionContext::From(script_state))) {
request->HandleResponse(DOMException::Create(
DOMExceptionCode::kUnknownError, kPermissionDeniedErrorMessage));
return request;
@@ -147,7 +300,7 @@ IDBOpenDBRequest* IDBFactory::OpenInternal(ScriptState* script_state,
version, std::move(metrics));
if (!IndexedDBClient::From(ExecutionContext::From(script_state))
- ->AllowIndexedDB(ExecutionContext::From(script_state), name)) {
+ ->AllowIndexedDB(ExecutionContext::From(script_state))) {
request->HandleResponse(DOMException::Create(
DOMExceptionCode::kUnknownError, kPermissionDeniedErrorMessage));
return request;
@@ -213,7 +366,7 @@ IDBOpenDBRequest* IDBFactory::DeleteDatabaseInternal(
std::move(metrics));
if (!IndexedDBClient::From(ExecutionContext::From(script_state))
- ->AllowIndexedDB(ExecutionContext::From(script_state), name)) {
+ ->AllowIndexedDB(ExecutionContext::From(script_state))) {
request->HandleResponse(DOMException::Create(
DOMExceptionCode::kUnknownError, kPermissionDeniedErrorMessage));
return request;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.h
index bc541748cff..68b8234455c 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.h
@@ -25,11 +25,14 @@
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_FACTORY_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_FACTORY_H_
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_factory.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_factory.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -39,11 +42,18 @@ namespace blink {
class ExceptionState;
class ScriptState;
-class IDBFactory final : public ScriptWrappable {
+class MODULES_EXPORT IDBFactory final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static IDBFactory* Create() { return new IDBFactory(); }
+ static IDBFactory* Create() { return MakeGarbageCollected<IDBFactory>(); }
+ static IDBFactory* CreateForTest(
+ std::unique_ptr<WebIDBFactory> web_idb_factory) {
+ return MakeGarbageCollected<IDBFactory>(std::move(web_idb_factory));
+ }
+
+ IDBFactory();
+ IDBFactory(std::unique_ptr<WebIDBFactory>);
// Implement the IDBFactory IDL
IDBOpenDBRequest* open(ScriptState*, const String& name, ExceptionState&);
@@ -65,9 +75,9 @@ class IDBFactory final : public ScriptWrappable {
const String& name,
ExceptionState&);
- private:
- IDBFactory();
+ ScriptPromise GetDatabaseInfo(ScriptState*, ExceptionState&);
+ private:
WebIDBFactory* GetFactory();
IDBOpenDBRequest* OpenInternal(ScriptState*,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.idl b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.idl
index 57cc48a7c61..291900fde26 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.idl
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory.idl
@@ -29,13 +29,18 @@
Exposed=(Window,Worker)
] interface IDBFactory {
[
- NewObject,
- CallWith=ScriptState,
- Measure,
- RaisesException
+ NewObject,
+ CallWith=ScriptState,
+ Measure,
+ RaisesException
] IDBOpenDBRequest open(DOMString name,
optional [EnforceRange] unsigned long long version);
[NewObject, CallWith=ScriptState, RaisesException] IDBOpenDBRequest deleteDatabase(DOMString name);
-
[CallWith=ScriptState, RaisesException] short cmp(any first, any second);
+ [
+ CallWith=ScriptState,
+ ImplementedAs=GetDatabaseInfo,
+ RaisesException
+ ] Promise<sequence<IDBDatabaseInfo>> databases();
};
+
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory_test.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory_test.cc
new file mode 100644
index 00000000000..7cdb287cb84
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_factory_test.cc
@@ -0,0 +1,132 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/indexeddb/idb_factory.h"
+
+#include <memory>
+
+#include "base/memory/ptr_util.h"
+#include "base/memory/scoped_refptr.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_name_and_version.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
+#include "third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+
+namespace blink {
+namespace {
+
+class TestHelperFunction : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
+ bool* called_flag) {
+ auto* self = new TestHelperFunction(script_state, called_flag);
+ return self->BindToV8Function();
+ }
+
+ private:
+ TestHelperFunction(ScriptState* script_state, bool* called_flag)
+ : ScriptFunction(script_state), called_flag_(called_flag) {}
+
+ ScriptValue Call(ScriptValue value) override {
+ *called_flag_ = true;
+ return value;
+ }
+
+ bool* called_flag_;
+};
+
+class IDBFactoryTest : public testing::Test {
+ protected:
+ IDBFactoryTest() {}
+
+ ~IDBFactoryTest() override {}
+};
+
+ACTION_TEMPLATE(SaveUniquePointer,
+ HAS_1_TEMPLATE_PARAMS(int, k),
+ AND_1_VALUE_PARAMS(unique_pointer)) {
+ *unique_pointer = base::WrapUnique(std::get<k>(args));
+}
+
+TEST_F(IDBFactoryTest, WebIDBGetDBInfoCallbacksResolvesPromise) {
+ V8TestingScope scope;
+ scope.GetDocument().SetSecurityOrigin(
+ SecurityOrigin::Create(KURL("https://example.com")));
+ std::unique_ptr<MockWebIDBFactory> web_factory = MockWebIDBFactory::Create();
+ std::unique_ptr<WebIDBCallbacks> wc;
+ EXPECT_CALL(*web_factory, GetDatabaseInfo(testing::_, testing::_, testing::_))
+ .Times(1)
+ .WillOnce(SaveUniquePointer<0>(&wc));
+ IDBFactory* factory = IDBFactory::CreateForTest(std::move(web_factory));
+
+ DummyExceptionStateForTesting exception_state;
+ ScriptPromise promise =
+ factory->GetDatabaseInfo(scope.GetScriptState(), exception_state);
+ bool on_fulfilled = false;
+ bool on_rejected = false;
+ promise.Then(
+ TestHelperFunction::CreateFunction(scope.GetScriptState(), &on_fulfilled),
+ TestHelperFunction::CreateFunction(scope.GetScriptState(), &on_rejected));
+
+ EXPECT_FALSE(on_fulfilled);
+ EXPECT_FALSE(on_rejected);
+
+ const WebVector<WebIDBNameAndVersion> wv;
+ wc->OnSuccess(wv);
+
+ EXPECT_FALSE(on_fulfilled);
+ EXPECT_FALSE(on_rejected);
+
+ v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
+
+ EXPECT_TRUE(on_fulfilled);
+ EXPECT_FALSE(on_rejected);
+}
+
+TEST_F(IDBFactoryTest, WebIDBGetDBNamesCallbacksRejectsPromise) {
+ V8TestingScope scope;
+ scope.GetDocument().SetSecurityOrigin(
+ SecurityOrigin::Create(KURL("https://example.com")));
+ std::unique_ptr<MockWebIDBFactory> web_factory = MockWebIDBFactory::Create();
+ std::unique_ptr<WebIDBCallbacks> wc;
+ EXPECT_CALL(*web_factory, GetDatabaseInfo(testing::_, testing::_, testing::_))
+ .Times(1)
+ .WillOnce(SaveUniquePointer<0>(&wc));
+ IDBFactory* factory = IDBFactory::CreateForTest(std::move(web_factory));
+
+ DummyExceptionStateForTesting exception_state;
+ ScriptPromise promise =
+ factory->GetDatabaseInfo(scope.GetScriptState(), exception_state);
+ bool on_fulfilled = false;
+ bool on_rejected = false;
+ promise.Then(
+ TestHelperFunction::CreateFunction(scope.GetScriptState(), &on_fulfilled),
+ TestHelperFunction::CreateFunction(scope.GetScriptState(), &on_rejected));
+
+ EXPECT_FALSE(on_fulfilled);
+ EXPECT_FALSE(on_rejected);
+
+ const WebVector<WebIDBNameAndVersion> wv;
+ wc->OnError(WebIDBDatabaseError(1));
+
+ EXPECT_FALSE(on_fulfilled);
+ EXPECT_FALSE(on_rejected);
+
+ v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
+
+ EXPECT_FALSE(on_fulfilled);
+ EXPECT_TRUE(on_rejected);
+}
+
+} // namespace
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.cc
index c8dd61b5f31..06564cbfadc 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.cc
@@ -131,7 +131,7 @@ IDBRequest* IDBIndex::openCursor(ScriptState* script_state,
transaction_->InactiveErrorMessage());
return nullptr;
}
- WebIDBCursorDirection direction =
+ mojom::IDBCursorDirection direction =
IDBCursor::StringToDirection(direction_string);
IDBKeyRange* key_range = IDBKeyRange::FromScriptValue(
ExecutionContext::From(script_state), range, exception_state);
@@ -149,13 +149,14 @@ IDBRequest* IDBIndex::openCursor(ScriptState* script_state,
IDBRequest* IDBIndex::openCursor(ScriptState* script_state,
IDBKeyRange* key_range,
- WebIDBCursorDirection direction,
+ mojom::IDBCursorDirection direction,
IDBRequest::AsyncTraceState metrics) {
IDBRequest* request = IDBRequest::Create(
script_state, this, transaction_.Get(), std::move(metrics));
- request->SetCursorDetails(IndexedDB::kCursorKeyAndValue, direction);
+ request->SetCursorDetails(indexed_db::kCursorKeyAndValue, direction);
BackendDB()->OpenCursor(transaction_->Id(), object_store_->Id(), Id(),
- key_range, direction, false, kWebIDBTaskTypeNormal,
+ key_range, direction, false,
+ mojom::IDBTaskType::Normal,
request->CreateWebCallbacks().release());
return request;
}
@@ -214,7 +215,7 @@ IDBRequest* IDBIndex::openKeyCursor(ScriptState* script_state,
transaction_->InactiveErrorMessage());
return nullptr;
}
- WebIDBCursorDirection direction =
+ mojom::IDBCursorDirection direction =
IDBCursor::StringToDirection(direction_string);
IDBKeyRange* key_range = IDBKeyRange::FromScriptValue(
ExecutionContext::From(script_state), range, exception_state);
@@ -228,10 +229,10 @@ IDBRequest* IDBIndex::openKeyCursor(ScriptState* script_state,
IDBRequest* request = IDBRequest::Create(
script_state, this, transaction_.Get(), std::move(metrics));
- request->SetCursorDetails(IndexedDB::kCursorKeyOnly, direction);
- BackendDB()->OpenCursor(transaction_->Id(), object_store_->Id(), Id(),
- key_range, direction, true, kWebIDBTaskTypeNormal,
- request->CreateWebCallbacks().release());
+ request->SetCursorDetails(indexed_db::kCursorKeyOnly, direction);
+ BackendDB()->OpenCursor(
+ transaction_->Id(), object_store_->Id(), Id(), key_range, direction, true,
+ mojom::IDBTaskType::Normal, request->CreateWebCallbacks().release());
return request;
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.h
index 99a48241580..20e69c4877a 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_index.h
@@ -27,13 +27,14 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_INDEX_H_
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_cursor.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key_path.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_metadata.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -50,9 +51,13 @@ class IDBIndex final : public ScriptWrappable {
static IDBIndex* Create(scoped_refptr<IDBIndexMetadata> metadata,
IDBObjectStore* object_store,
IDBTransaction* transaction) {
- return new IDBIndex(std::move(metadata), object_store, transaction);
+ return MakeGarbageCollected<IDBIndex>(std::move(metadata), object_store,
+ transaction);
}
+
+ IDBIndex(scoped_refptr<IDBIndexMetadata>, IDBObjectStore*, IDBTransaction*);
~IDBIndex() override;
+
void Trace(blink::Visitor*) override;
// Implement the IDL
@@ -113,14 +118,12 @@ class IDBIndex final : public ScriptWrappable {
IDBRequest* openCursor(
ScriptState*,
IDBKeyRange*,
- WebIDBCursorDirection,
+ mojom::IDBCursorDirection,
IDBRequest::AsyncTraceState = IDBRequest::AsyncTraceState());
WebIDBDatabase* BackendDB() const;
private:
- IDBIndex(scoped_refptr<IDBIndexMetadata>, IDBObjectStore*, IDBTransaction*);
-
const IDBIndexMetadata& Metadata() const { return *metadata_; }
IDBRequest* GetInternal(ScriptState*,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.cc
index 8ed421c8c74..d061b3e3fed 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.cc
@@ -34,6 +34,40 @@
namespace blink {
+namespace {
+
+size_t CalculateIDBKeyArraySize(const IDBKey::KeyArray& keys) {
+ size_t size(0);
+ for (const auto& key : keys)
+ size += key.get()->SizeEstimate();
+ return size;
+}
+
+} // namespace
+
+IDBKey::IDBKey() : type_(kInvalidType), size_estimate_(kIDBKeyOverheadSize) {}
+
+IDBKey::IDBKey(Type type, double number)
+ : type_(type),
+ number_(number),
+ size_estimate_(kIDBKeyOverheadSize + sizeof(number_)) {}
+
+IDBKey::IDBKey(const String& value)
+ : type_(kStringType),
+ string_(value),
+ size_estimate_(kIDBKeyOverheadSize + (string_.length() * sizeof(UChar))) {
+}
+
+IDBKey::IDBKey(scoped_refptr<SharedBuffer> value)
+ : type_(kBinaryType),
+ binary_(std::move(value)),
+ size_estimate_(kIDBKeyOverheadSize + binary_.get()->size()) {}
+
+IDBKey::IDBKey(KeyArray key_array)
+ : type_(kArrayType),
+ array_(std::move(key_array)),
+ size_estimate_(kIDBKeyOverheadSize + CalculateIDBKeyArraySize(array_)) {}
+
IDBKey::~IDBKey() = default;
bool IDBKey::IsValid() const {
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.h
index 3082acad539..9c8e9addf5d 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key.h
@@ -78,8 +78,50 @@ class MODULES_EXPORT IDBKey {
return base::WrapUnique(new IDBKey(std::move(array)));
}
+ // TODO(cmp): This |Clone| function is necessary for WebIDBKey's ctor
+ // functions. It needs to be available in this header file so
+ // web_idb_key.cc can use it. When the IDB Blink variant typemap
+ // moves to the renderer/modules/indexeddb/ types and off of the
+ // WebIDB* types, this |Clone| function should be removed.
+ static std::unique_ptr<IDBKey> Clone(const std::unique_ptr<IDBKey>& rkey_in) {
+ IDBKey* rkey = rkey_in.get();
+ if (!rkey_in.get())
+ return nullptr;
+
+ switch (rkey->GetType()) {
+ case kInvalidType:
+ return IDBKey::CreateInvalid();
+ case kArrayType: {
+ IDBKey::KeyArray lkey_array;
+ const auto& rkey_array = rkey->Array();
+ for (const auto& rkey_item : rkey_array)
+ lkey_array.push_back(IDBKey::Clone(rkey_item));
+ return IDBKey::CreateArray(std::move(lkey_array));
+ }
+ case kBinaryType:
+ return IDBKey::CreateBinary(rkey->Binary());
+ case kStringType:
+ return IDBKey::CreateString(rkey->GetString());
+ case kDateType:
+ return IDBKey::CreateDate(rkey->Date());
+ case kNumberType:
+ return IDBKey::CreateNumber(rkey->Number());
+
+ case kTypeEnumMax:
+ break; // Not used, NOTREACHED.
+ }
+ NOTREACHED();
+ return nullptr;
+ }
+
~IDBKey();
+ // Very rough estimate of minimum key size overhead.
+ //
+ // TODO(cmp): When the reference to this in web_idb_key.cc goes away, move
+ // this variable back to idb_key.cc's anonymous namespace.
+ static const size_t kIDBKeyOverheadSize = 16;
+
// In order of the least to the highest precedent in terms of sort order.
// These values are written to logs. New enum values can be added, but
// existing enums must never be renumbered or deleted and reused.
@@ -124,6 +166,7 @@ class MODULES_EXPORT IDBKey {
int Compare(const IDBKey* other) const;
bool IsLessThan(const IDBKey* other) const;
bool IsEqual(const IDBKey* other) const;
+ size_t SizeEstimate() const { return size_estimate_; }
// Returns a new key array with invalid keys and duplicates removed.
//
@@ -140,20 +183,22 @@ class MODULES_EXPORT IDBKey {
private:
DISALLOW_COPY_AND_ASSIGN(IDBKey);
- IDBKey() : type_(kInvalidType) {}
- IDBKey(Type type, double number) : type_(type), number_(number) {}
- explicit IDBKey(const class String& value)
- : type_(kStringType), string_(value) {}
- explicit IDBKey(scoped_refptr<SharedBuffer> value)
- : type_(kBinaryType), binary_(std::move(value)) {}
- explicit IDBKey(KeyArray key_array)
- : type_(kArrayType), array_(std::move(key_array)) {}
+ IDBKey();
+ IDBKey(Type type, double number);
+ explicit IDBKey(const String& value);
+ explicit IDBKey(scoped_refptr<SharedBuffer> value);
+ explicit IDBKey(KeyArray key_array);
Type type_;
KeyArray array_;
scoped_refptr<SharedBuffer> binary_;
- const class String string_;
+ const String string_;
const double number_ = 0;
+
+ // Initialized in IDBKey constructors based on key type and value size (see
+ // idb_key.cc). Returned via SizeEstimate() and used in IndexedDB code to
+ // verify that a given key is small enough to pass over IPC.
+ size_t size_estimate_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_path.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_path.cc
index af493f274a8..ca3f5c67ced 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_path.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_path.cc
@@ -38,22 +38,22 @@ namespace {
// The following correspond to grammar in ECMA-262.
const uint32_t kUnicodeLetter =
- WTF::Unicode::kLetter_Uppercase | WTF::Unicode::kLetter_Lowercase |
- WTF::Unicode::kLetter_Titlecase | WTF::Unicode::kLetter_Modifier |
- WTF::Unicode::kLetter_Other | WTF::Unicode::kNumber_Letter;
+ WTF::unicode::kLetter_Uppercase | WTF::unicode::kLetter_Lowercase |
+ WTF::unicode::kLetter_Titlecase | WTF::unicode::kLetter_Modifier |
+ WTF::unicode::kLetter_Other | WTF::unicode::kNumber_Letter;
const uint32_t kUnicodeCombiningMark =
- WTF::Unicode::kMark_NonSpacing | WTF::Unicode::kMark_SpacingCombining;
-const uint32_t kUnicodeDigit = WTF::Unicode::kNumber_DecimalDigit;
+ WTF::unicode::kMark_NonSpacing | WTF::unicode::kMark_SpacingCombining;
+const uint32_t kUnicodeDigit = WTF::unicode::kNumber_DecimalDigit;
const uint32_t kUnicodeConnectorPunctuation =
- WTF::Unicode::kPunctuation_Connector;
+ WTF::unicode::kPunctuation_Connector;
static inline bool IsIdentifierStartCharacter(UChar c) {
- return (WTF::Unicode::Category(c) & kUnicodeLetter) || (c == '$') ||
+ return (WTF::unicode::Category(c) & kUnicodeLetter) || (c == '$') ||
(c == '_');
}
static inline bool IsIdentifierCharacter(UChar c) {
- return (WTF::Unicode::Category(c) &
+ return (WTF::unicode::Category(c) &
(kUnicodeLetter | kUnicodeCombiningMark | kUnicodeDigit |
kUnicodeConnectorPunctuation)) ||
(c == '$') || (c == '_') || (c == kZeroWidthNonJoinerCharacter) ||
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc
index 3554ee367e4..193c0cfaf43 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc
@@ -56,8 +56,9 @@ IDBKeyRange* IDBKeyRange::FromScriptValue(ExecutionContext* context,
}
IDBKey* const upper_compressed = key.get();
- return new IDBKeyRange(std::move(key), upper_compressed, nullptr,
- kLowerBoundClosed, kUpperBoundClosed);
+ return MakeGarbageCollected<IDBKeyRange>(std::move(key), upper_compressed,
+ nullptr, kLowerBoundClosed,
+ kUpperBoundClosed);
}
IDBKeyRange::IDBKeyRange(std::unique_ptr<IDBKey> lower,
@@ -95,8 +96,9 @@ IDBKeyRange* IDBKeyRange::only(std::unique_ptr<IDBKey> key,
}
IDBKey* const upper_compressed = key.get();
- return new IDBKeyRange(std::move(key), upper_compressed, nullptr,
- kLowerBoundClosed, kUpperBoundClosed);
+ return MakeGarbageCollected<IDBKeyRange>(std::move(key), upper_compressed,
+ nullptr, kLowerBoundClosed,
+ kUpperBoundClosed);
}
IDBKeyRange* IDBKeyRange::only(ScriptState* script_state,
@@ -114,8 +116,9 @@ IDBKeyRange* IDBKeyRange::only(ScriptState* script_state,
}
IDBKey* const upper_compressed = key.get();
- return new IDBKeyRange(std::move(key), upper_compressed, nullptr,
- kLowerBoundClosed, kUpperBoundClosed);
+ return MakeGarbageCollected<IDBKeyRange>(std::move(key), upper_compressed,
+ nullptr, kLowerBoundClosed,
+ kUpperBoundClosed);
}
IDBKeyRange* IDBKeyRange::lowerBound(ScriptState* script_state,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.h
index e259981ce13..fb8132b90d7 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_key_range.h
@@ -49,10 +49,17 @@ class MODULES_EXPORT IDBKeyRange final : public ScriptWrappable {
LowerBoundType lower_type,
UpperBoundType upper_type) {
IDBKey* upper_compressed = upper.get();
- return new IDBKeyRange(std::move(lower), upper_compressed, std::move(upper),
- lower_type, upper_type);
+ return MakeGarbageCollected<IDBKeyRange>(std::move(lower), upper_compressed,
+ std::move(upper), lower_type,
+ upper_type);
}
+ IDBKeyRange(std::unique_ptr<IDBKey> lower,
+ IDBKey* upper,
+ std::unique_ptr<IDBKey> upper_if_distinct,
+ LowerBoundType lower_type,
+ UpperBoundType upper_type);
+
// Null if the script value is null or undefined, the range if it is one,
// otherwise tries to convert to a key and throws if it fails.
static IDBKeyRange* FromScriptValue(ExecutionContext*,
@@ -116,12 +123,6 @@ class MODULES_EXPORT IDBKeyRange final : public ScriptWrappable {
// are not considered compressed, as the left key is different from the right
// key.
- IDBKeyRange(std::unique_ptr<IDBKey> lower,
- IDBKey* upper,
- std::unique_ptr<IDBKey> upper_if_distinct,
- LowerBoundType lower_type,
- UpperBoundType upper_type);
-
// Owns the range's lower key, and possibly the upper key.
std::unique_ptr<IDBKey> lower_;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.cc
index 722fa6d674f..7f2f23dc118 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.cc
@@ -30,7 +30,6 @@
#include "base/feature_list.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/safe_conversions.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h"
#include "third_party/blink/public/platform/web_blob_info.h"
@@ -49,6 +48,7 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_key_path.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_tracing.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/histogram.h"
@@ -348,7 +348,7 @@ IDBRequest* IDBObjectStore::add(ScriptState* script_state,
ExceptionState& exception_state) {
IDB_TRACE1("IDBObjectStore::addRequestSetup", "store_name",
metadata_->name.Utf8());
- return DoPut(script_state, kWebIDBPutModeAddOnly, value, key,
+ return DoPut(script_state, mojom::IDBPutMode::AddOnly, value, key,
exception_state);
}
@@ -358,12 +358,12 @@ IDBRequest* IDBObjectStore::put(ScriptState* script_state,
ExceptionState& exception_state) {
IDB_TRACE1("IDBObjectStore::putRequestSetup", "store_name",
metadata_->name.Utf8());
- return DoPut(script_state, kWebIDBPutModeAddOrUpdate, value, key,
+ return DoPut(script_state, mojom::IDBPutMode::AddOrUpdate, value, key,
exception_state);
}
IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
- WebIDBPutMode put_mode,
+ mojom::IDBPutMode put_mode,
const ScriptValue& value,
const ScriptValue& key_value,
ExceptionState& exception_state) {
@@ -380,20 +380,20 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
}
IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
- WebIDBPutMode put_mode,
+ mojom::IDBPutMode put_mode,
const IDBRequest::Source& source,
const ScriptValue& value,
const IDBKey* key,
ExceptionState& exception_state) {
const char* tracing_name = nullptr;
switch (put_mode) {
- case kWebIDBPutModeAddOrUpdate:
+ case mojom::IDBPutMode::AddOrUpdate:
tracing_name = "IDBObjectStore::put";
break;
- case kWebIDBPutModeAddOnly:
+ case mojom::IDBPutMode::AddOnly:
tracing_name = "IDBObjectStore::add";
break;
- case kWebIDBPutModeCursorUpdate:
+ case mojom::IDBPutMode::CursorUpdate:
tracing_name = "IDBCursor::update";
break;
}
@@ -438,7 +438,7 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
const bool uses_in_line_keys = !key_path.IsNull();
const bool has_key_generator = autoIncrement();
- if (put_mode != kWebIDBPutModeCursorUpdate && uses_in_line_keys && key) {
+ if (put_mode != mojom::IDBPutMode::CursorUpdate && uses_in_line_keys && key) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The object store uses in-line keys and "
"the key parameter was provided.");
@@ -451,7 +451,7 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
// This test logically belongs in IDBCursor, but must operate on the cloned
// value.
- if (put_mode == kWebIDBPutModeCursorUpdate && uses_in_line_keys) {
+ if (put_mode == mojom::IDBPutMode::CursorUpdate && uses_in_line_keys) {
DCHECK(key);
DCHECK(clone.IsEmpty());
value_wrapper.Clone(script_state, &clone);
@@ -482,7 +482,7 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
if (uses_in_line_keys) {
if (clone.IsEmpty()) {
// For an IDBCursor.update(), the value should have been cloned above.
- DCHECK(put_mode != kWebIDBPutModeCursorUpdate);
+ DCHECK(put_mode != mojom::IDBPutMode::CursorUpdate);
value_wrapper.Clone(script_state, &clone);
DCHECK(!key_path_key);
@@ -500,7 +500,7 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
} else {
// The clone was created in the large if block above. The block should
// have thrown if key_path_key is not valid.
- DCHECK(put_mode == kWebIDBPutModeCursorUpdate);
+ DCHECK(put_mode == mojom::IDBPutMode::CursorUpdate);
DCHECK(key_path_key && key_path_key->IsValid());
}
@@ -558,8 +558,8 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
key_type_histogram.Count(static_cast<int>(key->GetType()));
}
- WebVector<WebIDBIndexKeys> index_keys;
- index_keys.reserve(Metadata().indexes.size());
+ Vector<WebIDBIndexKeys> index_keys;
+ index_keys.ReserveInitialCapacity(Metadata().indexes.size());
for (const auto& it : Metadata().indexes) {
if (clone.IsEmpty())
value_wrapper.Clone(script_state, &clone);
@@ -584,8 +584,7 @@ IDBRequest* IDBObjectStore::DoPut(ScriptState* script_state,
request->transit_blob_handles() = value_wrapper.TakeBlobDataHandles();
BackendDB()->Put(
transaction_->Id(), Id(), WebData(value_wrapper.TakeWireBytes()),
- value_wrapper.TakeBlobInfo(), WebIDBKeyView(key),
- static_cast<WebIDBPutMode>(put_mode),
+ value_wrapper.TakeBlobInfo(), WebIDBKeyView(key), put_mode,
request->CreateWebCallbacks().release(), std::move(index_keys));
return request;
@@ -727,13 +726,13 @@ class IndexPopulator final : public EventListener {
const IDBIndexMetadata& IndexMetadata() const { return *index_metadata_; }
- void handleEvent(ExecutionContext* execution_context, Event* event) override {
+ void Invoke(ExecutionContext* execution_context, Event* event) override {
if (!script_state_->ContextIsValid())
return;
- IDB_TRACE("IDBObjectStore::IndexPopulator::handleEvent");
+ IDB_TRACE("IDBObjectStore::IndexPopulator::Invoke");
DCHECK_EQ(ExecutionContext::From(script_state_), execution_context);
- DCHECK_EQ(event->type(), EventTypeNames::success);
+ DCHECK_EQ(event->type(), event_type_names::kSuccess);
EventTarget* target = event->target();
IDBRequest* request = static_cast<IDBRequest*>(target);
@@ -754,8 +753,8 @@ class IndexPopulator final : public EventListener {
const IDBKey* primary_key = cursor->IdbPrimaryKey();
ScriptValue value = cursor->value(script_state_);
- WebVector<WebIDBIndexKeys> index_keys;
- index_keys.reserve(1);
+ Vector<WebIDBIndexKeys> index_keys;
+ index_keys.ReserveInitialCapacity(1);
index_keys.emplace_back(
IndexMetadata().id,
GenerateIndexKeysForValue(script_state_->GetIsolate(),
@@ -786,7 +785,7 @@ class IndexPopulator final : public EventListener {
IDBIndex* IDBObjectStore::createIndex(ScriptState* script_state,
const String& name,
const IDBKeyPath& key_path,
- const IDBIndexParameters& options,
+ const IDBIndexParameters* options,
ExceptionState& exception_state) {
IDB_TRACE1("IDBObjectStore::createIndexRequestSetup", "store_name",
metadata_->name.Utf8());
@@ -820,7 +819,7 @@ IDBIndex* IDBObjectStore::createIndex(ScriptState* script_state,
"The keyPath argument contains an invalid key path.");
return nullptr;
}
- if (key_path.GetType() == IDBKeyPath::kArrayType && options.multiEntry()) {
+ if (key_path.GetType() == IDBKeyPath::kArrayType && options->multiEntry()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidAccessError,
"The keyPath argument was an array and the multiEntry option is true.");
@@ -835,13 +834,13 @@ IDBIndex* IDBObjectStore::createIndex(ScriptState* script_state,
int64_t index_id = metadata_->max_index_id + 1;
DCHECK_NE(index_id, IDBIndexMetadata::kInvalidId);
BackendDB()->CreateIndex(transaction_->Id(), Id(), index_id, name, key_path,
- options.unique(), options.multiEntry());
+ options->unique(), options->multiEntry());
++metadata_->max_index_id;
scoped_refptr<IDBIndexMetadata> index_metadata =
base::AdoptRef(new IDBIndexMetadata(
- name, index_id, key_path, options.unique(), options.multiEntry()));
+ name, index_id, key_path, options->unique(), options->multiEntry()));
IDBIndex* index = IDBIndex::Create(index_metadata, this, transaction_.Get());
index_map_.Set(name, index);
metadata_->indexes.Set(index_id, index_metadata);
@@ -851,8 +850,8 @@ IDBIndex* IDBObjectStore::createIndex(ScriptState* script_state,
return nullptr;
IDBRequest* index_request =
- openCursor(script_state, nullptr, kWebIDBCursorDirectionNext,
- kWebIDBTaskTypePreemptive, std::move(metrics));
+ openCursor(script_state, nullptr, mojom::IDBCursorDirection::Next,
+ mojom::IDBTaskType::Preemptive, std::move(metrics));
index_request->PreventPropagation();
// This is kept alive by being the success handler of the request, which is in
@@ -966,7 +965,7 @@ IDBRequest* IDBObjectStore::openCursor(ScriptState* script_state,
return nullptr;
}
- WebIDBCursorDirection direction =
+ mojom::IDBCursorDirection direction =
IDBCursor::StringToDirection(direction_string);
IDBKeyRange* key_range = IDBKeyRange::FromScriptValue(
ExecutionContext::From(script_state), range, exception_state);
@@ -979,18 +978,18 @@ IDBRequest* IDBObjectStore::openCursor(ScriptState* script_state,
return nullptr;
}
- return openCursor(script_state, key_range, direction, kWebIDBTaskTypeNormal,
- std::move(metrics));
+ return openCursor(script_state, key_range, direction,
+ mojom::IDBTaskType::Normal, std::move(metrics));
}
IDBRequest* IDBObjectStore::openCursor(ScriptState* script_state,
IDBKeyRange* range,
- WebIDBCursorDirection direction,
- WebIDBTaskType task_type,
+ mojom::IDBCursorDirection direction,
+ mojom::IDBTaskType task_type,
IDBRequest::AsyncTraceState metrics) {
IDBRequest* request = IDBRequest::Create(
script_state, this, transaction_.Get(), std::move(metrics));
- request->SetCursorDetails(IndexedDB::kCursorKeyAndValue, direction);
+ request->SetCursorDetails(indexed_db::kCursorKeyAndValue, direction);
BackendDB()->OpenCursor(transaction_->Id(), Id(),
IDBIndexMetadata::kInvalidId, range, direction, false,
@@ -1018,7 +1017,7 @@ IDBRequest* IDBObjectStore::openKeyCursor(ScriptState* script_state,
return nullptr;
}
- WebIDBCursorDirection direction =
+ mojom::IDBCursorDirection direction =
IDBCursor::StringToDirection(direction_string);
IDBKeyRange* key_range = IDBKeyRange::FromScriptValue(
ExecutionContext::From(script_state), range, exception_state);
@@ -1033,11 +1032,11 @@ IDBRequest* IDBObjectStore::openKeyCursor(ScriptState* script_state,
IDBRequest* request = IDBRequest::Create(
script_state, this, transaction_.Get(), std::move(metrics));
- request->SetCursorDetails(IndexedDB::kCursorKeyOnly, direction);
+ request->SetCursorDetails(indexed_db::kCursorKeyOnly, direction);
BackendDB()->OpenCursor(transaction_->Id(), Id(),
IDBIndexMetadata::kInvalidId, key_range, direction,
- true, kWebIDBTaskTypeNormal,
+ true, mojom::IDBTaskType::Normal,
request->CreateWebCallbacks().release());
return request;
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.h
index 4174356a2c4..9a59516a9a7 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.h
@@ -28,8 +28,6 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_cursor.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_index.h"
@@ -39,6 +37,8 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_metadata.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -53,8 +53,11 @@ class MODULES_EXPORT IDBObjectStore final : public ScriptWrappable {
public:
static IDBObjectStore* Create(scoped_refptr<IDBObjectStoreMetadata> metadata,
IDBTransaction* transaction) {
- return new IDBObjectStore(std::move(metadata), transaction);
+ return MakeGarbageCollected<IDBObjectStore>(std::move(metadata),
+ transaction);
}
+
+ IDBObjectStore(scoped_refptr<IDBObjectStoreMetadata>, IDBTransaction*);
~IDBObjectStore() override = default;
void Trace(blink::Visitor*) override;
@@ -107,7 +110,7 @@ class MODULES_EXPORT IDBObjectStore final : public ScriptWrappable {
IDBIndex* createIndex(ScriptState* script_state,
const String& name,
const StringOrStringSequence& key_path,
- const IDBIndexParameters& options,
+ const IDBIndexParameters* options,
ExceptionState& exception_state) {
return createIndex(script_state, name, IDBKeyPath(key_path), options,
exception_state);
@@ -119,7 +122,7 @@ class MODULES_EXPORT IDBObjectStore final : public ScriptWrappable {
// Exposed for the use of IDBCursor::update().
IDBRequest* DoPut(ScriptState*,
- WebIDBPutMode,
+ mojom::IDBPutMode,
const IDBRequest::Source&,
const ScriptValue&,
const IDBKey*,
@@ -129,8 +132,8 @@ class MODULES_EXPORT IDBObjectStore final : public ScriptWrappable {
IDBRequest* openCursor(
ScriptState*,
IDBKeyRange*,
- WebIDBCursorDirection,
- WebIDBTaskType = kWebIDBTaskTypeNormal,
+ mojom::IDBCursorDirection,
+ mojom::IDBTaskType = mojom::IDBTaskType::Normal,
IDBRequest::AsyncTraceState = IDBRequest::AsyncTraceState());
IDBRequest* deleteFunction(
ScriptState*,
@@ -187,15 +190,13 @@ class MODULES_EXPORT IDBObjectStore final : public ScriptWrappable {
private:
using IDBIndexMap = HeapHashMap<String, Member<IDBIndex>>;
- IDBObjectStore(scoped_refptr<IDBObjectStoreMetadata>, IDBTransaction*);
-
IDBIndex* createIndex(ScriptState*,
const String& name,
const IDBKeyPath&,
- const IDBIndexParameters&,
+ const IDBIndexParameters*,
ExceptionState&);
IDBRequest* DoPut(ScriptState*,
- WebIDBPutMode,
+ mojom::IDBPutMode,
const ScriptValue&,
const ScriptValue& key_value,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.idl b/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.idl
index dd4aa3e5444..24c6371df38 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.idl
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_object_store.idl
@@ -41,9 +41,9 @@
[NewObject, CallWith=ScriptState, RaisesException] IDBRequest get(any key);
[NewObject, CallWith=ScriptState, RaisesException] IDBRequest getKey(any key);
[NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAll([Default=Undefined] optional any query,
- [EnforceRange] optional unsigned long count);
+ optional [EnforceRange] unsigned long count);
[NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAllKeys([Default=Undefined] optional any query,
- [EnforceRange] optional unsigned long count);
+ optional [EnforceRange] unsigned long count);
[NewObject, CallWith=ScriptState, RaisesException] IDBRequest count([Default=Undefined] optional any key);
[NewObject, CallWith=ScriptState, RaisesException] IDBRequest openCursor([Default=Undefined] optional any range,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.cc
index 4e7f2df4948..1c67cf44264 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.cc
@@ -31,43 +31,44 @@ ScriptValue IDBObservation::value(ScriptState* script_state) {
return ScriptValue::From(script_state, value_);
}
-WebIDBOperationType IDBObservation::StringToOperationType(const String& type) {
- if (type == IndexedDBNames::add)
- return kWebIDBAdd;
- if (type == IndexedDBNames::put)
- return kWebIDBPut;
- if (type == IndexedDBNames::kDelete)
- return kWebIDBDelete;
- if (type == IndexedDBNames::clear)
- return kWebIDBClear;
+mojom::IDBOperationType IDBObservation::StringToOperationType(
+ const String& type) {
+ if (type == indexed_db_names::kAdd)
+ return mojom::IDBOperationType::Add;
+ if (type == indexed_db_names::kPut)
+ return mojom::IDBOperationType::Put;
+ if (type == indexed_db_names::kDelete)
+ return mojom::IDBOperationType::Delete;
+ if (type == indexed_db_names::kClear)
+ return mojom::IDBOperationType::Clear;
NOTREACHED();
- return kWebIDBAdd;
+ return mojom::IDBOperationType::Add;
}
const String& IDBObservation::type() const {
switch (operation_type_) {
- case kWebIDBAdd:
- return IndexedDBNames::add;
+ case mojom::IDBOperationType::Add:
+ return indexed_db_names::kAdd;
- case kWebIDBPut:
- return IndexedDBNames::put;
+ case mojom::IDBOperationType::Put:
+ return indexed_db_names::kPut;
- case kWebIDBDelete:
- return IndexedDBNames::kDelete;
+ case mojom::IDBOperationType::Delete:
+ return indexed_db_names::kDelete;
- case kWebIDBClear:
- return IndexedDBNames::clear;
+ case mojom::IDBOperationType::Clear:
+ return indexed_db_names::kClear;
default:
NOTREACHED();
- return IndexedDBNames::add;
+ return indexed_db_names::kAdd;
}
}
IDBObservation* IDBObservation::Create(WebIDBObservation observation,
v8::Isolate* isolate) {
- return new IDBObservation(std::move(observation), isolate);
+ return MakeGarbageCollected<IDBObservation>(std::move(observation), isolate);
}
IDBObservation::IDBObservation(WebIDBObservation observation,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.h
index f9a97d65457..339043ee3c9 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observation.h
@@ -8,6 +8,7 @@
#include <memory>
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -23,11 +24,12 @@ class IDBObservation final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static WebIDBOperationType StringToOperationType(const String&);
+ static mojom::IDBOperationType StringToOperationType(const String&);
// Consumes the WebIDBObservation.
static IDBObservation* Create(WebIDBObservation, v8::Isolate*);
+ IDBObservation(WebIDBObservation, v8::Isolate*);
~IDBObservation() override;
void Trace(blink::Visitor*) override;
@@ -38,11 +40,9 @@ class IDBObservation final : public ScriptWrappable {
const String& type() const;
private:
- IDBObservation(WebIDBObservation, v8::Isolate*);
-
Member<IDBKeyRange> key_range_;
Member<IDBAny> value_;
- const WebIDBOperationType operation_type_;
+ const mojom::IDBOperationType operation_type_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.cc
index c40aefac549..fb4c0617684 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.cc
@@ -19,7 +19,7 @@
namespace blink {
IDBObserver* IDBObserver::Create(V8IDBObserverCallback* callback) {
- return new IDBObserver(callback);
+ return MakeGarbageCollected<IDBObserver>(callback);
}
IDBObserver::IDBObserver(V8IDBObserverCallback* callback)
@@ -27,7 +27,7 @@ IDBObserver::IDBObserver(V8IDBObserverCallback* callback)
void IDBObserver::observe(IDBDatabase* database,
IDBTransaction* transaction,
- const IDBObserverInit& options,
+ const IDBObserverInit* options,
ExceptionState& exception_state) {
if (!transaction->IsActive()) {
exception_state.ThrowDOMException(
@@ -46,26 +46,26 @@ void IDBObserver::observe(IDBDatabase* database,
IDBDatabase::kDatabaseClosedErrorMessage);
return;
}
- if (!options.hasOperationTypes()) {
+ if (!options->hasOperationTypes()) {
exception_state.ThrowTypeError(
- "operationTypes not specified in observe options.");
+ "operationTypes not specified in observe options->");
return;
}
- if (options.operationTypes().IsEmpty()) {
+ if (options->operationTypes().IsEmpty()) {
exception_state.ThrowTypeError("operationTypes must be populated.");
return;
}
- std::bitset<kWebIDBOperationTypeCount> types;
- for (const auto& operation_type : options.operationTypes()) {
- if (operation_type == IndexedDBNames::add) {
- types[kWebIDBAdd] = true;
- } else if (operation_type == IndexedDBNames::put) {
- types[kWebIDBPut] = true;
- } else if (operation_type == IndexedDBNames::kDelete) {
- types[kWebIDBDelete] = true;
- } else if (operation_type == IndexedDBNames::clear) {
- types[kWebIDBClear] = true;
+ std::bitset<kIDBOperationTypeCount> types;
+ for (const auto& operation_type : options->operationTypes()) {
+ if (operation_type == indexed_db_names::kAdd) {
+ types[static_cast<size_t>(mojom::IDBOperationType::Add)] = true;
+ } else if (operation_type == indexed_db_names::kPut) {
+ types[static_cast<size_t>(mojom::IDBOperationType::Put)] = true;
+ } else if (operation_type == indexed_db_names::kDelete) {
+ types[static_cast<size_t>(mojom::IDBOperationType::Delete)] = true;
+ } else if (operation_type == indexed_db_names::kClear) {
+ types[static_cast<size_t>(mojom::IDBOperationType::Clear)] = true;
} else {
exception_state.ThrowTypeError(
"Unknown operation type in observe options: " + operation_type);
@@ -74,8 +74,8 @@ void IDBObserver::observe(IDBDatabase* database,
}
int32_t observer_id =
- database->AddObserver(this, transaction->Id(), options.transaction(),
- options.noRecords(), options.values(), types);
+ database->AddObserver(this, transaction->Id(), options->transaction(),
+ options->noRecords(), options->values(), types);
observer_ids_.insert(observer_id, database);
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.h
index b51ec3c3a03..85bdb35e94d 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer.h
@@ -28,18 +28,18 @@ class MODULES_EXPORT IDBObserver final : public ScriptWrappable {
V8IDBObserverCallback* Callback() { return callback_; }
+ explicit IDBObserver(V8IDBObserverCallback*);
+
// Implement the IDBObserver IDL.
void observe(IDBDatabase*,
IDBTransaction*,
- const IDBObserverInit&,
+ const IDBObserverInit*,
ExceptionState&);
void unobserve(IDBDatabase*, ExceptionState&);
void Trace(blink::Visitor*) override;
private:
- explicit IDBObserver(V8IDBObserverCallback*);
-
TraceWrapperMember<V8IDBObserverCallback> callback_;
HeapHashMap<int32_t, WeakMember<IDBDatabase>> observer_ids_;
};
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.cc
index 1e5ceec881b..af876c85b10 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.cc
@@ -36,8 +36,9 @@ IDBObserverChanges* IDBObserverChanges::Create(
const HeapVector<Member<IDBObservation>>& observations,
const WebVector<int32_t>& observation_indices) {
DCHECK_EQ(web_observations.size(), observations.size());
- return new IDBObserverChanges(database, transaction, web_observations,
- observations, observation_indices);
+ return MakeGarbageCollected<IDBObserverChanges>(
+ database, transaction, web_observations, observations,
+ observation_indices);
}
IDBObserverChanges::IDBObserverChanges(
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.h
index 1c48bcf04fa..53bc5deebb4 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_observer_changes.h
@@ -28,6 +28,13 @@ class IDBObserverChanges final : public ScriptWrappable {
const HeapVector<Member<IDBObservation>>& observations,
const WebVector<int32_t>& observation_indices);
+ IDBObserverChanges(IDBDatabase*,
+ IDBTransaction*,
+
+ const WebVector<WebIDBObservation>& web_observations,
+ const HeapVector<Member<IDBObservation>>& observations,
+ const WebVector<int32_t>& observation_indices);
+
void Trace(blink::Visitor*) override;
// Implement IDL
@@ -36,13 +43,6 @@ class IDBObserverChanges final : public ScriptWrappable {
ScriptValue records(ScriptState*);
private:
- IDBObserverChanges(IDBDatabase*,
- IDBTransaction*,
-
- const WebVector<WebIDBObservation>& web_observations,
- const HeapVector<Member<IDBObservation>>& observations,
- const WebVector<int32_t>& observation_indices);
-
void ExtractChanges(const WebVector<WebIDBObservation>& web_observations,
const HeapVector<Member<IDBObservation>>& observations,
const WebVector<int32_t>& observation_indices);
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.cc
index 25779b6f514..f8a81ea7ed1 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.cc
@@ -45,7 +45,7 @@ IDBOpenDBRequest* IDBOpenDBRequest::Create(
int64_t transaction_id,
int64_t version,
IDBRequest::AsyncTraceState metrics) {
- IDBOpenDBRequest* request = new IDBOpenDBRequest(
+ IDBOpenDBRequest* request = MakeGarbageCollected<IDBOpenDBRequest>(
script_state, callbacks, transaction_id, version, std::move(metrics));
request->PauseIfNeeded();
return request;
@@ -80,7 +80,7 @@ void IDBOpenDBRequest::ContextDestroyed(ExecutionContext* destroyed_context) {
}
const AtomicString& IDBOpenDBRequest::InterfaceName() const {
- return EventTargetNames::IDBOpenDBRequest;
+ return event_target_names::kIDBOpenDBRequest;
}
void IDBOpenDBRequest::EnqueueBlocked(int64_t old_version) {
@@ -92,14 +92,14 @@ void IDBOpenDBRequest::EnqueueBlocked(int64_t old_version) {
new_version_nullable = version_;
}
EnqueueEvent(IDBVersionChangeEvent::Create(
- EventTypeNames::blocked, old_version, new_version_nullable));
+ event_type_names::kBlocked, old_version, new_version_nullable));
}
void IDBOpenDBRequest::EnqueueUpgradeNeeded(
int64_t old_version,
std::unique_ptr<WebIDBDatabase> backend,
const IDBDatabaseMetadata& metadata,
- WebIDBDataLoss data_loss,
+ mojom::IDBDataLoss data_loss,
String data_loss_message) {
IDB_TRACE("IDBOpenDBRequest::onUpgradeNeeded()");
if (!ShouldEnqueueEvent()) {
@@ -128,7 +128,7 @@ void IDBOpenDBRequest::EnqueueUpgradeNeeded(
if (version_ == IDBDatabaseMetadata::kNoVersion)
version_ = 1;
- EnqueueEvent(IDBVersionChangeEvent::Create(EventTypeNames::upgradeneeded,
+ EnqueueEvent(IDBVersionChangeEvent::Create(event_type_names::kUpgradeneeded,
old_version, version_, data_loss,
data_loss_message));
}
@@ -157,7 +157,7 @@ void IDBOpenDBRequest::EnqueueResponse(std::unique_ptr<WebIDBDatabase> backend,
SetResult(IDBAny::Create(idb_database));
}
idb_database->SetMetadata(metadata);
- EnqueueEvent(Event::Create(EventTypeNames::success));
+ EnqueueEvent(Event::Create(event_type_names::kSuccess));
metrics_.RecordAndReset();
}
@@ -172,7 +172,7 @@ void IDBOpenDBRequest::EnqueueResponse(int64_t old_version) {
old_version = IDBDatabaseMetadata::kDefaultVersion;
}
SetResult(IDBAny::CreateUndefined());
- EnqueueEvent(IDBVersionChangeEvent::Create(EventTypeNames::success,
+ EnqueueEvent(IDBVersionChangeEvent::Create(event_type_names::kSuccess,
old_version, base::nullopt));
metrics_.RecordAndReset();
}
@@ -189,7 +189,7 @@ bool IDBOpenDBRequest::ShouldEnqueueEvent() const {
DispatchEventResult IDBOpenDBRequest::DispatchEventInternal(Event& event) {
// If the connection closed between onUpgradeNeeded and the delivery of the
// "success" event, an "error" event should be fired instead.
- if (event.type() == EventTypeNames::success &&
+ if (event.type() == event_type_names::kSuccess &&
ResultAsAny()->GetType() == IDBAny::kIDBDatabaseType &&
ResultAsAny()->IdbDatabase()->IsClosePending()) {
SetResult(nullptr);
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h
index 36d9ecb4be5..7752ece4f7f 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h
@@ -27,8 +27,8 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_IDB_OPEN_DB_REQUEST_H_
#include <memory>
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/modules/modules_export.h"
namespace blink {
@@ -44,14 +44,21 @@ class MODULES_EXPORT IDBOpenDBRequest final : public IDBRequest {
int64_t transaction_id,
int64_t version,
IDBRequest::AsyncTraceState metrics);
+
+ IDBOpenDBRequest(ScriptState*,
+ IDBDatabaseCallbacks*,
+ int64_t transaction_id,
+ int64_t version,
+ IDBRequest::AsyncTraceState metrics);
~IDBOpenDBRequest() override;
+
void Trace(blink::Visitor*) override;
void EnqueueBlocked(int64_t existing_version) override;
void EnqueueUpgradeNeeded(int64_t old_version,
std::unique_ptr<WebIDBDatabase>,
const IDBDatabaseMetadata&,
- WebIDBDataLoss,
+ mojom::IDBDataLoss,
String data_loss_message) override;
void EnqueueResponse(std::unique_ptr<WebIDBDatabase>,
const IDBDatabaseMetadata&) override;
@@ -62,8 +69,8 @@ class MODULES_EXPORT IDBOpenDBRequest final : public IDBRequest {
// EventTarget
const AtomicString& InterfaceName() const override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(blocked);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(upgradeneeded);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(blocked, kBlocked);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(upgradeneeded, kUpgradeneeded);
protected:
void EnqueueResponse(int64_t old_version) override;
@@ -74,12 +81,6 @@ class MODULES_EXPORT IDBOpenDBRequest final : public IDBRequest {
DispatchEventResult DispatchEventInternal(Event&) override;
private:
- IDBOpenDBRequest(ScriptState*,
- IDBDatabaseCallbacks*,
- int64_t transaction_id,
- int64_t version,
- IDBRequest::AsyncTraceState metrics);
-
Member<IDBDatabaseCallbacks> database_callbacks_;
const int64_t transaction_id_;
int64_t version_;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.cc
index 765b6267942..a457f84c9d5 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.cc
@@ -120,8 +120,8 @@ IDBRequest* IDBRequest::Create(ScriptState* script_state,
const Source& source,
IDBTransaction* transaction,
IDBRequest::AsyncTraceState metrics) {
- IDBRequest* request =
- new IDBRequest(script_state, source, transaction, std::move(metrics));
+ IDBRequest* request = MakeGarbageCollected<IDBRequest>(
+ script_state, source, transaction, std::move(metrics));
request->PauseIfNeeded();
// Requests associated with IDBFactory (open/deleteDatabase/getDatabaseNames)
// do not have an associated transaction.
@@ -200,9 +200,9 @@ const String& IDBRequest::readyState() const {
DCHECK(ready_state_ == PENDING || ready_state_ == DONE);
if (ready_state_ == PENDING)
- return IndexedDBNames::pending;
+ return indexed_db_names::kPending;
- return IndexedDBNames::done;
+ return indexed_db_names::kDone;
}
std::unique_ptr<WebIDBCallbacks> IDBRequest::CreateWebCallbacks() {
@@ -239,8 +239,8 @@ void IDBRequest::Abort() {
request_aborted_ = true;
}
-void IDBRequest::SetCursorDetails(IndexedDB::CursorType cursor_type,
- WebIDBCursorDirection direction) {
+void IDBRequest::SetCursorDetails(indexed_db::CursorType cursor_type,
+ mojom::IDBCursorDirection direction) {
DCHECK_EQ(ready_state_, PENDING);
DCHECK(!pending_cursor_);
cursor_type_ = cursor_type;
@@ -418,7 +418,7 @@ void IDBRequest::EnqueueResponse(DOMException* error) {
error_ = error;
SetResult(IDBAny::CreateUndefined());
pending_cursor_.Clear();
- EnqueueEvent(Event::CreateCancelableBubble(EventTypeNames::error));
+ EnqueueEvent(Event::CreateCancelableBubble(event_type_names::kError));
metrics_.RecordAndReset();
}
@@ -460,11 +460,11 @@ void IDBRequest::EnqueueResponse(std::unique_ptr<WebIDBCursor> backend,
DCHECK(!source.IsNull());
switch (cursor_type_) {
- case IndexedDB::kCursorKeyOnly:
+ case indexed_db::kCursorKeyOnly:
cursor = IDBCursor::Create(std::move(backend), cursor_direction_, this,
source, transaction_.Get());
break;
- case IndexedDB::kCursorKeyAndValue:
+ case indexed_db::kCursorKeyAndValue:
cursor = IDBCursorWithValue::Create(std::move(backend), cursor_direction_,
this, source, transaction_.Get());
break;
@@ -573,7 +573,7 @@ void IDBRequest::EnqueueResultInternal(IDBAny* result) {
DCHECK(!pending_cursor_);
DCHECK(transit_blob_handles_.IsEmpty());
SetResult(result);
- EnqueueEvent(Event::Create(EventTypeNames::success));
+ EnqueueEvent(Event::Create(event_type_names::kSuccess));
}
void IDBRequest::SetResult(IDBAny* result) {
@@ -625,7 +625,7 @@ void IDBRequest::ContextDestroyed(ExecutionContext*) {
}
const AtomicString& IDBRequest::InterfaceName() const {
- return EventTargetNames::IDBRequest;
+ return event_target_names::kIDBRequest;
}
ExecutionContext* IDBRequest::GetExecutionContext() const {
@@ -640,7 +640,7 @@ DispatchEventResult IDBRequest::DispatchEventInternal(Event& event) {
DCHECK(has_pending_activity_);
DCHECK_EQ(event.target(), this);
- if (event.type() != EventTypeNames::blocked)
+ if (event.type() != event_type_names::kBlocked)
ready_state_ = DONE;
HeapVector<Member<EventTarget>> targets;
@@ -657,7 +657,7 @@ DispatchEventResult IDBRequest::DispatchEventInternal(Event& event) {
// Cursor properties should not be updated until the success event is being
// dispatched.
IDBCursor* cursor_to_notify = nullptr;
- if (event.type() == EventTypeNames::success) {
+ if (event.type() == event_type_names::kSuccess) {
cursor_to_notify = GetResultCursor();
if (cursor_to_notify) {
cursor_to_notify->SetValueReady(std::move(cursor_key_),
@@ -666,23 +666,23 @@ DispatchEventResult IDBRequest::DispatchEventInternal(Event& event) {
}
}
- if (event.type() == EventTypeNames::upgradeneeded) {
+ if (event.type() == event_type_names::kUpgradeneeded) {
DCHECK(!did_fire_upgrade_needed_event_);
did_fire_upgrade_needed_event_ = true;
}
// FIXME: When we allow custom event dispatching, this will probably need to
// change.
- DCHECK(event.type() == EventTypeNames::success ||
- event.type() == EventTypeNames::error ||
- event.type() == EventTypeNames::blocked ||
- event.type() == EventTypeNames::upgradeneeded)
+ DCHECK(event.type() == event_type_names::kSuccess ||
+ event.type() == event_type_names::kError ||
+ event.type() == event_type_names::kBlocked ||
+ event.type() == event_type_names::kUpgradeneeded)
<< "event type was " << event.type();
const bool set_transaction_active =
transaction_ &&
- (event.type() == EventTypeNames::success ||
- event.type() == EventTypeNames::upgradeneeded ||
- (event.type() == EventTypeNames::error && !request_aborted_));
+ (event.type() == event_type_names::kSuccess ||
+ event.type() == event_type_names::kUpgradeneeded ||
+ (event.type() == event_type_names::kError && !request_aborted_));
if (set_transaction_active)
transaction_->SetActive(true);
@@ -710,7 +710,7 @@ DispatchEventResult IDBRequest::DispatchEventInternal(Event& event) {
DOMException::Create(DOMExceptionCode::kAbortError,
"Uncaught exception in event handler."));
transaction_->abort(IGNORE_EXCEPTION_FOR_TESTING);
- } else if (event.type() == EventTypeNames::error &&
+ } else if (event.type() == event_type_names::kError &&
dispatch_result == DispatchEventResult::kNotCanceled) {
transaction_->SetError(error_);
transaction_->abort(IGNORE_EXCEPTION_FOR_TESTING);
@@ -728,7 +728,7 @@ DispatchEventResult IDBRequest::DispatchEventInternal(Event& event) {
// An upgradeneeded event will always be followed by a success or error event,
// so must be kept alive.
- if (ready_state_ == DONE && event.type() != EventTypeNames::upgradeneeded)
+ if (ready_state_ == DONE && event.type() != event_type_names::kUpgradeneeded)
has_pending_activity_ = false;
return dispatch_result;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.h
index 5e1980d87e4..48226908cce 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request.h
@@ -34,7 +34,7 @@
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
#include "third_party/blink/public/platform/web_blob_info.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
@@ -49,6 +49,7 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_any.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
@@ -175,7 +176,10 @@ class MODULES_EXPORT IDBRequest : public EventTargetWithInlineData,
const Source&,
IDBTransaction*,
AsyncTraceState);
+
+ IDBRequest(ScriptState*, const Source&, IDBTransaction*, AsyncTraceState);
~IDBRequest() override;
+
void Trace(blink::Visitor*) override;
v8::Isolate* GetIsolate() const { return isolate_; }
@@ -214,10 +218,10 @@ class MODULES_EXPORT IDBRequest : public EventTargetWithInlineData,
WebIDBCallbacks* WebCallbacks() const { return web_callbacks_; }
#endif // DCHECK_IS_ON()
- DEFINE_ATTRIBUTE_EVENT_LISTENER(success);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(success, kSuccess);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
- void SetCursorDetails(IndexedDB::CursorType, WebIDBCursorDirection);
+ void SetCursorDetails(indexed_db::CursorType, mojom::IDBCursorDirection);
void SetPendingCursor(IDBCursor*);
void Abort();
@@ -276,7 +280,7 @@ class MODULES_EXPORT IDBRequest : public EventTargetWithInlineData,
virtual void EnqueueUpgradeNeeded(int64_t old_version,
std::unique_ptr<WebIDBDatabase>,
const IDBDatabaseMetadata&,
- WebIDBDataLoss,
+ mojom::IDBDataLoss,
String data_loss_message) {
NOTREACHED();
}
@@ -333,7 +337,6 @@ class MODULES_EXPORT IDBRequest : public EventTargetWithInlineData,
}
protected:
- IDBRequest(ScriptState*, const Source&, IDBTransaction*, AsyncTraceState);
void EnqueueEvent(Event*);
virtual bool ShouldEnqueueEvent() const;
void EnqueueResultInternal(IDBAny*);
@@ -390,8 +393,8 @@ class MODULES_EXPORT IDBRequest : public EventTargetWithInlineData,
Member<EventQueue> event_queue_;
// Only used if the result type will be a cursor.
- IndexedDB::CursorType cursor_type_ = IndexedDB::kCursorKeyAndValue;
- WebIDBCursorDirection cursor_direction_ = kWebIDBCursorDirectionNext;
+ indexed_db::CursorType cursor_type_ = indexed_db::kCursorKeyAndValue;
+ mojom::IDBCursorDirection cursor_direction_ = mojom::IDBCursorDirection::Next;
// When a cursor is continued/advanced, |result_| is cleared and
// |pendingCursor_| holds it.
Member<IDBCursor> pending_cursor_;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.cc
index f3a516cfcef..fc21d8271e9 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.cc
@@ -106,7 +106,7 @@ void IDBRequestLoader::DidFinishLoading() {
StartNextValue();
}
-void IDBRequestLoader::DidFail(FileError::ErrorCode) {
+void IDBRequestLoader::DidFail(FileErrorCode) {
#if DCHECK_IS_ON()
DCHECK(started_)
<< "FileReaderLoader called DidFail() before it was Start()ed";
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.h
index cc358bf1f3d..a6d5dd9837b 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_loader.h
@@ -52,7 +52,7 @@ class IDBRequestLoader : public FileReaderLoaderClient {
void DidStartLoading() override;
void DidReceiveDataForClient(const char* data, unsigned data_length) override;
void DidFinishLoading() override;
- void DidFail(FileError::ErrorCode) override;
+ void DidFail(FileErrorCode) override;
private:
// Starts unwrapping the next wrapped IDBValue.
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_queue_item.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_queue_item.cc
index cfbe57f7323..bb8753cd58a 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_queue_item.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_queue_item.cc
@@ -9,12 +9,12 @@
#include "base/callback.h"
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request_loader.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_value.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_test.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_test.cc
index f7003c6e2bd..1556b71144f 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_test.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_request_test.cc
@@ -82,7 +82,7 @@ class IDBRequestTest : public testing::Test {
HashSet<String> transaction_scope = {"store"};
transaction_ = IDBTransaction::CreateNonVersionChange(
scope.GetScriptState(), kTransactionId, transaction_scope,
- kWebIDBTransactionModeReadOnly, db_.Get());
+ mojom::IDBTransactionMode::ReadOnly, db_.Get());
IDBKeyPath store_key_path("primaryKey");
scoped_refptr<IDBObjectStoreMetadata> store_metadata = base::AdoptRef(
@@ -257,7 +257,7 @@ TEST_F(IDBRequestTest, ConnectionsAfterStopping) {
scope.GetExecutionContext()->NotifyContextDestroyed();
callbacks->OnUpgradeNeeded(kOldVersion, backend.release(), metadata,
- kWebIDBDataLossNone, String());
+ mojom::IDBDataLoss::None, String());
}
{
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc
index 588891f366f..f04b84cc5fa 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.cc
@@ -25,6 +25,8 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
+#include <memory>
+
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event_queue.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
@@ -41,8 +43,6 @@
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
-#include <memory>
-
using blink::WebIDBDatabase;
namespace blink {
@@ -55,7 +55,7 @@ IDBTransaction* IDBTransaction::CreateObserver(
DCHECK(!scope.IsEmpty()) << "Observer transactions must operate on a "
"well-defined set of stores";
IDBTransaction* transaction =
- new IDBTransaction(execution_context, id, scope, db);
+ MakeGarbageCollected<IDBTransaction>(execution_context, id, scope, db);
return transaction;
}
@@ -63,12 +63,13 @@ IDBTransaction* IDBTransaction::CreateNonVersionChange(
ScriptState* script_state,
int64_t id,
const HashSet<String>& scope,
- WebIDBTransactionMode mode,
+ mojom::IDBTransactionMode mode,
IDBDatabase* db) {
- DCHECK_NE(mode, kWebIDBTransactionModeVersionChange);
+ DCHECK_NE(mode, mojom::IDBTransactionMode::VersionChange);
DCHECK(!scope.IsEmpty()) << "Non-version transactions should operate on a "
"well-defined set of stores";
- return new IDBTransaction(script_state, id, scope, mode, db);
+ return MakeGarbageCollected<IDBTransaction>(script_state, id, scope, mode,
+ db);
}
IDBTransaction* IDBTransaction::CreateVersionChange(
@@ -77,8 +78,8 @@ IDBTransaction* IDBTransaction::CreateVersionChange(
IDBDatabase* db,
IDBOpenDBRequest* open_db_request,
const IDBDatabaseMetadata& old_metadata) {
- return new IDBTransaction(execution_context, id, db, open_db_request,
- old_metadata);
+ return MakeGarbageCollected<IDBTransaction>(execution_context, id, db,
+ open_db_request, old_metadata);
}
IDBTransaction::IDBTransaction(ExecutionContext* execution_context,
@@ -88,7 +89,7 @@ IDBTransaction::IDBTransaction(ExecutionContext* execution_context,
: ContextLifecycleObserver(execution_context),
id_(id),
database_(db),
- mode_(kWebIDBTransactionModeReadOnly),
+ mode_(mojom::IDBTransactionMode::ReadOnly),
scope_(scope),
state_(kActive),
event_queue_(
@@ -102,7 +103,7 @@ IDBTransaction::IDBTransaction(ExecutionContext* execution_context,
IDBTransaction::IDBTransaction(ScriptState* script_state,
int64_t id,
const HashSet<String>& scope,
- WebIDBTransactionMode mode,
+ mojom::IDBTransactionMode mode,
IDBDatabase* db)
: ContextLifecycleObserver(ExecutionContext::From(script_state)),
id_(id),
@@ -114,8 +115,8 @@ IDBTransaction::IDBTransaction(ScriptState* script_state,
DCHECK(database_);
DCHECK(!scope_.IsEmpty()) << "Non-versionchange transactions must operate "
"on a well-defined set of stores";
- DCHECK(mode_ == kWebIDBTransactionModeReadOnly ||
- mode_ == kWebIDBTransactionModeReadWrite)
+ DCHECK(mode_ == mojom::IDBTransactionMode::ReadOnly ||
+ mode_ == mojom::IDBTransactionMode::ReadWrite)
<< "Invalid transaction mode";
DCHECK_EQ(state_, kActive);
@@ -135,7 +136,7 @@ IDBTransaction::IDBTransaction(ExecutionContext* execution_context,
id_(id),
database_(db),
open_db_request_(open_db_request),
- mode_(kWebIDBTransactionModeVersionChange),
+ mode_(mojom::IDBTransactionMode::VersionChange),
state_(kInactive),
old_database_metadata_(old_metadata),
event_queue_(
@@ -231,7 +232,7 @@ void IDBTransaction::ObjectStoreCreated(const String& name,
IDBObjectStore* object_store) {
DCHECK_NE(state_, kFinished)
<< "A finished transaction created an object store";
- DCHECK_EQ(mode_, kWebIDBTransactionModeVersionChange)
+ DCHECK_EQ(mode_, mojom::IDBTransactionMode::VersionChange)
<< "A non-versionchange transaction created an object store";
DCHECK(!object_store_map_.Contains(name))
<< "An object store was created with the name of an existing store";
@@ -244,7 +245,7 @@ void IDBTransaction::ObjectStoreDeleted(const int64_t object_store_id,
const String& name) {
DCHECK_NE(state_, kFinished)
<< "A finished transaction deleted an object store";
- DCHECK_EQ(mode_, kWebIDBTransactionModeVersionChange)
+ DCHECK_EQ(mode_, mojom::IDBTransactionMode::VersionChange)
<< "A non-versionchange transaction deleted an object store";
IDBObjectStoreMap::iterator it = object_store_map_.find(name);
if (it == object_store_map_.end()) {
@@ -282,7 +283,7 @@ void IDBTransaction::ObjectStoreRenamed(const String& old_name,
const String& new_name) {
DCHECK_NE(state_, kFinished)
<< "A finished transaction renamed an object store";
- DCHECK_EQ(mode_, kWebIDBTransactionModeVersionChange)
+ DCHECK_EQ(mode_, mojom::IDBTransactionMode::VersionChange)
<< "A non-versionchange transaction renamed an object store";
DCHECK(!object_store_map_.Contains(new_name));
@@ -424,7 +425,7 @@ void IDBTransaction::OnAbort(DOMException* error) {
// Enqueue events before notifying database, as database may close which
// enqueues more events and order matters.
- EnqueueEvent(Event::CreateBubble(EventTypeNames::abort));
+ EnqueueEvent(Event::CreateBubble(event_type_names::kAbort));
Finished();
}
@@ -440,7 +441,7 @@ void IDBTransaction::OnComplete() {
// Enqueue events before notifying database, as database may close which
// enqueues more events and order matters.
- EnqueueEvent(Event::Create(EventTypeNames::complete));
+ EnqueueEvent(Event::Create(event_type_names::kComplete));
Finished();
}
@@ -452,15 +453,16 @@ bool IDBTransaction::HasPendingActivity() const {
return has_pending_activity_ && GetExecutionContext();
}
-WebIDBTransactionMode IDBTransaction::StringToMode(const String& mode_string) {
- if (mode_string == IndexedDBNames::readonly)
- return kWebIDBTransactionModeReadOnly;
- if (mode_string == IndexedDBNames::readwrite)
- return kWebIDBTransactionModeReadWrite;
- if (mode_string == IndexedDBNames::versionchange)
- return kWebIDBTransactionModeVersionChange;
+mojom::IDBTransactionMode IDBTransaction::StringToMode(
+ const String& mode_string) {
+ if (mode_string == indexed_db_names::kReadonly)
+ return mojom::IDBTransactionMode::ReadOnly;
+ if (mode_string == indexed_db_names::kReadwrite)
+ return mojom::IDBTransactionMode::ReadWrite;
+ if (mode_string == indexed_db_names::kVersionchange)
+ return mojom::IDBTransactionMode::VersionChange;
NOTREACHED();
- return kWebIDBTransactionModeReadOnly;
+ return mojom::IDBTransactionMode::ReadOnly;
}
WebIDBDatabase* IDBTransaction::BackendDB() const {
@@ -469,18 +471,18 @@ WebIDBDatabase* IDBTransaction::BackendDB() const {
const String& IDBTransaction::mode() const {
switch (mode_) {
- case kWebIDBTransactionModeReadOnly:
- return IndexedDBNames::readonly;
+ case mojom::IDBTransactionMode::ReadOnly:
+ return indexed_db_names::kReadonly;
- case kWebIDBTransactionModeReadWrite:
- return IndexedDBNames::readwrite;
+ case mojom::IDBTransactionMode::ReadWrite:
+ return indexed_db_names::kReadwrite;
- case kWebIDBTransactionModeVersionChange:
- return IndexedDBNames::versionchange;
+ case mojom::IDBTransactionMode::VersionChange:
+ return indexed_db_names::kVersionchange;
}
NOTREACHED();
- return IndexedDBNames::readonly;
+ return indexed_db_names::kReadonly;
}
DOMStringList* IDBTransaction::objectStoreNames() const {
@@ -495,7 +497,7 @@ DOMStringList* IDBTransaction::objectStoreNames() const {
}
const AtomicString& IDBTransaction::InterfaceName() const {
- return EventTargetNames::IDBTransaction;
+ return event_target_names::kIDBTransaction;
}
ExecutionContext* IDBTransaction::GetExecutionContext() const {
@@ -536,8 +538,8 @@ DispatchEventResult IDBTransaction::DispatchEventInternal(Event& event) {
// FIXME: When we allow custom event dispatching, this will probably need to
// change.
- DCHECK(event.type() == EventTypeNames::complete ||
- event.type() == EventTypeNames::abort);
+ DCHECK(event.type() == event_type_names::kComplete ||
+ event.type() == event_type_names::kAbort);
DispatchEventResult dispatch_result =
IDBEventDispatcher::Dispatch(event, targets);
// FIXME: Try to construct a test where |this| outlives openDBRequest and we
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.h
index bfb15df7825..f589fe3ed16 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction.h
@@ -29,7 +29,7 @@
#include <memory>
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/dom/dom_string_list.h"
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_metadata.h"
#include "third_party/blink/renderer/modules/indexeddb/indexed_db.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
@@ -74,7 +75,7 @@ class MODULES_EXPORT IDBTransaction final
static IDBTransaction* CreateNonVersionChange(ScriptState*,
int64_t,
const HashSet<String>& scope,
- WebIDBTransactionMode,
+ mojom::IDBTransactionMode,
IDBDatabase*);
static IDBTransaction* CreateVersionChange(
ExecutionContext*,
@@ -82,10 +83,29 @@ class MODULES_EXPORT IDBTransaction final
IDBDatabase*,
IDBOpenDBRequest*,
const IDBDatabaseMetadata& old_metadata);
+
+ // For observer transactions.
+ IDBTransaction(ExecutionContext*,
+ int64_t,
+ const HashSet<String>& scope,
+ IDBDatabase*);
+ // For non-upgrade transactions.
+ IDBTransaction(ScriptState*,
+ int64_t,
+ const HashSet<String>& scope,
+ mojom::IDBTransactionMode,
+ IDBDatabase*);
+ // For upgrade transactions.
+ IDBTransaction(ExecutionContext*,
+ int64_t,
+ IDBDatabase*,
+ IDBOpenDBRequest*,
+ const IDBDatabaseMetadata&);
~IDBTransaction() override;
+
void Trace(blink::Visitor*) override;
- static WebIDBTransactionMode StringToMode(const String&);
+ static mojom::IDBTransactionMode StringToMode(const String&);
// When the connection is closed backend will be 0.
WebIDBDatabase* BackendDB() const;
@@ -94,9 +114,11 @@ class MODULES_EXPORT IDBTransaction final
bool IsActive() const { return state_ == kActive; }
bool IsFinished() const { return state_ == kFinished; }
bool IsFinishing() const { return state_ == kFinishing; }
- bool IsReadOnly() const { return mode_ == kWebIDBTransactionModeReadOnly; }
+ bool IsReadOnly() const {
+ return mode_ == mojom::IDBTransactionMode::ReadOnly;
+ }
bool IsVersionChange() const {
- return mode_ == kWebIDBTransactionModeVersionChange;
+ return mode_ == mojom::IDBTransactionMode::VersionChange;
}
// Implement the IDBTransaction IDL
@@ -133,9 +155,9 @@ class MODULES_EXPORT IDBTransaction final
void SetActive(bool);
void SetError(DOMException*);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(complete);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(complete, kComplete);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
void OnAbort(DOMException*);
void OnComplete();
@@ -166,26 +188,6 @@ class MODULES_EXPORT IDBTransaction final
private:
using IDBObjectStoreMap = HeapHashMap<String, Member<IDBObjectStore>>;
- // For observer transactions.
- IDBTransaction(ExecutionContext*,
- int64_t,
- const HashSet<String>& scope,
- IDBDatabase*);
-
- // For non-upgrade transactions.
- IDBTransaction(ScriptState*,
- int64_t,
- const HashSet<String>& scope,
- WebIDBTransactionMode,
- IDBDatabase*);
-
- // For upgrade transactions.
- IDBTransaction(ExecutionContext*,
- int64_t,
- IDBDatabase*,
- IDBOpenDBRequest*,
- const IDBDatabaseMetadata&);
-
void EnqueueEvent(Event*);
// Called when a transaction is aborted.
@@ -205,7 +207,7 @@ class MODULES_EXPORT IDBTransaction final
const int64_t id_;
Member<IDBDatabase> database_;
Member<IDBOpenDBRequest> open_db_request_;
- const WebIDBTransactionMode mode_;
+ const mojom::IDBTransactionMode mode_;
// The names of the object stores that make up this transaction's scope.
//
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction_test.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction_test.cc
index 6e0e414b36f..075397815ed 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction_test.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_transaction_test.cc
@@ -98,7 +98,7 @@ class IDBTransactionTest : public testing::Test {
HashSet<String> transaction_scope = {"store"};
transaction_ = IDBTransaction::CreateNonVersionChange(
scope.GetScriptState(), kTransactionId, transaction_scope,
- kWebIDBTransactionModeReadOnly, db_.Get());
+ mojom::IDBTransactionMode::ReadOnly, db_.Get());
IDBKeyPath store_key_path("primaryKey");
scoped_refptr<IDBObjectStoreMetadata> store_metadata = base::AdoptRef(
@@ -123,7 +123,7 @@ TEST_F(IDBTransactionTest, ContextDestroyedEarlyDeath) {
BuildTransaction(scope, std::move(backend));
Persistent<HeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
- new HeapHashSet<WeakMember<IDBTransaction>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<IDBTransaction>>>();
;
live_transactions->insert(transaction_);
@@ -159,7 +159,7 @@ TEST_F(IDBTransactionTest, ContextDestroyedAfterDone) {
BuildTransaction(scope, std::move(backend));
Persistent<HeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
- new HeapHashSet<WeakMember<IDBTransaction>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<IDBTransaction>>>();
;
live_transactions->insert(transaction_);
@@ -201,7 +201,7 @@ TEST_F(IDBTransactionTest, ContextDestroyedWithQueuedResult) {
BuildTransaction(scope, std::move(backend));
Persistent<HeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
- new HeapHashSet<WeakMember<IDBTransaction>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<IDBTransaction>>>();
;
live_transactions->insert(transaction_);
@@ -240,7 +240,7 @@ TEST_F(IDBTransactionTest, ContextDestroyedWithTwoQueuedResults) {
BuildTransaction(scope, std::move(backend));
Persistent<HeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
- new HeapHashSet<WeakMember<IDBTransaction>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<IDBTransaction>>>();
;
live_transactions->insert(transaction_);
@@ -286,7 +286,7 @@ TEST_F(IDBTransactionTest, DocumentShutdownWithQueuedAndBlockedResults) {
BuildTransaction(scope, std::move(backend));
Persistent<HeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
- new HeapHashSet<WeakMember<IDBTransaction>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<IDBTransaction>>>();
;
live_transactions->insert(transaction_);
@@ -331,7 +331,7 @@ TEST_F(IDBTransactionTest, TransactionFinish) {
BuildTransaction(scope, std::move(backend));
Persistent<HeapHashSet<WeakMember<IDBTransaction>>> live_transactions =
- new HeapHashSet<WeakMember<IDBTransaction>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<IDBTransaction>>>();
;
live_transactions->insert(transaction_);
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h
index 5ae34bdef89..b2ff10e3127 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_value_wrapping.h
@@ -40,7 +40,7 @@ const base::Feature kIndexedDBLargeValueWrapping{
// This may be necessary when extracting the primary key and/or index keys
// for the serialized value.
// 2) Wrapping - DoneCloning() transitions the instance to an internal
-// reprensetation optimized for wrapping via WrapIfBiggerThan().
+// representation optimized for wrapping via WrapIfBiggerThan().
// 3) Reading results - After any desired wrapping is performed, the Take*()
// methods yield the serialized value components passed to the backing store.
// To avoid unnecessary copies, the Take*() methods move out parts of the
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.cc b/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.cc
index 8af46e19e37..e82a9d7f26f 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.cc
@@ -30,13 +30,13 @@
namespace blink {
IDBVersionChangeEvent::IDBVersionChangeEvent()
- : data_loss_(kWebIDBDataLossNone) {}
+ : data_loss_(mojom::IDBDataLoss::None) {}
IDBVersionChangeEvent::IDBVersionChangeEvent(
const AtomicString& event_type,
unsigned long long old_version,
const base::Optional<unsigned long long>& new_version,
- WebIDBDataLoss data_loss,
+ mojom::IDBDataLoss data_loss,
const String& data_loss_message)
: Event(event_type, Bubbles::kNo, Cancelable::kNo),
old_version_(old_version),
@@ -46,14 +46,14 @@ IDBVersionChangeEvent::IDBVersionChangeEvent(
IDBVersionChangeEvent::IDBVersionChangeEvent(
const AtomicString& event_type,
- const IDBVersionChangeEventInit& initializer)
+ const IDBVersionChangeEventInit* initializer)
: Event(event_type, Bubbles::kNo, Cancelable::kNo),
- old_version_(initializer.oldVersion()),
- data_loss_(kWebIDBDataLossNone) {
- if (initializer.hasNewVersion())
- new_version_ = initializer.newVersion();
- if (initializer.dataLoss() == "total")
- data_loss_ = kWebIDBDataLossTotal;
+ old_version_(initializer->oldVersion()),
+ data_loss_(mojom::IDBDataLoss::None) {
+ if (initializer->hasNewVersion())
+ new_version_ = initializer->newVersion();
+ if (initializer->dataLoss() == "total")
+ data_loss_ = mojom::IDBDataLoss::Total;
}
unsigned long long IDBVersionChangeEvent::newVersion(bool& is_null) const {
@@ -62,13 +62,13 @@ unsigned long long IDBVersionChangeEvent::newVersion(bool& is_null) const {
}
const AtomicString& IDBVersionChangeEvent::dataLoss() const {
- if (data_loss_ == kWebIDBDataLossTotal)
- return IndexedDBNames::total;
- return IndexedDBNames::none;
+ if (data_loss_ == mojom::IDBDataLoss::Total)
+ return indexed_db_names::kTotal;
+ return indexed_db_names::kNone;
}
const AtomicString& IDBVersionChangeEvent::InterfaceName() const {
- return EventNames::IDBVersionChangeEvent;
+ return event_interface_names::kIDBVersionChangeEvent;
}
void IDBVersionChangeEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h b/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h
index f3a15b9c5e6..70c5e1d384e 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/idb_version_change_event.h
@@ -28,6 +28,7 @@
#include "base/optional.h"
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/modules/event_modules.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_any.h"
@@ -41,22 +42,33 @@ class IDBVersionChangeEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static IDBVersionChangeEvent* Create() { return new IDBVersionChangeEvent(); }
+ static IDBVersionChangeEvent* Create() {
+ return MakeGarbageCollected<IDBVersionChangeEvent>();
+ }
static IDBVersionChangeEvent* Create(
const AtomicString& event_type,
unsigned long long old_version,
const base::Optional<unsigned long long>& new_version,
- WebIDBDataLoss data_loss = kWebIDBDataLossNone,
+ mojom::IDBDataLoss data_loss = mojom::IDBDataLoss::None,
const String& data_loss_message = String()) {
- return new IDBVersionChangeEvent(event_type, old_version, new_version,
- data_loss, data_loss_message);
+ return MakeGarbageCollected<IDBVersionChangeEvent>(
+ event_type, old_version, new_version, data_loss, data_loss_message);
}
static IDBVersionChangeEvent* Create(
const AtomicString& event_type,
- const IDBVersionChangeEventInit& initializer) {
- return new IDBVersionChangeEvent(event_type, initializer);
+ const IDBVersionChangeEventInit* initializer) {
+ return MakeGarbageCollected<IDBVersionChangeEvent>(event_type, initializer);
}
+ IDBVersionChangeEvent();
+ IDBVersionChangeEvent(const AtomicString& event_type,
+ unsigned long long old_version,
+ const base::Optional<unsigned long long>& new_version,
+ mojom::IDBDataLoss,
+ const String& data_loss);
+ IDBVersionChangeEvent(const AtomicString& event_type,
+ const IDBVersionChangeEventInit*);
+
unsigned long long oldVersion() const { return old_version_; }
unsigned long long newVersion(bool& is_null) const;
@@ -68,18 +80,9 @@ class IDBVersionChangeEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- IDBVersionChangeEvent();
- IDBVersionChangeEvent(const AtomicString& event_type,
- unsigned long long old_version,
- const base::Optional<unsigned long long>& new_version,
- WebIDBDataLoss,
- const String& data_loss);
- IDBVersionChangeEvent(const AtomicString& event_type,
- const IDBVersionChangeEventInit&);
-
unsigned long long old_version_;
base::Optional<unsigned long long> new_version_;
- WebIDBDataLoss data_loss_;
+ mojom::IDBDataLoss data_loss_;
String data_loss_message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db.h b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db.h
index a93def4e070..3a9847824cd 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db.h
@@ -28,11 +28,11 @@
namespace blink {
-namespace IndexedDB {
+namespace indexed_db {
enum CursorType { kCursorKeyAndValue = 0, kCursorKeyOnly };
-} // namespace IndexedDB
+} // namespace indexed_db
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink.typemap b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink.typemap
new file mode 100644
index 00000000000..fd306fa458d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink.typemap
@@ -0,0 +1,35 @@
+# Copyright 2018 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+mojom = "//third_party/blink/public/mojom/indexeddb/indexeddb.mojom"
+public_headers = [
+ "//third_party/blink/public/common/indexeddb/web_idb_types.h",
+ "//third_party/blink/public/platform/modules/indexeddb/web_idb_key.h",
+ "//third_party/blink/public/platform/modules/indexeddb/web_idb_key_path.h",
+ "//third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h",
+ "//third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h",
+ "//third_party/blink/public/platform/modules/indexeddb/web_idb_name_and_version.h",
+ "//third_party/blink/renderer/modules/indexeddb/idb_key_range.h",
+]
+traits_headers = [
+ "//mojo/public/cpp/base/string16_mojom_traits.h",
+ "//mojo/public/cpp/bindings/array_traits_web_vector.h",
+ "//mojo/public/cpp/bindings/array_traits_wtf_vector.h",
+ "//third_party/blink/public/common/indexeddb/indexed_db_default_mojom_traits.h",
+ "//third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.h",
+ "//third_party/blink/renderer/platform/mojo/string16_mojom_traits.h",
+]
+deps = [
+ "//mojo/public/cpp/bindings",
+ "//third_party/blink/renderer/platform/wtf",
+]
+type_mappings = [
+ "blink.mojom.IDBDatabaseMetadata=::blink::WebIDBMetadata",
+ "blink.mojom.IDBIndexKeys=::blink::WebIDBIndexKeys",
+ "blink.mojom.IDBIndexMetadata=::blink::WebIDBMetadata::Index",
+ "blink.mojom.IDBKey=::blink::WebIDBKey[move_only]",
+ "blink.mojom.IDBKeyPath=::blink::WebIDBKeyPath",
+ "blink.mojom.IDBKeyRange=::blink::WebIDBKeyRange",
+ "blink.mojom.IDBObjectStoreMetadata=::blink::WebIDBMetadata::ObjectStore",
+]
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.cc b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.cc
new file mode 100644
index 00000000000..280c6462210
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.cc
@@ -0,0 +1,291 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.h"
+
+#include "base/stl_util.h"
+#include "mojo/public/cpp/bindings/array_traits_web_vector.h"
+#include "mojo/public/cpp/bindings/array_traits_wtf_vector.h"
+#include "third_party/blink/public/common/indexeddb/indexed_db_default_mojom_traits.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key_range.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_metadata.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/platform/mojo/string16_mojom_traits.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+using blink::mojom::IDBCursorDirection;
+using blink::mojom::IDBDataLoss;
+using blink::mojom::IDBOperationType;
+
+namespace mojo {
+
+// static
+bool StructTraits<
+ blink::mojom::IDBDatabaseMetadataDataView,
+ blink::WebIDBMetadata>::Read(blink::mojom::IDBDatabaseMetadataDataView data,
+ blink::WebIDBMetadata* out) {
+ out->id = data.id();
+ String name;
+ if (!data.ReadName(&name))
+ return false;
+ out->name = name;
+ out->version = data.version();
+ out->max_object_store_id = data.max_object_store_id();
+ if (!data.ReadObjectStores(&out->object_stores))
+ return false;
+ return true;
+}
+
+// static
+bool StructTraits<blink::mojom::IDBIndexKeysDataView, blink::WebIDBIndexKeys>::
+ Read(blink::mojom::IDBIndexKeysDataView data, blink::WebIDBIndexKeys* out) {
+ out->first = data.index_id();
+ if (!data.ReadIndexKeys(&out->second))
+ return false;
+ return true;
+}
+
+// static
+bool StructTraits<blink::mojom::IDBIndexMetadataDataView,
+ blink::WebIDBMetadata::Index>::
+ Read(blink::mojom::IDBIndexMetadataDataView data,
+ blink::WebIDBMetadata::Index* out) {
+ out->id = data.id();
+ String name;
+ if (!data.ReadName(&name))
+ return false;
+ out->name = name;
+ if (!data.ReadKeyPath(&out->key_path))
+ return false;
+ out->unique = data.unique();
+ out->multi_entry = data.multi_entry();
+ return true;
+}
+
+// static
+blink::mojom::IDBKeyDataDataView::Tag
+UnionTraits<blink::mojom::IDBKeyDataDataView, blink::WebIDBKey>::GetTag(
+ const blink::WebIDBKey& key) {
+ switch (key.View().KeyType()) {
+ case blink::kWebIDBKeyTypeInvalid:
+ return blink::mojom::IDBKeyDataDataView::Tag::OTHER;
+ case blink::kWebIDBKeyTypeArray:
+ return blink::mojom::IDBKeyDataDataView::Tag::KEY_ARRAY;
+ case blink::kWebIDBKeyTypeBinary:
+ return blink::mojom::IDBKeyDataDataView::Tag::BINARY;
+ case blink::kWebIDBKeyTypeString:
+ return blink::mojom::IDBKeyDataDataView::Tag::STRING;
+ case blink::kWebIDBKeyTypeDate:
+ return blink::mojom::IDBKeyDataDataView::Tag::DATE;
+ case blink::kWebIDBKeyTypeNumber:
+ return blink::mojom::IDBKeyDataDataView::Tag::NUMBER;
+ case blink::kWebIDBKeyTypeNull:
+ return blink::mojom::IDBKeyDataDataView::Tag::OTHER;
+
+ // Not used, fall through to NOTREACHED.
+ case blink::kWebIDBKeyTypeMin:;
+ }
+ NOTREACHED();
+ return blink::mojom::IDBKeyDataDataView::Tag::OTHER;
+}
+
+// static
+bool UnionTraits<blink::mojom::IDBKeyDataDataView, blink::WebIDBKey>::Read(
+ blink::mojom::IDBKeyDataDataView data,
+ blink::WebIDBKey* out) {
+ switch (data.tag()) {
+ case blink::mojom::IDBKeyDataDataView::Tag::KEY_ARRAY: {
+ Vector<blink::WebIDBKey> array;
+ if (!data.ReadKeyArray(&array))
+ return false;
+ blink::WebVector<blink::WebIDBKey> webvector_array;
+ for (const auto& item : array) {
+ webvector_array.emplace_back(
+ blink::WebIDBKeyBuilder::Build(item.View()));
+ }
+ *out = blink::WebIDBKey::CreateArray(std::move(webvector_array));
+ return true;
+ }
+ case blink::mojom::IDBKeyDataDataView::Tag::BINARY: {
+ ArrayDataView<uint8_t> bytes;
+ data.GetBinaryDataView(&bytes);
+ *out = blink::WebIDBKey::CreateBinary(blink::WebData(
+ reinterpret_cast<const char*>(bytes.data()), bytes.size()));
+ return true;
+ }
+ case blink::mojom::IDBKeyDataDataView::Tag::STRING: {
+ String string;
+ if (!data.ReadString(&string))
+ return false;
+ *out = blink::WebIDBKey::CreateString(blink::WebString(string));
+ return true;
+ }
+ case blink::mojom::IDBKeyDataDataView::Tag::DATE:
+ *out = blink::WebIDBKey::CreateDate(data.date());
+ return true;
+ case blink::mojom::IDBKeyDataDataView::Tag::NUMBER:
+ *out = blink::WebIDBKey::CreateNumber(data.number());
+ return true;
+ case blink::mojom::IDBKeyDataDataView::Tag::OTHER:
+ switch (data.other()) {
+ case blink::mojom::IDBDatalessKeyType::Invalid:
+ *out = blink::WebIDBKey::CreateInvalid();
+ return true;
+ case blink::mojom::IDBDatalessKeyType::Null:
+ *out = blink::WebIDBKey::CreateNull();
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// static
+const blink::WebVector<blink::WebIDBKey>
+UnionTraits<blink::mojom::IDBKeyDataDataView, blink::WebIDBKey>::key_array(
+ const blink::WebIDBKey& key) {
+ const auto& array_view = key.View().ArrayView();
+ const size_t array_size = array_view.size();
+ Vector<blink::WebIDBKey> result;
+ result.ReserveInitialCapacity(SafeCast<wtf_size_t>(array_view.size()));
+ // |array_view| is of type WebIDBKeyArrayView which only implements size()
+ // and operator[]. Since it doesn't have other typical array functions, we
+ // must use an iterator-style for loop.
+ for (size_t i = 0; i < array_size; ++i)
+ result.emplace_back(blink::WebIDBKeyBuilder::Build(array_view[i]));
+ return result;
+}
+
+// static
+const Vector<uint8_t>
+UnionTraits<blink::mojom::IDBKeyDataDataView, blink::WebIDBKey>::binary(
+ const blink::WebIDBKey& key) {
+ const auto& data = key.View().Binary();
+ Vector<uint8_t> result;
+ result.ReserveInitialCapacity(SafeCast<wtf_size_t>(data.size()));
+ data.ForEachSegment([&result](const char* segment, size_t segment_size,
+ size_t segment_offset) {
+ const auto& segment_span = base::make_span(segment, segment + segment_size);
+ result.AppendRange(segment_span.begin(), segment_span.end());
+ return true;
+ });
+ return result;
+}
+
+// static
+const blink::WebIDBKey&
+StructTraits<blink::mojom::IDBKeyDataView, blink::WebIDBKey>::data(
+ const blink::WebIDBKey& key) {
+ return key;
+}
+
+// static
+bool StructTraits<blink::mojom::IDBKeyDataView, blink::WebIDBKey>::Read(
+ blink::mojom::IDBKeyDataView data,
+ blink::WebIDBKey* out) {
+ return data.ReadData(out);
+}
+
+// static
+blink::mojom::blink::IDBKeyPathDataPtr
+StructTraits<blink::mojom::IDBKeyPathDataView, blink::WebIDBKeyPath>::data(
+ const blink::WebIDBKeyPath& key_path) {
+ if (key_path.KeyPathType() == blink::kWebIDBKeyPathTypeNull)
+ return nullptr;
+
+ auto data = blink::mojom::blink::IDBKeyPathData::New();
+ switch (key_path.KeyPathType()) {
+ case blink::kWebIDBKeyPathTypeString: {
+ String key_path_string = key_path.String();
+ if (key_path_string.IsNull())
+ key_path_string = g_empty_string;
+ data->set_string(key_path_string);
+ return data;
+ }
+ case blink::kWebIDBKeyPathTypeArray: {
+ const auto& array = key_path.Array();
+ Vector<String> result;
+ result.ReserveInitialCapacity(SafeCast<wtf_size_t>(array.size()));
+ for (const auto& item : array)
+ result.push_back(item);
+ data->set_string_array(result);
+ return data;
+ }
+
+ case blink::kWebIDBKeyPathTypeNull:
+ break; // Not used, NOTREACHED.
+ }
+ NOTREACHED();
+ return data;
+}
+
+// static
+bool StructTraits<blink::mojom::IDBKeyPathDataView, blink::WebIDBKeyPath>::Read(
+ blink::mojom::IDBKeyPathDataView data,
+ blink::WebIDBKeyPath* out) {
+ blink::mojom::IDBKeyPathDataDataView data_view;
+ data.GetDataDataView(&data_view);
+
+ if (data_view.is_null()) {
+ *out = blink::WebIDBKeyPath();
+ return true;
+ }
+
+ switch (data_view.tag()) {
+ case blink::mojom::IDBKeyPathDataDataView::Tag::STRING: {
+ String string;
+ if (!data_view.ReadString(&string))
+ return false;
+ *out = blink::WebIDBKeyPath(blink::WebString(string));
+ return true;
+ }
+ case blink::mojom::IDBKeyPathDataDataView::Tag::STRING_ARRAY: {
+ Vector<String> array;
+ if (!data_view.ReadStringArray(&array))
+ return false;
+ *out = blink::WebIDBKeyPath(array);
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// static
+bool StructTraits<blink::mojom::IDBKeyRangeDataView, blink::WebIDBKeyRange>::
+ Read(blink::mojom::IDBKeyRangeDataView data, blink::WebIDBKeyRange* out) {
+ // TODO(cmp): Use WebIDBKey and WebIDBKeyRange directly.
+ blink::IndexedDBKey lower;
+ blink::IndexedDBKey upper;
+ if (!data.ReadLower(&lower) || !data.ReadUpper(&upper))
+ return false;
+
+ blink::IndexedDBKeyRange temp(lower, upper, data.lower_open(),
+ data.upper_open());
+ *out = blink::WebIDBKeyRangeBuilder::Build(temp);
+ return true;
+}
+
+// static
+bool StructTraits<blink::mojom::IDBObjectStoreMetadataDataView,
+ blink::WebIDBMetadata::ObjectStore>::
+ Read(blink::mojom::IDBObjectStoreMetadataDataView data,
+ blink::WebIDBMetadata::ObjectStore* out) {
+ out->id = data.id();
+ String name;
+ if (!data.ReadName(&name))
+ return false;
+ out->name = name;
+ if (!data.ReadKeyPath(&out->key_path))
+ return false;
+ out->auto_increment = data.auto_increment();
+ out->max_index_id = data.max_index_id();
+ if (!data.ReadIndexes(&out->indexes))
+ return false;
+ return true;
+}
+
+} // namespace mojo
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.h b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.h
new file mode 100644
index 00000000000..408631a1a40
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_blink_mojom_traits.h
@@ -0,0 +1,187 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_BLINK_MOJOM_TRAITS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_BLINK_MOJOM_TRAITS_H_
+
+#include <stdint.h>
+
+#include "third_party/blink/public/common/indexeddb/indexeddb_key.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key_range.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_metadata.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace mojo {
+
+template <>
+struct MODULES_EXPORT StructTraits<blink::mojom::IDBDatabaseMetadataDataView,
+ blink::WebIDBMetadata> {
+ static int64_t id(const blink::WebIDBMetadata& metadata) {
+ return metadata.id;
+ }
+ static WTF::String name(const blink::WebIDBMetadata& metadata) {
+ if (metadata.name.IsNull())
+ return g_empty_string;
+ return metadata.name;
+ }
+ static int64_t version(const blink::WebIDBMetadata& metadata) {
+ return metadata.version;
+ }
+ static int64_t max_object_store_id(const blink::WebIDBMetadata& metadata) {
+ return metadata.max_object_store_id;
+ }
+ static const blink::WebVector<blink::WebIDBMetadata::ObjectStore>&
+ object_stores(const blink::WebIDBMetadata& metadata) {
+ return metadata.object_stores;
+ }
+ static bool Read(blink::mojom::IDBDatabaseMetadataDataView data,
+ blink::WebIDBMetadata* out);
+};
+
+template <>
+struct MODULES_EXPORT
+ StructTraits<blink::mojom::IDBIndexKeysDataView, blink::WebIDBIndexKeys> {
+ static int64_t index_id(const blink::WebIDBIndexKeys& index_keys) {
+ return index_keys.first;
+ }
+ static const blink::WebVector<blink::WebIDBKey>& index_keys(
+ const blink::WebIDBIndexKeys& index_keys) {
+ return index_keys.second;
+ }
+ static bool Read(blink::mojom::IDBIndexKeysDataView data,
+ blink::WebIDBIndexKeys* out);
+};
+
+template <>
+struct MODULES_EXPORT StructTraits<blink::mojom::IDBIndexMetadataDataView,
+ blink::WebIDBMetadata::Index> {
+ static int64_t id(const blink::WebIDBMetadata::Index& metadata) {
+ return metadata.id;
+ }
+ static WTF::String name(const blink::WebIDBMetadata::Index& metadata) {
+ if (metadata.name.IsNull())
+ return g_empty_string;
+ return metadata.name;
+ }
+ static const blink::WebIDBKeyPath& key_path(
+ const blink::WebIDBMetadata::Index& metadata) {
+ return metadata.key_path;
+ }
+ static bool unique(const blink::WebIDBMetadata::Index& metadata) {
+ return metadata.unique;
+ }
+ static bool multi_entry(const blink::WebIDBMetadata::Index& metadata) {
+ return metadata.multi_entry;
+ }
+ static bool Read(blink::mojom::IDBIndexMetadataDataView data,
+ blink::WebIDBMetadata::Index* out);
+};
+
+template <>
+struct MODULES_EXPORT
+ UnionTraits<blink::mojom::IDBKeyDataDataView, blink::WebIDBKey> {
+ static blink::mojom::IDBKeyDataDataView::Tag GetTag(
+ const blink::WebIDBKey& key);
+ static bool Read(blink::mojom::IDBKeyDataDataView data,
+ blink::WebIDBKey* out);
+ static const blink::WebVector<blink::WebIDBKey> key_array(
+ const blink::WebIDBKey& key);
+ static const Vector<uint8_t> binary(const blink::WebIDBKey& key);
+ static const WTF::String string(const blink::WebIDBKey& key) {
+ String key_string = key.View().String();
+ if (key_string.IsNull())
+ key_string = g_empty_string;
+ return key_string;
+ }
+ static double date(const blink::WebIDBKey& key) { return key.View().Date(); }
+ static double number(const blink::WebIDBKey& key) {
+ return key.View().Number();
+ }
+ static blink::mojom::IDBDatalessKeyType other(const blink::WebIDBKey& key) {
+ switch (key.View().KeyType()) {
+ case blink::kWebIDBKeyTypeInvalid:
+ return blink::mojom::IDBDatalessKeyType::Invalid;
+ case blink::kWebIDBKeyTypeNull:
+ return blink::mojom::IDBDatalessKeyType::Null;
+ default:
+ NOTREACHED();
+ return blink::mojom::IDBDatalessKeyType::Invalid;
+ }
+ }
+};
+
+template <>
+struct MODULES_EXPORT
+ StructTraits<blink::mojom::IDBKeyDataView, blink::WebIDBKey> {
+ static const blink::WebIDBKey& data(const blink::WebIDBKey& key);
+ static bool Read(blink::mojom::IDBKeyDataView data, blink::WebIDBKey* out);
+};
+
+template <>
+struct MODULES_EXPORT
+ StructTraits<blink::mojom::IDBKeyPathDataView, blink::WebIDBKeyPath> {
+ static blink::mojom::blink::IDBKeyPathDataPtr data(
+ const blink::WebIDBKeyPath& key_path);
+ static bool Read(blink::mojom::IDBKeyPathDataView data,
+ blink::WebIDBKeyPath* out);
+};
+
+template <>
+struct MODULES_EXPORT
+ StructTraits<blink::mojom::IDBKeyRangeDataView, blink::WebIDBKeyRange> {
+ static blink::WebIDBKey lower(const blink::WebIDBKeyRange& key_range) {
+ return blink::WebIDBKeyBuilder::Build(key_range.Lower());
+ }
+ static blink::WebIDBKey upper(const blink::WebIDBKeyRange& key_range) {
+ return blink::WebIDBKeyBuilder::Build(key_range.Upper());
+ }
+ static bool lower_open(const blink::WebIDBKeyRange& key_range) {
+ return key_range.LowerOpen();
+ }
+ static bool upper_open(const blink::WebIDBKeyRange& key_range) {
+ return key_range.UpperOpen();
+ }
+ static bool Read(blink::mojom::IDBKeyRangeDataView data,
+ blink::WebIDBKeyRange* out);
+};
+
+template <>
+struct MODULES_EXPORT StructTraits<blink::mojom::IDBObjectStoreMetadataDataView,
+ blink::WebIDBMetadata::ObjectStore> {
+ static int64_t id(const blink::WebIDBMetadata::ObjectStore& metadata) {
+ return metadata.id;
+ }
+ static WTF::String name(const blink::WebIDBMetadata::ObjectStore& metadata) {
+ return metadata.name;
+ }
+ static const blink::WebIDBKeyPath& key_path(
+ const blink::WebIDBMetadata::ObjectStore& metadata) {
+ return metadata.key_path;
+ }
+ static bool auto_increment(
+ const blink::WebIDBMetadata::ObjectStore& metadata) {
+ return metadata.auto_increment;
+ }
+ static int64_t max_index_id(
+ const blink::WebIDBMetadata::ObjectStore& metadata) {
+ return metadata.max_index_id;
+ }
+ static const blink::WebVector<blink::WebIDBMetadata::Index>& indexes(
+ const blink::WebIDBMetadata::ObjectStore& metadata) {
+ return metadata.indexes;
+ }
+ static bool Read(blink::mojom::IDBObjectStoreMetadataDataView data,
+ blink::WebIDBMetadata::ObjectStore* out);
+};
+
+} // namespace mojo
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_BLINK_MOJOM_TRAITS_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.cc b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.cc
new file mode 100644
index 00000000000..360bdffd726
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.cc
@@ -0,0 +1,216 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h"
+
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_name_and_version.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h"
+
+using blink::IndexedDBDatabaseMetadata;
+using blink::WebBlobInfo;
+using blink::WebData;
+using blink::WebIDBCallbacks;
+using blink::WebIDBDatabase;
+using blink::WebIDBMetadata;
+using blink::WebIDBNameAndVersion;
+using blink::WebIDBValue;
+using blink::WebString;
+using blink::WebVector;
+using blink::mojom::blink::IDBDatabaseAssociatedPtrInfo;
+
+namespace blink {
+
+namespace {
+
+WebIDBValue ConvertReturnValue(const mojom::blink::IDBReturnValuePtr& value) {
+ if (!value)
+ return WebIDBValue(WebData(), WebVector<WebBlobInfo>());
+
+ WebIDBValue web_value = IndexedDBCallbacksImpl::ConvertValue(value->value);
+ web_value.SetInjectedPrimaryKey(value->primary_key, value->key_path);
+ return web_value;
+}
+
+WebIDBNameAndVersion ConvertNameVersion(
+ const mojom::blink::IDBNameAndVersionPtr& name_and_version) {
+ return WebIDBNameAndVersion(name_and_version->name,
+ name_and_version->version);
+}
+
+} // namespace
+
+// static
+WebIDBValue IndexedDBCallbacksImpl::ConvertValue(
+ const mojom::blink::IDBValuePtr& value) {
+ if (!value || value->bits.IsEmpty())
+ return WebIDBValue(WebData(), WebVector<WebBlobInfo>());
+
+ WebVector<WebBlobInfo> local_blob_info;
+ local_blob_info.reserve(value->blob_or_file_info.size());
+ for (const auto& info : value->blob_or_file_info) {
+ if (info->file) {
+ local_blob_info.emplace_back(
+ WebString(info->uuid), FilePathToWebString(info->file->path),
+ WebString(info->file->name), WebString(info->mime_type),
+ info->file->last_modified.ToDoubleT(), info->size,
+ info->blob.PassHandle());
+ } else {
+ local_blob_info.emplace_back(WebString(info->uuid),
+ WebString(info->mime_type), info->size,
+ info->blob.PassHandle());
+ }
+ }
+
+ // TODO(crbug.com/902498): Use mojom traits to map directly to WebData.
+ WebData web_data(reinterpret_cast<const char*>(value->bits.data()),
+ value->bits.size());
+ // Release value->bits std::vector.
+ value->bits.clear();
+ return WebIDBValue(std::move(web_data), std::move(local_blob_info));
+}
+
+IndexedDBCallbacksImpl::IndexedDBCallbacksImpl(
+ std::unique_ptr<WebIDBCallbacks> callbacks,
+ int64_t transaction_id,
+ const base::WeakPtr<WebIDBCursorImpl>& cursor)
+ : callbacks_(std::move(callbacks)),
+ cursor_(cursor),
+ transaction_id_(transaction_id) {}
+
+IndexedDBCallbacksImpl::~IndexedDBCallbacksImpl() = default;
+
+void IndexedDBCallbacksImpl::Error(int32_t code, const WTF::String& message) {
+ callbacks_->OnError(WebIDBDatabaseError(code, WebString(message)));
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessNamesAndVersionsList(
+ Vector<mojom::blink::IDBNameAndVersionPtr> names_and_versions) {
+ WebVector<WebIDBNameAndVersion> web_names_and_versions;
+ web_names_and_versions.reserve(names_and_versions.size());
+ for (const mojom::blink::IDBNameAndVersionPtr& name_version :
+ names_and_versions)
+ web_names_and_versions.emplace_back(ConvertNameVersion(name_version));
+ callbacks_->OnSuccess(web_names_and_versions);
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessStringList(const Vector<String>& value) {
+ WebVector<WebString> web_value(value.size());
+ std::transform(value.begin(), value.end(), web_value.begin(),
+ [](const WTF::String& s) { return WebString(s); });
+ callbacks_->OnSuccess(web_value);
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::Blocked(int64_t existing_version) {
+ callbacks_->OnBlocked(existing_version);
+ // Not resetting |callbacks_|. In this instance we will have to forward at
+ // least one other call in the set OnUpgradeNeeded() / OnSuccess() /
+ // OnError().
+}
+
+void IndexedDBCallbacksImpl::UpgradeNeeded(
+ IDBDatabaseAssociatedPtrInfo database_info,
+ int64_t old_version,
+ mojom::IDBDataLoss data_loss,
+ const String& data_loss_message,
+ const WebIDBMetadata& web_metadata) {
+ WebIDBDatabase* database = new WebIDBDatabaseImpl(std::move(database_info));
+ callbacks_->OnUpgradeNeeded(old_version, database, web_metadata, data_loss,
+ WebString(data_loss_message));
+ // Not resetting |callbacks_|. In this instance we will have to forward at
+ // least one other call in the set OnSuccess() / OnError().
+}
+
+void IndexedDBCallbacksImpl::SuccessDatabase(
+ IDBDatabaseAssociatedPtrInfo database_info,
+ const WebIDBMetadata& web_metadata) {
+ WebIDBDatabase* database = nullptr;
+ if (database_info.is_valid())
+ database = new WebIDBDatabaseImpl(std::move(database_info));
+
+ callbacks_->OnSuccess(database, web_metadata);
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessCursor(
+ mojom::blink::IDBCursorAssociatedPtrInfo cursor_info,
+ WebIDBKey key,
+ WebIDBKey primary_key,
+ mojom::blink::IDBValuePtr value) {
+ WebIDBCursorImpl* cursor =
+ new WebIDBCursorImpl(std::move(cursor_info), transaction_id_);
+ callbacks_->OnSuccess(cursor, std::move(key), std::move(primary_key),
+ ConvertValue(value));
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessValue(
+ mojom::blink::IDBReturnValuePtr value) {
+ callbacks_->OnSuccess(ConvertReturnValue(value));
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessCursorContinue(
+ WebIDBKey key,
+ WebIDBKey primary_key,
+ mojom::blink::IDBValuePtr value) {
+ callbacks_->OnSuccess(std::move(key), std::move(primary_key),
+ ConvertValue(value));
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessCursorPrefetch(
+ Vector<WebIDBKey> keys,
+ Vector<WebIDBKey> primary_keys,
+ Vector<mojom::blink::IDBValuePtr> values) {
+ Vector<WebIDBValue> web_values;
+ web_values.ReserveInitialCapacity(values.size());
+ for (const mojom::blink::IDBValuePtr& value : values)
+ web_values.emplace_back(ConvertValue(value));
+
+ if (cursor_) {
+ cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys),
+ std::move(web_values));
+ cursor_->CachedContinue(callbacks_.get());
+ }
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessArray(
+ Vector<mojom::blink::IDBReturnValuePtr> values) {
+ WebVector<WebIDBValue> web_values;
+ web_values.reserve(values.size());
+ for (const mojom::blink::IDBReturnValuePtr& value : values)
+ web_values.emplace_back(ConvertReturnValue(value));
+ callbacks_->OnSuccess(std::move(web_values));
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessKey(WebIDBKey key) {
+ callbacks_->OnSuccess(std::move(key));
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::SuccessInteger(int64_t value) {
+ callbacks_->OnSuccess(value);
+ callbacks_.reset();
+}
+
+void IndexedDBCallbacksImpl::Success() {
+ callbacks_->OnSuccess();
+ callbacks_.reset();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h
new file mode 100644
index 00000000000..efbaeb80604
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_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 THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_CALLBACKS_IMPL_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_CALLBACKS_IMPL_H_
+
+#include <stdint.h>
+
+#include <memory>
+
+#include "base/memory/scoped_refptr.h"
+#include "base/memory/weak_ptr.h"
+#include "mojo/public/cpp/bindings/associated_binding.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_metadata.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+
+namespace blink {
+
+class WebIDBCallbacks;
+class WebIDBCursorImpl;
+class WebIDBValue;
+
+// Implements the child-process end of the pipe used to deliver callbacks.
+// |callback_runner_| is used to post tasks back to the thread which owns the
+// blink::WebIDBCallbacks.
+class IndexedDBCallbacksImpl : public mojom::blink::IDBCallbacks {
+ public:
+ // |kNoTransaction| is used as the default transaction ID when instantiating
+ // an IndexedDBCallbacksImpl instance. See web_idb_factory_impl.cc for those
+ // cases.
+ enum : int64_t { kNoTransaction = -1 };
+
+ static WebIDBValue ConvertValue(const mojom::blink::IDBValuePtr& value);
+
+ IndexedDBCallbacksImpl(std::unique_ptr<WebIDBCallbacks> callbacks,
+ int64_t transaction_id,
+ const base::WeakPtr<WebIDBCursorImpl>& cursor);
+ ~IndexedDBCallbacksImpl() override;
+
+ // mojom::blink::IDBCallbacks implementation:
+ void Error(int32_t code, const String& message) override;
+ void SuccessNamesAndVersionsList(
+ Vector<mojom::blink::IDBNameAndVersionPtr> names_and_versions) override;
+ void SuccessStringList(const Vector<String>& value) override;
+ void Blocked(int64_t existing_version) override;
+ void UpgradeNeeded(mojom::blink::IDBDatabaseAssociatedPtrInfo database_info,
+ int64_t old_version,
+ mojom::IDBDataLoss data_loss,
+ const String& data_loss_message,
+ const WebIDBMetadata& metadata) override;
+ void SuccessDatabase(mojom::blink::IDBDatabaseAssociatedPtrInfo database_info,
+ const WebIDBMetadata& metadata) override;
+ void SuccessCursor(mojom::blink::IDBCursorAssociatedPtrInfo cursor,
+ WebIDBKey key,
+ WebIDBKey primary_key,
+ mojom::blink::IDBValuePtr value) override;
+ void SuccessValue(mojom::blink::IDBReturnValuePtr value) override;
+ void SuccessCursorContinue(WebIDBKey key,
+ WebIDBKey primary_key,
+ mojom::blink::IDBValuePtr value) override;
+ void SuccessCursorPrefetch(Vector<WebIDBKey> keys,
+ Vector<WebIDBKey> primary_keys,
+ Vector<mojom::blink::IDBValuePtr> values) override;
+ void SuccessArray(Vector<mojom::blink::IDBReturnValuePtr> values) override;
+ void SuccessKey(WebIDBKey key) override;
+ void SuccessInteger(int64_t value) override;
+ void Success() override;
+
+ private:
+ scoped_refptr<base::SingleThreadTaskRunner> callback_runner_;
+ std::unique_ptr<WebIDBCallbacks> callbacks_;
+ base::WeakPtr<WebIDBCursorImpl> cursor_;
+ int64_t transaction_id_;
+
+ DISALLOW_COPY_AND_ASSIGN(IndexedDBCallbacksImpl);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_CALLBACKS_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.cc b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.cc
index 40640a0a548..f2f37856b38 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.cc
@@ -4,11 +4,11 @@
#include "third_party/blink/renderer/modules/indexeddb/indexed_db_client.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/workers/worker_clients.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
@@ -18,11 +18,11 @@
namespace blink {
IndexedDBClient* IndexedDBClient::Create(LocalFrame& frame) {
- return new IndexedDBClient(frame);
+ return MakeGarbageCollected<IndexedDBClient>(frame);
}
IndexedDBClient* IndexedDBClient::Create(WorkerClients& worker_clients) {
- return new IndexedDBClient(worker_clients);
+ return MakeGarbageCollected<IndexedDBClient>(worker_clients);
}
IndexedDBClient::IndexedDBClient(LocalFrame& frame)
@@ -36,13 +36,12 @@ IndexedDBClient* IndexedDBClient::From(ExecutionContext* context) {
return Supplement<LocalFrame>::From<IndexedDBClient>(document->GetFrame());
}
- WorkerClients* clients = ToWorkerGlobalScope(*context).Clients();
+ WorkerClients* clients = To<WorkerGlobalScope>(*context).Clients();
DCHECK(clients);
return Supplement<WorkerClients>::From<IndexedDBClient>(clients);
}
-bool IndexedDBClient::AllowIndexedDB(ExecutionContext* context,
- const String& name) {
+bool IndexedDBClient::AllowIndexedDB(ExecutionContext* context) {
DCHECK(context->IsContextThread());
SECURITY_DCHECK(context->IsDocument() || context->IsWorkerGlobalScope());
@@ -50,14 +49,16 @@ bool IndexedDBClient::AllowIndexedDB(ExecutionContext* context,
LocalFrame* frame = document->GetFrame();
if (!frame)
return false;
- DCHECK(frame->GetContentSettingsClient());
- return frame->GetContentSettingsClient()->AllowIndexedDB(
- name, context->GetSecurityOrigin());
+ if (auto* settings_client = frame->GetContentSettingsClient()) {
+ return settings_client->AllowIndexedDB(
+ WebSecurityOrigin(context->GetSecurityOrigin()));
+ }
+ return true;
}
- WorkerGlobalScope& worker_global_scope = *ToWorkerGlobalScope(context);
+ WorkerGlobalScope& worker_global_scope = *To<WorkerGlobalScope>(context);
return WorkerContentSettingsClient::From(worker_global_scope)
- ->AllowIndexedDB(name);
+ ->AllowIndexedDB();
}
// static
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.h b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.h
index e34ad57b346..296e954d87e 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_client.h
@@ -55,16 +55,15 @@ class IndexedDBClient : public GarbageCollected<IndexedDBClient>,
static IndexedDBClient* Create(LocalFrame&);
static IndexedDBClient* Create(WorkerClients&);
+ explicit IndexedDBClient(LocalFrame&);
+ explicit IndexedDBClient(WorkerClients&);
+
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override { return "IndexedDBClient"; }
- bool AllowIndexedDB(ExecutionContext*, const String& name);
+ bool AllowIndexedDB(ExecutionContext*);
static IndexedDBClient* From(ExecutionContext*);
-
- private:
- explicit IndexedDBClient(LocalFrame&);
- explicit IndexedDBClient(WorkerClients&);
};
void ProvideIndexedDBClientTo(LocalFrame&, IndexedDBClient*);
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.cc b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.cc
new file mode 100644
index 00000000000..1149fab7b61
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.cc
@@ -0,0 +1,80 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h"
+
+#include <unordered_map>
+#include <utility>
+
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_observation.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h"
+
+using blink::WebVector;
+using blink::WebIDBDatabaseCallbacks;
+using blink::WebIDBObservation;
+
+namespace blink {
+
+IndexedDBDatabaseCallbacksImpl::IndexedDBDatabaseCallbacksImpl(
+ std::unique_ptr<WebIDBDatabaseCallbacks> callbacks)
+ : callbacks_(std::move(callbacks)) {}
+
+IndexedDBDatabaseCallbacksImpl::~IndexedDBDatabaseCallbacksImpl() = default;
+
+void IndexedDBDatabaseCallbacksImpl::ForcedClose() {
+ callbacks_->OnForcedClose();
+}
+
+void IndexedDBDatabaseCallbacksImpl::VersionChange(int64_t old_version,
+ int64_t new_version) {
+ callbacks_->OnVersionChange(old_version, new_version);
+}
+
+void IndexedDBDatabaseCallbacksImpl::Abort(int64_t transaction_id,
+ int32_t code,
+ const String& message) {
+ callbacks_->OnAbort(transaction_id,
+ blink::WebIDBDatabaseError(code, message));
+}
+
+void IndexedDBDatabaseCallbacksImpl::Complete(int64_t transaction_id) {
+ callbacks_->OnComplete(transaction_id);
+}
+
+void IndexedDBDatabaseCallbacksImpl::Changes(
+ mojom::blink::IDBObserverChangesPtr changes) {
+ WebVector<WebIDBObservation> web_observations;
+ web_observations.reserve(changes->observations.size());
+ for (const auto& observation : changes->observations) {
+ web_observations.emplace_back(
+ observation->object_store_id, observation->type, observation->key_range,
+ IndexedDBCallbacksImpl::ConvertValue(observation->value));
+ }
+
+ std::unordered_map<int32_t, WebVector<int32_t>> observation_index_map;
+ for (const auto& observation_pair : changes->observation_index_map) {
+ observation_index_map[observation_pair.key] =
+ WebVector<int32_t>(observation_pair.value);
+ }
+
+ std::unordered_map<int32_t, std::pair<int64_t, WebVector<int64_t>>>
+ observer_transactions;
+ for (const auto& transaction_pair : changes->transaction_map) {
+ // Moving an int64_t is rather silly. Sadly, std::make_pair's overloads
+ // accept either two rvalue arguments, or none.
+ observer_transactions[transaction_pair.key] =
+ std::make_pair<int64_t, Vector<int64_t>>(
+ std::move(transaction_pair.value->id),
+ std::move(transaction_pair.value->scope));
+ }
+
+ callbacks_->OnChanges(observation_index_map, std::move(web_observations),
+ observer_transactions);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h
new file mode 100644
index 00000000000..702ea69e5ad
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h
@@ -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.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DATABASE_CALLBACKS_IMPL_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DATABASE_CALLBACKS_IMPL_H_
+
+#include <stdint.h>
+
+#include <memory>
+
+#include "base/single_thread_task_runner.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+
+namespace blink {
+class WebIDBDatabaseCallbacks;
+
+class IndexedDBDatabaseCallbacksImpl
+ : public mojom::blink::IDBDatabaseCallbacks {
+ public:
+ explicit IndexedDBDatabaseCallbacksImpl(
+ std::unique_ptr<WebIDBDatabaseCallbacks> callbacks);
+ ~IndexedDBDatabaseCallbacksImpl() override;
+
+ // mojom::blink::IDBDatabaseCallbacks implementation
+ void ForcedClose() override;
+ void VersionChange(int64_t old_version, int64_t new_version) override;
+ void Abort(int64_t transaction_id,
+ int32_t code,
+ const WTF::String& message) override;
+ void Complete(int64_t transaction_id) override;
+ void Changes(mojom::blink::IDBObserverChangesPtr changes) override;
+
+ private:
+ std::unique_ptr<WebIDBDatabaseCallbacks> callbacks_;
+
+ DISALLOW_COPY_AND_ASSIGN(IndexedDBDatabaseCallbacksImpl);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DATABASE_CALLBACKS_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.cc b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.cc
new file mode 100644
index 00000000000..84198c49edf
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.cc
@@ -0,0 +1,49 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h"
+
+#include <utility>
+
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_observation.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h"
+
+namespace blink {
+// static
+IndexedDBDispatcher* IndexedDBDispatcher::GetInstanceForCurrentThread() {
+ DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<IndexedDBDispatcher>,
+ thread_specific_instance, ());
+ return thread_specific_instance;
+}
+
+IndexedDBDispatcher::IndexedDBDispatcher() = default;
+
+// static
+void IndexedDBDispatcher::RegisterCursor(WebIDBCursorImpl* cursor) {
+ IndexedDBDispatcher* this_ptr = GetInstanceForCurrentThread();
+ DCHECK(!this_ptr->cursors_.Contains(cursor));
+ this_ptr->cursors_.insert(cursor);
+}
+
+// static
+void IndexedDBDispatcher::UnregisterCursor(WebIDBCursorImpl* cursor) {
+ IndexedDBDispatcher* this_ptr = GetInstanceForCurrentThread();
+ DCHECK(this_ptr->cursors_.Contains(cursor));
+ this_ptr->cursors_.erase(cursor);
+}
+
+// static
+void IndexedDBDispatcher::ResetCursorPrefetchCaches(
+ int64_t transaction_id,
+ WebIDBCursorImpl* except_cursor) {
+ IndexedDBDispatcher* this_ptr = GetInstanceForCurrentThread();
+ for (WebIDBCursorImpl* cursor : this_ptr->cursors_) {
+ if (cursor != except_cursor && cursor->transaction_id() == transaction_id)
+ cursor->ResetPrefetchCache();
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h
new file mode 100644
index 00000000000..906d7068018
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h
@@ -0,0 +1,55 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DISPATCHER_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DISPATCHER_H_
+
+#include <stdint.h>
+
+#include "base/gtest_prod_util.h"
+#include "base/macros.h"
+#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+#include "third_party/blink/renderer/platform/wtf/hash_set.h"
+#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
+
+namespace blink {
+class WebIDBCursorImpl;
+
+// Handle the indexed db related communication for this context thread - the
+// main thread and each worker thread have their own copies.
+class MODULES_EXPORT IndexedDBDispatcher {
+ public:
+ static void RegisterCursor(WebIDBCursorImpl* cursor);
+ static void UnregisterCursor(WebIDBCursorImpl* cursor);
+
+ // Reset cursor prefetch caches for all cursors except |except_cursor|.
+ // In most callers, |except_cursor| is passed as nullptr, causing all cursors
+ // to have their prefetch cache to be reset. In 2 WebIDBCursorImpl callers,
+ // specifically from |Advance| and |CursorContinue|, these want to reset all
+ // cursor prefetch caches except the cursor the calls are running from. They
+ // get that behavior by passing |this| to |ResetCursorPrefetchCaches| which
+ // skips calling |ResetPrefetchCache| on them.
+ static void ResetCursorPrefetchCaches(int64_t transaction_id,
+ WebIDBCursorImpl* except_cursor);
+
+ private:
+ friend class WTF::ThreadSpecific<IndexedDBDispatcher>;
+
+ static IndexedDBDispatcher* GetInstanceForCurrentThread();
+
+ IndexedDBDispatcher();
+
+ FRIEND_TEST_ALL_PREFIXES(IndexedDBDispatcherTest, CursorReset);
+ FRIEND_TEST_ALL_PREFIXES(IndexedDBDispatcherTest, CursorTransactionId);
+
+ WTF::HashSet<WebIDBCursorImpl*> cursors_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DISPATCHER_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_names.json5 b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_names.json5
index 1f501ec886e..edab532e48d 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_names.json5
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/indexed_db_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "IndexedDB",
+ namespace: "indexed_db_names",
},
data: [
@@ -30,10 +30,7 @@
// https://github.com/WICG/indexed-db-observers/blob/gh-pages/EXPLAINER.md//records
"add",
"put",
- {
- name: "delete",
- Symbol: "kDelete",
- },
+ "delete",
"clear",
],
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc b/chromium/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc
index 00ff7182645..5cf1906a645 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/inspector_indexed_db_agent.cc
@@ -34,7 +34,6 @@
#include <utility>
#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -59,6 +58,7 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_open_db_request.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_transaction.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
@@ -124,8 +124,8 @@ class GetDatabaseNamesCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
- if (event->type() != EventTypeNames::success) {
+ void Invoke(ExecutionContext*, Event* event) override {
+ if (event->type() != event_type_names::kSuccess) {
request_callback_->sendFailure(Response::Error("Unexpected event type."));
return;
}
@@ -173,8 +173,8 @@ class DeleteCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
- if (event->type() != EventTypeNames::success) {
+ void Invoke(ExecutionContext*, Event* event) override {
+ if (event->type() != event_type_names::kSuccess) {
request_callback_->sendFailure(
Response::Error("Failed to delete database."));
return;
@@ -244,9 +244,9 @@ class ExecutableWithDatabase
SendFailure(Response::Error("Could not open database."));
return;
}
- idb_open_db_request->addEventListener(EventTypeNames::upgradeneeded,
+ idb_open_db_request->addEventListener(event_type_names::kUpgradeneeded,
upgrade_callback, false);
- idb_open_db_request->addEventListener(EventTypeNames::success,
+ idb_open_db_request->addEventListener(event_type_names::kSuccess,
open_callback, false);
}
@@ -270,8 +270,8 @@ class OpenDatabaseCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext* context, Event* event) override {
- if (event->type() != EventTypeNames::success) {
+ void Invoke(ExecutionContext* context, Event* event) override {
+ if (event->type() != event_type_names::kSuccess) {
executable_with_database_->GetRequestCallback()->sendFailure(
Response::Error("Unexpected event type."));
return;
@@ -323,8 +323,8 @@ class UpgradeDatabaseCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext* context, Event* event) override {
- if (event->type() != EventTypeNames::upgradeneeded) {
+ void Invoke(ExecutionContext* context, Event* event) override {
+ if (event->type() != event_type_names::kUpgradeneeded) {
executable_with_database_->GetRequestCallback()->sendFailure(
Response::Error("Unexpected event type."));
return;
@@ -354,7 +354,7 @@ IDBTransaction* TransactionForDatabase(
ScriptState* script_state,
IDBDatabase* idb_database,
const String& object_store_name,
- const String& mode = IndexedDBNames::readonly) {
+ const String& mode = indexed_db_names::kReadonly) {
DummyExceptionStateForTesting exception_state;
StringOrStringSequence scope;
scope.SetString(object_store_name);
@@ -561,8 +561,8 @@ class OpenCursorCallback final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
- if (event->type() != EventTypeNames::success) {
+ void Invoke(ExecutionContext*, Event* event) override {
+ if (event->type() != event_type_names::kSuccess) {
request_callback_->sendFailure(Response::Error("Unexpected event type."));
return;
}
@@ -704,16 +704,16 @@ class DataLoader final : public ExecutableWithDatabase<RequestDataCallback> {
}
idb_request = idb_index->openCursor(script_state, idb_key_range_.Get(),
- kWebIDBCursorDirectionNext);
+ mojom::IDBCursorDirection::Next);
} else {
idb_request = idb_object_store->openCursor(
- script_state, idb_key_range_.Get(), kWebIDBCursorDirectionNext);
+ script_state, idb_key_range_.Get(), mojom::IDBCursorDirection::Next);
}
OpenCursorCallback* open_cursor_callback = OpenCursorCallback::Create(
v8_session_, script_state, std::move(request_callback_), skip_count_,
page_size_);
- idb_request->addEventListener(EventTypeNames::success, open_cursor_callback,
- false);
+ idb_request->addEventListener(event_type_names::kSuccess,
+ open_cursor_callback, false);
}
RequestDataCallback* GetRequestCallback() override {
@@ -811,7 +811,7 @@ void InspectorIndexedDBAgent::requestDatabaseNames(
return;
}
idb_request->addEventListener(
- EventTypeNames::success,
+ event_type_names::kSuccess,
GetDatabaseNamesCallback::Create(
std::move(request_callback),
document->GetSecurityOrigin()->ToRawString()),
@@ -861,17 +861,22 @@ class DeleteObjectStoreEntriesListener final : public EventListener {
public:
static DeleteObjectStoreEntriesListener* Create(
std::unique_ptr<DeleteObjectStoreEntriesCallback> request_callback) {
- return new DeleteObjectStoreEntriesListener(std::move(request_callback));
+ return MakeGarbageCollected<DeleteObjectStoreEntriesListener>(
+ std::move(request_callback));
}
+ DeleteObjectStoreEntriesListener(
+ std::unique_ptr<DeleteObjectStoreEntriesCallback> request_callback)
+ : EventListener(EventListener::kCPPEventListenerType),
+ request_callback_(std::move(request_callback)) {}
~DeleteObjectStoreEntriesListener() override = default;
bool operator==(const EventListener& other) const override {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
- if (event->type() != EventTypeNames::success) {
+ void Invoke(ExecutionContext*, Event* event) override {
+ if (event->type() != event_type_names::kSuccess) {
request_callback_->sendFailure(
Response::Error("Failed to delete specified entries"));
return;
@@ -881,11 +886,6 @@ class DeleteObjectStoreEntriesListener final : public EventListener {
}
private:
- DeleteObjectStoreEntriesListener(
- std::unique_ptr<DeleteObjectStoreEntriesCallback> request_callback)
- : EventListener(EventListener::kCPPEventListenerType),
- request_callback_(std::move(request_callback)) {}
-
std::unique_ptr<DeleteObjectStoreEntriesCallback> request_callback_;
};
@@ -911,7 +911,7 @@ class DeleteObjectStoreEntries final
void Execute(IDBDatabase* idb_database, ScriptState* script_state) override {
IDBTransaction* idb_transaction =
TransactionForDatabase(script_state, idb_database, object_store_name_,
- IndexedDBNames::readwrite);
+ indexed_db_names::kReadwrite);
if (!idb_transaction) {
request_callback_->sendFailure(
Response::Error("Could not get transaction"));
@@ -928,7 +928,7 @@ class DeleteObjectStoreEntries final
IDBRequest* idb_request =
idb_object_store->deleteFunction(script_state, idb_key_range_.Get());
idb_request->addEventListener(
- EventTypeNames::success,
+ event_type_names::kSuccess,
DeleteObjectStoreEntriesListener::Create(std::move(request_callback_)),
false);
}
@@ -977,8 +977,8 @@ class ClearObjectStoreListener final : public EventListener {
return this == &other;
}
- void handleEvent(ExecutionContext*, Event* event) override {
- if (event->type() != EventTypeNames::complete) {
+ void Invoke(ExecutionContext*, Event* event) override {
+ if (event->type() != event_type_names::kComplete) {
request_callback_->sendFailure(Response::Error("Unexpected event type."));
return;
}
@@ -1013,7 +1013,7 @@ class ClearObjectStore final
void Execute(IDBDatabase* idb_database, ScriptState* script_state) override {
IDBTransaction* idb_transaction =
TransactionForDatabase(script_state, idb_database, object_store_name_,
- IndexedDBNames::readwrite);
+ indexed_db_names::kReadwrite);
if (!idb_transaction) {
request_callback_->sendFailure(
Response::Error("Could not get transaction"));
@@ -1038,7 +1038,7 @@ class ClearObjectStore final
return;
}
idb_transaction->addEventListener(
- EventTypeNames::complete,
+ event_type_names::kComplete,
ClearObjectStoreListener::Create(std::move(request_callback_)), false);
}
@@ -1096,7 +1096,7 @@ void InspectorIndexedDBAgent::deleteDatabase(
return;
}
idb_request->addEventListener(
- EventTypeNames::success,
+ event_type_names::kSuccess,
DeleteCallback::Create(std::move(request_callback),
document->GetSecurityOrigin()->ToRawString()),
false);
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.cc b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.cc
new file mode 100644
index 00000000000..1f7839527ff
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.cc
@@ -0,0 +1,39 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h"
+
+namespace blink {
+
+MockWebIDBCallbacks::MockWebIDBCallbacks() {}
+
+MockWebIDBCallbacks::~MockWebIDBCallbacks() {}
+
+void MockWebIDBCallbacks::OnSuccess(blink::WebIDBKey key,
+ blink::WebIDBKey primaryKey,
+ blink::WebIDBValue value) {
+ DoOnSuccess(key, primaryKey, value);
+}
+
+void MockWebIDBCallbacks::OnSuccess(blink::WebIDBCursor* cursor,
+ blink::WebIDBKey key,
+ blink::WebIDBKey primaryKey,
+ blink::WebIDBValue value) {
+ DoOnSuccess(cursor, key, primaryKey, value);
+}
+
+void MockWebIDBCallbacks::OnSuccess(blink::WebIDBKey key) {
+ DoOnSuccess(key);
+}
+
+void MockWebIDBCallbacks::OnSuccess(blink::WebIDBValue value) {
+ DoOnSuccess(value);
+}
+
+void MockWebIDBCallbacks::OnSuccess(
+ blink::WebVector<blink::WebIDBValue> values) {
+ DoOnSuccess(values);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h
new file mode 100644
index 00000000000..97fe12544ea
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h
@@ -0,0 +1,76 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_MOCK_WEB_IDB_CALLBACKS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_MOCK_WEB_IDB_CALLBACKS_H_
+
+#include "base/macros.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_name_and_version.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/public/web/web_heap.h"
+
+namespace blink {
+
+class MockWebIDBCallbacks : public blink::WebIDBCallbacks {
+ public:
+ MockWebIDBCallbacks();
+ ~MockWebIDBCallbacks() override;
+ MOCK_METHOD1(OnError, void(const blink::WebIDBDatabaseError&));
+
+ void OnSuccess(blink::WebIDBKey,
+ blink::WebIDBKey primaryKey,
+ blink::WebIDBValue) override;
+ MOCK_METHOD3(DoOnSuccess,
+ void(const blink::WebIDBKey& key,
+ const blink::WebIDBKey& primaryKey,
+ const blink::WebIDBValue& value));
+
+ MOCK_METHOD1(OnSuccess,
+ void(const blink::WebVector<blink::WebIDBNameAndVersion>&));
+ MOCK_METHOD1(OnSuccess, void(const blink::WebVector<blink::WebString>&));
+
+ void OnSuccess(blink::WebIDBCursor* cursor,
+ blink::WebIDBKey key,
+ blink::WebIDBKey primaryKey,
+ blink::WebIDBValue value) override;
+ MOCK_METHOD4(DoOnSuccess,
+ void(blink::WebIDBCursor*,
+ const blink::WebIDBKey&,
+ const blink::WebIDBKey& primaryKey,
+ const blink::WebIDBValue&));
+
+ MOCK_METHOD2(OnSuccess,
+ void(blink::WebIDBDatabase*, const blink::WebIDBMetadata&));
+ void OnSuccess(blink::WebIDBKey) override;
+ MOCK_METHOD1(DoOnSuccess, void(const blink::WebIDBKey&));
+
+ void OnSuccess(blink::WebIDBValue) override;
+ MOCK_METHOD1(DoOnSuccess, void(const blink::WebIDBValue&));
+
+ void OnSuccess(blink::WebVector<blink::WebIDBValue>) override;
+ MOCK_METHOD1(DoOnSuccess, void(const blink::WebVector<blink::WebIDBValue>&));
+
+ MOCK_METHOD1(OnSuccess, void(long long));
+ MOCK_METHOD0(OnSuccess, void());
+ MOCK_METHOD1(OnBlocked, void(long long oldVersion));
+ MOCK_METHOD5(OnUpgradeNeeded,
+ void(long long oldVersion,
+ blink::WebIDBDatabase*,
+ const blink::WebIDBMetadata&,
+ mojom::IDBDataLoss dataLoss,
+ blink::WebString dataLossMessage));
+ MOCK_METHOD0(Detach, void());
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(MockWebIDBCallbacks);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_MOCK_WEB_IDB_CALLBACKS_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_database.h b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_database.h
index a7325498632..04f7a5acda6 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_database.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_database.h
@@ -7,10 +7,10 @@
#include <gmock/gmock.h>
#include <memory>
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_range.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
namespace blink {
@@ -23,7 +23,7 @@ class MockWebIDBDatabase : public testing::StrictMock<WebIDBDatabase> {
MOCK_METHOD5(CreateObjectStore,
void(long long transaction_id,
long long object_store_id,
- const WebString& name,
+ const String& name,
const WebIDBKeyPath&,
bool auto_increment));
MOCK_METHOD2(DeleteObjectStore,
@@ -31,11 +31,11 @@ class MockWebIDBDatabase : public testing::StrictMock<WebIDBDatabase> {
MOCK_METHOD3(RenameObjectStore,
void(long long transaction_id,
long long object_store_id,
- const WebString& new_name));
+ const String& new_name));
MOCK_METHOD3(CreateTransaction,
void(long long id,
- const WebVector<long long>& scope,
- WebIDBTransactionMode));
+ const Vector<int64_t>& scope,
+ mojom::IDBTransactionMode));
MOCK_METHOD0(Close, void());
MOCK_METHOD0(VersionChangeIgnored, void());
MOCK_METHOD1(Abort, void(long long transaction_id));
@@ -44,7 +44,7 @@ class MockWebIDBDatabase : public testing::StrictMock<WebIDBDatabase> {
void(long long transaction_id,
long long object_store_id,
long long index_id,
- const WebString& name,
+ const String& name,
const WebIDBKeyPath&,
bool unique,
bool multi_entry));
@@ -56,7 +56,7 @@ class MockWebIDBDatabase : public testing::StrictMock<WebIDBDatabase> {
void(long long transaction_id,
long long object_store_id,
long long index_id,
- const WebString& new_name));
+ const String& new_name));
MOCK_METHOD6(
AddObserver,
void(long long transaction_id,
@@ -64,10 +64,10 @@ class MockWebIDBDatabase : public testing::StrictMock<WebIDBDatabase> {
bool include_transaction,
bool no_records,
bool values,
- const std::bitset<kWebIDBOperationTypeCount>& operation_types));
+ std::bitset<blink::kIDBOperationTypeCount> operation_types));
MOCK_CONST_METHOD1(ContainsObserverId, bool(int32_t id));
MOCK_METHOD1(RemoveObservers,
- void(const WebVector<int32_t>& observer_ids_to_remove));
+ void(const Vector<int32_t>& observer_ids_to_remove));
MOCK_METHOD6(Get,
void(long long transaction_id,
long long object_store_id,
@@ -88,29 +88,29 @@ class MockWebIDBDatabase : public testing::StrictMock<WebIDBDatabase> {
void(long long transaction_id,
long long object_store_id,
const WebData& value,
- const WebVector<WebBlobInfo>&,
+ const Vector<WebBlobInfo>&,
WebIDBKeyView primary_key,
- WebIDBPutMode,
+ mojom::IDBPutMode,
WebIDBCallbacks*,
- const WebVector<WebIDBIndexKeys>&));
+ const Vector<WebIDBIndexKeys>&));
MOCK_METHOD4(SetIndexKeys,
void(long long transaction_id,
long long object_store_id,
WebIDBKeyView primary_key,
- const WebVector<WebIDBIndexKeys>&));
+ const Vector<WebIDBIndexKeys>&));
MOCK_METHOD3(SetIndexesReady,
void(long long transaction_id,
long long object_store_id,
- const WebVector<long long>& index_ids));
+ const Vector<int64_t>& index_ids));
MOCK_METHOD8(OpenCursor,
void(long long transaction_id,
long long object_store_id,
long long index_id,
const WebIDBKeyRange&,
- WebIDBCursorDirection,
+ mojom::IDBCursorDirection,
bool key_only,
- WebIDBTaskType,
+ mojom::IDBTaskType,
WebIDBCallbacks*));
MOCK_METHOD5(Count,
void(long long transaction_id,
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.cc b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.cc
new file mode 100644
index 00000000000..80cf343612e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.cc
@@ -0,0 +1,20 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.h"
+
+#include <memory>
+
+#include "base/memory/ptr_util.h"
+
+namespace blink {
+
+MockWebIDBFactory::MockWebIDBFactory() = default;
+
+MockWebIDBFactory::~MockWebIDBFactory() = default;
+
+std::unique_ptr<MockWebIDBFactory> MockWebIDBFactory::Create() {
+ return base::WrapUnique(new MockWebIDBFactory());
+}
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.h b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.h
new file mode 100644
index 00000000000..47ffe2f93e6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/mock_web_idb_factory.h
@@ -0,0 +1,62 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_MOCK_WEB_IDB_FACTORY_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_MOCK_WEB_IDB_FACTORY_H_
+
+#include <gmock/gmock.h>
+#include <memory>
+
+#include "base/single_thread_task_runner.h"
+#include "third_party/blink/public/platform/web_common.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_factory.h"
+
+namespace base {
+class SingleThreadTaskRunner;
+}
+
+namespace blink {
+
+class WebIDBCallbacks;
+class WebIDBDatabaseCallbacks;
+class WebSecurityOrigin;
+class WebString;
+
+class MockWebIDBFactory : public testing::StrictMock<blink::WebIDBFactory> {
+ public:
+ ~MockWebIDBFactory() override;
+
+ static std::unique_ptr<MockWebIDBFactory> Create();
+
+ MOCK_METHOD3(GetDatabaseInfo,
+ void(WebIDBCallbacks*,
+ const WebSecurityOrigin&,
+ scoped_refptr<base::SingleThreadTaskRunner>));
+ MOCK_METHOD3(GetDatabaseNames,
+ void(WebIDBCallbacks*,
+ const WebSecurityOrigin&,
+ scoped_refptr<base::SingleThreadTaskRunner>));
+ MOCK_METHOD7(Open,
+ void(const WebString& name,
+ long long version,
+ long long transaction_id,
+ WebIDBCallbacks*,
+ WebIDBDatabaseCallbacks*,
+ const WebSecurityOrigin&,
+ scoped_refptr<base::SingleThreadTaskRunner>));
+ MOCK_METHOD5(DeleteDatabase,
+ void(const WebString& name,
+ WebIDBCallbacks*,
+ const WebSecurityOrigin&,
+ bool force_close,
+ scoped_refptr<base::SingleThreadTaskRunner>));
+
+ private:
+ MockWebIDBFactory();
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_MOCK_WEB_IDB_FACTORY_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc
index fe63972adb0..b4904837f97 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.cc
@@ -31,10 +31,9 @@
#include <memory>
#include "base/memory/ptr_util.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_cursor.h"
-#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_name_and_version.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
@@ -42,6 +41,8 @@
#include "third_party/blink/renderer/modules/indexeddb/idb_metadata.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_request.h"
#include "third_party/blink/renderer/modules/indexeddb/idb_value.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -51,6 +52,7 @@ using blink::WebIDBDatabaseError;
using blink::WebIDBKey;
using blink::WebIDBKeyPath;
using blink::WebIDBMetadata;
+using blink::WebIDBNameAndVersion;
using blink::WebIDBValue;
using blink::WebVector;
@@ -65,7 +67,7 @@ std::unique_ptr<WebIDBCallbacksImpl> WebIDBCallbacksImpl::Create(
WebIDBCallbacksImpl::WebIDBCallbacksImpl(IDBRequest* request)
: request_(request) {
probe::AsyncTaskScheduled(request_->GetExecutionContext(),
- IndexedDBNames::IndexedDB, this);
+ indexed_db_names::kIndexedDB, this);
}
WebIDBCallbacksImpl::~WebIDBCallbacksImpl() {
@@ -88,6 +90,12 @@ void WebIDBCallbacksImpl::OnError(const WebIDBDatabaseError& error) {
}
void WebIDBCallbacksImpl::OnSuccess(
+ const WebVector<WebIDBNameAndVersion>& web_name_and_version_list) {
+ // Only implemented in idb_factory.cc for the promise-based databases() call.
+ NOTREACHED();
+}
+
+void WebIDBCallbacksImpl::OnSuccess(
const WebVector<WebString>& web_string_list) {
if (!request_)
return;
@@ -207,7 +215,7 @@ void WebIDBCallbacksImpl::OnBlocked(long long old_version) {
void WebIDBCallbacksImpl::OnUpgradeNeeded(long long old_version,
WebIDBDatabase* database,
const WebIDBMetadata& metadata,
- unsigned short data_loss,
+ mojom::IDBDataLoss data_loss,
WebString data_loss_message) {
std::unique_ptr<WebIDBDatabase> db = base::WrapUnique(database);
if (request_) {
@@ -216,9 +224,9 @@ void WebIDBCallbacksImpl::OnUpgradeNeeded(long long old_version,
#if DCHECK_IS_ON()
DCHECK(!request_->TransactionHasQueuedResults());
#endif // DCHECK_IS_ON()
- request_->EnqueueUpgradeNeeded(
- old_version, std::move(db), IDBDatabaseMetadata(metadata),
- static_cast<WebIDBDataLoss>(data_loss), data_loss_message);
+ request_->EnqueueUpgradeNeeded(old_version, std::move(db),
+ IDBDatabaseMetadata(metadata), data_loss,
+ data_loss_message);
} else {
db->Close();
}
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.h
index 849ba811f7c..8cf4cb7ac8a 100644
--- a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.h
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_callbacks_impl.h
@@ -43,6 +43,7 @@ class WebIDBDatabase;
class WebIDBDatabaseError;
class WebIDBKey;
struct WebIDBMetadata;
+struct WebIDBNameAndVersion;
class WebIDBValue;
class WebIDBCallbacksImpl final : public WebIDBCallbacks {
@@ -55,6 +56,7 @@ class WebIDBCallbacksImpl final : public WebIDBCallbacks {
// Pointers transfer ownership.
void OnError(const WebIDBDatabaseError&) override;
+ void OnSuccess(const WebVector<WebIDBNameAndVersion>&) override;
void OnSuccess(const WebVector<WebString>&) override;
void OnSuccess(WebIDBCursor*,
WebIDBKey,
@@ -71,7 +73,7 @@ class WebIDBCallbacksImpl final : public WebIDBCallbacks {
void OnUpgradeNeeded(long long old_version,
WebIDBDatabase*,
const WebIDBMetadata&,
- unsigned short data_loss,
+ mojom::IDBDataLoss data_loss,
WebString data_loss_message) override;
void Detach() override;
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h
new file mode 100644
index 00000000000..998daa93b4c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_CURSOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_CURSOR_H_
+
+#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace blink {
+
+class MODULES_EXPORT WebIDBCursor {
+ public:
+ virtual ~WebIDBCursor() = default;
+
+ // Used to implement IDBCursor.advance().
+ virtual void Advance(uint32_t count, WebIDBCallbacks*) = 0;
+
+ // Used to implement IDBCursor.continue() and IDBCursor.continuePrimaryKey().
+ //
+ // The key and primary key are null when they are not supplied by the
+ // application. When both arguments are null, the cursor advances by one
+ // entry.
+ //
+ // The keys pointed to by WebIDBKeyView are only guaranteed to be alive for
+ // the duration of the call.
+ virtual void CursorContinue(WebIDBKeyView,
+ WebIDBKeyView primary_key,
+ WebIDBCallbacks*) = 0;
+
+ // Called after a cursor request's success handler is executed.
+ //
+ // This is only used by the cursor prefetching logic, and does not result in
+ // an IPC.
+ virtual void PostSuccessHandlerCallback() = 0;
+
+ protected:
+ WebIDBCursor() = default;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_CURSOR_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.cc b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.cc
new file mode 100644
index 00000000000..c308cf7cab9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.cc
@@ -0,0 +1,219 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h"
+
+#include <stddef.h>
+
+#include <string>
+#include <vector>
+
+#include "base/single_thread_task_runner.h"
+#include "mojo/public/cpp/bindings/strong_associated_binding.h"
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h"
+
+using blink::WebBlobInfo;
+using blink::WebData;
+using blink::WebIDBCallbacks;
+using blink::WebIDBKey;
+using blink::WebIDBKeyView;
+using blink::WebIDBValue;
+using blink::mojom::blink::IDBCallbacksAssociatedPtrInfo;
+using blink::mojom::blink::IDBCursorAssociatedPtrInfo;
+
+namespace blink {
+
+WebIDBCursorImpl::WebIDBCursorImpl(
+ mojom::blink::IDBCursorAssociatedPtrInfo cursor_info,
+ int64_t transaction_id)
+ : transaction_id_(transaction_id),
+ cursor_(std::move(cursor_info)),
+ continue_count_(0),
+ used_prefetches_(0),
+ pending_onsuccess_callbacks_(0),
+ prefetch_amount_(kMinPrefetchAmount),
+ weak_factory_(this) {
+ IndexedDBDispatcher::RegisterCursor(this);
+}
+
+WebIDBCursorImpl::~WebIDBCursorImpl() {
+ // It's not possible for there to be pending callbacks that address this
+ // object since inside WebKit, they hold a reference to the object which owns
+ // this object. But, if that ever changed, then we'd need to invalidate
+ // any such pointers.
+ IndexedDBDispatcher::UnregisterCursor(this);
+}
+
+void WebIDBCursorImpl::Advance(uint32_t count, WebIDBCallbacks* callbacks_ptr) {
+ std::unique_ptr<WebIDBCallbacks> callbacks(callbacks_ptr);
+ if (count <= prefetch_keys_.size()) {
+ CachedAdvance(count, callbacks.get());
+ return;
+ }
+ ResetPrefetchCache();
+
+ // Reset all cursor prefetch caches except for this cursor.
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id_, this);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ std::move(callbacks), transaction_id_, weak_factory_.GetWeakPtr());
+ cursor_->Advance(count, GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBCursorImpl::CursorContinue(WebIDBKeyView key,
+ WebIDBKeyView primary_key,
+ WebIDBCallbacks* callbacks_ptr) {
+ std::unique_ptr<WebIDBCallbacks> callbacks(callbacks_ptr);
+
+ if (key.KeyType() == kWebIDBKeyTypeNull &&
+ primary_key.KeyType() == kWebIDBKeyTypeNull) {
+ // No key(s), so this would qualify for a prefetch.
+ ++continue_count_;
+
+ if (!prefetch_keys_.IsEmpty()) {
+ // We have a prefetch cache, so serve the result from that.
+ CachedContinue(callbacks.get());
+ return;
+ }
+
+ if (continue_count_ > kPrefetchContinueThreshold) {
+ // Request pre-fetch.
+ ++pending_onsuccess_callbacks_;
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ std::move(callbacks), transaction_id_, weak_factory_.GetWeakPtr());
+ cursor_->Prefetch(prefetch_amount_,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+
+ // Increase prefetch_amount_ exponentially.
+ prefetch_amount_ *= 2;
+ if (prefetch_amount_ > kMaxPrefetchAmount)
+ prefetch_amount_ = kMaxPrefetchAmount;
+
+ return;
+ }
+ } else {
+ // Key argument supplied. We couldn't prefetch this.
+ ResetPrefetchCache();
+ }
+
+ // Reset all cursor prefetch caches except for this cursor.
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id_, this);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ std::move(callbacks), transaction_id_, weak_factory_.GetWeakPtr());
+ cursor_->CursorContinue(WebIDBKeyBuilder::Build(key),
+ WebIDBKeyBuilder::Build(primary_key),
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBCursorImpl::PostSuccessHandlerCallback() {
+ pending_onsuccess_callbacks_--;
+
+ // If the onsuccess callback called continue()/advance() on the cursor
+ // again, and that request was served by the prefetch cache, then
+ // pending_onsuccess_callbacks_ would be incremented. If not, it means the
+ // callback did something else, or nothing at all, in which case we need to
+ // reset the cache.
+
+ if (pending_onsuccess_callbacks_ == 0)
+ ResetPrefetchCache();
+}
+
+void WebIDBCursorImpl::SetPrefetchData(Vector<WebIDBKey> keys,
+ Vector<WebIDBKey> primary_keys,
+ Vector<WebIDBValue> values) {
+ // Keys and values are stored in reverse order so that a cache'd continue can
+ // pop a value off of the back and prevent new memory allocations.
+ prefetch_keys_.AppendRange(std::make_move_iterator(keys.rbegin()),
+ std::make_move_iterator(keys.rend()));
+ prefetch_primary_keys_.AppendRange(
+ std::make_move_iterator(primary_keys.rbegin()),
+ std::make_move_iterator(primary_keys.rend()));
+ prefetch_values_.AppendRange(std::make_move_iterator(values.rbegin()),
+ std::make_move_iterator(values.rend()));
+
+ used_prefetches_ = 0;
+ pending_onsuccess_callbacks_ = 0;
+}
+
+void WebIDBCursorImpl::CachedAdvance(unsigned long count,
+ WebIDBCallbacks* callbacks) {
+ DCHECK_GE(prefetch_keys_.size(), count);
+ DCHECK_EQ(prefetch_primary_keys_.size(), prefetch_keys_.size());
+ DCHECK_EQ(prefetch_values_.size(), prefetch_keys_.size());
+
+ while (count > 1) {
+ prefetch_keys_.pop_back();
+ prefetch_primary_keys_.pop_back();
+ prefetch_values_.pop_back();
+ ++used_prefetches_;
+ --count;
+ }
+
+ CachedContinue(callbacks);
+}
+
+void WebIDBCursorImpl::CachedContinue(WebIDBCallbacks* callbacks) {
+ DCHECK_GT(prefetch_keys_.size(), 0ul);
+ DCHECK_EQ(prefetch_primary_keys_.size(), prefetch_keys_.size());
+ DCHECK_EQ(prefetch_values_.size(), prefetch_keys_.size());
+
+ // Keys and values are stored in reverse order so that a cache'd continue can
+ // pop a value off of the back and prevent new memory allocations.
+ WebIDBKey key = std::move(prefetch_keys_.back());
+ WebIDBKey primary_key = std::move(prefetch_primary_keys_.back());
+ WebIDBValue value = std::move(prefetch_values_.back());
+
+ prefetch_keys_.pop_back();
+ prefetch_primary_keys_.pop_back();
+ prefetch_values_.pop_back();
+ ++used_prefetches_;
+
+ ++pending_onsuccess_callbacks_;
+
+ if (!continue_count_) {
+ // The cache was invalidated by a call to ResetPrefetchCache()
+ // after the RequestIDBCursorPrefetch() was made. Now that the
+ // initiating continue() call has been satisfied, discard
+ // the rest of the cache.
+ ResetPrefetchCache();
+ }
+
+ callbacks->OnSuccess(std::move(key), std::move(primary_key),
+ std::move(value));
+}
+
+void WebIDBCursorImpl::ResetPrefetchCache() {
+ continue_count_ = 0;
+ prefetch_amount_ = kMinPrefetchAmount;
+
+ if (prefetch_keys_.IsEmpty()) {
+ // No prefetch cache, so no need to reset the cursor in the back-end.
+ return;
+ }
+
+ // Reset the back-end cursor.
+ cursor_->PrefetchReset(used_prefetches_, prefetch_keys_.size());
+
+ // Reset the prefetch cache.
+ prefetch_keys_.clear();
+ prefetch_primary_keys_.clear();
+ prefetch_values_.clear();
+
+ pending_onsuccess_callbacks_ = 0;
+}
+
+IDBCallbacksAssociatedPtrInfo WebIDBCursorImpl::GetCallbacksProxy(
+ std::unique_ptr<IndexedDBCallbacksImpl> callbacks) {
+ IDBCallbacksAssociatedPtrInfo ptr_info;
+ auto request = mojo::MakeRequest(&ptr_info);
+ mojo::MakeStrongAssociatedBinding(std::move(callbacks), std::move(request));
+ return ptr_info;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h
new file mode 100644
index 00000000000..58e953fa26e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h
@@ -0,0 +1,93 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_CURSOR_IMPL_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_CURSOR_IMPL_H_
+
+#include <stdint.h>
+
+#include <vector>
+
+#include "base/gtest_prod_util.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_value.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace blink {
+
+class IndexedDBCallbacksImpl;
+
+class MODULES_EXPORT WebIDBCursorImpl : public WebIDBCursor {
+ public:
+ WebIDBCursorImpl(mojom::blink::IDBCursorAssociatedPtrInfo cursor,
+ int64_t transaction_id);
+ ~WebIDBCursorImpl() override;
+
+ void Advance(uint32_t count, WebIDBCallbacks* callback) override;
+ void CursorContinue(WebIDBKeyView key,
+ WebIDBKeyView primary_key,
+ WebIDBCallbacks* callback) override;
+ void PostSuccessHandlerCallback() override;
+
+ void SetPrefetchData(Vector<WebIDBKey> keys,
+ Vector<WebIDBKey> primary_keys,
+ Vector<WebIDBValue> values);
+
+ void CachedAdvance(unsigned long count, WebIDBCallbacks* callbacks);
+ void CachedContinue(WebIDBCallbacks* callbacks);
+
+ // This method is virtual so it can be overridden in unit tests.
+ virtual void ResetPrefetchCache();
+
+ int64_t transaction_id() const { return transaction_id_; }
+
+ private:
+ mojom::blink::IDBCallbacksAssociatedPtrInfo GetCallbacksProxy(
+ std::unique_ptr<IndexedDBCallbacksImpl> callbacks);
+
+ FRIEND_TEST_ALL_PREFIXES(IndexedDBDispatcherTest, CursorReset);
+ FRIEND_TEST_ALL_PREFIXES(IndexedDBDispatcherTest, CursorTransactionId);
+ FRIEND_TEST_ALL_PREFIXES(WebIDBCursorImplTest, AdvancePrefetchTest);
+ FRIEND_TEST_ALL_PREFIXES(WebIDBCursorImplTest, PrefetchReset);
+ FRIEND_TEST_ALL_PREFIXES(WebIDBCursorImplTest, PrefetchTest);
+
+ static constexpr int kPrefetchContinueThreshold = 2;
+ static constexpr int kMinPrefetchAmount = 5;
+ static constexpr int kMaxPrefetchAmount = 100;
+
+ int64_t transaction_id_;
+
+ mojom::blink::IDBCursorAssociatedPtr cursor_;
+
+ // Prefetch cache. Keys and values are stored in reverse order so that a
+ // cache'd continue can pop a value off of the back and prevent new memory
+ // allocations.
+ Vector<WebIDBKey> prefetch_keys_;
+ Vector<WebIDBKey> prefetch_primary_keys_;
+ Vector<WebIDBValue> prefetch_values_;
+
+ // Number of continue calls that would qualify for a pre-fetch.
+ int continue_count_;
+
+ // Number of items used from the last prefetch.
+ int used_prefetches_;
+
+ // Number of onsuccess handlers we are waiting for.
+ int pending_onsuccess_callbacks_;
+
+ // Number of items to request in next prefetch.
+ int prefetch_amount_;
+
+ base::WeakPtrFactory<WebIDBCursorImpl> weak_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(WebIDBCursorImpl);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_CURSOR_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl_unittest.cc b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl_unittest.cc
new file mode 100644
index 00000000000..76fa9b2ad2b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl_unittest.cc
@@ -0,0 +1,349 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <memory>
+
+#include "base/macros.h"
+#include "mojo/public/cpp/bindings/associated_binding.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h"
+#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+
+namespace blink {
+
+namespace {
+
+class MockCursorImpl : public mojom::blink::IDBCursor {
+ public:
+ explicit MockCursorImpl(mojom::blink::IDBCursorAssociatedRequest request)
+ : binding_(this, std::move(request)) {
+ binding_.set_connection_error_handler(base::BindOnce(
+ &MockCursorImpl::CursorDestroyed, base::Unretained(this)));
+ }
+
+ void Prefetch(
+ int32_t count,
+ mojom::blink::IDBCallbacksAssociatedPtrInfo callbacks) override {
+ ++prefetch_calls_;
+ last_prefetch_count_ = count;
+ }
+
+ void PrefetchReset(int32_t used_prefetches,
+ int32_t unused_prefetches) override {
+ ++reset_calls_;
+ last_used_count_ = used_prefetches;
+ }
+
+ void Advance(uint32_t count,
+ mojom::blink::IDBCallbacksAssociatedPtrInfo callbacks) override {
+ ++advance_calls_;
+ }
+
+ void CursorContinue(
+ WebIDBKey key,
+ WebIDBKey primary_key,
+ mojom::blink::IDBCallbacksAssociatedPtrInfo callbacks) override {
+ ++continue_calls_;
+ }
+
+ void CursorDestroyed() { destroyed_ = true; }
+
+ int prefetch_calls() { return prefetch_calls_; }
+ int last_prefetch_count() { return last_prefetch_count_; }
+ int reset_calls() { return reset_calls_; }
+ int last_used_count() { return last_used_count_; }
+ int advance_calls() { return advance_calls_; }
+ int continue_calls() { return continue_calls_; }
+ bool destroyed() { return destroyed_; }
+
+ private:
+ int prefetch_calls_ = 0;
+ int last_prefetch_count_ = 0;
+ int reset_calls_ = 0;
+ int last_used_count_ = 0;
+ int advance_calls_ = 0;
+ int continue_calls_ = 0;
+ bool destroyed_ = false;
+
+ mojo::AssociatedBinding<IDBCursor> binding_;
+};
+
+class MockContinueCallbacks : public testing::StrictMock<MockWebIDBCallbacks> {
+ public:
+ MockContinueCallbacks(IndexedDBKey* key = nullptr,
+ WebVector<WebBlobInfo>* blobs = nullptr)
+ : key_(key), blobs_(blobs) {}
+
+ void OnSuccess(WebIDBKey key,
+ WebIDBKey primaryKey,
+ WebIDBValue value) override {
+ if (key_)
+ *key_ = IndexedDBKeyBuilder::Build(key.View());
+ if (blobs_)
+ *blobs_ = value.BlobInfoForTesting();
+ }
+
+ private:
+ IndexedDBKey* key_;
+ WebVector<WebBlobInfo>* blobs_;
+};
+
+} // namespace
+
+class WebIDBCursorImplTest : public testing::Test {
+ public:
+ WebIDBCursorImplTest() : null_key_(WebIDBKey::CreateNull()) {
+ mojom::blink::IDBCursorAssociatedPtr ptr;
+ mock_cursor_ = std::make_unique<MockCursorImpl>(
+ mojo::MakeRequestAssociatedWithDedicatedPipe(&ptr));
+ cursor_ = std::make_unique<WebIDBCursorImpl>(ptr.PassInterface(), 1);
+ }
+
+ protected:
+ ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
+ WebIDBKey null_key_;
+ std::unique_ptr<WebIDBCursorImpl> cursor_;
+ std::unique_ptr<MockCursorImpl> mock_cursor_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(WebIDBCursorImplTest);
+};
+
+TEST_F(WebIDBCursorImplTest, PrefetchTest) {
+ // Call continue() until prefetching should kick in.
+ int continue_calls = 0;
+ EXPECT_EQ(mock_cursor_->continue_calls(), 0);
+ for (int i = 0; i < WebIDBCursorImpl::kPrefetchContinueThreshold; ++i) {
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(++continue_calls, mock_cursor_->continue_calls());
+ EXPECT_EQ(0, mock_cursor_->prefetch_calls());
+ }
+
+ // Do enough repetitions to verify that the count grows each time,
+ // but not so many that the maximum limit is hit.
+ const int kPrefetchRepetitions = 5;
+
+ int expected_key = 0;
+ int last_prefetch_count = 0;
+ for (int repetitions = 0; repetitions < kPrefetchRepetitions; ++repetitions) {
+ // Initiate the prefetch
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(continue_calls, mock_cursor_->continue_calls());
+ EXPECT_EQ(repetitions + 1, mock_cursor_->prefetch_calls());
+
+ // Verify that the requested count has increased since last time.
+ int prefetch_count = mock_cursor_->last_prefetch_count();
+ EXPECT_GT(prefetch_count, last_prefetch_count);
+ last_prefetch_count = prefetch_count;
+
+ // Fill the prefetch cache as requested.
+ Vector<WebIDBKey> keys;
+ Vector<WebIDBKey> primary_keys;
+ Vector<WebIDBValue> values;
+ size_t expected_size = 0;
+ for (int i = 0; i < prefetch_count; ++i) {
+ WebIDBKey key = WebIDBKey::CreateNumber(expected_key + i);
+ keys.emplace_back(std::move(key));
+ primary_keys.emplace_back();
+ expected_size++;
+ EXPECT_EQ(expected_size, keys.size());
+ EXPECT_EQ(expected_size, primary_keys.size());
+ WebVector<WebBlobInfo> blob_info;
+ blob_info.reserve(expected_key + i);
+ for (int j = 0; j < expected_key + i; ++j) {
+ blob_info.emplace_back(WebBlobInfo::BlobForTesting(
+ WebString("blobuuid"), "text/plain", 123));
+ }
+ values.emplace_back(WebData(), std::move(blob_info));
+ }
+ cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys),
+ std::move(values));
+
+ // Note that the real dispatcher would call cursor->CachedContinue()
+ // immediately after cursor->SetPrefetchData() to service the request
+ // that initiated the prefetch.
+
+ // Verify that the cache is used for subsequent continue() calls.
+ for (int i = 0; i < prefetch_count; ++i) {
+ IndexedDBKey key;
+ WebVector<WebBlobInfo> blobs;
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks(&key, &blobs));
+ platform_->RunUntilIdle();
+ EXPECT_EQ(continue_calls, mock_cursor_->continue_calls());
+ EXPECT_EQ(repetitions + 1, mock_cursor_->prefetch_calls());
+
+ EXPECT_EQ(kWebIDBKeyTypeNumber, key.type());
+ EXPECT_EQ(expected_key, static_cast<int>(blobs.size()));
+ EXPECT_EQ(expected_key++, key.number());
+ }
+ }
+
+ cursor_.reset();
+ platform_->RunUntilIdle();
+ EXPECT_TRUE(mock_cursor_->destroyed());
+}
+
+TEST_F(WebIDBCursorImplTest, AdvancePrefetchTest) {
+ // Call continue() until prefetching should kick in.
+ EXPECT_EQ(0, mock_cursor_->continue_calls());
+ for (int i = 0; i < WebIDBCursorImpl::kPrefetchContinueThreshold; ++i) {
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks());
+ }
+ platform_->RunUntilIdle();
+ EXPECT_EQ(0, mock_cursor_->prefetch_calls());
+
+ // Initiate the prefetch
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks());
+
+ platform_->RunUntilIdle();
+ EXPECT_EQ(1, mock_cursor_->prefetch_calls());
+ EXPECT_EQ(static_cast<int>(WebIDBCursorImpl::kPrefetchContinueThreshold),
+ mock_cursor_->continue_calls());
+ EXPECT_EQ(0, mock_cursor_->advance_calls());
+
+ const int prefetch_count = mock_cursor_->last_prefetch_count();
+
+ // Fill the prefetch cache as requested.
+ int expected_key = 0;
+ Vector<WebIDBKey> keys;
+ Vector<WebIDBKey> primary_keys;
+ Vector<WebIDBValue> values;
+ size_t expected_size = 0;
+ for (int i = 0; i < prefetch_count; ++i) {
+ WebIDBKey key = WebIDBKey::CreateNumber(expected_key + i);
+ keys.emplace_back(std::move(key));
+ primary_keys.emplace_back();
+ expected_size++;
+ EXPECT_EQ(expected_size, keys.size());
+ EXPECT_EQ(expected_size, primary_keys.size());
+ WebVector<WebBlobInfo> blob_info;
+ blob_info.reserve(expected_key + i);
+ for (int j = 0; j < expected_key + i; ++j) {
+ blob_info.emplace_back(WebBlobInfo::BlobForTesting(WebString("blobuuid"),
+ "text/plain", 123));
+ }
+ values.emplace_back(WebData(), std::move(blob_info));
+ }
+ cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys),
+ std::move(values));
+
+ // Note that the real dispatcher would call cursor->CachedContinue()
+ // immediately after cursor->SetPrefetchData() to service the request
+ // that initiated the prefetch.
+
+ // Need at least this many in the cache for the test steps.
+ ASSERT_GE(prefetch_count, 5);
+
+ // IDBCursor.continue()
+ IndexedDBKey key;
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks(&key));
+ platform_->RunUntilIdle();
+ EXPECT_EQ(0, key.number());
+
+ // IDBCursor.advance(1)
+ cursor_->Advance(1, new MockContinueCallbacks(&key));
+ platform_->RunUntilIdle();
+ EXPECT_EQ(1, key.number());
+
+ // IDBCursor.continue()
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks(&key));
+ platform_->RunUntilIdle();
+ EXPECT_EQ(2, key.number());
+
+ // IDBCursor.advance(2)
+ cursor_->Advance(2, new MockContinueCallbacks(&key));
+ platform_->RunUntilIdle();
+ EXPECT_EQ(4, key.number());
+
+ EXPECT_EQ(0, mock_cursor_->advance_calls());
+
+ // IDBCursor.advance(lots) - beyond the fetched amount
+ cursor_->Advance(WebIDBCursorImpl::kMaxPrefetchAmount,
+ new MockContinueCallbacks(&key));
+ platform_->RunUntilIdle();
+ EXPECT_EQ(1, mock_cursor_->advance_calls());
+ EXPECT_EQ(1, mock_cursor_->prefetch_calls());
+ EXPECT_EQ(static_cast<int>(WebIDBCursorImpl::kPrefetchContinueThreshold),
+ mock_cursor_->continue_calls());
+
+ cursor_.reset();
+ platform_->RunUntilIdle();
+ EXPECT_TRUE(mock_cursor_->destroyed());
+}
+
+TEST_F(WebIDBCursorImplTest, PrefetchReset) {
+ // Call continue() until prefetching should kick in.
+ int continue_calls = 0;
+ EXPECT_EQ(mock_cursor_->continue_calls(), 0);
+ for (int i = 0; i < WebIDBCursorImpl::kPrefetchContinueThreshold; ++i) {
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(++continue_calls, mock_cursor_->continue_calls());
+ EXPECT_EQ(0, mock_cursor_->prefetch_calls());
+ }
+
+ // Initiate the prefetch
+ cursor_->CursorContinue(null_key_.View(), null_key_.View(),
+ new MockContinueCallbacks());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(continue_calls, mock_cursor_->continue_calls());
+ EXPECT_EQ(1, mock_cursor_->prefetch_calls());
+ EXPECT_EQ(0, mock_cursor_->reset_calls());
+
+ // Now invalidate it
+ cursor_->ResetPrefetchCache();
+
+ // No reset should have been sent since nothing has been received yet.
+ platform_->RunUntilIdle();
+ EXPECT_EQ(0, mock_cursor_->reset_calls());
+
+ // Fill the prefetch cache as requested.
+ int prefetch_count = mock_cursor_->last_prefetch_count();
+ Vector<WebIDBKey> keys(prefetch_count);
+ Vector<WebIDBKey> primary_keys(prefetch_count);
+ Vector<WebIDBValue> values;
+ for (int i = 0; i < prefetch_count; ++i)
+ values.emplace_back(WebData(), WebVector<WebBlobInfo>());
+ cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys),
+ std::move(values));
+
+ // No reset should have been sent since prefetch data hasn't been used.
+ platform_->RunUntilIdle();
+ EXPECT_EQ(0, mock_cursor_->reset_calls());
+
+ // The real dispatcher would call cursor->CachedContinue(), so do that:
+ MockContinueCallbacks callbacks;
+ cursor_->CachedContinue(&callbacks);
+
+ // Now the cursor should have reset the rest of the cache.
+ platform_->RunUntilIdle();
+ EXPECT_EQ(1, mock_cursor_->reset_calls());
+ EXPECT_EQ(1, mock_cursor_->last_used_count());
+
+ cursor_.reset();
+ platform_->RunUntilIdle();
+ EXPECT_TRUE(mock_cursor_->destroyed());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database.h
new file mode 100644
index 00000000000..c98ae6098ff
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_DATABASE_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_DATABASE_H_
+
+#include <bitset>
+
+#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+class WebData;
+class WebIDBCallbacks;
+class WebIDBKeyPath;
+class WebIDBKeyRange;
+
+class MODULES_EXPORT WebIDBDatabase {
+ public:
+ virtual ~WebIDBDatabase() = default;
+
+ virtual void CreateObjectStore(long long transaction_id,
+ long long object_store_id,
+ const String& name,
+ const WebIDBKeyPath&,
+ bool auto_increment) = 0;
+ virtual void DeleteObjectStore(long long transaction_id,
+ long long object_store_id) = 0;
+ virtual void RenameObjectStore(long long transaction_id,
+ long long object_store_id,
+ const String& name) = 0;
+ virtual void CreateTransaction(long long id,
+ const Vector<int64_t>& scope,
+ mojom::IDBTransactionMode) = 0;
+ virtual void Close() = 0;
+ virtual void VersionChangeIgnored() = 0;
+
+ virtual void Abort(long long transaction_id) = 0;
+ virtual void Commit(long long transaction_id) = 0;
+
+ virtual void CreateIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const String& name,
+ const WebIDBKeyPath&,
+ bool unique,
+ bool multi_entry) = 0;
+ virtual void DeleteIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id) = 0;
+ virtual void RenameIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const String& new_name) = 0;
+
+ static const long long kMinimumIndexId = 30;
+
+ virtual void AddObserver(
+ long long transaction_id,
+ int32_t observer_id,
+ bool include_transaction,
+ bool no_records,
+ bool values,
+ std::bitset<blink::kIDBOperationTypeCount> operation_types) = 0;
+ virtual void RemoveObservers(
+ const Vector<int32_t>& observer_ids_to_remove) = 0;
+ virtual void Get(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange&,
+ bool key_only,
+ WebIDBCallbacks*) = 0;
+ virtual void GetAll(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange&,
+ long long max_count,
+ bool key_only,
+ WebIDBCallbacks*) = 0;
+ virtual void Put(long long transaction_id,
+ long long object_store_id,
+ const WebData& value,
+ const Vector<WebBlobInfo>&,
+ WebIDBKeyView primary_key,
+ mojom::IDBPutMode,
+ WebIDBCallbacks*,
+ const Vector<WebIDBIndexKeys>&) = 0;
+ virtual void SetIndexKeys(long long transaction_id,
+ long long object_store_id,
+ WebIDBKeyView primary_key,
+ const Vector<WebIDBIndexKeys>&) = 0;
+ virtual void SetIndexesReady(long long transaction_id,
+ long long object_store_id,
+ const Vector<int64_t>& index_ids) = 0;
+ virtual void OpenCursor(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange&,
+ mojom::IDBCursorDirection,
+ bool key_only,
+ mojom::IDBTaskType,
+ WebIDBCallbacks*) = 0;
+ virtual void Count(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange&,
+ WebIDBCallbacks*) = 0;
+ virtual void Delete(long long transaction_id,
+ long long object_store_id,
+ WebIDBKeyView primary_key,
+ WebIDBCallbacks*) = 0;
+ virtual void DeleteRange(long long transaction_id,
+ long long object_store_id,
+ const WebIDBKeyRange&,
+ WebIDBCallbacks*) = 0;
+ virtual void Clear(long long transaction_id,
+ long long object_store_id,
+ WebIDBCallbacks*) = 0;
+
+ protected:
+ WebIDBDatabase() = default;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_DATABASE_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.cc b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.cc
new file mode 100644
index 00000000000..c41c23e249f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.cc
@@ -0,0 +1,320 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h"
+
+#include <stddef.h>
+
+#include <string>
+#include <vector>
+
+#include "base/format_macros.h"
+#include "base/memory/ptr_util.h"
+#include "mojo/public/cpp/bindings/strong_associated_binding.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key.h"
+#include "third_party/blink/public/platform/file_path_conversion.h"
+#include "third_party/blink/public/platform/modules/indexeddb/indexed_db_key_builder.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_error.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_key_path.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_metadata.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h"
+
+namespace blink {
+
+WebIDBDatabaseImpl::WebIDBDatabaseImpl(
+ mojom::blink::IDBDatabaseAssociatedPtrInfo database_info)
+ : database_(std::move(database_info)) {}
+
+WebIDBDatabaseImpl::~WebIDBDatabaseImpl() = default;
+
+void WebIDBDatabaseImpl::CreateObjectStore(long long transaction_id,
+ long long object_store_id,
+ const String& name,
+ const WebIDBKeyPath& key_path,
+ bool auto_increment) {
+ database_->CreateObjectStore(transaction_id, object_store_id, name, key_path,
+ auto_increment);
+}
+
+void WebIDBDatabaseImpl::DeleteObjectStore(long long transaction_id,
+ long long object_store_id) {
+ database_->DeleteObjectStore(transaction_id, object_store_id);
+}
+
+void WebIDBDatabaseImpl::RenameObjectStore(long long transaction_id,
+ long long object_store_id,
+ const String& new_name) {
+ database_->RenameObjectStore(transaction_id, object_store_id, new_name);
+}
+
+void WebIDBDatabaseImpl::CreateTransaction(
+ long long transaction_id,
+ const Vector<int64_t>& object_store_ids,
+ mojom::IDBTransactionMode mode) {
+ database_->CreateTransaction(transaction_id, object_store_ids, mode);
+}
+
+void WebIDBDatabaseImpl::Close() {
+ database_->Close();
+}
+
+void WebIDBDatabaseImpl::VersionChangeIgnored() {
+ database_->VersionChangeIgnored();
+}
+
+void WebIDBDatabaseImpl::AddObserver(
+ long long transaction_id,
+ int32_t observer_id,
+ bool include_transaction,
+ bool no_records,
+ bool values,
+ std::bitset<blink::kIDBOperationTypeCount> operation_types) {
+ static_assert(kIDBOperationTypeCount < sizeof(uint32_t) * CHAR_BIT,
+ "IDBOperationTypeCount exceeds size of uint32_t");
+ database_->AddObserver(transaction_id, observer_id, include_transaction,
+ no_records, values,
+ static_cast<uint32_t>(operation_types.to_ulong()));
+}
+
+void WebIDBDatabaseImpl::RemoveObservers(const Vector<int32_t>& observer_ids) {
+ database_->RemoveObservers(observer_ids);
+}
+
+void WebIDBDatabaseImpl::Get(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange& key_range,
+ bool key_only,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->Get(transaction_id, object_store_id, index_id, key_range, key_only,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::GetAll(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange& key_range,
+ long long max_count,
+ bool key_only,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->GetAll(transaction_id, object_store_id, index_id, key_range,
+ key_only, max_count,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::Put(long long transaction_id,
+ long long object_store_id,
+ const WebData& value,
+ const Vector<WebBlobInfo>& web_blob_info,
+ WebIDBKeyView web_primary_key,
+ mojom::IDBPutMode put_mode,
+ WebIDBCallbacks* callbacks,
+ const Vector<WebIDBIndexKeys>& index_keys) {
+ WebIDBKey primary_key = WebIDBKeyBuilder::Build(web_primary_key);
+
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto mojo_value = mojom::blink::IDBValue::New();
+
+ // mojo_value->bits initialization.
+ value.ForEachSegment([&mojo_value](const char* segment, size_t segment_size,
+ size_t segment_offset) {
+ const auto& segment_span = base::make_span(segment, segment + segment_size);
+ mojo_value->bits.AppendRange(segment_span.begin(), segment_span.end());
+ return true;
+ });
+
+ // mojo_value->blob_or_file_info initialization.
+ mojo_value->blob_or_file_info.ReserveInitialCapacity(web_blob_info.size());
+ for (const WebBlobInfo& info : web_blob_info) {
+ auto blob_info = mojom::blink::IDBBlobInfo::New();
+ if (info.IsFile()) {
+ blob_info->file = mojom::blink::IDBFileInfo::New();
+ blob_info->file->path = WebStringToFilePath(info.FilePath());
+ String name = info.FileName();
+ if (name.IsNull())
+ name = g_empty_string;
+ blob_info->file->name = name;
+ blob_info->file->last_modified =
+ base::Time::FromDoubleT(info.LastModified());
+ }
+ blob_info->size = info.size();
+ blob_info->uuid = info.Uuid();
+ DCHECK(!blob_info->uuid.IsEmpty());
+ String mime_type = info.GetType();
+ if (mime_type.IsNull())
+ mime_type = g_empty_string;
+ blob_info->mime_type = mime_type;
+ blob_info->blob = mojom::blink::BlobPtrInfo(info.CloneBlobHandle(),
+ mojom::blink::Blob::Version_);
+ mojo_value->blob_or_file_info.push_back(std::move(blob_info));
+ }
+
+ size_t index_keys_size = 0;
+ for (const auto& index_key : index_keys) {
+ index_keys_size++; // Account for index_key.first (int64_t).
+ for (const auto& key : index_key.second) {
+ index_keys_size += key.SizeEstimate();
+ }
+ }
+
+ size_t arg_size =
+ mojo_value->bits.size() + primary_key.SizeEstimate() + index_keys_size;
+ if (arg_size >= max_put_value_size_) {
+ callbacks->OnError(blink::WebIDBDatabaseError(
+ blink::kWebIDBDatabaseExceptionUnknownError,
+ WebString(
+ String::Format("The serialized keys and/or value are too large"
+ " (size=%" PRIuS " bytes, max=%" PRIuS " bytes).",
+ arg_size, max_put_value_size_))));
+ return;
+ }
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->Put(transaction_id, object_store_id, std::move(mojo_value),
+ std::move(primary_key), put_mode, index_keys,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::SetIndexKeys(
+ long long transaction_id,
+ long long object_store_id,
+ WebIDBKeyView primary_key,
+ const Vector<WebIDBIndexKeys>& index_keys) {
+ IndexedDBKey temp(IndexedDBKeyBuilder::Build(primary_key));
+ database_->SetIndexKeys(transaction_id, object_store_id,
+ WebIDBKeyBuilder::Build(temp), std::move(index_keys));
+}
+
+void WebIDBDatabaseImpl::SetIndexesReady(long long transaction_id,
+ long long object_store_id,
+ const Vector<int64_t>& index_ids) {
+ database_->SetIndexesReady(transaction_id, object_store_id,
+ std::move(index_ids));
+}
+
+void WebIDBDatabaseImpl::OpenCursor(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange& key_range,
+ mojom::IDBCursorDirection direction,
+ bool key_only,
+ mojom::IDBTaskType task_type,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->OpenCursor(transaction_id, object_store_id, index_id, key_range,
+ direction, key_only, task_type,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::Count(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const WebIDBKeyRange& key_range,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->Count(transaction_id, object_store_id, index_id, key_range,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::Delete(long long transaction_id,
+ long long object_store_id,
+ WebIDBKeyView primary_key,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->DeleteRange(transaction_id, object_store_id,
+ WebIDBKeyRangeBuilder::Build(primary_key),
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::DeleteRange(long long transaction_id,
+ long long object_store_id,
+ const WebIDBKeyRange& key_range,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->DeleteRange(transaction_id, object_store_id, key_range,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::Clear(long long transaction_id,
+ long long object_store_id,
+ WebIDBCallbacks* callbacks) {
+ IndexedDBDispatcher::ResetCursorPrefetchCaches(transaction_id, nullptr);
+
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ database_->Clear(transaction_id, object_store_id,
+ GetCallbacksProxy(std::move(callbacks_impl)));
+}
+
+void WebIDBDatabaseImpl::CreateIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const String& name,
+ const WebIDBKeyPath& key_path,
+ bool unique,
+ bool multi_entry) {
+ database_->CreateIndex(transaction_id, object_store_id, index_id, name,
+ key_path, unique, multi_entry);
+}
+
+void WebIDBDatabaseImpl::DeleteIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id) {
+ database_->DeleteIndex(transaction_id, object_store_id, index_id);
+}
+
+void WebIDBDatabaseImpl::RenameIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const String& new_name) {
+ DCHECK(!new_name.IsNull());
+ database_->RenameIndex(transaction_id, object_store_id, index_id, new_name);
+}
+
+void WebIDBDatabaseImpl::Abort(long long transaction_id) {
+ database_->Abort(transaction_id);
+}
+
+void WebIDBDatabaseImpl::Commit(long long transaction_id) {
+ database_->Commit(transaction_id);
+}
+
+mojom::blink::IDBCallbacksAssociatedPtrInfo
+WebIDBDatabaseImpl::GetCallbacksProxy(
+ std::unique_ptr<IndexedDBCallbacksImpl> callbacks) {
+ mojom::blink::IDBCallbacksAssociatedPtrInfo ptr_info;
+ auto request = mojo::MakeRequest(&ptr_info);
+ mojo::MakeStrongAssociatedBinding(std::move(callbacks), std::move(request));
+ return ptr_info;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h
new file mode 100644
index 00000000000..b4df30eb822
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h
@@ -0,0 +1,145 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_DATABASE_IMPL_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_DATABASE_IMPL_H_
+
+#include <stdint.h>
+
+#include <set>
+
+#include "base/single_thread_task_runner.h"
+#include "third_party/blink/public/common/indexeddb/web_idb_types.h"
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace blink {
+class IndexedDBCallbacksImpl;
+class WebBlobInfo;
+class WebIDBCallbacks;
+
+class MODULES_EXPORT WebIDBDatabaseImpl : public blink::WebIDBDatabase {
+ public:
+ WebIDBDatabaseImpl(mojom::blink::IDBDatabaseAssociatedPtrInfo database);
+ ~WebIDBDatabaseImpl() override;
+
+ // blink::WebIDBDatabase
+ void CreateObjectStore(long long transaction_id,
+ long long objectstore_id,
+ const String& name,
+ const blink::WebIDBKeyPath&,
+ bool auto_increment) override;
+ void DeleteObjectStore(long long transaction_id,
+ long long object_store_id) override;
+ void RenameObjectStore(long long transaction_id,
+ long long object_store_id,
+ const String& new_name) override;
+ void CreateTransaction(long long transaction_id,
+ const Vector<int64_t>& scope,
+ mojom::IDBTransactionMode mode) override;
+
+ void Close() override;
+ void VersionChangeIgnored() override;
+
+ void AddObserver(
+ long long transaction_id,
+ int32_t observer_id,
+ bool include_transaction,
+ bool no_records,
+ bool values,
+ std::bitset<blink::kIDBOperationTypeCount> operation_types) override;
+ void RemoveObservers(const Vector<int32_t>& observer_ids) override;
+
+ void Get(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const blink::WebIDBKeyRange&,
+ bool key_only,
+ blink::WebIDBCallbacks*) override;
+ void GetAll(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const blink::WebIDBKeyRange&,
+ long long max_count,
+ bool key_only,
+ blink::WebIDBCallbacks*) override;
+ void Put(long long transaction_id,
+ long long object_store_id,
+ const blink::WebData& value,
+ const Vector<blink::WebBlobInfo>&,
+ blink::WebIDBKeyView primary_key,
+ mojom::IDBPutMode,
+ blink::WebIDBCallbacks*,
+ const Vector<blink::WebIDBIndexKeys>&) override;
+ void SetIndexKeys(long long transaction_id,
+ long long object_store_id,
+ blink::WebIDBKeyView primary_key,
+ const Vector<blink::WebIDBIndexKeys>&) override;
+ void SetIndexesReady(long long transaction_id,
+ long long object_store_id,
+ const Vector<int64_t>& index_ids) override;
+ void OpenCursor(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const blink::WebIDBKeyRange&,
+ mojom::IDBCursorDirection direction,
+ bool key_only,
+ mojom::IDBTaskType,
+ blink::WebIDBCallbacks*) override;
+ void Count(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const blink::WebIDBKeyRange&,
+ blink::WebIDBCallbacks*) override;
+ void Delete(long long transaction_id,
+ long long object_store_id,
+ blink::WebIDBKeyView primary_key,
+ blink::WebIDBCallbacks*) override;
+ void DeleteRange(long long transaction_id,
+ long long object_store_id,
+ const blink::WebIDBKeyRange&,
+ blink::WebIDBCallbacks*) override;
+ void Clear(long long transaction_id,
+ long long object_store_id,
+ blink::WebIDBCallbacks*) override;
+ void CreateIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const String& name,
+ const blink::WebIDBKeyPath&,
+ bool unique,
+ bool multi_entry) override;
+ void DeleteIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id) override;
+ void RenameIndex(long long transaction_id,
+ long long object_store_id,
+ long long index_id,
+ const String& new_name) override;
+ void Abort(long long transaction_id) override;
+ void Commit(long long transaction_id) override;
+
+ private:
+ mojom::blink::IDBCallbacksAssociatedPtrInfo GetCallbacksProxy(
+ std::unique_ptr<IndexedDBCallbacksImpl> callbacks);
+
+ FRIEND_TEST_ALL_PREFIXES(WebIDBDatabaseImplTest, ValueSizeTest);
+ FRIEND_TEST_ALL_PREFIXES(WebIDBDatabaseImplTest, KeyAndValueSizeTest);
+
+ // Maximum size (in bytes) of value/key pair allowed for put requests. Any
+ // requests larger than this size will be rejected.
+ // Used by unit tests to exercise behavior without allocating huge chunks
+ // of memory.
+ size_t max_put_value_size_ =
+ mojom::blink::kIDBMaxMessageSize - mojom::blink::kIDBMaxMessageOverhead;
+
+ std::set<int32_t> observer_ids_;
+ mojom::blink::IDBDatabaseAssociatedPtr database_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_DATABASE_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl_unittest.cc b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl_unittest.cc
new file mode 100644
index 00000000000..42f434233c4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_database_impl_unittest.cc
@@ -0,0 +1,93 @@
+// 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 <stddef.h>
+#include <stdint.h>
+
+#include <memory>
+
+#include "base/macros.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/common/indexeddb/indexeddb_key.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_blob_info.h"
+#include "third_party/blink/public/platform/web_data.h"
+#include "third_party/blink/public/web/web_heap.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_database_impl.h"
+
+using testing::_;
+using testing::Invoke;
+using testing::StrictMock;
+using testing::WithArgs;
+
+namespace blink {
+
+class WebIDBDatabaseImplTest : public testing::Test {};
+
+TEST_F(WebIDBDatabaseImplTest, ValueSizeTest) {
+ // For testing use a much smaller maximum size to prevent allocating >100 MB
+ // of memory, which crashes on memory-constrained systems.
+ const size_t kMaxValueSizeForTesting = 10 * 1024 * 1024; // 10 MB
+
+ const std::vector<char> data(kMaxValueSizeForTesting + 1);
+ const WebData value(&data.front(), data.size());
+ const Vector<WebBlobInfo> blob_info;
+ const WebIDBKey key = WebIDBKey::CreateNumber(0);
+ const int64_t transaction_id = 1;
+ const int64_t object_store_id = 2;
+ StrictMock<MockWebIDBCallbacks> callbacks;
+
+ ASSERT_GT(value.size() + key.SizeEstimate(), kMaxValueSizeForTesting);
+ ThreadState::Current()->CollectAllGarbage();
+ EXPECT_CALL(callbacks, OnError(_)).Times(1);
+
+ WebIDBDatabaseImpl database_impl(nullptr);
+ database_impl.max_put_value_size_ = kMaxValueSizeForTesting;
+ database_impl.Put(transaction_id, object_store_id, value, blob_info,
+ key.View(), mojom::IDBPutMode::AddOrUpdate, &callbacks,
+ Vector<blink::WebIDBIndexKeys>());
+}
+
+TEST_F(WebIDBDatabaseImplTest, KeyAndValueSizeTest) {
+ // For testing use a much smaller maximum size to prevent allocating >100 MB
+ // of memory, which crashes on memory-constrained systems.
+ const size_t kMaxValueSizeForTesting = 10 * 1024 * 1024; // 10 MB
+ const size_t kKeySize = 1024 * 1024;
+
+ const std::vector<char> data(kMaxValueSizeForTesting - kKeySize);
+ const WebData value(&data.front(), data.size());
+ const Vector<WebBlobInfo> blob_info;
+ const int64_t transaction_id = 1;
+ const int64_t object_store_id = 2;
+ StrictMock<MockWebIDBCallbacks> callbacks;
+
+ // For this test, we want IDBKey::SizeEstimate() minus kKeySize to be the
+ // smallest value > 0. An IDBKey with a string has a size_estimate_ equal to
+ // kOverheadSize (~16) + (string.length * sizeof(UChar)). Create
+ // |kKeySize / sizeof(UChar)| characters in String.
+ const unsigned int number_of_chars = kKeySize / sizeof(UChar);
+ Vector<UChar> key_string_vector;
+ key_string_vector.ReserveInitialCapacity(number_of_chars);
+ key_string_vector.Fill(u'0', number_of_chars);
+ String key_string(key_string_vector);
+ DCHECK_EQ(key_string.length(), number_of_chars);
+
+ WebIDBKey key = WebIDBKey::CreateString(key_string);
+ DCHECK_EQ(value.size(), kMaxValueSizeForTesting - kKeySize);
+ DCHECK_GT(key.SizeEstimate() - kKeySize, static_cast<unsigned long>(0));
+ DCHECK_GT(value.size() + key.SizeEstimate(), kMaxValueSizeForTesting);
+
+ ThreadState::Current()->CollectAllGarbage();
+ EXPECT_CALL(callbacks, OnError(_)).Times(1);
+
+ WebIDBDatabaseImpl database_impl(nullptr);
+ database_impl.max_put_value_size_ = kMaxValueSizeForTesting;
+ database_impl.Put(transaction_id, object_store_id, value, blob_info,
+ key.View(), mojom::IDBPutMode::AddOrUpdate, &callbacks,
+ Vector<blink::WebIDBIndexKeys>());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory.h
new file mode 100644
index 00000000000..71a2ce00a59
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_FACTORY_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_FACTORY_H_
+
+#include "base/single_thread_task_runner.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace base {
+class SingleThreadTaskRunner;
+}
+
+namespace blink {
+
+class WebIDBCallbacks;
+class WebIDBDatabaseCallbacks;
+class WebSecurityOrigin;
+class WebString;
+
+class MODULES_EXPORT WebIDBFactory {
+ public:
+ virtual ~WebIDBFactory() = default;
+
+ virtual void GetDatabaseInfo(WebIDBCallbacks*,
+ const WebSecurityOrigin&,
+ scoped_refptr<base::SingleThreadTaskRunner>) = 0;
+ virtual void GetDatabaseNames(
+ WebIDBCallbacks*,
+ const WebSecurityOrigin&,
+ scoped_refptr<base::SingleThreadTaskRunner>) = 0;
+ virtual void Open(const WebString& name,
+ long long version,
+ long long transaction_id,
+ WebIDBCallbacks*,
+ WebIDBDatabaseCallbacks*,
+ const WebSecurityOrigin&,
+ scoped_refptr<base::SingleThreadTaskRunner>) = 0;
+ virtual void DeleteDatabase(const WebString& name,
+ WebIDBCallbacks*,
+ const WebSecurityOrigin&,
+ bool force_close,
+ scoped_refptr<base::SingleThreadTaskRunner>) = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_FACTORY_H_
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.cc b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.cc
new file mode 100644
index 00000000000..f158e08cd10
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.cc
@@ -0,0 +1,95 @@
+// 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 "third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.h"
+
+#include "base/memory/ptr_util.h"
+#include "mojo/public/cpp/bindings/strong_associated_binding.h"
+#include "third_party/blink/public/platform/web_security_origin.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h"
+
+namespace blink {
+
+WebIDBFactoryImpl::WebIDBFactoryImpl(
+ mojom::blink::IDBFactoryPtrInfo factory_info)
+ : factory_(std::move(factory_info)) {}
+
+WebIDBFactoryImpl::~WebIDBFactoryImpl() = default;
+
+void WebIDBFactoryImpl::GetDatabaseInfo(
+ WebIDBCallbacks* callbacks,
+ const WebSecurityOrigin& origin,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), IndexedDBCallbacksImpl::kNoTransaction,
+ nullptr);
+ factory_->GetDatabaseInfo(GetCallbacksProxy(std::move(callbacks_impl)),
+ origin);
+}
+
+void WebIDBFactoryImpl::GetDatabaseNames(
+ WebIDBCallbacks* callbacks,
+ const WebSecurityOrigin& origin,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), IndexedDBCallbacksImpl::kNoTransaction,
+ nullptr);
+ factory_->GetDatabaseNames(GetCallbacksProxy(std::move(callbacks_impl)),
+ origin);
+}
+
+void WebIDBFactoryImpl::Open(
+ const WebString& name,
+ long long version,
+ long long transaction_id,
+ WebIDBCallbacks* callbacks,
+ WebIDBDatabaseCallbacks* database_callbacks,
+ const WebSecurityOrigin& origin,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), transaction_id, nullptr);
+ auto database_callbacks_impl =
+ std::make_unique<IndexedDBDatabaseCallbacksImpl>(
+ base::WrapUnique(database_callbacks));
+ DCHECK(!name.IsNull());
+ factory_->Open(GetCallbacksProxy(std::move(callbacks_impl)),
+ GetDatabaseCallbacksProxy(std::move(database_callbacks_impl)),
+ origin, name, version, transaction_id);
+}
+
+void WebIDBFactoryImpl::DeleteDatabase(
+ const WebString& name,
+ WebIDBCallbacks* callbacks,
+ const WebSecurityOrigin& origin,
+ bool force_close,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
+ auto callbacks_impl = std::make_unique<IndexedDBCallbacksImpl>(
+ base::WrapUnique(callbacks), IndexedDBCallbacksImpl::kNoTransaction,
+ nullptr);
+ DCHECK(!name.IsNull());
+ factory_->DeleteDatabase(GetCallbacksProxy(std::move(callbacks_impl)), origin,
+ name, force_close);
+}
+
+mojom::blink::IDBCallbacksAssociatedPtrInfo
+WebIDBFactoryImpl::GetCallbacksProxy(
+ std::unique_ptr<IndexedDBCallbacksImpl> callbacks) {
+ mojom::blink::IDBCallbacksAssociatedPtrInfo ptr_info;
+ auto request = mojo::MakeRequest(&ptr_info);
+ mojo::MakeStrongAssociatedBinding(std::move(callbacks), std::move(request));
+ return ptr_info;
+}
+
+mojom::blink::IDBDatabaseCallbacksAssociatedPtrInfo
+WebIDBFactoryImpl::GetDatabaseCallbacksProxy(
+ std::unique_ptr<IndexedDBDatabaseCallbacksImpl> callbacks) {
+ mojom::blink::IDBDatabaseCallbacksAssociatedPtrInfo ptr_info;
+ auto request = mojo::MakeRequest(&ptr_info);
+ mojo::MakeStrongAssociatedBinding(std::move(callbacks), std::move(request));
+ return ptr_info;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.h b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.h
new file mode 100644
index 00000000000..dbc69d838e3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/indexeddb/web_idb_factory_impl.h
@@ -0,0 +1,59 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_FACTORY_IMPL_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_FACTORY_IMPL_H_
+
+#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_callbacks.h"
+#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_callbacks.h"
+#include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_callbacks_impl.h"
+#include "third_party/blink/renderer/modules/indexeddb/indexed_db_database_callbacks_impl.h"
+#include "third_party/blink/renderer/modules/indexeddb/web_idb_factory.h"
+
+namespace blink {
+class WebSecurityOrigin;
+class WebString;
+
+class WebIDBFactoryImpl : public blink::WebIDBFactory {
+ public:
+ explicit WebIDBFactoryImpl(mojom::blink::IDBFactoryPtrInfo factory_info);
+ ~WebIDBFactoryImpl() override;
+
+ // See WebIDBFactory.h for documentation on these functions.
+ void GetDatabaseInfo(
+ blink::WebIDBCallbacks* callbacks,
+ const blink::WebSecurityOrigin& origin,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
+ void GetDatabaseNames(
+ blink::WebIDBCallbacks* callbacks,
+ const blink::WebSecurityOrigin& origin,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
+ void Open(const blink::WebString& name,
+ long long version,
+ long long transaction_id,
+ blink::WebIDBCallbacks* callbacks,
+ blink::WebIDBDatabaseCallbacks* databaseCallbacks,
+ const blink::WebSecurityOrigin& origin,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
+ void DeleteDatabase(
+ const blink::WebString& name,
+ blink::WebIDBCallbacks* callbacks,
+ const blink::WebSecurityOrigin& origin,
+ bool force_close,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
+
+ private:
+ mojom::blink::IDBCallbacksAssociatedPtrInfo GetCallbacksProxy(
+ std::unique_ptr<blink::IndexedDBCallbacksImpl> callbacks);
+ mojom::blink::IDBDatabaseCallbacksAssociatedPtrInfo GetDatabaseCallbacksProxy(
+ std::unique_ptr<blink::IndexedDBDatabaseCallbacksImpl> callbacks);
+
+ mojom::blink::IDBFactoryPtr factory_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_WEB_IDB_FACTORY_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/modules/installation/installation_service_impl.cc b/chromium/third_party/blink/renderer/modules/installation/installation_service_impl.cc
index b41e4328d61..021fd4f84f1 100644
--- a/chromium/third_party/blink/renderer/modules/installation/installation_service_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/installation/installation_service_impl.cc
@@ -33,7 +33,7 @@ void InstallationServiceImpl::OnInstall() {
if (!dom_window)
return;
- dom_window->DispatchEvent(*Event::Create(EventTypeNames::appinstalled));
+ dom_window->DispatchEvent(*Event::Create(event_type_names::kAppinstalled));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.cc b/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.cc
index 81c59a0ea7d..8524dc496c4 100644
--- a/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.cc
@@ -63,7 +63,8 @@ void InstalledAppController::ProvideTo(
LocalFrame& frame,
WebRelatedAppsFetcher* related_apps_fetcher) {
Supplement<LocalFrame>::ProvideTo(
- frame, new InstalledAppController(frame, related_apps_fetcher));
+ frame, MakeGarbageCollected<InstalledAppController>(
+ frame, related_apps_fetcher));
}
InstalledAppController* InstalledAppController::From(LocalFrame& frame) {
diff --git a/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.h b/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.h
index 1018ca37c7f..338c2b0c005 100644
--- a/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.h
+++ b/chromium/third_party/blink/renderer/modules/installedapp/installed_app_controller.h
@@ -31,6 +31,7 @@ class MODULES_EXPORT InstalledAppController final
public:
static const char kSupplementName[];
+ InstalledAppController(LocalFrame&, WebRelatedAppsFetcher*);
virtual ~InstalledAppController();
// Gets a list of related apps from the current page's manifest that belong
@@ -45,8 +46,6 @@ class MODULES_EXPORT InstalledAppController final
private:
class GetRelatedAppsCallbacks;
- InstalledAppController(LocalFrame&, WebRelatedAppsFetcher*);
-
// Inherited from ContextLifecycleObserver.
void ContextDestroyed(ExecutionContext*) override;
diff --git a/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc b/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc
index ed430f8b897..a17c784eeb0 100644
--- a/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc
+++ b/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc
@@ -36,7 +36,7 @@ NavigatorInstalledApp& NavigatorInstalledApp::From(Navigator& navigator) {
NavigatorInstalledApp* supplement =
Supplement<Navigator>::From<NavigatorInstalledApp>(navigator);
if (!supplement) {
- supplement = new NavigatorInstalledApp(navigator);
+ supplement = MakeGarbageCollected<NavigatorInstalledApp>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.h b/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.h
index 74a2b577e8a..fe19fd26a74 100644
--- a/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.h
+++ b/chromium/third_party/blink/renderer/modules/installedapp/navigator_installed_app.h
@@ -34,10 +34,9 @@ class NavigatorInstalledApp final
InstalledAppController* Controller();
- void Trace(blink::Visitor*) override;
-
- private:
explicit NavigatorInstalledApp(Navigator&);
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/installedapp/related_application.h b/chromium/third_party/blink/renderer/modules/installedapp/related_application.h
index 79e64d01eb4..fbddca666d9 100644
--- a/chromium/third_party/blink/renderer/modules/installedapp/related_application.h
+++ b/chromium/third_party/blink/renderer/modules/installedapp/related_application.h
@@ -18,9 +18,13 @@ class RelatedApplication final : public ScriptWrappable {
static RelatedApplication* Create(const String& platform,
const String& url,
const String& id) {
- return new RelatedApplication(platform, url, id);
+ return MakeGarbageCollected<RelatedApplication>(platform, url, id);
}
+ RelatedApplication(const String& platform,
+ const String& url,
+ const String& id)
+ : platform_(platform), url_(url), id_(id) {}
~RelatedApplication() override = default;
String platform() const { return platform_; }
@@ -28,11 +32,6 @@ class RelatedApplication final : public ScriptWrappable {
String id() const { return id_; }
private:
- RelatedApplication(const String& platform,
- const String& url,
- const String& id)
- : platform_(platform), url_(url), id_(id) {}
-
const String platform_;
const String url_;
const String id_;
diff --git a/chromium/third_party/blink/renderer/modules/keyboard/keyboard.cc b/chromium/third_party/blink/renderer/modules/keyboard/keyboard.cc
index 934fdb1208a..758cfde37da 100644
--- a/chromium/third_party/blink/renderer/modules/keyboard/keyboard.cc
+++ b/chromium/third_party/blink/renderer/modules/keyboard/keyboard.cc
@@ -12,8 +12,8 @@
namespace blink {
Keyboard::Keyboard(ExecutionContext* context)
- : keyboard_lock_(new KeyboardLock(context)),
- keyboard_layout_(new KeyboardLayout(context)) {}
+ : keyboard_lock_(MakeGarbageCollected<KeyboardLock>(context)),
+ keyboard_layout_(MakeGarbageCollected<KeyboardLayout>(context)) {}
Keyboard::~Keyboard() = default;
diff --git a/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout.cc b/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout.cc
index ab964f11fae..af4f02e627b 100644
--- a/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout.cc
+++ b/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout.cc
@@ -99,7 +99,7 @@ void KeyboardLayout::GotKeyboardLayoutMap(
switch (result->status) {
case mojom::blink::GetKeyboardLayoutMapStatus::kSuccess:
script_promise_resolver_->Resolve(
- new KeyboardLayoutMap(result->layout_map));
+ MakeGarbageCollected<KeyboardLayoutMap>(result->layout_map));
break;
case mojom::blink::GetKeyboardLayoutMapStatus::kFail:
script_promise_resolver_->Reject(
diff --git a/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.cc b/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.cc
index f71a3ea814a..65911926ef3 100644
--- a/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.cc
+++ b/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.cc
@@ -40,7 +40,7 @@ KeyboardLayoutMap::KeyboardLayoutMap(const HashMap<String, String>& map)
PairIterable<String, String>::IterationSource*
KeyboardLayoutMap::StartIteration(ScriptState*, ExceptionState&) {
- return new KeyboardLayoutMapIterationSource(*this);
+ return MakeGarbageCollected<KeyboardLayoutMapIterationSource>(*this);
}
bool KeyboardLayoutMap::GetMapEntry(ScriptState*,
diff --git a/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.idl b/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.idl
index 3a50176b6be..76d2acaa729 100644
--- a/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.idl
+++ b/chromium/third_party/blink/renderer/modules/keyboard/keyboard_layout_map.idl
@@ -5,7 +5,6 @@
// Keyboard Map specification: https://wicg.github.io/keyboard-map/
[
- RuntimeEnabled=KeyboardMap,
SecureContext
] interface KeyboardLayoutMap {
readonly maplike<DOMString, DOMString>;
diff --git a/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.cc b/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.cc
index c9d45743bef..55a9073870d 100644
--- a/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.cc
+++ b/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.cc
@@ -16,17 +16,17 @@ const char NavigatorKeyboard::kSupplementName[] = "NavigatorKeyboard";
NavigatorKeyboard::NavigatorKeyboard(Navigator& navigator)
: Supplement<Navigator>(navigator),
- keyboard_(
- new Keyboard(GetSupplementable()->GetFrame()
- ? GetSupplementable()->GetFrame()->GetDocument()
- : nullptr)) {}
+ keyboard_(MakeGarbageCollected<Keyboard>(
+ GetSupplementable()->GetFrame()
+ ? GetSupplementable()->GetFrame()->GetDocument()
+ : nullptr)) {}
// static
Keyboard* NavigatorKeyboard::keyboard(Navigator& navigator) {
NavigatorKeyboard* supplement =
Supplement<Navigator>::From<NavigatorKeyboard>(navigator);
if (!supplement) {
- supplement = new NavigatorKeyboard(navigator);
+ supplement = MakeGarbageCollected<NavigatorKeyboard>(navigator);
ProvideTo(navigator, supplement);
}
return supplement->keyboard_;
diff --git a/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.h b/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.h
index 0df1872d3ed..8ebfb08acaa 100644
--- a/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.h
+++ b/chromium/third_party/blink/renderer/modules/keyboard/navigator_keyboard.h
@@ -24,11 +24,11 @@ class NavigatorKeyboard final : public GarbageCollected<NavigatorKeyboard>,
static const char kSupplementName[];
static Keyboard* keyboard(Navigator&);
+ explicit NavigatorKeyboard(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorKeyboard(Navigator&);
-
Member<Keyboard> keyboard_;
};
diff --git a/chromium/third_party/blink/renderer/modules/locks/lock.cc b/chromium/third_party/blink/renderer/modules/locks/lock.cc
index 05f7c0c50b7..f8fd457420b 100644
--- a/chromium/third_party/blink/renderer/modules/locks/lock.cc
+++ b/chromium/third_party/blink/renderer/modules/locks/lock.cc
@@ -30,19 +30,20 @@ class Lock::ThenFunction final : public ScriptFunction {
static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
Lock* lock,
ResolveType type) {
- ThenFunction* self = new ThenFunction(script_state, lock, type);
+ ThenFunction* self =
+ MakeGarbageCollected<ThenFunction>(script_state, lock, type);
return self->BindToV8Function();
}
+ ThenFunction(ScriptState* script_state, Lock* lock, ResolveType type)
+ : ScriptFunction(script_state), lock_(lock), resolve_type_(type) {}
+
void Trace(blink::Visitor* visitor) override {
visitor->Trace(lock_);
ScriptFunction::Trace(visitor);
}
private:
- ThenFunction(ScriptState* script_state, Lock* lock, ResolveType type)
- : ScriptFunction(script_state), lock_(lock), resolve_type_(type) {}
-
ScriptValue Call(ScriptValue value) override {
DCHECK(lock_);
DCHECK(resolve_type_ == Fulfilled || resolve_type_ == Rejected);
@@ -65,7 +66,8 @@ Lock* Lock::Create(ScriptState* script_state,
mojom::blink::LockMode mode,
mojom::blink::LockHandlePtr handle,
LockManager* manager) {
- return new Lock(script_state, name, mode, std::move(handle), manager);
+ return MakeGarbageCollected<Lock>(script_state, name, mode, std::move(handle),
+ manager);
}
Lock::Lock(ScriptState* script_state,
diff --git a/chromium/third_party/blink/renderer/modules/locks/lock.h b/chromium/third_party/blink/renderer/modules/locks/lock.h
index 04a40bb91ad..a7bdc4f462f 100644
--- a/chromium/third_party/blink/renderer/modules/locks/lock.h
+++ b/chromium/third_party/blink/renderer/modules/locks/lock.h
@@ -30,6 +30,11 @@ class Lock final : public ScriptWrappable, public PausableObject {
mojom::blink::LockHandlePtr,
LockManager*);
+ Lock(ScriptState*,
+ const String& name,
+ mojom::blink::LockMode,
+ mojom::blink::LockHandlePtr,
+ LockManager*);
~Lock() override;
void Trace(blink::Visitor*) override;
@@ -52,12 +57,6 @@ class Lock final : public ScriptWrappable, public PausableObject {
private:
class ThenFunction;
- Lock(ScriptState*,
- const String& name,
- mojom::blink::LockMode,
- mojom::blink::LockHandlePtr,
- LockManager*);
-
void ReleaseIfHeld();
void OnConnectionError();
diff --git a/chromium/third_party/blink/renderer/modules/locks/lock.idl b/chromium/third_party/blink/renderer/modules/locks/lock.idl
index 24d444a7bb9..182914a5fd7 100644
--- a/chromium/third_party/blink/renderer/modules/locks/lock.idl
+++ b/chromium/third_party/blink/renderer/modules/locks/lock.idl
@@ -5,8 +5,7 @@
// https://wicg.github.io/web-locks/#lock
[
SecureContext,
- Exposed=(Window,Worker),
- RuntimeEnabled=WebLocksAPI
+ Exposed=(Window,Worker)
] interface Lock {
readonly attribute DOMString name;
readonly attribute LockMode mode;
diff --git a/chromium/third_party/blink/renderer/modules/locks/lock_manager.cc b/chromium/third_party/blink/renderer/modules/locks/lock_manager.cc
index 7c2ec8810d2..85ec1925765 100644
--- a/chromium/third_party/blink/renderer/modules/locks/lock_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/locks/lock_manager.cc
@@ -30,17 +30,18 @@ namespace {
constexpr char kRequestAbortedMessage[] = "The request was aborted.";
-LockInfo ToLockInfo(const mojom::blink::LockInfoPtr& record) {
- LockInfo info;
- info.setMode(Lock::ModeToString(record->mode));
- info.setName(record->name);
- info.setClientId(record->client_id);
+LockInfo* ToLockInfo(const mojom::blink::LockInfoPtr& record) {
+ LockInfo* info = LockInfo::Create();
+ ;
+ info->setMode(Lock::ModeToString(record->mode));
+ info->setName(record->name);
+ info->setClientId(record->client_id);
return info;
}
-HeapVector<LockInfo> ToLockInfos(
+HeapVector<Member<LockInfo>> ToLockInfos(
const Vector<mojom::blink::LockInfoPtr>& records) {
- HeapVector<LockInfo> out;
+ HeapVector<Member<LockInfo>> out;
out.ReserveInitialCapacity(records.size());
for (const auto& record : records)
out.push_back(ToLockInfo(record));
@@ -188,12 +189,13 @@ ScriptPromise LockManager::request(ScriptState* script_state,
const String& name,
V8LockGrantedCallback* callback,
ExceptionState& exception_state) {
- return request(script_state, name, LockOptions(), callback, exception_state);
+ return request(script_state, name, LockOptions::Create(), callback,
+ exception_state);
}
ScriptPromise LockManager::request(ScriptState* script_state,
const String& name,
- const LockOptions& options,
+ const LockOptions* options,
V8LockGrantedCallback* callback,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
@@ -219,7 +221,7 @@ ScriptPromise LockManager::request(ScriptState* script_state,
}
}
- mojom::blink::LockMode mode = Lock::StringToMode(options.mode());
+ mojom::blink::LockMode mode = Lock::StringToMode(options->mode());
// 6. Otherwise, if name starts with U+002D HYPHEN-MINUS (-), then reject
// promise with a "NotSupportedError" DOMException.
@@ -232,7 +234,7 @@ ScriptPromise LockManager::request(ScriptState* script_state,
// 7. Otherwise, if both options’ steal dictionary member and option’s
// ifAvailable dictionary member are true, then reject promise with a
// "NotSupportedError" DOMException.
- if (options.steal() && options.ifAvailable()) {
+ if (options->steal() && options->ifAvailable()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"The 'steal' and 'ifAvailable' options cannot be used together.");
@@ -242,7 +244,7 @@ ScriptPromise LockManager::request(ScriptState* script_state,
// 8. Otherwise, if options’ steal dictionary member is true and option’s mode
// dictionary member is not "exclusive", then reject promise with a
// "NotSupportedError" DOMException.
- if (options.steal() && mode != mojom::blink::LockMode::EXCLUSIVE) {
+ if (options->steal() && mode != mojom::blink::LockMode::EXCLUSIVE) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"The 'steal' option may only be used with 'exclusive' locks.");
@@ -253,13 +255,13 @@ ScriptPromise LockManager::request(ScriptState* script_state,
// of options’ steal dictionary member or options’ ifAvailable dictionary
// member is true, then reject promise with a "NotSupportedError"
// DOMException.
- if (options.hasSignal() && options.ifAvailable()) {
+ if (options->hasSignal() && options->ifAvailable()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"The 'signal' and 'ifAvailable' options cannot be used together.");
return ScriptPromise();
}
- if (options.hasSignal() && options.steal()) {
+ if (options->hasSignal() && options->steal()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"The 'signal' and 'steal' options cannot be used together.");
@@ -268,17 +270,17 @@ ScriptPromise LockManager::request(ScriptState* script_state,
// 10. Otherwise, if options’ signal dictionary member is present and its
// aborted flag is set, then reject promise with an "AbortError" DOMException.
- if (options.hasSignal() && options.signal()->aborted()) {
+ if (options->hasSignal() && options->signal()->aborted()) {
exception_state.ThrowDOMException(DOMExceptionCode::kAbortError,
kRequestAbortedMessage);
return ScriptPromise();
}
mojom::blink::LockManager::WaitMode wait =
- options.steal()
- ? mojom::blink::LockManager::WaitMode::PREEMPT
- : options.ifAvailable() ? mojom::blink::LockManager::WaitMode::NO_WAIT
- : mojom::blink::LockManager::WaitMode::WAIT;
+ options->steal() ? mojom::blink::LockManager::WaitMode::PREEMPT
+ : options->ifAvailable()
+ ? mojom::blink::LockManager::WaitMode::NO_WAIT
+ : mojom::blink::LockManager::WaitMode::WAIT;
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -288,19 +290,19 @@ ScriptPromise LockManager::request(ScriptState* script_state,
// promise, the current agent, environment’s id, origin, callback, name,
// options’ mode dictionary member, options’ ifAvailable dictionary member,
// and options’ steal dictionary member.
- LockRequestImpl* request = new LockRequestImpl(
+ LockRequestImpl* request = MakeGarbageCollected<LockRequestImpl>(
callback, resolver, name, mode, mojo::MakeRequest(&request_ptr), this);
AddPendingRequest(request);
// 11.2. If options’ signal dictionary member is present, then add the
// following abort steps to options’ signal dictionary member:
- if (options.hasSignal()) {
+ if (options->hasSignal()) {
// 11.2.1. Enqueue the steps to abort the request request to the lock task
// queue.
// 11.2.2. Reject promise with an "AbortError" DOMException.
- options.signal()->AddAlgorithm(WTF::Bind(&LockRequestImpl::Abort,
- WrapWeakPersistent(request),
- String(kRequestAbortedMessage)));
+ options->signal()->AddAlgorithm(WTF::Bind(&LockRequestImpl::Abort,
+ WrapWeakPersistent(request),
+ String(kRequestAbortedMessage)));
}
service_->RequestLock(name, mode, wait, std::move(request_ptr));
@@ -339,9 +341,9 @@ ScriptPromise LockManager::query(ScriptState* script_state,
[](ScriptPromiseResolver* resolver,
Vector<mojom::blink::LockInfoPtr> pending,
Vector<mojom::blink::LockInfoPtr> held) {
- LockManagerSnapshot snapshot;
- snapshot.setPending(ToLockInfos(pending));
- snapshot.setHeld(ToLockInfos(held));
+ LockManagerSnapshot* snapshot = LockManagerSnapshot::Create();
+ snapshot->setPending(ToLockInfos(pending));
+ snapshot->setHeld(ToLockInfos(held));
resolver->Resolve(snapshot);
},
WrapPersistent(resolver)));
diff --git a/chromium/third_party/blink/renderer/modules/locks/lock_manager.h b/chromium/third_party/blink/renderer/modules/locks/lock_manager.h
index cb113896b34..f7ba97ef787 100644
--- a/chromium/third_party/blink/renderer/modules/locks/lock_manager.h
+++ b/chromium/third_party/blink/renderer/modules/locks/lock_manager.h
@@ -34,7 +34,7 @@ class LockManager final : public ScriptWrappable,
ExceptionState&);
ScriptPromise request(ScriptState*,
const String& name,
- const LockOptions&,
+ const LockOptions*,
V8LockGrantedCallback*,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/modules/locks/lock_manager.idl b/chromium/third_party/blink/renderer/modules/locks/lock_manager.idl
index cfc6025d34a..dfa15d193b9 100644
--- a/chromium/third_party/blink/renderer/modules/locks/lock_manager.idl
+++ b/chromium/third_party/blink/renderer/modules/locks/lock_manager.idl
@@ -3,13 +3,12 @@
// found in the LICENSE file.
// https://wicg.github.io/web-locks/#callbackdef-lockgrantedcallback
-callback LockGrantedCallback = any (Lock lock);
+callback LockGrantedCallback = any (Lock? lock);
// https://wicg.github.io/web-locks/#lockmanager
[
SecureContext,
- Exposed=(Window,Worker),
- RuntimeEnabled=WebLocksAPI
+ Exposed=(Window,Worker)
] interface LockManager {
[CallWith=ScriptState, RaisesException, Measure] Promise<Lock> request(
DOMString name,
diff --git a/chromium/third_party/blink/renderer/modules/locks/navigator_locks.cc b/chromium/third_party/blink/renderer/modules/locks/navigator_locks.cc
index f18cfb50ecb..2ee6981a9e7 100644
--- a/chromium/third_party/blink/renderer/modules/locks/navigator_locks.cc
+++ b/chromium/third_party/blink/renderer/modules/locks/navigator_locks.cc
@@ -37,7 +37,7 @@ class NavigatorLocksImpl final : public GarbageCollected<NavigatorLocksImpl<T>>,
LockManager* GetLockManager(ExecutionContext* context) const {
if (!lock_manager_ && context) {
- lock_manager_ = new LockManager(context);
+ lock_manager_ = MakeGarbageCollected<LockManager>(context);
}
return lock_manager_.Get();
}
diff --git a/chromium/third_party/blink/renderer/modules/locks/navigator_locks.idl b/chromium/third_party/blink/renderer/modules/locks/navigator_locks.idl
index 7b9ef29b067..79d2709cc0c 100644
--- a/chromium/third_party/blink/renderer/modules/locks/navigator_locks.idl
+++ b/chromium/third_party/blink/renderer/modules/locks/navigator_locks.idl
@@ -6,8 +6,7 @@
[
SecureContext,
Exposed=Window,
- ImplementedAs=NavigatorLocks,
- RuntimeEnabled=WebLocksAPI
+ ImplementedAs=NavigatorLocks
] partial interface Navigator {
[CallWith=ScriptState] readonly attribute LockManager locks;
};
diff --git a/chromium/third_party/blink/renderer/modules/locks/worker_navigator_locks.idl b/chromium/third_party/blink/renderer/modules/locks/worker_navigator_locks.idl
index c8d07dc6945..cbbccdf050d 100644
--- a/chromium/third_party/blink/renderer/modules/locks/worker_navigator_locks.idl
+++ b/chromium/third_party/blink/renderer/modules/locks/worker_navigator_locks.idl
@@ -6,8 +6,7 @@
[
SecureContext,
Exposed=Worker,
- ImplementedAs=NavigatorLocks,
- RuntimeEnabled=WebLocksAPI
+ ImplementedAs=NavigatorLocks
] partial interface WorkerNavigator {
[CallWith=ScriptState] readonly attribute LockManager locks;
};
diff --git a/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.cc b/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.cc
index fa484250d3c..688a2a6971d 100644
--- a/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.cc
+++ b/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.cc
@@ -64,6 +64,8 @@ WTF::Vector<Purpose> ParsePurpose(const WTF::String& purpose) {
purpose_enum = Purpose::ANY;
} else if (lowercase_purpose == "badge") {
purpose_enum = Purpose::BADGE;
+ } else if (lowercase_purpose == "maskable") {
+ purpose_enum = Purpose::MASKABLE;
} else {
// TODO(rayankans): Issue developer warning.
continue;
@@ -95,13 +97,13 @@ WTF::String ParseType(const WTF::String& type) {
blink::mojom::blink::ManifestImageResourcePtr TypeConverter<
blink::mojom::blink::ManifestImageResourcePtr,
- blink::ManifestImageResource>::Convert(const blink::ManifestImageResource&
- image_resource) {
+ blink::ManifestImageResource*>::Convert(const blink::ManifestImageResource*
+ image_resource) {
auto image_resource_ptr = blink::mojom::blink::ManifestImageResource::New();
- image_resource_ptr->src = blink::KURL(image_resource.src());
- image_resource_ptr->sizes = ParseSizes(image_resource.sizes());
- image_resource_ptr->purpose = ParsePurpose(image_resource.purpose());
- image_resource_ptr->type = ParseType(image_resource.type());
+ image_resource_ptr->src = blink::KURL(image_resource->src());
+ image_resource_ptr->sizes = ParseSizes(image_resource->sizes());
+ image_resource_ptr->purpose = ParsePurpose(image_resource->purpose());
+ image_resource_ptr->type = ParseType(image_resource->type());
return image_resource_ptr;
}
@@ -110,22 +112,32 @@ blink::mojom::blink::ManifestImageResourcePtr TypeConverter<
namespace blink {
Manifest::ImageResource ConvertManifestImageResource(
- const ManifestImageResource& icon) {
+ const ManifestImageResource* icon) {
Manifest::ImageResource manifest_icon;
- manifest_icon.src = blink::KURL(icon.src());
- manifest_icon.type = WebString(mojo::ParseType(icon.type())).Utf16();
+ manifest_icon.src = blink::KURL(icon->src());
+ manifest_icon.type = WebString(mojo::ParseType(icon->type())).Utf16();
// Parse 'purpose'
- const auto purposes = mojo::ParsePurpose(icon.purpose());
+ const auto purposes = mojo::ParsePurpose(icon->purpose());
// ParsePurpose() would've weeded out any purposes that're not ANY or BADGE.
for (auto purpose : purposes) {
- manifest_icon.purpose.emplace_back(
- purpose == mojo::Purpose::ANY
- ? Manifest::ImageResource::Purpose::ANY
- : Manifest::ImageResource::Purpose::BADGE);
+ switch (purpose) {
+ case mojo::Purpose::ANY:
+ manifest_icon.purpose.emplace_back(
+ Manifest::ImageResource::Purpose::ANY);
+ break;
+ case mojo::Purpose::BADGE:
+ manifest_icon.purpose.emplace_back(
+ Manifest::ImageResource::Purpose::BADGE);
+ break;
+ case mojo::Purpose::MASKABLE:
+ manifest_icon.purpose.emplace_back(
+ Manifest::ImageResource::Purpose::MASKABLE);
+ break;
+ }
}
// Parse 'sizes'.
- WTF::Vector<WebSize> sizes = mojo::ParseSizes(icon.sizes());
+ WTF::Vector<WebSize> sizes = mojo::ParseSizes(icon->sizes());
for (const auto& size : sizes) {
manifest_icon.sizes.emplace_back(gfx::Size(size.height, size.width));
}
diff --git a/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.h b/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.h
index ad5589be61b..100eee1bc80 100644
--- a/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.h
+++ b/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters.h
@@ -13,7 +13,7 @@ namespace blink {
class ManifestImageResource;
MODULES_EXPORT Manifest::ImageResource ConvertManifestImageResource(
- const ManifestImageResource& image_resource);
+ const ManifestImageResource* image_resource);
} // namespace blink
@@ -22,9 +22,9 @@ namespace mojo {
template <>
struct MODULES_EXPORT
TypeConverter<blink::mojom::blink::ManifestImageResourcePtr,
- blink::ManifestImageResource> {
+ blink::ManifestImageResource*> {
static blink::mojom::blink::ManifestImageResourcePtr Convert(
- const blink::ManifestImageResource& image_resource);
+ const blink::ManifestImageResource* image_resource);
};
} // namespace mojo
diff --git a/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters_test.cc b/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters_test.cc
index a1bf8f1046e..53c9a706844 100644
--- a/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters_test.cc
+++ b/chromium/third_party/blink/renderer/modules/manifest/image_resource_type_converters_test.cc
@@ -22,53 +22,55 @@ using blink::mojom::blink::ManifestImageResourcePtr;
using blink::WebSize;
TEST(ImageResourceConverter, EmptySizesTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->sizes.IsEmpty());
// Explicitly set to empty.
- resource.setSizes("");
+ resource->setSizes("");
converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->sizes.IsEmpty());
}
TEST(ImageResourceConverter, ValidSizesTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
- resource.setSizes("2x3");
+ resource->setSizes("2x3");
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_EQ(converted->sizes.size(), 1u);
EXPECT_EQ(converted->sizes.front(), WebSize(2, 3));
- resource.setSizes("42X24");
+ resource->setSizes("42X24");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(converted->sizes.size(), 1u);
EXPECT_EQ(converted->sizes.front(), WebSize(42, 24));
- resource.setSizes("any");
+ resource->setSizes("any");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(converted->sizes.size(), 1u);
EXPECT_EQ(converted->sizes.front(), WebSize(0, 0));
- resource.setSizes("ANY");
+ resource->setSizes("ANY");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(converted->sizes.size(), 1u);
EXPECT_EQ(converted->sizes.front(), WebSize(0, 0));
- resource.setSizes("2x2 4x4");
+ resource->setSizes("2x2 4x4");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(converted->sizes.size(), 2u);
EXPECT_EQ(converted->sizes.front(), WebSize(2, 2));
EXPECT_EQ(converted->sizes.back(), WebSize(4, 4));
- resource.setSizes("2x2 4x4 2x2");
+ resource->setSizes("2x2 4x4 2x2");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(2u, converted->sizes.size());
EXPECT_EQ(WebSize(2, 2), converted->sizes.front());
EXPECT_EQ(WebSize(4, 4), converted->sizes.back());
- resource.setSizes(" 2x2 any");
+ resource->setSizes(" 2x2 any");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(2u, converted->sizes.size());
EXPECT_EQ(WebSize(2, 2), converted->sizes.front());
@@ -76,57 +78,60 @@ TEST(ImageResourceConverter, ValidSizesTest) {
}
TEST(ImageResourceConverter, InvalidSizesTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
- resource.setSizes("02x3");
+ resource->setSizes("02x3");
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->sizes.IsEmpty());
- resource.setSizes("42X024");
+ resource->setSizes("42X024");
converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->sizes.IsEmpty());
- resource.setSizes("42x");
+ resource->setSizes("42x");
converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->sizes.IsEmpty());
- resource.setSizes("foo");
+ resource->setSizes("foo");
converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->sizes.IsEmpty());
}
TEST(ImageResourceConverter, EmptyPurposeTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->purpose.IsEmpty());
// Explicitly set to empty.
- resource.setPurpose("");
+ resource->setPurpose("");
converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->purpose.IsEmpty());
}
TEST(ImageResourceConverter, ValidPurposeTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
- resource.setPurpose("any");
+ resource->setPurpose("any");
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_EQ(1u, converted->purpose.size());
ASSERT_EQ(Purpose::ANY, converted->purpose.front());
- resource.setPurpose(" Badge");
+ resource->setPurpose(" Badge");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(1u, converted->purpose.size());
ASSERT_EQ(Purpose::BADGE, converted->purpose.front());
- resource.setPurpose(" Badge AnY");
+ resource->setPurpose(" Badge AnY");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(2u, converted->purpose.size());
ASSERT_EQ(Purpose::BADGE, converted->purpose.front());
ASSERT_EQ(Purpose::ANY, converted->purpose.back());
- resource.setPurpose("any badge AnY");
+ resource->setPurpose("any badge AnY");
converted = ManifestImageResource::From(resource);
ASSERT_EQ(2u, converted->purpose.size());
ASSERT_EQ(Purpose::ANY, converted->purpose.front());
@@ -134,47 +139,52 @@ TEST(ImageResourceConverter, ValidPurposeTest) {
}
TEST(ImageResourceConverter, InvalidPurposeTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
- resource.setPurpose("any?");
+ resource->setPurpose("any?");
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->purpose.IsEmpty());
}
TEST(ImageResourceConverter, EmptyTypeTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->type.IsEmpty());
// Explicitly set to empty.
- resource.setType("");
+ resource->setType("");
converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->type.IsEmpty());
}
TEST(ImageResourceConverter, InvalidTypeTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
- resource.setType("image/NOTVALID!");
+ resource->setType("image/NOTVALID!");
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
ASSERT_TRUE(converted->type.IsEmpty());
}
TEST(ImageResourceConverter, ValidTypeTest) {
- blink::ManifestImageResource resource;
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
- resource.setType("image/jpeg");
+ resource->setType("image/jpeg");
ManifestImageResourcePtr converted = ManifestImageResource::From(resource);
EXPECT_EQ("image/jpeg", converted->type);
}
TEST(ImageResourceConverter, ExampleValueTest) {
- blink::ManifestImageResource resource;
- resource.setSrc("http://example.com/lolcat.jpg");
- resource.setPurpose("BADGE");
- resource.setSizes("32x32 64x64 128x128");
- resource.setType("image/jpeg");
+ blink::ManifestImageResource* resource =
+ blink::ManifestImageResource::Create();
+ resource->setSrc("http://example.com/lolcat.jpg");
+ resource->setPurpose("BADGE");
+ resource->setSizes("32x32 64x64 128x128");
+ resource->setType("image/jpeg");
auto expected_resource = ManifestImageResource::New();
expected_resource->src = blink::KURL("http://example.com/lolcat.jpg");
@@ -186,11 +196,11 @@ TEST(ImageResourceConverter, ExampleValueTest) {
}
TEST(ImageResourceConverter, BlinkToMojoTypeTest) {
- blink::ManifestImageResource icon;
- icon.setSrc("http://example.com/lolcat.jpg");
- icon.setPurpose("BADGE");
- icon.setSizes("32x32 64x64 128x128");
- icon.setType("image/jpeg");
+ blink::ManifestImageResource* icon = blink::ManifestImageResource::Create();
+ icon->setSrc("http://example.com/lolcat.jpg");
+ icon->setPurpose("BADGE");
+ icon->setSizes("32x32 64x64 128x128");
+ icon->setType("image/jpeg");
blink::Manifest::ImageResource mojo_icon =
blink::ConvertManifestImageResource(icon);
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/BUILD.gn b/chromium/third_party/blink/renderer/modules/media_capabilities/BUILD.gn
index 022538b47a8..d37c6e8eece 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/BUILD.gn
@@ -8,8 +8,10 @@ blink_modules_sources("media_capabilities") {
sources = [
"media_capabilities.cc",
"media_capabilities.h",
- "media_capabilities_info.cc",
- "media_capabilities_info.h",
+ "media_capabilities_decoding_info_callbacks.cc",
+ "media_capabilities_decoding_info_callbacks.h",
+ "media_capabilities_encoding_info_callbacks.cc",
+ "media_capabilities_encoding_info_callbacks.h",
"navigator_media_capabilities.cc",
"navigator_media_capabilities.h",
]
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/DEPS b/chromium/third_party/blink/renderer/modules/media_capabilities/DEPS
index 6bbc35c4180..15c36e310d6 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/DEPS
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/DEPS
@@ -1,4 +1,5 @@
include_rules = [
"-third_party/blink/renderer/modules",
+ "+third_party/blink/renderer/modules/encryptedmedia",
"+third_party/blink/renderer/modules/media_capabilities",
]
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc
index 93c78e5b9c5..af628cf4629 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc
@@ -9,14 +9,17 @@
#include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_client.h"
#include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_info.h"
#include "third_party/blink/public/platform/modules/media_capabilities/web_media_configuration.h"
+#include "third_party/blink/public/platform/modules/media_capabilities/web_media_decoding_configuration.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_media_recorder_handler.h"
-#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
+#include "third_party/blink/renderer/modules/encryptedmedia/encrypted_media_utils.h"
+#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.h"
+#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.h"
#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h"
#include "third_party/blink/renderer/modules/media_capabilities/media_configuration.h"
#include "third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.h"
@@ -80,39 +83,72 @@ bool IsValidMimeType(const String& content_type, const String& prefix) {
return parameters.begin()->name.LowerASCII() == kCodecsMimeTypeParam;
}
-bool IsValidMediaConfiguration(const MediaConfiguration& configuration) {
- return configuration.hasAudio() || configuration.hasVideo();
+bool IsValidMediaConfiguration(const MediaConfiguration* configuration) {
+ return configuration->hasAudio() || configuration->hasVideo();
}
-bool IsValidVideoConfiguration(const VideoConfiguration& configuration) {
- DCHECK(configuration.hasContentType());
+bool IsValidMediaDecodingConfiguration(
+ const MediaDecodingConfiguration* configuration,
+ String* message) {
+ if (!IsValidMediaConfiguration(configuration)) {
+ *message =
+ "The configuration dictionary has neither |video| nor |audio| "
+ "specified and needs at least one of them.";
+ return false;
+ }
+
+ if (configuration->hasKeySystemConfiguration()) {
+ if (configuration->keySystemConfiguration()->hasAudioRobustness() &&
+ !configuration->hasAudio()) {
+ *message =
+ "The keySystemConfiguration object contains an "
+ "audioRobustness property but the root configuration has no "
+ "audio configuration.";
+ return false;
+ }
+
+ if (configuration->keySystemConfiguration()->hasVideoRobustness() &&
+ !configuration->hasVideo()) {
+ *message =
+ "The keySystemConfiguration object contains an "
+ "videoRobustness property but the root configuration has no "
+ "video configuration.";
+ return false;
+ }
+ }
+
+ return true;
+}
- if (!IsValidMimeType(configuration.contentType(), kVideoMimeTypePrefix))
+bool IsValidVideoConfiguration(const VideoConfiguration* configuration) {
+ DCHECK(configuration->hasContentType());
+
+ if (!IsValidMimeType(configuration->contentType(), kVideoMimeTypePrefix))
return false;
- DCHECK(configuration.hasFramerate());
- if (std::isnan(ComputeFrameRate(configuration.framerate())))
+ DCHECK(configuration->hasFramerate());
+ if (std::isnan(ComputeFrameRate(configuration->framerate())))
return false;
return true;
}
-bool IsValidAudioConfiguration(const AudioConfiguration& configuration) {
- DCHECK(configuration.hasContentType());
+bool IsValidAudioConfiguration(const AudioConfiguration* configuration) {
+ DCHECK(configuration->hasContentType());
- if (!IsValidMimeType(configuration.contentType(), kAudioMimeTypePrefix))
+ if (!IsValidMimeType(configuration->contentType(), kAudioMimeTypePrefix))
return false;
return true;
}
WebAudioConfiguration ToWebAudioConfiguration(
- const AudioConfiguration& configuration) {
+ const AudioConfiguration* configuration) {
WebAudioConfiguration web_configuration;
// |contentType| is mandatory.
- DCHECK(configuration.hasContentType());
- ParsedContentType parsed_content_type(configuration.contentType());
+ DCHECK(configuration->hasContentType());
+ ParsedContentType parsed_content_type(configuration->contentType());
DCHECK(parsed_content_type.IsValid());
DCHECK(!parsed_content_type.GetParameters().HasDuplicatedNames());
@@ -121,26 +157,26 @@ WebAudioConfiguration ToWebAudioConfiguration(
web_configuration.codec = parsed_content_type.ParameterValueForName(codecs);
// |channels| is optional and will be set to a null WebString if not present.
- web_configuration.channels = configuration.hasChannels()
- ? WebString(configuration.channels())
+ web_configuration.channels = configuration->hasChannels()
+ ? WebString(configuration->channels())
: WebString();
- if (configuration.hasBitrate())
- web_configuration.bitrate = configuration.bitrate();
+ if (configuration->hasBitrate())
+ web_configuration.bitrate = configuration->bitrate();
- if (configuration.hasSamplerate())
- web_configuration.samplerate = configuration.samplerate();
+ if (configuration->hasSamplerate())
+ web_configuration.samplerate = configuration->samplerate();
return web_configuration;
}
WebVideoConfiguration ToWebVideoConfiguration(
- const VideoConfiguration& configuration) {
+ const VideoConfiguration* configuration) {
WebVideoConfiguration web_configuration;
// All the properties are mandatory.
- DCHECK(configuration.hasContentType());
- ParsedContentType parsed_content_type(configuration.contentType());
+ DCHECK(configuration->hasContentType());
+ ParsedContentType parsed_content_type(configuration->contentType());
DCHECK(parsed_content_type.IsValid());
DCHECK(!parsed_content_type.GetParameters().HasDuplicatedNames());
@@ -148,63 +184,114 @@ WebVideoConfiguration ToWebVideoConfiguration(
web_configuration.mime_type = parsed_content_type.MimeType().LowerASCII();
web_configuration.codec = parsed_content_type.ParameterValueForName(codecs);
- DCHECK(configuration.hasWidth());
- web_configuration.width = configuration.width();
+ DCHECK(configuration->hasWidth());
+ web_configuration.width = configuration->width();
- DCHECK(configuration.hasHeight());
- web_configuration.height = configuration.height();
+ DCHECK(configuration->hasHeight());
+ web_configuration.height = configuration->height();
- DCHECK(configuration.hasBitrate());
- web_configuration.bitrate = configuration.bitrate();
+ DCHECK(configuration->hasBitrate());
+ web_configuration.bitrate = configuration->bitrate();
- DCHECK(configuration.hasFramerate());
- double computed_framerate = ComputeFrameRate(configuration.framerate());
+ DCHECK(configuration->hasFramerate());
+ double computed_framerate = ComputeFrameRate(configuration->framerate());
DCHECK(!std::isnan(computed_framerate));
web_configuration.framerate = computed_framerate;
return web_configuration;
}
-WebMediaConfiguration ToWebMediaConfiguration(
- const MediaDecodingConfiguration& configuration) {
- WebMediaConfiguration web_configuration;
+WebMediaCapabilitiesKeySystemConfiguration
+ToWebMediaCapabilitiesKeySystemConfiguration(
+ const MediaCapabilitiesKeySystemConfiguration* configuration) {
+ WebMediaCapabilitiesKeySystemConfiguration web_configuration;
+
+ // |keySystem| is mandatory.
+ DCHECK(configuration->hasKeySystem());
+ web_configuration.key_system = configuration->keySystem();
+
+ if (configuration->hasInitDataType()) {
+ web_configuration.init_data_type =
+ EncryptedMediaUtils::ConvertToInitDataType(
+ configuration->initDataType());
+ }
+
+ // |audio_robustness| and |video_robustess| have a default value.
+ if (configuration->hasAudioRobustness())
+ web_configuration.audio_robustness = configuration->audioRobustness();
+ if (configuration->hasVideoRobustness())
+ web_configuration.video_robustness = configuration->videoRobustness();
+
+ // |distinctive_identifier| and |persistent_state| have a default value so
+ // they should only be set if needed.
+ if (configuration->hasDistinctiveIdentifier()) {
+ web_configuration.distinctive_identifier =
+ EncryptedMediaUtils::ConvertToMediaKeysRequirement(
+ configuration->distinctiveIdentifier());
+ }
+ if (configuration->hasPersistentState()) {
+ web_configuration.persistent_state =
+ EncryptedMediaUtils::ConvertToMediaKeysRequirement(
+ configuration->persistentState());
+ }
+
+ // |session_types| has a default value because it is a WebVector.
+ if (configuration->hasSessionTypes()) {
+ for (const String& session_type : configuration->sessionTypes()) {
+ web_configuration.session_types.emplace_back(
+ EncryptedMediaUtils::ConvertToSessionType(session_type));
+ }
+ }
+
+ return web_configuration;
+}
+
+WebMediaDecodingConfiguration ToWebMediaConfiguration(
+ const MediaDecodingConfiguration* configuration) {
+ WebMediaDecodingConfiguration web_configuration;
// |type| is mandatory.
- DCHECK(configuration.hasType());
- if (configuration.type() == "file")
+ DCHECK(configuration->hasType());
+ if (configuration->type() == "file")
web_configuration.type = MediaConfigurationType::kFile;
- else if (configuration.type() == "media-source")
+ else if (configuration->type() == "media-source")
web_configuration.type = MediaConfigurationType::kMediaSource;
else
NOTREACHED();
- if (configuration.hasAudio()) {
+ if (configuration->hasAudio()) {
web_configuration.audio_configuration =
- ToWebAudioConfiguration(configuration.audio());
+ ToWebAudioConfiguration(configuration->audio());
}
- if (configuration.hasVideo()) {
+ if (configuration->hasVideo()) {
web_configuration.video_configuration =
- ToWebVideoConfiguration(configuration.video());
+ ToWebVideoConfiguration(configuration->video());
+ }
+
+ if (configuration->hasKeySystemConfiguration()) {
+ web_configuration.key_system_configuration =
+ ToWebMediaCapabilitiesKeySystemConfiguration(
+ configuration->keySystemConfiguration());
}
return web_configuration;
}
WebMediaConfiguration ToWebMediaConfiguration(
- const MediaEncodingConfiguration& configuration) {
+ const MediaEncodingConfiguration* configuration) {
WebMediaConfiguration web_configuration;
// TODO(mcasas): parse and set the type for encoding.
- if (configuration.hasAudio()) {
+ if (configuration->hasAudio()) {
web_configuration.audio_configuration =
- ToWebAudioConfiguration(configuration.audio());
+ ToWebAudioConfiguration(configuration->audio());
}
- if (configuration.hasVideo()) {
+ if (configuration->hasVideo()) {
web_configuration.video_configuration =
- ToWebVideoConfiguration(configuration.video());
+ ToWebVideoConfiguration(configuration->video());
}
return web_configuration;
@@ -216,45 +303,62 @@ MediaCapabilities::MediaCapabilities() = default;
ScriptPromise MediaCapabilities::decodingInfo(
ScriptState* script_state,
- const MediaDecodingConfiguration& configuration) {
+ const MediaDecodingConfiguration* configuration) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- if (!IsValidMediaConfiguration(configuration)) {
- resolver->Reject(V8ThrowException::CreateTypeError(
- script_state->GetIsolate(),
- "The configuration dictionary has neither |video| nor |audio| "
- "specified and needs at least one of them."));
+ String error;
+ if (!IsValidMediaDecodingConfiguration(configuration, &error)) {
+ resolver->Reject(
+ V8ThrowException::CreateTypeError(script_state->GetIsolate(), error));
return promise;
}
- if (configuration.hasVideo() &&
- !IsValidVideoConfiguration(configuration.video())) {
+ if (configuration->hasVideo() &&
+ !IsValidVideoConfiguration(configuration->video())) {
resolver->Reject(V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"The video configuration dictionary is not valid."));
return promise;
}
- if (configuration.hasAudio() &&
- !IsValidAudioConfiguration(configuration.audio())) {
+ if (configuration->hasAudio() &&
+ !IsValidAudioConfiguration(configuration->audio())) {
resolver->Reject(V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"The audio configuration dictionary is not valid."));
return promise;
}
+ if (configuration->hasKeySystemConfiguration()) {
+ ExecutionContext* execution_context = ExecutionContext::From(script_state);
+ DCHECK(execution_context);
+ if (execution_context->IsWorkerGlobalScope()) {
+ resolver->Reject(DOMException::Create(
+ DOMExceptionCode::kInvalidStateError,
+ "Encrypted Media decoding info not available in Worker context."));
+ return promise;
+ }
+
+ if (!execution_context->IsSecureContext()) {
+ resolver->Reject(
+ DOMException::Create(DOMExceptionCode::kSecurityError,
+ "Encrypted Media decoding info can only be "
+ "queried in a secure context."));
+ return promise;
+ }
+ }
+
Platform::Current()->MediaCapabilitiesClient()->DecodingInfo(
ToWebMediaConfiguration(configuration),
- std::make_unique<CallbackPromiseAdapter<MediaCapabilitiesInfo, void>>(
- resolver));
+ std::make_unique<MediaCapabilitiesDecodingInfoCallbacks>(resolver));
return promise;
}
ScriptPromise MediaCapabilities::encodingInfo(
ScriptState* script_state,
- const MediaEncodingConfiguration& configuration) {
+ const MediaEncodingConfiguration* configuration) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -266,16 +370,16 @@ ScriptPromise MediaCapabilities::encodingInfo(
return promise;
}
- if (configuration.hasVideo() &&
- !IsValidVideoConfiguration(configuration.video())) {
+ if (configuration->hasVideo() &&
+ !IsValidVideoConfiguration(configuration->video())) {
resolver->Reject(V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"The video configuration dictionary is not valid."));
return promise;
}
- if (configuration.hasAudio() &&
- !IsValidAudioConfiguration(configuration.audio())) {
+ if (configuration->hasAudio() &&
+ !IsValidAudioConfiguration(configuration->audio())) {
resolver->Reject(V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"The audio configuration dictionary is not valid."));
@@ -295,8 +399,8 @@ ScriptPromise MediaCapabilities::encodingInfo(
handler->EncodingInfo(
ToWebMediaConfiguration(configuration),
- std::make_unique<CallbackPromiseAdapter<MediaCapabilitiesInfo, void>>(
- resolver));
+ std::make_unique<MediaCapabilitiesEncodingInfoCallbacks>(resolver));
+
return promise;
}
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h
index 3c1c8f2ff99..e913259c7d1 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h
@@ -21,8 +21,8 @@ class MediaCapabilities final : public ScriptWrappable {
public:
MediaCapabilities();
- ScriptPromise decodingInfo(ScriptState*, const MediaDecodingConfiguration&);
- ScriptPromise encodingInfo(ScriptState*, const MediaEncodingConfiguration&);
+ ScriptPromise decodingInfo(ScriptState*, const MediaDecodingConfiguration*);
+ ScriptPromise encodingInfo(ScriptState*, const MediaEncodingConfiguration*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.idl b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.idl
index 766714c655f..64a78de84af 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.idl
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities.idl
@@ -6,7 +6,7 @@
[Exposed=Window]
interface MediaCapabilities {
- [CallWith=ScriptState, Measure, OriginTrialEnabled=MediaCapabilities] Promise<MediaCapabilitiesInfo> decodingInfo(MediaDecodingConfiguration configuration);
+ [CallWith=ScriptState, Measure] Promise<MediaCapabilitiesDecodingInfo> decodingInfo(MediaDecodingConfiguration configuration);
[CallWith=ScriptState, Measure, RuntimeEnabled=MediaCapabilitiesEncodingInfo] Promise<MediaCapabilitiesInfo> encodingInfo(
MediaEncodingConfiguration configuration);
};
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info.idl b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info.idl
new file mode 100644
index 00000000000..8ddb1dec638
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info.idl
@@ -0,0 +1,9 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://wicg.github.io/media-capabilities/#dictdef-mediacapabilitiesdecodinginfo
+
+dictionary MediaCapabilitiesDecodingInfo : MediaCapabilitiesInfo {
+ [RuntimeEnabled=MediaCapabilitiesEncryptedMedia] MediaKeySystemAccess? keySystemAccess = null;
+};
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.cc b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.cc
new file mode 100644
index 00000000000..b40129b619c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.cc
@@ -0,0 +1,48 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.h"
+
+#include "third_party/blink/renderer/modules/encryptedmedia/media_key_system_access.h"
+#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info.h"
+
+namespace blink {
+
+MediaCapabilitiesDecodingInfoCallbacks::MediaCapabilitiesDecodingInfoCallbacks(
+ ScriptPromiseResolver* resolver)
+ : resolver_(resolver) {}
+
+MediaCapabilitiesDecodingInfoCallbacks::
+ ~MediaCapabilitiesDecodingInfoCallbacks() = default;
+
+void MediaCapabilitiesDecodingInfoCallbacks::OnSuccess(
+ std::unique_ptr<WebMediaCapabilitiesDecodingInfo> result) {
+ if (!resolver_->GetExecutionContext() ||
+ resolver_->GetExecutionContext()->IsContextDestroyed()) {
+ return;
+ }
+
+ Persistent<MediaCapabilitiesDecodingInfo> info(
+ MediaCapabilitiesDecodingInfo::Create());
+ info->setSupported(result->supported);
+ info->setSmooth(result->smooth);
+ info->setPowerEfficient(result->power_efficient);
+
+ if (result->content_decryption_module_access) {
+ // Per spec, the key system access should only be set if the configuration
+ // is supported.
+ DCHECK(result->supported);
+
+ info->setKeySystemAccess(new MediaKeySystemAccess(
+ std::move(result->content_decryption_module_access)));
+ }
+
+ resolver_->Resolve(std::move(info));
+}
+
+void MediaCapabilitiesDecodingInfoCallbacks::OnError() {
+ NOTREACHED();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.h b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.h
new file mode 100644
index 00000000000..7e2f9da6565
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_decoding_info_callbacks.h
@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_DECODING_INFO_CALLBACKS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_DECODING_INFO_CALLBACKS_H_
+
+#include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_callbacks.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
+#include "third_party/blink/renderer/platform/heap/persistent.h"
+
+namespace blink {
+
+class MediaCapabilitiesDecodingInfoCallbacks
+ : public WebMediaCapabilitiesDecodingInfoCallbacks {
+ public:
+ explicit MediaCapabilitiesDecodingInfoCallbacks(
+ ScriptPromiseResolver* resolver);
+
+ ~MediaCapabilitiesDecodingInfoCallbacks() override;
+
+ void OnSuccess(std::unique_ptr<WebMediaCapabilitiesDecodingInfo>) override;
+ void OnError() override;
+
+ private:
+ Persistent<ScriptPromiseResolver> resolver_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_QUERY_CALLBACKS_H_
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.cc b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.cc
new file mode 100644
index 00000000000..044b9c81667
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.cc
@@ -0,0 +1,37 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.h"
+
+#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h"
+
+namespace blink {
+
+MediaCapabilitiesEncodingInfoCallbacks::MediaCapabilitiesEncodingInfoCallbacks(
+ ScriptPromiseResolver* resolver)
+ : resolver_(resolver) {}
+
+MediaCapabilitiesEncodingInfoCallbacks::
+ ~MediaCapabilitiesEncodingInfoCallbacks() = default;
+
+void MediaCapabilitiesEncodingInfoCallbacks::OnSuccess(
+ std::unique_ptr<WebMediaCapabilitiesInfo> result) {
+ if (!resolver_->GetExecutionContext() ||
+ resolver_->GetExecutionContext()->IsContextDestroyed()) {
+ return;
+ }
+
+ Persistent<MediaCapabilitiesInfo> info(MediaCapabilitiesInfo::Create());
+ info->setSupported(result->supported);
+ info->setSmooth(result->smooth);
+ info->setPowerEfficient(result->power_efficient);
+
+ resolver_->Resolve(std::move(info));
+}
+
+void MediaCapabilitiesEncodingInfoCallbacks::OnError() {
+ NOTREACHED();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.h b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.h
new file mode 100644
index 00000000000..6f847b7a5b6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_encoding_info_callbacks.h
@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_ENCODING_INFO_CALLBACKS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_ENCODING_INFO_CALLBACKS_H_
+
+#include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_callbacks.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
+#include "third_party/blink/renderer/platform/heap/persistent.h"
+
+namespace blink {
+
+class MediaCapabilitiesEncodingInfoCallbacks
+ : public WebMediaCapabilitiesEncodingInfoCallbacks {
+ public:
+ explicit MediaCapabilitiesEncodingInfoCallbacks(
+ ScriptPromiseResolver* resolver);
+
+ ~MediaCapabilitiesEncodingInfoCallbacks() override;
+
+ void OnSuccess(std::unique_ptr<WebMediaCapabilitiesInfo>) override;
+ void OnError() override;
+
+ private:
+ Persistent<ScriptPromiseResolver> resolver_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_ENCODING_INFO_CALLBACKS_H_
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.cc b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.cc
deleted file mode 100644
index 30d3c49201c..00000000000
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h"
-
-namespace blink {
-
-// static
-MediaCapabilitiesInfo* MediaCapabilitiesInfo::Take(
- ScriptPromiseResolver*,
- std::unique_ptr<WebMediaCapabilitiesInfo> web_media_capabilities_info) {
- DCHECK(web_media_capabilities_info);
- return new MediaCapabilitiesInfo(std::move(web_media_capabilities_info));
-}
-
-bool MediaCapabilitiesInfo::supported() const {
- return web_media_capabilities_info_->supported;
-}
-
-bool MediaCapabilitiesInfo::smooth() const {
- return web_media_capabilities_info_->smooth;
-}
-
-bool MediaCapabilitiesInfo::powerEfficient() const {
- return web_media_capabilities_info_->power_efficient;
-}
-
-MediaCapabilitiesInfo::MediaCapabilitiesInfo(
- std::unique_ptr<WebMediaCapabilitiesInfo> web_media_capabilities_info)
- : web_media_capabilities_info_(std::move(web_media_capabilities_info)) {}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h
deleted file mode 100644
index da51fbc9eb8..00000000000
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_INFO_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_INFO_H_
-
-#include <memory>
-
-#include "third_party/blink/public/platform/modules/media_capabilities/web_media_capabilities_info.h"
-#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
-
-namespace blink {
-
-class ScriptPromiseResolver;
-
-// Implementation of the MediaCapabilitiesInfo interface.
-class MediaCapabilitiesInfo final : public ScriptWrappable {
- DEFINE_WRAPPERTYPEINFO();
-
- public:
- using WebType = std::unique_ptr<WebMediaCapabilitiesInfo>;
- static MediaCapabilitiesInfo* Take(ScriptPromiseResolver*,
- std::unique_ptr<WebMediaCapabilitiesInfo>);
-
- bool supported() const;
- bool smooth() const;
- bool powerEfficient() const;
-
- private:
- MediaCapabilitiesInfo() = delete;
- explicit MediaCapabilitiesInfo(std::unique_ptr<WebMediaCapabilitiesInfo>);
-
- std::unique_ptr<WebMediaCapabilitiesInfo> web_media_capabilities_info_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_INFO_H_
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.idl b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.idl
index 35c1c067fe3..1a80a702ba7 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.idl
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_info.idl
@@ -2,13 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://wicg.github.io/media-capabilities/#mediacapabilitiesinfo
+// https://wicg.github.io/media-capabilities/#media-capabilities-info
-[
- Exposed=Window,
- OriginTrialEnabled=MediaCapabilities
-] interface MediaCapabilitiesInfo {
- [Measure] readonly attribute boolean supported;
- [Measure] readonly attribute boolean smooth;
- [Measure] readonly attribute boolean powerEfficient;
+dictionary MediaCapabilitiesInfo {
+ required boolean supported;
+ required boolean smooth;
+ required boolean powerEfficient;
};
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_key_system_configuration.idl b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_key_system_configuration.idl
new file mode 100644
index 00000000000..459c8e0ddf6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_capabilities_key_system_configuration.idl
@@ -0,0 +1,15 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://wicg.github.io/media-capabilities/#dictdef-mediacapabilitieskeysystemconfiguration
+
+dictionary MediaCapabilitiesKeySystemConfiguration {
+ required DOMString keySystem;
+ DOMString initDataType = "";
+ DOMString audioRobustness;
+ DOMString videoRobustness;
+ MediaKeysRequirement distinctiveIdentifier = "optional";
+ MediaKeysRequirement persistentState = "optional";
+ sequence<DOMString> sessionTypes;
+};
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.idl b/chromium/third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.idl
index b794fd6a24c..26779a24d57 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.idl
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.idl
@@ -13,4 +13,5 @@ enum MediaDecodingType {
dictionary MediaDecodingConfiguration : MediaConfiguration {
required MediaDecodingType type;
+ [RuntimeEnabled=MediaCapabilitiesEncryptedMedia] MediaCapabilitiesKeySystemConfiguration keySystemConfiguration;
};
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.cc b/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.cc
index 768dfacc9d5..211a47bc8f2 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.cc
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.cc
@@ -18,7 +18,7 @@ MediaCapabilities* NavigatorMediaCapabilities::mediaCapabilities(
NavigatorMediaCapabilities& self =
NavigatorMediaCapabilities::From(navigator);
if (!self.capabilities_)
- self.capabilities_ = new MediaCapabilities();
+ self.capabilities_ = MakeGarbageCollected<MediaCapabilities>();
return self.capabilities_.Get();
}
@@ -35,7 +35,7 @@ NavigatorMediaCapabilities& NavigatorMediaCapabilities::From(
NavigatorMediaCapabilities* supplement =
Supplement<Navigator>::From<NavigatorMediaCapabilities>(navigator);
if (!supplement) {
- supplement = new NavigatorMediaCapabilities(navigator);
+ supplement = MakeGarbageCollected<NavigatorMediaCapabilities>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.h b/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.h
index 0a1beb603b8..e5bdd820f13 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.h
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.h
@@ -24,11 +24,11 @@ class NavigatorMediaCapabilities final
static MediaCapabilities* mediaCapabilities(Navigator&);
+ explicit NavigatorMediaCapabilities(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorMediaCapabilities(Navigator&);
-
static NavigatorMediaCapabilities& From(Navigator&);
// The MediaCapabilities instance of this Navigator.
diff --git a/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.idl b/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.idl
index 5f421afcb0e..6b00ca4c65d 100644
--- a/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.idl
+++ b/chromium/third_party/blink/renderer/modules/media_capabilities/navigator_media_capabilities.idl
@@ -6,8 +6,7 @@
[
Exposed=Window,
- ImplementedAs=NavigatorMediaCapabilities,
- OriginTrialEnabled=MediaCapabilities
+ ImplementedAs=NavigatorMediaCapabilities
] partial interface Navigator {
[SameObject] readonly attribute MediaCapabilities mediaCapabilities;
};
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/BUILD.gn b/chromium/third_party/blink/renderer/modules/media_controls/BUILD.gn
index 5c8e0de3a8a..4ab9dd5227d 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/media_controls/BUILD.gn
@@ -15,6 +15,8 @@ blink_modules_sources("media_controls") {
"elements/media_control_button_panel_element.h",
"elements/media_control_cast_button_element.cc",
"elements/media_control_cast_button_element.h",
+ "elements/media_control_consts.cc",
+ "elements/media_control_consts.h",
"elements/media_control_current_time_display_element.cc",
"elements/media_control_current_time_display_element.h",
"elements/media_control_display_cutout_fullscreen_button_element.cc",
@@ -91,7 +93,6 @@ blink_modules_sources("media_controls") {
deps = [
":media_controls_resources",
"//services/service_manager/public/cpp",
- "//third_party/blink/public:media_controls_resources_header",
]
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/DEPS b/chromium/third_party/blink/renderer/modules/media_controls/DEPS
index d7ede6ebe02..6f2a859f47b 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/DEPS
+++ b/chromium/third_party/blink/renderer/modules/media_controls/DEPS
@@ -1,5 +1,4 @@
include_rules = [
- "+blink/public/resources/grit/media_controls_resources.h",
"+mojo/public/cpp/bindings",
"+services/device/public/mojom/constants.mojom-blink.h",
"+services/device/public/mojom/screen_orientation.mojom-blink.h",
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element.cc
index 0848f2d8cce..da595e2a5e3 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element.cc
@@ -37,7 +37,8 @@ void MediaControlAnimatedArrowContainerElement::AnimatedArrow::ShowInternal() {
last_arrow_ = getElementById("arrow-3");
svg_container_ = getElementById("jump");
- event_listener_ = new MediaControlAnimationEventListener(this);
+ event_listener_ =
+ MakeGarbageCollected<MediaControlAnimationEventListener>(this);
}
void MediaControlAnimatedArrowContainerElement::AnimatedArrow::
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element_test.cc
index 584e6c168f4..a1d213ab619 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element_test.cc
@@ -39,7 +39,7 @@ class MediaControlAnimatedArrowContainerElementTest : public PageTestBase {
void SimulateShow() { arrow_element_->Show(); }
void SimulateAnimationIteration() {
- Event* event = Event::Create(EventTypeNames::animationiteration);
+ Event* event = Event::Create(event_type_names::kAnimationiteration);
GetElementById("arrow-3")->DispatchEvent(*event);
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.cc
index f7443373dc1..f31e1b45fe6 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.cc
@@ -13,16 +13,16 @@ MediaControlAnimationEventListener::MediaControlAnimationEventListener(
Observer* observer)
: EventListener(EventListener::kCPPEventListenerType), observer_(observer) {
observer_->WatchedAnimationElement().addEventListener(
- EventTypeNames::animationend, this, false);
+ event_type_names::kAnimationend, this, false);
observer_->WatchedAnimationElement().addEventListener(
- EventTypeNames::animationiteration, this, false);
+ event_type_names::kAnimationiteration, this, false);
}
void MediaControlAnimationEventListener::Detach() {
observer_->WatchedAnimationElement().removeEventListener(
- EventTypeNames::animationend, this, false);
+ event_type_names::kAnimationend, this, false);
observer_->WatchedAnimationElement().removeEventListener(
- EventTypeNames::animationiteration, this, false);
+ event_type_names::kAnimationiteration, this, false);
}
bool MediaControlAnimationEventListener::operator==(
@@ -35,13 +35,13 @@ void MediaControlAnimationEventListener::Trace(Visitor* visitor) {
EventListener::Trace(visitor);
}
-void MediaControlAnimationEventListener::handleEvent(ExecutionContext* context,
- Event* event) {
- if (event->type() == EventTypeNames::animationend) {
+void MediaControlAnimationEventListener::Invoke(ExecutionContext* context,
+ Event* event) {
+ if (event->type() == event_type_names::kAnimationend) {
observer_->OnAnimationEnd();
return;
}
- if (event->type() == EventTypeNames::animationiteration) {
+ if (event->type() == event_type_names::kAnimationiteration) {
observer_->OnAnimationIteration();
return;
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.h b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.h
index 0546d8afc42..987e3ea6ea5 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_animation_event_listener.h
@@ -52,7 +52,7 @@ class MODULES_EXPORT MediaControlAnimationEventListener final
void Trace(Visitor*) override;
private:
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
Member<Observer> observer_;
};
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.cc
index ea489594c5b..40f5426e955 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.cc
@@ -39,7 +39,7 @@ MediaControlCastButtonElement::MediaControlCastButtonElement(
SetShadowPseudoId(is_overlay_button
? "-internal-media-controls-overlay-cast-button"
: "-internal-media-controls-cast-button");
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
UpdateDisplayType();
}
@@ -93,7 +93,7 @@ const char* MediaControlCastButtonElement::GetNameForHistograms() const {
}
void MediaControlCastButtonElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
if (is_overlay_button_) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.CastOverlay"));
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.cc
new file mode 100644
index 00000000000..4941a77f7cf
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.cc
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h"
+
+namespace blink {
+
+const char kClosedCSSClass[] = "closed";
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h
new file mode 100644
index 00000000000..d1a85779e74
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h
@@ -0,0 +1,14 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_ELEMENTS_MEDIA_CONTROL_CONSTS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_ELEMENTS_MEDIA_CONTROL_CONSTS_H_
+
+namespace blink {
+
+extern const char kClosedCSSClass[];
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_ELEMENTS_MEDIA_CONTROL_CONSTS_H_
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element.cc
index f284d1737c0..e6646c3e770 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element.cc
@@ -18,7 +18,7 @@ MediaControlDisplayCutoutFullscreenButtonElement::
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls,
kMediaDisplayCutoutFullscreenButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString(
"-internal-media-controls-display-cutout-fullscreen-button"));
SetIsWanted(false);
@@ -31,7 +31,7 @@ bool MediaControlDisplayCutoutFullscreenButtonElement::
void MediaControlDisplayCutoutFullscreenButtonElement::DefaultEventHandler(
Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
// The button shouldn't be visible if not in fullscreen.
DCHECK(MediaElement().IsFullscreen());
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc
index 6f9fd45dd93..455234995f4 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc
@@ -23,7 +23,7 @@ namespace {
class MockDisplayCutoutChromeClient : public EmptyChromeClient {
public:
// ChromeClient overrides:
- void EnterFullscreen(LocalFrame& frame, const FullscreenOptions&) override {
+ void EnterFullscreen(LocalFrame& frame, const FullscreenOptions*) override {
Fullscreen::DidEnterFullscreen(*frame.GetDocument());
}
void ExitFullscreen(LocalFrame& frame) override {
@@ -36,7 +36,9 @@ class MockDisplayCutoutChromeClient : public EmptyChromeClient {
class MediaControlDisplayCutoutFullscreenButtonElementTest
: public PageTestBase {
public:
- static TouchEventInit GetValidTouchEventInit() { return TouchEventInit(); }
+ static TouchEventInit* GetValidTouchEventInit() {
+ return TouchEventInit::Create();
+ }
void SetUp() override {
chrome_client_ = new MockDisplayCutoutChromeClient();
@@ -50,7 +52,7 @@ class MediaControlDisplayCutoutFullscreenButtonElementTest
video_ = HTMLVideoElement::Create(GetDocument());
GetDocument().body()->AppendChild(video_);
- controls_ = new MediaControlsImpl(*video_);
+ controls_ = MakeGarbageCollected<MediaControlsImpl>(*video_);
controls_->InitializeControls();
display_cutout_fullscreen_button_ =
controls_->display_cutout_fullscreen_button_;
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.cc
index a240eac3b84..af3d60a8d98 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.cc
@@ -21,7 +21,7 @@ namespace blink {
MediaControlDownloadButtonElement::MediaControlDownloadButtonElement(
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaDownloadButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString("-internal-media-controls-download-button"));
SetIsWanted(false);
}
@@ -71,7 +71,7 @@ void MediaControlDownloadButtonElement::UpdateShownState() {
void MediaControlDownloadButtonElement::DefaultEventHandler(Event& event) {
const KURL& url = MediaElement().currentSrc();
- if (event.type() == EventTypeNames::click &&
+ if (event.type() == event_type_names::kClick &&
!(url.IsNull() || url.IsEmpty())) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.Download"));
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.cc
index 7a6b6ac02f8..93483865e9f 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.cc
@@ -19,11 +19,13 @@ namespace blink {
// static
bool MediaControlElementsHelper::IsUserInteractionEvent(const Event& event) {
const AtomicString& type = event.type();
- return type == EventTypeNames::pointerdown ||
- type == EventTypeNames::pointerup ||
- type == EventTypeNames::mousedown || type == EventTypeNames::mouseup ||
- type == EventTypeNames::click || type == EventTypeNames::dblclick ||
- event.IsKeyboardEvent() || event.IsTouchEvent();
+ return type == event_type_names::kPointerdown ||
+ type == event_type_names::kPointerup ||
+ type == event_type_names::kMousedown ||
+ type == event_type_names::kMouseup ||
+ type == event_type_names::kClick ||
+ type == event_type_names::kDblclick || event.IsKeyboardEvent() ||
+ event.IsTouchEvent();
}
// static
@@ -46,12 +48,12 @@ bool MediaControlElementsHelper::IsUserInteractionEventForSlider(
return false;
const AtomicString& type = event.type();
- return type == EventTypeNames::mouseover ||
- type == EventTypeNames::mouseout ||
- type == EventTypeNames::mousemove ||
- type == EventTypeNames::pointerover ||
- type == EventTypeNames::pointerout ||
- type == EventTypeNames::pointermove;
+ return type == event_type_names::kMouseover ||
+ type == event_type_names::kMouseout ||
+ type == event_type_names::kMousemove ||
+ type == event_type_names::kPointerover ||
+ type == event_type_names::kPointerout ||
+ type == event_type_names::kPointermove;
}
// static
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_fullscreen_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_fullscreen_button_element.cc
index b3ae69b8ecd..b8368826c34 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_fullscreen_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_fullscreen_button_element.cc
@@ -17,7 +17,7 @@ namespace blink {
MediaControlFullscreenButtonElement::MediaControlFullscreenButtonElement(
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaEnterFullscreenButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString("-webkit-media-controls-fullscreen-button"));
SetIsFullscreen(MediaElement().IsFullscreen());
SetIsWanted(false);
@@ -49,7 +49,7 @@ const char* MediaControlFullscreenButtonElement::GetNameForHistograms() const {
}
void MediaControlFullscreenButtonElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
RecordClickMetrics();
if (MediaElement().IsFullscreen())
GetMediaControls().ExitFullscreen();
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc
index 806b4ea1fe2..db9cb7d426c 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element.cc
@@ -199,7 +199,7 @@ void MediaControlInputElement::UpdateShownState() {
}
void MediaControlInputElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click)
+ if (event.type() == event_type_names::kClick)
MaybeRecordInteracted();
HTMLInputElement::DefaultEventHandler(event);
@@ -272,7 +272,7 @@ WebSize MediaControlInputElement::GetSizeOrDefault() const {
}
bool MediaControlInputElement::IsDisabled() const {
- return hasAttribute(HTMLNames::disabledAttr);
+ return hasAttribute(html_names::kDisabledAttr);
}
void MediaControlInputElement::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element_test.cc
index 17a12b2350d..e948fe7222e 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_input_element_test.cc
@@ -30,7 +30,7 @@ class MediaControlInputElementImpl final : public MediaControlInputElement {
MediaControlInputElementImpl(MediaControlsImpl& media_controls)
// Using arbitrary MediaControlElementType. It should have no impact.
: MediaControlInputElement(media_controls, kMediaDownloadButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetIsWanted(false);
}
@@ -57,7 +57,7 @@ class MediaControlInputElementTest : public PageTestBase {
// Create page and add a video element with controls.
PageTestBase::SetUp();
media_element_ = HTMLVideoElement::Create(GetDocument());
- media_element_->SetBooleanAttribute(HTMLNames::controlsAttr, true);
+ media_element_->SetBooleanAttribute(html_names::kControlsAttr, true);
GetDocument().body()->AppendChild(media_element_);
// Create instance of MediaControlInputElement to run tests on.
@@ -169,7 +169,7 @@ TEST_F(MediaControlInputElementTest, ClickRecordsInteraction) {
ControlInputElement().MaybeRecordDisplayed();
ControlInputElement().DispatchSimulatedClick(
- Event::CreateBubble(EventTypeNames::click), kSendNoEvents);
+ Event::CreateBubble(event_type_names::kClick), kSendNoEvents);
histogram_tester_.ExpectTotalCount(kControlInputElementHistogramName, 2);
histogram_tester_.ExpectBucketCount(kControlInputElementHistogramName, 0, 1);
@@ -236,7 +236,7 @@ TEST_F(MediaControlInputElementTest, OverflowElement_DisplayAfterInline) {
}
TEST_F(MediaControlInputElementTest, ShouldRecordDisplayStates_ReadyState) {
- MediaElement().setAttribute(HTMLNames::preloadAttr, "auto");
+ MediaElement().setAttribute(html_names::kPreloadAttr, "auto");
SetReadyState(HTMLMediaElement::kHaveNothing);
EXPECT_FALSE(
@@ -264,15 +264,15 @@ TEST_F(MediaControlInputElementTest, ShouldRecordDisplayStates_Preload) {
// the result.
SetReadyState(HTMLMediaElement::kHaveNothing);
- MediaElement().setAttribute(HTMLNames::preloadAttr, "none");
+ MediaElement().setAttribute(html_names::kPreloadAttr, "none");
EXPECT_TRUE(
MediaControlInputElement::ShouldRecordDisplayStates(MediaElement()));
- MediaElement().setAttribute(HTMLNames::preloadAttr, "preload");
+ MediaElement().setAttribute(html_names::kPreloadAttr, "preload");
EXPECT_FALSE(
MediaControlInputElement::ShouldRecordDisplayStates(MediaElement()));
- MediaElement().setAttribute(HTMLNames::preloadAttr, "auto");
+ MediaElement().setAttribute(html_names::kPreloadAttr, "auto");
EXPECT_FALSE(
MediaControlInputElement::ShouldRecordDisplayStates(MediaElement()));
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc
index dfb4d440740..c8aa69e60b1 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.cc
@@ -98,7 +98,8 @@ void MediaControlLoadingPanelElement::PopulateShadowDOM() {
"-internal-media-controls-loading-panel-spinner-mask-2-background",
mask2);
- event_listener_ = new MediaControlAnimationEventListener(this);
+ event_listener_ =
+ MakeGarbageCollected<MediaControlAnimationEventListener>(this);
}
void MediaControlLoadingPanelElement::RemovedFrom(
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc
index 813235783e9..36dc379eff4 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element_test.cc
@@ -24,14 +24,15 @@ class MediaControlLoadingPanelElementTest : public PageTestBase {
// Create page and add a video element with controls.
PageTestBase::SetUp();
media_element_ = HTMLVideoElement::Create(GetDocument());
- media_element_->SetBooleanAttribute(HTMLNames::controlsAttr, true);
+ media_element_->SetBooleanAttribute(html_names::kControlsAttr, true);
GetDocument().body()->AppendChild(media_element_);
// Create instance of MediaControlInputElement to run tests on.
media_controls_ =
static_cast<MediaControlsImpl*>(media_element_->GetMediaControls());
ASSERT_NE(media_controls_, nullptr);
- loading_element_ = new MediaControlLoadingPanelElement(*media_controls_);
+ loading_element_ =
+ MakeGarbageCollected<MediaControlLoadingPanelElement>(*media_controls_);
}
protected:
@@ -90,7 +91,7 @@ class MediaControlLoadingPanelElementTest : public PageTestBase {
void SimulateAnimationIterations(int count) {
for (int i = 0; i < count; i++) {
- TriggerEvent(EventTypeNames::animationiteration);
+ TriggerEvent(event_type_names::kAnimationiteration);
}
}
@@ -103,7 +104,7 @@ class MediaControlLoadingPanelElementTest : public PageTestBase {
ExpectAnimationIterationCount("infinite");
}
- void SimulateAnimationEnd() { TriggerEvent(EventTypeNames::animationend); }
+ void SimulateAnimationEnd() { TriggerEvent(event_type_names::kAnimationend); }
void SimulateControlsHidden() { loading_element_->OnControlsHidden(); }
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc
index da173711dda..f1c96f981ec 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.cc
@@ -15,7 +15,7 @@ namespace blink {
MediaControlMuteButtonElement::MediaControlMuteButtonElement(
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaMuteButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString("-webkit-media-controls-mute-button"));
}
@@ -51,7 +51,7 @@ const char* MediaControlMuteButtonElement::GetNameForHistograms() const {
}
void MediaControlMuteButtonElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
if (MediaElement().muted()) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.Unmute"));
@@ -65,13 +65,13 @@ void MediaControlMuteButtonElement::DefaultEventHandler(Event& event) {
}
if (!IsOverflowElement()) {
- if (event.type() == EventTypeNames::mouseover ||
- event.type() == EventTypeNames::focus) {
+ if (event.type() == event_type_names::kMouseover ||
+ event.type() == event_type_names::kFocus) {
GetMediaControls().OpenVolumeSliderIfNecessary();
}
- if (event.type() == EventTypeNames::mouseout ||
- event.type() == EventTypeNames::blur) {
+ if (event.type() == event_type_names::kMouseout ||
+ event.type() == event_type_names::kBlur) {
GetMediaControls().CloseVolumeSliderIfNecessary();
}
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.cc
index cb2ffa7acc1..a33e4b429cc 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.cc
@@ -16,7 +16,7 @@ namespace blink {
MediaControlOverflowMenuButtonElement::MediaControlOverflowMenuButtonElement(
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaOverflowButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString("-internal-media-controls-overflow-button"));
SetIsWanted(false);
}
@@ -43,8 +43,8 @@ void MediaControlOverflowMenuButtonElement::UpdateShownState() {
void MediaControlOverflowMenuButtonElement::DefaultEventHandler(Event& event) {
// Only respond to a click event if we are not disabled.
- if (!hasAttribute(HTMLNames::disabledAttr) &&
- event.type() == EventTypeNames::click) {
+ if (!hasAttribute(html_names::kDisabledAttr) &&
+ event.type() == event_type_names::kClick) {
if (GetMediaControls().OverflowMenuVisible()) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.OverflowClose"));
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc
index cb7d4e67ef0..710ecb69070 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.cc
@@ -6,10 +6,13 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/dom_token_list.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -18,6 +21,15 @@ MediaControlOverflowMenuListElement::MediaControlOverflowMenuListElement(
: MediaControlPopupMenuElement(media_controls, kMediaOverflowList) {
SetShadowPseudoId(
AtomicString("-internal-media-controls-overflow-menu-list"));
+ CloseOverflowMenu();
+}
+
+void MediaControlOverflowMenuListElement::OpenOverflowMenu() {
+ classList().Remove(kClosedCSSClass);
+}
+
+void MediaControlOverflowMenuListElement::CloseOverflowMenu() {
+ classList().Add(kClosedCSSClass);
}
void MediaControlOverflowMenuListElement::MaybeRecordTimeTaken(
@@ -38,7 +50,7 @@ void MediaControlOverflowMenuListElement::MaybeRecordTimeTaken(
}
void MediaControlOverflowMenuListElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click)
+ if (event.type() == event_type_names::kClick)
event.SetDefaultHandled();
MediaControlPopupMenuElement::DefaultEventHandler(event);
@@ -47,6 +59,11 @@ void MediaControlOverflowMenuListElement::DefaultEventHandler(Event& event) {
void MediaControlOverflowMenuListElement::SetIsWanted(bool wanted) {
MediaControlPopupMenuElement::SetIsWanted(wanted);
+ if (wanted)
+ OpenOverflowMenu();
+ else if (!GetMediaControls().TextTrackListIsWanted())
+ CloseOverflowMenu();
+
// Record the time the overflow menu was shown to a histogram.
if (wanted) {
DCHECK(!time_shown_);
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h
index 4da049d2d2f..3a8d38dabc1 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h
@@ -7,7 +7,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -21,6 +21,9 @@ class MediaControlOverflowMenuListElement final
public:
explicit MediaControlOverflowMenuListElement(MediaControlsImpl&);
+ void OpenOverflowMenu();
+ void CloseOverflowMenu();
+
// Override MediaControlPopupMenuElement
void SetIsWanted(bool) final;
Element* PopupAnchor() const final;
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_enclosure_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_enclosure_element.cc
index 1e80f7fcd8b..f66633f48e5 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_enclosure_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_enclosure_element.cc
@@ -18,10 +18,10 @@ MediaControlOverlayEnclosureElement::MediaControlOverlayEnclosureElement(
void MediaControlOverlayEnclosureElement::DefaultEventHandler(Event& event) {
// When the user interacts with the media element, the Cast overlay button
// needs to be shown.
- if (event.type() == EventTypeNames::gesturetap ||
- event.type() == EventTypeNames::click ||
- event.type() == EventTypeNames::pointerover ||
- event.type() == EventTypeNames::pointermove) {
+ if (event.type() == event_type_names::kGesturetap ||
+ event.type() == event_type_names::kClick ||
+ event.type() == event_type_names::kPointerover ||
+ event.type() == event_type_names::kPointermove) {
GetMediaControls().ShowOverlayCastButtonIfNeeded();
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_play_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_play_button_element.cc
index aa454a87048..0c1668197c1 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_play_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_play_button_element.cc
@@ -39,7 +39,7 @@ MediaControlOverlayPlayButtonElement::MediaControlOverlayPlayButtonElement(
: MediaControlInputElement(media_controls, kMediaPlayButton),
internal_button_(nullptr) {
EnsureUserAgentShadowRoot();
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString("-webkit-media-controls-overlay-play-button"));
if (MediaControlsImpl::IsModern()) {
@@ -76,8 +76,7 @@ void MediaControlOverlayPlayButtonElement::MaybePlayPause() {
// state. This allows potential recovery for transient network and decoder
// resource issues.
const String& url = MediaElement().currentSrc().GetString();
- if (MediaElement().error() && !HTMLMediaElement::IsMediaStreamURL(url) &&
- !HTMLMediaSource::Lookup(url)) {
+ if (MediaElement().error() && !HTMLMediaSource::Lookup(url)) {
MediaElement().load();
}
@@ -92,7 +91,7 @@ void MediaControlOverlayPlayButtonElement::MaybePlayPause() {
}
void MediaControlOverlayPlayButtonElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
event.SetDefaultHandled();
MaybePlayPause();
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element.cc
index 22848fc0ddd..2a6da96b45d 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -40,14 +41,15 @@ class MediaControlPanelElement::TransitionEventListener final
DCHECK(!attached_);
attached_ = true;
- element_->addEventListener(EventTypeNames::transitionend, this, false);
+ element_->addEventListener(event_type_names::kTransitionend, this, false);
}
void Detach() {
DCHECK(attached_);
attached_ = false;
- element_->removeEventListener(EventTypeNames::transitionend, this, false);
+ element_->removeEventListener(event_type_names::kTransitionend, this,
+ false);
}
bool IsAttached() const { return attached_; }
@@ -62,8 +64,11 @@ class MediaControlPanelElement::TransitionEventListener final
}
private:
- void handleEvent(ExecutionContext* context, Event* event) override {
- if (event->type() == EventTypeNames::transitionend) {
+ void Invoke(ExecutionContext* context, Event* event) override {
+ if (event->target() != element_)
+ return;
+
+ if (event->type() == event_type_names::kTransitionend) {
callback_.Run();
return;
}
@@ -150,10 +155,11 @@ bool MediaControlPanelElement::EventListenerIsAttachedForTest() const {
void MediaControlPanelElement::EnsureTransitionEventListener() {
// Create the event listener if it doesn't exist.
if (!event_listener_) {
- event_listener_ = new MediaControlPanelElement::TransitionEventListener(
- this,
- WTF::BindRepeating(&MediaControlPanelElement::HandleTransitionEndEvent,
- WrapWeakPersistent(this)));
+ event_listener_ =
+ MakeGarbageCollected<MediaControlPanelElement::TransitionEventListener>(
+ this, WTF::BindRepeating(
+ &MediaControlPanelElement::HandleTransitionEndEvent,
+ WrapWeakPersistent(this)));
}
// Attach the event listener if we are not attached.
@@ -173,7 +179,8 @@ void MediaControlPanelElement::DetachTransitionEventListener() {
void MediaControlPanelElement::DefaultEventHandler(Event& event) {
// Suppress the media element activation behavior (toggle play/pause) when
// any part of the control panel is clicked.
- if (event.type() == EventTypeNames::click && !MediaControlsImpl::IsModern()) {
+ if (event.type() == event_type_names::kClick &&
+ !MediaControlsImpl::IsModern()) {
event.SetDefaultHandled();
return;
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element_test.cc
index f44fe39f8cb..a6faf0872a9 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element_test.cc
@@ -21,18 +21,21 @@ class MediaControlPanelElementTest : public PageTestBase {
// Create page and add a video element with controls.
PageTestBase::SetUp();
media_element_ = HTMLVideoElement::Create(GetDocument());
- media_element_->SetBooleanAttribute(HTMLNames::controlsAttr, true);
+ media_element_->SetBooleanAttribute(html_names::kControlsAttr, true);
GetDocument().body()->AppendChild(media_element_);
// Create instance of MediaControlInputElement to run tests on.
media_controls_ =
static_cast<MediaControlsImpl*>(media_element_->GetMediaControls());
ASSERT_NE(media_controls_, nullptr);
- panel_element_ = new MediaControlPanelElement(*media_controls_);
+ panel_element_ =
+ MakeGarbageCollected<MediaControlPanelElement>(*media_controls_);
}
protected:
- void SimulateTransitionEnd() { TriggerEvent(EventTypeNames::transitionend); }
+ void SimulateTransitionEnd(Element& element) {
+ TriggerEvent(element, event_type_names::kTransitionend);
+ }
void ExpectPanelIsDisplayed() { EXPECT_TRUE(GetPanel().IsWanted()); }
@@ -52,9 +55,10 @@ class MediaControlPanelElementTest : public PageTestBase {
HTMLMediaElement& GetMediaElement() { return *media_element_.Get(); }
private:
- void TriggerEvent(const AtomicString& name) {
+ void TriggerEvent(Element& element, const AtomicString& name) {
Event* event = Event::Create(name);
- GetPanel().DispatchEvent(*event);
+ event->SetTarget(&element);
+ GetPanel().FireEventListeners(*event);
}
Persistent<HTMLMediaElement> media_element_;
@@ -63,6 +67,9 @@ class MediaControlPanelElementTest : public PageTestBase {
};
TEST_F(MediaControlPanelElementTest, StateTransitions) {
+ Element* child_div = HTMLDivElement::Create(GetPanel().GetDocument());
+ GetPanel().ParserAppendChild(child_div);
+
// Make sure we are displayed (we are already opaque).
GetPanel().SetIsDisplayed(true);
ExpectPanelIsDisplayed();
@@ -72,10 +79,15 @@ TEST_F(MediaControlPanelElementTest, StateTransitions) {
EventListenerNotCreated();
GetPanel().MakeTransparent();
- // The event listener should now be attached so we should simulate the
- // transition end and the panel will be hidden.
+ // The event listener should now be attached
EventListenerAttached();
- SimulateTransitionEnd();
+
+ // Simulate child div transition end and the panel should not be hidden
+ SimulateTransitionEnd(*child_div);
+ ExpectPanelIsDisplayed();
+
+ // Simulate panel transition end and the panel will be hidden
+ SimulateTransitionEnd(GetPanel());
ExpectPanelIsNotDisplayed();
// The event listener should be detached. We should now make the panel
@@ -86,7 +98,7 @@ TEST_F(MediaControlPanelElementTest, StateTransitions) {
// The event listener should now be attached so we should simulate the
// transition end event and the panel will be hidden.
EventListenerAttached();
- SimulateTransitionEnd();
+ SimulateTransitionEnd(GetPanel());
ExpectPanelIsDisplayed();
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_picture_in_picture_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_picture_in_picture_button_element.cc
index 3c6c79872a8..7e1968d6860 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_picture_in_picture_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_picture_in_picture_button_element.cc
@@ -18,7 +18,7 @@ namespace blink {
MediaControlPictureInPictureButtonElement::
MediaControlPictureInPictureButtonElement(MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaPlayButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(
AtomicString("-internal-media-controls-picture-in-picture-button"));
SetIsWanted(false);
@@ -66,7 +66,7 @@ const char* MediaControlPictureInPictureButtonElement::GetNameForHistograms()
void MediaControlPictureInPictureButtonElement::DefaultEventHandler(
Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
PictureInPictureControllerImpl& controller =
PictureInPictureControllerImpl::From(MediaElement().GetDocument());
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_play_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_play_button_element.cc
index e358f0005b7..843c19eb35c 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_play_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_play_button_element.cc
@@ -16,7 +16,7 @@ namespace blink {
MediaControlPlayButtonElement::MediaControlPlayButtonElement(
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaPlayButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(AtomicString("-webkit-media-controls-play-button"));
}
@@ -49,7 +49,7 @@ const char* MediaControlPlayButtonElement::GetNameForHistograms() const {
}
void MediaControlPlayButtonElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
if (MediaElement().paused()) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.Play"));
@@ -62,8 +62,7 @@ void MediaControlPlayButtonElement::DefaultEventHandler(Event& event) {
// state. This allows potential recovery for transient network and decoder
// resource issues.
const String& url = MediaElement().currentSrc().GetString();
- if (MediaElement().error() && !HTMLMediaElement::IsMediaStreamURL(url) &&
- !HTMLMediaSource::Lookup(url))
+ if (MediaElement().error() && !HTMLMediaSource::Lookup(url))
MediaElement().load();
MediaElement().TogglePlayState();
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc
index 0cb0d29c3a1..95aace33bc7 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_popup_menu_element.cc
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -47,26 +48,28 @@ class MediaControlPopupMenuElement::EventListener final
~EventListener() final = default;
void StartListening() {
- popup_menu_->addEventListener(EventTypeNames::keydown, this, false);
+ popup_menu_->addEventListener(event_type_names::kKeydown, this, false);
LocalDOMWindow* window = popup_menu_->GetDocument().domWindow();
- window->addEventListener(EventTypeNames::scroll, this, true);
+ window->addEventListener(event_type_names::kScroll, this, true);
if (DOMWindow* outer_window = window->top()) {
if (outer_window != window)
- outer_window->addEventListener(EventTypeNames::scroll, this, true);
- outer_window->addEventListener(EventTypeNames::resize, this, true);
+ outer_window->addEventListener(event_type_names::kScroll, this, true);
+ outer_window->addEventListener(event_type_names::kResize, this, true);
}
}
void StopListening() {
- popup_menu_->removeEventListener(EventTypeNames::keydown, this, false);
+ popup_menu_->removeEventListener(event_type_names::kKeydown, this, false);
LocalDOMWindow* window = popup_menu_->GetDocument().domWindow();
- window->removeEventListener(EventTypeNames::scroll, this, true);
+ window->removeEventListener(event_type_names::kScroll, this, true);
if (DOMWindow* outer_window = window->top()) {
- if (outer_window != window)
- outer_window->removeEventListener(EventTypeNames::scroll, this, true);
- outer_window->removeEventListener(EventTypeNames::resize, this, true);
+ if (outer_window != window) {
+ outer_window->removeEventListener(event_type_names::kScroll, this,
+ true);
+ }
+ outer_window->removeEventListener(event_type_names::kResize, this, true);
}
}
@@ -80,8 +83,9 @@ class MediaControlPopupMenuElement::EventListener final
}
private:
- void handleEvent(ExecutionContext*, Event* event) final {
- if (event->type() == EventTypeNames::keydown && event->IsKeyboardEvent()) {
+ void Invoke(ExecutionContext*, Event* event) final {
+ if (event->type() == event_type_names::kKeydown &&
+ event->IsKeyboardEvent()) {
KeyboardEvent* keyboard_event = ToKeyboardEvent(event);
bool handled = true;
@@ -111,8 +115,8 @@ class MediaControlPopupMenuElement::EventListener final
event->stopPropagation();
event->SetDefaultHandled();
}
- } else if (event->type() == EventTypeNames::resize ||
- event->type() == EventTypeNames::scroll) {
+ } else if (event->type() == event_type_names::kResize ||
+ event->type() == event_type_names::kScroll) {
popup_menu_->SetIsWanted(false);
}
}
@@ -131,7 +135,7 @@ void MediaControlPopupMenuElement::SetIsWanted(bool wanted) {
SelectFirstItem();
if (!event_listener_)
- event_listener_ = new EventListener(this);
+ event_listener_ = MakeGarbageCollected<EventListener>(this);
event_listener_->StartListening();
} else {
if (event_listener_)
@@ -144,15 +148,15 @@ void MediaControlPopupMenuElement::OnItemSelected() {
}
void MediaControlPopupMenuElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::pointermove) {
+ if (event.type() == event_type_names::kPointermove) {
ToElement(event.target()->ToNode())->focus();
- } else if (event.type() == EventTypeNames::focusout) {
+ } else if (event.type() == event_type_names::kFocusout) {
GetDocument()
.GetTaskRunner(TaskType::kMediaElementEvent)
->PostTask(FROM_HERE,
WTF::Bind(&MediaControlPopupMenuElement::HideIfNotFocused,
WrapWeakPersistent(this)));
- } else if (event.type() == EventTypeNames::click) {
+ } else if (event.type() == event_type_names::kClick) {
OnItemSelected();
event.stopPropagation();
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_scrubbing_message_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_scrubbing_message_element_test.cc
index 127612e505b..b2a1718ab1a 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_scrubbing_message_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_scrubbing_message_element_test.cc
@@ -26,7 +26,7 @@ class MediaControlScrubbingMessageElementTest : public PageTestBase {
// Create page and add a video element with controls.
PageTestBase::SetUp();
media_element_ = HTMLVideoElement::Create(GetDocument());
- media_element_->SetBooleanAttribute(HTMLNames::controlsAttr, true);
+ media_element_->SetBooleanAttribute(html_names::kControlsAttr, true);
GetDocument().body()->AppendChild(media_element_);
// Create instance of MediaControlScrubbingMessageElement to run tests on.
@@ -34,7 +34,8 @@ class MediaControlScrubbingMessageElementTest : public PageTestBase {
static_cast<MediaControlsImpl*>(media_element_->GetMediaControls());
ASSERT_NE(nullptr, media_controls_);
message_element_ =
- new MediaControlScrubbingMessageElement(*media_controls_);
+ MakeGarbageCollected<MediaControlScrubbingMessageElement>(
+ *media_controls_);
}
protected:
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_slider_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_slider_element.cc
index e1f55e00caf..e587c04e10c 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_slider_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_slider_element.cc
@@ -88,9 +88,10 @@ MediaControlSliderElement::MediaControlSliderElement(
segment_highlight_after_(nullptr),
resize_observer_(ResizeObserver::Create(
GetDocument(),
- new MediaControlSliderElementResizeObserverDelegate(this))) {
- setType(InputTypeNames::range);
- setAttribute(HTMLNames::stepAttr, "any");
+ MakeGarbageCollected<MediaControlSliderElementResizeObserverDelegate>(
+ this))) {
+ setType(input_type_names::kRange);
+ setAttribute(html_names::kStepAttr, "any");
resize_observer_->observe(this);
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc
index c04a9512b28..ec67e954426 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc
@@ -63,6 +63,9 @@ void MediaControlTextTrackListElement::SetIsWanted(bool wanted) {
if (wanted)
RefreshTextTrackListMenu();
+ if (!wanted && !GetMediaControls().OverflowMenuIsWanted())
+ GetMediaControls().CloseOverflowMenu();
+
MediaControlPopupMenuElement::SetIsWanted(wanted);
}
@@ -71,12 +74,12 @@ Element* MediaControlTextTrackListElement::PopupAnchor() const {
}
void MediaControlTextTrackListElement::DefaultEventHandler(Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
// This handles the back button click. Clicking on a menu item triggers the
// change event instead.
GetMediaControls().ToggleOverflowMenu();
event.SetDefaultHandled();
- } else if (event.type() == EventTypeNames::change) {
+ } else if (event.type() == event_type_names::kChange) {
// Identify which input element was selected and set track to showing
Node* target = event.target()->ToNode();
if (!target || !target->IsElementNode())
@@ -108,7 +111,7 @@ Element* MediaControlTextTrackListElement::CreateTextTrackListItem(
HTMLInputElement::Create(GetDocument(), CreateElementFlags());
track_item_input->SetShadowPseudoId(
AtomicString("-internal-media-controls-text-track-list-item-input"));
- track_item_input->setType(InputTypeNames::checkbox);
+ track_item_input->setType(input_type_names::kCheckbox);
track_item_input->SetIntegralAttribute(TrackIndexAttrName(), track_index);
if (!MediaElement().TextTracksVisible()) {
if (!track)
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.cc
index 456171e86fd..9679e4a3bdc 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.cc
@@ -34,6 +34,7 @@
namespace {
const double kCurrentTimeBufferedDelta = 1.0;
+const int kThumbRadius = 6;
// Only respond to main button of primary pointer(s).
bool IsValidPointerEvent(const blink::Event& event) {
@@ -81,13 +82,13 @@ bool MediaControlTimelineElement::WillRespondToMouseClickEvents() {
void MediaControlTimelineElement::SetPosition(double current_time) {
setValue(String::Number(current_time));
setAttribute(
- HTMLNames::aria_valuetextAttr,
+ html_names::kAriaValuetextAttr,
AtomicString(GetMediaControls().CurrentTimeDisplay().textContent(true)));
RenderBarSegments();
}
void MediaControlTimelineElement::SetDuration(double duration) {
- SetFloatingPointAttribute(HTMLNames::maxAttr,
+ SetFloatingPointAttribute(html_names::kMaxAttr,
std::isfinite(duration) ? duration : 0);
RenderBarSegments();
}
@@ -116,7 +117,7 @@ void MediaControlTimelineElement::DefaultEventHandler(Event& event) {
UserMetricsAction("Media.Controls.ScrubbingBegin"));
GetMediaControls().BeginScrubbing(MediaControlsImpl::IsTouchEvent(&event));
Element* thumb = UserAgentShadowRoot()->getElementById(
- ShadowElementNames::SliderThumb());
+ shadow_element_names::SliderThumb());
bool started_from_thumb = thumb && thumb == event.target()->ToNode();
metrics_.StartGesture(started_from_thumb);
} else if (EndScrubbingEvent(event)) {
@@ -126,10 +127,10 @@ void MediaControlTimelineElement::DefaultEventHandler(Event& event) {
metrics_.RecordEndGesture(TrackWidth(), MediaElement().duration());
}
- if (event.type() == EventTypeNames::keydown) {
+ if (event.type() == event_type_names::kKeydown) {
metrics_.StartKey();
}
- if (event.type() == EventTypeNames::keyup && event.IsKeyboardEvent()) {
+ if (event.type() == event_type_names::kKeyup && event.IsKeyboardEvent()) {
metrics_.RecordEndKey(TrackWidth(), ToKeyboardEvent(event).keyCode());
}
@@ -141,7 +142,7 @@ void MediaControlTimelineElement::DefaultEventHandler(Event& event) {
}
// Update the value based on the touchmove event.
- if (is_touching_ && event.type() == EventTypeNames::touchmove) {
+ if (is_touching_ && event.type() == event_type_names::kTouchmove) {
auto& touch_event = ToTouchEvent(event);
if (touch_event.touches()->length() != 1)
return;
@@ -150,7 +151,7 @@ void MediaControlTimelineElement::DefaultEventHandler(Event& event) {
double position =
max(0.0, fmin(1.0, touch->clientX() / TrackWidth() * ZoomFactor()));
SetPosition(position * MediaElement().duration());
- } else if (event.type() != EventTypeNames::input) {
+ } else if (event.type() != event_type_names::kInput) {
return;
}
@@ -198,6 +199,18 @@ void MediaControlTimelineElement::RenderBarSegments() {
}
double current_position = current_time / duration;
+
+ // Transform the current_position to always align with the center of thumb
+ // At time 0, the thumb's center is 6px away from beginning of progress bar
+ // At the end of video, thumb's center is -6px away from end of progress bar
+ // Convert 6px into ratio respect to progress bar width since
+ // current_position is range from 0 to 1
+ double width = TrackWidth() / ZoomFactor();
+ if (width != 0) {
+ double offset = kThumbRadius / width;
+ current_position += offset - 2 * offset * current_position;
+ }
+
MediaControlSliderElement::Position before_segment(0, 0);
MediaControlSliderElement::Position after_segment(0, 0);
@@ -259,11 +272,11 @@ void MediaControlTimelineElement::Trace(blink::Visitor* visitor) {
}
bool MediaControlTimelineElement::BeginScrubbingEvent(Event& event) {
- if (event.type() == EventTypeNames::touchstart) {
+ if (event.type() == event_type_names::kTouchstart) {
is_touching_ = true;
return true;
}
- if (event.type() == EventTypeNames::pointerdown)
+ if (event.type() == event_type_names::kPointerdown)
return IsValidPointerEvent(event);
return false;
@@ -282,14 +295,14 @@ void MediaControlTimelineElement::OnControlsShown() {
bool MediaControlTimelineElement::EndScrubbingEvent(Event& event) {
if (is_touching_) {
- if (event.type() == EventTypeNames::touchend ||
- event.type() == EventTypeNames::touchcancel ||
- event.type() == EventTypeNames::change) {
+ if (event.type() == event_type_names::kTouchend ||
+ event.type() == event_type_names::kTouchcancel ||
+ event.type() == event_type_names::kChange) {
is_touching_ = false;
return true;
}
- } else if (event.type() == EventTypeNames::pointerup ||
- event.type() == EventTypeNames::pointercancel) {
+ } else if (event.type() == event_type_names::kPointerup ||
+ event.type() == event_type_names::kPointercancel) {
return IsValidPointerEvent(event);
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element_test.cc
index b0697b0be55..9e1eb2d0d8b 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element_test.cc
@@ -17,21 +17,23 @@ namespace blink {
class MediaControlTimelineElementTest : public PageTestBase {
public:
- static PointerEventInit GetValidPointerEventInit() {
- PointerEventInit init;
- init.setIsPrimary(true);
- init.setButton(static_cast<int>(WebPointerProperties::Button::kLeft));
+ static PointerEventInit* GetValidPointerEventInit() {
+ PointerEventInit* init = PointerEventInit::Create();
+ init->setIsPrimary(true);
+ init->setButton(static_cast<int>(WebPointerProperties::Button::kLeft));
return init;
}
- static TouchEventInit GetValidTouchEventInit() { return TouchEventInit(); }
+ static TouchEventInit* GetValidTouchEventInit() {
+ return TouchEventInit::Create();
+ }
void SetUp() override {
PageTestBase::SetUp(IntSize(100, 100));
video_ = HTMLVideoElement::Create(GetDocument());
- controls_ = new MediaControlsImpl(*video_);
- timeline_ = new MediaControlTimelineElement(*controls_);
+ controls_ = MakeGarbageCollected<MediaControlsImpl>(*video_);
+ timeline_ = MakeGarbageCollected<MediaControlTimelineElement>(*controls_);
controls_->InitializeControls();
@@ -63,8 +65,8 @@ TEST_F(MediaControlTimelineElementTest, PointerDownRightClickNoOp) {
Video()->Play();
ASSERT_FALSE(Video()->paused());
- PointerEventInit init = GetValidPointerEventInit();
- init.setButton(static_cast<int>(WebPointerProperties::Button::kRight));
+ PointerEventInit* init = GetValidPointerEventInit();
+ init->setButton(static_cast<int>(WebPointerProperties::Button::kRight));
Timeline()->DispatchEvent(*PointerEvent::Create("pointerdown", init));
EXPECT_FALSE(Video()->paused());
}
@@ -73,8 +75,8 @@ TEST_F(MediaControlTimelineElementTest, PointerDownNotPrimaryNoOp) {
Video()->Play();
ASSERT_FALSE(Video()->paused());
- PointerEventInit init = GetValidPointerEventInit();
- init.setIsPrimary(false);
+ PointerEventInit* init = GetValidPointerEventInit();
+ init->setIsPrimary(false);
Timeline()->DispatchEvent(*PointerEvent::Create("pointerdown", init));
EXPECT_FALSE(Video()->paused());
}
@@ -97,8 +99,8 @@ TEST_F(MediaControlTimelineElementTest, PointerUpRightClickNoOp) {
Timeline()->DispatchEvent(
*PointerEvent::Create("pointerdown", GetValidPointerEventInit()));
- PointerEventInit init = GetValidPointerEventInit();
- init.setButton(static_cast<int>(WebPointerProperties::Button::kRight));
+ PointerEventInit* init = GetValidPointerEventInit();
+ init->setButton(static_cast<int>(WebPointerProperties::Button::kRight));
Timeline()->DispatchEvent(*PointerEvent::Create("pointerup", init));
EXPECT_TRUE(Video()->paused());
}
@@ -110,8 +112,8 @@ TEST_F(MediaControlTimelineElementTest, PointerUpNotPrimaryNoOp) {
Timeline()->DispatchEvent(
*PointerEvent::Create("pointerdown", GetValidPointerEventInit()));
- PointerEventInit init = GetValidPointerEventInit();
- init.setIsPrimary(false);
+ PointerEventInit* init = GetValidPointerEventInit();
+ init->setIsPrimary(false);
Timeline()->DispatchEvent(*PointerEvent::Create("pointerup", init));
EXPECT_TRUE(Video()->paused());
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.cc
index fae04b5917a..3b9c4470345 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.cc
@@ -46,7 +46,7 @@ MediaControlToggleClosedCaptionsButtonElement::
MediaControlToggleClosedCaptionsButtonElement(
MediaControlsImpl& media_controls)
: MediaControlInputElement(media_controls, kMediaShowClosedCaptionsButton) {
- setType(InputTypeNames::button);
+ setType(input_type_names::kButton);
SetShadowPseudoId(
AtomicString("-webkit-media-controls-toggle-closed-captions-button"));
SetClass(kClosedCaptionClass, UseClosedCaptionsIcon());
@@ -104,7 +104,7 @@ MediaControlToggleClosedCaptionsButtonElement::GetNameForHistograms() const {
void MediaControlToggleClosedCaptionsButtonElement::DefaultEventHandler(
Event& event) {
- if (event.type() == EventTypeNames::click) {
+ if (event.type() == event_type_names::kClick) {
if (MediaElement().textTracks()->length() == 1) {
// If only one track exists, toggle it on/off
if (MediaElement().textTracks()->HasShowingTracks())
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element_test.cc
index 76086f07951..aa591e2fd23 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element_test.cc
@@ -39,7 +39,8 @@ class MediaControlToggleClosedCaptionsButtonElementTest : public PageTestBase {
media_controls_ =
static_cast<MediaControlsImpl*>(media_element_->GetMediaControls());
captions_overflow_button_ =
- new MediaControlToggleClosedCaptionsButtonElement(*media_controls_);
+ MakeGarbageCollected<MediaControlToggleClosedCaptionsButtonElement>(
+ *media_controls_);
}
protected:
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc
index 2ffacc5f603..c5dc536c6d0 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc
@@ -10,21 +10,16 @@
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
namespace blink {
-namespace {
-
-const char kClosedCSSClass[] = "closed";
-
-} // anonymous namespace
-
MediaControlVolumeSliderElement::MediaControlVolumeSliderElement(
MediaControlsImpl& media_controls)
: MediaControlSliderElement(media_controls, kMediaVolumeSlider) {
- setAttribute(HTMLNames::maxAttr, "1");
+ setAttribute(html_names::kMaxAttr, "1");
SetShadowPseudoId(AtomicString("-webkit-media-controls-volume-slider"));
SetVolumeInternal(MediaElement().volume());
@@ -78,30 +73,30 @@ void MediaControlVolumeSliderElement::DefaultEventHandler(Event& event) {
MaybeRecordInteracted();
}
- if (event.type() == EventTypeNames::pointerdown) {
+ if (event.type() == event_type_names::kPointerdown) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.VolumeChangeBegin"));
}
- if (event.type() == EventTypeNames::pointerup) {
+ if (event.type() == event_type_names::kPointerup) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.VolumeChangeEnd"));
}
- if (event.type() == EventTypeNames::input) {
+ if (event.type() == event_type_names::kInput) {
double volume = value().ToDouble();
MediaElement().setVolume(volume);
MediaElement().setMuted(false);
SetVolumeInternal(volume);
}
- if (event.type() == EventTypeNames::mouseover ||
- event.type() == EventTypeNames::focus) {
+ if (event.type() == event_type_names::kMouseover ||
+ event.type() == event_type_names::kFocus) {
GetMediaControls().OpenVolumeSliderIfNecessary();
}
- if (event.type() == EventTypeNames::mouseout ||
- event.type() == EventTypeNames::blur) {
+ if (event.type() == event_type_names::kMouseout ||
+ event.type() == event_type_names::kBlur) {
GetMediaControls().CloseVolumeSliderIfNecessary();
}
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.cc
index c7306b258cb..6ec2a003c3e 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.cc
@@ -43,17 +43,18 @@ MediaControlsDisplayCutoutDelegate::MediaControlsDisplayCutoutDelegate(
void MediaControlsDisplayCutoutDelegate::Attach() {
DCHECK(video_element_->isConnected());
- GetDocument().addEventListener(EventTypeNames::fullscreenchange, this, true);
- GetDocument().addEventListener(EventTypeNames::webkitfullscreenchange, this,
+ GetDocument().addEventListener(event_type_names::kFullscreenchange, this,
true);
+ GetDocument().addEventListener(event_type_names::kWebkitfullscreenchange,
+ this, true);
}
void MediaControlsDisplayCutoutDelegate::Detach() {
DCHECK(!video_element_->isConnected());
- GetDocument().removeEventListener(EventTypeNames::fullscreenchange, this,
+ GetDocument().removeEventListener(event_type_names::kFullscreenchange, this,
true);
- GetDocument().removeEventListener(EventTypeNames::webkitfullscreenchange,
+ GetDocument().removeEventListener(event_type_names::kWebkitfullscreenchange,
this, true);
}
@@ -68,30 +69,32 @@ void MediaControlsDisplayCutoutDelegate::Trace(blink::Visitor* visitor) {
}
void MediaControlsDisplayCutoutDelegate::DidEnterFullscreen() {
- video_element_->addEventListener(EventTypeNames::touchstart, this, true);
- video_element_->addEventListener(EventTypeNames::touchend, this, true);
- video_element_->addEventListener(EventTypeNames::touchmove, this, true);
- video_element_->addEventListener(EventTypeNames::touchcancel, this, true);
+ video_element_->addEventListener(event_type_names::kTouchstart, this, true);
+ video_element_->addEventListener(event_type_names::kTouchend, this, true);
+ video_element_->addEventListener(event_type_names::kTouchmove, this, true);
+ video_element_->addEventListener(event_type_names::kTouchcancel, this, true);
}
void MediaControlsDisplayCutoutDelegate::DidExitFullscreen() {
GetDocument().GetViewportData().SetExpandIntoDisplayCutout(false);
- video_element_->removeEventListener(EventTypeNames::touchstart, this, true);
- video_element_->removeEventListener(EventTypeNames::touchend, this, true);
- video_element_->removeEventListener(EventTypeNames::touchmove, this, true);
- video_element_->removeEventListener(EventTypeNames::touchcancel, this, true);
+ video_element_->removeEventListener(event_type_names::kTouchstart, this,
+ true);
+ video_element_->removeEventListener(event_type_names::kTouchend, this, true);
+ video_element_->removeEventListener(event_type_names::kTouchmove, this, true);
+ video_element_->removeEventListener(event_type_names::kTouchcancel, this,
+ true);
}
-void MediaControlsDisplayCutoutDelegate::handleEvent(
+void MediaControlsDisplayCutoutDelegate::Invoke(
ExecutionContext* execution_context,
Event* event) {
if (event->IsTouchEvent()) {
HandleTouchEvent(ToTouchEvent(event));
return;
}
- if (event->type() == EventTypeNames::fullscreenchange ||
- event->type() == EventTypeNames::webkitfullscreenchange) {
+ if (event->type() == event_type_names::kFullscreenchange ||
+ event->type() == event_type_names::kWebkitfullscreenchange) {
// The fullscreen state has changed.
if (video_element_->IsFullscreen()) {
DidEnterFullscreen();
@@ -118,7 +121,7 @@ void MediaControlsDisplayCutoutDelegate::HandleTouchEvent(TouchEvent* event) {
// If it is a touch start event then we should flush any previous points we
// have stored.
- if (event->type() == EventTypeNames::touchstart)
+ if (event->type() == event_type_names::kTouchstart)
previous_.reset();
// Extract the two touch points and calculate the distance.
@@ -154,8 +157,8 @@ void MediaControlsDisplayCutoutDelegate::HandleTouchEvent(TouchEvent* event) {
// If we are finishing a touch then clear any stored value, otherwise store
// the latest distance.
- if (event->type() == EventTypeNames::touchend ||
- event->type() == EventTypeNames::touchcancel) {
+ if (event->type() == event_type_names::kTouchend ||
+ event->type() == event_type_names::kTouchcancel) {
DCHECK(previous_.has_value());
previous_.reset();
} else {
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h
index baae1e1a1ce..3ccce82c0a7 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h
@@ -57,7 +57,7 @@ class MODULES_EXPORT MediaControlsDisplayCutoutDelegate final
void DidExitFullscreen();
// EventListener implementation.
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
void HandleTouchEvent(TouchEvent*);
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc
index 04eb76ab939..7400de9b652 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc
@@ -26,7 +26,7 @@ namespace {
class DisplayCutoutMockChromeClient : public EmptyChromeClient {
public:
// ChromeClient overrides:
- void EnterFullscreen(LocalFrame& frame, const FullscreenOptions&) override {
+ void EnterFullscreen(LocalFrame& frame, const FullscreenOptions*) override {
Fullscreen::DidEnterFullscreen(*frame.GetDocument());
}
void ExitFullscreen(LocalFrame& frame) override {
@@ -75,35 +75,38 @@ class MediaControlsDisplayCutoutDelegateTest : public PageTestBase {
void SimulateContractingGesture() {
TouchList* list = CreateTouchListWithTwoPoints(5, 5, -5, -5);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(
+ CreateTouchEventWithList(event_type_names::kTouchstart, list));
list = CreateTouchListWithTwoPoints(4, 4, -4, -4);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchmove, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchmove, list));
list = CreateTouchListWithTwoPoints(0, 0, 0, 0);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchend, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchend, list));
}
void SimulateExpandingGesture() {
TouchList* list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(
+ CreateTouchEventWithList(event_type_names::kTouchstart, list));
list = CreateTouchListWithTwoPoints(4, 4, -4, -4);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchmove, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchmove, list));
list = CreateTouchListWithTwoPoints(5, 5, -5, -5);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchend, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchend, list));
}
void SimulateSingleTouchGesture() {
TouchList* list = CreateTouchListWithOnePoint(1, 1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(
+ CreateTouchEventWithList(event_type_names::kTouchstart, list));
list = CreateTouchListWithOnePoint(4, 4);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchmove, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchmove, list));
list = CreateTouchListWithOnePoint(5, 5);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchend, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchend, list));
}
bool HasGestureState() { return GetDelegate().previous_.has_value(); }
@@ -173,16 +176,16 @@ TEST_F(MediaControlsDisplayCutoutDelegateTest, CombinedGesture) {
// Simulate the an expanding gesture but do not finish it.
TouchList* list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchstart, list));
list = CreateTouchListWithTwoPoints(4, 4, -4, -4);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchmove, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchmove, list));
// Check the viewport fit value has been correctly set.
EXPECT_EQ(mojom::ViewportFit::kCoverForcedByUserAgent, CurrentViewportFit());
// Finish the gesture by contracting.
list = CreateTouchListWithTwoPoints(0, 0, 0, 0);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchend, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchend, list));
// Check the viewport fit value has been correctly set.
EXPECT_EQ(mojom::ViewportFit::kAuto, CurrentViewportFit());
@@ -253,15 +256,15 @@ TEST_F(MediaControlsDisplayCutoutDelegateTest, IncompleteGestureClearsState) {
// Simulate a gesture and check we have state.
TouchList* list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchstart, list));
list = CreateTouchListWithTwoPoints(2, 2, -2, -2);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchmove, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchmove, list));
EXPECT_TRUE(DirectionIsExpanding());
// Simulate another start gesture and make sure we do not have a direction.
list = CreateTouchListWithTwoPoints(3, 3, -3, -3);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchstart, list));
EXPECT_TRUE(DirectionIsUnknown());
}
@@ -288,12 +291,12 @@ TEST_F(MediaControlsDisplayCutoutDelegateTest, TouchCancelShouldClearState) {
// Simulate a gesture and check we have state.
TouchList* list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchstart, list));
EXPECT_TRUE(HasGestureState());
// Simulate a touchcancel gesture and check that clears the state.
list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchcancel, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchcancel, list));
EXPECT_FALSE(HasGestureState());
EXPECT_EQ(mojom::ViewportFit::kAuto, CurrentViewportFit());
}
@@ -303,12 +306,12 @@ TEST_F(MediaControlsDisplayCutoutDelegateTest, TouchEndShouldClearState) {
// Simulate a gesture and check we have state.
TouchList* list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchstart, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchstart, list));
EXPECT_TRUE(HasGestureState());
// Simulate a touchend gesture and check that clears the state.
list = CreateTouchListWithTwoPoints(1, 1, -1, -1);
- SimulateEvent(CreateTouchEventWithList(EventTypeNames::touchend, list));
+ SimulateEvent(CreateTouchEventWithList(event_type_names::kTouchend, list));
EXPECT_FALSE(HasGestureState());
EXPECT_EQ(mojom::ViewportFit::kAuto, CurrentViewportFit());
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
index 43a10f53557..94816019705 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
+#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_size.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_html.h"
@@ -86,6 +87,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -135,6 +137,14 @@ const char kImmersiveModeCSSClass[] = "immersive-mode";
// The delay between two taps to be recognized as a double tap gesture.
constexpr WTF::TimeDelta kDoubleTapDelay = TimeDelta::FromMilliseconds(300);
+// The time user have to hover on mute button to show volume slider.
+// If this value is changed, you need to change the corresponding value in
+// media_controls_impl_test.cc
+constexpr WTF::TimeDelta kTimeToShowVolumeSlider =
+ TimeDelta::FromMilliseconds(200);
+constexpr WTF::TimeDelta kTimeToShowVolumeSliderTest =
+ TimeDelta::FromMilliseconds(0);
+
// The number of seconds to jump when double tapping.
constexpr int kNumberOfSecondsToJump = 10;
@@ -176,7 +186,7 @@ bool ShouldShowPictureInPictureButton(HTMLMediaElement& media_element) {
}
bool ShouldShowCastButton(HTMLMediaElement& media_element) {
- if (media_element.FastHasAttribute(HTMLNames::disableremoteplaybackAttr))
+ if (media_element.FastHasAttribute(html_names::kDisableremoteplaybackAttr))
return false;
// Explicitly do not show cast button when:
@@ -209,7 +219,7 @@ bool PreferHiddenVolumeControls(const Document& document) {
}
// If you change this value, then also update the corresponding value in
-// LayoutTests/media/media-controls.js.
+// web_tests/media/media-controls.js.
constexpr TimeDelta kTimeWithoutMouseMovementBeforeHidingMediaControls =
TimeDelta::FromSeconds(3);
constexpr TimeDelta kModernTimeWithoutMouseMovementBeforeHidingMediaControls =
@@ -280,12 +290,13 @@ class MediaControlsImpl::MediaElementMutationCallback
public:
explicit MediaElementMutationCallback(MediaControlsImpl* controls)
: controls_(controls), observer_(MutationObserver::Create(this)) {
- MutationObserverInit init;
- init.setAttributeOldValue(true);
- init.setAttributes(true);
- init.setAttributeFilter({HTMLNames::disableremoteplaybackAttr.ToString(),
- HTMLNames::disablepictureinpictureAttr.ToString(),
- HTMLNames::posterAttr.ToString()});
+ MutationObserverInit* init = MutationObserverInit::Create();
+ init->setAttributeOldValue(true);
+ init->setAttributes(true);
+ init->setAttributeFilter(
+ {html_names::kDisableremoteplaybackAttr.ToString(),
+ html_names::kDisablepictureinpictureAttr.ToString(),
+ html_names::kPosterAttr.ToString()});
observer_->observe(&controls_->MediaElement(), init, ASSERT_NO_EXCEPTION);
}
@@ -304,18 +315,18 @@ class MediaControlsImpl::MediaElementMutationCallback
continue;
if (record->attributeName() ==
- HTMLNames::disableremoteplaybackAttr.ToString()) {
+ html_names::kDisableremoteplaybackAttr.ToString()) {
controls_->RefreshCastButtonVisibilityWithoutUpdate();
}
if (record->attributeName() ==
- HTMLNames::disablepictureinpictureAttr.ToString() &&
+ html_names::kDisablepictureinpictureAttr.ToString() &&
controls_->picture_in_picture_button_) {
controls_->picture_in_picture_button_->SetIsWanted(
ShouldShowPictureInPictureButton(controls_->MediaElement()));
}
- if (record->attributeName() == HTMLNames::posterAttr.ToString())
+ if (record->attributeName() == html_names::kPosterAttr.ToString())
controls_->UpdateCSSClassFromState();
BatchedControlUpdate batch(controls_);
@@ -371,7 +382,8 @@ MediaControlsImpl::MediaControlsImpl(HTMLMediaElement& media_element)
fullscreen_button_(nullptr),
display_cutout_fullscreen_button_(nullptr),
download_button_(nullptr),
- media_event_listener_(new MediaControlsMediaEventListener(this)),
+ media_event_listener_(
+ MakeGarbageCollected<MediaControlsMediaEventListener>(this)),
orientation_lock_delegate_(nullptr),
rotate_to_fullscreen_delegate_(nullptr),
display_cutout_delegate_(nullptr),
@@ -384,7 +396,7 @@ MediaControlsImpl::MediaControlsImpl(HTMLMediaElement& media_element)
is_paused_for_scrubbing_(false),
resize_observer_(ResizeObserver::Create(
media_element.GetDocument(),
- new MediaControlsResizeObserverDelegate(this))),
+ MakeGarbageCollected<MediaControlsResizeObserverDelegate>(this))),
element_size_changed_timer_(
media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
this,
@@ -393,7 +405,11 @@ MediaControlsImpl::MediaControlsImpl(HTMLMediaElement& media_element)
tap_timer_(
media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
this,
- &MediaControlsImpl::TapTimerFired) {
+ &MediaControlsImpl::TapTimerFired),
+ volume_slider_wanted_timer_(
+ media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
+ this,
+ &MediaControlsImpl::VolumeSliderWantedTimerFired) {
// On touch devices, start with the assumption that the user will interact via
// touch events.
Settings* settings = media_element.GetDocument().GetSettings();
@@ -404,7 +420,8 @@ MediaControlsImpl::MediaControlsImpl(HTMLMediaElement& media_element)
MediaControlsImpl* MediaControlsImpl::Create(HTMLMediaElement& media_element,
ShadowRoot& shadow_root) {
- MediaControlsImpl* controls = new MediaControlsImpl(media_element);
+ MediaControlsImpl* controls =
+ MakeGarbageCollected<MediaControlsImpl>(media_element);
controls->SetShadowPseudoId(AtomicString("-webkit-media-controls"));
controls->InitializeControls();
controls->Reset();
@@ -413,22 +430,23 @@ MediaControlsImpl* MediaControlsImpl::Create(HTMLMediaElement& media_element,
media_element.IsHTMLVideoElement()) {
// Initialize the orientation lock when going fullscreen feature.
controls->orientation_lock_delegate_ =
- new MediaControlsOrientationLockDelegate(
+ MakeGarbageCollected<MediaControlsOrientationLockDelegate>(
ToHTMLVideoElement(media_element));
}
if (MediaControlsDisplayCutoutDelegate::IsEnabled() &&
media_element.IsHTMLVideoElement()) {
// Initialize the pinch gesture to expand into the display cutout feature.
- controls->display_cutout_delegate_ = new MediaControlsDisplayCutoutDelegate(
- ToHTMLVideoElement(media_element));
+ controls->display_cutout_delegate_ =
+ MakeGarbageCollected<MediaControlsDisplayCutoutDelegate>(
+ ToHTMLVideoElement(media_element));
}
if (RuntimeEnabledFeatures::VideoRotateToFullscreenEnabled() &&
media_element.IsHTMLVideoElement()) {
// Initialize the rotate-to-fullscreen feature.
controls->rotate_to_fullscreen_delegate_ =
- new MediaControlsRotateToFullscreenDelegate(
+ MakeGarbageCollected<MediaControlsRotateToFullscreenDelegate>(
ToHTMLVideoElement(media_element));
}
@@ -439,7 +457,7 @@ MediaControlsImpl* MediaControlsImpl::Create(HTMLMediaElement& media_element,
->GetMediaDownloadInProductHelpEnabled() &&
media_element.IsHTMLVideoElement()) {
controls->download_iph_manager_ =
- new MediaDownloadInProductHelpManager(*controls);
+ MakeGarbageCollected<MediaDownloadInProductHelpManager>(*controls);
}
MediaControlsResourceLoader::InjectMediaControlsUAStyleSheet();
@@ -522,47 +540,55 @@ MediaControlsImpl* MediaControlsImpl::Create(HTMLMediaElement& media_element,
// (-internal-media-controls-display-cutout-fullscreen-button)
void MediaControlsImpl::InitializeControls() {
if (IsModern() && ShouldShowVideoControls()) {
- loading_panel_ = new MediaControlLoadingPanelElement(*this);
+ loading_panel_ =
+ MakeGarbageCollected<MediaControlLoadingPanelElement>(*this);
ParserAppendChild(loading_panel_);
}
- overlay_enclosure_ = new MediaControlOverlayEnclosureElement(*this);
+ overlay_enclosure_ =
+ MakeGarbageCollected<MediaControlOverlayEnclosureElement>(*this);
if (RuntimeEnabledFeatures::MediaControlsOverlayPlayButtonEnabled()) {
- overlay_play_button_ = new MediaControlOverlayPlayButtonElement(*this);
+ overlay_play_button_ =
+ MakeGarbageCollected<MediaControlOverlayPlayButtonElement>(*this);
if (!IsModern())
overlay_enclosure_->ParserAppendChild(overlay_play_button_);
}
- overlay_cast_button_ = new MediaControlCastButtonElement(*this, true);
+ overlay_cast_button_ =
+ MakeGarbageCollected<MediaControlCastButtonElement>(*this, true);
overlay_enclosure_->ParserAppendChild(overlay_cast_button_);
ParserAppendChild(overlay_enclosure_);
// Create an enclosing element for the panel so we can visually offset the
// controls correctly.
- enclosure_ = new MediaControlPanelEnclosureElement(*this);
+ enclosure_ = MakeGarbageCollected<MediaControlPanelEnclosureElement>(*this);
- panel_ = new MediaControlPanelElement(*this);
+ panel_ = MakeGarbageCollected<MediaControlPanelElement>(*this);
// If using the modern media controls, the buttons should belong to a
// seperate button panel. This is because they are displayed in two lines.
if (IsModern() && ShouldShowVideoControls()) {
- media_button_panel_ = new MediaControlButtonPanelElement(*this);
- scrubbing_message_ = new MediaControlScrubbingMessageElement(*this);
+ media_button_panel_ =
+ MakeGarbageCollected<MediaControlButtonPanelElement>(*this);
+ scrubbing_message_ =
+ MakeGarbageCollected<MediaControlScrubbingMessageElement>(*this);
}
- play_button_ = new MediaControlPlayButtonElement(*this);
+ play_button_ = MakeGarbageCollected<MediaControlPlayButtonElement>(*this);
- current_time_display_ = new MediaControlCurrentTimeDisplayElement(*this);
+ current_time_display_ =
+ MakeGarbageCollected<MediaControlCurrentTimeDisplayElement>(*this);
current_time_display_->SetIsWanted(true);
- duration_display_ = new MediaControlRemainingTimeDisplayElement(*this);
- timeline_ = new MediaControlTimelineElement(*this);
- mute_button_ = new MediaControlMuteButtonElement(*this);
+ duration_display_ =
+ MakeGarbageCollected<MediaControlRemainingTimeDisplayElement>(*this);
+ timeline_ = MakeGarbageCollected<MediaControlTimelineElement>(*this);
+ mute_button_ = MakeGarbageCollected<MediaControlMuteButtonElement>(*this);
- volume_slider_ = new MediaControlVolumeSliderElement(*this);
+ volume_slider_ = MakeGarbageCollected<MediaControlVolumeSliderElement>(*this);
if (PreferHiddenVolumeControls(GetDocument()))
volume_slider_->SetIsWanted(false);
@@ -571,7 +597,7 @@ void MediaControlsImpl::InitializeControls() {
GetDocument().GetSettings()->GetPictureInPictureEnabled() &&
MediaElement().IsHTMLVideoElement()) {
picture_in_picture_button_ =
- new MediaControlPictureInPictureButtonElement(*this);
+ MakeGarbageCollected<MediaControlPictureInPictureButtonElement>(*this);
picture_in_picture_button_->SetIsWanted(
ShouldShowPictureInPictureButton(MediaElement()));
}
@@ -579,25 +605,33 @@ void MediaControlsImpl::InitializeControls() {
if (RuntimeEnabledFeatures::DisplayCutoutAPIEnabled() &&
MediaElement().IsHTMLVideoElement()) {
display_cutout_fullscreen_button_ =
- new MediaControlDisplayCutoutFullscreenButtonElement(*this);
+ MakeGarbageCollected<MediaControlDisplayCutoutFullscreenButtonElement>(
+ *this);
}
- fullscreen_button_ = new MediaControlFullscreenButtonElement(*this);
- download_button_ = new MediaControlDownloadButtonElement(*this);
- cast_button_ = new MediaControlCastButtonElement(*this, false);
+ fullscreen_button_ =
+ MakeGarbageCollected<MediaControlFullscreenButtonElement>(*this);
+ download_button_ =
+ MakeGarbageCollected<MediaControlDownloadButtonElement>(*this);
+ cast_button_ =
+ MakeGarbageCollected<MediaControlCastButtonElement>(*this, false);
toggle_closed_captions_button_ =
- new MediaControlToggleClosedCaptionsButtonElement(*this);
- overflow_menu_ = new MediaControlOverflowMenuButtonElement(*this);
+ MakeGarbageCollected<MediaControlToggleClosedCaptionsButtonElement>(
+ *this);
+ overflow_menu_ =
+ MakeGarbageCollected<MediaControlOverflowMenuButtonElement>(*this);
PopulatePanel();
enclosure_->ParserAppendChild(panel_);
ParserAppendChild(enclosure_);
- text_track_list_ = new MediaControlTextTrackListElement(*this);
+ text_track_list_ =
+ MakeGarbageCollected<MediaControlTextTrackListElement>(*this);
ParserAppendChild(text_track_list_);
- overflow_list_ = new MediaControlOverflowMenuListElement(*this);
+ overflow_list_ =
+ MakeGarbageCollected<MediaControlOverflowMenuListElement>(*this);
ParserAppendChild(overflow_list_);
// The order in which we append elements to the overflow list is significant
@@ -605,22 +639,24 @@ void MediaControlsImpl::InitializeControls() {
// relative to each other. The first item appended appears at the top of the
// overflow menu.
overflow_list_->ParserAppendChild(play_button_->CreateOverflowElement(
- new MediaControlPlayButtonElement(*this)));
+ MakeGarbageCollected<MediaControlPlayButtonElement>(*this)));
overflow_list_->ParserAppendChild(fullscreen_button_->CreateOverflowElement(
- new MediaControlFullscreenButtonElement(*this)));
+ MakeGarbageCollected<MediaControlFullscreenButtonElement>(*this)));
overflow_list_->ParserAppendChild(download_button_->CreateOverflowElement(
- new MediaControlDownloadButtonElement(*this)));
+ MakeGarbageCollected<MediaControlDownloadButtonElement>(*this)));
overflow_list_->ParserAppendChild(mute_button_->CreateOverflowElement(
- new MediaControlMuteButtonElement(*this)));
+ MakeGarbageCollected<MediaControlMuteButtonElement>(*this)));
overflow_list_->ParserAppendChild(cast_button_->CreateOverflowElement(
- new MediaControlCastButtonElement(*this, false)));
+ MakeGarbageCollected<MediaControlCastButtonElement>(*this, false)));
overflow_list_->ParserAppendChild(
toggle_closed_captions_button_->CreateOverflowElement(
- new MediaControlToggleClosedCaptionsButtonElement(*this)));
+ MakeGarbageCollected<MediaControlToggleClosedCaptionsButtonElement>(
+ *this)));
if (picture_in_picture_button_) {
overflow_list_->ParserAppendChild(
picture_in_picture_button_->CreateOverflowElement(
- new MediaControlPictureInPictureButtonElement(*this)));
+ MakeGarbageCollected<MediaControlPictureInPictureButtonElement>(
+ *this)));
}
// Set the default CSS classes.
@@ -698,15 +734,17 @@ Node::InsertionNotificationRequest MediaControlsImpl::InsertedInto(
display_cutout_delegate_->Attach();
if (!resize_observer_) {
- resize_observer_ =
- ResizeObserver::Create(MediaElement().GetDocument(),
- new MediaControlsResizeObserverDelegate(this));
+ resize_observer_ = ResizeObserver::Create(
+ MediaElement().GetDocument(),
+ MakeGarbageCollected<MediaControlsResizeObserverDelegate>(this));
HTMLMediaElement& html_media_element = MediaElement();
resize_observer_->observe(&html_media_element);
}
- if (!element_mutation_callback_)
- element_mutation_callback_ = new MediaElementMutationCallback(this);
+ if (!element_mutation_callback_) {
+ element_mutation_callback_ =
+ MakeGarbageCollected<MediaElementMutationCallback>(this);
+ }
return HTMLDivElement::InsertedInto(root);
}
@@ -764,24 +802,24 @@ void MediaControlsImpl::UpdateCSSClassFromState() {
if (state == kNoSource) {
// Check if the play button or overflow menu has the "disabled" attribute
// set so we avoid unnecessarily resetting it.
- if (!play_button_->hasAttribute(HTMLNames::disabledAttr)) {
- play_button_->setAttribute(HTMLNames::disabledAttr, "");
+ if (!play_button_->hasAttribute(html_names::kDisabledAttr)) {
+ play_button_->setAttribute(html_names::kDisabledAttr, "");
updated = true;
}
if (ShouldShowVideoControls() &&
- !overflow_menu_->hasAttribute(HTMLNames::disabledAttr)) {
- overflow_menu_->setAttribute(HTMLNames::disabledAttr, "");
+ !overflow_menu_->hasAttribute(html_names::kDisabledAttr)) {
+ overflow_menu_->setAttribute(html_names::kDisabledAttr, "");
updated = true;
}
} else {
- if (play_button_->hasAttribute(HTMLNames::disabledAttr)) {
- play_button_->removeAttribute(HTMLNames::disabledAttr);
+ if (play_button_->hasAttribute(html_names::kDisabledAttr)) {
+ play_button_->removeAttribute(html_names::kDisabledAttr);
updated = true;
}
- if (overflow_menu_->hasAttribute(HTMLNames::disabledAttr)) {
- overflow_menu_->removeAttribute(HTMLNames::disabledAttr);
+ if (overflow_menu_->hasAttribute(html_names::kDisabledAttr)) {
+ overflow_menu_->removeAttribute(html_names::kDisabledAttr);
updated = true;
}
}
@@ -894,13 +932,13 @@ void MediaControlsImpl::OnControlsListUpdated() {
if (IsModern() && ShouldShowVideoControls()) {
fullscreen_button_->SetIsWanted(true);
- fullscreen_button_->setAttribute(HTMLNames::disabledAttr,
+ fullscreen_button_->setAttribute(html_names::kDisabledAttr,
ShouldShowFullscreenButton(MediaElement())
? AtomicString()
: AtomicString(""));
} else {
fullscreen_button_->SetIsWanted(ShouldShowFullscreenButton(MediaElement()));
- fullscreen_button_->removeAttribute(HTMLNames::disabledAttr);
+ fullscreen_button_->removeAttribute(html_names::kDisabledAttr);
}
RefreshCastButtonVisibilityWithoutUpdate();
@@ -1154,6 +1192,10 @@ void MediaControlsImpl::DisableShowingTextTracks() {
}
}
+bool MediaControlsImpl::TextTrackListIsWanted() {
+ return text_track_list_->IsWanted();
+}
+
String MediaControlsImpl::GetTextTrackLabel(TextTrack* track) const {
if (!track) {
return MediaElement().GetLocale().QueryString(
@@ -1234,7 +1276,7 @@ void MediaControlsImpl::ExitFullscreen() {
bool MediaControlsImpl::IsFullscreenEnabled() const {
return fullscreen_button_->IsWanted() &&
- !fullscreen_button_->hasAttribute(HTMLNames::disabledAttr);
+ !fullscreen_button_->hasAttribute(html_names::kDisabledAttr);
}
void MediaControlsImpl::RemotePlaybackStateChanged() {
@@ -1351,8 +1393,8 @@ void MediaControlsImpl::UpdateOverflowMenuWanted() const {
}
// The overflow menu is always wanted if it has the "disabled" attr set.
- overflow_wanted =
- overflow_wanted || overflow_menu_->hasAttribute(HTMLNames::disabledAttr);
+ overflow_wanted = overflow_wanted ||
+ overflow_menu_->hasAttribute(html_names::kDisabledAttr);
overflow_menu_->SetDoesFit(overflow_wanted);
overflow_menu_->SetIsWanted(overflow_wanted);
@@ -1385,10 +1427,8 @@ void MediaControlsImpl::UpdateSizingCSSClass() {
sizing_class == MediaControlsSizingClass::kSmall);
SetClass(kMediaControlsSizingMediumCSSClass,
ShouldShowVideoControls() &&
- sizing_class == MediaControlsSizingClass::kMedium);
- SetClass(kMediaControlsSizingLargeCSSClass,
- ShouldShowVideoControls() &&
- sizing_class == MediaControlsSizingClass::kLarge);
+ (sizing_class == MediaControlsSizingClass::kMedium ||
+ sizing_class == MediaControlsSizingClass::kLarge));
}
void MediaControlsImpl::MaybeToggleControlsFromTap() {
@@ -1458,24 +1498,24 @@ void MediaControlsImpl::DefaultEventHandler(Event& event) {
if (is_touch_event)
HandleTouchEvent(&event);
- if (event.type() == EventTypeNames::mouseover && !is_touch_event)
+ if (event.type() == event_type_names::kMouseover && !is_touch_event)
is_touch_interaction_ = false;
- if ((event.type() == EventTypeNames::pointerover ||
- event.type() == EventTypeNames::pointermove ||
- event.type() == EventTypeNames::pointerout) &&
+ if ((event.type() == event_type_names::kPointerover ||
+ event.type() == event_type_names::kPointermove ||
+ event.type() == event_type_names::kPointerout) &&
!is_touch_interaction_) {
HandlePointerEvent(&event);
}
- if (event.type() == EventTypeNames::click && !is_touch_interaction_)
+ if (event.type() == event_type_names::kClick && !is_touch_interaction_)
HandleClickEvent(&event);
// If the user is interacting with the controls via the keyboard, don't hide
// the controls. This will fire when the user tabs between controls (focusin)
// or when they seek either the timeline or volume sliders (input).
- if (event.type() == EventTypeNames::focusin ||
- event.type() == EventTypeNames::input) {
+ if (event.type() == event_type_names::kFocusin ||
+ event.type() == event_type_names::kInput) {
ResetHideMediaControlsTimer();
}
@@ -1504,7 +1544,7 @@ void MediaControlsImpl::DefaultEventHandler(Event& event) {
}
void MediaControlsImpl::HandlePointerEvent(Event* event) {
- if (event->type() == EventTypeNames::pointerover) {
+ if (event->type() == event_type_names::kPointerover) {
if (!ContainsRelatedTarget(event)) {
is_mouse_over_controls_ = true;
if (!MediaElement().paused()) {
@@ -1512,12 +1552,12 @@ void MediaControlsImpl::HandlePointerEvent(Event* event) {
StartHideMediaControlsIfNecessary();
}
}
- } else if (event->type() == EventTypeNames::pointerout) {
+ } else if (event->type() == event_type_names::kPointerout) {
if (!ContainsRelatedTarget(event)) {
is_mouse_over_controls_ = false;
StopHideMediaControlsTimer();
}
- } else if (event->type() == EventTypeNames::pointermove) {
+ } else if (event->type() == event_type_names::kPointermove) {
// When we get a mouse move, show the media controls, and start a timer
// that will hide the media controls after a 3 seconds without a mouse move.
is_mouse_over_controls_ = true;
@@ -1539,7 +1579,21 @@ void MediaControlsImpl::HandleClickEvent(Event* event) {
ExitFullscreen();
else
EnterFullscreen();
+
+ // If we paused for the first click of this double-click, then we need to
+ // resume playback, since the user was just toggling fullscreen.
+ if (is_paused_for_double_tap_) {
+ MediaElement().Play();
+ is_paused_for_double_tap_ = false;
+ }
} else {
+ // If the video is not paused, assume the user is clicking to pause the
+ // video. If the user clicks again for a fullscreen-toggling double-tap, we
+ // will resume playback.
+ if (!MediaElement().paused()) {
+ MediaElement().pause();
+ is_paused_for_double_tap_ = true;
+ }
tap_timer_.StartOneShot(kDoubleTapDelay, FROM_HERE);
}
}
@@ -1549,10 +1603,19 @@ void MediaControlsImpl::HandleTouchEvent(Event* event) {
is_mouse_over_controls_ = false;
is_touch_interaction_ = true;
- if (event->type() == EventTypeNames::click &&
+ if (event->type() == event_type_names::kClick &&
!ContainsRelatedTarget(event)) {
event->SetDefaultHandled();
+ // In immersive mode we don't use double-tap features, so instead of
+ // waiting 300 ms for a potential second tap, we just immediately toggle
+ // controls visiblity.
+ if (GetDocument().GetSettings() &&
+ GetDocument().GetSettings()->GetImmersiveModeEnabled()) {
+ MaybeToggleControlsFromTap();
+ return;
+ }
+
if (tap_timer_.IsActive()) {
// Cancel the visibility toggle event.
tap_timer_.Stop();
@@ -1569,7 +1632,7 @@ void MediaControlsImpl::HandleTouchEvent(Event* event) {
return;
}
- if (event->type() == EventTypeNames::gesturetap &&
+ if (event->type() == event_type_names::kGesturetap &&
!ContainsRelatedTarget(event) && !MediaElement().paused()) {
if (!IsVisible()) {
MakeOpaque();
@@ -1621,8 +1684,25 @@ bool MediaControlsImpl::IsOnLeftSide(Event* event) {
}
void MediaControlsImpl::TapTimerFired(TimerBase*) {
- if (is_touch_interaction_)
+ if (is_touch_interaction_) {
MaybeToggleControlsFromTap();
+ } else if (MediaElement().paused()) {
+ // If this is not a touch interaction and the video is paused, then either
+ // the user has just paused via click (in which case we've already paused
+ // and there's nothing to do), or the user is playing by click (in which
+ // case we need to start playing).
+ if (is_paused_for_double_tap_) {
+ Platform::Current()->RecordAction(
+ UserMetricsAction("Media.Controls.ClickAnywhereToPause"));
+ // TODO(https://crbug.com/896252): Show overlay pause animation.
+ is_paused_for_double_tap_ = false;
+ } else {
+ Platform::Current()->RecordAction(
+ UserMetricsAction("Media.Controls.ClickAnywhereToPlay"));
+ // TODO(https://crbug.com/896252): Show overlay play animation.
+ MediaElement().Play();
+ }
+ }
}
void MediaControlsImpl::HideMediaControlsTimerFired(TimerBase*) {
@@ -1689,11 +1769,11 @@ void MediaControlsImpl::OnVolumeChange() {
if (IsModern()) {
mute_button_->SetIsWanted(true);
mute_button_->setAttribute(
- HTMLNames::disabledAttr,
+ html_names::kDisabledAttr,
MediaElement().HasAudio() ? AtomicString() : AtomicString(""));
} else {
mute_button_->SetIsWanted(MediaElement().HasAudio());
- mute_button_->removeAttribute(HTMLNames::disabledAttr);
+ mute_button_->removeAttribute(html_names::kDisabledAttr);
}
// On modern media controls, if the volume slider is being used we don't want
@@ -2100,6 +2180,18 @@ void MediaControlsImpl::NetworkStateChanged() {
UpdateCSSClassFromState();
}
+void MediaControlsImpl::OpenOverflowMenu() {
+ overflow_list_->OpenOverflowMenu();
+}
+
+void MediaControlsImpl::CloseOverflowMenu() {
+ overflow_list_->CloseOverflowMenu();
+}
+
+bool MediaControlsImpl::OverflowMenuIsWanted() {
+ return overflow_list_->IsWanted();
+}
+
bool MediaControlsImpl::OverflowMenuVisible() {
return overflow_list_ ? overflow_list_->IsWanted() : false;
}
@@ -2115,14 +2207,31 @@ void MediaControlsImpl::StartHideMediaControlsIfNecessary() {
StartHideMediaControlsTimer();
}
+void MediaControlsImpl::VolumeSliderWantedTimerFired(TimerBase*) {
+ volume_slider_->OpenSlider();
+}
+
void MediaControlsImpl::OpenVolumeSliderIfNecessary() {
- if (ShouldOpenVolumeSlider())
- volume_slider_->OpenSlider();
+ if (ShouldOpenVolumeSlider()) {
+ if (volume_slider_->IsFocused() || mute_button_->IsFocused()) {
+ // When we're focusing with the keyboard, we don't need the delay.
+ volume_slider_->OpenSlider();
+ } else {
+ volume_slider_wanted_timer_.StartOneShot(
+ WebTestSupport::IsRunningWebTest() ? kTimeToShowVolumeSliderTest
+ : kTimeToShowVolumeSlider,
+ FROM_HERE);
+ }
+ }
}
void MediaControlsImpl::CloseVolumeSliderIfNecessary() {
- if (ShouldCloseVolumeSlider())
+ if (ShouldCloseVolumeSlider()) {
volume_slider_->CloseSlider();
+
+ if (volume_slider_wanted_timer_.IsActive())
+ volume_slider_wanted_timer_.Stop();
+ }
}
bool MediaControlsImpl::ShouldOpenVolumeSlider() const {
@@ -2136,7 +2245,8 @@ bool MediaControlsImpl::ShouldCloseVolumeSlider() const {
if (!volume_slider_ || !IsModern())
return false;
- return !(volume_slider_->IsHovered() || mute_button_->IsHovered());
+ return !(volume_slider_->IsHovered() || mute_button_->IsHovered() ||
+ volume_slider_->IsFocused() || mute_button_->IsFocused());
}
const MediaControlDownloadButtonElement& MediaControlsImpl::DownloadButton()
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.h b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.h
index 53e85b7e9e4..fc5927e83a6 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.h
@@ -78,6 +78,8 @@ class MODULES_EXPORT MediaControlsImpl final : public HTMLDivElement,
public:
static MediaControlsImpl* Create(HTMLMediaElement&, ShadowRoot&);
+
+ explicit MediaControlsImpl(HTMLMediaElement&);
~MediaControlsImpl() override = default;
// Returns whether the ModernMediaControlsEnabled runtime flag is on.
@@ -128,15 +130,21 @@ class MODULES_EXPORT MediaControlsImpl final : public HTMLDivElement,
void ToggleTextTrackList();
void ShowTextTrackAtIndex(unsigned);
void DisableShowingTextTracks();
+ bool TextTrackListIsWanted();
// Returns the label for the track when a valid track is passed in and "Off"
// when the parameter is null.
String GetTextTrackLabel(TextTrack*) const;
// Methods related to the overflow menu.
+ void OpenOverflowMenu();
+ void CloseOverflowMenu();
+ bool OverflowMenuIsWanted();
+
void ToggleOverflowMenu();
bool OverflowMenuVisible();
+ void VolumeSliderWantedTimerFired(TimerBase*);
void OpenVolumeSliderIfNecessary();
void CloseVolumeSliderIfNecessary();
@@ -237,8 +245,6 @@ class MODULES_EXPORT MediaControlsImpl final : public HTMLDivElement,
// check that the element is a video element first.
HTMLVideoElement& VideoElement();
- explicit MediaControlsImpl(HTMLMediaElement&);
-
void InitializeControls();
void PopulatePanel();
@@ -408,6 +414,11 @@ class MODULES_EXPORT MediaControlsImpl final : public HTMLDivElement,
// Timer for distinguishing double-taps.
TaskRunnerTimer<MediaControlsImpl> tap_timer_;
+ bool is_paused_for_double_tap_ = false;
+
+ // Timer to delay showing the volume slider to avoid accidental triggering
+ // of the slider
+ TaskRunnerTimer<MediaControlsImpl> volume_slider_wanted_timer_;
bool is_test_mode_ = false;
};
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc
index f636b810f95..dadc1b88038 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc
@@ -18,8 +18,10 @@
#include "third_party/blink/renderer/core/css/document_style_environment_variables.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/dom_token_list.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/geometry/dom_rect.h"
@@ -44,6 +46,7 @@
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
// The MediaTimelineWidths histogram suffix expected to be encountered in these
// tests. Depends on the OS, since Android sizes its timeline differently.
@@ -72,10 +75,12 @@ class MockWebMediaPlayerForImpl : public EmptyWebMediaPlayer {
// WebMediaPlayer overrides:
WebTimeRanges Seekable() const override { return seekable_; }
bool HasVideo() const override { return true; }
+ bool HasAudio() const override { return has_audio_; }
SurfaceLayerMode GetVideoSurfaceLayerMode() const override {
return SurfaceLayerMode::kAlways;
}
+ bool has_audio_ = false;
WebTimeRanges seekable_;
};
@@ -161,7 +166,7 @@ bool IsElementVisible(Element& element) {
}
void SimulateTransitionEnd(Element& element) {
- element.DispatchEvent(*Event::Create(EventTypeNames::transitionend));
+ element.DispatchEvent(*Event::Create(event_type_names::kTransitionend));
}
// This must match MediaControlDownloadButtonElement::DownloadActionMetrics.
@@ -268,6 +273,8 @@ class MediaControlsImplTest : public PageTestBase,
SimulateLoadedMetadata();
}
+ void SetHasAudio(bool has_audio) { WebMediaPlayer()->has_audio_ = has_audio; }
+
void ClickOverflowButton() {
MediaControls()
.download_button_->OverflowElementForTests()
@@ -324,7 +331,7 @@ void MediaControlsImplTest::MouseMoveTo(WebFloatPoint pos) {
WebInputEvent::GetStaticTimeStampForTests());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, {});
+ mouse_move_event, {}, {});
}
void MediaControlsImplTest::MouseUpAt(WebFloatPoint pos) {
@@ -406,18 +413,18 @@ TEST_F(MediaControlsImplTest, CastButtonDisableRemotePlaybackAttr) {
ASSERT_TRUE(IsElementVisible(*cast_button));
MediaControls().MediaElement().SetBooleanAttribute(
- HTMLNames::disableremoteplaybackAttr, true);
+ html_names::kDisableremoteplaybackAttr, true);
test::RunPendingTasks();
ASSERT_FALSE(IsElementVisible(*cast_button));
MediaControls().MediaElement().SetBooleanAttribute(
- HTMLNames::disableremoteplaybackAttr, false);
+ html_names::kDisableremoteplaybackAttr, false);
test::RunPendingTasks();
ASSERT_TRUE(IsElementVisible(*cast_button));
}
TEST_F(MediaControlsImplTest, CastOverlayDefault) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
Element* cast_overlay_button = GetElementByShadowPseudoId(
@@ -429,7 +436,7 @@ TEST_F(MediaControlsImplTest, CastOverlayDefault) {
}
TEST_F(MediaControlsImplTest, CastOverlayDisabled) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
ScopedMediaCastOverlayButtonForTest media_cast_overlay_button(false);
@@ -443,7 +450,7 @@ TEST_F(MediaControlsImplTest, CastOverlayDisabled) {
}
TEST_F(MediaControlsImplTest, CastOverlayDisableRemotePlaybackAttr) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
Element* cast_overlay_button = GetElementByShadowPseudoId(
@@ -455,18 +462,18 @@ TEST_F(MediaControlsImplTest, CastOverlayDisableRemotePlaybackAttr) {
ASSERT_TRUE(IsElementVisible(*cast_overlay_button));
MediaControls().MediaElement().SetBooleanAttribute(
- HTMLNames::disableremoteplaybackAttr, true);
+ html_names::kDisableremoteplaybackAttr, true);
test::RunPendingTasks();
ASSERT_FALSE(IsElementVisible(*cast_overlay_button));
MediaControls().MediaElement().SetBooleanAttribute(
- HTMLNames::disableremoteplaybackAttr, false);
+ html_names::kDisableremoteplaybackAttr, false);
test::RunPendingTasks();
ASSERT_TRUE(IsElementVisible(*cast_overlay_button));
}
TEST_F(MediaControlsImplTest, CastOverlayMediaControlsDisabled) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
Element* cast_overlay_button = GetElementByShadowPseudoId(
@@ -485,7 +492,7 @@ TEST_F(MediaControlsImplTest, CastOverlayMediaControlsDisabled) {
}
TEST_F(MediaControlsImplTest, CastOverlayDisabledMediaControlsDisabled) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
ScopedMediaCastOverlayButtonForTest media_cast_overlay_button(false);
@@ -626,7 +633,7 @@ TEST_F(MediaControlsImplPictureInPictureTest, PictureInPictureButtonVisible) {
ASSERT_FALSE(IsElementVisible(*picture_in_picture_button));
MediaControls().MediaElement().SetBooleanAttribute(
- HTMLNames::disablepictureinpictureAttr, true);
+ html_names::kDisablepictureinpictureAttr, true);
MediaControls().MediaElement().SetSrc("https://example.com/foo.mp4");
test::RunPendingTasks();
SetReady();
@@ -635,7 +642,7 @@ TEST_F(MediaControlsImplPictureInPictureTest, PictureInPictureButtonVisible) {
ASSERT_FALSE(IsElementVisible(*picture_in_picture_button));
MediaControls().MediaElement().SetBooleanAttribute(
- HTMLNames::disablepictureinpictureAttr, false);
+ html_names::kDisablepictureinpictureAttr, false);
test::RunPendingTasks();
ASSERT_TRUE(IsElementVisible(*picture_in_picture_button));
}
@@ -761,7 +768,7 @@ TEST_F(MediaControlsImplTest, TimelineSeekToRoundedEnd) {
// rounded up slightly to |rounded_up_duration| when setting the timeline's
// |max| attribute (crbug.com/695065).
double exact_duration = 596.586667;
- double rounded_up_duration = 596.587;
+ double rounded_up_duration = 596.586667;
LoadMediaWithDuration(exact_duration);
// Simulate a click slightly past the end of the track of the timeline's
@@ -998,7 +1005,16 @@ TEST_F(MediaControlsImplTest, TimeIsCorrectlyFormatted) {
namespace {
-class MediaControlsImplTestWithMockScheduler : public MediaControlsImplTest {
+class ModernMediaControlsImplTest : public MediaControlsImplTest {
+ public:
+ void SetUp() override {
+ RuntimeEnabledFeatures::SetModernMediaControlsEnabled(true);
+ MediaControlsImplTest::SetUp();
+ }
+};
+
+class MediaControlsImplTestWithMockScheduler
+ : public ModernMediaControlsImplTest {
public:
MediaControlsImplTestWithMockScheduler() { EnablePlatform(); }
@@ -1007,7 +1023,7 @@ class MediaControlsImplTestWithMockScheduler : public MediaControlsImplTest {
// DocumentParserTiming has DCHECKS to make sure time > 0.0.
platform()->AdvanceClockSeconds(1);
- MediaControlsImplTest::SetUp();
+ ModernMediaControlsImplTest::SetUp();
}
bool IsCursorHidden() {
@@ -1264,8 +1280,83 @@ TEST_F(MediaControlsImplTest, OverflowMenuMetricsTimeToDismiss) {
GetHistogramTester().ExpectTotalCount(kTimeToActionHistogramName, 0);
}
+TEST_F(MediaControlsImplTestWithMockScheduler,
+ ShowVolumeSliderAfterHoverTimerFired) {
+ const double kTimeToShowVolumeSlider = 0.2;
+
+ EnsureSizing();
+ MediaControls().MediaElement().SetSrc("https://example.com/foo.mp4");
+ platform()->RunForPeriodSeconds(1);
+ SetHasAudio(true);
+ SimulateLoadedMetadata();
+
+ WebTestSupport::SetIsRunningWebTest(false);
+
+ Element* volume_slider = GetElementByShadowPseudoId(
+ MediaControls(), "-webkit-media-controls-volume-slider");
+ Element* mute_btn = GetElementByShadowPseudoId(
+ MediaControls(), "-webkit-media-controls-mute-button");
+
+ ASSERT_NE(nullptr, volume_slider);
+ ASSERT_NE(nullptr, mute_btn);
+
+ EXPECT_TRUE(IsElementVisible(*mute_btn));
+ EXPECT_TRUE(volume_slider->classList().contains("closed"));
+
+ DOMRect* mute_btn_rect = mute_btn->getBoundingClientRect();
+ WebFloatPoint mute_btn_center(
+ mute_btn_rect->left() + mute_btn_rect->width() / 2,
+ mute_btn_rect->top() + mute_btn_rect->height() / 2);
+ WebFloatPoint edge(0, 0);
+
+ // Hover on mute button and stay
+ MouseMoveTo(mute_btn_center);
+ platform()->RunForPeriodSeconds(kTimeToShowVolumeSlider - 0.001);
+ EXPECT_TRUE(volume_slider->classList().contains("closed"));
+
+ platform()->RunForPeriodSeconds(0.002);
+ EXPECT_FALSE(volume_slider->classList().contains("closed"));
+
+ MouseMoveTo(edge);
+ EXPECT_TRUE(volume_slider->classList().contains("closed"));
+
+ // Hover on mute button and move away before timer fired
+ MouseMoveTo(mute_btn_center);
+ platform()->RunForPeriodSeconds(kTimeToShowVolumeSlider - 0.001);
+ EXPECT_TRUE(volume_slider->classList().contains("closed"));
+
+ MouseMoveTo(edge);
+ EXPECT_TRUE(volume_slider->classList().contains("closed"));
+}
+
+TEST_F(MediaControlsImplTestWithMockScheduler,
+ VolumeSliderBehaviorWhenFocused) {
+ MediaControls().MediaElement().SetSrc("https://example.com/foo.mp4");
+ platform()->RunForPeriodSeconds(1);
+ SetHasAudio(true);
+
+ WebTestSupport::SetIsRunningWebTest(false);
+
+ Element* volume_slider = GetElementByShadowPseudoId(
+ MediaControls(), "-webkit-media-controls-volume-slider");
+
+ ASSERT_NE(nullptr, volume_slider);
+
+ // Volume slider starts out hidden
+ EXPECT_TRUE(volume_slider->classList().contains("closed"));
+
+ // Tab focus should open volume slider immediately.
+ volume_slider->SetFocused(true, WebFocusType::kWebFocusTypeNone);
+ volume_slider->DispatchEvent(*Event::Create("focus"));
+ EXPECT_FALSE(volume_slider->classList().contains("closed"));
+
+ // Unhover slider while focused should not close slider.
+ volume_slider->DispatchEvent(*Event::Create("mouseout"));
+ EXPECT_FALSE(volume_slider->classList().contains("closed"));
+}
+
TEST_F(MediaControlsImplTest, CastOverlayDefaultHidesOnTimer) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
Element* cast_overlay_button = GetElementByShadowPseudoId(
@@ -1285,7 +1376,7 @@ TEST_F(MediaControlsImplTest, CastOverlayDefaultHidesOnTimer) {
}
TEST_F(MediaControlsImplTest, CastOverlayShowsOnSomeEvents) {
- MediaControls().MediaElement().SetBooleanAttribute(HTMLNames::controlsAttr,
+ MediaControls().MediaElement().SetBooleanAttribute(html_names::kControlsAttr,
false);
Element* cast_overlay_button = GetElementByShadowPseudoId(
@@ -1324,17 +1415,10 @@ TEST_F(MediaControlsImplTest, isConnected) {
EXPECT_FALSE(MediaControls().isConnected());
}
-class ModernMediaControlsImplTest : public MediaControlsImplTest {
- public:
- void SetUp() override {
- RuntimeEnabledFeatures::SetModernMediaControlsEnabled(true);
- MediaControlsImplTest::SetUp();
- }
-};
-
TEST_F(ModernMediaControlsImplTest, ControlsShouldUseSafeAreaInsets) {
+ UpdateAllLifecyclePhasesForTest();
{
- const ComputedStyle* style = MediaControls().EnsureComputedStyle();
+ const ComputedStyle* style = MediaControls().GetComputedStyle();
EXPECT_EQ(0.0, style->MarginTop().Pixels());
EXPECT_EQ(0.0, style->MarginLeft().Pixels());
EXPECT_EQ(0.0, style->MarginBottom().Pixels());
@@ -1351,10 +1435,10 @@ TEST_F(ModernMediaControlsImplTest, ControlsShouldUseSafeAreaInsets) {
"safe-area-inset-right", "4px");
EXPECT_TRUE(GetDocument().NeedsLayoutTreeUpdate());
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
{
- const ComputedStyle* style = MediaControls().EnsureComputedStyle();
+ const ComputedStyle* style = MediaControls().GetComputedStyle();
EXPECT_EQ(1.0, style->MarginTop().Pixels());
EXPECT_EQ(2.0, style->MarginLeft().Pixels());
EXPECT_EQ(3.0, style->MarginBottom().Pixels());
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.cc
index ffe4904ed7e..088f046bf30 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.cc
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/modules/remoteplayback/availability_callback_wrapper.h"
#include "third_party/blink/renderer/modules/remoteplayback/html_media_element_remote_playback.h"
#include "third_party/blink/renderer/modules/remoteplayback/remote_playback.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -26,30 +27,33 @@ MediaControlsMediaEventListener::MediaControlsMediaEventListener(
void MediaControlsMediaEventListener::Attach() {
DCHECK(GetMediaElement().isConnected());
- GetMediaElement().addEventListener(EventTypeNames::volumechange, this, false);
- GetMediaElement().addEventListener(EventTypeNames::focusin, this, false);
- GetMediaElement().addEventListener(EventTypeNames::timeupdate, this, false);
- GetMediaElement().addEventListener(EventTypeNames::play, this, false);
- GetMediaElement().addEventListener(EventTypeNames::playing, this, false);
- GetMediaElement().addEventListener(EventTypeNames::pause, this, false);
- GetMediaElement().addEventListener(EventTypeNames::durationchange, this,
+ GetMediaElement().addEventListener(event_type_names::kVolumechange, this,
false);
- GetMediaElement().addEventListener(EventTypeNames::error, this, false);
- GetMediaElement().addEventListener(EventTypeNames::loadedmetadata, this,
+ GetMediaElement().addEventListener(event_type_names::kFocusin, this, false);
+ GetMediaElement().addEventListener(event_type_names::kTimeupdate, this,
+ false);
+ GetMediaElement().addEventListener(event_type_names::kPlay, this, false);
+ GetMediaElement().addEventListener(event_type_names::kPlaying, this, false);
+ GetMediaElement().addEventListener(event_type_names::kPause, this, false);
+ GetMediaElement().addEventListener(event_type_names::kDurationchange, this,
+ false);
+ GetMediaElement().addEventListener(event_type_names::kError, this, false);
+ GetMediaElement().addEventListener(event_type_names::kLoadedmetadata, this,
+ false);
+ GetMediaElement().addEventListener(event_type_names::kKeypress, this, false);
+ GetMediaElement().addEventListener(event_type_names::kKeydown, this, false);
+ GetMediaElement().addEventListener(event_type_names::kKeyup, this, false);
+ GetMediaElement().addEventListener(event_type_names::kWaiting, this, false);
+ GetMediaElement().addEventListener(event_type_names::kProgress, this, false);
+ GetMediaElement().addEventListener(event_type_names::kLoadeddata, this,
false);
- GetMediaElement().addEventListener(EventTypeNames::keypress, this, false);
- GetMediaElement().addEventListener(EventTypeNames::keydown, this, false);
- GetMediaElement().addEventListener(EventTypeNames::keyup, this, false);
- GetMediaElement().addEventListener(EventTypeNames::waiting, this, false);
- GetMediaElement().addEventListener(EventTypeNames::progress, this, false);
- GetMediaElement().addEventListener(EventTypeNames::loadeddata, this, false);
// Listen to two different fullscreen events in order to make sure the new and
// old APIs are handled.
- GetMediaElement().addEventListener(EventTypeNames::webkitfullscreenchange,
+ GetMediaElement().addEventListener(event_type_names::kWebkitfullscreenchange,
this, false);
media_controls_->GetDocument().addEventListener(
- EventTypeNames::fullscreenchange, this, false);
+ event_type_names::kFullscreenchange, this, false);
// Picture-in-Picture events.
if (RuntimeEnabledFeatures::PictureInPictureEnabled() &&
@@ -58,29 +62,29 @@ void MediaControlsMediaEventListener::Attach() {
.GetSettings()
->GetPictureInPictureEnabled() &&
GetMediaElement().IsHTMLVideoElement()) {
- GetMediaElement().addEventListener(EventTypeNames::enterpictureinpicture,
+ GetMediaElement().addEventListener(event_type_names::kEnterpictureinpicture,
this, false);
- GetMediaElement().addEventListener(EventTypeNames::leavepictureinpicture,
+ GetMediaElement().addEventListener(event_type_names::kLeavepictureinpicture,
this, false);
}
// TextTracks events.
TextTrackList* text_tracks = GetMediaElement().textTracks();
- text_tracks->addEventListener(EventTypeNames::addtrack, this, false);
- text_tracks->addEventListener(EventTypeNames::change, this, false);
- text_tracks->addEventListener(EventTypeNames::removetrack, this, false);
+ text_tracks->addEventListener(event_type_names::kAddtrack, this, false);
+ text_tracks->addEventListener(event_type_names::kChange, this, false);
+ text_tracks->addEventListener(event_type_names::kRemovetrack, this, false);
// Keypress events.
if (media_controls_->PanelElement()) {
- media_controls_->PanelElement()->addEventListener(EventTypeNames::keypress,
- this, false);
+ media_controls_->PanelElement()->addEventListener(
+ event_type_names::kKeypress, this, false);
}
RemotePlayback* remote = GetRemotePlayback();
if (remote) {
- remote->addEventListener(EventTypeNames::connect, this);
- remote->addEventListener(EventTypeNames::connecting, this);
- remote->addEventListener(EventTypeNames::disconnect, this);
+ remote->addEventListener(event_type_names::kConnect, this);
+ remote->addEventListener(event_type_names::kConnecting, this);
+ remote->addEventListener(event_type_names::kDisconnect, this);
// TODO(avayvod, mlamouri): Attach can be called twice. See
// https://crbug.com/713275.
@@ -98,23 +102,23 @@ void MediaControlsMediaEventListener::Detach() {
DCHECK(!GetMediaElement().isConnected());
media_controls_->GetDocument().removeEventListener(
- EventTypeNames::fullscreenchange, this, false);
+ event_type_names::kFullscreenchange, this, false);
TextTrackList* text_tracks = GetMediaElement().textTracks();
- text_tracks->removeEventListener(EventTypeNames::addtrack, this, false);
- text_tracks->removeEventListener(EventTypeNames::change, this, false);
- text_tracks->removeEventListener(EventTypeNames::removetrack, this, false);
+ text_tracks->removeEventListener(event_type_names::kAddtrack, this, false);
+ text_tracks->removeEventListener(event_type_names::kChange, this, false);
+ text_tracks->removeEventListener(event_type_names::kRemovetrack, this, false);
if (media_controls_->PanelElement()) {
media_controls_->PanelElement()->removeEventListener(
- EventTypeNames::keypress, this, false);
+ event_type_names::kKeypress, this, false);
}
RemotePlayback* remote = GetRemotePlayback();
if (remote) {
- remote->removeEventListener(EventTypeNames::connect, this);
- remote->removeEventListener(EventTypeNames::connecting, this);
- remote->removeEventListener(EventTypeNames::disconnect, this);
+ remote->removeEventListener(event_type_names::kConnect, this);
+ remote->removeEventListener(event_type_names::kConnecting, this);
+ remote->removeEventListener(event_type_names::kDisconnect, this);
// TODO(avayvod): apparently Detach() can be called without a previous
// Attach() call. See https://crbug.com/713275 for more details.
@@ -141,61 +145,61 @@ RemotePlayback* MediaControlsMediaEventListener::GetRemotePlayback() {
return HTMLMediaElementRemotePlayback::remote(GetMediaElement());
}
-void MediaControlsMediaEventListener::handleEvent(
+void MediaControlsMediaEventListener::Invoke(
ExecutionContext* execution_context,
Event* event) {
- if (event->type() == EventTypeNames::volumechange) {
+ if (event->type() == event_type_names::kVolumechange) {
media_controls_->OnVolumeChange();
return;
}
- if (event->type() == EventTypeNames::focusin) {
+ if (event->type() == event_type_names::kFocusin) {
media_controls_->OnFocusIn();
return;
}
- if (event->type() == EventTypeNames::timeupdate) {
+ if (event->type() == event_type_names::kTimeupdate) {
media_controls_->OnTimeUpdate();
return;
}
- if (event->type() == EventTypeNames::durationchange) {
+ if (event->type() == event_type_names::kDurationchange) {
media_controls_->OnDurationChange();
return;
}
- if (event->type() == EventTypeNames::play) {
+ if (event->type() == event_type_names::kPlay) {
media_controls_->OnPlay();
return;
}
- if (event->type() == EventTypeNames::playing) {
+ if (event->type() == event_type_names::kPlaying) {
media_controls_->OnPlaying();
return;
}
- if (event->type() == EventTypeNames::pause) {
+ if (event->type() == event_type_names::kPause) {
media_controls_->OnPause();
return;
}
- if (event->type() == EventTypeNames::error) {
+ if (event->type() == event_type_names::kError) {
media_controls_->OnError();
return;
}
- if (event->type() == EventTypeNames::loadedmetadata) {
+ if (event->type() == event_type_names::kLoadedmetadata) {
media_controls_->OnLoadedMetadata();
return;
}
- if (event->type() == EventTypeNames::waiting) {
+ if (event->type() == event_type_names::kWaiting) {
media_controls_->OnWaiting();
return;
}
- if (event->type() == EventTypeNames::progress) {
+ if (event->type() == event_type_names::kProgress) {
media_controls_->OnLoadingProgress();
return;
}
- if (event->type() == EventTypeNames::loadeddata) {
+ if (event->type() == event_type_names::kLoadeddata) {
media_controls_->OnLoadedData();
return;
}
// Fullscreen handling.
- if (event->type() == EventTypeNames::fullscreenchange ||
- event->type() == EventTypeNames::webkitfullscreenchange) {
+ if (event->type() == event_type_names::kFullscreenchange ||
+ event->type() == event_type_names::kWebkitfullscreenchange) {
if (GetMediaElement().IsFullscreen())
media_controls_->OnEnteredFullscreen();
else
@@ -204,42 +208,42 @@ void MediaControlsMediaEventListener::handleEvent(
}
// Picture-in-Picture events.
- if (event->type() == EventTypeNames::enterpictureinpicture ||
- event->type() == EventTypeNames::leavepictureinpicture) {
+ if (event->type() == event_type_names::kEnterpictureinpicture ||
+ event->type() == event_type_names::kLeavepictureinpicture) {
media_controls_->OnPictureInPictureChanged();
return;
}
// TextTracks events.
- if (event->type() == EventTypeNames::addtrack ||
- event->type() == EventTypeNames::removetrack) {
+ if (event->type() == event_type_names::kAddtrack ||
+ event->type() == event_type_names::kRemovetrack) {
media_controls_->OnTextTracksAddedOrRemoved();
return;
}
- if (event->type() == EventTypeNames::change) {
+ if (event->type() == event_type_names::kChange) {
media_controls_->OnTextTracksChanged();
return;
}
// Keypress events.
- if (event->type() == EventTypeNames::keypress) {
+ if (event->type() == event_type_names::kKeypress) {
if (event->currentTarget() == media_controls_->PanelElement()) {
media_controls_->OnPanelKeypress();
return;
}
}
- if (event->type() == EventTypeNames::keypress ||
- event->type() == EventTypeNames::keydown ||
- event->type() == EventTypeNames::keyup) {
+ if (event->type() == event_type_names::kKeypress ||
+ event->type() == event_type_names::kKeydown ||
+ event->type() == event_type_names::kKeyup) {
media_controls_->OnMediaKeyboardEvent(event);
return;
}
// RemotePlayback state change events.
- if (event->type() == EventTypeNames::connect ||
- event->type() == EventTypeNames::connecting ||
- event->type() == EventTypeNames::disconnect) {
+ if (event->type() == event_type_names::kConnect ||
+ event->type() == event_type_names::kConnecting ||
+ event->type() == event_type_names::kDisconnect) {
media_controls_->RemotePlaybackStateChanged();
return;
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h
index 96672fc7373..78bc61a1e16 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h
@@ -35,7 +35,7 @@ class MediaControlsMediaEventListener final : public EventListener {
HTMLMediaElement& GetMediaElement();
RemotePlayback* GetRemotePlayback();
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
void OnRemotePlaybackAvailabilityChanged();
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.cc
index 0f49a4bc3a0..e679fc0249d 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.cc
@@ -104,20 +104,22 @@ MediaControlsOrientationLockDelegate::MediaControlsOrientationLockDelegate(
void MediaControlsOrientationLockDelegate::Attach() {
DCHECK(VideoElement().isConnected());
- GetDocument().addEventListener(EventTypeNames::fullscreenchange, this, true);
- VideoElement().addEventListener(EventTypeNames::webkitfullscreenchange, this,
+ GetDocument().addEventListener(event_type_names::kFullscreenchange, this,
+ true);
+ VideoElement().addEventListener(event_type_names::kWebkitfullscreenchange,
+ this, true);
+ VideoElement().addEventListener(event_type_names::kLoadedmetadata, this,
true);
- VideoElement().addEventListener(EventTypeNames::loadedmetadata, this, true);
}
void MediaControlsOrientationLockDelegate::Detach() {
DCHECK(!VideoElement().isConnected());
- GetDocument().removeEventListener(EventTypeNames::fullscreenchange, this,
+ GetDocument().removeEventListener(event_type_names::kFullscreenchange, this,
true);
- VideoElement().removeEventListener(EventTypeNames::webkitfullscreenchange,
+ VideoElement().removeEventListener(event_type_names::kWebkitfullscreenchange,
this, true);
- VideoElement().removeEventListener(EventTypeNames::loadedmetadata, this,
+ VideoElement().removeEventListener(event_type_names::kLoadedmetadata, this,
true);
}
@@ -171,9 +173,13 @@ void MediaControlsOrientationLockDelegate::ChangeLockToAnyOrientation() {
DCHECK_NE(locked_orientation_, kWebScreenOrientationLockDefault);
locked_orientation_ = kWebScreenOrientationLockAny;
- ScreenOrientationController::From(*GetDocument().GetFrame())
- ->lock(locked_orientation_,
- std::make_unique<DummyScreenOrientationCallback>());
+
+ // The document could have been detached from the frame.
+ if (LocalFrame* frame = GetDocument().GetFrame()) {
+ ScreenOrientationController::From(*frame)->lock(
+ locked_orientation_,
+ std::make_unique<DummyScreenOrientationCallback>());
+ }
}
void MediaControlsOrientationLockDelegate::MaybeUnlockOrientation() {
@@ -186,7 +192,7 @@ void MediaControlsOrientationLockDelegate::MaybeUnlockOrientation() {
monitor_.reset(); // Cancel any GotIsAutoRotateEnabledByUser Mojo callback.
if (LocalDOMWindow* dom_window = GetDocument().domWindow()) {
- dom_window->removeEventListener(EventTypeNames::deviceorientation, this,
+ dom_window->removeEventListener(event_type_names::kDeviceorientation, this,
false);
}
@@ -250,7 +256,7 @@ void MediaControlsOrientationLockDelegate::GotIsAutoRotateEnabledByUser(
}
if (LocalDOMWindow* dom_window = GetDocument().domWindow()) {
- dom_window->addEventListener(EventTypeNames::deviceorientation, this,
+ dom_window->addEventListener(event_type_names::kDeviceorientation, this,
false);
}
}
@@ -263,11 +269,11 @@ Document& MediaControlsOrientationLockDelegate::GetDocument() const {
return VideoElement().GetDocument();
}
-void MediaControlsOrientationLockDelegate::handleEvent(
+void MediaControlsOrientationLockDelegate::Invoke(
ExecutionContext* execution_context,
Event* event) {
- if (event->type() == EventTypeNames::fullscreenchange ||
- event->type() == EventTypeNames::webkitfullscreenchange) {
+ if (event->type() == event_type_names::kFullscreenchange ||
+ event->type() == event_type_names::kWebkitfullscreenchange) {
if (VideoElement().IsFullscreen()) {
if (state_ == State::kPendingFullscreen)
MaybeLockOrientation();
@@ -279,16 +285,17 @@ void MediaControlsOrientationLockDelegate::handleEvent(
return;
}
- if (event->type() == EventTypeNames::loadedmetadata) {
+ if (event->type() == event_type_names::kLoadedmetadata) {
if (state_ == State::kPendingMetadata)
MaybeLockOrientation();
return;
}
- if (event->type() == EventTypeNames::deviceorientation) {
+ if (event->type() == event_type_names::kDeviceorientation) {
if (event->isTrusted() &&
- event->InterfaceName() == EventNames::DeviceOrientationEvent) {
+ event->InterfaceName() ==
+ event_interface_names::kDeviceOrientationEvent) {
MaybeLockToAnyIfDeviceOrientationMatchesVideo(
ToDeviceOrientationEvent(event));
}
@@ -438,7 +445,7 @@ void MediaControlsOrientationLockDelegate::
// Job done: the user rotated their device to match the orientation of the
// video that we locked to, so now we can stop listening.
if (LocalDOMWindow* dom_window = GetDocument().domWindow()) {
- dom_window->removeEventListener(EventTypeNames::deviceorientation, this,
+ dom_window->removeEventListener(event_type_names::kDeviceorientation, this,
false);
}
// Delay before changing lock, as a workaround for the case where the device
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h
index ab7d3d2128e..37e14f2ee31 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h
@@ -10,7 +10,7 @@
#include "third_party/blink/public/common/screen_orientation/web_screen_orientation_lock_type.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
#include "third_party/blink/renderer/modules/modules_export.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -90,7 +90,7 @@ class MediaControlsOrientationLockDelegate final : public EventListener {
};
// EventListener implementation.
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
HTMLVideoElement& VideoElement() const;
Document& GetDocument() const;
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate_test.cc
index 4b2a3176e41..12def003f73 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate_test.cc
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/core/frame/frame_view.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/screen_orientation_controller.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/media/html_audio_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
@@ -29,10 +30,10 @@
#include "third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.h"
#include "third_party/blink/renderer/modules/screen_orientation/web_lock_orientation_callback.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/testing/empty_web_media_player.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
using testing::_;
using testing::AtLeast;
@@ -114,13 +115,13 @@ class MockChromeClientForOrientationLockDelegate final
}
// The real ChromeClient::EnterFullscreen/ExitFullscreen implementation is
// async due to IPC, emulate that by posting tasks:
- void EnterFullscreen(LocalFrame& frame, const FullscreenOptions&) override {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ void EnterFullscreen(LocalFrame& frame, const FullscreenOptions*) override {
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(DidEnterFullscreen, WrapPersistent(frame.GetDocument())));
}
void ExitFullscreen(LocalFrame& frame) override {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(DidExitFullscreen, WrapPersistent(frame.GetDocument())));
}
@@ -297,15 +298,15 @@ class MediaControlsOrientationLockAndRotateToFullscreenDelegateTest
void SetUp() override {
// Unset this to fix ScreenOrientationControllerImpl::ComputeOrientation.
// TODO(mlamouri): Refactor to avoid this (crbug.com/726817).
- was_running_layout_test_ = LayoutTestSupport::IsRunningLayoutTest();
- LayoutTestSupport::SetIsRunningLayoutTest(false);
+ was_running_layout_test_ = WebTestSupport::IsRunningWebTest();
+ WebTestSupport::SetIsRunningWebTest(false);
MediaControlsOrientationLockDelegateTest::SetUp();
// Reset the <video> element now we've enabled the runtime feature.
video_->parentElement()->RemoveChild(video_);
video_ = HTMLVideoElement::Create(GetDocument());
- video_->setAttribute(HTMLNames::controlsAttr, g_empty_atom);
+ video_->setAttribute(html_names::kControlsAttr, g_empty_atom);
// Most tests should call GetDocument().body()->AppendChild(&Video());
// This is not done automatically, so that tests control timing of `Attach`,
// which is important for MediaControlsRotateToFullscreenDelegate since
@@ -314,7 +315,7 @@ class MediaControlsOrientationLockAndRotateToFullscreenDelegateTest
void TearDown() override {
MediaControlsOrientationLockDelegateTest::TearDown();
- LayoutTestSupport::SetIsRunningLayoutTest(was_running_layout_test_);
+ WebTestSupport::SetIsRunningWebTest(was_running_layout_test_);
}
void SetIsAutoRotateEnabledByUser(bool enabled) {
@@ -413,7 +414,7 @@ class MediaControlsOrientationLockAndRotateToFullscreenDelegateTest
void UpdateVisibilityObserver() {
// Let IntersectionObserver update.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
test::RunPendingTasks();
}
@@ -1443,4 +1444,45 @@ TEST_F(MediaControlsOrientationLockAndRotateToFullscreenDelegateTest,
EXPECT_TRUE(DelegateWillUnlockFullscreen());
}
+TEST_F(MediaControlsOrientationLockAndRotateToFullscreenDelegateTest,
+ DetachBeforeChangeLockToAnyOrientation) {
+ // Naturally portrait device, initially portrait, with landscape video.
+ natural_orientation_is_portrait_ = true;
+ ASSERT_NO_FATAL_FAILURE(
+ RotateScreenTo(kWebScreenOrientationPortraitPrimary, 0));
+ InitVideo(640, 480);
+ SetIsAutoRotateEnabledByUser(true);
+
+ // Initially inline, unlocked orientation.
+ ASSERT_FALSE(Video().IsFullscreen());
+ CheckStatePendingFullscreen();
+ ASSERT_FALSE(DelegateWillUnlockFullscreen());
+
+ // Simulate user clicking on media controls fullscreen button.
+ SimulateEnterFullscreen();
+ EXPECT_TRUE(Video().IsFullscreen());
+
+ // MediaControlsOrientationLockDelegate should lock to landscape.
+ CheckStateMaybeLockedFullscreen();
+ EXPECT_EQ(kWebScreenOrientationLockLandscape, DelegateOrientationLock());
+
+ // This will trigger a screen orientation change to landscape.
+ ASSERT_NO_FATAL_FAILURE(
+ RotateScreenTo(kWebScreenOrientationLandscapePrimary, 90));
+
+ // Rotate the device to match.
+ RotateDeviceTo(90 /* landscape primary */);
+
+ // And immediately detach the document by synchronously navigating.
+ // One easy way to do this is to replace the document with a JavaScript URL.
+ GetFrame().GetSettings()->SetScriptEnabled(true);
+ GetFrame().Navigate(
+ FrameLoadRequest(&GetDocument(),
+ ResourceRequest("javascript:'Hello, world!'")),
+ WebFrameLoadType::kStandard);
+
+ // We should not crash after the unlock delay.
+ test::RunDelayedTasks(GetUnlockDelay());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.cc
index 3b05144a1e5..7248e6fc844 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.cc
@@ -5,9 +5,9 @@
#include "third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.h"
#include "build/build_config.h"
-#include "third_party/blink/public/resources/grit/media_controls_resources.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
-#include "third_party/blink/renderer/platform/media/resource_bundle_helper.h"
+#include "third_party/blink/renderer/modules/media_controls/resources/grit/media_controls_resources.h"
+#include "third_party/blink/renderer/platform/data_resource_helper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -31,7 +31,7 @@ MediaControlsResourceLoader::MediaControlsResourceLoader()
MediaControlsResourceLoader::~MediaControlsResourceLoader() = default;
String MediaControlsResourceLoader::GetMediaControlsCSS() const {
- return ResourceBundleHelper::UncompressResourceAsString(
+ return UncompressResourceAsString(
RuntimeEnabledFeatures::ModernMediaControlsEnabled()
? IDR_UASTYLE_MODERN_MEDIA_CONTROLS_CSS
: IDR_UASTYLE_LEGACY_MEDIA_CONTROLS_CSS);
@@ -40,56 +40,52 @@ String MediaControlsResourceLoader::GetMediaControlsCSS() const {
String MediaControlsResourceLoader::GetMediaControlsAndroidCSS() const {
if (RuntimeEnabledFeatures::ModernMediaControlsEnabled())
return String();
- return ResourceBundleHelper::UncompressResourceAsString(
+ return UncompressResourceAsString(
IDR_UASTYLE_LEGACY_MEDIA_CONTROLS_ANDROID_CSS);
};
// static
String MediaControlsResourceLoader::GetShadowTimelineStyleSheet() {
- return ResourceBundleHelper::UncompressResourceAsString(
+ return UncompressResourceAsString(
IDR_SHADOWSTYLE_MODERN_MEDIA_CONTROLS_TIMELINE_CSS);
};
// static
String MediaControlsResourceLoader::GetShadowLoadingStyleSheet() {
- return ResourceBundleHelper::UncompressResourceAsString(
+ return UncompressResourceAsString(
IDR_SHADOWSTYLE_MODERN_MEDIA_CONTROLS_LOADING_CSS);
};
// static
String MediaControlsResourceLoader::GetJumpSVGImage() {
- return ResourceBundleHelper::UncompressResourceAsString(
- IDR_MODERN_MEDIA_CONTROLS_JUMP_SVG);
+ return UncompressResourceAsString(IDR_MODERN_MEDIA_CONTROLS_JUMP_SVG);
};
// static
String MediaControlsResourceLoader::GetArrowRightSVGImage() {
- return ResourceBundleHelper::UncompressResourceAsString(
- IDR_MODERN_MEDIA_CONTROLS_ARROW_RIGHT_SVG);
+ return UncompressResourceAsString(IDR_MODERN_MEDIA_CONTROLS_ARROW_RIGHT_SVG);
};
// static
String MediaControlsResourceLoader::GetArrowLeftSVGImage() {
- return ResourceBundleHelper::UncompressResourceAsString(
- IDR_MODERN_MEDIA_CONTROLS_ARROW_LEFT_SVG);
+ return UncompressResourceAsString(IDR_MODERN_MEDIA_CONTROLS_ARROW_LEFT_SVG);
};
// static
String MediaControlsResourceLoader::GetScrubbingMessageStyleSheet() {
- return ResourceBundleHelper::UncompressResourceAsString(
+ return UncompressResourceAsString(
IDR_SHADOWSTYLE_MODERN_MEDIA_CONTROLS_SCRUBBING_MESSAGE_CSS);
};
// static
String MediaControlsResourceLoader::GetAnimatedArrowStyleSheet() {
- return ResourceBundleHelper::UncompressResourceAsString(
+ return UncompressResourceAsString(
IDR_SHADOWSTYLE_MODERN_MEDIA_CONTROLS_ANIMATED_ARROW_CSS);
};
// static
String MediaControlsResourceLoader::GetMediaInterstitialsStyleSheet() {
- return ResourceBundleHelper::UncompressResourceAsString(
- IDR_UASTYLE_MEDIA_INTERSTITIALS_CSS);
+ return UncompressResourceAsString(IDR_UASTYLE_MEDIA_INTERSTITIALS_CSS);
};
String MediaControlsResourceLoader::GetUAStyleSheet() {
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.cc
index ad5161cf1b7..47e05800320 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.cc
@@ -18,6 +18,7 @@
#include "third_party/blink/renderer/modules/device_orientation/device_orientation_data.h"
#include "third_party/blink/renderer/modules/device_orientation/device_orientation_event.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -42,20 +43,21 @@ void MediaControlsRotateToFullscreenDelegate::Attach() {
if (!dom_window)
return;
- video_element_->addEventListener(EventTypeNames::play, this, true);
- video_element_->addEventListener(EventTypeNames::pause, this, true);
+ video_element_->addEventListener(event_type_names::kPlay, this, true);
+ video_element_->addEventListener(event_type_names::kPause, this, true);
// Listen to two different fullscreen events in order to make sure the new and
// old APIs are handled.
- video_element_->addEventListener(EventTypeNames::webkitfullscreenchange, this,
- true);
+ video_element_->addEventListener(event_type_names::kWebkitfullscreenchange,
+ this, true);
video_element_->GetDocument().addEventListener(
- EventTypeNames::fullscreenchange, this, true);
+ event_type_names::kFullscreenchange, this, true);
current_screen_orientation_ = ComputeScreenOrientation();
// TODO(johnme): Check this is battery efficient (note that this doesn't need
// to receive events for 180 deg rotations).
- dom_window->addEventListener(EventTypeNames::orientationchange, this, false);
+ dom_window->addEventListener(event_type_names::kOrientationchange, this,
+ false);
// TODO(795286): device orientation now requires a v8::Context in the stack so
// we are creating one so the event pump starts running.
@@ -64,7 +66,8 @@ void MediaControlsRotateToFullscreenDelegate::Attach() {
return;
ScriptState::Scope scope(ToScriptStateForMainWorld(frame));
- dom_window->addEventListener(EventTypeNames::deviceorientation, this, false);
+ dom_window->addEventListener(event_type_names::kDeviceorientation, this,
+ false);
}
void MediaControlsRotateToFullscreenDelegate::Detach() {
@@ -77,20 +80,20 @@ void MediaControlsRotateToFullscreenDelegate::Detach() {
is_visible_ = false;
}
- video_element_->removeEventListener(EventTypeNames::play, this, true);
- video_element_->removeEventListener(EventTypeNames::pause, this, true);
+ video_element_->removeEventListener(event_type_names::kPlay, this, true);
+ video_element_->removeEventListener(event_type_names::kPause, this, true);
- video_element_->removeEventListener(EventTypeNames::webkitfullscreenchange,
+ video_element_->removeEventListener(event_type_names::kWebkitfullscreenchange,
this, true);
video_element_->GetDocument().removeEventListener(
- EventTypeNames::fullscreenchange, this, true);
+ event_type_names::kFullscreenchange, this, true);
LocalDOMWindow* dom_window = video_element_->GetDocument().domWindow();
if (!dom_window)
return;
- dom_window->removeEventListener(EventTypeNames::orientationchange, this,
+ dom_window->removeEventListener(event_type_names::kOrientationchange, this,
false);
- dom_window->removeEventListener(EventTypeNames::deviceorientation, this,
+ dom_window->removeEventListener(event_type_names::kDeviceorientation, this,
false);
}
@@ -99,24 +102,25 @@ bool MediaControlsRotateToFullscreenDelegate::operator==(
return this == &other;
}
-void MediaControlsRotateToFullscreenDelegate::handleEvent(
+void MediaControlsRotateToFullscreenDelegate::Invoke(
ExecutionContext* execution_context,
Event* event) {
- if (event->type() == EventTypeNames::play ||
- event->type() == EventTypeNames::pause ||
- event->type() == EventTypeNames::fullscreenchange ||
- event->type() == EventTypeNames::webkitfullscreenchange) {
+ if (event->type() == event_type_names::kPlay ||
+ event->type() == event_type_names::kPause ||
+ event->type() == event_type_names::kFullscreenchange ||
+ event->type() == event_type_names::kWebkitfullscreenchange) {
OnStateChange();
return;
}
- if (event->type() == EventTypeNames::deviceorientation) {
+ if (event->type() == event_type_names::kDeviceorientation) {
if (event->isTrusted() &&
- event->InterfaceName() == EventNames::DeviceOrientationEvent) {
+ event->InterfaceName() ==
+ event_interface_names::kDeviceOrientationEvent) {
OnDeviceOrientationAvailable(ToDeviceOrientationEvent(event));
}
return;
}
- if (event->type() == EventTypeNames::orientationchange) {
+ if (event->type() == event_type_names::kOrientationchange) {
OnScreenOrientationChange();
return;
}
@@ -133,7 +137,7 @@ void MediaControlsRotateToFullscreenDelegate::OnStateChange() {
<< needs_visibility_observer;
if (needs_visibility_observer && !visibility_observer_) {
- visibility_observer_ = new ElementVisibilityObserver(
+ visibility_observer_ = MakeGarbageCollected<ElementVisibilityObserver>(
video_element_,
WTF::BindRepeating(
&MediaControlsRotateToFullscreenDelegate::OnVisibilityChange,
@@ -158,7 +162,7 @@ void MediaControlsRotateToFullscreenDelegate::OnDeviceOrientationAvailable(
if (!dom_window)
return;
// Stop listening after the first event. Just need to know if it's available.
- dom_window->removeEventListener(EventTypeNames::deviceorientation, this,
+ dom_window->removeEventListener(event_type_names::kDeviceorientation, this,
false);
// MediaControlsOrientationLockDelegate needs Device Orientation events with
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.h b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.h
index d0671dbb6cb..6f537c994a9 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.h
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.h
@@ -44,7 +44,7 @@ class MediaControlsRotateToFullscreenDelegate final : public EventListener {
enum class SimpleOrientation { kPortrait, kLandscape, kUnknown };
// EventListener implementation.
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
void OnStateChange();
void OnVisibilityChange(bool is_visible);
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate_test.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate_test.cc
index e36f5176532..77d754ff02c 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate_test.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate_test.cc
@@ -38,7 +38,7 @@ using testing::Return;
namespace blink {
-using namespace HTMLNames;
+using namespace html_names;
namespace {
@@ -62,7 +62,7 @@ class MockChromeClient : public EmptyChromeClient {
->SetScreenOrientationAssociatedPtrForTests(
std::move(screen_orientation));
}
- void EnterFullscreen(LocalFrame& frame, const FullscreenOptions&) override {
+ void EnterFullscreen(LocalFrame& frame, const FullscreenOptions*) override {
Fullscreen::DidEnterFullscreen(*frame.GetDocument());
}
void ExitFullscreen(LocalFrame& frame) override {
@@ -109,7 +109,7 @@ class MediaControlsRotateToFullscreenDelegateTest
SetupPageWithClients(&clients, StubLocalFrameClient::Create());
video_ = HTMLVideoElement::Create(GetDocument());
- GetVideo().setAttribute(controlsAttr, g_empty_atom);
+ GetVideo().setAttribute(kControlsAttr, g_empty_atom);
// Most tests should call GetDocument().body()->AppendChild(&GetVideo());
// This is not done automatically, so that tests control timing of `Attach`.
}
@@ -146,7 +146,7 @@ class MediaControlsRotateToFullscreenDelegateTest
// If scripts are not enabled, controls will always be shown.
GetFrame().GetSettings()->SetScriptEnabled(true);
- GetVideo().removeAttribute(controlsAttr);
+ GetVideo().removeAttribute(kControlsAttr);
}
void DispatchEvent(EventTarget& target, const AtomicString& type) {
@@ -161,7 +161,7 @@ class MediaControlsRotateToFullscreenDelegateTest
void UpdateVisibilityObserver() {
// Let IntersectionObserver update.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
test::RunPendingTasks();
}
@@ -234,7 +234,7 @@ void MediaControlsRotateToFullscreenDelegateTest::RotateTo(
EXPECT_CALL(GetChromeClient(), GetScreenInfo())
.Times(AtLeast(1))
.WillRepeatedly(Return(screen_info));
- DispatchEvent(GetWindow(), EventTypeNames::orientationchange);
+ DispatchEvent(GetWindow(), event_type_names::kOrientationchange);
test::RunPendingTasks();
}
@@ -315,7 +315,7 @@ TEST_F(MediaControlsRotateToFullscreenDelegateTest,
EXPECT_FALSE(ObservedVisibility());
// Should have observed visibility once compositor updates.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
test::RunPendingTasks();
EXPECT_TRUE(ObservedVisibility());
@@ -336,7 +336,7 @@ TEST_F(MediaControlsRotateToFullscreenDelegateTest,
EXPECT_FALSE(ObservedVisibility());
// Should have observed visibility once compositor updates.
- GetDocument().View()->UpdateAllLifecyclePhases();
+ UpdateAllLifecyclePhasesForTest();
test::RunPendingTasks();
EXPECT_TRUE(ObservedVisibility());
}
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/media_download_in_product_help_manager.cc b/chromium/third_party/blink/renderer/modules/media_controls/media_download_in_product_help_manager.cc
index 0a6dc38676e..4ee08861394 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/media_download_in_product_help_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/media_controls/media_download_in_product_help_manager.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/resources/legacyMediaControls.css b/chromium/third_party/blink/renderer/modules/media_controls/resources/legacyMediaControls.css
index 1a0ed184bad..48efe3300d0 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/resources/legacyMediaControls.css
+++ b/chromium/third_party/blink/renderer/modules/media_controls/resources/legacyMediaControls.css
@@ -85,7 +85,7 @@ audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
min-width: 48px;
line-height: 32px;
background-color: #fafafa;
- /* The duration is also specified in MediaControlElements.cpp and LayoutTests/media/media-controls.js */
+ /* The duration is also specified in media_control_elements.cc and web_tests/media/media-controls.js */
transition: opacity 0.3s;
font-size: 12px;
diff --git a/chromium/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css b/chromium/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css
index 9d6ecde1cef..f247426e660 100644
--- a/chromium/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css
+++ b/chromium/third_party/blink/renderer/modules/media_controls/resources/modernMediaControls.css
@@ -100,10 +100,6 @@ video::-webkit-media-controls.sizing-medium div[pseudo="-webkit-media-controls-p
background-size: auto 200px;
}
-video::-webkit-media-controls.sizing-large div[pseudo="-webkit-media-controls-panel" i] {
- background-size: auto 312px;
-}
-
/* Need dark gradient at the top of the video when the scrubbing message is
* shown */
video::-webkit-media-controls:not(.audio-only) div[pseudo="-webkit-media-controls-panel" i].scrubbing-message {
@@ -122,10 +118,6 @@ video::-webkit-media-controls.sizing-medium div[pseudo="-webkit-media-controls-p
background-size: auto 120px, auto 200px;
}
-video::-webkit-media-controls.sizing-large div[pseudo="-webkit-media-controls-panel" i].scrubbing-message {
- background-size: auto 120px, auto 312px;
-}
-
audio::-internal-media-controls-button-panel,
video::-internal-media-controls-button-panel {
-webkit-appearance: -internal-media-control;
@@ -229,18 +221,6 @@ video::-webkit-media-controls.sizing-medium input[pseudo="-internal-media-contro
background-size: 32px;
}
-/* TODO(https://crbug.com/857120): remove these rules and the sizing-large CSS class. */
-video::-webkit-media-controls.sizing-large input[pseudo="-webkit-media-controls-play-button" i],
-video::-webkit-media-controls.sizing-large input[pseudo="-webkit-media-controls-mute-button" i],
-video::-webkit-media-controls.sizing-large input[pseudo="-webkit-media-controls-fullscreen-button" i],
-video::-webkit-media-controls.sizing-large input[pseudo="-internal-media-controls-display-cutout-fullscreen-button" i],
-video::-webkit-media-controls.sizing-large input[pseudo="-internal-media-controls-overflow-button" i] {
- width: 64px;
- height: 64px;
- min-width: 64px;
- background-size: 32px;
-}
-
video::-webkit-media-controls.sizing-small div[pseudo="-internal-media-controls-button-panel" i] {
height: 48px;
line-height: 48px;
@@ -253,13 +233,6 @@ video::-webkit-media-controls.sizing-medium div[pseudo="-internal-media-controls
padding: 0 16px 0 32px;
}
-/* TODO(https://crbug.com/857120): remove these rules and the sizing-large CSS class. */
-video::-webkit-media-controls.sizing-large div[pseudo="-internal-media-controls-button-panel" i] {
- height: 64px;
- line-height: 64px;
- padding: 0 16px 0 32px;
-}
-
audio::-webkit-media-controls-play-button,
video::-webkit-media-controls-play-button {
background-image: -webkit-image-set(url(ic_play_arrow.svg) 1x);
@@ -383,7 +356,7 @@ video::-webkit-media-controls-overlay-play-button {
/**
* The overlay-play-button is disabled if the video element is loaded via
- * MHTML, and a ruleset for input[type=button]:disabled in themeWin.css has
+ * MHTML, and a ruleset for input[type=button]:disabled in win.css has
* higher priority than the above ruleset.
*/
video::-webkit-media-controls-overlay-play-button:disabled {
@@ -465,11 +438,6 @@ video::-webkit-media-controls.sizing-medium input[pseudo="-webkit-media-controls
padding: 0 32px 20px 32px;
}
-/* TODO(https://crbug.com/857120): remove these rules and the sizing-large CSS class. */
-video::-webkit-media-controls.sizing-large input[pseudo="-webkit-media-controls-timeline" i] {
- padding: 0 32px 20px 32px;
-}
-
input[pseudo="-webkit-media-controls-timeline" i],
input[pseudo="-webkit-media-controls-timeline" i]::-internal-track-segment-highlight-before,
input[pseudo="-webkit-media-controls-timeline" i]::-internal-track-segment-highlight-after,
@@ -618,8 +586,7 @@ video::-webkit-media-controls-volume-slider.closed {
transition: width 0.3s ease, opacity 0.28s step-end;
}
-video::-webkit-media-controls.sizing-medium input[pseudo="-webkit-media-controls-volume-slider" i],
-video::-webkit-media-controls.sizing-large input[pseudo="-webkit-media-controls-volume-slider" i] {
+video::-webkit-media-controls.sizing-medium input[pseudo="-webkit-media-controls-volume-slider" i] {
padding: 30px 0; /* (64px button panel height - 4px slider height) / 2 */
}
@@ -670,8 +637,29 @@ video::-internal-media-controls-overflow-menu-list {
background: #FFFFFF;
box-shadow: 0 1px 9px 0 rgba(0,0,0,0.40);
border-radius: 2px;
+ transition: transform .2s ease-out, opacity .2s linear;
+ transform-origin: bottom right;
+}
+
+audio::-internal-media-controls-overflow-menu-list.closed,
+video::-internal-media-controls-overflow-menu-list.closed {
+ transform: scale(0);
+ opacity: 0;
+}
+
+
+audio::-webkit-media-controls div[pseudo="-internal-media-controls-overflow-menu-list" i].closed > *,
+video::-webkit-media-controls div[pseudo="-internal-media-controls-overflow-menu-list" i].closed > * {
+ opacity: 0;
}
+audio::-webkit-media-controls div[pseudo="-internal-media-controls-overflow-menu-list" i] > *,
+video::-webkit-media-controls div[pseudo="-internal-media-controls-overflow-menu-list" i] > * {
+ transition: opacity .2s linear .2s;
+}
+
+
+
audio::-internal-media-controls-text-track-list-header,
video::-internal-media-controls-text-track-list-header,
audio::-internal-media-controls-text-track-list-item,
@@ -692,35 +680,13 @@ video::-internal-media-controls-overflow-menu-list-item {
padding-right: 16px;
}
-/* TODO(https://crbug.com/857120): All these are the same, so these are unnecessary. */
-video::-webkit-media-controls.sizing-small div[pseudo="-internal-media-controls-overflow-menu-list" i] {
- min-width: 180px;
- max-width: 180px;
- max-height: 250px;
-}
-
-video::-webkit-media-controls.sizing-medium div[pseudo="-internal-media-controls-overflow-menu-list" i] {
- min-width: 180px;
- max-width: 180px;
- max-height: 250px;
-}
-
-video::-webkit-media-controls.sizing-large div[pseudo="-internal-media-controls-overflow-menu-list" i] {
- min-width: 180px;
- max-width: 180px;
- max-height: 250px;
-}
-
-/* TODO(https://crbug.com/857120): All these are the same, so these are unnecessary. */
-video::-webkit-media-controls.sizing-small label[pseudo="-internal-media-controls-overflow-menu-list-item" i] input {
- margin-left: 0;
- margin-right: 16px;
- width: 24px;
- height: 24px;
- min-width: 24px;
- background-size: 24px;
+video::-internal-media-controls-text-track-list,
+video::-internal-media-controls-overflow-menu-list {
+ max-width: 260px;
+ width: 95%;
}
+video::-webkit-media-controls.sizing-small label[pseudo="-internal-media-controls-overflow-menu-list-item" i] input,
video::-webkit-media-controls.sizing-medium label[pseudo="-internal-media-controls-overflow-menu-list-item" i] input {
margin-left: 0;
margin-right: 16px;
@@ -730,15 +696,6 @@ video::-webkit-media-controls.sizing-medium label[pseudo="-internal-media-contro
background-size: 24px;
}
-video::-webkit-media-controls.sizing-large label[pseudo="-internal-media-controls-overflow-menu-list-item" i] input {
- margin-left: 0;
- margin-right: 16px;
- width: 24px;
- height: 24px;
- min-width: 24px;
- background-size: 24px;
-}
-
label[pseudo="-internal-media-controls-overflow-menu-list-item"] input {
margin-left: -9px;
margin-right: 6px;
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.cc b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.cc
index 15530701722..6f53c0f770d 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.cc
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.cc
@@ -18,8 +18,8 @@ CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::Create(
HTMLCanvasElement* element,
ExecutionContext* context,
std::unique_ptr<WebCanvasCaptureHandler> handler) {
- return new CanvasCaptureMediaStreamTrack(component, element, context,
- std::move(handler));
+ return MakeGarbageCollected<CanvasCaptureMediaStreamTrack>(
+ component, element, context, std::move(handler));
}
CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::Create(
@@ -28,8 +28,8 @@ CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::Create(
ExecutionContext* context,
std::unique_ptr<WebCanvasCaptureHandler> handler,
double frame_rate) {
- return new CanvasCaptureMediaStreamTrack(component, element, context,
- std::move(handler), frame_rate);
+ return MakeGarbageCollected<CanvasCaptureMediaStreamTrack>(
+ component, element, context, std::move(handler), frame_rate);
}
HTMLCanvasElement* CanvasCaptureMediaStreamTrack::canvas() const {
@@ -44,7 +44,8 @@ CanvasCaptureMediaStreamTrack* CanvasCaptureMediaStreamTrack::clone(
ScriptState* script_state) {
MediaStreamComponent* cloned_component = Component()->Clone();
CanvasCaptureMediaStreamTrack* cloned_track =
- new CanvasCaptureMediaStreamTrack(*this, cloned_component);
+ MakeGarbageCollected<CanvasCaptureMediaStreamTrack>(*this,
+ cloned_component);
MediaStreamCenter::Instance().DidCreateMediaStreamTrack(cloned_component);
return cloned_track;
}
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.h b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.h
index 5166347f08c..e2a248475be 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.h
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/canvas_capture_media_stream_track.h
@@ -32,14 +32,6 @@ class CanvasCaptureMediaStreamTrack final : public MediaStreamTrack {
std::unique_ptr<WebCanvasCaptureHandler>,
double frame_rate);
- HTMLCanvasElement* canvas() const;
- void requestFrame();
-
- CanvasCaptureMediaStreamTrack* clone(ScriptState*) override;
-
- void Trace(blink::Visitor*) override;
-
- private:
CanvasCaptureMediaStreamTrack(const CanvasCaptureMediaStreamTrack&,
MediaStreamComponent*);
CanvasCaptureMediaStreamTrack(MediaStreamComponent*,
@@ -52,6 +44,14 @@ class CanvasCaptureMediaStreamTrack final : public MediaStreamTrack {
std::unique_ptr<WebCanvasCaptureHandler>,
double frame_rate);
+ HTMLCanvasElement* canvas() const;
+ void requestFrame();
+
+ CanvasCaptureMediaStreamTrack* clone(ScriptState*) override;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
Member<HTMLCanvasElement> canvas_element_;
Member<CanvasDrawListener> draw_listener_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/html_media_element_capture.cc b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/html_media_element_capture.cc
index c396e06ea9b..d993c18da1c 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/html_media_element_capture.cc
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/html_media_element_capture.cc
@@ -15,7 +15,6 @@
#include "third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h"
#include "third_party/blink/renderer/modules/encryptedmedia/media_keys.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream.h"
-#include "third_party/blink/renderer/modules/mediastream/media_stream_registry.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_center.h"
namespace blink {
@@ -35,7 +34,7 @@ class MediaElementEventListener final : public EventListener {
private:
// EventListener implementation.
- void handleEvent(ExecutionContext*, Event*) override;
+ void Invoke(ExecutionContext*, Event*) override;
bool operator==(const EventListener& other) const override {
return this == &other;
}
@@ -53,12 +52,12 @@ MediaElementEventListener::MediaElementEventListener(HTMLMediaElement* element,
UpdateSources(element->GetExecutionContext());
}
-void MediaElementEventListener::handleEvent(ExecutionContext* context,
- Event* event) {
+void MediaElementEventListener::Invoke(ExecutionContext* context,
+ Event* event) {
DVLOG(2) << __func__ << " " << event->type();
DCHECK(media_stream_);
- if (event->type() == EventTypeNames::ended) {
+ if (event->type() == event_type_names::kEnded) {
const MediaStreamTrackVector tracks = media_stream_->getTracks();
for (const auto& track : tracks) {
track->stopTrack(context);
@@ -68,7 +67,7 @@ void MediaElementEventListener::handleEvent(ExecutionContext* context,
media_stream_->StreamEnded();
return;
}
- if (event->type() != EventTypeNames::loadedmetadata)
+ if (event->type() != event_type_names::kLoadedmetadata)
return;
// If |media_element_| is a MediaStream, clone the new tracks.
@@ -78,11 +77,7 @@ void MediaElementEventListener::handleEvent(ExecutionContext* context,
track->stopTrack(context);
media_stream_->RemoveTrackByComponentAndFireEvents(track->Component());
}
- MediaStreamDescriptor* const descriptor =
- media_element_->currentSrc().IsEmpty()
- ? media_element_->GetSrcObject()
- : MediaStreamRegistry::Registry().LookupMediaStreamDescriptor(
- media_element_->currentSrc().GetString());
+ MediaStreamDescriptor* const descriptor = media_element_->GetSrcObject();
DCHECK(descriptor);
for (unsigned i = 0; i < descriptor->NumberOfAudioComponents(); i++) {
media_stream_->AddTrackByComponentAndFireEvents(
@@ -130,8 +125,7 @@ void MediaElementEventListener::UpdateSources(ExecutionContext* context) {
sources_.insert(track->Component()->Source());
if (!media_element_->currentSrc().IsEmpty() &&
- !media_element_->IsMediaDataCORSSameOrigin(
- context->GetSecurityOrigin())) {
+ !media_element_->IsMediaDataCorsSameOrigin()) {
for (auto source : sources_)
MediaStreamCenter::Instance().DidStopMediaStreamSource(source);
}
@@ -161,8 +155,7 @@ MediaStream* HTMLMediaElementCapture::captureStream(
}
ExecutionContext* context = ExecutionContext::From(script_state);
- if (!element.currentSrc().IsEmpty() &&
- !element.IsMediaDataCORSSameOrigin(context->GetSecurityOrigin())) {
+ if (!element.currentSrc().IsEmpty() && !element.IsMediaDataCorsSameOrigin()) {
exception_state.ThrowSecurityError(
"Cannot capture from element with cross-origin data");
return nullptr;
@@ -177,16 +170,12 @@ MediaStream* HTMLMediaElementCapture::captureStream(
MediaElementEventListener* listener =
new MediaElementEventListener(&element, stream);
- element.addEventListener(EventTypeNames::loadedmetadata, listener, false);
- element.addEventListener(EventTypeNames::ended, listener, false);
+ element.addEventListener(event_type_names::kLoadedmetadata, listener, false);
+ element.addEventListener(event_type_names::kEnded, listener, false);
// If |element| is actually playing a MediaStream, just clone it.
if (element.GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream) {
- MediaStreamDescriptor* const descriptor =
- element.currentSrc().IsEmpty()
- ? element.GetSrcObject()
- : MediaStreamRegistry::Registry().LookupMediaStreamDescriptor(
- element.currentSrc().GetString());
+ MediaStreamDescriptor* const descriptor = element.GetSrcObject();
DCHECK(descriptor);
return MediaStream::Create(context, descriptor);
}
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.cc b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.cc
index d770783fec7..aefa9528d7f 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.cc
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.cc
@@ -17,7 +17,7 @@ OnRequestCanvasDrawListener::~OnRequestCanvasDrawListener() = default;
// static
OnRequestCanvasDrawListener* OnRequestCanvasDrawListener::Create(
std::unique_ptr<WebCanvasCaptureHandler> handler) {
- return new OnRequestCanvasDrawListener(std::move(handler));
+ return MakeGarbageCollected<OnRequestCanvasDrawListener>(std::move(handler));
}
void OnRequestCanvasDrawListener::SendNewFrame(
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.h b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.h
index d3d5bf85045..617b7cce642 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.h
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/on_request_canvas_draw_listener.h
@@ -20,7 +20,9 @@ class OnRequestCanvasDrawListener final
USING_GARBAGE_COLLECTED_MIXIN(OnRequestCanvasDrawListener);
public:
+ OnRequestCanvasDrawListener(std::unique_ptr<WebCanvasCaptureHandler>);
~OnRequestCanvasDrawListener() override;
+
static OnRequestCanvasDrawListener* Create(
std::unique_ptr<WebCanvasCaptureHandler>);
void SendNewFrame(
@@ -28,9 +30,6 @@ class OnRequestCanvasDrawListener final
base::WeakPtr<WebGraphicsContext3DProviderWrapper>) override;
void Trace(blink::Visitor* visitor) override {}
-
- private:
- OnRequestCanvasDrawListener(std::unique_ptr<WebCanvasCaptureHandler>);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.cc b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.cc
index fd6e45da7d0..dbf0f8b5e5f 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.cc
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.cc
@@ -29,7 +29,8 @@ TimedCanvasDrawListener* TimedCanvasDrawListener::Create(
double frame_rate,
ExecutionContext* context) {
TimedCanvasDrawListener* listener =
- new TimedCanvasDrawListener(std::move(handler), frame_rate, context);
+ MakeGarbageCollected<TimedCanvasDrawListener>(std::move(handler),
+ frame_rate, context);
listener->request_frame_timer_.StartRepeating(listener->frame_interval_,
FROM_HERE);
return listener;
diff --git a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.h b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.h
index 5579f2da58b..a8c8d79ee48 100644
--- a/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.h
+++ b/chromium/third_party/blink/renderer/modules/mediacapturefromelement/timed_canvas_draw_listener.h
@@ -23,7 +23,11 @@ class TimedCanvasDrawListener final
USING_GARBAGE_COLLECTED_MIXIN(TimedCanvasDrawListener);
public:
+ TimedCanvasDrawListener(std::unique_ptr<WebCanvasCaptureHandler>,
+ double frame_rate,
+ ExecutionContext*);
~TimedCanvasDrawListener() override;
+
static TimedCanvasDrawListener* Create(
std::unique_ptr<WebCanvasCaptureHandler>,
double frame_rate,
@@ -35,9 +39,6 @@ class TimedCanvasDrawListener final
void Trace(blink::Visitor* visitor) override {}
private:
- TimedCanvasDrawListener(std::unique_ptr<WebCanvasCaptureHandler>,
- double frame_rate,
- ExecutionContext*);
// Implementation of TimerFiredFunction.
void RequestFrameTimerFired(TimerBase*);
diff --git a/chromium/third_party/blink/renderer/modules/mediarecorder/README.md b/chromium/third_party/blink/renderer/modules/mediarecorder/README.md
index 90dbc3a422a..46ef24f1ceb 100644
--- a/chromium/third_party/blink/renderer/modules/mediarecorder/README.md
+++ b/chromium/third_party/blink/renderer/modules/mediarecorder/README.md
@@ -49,7 +49,7 @@ can be flushed using `requestData()` or `stop()`. `event.data` contains the
recorded `Blob`.
[`MediaRecorderOptions`]: https://w3c.github.io/mediacapture-record/#mediarecorderoptions-section
-[isTypeSupported()]: https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/fast/mediarecorder/MediaRecorder-isTypeSupported.html
+[isTypeSupported()]: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/web_tests/fast/mediarecorder/MediaRecorder-isTypeSupported.html
## Implementation in Chromium
@@ -91,12 +91,12 @@ alternative is to use a Javascript library to reconstruct the Cues (see the
## Testing
-Media Recorder layout tests are located in [LayoutTests/fast/mediarecorder], and
-[LayoutTests/external/mediacapture-record], unittests in [content] and [media]
+Media Recorder layout tests are located in [web_tests/fast/mediarecorder], and
+[web_tests/external/mediacapture-record], unittests in [content] and [media]
and [browsertests].
-[LayoutTests/fast/mediarecorder]: https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/fast/mediarecorder/
-[LayoutTests/external/mediacapture-record]: https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/LayoutTests/external/wpt/mediacapture-record/
+[web_tests/fast/mediarecorder]: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/web_tests/fast/mediarecorder/
+[web_tests/external/mediacapture-record]: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/web_tests/external/wpt/mediacapture-record/
[content]: https://chromium.googlesource.com/chromium/src/+/master/content/renderer/media_recorder/
[media]: https://chromium.googlesource.com/chromium/src/+/master/media/muxers
[browsertests]: https://chromium.googlesource.com/chromium/src/+/master/content/browser/webrtc/webrtc_media_recorder_browsertest.cc
diff --git a/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.cc b/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.cc
index c34c2c37fd5..6ff4daa2946 100644
--- a/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.cc
+++ b/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.cc
@@ -11,7 +11,7 @@ namespace blink {
// static
BlobEvent* BlobEvent::Create(const AtomicString& type,
- const BlobEventInit& initializer) {
+ const BlobEventInit* initializer) {
return new BlobEvent(type, initializer);
}
@@ -23,7 +23,7 @@ BlobEvent* BlobEvent::Create(const AtomicString& type,
}
const AtomicString& BlobEvent::InterfaceName() const {
- return EventNames::BlobEvent;
+ return event_interface_names::kBlobEvent;
}
void BlobEvent::Trace(blink::Visitor* visitor) {
@@ -31,11 +31,11 @@ void BlobEvent::Trace(blink::Visitor* visitor) {
Event::Trace(visitor);
}
-BlobEvent::BlobEvent(const AtomicString& type, const BlobEventInit& initializer)
+BlobEvent::BlobEvent(const AtomicString& type, const BlobEventInit* initializer)
: Event(type, initializer),
- blob_(initializer.data()),
- timecode_(initializer.hasTimecode()
- ? initializer.timecode()
+ blob_(initializer->data()),
+ timecode_(initializer->hasTimecode()
+ ? initializer->timecode()
: WTF::double_conversion::Double::NaN()) {}
BlobEvent::BlobEvent(const AtomicString& type, Blob* blob, double timecode)
diff --git a/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.h b/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.h
index b5701b29f0a..cf7328a2d47 100644
--- a/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.h
+++ b/chromium/third_party/blink/renderer/modules/mediarecorder/blob_event.h
@@ -23,7 +23,7 @@ class MODULES_EXPORT BlobEvent final : public Event {
~BlobEvent() override = default;
static BlobEvent* Create(const AtomicString& type,
- const BlobEventInit& initializer);
+ const BlobEventInit* initializer);
static BlobEvent* Create(const AtomicString& type,
Blob* blob,
double timecode);
@@ -37,7 +37,7 @@ class MODULES_EXPORT BlobEvent final : public Event {
void Trace(blink::Visitor* visitor) override;
private:
- BlobEvent(const AtomicString& type, const BlobEventInit& initializer);
+ BlobEvent(const AtomicString& type, const BlobEventInit* initializer);
BlobEvent(const AtomicString& type, Blob* blob, double timecode);
Member<Blob> blob_;
diff --git a/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc b/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc
index 6b80cf3a665..e09ad439569 100644
--- a/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc
+++ b/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc
@@ -55,7 +55,7 @@ String StateToString(MediaRecorder::State state) {
// This method throws NotSupportedError.
void AllocateVideoAndAudioBitrates(ExceptionState& exception_state,
ExecutionContext* context,
- const MediaRecorderOptions& options,
+ const MediaRecorderOptions* options,
MediaStream* stream,
int* audio_bits_per_second,
int* video_bits_per_second) {
@@ -68,25 +68,25 @@ void AllocateVideoAndAudioBitrates(ExceptionState& exception_state,
const unsigned kMaxIntAsUnsigned = std::numeric_limits<int>::max();
int overall_bps = 0;
- if (options.hasBitsPerSecond())
- overall_bps = std::min(options.bitsPerSecond(), kMaxIntAsUnsigned);
+ if (options->hasBitsPerSecond())
+ overall_bps = std::min(options->bitsPerSecond(), kMaxIntAsUnsigned);
int video_bps = 0;
- if (options.hasVideoBitsPerSecond() && use_video)
- video_bps = std::min(options.videoBitsPerSecond(), kMaxIntAsUnsigned);
+ if (options->hasVideoBitsPerSecond() && use_video)
+ video_bps = std::min(options->videoBitsPerSecond(), kMaxIntAsUnsigned);
int audio_bps = 0;
- if (options.hasAudioBitsPerSecond() && use_audio)
- audio_bps = std::min(options.audioBitsPerSecond(), kMaxIntAsUnsigned);
+ if (options->hasAudioBitsPerSecond() && use_audio)
+ audio_bps = std::min(options->audioBitsPerSecond(), kMaxIntAsUnsigned);
if (use_audio) {
// |overallBps| overrides the specific audio and video bit rates.
- if (options.hasBitsPerSecond()) {
+ if (options->hasBitsPerSecond()) {
if (use_video)
audio_bps = overall_bps / 10;
else
audio_bps = overall_bps;
}
// Limit audio bitrate values if set explicitly or calculated.
- if (options.hasAudioBitsPerSecond() || options.hasBitsPerSecond()) {
+ if (options->hasAudioBitsPerSecond() || options->hasBitsPerSecond()) {
if (audio_bps > kLargestAutoAllocatedOpusBitRate) {
context->AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kWarningMessageLevel,
@@ -111,11 +111,11 @@ void AllocateVideoAndAudioBitrates(ExceptionState& exception_state,
if (use_video) {
// Allocate the remaining |overallBps|, if any, to video.
- if (options.hasBitsPerSecond())
+ if (options->hasBitsPerSecond())
video_bps = overall_bps - audio_bps;
// Clamp the video bit rate. Avoid clamping if the user has not set it
// explicitly.
- if (options.hasVideoBitsPerSecond() || options.hasBitsPerSecond()) {
+ if (options->hasVideoBitsPerSecond() || options->hasBitsPerSecond()) {
if (video_bps < kSmallestPossibleVpxBitRate) {
context->AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kWarningMessageLevel,
@@ -139,8 +139,8 @@ void AllocateVideoAndAudioBitrates(ExceptionState& exception_state,
MediaRecorder* MediaRecorder::Create(ExecutionContext* context,
MediaStream* stream,
ExceptionState& exception_state) {
- MediaRecorder* recorder = new MediaRecorder(
- context, stream, MediaRecorderOptions(), exception_state);
+ MediaRecorder* recorder = MakeGarbageCollected<MediaRecorder>(
+ context, stream, MediaRecorderOptions::Create(), exception_state);
recorder->PauseIfNeeded();
return recorder;
@@ -148,10 +148,10 @@ MediaRecorder* MediaRecorder::Create(ExecutionContext* context,
MediaRecorder* MediaRecorder::Create(ExecutionContext* context,
MediaStream* stream,
- const MediaRecorderOptions& options,
+ const MediaRecorderOptions* options,
ExceptionState& exception_state) {
- MediaRecorder* recorder =
- new MediaRecorder(context, stream, options, exception_state);
+ MediaRecorder* recorder = MakeGarbageCollected<MediaRecorder>(
+ context, stream, options, exception_state);
recorder->PauseIfNeeded();
return recorder;
@@ -159,11 +159,12 @@ MediaRecorder* MediaRecorder::Create(ExecutionContext* context,
MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
- const MediaRecorderOptions& options,
+ const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
- mime_type_(options.hasMimeType() ? options.mimeType() : kDefaultMimeType),
+ mime_type_(options->hasMimeType() ? options->mimeType()
+ : kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
@@ -208,7 +209,7 @@ MediaRecorder::MediaRecorder(ExecutionContext* context,
return;
}
// If the user requested no mimeType, query |recorder_handler_|.
- if (options.mimeType().IsEmpty()) {
+ if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
@@ -242,7 +243,7 @@ void MediaRecorder::start(int time_slice, ExceptionState& exception_state) {
"tracks available.");
return;
}
- ScheduleDispatchEvent(Event::Create(EventTypeNames::start));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kStart));
}
void MediaRecorder::stop(ExceptionState& exception_state) {
@@ -270,7 +271,7 @@ void MediaRecorder::pause(ExceptionState& exception_state) {
recorder_handler_->Pause();
- ScheduleDispatchEvent(Event::Create(EventTypeNames::pause));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kPause));
}
void MediaRecorder::resume(ExceptionState& exception_state) {
@@ -286,7 +287,7 @@ void MediaRecorder::resume(ExceptionState& exception_state) {
state_ = State::kRecording;
recorder_handler_->Resume();
- ScheduleDispatchEvent(Event::Create(EventTypeNames::resume));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kResume));
}
void MediaRecorder::requestData(ExceptionState& exception_state) {
@@ -319,7 +320,7 @@ bool MediaRecorder::isTypeSupported(ExecutionContext* context,
}
const AtomicString& MediaRecorder::InterfaceName() const {
- return EventTargetNames::MediaRecorder;
+ return event_target_names::kMediaRecorder;
}
ExecutionContext* MediaRecorder::GetExecutionContext() const {
@@ -349,7 +350,7 @@ void MediaRecorder::WriteData(const char* data,
double timecode) {
if (stopped_ && !last_in_slice) {
stopped_ = false;
- ScheduleDispatchEvent(Event::Create(EventTypeNames::start));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kStart));
}
if (!blob_data_) {
@@ -372,12 +373,12 @@ void MediaRecorder::WriteData(const char* data,
void MediaRecorder::OnError(const WebString& message) {
DLOG(ERROR) << message.Ascii();
StopRecording();
- ScheduleDispatchEvent(Event::Create(EventTypeNames::error));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kError));
}
void MediaRecorder::CreateBlobEvent(Blob* blob, double timecode) {
ScheduleDispatchEvent(
- BlobEvent::Create(EventTypeNames::dataavailable, blob, timecode));
+ BlobEvent::Create(event_type_names::kDataavailable, blob, timecode));
}
void MediaRecorder::StopRecording() {
@@ -388,7 +389,7 @@ void MediaRecorder::StopRecording() {
WriteData(nullptr /* data */, 0 /* length */, true /* lastInSlice */,
WTF::CurrentTimeMS());
- ScheduleDispatchEvent(Event::Create(EventTypeNames::stop));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kStop));
}
void MediaRecorder::ScheduleDispatchEvent(Event* event) {
diff --git a/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.h b/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.h
index 7597107ccb8..aaf3ab16c0a 100644
--- a/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.h
+++ b/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.h
@@ -39,23 +39,27 @@ class MODULES_EXPORT MediaRecorder final
ExceptionState& exception_state);
static MediaRecorder* Create(ExecutionContext* context,
MediaStream* stream,
- const MediaRecorderOptions& options,
+ const MediaRecorderOptions* options,
ExceptionState& exception_state);
+ MediaRecorder(ExecutionContext* context,
+ MediaStream* stream,
+ const MediaRecorderOptions* options,
+ ExceptionState& exception_state);
~MediaRecorder() override;
MediaStream* stream() const { return stream_.Get(); }
const String& mimeType() const { return mime_type_; }
String state() const;
- unsigned long videoBitsPerSecond() const { return video_bits_per_second_; }
- unsigned long audioBitsPerSecond() const { return audio_bits_per_second_; }
+ uint32_t videoBitsPerSecond() const { return video_bits_per_second_; }
+ uint32_t audioBitsPerSecond() const { return audio_bits_per_second_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(start);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(stop);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dataavailable);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pause);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resume);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(start, kStart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(stop, kStop);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(dataavailable, kDataavailable);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(pause, kPause);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resume, kResume);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
void start(ExceptionState& exception_state);
void start(int time_slice, ExceptionState& exception_state);
@@ -88,11 +92,6 @@ class MODULES_EXPORT MediaRecorder final
void Trace(blink::Visitor* visitor) override;
private:
- MediaRecorder(ExecutionContext* context,
- MediaStream* stream,
- const MediaRecorderOptions& options,
- ExceptionState& exception_state);
-
void CreateBlobEvent(Blob* blob, double timecode);
void StopRecording();
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.cc b/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.cc
index caaa6a4dc92..fee4f43a02d 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.cc
@@ -17,22 +17,23 @@ namespace blink {
// static
MediaMetadata* MediaMetadata::Create(ScriptState* script_state,
- const MediaMetadataInit& metadata,
+ const MediaMetadataInit* metadata,
ExceptionState& exception_state) {
- return new MediaMetadata(script_state, metadata, exception_state);
+ return MakeGarbageCollected<MediaMetadata>(script_state, metadata,
+ exception_state);
}
MediaMetadata::MediaMetadata(ScriptState* script_state,
- const MediaMetadataInit& metadata,
+ const MediaMetadataInit* metadata,
ExceptionState& exception_state)
: notify_session_timer_(ExecutionContext::From(script_state)
->GetTaskRunner(TaskType::kMiscPlatformAPI),
this,
&MediaMetadata::NotifySessionTimerFired) {
- title_ = metadata.title();
- artist_ = metadata.artist();
- album_ = metadata.album();
- SetArtworkInternal(script_state, metadata.artwork(), exception_state);
+ title_ = metadata->title();
+ artist_ = metadata->artist();
+ album_ = metadata->album();
+ SetArtworkInternal(script_state, metadata->artwork(), exception_state);
}
String MediaMetadata::title() const {
@@ -47,7 +48,7 @@ String MediaMetadata::album() const {
return album_;
}
-const HeapVector<MediaImage>& MediaMetadata::artwork() const {
+const HeapVector<Member<MediaImage>>& MediaMetadata::artwork() const {
return artwork_;
}
@@ -79,7 +80,7 @@ void MediaMetadata::setAlbum(const String& album) {
}
void MediaMetadata::setArtwork(ScriptState* script_state,
- const HeapVector<MediaImage>& artwork,
+ const HeapVector<Member<MediaImage>>& artwork,
ExceptionState& exception_state) {
SetArtworkInternal(script_state, artwork, exception_state);
NotifySessionAsync();
@@ -101,19 +102,20 @@ void MediaMetadata::NotifySessionTimerFired(TimerBase*) {
session_->OnMetadataChanged();
}
-void MediaMetadata::SetArtworkInternal(ScriptState* script_state,
- const HeapVector<MediaImage>& artwork,
- ExceptionState& exception_state) {
- HeapVector<MediaImage> processed_artwork(artwork);
+void MediaMetadata::SetArtworkInternal(
+ ScriptState* script_state,
+ const HeapVector<Member<MediaImage>>& artwork,
+ ExceptionState& exception_state) {
+ HeapVector<Member<MediaImage>> processed_artwork(artwork);
- for (MediaImage& image : processed_artwork) {
- KURL url = ExecutionContext::From(script_state)->CompleteURL(image.src());
+ for (MediaImage* image : processed_artwork) {
+ KURL url = ExecutionContext::From(script_state)->CompleteURL(image->src());
if (!url.IsValid()) {
- exception_state.ThrowTypeError("'" + image.src() +
+ exception_state.ThrowTypeError("'" + image->src() +
"' can't be resolved to a valid URL.");
return;
}
- image.setSrc(url);
+ image->setSrc(url);
}
DCHECK(!exception_state.HadException());
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.h b/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.h
index e632ad6543b..13055d4ab53 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.h
+++ b/chromium/third_party/blink/renderer/modules/mediasession/media_metadata.h
@@ -30,9 +30,11 @@ class MODULES_EXPORT MediaMetadata final : public ScriptWrappable {
public:
static MediaMetadata* Create(ScriptState*,
- const MediaMetadataInit&,
+ const MediaMetadataInit*,
ExceptionState&);
+ MediaMetadata(ScriptState*, const MediaMetadataInit*, ExceptionState&);
+
String title() const;
String artist() const;
String album() const;
@@ -40,12 +42,14 @@ class MODULES_EXPORT MediaMetadata final : public ScriptWrappable {
// Internal use only, returns a reference to m_artwork instead of a Frozen
// copy of a MediaImage array.
- const HeapVector<MediaImage>& artwork() const;
+ const HeapVector<Member<MediaImage>>& artwork() const;
void setTitle(const String&);
void setArtist(const String&);
void setAlbum(const String&);
- void setArtwork(ScriptState*, const HeapVector<MediaImage>&, ExceptionState&);
+ void setArtwork(ScriptState*,
+ const HeapVector<Member<MediaImage>>&,
+ ExceptionState&);
// Called by MediaSession to associate or de-associate itself.
void SetSession(MediaSession*);
@@ -53,8 +57,6 @@ class MODULES_EXPORT MediaMetadata final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- MediaMetadata(ScriptState*, const MediaMetadataInit&, ExceptionState&);
-
// Called when one of the metadata fields is updated from script. It will
// notify the session asynchronously in order to bundle multiple call in one
// notification.
@@ -67,13 +69,13 @@ class MODULES_EXPORT MediaMetadata final : public ScriptWrappable {
// Make an internal copy of the MediaImage vector with some internal steps
// such as parsing of the src property.
void SetArtworkInternal(ScriptState*,
- const HeapVector<MediaImage>&,
+ const HeapVector<Member<MediaImage>>&,
ExceptionState&);
String title_;
String artist_;
String album_;
- HeapVector<MediaImage> artwork_;
+ HeapVector<Member<MediaImage>> artwork_;
Member<MediaSession> session_;
TaskRunnerTimer<MediaMetadata> notify_session_timer_;
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/media_metadata_sanitizer.cc b/chromium/third_party/blink/renderer/modules/mediasession/media_metadata_sanitizer.cc
index b70fa5a6063..0db31ca016a 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/media_metadata_sanitizer.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasession/media_metadata_sanitizer.cc
@@ -60,19 +60,19 @@ bool CheckMediaImageSrcSanity(const KURL& src, ExecutionContext* context) {
// Sanitize MediaImage and do mojo serialization. Returns null when
// |image.src()| is bad.
blink::mojom::blink::MediaImagePtr SanitizeMediaImageAndConvertToMojo(
- const MediaImage& image,
+ const MediaImage* image,
ExecutionContext* context) {
blink::mojom::blink::MediaImagePtr mojo_image;
- KURL url = KURL(image.src());
+ KURL url = KURL(image->src());
if (!CheckMediaImageSrcSanity(url, context))
return mojo_image;
mojo_image = blink::mojom::blink::MediaImage::New();
mojo_image->src = url;
- mojo_image->type = image.type().Left(kMaxImageTypeLength);
+ mojo_image->type = image->type().Left(kMaxImageTypeLength);
for (const auto& web_size :
- WebIconSizesParser::ParseIconSizes(image.sizes())) {
+ WebIconSizesParser::ParseIconSizes(image->sizes())) {
mojo_image->sizes.push_back(web_size);
if (mojo_image->sizes.size() == kMaxNumberOfImageSizes) {
context->AddConsoleMessage(ConsoleMessage::Create(
@@ -100,7 +100,7 @@ MediaMetadataSanitizer::SanitizeAndConvertToMojo(const MediaMetadata* metadata,
mojo_metadata->artist = metadata->artist().Left(kMaxStringLength);
mojo_metadata->album = metadata->album().Left(kMaxStringLength);
- for (const MediaImage& image : metadata->artwork()) {
+ for (const MediaImage* image : metadata->artwork()) {
blink::mojom::blink::MediaImagePtr mojo_image =
SanitizeMediaImageAndConvertToMojo(image, context);
if (!mojo_image.is_null())
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/media_session.cc b/chromium/third_party/blink/renderer/modules/mediasession/media_session.cc
index 697e0f48ffc..80ded6b5ef6 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/media_session.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasession/media_session.cc
@@ -20,7 +20,7 @@ namespace blink {
namespace {
-using ::blink::mojom::blink::MediaSessionAction;
+using ::media_session::mojom::blink::MediaSessionAction;
const AtomicString& MojomActionToActionName(MediaSessionAction action) {
DEFINE_STATIC_LOCAL(const AtomicString, play_action_name, ("play"));
@@ -35,17 +35,17 @@ const AtomicString& MojomActionToActionName(MediaSessionAction action) {
("seekforward"));
switch (action) {
- case MediaSessionAction::PLAY:
+ case MediaSessionAction::kPlay:
return play_action_name;
- case MediaSessionAction::PAUSE:
+ case MediaSessionAction::kPause:
return pause_action_name;
- case MediaSessionAction::PREVIOUS_TRACK:
+ case MediaSessionAction::kPreviousTrack:
return previous_track_action_name;
- case MediaSessionAction::NEXT_TRACK:
+ case MediaSessionAction::kNextTrack:
return next_track_action_name;
- case MediaSessionAction::SEEK_BACKWARD:
+ case MediaSessionAction::kSeekBackward:
return seek_backward_action_name;
- case MediaSessionAction::SEEK_FORWARD:
+ case MediaSessionAction::kSeekForward:
return seek_forward_action_name;
default:
NOTREACHED();
@@ -56,17 +56,17 @@ const AtomicString& MojomActionToActionName(MediaSessionAction action) {
base::Optional<MediaSessionAction> ActionNameToMojomAction(
const String& action_name) {
if ("play" == action_name)
- return MediaSessionAction::PLAY;
+ return MediaSessionAction::kPlay;
if ("pause" == action_name)
- return MediaSessionAction::PAUSE;
+ return MediaSessionAction::kPause;
if ("previoustrack" == action_name)
- return MediaSessionAction::PREVIOUS_TRACK;
+ return MediaSessionAction::kPreviousTrack;
if ("nexttrack" == action_name)
- return MediaSessionAction::NEXT_TRACK;
+ return MediaSessionAction::kNextTrack;
if ("seekbackward" == action_name)
- return MediaSessionAction::SEEK_BACKWARD;
+ return MediaSessionAction::kSeekBackward;
if ("seekforward" == action_name)
- return MediaSessionAction::SEEK_FORWARD;
+ return MediaSessionAction::kSeekForward;
NOTREACHED();
return base::nullopt;
@@ -108,7 +108,7 @@ MediaSession::MediaSession(ExecutionContext* execution_context)
client_binding_(this) {}
MediaSession* MediaSession::Create(ExecutionContext* execution_context) {
- return new MediaSession(execution_context);
+ return MakeGarbageCollected<MediaSession>(execution_context);
}
void MediaSession::Dispose() {
@@ -213,7 +213,7 @@ mojom::blink::MediaSessionService* MediaSession::GetService() {
}
void MediaSession::DidReceiveAction(
- blink::mojom::blink::MediaSessionAction action) {
+ media_session::mojom::blink::MediaSessionAction action) {
Document* document = To<Document>(GetExecutionContext());
std::unique_ptr<UserGestureIndicator> gesture_indicator =
LocalFrame::NotifyUserActivation(document ? document->GetFrame()
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/media_session.h b/chromium/third_party/blink/renderer/modules/mediasession/media_session.h
index 45c9a2f63de..0f48b8095d7 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/media_session.h
+++ b/chromium/third_party/blink/renderer/modules/mediasession/media_session.h
@@ -32,6 +32,8 @@ class MODULES_EXPORT MediaSession final
public:
static MediaSession* Create(ExecutionContext*);
+ explicit MediaSession(ExecutionContext*);
+
void Dispose();
void setPlaybackState(const String&);
@@ -57,12 +59,11 @@ class MODULES_EXPORT MediaSession final
kActionDisabled,
};
- explicit MediaSession(ExecutionContext*);
-
void NotifyActionChange(const String& action, ActionChangeType);
// blink::mojom::blink::MediaSessionClient implementation.
- void DidReceiveAction(blink::mojom::blink::MediaSessionAction) override;
+ void DidReceiveAction(
+ media_session::mojom::blink::MediaSessionAction) override;
// Returns null when the ExecutionContext is not document.
mojom::blink::MediaSessionService* GetService();
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.cc b/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.cc
index 853faf27d19..e9b0122bbd3 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.cc
@@ -25,7 +25,7 @@ NavigatorMediaSession& NavigatorMediaSession::From(Navigator& navigator) {
NavigatorMediaSession* supplement =
Supplement<Navigator>::From<NavigatorMediaSession>(navigator);
if (!supplement) {
- supplement = new NavigatorMediaSession(navigator);
+ supplement = MakeGarbageCollected<NavigatorMediaSession>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.h b/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.h
index ed1b52b711b..5b630718e47 100644
--- a/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.h
+++ b/chromium/third_party/blink/renderer/modules/mediasession/navigator_media_session.h
@@ -26,11 +26,11 @@ class NavigatorMediaSession final
static NavigatorMediaSession& From(Navigator&);
static MediaSession* mediaSession(ScriptState*, Navigator&);
+ explicit NavigatorMediaSession(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorMediaSession(Navigator&);
-
// The MediaSession instance of this Navigator.
Member<MediaSession> session_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/media_source.cc b/chromium/third_party/blink/renderer/modules/mediasource/media_source.cc
index 2591f3459fe..3224fbd5f7c 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/media_source.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/media_source.cc
@@ -107,7 +107,7 @@ const AtomicString& MediaSource::EndedKeyword() {
}
MediaSource* MediaSource::Create(ExecutionContext* context) {
- return new MediaSource(context);
+ return MakeGarbageCollected<MediaSource>(context);
}
MediaSource::MediaSource(ExecutionContext* context)
@@ -255,12 +255,12 @@ void MediaSource::removeSourceBuffer(SourceBuffer* buffer,
void MediaSource::OnReadyStateChange(const AtomicString& old_state,
const AtomicString& new_state) {
if (IsOpen()) {
- ScheduleEvent(EventTypeNames::sourceopen);
+ ScheduleEvent(event_type_names::kSourceopen);
return;
}
if (old_state == OpenKeyword() && new_state == EndedKeyword()) {
- ScheduleEvent(EventTypeNames::sourceended);
+ ScheduleEvent(event_type_names::kSourceended);
return;
}
@@ -275,7 +275,7 @@ void MediaSource::OnReadyStateChange(const AtomicString& old_state,
attached_element_.Clear();
- ScheduleEvent(EventTypeNames::sourceclose);
+ ScheduleEvent(event_type_names::kSourceclose);
}
bool MediaSource::IsUpdating() const {
@@ -332,7 +332,7 @@ bool MediaSource::isTypeSupported(const String& type) {
}
const AtomicString& MediaSource::InterfaceName() const {
- return EventTargetNames::MediaSource;
+ return event_target_names::kMediaSource;
}
ExecutionContext* MediaSource::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/media_source.h b/chromium/third_party/blink/renderer/modules/mediasource/media_source.h
index a26dd1240b2..5cb42cf9b8b 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/media_source.h
+++ b/chromium/third_party/blink/renderer/modules/mediasource/media_source.h
@@ -63,6 +63,8 @@ class MediaSource final : public EventTargetWithInlineData,
static const AtomicString& EndedKeyword();
static MediaSource* Create(ExecutionContext*);
+
+ explicit MediaSource(ExecutionContext*);
~MediaSource() override;
static void LogAndThrowDOMException(ExceptionState&,
@@ -79,9 +81,9 @@ class MediaSource final : public EventTargetWithInlineData,
void removeSourceBuffer(SourceBuffer*, ExceptionState&);
void setDuration(double, ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceopen);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceended);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceclose);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceopen, kSourceopen);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceended, kSourceended);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceclose, kSourceclose);
const AtomicString& readyState() const { return ready_state_; }
void endOfStream(const AtomicString& error, ExceptionState&);
@@ -128,8 +130,6 @@ class MediaSource final : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- explicit MediaSource(ExecutionContext*);
-
void SetReadyState(const AtomicString&);
void OnReadyStateChange(const AtomicString&, const AtomicString&);
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/media_source_registry.cc b/chromium/third_party/blink/renderer/modules/mediasource/media_source_registry.cc
index 84c35851400..62a3c7b4742 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/media_source_registry.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/media_source_registry.cc
@@ -70,7 +70,8 @@ URLRegistrable* MediaSourceRegistry::Lookup(const String& url) {
}
MediaSourceRegistry::MediaSourceRegistry()
- : media_sources_(new HeapHashMap<String, Member<MediaSource>>) {
+ : media_sources_(
+ MakeGarbageCollected<HeapHashMap<String, Member<MediaSource>>>()) {
HTMLMediaSource::SetRegistry(this);
}
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.cc b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.cc
index a495b2e2be6..c265d3370ba 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.cc
@@ -108,8 +108,8 @@ SourceBuffer* SourceBuffer::Create(
std::unique_ptr<WebSourceBuffer> web_source_buffer,
MediaSource* source,
EventQueue* async_event_queue) {
- SourceBuffer* source_buffer =
- new SourceBuffer(std::move(web_source_buffer), source, async_event_queue);
+ SourceBuffer* source_buffer = MakeGarbageCollected<SourceBuffer>(
+ std::move(web_source_buffer), source, async_event_queue);
source_buffer->PauseIfNeeded();
return source_buffer;
}
@@ -508,7 +508,7 @@ void SourceBuffer::remove(double start,
// 7.4. Queue a task to fire a simple event named updatestart at this
// SourceBuffer object.
- ScheduleEvent(EventTypeNames::updatestart);
+ ScheduleEvent(event_type_names::kUpdatestart);
// 7.5. Return control to the caller and run the rest of the steps
// asynchronously.
@@ -610,8 +610,8 @@ void SourceBuffer::CancelRemove() {
updating_ = false;
if (!RuntimeEnabledFeatures::MediaSourceNewAbortAndDurationEnabled()) {
- ScheduleEvent(EventTypeNames::abort);
- ScheduleEvent(EventTypeNames::updateend);
+ ScheduleEvent(event_type_names::kAbort);
+ ScheduleEvent(event_type_names::kUpdateend);
}
TRACE_EVENT_ASYNC_END0("media", "SourceBuffer::remove", this);
@@ -639,11 +639,11 @@ void SourceBuffer::AbortIfUpdating() {
// 4.3. Queue a task to fire a simple event named abort at this SourceBuffer
// object.
- ScheduleEvent(EventTypeNames::abort);
+ ScheduleEvent(event_type_names::kAbort);
// 4.4. Queue a task to fire a simple event named updateend at this
// SourceBuffer object.
- ScheduleEvent(EventTypeNames::updateend);
+ ScheduleEvent(event_type_names::kUpdateend);
TRACE_EVENT_ASYNC_END0("media", trace_event_name, this);
}
@@ -724,7 +724,7 @@ void SourceBuffer::RemoveMediaTracks() {
// to fire a simple event named change at the HTMLMediaElement audioTracks
// list.
if (removed_enabled_audio_track) {
- Event* event = Event::Create(EventTypeNames::change);
+ Event* event = Event::Create(event_type_names::kChange);
event->SetTarget(&media_element->audioTracks());
media_element->ScheduleEvent(event);
}
@@ -764,7 +764,7 @@ void SourceBuffer::RemoveMediaTracks() {
// to fire a simple event named change at the HTMLMediaElement videoTracks
// list.
if (removed_selected_video_track) {
- Event* event = Event::Create(EventTypeNames::change);
+ Event* event = Event::Create(event_type_names::kChange);
event->SetTarget(&media_element->videoTracks());
media_element->ScheduleEvent(event);
}
@@ -1175,7 +1175,7 @@ ExecutionContext* SourceBuffer::GetExecutionContext() const {
}
const AtomicString& SourceBuffer::InterfaceName() const {
- return EventTargetNames::SourceBuffer;
+ return event_target_names::kSourceBuffer;
}
bool SourceBuffer::IsRemoved() const {
@@ -1294,7 +1294,7 @@ void SourceBuffer::AppendBufferInternal(double media_time,
// 4. Queue a task to fire a simple event named updatestart at this
// SourceBuffer object.
- ScheduleEvent(EventTypeNames::updatestart);
+ ScheduleEvent(event_type_names::kUpdatestart);
// 5. Asynchronously run the buffer append algorithm.
append_buffer_async_part_runner_->RunAsync();
@@ -1359,11 +1359,11 @@ void SourceBuffer::AppendBufferAsyncPart() {
// 4. Queue a task to fire a simple event named update at this SourceBuffer
// object.
- ScheduleEvent(EventTypeNames::update);
+ ScheduleEvent(event_type_names::kUpdate);
// 5. Queue a task to fire a simple event named updateend at this
// SourceBuffer object.
- ScheduleEvent(EventTypeNames::updateend);
+ ScheduleEvent(event_type_names::kUpdateend);
}
TRACE_EVENT_ASYNC_END0("media", "SourceBuffer::appendBuffer", this);
@@ -1392,11 +1392,11 @@ void SourceBuffer::RemoveAsyncPart() {
// 11. Queue a task to fire a simple event named update at this SourceBuffer
// object.
- ScheduleEvent(EventTypeNames::update);
+ ScheduleEvent(event_type_names::kUpdate);
// 12. Queue a task to fire a simple event named updateend at this
// SourceBuffer object.
- ScheduleEvent(EventTypeNames::updateend);
+ ScheduleEvent(event_type_names::kUpdateend);
}
void SourceBuffer::AppendError() {
@@ -1412,11 +1412,11 @@ void SourceBuffer::AppendError() {
// 3. Queue a task to fire a simple event named error at this SourceBuffer
// object.
- ScheduleEvent(EventTypeNames::error);
+ ScheduleEvent(event_type_names::kError);
// 4. Queue a task to fire a simple event named updateend at this SourceBuffer
// object.
- ScheduleEvent(EventTypeNames::updateend);
+ ScheduleEvent(event_type_names::kUpdateend);
// 5. If decode error is true, then run the end of stream algorithm with the
// error parameter set to "decode".
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.h b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.h
index 1e2ec4a9ae2..dcf697403ee 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.h
+++ b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.h
@@ -69,6 +69,7 @@ class SourceBuffer final : public EventTargetWithInlineData,
static const AtomicString& SegmentsKeyword();
static const AtomicString& SequenceKeyword();
+ SourceBuffer(std::unique_ptr<WebSourceBuffer>, MediaSource*, EventQueue*);
~SourceBuffer() override;
// SourceBuffer.idl methods
@@ -87,11 +88,11 @@ class SourceBuffer final : public EventTargetWithInlineData,
void setAppendWindowStart(double, ExceptionState&);
double appendWindowEnd() const;
void setAppendWindowEnd(double, ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(updatestart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(update);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(updateend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(updatestart, kUpdatestart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(update, kUpdate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(updateend, kUpdateend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(abort, kAbort);
TrackDefaultList* trackDefaults() const { return track_defaults_.Get(); }
void setTrackDefaults(TrackDefaultList*, ExceptionState&);
@@ -120,7 +121,6 @@ class SourceBuffer final : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- SourceBuffer(std::unique_ptr<WebSourceBuffer>, MediaSource*, EventQueue*);
void Dispose();
bool IsRemoved() const;
@@ -171,7 +171,7 @@ class SourceBuffer final : public EventTargetWithInlineData,
bool first_initialization_segment_received_;
Vector<unsigned char> pending_append_data_;
- size_t pending_append_data_offset_;
+ wtf_size_t pending_append_data_offset_;
Member<AsyncMethodRunner<SourceBuffer>> append_buffer_async_part_runner_;
double pending_remove_start_;
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.cc b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.cc
index 44ceda95a19..0e54d5306d2 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.cc
@@ -44,25 +44,25 @@ SourceBufferList::~SourceBufferList() = default;
void SourceBufferList::Add(SourceBuffer* buffer) {
list_.push_back(buffer);
- ScheduleEvent(EventTypeNames::addsourcebuffer);
+ ScheduleEvent(event_type_names::kAddsourcebuffer);
}
-void SourceBufferList::insert(size_t position, SourceBuffer* buffer) {
+void SourceBufferList::insert(wtf_size_t position, SourceBuffer* buffer) {
list_.insert(position, buffer);
- ScheduleEvent(EventTypeNames::addsourcebuffer);
+ ScheduleEvent(event_type_names::kAddsourcebuffer);
}
void SourceBufferList::Remove(SourceBuffer* buffer) {
- size_t index = list_.Find(buffer);
+ wtf_size_t index = list_.Find(buffer);
if (index == kNotFound)
return;
list_.EraseAt(index);
- ScheduleEvent(EventTypeNames::removesourcebuffer);
+ ScheduleEvent(event_type_names::kRemovesourcebuffer);
}
void SourceBufferList::Clear() {
list_.clear();
- ScheduleEvent(EventTypeNames::removesourcebuffer);
+ ScheduleEvent(event_type_names::kRemovesourcebuffer);
}
void SourceBufferList::ScheduleEvent(const AtomicString& event_name) {
@@ -75,7 +75,7 @@ void SourceBufferList::ScheduleEvent(const AtomicString& event_name) {
}
const AtomicString& SourceBufferList::InterfaceName() const {
- return EventTargetNames::SourceBufferList;
+ return event_target_names::kSourceBufferList;
}
void SourceBufferList::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.h b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.h
index 1a5fa6013cb..658138513c1 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.h
+++ b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_list.h
@@ -48,23 +48,25 @@ class SourceBufferList final : public EventTargetWithInlineData,
public:
static SourceBufferList* Create(ExecutionContext* context,
EventQueue* async_event_queue) {
- return new SourceBufferList(context, async_event_queue);
+ return MakeGarbageCollected<SourceBufferList>(context, async_event_queue);
}
+
+ SourceBufferList(ExecutionContext*, EventQueue*);
~SourceBufferList() override;
unsigned length() const { return list_.size(); }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(addsourcebuffer);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(removesourcebuffer);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(addsourcebuffer, kAddsourcebuffer);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(removesourcebuffer, kRemovesourcebuffer);
SourceBuffer* item(unsigned index) const {
return (index < list_.size()) ? list_[index].Get() : nullptr;
}
void Add(SourceBuffer*);
- void insert(size_t position, SourceBuffer*);
+ void insert(wtf_size_t position, SourceBuffer*);
void Remove(SourceBuffer*);
- size_t Find(SourceBuffer* buffer) { return list_.Find(buffer); }
+ wtf_size_t Find(SourceBuffer* buffer) { return list_.Find(buffer); }
bool Contains(SourceBuffer* buffer) {
return list_.Find(buffer) != kNotFound;
}
@@ -79,8 +81,6 @@ class SourceBufferList final : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- SourceBufferList(ExecutionContext*, EventQueue*);
-
void ScheduleEvent(const AtomicString&);
Member<EventQueue> async_event_queue_;
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_track_base_supplement.cc b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_track_base_supplement.cc
index 6272473a377..268c82c4e8e 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_track_base_supplement.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/source_buffer_track_base_supplement.cc
@@ -24,7 +24,7 @@ SourceBufferTrackBaseSupplement& SourceBufferTrackBaseSupplement::From(
TrackBase& track) {
SourceBufferTrackBaseSupplement* supplement = FromIfExists(track);
if (!supplement) {
- supplement = new SourceBufferTrackBaseSupplement();
+ supplement = MakeGarbageCollected<SourceBufferTrackBaseSupplement>();
Supplement<TrackBase>::ProvideTo(track, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/track_default.cc b/chromium/third_party/blink/renderer/modules/mediasource/track_default.cc
index a0bf329b7ce..46283ee2c13 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/track_default.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/track_default.cc
@@ -95,7 +95,8 @@ TrackDefault* TrackDefault::Create(const AtomicString& type,
// 7. Set the byteStreamTrackID attribute on this new object to
// |byteStreamTrackID|.
// These steps are done as constructor initializers.
- return new TrackDefault(type, language, label, kinds, byte_stream_track_id);
+ return MakeGarbageCollected<TrackDefault>(type, language, label, kinds,
+ byte_stream_track_id);
}
TrackDefault::~TrackDefault() = default;
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/track_default.h b/chromium/third_party/blink/renderer/modules/mediasource/track_default.h
index 21799c68f52..fd68ef348aa 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/track_default.h
+++ b/chromium/third_party/blink/renderer/modules/mediasource/track_default.h
@@ -29,6 +29,11 @@ class TrackDefault final : public ScriptWrappable {
const String& byte_stream_track_id,
ExceptionState&);
+ TrackDefault(const AtomicString& type,
+ const String& language,
+ const String& label,
+ const Vector<String>& kinds,
+ const String& byte_stream_track_id);
~TrackDefault() override;
// Implement the IDL
@@ -39,12 +44,6 @@ class TrackDefault final : public ScriptWrappable {
ScriptValue kinds(ScriptState*) const;
private:
- TrackDefault(const AtomicString& type,
- const String& language,
- const String& label,
- const Vector<String>& kinds,
- const String& byte_stream_track_id);
-
const AtomicString type_;
const String byte_stream_track_id_;
const String language_;
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.cc b/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.cc
index 83979690974..5b8a0b110e7 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.cc
@@ -11,7 +11,7 @@
namespace blink {
TrackDefaultList* TrackDefaultList::Create() {
- return new TrackDefaultList();
+ return MakeGarbageCollected<TrackDefaultList>();
}
TrackDefaultList* TrackDefaultList::Create(
@@ -47,7 +47,7 @@ TrackDefaultList* TrackDefaultList::Create(
// 2. Store a shallow copy of |trackDefaults| in this new object so the values
// can be returned by the accessor methods.
// This step is done in constructor initializer.
- return new TrackDefaultList(track_defaults);
+ return MakeGarbageCollected<TrackDefaultList>(track_defaults);
}
TrackDefault* TrackDefaultList::item(unsigned index) const {
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.h b/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.h
index 7e7a98755da..ba6f658ce29 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.h
+++ b/chromium/third_party/blink/renderer/modules/mediasource/track_default_list.h
@@ -23,16 +23,15 @@ class TrackDefaultList final : public ScriptWrappable {
static TrackDefaultList* Create(const HeapVector<Member<TrackDefault>>&,
ExceptionState&);
+ TrackDefaultList();
+ explicit TrackDefaultList(const HeapVector<Member<TrackDefault>>&);
+
unsigned length() const { return track_defaults_.size(); }
TrackDefault* item(unsigned) const;
void Trace(blink::Visitor*) override;
private:
- TrackDefaultList();
-
- explicit TrackDefaultList(const HeapVector<Member<TrackDefault>>&);
-
const HeapVector<Member<TrackDefault>> track_defaults_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.cc b/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.cc
index 9e0adf2b3a8..60943daba8e 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.cc
+++ b/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.cc
@@ -42,8 +42,9 @@ VideoPlaybackQuality* VideoPlaybackQuality::Create(
unsigned total_video_frames,
unsigned dropped_video_frames,
unsigned corrupted_video_frames) {
- return new VideoPlaybackQuality(document, total_video_frames,
- dropped_video_frames, corrupted_video_frames);
+ return MakeGarbageCollected<VideoPlaybackQuality>(
+ document, total_video_frames, dropped_video_frames,
+ corrupted_video_frames);
}
VideoPlaybackQuality::VideoPlaybackQuality(const Document& document,
diff --git a/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.h b/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.h
index f2b842916d2..53e9d4798e3 100644
--- a/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.h
+++ b/chromium/third_party/blink/renderer/modules/mediasource/video_playback_quality.h
@@ -47,17 +47,17 @@ class VideoPlaybackQuality : public ScriptWrappable {
unsigned dropped_video_frames,
unsigned corrupted_video_frames);
+ VideoPlaybackQuality(const Document&,
+ unsigned total_video_frames,
+ unsigned dropped_video_frames,
+ unsigned corrupted_video_frames);
+
double creationTime() const { return creation_time_; }
unsigned totalVideoFrames() const { return total_video_frames_; }
unsigned droppedVideoFrames() const { return dropped_video_frames_; }
unsigned corruptedVideoFrames() const { return corrupted_video_frames_; }
private:
- VideoPlaybackQuality(const Document&,
- unsigned total_video_frames,
- unsigned dropped_video_frames,
- unsigned corrupted_video_frames);
-
double creation_time_;
unsigned total_video_frames_;
unsigned dropped_video_frames_;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/BUILD.gn b/chromium/third_party/blink/renderer/modules/mediastream/BUILD.gn
index e77eb497dd3..00f60af5280 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/mediastream/BUILD.gn
@@ -23,15 +23,11 @@ blink_modules_sources("mediastream") {
"media_stream.h",
"media_stream_event.cc",
"media_stream_event.h",
- "media_stream_registry.cc",
- "media_stream_registry.h",
"media_stream_track.cc",
"media_stream_track.h",
"media_stream_track_content_hint.h",
"media_stream_track_event.cc",
"media_stream_track_event.h",
- "navigator_display_media.cc",
- "navigator_display_media.h",
"navigator_media_stream.cc",
"navigator_media_stream.h",
"navigator_user_media.cc",
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.cc b/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.cc
index 20018b19d78..7a3fa46572d 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.cc
@@ -5,6 +5,8 @@
#include "third_party/blink/renderer/modules/mediastream/input_device_info.h"
#include <algorithm>
+
+#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/blink/renderer/modules/mediastream/media_track_capabilities.h"
namespace blink {
@@ -36,7 +38,8 @@ InputDeviceInfo* InputDeviceInfo::Create(const String& device_id,
const String& label,
const String& group_id,
MediaDeviceType device_type) {
- return new InputDeviceInfo(device_id, label, group_id, device_type);
+ return MakeGarbageCollected<InputDeviceInfo>(device_id, label, group_id,
+ device_type);
}
InputDeviceInfo::InputDeviceInfo(const String& device_id,
@@ -71,45 +74,47 @@ void InputDeviceInfo::SetVideoInputCapabilities(
}
}
-void InputDeviceInfo::getCapabilities(MediaTrackCapabilities& capabilities) {
+MediaTrackCapabilities* InputDeviceInfo::getCapabilities() const {
+ MediaTrackCapabilities* capabilities = MediaTrackCapabilities::Create();
+
// If label is null, permissions have not been given and no capabilities
// should be returned.
if (label().IsEmpty())
- return;
+ return capabilities;
- capabilities.setDeviceId(deviceId());
- capabilities.setGroupId(groupId());
+ capabilities->setDeviceId(deviceId());
+ capabilities->setGroupId(groupId());
if (DeviceType() == MediaDeviceType::MEDIA_AUDIO_INPUT) {
- capabilities.setEchoCancellation({true, false});
- capabilities.setAutoGainControl({true, false});
- capabilities.setNoiseSuppression({true, false});
+ capabilities->setEchoCancellation({true, false});
+ capabilities->setAutoGainControl({true, false});
+ capabilities->setNoiseSuppression({true, false});
}
if (DeviceType() == MediaDeviceType::MEDIA_VIDEO_INPUT) {
if (!platform_capabilities_.width.empty()) {
- LongRange width;
- width.setMin(platform_capabilities_.width[0]);
- width.setMax(platform_capabilities_.width[1]);
- capabilities.setWidth(width);
+ LongRange* width = LongRange::Create();
+ width->setMin(platform_capabilities_.width[0]);
+ width->setMax(platform_capabilities_.width[1]);
+ capabilities->setWidth(width);
}
if (!platform_capabilities_.height.empty()) {
- LongRange height;
- height.setMin(platform_capabilities_.height[0]);
- height.setMax(platform_capabilities_.height[1]);
- capabilities.setHeight(height);
+ LongRange* height = LongRange::Create();
+ height->setMin(platform_capabilities_.height[0]);
+ height->setMax(platform_capabilities_.height[1]);
+ capabilities->setHeight(height);
}
if (!platform_capabilities_.aspect_ratio.empty()) {
- DoubleRange aspect_ratio;
- aspect_ratio.setMin(platform_capabilities_.aspect_ratio[0]);
- aspect_ratio.setMax(platform_capabilities_.aspect_ratio[1]);
- capabilities.setAspectRatio(aspect_ratio);
+ DoubleRange* aspect_ratio = DoubleRange::Create();
+ aspect_ratio->setMin(platform_capabilities_.aspect_ratio[0]);
+ aspect_ratio->setMax(platform_capabilities_.aspect_ratio[1]);
+ capabilities->setAspectRatio(aspect_ratio);
}
if (!platform_capabilities_.frame_rate.empty()) {
- DoubleRange frame_rate;
- frame_rate.setMin(platform_capabilities_.frame_rate[0]);
- frame_rate.setMax(platform_capabilities_.frame_rate[1]);
- capabilities.setFrameRate(frame_rate);
+ DoubleRange* frame_rate = DoubleRange::Create();
+ frame_rate->setMin(platform_capabilities_.frame_rate[0]);
+ frame_rate->setMax(platform_capabilities_.frame_rate[1]);
+ capabilities->setFrameRate(frame_rate);
}
Vector<String> facing_mode;
switch (platform_capabilities_.facing_mode) {
@@ -128,8 +133,11 @@ void InputDeviceInfo::getCapabilities(MediaTrackCapabilities& capabilities) {
case WebMediaStreamTrack::FacingMode::kNone:
break;
}
- capabilities.setFacingMode(facing_mode);
+ capabilities->setFacingMode(facing_mode);
+ capabilities->setResizeMode({WebMediaStreamTrack::kResizeModeNone,
+ WebMediaStreamTrack::kResizeModeRescale});
}
+ return capabilities;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.h b/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.h
index 32573d69691..abd16df086a 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/input_device_info.h
@@ -21,16 +21,16 @@ class InputDeviceInfo final : public MediaDeviceInfo {
const String& group_id,
MediaDeviceType);
- void SetVideoInputCapabilities(mojom::blink::VideoInputDeviceCapabilitiesPtr);
-
- void getCapabilities(MediaTrackCapabilities&);
-
- private:
InputDeviceInfo(const String& device_id,
const String& label,
const String& group_id,
MediaDeviceType);
+ void SetVideoInputCapabilities(mojom::blink::VideoInputDeviceCapabilitiesPtr);
+
+ MediaTrackCapabilities* getCapabilities() const;
+
+ private:
WebMediaStreamSource::Capabilities platform_capabilities_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.cc
index e34bb663e14..b7e868fc544 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.cc
@@ -45,7 +45,7 @@
namespace blink {
-namespace MediaConstraintsImpl {
+namespace media_constraints_impl {
// A naked value is treated as an "ideal" value in the basic constraints,
// but as an exact value in "advanced" constraints.
@@ -235,19 +235,19 @@ static bool Parse(const Dictionary& constraints_dictionary,
return true;
}
-static bool Parse(const MediaTrackConstraints& constraints_in,
+static bool Parse(const MediaTrackConstraints* constraints_in,
Vector<NameValueStringConstraint>& optional,
Vector<NameValueStringConstraint>& mandatory) {
Vector<NameValueStringConstraint> mandatory_constraints_vector;
- if (constraints_in.hasMandatory()) {
- bool ok = ParseMandatoryConstraintsDictionary(constraints_in.mandatory(),
+ if (constraints_in->hasMandatory()) {
+ bool ok = ParseMandatoryConstraintsDictionary(constraints_in->mandatory(),
mandatory);
if (!ok)
return false;
}
- if (constraints_in.hasOptional()) {
- const Vector<Dictionary>& optional_constraints = constraints_in.optional();
+ if (constraints_in->hasOptional()) {
+ const Vector<Dictionary>& optional_constraints = constraints_in->optional();
for (const auto& constraint : optional_constraints) {
if (constraint.IsUndefinedOrNull())
@@ -509,18 +509,18 @@ void CopyLongConstraint(const LongOrConstrainLongRange& blink_union_form,
}
return;
}
- const auto& blink_form = blink_union_form.GetAsConstrainLongRange();
- if (blink_form.hasMin()) {
- web_form.SetMin(blink_form.min());
+ const auto* blink_form = blink_union_form.GetAsConstrainLongRange();
+ if (blink_form->hasMin()) {
+ web_form.SetMin(blink_form->min());
}
- if (blink_form.hasMax()) {
- web_form.SetMax(blink_form.max());
+ if (blink_form->hasMax()) {
+ web_form.SetMax(blink_form->max());
}
- if (blink_form.hasIdeal()) {
- web_form.SetIdeal(blink_form.ideal());
+ if (blink_form->hasIdeal()) {
+ web_form.SetIdeal(blink_form->ideal());
}
- if (blink_form.hasExact()) {
- web_form.SetExact(blink_form.exact());
+ if (blink_form->hasExact()) {
+ web_form.SetExact(blink_form->exact());
}
}
@@ -538,18 +538,18 @@ void CopyDoubleConstraint(const DoubleOrConstrainDoubleRange& blink_union_form,
}
return;
}
- const auto& blink_form = blink_union_form.GetAsConstrainDoubleRange();
- if (blink_form.hasMin()) {
- web_form.SetMin(blink_form.min());
+ auto* blink_form = blink_union_form.GetAsConstrainDoubleRange();
+ if (blink_form->hasMin()) {
+ web_form.SetMin(blink_form->min());
}
- if (blink_form.hasMax()) {
- web_form.SetMax(blink_form.max());
+ if (blink_form->hasMax()) {
+ web_form.SetMax(blink_form->max());
}
- if (blink_form.hasIdeal()) {
- web_form.SetIdeal(blink_form.ideal());
+ if (blink_form->hasIdeal()) {
+ web_form.SetIdeal(blink_form->ideal());
}
- if (blink_form.hasExact()) {
- web_form.SetExact(blink_form.exact());
+ if (blink_form->hasExact()) {
+ web_form.SetExact(blink_form->exact());
}
}
@@ -581,19 +581,19 @@ void CopyStringConstraint(
}
return;
}
- const auto& blink_form = blink_union_form.GetAsConstrainDOMStringParameters();
- if (blink_form.hasIdeal()) {
- if (blink_form.ideal().IsStringSequence()) {
- web_form.SetIdeal(blink_form.ideal().GetAsStringSequence());
- } else if (blink_form.ideal().IsString()) {
- web_form.SetIdeal(Vector<String>(1, blink_form.ideal().GetAsString()));
+ auto* blink_form = blink_union_form.GetAsConstrainDOMStringParameters();
+ if (blink_form->hasIdeal()) {
+ if (blink_form->ideal().IsStringSequence()) {
+ web_form.SetIdeal(blink_form->ideal().GetAsStringSequence());
+ } else if (blink_form->ideal().IsString()) {
+ web_form.SetIdeal(Vector<String>(1, blink_form->ideal().GetAsString()));
}
}
- if (blink_form.hasExact()) {
- if (blink_form.exact().IsStringSequence()) {
- web_form.SetExact(blink_form.exact().GetAsStringSequence());
- } else if (blink_form.exact().IsString()) {
- web_form.SetExact(Vector<String>(1, blink_form.exact().GetAsString()));
+ if (blink_form->hasExact()) {
+ if (blink_form->exact().IsStringSequence()) {
+ web_form.SetExact(blink_form->exact().GetAsStringSequence());
+ } else if (blink_form->exact().IsString()) {
+ web_form.SetExact(Vector<String>(1, blink_form->exact().GetAsString()));
}
}
}
@@ -613,113 +613,118 @@ void CopyBooleanConstraint(
}
return;
}
- const auto& blink_form = blink_union_form.GetAsConstrainBooleanParameters();
- if (blink_form.hasIdeal()) {
- web_form.SetIdeal(blink_form.ideal());
+ auto* blink_form = blink_union_form.GetAsConstrainBooleanParameters();
+ if (blink_form->hasIdeal()) {
+ web_form.SetIdeal(blink_form->ideal());
}
- if (blink_form.hasExact()) {
- web_form.SetExact(blink_form.exact());
+ if (blink_form->hasExact()) {
+ web_form.SetExact(blink_form->exact());
}
}
-void CopyConstraintSet(const MediaTrackConstraintSet& constraints_in,
+void CopyConstraintSet(const MediaTrackConstraintSet* constraints_in,
NakedValueDisposition naked_treatment,
WebMediaTrackConstraintSet& constraint_buffer) {
- if (constraints_in.hasWidth()) {
- CopyLongConstraint(constraints_in.width(), naked_treatment,
+ if (constraints_in->hasWidth()) {
+ CopyLongConstraint(constraints_in->width(), naked_treatment,
constraint_buffer.width);
}
- if (constraints_in.hasHeight()) {
- CopyLongConstraint(constraints_in.height(), naked_treatment,
+ if (constraints_in->hasHeight()) {
+ CopyLongConstraint(constraints_in->height(), naked_treatment,
constraint_buffer.height);
}
- if (constraints_in.hasAspectRatio()) {
- CopyDoubleConstraint(constraints_in.aspectRatio(), naked_treatment,
+ if (constraints_in->hasAspectRatio()) {
+ CopyDoubleConstraint(constraints_in->aspectRatio(), naked_treatment,
constraint_buffer.aspect_ratio);
}
- if (constraints_in.hasFrameRate()) {
- CopyDoubleConstraint(constraints_in.frameRate(), naked_treatment,
+ if (constraints_in->hasFrameRate()) {
+ CopyDoubleConstraint(constraints_in->frameRate(), naked_treatment,
constraint_buffer.frame_rate);
}
- if (constraints_in.hasFacingMode()) {
- CopyStringConstraint(constraints_in.facingMode(), naked_treatment,
+ if (constraints_in->hasFacingMode()) {
+ CopyStringConstraint(constraints_in->facingMode(), naked_treatment,
constraint_buffer.facing_mode);
}
- if (constraints_in.hasVolume()) {
- CopyDoubleConstraint(constraints_in.volume(), naked_treatment,
+ if (constraints_in->hasResizeMode()) {
+ CopyStringConstraint(constraints_in->resizeMode(), naked_treatment,
+ constraint_buffer.resize_mode);
+ }
+ if (constraints_in->hasVolume()) {
+ CopyDoubleConstraint(constraints_in->volume(), naked_treatment,
constraint_buffer.volume);
}
- if (constraints_in.hasSampleRate()) {
- CopyLongConstraint(constraints_in.sampleRate(), naked_treatment,
+ if (constraints_in->hasSampleRate()) {
+ CopyLongConstraint(constraints_in->sampleRate(), naked_treatment,
constraint_buffer.sample_rate);
}
- if (constraints_in.hasSampleSize()) {
- CopyLongConstraint(constraints_in.sampleSize(), naked_treatment,
+ if (constraints_in->hasSampleSize()) {
+ CopyLongConstraint(constraints_in->sampleSize(), naked_treatment,
constraint_buffer.sample_size);
}
- if (constraints_in.hasEchoCancellation()) {
- CopyBooleanConstraint(constraints_in.echoCancellation(), naked_treatment,
+ if (constraints_in->hasEchoCancellation()) {
+ CopyBooleanConstraint(constraints_in->echoCancellation(), naked_treatment,
constraint_buffer.echo_cancellation);
}
- if (constraints_in.hasEchoCancellationType()) {
- CopyStringConstraint(constraints_in.echoCancellationType(), naked_treatment,
+ if (constraints_in->hasEchoCancellationType()) {
+ CopyStringConstraint(constraints_in->echoCancellationType(),
+ naked_treatment,
constraint_buffer.echo_cancellation_type);
}
- if (constraints_in.hasAutoGainControl()) {
- CopyBooleanConstraint(constraints_in.autoGainControl(), naked_treatment,
+ if (constraints_in->hasAutoGainControl()) {
+ CopyBooleanConstraint(constraints_in->autoGainControl(), naked_treatment,
constraint_buffer.goog_auto_gain_control);
}
- if (constraints_in.hasNoiseSuppression()) {
- CopyBooleanConstraint(constraints_in.noiseSuppression(), naked_treatment,
+ if (constraints_in->hasNoiseSuppression()) {
+ CopyBooleanConstraint(constraints_in->noiseSuppression(), naked_treatment,
constraint_buffer.goog_noise_suppression);
}
- if (constraints_in.hasLatency()) {
- CopyDoubleConstraint(constraints_in.latency(), naked_treatment,
+ if (constraints_in->hasLatency()) {
+ CopyDoubleConstraint(constraints_in->latency(), naked_treatment,
constraint_buffer.latency);
}
- if (constraints_in.hasChannelCount()) {
- CopyLongConstraint(constraints_in.channelCount(), naked_treatment,
+ if (constraints_in->hasChannelCount()) {
+ CopyLongConstraint(constraints_in->channelCount(), naked_treatment,
constraint_buffer.channel_count);
}
- if (constraints_in.hasDeviceId()) {
- CopyStringConstraint(constraints_in.deviceId(), naked_treatment,
+ if (constraints_in->hasDeviceId()) {
+ CopyStringConstraint(constraints_in->deviceId(), naked_treatment,
constraint_buffer.device_id);
}
- if (constraints_in.hasGroupId()) {
- CopyStringConstraint(constraints_in.groupId(), naked_treatment,
+ if (constraints_in->hasGroupId()) {
+ CopyStringConstraint(constraints_in->groupId(), naked_treatment,
constraint_buffer.group_id);
}
- if (constraints_in.hasVideoKind()) {
- CopyStringConstraint(constraints_in.videoKind(), naked_treatment,
+ if (constraints_in->hasVideoKind()) {
+ CopyStringConstraint(constraints_in->videoKind(), naked_treatment,
constraint_buffer.video_kind);
}
- if (constraints_in.hasDepthNear()) {
- CopyDoubleConstraint(constraints_in.depthNear(), naked_treatment,
+ if (constraints_in->hasDepthNear()) {
+ CopyDoubleConstraint(constraints_in->depthNear(), naked_treatment,
constraint_buffer.depth_near);
}
- if (constraints_in.hasDepthFar()) {
- CopyDoubleConstraint(constraints_in.depthFar(), naked_treatment,
+ if (constraints_in->hasDepthFar()) {
+ CopyDoubleConstraint(constraints_in->depthFar(), naked_treatment,
constraint_buffer.depth_far);
}
- if (constraints_in.hasFocalLengthX()) {
- CopyDoubleConstraint(constraints_in.focalLengthX(), naked_treatment,
+ if (constraints_in->hasFocalLengthX()) {
+ CopyDoubleConstraint(constraints_in->focalLengthX(), naked_treatment,
constraint_buffer.focal_length_x);
}
- if (constraints_in.hasFocalLengthY()) {
- CopyDoubleConstraint(constraints_in.focalLengthY(), naked_treatment,
+ if (constraints_in->hasFocalLengthY()) {
+ CopyDoubleConstraint(constraints_in->focalLengthY(), naked_treatment,
constraint_buffer.focal_length_y);
}
}
WebMediaConstraints ConvertConstraintsToWeb(
- const MediaTrackConstraints& constraints_in) {
+ const MediaTrackConstraints* constraints_in) {
WebMediaConstraints constraints;
WebMediaTrackConstraintSet constraint_buffer;
Vector<WebMediaTrackConstraintSet> advanced_buffer;
CopyConstraintSet(constraints_in, NakedValueDisposition::kTreatAsIdeal,
constraint_buffer);
- if (constraints_in.hasAdvanced()) {
- for (const auto& element : constraints_in.advanced()) {
+ if (constraints_in->hasAdvanced()) {
+ for (const auto& element : constraints_in->advanced()) {
WebMediaTrackConstraintSet advanced_element;
CopyConstraintSet(element, NakedValueDisposition::kTreatAsExact,
advanced_element);
@@ -731,10 +736,10 @@ WebMediaConstraints ConvertConstraintsToWeb(
}
WebMediaConstraints Create(ExecutionContext* context,
- const MediaTrackConstraints& constraints_in,
+ const MediaTrackConstraints* constraints_in,
MediaErrorState& error_state) {
WebMediaConstraints standard_form = ConvertConstraintsToWeb(constraints_in);
- if (constraints_in.hasOptional() || constraints_in.hasMandatory()) {
+ if (constraints_in->hasOptional() || constraints_in->hasMandatory()) {
if (!standard_form.IsEmpty()) {
UseCounter::Count(context, WebFeature::kMediaStreamConstraintsOldAndNew);
error_state.ThrowTypeError(
@@ -812,15 +817,15 @@ LongOrConstrainLongRange ConvertLong(const LongConstraint& input,
if (UseNakedNumeric(input, naked_treatment)) {
output_union.SetLong(GetNakedValue<uint32_t>(input, naked_treatment));
} else if (!input.IsEmpty()) {
- ConstrainLongRange output;
+ ConstrainLongRange* output = ConstrainLongRange::Create();
if (input.HasExact())
- output.setExact(input.Exact());
+ output->setExact(input.Exact());
if (input.HasMin())
- output.setMin(input.Min());
+ output->setMin(input.Min());
if (input.HasMax())
- output.setMax(input.Max());
+ output->setMax(input.Max());
if (input.HasIdeal())
- output.setIdeal(input.Ideal());
+ output->setIdeal(input.Ideal());
output_union.SetConstrainLongRange(output);
}
return output_union;
@@ -833,15 +838,15 @@ DoubleOrConstrainDoubleRange ConvertDouble(
if (UseNakedNumeric(input, naked_treatment)) {
output_union.SetDouble(GetNakedValue<double>(input, naked_treatment));
} else if (!input.IsEmpty()) {
- ConstrainDoubleRange output;
+ ConstrainDoubleRange* output = ConstrainDoubleRange::Create();
if (input.HasExact())
- output.setExact(input.Exact());
+ output->setExact(input.Exact());
if (input.HasIdeal())
- output.setIdeal(input.Ideal());
+ output->setIdeal(input.Ideal());
if (input.HasMin())
- output.setMin(input.Min());
+ output->setMin(input.Min());
if (input.HasMax())
- output.setMax(input.Max());
+ output->setMax(input.Max());
output_union.SetConstrainDoubleRange(output);
}
return output_union;
@@ -877,11 +882,12 @@ StringOrStringSequenceOrConstrainDOMStringParameters ConvertString(
output_union.SetString(input_buffer[0]);
}
} else if (!input.IsEmpty()) {
- ConstrainDOMStringParameters output;
+ ConstrainDOMStringParameters* output =
+ ConstrainDOMStringParameters::Create();
if (input.HasExact())
- output.setExact(ConvertStringSequence(input.Exact()));
+ output->setExact(ConvertStringSequence(input.Exact()));
if (input.HasIdeal())
- output.setIdeal(ConvertStringSequence(input.Ideal()));
+ output->setIdeal(ConvertStringSequence(input.Ideal()));
output_union.SetConstrainDOMStringParameters(output);
}
return output_union;
@@ -894,11 +900,11 @@ BooleanOrConstrainBooleanParameters ConvertBoolean(
if (UseNakedNonNumeric(input, naked_treatment)) {
output_union.SetBoolean(GetNakedValue<bool>(input, naked_treatment));
} else if (!input.IsEmpty()) {
- ConstrainBooleanParameters output;
+ ConstrainBooleanParameters* output = ConstrainBooleanParameters::Create();
if (input.HasExact())
- output.setExact(input.Exact());
+ output->setExact(input.Exact());
if (input.HasIdeal())
- output.setIdeal(input.Ideal());
+ output->setIdeal(input.Ideal());
output_union.SetConstrainBooleanParameters(output);
}
return output_union;
@@ -906,65 +912,70 @@ BooleanOrConstrainBooleanParameters ConvertBoolean(
void ConvertConstraintSet(const WebMediaTrackConstraintSet& input,
NakedValueDisposition naked_treatment,
- MediaTrackConstraintSet& output) {
+ MediaTrackConstraintSet* output) {
if (!input.width.IsEmpty())
- output.setWidth(ConvertLong(input.width, naked_treatment));
+ output->setWidth(ConvertLong(input.width, naked_treatment));
if (!input.height.IsEmpty())
- output.setHeight(ConvertLong(input.height, naked_treatment));
+ output->setHeight(ConvertLong(input.height, naked_treatment));
if (!input.aspect_ratio.IsEmpty())
- output.setAspectRatio(ConvertDouble(input.aspect_ratio, naked_treatment));
+ output->setAspectRatio(ConvertDouble(input.aspect_ratio, naked_treatment));
if (!input.frame_rate.IsEmpty())
- output.setFrameRate(ConvertDouble(input.frame_rate, naked_treatment));
+ output->setFrameRate(ConvertDouble(input.frame_rate, naked_treatment));
if (!input.facing_mode.IsEmpty())
- output.setFacingMode(ConvertString(input.facing_mode, naked_treatment));
+ output->setFacingMode(ConvertString(input.facing_mode, naked_treatment));
+ if (!input.resize_mode.IsEmpty())
+ output->setResizeMode(ConvertString(input.resize_mode, naked_treatment));
if (!input.volume.IsEmpty())
- output.setVolume(ConvertDouble(input.volume, naked_treatment));
+ output->setVolume(ConvertDouble(input.volume, naked_treatment));
if (!input.sample_rate.IsEmpty())
- output.setSampleRate(ConvertLong(input.sample_rate, naked_treatment));
+ output->setSampleRate(ConvertLong(input.sample_rate, naked_treatment));
if (!input.sample_size.IsEmpty())
- output.setSampleSize(ConvertLong(input.sample_size, naked_treatment));
+ output->setSampleSize(ConvertLong(input.sample_size, naked_treatment));
if (!input.echo_cancellation.IsEmpty()) {
- output.setEchoCancellation(
+ output->setEchoCancellation(
ConvertBoolean(input.echo_cancellation, naked_treatment));
}
if (!input.goog_auto_gain_control.IsEmpty()) {
- output.setAutoGainControl(
+ output->setAutoGainControl(
ConvertBoolean(input.goog_auto_gain_control, naked_treatment));
}
if (!input.goog_noise_suppression.IsEmpty()) {
- output.setNoiseSuppression(
+ output->setNoiseSuppression(
ConvertBoolean(input.goog_noise_suppression, naked_treatment));
}
if (!input.latency.IsEmpty())
- output.setLatency(ConvertDouble(input.latency, naked_treatment));
+ output->setLatency(ConvertDouble(input.latency, naked_treatment));
if (!input.channel_count.IsEmpty())
- output.setChannelCount(ConvertLong(input.channel_count, naked_treatment));
+ output->setChannelCount(ConvertLong(input.channel_count, naked_treatment));
if (!input.device_id.IsEmpty())
- output.setDeviceId(ConvertString(input.device_id, naked_treatment));
+ output->setDeviceId(ConvertString(input.device_id, naked_treatment));
if (!input.group_id.IsEmpty())
- output.setGroupId(ConvertString(input.group_id, naked_treatment));
+ output->setGroupId(ConvertString(input.group_id, naked_treatment));
if (!input.video_kind.IsEmpty())
- output.setVideoKind(ConvertString(input.video_kind, naked_treatment));
+ output->setVideoKind(ConvertString(input.video_kind, naked_treatment));
// TODO(hta): Decide the future of the nonstandard constraints.
// If they go forward, they need to be added here.
// https://crbug.com/605673
}
-void ConvertConstraints(const WebMediaConstraints& input,
- MediaTrackConstraints& output) {
+MediaTrackConstraints* ConvertConstraints(const WebMediaConstraints& input) {
+ MediaTrackConstraints* output = MediaTrackConstraints::Create();
if (input.IsNull())
- return;
+ return output;
ConvertConstraintSet(input.Basic(), NakedValueDisposition::kTreatAsIdeal,
output);
- HeapVector<MediaTrackConstraintSet> advanced_vector;
+
+ HeapVector<Member<MediaTrackConstraintSet>> advanced_vector;
for (const auto& it : input.Advanced()) {
- MediaTrackConstraintSet element;
+ MediaTrackConstraintSet* element = MediaTrackConstraintSet::Create();
ConvertConstraintSet(it, NakedValueDisposition::kTreatAsExact, element);
advanced_vector.push_back(element);
}
if (!advanced_vector.IsEmpty())
- output.setAdvanced(advanced_vector);
+ output->setAdvanced(advanced_vector);
+
+ return output;
}
-} // namespace MediaConstraintsImpl
+} // namespace media_constraints_impl
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.h b/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.h
index 69f66c2d8c2..d5579338879 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_impl.h
@@ -42,22 +42,23 @@ class Dictionary;
class ExecutionContext;
class MediaTrackConstraints;
-namespace MediaConstraintsImpl {
+namespace media_constraints_impl {
WebMediaConstraints Create();
WebMediaConstraints Create(ExecutionContext*,
const Dictionary&,
MediaErrorState&);
WebMediaConstraints Create(ExecutionContext*,
- const MediaTrackConstraints&,
+ const MediaTrackConstraints*,
MediaErrorState&);
// Exported with MODULES_EXPORT for testing
-MODULES_EXPORT void ConvertConstraints(const WebMediaConstraints& input,
- MediaTrackConstraints& output);
+MODULES_EXPORT MediaTrackConstraints* ConvertConstraints(
+ const WebMediaConstraints& input);
+
// Exported for testing only.
MODULES_EXPORT WebMediaConstraints
-ConvertConstraintsToWeb(const MediaTrackConstraints&);
+ConvertConstraintsToWeb(const MediaTrackConstraints*);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_test.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_test.cc
index 30a10042db2..02c573a3c0d 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_test.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_constraints_test.cc
@@ -120,29 +120,28 @@ TEST(MediaTrackConstraintsTest, ConstraintsToString) {
TEST(MediaTrackConstraintsTest, ConvertWebConstraintsBasic) {
WebMediaConstraints input;
- MediaTrackConstraints output;
-
- MediaConstraintsImpl::ConvertConstraints(input, output);
+ MediaTrackConstraints* output =
+ media_constraints_impl::ConvertConstraints(input);
+ ALLOW_UNUSED_LOCAL(output);
}
TEST(MediaTrackConstraintsTest, ConvertWebSingleStringConstraint) {
WebMediaConstraints input;
- MediaTrackConstraints output;
WebMediaTrackConstraintSet basic;
WebVector<WebMediaTrackConstraintSet> advanced;
basic.facing_mode.SetIdeal(WebVector<WebString>(&"foo", 1));
input.Initialize(basic, advanced);
- MediaConstraintsImpl::ConvertConstraints(input, output);
- ASSERT_TRUE(output.hasFacingMode());
- ASSERT_TRUE(output.facingMode().IsString());
- EXPECT_EQ("foo", output.facingMode().GetAsString());
+ MediaTrackConstraints* output =
+ media_constraints_impl::ConvertConstraints(input);
+ ASSERT_TRUE(output->hasFacingMode());
+ ASSERT_TRUE(output->facingMode().IsString());
+ EXPECT_EQ("foo", output->facingMode().GetAsString());
}
TEST(MediaTrackConstraintsTest, ConvertWebDoubleStringConstraint) {
WebMediaConstraints input;
- MediaTrackConstraints output;
WebVector<WebString> buffer(static_cast<size_t>(2u));
buffer[0] = "foo";
@@ -152,60 +151,64 @@ TEST(MediaTrackConstraintsTest, ConvertWebDoubleStringConstraint) {
std::vector<WebMediaTrackConstraintSet> advanced;
basic.facing_mode.SetIdeal(buffer);
input.Initialize(basic, advanced);
- MediaConstraintsImpl::ConvertConstraints(input, output);
- ASSERT_TRUE(output.hasFacingMode());
- ASSERT_TRUE(output.facingMode().IsStringSequence());
- auto out_buffer = output.facingMode().GetAsStringSequence();
+
+ MediaTrackConstraints* output =
+ media_constraints_impl::ConvertConstraints(input);
+ ASSERT_TRUE(output->hasFacingMode());
+ ASSERT_TRUE(output->facingMode().IsStringSequence());
+ auto out_buffer = output->facingMode().GetAsStringSequence();
EXPECT_EQ("foo", out_buffer[0]);
EXPECT_EQ("bar", out_buffer[1]);
}
TEST(MediaTrackConstraintsTest, ConvertBlinkStringConstraint) {
- MediaTrackConstraints input;
+ MediaTrackConstraints* input = MediaTrackConstraints::Create();
WebMediaConstraints output;
StringOrStringSequenceOrConstrainDOMStringParameters parameter;
parameter.SetString("foo");
- input.setFacingMode(parameter);
- output = MediaConstraintsImpl::ConvertConstraintsToWeb(input);
+ input->setFacingMode(parameter);
+ output = media_constraints_impl::ConvertConstraintsToWeb(input);
ASSERT_TRUE(output.Basic().facing_mode.HasIdeal());
ASSERT_EQ(1U, output.Basic().facing_mode.Ideal().size());
ASSERT_EQ("foo", output.Basic().facing_mode.Ideal()[0]);
}
TEST(MediaTrackConstraintsTest, ConvertBlinkComplexStringConstraint) {
- MediaTrackConstraints input;
+ MediaTrackConstraints* input = MediaTrackConstraints::Create();
WebMediaConstraints output;
StringOrStringSequenceOrConstrainDOMStringParameters parameter;
- ConstrainDOMStringParameters subparameter;
+ ConstrainDOMStringParameters* subparameter =
+ ConstrainDOMStringParameters::Create();
StringOrStringSequence inner_string;
inner_string.SetString("foo");
- subparameter.setIdeal(inner_string);
+ subparameter->setIdeal(inner_string);
parameter.SetConstrainDOMStringParameters(subparameter);
- input.setFacingMode(parameter);
- output = MediaConstraintsImpl::ConvertConstraintsToWeb(input);
+ input->setFacingMode(parameter);
+ output = media_constraints_impl::ConvertConstraintsToWeb(input);
ASSERT_TRUE(output.Basic().facing_mode.HasIdeal());
ASSERT_EQ(1U, output.Basic().facing_mode.Ideal().size());
ASSERT_EQ("foo", output.Basic().facing_mode.Ideal()[0]);
// Convert this back, and see that it appears as a single string.
- MediaTrackConstraints recycled;
- MediaConstraintsImpl::ConvertConstraints(output, recycled);
- ASSERT_TRUE(recycled.hasFacingMode());
- ASSERT_TRUE(recycled.facingMode().IsString());
- ASSERT_EQ("foo", recycled.facingMode().GetAsString());
+ MediaTrackConstraints* recycled =
+ media_constraints_impl::ConvertConstraints(output);
+ ASSERT_TRUE(recycled->hasFacingMode());
+ ASSERT_TRUE(recycled->facingMode().IsString());
+ ASSERT_EQ("foo", recycled->facingMode().GetAsString());
}
TEST(MediaTrackConstraintsTest, NakedIsExactInAdvanced) {
- MediaTrackConstraints input;
- WebMediaConstraints output;
+ MediaTrackConstraints* input = MediaTrackConstraints::Create();
StringOrStringSequenceOrConstrainDOMStringParameters parameter;
parameter.SetString("foo");
- input.setFacingMode(parameter);
- HeapVector<MediaTrackConstraintSet> advanced(1);
- advanced[0].setFacingMode(parameter);
- input.setAdvanced(advanced);
- output = MediaConstraintsImpl::ConvertConstraintsToWeb(input);
-
+ input->setFacingMode(parameter);
+ HeapVector<Member<MediaTrackConstraintSet>> advanced(
+ 1, MediaTrackConstraintSet::Create());
+ advanced[0]->setFacingMode(parameter);
+ input->setAdvanced(advanced);
+
+ WebMediaConstraints output =
+ media_constraints_impl::ConvertConstraintsToWeb(input);
ASSERT_TRUE(output.Basic().facing_mode.HasIdeal());
ASSERT_FALSE(output.Basic().facing_mode.HasExact());
ASSERT_EQ(1U, output.Basic().facing_mode.Ideal().size());
@@ -219,8 +222,6 @@ TEST(MediaTrackConstraintsTest, NakedIsExactInAdvanced) {
TEST(MediaTrackConstraintsTest, IdealAndExactConvertToNaked) {
WebMediaConstraints input;
- MediaTrackConstraints output;
-
WebVector<WebString> buffer(static_cast<size_t>(1u));
WebMediaTrackConstraintSet basic;
@@ -235,30 +236,32 @@ TEST(MediaTrackConstraintsTest, IdealAndExactConvertToNaked) {
advanced.push_back(advanced_element1);
advanced.push_back(advanced_element2);
input.Initialize(basic, advanced);
- MediaConstraintsImpl::ConvertConstraints(input, output);
+
+ MediaTrackConstraints* output =
+ media_constraints_impl::ConvertConstraints(input);
// The first element should return a ConstrainDOMStringParameters
// with an "ideal" value containing a String value of "ideal".
// The second element should return a ConstrainDOMStringParameters
// with a String value of "exact".
- ASSERT_TRUE(output.hasAdvanced());
- ASSERT_EQ(2U, output.advanced().size());
- MediaTrackConstraintSet element1 = output.advanced()[0];
- MediaTrackConstraintSet element2 = output.advanced()[1];
-
- ASSERT_TRUE(output.hasFacingMode());
- ASSERT_TRUE(output.facingMode().IsString());
- EXPECT_EQ("ideal", output.facingMode().GetAsString());
-
- ASSERT_TRUE(element1.hasFacingMode());
- ASSERT_TRUE(element1.facingMode().IsConstrainDOMStringParameters());
- EXPECT_EQ("ideal", element1.facingMode()
+ ASSERT_TRUE(output->hasAdvanced());
+ ASSERT_EQ(2U, output->advanced().size());
+ MediaTrackConstraintSet* element1 = output->advanced()[0];
+ MediaTrackConstraintSet* element2 = output->advanced()[1];
+
+ ASSERT_TRUE(output->hasFacingMode());
+ ASSERT_TRUE(output->facingMode().IsString());
+ EXPECT_EQ("ideal", output->facingMode().GetAsString());
+
+ ASSERT_TRUE(element1->hasFacingMode());
+ ASSERT_TRUE(element1->facingMode().IsConstrainDOMStringParameters());
+ EXPECT_EQ("ideal", element1->facingMode()
.GetAsConstrainDOMStringParameters()
- .ideal()
+ ->ideal()
.GetAsString());
- ASSERT_TRUE(element2.hasFacingMode());
- ASSERT_TRUE(element2.facingMode().IsString());
- EXPECT_EQ("exact", element2.facingMode().GetAsString());
+ ASSERT_TRUE(element2->hasFacingMode());
+ ASSERT_TRUE(element2->facingMode().IsString());
+ EXPECT_EQ("exact", element2->facingMode().GetAsString());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.cc
index c211391001a..325477ccb9e 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.cc
@@ -35,7 +35,8 @@ MediaDeviceInfo* MediaDeviceInfo::Create(const String& device_id,
const String& label,
const String& group_id,
MediaDeviceType device_type) {
- return new MediaDeviceInfo(device_id, label, group_id, device_type);
+ return MakeGarbageCollected<MediaDeviceInfo>(device_id, label, group_id,
+ device_type);
}
MediaDeviceInfo::MediaDeviceInfo(const String& device_id,
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.h b/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.h
index f93d6e7a63e..737a37b4846 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_device_info.h
@@ -48,6 +48,11 @@ class MODULES_EXPORT MediaDeviceInfo : public ScriptWrappable {
const String& group_id,
MediaDeviceType);
+ MediaDeviceInfo(const String& device_id,
+ const String& label,
+ const String& group_id,
+ MediaDeviceType);
+
String deviceId() const;
String kind() const;
String label() const;
@@ -57,12 +62,6 @@ class MODULES_EXPORT MediaDeviceInfo : public ScriptWrappable {
ScriptValue toJSONForBinding(ScriptState*);
- protected:
- MediaDeviceInfo(const String& device_id,
- const String& label,
- const String& group_id,
- MediaDeviceType);
-
private:
String device_id_;
String label_;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_devices.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_devices.cc
index 19ccd3104c1..7d099e57634 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_devices.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_devices.cc
@@ -18,6 +18,7 @@
#include "third_party/blink/renderer/modules/mediastream/media_error_state.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream_constraints.h"
+#include "third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.h"
#include "third_party/blink/renderer/modules/mediastream/navigator_media_stream.h"
#include "third_party/blink/renderer/modules/mediastream/user_media_controller.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
@@ -61,7 +62,7 @@ class PromiseResolverCallbacks final : public UserMediaRequest::Callbacks {
} // namespace
MediaDevices* MediaDevices::Create(ExecutionContext* context) {
- MediaDevices* media_devices = new MediaDevices(context);
+ MediaDevices* media_devices = MakeGarbageCollected<MediaDevices>(context);
media_devices->PauseIfNeeded();
return media_devices;
}
@@ -101,8 +102,12 @@ ScriptPromise MediaDevices::enumerateDevices(ScriptState* script_state) {
return promise;
}
+MediaTrackSupportedConstraints* MediaDevices::getSupportedConstraints() const {
+ return MediaTrackSupportedConstraints::Create();
+}
+
ScriptPromise MediaDevices::getUserMedia(ScriptState* script_state,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
ExceptionState& exception_state) {
return SendUserMediaRequest(script_state,
WebUserMediaRequest::MediaType::kUserMedia,
@@ -112,7 +117,7 @@ ScriptPromise MediaDevices::getUserMedia(ScriptState* script_state,
ScriptPromise MediaDevices::SendUserMediaRequest(
ScriptState* script_state,
WebUserMediaRequest::MediaType media_type,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
ExceptionState& exception_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
PromiseResolverCallbacks* callbacks =
@@ -153,8 +158,17 @@ ScriptPromise MediaDevices::SendUserMediaRequest(
return promise;
}
+ScriptPromise MediaDevices::getDisplayMedia(
+ ScriptState* script_state,
+ const MediaStreamConstraints* options,
+ ExceptionState& exception_state) {
+ return SendUserMediaRequest(script_state,
+ WebUserMediaRequest::MediaType::kDisplayMedia,
+ options, exception_state);
+}
+
const AtomicString& MediaDevices::InterfaceName() const {
- return EventTargetNames::MediaDevices;
+ return event_target_names::kMediaDevices;
}
ExecutionContext* MediaDevices::GetExecutionContext() const {
@@ -216,7 +230,7 @@ void MediaDevices::OnDevicesChanged(
DCHECK(document);
if (RuntimeEnabledFeatures::OnDeviceChangeEnabled())
- ScheduleDispatchEvent(Event::Create(EventTypeNames::devicechange));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kDevicechange));
if (device_change_test_callback_)
std::move(device_change_test_callback_).Run();
@@ -277,20 +291,21 @@ void MediaDevices::DevicesEnumerated(
return;
}
- DCHECK_EQ(static_cast<size_t>(MediaDeviceType::NUM_MEDIA_DEVICE_TYPES),
+ DCHECK_EQ(static_cast<wtf_size_t>(MediaDeviceType::NUM_MEDIA_DEVICE_TYPES),
enumeration.size());
if (!video_input_capabilities.IsEmpty()) {
DCHECK_EQ(
- enumeration[static_cast<size_t>(MediaDeviceType::MEDIA_VIDEO_INPUT)]
+ enumeration[static_cast<wtf_size_t>(MediaDeviceType::MEDIA_VIDEO_INPUT)]
.size(),
video_input_capabilities.size());
}
MediaDeviceInfoVector media_devices;
- for (size_t i = 0;
- i < static_cast<size_t>(MediaDeviceType::NUM_MEDIA_DEVICE_TYPES); ++i) {
- for (size_t j = 0; j < enumeration[i].size(); ++j) {
+ for (wtf_size_t i = 0;
+ i < static_cast<wtf_size_t>(MediaDeviceType::NUM_MEDIA_DEVICE_TYPES);
+ ++i) {
+ for (wtf_size_t j = 0; j < enumeration[i].size(); ++j) {
MediaDeviceType device_type = static_cast<MediaDeviceType>(i);
mojom::blink::MediaDeviceInfoPtr device_info =
std::move(enumeration[i][j]);
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_devices.h b/chromium/third_party/blink/renderer/modules/mediastream/media_devices.h
index b8a99e5e3d6..563cf4a174e 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_devices.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_devices.h
@@ -38,18 +38,24 @@ class MODULES_EXPORT MediaDevices final
public:
static MediaDevices* Create(ExecutionContext*);
+
+ explicit MediaDevices(ExecutionContext*);
~MediaDevices() override;
ScriptPromise enumerateDevices(ScriptState*);
- void getSupportedConstraints(MediaTrackSupportedConstraints& result) {}
+ MediaTrackSupportedConstraints* getSupportedConstraints() const;
ScriptPromise getUserMedia(ScriptState*,
- const MediaStreamConstraints&,
+ const MediaStreamConstraints*,
ExceptionState&);
ScriptPromise SendUserMediaRequest(ScriptState*,
WebUserMediaRequest::MediaType,
- const MediaStreamConstraints&,
+ const MediaStreamConstraints*,
ExceptionState&);
+ ScriptPromise getDisplayMedia(ScriptState*,
+ const MediaStreamConstraints*,
+ ExceptionState&);
+
// EventTarget overrides.
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
@@ -88,7 +94,7 @@ class MODULES_EXPORT MediaDevices final
void Trace(blink::Visitor*) override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(devicechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(devicechange, kDevicechange);
protected:
// EventTarget overrides.
@@ -99,7 +105,6 @@ class MODULES_EXPORT MediaDevices final
private:
FRIEND_TEST_ALL_PREFIXES(MediaDevicesTest, ObserveDeviceChangeEvent);
- explicit MediaDevices(ExecutionContext*);
void ScheduleDispatchEvent(Event*);
void DispatchScheduledEvent();
void StartObserving();
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_devices.idl b/chromium/third_party/blink/renderer/modules/mediastream/media_devices.idl
index c37a6b2ad35..8e803c593b4 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_devices.idl
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_devices.idl
@@ -10,10 +10,18 @@
ActiveScriptWrappable
] interface MediaDevices : EventTarget {
[RuntimeEnabled=OnDeviceChange] attribute EventHandler ondevicechange;
- [CallWith=ScriptState, MeasureAs=MediaDevicesEnumerateDevices] Promise<sequence<MediaDeviceInfo>> enumerateDevices();
+ [
+ CallWith = ScriptState, MeasureAs = MediaDevicesEnumerateDevices
+ ] Promise<sequence<MediaDeviceInfo>>
+ enumerateDevices();
MediaTrackSupportedConstraints getSupportedConstraints();
- [CallWith=ScriptState,
- RaisesException,
- MeasureAs=GetUserMediaPromise
- ] Promise<MediaStream> getUserMedia(optional MediaStreamConstraints constraints);
+ [
+ CallWith = ScriptState, RaisesException, MeasureAs = GetUserMediaPromise
+ ] Promise<MediaStream>
+ getUserMedia(optional MediaStreamConstraints constraints);
+ [
+ RuntimeEnabled = GetDisplayMedia, CallWith = ScriptState, RaisesException,
+ MeasureAs = GetDisplayMedia
+ ] Promise<MediaStream>
+ getDisplayMedia(optional MediaStreamConstraints constraints);
};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_devices_test.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_devices_test.cc
index daf9d684dd3..57fa3037edc 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_devices_test.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_devices_test.cc
@@ -170,12 +170,11 @@ class PromiseObserver {
static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
bool* flag_to_set,
ScriptValue* arg_to_set) {
- MyScriptFunction* self =
- new MyScriptFunction(script_state, flag_to_set, arg_to_set);
+ MyScriptFunction* self = MakeGarbageCollected<MyScriptFunction>(
+ script_state, flag_to_set, arg_to_set);
return self->BindToV8Function();
}
- private:
MyScriptFunction(ScriptState* script_state,
bool* flag_to_set,
ScriptValue* arg_to_set)
@@ -187,6 +186,8 @@ class PromiseObserver {
*arg_to_set_ = arg;
return arg;
}
+
+ private:
bool* flag_to_set_;
ScriptValue* arg_to_set_;
};
@@ -200,7 +201,7 @@ class MediaDevicesTest : public testing::Test {
public:
using MediaDeviceInfos = HeapVector<Member<MediaDeviceInfo>>;
- MediaDevicesTest() : device_infos_(new MediaDeviceInfos) {
+ MediaDevicesTest() : device_infos_(MakeGarbageCollected<MediaDeviceInfos>()) {
dispatcher_host_ = std::make_unique<MockMediaDevicesDispatcherHost>();
}
@@ -223,7 +224,7 @@ class MediaDevicesTest : public testing::Test {
void DevicesEnumerated(const MediaDeviceInfoVector& device_infos) {
devices_enumerated_ = true;
- for (size_t i = 0; i < device_infos.size(); i++) {
+ for (wtf_size_t i = 0; i < device_infos.size(); i++) {
device_infos_->push_back(MediaDeviceInfo::Create(
device_infos[i]->deviceId(), device_infos[i]->label(),
device_infos[i]->groupId(), device_infos[i]->DeviceType()));
@@ -274,7 +275,7 @@ class MediaDevicesTest : public testing::Test {
TEST_F(MediaDevicesTest, GetUserMediaCanBeCalled) {
V8TestingScope scope;
- MediaStreamConstraints constraints;
+ MediaStreamConstraints* constraints = MediaStreamConstraints::Create();
ScriptPromise promise =
GetMediaDevices(scope.GetExecutionContext())
->getUserMedia(scope.GetScriptState(), constraints,
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_stream.cc
index feef966d923..2296ede22fe 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream.cc
@@ -28,7 +28,6 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
-#include "third_party/blink/renderer/modules/mediastream/media_stream_registry.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream_track_event.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
@@ -39,8 +38,8 @@ namespace blink {
static bool ContainsSource(MediaStreamTrackVector& track_vector,
MediaStreamSource* source) {
- for (size_t i = 0; i < track_vector.size(); ++i) {
- if (source->Id() == track_vector[i]->Component()->Source()->Id())
+ for (MediaStreamTrack* track : track_vector) {
+ if (source->Id() == track->Component()->Source()->Id())
return true;
}
return false;
@@ -57,7 +56,7 @@ MediaStream* MediaStream::Create(ExecutionContext* context) {
MediaStreamTrackVector audio_tracks;
MediaStreamTrackVector video_tracks;
- return new MediaStream(context, audio_tracks, video_tracks);
+ return MakeGarbageCollected<MediaStream>(context, audio_tracks, video_tracks);
}
MediaStream* MediaStream::Create(ExecutionContext* context,
@@ -67,13 +66,13 @@ MediaStream* MediaStream::Create(ExecutionContext* context,
MediaStreamTrackVector audio_tracks;
MediaStreamTrackVector video_tracks;
- for (size_t i = 0; i < stream->audio_tracks_.size(); ++i)
- ProcessTrack(stream->audio_tracks_[i].Get(), audio_tracks);
+ for (MediaStreamTrack* track : stream->audio_tracks_)
+ ProcessTrack(track, audio_tracks);
- for (size_t i = 0; i < stream->video_tracks_.size(); ++i)
- ProcessTrack(stream->video_tracks_[i].Get(), video_tracks);
+ for (MediaStreamTrack* track : stream->video_tracks_)
+ ProcessTrack(track, video_tracks);
- return new MediaStream(context, audio_tracks, video_tracks);
+ return MakeGarbageCollected<MediaStream>(context, audio_tracks, video_tracks);
}
MediaStream* MediaStream::Create(ExecutionContext* context,
@@ -81,24 +80,24 @@ MediaStream* MediaStream::Create(ExecutionContext* context,
MediaStreamTrackVector audio_tracks;
MediaStreamTrackVector video_tracks;
- for (size_t i = 0; i < tracks.size(); ++i)
- ProcessTrack(tracks[i].Get(),
- tracks[i]->kind() == "audio" ? audio_tracks : video_tracks);
+ for (MediaStreamTrack* track : tracks) {
+ ProcessTrack(track, track->kind() == "audio" ? audio_tracks : video_tracks);
+ }
- return new MediaStream(context, audio_tracks, video_tracks);
+ return MakeGarbageCollected<MediaStream>(context, audio_tracks, video_tracks);
}
MediaStream* MediaStream::Create(ExecutionContext* context,
MediaStreamDescriptor* stream_descriptor) {
- return new MediaStream(context, stream_descriptor);
+ return MakeGarbageCollected<MediaStream>(context, stream_descriptor);
}
MediaStream* MediaStream::Create(ExecutionContext* context,
MediaStreamDescriptor* stream_descriptor,
const MediaStreamTrackVector& audio_tracks,
const MediaStreamTrackVector& video_tracks) {
- return new MediaStream(context, stream_descriptor, audio_tracks,
- video_tracks);
+ return MakeGarbageCollected<MediaStream>(context, stream_descriptor,
+ audio_tracks, video_tracks);
}
MediaStream::MediaStream(ExecutionContext* context,
@@ -111,18 +110,18 @@ MediaStream::MediaStream(ExecutionContext* context,
&MediaStream::ScheduledEventTimerFired) {
descriptor_->SetClient(this);
- size_t number_of_audio_tracks = descriptor_->NumberOfAudioComponents();
+ uint32_t number_of_audio_tracks = descriptor_->NumberOfAudioComponents();
audio_tracks_.ReserveCapacity(number_of_audio_tracks);
- for (size_t i = 0; i < number_of_audio_tracks; i++) {
+ for (uint32_t i = 0; i < number_of_audio_tracks; i++) {
MediaStreamTrack* new_track =
MediaStreamTrack::Create(context, descriptor_->AudioComponent(i));
new_track->RegisterMediaStream(this);
audio_tracks_.push_back(new_track);
}
- size_t number_of_video_tracks = descriptor_->NumberOfVideoComponents();
+ uint32_t number_of_video_tracks = descriptor_->NumberOfVideoComponents();
video_tracks_.ReserveCapacity(number_of_video_tracks);
- for (size_t i = 0; i < number_of_video_tracks; i++) {
+ for (uint32_t i = 0; i < number_of_video_tracks; i++) {
MediaStreamTrack* new_track =
MediaStreamTrack::Create(context, descriptor_->VideoComponent(i));
new_track->RegisterMediaStream(this);
@@ -147,15 +146,13 @@ MediaStream::MediaStream(ExecutionContext* context,
descriptor_->SetClient(this);
audio_tracks_.ReserveCapacity(audio_tracks.size());
- for (size_t i = 0; i < audio_tracks.size(); ++i) {
- MediaStreamTrack* audio_track = audio_tracks[i];
+ for (MediaStreamTrack* audio_track : audio_tracks) {
DCHECK_EQ("audio", audio_track->kind());
audio_track->RegisterMediaStream(this);
audio_tracks_.push_back(audio_track);
}
video_tracks_.ReserveCapacity(video_tracks.size());
- for (size_t i = 0; i < video_tracks.size(); ++i) {
- MediaStreamTrack* video_track = video_tracks[i];
+ for (MediaStreamTrack* video_track : video_tracks) {
DCHECK_EQ("video", video_track->kind());
video_track->RegisterMediaStream(this);
video_tracks_.push_back(video_track);
@@ -201,6 +198,10 @@ MediaStream::MediaStream(ExecutionContext* context,
MediaStream::~MediaStream() = default;
+bool MediaStream::HasPendingActivity() const {
+ return !scheduled_events_.IsEmpty();
+}
+
bool MediaStream::EmptyOrOnlyEndedTracks() {
if (!audio_tracks_.size() && !video_tracks_.size()) {
return true;
@@ -221,13 +222,13 @@ bool MediaStream::EmptyOrOnlyEndedTracks() {
bool MediaStream::TracksMatchDescriptor() {
if (audio_tracks_.size() != descriptor_->NumberOfAudioComponents())
return false;
- for (size_t i = 0; i < audio_tracks_.size(); i++) {
+ for (wtf_size_t i = 0; i < audio_tracks_.size(); i++) {
if (audio_tracks_[i]->Component() != descriptor_->AudioComponent(i))
return false;
}
if (video_tracks_.size() != descriptor_->NumberOfVideoComponents())
return false;
- for (size_t i = 0; i < video_tracks_.size(); i++) {
+ for (wtf_size_t i = 0; i < video_tracks_.size(); i++) {
if (video_tracks_[i]->Component() != descriptor_->VideoComponent(i))
return false;
}
@@ -270,7 +271,7 @@ void MediaStream::addTrack(MediaStreamTrack* track,
if (!active() && !track->Ended()) {
descriptor_->SetActive(true);
- ScheduleDispatchEvent(Event::Create(EventTypeNames::active));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kActive));
}
for (auto& observer : observers_)
@@ -286,7 +287,7 @@ void MediaStream::removeTrack(MediaStreamTrack* track,
return;
}
- size_t pos = kNotFound;
+ wtf_size_t pos = kNotFound;
switch (track->Component()->Source()->GetType()) {
case MediaStreamSource::kTypeAudio:
pos = audio_tracks_.Find(track);
@@ -307,7 +308,7 @@ void MediaStream::removeTrack(MediaStreamTrack* track,
if (active() && EmptyOrOnlyEndedTracks()) {
descriptor_->SetActive(false);
- ScheduleDispatchEvent(Event::Create(EventTypeNames::inactive));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kInactive));
}
for (auto& observer : observers_)
@@ -373,17 +374,17 @@ void MediaStream::StreamEnded() {
if (active()) {
descriptor_->SetActive(false);
- ScheduleDispatchEvent(Event::Create(EventTypeNames::inactive));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kInactive));
}
}
bool MediaStream::AddEventListenerInternal(
const AtomicString& event_type,
EventListener* listener,
- const AddEventListenerOptionsResolved& options) {
- if (event_type == EventTypeNames::active) {
+ const AddEventListenerOptionsResolved* options) {
+ if (event_type == event_type_names::kActive) {
UseCounter::Count(GetExecutionContext(), WebFeature::kMediaStreamOnActive);
- } else if (event_type == EventTypeNames::inactive) {
+ } else if (event_type == event_type_names::kInactive) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kMediaStreamOnInactive);
}
@@ -393,7 +394,7 @@ bool MediaStream::AddEventListenerInternal(
}
const AtomicString& MediaStream::InterfaceName() const {
- return EventTargetNames::MediaStream;
+ return event_target_names::kMediaStream;
}
void MediaStream::AddTrackByComponentAndFireEvents(
@@ -422,8 +423,8 @@ void MediaStream::RemoveTrackByComponentAndFireEvents(
break;
}
- size_t index = kNotFound;
- for (size_t i = 0; i < tracks->size(); ++i) {
+ wtf_size_t index = kNotFound;
+ for (wtf_size_t i = 0; i < tracks->size(); ++i) {
if ((*tracks)[i]->Component() == component) {
index = i;
break;
@@ -438,11 +439,11 @@ void MediaStream::RemoveTrackByComponentAndFireEvents(
track->UnregisterMediaStream(this);
tracks->EraseAt(index);
ScheduleDispatchEvent(
- MediaStreamTrackEvent::Create(EventTypeNames::removetrack, track));
+ MediaStreamTrackEvent::Create(event_type_names::kRemovetrack, track));
if (active() && EmptyOrOnlyEndedTracks()) {
descriptor_->SetActive(false);
- ScheduleDispatchEvent(Event::Create(EventTypeNames::inactive));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kInactive));
}
}
@@ -460,11 +461,11 @@ void MediaStream::AddTrackAndFireEvents(MediaStreamTrack* track) {
descriptor_->AddComponent(track->Component());
ScheduleDispatchEvent(
- MediaStreamTrackEvent::Create(EventTypeNames::addtrack, track));
+ MediaStreamTrackEvent::Create(event_type_names::kAddtrack, track));
if (!active() && !track->Ended()) {
descriptor_->SetActive(true);
- ScheduleDispatchEvent(Event::Create(EventTypeNames::active));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kActive));
}
}
@@ -494,10 +495,6 @@ void MediaStream::ScheduledEventTimerFired(TimerBase*) {
events.clear();
}
-URLRegistry& MediaStream::Registry() const {
- return MediaStreamRegistry::Registry();
-}
-
void MediaStream::Trace(blink::Visitor* visitor) {
visitor->Trace(audio_tracks_);
visitor->Trace(video_tracks_);
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream.h b/chromium/third_party/blink/renderer/modules/mediastream/media_stream.h
index 8b815ef7050..205fc7bdad1 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream.h
@@ -26,7 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_H_
-#include "third_party/blink/renderer/core/fileapi/url_registry.h"
+#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream_track.h"
#include "third_party/blink/renderer/modules/modules_export.h"
@@ -51,10 +51,11 @@ class MODULES_EXPORT MediaStreamObserver : public GarbageCollectedMixin {
void Trace(blink::Visitor* visitor) override {}
};
-class MODULES_EXPORT MediaStream final : public EventTargetWithInlineData,
- public ContextClient,
- public URLRegistrable,
- public MediaStreamDescriptorClient {
+class MODULES_EXPORT MediaStream final
+ : public EventTargetWithInlineData,
+ public ContextClient,
+ public ActiveScriptWrappable<MediaStream>,
+ public MediaStreamDescriptorClient {
USING_GARBAGE_COLLECTED_MIXIN(MediaStream);
DEFINE_WRAPPERTYPEINFO();
@@ -78,6 +79,15 @@ class MODULES_EXPORT MediaStream final : public EventTargetWithInlineData,
MediaStreamDescriptor*,
const MediaStreamTrackVector& audio_tracks,
const MediaStreamTrackVector& video_tracks);
+
+ MediaStream(ExecutionContext*, MediaStreamDescriptor*);
+ MediaStream(ExecutionContext*,
+ MediaStreamDescriptor*,
+ const MediaStreamTrackVector& audio_tracks,
+ const MediaStreamTrackVector& video_tracks);
+ MediaStream(ExecutionContext*,
+ const MediaStreamTrackVector& audio_tracks,
+ const MediaStreamTrackVector& video_tracks);
~MediaStream() override;
String id() const { return descriptor_->Id(); }
@@ -96,10 +106,10 @@ class MODULES_EXPORT MediaStream final : public EventTargetWithInlineData,
bool active() const { return descriptor_->Active(); }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(active);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(inactive);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(active, kActive);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(inactive, kInactive);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack, kAddtrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack, kRemovetrack);
void TrackEnded();
@@ -127,8 +137,8 @@ class MODULES_EXPORT MediaStream final : public EventTargetWithInlineData,
return ContextClient::GetExecutionContext();
}
- // URLRegistrable
- URLRegistry& Registry() const override;
+ // ActiveScriptWrappable
+ bool HasPendingActivity() const override;
void Trace(blink::Visitor*) override;
@@ -136,18 +146,9 @@ class MODULES_EXPORT MediaStream final : public EventTargetWithInlineData,
bool AddEventListenerInternal(
const AtomicString& event_type,
EventListener*,
- const AddEventListenerOptionsResolved&) override;
+ const AddEventListenerOptionsResolved*) override;
private:
- MediaStream(ExecutionContext*, MediaStreamDescriptor*);
- MediaStream(ExecutionContext*,
- MediaStreamDescriptor*,
- const MediaStreamTrackVector& audio_tracks,
- const MediaStreamTrackVector& video_tracks);
- MediaStream(ExecutionContext*,
- const MediaStreamTrackVector& audio_tracks,
- const MediaStreamTrackVector& video_tracks);
-
bool EmptyOrOnlyEndedTracks();
bool TracksMatchDescriptor();
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream.idl b/chromium/third_party/blink/renderer/modules/mediastream/media_stream.idl
index 9add324fcb8..03a3aaefeb8 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream.idl
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream.idl
@@ -26,6 +26,7 @@
// https://w3c.github.io/mediacapture-main/#idl-def-mediastream
[
+ ActiveScriptWrappable,
Constructor,
Constructor(MediaStream stream),
Constructor(sequence<MediaStreamTrack> tracks),
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.cc
index 0c1bdbe3b72..a0e1333468e 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.cc
@@ -28,13 +28,13 @@ namespace blink {
MediaStreamEvent* MediaStreamEvent::Create(const AtomicString& type,
MediaStream* stream) {
- return new MediaStreamEvent(type, stream);
+ return MakeGarbageCollected<MediaStreamEvent>(type, stream);
}
MediaStreamEvent* MediaStreamEvent::Create(
const AtomicString& type,
- const MediaStreamEventInit& initializer) {
- return new MediaStreamEvent(type, initializer);
+ const MediaStreamEventInit* initializer) {
+ return MakeGarbageCollected<MediaStreamEvent>(type, initializer);
}
MediaStreamEvent::MediaStreamEvent(const AtomicString& type,
@@ -42,10 +42,10 @@ MediaStreamEvent::MediaStreamEvent(const AtomicString& type,
: Event(type, Bubbles::kNo, Cancelable::kNo), stream_(stream) {}
MediaStreamEvent::MediaStreamEvent(const AtomicString& type,
- const MediaStreamEventInit& initializer)
+ const MediaStreamEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasStream())
- stream_ = initializer.stream();
+ if (initializer->hasStream())
+ stream_ = initializer->stream();
}
MediaStreamEvent::~MediaStreamEvent() = default;
@@ -60,7 +60,7 @@ MediaStream* MediaStreamEvent::stream(bool& is_null) const {
}
const AtomicString& MediaStreamEvent::InterfaceName() const {
- return EventNames::MediaStreamEvent;
+ return event_interface_names::kMediaStreamEvent;
}
void MediaStreamEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.h b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.h
index 70a26190017..ff9ef476c19 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_event.h
@@ -36,11 +36,13 @@ class MediaStreamEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ MediaStreamEvent(const AtomicString& type, MediaStream*);
+ MediaStreamEvent(const AtomicString& type, const MediaStreamEventInit*);
~MediaStreamEvent() override;
static MediaStreamEvent* Create(const AtomicString& type, MediaStream*);
static MediaStreamEvent* Create(const AtomicString& type,
- const MediaStreamEventInit& initializer);
+ const MediaStreamEventInit* initializer);
MediaStream* stream() const;
MediaStream* stream(bool&) const;
@@ -50,9 +52,6 @@ class MediaStreamEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- MediaStreamEvent(const AtomicString& type, MediaStream*);
- MediaStreamEvent(const AtomicString& type, const MediaStreamEventInit&);
-
Member<MediaStream> stream_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.cc
deleted file mode 100644
index db5b71d3df5..00000000000
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/modules/mediastream/media_stream_registry.h"
-
-#include "third_party/blink/renderer/core/html/media/html_media_element.h"
-#include "third_party/blink/renderer/modules/mediastream/media_stream.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-
-namespace blink {
-
-MediaStreamRegistry& MediaStreamRegistry::Registry() {
- // Since WebWorkers cannot obtain MediaStream objects, we should be on the
- // main thread.
- DCHECK(IsMainThread());
- DEFINE_STATIC_LOCAL(MediaStreamRegistry, instance, ());
- return instance;
-}
-
-void MediaStreamRegistry::RegisterURL(SecurityOrigin*,
- const KURL& url,
- URLRegistrable* stream) {
- DCHECK(&stream->Registry() == this);
- DCHECK(IsMainThread());
- stream_descriptors_->Set(url.GetString(),
- static_cast<MediaStream*>(stream)->Descriptor());
-}
-
-void MediaStreamRegistry::UnregisterURL(const KURL& url) {
- DCHECK(IsMainThread());
- stream_descriptors_->erase(url.GetString());
-}
-
-bool MediaStreamRegistry::Contains(const String& url) {
- DCHECK(IsMainThread());
- return stream_descriptors_->Contains(url);
-}
-
-MediaStreamDescriptor* MediaStreamRegistry::LookupMediaStreamDescriptor(
- const String& url) {
- DCHECK(IsMainThread());
- return stream_descriptors_->at(url);
-}
-
-MediaStreamRegistry::MediaStreamRegistry()
- : stream_descriptors_(
- new HeapHashMap<String, Member<MediaStreamDescriptor>>) {
- HTMLMediaElement::SetMediaStreamRegistry(this);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.h b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.h
deleted file mode 100644
index 8f34641d7bc..00000000000
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_registry.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_REGISTRY_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_REGISTRY_H_
-
-#include "third_party/blink/renderer/core/fileapi/url_registry.h"
-#include "third_party/blink/renderer/modules/modules_export.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/heap/persistent.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
-
-namespace blink {
-
-class KURL;
-class MediaStreamDescriptor;
-
-class MODULES_EXPORT MediaStreamRegistry final : public URLRegistry {
- public:
- // Returns a single instance of MediaStreamRegistry.
- static MediaStreamRegistry& Registry();
-
- // Registers a blob URL referring to the specified stream data.
- void RegisterURL(SecurityOrigin*, const KURL&, URLRegistrable*) override;
- void UnregisterURL(const KURL&) override;
- bool Contains(const String&) override;
-
- MediaStreamDescriptor* LookupMediaStreamDescriptor(const String& url);
-
- private:
- MediaStreamRegistry();
- Persistent<HeapHashMap<String, Member<MediaStreamDescriptor>>>
- stream_descriptors_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_REGISTRY_H_
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.cc
index 062a7c5a0a7..7406b72ea54 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.cc
@@ -44,6 +44,8 @@
#include "third_party/blink/renderer/modules/mediastream/media_track_settings.h"
#include "third_party/blink/renderer/modules/mediastream/overconstrained_error.h"
#include "third_party/blink/renderer/modules/mediastream/user_media_controller.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_center.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_component.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -66,53 +68,55 @@ static const char kContentHintStringVideoText[] = "text";
// spec-compliant main implementation and remove these support functions.
// http://crbug.com/708723
bool ConstraintSetHasImageCapture(
- const MediaTrackConstraintSet& constraint_set) {
- return constraint_set.hasWhiteBalanceMode() ||
- constraint_set.hasExposureMode() || constraint_set.hasFocusMode() ||
- constraint_set.hasPointsOfInterest() ||
- constraint_set.hasExposureCompensation() ||
- constraint_set.hasExposureTime() ||
- constraint_set.hasColorTemperature() || constraint_set.hasIso() ||
- constraint_set.hasBrightness() || constraint_set.hasContrast() ||
- constraint_set.hasSaturation() || constraint_set.hasSharpness() ||
- constraint_set.hasFocusDistance() || constraint_set.hasZoom() ||
- constraint_set.hasTorch();
+ const MediaTrackConstraintSet* constraint_set) {
+ return constraint_set->hasWhiteBalanceMode() ||
+ constraint_set->hasExposureMode() || constraint_set->hasFocusMode() ||
+ constraint_set->hasPointsOfInterest() ||
+ constraint_set->hasExposureCompensation() ||
+ constraint_set->hasExposureTime() ||
+ constraint_set->hasColorTemperature() || constraint_set->hasIso() ||
+ constraint_set->hasBrightness() || constraint_set->hasContrast() ||
+ constraint_set->hasSaturation() || constraint_set->hasSharpness() ||
+ constraint_set->hasFocusDistance() || constraint_set->hasZoom() ||
+ constraint_set->hasTorch();
}
bool ConstraintSetHasNonImageCapture(
- const MediaTrackConstraintSet& constraint_set) {
- return constraint_set.hasAspectRatio() || constraint_set.hasChannelCount() ||
- constraint_set.hasDepthFar() || constraint_set.hasDepthNear() ||
- constraint_set.hasDeviceId() || constraint_set.hasEchoCancellation() ||
- constraint_set.hasFacingMode() || constraint_set.hasFocalLengthX() ||
- constraint_set.hasFocalLengthY() || constraint_set.hasFrameRate() ||
- constraint_set.hasGroupId() || constraint_set.hasHeight() ||
- constraint_set.hasLatency() || constraint_set.hasSampleRate() ||
- constraint_set.hasSampleSize() || constraint_set.hasVideoKind() ||
- constraint_set.hasVolume() || constraint_set.hasWidth();
+ const MediaTrackConstraintSet* constraint_set) {
+ return constraint_set->hasAspectRatio() ||
+ constraint_set->hasChannelCount() || constraint_set->hasDepthFar() ||
+ constraint_set->hasDepthNear() || constraint_set->hasDeviceId() ||
+ constraint_set->hasEchoCancellation() ||
+ constraint_set->hasFacingMode() || constraint_set->hasResizeMode() ||
+ constraint_set->hasFocalLengthX() ||
+ constraint_set->hasFocalLengthY() || constraint_set->hasFrameRate() ||
+ constraint_set->hasGroupId() || constraint_set->hasHeight() ||
+ constraint_set->hasLatency() || constraint_set->hasSampleRate() ||
+ constraint_set->hasSampleSize() || constraint_set->hasVideoKind() ||
+ constraint_set->hasVolume() || constraint_set->hasWidth();
}
bool ConstraintSetHasImageAndNonImageCapture(
- const MediaTrackConstraintSet& constraint_set) {
+ const MediaTrackConstraintSet* constraint_set) {
return ConstraintSetHasImageCapture(constraint_set) &&
ConstraintSetHasNonImageCapture(constraint_set);
}
-bool ConstraintSetIsNonEmpty(const MediaTrackConstraintSet& constraint_set) {
+bool ConstraintSetIsNonEmpty(const MediaTrackConstraintSet* constraint_set) {
return ConstraintSetHasImageCapture(constraint_set) ||
ConstraintSetHasNonImageCapture(constraint_set);
}
template <typename ConstraintSetCondition>
bool ConstraintsSatisfyCondition(ConstraintSetCondition condition,
- const MediaTrackConstraints& constraints) {
+ const MediaTrackConstraints* constraints) {
if (condition(constraints))
return true;
- if (!constraints.hasAdvanced())
+ if (!constraints->hasAdvanced())
return false;
- for (const auto& advanced_set : constraints.advanced()) {
+ for (const auto& advanced_set : constraints->advanced()) {
if (condition(advanced_set))
return true;
}
@@ -121,16 +125,16 @@ bool ConstraintsSatisfyCondition(ConstraintSetCondition condition,
}
bool ConstraintsHaveImageAndNonImageCapture(
- const MediaTrackConstraints& constraints) {
+ const MediaTrackConstraints* constraints) {
return ConstraintsSatisfyCondition(ConstraintSetHasImageAndNonImageCapture,
constraints);
}
-bool ConstraintsAreEmpty(const MediaTrackConstraints& constraints) {
+bool ConstraintsAreEmpty(const MediaTrackConstraints* constraints) {
return !ConstraintsSatisfyCondition(ConstraintSetIsNonEmpty, constraints);
}
-bool ConstraintsHaveImageCapture(const MediaTrackConstraints& constraints) {
+bool ConstraintsHaveImageCapture(const MediaTrackConstraints* constraints) {
return ConstraintsSatisfyCondition(ConstraintSetHasImageCapture, constraints);
}
@@ -138,7 +142,7 @@ bool ConstraintsHaveImageCapture(const MediaTrackConstraints& constraints) {
MediaStreamTrack* MediaStreamTrack::Create(ExecutionContext* context,
MediaStreamComponent* component) {
- return new MediaStreamTrack(context, component);
+ return MakeGarbageCollected<MediaStreamTrack>(context, component);
}
MediaStreamTrack::MediaStreamTrack(ExecutionContext* context,
@@ -307,9 +311,9 @@ void MediaStreamTrack::stopTrack(ExecutionContext* execution_context) {
MediaStreamTrack* MediaStreamTrack::clone(ScriptState* script_state) {
MediaStreamComponent* cloned_component = Component()->Clone();
- MediaStreamTrack* cloned_track =
- new MediaStreamTrack(ExecutionContext::From(script_state),
- cloned_component, ready_state_, stopped_);
+ MediaStreamTrack* cloned_track = MakeGarbageCollected<MediaStreamTrack>(
+ ExecutionContext::From(script_state), cloned_component, ready_state_,
+ stopped_);
MediaStreamCenter::Instance().DidCloneMediaStreamTrack(Component(),
cloned_component);
return cloned_track;
@@ -319,56 +323,57 @@ void MediaStreamTrack::SetConstraints(const WebMediaConstraints& constraints) {
component_->SetConstraints(constraints);
}
-void MediaStreamTrack::getCapabilities(MediaTrackCapabilities& capabilities) {
+MediaTrackCapabilities* MediaStreamTrack::getCapabilities() const {
+ MediaTrackCapabilities* capabilities = MediaTrackCapabilities::Create();
if (image_capture_)
capabilities = image_capture_->GetMediaTrackCapabilities();
auto platform_capabilities = component_->Source()->GetCapabilities();
- capabilities.setDeviceId(platform_capabilities.device_id);
+ capabilities->setDeviceId(platform_capabilities.device_id);
if (!platform_capabilities.group_id.IsNull())
- capabilities.setGroupId(platform_capabilities.group_id);
+ capabilities->setGroupId(platform_capabilities.group_id);
if (component_->Source()->GetType() == MediaStreamSource::kTypeAudio) {
Vector<bool> echo_cancellation, auto_gain_control, noise_suppression;
for (bool value : platform_capabilities.echo_cancellation)
echo_cancellation.push_back(value);
- capabilities.setEchoCancellation(echo_cancellation);
+ capabilities->setEchoCancellation(echo_cancellation);
for (bool value : platform_capabilities.auto_gain_control)
auto_gain_control.push_back(value);
- capabilities.setAutoGainControl(auto_gain_control);
+ capabilities->setAutoGainControl(auto_gain_control);
for (bool value : platform_capabilities.noise_suppression)
noise_suppression.push_back(value);
- capabilities.setNoiseSuppression(noise_suppression);
+ capabilities->setNoiseSuppression(noise_suppression);
Vector<String> echo_cancellation_type;
for (String value : platform_capabilities.echo_cancellation_type)
echo_cancellation_type.push_back(value);
- capabilities.setEchoCancellationType(echo_cancellation_type);
+ capabilities->setEchoCancellationType(echo_cancellation_type);
}
if (component_->Source()->GetType() == MediaStreamSource::kTypeVideo) {
if (platform_capabilities.width.size() == 2) {
- LongRange width;
- width.setMin(platform_capabilities.width[0]);
- width.setMax(platform_capabilities.width[1]);
- capabilities.setWidth(width);
+ LongRange* width = LongRange::Create();
+ width->setMin(platform_capabilities.width[0]);
+ width->setMax(platform_capabilities.width[1]);
+ capabilities->setWidth(width);
}
if (platform_capabilities.height.size() == 2) {
- LongRange height;
- height.setMin(platform_capabilities.height[0]);
- height.setMax(platform_capabilities.height[1]);
- capabilities.setHeight(height);
+ LongRange* height = LongRange::Create();
+ height->setMin(platform_capabilities.height[0]);
+ height->setMax(platform_capabilities.height[1]);
+ capabilities->setHeight(height);
}
if (platform_capabilities.aspect_ratio.size() == 2) {
- DoubleRange aspect_ratio;
- aspect_ratio.setMin(platform_capabilities.aspect_ratio[0]);
- aspect_ratio.setMax(platform_capabilities.aspect_ratio[1]);
- capabilities.setAspectRatio(aspect_ratio);
+ DoubleRange* aspect_ratio = DoubleRange::Create();
+ aspect_ratio->setMin(platform_capabilities.aspect_ratio[0]);
+ aspect_ratio->setMax(platform_capabilities.aspect_ratio[1]);
+ capabilities->setAspectRatio(aspect_ratio);
}
if (platform_capabilities.frame_rate.size() == 2) {
- DoubleRange frame_rate;
- frame_rate.setMin(platform_capabilities.frame_rate[0]);
- frame_rate.setMax(platform_capabilities.frame_rate[1]);
- capabilities.setFrameRate(frame_rate);
+ DoubleRange* frame_rate = DoubleRange::Create();
+ frame_rate->setMin(platform_capabilities.frame_rate[0]);
+ frame_rate->setMax(platform_capabilities.frame_rate[1]);
+ capabilities->setFrameRate(frame_rate);
}
Vector<String> facing_mode;
switch (platform_capabilities.facing_mode) {
@@ -387,113 +392,122 @@ void MediaStreamTrack::getCapabilities(MediaTrackCapabilities& capabilities) {
default:
break;
}
- capabilities.setFacingMode(facing_mode);
+ capabilities->setFacingMode(facing_mode);
+ capabilities->setResizeMode({WebMediaStreamTrack::kResizeModeNone,
+ WebMediaStreamTrack::kResizeModeRescale});
}
+ return capabilities;
}
-void MediaStreamTrack::getConstraints(MediaTrackConstraints& constraints) {
- MediaConstraintsImpl::ConvertConstraints(component_->Constraints(),
- constraints);
-
+MediaTrackConstraints* MediaStreamTrack::getConstraints() const {
+ MediaTrackConstraints* constraints =
+ media_constraints_impl::ConvertConstraints(component_->Constraints());
if (!image_capture_)
- return;
- HeapVector<MediaTrackConstraintSet> vector;
- if (constraints.hasAdvanced())
- vector = constraints.advanced();
+ return constraints;
+
+ HeapVector<Member<MediaTrackConstraintSet>> vector;
+ if (constraints->hasAdvanced())
+ vector = constraints->advanced();
// TODO(mcasas): consider consolidating this code in MediaContraintsImpl.
- auto image_capture_constraints = image_capture_->GetMediaTrackConstraints();
+ MediaTrackConstraintSet* image_capture_constraints =
+ const_cast<MediaTrackConstraintSet*>(
+ image_capture_->GetMediaTrackConstraints());
// TODO(mcasas): add |torch|, https://crbug.com/700607.
- if (image_capture_constraints.hasWhiteBalanceMode() ||
- image_capture_constraints.hasExposureMode() ||
- image_capture_constraints.hasFocusMode() ||
- image_capture_constraints.hasExposureCompensation() ||
- image_capture_constraints.hasExposureTime() ||
- image_capture_constraints.hasColorTemperature() ||
- image_capture_constraints.hasIso() ||
- image_capture_constraints.hasBrightness() ||
- image_capture_constraints.hasContrast() ||
- image_capture_constraints.hasSaturation() ||
- image_capture_constraints.hasSharpness() ||
- image_capture_constraints.hasFocusDistance() ||
- image_capture_constraints.hasZoom()) {
+ if (image_capture_constraints->hasWhiteBalanceMode() ||
+ image_capture_constraints->hasExposureMode() ||
+ image_capture_constraints->hasFocusMode() ||
+ image_capture_constraints->hasExposureCompensation() ||
+ image_capture_constraints->hasExposureTime() ||
+ image_capture_constraints->hasColorTemperature() ||
+ image_capture_constraints->hasIso() ||
+ image_capture_constraints->hasBrightness() ||
+ image_capture_constraints->hasContrast() ||
+ image_capture_constraints->hasSaturation() ||
+ image_capture_constraints->hasSharpness() ||
+ image_capture_constraints->hasFocusDistance() ||
+ image_capture_constraints->hasZoom()) {
// Add image capture constraints, if any, as another entry to advanced().
- vector.emplace_back(image_capture_constraints);
- constraints.setAdvanced(vector);
+ vector.push_back(image_capture_constraints);
+ constraints->setAdvanced(vector);
}
+ return constraints;
}
-void MediaStreamTrack::getSettings(MediaTrackSettings& settings) {
+MediaTrackSettings* MediaStreamTrack::getSettings() const {
+ MediaTrackSettings* settings = MediaTrackSettings::Create();
WebMediaStreamTrack::Settings platform_settings;
component_->GetSettings(platform_settings);
if (platform_settings.HasFrameRate())
- settings.setFrameRate(platform_settings.frame_rate);
+ settings->setFrameRate(platform_settings.frame_rate);
if (platform_settings.HasWidth())
- settings.setWidth(platform_settings.width);
+ settings->setWidth(platform_settings.width);
if (platform_settings.HasHeight())
- settings.setHeight(platform_settings.height);
+ settings->setHeight(platform_settings.height);
if (platform_settings.HasAspectRatio())
- settings.setAspectRatio(platform_settings.aspect_ratio);
+ settings->setAspectRatio(platform_settings.aspect_ratio);
if (RuntimeEnabledFeatures::MediaCaptureDepthVideoKindEnabled() &&
component_->Source()->GetType() == MediaStreamSource::kTypeVideo) {
if (platform_settings.HasVideoKind())
- settings.setVideoKind(platform_settings.video_kind);
+ settings->setVideoKind(platform_settings.video_kind);
}
if (RuntimeEnabledFeatures::MediaCaptureDepthEnabled() &&
component_->Source()->GetType() == MediaStreamSource::kTypeVideo) {
if (platform_settings.HasDepthNear())
- settings.setDepthNear(platform_settings.depth_near);
+ settings->setDepthNear(platform_settings.depth_near);
if (platform_settings.HasDepthFar())
- settings.setDepthFar(platform_settings.depth_far);
+ settings->setDepthFar(platform_settings.depth_far);
if (platform_settings.HasFocalLengthX())
- settings.setFocalLengthX(platform_settings.focal_length_x);
+ settings->setFocalLengthX(platform_settings.focal_length_x);
if (platform_settings.HasFocalLengthY())
- settings.setFocalLengthY(platform_settings.focal_length_y);
+ settings->setFocalLengthY(platform_settings.focal_length_y);
}
- settings.setDeviceId(platform_settings.device_id);
+ settings->setDeviceId(platform_settings.device_id);
if (!platform_settings.group_id.IsNull())
- settings.setGroupId(platform_settings.group_id);
+ settings->setGroupId(platform_settings.group_id);
if (platform_settings.HasFacingMode()) {
switch (platform_settings.facing_mode) {
case WebMediaStreamTrack::FacingMode::kUser:
- settings.setFacingMode("user");
+ settings->setFacingMode("user");
break;
case WebMediaStreamTrack::FacingMode::kEnvironment:
- settings.setFacingMode("environment");
+ settings->setFacingMode("environment");
break;
case WebMediaStreamTrack::FacingMode::kLeft:
- settings.setFacingMode("left");
+ settings->setFacingMode("left");
break;
case WebMediaStreamTrack::FacingMode::kRight:
- settings.setFacingMode("right");
+ settings->setFacingMode("right");
break;
default:
// None, or unknown facing mode. Ignore.
break;
}
}
+ if (!platform_settings.resize_mode.IsNull())
+ settings->setResizeMode(platform_settings.resize_mode);
if (platform_settings.echo_cancellation)
- settings.setEchoCancellation(*platform_settings.echo_cancellation);
+ settings->setEchoCancellation(*platform_settings.echo_cancellation);
if (platform_settings.auto_gain_control)
- settings.setAutoGainControl(*platform_settings.auto_gain_control);
+ settings->setAutoGainControl(*platform_settings.auto_gain_control);
if (platform_settings.noise_supression)
- settings.setNoiseSuppression(*platform_settings.noise_supression);
- if (OriginTrials::ExperimentalHardwareEchoCancellationEnabled(
+ settings->setNoiseSuppression(*platform_settings.noise_supression);
+ if (origin_trials::ExperimentalHardwareEchoCancellationEnabled(
GetExecutionContext()) &&
!platform_settings.echo_cancellation_type.IsNull()) {
- settings.setEchoCancellationType(platform_settings.echo_cancellation_type);
+ settings->setEchoCancellationType(platform_settings.echo_cancellation_type);
}
if (platform_settings.HasSampleRate())
- settings.setSampleRate(platform_settings.sample_rate);
+ settings->setSampleRate(platform_settings.sample_rate);
if (platform_settings.HasSampleSize())
- settings.setSampleSize(platform_settings.sample_size);
+ settings->setSampleSize(platform_settings.sample_size);
if (platform_settings.HasChannelCount())
- settings.setChannelCount(platform_settings.channel_count);
+ settings->setChannelCount(platform_settings.channel_count);
if (platform_settings.HasLatency())
- settings.setLatency(platform_settings.latency);
+ settings->setLatency(platform_settings.latency);
if (platform_settings.HasVolume())
- settings.setVolume(platform_settings.volume);
+ settings->setVolume(platform_settings.volume);
if (image_capture_)
image_capture_->GetMediaTrackSettings(settings);
@@ -514,10 +528,10 @@ void MediaStreamTrack::getSettings(MediaTrackSettings& settings) {
value = "browser";
break;
}
- settings.setDisplaySurface(value);
+ settings->setDisplaySurface(value);
}
if (platform_settings.logical_surface)
- settings.setLogicalSurface(platform_settings.logical_surface.value());
+ settings->setLogicalSurface(platform_settings.logical_surface.value());
if (platform_settings.cursor) {
WTF::String value;
switch (platform_settings.cursor.value()) {
@@ -531,20 +545,21 @@ void MediaStreamTrack::getSettings(MediaTrackSettings& settings) {
value = "motion";
break;
}
- settings.setCursor(value);
+ settings->setCursor(value);
}
+ return settings;
}
ScriptPromise MediaStreamTrack::applyConstraints(
ScriptState* script_state,
- const MediaTrackConstraints& constraints) {
+ const MediaTrackConstraints* constraints) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
MediaErrorState error_state;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
- WebMediaConstraints web_constraints =
- MediaConstraintsImpl::Create(execution_context, constraints, error_state);
+ WebMediaConstraints web_constraints = media_constraints_impl::Create(
+ execution_context, constraints, error_state);
if (error_state.HadException()) {
resolver->Reject(
OverconstrainedError::Create(String(), "Cannot parse constraints"));
@@ -599,13 +614,13 @@ ScriptPromise MediaStreamTrack::applyConstraints(
void MediaStreamTrack::applyConstraintsImageCapture(
ScriptPromiseResolver* resolver,
- const MediaTrackConstraints& constraints) {
+ const MediaTrackConstraints* constraints) {
// |constraints| empty means "remove/clear all current constraints".
- if (!constraints.hasAdvanced() || constraints.advanced().IsEmpty()) {
+ if (!constraints->hasAdvanced() || constraints->advanced().IsEmpty()) {
image_capture_->ClearMediaTrackConstraints();
resolver->Resolve();
} else {
- image_capture_->SetMediaTrackConstraints(resolver, constraints.advanced());
+ image_capture_->SetMediaTrackConstraints(resolver, constraints->advanced());
}
}
@@ -621,14 +636,14 @@ void MediaStreamTrack::SourceChangedState() {
switch (ready_state_) {
case MediaStreamSource::kReadyStateLive:
component_->SetMuted(false);
- DispatchEvent(*Event::Create(EventTypeNames::unmute));
+ DispatchEvent(*Event::Create(event_type_names::kUnmute));
break;
case MediaStreamSource::kReadyStateMuted:
component_->SetMuted(true);
- DispatchEvent(*Event::Create(EventTypeNames::mute));
+ DispatchEvent(*Event::Create(event_type_names::kMute));
break;
case MediaStreamSource::kReadyStateEnded:
- DispatchEvent(*Event::Create(EventTypeNames::ended));
+ DispatchEvent(*Event::Create(event_type_names::kEnded));
PropagateTrackEnded();
break;
}
@@ -661,7 +676,7 @@ bool MediaStreamTrack::HasPendingActivity() const {
//
// Hence insisting on keeping this object alive until the 'ended'
// state has been reached & handled.
- return !Ended() && HasEventListeners(EventTypeNames::ended);
+ return !Ended() && HasEventListeners(event_type_names::kEnded);
}
std::unique_ptr<AudioSourceProvider> MediaStreamTrack::CreateWebAudioSource() {
@@ -684,7 +699,7 @@ void MediaStreamTrack::UnregisterMediaStream(MediaStream* media_stream) {
}
const AtomicString& MediaStreamTrack::InterfaceName() const {
- return EventTargetNames::MediaStreamTrack;
+ return event_target_names::kMediaStreamTrack;
}
ExecutionContext* MediaStreamTrack::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.h b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.h
index 4f278c2551e..10d8c2fda31 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track.h
@@ -57,6 +57,12 @@ class MODULES_EXPORT MediaStreamTrack
public:
static MediaStreamTrack* Create(ExecutionContext*, MediaStreamComponent*);
+
+ MediaStreamTrack(ExecutionContext*, MediaStreamComponent*);
+ MediaStreamTrack(ExecutionContext*,
+ MediaStreamComponent*,
+ MediaStreamSource::ReadyState,
+ bool stopped);
~MediaStreamTrack() override;
String kind() const;
@@ -80,14 +86,14 @@ class MODULES_EXPORT MediaStreamTrack
// Called from UserMediaRequest when it succeeds. It is not IDL-exposed.
void SetConstraints(const WebMediaConstraints&);
- void getCapabilities(MediaTrackCapabilities&);
- void getConstraints(MediaTrackConstraints&);
- void getSettings(MediaTrackSettings&);
- ScriptPromise applyConstraints(ScriptState*, const MediaTrackConstraints&);
+ MediaTrackCapabilities* getCapabilities() const;
+ MediaTrackConstraints* getConstraints() const;
+ MediaTrackSettings* getSettings() const;
+ ScriptPromise applyConstraints(ScriptState*, const MediaTrackConstraints*);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mute);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(unmute);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(ended);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(mute, kMute);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(unmute, kUnmute);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(ended, kEnded);
MediaStreamComponent* Component() { return component_; }
bool Ended() const;
@@ -112,18 +118,12 @@ class MODULES_EXPORT MediaStreamTrack
private:
friend class CanvasCaptureMediaStreamTrack;
- MediaStreamTrack(ExecutionContext*, MediaStreamComponent*);
- MediaStreamTrack(ExecutionContext*,
- MediaStreamComponent*,
- MediaStreamSource::ReadyState,
- bool stopped);
-
// MediaStreamSourceObserver
void SourceChangedState() override;
void PropagateTrackEnded();
void applyConstraintsImageCapture(ScriptPromiseResolver*,
- const MediaTrackConstraints&);
+ const MediaTrackConstraints*);
MediaStreamSource::ReadyState ready_state_;
HeapHashSet<Member<MediaStream>> registered_media_streams_;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.cc b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.cc
index 71485e1affc..0f75ef34b69 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.cc
@@ -30,7 +30,7 @@ namespace blink {
MediaStreamTrackEvent* MediaStreamTrackEvent::Create(const AtomicString& type,
MediaStreamTrack* track) {
- return new MediaStreamTrackEvent(type, track);
+ return MakeGarbageCollected<MediaStreamTrackEvent>(type, track);
}
MediaStreamTrackEvent::MediaStreamTrackEvent(const AtomicString& type,
@@ -41,14 +41,14 @@ MediaStreamTrackEvent::MediaStreamTrackEvent(const AtomicString& type,
MediaStreamTrackEvent* MediaStreamTrackEvent::Create(
const AtomicString& type,
- const MediaStreamTrackEventInit& initializer) {
- return new MediaStreamTrackEvent(type, initializer);
+ const MediaStreamTrackEventInit* initializer) {
+ return MakeGarbageCollected<MediaStreamTrackEvent>(type, initializer);
}
MediaStreamTrackEvent::MediaStreamTrackEvent(
const AtomicString& type,
- const MediaStreamTrackEventInit& initializer)
- : Event(type, initializer), track_(initializer.track()) {
+ const MediaStreamTrackEventInit* initializer)
+ : Event(type, initializer), track_(initializer->track()) {
DCHECK(track_);
}
@@ -59,7 +59,7 @@ MediaStreamTrack* MediaStreamTrackEvent::track() const {
}
const AtomicString& MediaStreamTrackEvent::InterfaceName() const {
- return EventNames::MediaStreamTrackEvent;
+ return event_interface_names::kMediaStreamTrackEvent;
}
void MediaStreamTrackEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.h b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.h
index 5383103ee54..4bf6f6d9434 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_stream_track_event.h
@@ -42,7 +42,11 @@ class MediaStreamTrackEvent final : public Event {
static MediaStreamTrackEvent* Create(const AtomicString& type,
MediaStreamTrack*);
static MediaStreamTrackEvent* Create(const AtomicString& type,
- const MediaStreamTrackEventInit&);
+ const MediaStreamTrackEventInit*);
+
+ MediaStreamTrackEvent(const AtomicString& type, MediaStreamTrack*);
+ MediaStreamTrackEvent(const AtomicString& type,
+ const MediaStreamTrackEventInit*);
MediaStreamTrack* track() const;
@@ -52,10 +56,6 @@ class MediaStreamTrackEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- MediaStreamTrackEvent(const AtomicString& type, MediaStreamTrack*);
- MediaStreamTrackEvent(const AtomicString& type,
- const MediaStreamTrackEventInit&);
-
Member<MediaStreamTrack> track_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl b/chromium/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl
index b6f68f95aec..8fa90be86d3 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_track_capabilities.idl
@@ -8,6 +8,7 @@ dictionary MediaTrackCapabilities {
DoubleRange aspectRatio;
DoubleRange frameRate;
sequence<DOMString> facingMode;
+ sequence<DOMString> resizeMode;
sequence<boolean> echoCancellation;
// See http://crbug.com/846270.
[OriginTrialEnabled=ExperimentalHardwareEchoCancellation] sequence<DOMString> echoCancellationType;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl b/chromium/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl
index 08ce2d9c22e..1cb0515ae88 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_track_constraint_set.idl
@@ -16,6 +16,7 @@ dictionary MediaTrackConstraintSet {
ConstrainDouble aspectRatio;
ConstrainDouble frameRate;
ConstrainDOMString facingMode;
+ ConstrainDOMString resizeMode;
ConstrainDouble volume;
ConstrainLong sampleRate;
ConstrainLong sampleSize;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_track_settings.idl b/chromium/third_party/blink/renderer/modules/mediastream/media_track_settings.idl
index 8daf0e93368..d4fd9fdcb1b 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_track_settings.idl
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_track_settings.idl
@@ -10,6 +10,7 @@ dictionary MediaTrackSettings {
double aspectRatio;
double frameRate;
DOMString facingMode;
+ DOMString resizeMode;
double volume;
long sampleRate;
long sampleSize;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl b/chromium/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl
index 8d288b623ef..6ca0f003a66 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl
+++ b/chromium/third_party/blink/renderer/modules/mediastream/media_track_supported_constraints.idl
@@ -13,6 +13,7 @@ dictionary MediaTrackSupportedConstraints {
boolean aspectRatio = true;
boolean frameRate = true;
boolean facingMode = true;
+ boolean resizeMode = true;
boolean volume = true;
boolean sampleRate = true;
boolean sampleSize = true;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.cc b/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.cc
deleted file mode 100644
index a78d87f61ee..00000000000
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/modules/mediastream/navigator_display_media.h"
-
-#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
-#include "third_party/blink/renderer/core/dom/dom_exception.h"
-#include "third_party/blink/renderer/modules/mediastream/media_devices.h"
-#include "third_party/blink/renderer/modules/mediastream/navigator_user_media.h"
-
-namespace blink {
-
-ScriptPromise NavigatorDisplayMedia::getDisplayMedia(
- ScriptState* script_state,
- Navigator& navigator,
- const MediaStreamConstraints& options,
- ExceptionState& exception_state) {
- MediaDevices* const media_devices =
- NavigatorUserMedia::mediaDevices(navigator);
- if (!media_devices) {
- return ScriptPromise::RejectWithDOMException(
- script_state, DOMException::Create(DOMExceptionCode::kNotSupportedError,
- "Current frame is detached."));
- }
-
- return media_devices->SendUserMediaRequest(
- script_state, WebUserMediaRequest::MediaType::kDisplayMedia, options,
- exception_state);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.h b/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.h
deleted file mode 100644
index ab22babc8e8..00000000000
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.h
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_NAVIGATOR_DISPLAY_MEDIA_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_NAVIGATOR_DISPLAY_MEDIA_H_
-
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-
-#include "third_party/blink/renderer/core/frame/navigator.h"
-
-namespace blink {
-
-class ExceptionState;
-class MediaStreamConstraints;
-class ScriptPromise;
-class ScriptState;
-
-class NavigatorDisplayMedia {
- STATIC_ONLY(NavigatorDisplayMedia);
-
- public:
- static ScriptPromise getDisplayMedia(ScriptState*,
- Navigator&,
- const MediaStreamConstraints&,
- ExceptionState&);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_NAVIGATOR_DISPLAY_MEDIA_H_
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.idl b/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.idl
deleted file mode 100644
index 8afdc7e3710..00000000000
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_display_media.idl
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// https://w3c.github.io/mediacapture-screen-share/
-[
- ImplementedAs = NavigatorDisplayMedia,
- RuntimeEnabled = GetDisplayMedia
-] partial interface Navigator {
- [CallWith = ScriptState, RaisesException] Promise<MediaStream>
- getDisplayMedia(optional MediaStreamConstraints constraints);
-};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.cc b/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.cc
index 542b64aaf80..1dba754a5b8 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.cc
@@ -41,7 +41,7 @@ namespace blink {
void NavigatorMediaStream::getUserMedia(
Navigator& navigator,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
V8NavigatorUserMediaSuccessCallback* success_callback,
V8NavigatorUserMediaErrorCallback* error_callback,
ExceptionState& exception_state) {
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.h b/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.h
index 12350d8eeab..307b164ea96 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/navigator_media_stream.h
@@ -38,7 +38,7 @@ class NavigatorMediaStream {
public:
static void getUserMedia(Navigator&,
- const MediaStreamConstraints&,
+ const MediaStreamConstraints*,
V8NavigatorUserMediaSuccessCallback*,
V8NavigatorUserMediaErrorCallback*,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.cc b/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.cc
index dfc9ec377ae..8782de1e5e6 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.cc
@@ -24,7 +24,7 @@ NavigatorUserMedia& NavigatorUserMedia::From(Navigator& navigator) {
NavigatorUserMedia* supplement =
Supplement<Navigator>::From<NavigatorUserMedia>(navigator);
if (!supplement) {
- supplement = new NavigatorUserMedia(navigator);
+ supplement = MakeGarbageCollected<NavigatorUserMedia>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.h b/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.h
index 8106ff73a74..52006e37f2d 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/navigator_user_media.h
@@ -21,10 +21,12 @@ class NavigatorUserMedia final : public GarbageCollected<NavigatorUserMedia>,
static const char kSupplementName[];
static MediaDevices* mediaDevices(Navigator&);
+
+ explicit NavigatorUserMedia(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorUserMedia(Navigator&);
MediaDevices* GetMediaDevices();
static NavigatorUserMedia& From(Navigator&);
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.cc b/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.cc
index 4eecc43b262..6020055ede3 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.cc
@@ -8,7 +8,7 @@ namespace blink {
OverconstrainedError* OverconstrainedError::Create(const String& constraint,
const String& message) {
- return new OverconstrainedError(constraint, message);
+ return MakeGarbageCollected<OverconstrainedError>(constraint, message);
}
OverconstrainedError::OverconstrainedError(const String& constraint,
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.h b/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.h
index 9f1aa183fd3..533eb5e7e00 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/overconstrained_error.h
@@ -17,13 +17,13 @@ class OverconstrainedError final : public ScriptWrappable {
static OverconstrainedError* Create(const String& constraint,
const String& message);
+ OverconstrainedError(const String& constraint, const String& message);
+
String name() const { return "OverconstrainedError"; }
const String& constraint() const { return constraint_; }
const String& message() const { return message_; }
private:
- OverconstrainedError(const String& constraint, const String& message);
-
String constraint_;
String message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.cc b/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.cc
index 663763d67c4..06b08c2a594 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.cc
@@ -13,7 +13,7 @@ ScriptPromise InternalsMediaStream::addFakeDevice(
ScriptState* script_state,
Internals&,
const MediaDeviceInfo* device_info,
- const MediaTrackConstraints& capabilities,
+ const MediaTrackConstraints*,
const MediaStreamTrack* data_source) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.h b/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.h
index 69d29225e7c..03b9f3b4393 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/testing/internals_media_stream.h
@@ -23,7 +23,7 @@ class InternalsMediaStream {
static ScriptPromise addFakeDevice(ScriptState*,
Internals&,
const MediaDeviceInfo*,
- const MediaTrackConstraints& capabilities,
+ const MediaTrackConstraints* capabilities,
const MediaStreamTrack* data_source);
};
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.cc b/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.cc
index ae63eeae96f..658bd8e2ae9 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.cc
@@ -40,7 +40,8 @@ void UserMediaController::Trace(blink::Visitor* visitor) {
void ProvideUserMediaTo(LocalFrame& frame,
std::unique_ptr<UserMediaClient> client) {
UserMediaController::ProvideTo(
- frame, new UserMediaController(frame, std::move(client)));
+ frame,
+ MakeGarbageCollected<UserMediaController>(frame, std::move(client)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.h b/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.h
index b0b38dbf56d..c44e2346178 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/user_media_controller.h
@@ -53,6 +53,7 @@ class UserMediaController final
void CancelUserMediaRequest(UserMediaRequest*);
void ApplyConstraints(ApplyConstraintsRequest*);
void StopTrack(MediaStreamComponent*);
+ bool HasRequestedUserMedia();
static UserMediaController* From(LocalFrame* frame) {
return Supplement<LocalFrame>::From<UserMediaController>(frame);
@@ -60,10 +61,12 @@ class UserMediaController final
private:
std::unique_ptr<UserMediaClient> client_;
+ bool has_requested_user_media_ = false;
};
inline void UserMediaController::RequestUserMedia(UserMediaRequest* request) {
client_->RequestUserMedia(request);
+ has_requested_user_media_ = true;
}
inline void UserMediaController::CancelUserMediaRequest(
@@ -80,6 +83,10 @@ inline void UserMediaController::StopTrack(MediaStreamComponent* track) {
client_->StopTrack(track);
}
+inline bool UserMediaController::HasRequestedUserMedia() {
+ return has_requested_user_media_;
+}
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_USER_MEDIA_CONTROLLER_H_
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.cc b/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.cc
index 06e0ae7b328..8a2ca93c251 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.cc
+++ b/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.cc
@@ -298,12 +298,12 @@ WebMediaConstraints ParseOptions(ExecutionContext* context,
if (options.IsNull()) {
// Do nothing.
} else if (options.IsMediaTrackConstraints()) {
- constraints = MediaConstraintsImpl::Create(
+ constraints = media_constraints_impl::Create(
context, options.GetAsMediaTrackConstraints(), error_state);
} else {
DCHECK(options.IsBoolean());
if (options.GetAsBoolean()) {
- constraints = MediaConstraintsImpl::Create();
+ constraints = media_constraints_impl::Create();
}
}
@@ -317,9 +317,13 @@ class UserMediaRequest::V8Callbacks final : public UserMediaRequest::Callbacks {
static V8Callbacks* Create(
V8NavigatorUserMediaSuccessCallback* success_callback,
V8NavigatorUserMediaErrorCallback* error_callback) {
- return new V8Callbacks(success_callback, error_callback);
+ return MakeGarbageCollected<V8Callbacks>(success_callback, error_callback);
}
+ V8Callbacks(V8NavigatorUserMediaSuccessCallback* success_callback,
+ V8NavigatorUserMediaErrorCallback* error_callback)
+ : success_callback_(ToV8PersistentCallbackFunction(success_callback)),
+ error_callback_(ToV8PersistentCallbackFunction(error_callback)) {}
~V8Callbacks() override = default;
void Trace(blink::Visitor* visitor) override {
@@ -338,11 +342,6 @@ class UserMediaRequest::V8Callbacks final : public UserMediaRequest::Callbacks {
}
private:
- V8Callbacks(V8NavigatorUserMediaSuccessCallback* success_callback,
- V8NavigatorUserMediaErrorCallback* error_callback)
- : success_callback_(ToV8PersistentCallbackFunction(success_callback)),
- error_callback_(ToV8PersistentCallbackFunction(error_callback)) {}
-
// As Blink does not hold a UserMediaRequest and lets content/ hold it,
// we cannot use wrapper-tracing to keep the underlying callback functions.
// Plus, it's guaranteed that the callbacks are one-shot type (not repeated
@@ -358,39 +357,61 @@ UserMediaRequest* UserMediaRequest::Create(
ExecutionContext* context,
UserMediaController* controller,
WebUserMediaRequest::MediaType media_type,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
Callbacks* callbacks,
MediaErrorState& error_state) {
WebMediaConstraints audio =
- ParseOptions(context, options.audio(), error_state);
+ ParseOptions(context, options->audio(), error_state);
if (error_state.HadException())
return nullptr;
WebMediaConstraints video =
- ParseOptions(context, options.video(), error_state);
+ ParseOptions(context, options->video(), error_state);
if (error_state.HadException())
return nullptr;
if (media_type == WebUserMediaRequest::MediaType::kDisplayMedia) {
- // TODO(emircan): Support constraints after the spec change.
- // https://w3c.github.io/mediacapture-screen-share/#constraints
- // 5.2 Constraining Display Surface Selection
- // The getDisplayMedia function does not permit the use of constraints for
- // selection of a source as described in the getUserMedia() algorithm.
- // Prior to invoking the getUserMedia() algorithm, if either of the video
- // and audio attributes are set to a MediaTrackConstraints value (as
- // opposed to being absent or set to a Boolean value), reject the promise
- // with a InvalidAccessError and abort.
- if (options.audio().IsMediaTrackConstraints() ||
- options.video().IsMediaTrackConstraints()) {
- error_state.ThrowDOMException(
- DOMExceptionCode::kInvalidAccessError,
- "getDisplayMedia() does not permit the use of constraints.");
+ // https://w3c.github.io/mediacapture-screen-share/#navigator-additions
+ // 5.1 Navigator Additions
+ // 1. Let constraints be the method's first argument.
+ // 2. For each member present in constraints whose value, value, is a
+ // dictionary, run the following steps:
+ // 1. If value contains a member named advanced, return a promise rejected
+ // with a newly created TypeError.
+ // 2. If value contains a member which in turn is a dictionary containing
+ // a member named either min or exact, return a promise rejected with a
+ // newly created TypeError.
+ // 3. Let requestedMediaTypes be the set of media types in constraints with
+ // either a dictionary value or a value of true.
+ // 4. If requestedMediaTypes is the empty set, set requestedMediaTypes to a
+ // set containing "video".
+ if ((!audio.IsNull() && !audio.Advanced().empty()) ||
+ (!video.IsNull() && !video.Advanced().empty())) {
+ error_state.ThrowTypeError("Advanced constraints are not supported");
+ return nullptr;
+ }
+ if ((!audio.IsNull() && audio.Basic().HasMin()) ||
+ (!video.IsNull() && video.Basic().HasMin())) {
+ error_state.ThrowTypeError("min constraints are not supported");
return nullptr;
}
- // TODO(emircan): Enable when audio capture is supported.
- if (!options.audio().IsNull() && options.audio().GetAsBoolean()) {
- error_state.ThrowTypeError("Audio is not supported");
+ if ((!audio.IsNull() && audio.Basic().HasExact()) ||
+ (!video.IsNull() && video.Basic().HasExact())) {
+ error_state.ThrowTypeError("exact constraints are not supported");
+ return nullptr;
+ }
+ if (audio.IsNull() && video.IsNull()) {
+ video = ParseOptions(context,
+ BooleanOrMediaTrackConstraints::FromBoolean(true),
+ error_state);
+ if (error_state.HadException())
+ return nullptr;
+ }
+
+ // TODO(emircan): Enable when audio capture is actually supported, see
+ // https://crbug.com/896333.
+ if (!options->audio().IsNull() && options->audio().GetAsBoolean()) {
+ error_state.ThrowTypeError("Audio capture is not supported");
return nullptr;
}
}
@@ -406,14 +427,14 @@ UserMediaRequest* UserMediaRequest::Create(
if (!video.IsNull())
CountVideoConstraintUses(context, video);
- return new UserMediaRequest(context, controller, media_type, audio, video,
- callbacks);
+ return MakeGarbageCollected<UserMediaRequest>(context, controller, media_type,
+ audio, video, callbacks);
}
UserMediaRequest* UserMediaRequest::Create(
ExecutionContext* context,
UserMediaController* controller,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
V8NavigatorUserMediaSuccessCallback* success_callback,
V8NavigatorUserMediaErrorCallback* error_callback,
MediaErrorState& error_state) {
@@ -425,9 +446,9 @@ UserMediaRequest* UserMediaRequest::Create(
UserMediaRequest* UserMediaRequest::CreateForTesting(
const WebMediaConstraints& audio,
const WebMediaConstraints& video) {
- return new UserMediaRequest(nullptr, nullptr,
- WebUserMediaRequest::MediaType::kUserMedia, audio,
- video, nullptr);
+ return MakeGarbageCollected<UserMediaRequest>(
+ nullptr, nullptr, WebUserMediaRequest::MediaType::kUserMedia, audio,
+ video, nullptr);
}
UserMediaRequest::UserMediaRequest(ExecutionContext* context,
@@ -441,14 +462,14 @@ UserMediaRequest::UserMediaRequest(ExecutionContext* context,
audio_(audio),
video_(video),
should_disable_hardware_noise_suppression_(
- OriginTrials::DisableHardwareNoiseSuppressionEnabled(context)),
+ origin_trials::DisableHardwareNoiseSuppressionEnabled(context)),
controller_(controller),
callbacks_(callbacks) {
if (should_disable_hardware_noise_suppression_) {
UseCounter::Count(context,
WebFeature::kUserMediaDisableHardwareNoiseSuppression);
}
- if (OriginTrials::ExperimentalHardwareEchoCancellationEnabled(context)) {
+ if (origin_trials::ExperimentalHardwareEchoCancellationEnabled(context)) {
UseCounter::Count(
context,
WebFeature::kUserMediaEnableExperimentalHardwareEchoCancellation);
diff --git a/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.h b/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.h
index 4809285a8e2..5afb383f6dc 100644
--- a/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.h
+++ b/chromium/third_party/blink/renderer/modules/mediastream/user_media_request.h
@@ -74,17 +74,24 @@ class MODULES_EXPORT UserMediaRequest final
static UserMediaRequest* Create(ExecutionContext*,
UserMediaController*,
WebUserMediaRequest::MediaType media_type,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
Callbacks*,
MediaErrorState&);
static UserMediaRequest* Create(ExecutionContext*,
UserMediaController*,
- const MediaStreamConstraints& options,
+ const MediaStreamConstraints* options,
V8NavigatorUserMediaSuccessCallback*,
V8NavigatorUserMediaErrorCallback*,
MediaErrorState&);
static UserMediaRequest* CreateForTesting(const WebMediaConstraints& audio,
const WebMediaConstraints& video);
+
+ UserMediaRequest(ExecutionContext*,
+ UserMediaController*,
+ WebUserMediaRequest::MediaType media_type,
+ WebMediaConstraints audio,
+ WebMediaConstraints video,
+ Callbacks*);
virtual ~UserMediaRequest();
Document* OwnerDocument();
@@ -115,13 +122,6 @@ class MODULES_EXPORT UserMediaRequest final
void Trace(blink::Visitor*) override;
private:
- UserMediaRequest(ExecutionContext*,
- UserMediaController*,
- WebUserMediaRequest::MediaType media_type,
- WebMediaConstraints audio,
- WebMediaConstraints video,
- Callbacks*);
-
WebUserMediaRequest::MediaType media_type_;
WebMediaConstraints audio_;
WebMediaConstraints video_;
diff --git a/chromium/third_party/blink/renderer/modules/modules_idl_files.gni b/chromium/third_party/blink/renderer/modules/modules_idl_files.gni
index c97681e4079..ce6f8931996 100644
--- a/chromium/third_party/blink/renderer/modules/modules_idl_files.gni
+++ b/chromium/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -63,13 +63,13 @@ modules_idl_files =
"animationworklet/animation_worklet_global_scope.idl",
"animationworklet/effect_proxy.idl",
"animationworklet/worklet_animation.idl",
+ "animationworklet/worklet_group_effect_proxy.idl",
"app_banner/before_install_prompt_event.idl",
"background_fetch/background_fetch_event.idl",
"background_fetch/background_fetch_fetch.idl",
"background_fetch/background_fetch_manager.idl",
"background_fetch/background_fetch_record.idl",
"background_fetch/background_fetch_registration.idl",
- "background_fetch/background_fetch_settled_fetch.idl",
"background_fetch/background_fetch_update_ui_event.idl",
"background_sync/sync_event.idl",
"background_sync/sync_manager.idl",
@@ -93,6 +93,8 @@ modules_idl_files =
"canvas/imagebitmap/image_bitmap_rendering_context.idl",
"canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.idl",
"clipboard/clipboard.idl",
+ "contacts_picker/contact_info.idl",
+ "contacts_picker/contacts_manager.idl",
"cookie_store/cookie_change_event.idl",
"cookie_store/cookie_store.idl",
"cookie_store/extendable_cookie_change_event.idl",
@@ -151,7 +153,9 @@ modules_idl_files =
"filesystem/metadata.idl",
"filesystem/metadata_callback.idl",
"gamepad/gamepad.idl",
+ "gamepad/gamepad_axis_event.idl",
"gamepad/gamepad_button.idl",
+ "gamepad/gamepad_button_event.idl",
"gamepad/gamepad_event.idl",
"gamepad/gamepad_haptic_actuator.idl",
"gamepad/gamepad_list.idl",
@@ -183,7 +187,6 @@ modules_idl_files =
"locks/lock.idl",
"locks/lock_manager.idl",
"media_capabilities/media_capabilities.idl",
- "media_capabilities/media_capabilities_info.idl",
"mediacapturefromelement/canvas_capture_media_stream_track.idl",
"mediarecorder/blob_event.idl",
"mediarecorder/media_recorder.idl",
@@ -220,6 +223,7 @@ modules_idl_files =
"peerconnection/rtc_certificate.idl",
"peerconnection/rtc_data_channel.idl",
"peerconnection/rtc_data_channel_event.idl",
+ "peerconnection/rtc_dtls_transport.idl",
"peerconnection/rtc_dtmf_sender.idl",
"peerconnection/rtc_dtmf_tone_change_event.idl",
"peerconnection/rtc_ice_candidate.idl",
@@ -489,6 +493,7 @@ modules_dictionary_idl_files =
"canvas/canvas2d/canvas_rendering_context_2d_settings.idl",
"canvas/canvas2d/hit_region_options.idl",
"canvas/htmlcanvas/canvas_context_creation_attributes_module.idl",
+ "contacts_picker/contacts_select_options.idl",
"cookie_store/cookie_change_event_init.idl",
"cookie_store/cookie_list_item.idl",
"cookie_store/cookie_store_delete_options.idl",
@@ -535,12 +540,15 @@ modules_dictionary_idl_files =
"filesystem/file_system_get_directory_options.idl",
"filesystem/file_system_get_file_options.idl",
"filesystem/get_system_directory_options.idl",
+ "gamepad/gamepad_axis_event_init.idl",
+ "gamepad/gamepad_button_event_init.idl",
"gamepad/gamepad_effect_parameters.idl",
"gamepad/gamepad_event_init.idl",
"geolocation/position_options.idl",
"imagecapture/constrain_point_2d_parameters.idl",
"imagecapture/photo_settings.idl",
"imagecapture/point_2d.idl",
+ "indexeddb/idb_database_info.idl",
"indexeddb/idb_index_parameters.idl",
"indexeddb/idb_object_store_parameters.idl",
"indexeddb/idb_observer_init.idl",
@@ -551,6 +559,9 @@ modules_dictionary_idl_files =
"manifest/image_resource.idl",
"media_capabilities/audio_configuration.idl",
"media_capabilities/media_configuration.idl",
+ "media_capabilities/media_capabilities_decoding_info.idl",
+ "media_capabilities/media_capabilities_info.idl",
+ "media_capabilities/media_capabilities_key_system_configuration.idl",
"media_capabilities/media_decoding_configuration.idl",
"media_capabilities/media_encoding_configuration.idl",
"media_capabilities/video_configuration.idl",
@@ -618,6 +629,7 @@ modules_dictionary_idl_files =
"peerconnection/rtc_peer_connection_ice_event_init.idl",
"peerconnection/rtc_quic_parameters.idl",
"peerconnection/rtc_quic_stream_event_init.idl",
+ "peerconnection/rtc_quic_stream_read_result.idl",
"peerconnection/rtc_rtcp_parameters.idl",
"peerconnection/rtc_rtp_capabilities.idl",
"peerconnection/rtc_rtp_codec_capability.idl",
@@ -642,6 +654,7 @@ modules_dictionary_idl_files =
"push_messaging/push_event_init.idl",
"push_messaging/push_subscription_options_init.idl",
"quota/storage_estimate.idl",
+ "quota/storage_usage_details.idl",
"sensor/sensor_error_event_init.idl",
"sensor/sensor_options.idl",
"sensor/spatial_sensor_options.idl",
@@ -728,6 +741,7 @@ modules_dependency_idl_files =
"cache_storage/worker_cache_storage.idl",
"canvas/canvas2d/canvas_path.idl",
"clipboard/navigator_clipboard.idl",
+ "contacts_picker/navigator_contacts.idl",
"cookie_store/service_worker_global_scope_cookie_store.idl",
"cookie_store/window_cookie_store.idl",
"credentialmanager/credential_user_data.idl",
@@ -764,7 +778,6 @@ modules_dependency_idl_files =
"mediasource/url_media_source.idl",
"mediasource/video_track_source_buffer.idl",
"mediastream/media_stream_track_content_hint.idl",
- "mediastream/navigator_display_media.idl",
"mediastream/navigator_media_stream.idl",
"mediastream/navigator_user_media.idl",
"mediastream/window_media_stream.idl",
diff --git a/chromium/third_party/blink/renderer/modules/modules_initializer.cc b/chromium/third_party/blink/renderer/modules/modules_initializer.cc
index 82b006bfe0f..0774044b411 100644
--- a/chromium/third_party/blink/renderer/modules/modules_initializer.cc
+++ b/chromium/third_party/blink/renderer/modules/modules_initializer.cc
@@ -22,18 +22,16 @@
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
-#include "third_party/blink/renderer/core/inspector/inspector_session.h"
+#include "third_party/blink/renderer/core/inspector/devtools_session.h"
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
+#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/workers/worker_clients.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h"
#include "third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h"
-#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h"
#include "third_party/blink/renderer/modules/app_banner/app_banner_controller.h"
-#include "third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client.h"
-#include "third_party/blink/renderer/modules/audio_output_devices/audio_output_device_client_impl.h"
#include "third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.h"
#include "third_party/blink/renderer/modules/cache_storage/inspector_cache_storage_agent.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h"
@@ -47,8 +45,8 @@
#include "third_party/blink/renderer/modules/document_metadata/copyless_paste_server.h"
#include "third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.h"
#include "third_party/blink/renderer/modules/encryptedmedia/media_keys_controller.h"
+#include "third_party/blink/renderer/modules/event_interface_modules_names.h"
#include "third_party/blink/renderer/modules/event_modules_factory.h"
-#include "third_party/blink/renderer/modules/event_modules_names.h"
#include "third_party/blink/renderer/modules/event_target_modules_names.h"
#include "third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h"
#include "third_party/blink/renderer/modules/filesystem/dragged_isolated_file_system_impl.h"
@@ -83,31 +81,33 @@
#include "third_party/blink/renderer/modules/webdatabase/database_manager.h"
#include "third_party/blink/renderer/modules/webdatabase/inspector_database_agent.h"
#include "third_party/blink/renderer/modules/webdatabase/web_database_impl.h"
+#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
#if defined(SUPPORT_WEBGL2_COMPUTE_CONTEXT)
#include "third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.h"
#endif
+#include "third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h"
#include "third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h"
#include "third_party/blink/renderer/modules/webgl/webgl_rendering_context.h"
#include "third_party/blink/renderer/modules/xr/xr_presentation_context.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/mojo/mojo_helper.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
void ModulesInitializer::Initialize() {
// Strings must be initialized before calling CoreInitializer::init().
const unsigned kModulesStaticStringsCount =
- EventNames::EventModulesNamesCount +
- EventTargetNames::EventTargetModulesNamesCount +
- IndexedDBNames::IndexedDBNamesCount;
+ event_interface_names::kModulesNamesCount +
+ event_target_names::kModulesNamesCount + indexed_db_names::kNamesCount;
StringImpl::ReserveStaticStringsCapacityForSize(kModulesStaticStringsCount);
- EventNames::initModules();
- EventTargetNames::initModules();
+ event_interface_names::InitModules();
+ event_target_names::InitModules();
Document::RegisterEventFactory(EventModulesFactory::Create());
ModuleBindingsInitializer::Init();
- IndexedDBNames::init();
+ indexed_db_names::Init();
AXObjectCache::Init(AXObjectCacheImpl::Create);
DraggedIsolatedFileSystem::Init(
DraggedIsolatedFileSystemImpl::PrepareForDataObject);
@@ -182,12 +182,9 @@ void ModulesInitializer::InstallSupplements(LocalFrame& frame) const {
ScreenOrientationControllerImpl::ProvideTo(frame);
if (RuntimeEnabledFeatures::PresentationEnabled())
PresentationController::ProvideTo(frame);
- if (RuntimeEnabledFeatures::AudioOutputDevicesEnabled()) {
- ProvideAudioOutputDeviceClientTo(frame,
- new AudioOutputDeviceClientImpl(frame));
- }
InstalledAppController::ProvideTo(frame, client->GetRelatedAppsFetcher());
::blink::ProvideSpeechRecognitionTo(frame);
+ InspectorAccessibilityAgent::ProvideTo(&frame);
}
void ModulesInitializer::ProvideLocalFileSystemToWorker(
@@ -214,18 +211,21 @@ ModulesInitializer::CreatePictureInPictureController(Document& document) const {
}
void ModulesInitializer::InitInspectorAgentSession(
- InspectorSession* session,
+ DevToolsSession* session,
bool allow_view_agents,
InspectorDOMAgent* dom_agent,
InspectedFrames* inspected_frames,
Page* page) const {
+ session->Append(MakeGarbageCollected<InspectorIndexedDBAgent>(
+ inspected_frames, session->V8Session()));
+ session->Append(
+ MakeGarbageCollected<DeviceOrientationInspectorAgent>(inspected_frames));
session->Append(
- new InspectorIndexedDBAgent(inspected_frames, session->V8Session()));
- session->Append(new DeviceOrientationInspectorAgent(inspected_frames));
- session->Append(new InspectorDOMStorageAgent(inspected_frames));
+ MakeGarbageCollected<InspectorDOMStorageAgent>(inspected_frames));
if (allow_view_agents) {
session->Append(InspectorDatabaseAgent::Create(page));
- session->Append(new InspectorAccessibilityAgent(inspected_frames, dom_agent));
+ session->Append(MakeGarbageCollected<InspectorAccessibilityAgent>(
+ inspected_frames, dom_agent));
session->Append(InspectorCacheStorageAgent::Create(inspected_frames));
}
}
@@ -239,7 +239,7 @@ void ModulesInitializer::OnClearWindowObjectInMainWorld(
NavigatorGamepad::From(document);
NavigatorServiceWorker::From(document);
DOMWindowStorageController::From(document);
- if (OriginTrials::WebVREnabled(document.GetExecutionContext()))
+ if (origin_trials::WebVREnabled(document.GetExecutionContext()))
NavigatorVR::From(document);
if (RuntimeEnabledFeatures::PresentationEnabled() &&
settings.GetPresentationReceiver()) {
@@ -281,8 +281,16 @@ void ModulesInitializer::ForceNextWebGLContextCreationToFail() const {
WebGLRenderingContext::ForceNextWebGLContextCreationToFail();
}
-void ModulesInitializer::CollectAllGarbageForAnimationWorklet() const {
- AnimationWorkletThread::CollectAllGarbage();
+void ModulesInitializer::CollectAllGarbageForAnimationAndPaintWorklet() const {
+ AnimationAndPaintWorkletThread::CollectAllGarbage();
+}
+
+void ModulesInitializer::CloneSessionStorage(
+ Page* clone_from_page,
+ const SessionStorageNamespaceId& clone_to_namespace) {
+ StorageNamespace* storage_namespace = StorageNamespace::From(clone_from_page);
+ if (storage_namespace)
+ storage_namespace->CloneTo(WebString::FromLatin1(clone_to_namespace));
}
void ModulesInitializer::RegisterInterfaces(
diff --git a/chromium/third_party/blink/renderer/modules/modules_initializer.h b/chromium/third_party/blink/renderer/modules/modules_initializer.h
index 4a0fea1b936..e67c306cd14 100644
--- a/chromium/third_party/blink/renderer/modules/modules_initializer.h
+++ b/chromium/third_party/blink/renderer/modules/modules_initializer.h
@@ -28,7 +28,7 @@ class MODULES_EXPORT ModulesInitializer : public CoreInitializer {
ShadowRoot&) const override;
PictureInPictureController* CreatePictureInPictureController(
Document&) const override;
- void InitInspectorAgentSession(InspectorSession*,
+ void InitInspectorAgentSession(DevToolsSession*,
bool,
InspectorDOMAgent*,
InspectedFrames*,
@@ -45,7 +45,11 @@ class MODULES_EXPORT ModulesInitializer : public CoreInitializer {
void ProvideModulesToPage(Page&, WebViewClient*) const override;
void ForceNextWebGLContextCreationToFail() const override;
- void CollectAllGarbageForAnimationWorklet() const override;
+ void CollectAllGarbageForAnimationAndPaintWorklet() const override;
+
+ void CloneSessionStorage(
+ Page* clone_from_page,
+ const SessionStorageNamespaceId& clone_to_namespace) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc
index e62eb4a998d..d333b14e3f5 100644
--- a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc
+++ b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.cc
@@ -92,7 +92,7 @@ static bool IsSchemeWhitelisted(const String& scheme) {
InitCustomSchemeHandlerWhitelist();
StringBuilder builder;
- builder.Append(scheme.DeprecatedLower().Ascii().data());
+ builder.Append(scheme.LowerASCII());
return g_scheme_whitelist->Contains(builder.ToString());
}
@@ -192,7 +192,8 @@ const char NavigatorContentUtils::kSupplementName[] = "NavigatorContentUtils";
void NavigatorContentUtils::ProvideTo(Navigator& navigator,
NavigatorContentUtilsClient* client) {
Supplement<Navigator>::ProvideTo(
- navigator, new NavigatorContentUtils(navigator, client));
+ navigator,
+ MakeGarbageCollected<NavigatorContentUtils>(navigator, client));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.h b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.h
index 50075545da6..c8044252b26 100644
--- a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.h
+++ b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils.h
@@ -46,6 +46,9 @@ class MODULES_EXPORT NavigatorContentUtils final
public:
static const char kSupplementName[];
+ NavigatorContentUtils(Navigator& navigator,
+ NavigatorContentUtilsClient* client)
+ : Supplement<Navigator>(navigator), client_(client) {}
virtual ~NavigatorContentUtils();
static NavigatorContentUtils* From(Navigator&);
@@ -69,10 +72,6 @@ class MODULES_EXPORT NavigatorContentUtils final
}
private:
- NavigatorContentUtils(Navigator& navigator,
- NavigatorContentUtilsClient* client)
- : Supplement<Navigator>(navigator), client_(client) {}
-
NavigatorContentUtilsClient* Client() { return client_.Get(); }
Member<NavigatorContentUtilsClient> client_;
diff --git a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.cc b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.cc
index dadaead7c8e..47c96929032 100644
--- a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.cc
+++ b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.cc
@@ -12,7 +12,7 @@ namespace blink {
NavigatorContentUtilsClient* NavigatorContentUtilsClient::Create(
WebLocalFrameImpl* web_frame) {
- return new NavigatorContentUtilsClient(web_frame);
+ return MakeGarbageCollected<NavigatorContentUtilsClient>(web_frame);
}
NavigatorContentUtilsClient::NavigatorContentUtilsClient(
diff --git a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.h b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.h
index 0b0fb2d5f4f..be6ef1822e4 100644
--- a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.h
+++ b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/navigator_content_utils_client.h
@@ -18,6 +18,8 @@ class MODULES_EXPORT NavigatorContentUtilsClient
: public GarbageCollectedFinalized<NavigatorContentUtilsClient> {
public:
static NavigatorContentUtilsClient* Create(WebLocalFrameImpl*);
+
+ explicit NavigatorContentUtilsClient(WebLocalFrameImpl*);
virtual ~NavigatorContentUtilsClient() = default;
virtual void RegisterProtocolHandler(const String& scheme,
@@ -28,9 +30,6 @@ class MODULES_EXPORT NavigatorContentUtilsClient
virtual void Trace(blink::Visitor*);
- protected:
- explicit NavigatorContentUtilsClient(WebLocalFrameImpl*);
-
private:
Member<WebLocalFrameImpl> web_frame_;
};
diff --git a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/testing/navigator_content_utils_client_mock.h b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/testing/navigator_content_utils_client_mock.h
index 87062c64f2f..bbdb43d0d56 100644
--- a/chromium/third_party/blink/renderer/modules/navigatorcontentutils/testing/navigator_content_utils_client_mock.h
+++ b/chromium/third_party/blink/renderer/modules/navigatorcontentutils/testing/navigator_content_utils_client_mock.h
@@ -18,9 +18,12 @@ class NavigatorContentUtilsClientMock final
: public NavigatorContentUtilsClient {
public:
static NavigatorContentUtilsClientMock* Create() {
- return new NavigatorContentUtilsClientMock;
+ return MakeGarbageCollected<NavigatorContentUtilsClientMock>();
}
+ // TODO(sashab): Make NavigatorContentUtilsClientMock non-virtual and test it
+ // using a WebLocalFrameClient mock.
+ NavigatorContentUtilsClientMock() : NavigatorContentUtilsClient(nullptr) {}
~NavigatorContentUtilsClientMock() override = default;
void RegisterProtocolHandler(const String& scheme,
@@ -30,10 +33,6 @@ class NavigatorContentUtilsClientMock final
void UnregisterProtocolHandler(const String& scheme, const KURL&) override;
private:
- // TODO(sashab): Make NavigatorContentUtilsClientMock non-virtual and test it
- // using a WebLocalFrameClient mock.
- NavigatorContentUtilsClientMock() : NavigatorContentUtilsClient(nullptr) {}
-
typedef struct {
String scheme;
KURL url;
diff --git a/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.cc b/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.cc
index 2f361747502..0b2e26163fd 100644
--- a/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.cc
+++ b/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.cc
@@ -19,7 +19,7 @@ NavigatorNetworkInformation& NavigatorNetworkInformation::From(
NavigatorNetworkInformation* supplement =
ToNavigatorNetworkInformation(navigator);
if (!supplement) {
- supplement = new NavigatorNetworkInformation(navigator);
+ supplement = MakeGarbageCollected<NavigatorNetworkInformation>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.h b/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.h
index 2ba20a3832a..5156a82c860 100644
--- a/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.h
+++ b/chromium/third_party/blink/renderer/modules/netinfo/navigator_network_information.h
@@ -27,10 +27,11 @@ class NavigatorNetworkInformation final
static NavigatorNetworkInformation* ToNavigatorNetworkInformation(Navigator&);
static NetworkInformation* connection(Navigator&);
+ explicit NavigatorNetworkInformation(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorNetworkInformation(Navigator&);
NetworkInformation* connection();
Member<NetworkInformation> connection_;
diff --git a/chromium/third_party/blink/renderer/modules/netinfo/network_information.cc b/chromium/third_party/blink/renderer/modules/netinfo/network_information.cc
index 7597be853ed..fe217c7c313 100644
--- a/chromium/third_party/blink/renderer/modules/netinfo/network_information.cc
+++ b/chromium/third_party/blink/renderer/modules/netinfo/network_information.cc
@@ -74,7 +74,7 @@ String GetConsoleLogStringForWebHoldback() {
} // namespace
NetworkInformation* NetworkInformation::Create(ExecutionContext* context) {
- return new NetworkInformation(context);
+ return MakeGarbageCollected<NetworkInformation>(context);
}
NetworkInformation::~NetworkInformation() {
@@ -216,12 +216,12 @@ void NetworkInformation::ConnectionChange(
save_data_ = save_data;
if (type_changed)
- DispatchEvent(*Event::Create(EventTypeNames::typechange));
- DispatchEvent(*Event::Create(EventTypeNames::change));
+ DispatchEvent(*Event::Create(event_type_names::kTypechange));
+ DispatchEvent(*Event::Create(event_type_names::kChange));
}
const AtomicString& NetworkInformation::InterfaceName() const {
- return EventTargetNames::NetworkInformation;
+ return event_target_names::kNetworkInformation;
}
ExecutionContext* NetworkInformation::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/netinfo/network_information.h b/chromium/third_party/blink/renderer/modules/netinfo/network_information.h
index b8170e43fcd..5e605a4eece 100644
--- a/chromium/third_party/blink/renderer/modules/netinfo/network_information.h
+++ b/chromium/third_party/blink/renderer/modules/netinfo/network_information.h
@@ -28,6 +28,8 @@ class NetworkInformation final
public:
static NetworkInformation* Create(ExecutionContext*);
+
+ explicit NetworkInformation(ExecutionContext*);
~NetworkInformation() override;
String type() const;
@@ -59,8 +61,8 @@ class NetworkInformation final
void Trace(blink::Visitor*) override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(typechange); // Deprecated
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(typechange, kTypechange); // Deprecated
protected:
// EventTarget overrides.
@@ -70,7 +72,6 @@ class NetworkInformation final
const RegisteredEventListener&) final;
private:
- explicit NetworkInformation(ExecutionContext*);
void StartObserving();
void StopObserving();
diff --git a/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.cc b/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.cc
index 2c182dfe619..cca89beef05 100644
--- a/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.cc
+++ b/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.cc
@@ -22,7 +22,8 @@ WorkerNavigatorNetworkInformation& WorkerNavigatorNetworkInformation::From(
WorkerNavigatorNetworkInformation* supplement =
ToWorkerNavigatorNetworkInformation(navigator, context);
if (!supplement) {
- supplement = new WorkerNavigatorNetworkInformation(navigator, context);
+ supplement = MakeGarbageCollected<WorkerNavigatorNetworkInformation>(
+ navigator, context);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.h b/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.h
index 0a5898cc774..9a6a9615caa 100644
--- a/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.h
+++ b/chromium/third_party/blink/renderer/modules/netinfo/worker_navigator_network_information.h
@@ -31,10 +31,11 @@ class WorkerNavigatorNetworkInformation final
static NetworkInformation* connection(ScriptState*, WorkerNavigator&);
+ WorkerNavigatorNetworkInformation(WorkerNavigator&, ExecutionContext*);
+
void Trace(blink::Visitor*) override;
private:
- WorkerNavigatorNetworkInformation(WorkerNavigator&, ExecutionContext*);
NetworkInformation* connection(ExecutionContext*);
Member<NetworkInformation> connection_;
diff --git a/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.cc b/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.cc
index 8a08fe21fa6..7cd57186d79 100644
--- a/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.cc
+++ b/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.cc
@@ -18,7 +18,7 @@ NavigatorNFC& NavigatorNFC::From(Navigator& navigator) {
NavigatorNFC* supplement =
Supplement<Navigator>::From<NavigatorNFC>(navigator);
if (!supplement) {
- supplement = new NavigatorNFC(navigator);
+ supplement = MakeGarbageCollected<NavigatorNFC>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.h b/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.h
index f0bb42b5305..724252aa0da 100644
--- a/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.h
+++ b/chromium/third_party/blink/renderer/modules/nfc/navigator_nfc.h
@@ -26,11 +26,11 @@ class NavigatorNFC final : public GarbageCollected<NavigatorNFC>,
static NFC* nfc(Navigator&);
+ explicit NavigatorNFC(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorNFC(Navigator&);
-
TraceWrapperMember<NFC> nfc_;
};
diff --git a/chromium/third_party/blink/renderer/modules/nfc/nfc.cc b/chromium/third_party/blink/renderer/modules/nfc/nfc.cc
index 282d7b54c03..5a41f334447 100644
--- a/chromium/third_party/blink/renderer/modules/nfc/nfc.cc
+++ b/chromium/third_party/blink/renderer/modules/nfc/nfc.cc
@@ -95,9 +95,9 @@ NFCWatchMode toNFCWatchMode(const String& watchMode) {
// String or Number => 'text' record
// ArrayBuffer => 'opaque' record
// JSON serializable Object => 'json' record
-NFCRecordType deduceRecordTypeFromDataType(const blink::NFCRecord& record) {
- if (record.hasData()) {
- v8::Local<v8::Value> value = record.data().V8Value();
+NFCRecordType deduceRecordTypeFromDataType(const blink::NFCRecord* record) {
+ if (record->hasData()) {
+ v8::Local<v8::Value> value = record->data().V8Value();
if (value->IsString() ||
(value->IsNumber() && !std::isnan(value.As<v8::Number>()->Value()))) {
@@ -220,12 +220,12 @@ struct TypeConverter<base::Optional<Vector<uint8_t>>, blink::ScriptValue> {
};
template <>
-struct TypeConverter<NFCRecordPtr, blink::NFCRecord> {
- static NFCRecordPtr Convert(const blink::NFCRecord& record) {
+struct TypeConverter<NFCRecordPtr, blink::NFCRecord*> {
+ static NFCRecordPtr Convert(const blink::NFCRecord* record) {
NFCRecordPtr recordPtr = NFCRecord::New();
- if (record.hasRecordType())
- recordPtr->record_type = toNFCRecordType(record.recordType());
+ if (record->hasRecordType())
+ recordPtr->record_type = toNFCRecordType(record->recordType());
else
recordPtr->record_type = deduceRecordTypeFromDataType(record);
@@ -237,14 +237,14 @@ struct TypeConverter<NFCRecordPtr, blink::NFCRecord> {
switch (recordPtr->record_type) {
case NFCRecordType::TEXT:
case NFCRecordType::URL:
- setMediaType(recordPtr, record.mediaType(), kPlainTextMimeType);
+ setMediaType(recordPtr, record->mediaType(), kPlainTextMimeType);
recordPtr->media_type.append(kCharSetUTF8);
break;
case NFCRecordType::JSON:
- setMediaType(recordPtr, record.mediaType(), kJsonMimeType);
+ setMediaType(recordPtr, record->mediaType(), kJsonMimeType);
break;
case NFCRecordType::OPAQUE_RECORD:
- setMediaType(recordPtr, record.mediaType(), kOpaqueMimeType);
+ setMediaType(recordPtr, record->mediaType(), kOpaqueMimeType);
break;
default:
NOTREACHED();
@@ -252,7 +252,7 @@ struct TypeConverter<NFCRecordPtr, blink::NFCRecord> {
}
auto recordData =
- mojo::ConvertTo<base::Optional<Vector<uint8_t>>>(record.data());
+ mojo::ConvertTo<base::Optional<Vector<uint8_t>>>(record->data());
// If JS object cannot be converted to uint8_t array, return null,
// interrupt NFCMessage conversion algorithm and reject promise with
// SyntaxError exception.
@@ -265,13 +265,13 @@ struct TypeConverter<NFCRecordPtr, blink::NFCRecord> {
};
template <>
-struct TypeConverter<NFCMessagePtr, blink::NFCMessage> {
- static NFCMessagePtr Convert(const blink::NFCMessage& message) {
+struct TypeConverter<NFCMessagePtr, blink::NFCMessage*> {
+ static NFCMessagePtr Convert(const blink::NFCMessage* message) {
NFCMessagePtr messagePtr = NFCMessage::New();
- messagePtr->url = message.url();
- messagePtr->data.resize(message.records().size());
- for (wtf_size_t i = 0; i < message.records().size(); ++i) {
- NFCRecordPtr record = NFCRecord::From(message.records()[i]);
+ messagePtr->url = message->url();
+ messagePtr->data.resize(message->records().size());
+ for (wtf_size_t i = 0; i < message->records().size(); ++i) {
+ NFCRecordPtr record = NFCRecord::From(message->records()[i].Get());
if (record.is_null())
return nullptr;
@@ -308,25 +308,25 @@ struct TypeConverter<NFCMessagePtr, blink::NFCPushMessage> {
};
template <>
-struct TypeConverter<NFCPushOptionsPtr, blink::NFCPushOptions> {
- static NFCPushOptionsPtr Convert(const blink::NFCPushOptions& pushOptions) {
+struct TypeConverter<NFCPushOptionsPtr, const blink::NFCPushOptions*> {
+ static NFCPushOptionsPtr Convert(const blink::NFCPushOptions* pushOptions) {
// https://w3c.github.io/web-nfc/#the-nfcpushoptions-dictionary
// Default values for NFCPushOptions dictionary are:
// target = 'any', timeout = Infinity, ignoreRead = true
NFCPushOptionsPtr pushOptionsPtr = NFCPushOptions::New();
- if (pushOptions.hasTarget())
- pushOptionsPtr->target = toNFCPushTarget(pushOptions.target());
+ if (pushOptions->hasTarget())
+ pushOptionsPtr->target = toNFCPushTarget(pushOptions->target());
else
pushOptionsPtr->target = NFCPushTarget::ANY;
- if (pushOptions.hasTimeout())
- pushOptionsPtr->timeout = pushOptions.timeout();
+ if (pushOptions->hasTimeout())
+ pushOptionsPtr->timeout = pushOptions->timeout();
else
pushOptionsPtr->timeout = std::numeric_limits<double>::infinity();
- if (pushOptions.hasIgnoreRead())
- pushOptionsPtr->ignore_read = pushOptions.ignoreRead();
+ if (pushOptions->hasIgnoreRead())
+ pushOptionsPtr->ignore_read = pushOptions->ignoreRead();
else
pushOptionsPtr->ignore_read = true;
@@ -335,25 +335,25 @@ struct TypeConverter<NFCPushOptionsPtr, blink::NFCPushOptions> {
};
template <>
-struct TypeConverter<NFCWatchOptionsPtr, blink::NFCWatchOptions> {
+struct TypeConverter<NFCWatchOptionsPtr, const blink::NFCWatchOptions*> {
static NFCWatchOptionsPtr Convert(
- const blink::NFCWatchOptions& watchOptions) {
+ const blink::NFCWatchOptions* watchOptions) {
// https://w3c.github.io/web-nfc/#the-nfcwatchoptions-dictionary
// Default values for NFCWatchOptions dictionary are:
// url = "", recordType = null, mediaType = "", mode = "web-nfc-only"
NFCWatchOptionsPtr watchOptionsPtr = NFCWatchOptions::New();
- watchOptionsPtr->url = watchOptions.url();
- watchOptionsPtr->media_type = watchOptions.mediaType();
+ watchOptionsPtr->url = watchOptions->url();
+ watchOptionsPtr->media_type = watchOptions->mediaType();
- if (watchOptions.hasMode())
- watchOptionsPtr->mode = toNFCWatchMode(watchOptions.mode());
+ if (watchOptions->hasMode())
+ watchOptionsPtr->mode = toNFCWatchMode(watchOptions->mode());
else
watchOptionsPtr->mode = NFCWatchMode::WEBNFC_ONLY;
- if (watchOptions.hasRecordType()) {
+ if (watchOptions->hasRecordType()) {
watchOptionsPtr->record_filter = NFCRecordTypeFilter::New();
watchOptionsPtr->record_filter->record_type =
- toNFCRecordType(watchOptions.recordType());
+ toNFCRecordType(watchOptions->recordType());
}
return watchOptionsPtr;
@@ -380,8 +380,8 @@ ScriptPromise RejectWithDOMException(ScriptState* script_state,
}
ScriptPromise RejectIfInvalidTextRecord(ScriptState* script_state,
- const NFCRecord& record) {
- v8::Local<v8::Value> value = record.data().V8Value();
+ const NFCRecord* record) {
+ v8::Local<v8::Value> value = record->data().V8Value();
if (!value->IsString() &&
!(value->IsNumber() && !std::isnan(value.As<v8::Number>()->Value()))) {
return RejectWithTypeError(script_state,
@@ -389,8 +389,8 @@ ScriptPromise RejectIfInvalidTextRecord(ScriptState* script_state,
"String or UnrestrctedDouble type.");
}
- if (record.hasMediaType() &&
- !record.mediaType().StartsWithIgnoringASCIICase(kPlainTextMimePrefix)) {
+ if (record->hasMediaType() &&
+ !record->mediaType().StartsWithIgnoringASCIICase(kPlainTextMimePrefix)) {
return RejectWithDOMException(script_state, DOMExceptionCode::kSyntaxError,
"Invalid media type for 'text' record.");
}
@@ -399,13 +399,13 @@ ScriptPromise RejectIfInvalidTextRecord(ScriptState* script_state,
}
ScriptPromise RejectIfInvalidURLRecord(ScriptState* script_state,
- const NFCRecord& record) {
- if (!record.data().V8Value()->IsString()) {
+ const NFCRecord* record) {
+ if (!record->data().V8Value()->IsString()) {
return RejectWithTypeError(
script_state, "The data for 'url' NFCRecord must be of String type.");
}
- blink::V8StringResource<> string_resource = record.data().V8Value();
+ blink::V8StringResource<> string_resource = record->data().V8Value();
if (!string_resource.Prepare() ||
!KURL(NullURL(), string_resource).IsValid()) {
return RejectWithDOMException(script_state, DOMExceptionCode::kSyntaxError,
@@ -416,8 +416,8 @@ ScriptPromise RejectIfInvalidURLRecord(ScriptState* script_state,
}
ScriptPromise RejectIfInvalidJSONRecord(ScriptState* script_state,
- const NFCRecord& record) {
- v8::Local<v8::Value> value = record.data().V8Value();
+ const NFCRecord* record) {
+ v8::Local<v8::Value> value = record->data().V8Value();
if (!value->IsObject() || value->IsArrayBuffer()) {
return RejectWithTypeError(
script_state, "The data for 'json' NFCRecord must be of Object type.");
@@ -425,10 +425,10 @@ ScriptPromise RejectIfInvalidJSONRecord(ScriptState* script_state,
// If JSON record has media type, it must be equal to "application/json" or
// start with "application/" and end with "+json".
- if (record.hasMediaType() &&
- (record.mediaType() != kJsonMimeType &&
- !(record.mediaType().StartsWithIgnoringASCIICase(kJsonMimePrefix) &&
- record.mediaType().EndsWithIgnoringASCIICase(kJsonMimePostfix)))) {
+ if (record->hasMediaType() &&
+ (record->mediaType() != kJsonMimeType &&
+ !(record->mediaType().StartsWithIgnoringASCIICase(kJsonMimePrefix) &&
+ record->mediaType().EndsWithIgnoringASCIICase(kJsonMimePostfix)))) {
return RejectWithDOMException(script_state, DOMExceptionCode::kSyntaxError,
"Invalid media type for 'json' record.");
}
@@ -437,8 +437,8 @@ ScriptPromise RejectIfInvalidJSONRecord(ScriptState* script_state,
}
ScriptPromise RejectIfInvalidOpaqueRecord(ScriptState* script_state,
- const NFCRecord& record) {
- if (!record.data().V8Value()->IsArrayBuffer()) {
+ const NFCRecord* record) {
+ if (!record->data().V8Value()->IsArrayBuffer()) {
return RejectWithTypeError(
script_state,
"The data for 'opaque' NFCRecord must be of ArrayBuffer type.");
@@ -448,10 +448,10 @@ ScriptPromise RejectIfInvalidOpaqueRecord(ScriptState* script_state,
}
ScriptPromise RejectIfInvalidNFCRecord(ScriptState* script_state,
- const NFCRecord& record) {
+ const NFCRecord* record) {
device::mojom::blink::NFCRecordType type;
- if (record.hasRecordType()) {
- type = mojo::toNFCRecordType(record.recordType());
+ if (record->hasRecordType()) {
+ type = mojo::toNFCRecordType(record->recordType());
} else {
type = mojo::deduceRecordTypeFromDataType(record);
@@ -463,7 +463,7 @@ ScriptPromise RejectIfInvalidNFCRecord(ScriptState* script_state,
}
// Non-empty records must have data.
- if (!record.hasData() &&
+ if (!record->hasData() &&
(type != device::mojom::blink::NFCRecordType::EMPTY)) {
return RejectWithTypeError(script_state,
"Nonempty NFCRecord must have data.");
@@ -489,7 +489,7 @@ ScriptPromise RejectIfInvalidNFCRecord(ScriptState* script_state,
ScriptPromise RejectIfInvalidNFCRecordArray(
ScriptState* script_state,
- const HeapVector<NFCRecord>& records) {
+ const HeapVector<Member<NFCRecord>>& records) {
for (const auto& record : records) {
ScriptPromise isValidRecord =
RejectIfInvalidNFCRecord(script_state, record);
@@ -513,13 +513,13 @@ ScriptPromise RejectIfInvalidNFCPushMessage(
if (push_message.IsNFCMessage()) {
// https://w3c.github.io/web-nfc/#the-push-method
// If NFCMessage.records is empty, reject promise with TypeError
- const NFCMessage& message = push_message.GetAsNFCMessage();
- if (!message.hasRecords() || message.records().IsEmpty()) {
+ const NFCMessage* message = push_message.GetAsNFCMessage();
+ if (!message->hasRecords() || message->records().IsEmpty()) {
return RejectWithTypeError(script_state,
"Empty NFCMessage was provided.");
}
- return RejectIfInvalidNFCRecordArray(script_state, message.records());
+ return RejectIfInvalidNFCRecordArray(script_state, message->records());
}
return ScriptPromise();
@@ -605,23 +605,23 @@ v8::Local<v8::Value> ToV8(ScriptState* script_state,
return v8::Local<v8::Value>();
}
-NFCRecord ToNFCRecord(ScriptState* script_state,
- const device::mojom::blink::NFCRecordPtr& record) {
- NFCRecord nfc_record;
- nfc_record.setMediaType(record->media_type);
- nfc_record.setRecordType(ToNFCRecordType(record->record_type));
- nfc_record.setData(ScriptValue(script_state, ToV8(script_state, record)));
+NFCRecord* ToNFCRecord(ScriptState* script_state,
+ const device::mojom::blink::NFCRecordPtr& record) {
+ NFCRecord* nfc_record = NFCRecord::Create();
+ nfc_record->setMediaType(record->media_type);
+ nfc_record->setRecordType(ToNFCRecordType(record->record_type));
+ nfc_record->setData(ScriptValue(script_state, ToV8(script_state, record)));
return nfc_record;
}
-NFCMessage ToNFCMessage(ScriptState* script_state,
- const device::mojom::blink::NFCMessagePtr& message) {
- NFCMessage nfc_message;
- nfc_message.setURL(message->url);
- blink::HeapVector<NFCRecord> records;
+NFCMessage* ToNFCMessage(ScriptState* script_state,
+ const device::mojom::blink::NFCMessagePtr& message) {
+ NFCMessage* nfc_message = NFCMessage::Create();
+ nfc_message->setURL(message->url);
+ blink::HeapVector<Member<NFCRecord>> records;
for (wtf_size_t i = 0; i < message->data.size(); ++i)
records.push_back(ToNFCRecord(script_state, message->data[i]));
- nfc_message.setRecords(records);
+ nfc_message->setRecords(records);
return nfc_message;
}
@@ -655,7 +655,7 @@ NFC::NFC(LocalFrame* frame)
}
NFC* NFC::Create(LocalFrame* frame) {
- NFC* nfc = new NFC(frame);
+ NFC* nfc = MakeGarbageCollected<NFC>(frame);
return nfc;
}
@@ -679,7 +679,7 @@ void NFC::ContextDestroyed(ExecutionContext*) {
// https://w3c.github.io/web-nfc/#dom-nfc-push
ScriptPromise NFC::push(ScriptState* script_state,
const NFCPushMessage& push_message,
- const NFCPushOptions& options) {
+ const NFCPushOptions* options) {
ScriptPromise promise = RejectIfNotSupported(script_state);
if (!promise.IsEmpty())
return promise;
@@ -692,8 +692,8 @@ ScriptPromise NFC::push(ScriptState* script_state,
// https://w3c.github.io/web-nfc/#dom-nfc-push
// 9. If timeout value is NaN or negative, reject promise with "TypeError"
// and abort these steps.
- if (options.hasTimeout() &&
- (std::isnan(options.timeout()) || options.timeout() < 0)) {
+ if (options->hasTimeout() &&
+ (std::isnan(options->timeout()) || options->timeout() < 0)) {
return RejectWithTypeError(
script_state, "Invalid NFCPushOptions.timeout value was provided.");
}
@@ -748,14 +748,14 @@ ScriptPromise NFC::cancelPush(ScriptState* script_state, const String& target) {
// https://w3c.github.io/web-nfc/#dom-nfc-watch
ScriptPromise NFC::watch(ScriptState* script_state,
V8MessageCallback* callback,
- const NFCWatchOptions& options) {
+ const NFCWatchOptions* options) {
ScriptPromise promise = RejectIfNotSupported(script_state);
if (!promise.IsEmpty())
return promise;
// https://w3c.github.io/web-nfc/#dom-nfc-watch (Step 9)
- if (options.hasURL() && !options.url().IsEmpty()) {
- KURL pattern_url(options.url());
+ if (options->hasURL() && !options->url().IsEmpty()) {
+ KURL pattern_url(options->url());
if (!pattern_url.IsValid() || pattern_url.Protocol() != kProtocolHttps) {
return RejectWithDOMException(script_state,
DOMExceptionCode::kSyntaxError,
@@ -862,7 +862,7 @@ void NFC::OnWatch(const Vector<uint32_t>& ids,
ScriptState* script_state = callback->CallbackRelevantScriptState();
DCHECK(script_state);
ScriptState::Scope scope(script_state);
- NFCMessage nfc_message = ToNFCMessage(script_state, message);
+ const NFCMessage* nfc_message = ToNFCMessage(script_state, message);
callback->InvokeAndReportException(nullptr, nfc_message);
}
}
diff --git a/chromium/third_party/blink/renderer/modules/nfc/nfc.h b/chromium/third_party/blink/renderer/modules/nfc/nfc.h
index 554581deb53..dc910b474a0 100644
--- a/chromium/third_party/blink/renderer/modules/nfc/nfc.h
+++ b/chromium/third_party/blink/renderer/modules/nfc/nfc.h
@@ -33,6 +33,7 @@ class NFC final : public ScriptWrappable,
public:
static NFC* Create(LocalFrame*);
+ explicit NFC(LocalFrame*);
~NFC() override;
void Dispose();
@@ -43,13 +44,13 @@ class NFC final : public ScriptWrappable,
// Pushes NFCPushMessage asynchronously to NFC tag / peer.
ScriptPromise push(ScriptState*,
const NFCPushMessage&,
- const NFCPushOptions&);
+ const NFCPushOptions*);
// Cancels ongoing push operation.
ScriptPromise cancelPush(ScriptState*, const String&);
// Starts watching for NFC messages that match NFCWatchOptions criteria.
- ScriptPromise watch(ScriptState*, V8MessageCallback*, const NFCWatchOptions&);
+ ScriptPromise watch(ScriptState*, V8MessageCallback*, const NFCWatchOptions*);
// Cancels watch operation with id.
ScriptPromise cancelWatch(ScriptState*, int32_t id);
@@ -85,7 +86,6 @@ class NFC final : public ScriptWrappable,
device::mojom::blink::NFCMessagePtr) override;
private:
- explicit NFC(LocalFrame*);
device::mojom::blink::NFCPtr nfc_;
mojo::Binding<device::mojom::blink::NFCClient> client_binding_;
HeapHashSet<Member<ScriptPromiseResolver>> requests_;
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification.cc b/chromium/third_party/blink/renderer/modules/notifications/notification.cc
index ce2d4eb96d1..0b29ba52e31 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification.cc
@@ -63,7 +63,7 @@ namespace blink {
Notification* Notification::Create(ExecutionContext* context,
const String& title,
- const NotificationOptions& options,
+ const NotificationOptions* options,
ExceptionState& exception_state) {
// The Notification constructor may be disabled through a runtime feature when
// the platform does not support non-persistent notifications.
@@ -80,7 +80,7 @@ Notification* Notification::Create(ExecutionContext* context,
return nullptr;
}
- if (!options.actions().IsEmpty()) {
+ if (!options->actions().IsEmpty()) {
exception_state.ThrowTypeError(
"Actions are only supported for persistent notifications shown using "
"ServiceWorkerRegistration.showNotification().");
@@ -113,8 +113,8 @@ Notification* Notification::Create(ExecutionContext* context,
return nullptr;
}
- Notification* notification =
- new Notification(context, Type::kNonPersistent, std::move(data));
+ Notification* notification = MakeGarbageCollected<Notification>(
+ context, Type::kNonPersistent, std::move(data));
// TODO(https://crbug.com/595685): Make |token| a constructor parameter
// once persistent notifications have been mojofied too.
@@ -141,8 +141,8 @@ Notification* Notification::Create(ExecutionContext* context,
const String& notification_id,
mojom::blink::NotificationDataPtr data,
bool showing) {
- Notification* notification =
- new Notification(context, Type::kPersistent, std::move(data));
+ Notification* notification = MakeGarbageCollected<Notification>(
+ context, Type::kPersistent, std::move(data));
notification->SetState(showing ? State::kShowing : State::kClosed);
notification->SetNotificationId(notification_id);
return notification;
@@ -182,7 +182,7 @@ void Notification::PrepareShow() {
return;
}
- loader_ = new NotificationResourcesLoader(
+ loader_ = MakeGarbageCollected<NotificationResourcesLoader>(
WTF::Bind(&Notification::DidLoadResources, WrapWeakPersistent(this)));
loader_->Start(GetExecutionContext(), *data_);
}
@@ -192,7 +192,10 @@ void Notification::DidLoadResources(NotificationResourcesLoader* loader) {
mojom::blink::NonPersistentNotificationListenerPtr event_listener;
- listener_binding_.Bind(mojo::MakeRequest(&event_listener));
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner =
+ GetExecutionContext()->GetTaskRunner(blink::TaskType::kInternalDefault);
+ listener_binding_.Bind(mojo::MakeRequest(&event_listener, task_runner),
+ task_runner);
NotificationManager::From(GetExecutionContext())
->DisplayNonPersistentNotification(token_, data_->Clone(),
@@ -224,18 +227,19 @@ void Notification::close() {
}
void Notification::OnShow() {
- DispatchEvent(*Event::Create(EventTypeNames::show));
+ DispatchEvent(*Event::Create(event_type_names::kShow));
}
void Notification::OnClick(OnClickCallback completed_closure) {
ExecutionContext* context = GetExecutionContext();
Document* document = DynamicTo<Document>(context);
- std::unique_ptr<UserGestureIndicator> gesture_indicator =
- LocalFrame::NotifyUserActivation(
- document ? document->GetFrame() : nullptr,
- UserGestureToken::kNewGesture);
+ std::unique_ptr<UserGestureIndicator> gesture_indicator;
+ if (document && document->GetFrame()) {
+ gesture_indicator = LocalFrame::NotifyUserActivation(
+ document->GetFrame(), UserGestureToken::kNewGesture);
+ }
ScopedWindowFocusAllowedIndicator window_focus_allowed(GetExecutionContext());
- DispatchEvent(*Event::Create(EventTypeNames::click));
+ DispatchEvent(*Event::Create(event_type_names::kClick));
std::move(completed_closure).Run();
}
@@ -245,13 +249,13 @@ void Notification::OnClose(OnCloseCallback completed_closure) {
// should be Closing if the developer initiated the close.
if (state_ == State::kShowing || state_ == State::kClosing) {
state_ = State::kClosed;
- DispatchEvent(*Event::Create(EventTypeNames::close));
+ DispatchEvent(*Event::Create(event_type_names::kClose));
}
std::move(completed_closure).Run();
}
void Notification::DispatchErrorEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::error));
+ DispatchEvent(*Event::Create(event_type_names::kError));
}
String Notification::title() const {
@@ -347,23 +351,23 @@ Vector<v8::Local<v8::Value>> Notification::actions(
data_->actions.value();
result.Grow(actions.size());
for (wtf_size_t i = 0; i < actions.size(); ++i) {
- NotificationAction action;
+ NotificationAction* action = NotificationAction::Create();
switch (actions[i]->type) {
case mojom::blink::NotificationActionType::BUTTON:
- action.setType("button");
+ action->setType("button");
break;
case mojom::blink::NotificationActionType::TEXT:
- action.setType("text");
+ action->setType("text");
break;
default:
NOTREACHED() << "Unknown action type: " << actions[i]->type;
}
- action.setAction(actions[i]->action);
- action.setTitle(actions[i]->title);
- action.setIcon(actions[i]->icon.GetString());
- action.setPlaceholder(actions[i]->placeholder);
+ action->setAction(actions[i]->action);
+ action->setTitle(actions[i]->title);
+ action->setIcon(actions[i]->icon.GetString());
+ action->setPlaceholder(actions[i]->placeholder);
// Both the Action dictionaries themselves and the sequence they'll be
// returned in are expected to the frozen. This cannot be done with
@@ -448,7 +452,7 @@ ScriptPromise Notification::requestPermission(
script_state, deprecated_callback);
}
-size_t Notification::maxActions() {
+uint32_t Notification::maxActions() {
return kWebNotificationMaxActions;
}
@@ -458,7 +462,7 @@ DispatchEventResult Notification::DispatchEventInternal(Event& event) {
}
const AtomicString& Notification::InterfaceName() const {
- return EventTargetNames::Notification;
+ return event_target_names::kNotification;
}
void Notification::ContextDestroyed(ExecutionContext* context) {
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification.h b/chromium/third_party/blink/renderer/modules/notifications/notification.h
index 3cd76838585..2cb9a2aad58 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification.h
@@ -70,7 +70,7 @@ class MODULES_EXPORT Notification final
// when the developer-provided data is valid.
static Notification* Create(ExecutionContext* context,
const String& title,
- const NotificationOptions& options,
+ const NotificationOptions* options,
ExceptionState& state);
// Used for embedder-created persistent notifications. Initializes the state
@@ -80,14 +80,22 @@ class MODULES_EXPORT Notification final
mojom::blink::NotificationDataPtr data,
bool showing);
+ // The type of notification this instance represents. Non-persistent
+ // notifications will have events delivered to their instance, whereas
+ // persistent notification will be using a Service Worker.
+ enum class Type { kNonPersistent, kPersistent };
+
+ Notification(ExecutionContext* context,
+ Type type,
+ mojom::blink::NotificationDataPtr data);
~Notification() override;
void close();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(show);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(click, kClick);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(show, kShow);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose);
// NonPersistentNotificationListener interface.
void OnShow() override;
@@ -116,7 +124,7 @@ class MODULES_EXPORT Notification final
ScriptState* script_state,
V8NotificationPermissionCallback* deprecated_callback = nullptr);
- static size_t maxActions();
+ static uint32_t maxActions();
// EventTarget interface.
ExecutionContext* GetExecutionContext() const final {
@@ -137,18 +145,9 @@ class MODULES_EXPORT Notification final
DispatchEventResult DispatchEventInternal(Event& event) final;
private:
- // The type of notification this instance represents. Non-persistent
- // notifications will have events delivered to their instance, whereas
- // persistent notification will be using a Service Worker.
- enum class Type { kNonPersistent, kPersistent };
-
// The current phase of the notification in its lifecycle.
enum class State { kLoading, kShowing, kClosing, kClosed };
- Notification(ExecutionContext* context,
- Type type,
- mojom::blink::NotificationDataPtr data);
-
// Sets the state of the notification in its lifecycle.
void SetState(State state) { state_ = state; }
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_action.idl b/chromium/third_party/blink/renderer/modules/notifications/notification_action.idl
index 4f0ec6c9bf8..1323382f63f 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_action.idl
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_action.idl
@@ -4,15 +4,15 @@
// https://notifications.spec.whatwg.org/#dictdef-notificationaction
-[RuntimeEnabled=NotificationInlineReplies] enum NotificationActionType {
+enum NotificationActionType {
"button",
"text"
};
dictionary NotificationAction {
- [RuntimeEnabled=NotificationInlineReplies] NotificationActionType type = "button";
+ NotificationActionType type = "button";
required DOMString action;
required DOMString title;
USVString icon;
- [RuntimeEnabled=NotificationInlineReplies] DOMString? placeholder = null;
+ DOMString? placeholder = null;
};
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_data.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_data.cc
index 4e22ec98d17..a7cdf408737 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_data.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_data.cc
@@ -40,17 +40,17 @@ KURL CompleteURL(ExecutionContext* context, const String& string_url) {
mojom::blink::NotificationDataPtr CreateNotificationData(
ExecutionContext* context,
const String& title,
- const NotificationOptions& options,
+ const NotificationOptions* options,
ExceptionState& exception_state) {
// If silent is true, the notification must not have a vibration pattern.
- if (options.hasVibrate() && options.silent()) {
+ if (options->hasVibrate() && options->silent()) {
exception_state.ThrowTypeError(
"Silent notifications must not specify vibration patterns.");
return nullptr;
}
// If renotify is true, the notification must have a tag.
- if (options.renotify() && options.tag().IsEmpty()) {
+ if (options->renotify() && options->tag().IsEmpty()) {
exception_state.ThrowTypeError(
"Notifications which set the renotify flag must specify a non-empty "
"tag.");
@@ -60,34 +60,34 @@ mojom::blink::NotificationDataPtr CreateNotificationData(
auto notification_data = mojom::blink::NotificationData::New();
notification_data->title = title;
- notification_data->direction = ToDirectionEnumValue(options.dir());
- notification_data->lang = options.lang();
- notification_data->body = options.body();
- notification_data->tag = options.tag();
+ notification_data->direction = ToDirectionEnumValue(options->dir());
+ notification_data->lang = options->lang();
+ notification_data->body = options->body();
+ notification_data->tag = options->tag();
- if (options.hasImage() && !options.image().IsEmpty())
- notification_data->image = CompleteURL(context, options.image());
+ if (options->hasImage() && !options->image().IsEmpty())
+ notification_data->image = CompleteURL(context, options->image());
- if (options.hasIcon() && !options.icon().IsEmpty())
- notification_data->icon = CompleteURL(context, options.icon());
+ if (options->hasIcon() && !options->icon().IsEmpty())
+ notification_data->icon = CompleteURL(context, options->icon());
- if (options.hasBadge() && !options.badge().IsEmpty())
- notification_data->badge = CompleteURL(context, options.badge());
+ if (options->hasBadge() && !options->badge().IsEmpty())
+ notification_data->badge = CompleteURL(context, options->badge());
VibrationController::VibrationPattern vibration_pattern =
- VibrationController::SanitizeVibrationPattern(options.vibrate());
+ VibrationController::SanitizeVibrationPattern(options->vibrate());
notification_data->vibration_pattern = Vector<int32_t>();
notification_data->vibration_pattern->Append(vibration_pattern.data(),
vibration_pattern.size());
- notification_data->timestamp = options.hasTimestamp()
- ? static_cast<double>(options.timestamp())
+ notification_data->timestamp = options->hasTimestamp()
+ ? static_cast<double>(options->timestamp())
: WTF::CurrentTimeMS();
- notification_data->renotify = options.renotify();
- notification_data->silent = options.silent();
- notification_data->require_interaction = options.requireInteraction();
+ notification_data->renotify = options->renotify();
+ notification_data->silent = options->silent();
+ notification_data->require_interaction = options->requireInteraction();
- if (options.hasData()) {
- const ScriptValue& data = options.data();
+ if (options->hasData()) {
+ const ScriptValue& data = options->data();
v8::Isolate* isolate = data.GetIsolate();
DCHECK(isolate->InContext());
SerializedScriptValue::SerializeOptions options;
@@ -107,22 +107,22 @@ mojom::blink::NotificationDataPtr CreateNotificationData(
Vector<mojom::blink::NotificationActionPtr> actions;
const size_t max_actions = Notification::maxActions();
- for (const NotificationAction& action : options.actions()) {
+ for (const NotificationAction* action : options->actions()) {
if (actions.size() >= max_actions)
break;
auto notification_action = mojom::blink::NotificationAction::New();
- notification_action->action = action.action();
- notification_action->title = action.title();
+ notification_action->action = action->action();
+ notification_action->title = action->title();
- if (action.type() == "button")
+ if (action->type() == "button")
notification_action->type = mojom::blink::NotificationActionType::BUTTON;
- else if (action.type() == "text")
+ else if (action->type() == "text")
notification_action->type = mojom::blink::NotificationActionType::TEXT;
else
- NOTREACHED() << "Unknown action type: " << action.type();
+ NOTREACHED() << "Unknown action type: " << action->type();
- if (action.hasPlaceholder() &&
+ if (action->hasPlaceholder() &&
notification_action->type ==
mojom::blink::NotificationActionType::BUTTON) {
exception_state.ThrowTypeError(
@@ -130,10 +130,10 @@ mojom::blink::NotificationDataPtr CreateNotificationData(
return nullptr;
}
- notification_action->placeholder = action.placeholder();
+ notification_action->placeholder = action->placeholder();
- if (action.hasIcon() && !action.icon().IsEmpty())
- notification_action->icon = CompleteURL(context, action.icon());
+ if (action->hasIcon() && !action->icon().IsEmpty())
+ notification_action->icon = CompleteURL(context, action->icon());
actions.push_back(std::move(notification_action));
}
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_data.h b/chromium/third_party/blink/renderer/modules/notifications/notification_data.h
index 2e21e5b5fbe..11d462d100e 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_data.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_data.h
@@ -25,7 +25,7 @@ class NotificationOptions;
MODULES_EXPORT mojom::blink::NotificationDataPtr CreateNotificationData(
ExecutionContext* context,
const String& title,
- const NotificationOptions& options,
+ const NotificationOptions* options,
ExceptionState& exception_state);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_data_test.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_data_test.cc
index 24296339e3d..2005d93042d 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_data_test.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_data_test.cc
@@ -83,32 +83,32 @@ TEST_F(NotificationDataTest, ReflectProperties) {
UnsignedLongOrUnsignedLongSequence vibration_sequence;
vibration_sequence.SetUnsignedLongSequence(vibration_pattern);
- HeapVector<NotificationAction> actions;
+ HeapVector<Member<NotificationAction>> actions;
for (size_t i = 0; i < Notification::maxActions(); ++i) {
- NotificationAction action;
- action.setType(kNotificationActionType);
- action.setAction(kNotificationActionAction);
- action.setTitle(kNotificationActionTitle);
- action.setIcon(kNotificationActionIcon);
- action.setPlaceholder(kNotificationActionPlaceholder);
+ NotificationAction* action = NotificationAction::Create();
+ action->setType(kNotificationActionType);
+ action->setAction(kNotificationActionAction);
+ action->setTitle(kNotificationActionTitle);
+ action->setIcon(kNotificationActionIcon);
+ action->setPlaceholder(kNotificationActionPlaceholder);
actions.push_back(action);
}
- NotificationOptions options;
- options.setDir(kNotificationDir);
- options.setLang(kNotificationLang);
- options.setBody(kNotificationBody);
- options.setTag(kNotificationTag);
- options.setImage(kNotificationImage);
- options.setIcon(kNotificationIcon);
- options.setBadge(kNotificationBadge);
- options.setVibrate(vibration_sequence);
- options.setTimestamp(kNotificationTimestamp);
- options.setRenotify(kNotificationRenotify);
- options.setSilent(kNotificationSilent);
- options.setRequireInteraction(kNotificationRequireInteraction);
- options.setActions(actions);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setDir(kNotificationDir);
+ options->setLang(kNotificationLang);
+ options->setBody(kNotificationBody);
+ options->setTag(kNotificationTag);
+ options->setImage(kNotificationImage);
+ options->setIcon(kNotificationIcon);
+ options->setBadge(kNotificationBadge);
+ options->setVibrate(vibration_sequence);
+ options->setTimestamp(kNotificationTimestamp);
+ options->setRenotify(kNotificationRenotify);
+ options->setSilent(kNotificationSilent);
+ options->setRequireInteraction(kNotificationRequireInteraction);
+ options->setActions(actions);
// TODO(peter): Test |options.data| and |notificationData.data|.
@@ -162,9 +162,9 @@ TEST_F(NotificationDataTest, SilentNotificationWithVibration) {
UnsignedLongOrUnsignedLongSequence vibration_sequence;
vibration_sequence.SetUnsignedLongSequence(vibration_pattern);
- NotificationOptions options;
- options.setVibrate(vibration_sequence);
- options.setSilent(true);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setVibrate(vibration_sequence);
+ options->setSilent(true);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
@@ -176,14 +176,14 @@ TEST_F(NotificationDataTest, SilentNotificationWithVibration) {
}
TEST_F(NotificationDataTest, ActionTypeButtonWithPlaceholder) {
- HeapVector<NotificationAction> actions;
- NotificationAction action;
- action.setType("button");
- action.setPlaceholder("I'm afraid I can't do that...");
+ HeapVector<Member<NotificationAction>> actions;
+ NotificationAction* action = NotificationAction::Create();
+ action->setType("button");
+ action->setPlaceholder("I'm afraid I can't do that...");
actions.push_back(action);
- NotificationOptions options;
- options.setActions(actions);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setActions(actions);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
@@ -195,9 +195,9 @@ TEST_F(NotificationDataTest, ActionTypeButtonWithPlaceholder) {
}
TEST_F(NotificationDataTest, RenotifyWithEmptyTag) {
- NotificationOptions options;
- options.setTag(kNotificationEmptyTag);
- options.setRenotify(true);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setTag(kNotificationEmptyTag);
+ options->setRenotify(true);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
@@ -210,20 +210,20 @@ TEST_F(NotificationDataTest, RenotifyWithEmptyTag) {
}
TEST_F(NotificationDataTest, InvalidIconUrls) {
- HeapVector<NotificationAction> actions;
+ HeapVector<Member<NotificationAction>> actions;
for (size_t i = 0; i < Notification::maxActions(); ++i) {
- NotificationAction action;
- action.setAction(kNotificationActionAction);
- action.setTitle(kNotificationActionTitle);
- action.setIcon(kNotificationIconInvalid);
+ NotificationAction* action = NotificationAction::Create();
+ action->setAction(kNotificationActionAction);
+ action->setTitle(kNotificationActionTitle);
+ action->setIcon(kNotificationIconInvalid);
actions.push_back(action);
}
- NotificationOptions options;
- options.setImage(kNotificationIconInvalid);
- options.setIcon(kNotificationIconInvalid);
- options.setBadge(kNotificationIconInvalid);
- options.setActions(actions);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setImage(kNotificationIconInvalid);
+ options->setIcon(kNotificationIconInvalid);
+ options->setBadge(kNotificationIconInvalid);
+ options->setActions(actions);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
@@ -245,8 +245,8 @@ TEST_F(NotificationDataTest, VibrationNormalization) {
UnsignedLongOrUnsignedLongSequence vibration_sequence;
vibration_sequence.SetUnsignedLongSequence(unnormalized_pattern);
- NotificationOptions options;
- options.setVibrate(vibration_sequence);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setVibrate(vibration_sequence);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
@@ -266,7 +266,7 @@ TEST_F(NotificationDataTest, VibrationNormalization) {
}
TEST_F(NotificationDataTest, DefaultTimestampValue) {
- NotificationOptions options;
+ NotificationOptions* options = NotificationOptions::Create();
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
@@ -289,8 +289,8 @@ TEST_F(NotificationDataTest, DirectionValues) {
mappings.insert("peter", mojom::blink::NotificationDirection::AUTO);
for (const String& direction : mappings.Keys()) {
- NotificationOptions options;
- options.setDir(direction);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setDir(direction);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data =
@@ -303,17 +303,17 @@ TEST_F(NotificationDataTest, DirectionValues) {
}
TEST_F(NotificationDataTest, MaximumActionCount) {
- HeapVector<NotificationAction> actions;
+ HeapVector<Member<NotificationAction>> actions;
for (size_t i = 0; i < Notification::maxActions() + 2; ++i) {
- NotificationAction action;
- action.setAction(String::Number(i));
- action.setTitle(kNotificationActionTitle);
+ NotificationAction* action = NotificationAction::Create();
+ action->setAction(String::Number(i));
+ action->setTitle(kNotificationActionTitle);
actions.push_back(action);
}
- NotificationOptions options;
- options.setActions(actions);
+ NotificationOptions* options = NotificationOptions::Create();
+ options->setActions(actions);
DummyExceptionStateForTesting exception_state;
mojom::blink::NotificationDataPtr notification_data = CreateNotificationData(
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_event.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_event.cc
index af578be5ec2..d41d96adbe0 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_event.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_event.cc
@@ -10,28 +10,28 @@
namespace blink {
NotificationEvent::NotificationEvent(const AtomicString& type,
- const NotificationEventInit& initializer)
+ const NotificationEventInit* initializer)
: ExtendableEvent(type, initializer),
- action_(initializer.action()),
- reply_(initializer.reply()) {
- if (initializer.hasNotification())
- notification_ = initializer.notification();
+ action_(initializer->action()),
+ reply_(initializer->reply()) {
+ if (initializer->hasNotification())
+ notification_ = initializer->notification();
}
NotificationEvent::NotificationEvent(const AtomicString& type,
- const NotificationEventInit& initializer,
+ const NotificationEventInit* initializer,
WaitUntilObserver* observer)
: ExtendableEvent(type, initializer, observer),
- action_(initializer.action()),
- reply_(initializer.reply()) {
- if (initializer.hasNotification())
- notification_ = initializer.notification();
+ action_(initializer->action()),
+ reply_(initializer->reply()) {
+ if (initializer->hasNotification())
+ notification_ = initializer->notification();
}
NotificationEvent::~NotificationEvent() = default;
const AtomicString& NotificationEvent::InterfaceName() const {
- return EventNames::NotificationEvent;
+ return event_interface_names::kNotificationEvent;
}
void NotificationEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_event.h b/chromium/third_party/blink/renderer/modules/notifications/notification_event.h
index 309aee02c78..2ff7f52baf2 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_event.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_event.h
@@ -20,15 +20,20 @@ class MODULES_EXPORT NotificationEvent final : public ExtendableEvent {
public:
static NotificationEvent* Create(const AtomicString& type,
- const NotificationEventInit& initializer) {
- return new NotificationEvent(type, initializer);
+ const NotificationEventInit* initializer) {
+ return MakeGarbageCollected<NotificationEvent>(type, initializer);
}
static NotificationEvent* Create(const AtomicString& type,
- const NotificationEventInit& initializer,
+ const NotificationEventInit* initializer,
WaitUntilObserver* observer) {
- return new NotificationEvent(type, initializer, observer);
+ return MakeGarbageCollected<NotificationEvent>(type, initializer, observer);
}
+ NotificationEvent(const AtomicString& type,
+ const NotificationEventInit* initializer);
+ NotificationEvent(const AtomicString& type,
+ const NotificationEventInit* initializer,
+ WaitUntilObserver* observer);
~NotificationEvent() override;
Notification* getNotification() const { return notification_.Get(); }
@@ -41,12 +46,6 @@ class MODULES_EXPORT NotificationEvent final : public ExtendableEvent {
void Trace(blink::Visitor* visitor) override;
private:
- NotificationEvent(const AtomicString& type,
- const NotificationEventInit& initializer);
- NotificationEvent(const AtomicString& type,
- const NotificationEventInit& initializer,
- WaitUntilObserver* observer);
-
Member<Notification> notification_;
String action_;
String reply_;
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_event.idl b/chromium/third_party/blink/renderer/modules/notifications/notification_event.idl
index 7490f2a5d0f..89ded1ac7b2 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_event.idl
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_event.idl
@@ -11,5 +11,5 @@
] interface NotificationEvent : ExtendableEvent {
[ImplementedAs=getNotification] readonly attribute Notification notification;
readonly attribute DOMString action;
- [RuntimeEnabled=NotificationInlineReplies] readonly attribute DOMString? reply;
+ readonly attribute DOMString? reply;
};
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_event_init.idl b/chromium/third_party/blink/renderer/modules/notifications/notification_event_init.idl
index b1081e3ae6e..f77ef81cf8b 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_event_init.idl
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_event_init.idl
@@ -7,5 +7,5 @@
dictionary NotificationEventInit : ExtendableEventInit {
required Notification notification;
DOMString action = "";
- [RuntimeEnabled=NotificationInlineReplies] DOMString? reply = "";
+ DOMString? reply = "";
};
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.cc
index efe063638b4..3b4dec590e5 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.cc
@@ -84,10 +84,10 @@ SkBitmap NotificationImageLoader::ScaleDownIfNeeded(const SkBitmap& image,
static_cast<double>(max_height_px) / image.height());
TimeTicks start_time = CurrentTimeTicks();
// TODO(peter): Try using RESIZE_BETTER for large images.
- SkBitmap scaled_image =
- skia::ImageOperations::Resize(image, skia::ImageOperations::RESIZE_BEST,
- std::lround(scale * image.width()),
- std::lround(scale * image.height()));
+ SkBitmap scaled_image = skia::ImageOperations::Resize(
+ image, skia::ImageOperations::RESIZE_BEST,
+ static_cast<int>(std::lround(scale * image.width())),
+ static_cast<int>(std::lround(scale * image.height())));
NOTIFICATION_HISTOGRAM_COUNTS(
LoadScaleDownTime, type,
base::saturated_cast<base::HistogramBase::Sample>(
@@ -116,7 +116,7 @@ void NotificationImageLoader::Start(ExecutionContext* context,
resource_request.SetRequestContext(mojom::RequestContextType::IMAGE);
resource_request.SetPriority(ResourceLoadPriority::kMedium);
- threadable_loader_ = new ThreadableLoader(
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
*context, this, resource_loader_options);
threadable_loader_->SetTimeout(
TimeDelta::FromMilliseconds(kImageFetchTimeoutInMs));
@@ -155,8 +155,10 @@ void NotificationImageLoader::DidFinishLoading(
1000 * 60 * 60 /* 1 hour max */);
if (data_) {
- NOTIFICATION_HISTOGRAM_COUNTS(LoadFileSize, type_, data_->size(),
- 10000000 /* ~10mb max */);
+ NOTIFICATION_HISTOGRAM_COUNTS(
+ LoadFileSize, type_,
+ base::saturated_cast<base::HistogramBase::Sample>(data_->size()),
+ 10000000 /* ~10mb max */);
const bool data_complete = true;
std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create(
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.h b/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.h
index 7b40f7de172..1971cb6fefd 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader.h
@@ -27,6 +27,8 @@ class ResourceError;
class MODULES_EXPORT NotificationImageLoader final
: public GarbageCollectedFinalized<NotificationImageLoader>,
public ThreadableLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(NotificationImageLoader);
+
public:
// Type names are used in UMAs, so do not rename.
enum class Type { kImage, kIcon, kBadge, kActionIcon };
@@ -59,7 +61,10 @@ class MODULES_EXPORT NotificationImageLoader final
void DidFail(const ResourceError& error) override;
void DidFailRedirectCheck() override;
- void Trace(blink::Visitor* visitor) { visitor->Trace(threadable_loader_); }
+ void Trace(blink::Visitor* visitor) override {
+ visitor->Trace(threadable_loader_);
+ ThreadableLoaderClient::Trace(visitor);
+ }
private:
void RunCallbackWithEmptyBitmap();
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc
index 1495b7fe57c..8100242ca29 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc
@@ -37,8 +37,8 @@ class NotificationImageLoaderTest : public PageTestBase {
NotificationImageLoaderTest()
: // Use an arbitrary type, since it only affects which UMA bucket we
// use.
- loader_(
- new NotificationImageLoader(NotificationImageLoader::Type::kIcon)) {
+ loader_(MakeGarbageCollected<NotificationImageLoader>(
+ NotificationImageLoader::Type::kIcon)) {
EnablePlatform();
}
@@ -54,7 +54,7 @@ class NotificationImageLoaderTest : public PageTestBase {
// Registers a mocked URL. When fetched it will be loaded form the test data
// directory.
WebURL RegisterMockedURL(const String& file_name) {
- WebURL registered_url = URLTestHelpers::RegisterMockedURLLoadFromBase(
+ WebURL registered_url = url_test_helpers::RegisterMockedURLLoadFromBase(
kNotificationImageLoaderBaseUrl,
test::CoreTestDataPath(kNotificationImageLoaderBaseDir), file_name,
"image/png");
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_manager.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_manager.cc
index 36bc76a3af6..8ccdb3c2fbe 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_manager.cc
@@ -4,12 +4,12 @@
#include "third_party/blink/renderer/modules/notifications/notification_manager.h"
+#include "base/numerics/safe_conversions.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/mojom/notifications/notification.mojom-blink.h"
#include "third_party/blink/public/platform/interface_provider.h"
#include "third_party/blink/public/platform/modules/permissions/permission.mojom-blink.h"
#include "third_party/blink/public/platform/modules/permissions/permission_status.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -35,7 +35,7 @@ NotificationManager* NotificationManager::From(ExecutionContext* context) {
NotificationManager* manager =
Supplement<ExecutionContext>::From<NotificationManager>(context);
if (!manager) {
- manager = new NotificationManager(*context);
+ manager = MakeGarbageCollected<NotificationManager>(*context);
Supplement<ExecutionContext>::ProvideTo(*context, manager);
}
@@ -129,7 +129,7 @@ void NotificationManager::CloseNonPersistentNotification(const String& token) {
}
void NotificationManager::DisplayPersistentNotification(
- blink::WebServiceWorkerRegistration* service_worker_registration,
+ int64_t service_worker_registration_id,
mojom::blink::NotificationDataPtr notification_data,
mojom::blink::NotificationResourcesPtr notification_resources,
ScriptPromiseResolver* resolver) {
@@ -156,7 +156,8 @@ void NotificationManager::DisplayPersistentNotification(
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, notification_data_size_histogram,
("Notifications.AuthorDataSize", 1, 1000, 50));
- notification_data_size_histogram.Count(author_data_size);
+ notification_data_size_histogram.Count(
+ base::saturated_cast<base::HistogramBase::Sample>(author_data_size));
if (author_data_size >
mojom::blink::NotificationData::kMaximumDeveloperDataSize) {
@@ -165,8 +166,8 @@ void NotificationManager::DisplayPersistentNotification(
}
GetNotificationService()->DisplayPersistentNotification(
- service_worker_registration->RegistrationId(),
- std::move(notification_data), std::move(notification_resources),
+ service_worker_registration_id, std::move(notification_data),
+ std::move(notification_resources),
WTF::Bind(&NotificationManager::DidDisplayPersistentNotification,
WrapPersistent(this), WrapPersistent(resolver)));
}
@@ -193,11 +194,11 @@ void NotificationManager::ClosePersistentNotification(
}
void NotificationManager::GetNotifications(
- WebServiceWorkerRegistration* service_worker_registration,
+ int64_t service_worker_registration_id,
const WebString& filter_tag,
ScriptPromiseResolver* resolver) {
GetNotificationService()->GetNotifications(
- service_worker_registration->RegistrationId(), filter_tag,
+ service_worker_registration_id, filter_tag,
WTF::Bind(&NotificationManager::DidGetNotifications, WrapPersistent(this),
WrapPersistent(resolver)));
}
@@ -211,7 +212,7 @@ void NotificationManager::DidGetNotifications(
HeapVector<Member<Notification>> notifications;
notifications.ReserveInitialCapacity(notification_ids.size());
- for (size_t i = 0; i < notification_ids.size(); ++i) {
+ for (wtf_size_t i = 0; i < notification_ids.size(); ++i) {
notifications.push_back(Notification::Create(
resolver->GetExecutionContext(), notification_ids[i],
std::move(notification_datas[i]), true /* showing */));
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_manager.h b/chromium/third_party/blink/renderer/modules/notifications/notification_manager.h
index 988715534ee..09bbbf888c4 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_manager.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_manager.h
@@ -18,7 +18,6 @@ namespace blink {
class ScriptPromise;
class ScriptPromiseResolver;
class ScriptState;
-class WebServiceWorkerRegistration;
// The notification manager, unique to the execution context, is responsible for
// connecting and communicating with the Mojo notification service.
@@ -35,6 +34,7 @@ class NotificationManager final
static NotificationManager* From(ExecutionContext* context);
+ explicit NotificationManager(ExecutionContext& context);
~NotificationManager();
// Returns the notification permission status of the current origin. This
@@ -61,7 +61,7 @@ class NotificationManager final
// Shows a notification from a service worker.
void DisplayPersistentNotification(
- blink::WebServiceWorkerRegistration* service_worker_registration,
+ int64_t service_worker_registration_id,
mojom::blink::NotificationDataPtr notification_data,
mojom::blink::NotificationResourcesPtr notification_resources,
ScriptPromiseResolver* resolver);
@@ -72,16 +72,13 @@ class NotificationManager final
// Asynchronously gets the persistent notifications belonging to the Service
// Worker Registration. If |filter_tag| is not an empty string, only the
// notification with the given tag will be considered.
- void GetNotifications(
- WebServiceWorkerRegistration* service_worker_registration,
- const WebString& filter_tag,
- ScriptPromiseResolver* resolver);
+ void GetNotifications(int64_t service_worker_registration_id,
+ const WebString& filter_tag,
+ ScriptPromiseResolver* resolver);
void Trace(blink::Visitor* visitor) override;
private:
- explicit NotificationManager(ExecutionContext& context);
-
void DidDisplayPersistentNotification(
ScriptPromiseResolver* resolver,
mojom::blink::PersistentNotificationError error);
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc
index 8bc1348277f..5adbcc2fac2 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.cc
@@ -29,9 +29,9 @@ void NotificationResourcesLoader::Start(
DCHECK(!started_);
started_ = true;
- size_t num_actions = notification_data.actions.has_value()
- ? notification_data.actions->size()
- : 0;
+ wtf_size_t num_actions = notification_data.actions.has_value()
+ ? notification_data.actions->size()
+ : 0;
pending_request_count_ = 3 /* image, icon, badge */ + num_actions;
// TODO(johnme): ensure image is not loaded when it will not be used.
@@ -50,7 +50,7 @@ void NotificationResourcesLoader::Start(
WrapWeakPersistent(this)));
action_icons_.resize(num_actions);
- for (size_t i = 0; i < num_actions; i++)
+ for (wtf_size_t i = 0; i < num_actions; i++)
LoadImage(context, NotificationImageLoader::Type::kActionIcon,
notification_data.actions.value()[i]->icon,
WTF::Bind(&NotificationResourcesLoader::DidLoadActionIcon,
@@ -86,7 +86,8 @@ void NotificationResourcesLoader::LoadImage(
return;
}
- NotificationImageLoader* image_loader = new NotificationImageLoader(type);
+ NotificationImageLoader* image_loader =
+ MakeGarbageCollected<NotificationImageLoader>(type);
image_loaders_.push_back(image_loader);
image_loader->Start(context, url, std::move(image_callback));
}
@@ -109,7 +110,7 @@ void NotificationResourcesLoader::DidLoadBadge(const SkBitmap& image) {
DidFinishRequest();
}
-void NotificationResourcesLoader::DidLoadActionIcon(size_t action_index,
+void NotificationResourcesLoader::DidLoadActionIcon(wtf_size_t action_index,
const SkBitmap& image) {
DCHECK_LT(action_index, action_icons_.size());
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.h b/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.h
index 1e8eb32074b..5568ef49c7b 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader.h
@@ -63,7 +63,7 @@ class MODULES_EXPORT NotificationResourcesLoader final
void DidLoadImage(const SkBitmap& image);
void DidLoadIcon(const SkBitmap& image);
void DidLoadBadge(const SkBitmap& image);
- void DidLoadActionIcon(size_t action_index, const SkBitmap& image);
+ void DidLoadActionIcon(wtf_size_t action_index, const SkBitmap& image);
// Decrements |m_pendingRequestCount| and runs |m_completionCallback| if
// there are no more pending requests.
diff --git a/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader_test.cc b/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader_test.cc
index 860dcad26ad..bafa9876a47 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader_test.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/notification_resources_loader_test.cc
@@ -34,7 +34,7 @@ constexpr char kResourcesLoaderIcon3000x2000[] = "3000x2000.png";
class NotificationResourcesLoaderTest : public PageTestBase {
public:
NotificationResourcesLoaderTest()
- : loader_(new NotificationResourcesLoader(
+ : loader_(MakeGarbageCollected<NotificationResourcesLoader>(
Bind(&NotificationResourcesLoaderTest::DidFetchResources,
WTF::Unretained(this)))) {}
@@ -62,7 +62,7 @@ class NotificationResourcesLoaderTest : public PageTestBase {
// Registers a mocked url. When fetched, |fileName| will be loaded from the
// test data directory.
KURL RegisterMockedURL(const String& file_name) {
- KURL registered_url = URLTestHelpers::RegisterMockedURLLoadFromBase(
+ KURL registered_url = url_test_helpers::RegisterMockedURLLoadFromBase(
kResourcesLoaderBaseUrl,
test::CoreTestDataPath(kResourcesLoaderBaseDir), file_name,
"image/png");
@@ -72,7 +72,7 @@ class NotificationResourcesLoaderTest : public PageTestBase {
// Registers a mocked url that will fail to be fetched, with a 404 error.
KURL RegisterMockedErrorURL(const String& file_name) {
KURL url(kResourcesLoaderBaseUrl + file_name);
- URLTestHelpers::RegisterMockedErrorURLLoad(url);
+ url_test_helpers::RegisterMockedErrorURLLoad(url);
return url;
}
diff --git a/chromium/third_party/blink/renderer/modules/notifications/service_worker_global_scope_notifications.h b/chromium/third_party/blink/renderer/modules/notifications/service_worker_global_scope_notifications.h
index be423bf5f97..a059f9b3bd5 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/service_worker_global_scope_notifications.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/service_worker_global_scope_notifications.h
@@ -14,8 +14,8 @@ class ServiceWorkerGlobalScopeNotifications {
STATIC_ONLY(ServiceWorkerGlobalScopeNotifications);
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(notificationclick);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(notificationclose);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(notificationclick, kNotificationclick);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(notificationclose, kNotificationclose);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.cc b/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.cc
index 72dba71a5f7..c9f2abeaf78 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.cc
+++ b/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.cc
@@ -32,7 +32,7 @@ ScriptPromise ServiceWorkerRegistrationNotifications::showNotification(
ScriptState* script_state,
ServiceWorkerRegistration& registration,
const String& title,
- const NotificationOptions& options,
+ const NotificationOptions* options,
ExceptionState& exception_state) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
@@ -67,7 +67,7 @@ ScriptPromise ServiceWorkerRegistrationNotifications::showNotification(
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, notification_count_histogram,
("Notifications.PersistentNotificationActionCount", 17));
- notification_count_histogram.Count(options.actions().size());
+ notification_count_histogram.Count(options->actions().size());
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -81,13 +81,13 @@ ScriptPromise ServiceWorkerRegistrationNotifications::showNotification(
ScriptPromise ServiceWorkerRegistrationNotifications::getNotifications(
ScriptState* script_state,
ServiceWorkerRegistration& registration,
- const GetNotificationOptions& options) {
+ const GetNotificationOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
ExecutionContext* execution_context = ExecutionContext::From(script_state);
NotificationManager::From(execution_context)
- ->GetNotifications(registration.WebRegistration(), options.tag(),
+ ->GetNotifications(registration.RegistrationId(), options->tag(),
WrapPersistent(resolver));
return promise;
}
@@ -116,8 +116,8 @@ ServiceWorkerRegistrationNotifications::From(
Supplement<ServiceWorkerRegistration>::From<
ServiceWorkerRegistrationNotifications>(registration);
if (!supplement) {
- supplement = new ServiceWorkerRegistrationNotifications(execution_context,
- &registration);
+ supplement = MakeGarbageCollected<ServiceWorkerRegistrationNotifications>(
+ execution_context, &registration);
ProvideTo(registration, supplement);
}
return *supplement;
@@ -128,10 +128,11 @@ void ServiceWorkerRegistrationNotifications::PrepareShow(
ScriptPromiseResolver* resolver) {
scoped_refptr<const SecurityOrigin> origin =
GetExecutionContext()->GetSecurityOrigin();
- NotificationResourcesLoader* loader = new NotificationResourcesLoader(
- WTF::Bind(&ServiceWorkerRegistrationNotifications::DidLoadResources,
- WrapWeakPersistent(this), std::move(origin), data->Clone(),
- WrapPersistent(resolver)));
+ NotificationResourcesLoader* loader =
+ MakeGarbageCollected<NotificationResourcesLoader>(
+ WTF::Bind(&ServiceWorkerRegistrationNotifications::DidLoadResources,
+ WrapWeakPersistent(this), std::move(origin), data->Clone(),
+ WrapPersistent(resolver)));
loaders_.insert(loader);
loader->Start(GetExecutionContext(), *data);
}
@@ -144,7 +145,7 @@ void ServiceWorkerRegistrationNotifications::DidLoadResources(
DCHECK(loaders_.Contains(loader));
NotificationManager::From(GetExecutionContext())
- ->DisplayPersistentNotification(registration_->WebRegistration(),
+ ->DisplayPersistentNotification(registration_->RegistrationId(),
std::move(data), loader->GetResources(),
WrapPersistent(resolver));
loaders_.erase(loader);
diff --git a/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.h b/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.h
index 38c1ad06f17..dd09d8438ad 100644
--- a/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.h
+++ b/chromium/third_party/blink/renderer/modules/notifications/service_worker_registration_notifications.h
@@ -41,11 +41,14 @@ class ServiceWorkerRegistrationNotifications final
static ScriptPromise showNotification(ScriptState* script_state,
ServiceWorkerRegistration& registration,
const String& title,
- const NotificationOptions& options,
+ const NotificationOptions* options,
ExceptionState& exception_state);
static ScriptPromise getNotifications(ScriptState* script_state,
ServiceWorkerRegistration& registration,
- const GetNotificationOptions& options);
+ const GetNotificationOptions* options);
+
+ ServiceWorkerRegistrationNotifications(ExecutionContext*,
+ ServiceWorkerRegistration*);
// ContextLifecycleObserver interface.
void ContextDestroyed(ExecutionContext* context) override;
@@ -53,9 +56,6 @@ class ServiceWorkerRegistrationNotifications final
void Trace(blink::Visitor* visitor) override;
private:
- ServiceWorkerRegistrationNotifications(ExecutionContext*,
- ServiceWorkerRegistration*);
-
static ServiceWorkerRegistrationNotifications& From(
ExecutionContext* context,
ServiceWorkerRegistration& registration);
diff --git a/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.cc b/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.cc
index bfa812d0166..752bbc1728d 100644
--- a/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.cc
@@ -18,13 +18,13 @@ namespace blink {
AbortPaymentEvent* AbortPaymentEvent::Create(
const AtomicString& type,
- const ExtendableEventInit& initializer) {
+ const ExtendableEventInit* initializer) {
return new AbortPaymentEvent(type, initializer, nullptr, nullptr);
}
AbortPaymentEvent* AbortPaymentEvent::Create(
const AtomicString& type,
- const ExtendableEventInit& initializer,
+ const ExtendableEventInit* initializer,
RespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer) {
return new AbortPaymentEvent(type, initializer, respond_with_observer,
@@ -34,7 +34,7 @@ AbortPaymentEvent* AbortPaymentEvent::Create(
AbortPaymentEvent::~AbortPaymentEvent() = default;
const AtomicString& AbortPaymentEvent::InterfaceName() const {
- return EventNames::AbortPaymentEvent;
+ return event_interface_names::kAbortPaymentEvent;
}
void AbortPaymentEvent::respondWith(ScriptState* script_state,
@@ -52,7 +52,7 @@ void AbortPaymentEvent::Trace(blink::Visitor* visitor) {
}
AbortPaymentEvent::AbortPaymentEvent(const AtomicString& type,
- const ExtendableEventInit& initializer,
+ const ExtendableEventInit* initializer,
RespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer)
: ExtendableEvent(type, initializer, wait_until_observer),
diff --git a/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.h b/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.h
index 6fc74bf58c3..6f77bbd5275 100644
--- a/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.h
+++ b/chromium/third_party/blink/renderer/modules/payments/abort_payment_event.h
@@ -27,9 +27,9 @@ class MODULES_EXPORT AbortPaymentEvent final : public ExtendableEvent {
public:
static AbortPaymentEvent* Create(const AtomicString& type,
- const ExtendableEventInit&);
+ const ExtendableEventInit*);
static AbortPaymentEvent* Create(const AtomicString& type,
- const ExtendableEventInit&,
+ const ExtendableEventInit*,
RespondWithObserver*,
WaitUntilObserver*);
~AbortPaymentEvent() override;
@@ -42,7 +42,7 @@ class MODULES_EXPORT AbortPaymentEvent final : public ExtendableEvent {
private:
AbortPaymentEvent(const AtomicString& type,
- const ExtendableEventInit&,
+ const ExtendableEventInit*,
RespondWithObserver*,
WaitUntilObserver*);
diff --git a/chromium/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc b/chromium/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc
index b44dae52744..55992d19323 100644
--- a/chromium/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc
@@ -27,7 +27,7 @@ void AbortPaymentRespondWithObserver::OnResponseRejected(
"AbortPaymentEvent", error);
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToAbortPaymentEvent(event_id_, false, event_dispatch_time_);
+ ->RespondToAbortPaymentEvent(event_id_, false);
}
void AbortPaymentRespondWithObserver::OnResponseFulfilled(
@@ -47,13 +47,13 @@ void AbortPaymentRespondWithObserver::OnResponseFulfilled(
}
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToAbortPaymentEvent(event_id_, response, event_dispatch_time_);
+ ->RespondToAbortPaymentEvent(event_id_, response);
}
void AbortPaymentRespondWithObserver::OnNoResponse() {
DCHECK(GetExecutionContext());
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToAbortPaymentEvent(event_id_, false, event_dispatch_time_);
+ ->RespondToAbortPaymentEvent(event_id_, false);
}
void AbortPaymentRespondWithObserver::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/payments/basic_card_helper.cc b/chromium/third_party/blink/renderer/modules/payments/basic_card_helper.cc
index 3d3511afe79..c454b57ccec 100644
--- a/chromium/third_party/blink/renderer/modules/payments/basic_card_helper.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/basic_card_helper.cc
@@ -43,20 +43,20 @@ void BasicCardHelper::ParseBasiccardData(
ExceptionState& exception_state) {
DCHECK(!input.IsEmpty());
- BasicCardRequest basic_card;
+ BasicCardRequest* basic_card = BasicCardRequest::Create();
V8BasicCardRequest::ToImpl(input.GetIsolate(), input.V8Value(), basic_card,
exception_state);
if (exception_state.HadException())
return;
- if (basic_card.hasSupportedNetworks()) {
- if (basic_card.supportedNetworks().size() > PaymentRequest::kMaxListSize) {
+ if (basic_card->hasSupportedNetworks()) {
+ if (basic_card->supportedNetworks().size() > PaymentRequest::kMaxListSize) {
exception_state.ThrowTypeError(
"basic-card supportedNetworks cannot be longer than 1024 elements");
return;
}
- for (const String& network : basic_card.supportedNetworks()) {
+ for (const String& network : basic_card->supportedNetworks()) {
for (size_t i = 0; i < arraysize(kBasicCardNetworks); ++i) {
if (network == kBasicCardNetworks[i].name) {
supported_networks_output.push_back(kBasicCardNetworks[i].code);
@@ -66,14 +66,14 @@ void BasicCardHelper::ParseBasiccardData(
}
}
- if (basic_card.hasSupportedTypes()) {
- if (basic_card.supportedTypes().size() > PaymentRequest::kMaxListSize) {
+ if (basic_card->hasSupportedTypes()) {
+ if (basic_card->supportedTypes().size() > PaymentRequest::kMaxListSize) {
exception_state.ThrowTypeError(
"basic-card supportedTypes cannot be longer than 1024 elements");
return;
}
- for (const String& type : basic_card.supportedTypes()) {
+ for (const String& type : basic_card->supportedTypes()) {
for (size_t i = 0; i < arraysize(kBasicCardTypes); ++i) {
if (type == kBasicCardTypes[i].name) {
supported_types_output.push_back(kBasicCardTypes[i].code);
diff --git a/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.cc b/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.cc
index 106793d6bd2..a03a1d06f5c 100644
--- a/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.cc
@@ -17,13 +17,13 @@ namespace blink {
CanMakePaymentEvent* CanMakePaymentEvent::Create(
const AtomicString& type,
- const CanMakePaymentEventInit& initializer) {
+ const CanMakePaymentEventInit* initializer) {
return new CanMakePaymentEvent(type, initializer, nullptr, nullptr);
}
CanMakePaymentEvent* CanMakePaymentEvent::Create(
const AtomicString& type,
- const CanMakePaymentEventInit& initializer,
+ const CanMakePaymentEventInit* initializer,
RespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer) {
return new CanMakePaymentEvent(type, initializer, respond_with_observer,
@@ -33,7 +33,7 @@ CanMakePaymentEvent* CanMakePaymentEvent::Create(
CanMakePaymentEvent::~CanMakePaymentEvent() = default;
const AtomicString& CanMakePaymentEvent::InterfaceName() const {
- return EventNames::CanMakePaymentEvent;
+ return event_interface_names::kCanMakePaymentEvent;
}
const String& CanMakePaymentEvent::topOrigin() const {
@@ -44,12 +44,13 @@ const String& CanMakePaymentEvent::paymentRequestOrigin() const {
return payment_request_origin_;
}
-const HeapVector<PaymentMethodData>& CanMakePaymentEvent::methodData() const {
+const HeapVector<Member<PaymentMethodData>>& CanMakePaymentEvent::methodData()
+ const {
return method_data_;
}
-const HeapVector<PaymentDetailsModifier>& CanMakePaymentEvent::modifiers()
- const {
+const HeapVector<Member<PaymentDetailsModifier>>&
+CanMakePaymentEvent::modifiers() const {
return modifiers_;
}
@@ -78,18 +79,18 @@ void CanMakePaymentEvent::Trace(blink::Visitor* visitor) {
CanMakePaymentEvent::CanMakePaymentEvent(
const AtomicString& type,
- const CanMakePaymentEventInit& initializer,
+ const CanMakePaymentEventInit* initializer,
RespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer)
: ExtendableEvent(type, initializer, wait_until_observer),
- top_origin_(initializer.topOrigin()),
- payment_request_origin_(initializer.paymentRequestOrigin()),
- method_data_(initializer.hasMethodData()
- ? initializer.methodData()
- : HeapVector<PaymentMethodData>()),
- modifiers_(initializer.hasModifiers()
- ? initializer.modifiers()
- : HeapVector<PaymentDetailsModifier>()),
+ top_origin_(initializer->topOrigin()),
+ payment_request_origin_(initializer->paymentRequestOrigin()),
+ method_data_(initializer->hasMethodData()
+ ? initializer->methodData()
+ : HeapVector<Member<PaymentMethodData>>()),
+ modifiers_(initializer->hasModifiers()
+ ? initializer->modifiers()
+ : HeapVector<Member<PaymentDetailsModifier>>()),
observer_(respond_with_observer) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.h b/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.h
index 486eb43c666..3931550f133 100644
--- a/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.h
+++ b/chromium/third_party/blink/renderer/modules/payments/can_make_payment_event.h
@@ -28,9 +28,9 @@ class MODULES_EXPORT CanMakePaymentEvent final : public ExtendableEvent {
public:
static CanMakePaymentEvent* Create(const AtomicString& type,
- const CanMakePaymentEventInit&);
+ const CanMakePaymentEventInit*);
static CanMakePaymentEvent* Create(const AtomicString& type,
- const CanMakePaymentEventInit&,
+ const CanMakePaymentEventInit*,
RespondWithObserver*,
WaitUntilObserver*);
~CanMakePaymentEvent() override;
@@ -39,8 +39,8 @@ class MODULES_EXPORT CanMakePaymentEvent final : public ExtendableEvent {
const String& topOrigin() const;
const String& paymentRequestOrigin() const;
- const HeapVector<PaymentMethodData>& methodData() const;
- const HeapVector<PaymentDetailsModifier>& modifiers() const;
+ const HeapVector<Member<PaymentMethodData>>& methodData() const;
+ const HeapVector<Member<PaymentDetailsModifier>>& modifiers() const;
void respondWith(ScriptState*, ScriptPromise, ExceptionState&);
@@ -48,14 +48,14 @@ class MODULES_EXPORT CanMakePaymentEvent final : public ExtendableEvent {
private:
CanMakePaymentEvent(const AtomicString& type,
- const CanMakePaymentEventInit&,
+ const CanMakePaymentEventInit*,
RespondWithObserver*,
WaitUntilObserver*);
String top_origin_;
String payment_request_origin_;
- HeapVector<PaymentMethodData> method_data_;
- HeapVector<PaymentDetailsModifier> modifiers_;
+ HeapVector<Member<PaymentMethodData>> method_data_;
+ HeapVector<Member<PaymentDetailsModifier>> modifiers_;
Member<RespondWithObserver> observer_;
};
diff --git a/chromium/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc b/chromium/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc
index 60da1171b80..41e87e2b80a 100644
--- a/chromium/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc
@@ -27,7 +27,7 @@ void CanMakePaymentRespondWithObserver::OnResponseRejected(
"CanMakePaymentEvent", error);
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToCanMakePaymentEvent(event_id_, false, event_dispatch_time_);
+ ->RespondToCanMakePaymentEvent(event_id_, false);
}
void CanMakePaymentRespondWithObserver::OnResponseFulfilled(
@@ -47,13 +47,13 @@ void CanMakePaymentRespondWithObserver::OnResponseFulfilled(
}
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToCanMakePaymentEvent(event_id_, response, event_dispatch_time_);
+ ->RespondToCanMakePaymentEvent(event_id_, response);
}
void CanMakePaymentRespondWithObserver::OnNoResponse() {
DCHECK(GetExecutionContext());
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToCanMakePaymentEvent(event_id_, true, event_dispatch_time_);
+ ->RespondToCanMakePaymentEvent(event_id_, true);
}
void CanMakePaymentRespondWithObserver::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.cc b/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.cc
index 39a0071428f..0170596ef7d 100644
--- a/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.cc
@@ -20,7 +20,7 @@ const char HTMLIFrameElementPayments::kSupplementName[] =
bool HTMLIFrameElementPayments::FastHasAttribute(
const QualifiedName& name,
const HTMLIFrameElement& element) {
- DCHECK(name == HTMLNames::allowpaymentrequestAttr);
+ DCHECK(name == html_names::kAllowpaymentrequestAttr);
return element.FastHasAttribute(name);
}
@@ -28,7 +28,7 @@ bool HTMLIFrameElementPayments::FastHasAttribute(
void HTMLIFrameElementPayments::SetBooleanAttribute(const QualifiedName& name,
HTMLIFrameElement& element,
bool value) {
- DCHECK(name == HTMLNames::allowpaymentrequestAttr);
+ DCHECK(name == html_names::kAllowpaymentrequestAttr);
element.SetBooleanAttribute(name, value);
}
@@ -38,7 +38,7 @@ HTMLIFrameElementPayments& HTMLIFrameElementPayments::From(
HTMLIFrameElementPayments* supplement =
Supplement<HTMLIFrameElement>::From<HTMLIFrameElementPayments>(iframe);
if (!supplement) {
- supplement = new HTMLIFrameElementPayments();
+ supplement = MakeGarbageCollected<HTMLIFrameElementPayments>();
ProvideTo(iframe, supplement);
}
return *supplement;
@@ -48,7 +48,7 @@ HTMLIFrameElementPayments& HTMLIFrameElementPayments::From(
bool HTMLIFrameElementPayments::AllowPaymentRequest(
HTMLIFrameElement& element) {
return RuntimeEnabledFeatures::PaymentRequestEnabled() &&
- element.FastHasAttribute(HTMLNames::allowpaymentrequestAttr);
+ element.FastHasAttribute(html_names::kAllowpaymentrequestAttr);
}
void HTMLIFrameElementPayments::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.h b/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.h
index 0d1c9c30ea1..195d5e3de67 100644
--- a/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.h
+++ b/chromium/third_party/blink/renderer/modules/payments/html_iframe_element_payments.h
@@ -22,6 +22,8 @@ class HTMLIFrameElementPayments final
public:
static const char kSupplementName[];
+ HTMLIFrameElementPayments();
+
static bool FastHasAttribute(const QualifiedName&, const HTMLIFrameElement&);
static void SetBooleanAttribute(const QualifiedName&,
HTMLIFrameElement&,
@@ -30,9 +32,6 @@ class HTMLIFrameElementPayments final
static bool AllowPaymentRequest(HTMLIFrameElement&);
void Trace(blink::Visitor*) override;
-
- private:
- HTMLIFrameElementPayments();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/on_payment_response_test.cc b/chromium/third_party/blink/renderer/modules/payments/on_payment_response_test.cc
index dc139e1e201..5c3852d70b1 100644
--- a/chromium/third_party/blink/renderer/modules/payments/on_payment_response_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/on_payment_response_test.cc
@@ -22,8 +22,8 @@ TEST(OnPaymentResponseTest, RejectMissingShippingOption) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -48,8 +48,8 @@ TEST(OnPaymentResponseTest, RejectMissingAddress) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -71,8 +71,8 @@ TEST(OnPaymentResponseTest, RejectMissingName) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerName(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerName(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -93,8 +93,8 @@ TEST(OnPaymentResponseTest, RejectMissingEmail) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerEmail(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerEmail(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -115,8 +115,8 @@ TEST(OnPaymentResponseTest, RejectMissingPhone) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerPhone(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerPhone(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -137,8 +137,8 @@ TEST(OnPaymentResponseTest, RejectEmptyShippingOption) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -164,8 +164,8 @@ TEST(OnPaymentResponseTest, RejectEmptyAddress) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -188,8 +188,8 @@ TEST(OnPaymentResponseTest, RejectEmptyName) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerName(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerName(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -211,8 +211,8 @@ TEST(OnPaymentResponseTest, RejectEmptyEmail) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerEmail(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerEmail(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -234,8 +234,8 @@ TEST(OnPaymentResponseTest, RejectEmptyPhone) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerPhone(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerPhone(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -257,8 +257,8 @@ TEST(OnPaymentResponseTest, RejectNotRequestedAddress) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -283,8 +283,8 @@ TEST(OnPaymentResponseTest, RejectNotRequestedShippingOption) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -306,8 +306,8 @@ TEST(OnPaymentResponseTest, RejectNotRequestedName) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerName(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerName(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -329,8 +329,8 @@ TEST(OnPaymentResponseTest, RejectNotRequestedEmail) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerEmail(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerEmail(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -352,8 +352,8 @@ TEST(OnPaymentResponseTest, RejectNotRequestedPhone) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerPhone(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerPhone(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -375,8 +375,8 @@ TEST(OnPaymentResponseTest, RejectInvalidAddress) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -424,8 +424,8 @@ TEST(OnPaymentResponseTest, CanRequestShippingInformation) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -459,8 +459,8 @@ TEST(OnPaymentResponseTest, CanRequestName) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerName(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerName(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -489,8 +489,8 @@ TEST(OnPaymentResponseTest, CanRequestEmail) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerEmail(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerEmail(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -518,8 +518,8 @@ TEST(OnPaymentResponseTest, CanRequestPhone) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerPhone(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerPhone(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -548,8 +548,8 @@ TEST(OnPaymentResponseTest, ShippingInformationNotRequired) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -575,8 +575,8 @@ TEST(OnPaymentResponseTest, PhoneNotRequred) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerPhone(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerPhone(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -604,8 +604,8 @@ TEST(OnPaymentResponseTest, NameNotRequired) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerName(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerName(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -633,8 +633,8 @@ TEST(OnPaymentResponseTest, EmailNotRequired) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestPayerEmail(false);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestPayerEmail(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_address_test.cc b/chromium/third_party/blink/renderer/modules/payments/payment_address_test.cc
index 5ec262ed8e1..80f5b65457d 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_address_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_address_test.cc
@@ -28,7 +28,8 @@ TEST(PaymentAddressTest, ValuesAreCopiedOver) {
input->recipient = "Jon Doe";
input->phone = "Phone Number";
- PaymentAddress* output = new PaymentAddress(std::move(input));
+ PaymentAddress* output =
+ MakeGarbageCollected<PaymentAddress>(std::move(input));
EXPECT_EQ("US", output->country());
EXPECT_EQ(3U, output->addressLine().size());
@@ -51,7 +52,8 @@ TEST(PaymentAddressTest, IgnoreScriptCodeWithEmptyLanguageCode) {
payments::mojom::blink::PaymentAddress::New();
input->script_code = "Latn";
- PaymentAddress* output = new PaymentAddress(std::move(input));
+ PaymentAddress* output =
+ MakeGarbageCollected<PaymentAddress>(std::move(input));
EXPECT_TRUE(output->languageCode().IsEmpty());
}
@@ -61,7 +63,8 @@ TEST(PaymentAddressTest, NoHyphenWithEmptyScriptCode) {
payments::mojom::blink::PaymentAddress::New();
input->language_code = "en";
- PaymentAddress* output = new PaymentAddress(std::move(input));
+ PaymentAddress* output =
+ MakeGarbageCollected<PaymentAddress>(std::move(input));
EXPECT_EQ("en", output->languageCode());
}
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_global_scope.h b/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_global_scope.h
index bc21367a3f0..47242ed9d4a 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_global_scope.h
@@ -14,9 +14,9 @@ class PaymentAppServiceWorkerGlobalScope {
STATIC_ONLY(PaymentAppServiceWorkerGlobalScope);
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abortpayment);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canmakepayment);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(paymentrequest);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abortpayment, kAbortpayment);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canmakepayment, kCanmakepayment);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(paymentrequest, kPaymentrequest);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.cc b/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.cc
index d8a139f0275..55b96f6e9ed 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.cc
@@ -22,7 +22,8 @@ PaymentAppServiceWorkerRegistration& PaymentAppServiceWorkerRegistration::From(
PaymentAppServiceWorkerRegistration>(registration);
if (!supplement) {
- supplement = new PaymentAppServiceWorkerRegistration(&registration);
+ supplement = MakeGarbageCollected<PaymentAppServiceWorkerRegistration>(
+ &registration);
ProvideTo(registration, supplement);
}
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.h b/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.h
index 337c715f31b..5e8f5a0ac31 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_app_service_worker_registration.h
@@ -24,7 +24,9 @@ class PaymentAppServiceWorkerRegistration final
public:
static const char kSupplementName[];
+ explicit PaymentAppServiceWorkerRegistration(ServiceWorkerRegistration*);
virtual ~PaymentAppServiceWorkerRegistration();
+
static PaymentAppServiceWorkerRegistration& From(ServiceWorkerRegistration&);
static PaymentManager* paymentManager(ScriptState*,
@@ -34,8 +36,6 @@ class PaymentAppServiceWorkerRegistration final
void Trace(blink::Visitor*) override;
private:
- explicit PaymentAppServiceWorkerRegistration(ServiceWorkerRegistration*);
-
Member<ServiceWorkerRegistration> registration_;
Member<PaymentManager> payment_manager_;
};
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.cc b/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.cc
index f96645282a7..877ffc58823 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/public/platform/modules/payments/web_payment_method_data.h"
#include "third_party/blink/public/platform/modules/payments/web_payment_request_event_data.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
+#include "third_party/blink/renderer/modules/payments/can_make_payment_event_init.h"
#include "third_party/blink/renderer/modules/payments/payment_currency_amount.h"
#include "third_party/blink/renderer/modules/payments/payment_details_modifier.h"
#include "third_party/blink/renderer/modules/payments/payment_item.h"
@@ -17,33 +18,33 @@
namespace blink {
namespace {
-PaymentCurrencyAmount ToPaymentCurrencyAmount(
+PaymentCurrencyAmount* ToPaymentCurrencyAmount(
const WebPaymentCurrencyAmount& web_amount) {
- PaymentCurrencyAmount amount;
- amount.setCurrency(web_amount.currency);
- amount.setValue(web_amount.value);
+ PaymentCurrencyAmount* amount = PaymentCurrencyAmount::Create();
+ amount->setCurrency(web_amount.currency);
+ amount->setValue(web_amount.value);
return amount;
}
-PaymentItem ToPaymentItem(const WebPaymentItem& web_item) {
- PaymentItem item;
- item.setLabel(web_item.label);
- item.setAmount(ToPaymentCurrencyAmount(web_item.amount));
- item.setPending(web_item.pending);
+PaymentItem* ToPaymentItem(const WebPaymentItem& web_item) {
+ PaymentItem* item = PaymentItem::Create();
+ item->setLabel(web_item.label);
+ item->setAmount(ToPaymentCurrencyAmount(web_item.amount));
+ item->setPending(web_item.pending);
return item;
}
-PaymentDetailsModifier ToPaymentDetailsModifier(
+PaymentDetailsModifier* ToPaymentDetailsModifier(
ScriptState* script_state,
const WebPaymentDetailsModifier& web_modifier) {
- PaymentDetailsModifier modifier;
- modifier.setSupportedMethod(web_modifier.supported_method);
- modifier.setTotal(ToPaymentItem(web_modifier.total));
- HeapVector<PaymentItem> additional_display_items;
+ PaymentDetailsModifier* modifier = PaymentDetailsModifier::Create();
+ modifier->setSupportedMethod(web_modifier.supported_method);
+ modifier->setTotal(ToPaymentItem(web_modifier.total));
+ HeapVector<Member<PaymentItem>> additional_display_items;
for (const auto& web_item : web_modifier.additional_display_items) {
additional_display_items.push_back(ToPaymentItem(web_item));
}
- modifier.setAdditionalDisplayItems(additional_display_items);
+ modifier->setAdditionalDisplayItems(additional_display_items);
return modifier;
}
@@ -62,70 +63,70 @@ ScriptValue StringDataToScriptValue(ScriptState* script_state,
return ScriptValue(script_state, v8_value);
}
-PaymentMethodData ToPaymentMethodData(
+PaymentMethodData* ToPaymentMethodData(
ScriptState* script_state,
const WebPaymentMethodData& web_method_data) {
- PaymentMethodData method_data;
- method_data.setSupportedMethod(web_method_data.supported_method);
- method_data.setData(
+ PaymentMethodData* method_data = PaymentMethodData::Create();
+ method_data->setSupportedMethod(web_method_data.supported_method);
+ method_data->setData(
StringDataToScriptValue(script_state, web_method_data.stringified_data));
return method_data;
}
} // namespace
-PaymentRequestEventInit PaymentEventDataConversion::ToPaymentRequestEventInit(
+PaymentRequestEventInit* PaymentEventDataConversion::ToPaymentRequestEventInit(
ScriptState* script_state,
const WebPaymentRequestEventData& web_event_data) {
DCHECK(script_state);
- PaymentRequestEventInit event_data;
+ PaymentRequestEventInit* event_data = PaymentRequestEventInit::Create();
if (!script_state->ContextIsValid())
return event_data;
ScriptState::Scope scope(script_state);
- event_data.setTopOrigin(web_event_data.top_origin);
- event_data.setPaymentRequestOrigin(web_event_data.payment_request_origin);
- event_data.setPaymentRequestId(web_event_data.payment_request_id);
- HeapVector<PaymentMethodData> method_data;
+ event_data->setTopOrigin(web_event_data.top_origin);
+ event_data->setPaymentRequestOrigin(web_event_data.payment_request_origin);
+ event_data->setPaymentRequestId(web_event_data.payment_request_id);
+ HeapVector<Member<PaymentMethodData>> method_data;
for (const auto& md : web_event_data.method_data) {
method_data.push_back(ToPaymentMethodData(script_state, md));
}
- event_data.setMethodData(method_data);
- event_data.setTotal(ToPaymentCurrencyAmount(web_event_data.total));
- HeapVector<PaymentDetailsModifier> modifiers;
+ event_data->setMethodData(method_data);
+ event_data->setTotal(ToPaymentCurrencyAmount(web_event_data.total));
+ HeapVector<Member<PaymentDetailsModifier>> modifiers;
for (const auto& modifier : web_event_data.modifiers) {
modifiers.push_back(ToPaymentDetailsModifier(script_state, modifier));
}
- event_data.setModifiers(modifiers);
- event_data.setInstrumentKey(web_event_data.instrument_key);
+ event_data->setModifiers(modifiers);
+ event_data->setInstrumentKey(web_event_data.instrument_key);
return event_data;
}
-CanMakePaymentEventInit PaymentEventDataConversion::ToCanMakePaymentEventInit(
+CanMakePaymentEventInit* PaymentEventDataConversion::ToCanMakePaymentEventInit(
ScriptState* script_state,
const WebCanMakePaymentEventData& web_event_data) {
DCHECK(script_state);
- CanMakePaymentEventInit event_data;
+ CanMakePaymentEventInit* event_data = CanMakePaymentEventInit::Create();
if (!script_state->ContextIsValid())
return event_data;
ScriptState::Scope scope(script_state);
- event_data.setTopOrigin(web_event_data.top_origin);
- event_data.setPaymentRequestOrigin(web_event_data.payment_request_origin);
- HeapVector<PaymentMethodData> method_data;
+ event_data->setTopOrigin(web_event_data.top_origin);
+ event_data->setPaymentRequestOrigin(web_event_data.payment_request_origin);
+ HeapVector<Member<PaymentMethodData>> method_data;
for (const auto& md : web_event_data.method_data) {
method_data.push_back(ToPaymentMethodData(script_state, md));
}
- event_data.setMethodData(method_data);
- HeapVector<PaymentDetailsModifier> modifiers;
+ event_data->setMethodData(method_data);
+ HeapVector<Member<PaymentDetailsModifier>> modifiers;
for (const auto& modifier : web_event_data.modifiers) {
modifiers.push_back(ToPaymentDetailsModifier(script_state, modifier));
}
- event_data.setModifiers(modifiers);
+ event_data->setModifiers(modifiers);
return event_data;
}
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.h b/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.h
index 9e03c6eb051..e8643e7c33b 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion.h
@@ -11,6 +11,8 @@
namespace blink {
+class CanMakePaymentEventInit;
+class PaymentRequestEventInit;
class ScriptState;
struct WebCanMakePaymentEventData;
struct WebPaymentRequestEventData;
@@ -19,10 +21,10 @@ class MODULES_EXPORT PaymentEventDataConversion {
STATIC_ONLY(PaymentEventDataConversion);
public:
- static CanMakePaymentEventInit ToCanMakePaymentEventInit(
+ static CanMakePaymentEventInit* ToCanMakePaymentEventInit(
ScriptState*,
const WebCanMakePaymentEventData&);
- static PaymentRequestEventInit ToPaymentRequestEventInit(
+ static PaymentRequestEventInit* ToPaymentRequestEventInit(
ScriptState*,
const WebPaymentRequestEventData&);
};
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion_test.cc b/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion_test.cc
index 3f0109f72f1..a1db5a3fa70 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_event_data_conversion_test.cc
@@ -56,26 +56,26 @@ TEST(PaymentEventDataConversionTest, ToCanMakePaymentEventData) {
V8TestingScope scope;
WebCanMakePaymentEventData web_data =
CreateWebCanMakePaymentEventDataForTest();
- CanMakePaymentEventInit data =
+ CanMakePaymentEventInit* data =
PaymentEventDataConversion::ToCanMakePaymentEventInit(
scope.GetScriptState(), web_data);
- ASSERT_TRUE(data.hasTopOrigin());
- EXPECT_EQ("https://example.com", data.topOrigin());
+ ASSERT_TRUE(data->hasTopOrigin());
+ EXPECT_EQ("https://example.com", data->topOrigin());
- ASSERT_TRUE(data.hasPaymentRequestOrigin());
- EXPECT_EQ("https://example.com", data.paymentRequestOrigin());
+ ASSERT_TRUE(data->hasPaymentRequestOrigin());
+ EXPECT_EQ("https://example.com", data->paymentRequestOrigin());
- ASSERT_TRUE(data.hasMethodData());
- ASSERT_EQ(1UL, data.methodData().size());
- ASSERT_TRUE(data.methodData().front().hasSupportedMethod());
- ASSERT_EQ("foo", data.methodData().front().supportedMethod());
- ASSERT_TRUE(data.methodData().front().hasData());
- ASSERT_TRUE(data.methodData().front().data().IsObject());
+ ASSERT_TRUE(data->hasMethodData());
+ ASSERT_EQ(1UL, data->methodData().size());
+ ASSERT_TRUE(data->methodData().front()->hasSupportedMethod());
+ ASSERT_EQ("foo", data->methodData().front()->supportedMethod());
+ ASSERT_TRUE(data->methodData().front()->hasData());
+ ASSERT_TRUE(data->methodData().front()->data().IsObject());
String stringified_data = ToBlinkString<String>(
v8::JSON::Stringify(
scope.GetContext(),
- data.methodData().front().data().V8Value().As<v8::Object>())
+ data->methodData().front()->data().V8Value().As<v8::Object>())
.ToLocalChecked(),
kDoNotExternalize);
EXPECT_EQ("{\"merchantId\":\"12345\"}", stringified_data);
@@ -85,41 +85,41 @@ TEST(PaymentEventDataConversionTest, ToPaymentRequestEventData) {
V8TestingScope scope;
WebPaymentRequestEventData web_data =
CreateWebPaymentRequestEventDataForTest();
- PaymentRequestEventInit data =
+ PaymentRequestEventInit* data =
PaymentEventDataConversion::ToPaymentRequestEventInit(
scope.GetScriptState(), web_data);
- ASSERT_TRUE(data.hasTopOrigin());
- EXPECT_EQ("https://example.com", data.topOrigin());
+ ASSERT_TRUE(data->hasTopOrigin());
+ EXPECT_EQ("https://example.com", data->topOrigin());
- ASSERT_TRUE(data.hasPaymentRequestOrigin());
- EXPECT_EQ("https://example.com", data.paymentRequestOrigin());
+ ASSERT_TRUE(data->hasPaymentRequestOrigin());
+ EXPECT_EQ("https://example.com", data->paymentRequestOrigin());
- ASSERT_TRUE(data.hasPaymentRequestId());
- EXPECT_EQ("payment-request-id", data.paymentRequestId());
+ ASSERT_TRUE(data->hasPaymentRequestId());
+ EXPECT_EQ("payment-request-id", data->paymentRequestId());
- ASSERT_TRUE(data.hasMethodData());
- ASSERT_EQ(1UL, data.methodData().size());
- ASSERT_TRUE(data.methodData().front().hasSupportedMethod());
- ASSERT_EQ("foo", data.methodData().front().supportedMethod());
- ASSERT_TRUE(data.methodData().front().hasData());
- ASSERT_TRUE(data.methodData().front().data().IsObject());
+ ASSERT_TRUE(data->hasMethodData());
+ ASSERT_EQ(1UL, data->methodData().size());
+ ASSERT_TRUE(data->methodData().front()->hasSupportedMethod());
+ ASSERT_EQ("foo", data->methodData().front()->supportedMethod());
+ ASSERT_TRUE(data->methodData().front()->hasData());
+ ASSERT_TRUE(data->methodData().front()->data().IsObject());
String stringified_data = ToBlinkString<String>(
v8::JSON::Stringify(
scope.GetContext(),
- data.methodData().front().data().V8Value().As<v8::Object>())
+ data->methodData().front()->data().V8Value().As<v8::Object>())
.ToLocalChecked(),
kDoNotExternalize);
EXPECT_EQ("{\"merchantId\":\"12345\"}", stringified_data);
- ASSERT_TRUE(data.hasTotal());
- ASSERT_TRUE(data.total().hasCurrency());
- EXPECT_EQ("USD", data.total().currency());
- ASSERT_TRUE(data.total().hasValue());
- EXPECT_EQ("9.99", data.total().value());
+ ASSERT_TRUE(data->hasTotal());
+ ASSERT_TRUE(data->total()->hasCurrency());
+ EXPECT_EQ("USD", data->total()->currency());
+ ASSERT_TRUE(data->total()->hasValue());
+ EXPECT_EQ("9.99", data->total()->value());
- ASSERT_TRUE(data.hasInstrumentKey());
- EXPECT_EQ("payment-instrument-key", data.instrumentKey());
+ ASSERT_TRUE(data->hasInstrumentKey());
+ EXPECT_EQ("payment-instrument-key", data->instrumentKey());
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_handler_utils.cc b/chromium/third_party/blink/renderer/modules/payments/payment_handler_utils.cc
index 7a571d466d0..215faa28ea3 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_handler_utils.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_handler_utils.cc
@@ -43,7 +43,7 @@ void PaymentHandlerUtils::ReportResponseError(
case ServiceWorkerResponseError::kBodyLocked:
case ServiceWorkerResponseError::kRedirectedResponseForNotFollowRequest:
case ServiceWorkerResponseError::kDataPipeCreationFailed:
- case ServiceWorkerResponseError::kResponseTypeCORSForRequestModeSameOrigin:
+ case ServiceWorkerResponseError::kResponseTypeCorsForRequestModeSameOrigin:
case ServiceWorkerResponseError::kResponseBodyBroken:
NOTREACHED();
error_message = error_message + "an unexpected error occurred.";
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_instruments.cc b/chromium/third_party/blink/renderer/modules/payments/payment_instruments.cc
index c452409fdbf..d67dd5b2c92 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_instruments.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_instruments.cc
@@ -28,6 +28,7 @@
#include "third_party/blink/renderer/modules/payments/payment_manager.h"
#include "third_party/blink/renderer/modules/permissions/permission_utils.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -40,10 +41,6 @@ bool rejectError(ScriptPromiseResolver* resolver,
switch (status) {
case payments::mojom::blink::PaymentHandlerStatus::SUCCESS:
return false;
- case payments::mojom::blink::PaymentHandlerStatus::NOT_IMPLEMENTED:
- resolver->Reject(DOMException::Create(
- DOMExceptionCode::kNotSupportedError, "Not implemented yet"));
- return true;
case payments::mojom::blink::PaymentHandlerStatus::NOT_FOUND:
resolver->Resolve();
return true;
@@ -102,23 +99,23 @@ ScriptPromise RejectNotAllowedToUsePaymentFeatures(ScriptState* script_state) {
class PaymentInstrumentParameter
: public GarbageCollectedFinalized<PaymentInstrumentParameter> {
public:
- explicit PaymentInstrumentParameter(const PaymentInstrument& instrument)
- : has_icons_(instrument.hasIcons()),
- has_capabilities_(instrument.hasCapabilities()),
- has_method_(instrument.hasMethod()),
- has_name_(instrument.hasName()),
- capabilities_(instrument.capabilities()),
- method_(instrument.method()),
- name_(instrument.name()) {
+ explicit PaymentInstrumentParameter(const PaymentInstrument* instrument)
+ : has_icons_(instrument->hasIcons()),
+ has_capabilities_(instrument->hasCapabilities()),
+ has_method_(instrument->hasMethod()),
+ has_name_(instrument->hasName()),
+ capabilities_(instrument->capabilities()),
+ method_(instrument->method()),
+ name_(instrument->name()) {
if (has_icons_)
- icons_ = instrument.icons();
+ icons_ = instrument->icons();
}
bool has_capabilities() const { return has_capabilities_; }
ScriptValue capabilities() const { return capabilities_; }
bool has_icons() const { return has_icons_; }
- const HeapVector<ImageObject>& icons() const { return icons_; }
+ const HeapVector<Member<ImageObject>>& icons() const { return icons_; }
bool has_method() const { return has_method_; }
const String& method() const { return method_; }
@@ -135,7 +132,7 @@ class PaymentInstrumentParameter
bool has_name_;
ScriptValue capabilities_;
- HeapVector<ImageObject> icons_;
+ HeapVector<Member<ImageObject>> icons_;
String method_;
String name_;
};
@@ -229,7 +226,7 @@ ScriptPromise PaymentInstruments::has(ScriptState* script_state,
ScriptPromise PaymentInstruments::set(ScriptState* script_state,
const String& instrument_key,
- const PaymentInstrument& details,
+ const PaymentInstrument* details,
ExceptionState& exception_state) {
if (!AllowedToUsePaymentFeatures(script_state))
return RejectNotAllowedToUsePaymentFeatures(script_state);
@@ -252,10 +249,11 @@ ScriptPromise PaymentInstruments::set(ScriptState* script_state,
mojom::blink::PermissionName::PAYMENT_HANDLER),
LocalFrame::HasTransientUserActivation(doc ? doc->GetFrame()
: nullptr),
- WTF::Bind(&PaymentInstruments::OnRequestPermission,
- WrapPersistent(this), WrapPersistent(resolver),
- instrument_key,
- WrapPersistent(new PaymentInstrumentParameter(details))));
+ WTF::Bind(
+ &PaymentInstruments::OnRequestPermission, WrapPersistent(this),
+ WrapPersistent(resolver), instrument_key,
+ WrapPersistent(
+ MakeGarbageCollected<PaymentInstrumentParameter>(details))));
return resolver->Promise();
}
@@ -313,22 +311,22 @@ void PaymentInstruments::OnRequestPermission(
if (details->has_icons()) {
ExecutionContext* context =
ExecutionContext::From(resolver->GetScriptState());
- for (const ImageObject image_object : details->icons()) {
- KURL parsed_url = context->CompleteURL(image_object.src());
+ for (const ImageObject* image_object : details->icons()) {
+ KURL parsed_url = context->CompleteURL(image_object->src());
if (!parsed_url.IsValid() || !parsed_url.ProtocolIsInHTTPFamily()) {
resolver->Reject(V8ThrowException::CreateTypeError(
resolver->GetScriptState()->GetIsolate(),
- "'" + image_object.src() + "' is not a valid URL."));
+ "'" + image_object->src() + "' is not a valid URL."));
return;
}
mojom::blink::ManifestImageResourcePtr icon =
mojom::blink::ManifestImageResource::New();
icon->src = parsed_url;
- icon->type = image_object.type();
+ icon->type = image_object->type();
icon->purpose.push_back(blink::mojom::ManifestImageResource_Purpose::ANY);
WebVector<WebSize> web_sizes =
- WebIconSizesParser::ParseIconSizes(image_object.sizes());
+ WebIconSizesParser::ParseIconSizes(image_object->sizes());
for (const auto& web_size : web_sizes) {
icon->sizes.push_back(web_size);
}
@@ -396,28 +394,28 @@ void PaymentInstruments::onGetPaymentInstrument(
if (rejectError(resolver, status))
return;
- PaymentInstrument instrument;
- instrument.setName(stored_instrument->name);
+ PaymentInstrument* instrument = PaymentInstrument::Create();
+ instrument->setName(stored_instrument->name);
- HeapVector<ImageObject> icons;
+ HeapVector<Member<ImageObject>> icons;
for (const auto& icon : stored_instrument->icons) {
- ImageObject image_object;
- image_object.setSrc(icon->src.GetString());
- image_object.setType(icon->type);
+ ImageObject* image_object = ImageObject::Create();
+ image_object->setSrc(icon->src.GetString());
+ image_object->setType(icon->type);
String sizes = WTF::g_empty_string;
for (const auto& size : icon->sizes) {
sizes = sizes + String::Format("%dx%d ", size.width, size.height);
}
- image_object.setSizes(sizes.StripWhiteSpace());
- icons.emplace_back(image_object);
+ image_object->setSizes(sizes.StripWhiteSpace());
+ icons.push_back(image_object);
}
- instrument.setIcons(icons);
- instrument.setMethod(stored_instrument->method);
+ instrument->setIcons(icons);
+ instrument->setMethod(stored_instrument->method);
if (!stored_instrument->stringified_capabilities.IsEmpty()) {
ExceptionState exception_state(resolver->GetScriptState()->GetIsolate(),
ExceptionState::kGetterContext,
"PaymentInstruments", "get");
- instrument.setCapabilities(
+ instrument->setCapabilities(
ScriptValue(resolver->GetScriptState(),
FromJSONString(resolver->GetScriptState()->GetIsolate(),
resolver->GetScriptState()->GetContext(),
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_instruments.h b/chromium/third_party/blink/renderer/modules/payments/payment_instruments.h
index 664a90e3c1f..81805d305ea 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_instruments.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_instruments.h
@@ -35,7 +35,7 @@ class MODULES_EXPORT PaymentInstruments final : public ScriptWrappable {
ScriptPromise has(ScriptState*, const String& instrument_key);
ScriptPromise set(ScriptState*,
const String& instrument_key,
- const PaymentInstrument& details,
+ const PaymentInstrument* details,
ExceptionState&);
ScriptPromise clear(ScriptState*);
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_manager.cc b/chromium/third_party/blink/renderer/modules/payments/payment_manager.cc
index 29517bb614a..f9db07d10b6 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_manager.cc
@@ -16,12 +16,12 @@ namespace blink {
PaymentManager* PaymentManager::Create(
ServiceWorkerRegistration* registration) {
- return new PaymentManager(registration);
+ return MakeGarbageCollected<PaymentManager>(registration);
}
PaymentInstruments* PaymentManager::instruments() {
if (!instruments_)
- instruments_ = new PaymentInstruments(manager_);
+ instruments_ = MakeGarbageCollected<PaymentInstruments>(manager_);
return instruments_;
}
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_manager.h b/chromium/third_party/blink/renderer/modules/payments/payment_manager.h
index 139d0018fdb..20677a3d65a 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_manager.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_manager.h
@@ -23,6 +23,8 @@ class MODULES_EXPORT PaymentManager final : public ScriptWrappable {
public:
static PaymentManager* Create(ServiceWorkerRegistration*);
+ explicit PaymentManager(ServiceWorkerRegistration*);
+
PaymentInstruments* instruments();
const String& userHint();
@@ -31,8 +33,6 @@ class MODULES_EXPORT PaymentManager final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit PaymentManager(ServiceWorkerRegistration*);
-
void OnServiceConnectionError();
Member<ServiceWorkerRegistration> registration_;
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.cc b/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.cc
index 7d47a1040c7..72ad2483129 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.cc
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/heap/visitor.h"
namespace blink {
@@ -15,7 +16,7 @@ PaymentMethodChangeEvent::~PaymentMethodChangeEvent() = default;
PaymentMethodChangeEvent* PaymentMethodChangeEvent::Create(
ScriptState* script_state,
const AtomicString& type,
- const PaymentMethodChangeEventInit& init) {
+ const PaymentMethodChangeEventInit* init) {
return new PaymentMethodChangeEvent(script_state, type, init);
}
@@ -25,19 +26,28 @@ const String& PaymentMethodChangeEvent::methodName() const {
const ScriptValue PaymentMethodChangeEvent::methodDetails(
ScriptState* script_state) const {
- return ScriptValue(script_state, method_details_.V8ValueFor(script_state));
+ if (method_details_.IsEmpty())
+ return ScriptValue::CreateNull(script_state);
+ return ScriptValue::ToWorldSafeScriptValue(script_state, method_details_);
+}
+
+void PaymentMethodChangeEvent::Trace(Visitor* visitor) {
+ visitor->Trace(method_details_);
+ PaymentRequestUpdateEvent::Trace(visitor);
}
PaymentMethodChangeEvent::PaymentMethodChangeEvent(
ScriptState* script_state,
const AtomicString& type,
- const PaymentMethodChangeEventInit& init)
+ const PaymentMethodChangeEventInit* init)
: PaymentRequestUpdateEvent(ExecutionContext::From(script_state),
type,
init),
- method_name_(init.methodName()),
- method_details_(init.hasMethodDetails()
- ? init.methodDetails()
- : ScriptValue::CreateNull(script_state)) {}
+ method_name_(init->methodName()) {
+ if (init->hasMethodDetails()) {
+ method_details_.Set(init->methodDetails().GetIsolate(),
+ init->methodDetails().V8Value());
+ }
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.h b/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.h
index f557cbcd21f..5783b009983 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_method_change_event.h
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/modules/payments/payment_method_change_event_init.h"
#include "third_party/blink/renderer/modules/payments/payment_request_update_event.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -28,18 +29,21 @@ class MODULES_EXPORT PaymentMethodChangeEvent final
static PaymentMethodChangeEvent* Create(
ScriptState*,
const AtomicString& type,
- const PaymentMethodChangeEventInit& = PaymentMethodChangeEventInit());
+ const PaymentMethodChangeEventInit* =
+ PaymentMethodChangeEventInit::Create());
const String& methodName() const;
const ScriptValue methodDetails(ScriptState*) const;
+ void Trace(Visitor* visitor) override;
+
private:
PaymentMethodChangeEvent(ScriptState*,
const AtomicString& type,
- const PaymentMethodChangeEventInit&);
+ const PaymentMethodChangeEventInit*);
String method_name_;
- ScriptValue method_details_;
+ TraceWrapperV8Reference<v8::Value> method_details_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request.cc
index e16c732ce23..34f940dabdc 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request.cc
@@ -57,6 +57,7 @@
#include "third_party/blink/renderer/platform/uuid.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -88,53 +89,53 @@ using ::payments::mojom::blink::PaymentValidationErrorsPtr;
namespace mojo {
template <>
-struct TypeConverter<PaymentCurrencyAmountPtr, blink::PaymentCurrencyAmount> {
+struct TypeConverter<PaymentCurrencyAmountPtr, blink::PaymentCurrencyAmount*> {
static PaymentCurrencyAmountPtr Convert(
- const blink::PaymentCurrencyAmount& input) {
+ const blink::PaymentCurrencyAmount* input) {
PaymentCurrencyAmountPtr output = PaymentCurrencyAmount::New();
- output->currency = input.currency().UpperASCII();
- output->value = input.value();
+ output->currency = input->currency().UpperASCII();
+ output->value = input->value();
return output;
}
};
template <>
-struct TypeConverter<PaymentItemPtr, blink::PaymentItem> {
- static PaymentItemPtr Convert(const blink::PaymentItem& input) {
+struct TypeConverter<PaymentItemPtr, blink::PaymentItem*> {
+ static PaymentItemPtr Convert(const blink::PaymentItem* input) {
PaymentItemPtr output = payments::mojom::blink::PaymentItem::New();
- output->label = input.label();
- output->amount = PaymentCurrencyAmount::From(input.amount());
- output->pending = input.pending();
+ output->label = input->label();
+ output->amount = PaymentCurrencyAmount::From(input->amount());
+ output->pending = input->pending();
return output;
}
};
template <>
-struct TypeConverter<PaymentShippingOptionPtr, blink::PaymentShippingOption> {
+struct TypeConverter<PaymentShippingOptionPtr, blink::PaymentShippingOption*> {
static PaymentShippingOptionPtr Convert(
- const blink::PaymentShippingOption& input) {
+ const blink::PaymentShippingOption* input) {
PaymentShippingOptionPtr output =
payments::mojom::blink::PaymentShippingOption::New();
- output->id = input.id();
- output->label = input.label();
- output->amount = PaymentCurrencyAmount::From(input.amount());
- output->selected = input.hasSelected() && input.selected();
+ output->id = input->id();
+ output->label = input->label();
+ output->amount = PaymentCurrencyAmount::From(input->amount());
+ output->selected = input->hasSelected() && input->selected();
return output;
}
};
template <>
-struct TypeConverter<PaymentOptionsPtr, blink::PaymentOptions> {
- static PaymentOptionsPtr Convert(const blink::PaymentOptions& input) {
+struct TypeConverter<PaymentOptionsPtr, blink::PaymentOptions*> {
+ static PaymentOptionsPtr Convert(const blink::PaymentOptions* input) {
PaymentOptionsPtr output = payments::mojom::blink::PaymentOptions::New();
- output->request_payer_name = input.requestPayerName();
- output->request_payer_email = input.requestPayerEmail();
- output->request_payer_phone = input.requestPayerPhone();
- output->request_shipping = input.requestShipping();
+ output->request_payer_name = input->requestPayerName();
+ output->request_payer_email = input->requestPayerEmail();
+ output->request_payer_phone = input->requestPayerPhone();
+ output->request_shipping = input->requestShipping();
- if (input.shippingType() == "delivery")
+ if (input->shippingType() == "delivery")
output->shipping_type = PaymentShippingType::DELIVERY;
- else if (input.shippingType() == "pickup")
+ else if (input->shippingType() == "pickup")
output->shipping_type = PaymentShippingType::PICKUP;
else
output->shipping_type = PaymentShippingType::SHIPPING;
@@ -145,57 +146,58 @@ struct TypeConverter<PaymentOptionsPtr, blink::PaymentOptions> {
template <>
struct TypeConverter<PaymentValidationErrorsPtr,
- blink::PaymentValidationErrors> {
+ blink::PaymentValidationErrors*> {
static PaymentValidationErrorsPtr Convert(
- const blink::PaymentValidationErrors& input) {
+ const blink::PaymentValidationErrors* input) {
PaymentValidationErrorsPtr output =
payments::mojom::blink::PaymentValidationErrors::New();
- output->payer = input.hasPayer() ? PayerErrors::From(input.payer())
- : PayerErrors::From(blink::PayerErrors());
+ output->payer = input->hasPayer()
+ ? PayerErrors::From(input->payer())
+ : PayerErrors::From(blink::PayerErrors::Create());
output->shipping_address =
- input.hasShippingAddress()
- ? AddressErrors::From(input.shippingAddress())
- : AddressErrors::From(blink::AddressErrors());
+ input->hasShippingAddress()
+ ? AddressErrors::From(input->shippingAddress())
+ : AddressErrors::From(blink::AddressErrors::Create());
return output;
}
};
template <>
-struct TypeConverter<PayerErrorsPtr, blink::PayerErrors> {
- static PayerErrorsPtr Convert(const blink::PayerErrors& input) {
+struct TypeConverter<PayerErrorsPtr, blink::PayerErrors*> {
+ static PayerErrorsPtr Convert(const blink::PayerErrors* input) {
PayerErrorsPtr output = payments::mojom::blink::PayerErrors::New();
- output->email = input.hasEmail() ? input.email() : g_empty_string;
- output->name = input.hasName() ? input.name() : g_empty_string;
- output->phone = input.hasPhone() ? input.phone() : g_empty_string;
+ output->email = input->hasEmail() ? input->email() : g_empty_string;
+ output->name = input->hasName() ? input->name() : g_empty_string;
+ output->phone = input->hasPhone() ? input->phone() : g_empty_string;
return output;
}
};
template <>
-struct TypeConverter<AddressErrorsPtr, blink::AddressErrors> {
- static AddressErrorsPtr Convert(const blink::AddressErrors& input) {
+struct TypeConverter<AddressErrorsPtr, blink::AddressErrors*> {
+ static AddressErrorsPtr Convert(const blink::AddressErrors* input) {
AddressErrorsPtr output = payments::mojom::blink::AddressErrors::New();
output->address_line =
- input.hasAddressLine() ? input.addressLine() : g_empty_string;
- output->city = input.hasCity() ? input.city() : g_empty_string;
- output->country = input.hasCountry() ? input.country() : g_empty_string;
- output->dependent_locality = input.hasDependentLocality()
- ? input.dependentLocality()
+ input->hasAddressLine() ? input->addressLine() : g_empty_string;
+ output->city = input->hasCity() ? input->city() : g_empty_string;
+ output->country = input->hasCountry() ? input->country() : g_empty_string;
+ output->dependent_locality = input->hasDependentLocality()
+ ? input->dependentLocality()
: g_empty_string;
output->language_code =
- input.hasLanguageCode() ? input.languageCode() : g_empty_string;
+ input->hasLanguageCode() ? input->languageCode() : g_empty_string;
output->organization =
- input.hasOrganization() ? input.organization() : g_empty_string;
- output->phone = input.hasPhone() ? input.phone() : g_empty_string;
+ input->hasOrganization() ? input->organization() : g_empty_string;
+ output->phone = input->hasPhone() ? input->phone() : g_empty_string;
output->postal_code =
- input.hasPostalCode() ? input.postalCode() : g_empty_string;
+ input->hasPostalCode() ? input->postalCode() : g_empty_string;
output->recipient =
- input.hasRecipient() ? input.recipient() : g_empty_string;
- output->region = input.hasRegion() ? input.region() : g_empty_string;
+ input->hasRecipient() ? input->recipient() : g_empty_string;
+ output->region = input->hasRegion() ? input->region() : g_empty_string;
output->region_code =
- input.hasRegionCode() ? input.regionCode() : g_empty_string;
+ input->hasRegionCode() ? input->regionCode() : g_empty_string;
output->sorting_code =
- input.hasSortingCode() ? input.sortingCode() : g_empty_string;
+ input->hasSortingCode() ? input->sortingCode() : g_empty_string;
return output;
}
};
@@ -212,65 +214,66 @@ constexpr TimeDelta kCompleteTimeout = TimeDelta::FromSeconds(60);
// Validates ShippingOption or PaymentItem, which happen to have identical
// fields, except for "id", which is present only in ShippingOption.
template <typename T>
-void ValidateShippingOptionOrPaymentItem(const T& item,
+void ValidateShippingOptionOrPaymentItem(const T* item,
const String& item_name,
ExecutionContext& execution_context,
ExceptionState& exception_state) {
- DCHECK(item.hasLabel());
- DCHECK(item.hasAmount());
- DCHECK(item.amount().hasValue());
- DCHECK(item.amount().hasCurrency());
+ DCHECK(item->hasLabel());
+ DCHECK(item->hasAmount());
+ DCHECK(item->amount()->hasValue());
+ DCHECK(item->amount()->hasCurrency());
- if (item.label().length() > PaymentRequest::kMaxStringLength) {
+ if (item->label().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError("The label for " + item_name +
" cannot be longer than 1024 characters");
return;
}
- if (item.amount().currency().length() > PaymentRequest::kMaxStringLength) {
+ if (item->amount()->currency().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError("The currency code for " + item_name +
" cannot be longer than 1024 characters");
return;
}
- if (item.amount().value().length() > PaymentRequest::kMaxStringLength) {
+ if (item->amount()->value().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError("The amount value for " + item_name +
" cannot be longer than 1024 characters");
return;
}
String error_message;
- if (!PaymentsValidators::IsValidAmountFormat(item.amount().value(), item_name,
- &error_message)) {
+ if (!PaymentsValidators::IsValidAmountFormat(item->amount()->value(),
+ item_name, &error_message)) {
exception_state.ThrowTypeError(error_message);
return;
}
- if (item.label().IsEmpty()) {
+ if (item->label().IsEmpty()) {
execution_context.AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kErrorMessageLevel,
"Empty " + item_name + " label may be confusing the user"));
return;
}
- if (!PaymentsValidators::IsValidCurrencyCodeFormat(item.amount().currency(),
+ if (!PaymentsValidators::IsValidCurrencyCodeFormat(item->amount()->currency(),
&error_message)) {
exception_state.ThrowRangeError(error_message);
return;
}
}
-void ValidateAndConvertDisplayItems(const HeapVector<PaymentItem>& input,
- const String& item_names,
- Vector<PaymentItemPtr>& output,
- ExecutionContext& execution_context,
- ExceptionState& exception_state) {
+void ValidateAndConvertDisplayItems(
+ const HeapVector<Member<PaymentItem>>& input,
+ const String& item_names,
+ Vector<PaymentItemPtr>& output,
+ ExecutionContext& execution_context,
+ ExceptionState& exception_state) {
if (input.size() > PaymentRequest::kMaxListSize) {
exception_state.ThrowTypeError("At most 1024 " + item_names + " allowed");
return;
}
- for (const PaymentItem& item : input) {
+ for (PaymentItem* item : input) {
ValidateShippingOptionOrPaymentItem(item, item_names, execution_context,
exception_state);
if (exception_state.HadException())
@@ -285,7 +288,7 @@ void ValidateAndConvertDisplayItems(const HeapVector<PaymentItem>& input,
// to clear |output| when an exception is thrown, because the caller takes care
// of deleting |output|.
void ValidateAndConvertShippingOptions(
- const HeapVector<PaymentShippingOption>& input,
+ const HeapVector<Member<PaymentShippingOption>>& input,
Vector<PaymentShippingOptionPtr>& output,
String& shipping_option_output,
ExecutionContext& execution_context,
@@ -296,43 +299,43 @@ void ValidateAndConvertShippingOptions(
}
HashSet<String> unique_ids;
- for (const PaymentShippingOption& option : input) {
+ for (PaymentShippingOption* option : input) {
ValidateShippingOptionOrPaymentItem(option, "shippingOptions",
execution_context, exception_state);
if (exception_state.HadException())
return;
- DCHECK(option.hasId());
- if (option.id().length() > PaymentRequest::kMaxStringLength) {
+ DCHECK(option->hasId());
+ if (option->id().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError(
"Shipping option ID cannot be longer than 1024 characters");
return;
}
- if (option.id().IsEmpty()) {
+ if (option->id().IsEmpty()) {
execution_context.AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kWarningMessageLevel,
"Empty shipping option ID may be hard to debug"));
return;
}
- if (unique_ids.Contains(option.id())) {
+ if (unique_ids.Contains(option->id())) {
exception_state.ThrowTypeError(
"Cannot have duplicate shipping option identifiers");
return;
}
- if (option.selected())
- shipping_option_output = option.id();
+ if (option->selected())
+ shipping_option_output = option->id();
- unique_ids.insert(option.id());
+ unique_ids.insert(option->id());
output.push_back(
payments::mojom::blink::PaymentShippingOption::From(option));
}
}
-void ValidateAndConvertTotal(const PaymentItem& input,
+void ValidateAndConvertTotal(const PaymentItem* input,
const String& item_name,
PaymentItemPtr& output,
ExecutionContext& execution_context,
@@ -342,49 +345,50 @@ void ValidateAndConvertTotal(const PaymentItem& input,
if (exception_state.HadException())
return;
- if (input.amount().value()[0] == '-') {
+ if (input->amount()->value()[0] == '-') {
exception_state.ThrowTypeError("Total amount value should be non-negative");
return;
}
- output = payments::mojom::blink::PaymentItem::From(input);
+ output = payments::mojom::blink::PaymentItem::From(
+ const_cast<PaymentItem*>(input));
}
// Parses Android Pay data to avoid parsing JSON in the browser.
void SetAndroidPayMethodData(const ScriptValue& input,
PaymentMethodDataPtr& output,
ExceptionState& exception_state) {
- AndroidPayMethodData android_pay;
+ AndroidPayMethodData* android_pay = AndroidPayMethodData::Create();
V8AndroidPayMethodData::ToImpl(input.GetIsolate(), input.V8Value(),
android_pay, exception_state);
if (exception_state.HadException())
return;
- if (android_pay.hasEnvironment() && android_pay.environment() == "TEST")
+ if (android_pay->hasEnvironment() && android_pay->environment() == "TEST")
output->environment = payments::mojom::blink::AndroidPayEnvironment::TEST;
- if (android_pay.hasMerchantName() &&
- android_pay.merchantName().length() > PaymentRequest::kMaxStringLength) {
+ if (android_pay->hasMerchantName() &&
+ android_pay->merchantName().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError(
"Android Pay merchant name cannot be longer than 1024 characters");
return;
}
- output->merchant_name = android_pay.merchantName();
+ output->merchant_name = android_pay->merchantName();
- if (android_pay.hasMerchantId() &&
- android_pay.merchantId().length() > PaymentRequest::kMaxStringLength) {
+ if (android_pay->hasMerchantId() &&
+ android_pay->merchantId().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError(
"Android Pay merchant id cannot be longer than 1024 characters");
return;
}
- output->merchant_id = android_pay.merchantId();
+ output->merchant_id = android_pay->merchantId();
// 0 means the merchant did not specify or it was an invalid value
output->min_google_play_services_version = 0;
- if (android_pay.hasMinGooglePlayServicesVersion()) {
+ if (android_pay->hasMinGooglePlayServicesVersion()) {
bool ok = false;
int min_google_play_services_version =
- android_pay.minGooglePlayServicesVersion().ToIntStrict(&ok);
+ android_pay->minGooglePlayServicesVersion().ToIntStrict(&ok);
if (ok) {
output->min_google_play_services_version =
min_google_play_services_version;
@@ -393,10 +397,10 @@ void SetAndroidPayMethodData(const ScriptValue& input,
// 0 means the merchant did not specify or it was an invalid value
output->api_version = 0;
- if (android_pay.hasApiVersion())
- output->api_version = android_pay.apiVersion();
+ if (android_pay->hasApiVersion())
+ output->api_version = android_pay->apiVersion();
- if (android_pay.hasAllowedCardNetworks()) {
+ if (android_pay->hasAllowedCardNetworks()) {
using ::payments::mojom::blink::AndroidPayCardNetwork;
const struct {
@@ -408,7 +412,7 @@ void SetAndroidPayMethodData(const ScriptValue& input,
{AndroidPayCardNetwork::VISA, "VISA"}};
for (const String& allowed_card_network :
- android_pay.allowedCardNetworks()) {
+ android_pay->allowedCardNetworks()) {
for (size_t i = 0; i < arraysize(kAndroidPayNetwork); ++i) {
if (allowed_card_network == kAndroidPayNetwork[i].name) {
output->allowed_card_networks.push_back(kAndroidPayNetwork[i].code);
@@ -418,12 +422,12 @@ void SetAndroidPayMethodData(const ScriptValue& input,
}
}
- if (android_pay.hasPaymentMethodTokenizationParameters()) {
- const blink::AndroidPayTokenization& tokenization =
- android_pay.paymentMethodTokenizationParameters();
+ if (android_pay->hasPaymentMethodTokenizationParameters()) {
+ const blink::AndroidPayTokenization* tokenization =
+ android_pay->paymentMethodTokenizationParameters();
output->tokenization_type =
payments::mojom::blink::AndroidPayTokenization::UNSPECIFIED;
- if (tokenization.hasTokenizationType()) {
+ if (tokenization->hasTokenizationType()) {
using ::payments::mojom::blink::AndroidPayTokenization;
const struct {
@@ -434,7 +438,7 @@ void SetAndroidPayMethodData(const ScriptValue& input,
{AndroidPayTokenization::NETWORK_TOKEN, "NETWORK_TOKEN"}};
for (size_t i = 0; i < arraysize(kAndroidPayTokenization); ++i) {
- if (tokenization.tokenizationType() ==
+ if (tokenization->tokenizationType() ==
kAndroidPayTokenization[i].name) {
output->tokenization_type = kAndroidPayTokenization[i].code;
break;
@@ -442,9 +446,9 @@ void SetAndroidPayMethodData(const ScriptValue& input,
}
}
- if (tokenization.hasParameters()) {
+ if (tokenization->hasParameters()) {
const Vector<String>& keys =
- tokenization.parameters().GetPropertyNames(exception_state);
+ tokenization->parameters().GetPropertyNames(exception_state);
if (exception_state.HadException())
return;
if (keys.size() > PaymentRequest::kMaxListSize) {
@@ -454,7 +458,7 @@ void SetAndroidPayMethodData(const ScriptValue& input,
}
String value;
for (const String& key : keys) {
- if (!DictionaryHelper::Get(tokenization.parameters(), key, value))
+ if (!DictionaryHelper::Get(tokenization->parameters(), key, value))
continue;
if (key.length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError(
@@ -558,7 +562,7 @@ bool IsValidMethodFormat(const String& identifier) {
}
void ValidateAndConvertPaymentDetailsModifiers(
- const HeapVector<PaymentDetailsModifier>& input,
+ const HeapVector<Member<PaymentDetailsModifier>>& input,
Vector<PaymentDetailsModifierPtr>& output,
ExecutionContext& execution_context,
ExceptionState& exception_state) {
@@ -567,18 +571,18 @@ void ValidateAndConvertPaymentDetailsModifiers(
return;
}
- for (const PaymentDetailsModifier& modifier : input) {
+ for (const PaymentDetailsModifier* modifier : input) {
output.push_back(payments::mojom::blink::PaymentDetailsModifier::New());
- if (modifier.hasTotal()) {
- ValidateAndConvertTotal(modifier.total(), "modifier total",
+ if (modifier->hasTotal()) {
+ ValidateAndConvertTotal(modifier->total(), "modifier total",
output.back()->total, execution_context,
exception_state);
if (exception_state.HadException())
return;
}
- if (modifier.hasAdditionalDisplayItems()) {
- ValidateAndConvertDisplayItems(modifier.additionalDisplayItems(),
+ if (modifier->hasAdditionalDisplayItems()) {
+ ValidateAndConvertDisplayItems(modifier->additionalDisplayItems(),
"additional display items in modifier",
output.back()->additional_display_items,
execution_context, exception_state);
@@ -586,22 +590,22 @@ void ValidateAndConvertPaymentDetailsModifiers(
return;
}
- if (!IsValidMethodFormat(modifier.supportedMethod())) {
+ if (!IsValidMethodFormat(modifier->supportedMethod())) {
exception_state.ThrowRangeError(
"Invalid payment method identifier format");
return;
}
- CountPaymentRequestNetworkNameInSupportedMethod(modifier.supportedMethod(),
+ CountPaymentRequestNetworkNameInSupportedMethod(modifier->supportedMethod(),
execution_context);
output.back()->method_data =
payments::mojom::blink::PaymentMethodData::New();
- output.back()->method_data->supported_method = modifier.supportedMethod();
+ output.back()->method_data->supported_method = modifier->supportedMethod();
- if (modifier.hasData() && !modifier.data().IsEmpty()) {
+ if (modifier->hasData() && !modifier->data().IsEmpty()) {
StringifyAndParseMethodSpecificData(
- modifier.supportedMethod(), modifier.data(),
+ modifier->supportedMethod(), modifier->data(),
output.back()->method_data, exception_state);
} else {
output.back()->method_data->stringified_data = "";
@@ -609,14 +613,14 @@ void ValidateAndConvertPaymentDetailsModifiers(
}
}
-void ValidateAndConvertPaymentDetailsBase(const PaymentDetailsBase& input,
- const PaymentOptions& options,
+void ValidateAndConvertPaymentDetailsBase(const PaymentDetailsBase* input,
+ const PaymentOptions* options,
PaymentDetailsPtr& output,
String& shipping_option_output,
ExecutionContext& execution_context,
ExceptionState& exception_state) {
- if (input.hasDisplayItems()) {
- ValidateAndConvertDisplayItems(input.displayItems(), "display items",
+ if (input->hasDisplayItems()) {
+ ValidateAndConvertDisplayItems(input->displayItems(), "display items",
output->display_items, execution_context,
exception_state);
if (exception_state.HadException())
@@ -625,9 +629,9 @@ void ValidateAndConvertPaymentDetailsBase(const PaymentDetailsBase& input,
// If requestShipping is specified and there are shipping options to validate,
// proceed with validation.
- if (options.requestShipping() && input.hasShippingOptions()) {
+ if (options->requestShipping() && input->hasShippingOptions()) {
ValidateAndConvertShippingOptions(
- input.shippingOptions(), output->shipping_options,
+ input->shippingOptions(), output->shipping_options,
shipping_option_output, execution_context, exception_state);
if (exception_state.HadException())
return;
@@ -635,21 +639,21 @@ void ValidateAndConvertPaymentDetailsBase(const PaymentDetailsBase& input,
shipping_option_output = String();
}
- if (input.hasModifiers()) {
+ if (input->hasModifiers()) {
ValidateAndConvertPaymentDetailsModifiers(
- input.modifiers(), output->modifiers, execution_context,
+ input->modifiers(), output->modifiers, execution_context,
exception_state);
}
}
-void ValidateAndConvertPaymentDetailsInit(const PaymentDetailsInit& input,
- const PaymentOptions& options,
+void ValidateAndConvertPaymentDetailsInit(const PaymentDetailsInit* input,
+ const PaymentOptions* options,
PaymentDetailsPtr& output,
String& shipping_option_output,
ExecutionContext& execution_context,
ExceptionState& exception_state) {
- DCHECK(input.hasTotal());
- ValidateAndConvertTotal(input.total(), "total", output->total,
+ DCHECK(input->hasTotal());
+ ValidateAndConvertTotal(input->total(), "total", output->total,
execution_context, exception_state);
if (exception_state.HadException())
return;
@@ -659,8 +663,8 @@ void ValidateAndConvertPaymentDetailsInit(const PaymentDetailsInit& input,
execution_context, exception_state);
}
-void ValidateAndConvertPaymentDetailsUpdate(const PaymentDetailsUpdate& input,
- const PaymentOptions& options,
+void ValidateAndConvertPaymentDetailsUpdate(const PaymentDetailsUpdate* input,
+ const PaymentOptions* options,
PaymentDetailsPtr& output,
String& shipping_option_output,
ExecutionContext& execution_context,
@@ -671,38 +675,38 @@ void ValidateAndConvertPaymentDetailsUpdate(const PaymentDetailsUpdate& input,
if (exception_state.HadException())
return;
- if (input.hasTotal()) {
- ValidateAndConvertTotal(input.total(), "total", output->total,
+ if (input->hasTotal()) {
+ ValidateAndConvertTotal(input->total(), "total", output->total,
execution_context, exception_state);
if (exception_state.HadException())
return;
}
- if (input.hasError()) {
+ if (input->hasError()) {
String error_message;
- if (!PaymentsValidators::IsValidErrorMsgFormat(input.error(),
+ if (!PaymentsValidators::IsValidErrorMsgFormat(input->error(),
&error_message)) {
exception_state.ThrowTypeError(error_message);
return;
}
- output->error = input.error();
+ output->error = input->error();
}
- if (input.hasShippingAddressErrors()) {
+ if (input->hasShippingAddressErrors()) {
String error_message;
if (!PaymentsValidators::IsValidAddressErrorsFormat(
- input.shippingAddressErrors(), &error_message)) {
+ input->shippingAddressErrors(), &error_message)) {
exception_state.ThrowTypeError(error_message);
return;
}
output->shipping_address_errors =
payments::mojom::blink::AddressErrors::From(
- input.shippingAddressErrors());
+ input->shippingAddressErrors());
}
}
void ValidateAndConvertPaymentMethodData(
- const HeapVector<PaymentMethodData>& input,
+ const HeapVector<Member<PaymentMethodData>>& input,
Vector<payments::mojom::blink::PaymentMethodDataPtr>& output,
HashSet<String>& method_names,
ExecutionContext& execution_context,
@@ -718,26 +722,26 @@ void ValidateAndConvertPaymentMethodData(
return;
}
- for (const PaymentMethodData payment_method_data : input) {
- if (!IsValidMethodFormat(payment_method_data.supportedMethod())) {
+ for (const PaymentMethodData* payment_method_data : input) {
+ if (!IsValidMethodFormat(payment_method_data->supportedMethod())) {
exception_state.ThrowRangeError(
"Invalid payment method identifier format");
return;
}
- method_names.insert(payment_method_data.supportedMethod());
+ method_names.insert(payment_method_data->supportedMethod());
CountPaymentRequestNetworkNameInSupportedMethod(
- payment_method_data.supportedMethod(), execution_context);
+ payment_method_data->supportedMethod(), execution_context);
output.push_back(payments::mojom::blink::PaymentMethodData::New());
- output.back()->supported_method = payment_method_data.supportedMethod();
+ output.back()->supported_method = payment_method_data->supportedMethod();
- if (payment_method_data.hasData() &&
- !payment_method_data.data().IsEmpty()) {
- StringifyAndParseMethodSpecificData(payment_method_data.supportedMethod(),
- payment_method_data.data(),
- output.back(), exception_state);
+ if (payment_method_data->hasData() &&
+ !payment_method_data->data().IsEmpty()) {
+ StringifyAndParseMethodSpecificData(
+ payment_method_data->supportedMethod(), payment_method_data->data(),
+ output.back(), exception_state);
} else {
output.back()->stringified_data = "";
}
@@ -772,21 +776,22 @@ void WarnIgnoringQueryQuotaForCanMakePayment(
PaymentRequest* PaymentRequest::Create(
ExecutionContext* execution_context,
- const HeapVector<PaymentMethodData>& method_data,
- const PaymentDetailsInit& details,
+ const HeapVector<Member<PaymentMethodData>>& method_data,
+ const PaymentDetailsInit* details,
ExceptionState& exception_state) {
- return new PaymentRequest(execution_context, method_data, details,
- PaymentOptions(), exception_state);
+ return MakeGarbageCollected<PaymentRequest>(execution_context, method_data,
+ details, PaymentOptions::Create(),
+ exception_state);
}
PaymentRequest* PaymentRequest::Create(
ExecutionContext* execution_context,
- const HeapVector<PaymentMethodData>& method_data,
- const PaymentDetailsInit& details,
- const PaymentOptions& options,
+ const HeapVector<Member<PaymentMethodData>>& method_data,
+ const PaymentDetailsInit* details,
+ const PaymentOptions* options,
ExceptionState& exception_state) {
- return new PaymentRequest(execution_context, method_data, details, options,
- exception_state);
+ return MakeGarbageCollected<PaymentRequest>(
+ execution_context, method_data, details, options, exception_state);
}
PaymentRequest::~PaymentRequest() = default;
@@ -874,7 +879,7 @@ bool PaymentRequest::HasPendingActivity() const {
}
const AtomicString& PaymentRequest::InterfaceName() const {
- return EventTargetNames::PaymentRequest;
+ return event_target_names::kPaymentRequest;
}
ExecutionContext* PaymentRequest::GetExecutionContext() const {
@@ -882,7 +887,7 @@ ExecutionContext* PaymentRequest::GetExecutionContext() const {
}
ScriptPromise PaymentRequest::Retry(ScriptState* script_state,
- const PaymentValidationErrors& errors) {
+ const PaymentValidationErrors* errors) {
if (!script_state->ContextIsValid() || !LocalDOMWindow::From(script_state) ||
!LocalDOMWindow::From(script_state)->GetFrame()) {
return ScriptPromise::RejectWithDOMException(
@@ -923,7 +928,8 @@ ScriptPromise PaymentRequest::Retry(ScriptState* script_state,
// The payment provider should respond in PaymentRequest::OnPaymentResponse().
payment_provider_->Retry(
- payments::mojom::blink::PaymentValidationErrors::From(errors));
+ payments::mojom::blink::PaymentValidationErrors::From(
+ const_cast<PaymentValidationErrors*>(errors)));
retry_resolver_ = ScriptPromiseResolver::Create(script_state);
@@ -976,11 +982,12 @@ ScriptPromise PaymentRequest::Complete(ScriptState* script_state,
}
void PaymentRequest::OnUpdatePaymentDetails(
+ const AtomicString& event_type,
const ScriptValue& details_script_value) {
if (!GetPendingAcceptPromiseResolver() || !payment_provider_)
return;
- PaymentDetailsUpdate details;
+ PaymentDetailsUpdate* details = PaymentDetailsUpdate::Create();
ExceptionState exception_state(v8::Isolate::GetCurrent(),
ExceptionState::kConstructionContext,
"PaymentDetailsUpdate");
@@ -994,7 +1001,7 @@ void PaymentRequest::OnUpdatePaymentDetails(
return;
}
- if (!details.hasTotal()) {
+ if (!details->hasTotal()) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kSyntaxError, "Total required"));
ClearResolversAndCloseMojoConnection();
@@ -1012,7 +1019,21 @@ void PaymentRequest::OnUpdatePaymentDetails(
return;
}
- if (!options_.requestShipping())
+ // TODO(https://crbug.com/902291): We should make shippingOptions optional.
+ if (options_->requestShipping() && !details->hasShippingOptions()) {
+ if (event_type == event_type_names::kShippingaddresschange) {
+ UseCounter::Count(
+ GetExecutionContext(),
+ WebFeature::kUpdateWithoutShippingOptionOnShippingAddressChange);
+ }
+ if (event_type == event_type_names::kShippingoptionchange) {
+ UseCounter::Count(
+ GetExecutionContext(),
+ WebFeature::kUpdateWithoutShippingOptionOnShippingOptionChange);
+ }
+ }
+
+ if (!options_->requestShipping())
validated_details->shipping_options.clear();
payment_provider_->UpdateWith(std::move(validated_details));
@@ -1049,11 +1070,12 @@ void PaymentRequest::OnCompleteTimeoutForTesting() {
OnCompleteTimeout(nullptr);
}
-PaymentRequest::PaymentRequest(ExecutionContext* execution_context,
- const HeapVector<PaymentMethodData>& method_data,
- const PaymentDetailsInit& details,
- const PaymentOptions& options,
- ExceptionState& exception_state)
+PaymentRequest::PaymentRequest(
+ ExecutionContext* execution_context,
+ const HeapVector<Member<PaymentMethodData>>& method_data,
+ const PaymentDetailsInit* details,
+ const PaymentOptions* options,
+ ExceptionState& exception_state)
: ContextLifecycleObserver(execution_context),
options_(options),
client_binding_(this),
@@ -1070,8 +1092,8 @@ PaymentRequest::PaymentRequest(ExecutionContext* execution_context,
return;
}
- if (details.hasId() &&
- details.id().length() > PaymentRequest::kMaxStringLength) {
+ if (details->hasId() &&
+ details->id().length() > PaymentRequest::kMaxStringLength) {
exception_state.ThrowTypeError("ID cannot be longer than 1024 characters");
return;
}
@@ -1079,7 +1101,7 @@ PaymentRequest::PaymentRequest(ExecutionContext* execution_context,
PaymentDetailsPtr validated_details =
payments::mojom::blink::PaymentDetails::New();
validated_details->id = id_ =
- details.hasId() ? details.id() : CreateCanonicalUUIDString();
+ details->hasId() ? details->id() : CreateCanonicalUUIDString();
Vector<payments::mojom::blink::PaymentMethodDataPtr> validated_method_data;
ValidateAndConvertPaymentMethodData(method_data, validated_method_data,
@@ -1094,8 +1116,8 @@ PaymentRequest::PaymentRequest(ExecutionContext* execution_context,
if (exception_state.HadException())
return;
- if (options_.requestShipping())
- shipping_type_ = options_.shippingType();
+ if (options_->requestShipping())
+ shipping_type_ = options_->shippingType();
else
validated_details->shipping_options.clear();
@@ -1110,10 +1132,10 @@ PaymentRequest::PaymentRequest(ExecutionContext* execution_context,
payments::mojom::blink::PaymentRequestClientPtr client;
client_binding_.Bind(mojo::MakeRequest(&client));
- payment_provider_->Init(
- std::move(client), std::move(validated_method_data),
- std::move(validated_details),
- payments::mojom::blink::PaymentOptions::From(options_));
+ payment_provider_->Init(std::move(client), std::move(validated_method_data),
+ std::move(validated_details),
+ payments::mojom::blink::PaymentOptions::From(
+ const_cast<PaymentOptions*>(options_.Get())));
}
void PaymentRequest::ContextDestroyed(ExecutionContext*) {
@@ -1132,10 +1154,10 @@ void PaymentRequest::OnShippingAddressChange(PaymentAddressPtr address) {
return;
}
- shipping_address_ = new PaymentAddress(std::move(address));
+ shipping_address_ = MakeGarbageCollected<PaymentAddress>(std::move(address));
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ GetExecutionContext(), event_type_names::kShippingaddresschange);
event->SetTarget(this);
event->SetPaymentDetailsUpdater(this);
DispatchEvent(*event);
@@ -1154,7 +1176,7 @@ void PaymentRequest::OnShippingOptionChange(const String& shipping_option_id) {
shipping_option_ = shipping_option_id;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- GetExecutionContext(), EventTypeNames::shippingoptionchange);
+ GetExecutionContext(), event_type_names::kShippingoptionchange);
event->SetTarget(this);
event->SetPaymentDetailsUpdater(this);
DispatchEvent(*event);
@@ -1174,7 +1196,7 @@ void PaymentRequest::OnPayerDetailChange(
DCHECK(!complete_resolver_);
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- GetExecutionContext(), EventTypeNames::payerdetailchange);
+ GetExecutionContext(), event_type_names::kPayerdetailchange);
event->SetTarget(payment_response_);
event->SetPaymentDetailsUpdater(this);
payment_response_->UpdatePayerDetail(std::move(detail));
@@ -1186,7 +1208,7 @@ void PaymentRequest::OnPaymentResponse(PaymentResponsePtr response) {
DCHECK(!complete_resolver_);
ScriptPromiseResolver* resolver = GetPendingAcceptPromiseResolver();
- if (options_.requestShipping()) {
+ if (options_->requestShipping()) {
if (!response->shipping_address || response->shipping_option.IsEmpty()) {
resolver->Reject(DOMException::Create(DOMExceptionCode::kSyntaxError));
ClearResolversAndCloseMojoConnection();
@@ -1202,8 +1224,8 @@ void PaymentRequest::OnPaymentResponse(PaymentResponsePtr response) {
return;
}
- shipping_address_ =
- new PaymentAddress(std::move(response->shipping_address));
+ shipping_address_ = MakeGarbageCollected<PaymentAddress>(
+ std::move(response->shipping_address));
shipping_option_ = response->shipping_option;
} else {
if (response->shipping_address || !response->shipping_option.IsNull()) {
@@ -1214,12 +1236,12 @@ void PaymentRequest::OnPaymentResponse(PaymentResponsePtr response) {
}
DCHECK(response->payer);
- if ((options_.requestPayerName() && response->payer->name.IsEmpty()) ||
- (options_.requestPayerEmail() && response->payer->email.IsEmpty()) ||
- (options_.requestPayerPhone() && response->payer->phone.IsEmpty()) ||
- (!options_.requestPayerName() && !response->payer->name.IsNull()) ||
- (!options_.requestPayerEmail() && !response->payer->email.IsNull()) ||
- (!options_.requestPayerPhone() && !response->payer->phone.IsNull())) {
+ if ((options_->requestPayerName() && response->payer->name.IsEmpty()) ||
+ (options_->requestPayerEmail() && response->payer->email.IsEmpty()) ||
+ (options_->requestPayerPhone() && response->payer->phone.IsEmpty()) ||
+ (!options_->requestPayerName() && !response->payer->name.IsNull()) ||
+ (!options_->requestPayerEmail() && !response->payer->email.IsNull()) ||
+ (!options_->requestPayerPhone() && !response->payer->phone.IsNull())) {
resolver->Reject(DOMException::Create(DOMExceptionCode::kSyntaxError));
ClearResolversAndCloseMojoConnection();
return;
@@ -1238,9 +1260,9 @@ void PaymentRequest::OnPaymentResponse(PaymentResponsePtr response) {
// connection to display a success or failure message to the user.
retry_resolver_.Clear();
} else if (accept_resolver_) {
- payment_response_ = new PaymentResponse(accept_resolver_->GetScriptState(),
- std::move(response),
- shipping_address_.Get(), this, id_);
+ payment_response_ = MakeGarbageCollected<PaymentResponse>(
+ accept_resolver_->GetScriptState(), std::move(response),
+ shipping_address_.Get(), this, id_);
accept_resolver_->Resolve(payment_response_);
// Do not close the mojo connection here. The merchant website should call
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request.h b/chromium/third_party/blink/renderer/modules/payments/payment_request.h
index 0b264dc9458..9045d3505a7 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request.h
@@ -50,15 +50,20 @@ class MODULES_EXPORT PaymentRequest final
public:
static PaymentRequest* Create(ExecutionContext*,
- const HeapVector<PaymentMethodData>&,
- const PaymentDetailsInit&,
+ const HeapVector<Member<PaymentMethodData>>&,
+ const PaymentDetailsInit*,
ExceptionState&);
static PaymentRequest* Create(ExecutionContext*,
- const HeapVector<PaymentMethodData>&,
- const PaymentDetailsInit&,
- const PaymentOptions&,
+ const HeapVector<Member<PaymentMethodData>>&,
+ const PaymentDetailsInit*,
+ const PaymentOptions*,
ExceptionState&);
+ PaymentRequest(ExecutionContext*,
+ const HeapVector<Member<PaymentMethodData>>&,
+ const PaymentDetailsInit*,
+ const PaymentOptions*,
+ ExceptionState&);
~PaymentRequest() override;
ScriptPromise show(ScriptState*);
@@ -69,9 +74,10 @@ class MODULES_EXPORT PaymentRequest final
const String& shippingOption() const { return shipping_option_; }
const String& shippingType() const { return shipping_type_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(shippingaddresschange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(shippingoptionchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(paymentmethodchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(shippingaddresschange,
+ kShippingaddresschange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(shippingoptionchange, kShippingoptionchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(paymentmethodchange, kPaymentmethodchange);
ScriptPromise canMakePayment(ScriptState*);
@@ -84,10 +90,11 @@ class MODULES_EXPORT PaymentRequest final
// PaymentStateResolver:
ScriptPromise Complete(ScriptState*, PaymentComplete result) override;
- ScriptPromise Retry(ScriptState*, const PaymentValidationErrors&) override;
+ ScriptPromise Retry(ScriptState*, const PaymentValidationErrors*) override;
// PaymentUpdater:
- void OnUpdatePaymentDetails(const ScriptValue& details_script_value) override;
+ void OnUpdatePaymentDetails(const AtomicString& event_type,
+ const ScriptValue& details_script_value) override;
void OnUpdatePaymentDetailsFailure(const String& error) override;
void Trace(blink::Visitor*) override;
@@ -104,12 +111,6 @@ class MODULES_EXPORT PaymentRequest final
};
private:
- PaymentRequest(ExecutionContext*,
- const HeapVector<PaymentMethodData>&,
- const PaymentDetailsInit&,
- const PaymentOptions&,
- ExceptionState&);
-
// LifecycleObserver:
void ContextDestroyed(ExecutionContext*) override;
@@ -137,7 +138,7 @@ class MODULES_EXPORT PaymentRequest final
// spec.
ScriptPromiseResolver* GetPendingAcceptPromiseResolver() const;
- PaymentOptions options_;
+ Member<const PaymentOptions> options_;
Member<PaymentAddress> shipping_address_;
Member<PaymentResponse> payment_response_;
String id_;
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_details_test.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request_details_test.cc
index f894f7185fa..91e84a9a980 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_details_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_details_test.cc
@@ -36,7 +36,7 @@ class DetailsTestCase {
~DetailsTestCase() = default;
- PaymentDetailsInit BuildDetails() const {
+ PaymentDetailsInit* BuildDetails() const {
return BuildPaymentDetailsInitForTest(detail_, data_, mod_type_,
value_to_use_);
}
@@ -129,8 +129,8 @@ TEST_P(PaymentRequestDetailsTest, ValidatesDetails) {
SecurityOrigin::Create(KURL("https://www.example.com/")));
scope.GetDocument().SetSecureContextStateForTesting(
SecureContextState::kSecure);
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
GetParam().BuildDetails(), options, scope.GetExceptionState());
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_event.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request_event.cc
index 2b422f7b0ed..863cf8e2934 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_event.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_event.cc
@@ -20,23 +20,24 @@ namespace blink {
PaymentRequestEvent* PaymentRequestEvent::Create(
const AtomicString& type,
- const PaymentRequestEventInit& initializer) {
- return new PaymentRequestEvent(type, initializer, nullptr, nullptr);
+ const PaymentRequestEventInit* initializer) {
+ return MakeGarbageCollected<PaymentRequestEvent>(type, initializer, nullptr,
+ nullptr);
}
PaymentRequestEvent* PaymentRequestEvent::Create(
const AtomicString& type,
- const PaymentRequestEventInit& initializer,
+ const PaymentRequestEventInit* initializer,
RespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer) {
- return new PaymentRequestEvent(type, initializer, respond_with_observer,
- wait_until_observer);
+ return MakeGarbageCollected<PaymentRequestEvent>(
+ type, initializer, respond_with_observer, wait_until_observer);
}
PaymentRequestEvent::~PaymentRequestEvent() = default;
const AtomicString& PaymentRequestEvent::InterfaceName() const {
- return EventNames::PaymentRequestEvent;
+ return event_interface_names::kPaymentRequestEvent;
}
const String& PaymentRequestEvent::topOrigin() const {
@@ -51,7 +52,8 @@ const String& PaymentRequestEvent::paymentRequestId() const {
return payment_request_id_;
}
-const HeapVector<PaymentMethodData>& PaymentRequestEvent::methodData() const {
+const HeapVector<Member<PaymentMethodData>>& PaymentRequestEvent::methodData()
+ const {
return method_data_;
}
@@ -59,8 +61,8 @@ const ScriptValue PaymentRequestEvent::total(ScriptState* script_state) const {
return ScriptValue::From(script_state, total_);
}
-const HeapVector<PaymentDetailsModifier>& PaymentRequestEvent::modifiers()
- const {
+const HeapVector<Member<PaymentDetailsModifier>>&
+PaymentRequestEvent::modifiers() const {
return modifiers_;
}
@@ -125,6 +127,7 @@ void PaymentRequestEvent::respondWith(ScriptState* script_state,
void PaymentRequestEvent::Trace(blink::Visitor* visitor) {
visitor->Trace(method_data_);
+ visitor->Trace(total_);
visitor->Trace(modifiers_);
visitor->Trace(observer_);
ExtendableEvent::Trace(visitor);
@@ -132,22 +135,22 @@ void PaymentRequestEvent::Trace(blink::Visitor* visitor) {
PaymentRequestEvent::PaymentRequestEvent(
const AtomicString& type,
- const PaymentRequestEventInit& initializer,
+ const PaymentRequestEventInit* initializer,
RespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer)
: ExtendableEvent(type, initializer, wait_until_observer),
- top_origin_(initializer.topOrigin()),
- payment_request_origin_(initializer.paymentRequestOrigin()),
- payment_request_id_(initializer.paymentRequestId()),
- method_data_(initializer.hasMethodData()
- ? initializer.methodData()
- : HeapVector<PaymentMethodData>()),
- total_(initializer.hasTotal() ? initializer.total()
- : PaymentCurrencyAmount()),
- modifiers_(initializer.hasModifiers()
- ? initializer.modifiers()
- : HeapVector<PaymentDetailsModifier>()),
- instrument_key_(initializer.instrumentKey()),
+ top_origin_(initializer->topOrigin()),
+ payment_request_origin_(initializer->paymentRequestOrigin()),
+ payment_request_id_(initializer->paymentRequestId()),
+ method_data_(initializer->hasMethodData()
+ ? initializer->methodData()
+ : HeapVector<Member<PaymentMethodData>>()),
+ total_(initializer->hasTotal() ? initializer->total()
+ : PaymentCurrencyAmount::Create()),
+ modifiers_(initializer->hasModifiers()
+ ? initializer->modifiers()
+ : HeapVector<Member<PaymentDetailsModifier>>()),
+ instrument_key_(initializer->instrumentKey()),
observer_(respond_with_observer) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_event.h b/chromium/third_party/blink/renderer/modules/payments/payment_request_event.h
index 7c113bf99eb..24333aa4c9f 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_event.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_event.h
@@ -26,11 +26,16 @@ class MODULES_EXPORT PaymentRequestEvent final : public ExtendableEvent {
public:
static PaymentRequestEvent* Create(const AtomicString& type,
- const PaymentRequestEventInit&);
+ const PaymentRequestEventInit*);
static PaymentRequestEvent* Create(const AtomicString& type,
- const PaymentRequestEventInit&,
+ const PaymentRequestEventInit*,
RespondWithObserver*,
WaitUntilObserver*);
+
+ PaymentRequestEvent(const AtomicString& type,
+ const PaymentRequestEventInit*,
+ RespondWithObserver*,
+ WaitUntilObserver*);
~PaymentRequestEvent() override;
const AtomicString& InterfaceName() const override;
@@ -38,9 +43,9 @@ class MODULES_EXPORT PaymentRequestEvent final : public ExtendableEvent {
const String& topOrigin() const;
const String& paymentRequestOrigin() const;
const String& paymentRequestId() const;
- const HeapVector<PaymentMethodData>& methodData() const;
+ const HeapVector<Member<PaymentMethodData>>& methodData() const;
const ScriptValue total(ScriptState*) const;
- const HeapVector<PaymentDetailsModifier>& modifiers() const;
+ const HeapVector<Member<PaymentDetailsModifier>>& modifiers() const;
const String& instrumentKey() const;
ScriptPromise openWindow(ScriptState*, const String& url);
@@ -49,17 +54,12 @@ class MODULES_EXPORT PaymentRequestEvent final : public ExtendableEvent {
void Trace(blink::Visitor*) override;
private:
- PaymentRequestEvent(const AtomicString& type,
- const PaymentRequestEventInit&,
- RespondWithObserver*,
- WaitUntilObserver*);
-
String top_origin_;
String payment_request_origin_;
String payment_request_id_;
- HeapVector<PaymentMethodData> method_data_;
- PaymentCurrencyAmount total_;
- HeapVector<PaymentDetailsModifier> modifiers_;
+ HeapVector<Member<PaymentMethodData>> method_data_;
+ Member<PaymentCurrencyAmount> total_;
+ HeapVector<Member<PaymentDetailsModifier>> modifiers_;
String instrument_key_;
Member<RespondWithObserver> observer_;
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc
index b2401063f74..c8e5ee19d13 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc
@@ -23,7 +23,8 @@ PaymentRequestRespondWithObserver* PaymentRequestRespondWithObserver::Create(
ExecutionContext* context,
int event_id,
WaitUntilObserver* observer) {
- return new PaymentRequestRespondWithObserver(context, event_id, observer);
+ return MakeGarbageCollected<PaymentRequestRespondWithObserver>(
+ context, event_id, observer);
}
void PaymentRequestRespondWithObserver::OnResponseRejected(
@@ -33,7 +34,7 @@ void PaymentRequestRespondWithObserver::OnResponseRejected(
WebPaymentHandlerResponse web_data;
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToPaymentRequestEvent(event_id_, web_data, event_dispatch_time_);
+ ->RespondToPaymentRequestEvent(event_id_, web_data);
}
void PaymentRequestRespondWithObserver::OnResponseFulfilled(
@@ -44,8 +45,9 @@ void PaymentRequestRespondWithObserver::OnResponseFulfilled(
DCHECK(GetExecutionContext());
ExceptionState exception_state(value.GetIsolate(), context_type,
interface_name, property_name);
- PaymentHandlerResponse response = ScriptValue::To<PaymentHandlerResponse>(
- ToIsolate(GetExecutionContext()), value, exception_state);
+ PaymentHandlerResponse* response =
+ NativeValueTraits<PaymentHandlerResponse>::NativeValue(
+ ToIsolate(GetExecutionContext()), value.V8Value(), exception_state);
if (exception_state.HadException()) {
exception_state.ClearException();
OnResponseRejected(mojom::ServiceWorkerResponseError::kNoV8Instance);
@@ -53,7 +55,7 @@ void PaymentRequestRespondWithObserver::OnResponseFulfilled(
}
// Check payment response validity.
- if (!response.hasMethodName() || !response.hasDetails()) {
+ if (!response->hasMethodName() || !response->hasDetails()) {
GetExecutionContext()->AddConsoleMessage(
ConsoleMessage::Create(kJSMessageSource, kErrorMessageLevel,
"'PaymentHandlerResponse.methodName' and "
@@ -64,11 +66,11 @@ void PaymentRequestRespondWithObserver::OnResponseFulfilled(
}
WebPaymentHandlerResponse web_data;
- web_data.method_name = response.methodName();
+ web_data.method_name = response->methodName();
v8::Local<v8::String> details_value;
- if (!v8::JSON::Stringify(response.details().GetContext(),
- response.details().V8Value().As<v8::Object>())
+ if (!v8::JSON::Stringify(response->details().GetContext(),
+ response->details().V8Value().As<v8::Object>())
.ToLocal(&details_value)) {
GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kErrorMessageLevel,
@@ -79,14 +81,13 @@ void PaymentRequestRespondWithObserver::OnResponseFulfilled(
}
web_data.stringified_details = ToCoreString(details_value);
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToPaymentRequestEvent(event_id_, web_data, event_dispatch_time_);
+ ->RespondToPaymentRequestEvent(event_id_, web_data);
}
void PaymentRequestRespondWithObserver::OnNoResponse() {
DCHECK(GetExecutionContext());
ServiceWorkerGlobalScopeClient::From(GetExecutionContext())
- ->RespondToPaymentRequestEvent(event_id_, WebPaymentHandlerResponse(),
- event_dispatch_time_);
+ ->RespondToPaymentRequestEvent(event_id_, WebPaymentHandlerResponse());
}
PaymentRequestRespondWithObserver::PaymentRequestRespondWithObserver(
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.h b/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.h
index 12e6cb598de..558336f0af2 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.h
@@ -21,6 +21,9 @@ class WaitUntilObserver;
class MODULES_EXPORT PaymentRequestRespondWithObserver final
: public RespondWithObserver {
public:
+ PaymentRequestRespondWithObserver(ExecutionContext*,
+ int event_id,
+ WaitUntilObserver*);
~PaymentRequestRespondWithObserver() override = default;
static PaymentRequestRespondWithObserver* Create(ExecutionContext*,
@@ -35,11 +38,6 @@ class MODULES_EXPORT PaymentRequestRespondWithObserver final
void OnNoResponse() override;
void Trace(blink::Visitor*) override;
-
- private:
- PaymentRequestRespondWithObserver(ExecutionContext*,
- int event_id,
- WaitUntilObserver*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_test.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request_test.cc
index 0663a0fbec0..08cc5ee0903 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_test.cc
@@ -7,6 +7,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/modules/payments/payment_test_helper.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
@@ -27,7 +28,7 @@ TEST(PaymentRequestTest, SupportedMethodListRequired) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
PaymentRequest::Create(
- scope.GetExecutionContext(), HeapVector<PaymentMethodData>(),
+ scope.GetExecutionContext(), HeapVector<Member<PaymentMethodData>>(),
BuildPaymentDetailsInitForTest(), scope.GetExceptionState());
EXPECT_TRUE(scope.GetExceptionState().HadException());
@@ -38,10 +39,10 @@ TEST(PaymentRequestTest, SupportedMethodListRequired) {
TEST(PaymentRequestTest, NullShippingOptionWhenNoOptionsAvailable) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -53,12 +54,14 @@ TEST(PaymentRequestTest, NullShippingOptionWhenNoOptionsAvailable) {
TEST(PaymentRequestTest, NullShippingOptionWhenMultipleOptionsAvailable) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- details.setShippingOptions(
- HeapVector<PaymentShippingOption>(2, BuildShippingOptionForTest()));
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ HeapVector<Member<PaymentShippingOption>> shipping_options;
+ shipping_options.push_back(BuildShippingOptionForTest());
+ shipping_options.push_back(BuildShippingOptionForTest());
+ details->setShippingOptions(shipping_options);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -70,9 +73,9 @@ TEST(PaymentRequestTest, NullShippingOptionWhenMultipleOptionsAvailable) {
TEST(PaymentRequestTest, DontSelectSingleAvailableShippingOptionByDefault) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- details.setShippingOptions(HeapVector<PaymentShippingOption>(
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ details->setShippingOptions(HeapVector<Member<PaymentShippingOption>>(
1, BuildShippingOptionForTest(kPaymentTestDataId,
kPaymentTestOverwriteValue, "standard")));
@@ -87,12 +90,12 @@ TEST(PaymentRequestTest,
DontSelectSingleAvailableShippingOptionWhenShippingNotRequested) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- details.setShippingOptions(
- HeapVector<PaymentShippingOption>(1, BuildShippingOptionForTest()));
- PaymentOptions options;
- options.setRequestShipping(false);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ details->setShippingOptions(HeapVector<Member<PaymentShippingOption>>(
+ 1, BuildShippingOptionForTest()));
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -105,12 +108,12 @@ TEST(PaymentRequestTest,
DontSelectSingleUnselectedShippingOptionWhenShippingRequested) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- details.setShippingOptions(
- HeapVector<PaymentShippingOption>(1, BuildShippingOptionForTest()));
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ details->setShippingOptions(HeapVector<Member<PaymentShippingOption>>(
+ 1, BuildShippingOptionForTest()));
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -123,15 +126,15 @@ TEST(PaymentRequestTest,
SelectSingleSelectedShippingOptionWhenShippingRequested) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- HeapVector<PaymentShippingOption> shipping_options(
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ HeapVector<Member<PaymentShippingOption>> shipping_options(
1, BuildShippingOptionForTest(kPaymentTestDataId,
kPaymentTestOverwriteValue, "standard"));
- shipping_options[0].setSelected(true);
- details.setShippingOptions(shipping_options);
- PaymentOptions options;
- options.setRequestShipping(true);
+ shipping_options[0]->setSelected(true);
+ details->setShippingOptions(shipping_options);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -144,17 +147,17 @@ TEST(PaymentRequestTest,
SelectOnlySelectedShippingOptionWhenShippingRequested) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- HeapVector<PaymentShippingOption> shipping_options(2);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ HeapVector<Member<PaymentShippingOption>> shipping_options(2);
shipping_options[0] = BuildShippingOptionForTest(
kPaymentTestDataId, kPaymentTestOverwriteValue, "standard");
- shipping_options[0].setSelected(true);
+ shipping_options[0]->setSelected(true);
shipping_options[1] = BuildShippingOptionForTest(
kPaymentTestDataId, kPaymentTestOverwriteValue, "express");
- details.setShippingOptions(shipping_options);
- PaymentOptions options;
- options.setRequestShipping(true);
+ details->setShippingOptions(shipping_options);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -167,18 +170,18 @@ TEST(PaymentRequestTest,
SelectLastSelectedShippingOptionWhenShippingRequested) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- HeapVector<PaymentShippingOption> shipping_options(2);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ HeapVector<Member<PaymentShippingOption>> shipping_options(2);
shipping_options[0] = BuildShippingOptionForTest(
kPaymentTestDataId, kPaymentTestOverwriteValue, "standard");
- shipping_options[0].setSelected(true);
+ shipping_options[0]->setSelected(true);
shipping_options[1] = BuildShippingOptionForTest(
kPaymentTestDataId, kPaymentTestOverwriteValue, "express");
- shipping_options[1].setSelected(true);
- details.setShippingOptions(shipping_options);
- PaymentOptions options;
- options.setRequestShipping(true);
+ shipping_options[1]->setSelected(true);
+ details->setShippingOptions(shipping_options);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -190,10 +193,10 @@ TEST(PaymentRequestTest,
TEST(PaymentRequestTest, NullShippingTypeWhenRequestShippingIsFalse) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- PaymentOptions options;
- options.setRequestShipping(false);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(false);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -206,10 +209,10 @@ TEST(PaymentRequestTest,
DefaultShippingTypeWhenRequestShippingIsTrueWithNoSpecificType) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -221,11 +224,11 @@ TEST(PaymentRequestTest,
TEST(PaymentRequestTest, DeliveryShippingTypeWhenShippingTypeIsDelivery) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- PaymentOptions options;
- options.setRequestShipping(true);
- options.setShippingType("delivery");
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
+ options->setShippingType("delivery");
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -237,11 +240,11 @@ TEST(PaymentRequestTest, DeliveryShippingTypeWhenShippingTypeIsDelivery) {
TEST(PaymentRequestTest, PickupShippingTypeWhenShippingTypeIsPickup) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- PaymentOptions options;
- options.setRequestShipping(true);
- options.setShippingType("pickup");
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
+ options->setShippingType("pickup");
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
@@ -387,6 +390,7 @@ TEST(PaymentRequestTest, IgnoreUpdatePaymentDetailsAfterShowPromiseResolved) {
->OnPaymentResponse(BuildPaymentResponseForTest());
request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
ScriptValue::From(scope.GetScriptState(), "foo"));
}
@@ -403,6 +407,7 @@ TEST(PaymentRequestTest, RejectShowPromiseOnNonPaymentDetailsUpdate) {
.Then(funcs.ExpectNoCall(), funcs.ExpectCall());
request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
ScriptValue::From(scope.GetScriptState(), "NotPaymentDetails"));
}
@@ -418,11 +423,13 @@ TEST(PaymentRequestTest, RejectShowPromiseOnInvalidPaymentDetailsUpdate) {
request->show(scope.GetScriptState())
.Then(funcs.ExpectNoCall(), funcs.ExpectCall());
- request->OnUpdatePaymentDetails(ScriptValue::From(
- scope.GetScriptState(),
- FromJSONString(scope.GetScriptState()->GetIsolate(),
- scope.GetScriptState()->GetContext(), "{\"total\": {}}",
- scope.GetExceptionState())));
+ request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
+ ScriptValue::From(
+ scope.GetScriptState(),
+ FromJSONString(scope.GetScriptState()->GetIsolate(),
+ scope.GetScriptState()->GetContext(),
+ "{\"total\": {}}", scope.GetExceptionState())));
EXPECT_FALSE(scope.GetExceptionState().HadException());
}
@@ -431,10 +438,10 @@ TEST(PaymentRequestTest,
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
options, scope.GetExceptionState());
@@ -448,11 +455,13 @@ TEST(PaymentRequestTest,
"\"shippingOptions\": [{\"id\": \"standardShippingOption\", \"label\": "
"\"Standard shipping\", \"amount\": {\"currency\": \"USD\", \"value\": "
"\"5.00\"}, \"selected\": true}]}";
- request->OnUpdatePaymentDetails(ScriptValue::From(
- scope.GetScriptState(),
- FromJSONString(scope.GetScriptState()->GetIsolate(),
- scope.GetScriptState()->GetContext(),
- detail_with_shipping_options, scope.GetExceptionState())));
+ request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
+ ScriptValue::From(scope.GetScriptState(),
+ FromJSONString(scope.GetScriptState()->GetIsolate(),
+ scope.GetScriptState()->GetContext(),
+ detail_with_shipping_options,
+ scope.GetExceptionState())));
EXPECT_FALSE(scope.GetExceptionState().HadException());
EXPECT_EQ("standardShippingOption", request->shippingOption());
String detail_without_shipping_options =
@@ -460,6 +469,7 @@ TEST(PaymentRequestTest,
"\"value\": \"5.00\"}}}";
request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
ScriptValue::From(scope.GetScriptState(),
FromJSONString(scope.GetScriptState()->GetIsolate(),
scope.GetScriptState()->GetContext(),
@@ -476,8 +486,8 @@ TEST(
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -493,6 +503,7 @@ TEST(
"\"USD\", \"value\": \"50.00\"}}]}";
request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
ScriptValue::From(scope.GetScriptState(),
FromJSONString(scope.GetScriptState()->GetIsolate(),
scope.GetScriptState()->GetContext(),
@@ -506,8 +517,8 @@ TEST(PaymentRequestTest, UseTheSelectedShippingOptionFromPaymentDetailsUpdate) {
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentOptions options;
- options.setRequestShipping(true);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), options, scope.GetExceptionState());
@@ -523,6 +534,7 @@ TEST(PaymentRequestTest, UseTheSelectedShippingOptionFromPaymentDetailsUpdate) {
"\"USD\", \"value\": \"50.00\"}, \"selected\": true}]}";
request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
ScriptValue::From(scope.GetScriptState(),
FromJSONString(scope.GetScriptState()->GetIsolate(),
scope.GetScriptState()->GetContext(),
@@ -548,11 +560,13 @@ TEST(PaymentRequestTest, NoExceptionWithErrorMessageInUpdate) {
"\"value\": \"5.00\"}},"
"\"error\": \"This is an error message.\"}";
- request->OnUpdatePaymentDetails(ScriptValue::From(
- scope.GetScriptState(),
- FromJSONString(scope.GetScriptState()->GetIsolate(),
- scope.GetScriptState()->GetContext(),
- detail_with_error_msg, scope.GetExceptionState())));
+ request->OnUpdatePaymentDetails(
+ event_type_names::kShippingaddresschange,
+ ScriptValue::From(
+ scope.GetScriptState(),
+ FromJSONString(scope.GetScriptState()->GetIsolate(),
+ scope.GetScriptState()->GetContext(),
+ detail_with_error_msg, scope.GetExceptionState())));
EXPECT_FALSE(scope.GetExceptionState().HadException());
}
@@ -561,17 +575,17 @@ TEST(PaymentRequestTest,
V8TestingScope scope;
PaymentRequestMockFunctionScope funcs(scope.GetScriptState());
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- HeapVector<PaymentShippingOption> shipping_options(2);
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ HeapVector<Member<PaymentShippingOption>> shipping_options(2);
shipping_options[0] = BuildShippingOptionForTest(
kPaymentTestDataId, kPaymentTestOverwriteValue, "standard");
- shipping_options[0].setSelected(true);
+ shipping_options[0]->setSelected(true);
shipping_options[1] = BuildShippingOptionForTest(
kPaymentTestDataId, kPaymentTestOverwriteValue, "standard");
- details.setShippingOptions(shipping_options);
- PaymentOptions options;
- options.setRequestShipping(true);
+ details->setShippingOptions(shipping_options);
+ PaymentOptions* options = PaymentOptions::Create();
+ options->setRequestShipping(true);
PaymentRequest::Create(scope.GetExecutionContext(),
BuildPaymentMethodDataForTest(), details, options,
scope.GetExceptionState());
@@ -581,9 +595,9 @@ TEST(PaymentRequestTest,
TEST(PaymentRequestTest, DetailsIdIsSet) {
V8TestingScope scope;
MakePaymentRequestOriginSecure(scope.GetDocument());
- PaymentDetailsInit details;
- details.setTotal(BuildPaymentItemForTest());
- details.setId("my_payment_id");
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
+ details->setTotal(BuildPaymentItemForTest());
+ details->setId("my_payment_id");
PaymentRequest* request = PaymentRequest::Create(
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(), details,
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.cc
index 92e86937a7d..080fc25b647 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.cc
@@ -23,31 +23,32 @@ constexpr TimeDelta kAbortTimeout = TimeDelta::FromSeconds(60);
class UpdatePaymentDetailsFunction : public ScriptFunction {
public:
- static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
- PaymentUpdater* updater) {
+ static v8::Local<v8::Function> CreateFunction(
+ ScriptState* script_state,
+ PaymentRequestUpdateEvent* update_event) {
UpdatePaymentDetailsFunction* self =
- new UpdatePaymentDetailsFunction(script_state, updater);
+ new UpdatePaymentDetailsFunction(script_state, update_event);
return self->BindToV8Function();
}
void Trace(blink::Visitor* visitor) override {
- visitor->Trace(updater_);
+ visitor->Trace(update_event_);
ScriptFunction::Trace(visitor);
}
private:
UpdatePaymentDetailsFunction(ScriptState* script_state,
- PaymentUpdater* updater)
- : ScriptFunction(script_state), updater_(updater) {
- DCHECK(updater_);
+ PaymentRequestUpdateEvent* update_event)
+ : ScriptFunction(script_state), update_event_(update_event) {
+ DCHECK(update_event_);
}
ScriptValue Call(ScriptValue value) override {
- updater_->OnUpdatePaymentDetails(value);
+ update_event_->OnUpdatePaymentDetails(update_event_->type(), value);
return ScriptValue();
}
- Member<PaymentUpdater> updater_;
+ Member<PaymentRequestUpdateEvent> update_event_;
};
class UpdatePaymentDetailsErrorFunction : public ScriptFunction {
@@ -89,8 +90,9 @@ PaymentRequestUpdateEvent::~PaymentRequestUpdateEvent() = default;
PaymentRequestUpdateEvent* PaymentRequestUpdateEvent::Create(
ExecutionContext* execution_context,
const AtomicString& type,
- const PaymentRequestUpdateEventInit& init) {
- return new PaymentRequestUpdateEvent(execution_context, type, init);
+ const PaymentRequestUpdateEventInit* init) {
+ return MakeGarbageCollected<PaymentRequestUpdateEvent>(execution_context,
+ type, init);
}
void PaymentRequestUpdateEvent::SetPaymentDetailsUpdater(
@@ -130,11 +132,12 @@ void PaymentRequestUpdateEvent::updateWith(ScriptState* script_state,
}
void PaymentRequestUpdateEvent::OnUpdatePaymentDetails(
+ const AtomicString& event_type,
const ScriptValue& details_script_value) {
if (!updater_)
return;
abort_timer_.Stop();
- updater_->OnUpdatePaymentDetails(details_script_value);
+ updater_->OnUpdatePaymentDetails(event_type, details_script_value);
updater_ = nullptr;
}
@@ -159,7 +162,7 @@ void PaymentRequestUpdateEvent::OnUpdateEventTimeoutForTesting() {
PaymentRequestUpdateEvent::PaymentRequestUpdateEvent(
ExecutionContext* execution_context,
const AtomicString& type,
- const PaymentRequestUpdateEventInit& init)
+ const PaymentRequestUpdateEventInit* init)
: Event(type, init),
wait_for_update_(false),
abort_timer_(execution_context->GetTaskRunner(TaskType::kUserInteraction),
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.h b/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.h
index 27380478aad..d8618f539a6 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event.h
@@ -26,12 +26,16 @@ class MODULES_EXPORT PaymentRequestUpdateEvent : public Event,
USING_GARBAGE_COLLECTED_MIXIN(PaymentRequestUpdateEvent)
public:
+ PaymentRequestUpdateEvent(ExecutionContext*,
+ const AtomicString& type,
+ const PaymentRequestUpdateEventInit*);
~PaymentRequestUpdateEvent() override;
static PaymentRequestUpdateEvent* Create(
ExecutionContext*,
const AtomicString& type,
- const PaymentRequestUpdateEventInit& = PaymentRequestUpdateEventInit());
+ const PaymentRequestUpdateEventInit* =
+ PaymentRequestUpdateEventInit::Create());
void SetPaymentDetailsUpdater(PaymentUpdater*);
@@ -40,18 +44,14 @@ class MODULES_EXPORT PaymentRequestUpdateEvent : public Event,
bool is_waiting_for_update() const { return wait_for_update_; }
// PaymentUpdater:
- void OnUpdatePaymentDetails(const ScriptValue& details_script_value) override;
+ void OnUpdatePaymentDetails(const AtomicString& event_type,
+ const ScriptValue& details_script_value) override;
void OnUpdatePaymentDetailsFailure(const String& error) override;
void Trace(blink::Visitor*) override;
void OnUpdateEventTimeoutForTesting();
- protected:
- PaymentRequestUpdateEvent(ExecutionContext*,
- const AtomicString& type,
- const PaymentRequestUpdateEventInit&);
-
private:
void OnUpdateEventTimeout(TimerBase*);
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event_test.cc b/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event_test.cc
index ff8142374b8..4e2148cba1d 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_request_update_event_test.cc
@@ -28,8 +28,9 @@ class MockPaymentUpdater : public GarbageCollectedFinalized<MockPaymentUpdater>,
MockPaymentUpdater() = default;
~MockPaymentUpdater() override = default;
- MOCK_METHOD1(OnUpdatePaymentDetails,
- void(const ScriptValue& detailsScriptValue));
+ MOCK_METHOD2(OnUpdatePaymentDetails,
+ void(const AtomicString& event_type,
+ const ScriptValue& detailsScriptValue));
MOCK_METHOD1(OnUpdatePaymentDetailsFailure, void(const String& error));
void Trace(blink::Visitor* visitor) override {}
@@ -38,7 +39,7 @@ class MockPaymentUpdater : public GarbageCollectedFinalized<MockPaymentUpdater>,
TEST(PaymentRequestUpdateEventTest, OnUpdatePaymentDetailsCalled) {
V8TestingScope scope;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
MockPaymentUpdater* updater = new MockPaymentUpdater;
event->SetTrusted(true);
event->SetPaymentDetailsUpdater(updater);
@@ -49,7 +50,9 @@ TEST(PaymentRequestUpdateEventTest, OnUpdatePaymentDetailsCalled) {
scope.GetExceptionState());
EXPECT_FALSE(scope.GetExceptionState().HadException());
- EXPECT_CALL(*updater, OnUpdatePaymentDetails(testing::_));
+ EXPECT_CALL(*updater,
+ OnUpdatePaymentDetails(event_type_names::kShippingaddresschange,
+ testing::_));
EXPECT_CALL(*updater, OnUpdatePaymentDetailsFailure(testing::_)).Times(0);
payment_details->Resolve("foo");
@@ -58,7 +61,7 @@ TEST(PaymentRequestUpdateEventTest, OnUpdatePaymentDetailsCalled) {
TEST(PaymentRequestUpdateEventTest, OnUpdatePaymentDetailsFailureCalled) {
V8TestingScope scope;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
MockPaymentUpdater* updater = new MockPaymentUpdater;
event->SetTrusted(true);
event->SetPaymentDetailsUpdater(updater);
@@ -69,7 +72,10 @@ TEST(PaymentRequestUpdateEventTest, OnUpdatePaymentDetailsFailureCalled) {
scope.GetExceptionState());
EXPECT_FALSE(scope.GetExceptionState().HadException());
- EXPECT_CALL(*updater, OnUpdatePaymentDetails(testing::_)).Times(0);
+ EXPECT_CALL(*updater,
+ OnUpdatePaymentDetails(event_type_names::kShippingaddresschange,
+ testing::_))
+ .Times(0);
EXPECT_CALL(*updater, OnUpdatePaymentDetailsFailure(testing::_));
payment_details->Reject("oops");
@@ -78,7 +84,7 @@ TEST(PaymentRequestUpdateEventTest, OnUpdatePaymentDetailsFailureCalled) {
TEST(PaymentRequestUpdateEventTest, CannotUpdateWithoutDispatching) {
V8TestingScope scope;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
event->SetPaymentDetailsUpdater(new MockPaymentUpdater);
event->updateWith(
@@ -92,7 +98,7 @@ TEST(PaymentRequestUpdateEventTest, CannotUpdateWithoutDispatching) {
TEST(PaymentRequestUpdateEventTest, CannotUpdateTwice) {
V8TestingScope scope;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
MockPaymentUpdater* updater = new MockPaymentUpdater;
event->SetTrusted(true);
event->SetPaymentDetailsUpdater(updater);
@@ -114,7 +120,7 @@ TEST(PaymentRequestUpdateEventTest, CannotUpdateTwice) {
TEST(PaymentRequestUpdateEventTest, UpdaterNotRequired) {
V8TestingScope scope;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
event->SetTrusted(true);
event->updateWith(
@@ -133,7 +139,7 @@ TEST(PaymentRequestUpdateEventTest, AddressChangeUpdateWithTimeout) {
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), scope.GetExceptionState());
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
event->SetPaymentDetailsUpdater(request);
event->SetTrusted(true);
EXPECT_FALSE(scope.GetExceptionState().HadException());
@@ -166,7 +172,7 @@ TEST(PaymentRequestUpdateEventTest, OptionChangeUpdateWithTimeout) {
scope.GetExecutionContext(), BuildPaymentMethodDataForTest(),
BuildPaymentDetailsInitForTest(), scope.GetExceptionState());
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingoptionchange);
+ scope.GetExecutionContext(), event_type_names::kShippingoptionchange);
event->SetTrusted(true);
event->SetPaymentDetailsUpdater(request);
EXPECT_FALSE(scope.GetExceptionState().HadException());
@@ -200,7 +206,7 @@ TEST(PaymentRequestUpdateEventTest, AddressChangePromiseTimeout) {
BuildPaymentDetailsInitForTest(), scope.GetExceptionState());
EXPECT_FALSE(scope.GetExceptionState().HadException());
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
event->SetTrusted(true);
event->SetPaymentDetailsUpdater(request);
event->SetEventPhase(Event::kCapturingPhase);
@@ -233,7 +239,7 @@ TEST(PaymentRequestUpdateEventTest, OptionChangePromiseTimeout) {
BuildPaymentDetailsInitForTest(), scope.GetExceptionState());
EXPECT_FALSE(scope.GetExceptionState().HadException());
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingoptionchange);
+ scope.GetExecutionContext(), event_type_names::kShippingoptionchange);
event->SetTrusted(true);
event->SetPaymentDetailsUpdater(request);
event->SetEventPhase(Event::kCapturingPhase);
@@ -260,7 +266,7 @@ TEST(PaymentRequestUpdateEventTest, OptionChangePromiseTimeout) {
TEST(PaymentRequestUpdateEventTest, NotAllowUntrustedEvent) {
V8TestingScope scope;
PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::Create(
- scope.GetExecutionContext(), EventTypeNames::shippingaddresschange);
+ scope.GetExecutionContext(), event_type_names::kShippingaddresschange);
event->SetTrusted(false);
event->updateWith(
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_response.cc b/chromium/third_party/blink/renderer/modules/payments/payment_response.cc
index 68f5ae9f221..d49786f98ed 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_response.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_response.cc
@@ -63,7 +63,8 @@ void PaymentResponse::UpdateDetailsFromJSON(ScriptState* script_state,
const String& json) {
ScriptState::Scope scope(script_state);
if (json.IsEmpty()) {
- details_ = V8ObjectBuilder(script_state).GetScriptValue();
+ details_.Set(script_state->GetIsolate(),
+ V8ObjectBuilder(script_state).V8Value());
return;
}
@@ -75,10 +76,11 @@ void PaymentResponse::UpdateDetailsFromJSON(ScriptState* script_state,
json, exception_state);
if (exception_state.HadException()) {
exception_state.ClearException();
- details_ = V8ObjectBuilder(script_state).GetScriptValue();
+ details_.Set(script_state->GetIsolate(),
+ V8ObjectBuilder(script_state).V8Value());
return;
}
- details_ = ScriptValue(script_state, parsed_value);
+ details_.Set(script_state->GetIsolate(), parsed_value);
}
ScriptValue PaymentResponse::toJSONForBinding(ScriptState* script_state) const {
@@ -102,7 +104,7 @@ ScriptValue PaymentResponse::toJSONForBinding(ScriptState* script_state) const {
}
ScriptValue PaymentResponse::details(ScriptState* script_state) const {
- return ScriptValue(script_state, details_.V8ValueFor(script_state));
+ return ScriptValue::ToWorldSafeScriptValue(script_state, details_);
}
ScriptPromise PaymentResponse::complete(ScriptState* script_state,
@@ -118,7 +120,7 @@ ScriptPromise PaymentResponse::complete(ScriptState* script_state,
ScriptPromise PaymentResponse::retry(
ScriptState* script_state,
- const PaymentValidationErrors& error_fields) {
+ const PaymentValidationErrors* error_fields) {
return payment_state_resolver_->Retry(script_state, error_fields);
}
@@ -127,7 +129,7 @@ bool PaymentResponse::HasPendingActivity() const {
}
const AtomicString& PaymentResponse::InterfaceName() const {
- return EventTypeNames::payerdetailchange;
+ return event_type_names::kPayerdetailchange;
}
ExecutionContext* PaymentResponse::GetExecutionContext() const {
@@ -135,6 +137,7 @@ ExecutionContext* PaymentResponse::GetExecutionContext() const {
}
void PaymentResponse::Trace(blink::Visitor* visitor) {
+ visitor->Trace(details_);
visitor->Trace(shipping_address_);
visitor->Trace(payment_state_resolver_);
EventTargetWithInlineData::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_response.h b/chromium/third_party/blink/renderer/modules/payments/payment_response.h
index f20071dc9f7..c404239ebcd 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_response.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_response.h
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/payments/payment_currency_amount.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -59,11 +60,11 @@ class MODULES_EXPORT PaymentResponse final
const String& payerPhone() const { return payer_phone_; }
ScriptPromise complete(ScriptState*, const String& result = "");
- ScriptPromise retry(ScriptState*, const PaymentValidationErrors&);
+ ScriptPromise retry(ScriptState*, const PaymentValidationErrors*);
bool HasPendingActivity() const override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(payerdetailchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(payerdetailchange, kPayerdetailchange);
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
@@ -73,7 +74,7 @@ class MODULES_EXPORT PaymentResponse final
private:
String request_id_;
String method_name_;
- ScriptValue details_;
+ TraceWrapperV8Reference<v8::Value> details_;
Member<PaymentAddress> shipping_address_;
String shipping_option_;
String payer_name_;
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_response.idl b/chromium/third_party/blink/renderer/modules/payments/payment_response.idl
index 31096ecec5d..f5d94a35018 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_response.idl
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_response.idl
@@ -30,7 +30,7 @@ enum PaymentComplete {
readonly attribute DOMString? payerPhone;
[CallWith=ScriptState, NewObject] Promise<void> complete(optional PaymentComplete paymentResult = "unknown");
- [CallWith=ScriptState, NewObject, RuntimeEnabled=PaymentRetry] Promise<void> retry(PaymentValidationErrors errorFields);
+ [CallWith=ScriptState, NewObject, RuntimeEnabled=PaymentRetry] Promise<void> retry(optional PaymentValidationErrors errorFields);
[RuntimeEnabled=PaymentRetry] attribute EventHandler onpayerdetailchange;
};
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_response_test.cc b/chromium/third_party/blink/renderer/modules/payments/payment_response_test.cc
index 5f1b4d99506..e95f4eff0fc 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_response_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_response_test.cc
@@ -39,7 +39,7 @@ class MockPaymentStateResolver final
MOCK_METHOD2(Complete, ScriptPromise(ScriptState*, PaymentComplete result));
MOCK_METHOD2(Retry,
ScriptPromise(ScriptState*,
- const PaymentValidationErrors& errorFields));
+ const PaymentValidationErrors* errorFields));
void Trace(blink::Visitor* visitor) override {}
@@ -59,9 +59,9 @@ TEST(PaymentResponseTest, DataCopiedOver) {
input->payer->phone = "0123";
MockPaymentStateResolver* complete_callback = new MockPaymentStateResolver;
- PaymentResponse* output =
- new PaymentResponse(scope.GetScriptState(), std::move(input), nullptr,
- complete_callback, "id");
+ PaymentResponse* output = MakeGarbageCollected<PaymentResponse>(
+ scope.GetScriptState(), std::move(input), nullptr, complete_callback,
+ "id");
EXPECT_EQ("foo", output->methodName());
EXPECT_EQ("standardShippingOption", output->shippingOption());
@@ -91,9 +91,9 @@ TEST(PaymentResponseTest,
BuildPaymentResponseForTest();
input->stringified_details = "transactionId";
MockPaymentStateResolver* complete_callback = new MockPaymentStateResolver;
- PaymentResponse* output =
- new PaymentResponse(scope.GetScriptState(), std::move(input), nullptr,
- complete_callback, "id");
+ PaymentResponse* output = MakeGarbageCollected<PaymentResponse>(
+ scope.GetScriptState(), std::move(input), nullptr, complete_callback,
+ "id");
ScriptValue details = output->details(scope.GetScriptState());
ASSERT_TRUE(details.V8Value()->IsObject());
@@ -114,9 +114,9 @@ TEST(PaymentResponseTest, PaymentResponseDetailsRetrunsTheSameObject) {
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
MockPaymentStateResolver* complete_callback = new MockPaymentStateResolver;
- PaymentResponse* output =
- new PaymentResponse(scope.GetScriptState(), std::move(input), nullptr,
- complete_callback, "id");
+ PaymentResponse* output = MakeGarbageCollected<PaymentResponse>(
+ scope.GetScriptState(), std::move(input), nullptr, complete_callback,
+ "id");
EXPECT_EQ(output->details(scope.GetScriptState()),
output->details(scope.GetScriptState()));
}
@@ -128,9 +128,9 @@ TEST(PaymentResponseTest, CompleteCalledWithSuccess) {
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
MockPaymentStateResolver* complete_callback = new MockPaymentStateResolver;
- PaymentResponse* output =
- new PaymentResponse(scope.GetScriptState(), std::move(input), nullptr,
- complete_callback, "id");
+ PaymentResponse* output = MakeGarbageCollected<PaymentResponse>(
+ scope.GetScriptState(), std::move(input), nullptr, complete_callback,
+ "id");
EXPECT_CALL(*complete_callback,
Complete(scope.GetScriptState(), PaymentStateResolver::kSuccess));
@@ -145,9 +145,9 @@ TEST(PaymentResponseTest, CompleteCalledWithFailure) {
input->method_name = "foo";
input->stringified_details = "{\"transactionId\": 123}";
MockPaymentStateResolver* complete_callback = new MockPaymentStateResolver;
- PaymentResponse* output =
- new PaymentResponse(scope.GetScriptState(), std::move(input), nullptr,
- complete_callback, "id");
+ PaymentResponse* output = MakeGarbageCollected<PaymentResponse>(
+ scope.GetScriptState(), std::move(input), nullptr, complete_callback,
+ "id");
EXPECT_CALL(*complete_callback,
Complete(scope.GetScriptState(), PaymentStateResolver::kFail));
@@ -173,11 +173,11 @@ TEST(PaymentResponseTest, JSONSerializerTest) {
input->shipping_address->address_line.push_back("BIN1");
input->shipping_address->address_line.push_back("First floor");
PaymentAddress* address =
- new PaymentAddress(std::move(input->shipping_address));
+ MakeGarbageCollected<PaymentAddress>(std::move(input->shipping_address));
- PaymentResponse* output =
- new PaymentResponse(scope.GetScriptState(), std::move(input), address,
- new MockPaymentStateResolver, "id");
+ PaymentResponse* output = MakeGarbageCollected<PaymentResponse>(
+ scope.GetScriptState(), std::move(input), address,
+ new MockPaymentStateResolver, "id");
ScriptValue json_object = output->toJSONForBinding(scope.GetScriptState());
EXPECT_TRUE(json_object.IsObject());
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_state_resolver.h b/chromium/third_party/blink/renderer/modules/payments/payment_state_resolver.h
index 5cded1ec7fd..c9014ac1e96 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_state_resolver.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_state_resolver.h
@@ -19,7 +19,7 @@ class MODULES_EXPORT PaymentStateResolver : public GarbageCollectedMixin {
enum PaymentComplete { kFail, kSuccess, kUnknown };
virtual ScriptPromise Complete(ScriptState*, PaymentComplete result) = 0;
- virtual ScriptPromise Retry(ScriptState*, const PaymentValidationErrors&) = 0;
+ virtual ScriptPromise Retry(ScriptState*, const PaymentValidationErrors*) = 0;
protected:
virtual ~PaymentStateResolver() = default;
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.cc b/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.cc
index b532619a039..2b206afbe0e 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.cc
@@ -18,34 +18,34 @@ static int g_unique_id = 0;
// PaymentItem and PaymentShippingOption have identical structure
// except for the "id" field, which is present only in PaymentShippingOption.
template <typename PaymentItemOrPaymentShippingOption>
-void SetValues(PaymentItemOrPaymentShippingOption& original,
+void SetValues(PaymentItemOrPaymentShippingOption* original,
PaymentTestDataToChange data,
PaymentTestModificationType modification_type,
const String& value_to_use) {
- PaymentCurrencyAmount item_amount;
+ PaymentCurrencyAmount* item_amount = PaymentCurrencyAmount::Create();
if (data == kPaymentTestDataCurrencyCode) {
if (modification_type == kPaymentTestOverwriteValue)
- item_amount.setCurrency(value_to_use);
+ item_amount->setCurrency(value_to_use);
} else {
- item_amount.setCurrency("USD");
+ item_amount->setCurrency("USD");
}
if (data == kPaymentTestDataValue) {
if (modification_type == kPaymentTestOverwriteValue)
- item_amount.setValue(value_to_use);
+ item_amount->setValue(value_to_use);
} else {
- item_amount.setValue("9.99");
+ item_amount->setValue("9.99");
}
if (data != kPaymentTestDataAmount ||
modification_type != kPaymentTestRemoveKey)
- original.setAmount(item_amount);
+ original->setAmount(item_amount);
if (data == kPaymentTestDataLabel) {
if (modification_type == kPaymentTestOverwriteValue)
- original.setLabel(value_to_use);
+ original->setLabel(value_to_use);
} else {
- original.setLabel("Label");
+ original->setLabel("Label");
}
}
@@ -54,21 +54,24 @@ void BuildPaymentDetailsBase(PaymentTestDetailToChange detail,
PaymentTestModificationType modification_type,
const String& value_to_use,
PaymentDetailsBase* details) {
- PaymentItem item;
- if (detail == kPaymentTestDetailItem)
+ PaymentItem* item = nullptr;
+ if (detail == kPaymentTestDetailItem) {
item = BuildPaymentItemForTest(data, modification_type, value_to_use);
- else
+ } else {
item = BuildPaymentItemForTest();
+ }
+ DCHECK(item);
- PaymentShippingOption shipping_option;
+ PaymentShippingOption* shipping_option = nullptr;
if (detail == kPaymentTestDetailShippingOption) {
shipping_option =
BuildShippingOptionForTest(data, modification_type, value_to_use);
} else {
shipping_option = BuildShippingOptionForTest();
}
+ DCHECK(shipping_option);
- PaymentDetailsModifier modifier;
+ PaymentDetailsModifier* modifier = nullptr;
if (detail == kPaymentTestDetailModifierTotal ||
detail == kPaymentTestDetailModifierItem) {
modifier = BuildPaymentDetailsModifierForTest(
@@ -76,115 +79,122 @@ void BuildPaymentDetailsBase(PaymentTestDetailToChange detail,
} else {
modifier = BuildPaymentDetailsModifierForTest();
}
+ DCHECK(modifier);
- details->setDisplayItems(HeapVector<PaymentItem>(1, item));
+ details->setDisplayItems(HeapVector<Member<PaymentItem>>(1, item));
details->setShippingOptions(
- HeapVector<PaymentShippingOption>(1, shipping_option));
- details->setModifiers(HeapVector<PaymentDetailsModifier>(1, modifier));
+ HeapVector<Member<PaymentShippingOption>>(1, shipping_option));
+ details->setModifiers(
+ HeapVector<Member<PaymentDetailsModifier>>(1, modifier));
}
} // namespace
-PaymentItem BuildPaymentItemForTest(
+PaymentItem* BuildPaymentItemForTest(
PaymentTestDataToChange data,
PaymentTestModificationType modification_type,
const String& value_to_use) {
DCHECK_NE(data, kPaymentTestDataId);
- PaymentItem item;
+ PaymentItem* item = PaymentItem::Create();
SetValues(item, data, modification_type, value_to_use);
return item;
}
-PaymentShippingOption BuildShippingOptionForTest(
+PaymentShippingOption* BuildShippingOptionForTest(
PaymentTestDataToChange data,
PaymentTestModificationType modification_type,
const String& value_to_use) {
- PaymentShippingOption shipping_option;
+ PaymentShippingOption* shipping_option = PaymentShippingOption::Create();
if (data == kPaymentTestDataId) {
if (modification_type == kPaymentTestOverwriteValue)
- shipping_option.setId(value_to_use);
+ shipping_option->setId(value_to_use);
} else {
- shipping_option.setId("id" + String::Number(g_unique_id++));
+ shipping_option->setId("id" + String::Number(g_unique_id++));
}
SetValues(shipping_option, data, modification_type, value_to_use);
return shipping_option;
}
-PaymentDetailsModifier BuildPaymentDetailsModifierForTest(
+PaymentDetailsModifier* BuildPaymentDetailsModifierForTest(
PaymentTestDetailToChange detail,
PaymentTestDataToChange data,
PaymentTestModificationType modification_type,
const String& value_to_use) {
- PaymentItem total;
- if (detail == kPaymentTestDetailModifierTotal)
+ PaymentItem* total = nullptr;
+ if (detail == kPaymentTestDetailModifierTotal) {
total = BuildPaymentItemForTest(data, modification_type, value_to_use);
- else
+ } else {
total = BuildPaymentItemForTest();
+ }
+ DCHECK(total);
- PaymentItem item;
- if (detail == kPaymentTestDetailModifierItem)
+ PaymentItem* item = nullptr;
+ if (detail == kPaymentTestDetailModifierItem) {
item = BuildPaymentItemForTest(data, modification_type, value_to_use);
- else
+ } else {
item = BuildPaymentItemForTest();
+ }
+ DCHECK(item);
- PaymentDetailsModifier modifier;
- modifier.setSupportedMethod("foo");
- modifier.setTotal(total);
- modifier.setAdditionalDisplayItems(HeapVector<PaymentItem>(1, item));
+ PaymentDetailsModifier* modifier = PaymentDetailsModifier::Create();
+ modifier->setSupportedMethod("foo");
+ modifier->setTotal(total);
+ modifier->setAdditionalDisplayItems(HeapVector<Member<PaymentItem>>(1, item));
return modifier;
}
-PaymentDetailsInit BuildPaymentDetailsInitForTest(
+PaymentDetailsInit* BuildPaymentDetailsInitForTest(
PaymentTestDetailToChange detail,
PaymentTestDataToChange data,
PaymentTestModificationType modification_type,
const String& value_to_use) {
- PaymentDetailsInit details;
+ PaymentDetailsInit* details = PaymentDetailsInit::Create();
BuildPaymentDetailsBase(detail, data, modification_type, value_to_use,
- &details);
+ details);
if (detail == kPaymentTestDetailTotal) {
- details.setTotal(
+ details->setTotal(
BuildPaymentItemForTest(data, modification_type, value_to_use));
} else {
- details.setTotal(BuildPaymentItemForTest());
+ details->setTotal(BuildPaymentItemForTest());
}
return details;
}
-PaymentDetailsUpdate BuildPaymentDetailsUpdateForTest(
+PaymentDetailsUpdate* BuildPaymentDetailsUpdateForTest(
PaymentTestDetailToChange detail,
PaymentTestDataToChange data,
PaymentTestModificationType modification_type,
const String& value_to_use) {
- PaymentDetailsUpdate details;
+ PaymentDetailsUpdate* details = PaymentDetailsUpdate::Create();
BuildPaymentDetailsBase(detail, data, modification_type, value_to_use,
- &details);
+ details);
if (detail == kPaymentTestDetailTotal) {
- details.setTotal(
+ details->setTotal(
BuildPaymentItemForTest(data, modification_type, value_to_use));
} else {
- details.setTotal(BuildPaymentItemForTest());
+ details->setTotal(BuildPaymentItemForTest());
}
if (detail == kPaymentTestDetailError)
- details.setError(value_to_use);
+ details->setError(value_to_use);
return details;
}
-PaymentDetailsUpdate BuildPaymentDetailsErrorMsgForTest(
+PaymentDetailsUpdate* BuildPaymentDetailsErrorMsgForTest(
const String& value_to_use) {
return BuildPaymentDetailsUpdateForTest(
kPaymentTestDetailError, kPaymentTestDataNone, kPaymentTestOverwriteValue,
value_to_use);
}
-HeapVector<PaymentMethodData> BuildPaymentMethodDataForTest() {
- HeapVector<PaymentMethodData> method_data(1, PaymentMethodData());
- method_data[0].setSupportedMethod("foo");
+HeapVector<Member<PaymentMethodData>> BuildPaymentMethodDataForTest() {
+ HeapVector<Member<PaymentMethodData>> method_data(
+ 1, PaymentMethodData::Create());
+ method_data[0]->setSupportedMethod("foo");
return method_data;
}
@@ -214,19 +224,20 @@ PaymentRequestMockFunctionScope::~PaymentRequestMockFunctionScope() {
v8::Local<v8::Function> PaymentRequestMockFunctionScope::ExpectCall(
String* captor) {
- mock_functions_.push_back(new MockFunction(script_state_, captor));
+ mock_functions_.push_back(
+ MakeGarbageCollected<MockFunction>(script_state_, captor));
EXPECT_CALL(*mock_functions_.back(), Call(testing::_));
return mock_functions_.back()->Bind();
}
v8::Local<v8::Function> PaymentRequestMockFunctionScope::ExpectCall() {
- mock_functions_.push_back(new MockFunction(script_state_));
+ mock_functions_.push_back(MakeGarbageCollected<MockFunction>(script_state_));
EXPECT_CALL(*mock_functions_.back(), Call(testing::_));
return mock_functions_.back()->Bind();
}
v8::Local<v8::Function> PaymentRequestMockFunctionScope::ExpectNoCall() {
- mock_functions_.push_back(new MockFunction(script_state_));
+ mock_functions_.push_back(MakeGarbageCollected<MockFunction>(script_state_));
EXPECT_CALL(*mock_functions_.back(), Call(testing::_)).Times(0);
return mock_functions_.back()->Bind();
}
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.h b/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.h
index f81fbc53187..b9bd4fad9e2 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_test_helper.h
@@ -50,38 +50,38 @@ enum PaymentTestModificationType {
kPaymentTestRemoveKey
};
-PaymentItem BuildPaymentItemForTest(
+PaymentItem* BuildPaymentItemForTest(
PaymentTestDataToChange = kPaymentTestDataNone,
PaymentTestModificationType = kPaymentTestOverwriteValue,
const String& value_to_use = String());
-PaymentShippingOption BuildShippingOptionForTest(
+PaymentShippingOption* BuildShippingOptionForTest(
PaymentTestDataToChange = kPaymentTestDataNone,
PaymentTestModificationType = kPaymentTestOverwriteValue,
const String& value_to_use = String());
-PaymentDetailsModifier BuildPaymentDetailsModifierForTest(
+PaymentDetailsModifier* BuildPaymentDetailsModifierForTest(
PaymentTestDetailToChange = kPaymentTestDetailNone,
PaymentTestDataToChange = kPaymentTestDataNone,
PaymentTestModificationType = kPaymentTestOverwriteValue,
const String& value_to_use = String());
-PaymentDetailsInit BuildPaymentDetailsInitForTest(
+PaymentDetailsInit* BuildPaymentDetailsInitForTest(
PaymentTestDetailToChange = kPaymentTestDetailNone,
PaymentTestDataToChange = kPaymentTestDataNone,
PaymentTestModificationType = kPaymentTestOverwriteValue,
const String& value_to_use = String());
-PaymentDetailsUpdate BuildPaymentDetailsUpdateForTest(
+PaymentDetailsUpdate* BuildPaymentDetailsUpdateForTest(
PaymentTestDetailToChange = kPaymentTestDetailNone,
PaymentTestDataToChange = kPaymentTestDataNone,
PaymentTestModificationType = kPaymentTestOverwriteValue,
const String& value_to_use = String());
-PaymentDetailsUpdate BuildPaymentDetailsErrorMsgForTest(
+PaymentDetailsUpdate* BuildPaymentDetailsErrorMsgForTest(
const String& value_to_use = String());
-HeapVector<PaymentMethodData> BuildPaymentMethodDataForTest();
+HeapVector<Member<PaymentMethodData>> BuildPaymentMethodDataForTest();
payments::mojom::blink::PaymentResponsePtr BuildPaymentResponseForTest();
diff --git a/chromium/third_party/blink/renderer/modules/payments/payment_updater.h b/chromium/third_party/blink/renderer/modules/payments/payment_updater.h
index 0e278dd9590..57cccf92dfd 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payment_updater.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payment_updater.h
@@ -16,6 +16,7 @@ class ScriptValue;
class MODULES_EXPORT PaymentUpdater : public GarbageCollectedMixin {
public:
virtual void OnUpdatePaymentDetails(
+ const AtomicString& event_type,
const ScriptValue& details_script_value) = 0;
virtual void OnUpdatePaymentDetailsFailure(const String& error) = 0;
diff --git a/chromium/third_party/blink/renderer/modules/payments/payments_validators.cc b/chromium/third_party/blink/renderer/modules/payments/payments_validators.cc
index 467d970f0c1..966cb946694 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payments_validators.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payments_validators.cc
@@ -129,58 +129,60 @@ bool PaymentsValidators::IsValidErrorMsgFormat(const String& error,
// static
bool PaymentsValidators::IsValidAddressErrorsFormat(
- const AddressErrors& errors,
+ const AddressErrors* errors,
String* optional_error_message) {
- return (!errors.hasAddressLine() ||
- IsValidErrorMsgFormat(errors.addressLine(),
+ return (!errors->hasAddressLine() ||
+ IsValidErrorMsgFormat(errors->addressLine(),
optional_error_message)) &&
- (!errors.hasCity() ||
- IsValidErrorMsgFormat(errors.city(), optional_error_message)) &&
- (!errors.hasCountry() ||
- IsValidErrorMsgFormat(errors.country(), optional_error_message)) &&
- (!errors.hasDependentLocality() ||
- IsValidErrorMsgFormat(errors.dependentLocality(),
+ (!errors->hasCity() ||
+ IsValidErrorMsgFormat(errors->city(), optional_error_message)) &&
+ (!errors->hasCountry() ||
+ IsValidErrorMsgFormat(errors->country(), optional_error_message)) &&
+ (!errors->hasDependentLocality() ||
+ IsValidErrorMsgFormat(errors->dependentLocality(),
optional_error_message)) &&
- (!errors.hasLanguageCode() ||
- IsValidErrorMsgFormat(errors.languageCode(),
+ (!errors->hasLanguageCode() ||
+ IsValidErrorMsgFormat(errors->languageCode(),
optional_error_message)) &&
- (!errors.hasOrganization() ||
- IsValidErrorMsgFormat(errors.organization(),
+ (!errors->hasOrganization() ||
+ IsValidErrorMsgFormat(errors->organization(),
optional_error_message)) &&
- (!errors.hasPhone() ||
- IsValidErrorMsgFormat(errors.phone(), optional_error_message)) &&
- (!errors.hasPostalCode() ||
- IsValidErrorMsgFormat(errors.postalCode(), optional_error_message)) &&
- (!errors.hasRecipient() ||
- IsValidErrorMsgFormat(errors.recipient(), optional_error_message)) &&
- (!errors.hasRegion() ||
- IsValidErrorMsgFormat(errors.region(), optional_error_message)) &&
- (!errors.hasRegionCode() ||
- IsValidErrorMsgFormat(errors.regionCode(), optional_error_message)) &&
- (!errors.hasSortingCode() ||
- IsValidErrorMsgFormat(errors.sortingCode(), optional_error_message));
+ (!errors->hasPhone() ||
+ IsValidErrorMsgFormat(errors->phone(), optional_error_message)) &&
+ (!errors->hasPostalCode() ||
+ IsValidErrorMsgFormat(errors->postalCode(),
+ optional_error_message)) &&
+ (!errors->hasRecipient() ||
+ IsValidErrorMsgFormat(errors->recipient(), optional_error_message)) &&
+ (!errors->hasRegion() ||
+ IsValidErrorMsgFormat(errors->region(), optional_error_message)) &&
+ (!errors->hasRegionCode() ||
+ IsValidErrorMsgFormat(errors->regionCode(),
+ optional_error_message)) &&
+ (!errors->hasSortingCode() ||
+ IsValidErrorMsgFormat(errors->sortingCode(), optional_error_message));
}
// static
bool PaymentsValidators::IsValidPayerErrorsFormat(
- const PayerErrors& errors,
+ const PayerErrors* errors,
String* optional_error_message) {
- return (!errors.hasEmail() ||
- IsValidErrorMsgFormat(errors.email(), optional_error_message)) &&
- (!errors.hasName() ||
- IsValidErrorMsgFormat(errors.name(), optional_error_message)) &&
- (!errors.hasPhone() ||
- IsValidErrorMsgFormat(errors.phone(), optional_error_message));
+ return (!errors->hasEmail() ||
+ IsValidErrorMsgFormat(errors->email(), optional_error_message)) &&
+ (!errors->hasName() ||
+ IsValidErrorMsgFormat(errors->name(), optional_error_message)) &&
+ (!errors->hasPhone() ||
+ IsValidErrorMsgFormat(errors->phone(), optional_error_message));
}
// static
bool PaymentsValidators::IsValidPaymentValidationErrorsFormat(
- const PaymentValidationErrors& errors,
+ const PaymentValidationErrors* errors,
String* optional_error_message) {
- return (!errors.hasPayer() ||
- IsValidPayerErrorsFormat(errors.payer(), optional_error_message)) &&
- (!errors.hasShippingAddress() ||
- IsValidAddressErrorsFormat(errors.shippingAddress(),
+ return (!errors->hasPayer() ||
+ IsValidPayerErrorsFormat(errors->payer(), optional_error_message)) &&
+ (!errors->hasShippingAddress() ||
+ IsValidAddressErrorsFormat(errors->shippingAddress(),
optional_error_message));
}
diff --git a/chromium/third_party/blink/renderer/modules/payments/payments_validators.h b/chromium/third_party/blink/renderer/modules/payments/payments_validators.h
index 1a7d384165b..dafd439fb4d 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payments_validators.h
+++ b/chromium/third_party/blink/renderer/modules/payments/payments_validators.h
@@ -57,16 +57,16 @@ class MODULES_EXPORT PaymentsValidators final {
String* optional_error_message);
// Returns false if |errors| has too long string (greater than 2048).
- static bool IsValidAddressErrorsFormat(const AddressErrors& errors,
+ static bool IsValidAddressErrorsFormat(const AddressErrors* errors,
String* optional_error_message);
// Returns false if |errors| has too long string (greater than 2048).
- static bool IsValidPayerErrorsFormat(const PayerErrors& errors,
+ static bool IsValidPayerErrorsFormat(const PayerErrors* errors,
String* optional_error_message);
// Returns false if |errors| has too long string (greater than 2048).
static bool IsValidPaymentValidationErrorsFormat(
- const PaymentValidationErrors& errors,
+ const PaymentValidationErrors* errors,
String* optional_error_message);
};
diff --git a/chromium/third_party/blink/renderer/modules/payments/payments_validators_test.cc b/chromium/third_party/blink/renderer/modules/payments/payments_validators_test.cc
index 431c7751226..bbe337fe9b9 100644
--- a/chromium/third_party/blink/renderer/modules/payments/payments_validators_test.cc
+++ b/chromium/third_party/blink/renderer/modules/payments/payments_validators_test.cc
@@ -292,32 +292,32 @@ struct ValidationErrorsTestCase {
return test_case; \
})()
-PaymentValidationErrors toPaymentValidationErrors(
+PaymentValidationErrors* toPaymentValidationErrors(
ValidationErrorsTestCase test_case) {
- PaymentValidationErrors errors;
-
- PayerErrors payer;
- payer.setEmail(test_case.m_payer_email);
- payer.setName(test_case.m_payer_name);
- payer.setPhone(test_case.m_payer_phone);
-
- AddressErrors shipping_address;
- shipping_address.setAddressLine(test_case.m_shipping_address_address_line);
- shipping_address.setCity(test_case.m_shipping_address_city);
- shipping_address.setCountry(test_case.m_shipping_address_country);
- shipping_address.setDependentLocality(
+ PaymentValidationErrors* errors = PaymentValidationErrors::Create();
+
+ PayerErrors* payer = PayerErrors::Create();
+ payer->setEmail(test_case.m_payer_email);
+ payer->setName(test_case.m_payer_name);
+ payer->setPhone(test_case.m_payer_phone);
+
+ AddressErrors* shipping_address = AddressErrors::Create();
+ shipping_address->setAddressLine(test_case.m_shipping_address_address_line);
+ shipping_address->setCity(test_case.m_shipping_address_city);
+ shipping_address->setCountry(test_case.m_shipping_address_country);
+ shipping_address->setDependentLocality(
test_case.m_shipping_address_dependent_locality);
- shipping_address.setLanguageCode(test_case.m_shipping_address_language_code);
- shipping_address.setOrganization(test_case.m_shipping_address_organization);
- shipping_address.setPhone(test_case.m_shipping_address_phone);
- shipping_address.setPostalCode(test_case.m_shipping_address_postal_code);
- shipping_address.setRecipient(test_case.m_shipping_address_recipient);
- shipping_address.setRegion(test_case.m_shipping_address_region);
- shipping_address.setRegionCode(test_case.m_shipping_address_region_code);
- shipping_address.setSortingCode(test_case.m_shipping_address_sorting_code);
-
- errors.setPayer(payer);
- errors.setShippingAddress(shipping_address);
+ shipping_address->setLanguageCode(test_case.m_shipping_address_language_code);
+ shipping_address->setOrganization(test_case.m_shipping_address_organization);
+ shipping_address->setPhone(test_case.m_shipping_address_phone);
+ shipping_address->setPostalCode(test_case.m_shipping_address_postal_code);
+ shipping_address->setRecipient(test_case.m_shipping_address_recipient);
+ shipping_address->setRegion(test_case.m_shipping_address_region);
+ shipping_address->setRegionCode(test_case.m_shipping_address_region_code);
+ shipping_address->setSortingCode(test_case.m_shipping_address_sorting_code);
+
+ errors->setPayer(payer);
+ errors->setShippingAddress(shipping_address);
return errors;
}
@@ -327,7 +327,7 @@ class PaymentsErrorMessageValidatorTest
TEST_P(PaymentsErrorMessageValidatorTest,
IsValidPaymentValidationErrorsFormat) {
- PaymentValidationErrors errors = toPaymentValidationErrors(GetParam());
+ PaymentValidationErrors* errors = toPaymentValidationErrors(GetParam());
String error_message;
EXPECT_EQ(GetParam().expected_valid,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/BUILD.gn b/chromium/third_party/blink/renderer/modules/peerconnection/BUILD.gn
index 0592dce010e..0054f5936aa 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/BUILD.gn
@@ -34,12 +34,18 @@ blink_modules_sources("peerconnection") {
"adapters/quic_transport_proxy.h",
"adapters/web_rtc_cross_thread_copier.cc",
"adapters/web_rtc_cross_thread_copier.h",
+ "byte_buffer_queue.cc",
+ "byte_buffer_queue.h",
+ "call_setup_state_tracker.cc",
+ "call_setup_state_tracker.h",
"rtc_certificate.cc",
"rtc_certificate.h",
"rtc_data_channel.cc",
"rtc_data_channel.h",
"rtc_data_channel_event.cc",
"rtc_data_channel_event.h",
+ "rtc_dtls_transport.cc",
+ "rtc_dtls_transport.h",
"rtc_dtmf_sender.cc",
"rtc_dtmf_sender.h",
"rtc_dtmf_tone_change_event.cc",
@@ -54,6 +60,8 @@ blink_modules_sources("peerconnection") {
"rtc_legacy_stats_report.h",
"rtc_peer_connection.cc",
"rtc_peer_connection.h",
+ "rtc_peer_connection_controller.cc",
+ "rtc_peer_connection_controller.h",
"rtc_peer_connection_ice_event.cc",
"rtc_peer_connection_ice_event.h",
"rtc_quic_stream.cc",
@@ -72,6 +80,7 @@ blink_modules_sources("peerconnection") {
"rtc_rtp_transceiver.h",
"rtc_session_description.cc",
"rtc_session_description.h",
+ "rtc_session_description_enums.h",
"rtc_session_description_request_impl.cc",
"rtc_session_description_request_impl.h",
"rtc_session_description_request_promise_impl.cc",
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/OWNERS b/chromium/third_party/blink/renderer/modules/peerconnection/OWNERS
index 076109be5f9..347366aa979 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/OWNERS
@@ -1,6 +1,7 @@
guidou@chromium.org
hbos@chromium.org
orphis@chromium.org
+steveanton@chromium.org
tommi@chromium.org
# COMPONENT: Blink>WebRTC
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h
index 8d5f51e72cf..757ad216b9b 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h
@@ -9,6 +9,8 @@
namespace blink {
+class LocalFrame;
+
// This class creates a single concrete instance of an IceTransportAdapter with
// a hook to allow creating dependencies on the main thread (the
// IceTransportAdapter is created on the worker thread).
@@ -19,7 +21,7 @@ class IceTransportAdapterCrossThreadFactory {
virtual ~IceTransportAdapterCrossThreadFactory() = default;
// Construct any dependencies on the main thread. Can only be called once.
- virtual void InitializeOnMainThread() = 0;
+ virtual void InitializeOnMainThread(LocalFrame&) = 0;
// Construct the IceTransportAdapter instance with the given delegate. Can
// only be called once.
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.cc
index 9b0eb52ca30..9bb782218be 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.cc
@@ -19,8 +19,8 @@ class QuicPacketTransportAdapter : public P2PQuicPacketTransport,
DCHECK(p2p_transport_channel_);
p2p_transport_channel_->SignalReadPacket.connect(
this, &QuicPacketTransportAdapter::OnReadPacket);
- p2p_transport_channel_->SignalWritableState.connect(
- this, &QuicPacketTransportAdapter::OnWritableState);
+ p2p_transport_channel_->SignalReadyToSend.connect(
+ this, &QuicPacketTransportAdapter::OnReadyToSend);
}
~QuicPacketTransportAdapter() override {
@@ -62,14 +62,12 @@ class QuicPacketTransportAdapter : public P2PQuicPacketTransport,
}
receive_delegate_->OnPacketDataReceived(buffer, buffer_length);
}
- void OnWritableState(rtc::PacketTransportInternal* packet_transport) {
+ void OnReadyToSend(rtc::PacketTransportInternal* packet_transport) {
DCHECK_EQ(packet_transport, p2p_transport_channel_);
if (!write_observer_) {
return;
}
- if (p2p_transport_channel_->writable()) {
- write_observer_->OnCanWrite();
- }
+ write_observer_->OnCanWrite();
}
cricket::P2PTransportChannel* p2p_transport_channel_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_host.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_host.cc
index 5860ed120ed..a005bd4aa17 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_host.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_host.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc
index b1463372d2e..1c9dc5dd496 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc
@@ -4,15 +4,16 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_host.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
IceTransportProxy::IceTransportProxy(
- FrameScheduler* frame_scheduler,
+ LocalFrame& frame,
scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
scoped_refptr<base::SingleThreadTaskRunner> host_thread,
Delegate* delegate,
@@ -22,13 +23,13 @@ IceTransportProxy::IceTransportProxy(
host_(nullptr, base::OnTaskRunnerDeleter(host_thread_)),
delegate_(delegate),
connection_handle_for_scheduler_(
- frame_scheduler->OnActiveConnectionCreated()),
+ frame.GetFrameScheduler()->OnActiveConnectionCreated()),
weak_ptr_factory_(this) {
DCHECK(host_thread_);
DCHECK(delegate_);
DCHECK(adapter_factory);
DCHECK(proxy_thread_->BelongsToCurrentThread());
- adapter_factory->InitializeOnMainThread();
+ adapter_factory->InitializeOnMainThread(frame);
// Wait to initialize the host until the weak_ptr_factory_ is initialized.
// The IceTransportHost is constructed on the proxy thread but should only be
// interacted with via PostTask to the host thread. The OnTaskRunnerDeleter
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h
index d10b8666da0..6907f860070 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h
@@ -21,6 +21,7 @@ class Thread;
namespace blink {
class IceTransportHost;
+class LocalFrame;
class QuicTransportProxy;
// This class allows the ICE implementation (P2PTransportChannel) to run on a
@@ -60,7 +61,7 @@ class IceTransportProxy final {
// The P2PTransportChannel will be created with the given PortAllocator.
// The delegate must outlive the IceTransportProxy.
IceTransportProxy(
- FrameScheduler* frame_scheduler,
+ LocalFrame& frame,
scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
scoped_refptr<base::SingleThreadTaskRunner> host_thread,
Delegate* delegate,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream.h
index a7ae56f2261..a6d923eda71 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream.h
@@ -5,6 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_P2P_QUIC_STREAM_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_P2P_QUIC_STREAM_H_
+#include <stdint.h>
+
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
namespace blink {
// The bidirectional QUIC stream object to be used by the RTCQuicStream Web
@@ -13,7 +17,8 @@ namespace blink {
// Lifetime: The P2PQuicStream is owned by the P2PQuicTransport, and can be
// deleted after the stream is closed for reading and writing. This can happen
// in 3 ways: 1) OnRemoteReset has been fired. 2) Calling Reset(). 3) Both
-// Finish() has been called and OnRemoteFinish has been fired.
+// a FIN bit has been sent with WriteData(_, true) and OnRemoteFinish has been
+// fired.
class P2PQuicStream {
public:
// Receives callbacks for receiving RST_STREAM frames or a STREAM_FRAME with
@@ -29,15 +34,25 @@ class P2PQuicStream {
// deleted by the quic::QuicSession.
virtual void OnRemoteReset() {}
- // Called when the P2PQuicStream has consumed all incoming data from the
- // remote side up to the FIN bit. Consuming means that the data is marked
- // as consumed by quic::QuicStreamSequencer, but the data has not
- // necessarily been read by the application. If the stream has already
- // finished writing, then upon consuming the FIN bit the stream can no
- // longer read or write and is deleted by the quic::QuicSession.
- virtual void OnRemoteFinish() {}
+ // Called when the P2PQuicStream has received data from the remote side.
+ // If |fin| is set to true that means that the FIN bit has been received
+ // and the Delegate will no longer receive data with OnDataReceived.
+ // If the stream has already finished writing, then upon receiving the FIN
+ // bit the stream can no longer read or write and is deleted by the
+ // quic::QuicSession.
+ virtual void OnDataReceived(Vector<uint8_t> data, bool fin) {}
+
+ // Called when data written with WriteData() has been consumed by QUIC.
+ //
+ // This will happen immediately after calling WriteData(), unless QUIC has
+ // buffered the data in which case it will be fired when the stream is no
+ // longer write blocked and the data is consumed. |amount| specifies how
+ // much data was consumed in bytes.
+ virtual void OnWriteDataConsumed(uint32_t amount) {}
};
+ virtual ~P2PQuicStream() = default;
+
// Sends a RST_STREAM frame to the remote side. This closes the P2PQuicStream
// for reading & writing and it will be deleted by the quic::QuicSession. When
// the remote side receives the RST_STREAM frame it will close the stream for
@@ -46,18 +61,24 @@ class P2PQuicStream {
// received from the remote side, because the local stream is already closed.
virtual void Reset() = 0;
- // Sends a stream frame with the FIN bit set, which notifies the remote side
- // that this stream is done writing. The stream can no longer write after
- // calling this function. If the stream has already received a FIN bit, this
- // will close the stream for reading & writing and it will be deleted by the
- // quic::QuicSession.
- virtual void Finish() = 0;
+ // Marks received data of size |amount| as being consumed by the Delegate.
+ // This is used in conjuction with Delegate::OnDataReceived, to let the
+ // P2PQuicStream know that received data has been consumed. This allows the
+ // P2PQuicStream to send back pressure to the send side, if the Delegate
+ // cannot receive more data.
+ virtual void MarkReceivedDataConsumed(uint32_t amount) = 0;
+
+ // Writes |data| to a STREAM frame and gives it to QUIC to be buffered or sent
+ // to the remote endpoint. Once that data has been sent Delegate::OnDataSent()
+ // will be fired. Specifying |fin| to true will mark the STREAM frame with the
+ // FIN bit set, which notifies the remote side that this stream is done
+ // writing. After sending the FIN bit, the P2PQuicStream can no longer write.
+ // Once the P2PQuicStream has sent AND received the FIN bit it will be closed
+ // for reading and writing and deleted by the quic::QuicSession.
+ virtual void WriteData(Vector<uint8_t> data, bool fin) = 0;
// Sets the delegate object, which must outlive the P2PQuicStream.
virtual void SetDelegate(Delegate* delegate) = 0;
-
- // TODO:(https://crbug.com/874296): Create functions for reading and writing,
- // specifically for waitForReadable/waitForWriteable.
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.cc
index ce6c4f4fda4..a01078cee8b 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.cc
@@ -9,17 +9,83 @@
namespace blink {
P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
- quic::QuicSession* session)
- : quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL) {}
+ quic::QuicSession* session,
+ uint32_t delegate_read_buffer_size,
+ uint32_t write_buffer_size)
+ : quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL),
+ delegate_read_buffer_size_(delegate_read_buffer_size),
+ write_buffer_size_(write_buffer_size) {
+ DCHECK_GT(delegate_read_buffer_size_, 0u);
+ DCHECK_GT(write_buffer_size_, 0u);
+}
P2PQuicStreamImpl::~P2PQuicStreamImpl() {}
void P2PQuicStreamImpl::OnDataAvailable() {
- // We just drop the data by marking all data as immediately consumed.
- sequencer()->MarkConsumed(sequencer()->ReadableBytes());
- if (sequencer()->IsClosed()) {
- // This means all data has been consumed up to the FIN bit.
- OnFinRead();
+ DCHECK(delegate_);
+ if (!sequencer()->HasBytesToRead() && sequencer()->IsClosed()) {
+ // We have consumed all data from the sequencer up to the FIN bit. This can
+ // only occur by receiving an empty STREAM frame with the FIN bit set.
+ quic::QuicStream::OnFinRead();
+ delegate_->OnDataReceived({}, /*fin=*/true);
+ consumed_fin_ = true;
+ }
+
+ uint32_t delegate_read_buffer_available =
+ delegate_read_buffer_size_ - delegate_read_buffered_amount_;
+ uint32_t total_read_amount =
+ std::min(static_cast<uint32_t>(sequencer()->ReadableBytes()),
+ delegate_read_buffer_available);
+ // Nothing to do if the delegate's read buffer can't fit anymore data,
+ // or the sequencer doesn't have any data available to be read.
+ if (total_read_amount == 0 || consumed_fin_) {
+ return;
+ }
+ Vector<uint8_t> data(total_read_amount);
+ uint32_t current_data_offset = 0;
+ struct iovec iov;
+
+ // Read data from the quic::QuicStreamSequencer until we have exhausted the
+ // data, or have read at least the amount of the delegate's read buffer size.
+ while (sequencer()->GetReadableRegion(&iov)) {
+ uint32_t read_amount = static_cast<uint32_t>(iov.iov_len);
+ if (read_amount == 0) {
+ // Read everything available from the quic::QuicStreamSequencer.
+ DCHECK_EQ(current_data_offset, total_read_amount);
+ break;
+ }
+ // Limit the |consume_amount| by the amount available in the delegate's read
+ // buffer.
+ uint32_t consume_amount = std::min(
+ read_amount, delegate_read_buffer_available - current_data_offset);
+ memcpy(data.data() + current_data_offset, iov.iov_base, consume_amount);
+ sequencer()->MarkConsumed(consume_amount);
+ current_data_offset += consume_amount;
+ if (read_amount > consume_amount) {
+ // The delegate cannot store more data in its read buffer.
+ DCHECK_EQ(current_data_offset, total_read_amount);
+ break;
+ }
+ }
+
+ bool fin = !sequencer()->HasBytesToRead() && sequencer()->IsClosed();
+ delegate_read_buffered_amount_ += data.size();
+ DCHECK(delegate_read_buffer_size_ >= delegate_read_buffered_amount_);
+ if (fin) {
+ quic::QuicStream::OnFinRead();
+ consumed_fin_ = fin;
+ }
+ delegate_->OnDataReceived(std::move(data), fin);
+}
+
+void P2PQuicStreamImpl::OnStreamDataConsumed(size_t bytes_consumed) {
+ DCHECK(delegate_);
+ // We should never consume more than has been written.
+ DCHECK_GE(write_buffered_amount_, bytes_consumed);
+ QuicStream::OnStreamDataConsumed(bytes_consumed);
+ if (bytes_consumed > 0) {
+ write_buffered_amount_ -= bytes_consumed;
+ delegate_->OnWriteDataConsumed(bytes_consumed);
}
}
@@ -32,10 +98,23 @@ void P2PQuicStreamImpl::Reset() {
quic::QuicStream::Reset(quic::QuicRstStreamErrorCode::QUIC_STREAM_CANCELLED);
}
-void P2PQuicStreamImpl::Finish() {
- // Should never call Finish twice.
- DCHECK(!fin_sent());
- quic::QuicStream::WriteOrBufferData("", /*fin=*/true, nullptr);
+void P2PQuicStreamImpl::MarkReceivedDataConsumed(uint32_t amount) {
+ DCHECK_GE(delegate_read_buffered_amount_, amount);
+ delegate_read_buffered_amount_ -= amount;
+ if (sequencer()->HasBytesToRead() || !consumed_fin_) {
+ OnDataAvailable();
+ }
+}
+
+void P2PQuicStreamImpl::WriteData(Vector<uint8_t> data, bool fin) {
+ // It is up to the delegate to not write more data than the
+ // |write_buffer_size_|.
+ DCHECK_GE(write_buffer_size_, data.size() + write_buffered_amount_);
+ write_buffered_amount_ += data.size();
+ QuicStream::WriteOrBufferData(
+ quic::QuicStringPiece(reinterpret_cast<const char*>(data.data()),
+ data.size()),
+ fin, nullptr);
}
void P2PQuicStreamImpl::SetDelegate(P2PQuicStream::Delegate* delegate) {
@@ -43,8 +122,6 @@ void P2PQuicStreamImpl::SetDelegate(P2PQuicStream::Delegate* delegate) {
}
void P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
- // TODO(https://crbug.com/874296): If we get an incoming stream we need to
- // make sure that the delegate is set before we have incoming data.
DCHECK(delegate_);
// Calling this on the QuicStream will ensure that the stream is closed
// for reading and writing and we send a RST frame to the remote side if
@@ -53,14 +130,17 @@ void P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
delegate_->OnRemoteReset();
}
-void P2PQuicStreamImpl::OnFinRead() {
- // TODO(https://crbug.com/874296): If we get an incoming stream we need to
- // make sure that the delegate is set before we have incoming data.
- DCHECK(delegate_);
- // Calling this on the QuicStream ensures that the stream is closed
- // for reading.
- quic::QuicStream::OnFinRead();
- delegate_->OnRemoteFinish();
+void P2PQuicStreamImpl::OnClose() {
+ closed_ = true;
+ quic::QuicStream::OnClose();
+}
+
+bool P2PQuicStreamImpl::IsClosedForTesting() {
+ return closed_;
+}
+
+uint32_t P2PQuicStreamImpl::DelegateReadBufferedAmountForTesting() {
+ return delegate_read_buffered_amount_;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.h
index 81cb68d02d0..f4553acd8f5 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.h
@@ -14,10 +14,28 @@ namespace blink {
class MODULES_EXPORT P2PQuicStreamImpl final : public P2PQuicStream,
public quic::QuicStream {
public:
- P2PQuicStreamImpl(quic::QuicStreamId id, quic::QuicSession* session);
+ P2PQuicStreamImpl(quic::QuicStreamId id,
+ quic::QuicSession* session,
+ uint32_t delegate_read_buffer_size,
+ uint32_t write_buffer_size);
~P2PQuicStreamImpl() override;
+ // P2PQuicStream overrides
+ void SetDelegate(P2PQuicStream::Delegate* delegate) override;
+
+ void Reset() override;
+
+ void WriteData(Vector<uint8_t> data, bool fin) override;
+
+ void MarkReceivedDataConsumed(uint32_t amount) override;
- // QuicStream overrides.
+ // For testing purposes. This is returns true after quic::QuicStream::OnClose
+ bool IsClosedForTesting();
+
+ // For testing purposes. This exposes the amount of received data that the
+ // P2PQuicStream is aware is buffered by the delegate.
+ uint32_t DelegateReadBufferedAmountForTesting();
+
+ // quic::QuicStream overrides.
//
// Right now this marks the data as consumed and drops it.
// TODO(https://crbug.com/874296): We need to update this function for
@@ -25,31 +43,54 @@ class MODULES_EXPORT P2PQuicStreamImpl final : public P2PQuicStream,
// busy. See:
// https://w3c.github.io/webrtc-quic/#dom-rtcquicstream-waitforreadable
void OnDataAvailable() override;
-
- // P2PQuicStream overrides
- void SetDelegate(P2PQuicStream::Delegate* delegate) override;
-
- void Reset() override;
-
- void Finish() override;
-
- // quic::QuicStream overrides
- //
// Called by the quic::QuicSession when receiving a RST_STREAM frame from the
// remote side. This closes the stream for reading & writing (if not already
// closed), and sends a RST_STREAM frame if one has not been sent yet.
void OnStreamReset(const quic::QuicRstStreamFrame& frame) override;
+ // Called by the quic::QuicSession. This means the stream is closed for
+ // reading
+ // and writing, and can now be deleted by the quic::QuicSession.
+ void OnClose() override;
- // Called when the stream has finished consumed data up to the FIN bit from
- // the quic::QuicStreamSequencer. This will close the underlying QuicStream
- // for reading. This can be called either by the P2PQuicStreamImpl when
- // reading data, or by the quic::QuicStreamSequencer if we're done reading &
- // receive a stream frame with the FIN bit.
- void OnFinRead() override;
+ protected:
+ // quic::QuicStream overrides.
+ //
+ // Called when written data (from WriteData()) is consumed by QUIC. This means
+ // the data has either been sent across the wire, or it has been turned into a
+ // packet and queued if the socket is unexpectedly blocked.
+ void OnStreamDataConsumed(size_t bytes_consumed) override;
private:
using quic::QuicStream::Reset;
+
+ // Outlives the P2PQuicStreamImpl.
Delegate* delegate_;
+
+ // The read buffer size of the delegate. The |delegate_read_buffered_amount_|
+ // must never exceed this value (enforced by the P2PQuicStreamImpl).
+ const uint32_t delegate_read_buffer_size_;
+ // The maximum size allowed to be buffered write side. The
+ // |write_buffered_amount_| must never exceed this value, and it is up
+ // to the delegate to enforce this.
+ const uint32_t write_buffer_size_;
+ // How much total data has been received and given to the delegate,
+ // but not yet consumed by the delegate. This value gets increased when data
+ // is received from the QUIC library in OnDataAvailable() and and decreased
+ // when the delegate updates that data has been read with
+ // MarkReceivedDataConsumed().
+ uint32_t delegate_read_buffered_amount_ = 0;
+ // How much data is buffered by the QUIC library, but has not yet
+ // been sent. This value gets increased when WriteData() is called
+ // and decreased when OnDataConsumed() gets called by the QUIC library,
+ // due to the data being sent.
+ uint32_t write_buffered_amount_ = 0;
+
+ // Set after OnClose gets called.
+ bool closed_ = false;
+
+ // This is set after the sequencer is closed due to the P2PQuicStream
+ // consuming all of the sequencer's data up to the FIN bit.
+ bool consumed_fin_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_unittest.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_unittest.cc
new file mode 100644
index 00000000000..0a36ce345dc
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_unittest.cc
@@ -0,0 +1,442 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream.h"
+#include "net/test/gtest_util.h"
+#include "net/third_party/quic/core/quic_data_writer.h"
+#include "net/third_party/quic/test_tools/quic_test_utils.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_stream_impl.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/test/mock_p2p_quic_stream_delegate.h"
+
+namespace blink {
+
+namespace {
+
+using testing::_;
+using testing::ElementsAre;
+using testing::ElementsAreArray;
+using testing::Invoke;
+using testing::InvokeWithoutArgs;
+
+const uint32_t kDefaultStreamWriteBufferSize = 1024;
+const uint32_t kDefaultStreamDelegateReadBufferSize = 1024;
+const quic::QuicStreamId kStreamId = 5;
+const uint8_t kSomeData[] = {'h', 'o', 'w', 'd', 'y'};
+const uint8_t kMoreData[] = {'m', 'o', 'r', 'e'};
+
+} // namespace
+
+// Unit tests for the P2PQuicStream, using a mock QuicSession, which allows
+// us to isolate testing the behaviors of reading a writing.
+class P2PQuicStreamTest : public testing::Test {
+ public:
+ P2PQuicStreamTest()
+ : connection_(
+ new quic::test::MockQuicConnection(&connection_helper_,
+ &alarm_factory_,
+ quic::Perspective::IS_CLIENT)),
+ session_(connection_) {
+ session_.Initialize();
+ // DCHECKS get hit when the clock is at 0.
+ connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
+ }
+
+ ~P2PQuicStreamTest() override {}
+
+ void InitializeStream(
+ uint32_t delegate_read_buffer_size = kDefaultStreamDelegateReadBufferSize,
+ uint32_t write_buffer_size = kDefaultStreamWriteBufferSize) {
+ stream_ = new P2PQuicStreamImpl(
+ kStreamId, &session_, delegate_read_buffer_size, write_buffer_size);
+ stream_->SetDelegate(&delegate_);
+ // The session takes the ownership of the stream.
+ session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
+ }
+
+ template <wtf_size_t Size>
+ static quic::QuicStringPiece StringPieceFromArray(
+ const uint8_t (&array)[Size]) {
+ return quic::QuicStringPiece(reinterpret_cast<const char*>(array), Size);
+ }
+
+ template <wtf_size_t Size>
+ static Vector<uint8_t> VectorFromArray(const uint8_t (&array)[Size]) {
+ Vector<uint8_t> vector;
+ vector.Append(array, Size);
+ return vector;
+ }
+
+ quic::test::MockQuicConnectionHelper connection_helper_;
+ quic::test::MockAlarmFactory alarm_factory_;
+ // Owned by the |session_|.
+ quic::test::MockQuicConnection* connection_;
+ // The MockQuicSession allows us to see data that is being written and control
+ // whether the data is being "sent across" or blocked.
+ quic::test::MockQuicSession session_;
+ MockP2PQuicStreamDelegate delegate_;
+ // Owned by |session_|.
+ P2PQuicStreamImpl* stream_;
+};
+
+TEST_F(P2PQuicStreamTest, StreamSendsFinAndCanNoLongerWrite) {
+ InitializeStream();
+ EXPECT_CALL(session_, WritevData(stream_, kStreamId, _, _, _))
+ .WillOnce(Invoke(quic::test::MockQuicSession::ConsumeData));
+
+ stream_->WriteData({}, /*fin=*/true);
+
+ EXPECT_TRUE(stream_->fin_sent());
+ EXPECT_TRUE(stream_->write_side_closed());
+ EXPECT_FALSE(stream_->reading_stopped());
+}
+
+TEST_F(P2PQuicStreamTest, StreamResetSendsRst) {
+ InitializeStream();
+ EXPECT_CALL(session_, SendRstStream(kStreamId, _, _));
+ stream_->Reset();
+ EXPECT_TRUE(stream_->rst_sent());
+}
+
+// Tests that when a stream receives a stream frame with the FIN bit set it
+// will fire the appropriate callback and close the stream for reading.
+TEST_F(P2PQuicStreamTest, StreamOnStreamFrameWithFin) {
+ InitializeStream();
+ EXPECT_CALL(delegate_, OnDataReceived(_, /*fin=*/true));
+
+ quic::QuicStreamFrame fin_frame(kStreamId, /*fin=*/true, 0, 0);
+ stream_->OnStreamFrame(fin_frame);
+
+ EXPECT_TRUE(stream_->reading_stopped());
+ EXPECT_FALSE(stream_->write_side_closed());
+}
+
+// Tests that when a stream receives a stream frame with the FIN bit set after
+// it has written the FIN bit, then the stream will close.
+TEST_F(P2PQuicStreamTest, StreamClosedAfterSendingThenReceivingFin) {
+ InitializeStream();
+ EXPECT_CALL(session_, WritevData(stream_, kStreamId, _, _, _))
+ .WillOnce(Invoke(quic::test::MockQuicSession::ConsumeData));
+ stream_->WriteData({}, /*fin=*/true);
+ EXPECT_FALSE(stream_->IsClosedForTesting());
+
+ quic::QuicStreamFrame fin_frame(stream_->id(), /*fin=*/true, 0, 0);
+ stream_->OnStreamFrame(fin_frame);
+
+ EXPECT_TRUE(stream_->reading_stopped());
+ EXPECT_TRUE(stream_->write_side_closed());
+ EXPECT_TRUE(stream_->IsClosedForTesting());
+}
+
+// Tests that when a stream writes a FIN bit after receiving a stream frame with
+// the FIN bit then the stream will close.
+TEST_F(P2PQuicStreamTest, StreamClosedAfterReceivingThenSendingFin) {
+ InitializeStream();
+ quic::QuicStreamFrame fin_frame(stream_->id(), /*fin=*/true, 0, 0);
+ stream_->OnStreamFrame(fin_frame);
+ EXPECT_FALSE(stream_->IsClosedForTesting());
+
+ EXPECT_CALL(session_, WritevData(stream_, kStreamId, _, _, _))
+ .WillOnce(Invoke(quic::test::MockQuicSession::ConsumeData));
+
+ stream_->WriteData({}, /*fin=*/true);
+
+ EXPECT_TRUE(stream_->IsClosedForTesting());
+}
+
+// Tests that when a stream writes some data with the FIN bit set, and receives
+// data with the FIN bit set it will become closed.
+TEST_F(P2PQuicStreamTest, StreamClosedAfterWritingAndReceivingDataWithFin) {
+ InitializeStream();
+ EXPECT_CALL(session_,
+ WritevData(stream_, kStreamId,
+ /*write_length=*/base::size(kSomeData), _, _))
+ .WillOnce(Invoke(quic::test::MockQuicSession::ConsumeData));
+ stream_->WriteData(VectorFromArray(kSomeData),
+ /*fin=*/true);
+ EXPECT_FALSE(stream_->IsClosedForTesting());
+
+ quic::QuicStreamFrame fin_frame_with_data(stream_->id(), /*fin=*/true, 0,
+ StringPieceFromArray(kSomeData));
+ stream_->OnStreamFrame(fin_frame_with_data);
+
+ EXPECT_TRUE(stream_->reading_stopped());
+ EXPECT_TRUE(stream_->write_side_closed());
+ EXPECT_TRUE(stream_->IsClosedForTesting());
+}
+
+// Tests that when a stream receives a RST_STREAM frame it will fire the
+// appropriate callback and the stream will become closed.
+TEST_F(P2PQuicStreamTest, StreamClosedAfterReceivingReset) {
+ InitializeStream();
+ EXPECT_CALL(delegate_, OnRemoteReset());
+
+ quic::QuicRstStreamFrame rst_frame(quic::kInvalidControlFrameId, kStreamId,
+ quic::QUIC_STREAM_CANCELLED, 0);
+ stream_->OnStreamReset(rst_frame);
+
+ EXPECT_TRUE(stream_->IsClosedForTesting());
+}
+
+// Tests that data written to the P2PQuicStream will appropriately get written
+// to the underlying QUIC library.
+TEST_F(P2PQuicStreamTest, StreamWritesData) {
+ InitializeStream();
+ EXPECT_CALL(session_,
+ WritevData(stream_, kStreamId,
+ /*write_length=*/base::size(kSomeData), _, _))
+ .WillOnce(Invoke([](quic::QuicStream* stream, quic::QuicStreamId id,
+ size_t write_length, quic::QuicStreamOffset offset,
+ quic::StreamSendingState state) {
+ // quic::QuicSession::WritevData does not pass the data. The data is
+ // saved to the stream, so we must grab it before it's consumed, in
+ // order to check that it's what was written.
+ std::string data_consumed_by_quic(write_length, 'a');
+ quic::QuicDataWriter writer(write_length, &data_consumed_by_quic[0],
+ quic::NETWORK_BYTE_ORDER);
+ stream->WriteStreamData(offset, write_length, &writer);
+
+ EXPECT_THAT(data_consumed_by_quic, ElementsAreArray(kSomeData));
+ EXPECT_EQ(quic::StreamSendingState::NO_FIN, state);
+ return quic::QuicConsumedData(
+ write_length, state != quic::StreamSendingState::NO_FIN);
+ }));
+ EXPECT_CALL(delegate_, OnWriteDataConsumed(base::size(kSomeData)));
+
+ stream_->WriteData(VectorFromArray(kSomeData), /*fin=*/false);
+}
+
+// Tests that data written to the P2PQuicStream will appropriately get written
+// to the underlying QUIC library with the FIN bit set.
+TEST_F(P2PQuicStreamTest, StreamWritesDataWithFin) {
+ InitializeStream();
+ EXPECT_CALL(session_,
+ WritevData(stream_, kStreamId,
+ /*write_length=*/base::size(kSomeData), _, _))
+ .WillOnce(Invoke([](quic::QuicStream* stream, quic::QuicStreamId id,
+ size_t write_length, quic::QuicStreamOffset offset,
+ quic::StreamSendingState state) {
+ // WritevData does not pass the data. The data is saved to the stream,
+ // so we must grab it before it's consumed, in order to check that it's
+ // what was written.
+ std::string data_consumed_by_quic(write_length, 'a');
+ quic::QuicDataWriter writer(write_length, &data_consumed_by_quic[0],
+ quic::NETWORK_BYTE_ORDER);
+ stream->WriteStreamData(offset, write_length, &writer);
+
+ EXPECT_THAT(data_consumed_by_quic, ElementsAreArray(kSomeData));
+ EXPECT_EQ(quic::StreamSendingState::FIN, state);
+ return quic::QuicConsumedData(
+ write_length, state != quic::StreamSendingState::NO_FIN);
+ }));
+ EXPECT_CALL(delegate_, OnWriteDataConsumed(base::size(kSomeData)));
+
+ stream_->WriteData(VectorFromArray(kSomeData), /*fin=*/true);
+}
+
+// Tests that when written data is not consumed by QUIC (due to buffering),
+// the OnWriteDataConsumed will not get fired.
+TEST_F(P2PQuicStreamTest, StreamWritesDataAndNotConsumedByQuic) {
+ InitializeStream();
+ EXPECT_CALL(delegate_, OnWriteDataConsumed(_)).Times(0);
+ EXPECT_CALL(session_,
+ WritevData(stream_, kStreamId,
+ /*write_length=*/base::size(kSomeData), _, _))
+ .WillOnce(Invoke([](quic::QuicStream* stream, quic::QuicStreamId id,
+ size_t write_length, quic::QuicStreamOffset offset,
+ quic::StreamSendingState state) {
+ // We mock that the QUIC library is not consuming the data, meaning it's
+ // being buffered. In this case, the OnWriteDataConsumed() callback
+ // should not be called.
+ return quic::QuicConsumedData(/*bytes_consumed=*/0,
+ quic::StreamSendingState::NO_FIN);
+ }));
+
+ stream_->WriteData(VectorFromArray(kSomeData), /*fin=*/true);
+}
+
+// Tests that OnWriteDataConsumed() is fired with the amount consumed by QUIC.
+// This tests the case when amount consumed by QUIC is less than what is written
+// with P2PQuicStream::WriteData. This can happen when QUIC is receiving back
+// pressure from the receive side, and its "send window" is smaller than the
+// amount attempted to be written.
+TEST_F(P2PQuicStreamTest, StreamWritesDataAndPartiallyConsumedByQuic) {
+ InitializeStream();
+ size_t amount_consumed_by_quic = 2;
+ EXPECT_CALL(delegate_, OnWriteDataConsumed(amount_consumed_by_quic));
+ EXPECT_CALL(session_,
+ WritevData(stream_, kStreamId,
+ /*write_length=*/base::size(kSomeData), _, _))
+ .WillOnce(Invoke([&amount_consumed_by_quic](
+ quic::QuicStream* stream, quic::QuicStreamId id,
+ size_t write_length, quic::QuicStreamOffset offset,
+ quic::StreamSendingState state) {
+ // We mock that the QUIC library is only consuming some of the data,
+ // meaning the rest is being buffered.
+ return quic::QuicConsumedData(
+ /*bytes_consumed=*/amount_consumed_by_quic,
+ quic::StreamSendingState::NO_FIN);
+ }));
+
+ stream_->WriteData(VectorFromArray(kSomeData), /*fin=*/true);
+}
+
+// Tests if a P2PQuicStream receives data it will appropriately fire the
+// OnDataReceived callback to the delegate.
+TEST_F(P2PQuicStreamTest, StreamReceivesData) {
+ InitializeStream();
+ quic::QuicStreamFrame stream_frame(stream_->id(), /*fin=*/false, 0,
+ StringPieceFromArray(kSomeData));
+
+ EXPECT_CALL(delegate_, OnDataReceived(VectorFromArray(kSomeData),
+ /*fin=*/false));
+
+ stream_->OnStreamFrame(stream_frame);
+}
+
+// Tests that when received data is marked consumed it is appropriately
+// reflected in the P2PQuicStream's view of the delegate read buffer size.
+TEST_F(P2PQuicStreamTest, MarkConsumedData) {
+ InitializeStream();
+ quic::QuicStreamFrame stream_frame(stream_->id(), /*fin=*/false, 0,
+ StringPieceFromArray(kSomeData));
+
+ EXPECT_CALL(delegate_, OnDataReceived(_, _));
+ stream_->OnStreamFrame(stream_frame);
+ // At this point the application has received data but not marked is as
+ // consumed, so from the P2PQuicStream perspective that data has been
+ // buffered.
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+
+ stream_->MarkReceivedDataConsumed(base::size(kSomeData));
+ EXPECT_EQ(0u, stream_->DelegateReadBufferedAmountForTesting());
+}
+
+// Tests that if the delegate's read buffer is "full" from the
+// P2PQuicStream's perspective, then getting more data will not fire the
+// OnDataReceived callback.
+TEST_F(P2PQuicStreamTest, StreamReceivesDataWithFullReadBuffer) {
+ // The P2PQuicStream is created with a delegate read buffer size equal
+ // to the size of the data that is being received.
+ InitializeStream(/*delegate_read_buffer_size=*/base::size(kSomeData));
+ quic::QuicStreamFrame stream_frame(stream_->id(), /*fin=*/false, 0,
+ StringPieceFromArray(kSomeData));
+
+ EXPECT_CALL(delegate_, OnDataReceived(_, _)).Times(1);
+ stream_->OnStreamFrame(stream_frame);
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+
+ // Delegate read buffer is now full. Receiving more data should not fire the
+ // callback.
+ quic::QuicStreamFrame new_stream_frame(stream_->id(), /*fin=*/false,
+ /*offset=*/base::size(kSomeData),
+ StringPieceFromArray(kMoreData));
+ stream_->OnStreamFrame(new_stream_frame);
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+}
+
+// Tests that if the delegate's read buffer is "full" from the
+// P2PQuicStream's perspective, and then getting an empty STREAM frame with the
+// FIN bit set, will fire Delegate::OnDataReceived with fin set to true.
+TEST_F(P2PQuicStreamTest, StreamReceivesFinWithFullReadBuffer) {
+ // The P2PQuicStream is created with a delegate read buffer size equal
+ // to the size of the data that is being received.
+ InitializeStream(/*delegate_read_buffer_size=*/base::size(kSomeData));
+ quic::QuicStreamFrame stream_frame(stream_->id(), /*fin=*/false, 0,
+ StringPieceFromArray(kSomeData));
+
+ EXPECT_CALL(delegate_, OnDataReceived(ElementsAreArray(kSomeData),
+ /*fin=*/false))
+ .Times(1);
+ stream_->OnStreamFrame(stream_frame);
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+
+ // Delegate read buffer is now full, but because the STREAM frame with the FIN
+ // bit doesn't contain any data, it means that all data has been consumed from
+ // the sequencer up to the FIN bit. This fires OnDataReceived with the
+ // fin=true.
+ EXPECT_CALL(delegate_, OnDataReceived(_, true)).Times(1);
+ quic::QuicStreamFrame new_stream_frame(stream_->id(), /*fin=*/true,
+ /*offset=*/base::size(kSomeData), 0);
+ stream_->OnStreamFrame(new_stream_frame);
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+}
+
+// Tests that when the delegate's read buffer is "full" from the
+// P2PQuicStream's perspective, the Delegate::OnDataReceived callback is
+// fired after the received data is marked as consumed by the delegate.
+TEST_F(P2PQuicStreamTest, StreamDataConsumedWithFullDelegateReadBuffer) {
+ // The P2PQuicStream is created with a delegate read buffer size equal
+ // to the size of the data that is being received.
+ InitializeStream(/*delegate_read_buffer_size=*/base::size(kSomeData));
+ quic::QuicStreamFrame stream_frame(stream_->id(), /*fin=*/false, 0,
+ StringPieceFromArray(kSomeData));
+
+ EXPECT_CALL(delegate_, OnDataReceived(ElementsAreArray(kSomeData),
+ /*fin=*/false))
+ .Times(1);
+ stream_->OnStreamFrame(stream_frame);
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+
+ // Delegate read buffer is now full. Receiving more data should not fire the
+ // callback.
+ quic::QuicStreamFrame new_stream_frame(stream_->id(), /*fin=*/true,
+ /*offset=*/base::size(kSomeData),
+ StringPieceFromArray(kMoreData));
+ stream_->OnStreamFrame(new_stream_frame);
+ EXPECT_EQ(base::size(kSomeData),
+ stream_->DelegateReadBufferedAmountForTesting());
+
+ // Marking the original data as consumed should fire the new data to be
+ // received.
+ EXPECT_CALL(delegate_, OnDataReceived(ElementsAreArray(kMoreData),
+ /*fin=*/true))
+ .Times(1);
+ stream_->MarkReceivedDataConsumed(base::size(kSomeData));
+ EXPECT_EQ(base::size(kMoreData),
+ stream_->DelegateReadBufferedAmountForTesting());
+}
+
+// Tests that when receiving more data than available in the delegate read
+// buffer, that the delegate will get an OnDataReceived callback for the amount
+// available in its buffer. Then later when the delegate marks the data as
+// consumed it will get another OnDataReceived callback.
+TEST_F(P2PQuicStreamTest, StreamReceivesMoreDataThanDelegateReadBufferSize) {
+ const uint8_t kData[] = {'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'};
+ // The P2PQuicStream is created with a delegate read buffer size equal
+ // to half of the data being sent.
+ InitializeStream(/*delegate_read_buffer_size=*/4);
+ quic::QuicStreamFrame stream_frame(stream_->id(), /*fin=*/true, 0,
+ StringPieceFromArray(kData));
+
+ // Upon receiving the stream frame the Delegate should receive "some", because
+ // that's all it has space to buffer.
+ EXPECT_CALL(delegate_, OnDataReceived(ElementsAre('s', 'o', 'm', 'e'),
+ /*fin=*/false))
+ .Times(1);
+ stream_->OnStreamFrame(stream_frame);
+ EXPECT_EQ(4u, stream_->DelegateReadBufferedAmountForTesting());
+
+ // Upon consuming 2 bytes of data, the delegate should receive the next part
+ // of the message - "da".
+ EXPECT_CALL(delegate_, OnDataReceived(ElementsAre('d', 'a'), /*fin=*/false))
+ .Times(1);
+ stream_->MarkReceivedDataConsumed(2);
+ EXPECT_EQ(4u, stream_->DelegateReadBufferedAmountForTesting());
+
+ // After consuming 4 bytes of data (all received data thus far), the delegate
+ // should receive the next part of the message - "ta" and the FIN bit.
+ EXPECT_CALL(delegate_, OnDataReceived(ElementsAre('t', 'a'), /*fin=*/true))
+ .Times(1);
+ stream_->MarkReceivedDataConsumed(4);
+ // Just the last data received ("ta") is held in the delegate's read buffer.
+ EXPECT_EQ(2u, stream_->DelegateReadBufferedAmountForTesting());
+}
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h
index a6c67feb4d8..1d9b695c330 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h
@@ -13,44 +13,44 @@
namespace blink {
-// A simple config object for creating a P2PQuicTransport. It's constructor
-// guarantees that the required objects for creating a P2PQuicTransport are part
-// of the P2PQuicTransportConfig.
+// A simple config object for creating a P2PQuicTransport. Its constructor
+// guarantees that the required configuration for creating a P2PQuicTransport
+// are part of the P2PQuicTransportConfig.
struct P2PQuicTransportConfig final {
// This object is only moveable.
explicit P2PQuicTransportConfig(
- P2PQuicTransport::Delegate* const delegate_in,
- P2PQuicPacketTransport* const packet_transport_in,
+ quic::Perspective perspective,
const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>
- certificates_in)
- : packet_transport(packet_transport_in),
+ certificates_in,
+ uint32_t stream_delegate_read_buffer_size_in,
+ uint32_t stream_write_buffer_size_in)
+ : perspective(perspective),
certificates(certificates_in),
- delegate(delegate_in) {
+ stream_delegate_read_buffer_size(stream_delegate_read_buffer_size_in),
+ stream_write_buffer_size(stream_write_buffer_size_in) {
DCHECK_GT(certificates.size(), 0u);
- DCHECK(packet_transport);
- DCHECK(delegate);
+ DCHECK_GT(stream_delegate_read_buffer_size, 0u);
+ DCHECK_GT(stream_write_buffer_size, 0u);
}
- P2PQuicTransportConfig(const P2PQuicTransportConfig&) = delete;
- P2PQuicTransportConfig& operator=(const P2PQuicTransportConfig&) = delete;
- P2PQuicTransportConfig(P2PQuicTransportConfig&&) = default;
- P2PQuicTransportConfig& operator=(P2PQuicTransportConfig&&) = delete;
- ~P2PQuicTransportConfig() = default;
- // The standard case is an ICE transport. It's lifetime will be managed by
- // the ICE transport objects and outlive the P2PQuicTransport.
- P2PQuicPacketTransport* const packet_transport;
- bool is_server = true;
+ // Client or server.
+ quic::Perspective perspective;
// The certificates are owned by the P2PQuicTransport. These come from
// blink::RTCCertificates: https://www.w3.org/TR/webrtc/#dom-rtccertificate
const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
- // Mandatory for creating a P2PQuicTransport and must outlive
- // the P2PQuicTransport. In the standard case the |delegate_| will be
- // the object that owns the P2PQuicTransport.
- P2PQuicTransport::Delegate* const delegate;
// When set to true the P2PQuicTransport will immediately be able
// to listen and respond to a crypto handshake upon construction.
// This will NOT start a handshake.
bool can_respond_to_crypto_handshake = true;
+ // The amount that the delegate can store in its read buffer. This is a
+ // mandatory field that must be set to ensure that the
+ // P2PQuicStream::Delegate will not give the delegate more data than it can
+ // store.
+ const uint32_t stream_delegate_read_buffer_size;
+ // The amount that the P2PQuicStream will allow to buffer. This is a mandatory
+ // field that must be set to ensure that the client of the P2PQuicStream does
+ // not write more data than can be buffered.
+ const uint32_t stream_write_buffer_size;
};
// For creating a P2PQuicTransport. This factory should be injected into
@@ -64,8 +64,14 @@ class P2PQuicTransportFactory {
// Creates the P2PQuicTransport. This should be called on the same
// thread that the P2PQuicTransport will be used on.
+ // |delegate| receives callbacks from the P2PQuicTransport on the same thread.
+ // It must outlive the P2PQuicTransport.
+ // |packet_transport| is used to send and receive UDP packets. It must outlive
+ // the P2PQuicTransport.
virtual std::unique_ptr<P2PQuicTransport> CreateQuicTransport(
- P2PQuicTransportConfig config) = 0;
+ P2PQuicTransport::Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& config) = 0;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.cc
index 73e4c3a649a..532871719bd 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.cc
@@ -140,15 +140,13 @@ class P2PQuicPacketWriter : public quic::QuicPacketWriter,
// using the QuicTransportConfig::packet_transport for writing. The |helper|
// and |alarm_factory| should be chromium specific implementations.
std::unique_ptr<quic::QuicConnection> CreateQuicConnection(
- bool is_server,
+ quic::Perspective perspective,
quic::QuicConnectionHelperInterface* helper,
quic::QuicPacketWriter* packet_writer,
quic::QuicAlarmFactory* alarm_factory) {
quic::QuicIpAddress ip;
ip.FromString("0.0.0.0");
quic::QuicSocketAddress dummy_address(ip, 0 /* Port */);
- quic::Perspective perspective =
- is_server ? quic::Perspective::IS_SERVER : quic::Perspective::IS_CLIENT;
return std::make_unique<quic::QuicConnection>(
0 /* dummy ID */, dummy_address, helper, alarm_factory, packet_writer,
/* owns_writer */ true, perspective, quic::CurrentSupportedVersions());
@@ -166,9 +164,12 @@ P2PQuicTransportFactoryImpl::P2PQuicTransportFactoryImpl(
// QuicClock, QuicRandom, QuicConnectionHelper and QuicAlarmFactory.
std::unique_ptr<P2PQuicTransport>
P2PQuicTransportFactoryImpl::CreateQuicTransport(
- P2PQuicTransportConfig config) {
- DCHECK(config.packet_transport);
+ P2PQuicTransport::Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& config) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(delegate);
+ DCHECK(packet_transport);
quic::QuicRandom* quic_random = quic::QuicRandom::GetInstance();
// The P2PQuicSession owns these chromium specific objects required
@@ -177,9 +178,9 @@ P2PQuicTransportFactoryImpl::CreateQuicTransport(
std::make_unique<net::QuicChromiumConnectionHelper>(clock_, quic_random);
P2PQuicPacketWriter* packet_writer =
- new P2PQuicPacketWriter(config.packet_transport);
+ new P2PQuicPacketWriter(packet_transport);
std::unique_ptr<quic::QuicConnection> quic_connection = CreateQuicConnection(
- config.is_server, helper.get(), packet_writer, alarm_factory_.get());
+ config.perspective, helper.get(), packet_writer, alarm_factory_.get());
// It's okay for the quic::QuicConnection to have a P2PQuicPacketWriter before
// the P2PQuicPacketWriter is initialized, because the P2QuicPacketWriter
// won't be writable until this occurs.
@@ -188,7 +189,7 @@ P2PQuicTransportFactoryImpl::CreateQuicTransport(
// QUIC configurations for the session are specified here.
quic::QuicConfig quic_config;
return std::make_unique<P2PQuicTransportImpl>(
- std::move(config), std::move(helper), std::move(quic_connection),
- quic_config, clock_);
+ delegate, packet_transport, std::move(config), std::move(helper),
+ std::move(quic_connection), quic_config, clock_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.h
index 6bc83546ab8..34830ed00f0 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.h
@@ -26,7 +26,9 @@ class MODULES_EXPORT P2PQuicTransportFactoryImpl final
// QuicTransportFactoryInterface override.
std::unique_ptr<P2PQuicTransport> CreateQuicTransport(
- P2PQuicTransportConfig config) override;
+ P2PQuicTransport::Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& config) override;
private:
// This is used to create a QuicChromiumConnectionHelper for the session.
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.cc
index fe216c251e0..47c2b2ceebc 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.cc
@@ -135,24 +135,32 @@ class DummyCryptoServerStreamHelper
} // namespace
P2PQuicTransportImpl::P2PQuicTransportImpl(
- P2PQuicTransportConfig p2p_transport_config,
+ Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
- : quic::QuicSession(connection.get(), nullptr /* visitor */, quic_config),
+ : quic::QuicSession(connection.get(),
+ nullptr /* visitor */,
+ quic_config,
+ quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
- perspective_(p2p_transport_config.is_server
- ? quic::Perspective::IS_SERVER
- : quic::Perspective::IS_CLIENT),
- packet_transport_(p2p_transport_config.packet_transport),
- delegate_(p2p_transport_config.delegate),
- clock_(clock) {
+ perspective_(p2p_transport_config.perspective),
+ packet_transport_(packet_transport),
+ delegate_(delegate),
+ clock_(clock),
+ stream_delegate_read_buffer_size_(
+ p2p_transport_config.stream_delegate_read_buffer_size),
+ stream_write_buffer_size_(p2p_transport_config.stream_write_buffer_size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
+ DCHECK_GT(stream_delegate_read_buffer_size_, 0u);
+ DCHECK_GT(stream_write_buffer_size_, 0u);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
@@ -232,12 +240,7 @@ P2PQuicStreamImpl* P2PQuicTransportImpl::CreateOutgoingBidirectionalStream() {
return stream;
}
-P2PQuicStreamImpl* P2PQuicTransportImpl::CreateOutgoingUnidirectionalStream() {
- DCHECK(false);
- return nullptr;
-}
-
-P2PQuicStreamImpl* P2PQuicTransportImpl::CreateIncomingDynamicStream(
+P2PQuicStreamImpl* P2PQuicTransportImpl::CreateIncomingStream(
quic::QuicStreamId id) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
P2PQuicStreamImpl* stream = CreateStreamInternal(id);
@@ -252,7 +255,8 @@ P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal(
DCHECK(crypto_stream_);
DCHECK(IsEncryptionEstablished());
DCHECK(!IsClosed());
- return new P2PQuicStreamImpl(id, this);
+ return new P2PQuicStreamImpl(id, this, stream_delegate_read_buffer_size_,
+ stream_write_buffer_size_);
}
void P2PQuicTransportImpl::InitializeCryptoStream() {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.h
index 609f223cc98..4eeeaee9930 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.h
@@ -44,7 +44,9 @@ class MODULES_EXPORT P2PQuicTransportImpl final
public quic::QuicCryptoClientStream::ProofHandler {
public:
P2PQuicTransportImpl(
- P2PQuicTransportConfig p2p_transport_config,
+ Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
@@ -104,14 +106,13 @@ class MODULES_EXPORT P2PQuicTransportImpl final
// Creates a new stream initiated from the remote side. The caller does not
// own the stream, so the stream is activated and ownership is moved to the
// quic::QuicSession.
- P2PQuicStreamImpl* CreateIncomingDynamicStream(
+ P2PQuicStreamImpl* CreateIncomingStream(
quic::QuicStreamId id) override;
// Creates a new outgoing stream. The caller does not own the
// stream, so the stream is activated and ownership is moved to the
// quic::QuicSession.
- P2PQuicStreamImpl* CreateOutgoingBidirectionalStream() override;
- P2PQuicStreamImpl* CreateOutgoingUnidirectionalStream() override;
+ P2PQuicStreamImpl* CreateOutgoingBidirectionalStream();
void OnCryptoHandshakeEvent(CryptoHandshakeEvent event) override;
@@ -171,6 +172,11 @@ class MODULES_EXPORT P2PQuicTransportImpl final
// Owned by whatever creates the P2PQuicTransportImpl. The |clock_| needs to
// outlive the P2PQuicTransportImpl.
quic::QuicClock* clock_ = nullptr;
+ // The size of the stream delegate's read buffer, used when creating
+ // P2PQuicStreams.
+ uint32_t stream_delegate_read_buffer_size_;
+ // Determines the size of the write buffer when P2PQuicStreams.
+ uint32_t stream_write_buffer_size_;
THREAD_CHECKER(thread_checker_);
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_test.cc
index c889ea9d2a2..e126df37213 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_test.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_test.cc
@@ -10,6 +10,8 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_packet_transport.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory_impl.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_impl.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/test/mock_p2p_quic_stream_delegate.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/test/mock_p2p_quic_transport_delegate.h"
#include "third_party/webrtc/rtc_base/rtccertificate.h"
#include "third_party/webrtc/rtc_base/sslfingerprint.h"
#include "third_party/webrtc/rtc_base/sslidentity.h"
@@ -18,133 +20,86 @@ namespace blink {
namespace {
-// The types of callbacks that can be fired on a P2PQuicTransport::Delegate.
-enum class TransportCallbackType {
- kNone,
- kOnRemoteStopped,
- kOnConnectionFailed,
- kOnConnected,
- kOnStream
-};
-
-// The types of callbacks that can be fired on a P2PQuicStream::Delegate.
-enum class StreamCallbackType { kNone, kOnRemoteReset, kOnRemoteFinish };
-
-// The QuicStreamDelegate implements counters for callbacks. It can also set
-// expectations for a specific callback. When an expectation is set the
-// quic::TestTaskRunner drives the test until the callbacks have been fired, and
-// we are no longer expecting the callback.
-class QuicStreamDelegateForTesting final : public P2PQuicStream::Delegate {
+using testing::_;
+using testing::ElementsAreArray;
+using testing::Invoke;
+using testing::InvokeWithoutArgs;
+using ::testing::MakePolymorphicAction;
+using ::testing::PolymorphicAction;
+
+const uint8_t kTriggerRemoteStreamPhrase[] = {'o', 'p', 'e', 'n', ' ', 's',
+ 'e', 's', 'a', 'm', 'e'};
+const uint32_t kTransportWriteBufferSize = 100 * 1024;
+const uint32_t kTransportDelegateReadBufferSize = 100 * 1024;
+
+// A custom gmock Action that fires the given callback. This is used in
+// conjuction with the CallbackRunLoop in order to drive the TestTaskRunner
+// until callbacks are fired. For example:
+// CallbackRunLoop run_loop(runner());
+// EXPECT_CALL(&object, foo())
+// .WillOnce(FireCallback(run_loop.CreateCallback()));
+// run_loop.RunUntilCallbacksFired(task_runner);
+class FireCallbackAction {
public:
- ~QuicStreamDelegateForTesting() override {}
-
- void OnRemoteReset() override {
- if (callback_type_expected_ == StreamCallbackType::kOnRemoteReset) {
- callback_type_expected_ = StreamCallbackType::kNone;
- }
- remote_reset_count_++;
- };
-
- void OnRemoteFinish() override {
- if (callback_type_expected_ == StreamCallbackType::kOnRemoteFinish) {
- callback_type_expected_ = StreamCallbackType::kNone;
- }
- remote_finish_count_++;
- };
-
- int remote_reset_count() { return remote_reset_count_; }
-
- int remote_finish_count() { return remote_finish_count_; }
-
- // Sets the type of callback expected to be called.
- void ExpectCallback(StreamCallbackType callback_type) {
- callback_type_expected_ = callback_type;
- }
+ FireCallbackAction(base::RepeatingCallback<void()> callback)
+ : callback_(callback) {}
- // Returns if we are expecting a callback that hasn't been fired yet.
- bool IsExpectingCallback() const {
- return callback_type_expected_ != StreamCallbackType::kNone;
+ template <typename Result, typename ArgumentTuple>
+ Result Perform(const ArgumentTuple& args) const {
+ callback_.Run();
}
private:
- int remote_reset_count_ = 0;
- int remote_finish_count_ = 0;
- StreamCallbackType callback_type_expected_ = StreamCallbackType::kNone;
+ base::RepeatingCallback<void()> callback_;
};
-// Implements counters for callbacks. It can also set expectations for a
-// specific callback. When an expectation is set the quic::TestTaskRunner
-// drives the test until the callbacks have been fired, and we are no longer
-// expecting the callback.
+// Returns the custom gmock PolymorphicAction created from the
+// FireCallbackAction above.
+PolymorphicAction<FireCallbackAction> FireCallback(
+ base::RepeatingCallback<void()> callback) {
+ return MakePolymorphicAction(FireCallbackAction(callback));
+}
+
+// A helper object that can drive a TestTaskRunner's tasks, until
+// callbacks are fired.
//
-// TODO(https://crbug.com/874296): If these files get moved to the platform
-// directory we will run the tests in a different test environment. In that case
-// it will make more sense to use the TestCompletionCallback and the RunLoop for
-// driving the test.
-class QuicTransportDelegateForTest final : public P2PQuicTransport::Delegate {
+// TODO(https://crbug.com/874296): If the test files get moved to the platform
+// directory we will run the tests in a different test environment. In that
+// case it will make more sense to use the TestCompletionCallback and the
+// RunLoop for driving the test.
+class CallbackRunLoop {
public:
- ~QuicTransportDelegateForTest() override {}
- void OnRemoteStopped() override {
- if (callback_type_expected_ == TransportCallbackType::kOnRemoteStopped) {
- callback_type_expected_ = TransportCallbackType::kNone;
- }
- stopped_count_++;
- }
-
- void OnConnectionFailed(const std::string& error_details,
- bool from_remote) override {
- if (callback_type_expected_ == TransportCallbackType::kOnConnectionFailed) {
- callback_type_expected_ = TransportCallbackType::kNone;
- }
- connection_failed_count_++;
- }
+ CallbackRunLoop(scoped_refptr<net::test::TestTaskRunner> task_runner)
+ : task_runner_(task_runner) {}
- void OnConnected() override {
- if (callback_type_expected_ == TransportCallbackType::kOnConnected) {
- callback_type_expected_ = TransportCallbackType::kNone;
- }
- connected_count_++;
- }
-
- // We store the remotely created stream.
- void OnStream(P2PQuicStream* stream) override {
- if (callback_type_expected_ == TransportCallbackType::kOnStream) {
- callback_type_expected_ = TransportCallbackType::kNone;
+ // Drives the run loop until all created callbacks have been fired.
+ // This is done using the |task_runner_|, which runs the tasks
+ // in the correct order and then advances the quic::MockClock to the time the
+ // task is run.
+ void RunUntilCallbacksFired() {
+ while (callback_counter_ != 0) {
+ ASSERT_GT(task_runner_->GetPostedTasks().size(), 0u);
+ task_runner_->RunNextTask();
}
- streams_.push_back(static_cast<P2PQuicStreamImpl*>(stream));
- on_stream_count_++;
- }
-
- int stopped_count() const { return stopped_count_; }
-
- int connection_failed_count() const { return connection_failed_count_; }
-
- int connected_count() const { return connected_count_; }
-
- int on_stream_count() const { return on_stream_count_; }
-
- // Sets the type of callback expected to be called.
- void ExpectCallback(TransportCallbackType callback_type) {
- callback_type_expected_ = callback_type;
}
- // Returns if we are expecting a callback that hasn't been fired yet.
- bool IsExpectingCallback() const {
- return callback_type_expected_ != TransportCallbackType::kNone;
+ // Creates a callback and increments the |callback_counter_|. The callback,
+ // when fired, will decrement the counter. This callback must only
+ // be Run() once (it is a RepeatingCallback because MakePolymorphicAction()
+ // requires that the action is COPYABLE).
+ base::RepeatingCallback<void()> CreateCallback() {
+ callback_counter_++;
+ return base::BindRepeating(&CallbackRunLoop::OnCallbackFired,
+ base::Unretained(this));
}
- std::vector<P2PQuicStreamImpl*> streams() const { return streams_; }
-
private:
- TransportCallbackType callback_type_expected_ = TransportCallbackType::kNone;
- int stopped_count_ = 0;
- int connection_failed_count_ = 0;
- int connected_count_ = 0;
- int on_stream_count_ = 0;
- // The delegates created for each stream as a result of the remote side
- // creating streams and sending data (triggering OnStream). P2PQuicStreamsImpl
- // are owned by the P2PQuicTransport.
- std::vector<P2PQuicStreamImpl*> streams_;
+ void OnCallbackFired() { callback_counter_--; }
+
+ scoped_refptr<net::test::TestTaskRunner> task_runner_;
+ // Incremented when a callback is created and decremented when the returned
+ // callback is later Run().
+ size_t callback_counter_ = 0;
};
// This is a fake packet transport to be used by the P2PQuicTransportImpl. It
@@ -271,12 +226,15 @@ class FakePacketTransport : public P2PQuicPacketTransport,
quic::MockClock* clock_;
};
-// A helper class to bundle test objects together.
+// A helper class to bundle test objects together. It keeps track of the
+// P2PQuicTransport, P2PQuicStream and the associated delegate objects. This
+// also keeps track of when callbacks are expected on the delegate objects,
+// which allows running the TestTaskRunner tasks until they have been fired.
class QuicPeerForTest {
public:
QuicPeerForTest(
std::unique_ptr<FakePacketTransport> packet_transport,
- std::unique_ptr<QuicTransportDelegateForTest> quic_transport_delegate,
+ std::unique_ptr<MockP2PQuicTransportDelegate> quic_transport_delegate,
std::unique_ptr<P2PQuicTransportImpl> quic_transport,
rtc::scoped_refptr<rtc::RTCCertificate> certificate)
: packet_transport_(std::move(packet_transport)),
@@ -284,9 +242,28 @@ class QuicPeerForTest {
quic_transport_(std::move(quic_transport)),
certificate_(certificate) {}
+ // A helper that creates a stream and creates and attaches a delegate.
+ void CreateStreamWithDelegate() {
+ stream_ = quic_transport_->CreateStream();
+ stream_delegate_ = std::make_unique<MockP2PQuicStreamDelegate>();
+ stream_->SetDelegate(stream_delegate_.get());
+ stream_id_ = stream_->id();
+ }
+
+ // When a remote stream is created via P2PQuicTransport::Delegate::OnStream,
+ // this is called to set the stream.
+ void SetStreamAndDelegate(
+ P2PQuicStreamImpl* stream,
+ std::unique_ptr<MockP2PQuicStreamDelegate> stream_delegate) {
+ DCHECK(stream);
+ stream_ = stream;
+ stream_id_ = stream->id();
+ stream_delegate_ = std::move(stream_delegate);
+ }
+
FakePacketTransport* packet_transport() { return packet_transport_.get(); }
- QuicTransportDelegateForTest* quic_transport_delegate() {
+ MockP2PQuicTransportDelegate* quic_transport_delegate() {
return quic_transport_delegate_.get();
}
@@ -294,9 +271,26 @@ class QuicPeerForTest {
rtc::scoped_refptr<rtc::RTCCertificate> certificate() { return certificate_; }
+ P2PQuicStreamImpl* stream() const { return stream_; }
+
+ MockP2PQuicStreamDelegate* stream_delegate() const {
+ return stream_delegate_.get();
+ }
+
+ quic::QuicStreamId stream_id() const { return stream_id_; }
+
private:
std::unique_ptr<FakePacketTransport> packet_transport_;
- std::unique_ptr<QuicTransportDelegateForTest> quic_transport_delegate_;
+ std::unique_ptr<MockP2PQuicTransportDelegate> quic_transport_delegate_;
+ // The corresponding delegate to |stream_|.
+ std::unique_ptr<MockP2PQuicStreamDelegate> stream_delegate_ = nullptr;
+ // Created as a result of CreateStreamWithDelegate() or RemoteStreamCreated().
+ // Owned by the |quic_transport_|.
+ P2PQuicStreamImpl* stream_ = nullptr;
+ // The corresponding ID for |stream_|. This can be used to check if the stream
+ // is closed at the transport level (after the stream object could be
+ // deleted).
+ quic::QuicStreamId stream_id_;
std::unique_ptr<P2PQuicTransportImpl> quic_transport_;
rtc::scoped_refptr<rtc::RTCCertificate> certificate_;
};
@@ -381,9 +375,9 @@ class P2PQuicTransportTest : public testing::Test {
quic_transport_factory_ = std::make_unique<P2PQuicTransportFactoryImpl>(
&clock_, std::unique_ptr<net::QuicChromiumAlarmFactory>(alarm_factory));
- std::unique_ptr<FakePacketTransport> client_packet_transport =
+ auto client_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
- std::unique_ptr<FakePacketTransport> server_packet_transport =
+ auto server_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
// Connect the transports so that they can speak to each other.
client_packet_transport->ConnectPeerTransport(
@@ -393,15 +387,13 @@ class P2PQuicTransportTest : public testing::Test {
rtc::scoped_refptr<rtc::RTCCertificate> client_cert =
CreateTestCertificate();
- std::unique_ptr<QuicTransportDelegateForTest>
- client_quic_transport_delegate =
- std::make_unique<QuicTransportDelegateForTest>();
+ auto client_quic_transport_delegate =
+ std::make_unique<MockP2PQuicTransportDelegate>();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> client_certificates;
client_certificates.push_back(client_cert);
- P2PQuicTransportConfig client_config(client_quic_transport_delegate.get(),
- client_packet_transport.get(),
- client_certificates);
- client_config.is_server = false;
+ P2PQuicTransportConfig client_config(
+ quic::Perspective::IS_CLIENT, client_certificates,
+ kTransportDelegateReadBufferSize, kTransportWriteBufferSize);
client_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
// We can't downcast a unique_ptr to an object, so we have to release, cast
@@ -409,7 +401,9 @@ class P2PQuicTransportTest : public testing::Test {
P2PQuicTransportImpl* client_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
- ->CreateQuicTransport(std::move(client_config))
+ ->CreateQuicTransport(client_quic_transport_delegate.get(),
+ client_packet_transport.get(),
+ client_config)
.release());
std::unique_ptr<P2PQuicTransportImpl> client_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(client_quic_transport_ptr);
@@ -418,24 +412,24 @@ class P2PQuicTransportTest : public testing::Test {
std::move(client_quic_transport_delegate),
std::move(client_quic_transport), client_cert);
- std::unique_ptr<QuicTransportDelegateForTest>
- server_quic_transport_delegate =
- std::make_unique<QuicTransportDelegateForTest>();
+ auto server_quic_transport_delegate =
+ std::make_unique<MockP2PQuicTransportDelegate>();
rtc::scoped_refptr<rtc::RTCCertificate> server_cert =
CreateTestCertificate();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> server_certificates;
server_certificates.push_back(server_cert);
- P2PQuicTransportConfig server_config(server_quic_transport_delegate.get(),
- server_packet_transport.get(),
- server_certificates);
- server_config.is_server = true;
+ P2PQuicTransportConfig server_config(
+ quic::Perspective::IS_SERVER, server_certificates,
+ kTransportDelegateReadBufferSize, kTransportWriteBufferSize);
server_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* server_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
- ->CreateQuicTransport(std::move(server_config))
+ ->CreateQuicTransport(server_quic_transport_delegate.get(),
+ server_packet_transport.get(),
+ server_config)
.release());
std::unique_ptr<P2PQuicTransportImpl> server_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(server_quic_transport_ptr);
@@ -466,26 +460,6 @@ class P2PQuicTransportTest : public testing::Test {
server_peer_->quic_transport()->InitializeCryptoStream();
}
- // Drives the test until we are't expecting any more callbacks to be fired.
- // This is done using the net::test::TestTaskRunner, which runs the tasks
- // in the correct order and then advances the quic::MockClock to the time the
- // task is run.
- void RunUntilCallbacksFired() {
- while (server_peer_->quic_transport_delegate()->IsExpectingCallback() ||
- client_peer_->quic_transport_delegate()->IsExpectingCallback() ||
- ExpectingStreamCallback()) {
- // We shouldn't enter a case where we are expecting a callback
- // and we're out of tasks to run.
- ASSERT_GT(runner_->GetPostedTasks().size(), 0u);
- runner_->RunNextTask();
- }
- }
-
- bool ExpectingStreamCallback() {
- return streams_setup_ && (client_stream_delegate_->IsExpectingCallback() ||
- server_stream_delegate_->IsExpectingCallback());
- }
-
// Drives the test by running the current tasks that are posted.
void RunCurrentTasks() {
size_t posted_tasks_size = runner_->GetPostedTasks().size();
@@ -513,51 +487,59 @@ class P2PQuicTransportTest : public testing::Test {
// Sets up an initial handshake and connection between peers.
void Connect() {
- client_peer_->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnected);
- server_peer_->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnected);
+ CallbackRunLoop run_loop(runner());
+
+ EXPECT_CALL(*client_peer_->quic_transport_delegate(), OnConnected())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnConnected())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
StartHandshake();
- RunUntilCallbacksFired();
- ExpectSecureConnection();
+ run_loop.RunUntilCallbacksFired();
}
// Creates a P2PQuicStreamImpl on both the client and server side that are
- // connected to each other.
+ // connected to each other. The client's stream is created with
+ // P2PQuicTransport::CreateStream, while the server's stream is initiated from
+ // the remote (client) side, with P2PQuicStream::Delegate::OnStream. This
+ // allows us to test at an integration level with connected streams.
void SetupConnectedStreams() {
+ CallbackRunLoop run_loop(runner());
// We must already have a secure connection before streams are created.
ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished());
ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished());
- client_stream_ = client_peer_->quic_transport()->CreateStream();
- ASSERT_TRUE(client_stream_);
- client_stream_id_ = client_stream_->id();
- client_stream_delegate_ = std::make_unique<QuicStreamDelegateForTesting>();
- client_stream_->SetDelegate(client_stream_delegate_.get());
+ client_peer_->CreateStreamWithDelegate();
+ ASSERT_TRUE(client_peer_->stream());
+ ASSERT_TRUE(client_peer_->stream_delegate());
// Send some data to trigger the remote side (server side) to get an
- // incoming stream.
- server_peer_->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnStream);
- client_stream_->WriteOrBufferData("hello", false, nullptr);
- RunUntilCallbacksFired();
-
- ASSERT_EQ(1u, server_peer_->quic_transport()->GetNumActiveStreams());
- ASSERT_EQ(1u, client_peer_->quic_transport()->GetNumActiveStreams());
- ASSERT_EQ(1u, server_peer_->quic_transport_delegate()->streams().size());
- server_stream_ = server_peer_->quic_transport_delegate()->streams()[0];
- ASSERT_TRUE(server_stream_);
- server_stream_id_ = server_stream_->id();
- server_stream_delegate_ = std::make_unique<QuicStreamDelegateForTesting>();
- server_stream_->SetDelegate(server_stream_delegate_.get());
- streams_setup_ = true;
- }
-
- void ExpectSecureConnection() {
- EXPECT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished());
- EXPECT_TRUE(client_peer_->quic_transport()->IsCryptoHandshakeConfirmed());
- EXPECT_TRUE(server_peer_->quic_transport()->IsCryptoHandshakeConfirmed());
- EXPECT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished());
+ // incoming stream. We capture the stream and set it's delegate when
+ // OnStream gets called on the mock object.
+ base::RepeatingCallback<void()> callback = run_loop.CreateCallback();
+ QuicPeerForTest* server_peer_ptr = server_peer_.get();
+ MockP2PQuicStreamDelegate* stream_delegate =
+ new MockP2PQuicStreamDelegate();
+ P2PQuicStream* server_stream;
+ EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_))
+ .WillOnce(Invoke([&callback, &server_stream,
+ &stream_delegate](P2PQuicStream* stream) {
+ stream->SetDelegate(stream_delegate);
+ server_stream = stream;
+ callback.Run();
+ }));
+
+ client_peer_->stream()->WriteData(
+ VectorFromArray(kTriggerRemoteStreamPhrase),
+ /*fin=*/false);
+ run_loop.RunUntilCallbacksFired();
+ // Set the stream and delegate to the |server_peer_|, so that it can be
+ // accessed by tests later.
+ server_peer_ptr->SetStreamAndDelegate(
+ static_cast<P2PQuicStreamImpl*>(server_stream),
+ std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate));
+ ASSERT_TRUE(client_peer_->stream());
+ ASSERT_TRUE(client_peer_->stream_delegate());
}
void ExpectConnectionNotEstablished() {
@@ -567,65 +549,27 @@ class P2PQuicTransportTest : public testing::Test {
EXPECT_FALSE(server_peer_->quic_transport()->IsEncryptionEstablished());
}
- // Test that the callbacks were called appropriately after a successful
- // crypto handshake.
- void ExpectSuccessfulHandshake() {
- EXPECT_EQ(1, client_peer_->quic_transport_delegate()->connected_count());
- EXPECT_EQ(0, client_peer_->quic_transport_delegate()->stopped_count());
- EXPECT_EQ(
- 0, client_peer_->quic_transport_delegate()->connection_failed_count());
-
- EXPECT_EQ(1, server_peer_->quic_transport_delegate()->connected_count());
- EXPECT_EQ(0, server_peer_->quic_transport_delegate()->stopped_count());
- EXPECT_EQ(
- 0, server_peer_->quic_transport_delegate()->connection_failed_count());
- }
-
void ExpectTransportsClosed() {
EXPECT_TRUE(client_peer_->quic_transport()->IsClosed());
EXPECT_TRUE(server_peer_->quic_transport()->IsClosed());
}
+ // Expects that streams of both the server and client transports are
+ // closed.
void ExpectStreamsClosed() {
- ASSERT_TRUE(streams_setup_);
EXPECT_EQ(0u, client_peer_->quic_transport()->GetNumActiveStreams());
- EXPECT_TRUE(
- client_peer_->quic_transport()->IsClosedStream(client_stream_id_));
+ EXPECT_TRUE(client_peer_->quic_transport()->IsClosedStream(
+ client_peer()->stream_id()));
+
EXPECT_EQ(0u, server_peer_->quic_transport()->GetNumActiveStreams());
- EXPECT_TRUE(
- server_peer()->quic_transport()->IsClosedStream(server_stream_id_));
+ EXPECT_TRUE(server_peer()->quic_transport()->IsClosedStream(
+ server_peer()->stream_id()));
}
// Exposes these private functions to the test.
bool IsClientClosed() { return client_peer_->quic_transport()->IsClosed(); }
bool IsServerClosed() { return server_peer_->quic_transport()->IsClosed(); }
- // Tests that the callbacks were appropriately called after the client
- // stops the connection. Only the server should receive the OnRemoteStopped()
- // callback.
- void ExpectClientStopped() {
- ExpectTransportsClosed();
- EXPECT_EQ(0, client_peer_->quic_transport_delegate()->stopped_count());
- EXPECT_EQ(
- 0, client_peer_->quic_transport_delegate()->connection_failed_count());
- EXPECT_EQ(1, server_peer_->quic_transport_delegate()->stopped_count());
- EXPECT_EQ(
- 0, server_peer_->quic_transport_delegate()->connection_failed_count());
- }
-
- // Tests that the callbacks were appropriately called after the server
- // stops the connection. Only the client should receive the OnRemoteStopped()
- // callback.
- void ExpectServerStopped() {
- ExpectTransportsClosed();
- EXPECT_EQ(1, client_peer_->quic_transport_delegate()->stopped_count());
- EXPECT_EQ(
- 0, client_peer_->quic_transport_delegate()->connection_failed_count());
- EXPECT_EQ(0, server_peer_->quic_transport_delegate()->stopped_count());
- EXPECT_EQ(
- 0, server_peer_->quic_transport_delegate()->connection_failed_count());
- }
-
QuicPeerForTest* client_peer() { return client_peer_.get(); }
quic::QuicConnection* client_connection() {
@@ -638,20 +582,13 @@ class P2PQuicTransportTest : public testing::Test {
return server_peer_->quic_transport()->connection();
}
- P2PQuicStreamImpl* server_stream() { return server_stream_; }
-
- P2PQuicStreamImpl* client_stream() { return client_stream_; }
+ scoped_refptr<net::test::TestTaskRunner> runner() { return runner_; }
- quic::QuicStreamId server_stream_id() { return server_stream_id_; }
-
- quic::QuicStreamId client_stream_id() { return client_stream_id_; }
-
- QuicStreamDelegateForTesting* server_stream_delegate() {
- return server_stream_delegate_.get();
- }
-
- QuicStreamDelegateForTesting* client_stream_delegate() {
- return client_stream_delegate_.get();
+ template <wtf_size_t Size>
+ static Vector<uint8_t> VectorFromArray(const uint8_t (&array)[Size]) {
+ Vector<uint8_t> vector;
+ vector.Append(array, Size);
+ return vector;
}
private:
@@ -664,17 +601,6 @@ class P2PQuicTransportTest : public testing::Test {
std::unique_ptr<P2PQuicTransportFactoryImpl> quic_transport_factory_;
std::unique_ptr<QuicPeerForTest> client_peer_;
std::unique_ptr<QuicPeerForTest> server_peer_;
-
- // Stream objects, which are created with SetupConnectedStream().
- bool streams_setup_ = false;
- std::unique_ptr<QuicStreamDelegateForTesting> client_stream_delegate_;
- std::unique_ptr<QuicStreamDelegateForTesting> server_stream_delegate_;
- // The P2PQuicStreamImpls are owned by the P2PQuicTransport.
- P2PQuicStreamImpl* client_stream_ = nullptr;
- P2PQuicStreamImpl* server_stream_ = nullptr;
- // We cache the values before the streams are potentially closed and deleted.
- quic::QuicStreamId server_stream_id_;
- quic::QuicStreamId client_stream_id_;
};
// Tests that we can connect two quic transports.
@@ -682,31 +608,42 @@ TEST_F(P2PQuicTransportTest, HandshakeConnectsPeers) {
Initialize();
Connect();
- ExpectSuccessfulHandshake();
+ EXPECT_TRUE(client_peer()->quic_transport()->IsEncryptionEstablished());
+ EXPECT_TRUE(client_peer()->quic_transport()->IsCryptoHandshakeConfirmed());
+ EXPECT_TRUE(server_peer()->quic_transport()->IsCryptoHandshakeConfirmed());
+ EXPECT_TRUE(server_peer()->quic_transport()->IsEncryptionEstablished());
}
// Tests the standard case for the server side closing the connection.
TEST_F(P2PQuicTransportTest, ServerStops) {
Initialize();
Connect();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnRemoteStopped);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .Times(0);
+
server_peer()->quic_transport()->Stop();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
- ExpectServerStopped();
+ ExpectTransportsClosed();
}
// Tests the standard case for the client side closing the connection.
TEST_F(P2PQuicTransportTest, ClientStops) {
Initialize();
Connect();
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnRemoteStopped);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .Times(0);
+
client_peer()->quic_transport()->Stop();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
- ExpectClientStopped();
+ ExpectTransportsClosed();
}
// Tests that if either side tries to close the connection a second time, it
@@ -714,29 +651,37 @@ TEST_F(P2PQuicTransportTest, ClientStops) {
TEST_F(P2PQuicTransportTest, StopAfterStopped) {
Initialize();
Connect();
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnRemoteStopped);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
client_peer()->quic_transport()->Stop();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
+
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .Times(0);
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .Times(0);
+
client_peer()->quic_transport()->Stop();
server_peer()->quic_transport()->Stop();
RunCurrentTasks();
- ExpectClientStopped();
+ ExpectTransportsClosed();
}
// Tests that when the client closes the connection the subsequent call to
-// Start() will be ignored.
+// StartHandshake() will be ignored.
TEST_F(P2PQuicTransportTest, ClientStopsBeforeClientStarts) {
Initialize();
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnRemoteStopped);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
client_peer()->quic_transport()->Stop();
StartHandshake();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectConnectionNotEstablished();
- ExpectClientStopped();
+ ExpectTransportsClosed();
}
// Tests that if the server closes the connection before the client starts the
@@ -744,29 +689,37 @@ TEST_F(P2PQuicTransportTest, ClientStopsBeforeClientStarts) {
// ignored.
TEST_F(P2PQuicTransportTest, ServerStopsBeforeClientStarts) {
Initialize();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnRemoteStopped);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnRemoteStopped())
+ .Times(0);
+
server_peer()->quic_transport()->Stop();
StartHandshake();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectConnectionNotEstablished();
- ExpectServerStopped();
+ ExpectTransportsClosed();
}
// Tests that when the server's connection fails and then a handshake is
// attempted the transports will not become connected.
TEST_F(P2PQuicTransportTest, ClientConnectionClosesBeforeHandshake) {
Initialize();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
client_connection()->CloseConnection(
quic::QuicErrorCode::QUIC_INTERNAL_ERROR, "internal error",
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
StartHandshake();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectConnectionNotEstablished();
}
@@ -775,15 +728,19 @@ TEST_F(P2PQuicTransportTest, ClientConnectionClosesBeforeHandshake) {
// attempted the transports will not become connected.
TEST_F(P2PQuicTransportTest, ServerConnectionClosesBeforeHandshake) {
Initialize();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
server_connection()->CloseConnection(
quic::QuicErrorCode::QUIC_INTERNAL_ERROR, "internal error",
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
StartHandshake();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectConnectionNotEstablished();
}
@@ -791,17 +748,17 @@ TEST_F(P2PQuicTransportTest, ServerConnectionClosesBeforeHandshake) {
// Tests that the appropriate callbacks are fired when the handshake fails.
TEST_F(P2PQuicTransportTest, HandshakeFailure) {
InitializeWithFailingProofVerification();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
StartHandshake();
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
- EXPECT_EQ(
- 1, client_peer()->quic_transport_delegate()->connection_failed_count());
- EXPECT_EQ(
- 1, server_peer()->quic_transport_delegate()->connection_failed_count());
ExpectConnectionNotEstablished();
ExpectTransportsClosed();
}
@@ -811,21 +768,21 @@ TEST_F(P2PQuicTransportTest, HandshakeFailure) {
TEST_F(P2PQuicTransportTest, ClientConnectionFailureAfterConnected) {
Initialize();
Connect();
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, /*from_remote=*/false))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, /*from_remote=*/true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
// Close the connection with an internal QUIC error.
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
client_connection()->CloseConnection(
quic::QuicErrorCode::QUIC_INTERNAL_ERROR, "internal error",
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectTransportsClosed();
- EXPECT_EQ(
- 1, client_peer()->quic_transport_delegate()->connection_failed_count());
- EXPECT_EQ(
- 1, server_peer()->quic_transport_delegate()->connection_failed_count());
}
// Tests that the appropriate callbacks are fired when the server's connection
@@ -833,21 +790,20 @@ TEST_F(P2PQuicTransportTest, ClientConnectionFailureAfterConnected) {
TEST_F(P2PQuicTransportTest, ServerConnectionFailureAfterConnected) {
Initialize();
Connect();
- // Close the connection with an internal QUIC error.
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, /*from_remote=*/true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, /*from_remote=*/false))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
server_connection()->CloseConnection(
quic::QuicErrorCode::QUIC_INTERNAL_ERROR, "internal error",
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectTransportsClosed();
- EXPECT_EQ(
- 1, client_peer()->quic_transport_delegate()->connection_failed_count());
- EXPECT_EQ(
- 1, server_peer()->quic_transport_delegate()->connection_failed_count());
}
// Tests that closing the connection with no ACK frame does not make any
@@ -855,39 +811,41 @@ TEST_F(P2PQuicTransportTest, ServerConnectionFailureAfterConnected) {
TEST_F(P2PQuicTransportTest, ConnectionFailureNoAckFrame) {
Initialize();
Connect();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
client_connection()->CloseConnection(
quic::QuicErrorCode::QUIC_INTERNAL_ERROR, "internal error",
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET_WITH_NO_ACK);
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
ExpectTransportsClosed();
- EXPECT_EQ(
- 1, client_peer()->quic_transport_delegate()->connection_failed_count());
- EXPECT_EQ(
- 1, server_peer()->quic_transport_delegate()->connection_failed_count());
}
// Tests that a silent failure will only close on one side.
TEST_F(P2PQuicTransportTest, ConnectionSilentFailure) {
Initialize();
Connect();
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnConnectionFailed);
+ CallbackRunLoop run_loop(runner());
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(),
+ OnConnectionFailed(_, _))
+ .Times(0);
+
client_connection()->CloseConnection(
quic::QuicErrorCode::QUIC_INTERNAL_ERROR, "internal error",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
- RunUntilCallbacksFired();
+ run_loop.RunUntilCallbacksFired();
EXPECT_TRUE(IsClientClosed());
- EXPECT_EQ(
- 1, client_peer()->quic_transport_delegate()->connection_failed_count());
EXPECT_FALSE(IsServerClosed());
- EXPECT_EQ(
- 0, server_peer()->quic_transport_delegate()->connection_failed_count());
}
// Tests that the client transport can create a stream and an incoming stream
@@ -895,23 +853,34 @@ TEST_F(P2PQuicTransportTest, ConnectionSilentFailure) {
TEST_F(P2PQuicTransportTest, ClientCreatesStream) {
Initialize();
Connect();
- P2PQuicStreamImpl* client_stream =
- client_peer()->quic_transport()->CreateStream();
+ CallbackRunLoop run_loop(runner());
+ client_peer()->CreateStreamWithDelegate();
+ ASSERT_TRUE(client_peer()->stream());
+
RunCurrentTasks();
- ASSERT_TRUE(client_stream);
EXPECT_TRUE(client_peer()->quic_transport()->HasOpenDynamicStreams());
- EXPECT_EQ(0, server_peer()->quic_transport_delegate()->on_stream_count());
EXPECT_FALSE(server_peer()->quic_transport()->HasOpenDynamicStreams());
// After sending data across it will trigger a stream to be created on the
// server side.
- server_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnStream);
- client_stream->WriteOrBufferData("hello", false, nullptr);
- RunUntilCallbacksFired();
+ MockP2PQuicStreamDelegate server_stream_delegate;
+ base::RepeatingCallback<void()> callback = run_loop.CreateCallback();
+ EXPECT_CALL(*server_peer()->quic_transport_delegate(), OnStream(_))
+ .WillOnce(
+ Invoke([&callback, &server_stream_delegate](P2PQuicStream* stream) {
+ ASSERT_TRUE(stream);
+ // The Delegate must get immediately set to a new incoming stream.
+ stream->SetDelegate(&server_stream_delegate);
+ // Allows the run loop to run until this is fired.
+ callback.Run();
+ }));
+
+ client_peer()->stream()->WriteData(
+ VectorFromArray(kTriggerRemoteStreamPhrase),
+ /*fin=*/false);
+ run_loop.RunUntilCallbacksFired();
- EXPECT_EQ(1, server_peer()->quic_transport_delegate()->on_stream_count());
EXPECT_TRUE(server_peer()->quic_transport()->HasOpenDynamicStreams());
}
@@ -920,23 +889,34 @@ TEST_F(P2PQuicTransportTest, ClientCreatesStream) {
TEST_F(P2PQuicTransportTest, ServerCreatesStream) {
Initialize();
Connect();
- P2PQuicStreamImpl* server_stream =
- server_peer()->quic_transport()->CreateStream();
+ CallbackRunLoop run_loop(runner());
+ server_peer()->CreateStreamWithDelegate();
+ ASSERT_TRUE(server_peer()->stream());
+
RunCurrentTasks();
- ASSERT_TRUE(server_stream);
EXPECT_TRUE(server_peer()->quic_transport()->HasOpenDynamicStreams());
- EXPECT_EQ(0, client_peer()->quic_transport_delegate()->on_stream_count());
EXPECT_FALSE(client_peer()->quic_transport()->HasOpenDynamicStreams());
// After sending data across it will trigger a stream to be created on the
- // client side.
- client_peer()->quic_transport_delegate()->ExpectCallback(
- TransportCallbackType::kOnStream);
- server_stream->WriteOrBufferData("hello", false, nullptr);
- RunUntilCallbacksFired();
+ // server side.
+ MockP2PQuicStreamDelegate client_stream_delegate;
+ base::RepeatingCallback<void()> callback = run_loop.CreateCallback();
+ EXPECT_CALL(*client_peer()->quic_transport_delegate(), OnStream(_))
+ .WillOnce(
+ Invoke([&callback, &client_stream_delegate](P2PQuicStream* stream) {
+ ASSERT_TRUE(stream);
+ // The Delegate must get immediately set to a new incoming stream.
+ stream->SetDelegate(&client_stream_delegate);
+ // Allows the run loop to run until this is fired.
+ callback.Run();
+ }));
+
+ server_peer()->stream()->WriteData(
+ VectorFromArray(kTriggerRemoteStreamPhrase),
+ /*fin=*/false);
+ run_loop.RunUntilCallbacksFired();
- EXPECT_EQ(1, client_peer()->quic_transport_delegate()->on_stream_count());
EXPECT_TRUE(client_peer()->quic_transport()->HasOpenDynamicStreams());
}
@@ -976,11 +956,13 @@ TEST_F(P2PQuicTransportTest, ClientStreamReset) {
Initialize();
Connect();
SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
- server_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteReset);
- client_stream()->Reset();
- RunUntilCallbacksFired();
+ EXPECT_CALL(*server_peer()->stream_delegate(), OnRemoteReset())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ client_peer()->stream()->Reset();
+ run_loop.RunUntilCallbacksFired();
ExpectStreamsClosed();
}
@@ -990,188 +972,164 @@ TEST_F(P2PQuicTransportTest, ServerStreamReset) {
Initialize();
Connect();
SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
- client_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteReset);
- server_stream()->Reset();
- RunUntilCallbacksFired();
+ EXPECT_CALL(*client_peer()->stream_delegate(), OnRemoteReset())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ server_peer()->stream()->Reset();
+ run_loop.RunUntilCallbacksFired();
ExpectStreamsClosed();
}
-// Tests the basic case for calling Finish() on both sides.
-TEST_F(P2PQuicTransportTest, StreamFinishHandshake) {
+// Tests the basic case for sending a FIN bit on both sides.
+TEST_F(P2PQuicTransportTest, StreamClosedAfterSendingAndReceivingFin) {
Initialize();
Connect();
SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
+
+ EXPECT_CALL(*server_peer()->stream_delegate(),
+ OnDataReceived(_, /*fin=*/true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
- server_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteFinish);
- client_stream()->Finish();
- RunUntilCallbacksFired();
+ client_peer()->stream()->WriteData({}, /*fin=*/true);
+ run_loop.RunUntilCallbacksFired();
ASSERT_EQ(1u, server_peer()->quic_transport()->GetNumActiveStreams());
ASSERT_EQ(1u, client_peer()->quic_transport()->GetNumActiveStreams());
- EXPECT_EQ(0, client_stream_delegate()->remote_finish_count());
- EXPECT_TRUE(client_stream()->write_side_closed());
- EXPECT_FALSE(client_stream()->reading_stopped());
- EXPECT_FALSE(server_stream()->write_side_closed());
- EXPECT_TRUE(server_stream()->reading_stopped());
- EXPECT_FALSE(
- server_peer()->quic_transport()->IsClosedStream(server_stream_id()));
- EXPECT_FALSE(
- client_peer()->quic_transport()->IsClosedStream(client_stream_id()));
-
- client_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteFinish);
- server_stream()->Finish();
- RunUntilCallbacksFired();
+ EXPECT_TRUE(client_peer()->stream()->write_side_closed());
+ EXPECT_FALSE(client_peer()->stream()->reading_stopped());
+ EXPECT_FALSE(server_peer()->stream()->write_side_closed());
+ EXPECT_TRUE(server_peer()->stream()->reading_stopped());
+ EXPECT_FALSE(server_peer()->quic_transport()->IsClosedStream(
+ server_peer()->stream_id()));
+ EXPECT_FALSE(client_peer()->quic_transport()->IsClosedStream(
+ client_peer()->stream_id()));
+
+ EXPECT_CALL(*client_peer()->stream_delegate(),
+ OnDataReceived(_, /*fin=*/true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ server_peer()->stream()->WriteData({}, /*fin=*/true);
+ run_loop.RunUntilCallbacksFired();
+
// This is required so that the client acks the FIN back to the server side
// and the server side removes its zombie streams.
RunCurrentTasks();
ASSERT_EQ(0u, server_peer()->quic_transport()->GetNumActiveStreams());
ASSERT_EQ(0u, client_peer()->quic_transport()->GetNumActiveStreams());
- EXPECT_EQ(1, server_stream_delegate()->remote_finish_count());
- EXPECT_EQ(1, client_stream_delegate()->remote_finish_count());
- EXPECT_TRUE(
- server_peer()->quic_transport()->IsClosedStream(server_stream_id()));
- EXPECT_TRUE(
- client_peer()->quic_transport()->IsClosedStream(client_stream_id()));
+ EXPECT_TRUE(server_peer()->quic_transport()->IsClosedStream(
+ server_peer()->stream_id()));
+ EXPECT_TRUE(client_peer()->quic_transport()->IsClosedStream(
+ client_peer()->stream_id()));
}
-// Tests that if a Reset() is called after Finish(), both sides close down
-// properly.
-TEST_F(P2PQuicTransportTest, StreamResetAfterFinish) {
+// Tests that if a Reset() is called after sending a FIN bit, both sides close
+// down properly.
+TEST_F(P2PQuicTransportTest, StreamResetAfterSendingFin) {
Initialize();
Connect();
SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
+
+ EXPECT_CALL(*server_peer()->stream_delegate(),
+ OnDataReceived(_, /*fin=*/true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ client_peer()->stream()->WriteData({}, /*fin=*/true);
+ run_loop.RunUntilCallbacksFired();
- server_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteFinish);
- client_stream()->Finish();
- RunUntilCallbacksFired();
+ EXPECT_CALL(*server_peer()->stream_delegate(), OnRemoteReset())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*client_peer()->stream_delegate(), OnRemoteReset()).Times(0);
- server_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteReset);
- client_stream()->Reset();
- RunUntilCallbacksFired();
+ client_peer()->stream()->Reset();
+ run_loop.RunUntilCallbacksFired();
ExpectStreamsClosed();
- EXPECT_EQ(0, client_stream_delegate()->remote_reset_count());
}
// Tests that if a Reset() is called after receiving a stream frame with the FIN
// bit set from the remote side, both sides close down properly.
-TEST_F(P2PQuicTransportTest, StreamResetAfterRemoteFinish) {
+TEST_F(P2PQuicTransportTest, StreamResetAfterReceivingFin) {
Initialize();
Connect();
SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
- server_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteFinish);
- client_stream()->Finish();
- RunUntilCallbacksFired();
+ EXPECT_CALL(*server_peer()->stream_delegate(),
+ OnDataReceived(_, /*fin=*/true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ client_peer()->stream()->WriteData({}, /*fin=*/true);
+ run_loop.RunUntilCallbacksFired();
+
+ EXPECT_CALL(*client_peer()->stream_delegate(), OnRemoteReset())
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->stream_delegate(), OnRemoteReset()).Times(0);
- client_stream_delegate()->ExpectCallback(StreamCallbackType::kOnRemoteReset);
// The server stream has received its FIN bit from the remote side, and
// responds with a Reset() to close everything down.
- server_stream()->Reset();
- RunUntilCallbacksFired();
+ server_peer()->stream()->Reset();
+ run_loop.RunUntilCallbacksFired();
ExpectStreamsClosed();
- EXPECT_EQ(0, server_stream_delegate()->remote_reset_count());
-}
-
-// The following unit tests are more isolated to the P2PQuicStreamImpl
-// implementation. They only test a stream's behavior on one side (not any
-// interactions between two connected streams).
-
-TEST_F(P2PQuicTransportTest, StreamFinishSendsFinAndCanNoLongerWrite) {
- Initialize();
- Connect();
- P2PQuicStreamImpl* stream = client_peer()->quic_transport()->CreateStream();
-
- stream->Finish();
- EXPECT_TRUE(stream->fin_sent());
- EXPECT_TRUE(stream->write_side_closed());
- EXPECT_FALSE(stream->reading_stopped());
}
-TEST_F(P2PQuicTransportTest, StreamResetSendsRstAndBecomesClosed) {
+// Tests that when data is sent on a stream it is received on the other end.
+TEST_F(P2PQuicTransportTest, StreamDataSentThenReceivedOnRemoteSide) {
Initialize();
Connect();
-
- P2PQuicStreamImpl* stream = client_peer()->quic_transport()->CreateStream();
- quic::QuicStreamId stream_id = stream->id();
-
- stream->Reset();
-
- EXPECT_TRUE(client_peer()->quic_transport()->IsClosedStream(stream_id));
-}
-
-// Tests that when a stream receives a stream frame with the FIN bit set it
-// will fire the appropriate callback and close the stream for reading.
-TEST_F(P2PQuicTransportTest, StreamOnStreamFrameWithFin) {
- Initialize();
- Connect();
- P2PQuicStreamImpl* stream = client_peer()->quic_transport()->CreateStream();
- QuicStreamDelegateForTesting stream_delegate;
- stream->SetDelegate(&stream_delegate);
-
- quic::QuicStreamFrame fin_frame(stream->id(), /*fin=*/true, 0, 0);
- stream->OnStreamFrame(fin_frame);
- EXPECT_EQ(1, stream_delegate.remote_finish_count());
- EXPECT_TRUE(stream->reading_stopped());
- EXPECT_FALSE(stream->write_side_closed());
-}
-
-// Tests that when a stream receives a stream frame with the FIN bit set after
-// it has called Finish(), then the stream will close.
-TEST_F(P2PQuicTransportTest, StreamClosedAfterReceivesFin) {
- Initialize();
- Connect();
- P2PQuicStreamImpl* stream = client_peer()->quic_transport()->CreateStream();
- quic::QuicStreamId stream_id = stream->id();
- QuicStreamDelegateForTesting stream_delegate;
- stream->SetDelegate(&stream_delegate);
-
- stream->Finish();
- EXPECT_FALSE(client_peer()->quic_transport()->IsClosedStream(stream_id));
- quic::QuicStreamFrame fin_frame(stream->id(), /*fin=*/true, 0, 0);
- stream->OnStreamFrame(fin_frame);
-
- EXPECT_TRUE(client_peer()->quic_transport()->IsClosedStream(stream_id));
-}
-
-// Tests that when a stream calls Finish() after receiving a stream frame with
-// the FIN bit then the stream will close.
-TEST_F(P2PQuicTransportTest, StreamClosedAfterFinish) {
- Initialize();
- Connect();
- P2PQuicStreamImpl* stream = client_peer()->quic_transport()->CreateStream();
- quic::QuicStreamId stream_id = stream->id();
- QuicStreamDelegateForTesting stream_delegate;
- stream->SetDelegate(&stream_delegate);
-
- quic::QuicStreamFrame fin_frame(stream->id(), /*fin=*/true, 0, 0);
- stream->OnStreamFrame(fin_frame);
- EXPECT_FALSE(client_peer()->quic_transport()->IsClosedStream(stream_id));
- stream->Finish();
-
- EXPECT_TRUE(client_peer()->quic_transport()->IsClosedStream(stream_id));
+ SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
+ const uint8_t kMessage[] = {'h', 'o', 'w', 'd', 'y'};
+
+ EXPECT_CALL(*server_peer()->stream_delegate(),
+ OnDataReceived(ElementsAreArray(kMessage), false))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*client_peer()->stream_delegate(),
+ OnWriteDataConsumed(base::size(kMessage)))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ client_peer()->stream()->WriteData(VectorFromArray(kMessage),
+ /* fin= */ false);
+ run_loop.RunUntilCallbacksFired();
}
-// Tests that when a stream receives a RST_STREAM frame it will fire the
-// appropriate callback and the stream will become closed.
-TEST_F(P2PQuicTransportTest, StreamClosedAfterReceivingReset) {
+// Tests that if both sides have a stream that sends data and FIN bit
+// they both close down for reading and writing properly.
+TEST_F(P2PQuicTransportTest, StreamDataSentWithFinClosesStreams) {
Initialize();
Connect();
- P2PQuicStreamImpl* stream = client_peer()->quic_transport()->CreateStream();
- quic::QuicStreamId stream_id = stream->id();
- QuicStreamDelegateForTesting stream_delegate;
- stream->SetDelegate(&stream_delegate);
-
- quic::QuicRstStreamFrame rst_frame(quic::kInvalidControlFrameId, stream_id,
- quic::QUIC_STREAM_CANCELLED, 0);
- stream->OnStreamReset(rst_frame);
+ SetupConnectedStreams();
+ CallbackRunLoop run_loop(runner());
+ const uint8_t kServerMessage[] = {'s', 'e', 'r', 'v', 'e', 'r'};
+ const uint8_t kClientMessage[] = {'c', 'l', 'i', 'e', 'n', 't'};
+
+ EXPECT_CALL(*server_peer()->stream_delegate(),
+ OnDataReceived(VectorFromArray(kClientMessage), true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*server_peer()->stream_delegate(),
+ OnWriteDataConsumed(base::size(kServerMessage)))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ EXPECT_CALL(*client_peer()->stream_delegate(),
+ OnDataReceived(ElementsAreArray(kServerMessage), true))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+ EXPECT_CALL(*client_peer()->stream_delegate(),
+ OnWriteDataConsumed(base::size(kClientMessage)))
+ .WillOnce(FireCallback(run_loop.CreateCallback()));
+
+ client_peer()->stream()->WriteData(VectorFromArray(kClientMessage),
+ /*fin=*/true);
+ server_peer()->stream()->WriteData(VectorFromArray(kServerMessage),
+ /*fin=*/true);
+ run_loop.RunUntilCallbacksFired();
- EXPECT_EQ(1, stream_delegate.remote_reset_count());
- EXPECT_TRUE(client_peer()->quic_transport()->IsClosedStream(stream_id));
+ ExpectStreamsClosed();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.cc
index 71545c64e99..a0937ef43e3 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -49,13 +49,22 @@ void QuicStreamHost::Reset() {
Delete();
}
-void QuicStreamHost::Finish() {
+void QuicStreamHost::MarkReceivedDataConsumed(uint32_t amount) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(p2p_stream_);
- p2p_stream_->Finish();
- writeable_ = false;
- if (!readable_ && !writeable_) {
- Delete();
+ p2p_stream_->MarkReceivedDataConsumed(amount);
+}
+
+void QuicStreamHost::WriteData(Vector<uint8_t> data, bool fin) {
+ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(p2p_stream_);
+ p2p_stream_->WriteData(data, fin);
+ if (fin) {
+ DCHECK(writable_);
+ writable_ = false;
+ if (!readable_ && !writable_) {
+ Delete();
+ }
}
}
@@ -67,17 +76,26 @@ void QuicStreamHost::OnRemoteReset() {
Delete();
}
-void QuicStreamHost::OnRemoteFinish() {
+void QuicStreamHost::OnDataReceived(Vector<uint8_t> data, bool fin) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
- PostCrossThreadTask(
- *proxy_thread(), FROM_HERE,
- CrossThreadBind(&QuicStreamProxy::OnRemoteFinish, stream_proxy_));
- readable_ = false;
- if (!readable_ && !writeable_) {
- Delete();
+ PostCrossThreadTask(*proxy_thread(), FROM_HERE,
+ CrossThreadBind(&QuicStreamProxy::OnDataReceived,
+ stream_proxy_, std::move(data), fin));
+ if (fin) {
+ readable_ = false;
+ if (!readable_ && !writable_) {
+ Delete();
+ }
}
}
+void QuicStreamHost::OnWriteDataConsumed(uint32_t amount) {
+ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ PostCrossThreadTask(*proxy_thread(), FROM_HERE,
+ CrossThreadBind(&QuicStreamProxy::OnWriteDataConsumed,
+ stream_proxy_, amount));
+}
+
void QuicStreamHost::Delete() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(transport_host_);
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.h
index baab847dff6..4607b6ca94f 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_host.h
@@ -56,7 +56,8 @@ class QuicStreamHost final : public base::SupportsWeakPtr<QuicStreamHost>,
scoped_refptr<base::SingleThreadTaskRunner> proxy_thread() const;
void Reset();
- void Finish();
+ void MarkReceivedDataConsumed(uint32_t amount);
+ void WriteData(Vector<uint8_t> data, bool fin);
private:
// Instruct the QuicTransportHost to remove and delete this stream host.
@@ -64,7 +65,8 @@ class QuicStreamHost final : public base::SupportsWeakPtr<QuicStreamHost>,
// P2PQuicStream::Delegate overrides.
void OnRemoteReset() override;
- void OnRemoteFinish() override;
+ void OnDataReceived(Vector<uint8_t> data, bool fin) override;
+ void OnWriteDataConsumed(uint32_t amount) override;
// Up reference. Owned by QuicTransportProxy.
QuicTransportHost* transport_host_ = nullptr;
@@ -73,10 +75,10 @@ class QuicStreamHost final : public base::SupportsWeakPtr<QuicStreamHost>,
// Back reference. Owned by QuicTransportProxy.
base::WeakPtr<QuicStreamProxy> stream_proxy_;
- // |readable_| transitions to false when OnRemoteFinish() is called.
+ // |readable_| transitions to false when OnDataReceived(_, true) is called.
bool readable_ = true;
- // |writeable_| transitions to false when Finish() is called.
- bool writeable_ = true;
+ // |writable_| transitions to false when WriteData(_, true) is called.
+ bool writable_ = true;
THREAD_CHECKER(thread_checker_);
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.cc
index e50ebf0925d..2d3df4abbdb 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -51,13 +51,23 @@ void QuicStreamProxy::Reset() {
Delete();
}
-void QuicStreamProxy::Finish() {
+void QuicStreamProxy::MarkReceivedDataConsumed(uint32_t amount) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
PostCrossThreadTask(*host_thread(), FROM_HERE,
- CrossThreadBind(&QuicStreamHost::Finish, stream_host_));
- writeable_ = false;
- if (!readable_ && !writeable_) {
- Delete();
+ CrossThreadBind(&QuicStreamHost::MarkReceivedDataConsumed,
+ stream_host_, amount));
+}
+
+void QuicStreamProxy::WriteData(Vector<uint8_t> data, bool fin) {
+ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ PostCrossThreadTask(*host_thread(), FROM_HERE,
+ CrossThreadBind(&QuicStreamHost::WriteData, stream_host_,
+ std::move(data), fin));
+ if (fin) {
+ writable_ = false;
+ if (!readable_ && !writable_) {
+ Delete();
+ }
}
}
@@ -70,16 +80,24 @@ void QuicStreamProxy::OnRemoteReset() {
delegate_copy->OnRemoteReset();
}
-void QuicStreamProxy::OnRemoteFinish() {
+void QuicStreamProxy::OnDataReceived(Vector<uint8_t> data, bool fin) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
// Need to copy the |delegate_| member since Delete() will destroy |this|.
Delegate* delegate_copy = delegate_;
- readable_ = false;
- if (!readable_ && !writeable_) {
- Delete();
+ if (fin) {
+ readable_ = false;
+ if (!readable_ && !writable_) {
+ Delete();
+ }
}
- delegate_copy->OnRemoteFinish();
+ delegate_copy->OnDataReceived(std::move(data), fin);
+}
+
+void QuicStreamProxy::OnWriteDataConsumed(uint32_t amount) {
+ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
+ DCHECK(delegate_);
+ delegate_->OnWriteDataConsumed(amount);
}
void QuicStreamProxy::Delete() {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.h
index 0d059f635f6..5881aef8e0b 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.h
@@ -9,6 +9,7 @@
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_checker.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -43,8 +44,10 @@ class QuicStreamProxy final : public base::SupportsWeakPtr<QuicStreamProxy> {
// Called when the remote side resets the stream.
virtual void OnRemoteReset() {}
- // Called when the remote side finishes the stream.
- virtual void OnRemoteFinish() {}
+ // Called when the remote side receives data and/or the finish bit.
+ virtual void OnDataReceived(Vector<uint8_t> data, bool fin) {}
+ // Called when data written with WriteData() has been consumed by QUIC.
+ virtual void OnWriteDataConsumed(uint32_t amount) {}
};
QuicStreamProxy();
@@ -67,7 +70,8 @@ class QuicStreamProxy final : public base::SupportsWeakPtr<QuicStreamProxy> {
scoped_refptr<base::SingleThreadTaskRunner> host_thread() const;
void Reset();
- void Finish();
+ void MarkReceivedDataConsumed(uint32_t amount);
+ void WriteData(Vector<uint8_t> data, bool fin);
private:
// Instruct the QuicTransportProxy to remove and delete this stream proxy.
@@ -76,7 +80,8 @@ class QuicStreamProxy final : public base::SupportsWeakPtr<QuicStreamProxy> {
// Callbacks from QuicStreamHost.
friend class QuicStreamHost;
void OnRemoteReset();
- void OnRemoteFinish();
+ void OnDataReceived(Vector<uint8_t> data, bool fin);
+ void OnWriteDataConsumed(uint32_t amount);
// Up reference. Owned by the QuicTransportProxy client.
QuicTransportProxy* transport_proxy_ = nullptr;
@@ -85,10 +90,10 @@ class QuicStreamProxy final : public base::SupportsWeakPtr<QuicStreamProxy> {
// Back reference. Owned by the RTCQuicTransport.
Delegate* delegate_ = nullptr;
- // |readable_| transitions to false when OnRemoteFinish() is called.
+ // |readable_| transitions to false when OnDataReceived(_, true) is called.
bool readable_ = true;
- // |writeable_| transitions to false when Finish() is called.
- bool writeable_ = true;
+ // |writable_| transitions to false when WriteData(_, true) is called.
+ bool writable_ = true;
THREAD_CHECKER(thread_checker_);
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.cc
index cc99a068d8e..5cddf17200a 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -36,20 +36,16 @@ QuicTransportHost::~QuicTransportHost() {
}
}
-void QuicTransportHost::Initialize(
- IceTransportHost* ice_transport_host,
- quic::Perspective perspective,
- const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates) {
+void QuicTransportHost::Initialize(IceTransportHost* ice_transport_host,
+ const P2PQuicTransportConfig& config) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(ice_transport_host);
DCHECK(!ice_transport_host_);
ice_transport_host_ = ice_transport_host;
- P2PQuicTransportConfig config(
- this, ice_transport_host->ConnectConsumer(this)->packet_transport(),
- certificates);
- config.is_server = (perspective == quic::Perspective::IS_SERVER);
- quic_transport_ =
- quic_transport_factory_->CreateQuicTransport(std::move(config));
+ IceTransportAdapter* ice_transport_adapter =
+ ice_transport_host_->ConnectConsumer(this);
+ quic_transport_ = quic_transport_factory_->CreateQuicTransport(
+ /*delegate=*/this, ice_transport_adapter->packet_transport(), config);
}
scoped_refptr<base::SingleThreadTaskRunner> QuicTransportHost::proxy_thread()
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h
index 82b52eeb929..8a8927b400a 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h
@@ -13,11 +13,11 @@
#include "base/threading/thread_checker.h"
#include "net/third_party/quic/core/quic_types.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h"
namespace blink {
class IceTransportHost;
-class P2PQuicTransportFactory;
class QuicStreamHost;
class QuicTransportProxy;
@@ -50,10 +50,8 @@ class QuicTransportHost final : public P2PQuicTransport::Delegate {
std::unique_ptr<P2PQuicTransportFactory> quic_transport_factory);
~QuicTransportHost() override;
- void Initialize(
- IceTransportHost* ice_transport_host,
- quic::Perspective perspective,
- const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates);
+ void Initialize(IceTransportHost* ice_transport_host,
+ const P2PQuicTransportConfig& config);
scoped_refptr<base::SingleThreadTaskRunner> proxy_thread() const;
scoped_refptr<base::SingleThreadTaskRunner> host_thread() const;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.cc b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.cc
index af29f9e0546..66343f40130 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.cc
@@ -12,16 +12,15 @@
#include "third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_host.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
QuicTransportProxy::QuicTransportProxy(
Delegate* delegate,
IceTransportProxy* ice_transport_proxy,
- quic::Perspective perspective,
- const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates,
- std::unique_ptr<P2PQuicTransportFactory> quic_transport_factory)
+ std::unique_ptr<P2PQuicTransportFactory> quic_transport_factory,
+ const P2PQuicTransportConfig& config)
: host_(nullptr,
base::OnTaskRunnerDeleter(ice_transport_proxy->host_thread())),
delegate_(delegate),
@@ -46,11 +45,11 @@ QuicTransportProxy::QuicTransportProxy(
// object.
IceTransportHost* ice_transport_host =
ice_transport_proxy->ConnectConsumer(this);
- PostCrossThreadTask(*host_thread(), FROM_HERE,
- CrossThreadBind(&QuicTransportHost::Initialize,
- CrossThreadUnretained(host_.get()),
- CrossThreadUnretained(ice_transport_host),
- perspective, certificates));
+ PostCrossThreadTask(
+ *host_thread(), FROM_HERE,
+ CrossThreadBind(&QuicTransportHost::Initialize,
+ CrossThreadUnretained(host_.get()),
+ CrossThreadUnretained(ice_transport_host), config));
}
QuicTransportProxy::~QuicTransportProxy() {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h
index 004aced7f9d..c0eaa7aecda 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h
@@ -12,11 +12,10 @@
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_checker.h"
-#include "net/third_party/quic/core/quic_types.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/p2p_quic_transport_factory.h"
#include "third_party/webrtc/rtc_base/scoped_ref_ptr.h"
namespace rtc {
-class RTCCertificate;
struct SSLFingerprint;
} // namespace rtc
@@ -25,7 +24,6 @@ namespace blink {
class IceTransportProxy;
class QuicStreamProxy;
class QuicTransportHost;
-class P2PQuicTransportFactory;
// This class allows the QUIC implementation (P2PQuicTransport) to run on a
// thread different from the thread from which it is controlled. All
@@ -66,9 +64,8 @@ class QuicTransportProxy final {
QuicTransportProxy(
Delegate* delegate,
IceTransportProxy* ice_transport_proxy,
- quic::Perspective perspective,
- const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates,
- std::unique_ptr<P2PQuicTransportFactory> quic_transport_factory);
+ std::unique_ptr<P2PQuicTransportFactory> quic_transport_factory,
+ const P2PQuicTransportConfig& config);
~QuicTransportProxy();
scoped_refptr<base::SingleThreadTaskRunner> proxy_thread() const;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h
index 73ab10b27a1..1f11477a4ca 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h
@@ -28,6 +28,8 @@ class SocketAddress;
namespace blink {
+struct P2PQuicTransportConfig;
+
template <>
struct CrossThreadCopier<std::string>
: public CrossThreadCopierPassThrough<std::string> {
@@ -86,6 +88,12 @@ struct CrossThreadCopier<std::pair<cricket::Candidate, cricket::Candidate>>
STATIC_ONLY(CrossThreadCopier);
};
+template <>
+struct CrossThreadCopier<P2PQuicTransportConfig>
+ : public CrossThreadCopierPassThrough<P2PQuicTransportConfig> {
+ STATIC_ONLY(CrossThreadCopier);
+};
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_WEB_RTC_CROSS_THREAD_COPIER_H_
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.cc b/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.cc
new file mode 100644
index 00000000000..defda76f8e3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.cc
@@ -0,0 +1,71 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h"
+
+namespace blink {
+
+wtf_size_t ByteBufferQueue::ReadInto(base::span<uint8_t> buffer_out) {
+ wtf_size_t read_amount = 0;
+ while (!buffer_out.empty() && !deque_of_buffers_.empty()) {
+ base::span<const uint8_t> front_buffer =
+ base::make_span(deque_of_buffers_.front())
+ .subspan(front_buffer_offset_);
+ DCHECK_GT(front_buffer.size(), 0u);
+ wtf_size_t buffer_read_amount =
+ std::min(buffer_out.size(), front_buffer.size());
+ memcpy(buffer_out.data(), front_buffer.data(), buffer_read_amount);
+ read_amount += buffer_read_amount;
+ buffer_out = buffer_out.subspan(buffer_read_amount);
+ if (buffer_read_amount < front_buffer.size()) {
+ front_buffer_offset_ += buffer_read_amount;
+ } else {
+ deque_of_buffers_.pop_front();
+ front_buffer_offset_ = 0;
+ }
+ }
+ size_ -= read_amount;
+#if DCHECK_IS_ON()
+ CheckInvariants();
+#endif
+ return read_amount;
+}
+
+void ByteBufferQueue::Append(Vector<uint8_t> buffer) {
+ if (buffer.IsEmpty()) {
+ return;
+ }
+ size_ += buffer.size();
+ deque_of_buffers_.push_back(std::move(buffer));
+#if DCHECK_IS_ON()
+ CheckInvariants();
+#endif
+}
+
+void ByteBufferQueue::Clear() {
+ deque_of_buffers_.clear();
+ front_buffer_offset_ = 0;
+ size_ = 0;
+#if DCHECK_IS_ON()
+ CheckInvariants();
+#endif
+}
+
+#if DCHECK_IS_ON()
+void ByteBufferQueue::CheckInvariants() const {
+ wtf_size_t buffer_size_sum = 0;
+ for (const auto& buffer : deque_of_buffers_) {
+ DCHECK(!buffer.IsEmpty());
+ buffer_size_sum += buffer.size();
+ }
+ DCHECK_EQ(size_, buffer_size_sum - front_buffer_offset_);
+ if (deque_of_buffers_.empty()) {
+ DCHECK_EQ(front_buffer_offset_, 0u);
+ } else {
+ DCHECK_LT(front_buffer_offset_, deque_of_buffers_.front().size());
+ }
+}
+#endif
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h b/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h
new file mode 100644
index 00000000000..e6b8aea0752
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h
@@ -0,0 +1,65 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_BYTE_BUFFER_QUEUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_BYTE_BUFFER_QUEUE_H_
+
+#include "base/containers/span.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+#include "third_party/blink/renderer/platform/wtf/deque.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+// A ByteBufferQueue is a byte buffer with O(1) append and O(n) read operations.
+// Clients can append entire byte buffers then copy data out across buffer
+// boundaries using |ReadInto|.
+class MODULES_EXPORT ByteBufferQueue final {
+ public:
+ // Number of bytes that can be read.
+ wtf_size_t size() const { return size_; }
+
+ // True if size() == 0.
+ bool empty() const { return size_ == 0; }
+
+ // Copies data into the given byte span. This will cause bytes to be consumed
+ // so that the next call to ReadInto will return different bytes.
+ // Returns the number of bytes written to |buffer_out|.
+ wtf_size_t ReadInto(base::span<uint8_t> buffer_out);
+
+ // Appends the contents of a byte buffer. This takes ownership of the buffer.
+ void Append(Vector<uint8_t> buffer);
+
+ // Clear stored buffers.
+ void Clear();
+
+ private:
+#if DCHECK_IS_ON()
+ void CheckInvariants() const;
+#endif
+
+ // Number of bytes that can be read.
+ // |Append()| adds to this number.
+ // |ReadInto()| subtracts from this number.
+ // Invariant: |size_| = sum of |deque_of_buffers_| element sizes -
+ // |front_buffer_offset_|.
+ wtf_size_t size_ = 0;
+
+ // Double-ended queue of byte buffers.
+ // |Append()| pushes to the right.
+ // |ReadInto()| pops from the left (if an entire buffer has been read).
+ // Invariant: No element in |deque_of_buffers_| is empty.
+ Deque<Vector<uint8_t>> deque_of_buffers_;
+
+ // The offset from which to start reading the buffer at the front of
+ // |deque_of_buffers_|.
+ // Invariants:
+ // - If |deque_of_buffers_| is empty, |front_buffer_offset_| = 0.
+ // - Otherwise, |front_buffer_offset_| < |deque_of_buffers_|.front().size().
+ wtf_size_t front_buffer_offset_ = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_BYTE_BUFFER_QUEUE_H_
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue_test.cc
new file mode 100644
index 00000000000..0df503cce46
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/byte_buffer_queue_test.cc
@@ -0,0 +1,127 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h"
+#include "testing/gmock/include/gmock/gmock.h"
+
+namespace blink {
+
+using testing::ElementsAre;
+
+TEST(ByteBufferQueueTest, DefaultConstructor) {
+ ByteBufferQueue buffer_queue;
+ EXPECT_EQ(0u, buffer_queue.size());
+ EXPECT_TRUE(buffer_queue.empty());
+}
+
+TEST(ByteBufferQueueTest, AppendEmpty) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({});
+ EXPECT_TRUE(buffer_queue.empty());
+}
+
+TEST(ByteBufferQueueTest, AppendOneSegment) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ EXPECT_EQ(3u, buffer_queue.size());
+}
+
+TEST(ByteBufferQueueTest, AppendTwoSegments) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ buffer_queue.Append({4, 5});
+ EXPECT_EQ(5u, buffer_queue.size());
+}
+
+TEST(ByteBufferQueueTest, ReadIntoEmpty) {
+ ByteBufferQueue buffer_queue;
+ Vector<uint8_t> data(100);
+ EXPECT_EQ(0u, buffer_queue.ReadInto(base::make_span(data)));
+}
+
+TEST(ByteBufferQueueTest, ReadIntoLessThanOneSegment) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ Vector<uint8_t> data(2);
+ EXPECT_EQ(2u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_EQ(1u, buffer_queue.size());
+ EXPECT_THAT(data, ElementsAre(1, 2));
+}
+
+TEST(ByteBufferQueueTest, ReadIntoExactOneSegmentSize) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ Vector<uint8_t> data(3);
+ EXPECT_EQ(3u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_EQ(0u, buffer_queue.size());
+ EXPECT_THAT(data, ElementsAre(1, 2, 3));
+}
+
+TEST(ByteBufferQueueTest, ReadIntoOverOneSegmentSize) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ Vector<uint8_t> data(5);
+ EXPECT_EQ(3u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_EQ(0u, buffer_queue.size());
+ EXPECT_THAT(data, ElementsAre(1, 2, 3, 0, 0));
+}
+
+TEST(ByteBufferQueueTest, ReadIntoEmptyData) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ Vector<uint8_t> data;
+ EXPECT_EQ(0u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_EQ(3u, buffer_queue.size());
+}
+
+TEST(ByteBufferQueueTest, ReadIntoExactlyTwoSegments) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ buffer_queue.Append({4, 5});
+ Vector<uint8_t> data(5);
+ EXPECT_EQ(5u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_EQ(0u, buffer_queue.size());
+ EXPECT_THAT(data, ElementsAre(1, 2, 3, 4, 5));
+}
+
+TEST(ByteBufferQueueTest, ReadIntoAcrossTwoSegmentsMisaligned) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Append({1, 2, 3});
+ buffer_queue.Append({4, 5});
+
+ Vector<uint8_t> data(2);
+ EXPECT_EQ(2u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_THAT(data, ElementsAre(1, 2));
+
+ EXPECT_EQ(2u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_THAT(data, ElementsAre(3, 4));
+
+ EXPECT_EQ(1u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_THAT(data, ElementsAre(5, 4));
+}
+
+TEST(ByteBufferQueueTest, ClearEmptyBuffer) {
+ ByteBufferQueue buffer_queue;
+ buffer_queue.Clear();
+ EXPECT_EQ(0u, buffer_queue.size());
+ EXPECT_TRUE(buffer_queue.empty());
+}
+
+TEST(ByteBufferQueueTest, ReadIntoAfterClearThenAppend) {
+ ByteBufferQueue buffer_queue;
+
+ buffer_queue.Append({1, 2, 3});
+ Vector<uint8_t> data(2);
+ buffer_queue.ReadInto(base::make_span(data));
+
+ buffer_queue.Clear();
+ EXPECT_EQ(0u, buffer_queue.size());
+ EXPECT_EQ(0u, buffer_queue.ReadInto(base::make_span(data)));
+
+ buffer_queue.Append({4, 5});
+ EXPECT_EQ(2u, buffer_queue.ReadInto(base::make_span(data)));
+ EXPECT_THAT(data, ElementsAre(4, 5));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.cc b/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.cc
new file mode 100644
index 00000000000..168dbf5f012
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.cc
@@ -0,0 +1,144 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h"
+
+namespace blink {
+
+namespace {
+
+bool IsRejectedOffererState(OffererState state) {
+ return state == OffererState::kCreateOfferRejected ||
+ state == OffererState::kSetLocalOfferRejected ||
+ state == OffererState::kSetRemoteAnswerRejected;
+}
+
+bool IsRejectedAnswererState(AnswererState state) {
+ return state == AnswererState::kSetRemoteOfferRejected ||
+ state == AnswererState::kCreateAnswerRejected ||
+ state == AnswererState::kSetLocalAnswerRejected;
+}
+
+} // namespace
+
+CallSetupStateTracker::CallSetupStateTracker()
+ : valid_offerer_transitions_(
+ {std::make_pair(OffererState::kNotStarted,
+ OffererState::kCreateOfferPending),
+ // createOffer()
+ std::make_pair(OffererState::kCreateOfferPending,
+ OffererState::kCreateOfferRejected),
+ std::make_pair(OffererState::kCreateOfferPending,
+ OffererState::kCreateOfferResolved),
+ std::make_pair(OffererState::kCreateOfferRejected,
+ OffererState::kCreateOfferResolved),
+ std::make_pair(OffererState::kCreateOfferResolved,
+ OffererState::kSetLocalOfferPending),
+ // setLocalDescription(offer)
+ std::make_pair(OffererState::kSetLocalOfferPending,
+ OffererState::kSetLocalOfferRejected),
+ std::make_pair(OffererState::kSetLocalOfferPending,
+ OffererState::kSetLocalOfferResolved),
+ std::make_pair(OffererState::kSetLocalOfferRejected,
+ OffererState::kSetLocalOfferResolved),
+ std::make_pair(OffererState::kSetLocalOfferResolved,
+ OffererState::kSetRemoteAnswerPending),
+ // setRemoteDescription(answer)
+ std::make_pair(OffererState::kSetRemoteAnswerPending,
+ OffererState::kSetRemoteAnswerRejected),
+ std::make_pair(OffererState::kSetRemoteAnswerPending,
+ OffererState::kSetRemoteAnswerResolved),
+ std::make_pair(OffererState::kSetRemoteAnswerRejected,
+ OffererState::kSetRemoteAnswerResolved)}),
+ valid_answerer_transitions_({
+ std::make_pair(AnswererState::kNotStarted,
+ AnswererState::kSetRemoteOfferPending),
+ // setRemoteDescription(answer)
+ std::make_pair(AnswererState::kSetRemoteOfferPending,
+ AnswererState::kSetRemoteOfferRejected),
+ std::make_pair(AnswererState::kSetRemoteOfferPending,
+ AnswererState::kSetRemoteOfferResolved),
+ std::make_pair(AnswererState::kSetRemoteOfferRejected,
+ AnswererState::kSetRemoteOfferResolved),
+ std::make_pair(AnswererState::kSetRemoteOfferResolved,
+ AnswererState::kCreateAnswerPending),
+ // createAnswer()
+ std::make_pair(AnswererState::kCreateAnswerPending,
+ AnswererState::kCreateAnswerRejected),
+ std::make_pair(AnswererState::kCreateAnswerPending,
+ AnswererState::kCreateAnswerResolved),
+ std::make_pair(AnswererState::kCreateAnswerRejected,
+ AnswererState::kCreateAnswerResolved),
+ std::make_pair(AnswererState::kCreateAnswerResolved,
+ AnswererState::kSetLocalAnswerPending),
+ // setLocalDescription(answer)
+ std::make_pair(AnswererState::kSetLocalAnswerPending,
+ AnswererState::kSetLocalAnswerRejected),
+ std::make_pair(AnswererState::kSetLocalAnswerPending,
+ AnswererState::kSetLocalAnswerResolved),
+ std::make_pair(AnswererState::kSetLocalAnswerRejected,
+ AnswererState::kSetLocalAnswerResolved),
+ }),
+ offerer_state_(OffererState::kNotStarted),
+ answerer_state_(AnswererState::kNotStarted),
+ has_ever_failed_(false),
+ document_uses_media_(false) {}
+
+OffererState CallSetupStateTracker::offerer_state() const {
+ return offerer_state_;
+}
+
+AnswererState CallSetupStateTracker::answerer_state() const {
+ return answerer_state_;
+}
+
+bool CallSetupStateTracker::document_uses_media() const {
+ return document_uses_media_;
+}
+
+CallSetupState CallSetupStateTracker::GetCallSetupState() const {
+ if (offerer_state_ == OffererState::kNotStarted &&
+ answerer_state_ == AnswererState::kNotStarted) {
+ return CallSetupState::kNotStarted;
+ }
+ if (offerer_state_ == OffererState::kSetRemoteAnswerResolved ||
+ answerer_state_ == AnswererState::kSetLocalAnswerResolved) {
+ return CallSetupState::kSucceeded;
+ }
+ if (has_ever_failed_)
+ return CallSetupState::kFailed;
+ return CallSetupState::kStarted;
+}
+
+bool CallSetupStateTracker::NoteOffererStateEvent(OffererState event,
+ bool document_uses_media) {
+ if (document_uses_media)
+ document_uses_media_ = true;
+ auto transition = std::make_pair(offerer_state_, event);
+ if (valid_offerer_transitions_.find(transition) ==
+ valid_offerer_transitions_.end()) {
+ return false;
+ }
+ offerer_state_ = event;
+ if (IsRejectedOffererState(offerer_state_))
+ has_ever_failed_ = true;
+ return true;
+}
+
+bool CallSetupStateTracker::NoteAnswererStateEvent(AnswererState event,
+ bool document_uses_media) {
+ if (document_uses_media)
+ document_uses_media_ = true;
+ auto transition = std::make_pair(answerer_state_, event);
+ if (valid_answerer_transitions_.find(transition) ==
+ valid_answerer_transitions_.end()) {
+ return false;
+ }
+ answerer_state_ = event;
+ if (IsRejectedAnswererState(answerer_state_))
+ has_ever_failed_ = true;
+ return true;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h b/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h
new file mode 100644
index 00000000000..1c2e10736b9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h
@@ -0,0 +1,135 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_CALL_SETUP_STATE_TRACKER_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_CALL_SETUP_STATE_TRACKER_H_
+
+#include <set>
+#include <utility>
+
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace blink {
+
+// Represents the different states that an offerer can go through during call
+// setup, where later steps involve SDP exchange.
+//
+// Valid transitions are from an operation's "pending" to "resolved" or
+// "rejected" state. "Rejected" can transition to "resolved" if another attempt
+// is made (without going to "pending" in-between). Only "resolved" can
+// transition to the next operation's "pending" state. Transition between
+// operations are only valid in the defined order.
+//
+// The model we are using is one that measures how close we get to establishing
+// a connection. In reality, the peer connection may make multiple tries, and
+// follow multiple paths towards reaching a connected state, but we're only
+// interested in seeing how far it got on its most successful attempt.
+enum class OffererState {
+ kNotStarted = 0,
+ // createOffer()
+ kCreateOfferPending = 1,
+ kCreateOfferRejected = 2,
+ kCreateOfferResolved = 3,
+ // setLocalDescription(offer)
+ kSetLocalOfferPending = 4,
+ kSetLocalOfferRejected = 5,
+ kSetLocalOfferResolved = 6,
+ // setRemoteDescription(answer)
+ kSetRemoteAnswerPending = 7,
+ kSetRemoteAnswerRejected = 8,
+ kSetRemoteAnswerResolved = 9,
+
+ kMaxValue = kSetRemoteAnswerResolved,
+};
+
+// Represents the different states that an answerer can go through during call
+// setup, where initial steps involve SDP exchange. The transition graph for
+// this enum follows the same logic as OffererState, see above.
+enum class AnswererState {
+ kNotStarted = 0,
+ // setRemoteDescription(offer)
+ kSetRemoteOfferPending = 1,
+ kSetRemoteOfferRejected = 2,
+ kSetRemoteOfferResolved = 3,
+ // createAnswer()
+ kCreateAnswerPending = 4,
+ kCreateAnswerRejected = 5,
+ kCreateAnswerResolved = 6,
+ // setLocalDescription(answer)
+ kSetLocalAnswerPending = 7,
+ kSetLocalAnswerRejected = 8,
+ kSetLocalAnswerResolved = 9,
+
+ kMaxValue = kSetLocalAnswerResolved,
+};
+
+// A metric reflecting the most successful attempt towards reaching a connected
+// state. It's a simplified view based on a CallSetupStateTracker's OffererState
+// and AnswererState. Transition graph:
+//
+// kNotStarted
+// v
+// kStarted ----+
+// v |
+// kFailed |
+// v |
+// kSucceded <--+
+//
+enum class CallSetupState {
+ // OffererState and AnswererState are both in kNotStarted.
+ kNotStarted = 0,
+ // OffererState or AnswererState have had a value other than kNotStarted, but
+ // the conditions for any of the other states have not been reached.
+ kStarted = 1,
+ // OffererState or AnswererState have or have had one of the "rejected"
+ // states, and the condition for kSucceeded has not been reached.
+ kFailed = 2,
+ // OffererState or AnswererState is in the final "resolved" state -
+ // OffererState::kSetRemoteAnswerResolved or
+ // AnswererState::kSetLocalAnswerResolved.
+ kSucceeded = 3,
+
+ kMaxValue = kSucceeded,
+};
+
+class MODULES_EXPORT CallSetupStateTracker {
+ public:
+ CallSetupStateTracker();
+
+ OffererState offerer_state() const;
+ AnswererState answerer_state() const;
+ CallSetupState GetCallSetupState() const;
+ bool document_uses_media() const;
+
+ // The |event| describes what event just happened, see enum definitions.
+ // The |document_uses_media| parameter is meant to reflect whether or not the
+ // document is using media, such as if getUserMedia() has ever been called
+ // (this is up to the caller). The tracker remembers if this has ever been
+ // true with document_uses_media() which allows the tracker to know about this
+ // even if it outlives the document. If it has ever been true,
+ // document_uses_media() stays true even if subsequent calls are made with the
+ // value false.
+ bool NoteOffererStateEvent(OffererState event, bool document_uses_media);
+ bool NoteAnswererStateEvent(AnswererState event, bool document_uses_media);
+
+ private:
+ const std::set<std::pair<OffererState, OffererState>>
+ valid_offerer_transitions_;
+ const std::set<std::pair<AnswererState, AnswererState>>
+ valid_answerer_transitions_;
+
+ OffererState offerer_state_;
+ AnswererState answerer_state_;
+ // If the tracker has ever been in any of the "rejected" states. This remains
+ // true even if the peer connection recovers to a non-"rejected" state.
+ bool has_ever_failed_;
+ // If the document has ever been noted to use media based on
+ // Note[Offerer/Answerer]StateEvent() calls. Once true, this value will never
+ // be false again.
+ bool document_uses_media_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_CALL_SETUP_STATE_TRACKER_H_
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker_unittest.cc b/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker_unittest.cc
new file mode 100644
index 00000000000..fc0eca4bf9a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker_unittest.cc
@@ -0,0 +1,408 @@
+// Copyright (c) 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace blink {
+
+namespace {
+
+template <typename StateType>
+std::vector<StateType> GetAllCallSetupStates();
+
+template <>
+std::vector<OffererState> GetAllCallSetupStates() {
+ std::vector<OffererState> states = {OffererState::kNotStarted,
+ OffererState::kCreateOfferPending,
+ OffererState::kCreateOfferRejected,
+ OffererState::kCreateOfferResolved,
+ OffererState::kSetLocalOfferPending,
+ OffererState::kSetLocalOfferRejected,
+ OffererState::kSetLocalOfferResolved,
+ OffererState::kSetRemoteAnswerPending,
+ OffererState::kSetRemoteAnswerRejected,
+ OffererState::kSetRemoteAnswerResolved};
+ EXPECT_EQ(static_cast<size_t>(OffererState::kMaxValue) + 1u, states.size());
+ return states;
+}
+
+template <>
+std::vector<AnswererState> GetAllCallSetupStates() {
+ std::vector<AnswererState> states = {AnswererState::kNotStarted,
+ AnswererState::kSetRemoteOfferPending,
+ AnswererState::kSetRemoteOfferRejected,
+ AnswererState::kSetRemoteOfferResolved,
+ AnswererState::kCreateAnswerPending,
+ AnswererState::kCreateAnswerRejected,
+ AnswererState::kCreateAnswerResolved,
+ AnswererState::kSetLocalAnswerPending,
+ AnswererState::kSetLocalAnswerRejected,
+ AnswererState::kSetLocalAnswerResolved};
+ EXPECT_EQ(static_cast<size_t>(AnswererState::kMaxValue) + 1u, states.size());
+ return states;
+}
+
+} // namespace
+
+class CallSetupStateTrackerTest : public testing::Test {
+ public:
+ enum class Reachability {
+ kReachable,
+ kUnreachable,
+ };
+
+ template <typename StateType>
+ StateType current_state() const;
+
+ bool NoteStateEvent(CallSetupStateTracker* tracker,
+ OffererState event) const {
+ return tracker->NoteOffererStateEvent(event, false);
+ }
+
+ bool NoteStateEvent(CallSetupStateTracker* tracker,
+ AnswererState event) const {
+ return tracker->NoteAnswererStateEvent(event, false);
+ }
+
+ template <typename StateType>
+ bool VerifyReachability(Reachability reachability,
+ std::vector<StateType> states) const {
+ bool expected_state_reached = (reachability == Reachability::kReachable);
+ for (const auto& state : states) {
+ bool did_reach_state;
+ if (state == current_state<StateType>()) {
+ // The current state always counts as reachable.
+ did_reach_state = true;
+ } else {
+ // Perform the test on a copy to avoid mutating |tracker_|.
+ CallSetupStateTracker tracker_copy = tracker_;
+ did_reach_state = NoteStateEvent(&tracker_copy, state);
+ }
+ if (did_reach_state != expected_state_reached)
+ return false;
+ }
+ return true;
+ }
+
+ template <typename StateType>
+ bool VerifyOnlyReachableStates(std::vector<StateType> reachable_states,
+ bool include_current = true) const {
+ if (include_current)
+ reachable_states.push_back(current_state<StateType>());
+ std::vector<StateType> unreachable_states =
+ GetAllCallSetupStates<StateType>();
+ for (const auto& reachable_state : reachable_states) {
+ unreachable_states.erase(std::find(unreachable_states.begin(),
+ unreachable_states.end(),
+ reachable_state));
+ }
+ return VerifyReachability<StateType>(Reachability::kReachable,
+ reachable_states) &&
+ VerifyReachability<StateType>(Reachability::kUnreachable,
+ unreachable_states);
+ }
+
+ protected:
+ CallSetupStateTracker tracker_;
+};
+
+// The following two template specializations can be moved to the class
+// declaration once we officially switch to C++17 (we need C++ DR727 to be
+// implemented).
+template <>
+OffererState CallSetupStateTrackerTest::current_state() const {
+ return tracker_.offerer_state();
+}
+
+template <>
+AnswererState CallSetupStateTrackerTest::current_state() const {
+ return tracker_.answerer_state();
+}
+
+TEST_F(CallSetupStateTrackerTest, InitialState) {
+ EXPECT_EQ(OffererState::kNotStarted, tracker_.offerer_state());
+ EXPECT_EQ(AnswererState::kNotStarted, tracker_.answerer_state());
+ EXPECT_EQ(CallSetupState::kNotStarted, tracker_.GetCallSetupState());
+ EXPECT_FALSE(tracker_.document_uses_media());
+}
+
+TEST_F(CallSetupStateTrackerTest, OffererSuccessfulNegotiation) {
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kCreateOfferPending}));
+ EXPECT_TRUE(
+ tracker_.NoteOffererStateEvent(OffererState::kCreateOfferPending, false));
+ EXPECT_EQ(OffererState::kCreateOfferPending, tracker_.offerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kCreateOfferResolved,
+ OffererState::kCreateOfferRejected}));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(OffererState::kCreateOfferResolved,
+ false));
+ EXPECT_EQ(OffererState::kCreateOfferResolved, tracker_.offerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kSetLocalOfferPending}));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferPending, false));
+ EXPECT_EQ(OffererState::kSetLocalOfferPending, tracker_.offerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kSetLocalOfferResolved,
+ OffererState::kSetLocalOfferRejected}));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferResolved, false));
+ EXPECT_EQ(OffererState::kSetLocalOfferResolved, tracker_.offerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kSetRemoteAnswerPending}));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerPending, false));
+ EXPECT_EQ(OffererState::kSetRemoteAnswerPending, tracker_.offerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kSetRemoteAnswerResolved,
+ OffererState::kSetRemoteAnswerRejected}));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerResolved, false));
+ EXPECT_EQ(OffererState::kSetRemoteAnswerResolved, tracker_.offerer_state());
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>({}));
+}
+
+TEST_F(CallSetupStateTrackerTest, OffererCreateOfferRejected) {
+ EXPECT_TRUE(
+ tracker_.NoteOffererStateEvent(OffererState::kCreateOfferPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(OffererState::kCreateOfferRejected,
+ false));
+ EXPECT_EQ(OffererState::kCreateOfferRejected, tracker_.offerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kCreateOfferResolved}));
+}
+
+TEST_F(CallSetupStateTrackerTest, OffererSetLocalOfferRejected) {
+ EXPECT_TRUE(
+ tracker_.NoteOffererStateEvent(OffererState::kCreateOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(OffererState::kCreateOfferResolved,
+ false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferRejected, false));
+ EXPECT_EQ(OffererState::kSetLocalOfferRejected, tracker_.offerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kSetLocalOfferResolved}));
+}
+
+TEST_F(CallSetupStateTrackerTest, OffererSetRemoteAnswerRejected) {
+ EXPECT_TRUE(
+ tracker_.NoteOffererStateEvent(OffererState::kCreateOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(OffererState::kCreateOfferResolved,
+ false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferResolved, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerRejected, false));
+ EXPECT_EQ(OffererState::kSetRemoteAnswerRejected, tracker_.offerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<OffererState>(
+ {OffererState::kSetRemoteAnswerResolved}));
+}
+
+TEST_F(CallSetupStateTrackerTest, OffererRejectThenSucceed) {
+ EXPECT_TRUE(
+ tracker_.NoteOffererStateEvent(OffererState::kCreateOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(OffererState::kCreateOfferResolved,
+ false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferResolved, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerRejected, false));
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ // Pending another operation should not revert the states to "pending" or
+ // "started".
+ EXPECT_FALSE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerResolved, false));
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_.GetCallSetupState());
+}
+
+TEST_F(CallSetupStateTrackerTest, AnswererSuccessfulNegotiation) {
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kSetRemoteOfferPending}));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, false));
+ EXPECT_EQ(AnswererState::kSetRemoteOfferPending, tracker_.answerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kSetRemoteOfferResolved,
+ AnswererState::kSetRemoteOfferRejected}));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferResolved, false));
+ EXPECT_EQ(AnswererState::kSetRemoteOfferResolved, tracker_.answerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kCreateAnswerPending}));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerPending, false));
+ EXPECT_EQ(AnswererState::kCreateAnswerPending, tracker_.answerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kCreateAnswerResolved,
+ AnswererState::kCreateAnswerRejected}));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerResolved, false));
+ EXPECT_EQ(AnswererState::kCreateAnswerResolved, tracker_.answerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kSetLocalAnswerPending}));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerPending, false));
+ EXPECT_EQ(AnswererState::kSetLocalAnswerPending, tracker_.answerer_state());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kSetLocalAnswerResolved,
+ AnswererState::kSetLocalAnswerRejected}));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerResolved, false));
+ EXPECT_EQ(AnswererState::kSetLocalAnswerResolved, tracker_.answerer_state());
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>({}));
+}
+
+TEST_F(CallSetupStateTrackerTest, AnswererSetRemoteOfferRejected) {
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferRejected, false));
+ EXPECT_EQ(AnswererState::kSetRemoteOfferRejected, tracker_.answerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kSetRemoteOfferResolved}));
+}
+
+TEST_F(CallSetupStateTrackerTest, AnswererCreateAnswerRejected) {
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferResolved, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerRejected, false));
+ EXPECT_EQ(AnswererState::kCreateAnswerRejected, tracker_.answerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kCreateAnswerResolved}));
+}
+
+TEST_F(CallSetupStateTrackerTest, AnswererSetLocalAnswerRejected) {
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferResolved, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerPending, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerResolved, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerRejected, false));
+ EXPECT_EQ(AnswererState::kSetLocalAnswerRejected, tracker_.answerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(VerifyOnlyReachableStates<AnswererState>(
+ {AnswererState::kSetLocalAnswerResolved}));
+}
+
+TEST_F(CallSetupStateTrackerTest, AnswererRejectThenSucceed) {
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferResolved, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerPending, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerResolved, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kStarted, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerRejected, false));
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ // Pending another operation should not revert the states to "pending" or
+ // "started".
+ EXPECT_FALSE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerPending, false));
+ EXPECT_EQ(CallSetupState::kFailed, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerResolved, false));
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_.GetCallSetupState());
+}
+
+// Succeeding in one role and subsequently failing in another should not revert
+// the call setup state from kSucceeded; the most succeessful attempt would
+// still have been successful.
+TEST_F(CallSetupStateTrackerTest, OffererSucceedAnswererFail) {
+ EXPECT_TRUE(
+ tracker_.NoteOffererStateEvent(OffererState::kCreateOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(OffererState::kCreateOfferResolved,
+ false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferResolved, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerPending, false));
+ EXPECT_TRUE(tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerResolved, false));
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_.GetCallSetupState());
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, false));
+ EXPECT_TRUE(tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferRejected, false));
+ // Still succeeded.
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_.GetCallSetupState());
+}
+
+TEST_F(CallSetupStateTrackerTest, SetDocumentMedia) {
+ // Any offerer state event can set document_uses_media().
+ for (auto offerer_state : GetAllCallSetupStates<OffererState>()) {
+ CallSetupStateTracker tracker;
+ EXPECT_FALSE(tracker.document_uses_media());
+ tracker.NoteOffererStateEvent(offerer_state, true);
+ EXPECT_TRUE(tracker.document_uses_media());
+ }
+ // Any answerer state event can set document_uses_media().
+ for (auto answerer_state : GetAllCallSetupStates<AnswererState>()) {
+ CallSetupStateTracker tracker;
+ EXPECT_FALSE(tracker.document_uses_media());
+ tracker.NoteAnswererStateEvent(answerer_state, true);
+ EXPECT_TRUE(tracker.document_uses_media());
+ }
+}
+
+TEST_F(CallSetupStateTrackerTest, DocumentMediaCannotBeUnset) {
+ tracker_.NoteOffererStateEvent(OffererState::kSetLocalOfferPending, true);
+ EXPECT_TRUE(tracker_.document_uses_media());
+ tracker_.NoteOffererStateEvent(OffererState::kSetLocalOfferResolved, false);
+ // If it has ever been true, it stays true.
+ EXPECT_TRUE(tracker_.document_uses_media());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc
index 4fd68ad6a02..d6ac0d6314d 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.cc
@@ -33,6 +33,7 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/platform/bindings/to_v8.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
+#include "third_party/webrtc/rtc_base/sslcertificate.h"
namespace blink {
@@ -44,21 +45,21 @@ DOMTimeStamp RTCCertificate::expires() const {
return static_cast<DOMTimeStamp>(certificate_->Expires());
}
-HeapVector<RTCDtlsFingerprint> RTCCertificate::getFingerprints() {
+HeapVector<Member<RTCDtlsFingerprint>> RTCCertificate::getFingerprints() {
std::unique_ptr<rtc::SSLCertificateStats> first_certificate_stats =
certificate_->ssl_certificate().GetStats();
- HeapVector<RTCDtlsFingerprint> fingerprints;
+ HeapVector<Member<RTCDtlsFingerprint>> fingerprints;
for (rtc::SSLCertificateStats* certificate_stats =
first_certificate_stats.get();
certificate_stats; certificate_stats = certificate_stats->issuer.get()) {
- fingerprints.emplace_back();
- auto& fingerprint = fingerprints.back();
- fingerprint.setAlgorithm(WTF::String::FromUTF8(
+ RTCDtlsFingerprint* fingerprint = RTCDtlsFingerprint::Create();
+ fingerprint->setAlgorithm(WTF::String::FromUTF8(
certificate_stats->fingerprint_algorithm.c_str()));
- fingerprint.setValue(
+ fingerprint->setValue(
WTF::String::FromUTF8(certificate_stats->fingerprint.c_str())
.LowerASCII());
+ fingerprints.push_back(fingerprint);
}
return fingerprints;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.h
index 4b3aa2e47d1..69dbc5a908b 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_certificate.h
@@ -57,7 +57,7 @@ class MODULES_EXPORT RTCCertificate final : public ScriptWrappable {
// Returns the expiration time in ms relative to epoch, 1970-01-01T00:00:00Z.
DOMTimeStamp expires() const;
- HeapVector<RTCDtlsFingerprint> getFingerprints();
+ HeapVector<Member<RTCDtlsFingerprint>> getFingerprints();
private:
rtc::scoped_refptr<rtc::RTCCertificate> certificate_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl
index 633321c8753..280480bcc0d 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_configuration.idl
@@ -48,4 +48,8 @@ dictionary RTCConfiguration {
[EnforceRange] octet iceCandidatePoolSize = 0;
// Nonstandard, added for Unified Plan migration
[RuntimeEnabled=RTCUnifiedPlan] SdpSemantics sdpSemantics;
+ [OriginTrialEnabled=RtcAudioJitterBufferMaxPackets] long rtcAudioJitterBufferMaxPackets;
+ [OriginTrialEnabled=RtcAudioJitterBufferMaxPackets] boolean rtcAudioJitterBufferFastAccelerate;
+ [OriginTrialEnabled=RtcAudioJitterBufferMaxPackets] long rtcAudioJitterBufferMinDelayMs;
};
+
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc
index 2c897858d57..f5d3e244130 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.cc
@@ -37,6 +37,7 @@
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -59,7 +60,8 @@ RTCDataChannel* RTCDataChannel::Create(
ExecutionContext* context,
std::unique_ptr<WebRTCDataChannelHandler> handler) {
DCHECK(handler);
- RTCDataChannel* channel = new RTCDataChannel(context, std::move(handler));
+ RTCDataChannel* channel =
+ MakeGarbageCollected<RTCDataChannel>(context, std::move(handler));
channel->PauseIfNeeded();
return channel;
@@ -78,7 +80,8 @@ RTCDataChannel* RTCDataChannel::Create(
"RTCDataChannel is not supported");
return nullptr;
}
- RTCDataChannel* channel = new RTCDataChannel(context, std::move(handler));
+ RTCDataChannel* channel =
+ MakeGarbageCollected<RTCDataChannel>(context, std::move(handler));
channel->PauseIfNeeded();
return channel;
@@ -164,7 +167,7 @@ String RTCDataChannel::readyState() const {
}
unsigned RTCDataChannel::bufferedAmount() const {
- return handler_->BufferedAmount();
+ return SafeCast<unsigned>(handler_->BufferedAmount());
}
unsigned RTCDataChannel::bufferedAmountLowThreshold() const {
@@ -258,10 +261,10 @@ void RTCDataChannel::DidChangeReadyState(
switch (ready_state_) {
case kReadyStateOpen:
- ScheduleDispatchEvent(Event::Create(EventTypeNames::open));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kOpen));
break;
case kReadyStateClosed:
- ScheduleDispatchEvent(Event::Create(EventTypeNames::close));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kClose));
break;
default:
break;
@@ -271,7 +274,7 @@ void RTCDataChannel::DidChangeReadyState(
void RTCDataChannel::DidDecreaseBufferedAmount(unsigned previous_amount) {
if (previous_amount > buffered_amount_low_threshold_ &&
bufferedAmount() <= buffered_amount_low_threshold_) {
- ScheduleDispatchEvent(Event::Create(EventTypeNames::bufferedamountlow));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kBufferedamountlow));
}
}
@@ -285,7 +288,8 @@ void RTCDataChannel::DidReceiveRawData(const char* data, size_t data_length) {
return;
}
if (binary_type_ == kBinaryTypeArrayBuffer) {
- DOMArrayBuffer* buffer = DOMArrayBuffer::Create(data, data_length);
+ DOMArrayBuffer* buffer =
+ DOMArrayBuffer::Create(data, SafeCast<unsigned>(data_length));
ScheduleDispatchEvent(MessageEvent::Create(buffer));
return;
}
@@ -293,11 +297,11 @@ void RTCDataChannel::DidReceiveRawData(const char* data, size_t data_length) {
}
void RTCDataChannel::DidDetectError() {
- ScheduleDispatchEvent(Event::Create(EventTypeNames::error));
+ ScheduleDispatchEvent(Event::Create(event_type_names::kError));
}
const AtomicString& RTCDataChannel::InterfaceName() const {
- return EventTargetNames::RTCDataChannel;
+ return event_target_names::kRTCDataChannel;
}
ExecutionContext* RTCDataChannel::GetExecutionContext() const {
@@ -341,14 +345,14 @@ bool RTCDataChannel::HasPendingActivity() const {
bool has_valid_listeners = false;
switch (ready_state_) {
case kReadyStateConnecting:
- has_valid_listeners |= HasEventListeners(EventTypeNames::open);
+ has_valid_listeners |= HasEventListeners(event_type_names::kOpen);
FALLTHROUGH;
case kReadyStateOpen:
- has_valid_listeners |= HasEventListeners(EventTypeNames::message);
+ has_valid_listeners |= HasEventListeners(event_type_names::kMessage);
FALLTHROUGH;
case kReadyStateClosing:
- has_valid_listeners |= HasEventListeners(EventTypeNames::error) ||
- HasEventListeners(EventTypeNames::close);
+ has_valid_listeners |= HasEventListeners(event_type_names::kError) ||
+ HasEventListeners(event_type_names::kClose);
break;
default:
break;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h
index 0208c245594..bcc0e81bb14 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h
@@ -64,6 +64,8 @@ class MODULES_EXPORT RTCDataChannel final
const String& label,
const WebRTCDataChannelInit&,
ExceptionState&);
+
+ RTCDataChannel(ExecutionContext*, std::unique_ptr<WebRTCDataChannelHandler>);
~RTCDataChannel() override;
ReadyState GetHandlerState() const;
@@ -95,11 +97,11 @@ class MODULES_EXPORT RTCDataChannel final
void close();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(open);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(bufferedamountlow);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(open, kOpen);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(bufferedamountlow, kBufferedamountlow);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
// EventTarget
const AtomicString& InterfaceName() const override;
@@ -123,7 +125,6 @@ class MODULES_EXPORT RTCDataChannel final
void DidDetectError() override;
private:
- RTCDataChannel(ExecutionContext*, std::unique_ptr<WebRTCDataChannelHandler>);
void Dispose();
void ScheduleDispatchEvent(Event*);
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.cc
index f5bf18b8152..9ea073423aa 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.cc
@@ -28,13 +28,13 @@ namespace blink {
RTCDataChannelEvent* RTCDataChannelEvent::Create(const AtomicString& type,
RTCDataChannel* channel) {
- return new RTCDataChannelEvent(type, channel);
+ return MakeGarbageCollected<RTCDataChannelEvent>(type, channel);
}
RTCDataChannelEvent* RTCDataChannelEvent::Create(
const AtomicString& type,
- const RTCDataChannelEventInit& initializer) {
- return new RTCDataChannelEvent(type, initializer);
+ const RTCDataChannelEventInit* initializer) {
+ return MakeGarbageCollected<RTCDataChannelEvent>(type, initializer);
}
RTCDataChannelEvent::RTCDataChannelEvent(const AtomicString& type,
@@ -43,8 +43,8 @@ RTCDataChannelEvent::RTCDataChannelEvent(const AtomicString& type,
RTCDataChannelEvent::RTCDataChannelEvent(
const AtomicString& type,
- const RTCDataChannelEventInit& initializer)
- : Event(type, initializer), channel_(initializer.channel()) {}
+ const RTCDataChannelEventInit* initializer)
+ : Event(type, initializer), channel_(initializer->channel()) {}
RTCDataChannelEvent::~RTCDataChannelEvent() = default;
@@ -53,7 +53,7 @@ RTCDataChannel* RTCDataChannelEvent::channel() const {
}
const AtomicString& RTCDataChannelEvent::InterfaceName() const {
- return EventNames::RTCDataChannelEvent;
+ return event_interface_names::kRTCDataChannelEvent;
}
void RTCDataChannelEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.h
index 79ab6cd46f3..e6efc564fd9 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_event.h
@@ -36,13 +36,15 @@ class RTCDataChannelEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ RTCDataChannelEvent(const AtomicString& type, RTCDataChannel*);
+ RTCDataChannelEvent(const AtomicString& type, const RTCDataChannelEventInit*);
~RTCDataChannelEvent() override;
static RTCDataChannelEvent* Create(const AtomicString& type,
RTCDataChannel*);
static RTCDataChannelEvent* Create(const AtomicString& type,
- const RTCDataChannelEventInit&);
+ const RTCDataChannelEventInit*);
RTCDataChannel* channel() const;
@@ -51,10 +53,6 @@ class RTCDataChannelEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- RTCDataChannelEvent(const AtomicString& type,
- RTCDataChannel*);
-
- RTCDataChannelEvent(const AtomicString& type, const RTCDataChannelEventInit&);
Member<RTCDataChannel> channel_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc
index 5e13deab339..ceab4fae201 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_data_channel_test.cc
@@ -64,7 +64,8 @@ class MockHandler final : public WebRTCDataChannelHandler {
unsigned long old_buffered_amount = buffered_amount_;
buffered_amount_ -= bytes;
if (client_) {
- client_->DidDecreaseBufferedAmount(old_buffered_amount);
+ client_->DidDecreaseBufferedAmount(
+ static_cast<unsigned>(old_buffered_amount));
}
}
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc
new file mode 100644
index 00000000000..feadf0ac9d6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc
@@ -0,0 +1,72 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h"
+
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/dom/events/event.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_error_util.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_gather_options.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event_init.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+#include "third_party/webrtc/api/jsepicecandidate.h"
+#include "third_party/webrtc/api/peerconnectioninterface.h"
+#include "third_party/webrtc/p2p/base/portallocator.h"
+#include "third_party/webrtc/p2p/base/transportdescription.h"
+#include "third_party/webrtc/pc/iceserverparsing.h"
+#include "third_party/webrtc/pc/webrtcsdp.h"
+
+namespace blink {
+
+RTCDtlsTransport* RTCDtlsTransport::Create(ExecutionContext* context) {
+ return new RTCDtlsTransport(context);
+}
+
+RTCDtlsTransport::RTCDtlsTransport(ExecutionContext* context)
+ : ContextClient(context) {}
+
+RTCDtlsTransport::~RTCDtlsTransport() {}
+
+String RTCDtlsTransport::state() const {
+ NOTIMPLEMENTED();
+ return "";
+}
+
+const HeapVector<Member<DOMArrayBuffer>>&
+RTCDtlsTransport::getRemoteCertificates() const {
+ return remote_certificates_;
+}
+
+RTCIceTransport* RTCDtlsTransport::iceTransport() const {
+ // TODO(crbug.com/907849): Implement returning an IceTransport
+ NOTIMPLEMENTED();
+ return nullptr;
+}
+
+const AtomicString& RTCDtlsTransport::InterfaceName() const {
+ return event_target_names::kRTCDtlsTransport;
+}
+
+ExecutionContext* RTCDtlsTransport::GetExecutionContext() const {
+ return ContextClient::GetExecutionContext();
+}
+
+void RTCDtlsTransport::Trace(Visitor* visitor) {
+ visitor->Trace(remote_certificates_);
+ EventTargetWithInlineData::Trace(visitor);
+ ContextClient::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h
new file mode 100644
index 00000000000..afe492c7dca
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h
@@ -0,0 +1,59 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_DTLS_TRANSPORT_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_DTLS_TRANSPORT_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
+#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/modules/event_target_modules.h"
+
+namespace blink {
+
+class DOMArrayBuffer;
+class RTCIceTransport;
+
+enum class RTCDtlsTransportState {
+ kNew,
+ kChecking,
+ kConnected,
+ kCompleted,
+ kDisconnected,
+ kFailed,
+ kClosed
+};
+
+// Blink bindings for the RTCDtlsTransport JavaScript object.
+//
+class MODULES_EXPORT RTCDtlsTransport final : public EventTargetWithInlineData,
+ public ContextClient {
+ DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(RTCDtlsTransport);
+
+ public:
+ static RTCDtlsTransport* Create(ExecutionContext* context);
+
+ ~RTCDtlsTransport() override;
+
+ // rtc_dtls_transport.idl
+ RTCIceTransport* iceTransport() const;
+ String state() const;
+ const HeapVector<Member<DOMArrayBuffer>>& getRemoteCertificates() const;
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+
+ // EventTarget overrides.
+ const AtomicString& InterfaceName() const override;
+ ExecutionContext* GetExecutionContext() const override;
+ // For garbage collection.
+ void Trace(blink::Visitor* visitor) override;
+
+ private:
+ explicit RTCDtlsTransport(ExecutionContext* context);
+ HeapVector<Member<DOMArrayBuffer>> remote_certificates_;
+};
+
+} // namespace blink
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_DTLS_TRANSPORT_H_
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.idl
new file mode 100644
index 00000000000..c514ca92801
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.idl
@@ -0,0 +1,24 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// http://w3c.github.io/webrtc-pc/#rtcdtlstransport-interface
+
+enum RTCDtlsTransportState {
+ "new",
+ "connecting",
+ "connected",
+ "closed",
+ "failed"
+};
+
+[
+ Exposed=Window,
+ RuntimeEnabled=RTCDtlsTransport
+] interface RTCDtlsTransport : EventTarget {
+ readonly attribute RTCIceTransport iceTransport;
+ readonly attribute RTCDtlsTransportState state;
+ sequence<ArrayBuffer> getRemoteCertificates();
+ attribute EventHandler onstatechange;
+ attribute EventHandler onerror;
+};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.cc
index d312c8030e0..cd60d6e519d 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.cc
@@ -50,7 +50,8 @@ RTCDTMFSender* RTCDTMFSender::Create(
ExecutionContext* context,
std::unique_ptr<WebRTCDTMFSenderHandler> dtmf_sender_handler) {
DCHECK(dtmf_sender_handler);
- return new RTCDTMFSender(context, std::move(dtmf_sender_handler));
+ return MakeGarbageCollected<RTCDTMFSender>(context,
+ std::move(dtmf_sender_handler));
}
RTCDTMFSender::RTCDTMFSender(ExecutionContext* context,
@@ -168,7 +169,7 @@ void RTCDTMFSender::DidPlayTone(const WebString& tone) {
}
const AtomicString& RTCDTMFSender::InterfaceName() const {
- return EventTargetNames::RTCDTMFSender;
+ return event_target_names::kRTCDTMFSender;
}
ExecutionContext* RTCDTMFSender::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.h
index 1ee1ead6834..dbf139f1426 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_sender.h
@@ -47,6 +47,8 @@ class RTCDTMFSender final : public EventTargetWithInlineData,
public:
static RTCDTMFSender* Create(ExecutionContext*,
std::unique_ptr<WebRTCDTMFSenderHandler>);
+
+ RTCDTMFSender(ExecutionContext*, std::unique_ptr<WebRTCDTMFSenderHandler>);
~RTCDTMFSender() override;
bool canInsertDTMF() const;
@@ -59,7 +61,7 @@ class RTCDTMFSender final : public EventTargetWithInlineData,
int inter_tone_gap,
ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(tonechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(tonechange, kTonechange);
// EventTarget
const AtomicString& InterfaceName() const override;
@@ -71,8 +73,6 @@ class RTCDTMFSender final : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- RTCDTMFSender(ExecutionContext*,
- std::unique_ptr<WebRTCDTMFSenderHandler>);
void Dispose();
// WebRTCDTMFSenderHandlerClient
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.cc
index edb5571b9ca..8b321187763 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.cc
@@ -30,24 +30,24 @@
namespace blink {
RTCDTMFToneChangeEvent* RTCDTMFToneChangeEvent::Create(const String& tone) {
- return new RTCDTMFToneChangeEvent(tone);
+ return MakeGarbageCollected<RTCDTMFToneChangeEvent>(tone);
}
RTCDTMFToneChangeEvent* RTCDTMFToneChangeEvent::Create(
const AtomicString& type,
- const RTCDTMFToneChangeEventInit& initializer) {
- return new RTCDTMFToneChangeEvent(initializer);
+ const RTCDTMFToneChangeEventInit* initializer) {
+ return MakeGarbageCollected<RTCDTMFToneChangeEvent>(initializer);
}
RTCDTMFToneChangeEvent::RTCDTMFToneChangeEvent(const String& tone)
- : Event(EventTypeNames::tonechange, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kTonechange, Bubbles::kNo, Cancelable::kNo),
tone_(tone) {}
RTCDTMFToneChangeEvent::RTCDTMFToneChangeEvent(
- const RTCDTMFToneChangeEventInit& initializer)
- : Event(EventTypeNames::tonechange, initializer) {
- if (initializer.hasTone())
- tone_ = initializer.tone();
+ const RTCDTMFToneChangeEventInit* initializer)
+ : Event(event_type_names::kTonechange, initializer) {
+ if (initializer->hasTone())
+ tone_ = initializer->tone();
}
RTCDTMFToneChangeEvent::~RTCDTMFToneChangeEvent() = default;
@@ -57,7 +57,7 @@ const String& RTCDTMFToneChangeEvent::tone() const {
}
const AtomicString& RTCDTMFToneChangeEvent::InterfaceName() const {
- return EventNames::RTCDTMFToneChangeEvent;
+ return event_interface_names::kRTCDTMFToneChangeEvent;
}
void RTCDTMFToneChangeEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.h
index 0e5cb4b9475..46db919c524 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_dtmf_tone_change_event.h
@@ -36,12 +36,14 @@ class RTCDTMFToneChangeEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit RTCDTMFToneChangeEvent(const String& tone);
+ explicit RTCDTMFToneChangeEvent(const RTCDTMFToneChangeEventInit*);
~RTCDTMFToneChangeEvent() override;
static RTCDTMFToneChangeEvent* Create(const String& tone);
static RTCDTMFToneChangeEvent* Create(
const AtomicString& type,
- const RTCDTMFToneChangeEventInit& initializer);
+ const RTCDTMFToneChangeEventInit* initializer);
const String& tone() const;
@@ -50,9 +52,6 @@ class RTCDTMFToneChangeEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- explicit RTCDTMFToneChangeEvent(const String& tone);
- explicit RTCDTMFToneChangeEvent(const RTCDTMFToneChangeEventInit&);
-
String tone_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.cc
index 36cd0a5f0e1..dcbe9c51279 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.cc
@@ -42,9 +42,10 @@ namespace blink {
RTCIceCandidate* RTCIceCandidate::Create(
ExecutionContext* context,
- const RTCIceCandidateInit& candidate_init,
+ const RTCIceCandidateInit* candidate_init,
ExceptionState& exception_state) {
- if (!candidate_init.hasCandidate() || !candidate_init.candidate().length()) {
+ if (!candidate_init->hasCandidate() ||
+ !candidate_init->candidate().length()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kTypeMismatchError,
ExceptionMessages::IncorrectPropertyType(
@@ -53,25 +54,25 @@ RTCIceCandidate* RTCIceCandidate::Create(
}
String sdp_mid;
- if (candidate_init.hasSdpMid())
- sdp_mid = candidate_init.sdpMid();
+ if (candidate_init->hasSdpMid())
+ sdp_mid = candidate_init->sdpMid();
// TODO(guidou): Change default value to -1. crbug.com/614958.
unsigned short sdp_m_line_index = 0;
- if (candidate_init.hasSdpMLineIndex()) {
- sdp_m_line_index = candidate_init.sdpMLineIndex();
+ if (candidate_init->hasSdpMLineIndex()) {
+ sdp_m_line_index = candidate_init->sdpMLineIndex();
} else {
UseCounter::Count(context,
WebFeature::kRTCIceCandidateDefaultSdpMLineIndex);
}
- return new RTCIceCandidate(WebRTCICECandidate::Create(
- candidate_init.candidate(), sdp_mid, sdp_m_line_index));
+ return MakeGarbageCollected<RTCIceCandidate>(WebRTCICECandidate::Create(
+ candidate_init->candidate(), sdp_mid, sdp_m_line_index));
}
RTCIceCandidate* RTCIceCandidate::Create(
scoped_refptr<WebRTCICECandidate> web_candidate) {
- return new RTCIceCandidate(std::move(web_candidate));
+ return MakeGarbageCollected<RTCIceCandidate>(std::move(web_candidate));
}
RTCIceCandidate::RTCIceCandidate(
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h
index b5715c8dee9..1aec3ed3bb0 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h
@@ -49,10 +49,12 @@ class MODULES_EXPORT RTCIceCandidate final : public ScriptWrappable {
public:
static RTCIceCandidate* Create(ExecutionContext*,
- const RTCIceCandidateInit&,
+ const RTCIceCandidateInit*,
ExceptionState&);
static RTCIceCandidate* Create(scoped_refptr<WebRTCICECandidate>);
+ explicit RTCIceCandidate(scoped_refptr<WebRTCICECandidate>);
+
String candidate() const;
void setCandidate(String);
String sdpMid() const;
@@ -65,8 +67,6 @@ class MODULES_EXPORT RTCIceCandidate final : public ScriptWrappable {
scoped_refptr<WebRTCICECandidate> WebCandidate() const;
private:
- explicit RTCIceCandidate(scoped_refptr<WebRTCICECandidate>);
-
scoped_refptr<WebRTCICECandidate> web_candidate_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc
index 2f4c4d6d152..32caf50cd84 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.h"
@@ -54,11 +55,11 @@ RTCIceCandidate* ConvertToRtcIceCandidate(const cricket::Candidate& candidate) {
class DefaultIceTransportAdapterCrossThreadFactory
: public IceTransportAdapterCrossThreadFactory {
public:
- void InitializeOnMainThread() override {
+ void InitializeOnMainThread(LocalFrame& frame) override {
DCHECK(!port_allocator_);
DCHECK(!worker_thread_rtc_thread_);
port_allocator_ = Platform::Current()->CreateWebRtcPortAllocator(
- WebLocalFrame::FrameForCurrentContext());
+ frame.Client()->GetWebFrame());
worker_thread_rtc_thread_ =
Platform::Current()->GetWebRtcWorkerThreadRtcThread();
}
@@ -84,7 +85,7 @@ RTCIceTransport* RTCIceTransport::Create(ExecutionContext* context) {
frame->GetTaskRunner(TaskType::kNetworking);
scoped_refptr<base::SingleThreadTaskRunner> host_thread =
Platform::Current()->GetWebRtcWorkerThread();
- return new RTCIceTransport(
+ return MakeGarbageCollected<RTCIceTransport>(
context, std::move(proxy_thread), std::move(host_thread),
std::make_unique<DefaultIceTransportAdapterCrossThreadFactory>());
}
@@ -94,9 +95,9 @@ RTCIceTransport* RTCIceTransport::Create(
scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
scoped_refptr<base::SingleThreadTaskRunner> host_thread,
std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory) {
- return new RTCIceTransport(context, std::move(proxy_thread),
- std::move(host_thread),
- std::move(adapter_factory));
+ return MakeGarbageCollected<RTCIceTransport>(context, std::move(proxy_thread),
+ std::move(host_thread),
+ std::move(adapter_factory));
}
RTCIceTransport::RTCIceTransport(
@@ -113,9 +114,9 @@ RTCIceTransport::RTCIceTransport(
LocalFrame* frame = To<Document>(context)->GetFrame();
DCHECK(frame);
- proxy_.reset(new IceTransportProxy(
- frame->GetFrameScheduler(), std::move(proxy_thread),
- std::move(host_thread), this, std::move(adapter_factory)));
+ proxy_ = std::make_unique<IceTransportProxy>(*frame, std::move(proxy_thread),
+ std::move(host_thread), this,
+ std::move(adapter_factory));
GenerateLocalParameters();
}
@@ -205,56 +206,53 @@ RTCIceTransport::getRemoteCandidates() const {
return remote_candidates_;
}
-void RTCIceTransport::getSelectedCandidatePair(
- base::Optional<RTCIceCandidatePair>& result) const {
- result = selected_candidate_pair_;
+RTCIceCandidatePair* RTCIceTransport::getSelectedCandidatePair() const {
+ return selected_candidate_pair_;
}
-void RTCIceTransport::getLocalParameters(
- base::Optional<RTCIceParameters>& result) const {
- result = local_parameters_;
+RTCIceParameters* RTCIceTransport::getLocalParameters() const {
+ return local_parameters_;
}
-void RTCIceTransport::getRemoteParameters(
- base::Optional<RTCIceParameters>& result) const {
- result = remote_parameters_;
+RTCIceParameters* RTCIceTransport::getRemoteParameters() const {
+ return remote_parameters_;
}
static webrtc::PeerConnectionInterface::IceServer ConvertIceServer(
- const RTCIceServer& ice_server) {
+ const RTCIceServer* ice_server) {
webrtc::PeerConnectionInterface::IceServer converted_ice_server;
// Prefer standardized 'urls' field over deprecated 'url' field.
Vector<String> url_strings;
- if (ice_server.hasURLs()) {
- if (ice_server.urls().IsString()) {
- url_strings.push_back(ice_server.urls().GetAsString());
- } else if (ice_server.urls().IsStringSequence()) {
- url_strings = ice_server.urls().GetAsStringSequence();
+ if (ice_server->hasURLs()) {
+ if (ice_server->urls().IsString()) {
+ url_strings.push_back(ice_server->urls().GetAsString());
+ } else if (ice_server->urls().IsStringSequence()) {
+ url_strings = ice_server->urls().GetAsStringSequence();
}
- } else if (ice_server.hasURL()) {
- url_strings.push_back(ice_server.url());
+ } else if (ice_server->hasURL()) {
+ url_strings.push_back(ice_server->url());
}
for (const String& url_string : url_strings) {
converted_ice_server.urls.push_back(WebString(url_string).Utf8());
}
- converted_ice_server.username = WebString(ice_server.username()).Utf8();
- converted_ice_server.password = WebString(ice_server.credential()).Utf8();
+ converted_ice_server.username = WebString(ice_server->username()).Utf8();
+ converted_ice_server.password = WebString(ice_server->credential()).Utf8();
return converted_ice_server;
}
static cricket::IceParameters ConvertIceParameters(
- const RTCIceParameters& ice_parameters) {
+ const RTCIceParameters* ice_parameters) {
cricket::IceParameters converted_ice_parameters;
converted_ice_parameters.ufrag =
- WebString(ice_parameters.usernameFragment()).Utf8();
- converted_ice_parameters.pwd = WebString(ice_parameters.password()).Utf8();
+ WebString(ice_parameters->usernameFragment()).Utf8();
+ converted_ice_parameters.pwd = WebString(ice_parameters->password()).Utf8();
return converted_ice_parameters;
}
static std::vector<webrtc::PeerConnectionInterface::IceServer>
-ConvertIceServers(const HeapVector<RTCIceServer>& ice_servers) {
+ConvertIceServers(const HeapVector<Member<RTCIceServer>>& ice_servers) {
std::vector<webrtc::PeerConnectionInterface::IceServer> converted_ice_servers;
- for (const RTCIceServer& ice_server : ice_servers) {
+ for (const RTCIceServer* ice_server : ice_servers) {
converted_ice_servers.push_back(ConvertIceServer(ice_server));
}
return converted_ice_servers;
@@ -271,7 +269,7 @@ static IceTransportPolicy IceTransportPolicyFromString(const String& str) {
return IceTransportPolicy::kAll;
}
-void RTCIceTransport::gather(const RTCIceGatherOptions& options,
+void RTCIceTransport::gather(RTCIceGatherOptions* options,
ExceptionState& exception_state) {
if (RaiseExceptionIfClosed(exception_state)) {
return;
@@ -284,8 +282,8 @@ void RTCIceTransport::gather(const RTCIceGatherOptions& options,
return;
}
std::vector<webrtc::PeerConnectionInterface::IceServer> ice_servers;
- if (options.hasIceServers()) {
- ice_servers = ConvertIceServers(options.iceServers());
+ if (options->hasIceServers()) {
+ ice_servers = ConvertIceServers(options->iceServers());
}
cricket::ServerAddresses stun_servers;
std::vector<cricket::RelayServerConfig> turn_servers;
@@ -300,7 +298,7 @@ void RTCIceTransport::gather(const RTCIceGatherOptions& options,
gathering_state_ = cricket::kIceGatheringGathering;
proxy_->StartGathering(ConvertIceParameters(local_parameters_), stun_servers,
turn_servers,
- IceTransportPolicyFromString(options.gatherPolicy()));
+ IceTransportPolicyFromString(options->gatherPolicy()));
}
static cricket::IceRole IceRoleFromString(const String& role_string) {
@@ -314,20 +312,20 @@ static cricket::IceRole IceRoleFromString(const String& role_string) {
return cricket::ICEROLE_UNKNOWN;
}
-static bool RTCIceParametersAreEqual(const RTCIceParameters& a,
- const RTCIceParameters& b) {
- return a.usernameFragment() == b.usernameFragment() &&
- a.password() == b.password();
+static bool RTCIceParametersAreEqual(const RTCIceParameters* a,
+ const RTCIceParameters* b) {
+ return a->usernameFragment() == b->usernameFragment() &&
+ a->password() == b->password();
}
-void RTCIceTransport::start(const RTCIceParameters& remote_parameters,
+void RTCIceTransport::start(RTCIceParameters* remote_parameters,
const String& role_string,
ExceptionState& exception_state) {
if (RaiseExceptionIfClosed(exception_state)) {
return;
}
- if (!remote_parameters.hasUsernameFragment() ||
- !remote_parameters.hasPassword()) {
+ if (!remote_parameters->hasUsernameFragment() ||
+ !remote_parameters->hasPassword()) {
exception_state.ThrowTypeError(
"remoteParameters must have usernameFragment and password fields set.");
return;
@@ -340,7 +338,7 @@ void RTCIceTransport::start(const RTCIceParameters& remote_parameters,
return;
}
if (remote_parameters_ &&
- RTCIceParametersAreEqual(*remote_parameters_, remote_parameters)) {
+ RTCIceParametersAreEqual(remote_parameters_, remote_parameters)) {
// No change to remote parameters: do nothing.
return;
}
@@ -360,13 +358,14 @@ void RTCIceTransport::start(const RTCIceParameters& remote_parameters,
proxy_->Start(ConvertIceParameters(remote_parameters), role,
initial_remote_candidates);
if (consumer_) {
- consumer_->OnTransportStarted();
+ consumer_->OnIceTransportStarted();
}
} else {
remote_candidates_.clear();
state_ = RTCIceTransportState::kNew;
proxy_->HandleRemoteRestart(ConvertIceParameters(remote_parameters));
}
+
remote_parameters_ = remote_parameters;
}
@@ -374,14 +373,7 @@ void RTCIceTransport::stop() {
if (IsClosed()) {
return;
}
- if (HasConsumer()) {
- consumer_->stop();
- }
- // Stopping the consumer should cause it to disconnect.
- DCHECK(!HasConsumer());
- state_ = RTCIceTransportState::kClosed;
- selected_candidate_pair_ = base::nullopt;
- proxy_.reset();
+ Close(CloseReason::kStopped);
}
void RTCIceTransport::addRemoteCandidate(RTCIceCandidate* remote_candidate,
@@ -404,9 +396,10 @@ void RTCIceTransport::addRemoteCandidate(RTCIceCandidate* remote_candidate,
}
void RTCIceTransport::GenerateLocalParameters() {
- local_parameters_.setUsernameFragment(
+ local_parameters_ = RTCIceParameters::Create();
+ local_parameters_->setUsernameFragment(
WebString::FromUTF8(rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH)));
- local_parameters_.setPassword(
+ local_parameters_->setPassword(
WebString::FromUTF8(rtc::CreateRandomString(cricket::ICE_PWD_LENGTH)));
}
@@ -420,17 +413,18 @@ void RTCIceTransport::OnGatheringStateChanged(
DispatchEvent(*RTCPeerConnectionIceEvent::Create(nullptr));
}
gathering_state_ = new_state;
- DispatchEvent(*Event::Create(EventTypeNames::gatheringstatechange));
+ DispatchEvent(*Event::Create(event_type_names::kGatheringstatechange));
}
void RTCIceTransport::OnCandidateGathered(
const cricket::Candidate& parsed_candidate) {
RTCIceCandidate* candidate = ConvertToRtcIceCandidate(parsed_candidate);
local_candidates_.push_back(candidate);
- RTCPeerConnectionIceEventInit event_init;
- event_init.setCandidate(candidate);
- DispatchEvent(*RTCPeerConnectionIceEvent::Create(EventTypeNames::icecandidate,
- event_init));
+ RTCPeerConnectionIceEventInit* event_init =
+ RTCPeerConnectionIceEventInit::Create();
+ event_init->setCandidate(candidate);
+ DispatchEvent(*RTCPeerConnectionIceEvent::Create(
+ event_type_names::kIcecandidate, event_init));
}
static RTCIceTransportState ConvertIceTransportState(
@@ -457,9 +451,9 @@ void RTCIceTransport::OnStateChanged(cricket::IceTransportState new_state) {
}
state_ = local_new_state;
if (state_ == RTCIceTransportState::kFailed) {
- selected_candidate_pair_ = base::nullopt;
+ selected_candidate_pair_ = nullptr;
}
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ DispatchEvent(*Event::Create(event_type_names::kStatechange));
}
void RTCIceTransport::OnSelectedCandidatePairChanged(
@@ -469,10 +463,22 @@ void RTCIceTransport::OnSelectedCandidatePairChanged(
ConvertToRtcIceCandidate(selected_candidate_pair.first);
RTCIceCandidate* remote =
ConvertToRtcIceCandidate(selected_candidate_pair.second);
- selected_candidate_pair_ = RTCIceCandidatePair();
+ selected_candidate_pair_ = RTCIceCandidatePair::Create();
selected_candidate_pair_->setLocal(local);
selected_candidate_pair_->setRemote(remote);
- DispatchEvent(*Event::Create(EventTypeNames::selectedcandidatepairchange));
+ DispatchEvent(*Event::Create(event_type_names::kSelectedcandidatepairchange));
+}
+
+void RTCIceTransport::Close(CloseReason reason) {
+ DCHECK_NE(state_, RTCIceTransportState::kClosed);
+ if (HasConsumer()) {
+ consumer_->OnIceTransportClosed(reason);
+ }
+ // Notifying the consumer that we're closing should cause it to disconnect.
+ DCHECK(!HasConsumer());
+ state_ = RTCIceTransportState::kClosed;
+ selected_candidate_pair_ = nullptr;
+ proxy_.reset();
}
bool RTCIceTransport::RaiseExceptionIfClosed(
@@ -487,7 +493,7 @@ bool RTCIceTransport::RaiseExceptionIfClosed(
}
const AtomicString& RTCIceTransport::InterfaceName() const {
- return EventTargetNames::RTCIceTransport;
+ return event_target_names::kRTCIceTransport;
}
ExecutionContext* RTCIceTransport::GetExecutionContext() const {
@@ -495,7 +501,10 @@ ExecutionContext* RTCIceTransport::GetExecutionContext() const {
}
void RTCIceTransport::ContextDestroyed(ExecutionContext*) {
- stop();
+ if (IsClosed()) {
+ return;
+ }
+ Close(CloseReason::kContextDestroyed);
}
bool RTCIceTransport::HasPendingActivity() const {
@@ -507,6 +516,8 @@ bool RTCIceTransport::HasPendingActivity() const {
void RTCIceTransport::Trace(blink::Visitor* visitor) {
visitor->Trace(local_candidates_);
visitor->Trace(remote_candidates_);
+ visitor->Trace(local_parameters_);
+ visitor->Trace(remote_parameters_);
visitor->Trace(selected_candidate_pair_);
visitor->Trace(consumer_);
EventTargetWithInlineData::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h
index 2a39f0c5dbc..6f3c82232ab 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h
@@ -50,6 +50,13 @@ class MODULES_EXPORT RTCIceTransport final
USING_GARBAGE_COLLECTED_MIXIN(RTCIceTransport);
public:
+ enum class CloseReason {
+ // stop() was called.
+ kStopped,
+ // The ExecutionContext is being destroyed.
+ kContextDestroyed,
+ };
+
static RTCIceTransport* Create(ExecutionContext* context);
static RTCIceTransport* Create(
ExecutionContext* context,
@@ -57,6 +64,11 @@ class MODULES_EXPORT RTCIceTransport final
scoped_refptr<base::SingleThreadTaskRunner> host_thread,
std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory);
+ explicit RTCIceTransport(
+ ExecutionContext* context,
+ scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
+ scoped_refptr<base::SingleThreadTaskRunner> host_thread,
+ std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory);
~RTCIceTransport() override;
// Returns true if start() has been called.
@@ -85,22 +97,21 @@ class MODULES_EXPORT RTCIceTransport final
String gatheringState() const;
const HeapVector<Member<RTCIceCandidate>>& getLocalCandidates() const;
const HeapVector<Member<RTCIceCandidate>>& getRemoteCandidates() const;
- void getSelectedCandidatePair(
- base::Optional<RTCIceCandidatePair>& result) const;
- void getLocalParameters(base::Optional<RTCIceParameters>& result) const;
- void getRemoteParameters(base::Optional<RTCIceParameters>& result) const;
- void gather(const RTCIceGatherOptions& options,
- ExceptionState& exception_state);
- void start(const RTCIceParameters& remote_parameters,
+ RTCIceCandidatePair* getSelectedCandidatePair() const;
+ RTCIceParameters* getLocalParameters() const;
+ RTCIceParameters* getRemoteParameters() const;
+ void gather(RTCIceGatherOptions* options, ExceptionState& exception_state);
+ void start(RTCIceParameters* remote_parameters,
const String& role,
ExceptionState& exception_state);
void stop();
void addRemoteCandidate(RTCIceCandidate* remote_candidate,
ExceptionState& exception_state);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(gatheringstatechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(selectedcandidatepairchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(gatheringstatechange, kGatheringstatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(selectedcandidatepairchange,
+ kSelectedcandidatepairchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidate, kIcecandidate);
// EventTarget overrides.
const AtomicString& InterfaceName() const override;
@@ -116,12 +127,6 @@ class MODULES_EXPORT RTCIceTransport final
void Trace(blink::Visitor* visitor) override;
private:
- explicit RTCIceTransport(
- ExecutionContext* context,
- scoped_refptr<base::SingleThreadTaskRunner> proxy_thread,
- scoped_refptr<base::SingleThreadTaskRunner> host_thread,
- std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory);
-
// IceTransportProxy::Delegate overrides.
void OnGatheringStateChanged(cricket::IceGatheringState new_state) override;
void OnCandidateGathered(const cricket::Candidate& candidate) override;
@@ -134,6 +139,11 @@ class MODULES_EXPORT RTCIceTransport final
// password.
void GenerateLocalParameters();
+ // Permenantly closes the RTCIceTransport with the given reason.
+ // The RTCIceTransport must not already be closed.
+ // This will transition the state to closed.
+ void Close(CloseReason reason);
+
bool RaiseExceptionIfClosed(ExceptionState& exception_state) const;
cricket::IceRole role_ = cricket::ICEROLE_UNKNOWN;
@@ -143,10 +153,9 @@ class MODULES_EXPORT RTCIceTransport final
HeapVector<Member<RTCIceCandidate>> local_candidates_;
HeapVector<Member<RTCIceCandidate>> remote_candidates_;
- RTCIceParameters local_parameters_;
- base::Optional<RTCIceParameters> remote_parameters_;
-
- base::Optional<RTCIceCandidatePair> selected_candidate_pair_;
+ Member<RTCIceParameters> local_parameters_;
+ Member<RTCIceParameters> remote_parameters_;
+ Member<RTCIceCandidatePair> selected_candidate_pair_;
Member<RTCQuicTransport> consumer_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.cc
index 1dcb46312f3..a4b6e648b16 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.cc
@@ -27,7 +27,6 @@ using testing::DoDefault;
using testing::ElementsAre;
using testing::Field;
using testing::InSequence;
-using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::Mock;
using testing::StrEq;
@@ -35,14 +34,13 @@ using testing::StrNe;
constexpr char kRemoteUsernameFragment1[] = "usernameFragment";
constexpr char kRemotePassword1[] = "password";
-
constexpr char kRemoteUsernameFragment2[] = "secondUsernameFragment";
constexpr char kRemotePassword2[] = "secondPassword";
-RTCIceParameters CreateRemoteRTCIceParameters2() {
- RTCIceParameters ice_parameters;
- ice_parameters.setUsernameFragment(kRemoteUsernameFragment2);
- ice_parameters.setPassword(kRemotePassword2);
+RTCIceParameters* CreateRemoteRTCIceParameters2() {
+ RTCIceParameters* ice_parameters = RTCIceParameters::Create();
+ ice_parameters->setUsernameFragment(kRemoteUsernameFragment2);
+ ice_parameters->setPassword(kRemotePassword2);
return ice_parameters;
}
@@ -56,8 +54,8 @@ constexpr char kRemoteIceCandidateStr2[] =
RTCIceCandidate* RTCIceCandidateFromString(V8TestingScope& scope,
const String& candidate_str) {
- RTCIceCandidateInit init;
- init.setCandidate(candidate_str);
+ RTCIceCandidateInit* init = RTCIceCandidateInit::Create();
+ init->setCandidate(candidate_str);
return RTCIceCandidate::Create(scope.GetExecutionContext(), init,
ASSERT_NO_EXCEPTION);
}
@@ -74,10 +72,10 @@ cricket::Candidate CricketCandidateFromString(
} // namespace
// static
-RTCIceParameters RTCIceTransportTest::CreateRemoteRTCIceParameters1() {
- RTCIceParameters ice_parameters;
- ice_parameters.setUsernameFragment(kRemoteUsernameFragment1);
- ice_parameters.setPassword(kRemotePassword1);
+RTCIceParameters* RTCIceTransportTest::CreateRemoteRTCIceParameters1() {
+ RTCIceParameters* ice_parameters = RTCIceParameters::Create();
+ ice_parameters->setUsernameFragment(kRemoteUsernameFragment1);
+ ice_parameters->setPassword(kRemotePassword1);
return ice_parameters;
}
@@ -135,7 +133,7 @@ RTCIceTransport* RTCIceTransportTest::CreateIceTransport(
}
MockEventListener* RTCIceTransportTest::CreateMockEventListener() {
- MockEventListener* event_listener = new MockEventListener();
+ MockEventListener* event_listener = MakeGarbageCollected<MockEventListener>();
mock_event_listeners_.push_back(event_listener);
return event_listener;
}
@@ -154,8 +152,8 @@ TEST_F(RTCIceTransportTest, GatherStartsGatheringWithNonEmptyLocalParameters) {
Persistent<RTCIceTransport> ice_transport =
CreateIceTransport(scope, std::move(mock));
- RTCIceGatherOptions options;
- options.setGatherPolicy("all");
+ RTCIceGatherOptions* options = RTCIceGatherOptions::Create();
+ options->setGatherPolicy("all");
ice_transport->gather(options, ASSERT_NO_EXCEPTION);
}
@@ -170,8 +168,8 @@ TEST_F(RTCIceTransportTest, GatherIceTransportPolicyAll) {
Persistent<RTCIceTransport> ice_transport =
CreateIceTransport(scope, std::move(mock));
- RTCIceGatherOptions options;
- options.setGatherPolicy("all");
+ RTCIceGatherOptions* options = RTCIceGatherOptions::Create();
+ options->setGatherPolicy("all");
ice_transport->gather(options, ASSERT_NO_EXCEPTION);
}
@@ -186,8 +184,8 @@ TEST_F(RTCIceTransportTest, GatherIceTransportPolicyRelay) {
Persistent<RTCIceTransport> ice_transport =
CreateIceTransport(scope, std::move(mock));
- RTCIceGatherOptions options;
- options.setGatherPolicy("relay");
+ RTCIceGatherOptions* options = RTCIceGatherOptions::Create();
+ options->setGatherPolicy("relay");
ice_transport->gather(options, ASSERT_NO_EXCEPTION);
}
@@ -201,8 +199,8 @@ TEST_F(RTCIceTransportTest, StopDeletesIceTransportAdapter) {
Persistent<RTCIceTransport> ice_transport =
CreateIceTransport(scope, std::move(mock));
- RTCIceGatherOptions options;
- options.setGatherPolicy("all");
+ RTCIceGatherOptions* options = RTCIceGatherOptions::Create();
+ options->setGatherPolicy("all");
ice_transport->gather(options, ASSERT_NO_EXCEPTION);
ice_transport->stop();
@@ -213,19 +211,20 @@ TEST_F(RTCIceTransportTest, StopDeletesIceTransportAdapter) {
// Test that the IceTransportAdapter is deleted on ContextDestroyed.
TEST_F(RTCIceTransportTest, ContextDestroyedDeletesIceTransportAdapter) {
- V8TestingScope scope;
-
bool mock_deleted = false;
- auto mock = std::make_unique<MockIceTransportAdapter>();
- EXPECT_CALL(*mock, Die()).WillOnce(Assign(&mock_deleted, true));
+ {
+ V8TestingScope scope;
- Persistent<RTCIceTransport> ice_transport =
- CreateIceTransport(scope, std::move(mock));
- RTCIceGatherOptions options;
- options.setGatherPolicy("all");
- ice_transport->gather(options, ASSERT_NO_EXCEPTION);
+ auto mock = std::make_unique<MockIceTransportAdapter>();
+ EXPECT_CALL(*mock, Die()).WillOnce(Assign(&mock_deleted, true));
+
+ Persistent<RTCIceTransport> ice_transport =
+ CreateIceTransport(scope, std::move(mock));
+ RTCIceGatherOptions* options = RTCIceGatherOptions::Create();
+ options->setGatherPolicy("all");
+ ice_transport->gather(options, ASSERT_NO_EXCEPTION);
+ } // ContextDestroyed when V8TestingScope goes out of scope.
- ice_transport->ContextDestroyed(scope.GetExecutionContext());
RunUntilIdle();
EXPECT_TRUE(mock_deleted);
@@ -239,8 +238,8 @@ TEST_F(RTCIceTransportTest, OnGatheringStateChangedCompleteFiresEvents) {
IceTransportAdapter::Delegate* delegate = nullptr;
Persistent<RTCIceTransport> ice_transport =
CreateIceTransport(scope, &delegate);
- RTCIceGatherOptions options;
- options.setGatherPolicy("all");
+ RTCIceGatherOptions* options = RTCIceGatherOptions::Create();
+ options->setGatherPolicy("all");
ice_transport->gather(options, ASSERT_NO_EXCEPTION);
RunUntilIdle();
ASSERT_TRUE(delegate);
@@ -251,19 +250,20 @@ TEST_F(RTCIceTransportTest, OnGatheringStateChangedCompleteFiresEvents) {
CreateMockEventListener();
{
InSequence dummy;
- EXPECT_CALL(*ice_candidate_listener, handleEvent(_, _))
- .WillOnce(Invoke([ice_transport](ExecutionContext*, Event* event) {
- auto* ice_event = static_cast<RTCPeerConnectionIceEvent*>(event);
- EXPECT_EQ(nullptr, ice_event->candidate());
- }));
- EXPECT_CALL(*gathering_state_change_listener, handleEvent(_, _))
+ EXPECT_CALL(*ice_candidate_listener, Invoke(_, _))
+ .WillOnce(
+ testing::Invoke([ice_transport](ExecutionContext*, Event* event) {
+ auto* ice_event = static_cast<RTCPeerConnectionIceEvent*>(event);
+ EXPECT_EQ(nullptr, ice_event->candidate());
+ }));
+ EXPECT_CALL(*gathering_state_change_listener, Invoke(_, _))
.WillOnce(InvokeWithoutArgs([ice_transport] {
EXPECT_EQ("complete", ice_transport->gatheringState());
}));
}
- ice_transport->addEventListener(EventTypeNames::icecandidate,
+ ice_transport->addEventListener(event_type_names::kIcecandidate,
ice_candidate_listener);
- ice_transport->addEventListener(EventTypeNames::gatheringstatechange,
+ ice_transport->addEventListener(event_type_names::kGatheringstatechange,
gathering_state_change_listener);
delegate->OnGatheringStateChanged(cricket::kIceGatheringComplete);
@@ -334,10 +334,11 @@ TEST_F(RTCIceTransportTest, OnStateChangedCompletedUpdatesStateAndFiresEvent) {
ASSERT_TRUE(delegate);
Persistent<MockEventListener> event_listener = CreateMockEventListener();
- EXPECT_CALL(*event_listener, handleEvent(_, _))
+ EXPECT_CALL(*event_listener, Invoke(_, _))
.WillOnce(InvokeWithoutArgs(
[ice_transport] { EXPECT_EQ("connected", ice_transport->state()); }));
- ice_transport->addEventListener(EventTypeNames::statechange, event_listener);
+ ice_transport->addEventListener(event_type_names::kStatechange,
+ event_listener);
ice_transport->addRemoteCandidate(
RTCIceCandidateFromString(scope, kRemoteIceCandidateStr1),
@@ -364,10 +365,11 @@ TEST_F(RTCIceTransportTest, OnStateChangedFailedUpdatesStateAndFiresEvent) {
ASSERT_TRUE(delegate);
Persistent<MockEventListener> event_listener = CreateMockEventListener();
- EXPECT_CALL(*event_listener, handleEvent(_, _))
+ EXPECT_CALL(*event_listener, Invoke(_, _))
.WillOnce(InvokeWithoutArgs(
[ice_transport] { EXPECT_EQ("failed", ice_transport->state()); }));
- ice_transport->addEventListener(EventTypeNames::statechange, event_listener);
+ ice_transport->addEventListener(event_type_names::kStatechange,
+ event_listener);
ice_transport->addRemoteCandidate(
RTCIceCandidateFromString(scope, kRemoteIceCandidateStr1),
@@ -394,18 +396,18 @@ TEST_F(RTCIceTransportTest, InitialOnSelectedCandidatePairChangedFiresEvent) {
ASSERT_TRUE(delegate);
Persistent<MockEventListener> event_listener = CreateMockEventListener();
- EXPECT_CALL(*event_listener, handleEvent(_, _))
+ EXPECT_CALL(*event_listener, Invoke(_, _))
.WillOnce(InvokeWithoutArgs([ice_transport] {
- base::Optional<RTCIceCandidatePair> selected_candidate_pair;
- ice_transport->getSelectedCandidatePair(selected_candidate_pair);
+ RTCIceCandidatePair* selected_candidate_pair =
+ ice_transport->getSelectedCandidatePair();
ASSERT_TRUE(selected_candidate_pair);
EXPECT_EQ(ice_transport->getLocalCandidates()[0]->candidate(),
selected_candidate_pair->local()->candidate());
EXPECT_EQ(ice_transport->getRemoteCandidates()[0]->candidate(),
selected_candidate_pair->remote()->candidate());
}));
- ice_transport->addEventListener(EventTypeNames::selectedcandidatepairchange,
- event_listener);
+ ice_transport->addEventListener(
+ event_type_names::kSelectedcandidatepairchange, event_listener);
ice_transport->addRemoteCandidate(
RTCIceCandidateFromString(scope, kRemoteIceCandidateStr1),
@@ -434,19 +436,19 @@ TEST_F(RTCIceTransportTest,
ASSERT_TRUE(delegate);
Persistent<MockEventListener> event_listener = CreateMockEventListener();
- EXPECT_CALL(*event_listener, handleEvent(_, _))
+ EXPECT_CALL(*event_listener, Invoke(_, _))
.WillOnce(DoDefault()) // First event is already tested above.
.WillOnce(InvokeWithoutArgs([ice_transport] {
- base::Optional<RTCIceCandidatePair> selected_candidate_pair;
- ice_transport->getSelectedCandidatePair(selected_candidate_pair);
+ RTCIceCandidatePair* selected_candidate_pair =
+ ice_transport->getSelectedCandidatePair();
ASSERT_TRUE(selected_candidate_pair);
EXPECT_EQ(ice_transport->getLocalCandidates()[0]->candidate(),
selected_candidate_pair->local()->candidate());
EXPECT_EQ(ice_transport->getRemoteCandidates()[1]->candidate(),
selected_candidate_pair->remote()->candidate());
}));
- ice_transport->addEventListener(EventTypeNames::selectedcandidatepairchange,
- event_listener);
+ ice_transport->addEventListener(
+ event_type_names::kSelectedcandidatepairchange, event_listener);
ice_transport->addRemoteCandidate(
RTCIceCandidateFromString(scope, kRemoteIceCandidateStr1),
@@ -485,23 +487,23 @@ TEST_F(RTCIceTransportTest,
Persistent<MockEventListener> state_change_event_listener =
CreateMockEventListener();
- EXPECT_CALL(*state_change_event_listener, handleEvent(_, _))
+ EXPECT_CALL(*state_change_event_listener, Invoke(_, _))
.WillOnce(DoDefault()) // First event is for 'connected'.
.WillOnce(InvokeWithoutArgs([ice_transport] {
EXPECT_EQ("failed", ice_transport->state());
- base::Optional<RTCIceCandidatePair> selected_candidate_pair;
- ice_transport->getSelectedCandidatePair(selected_candidate_pair);
- EXPECT_EQ(base::nullopt, selected_candidate_pair);
+ RTCIceCandidatePair* selected_candidate_pair =
+ ice_transport->getSelectedCandidatePair();
+ EXPECT_EQ(nullptr, selected_candidate_pair);
}));
- ice_transport->addEventListener(EventTypeNames::statechange,
+ ice_transport->addEventListener(event_type_names::kStatechange,
state_change_event_listener);
Persistent<MockEventListener> selected_candidate_pair_change_event_listener =
CreateMockEventListener();
- EXPECT_CALL(*selected_candidate_pair_change_event_listener, handleEvent(_, _))
+ EXPECT_CALL(*selected_candidate_pair_change_event_listener, Invoke(_, _))
.Times(1); // First event is for the connected pair.
ice_transport->addEventListener(
- EventTypeNames::selectedcandidatepairchange,
+ event_type_names::kSelectedcandidatepairchange,
selected_candidate_pair_change_event_listener);
// Establish the connection
@@ -536,18 +538,18 @@ TEST_F(RTCIceTransportTest,
ASSERT_TRUE(delegate);
Persistent<MockEventListener> event_listener = CreateMockEventListener();
- EXPECT_CALL(*event_listener, handleEvent(_, _))
+ EXPECT_CALL(*event_listener, Invoke(_, _))
.WillOnce(InvokeWithoutArgs([ice_transport] {
- base::Optional<RTCIceCandidatePair> selected_candidate_pair;
- ice_transport->getSelectedCandidatePair(selected_candidate_pair);
+ RTCIceCandidatePair* selected_candidate_pair =
+ ice_transport->getSelectedCandidatePair();
ASSERT_TRUE(selected_candidate_pair);
EXPECT_EQ(kLocalIceCandidateStr1,
selected_candidate_pair->local()->candidate());
EXPECT_EQ(kRemoteIceCandidateStr1,
selected_candidate_pair->remote()->candidate());
}));
- ice_transport->addEventListener(EventTypeNames::selectedcandidatepairchange,
- event_listener);
+ ice_transport->addEventListener(
+ event_type_names::kSelectedcandidatepairchange, event_listener);
ice_transport->addRemoteCandidate(
RTCIceCandidateFromString(scope, kRemoteIceCandidateStr1),
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h
index 9e2d7c1f91f..4cc2bff8a5e 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h
@@ -21,12 +21,12 @@ class MockEventListener final : public EventListener {
return this == &other;
}
- MOCK_METHOD2(handleEvent, void(ExecutionContext*, Event*));
+ MOCK_METHOD2(Invoke, void(ExecutionContext*, Event*));
};
class RTCIceTransportTest : public testing::Test {
public:
- static RTCIceParameters CreateRemoteRTCIceParameters1();
+ static RTCIceParameters* CreateRemoteRTCIceParameters1();
RTCIceTransportTest();
~RTCIceTransportTest() override;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.cc
index ee5dba9424e..ac3110bacce 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.cc
@@ -30,7 +30,7 @@ namespace blink {
RTCLegacyStatsReport* RTCLegacyStatsReport::Create(const String& id,
const String& type,
double timestamp) {
- return new RTCLegacyStatsReport(id, type, timestamp);
+ return MakeGarbageCollected<RTCLegacyStatsReport>(id, type, timestamp);
}
RTCLegacyStatsReport::RTCLegacyStatsReport(const String& id,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.h
index f7adcb61f94..d784ee09fcb 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_legacy_stats_report.h
@@ -41,6 +41,8 @@ class RTCLegacyStatsReport final : public ScriptWrappable {
const String& type,
double timestamp);
+ RTCLegacyStatsReport(const String& id, const String& type, double timestamp);
+
double timestamp() const { return timestamp_; }
String id() { return id_; }
String type() { return type_; }
@@ -50,8 +52,6 @@ class RTCLegacyStatsReport final : public ScriptWrappable {
void AddStatistic(const String& name, const String& value);
private:
- RTCLegacyStatsReport(const String& id, const String& type, double timestamp);
-
String id_;
String type_;
double timestamp_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
index 1072ca64219..e21602e3d2a 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -80,6 +80,7 @@
#include "third_party/blink/renderer/modules/mediastream/media_constraints_impl.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream_event.h"
+#include "third_party/blink/renderer/modules/mediastream/user_media_controller.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_answer_options.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_configuration.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_data_channel.h"
@@ -113,6 +114,7 @@
#include "third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/webrtc/api/jsep.h"
#include "third_party/webrtc/api/peerconnectioninterface.h"
@@ -176,34 +178,34 @@ bool CallErrorCallbackIfSignalingStateClosed(
bool IsIceCandidateMissingSdp(
const RTCIceCandidateInitOrRTCIceCandidate& candidate) {
if (candidate.IsRTCIceCandidateInit()) {
- const RTCIceCandidateInit& ice_candidate_init =
+ const RTCIceCandidateInit* ice_candidate_init =
candidate.GetAsRTCIceCandidateInit();
- return !ice_candidate_init.hasSdpMid() &&
- !ice_candidate_init.hasSdpMLineIndex();
+ return !ice_candidate_init->hasSdpMid() &&
+ !ice_candidate_init->hasSdpMLineIndex();
}
DCHECK(candidate.IsRTCIceCandidate());
return false;
}
-WebRTCOfferOptions ConvertToWebRTCOfferOptions(const RTCOfferOptions& options) {
+WebRTCOfferOptions ConvertToWebRTCOfferOptions(const RTCOfferOptions* options) {
return WebRTCOfferOptions(RTCOfferOptionsPlatform::Create(
- options.hasOfferToReceiveVideo()
- ? std::max(options.offerToReceiveVideo(), 0)
+ options->hasOfferToReceiveVideo()
+ ? std::max(options->offerToReceiveVideo(), 0)
: -1,
- options.hasOfferToReceiveAudio()
- ? std::max(options.offerToReceiveAudio(), 0)
+ options->hasOfferToReceiveAudio()
+ ? std::max(options->offerToReceiveAudio(), 0)
: -1,
- options.hasVoiceActivityDetection() ? options.voiceActivityDetection()
- : true,
- options.hasIceRestart() ? options.iceRestart() : false));
+ options->hasVoiceActivityDetection() ? options->voiceActivityDetection()
+ : true,
+ options->hasIceRestart() ? options->iceRestart() : false));
}
WebRTCAnswerOptions ConvertToWebRTCAnswerOptions(
- const RTCAnswerOptions& options) {
+ const RTCAnswerOptions* options) {
return WebRTCAnswerOptions(RTCAnswerOptionsPlatform::Create(
- options.hasVoiceActivityDetection() ? options.voiceActivityDetection()
- : true));
+ options->hasVoiceActivityDetection() ? options->voiceActivityDetection()
+ : true));
}
scoped_refptr<WebRTCICECandidate> ConvertToWebRTCIceCandidate(
@@ -211,18 +213,18 @@ scoped_refptr<WebRTCICECandidate> ConvertToWebRTCIceCandidate(
const RTCIceCandidateInitOrRTCIceCandidate& candidate) {
DCHECK(!candidate.IsNull());
if (candidate.IsRTCIceCandidateInit()) {
- const RTCIceCandidateInit& ice_candidate_init =
+ const RTCIceCandidateInit* ice_candidate_init =
candidate.GetAsRTCIceCandidateInit();
// TODO(guidou): Change default value to -1. crbug.com/614958.
unsigned short sdp_m_line_index = 0;
- if (ice_candidate_init.hasSdpMLineIndex()) {
- sdp_m_line_index = ice_candidate_init.sdpMLineIndex();
+ if (ice_candidate_init->hasSdpMLineIndex()) {
+ sdp_m_line_index = ice_candidate_init->sdpMLineIndex();
} else {
UseCounter::Count(context,
WebFeature::kRTCIceCandidateDefaultSdpMLineIndex);
}
- return WebRTCICECandidate::Create(ice_candidate_init.candidate(),
- ice_candidate_init.sdpMid(),
+ return WebRTCICECandidate::Create(ice_candidate_init->candidate(),
+ ice_candidate_init->sdpMid(),
sdp_m_line_index);
}
@@ -238,14 +240,14 @@ enum SdpSemanticRequested {
};
SdpSemanticRequested GetSdpSemanticRequested(
- const blink::RTCConfiguration& configuration) {
- if (!configuration.hasSdpSemantics()) {
+ const blink::RTCConfiguration* configuration) {
+ if (!configuration->hasSdpSemantics()) {
return kSdpSemanticRequestedDefault;
}
- if (configuration.sdpSemantics() == "plan-b") {
+ if (configuration->sdpSemantics() == "plan-b") {
return kSdpSemanticRequestedPlanB;
}
- if (configuration.sdpSemantics() == "unified-plan") {
+ if (configuration->sdpSemantics() == "unified-plan") {
return kSdpSemanticRequestedUnifiedPlan;
}
@@ -268,7 +270,8 @@ class WebRTCCertificateObserver : public WebRTCCertificateCallback {
: resolver_(resolver) {}
void OnSuccess(rtc::scoped_refptr<rtc::RTCCertificate> certificate) override {
- resolver_->Resolve(new RTCCertificate(std::move(certificate)));
+ resolver_->Resolve(
+ MakeGarbageCollected<RTCCertificate>(std::move(certificate)));
}
void OnError() override { resolver_->Reject(); }
@@ -286,45 +289,45 @@ webrtc::PeerConnectionInterface::IceTransportsType IceTransportPolicyFromString(
webrtc::PeerConnectionInterface::RTCConfiguration ParseConfiguration(
ExecutionContext* context,
- const RTCConfiguration& configuration,
+ const RTCConfiguration* configuration,
ExceptionState& exception_state) {
DCHECK(context);
webrtc::PeerConnectionInterface::RTCConfiguration web_configuration;
- if (configuration.hasIceTransportPolicy()) {
+ if (configuration->hasIceTransportPolicy()) {
UseCounter::Count(context, WebFeature::kRTCConfigurationIceTransportPolicy);
web_configuration.type =
- IceTransportPolicyFromString(configuration.iceTransportPolicy());
- } else if (configuration.hasIceTransports()) {
+ IceTransportPolicyFromString(configuration->iceTransportPolicy());
+ } else if (configuration->hasIceTransports()) {
UseCounter::Count(context, WebFeature::kRTCConfigurationIceTransports);
web_configuration.type =
- IceTransportPolicyFromString(configuration.iceTransports());
+ IceTransportPolicyFromString(configuration->iceTransports());
}
- if (configuration.bundlePolicy() == "max-compat") {
+ if (configuration->bundlePolicy() == "max-compat") {
web_configuration.bundle_policy =
webrtc::PeerConnectionInterface::kBundlePolicyMaxCompat;
- } else if (configuration.bundlePolicy() == "max-bundle") {
+ } else if (configuration->bundlePolicy() == "max-bundle") {
web_configuration.bundle_policy =
webrtc::PeerConnectionInterface::kBundlePolicyMaxBundle;
} else {
- DCHECK_EQ(configuration.bundlePolicy(), "balanced");
+ DCHECK_EQ(configuration->bundlePolicy(), "balanced");
}
- if (configuration.rtcpMuxPolicy() == "negotiate") {
+ if (configuration->rtcpMuxPolicy() == "negotiate") {
web_configuration.rtcp_mux_policy =
webrtc::PeerConnectionInterface::kRtcpMuxPolicyNegotiate;
Deprecation::CountDeprecation(context, WebFeature::kRtcpMuxPolicyNegotiate);
} else {
- DCHECK_EQ(configuration.rtcpMuxPolicy(), "require");
+ DCHECK_EQ(configuration->rtcpMuxPolicy(), "require");
}
- if (configuration.hasSdpSemantics()) {
- if (configuration.sdpSemantics() == "plan-b") {
+ if (configuration->hasSdpSemantics()) {
+ if (configuration->sdpSemantics() == "plan-b") {
web_configuration.sdp_semantics = webrtc::SdpSemantics::kPlanB;
} else {
- DCHECK_EQ(configuration.sdpSemantics(), "unified-plan");
+ DCHECK_EQ(configuration->sdpSemantics(), "unified-plan");
web_configuration.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
}
} else {
@@ -340,29 +343,29 @@ webrtc::PeerConnectionInterface::RTCConfiguration ParseConfiguration(
}
}
- if (configuration.hasIceServers()) {
+ if (configuration->hasIceServers()) {
std::vector<webrtc::PeerConnectionInterface::IceServer> ice_servers;
- for (const RTCIceServer& ice_server : configuration.iceServers()) {
+ for (const RTCIceServer* ice_server : configuration->iceServers()) {
Vector<String> url_strings;
- if (ice_server.hasURLs()) {
+ if (ice_server->hasURLs()) {
UseCounter::Count(context, WebFeature::kRTCIceServerURLs);
- const StringOrStringSequence& urls = ice_server.urls();
+ const StringOrStringSequence& urls = ice_server->urls();
if (urls.IsString()) {
url_strings.push_back(urls.GetAsString());
} else {
DCHECK(urls.IsStringSequence());
url_strings = urls.GetAsStringSequence();
}
- } else if (ice_server.hasURL()) {
+ } else if (ice_server->hasURL()) {
UseCounter::Count(context, WebFeature::kRTCIceServerURL);
- url_strings.push_back(ice_server.url());
+ url_strings.push_back(ice_server->url());
} else {
exception_state.ThrowTypeError("Malformed RTCIceServer");
return {};
}
- String username = ice_server.username();
- String credential = ice_server.credential();
+ String username = ice_server->username();
+ String credential = ice_server->credential();
for (const String& url_string : url_strings) {
KURL url(NullURL(), url_string);
@@ -399,19 +402,38 @@ webrtc::PeerConnectionInterface::RTCConfiguration ParseConfiguration(
web_configuration.servers = ice_servers;
}
- if (configuration.hasCertificates()) {
+ if (configuration->hasCertificates()) {
const HeapVector<Member<RTCCertificate>>& certificates =
- configuration.certificates();
+ configuration->certificates();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates_copy(
certificates.size());
- for (size_t i = 0; i < certificates.size(); ++i) {
+ for (wtf_size_t i = 0; i < certificates.size(); ++i) {
certificates_copy[i] = certificates[i]->Certificate();
}
web_configuration.certificates = std::move(certificates_copy);
}
web_configuration.ice_candidate_pool_size =
- configuration.iceCandidatePoolSize();
+ configuration->iceCandidatePoolSize();
+
+ if (configuration->hasRtcAudioJitterBufferMaxPackets()) {
+ UseCounter::Count(context, WebFeature::kRTCMaxAudioBufferSize);
+ web_configuration.audio_jitter_buffer_max_packets =
+ static_cast<int>(configuration->rtcAudioJitterBufferMaxPackets());
+ }
+
+ if (configuration->hasRtcAudioJitterBufferFastAccelerate()) {
+ UseCounter::Count(context, WebFeature::kRTCMaxAudioBufferSize);
+ web_configuration.audio_jitter_buffer_fast_accelerate =
+ configuration->hasRtcAudioJitterBufferFastAccelerate();
+ }
+
+ if (configuration->hasRtcAudioJitterBufferMinDelayMs()) {
+ UseCounter::Count(context, WebFeature::kRTCMaxAudioBufferSize);
+ web_configuration.audio_jitter_buffer_min_delay_ms =
+ static_cast<int>(configuration->rtcAudioJitterBufferMinDelayMs());
+ }
+
return web_configuration;
}
@@ -461,22 +483,24 @@ bool FingerprintMismatch(String old_sdp, String new_sdp) {
// It's impossible to generate a valid fingerprint without createOffer
// or createAnswer, so this only applies when there are no fingerprints.
// This is allowed.
- const size_t new_fingerprint_pos = new_sdp.Find("\na=fingerprint:");
+ const wtf_size_t new_fingerprint_pos = new_sdp.Find("\na=fingerprint:");
if (new_fingerprint_pos == kNotFound) {
return false;
}
// Look for fingerprint having been added. Not allowed.
- const size_t old_fingerprint_pos = old_sdp.Find("\na=fingerprint:");
+ const wtf_size_t old_fingerprint_pos = old_sdp.Find("\na=fingerprint:");
if (old_fingerprint_pos == kNotFound) {
return true;
}
// Look for fingerprint being modified. Not allowed. Handle differences in
// line endings ('\r\n' vs, '\n' when looking for the end of the fingerprint).
- size_t old_fingerprint_end = old_sdp.Find("\r\n", old_fingerprint_pos + 1);
+ wtf_size_t old_fingerprint_end =
+ old_sdp.Find("\r\n", old_fingerprint_pos + 1);
if (old_fingerprint_end == WTF::kNotFound) {
old_fingerprint_end = old_sdp.Find("\n", old_fingerprint_pos + 1);
}
- size_t new_fingerprint_end = new_sdp.Find("\r\n", new_fingerprint_pos + 1);
+ wtf_size_t new_fingerprint_end =
+ new_sdp.Find("\r\n", new_fingerprint_pos + 1);
if (new_fingerprint_end == WTF::kNotFound) {
new_fingerprint_end = new_sdp.Find("\n", new_fingerprint_pos + 1);
}
@@ -486,8 +510,94 @@ bool FingerprintMismatch(String old_sdp, String new_sdp) {
new_fingerprint_end - new_fingerprint_pos);
}
+enum class SdpFormat {
+ kSimple,
+ kComplexPlanB,
+ kComplexUnifiedPlan,
+};
+
+base::Optional<SdpFormat> DeduceSdpFormat(const String& type,
+ const String& sdp) {
+ std::unique_ptr<webrtc::SessionDescriptionInterface> session_description(
+ webrtc::CreateSessionDescription(type.Utf8().data(), sdp.Utf8().data(),
+ nullptr));
+ if (!session_description)
+ return base::nullopt;
+ size_t num_audio_mlines = 0u;
+ size_t num_video_mlines = 0u;
+ size_t num_audio_tracks = 0u;
+ size_t num_video_tracks = 0u;
+ for (const cricket::ContentInfo& content :
+ session_description->description()->contents()) {
+ cricket::MediaType media_type = content.media_description()->type();
+ size_t num_tracks = std::max(static_cast<size_t>(1u),
+ content.media_description()->streams().size());
+ if (media_type == cricket::MEDIA_TYPE_AUDIO) {
+ ++num_audio_mlines;
+ num_audio_tracks += num_tracks;
+ } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
+ ++num_video_mlines;
+ num_video_tracks += num_tracks;
+ }
+ }
+ if (num_audio_mlines <= 1u && num_audio_tracks <= 1u &&
+ num_video_mlines <= 1u && num_video_tracks <= 1u) {
+ return SdpFormat::kSimple;
+ }
+ if ((num_audio_mlines == 1u && num_audio_tracks > 1u) ||
+ (num_video_mlines == 1u && num_video_tracks > 1u)) {
+ return SdpFormat::kComplexPlanB;
+ }
+ DCHECK(num_audio_mlines > 1u || num_audio_tracks > 1u ||
+ num_video_mlines > 1u || num_video_tracks > 1u);
+ return SdpFormat::kComplexUnifiedPlan;
+}
+
+RTCSetSessionDescriptionOperation GetRTCVoidRequestOperationType(
+ RTCPeerConnection::SetSdpOperationType operation,
+ const RTCSessionDescriptionInit& description) {
+ switch (operation) {
+ case RTCPeerConnection::SetSdpOperationType::kSetLocalDescription:
+ if (description.type() == "offer")
+ return RTCSetSessionDescriptionOperation::kSetLocalDescriptionOffer;
+ if (description.type() == "answer" || description.type() == "pranswer")
+ return RTCSetSessionDescriptionOperation::kSetLocalDescriptionAnswer;
+ return RTCSetSessionDescriptionOperation::kSetLocalDescriptionInvalidType;
+ case RTCPeerConnection::SetSdpOperationType::kSetRemoteDescription:
+ if (description.type() == "offer")
+ return RTCSetSessionDescriptionOperation::kSetRemoteDescriptionOffer;
+ if (description.type() == "answer" || description.type() == "pranswer")
+ return RTCSetSessionDescriptionOperation::kSetRemoteDescriptionAnswer;
+ return RTCSetSessionDescriptionOperation::
+ kSetRemoteDescriptionInvalidType;
+ }
+}
+
} // namespace
+SdpUsageCategory DeduceSdpUsageCategory(const String& sdp_type,
+ const String& sdp,
+ bool sdp_semantics_specified,
+ webrtc::SdpSemantics sdp_semantics) {
+ auto sdp_format = DeduceSdpFormat(sdp_type, sdp);
+ if (!sdp_format)
+ return SdpUsageCategory::kUnknown;
+ switch (*sdp_format) {
+ case SdpFormat::kSimple:
+ return SdpUsageCategory::kSafe;
+ case SdpFormat::kComplexPlanB:
+ return (sdp_semantics_specified &&
+ sdp_semantics == webrtc::SdpSemantics::kPlanB)
+ ? SdpUsageCategory::kSafe
+ : SdpUsageCategory::kUnsafe;
+ case SdpFormat::kComplexUnifiedPlan:
+ return (sdp_semantics_specified &&
+ sdp_semantics == webrtc::SdpSemantics::kUnifiedPlan)
+ ? SdpUsageCategory::kSafe
+ : SdpUsageCategory::kUnsafe;
+ }
+}
+
RTCPeerConnection::EventWrapper::EventWrapper(Event* event,
BoolFunction function)
: event_(event), setup_function_(std::move(function)) {}
@@ -505,7 +615,7 @@ void RTCPeerConnection::EventWrapper::Trace(blink::Visitor* visitor) {
RTCPeerConnection* RTCPeerConnection::Create(
ExecutionContext* context,
- const RTCConfiguration& rtc_configuration,
+ const RTCConfiguration* rtc_configuration,
const Dictionary& media_constraints,
ExceptionState& exception_state) {
// Count number of PeerConnections that could potentially be impacted by CSP
@@ -546,15 +656,15 @@ RTCPeerConnection* RTCPeerConnection::Create(
}
MediaErrorState media_error_state;
- WebMediaConstraints constraints = MediaConstraintsImpl::Create(
+ WebMediaConstraints constraints = media_constraints_impl::Create(
context, media_constraints, media_error_state);
if (media_error_state.HadException()) {
media_error_state.RaiseException(exception_state);
return nullptr;
}
- RTCPeerConnection* peer_connection = new RTCPeerConnection(
- context, std::move(configuration), rtc_configuration.hasSdpSemantics(),
+ RTCPeerConnection* peer_connection = MakeGarbageCollected<RTCPeerConnection>(
+ context, std::move(configuration), rtc_configuration->hasSdpSemantics(),
constraints, exception_state);
peer_connection->PauseIfNeeded();
if (exception_state.HadException())
@@ -576,8 +686,10 @@ RTCPeerConnection::RTCPeerConnection(
: PausableObject(context),
signaling_state_(
webrtc::PeerConnectionInterface::SignalingState::kStable),
- ice_gathering_state_(kICEGatheringStateNew),
- ice_connection_state_(kICEConnectionStateNew),
+ ice_gathering_state_(webrtc::PeerConnectionInterface::kIceGatheringNew),
+ ice_connection_state_(webrtc::PeerConnectionInterface::kIceConnectionNew),
+ peer_connection_state_(
+ webrtc::PeerConnectionInterface::PeerConnectionState::kNew),
// WebRTC spec specifies kNetworking as task source.
// https://www.w3.org/TR/webrtc/#operation
dispatch_scheduled_event_runner_(
@@ -656,23 +768,51 @@ void RTCPeerConnection::Dispose() {
// Promptly clears a raw reference from content/ to an on-heap object
// so that content/ doesn't access it in a lazy sweeping phase.
peer_handler_.reset();
+
+ // UMA for CallSetupStates. This metric is reported regardless of whether or
+ // not getUserMedia() has been called in this document.
+ UMA_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CallSetupState.OffererState",
+ call_setup_state_tracker_.offerer_state());
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.CallSetupState.AnswererState",
+ call_setup_state_tracker_.answerer_state());
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.CallSetupState.CallSetupState",
+ call_setup_state_tracker_.GetCallSetupState());
+ // UMA for CallSetupStates only for documents that have performed
+ // getUserMedia(). This heuristic hints that the peer connection is likely
+ // used in a media/conferencing context, which is a use case that may be
+ // particularly sensitive to the Plan B vs Unified Plan switch.
+ if (call_setup_state_tracker_.document_uses_media()) {
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.CallSetupStateWithGum.OffererState",
+ call_setup_state_tracker_.offerer_state());
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.CallSetupStateWithGum.AnswererState",
+ call_setup_state_tracker_.answerer_state());
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.CallSetupStateWithGum.CallSetupState",
+ call_setup_state_tracker_.GetCallSetupState());
+ }
}
ScriptPromise RTCPeerConnection::createOffer(ScriptState* script_state,
- const RTCOfferOptions& options) {
+ const RTCOfferOptions* options) {
if (signaling_state_ ==
webrtc::PeerConnectionInterface::SignalingState::kClosed) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kInvalidStateError,
kSignalingStateClosedMessage));
}
-
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ OffererState::kCreateOfferPending, HasDocumentMedia());
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
RTCSessionDescriptionRequest* request =
RTCSessionDescriptionRequestPromiseImpl::Create(
- this, resolver, "RTCPeerConnection", "createOffer");
- if (options.hasOfferToReceiveAudio() || options.hasOfferToReceiveVideo()) {
+ RTCCreateSessionDescriptionOperation::kCreateOffer, this, resolver,
+ "RTCPeerConnection", "createOffer");
+ if (options->hasOfferToReceiveAudio() || options->hasOfferToReceiveVideo()) {
ExecutionContext* context = ExecutionContext::From(script_state);
UseCounter::Count(
context,
@@ -700,9 +840,13 @@ ScriptPromise RTCPeerConnection::createOffer(
ParseOfferOptions(rtc_offer_options, exception_state);
if (exception_state.HadException())
return ScriptPromise();
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ OffererState::kCreateOfferPending, HasDocumentMedia());
RTCSessionDescriptionRequest* request =
RTCSessionDescriptionRequestImpl::Create(
- GetExecutionContext(), this, success_callback, error_callback);
+ GetExecutionContext(),
+ RTCCreateSessionDescriptionOperation::kCreateOffer, this,
+ success_callback, error_callback);
if (offer_options) {
if (offer_options->OfferToReceiveAudio() != -1 ||
@@ -717,7 +861,7 @@ ScriptPromise RTCPeerConnection::createOffer(
peer_handler_->CreateOffer(request, WebRTCOfferOptions(offer_options));
} else {
MediaErrorState media_error_state;
- WebMediaConstraints constraints = MediaConstraintsImpl::Create(
+ WebMediaConstraints constraints = media_constraints_impl::Create(
context, rtc_offer_options, media_error_state);
// Report constraints parsing errors via the callback, but ignore
// unknown/unsupported constraints as they would be silently discarded by
@@ -745,7 +889,7 @@ ScriptPromise RTCPeerConnection::createOffer(
}
ScriptPromise RTCPeerConnection::createAnswer(ScriptState* script_state,
- const RTCAnswerOptions& options) {
+ const RTCAnswerOptions* options) {
if (signaling_state_ ==
webrtc::PeerConnectionInterface::SignalingState::kClosed) {
return ScriptPromise::RejectWithDOMException(
@@ -753,11 +897,14 @@ ScriptPromise RTCPeerConnection::createAnswer(ScriptState* script_state,
kSignalingStateClosedMessage));
}
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerPending, HasDocumentMedia());
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
RTCSessionDescriptionRequest* request =
RTCSessionDescriptionRequestPromiseImpl::Create(
- this, resolver, "RTCPeerConnection", "createAnswer");
+ RTCCreateSessionDescriptionOperation::kCreateAnswer, this, resolver,
+ "RTCPeerConnection", "createAnswer");
peer_handler_->CreateAnswer(request, ConvertToWebRTCAnswerOptions(options));
return promise;
}
@@ -784,7 +931,7 @@ ScriptPromise RTCPeerConnection::createAnswer(
return ScriptPromise::CastUndefined(script_state);
MediaErrorState media_error_state;
- WebMediaConstraints constraints = MediaConstraintsImpl::Create(
+ WebMediaConstraints constraints = media_constraints_impl::Create(
context, media_constraints, media_error_state);
// Report constraints parsing errors via the callback, but ignore
// unknown/unsupported constraints as they would be silently discarded by
@@ -797,16 +944,20 @@ ScriptPromise RTCPeerConnection::createAnswer(
return ScriptPromise::CastUndefined(script_state);
}
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ AnswererState::kCreateAnswerPending, HasDocumentMedia());
RTCSessionDescriptionRequest* request =
RTCSessionDescriptionRequestImpl::Create(
- GetExecutionContext(), this, success_callback, error_callback);
+ GetExecutionContext(),
+ RTCCreateSessionDescriptionOperation::kCreateAnswer, this,
+ success_callback, error_callback);
peer_handler_->CreateAnswer(request, constraints);
return ScriptPromise::CastUndefined(script_state);
}
DOMException* RTCPeerConnection::checkSdpForStateErrors(
ExecutionContext* context,
- const RTCSessionDescriptionInit& session_description_init,
+ const RTCSessionDescriptionInit* session_description_init,
String* sdp) {
if (signaling_state_ ==
webrtc::PeerConnectionInterface::SignalingState::kClosed) {
@@ -814,11 +965,11 @@ DOMException* RTCPeerConnection::checkSdpForStateErrors(
kSignalingStateClosedMessage);
}
- *sdp = session_description_init.sdp();
- if (session_description_init.type() == "offer") {
+ *sdp = session_description_init->sdp();
+ if (session_description_init->type() == "offer") {
if (sdp->IsNull() || sdp->IsEmpty()) {
*sdp = last_offer_;
- } else if (session_description_init.sdp() != last_offer_) {
+ } else if (session_description_init->sdp() != last_offer_) {
if (FingerprintMismatch(last_offer_, *sdp)) {
return DOMException::Create(DOMExceptionCode::kInvalidModificationError,
kModifiedSdpMessage);
@@ -828,11 +979,11 @@ DOMException* RTCPeerConnection::checkSdpForStateErrors(
// TODO(https://crbug.com/823036): Return failure for all modification.
}
}
- } else if (session_description_init.type() == "answer" ||
- session_description_init.type() == "pranswer") {
+ } else if (session_description_init->type() == "answer" ||
+ session_description_init->type() == "pranswer") {
if (sdp->IsNull() || sdp->IsEmpty()) {
*sdp = last_answer_;
- } else if (session_description_init.sdp() != last_answer_) {
+ } else if (session_description_init->sdp() != last_answer_) {
if (FingerprintMismatch(last_answer_, *sdp)) {
return DOMException::Create(DOMExceptionCode::kInvalidModificationError,
kModifiedSdpMessage);
@@ -846,72 +997,208 @@ DOMException* RTCPeerConnection::checkSdpForStateErrors(
return nullptr;
}
-bool RTCPeerConnection::ShouldShowComplexPlanBSdpWarning(
- const RTCSessionDescriptionInit& session_description_init) const {
- if (sdp_semantics_specified_)
- return false;
- if (!session_description_init.hasType() || !session_description_init.hasSdp())
- return false;
- std::unique_ptr<webrtc::SessionDescriptionInterface> session_description(
- webrtc::CreateSessionDescription(
- session_description_init.type().Utf8().data(),
- session_description_init.sdp().Utf8().data(), nullptr));
- if (!session_description)
- return false;
- size_t num_audio_mlines = 0u;
- size_t num_video_mlines = 0u;
- size_t num_audio_tracks = 0u;
- size_t num_video_tracks = 0u;
- for (const cricket::ContentInfo& content :
- session_description->description()->contents()) {
- cricket::MediaType media_type = content.media_description()->type();
- size_t num_tracks = std::max(static_cast<size_t>(1u),
- content.media_description()->streams().size());
- if (media_type == cricket::MEDIA_TYPE_AUDIO) {
- ++num_audio_mlines;
- num_audio_tracks += num_tracks;
- } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
- ++num_video_mlines;
- num_video_tracks += num_tracks;
- }
+base::Optional<ComplexSdpCategory> RTCPeerConnection::CheckForComplexSdp(
+ const RTCSessionDescriptionInit* session_description_init) const {
+ if (!session_description_init->hasType() ||
+ !session_description_init->hasSdp())
+ return base::nullopt;
+
+ base::Optional<SdpFormat> sdp_format = DeduceSdpFormat(
+ session_description_init->type(), session_description_init->sdp());
+ if (!sdp_format) {
+ return sdp_semantics_specified_
+ ? ComplexSdpCategory::kErrorExplicitSemantics
+ : ComplexSdpCategory::kErrorImplicitSemantics;
}
- return (num_audio_mlines == 1u && num_audio_tracks > 1u) ||
- (num_video_mlines == 1u && num_video_tracks > 1u);
+
+ if (*sdp_format == SdpFormat::kComplexPlanB) {
+ return sdp_semantics_specified_
+ ? ComplexSdpCategory::kPlanBExplicitSemantics
+ : ComplexSdpCategory::kPlanBImplicitSemantics;
+ } else if (*sdp_format == SdpFormat::kComplexUnifiedPlan) {
+ return sdp_semantics_specified_
+ ? ComplexSdpCategory::kUnifiedPlanExplicitSemantics
+ : ComplexSdpCategory::kUnifiedPlanImplicitSemantics;
+ }
+
+ return base::nullopt;
}
-ScriptPromise RTCPeerConnection::setLocalDescription(
- ScriptState* script_state,
- const RTCSessionDescriptionInit& session_description_init) {
- if (ShouldShowComplexPlanBSdpWarning(session_description_init)) {
+void RTCPeerConnection::MaybeWarnAboutUnsafeSdp(
+ const RTCSessionDescriptionInit* session_description_init) const {
+ base::Optional<ComplexSdpCategory> complex_sdp_category =
+ CheckForComplexSdp(session_description_init);
+ if (!complex_sdp_category)
+ return;
+
+ Document* document = To<Document>(GetExecutionContext());
+ RTCPeerConnectionController::From(*document).MaybeReportComplexSdp(
+ *complex_sdp_category);
+
+ if (*complex_sdp_category == ComplexSdpCategory::kPlanBImplicitSemantics) {
Deprecation::CountDeprecation(
GetExecutionContext(),
WebFeature::kRTCPeerConnectionComplexPlanBSdpUsingDefaultSdpSemantics);
}
+}
+
+const CallSetupStateTracker& RTCPeerConnection::call_setup_state_tracker()
+ const {
+ return call_setup_state_tracker_;
+}
+
+void RTCPeerConnection::NoteCallSetupStateEventPending(
+ RTCPeerConnection::SetSdpOperationType operation,
+ const RTCSessionDescriptionInit& description) {
+ switch (operation) {
+ case RTCPeerConnection::SetSdpOperationType::kSetLocalDescription:
+ if (description.type() == "offer") {
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ OffererState::kSetLocalOfferPending, HasDocumentMedia());
+ } else if (description.type() == "answer" ||
+ description.type() == "pranswer") {
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetLocalAnswerPending, HasDocumentMedia());
+ }
+ break;
+ case RTCPeerConnection::SetSdpOperationType::kSetRemoteDescription:
+ if (description.type() == "offer") {
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ AnswererState::kSetRemoteOfferPending, HasDocumentMedia());
+ } else if (description.type() == "answer" ||
+ description.type() == "pranswer") {
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ OffererState::kSetRemoteAnswerPending, HasDocumentMedia());
+ }
+ break;
+ }
+}
+
+void RTCPeerConnection::NoteSessionDescriptionRequestCompleted(
+ RTCCreateSessionDescriptionOperation operation,
+ bool success) {
+ switch (operation) {
+ case RTCCreateSessionDescriptionOperation::kCreateOffer:
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ success ? OffererState::kCreateOfferResolved
+ : OffererState::kCreateOfferRejected,
+ HasDocumentMedia());
+ return;
+ case RTCCreateSessionDescriptionOperation::kCreateAnswer:
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ success ? AnswererState::kCreateAnswerResolved
+ : AnswererState::kCreateAnswerRejected,
+ HasDocumentMedia());
+ return;
+ }
+}
+
+void RTCPeerConnection::NoteVoidRequestCompleted(
+ RTCSetSessionDescriptionOperation operation,
+ bool success) {
+ switch (operation) {
+ case RTCSetSessionDescriptionOperation::kSetLocalDescriptionOffer:
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ success ? OffererState::kSetLocalOfferResolved
+ : OffererState::kSetLocalOfferRejected,
+ HasDocumentMedia());
+ break;
+ case RTCSetSessionDescriptionOperation::kSetLocalDescriptionAnswer:
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ success ? AnswererState::kSetLocalAnswerResolved
+ : AnswererState::kSetLocalAnswerRejected,
+ HasDocumentMedia());
+ break;
+ case RTCSetSessionDescriptionOperation::kSetRemoteDescriptionOffer:
+ call_setup_state_tracker_.NoteAnswererStateEvent(
+ success ? AnswererState::kSetRemoteOfferResolved
+ : AnswererState::kSetRemoteOfferRejected,
+ HasDocumentMedia());
+ break;
+ case RTCSetSessionDescriptionOperation::kSetRemoteDescriptionAnswer:
+ call_setup_state_tracker_.NoteOffererStateEvent(
+ success ? OffererState::kSetRemoteAnswerResolved
+ : OffererState::kSetRemoteAnswerRejected,
+ HasDocumentMedia());
+ break;
+ case RTCSetSessionDescriptionOperation::kSetLocalDescriptionInvalidType:
+ case RTCSetSessionDescriptionOperation::kSetRemoteDescriptionInvalidType:
+ break;
+ }
+}
+
+bool RTCPeerConnection::HasDocumentMedia() const {
+ UserMediaController* user_media_controller = UserMediaController::From(
+ To<Document>(GetExecutionContext())->GetFrame());
+ return user_media_controller &&
+ user_media_controller->HasRequestedUserMedia();
+}
+
+void RTCPeerConnection::ReportSetSdpUsage(
+ SetSdpOperationType operation_type,
+ const RTCSessionDescriptionInit* session_description_init) const {
+ SdpUsageCategory sdp_usage = DeduceSdpUsageCategory(
+ session_description_init->type(), session_description_init->sdp(),
+ sdp_semantics_specified_, sdp_semantics_);
+ if (session_description_init->type() == "offer") {
+ switch (operation_type) {
+ case SetSdpOperationType::kSetLocalDescription:
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpComplexUsage.SetLocalOffer", sdp_usage);
+ break;
+ case SetSdpOperationType::kSetRemoteDescription:
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpComplexUsage.SetRemoteOffer", sdp_usage);
+ break;
+ }
+ } else if (session_description_init->type() == "answer" ||
+ session_description_init->type() == "pranswer") {
+ switch (operation_type) {
+ case SetSdpOperationType::kSetLocalDescription:
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpComplexUsage.SetLocalAnswer", sdp_usage);
+ break;
+ case SetSdpOperationType::kSetRemoteDescription:
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpComplexUsage.SetRemoteAnswer", sdp_usage);
+ break;
+ }
+ }
+}
+
+ScriptPromise RTCPeerConnection::setLocalDescription(
+ ScriptState* script_state,
+ const RTCSessionDescriptionInit* session_description_init) {
+ MaybeWarnAboutUnsafeSdp(session_description_init);
+ ReportSetSdpUsage(SetSdpOperationType::kSetLocalDescription,
+ session_description_init);
String sdp;
DOMException* exception = checkSdpForStateErrors(
ExecutionContext::From(script_state), session_description_init, &sdp);
if (exception) {
return ScriptPromise::RejectWithDOMException(script_state, exception);
}
+ NoteCallSetupStateEventPending(SetSdpOperationType::kSetLocalDescription,
+ *session_description_init);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
RTCVoidRequest* request = RTCVoidRequestPromiseImpl::Create(
+ GetRTCVoidRequestOperationType(SetSdpOperationType::kSetLocalDescription,
+ *session_description_init),
this, resolver, "RTCPeerConnection", "setLocalDescription");
peer_handler_->SetLocalDescription(
- request, WebRTCSessionDescription(session_description_init.type(), sdp));
+ request, WebRTCSessionDescription(session_description_init->type(), sdp));
return promise;
}
ScriptPromise RTCPeerConnection::setLocalDescription(
ScriptState* script_state,
- const RTCSessionDescriptionInit& session_description_init,
+ const RTCSessionDescriptionInit* session_description_init,
V8VoidFunction* success_callback,
V8RTCPeerConnectionErrorCallback* error_callback) {
- if (ShouldShowComplexPlanBSdpWarning(session_description_init)) {
- Deprecation::CountDeprecation(
- GetExecutionContext(),
- WebFeature::kRTCPeerConnectionComplexPlanBSdpUsingDefaultSdpSemantics);
- }
+ MaybeWarnAboutUnsafeSdp(session_description_init);
+ ReportSetSdpUsage(SetSdpOperationType::kSetLocalDescription,
+ session_description_init);
ExecutionContext* context = ExecutionContext::From(script_state);
if (success_callback && error_callback) {
UseCounter::Count(
@@ -939,11 +1226,16 @@ ScriptPromise RTCPeerConnection::setLocalDescription(
return ScriptPromise::CastUndefined(script_state);
}
+ NoteCallSetupStateEventPending(SetSdpOperationType::kSetLocalDescription,
+ *session_description_init);
RTCVoidRequest* request = RTCVoidRequestImpl::Create(
- GetExecutionContext(), this, success_callback, error_callback);
+ GetExecutionContext(),
+ GetRTCVoidRequestOperationType(SetSdpOperationType::kSetLocalDescription,
+ *session_description_init),
+ this, success_callback, error_callback);
peer_handler_->SetLocalDescription(
- request, WebRTCSessionDescription(session_description_init.type(),
- session_description_init.sdp()));
+ request, WebRTCSessionDescription(session_description_init->type(),
+ session_description_init->sdp()));
return ScriptPromise::CastUndefined(script_state);
}
@@ -976,12 +1268,10 @@ RTCSessionDescription* RTCPeerConnection::pendingLocalDescription() {
ScriptPromise RTCPeerConnection::setRemoteDescription(
ScriptState* script_state,
- const RTCSessionDescriptionInit& session_description_init) {
- if (ShouldShowComplexPlanBSdpWarning(session_description_init)) {
- Deprecation::CountDeprecation(
- GetExecutionContext(),
- WebFeature::kRTCPeerConnectionComplexPlanBSdpUsingDefaultSdpSemantics);
- }
+ const RTCSessionDescriptionInit* session_description_init) {
+ MaybeWarnAboutUnsafeSdp(session_description_init);
+ ReportSetSdpUsage(SetSdpOperationType::kSetRemoteDescription,
+ session_description_init);
if (signaling_state_ ==
webrtc::PeerConnectionInterface::SignalingState::kClosed) {
return ScriptPromise::RejectWithDOMException(
@@ -989,26 +1279,28 @@ ScriptPromise RTCPeerConnection::setRemoteDescription(
kSignalingStateClosedMessage));
}
+ NoteCallSetupStateEventPending(SetSdpOperationType::kSetRemoteDescription,
+ *session_description_init);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
RTCVoidRequest* request = RTCVoidRequestPromiseImpl::Create(
+ GetRTCVoidRequestOperationType(SetSdpOperationType::kSetRemoteDescription,
+ *session_description_init),
this, resolver, "RTCPeerConnection", "setRemoteDescription");
peer_handler_->SetRemoteDescription(
- request, WebRTCSessionDescription(session_description_init.type(),
- session_description_init.sdp()));
+ request, WebRTCSessionDescription(session_description_init->type(),
+ session_description_init->sdp()));
return promise;
}
ScriptPromise RTCPeerConnection::setRemoteDescription(
ScriptState* script_state,
- const RTCSessionDescriptionInit& session_description_init,
+ const RTCSessionDescriptionInit* session_description_init,
V8VoidFunction* success_callback,
V8RTCPeerConnectionErrorCallback* error_callback) {
- if (ShouldShowComplexPlanBSdpWarning(session_description_init)) {
- Deprecation::CountDeprecation(
- GetExecutionContext(),
- WebFeature::kRTCPeerConnectionComplexPlanBSdpUsingDefaultSdpSemantics);
- }
+ MaybeWarnAboutUnsafeSdp(session_description_init);
+ ReportSetSdpUsage(SetSdpOperationType::kSetRemoteDescription,
+ session_description_init);
ExecutionContext* context = ExecutionContext::From(script_state);
if (success_callback && error_callback) {
UseCounter::Count(
@@ -1030,11 +1322,16 @@ ScriptPromise RTCPeerConnection::setRemoteDescription(
if (CallErrorCallbackIfSignalingStateClosed(signaling_state_, error_callback))
return ScriptPromise::CastUndefined(script_state);
+ NoteCallSetupStateEventPending(SetSdpOperationType::kSetRemoteDescription,
+ *session_description_init);
RTCVoidRequest* request = RTCVoidRequestImpl::Create(
- GetExecutionContext(), this, success_callback, error_callback);
+ GetExecutionContext(),
+ GetRTCVoidRequestOperationType(SetSdpOperationType::kSetRemoteDescription,
+ *session_description_init),
+ this, success_callback, error_callback);
peer_handler_->SetRemoteDescription(
- request, WebRTCSessionDescription(session_description_init.type(),
- session_description_init.sdp()));
+ request, WebRTCSessionDescription(session_description_init->type(),
+ session_description_init->sdp()));
return ScriptPromise::CastUndefined(script_state);
}
@@ -1065,15 +1362,17 @@ RTCSessionDescription* RTCPeerConnection::pendingRemoteDescription() {
return RTCSessionDescription::Create(web_session_description);
}
-void RTCPeerConnection::getConfiguration(RTCConfiguration& result) {
+RTCConfiguration* RTCPeerConnection::getConfiguration(
+ ScriptState* script_state) const {
+ RTCConfiguration* result = RTCConfiguration::Create();
const auto& webrtc_configuration = peer_handler_->GetConfiguration();
switch (webrtc_configuration.type) {
case webrtc::PeerConnectionInterface::kRelay:
- result.setIceTransportPolicy("relay");
+ result->setIceTransportPolicy("relay");
break;
case webrtc::PeerConnectionInterface::kAll:
- result.setIceTransportPolicy("all");
+ result->setIceTransportPolicy("all");
break;
default:
NOTREACHED();
@@ -1081,13 +1380,13 @@ void RTCPeerConnection::getConfiguration(RTCConfiguration& result) {
switch (webrtc_configuration.bundle_policy) {
case webrtc::PeerConnectionInterface::kBundlePolicyMaxCompat:
- result.setBundlePolicy("max-compat");
+ result->setBundlePolicy("max-compat");
break;
case webrtc::PeerConnectionInterface::kBundlePolicyMaxBundle:
- result.setBundlePolicy("max-bundle");
+ result->setBundlePolicy("max-bundle");
break;
case webrtc::PeerConnectionInterface::kBundlePolicyBalanced:
- result.setBundlePolicy("balanced");
+ result->setBundlePolicy("balanced");
break;
default:
NOTREACHED();
@@ -1095,10 +1394,10 @@ void RTCPeerConnection::getConfiguration(RTCConfiguration& result) {
switch (webrtc_configuration.rtcp_mux_policy) {
case webrtc::PeerConnectionInterface::kRtcpMuxPolicyNegotiate:
- result.setRtcpMuxPolicy("negotiate");
+ result->setRtcpMuxPolicy("negotiate");
break;
case webrtc::PeerConnectionInterface::kRtcpMuxPolicyRequire:
- result.setRtcpMuxPolicy("require");
+ result->setRtcpMuxPolicy("require");
break;
default:
NOTREACHED();
@@ -1106,50 +1405,69 @@ void RTCPeerConnection::getConfiguration(RTCConfiguration& result) {
switch (webrtc_configuration.sdp_semantics) {
case webrtc::SdpSemantics::kPlanB:
- result.setSdpSemantics("plan-b");
+ result->setSdpSemantics("plan-b");
break;
case webrtc::SdpSemantics::kUnifiedPlan:
- result.setSdpSemantics("unified-plan");
+ result->setSdpSemantics("unified-plan");
break;
default:
NOTREACHED();
}
- HeapVector<RTCIceServer> ice_servers;
- ice_servers.ReserveCapacity(webrtc_configuration.servers.size());
+ HeapVector<Member<RTCIceServer>> ice_servers;
+ ice_servers.ReserveCapacity(
+ SafeCast<wtf_size_t>(webrtc_configuration.servers.size()));
for (const auto& webrtc_server : webrtc_configuration.servers) {
- ice_servers.emplace_back();
- auto& ice_server = ice_servers.back();
+ auto* ice_server = RTCIceServer::Create();
StringOrStringSequence urls;
Vector<String> url_vector;
- url_vector.ReserveCapacity(webrtc_server.urls.size());
+ url_vector.ReserveCapacity(SafeCast<wtf_size_t>(webrtc_server.urls.size()));
for (const auto& url : webrtc_server.urls) {
url_vector.emplace_back(url.c_str());
}
urls.SetStringSequence(std::move(url_vector));
- ice_server.setURLs(urls);
- ice_server.setUsername(webrtc_server.username.c_str());
- ice_server.setCredential(webrtc_server.password.c_str());
+ ice_server->setURLs(urls);
+ ice_server->setUsername(webrtc_server.username.c_str());
+ ice_server->setCredential(webrtc_server.password.c_str());
+ ice_servers.push_back(ice_server);
}
- result.setIceServers(ice_servers);
+ result->setIceServers(ice_servers);
if (!webrtc_configuration.certificates.empty()) {
HeapVector<blink::Member<RTCCertificate>> certificates;
- certificates.ReserveCapacity(webrtc_configuration.certificates.size());
+ certificates.ReserveCapacity(
+ SafeCast<wtf_size_t>(webrtc_configuration.certificates.size()));
for (const auto& webrtc_certificate : webrtc_configuration.certificates) {
- certificates.emplace_back(new RTCCertificate(webrtc_certificate));
+ certificates.emplace_back(
+ MakeGarbageCollected<RTCCertificate>(webrtc_certificate));
}
- result.setCertificates(certificates);
+ result->setCertificates(certificates);
+ }
+
+ result->setIceCandidatePoolSize(webrtc_configuration.ice_candidate_pool_size);
+
+ const auto* context = ExecutionContext::From(script_state);
+ if (origin_trials::RtcAudioJitterBufferMaxPacketsEnabled(context)) {
+ int audio_jitter_buffer_max_packets =
+ webrtc_configuration.audio_jitter_buffer_max_packets;
+ result->setRtcAudioJitterBufferMaxPackets(
+ static_cast<int32_t>(audio_jitter_buffer_max_packets));
+ result->setRtcAudioJitterBufferFastAccelerate(
+ webrtc_configuration.audio_jitter_buffer_fast_accelerate);
+ int audio_jitter_buffer_min_delay_ms =
+ webrtc_configuration.audio_jitter_buffer_min_delay_ms;
+ result->setRtcAudioJitterBufferMinDelayMs(
+ static_cast<int32_t>(audio_jitter_buffer_min_delay_ms));
}
- result.setIceCandidatePoolSize(webrtc_configuration.ice_candidate_pool_size);
+ return result;
}
void RTCPeerConnection::setConfiguration(
ScriptState* script_state,
- const RTCConfiguration& rtc_configuration,
+ const RTCConfiguration* rtc_configuration,
ExceptionState& exception_state) {
if (ThrowExceptionIfSignalingStateClosed(signaling_state_, exception_state))
return;
@@ -1331,7 +1649,7 @@ ScriptPromise RTCPeerConnection::addIceCandidate(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
RTCVoidRequest* request = RTCVoidRequestPromiseImpl::Create(
- this, resolver, "RTCPeerConnection", "addIceCandidate");
+ base::nullopt, this, resolver, "RTCPeerConnection", "addIceCandidate");
scoped_refptr<WebRTCICECandidate> web_candidate = ConvertToWebRTCIceCandidate(
ExecutionContext::From(script_state), candidate);
bool implemented =
@@ -1363,8 +1681,9 @@ ScriptPromise RTCPeerConnection::addIceCandidate(
return ScriptPromise();
}
- RTCVoidRequest* request = RTCVoidRequestImpl::Create(
- GetExecutionContext(), this, success_callback, error_callback);
+ RTCVoidRequest* request =
+ RTCVoidRequestImpl::Create(GetExecutionContext(), base::nullopt, this,
+ success_callback, error_callback);
scoped_refptr<WebRTCICECandidate> web_candidate = ConvertToWebRTCIceCandidate(
ExecutionContext::From(script_state), candidate);
bool implemented =
@@ -1400,11 +1719,11 @@ String RTCPeerConnection::signalingState() const {
String RTCPeerConnection::iceGatheringState() const {
switch (ice_gathering_state_) {
- case kICEGatheringStateNew:
+ case webrtc::PeerConnectionInterface::kIceGatheringNew:
return "new";
- case kICEGatheringStateGathering:
+ case webrtc::PeerConnectionInterface::kIceGatheringGathering:
return "gathering";
- case kICEGatheringStateComplete:
+ case webrtc::PeerConnectionInterface::kIceGatheringComplete:
return "complete";
}
@@ -1413,20 +1732,48 @@ String RTCPeerConnection::iceGatheringState() const {
}
String RTCPeerConnection::iceConnectionState() const {
+ if (closed_) {
+ return "closed";
+ }
switch (ice_connection_state_) {
- case kICEConnectionStateNew:
+ case webrtc::PeerConnectionInterface::kIceConnectionNew:
return "new";
- case kICEConnectionStateChecking:
+ case webrtc::PeerConnectionInterface::kIceConnectionChecking:
return "checking";
- case kICEConnectionStateConnected:
+ case webrtc::PeerConnectionInterface::kIceConnectionConnected:
return "connected";
- case kICEConnectionStateCompleted:
+ case webrtc::PeerConnectionInterface::kIceConnectionCompleted:
return "completed";
- case kICEConnectionStateFailed:
+ case webrtc::PeerConnectionInterface::kIceConnectionFailed:
return "failed";
- case kICEConnectionStateDisconnected:
+ case webrtc::PeerConnectionInterface::kIceConnectionDisconnected:
+ return "disconnected";
+ case webrtc::PeerConnectionInterface::kIceConnectionClosed:
+ return "closed";
+ case webrtc::PeerConnectionInterface::kIceConnectionMax:
+ NOTREACHED();
+ }
+
+ NOTREACHED();
+ return String();
+}
+
+String RTCPeerConnection::connectionState() const {
+ if (closed_) {
+ return "closed";
+ }
+ switch (peer_connection_state_) {
+ case webrtc::PeerConnectionInterface::PeerConnectionState::kNew:
+ return "new";
+ case webrtc::PeerConnectionInterface::PeerConnectionState::kConnecting:
+ return "connecting";
+ case webrtc::PeerConnectionInterface::PeerConnectionState::kConnected:
+ return "connected";
+ case webrtc::PeerConnectionInterface::PeerConnectionState::kDisconnected:
return "disconnected";
- case kICEConnectionStateClosed:
+ case webrtc::PeerConnectionInterface::PeerConnectionState::kFailed:
+ return "failed";
+ case webrtc::PeerConnectionInterface::PeerConnectionState::kClosed:
return "closed";
}
@@ -1443,8 +1790,8 @@ void RTCPeerConnection::addStream(ScriptState* script_state,
if (!media_constraints.IsUndefinedOrNull()) {
MediaErrorState media_error_state;
WebMediaConstraints constraints =
- MediaConstraintsImpl::Create(ExecutionContext::From(script_state),
- media_constraints, media_error_state);
+ media_constraints_impl::Create(ExecutionContext::From(script_state),
+ media_constraints, media_error_state);
if (media_error_state.HadException()) {
media_error_state.RaiseException(exception_state);
return;
@@ -1479,7 +1826,7 @@ void RTCPeerConnection::removeStream(MediaStream* stream,
}
String RTCPeerConnection::id(ScriptState* script_state) const {
- DCHECK(OriginTrials::RtcPeerConnectionIdEnabled(
+ DCHECK(origin_trials::RtcPeerConnectionIdEnabled(
ExecutionContext::From(script_state)));
return peer_handler_->Id();
}
@@ -1633,8 +1980,8 @@ ScriptPromise RTCPeerConnection::PromiseBasedGetStats(
ScriptPromiseResolver* resolver =
ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- peer_handler_->GetStats(
- WebRTCStatsReportCallbackResolver::Create(resolver));
+ peer_handler_->GetStats(WebRTCStatsReportCallbackResolver::Create(resolver),
+ GetRTCStatsFilter(script_state));
return promise;
}
@@ -1693,7 +2040,7 @@ const HeapVector<Member<RTCRtpReceiver>>& RTCPeerConnection::getReceivers()
RTCRtpTransceiver* RTCPeerConnection::addTransceiver(
const MediaStreamTrackOrString& track_or_kind,
- const RTCRtpTransceiverInit& init,
+ const RTCRtpTransceiverInit* init,
ExceptionState& exception_state) {
if (sdp_semantics_ != webrtc::SdpSemantics::kUnifiedPlan) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
@@ -1760,7 +2107,7 @@ RTCRtpSender* RTCPeerConnection::addTrack(MediaStreamTrack* track,
}
WebVector<WebMediaStream> web_streams(streams.size());
- for (size_t i = 0; i < streams.size(); ++i) {
+ for (wtf_size_t i = 0; i < streams.size(); ++i) {
web_streams[i] = streams[i]->Descriptor();
}
webrtc::RTCErrorOr<std::unique_ptr<WebRTCRtpTransceiver>>
@@ -1846,38 +2193,38 @@ void RTCPeerConnection::removeTrack(RTCRtpSender* sender,
RTCDataChannel* RTCPeerConnection::createDataChannel(
ScriptState* script_state,
String label,
- const RTCDataChannelInit& data_channel_dict,
+ const RTCDataChannelInit* data_channel_dict,
ExceptionState& exception_state) {
if (ThrowExceptionIfSignalingStateClosed(signaling_state_, exception_state))
return nullptr;
WebRTCDataChannelInit init;
- init.ordered = data_channel_dict.ordered();
+ init.ordered = data_channel_dict->ordered();
ExecutionContext* context = ExecutionContext::From(script_state);
// maxPacketLifeTime and maxRetransmitTime are two names for the same thing,
// but maxPacketLifeTime is the standardized name so it takes precedence.
- if (data_channel_dict.hasMaxPacketLifeTime()) {
+ if (data_channel_dict->hasMaxPacketLifeTime()) {
UseCounter::Count(
context,
WebFeature::kRTCPeerConnectionCreateDataChannelMaxPacketLifeTime);
- init.max_retransmit_time = data_channel_dict.maxPacketLifeTime();
- } else if (data_channel_dict.hasMaxRetransmitTime()) {
+ init.max_retransmit_time = data_channel_dict->maxPacketLifeTime();
+ } else if (data_channel_dict->hasMaxRetransmitTime()) {
Deprecation::CountDeprecation(
context, WebFeature::kRTCDataChannelInitMaxRetransmitTime);
UseCounter::Count(
context,
WebFeature::kRTCPeerConnectionCreateDataChannelMaxRetransmitTime);
- init.max_retransmit_time = data_channel_dict.maxRetransmitTime();
+ init.max_retransmit_time = data_channel_dict->maxRetransmitTime();
}
- if (data_channel_dict.hasMaxRetransmits()) {
+ if (data_channel_dict->hasMaxRetransmits()) {
UseCounter::Count(
context, WebFeature::kRTCPeerConnectionCreateDataChannelMaxRetransmits);
- init.max_retransmits = data_channel_dict.maxRetransmits();
+ init.max_retransmits = data_channel_dict->maxRetransmits();
}
- init.protocol = data_channel_dict.protocol();
- init.negotiated = data_channel_dict.negotiated();
- if (data_channel_dict.hasId())
- init.id = data_channel_dict.id();
+ init.protocol = data_channel_dict->protocol();
+ init.negotiated = data_channel_dict->negotiated();
+ if (data_channel_dict->hasId())
+ init.id = data_channel_dict->id();
RTCDataChannel* channel = RTCDataChannel::Create(
GetExecutionContext(), peer_handler_.get(), label, init, exception_state);
@@ -1959,7 +2306,8 @@ RTCRtpSender* RTCPeerConnection::CreateOrUpdateSender(
RTCRtpSender* sender;
if (sender_it == rtp_senders_.end()) {
// Create new sender (with empty stream set).
- sender = new RTCRtpSender(this, std::move(web_sender), kind, track, {});
+ sender = MakeGarbageCollected<RTCRtpSender>(
+ this, std::move(web_sender), kind, track, MediaStreamVector());
rtp_senders_.push_back(sender);
} else {
// Update existing sender (not touching the stream set).
@@ -1988,7 +2336,8 @@ RTCRtpReceiver* RTCPeerConnection::CreateOrUpdateReceiver(
RTCRtpReceiver* receiver;
if (receiver_it == rtp_receivers_.end()) {
// Create new receiver.
- receiver = new RTCRtpReceiver(std::move(web_receiver), track, {});
+ receiver = MakeGarbageCollected<RTCRtpReceiver>(std::move(web_receiver),
+ track, MediaStreamVector());
// Receiving tracks should be muted by default. SetReadyState() propagates
// the related state changes to ensure it is muted on all layers. It also
// fires events - which is not desired - but because they fire synchronously
@@ -2020,8 +2369,8 @@ RTCRtpTransceiver* RTCPeerConnection::CreateOrUpdateTransceiver(
auto* transceiver_it = FindTransceiver(*web_transceiver);
if (transceiver_it == transceivers_.end()) {
// Create new tranceiver.
- transceiver = new RTCRtpTransceiver(this, std::move(web_transceiver),
- sender, receiver);
+ transceiver = MakeGarbageCollected<RTCRtpTransceiver>(
+ this, std::move(web_transceiver), sender, receiver);
transceivers_.push_back(transceiver);
} else {
// Update existing transceiver.
@@ -2080,10 +2429,16 @@ void RTCPeerConnection::RegisterTrack(MediaStreamTrack* track) {
}
void RTCPeerConnection::NoteSdpCreated(const RTCSessionDescription& desc) {
+ SdpUsageCategory sdp_usage = DeduceSdpUsageCategory(
+ desc.type(), desc.sdp(), sdp_semantics_specified_, sdp_semantics_);
if (desc.type() == "offer") {
last_offer_ = desc.sdp();
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpComplexUsage.CreateOffer", sdp_usage);
} else if (desc.type() == "answer") {
last_answer_ = desc.sdp();
+ UMA_HISTOGRAM_ENUMERATION(
+ "WebRTC.PeerConnection.SdpComplexUsage.CreateAnswer", sdp_usage);
}
}
@@ -2127,7 +2482,7 @@ void RTCPeerConnection::MaybeFireNegotiationNeeded() {
if (!negotiation_needed_ || closed_)
return;
negotiation_needed_ = false;
- DispatchEvent(*Event::Create(EventTypeNames::negotiationneeded));
+ DispatchEvent(*Event::Create(event_type_names::kNegotiationneeded));
}
void RTCPeerConnection::DidGenerateICECandidate(
@@ -2147,20 +2502,27 @@ void RTCPeerConnection::DidChangeSignalingState(
ChangeSignalingState(new_state, true);
}
-void RTCPeerConnection::DidChangeICEGatheringState(
- ICEGatheringState new_state) {
+void RTCPeerConnection::DidChangeIceGatheringState(
+ webrtc::PeerConnectionInterface::IceGatheringState new_state) {
DCHECK(!closed_);
DCHECK(GetExecutionContext()->IsContextThread());
ChangeIceGatheringState(new_state);
}
-void RTCPeerConnection::DidChangeICEConnectionState(
- ICEConnectionState new_state) {
+void RTCPeerConnection::DidChangeIceConnectionState(
+ webrtc::PeerConnectionInterface::IceConnectionState new_state) {
DCHECK(!closed_);
DCHECK(GetExecutionContext()->IsContextThread());
ChangeIceConnectionState(new_state);
}
+void RTCPeerConnection::DidChangePeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState new_state) {
+ DCHECK(!closed_);
+ DCHECK(GetExecutionContext()->IsContextThread());
+ ChangePeerConnectionState(new_state);
+}
+
void RTCPeerConnection::DidAddReceiverPlanB(
std::unique_ptr<WebRTCRtpReceiver> web_receiver) {
DCHECK(!closed_);
@@ -2201,7 +2563,7 @@ void RTCPeerConnection::DidAddReceiverPlanB(
std::move(audio_tracks), std::move(video_tracks));
// Schedule to fire "pc.onaddstream".
ScheduleDispatchEvent(
- MediaStreamEvent::Create(EventTypeNames::addstream, stream));
+ MediaStreamEvent::Create(event_type_names::kAddstream, stream));
} else {
// The stream already exists, add the track to it.
// This will cause to schedule to fire "stream.onaddtrack".
@@ -2210,11 +2572,11 @@ void RTCPeerConnection::DidAddReceiverPlanB(
streams.push_back(stream);
}
DCHECK(FindReceiver(*web_receiver) == rtp_receivers_.end());
- RTCRtpReceiver* rtp_receiver =
- new RTCRtpReceiver(std::move(web_receiver), track, streams);
+ RTCRtpReceiver* rtp_receiver = MakeGarbageCollected<RTCRtpReceiver>(
+ std::move(web_receiver), track, streams);
rtp_receivers_.push_back(rtp_receiver);
- ScheduleDispatchEvent(
- new RTCTrackEvent(rtp_receiver, rtp_receiver->track(), streams, nullptr));
+ ScheduleDispatchEvent(MakeGarbageCollected<RTCTrackEvent>(
+ rtp_receiver, rtp_receiver->track(), streams, nullptr));
}
void RTCPeerConnection::DidRemoveReceiverPlanB(
@@ -2244,7 +2606,7 @@ void RTCPeerConnection::DidRemoveReceiverPlanB(
stream->StreamEnded();
stream->UnregisterObserver(this);
ScheduleDispatchEvent(
- MediaStreamEvent::Create(EventTypeNames::removestream, stream));
+ MediaStreamEvent::Create(event_type_names::kRemovestream, stream));
}
}
@@ -2269,16 +2631,30 @@ void RTCPeerConnection::DidModifyTransceivers(
RTCRtpTransceiver* transceiver =
CreateOrUpdateTransceiver(std::move(web_transceiver));
- // The transceiver is now up-to-date. Compare before/after values of
- // FiredDirectionHasRecv() and process the remote track if it changed.
- if (is_remote_description && !previously_had_recv &&
- transceiver->FiredDirectionHasRecv()) {
- ProcessAdditionOfRemoteTrack(
- transceiver, transceiver->web_transceiver()->Receiver()->StreamIds(),
- &add_list, &track_events);
+ size_t add_list_prev_size = add_list.size();
+ // "Set the associated remote streams".
+ // https://w3c.github.io/webrtc-pc/#set-associated-remote-streams
+ SetAssociatedMediaStreams(
+ transceiver->receiver(),
+ transceiver->web_transceiver()->Receiver()->StreamIds(), &remove_list,
+ &add_list);
+ // The transceiver is now up-to-date. Check if the receiver's track is now
+ // considered added or removed (though a receiver's track is never truly
+ // removed). A track event indicates either that the track was "added" in
+ // the sense that FiredDirectionHasRecv() changed, or that a new remote
+ // stream was added containing the receiver's track.
+ if (is_remote_description &&
+ ((!previously_had_recv && transceiver->FiredDirectionHasRecv()) ||
+ add_list_prev_size != add_list.size())) {
+ // "Process the addition of a remote track".
+ // https://w3c.github.io/webrtc-pc/#process-remote-track-addition
+ track_events.push_back(transceiver);
}
if (previously_had_recv && !transceiver->FiredDirectionHasRecv()) {
- ProcessRemovalOfRemoteTrack(transceiver, &remove_list, &mute_tracks);
+ // "Process the removal of a remote track".
+ // https://w3c.github.io/webrtc-pc/#process-remote-track-removal
+ if (!transceiver->receiver()->track()->muted())
+ mute_tracks.push_back(transceiver->receiver()->track());
}
}
MediaStreamVector current_streams = getRemoteStreams();
@@ -2316,20 +2692,20 @@ void RTCPeerConnection::DidModifyTransceivers(
// Legacy APIs: "pc.onaddstream" and "pc.onremovestream".
for (const auto& current_stream : current_streams) {
if (!previous_streams.Contains(current_stream)) {
- ScheduleDispatchEvent(
- MediaStreamEvent::Create(EventTypeNames::addstream, current_stream));
+ ScheduleDispatchEvent(MediaStreamEvent::Create(
+ event_type_names::kAddstream, current_stream));
}
}
for (const auto& previous_stream : previous_streams) {
if (!current_streams.Contains(previous_stream)) {
ScheduleDispatchEvent(MediaStreamEvent::Create(
- EventTypeNames::removestream, previous_stream));
+ event_type_names::kRemovestream, previous_stream));
}
}
// Fire "pc.ontrack" synchronously.
for (auto& transceiver : track_events) {
- auto* track_event = new RTCTrackEvent(
+ auto* track_event = MakeGarbageCollected<RTCTrackEvent>(
transceiver->receiver(), transceiver->receiver()->track(),
transceiver->receiver()->streams(), transceiver);
DispatchEvent(*track_event);
@@ -2344,29 +2720,6 @@ void RTCPeerConnection::DidModifyTransceivers(
}
}
-void RTCPeerConnection::ProcessAdditionOfRemoteTrack(
- RTCRtpTransceiver* transceiver,
- const WebVector<WebString>& stream_ids,
- HeapVector<std::pair<Member<MediaStream>, Member<MediaStreamTrack>>>*
- add_list,
- HeapVector<Member<RTCRtpTransceiver>>* track_events) {
- SetAssociatedMediaStreams(transceiver->receiver(), stream_ids, nullptr,
- add_list);
- track_events->push_back(transceiver);
-}
-
-void RTCPeerConnection::ProcessRemovalOfRemoteTrack(
- RTCRtpTransceiver* transceiver,
- HeapVector<std::pair<Member<MediaStream>, Member<MediaStreamTrack>>>*
- remove_list,
- HeapVector<Member<MediaStreamTrack>>* mute_tracks) {
- WebVector<WebString> stream_ids = {};
- SetAssociatedMediaStreams(transceiver->receiver(), stream_ids, remove_list,
- nullptr);
- if (!transceiver->receiver()->track()->muted())
- mute_tracks->push_back(transceiver->receiver()->track());
-}
-
void RTCPeerConnection::SetAssociatedMediaStreams(
RTCRtpReceiver* receiver,
const WebVector<WebString>& stream_ids,
@@ -2421,7 +2774,7 @@ void RTCPeerConnection::DidAddRemoteDataChannel(
RTCDataChannel* channel =
RTCDataChannel::Create(GetExecutionContext(), base::WrapUnique(handler));
ScheduleDispatchEvent(
- RTCDataChannelEvent::Create(EventTypeNames::datachannel, channel));
+ RTCDataChannelEvent::Create(event_type_names::kDatachannel, channel));
has_data_channels_ = true;
}
@@ -2438,7 +2791,7 @@ void RTCPeerConnection::ReleasePeerConnectionHandler() {
return;
stopped_ = true;
- ice_connection_state_ = kICEConnectionStateClosed;
+ ice_connection_state_ = webrtc::PeerConnectionInterface::kIceConnectionClosed;
signaling_state_ = webrtc::PeerConnectionInterface::SignalingState::kClosed;
dispatch_scheduled_event_runner_->Stop();
@@ -2455,7 +2808,7 @@ void RTCPeerConnection::ClosePeerConnection() {
}
const AtomicString& RTCPeerConnection::InterfaceName() const {
- return EventTargetNames::RTCPeerConnection;
+ return event_target_names::kRTCPeerConnection;
}
ExecutionContext* RTCPeerConnection::GetExecutionContext() const {
@@ -2482,7 +2835,7 @@ void RTCPeerConnection::ChangeSignalingState(
if (signaling_state_ !=
webrtc::PeerConnectionInterface::SignalingState::kClosed) {
signaling_state_ = signaling_state;
- Event* event = Event::Create(EventTypeNames::signalingstatechange);
+ Event* event = Event::Create(event_type_names::kSignalingstatechange);
if (dispatch_event_immediately)
DispatchEvent(*event);
else
@@ -2491,13 +2844,15 @@ void RTCPeerConnection::ChangeSignalingState(
}
void RTCPeerConnection::ChangeIceGatheringState(
- ICEGatheringState ice_gathering_state) {
- if (ice_connection_state_ != kICEConnectionStateClosed) {
+ webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state) {
+ if (ice_connection_state_ !=
+ webrtc::PeerConnectionInterface::kIceConnectionClosed) {
ScheduleDispatchEvent(
- Event::Create(EventTypeNames::icegatheringstatechange),
+ Event::Create(event_type_names::kIcegatheringstatechange),
WTF::Bind(&RTCPeerConnection::SetIceGatheringState,
WrapPersistent(this), ice_gathering_state));
- if (ice_gathering_state == kICEGatheringStateComplete) {
+ if (ice_gathering_state ==
+ webrtc::PeerConnectionInterface::kIceGatheringComplete) {
// If ICE gathering is completed, generate a null ICE candidate, to
// signal end of candidates.
ScheduleDispatchEvent(RTCPeerConnectionIceEvent::Create(nullptr));
@@ -2506,8 +2861,9 @@ void RTCPeerConnection::ChangeIceGatheringState(
}
bool RTCPeerConnection::SetIceGatheringState(
- ICEGatheringState ice_gathering_state) {
- if (ice_connection_state_ != kICEConnectionStateClosed &&
+ webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state) {
+ if (ice_connection_state_ !=
+ webrtc::PeerConnectionInterface::kIceConnectionClosed &&
ice_gathering_state_ != ice_gathering_state) {
ice_gathering_state_ = ice_gathering_state;
return true;
@@ -2516,23 +2872,49 @@ bool RTCPeerConnection::SetIceGatheringState(
}
void RTCPeerConnection::ChangeIceConnectionState(
- ICEConnectionState ice_connection_state) {
- if (ice_connection_state_ != kICEConnectionStateClosed) {
+ webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state) {
+ if (ice_connection_state_ !=
+ webrtc::PeerConnectionInterface::kIceConnectionClosed) {
ScheduleDispatchEvent(
- Event::Create(EventTypeNames::iceconnectionstatechange),
+ Event::Create(event_type_names::kIceconnectionstatechange),
WTF::Bind(&RTCPeerConnection::SetIceConnectionState,
WrapPersistent(this), ice_connection_state));
}
}
bool RTCPeerConnection::SetIceConnectionState(
- ICEConnectionState ice_connection_state) {
- if (ice_connection_state_ != kICEConnectionStateClosed &&
+ webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state) {
+ if (ice_connection_state_ !=
+ webrtc::PeerConnectionInterface::kIceConnectionClosed &&
ice_connection_state_ != ice_connection_state) {
ice_connection_state_ = ice_connection_state;
- if (ice_connection_state_ == kICEConnectionStateConnected)
+ if (ice_connection_state_ ==
+ webrtc::PeerConnectionInterface::kIceConnectionConnected)
RecordRapporMetrics();
+ return true;
+ }
+ return false;
+}
+
+void RTCPeerConnection::ChangePeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState
+ peer_connection_state) {
+ if (peer_connection_state_ !=
+ webrtc::PeerConnectionInterface::PeerConnectionState::kClosed) {
+ ScheduleDispatchEvent(
+ Event::Create(event_type_names::kConnectionstatechange),
+ WTF::Bind(&RTCPeerConnection::SetPeerConnectionState,
+ WrapPersistent(this), peer_connection_state));
+ }
+}
+bool RTCPeerConnection::SetPeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState
+ peer_connection_state) {
+ if (peer_connection_state_ !=
+ webrtc::PeerConnectionInterface::PeerConnectionState::kClosed &&
+ peer_connection_state_ != peer_connection_state) {
+ peer_connection_state_ = peer_connection_state;
return true;
}
return false;
@@ -2544,7 +2926,10 @@ void RTCPeerConnection::CloseInternal() {
peer_handler_->Stop();
closed_ = true;
- ChangeIceConnectionState(kICEConnectionStateClosed);
+ ChangeIceConnectionState(
+ webrtc::PeerConnectionInterface::kIceConnectionClosed);
+ SetPeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState::kClosed);
ChangeSignalingState(webrtc::PeerConnectionInterface::SignalingState::kClosed,
false);
for (auto& transceiver : transceivers_) {
@@ -2565,7 +2950,7 @@ void RTCPeerConnection::ScheduleDispatchEvent(Event* event) {
void RTCPeerConnection::ScheduleDispatchEvent(Event* event,
BoolFunction setup_function) {
scheduled_events_.push_back(
- new EventWrapper(event, std::move(setup_function)));
+ MakeGarbageCollected<EventWrapper>(event, std::move(setup_function)));
dispatch_scheduled_event_runner_->RunAsync();
}
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
index fc779f36c01..43782a7271e 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
@@ -42,10 +42,15 @@
#include "third_party/blink/renderer/modules/crypto/normalize_algorithm.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream.h"
+#include "third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h"
#include "third_party/blink/renderer/platform/async_method_runner.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
+#include "third_party/blink/renderer/platform/peerconnection/rtc_session_description_request.h"
+#include "third_party/blink/renderer/platform/peerconnection/rtc_void_request.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
namespace blink {
@@ -72,6 +77,28 @@ class V8RTCSessionDescriptionCallback;
class V8RTCStatsCallback;
class V8VoidFunction;
+// This enum is used to track usage of SDP during the transition of the default
+// "sdpSemantics" value from "Plan B" to "Unified Plan". Usage refers to
+// operations such as createOffer(), createAnswer(), setLocalDescription() and
+// setRemoteDescription(). "Complex" SDP refers to SDP that is not compatible
+// between SDP formats. Usage of SDP falls into two categories: "safe" and
+// "unsafe". Applications with unsafe usage are predicted to break when the
+// default changes. This includes complex SDP usage and relying on the default
+// sdpSemantics. kUnknown is used if the SDP format could not be deduced, such
+// as if SDP could not be parsed.
+enum class SdpUsageCategory {
+ kSafe = 0,
+ kUnsafe = 1,
+ kUnknown = 2,
+ kMaxValue = kUnknown,
+};
+
+MODULES_EXPORT SdpUsageCategory
+DeduceSdpUsageCategory(const String& sdp_type,
+ const String& sdp,
+ bool sdp_semantics_specified,
+ webrtc::SdpSemantics sdp_semantics);
+
class MODULES_EXPORT RTCPeerConnection final
: public EventTargetWithInlineData,
public WebRTCPeerConnectionHandlerClient,
@@ -84,29 +111,35 @@ class MODULES_EXPORT RTCPeerConnection final
public:
static RTCPeerConnection* Create(ExecutionContext*,
- const RTCConfiguration&,
+ const RTCConfiguration*,
const Dictionary&,
ExceptionState&);
+
+ RTCPeerConnection(ExecutionContext*,
+ webrtc::PeerConnectionInterface::RTCConfiguration,
+ bool sdp_semantics_specified,
+ WebMediaConstraints,
+ ExceptionState&);
~RTCPeerConnection() override;
- ScriptPromise createOffer(ScriptState*, const RTCOfferOptions&);
+ ScriptPromise createOffer(ScriptState*, const RTCOfferOptions*);
ScriptPromise createOffer(ScriptState*,
V8RTCSessionDescriptionCallback*,
V8RTCPeerConnectionErrorCallback*,
const Dictionary&,
ExceptionState&);
- ScriptPromise createAnswer(ScriptState*, const RTCAnswerOptions&);
+ ScriptPromise createAnswer(ScriptState*, const RTCAnswerOptions*);
ScriptPromise createAnswer(ScriptState*,
V8RTCSessionDescriptionCallback*,
V8RTCPeerConnectionErrorCallback*,
const Dictionary&);
ScriptPromise setLocalDescription(ScriptState*,
- const RTCSessionDescriptionInit&);
+ const RTCSessionDescriptionInit*);
ScriptPromise setLocalDescription(
ScriptState*,
- const RTCSessionDescriptionInit&,
+ const RTCSessionDescriptionInit*,
V8VoidFunction*,
V8RTCPeerConnectionErrorCallback* = nullptr);
RTCSessionDescription* localDescription();
@@ -114,10 +147,10 @@ class MODULES_EXPORT RTCPeerConnection final
RTCSessionDescription* pendingLocalDescription();
ScriptPromise setRemoteDescription(ScriptState*,
- const RTCSessionDescriptionInit&);
+ const RTCSessionDescriptionInit*);
ScriptPromise setRemoteDescription(
ScriptState*,
- const RTCSessionDescriptionInit&,
+ const RTCSessionDescriptionInit*,
V8VoidFunction*,
V8RTCPeerConnectionErrorCallback* = nullptr);
RTCSessionDescription* remoteDescription();
@@ -126,8 +159,8 @@ class MODULES_EXPORT RTCPeerConnection final
String signalingState() const;
- void getConfiguration(RTCConfiguration&);
- void setConfiguration(ScriptState*, const RTCConfiguration&, ExceptionState&);
+ RTCConfiguration* getConfiguration(ScriptState*) const;
+ void setConfiguration(ScriptState*, const RTCConfiguration*, ExceptionState&);
// Certificate management
// http://w3c.github.io/webrtc-pc/#sec.cert-mgmt
@@ -149,6 +182,8 @@ class MODULES_EXPORT RTCPeerConnection final
String iceConnectionState() const;
+ String connectionState() const;
+
// A local stream is any stream associated with a sender.
MediaStreamVector getLocalStreams() const;
// A remote stream is any stream associated with a receiver.
@@ -184,15 +219,15 @@ class MODULES_EXPORT RTCPeerConnection final
const HeapVector<Member<RTCRtpSender>>& getSenders() const;
const HeapVector<Member<RTCRtpReceiver>>& getReceivers() const;
RTCRtpTransceiver* addTransceiver(const MediaStreamTrackOrString&,
- const RTCRtpTransceiverInit&,
+ const RTCRtpTransceiverInit*,
ExceptionState&);
RTCRtpSender* addTrack(MediaStreamTrack*, MediaStreamVector, ExceptionState&);
void removeTrack(RTCRtpSender*, ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(track);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(track, kTrack);
RTCDataChannel* createDataChannel(ScriptState*,
String label,
- const RTCDataChannelInit&,
+ const RTCDataChannelInit*,
ExceptionState&);
RTCDTMFSender* createDTMFSender(MediaStreamTrack*, ExceptionState&);
@@ -209,17 +244,29 @@ class MODULES_EXPORT RTCPeerConnection final
bool ShouldFireDefaultCallbacks() { return !closed_ && !stopped_; }
bool ShouldFireGetStatsCallback() { return !stopped_; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(negotiationneeded);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidate);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(signalingstatechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(addstream);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(removestream);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(iceconnectionstatechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(icegatheringstatechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(datachannel);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(negotiationneeded, kNegotiationneeded);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidate, kIcecandidate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(signalingstatechange, kSignalingstatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(addstream, kAddstream);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(removestream, kRemovestream);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(iceconnectionstatechange,
+ kIceconnectionstatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connectionstatechange,
+ kConnectionstatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(icegatheringstatechange,
+ kIcegatheringstatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(datachannel, kDatachannel);
// Utility to note result of CreateOffer / CreateAnswer
void NoteSdpCreated(const RTCSessionDescription&);
+ // Utility to report SDP usage of setLocalDescription / setRemoteDescription.
+ enum class SetSdpOperationType {
+ kSetLocalDescription,
+ kSetRemoteDescription,
+ };
+ void ReportSetSdpUsage(
+ SetSdpOperationType operation_type,
+ const RTCSessionDescriptionInit* session_description_init) const;
// MediaStreamObserver
void OnStreamAddTrack(MediaStream*, MediaStreamTrack*) override;
@@ -230,8 +277,12 @@ class MODULES_EXPORT RTCPeerConnection final
void DidGenerateICECandidate(scoped_refptr<WebRTCICECandidate>) override;
void DidChangeSignalingState(
webrtc::PeerConnectionInterface::SignalingState) override;
- void DidChangeICEGatheringState(ICEGatheringState) override;
- void DidChangeICEConnectionState(ICEConnectionState) override;
+ void DidChangeIceGatheringState(
+ webrtc::PeerConnectionInterface::IceGatheringState) override;
+ void DidChangeIceConnectionState(
+ webrtc::PeerConnectionInterface::IceConnectionState) override;
+ void DidChangePeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState) override;
void DidAddReceiverPlanB(std::unique_ptr<WebRTCRtpReceiver>) override;
void DidRemoveReceiverPlanB(std::unique_ptr<WebRTCRtpReceiver>) override;
void DidModifyTransceivers(std::vector<std::unique_ptr<WebRTCRtpTransceiver>>,
@@ -258,17 +309,28 @@ class MODULES_EXPORT RTCPeerConnection final
static int PeerConnectionCount();
static int PeerConnectionCountLimit();
- // SLD/SRD helper method, public for testing.
- // "Complex" Plan B SDP is SDP that is not compatible with Unified Plan, i.e.
- // SDP that has multiple tracks listed under the same m= sections. We should
- // show a deprecation warning when setLocalDescription() or
- // setRemoteDescription() is called and:
- // - The SDP is complex Plan B SDP.
- // - sdpSemantics was not specified at RTCPeerConnection construction.
- // Such calls would normally succeed, but as soon as the default switches to
- // Unified Plan they would fail. This decides whether to show deprecation for
- // WebFeature::kRTCPeerConnectionComplexPlanBSdpUsingDefaultSdpSemantics.
- bool ShouldShowComplexPlanBSdpWarning(const RTCSessionDescriptionInit&) const;
+ // SLD/SRD Helper method, public for testing.
+ // This function returns a value that indicates if complex SDP is being used
+ // and whether a format is explicitly specified. If the SDP is not complex or
+ // it could not be parsed, base::nullopt is returned.
+ // When "Complex" SDP (i.e., SDP that has multiple tracks) is used without
+ // explicitly specifying the SDP format, there may be errors if the
+ // application assumes a format that differs from the actual default format.
+ base::Optional<ComplexSdpCategory> CheckForComplexSdp(
+ const RTCSessionDescriptionInit* session_description_init) const;
+
+ const CallSetupStateTracker& call_setup_state_tracker() const;
+ void NoteCallSetupStateEventPending(
+ RTCPeerConnection::SetSdpOperationType operation,
+ const RTCSessionDescriptionInit& description);
+ void NoteSessionDescriptionRequestCompleted(
+ RTCCreateSessionDescriptionOperation operation,
+ bool success);
+ void NoteVoidRequestCompleted(RTCSetSessionDescriptionOperation operation,
+ bool success);
+ // Checks if the document that the peer connection lives in has ever executed
+ // getUserMedia().
+ bool HasDocumentMedia() const;
void Trace(blink::Visitor*) override;
@@ -297,12 +359,6 @@ class MODULES_EXPORT RTCPeerConnection final
private:
BoolFunction setup_function_;
};
-
- RTCPeerConnection(ExecutionContext*,
- webrtc::PeerConnectionInterface::RTCConfiguration,
- bool sdp_semantics_specified,
- WebMediaConstraints,
- ExceptionState&);
void Dispose();
void ScheduleDispatchEvent(Event*);
@@ -346,19 +402,6 @@ class MODULES_EXPORT RTCPeerConnection final
RTCRtpTransceiver* CreateOrUpdateTransceiver(
std::unique_ptr<WebRTCRtpTransceiver>);
- // https://w3c.github.io/webrtc-pc/#process-remote-track-addition
- void ProcessAdditionOfRemoteTrack(
- RTCRtpTransceiver* transceiver,
- const WebVector<WebString>& stream_ids,
- HeapVector<std::pair<Member<MediaStream>, Member<MediaStreamTrack>>>*
- add_list,
- HeapVector<Member<RTCRtpTransceiver>>* track_events);
- // https://w3c.github.io/webrtc-pc/#process-remote-track-removal
- void ProcessRemovalOfRemoteTrack(
- RTCRtpTransceiver* transceiver,
- HeapVector<std::pair<Member<MediaStream>, Member<MediaStreamTrack>>>*
- remove_list,
- HeapVector<Member<MediaStreamTrack>>* mute_tracks);
// Update the |receiver->streams()| to the streams indicated by |stream_ids|,
// adding to |remove_list| and |add_list| accordingly.
// https://w3c.github.io/webrtc-pc/#set-associated-remote-streams
@@ -393,26 +436,34 @@ class MODULES_EXPORT RTCPeerConnection final
// that are delayed somehow and cause the application to read a "complete"
// gathering state twice, missing the "gathering" state in the middle.
void ChangeIceGatheringState(
- WebRTCPeerConnectionHandlerClient::ICEGatheringState);
- bool SetIceGatheringState(
- WebRTCPeerConnectionHandlerClient::ICEGatheringState);
+ webrtc::PeerConnectionInterface::IceGatheringState);
+ bool SetIceGatheringState(webrtc::PeerConnectionInterface::IceGatheringState);
void ChangeIceConnectionState(
- WebRTCPeerConnectionHandlerClient::ICEConnectionState);
+ webrtc::PeerConnectionInterface::IceConnectionState);
bool SetIceConnectionState(
- WebRTCPeerConnectionHandlerClient::ICEConnectionState);
+ webrtc::PeerConnectionInterface::IceConnectionState);
+
+ void ChangePeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState);
+ bool SetPeerConnectionState(
+ webrtc::PeerConnectionInterface::PeerConnectionState);
void CloseInternal();
void RecordRapporMetrics();
DOMException* checkSdpForStateErrors(ExecutionContext*,
- const RTCSessionDescriptionInit&,
+ const RTCSessionDescriptionInit*,
String* sdp);
+ void MaybeWarnAboutUnsafeSdp(
+ const RTCSessionDescriptionInit* session_description_init) const;
webrtc::PeerConnectionInterface::SignalingState signaling_state_;
- ICEGatheringState ice_gathering_state_;
- ICEConnectionState ice_connection_state_;
+ webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state_;
+ webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state_;
+ webrtc::PeerConnectionInterface::PeerConnectionState peer_connection_state_;
+ CallSetupStateTracker call_setup_state_tracker_;
// A map containing any track that is in use by the peer connection. This
// includes tracks of |rtp_senders_| and |rtp_receivers_|.
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl
index 41becb6a96d..9aa8ddd9bb6 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl
@@ -49,6 +49,15 @@ enum RTCIceConnectionState {
"closed"
};
+enum RTCPeerConnectionState {
+ "new",
+ "connecting",
+ "connected",
+ "disconnected",
+ "failed",
+ "closed"
+};
+
// https://w3c.github.io/webrtc-pc/#interface-definition
// TODO(guidou): Many types are of the wrong type in this interface:
@@ -75,14 +84,16 @@ enum RTCIceConnectionState {
readonly attribute RTCSignalingState signalingState;
readonly attribute RTCIceGatheringState iceGatheringState;
readonly attribute RTCIceConnectionState iceConnectionState;
+ readonly attribute RTCPeerConnectionState connectionState;
// readonly attribute boolean? canTrickleIceCandidates;
- RTCConfiguration getConfiguration();
+ [CallWith=ScriptState] RTCConfiguration getConfiguration();
[CallWith=ScriptState, RaisesException] void setConfiguration(RTCConfiguration configuration);
void close();
attribute EventHandler onnegotiationneeded;
attribute EventHandler onicecandidate;
attribute EventHandler onsignalingstatechange;
attribute EventHandler oniceconnectionstatechange;
+ attribute EventHandler onconnectionstatechange;
attribute EventHandler onicegatheringstatechange;
// https://w3c.github.io/webrtc-pc/#legacy-interface-extensions
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.cc
new file mode 100644
index 00000000000..b09cf4dcaae
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.cc
@@ -0,0 +1,48 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h"
+
+#include "services/metrics/public/cpp/ukm_builders.h"
+
+namespace blink {
+
+// static
+const char RTCPeerConnectionController::kSupplementName[] =
+ "RTCPeerConnectionController";
+
+// static
+RTCPeerConnectionController& RTCPeerConnectionController::From(
+ Document& document) {
+ RTCPeerConnectionController* supplement =
+ Supplement<Document>::From<RTCPeerConnectionController>(document);
+ if (!supplement) {
+ supplement = new RTCPeerConnectionController(document);
+ Supplement<Document>::ProvideTo(document, supplement);
+ }
+ return *supplement;
+}
+
+RTCPeerConnectionController::RTCPeerConnectionController(Document& document)
+ : Supplement<Document>(document) {}
+
+void RTCPeerConnectionController::MaybeReportComplexSdp(
+ ComplexSdpCategory complex_sdp_category) {
+ if (has_reported_ukm_)
+ return;
+
+ // Report only the first observation for the document and ignore all others.
+ // This provides a good balance between privacy and meaningful metrics.
+ has_reported_ukm_ = true;
+ ukm::SourceId source_id = GetSupplementable()->UkmSourceID();
+ ukm::builders::WebRTC_ComplexSdp(source_id)
+ .SetCategory(static_cast<int64_t>(complex_sdp_category))
+ .Record(GetSupplementable()->UkmRecorder());
+}
+
+void RTCPeerConnectionController::Trace(Visitor* visitor) {
+ Supplement<Document>::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h
new file mode 100644
index 00000000000..281ddbaba20
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h
@@ -0,0 +1,51 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_CONTROLLER_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_CONTROLLER_H_
+
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/supplementable.h"
+
+namespace blink {
+
+// This enum is used to track usage of Complex SDP with UKM.
+// The prefix indicates the SDP format used (PlanB or UnifiedPlan) or error if
+// the SDP could not be parsed.
+// The suffix indicates whether the peer connection has been configured with
+// explicit SDP semantics (ExplicitSemantics) or not (ImplicitSemantics). The
+// SDP format used does not necessarily match the semantics with which the peer
+// connection has been configured.
+enum class ComplexSdpCategory {
+ kPlanBImplicitSemantics = 0,
+ kPlanBExplicitSemantics = 1,
+ kUnifiedPlanImplicitSemantics = 2,
+ kUnifiedPlanExplicitSemantics = 3,
+ kErrorImplicitSemantics = 4,
+ kErrorExplicitSemantics = 5,
+};
+
+class RTCPeerConnectionController
+ : public GarbageCollected<RTCPeerConnectionController>,
+ public Supplement<Document> {
+ USING_GARBAGE_COLLECTED_MIXIN(RTCPeerConnectionController);
+
+ public:
+ static const char kSupplementName[];
+ static RTCPeerConnectionController& From(Document&);
+
+ void MaybeReportComplexSdp(ComplexSdpCategory);
+
+ void Trace(Visitor*) override;
+
+ private:
+ explicit RTCPeerConnectionController(Document&);
+
+ bool has_reported_ukm_ = false;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_CONTROLLER_H_
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.cc
index 97ee5a333f0..747643b78c1 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.cc
@@ -32,23 +32,23 @@ namespace blink {
RTCPeerConnectionIceEvent* RTCPeerConnectionIceEvent::Create(
RTCIceCandidate* candidate) {
- return new RTCPeerConnectionIceEvent(candidate);
+ return MakeGarbageCollected<RTCPeerConnectionIceEvent>(candidate);
}
RTCPeerConnectionIceEvent* RTCPeerConnectionIceEvent::Create(
const AtomicString& type,
- const RTCPeerConnectionIceEventInit& initializer) {
- return new RTCPeerConnectionIceEvent(type, initializer);
+ const RTCPeerConnectionIceEventInit* initializer) {
+ return MakeGarbageCollected<RTCPeerConnectionIceEvent>(type, initializer);
}
RTCPeerConnectionIceEvent::RTCPeerConnectionIceEvent(RTCIceCandidate* candidate)
- : Event(EventTypeNames::icecandidate, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kIcecandidate, Bubbles::kNo, Cancelable::kNo),
candidate_(candidate) {}
RTCPeerConnectionIceEvent::RTCPeerConnectionIceEvent(
const AtomicString& type,
- const RTCPeerConnectionIceEventInit& initializer)
- : Event(type, initializer), candidate_(initializer.candidate()) {}
+ const RTCPeerConnectionIceEventInit* initializer)
+ : Event(type, initializer), candidate_(initializer->candidate()) {}
RTCPeerConnectionIceEvent::~RTCPeerConnectionIceEvent() = default;
@@ -57,7 +57,7 @@ RTCIceCandidate* RTCPeerConnectionIceEvent::candidate() const {
}
const AtomicString& RTCPeerConnectionIceEvent::InterfaceName() const {
- return EventNames::RTCPeerConnectionIceEvent;
+ return event_interface_names::kRTCPeerConnectionIceEvent;
}
void RTCPeerConnectionIceEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h
index bdedd7d9cc0..fd335e0ad36 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h
@@ -36,13 +36,16 @@ class MODULES_EXPORT RTCPeerConnectionIceEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ RTCPeerConnectionIceEvent(RTCIceCandidate*);
+ RTCPeerConnectionIceEvent(const AtomicString& type,
+ const RTCPeerConnectionIceEventInit*);
~RTCPeerConnectionIceEvent() override;
static RTCPeerConnectionIceEvent* Create(RTCIceCandidate*);
static RTCPeerConnectionIceEvent* Create(
const AtomicString& type,
- const RTCPeerConnectionIceEventInit&);
+ const RTCPeerConnectionIceEventInit*);
RTCIceCandidate* candidate() const;
@@ -51,11 +54,6 @@ class MODULES_EXPORT RTCPeerConnectionIceEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- RTCPeerConnectionIceEvent(RTCIceCandidate*);
-
- RTCPeerConnectionIceEvent(const AtomicString& type,
- const RTCPeerConnectionIceEventInit&);
-
Member<RTCIceCandidate> candidate_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc
index a20d8fa8d5c..0e433dd021e 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_test.cc
@@ -8,21 +8,32 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h"
#include "third_party/blink/public/platform/web_rtc_rtp_receiver.h"
#include "third_party/blink/public/platform/web_rtc_rtp_sender.h"
#include "third_party/blink/public/platform/web_rtc_session_description.h"
+#include "third_party/blink/public/platform/web_rtc_session_description_request.h"
+#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_heap.h"
#include "third_party/blink/renderer/bindings/core/v8/dictionary.h"
+#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_void_function.h"
+#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_peer_connection_error_callback.h"
+#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_session_description_callback.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream_track.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_answer_options.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_configuration.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_server.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_offer_options.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_init.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h"
+#include "third_party/webrtc/api/rtcerror.h"
+#include "v8/include/v8.h"
namespace blink {
@@ -359,17 +370,19 @@ static const char* kOfferSdpPlanBMultipleAudioTracks =
"a=ssrc:4092260337 mslabel:46f8615e-7599-49f3-9a45-3cf0faf58614\r\n"
"a=ssrc:4092260337 label:6b5f436e-f85d-40a1-83e4-acec63ca4b82\r\n";
-class RTCPeerConnectionTest : public testing::Test {
+template <typename PlatformSupportType>
+class RTCPeerConnectionTestWithPlatformTestingPlatformType
+ : public testing::Test {
public:
RTCPeerConnection* CreatePC(V8TestingScope& scope,
const String& sdpSemantics = String()) {
- RTCConfiguration config;
- config.setSdpSemantics(sdpSemantics);
- RTCIceServer ice_server;
- ice_server.setURL("stun:fake.stun.url");
- HeapVector<RTCIceServer> ice_servers;
+ RTCConfiguration* config = RTCConfiguration::Create();
+ config->setSdpSemantics(sdpSemantics);
+ RTCIceServer* ice_server = RTCIceServer::Create();
+ ice_server->setURL("stun:fake.stun.url");
+ HeapVector<Member<RTCIceServer>> ice_servers;
ice_servers.push_back(ice_server);
- config.setIceServers(ice_servers);
+ config->setIceServers(ice_servers);
return RTCPeerConnection::Create(scope.GetExecutionContext(), config,
Dictionary(), scope.GetExceptionState());
}
@@ -405,8 +418,14 @@ class RTCPeerConnectionTest : public testing::Test {
EXPECT_EQ("", GetExceptionMessage(scope));
}
- private:
- ScopedTestingPlatformSupport<TestingPlatformSupportWithWebRTC> platform;
+ protected:
+ ScopedTestingPlatformSupport<PlatformSupportType> platform_;
+};
+
+class RTCPeerConnectionTest
+ : public RTCPeerConnectionTestWithPlatformTestingPlatformType<
+ TestingPlatformSupportWithWebRTC> {
+ public:
};
TEST_F(RTCPeerConnectionTest, GetAudioTrack) {
@@ -572,78 +591,549 @@ TEST_F(RTCPeerConnectionTest, GetTrackRemoveStreamAndGCWithPersistentStream) {
EXPECT_FALSE(pc->GetTrack(track_component));
}
-TEST_F(RTCPeerConnectionTest, PlanBSdpWarningNotShownWhenPlanBSpecified) {
+TEST_F(RTCPeerConnectionTest, CheckForComplexSdpWithSdpSemanticsPlanB) {
V8TestingScope scope;
Persistent<RTCPeerConnection> pc = CreatePC(scope, "plan-b");
- RTCSessionDescriptionInit sdp;
- sdp.setType("offer");
- // It doesn't matter the SDP, never show a warning if sdpSemantics was
- // specified at construction.
- sdp.setSdp(kOfferSdpUnifiedPlanSingleAudioSingleVideo);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpUnifiedPlanMultipleAudioTracks);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpPlanBSingleAudioSingleVideo);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpPlanBMultipleAudioTracks);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
+ RTCSessionDescriptionInit* sdp = RTCSessionDescriptionInit::Create();
+ sdp->setType("offer");
+ sdp->setSdp(kOfferSdpUnifiedPlanMultipleAudioTracks);
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kUnifiedPlanExplicitSemantics);
+ sdp->setSdp(kOfferSdpPlanBMultipleAudioTracks);
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kPlanBExplicitSemantics);
+ sdp->setSdp("invalid sdp");
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kErrorExplicitSemantics);
+ // No Complex SDP is detected if only a single track per m= section is used.
+ sdp->setSdp(kOfferSdpUnifiedPlanSingleAudioSingleVideo);
+ ASSERT_FALSE(pc->CheckForComplexSdp(sdp).has_value());
+ sdp->setSdp(kOfferSdpPlanBSingleAudioSingleVideo);
+ ASSERT_FALSE(pc->CheckForComplexSdp(sdp).has_value());
}
-TEST_F(RTCPeerConnectionTest, PlanBSdpWarningNotShownWhenUnifiedPlanSpecified) {
+TEST_F(RTCPeerConnectionTest, CheckForComplexSdpWithSdpSemanticsUnifiedPlan) {
V8TestingScope scope;
Persistent<RTCPeerConnection> pc = CreatePC(scope, "unified-plan");
- RTCSessionDescriptionInit sdp;
- sdp.setType("offer");
- // It doesn't matter the SDP, never show a warning if sdpSemantics was
- // specified at construction.
- sdp.setSdp(kOfferSdpUnifiedPlanSingleAudioSingleVideo);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpUnifiedPlanMultipleAudioTracks);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpPlanBSingleAudioSingleVideo);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpPlanBMultipleAudioTracks);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
+ RTCSessionDescriptionInit* sdp = RTCSessionDescriptionInit::Create();
+ sdp->setType("offer");
+ sdp->setSdp(kOfferSdpUnifiedPlanMultipleAudioTracks);
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kUnifiedPlanExplicitSemantics);
+ sdp->setSdp(kOfferSdpPlanBMultipleAudioTracks);
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kPlanBExplicitSemantics);
+ sdp->setSdp("invalid sdp");
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kErrorExplicitSemantics);
+ // No Complex SDP is detected if only a single track per m= section is used.
+ sdp->setSdp(kOfferSdpUnifiedPlanSingleAudioSingleVideo);
+ ASSERT_FALSE(pc->CheckForComplexSdp(sdp).has_value());
+ sdp->setSdp(kOfferSdpPlanBSingleAudioSingleVideo);
+ ASSERT_FALSE(pc->CheckForComplexSdp(sdp).has_value());
}
-TEST_F(RTCPeerConnectionTest, PlanBSdpWarningNotShownWhenInvalidSdp) {
+TEST_F(RTCPeerConnectionTest, CheckForComplexSdpWithSdpSemanticsUnspecified) {
V8TestingScope scope;
Persistent<RTCPeerConnection> pc = CreatePC(scope);
- RTCSessionDescriptionInit sdp;
- sdp.setType("offer");
- sdp.setSdp("invalid sdp");
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
+ RTCSessionDescriptionInit* sdp = RTCSessionDescriptionInit::Create();
+ sdp->setType("offer");
+ sdp->setSdp(kOfferSdpPlanBMultipleAudioTracks);
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kPlanBImplicitSemantics);
+ sdp->setSdp(kOfferSdpUnifiedPlanMultipleAudioTracks);
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kUnifiedPlanImplicitSemantics);
+ sdp->setSdp("invalid sdp");
+ ASSERT_TRUE(pc->CheckForComplexSdp(sdp).has_value());
+ ASSERT_EQ(pc->CheckForComplexSdp(sdp),
+ ComplexSdpCategory::kErrorImplicitSemantics);
+ // No Complex SDP is detected if only a single track per m= section is used.
+ sdp->setSdp(kOfferSdpUnifiedPlanSingleAudioSingleVideo);
+ ASSERT_FALSE(pc->CheckForComplexSdp(sdp).has_value());
+ sdp->setSdp(kOfferSdpPlanBSingleAudioSingleVideo);
+ ASSERT_FALSE(pc->CheckForComplexSdp(sdp).has_value());
+}
+
+enum class AsyncOperationAction {
+ kLeavePending,
+ kResolve,
+ kReject,
+};
+
+template <typename RequestType>
+void CompleteRequest(RequestType request, bool resolve);
+
+template <>
+void CompleteRequest(WebRTCSessionDescriptionRequest request, bool resolve) {
+ if (resolve) {
+ WebRTCSessionDescription description =
+ WebRTCSessionDescription(WebString(), WebString());
+ request.RequestSucceeded(description);
+ } else {
+ request.RequestFailed(
+ webrtc::RTCError(webrtc::RTCErrorType::INVALID_MODIFICATION));
+ }
+}
+
+template <>
+void CompleteRequest(WebRTCVoidRequest request, bool resolve) {
+ if (resolve) {
+ request.RequestSucceeded();
+ } else {
+ request.RequestFailed(
+ webrtc::RTCError(webrtc::RTCErrorType::INVALID_MODIFICATION));
+ }
+}
+
+template <typename RequestType>
+void PostToCompleteRequest(AsyncOperationAction action,
+ const RequestType& request) {
+ switch (action) {
+ case AsyncOperationAction::kLeavePending:
+ return;
+ case AsyncOperationAction::kResolve:
+ scheduler::GetSequencedTaskRunnerForTesting()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&CompleteRequest<RequestType>, request, true));
+ return;
+ case AsyncOperationAction::kReject:
+ scheduler::GetSequencedTaskRunnerForTesting()->PostTask(
+ FROM_HERE,
+ base::BindOnce(&CompleteRequest<RequestType>, request, false));
+ return;
+ }
+}
+
+class FakeWebRTCPeerConnectionHandler : public MockWebRTCPeerConnectionHandler {
+ public:
+ void CreateOffer(const WebRTCSessionDescriptionRequest& request,
+ const WebMediaConstraints&) override {
+ PostToCompleteRequest<WebRTCSessionDescriptionRequest>(
+ async_operation_action_, request);
+ }
+
+ void CreateOffer(const WebRTCSessionDescriptionRequest& request,
+ const WebRTCOfferOptions&) override {
+ PostToCompleteRequest<WebRTCSessionDescriptionRequest>(
+ async_operation_action_, request);
+ }
+
+ void CreateAnswer(const WebRTCSessionDescriptionRequest& request,
+ const WebMediaConstraints&) override {
+ PostToCompleteRequest<WebRTCSessionDescriptionRequest>(
+ async_operation_action_, request);
+ }
+
+ void CreateAnswer(const WebRTCSessionDescriptionRequest& request,
+ const WebRTCAnswerOptions&) override {
+ PostToCompleteRequest<WebRTCSessionDescriptionRequest>(
+ async_operation_action_, request);
+ }
+
+ void SetLocalDescription(const WebRTCVoidRequest& request,
+ const WebRTCSessionDescription&) override {
+ PostToCompleteRequest<WebRTCVoidRequest>(async_operation_action_, request);
+ }
+
+ void SetRemoteDescription(const WebRTCVoidRequest& request,
+ const WebRTCSessionDescription&) override {
+ PostToCompleteRequest<WebRTCVoidRequest>(async_operation_action_, request);
+ }
+
+ void set_async_operation_action(AsyncOperationAction action) {
+ async_operation_action_ = action;
+ }
+
+ private:
+ // Decides what to do with future async operations' promises/callbacks.
+ AsyncOperationAction async_operation_action_ =
+ AsyncOperationAction::kLeavePending;
+};
+
+class TestingPlatformSupportWithFakeWebRTC : public TestingPlatformSupport {
+ public:
+ std::unique_ptr<WebRTCPeerConnectionHandler> CreateRTCPeerConnectionHandler(
+ WebRTCPeerConnectionHandlerClient*,
+ scoped_refptr<base::SingleThreadTaskRunner>) override {
+ handler_ = new FakeWebRTCPeerConnectionHandler();
+ return std::unique_ptr<WebRTCPeerConnectionHandler>(handler_);
+ }
+
+ FakeWebRTCPeerConnectionHandler* handler() const { return handler_; }
+
+ private:
+ FakeWebRTCPeerConnectionHandler* handler_;
+};
+
+// These tests verifies the code paths for notifying the peer connection's
+// CallSetupStateTracker of offerer and answerer events. Because fakes are used
+// the test can pass empty SDP around, deciding whether to resolve or reject
+// based on controlling the fake instead of validify of SDP, and
+// platform_->RunUntilIdle() is enough to ensure a pending operation has
+// completed. Without fakes we would have had to await promises and callbacks,
+// passing SDP returned by one operation to the next.
+class RTCPeerConnectionCallSetupStateTest
+ : public RTCPeerConnectionTestWithPlatformTestingPlatformType<
+ TestingPlatformSupportWithFakeWebRTC> {
+ public:
+ RTCPeerConnection* Initialize(V8TestingScope& scope) {
+ RTCPeerConnection* pc = CreatePC(scope);
+ tracker_ = &pc->call_setup_state_tracker();
+ SetNextOperationIsSuccessful(true);
+ return pc;
+ }
+
+ void SetNextOperationIsSuccessful(bool successful) {
+ platform_->handler()->set_async_operation_action(
+ successful ? AsyncOperationAction::kResolve
+ : AsyncOperationAction::kReject);
+ }
+
+ RTCSessionDescriptionInit* EmptyOffer() {
+ auto* sdp = RTCSessionDescriptionInit::Create();
+ sdp->setType("offer");
+ return sdp;
+ }
+
+ RTCSessionDescriptionInit* EmptyAnswer() {
+ auto* sdp = RTCSessionDescriptionInit::Create();
+ sdp->setType("answer");
+ return sdp;
+ }
+
+ template <typename CallbackType>
+ CallbackType* CreateEmptyCallback(V8TestingScope& scope) {
+ v8::Local<v8::Function> v8_function =
+ v8::Function::New(scope.GetContext(), EmptyHandler).ToLocalChecked();
+ return CallbackType::Create(v8_function);
+ }
+
+ Dictionary ToDictionary(V8TestingScope& scope,
+ const IDLDictionaryBase* value) {
+ return Dictionary(
+ scope.GetIsolate(),
+ ToV8(value, scope.GetContext()->Global(), scope.GetIsolate()),
+ scope.GetExceptionState());
+ }
+
+ private:
+ static void EmptyHandler(const v8::FunctionCallbackInfo<v8::Value>& args) {}
+
+ protected:
+ const CallSetupStateTracker* tracker_ = nullptr;
+};
+
+TEST_F(RTCPeerConnectionCallSetupStateTest, InitialState) {
+ V8TestingScope scope;
+ Initialize(scope);
+ EXPECT_EQ(OffererState::kNotStarted, tracker_->offerer_state());
+ EXPECT_EQ(AnswererState::kNotStarted, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kNotStarted, tracker_->GetCallSetupState());
}
-TEST_F(RTCPeerConnectionTest, PlanBSdpWarningNotShownForSingleTracks) {
+TEST_F(RTCPeerConnectionCallSetupStateTest, OffererSucceeded) {
V8TestingScope scope;
- Persistent<RTCPeerConnection> pc = CreatePC(scope);
- RTCSessionDescriptionInit sdp;
- sdp.setType("offer");
- // Neither Unified Plan or Plan B SDP should result in a warning if only a
- // single track per m= section is used.
- sdp.setSdp(kOfferSdpUnifiedPlanSingleAudioSingleVideo);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
- sdp.setSdp(kOfferSdpPlanBSingleAudioSingleVideo);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
+ RTCPeerConnection* pc = Initialize(scope);
+ // createOffer()
+ pc->createOffer(scope.GetScriptState(), RTCOfferOptions::Create());
+ EXPECT_EQ(OffererState::kCreateOfferPending, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kCreateOfferResolved, tracker_->offerer_state());
+ // setLocalDescription(offer)
+ pc->setLocalDescription(scope.GetScriptState(), EmptyOffer());
+ EXPECT_EQ(OffererState::kSetLocalOfferPending, tracker_->offerer_state());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kSetLocalOfferResolved, tracker_->offerer_state());
+ // setRemoteDescription(answer)
+ pc->setRemoteDescription(scope.GetScriptState(), EmptyAnswer());
+ EXPECT_EQ(OffererState::kSetRemoteAnswerPending, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kSetRemoteAnswerResolved, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_->GetCallSetupState());
}
-TEST_F(RTCPeerConnectionTest, PlanBSdpWarningShownForComplexPlanB) {
+TEST_F(RTCPeerConnectionCallSetupStateTest, OffererFailedAtCreateOffer) {
V8TestingScope scope;
- Persistent<RTCPeerConnection> pc = CreatePC(scope);
- RTCSessionDescriptionInit sdp;
- sdp.setType("offer");
- sdp.setSdp(kOfferSdpPlanBMultipleAudioTracks);
- ASSERT_TRUE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
+ RTCPeerConnection* pc = Initialize(scope);
+ // createOffer()
+ SetNextOperationIsSuccessful(false);
+ pc->createOffer(scope.GetScriptState(), RTCOfferOptions::Create());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kCreateOfferRejected, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_->GetCallSetupState());
}
-TEST_F(RTCPeerConnectionTest, PlanBSdpWarningNotShownForComplexUnifiedPlan) {
+TEST_F(RTCPeerConnectionCallSetupStateTest,
+ OffererFailedAtSetLocalDescription) {
V8TestingScope scope;
- Persistent<RTCPeerConnection> pc = CreatePC(scope);
- RTCSessionDescriptionInit sdp;
- sdp.setType("offer");
- sdp.setSdp(kOfferSdpUnifiedPlanMultipleAudioTracks);
- ASSERT_FALSE(pc->ShouldShowComplexPlanBSdpWarning(sdp));
+ RTCPeerConnection* pc = Initialize(scope);
+ // createOffer()
+ pc->createOffer(scope.GetScriptState(), RTCOfferOptions::Create());
+ platform_->RunUntilIdle();
+ // setLocalDescription(offer)
+ SetNextOperationIsSuccessful(false);
+ pc->setLocalDescription(scope.GetScriptState(), EmptyOffer());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kSetLocalOfferRejected, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest,
+ OffererFailedAtSetRemoteDescription) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // createOffer()
+ pc->createOffer(scope.GetScriptState(), RTCOfferOptions::Create());
+ platform_->RunUntilIdle();
+ // setLocalDescription(offer)
+ pc->setLocalDescription(scope.GetScriptState(), EmptyOffer());
+ platform_->RunUntilIdle();
+ // setRemoteDescription(answer)
+ SetNextOperationIsSuccessful(false);
+ pc->setRemoteDescription(scope.GetScriptState(), EmptyAnswer());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kSetRemoteAnswerRejected, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest, OffererLegacyApiPath) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // Legacy createOffer() with callbacks
+ pc->createOffer(scope.GetScriptState(),
+ CreateEmptyCallback<V8RTCSessionDescriptionCallback>(scope),
+ CreateEmptyCallback<V8RTCPeerConnectionErrorCallback>(scope),
+ ToDictionary(scope, RTCOfferOptions::Create()),
+ scope.GetExceptionState());
+ EXPECT_EQ(OffererState::kCreateOfferPending, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kCreateOfferResolved, tracker_->offerer_state());
+ // Legacy setLocalDescription(offer) with callbacks
+ pc->setLocalDescription(
+ scope.GetScriptState(), EmptyOffer(),
+ CreateEmptyCallback<V8VoidFunction>(scope),
+ CreateEmptyCallback<V8RTCPeerConnectionErrorCallback>(scope));
+ EXPECT_EQ(OffererState::kSetLocalOfferPending, tracker_->offerer_state());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kSetLocalOfferResolved, tracker_->offerer_state());
+ // Legacy setRemoteDescription(answer) with callbacks
+ pc->setRemoteDescription(
+ scope.GetScriptState(), EmptyAnswer(),
+ CreateEmptyCallback<V8VoidFunction>(scope),
+ CreateEmptyCallback<V8RTCPeerConnectionErrorCallback>(scope));
+ EXPECT_EQ(OffererState::kSetRemoteAnswerPending, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(OffererState::kSetRemoteAnswerResolved, tracker_->offerer_state());
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest, AnswererSucceeded) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // setRemoteDescription(offer)
+ pc->setRemoteDescription(scope.GetScriptState(), EmptyOffer());
+ EXPECT_EQ(AnswererState::kSetRemoteOfferPending, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kSetRemoteOfferResolved, tracker_->answerer_state());
+ // createAnswer()
+ pc->createAnswer(scope.GetScriptState(), RTCAnswerOptions::Create());
+ EXPECT_EQ(AnswererState::kCreateAnswerPending, tracker_->answerer_state());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kCreateAnswerResolved, tracker_->answerer_state());
+ // setLocalDescription(answer)
+ pc->setLocalDescription(scope.GetScriptState(), EmptyAnswer());
+ EXPECT_EQ(AnswererState::kSetLocalAnswerPending, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kSetLocalAnswerResolved, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest,
+ AnswererFailedAtSetRemoteDescription) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // setRemoteDescription(offer)
+ SetNextOperationIsSuccessful(false);
+ pc->setRemoteDescription(scope.GetScriptState(), EmptyOffer());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kSetRemoteOfferRejected, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest, AnswererFailedAtCreateAnswer) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // setRemoteDescription(offer)
+ pc->setRemoteDescription(scope.GetScriptState(), EmptyOffer());
+ platform_->RunUntilIdle();
+ // createAnswer()
+ SetNextOperationIsSuccessful(false);
+ pc->createAnswer(scope.GetScriptState(), RTCAnswerOptions::Create());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kCreateAnswerRejected, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest,
+ AnswererFailedAtSetLocalDescription) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // setRemoteDescription(offer)
+ pc->setRemoteDescription(scope.GetScriptState(), EmptyOffer());
+ platform_->RunUntilIdle();
+ // createAnswer()
+ pc->createAnswer(scope.GetScriptState(), RTCAnswerOptions::Create());
+ platform_->RunUntilIdle();
+ // setLocalDescription(answer)
+ SetNextOperationIsSuccessful(false);
+ pc->setLocalDescription(scope.GetScriptState(), EmptyAnswer());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kSetLocalAnswerRejected, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kFailed, tracker_->GetCallSetupState());
+}
+
+TEST_F(RTCPeerConnectionCallSetupStateTest, AnswererLegacyApiPath) {
+ V8TestingScope scope;
+ RTCPeerConnection* pc = Initialize(scope);
+ // Legacy setRemoteDescription(offer) with callbacks
+ pc->setRemoteDescription(
+ scope.GetScriptState(), EmptyOffer(),
+ CreateEmptyCallback<V8VoidFunction>(scope),
+ CreateEmptyCallback<V8RTCPeerConnectionErrorCallback>(scope));
+ EXPECT_EQ(AnswererState::kSetRemoteOfferPending, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kSetRemoteOfferResolved, tracker_->answerer_state());
+ // Legacy createAnswer() with callbacks
+ pc->createAnswer(scope.GetScriptState(),
+ CreateEmptyCallback<V8RTCSessionDescriptionCallback>(scope),
+ CreateEmptyCallback<V8RTCPeerConnectionErrorCallback>(scope),
+ Dictionary() /* media_constraints */);
+ EXPECT_EQ(AnswererState::kCreateAnswerPending, tracker_->answerer_state());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kCreateAnswerResolved, tracker_->answerer_state());
+ // Legacy setLocalDescription(answer) with callbacks
+ pc->setLocalDescription(
+ scope.GetScriptState(), EmptyAnswer(),
+ CreateEmptyCallback<V8VoidFunction>(scope),
+ CreateEmptyCallback<V8RTCPeerConnectionErrorCallback>(scope));
+ EXPECT_EQ(AnswererState::kSetLocalAnswerPending, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kStarted, tracker_->GetCallSetupState());
+ platform_->RunUntilIdle();
+ EXPECT_EQ(AnswererState::kSetLocalAnswerResolved, tracker_->answerer_state());
+ EXPECT_EQ(CallSetupState::kSucceeded, tracker_->GetCallSetupState());
+}
+
+// Test that simple Plan B is considered safe regardless of configurations.
+TEST(DeduceSdpUsageCategory, SimplePlanBIsAlwaysSafe) {
+ // If the default is Plan B.
+ EXPECT_EQ(
+ SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBSingleAudioSingleVideo,
+ false, webrtc::SdpSemantics::kPlanB));
+ // If the default is Unified Plan.
+ EXPECT_EQ(
+ SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBSingleAudioSingleVideo,
+ false, webrtc::SdpSemantics::kUnifiedPlan));
+ // If sdpSemantics is explicitly set to Plan B.
+ EXPECT_EQ(
+ SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBSingleAudioSingleVideo,
+ true, webrtc::SdpSemantics::kPlanB));
+ // If sdpSemantics is explicitly set to Unified Plan.
+ EXPECT_EQ(
+ SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBSingleAudioSingleVideo,
+ true, webrtc::SdpSemantics::kUnifiedPlan));
+}
+
+// Test that simple Unified Plan is considered safe regardless of
+// configurations.
+TEST(DeduceSdpUsageCategory, SimpleUnifiedPlanIsAlwaysSafe) {
+ // If the default is Plan B.
+ EXPECT_EQ(SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer",
+ kOfferSdpUnifiedPlanSingleAudioSingleVideo,
+ false, webrtc::SdpSemantics::kPlanB));
+ // If the default is Unified Plan.
+ EXPECT_EQ(SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer",
+ kOfferSdpUnifiedPlanSingleAudioSingleVideo,
+ false, webrtc::SdpSemantics::kUnifiedPlan));
+ // If sdpSemantics is explicitly set to Plan B.
+ EXPECT_EQ(SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer",
+ kOfferSdpUnifiedPlanSingleAudioSingleVideo,
+ true, webrtc::SdpSemantics::kPlanB));
+ // If sdpSemantics is explicitly set to Unified Plan.
+ EXPECT_EQ(SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer",
+ kOfferSdpUnifiedPlanSingleAudioSingleVideo,
+ true, webrtc::SdpSemantics::kUnifiedPlan));
+}
+
+// Test that complex SDP is always unsafe when relying on default sdpSemantics.
+TEST(DeduceSdpUsageCategory, ComplexSdpIsAlwaysUnsafeWithDefaultSdpSemantics) {
+ // If the default is Plan B and the SDP is complex Plan B.
+ EXPECT_EQ(SdpUsageCategory::kUnsafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBMultipleAudioTracks,
+ false, webrtc::SdpSemantics::kPlanB));
+ // If the default is Plan B and the SDP is complex Unified Plan.
+ EXPECT_EQ(
+ SdpUsageCategory::kUnsafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpUnifiedPlanMultipleAudioTracks,
+ false, webrtc::SdpSemantics::kPlanB));
+ // If the default is Unified Plan and the SDP is complex Plan B.
+ EXPECT_EQ(SdpUsageCategory::kUnsafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBMultipleAudioTracks,
+ false, webrtc::SdpSemantics::kUnifiedPlan));
+ // If the default is Unified Plan and the SDP is complex UNified Plan.
+ EXPECT_EQ(
+ SdpUsageCategory::kUnsafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpUnifiedPlanMultipleAudioTracks,
+ false, webrtc::SdpSemantics::kUnifiedPlan));
+}
+
+// Test that when sdpSemantics is explicitly set, complex SDP is safe if it is
+// of the same format and unsafe if the format is different.
+TEST(DeduceSdpUsageCategory, ComplexSdpIsSafeIfMatchingExplicitSdpSemantics) {
+ // If sdpSemantics is explicitly set to Plan B and the SDP is complex Plan B.
+ EXPECT_EQ(SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBMultipleAudioTracks,
+ true, webrtc::SdpSemantics::kPlanB));
+ // If sdpSemantics is explicitly set to Unified Plan and the SDP is complex
+ // Unified Plan.
+ EXPECT_EQ(
+ SdpUsageCategory::kSafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpUnifiedPlanMultipleAudioTracks,
+ true, webrtc::SdpSemantics::kUnifiedPlan));
+ // If the sdpSemantics is explicitly set to Plan B but the SDP is complex
+ // Unified Plan.
+ EXPECT_EQ(
+ SdpUsageCategory::kUnsafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpUnifiedPlanMultipleAudioTracks,
+ true, webrtc::SdpSemantics::kPlanB));
+ // If the sdpSemantics is explicitly set to Unified Plan but the SDP is
+ // complex Plan B.
+ EXPECT_EQ(SdpUsageCategory::kUnsafe,
+ DeduceSdpUsageCategory("offer", kOfferSdpPlanBMultipleAudioTracks,
+ true, webrtc::SdpSemantics::kUnifiedPlan));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.cc
index 66f32031b94..5b654f4bf3b 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.cc
@@ -3,18 +3,55 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h"
+#include "base/containers/span.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
-#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
namespace blink {
+const uint32_t RTCQuicStream::kWriteBufferSize = 4 * 1024;
+const uint32_t RTCQuicStream::kReadBufferSize = 4 * 1024;
+
+class RTCQuicStream::PendingReadBufferedAmountPromise
+ : public GarbageCollected<PendingReadBufferedAmountPromise> {
+ public:
+ PendingReadBufferedAmountPromise(ScriptPromiseResolver* promise_resolver,
+ uint32_t readable_amount)
+ : promise_resolver_(promise_resolver),
+ readable_amount_(readable_amount) {}
+
+ ScriptPromiseResolver* promise_resolver() const { return promise_resolver_; }
+ uint32_t readable_amount() const { return readable_amount_; }
+
+ void Trace(Visitor* visitor) { visitor->Trace(promise_resolver_); }
+
+ private:
+ Member<ScriptPromiseResolver> promise_resolver_;
+ uint32_t readable_amount_;
+};
+
+class RTCQuicStream::PendingWriteBufferedAmountPromise
+ : public GarbageCollected<PendingWriteBufferedAmountPromise> {
+ public:
+ PendingWriteBufferedAmountPromise(ScriptPromiseResolver* promise_resolver,
+ uint32_t threshold)
+ : promise_resolver_(promise_resolver), threshold_(threshold) {}
+
+ ScriptPromiseResolver* promise_resolver() const { return promise_resolver_; }
+ uint32_t threshold() const { return threshold_; }
+
+ void Trace(Visitor* visitor) { visitor->Trace(promise_resolver_); }
+
+ private:
+ Member<ScriptPromiseResolver> promise_resolver_;
+ uint32_t threshold_;
+};
+
RTCQuicStream::RTCQuicStream(ExecutionContext* context,
RTCQuicTransport* transport,
QuicStreamProxy* stream_proxy)
- : EventTargetWithInlineData(),
- ContextClient(context),
- transport_(transport),
- proxy_(stream_proxy) {
+ : ContextClient(context), transport_(transport), proxy_(stream_proxy) {
DCHECK(transport_);
DCHECK(proxy_);
}
@@ -42,25 +79,88 @@ String RTCQuicStream::state() const {
}
uint32_t RTCQuicStream::readBufferedAmount() const {
- return read_buffered_amount_;
+ return receive_buffer_.size();
+}
+
+uint32_t RTCQuicStream::maxReadBufferedAmount() const {
+ return kReadBufferSize;
}
uint32_t RTCQuicStream::writeBufferedAmount() const {
return write_buffered_amount_;
}
+uint32_t RTCQuicStream::maxWriteBufferedAmount() const {
+ return kWriteBufferSize;
+}
+
+RTCQuicStreamReadResult* RTCQuicStream::readInto(
+ NotShared<DOMUint8Array> data,
+ ExceptionState& exception_state) {
+ if (RaiseIfNotReadable(exception_state)) {
+ return 0;
+ }
+ uint32_t read_amount = static_cast<uint32_t>(receive_buffer_.ReadInto(
+ base::make_span(data.View()->Data(), data.View()->length())));
+ if (!received_fin_ && read_amount > 0) {
+ proxy_->MarkReceivedDataConsumed(read_amount);
+ }
+ if (receive_buffer_.empty() && received_fin_) {
+ read_fin_ = true;
+ if (wrote_fin_) {
+ DCHECK_EQ(state_, RTCQuicStreamState::kClosing);
+ Close(CloseReason::kReadWriteFinished);
+ } else {
+ DCHECK_EQ(state_, RTCQuicStreamState::kOpen);
+ state_ = RTCQuicStreamState::kClosing;
+ }
+ }
+ auto* result = RTCQuicStreamReadResult::Create();
+ result->setAmount(read_amount);
+ result->setFinished(read_fin_);
+ return result;
+}
+
+void RTCQuicStream::write(NotShared<DOMUint8Array> data,
+ ExceptionState& exception_state) {
+ if (RaiseIfNotWritable(exception_state)) {
+ return;
+ }
+ if (data.View()->length() == 0) {
+ return;
+ }
+ uint32_t remaining_write_buffer_size =
+ kWriteBufferSize - writeBufferedAmount();
+ if (data.View()->length() > remaining_write_buffer_size) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kOperationError,
+ "The write data size of " + String::Number(data.View()->length()) +
+ " bytes would exceed the remaining write buffer size of " +
+ String::Number(remaining_write_buffer_size) + " bytes.");
+ return;
+ }
+ Vector<uint8_t> data_vector(data.View()->length());
+ memcpy(data_vector.data(), data.View()->Data(), data.View()->length());
+ proxy_->WriteData(std::move(data_vector), /*fin=*/false);
+ write_buffered_amount_ += data.View()->length();
+}
+
void RTCQuicStream::finish() {
- if (!writeable_) {
+ if (IsClosed()) {
return;
}
- proxy_->Finish();
- writeable_ = false;
- if (readable_) {
+ if (wrote_fin_) {
+ return;
+ }
+ proxy_->WriteData({}, /*fin=*/true);
+ wrote_fin_ = true;
+ if (!read_fin_) {
DCHECK_EQ(state_, RTCQuicStreamState::kOpen);
state_ = RTCQuicStreamState::kClosing;
+ RejectPendingWaitForWriteBufferedAmountBelowPromises();
} else {
DCHECK_EQ(state_, RTCQuicStreamState::kClosing);
- Close();
+ Close(CloseReason::kReadWriteFinished);
}
}
@@ -68,46 +168,224 @@ void RTCQuicStream::reset() {
if (IsClosed()) {
return;
}
- proxy_->Reset();
- writeable_ = false;
- readable_ = false;
- Close();
+ Close(CloseReason::kLocalReset);
}
-void RTCQuicStream::Stop() {
- readable_ = false;
- writeable_ = false;
- state_ = RTCQuicStreamState::kClosed;
- proxy_ = nullptr;
+ScriptPromise RTCQuicStream::waitForReadable(ScriptState* script_state,
+ uint32_t amount,
+ ExceptionState& exception_state) {
+ if (RaiseIfNotReadable(exception_state)) {
+ return ScriptPromise();
+ }
+ if (amount > kReadBufferSize) {
+ exception_state.ThrowTypeError(
+ "The amount " + String::Number(amount) +
+ " is greater than the maximum read buffer size of " +
+ String::Number(kReadBufferSize) + ".");
+ return ScriptPromise();
+ }
+ ScriptPromiseResolver* promise_resolver =
+ ScriptPromiseResolver::Create(script_state);
+ ScriptPromise promise = promise_resolver->Promise();
+ if (received_fin_ || receive_buffer_.size() >= amount) {
+ promise_resolver->Resolve();
+ } else {
+ pending_read_buffered_amount_promises_.push_back(
+ new PendingReadBufferedAmountPromise(promise_resolver, amount));
+ }
+ return promise;
+}
+
+ScriptPromise RTCQuicStream::waitForWriteBufferedAmountBelow(
+ ScriptState* script_state,
+ uint32_t threshold,
+ ExceptionState& exception_state) {
+ if (RaiseIfNotWritable(exception_state)) {
+ return ScriptPromise();
+ }
+ ScriptPromiseResolver* promise_resolver =
+ ScriptPromiseResolver::Create(script_state);
+ ScriptPromise promise = promise_resolver->Promise();
+ if (write_buffered_amount_ <= threshold) {
+ promise_resolver->Resolve();
+ } else {
+ pending_write_buffered_amount_promises_.push_back(
+ new PendingWriteBufferedAmountPromise(promise_resolver, threshold));
+ }
+ return promise;
+}
+
+bool RTCQuicStream::RaiseIfNotReadable(ExceptionState& exception_state) {
+ if (read_fin_) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The stream is not readable: The end of the stream has been read.");
+ return true;
+ }
+ if (IsClosed()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The stream is not readable: The stream is closed.");
+ return true;
+ }
+ return false;
+}
+
+bool RTCQuicStream::RaiseIfNotWritable(ExceptionState& exception_state) {
+ if (wrote_fin_) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The stream is not writable: finish() has been called.");
+ return true;
+ }
+ if (IsClosed()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The stream is not writable: The stream is closed.");
+ return true;
+ }
+ return false;
}
-void RTCQuicStream::Close() {
- Stop();
- transport_->RemoveStream(this);
+void RTCQuicStream::RejectPendingWaitForReadablePromises() {
+ // TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
+ // order is under specified.
+ for (PendingReadBufferedAmountPromise* pending_promise :
+ pending_read_buffered_amount_promises_) {
+ ScriptState::Scope scope(
+ pending_promise->promise_resolver()->GetScriptState());
+ ExceptionState exception_state(
+ pending_promise->promise_resolver()->GetScriptState()->GetIsolate(),
+ ExceptionState::kExecutionContext, "RTCQuicStream", "waitForReadable");
+ exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
+ "The RTCQuicStream is not readable.");
+ pending_promise->promise_resolver()->Reject(exception_state);
+ }
+ pending_read_buffered_amount_promises_.clear();
+}
+
+void RTCQuicStream::RejectPendingWaitForWriteBufferedAmountBelowPromises() {
+ // TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
+ // order is under specified.
+ for (PendingWriteBufferedAmountPromise* pending_promise :
+ pending_write_buffered_amount_promises_) {
+ ScriptState::Scope scope(
+ pending_promise->promise_resolver()->GetScriptState());
+ ExceptionState exception_state(
+ pending_promise->promise_resolver()->GetScriptState()->GetIsolate(),
+ ExceptionState::kExecutionContext, "RTCQuicStream",
+ "waitForWriteBufferedAmountBelow");
+ exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
+ "The stream is no longer writable.");
+ pending_promise->promise_resolver()->Reject(exception_state);
+ }
+ pending_write_buffered_amount_promises_.clear();
}
void RTCQuicStream::OnRemoteReset() {
- DCHECK_NE(state_, RTCQuicStreamState::kClosed);
- Close();
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ Close(CloseReason::kRemoteReset);
}
-void RTCQuicStream::OnRemoteFinish() {
+void RTCQuicStream::OnDataReceived(Vector<uint8_t> data, bool fin) {
+ DCHECK(!received_fin_);
+ DCHECK_LE(data.size(), kReadBufferSize - receive_buffer_.size());
+ received_fin_ = fin;
+ receive_buffer_.Append(std::move(data));
+ // TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
+ // order is under specified.
+ for (auto* it = pending_read_buffered_amount_promises_.begin();
+ it != pending_read_buffered_amount_promises_.end();
+ /* incremented manually */) {
+ PendingReadBufferedAmountPromise* pending_promise = *it;
+ if (received_fin_ ||
+ receive_buffer_.size() >= pending_promise->readable_amount()) {
+ pending_promise->promise_resolver()->Resolve();
+ it = pending_read_buffered_amount_promises_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+}
+
+void RTCQuicStream::OnWriteDataConsumed(uint32_t amount) {
+ DCHECK_GE(write_buffered_amount_, amount);
+ write_buffered_amount_ -= amount;
+ // TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
+ // order is under specified.
+ for (auto* it = pending_write_buffered_amount_promises_.begin();
+ it != pending_write_buffered_amount_promises_.end();
+ /* incremented manually */) {
+ PendingWriteBufferedAmountPromise* pending_promise = *it;
+ if (write_buffered_amount_ <= pending_promise->threshold()) {
+ pending_promise->promise_resolver()->Resolve();
+ it = pending_write_buffered_amount_promises_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+}
+
+void RTCQuicStream::OnQuicTransportClosed(
+ RTCQuicTransport::CloseReason reason) {
+ switch (reason) {
+ case RTCQuicTransport::CloseReason::kContextDestroyed:
+ Close(CloseReason::kContextDestroyed);
+ break;
+ default:
+ Close(CloseReason::kQuicTransportClosed);
+ break;
+ }
+}
+
+void RTCQuicStream::Close(CloseReason reason) {
DCHECK_NE(state_, RTCQuicStreamState::kClosed);
- DCHECK(readable_);
- readable_ = false;
- if (writeable_) {
- DCHECK_EQ(state_, RTCQuicStreamState::kOpen);
- state_ = RTCQuicStreamState::kClosing;
- } else {
- DCHECK_EQ(state_, RTCQuicStreamState::kClosing);
- Close();
+
+ // Tear down the QuicStreamProxy.
+ // If the Close is caused by a remote event or regular use of WriteData, the
+ // QuicStreamProxy will have already been deleted.
+ // If the Close is caused by the transport then the transport is responsible
+ // for deleting the QuicStreamProxy.
+ if (reason == CloseReason::kLocalReset) {
+ // This deletes the QuicStreamProxy.
+ proxy_->Reset();
+ }
+ proxy_ = nullptr;
+
+ // Remove this stream from the RTCQuicTransport unless closing from a
+ // transport-level event.
+ switch (reason) {
+ case CloseReason::kReadWriteFinished:
+ case CloseReason::kLocalReset:
+ case CloseReason::kRemoteReset:
+ transport_->RemoveStream(this);
+ break;
+ case CloseReason::kQuicTransportClosed:
+ case CloseReason::kContextDestroyed:
+ // The RTCQuicTransport will handle clearing its list of streams.
+ break;
+ }
+
+ // Clear observable state.
+ receive_buffer_.Clear();
+ write_buffered_amount_ = 0;
+
+ // It's illegal to resolve or reject promises when the ExecutionContext is
+ // being destroyed.
+ if (reason != CloseReason::kContextDestroyed) {
+ RejectPendingWaitForReadablePromises();
+ RejectPendingWaitForWriteBufferedAmountBelowPromises();
+ }
+
+ // Change the state. Fire the statechange event only if the close is caused by
+ // a remote stream event.
+ state_ = RTCQuicStreamState::kClosed;
+ if (reason == CloseReason::kRemoteReset) {
+ DispatchEvent(*Event::Create(event_type_names::kStatechange));
}
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
}
const AtomicString& RTCQuicStream::InterfaceName() const {
- return EventTargetNames::RTCQuicStream;
+ return event_target_names::kRTCQuicStream;
}
ExecutionContext* RTCQuicStream::GetExecutionContext() const {
@@ -116,6 +394,8 @@ ExecutionContext* RTCQuicStream::GetExecutionContext() const {
void RTCQuicStream::Trace(blink::Visitor* visitor) {
visitor->Trace(transport_);
+ visitor->Trace(pending_read_buffered_amount_promises_);
+ visitor->Trace(pending_write_buffered_amount_promises_);
EventTargetWithInlineData::Trace(visitor);
ContextClient::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h
index b2952b2cffb..98a4e2941f0 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h
@@ -6,63 +6,133 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_QUIC_STREAM_H_
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h"
+#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/quic_stream_proxy.h"
+#include "third_party/blink/renderer/modules/peerconnection/byte_buffer_queue.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_read_result.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h"
namespace blink {
-class RTCQuicTransport;
+class ScriptPromise;
enum class RTCQuicStreamState { kNew, kOpening, kOpen, kClosing, kClosed };
+// The RTCQuicStream does not need to be ActiveScriptWrappable since the
+// RTCQuicTransport that it is associated with holds a strong reference to it
+// as long as it is not closed.
class MODULES_EXPORT RTCQuicStream final : public EventTargetWithInlineData,
public ContextClient,
public QuicStreamProxy::Delegate {
DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(RTCQuicStream);
public:
+ // TODO(steveanton): These maybe should be adjustable.
+ static const uint32_t kWriteBufferSize;
+ static const uint32_t kReadBufferSize;
+
+ enum class CloseReason {
+ // Both read and write sides have been finished.
+ kReadWriteFinished,
+ // reset() was called.
+ kLocalReset,
+ // The remote stream sent a reset().
+ kRemoteReset,
+ // The RTCQuicTransport has closed.
+ kQuicTransportClosed,
+ // The ExecutionContext is being destroyed.
+ kContextDestroyed,
+ };
+
RTCQuicStream(ExecutionContext* context,
RTCQuicTransport* transport,
QuicStreamProxy* stream_proxy);
~RTCQuicStream() override;
- // Called from the RTCQuicTransport when it is being stopped.
- void Stop();
- bool IsClosed() const { return state_ == RTCQuicStreamState::kClosed; }
+ // Called by the RTCQuicTransport when it is being closed.
+ void OnQuicTransportClosed(RTCQuicTransport::CloseReason reason);
// rtc_quic_stream.idl
RTCQuicTransport* transport() const;
String state() const;
uint32_t readBufferedAmount() const;
+ uint32_t maxReadBufferedAmount() const;
uint32_t writeBufferedAmount() const;
+ uint32_t maxWriteBufferedAmount() const;
+ RTCQuicStreamReadResult* readInto(NotShared<DOMUint8Array> data,
+ ExceptionState& exception_state);
+ void write(NotShared<DOMUint8Array> data, ExceptionState& exception_state);
void finish();
void reset();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange);
+ ScriptPromise waitForWriteBufferedAmountBelow(
+ ScriptState* script_state,
+ uint32_t threshold,
+ ExceptionState& exception_state);
+ ScriptPromise waitForReadable(ScriptState* script_state,
+ uint32_t amount,
+ ExceptionState& exception_state);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
// EventTarget overrides.
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
// For garbage collection.
- void Trace(blink::Visitor* visitor) override;
+ void Trace(Visitor* visitor) override;
private:
- // Closes the stream. This will change the state to kClosed and deregister it
- // from the RTCQuicTransport. The QuicStreamProxy can no longer be used after
- // this point.
- void Close();
+ class PendingReadBufferedAmountPromise;
+ class PendingWriteBufferedAmountPromise;
// QuicStreamProxy::Delegate overrides.
void OnRemoteReset() override;
- void OnRemoteFinish() override;
+ void OnDataReceived(Vector<uint8_t> data, bool fin) override;
+ void OnWriteDataConsumed(uint32_t amount) override;
+
+ bool RaiseIfNotReadable(ExceptionState&);
+ bool RaiseIfNotWritable(ExceptionState&);
+
+ // Permenantly closes the RTCQuicStream with the given reason.
+ // The RTCQuicStream must not already be closed.
+ // This will transition the state to closed.
+ void Close(CloseReason reason);
+
+ bool IsClosed() const { return state_ == RTCQuicStreamState::kClosed; }
+
+ void RejectPendingWaitForReadablePromises();
+ void RejectPendingWaitForWriteBufferedAmountBelowPromises();
Member<RTCQuicTransport> transport_;
RTCQuicStreamState state_ = RTCQuicStreamState::kOpen;
- bool readable_ = true;
- bool writeable_ = true;
- uint32_t read_buffered_amount_ = 0;
+
+ // Data that has been received but not read.
+ // OnDataReceived() appends to the read buffer.
+ // readInto() will read out from the front of the buffer.
+ ByteBufferQueue receive_buffer_;
+ // True if the fin has been received from the network.
+ bool received_fin_ = false;
+ // True if the fin has been read out via readInto(). This signifies that the
+ // RTCQuicStream is closed for reading.
+ bool read_fin_ = false;
+ // Pending waitForReadable promises.
+ HeapVector<Member<PendingReadBufferedAmountPromise>>
+ pending_read_buffered_amount_promises_;
+
+ // Amount of bytes written but may not yet have been sent by the underlying
+ // P2PQuicStream.
+ // write() increases this number.
+ // OnDataSent() decreases this number.
uint32_t write_buffered_amount_ = 0;
+ // True if finish() has been called.
+ bool wrote_fin_ = false;
+ // Pending waitForWriteBufferedAmountBelow Promises.
+ HeapVector<Member<PendingWriteBufferedAmountPromise>>
+ pending_write_buffered_amount_promises_;
+
QuicStreamProxy* proxy_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl
index 945d6b4af5d..6bb9b72f553 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.idl
@@ -19,9 +19,17 @@ enum RTCQuicStreamState {
readonly attribute RTCQuicTransport transport;
readonly attribute RTCQuicStreamState state;
readonly attribute unsigned long readBufferedAmount;
+ readonly attribute unsigned long maxReadBufferedAmount;
readonly attribute unsigned long writeBufferedAmount;
+ readonly attribute unsigned long maxWriteBufferedAmount;
+ [RaisesException] RTCQuicStreamReadResult readInto(Uint8Array data);
+ [RaisesException] void write(Uint8Array data);
void finish();
void reset();
+ [CallWith=ScriptState, RaisesException]
+ Promise<void> waitForWriteBufferedAmountBelow(unsigned long amount);
+ [CallWith=ScriptState, RaisesException]
+ Promise<void> waitForReadable(unsigned long amount);
attribute EventHandler onstatechange;
// TODO(crbug.com/868068): Implement remaining methods, attributes, and events.
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.cc
index af4228d12f4..b7a102ba6ac 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.cc
@@ -14,18 +14,18 @@ RTCQuicStreamEvent* RTCQuicStreamEvent::Create(RTCQuicStream* stream) {
RTCQuicStreamEvent* RTCQuicStreamEvent::Create(
const AtomicString& type,
- const RTCQuicStreamEventInit& initializer) {
+ const RTCQuicStreamEventInit* initializer) {
return new RTCQuicStreamEvent(type, initializer);
}
RTCQuicStreamEvent::RTCQuicStreamEvent(RTCQuicStream* stream)
- : Event(EventTypeNames::quicstream, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kQuicstream, Bubbles::kNo, Cancelable::kNo),
stream_(stream) {}
RTCQuicStreamEvent::RTCQuicStreamEvent(
const AtomicString& type,
- const RTCQuicStreamEventInit& initializer)
- : Event(type, initializer), stream_(initializer.stream()) {}
+ const RTCQuicStreamEventInit* initializer)
+ : Event(type, initializer), stream_(initializer->stream()) {}
RTCQuicStreamEvent::~RTCQuicStreamEvent() = default;
@@ -34,7 +34,7 @@ RTCQuicStream* RTCQuicStreamEvent::stream() const {
}
const AtomicString& RTCQuicStreamEvent::InterfaceName() const {
- return EventNames::RTCQuicStreamEvent;
+ return event_interface_names::kRTCQuicStreamEvent;
}
void RTCQuicStreamEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.h
index 6e60d9a40ae..227b68cfc3f 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.h
@@ -12,13 +12,13 @@ namespace blink {
class RTCQuicStream;
class RTCQuicStreamEventInit;
-class RTCQuicStreamEvent final : public Event {
+class MODULES_EXPORT RTCQuicStreamEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
static RTCQuicStreamEvent* Create(RTCQuicStream* stream);
static RTCQuicStreamEvent* Create(const AtomicString& type,
- const RTCQuicStreamEventInit& init);
+ const RTCQuicStreamEventInit* init);
~RTCQuicStreamEvent() override;
@@ -34,7 +34,7 @@ class RTCQuicStreamEvent final : public Event {
private:
RTCQuicStreamEvent(RTCQuicStream* stream);
RTCQuicStreamEvent(const AtomicString& type,
- const RTCQuicStreamEventInit& init);
+ const RTCQuicStreamEventInit* init);
Member<RTCQuicStream> stream_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_read_result.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_read_result.idl
new file mode 100644
index 00000000000..b2d58c25d11
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_read_result.idl
@@ -0,0 +1,9 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://w3c.github.io/webrtc-quic/#dom-rtcquicstreamreadresult
+dictionary RTCQuicStreamReadResult {
+ unsigned long amount;
+ boolean finished;
+};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_test.cc
new file mode 100644
index 00000000000..5392c2b8882
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_test.cc
@@ -0,0 +1,1172 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This file tests the RTCQuicStream Blink bindings, QuicStreamProxy and
+// QuicStreamHost by mocking out the underlying P2PQuicTransport.
+// Everything is run on a single thread but with separate TestSimpleTaskRunners
+// for the main thread / worker thread.
+
+#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
+#include "third_party/blink/renderer/modules/peerconnection/adapters/test/mock_p2p_quic_stream.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_stream_event.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.h"
+
+namespace blink {
+namespace {
+
+using testing::_;
+using testing::ElementsAre;
+using testing::InvokeWithoutArgs;
+using testing::Return;
+using testing::SaveArg;
+
+NotShared<DOMUint8Array> CreateUint8Array(const Vector<uint8_t>& data) {
+ return NotShared<DOMUint8Array>(
+ DOMUint8Array::Create(data.data(), data.size()));
+}
+
+NotShared<DOMUint8Array> CreateUint8ArrayOfLength(uint32_t length) {
+ return NotShared<DOMUint8Array>(DOMUint8Array::Create(length));
+}
+
+} // namespace
+
+class RTCQuicStreamTest : public RTCQuicTransportTest {
+ public:
+ RTCQuicStream* CreateQuicStream(V8TestingScope& scope,
+ MockP2PQuicStream* mock_stream) {
+ auto p2p_quic_transport = std::make_unique<MockP2PQuicTransport>();
+ EXPECT_CALL(*p2p_quic_transport, CreateStream())
+ .WillOnce(Return(mock_stream));
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateConnectedQuicTransport(scope, std::move(p2p_quic_transport));
+ return quic_transport->createStream(ASSERT_NO_EXCEPTION);
+ }
+};
+
+// Test that RTCQuicTransport.createStream causes CreateStream to be called on
+// the underlying transport and a P2PQuicStream::Delegate to be set on the
+// underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, RTCQuicTransportCreateStreamCallsUnderlying) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, SetDelegate(_))
+ .WillOnce(testing::Invoke(
+ [](P2PQuicStream::Delegate* delegate) { EXPECT_TRUE(delegate); }));
+
+ auto p2p_quic_transport = std::make_unique<MockP2PQuicTransport>();
+ EXPECT_CALL(*p2p_quic_transport, CreateStream())
+ .WillOnce(Return(p2p_quic_stream.get()));
+
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateConnectedQuicTransport(scope, std::move(p2p_quic_transport));
+ Persistent<RTCQuicStream> quic_stream =
+ quic_transport->createStream(ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+}
+
+// Test that calling OnStream on the P2PQuicTransport delegate causes a
+// quicstream event to fire with a new RTCQuicStream.
+TEST_F(RTCQuicStreamTest, NewRemoteStreamFiresEvent) {
+ V8TestingScope scope;
+
+ P2PQuicTransport::Delegate* transport_delegate = nullptr;
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateConnectedQuicTransport(scope, &transport_delegate);
+
+ Persistent<MockEventListener> quic_stream_listener =
+ CreateMockEventListener();
+ EXPECT_CALL(*quic_stream_listener, Invoke(_, _))
+ .WillOnce(testing::Invoke([](ExecutionContext*, Event* event) {
+ auto* stream_event = static_cast<RTCQuicStreamEvent*>(event);
+ EXPECT_NE(nullptr, stream_event->stream());
+ }));
+ quic_transport->addEventListener(event_type_names::kQuicstream,
+ quic_stream_listener);
+
+ ASSERT_TRUE(transport_delegate);
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, SetDelegate(_))
+ .WillOnce(testing::Invoke(
+ [](P2PQuicStream::Delegate* delegate) { EXPECT_TRUE(delegate); }));
+ transport_delegate->OnStream(p2p_quic_stream.get());
+
+ RunUntilIdle();
+}
+
+// Test that calling reset() calls Reset() on the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, ResetCallsUnderlying) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, Reset()).Times(1);
+
+ auto p2p_quic_transport = std::make_unique<MockP2PQuicTransport>();
+ EXPECT_CALL(*p2p_quic_transport, CreateStream())
+ .WillOnce(Return(p2p_quic_stream.get()));
+
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateConnectedQuicTransport(scope, std::move(p2p_quic_transport));
+ Persistent<RTCQuicStream> stream =
+ quic_transport->createStream(ASSERT_NO_EXCEPTION);
+
+ stream->reset();
+
+ RunUntilIdle();
+}
+
+// Test that calling OnRemoteReset() on the P2PQuicStream delegate fires a
+// statechange event to 'closed'.
+TEST_F(RTCQuicStreamTest, OnRemoteResetFiresStateChangeToClosed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, SetDelegate(_))
+ .WillOnce(SaveArg<0>(&stream_delegate));
+
+ auto p2p_quic_transport = std::make_unique<MockP2PQuicTransport>();
+ EXPECT_CALL(*p2p_quic_transport, CreateStream())
+ .WillOnce(Return(p2p_quic_stream.get()));
+
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateConnectedQuicTransport(scope, std::move(p2p_quic_transport));
+ Persistent<RTCQuicStream> quic_stream =
+ quic_transport->createStream(ASSERT_NO_EXCEPTION);
+
+ Persistent<MockEventListener> state_change_listener =
+ CreateMockEventListener();
+ EXPECT_CALL(*state_change_listener, Invoke(_, _))
+ .WillOnce(InvokeWithoutArgs(
+ [quic_stream]() { EXPECT_EQ("closed", quic_stream->state()); }));
+ quic_stream->addEventListener(event_type_names::kStatechange,
+ state_change_listener);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnRemoteReset();
+
+ RunUntilIdle();
+}
+
+// Test that a pending OnRemoteReset() is ignored if reset() is called first.
+TEST_F(RTCQuicStreamTest, PendingOnRemoteResetIgnoredAfterReset) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, SetDelegate(_))
+ .WillOnce(SaveArg<0>(&stream_delegate));
+
+ auto p2p_quic_transport = std::make_unique<MockP2PQuicTransport>();
+ EXPECT_CALL(*p2p_quic_transport, CreateStream())
+ .WillOnce(Return(p2p_quic_stream.get()));
+
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateConnectedQuicTransport(scope, std::move(p2p_quic_transport));
+ Persistent<RTCQuicStream> quic_stream =
+ quic_transport->createStream(ASSERT_NO_EXCEPTION);
+
+ // Expect no statechange event since reset() will already transition the state
+ // to 'closed'.
+ Persistent<MockEventListener> state_change_listener =
+ CreateMockEventListener();
+ EXPECT_CALL(*state_change_listener, Invoke(_, _)).Times(0);
+ quic_stream->addEventListener(event_type_names::kStatechange,
+ state_change_listener);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnRemoteReset();
+ quic_stream->reset();
+ EXPECT_EQ("closed", quic_stream->state());
+
+ RunUntilIdle();
+
+ EXPECT_EQ("closed", quic_stream->state());
+}
+
+// The following group tests write(), finish(), writeBufferedAmount(), and
+// maxWriteBufferdAmount().
+
+// Test that write() adds to writeBufferedAmount().
+TEST_F(RTCQuicStreamTest, WriteAddsToWriteBufferedAmount) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ stream->write(CreateUint8Array({1, 2}), ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(2u, stream->writeBufferedAmount());
+
+ stream->write(CreateUint8Array({3, 4, 5}), ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(5u, stream->writeBufferedAmount());
+
+ RunUntilIdle();
+}
+
+// Test that write() calls WriteData() on the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, WriteCallsWriteData) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, WriteData(_, _))
+ .WillOnce(testing::Invoke([](Vector<uint8_t> data, bool fin) {
+ EXPECT_THAT(data, ElementsAre(1, 2, 3, 4));
+ EXPECT_FALSE(fin);
+ }));
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8Array({1, 2, 3, 4}), ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+}
+
+// Test that write() with no data succeeds but does not post a WriteData() to
+// the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, WriteWithEmptyArrayDoesNotCallWriteData) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, WriteData(_, _)).Times(0);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8Array({}), ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+}
+
+// Test that finish() calls WriteData() on the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, FinishCallsWriteData) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+ EXPECT_CALL(*p2p_quic_stream, WriteData(_, _))
+ .WillOnce(testing::Invoke([](Vector<uint8_t> data, bool fin) {
+ EXPECT_THAT(data, ElementsAre());
+ EXPECT_TRUE(fin);
+ }));
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->finish();
+
+ RunUntilIdle();
+}
+
+// Test that writeBufferedAmount is decreased when receiving OnWriteDataConsumed
+// from the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, OnWriteDataConsumedSubtractsFromWriteBufferedAmount) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(4), ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnWriteDataConsumed(4);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(0u, stream->writeBufferedAmount());
+}
+
+// Test that writeBufferedAmount is set to 0 if the stream was reset by the
+// remote peer.
+TEST_F(RTCQuicStreamTest, OnRemoteResetSetsWriteBufferedAmountToZero) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(4), ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnRemoteReset();
+
+ RunUntilIdle();
+
+ EXPECT_EQ(0u, stream->writeBufferedAmount());
+
+ RunUntilIdle();
+}
+
+// Test that writeBufferedAmount is set to 0 if the stream calls finish(),
+// followed by receiving a finish from the remote side, and reading it out.
+//
+// TODO(https://crbug.com/874296): It doesn't really make sense the write buffer
+// gets cleared in this case. Consider changing this.
+TEST_F(RTCQuicStreamTest,
+ FinishThenReceiveFinishSetsWriteBufferedAmountToZero) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(4), ASSERT_NO_EXCEPTION);
+ stream->finish();
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(4u, stream->writeBufferedAmount());
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(10));
+ EXPECT_TRUE(stream->readInto(read_buffer, ASSERT_NO_EXCEPTION)->finished());
+ EXPECT_EQ(0u, stream->writeBufferedAmount());
+
+ RunUntilIdle();
+}
+
+// Test that write throws an InvalidStateError if the stream was reset by the
+// remote peer.
+TEST_F(RTCQuicStreamTest, WriteThrowsIfRemoteReset) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnRemoteReset();
+
+ RunUntilIdle();
+
+ stream->write(CreateUint8ArrayOfLength(1), scope.GetExceptionState());
+ EXPECT_EQ(DOMExceptionCode::kInvalidStateError,
+ scope.GetExceptionState().CodeAs<DOMExceptionCode>());
+
+ RunUntilIdle();
+}
+
+// The following group tests waitForWriteBufferedAmountBelow().
+
+// Test that a waitForWriteBufferedAmountBelow() promise resolves once
+// OnWriteDataConsumed() frees up enough write buffer space.
+TEST_F(RTCQuicStreamTest, WaitForWriteBufferedAmountBelowResolves) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(stream->maxWriteBufferedAmount()),
+ ASSERT_NO_EXCEPTION);
+
+ ScriptPromise promise = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), stream->maxWriteBufferedAmount() - 1,
+ ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kPending,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnWriteDataConsumed(1);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that a waitForWriteBufferedAmount() promise does not resolve until
+// OnWriteDataConsumed() frees up exactly the threshold amount.
+TEST_F(RTCQuicStreamTest,
+ WaitForWriteBufferedAmountBelowDoesNotResolveUntilExceedsThreshold) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(stream->maxWriteBufferedAmount()),
+ ASSERT_NO_EXCEPTION);
+
+ ScriptPromise promise = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), stream->maxWriteBufferedAmount() - 10,
+ ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kPending,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ RunUntilIdle();
+
+ // Post OnWriteDataConsumed(9) -- this should not resolve the promise since
+ // we're waiting for 10 bytes to be available.
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnWriteDataConsumed(9);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kPending,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ // Post OnWriteDataConsumed(1) -- this should resolve the promise since now we
+ // have 9 + 1 = 10 bytes available.
+ stream_delegate->OnWriteDataConsumed(1);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that if two waitForWriteBufferedAmount() promises are waiting on
+// different thresholds, OnWriteDataConsumed() which satisfies the first
+// threshold but not the second will only resolve the first promise. Once
+// OnWriteDataConsumed() is received again past the second threshold then the
+// second promise will be resolved.
+TEST_F(RTCQuicStreamTest,
+ TwoWaitForWriteBufferedAmountBelowPromisesResolveInSequence) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(stream->maxWriteBufferedAmount()),
+ ASSERT_NO_EXCEPTION);
+
+ ScriptPromise promise_10 = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), stream->maxWriteBufferedAmount() - 10,
+ ASSERT_NO_EXCEPTION);
+ ScriptPromise promise_90 = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), stream->maxWriteBufferedAmount() - 90,
+ ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnWriteDataConsumed(10);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_10.V8Value().As<v8::Promise>()->State());
+ EXPECT_EQ(v8::Promise::kPending,
+ promise_90.V8Value().As<v8::Promise>()->State());
+
+ stream_delegate->OnWriteDataConsumed(80);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_90.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that if two waitForWriteBufferedAmount() promises are waiting on
+// different thresholds and a single OnWriteDataConsumed() is received such that
+// the buffered amount is below both thresholds then both promises are resolved.
+TEST_F(RTCQuicStreamTest,
+ TwoWaitForWriteBufferedAmountBelowPromisesResolveTogether) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(stream->maxWriteBufferedAmount()),
+ ASSERT_NO_EXCEPTION);
+
+ ScriptPromise promise_10 = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), stream->maxWriteBufferedAmount() - 10,
+ ASSERT_NO_EXCEPTION);
+ ScriptPromise promise_90 = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), stream->maxWriteBufferedAmount() - 90,
+ ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnWriteDataConsumed(90);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_10.V8Value().As<v8::Promise>()->State());
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_90.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that when receiving OnRemoteReset() the waitForWriteBufferedAmountBelow
+// Promise will be rejected.
+TEST_F(RTCQuicStreamTest,
+ WaitForWriteBufferedAmountBelowPromisesRejectedOnRemoteReset) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(stream->maxWriteBufferedAmount()),
+ ASSERT_NO_EXCEPTION);
+
+ ScriptPromise promise = stream->waitForWriteBufferedAmountBelow(
+ scope.GetScriptState(), 0, ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnRemoteReset();
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kRejected,
+ promise.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that there is no crash when the ExecutionContext is being destroyed and
+// there are pending waitForWriteBufferedAmountBelow() promises. If the
+// RTCQuicStream attempts to resolve the promise in ContextDestroyed, it will
+// likely crash since the v8::Isolate is being torn down.
+TEST_F(
+ RTCQuicStreamTest,
+ NoCrashIfPendingWaitForWriteBufferedAmountBelowPromisesOnContextDestroyed) {
+ V8TestingScope scope;
+
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>();
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->write(CreateUint8ArrayOfLength(stream->maxWriteBufferedAmount()),
+ ASSERT_NO_EXCEPTION);
+
+ stream->waitForWriteBufferedAmountBelow(scope.GetScriptState(), 0,
+ ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+}
+
+// The following group tests readInto(), readBufferedAmount(), and
+// maxReadBufferedAmount().
+
+static base::span<const uint8_t> GetSpan(NotShared<DOMUint8Array> data) {
+ return base::make_span(data.View()->Data(), data.View()->length());
+}
+
+// Test that readInto() with an empty data buffer succeeds but does not post
+// MarkReceivedDataConsumed() to the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, ReadIntoEmptyDoesNotPostMarkReceivedDataConsumed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ EXPECT_CALL(*p2p_quic_stream, MarkReceivedDataConsumed(_)).Times(0);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ EXPECT_EQ(0u, stream->readBufferedAmount());
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(0));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(0u, result->amount());
+ EXPECT_FALSE(result->finished());
+ EXPECT_EQ(0u, stream->readBufferedAmount());
+
+ RunUntilIdle();
+}
+
+// Test that data delived via OnDataReceived() increases readBufferedAmount.
+TEST_F(RTCQuicStreamTest, OnDataReceivedIncreasesReadBufferedAmount) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(3u, stream->readBufferedAmount());
+}
+
+// Test that readInto() reads out data received from OnDataReceived() and
+// decreases readBufferedAmount.
+TEST_F(RTCQuicStreamTest, ReadIntoReadsDataFromOnDataReceived) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(5));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(3u, result->amount());
+ EXPECT_FALSE(result->finished());
+ EXPECT_THAT(GetSpan(read_buffer), ElementsAre(1, 2, 3, 0, 0));
+ EXPECT_EQ(0u, stream->readBufferedAmount());
+
+ RunUntilIdle();
+}
+
+// Test that readInto() posts MarkReceivedDataConsumed() with the amount of
+// bytes read to the underlying P2PQuicStream.
+TEST_F(RTCQuicStreamTest, ReadIntoPostsMarkReceivedDataConsumed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ EXPECT_CALL(*p2p_quic_stream, MarkReceivedDataConsumed(3)).Times(1);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(5));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(3u, result->amount());
+ EXPECT_FALSE(result->finished());
+
+ RunUntilIdle();
+}
+
+// Test that readInto() returns {finished: true} if OnDataReceived() has
+// indicated the stream is finished without receiving any data.
+TEST_F(RTCQuicStreamTest, ReadIntoReadsBareFin) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> empty_read_buffer(DOMUint8Array::Create(0));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(empty_read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(0u, result->amount());
+ EXPECT_TRUE(result->finished());
+
+ RunUntilIdle();
+}
+
+// Test that readInto() indicates finished once all buffered received data has
+// been read.
+TEST_F(RTCQuicStreamTest, ReadIntoReadsBufferedDataAndFinish) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(3));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(3u, result->amount());
+ EXPECT_TRUE(result->finished());
+ EXPECT_THAT(GetSpan(read_buffer), ElementsAre(1, 2, 3));
+
+ RunUntilIdle();
+}
+
+// Test that readInto() does not indicate finished until all buffered data has
+// been read out, even if the fin has already been received.
+TEST_F(RTCQuicStreamTest, ReadIntoReadsPartialDataBeforeFin) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ {
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(2));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(2u, result->amount());
+ EXPECT_FALSE(result->finished());
+ EXPECT_THAT(GetSpan(read_buffer), ElementsAre(1, 2));
+ }
+
+ {
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(2));
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(1u, result->amount());
+ EXPECT_TRUE(result->finished());
+ EXPECT_THAT(GetSpan(read_buffer), ElementsAre(3, 0));
+ }
+
+ RunUntilIdle();
+}
+
+// Test that readInto() does not post MarkReceivedDataConsumed() to the
+// underlying P2PQuicStream once the finish flag has been delivered in
+// OnDataReceived().
+TEST_F(RTCQuicStreamTest,
+ ReadIntoDoesNotPostMarkReceivedDataConsumedOnceFinReceived) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ EXPECT_CALL(*p2p_quic_stream, MarkReceivedDataConsumed(_)).Times(0);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(2));
+
+ RTCQuicStreamReadResult* result =
+ stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(2u, result->amount());
+ EXPECT_FALSE(result->finished());
+
+ result = stream->readInto(read_buffer, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(1u, result->amount());
+ EXPECT_TRUE(result->finished());
+
+ RunUntilIdle();
+}
+
+// Test that readInto() throws an InvalidStateError if the finish flag has
+// already been read out.
+TEST_F(RTCQuicStreamTest, ReadIntoThrowsIfFinishAlreadyRead) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(2));
+ EXPECT_TRUE(stream->readInto(read_buffer, ASSERT_NO_EXCEPTION)->finished());
+
+ stream->readInto(read_buffer, scope.GetExceptionState());
+ EXPECT_EQ(DOMExceptionCode::kInvalidStateError,
+ scope.GetExceptionState().CodeAs<DOMExceptionCode>());
+}
+
+// Test that readInto() throws an InvalidStateError if the stream is closed.
+TEST_F(RTCQuicStreamTest, ReadIntoThrowsIfClosed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+ stream->reset();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(2));
+ stream->readInto(read_buffer, scope.GetExceptionState());
+ EXPECT_EQ(DOMExceptionCode::kInvalidStateError,
+ scope.GetExceptionState().CodeAs<DOMExceptionCode>());
+
+ RunUntilIdle();
+}
+
+// The following group tests waitForReadable().
+
+// Test that a waitForReadable() promise resolves once OnDataReceived() delivers
+// enough data.
+TEST_F(RTCQuicStreamTest, WaitForReadableResolves) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ ScriptPromise promise =
+ stream->waitForReadable(scope.GetScriptState(), 3, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kPending,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that a waitForReadable() promise resolves immediately if sufficient data
+// is already in the receive buffer.
+TEST_F(RTCQuicStreamTest, WaitForReadableResolveImmediately) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ ScriptPromise promise =
+ stream->waitForReadable(scope.GetScriptState(), 3, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ RunUntilIdle();
+}
+
+// Test that a waitForReadable() promise resolves immediately if finish has
+// been received, but not yet read out.
+TEST_F(RTCQuicStreamTest,
+ WaitForReadableResolveImmediatelyAfterFinishReceived) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ ScriptPromise promise =
+ stream->waitForReadable(scope.GetScriptState(), 10, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ RunUntilIdle();
+}
+
+// Test that a waitForReadable() promise does not resolve until OnDataReceived()
+// delivers at least the readable amount.
+TEST_F(RTCQuicStreamTest, WaitForReadableDoesNotResolveUntilExceedsThreshold) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ ScriptPromise promise =
+ stream->waitForReadable(scope.GetScriptState(), 5, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kPending,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kPending,
+ promise.V8Value().As<v8::Promise>()->State());
+
+ stream_delegate->OnDataReceived({4, 5}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that if two waitForReadable() promises are waiting on different readable
+// amounts, OnDataReceived() which satisfies the first readable amount but not
+// the second will only resolve the first promise. Once OnDataReceived() is
+// received again with readable amount satisfying the second promise then it
+// will be resolved.
+TEST_F(RTCQuicStreamTest, TwoWaitForReadablePromisesResolveInSequence) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ ScriptPromise promise_3 =
+ stream->waitForReadable(scope.GetScriptState(), 3, ASSERT_NO_EXCEPTION);
+ ScriptPromise promise_5 =
+ stream->waitForReadable(scope.GetScriptState(), 5, ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_3.V8Value().As<v8::Promise>()->State());
+ EXPECT_EQ(v8::Promise::kPending,
+ promise_5.V8Value().As<v8::Promise>()->State());
+
+ stream_delegate->OnDataReceived({4, 5}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_5.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that if two waitForReadable() promises are waiting on different
+// thresholds and a single OnDataReceived() is received such that the readable
+// amount satisfies both promises then they are both resolved.
+TEST_F(RTCQuicStreamTest, TwoWaitForReadablePromisesResolveTogether) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ ScriptPromise promise_3 =
+ stream->waitForReadable(scope.GetScriptState(), 3, ASSERT_NO_EXCEPTION);
+ ScriptPromise promise_5 =
+ stream->waitForReadable(scope.GetScriptState(), 5, ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({1, 2, 3, 4, 5}, /*fin=*/false);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_3.V8Value().As<v8::Promise>()->State());
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_5.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that a remote finish immediately resolves all pending waitForReadable()
+// promises.
+TEST_F(RTCQuicStreamTest, RemoteFinishResolvesPendingWaitForReadablePromises) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ ScriptPromise promise_3 =
+ stream->waitForReadable(scope.GetScriptState(), 3, ASSERT_NO_EXCEPTION);
+ ScriptPromise promise_5 =
+ stream->waitForReadable(scope.GetScriptState(), 5, ASSERT_NO_EXCEPTION);
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_3.V8Value().As<v8::Promise>()->State());
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise_5.V8Value().As<v8::Promise>()->State());
+}
+
+// Test that calling waitForReadable() resolves immediately if the finish has
+// been received via OnDataReceived() but not yet read out via readInto().
+// Note: If the finish has been read out via readInto(), waitForReadable() will
+// throw an exception since the stream is no longer readable.
+TEST_F(RTCQuicStreamTest, WaitForReadableResolvesImmediatelyIfRemoteFinished) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ ScriptPromise promise =
+ stream->waitForReadable(scope.GetScriptState(), 5, ASSERT_NO_EXCEPTION);
+ EXPECT_EQ(v8::Promise::kFulfilled,
+ promise.V8Value().As<v8::Promise>()->State());
+}
+
+// The following group tests state transitions with reset(), finish(), remote
+// reset() and remote finish()
+
+// Test that a OnRemoteReset() immediately transitions the state to 'closed'.
+TEST_F(RTCQuicStreamTest, OnRemoteResetTransitionsToClosed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ EXPECT_EQ("open", stream->state());
+ stream_delegate->OnRemoteReset();
+
+ RunUntilIdle();
+
+ EXPECT_EQ("closed", stream->state());
+
+ RunUntilIdle();
+}
+
+// Test that calling finish() after reading out a remote finish transitions
+// state to 'closed'.
+TEST_F(RTCQuicStreamTest, FinishAfterReadingRemoteFinishTransitionsToClosed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ EXPECT_CALL(*p2p_quic_stream, WriteData(_, true)).Times(1);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(10));
+ EXPECT_TRUE(stream->readInto(read_buffer, ASSERT_NO_EXCEPTION)->finished());
+
+ EXPECT_EQ("closing", stream->state());
+
+ stream->finish();
+
+ EXPECT_EQ("closed", stream->state());
+
+ RunUntilIdle();
+}
+
+// Test that reading out a remote finish after calling finish() transitions
+// state to 'closed'.
+TEST_F(RTCQuicStreamTest, ReadingRemoteFinishAfterFinishTransitionsToClosed) {
+ V8TestingScope scope;
+
+ P2PQuicStream::Delegate* stream_delegate = nullptr;
+ auto p2p_quic_stream = std::make_unique<MockP2PQuicStream>(&stream_delegate);
+ EXPECT_CALL(*p2p_quic_stream, WriteData(_, true)).Times(1);
+ Persistent<RTCQuicStream> stream =
+ CreateQuicStream(scope, p2p_quic_stream.get());
+
+ stream->finish();
+
+ EXPECT_EQ("closing", stream->state());
+
+ RunUntilIdle();
+
+ ASSERT_TRUE(stream_delegate);
+ stream_delegate->OnDataReceived({}, /*fin=*/true);
+
+ RunUntilIdle();
+
+ EXPECT_EQ("closing", stream->state());
+
+ NotShared<DOMUint8Array> read_buffer(DOMUint8Array::Create(10));
+ EXPECT_TRUE(stream->readInto(read_buffer, ASSERT_NO_EXCEPTION)->finished());
+
+ EXPECT_EQ("closed", stream->state());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.cc
index 926ba270ffc..77a09482c0a 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.cc
@@ -33,9 +33,12 @@ class DefaultP2PQuicTransportFactory : public P2PQuicTransportFactory {
// P2PQuicTransportFactory overrides.
std::unique_ptr<P2PQuicTransport> CreateQuicTransport(
- P2PQuicTransportConfig config) override {
+ P2PQuicTransport::Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& config) override {
DCHECK(host_thread_->RunsTasksInCurrentSequence());
- return GetFactory()->CreateQuicTransport(std::move(config));
+ return GetFactory()->CreateQuicTransport(delegate, packet_transport,
+ config);
}
private:
@@ -96,8 +99,9 @@ RTCQuicTransport* RTCQuicTransport::Create(
return nullptr;
}
}
- return new RTCQuicTransport(context, transport, certificates, exception_state,
- std::move(p2p_quic_transport_factory));
+ return MakeGarbageCollected<RTCQuicTransport>(
+ context, transport, certificates, exception_state,
+ std::move(p2p_quic_transport_factory));
}
RTCQuicTransport::RTCQuicTransport(
@@ -106,7 +110,7 @@ RTCQuicTransport::RTCQuicTransport(
const HeapVector<Member<RTCCertificate>>& certificates,
ExceptionState& exception_state,
std::unique_ptr<P2PQuicTransportFactory> p2p_quic_transport_factory)
- : ContextLifecycleObserver(context),
+ : ContextClient(context),
transport_(transport),
certificates_(certificates),
p2p_quic_transport_factory_(std::move(p2p_quic_transport_factory)) {
@@ -117,18 +121,6 @@ RTCQuicTransport::~RTCQuicTransport() {
DCHECK(!proxy_);
}
-void RTCQuicTransport::Close(RTCQuicTransportState new_state) {
- DCHECK(!IsClosed());
- for (RTCQuicStream* stream : streams_) {
- stream->Stop();
- }
- streams_.clear();
- transport_->DisconnectConsumer(this);
- proxy_.reset();
- state_ = new_state;
- DCHECK(IsClosed());
-}
-
RTCIceTransport* RTCQuicTransport::transport() const {
return transport_;
}
@@ -149,8 +141,10 @@ String RTCQuicTransport::state() const {
return String();
}
-void RTCQuicTransport::getLocalParameters(RTCQuicParameters& result) const {
- HeapVector<RTCDtlsFingerprint> fingerprints;
+RTCQuicParameters* RTCQuicTransport::getLocalParameters() const {
+ RTCQuicParameters* result = RTCQuicParameters::Create();
+
+ HeapVector<Member<RTCDtlsFingerprint>> fingerprints;
for (const auto& certificate : certificates_) {
// TODO(github.com/w3c/webrtc-quic/issues/33): The specification says that
// getLocalParameters should return one fingerprint per certificate but is
@@ -160,12 +154,12 @@ void RTCQuicTransport::getLocalParameters(RTCQuicParameters& result) const {
fingerprints.push_back(certificate_fingerprint);
}
}
- result.setFingerprints(fingerprints);
+ result->setFingerprints(fingerprints);
+ return result;
}
-void RTCQuicTransport::getRemoteParameters(
- base::Optional<RTCQuicParameters>& result) const {
- result = remote_parameters_;
+RTCQuicParameters* RTCQuicTransport::getRemoteParameters() const {
+ return remote_parameters_;
}
const HeapVector<Member<RTCCertificate>>& RTCQuicTransport::getCertificates()
@@ -190,7 +184,7 @@ static quic::Perspective QuicPerspectiveFromIceRole(cricket::IceRole ice_role) {
return quic::Perspective::IS_CLIENT;
}
-void RTCQuicTransport::start(const RTCQuicParameters& remote_parameters,
+void RTCQuicTransport::start(const RTCQuicParameters* remote_parameters,
ExceptionState& exception_state) {
if (RaiseExceptionIfClosed(exception_state)) {
return;
@@ -200,16 +194,16 @@ void RTCQuicTransport::start(const RTCQuicParameters& remote_parameters,
"Cannot start() multiple times.");
return;
}
- remote_parameters_ = remote_parameters;
+ remote_parameters_ = const_cast<RTCQuicParameters*>(remote_parameters);
if (transport_->IsStarted()) {
StartConnection();
}
}
static std::unique_ptr<rtc::SSLFingerprint> RTCDtlsFingerprintToSSLFingerprint(
- const RTCDtlsFingerprint& dtls_fingerprint) {
- std::string algorithm = WebString(dtls_fingerprint.algorithm()).Utf8();
- std::string value = WebString(dtls_fingerprint.value()).Utf8();
+ const RTCDtlsFingerprint* dtls_fingerprint) {
+ std::string algorithm = WebString(dtls_fingerprint->algorithm()).Utf8();
+ std::string value = WebString(dtls_fingerprint->value()).Utf8();
std::unique_ptr<rtc::SSLFingerprint> rtc_fingerprint(
rtc::SSLFingerprint::CreateFromRfc4572(algorithm, value));
DCHECK(rtc_fingerprint);
@@ -227,19 +221,26 @@ void RTCQuicTransport::StartConnection() {
rtc_certificates.push_back(certificate->Certificate());
}
IceTransportProxy* transport_proxy = transport_->ConnectConsumer(this);
- proxy_.reset(new QuicTransportProxy(
- this, transport_proxy, QuicPerspectiveFromIceRole(transport_->GetRole()),
- rtc_certificates, std::move(p2p_quic_transport_factory_)));
+ // TODO(https://crbug.com/874296): Use the proper read/write buffer sizees
+ // once write() and readInto() are implemented.
+ const uint32_t stream_buffer_size = 24 * 1024 * 1024;
+ P2PQuicTransportConfig quic_transport_config(
+ QuicPerspectiveFromIceRole(transport_->GetRole()), rtc_certificates,
+ /*stream_delegate_read_buffer_size_in=*/stream_buffer_size,
+ /*stream_write_buffer_size_in=*/stream_buffer_size);
+ proxy_.reset(new QuicTransportProxy(this, transport_proxy,
+ std::move(p2p_quic_transport_factory_),
+ quic_transport_config));
std::vector<std::unique_ptr<rtc::SSLFingerprint>> rtc_fingerprints;
- for (const RTCDtlsFingerprint& fingerprint :
+ for (const RTCDtlsFingerprint* fingerprint :
remote_parameters_->fingerprints()) {
rtc_fingerprints.push_back(RTCDtlsFingerprintToSSLFingerprint(fingerprint));
}
proxy_->Start(std::move(rtc_fingerprints));
}
-void RTCQuicTransport::OnTransportStarted() {
+void RTCQuicTransport::OnIceTransportStarted() {
// The RTCIceTransport has now been started.
if (remote_parameters_) {
StartConnection();
@@ -250,10 +251,7 @@ void RTCQuicTransport::stop() {
if (IsClosed()) {
return;
}
- if (proxy_) {
- proxy_->Stop();
- }
- Close(RTCQuicTransportState::kClosed);
+ Close(CloseReason::kLocalStopped);
}
RTCQuicStream* RTCQuicTransport::createStream(ExceptionState& exception_state) {
@@ -284,18 +282,16 @@ void RTCQuicTransport::RemoveStream(RTCQuicStream* stream) {
void RTCQuicTransport::OnConnected() {
state_ = RTCQuicTransportState::kConnected;
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ DispatchEvent(*Event::Create(event_type_names::kStatechange));
}
void RTCQuicTransport::OnConnectionFailed(const std::string& error_details,
bool from_remote) {
- Close(RTCQuicTransportState::kFailed);
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ Close(CloseReason::kFailed);
}
void RTCQuicTransport::OnRemoteStopped() {
- Close(RTCQuicTransportState::kClosed);
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ Close(CloseReason::kRemoteStopped);
}
void RTCQuicTransport::OnStream(QuicStreamProxy* stream_proxy) {
@@ -303,6 +299,57 @@ void RTCQuicTransport::OnStream(QuicStreamProxy* stream_proxy) {
DispatchEvent(*RTCQuicStreamEvent::Create(stream));
}
+void RTCQuicTransport::OnIceTransportClosed(
+ RTCIceTransport::CloseReason reason) {
+ if (reason == RTCIceTransport::CloseReason::kContextDestroyed) {
+ Close(CloseReason::kContextDestroyed);
+ } else {
+ Close(CloseReason::kIceTransportClosed);
+ }
+}
+
+void RTCQuicTransport::Close(CloseReason reason) {
+ DCHECK(!IsClosed());
+
+ // Disconnect from the RTCIceTransport, allowing a new RTCQuicTransport to
+ // connect to it.
+ transport_->DisconnectConsumer(this);
+
+ // Notify the active streams that the transport is closing.
+ for (RTCQuicStream* stream : streams_) {
+ stream->OnQuicTransportClosed(reason);
+ }
+ streams_.clear();
+
+ // Tear down the QuicTransportProxy and change the state.
+ switch (reason) {
+ case CloseReason::kLocalStopped:
+ case CloseReason::kIceTransportClosed:
+ case CloseReason::kContextDestroyed:
+ // The QuicTransportProxy may be active so gracefully Stop() before
+ // destroying it.
+ if (proxy_) {
+ proxy_->Stop();
+ proxy_.reset();
+ }
+ state_ = RTCQuicTransportState::kClosed;
+ break;
+ case CloseReason::kRemoteStopped:
+ case CloseReason::kFailed:
+ // The QuicTransportProxy has already been closed by the event, so just go
+ // ahead and delete it.
+ proxy_.reset();
+ state_ =
+ (reason == CloseReason::kFailed ? RTCQuicTransportState::kFailed
+ : RTCQuicTransportState::kClosed);
+ DispatchEvent(*Event::Create(event_type_names::kStatechange));
+ break;
+ }
+
+ DCHECK(!proxy_);
+ DCHECK(IsClosed());
+}
+
bool RTCQuicTransport::RaiseExceptionIfClosed(
ExceptionState& exception_state) const {
if (IsClosed()) {
@@ -315,19 +362,11 @@ bool RTCQuicTransport::RaiseExceptionIfClosed(
}
const AtomicString& RTCQuicTransport::InterfaceName() const {
- return EventTargetNames::RTCQuicTransport;
+ return event_target_names::kRTCQuicTransport;
}
ExecutionContext* RTCQuicTransport::GetExecutionContext() const {
- return ContextLifecycleObserver::GetExecutionContext();
-}
-
-void RTCQuicTransport::ContextDestroyed(ExecutionContext*) {
- stop();
-}
-
-bool RTCQuicTransport::HasPendingActivity() const {
- return static_cast<bool>(proxy_);
+ return ContextClient::GetExecutionContext();
}
void RTCQuicTransport::Trace(blink::Visitor* visitor) {
@@ -337,7 +376,7 @@ void RTCQuicTransport::Trace(blink::Visitor* visitor) {
visitor->Trace(remote_parameters_);
visitor->Trace(streams_);
EventTargetWithInlineData::Trace(visitor);
- ContextLifecycleObserver::Trace(visitor);
+ ContextClient::Trace(visitor);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h
index d469d81ae28..c69f9e7dc8e 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h
@@ -5,10 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_QUIC_TRANSPORT_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_QUIC_TRANSPORT_H_
-#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/peerconnection/adapters/quic_transport_proxy.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_parameters.h"
namespace blink {
@@ -16,7 +16,6 @@ namespace blink {
class DOMArrayBuffer;
class ExceptionState;
class RTCCertificate;
-class RTCIceTransport;
class RTCQuicStream;
class P2PQuicTransportFactory;
@@ -28,15 +27,30 @@ enum class RTCQuicTransportState {
kFailed
};
+// The RTCQuicTransport does not need to be ActiveScriptWrappable since the
+// RTCIceTransport to which it is attached holds a strong reference to it as
+// long as it is alive.
class MODULES_EXPORT RTCQuicTransport final
: public EventTargetWithInlineData,
- public ActiveScriptWrappable<RTCQuicTransport>,
- public ContextLifecycleObserver,
+ public ContextClient,
public QuicTransportProxy::Delegate {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(RTCQuicTransport);
public:
+ enum class CloseReason {
+ // stop() was called.
+ kLocalStopped,
+ // The remote side closed the QUIC connection.
+ kRemoteStopped,
+ // The QUIC connection failed.
+ kFailed,
+ // The RTCIceTransport was closed.
+ kIceTransportClosed,
+ // The ExecutionContext is being destroyed.
+ kContextDestroyed,
+ };
+
static RTCQuicTransport* Create(
ExecutionContext* context,
RTCIceTransport* transport,
@@ -49,50 +63,46 @@ class MODULES_EXPORT RTCQuicTransport final
ExceptionState& exception_state,
std::unique_ptr<P2PQuicTransportFactory> p2p_quic_transport_factory);
+ RTCQuicTransport(
+ ExecutionContext* context,
+ RTCIceTransport* transport,
+ const HeapVector<Member<RTCCertificate>>& certificates,
+ ExceptionState& exception_state,
+ std::unique_ptr<P2PQuicTransportFactory> p2p_quic_transport_factory);
~RTCQuicTransport() override;
+ // Called by the RTCIceTransport when it is being closed.
+ void OnIceTransportClosed(RTCIceTransport::CloseReason reason);
+
+ // Called by the RTCIceTransport when its start() method is called.
+ void OnIceTransportStarted();
+
RTCQuicStream* AddStream(QuicStreamProxy* stream_proxy);
void RemoveStream(RTCQuicStream* stream);
// https://w3c.github.io/webrtc-quic/#quic-transport*
RTCIceTransport* transport() const;
String state() const;
- void getLocalParameters(RTCQuicParameters& result) const;
- void getRemoteParameters(base::Optional<RTCQuicParameters>& result) const;
+ RTCQuicParameters* getLocalParameters() const;
+ RTCQuicParameters* getRemoteParameters() const;
const HeapVector<Member<RTCCertificate>>& getCertificates() const;
const HeapVector<Member<DOMArrayBuffer>>& getRemoteCertificates() const;
- void start(const RTCQuicParameters& remote_parameters,
+ void start(const RTCQuicParameters* remote_parameters,
ExceptionState& exception_state);
void stop();
RTCQuicStream* createStream(ExceptionState& exception_state);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(quicstream);
-
- // Called by the RTCIceTransport when its start() method is called.
- void OnTransportStarted();
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(quicstream, kQuicstream);
// EventTarget overrides.
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
- // ContextLifecycleObserver overrides.
- void ContextDestroyed(ExecutionContext*) override;
-
- // ActiveScriptWrappable overrides.
- bool HasPendingActivity() const override;
-
// For garbage collection.
void Trace(blink::Visitor* visitor) override;
private:
- RTCQuicTransport(
- ExecutionContext* context,
- RTCIceTransport* transport,
- const HeapVector<Member<RTCCertificate>>& certificates,
- ExceptionState& exception_state,
- std::unique_ptr<P2PQuicTransportFactory> p2p_quic_transport_factory);
-
// QuicTransportProxy::Delegate overrides;
void OnConnected() override;
void OnConnectionFailed(const std::string& error_details,
@@ -100,21 +110,23 @@ class MODULES_EXPORT RTCQuicTransport final
void OnRemoteStopped() override;
void OnStream(QuicStreamProxy* stream_proxy) override;
- bool IsClosed() const { return state_ == RTCQuicTransportState::kClosed; }
- bool RaiseExceptionIfClosed(ExceptionState& exception_state) const;
-
// Starts the underlying QUIC connection.
void StartConnection();
- // Close all streams, delete the underlying QUIC transport, and transition to
- // the given state, closed or failed.
- void Close(RTCQuicTransportState new_state);
+ // Permenantly closes the RTCQuicTransport with the given reason.
+ // The RTCQuicTransport must not already be closed or failed.
+ // This will transition the state to either closed or failed according to the
+ // reason.
+ void Close(CloseReason reason);
+
+ bool IsClosed() const { return state_ == RTCQuicTransportState::kClosed; }
+ bool RaiseExceptionIfClosed(ExceptionState& exception_state) const;
Member<RTCIceTransport> transport_;
RTCQuicTransportState state_ = RTCQuicTransportState::kNew;
HeapVector<Member<RTCCertificate>> certificates_;
HeapVector<Member<DOMArrayBuffer>> remote_certificates_;
- base::Optional<RTCQuicParameters> remote_parameters_;
+ Member<RTCQuicParameters> remote_parameters_;
std::unique_ptr<P2PQuicTransportFactory> p2p_quic_transport_factory_;
std::unique_ptr<QuicTransportProxy> proxy_;
HeapHashSet<Member<RTCQuicStream>> streams_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl
index ab25d010506..89a2a696071 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.idl
@@ -13,7 +13,6 @@ enum RTCQuicTransportState {
// https://w3c.github.io/webrtc-quic/#quic-transport*
[
- ActiveScriptWrappable,
Constructor(RTCIceTransport transport, sequence<RTCCertificate> certificates),
ConstructorCallWith=ExecutionContext,
RaisesException=Constructor,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.cc
index e16b065df82..5c2df982b99 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.cc
@@ -24,9 +24,9 @@ using testing::Mock;
HeapVector<Member<RTCCertificate>> GenerateLocalRTCCertificates() {
HeapVector<Member<RTCCertificate>> certificates;
- certificates.push_back(
- new RTCCertificate(rtc::RTCCertificateGenerator::GenerateCertificate(
- rtc::KeyParams::ECDSA(), absl::nullopt)));
+ certificates.push_back(MakeGarbageCollected<RTCCertificate>(
+ rtc::RTCCertificateGenerator::GenerateCertificate(rtc::KeyParams::ECDSA(),
+ absl::nullopt)));
return certificates;
}
@@ -35,18 +35,18 @@ constexpr char kRemoteFingerprintValue1[] =
"8E:57:5F:8E:65:D2:83:7B:05:97:BB:72:DE:09:DE:03:BD:95:9B:A0:03:10:50:82:"
"5E:73:38:16:4C:E0:C5:84";
-RTCDtlsFingerprint CreateRemoteFingerprint1() {
- RTCDtlsFingerprint dtls_fingerprint;
- dtls_fingerprint.setAlgorithm(kRemoteFingerprintAlgorithm1);
- dtls_fingerprint.setValue(kRemoteFingerprintValue1);
+RTCDtlsFingerprint* CreateRemoteFingerprint1() {
+ RTCDtlsFingerprint* dtls_fingerprint = RTCDtlsFingerprint::Create();
+ dtls_fingerprint->setAlgorithm(kRemoteFingerprintAlgorithm1);
+ dtls_fingerprint->setValue(kRemoteFingerprintValue1);
return dtls_fingerprint;
}
-RTCQuicParameters CreateRemoteRTCQuicParameters1() {
- HeapVector<RTCDtlsFingerprint> fingerprints;
+RTCQuicParameters* CreateRemoteRTCQuicParameters1() {
+ HeapVector<Member<RTCDtlsFingerprint>> fingerprints;
fingerprints.push_back(CreateRemoteFingerprint1());
- RTCQuicParameters quic_parameters;
- quic_parameters.setFingerprints(fingerprints);
+ RTCQuicParameters* quic_parameters = RTCQuicParameters::Create();
+ quic_parameters->setFingerprints(fingerprints);
return quic_parameters;
}
@@ -73,6 +73,36 @@ RTCQuicTransport* RTCQuicTransportTest::CreateQuicTransport(
std::move(mock_factory));
}
+RTCQuicTransport* RTCQuicTransportTest::CreateConnectedQuicTransport(
+ V8TestingScope& scope,
+ P2PQuicTransport::Delegate** delegate_out) {
+ return CreateConnectedQuicTransport(
+ scope, std::make_unique<MockP2PQuicTransport>(), delegate_out);
+}
+
+RTCQuicTransport* RTCQuicTransportTest::CreateConnectedQuicTransport(
+ V8TestingScope& scope,
+ std::unique_ptr<MockP2PQuicTransport> mock_transport,
+ P2PQuicTransport::Delegate** delegate_out) {
+ Persistent<RTCIceTransport> ice_transport = CreateIceTransport(scope);
+ ice_transport->start(CreateRemoteRTCIceParameters1(), "controlling",
+ ASSERT_NO_EXCEPTION);
+ P2PQuicTransport::Delegate* delegate = nullptr;
+ Persistent<RTCQuicTransport> quic_transport =
+ CreateQuicTransport(scope, ice_transport, GenerateLocalRTCCertificates(),
+ std::move(mock_transport), &delegate);
+ quic_transport->start(CreateRemoteRTCQuicParameters1(), ASSERT_NO_EXCEPTION);
+ RunUntilIdle();
+ DCHECK(delegate);
+ delegate->OnConnected();
+ RunUntilIdle();
+ DCHECK_EQ("connected", quic_transport->state());
+ if (delegate_out) {
+ *delegate_out = delegate;
+ }
+ return quic_transport;
+}
+
// Test that calling start() creates a P2PQuicTransport with the correct
// P2PQuicTransportConfig. The config should have:
// 1. The P2PQuicPacketTransport returned by the MockIceTransportAdapter.
@@ -93,24 +123,26 @@ TEST_F(RTCQuicTransportTest, P2PQuicTransportConstructedByStart) {
rtc::scoped_refptr<rtc::RTCCertificate> certificate =
rtc::RTCCertificateGenerator::GenerateCertificate(rtc::KeyParams::ECDSA(),
absl::nullopt);
- auto mock_factory = std::make_unique<MockP2PQuicTransportFactory>(
- std::make_unique<MockP2PQuicTransport>());
- EXPECT_CALL(*mock_factory, OnCreateQuicTransport(_))
- .WillOnce(Invoke([quic_packet_transport_ptr,
- certificate](const P2PQuicTransportConfig& config) {
- EXPECT_EQ(quic_packet_transport_ptr, config.packet_transport);
- EXPECT_TRUE(config.is_server);
+ auto mock_factory = std::make_unique<MockP2PQuicTransportFactory>();
+ EXPECT_CALL(*mock_factory, CreateQuicTransport(_, _, _))
+ .WillOnce(Invoke([quic_packet_transport_ptr, certificate](
+ P2PQuicTransport::Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& config) {
+ EXPECT_EQ(quic_packet_transport_ptr, packet_transport);
+ EXPECT_EQ(quic::Perspective::IS_SERVER, config.perspective);
EXPECT_THAT(config.certificates, ElementsAre(certificate));
+ return std::make_unique<MockP2PQuicTransport>();
}));
HeapVector<Member<RTCCertificate>> certificates;
- certificates.push_back(new RTCCertificate(certificate));
+ certificates.push_back(MakeGarbageCollected<RTCCertificate>(certificate));
Persistent<RTCQuicTransport> quic_transport = CreateQuicTransport(
scope, ice_transport, certificates, std::move(mock_factory));
quic_transport->start(CreateRemoteRTCQuicParameters1(), ASSERT_NO_EXCEPTION);
}
-// Test that calling start() creates a P2PQuicTransport with
-// |config.is_server| = false if the RTCIceTransport role is 'controlled'.
+// Test that calling start() creates a P2PQuicTransport with client perspective
+// if the RTCIceTransport role is 'controlled'.
TEST_F(RTCQuicTransportTest, P2PQuicTransportConstructedByStartClient) {
V8TestingScope scope;
@@ -123,9 +155,12 @@ TEST_F(RTCQuicTransportTest, P2PQuicTransportConstructedByStartClient) {
auto mock_factory = std::make_unique<MockP2PQuicTransportFactory>(
std::make_unique<MockP2PQuicTransport>());
- EXPECT_CALL(*mock_factory, OnCreateQuicTransport(_))
- .WillOnce(Invoke([](const P2PQuicTransportConfig& config) {
- EXPECT_FALSE(config.is_server);
+ EXPECT_CALL(*mock_factory, CreateQuicTransport(_, _, _))
+ .WillOnce(Invoke([](P2PQuicTransport::Delegate* delegate,
+ P2PQuicPacketTransport* packet_transport,
+ const P2PQuicTransportConfig& config) {
+ EXPECT_EQ(quic::Perspective::IS_CLIENT, config.perspective);
+ return std::make_unique<MockP2PQuicTransport>();
}));
Persistent<RTCQuicTransport> quic_transport =
CreateQuicTransport(scope, ice_transport, GenerateLocalRTCCertificates(),
@@ -211,22 +246,24 @@ TEST_F(RTCQuicTransportTest, RTCIceTransportStopDeletesP2PQuicTransport) {
// is ContextDestroyed.
TEST_F(RTCQuicTransportTest,
RTCIceTransportContextDestroyedDeletesP2PQuicTransport) {
- V8TestingScope scope;
+ bool mock_deleted = false;
+ {
+ V8TestingScope scope;
- Persistent<RTCIceTransport> ice_transport = CreateIceTransport(scope);
- ice_transport->start(CreateRemoteRTCIceParameters1(), "controlling",
- ASSERT_NO_EXCEPTION);
+ Persistent<RTCIceTransport> ice_transport = CreateIceTransport(scope);
+ ice_transport->start(CreateRemoteRTCIceParameters1(), "controlling",
+ ASSERT_NO_EXCEPTION);
- bool mock_deleted = false;
- auto mock_transport = std::make_unique<MockP2PQuicTransport>();
- EXPECT_CALL(*mock_transport, Die()).WillOnce(Assign(&mock_deleted, true));
+ auto mock_transport = std::make_unique<MockP2PQuicTransport>();
+ EXPECT_CALL(*mock_transport, Die()).WillOnce(Assign(&mock_deleted, true));
- Persistent<RTCQuicTransport> quic_transport =
- CreateQuicTransport(scope, ice_transport, GenerateLocalRTCCertificates(),
- std::move(mock_transport));
- quic_transport->start(CreateRemoteRTCQuicParameters1(), ASSERT_NO_EXCEPTION);
+ Persistent<RTCQuicTransport> quic_transport = CreateQuicTransport(
+ scope, ice_transport, GenerateLocalRTCCertificates(),
+ std::move(mock_transport));
+ quic_transport->start(CreateRemoteRTCQuicParameters1(),
+ ASSERT_NO_EXCEPTION);
+ } // ContextDestroyed when V8TestingScope goes out of scope.
- ice_transport->ContextDestroyed(scope.GetExecutionContext());
RunUntilIdle();
EXPECT_TRUE(mock_deleted);
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.h
index 05683f98c4c..f299471bbe4 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_quic_transport_test.h
@@ -33,6 +33,16 @@ class RTCQuicTransportTest : public RTCIceTransportTest {
RTCIceTransport* ice_transport,
const HeapVector<Member<RTCCertificate>>& certificates,
std::unique_ptr<MockP2PQuicTransportFactory> mock_factory);
+
+ // Construct a new RTCQuicTransport and RTCIceTransport and call start() on
+ // both objects.
+ RTCQuicTransport* CreateConnectedQuicTransport(
+ V8TestingScope& scope,
+ P2PQuicTransport::Delegate** delegate_out = nullptr);
+ RTCQuicTransport* CreateConnectedQuicTransport(
+ V8TestingScope& scope,
+ std::unique_ptr<MockP2PQuicTransport> mock_transport,
+ P2PQuicTransport::Delegate** delegate_out = nullptr);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_encoding_parameters.idl b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_encoding_parameters.idl
index 63b427d6dd1..eae7611b863 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_encoding_parameters.idl
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_encoding_parameters.idl
@@ -16,8 +16,9 @@ dictionary RTCRtpEncodingParameters : RTCRtpCodingParameters {
//TODO(orphis): Missing dtx. https://crbug.com/857044
boolean active = true;
RTCPriorityType priority = "low";
+ RTCPriorityType networkPriority = "low";
//TODO(orphis): Missing ptime. https://crbug.com/857046
unsigned long maxBitrate;
//TODO(orphis): Missing maxFramerate. https://crbug.com/857047
//TODO(orphis): Missing scaleResolutionDownBy. https://crbug.com/857048
-}; \ No newline at end of file
+};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.cc
index faa91366739..341b2320360 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.cc
@@ -8,8 +8,10 @@
#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/blink/public/platform/web_rtc_rtp_contributing_source.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_capabilities.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h"
#include "third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/webrtc/api/rtpparameters.h"
@@ -38,7 +40,8 @@ RTCRtpReceiver::getContributingSources() {
ScriptPromise RTCRtpReceiver::getStats(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- receiver_->GetStats(WebRTCStatsReportCallbackResolver::Create(resolver));
+ receiver_->GetStats(WebRTCStatsReportCallbackResolver::Create(resolver),
+ GetRTCStatsFilter(script_state));
return promise;
}
@@ -69,7 +72,8 @@ void RTCRtpReceiver::UpdateSourcesIfNeeded() {
DCHECK_EQ(web_contributing_source->SourceType(),
WebRTCRtpContributingSourceType::CSRC);
RTCRtpContributingSource* contributing_source =
- new RTCRtpContributingSource(this, *web_contributing_source);
+ MakeGarbageCollected<RTCRtpContributingSource>(
+ this, *web_contributing_source);
contributing_sources_.push_back(contributing_source);
}
// Clear the flag and schedule a microtask to reset it to true. This makes
@@ -94,27 +98,28 @@ void RTCRtpReceiver::Trace(blink::Visitor* visitor) {
ScriptWrappable::Trace(visitor);
}
-void RTCRtpReceiver::getCapabilities(
- const String& kind,
- base::Optional<RTCRtpCapabilities>& capabilities) {
+RTCRtpCapabilities* RTCRtpReceiver::getCapabilities(const String& kind) {
if (kind != "audio" && kind != "video")
- return;
+ return nullptr;
- capabilities = RTCRtpCapabilities{};
+ RTCRtpCapabilities* capabilities = RTCRtpCapabilities::Create();
+ capabilities->setCodecs(HeapVector<Member<RTCRtpCodecCapability>>());
+ capabilities->setHeaderExtensions(
+ HeapVector<Member<RTCRtpHeaderExtensionCapability>>());
std::unique_ptr<webrtc::RtpCapabilities> rtc_capabilities =
blink::Platform::Current()->GetRtpSenderCapabilities(kind);
- HeapVector<RTCRtpCodecCapability> codecs;
- codecs.ReserveInitialCapacity(rtc_capabilities->codecs.size());
+ HeapVector<Member<RTCRtpCodecCapability>> codecs;
+ codecs.ReserveInitialCapacity(
+ SafeCast<wtf_size_t>(rtc_capabilities->codecs.size()));
for (const auto& rtc_codec : rtc_capabilities->codecs) {
- codecs.emplace_back();
- auto& codec = codecs.back();
- codec.setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type().c_str()));
+ auto* codec = RTCRtpCodecCapability::Create();
+ codec->setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type().c_str()));
if (rtc_codec.clock_rate)
- codec.setClockRate(rtc_codec.clock_rate.value());
+ codec->setClockRate(rtc_codec.clock_rate.value());
if (rtc_codec.num_channels)
- codec.setChannels(rtc_codec.num_channels.value());
+ codec->setChannels(rtc_codec.num_channels.value());
if (rtc_codec.parameters.size()) {
std::string sdp_fmtp_line;
for (const auto& parameter : rtc_codec.parameters) {
@@ -122,21 +127,24 @@ void RTCRtpReceiver::getCapabilities(
sdp_fmtp_line += ";";
sdp_fmtp_line += parameter.first + "=" + parameter.second;
}
- codec.setSdpFmtpLine(sdp_fmtp_line.c_str());
+ codec->setSdpFmtpLine(sdp_fmtp_line.c_str());
}
+ codecs.push_back(codec);
}
capabilities->setCodecs(codecs);
- HeapVector<RTCRtpHeaderExtensionCapability> header_extensions;
+ HeapVector<Member<RTCRtpHeaderExtensionCapability>> header_extensions;
header_extensions.ReserveInitialCapacity(
- rtc_capabilities->header_extensions.size());
+ SafeCast<wtf_size_t>(rtc_capabilities->header_extensions.size()));
for (const auto& rtc_header_extension : rtc_capabilities->header_extensions) {
- header_extensions.emplace_back();
- auto& header_extension = header_extensions.back();
- header_extension.setUri(
+ auto* header_extension = RTCRtpHeaderExtensionCapability::Create();
+ header_extension->setUri(
WTF::String::FromUTF8(rtc_header_extension.uri.c_str()));
+ header_extensions.push_back(header_extension);
}
capabilities->setHeaderExtensions(header_extensions);
+
+ return capabilities;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h
index fcc57a5b042..5e560ec3139 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_receiver.h
@@ -30,8 +30,7 @@ class RTCRtpReceiver final : public ScriptWrappable {
MediaStreamTrack*,
MediaStreamVector);
- static void getCapabilities(const String& kind,
- base::Optional<RTCRtpCapabilities>& result);
+ static RTCRtpCapabilities* getCapabilities(const String& kind);
MediaStreamTrack* track() const;
const HeapVector<Member<RTCRtpContributingSource>>& getContributingSources();
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc
index 74d64280c36..d6977a5437c 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.cc
@@ -13,10 +13,12 @@
#include "third_party/blink/renderer/modules/peerconnection/rtc_error_util.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_capabilities.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h"
#include "third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.h"
#include "third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_void_request.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -84,83 +86,87 @@ class SetParametersRequest : public RTCVoidRequestScriptPromiseResolverImpl {
Member<RTCRtpSender> sender_;
};
-bool HasInvalidModification(const RTCRtpSendParameters& parameters,
- const RTCRtpSendParameters& new_parameters) {
- if (parameters.hasTransactionId() != new_parameters.hasTransactionId() ||
- (parameters.hasTransactionId() &&
- parameters.transactionId() != new_parameters.transactionId())) {
+bool HasInvalidModification(const RTCRtpSendParameters* parameters,
+ const RTCRtpSendParameters* new_parameters) {
+ if (parameters->hasTransactionId() != new_parameters->hasTransactionId() ||
+ (parameters->hasTransactionId() &&
+ parameters->transactionId() != new_parameters->transactionId())) {
return true;
}
- if (parameters.hasEncodings() != new_parameters.hasEncodings())
+ if (parameters->hasEncodings() != new_parameters->hasEncodings())
return true;
- if (parameters.hasEncodings()) {
- if (parameters.encodings().size() != new_parameters.encodings().size())
+ if (parameters->hasEncodings()) {
+ if (parameters->encodings().size() != new_parameters->encodings().size())
return true;
}
- if (parameters.hasHeaderExtensions() != new_parameters.hasHeaderExtensions())
+ if (parameters->hasHeaderExtensions() !=
+ new_parameters->hasHeaderExtensions())
return true;
- if (parameters.hasHeaderExtensions()) {
- if (parameters.headerExtensions().size() !=
- new_parameters.headerExtensions().size())
+ if (parameters->hasHeaderExtensions()) {
+ if (parameters->headerExtensions().size() !=
+ new_parameters->headerExtensions().size())
return true;
- for (size_t i = 0; i < parameters.headerExtensions().size(); ++i) {
- const auto& header_extension = parameters.headerExtensions()[i];
- const auto& new_header_extension = new_parameters.headerExtensions()[i];
- if (header_extension.hasUri() != new_header_extension.hasUri() ||
- (header_extension.hasUri() &&
- header_extension.uri() != new_header_extension.uri()) ||
- header_extension.hasId() != new_header_extension.hasId() ||
- (header_extension.hasId() &&
- header_extension.id() != new_header_extension.id()) ||
- header_extension.hasEncrypted() !=
- new_header_extension.hasEncrypted() ||
- (header_extension.hasEncrypted() &&
- header_extension.encrypted() != new_header_extension.encrypted())) {
+ for (wtf_size_t i = 0; i < parameters->headerExtensions().size(); ++i) {
+ const auto& header_extension = parameters->headerExtensions()[i];
+ const auto& new_header_extension = new_parameters->headerExtensions()[i];
+ if (header_extension->hasUri() != new_header_extension->hasUri() ||
+ (header_extension->hasUri() &&
+ header_extension->uri() != new_header_extension->uri()) ||
+ header_extension->hasId() != new_header_extension->hasId() ||
+ (header_extension->hasId() &&
+ header_extension->id() != new_header_extension->id()) ||
+ header_extension->hasEncrypted() !=
+ new_header_extension->hasEncrypted() ||
+ (header_extension->hasEncrypted() &&
+ header_extension->encrypted() !=
+ new_header_extension->encrypted())) {
return true;
}
}
}
- if (parameters.hasRtcp() != new_parameters.hasRtcp() ||
- (parameters.hasRtcp() &&
- ((parameters.rtcp().hasCname() != new_parameters.rtcp().hasCname() ||
- (parameters.rtcp().hasCname() &&
- parameters.rtcp().cname() != new_parameters.rtcp().cname())) ||
- (parameters.rtcp().hasReducedSize() !=
- new_parameters.rtcp().hasReducedSize() ||
- (parameters.rtcp().hasReducedSize() &&
- parameters.rtcp().reducedSize() !=
- new_parameters.rtcp().reducedSize()))))) {
+ if (parameters->hasRtcp() != new_parameters->hasRtcp() ||
+ (parameters->hasRtcp() &&
+ ((parameters->rtcp()->hasCname() != new_parameters->rtcp()->hasCname() ||
+ (parameters->rtcp()->hasCname() &&
+ parameters->rtcp()->cname() != new_parameters->rtcp()->cname())) ||
+ (parameters->rtcp()->hasReducedSize() !=
+ new_parameters->rtcp()->hasReducedSize() ||
+ (parameters->rtcp()->hasReducedSize() &&
+ parameters->rtcp()->reducedSize() !=
+ new_parameters->rtcp()->reducedSize()))))) {
return true;
}
- if (parameters.hasCodecs() != new_parameters.hasCodecs())
+ if (parameters->hasCodecs() != new_parameters->hasCodecs())
return true;
- if (parameters.hasCodecs()) {
- if (parameters.codecs().size() != new_parameters.codecs().size())
+ if (parameters->hasCodecs()) {
+ if (parameters->codecs().size() != new_parameters->codecs().size())
return true;
- for (std::size_t i = 0; i < parameters.codecs().size(); ++i) {
- const auto& codec = parameters.codecs()[i];
- const auto& new_codec = new_parameters.codecs()[i];
- if (codec.hasPayloadType() != new_codec.hasPayloadType() ||
- (codec.hasPayloadType() &&
- codec.payloadType() != new_codec.payloadType()) ||
- codec.hasMimeType() != new_codec.hasMimeType() ||
- (codec.hasMimeType() && codec.mimeType() != new_codec.mimeType()) ||
- codec.hasClockRate() != new_codec.hasClockRate() ||
- (codec.hasClockRate() &&
- codec.clockRate() != new_codec.clockRate()) ||
- codec.hasChannels() != new_codec.hasChannels() ||
- (codec.hasChannels() && codec.channels() != new_codec.channels()) ||
- codec.hasSdpFmtpLine() != new_codec.hasSdpFmtpLine() ||
- (codec.hasSdpFmtpLine() &&
- codec.sdpFmtpLine() != new_codec.sdpFmtpLine())) {
+ for (wtf_size_t i = 0; i < parameters->codecs().size(); ++i) {
+ const auto& codec = parameters->codecs()[i];
+ const auto& new_codec = new_parameters->codecs()[i];
+ if (codec->hasPayloadType() != new_codec->hasPayloadType() ||
+ (codec->hasPayloadType() &&
+ codec->payloadType() != new_codec->payloadType()) ||
+ codec->hasMimeType() != new_codec->hasMimeType() ||
+ (codec->hasMimeType() &&
+ codec->mimeType() != new_codec->mimeType()) ||
+ codec->hasClockRate() != new_codec->hasClockRate() ||
+ (codec->hasClockRate() &&
+ codec->clockRate() != new_codec->clockRate()) ||
+ codec->hasChannels() != new_codec->hasChannels() ||
+ (codec->hasChannels() &&
+ codec->channels() != new_codec->channels()) ||
+ codec->hasSdpFmtpLine() != new_codec->hasSdpFmtpLine() ||
+ (codec->hasSdpFmtpLine() &&
+ codec->sdpFmtpLine() != new_codec->sdpFmtpLine())) {
return true;
}
}
@@ -217,12 +223,12 @@ double PriorityToDouble(const WTF::String& priority) {
std::tuple<std::vector<webrtc::RtpEncodingParameters>,
webrtc::DegradationPreference>
-ToRtpParameters(const RTCRtpSendParameters& parameters) {
+ToRtpParameters(const RTCRtpSendParameters* parameters) {
std::vector<webrtc::RtpEncodingParameters> encodings;
- if (parameters.hasEncodings()) {
- encodings.reserve(parameters.encodings().size());
+ if (parameters->hasEncodings()) {
+ encodings.reserve(parameters->encodings().size());
- for (const auto& encoding : parameters.encodings()) {
+ for (const auto& encoding : parameters->encodings()) {
encodings.push_back(ToRtpEncodingParameters(encoding));
}
}
@@ -235,15 +241,17 @@ ToRtpParameters(const RTCRtpSendParameters& parameters) {
} // namespace
webrtc::RtpEncodingParameters ToRtpEncodingParameters(
- const RTCRtpEncodingParameters& encoding) {
+ const RTCRtpEncodingParameters* encoding) {
// TODO(orphis): Forward missing fields from the WebRTC library:
// codecPayloadType, dtx, ptime, maxFramerate, scaleResolutionDownBy,
// rid
webrtc::RtpEncodingParameters webrtc_encoding;
- webrtc_encoding.active = encoding.active();
- webrtc_encoding.bitrate_priority = PriorityToDouble(encoding.priority());
- if (encoding.hasMaxBitrate())
- webrtc_encoding.max_bitrate_bps = clampTo<int>(encoding.maxBitrate());
+ webrtc_encoding.active = encoding->active();
+ webrtc_encoding.bitrate_priority = PriorityToDouble(encoding->priority());
+ webrtc_encoding.network_priority =
+ PriorityToDouble(encoding->networkPriority());
+ if (encoding->hasMaxBitrate())
+ webrtc_encoding.max_bitrate_bps = clampTo<int>(encoding->maxBitrate());
return webrtc_encoding;
}
@@ -286,56 +294,61 @@ ScriptPromise RTCRtpSender::replaceTrack(ScriptState* script_state,
return promise;
}
-void RTCRtpSender::getParameters(RTCRtpSendParameters& parameters) {
+RTCRtpSendParameters* RTCRtpSender::getParameters() {
+ RTCRtpSendParameters* parameters = RTCRtpSendParameters::Create();
// TODO(orphis): Forward missing fields from the WebRTC library:
// degradationPreference
std::unique_ptr<webrtc::RtpParameters> webrtc_parameters =
sender_->GetParameters();
- parameters.setTransactionId(webrtc_parameters->transaction_id.c_str());
+ parameters->setTransactionId(webrtc_parameters->transaction_id.c_str());
- RTCRtcpParameters rtcp;
- rtcp.setCname(webrtc_parameters->rtcp.cname.c_str());
- rtcp.setReducedSize(webrtc_parameters->rtcp.reduced_size);
- parameters.setRtcp(rtcp);
+ RTCRtcpParameters* rtcp = RTCRtcpParameters::Create();
+ rtcp->setCname(webrtc_parameters->rtcp.cname.c_str());
+ rtcp->setReducedSize(webrtc_parameters->rtcp.reduced_size);
+ parameters->setRtcp(rtcp);
- HeapVector<RTCRtpEncodingParameters> encodings;
- encodings.ReserveCapacity(webrtc_parameters->encodings.size());
+ HeapVector<Member<RTCRtpEncodingParameters>> encodings;
+ encodings.ReserveCapacity(
+ SafeCast<wtf_size_t>(webrtc_parameters->encodings.size()));
for (const auto& web_encoding : webrtc_parameters->encodings) {
// TODO(orphis): Forward missing fields from the WebRTC library:
// codecPayloadType, dtx, ptime, maxFramerate, scaleResolutionDownBy, rid
- encodings.emplace_back();
- RTCRtpEncodingParameters& encoding = encodings.back();
- encoding.setActive(web_encoding.active);
+ RTCRtpEncodingParameters* encoding = RTCRtpEncodingParameters::Create();
+ encoding->setActive(web_encoding.active);
if (web_encoding.max_bitrate_bps)
- encoding.setMaxBitrate(web_encoding.max_bitrate_bps.value());
- encoding.setPriority(
+ encoding->setMaxBitrate(web_encoding.max_bitrate_bps.value());
+ encoding->setPriority(
PriorityFromDouble(web_encoding.bitrate_priority).c_str());
+ encoding->setNetworkPriority(
+ PriorityFromDouble(web_encoding.network_priority).c_str());
+ encodings.push_back(encoding);
}
- parameters.setEncodings(encodings);
+ parameters->setEncodings(encodings);
- HeapVector<RTCRtpHeaderExtensionParameters> headers;
- headers.ReserveCapacity(webrtc_parameters->header_extensions.size());
+ HeapVector<Member<RTCRtpHeaderExtensionParameters>> headers;
+ headers.ReserveCapacity(
+ SafeCast<wtf_size_t>(webrtc_parameters->header_extensions.size()));
for (const auto& web_header : webrtc_parameters->header_extensions) {
- headers.emplace_back();
- RTCRtpHeaderExtensionParameters& header = headers.back();
- header.setUri(web_header.uri.c_str());
- header.setId(web_header.id);
- header.setEncrypted(web_header.encrypt);
+ auto* header = RTCRtpHeaderExtensionParameters::Create();
+ header->setUri(web_header.uri.c_str());
+ header->setId(web_header.id);
+ header->setEncrypted(web_header.encrypt);
+ headers.push_back(header);
}
- parameters.setHeaderExtensions(headers);
+ parameters->setHeaderExtensions(headers);
- HeapVector<RTCRtpCodecParameters> codecs;
- codecs.ReserveCapacity(webrtc_parameters->codecs.size());
+ HeapVector<Member<RTCRtpCodecParameters>> codecs;
+ codecs.ReserveCapacity(
+ SafeCast<wtf_size_t>(webrtc_parameters->codecs.size()));
for (const auto& web_codec : webrtc_parameters->codecs) {
- codecs.emplace_back();
- RTCRtpCodecParameters& codec = codecs.back();
- codec.setPayloadType(web_codec.payload_type);
- codec.setMimeType(WTF::String::FromUTF8(web_codec.mime_type().c_str()));
+ auto* codec = RTCRtpCodecParameters::Create();
+ codec->setPayloadType(web_codec.payload_type);
+ codec->setMimeType(WTF::String::FromUTF8(web_codec.mime_type().c_str()));
if (web_codec.clock_rate)
- codec.setClockRate(web_codec.clock_rate.value());
+ codec->setClockRate(web_codec.clock_rate.value());
if (web_codec.num_channels)
- codec.setChannels(web_codec.num_channels.value());
+ codec->setChannels(web_codec.num_channels.value());
if (web_codec.parameters.size()) {
std::string sdp_fmtp_line;
for (const auto& parameter : web_codec.parameters) {
@@ -343,17 +356,20 @@ void RTCRtpSender::getParameters(RTCRtpSendParameters& parameters) {
sdp_fmtp_line += ";";
sdp_fmtp_line += parameter.first + "=" + parameter.second;
}
- codec.setSdpFmtpLine(sdp_fmtp_line.c_str());
+ codec->setSdpFmtpLine(sdp_fmtp_line.c_str());
}
+ codecs.push_back(codec);
}
- parameters.setCodecs(codecs);
+ parameters->setCodecs(codecs);
last_returned_parameters_ = parameters;
+
+ return parameters;
}
ScriptPromise RTCRtpSender::setParameters(
ScriptState* script_state,
- const RTCRtpSendParameters& parameters) {
+ const RTCRtpSendParameters* parameters) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -368,7 +384,7 @@ ScriptPromise RTCRtpSender::setParameters(
// there is no perfect 1-1 mapping between the Javascript layer and native.
// So we save the last returned dictionary and enforce the check at this
// level instead.
- if (HasInvalidModification(last_returned_parameters_.value(), parameters)) {
+ if (HasInvalidModification(last_returned_parameters_, parameters)) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kInvalidModificationError,
"Read-only field modified in setParameters()."));
@@ -389,13 +405,14 @@ ScriptPromise RTCRtpSender::setParameters(
}
void RTCRtpSender::ClearLastReturnedParameters() {
- last_returned_parameters_.reset();
+ last_returned_parameters_ = nullptr;
}
ScriptPromise RTCRtpSender::getStats(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- sender_->GetStats(WebRTCStatsReportCallbackResolver::Create(resolver));
+ sender_->GetStats(WebRTCStatsReportCallbackResolver::Create(resolver),
+ GetRTCStatsFilter(script_state));
return promise;
}
@@ -447,27 +464,28 @@ void RTCRtpSender::Trace(blink::Visitor* visitor) {
ScriptWrappable::Trace(visitor);
}
-void RTCRtpSender::getCapabilities(
- const String& kind,
- base::Optional<RTCRtpCapabilities>& capabilities) {
+RTCRtpCapabilities* RTCRtpSender::getCapabilities(const String& kind) {
if (kind != "audio" && kind != "video")
- return;
+ return nullptr;
- capabilities = RTCRtpCapabilities{};
+ RTCRtpCapabilities* capabilities = RTCRtpCapabilities::Create();
+ capabilities->setCodecs(HeapVector<Member<RTCRtpCodecCapability>>());
+ capabilities->setHeaderExtensions(
+ HeapVector<Member<RTCRtpHeaderExtensionCapability>>());
std::unique_ptr<webrtc::RtpCapabilities> rtc_capabilities =
blink::Platform::Current()->GetRtpSenderCapabilities(kind);
- HeapVector<RTCRtpCodecCapability> codecs;
- codecs.ReserveInitialCapacity(rtc_capabilities->codecs.size());
+ HeapVector<Member<RTCRtpCodecCapability>> codecs;
+ codecs.ReserveInitialCapacity(
+ SafeCast<wtf_size_t>(rtc_capabilities->codecs.size()));
for (const auto& rtc_codec : rtc_capabilities->codecs) {
- codecs.emplace_back();
- auto& codec = codecs.back();
- codec.setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type().c_str()));
+ auto* codec = RTCRtpCodecCapability::Create();
+ codec->setMimeType(WTF::String::FromUTF8(rtc_codec.mime_type().c_str()));
if (rtc_codec.clock_rate)
- codec.setClockRate(rtc_codec.clock_rate.value());
+ codec->setClockRate(rtc_codec.clock_rate.value());
if (rtc_codec.num_channels)
- codec.setChannels(rtc_codec.num_channels.value());
+ codec->setChannels(rtc_codec.num_channels.value());
if (rtc_codec.parameters.size()) {
std::string sdp_fmtp_line;
for (const auto& parameter : rtc_codec.parameters) {
@@ -475,21 +493,24 @@ void RTCRtpSender::getCapabilities(
sdp_fmtp_line += ";";
sdp_fmtp_line += parameter.first + "=" + parameter.second;
}
- codec.setSdpFmtpLine(sdp_fmtp_line.c_str());
+ codec->setSdpFmtpLine(sdp_fmtp_line.c_str());
}
+ codecs.push_back(codec);
}
capabilities->setCodecs(codecs);
- HeapVector<RTCRtpHeaderExtensionCapability> header_extensions;
+ HeapVector<Member<RTCRtpHeaderExtensionCapability>> header_extensions;
header_extensions.ReserveInitialCapacity(
- rtc_capabilities->header_extensions.size());
+ SafeCast<wtf_size_t>(rtc_capabilities->header_extensions.size()));
for (const auto& rtc_header_extension : rtc_capabilities->header_extensions) {
- header_extensions.emplace_back();
- auto& header_extension = header_extensions.back();
- header_extension.setUri(
+ auto* header_extension = RTCRtpHeaderExtensionCapability::Create();
+ header_extension->setUri(
WTF::String::FromUTF8(rtc_header_extension.uri.c_str()));
+ header_extensions.push_back(header_extension);
}
capabilities->setHeaderExtensions(header_extensions);
+
+ return capabilities;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h
index 6803a213b32..c35d6ff39bc 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h
@@ -25,7 +25,7 @@ class RTCPeerConnection;
class RTCRtpCapabilities;
webrtc::RtpEncodingParameters ToRtpEncodingParameters(
- const RTCRtpEncodingParameters&);
+ const RTCRtpEncodingParameters*);
// https://w3c.github.io/webrtc-pc/#rtcrtpsender-interface
class RTCRtpSender final : public ScriptWrappable {
@@ -43,10 +43,9 @@ class RTCRtpSender final : public ScriptWrappable {
MediaStreamTrack* track();
ScriptPromise replaceTrack(ScriptState*, MediaStreamTrack*);
RTCDTMFSender* dtmf();
- static void getCapabilities(const String& kind,
- base::Optional<RTCRtpCapabilities>& result);
- void getParameters(RTCRtpSendParameters&);
- ScriptPromise setParameters(ScriptState*, const RTCRtpSendParameters&);
+ static RTCRtpCapabilities* getCapabilities(const String& kind);
+ RTCRtpSendParameters* getParameters();
+ ScriptPromise setParameters(ScriptState*, const RTCRtpSendParameters*);
ScriptPromise getStats(ScriptState*);
WebRTCRtpSender* web_sender();
@@ -68,7 +67,7 @@ class RTCRtpSender final : public ScriptWrappable {
Member<MediaStreamTrack> track_;
Member<RTCDTMFSender> dtmf_;
MediaStreamVector streams_;
- base::Optional<RTCRtpSendParameters> last_returned_parameters_;
+ Member<RTCRtpSendParameters> last_returned_parameters_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc
index 91e6757baf6..887f3cb0496 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.cc
@@ -66,20 +66,20 @@ bool TransceiverDirectionFromString(
} // namespace
webrtc::RtpTransceiverInit ToRtpTransceiverInit(
- const RTCRtpTransceiverInit& init) {
+ const RTCRtpTransceiverInit* init) {
webrtc::RtpTransceiverInit webrtc_init;
base::Optional<webrtc::RtpTransceiverDirection> direction;
- if (init.hasDirection() &&
- TransceiverDirectionFromString(init.direction(), &direction) &&
+ if (init->hasDirection() &&
+ TransceiverDirectionFromString(init->direction(), &direction) &&
direction) {
webrtc_init.direction = *direction;
}
- DCHECK(init.hasStreams());
- for (const auto& stream : init.streams()) {
+ DCHECK(init->hasStreams());
+ for (const auto& stream : init->streams()) {
webrtc_init.stream_ids.push_back(stream->id().Utf8().data());
}
- DCHECK(init.hasSendEncodings());
- for (const auto& encoding : init.sendEncodings()) {
+ DCHECK(init->hasSendEncodings());
+ for (const auto& encoding : init->sendEncodings()) {
webrtc_init.send_encodings.push_back(ToRtpEncodingParameters(encoding));
}
return webrtc_init;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h
index c123616bcd8..117771105de 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h
@@ -22,7 +22,7 @@ class RTCPeerConnection;
class RTCRtpReceiver;
class RTCRtpSender;
-webrtc::RtpTransceiverInit ToRtpTransceiverInit(const RTCRtpTransceiverInit&);
+webrtc::RtpTransceiverInit ToRtpTransceiverInit(const RTCRtpTransceiverInit*);
class RTCRtpTransceiver final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.cc
index 545d2ea1eac..ec940e153d7 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.cc
@@ -40,25 +40,26 @@ namespace blink {
RTCSessionDescription* RTCSessionDescription::Create(
ExecutionContext* context,
- const RTCSessionDescriptionInit& description_init_dict) {
+ const RTCSessionDescriptionInit* description_init_dict) {
String type;
- if (description_init_dict.hasType())
- type = description_init_dict.type();
+ if (description_init_dict->hasType())
+ type = description_init_dict->type();
else
UseCounter::Count(context, WebFeature::kRTCSessionDescriptionInitNoType);
String sdp;
- if (description_init_dict.hasSdp())
- sdp = description_init_dict.sdp();
+ if (description_init_dict->hasSdp())
+ sdp = description_init_dict->sdp();
else
UseCounter::Count(context, WebFeature::kRTCSessionDescriptionInitNoSdp);
- return new RTCSessionDescription(WebRTCSessionDescription(type, sdp));
+ return MakeGarbageCollected<RTCSessionDescription>(
+ WebRTCSessionDescription(type, sdp));
}
RTCSessionDescription* RTCSessionDescription::Create(
WebRTCSessionDescription web_session_description) {
- return new RTCSessionDescription(web_session_description);
+ return MakeGarbageCollected<RTCSessionDescription>(web_session_description);
}
RTCSessionDescription::RTCSessionDescription(
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.h
index eeef67dcb99..6e89b71d1cb 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description.h
@@ -47,9 +47,11 @@ class RTCSessionDescription final : public ScriptWrappable {
public:
static RTCSessionDescription* Create(ExecutionContext*,
- const RTCSessionDescriptionInit&);
+ const RTCSessionDescriptionInit*);
static RTCSessionDescription* Create(WebRTCSessionDescription);
+ explicit RTCSessionDescription(WebRTCSessionDescription);
+
String type() const;
void setType(const String&);
@@ -61,8 +63,6 @@ class RTCSessionDescription final : public ScriptWrappable {
WebRTCSessionDescription WebSessionDescription();
private:
- explicit RTCSessionDescription(WebRTCSessionDescription);
-
WebRTCSessionDescription web_session_description_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h
new file mode 100644
index 00000000000..867e4e40e45
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h
@@ -0,0 +1,32 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SESSION_DESCRIPTION_ENUMS_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SESSION_DESCRIPTION_ENUMS_H_
+
+namespace blink {
+
+// RTCPeerConnection methods that are used to create session descriptions (SDP).
+// See RTCPeerConnection::createOffer() and RTCPeerConnection::createAnswer().
+enum class RTCCreateSessionDescriptionOperation {
+ kCreateOffer,
+ kCreateAnswer,
+};
+
+// RTCPeerConnection operations that are used to set session descriptions (SDP).
+// See methods RTCPeerConnection::setLocalDescription() and
+// RTCPeerConnection::setRemoteDescription() - the SDP parameter can have the
+// type "offer" or "answer".
+enum class RTCSetSessionDescriptionOperation {
+ kSetLocalDescriptionOffer,
+ kSetLocalDescriptionAnswer,
+ kSetLocalDescriptionInvalidType,
+ kSetRemoteDescriptionOffer,
+ kSetRemoteDescriptionAnswer,
+ kSetRemoteDescriptionInvalidType,
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SESSION_DESCRIPTION_ENUMS_H_
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.cc
index 3f7ecf0dc77..e056b928ee2 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.cc
@@ -41,19 +41,22 @@ namespace blink {
RTCSessionDescriptionRequestImpl* RTCSessionDescriptionRequestImpl::Create(
ExecutionContext* context,
+ RTCCreateSessionDescriptionOperation operation,
RTCPeerConnection* requester,
V8RTCSessionDescriptionCallback* success_callback,
V8RTCPeerConnectionErrorCallback* error_callback) {
- return new RTCSessionDescriptionRequestImpl(context, requester,
- success_callback, error_callback);
+ return MakeGarbageCollected<RTCSessionDescriptionRequestImpl>(
+ context, operation, requester, success_callback, error_callback);
}
RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(
ExecutionContext* context,
+ RTCCreateSessionDescriptionOperation operation,
RTCPeerConnection* requester,
V8RTCSessionDescriptionCallback* success_callback,
V8RTCPeerConnectionErrorCallback* error_callback)
: ContextLifecycleObserver(context),
+ operation_(operation),
success_callback_(ToV8PersistentCallbackFunction(success_callback)),
error_callback_(ToV8PersistentCallbackFunction(error_callback)),
requester_(requester) {
@@ -67,6 +70,7 @@ void RTCSessionDescriptionRequestImpl::RequestSucceeded(
bool should_fire_callback =
requester_ ? requester_->ShouldFireDefaultCallbacks() : false;
if (should_fire_callback && success_callback_) {
+ requester_->NoteSessionDescriptionRequestCompleted(operation_, true);
auto* description = RTCSessionDescription::Create(web_session_description);
requester_->NoteSdpCreated(*description);
success_callback_->InvokeAndReportException(nullptr, description);
@@ -79,6 +83,7 @@ void RTCSessionDescriptionRequestImpl::RequestFailed(
bool should_fire_callback =
requester_ ? requester_->ShouldFireDefaultCallbacks() : false;
if (should_fire_callback && error_callback_) {
+ requester_->NoteSessionDescriptionRequestCompleted(operation_, false);
error_callback_->InvokeAndReportException(
nullptr, CreateDOMExceptionFromRTCError(error));
}
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.h
index 9baf491a636..142915a0884 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.h
@@ -35,6 +35,7 @@
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_peer_connection_error_callback.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_session_description_callback.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_session_description_request.h"
@@ -43,6 +44,9 @@ namespace blink {
class RTCPeerConnection;
class WebRTCSessionDescription;
+// TODO(https://crbug.com/908468): Split up the operation-specific codepaths
+// into separate request implementations and find a way to consolidate the
+// shared code as to not repeat the majority of the implementations.
class RTCSessionDescriptionRequestImpl final
: public RTCSessionDescriptionRequest,
public ContextLifecycleObserver {
@@ -51,9 +55,16 @@ class RTCSessionDescriptionRequestImpl final
public:
static RTCSessionDescriptionRequestImpl* Create(
ExecutionContext*,
+ RTCCreateSessionDescriptionOperation,
RTCPeerConnection*,
V8RTCSessionDescriptionCallback*,
V8RTCPeerConnectionErrorCallback*);
+
+ RTCSessionDescriptionRequestImpl(ExecutionContext*,
+ RTCCreateSessionDescriptionOperation,
+ RTCPeerConnection*,
+ V8RTCSessionDescriptionCallback*,
+ V8RTCPeerConnectionErrorCallback*);
~RTCSessionDescriptionRequestImpl() override;
void RequestSucceeded(const WebRTCSessionDescription&) override;
@@ -65,13 +76,9 @@ class RTCSessionDescriptionRequestImpl final
void Trace(blink::Visitor*) override;
private:
- RTCSessionDescriptionRequestImpl(ExecutionContext*,
- RTCPeerConnection*,
- V8RTCSessionDescriptionCallback*,
- V8RTCPeerConnectionErrorCallback*);
-
void Clear();
+ RTCCreateSessionDescriptionOperation operation_;
// This request object is held by WebRTCPeerConnectionHandler, which doesn't
// support wrapper-tracing. Thus, this object holds the underlying callback
// functions as persistent handles. This is acceptable because the request
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.cc
index c3fc0f392ea..fd2bded9de7 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.cc
@@ -14,20 +14,25 @@
namespace blink {
RTCSessionDescriptionRequestPromiseImpl*
-RTCSessionDescriptionRequestPromiseImpl::Create(RTCPeerConnection* requester,
- ScriptPromiseResolver* resolver,
- const char* interface_name,
- const char* property_name) {
- return new RTCSessionDescriptionRequestPromiseImpl(
- requester, resolver, interface_name, property_name);
+RTCSessionDescriptionRequestPromiseImpl::Create(
+ RTCCreateSessionDescriptionOperation operation,
+ RTCPeerConnection* requester,
+ ScriptPromiseResolver* resolver,
+ const char* interface_name,
+ const char* property_name) {
+ return MakeGarbageCollected<RTCSessionDescriptionRequestPromiseImpl>(
+ operation, requester, resolver, interface_name, property_name);
}
RTCSessionDescriptionRequestPromiseImpl::
- RTCSessionDescriptionRequestPromiseImpl(RTCPeerConnection* requester,
- ScriptPromiseResolver* resolver,
- const char* interface_name,
- const char* property_name)
- : requester_(requester),
+ RTCSessionDescriptionRequestPromiseImpl(
+ RTCCreateSessionDescriptionOperation operation,
+ RTCPeerConnection* requester,
+ ScriptPromiseResolver* resolver,
+ const char* interface_name,
+ const char* property_name)
+ : operation_(operation),
+ requester_(requester),
resolver_(resolver),
interface_name_(interface_name),
property_name_(property_name) {
@@ -41,6 +46,7 @@ RTCSessionDescriptionRequestPromiseImpl::
void RTCSessionDescriptionRequestPromiseImpl::RequestSucceeded(
const WebRTCSessionDescription& web_session_description) {
if (requester_ && requester_->ShouldFireDefaultCallbacks()) {
+ requester_->NoteSessionDescriptionRequestCompleted(operation_, true);
auto* description = RTCSessionDescription::Create(web_session_description);
requester_->NoteSdpCreated(*description);
resolver_->Resolve(description);
@@ -56,6 +62,7 @@ void RTCSessionDescriptionRequestPromiseImpl::RequestSucceeded(
void RTCSessionDescriptionRequestPromiseImpl::RequestFailed(
const webrtc::RTCError& error) {
if (requester_ && requester_->ShouldFireDefaultCallbacks()) {
+ requester_->NoteSessionDescriptionRequestCompleted(operation_, false);
ScriptState::Scope scope(resolver_->GetScriptState());
ExceptionState exception_state(resolver_->GetScriptState()->GetIsolate(),
ExceptionState::kExecutionContext,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.h
index 55583fd8c47..00eb8f4559f 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_promise_impl.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SESSION_DESCRIPTION_REQUEST_PROMISE_IMPL_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SESSION_DESCRIPTION_REQUEST_PROMISE_IMPL_H_
+#include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_session_description_request.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -14,14 +15,24 @@ class RTCPeerConnection;
class ScriptPromiseResolver;
class WebRTCSessionDescription;
+// TODO(https://crbug.com/908468): Split up the operation-specific codepaths
+// into separate request implementations and find a way to consolidate the
+// shared code as to not repeat the majority of the implementations.
class RTCSessionDescriptionRequestPromiseImpl final
: public RTCSessionDescriptionRequest {
public:
static RTCSessionDescriptionRequestPromiseImpl* Create(
+ RTCCreateSessionDescriptionOperation,
RTCPeerConnection*,
ScriptPromiseResolver*,
const char* interface_name,
const char* property_name);
+
+ RTCSessionDescriptionRequestPromiseImpl(RTCCreateSessionDescriptionOperation,
+ RTCPeerConnection*,
+ ScriptPromiseResolver*,
+ const char* interface_name,
+ const char* property_name);
~RTCSessionDescriptionRequestPromiseImpl() override;
// RTCSessionDescriptionRequest
@@ -31,13 +42,9 @@ class RTCSessionDescriptionRequestPromiseImpl final
void Trace(blink::Visitor*) override;
private:
- RTCSessionDescriptionRequestPromiseImpl(RTCPeerConnection*,
- ScriptPromiseResolver*,
- const char* interface_name,
- const char* property_name);
-
void Clear();
+ RTCCreateSessionDescriptionOperation operation_;
Member<RTCPeerConnection> requester_;
Member<ScriptPromiseResolver> resolver_;
const char* interface_name_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.cc
index 14d10643487..7f73c9b6d54 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.cc
@@ -3,154 +3,92 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h"
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
namespace {
-template <typename T>
-bool AddPropertyValue(v8::Local<v8::Object>& v8_object,
- v8::Isolate* isolate,
- T name,
- v8::Local<v8::Value> value) {
- return V8CallBoolean(v8_object->CreateDataProperty(
- isolate->GetCurrentContext(), V8String(isolate, name), value));
-}
+v8::Local<v8::Value> WebRTCStatsToValue(ScriptState* script_state,
+ const WebRTCStats* stats) {
+ V8ObjectBuilder builder(script_state);
-bool AddPropertySequenceOfBooleans(v8::Local<v8::Object>& v8_object,
- v8::Isolate* isolate,
- WebString name,
- const WebVector<int>& web_vector) {
- v8::Local<v8::Array> v8_array = v8::Array::New(isolate, web_vector.size());
- for (size_t i = 0; i < web_vector.size(); ++i) {
- if (!V8CallBoolean(v8_array->CreateDataProperty(
- isolate->GetCurrentContext(), static_cast<uint32_t>(i),
- v8::Boolean::New(isolate, static_cast<bool>(web_vector[i])))))
- return false;
- }
- return AddPropertyValue(v8_object, isolate, name, v8_array);
-}
+ builder.AddString("id", stats->Id());
+ builder.AddNumber("timestamp", stats->Timestamp());
+ builder.AddString("type", stats->GetType());
-template <typename T>
-bool AddPropertySequenceOfNumbers(v8::Local<v8::Object>& v8_object,
- v8::Isolate* isolate,
- WebString name,
- const WebVector<T>& web_vector) {
- v8::Local<v8::Array> v8_array = v8::Array::New(isolate, web_vector.size());
- for (size_t i = 0; i < web_vector.size(); ++i) {
- if (!V8CallBoolean(v8_array->CreateDataProperty(
- isolate->GetCurrentContext(), static_cast<uint32_t>(i),
- v8::Number::New(isolate, static_cast<double>(web_vector[i])))))
- return false;
- }
- return AddPropertyValue(v8_object, isolate, name, v8_array);
-}
+ auto add_vector = [&builder](const WebString& name, auto web_vector) {
+ Vector<typename decltype(web_vector)::value_type> vector(
+ SafeCast<wtf_size_t>(web_vector.size()));
+ std::move(web_vector.begin(), web_vector.end(), vector.begin());
+ builder.Add(name, vector);
+ };
-bool AddPropertySequenceOfStrings(v8::Local<v8::Object>& v8_object,
- v8::Isolate* isolate,
- WebString name,
- const WebVector<WebString>& web_vector) {
- v8::Local<v8::Array> v8_array = v8::Array::New(isolate, web_vector.size());
- for (size_t i = 0; i < web_vector.size(); ++i) {
- if (!V8CallBoolean(v8_array->CreateDataProperty(
- isolate->GetCurrentContext(), static_cast<uint32_t>(i),
- V8String(isolate, web_vector[i]))))
- return false;
- }
- return AddPropertyValue(v8_object, isolate, name, v8_array);
-}
-
-v8::Local<v8::Value> WebRTCStatsToValue(ScriptState* script_state,
- const WebRTCStats* stats) {
- v8::Isolate* isolate = script_state->GetIsolate();
- v8::Local<v8::Object> v8_object = v8::Object::New(isolate);
-
- bool success = true;
- success &= AddPropertyValue(v8_object, isolate, "id",
- V8String(isolate, stats->Id()));
- success &= AddPropertyValue(v8_object, isolate, "timestamp",
- v8::Number::New(isolate, stats->Timestamp()));
- success &= AddPropertyValue(v8_object, isolate, "type",
- V8String(isolate, stats->GetType()));
- for (size_t i = 0; i < stats->MembersCount() && success; ++i) {
+ for (size_t i = 0; i < stats->MembersCount(); ++i) {
std::unique_ptr<WebRTCStatsMember> member = stats->GetMember(i);
if (!member->IsDefined())
continue;
WebString name = member->GetName();
switch (member->GetType()) {
case kWebRTCStatsMemberTypeBool:
- success &=
- AddPropertyValue(v8_object, isolate, name,
- v8::Boolean::New(isolate, member->ValueBool()));
+ builder.AddBoolean(name, member->ValueBool());
break;
case kWebRTCStatsMemberTypeInt32:
- success &= AddPropertyValue(
- v8_object, isolate, name,
- v8::Number::New(isolate,
- static_cast<double>(member->ValueInt32())));
+ builder.AddNumber(name, static_cast<double>(member->ValueInt32()));
break;
case kWebRTCStatsMemberTypeUint32:
- success &= AddPropertyValue(
- v8_object, isolate, name,
- v8::Number::New(isolate,
- static_cast<double>(member->ValueUint32())));
+ builder.AddNumber(name, static_cast<double>(member->ValueUint32()));
break;
case kWebRTCStatsMemberTypeInt64:
- success &= AddPropertyValue(
- v8_object, isolate, name,
- v8::Number::New(isolate,
- static_cast<double>(member->ValueInt64())));
+ builder.AddNumber(name, static_cast<double>(member->ValueInt64()));
break;
case kWebRTCStatsMemberTypeUint64:
- success &= AddPropertyValue(
- v8_object, isolate, name,
- v8::Number::New(isolate,
- static_cast<double>(member->ValueUint64())));
+ builder.AddNumber(name, static_cast<double>(member->ValueUint64()));
break;
case kWebRTCStatsMemberTypeDouble:
- success &=
- AddPropertyValue(v8_object, isolate, name,
- v8::Number::New(isolate, member->ValueDouble()));
+ builder.AddNumber(name, member->ValueDouble());
break;
case kWebRTCStatsMemberTypeString:
- success &= AddPropertyValue(v8_object, isolate, name,
- V8String(isolate, member->ValueString()));
+ builder.AddString(name, member->ValueString());
break;
- case kWebRTCStatsMemberTypeSequenceBool:
- success &= AddPropertySequenceOfBooleans(v8_object, isolate, name,
- member->ValueSequenceBool());
+ case kWebRTCStatsMemberTypeSequenceBool: {
+ WebVector<int> sequence = member->ValueSequenceBool();
+ Vector<bool> vector(SafeCast<wtf_size_t>(sequence.size()));
+ std::copy(sequence.begin(), sequence.end(), vector.begin());
+ builder.Add(name, vector);
break;
+ }
case kWebRTCStatsMemberTypeSequenceInt32:
- success &= AddPropertySequenceOfNumbers(v8_object, isolate, name,
- member->ValueSequenceInt32());
+ add_vector(name, member->ValueSequenceInt32());
break;
case kWebRTCStatsMemberTypeSequenceUint32:
- success &= AddPropertySequenceOfNumbers(v8_object, isolate, name,
- member->ValueSequenceUint32());
+ add_vector(name, member->ValueSequenceUint32());
break;
case kWebRTCStatsMemberTypeSequenceInt64:
- success &= AddPropertySequenceOfNumbers(v8_object, isolate, name,
- member->ValueSequenceInt64());
+ add_vector(name, member->ValueSequenceInt64());
break;
case kWebRTCStatsMemberTypeSequenceUint64:
- success &= AddPropertySequenceOfNumbers(v8_object, isolate, name,
- member->ValueSequenceUint64());
+ add_vector(name, member->ValueSequenceUint64());
break;
case kWebRTCStatsMemberTypeSequenceDouble:
- success &= AddPropertySequenceOfNumbers(v8_object, isolate, name,
- member->ValueSequenceDouble());
+ add_vector(name, member->ValueSequenceDouble());
break;
case kWebRTCStatsMemberTypeSequenceString:
- success &= AddPropertySequenceOfStrings(v8_object, isolate, name,
- member->ValueSequenceString());
+ add_vector(name, member->ValueSequenceString());
break;
default:
NOTREACHED();
}
}
- if (!success) {
+
+ v8::Local<v8::Object> v8_object = builder.V8Value();
+ if (v8_object.IsEmpty()) {
NOTREACHED();
- return v8::Undefined(isolate);
+ return v8::Undefined(script_state->GetIsolate());
}
return v8_object;
}
@@ -179,9 +117,23 @@ class RTCStatsReportIterationSource final
} // namespace
+RTCStatsFilter GetRTCStatsFilter(const ScriptState* script_state) {
+ const ExecutionContext* context = ExecutionContext::From(script_state);
+ DCHECK(context->IsContextThread());
+ // If this original trial is enabled then it exposes jitterBufferFlushes
+ // metric
+ return origin_trials::RtcAudioJitterBufferMaxPacketsEnabled(context)
+ ? RTCStatsFilter::kIncludeNonStandardMembers
+ : RTCStatsFilter::kIncludeOnlyStandardMembers;
+}
+
RTCStatsReport::RTCStatsReport(std::unique_ptr<WebRTCStatsReport> report)
: report_(std::move(report)) {}
+uint32_t RTCStatsReport::size() const {
+ return base::saturated_cast<uint32_t>(report_->Size());
+}
+
PairIterable<String, v8::Local<v8::Value>>::IterationSource*
RTCStatsReport::StartIteration(ScriptState*, ExceptionState&) {
return new RTCStatsReportIterationSource(report_->CopyHandle());
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h
index 2f3bee3f87c..1e4aa9d0bdd 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_report.h
@@ -15,6 +15,10 @@
namespace blink {
+// Determines if non-standardized members should be exposed based on if any
+// known WebRTC related Origin Trials are running.
+RTCStatsFilter GetRTCStatsFilter(const ScriptState* script_state);
+
// https://w3c.github.io/webrtc-pc/#rtcstatsreport-object
class RTCStatsReport final : public ScriptWrappable,
public Maplike<String, v8::Local<v8::Value>> {
@@ -23,7 +27,7 @@ class RTCStatsReport final : public ScriptWrappable,
public:
RTCStatsReport(std::unique_ptr<WebRTCStatsReport>);
- size_t size() const { return report_->Size(); }
+ uint32_t size() const;
// Maplike<String, v8::Local<v8::Value>>
PairIterable<String, v8::Local<v8::Value>>::IterationSource* StartIteration(
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.cc
index 9ac329065e4..3bcc1ef53ba 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.cc
@@ -33,7 +33,8 @@ RTCStatsRequestImpl* RTCStatsRequestImpl::Create(ExecutionContext* context,
RTCPeerConnection* requester,
V8RTCStatsCallback* callback,
MediaStreamTrack* selector) {
- return new RTCStatsRequestImpl(context, requester, callback, selector);
+ return MakeGarbageCollected<RTCStatsRequestImpl>(context, requester, callback,
+ selector);
}
RTCStatsRequestImpl::RTCStatsRequestImpl(ExecutionContext* context,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.h
index 8d1e8b6d0ef..31fb7cf8ec2 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_request_impl.h
@@ -47,6 +47,11 @@ class RTCStatsRequestImpl final : public RTCStatsRequest,
RTCPeerConnection*,
V8RTCStatsCallback*,
MediaStreamTrack*);
+
+ RTCStatsRequestImpl(ExecutionContext*,
+ RTCPeerConnection*,
+ V8RTCStatsCallback*,
+ MediaStreamTrack*);
~RTCStatsRequestImpl() override;
RTCStatsResponseBase* CreateResponse() override;
@@ -61,11 +66,6 @@ class RTCStatsRequestImpl final : public RTCStatsRequest,
void Trace(blink::Visitor*) override;
private:
- RTCStatsRequestImpl(ExecutionContext*,
- RTCPeerConnection*,
- V8RTCStatsCallback*,
- MediaStreamTrack*);
-
void Clear();
// This request object is held by WebRTCPeerConnectionHandler, which doesn't
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.cc
index bea019f5590..f7f3f4e9f5c 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.cc
@@ -27,7 +27,7 @@
namespace blink {
RTCStatsResponse* RTCStatsResponse::Create() {
- return new RTCStatsResponse();
+ return MakeGarbageCollected<RTCStatsResponse>();
}
RTCStatsResponse::RTCStatsResponse() = default;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.h
index 287334664c3..b3b6d94ae1a 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_stats_response.h
@@ -41,6 +41,8 @@ class RTCStatsResponse final : public RTCStatsResponseBase {
public:
static RTCStatsResponse* Create();
+ RTCStatsResponse();
+
const HeapVector<Member<RTCLegacyStatsReport>>& result() const {
return result_;
}
@@ -51,8 +53,6 @@ class RTCStatsResponse final : public RTCStatsResponseBase {
void Trace(blink::Visitor*) override;
private:
- RTCStatsResponse();
-
HeapVector<Member<RTCLegacyStatsReport>> result_;
HashMap<String, int> idmap_;
};
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.cc
index 075c1008eec..bc83ff1648f 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.cc
@@ -13,17 +13,17 @@
namespace blink {
RTCTrackEvent* RTCTrackEvent::Create(const AtomicString& type,
- const RTCTrackEventInit& eventInitDict) {
- return new RTCTrackEvent(type, eventInitDict);
+ const RTCTrackEventInit* eventInitDict) {
+ return MakeGarbageCollected<RTCTrackEvent>(type, eventInitDict);
}
RTCTrackEvent::RTCTrackEvent(const AtomicString& type,
- const RTCTrackEventInit& eventInitDict)
+ const RTCTrackEventInit* eventInitDict)
: Event(type, eventInitDict),
- receiver_(eventInitDict.receiver()),
- track_(eventInitDict.track()),
- streams_(eventInitDict.streams()),
- transceiver_(eventInitDict.transceiver()) {
+ receiver_(eventInitDict->receiver()),
+ track_(eventInitDict->track()),
+ streams_(eventInitDict->streams()),
+ transceiver_(eventInitDict->transceiver()) {
DCHECK(receiver_);
DCHECK(track_);
}
@@ -32,7 +32,7 @@ RTCTrackEvent::RTCTrackEvent(RTCRtpReceiver* receiver,
MediaStreamTrack* track,
const HeapVector<Member<MediaStream>>& streams,
RTCRtpTransceiver* transceiver)
- : Event(EventTypeNames::track, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kTrack, Bubbles::kNo, Cancelable::kNo),
receiver_(receiver),
track_(track),
streams_(streams),
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.h
index cbeaf6bd0a1..dedd3ce8546 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_track_event.h
@@ -24,11 +24,13 @@ class RTCTrackEvent final : public Event {
public:
static RTCTrackEvent* Create(const AtomicString& type,
- const RTCTrackEventInit& eventInitDict);
+ const RTCTrackEventInit* eventInitDict);
RTCTrackEvent(RTCRtpReceiver*,
MediaStreamTrack*,
const HeapVector<Member<MediaStream>>&,
RTCRtpTransceiver*);
+ RTCTrackEvent(const AtomicString& type,
+ const RTCTrackEventInit* eventInitDict);
RTCRtpReceiver* receiver() const;
MediaStreamTrack* track() const;
@@ -38,9 +40,6 @@ class RTCTrackEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- RTCTrackEvent(const AtomicString& type,
- const RTCTrackEventInit& eventInitDict);
-
Member<RTCRtpReceiver> receiver_;
Member<MediaStreamTrack> track_;
HeapVector<Member<MediaStream>> streams_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.cc
index 250c7cb0490..11c6c25f223 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.cc
@@ -38,19 +38,23 @@ namespace blink {
RTCVoidRequestImpl* RTCVoidRequestImpl::Create(
ExecutionContext* context,
+ base::Optional<RTCSetSessionDescriptionOperation> operation,
RTCPeerConnection* requester,
V8VoidFunction* success_callback,
V8RTCPeerConnectionErrorCallback* error_callback) {
- return new RTCVoidRequestImpl(context, requester, success_callback,
- error_callback);
+ return MakeGarbageCollected<RTCVoidRequestImpl>(context, std::move(operation),
+ requester, success_callback,
+ error_callback);
}
RTCVoidRequestImpl::RTCVoidRequestImpl(
ExecutionContext* context,
+ base::Optional<RTCSetSessionDescriptionOperation> operation,
RTCPeerConnection* requester,
V8VoidFunction* success_callback,
V8RTCPeerConnectionErrorCallback* error_callback)
: ContextLifecycleObserver(context),
+ operation_(std::move(operation)),
success_callback_(ToV8PersistentCallbackFunction(success_callback)),
error_callback_(ToV8PersistentCallbackFunction(error_callback)),
requester_(requester) {
@@ -62,8 +66,11 @@ RTCVoidRequestImpl::~RTCVoidRequestImpl() = default;
void RTCVoidRequestImpl::RequestSucceeded() {
bool should_fire_callback =
requester_ && requester_->ShouldFireDefaultCallbacks();
- if (should_fire_callback && success_callback_)
+ if (should_fire_callback && success_callback_) {
+ if (operation_)
+ requester_->NoteVoidRequestCompleted(*operation_, true);
success_callback_->InvokeAndReportException(nullptr);
+ }
Clear();
}
@@ -72,6 +79,8 @@ void RTCVoidRequestImpl::RequestFailed(const webrtc::RTCError& error) {
bool should_fire_callback =
requester_ && requester_->ShouldFireDefaultCallbacks();
if (should_fire_callback && error_callback_.Get()) {
+ if (operation_)
+ requester_->NoteVoidRequestCompleted(*operation_, false);
error_callback_->InvokeAndReportException(
nullptr, CreateDOMExceptionFromRTCError(error));
}
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.h
index 3905e4d8b65..113f7a1497b 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_impl.h
@@ -31,9 +31,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_VOID_REQUEST_IMPL_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_VOID_REQUEST_IMPL_H_
+#include "base/optional.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_void_function.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_rtc_peer_connection_error_callback.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_void_request.h"
@@ -41,15 +43,26 @@ namespace blink {
class RTCPeerConnection;
+// TODO(https://crbug.com/908468): Split up the operation-specific codepaths
+// into separate request implementations and find a way to consolidate the
+// shared code as to not repeat the majority of the implementations.
class RTCVoidRequestImpl final : public RTCVoidRequest,
public ContextLifecycleObserver {
USING_GARBAGE_COLLECTED_MIXIN(RTCVoidRequestImpl);
public:
- static RTCVoidRequestImpl* Create(ExecutionContext*,
- RTCPeerConnection*,
- V8VoidFunction*,
- V8RTCPeerConnectionErrorCallback*);
+ static RTCVoidRequestImpl* Create(
+ ExecutionContext*,
+ base::Optional<RTCSetSessionDescriptionOperation>,
+ RTCPeerConnection*,
+ V8VoidFunction*,
+ V8RTCPeerConnectionErrorCallback*);
+
+ RTCVoidRequestImpl(ExecutionContext*,
+ base::Optional<RTCSetSessionDescriptionOperation>,
+ RTCPeerConnection*,
+ V8VoidFunction*,
+ V8RTCPeerConnectionErrorCallback*);
~RTCVoidRequestImpl() override;
// RTCVoidRequest
@@ -62,13 +75,9 @@ class RTCVoidRequestImpl final : public RTCVoidRequest,
void Trace(blink::Visitor*) override;
private:
- RTCVoidRequestImpl(ExecutionContext*,
- RTCPeerConnection*,
- V8VoidFunction*,
- V8RTCPeerConnectionErrorCallback*);
-
void Clear();
+ base::Optional<RTCSetSessionDescriptionOperation> operation_;
// This request object is held by WebRTCPeerConnectionHandler, which doesn't
// support wrapper-tracing. Thus, this object holds the underlying callback
// functions as persistent handles. This is acceptable because the request
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.cc
index 667d3e474d7..4e8dd2133de 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.cc
@@ -12,20 +12,23 @@
namespace blink {
RTCVoidRequestPromiseImpl* RTCVoidRequestPromiseImpl::Create(
+ base::Optional<RTCSetSessionDescriptionOperation> operation,
RTCPeerConnection* requester,
ScriptPromiseResolver* resolver,
const char* interface_name,
const char* property_name) {
- return new RTCVoidRequestPromiseImpl(requester, resolver, interface_name,
- property_name);
+ return MakeGarbageCollected<RTCVoidRequestPromiseImpl>(
+ std::move(operation), requester, resolver, interface_name, property_name);
}
RTCVoidRequestPromiseImpl::RTCVoidRequestPromiseImpl(
+ base::Optional<RTCSetSessionDescriptionOperation> operation,
RTCPeerConnection* requester,
ScriptPromiseResolver* resolver,
const char* interface_name,
const char* property_name)
- : requester_(requester),
+ : operation_(std::move(operation)),
+ requester_(requester),
resolver_(resolver),
interface_name_(interface_name),
property_name_(property_name) {
@@ -37,6 +40,8 @@ RTCVoidRequestPromiseImpl::~RTCVoidRequestPromiseImpl() = default;
void RTCVoidRequestPromiseImpl::RequestSucceeded() {
if (requester_ && requester_->ShouldFireDefaultCallbacks()) {
+ if (operation_)
+ requester_->NoteVoidRequestCompleted(*operation_, true);
resolver_->Resolve();
} else {
// This is needed to have the resolver release its internal resources
@@ -49,6 +54,8 @@ void RTCVoidRequestPromiseImpl::RequestSucceeded() {
void RTCVoidRequestPromiseImpl::RequestFailed(const webrtc::RTCError& error) {
if (requester_ && requester_->ShouldFireDefaultCallbacks()) {
+ if (operation_)
+ requester_->NoteVoidRequestCompleted(*operation_, false);
ScriptState::Scope scope(resolver_->GetScriptState());
ExceptionState exception_state(resolver_->GetScriptState()->GetIsolate(),
ExceptionState::kExecutionContext,
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.h
index 11bf4eea377..2757d43777a 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_promise_impl.h
@@ -5,6 +5,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_VOID_REQUEST_PROMISE_IMPL_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_VOID_REQUEST_PROMISE_IMPL_H_
+#include "base/optional.h"
+#include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h"
#include "third_party/blink/renderer/platform/peerconnection/rtc_void_request.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -13,12 +15,23 @@ namespace blink {
class ScriptPromiseResolver;
class RTCPeerConnection;
+// TODO(https://crbug.com/908468): Split up the operation-specific codepaths
+// into separate request implementations and find a way to consolidate the
+// shared code as to not repeat the majority of the implementations.
class RTCVoidRequestPromiseImpl final : public RTCVoidRequest {
public:
- static RTCVoidRequestPromiseImpl* Create(RTCPeerConnection*,
- ScriptPromiseResolver*,
- const char* interface_name,
- const char* property_name);
+ static RTCVoidRequestPromiseImpl* Create(
+ base::Optional<RTCSetSessionDescriptionOperation>,
+ RTCPeerConnection*,
+ ScriptPromiseResolver*,
+ const char* interface_name,
+ const char* property_name);
+
+ RTCVoidRequestPromiseImpl(base::Optional<RTCSetSessionDescriptionOperation>,
+ RTCPeerConnection*,
+ ScriptPromiseResolver*,
+ const char* interface_name,
+ const char* property_name);
~RTCVoidRequestPromiseImpl() override;
// RTCVoidRequest
@@ -28,13 +41,9 @@ class RTCVoidRequestPromiseImpl final : public RTCVoidRequest {
void Trace(blink::Visitor*) override;
private:
- RTCVoidRequestPromiseImpl(RTCPeerConnection*,
- ScriptPromiseResolver*,
- const char* interface_name,
- const char* property_name);
-
void Clear();
+ base::Optional<RTCSetSessionDescriptionOperation> operation_;
Member<RTCPeerConnection> requester_;
Member<ScriptPromiseResolver> resolver_;
const char* interface_name_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.cc b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.cc
index 17fd6ec747d..43db1d2f163 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.cc
@@ -14,8 +14,8 @@ RTCVoidRequestScriptPromiseResolverImpl*
RTCVoidRequestScriptPromiseResolverImpl::Create(ScriptPromiseResolver* resolver,
const char* interface_name,
const char* property_name) {
- return new RTCVoidRequestScriptPromiseResolverImpl(resolver, interface_name,
- property_name);
+ return MakeGarbageCollected<RTCVoidRequestScriptPromiseResolverImpl>(
+ resolver, interface_name, property_name);
}
RTCVoidRequestScriptPromiseResolverImpl::
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.h b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.h
index 73ecbe2fe71..20d9d22482d 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.h
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/rtc_void_request_script_promise_resolver_impl.h
@@ -18,6 +18,10 @@ class RTCVoidRequestScriptPromiseResolverImpl : public RTCVoidRequest {
ScriptPromiseResolver*,
const char* interface_name,
const char* property_name);
+
+ RTCVoidRequestScriptPromiseResolverImpl(ScriptPromiseResolver*,
+ const char* interface_name,
+ const char* property_name);
~RTCVoidRequestScriptPromiseResolverImpl() override;
// RTCVoidRequest
@@ -27,10 +31,6 @@ class RTCVoidRequestScriptPromiseResolverImpl : public RTCVoidRequest {
void Trace(blink::Visitor*) override;
protected:
- RTCVoidRequestScriptPromiseResolverImpl(ScriptPromiseResolver*,
- const char* interface_name,
- const char* property_name);
-
Member<ScriptPromiseResolver> resolver_;
const char* interface_name_;
const char* property_name_;
diff --git a/chromium/third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.cc b/chromium/third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.cc
index 479d7df01ae..e2b861337cd 100644
--- a/chromium/third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.cc
+++ b/chromium/third_party/blink/renderer/modules/peerconnection/web_rtc_stats_report_callback_resolver.cc
@@ -24,7 +24,7 @@ void WebRTCStatsReportCallbackResolver::OnStatsDelivered(
std::unique_ptr<WebRTCStatsReport> report) {
DCHECK(
ExecutionContext::From(resolver_->GetScriptState())->IsContextThread());
- resolver_->Resolve(new RTCStatsReport(std::move(report)));
+ resolver_->Resolve(MakeGarbageCollected<RTCStatsReport>(std::move(report)));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.cc b/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.cc
index b9d842b1bf9..e477dc3b0e5 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.cc
+++ b/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.cc
@@ -19,7 +19,7 @@ NavigatorPermissions& NavigatorPermissions::From(Navigator& navigator) {
NavigatorPermissions* supplement =
Supplement<Navigator>::From<NavigatorPermissions>(navigator);
if (!supplement) {
- supplement = new NavigatorPermissions();
+ supplement = MakeGarbageCollected<NavigatorPermissions>();
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -29,7 +29,7 @@ NavigatorPermissions& NavigatorPermissions::From(Navigator& navigator) {
Permissions* NavigatorPermissions::permissions(Navigator& navigator) {
NavigatorPermissions& self = NavigatorPermissions::From(navigator);
if (!self.permissions_)
- self.permissions_ = new Permissions();
+ self.permissions_ = MakeGarbageCollected<Permissions>();
return self.permissions_.Get();
}
diff --git a/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.h b/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.h
index a4116a553f3..651603a3bff 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.h
+++ b/chromium/third_party/blink/renderer/modules/permissions/navigator_permissions.h
@@ -25,11 +25,11 @@ class NavigatorPermissions final
static NavigatorPermissions& From(Navigator&);
static Permissions* permissions(Navigator&);
+ NavigatorPermissions();
+
void Trace(blink::Visitor*) override;
private:
- NavigatorPermissions();
-
Member<Permissions> permissions_;
};
diff --git a/chromium/third_party/blink/renderer/modules/permissions/permission_status.cc b/chromium/third_party/blink/renderer/modules/permissions/permission_status.cc
index ca9bfea83c7..5e83c7f688a 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/permission_status.cc
+++ b/chromium/third_party/blink/renderer/modules/permissions/permission_status.cc
@@ -26,8 +26,8 @@ PermissionStatus* PermissionStatus::CreateAndListen(
ExecutionContext* execution_context,
MojoPermissionStatus status,
MojoPermissionDescriptor descriptor) {
- PermissionStatus* permission_status =
- new PermissionStatus(execution_context, status, std::move(descriptor));
+ PermissionStatus* permission_status = MakeGarbageCollected<PermissionStatus>(
+ execution_context, status, std::move(descriptor));
permission_status->PauseIfNeeded();
permission_status->StartListening();
return permission_status;
@@ -48,7 +48,7 @@ void PermissionStatus::Dispose() {
}
const AtomicString& PermissionStatus::InterfaceName() const {
- return EventTargetNames::PermissionStatus;
+ return event_target_names::kPermissionStatus;
}
ExecutionContext* PermissionStatus::GetExecutionContext() const {
@@ -106,7 +106,7 @@ void PermissionStatus::OnPermissionStatusChange(MojoPermissionStatus status) {
return;
status_ = status;
- DispatchEvent(*Event::Create(EventTypeNames::change));
+ DispatchEvent(*Event::Create(event_type_names::kChange));
}
void PermissionStatus::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/permissions/permission_status.h b/chromium/third_party/blink/renderer/modules/permissions/permission_status.h
index 71025860c8d..797286c2ba1 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/permission_status.h
+++ b/chromium/third_party/blink/renderer/modules/permissions/permission_status.h
@@ -40,6 +40,10 @@ class PermissionStatus final : public EventTargetWithInlineData,
static PermissionStatus* CreateAndListen(ExecutionContext*,
MojoPermissionStatus,
MojoPermissionDescriptor);
+
+ PermissionStatus(ExecutionContext*,
+ MojoPermissionStatus,
+ MojoPermissionDescriptor);
~PermissionStatus() override;
void Dispose();
@@ -57,15 +61,11 @@ class PermissionStatus final : public EventTargetWithInlineData,
String state() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
void Trace(blink::Visitor*) override;
private:
- PermissionStatus(ExecutionContext*,
- MojoPermissionStatus,
- MojoPermissionDescriptor);
-
void StartListening();
void StopListening();
diff --git a/chromium/third_party/blink/renderer/modules/permissions/permissions.cc b/chromium/third_party/blink/renderer/modules/permissions/permissions.cc
index 4b57a3013a2..137ae641237 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/permissions.cc
+++ b/chromium/third_party/blink/renderer/modules/permissions/permissions.cc
@@ -49,7 +49,7 @@ namespace {
PermissionDescriptorPtr ParsePermission(ScriptState* script_state,
const ScriptValue raw_permission,
ExceptionState& exception_state) {
- PermissionDescriptor permission =
+ PermissionDescriptor* permission =
NativeValueTraits<PermissionDescriptor>::NativeValue(
script_state->GetIsolate(), raw_permission.V8Value(),
exception_state);
@@ -59,7 +59,7 @@ PermissionDescriptorPtr ParsePermission(ScriptState* script_state,
return nullptr;
}
- const String& name = permission.name();
+ const String& name = permission->name();
if (name == "geolocation")
return CreatePermissionDescriptor(PermissionName::GEOLOCATION);
if (name == "camera")
@@ -71,7 +71,7 @@ PermissionDescriptorPtr ParsePermission(ScriptState* script_state,
if (name == "persistent-storage")
return CreatePermissionDescriptor(PermissionName::DURABLE_STORAGE);
if (name == "push") {
- PushPermissionDescriptor push_permission =
+ PushPermissionDescriptor* push_permission =
NativeValueTraits<PushPermissionDescriptor>::NativeValue(
script_state->GetIsolate(), raw_permission.V8Value(),
exception_state);
@@ -81,7 +81,7 @@ PermissionDescriptorPtr ParsePermission(ScriptState* script_state,
}
// Only "userVisibleOnly" push is supported for now.
- if (!push_permission.userVisibleOnly()) {
+ if (!push_permission->userVisibleOnly()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Push Permission without userVisibleOnly:true isn't supported yet.");
@@ -91,11 +91,11 @@ PermissionDescriptorPtr ParsePermission(ScriptState* script_state,
return CreatePermissionDescriptor(PermissionName::NOTIFICATIONS);
}
if (name == "midi") {
- MidiPermissionDescriptor midi_permission =
+ MidiPermissionDescriptor* midi_permission =
NativeValueTraits<MidiPermissionDescriptor>::NativeValue(
script_state->GetIsolate(), raw_permission.V8Value(),
exception_state);
- return CreateMidiPermissionDescriptor(midi_permission.sysex());
+ return CreateMidiPermissionDescriptor(midi_permission->sysex());
}
if (name == "background-sync")
return CreatePermissionDescriptor(PermissionName::BACKGROUND_SYNC);
@@ -130,17 +130,17 @@ PermissionDescriptorPtr ParsePermission(ScriptState* script_state,
if (name == "clipboard-write")
permission_name = PermissionName::CLIPBOARD_WRITE;
- ClipboardPermissionDescriptor clipboard_permission =
+ ClipboardPermissionDescriptor* clipboard_permission =
NativeValueTraits<ClipboardPermissionDescriptor>::NativeValue(
script_state->GetIsolate(), raw_permission.V8Value(),
exception_state);
return CreateClipboardPermissionDescriptor(
- permission_name, clipboard_permission.allowWithoutGesture());
+ permission_name, clipboard_permission->allowWithoutGesture());
}
if (name == "payment-handler")
return CreatePermissionDescriptor(PermissionName::PAYMENT_HANDLER);
if (name == "background-fetch") {
- if (!OriginTrials::BackgroundFetchEnabled(
+ if (!origin_trials::BackgroundFetchEnabled(
ExecutionContext::From(script_state))) {
exception_state.ThrowTypeError("Background Fetch is not enabled.");
return nullptr;
@@ -232,7 +232,7 @@ ScriptPromise Permissions::requestAll(
Vector<PermissionDescriptorPtr> internal_permissions;
Vector<int> caller_index_to_internal_index;
caller_index_to_internal_index.resize(raw_permissions.size());
- for (size_t i = 0; i < raw_permissions.size(); ++i) {
+ for (wtf_size_t i = 0; i < raw_permissions.size(); ++i) {
const ScriptValue& raw_permission = raw_permissions[i];
auto descriptor =
@@ -241,8 +241,8 @@ ScriptPromise Permissions::requestAll(
return ScriptPromise();
// Only append permissions types that are not already present in the vector.
- size_t internal_index = kNotFound;
- for (size_t j = 0; j < internal_permissions.size(); ++j) {
+ wtf_size_t internal_index = kNotFound;
+ for (wtf_size_t j = 0; j < internal_permissions.size(); ++j) {
if (internal_permissions[j]->name == descriptor->name) {
internal_index = j;
break;
diff --git a/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.cc b/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.cc
index 8bac10f40ab..db143caee7e 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.cc
+++ b/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.cc
@@ -22,7 +22,7 @@ WorkerNavigatorPermissions& WorkerNavigatorPermissions::From(
Supplement<WorkerNavigator>::From<WorkerNavigatorPermissions>(
worker_navigator);
if (!supplement) {
- supplement = new WorkerNavigatorPermissions();
+ supplement = MakeGarbageCollected<WorkerNavigatorPermissions>();
ProvideTo(worker_navigator, supplement);
}
return *supplement;
@@ -34,7 +34,7 @@ Permissions* WorkerNavigatorPermissions::permissions(
WorkerNavigatorPermissions& self =
WorkerNavigatorPermissions::From(worker_navigator);
if (!self.permissions_)
- self.permissions_ = new Permissions();
+ self.permissions_ = MakeGarbageCollected<Permissions>();
return self.permissions_;
}
diff --git a/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.h b/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.h
index 0603f0be92c..06aab064a49 100644
--- a/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.h
+++ b/chromium/third_party/blink/renderer/modules/permissions/worker_navigator_permissions.h
@@ -25,11 +25,11 @@ class WorkerNavigatorPermissions final
static WorkerNavigatorPermissions& From(WorkerNavigator&);
static Permissions* permissions(WorkerNavigator&);
+ WorkerNavigatorPermissions();
+
void Trace(blink::Visitor*) override;
private:
- WorkerNavigatorPermissions();
-
Member<Permissions> permissions_;
};
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/document_picture_in_picture.cc b/chromium/third_party/blink/renderer/modules/picture_in_picture/document_picture_in_picture.cc
index 2628c46dc9a..cfd09a8f981 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/document_picture_in_picture.cc
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/document_picture_in_picture.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -32,8 +33,7 @@ ScriptPromise DocumentPictureInPicture::exitPictureInPicture(
Document& document) {
PictureInPictureControllerImpl& controller =
PictureInPictureControllerImpl::From(document);
- Element* picture_in_picture_element =
- controller.PictureInPictureElement(document);
+ Element* picture_in_picture_element = controller.PictureInPictureElement();
if (!picture_in_picture_element) {
return ScriptPromise::RejectWithDOMException(
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.cc b/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.cc
index 3b3e738175a..4839db8a6cc 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.cc
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.cc
@@ -14,7 +14,7 @@ EnterPictureInPictureEvent* EnterPictureInPictureEvent::Create(
EnterPictureInPictureEvent* EnterPictureInPictureEvent::Create(
const AtomicString& type,
- const EnterPictureInPictureEventInit& initializer) {
+ const EnterPictureInPictureEventInit* initializer) {
return new EnterPictureInPictureEvent(type, initializer);
}
@@ -31,9 +31,9 @@ EnterPictureInPictureEvent::EnterPictureInPictureEvent(
EnterPictureInPictureEvent::EnterPictureInPictureEvent(
AtomicString const& type,
- const EnterPictureInPictureEventInit& initializer)
+ const EnterPictureInPictureEventInit* initializer)
: Event(type, initializer),
- picture_in_picture_window_(initializer.pictureInPictureWindow()) {}
+ picture_in_picture_window_(initializer->pictureInPictureWindow()) {}
void EnterPictureInPictureEvent::Trace(blink::Visitor* visitor) {
visitor->Trace(picture_in_picture_window_);
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.h b/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.h
index 5db7c83cde1..73989f0aa43 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.h
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.h
@@ -22,7 +22,7 @@ class MODULES_EXPORT EnterPictureInPictureEvent final : public Event {
PictureInPictureWindow*);
static EnterPictureInPictureEvent* Create(
const AtomicString&,
- const EnterPictureInPictureEventInit&);
+ const EnterPictureInPictureEventInit*);
PictureInPictureWindow* pictureInPictureWindow() const;
@@ -31,7 +31,7 @@ class MODULES_EXPORT EnterPictureInPictureEvent final : public Event {
private:
EnterPictureInPictureEvent(AtomicString const&, PictureInPictureWindow*);
EnterPictureInPictureEvent(AtomicString const&,
- const EnterPictureInPictureEventInit&);
+ const EnterPictureInPictureEventInit*);
Member<PictureInPictureWindow> picture_in_picture_window_;
};
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.cc b/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.cc
index a07678ca9c5..b6a8505674f 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.cc
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_control.h"
#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h"
#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -104,7 +105,7 @@ ScriptPromise HTMLVideoElementPictureInPicture::requestPictureInPicture(
void HTMLVideoElementPictureInPicture::setPictureInPictureControls(
HTMLVideoElement& element,
- const HeapVector<PictureInPictureControl>& controls) {
+ const HeapVector<Member<PictureInPictureControl>>& controls) {
Document& document = element.GetDocument();
PictureInPictureControllerImpl& controller =
@@ -118,7 +119,7 @@ void HTMLVideoElementPictureInPicture::setPictureInPictureControls(
bool HTMLVideoElementPictureInPicture::FastHasAttribute(
const QualifiedName& name,
const HTMLVideoElement& element) {
- DCHECK(name == HTMLNames::disablepictureinpictureAttr);
+ DCHECK(name == html_names::kDisablepictureinpictureAttr);
return element.FastHasAttribute(name);
}
@@ -127,7 +128,7 @@ void HTMLVideoElementPictureInPicture::SetBooleanAttribute(
const QualifiedName& name,
HTMLVideoElement& element,
bool value) {
- DCHECK(name == HTMLNames::disablepictureinpictureAttr);
+ DCHECK(name == html_names::kDisablepictureinpictureAttr);
element.SetBooleanAttribute(name, value);
if (!value)
@@ -145,31 +146,31 @@ void HTMLVideoElementPictureInPicture::SetBooleanAttribute(
// static
std::vector<PictureInPictureControlInfo>
HTMLVideoElementPictureInPicture::ToPictureInPictureControlInfoVector(
- const HeapVector<PictureInPictureControl>& controls) {
+ const HeapVector<Member<PictureInPictureControl>>& controls) {
std::vector<PictureInPictureControlInfo> converted_controls;
- for (size_t i = 0; i < controls.size(); ++i) {
+ for (const PictureInPictureControl* control : controls) {
PictureInPictureControlInfo current_converted_control;
- HeapVector<MediaImage> current_icons = controls[i].icons();
+ HeapVector<Member<MediaImage>> current_icons = control->icons();
// Only two icons are supported, so cap the loop at running that many times
// to avoid potential problems.
- for (size_t j = 0; j < current_icons.size() && j < 2; ++j) {
+ for (wtf_size_t j = 0; j < current_icons.size() && j < 2; ++j) {
PictureInPictureControlInfo::Icon current_icon;
- current_icon.src = KURL(WebString(current_icons[j].src()));
+ current_icon.src = KURL(WebString(current_icons[j]->src()));
WebVector<WebSize> sizes = WebIconSizesParser::ParseIconSizes(
- WebString(current_icons[j].sizes()));
+ WebString(current_icons[j]->sizes()));
std::vector<gfx::Size> converted_sizes;
for (size_t i = 0; i < sizes.size(); ++i)
converted_sizes.push_back(static_cast<gfx::Size>(sizes[i]));
current_icon.sizes = converted_sizes;
- current_icon.type = WebString(current_icons[j].type()).Utf8();
+ current_icon.type = WebString(current_icons[j]->type()).Utf8();
current_converted_control.icons.push_back(current_icon);
}
- current_converted_control.id = WebString(controls[i].id()).Utf8();
- current_converted_control.label = WebString(controls[i].label()).Utf8();
+ current_converted_control.id = WebString(control->id()).Utf8();
+ current_converted_control.label = WebString(control->label()).Utf8();
converted_controls.push_back(current_converted_control);
}
return converted_controls;
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.h b/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.h
index 8cdd5b42c2e..fe08f252dc9 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.h
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture.h
@@ -25,7 +25,7 @@ class MODULES_EXPORT HTMLVideoElementPictureInPicture {
static void setPictureInPictureControls(
HTMLVideoElement&,
- const HeapVector<PictureInPictureControl>&);
+ const HeapVector<Member<PictureInPictureControl>>&);
static bool FastHasAttribute(const QualifiedName&, const HTMLVideoElement&);
@@ -33,13 +33,16 @@ class MODULES_EXPORT HTMLVideoElementPictureInPicture {
HTMLVideoElement&,
bool);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(enterpictureinpicture);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(leavepictureinpicture);
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pictureinpicturecontrolclick);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(enterpictureinpicture,
+ kEnterpictureinpicture);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(leavepictureinpicture,
+ kLeavepictureinpicture);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pictureinpicturecontrolclick,
+ kPictureinpicturecontrolclick);
static std::vector<PictureInPictureControlInfo>
ToPictureInPictureControlInfoVector(
- const HeapVector<PictureInPictureControl>&);
+ const HeapVector<Member<PictureInPictureControl>>&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture_test.cc b/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture_test.cc
index 4587e413f41..487156953ca 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture_test.cc
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/html_video_element_picture_in_picture_test.cc
@@ -12,19 +12,19 @@ namespace blink {
TEST(HTMLVideoElementPictureInPictureTest,
ToPictureInPictureControlInfoVector_Basic) {
- MediaImage image;
- image.setSrc("https://dummyimage.com/144x144/7d727d/fafafa.gif");
- image.setSizes("144x144");
- image.setType("image/gif");
- HeapVector<MediaImage> images;
+ MediaImage* image = MediaImage::Create();
+ image->setSrc("https://dummyimage.com/144x144/7d727d/fafafa.gif");
+ image->setSizes("144x144");
+ image->setType("image/gif");
+ HeapVector<Member<MediaImage>> images;
images.push_back(image);
- PictureInPictureControl control;
- control.setId(WTF::String("Test id"));
- control.setLabel(WTF::String("Test label"));
- control.setIcons(images);
+ PictureInPictureControl* control = PictureInPictureControl::Create();
+ control->setId(WTF::String("Test id"));
+ control->setLabel(WTF::String("Test label"));
+ control->setIcons(images);
- HeapVector<PictureInPictureControl> controls;
+ HeapVector<Member<PictureInPictureControl>> controls;
controls.push_back(control);
std::vector<PictureInPictureControlInfo> converted_controls =
@@ -38,26 +38,26 @@ TEST(HTMLVideoElementPictureInPictureTest,
TEST(HTMLVideoElementPictureInPictureTest,
ToPictureInPictureControlInfoVector_MultipleImages) {
- MediaImage image;
- image.setSrc("https://dummyimage.com/144x144/7d727d/fafafa.gif");
- image.setSizes("144x144");
- image.setType("image/gif");
+ MediaImage* image = MediaImage::Create();
+ image->setSrc("https://dummyimage.com/144x144/7d727d/fafafa.gif");
+ image->setSizes("144x144");
+ image->setType("image/gif");
- MediaImage image2;
- image2.setSrc("https://dummyimage.com/96x96/7d727d/fafafa.gif");
- image2.setSizes("96x96");
- image2.setType("image/gif");
+ MediaImage* image2 = MediaImage::Create();
+ image2->setSrc("https://dummyimage.com/96x96/7d727d/fafafa.gif");
+ image2->setSizes("96x96");
+ image2->setType("image/gif");
- HeapVector<MediaImage> images;
+ HeapVector<Member<MediaImage>> images;
images.push_back(image);
images.push_back(image2);
- PictureInPictureControl control;
- control.setId(WTF::String("Test id"));
- control.setLabel(WTF::String("Test label"));
- control.setIcons(images);
+ PictureInPictureControl* control = PictureInPictureControl::Create();
+ control->setId(WTF::String("Test id"));
+ control->setLabel(WTF::String("Test label"));
+ control->setIcons(images);
- HeapVector<PictureInPictureControl> controls;
+ HeapVector<Member<PictureInPictureControl>> controls;
controls.push_back(control);
std::vector<PictureInPictureControlInfo> converted_controls =
@@ -73,19 +73,19 @@ TEST(HTMLVideoElementPictureInPictureTest,
TEST(HTMLVideoElementPictureInPictureTest,
ToPictureInPictureControlInfoVector_InvalidSize) {
- MediaImage image;
- image.setSrc("https://dummyimage.com/144x144/7d727d/fafafa.gif");
- image.setSizes("144");
- image.setType("image/gif");
- HeapVector<MediaImage> images;
+ MediaImage* image = MediaImage::Create();
+ image->setSrc("https://dummyimage.com/144x144/7d727d/fafafa.gif");
+ image->setSizes("144");
+ image->setType("image/gif");
+ HeapVector<Member<MediaImage>> images;
images.push_back(image);
- PictureInPictureControl control;
- control.setId(WTF::String("Test id"));
- control.setLabel(WTF::String("Test label"));
- control.setIcons(images);
+ PictureInPictureControl* control = PictureInPictureControl::Create();
+ control->setId(WTF::String("Test id"));
+ control->setLabel(WTF::String("Test label"));
+ control->setIcons(images);
- HeapVector<PictureInPictureControl> controls;
+ HeapVector<Member<PictureInPictureControl>> controls;
controls.push_back(control);
std::vector<PictureInPictureControlInfo> converted_controls =
@@ -101,7 +101,7 @@ TEST(HTMLVideoElementPictureInPictureTest,
TEST(HTMLVideoElementPictureInPictureTest,
ToPictureInPictureControlInfoVector_Empty) {
- HeapVector<PictureInPictureControl> controls;
+ HeapVector<Member<PictureInPictureControl>> controls;
std::vector<PictureInPictureControlInfo> converted_controls =
HTMLVideoElementPictureInPicture::ToPictureInPictureControlInfoVector(
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc
index c8ff90a439d..fdf447f6a87 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/modules/picture_in_picture/enter_picture_in_picture_event.h"
#include "third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -22,7 +23,7 @@ PictureInPictureControllerImpl::~PictureInPictureControllerImpl() = default;
// static
PictureInPictureControllerImpl* PictureInPictureControllerImpl::Create(
Document& document) {
- return new PictureInPictureControllerImpl(document);
+ return MakeGarbageCollected<PictureInPictureControllerImpl>(document);
}
// static
@@ -76,7 +77,7 @@ PictureInPictureControllerImpl::IsElementAllowed(
if (!element.HasVideo())
return Status::kVideoTrackNotAvailable;
- if (element.FastHasAttribute(HTMLNames::disablepictureinpictureAttr))
+ if (element.FastHasAttribute(html_names::kDisablepictureinpictureAttr))
return Status::kDisabledByAttribute;
return Status::kEnabled;
@@ -121,12 +122,12 @@ void PictureInPictureControllerImpl::OnEnteredPictureInPicture(
if (picture_in_picture_window_)
picture_in_picture_window_->OnClose();
- picture_in_picture_window_ = new PictureInPictureWindow(
+ picture_in_picture_window_ = MakeGarbageCollected<PictureInPictureWindow>(
GetSupplementable(), picture_in_picture_window_size);
picture_in_picture_element_->DispatchEvent(
*EnterPictureInPictureEvent::Create(
- EventTypeNames::enterpictureinpicture,
+ event_type_names::kEnterpictureinpicture,
WrapPersistent(picture_in_picture_window_.Get())));
element->GetWebMediaPlayer()->RegisterPictureInPictureWindowResizeCallback(
@@ -170,7 +171,7 @@ void PictureInPictureControllerImpl::OnExitedPictureInPicture(
element->OnExitedPictureInPicture();
element->DispatchEvent(
- *Event::CreateBubble(EventTypeNames::leavepictureinpicture));
+ *Event::CreateBubble(event_type_names::kLeavepictureinpicture));
}
if (resolver)
@@ -189,10 +190,14 @@ void PictureInPictureControllerImpl::OnPictureInPictureControlClicked(
picture_in_picture_element_) {
picture_in_picture_element_->DispatchEvent(
*PictureInPictureControlEvent::Create(
- EventTypeNames::pictureinpicturecontrolclick, control_id));
+ event_type_names::kPictureinpicturecontrolclick, control_id));
}
}
+Element* PictureInPictureControllerImpl::PictureInPictureElement() const {
+ return picture_in_picture_element_;
+}
+
Element* PictureInPictureControllerImpl::PictureInPictureElement(
TreeScope& scope) const {
if (!picture_in_picture_element_)
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h
index b7bcf09314c..1c5c2f36baa 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_controller_impl.h
@@ -27,6 +27,7 @@ class PictureInPictureControllerImpl : public PictureInPictureController {
WTF_MAKE_NONCOPYABLE(PictureInPictureControllerImpl);
public:
+ explicit PictureInPictureControllerImpl(Document&);
~PictureInPictureControllerImpl() override;
// Meant to be called internally by PictureInPictureController::From()
@@ -46,6 +47,7 @@ class PictureInPictureControllerImpl : public PictureInPictureController {
Status IsDocumentAllowed() const;
// Returns element currently in Picture-in-Picture if any. Null otherwise.
+ Element* PictureInPictureElement() const;
Element* PictureInPictureElement(TreeScope&) const;
// Implementation of PictureInPictureController.
@@ -67,8 +69,6 @@ class PictureInPictureControllerImpl : public PictureInPictureController {
void OnExitedPictureInPicture(ScriptPromiseResolver*) override;
void OnPictureInPictureControlClicked(const WebString& control_id) override;
- explicit PictureInPictureControllerImpl(Document&);
-
// The Picture-in-Picture element for the associated document.
Member<HTMLVideoElement> picture_in_picture_element_;
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.cc b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.cc
index 847602d7121..7475eaba3dc 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.cc
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.cc
@@ -24,17 +24,17 @@ void PictureInPictureWindow::OnResize(const WebSize& size) {
return;
size_ = size;
- DispatchEvent(*Event::Create(EventTypeNames::resize));
+ DispatchEvent(*Event::Create(event_type_names::kResize));
}
const AtomicString& PictureInPictureWindow::InterfaceName() const {
- return EventTargetNames::PictureInPictureWindow;
+ return event_target_names::kPictureInPictureWindow;
}
void PictureInPictureWindow::AddedEventListener(
const AtomicString& event_type,
RegisteredEventListener& registered_listener) {
- if (event_type == EventTypeNames::resize) {
+ if (event_type == event_type_names::kResize) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kPictureInPictureWindowResizeEventListener);
}
diff --git a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h
index 0674c09d7d3..e34373496d0 100644
--- a/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h
+++ b/chromium/third_party/blink/renderer/modules/picture_in_picture/picture_in_picture_window.h
@@ -35,7 +35,7 @@ class PictureInPictureWindow
// Called when the Picture-in-Picture window is resized.
void OnResize(const WebSize&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resize);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resize, kResize);
// EventTarget overrides.
const AtomicString& InterfaceName() const override;
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.cc b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.cc
index 8ff4b451b38..a086557ea27 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.cc
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.cc
@@ -49,7 +49,7 @@ String DOMMimeType::suffixes() const {
const Vector<String>& extensions = mime_class_info_->Extensions();
StringBuilder builder;
- for (size_t i = 0; i < extensions.size(); ++i) {
+ for (wtf_size_t i = 0; i < extensions.size(); ++i) {
if (i)
builder.Append(',');
builder.Append(extensions[i]);
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.h b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.h
index d179623c2cd..f8823c80954 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.h
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type.h
@@ -39,9 +39,11 @@ class DOMMimeType final : public ScriptWrappable, public ContextClient {
public:
static DOMMimeType* Create(LocalFrame* frame,
const MimeClassInfo& mime_class_info) {
- return new DOMMimeType(frame, mime_class_info);
+ return MakeGarbageCollected<DOMMimeType>(frame, mime_class_info);
}
+ DOMMimeType(LocalFrame*, const MimeClassInfo&);
+
const String& type() const;
String suffixes() const;
const String& description() const;
@@ -50,8 +52,6 @@ class DOMMimeType final : public ScriptWrappable, public ContextClient {
void Trace(blink::Visitor*) override;
private:
- DOMMimeType(LocalFrame*, const MimeClassInfo&);
-
Member<const MimeClassInfo> mime_class_info_;
};
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.cc b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.cc
index 5b027492922..70c3daea06b 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.cc
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.cc
@@ -63,7 +63,7 @@ DOMMimeType* DOMMimeTypeArray::namedItem(const AtomicString& property_name) {
for (const Member<MimeClassInfo>& mime : data->Mimes()) {
if (mime->Type() == property_name) {
- size_t index = &mime - &data->Mimes()[0];
+ unsigned index = static_cast<unsigned>(&mime - &data->Mimes()[0]);
return item(index);
}
}
@@ -111,7 +111,8 @@ void DOMMimeTypeArray::UpdatePluginData() {
if (mime) {
for (const Member<MimeClassInfo>& mime_info : data->Mimes()) {
if (mime->type() == mime_info->Type()) {
- size_t index = &mime_info - &data->Mimes()[0];
+ unsigned index =
+ static_cast<unsigned>(&mime_info - &data->Mimes()[0]);
dom_mime_types_[index] = mime;
}
}
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.h b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.h
index b37bc75ac1e..e29e9e4036b 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.h
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_mime_type_array.h
@@ -42,8 +42,11 @@ class DOMMimeTypeArray final : public ScriptWrappable,
public:
static DOMMimeTypeArray* Create(LocalFrame* frame) {
- return new DOMMimeTypeArray(frame);
+ return MakeGarbageCollected<DOMMimeTypeArray>(frame);
}
+
+ explicit DOMMimeTypeArray(LocalFrame*);
+
void UpdatePluginData();
unsigned length() const;
@@ -58,7 +61,6 @@ class DOMMimeTypeArray final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
private:
- explicit DOMMimeTypeArray(LocalFrame*);
PluginData* GetPluginData() const;
void ContextDestroyed(ExecutionContext*) override;
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_plugin.h b/chromium/third_party/blink/renderer/modules/plugins/dom_plugin.h
index e39b238f028..1fb9b7a6171 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_plugin.h
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_plugin.h
@@ -37,9 +37,11 @@ class DOMPlugin final : public ScriptWrappable, public ContextClient {
public:
static DOMPlugin* Create(LocalFrame* frame, const PluginInfo& plugin_info) {
- return new DOMPlugin(frame, plugin_info);
+ return MakeGarbageCollected<DOMPlugin>(frame, plugin_info);
}
+ DOMPlugin(LocalFrame*, const PluginInfo&);
+
String name() const;
String filename() const;
String description() const;
@@ -54,8 +56,6 @@ class DOMPlugin final : public ScriptWrappable, public ContextClient {
void Trace(blink::Visitor*) override;
private:
- DOMPlugin(LocalFrame*, const PluginInfo&);
-
Member<const PluginInfo> plugin_info_;
};
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc b/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc
index e8cbb82500f..a054d5428d6 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc
@@ -69,7 +69,8 @@ DOMPlugin* DOMPluginArray::namedItem(const AtomicString& property_name) {
for (const Member<PluginInfo>& plugin_info : data->Plugins()) {
if (plugin_info->Name() == property_name) {
- size_t index = &plugin_info - &data->Plugins()[0];
+ unsigned index =
+ static_cast<unsigned>(&plugin_info - &data->Plugins()[0]);
return item(index);
}
}
@@ -138,7 +139,8 @@ void DOMPluginArray::UpdatePluginData() {
if (plugin) {
for (const Member<PluginInfo>& plugin_info : data->Plugins()) {
if (plugin->name() == plugin_info->Name()) {
- size_t index = &plugin_info - &data->Plugins()[0];
+ unsigned index =
+ static_cast<unsigned>(&plugin_info - &data->Plugins()[0]);
dom_plugins_[index] = plugin;
}
}
diff --git a/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.h b/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.h
index 26092fcf8b6..fa4c33de97d 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.h
+++ b/chromium/third_party/blink/renderer/modules/plugins/dom_plugin_array.h
@@ -42,8 +42,11 @@ class DOMPluginArray final : public ScriptWrappable,
public:
static DOMPluginArray* Create(LocalFrame* frame) {
- return new DOMPluginArray(frame);
+ return MakeGarbageCollected<DOMPluginArray>(frame);
}
+
+ explicit DOMPluginArray(LocalFrame*);
+
void UpdatePluginData();
unsigned length() const;
@@ -60,7 +63,6 @@ class DOMPluginArray final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
private:
- explicit DOMPluginArray(LocalFrame*);
PluginData* GetPluginData() const;
void ContextDestroyed(ExecutionContext*) override;
diff --git a/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.cc b/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.cc
index 79a170eb787..6cb12a8577e 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.cc
+++ b/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.cc
@@ -19,7 +19,7 @@ NavigatorPlugins::NavigatorPlugins(Navigator& navigator)
NavigatorPlugins& NavigatorPlugins::From(Navigator& navigator) {
NavigatorPlugins* supplement = ToNavigatorPlugins(navigator);
if (!supplement) {
- supplement = new NavigatorPlugins(navigator);
+ supplement = MakeGarbageCollected<NavigatorPlugins>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.h b/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.h
index 33aff1ff3ce..602ebc816d4 100644
--- a/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.h
+++ b/chromium/third_party/blink/renderer/modules/plugins/navigator_plugins.h
@@ -29,11 +29,11 @@ class NavigatorPlugins final : public GarbageCollected<NavigatorPlugins>,
static DOMMimeTypeArray* mimeTypes(Navigator&);
static bool javaEnabled(Navigator&);
+ explicit NavigatorPlugins(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorPlugins(Navigator&);
-
DOMPluginArray* plugins(LocalFrame*) const;
DOMMimeTypeArray* mimeTypes(LocalFrame*) const;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/OWNERS b/chromium/third_party/blink/renderer/modules/presentation/OWNERS
index 210cf4062f5..60162ad0a3b 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/presentation/OWNERS
@@ -1,4 +1,3 @@
-imcheng@chromium.org
mfoltz@chromium.org
mlamouri@chromium.org
diff --git a/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.cc b/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.cc
index 342358bcc07..5faa2d52511 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.cc
@@ -19,7 +19,7 @@ NavigatorPresentation& NavigatorPresentation::From(Navigator& navigator) {
NavigatorPresentation* supplement =
Supplement<Navigator>::From<NavigatorPresentation>(navigator);
if (!supplement) {
- supplement = new NavigatorPresentation();
+ supplement = MakeGarbageCollected<NavigatorPresentation>();
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.h b/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.h
index 584ec1b234a..e0818acc7fd 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.h
@@ -25,11 +25,11 @@ class NavigatorPresentation final
static NavigatorPresentation& From(Navigator&);
static Presentation* presentation(Navigator&);
+ NavigatorPresentation();
+
void Trace(blink::Visitor*) override;
private:
- NavigatorPresentation();
-
Presentation* presentation();
Member<Presentation> presentation_;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.idl b/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.idl
index 7b0799a2fe0..ff7cb578207 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/navigator_presentation.idl
@@ -8,5 +8,5 @@
ImplementedAs=NavigatorPresentation,
RuntimeEnabled=Presentation
] partial interface Navigator {
- [SameObject] readonly attribute Presentation presentation;
+ [SameObject, SecureContext] readonly attribute Presentation presentation;
};
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation.cc
index 4e7b5db14be..385e1def64a 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation.cc
@@ -20,7 +20,7 @@ Presentation::Presentation(LocalFrame* frame) : ContextClient(frame) {}
// static
Presentation* Presentation::Create(LocalFrame* frame) {
DCHECK(frame);
- Presentation* presentation = new Presentation(frame);
+ Presentation* presentation = MakeGarbageCollected<Presentation>(frame);
PresentationController* controller = PresentationController::From(*frame);
DCHECK(controller);
controller->SetPresentation(presentation);
@@ -59,7 +59,7 @@ PresentationReceiver* Presentation::receiver() {
}
if (!receiver_)
- receiver_ = new PresentationReceiver(GetFrame());
+ receiver_ = MakeGarbageCollected<PresentationReceiver>(GetFrame());
return receiver_;
}
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation.h b/chromium/third_party/blink/renderer/modules/presentation/presentation.h
index b29256c511f..8948c2c4782 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation.h
@@ -27,6 +27,8 @@ class Presentation final : public ScriptWrappable, public ContextClient {
public:
static Presentation* Create(LocalFrame*);
+ explicit Presentation(LocalFrame*);
+
void Trace(blink::Visitor*) override;
PresentationRequest* defaultRequest() const;
@@ -35,8 +37,6 @@ class Presentation final : public ScriptWrappable, public ContextClient {
PresentationReceiver* receiver();
private:
- explicit Presentation(LocalFrame*);
-
// Default PresentationRequest used by the embedder.
Member<PresentationRequest> default_request_;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation.idl
index 6a3acbb92de..0cae99735dc 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation.idl
@@ -6,6 +6,7 @@
[
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface Presentation {
[MeasureAs=PresentationDefaultRequest] attribute PresentationRequest? defaultRequest;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.cc
index 8c3c92da83a..f4510ba9820 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.cc
@@ -23,8 +23,8 @@ PresentationAvailability* PresentationAvailability::Take(
const WTF::Vector<KURL>& urls,
bool value) {
PresentationAvailability* presentation_availability =
- new PresentationAvailability(resolver->GetExecutionContext(), urls,
- value);
+ MakeGarbageCollected<PresentationAvailability>(
+ resolver->GetExecutionContext(), urls, value);
presentation_availability->PauseIfNeeded();
presentation_availability->UpdateListening();
return presentation_availability;
@@ -45,7 +45,7 @@ PresentationAvailability::PresentationAvailability(
PresentationAvailability::~PresentationAvailability() = default;
const AtomicString& PresentationAvailability::InterfaceName() const {
- return EventTargetNames::PresentationAvailability;
+ return event_target_names::kPresentationAvailability;
}
ExecutionContext* PresentationAvailability::GetExecutionContext() const {
@@ -57,7 +57,7 @@ void PresentationAvailability::AddedEventListener(
RegisteredEventListener& registered_listener) {
EventTargetWithInlineData::AddedEventListener(event_type,
registered_listener);
- if (event_type == EventTypeNames::change) {
+ if (event_type == event_type_names::kChange) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kPresentationAvailabilityChangeEventListener);
}
@@ -70,7 +70,7 @@ void PresentationAvailability::AvailabilityChanged(
return;
value_ = value;
- DispatchEvent(*Event::Create(EventTypeNames::change));
+ DispatchEvent(*Event::Create(event_type_names::kChange));
}
bool PresentationAvailability::HasPendingActivity() const {
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.h
index 75f5740ee4f..bbef7b4daf6 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.h
@@ -38,6 +38,8 @@ class MODULES_EXPORT PresentationAvailability final
static PresentationAvailability* Take(PresentationAvailabilityProperty*,
const WTF::Vector<KURL>&,
bool);
+
+ PresentationAvailability(ExecutionContext*, const WTF::Vector<KURL>&, bool);
~PresentationAvailability() override;
// EventTarget implementation.
@@ -61,7 +63,7 @@ class MODULES_EXPORT PresentationAvailability final
bool value() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
void Trace(blink::Visitor*) override;
@@ -81,8 +83,6 @@ class MODULES_EXPORT PresentationAvailability final
kInactive,
};
- PresentationAvailability(ExecutionContext*, const WTF::Vector<KURL>&, bool);
-
void SetState(State);
void UpdateListening();
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.idl
index 46d0d4a30c3..a79781ebf73 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability.idl
@@ -7,6 +7,7 @@
[
ActiveScriptWrappable,
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationAvailability : EventTarget {
readonly attribute boolean value;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_state.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_state.cc
index ba08fa134d9..62119692b11 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_state.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_state.cc
@@ -24,7 +24,7 @@ void PresentationAvailabilityState::RequestAvailability(
auto screen_availability = GetScreenAvailability(urls);
// Reject Promise if screen availability is unsupported for all URLs.
if (screen_availability == mojom::blink::ScreenAvailability::DISABLED) {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(
&PresentationAvailabilityCallbacks::RejectAvailabilityNotSupported,
@@ -40,7 +40,7 @@ void PresentationAvailabilityState::RequestAvailability(
}
if (screen_availability != mojom::blink::ScreenAvailability::UNKNOWN) {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&PresentationAvailabilityCallbacks::Resolve,
std::move(callback),
screen_availability ==
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_test.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_test.cc
index 74c0702bfe7..b2a654b5770 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_test.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_availability_test.cc
@@ -26,8 +26,8 @@ TEST(PresentationAvailabilityTest, NoPageVisibilityChangeAfterDetach) {
{
V8TestingScope scope;
WTF::Vector<KURL> urls;
- urls.push_back(URLTestHelpers::ToKURL("https://example.com"));
- urls.push_back(URLTestHelpers::ToKURL("https://another.com"));
+ urls.push_back(url_test_helpers::ToKURL("https://example.com"));
+ urls.push_back(url_test_helpers::ToKURL("https://another.com"));
Persistent<PresentationAvailabilityProperty> resolver =
new PresentationAvailabilityProperty(
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.cc
index 68acf374d54..0c3875d4336 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/events/message_event.h"
+#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader_client.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
@@ -25,6 +26,7 @@
#include "third_party/blink/renderer/modules/presentation/presentation_receiver.h"
#include "third_party/blink/renderer/modules/presentation/presentation_request.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
@@ -136,7 +138,7 @@ class PresentationConnection::BlobLoader final
presentation_connection_->DidFinishLoadingBlob(
loader_->ArrayBufferResult());
}
- void DidFail(FileError::ErrorCode error_code) override {
+ void DidFail(FileErrorCode error_code) override {
presentation_connection_->DidFailLoadingBlob(error_code);
}
@@ -189,12 +191,12 @@ void PresentationConnection::DidChangeState(
case mojom::blink::PresentationConnectionState::CONNECTING:
return;
case mojom::blink::PresentationConnectionState::CONNECTED:
- DispatchStateChangeEvent(Event::Create(EventTypeNames::connect));
+ DispatchStateChangeEvent(Event::Create(event_type_names::kConnect));
return;
case mojom::blink::PresentationConnectionState::CLOSED:
return;
case mojom::blink::PresentationConnectionState::TERMINATED:
- DispatchStateChangeEvent(Event::Create(EventTypeNames::terminate));
+ DispatchStateChangeEvent(Event::Create(event_type_names::kTerminate));
return;
}
NOTREACHED();
@@ -240,7 +242,7 @@ ControllerPresentationConnection* ControllerPresentationConnection::Take(
// Fire onconnectionavailable event asynchronously.
auto* event = PresentationConnectionAvailableEvent::Create(
- EventTypeNames::connectionavailable, connection);
+ event_type_names::kConnectionavailable, connection);
request->GetExecutionContext()
->GetTaskRunner(TaskType::kPresentation)
->PostTask(FROM_HERE,
@@ -302,9 +304,9 @@ ReceiverPresentationConnection* ReceiverPresentationConnection::Take(
DCHECK(receiver);
ReceiverPresentationConnection* connection =
- new ReceiverPresentationConnection(*receiver->GetFrame(), receiver,
- presentation_info.id,
- presentation_info.url);
+ MakeGarbageCollected<ReceiverPresentationConnection>(
+ *receiver->GetFrame(), receiver, presentation_info.id,
+ presentation_info.url);
connection->Init(std::move(controller_connection),
std::move(receiver_connection_request));
@@ -367,7 +369,7 @@ void ReceiverPresentationConnection::Trace(blink::Visitor* visitor) {
}
const AtomicString& PresentationConnection::InterfaceName() const {
- return EventTargetNames::PresentationConnection;
+ return event_target_names::kPresentationConnection;
}
ExecutionContext* PresentationConnection::GetExecutionContext() const {
@@ -381,17 +383,17 @@ void PresentationConnection::AddedEventListener(
RegisteredEventListener& registered_listener) {
EventTargetWithInlineData::AddedEventListener(event_type,
registered_listener);
- if (event_type == EventTypeNames::connect) {
+ if (event_type == event_type_names::kConnect) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kPresentationConnectionConnectEventListener);
- } else if (event_type == EventTypeNames::close) {
+ } else if (event_type == event_type_names::kClose) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kPresentationConnectionCloseEventListener);
- } else if (event_type == EventTypeNames::terminate) {
+ } else if (event_type == event_type_names::kTerminate) {
UseCounter::Count(
GetExecutionContext(),
WebFeature::kPresentationConnectionTerminateEventListener);
- } else if (event_type == EventTypeNames::message) {
+ } else if (event_type == event_type_names::kMessage) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kPresentationConnectionMessageEventListener);
}
@@ -419,7 +421,7 @@ void PresentationConnection::send(const String& message,
if (!CanSendMessage(exception_state))
return;
- messages_.push_back(new Message(message));
+ messages_.push_back(MakeGarbageCollected<Message>(message));
HandleMessageQueue();
}
@@ -430,7 +432,7 @@ void PresentationConnection::send(DOMArrayBuffer* array_buffer,
if (!CanSendMessage(exception_state))
return;
- messages_.push_back(new Message(array_buffer));
+ messages_.push_back(MakeGarbageCollected<Message>(array_buffer));
HandleMessageQueue();
}
@@ -441,7 +443,8 @@ void PresentationConnection::send(
if (!CanSendMessage(exception_state))
return;
- messages_.push_back(new Message(array_buffer_view.View()->buffer()));
+ messages_.push_back(
+ MakeGarbageCollected<Message>(array_buffer_view.View()->buffer()));
HandleMessageQueue();
}
@@ -450,7 +453,7 @@ void PresentationConnection::send(Blob* data, ExceptionState& exception_state) {
if (!CanSendMessage(exception_state))
return;
- messages_.push_back(new Message(data->GetBlobDataHandle()));
+ messages_.push_back(MakeGarbageCollected<Message>(data->GetBlobDataHandle()));
HandleMessageQueue();
}
@@ -495,7 +498,8 @@ void PresentationConnection::HandleMessageQueue() {
break;
case kMessageTypeBlob:
DCHECK(!blob_loader_);
- blob_loader_ = new BlobLoader(message->blob_data_handle, this);
+ blob_loader_ =
+ MakeGarbageCollected<BlobLoader>(message->blob_data_handle, this);
break;
}
}
@@ -590,7 +594,8 @@ void PresentationConnection::DidClose(
state_ = mojom::blink::PresentationConnectionState::CLOSED;
DispatchStateChangeEvent(PresentationConnectionCloseEvent::Create(
- EventTypeNames::close, ConnectionCloseReasonToString(reason), message));
+ event_type_names::kClose, ConnectionCloseReasonToString(reason),
+ message));
}
void PresentationConnection::DidFinishLoadingBlob(DOMArrayBuffer* buffer) {
@@ -607,8 +612,7 @@ void PresentationConnection::DidFinishLoadingBlob(DOMArrayBuffer* buffer) {
HandleMessageQueue();
}
-void PresentationConnection::DidFailLoadingBlob(
- FileError::ErrorCode error_code) {
+void PresentationConnection::DidFailLoadingBlob(FileErrorCode error_code) {
DCHECK(!messages_.IsEmpty());
DCHECK_EQ(messages_.front()->type, kMessageTypeBlob);
// FIXME: generate error message?
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.h
index 3168d5bad32..9ac31e43f27 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.h
@@ -11,7 +11,6 @@
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
-#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
@@ -25,6 +24,7 @@ namespace blink {
class DOMArrayBuffer;
class DOMArrayBufferView;
+enum class FileErrorCode;
class PresentationController;
class PresentationReceiver;
class PresentationRequest;
@@ -64,10 +64,10 @@ class PresentationConnection : public EventTargetWithInlineData,
String binaryType() const;
void setBinaryType(const String&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(terminate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(terminate, kTerminate);
// Returns true if this connection's id equals to |id| and its url equals to
// |url|.
@@ -131,7 +131,7 @@ class PresentationConnection : public EventTargetWithInlineData,
// Callbacks invoked from BlobLoader.
void DidFinishLoadingBlob(DOMArrayBuffer*);
- void DidFailLoadingBlob(FileError::ErrorCode);
+ void DidFailLoadingBlob(FileErrorCode);
void SendMessageToTargetConnection(
mojom::blink::PresentationConnectionMessagePtr);
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.idl
index ed89633d5de..92865206902 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection.idl
@@ -12,6 +12,7 @@ enum PresentationConnectionState {
[
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationConnection : EventTarget {
readonly attribute USVString id;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.cc
index 6236744417e..27c7dcd1047 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.cc
@@ -19,12 +19,12 @@ PresentationConnectionAvailableEvent::PresentationConnectionAvailableEvent(
PresentationConnectionAvailableEvent::PresentationConnectionAvailableEvent(
const AtomicString& event_type,
- const PresentationConnectionAvailableEventInit& initializer)
- : Event(event_type, initializer), connection_(initializer.connection()) {}
+ const PresentationConnectionAvailableEventInit* initializer)
+ : Event(event_type, initializer), connection_(initializer->connection()) {}
const AtomicString& PresentationConnectionAvailableEvent::InterfaceName()
const {
- return EventNames::PresentationConnectionAvailableEvent;
+ return event_interface_names::kPresentationConnectionAvailableEvent;
}
void PresentationConnectionAvailableEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.h
index f7ffa7b643d..af32dc82ed8 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.h
@@ -20,17 +20,24 @@ class PresentationConnectionAvailableEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ PresentationConnectionAvailableEvent(const AtomicString& event_type,
+ PresentationConnection*);
+ PresentationConnectionAvailableEvent(
+ const AtomicString& event_type,
+ const PresentationConnectionAvailableEventInit* initializer);
~PresentationConnectionAvailableEvent() override;
static PresentationConnectionAvailableEvent* Create(
const AtomicString& event_type,
PresentationConnection* connection) {
- return new PresentationConnectionAvailableEvent(event_type, connection);
+ return MakeGarbageCollected<PresentationConnectionAvailableEvent>(
+ event_type, connection);
}
static PresentationConnectionAvailableEvent* Create(
const AtomicString& event_type,
- const PresentationConnectionAvailableEventInit& initializer) {
- return new PresentationConnectionAvailableEvent(event_type, initializer);
+ const PresentationConnectionAvailableEventInit* initializer) {
+ return MakeGarbageCollected<PresentationConnectionAvailableEvent>(
+ event_type, initializer);
}
PresentationConnection* connection() { return connection_.Get(); }
@@ -40,22 +47,17 @@ class PresentationConnectionAvailableEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- PresentationConnectionAvailableEvent(const AtomicString& event_type,
- PresentationConnection*);
- PresentationConnectionAvailableEvent(
- const AtomicString& event_type,
- const PresentationConnectionAvailableEventInit& initializer);
-
Member<PresentationConnection> connection_;
};
-DEFINE_TYPE_CASTS(PresentationConnectionAvailableEvent,
- Event,
- event,
- event->InterfaceName() ==
- EventNames::PresentationConnectionAvailableEvent,
- event.InterfaceName() ==
- EventNames::PresentationConnectionAvailableEvent);
+DEFINE_TYPE_CASTS(
+ PresentationConnectionAvailableEvent,
+ Event,
+ event,
+ event->InterfaceName() ==
+ event_interface_names::kPresentationConnectionAvailableEvent,
+ event.InterfaceName() ==
+ event_interface_names::kPresentationConnectionAvailableEvent);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.idl
index 3cc7b0dbb8a..a692f43867f 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_available_event.idl
@@ -7,6 +7,7 @@
[
Constructor(DOMString type, PresentationConnectionAvailableEventInit eventInitDict),
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationConnectionAvailableEvent : Event {
[SameObject] readonly attribute PresentationConnection connection;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.cc
index b4d70856a06..7dc754f4013 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.cc
@@ -18,13 +18,13 @@ PresentationConnectionCloseEvent::PresentationConnectionCloseEvent(
PresentationConnectionCloseEvent::PresentationConnectionCloseEvent(
const AtomicString& event_type,
- const PresentationConnectionCloseEventInit& initializer)
+ const PresentationConnectionCloseEventInit* initializer)
: Event(event_type, initializer),
- reason_(initializer.reason()),
- message_(initializer.message()) {}
+ reason_(initializer->reason()),
+ message_(initializer->message()) {}
const AtomicString& PresentationConnectionCloseEvent::InterfaceName() const {
- return EventNames::PresentationConnectionCloseEvent;
+ return event_interface_names::kPresentationConnectionCloseEvent;
}
void PresentationConnectionCloseEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.h
index da389e2807c..e719dd6d0d2 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.h
@@ -19,19 +19,27 @@ class PresentationConnectionCloseEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
+ PresentationConnectionCloseEvent(const AtomicString& event_type,
+ const String& reason,
+ const String& message);
+ PresentationConnectionCloseEvent(
+ const AtomicString& event_type,
+ const PresentationConnectionCloseEventInit* initializer);
~PresentationConnectionCloseEvent() override = default;
static PresentationConnectionCloseEvent* Create(
const AtomicString& event_type,
const String& reason,
const String& message) {
- return new PresentationConnectionCloseEvent(event_type, reason, message);
+ return MakeGarbageCollected<PresentationConnectionCloseEvent>(
+ event_type, reason, message);
}
static PresentationConnectionCloseEvent* Create(
const AtomicString& event_type,
- const PresentationConnectionCloseEventInit& initializer) {
- return new PresentationConnectionCloseEvent(event_type, initializer);
+ const PresentationConnectionCloseEventInit* initializer) {
+ return MakeGarbageCollected<PresentationConnectionCloseEvent>(event_type,
+ initializer);
}
const String& reason() const { return reason_; }
@@ -42,13 +50,6 @@ class PresentationConnectionCloseEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- PresentationConnectionCloseEvent(const AtomicString& event_type,
- const String& reason,
- const String& message);
- PresentationConnectionCloseEvent(
- const AtomicString& event_type,
- const PresentationConnectionCloseEventInit& initializer);
-
String reason_;
String message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.idl
index c763afdf5bc..c89e56cae42 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_close_event.idl
@@ -9,6 +9,7 @@ enum PresentationConnectionCloseReason { "error", "closed", "wentaway" };
[
Constructor(DOMString type, PresentationConnectionCloseEventInit eventInitDict),
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationConnectionCloseEvent : Event {
readonly attribute PresentationConnectionCloseReason reason;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.cc
index b706fc951ad..582b9546be3 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.cc
@@ -16,7 +16,7 @@ PresentationConnectionList::PresentationConnectionList(
: ContextClient(context) {}
const AtomicString& PresentationConnectionList::InterfaceName() const {
- return EventTargetNames::PresentationConnectionList;
+ return event_target_names::kPresentationConnectionList;
}
const HeapVector<Member<ReceiverPresentationConnection>>&
@@ -29,7 +29,7 @@ void PresentationConnectionList::AddedEventListener(
RegisteredEventListener& registered_listener) {
EventTargetWithInlineData::AddedEventListener(event_type,
registered_listener);
- if (event_type == EventTypeNames::connectionavailable) {
+ if (event_type == event_type_names::kConnectionavailable) {
UseCounter::Count(
GetExecutionContext(),
WebFeature::kPresentationRequestConnectionAvailableEventListener);
@@ -55,7 +55,7 @@ bool PresentationConnectionList::RemoveConnection(
void PresentationConnectionList::DispatchConnectionAvailableEvent(
PresentationConnection* connection) {
DispatchEvent(*PresentationConnectionAvailableEvent::Create(
- EventTypeNames::connectionavailable, connection));
+ event_type_names::kConnectionavailable, connection));
}
bool PresentationConnectionList::IsEmpty() {
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.h
index ca34797c552..e0aa072dbdc 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.h
@@ -34,7 +34,7 @@ class MODULES_EXPORT PresentationConnectionList final
// PresentationConnectionList.idl implementation.
const HeapVector<Member<ReceiverPresentationConnection>>& connections() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connectionavailable);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connectionavailable, kConnectionavailable);
void AddConnection(ReceiverPresentationConnection*);
// Remove connection from connection list. Returns true if connection is
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.idl
index 6fb357214a8..3d7af600d75 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_connection_list.idl
@@ -6,6 +6,7 @@
[
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationConnectionList : EventTarget {
readonly attribute FrozenArray<PresentationConnection> connections;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.cc
index 0bb8d0c060e..3e97d5479b9 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.cc
@@ -35,7 +35,8 @@ PresentationController* PresentationController::From(LocalFrame& frame) {
// static
void PresentationController::ProvideTo(LocalFrame& frame) {
- Supplement<LocalFrame>::ProvideTo(frame, new PresentationController(frame));
+ Supplement<LocalFrame>::ProvideTo(
+ frame, MakeGarbageCollected<PresentationController>(frame));
}
// static
@@ -121,7 +122,6 @@ void PresentationController::OnDefaultPresentationStarted(
if (!presentation_ || !presentation_->defaultRequest())
return;
- PresentationRequest::RecordStartOriginTypeAccess(*GetExecutionContext());
auto* connection = ControllerPresentationConnection::Take(
this, *result->presentation_info, presentation_->defaultRequest());
// TODO(btolsch): Convert this and similar calls to just use InterfacePtrInfo
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.h
index 986fa387a4a..2d7a4b010ca 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_controller.h
@@ -14,7 +14,6 @@
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/presentation/presentation.h"
#include "third_party/blink/renderer/modules/presentation/presentation_availability_callbacks.h"
-#include "third_party/blink/renderer/modules/presentation/presentation_request.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
@@ -39,6 +38,7 @@ class MODULES_EXPORT PresentationController
public:
static const char kSupplementName[];
+ PresentationController(LocalFrame&);
~PresentationController() override;
static PresentationController* From(LocalFrame&);
@@ -78,9 +78,6 @@ class MODULES_EXPORT PresentationController
virtual void AddAvailabilityObserver(PresentationAvailabilityObserver*);
virtual void RemoveAvailabilityObserver(PresentationAvailabilityObserver*);
- protected:
- PresentationController(LocalFrame&);
-
private:
// Implementation of ContextLifecycleObserver.
void ContextDestroyed(ExecutionContext*) override;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.cc
index cfbe7e85d3a..4a0d6af3cdd 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.cc
@@ -25,7 +25,8 @@ namespace blink {
PresentationReceiver::PresentationReceiver(LocalFrame* frame)
: ContextLifecycleObserver(frame->GetDocument()),
- connection_list_(new PresentationConnectionList(frame->GetDocument())),
+ connection_list_(MakeGarbageCollected<PresentationConnectionList>(
+ frame->GetDocument())),
receiver_binding_(this) {
auto* interface_provider = GetFrame()->Client()->GetInterfaceProvider();
interface_provider->GetInterface(mojo::MakeRequest(&presentation_service_));
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.idl
index 2d19915c184..55848c41cf6 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver.idl
@@ -6,6 +6,7 @@
[
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationReceiver {
[SameObject, CallWith=ScriptState] readonly attribute Promise<PresentationConnectionList> connectionList;
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver_test.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver_test.cc
index 17200449440..e09a5126395 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver_test.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_receiver_test.cc
@@ -29,13 +29,13 @@ class MockEventListenerForPresentationReceiver : public EventListener {
return this == &other;
}
- MOCK_METHOD2(handleEvent, void(ExecutionContext* executionContext, Event*));
+ MOCK_METHOD2(Invoke, void(ExecutionContext* executionContext, Event*));
};
class PresentationReceiverTest : public testing::Test {
public:
PresentationReceiverTest()
- : connection_info_(KURL("http://example.com"), "id") {}
+ : connection_info_(KURL("https://example.com"), "id") {}
void AddConnectionavailableEventListener(EventListener*,
const PresentationReceiver*);
void VerifyConnectionListPropertyState(ScriptPromisePropertyBase::State,
@@ -60,7 +60,7 @@ void PresentationReceiverTest::AddConnectionavailableEventListener(
EventListener* event_handler,
const PresentationReceiver* receiver) {
receiver->connection_list_->addEventListener(
- EventTypeNames::connectionavailable, event_handler);
+ event_type_names::kConnectionavailable, event_handler);
}
void PresentationReceiverTest::VerifyConnectionListPropertyState(
@@ -79,12 +79,13 @@ using testing::StrictMock;
TEST_F(PresentationReceiverTest, NoConnectionUnresolvedConnectionList) {
V8TestingScope scope;
- auto* receiver = new PresentationReceiver(&scope.GetFrame());
+ auto* receiver =
+ MakeGarbageCollected<PresentationReceiver>(&scope.GetFrame());
auto* event_handler =
new StrictMock<MockEventListenerForPresentationReceiver>();
AddConnectionavailableEventListener(event_handler, receiver);
- EXPECT_CALL(*event_handler, handleEvent(testing::_, testing::_)).Times(0);
+ EXPECT_CALL(*event_handler, Invoke(testing::_, testing::_)).Times(0);
receiver->connectionList(scope.GetScriptState());
@@ -95,12 +96,13 @@ TEST_F(PresentationReceiverTest, NoConnectionUnresolvedConnectionList) {
TEST_F(PresentationReceiverTest, OneConnectionResolvedConnectionListNoEvent) {
V8TestingScope scope;
- auto* receiver = new PresentationReceiver(&scope.GetFrame());
+ auto* receiver =
+ MakeGarbageCollected<PresentationReceiver>(&scope.GetFrame());
auto* event_handler =
new StrictMock<MockEventListenerForPresentationReceiver>();
AddConnectionavailableEventListener(event_handler, receiver);
- EXPECT_CALL(*event_handler, handleEvent(testing::_, testing::_)).Times(0);
+ EXPECT_CALL(*event_handler, Invoke(testing::_, testing::_)).Times(0);
receiver->connectionList(scope.GetScriptState());
@@ -116,12 +118,13 @@ TEST_F(PresentationReceiverTest, OneConnectionResolvedConnectionListNoEvent) {
TEST_F(PresentationReceiverTest, TwoConnectionsFireOnconnectionavailableEvent) {
V8TestingScope scope;
- auto* receiver = new PresentationReceiver(&scope.GetFrame());
+ auto* receiver =
+ MakeGarbageCollected<PresentationReceiver>(&scope.GetFrame());
StrictMock<MockEventListenerForPresentationReceiver>* event_handler =
new StrictMock<MockEventListenerForPresentationReceiver>();
AddConnectionavailableEventListener(event_handler, receiver);
- EXPECT_CALL(*event_handler, handleEvent(testing::_, testing::_)).Times(1);
+ EXPECT_CALL(*event_handler, Invoke(testing::_, testing::_)).Times(1);
receiver->connectionList(scope.GetScriptState());
@@ -147,12 +150,13 @@ TEST_F(PresentationReceiverTest, TwoConnectionsFireOnconnectionavailableEvent) {
TEST_F(PresentationReceiverTest, TwoConnectionsNoEvent) {
V8TestingScope scope;
- auto* receiver = new PresentationReceiver(&scope.GetFrame());
+ auto* receiver =
+ MakeGarbageCollected<PresentationReceiver>(&scope.GetFrame());
StrictMock<MockEventListenerForPresentationReceiver>* event_handler =
new StrictMock<MockEventListenerForPresentationReceiver>();
AddConnectionavailableEventListener(event_handler, receiver);
- EXPECT_CALL(*event_handler, handleEvent(testing::_, testing::_)).Times(0);
+ EXPECT_CALL(*event_handler, Invoke(testing::_, testing::_)).Times(0);
// Receive first connection.
receiver->OnReceiverConnectionAvailable(
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_request.cc b/chromium/third_party/blink/renderer/modules/presentation/presentation_request.cc
index 8d11b2b41cc..3258500b76f 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_request.cc
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_request.cc
@@ -38,7 +38,6 @@ Settings* GetSettings(ExecutionContext* execution_context) {
}
bool IsKnownProtocolForPresentationUrl(const KURL& url) {
- // TODO(crbug.com/733381): Restrict to https + custom schemes.
return url.ProtocolIsInHTTPFamily() || url.ProtocolIs("cast") ||
url.ProtocolIs("cast-dial");
}
@@ -96,11 +95,12 @@ PresentationRequest* PresentationRequest::Create(
return nullptr;
}
- return new PresentationRequest(execution_context, parsed_urls);
+ return MakeGarbageCollected<PresentationRequest>(execution_context,
+ parsed_urls);
}
const AtomicString& PresentationRequest::InterfaceName() const {
- return EventTargetNames::PresentationRequest;
+ return event_target_names::kPresentationRequest;
}
ExecutionContext* PresentationRequest::GetExecutionContext() const {
@@ -112,7 +112,7 @@ void PresentationRequest::AddedEventListener(
RegisteredEventListener& registered_listener) {
EventTargetWithInlineData::AddedEventListener(event_type,
registered_listener);
- if (event_type == EventTypeNames::connectionavailable) {
+ if (event_type == event_type_names::kConnectionavailable) {
UseCounter::Count(
GetExecutionContext(),
WebFeature::kPresentationRequestConnectionAvailableEventListener);
@@ -132,19 +132,6 @@ bool PresentationRequest::HasPendingActivity() const {
ScriptPromisePropertyBase::kPending;
}
-// static
-void PresentationRequest::RecordStartOriginTypeAccess(
- ExecutionContext& execution_context) {
- if (execution_context.IsSecureContext()) {
- UseCounter::Count(&execution_context,
- WebFeature::kPresentationRequestStartSecureOrigin);
- } else {
- Deprecation::CountDeprecation(
- &execution_context,
- WebFeature::kPresentationRequestStartInsecureOrigin);
- }
-}
-
ScriptPromise PresentationRequest::start(ScriptState* script_state) {
ExecutionContext* execution_context = GetExecutionContext();
Settings* context_settings = GetSettings(execution_context);
@@ -171,7 +158,6 @@ ScriptPromise PresentationRequest::start(ScriptState* script_state) {
DOMExceptionCode::kInvalidStateError,
"The PresentationRequest is no longer associated to a frame."));
- RecordStartOriginTypeAccess(*execution_context);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
controller->GetPresentationService()->StartPresentation(
@@ -247,20 +233,6 @@ void PresentationRequest::Trace(blink::Visitor* visitor) {
PresentationRequest::PresentationRequest(ExecutionContext* execution_context,
const Vector<KURL>& urls)
- : ContextClient(execution_context), urls_(urls) {
- RecordConstructorOriginTypeAccess(*execution_context);
-}
-
-// static
-void PresentationRequest::RecordConstructorOriginTypeAccess(
- ExecutionContext& execution_context) {
- if (execution_context.IsSecureContext()) {
- UseCounter::Count(&execution_context,
- WebFeature::kPresentationRequestSecureOrigin);
- } else {
- UseCounter::Count(&execution_context,
- WebFeature::kPresentationRequestInsecureOrigin);
- }
-}
+ : ContextClient(execution_context), urls_(urls) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_request.h b/chromium/third_party/blink/renderer/modules/presentation/presentation_request.h
index 4c581e03c10..65d59f6ab7b 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_request.h
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_request.h
@@ -28,6 +28,7 @@ class MODULES_EXPORT PresentationRequest final
DEFINE_WRAPPERTYPEINFO();
public:
+ PresentationRequest(ExecutionContext*, const Vector<KURL>&);
~PresentationRequest() override = default;
static PresentationRequest* Create(ExecutionContext*,
@@ -44,15 +45,13 @@ class MODULES_EXPORT PresentationRequest final
// ScriptWrappable implementation.
bool HasPendingActivity() const final;
- static void RecordStartOriginTypeAccess(ExecutionContext&);
-
ScriptPromise start(ScriptState*);
ScriptPromise reconnect(ScriptState*, const String& id);
ScriptPromise getAvailability(ScriptState*);
const Vector<KURL>& Urls() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connectionavailable);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connectionavailable, kConnectionavailable);
void Trace(blink::Visitor*) override;
@@ -62,9 +61,6 @@ class MODULES_EXPORT PresentationRequest final
RegisteredEventListener&) override;
private:
- PresentationRequest(ExecutionContext*, const Vector<KURL>&);
- static void RecordConstructorOriginTypeAccess(ExecutionContext&);
-
Member<PresentationAvailabilityProperty> availability_property_;
Vector<KURL> urls_;
};
diff --git a/chromium/third_party/blink/renderer/modules/presentation/presentation_request.idl b/chromium/third_party/blink/renderer/modules/presentation/presentation_request.idl
index b8acdd19ee3..82299190a1b 100644
--- a/chromium/third_party/blink/renderer/modules/presentation/presentation_request.idl
+++ b/chromium/third_party/blink/renderer/modules/presentation/presentation_request.idl
@@ -12,6 +12,7 @@
MeasureAs=PresentationRequestConstructor,
RaisesException=Constructor,
RuntimeEnabled=Presentation,
+ SecureContext,
Exposed=Window
] interface PresentationRequest : EventTarget {
[CallWith=ScriptState, MeasureAs=PresentationRequestStart] Promise<PresentationConnection> start();
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_controller.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_controller.cc
index c460c4fbb04..7af810a8eb1 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_controller.cc
@@ -23,7 +23,8 @@ WebPushClient& PushController::ClientFrom(LocalFrame* frame) {
const char PushController::kSupplementName[] = "PushController";
void ProvidePushControllerTo(LocalFrame& frame, WebPushClient* client) {
- PushController::ProvideTo(frame, new PushController(frame, client));
+ PushController::ProvideTo(
+ frame, MakeGarbageCollected<PushController>(frame, client));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_event.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_event.cc
index b5e11cc3ae5..8353a24cd4c 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_event.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_event.cc
@@ -11,18 +11,19 @@ namespace blink {
PushEvent::PushEvent(const AtomicString& type,
PushMessageData* data,
WaitUntilObserver* observer)
- : ExtendableEvent(type, ExtendableEventInit(), observer), data_(data) {}
+ : ExtendableEvent(type, ExtendableEventInit::Create(), observer),
+ data_(data) {}
-PushEvent::PushEvent(const AtomicString& type, const PushEventInit& initializer)
+PushEvent::PushEvent(const AtomicString& type, const PushEventInit* initializer)
: ExtendableEvent(type, initializer) {
- if (initializer.hasData())
- data_ = PushMessageData::Create(initializer.data());
+ if (initializer->hasData())
+ data_ = PushMessageData::Create(initializer->data());
}
PushEvent::~PushEvent() = default;
const AtomicString& PushEvent::InterfaceName() const {
- return EventNames::PushEvent;
+ return event_interface_names::kPushEvent;
}
PushMessageData* PushEvent::data() {
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_event.h b/chromium/third_party/blink/renderer/modules/push_messaging/push_event.h
index ce17e4ca406..296a1db0828 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_event.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_event.h
@@ -24,13 +24,17 @@ class MODULES_EXPORT PushEvent final : public ExtendableEvent {
static PushEvent* Create(const AtomicString& type,
PushMessageData* data,
WaitUntilObserver* observer) {
- return new PushEvent(type, data, observer);
+ return MakeGarbageCollected<PushEvent>(type, data, observer);
}
static PushEvent* Create(const AtomicString& type,
- const PushEventInit& initializer) {
- return new PushEvent(type, initializer);
+ const PushEventInit* initializer) {
+ return MakeGarbageCollected<PushEvent>(type, initializer);
}
+ PushEvent(const AtomicString& type,
+ PushMessageData* data,
+ WaitUntilObserver* observer);
+ PushEvent(const AtomicString& type, const PushEventInit* initializer);
~PushEvent() override;
// ExtendableEvent interface.
@@ -41,11 +45,6 @@ class MODULES_EXPORT PushEvent final : public ExtendableEvent {
void Trace(blink::Visitor* visitor) override;
private:
- PushEvent(const AtomicString& type,
- PushMessageData* data,
- WaitUntilObserver* observer);
- PushEvent(const AtomicString& type, const PushEventInit& initializer);
-
Member<PushMessageData> data_;
};
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.cc
index a4760fba894..0c3cdc3a675 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.cc
@@ -51,7 +51,7 @@ Vector<String> PushManager::supportedContentEncodings() {
}
ScriptPromise PushManager::subscribe(ScriptState* script_state,
- const PushSubscriptionOptionsInit& options,
+ const PushSubscriptionOptionsInit* options,
ExceptionState& exception_state) {
if (!registration_->active())
return ScriptPromise::RejectWithDOMException(
@@ -79,13 +79,13 @@ ScriptPromise PushManager::subscribe(ScriptState* script_state,
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"Document is detached from window."));
PushController::ClientFrom(frame).Subscribe(
- registration_->WebRegistration(), web_options,
+ registration_->RegistrationId(), web_options,
LocalFrame::HasTransientUserActivation(frame,
true /* check_if_main_thread */),
std::make_unique<PushSubscriptionCallbacks>(resolver, registration_));
} else {
PushProvider()->Subscribe(
- registration_->WebRegistration(), web_options,
+ registration_->RegistrationId(), web_options,
LocalFrame::HasTransientUserActivation(nullptr,
true /* check_if_main_thread */),
std::make_unique<PushSubscriptionCallbacks>(resolver, registration_));
@@ -99,14 +99,14 @@ ScriptPromise PushManager::getSubscription(ScriptState* script_state) {
ScriptPromise promise = resolver->Promise();
PushProvider()->GetSubscription(
- registration_->WebRegistration(),
+ registration_->RegistrationId(),
std::make_unique<PushSubscriptionCallbacks>(resolver, registration_));
return promise;
}
ScriptPromise PushManager::permissionState(
ScriptState* script_state,
- const PushSubscriptionOptionsInit& options,
+ const PushSubscriptionOptionsInit* options,
ExceptionState& exception_state) {
if (auto* document =
DynamicTo<Document>(ExecutionContext::From(script_state))) {
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.h b/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.h
index 8901b90e05e..5e60a64ddc9 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_manager.h
@@ -22,26 +22,26 @@ class MODULES_EXPORT PushManager final : public ScriptWrappable {
public:
static PushManager* Create(ServiceWorkerRegistration* registration) {
- return new PushManager(registration);
+ return MakeGarbageCollected<PushManager>(registration);
}
+ explicit PushManager(ServiceWorkerRegistration* registration);
+
// Web-exposed property:
static Vector<String> supportedContentEncodings();
// Web-exposed methods:
ScriptPromise subscribe(ScriptState* script_state,
- const PushSubscriptionOptionsInit& options,
+ const PushSubscriptionOptionsInit* options,
ExceptionState& exception_state);
ScriptPromise getSubscription(ScriptState* script_state);
ScriptPromise permissionState(ScriptState* script_state,
- const PushSubscriptionOptionsInit& options,
+ const PushSubscriptionOptionsInit* options,
ExceptionState& exception_state);
void Trace(blink::Visitor* visitor) override;
private:
- explicit PushManager(ServiceWorkerRegistration* registration);
-
Member<ServiceWorkerRegistration> registration_;
};
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_manager_test.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_manager_test.cc
index a3e07d1548f..7f0321f3eca 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_manager_test.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_manager_test.cc
@@ -28,8 +28,8 @@ const uint8_t kApplicationServerKey[kApplicationServerKeyLength] = {
0xB6, 0x01, 0x20, 0xD8, 0x35, 0xA5, 0xD9, 0x3C, 0x43, 0xDF};
TEST(PushManagerTest, ValidSenderKey) {
- PushSubscriptionOptionsInit options;
- options.setApplicationServerKey(
+ PushSubscriptionOptionsInit* options = PushSubscriptionOptionsInit::Create();
+ options->setApplicationServerKey(
ArrayBufferOrArrayBufferView::FromArrayBuffer(DOMArrayBuffer::Create(
kApplicationServerKey, kApplicationServerKeyLength)));
@@ -54,9 +54,10 @@ TEST(PushManagerTest, ValidSenderKey) {
TEST(PushManagerTest, InvalidSenderKeyLength) {
uint8_t sender_key[kMaxKeyLength + 1];
memset(sender_key, 0, sizeof(sender_key));
- PushSubscriptionOptionsInit options;
- options.setApplicationServerKey(ArrayBufferOrArrayBufferView::FromArrayBuffer(
- DOMArrayBuffer::Create(sender_key, kMaxKeyLength + 1)));
+ PushSubscriptionOptionsInit* options = PushSubscriptionOptionsInit::Create();
+ options->setApplicationServerKey(
+ ArrayBufferOrArrayBufferView::FromArrayBuffer(
+ DOMArrayBuffer::Create(sender_key, kMaxKeyLength + 1)));
DummyExceptionStateForTesting exception_state;
WebPushSubscriptionOptions output =
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.cc
index 6282e7acfe5..69220f1cec7 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.cc
@@ -37,14 +37,15 @@ PushMessageData* PushMessageData::Create(
? message_data.GetAsArrayBufferView().View()->buffer()
: message_data.GetAsArrayBuffer();
- return new PushMessageData(static_cast<const char*>(buffer->Data()),
- buffer->ByteLength());
+ return MakeGarbageCollected<PushMessageData>(
+ static_cast<const char*>(buffer->Data()), buffer->ByteLength());
}
if (message_data.IsUSVString()) {
CString encoded_string = UTF8Encoding().Encode(
message_data.GetAsUSVString(), WTF::kNoUnencodables);
- return new PushMessageData(encoded_string.data(), encoded_string.length());
+ return MakeGarbageCollected<PushMessageData>(encoded_string.data(),
+ encoded_string.length());
}
DCHECK(message_data.IsNull());
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.h b/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.h
index 3288be3dbdf..11856018b35 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_message_data.h
@@ -28,6 +28,7 @@ class MODULES_EXPORT PushMessageData final : public ScriptWrappable {
static PushMessageData* Create(
const ArrayBufferOrArrayBufferViewOrUSVString& data);
+ PushMessageData(const char* data, unsigned bytes_size);
~PushMessageData() override;
DOMArrayBuffer* arrayBuffer() const;
@@ -37,8 +38,6 @@ class MODULES_EXPORT PushMessageData final : public ScriptWrappable {
String text() const;
private:
- PushMessageData(const char* data, unsigned bytes_size);
-
Vector<char> data_;
};
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc
index da7c2ff21e7..57dbbcb88cb 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.cc
@@ -45,7 +45,8 @@ PushMessagingBridge* PushMessagingBridge::From(
service_worker_registration);
if (!bridge) {
- bridge = new PushMessagingBridge(*service_worker_registration);
+ bridge =
+ MakeGarbageCollected<PushMessagingBridge>(*service_worker_registration);
Supplement<ServiceWorkerRegistration>::ProvideTo(
*service_worker_registration, bridge);
}
@@ -63,7 +64,7 @@ const char PushMessagingBridge::kSupplementName[] = "PushMessagingBridge";
ScriptPromise PushMessagingBridge::GetPermissionState(
ScriptState* script_state,
- const PushSubscriptionOptionsInit& options) {
+ const PushSubscriptionOptionsInit* options) {
ExecutionContext* context = ExecutionContext::From(script_state);
if (!permission_service_) {
ConnectToPermissionService(context,
@@ -78,7 +79,7 @@ ScriptPromise PushMessagingBridge::GetPermissionState(
// receiving a push message. Permission is denied without this setting.
//
// TODO(peter): Would it be better to resolve DENIED rather than rejecting?
- if (!options.hasUserVisibleOnly() || !options.userVisibleOnly()) {
+ if (!options->hasUserVisibleOnly() || !options->userVisibleOnly()) {
resolver->Reject(DOMException::Create(DOMExceptionCode::kNotSupportedError,
kUserVisibleOnlyRequired));
return promise;
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.h b/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.h
index f2690b06198..e5082216b29 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_messaging_bridge.h
@@ -33,15 +33,14 @@ class PushMessagingBridge final
static PushMessagingBridge* From(ServiceWorkerRegistration* registration);
+ explicit PushMessagingBridge(ServiceWorkerRegistration& registration);
virtual ~PushMessagingBridge();
// Asynchronously determines the permission state for the current origin.
ScriptPromise GetPermissionState(ScriptState* script_state,
- const PushSubscriptionOptionsInit& options);
+ const PushSubscriptionOptionsInit* options);
private:
- explicit PushMessagingBridge(ServiceWorkerRegistration& registration);
-
// Method to be invoked when the permission status has been retrieved from the
// permission service. Will settle the given |resolver|.
void DidGetPermissionState(ScriptPromiseResolver* resolver,
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.cc
index 2e2032d8723..4d6777177c5 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.cc
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/modules/push_messaging/push_subscription_options.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
namespace blink {
@@ -51,7 +52,8 @@ PushSubscription* PushSubscription::Take(
ServiceWorkerRegistration* service_worker_registration) {
if (!push_subscription)
return nullptr;
- return new PushSubscription(*push_subscription, service_worker_registration);
+ return MakeGarbageCollected<PushSubscription>(*push_subscription,
+ service_worker_registration);
}
void PushSubscription::Dispose(WebPushSubscription* push_subscription) {
@@ -64,10 +66,12 @@ PushSubscription::PushSubscription(
ServiceWorkerRegistration* service_worker_registration)
: endpoint_(subscription.endpoint),
options_(PushSubscriptionOptions::Create(subscription.options)),
- p256dh_(DOMArrayBuffer::Create(subscription.p256dh.Data(),
- subscription.p256dh.size())),
- auth_(DOMArrayBuffer::Create(subscription.auth.Data(),
- subscription.auth.size())),
+ p256dh_(DOMArrayBuffer::Create(
+ subscription.p256dh.Data(),
+ SafeCast<unsigned>(subscription.p256dh.size()))),
+ auth_(
+ DOMArrayBuffer::Create(subscription.auth.Data(),
+ SafeCast<unsigned>(subscription.auth.size()))),
service_worker_registration_(service_worker_registration) {}
PushSubscription::~PushSubscription() = default;
@@ -98,7 +102,7 @@ ScriptPromise PushSubscription::unsubscribe(ScriptState* script_state) {
DCHECK(web_push_provider);
web_push_provider->Unsubscribe(
- service_worker_registration_->WebRegistration(),
+ service_worker_registration_->RegistrationId(),
std::make_unique<CallbackPromiseAdapter<bool, PushError>>(resolver));
return promise;
}
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.h b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.h
index f6c00acba9c..0fbed77472b 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription.h
@@ -35,6 +35,8 @@ class MODULES_EXPORT PushSubscription final : public ScriptWrappable {
ServiceWorkerRegistration* service_worker_registration);
static void Dispose(WebPushSubscription* subscription_raw);
+ PushSubscription(const WebPushSubscription& subscription,
+ ServiceWorkerRegistration* service_worker_registration);
~PushSubscription() override;
KURL endpoint() const { return endpoint_; }
@@ -53,9 +55,6 @@ class MODULES_EXPORT PushSubscription final : public ScriptWrappable {
FRIEND_TEST_ALL_PREFIXES(PushSubscriptionTest,
SerializesToBase64URLWithoutPadding);
- PushSubscription(const WebPushSubscription& subscription,
- ServiceWorkerRegistration* service_worker_registration);
-
KURL endpoint_;
Member<PushSubscriptionOptions> options_;
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.cc b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.cc
index 0a7c4810557..f402d80ea63 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -62,22 +63,23 @@ String BufferSourceToString(
// static
WebPushSubscriptionOptions PushSubscriptionOptions::ToWeb(
- const PushSubscriptionOptionsInit& options,
+ const PushSubscriptionOptionsInit* options,
ExceptionState& exception_state) {
WebPushSubscriptionOptions web_options;
- web_options.user_visible_only = options.userVisibleOnly();
- if (options.hasApplicationServerKey())
+ web_options.user_visible_only = options->userVisibleOnly();
+ if (options->hasApplicationServerKey()) {
web_options.application_server_key =
- BufferSourceToString(options.applicationServerKey(), exception_state);
+ BufferSourceToString(options->applicationServerKey(), exception_state);
+ }
return web_options;
}
PushSubscriptionOptions::PushSubscriptionOptions(
const WebPushSubscriptionOptions& options)
: user_visible_only_(options.user_visible_only),
- application_server_key_(
- DOMArrayBuffer::Create(options.application_server_key.Latin1().data(),
- options.application_server_key.length())) {}
+ application_server_key_(DOMArrayBuffer::Create(
+ options.application_server_key.Latin1().data(),
+ SafeCast<unsigned>(options.application_server_key.length()))) {}
void PushSubscriptionOptions::Trace(blink::Visitor* visitor) {
visitor->Trace(application_server_key_);
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.h b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.h
index f3b27dbe058..baca043559a 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/push_subscription_options.h
@@ -23,14 +23,16 @@ class PushSubscriptionOptions final : public ScriptWrappable {
// Converts developer-provided dictionary to WebPushSubscriptionOptions.
// Throws if applicationServerKey is invalid.
MODULES_EXPORT static WebPushSubscriptionOptions ToWeb(
- const PushSubscriptionOptionsInit& options,
+ const PushSubscriptionOptionsInit* options,
ExceptionState& exception_state);
static PushSubscriptionOptions* Create(
const WebPushSubscriptionOptions& options) {
- return new PushSubscriptionOptions(options);
+ return MakeGarbageCollected<PushSubscriptionOptions>(options);
}
+ explicit PushSubscriptionOptions(const WebPushSubscriptionOptions& options);
+
bool userVisibleOnly() const { return user_visible_only_; }
// Mutable by web developer. See https://github.com/w3c/push-api/issues/198.
@@ -41,8 +43,6 @@ class PushSubscriptionOptions final : public ScriptWrappable {
void Trace(blink::Visitor* visitor) override;
private:
- explicit PushSubscriptionOptions(const WebPushSubscriptionOptions& options);
-
bool user_visible_only_;
Member<DOMArrayBuffer> application_server_key_;
};
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_global_scope_push.h b/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_global_scope_push.h
index 04eb0f3a5d4..2411e98498a 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_global_scope_push.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_global_scope_push.h
@@ -11,7 +11,7 @@ namespace blink {
class ServiceWorkerGlobalScopePush {
public:
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(push);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(push, kPush);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.cc b/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.cc
index ac32d649a11..25eb7810a74 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.cc
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.cc
@@ -24,7 +24,8 @@ ServiceWorkerRegistrationPush& ServiceWorkerRegistrationPush::From(
Supplement<ServiceWorkerRegistration>::From<
ServiceWorkerRegistrationPush>(registration);
if (!supplement) {
- supplement = new ServiceWorkerRegistrationPush(&registration);
+ supplement =
+ MakeGarbageCollected<ServiceWorkerRegistrationPush>(&registration);
ProvideTo(registration, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.h b/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.h
index 16a0120f985..b1d7f38c404 100644
--- a/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.h
+++ b/chromium/third_party/blink/renderer/modules/push_messaging/service_worker_registration_push.h
@@ -23,6 +23,8 @@ class ServiceWorkerRegistrationPush final
public:
static const char kSupplementName[];
+ explicit ServiceWorkerRegistrationPush(
+ ServiceWorkerRegistration* registration);
virtual ~ServiceWorkerRegistrationPush();
static ServiceWorkerRegistrationPush& From(
ServiceWorkerRegistration& registration);
@@ -33,9 +35,6 @@ class ServiceWorkerRegistrationPush final
void Trace(blink::Visitor* visitor) override;
private:
- explicit ServiceWorkerRegistrationPush(
- ServiceWorkerRegistration* registration);
-
Member<ServiceWorkerRegistration> registration_;
Member<PushManager> push_manager_;
};
diff --git a/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_info.h b/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_info.h
index 57e26d4d181..a52c31890f8 100644
--- a/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_info.h
+++ b/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_info.h
@@ -52,7 +52,11 @@ class DeprecatedStorageInfo final : public ScriptWrappable {
kPersistent,
};
- static DeprecatedStorageInfo* Create() { return new DeprecatedStorageInfo(); }
+ static DeprecatedStorageInfo* Create() {
+ return MakeGarbageCollected<DeprecatedStorageInfo>();
+ }
+
+ DeprecatedStorageInfo();
void queryUsageAndQuota(ScriptState*,
int storage_type,
@@ -68,8 +72,6 @@ class DeprecatedStorageInfo final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- DeprecatedStorageInfo();
-
DeprecatedStorageQuota* GetStorageQuota(int storage_type);
mutable Member<DeprecatedStorageQuota> temporary_storage_;
diff --git a/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.cc b/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.cc
index f0f64389878..f2f784b9bb2 100644
--- a/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.cc
+++ b/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.cc
@@ -42,13 +42,16 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/quota/dom_error.h"
#include "third_party/blink/renderer/modules/quota/quota_utils.h"
+#include "third_party/blink/renderer/modules/quota/storage_estimate.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
using mojom::StorageType;
+using mojom::blink::UsageBreakdownPtr;
namespace {
@@ -68,7 +71,8 @@ void DeprecatedQueryStorageUsageAndQuotaCallback(
V8PersistentCallbackFunction<V8StorageErrorCallback>* error_callback,
mojom::QuotaStatusCode status_code,
int64_t usage_in_bytes,
- int64_t quota_in_bytes) {
+ int64_t quota_in_bytes,
+ UsageBreakdownPtr usage_breakdown) {
if (status_code != mojom::QuotaStatusCode::kOk) {
if (error_callback) {
error_callback->InvokeAndReportException(nullptr,
@@ -156,7 +160,8 @@ void DeprecatedStorageQuota::queryUsageAndQuota(
.QueryStorageUsageAndQuota(
WrapRefCounted(security_origin), storage_type,
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
- std::move(callback), mojom::QuotaStatusCode::kErrorAbort, 0, 0));
+ std::move(callback), mojom::QuotaStatusCode::kErrorAbort, 0, 0,
+ nullptr));
}
void DeprecatedStorageQuota::requestQuota(
@@ -198,8 +203,11 @@ void DeprecatedStorageQuota::requestQuota(
mojom::blink::QuotaDispatcherHost& DeprecatedStorageQuota::GetQuotaHost(
ExecutionContext* execution_context) {
if (!quota_host_) {
- ConnectToQuotaDispatcherHost(execution_context,
- mojo::MakeRequest(&quota_host_));
+ ConnectToQuotaDispatcherHost(
+ execution_context,
+ mojo::MakeRequest(&quota_host_,
+ execution_context->GetTaskRunner(
+ blink::TaskType::kInternalDefault)));
}
return *quota_host_;
}
diff --git a/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.h b/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.h
index 0d5bb07f26d..49037321cde 100644
--- a/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.h
+++ b/chromium/third_party/blink/renderer/modules/quota/deprecated_storage_quota.h
@@ -54,13 +54,15 @@ class DeprecatedStorageQuota final : public ScriptWrappable {
};
static DeprecatedStorageQuota* Create(Type type) {
- return new DeprecatedStorageQuota(type);
+ return MakeGarbageCollected<DeprecatedStorageQuota>(type);
}
static void EnqueueStorageErrorCallback(ScriptState*,
V8StorageErrorCallback*,
DOMExceptionCode);
+ explicit DeprecatedStorageQuota(Type);
+
void queryUsageAndQuota(ScriptState*,
V8StorageUsageCallback*,
V8StorageErrorCallback* = nullptr);
@@ -71,8 +73,6 @@ class DeprecatedStorageQuota final : public ScriptWrappable {
V8StorageErrorCallback* = nullptr);
private:
- explicit DeprecatedStorageQuota(Type);
-
// Binds the interface (if not already bound) with the given interface
// provider, and returns it,
mojom::blink::QuotaDispatcherHost& GetQuotaHost(ExecutionContext*);
diff --git a/chromium/third_party/blink/renderer/modules/quota/dom_error.cc b/chromium/third_party/blink/renderer/modules/quota/dom_error.cc
index 0a28ba7ea3f..7cc2ce8b1ef 100644
--- a/chromium/third_party/blink/renderer/modules/quota/dom_error.cc
+++ b/chromium/third_party/blink/renderer/modules/quota/dom_error.cc
@@ -32,10 +32,10 @@ DOMError* DOMError::Create(mojom::QuotaStatusCode status_code) {
ExceptionCode exception_code = static_cast<ExceptionCode>(status_code);
if (IsDOMExceptionCode(exception_code)) {
DOMExceptionCode code = static_cast<DOMExceptionCode>(exception_code);
- return new DOMError(DOMException::GetErrorName(code),
- DOMException::GetErrorMessage(code));
+ return MakeGarbageCollected<DOMError>(DOMException::GetErrorName(code),
+ DOMException::GetErrorMessage(code));
}
- return new DOMError("UnknownError", "Unknown error.");
+ return MakeGarbageCollected<DOMError>("UnknownError", "Unknown error.");
}
DOMError::~DOMError() = default;
diff --git a/chromium/third_party/blink/renderer/modules/quota/dom_error.h b/chromium/third_party/blink/renderer/modules/quota/dom_error.h
index b0f902e9da8..8ea2baffc08 100644
--- a/chromium/third_party/blink/renderer/modules/quota/dom_error.h
+++ b/chromium/third_party/blink/renderer/modules/quota/dom_error.h
@@ -39,25 +39,26 @@ class MODULES_EXPORT DOMError : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static DOMError* Create(const String& name) { return new DOMError(name); }
+ static DOMError* Create(const String& name) {
+ return MakeGarbageCollected<DOMError>(name);
+ }
static DOMError* Create(const String& name, const String& message) {
- return new DOMError(name, message);
+ return MakeGarbageCollected<DOMError>(name, message);
}
static DOMError* Create(DOMExceptionCode exception_code) {
- return new DOMError(DOMException::GetErrorName(exception_code),
- DOMException::GetErrorMessage(exception_code));
+ return MakeGarbageCollected<DOMError>(
+ DOMException::GetErrorName(exception_code),
+ DOMException::GetErrorMessage(exception_code));
}
static DOMError* Create(mojom::QuotaStatusCode status_code);
+ explicit DOMError(const String& name);
+ DOMError(const String& name, const String& message);
~DOMError() override;
const String& name() const { return name_; }
const String& message() const { return message_; }
- protected:
- explicit DOMError(const String& name);
- DOMError(const String& name, const String& message);
-
private:
const String name_;
const String message_;
diff --git a/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.cc b/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.cc
index b80df9ffdfb..c8730c81ddd 100644
--- a/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.cc
+++ b/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.cc
@@ -47,7 +47,7 @@ DOMWindowQuota& DOMWindowQuota::From(LocalDOMWindow& window) {
DOMWindowQuota* supplement =
Supplement<LocalDOMWindow>::From<DOMWindowQuota>(window);
if (!supplement) {
- supplement = new DOMWindowQuota(window);
+ supplement = MakeGarbageCollected<DOMWindowQuota>(window);
ProvideTo(window, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.h b/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.h
index eab3c417376..bfd2e97b0fa 100644
--- a/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.h
+++ b/chromium/third_party/blink/renderer/modules/quota/dom_window_quota.h
@@ -46,6 +46,8 @@ class DOMWindowQuota final : public GarbageCollected<DOMWindowQuota>,
public:
static const char kSupplementName[];
+ explicit DOMWindowQuota(LocalDOMWindow&);
+
static DOMWindowQuota& From(LocalDOMWindow&);
static DeprecatedStorageInfo* webkitStorageInfo(LocalDOMWindow&);
DeprecatedStorageInfo* webkitStorageInfo() const;
@@ -53,8 +55,6 @@ class DOMWindowQuota final : public GarbageCollected<DOMWindowQuota>,
void Trace(blink::Visitor*) override;
private:
- explicit DOMWindowQuota(LocalDOMWindow&);
-
mutable Member<DeprecatedStorageInfo> storage_info_;
};
diff --git a/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.cc b/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.cc
index 4438e77ceb8..0c9e97b3ac6 100644
--- a/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.cc
+++ b/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.cc
@@ -45,7 +45,7 @@ NavigatorStorageQuota& NavigatorStorageQuota::From(Navigator& navigator) {
NavigatorStorageQuota* supplement =
Supplement<Navigator>::From<NavigatorStorageQuota>(navigator);
if (!supplement) {
- supplement = new NavigatorStorageQuota(navigator);
+ supplement = MakeGarbageCollected<NavigatorStorageQuota>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -82,7 +82,7 @@ DeprecatedStorageQuota* NavigatorStorageQuota::webkitPersistentStorage() const {
StorageManager* NavigatorStorageQuota::storage() const {
if (!storage_manager_)
- storage_manager_ = new StorageManager();
+ storage_manager_ = MakeGarbageCollected<StorageManager>();
return storage_manager_.Get();
}
diff --git a/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.h b/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.h
index 40b2ec4a311..a79d60a862b 100644
--- a/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.h
+++ b/chromium/third_party/blink/renderer/modules/quota/navigator_storage_quota.h
@@ -58,11 +58,11 @@ class NavigatorStorageQuota final
DeprecatedStorageQuota* webkitPersistentStorage() const;
StorageManager* storage() const;
+ explicit NavigatorStorageQuota(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorStorageQuota(Navigator&);
-
mutable Member<DeprecatedStorageQuota> temporary_storage_;
mutable Member<DeprecatedStorageQuota> persistent_storage_;
mutable Member<StorageManager> storage_manager_;
diff --git a/chromium/third_party/blink/renderer/modules/quota/storage_estimate.idl b/chromium/third_party/blink/renderer/modules/quota/storage_estimate.idl
index 3b38d0197a6..46b9a7326ff 100644
--- a/chromium/third_party/blink/renderer/modules/quota/storage_estimate.idl
+++ b/chromium/third_party/blink/renderer/modules/quota/storage_estimate.idl
@@ -7,4 +7,5 @@
dictionary StorageEstimate {
unsigned long long usage;
unsigned long long quota;
+ [RuntimeEnabled=StorageQuotaDetails] StorageUsageDetails usageDetails;
};
diff --git a/chromium/third_party/blink/renderer/modules/quota/storage_manager.cc b/chromium/third_party/blink/renderer/modules/quota/storage_manager.cc
index 609ec79ad5c..764d93a3e68 100644
--- a/chromium/third_party/blink/renderer/modules/quota/storage_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/quota/storage_manager.cc
@@ -6,6 +6,7 @@
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/mojom/quota/quota_types.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_storage_estimate.h"
@@ -25,6 +26,7 @@ namespace blink {
using mojom::blink::PermissionName;
using mojom::blink::PermissionService;
using mojom::blink::PermissionStatus;
+using mojom::blink::UsageBreakdownPtr;
namespace {
@@ -34,7 +36,8 @@ const char kUniqueOriginErrorMessage[] =
void QueryStorageUsageAndQuotaCallback(ScriptPromiseResolver* resolver,
mojom::QuotaStatusCode status_code,
int64_t usage_in_bytes,
- int64_t quota_in_bytes) {
+ int64_t quota_in_bytes,
+ UsageBreakdownPtr usage_breakdown) {
if (status_code != mojom::QuotaStatusCode::kOk) {
// TODO(sashab): Replace this with a switch statement, and remove the enum
// values from QuotaStatusCode.
@@ -43,9 +46,30 @@ void QueryStorageUsageAndQuotaCallback(ScriptPromiseResolver* resolver,
return;
}
- StorageEstimate estimate;
- estimate.setUsage(usage_in_bytes);
- estimate.setQuota(quota_in_bytes);
+ StorageEstimate* estimate = StorageEstimate::Create();
+ estimate->setUsage(usage_in_bytes);
+ estimate->setQuota(quota_in_bytes);
+
+ // We only want to show usage details for systems that are used by the app,
+ // this way we do not create any web compatibility issues by unecessarily
+ // exposing obsoleted/proprietary storage systems, but also report when
+ // those systems are in use.
+ StorageUsageDetails* details = StorageUsageDetails::Create();
+ if (usage_breakdown->appcache) {
+ details->setApplicationCache(usage_breakdown->appcache);
+ }
+ if (usage_breakdown->indexedDatabase) {
+ details->setIndexedDB(usage_breakdown->indexedDatabase);
+ }
+ if (usage_breakdown->serviceWorkerCache) {
+ details->setCaches(usage_breakdown->serviceWorkerCache);
+ }
+ if (usage_breakdown->serviceWorker) {
+ details->setServiceWorkerRegistrations(usage_breakdown->serviceWorker);
+ }
+
+ estimate->setUsageDetails(details);
+
resolver->Resolve(estimate);
}
@@ -115,7 +139,8 @@ ScriptPromise StorageManager::estimate(ScriptState* script_state) {
.QueryStorageUsageAndQuota(
WrapRefCounted(security_origin), mojom::StorageType::kTemporary,
mojo::WrapCallbackWithDefaultInvokeIfNotRun(
- std::move(callback), mojom::QuotaStatusCode::kErrorAbort, 0, 0));
+ std::move(callback), mojom::QuotaStatusCode::kErrorAbort, 0, 0,
+ nullptr));
return promise;
}
diff --git a/chromium/third_party/blink/renderer/modules/quota/storage_usage_details.idl b/chromium/third_party/blink/renderer/modules/quota/storage_usage_details.idl
new file mode 100644
index 00000000000..4163a9a495b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/quota/storage_usage_details.idl
@@ -0,0 +1,13 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://storage.spec.whatwg.org/#api
+
+dictionary StorageUsageDetails {
+ unsigned long long applicationCache;
+ unsigned long long indexedDB;
+ unsigned long long caches;
+ unsigned long long serviceWorkerRegistrations;
+ unsigned long long websql;
+};
diff --git a/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.cc b/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.cc
index 75d647f4ed6..4958c37f581 100644
--- a/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.cc
+++ b/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.cc
@@ -45,7 +45,7 @@ WorkerNavigatorStorageQuota& WorkerNavigatorStorageQuota::From(
WorkerNavigatorStorageQuota* supplement =
Supplement<WorkerNavigator>::From<WorkerNavigatorStorageQuota>(navigator);
if (!supplement) {
- supplement = new WorkerNavigatorStorageQuota();
+ supplement = MakeGarbageCollected<WorkerNavigatorStorageQuota>();
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -58,7 +58,7 @@ StorageManager* WorkerNavigatorStorageQuota::storage(
StorageManager* WorkerNavigatorStorageQuota::storage() const {
if (!storage_manager_)
- storage_manager_ = new StorageManager();
+ storage_manager_ = MakeGarbageCollected<StorageManager>();
return storage_manager_.Get();
}
diff --git a/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.h b/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.h
index b3250073a6d..d87758f5387 100644
--- a/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.h
+++ b/chromium/third_party/blink/renderer/modules/quota/worker_navigator_storage_quota.h
@@ -54,11 +54,11 @@ class WorkerNavigatorStorageQuota final
StorageManager* storage() const;
+ explicit WorkerNavigatorStorageQuota();
+
void Trace(blink::Visitor*) override;
private:
- explicit WorkerNavigatorStorageQuota();
-
mutable Member<StorageManager> storage_manager_;
};
diff --git a/chromium/third_party/blink/renderer/modules/remoteplayback/html_media_element_remote_playback.cc b/chromium/third_party/blink/renderer/modules/remoteplayback/html_media_element_remote_playback.cc
index b77769d5b29..617d273383b 100644
--- a/chromium/third_party/blink/renderer/modules/remoteplayback/html_media_element_remote_playback.cc
+++ b/chromium/third_party/blink/renderer/modules/remoteplayback/html_media_element_remote_playback.cc
@@ -16,7 +16,7 @@ namespace blink {
bool HTMLMediaElementRemotePlayback::FastHasAttribute(
const QualifiedName& name,
const HTMLMediaElement& element) {
- DCHECK(name == HTMLNames::disableremoteplaybackAttr);
+ DCHECK(name == html_names::kDisableremoteplaybackAttr);
return element.FastHasAttribute(name);
}
@@ -25,7 +25,7 @@ void HTMLMediaElementRemotePlayback::SetBooleanAttribute(
const QualifiedName& name,
HTMLMediaElement& element,
bool value) {
- DCHECK(name == HTMLNames::disableremoteplaybackAttr);
+ DCHECK(name == html_names::kDisableremoteplaybackAttr);
element.SetBooleanAttribute(name, value);
HTMLMediaElementRemotePlayback& self =
@@ -41,7 +41,7 @@ HTMLMediaElementRemotePlayback& HTMLMediaElementRemotePlayback::From(
Supplement<HTMLMediaElement>::From<HTMLMediaElementRemotePlayback>(
element);
if (!supplement) {
- supplement = new HTMLMediaElementRemotePlayback();
+ supplement = MakeGarbageCollected<HTMLMediaElementRemotePlayback>();
ProvideTo(element, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.cc b/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.cc
index d20885bc586..bc20e505cbb 100644
--- a/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.cc
+++ b/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.cc
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/modules/presentation/presentation_controller.h"
#include "third_party/blink/renderer/modules/remoteplayback/availability_callback_wrapper.h"
#include "third_party/blink/renderer/platform/memory_coordinator.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
namespace blink {
@@ -58,8 +59,8 @@ KURL GetAvailabilityUrl(const WebURL& source, bool is_source_supported) {
// remote-playback://<encoded-data> where |encoded-data| is base64 URL
// encoded string representation of the source URL.
std::string source_string = source.GetString().Utf8();
- String encoded_source =
- WTF::Base64URLEncode(source_string.data(), source_string.length());
+ String encoded_source = WTF::Base64URLEncode(
+ source_string.data(), SafeCast<unsigned>(source_string.length()));
return KURL("remote-playback://" + encoded_source);
}
@@ -72,7 +73,7 @@ bool IsBackgroundAvailabilityMonitoringDisabled() {
// static
RemotePlayback* RemotePlayback::Create(HTMLMediaElement& element) {
- return new RemotePlayback(element);
+ return MakeGarbageCollected<RemotePlayback>(element);
}
RemotePlayback::RemotePlayback(HTMLMediaElement& element)
@@ -86,7 +87,7 @@ RemotePlayback::RemotePlayback(HTMLMediaElement& element)
presentation_connection_binding_(this) {}
const AtomicString& RemotePlayback::InterfaceName() const {
- return EventTargetNames::RemotePlayback;
+ return event_target_names::kRemotePlayback;
}
ExecutionContext* RemotePlayback::GetExecutionContext() const {
@@ -99,7 +100,8 @@ ScriptPromise RemotePlayback::watchAvailability(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- if (media_element_->FastHasAttribute(HTMLNames::disableremoteplaybackAttr)) {
+ if (media_element_->FastHasAttribute(
+ html_names::kDisableremoteplaybackAttr)) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"disableRemotePlayback attribute is present."));
@@ -129,7 +131,8 @@ ScriptPromise RemotePlayback::cancelWatchAvailability(ScriptState* script_state,
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- if (media_element_->FastHasAttribute(HTMLNames::disableremoteplaybackAttr)) {
+ if (media_element_->FastHasAttribute(
+ html_names::kDisableremoteplaybackAttr)) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"disableRemotePlayback attribute is present."));
@@ -152,7 +155,8 @@ ScriptPromise RemotePlayback::cancelWatchAvailability(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- if (media_element_->FastHasAttribute(HTMLNames::disableremoteplaybackAttr)) {
+ if (media_element_->FastHasAttribute(
+ html_names::kDisableremoteplaybackAttr)) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"disableRemotePlayback attribute is present."));
@@ -170,7 +174,8 @@ ScriptPromise RemotePlayback::prompt(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- if (media_element_->FastHasAttribute(HTMLNames::disableremoteplaybackAttr)) {
+ if (media_element_->FastHasAttribute(
+ html_names::kDisableremoteplaybackAttr)) {
resolver->Reject(
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"disableRemotePlayback attribute is present."));
@@ -348,7 +353,7 @@ void RemotePlayback::StateChanged(WebRemotePlaybackState state) {
state_ = state;
switch (state_) {
case WebRemotePlaybackState::kConnecting:
- DispatchEvent(*Event::Create(EventTypeNames::connecting));
+ DispatchEvent(*Event::Create(event_type_names::kConnecting));
if (RuntimeEnabledFeatures::NewRemotePlaybackPipelineEnabled()) {
if (media_element_->IsHTMLVideoElement()) {
// TODO(xjz): Pass the remote device name.
@@ -358,10 +363,10 @@ void RemotePlayback::StateChanged(WebRemotePlaybackState state) {
}
break;
case WebRemotePlaybackState::kConnected:
- DispatchEvent(*Event::Create(EventTypeNames::connect));
+ DispatchEvent(*Event::Create(event_type_names::kConnect));
break;
case WebRemotePlaybackState::kDisconnected:
- DispatchEvent(*Event::Create(EventTypeNames::disconnect));
+ DispatchEvent(*Event::Create(event_type_names::kDisconnect));
if (RuntimeEnabledFeatures::NewRemotePlaybackPipelineEnabled()) {
if (media_element_->IsHTMLVideoElement()) {
ToHTMLVideoElement(media_element_)
diff --git a/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.h b/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.h
index 9e5a48d9ada..bed56ca4273 100644
--- a/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.h
+++ b/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback.h
@@ -57,6 +57,8 @@ class MODULES_EXPORT RemotePlayback final
static RemotePlayback* Create(HTMLMediaElement&);
+ explicit RemotePlayback(HTMLMediaElement&);
+
// Notifies this object that disableRemotePlayback attribute was set on the
// corresponding media element.
void RemotePlaybackDisabled();
@@ -124,9 +126,9 @@ class MODULES_EXPORT RemotePlayback final
// ContextLifecycleObserver implementation.
void ContextDestroyed(ExecutionContext*) override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connecting);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connecting, kConnecting);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect, kDisconnect);
void Trace(blink::Visitor*) override;
@@ -135,8 +137,6 @@ class MODULES_EXPORT RemotePlayback final
friend class RemotePlaybackTest;
friend class MediaControlsImplTest;
- explicit RemotePlayback(HTMLMediaElement&);
-
// Calls the specified availability callback with the current availability.
// Need a void() method to post it as a task.
void NotifyInitialAvailability(int callback_id);
diff --git a/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback_test.cc b/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback_test.cc
index f283e8f2561..4c000cc6816 100644
--- a/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback_test.cc
+++ b/chromium/third_party/blink/renderer/modules/remoteplayback/remote_playback_test.cc
@@ -47,7 +47,7 @@ class MockEventListenerForRemotePlayback : public EventListener {
return this == &other;
}
- MOCK_METHOD2(handleEvent, void(ExecutionContext* executionContext, Event*));
+ MOCK_METHOD2(Invoke, void(ExecutionContext* executionContext, Event*));
};
class MockPresentationController final : public PresentationController {
@@ -199,17 +199,16 @@ TEST_F(RemotePlaybackTest, StateChangeEvents) {
auto* disconnect_handler =
new testing::StrictMock<MockEventListenerForRemotePlayback>();
- remote_playback->addEventListener(EventTypeNames::connecting,
+ remote_playback->addEventListener(event_type_names::kConnecting,
connecting_handler);
- remote_playback->addEventListener(EventTypeNames::connect, connect_handler);
- remote_playback->addEventListener(EventTypeNames::disconnect,
+ remote_playback->addEventListener(event_type_names::kConnect,
+ connect_handler);
+ remote_playback->addEventListener(event_type_names::kDisconnect,
disconnect_handler);
- EXPECT_CALL(*connecting_handler, handleEvent(testing::_, testing::_))
- .Times(1);
- EXPECT_CALL(*connect_handler, handleEvent(testing::_, testing::_)).Times(1);
- EXPECT_CALL(*disconnect_handler, handleEvent(testing::_, testing::_))
- .Times(1);
+ EXPECT_CALL(*connecting_handler, Invoke(testing::_, testing::_)).Times(1);
+ EXPECT_CALL(*connect_handler, Invoke(testing::_, testing::_)).Times(1);
+ EXPECT_CALL(*disconnect_handler, Invoke(testing::_, testing::_)).Times(1);
SetState(remote_playback, WebRemotePlaybackState::kConnecting);
SetState(remote_playback, WebRemotePlaybackState::kConnecting);
@@ -248,7 +247,7 @@ TEST_F(RemotePlaybackTest,
remote_playback->prompt(scope.GetScriptState())
.Then(resolve->Bind(), reject->Bind());
HTMLMediaElementRemotePlayback::SetBooleanAttribute(
- HTMLNames::disableremoteplaybackAttr, *element, true);
+ html_names::kDisableremoteplaybackAttr, *element, true);
// Runs pending promises.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
@@ -289,7 +288,7 @@ TEST_F(RemotePlaybackTest, DisableRemotePlaybackCancelsAvailabilityCallbacks) {
.Then(resolve->Bind(), reject->Bind());
HTMLMediaElementRemotePlayback::SetBooleanAttribute(
- HTMLNames::disableremoteplaybackAttr, *element, true);
+ html_names::kDisableremoteplaybackAttr, *element, true);
// Runs pending promises.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
@@ -386,7 +385,7 @@ TEST_F(RemotePlaybackTest, IsListening) {
LocalFrame& frame = page_holder->GetFrame();
MockPresentationController* mock_controller =
- new MockPresentationController(frame);
+ MakeGarbageCollected<MockPresentationController>(frame);
Supplement<LocalFrame>::ProvideTo(
frame, static_cast<PresentationController*>(mock_controller));
diff --git a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc
index 2af9f927629..f3bcbaceab8 100644
--- a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc
+++ b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.cc
@@ -100,7 +100,8 @@ ScreenOrientation* ScreenOrientation::Create(LocalFrame* frame) {
if (!ScreenOrientationControllerImpl::From(*frame))
return nullptr;
- ScreenOrientation* orientation = new ScreenOrientation(frame);
+ ScreenOrientation* orientation =
+ MakeGarbageCollected<ScreenOrientation>(frame);
DCHECK(orientation->Controller());
// FIXME: ideally, we would like to provide the ScreenOrientationController
// the case where it is not defined but for the moment, it is eagerly
@@ -119,7 +120,7 @@ ScreenOrientation::ScreenOrientation(LocalFrame* frame)
ScreenOrientation::~ScreenOrientation() = default;
const WTF::AtomicString& ScreenOrientation::InterfaceName() const {
- return EventTargetNames::ScreenOrientation;
+ return event_target_names::kScreenOrientation;
}
ExecutionContext* ScreenOrientation::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.h b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.h
index 232abdb1f01..49527e7c19e 100644
--- a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.h
+++ b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation.h
@@ -29,6 +29,7 @@ class ScreenOrientation final : public EventTargetWithInlineData,
public:
static ScreenOrientation* Create(LocalFrame*);
+ explicit ScreenOrientation(LocalFrame*);
~ScreenOrientation() override;
// EventTarget implementation.
@@ -44,7 +45,7 @@ class ScreenOrientation final : public EventTargetWithInlineData,
ScriptPromise lock(ScriptState*, const AtomicString& orientation);
void unlock();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change, kChange);
// Helper being used by this class and LockOrientationCallback.
static const AtomicString& OrientationTypeToString(WebScreenOrientationType);
@@ -52,8 +53,6 @@ class ScreenOrientation final : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- explicit ScreenOrientation(LocalFrame*);
-
ScreenOrientationControllerImpl* Controller();
WebScreenOrientationType type_;
diff --git a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.cc b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.cc
index 00ac5f416c0..e533cab2fde 100644
--- a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.cc
@@ -18,7 +18,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/modules/screen_orientation/screen_orientation.h"
#include "third_party/blink/renderer/modules/screen_orientation/screen_orientation_dispatcher.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -26,7 +26,7 @@ ScreenOrientationControllerImpl::~ScreenOrientationControllerImpl() = default;
void ScreenOrientationControllerImpl::ProvideTo(LocalFrame& frame) {
ScreenOrientationController::ProvideTo(
- frame, new ScreenOrientationControllerImpl(frame));
+ frame, MakeGarbageCollected<ScreenOrientationControllerImpl>(frame));
}
ScreenOrientationControllerImpl* ScreenOrientationControllerImpl::From(
@@ -55,10 +55,10 @@ ScreenOrientationControllerImpl::ScreenOrientationControllerImpl(
WebScreenOrientationType ScreenOrientationControllerImpl::ComputeOrientation(
const IntRect& rect,
uint16_t rotation) {
- // Bypass orientation detection in layout tests to get consistent results.
- // FIXME: The screen dimension should be fixed when running the layout tests
+ // Bypass orientation detection in web tests to get consistent results.
+ // FIXME: The screen dimension should be fixed when running the web tests
// to avoid such issues.
- if (LayoutTestSupport::IsRunningLayoutTest())
+ if (WebTestSupport::IsRunningWebTest())
return kWebScreenOrientationPortraitPrimary;
bool is_tall_display = rotation % 180 ? rect.Height() < rect.Width()
@@ -168,9 +168,9 @@ void ScreenOrientationControllerImpl::NotifyOrientationChanged() {
dispatch_event_timer_.StartOneShot(TimeDelta(), FROM_HERE);
// ... and child frames, if they have a ScreenOrientationControllerImpl.
- for (size_t i = 0; i < child_frames.size(); ++i) {
+ for (LocalFrame* child_frame : child_frames) {
if (ScreenOrientationControllerImpl* controller =
- ScreenOrientationControllerImpl::From(*child_frames[i])) {
+ ScreenOrientationControllerImpl::From(*child_frame)) {
controller->NotifyOrientationChanged();
}
}
@@ -221,7 +221,7 @@ void ScreenOrientationControllerImpl::DispatchEventTimerFired(TimerBase*) {
ScopedAllowFullscreen allow_fullscreen(
ScopedAllowFullscreen::kOrientationChange);
- orientation_->DispatchEvent(*Event::Create(EventTypeNames::change));
+ orientation_->DispatchEvent(*Event::Create(event_type_names::kChange));
}
void ScreenOrientationControllerImpl::DidUpdateData() {
diff --git a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.h b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.h
index 61d6564a555..4ce2346045e 100644
--- a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.h
+++ b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_orientation_controller_impl.h
@@ -30,6 +30,7 @@ class MODULES_EXPORT ScreenOrientationControllerImpl final
WTF_MAKE_NONCOPYABLE(ScreenOrientationControllerImpl);
public:
+ explicit ScreenOrientationControllerImpl(LocalFrame&);
~ScreenOrientationControllerImpl() override;
void SetOrientation(ScreenOrientation*);
@@ -53,8 +54,6 @@ class MODULES_EXPORT ScreenOrientationControllerImpl final
friend class MediaControlsOrientationLockAndRotateToFullscreenDelegateTest;
friend class ScreenOrientationControllerImplTest;
- explicit ScreenOrientationControllerImpl(LocalFrame&);
-
static WebScreenOrientationType ComputeOrientation(const IntRect&, uint16_t);
// Inherited from PlatformEventController.
diff --git a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_screen_orientation.cc b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_screen_orientation.cc
index 4e09f7257fb..c7f6a92f6f1 100644
--- a/chromium/third_party/blink/renderer/modules/screen_orientation/screen_screen_orientation.cc
+++ b/chromium/third_party/blink/renderer/modules/screen_orientation/screen_screen_orientation.cc
@@ -15,7 +15,7 @@ ScreenScreenOrientation& ScreenScreenOrientation::From(Screen& screen) {
ScreenScreenOrientation* supplement =
Supplement<Screen>::From<ScreenScreenOrientation>(screen);
if (!supplement) {
- supplement = new ScreenScreenOrientation();
+ supplement = MakeGarbageCollected<ScreenScreenOrientation>();
ProvideTo(screen, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/sensor/README.md b/chromium/third_party/blink/renderer/modules/sensor/README.md
index 7cb9d81b2a2..2b6e9024e5d 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/README.md
+++ b/chromium/third_party/blink/renderer/modules/sensor/README.md
@@ -15,7 +15,7 @@ The platform-specific parts of the implementation are located in
## Testing
-Sensors layout tests are located in `LayoutTests/sensor`.
+Sensors layout tests are located in `web_tests/sensor`.
Sensors browser tests are located in `content/test/data/generic_sensor`.
diff --git a/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.cc b/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.cc
index 2e8aea3ace7..b2f1a985b35 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.cc
@@ -10,7 +10,7 @@ namespace blink {
AbsoluteOrientationSensor* AbsoluteOrientationSensor::Create(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state) {
return new AbsoluteOrientationSensor(execution_context, options,
exception_state);
@@ -20,12 +20,13 @@ AbsoluteOrientationSensor* AbsoluteOrientationSensor::Create(
AbsoluteOrientationSensor* AbsoluteOrientationSensor::Create(
ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SpatialSensorOptions(), exception_state);
+ return Create(execution_context, SpatialSensorOptions::Create(),
+ exception_state);
}
AbsoluteOrientationSensor::AbsoluteOrientationSensor(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state)
: OrientationSensor(execution_context,
options,
diff --git a/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.h b/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.h
index 06cd2d61357..5820f49f8c6 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/absolute_orientation_sensor.h
@@ -15,7 +15,7 @@ class AbsoluteOrientationSensor final : public OrientationSensor {
public:
static AbsoluteOrientationSensor* Create(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
static AbsoluteOrientationSensor* Create(ExecutionContext*, ExceptionState&);
@@ -23,7 +23,7 @@ class AbsoluteOrientationSensor final : public OrientationSensor {
private:
AbsoluteOrientationSensor(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
};
diff --git a/chromium/third_party/blink/renderer/modules/sensor/accelerometer.cc b/chromium/third_party/blink/renderer/modules/sensor/accelerometer.cc
index c7575624759..26b5ec437ae 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/accelerometer.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/accelerometer.cc
@@ -9,7 +9,7 @@ using device::mojom::blink::SensorType;
namespace blink {
Accelerometer* Accelerometer::Create(ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state) {
return new Accelerometer(execution_context, options, exception_state,
SensorType::ACCELEROMETER,
@@ -19,12 +19,13 @@ Accelerometer* Accelerometer::Create(ExecutionContext* execution_context,
// static
Accelerometer* Accelerometer::Create(ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SpatialSensorOptions(), exception_state);
+ return Create(execution_context, SpatialSensorOptions::Create(),
+ exception_state);
}
Accelerometer::Accelerometer(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state,
SensorType sensor_type,
const Vector<mojom::FeaturePolicyFeature>& features)
diff --git a/chromium/third_party/blink/renderer/modules/sensor/accelerometer.h b/chromium/third_party/blink/renderer/modules/sensor/accelerometer.h
index 2f8db564da7..38bf7715205 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/accelerometer.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/accelerometer.h
@@ -15,7 +15,7 @@ class Accelerometer : public Sensor {
public:
static Accelerometer* Create(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
static Accelerometer* Create(ExecutionContext*, ExceptionState&);
@@ -27,7 +27,7 @@ class Accelerometer : public Sensor {
protected:
Accelerometer(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&,
device::mojom::blink::SensorType,
const Vector<mojom::FeaturePolicyFeature>&);
diff --git a/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.cc b/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.cc
index a87463f4927..f4695887b7c 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.cc
@@ -14,7 +14,7 @@ namespace blink {
// static
AmbientLightSensor* AmbientLightSensor::Create(
ExecutionContext* execution_context,
- const SensorOptions& options,
+ const SensorOptions* options,
ExceptionState& exception_state) {
return new AmbientLightSensor(execution_context, options, exception_state);
}
@@ -23,11 +23,11 @@ AmbientLightSensor* AmbientLightSensor::Create(
AmbientLightSensor* AmbientLightSensor::Create(
ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SensorOptions(), exception_state);
+ return Create(execution_context, SensorOptions::Create(), exception_state);
}
AmbientLightSensor::AmbientLightSensor(ExecutionContext* execution_context,
- const SensorOptions& options,
+ const SensorOptions* options,
ExceptionState& exception_state)
: Sensor(execution_context,
options,
diff --git a/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.h b/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.h
index 25ae4c4c86c..c7dfcbdcd4f 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/ambient_light_sensor.h
@@ -14,7 +14,7 @@ class AmbientLightSensor final : public Sensor {
public:
static AmbientLightSensor* Create(ExecutionContext*,
- const SensorOptions&,
+ const SensorOptions*,
ExceptionState&);
static AmbientLightSensor* Create(ExecutionContext*, ExceptionState&);
@@ -23,7 +23,7 @@ class AmbientLightSensor final : public Sensor {
void Trace(blink::Visitor*) override;
private:
- AmbientLightSensor(ExecutionContext*, const SensorOptions&, ExceptionState&);
+ AmbientLightSensor(ExecutionContext*, const SensorOptions*, ExceptionState&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/sensor/gyroscope.cc b/chromium/third_party/blink/renderer/modules/sensor/gyroscope.cc
index 772033bd344..b03a5f8ab72 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/gyroscope.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/gyroscope.cc
@@ -9,19 +9,21 @@ using device::mojom::blink::SensorType;
namespace blink {
Gyroscope* Gyroscope::Create(ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state) {
- return new Gyroscope(execution_context, options, exception_state);
+ return MakeGarbageCollected<Gyroscope>(execution_context, options,
+ exception_state);
}
// static
Gyroscope* Gyroscope::Create(ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SpatialSensorOptions(), exception_state);
+ return Create(execution_context, SpatialSensorOptions::Create(),
+ exception_state);
}
Gyroscope::Gyroscope(ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state)
: Sensor(execution_context,
options,
diff --git a/chromium/third_party/blink/renderer/modules/sensor/gyroscope.h b/chromium/third_party/blink/renderer/modules/sensor/gyroscope.h
index ef9c81dd6dc..27e36a14e9a 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/gyroscope.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/gyroscope.h
@@ -15,18 +15,17 @@ class Gyroscope final : public Sensor {
public:
static Gyroscope* Create(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
static Gyroscope* Create(ExecutionContext*, ExceptionState&);
+ Gyroscope(ExecutionContext*, const SpatialSensorOptions*, ExceptionState&);
+
double x(bool& is_null) const;
double y(bool& is_null) const;
double z(bool& is_null) const;
void Trace(blink::Visitor*) override;
-
- private:
- Gyroscope(ExecutionContext*, const SpatialSensorOptions&, ExceptionState&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.cc b/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.cc
index aefa4840c75..26283bb9426 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.cc
@@ -10,22 +10,23 @@ namespace blink {
LinearAccelerationSensor* LinearAccelerationSensor::Create(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state) {
- return new LinearAccelerationSensor(execution_context, options,
- exception_state);
+ return MakeGarbageCollected<LinearAccelerationSensor>(
+ execution_context, options, exception_state);
}
// static
LinearAccelerationSensor* LinearAccelerationSensor::Create(
ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SpatialSensorOptions(), exception_state);
+ return Create(execution_context, SpatialSensorOptions::Create(),
+ exception_state);
}
LinearAccelerationSensor::LinearAccelerationSensor(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state)
: Accelerometer(execution_context,
options,
diff --git a/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.h b/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.h
index 98610594065..bf54c82ba31 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/linear_acceleration_sensor.h
@@ -14,16 +14,15 @@ class LinearAccelerationSensor final : public Accelerometer {
public:
static LinearAccelerationSensor* Create(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
static LinearAccelerationSensor* Create(ExecutionContext*, ExceptionState&);
- void Trace(blink::Visitor*) override;
-
- private:
LinearAccelerationSensor(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/sensor/magnetometer.cc b/chromium/third_party/blink/renderer/modules/sensor/magnetometer.cc
index 799c093425b..c1d8838231a 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/magnetometer.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/magnetometer.cc
@@ -10,19 +10,21 @@ namespace blink {
// static
Magnetometer* Magnetometer::Create(ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state) {
- return new Magnetometer(execution_context, options, exception_state);
+ return MakeGarbageCollected<Magnetometer>(execution_context, options,
+ exception_state);
}
// static
Magnetometer* Magnetometer::Create(ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SpatialSensorOptions(), exception_state);
+ return Create(execution_context, SpatialSensorOptions::Create(),
+ exception_state);
}
Magnetometer::Magnetometer(ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state)
: Sensor(execution_context,
options,
diff --git a/chromium/third_party/blink/renderer/modules/sensor/magnetometer.h b/chromium/third_party/blink/renderer/modules/sensor/magnetometer.h
index 0f830740457..f4e2e576ea5 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/magnetometer.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/magnetometer.h
@@ -15,18 +15,17 @@ class Magnetometer final : public Sensor {
public:
static Magnetometer* Create(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
static Magnetometer* Create(ExecutionContext*, ExceptionState&);
+ Magnetometer(ExecutionContext*, const SpatialSensorOptions*, ExceptionState&);
+
double x(bool& is_null) const;
double y(bool& is_null) const;
double z(bool& is_null) const;
void Trace(blink::Visitor*) override;
-
- private:
- Magnetometer(ExecutionContext*, const SpatialSensorOptions&, ExceptionState&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.cc b/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.cc
index 733c3627f60..dcd639377a1 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.cc
@@ -116,7 +116,7 @@ bool OrientationSensor::isReadingDirty() const {
OrientationSensor::OrientationSensor(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state,
device::mojom::blink::SensorType type,
const Vector<mojom::FeaturePolicyFeature>& features)
diff --git a/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.h b/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.h
index 0c911e0e461..d6936e83039 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/orientation_sensor.h
@@ -25,7 +25,7 @@ class OrientationSensor : public Sensor {
protected:
OrientationSensor(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&,
device::mojom::blink::SensorType,
const Vector<mojom::FeaturePolicyFeature>& features);
diff --git a/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.cc b/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.cc
index 822baadff0b..ef206c04ee3 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.cc
@@ -10,22 +10,23 @@ namespace blink {
RelativeOrientationSensor* RelativeOrientationSensor::Create(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state) {
- return new RelativeOrientationSensor(execution_context, options,
- exception_state);
+ return MakeGarbageCollected<RelativeOrientationSensor>(
+ execution_context, options, exception_state);
}
// static
RelativeOrientationSensor* RelativeOrientationSensor::Create(
ExecutionContext* execution_context,
ExceptionState& exception_state) {
- return Create(execution_context, SpatialSensorOptions(), exception_state);
+ return Create(execution_context, SpatialSensorOptions::Create(),
+ exception_state);
}
RelativeOrientationSensor::RelativeOrientationSensor(
ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state)
: OrientationSensor(execution_context,
options,
diff --git a/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.h b/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.h
index c5746dfea4a..fca41a496ac 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/relative_orientation_sensor.h
@@ -15,16 +15,15 @@ class RelativeOrientationSensor final : public OrientationSensor {
public:
static RelativeOrientationSensor* Create(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
static RelativeOrientationSensor* Create(ExecutionContext*, ExceptionState&);
- void Trace(blink::Visitor*) override;
-
- private:
RelativeOrientationSensor(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&);
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor.cc b/chromium/third_party/blink/renderer/modules/sensor/sensor.cc
index 36fc02340d9..b4efc3b615e 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor.cc
@@ -15,7 +15,7 @@
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/modules/sensor/sensor_error_event.h"
#include "third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -26,14 +26,15 @@ bool AreFeaturesEnabled(Document* document,
const Vector<mojom::FeaturePolicyFeature>& features) {
return std::all_of(features.begin(), features.end(),
[document](mojom::FeaturePolicyFeature feature) {
- return document->IsFeatureEnabled(feature);
+ return document->IsFeatureEnabled(
+ feature, ReportOptions::kReportOnFailure);
});
}
} // namespace
Sensor::Sensor(ExecutionContext* execution_context,
- const SensorOptions& sensor_options,
+ const SensorOptions* sensor_options,
ExceptionState& exception_state,
device::mojom::blink::SensorType type,
const Vector<mojom::FeaturePolicyFeature>& features)
@@ -54,8 +55,8 @@ Sensor::Sensor(ExecutionContext* execution_context,
}
// Check the given frequency value.
- if (sensor_options.hasFrequency()) {
- frequency_ = sensor_options.frequency();
+ if (sensor_options->hasFrequency()) {
+ frequency_ = sensor_options->frequency();
const double max_allowed_frequency =
device::GetSensorMaxAllowedFrequency(type_);
if (frequency_ > max_allowed_frequency) {
@@ -71,16 +72,16 @@ Sensor::Sensor(ExecutionContext* execution_context,
}
Sensor::Sensor(ExecutionContext* execution_context,
- const SpatialSensorOptions& options,
+ const SpatialSensorOptions* options,
ExceptionState& exception_state,
device::mojom::blink::SensorType sensor_type,
const Vector<mojom::FeaturePolicyFeature>& features)
: Sensor(execution_context,
- static_cast<const SensorOptions&>(options),
+ static_cast<const SensorOptions*>(options),
exception_state,
sensor_type,
features) {
- use_screen_coords_ = (options.referenceFrame() == "screen");
+ use_screen_coords_ = (options->referenceFrame() == "screen");
}
Sensor::~Sensor() = default;
@@ -129,7 +130,7 @@ DOMHighResTimeStamp Sensor::timestamp(ScriptState* script_state,
DCHECK(sensor_proxy_);
is_null = false;
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
// In layout tests performance.now() * 0.001 is passed to the shared buffer.
return sensor_proxy_->GetReading().timestamp() * 1000;
}
@@ -338,7 +339,7 @@ void Sensor::HandleError(DOMExceptionCode code,
void Sensor::NotifyReading() {
DCHECK_EQ(state_, SensorState::kActivated);
last_reported_timestamp_ = sensor_proxy_->GetReading().timestamp();
- DispatchEvent(*Event::Create(EventTypeNames::reading));
+ DispatchEvent(*Event::Create(event_type_names::kReading));
}
void Sensor::NotifyActivated() {
@@ -354,13 +355,13 @@ void Sensor::NotifyActivated() {
WTF::Bind(&Sensor::NotifyReading, WrapWeakPersistent(this)));
}
- DispatchEvent(*Event::Create(EventTypeNames::activate));
+ DispatchEvent(*Event::Create(event_type_names::kActivate));
}
void Sensor::NotifyError(DOMException* error) {
DCHECK_NE(state_, SensorState::kIdle);
state_ = SensorState::kIdle;
- DispatchEvent(*SensorErrorEvent::Create(EventTypeNames::error, error));
+ DispatchEvent(*SensorErrorEvent::Create(event_type_names::kError, error));
}
bool Sensor::IsIdleOrErrored() const {
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor.h b/chromium/third_party/blink/renderer/modules/sensor/sensor.h
index 2bc47db4928..1be8636e93a 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor.h
@@ -19,7 +19,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
namespace blink {
@@ -44,7 +44,7 @@ class Sensor : public EventTargetWithInlineData,
// EventTarget overrides.
const AtomicString& InterfaceName() const override {
- return EventTargetNames::Sensor;
+ return event_target_names::kSensor;
}
ExecutionContext* GetExecutionContext() const override {
return ContextLifecycleObserver::GetExecutionContext();
@@ -55,9 +55,9 @@ class Sensor : public EventTargetWithInlineData,
bool hasReading() const;
DOMHighResTimeStamp timestamp(ScriptState*, bool& is_null) const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(reading);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(activate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(reading, kReading);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(activate, kActivate);
// ActiveScriptWrappable overrides.
bool HasPendingActivity() const override;
@@ -66,13 +66,13 @@ class Sensor : public EventTargetWithInlineData,
protected:
Sensor(ExecutionContext*,
- const SensorOptions&,
+ const SensorOptions*,
ExceptionState&,
device::mojom::blink::SensorType,
const Vector<mojom::FeaturePolicyFeature>&);
Sensor(ExecutionContext*,
- const SpatialSensorOptions&,
+ const SpatialSensorOptions*,
ExceptionState&,
device::mojom::blink::SensorType,
const Vector<mojom::FeaturePolicyFeature>&);
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.cc b/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.cc
index 96a1dcd8e84..7a5fbfee904 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.cc
@@ -18,13 +18,13 @@ SensorErrorEvent::SensorErrorEvent(const AtomicString& event_type,
}
SensorErrorEvent::SensorErrorEvent(const AtomicString& event_type,
- const SensorErrorEventInit& initializer)
- : Event(event_type, initializer), error_(initializer.error()) {
+ const SensorErrorEventInit* initializer)
+ : Event(event_type, initializer), error_(initializer->error()) {
DCHECK(error_);
}
const AtomicString& SensorErrorEvent::InterfaceName() const {
- return EventNames::SensorErrorEvent;
+ return event_interface_names::kSensorErrorEvent;
}
void SensorErrorEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.h b/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.h
index bcc991a107e..4825d586fb6 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_error_event.h
@@ -18,14 +18,17 @@ class SensorErrorEvent : public Event {
public:
static SensorErrorEvent* Create(const AtomicString& event_type,
DOMException* error) {
- return new SensorErrorEvent(event_type, error);
+ return MakeGarbageCollected<SensorErrorEvent>(event_type, error);
}
static SensorErrorEvent* Create(const AtomicString& event_type,
- const SensorErrorEventInit& initializer) {
- return new SensorErrorEvent(event_type, initializer);
+ const SensorErrorEventInit* initializer) {
+ return MakeGarbageCollected<SensorErrorEvent>(event_type, initializer);
}
+ SensorErrorEvent(const AtomicString& event_type, DOMException* error);
+ SensorErrorEvent(const AtomicString& event_type,
+ const SensorErrorEventInit* initializer);
~SensorErrorEvent() override;
void Trace(blink::Visitor*) override;
@@ -35,18 +38,16 @@ class SensorErrorEvent : public Event {
DOMException* error() { return error_; }
private:
- SensorErrorEvent(const AtomicString& event_type, DOMException* error);
- SensorErrorEvent(const AtomicString& event_type,
- const SensorErrorEventInit& initializer);
-
Member<DOMException> error_;
};
DEFINE_TYPE_CASTS(SensorErrorEvent,
Event,
event,
- event->InterfaceName() == EventNames::SensorErrorEvent,
- event.InterfaceName() == EventNames::SensorErrorEvent);
+ event->InterfaceName() ==
+ event_interface_names::kSensorErrorEvent,
+ event.InterfaceName() ==
+ event_interface_names::kSensorErrorEvent);
} // namepsace blink
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc b/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc
index d0cb3372ca1..210c0cc3adf 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.cc
@@ -36,7 +36,7 @@ SensorProviderProxy* SensorProviderProxy::From(Document* document) {
SensorProviderProxy* provider_proxy =
Supplement<Document>::From<SensorProviderProxy>(*document);
if (!provider_proxy) {
- provider_proxy = new SensorProviderProxy(*document);
+ provider_proxy = MakeGarbageCollected<SensorProviderProxy>(*document);
Supplement<Document>::ProvideTo(*document, provider_proxy);
}
provider_proxy->InitializeIfNeeded();
@@ -58,8 +58,10 @@ SensorProxy* SensorProviderProxy::CreateSensorProxy(
SensorProxy* sensor =
inspector_mode_
? static_cast<SensorProxy*>(
- new SensorProxyInspectorImpl(type, this, page))
- : static_cast<SensorProxy*>(new SensorProxyImpl(type, this, page));
+ MakeGarbageCollected<SensorProxyInspectorImpl>(type, this,
+ page))
+ : static_cast<SensorProxy*>(
+ MakeGarbageCollected<SensorProxyImpl>(type, this, page));
sensor_proxies_.insert(sensor);
return sensor;
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h b/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h
index 324ca953dbd..914b0531dbd 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h
@@ -28,6 +28,7 @@ class SensorProviderProxy final
static SensorProviderProxy* From(Document*);
+ explicit SensorProviderProxy(Document&);
~SensorProviderProxy();
SensorProxy* CreateSensorProxy(device::mojom::blink::SensorType, Page*);
@@ -50,7 +51,6 @@ class SensorProviderProxy final
const SensorsSet& sensor_proxies() const { return sensor_proxies_; }
// For SensorProviderProxy personal use.
- explicit SensorProviderProxy(Document&);
void InitializeIfNeeded();
bool IsInitialized() const { return sensor_provider_.is_bound(); }
void OnSensorProviderConnectionError();
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy.cc b/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy.cc
index ec5b6d73e63..9b3fed19a89 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/modules/sensor/sensor_provider_proxy.h"
#include "third_party/blink/renderer/modules/sensor/sensor_reading_remapper.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -67,7 +67,7 @@ void SensorProxy::ReportError(DOMExceptionCode code, const String& message) {
namespace {
uint16_t GetScreenOrientationAngleForPage(Page* page) {
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
// Simulate that the device is turned 90 degrees on the right.
// 'orientation_angle' must be 270 as per
// https://w3c.github.io/screen-orientation/#dfn-update-the-orientation-information.
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc b/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc
index c52eb7c19f2..9aee25cc351 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_impl.cc
@@ -264,8 +264,9 @@ void SensorProxyImpl::AddActiveFrequency(double frequency) {
if (it == active_frequencies_.end()) {
active_frequencies_.push_back(frequency);
} else {
- active_frequencies_.insert(std::distance(active_frequencies_.begin(), it),
- frequency);
+ active_frequencies_.insert(
+ static_cast<wtf_size_t>(std::distance(active_frequencies_.begin(), it)),
+ frequency);
}
UpdatePollingStatus();
}
diff --git a/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc b/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc
index f4bf5646020..8a2de5b2290 100644
--- a/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/sensor/sensor_proxy_inspector_impl.cc
@@ -37,8 +37,7 @@ void SensorProxyInspectorImpl::Initialize() {
auto callback = WTF::Bind(&SensorProxyInspectorImpl::OnSensorCreated,
WrapWeakPersistent(this));
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
- FROM_HERE, std::move(callback));
+ Thread::Current()->GetTaskRunner()->PostTask(FROM_HERE, std::move(callback));
}
void SensorProxyInspectorImpl::AddConfiguration(
diff --git a/chromium/third_party/blink/renderer/modules/serial/serial.cc b/chromium/third_party/blink/renderer/modules/serial/serial.cc
index 8c3a6407147..e88aa55560c 100644
--- a/chromium/third_party/blink/renderer/modules/serial/serial.cc
+++ b/chromium/third_party/blink/renderer/modules/serial/serial.cc
@@ -18,7 +18,7 @@ ExecutionContext* Serial::GetExecutionContext() const {
}
const AtomicString& Serial::InterfaceName() const {
- return EventTargetNames::Serial;
+ return event_target_names::kSerial;
}
ScriptPromise Serial::getPorts(ScriptState* script_state) {
@@ -27,7 +27,7 @@ ScriptPromise Serial::getPorts(ScriptState* script_state) {
}
ScriptPromise Serial::requestPort(ScriptState* script_state,
- const SerialPortRequestOptions& options) {
+ const SerialPortRequestOptions* options) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kNotSupportedError));
}
diff --git a/chromium/third_party/blink/renderer/modules/serial/serial.h b/chromium/third_party/blink/renderer/modules/serial/serial.h
index ead1ec0cbe5..3edf86105e1 100644
--- a/chromium/third_party/blink/renderer/modules/serial/serial.h
+++ b/chromium/third_party/blink/renderer/modules/serial/serial.h
@@ -30,10 +30,10 @@ class Serial final : public EventTargetWithInlineData,
ExecutionContext* GetExecutionContext() const override;
const AtomicString& InterfaceName() const override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect, kDisconnect);
ScriptPromise getPorts(ScriptState*);
- ScriptPromise requestPort(ScriptState*, const SerialPortRequestOptions&);
+ ScriptPromise requestPort(ScriptState*, const SerialPortRequestOptions*);
void Trace(Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/modules/serial/serial_port.cc b/chromium/third_party/blink/renderer/modules/serial/serial_port.cc
index 10739a4db1e..d8b125de03f 100644
--- a/chromium/third_party/blink/renderer/modules/serial/serial_port.cc
+++ b/chromium/third_party/blink/renderer/modules/serial/serial_port.cc
@@ -16,7 +16,7 @@ ScriptValue SerialPort::out(ScriptState* script_state) {
}
ScriptPromise SerialPort::open(ScriptState* script_state,
- const SerialOptions& options) {
+ const SerialOptions* options) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kNotSupportedError));
}
diff --git a/chromium/third_party/blink/renderer/modules/serial/serial_port.h b/chromium/third_party/blink/renderer/modules/serial/serial_port.h
index baadd7b0601..82211e20265 100644
--- a/chromium/third_party/blink/renderer/modules/serial/serial_port.h
+++ b/chromium/third_party/blink/renderer/modules/serial/serial_port.h
@@ -21,7 +21,7 @@ class SerialPort final : public ScriptWrappable {
ScriptValue in(ScriptState*);
ScriptValue out(ScriptState*);
- ScriptPromise open(ScriptState*, const SerialOptions& options);
+ ScriptPromise open(ScriptState*, const SerialOptions* options);
ScriptPromise close(ScriptState*);
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/BUILD.gn b/chromium/third_party/blink/renderer/modules/service_worker/BUILD.gn
index fbe04fd2759..cbe8fd6706d 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/service_worker/BUILD.gn
@@ -16,8 +16,6 @@ blink_modules_sources("service_worker") {
"fetch_respond_with_observer.h",
"install_event.cc",
"install_event.h",
- "navigation_preload_callbacks.cc",
- "navigation_preload_callbacks.h",
"navigation_preload_manager.cc",
"navigation_preload_manager.h",
"navigator_service_worker.cc",
@@ -32,8 +30,6 @@ blink_modules_sources("service_worker") {
"service_worker_clients.h",
"service_worker_container.cc",
"service_worker_container.h",
- "service_worker_container_client.cc",
- "service_worker_container_client.h",
"service_worker_content_settings_proxy.cc",
"service_worker_content_settings_proxy.h",
"service_worker_error.cc",
@@ -46,6 +42,8 @@ blink_modules_sources("service_worker") {
"service_worker_global_scope_proxy.h",
"service_worker_installed_scripts_manager.cc",
"service_worker_installed_scripts_manager.h",
+ "service_worker_module_tree_client.cc",
+ "service_worker_module_tree_client.h",
"service_worker_registration.cc",
"service_worker_registration.h",
"service_worker_script_cached_metadata_handler.cc",
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/DEPS b/chromium/third_party/blink/renderer/modules/service_worker/DEPS
index a6301afa47f..831dcbc4bdd 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/DEPS
+++ b/chromium/third_party/blink/renderer/modules/service_worker/DEPS
@@ -3,7 +3,6 @@ include_rules = [
"+base/threading/thread_checker.h",
"+mojo/public/cpp/bindings/strong_binding.h",
"+mojo/public/cpp/system/data_pipe.h",
- "+services/network/public/mojom",
"-third_party/blink/renderer/modules",
"+third_party/blink/renderer/modules/event_modules.h",
"+third_party/blink/renderer/modules/event_target_modules.h",
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/client.idl b/chromium/third_party/blink/renderer/modules/service_worker/client.idl
index 9a752de5dea..a3004e00361 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/client.idl
+++ b/chromium/third_party/blink/renderer/modules/service_worker/client.idl
@@ -10,8 +10,8 @@
readonly attribute USVString url;
readonly attribute DOMString id;
readonly attribute ClientType type;
- [CallWith=ScriptState, RaisesException] void postMessage(any message, optional sequence<object> transfer = []);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, optional PostMessageOptions options);
// FIXME: frameType is non-standard, see https://crbug.com/697110
[CallWith=ScriptState] readonly attribute ContextFrameType frameType;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.cc b/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.cc
index 6a43b0bd864..1335f012dba 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.cc
@@ -38,14 +38,14 @@ namespace blink {
ExtendableEvent* ExtendableEvent::Create(
const AtomicString& type,
- const ExtendableEventInit& event_init) {
- return new ExtendableEvent(type, event_init);
+ const ExtendableEventInit* event_init) {
+ return MakeGarbageCollected<ExtendableEvent>(type, event_init);
}
ExtendableEvent* ExtendableEvent::Create(const AtomicString& type,
- const ExtendableEventInit& event_init,
+ const ExtendableEventInit* event_init,
WaitUntilObserver* observer) {
- return new ExtendableEvent(type, event_init, observer);
+ return MakeGarbageCollected<ExtendableEvent>(type, event_init, observer);
}
ExtendableEvent::~ExtendableEvent() = default;
@@ -64,16 +64,16 @@ void ExtendableEvent::waitUntil(ScriptState* script_state,
}
ExtendableEvent::ExtendableEvent(const AtomicString& type,
- const ExtendableEventInit& initializer)
+ const ExtendableEventInit* initializer)
: Event(type, initializer) {}
ExtendableEvent::ExtendableEvent(const AtomicString& type,
- const ExtendableEventInit& initializer,
+ const ExtendableEventInit* initializer,
WaitUntilObserver* observer)
: Event(type, initializer), observer_(observer) {}
const AtomicString& ExtendableEvent::InterfaceName() const {
- return EventNames::ExtendableEvent;
+ return event_interface_names::kExtendableEvent;
}
void ExtendableEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.h b/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.h
index 22a1fa3eea2..75932320766 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/extendable_event.h
@@ -45,11 +45,15 @@ class MODULES_EXPORT ExtendableEvent : public Event {
public:
static ExtendableEvent* Create(const AtomicString& type,
- const ExtendableEventInit&);
+ const ExtendableEventInit*);
static ExtendableEvent* Create(const AtomicString& type,
- const ExtendableEventInit&,
+ const ExtendableEventInit*,
WaitUntilObserver*);
+ ExtendableEvent(const AtomicString& type, const ExtendableEventInit*);
+ ExtendableEvent(const AtomicString& type,
+ const ExtendableEventInit*,
+ WaitUntilObserver*);
~ExtendableEvent() override;
void waitUntil(ScriptState*, ScriptPromise, ExceptionState&);
@@ -58,11 +62,6 @@ class MODULES_EXPORT ExtendableEvent : public Event {
void Trace(blink::Visitor*) override;
protected:
- ExtendableEvent(const AtomicString& type, const ExtendableEventInit&);
- ExtendableEvent(const AtomicString& type,
- const ExtendableEventInit&,
- WaitUntilObserver*);
-
Member<WaitUntilObserver> observer_;
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.cc b/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.cc
index c9826adceed..758194d9081 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.cc
@@ -8,15 +8,16 @@ namespace blink {
ExtendableMessageEvent* ExtendableMessageEvent::Create(
const AtomicString& type,
- const ExtendableMessageEventInit& initializer) {
- return new ExtendableMessageEvent(type, initializer);
+ const ExtendableMessageEventInit* initializer) {
+ return MakeGarbageCollected<ExtendableMessageEvent>(type, initializer);
}
ExtendableMessageEvent* ExtendableMessageEvent::Create(
const AtomicString& type,
- const ExtendableMessageEventInit& initializer,
+ const ExtendableMessageEventInit* initializer,
WaitUntilObserver* observer) {
- return new ExtendableMessageEvent(type, initializer, observer);
+ return MakeGarbageCollected<ExtendableMessageEvent>(type, initializer,
+ observer);
}
ExtendableMessageEvent* ExtendableMessageEvent::Create(
@@ -24,7 +25,8 @@ ExtendableMessageEvent* ExtendableMessageEvent::Create(
const String& origin,
MessagePortArray* ports,
WaitUntilObserver* observer) {
- return new ExtendableMessageEvent(std::move(data), origin, ports, observer);
+ return MakeGarbageCollected<ExtendableMessageEvent>(std::move(data), origin,
+ ports, observer);
}
ExtendableMessageEvent* ExtendableMessageEvent::Create(
@@ -33,8 +35,8 @@ ExtendableMessageEvent* ExtendableMessageEvent::Create(
MessagePortArray* ports,
ServiceWorkerClient* source,
WaitUntilObserver* observer) {
- ExtendableMessageEvent* event =
- new ExtendableMessageEvent(std::move(data), origin, ports, observer);
+ ExtendableMessageEvent* event = MakeGarbageCollected<ExtendableMessageEvent>(
+ std::move(data), origin, ports, observer);
event->source_as_client_ = source;
return event;
}
@@ -45,23 +47,12 @@ ExtendableMessageEvent* ExtendableMessageEvent::Create(
MessagePortArray* ports,
ServiceWorker* source,
WaitUntilObserver* observer) {
- ExtendableMessageEvent* event =
- new ExtendableMessageEvent(std::move(data), origin, ports, observer);
+ ExtendableMessageEvent* event = MakeGarbageCollected<ExtendableMessageEvent>(
+ std::move(data), origin, ports, observer);
event->source_as_service_worker_ = source;
return event;
}
-MessagePortArray ExtendableMessageEvent::ports() const {
- // TODO(bashi): Currently we return a copied array because the binding
- // layer could modify the content of the array while executing JS callbacks.
- // Avoid copying once we can make sure that the binding layer won't
- // modify the content.
- if (ports_) {
- return *ports_;
- }
- return MessagePortArray();
-}
-
void ExtendableMessageEvent::source(
ClientOrServiceWorkerOrMessagePort& result) const {
if (source_as_client_)
@@ -76,8 +67,19 @@ void ExtendableMessageEvent::source(
result = ClientOrServiceWorkerOrMessagePort();
}
+MessagePortArray ExtendableMessageEvent::ports() const {
+ // TODO(bashi): Currently we return a copied array because the binding
+ // layer could modify the content of the array while executing JS callbacks.
+ // Avoid copying once we can make sure that the binding layer won't
+ // modify the content.
+ if (ports_) {
+ return *ports_;
+ }
+ return MessagePortArray();
+}
+
const AtomicString& ExtendableMessageEvent::InterfaceName() const {
- return EventNames::ExtendableMessageEvent;
+ return event_interface_names::kExtendableMessageEvent;
}
void ExtendableMessageEvent::Trace(blink::Visitor* visitor) {
@@ -90,28 +92,28 @@ void ExtendableMessageEvent::Trace(blink::Visitor* visitor) {
ExtendableMessageEvent::ExtendableMessageEvent(
const AtomicString& type,
- const ExtendableMessageEventInit& initializer)
+ const ExtendableMessageEventInit* initializer)
: ExtendableMessageEvent(type, initializer, nullptr) {}
ExtendableMessageEvent::ExtendableMessageEvent(
const AtomicString& type,
- const ExtendableMessageEventInit& initializer,
+ const ExtendableMessageEventInit* initializer,
WaitUntilObserver* observer)
: ExtendableEvent(type, initializer, observer) {
- if (initializer.hasOrigin())
- origin_ = initializer.origin();
- if (initializer.hasLastEventId())
- last_event_id_ = initializer.lastEventId();
- if (initializer.hasSource()) {
- if (initializer.source().IsClient())
- source_as_client_ = initializer.source().GetAsClient();
- else if (initializer.source().IsServiceWorker())
- source_as_service_worker_ = initializer.source().GetAsServiceWorker();
- else if (initializer.source().IsMessagePort())
- source_as_message_port_ = initializer.source().GetAsMessagePort();
+ if (initializer->hasOrigin())
+ origin_ = initializer->origin();
+ if (initializer->hasLastEventId())
+ last_event_id_ = initializer->lastEventId();
+ if (initializer->hasSource()) {
+ if (initializer->source().IsClient())
+ source_as_client_ = initializer->source().GetAsClient();
+ else if (initializer->source().IsServiceWorker())
+ source_as_service_worker_ = initializer->source().GetAsServiceWorker();
+ else if (initializer->source().IsMessagePort())
+ source_as_message_port_ = initializer->source().GetAsMessagePort();
}
- if (initializer.hasPorts())
- ports_ = new MessagePortArray(initializer.ports());
+ if (initializer->hasPorts())
+ ports_ = MakeGarbageCollected<MessagePortArray>(initializer->ports());
}
ExtendableMessageEvent::ExtendableMessageEvent(
@@ -119,8 +121,8 @@ ExtendableMessageEvent::ExtendableMessageEvent(
const String& origin,
MessagePortArray* ports,
WaitUntilObserver* observer)
- : ExtendableEvent(EventTypeNames::message,
- ExtendableMessageEventInit(),
+ : ExtendableEvent(event_type_names::kMessage,
+ ExtendableMessageEventInit::Create(),
observer),
serialized_data_(std::move(data)),
origin_(origin),
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.h b/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.h
index e56addf886d..b0517c6dc54 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/extendable_message_event.h
@@ -18,10 +18,10 @@ class MODULES_EXPORT ExtendableMessageEvent final : public ExtendableEvent {
public:
static ExtendableMessageEvent* Create(
const AtomicString& type,
- const ExtendableMessageEventInit& initializer);
+ const ExtendableMessageEventInit* initializer);
static ExtendableMessageEvent* Create(
const AtomicString& type,
- const ExtendableMessageEventInit& initializer,
+ const ExtendableMessageEventInit* initializer,
WaitUntilObserver*);
static ExtendableMessageEvent* Create(
scoped_refptr<SerializedScriptValue> data,
@@ -41,32 +41,33 @@ class MODULES_EXPORT ExtendableMessageEvent final : public ExtendableEvent {
ServiceWorker* source,
WaitUntilObserver*);
+ ExtendableMessageEvent(const AtomicString& type,
+ const ExtendableMessageEventInit* initializer);
+ ExtendableMessageEvent(const AtomicString& type,
+ const ExtendableMessageEventInit* initializer,
+ WaitUntilObserver*);
+ ExtendableMessageEvent(scoped_refptr<SerializedScriptValue> data,
+ const String& origin,
+ MessagePortArray* ports,
+ WaitUntilObserver*);
+
SerializedScriptValue* SerializedData() const {
return serialized_data_.get();
}
void SetSerializedData(scoped_refptr<SerializedScriptValue> serialized_data) {
serialized_data_ = std::move(serialized_data);
}
+
const String& origin() const { return origin_; }
const String& lastEventId() const { return last_event_id_; }
- MessagePortArray ports() const;
void source(ClientOrServiceWorkerOrMessagePort& result) const;
+ MessagePortArray ports() const;
const AtomicString& InterfaceName() const override;
void Trace(blink::Visitor*) override;
private:
- ExtendableMessageEvent(const AtomicString& type,
- const ExtendableMessageEventInit& initializer);
- ExtendableMessageEvent(const AtomicString& type,
- const ExtendableMessageEventInit& initializer,
- WaitUntilObserver*);
- ExtendableMessageEvent(scoped_refptr<SerializedScriptValue> data,
- const String& origin,
- MessagePortArray* ports,
- WaitUntilObserver*);
-
scoped_refptr<SerializedScriptValue> serialized_data_;
String origin_;
String last_event_id_;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.cc b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.cc
index b790caea27f..c95d157c353 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.cc
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include <utility>
+
#include "third_party/blink/renderer/modules/service_worker/fetch_event.h"
#include "base/memory/scoped_refptr.h"
@@ -10,7 +12,6 @@
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h"
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/core/fetch/response.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
@@ -26,19 +27,20 @@ namespace blink {
FetchEvent* FetchEvent::Create(ScriptState* script_state,
const AtomicString& type,
- const FetchEventInit& initializer) {
- return new FetchEvent(script_state, type, initializer, nullptr, nullptr,
- false);
+ const FetchEventInit* initializer) {
+ return MakeGarbageCollected<FetchEvent>(script_state, type, initializer,
+ nullptr, nullptr, false);
}
FetchEvent* FetchEvent::Create(ScriptState* script_state,
const AtomicString& type,
- const FetchEventInit& initializer,
+ const FetchEventInit* initializer,
FetchRespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer,
bool navigation_preload_sent) {
- return new FetchEvent(script_state, type, initializer, respond_with_observer,
- wait_until_observer, navigation_preload_sent);
+ return MakeGarbageCollected<FetchEvent>(
+ script_state, type, initializer, respond_with_observer,
+ wait_until_observer, navigation_preload_sent);
}
Request* FetchEvent::request() const {
@@ -49,6 +51,10 @@ String FetchEvent::clientId() const {
return client_id_;
}
+String FetchEvent::resultingClientId() const {
+ return resulting_client_id_;
+}
+
bool FetchEvent::isReload() const {
UseCounter::Count(GetExecutionContext(), WebFeature::kFetchEventIsReload);
return is_reload_;
@@ -67,7 +73,7 @@ ScriptPromise FetchEvent::preloadResponse(ScriptState* script_state) {
}
const AtomicString& FetchEvent::InterfaceName() const {
- return EventNames::FetchEvent;
+ return event_interface_names::kFetchEvent;
}
bool FetchEvent::HasPendingActivity() const {
@@ -83,7 +89,7 @@ bool FetchEvent::HasPendingActivity() const {
FetchEvent::FetchEvent(ScriptState* script_state,
const AtomicString& type,
- const FetchEventInit& initializer,
+ const FetchEventInit* initializer,
FetchRespondWithObserver* respond_with_observer,
WaitUntilObserver* wait_until_observer,
bool navigation_preload_sent)
@@ -97,9 +103,10 @@ FetchEvent::FetchEvent(ScriptState* script_state,
if (!navigation_preload_sent)
preload_response_property_->ResolveWithUndefined();
- client_id_ = initializer.clientId();
- is_reload_ = initializer.isReload();
- request_ = initializer.request();
+ client_id_ = initializer->clientId();
+ resulting_client_id_ = initializer->resultingClientId();
+ is_reload_ = initializer->isReload();
+ request_ = initializer->request();
}
FetchEvent::~FetchEvent() = default;
@@ -114,15 +121,19 @@ void FetchEvent::OnNavigationPreloadResponse(
DCHECK(!preload_response_);
ScriptState::Scope scope(script_state);
preload_response_ = std::move(response);
+ DataPipeBytesConsumer* bytes_consumer = nullptr;
if (data_pipe.is_valid()) {
- data_pipe_consumer_ = new DataPipeBytesConsumer(
- ExecutionContext::From(script_state), std::move(data_pipe));
+ DataPipeBytesConsumer::CompletionNotifier* completion_notifier = nullptr;
+ bytes_consumer =
+ new DataPipeBytesConsumer(ExecutionContext::From(script_state),
+ std::move(data_pipe), &completion_notifier);
+ body_completion_notifier_ = completion_notifier;
}
// TODO(ricea): Verify that this response can't be aborted from JS.
FetchResponseData* response_data =
- data_pipe_consumer_
+ bytes_consumer
? FetchResponseData::CreateWithBuffer(new BodyStreamBuffer(
- script_state, data_pipe_consumer_,
+ script_state, bytes_consumer,
new AbortSignal(ExecutionContext::From(script_state))))
: FetchResponseData::Create();
Vector<KURL> url_list(1);
@@ -138,7 +149,7 @@ void FetchEvent::OnNavigationPreloadResponse(
response_data->HeaderList()->Append(header.key, header.value);
}
FetchResponseData* tainted_response =
- NetworkUtils::IsRedirectResponseCode(preload_response_->HttpStatusCode())
+ network_utils::IsRedirectResponseCode(preload_response_->HttpStatusCode())
? response_data->CreateOpaqueRedirectFilteredResponse()
: response_data->CreateBasicFilteredResponse();
preload_response_property_->Resolve(
@@ -150,9 +161,9 @@ void FetchEvent::OnNavigationPreloadError(
std::unique_ptr<WebServiceWorkerError> error) {
if (!script_state->ContextIsValid())
return;
- if (data_pipe_consumer_) {
- data_pipe_consumer_->SignalError();
- data_pipe_consumer_ = nullptr;
+ if (body_completion_notifier_) {
+ body_completion_notifier_->SignalError(BytesConsumer::Error());
+ body_completion_notifier_ = nullptr;
}
DCHECK(preload_response_property_);
if (preload_response_property_->GetState() !=
@@ -170,9 +181,9 @@ void FetchEvent::OnNavigationPreloadComplete(
int64_t encoded_body_length,
int64_t decoded_body_length) {
DCHECK(preload_response_);
- if (data_pipe_consumer_) {
- data_pipe_consumer_->SignalComplete();
- data_pipe_consumer_ = nullptr;
+ if (body_completion_notifier_) {
+ body_completion_notifier_->SignalComplete();
+ body_completion_notifier_ = nullptr;
}
std::unique_ptr<WebURLResponse> response = std::move(preload_response_);
ResourceResponse resource_response = response->ToResourceResponse();
@@ -197,7 +208,7 @@ void FetchEvent::Trace(blink::Visitor* visitor) {
visitor->Trace(observer_);
visitor->Trace(request_);
visitor->Trace(preload_response_property_);
- visitor->Trace(data_pipe_consumer_);
+ visitor->Trace(body_completion_notifier_);
ExtendableEvent::Trace(visitor);
ContextClient::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.h b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.h
index 5482c436e63..d4c68241d7f 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.h
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_property.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/core/fetch/data_pipe_bytes_consumer.h"
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/modules/event_modules.h"
#include "third_party/blink/renderer/modules/modules_export.h"
@@ -22,7 +23,6 @@
namespace blink {
-class DataPipeBytesConsumer;
class ExceptionState;
class FetchRespondWithObserver;
class Request;
@@ -48,18 +48,25 @@ class MODULES_EXPORT FetchEvent final
Member<DOMException>>;
static FetchEvent* Create(ScriptState*,
const AtomicString& type,
- const FetchEventInit&);
+ const FetchEventInit*);
static FetchEvent* Create(ScriptState*,
const AtomicString& type,
- const FetchEventInit&,
+ const FetchEventInit*,
FetchRespondWithObserver*,
WaitUntilObserver*,
bool navigation_preload_sent);
+ FetchEvent(ScriptState*,
+ const AtomicString& type,
+ const FetchEventInit*,
+ FetchRespondWithObserver*,
+ WaitUntilObserver*,
+ bool navigation_preload_sent);
~FetchEvent() override;
Request* request() const;
String clientId() const;
+ String resultingClientId() const;
bool isReload() const;
void respondWith(ScriptState*, ScriptPromise, ExceptionState&);
@@ -83,21 +90,14 @@ class MODULES_EXPORT FetchEvent final
void Trace(blink::Visitor*) override;
- protected:
- FetchEvent(ScriptState*,
- const AtomicString& type,
- const FetchEventInit&,
- FetchRespondWithObserver*,
- WaitUntilObserver*,
- bool navigation_preload_sent);
-
private:
Member<FetchRespondWithObserver> observer_;
TraceWrapperMember<Request> request_;
Member<PreloadResponseProperty> preload_response_property_;
std::unique_ptr<WebURLResponse> preload_response_;
- Member<DataPipeBytesConsumer> data_pipe_consumer_;
+ Member<DataPipeBytesConsumer::CompletionNotifier> body_completion_notifier_;
String client_id_;
+ String resulting_client_id_;
bool is_reload_;
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.idl b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.idl
index 16e30dba8ef..53439e53d77 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.idl
+++ b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event.idl
@@ -11,6 +11,7 @@
] interface FetchEvent : ExtendableEvent {
[SameObject] readonly attribute Request request;
readonly attribute DOMString clientId;
+ readonly attribute DOMString resultingClientId;
readonly attribute boolean isReload;
[CallWith=ScriptState, RaisesException] void respondWith(Promise<Response> r);
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event_init.idl b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event_init.idl
index 67706abada1..df07d0c43c2 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/fetch_event_init.idl
+++ b/chromium/third_party/blink/renderer/modules/service_worker/fetch_event_init.idl
@@ -7,5 +7,6 @@
dictionary FetchEventInit : ExtendableEventInit {
required Request request;
DOMString clientId = "";
+ DOMString resultingClientId = "";
boolean isReload = false;
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc b/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc
index 7860b3bc2a4..3fd575b24a5 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc
@@ -79,7 +79,7 @@ const String GetMessageForResponseError(ServiceWorkerResponseError error,
"an \"opaqueredirect\" type response was used for a "
"request whose redirect mode is not \"manual\".";
break;
- case ServiceWorkerResponseError::kResponseTypeCORSForRequestModeSameOrigin:
+ case ServiceWorkerResponseError::kResponseTypeCorsForRequestModeSameOrigin:
error_message = error_message +
"a \"cors\" type response was used for a request whose "
"mode is \"same-origin\".";
@@ -203,9 +203,9 @@ FetchRespondWithObserver* FetchRespondWithObserver::Create(
network::mojom::RequestContextFrameType frame_type,
mojom::RequestContextType request_context,
WaitUntilObserver* observer) {
- return new FetchRespondWithObserver(context, fetch_event_id, request_url,
- request_mode, redirect_mode, frame_type,
- request_context, observer);
+ return MakeGarbageCollected<FetchRespondWithObserver>(
+ context, fetch_event_id, request_url, request_mode, redirect_mode,
+ frame_type, request_context, observer);
}
// This function may be called when an exception is scheduled. Thus, it must
@@ -233,7 +233,7 @@ void FetchRespondWithObserver::OnResponseFulfilled(
const char* interface_name,
const char* property_name) {
DCHECK(GetExecutionContext());
- if (!V8Response::hasInstance(value.V8Value(),
+ if (!V8Response::HasInstance(value.V8Value(),
ToIsolate(GetExecutionContext()))) {
OnResponseRejected(ServiceWorkerResponseError::kNoV8Instance);
return;
@@ -252,14 +252,14 @@ void FetchRespondWithObserver::OnResponseFulfilled(
OnResponseRejected(ServiceWorkerResponseError::kResponseTypeError);
return;
}
- if (response_type == network::mojom::FetchResponseType::kCORS &&
+ if (response_type == network::mojom::FetchResponseType::kCors &&
request_mode_ == network::mojom::FetchRequestMode::kSameOrigin) {
OnResponseRejected(
- ServiceWorkerResponseError::kResponseTypeCORSForRequestModeSameOrigin);
+ ServiceWorkerResponseError::kResponseTypeCorsForRequestModeSameOrigin);
return;
}
if (response_type == network::mojom::FetchResponseType::kOpaque) {
- if (request_mode_ != network::mojom::FetchRequestMode::kNoCORS) {
+ if (request_mode_ != network::mojom::FetchRequestMode::kNoCors) {
OnResponseRejected(ServiceWorkerResponseError::kResponseTypeOpaque);
return;
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.h b/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.h
index 892927e5aa4..631ed3797b7 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.h
@@ -22,6 +22,14 @@ class WaitUntilObserver;
// notifies the client.
class MODULES_EXPORT FetchRespondWithObserver : public RespondWithObserver {
public:
+ FetchRespondWithObserver(ExecutionContext*,
+ int fetch_event_id,
+ const KURL& request_url,
+ network::mojom::FetchRequestMode,
+ network::mojom::FetchRedirectMode,
+ network::mojom::RequestContextFrameType,
+ mojom::RequestContextType,
+ WaitUntilObserver*);
~FetchRespondWithObserver() override = default;
static FetchRespondWithObserver* Create(
@@ -43,16 +51,6 @@ class MODULES_EXPORT FetchRespondWithObserver : public RespondWithObserver {
void Trace(blink::Visitor*) override;
- protected:
- FetchRespondWithObserver(ExecutionContext*,
- int fetch_event_id,
- const KURL& request_url,
- network::mojom::FetchRequestMode,
- network::mojom::FetchRedirectMode,
- network::mojom::RequestContextFrameType,
- mojom::RequestContextType,
- WaitUntilObserver*);
-
private:
const KURL request_url_;
const network::mojom::FetchRequestMode request_mode_;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/install_event.cc b/chromium/third_party/blink/renderer/modules/service_worker/install_event.cc
index bf57ae88683..35e3682c048 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/install_event.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/install_event.cc
@@ -12,29 +12,30 @@
namespace blink {
InstallEvent* InstallEvent::Create(const AtomicString& type,
- const ExtendableEventInit& event_init) {
- return new InstallEvent(type, event_init);
+ const ExtendableEventInit* event_init) {
+ return MakeGarbageCollected<InstallEvent>(type, event_init);
}
InstallEvent* InstallEvent::Create(const AtomicString& type,
- const ExtendableEventInit& event_init,
+ const ExtendableEventInit* event_init,
int event_id,
WaitUntilObserver* observer) {
- return new InstallEvent(type, event_init, event_id, observer);
+ return MakeGarbageCollected<InstallEvent>(type, event_init, event_id,
+ observer);
}
InstallEvent::~InstallEvent() = default;
const AtomicString& InstallEvent::InterfaceName() const {
- return EventNames::InstallEvent;
+ return event_interface_names::kInstallEvent;
}
InstallEvent::InstallEvent(const AtomicString& type,
- const ExtendableEventInit& initializer)
+ const ExtendableEventInit* initializer)
: ExtendableEvent(type, initializer), event_id_(0) {}
InstallEvent::InstallEvent(const AtomicString& type,
- const ExtendableEventInit& initializer,
+ const ExtendableEventInit* initializer,
int event_id,
WaitUntilObserver* observer)
: ExtendableEvent(type, initializer, observer), event_id_(event_id) {}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/install_event.h b/chromium/third_party/blink/renderer/modules/service_worker/install_event.h
index 14cfeba1699..5cbc94b2e07 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/install_event.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/install_event.h
@@ -16,22 +16,22 @@ class MODULES_EXPORT InstallEvent : public ExtendableEvent {
public:
static InstallEvent* Create(const AtomicString& type,
- const ExtendableEventInit&);
+ const ExtendableEventInit*);
static InstallEvent* Create(const AtomicString& type,
- const ExtendableEventInit&,
+ const ExtendableEventInit*,
int event_id,
WaitUntilObserver*);
+ InstallEvent(const AtomicString& type, const ExtendableEventInit*);
+ InstallEvent(const AtomicString& type,
+ const ExtendableEventInit*,
+ int event_id,
+ WaitUntilObserver*);
~InstallEvent() override;
const AtomicString& InterfaceName() const override;
protected:
- InstallEvent(const AtomicString& type, const ExtendableEventInit&);
- InstallEvent(const AtomicString& type,
- const ExtendableEventInit&,
- int event_id,
- WaitUntilObserver*);
const int event_id_;
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.cc b/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.cc
deleted file mode 100644
index 88d4c2ac601..00000000000
--- a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.cc
+++ /dev/null
@@ -1,90 +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 "third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.h"
-
-#include "third_party/blink/public/platform/modules/service_worker/web_navigation_preload_state.h"
-#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
-#include "third_party/blink/renderer/core/dom/dom_exception.h"
-#include "third_party/blink/renderer/modules/service_worker/navigation_preload_state.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_error.h"
-
-namespace blink {
-
-EnableNavigationPreloadCallbacks::EnableNavigationPreloadCallbacks(
- ScriptPromiseResolver* resolver)
- : resolver_(resolver) {
- DCHECK(resolver_);
-}
-
-EnableNavigationPreloadCallbacks::~EnableNavigationPreloadCallbacks() = default;
-
-void EnableNavigationPreloadCallbacks::OnSuccess() {
- if (!resolver_->GetExecutionContext() ||
- resolver_->GetExecutionContext()->IsContextDestroyed())
- return;
- resolver_->Resolve();
-}
-
-void EnableNavigationPreloadCallbacks::OnError(
- const WebServiceWorkerError& error) {
- if (!resolver_->GetExecutionContext() ||
- resolver_->GetExecutionContext()->IsContextDestroyed())
- return;
- resolver_->Reject(ServiceWorkerError::Take(resolver_.Get(), error));
-}
-
-GetNavigationPreloadStateCallbacks::GetNavigationPreloadStateCallbacks(
- ScriptPromiseResolver* resolver)
- : resolver_(resolver) {
- DCHECK(resolver_);
-}
-
-GetNavigationPreloadStateCallbacks::~GetNavigationPreloadStateCallbacks() =
- default;
-
-void GetNavigationPreloadStateCallbacks::OnSuccess(
- const WebNavigationPreloadState& state) {
- if (!resolver_->GetExecutionContext() ||
- resolver_->GetExecutionContext()->IsContextDestroyed())
- return;
- NavigationPreloadState dict;
- dict.setEnabled(state.enabled);
- dict.setHeaderValue(state.header_value);
- resolver_->Resolve(dict);
-}
-
-void GetNavigationPreloadStateCallbacks::OnError(
- const WebServiceWorkerError& error) {
- if (!resolver_->GetExecutionContext() ||
- resolver_->GetExecutionContext()->IsContextDestroyed())
- return;
- resolver_->Reject(ServiceWorkerError::Take(resolver_.Get(), error));
-}
-
-SetNavigationPreloadHeaderCallbacks::SetNavigationPreloadHeaderCallbacks(
- ScriptPromiseResolver* resolver)
- : resolver_(resolver) {
- DCHECK(resolver_);
-}
-
-SetNavigationPreloadHeaderCallbacks::~SetNavigationPreloadHeaderCallbacks() =
- default;
-
-void SetNavigationPreloadHeaderCallbacks::OnSuccess() {
- if (!resolver_->GetExecutionContext() ||
- resolver_->GetExecutionContext()->IsContextDestroyed())
- return;
- resolver_->Resolve();
-}
-
-void SetNavigationPreloadHeaderCallbacks::OnError(
- const WebServiceWorkerError& error) {
- if (!resolver_->GetExecutionContext() ||
- resolver_->GetExecutionContext()->IsContextDestroyed())
- return;
- resolver_->Reject(ServiceWorkerError::Take(resolver_.Get(), error));
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.h b/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.h
deleted file mode 100644
index 89d60fb47b8..00000000000
--- a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.h
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2016 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_NAVIGATION_PRELOAD_CALLBACKS_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_NAVIGATION_PRELOAD_CALLBACKS_H_
-
-#include "base/macros.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration.h"
-#include "third_party/blink/renderer/platform/heap/persistent.h"
-
-namespace blink {
-
-class ScriptPromiseResolver;
-struct WebNavigationPreloadState;
-struct WebServiceWorkerError;
-
-class EnableNavigationPreloadCallbacks final
- : public WebServiceWorkerRegistration::WebEnableNavigationPreloadCallbacks {
- public:
- explicit EnableNavigationPreloadCallbacks(ScriptPromiseResolver*);
- ~EnableNavigationPreloadCallbacks() override;
-
- // WebEnableNavigationPreloadCallbacks interface.
- void OnSuccess() override;
- void OnError(const WebServiceWorkerError&) override;
-
- private:
- Persistent<ScriptPromiseResolver> resolver_;
- DISALLOW_COPY_AND_ASSIGN(EnableNavigationPreloadCallbacks);
-};
-
-class GetNavigationPreloadStateCallbacks final
- : public WebServiceWorkerRegistration::
- WebGetNavigationPreloadStateCallbacks {
- public:
- explicit GetNavigationPreloadStateCallbacks(ScriptPromiseResolver*);
- ~GetNavigationPreloadStateCallbacks() override;
-
- // WebGetNavigationPreloadStateCallbacks interface.
- void OnSuccess(const WebNavigationPreloadState&) override;
- void OnError(const WebServiceWorkerError&) override;
-
- private:
- Persistent<ScriptPromiseResolver> resolver_;
- DISALLOW_COPY_AND_ASSIGN(GetNavigationPreloadStateCallbacks);
-};
-
-class SetNavigationPreloadHeaderCallbacks final
- : public WebServiceWorkerRegistration::
- WebSetNavigationPreloadHeaderCallbacks {
- public:
- explicit SetNavigationPreloadHeaderCallbacks(ScriptPromiseResolver*);
- ~SetNavigationPreloadHeaderCallbacks() override;
-
- // WebSetNavigationPreloadHeaderCallbacks interface.
- void OnSuccess(void) override;
- void OnError(const WebServiceWorkerError&) override;
-
- private:
- Persistent<ScriptPromiseResolver> resolver_;
- DISALLOW_COPY_AND_ASSIGN(SetNavigationPreloadHeaderCallbacks);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_NAVIGATION_PRELOAD_CALLBACKS_H_
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.cc b/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.cc
index e64157b046b..7183dc9dd14 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.cc
@@ -8,8 +8,6 @@
#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
-#include "third_party/blink/renderer/modules/service_worker/navigation_preload_callbacks.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_container_client.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
@@ -36,16 +34,14 @@ ScriptPromise NavigationPreloadManager::setHeaderValue(
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- registration_->WebRegistration()->SetNavigationPreloadHeader(
- value, std::make_unique<SetNavigationPreloadHeaderCallbacks>(resolver));
+ registration_->SetNavigationPreloadHeader(value, resolver);
return promise;
}
ScriptPromise NavigationPreloadManager::getState(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- registration_->WebRegistration()->GetNavigationPreloadState(
- std::make_unique<GetNavigationPreloadStateCallbacks>(resolver));
+ registration_->GetNavigationPreloadState(resolver);
return promise;
}
@@ -57,8 +53,7 @@ ScriptPromise NavigationPreloadManager::SetEnabled(bool enable,
ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
- registration_->WebRegistration()->EnableNavigationPreload(
- enable, std::make_unique<EnableNavigationPreloadCallbacks>(resolver));
+ registration_->EnableNavigationPreload(enable, resolver);
return promise;
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.h b/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.h
index 263ff5cb605..a04c52825d2 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/navigation_preload_manager.h
@@ -19,9 +19,11 @@ class NavigationPreloadManager final : public ScriptWrappable {
public:
static NavigationPreloadManager* Create(
ServiceWorkerRegistration* registration) {
- return new NavigationPreloadManager(registration);
+ return MakeGarbageCollected<NavigationPreloadManager>(registration);
}
+ explicit NavigationPreloadManager(ServiceWorkerRegistration*);
+
ScriptPromise enable(ScriptState*);
ScriptPromise disable(ScriptState*);
ScriptPromise setHeaderValue(ScriptState*, const String& value);
@@ -30,8 +32,6 @@ class NavigationPreloadManager final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- explicit NavigationPreloadManager(ServiceWorkerRegistration*);
-
ScriptPromise SetEnabled(bool enable, ScriptState*);
Member<ServiceWorkerRegistration> registration_;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc b/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc
index 4c438f47edd..bd2c427bbe5 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc
@@ -45,7 +45,7 @@ NavigatorServiceWorker* NavigatorServiceWorker::From(Document& document) {
NavigatorServiceWorker& NavigatorServiceWorker::From(Navigator& navigator) {
NavigatorServiceWorker* supplement = ToNavigatorServiceWorker(navigator);
if (!supplement) {
- supplement = new NavigatorServiceWorker(navigator);
+ supplement = MakeGarbageCollected<NavigatorServiceWorker>(navigator);
ProvideTo(navigator, supplement);
}
if (navigator.GetFrame() && navigator.GetFrame()
@@ -122,23 +122,13 @@ ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(
frame->GetSecurityContext()->GetSecurityOrigin()->IsLocal()) {
UseCounter::Count(frame, WebFeature::kFileAccessedServiceWorker);
}
- if (!service_worker_ && frame) {
- // We need to create a new ServiceWorkerContainer when the frame
- // navigates to a new document. In practice, this happens only when the
- // frame navigates from the initial empty page to a new same-origin page.
- DCHECK(frame->DomWindow());
- service_worker_ = ServiceWorkerContainer::Create(
- frame->DomWindow()->GetExecutionContext(), this);
- }
- return service_worker_.Get();
-}
-
-void NavigatorServiceWorker::ClearServiceWorker() {
- service_worker_ = nullptr;
+ if (!frame)
+ return nullptr;
+ return ServiceWorkerContainer::From(
+ To<Document>(frame->DomWindow()->GetExecutionContext()));
}
void NavigatorServiceWorker::Trace(blink::Visitor* visitor) {
- visitor->Trace(service_worker_);
Supplement<Navigator>::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.h b/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.h
index 681910dfe41..11747d692fe 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/navigator_service_worker.h
@@ -35,16 +35,13 @@ class MODULES_EXPORT NavigatorServiceWorker final
static ServiceWorkerContainer* serviceWorker(ScriptState*,
Navigator&,
String& error_message);
- void ClearServiceWorker();
+ explicit NavigatorServiceWorker(Navigator&);
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorServiceWorker(Navigator&);
ServiceWorkerContainer* serviceWorker(LocalFrame*, ExceptionState&);
ServiceWorkerContainer* serviceWorker(LocalFrame*, String& error_message);
-
- Member<ServiceWorkerContainer> service_worker_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker.cc
index e16880a2b11..89173f7e2bc 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker.cc
@@ -41,7 +41,7 @@
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/messaging/post_message_options.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_container_client.h"
+#include "third_party/blink/renderer/modules/service_worker/service_worker_container.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
@@ -49,22 +49,22 @@
namespace blink {
const AtomicString& ServiceWorker::InterfaceName() const {
- return EventTargetNames::ServiceWorker;
+ return event_target_names::kServiceWorker;
}
void ServiceWorker::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void ServiceWorker::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
if (!GetExecutionContext()) {
exception_state.ThrowDOMException(
@@ -111,7 +111,7 @@ ScriptPromise ServiceWorker::InternalsTerminate(ScriptState* script_state) {
void ServiceWorker::StateChanged(mojom::blink::ServiceWorkerState new_state) {
state_ = new_state;
- this->DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ this->DispatchEvent(*Event::Create(event_type_names::kStatechange));
}
String ServiceWorker::scriptURL() const {
@@ -139,6 +139,17 @@ String ServiceWorker::state() const {
return g_null_atom;
}
+ServiceWorker* ServiceWorker::From(
+ ExecutionContext* context,
+ mojom::blink::ServiceWorkerObjectInfoPtr info) {
+ if (!info)
+ return nullptr;
+ return From(context, WebServiceWorkerObjectInfo(
+ info->version_id, info->state, info->url,
+ info->host_ptr_info.PassHandle(),
+ info->request.PassHandle()));
+}
+
ServiceWorker* ServiceWorker::From(ExecutionContext* context,
WebServiceWorkerObjectInfo info) {
if (!context)
@@ -146,12 +157,11 @@ ServiceWorker* ServiceWorker::From(ExecutionContext* context,
if (info.version_id == mojom::blink::kInvalidServiceWorkerVersionId)
return nullptr;
- if (context->IsServiceWorkerGlobalScope()) {
- return ToServiceWorkerGlobalScope(context)->GetOrCreateServiceWorker(
- std::move(info));
+ if (auto* scope = DynamicTo<ServiceWorkerGlobalScope>(context)) {
+ return scope->GetOrCreateServiceWorker(std::move(info));
}
- return ServiceWorkerContainerClient::From(To<Document>(context))
+ return ServiceWorkerContainer::From(To<Document>(context))
->GetOrCreateServiceWorker(std::move(info));
}
@@ -173,11 +183,15 @@ ServiceWorker::ServiceWorker(ExecutionContext* execution_context,
state_(info.state),
binding_(this) {
DCHECK_NE(mojom::blink::kInvalidServiceWorkerVersionId, info.version_id);
- host_.Bind(mojom::blink::ServiceWorkerObjectHostAssociatedPtrInfo(
- std::move(info.host_ptr_info),
- mojom::blink::ServiceWorkerObjectHost::Version_));
- binding_.Bind(mojom::blink::ServiceWorkerObjectAssociatedRequest(
- std::move(info.request)));
+ host_.Bind(
+ mojom::blink::ServiceWorkerObjectHostAssociatedPtrInfo(
+ std::move(info.host_ptr_info),
+ mojom::blink::ServiceWorkerObjectHost::Version_),
+ execution_context->GetTaskRunner(blink::TaskType::kInternalDefault));
+ binding_.Bind(
+ mojom::blink::ServiceWorkerObjectAssociatedRequest(
+ std::move(info.request)),
+ execution_context->GetTaskRunner(blink::TaskType::kInternalDefault));
}
ServiceWorker::~ServiceWorker() = default;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker.h
index f6d3cb7b5ff..c999f730a5f 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker.h
@@ -55,6 +55,10 @@ class MODULES_EXPORT ServiceWorker final
USING_GARBAGE_COLLECTED_MIXIN(ServiceWorker);
public:
+ static ServiceWorker* From(ExecutionContext*,
+ mojom::blink::ServiceWorkerObjectInfoPtr);
+ // TODO(crbug.com/879019): Eventually we'll remove WebServiceWorkerObjectInfo
+ // and use the above From() everywhere instead of this one.
static ServiceWorker* From(ExecutionContext*, WebServiceWorkerObjectInfo);
ServiceWorker(ExecutionContext*, WebServiceWorkerObjectInfo);
@@ -70,12 +74,12 @@ class MODULES_EXPORT ServiceWorker final
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
String scriptURL() const;
String state() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
ServiceWorker* ToServiceWorker() override { return this; }
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker.idl b/chromium/third_party/blink/renderer/modules/service_worker/service_worker.idl
index 44814895f2e..8ee3e022618 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker.idl
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker.idl
@@ -43,8 +43,8 @@ enum ServiceWorkerState {
SecureContext
] interface ServiceWorker : EventTarget {
- [CallWith=ScriptState, RaisesException] void postMessage(any message, optional sequence<object> transfer = []);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, optional PostMessageOptions options);
readonly attribute USVString scriptURL;
readonly attribute ServiceWorkerState state;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.cc
index a6c32d2b03b..0e556cf4fca 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.cc
@@ -23,12 +23,12 @@ namespace blink {
ServiceWorkerClient* ServiceWorkerClient::Create(
const WebServiceWorkerClientInfo& info) {
- return new ServiceWorkerClient(info);
+ return MakeGarbageCollected<ServiceWorkerClient>(info);
}
ServiceWorkerClient* ServiceWorkerClient::Create(
const mojom::blink::ServiceWorkerClientInfo& info) {
- return new ServiceWorkerClient(info);
+ return MakeGarbageCollected<ServiceWorkerClient>(info);
}
ServiceWorkerClient::ServiceWorkerClient(const WebServiceWorkerClientInfo& info)
@@ -83,15 +83,15 @@ void ServiceWorkerClient::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void ServiceWorkerClient::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
Transferables transferables;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.h
index e6c44cb9762..a19e4653138 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_client.h
@@ -27,6 +27,8 @@ class MODULES_EXPORT ServiceWorkerClient : public ScriptWrappable {
static ServiceWorkerClient* Create(
const mojom::blink::ServiceWorkerClientInfo&);
+ explicit ServiceWorkerClient(const WebServiceWorkerClientInfo&);
+ explicit ServiceWorkerClient(const mojom::blink::ServiceWorkerClientInfo&);
~ServiceWorkerClient() override;
// Client.idl
@@ -40,13 +42,10 @@ class MODULES_EXPORT ServiceWorkerClient : public ScriptWrappable {
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
protected:
- explicit ServiceWorkerClient(const WebServiceWorkerClientInfo&);
- explicit ServiceWorkerClient(const mojom::blink::ServiceWorkerClientInfo&);
-
String Uuid() const { return uuid_; }
private:
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.cc
index af1a97e11d5..6ea5d173152 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.cc
@@ -104,7 +104,7 @@ void DidGetClients(ScriptPromiseResolver* resolver,
} // namespace
ServiceWorkerClients* ServiceWorkerClients::Create() {
- return new ServiceWorkerClients();
+ return MakeGarbageCollected<ServiceWorkerClients>();
}
ServiceWorkerClients::ServiceWorkerClients() = default;
@@ -125,7 +125,7 @@ ScriptPromise ServiceWorkerClients::get(ScriptState* script_state,
ScriptPromise ServiceWorkerClients::matchAll(
ScriptState* script_state,
- const ClientQueryOptions& options) {
+ const ClientQueryOptions* options) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
// FIXME: May be null due to worker termination: http://crbug.com/413518.
if (!execution_context)
@@ -135,7 +135,7 @@ ScriptPromise ServiceWorkerClients::matchAll(
ServiceWorkerGlobalScopeClient::From(execution_context)
->GetClients(
mojom::blink::ServiceWorkerClientQueryOptions::New(
- options.includeUncontrolled(), GetClientType(options.type())),
+ options->includeUncontrolled(), GetClientType(options->type())),
WTF::Bind(&DidGetClients, WrapPersistent(resolver)));
return resolver->Promise();
}
@@ -159,7 +159,8 @@ ScriptPromise ServiceWorkerClients::openWindow(ScriptState* script_state,
ScriptPromise promise = resolver->Promise();
ExecutionContext* context = ExecutionContext::From(script_state);
- KURL parsed_url = KURL(ToWorkerGlobalScope(context)->location()->Url(), url);
+ KURL parsed_url =
+ KURL(To<WorkerGlobalScope>(context)->location()->Url(), url);
if (!parsed_url.IsValid()) {
resolver->Reject(V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "'" + url + "' is not a valid URL."));
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.h
index 3e6bc04da34..aab19e2212b 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_clients.h
@@ -21,14 +21,13 @@ class ServiceWorkerClients final : public ScriptWrappable {
public:
static ServiceWorkerClients* Create();
+ ServiceWorkerClients();
+
// Clients.idl
ScriptPromise get(ScriptState*, const String& id);
- ScriptPromise matchAll(ScriptState*, const ClientQueryOptions&);
+ ScriptPromise matchAll(ScriptState*, const ClientQueryOptions*);
ScriptPromise openWindow(ScriptState*, const String& url);
ScriptPromise claim(ScriptState*);
-
- private:
- ServiceWorkerClients();
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.cc
index 3ef322ab040..4b90c36e91d 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.cc
@@ -34,8 +34,6 @@
#include "base/macros.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
@@ -50,14 +48,14 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/messaging/blink_transferable_message.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
-#include "third_party/blink/renderer/modules/service_worker/navigator_service_worker.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_container_client.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_error.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
@@ -96,18 +94,18 @@ class GetRegistrationCallback : public WebServiceWorkerProvider::
: resolver_(resolver) {}
~GetRegistrationCallback() override = default;
- void OnSuccess(
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) override {
+ void OnSuccess(WebServiceWorkerRegistrationObjectInfo info) override {
if (!resolver_->GetExecutionContext() ||
resolver_->GetExecutionContext()->IsContextDestroyed())
return;
- if (!handle) {
+ if (info.registration_id ==
+ mojom::blink::kInvalidServiceWorkerRegistrationId) {
// Resolve the promise with undefined.
resolver_->Resolve();
return;
}
- resolver_->Resolve(ServiceWorkerRegistration::GetOrCreate(
- resolver_->GetExecutionContext(), std::move(handle)));
+ resolver_->Resolve(
+ ServiceWorkerRegistration::Take(resolver_, std::move(info)));
}
void OnError(const WebServiceWorkerError& error) override {
@@ -132,14 +130,15 @@ class ServiceWorkerContainer::GetRegistrationForReadyCallback
: ready_(ready) {}
~GetRegistrationForReadyCallback() override = default;
- void OnSuccess(
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) override {
+ void OnSuccess(WebServiceWorkerRegistrationObjectInfo info) override {
DCHECK_EQ(ready_->GetState(), ReadyProperty::kPending);
if (ready_->GetExecutionContext() &&
!ready_->GetExecutionContext()->IsContextDestroyed()) {
- ready_->Resolve(ServiceWorkerRegistration::GetOrCreate(
- ready_->GetExecutionContext(), std::move(handle)));
+ ready_->Resolve(
+ ServiceWorkerContainer::From(
+ To<Document>(ready_->GetExecutionContext()))
+ ->GetOrCreateServiceWorkerRegistration(std::move(info)));
}
}
@@ -148,10 +147,38 @@ class ServiceWorkerContainer::GetRegistrationForReadyCallback
DISALLOW_COPY_AND_ASSIGN(GetRegistrationForReadyCallback);
};
-ServiceWorkerContainer* ServiceWorkerContainer::Create(
- ExecutionContext* execution_context,
- NavigatorServiceWorker* navigator) {
- return new ServiceWorkerContainer(execution_context, navigator);
+const char ServiceWorkerContainer::kSupplementName[] = "ServiceWorkerContainer";
+
+ServiceWorkerContainer* ServiceWorkerContainer::From(Document* document) {
+ if (!document)
+ return nullptr;
+
+ ServiceWorkerContainer* container =
+ Supplement<Document>::From<ServiceWorkerContainer>(document);
+ if (!container) {
+ // TODO(leonhsl): Figure out whether it's really necessary to create an
+ // instance when there's no frame or frame client for |document|.
+ container = MakeGarbageCollected<ServiceWorkerContainer>(document);
+ Supplement<Document>::ProvideTo(*document, container);
+ if (document->GetFrame() && document->GetFrame()->Client()) {
+ std::unique_ptr<WebServiceWorkerProvider> provider =
+ document->GetFrame()->Client()->CreateServiceWorkerProvider();
+ if (provider) {
+ provider->SetClient(container);
+ container->provider_ = std::move(provider);
+ }
+ }
+ }
+ return container;
+}
+
+ServiceWorkerContainer* ServiceWorkerContainer::CreateForTesting(
+ Document* document,
+ std::unique_ptr<WebServiceWorkerProvider> provider) {
+ ServiceWorkerContainer* container =
+ MakeGarbageCollected<ServiceWorkerContainer>(document);
+ container->provider_ = std::move(provider);
+ return container;
}
ServiceWorkerContainer::~ServiceWorkerContainer() {
@@ -164,21 +191,22 @@ void ServiceWorkerContainer::ContextDestroyed(ExecutionContext*) {
provider_ = nullptr;
}
controller_ = nullptr;
- navigator_->ClearServiceWorker();
}
void ServiceWorkerContainer::Trace(blink::Visitor* visitor) {
visitor->Trace(controller_);
visitor->Trace(ready_);
- visitor->Trace(navigator_);
+ visitor->Trace(service_worker_registration_objects_);
+ visitor->Trace(service_worker_objects_);
EventTargetWithInlineData::Trace(visitor);
+ Supplement<Document>::Trace(visitor);
ContextLifecycleObserver::Trace(visitor);
}
ScriptPromise ServiceWorkerContainer::registerServiceWorker(
ScriptState* script_state,
const String& url,
- const RegistrationOptions& options) {
+ const RegistrationOptions* options) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -192,7 +220,7 @@ ScriptPromise ServiceWorkerContainer::registerServiceWorker(
// TODO(asamidoi): Remove this check after module loading for
// ServiceWorker is enabled by default (https://crbug.com/824647).
- if (options.type() == "module" &&
+ if (options->type() == "module" &&
!RuntimeEnabledFeatures::ModuleServiceWorkerEnabled()) {
resolver->Reject(DOMException::Create(
DOMExceptionCode::kNotSupportedError,
@@ -216,7 +244,7 @@ ScriptPromise ServiceWorkerContainer::registerServiceWorker(
if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers(
page_url.Protocol())) {
callbacks->OnError(WebServiceWorkerError(
- mojom::blink::ServiceWorkerErrorType::kSecurity,
+ mojom::blink::ServiceWorkerErrorType::kType,
String("Failed to register a ServiceWorker: The URL protocol of the "
"current origin ('" +
document_origin->ToString() + "') is not supported.")));
@@ -226,6 +254,16 @@ ScriptPromise ServiceWorkerContainer::registerServiceWorker(
KURL script_url = execution_context->CompleteURL(url);
script_url.RemoveFragmentIdentifier();
+ if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers(
+ script_url.Protocol())) {
+ callbacks->OnError(WebServiceWorkerError(
+ mojom::blink::ServiceWorkerErrorType::kType,
+ String("Failed to register a ServiceWorker: The URL protocol of the "
+ "script ('" +
+ script_url.GetString() + "') is not supported.")));
+ return promise;
+ }
+
if (!document_origin->CanRequest(script_url)) {
scoped_refptr<const SecurityOrigin> script_origin =
SecurityOrigin::Create(script_url);
@@ -238,47 +276,39 @@ ScriptPromise ServiceWorkerContainer::registerServiceWorker(
document_origin->ToString() + "').")));
return promise;
}
+
+ KURL scope_url;
+ if (options->scope().IsNull())
+ scope_url = KURL(script_url, "./");
+ else
+ scope_url = execution_context->CompleteURL(options->scope());
+ scope_url.RemoveFragmentIdentifier();
+
if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers(
- script_url.Protocol())) {
+ scope_url.Protocol())) {
callbacks->OnError(WebServiceWorkerError(
- mojom::blink::ServiceWorkerErrorType::kSecurity,
+ mojom::blink::ServiceWorkerErrorType::kType,
String("Failed to register a ServiceWorker: The URL protocol of the "
- "script ('" +
- script_url.GetString() + "') is not supported.")));
+ "scope ('" +
+ scope_url.GetString() + "') is not supported.")));
return promise;
}
- KURL pattern_url;
- if (options.scope().IsNull())
- pattern_url = KURL(script_url, "./");
- else
- pattern_url = execution_context->CompleteURL(options.scope());
- pattern_url.RemoveFragmentIdentifier();
-
- if (!document_origin->CanRequest(pattern_url)) {
- scoped_refptr<const SecurityOrigin> pattern_origin =
- SecurityOrigin::Create(pattern_url);
+ if (!document_origin->CanRequest(scope_url)) {
+ scoped_refptr<const SecurityOrigin> scope_origin =
+ SecurityOrigin::Create(scope_url);
callbacks->OnError(
WebServiceWorkerError(mojom::blink::ServiceWorkerErrorType::kSecurity,
String("Failed to register a ServiceWorker: The "
"origin of the provided scope ('" +
- pattern_origin->ToString() +
+ scope_origin->ToString() +
"') does not match the current origin ('" +
document_origin->ToString() + "').")));
return promise;
}
- if (!SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers(
- pattern_url.Protocol())) {
- callbacks->OnError(WebServiceWorkerError(
- mojom::blink::ServiceWorkerErrorType::kSecurity,
- String("Failed to register a ServiceWorker: The URL protocol of the "
- "scope ('" +
- pattern_url.GetString() + "') is not supported.")));
- return promise;
- }
WebString web_error_message;
- if (!provider_->ValidateScopeAndScriptURL(pattern_url, script_url,
+ if (!provider_->ValidateScopeAndScriptURL(scope_url, script_url,
&web_error_message)) {
callbacks->OnError(WebServiceWorkerError(
mojom::blink::ServiceWorkerErrorType::kType,
@@ -305,10 +335,10 @@ ScriptPromise ServiceWorkerContainer::registerServiceWorker(
}
mojom::ServiceWorkerUpdateViaCache update_via_cache =
- ParseUpdateViaCache(options.updateViaCache());
- mojom::ScriptType type = ParseScriptType(options.type());
+ ParseUpdateViaCache(options->updateViaCache());
+ mojom::ScriptType type = ParseScriptType(options->type());
- provider_->RegisterServiceWorker(pattern_url, script_url, type,
+ provider_->RegisterServiceWorker(scope_url, script_url, type,
update_via_cache, std::move(callbacks));
return promise;
}
@@ -440,7 +470,7 @@ void ServiceWorkerContainer::SetController(
WebFeature::kServiceWorkerControlledPage);
}
if (should_notify_controller_change)
- DispatchEvent(*Event::Create(EventTypeNames::controllerchange));
+ DispatchEvent(*Event::Create(event_type_names::kControllerchange));
}
void ServiceWorkerContainer::DispatchMessageEvent(
@@ -476,27 +506,49 @@ void ServiceWorkerContainer::CountFeature(mojom::WebFeature feature) {
Deprecation::CountDeprecation(GetExecutionContext(), feature);
}
+ExecutionContext* ServiceWorkerContainer::GetExecutionContext() const {
+ return GetSupplementable();
+}
+
const AtomicString& ServiceWorkerContainer::InterfaceName() const {
- return EventTargetNames::ServiceWorkerContainer;
+ return event_target_names::kServiceWorkerContainer;
}
-ServiceWorkerContainer::ServiceWorkerContainer(
- ExecutionContext* execution_context,
- NavigatorServiceWorker* navigator)
- : ContextLifecycleObserver(execution_context),
- provider_(nullptr),
- navigator_(navigator) {
- if (!execution_context)
- return;
+ServiceWorkerRegistration*
+ServiceWorkerContainer::GetOrCreateServiceWorkerRegistration(
+ WebServiceWorkerRegistrationObjectInfo info) {
+ if (info.registration_id == mojom::blink::kInvalidServiceWorkerRegistrationId)
+ return nullptr;
+
+ ServiceWorkerRegistration* registration =
+ service_worker_registration_objects_.at(info.registration_id);
+ if (registration) {
+ registration->Attach(std::move(info));
+ return registration;
+ }
+
+ registration = MakeGarbageCollected<ServiceWorkerRegistration>(
+ GetSupplementable(), std::move(info));
+ service_worker_registration_objects_.Set(info.registration_id, registration);
+ return registration;
+}
- if (ServiceWorkerContainerClient* client =
- ServiceWorkerContainerClient::From(To<Document>(execution_context))) {
- provider_ = client->Provider();
- if (provider_)
- provider_->SetClient(this);
+ServiceWorker* ServiceWorkerContainer::GetOrCreateServiceWorker(
+ WebServiceWorkerObjectInfo info) {
+ if (info.version_id == mojom::blink::kInvalidServiceWorkerVersionId)
+ return nullptr;
+ ServiceWorker* worker = service_worker_objects_.at(info.version_id);
+ if (!worker) {
+ worker = MakeGarbageCollected<ServiceWorker>(GetSupplementable(),
+ std::move(info));
+ service_worker_objects_.Set(info.version_id, worker);
}
+ return worker;
}
+ServiceWorkerContainer::ServiceWorkerContainer(Document* document)
+ : Supplement<Document>(*document), ContextLifecycleObserver(document) {}
+
ServiceWorkerContainer::ReadyProperty*
ServiceWorkerContainer::CreateReadyProperty() {
return new ReadyProperty(GetExecutionContext(), this, ReadyProperty::kReady);
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.h
index d45a9db839d..7e9914fec08 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container.h
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_property.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/service_worker/registration_options.h"
@@ -50,11 +51,10 @@
namespace blink {
class ExecutionContext;
-class NavigatorServiceWorker;
-class WebServiceWorkerProvider;
class MODULES_EXPORT ServiceWorkerContainer final
: public EventTargetWithInlineData,
+ public Supplement<Document>,
public ContextLifecycleObserver,
public WebServiceWorkerProviderClient {
DEFINE_WRAPPERTYPEINFO();
@@ -64,19 +64,25 @@ class MODULES_EXPORT ServiceWorkerContainer final
using RegistrationCallbacks =
WebServiceWorkerProvider::WebServiceWorkerRegistrationCallbacks;
- static ServiceWorkerContainer* Create(ExecutionContext*,
- NavigatorServiceWorker*);
+ static const char kSupplementName[];
+
+ static ServiceWorkerContainer* From(Document*);
+
+ static ServiceWorkerContainer* CreateForTesting(
+ Document*,
+ std::unique_ptr<WebServiceWorkerProvider>);
+
+ explicit ServiceWorkerContainer(Document*);
~ServiceWorkerContainer() override;
void Trace(blink::Visitor*) override;
ServiceWorker* controller() { return controller_; }
ScriptPromise ready(ScriptState*);
- WebServiceWorkerProvider* Provider() { return provider_; }
ScriptPromise registerServiceWorker(ScriptState*,
const String& pattern,
- const RegistrationOptions&);
+ const RegistrationOptions*);
ScriptPromise getRegistration(ScriptState*, const String& document_url);
ScriptPromise getRegistrations(ScriptState*);
@@ -90,17 +96,22 @@ class MODULES_EXPORT ServiceWorkerContainer final
void CountFeature(mojom::WebFeature) override;
// EventTarget overrides.
- ExecutionContext* GetExecutionContext() const override {
- return ContextLifecycleObserver::GetExecutionContext();
- }
+ ExecutionContext* GetExecutionContext() const override;
const AtomicString& InterfaceName() const override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(controllerchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(controllerchange, kControllerchange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
- private:
- ServiceWorkerContainer(ExecutionContext*, NavigatorServiceWorker*);
+ // Returns the ServiceWorkerRegistration object described by the given info.
+ // Creates a new object if needed, or else returns the existing one.
+ ServiceWorkerRegistration* GetOrCreateServiceWorkerRegistration(
+ WebServiceWorkerRegistrationObjectInfo);
+ // Returns the ServiceWorker object described by the given info. Creates a new
+ // object if needed, or else returns the existing one.
+ ServiceWorker* GetOrCreateServiceWorker(WebServiceWorkerObjectInfo);
+
+ private:
class GetRegistrationForReadyCallback;
using ReadyProperty =
ScriptPromiseProperty<Member<ServiceWorkerContainer>,
@@ -108,10 +119,24 @@ class MODULES_EXPORT ServiceWorkerContainer final
Member<ServiceWorkerRegistration>>;
ReadyProperty* CreateReadyProperty();
- WebServiceWorkerProvider* provider_;
+ std::unique_ptr<WebServiceWorkerProvider> provider_;
Member<ServiceWorker> controller_;
Member<ReadyProperty> ready_;
- Member<NavigatorServiceWorker> navigator_;
+
+ // Map from service worker registration id to JavaScript
+ // ServiceWorkerRegistration object in current execution context.
+ HeapHashMap<int64_t,
+ WeakMember<ServiceWorkerRegistration>,
+ WTF::IntHash<int64_t>,
+ WTF::UnsignedWithZeroKeyHashTraits<int64_t>>
+ service_worker_registration_objects_;
+ // Map from service worker version id to JavaScript ServiceWorker object in
+ // current execution context.
+ HeapHashMap<int64_t,
+ WeakMember<ServiceWorker>,
+ WTF::IntHash<int64_t>,
+ WTF::UnsignedWithZeroKeyHashTraits<int64_t>>
+ service_worker_objects_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.cc
deleted file mode 100644
index 3f37a5898fb..00000000000
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.cc
+++ /dev/null
@@ -1,59 +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 "third_party/blink/renderer/modules/service_worker/service_worker_container_client.h"
-
-#include <memory>
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/core/frame/local_frame_client.h"
-
-namespace blink {
-
-ServiceWorkerContainerClient::ServiceWorkerContainerClient(
- Document& document,
- std::unique_ptr<WebServiceWorkerProvider> provider)
- : Supplement<Document>(document), provider_(std::move(provider)) {}
-
-ServiceWorkerContainerClient::~ServiceWorkerContainerClient() = default;
-
-const char ServiceWorkerContainerClient::kSupplementName[] =
- "ServiceWorkerContainerClient";
-
-ServiceWorker* ServiceWorkerContainerClient::GetOrCreateServiceWorker(
- WebServiceWorkerObjectInfo info) {
- if (info.version_id == mojom::blink::kInvalidServiceWorkerVersionId)
- return nullptr;
- ServiceWorker* worker = service_worker_objects_.at(info.version_id);
- if (!worker) {
- worker = new ServiceWorker(GetSupplementable(), std::move(info));
- service_worker_objects_.Set(info.version_id, worker);
- }
- return worker;
-}
-
-ServiceWorkerContainerClient* ServiceWorkerContainerClient::From(
- Document* document) {
- if (!document)
- return nullptr;
- if (!document->GetFrame() || !document->GetFrame()->Client())
- return nullptr;
-
- ServiceWorkerContainerClient* client =
- Supplement<Document>::From<ServiceWorkerContainerClient>(document);
- if (!client) {
- client = new ServiceWorkerContainerClient(
- *document,
- document->GetFrame()->Client()->CreateServiceWorkerProvider());
- Supplement<Document>::ProvideTo(*document, client);
- }
- return client;
-}
-
-void ServiceWorkerContainerClient::Trace(blink::Visitor* visitor) {
- visitor->Trace(service_worker_objects_);
- Supplement<Document>::Trace(visitor);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.h
deleted file mode 100644
index 91cdb99791d..00000000000
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_client.h
+++ /dev/null
@@ -1,67 +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 THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_CONTAINER_CLIENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_CONTAINER_CLIENT_H_
-
-#include <memory>
-
-#include "base/macros.h"
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/modules/modules_export.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker.h"
-#include "third_party/blink/renderer/platform/bindings/name_client.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-
-namespace blink {
-
-class WebServiceWorkerProvider;
-
-// This mainly exists to provide access to WebServiceWorkerProvider.
-// Owned by Document.
-class MODULES_EXPORT ServiceWorkerContainerClient final
- : public GarbageCollectedFinalized<ServiceWorkerContainerClient>,
- public Supplement<Document>,
- public NameClient {
- USING_GARBAGE_COLLECTED_MIXIN(ServiceWorkerContainerClient);
-
- public:
- static const char kSupplementName[];
-
- ServiceWorkerContainerClient(Document&,
- std::unique_ptr<WebServiceWorkerProvider>);
- virtual ~ServiceWorkerContainerClient();
-
- // Returns the ServiceWorker object described by the object info in current
- // execution context. Creates a new object if needed, or else returns the
- // existing one.
- ServiceWorker* GetOrCreateServiceWorker(WebServiceWorkerObjectInfo);
-
- WebServiceWorkerProvider* Provider() { return provider_.get(); }
-
- static ServiceWorkerContainerClient* From(Document*);
-
- void Trace(blink::Visitor* visitor) override;
-
- const char* NameInHeapSnapshot() const override {
- return "ServiceWorkerContainerClient";
- }
-
- private:
- std::unique_ptr<WebServiceWorkerProvider> provider_;
- // Map from service worker version id to JavaScript ServiceWorker object in
- // current execution context.
- HeapHashMap<int64_t,
- WeakMember<ServiceWorker>,
- WTF::IntHash<int64_t>,
- WTF::UnsignedWithZeroKeyHashTraits<int64_t>>
- service_worker_objects_;
-
- DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContainerClient);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_CONTAINER_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_test.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_test.cc
index a750ba02712..072c0a84efc 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_test.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_container_test.cc
@@ -1,4 +1,3 @@
-
// 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.
@@ -24,7 +23,6 @@
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/modules/service_worker/navigator_service_worker.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_container_client.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
@@ -122,6 +120,33 @@ class ExpectDOMException : public ScriptValueTest {
String expected_message_;
};
+// Matches a ScriptValue and a TypeError with a message.
+class ExpectTypeError : public ScriptValueTest {
+ public:
+ ExpectTypeError(const String& expected_message)
+ : expected_message_(expected_message) {}
+
+ ~ExpectTypeError() override = default;
+
+ void operator()(ScriptValue value) const override {
+ v8::Isolate* isolate = value.GetIsolate();
+ v8::Local<v8::Context> context = value.GetContext();
+ v8::Local<v8::Object> error_object =
+ value.V8Value()->ToObject(context).ToLocalChecked();
+ v8::Local<v8::Value> name =
+ error_object->Get(context, V8String(isolate, "name")).ToLocalChecked();
+ v8::Local<v8::Value> message =
+ error_object->Get(context, V8String(isolate, "message"))
+ .ToLocalChecked();
+
+ EXPECT_EQ("TypeError", ToCoreString(name->ToString(isolate)));
+ EXPECT_EQ(expected_message_, ToCoreString(message->ToString(isolate)));
+ }
+
+ private:
+ String expected_message_;
+};
+
// Service Worker-specific tests.
class NotReachedWebServiceWorkerProvider : public WebServiceWorkerProvider {
@@ -129,7 +154,7 @@ class NotReachedWebServiceWorkerProvider : public WebServiceWorkerProvider {
~NotReachedWebServiceWorkerProvider() override = default;
void RegisterServiceWorker(
- const WebURL& pattern,
+ const WebURL& scope,
const WebURL& script_url,
blink::mojom::ScriptType script_type,
mojom::ServiceWorkerUpdateViaCache update_via_cache,
@@ -154,21 +179,11 @@ class ServiceWorkerContainerTest : public PageTestBase {
V8GCController::CollectAllGarbageForTesting(GetIsolate());
}
- ExecutionContext* GetExecutionContext() { return &GetDocument(); }
- NavigatorServiceWorker* GetNavigatorServiceWorker() {
- return NavigatorServiceWorker::From(GetDocument());
- }
v8::Isolate* GetIsolate() { return v8::Isolate::GetCurrent(); }
ScriptState* GetScriptState() {
return ToScriptStateForMainWorld(GetDocument().GetFrame());
}
- void Provide(std::unique_ptr<WebServiceWorkerProvider> provider) {
- Supplement<Document>::ProvideTo(
- GetDocument(),
- new ServiceWorkerContainerClient(GetDocument(), std::move(provider)));
- }
-
void SetPageURL(const String& url) {
// For URL completion.
GetDocument().SetURL(KURL(NullURL(), url));
@@ -187,13 +202,13 @@ class ServiceWorkerContainerTest : public PageTestBase {
const ScriptValueTest& value_test) {
// When the registration is rejected, a register call must not reach
// the provider.
- Provide(std::make_unique<NotReachedWebServiceWorkerProvider>());
-
- ServiceWorkerContainer* container = ServiceWorkerContainer::Create(
- GetExecutionContext(), GetNavigatorServiceWorker());
+ ServiceWorkerContainer* container =
+ ServiceWorkerContainer::CreateForTesting(
+ &GetDocument(),
+ std::make_unique<NotReachedWebServiceWorkerProvider>());
ScriptState::Scope script_scope(GetScriptState());
- RegistrationOptions options;
- options.setScope(scope);
+ RegistrationOptions* options = RegistrationOptions::Create();
+ options->setScope(scope);
ScriptPromise promise =
container->registerServiceWorker(GetScriptState(), script_url, options);
ExpectRejected(GetScriptState(), promise, value_test);
@@ -201,10 +216,10 @@ class ServiceWorkerContainerTest : public PageTestBase {
void TestGetRegistrationRejected(const String& document_url,
const ScriptValueTest& value_test) {
- Provide(std::make_unique<NotReachedWebServiceWorkerProvider>());
-
- ServiceWorkerContainer* container = ServiceWorkerContainer::Create(
- GetExecutionContext(), GetNavigatorServiceWorker());
+ ServiceWorkerContainer* container =
+ ServiceWorkerContainer::CreateForTesting(
+ &GetDocument(),
+ std::make_unique<NotReachedWebServiceWorkerProvider>());
ScriptState::Scope script_scope(GetScriptState());
ScriptPromise promise =
container->getRegistration(GetScriptState(), document_url);
@@ -224,14 +239,24 @@ TEST_F(ServiceWorkerContainerTest, Register_CrossOriginScriptIsRejected) {
"current origin ('https://www.example.com')."));
}
+TEST_F(ServiceWorkerContainerTest, Register_UnsupportedSchemeIsRejected) {
+ SetPageURL("https://www.example.com");
+ TestRegisterRejected(
+ "https://www.example.com",
+ "wss://www.example.com/", // Only support http and https
+ ExpectTypeError(
+ "Failed to register a ServiceWorker: The URL protocol "
+ "of the scope ('wss://www.example.com/') is not supported."));
+}
+
TEST_F(ServiceWorkerContainerTest, Register_CrossOriginScopeIsRejected) {
SetPageURL("https://www.example.com");
TestRegisterRejected(
"https://www.example.com",
- "wss://www.example.com/", // Differs by protocol
+ "http://www.example.com/", // Differs by protocol
ExpectDOMException("SecurityError",
"Failed to register a ServiceWorker: The origin of "
- "the provided scope ('wss://www.example.com') does "
+ "the provided scope ('http://www.example.com') does "
"not match the current origin "
"('https://www.example.com')."));
}
@@ -282,14 +307,14 @@ class StubWebServiceWorkerProvider {
~WebServiceWorkerProviderImpl() override = default;
void RegisterServiceWorker(
- const WebURL& pattern,
+ const WebURL& scope,
const WebURL& script_url,
blink::mojom::ScriptType script_type,
mojom::ServiceWorkerUpdateViaCache update_via_cache,
std::unique_ptr<WebServiceWorkerRegistrationCallbacks> callbacks)
override {
owner_.register_call_count_++;
- owner_.register_scope_ = pattern;
+ owner_.register_scope_ = scope;
owner_.register_script_url_ = script_url;
owner_.script_type_ = script_type;
owner_.update_via_cache_ = update_via_cache;
@@ -334,16 +359,14 @@ TEST_F(ServiceWorkerContainerTest,
SetPageURL("http://localhost/x/index.html");
StubWebServiceWorkerProvider stub_provider;
- Provide(stub_provider.Provider());
-
- ServiceWorkerContainer* container = ServiceWorkerContainer::Create(
- GetExecutionContext(), GetNavigatorServiceWorker());
+ ServiceWorkerContainer* container = ServiceWorkerContainer::CreateForTesting(
+ &GetDocument(), stub_provider.Provider());
// register
{
ScriptState::Scope script_scope(GetScriptState());
- RegistrationOptions options;
- options.setScope("y/");
+ RegistrationOptions* options = RegistrationOptions::Create();
+ options->setScope("y/");
container->registerServiceWorker(GetScriptState(), "/x/y/worker.js",
options);
@@ -363,10 +386,8 @@ TEST_F(ServiceWorkerContainerTest,
SetPageURL("http://localhost/x/index.html");
StubWebServiceWorkerProvider stub_provider;
- Provide(stub_provider.Provider());
-
- ServiceWorkerContainer* container = ServiceWorkerContainer::Create(
- GetExecutionContext(), GetNavigatorServiceWorker());
+ ServiceWorkerContainer* container = ServiceWorkerContainer::CreateForTesting(
+ &GetDocument(), stub_provider.Provider());
{
ScriptState::Scope script_scope(GetScriptState());
@@ -385,16 +406,14 @@ TEST_F(ServiceWorkerContainerTest,
SetPageURL("http://localhost/x/index.html");
StubWebServiceWorkerProvider stub_provider;
- Provide(stub_provider.Provider());
-
- ServiceWorkerContainer* container = ServiceWorkerContainer::Create(
- GetExecutionContext(), GetNavigatorServiceWorker());
+ ServiceWorkerContainer* container = ServiceWorkerContainer::CreateForTesting(
+ &GetDocument(), stub_provider.Provider());
// register
{
ScriptState::Scope script_scope(GetScriptState());
- RegistrationOptions options;
- options.setUpdateViaCache("none");
+ RegistrationOptions* options = RegistrationOptions::Create();
+ options->setUpdateViaCache("none");
container->registerServiceWorker(GetScriptState(), "/x/y/worker.js",
options);
@@ -413,16 +432,14 @@ TEST_F(ServiceWorkerContainerTest, Register_TypeOptionDelegatesToProvider) {
SetPageURL("http://localhost/x/index.html");
StubWebServiceWorkerProvider stub_provider;
- Provide(stub_provider.Provider());
-
- ServiceWorkerContainer* container = ServiceWorkerContainer::Create(
- GetExecutionContext(), GetNavigatorServiceWorker());
+ ServiceWorkerContainer* container = ServiceWorkerContainer::CreateForTesting(
+ &GetDocument(), stub_provider.Provider());
// register
{
ScriptState::Scope script_scope(GetScriptState());
- RegistrationOptions options;
- options.setType("module");
+ RegistrationOptions* options = RegistrationOptions::Create();
+ options->setType("module");
container->registerServiceWorker(GetScriptState(), "/x/y/worker.js",
options);
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.cc
index f545f92c75a..e11ec2a1798 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.cc
@@ -21,10 +21,9 @@ bool ServiceWorkerContentSettingsProxy::RequestFileSystemAccessSync() {
}
bool ServiceWorkerContentSettingsProxy::AllowIndexedDB(
- const blink::WebString& name,
const blink::WebSecurityOrigin&) {
bool result = false;
- GetService()->AllowIndexedDB(name, &result);
+ GetService()->AllowIndexedDB(&result);
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.h
index 188a62ba895..75ce9b1fb02 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.h
@@ -28,7 +28,7 @@ class ServiceWorkerContentSettingsProxy final
// Asks the browser process about the settings.
// Blocks until the response arrives.
bool RequestFileSystemAccessSync() override;
- bool AllowIndexedDB(const WebString& name, const WebSecurityOrigin&) override;
+ bool AllowIndexedDB(const WebSecurityOrigin&) override;
private:
// To ensure the returned pointer is destructed on the same thread
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc
index 1430d951115..b8e62374a1a 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc
@@ -34,6 +34,7 @@
#include <utility>
#include "base/memory/ptr_util.h"
+#include "base/numerics/safe_conversions.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
@@ -52,12 +53,13 @@
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/installed_scripts_manager.h"
#include "third_party/blink/renderer/core/workers/worker_clients.h"
-#include "third_party/blink/renderer/core/workers/worker_module_tree_client.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/service_worker/respond_with_observer.h"
+#include "third_party/blink/renderer/modules/service_worker/service_worker.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_clients.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h"
+#include "third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_script_cached_metadata_handler.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_thread.h"
@@ -101,12 +103,13 @@ ServiceWorkerGlobalScope* ServiceWorkerGlobalScope::Create(
// CSP headers, referrer policy, and origin trial tokens will be provided by
// the InstalledScriptsManager in EvaluateClassicScript().
DCHECK(creation_params->content_security_policy_parsed_headers.IsEmpty());
- DCHECK_EQ(kReferrerPolicyDefault, creation_params->referrer_policy);
+ DCHECK_EQ(network::mojom::ReferrerPolicy::kDefault,
+ creation_params->referrer_policy);
DCHECK(creation_params->origin_trial_tokens->IsEmpty());
}
- return new ServiceWorkerGlobalScope(std::move(creation_params), thread,
- std::move(cache_storage_info),
- time_origin);
+ return MakeGarbageCollected<ServiceWorkerGlobalScope>(
+ std::move(creation_params), thread, std::move(cache_storage_info),
+ time_origin);
}
ServiceWorkerGlobalScope::ServiceWorkerGlobalScope(
@@ -126,9 +129,12 @@ void ServiceWorkerGlobalScope::ReadyToEvaluateScript() {
std::move(evaluate_script_).Run();
}
+bool ServiceWorkerGlobalScope::ShouldInstallV8Extensions() const {
+ return Platform::Current()->AllowScriptExtensionForServiceWorker(Url());
+}
+
void ServiceWorkerGlobalScope::EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data) {
DCHECK(IsContextThread());
@@ -136,8 +142,8 @@ void ServiceWorkerGlobalScope::EvaluateClassicScript(
if (!evaluate_script_ready_) {
evaluate_script_ =
WTF::Bind(&ServiceWorkerGlobalScope::EvaluateClassicScript,
- WrapWeakPersistent(this), script_url, access_control_status,
- std::move(source_code), std::move(cached_meta_data));
+ WrapWeakPersistent(this), script_url, std::move(source_code),
+ std::move(cached_meta_data));
return;
}
@@ -150,6 +156,9 @@ void ServiceWorkerGlobalScope::EvaluateClassicScript(
std::unique_ptr<InstalledScriptsManager::ScriptData> script_data =
installed_scripts_manager->GetScriptData(script_url);
if (!script_data) {
+ ReportingProxy().DidFailToLoadInstalledClassicScript();
+ // This will eventually initiate worker thread termination. See
+ // ServiceWorkerGlobalScopeProxy::DidCloseWorkerGlobalScope() for details.
close();
return;
}
@@ -176,8 +185,7 @@ void ServiceWorkerGlobalScope::EvaluateClassicScript(
ReportingProxy().DidLoadInstalledScript();
}
- WorkerGlobalScope::EvaluateClassicScript(script_url, access_control_status,
- source_code,
+ WorkerGlobalScope::EvaluateClassicScript(script_url, source_code,
std::move(cached_meta_data));
}
@@ -187,10 +195,18 @@ void ServiceWorkerGlobalScope::ImportModuleScript(
network::mojom::FetchCredentialsMode credentials_mode) {
Modulator* modulator = Modulator::From(ScriptController()->GetScriptState());
+ ModuleScriptCustomFetchType fetch_type =
+ ModuleScriptCustomFetchType::kWorkerConstructor;
+ InstalledScriptsManager* installed_scripts_manager =
+ GetThread()->GetInstalledScriptsManager();
+ if (installed_scripts_manager &&
+ installed_scripts_manager->IsScriptInstalled(module_url_record)) {
+ fetch_type = ModuleScriptCustomFetchType::kInstalledServiceWorker;
+ }
+
FetchModuleScript(module_url_record, outside_settings_object,
mojom::RequestContextType::SERVICE_WORKER, credentials_mode,
- ModuleScriptCustomFetchType::kWorkerConstructor,
- new WorkerModuleTreeClient(modulator));
+ fetch_type, new ServiceWorkerModuleTreeClient(modulator));
}
void ServiceWorkerGlobalScope::Dispose() {
@@ -202,17 +218,19 @@ void ServiceWorkerGlobalScope::Dispose() {
void ServiceWorkerGlobalScope::CountWorkerScript(size_t script_size,
size_t cached_metadata_size) {
- DCHECK_EQ(GetScriptType(), ScriptType::kClassic);
+ DCHECK_EQ(GetScriptType(), mojom::ScriptType::kClassic);
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, script_size_histogram,
("ServiceWorker.ScriptSize", 1000, 5000000, 50));
- script_size_histogram.Count(script_size);
+ script_size_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(script_size));
if (cached_metadata_size) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, script_cached_metadata_size_histogram,
("ServiceWorker.ScriptCachedMetadataSize", 1000, 50000000, 50));
- script_cached_metadata_size_histogram.Count(cached_metadata_size);
+ script_cached_metadata_size_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(cached_metadata_size));
}
CountScriptInternal(script_size, cached_metadata_size);
@@ -221,7 +239,7 @@ void ServiceWorkerGlobalScope::CountWorkerScript(size_t script_size,
void ServiceWorkerGlobalScope::CountImportedScript(
size_t script_size,
size_t cached_metadata_size) {
- DCHECK_EQ(GetScriptType(), ScriptType::kClassic);
+ DCHECK_EQ(GetScriptType(), mojom::ScriptType::kClassic);
CountScriptInternal(script_size, cached_metadata_size);
}
@@ -232,7 +250,7 @@ void ServiceWorkerGlobalScope::DidEvaluateScript() {
// Skip recording UMAs for module scripts because there're no ways to get the
// number of static-imported scripts and the total size of the imported
// scripts.
- if (GetScriptType() == ScriptType::kModule) {
+ if (GetScriptType() == mojom::ScriptType::kModule) {
return;
}
@@ -240,16 +258,20 @@ void ServiceWorkerGlobalScope::DidEvaluateScript() {
// if they're no longer used.
DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, script_count_histogram,
("ServiceWorker.ScriptCount", 1, 1000, 50));
- script_count_histogram.Count(script_count_);
+ script_count_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(script_count_));
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, script_total_size_histogram,
("ServiceWorker.ScriptTotalSize", 1000, 5000000, 50));
- script_total_size_histogram.Count(script_total_size_);
+ script_total_size_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(script_total_size_));
if (script_cached_metadata_total_size_) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, cached_metadata_histogram,
("ServiceWorker.ScriptCachedMetadataTotalSize", 1000, 50000000, 50));
- cached_metadata_histogram.Count(script_cached_metadata_total_size_);
+ cached_metadata_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(
+ script_cached_metadata_total_size_));
}
}
@@ -291,11 +313,11 @@ void ServiceWorkerGlobalScope::BindServiceWorkerHost(
}
void ServiceWorkerGlobalScope::SetRegistration(
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) {
+ WebServiceWorkerRegistrationObjectInfo info) {
if (!GetExecutionContext())
return;
- registration_ = ServiceWorkerRegistration::GetOrCreate(
- GetExecutionContext(), base::WrapUnique(handle.release()));
+ registration_ = MakeGarbageCollected<ServiceWorkerRegistration>(
+ GetExecutionContext(), std::move(info));
}
ServiceWorker* ServiceWorkerGlobalScope::GetOrCreateServiceWorker(
@@ -304,7 +326,7 @@ ServiceWorker* ServiceWorkerGlobalScope::GetOrCreateServiceWorker(
return nullptr;
ServiceWorker* worker = service_worker_objects_.at(info.version_id);
if (!worker) {
- worker = new ServiceWorker(this, std::move(info));
+ worker = MakeGarbageCollected<ServiceWorker>(this, std::move(info));
service_worker_objects_.Set(info.version_id, worker);
}
return worker;
@@ -313,7 +335,7 @@ ServiceWorker* ServiceWorkerGlobalScope::GetOrCreateServiceWorker(
bool ServiceWorkerGlobalScope::AddEventListenerInternal(
const AtomicString& event_type,
EventListener* listener,
- const AddEventListenerOptionsResolved& options) {
+ const AddEventListenerOptionsResolved* options) {
if (did_evaluate_script_) {
String message = String::Format(
"Event handler of '%s' event must be added on the initial evaluation "
@@ -327,7 +349,7 @@ bool ServiceWorkerGlobalScope::AddEventListenerInternal(
}
const AtomicString& ServiceWorkerGlobalScope::InterfaceName() const {
- return EventTargetNames::ServiceWorkerGlobalScope;
+ return event_target_names::kServiceWorkerGlobalScope;
}
void ServiceWorkerGlobalScope::DispatchExtendableEvent(
@@ -396,7 +418,7 @@ ServiceWorkerGlobalScope::CreateWorkerScriptCachedMetadataHandler(
ScriptPromise ServiceWorkerGlobalScope::fetch(ScriptState* script_state,
const RequestInfo& input,
- const RequestInit& init,
+ const RequestInit* init,
ExceptionState& exception_state) {
return GlobalFetch::fetch(script_state, *this, input, init, exception_state);
}
@@ -419,14 +441,16 @@ void ServiceWorkerGlobalScope::CountCacheStorageInstalledScript(
CustomCountHistogram, script_size_histogram,
("ServiceWorker.CacheStorageInstalledScript.ScriptSize", 1000, 5000000,
50));
- script_size_histogram.Count(script_size);
+ script_size_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(script_size));
if (script_metadata_size) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, script_metadata_size_histogram,
("ServiceWorker.CacheStorageInstalledScript.CachedMetadataSize", 1000,
50000000, 50));
- script_metadata_size_histogram.Count(script_metadata_size);
+ script_metadata_size_histogram.Count(
+ base::saturated_cast<base::Histogram::Sample>(script_metadata_size));
}
}
@@ -441,13 +465,15 @@ void ServiceWorkerGlobalScope::SetIsInstalling(bool is_installing) {
CustomCountHistogram, cache_storage_installed_script_count_histogram,
("ServiceWorker.CacheStorageInstalledScript.Count", 1, 1000, 50));
cache_storage_installed_script_count_histogram.Count(
- cache_storage_installed_script_count_);
+ base::saturated_cast<base::Histogram::Sample>(
+ cache_storage_installed_script_count_));
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, cache_storage_installed_script_total_size_histogram,
("ServiceWorker.CacheStorageInstalledScript.ScriptTotalSize", 1000,
50000000, 50));
cache_storage_installed_script_total_size_histogram.Count(
- cache_storage_installed_script_total_size_);
+ base::saturated_cast<base::Histogram::Sample>(
+ cache_storage_installed_script_total_size_));
if (cache_storage_installed_script_metadata_total_size_) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
@@ -456,7 +482,8 @@ void ServiceWorkerGlobalScope::SetIsInstalling(bool is_installing) {
("ServiceWorker.CacheStorageInstalledScript.CachedMetadataTotalSize",
1000, 50000000, 50));
cache_storage_installed_script_metadata_total_size_histogram.Count(
- cache_storage_installed_script_metadata_total_size_);
+ base::saturated_cast<base::Histogram::Sample>(
+ cache_storage_installed_script_metadata_total_size_));
}
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h
index 4fc509a1165..1abbcf9aa9a 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h
@@ -33,13 +33,11 @@
#include <memory>
#include "third_party/blink/public/mojom/service_worker/service_worker.mojom-blink.h"
#include "third_party/blink/public/platform/modules/cache_storage/cache_storage.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration.h"
#include "third_party/blink/renderer/bindings/core/v8/request_or_usv_string.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/modules/modules_export.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -48,11 +46,14 @@ class RespondWithObserver;
class RequestInit;
class ScriptPromise;
class ScriptState;
+class ServiceWorker;
class ServiceWorkerClients;
class ServiceWorkerRegistration;
class ServiceWorkerThread;
class WaitUntilObserver;
struct GlobalScopeCreationParams;
+struct WebServiceWorkerObjectInfo;
+struct WebServiceWorkerRegistrationObjectInfo;
typedef RequestOrUSVString RequestInfo;
@@ -66,13 +67,19 @@ class MODULES_EXPORT ServiceWorkerGlobalScope final : public WorkerGlobalScope {
mojom::blink::CacheStoragePtrInfo,
base::TimeTicks time_origin);
+ ServiceWorkerGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
+ ServiceWorkerThread*,
+ mojom::blink::CacheStoragePtrInfo,
+ base::TimeTicks time_origin);
~ServiceWorkerGlobalScope() override;
+
+ // ExecutionContext overrides:
bool IsServiceWorkerGlobalScope() const override { return true; }
+ bool ShouldInstallV8Extensions() const final;
// Implements WorkerGlobalScope.
void EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data) override;
void ImportModuleScript(
@@ -97,18 +104,17 @@ class MODULES_EXPORT ServiceWorkerGlobalScope final : public WorkerGlobalScope {
ScriptPromise fetch(ScriptState*,
const RequestInfo&,
- const RequestInit&,
+ const RequestInit*,
ExceptionState&);
ScriptPromise skipWaiting(ScriptState*);
void BindServiceWorkerHost(mojom::blink::ServiceWorkerHostAssociatedPtrInfo);
- void SetRegistration(std::unique_ptr<WebServiceWorkerRegistration::Handle>);
+ void SetRegistration(WebServiceWorkerRegistrationObjectInfo info);
- // Returns the ServiceWorker object described by the object info in current
- // execution context. Creates a new object if needed, or else returns the
- // existing one.
+ // Returns the ServiceWorker object described by the given info. Creates a new
+ // object if needed, or else returns the existing one.
ServiceWorker* GetOrCreateServiceWorker(WebServiceWorkerObjectInfo);
// EventTarget
@@ -132,10 +138,10 @@ class MODULES_EXPORT ServiceWorkerGlobalScope final : public WorkerGlobalScope {
mojom::blink::CacheStoragePtrInfo TakeCacheStorage();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(install);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(activate);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(fetch);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(install, kInstall);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(activate, kActivate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(fetch, kFetch);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
void Trace(blink::Visitor*) override;
@@ -144,13 +150,9 @@ class MODULES_EXPORT ServiceWorkerGlobalScope final : public WorkerGlobalScope {
bool AddEventListenerInternal(
const AtomicString& event_type,
EventListener*,
- const AddEventListenerOptionsResolved&) override;
+ const AddEventListenerOptionsResolved*) override;
private:
- ServiceWorkerGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
- ServiceWorkerThread*,
- mojom::blink::CacheStoragePtrInfo,
- base::TimeTicks time_origin);
void importScripts(const Vector<String>& urls, ExceptionState&) override;
SingleCachedMetadataHandler* CreateWorkerScriptCachedMetadataHandler(
const KURL& script_url,
@@ -188,11 +190,12 @@ class MODULES_EXPORT ServiceWorkerGlobalScope final : public WorkerGlobalScope {
mojom::blink::CacheStoragePtrInfo cache_storage_info_;
};
-DEFINE_TYPE_CASTS(ServiceWorkerGlobalScope,
- ExecutionContext,
- context,
- context->IsServiceWorkerGlobalScope(),
- context.IsServiceWorkerGlobalScope());
+template <>
+struct DowncastTraits<ServiceWorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsServiceWorkerGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.cc
index 5810258d03b..a90f55499f8 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.cc
@@ -43,6 +43,7 @@
#include "third_party/blink/renderer/modules/service_worker/service_worker_window_client.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -111,7 +112,7 @@ void ServiceWorkerGlobalScopeClient::SetCachedMetadata(const KURL& url,
const char* data,
size_t size) {
Vector<uint8_t> meta_data;
- meta_data.Append(data, size);
+ meta_data.Append(data, SafeCast<wtf_size_t>(size));
service_worker_host_->SetCachedMetadata(url, meta_data);
}
@@ -148,56 +149,44 @@ void ServiceWorkerGlobalScopeClient::Navigate(const String& client_uuid,
void ServiceWorkerGlobalScopeClient::DidHandleActivateEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleActivateEvent(event_id, status, event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleActivateEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleBackgroundFetchAbortEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleBackgroundFetchAbortEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleBackgroundFetchAbortEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleBackgroundFetchClickEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleBackgroundFetchClickEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleBackgroundFetchClickEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleBackgroundFetchFailEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleBackgroundFetchFailEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleBackgroundFetchFailEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleBackgroundFetchSuccessEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleBackgroundFetchSuccessEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleBackgroundFetchSuccessEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleCookieChangeEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleCookieChangeEvent(event_id, status, event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleCookieChangeEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleExtendableMessageEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleExtendableMessageEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleExtendableMessageEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::RespondToFetchEventWithNoResponse(
@@ -230,92 +219,74 @@ void ServiceWorkerGlobalScopeClient::RespondToFetchEventWithResponseStream(
void ServiceWorkerGlobalScopeClient::RespondToAbortPaymentEvent(
int event_id,
- bool abort_payment,
- base::TimeTicks event_dispatch_time) {
- client_.RespondToAbortPaymentEvent(event_id, abort_payment,
- event_dispatch_time);
+ bool abort_payment) {
+ client_.RespondToAbortPaymentEvent(event_id, abort_payment);
}
void ServiceWorkerGlobalScopeClient::RespondToCanMakePaymentEvent(
int event_id,
- bool response,
- base::TimeTicks event_dispatch_time) {
- client_.RespondToCanMakePaymentEvent(event_id, response, event_dispatch_time);
+ bool response) {
+ client_.RespondToCanMakePaymentEvent(event_id, response);
}
void ServiceWorkerGlobalScopeClient::RespondToPaymentRequestEvent(
int event_id,
- const WebPaymentHandlerResponse& response,
- base::TimeTicks event_dispatch_time) {
- client_.RespondToPaymentRequestEvent(event_id, response, event_dispatch_time);
+ const WebPaymentHandlerResponse& response) {
+ client_.RespondToPaymentRequestEvent(event_id, response);
}
void ServiceWorkerGlobalScopeClient::DidHandleFetchEvent(
int fetch_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleFetchEvent(fetch_event_id, status, event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleFetchEvent(fetch_event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleInstallEvent(
int install_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleInstallEvent(install_event_id, status, event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleInstallEvent(install_event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleNotificationClickEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleNotificationClickEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleNotificationClickEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleNotificationCloseEvent(
int event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleNotificationCloseEvent(event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleNotificationCloseEvent(event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandlePushEvent(
int push_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandlePushEvent(push_event_id, status, event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandlePushEvent(push_event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleSyncEvent(
int sync_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleSyncEvent(sync_event_id, status, event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleSyncEvent(sync_event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleAbortPaymentEvent(
int abort_payment_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleAbortPaymentEvent(abort_payment_event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleAbortPaymentEvent(abort_payment_event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandleCanMakePaymentEvent(
int payment_request_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandleCanMakePaymentEvent(payment_request_event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandleCanMakePaymentEvent(payment_request_event_id, status);
}
void ServiceWorkerGlobalScopeClient::DidHandlePaymentRequestEvent(
int payment_request_event_id,
- mojom::ServiceWorkerEventStatus status,
- base::TimeTicks event_dispatch_time) {
- client_.DidHandlePaymentRequestEvent(payment_request_event_id, status,
- event_dispatch_time);
+ mojom::ServiceWorkerEventStatus status) {
+ client_.DidHandlePaymentRequestEvent(payment_request_event_id, status);
}
void ServiceWorkerGlobalScopeClient::BindServiceWorkerHost(
@@ -336,7 +307,7 @@ ServiceWorkerGlobalScopeClient* ServiceWorkerGlobalScopeClient::From(
ExecutionContext* context) {
// TODO(horo): Replace CHECK() to DCHECK() when crbug.com/749930 is fixed.
CHECK(context);
- WorkerClients* worker_clients = ToWorkerGlobalScope(context)->Clients();
+ WorkerClients* worker_clients = To<WorkerGlobalScope>(context)->Clients();
CHECK(worker_clients);
ServiceWorkerGlobalScopeClient* client =
Supplement<WorkerClients>::From<ServiceWorkerGlobalScopeClient>(
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h
index a5336ece430..1959da5b993 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_client.h
@@ -87,28 +87,19 @@ class MODULES_EXPORT ServiceWorkerGlobalScopeClient final
void Focus(const String& client_uuid, FocusCallback);
void Navigate(const String& client_uuid, const KURL&, ScriptPromiseResolver*);
- void DidHandleActivateEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ void DidHandleActivateEvent(int event_id, mojom::ServiceWorkerEventStatus);
void DidHandleBackgroundFetchAbortEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandleBackgroundFetchClickEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandleBackgroundFetchFailEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
- void DidHandleBackgroundFetchSuccessEvent(
- int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
+ void DidHandleBackgroundFetchSuccessEvent(int event_id,
+ mojom::ServiceWorkerEventStatus);
void DidHandleCookieChangeEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandleExtendableMessageEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void RespondToFetchEventWithNoResponse(
int fetch_event_id,
base::TimeTicks event_dispatch_time,
@@ -123,42 +114,25 @@ class MODULES_EXPORT ServiceWorkerGlobalScopeClient final
WebServiceWorkerStreamHandle*,
base::TimeTicks event_dispatch_time,
base::TimeTicks respond_with_settled_time);
- void RespondToAbortPaymentEvent(int event_id,
- bool abort_payment,
- base::TimeTicks event_dispatch_time);
- void RespondToCanMakePaymentEvent(int event_id,
- bool can_make_payment,
- base::TimeTicks event_dispatch_time);
+ void RespondToAbortPaymentEvent(int event_id, bool abort_payment);
+ void RespondToCanMakePaymentEvent(int event_id, bool can_make_payment);
void RespondToPaymentRequestEvent(int event_id,
- const WebPaymentHandlerResponse&,
- base::TimeTicks event_dispatch_time);
- void DidHandleFetchEvent(int fetch_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ const WebPaymentHandlerResponse&);
+ void DidHandleFetchEvent(int fetch_event_id, mojom::ServiceWorkerEventStatus);
void DidHandleInstallEvent(int install_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandleNotificationClickEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandleNotificationCloseEvent(int event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
- void DidHandlePushEvent(int push_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
- void DidHandleSyncEvent(int sync_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
+ void DidHandlePushEvent(int push_event_id, mojom::ServiceWorkerEventStatus);
+ void DidHandleSyncEvent(int sync_event_id, mojom::ServiceWorkerEventStatus);
void DidHandleAbortPaymentEvent(int abort_payment_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandleCanMakePaymentEvent(int payment_request_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void DidHandlePaymentRequestEvent(int payment_request_event_id,
- mojom::ServiceWorkerEventStatus,
- base::TimeTicks event_dispatch_time);
+ mojom::ServiceWorkerEventStatus);
void BindServiceWorkerHost(
mojom::blink::ServiceWorkerHostAssociatedPtrInfo service_worker_host);
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.cc
index f5dd6631a21..8b71293e79f 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom-blink.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom-blink.h"
#include "third_party/blink/public/platform/modules/notifications/web_notification_data.h"
+#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_error.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h"
#include "third_party/blink/public/web/modules/service_worker/web_service_worker_context_client.h"
#include "third_party/blink/public/web/web_serialized_script_value.h"
@@ -86,6 +87,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace mojo {
@@ -143,10 +145,11 @@ struct TypeConverter<blink::mojom::blink::NotificationDataPtr,
static blink::mojom::blink::NotificationDataPtr Convert(
const blink::WebNotificationData& input) {
Vector<int32_t> vibration_pattern;
- vibration_pattern.Append(input.vibrate.Data(), input.vibrate.size());
+ vibration_pattern.Append(input.vibrate.Data(),
+ SafeCast<wtf_size_t>(input.vibrate.size()));
Vector<uint8_t> data;
- data.Append(input.data.Data(), input.data.size());
+ data.Append(input.data.Data(), SafeCast<wtf_size_t>(input.data.size()));
Vector<blink::mojom::blink::NotificationActionPtr> actions;
for (const auto& web_action : input.actions) {
@@ -169,7 +172,8 @@ namespace blink {
ServiceWorkerGlobalScopeProxy* ServiceWorkerGlobalScopeProxy::Create(
WebEmbeddedWorkerImpl& embedded_worker,
WebServiceWorkerContextClient& client) {
- return new ServiceWorkerGlobalScopeProxy(embedded_worker, client);
+ return MakeGarbageCollected<ServiceWorkerGlobalScopeProxy>(embedded_worker,
+ client);
}
ServiceWorkerGlobalScopeProxy::~ServiceWorkerGlobalScopeProxy() {
@@ -192,9 +196,9 @@ void ServiceWorkerGlobalScopeProxy::BindServiceWorkerHost(
}
void ServiceWorkerGlobalScopeProxy::SetRegistration(
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) {
+ WebServiceWorkerRegistrationObjectInfo info) {
DCHECK(WorkerGlobalScope()->IsContextThread());
- WorkerGlobalScope()->SetRegistration(std::move(handle));
+ WorkerGlobalScope()->SetRegistration(std::move(info));
}
void ServiceWorkerGlobalScopeProxy::ReadyToEvaluateScript() {
@@ -215,13 +219,13 @@ void ServiceWorkerGlobalScopeProxy::DispatchBackgroundFetchAbortEvent(
// BackgroundFetchEvent::Create which eventually calls ToV8.
ScriptState::Scope scope(script_state);
- BackgroundFetchEventInit init;
- init.setRegistration(new BackgroundFetchRegistration(
+ BackgroundFetchEventInit* init = BackgroundFetchEventInit::Create();
+ init->setRegistration(new BackgroundFetchRegistration(
WorkerGlobalScope()->registration() /* service_worker_registration */,
registration));
BackgroundFetchEvent* event = BackgroundFetchEvent::Create(
- EventTypeNames::backgroundfetchabort, init, observer);
+ event_type_names::kBackgroundfetchabort, init, observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -233,13 +237,13 @@ void ServiceWorkerGlobalScopeProxy::DispatchBackgroundFetchClickEvent(
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kBackgroundFetchClick, event_id);
- BackgroundFetchEventInit init;
- init.setRegistration(new BackgroundFetchRegistration(
+ BackgroundFetchEventInit* init = BackgroundFetchEventInit::Create();
+ init->setRegistration(new BackgroundFetchRegistration(
WorkerGlobalScope()->registration() /* service_worker_registration */,
registration));
BackgroundFetchEvent* event = BackgroundFetchEvent::Create(
- EventTypeNames::backgroundfetchclick, init, observer);
+ event_type_names::kBackgroundfetchclick, init, observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -258,13 +262,13 @@ void ServiceWorkerGlobalScopeProxy::DispatchBackgroundFetchFailEvent(
// BackgroundFetchSettledEvent::Create which eventually calls ToV8.
ScriptState::Scope scope(script_state);
- BackgroundFetchEventInit init;
- init.setRegistration(new BackgroundFetchRegistration(
+ BackgroundFetchEventInit* init = BackgroundFetchEventInit::Create();
+ init->setRegistration(new BackgroundFetchRegistration(
WorkerGlobalScope()->registration() /* service_worker_registration */,
registration));
BackgroundFetchUpdateUIEvent* event = BackgroundFetchUpdateUIEvent::Create(
- EventTypeNames::backgroundfetchfail, init, observer,
+ event_type_names::kBackgroundfetchfail, init, observer,
worker_global_scope_->registration());
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
@@ -285,13 +289,13 @@ void ServiceWorkerGlobalScopeProxy::DispatchBackgroundFetchSuccessEvent(
// BackgroundFetchSettledEvent::Create which eventually calls ToV8.
ScriptState::Scope scope(script_state);
- BackgroundFetchEventInit init;
- init.setRegistration(new BackgroundFetchRegistration(
+ BackgroundFetchEventInit* init = BackgroundFetchEventInit::Create();
+ init->setRegistration(new BackgroundFetchRegistration(
WorkerGlobalScope()->registration() /* service_worker_registration */,
registration));
BackgroundFetchUpdateUIEvent* event = BackgroundFetchUpdateUIEvent::Create(
- EventTypeNames::backgroundfetchsuccess, init, observer,
+ event_type_names::kBackgroundfetchsuccess, init, observer,
worker_global_scope_->registration());
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
@@ -301,8 +305,8 @@ void ServiceWorkerGlobalScopeProxy::DispatchActivateEvent(int event_id) {
DCHECK(WorkerGlobalScope()->IsContextThread());
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kActivate, event_id);
- Event* event = ExtendableEvent::Create(EventTypeNames::activate,
- ExtendableEventInit(), observer);
+ Event* event = ExtendableEvent::Create(
+ event_type_names::kActivate, ExtendableEventInit::Create(), observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -314,11 +318,11 @@ void ServiceWorkerGlobalScopeProxy::DispatchCookieChangeEvent(
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kCookieChange, event_id);
- HeapVector<CookieListItem> changed;
- HeapVector<CookieListItem> deleted;
+ HeapVector<Member<CookieListItem>> changed;
+ HeapVector<Member<CookieListItem>> deleted;
CookieChangeEvent::ToEventInfo(cookie, change_cause, changed, deleted);
Event* event = ExtendableCookieChangeEvent::Create(
- EventTypeNames::cookiechange, std::move(changed), std::move(deleted),
+ event_type_names::kCookiechange, std::move(changed), std::move(deleted),
observer);
// TODO(pwnall): Handle handle the case when
@@ -393,16 +397,18 @@ void ServiceWorkerGlobalScopeProxy::DispatchFetchEvent(
Request* request = Request::Create(
WorkerGlobalScope()->ScriptController()->GetScriptState(), web_request);
request->getHeaders()->SetGuard(Headers::kImmutableGuard);
- FetchEventInit event_init;
- event_init.setCancelable(true);
- event_init.setRequest(request);
- event_init.setClientId(
+ FetchEventInit* event_init = FetchEventInit::Create();
+ event_init->setCancelable(true);
+ event_init->setRequest(request);
+ event_init->setClientId(
web_request.IsMainResourceLoad() ? WebString() : web_request.ClientId());
- event_init.setIsReload(web_request.IsReload());
+ event_init->setResultingClientId(
+ !web_request.IsMainResourceLoad() ? WebString() : web_request.ClientId());
+ event_init->setIsReload(web_request.IsReload());
ScriptState* script_state =
WorkerGlobalScope()->ScriptController()->GetScriptState();
FetchEvent* fetch_event = FetchEvent::Create(
- script_state, EventTypeNames::fetch, event_init, respond_with_observer,
+ script_state, event_type_names::kFetch, event_init, respond_with_observer,
wait_until_observer, navigation_preload_sent);
if (navigation_preload_sent) {
// Keep |fetchEvent| until OnNavigationPreloadComplete() or
@@ -468,8 +474,9 @@ void ServiceWorkerGlobalScopeProxy::DispatchInstallEvent(int event_id) {
DCHECK(WorkerGlobalScope()->IsContextThread());
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kInstall, event_id);
- Event* event = InstallEvent::Create(
- EventTypeNames::install, ExtendableEventInit(), event_id, observer);
+ Event* event =
+ InstallEvent::Create(event_type_names::kInstall,
+ ExtendableEventInit::Create(), event_id, observer);
WorkerGlobalScope()->SetIsInstalling(true);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -483,14 +490,14 @@ void ServiceWorkerGlobalScopeProxy::DispatchNotificationClickEvent(
DCHECK(WorkerGlobalScope()->IsContextThread());
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kNotificationClick, event_id);
- NotificationEventInit event_init;
- event_init.setNotification(Notification::Create(
+ NotificationEventInit* event_init = NotificationEventInit::Create();
+ event_init->setNotification(Notification::Create(
WorkerGlobalScope(), notification_id,
mojom::blink::NotificationData::From(data), true /* showing */));
if (0 <= action_index && action_index < static_cast<int>(data.actions.size()))
- event_init.setAction(data.actions[action_index].action);
- event_init.setReply(reply);
- Event* event = NotificationEvent::Create(EventTypeNames::notificationclick,
+ event_init->setAction(data.actions[action_index].action);
+ event_init->setReply(reply);
+ Event* event = NotificationEvent::Create(event_type_names::kNotificationclick,
event_init, observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -502,12 +509,12 @@ void ServiceWorkerGlobalScopeProxy::DispatchNotificationCloseEvent(
DCHECK(WorkerGlobalScope()->IsContextThread());
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kNotificationClose, event_id);
- NotificationEventInit event_init;
- event_init.setAction(WTF::String()); // initialize as null.
- event_init.setNotification(Notification::Create(
+ NotificationEventInit* event_init = NotificationEventInit::Create();
+ event_init->setAction(WTF::String()); // initialize as null.
+ event_init->setNotification(Notification::Create(
WorkerGlobalScope(), notification_id,
mojom::blink::NotificationData::From(data), false /* showing */));
- Event* event = NotificationEvent::Create(EventTypeNames::notificationclose,
+ Event* event = NotificationEvent::Create(event_type_names::kNotificationclose,
event_init, observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -517,7 +524,7 @@ void ServiceWorkerGlobalScopeProxy::DispatchPushEvent(int event_id,
DCHECK(WorkerGlobalScope()->IsContextThread());
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kPush, event_id);
- Event* event = PushEvent::Create(EventTypeNames::push,
+ Event* event = PushEvent::Create(event_type_names::kPush,
PushMessageData::Create(data), observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -529,7 +536,7 @@ void ServiceWorkerGlobalScopeProxy::DispatchSyncEvent(int event_id,
WaitUntilObserver* observer = WaitUntilObserver::Create(
WorkerGlobalScope(), WaitUntilObserver::kSync, event_id);
Event* event =
- SyncEvent::Create(EventTypeNames::sync, id, last_chance, observer);
+ SyncEvent::Create(event_type_names::kSync, id, last_chance, observer);
WorkerGlobalScope()->DispatchExtendableEvent(event, observer);
}
@@ -542,7 +549,7 @@ void ServiceWorkerGlobalScopeProxy::DispatchAbortPaymentEvent(int event_id) {
wait_until_observer);
Event* event = AbortPaymentEvent::Create(
- EventTypeNames::abortpayment, ExtendableEventInit(),
+ event_type_names::kAbortpayment, ExtendableEventInit::Create(),
respond_with_observer, wait_until_observer);
WorkerGlobalScope()->DispatchExtendableEventWithRespondWith(
@@ -560,7 +567,7 @@ void ServiceWorkerGlobalScopeProxy::DispatchCanMakePaymentEvent(
wait_until_observer);
Event* event = CanMakePaymentEvent::Create(
- EventTypeNames::canmakepayment,
+ event_type_names::kCanmakepayment,
PaymentEventDataConversion::ToCanMakePaymentEventInit(
WorkerGlobalScope()->ScriptController()->GetScriptState(),
web_event_data),
@@ -581,7 +588,7 @@ void ServiceWorkerGlobalScopeProxy::DispatchPaymentRequestEvent(
wait_until_observer);
Event* event = PaymentRequestEvent::Create(
- EventTypeNames::paymentrequest,
+ event_type_names::kPaymentrequest,
PaymentEventDataConversion::ToPaymentRequestEventInit(
WorkerGlobalScope()->ScriptController()->GetScriptState(),
web_app_request),
@@ -593,7 +600,7 @@ void ServiceWorkerGlobalScopeProxy::DispatchPaymentRequestEvent(
bool ServiceWorkerGlobalScopeProxy::HasFetchEventHandler() {
DCHECK(WorkerGlobalScope()->IsContextThread());
- return WorkerGlobalScope()->HasEventListeners(EventTypeNames::fetch);
+ return WorkerGlobalScope()->HasEventListeners(event_type_names::kFetch);
}
void ServiceWorkerGlobalScopeProxy::CountFeature(WebFeature feature) {
@@ -624,19 +631,6 @@ void ServiceWorkerGlobalScopeProxy::ReportConsoleMessage(
location->Url());
}
-void ServiceWorkerGlobalScopeProxy::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- DCHECK(embedded_worker_);
- PostCrossThreadTask(
- *parent_execution_context_task_runners_->Get(
- TaskType::kInternalInspector),
- FROM_HERE,
- CrossThreadBind(&WebEmbeddedWorkerImpl::PostMessageToPageInspector,
- CrossThreadUnretained(embedded_worker_), session_id,
- message));
-}
-
void ServiceWorkerGlobalScopeProxy::DidCreateWorkerGlobalScope(
WorkerOrWorkletGlobalScope* worker_global_scope) {
DCHECK(!worker_global_scope_);
@@ -658,6 +652,20 @@ void ServiceWorkerGlobalScopeProxy::DidLoadInstalledScript() {
Client().WorkerScriptLoaded();
}
+void ServiceWorkerGlobalScopeProxy::DidFailToLoadInstalledClassicScript() {
+ DCHECK(WorkerGlobalScope()->IsContextThread());
+
+ // Tell ServiceWorkerContextClient about the failure. The generic
+ // WorkerContextFailedToStart() wouldn't make sense because
+ // WorkerContextStarted() was already called.
+ Client().FailedToLoadInstalledClassicScript();
+}
+
+void ServiceWorkerGlobalScopeProxy::DidFailToFetchModuleScript() {
+ DCHECK(WorkerGlobalScope()->IsContextThread());
+ Client().FailedToFetchModuleScript();
+}
+
void ServiceWorkerGlobalScopeProxy::WillEvaluateClassicScript(
size_t script_size,
size_t cached_metadata_size) {
@@ -695,18 +703,13 @@ void ServiceWorkerGlobalScopeProxy::DidEvaluateModuleScript(bool success) {
void ServiceWorkerGlobalScopeProxy::DidCloseWorkerGlobalScope() {
DCHECK(WorkerGlobalScope()->IsContextThread());
- // close() is not web-exposed. This is called when ServiceWorkerGlobalScope
- // internally requests close() due to failure on startup when installed
- // scripts couldn't be read.
+ // close() is not web-exposed for ServiceWorker. This is called when
+ // ServiceWorkerGlobalScope internally requests close(), for example, due to
+ // failure on startup when installed scripts couldn't be read.
//
// This may look like a roundabout way to terminate the thread, but close()
// seems like the standard way to initiate termination from inside the thread.
- // Tell ServiceWorkerContextClient about the failure. The generic
- // WorkerContextFailedToStart() wouldn't make sense because
- // WorkerContextStarted() was already called.
- Client().FailedToLoadInstalledScript();
-
// ServiceWorkerGlobalScope expects us to terminate the thread, so request
// that here.
PostCrossThreadTask(
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.h
index 374e56e66e7..5daac90dd84 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_global_scope_proxy.h
@@ -73,13 +73,15 @@ class ServiceWorkerGlobalScopeProxy final
public:
static ServiceWorkerGlobalScopeProxy* Create(WebEmbeddedWorkerImpl&,
WebServiceWorkerContextClient&);
+
+ ServiceWorkerGlobalScopeProxy(WebEmbeddedWorkerImpl&,
+ WebServiceWorkerContextClient&);
~ServiceWorkerGlobalScopeProxy() override;
// WebServiceWorkerContextProxy overrides:
void BindServiceWorkerHost(
mojo::ScopedInterfaceEndpointHandle service_worker_host) override;
- void SetRegistration(
- std::unique_ptr<WebServiceWorkerRegistration::Handle>) override;
+ void SetRegistration(WebServiceWorkerRegistrationObjectInfo info) override;
// Must be called after the above BindServiceWorkerHost() and
// SetRegistration() got called.
void ReadyToEvaluateScript() override;
@@ -152,10 +154,11 @@ class ServiceWorkerGlobalScopeProxy final
MessageLevel,
const String& message,
SourceLocation*) override;
- void PostMessageToPageInspector(int session_id, const String&) override;
void DidCreateWorkerGlobalScope(WorkerOrWorkletGlobalScope*) override;
void DidInitializeWorkerContext() override;
void DidLoadInstalledScript() override;
+ void DidFailToLoadInstalledClassicScript() override;
+ void DidFailToFetchModuleScript() override;
void WillEvaluateClassicScript(size_t script_size,
size_t cached_metadata_size) override;
void WillEvaluateImportedClassicScript(size_t script_size,
@@ -179,9 +182,6 @@ class ServiceWorkerGlobalScopeProxy final
void TerminateWorkerContext();
private:
- ServiceWorkerGlobalScopeProxy(WebEmbeddedWorkerImpl&,
- WebServiceWorkerContextClient&);
-
WebServiceWorkerContextClient& Client() const;
ServiceWorkerGlobalScope* WorkerGlobalScope() const;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager.cc
index b42870a6348..6f42d50bb47 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager.cc
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -96,11 +97,11 @@ class Receiver {
watcher_.ArmOrNotify();
}
- bool is_running() const { return handle_.is_valid(); }
- bool has_received_all_data() const { return remaining_bytes_ == 0; }
+ bool IsRunning() const { return handle_.is_valid(); }
+ bool HasReceivedAllData() const { return remaining_bytes_ == 0; }
Vector<BytesChunk> TakeChunks() {
- DCHECK(!is_running());
+ DCHECK(!IsRunning());
return std::move(chunks_);
}
@@ -108,7 +109,7 @@ class Receiver {
void OnCompleted() {
handle_.reset();
watcher_.Cancel();
- if (!has_received_all_data())
+ if (!HasReceivedAllData())
chunks_.clear();
DCHECK(callback_);
std::move(callback_).Run();
@@ -206,8 +207,8 @@ class Internal : public mojom::blink::ServiceWorkerInstalledScriptsManager {
DCHECK(iter != running_receivers_.end());
std::unique_ptr<BundledReceivers> receivers = std::move(iter->value);
DCHECK(receivers);
- if (!receivers->body()->has_received_all_data() ||
- !receivers->meta_data()->has_received_all_data()) {
+ if (!receivers->body()->HasReceivedAllData() ||
+ !receivers->meta_data()->HasReceivedAllData()) {
script_container_->AddOnIOThread(script_info->script_url,
nullptr /* data */);
running_receivers_.erase(iter);
@@ -289,9 +290,10 @@ ServiceWorkerInstalledScriptsManager::GetScriptData(const KURL& script_url) {
for (const auto& chunk : raw_script_data->MetaDataChunks())
total_metadata_size += chunk.size();
meta_data = std::make_unique<Vector<char>>();
- meta_data->ReserveInitialCapacity(total_metadata_size);
+ meta_data->ReserveInitialCapacity(
+ SafeCast<wtf_size_t>(total_metadata_size));
for (const auto& chunk : raw_script_data->MetaDataChunks())
- meta_data->Append(chunk.data(), chunk.size());
+ meta_data->Append(chunk.data(), static_cast<wtf_size_t>(chunk.size()));
}
return std::make_unique<InstalledScriptsManager::ScriptData>(
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager_test.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager_test.cc
index 2c41d7c7168..be7d9a05c9d 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager_test.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager_test.cc
@@ -10,9 +10,9 @@
#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.cc
new file mode 100644
index 00000000000..bc867582b85
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.cc
@@ -0,0 +1,56 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.h"
+
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/script/module_script.h"
+#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
+#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
+
+namespace blink {
+
+ServiceWorkerModuleTreeClient::ServiceWorkerModuleTreeClient(
+ Modulator* modulator)
+ : modulator_(modulator) {}
+
+// This client is used for both new and installed scripts. In the new scripts
+// case, this is a partial implementation of the custom "perfom the fetch" hook
+// in the spec: https://w3c.github.io/ServiceWorker/#update-algorithm For
+// installed scripts, there is no corresponding specification text because there
+// is no fetching process there. The service worker simply uses its associated
+// script resource.
+void ServiceWorkerModuleTreeClient::NotifyModuleTreeLoadFinished(
+ ModuleScript* module_script) {
+ auto* execution_context =
+ ExecutionContext::From(modulator_->GetScriptState());
+ auto* worker_global_scope = To<WorkerGlobalScope>(execution_context);
+ blink::WorkerReportingProxy& worker_reporting_proxy =
+ worker_global_scope->ReportingProxy();
+
+ if (!module_script) {
+ // (In the update case) Step 9: "If the algorithm asynchronously completes
+ // with null, then: Invoke Reject Job Promise with job and TypeError."
+ // DidFailToFetchModuleScript() signals that startup failed, which causes
+ // ServiceWorkerRegisterJob to reject the job promise.
+ worker_reporting_proxy.DidFailToFetchModuleScript();
+ worker_global_scope->close();
+ return;
+ }
+
+ // (In the update case) Step 9: "Else, continue the rest of these steps after
+ // the algorithm's asynchronous completion, with script being the asynchronous
+ // completion value."
+ worker_reporting_proxy.WillEvaluateModuleScript();
+ ScriptValue error = modulator_->ExecuteModule(
+ module_script, Modulator::CaptureEvalErrorFlag::kReport);
+ worker_reporting_proxy.DidEvaluateModuleScript(error.IsEmpty());
+}
+
+void ServiceWorkerModuleTreeClient::Trace(blink::Visitor* visitor) {
+ visitor->Trace(modulator_);
+ ModuleTreeClient::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.h
new file mode 100644
index 00000000000..e6cae49b147
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_module_tree_client.h
@@ -0,0 +1,33 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_MODULE_TREE_CLIENT_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_MODULE_TREE_CLIENT_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/script/modulator.h"
+#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
+
+namespace blink {
+
+class ModuleScript;
+
+// This is an implementation of ModuleTreeClient for service workers that lives
+// on the worker context's thread.
+class ServiceWorkerModuleTreeClient final : public ModuleTreeClient {
+ public:
+ explicit ServiceWorkerModuleTreeClient(Modulator*);
+
+ // Implements ModuleTreeClient.
+ void NotifyModuleTreeLoadFinished(ModuleScript*) final;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ Member<Modulator> modulator_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_MODULE_TREE_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc
index bb515811db5..dc278077fda 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.cc
@@ -8,69 +8,174 @@
#include <utility>
#include "base/memory/ptr_util.h"
-#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom-blink.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider.h"
-#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_container_client.h"
+#include "third_party/blink/renderer/modules/service_worker/navigation_preload_state.h"
+#include "third_party/blink/renderer/modules/service_worker/service_worker_container.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_error.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
-ServiceWorkerRegistration* ServiceWorkerRegistration::Take(
- ScriptPromiseResolver* resolver,
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) {
- return GetOrCreate(resolver->GetExecutionContext(), std::move(handle));
-}
+namespace {
-bool ServiceWorkerRegistration::HasPendingActivity() const {
- return !stopped_;
-}
+void DidUpdate(ScriptPromiseResolver* resolver,
+ ServiceWorkerRegistration* registration,
+ mojom::ServiceWorkerErrorType error,
+ const String& error_msg) {
+ if (!resolver->GetExecutionContext() ||
+ resolver->GetExecutionContext()->IsContextDestroyed()) {
+ return;
+ }
-const AtomicString& ServiceWorkerRegistration::InterfaceName() const {
- return EventTargetNames::ServiceWorkerRegistration;
+ if (error != mojom::ServiceWorkerErrorType::kNone) {
+ DCHECK(!error_msg.IsNull());
+ ScriptState::Scope scope(resolver->GetScriptState());
+ resolver->Reject(ServiceWorkerErrorForUpdate::Take(
+ resolver, WebServiceWorkerError(error, error_msg)));
+ return;
+ }
+ resolver->Resolve(registration);
}
-void ServiceWorkerRegistration::DispatchUpdateFoundEvent() {
- DispatchEvent(*Event::Create(EventTypeNames::updatefound));
+void DidUnregister(ScriptPromiseResolver* resolver,
+ mojom::ServiceWorkerErrorType error,
+ const String& error_msg) {
+ if (!resolver->GetExecutionContext() ||
+ resolver->GetExecutionContext()->IsContextDestroyed()) {
+ return;
+ }
+
+ if (error != mojom::ServiceWorkerErrorType::kNone &&
+ error != mojom::ServiceWorkerErrorType::kNotFound) {
+ DCHECK(!error_msg.IsNull());
+ resolver->Reject(
+ ServiceWorkerError::GetException(resolver, error, error_msg));
+ return;
+ }
+ resolver->Resolve(error == mojom::ServiceWorkerErrorType::kNone);
}
-void ServiceWorkerRegistration::SetInstalling(WebServiceWorkerObjectInfo info) {
- if (!GetExecutionContext())
+void DidEnableNavigationPreload(ScriptPromiseResolver* resolver,
+ mojom::ServiceWorkerErrorType error,
+ const String& error_msg) {
+ if (!resolver->GetExecutionContext() ||
+ resolver->GetExecutionContext()->IsContextDestroyed()) {
+ return;
+ }
+
+ if (error != mojom::ServiceWorkerErrorType::kNone) {
+ DCHECK(!error_msg.IsNull());
+ resolver->Reject(
+ ServiceWorkerError::GetException(resolver, error, error_msg));
return;
- installing_ = ServiceWorker::From(GetExecutionContext(), std::move(info));
+ }
+ resolver->Resolve();
}
-void ServiceWorkerRegistration::SetWaiting(WebServiceWorkerObjectInfo info) {
- if (!GetExecutionContext())
+void DidGetNavigationPreloadState(
+ ScriptPromiseResolver* resolver,
+ mojom::ServiceWorkerErrorType error,
+ const String& error_msg,
+ mojom::blink::NavigationPreloadStatePtr state) {
+ if (!resolver->GetExecutionContext() ||
+ resolver->GetExecutionContext()->IsContextDestroyed()) {
+ return;
+ }
+
+ if (error != mojom::ServiceWorkerErrorType::kNone) {
+ DCHECK(!error_msg.IsNull());
+ resolver->Reject(
+ ServiceWorkerError::GetException(resolver, error, error_msg));
return;
- waiting_ = ServiceWorker::From(GetExecutionContext(), std::move(info));
+ }
+ NavigationPreloadState* dict = NavigationPreloadState::Create();
+ dict->setEnabled(state->enabled);
+ dict->setHeaderValue(state->header);
+ resolver->Resolve(dict);
}
-void ServiceWorkerRegistration::SetActive(WebServiceWorkerObjectInfo info) {
- if (!GetExecutionContext())
+void DidSetNavigationPreloadHeader(ScriptPromiseResolver* resolver,
+ mojom::ServiceWorkerErrorType error,
+ const String& error_msg) {
+ if (!resolver->GetExecutionContext() ||
+ resolver->GetExecutionContext()->IsContextDestroyed()) {
return;
- active_ = ServiceWorker::From(GetExecutionContext(), std::move(info));
+ }
+
+ if (error != mojom::ServiceWorkerErrorType::kNone) {
+ DCHECK(!error_msg.IsNull());
+ resolver->Reject(
+ ServiceWorkerError::GetException(resolver, error, error_msg));
+ return;
+ }
+ resolver->Resolve();
}
-ServiceWorkerRegistration* ServiceWorkerRegistration::GetOrCreate(
+} // namespace
+
+ServiceWorkerRegistration* ServiceWorkerRegistration::Take(
+ ScriptPromiseResolver* resolver,
+ WebServiceWorkerRegistrationObjectInfo info) {
+ return ServiceWorkerContainer::From(
+ To<Document>(resolver->GetExecutionContext()))
+ ->GetOrCreateServiceWorkerRegistration(std::move(info));
+}
+
+ServiceWorkerRegistration::ServiceWorkerRegistration(
ExecutionContext* execution_context,
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) {
- DCHECK(handle);
+ WebServiceWorkerRegistrationObjectInfo info)
+ : ContextLifecycleObserver(execution_context),
+ registration_id_(info.registration_id),
+ scope_(std::move(info.scope)),
+ type_(info.type),
+ binding_(this),
+ stopped_(false) {
+ DCHECK_NE(mojom::blink::kInvalidServiceWorkerRegistrationId,
+ registration_id_);
+ Attach(std::move(info));
+}
+
+void ServiceWorkerRegistration::Attach(
+ WebServiceWorkerRegistrationObjectInfo info) {
+ DCHECK_EQ(registration_id_, info.registration_id);
+ DCHECK_EQ(scope_.GetString(), WTF::String(info.scope.GetString()));
+ DCHECK_EQ(type_, info.type);
- ServiceWorkerRegistration* existing_registration =
- static_cast<ServiceWorkerRegistration*>(handle->Registration()->Proxy());
- if (existing_registration) {
- DCHECK_EQ(existing_registration->GetExecutionContext(), execution_context);
- return existing_registration;
+ // If |host_| is bound, it already points to the same object host as
+ // |info.host_ptr_info|, so there is no need to bind again.
+ if (!host_) {
+ host_.Bind(
+ mojom::blink::ServiceWorkerRegistrationObjectHostAssociatedPtrInfo(
+ std::move(info.host_ptr_info),
+ mojom::blink::ServiceWorkerRegistrationObjectHost::Version_),
+ GetExecutionContext()->GetTaskRunner(
+ blink::TaskType::kInternalDefault));
}
+ // The host expects us to use |info.request| so bind to it.
+ binding_.Close();
+ binding_.Bind(
+ mojom::blink::ServiceWorkerRegistrationObjectAssociatedRequest(
+ std::move(info.request)),
+ GetExecutionContext()->GetTaskRunner(blink::TaskType::kInternalDefault));
+
+ update_via_cache_ = info.update_via_cache;
+ installing_ =
+ ServiceWorker::From(GetExecutionContext(), std::move(info.installing));
+ waiting_ =
+ ServiceWorker::From(GetExecutionContext(), std::move(info.waiting));
+ active_ = ServiceWorker::From(GetExecutionContext(), std::move(info.active));
+}
- return new ServiceWorkerRegistration(execution_context, std::move(handle));
+bool ServiceWorkerRegistration::HasPendingActivity() const {
+ return !stopped_;
+}
+
+const AtomicString& ServiceWorkerRegistration::InterfaceName() const {
+ return event_target_names::kServiceWorkerRegistration;
}
NavigationPreloadManager* ServiceWorkerRegistration::navigationPreload() {
@@ -80,11 +185,11 @@ NavigationPreloadManager* ServiceWorkerRegistration::navigationPreload() {
}
String ServiceWorkerRegistration::scope() const {
- return handle_->Registration()->Scope().GetString();
+ return scope_.GetString();
}
String ServiceWorkerRegistration::updateViaCache() const {
- switch (handle_->Registration()->UpdateViaCache()) {
+ switch (update_via_cache_) {
case mojom::ServiceWorkerUpdateViaCache::kImports:
return "imports";
case mojom::ServiceWorkerUpdateViaCache::kAll:
@@ -96,6 +201,27 @@ String ServiceWorkerRegistration::updateViaCache() const {
return "";
}
+void ServiceWorkerRegistration::EnableNavigationPreload(
+ bool enable,
+ ScriptPromiseResolver* resolver) {
+ host_->EnableNavigationPreload(
+ enable, WTF::Bind(&DidEnableNavigationPreload, WrapPersistent(resolver)));
+}
+
+void ServiceWorkerRegistration::GetNavigationPreloadState(
+ ScriptPromiseResolver* resolver) {
+ host_->GetNavigationPreloadState(
+ WTF::Bind(&DidGetNavigationPreloadState, WrapPersistent(resolver)));
+}
+
+void ServiceWorkerRegistration::SetNavigationPreloadHeader(
+ const String& value,
+ ScriptPromiseResolver* resolver) {
+ host_->SetNavigationPreloadHeader(
+ value,
+ WTF::Bind(&DidSetNavigationPreloadHeader, WrapPersistent(resolver)));
+}
+
ScriptPromise ServiceWorkerRegistration::update(ScriptState* script_state) {
if (!GetExecutionContext()) {
return ScriptPromise::RejectWithDOMException(
@@ -105,12 +231,9 @@ ScriptPromise ServiceWorkerRegistration::update(ScriptState* script_state) {
"associated provider is available."));
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
- ScriptPromise promise = resolver->Promise();
- handle_->Registration()->Update(
- std::make_unique<CallbackPromiseAdapter<ServiceWorkerRegistration,
- ServiceWorkerErrorForUpdate>>(
- resolver));
- return promise;
+ host_->Update(
+ WTF::Bind(&DidUpdate, WrapPersistent(resolver), WrapPersistent(this)));
+ return resolver->Promise();
}
ScriptPromise ServiceWorkerRegistration::unregister(ScriptState* script_state) {
@@ -123,35 +246,12 @@ ScriptPromise ServiceWorkerRegistration::unregister(ScriptState* script_state) {
"associated provider is available."));
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
- ScriptPromise promise = resolver->Promise();
- handle_->Registration()->Unregister(
- std::make_unique<CallbackPromiseAdapter<bool, ServiceWorkerError>>(
- resolver));
- return promise;
-}
-
-ServiceWorkerRegistration::ServiceWorkerRegistration(
- ExecutionContext* execution_context,
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle)
- : ContextLifecycleObserver(execution_context),
- handle_(std::move(handle)),
- stopped_(false) {
- DCHECK(handle_);
- DCHECK(!handle_->Registration()->Proxy());
-
- if (!execution_context)
- return;
- handle_->Registration()->SetProxy(this);
+ host_->Unregister(WTF::Bind(&DidUnregister, WrapPersistent(resolver)));
+ return resolver->Promise();
}
ServiceWorkerRegistration::~ServiceWorkerRegistration() = default;
-void ServiceWorkerRegistration::Dispose() {
- // Promptly clears a raw reference from content/ to an on-heap object
- // so that content/ doesn't access it in a lazy sweeping phase.
- handle_.reset();
-}
-
void ServiceWorkerRegistration::Trace(blink::Visitor* visitor) {
visitor->Trace(installing_);
visitor->Trace(waiting_);
@@ -166,7 +266,38 @@ void ServiceWorkerRegistration::ContextDestroyed(ExecutionContext*) {
if (stopped_)
return;
stopped_ = true;
- handle_->Registration()->ProxyStopped();
+}
+
+void ServiceWorkerRegistration::SetServiceWorkerObjects(
+ mojom::blink::ChangedServiceWorkerObjectsMaskPtr changed_mask,
+ mojom::blink::ServiceWorkerObjectInfoPtr installing,
+ mojom::blink::ServiceWorkerObjectInfoPtr waiting,
+ mojom::blink::ServiceWorkerObjectInfoPtr active) {
+ if (!GetExecutionContext())
+ return;
+
+ DCHECK(changed_mask->installing || !installing);
+ if (changed_mask->installing) {
+ installing_ =
+ ServiceWorker::From(GetExecutionContext(), std::move(installing));
+ }
+ DCHECK(changed_mask->waiting || !waiting);
+ if (changed_mask->waiting) {
+ waiting_ = ServiceWorker::From(GetExecutionContext(), std::move(waiting));
+ }
+ DCHECK(changed_mask->active || !active);
+ if (changed_mask->active) {
+ active_ = ServiceWorker::From(GetExecutionContext(), std::move(active));
+ }
+}
+
+void ServiceWorkerRegistration::SetUpdateViaCache(
+ mojom::blink::ServiceWorkerUpdateViaCache update_via_cache) {
+ update_via_cache_ = update_via_cache;
+}
+
+void ServiceWorkerRegistration::UpdateFound() {
+ DispatchEvent(*Event::Create(event_type_names::kUpdatefound));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.h
index 70d5bbfed0a..9884fb02968 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_registration.h
@@ -6,8 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_MODULES_SERVICE_WORKER_SERVICE_WORKER_REGISTRATION_H_
#include <memory>
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration.h"
-#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration_proxy.h"
+#include "mojo/public/cpp/bindings/associated_binding.h"
+#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_registration_object_info.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
@@ -15,7 +16,6 @@
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/modules/service_worker/navigation_preload_manager.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
@@ -24,25 +24,38 @@ namespace blink {
class ScriptPromise;
class ScriptState;
-// The implementation of a service worker registration object in Blink. Actual
-// registration representation is in the embedder and this class accesses it
-// via WebServiceWorkerRegistration::Handle object.
+// The implementation of a service worker registration object in Blink.
class ServiceWorkerRegistration final
: public EventTargetWithInlineData,
public ActiveScriptWrappable<ServiceWorkerRegistration>,
public ContextLifecycleObserver,
- public WebServiceWorkerRegistrationProxy,
- public Supplementable<ServiceWorkerRegistration> {
+ public Supplementable<ServiceWorkerRegistration>,
+ public mojom::blink::ServiceWorkerRegistrationObject {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(ServiceWorkerRegistration);
- USING_PRE_FINALIZER(ServiceWorkerRegistration, Dispose);
public:
// Called from CallbackPromiseAdapter.
- using WebType = std::unique_ptr<WebServiceWorkerRegistration::Handle>;
+ using WebType = WebServiceWorkerRegistrationObjectInfo;
static ServiceWorkerRegistration* Take(
ScriptPromiseResolver*,
- std::unique_ptr<WebServiceWorkerRegistration::Handle>);
+ WebServiceWorkerRegistrationObjectInfo);
+
+ ServiceWorkerRegistration(ExecutionContext*,
+ WebServiceWorkerRegistrationObjectInfo);
+
+ // Eager finalization needed to promptly invalidate the corresponding entry of
+ // the (registration id, WeakMember<ServiceWorkerRegistration>) map inside
+ // ServiceWorkerContainer.
+ EAGERLY_FINALIZE();
+
+ // Called in 2 scenarios:
+ // - when constructing |this|.
+ // - when the browser process sends a new
+ // WebServiceWorkerRegistrationObjectInfo and |this| already exists for the
+ // described ServiceWorkerRegistration, the new info may contain some
+ // information to be updated, e.g. {installing,waiting,active} objects.
+ void Attach(WebServiceWorkerRegistrationObjectInfo);
// ScriptWrappable overrides.
bool HasPendingActivity() const final;
@@ -53,18 +66,6 @@ class ServiceWorkerRegistration final
return ContextLifecycleObserver::GetExecutionContext();
}
- // WebServiceWorkerRegistrationProxy overrides.
- void DispatchUpdateFoundEvent() override;
- void SetInstalling(WebServiceWorkerObjectInfo) override;
- void SetWaiting(WebServiceWorkerObjectInfo) override;
- void SetActive(WebServiceWorkerObjectInfo) override;
-
- // Returns an existing registration object for the handle if it exists.
- // Otherwise, returns a new registration object.
- static ServiceWorkerRegistration* GetOrCreate(
- ExecutionContext*,
- std::unique_ptr<WebServiceWorkerRegistration::Handle>);
-
ServiceWorker* installing() { return installing_; }
ServiceWorker* waiting() { return waiting_; }
ServiceWorker* active() { return active_; }
@@ -73,36 +74,64 @@ class ServiceWorkerRegistration final
String scope() const;
String updateViaCache() const;
- WebServiceWorkerRegistration* WebRegistration() {
- return handle_->Registration();
- }
+ int64_t RegistrationId() const { return registration_id_; }
+
+ void EnableNavigationPreload(bool enable, ScriptPromiseResolver* resolver);
+ void GetNavigationPreloadState(ScriptPromiseResolver* resolver);
+ void SetNavigationPreloadHeader(const String& value,
+ ScriptPromiseResolver* resolver);
ScriptPromise update(ScriptState*);
ScriptPromise unregister(ScriptState*);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(updatefound);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(updatefound, kUpdatefound);
~ServiceWorkerRegistration() override;
void Trace(blink::Visitor*) override;
private:
- ServiceWorkerRegistration(
- ExecutionContext*,
- std::unique_ptr<WebServiceWorkerRegistration::Handle>);
- void Dispose();
-
// ContextLifecycleObserver overrides.
void ContextDestroyed(ExecutionContext*) override;
- // A handle to the registration representation in the embedder.
- std::unique_ptr<WebServiceWorkerRegistration::Handle> handle_;
+ // Implements mojom::blink::ServiceWorkerRegistrationObject.
+ void SetServiceWorkerObjects(
+ mojom::blink::ChangedServiceWorkerObjectsMaskPtr changed_mask,
+ mojom::blink::ServiceWorkerObjectInfoPtr installing,
+ mojom::blink::ServiceWorkerObjectInfoPtr waiting,
+ mojom::blink::ServiceWorkerObjectInfoPtr active) override;
+ void SetUpdateViaCache(
+ mojom::blink::ServiceWorkerUpdateViaCache update_via_cache) override;
+ void UpdateFound() override;
Member<ServiceWorker> installing_;
Member<ServiceWorker> waiting_;
Member<ServiceWorker> active_;
Member<NavigationPreloadManager> navigation_preload_;
+ const int64_t registration_id_;
+ const KURL scope_;
+ const mojom::ScriptType type_;
+ mojom::ServiceWorkerUpdateViaCache update_via_cache_;
+ // Both |host_| and |binding_| are associated with
+ // content.mojom.ServiceWorkerContainer interface for a Document, and
+ // content.mojom.ServiceWorker interface for a ServiceWorkerGlobalScope.
+ //
+ // |host_| keeps the Mojo connection to the
+ // browser-side ServiceWorkerRegistrationObjectHost, whose lifetime is bound
+ // to the Mojo connection. It is bound on the
+ // main thread for service worker clients (document), and is bound on the
+ // service worker thread for service worker execution contexts.
+ mojom::blink::ServiceWorkerRegistrationObjectHostAssociatedPtr host_;
+ // |binding_| keeps the Mojo binding to serve its other Mojo endpoint (i.e.
+ // the caller end) held by the ServiceWorkerRegistrationObjectHost in
+ // the browser process.
+ // It is bound on the main thread for service worker clients (document), and
+ // is bound on the service worker thread for service worker execution
+ // contexts.
+ mojo::AssociatedBinding<mojom::blink::ServiceWorkerRegistrationObject>
+ binding_;
+
bool stopped_;
};
@@ -111,13 +140,12 @@ class ServiceWorkerRegistrationArray {
public:
// Called from CallbackPromiseAdapter.
- using WebType = std::unique_ptr<
- WebVector<std::unique_ptr<WebServiceWorkerRegistration::Handle>>>;
+ using WebType = WebVector<WebServiceWorkerRegistrationObjectInfo>;
static HeapVector<Member<ServiceWorkerRegistration>> Take(
ScriptPromiseResolver* resolver,
WebType web_service_worker_registrations) {
HeapVector<Member<ServiceWorkerRegistration>> registrations;
- for (auto& registration : *web_service_worker_registrations) {
+ for (auto& registration : web_service_worker_registrations) {
registrations.push_back(
ServiceWorkerRegistration::Take(resolver, std::move(registration)));
}
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_script_cached_metadata_handler.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_script_cached_metadata_handler.h
index cea3dafcad6..cd9325eed6e 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_script_cached_metadata_handler.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_script_cached_metadata_handler.h
@@ -23,9 +23,13 @@ class ServiceWorkerScriptCachedMetadataHandler
WorkerGlobalScope* worker_global_scope,
const KURL& script_url,
const Vector<char>* meta_data) {
- return new ServiceWorkerScriptCachedMetadataHandler(worker_global_scope,
- script_url, meta_data);
+ return MakeGarbageCollected<ServiceWorkerScriptCachedMetadataHandler>(
+ worker_global_scope, script_url, meta_data);
}
+
+ ServiceWorkerScriptCachedMetadataHandler(WorkerGlobalScope*,
+ const KURL& script_url,
+ const Vector<char>* meta_data);
~ServiceWorkerScriptCachedMetadataHandler() override;
void Trace(blink::Visitor*) override;
void SetCachedMetadata(uint32_t data_type_id,
@@ -39,10 +43,6 @@ class ServiceWorkerScriptCachedMetadataHandler
bool IsServedFromCacheStorage() const override;
private:
- ServiceWorkerScriptCachedMetadataHandler(WorkerGlobalScope*,
- const KURL& script_url,
- const Vector<char>* meta_data);
-
Member<WorkerGlobalScope> worker_global_scope_;
KURL script_url_;
scoped_refptr<CachedMetadata> cached_metadata_;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.cc b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.cc
index 6e9f32087dd..07c3edf4f25 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.cc
@@ -43,13 +43,13 @@ void DidFocus(ScriptPromiseResolver* resolver,
ServiceWorkerWindowClient* ServiceWorkerWindowClient::Create(
const WebServiceWorkerClientInfo& info) {
DCHECK_EQ(mojom::blink::ServiceWorkerClientType::kWindow, info.client_type);
- return new ServiceWorkerWindowClient(info);
+ return MakeGarbageCollected<ServiceWorkerWindowClient>(info);
}
ServiceWorkerWindowClient* ServiceWorkerWindowClient::Create(
const mojom::blink::ServiceWorkerClientInfo& info) {
DCHECK_EQ(mojom::blink::ServiceWorkerClientType::kWindow, info.client_type);
- return new ServiceWorkerWindowClient(info);
+ return MakeGarbageCollected<ServiceWorkerWindowClient>(info);
}
ServiceWorkerWindowClient::ServiceWorkerWindowClient(
@@ -92,7 +92,8 @@ ScriptPromise ServiceWorkerWindowClient::navigate(ScriptState* script_state,
ScriptPromise promise = resolver->Promise();
ExecutionContext* context = ExecutionContext::From(script_state);
- KURL parsed_url = KURL(ToWorkerGlobalScope(context)->location()->Url(), url);
+ KURL parsed_url =
+ KURL(To<WorkerGlobalScope>(context)->location()->Url(), url);
if (!parsed_url.IsValid() || parsed_url.ProtocolIsAbout()) {
resolver->Reject(V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "'" + url + "' is not a valid URL."));
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.h b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.h
index 863d318f4b2..59988a85e20 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/service_worker_window_client.h
@@ -24,6 +24,10 @@ class MODULES_EXPORT ServiceWorkerWindowClient final
static ServiceWorkerWindowClient* Create(const WebServiceWorkerClientInfo&);
static ServiceWorkerWindowClient* Create(
const mojom::blink::ServiceWorkerClientInfo&);
+
+ explicit ServiceWorkerWindowClient(const WebServiceWorkerClientInfo&);
+ explicit ServiceWorkerWindowClient(
+ const mojom::blink::ServiceWorkerClientInfo&);
~ServiceWorkerWindowClient() override;
// WindowClient.idl
@@ -35,10 +39,6 @@ class MODULES_EXPORT ServiceWorkerWindowClient final
void Trace(blink::Visitor*) override;
private:
- explicit ServiceWorkerWindowClient(const WebServiceWorkerClientInfo&);
- explicit ServiceWorkerWindowClient(
- const mojom::blink::ServiceWorkerClientInfo&);
-
mojom::PageVisibilityState page_visibility_state_;
bool is_focused_;
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc b/chromium/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc
index b04d2a84135..50a8368fc0e 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/thread_safe_script_container_test.cc
@@ -9,9 +9,9 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.cc b/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.cc
index ceb65d2efd8..20b174044d9 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.cc
@@ -13,8 +13,8 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "v8/include/v8.h"
@@ -28,7 +28,7 @@ const unsigned kWindowInteractionTimeout = 10;
const unsigned kWindowInteractionTimeoutForTest = 1;
TimeDelta WindowInteractionTimeout() {
- return TimeDelta::FromSeconds(LayoutTestSupport::IsRunningLayoutTest()
+ return TimeDelta::FromSeconds(WebTestSupport::IsRunningWebTest()
? kWindowInteractionTimeoutForTest
: kWindowInteractionTimeout);
}
@@ -47,17 +47,11 @@ class WaitUntilObserver::ThenFunction final : public ScriptFunction {
WaitUntilObserver* observer,
ResolveType type,
PromiseSettledCallback callback) {
- ThenFunction* self =
- new ThenFunction(script_state, observer, type, std::move(callback));
+ ThenFunction* self = MakeGarbageCollected<ThenFunction>(
+ script_state, observer, type, std::move(callback));
return self->BindToV8Function();
}
- void Trace(blink::Visitor* visitor) override {
- visitor->Trace(observer_);
- ScriptFunction::Trace(visitor);
- }
-
- private:
ThenFunction(ScriptState* script_state,
WaitUntilObserver* observer,
ResolveType type,
@@ -67,6 +61,12 @@ class WaitUntilObserver::ThenFunction final : public ScriptFunction {
resolve_type_(type),
callback_(std::move(callback)) {}
+ void Trace(blink::Visitor* visitor) override {
+ visitor->Trace(observer_);
+ ScriptFunction::Trace(visitor);
+ }
+
+ private:
ScriptValue Call(ScriptValue value) override {
DCHECK(observer_);
DCHECK(resolve_type_ == kFulfilled || resolve_type_ == kRejected);
@@ -107,11 +107,10 @@ class WaitUntilObserver::ThenFunction final : public ScriptFunction {
WaitUntilObserver* WaitUntilObserver::Create(ExecutionContext* context,
EventType type,
int event_id) {
- return new WaitUntilObserver(context, type, event_id);
+ return MakeGarbageCollected<WaitUntilObserver>(context, type, event_id);
}
void WaitUntilObserver::WillDispatchEvent() {
- event_dispatch_time_ = WTF::CurrentTimeTicks();
// When handling a notificationclick, paymentrequest, or backgroundfetchclick
// event, we want to allow one window to be focused or opened. These calls are
// allowed between the call to willDispatchEvent() and the last call to
@@ -138,34 +137,14 @@ void WaitUntilObserver::WaitUntil(ScriptState* script_state,
ExceptionState& exception_state,
PromiseSettledCallback on_promise_fulfilled,
PromiseSettledCallback on_promise_rejected) {
- if (pending_promises_ == 0) {
- switch (event_dispatch_state_) {
- case EventDispatchState::kInitial:
- NOTREACHED();
- return;
- case EventDispatchState::kDispatching:
- if (!v8::MicrotasksScope::IsRunningMicrotasks(
- script_state->GetIsolate())) {
- break;
- }
- // didDispatchEvent() is called after both the event handler
- // execution finished and microtasks queued by the event handler execution
- // finished, it's hard to get the precise time point between the 2
- // execution phases.
- // So even in EventDispatchState::kDispatching state at this time point,
- // running microtask indicates that event handler execution has actually
- // finished, in such case if there aren't any outstanding extend lifetime
- // promises, we should throw here.
- FALLTHROUGH;
- case EventDispatchState::kDispatched:
- case EventDispatchState::kFailed:
- exception_state.ThrowDOMException(
- DOMExceptionCode::kInvalidStateError,
- "The event handler is already finished "
- "and no extend lifetime promises are "
- "outstanding.");
- return;
- }
+ DCHECK_NE(event_dispatch_state_, EventDispatchState::kInitial);
+
+ if (!IsEventActive(script_state)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidStateError,
+ "The event handler is already finished and no extend lifetime "
+ "promises are outstanding.");
+ return;
}
if (!execution_context_)
@@ -195,6 +174,30 @@ void WaitUntilObserver::WaitUntil(ScriptState* script_state,
std::move(on_promise_rejected)));
}
+bool WaitUntilObserver::IsEventActive(ScriptState* script_state) const {
+ if (pending_promises_ > 0)
+ return true;
+
+ switch (event_dispatch_state_) {
+ case EventDispatchState::kDispatching:
+ // DidDispatchEvent() is called after both the event handler
+ // execution finished and microtasks queued by the event handler execution
+ // finished, it's hard to get the precise time point between the 2
+ // execution phases.
+ // So even in EventDispatchState::kDispatching state at this time point,
+ // running microtask indicates that event handler execution has actually
+ // finished, in such case if there aren't any outstanding extend lifetime
+ // promises.
+ return !v8::MicrotasksScope::IsRunningMicrotasks(
+ script_state->GetIsolate());
+ case EventDispatchState::kInitial:
+ case EventDispatchState::kDispatched:
+ case EventDispatchState::kFailed:
+ return false;
+ }
+ NOTREACHED();
+}
+
WaitUntilObserver::WaitUntilObserver(ExecutionContext* context,
EventType type,
int event_id)
@@ -202,7 +205,7 @@ WaitUntilObserver::WaitUntilObserver(ExecutionContext* context,
type_(type),
event_id_(event_id),
consume_window_interaction_timer_(
- Platform::Current()->CurrentThread()->GetTaskRunner(),
+ Thread::Current()->GetTaskRunner(),
this,
&WaitUntilObserver::ConsumeWindowInteraction) {}
@@ -244,7 +247,7 @@ void WaitUntilObserver::MaybeCompleteEvent() {
// event.
break;
case EventDispatchState::kFailed:
- // Dispatch had some error, complete the event immediatelly.
+ // Dispatch had some error, complete the event immediately.
break;
}
@@ -257,66 +260,55 @@ void WaitUntilObserver::MaybeCompleteEvent() {
: mojom::ServiceWorkerEventStatus::COMPLETED;
switch (type_) {
case kAbortPayment:
- client->DidHandleAbortPaymentEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleAbortPaymentEvent(event_id_, status);
break;
case kActivate:
- client->DidHandleActivateEvent(event_id_, status, event_dispatch_time_);
+ client->DidHandleActivateEvent(event_id_, status);
break;
case kCanMakePayment:
- client->DidHandleCanMakePaymentEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleCanMakePaymentEvent(event_id_, status);
break;
case kCookieChange:
- client->DidHandleCookieChangeEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleCookieChangeEvent(event_id_, status);
break;
case kFetch:
- client->DidHandleFetchEvent(event_id_, status, event_dispatch_time_);
+ client->DidHandleFetchEvent(event_id_, status);
break;
case kInstall:
- ToServiceWorkerGlobalScope(execution_context_)->SetIsInstalling(false);
- client->DidHandleInstallEvent(event_id_, status, event_dispatch_time_);
+ To<ServiceWorkerGlobalScope>(*execution_context_).SetIsInstalling(false);
+ client->DidHandleInstallEvent(event_id_, status);
break;
case kMessage:
- client->DidHandleExtendableMessageEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleExtendableMessageEvent(event_id_, status);
break;
case kNotificationClick:
- client->DidHandleNotificationClickEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleNotificationClickEvent(event_id_, status);
consume_window_interaction_timer_.Stop();
ConsumeWindowInteraction(nullptr);
break;
case kNotificationClose:
- client->DidHandleNotificationCloseEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleNotificationCloseEvent(event_id_, status);
break;
case kPush:
- client->DidHandlePushEvent(event_id_, status, event_dispatch_time_);
+ client->DidHandlePushEvent(event_id_, status);
break;
case kSync:
- client->DidHandleSyncEvent(event_id_, status, event_dispatch_time_);
+ client->DidHandleSyncEvent(event_id_, status);
break;
case kPaymentRequest:
- client->DidHandlePaymentRequestEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandlePaymentRequestEvent(event_id_, status);
break;
case kBackgroundFetchAbort:
- client->DidHandleBackgroundFetchAbortEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleBackgroundFetchAbortEvent(event_id_, status);
break;
case kBackgroundFetchClick:
- client->DidHandleBackgroundFetchClickEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleBackgroundFetchClickEvent(event_id_, status);
break;
case kBackgroundFetchFail:
- client->DidHandleBackgroundFetchFailEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleBackgroundFetchFailEvent(event_id_, status);
break;
case kBackgroundFetchSuccess:
- client->DidHandleBackgroundFetchSuccessEvent(event_id_, status,
- event_dispatch_time_);
+ client->DidHandleBackgroundFetchSuccessEvent(event_id_, status);
break;
}
execution_context_ = nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.h b/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.h
index fa322d6e0c2..2f025fc8070 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.h
+++ b/chromium/third_party/blink/renderer/modules/service_worker/wait_until_observer.h
@@ -47,6 +47,8 @@ class MODULES_EXPORT WaitUntilObserver final
static WaitUntilObserver* Create(ExecutionContext*, EventType, int event_id);
+ WaitUntilObserver(ExecutionContext*, EventType, int event_id);
+
// Must be called before dispatching the event.
void WillDispatchEvent();
// Must be called after dispatching the event. If |event_dispatch_failed| is
@@ -69,6 +71,10 @@ class MODULES_EXPORT WaitUntilObserver final
PromiseSettledCallback on_promise_fulfilled = PromiseSettledCallback(),
PromiseSettledCallback on_promise_rejected = PromiseSettledCallback());
+ // Whether the associated event is active.
+ // https://w3c.github.io/ServiceWorker/#extendableevent-active.
+ bool IsEventActive(ScriptState* script_state) const;
+
virtual void Trace(blink::Visitor*);
private:
@@ -88,8 +94,6 @@ class MODULES_EXPORT WaitUntilObserver final
kFailed
};
- WaitUntilObserver(ExecutionContext*, EventType, int event_id);
-
void IncrementPendingPromiseCount();
void DecrementPendingPromiseCount();
@@ -110,7 +114,6 @@ class MODULES_EXPORT WaitUntilObserver final
int pending_promises_ = 0;
EventDispatchState event_dispatch_state_ = EventDispatchState::kInitial;
bool has_rejected_promise_ = false;
- TimeTicks event_dispatch_time_;
TaskRunnerTimer<WaitUntilObserver> consume_window_interaction_timer_;
};
diff --git a/chromium/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc b/chromium/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
index c8dbc3143e4..17abf021c46 100644
--- a/chromium/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
+++ b/chromium/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
@@ -102,7 +102,8 @@ class WebEmbeddedWorkerImplTest : public testing::Test {
worker_ = WebEmbeddedWorkerImpl::CreateForTesting(
std::move(client), std::move(installed_scripts_manager));
- WebURL script_url = URLTestHelpers::ToKURL("https://www.example.com/sw.js");
+ WebURL script_url =
+ url_test_helpers::ToKURL("https://www.example.com/sw.js");
WebURLResponse response(script_url);
response.SetMIMEType("text/javascript");
response.SetHTTPStatusCode(200);
@@ -116,7 +117,7 @@ class WebEmbeddedWorkerImplTest : public testing::Test {
WebEmbeddedWorkerStartData::kDontPauseAfterDownload;
start_data_.wait_for_debugger_mode =
WebEmbeddedWorkerStartData::kDontWaitForDebugger;
- start_data_.v8_cache_options = WebSettings::kV8CacheOptionsDefault;
+ start_data_.v8_cache_options = WebSettings::V8CacheOptions::kDefault;
}
void TearDown() override {
@@ -209,7 +210,7 @@ TEST_F(WebEmbeddedWorkerImplTest, TerminateWhilePausedAfterDownload) {
TEST_F(WebEmbeddedWorkerImplTest, ScriptNotFound) {
WebURL script_url =
- URLTestHelpers::ToKURL("https://www.example.com/sw-404.js");
+ url_test_helpers::ToKURL("https://www.example.com/sw-404.js");
WebURLResponse response;
response.SetMIMEType("text/javascript");
response.SetHTTPStatusCode(404);
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/barcode_detector.cc b/chromium/third_party/blink/renderer/modules/shapedetection/barcode_detector.cc
index 2ee1c2eccca..66a43d4ff58 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/barcode_detector.cc
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/barcode_detector.cc
@@ -61,11 +61,11 @@ void BarcodeDetector::OnDetectBarcodes(
HeapVector<Member<DetectedBarcode>> detected_barcodes;
for (const auto& barcode : barcode_detection_results) {
- HeapVector<Point2D> corner_points;
+ HeapVector<Member<Point2D>> corner_points;
for (const auto& corner_point : barcode->corner_points) {
- Point2D point;
- point.setX(corner_point.x);
- point.setY(corner_point.y);
+ Point2D* point = Point2D::Create();
+ point->setX(corner_point.x);
+ point->setY(corner_point.y);
corner_points.push_back(point);
}
detected_barcodes.push_back(DetectedBarcode::Create(
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.cc b/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.cc
index 09cafa69fe5..4815379be2b 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.cc
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.cc
@@ -10,15 +10,17 @@
namespace blink {
DetectedBarcode* DetectedBarcode::Create() {
- HeapVector<Point2D> empty_list;
- return new DetectedBarcode(g_empty_string,
- DOMRectReadOnly::Create(0, 0, 0, 0), empty_list);
+ HeapVector<Member<Point2D>> empty_list;
+ return MakeGarbageCollected<DetectedBarcode>(
+ g_empty_string, DOMRectReadOnly::Create(0, 0, 0, 0), empty_list);
}
-DetectedBarcode* DetectedBarcode::Create(String raw_value,
- DOMRectReadOnly* bounding_box,
- HeapVector<Point2D> corner_points) {
- return new DetectedBarcode(raw_value, bounding_box, corner_points);
+DetectedBarcode* DetectedBarcode::Create(
+ String raw_value,
+ DOMRectReadOnly* bounding_box,
+ HeapVector<Member<Point2D>> corner_points) {
+ return MakeGarbageCollected<DetectedBarcode>(raw_value, bounding_box,
+ corner_points);
}
const String& DetectedBarcode::rawValue() const {
@@ -29,13 +31,13 @@ DOMRectReadOnly* DetectedBarcode::boundingBox() const {
return bounding_box_.Get();
}
-const HeapVector<Point2D>& DetectedBarcode::cornerPoints() const {
+const HeapVector<Member<Point2D>>& DetectedBarcode::cornerPoints() const {
return corner_points_;
}
DetectedBarcode::DetectedBarcode(String raw_value,
DOMRectReadOnly* bounding_box,
- HeapVector<Point2D> corner_points)
+ HeapVector<Member<Point2D>> corner_points)
: raw_value_(raw_value),
bounding_box_(bounding_box),
corner_points_(corner_points) {}
@@ -47,8 +49,8 @@ ScriptValue DetectedBarcode::toJSONForBinding(ScriptState* script_state) const {
Vector<ScriptValue> corner_points;
for (const auto& corner_point : corner_points_) {
V8ObjectBuilder builder(script_state);
- builder.AddNumber("x", corner_point.x());
- builder.AddNumber("y", corner_point.y());
+ builder.AddNumber("x", corner_point->x());
+ builder.AddNumber("y", corner_point->y());
corner_points.push_back(builder.GetScriptValue());
}
result.Add("cornerPoints", corner_points);
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.h b/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.h
index c6f2fe11c65..201a6d1a276 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.h
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/detected_barcode.h
@@ -20,21 +20,23 @@ class MODULES_EXPORT DetectedBarcode final : public ScriptWrappable {
public:
static DetectedBarcode* Create();
- static DetectedBarcode* Create(String, DOMRectReadOnly*, HeapVector<Point2D>);
+ static DetectedBarcode* Create(String,
+ DOMRectReadOnly*,
+ HeapVector<Member<Point2D>>);
+
+ DetectedBarcode(String, DOMRectReadOnly*, HeapVector<Member<Point2D>>);
const String& rawValue() const;
DOMRectReadOnly* boundingBox() const;
- const HeapVector<Point2D>& cornerPoints() const;
+ const HeapVector<Member<Point2D>>& cornerPoints() const;
ScriptValue toJSONForBinding(ScriptState*) const;
void Trace(blink::Visitor*) override;
private:
- DetectedBarcode(String, DOMRectReadOnly*, HeapVector<Point2D>);
-
const String raw_value_;
const Member<DOMRectReadOnly> bounding_box_;
- const HeapVector<Point2D> corner_points_;
+ const HeapVector<Member<Point2D>> corner_points_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.cc b/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.cc
index 8228b01bf5a..beb88c65834 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.cc
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.cc
@@ -10,23 +10,25 @@
namespace blink {
DetectedFace* DetectedFace::Create() {
- return new DetectedFace(DOMRectReadOnly::Create(0, 0, 0, 0));
+ return MakeGarbageCollected<DetectedFace>(
+ DOMRectReadOnly::Create(0, 0, 0, 0));
}
DetectedFace* DetectedFace::Create(DOMRectReadOnly* bounding_box) {
- return new DetectedFace(bounding_box);
+ return MakeGarbageCollected<DetectedFace>(bounding_box);
}
-DetectedFace* DetectedFace::Create(DOMRectReadOnly* bounding_box,
- const HeapVector<Landmark>& landmarks) {
- return new DetectedFace(bounding_box, landmarks);
+DetectedFace* DetectedFace::Create(
+ DOMRectReadOnly* bounding_box,
+ const HeapVector<Member<Landmark>>& landmarks) {
+ return MakeGarbageCollected<DetectedFace>(bounding_box, landmarks);
}
DOMRectReadOnly* DetectedFace::boundingBox() const {
return bounding_box_.Get();
}
-const HeapVector<Landmark>& DetectedFace::landmarks() const {
+const HeapVector<Member<Landmark>>& DetectedFace::landmarks() const {
return landmarks_;
}
@@ -34,7 +36,7 @@ DetectedFace::DetectedFace(DOMRectReadOnly* bounding_box)
: bounding_box_(bounding_box) {}
DetectedFace::DetectedFace(DOMRectReadOnly* bounding_box,
- const HeapVector<Landmark>& landmarks)
+ const HeapVector<Member<Landmark>>& landmarks)
: bounding_box_(bounding_box), landmarks_(landmarks) {}
ScriptValue DetectedFace::toJSONForBinding(ScriptState* script_state) const {
@@ -43,12 +45,12 @@ ScriptValue DetectedFace::toJSONForBinding(ScriptState* script_state) const {
Vector<ScriptValue> landmarks;
for (const auto& landmark : landmarks_) {
V8ObjectBuilder landmark_builder(script_state);
- landmark_builder.AddString("type", landmark.type());
+ landmark_builder.AddString("type", landmark->type());
Vector<ScriptValue> locations;
- for (const auto& location : landmark.locations()) {
+ for (const auto& location : landmark->locations()) {
V8ObjectBuilder location_builder(script_state);
- location_builder.AddNumber("x", location.x());
- location_builder.AddNumber("y", location.y());
+ location_builder.AddNumber("x", location->x());
+ location_builder.AddNumber("y", location->y());
locations.push_back(location_builder.GetScriptValue());
}
landmark_builder.Add("locations", locations);
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.h b/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.h
index 6935e84330d..40be303f637 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.h
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/detected_face.h
@@ -20,20 +20,21 @@ class MODULES_EXPORT DetectedFace final : public ScriptWrappable {
public:
static DetectedFace* Create();
static DetectedFace* Create(DOMRectReadOnly*);
- static DetectedFace* Create(DOMRectReadOnly*, const HeapVector<Landmark>&);
+ static DetectedFace* Create(DOMRectReadOnly*,
+ const HeapVector<Member<Landmark>>&);
+
+ explicit DetectedFace(DOMRectReadOnly*);
+ DetectedFace(DOMRectReadOnly*, const HeapVector<Member<Landmark>>&);
DOMRectReadOnly* boundingBox() const;
- const HeapVector<Landmark>& landmarks() const;
+ const HeapVector<Member<Landmark>>& landmarks() const;
ScriptValue toJSONForBinding(ScriptState*) const;
void Trace(blink::Visitor*) override;
private:
- explicit DetectedFace(DOMRectReadOnly*);
- DetectedFace(DOMRectReadOnly*, const HeapVector<Landmark>&);
-
const Member<DOMRectReadOnly> bounding_box_;
- const HeapVector<Landmark> landmarks_;
+ const HeapVector<Member<Landmark>> landmarks_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.cc b/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.cc
index 7a03de27916..dfd3de3a063 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.cc
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.cc
@@ -10,15 +10,16 @@
namespace blink {
DetectedText* DetectedText::Create() {
- HeapVector<Point2D> empty_list;
- return new DetectedText(g_empty_string, DOMRectReadOnly::Create(0, 0, 0, 0),
- empty_list);
+ HeapVector<Member<Point2D>> empty_list;
+ return MakeGarbageCollected<DetectedText>(
+ g_empty_string, DOMRectReadOnly::Create(0, 0, 0, 0), empty_list);
}
DetectedText* DetectedText::Create(String raw_value,
DOMRectReadOnly* bounding_box,
- HeapVector<Point2D> corner_points) {
- return new DetectedText(raw_value, bounding_box, corner_points);
+ HeapVector<Member<Point2D>> corner_points) {
+ return MakeGarbageCollected<DetectedText>(raw_value, bounding_box,
+ corner_points);
}
const String& DetectedText::rawValue() const {
@@ -29,13 +30,13 @@ DOMRectReadOnly* DetectedText::boundingBox() const {
return bounding_box_.Get();
}
-const HeapVector<Point2D>& DetectedText::cornerPoints() const {
+const HeapVector<Member<Point2D>>& DetectedText::cornerPoints() const {
return corner_points_;
}
DetectedText::DetectedText(String raw_value,
DOMRectReadOnly* bounding_box,
- HeapVector<Point2D> corner_points)
+ HeapVector<Member<Point2D>> corner_points)
: raw_value_(raw_value),
bounding_box_(bounding_box),
corner_points_(corner_points) {}
@@ -47,8 +48,8 @@ ScriptValue DetectedText::toJSONForBinding(ScriptState* script_state) const {
Vector<ScriptValue> corner_points;
for (const auto& corner_point : corner_points_) {
V8ObjectBuilder builder(script_state);
- builder.AddNumber("x", corner_point.x());
- builder.AddNumber("y", corner_point.y());
+ builder.AddNumber("x", corner_point->x());
+ builder.AddNumber("y", corner_point->y());
corner_points.push_back(builder.GetScriptValue());
}
result.Add("cornerPoints", corner_points);
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.h b/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.h
index 09f43783bc6..8af515e743d 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.h
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/detected_text.h
@@ -20,21 +20,23 @@ class MODULES_EXPORT DetectedText final : public ScriptWrappable {
public:
static DetectedText* Create();
- static DetectedText* Create(String, DOMRectReadOnly*, HeapVector<Point2D>);
+ static DetectedText* Create(String,
+ DOMRectReadOnly*,
+ HeapVector<Member<Point2D>>);
+
+ DetectedText(String, DOMRectReadOnly*, HeapVector<Member<Point2D>>);
const String& rawValue() const;
DOMRectReadOnly* boundingBox() const;
- const HeapVector<Point2D>& cornerPoints() const;
+ const HeapVector<Member<Point2D>>& cornerPoints() const;
ScriptValue toJSONForBinding(ScriptState*) const;
void Trace(blink::Visitor*) override;
private:
- DetectedText(String, DOMRectReadOnly*, HeapVector<Point2D>);
-
const String raw_value_;
const Member<DOMRectReadOnly> bounding_box_;
- const HeapVector<Point2D> corner_points_;
+ const HeapVector<Member<Point2D>> corner_points_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.cc b/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.cc
index 991dea9d475..fa7a0723460 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.cc
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.cc
@@ -22,17 +22,17 @@
namespace blink {
FaceDetector* FaceDetector::Create(ExecutionContext* context,
- const FaceDetectorOptions& options) {
- return new FaceDetector(context, options);
+ const FaceDetectorOptions* options) {
+ return MakeGarbageCollected<FaceDetector>(context, options);
}
FaceDetector::FaceDetector(ExecutionContext* context,
- const FaceDetectorOptions& options)
+ const FaceDetectorOptions* options)
: ShapeDetector() {
auto face_detector_options =
shape_detection::mojom::blink::FaceDetectorOptions::New();
- face_detector_options->max_detected_faces = options.maxDetectedFaces();
- face_detector_options->fast_mode = options.fastMode();
+ face_detector_options->max_detected_faces = options->maxDetectedFaces();
+ face_detector_options->fast_mode = options->fastMode();
shape_detection::mojom::blink::FaceDetectionProviderPtr provider;
auto request = mojo::MakeRequest(&provider);
@@ -72,19 +72,19 @@ void FaceDetector::OnDetectFaces(
HeapVector<Member<DetectedFace>> detected_faces;
for (const auto& face : face_detection_results) {
- HeapVector<Landmark> landmarks;
+ HeapVector<Member<Landmark>> landmarks;
for (const auto& landmark : face->landmarks) {
- HeapVector<Point2D> locations;
+ HeapVector<Member<Point2D>> locations;
for (const auto& location : landmark->locations) {
- Point2D web_location;
- web_location.setX(location.x);
- web_location.setY(location.y);
+ Point2D* web_location = Point2D::Create();
+ web_location->setX(location.x);
+ web_location->setY(location.y);
locations.push_back(web_location);
}
- Landmark web_landmark;
- web_landmark.setLocations(locations);
- web_landmark.setType(mojo::ConvertTo<String>(landmark->type));
+ Landmark* web_landmark = Landmark::Create();
+ web_landmark->setLocations(locations);
+ web_landmark->setType(mojo::ConvertTo<String>(landmark->type));
landmarks.push_back(web_landmark);
}
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.h b/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.h
index 34ae04ce052..86537084d01 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.h
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/face_detector.h
@@ -21,12 +21,13 @@ class MODULES_EXPORT FaceDetector final : public ShapeDetector {
DEFINE_WRAPPERTYPEINFO();
public:
- static FaceDetector* Create(ExecutionContext*, const FaceDetectorOptions&);
+ static FaceDetector* Create(ExecutionContext*, const FaceDetectorOptions*);
+
+ FaceDetector(ExecutionContext*, const FaceDetectorOptions*);
void Trace(blink::Visitor*) override;
private:
- FaceDetector(ExecutionContext*, const FaceDetectorOptions&);
~FaceDetector() override = default;
ScriptPromise DoDetect(ScriptPromiseResolver*, SkBitmap) override;
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/shape_detector.h b/chromium/third_party/blink/renderer/modules/shapedetection/shape_detector.h
index c752ac26d43..7b7e2cdbc2a 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/shape_detector.h
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/shape_detector.h
@@ -8,7 +8,7 @@
#include "skia/public/interfaces/bitmap.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
-#include "third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.h"
+#include "third_party/blink/renderer/core/frame/window_or_worker_global_scope.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.cc b/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.cc
index 9dc25067788..3e0e6ae66dc 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.cc
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.cc
@@ -16,7 +16,7 @@
namespace blink {
TextDetector* TextDetector::Create(ExecutionContext* context) {
- return new TextDetector(context);
+ return MakeGarbageCollected<TextDetector>(context);
}
TextDetector::TextDetector(ExecutionContext* context) : ShapeDetector() {
@@ -55,11 +55,11 @@ void TextDetector::OnDetectText(
HeapVector<Member<DetectedText>> detected_text;
for (const auto& text : text_detection_results) {
- HeapVector<Point2D> corner_points;
+ HeapVector<Member<Point2D>> corner_points;
for (const auto& corner_point : text->corner_points) {
- Point2D point;
- point.setX(corner_point.x);
- point.setY(corner_point.y);
+ Point2D* point = Point2D::Create();
+ point->setX(corner_point.x);
+ point->setY(corner_point.y);
corner_points.push_back(point);
}
detected_text.push_back(DetectedText::Create(
diff --git a/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.h b/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.h
index cb178b9f686..89136af5626 100644
--- a/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.h
+++ b/chromium/third_party/blink/renderer/modules/shapedetection/text_detector.h
@@ -22,10 +22,11 @@ class MODULES_EXPORT TextDetector final : public ShapeDetector {
public:
static TextDetector* Create(ExecutionContext*);
+ explicit TextDetector(ExecutionContext*);
+
void Trace(blink::Visitor*) override;
private:
- explicit TextDetector(ExecutionContext*);
~TextDetector() override = default;
ScriptPromise DoDetect(ScriptPromiseResolver*, SkBitmap) override;
diff --git a/chromium/third_party/blink/renderer/modules/speech/BUILD.gn b/chromium/third_party/blink/renderer/modules/speech/BUILD.gn
index 5597ba5fa8e..7a45f968463 100644
--- a/chromium/third_party/blink/renderer/modules/speech/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/speech/BUILD.gn
@@ -17,7 +17,6 @@ blink_modules_sources("speech") {
"speech_recognition.h",
"speech_recognition_alternative.cc",
"speech_recognition_alternative.h",
- "speech_recognition_client.h",
"speech_recognition_controller.cc",
"speech_recognition_controller.h",
"speech_recognition_error.cc",
diff --git a/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.cc b/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.cc
index 3b3f4ae7d73..2f36298c879 100644
--- a/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.cc
@@ -50,7 +50,7 @@ DOMWindowSpeechSynthesis& DOMWindowSpeechSynthesis::From(
DOMWindowSpeechSynthesis* supplement =
Supplement<LocalDOMWindow>::From<DOMWindowSpeechSynthesis>(window);
if (!supplement) {
- supplement = new DOMWindowSpeechSynthesis(window);
+ supplement = MakeGarbageCollected<DOMWindowSpeechSynthesis>(window);
ProvideTo(window, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.h b/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.h
index 81a9e8132fb..3602bd8d1cb 100644
--- a/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.h
+++ b/chromium/third_party/blink/renderer/modules/speech/dom_window_speech_synthesis.h
@@ -47,11 +47,11 @@ class MODULES_EXPORT DOMWindowSpeechSynthesis final
static SpeechSynthesis* speechSynthesis(ScriptState*, LocalDOMWindow&);
static DOMWindowSpeechSynthesis& From(LocalDOMWindow&);
+ explicit DOMWindowSpeechSynthesis(LocalDOMWindow&);
+
void Trace(blink::Visitor*) override;
private:
- explicit DOMWindowSpeechSynthesis(LocalDOMWindow&);
-
SpeechSynthesis* speechSynthesis(ScriptState*);
Member<SpeechSynthesis> speech_synthesis_;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_grammar.cc b/chromium/third_party/blink/renderer/modules/speech/speech_grammar.cc
index 59982229e20..fba694147e1 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_grammar.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_grammar.cc
@@ -31,11 +31,11 @@
namespace blink {
SpeechGrammar* SpeechGrammar::Create() {
- return new SpeechGrammar;
+ return MakeGarbageCollected<SpeechGrammar>();
}
SpeechGrammar* SpeechGrammar::Create(const KURL& src, double weight) {
- return new SpeechGrammar(src, weight);
+ return MakeGarbageCollected<SpeechGrammar>(src, weight);
}
void SpeechGrammar::setSrc(ScriptState* script_state, const String& src) {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_grammar.h b/chromium/third_party/blink/renderer/modules/speech/speech_grammar.h
index 55437e0797f..4d62a5bc224 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_grammar.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_grammar.h
@@ -44,6 +44,9 @@ class MODULES_EXPORT SpeechGrammar final : public ScriptWrappable {
// constructor should look like.
static SpeechGrammar* Create(const KURL& src, double weight);
+ SpeechGrammar();
+ SpeechGrammar(const KURL& src, double weight);
+
const KURL& src(ScriptState*) const { return src_; }
const KURL& src() const { return src_; }
void setSrc(ScriptState*, const String& src);
@@ -52,9 +55,6 @@ class MODULES_EXPORT SpeechGrammar final : public ScriptWrappable {
void setWeight(double weight) { weight_ = weight; }
private:
- SpeechGrammar();
- SpeechGrammar(const KURL& src, double weight);
-
KURL src_;
double weight_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.cc b/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.cc
index 2c7ce846f9c..c4cebb4a753 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.cc
@@ -32,7 +32,7 @@
namespace blink {
SpeechGrammarList* SpeechGrammarList::Create() {
- return new SpeechGrammarList;
+ return MakeGarbageCollected<SpeechGrammarList>();
}
SpeechGrammar* SpeechGrammarList::item(unsigned index) const {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.h b/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.h
index 1571dab9a72..14978bac681 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_grammar_list.h
@@ -41,6 +41,8 @@ class MODULES_EXPORT SpeechGrammarList final : public ScriptWrappable {
public:
static SpeechGrammarList* Create();
+ SpeechGrammarList();
+
unsigned length() const { return grammars_.size(); }
SpeechGrammar* item(unsigned) const;
@@ -50,8 +52,6 @@ class MODULES_EXPORT SpeechGrammarList final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- SpeechGrammarList();
-
HeapVector<Member<SpeechGrammar>> grammars_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition.cc
index 5047cac243d..681ecf0c9a0 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition.cc
@@ -38,7 +38,7 @@ namespace blink {
SpeechRecognition* SpeechRecognition::Create(ExecutionContext* context) {
Document& document = To<Document>(*context);
- return new SpeechRecognition(document.GetFrame(), context);
+ return MakeGarbageCollected<SpeechRecognition>(document.GetFrame(), context);
}
void SpeechRecognition::start(ExceptionState& exception_state) {
@@ -143,25 +143,25 @@ void SpeechRecognition::ErrorOccurred(
}
void SpeechRecognition::Started() {
- DispatchEvent(*Event::Create(EventTypeNames::start));
+ DispatchEvent(*Event::Create(event_type_names::kStart));
}
void SpeechRecognition::AudioStarted() {
- DispatchEvent(*Event::Create(EventTypeNames::audiostart));
+ DispatchEvent(*Event::Create(event_type_names::kAudiostart));
}
void SpeechRecognition::SoundStarted() {
- DispatchEvent(*Event::Create(EventTypeNames::soundstart));
- DispatchEvent(*Event::Create(EventTypeNames::speechstart));
+ DispatchEvent(*Event::Create(event_type_names::kSoundstart));
+ DispatchEvent(*Event::Create(event_type_names::kSpeechstart));
}
void SpeechRecognition::SoundEnded() {
- DispatchEvent(*Event::Create(EventTypeNames::speechend));
- DispatchEvent(*Event::Create(EventTypeNames::soundend));
+ DispatchEvent(*Event::Create(event_type_names::kSpeechend));
+ DispatchEvent(*Event::Create(event_type_names::kSoundend));
}
void SpeechRecognition::AudioEnded() {
- DispatchEvent(*Event::Create(EventTypeNames::audioend));
+ DispatchEvent(*Event::Create(event_type_names::kAudioend));
}
void SpeechRecognition::Ended() {
@@ -169,11 +169,11 @@ void SpeechRecognition::Ended() {
stopping_ = false;
session_.reset();
binding_.Close();
- DispatchEvent(*Event::Create(EventTypeNames::end));
+ DispatchEvent(*Event::Create(event_type_names::kEnd));
}
const AtomicString& SpeechRecognition::InterfaceName() const {
- return EventTargetNames::SpeechRecognition;
+ return event_target_names::kSpeechRecognition;
}
ExecutionContext* SpeechRecognition::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition.h
index ed6259ee8d8..a6850bd1109 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition.h
@@ -58,6 +58,8 @@ class MODULES_EXPORT SpeechRecognition final
public:
static SpeechRecognition* Create(ExecutionContext*);
+
+ SpeechRecognition(LocalFrame*, ExecutionContext*);
~SpeechRecognition() override;
// SpeechRecognition.idl implemementation.
@@ -106,23 +108,21 @@ class MODULES_EXPORT SpeechRecognition final
// PageVisibilityObserver
void PageVisibilityChanged() override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(audiostart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(soundstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(speechstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(speechend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(soundend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(audioend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(result);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(nomatch);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(start);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(end);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(audiostart, kAudiostart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(soundstart, kSoundstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(speechstart, kSpeechstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(speechend, kSpeechend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(soundend, kSoundend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(audioend, kAudioend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(result, kResult);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(nomatch, kNomatch);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(start, kStart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(end, kEnd);
void Trace(blink::Visitor*) override;
private:
- SpeechRecognition(LocalFrame*, ExecutionContext*);
-
void OnConnectionError();
Member<SpeechGrammarList> grammars_;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.cc
index 95144c24cda..e2dddb608fe 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.cc
@@ -30,7 +30,8 @@ namespace blink {
SpeechRecognitionAlternative* SpeechRecognitionAlternative::Create(
const String& transcript,
double confidence) {
- return new SpeechRecognitionAlternative(transcript, confidence);
+ return MakeGarbageCollected<SpeechRecognitionAlternative>(transcript,
+ confidence);
}
SpeechRecognitionAlternative::SpeechRecognitionAlternative(
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.h
index fb994f447e5..1a7e21e8b07 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_alternative.h
@@ -39,12 +39,12 @@ class MODULES_EXPORT SpeechRecognitionAlternative final
public:
static SpeechRecognitionAlternative* Create(const String&, double);
+ SpeechRecognitionAlternative(const String&, double);
+
const String& transcript() const { return transcript_; }
double confidence() const { return confidence_; }
private:
- SpeechRecognitionAlternative(const String&, double);
-
String transcript_;
double confidence_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.cc
index c16ed4933c7..69830f64db4 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.cc
@@ -46,7 +46,7 @@ SpeechRecognitionController::~SpeechRecognitionController() {
SpeechRecognitionController* SpeechRecognitionController::Create(
LocalFrame& frame) {
- return new SpeechRecognitionController(frame);
+ return MakeGarbageCollected<SpeechRecognitionController>(frame);
}
void SpeechRecognitionController::Start(
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.h
index 06c4c2a9080..8ab8880d08b 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_controller.h
@@ -44,6 +44,7 @@ class SpeechRecognitionController final
public:
static const char kSupplementName[];
+ explicit SpeechRecognitionController(LocalFrame& frame);
virtual ~SpeechRecognitionController();
void Start(mojom::blink::SpeechRecognitionSessionRequest session_request,
@@ -60,8 +61,6 @@ class SpeechRecognitionController final
}
private:
- explicit SpeechRecognitionController(LocalFrame& frame);
-
mojom::blink::SpeechRecognizer& GetSpeechRecognizer();
mojom::blink::SpeechRecognizerPtr speech_recognizer_;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.cc
index 1e2ba2253d6..19f2123b29a 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.cc
@@ -62,33 +62,34 @@ static String ErrorCodeToString(mojom::blink::SpeechRecognitionErrorCode code) {
SpeechRecognitionError* SpeechRecognitionError::Create(
mojom::blink::SpeechRecognitionErrorCode code,
const String& message) {
- return new SpeechRecognitionError(ErrorCodeToString(code), message);
+ return MakeGarbageCollected<SpeechRecognitionError>(ErrorCodeToString(code),
+ message);
}
SpeechRecognitionError* SpeechRecognitionError::Create(
const AtomicString& event_name,
- const SpeechRecognitionErrorInit& initializer) {
- return new SpeechRecognitionError(event_name, initializer);
+ const SpeechRecognitionErrorInit* initializer) {
+ return MakeGarbageCollected<SpeechRecognitionError>(event_name, initializer);
}
SpeechRecognitionError::SpeechRecognitionError(const String& error,
const String& message)
- : Event(EventTypeNames::error, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kError, Bubbles::kNo, Cancelable::kNo),
error_(error),
message_(message) {}
SpeechRecognitionError::SpeechRecognitionError(
const AtomicString& event_name,
- const SpeechRecognitionErrorInit& initializer)
+ const SpeechRecognitionErrorInit* initializer)
: Event(event_name, initializer) {
- if (initializer.hasError())
- error_ = initializer.error();
- if (initializer.hasMessage())
- message_ = initializer.message();
+ if (initializer->hasError())
+ error_ = initializer->error();
+ if (initializer->hasMessage())
+ message_ = initializer->message();
}
const AtomicString& SpeechRecognitionError::InterfaceName() const {
- return EventNames::SpeechRecognitionError;
+ return event_interface_names::kSpeechRecognitionError;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.h
index 4314c11f1bd..2d09eddfa14 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_error.h
@@ -42,7 +42,11 @@ class MODULES_EXPORT SpeechRecognitionError final : public Event {
mojom::blink::SpeechRecognitionErrorCode,
const String&);
static SpeechRecognitionError* Create(const AtomicString&,
- const SpeechRecognitionErrorInit&);
+ const SpeechRecognitionErrorInit*);
+
+ SpeechRecognitionError(const String&, const String&);
+ SpeechRecognitionError(const AtomicString&,
+ const SpeechRecognitionErrorInit*);
const String& error() { return error_; }
const String& message() { return message_; }
@@ -52,10 +56,6 @@ class MODULES_EXPORT SpeechRecognitionError final : public Event {
void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
private:
- SpeechRecognitionError(const String&, const String&);
- SpeechRecognitionError(const AtomicString&,
- const SpeechRecognitionErrorInit&);
-
String error_;
String message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.cc
index 5236cc5eaa4..682bb5f608c 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.cc
@@ -31,15 +31,15 @@ namespace blink {
SpeechRecognitionEvent* SpeechRecognitionEvent::Create(
const AtomicString& event_name,
- const SpeechRecognitionEventInit& initializer) {
- return new SpeechRecognitionEvent(event_name, initializer);
+ const SpeechRecognitionEventInit* initializer) {
+ return MakeGarbageCollected<SpeechRecognitionEvent>(event_name, initializer);
}
SpeechRecognitionEvent* SpeechRecognitionEvent::CreateResult(
uint32_t result_index,
const HeapVector<Member<SpeechRecognitionResult>>& results) {
- return new SpeechRecognitionEvent(
- EventTypeNames::result, result_index,
+ return MakeGarbageCollected<SpeechRecognitionEvent>(
+ event_type_names::kResult, result_index,
SpeechRecognitionResultList::Create(results));
}
@@ -48,26 +48,27 @@ SpeechRecognitionEvent* SpeechRecognitionEvent::CreateNoMatch(
if (result) {
HeapVector<Member<SpeechRecognitionResult>> results;
results.push_back(result);
- return new SpeechRecognitionEvent(
- EventTypeNames::nomatch, 0,
+ return MakeGarbageCollected<SpeechRecognitionEvent>(
+ event_type_names::kNomatch, 0,
SpeechRecognitionResultList::Create(results));
}
- return new SpeechRecognitionEvent(EventTypeNames::nomatch, 0, nullptr);
+ return MakeGarbageCollected<SpeechRecognitionEvent>(
+ event_type_names::kNomatch, 0, nullptr);
}
const AtomicString& SpeechRecognitionEvent::InterfaceName() const {
- return EventNames::SpeechRecognitionEvent;
+ return event_interface_names::kSpeechRecognitionEvent;
}
SpeechRecognitionEvent::SpeechRecognitionEvent(
const AtomicString& event_name,
- const SpeechRecognitionEventInit& initializer)
+ const SpeechRecognitionEventInit* initializer)
: Event(event_name, initializer), result_index_(0) {
- if (initializer.hasResultIndex())
- result_index_ = initializer.resultIndex();
- if (initializer.hasResults())
- results_ = initializer.results();
+ if (initializer->hasResultIndex())
+ result_index_ = initializer->resultIndex();
+ if (initializer->hasResults())
+ results_ = initializer->results();
}
SpeechRecognitionEvent::SpeechRecognitionEvent(
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.h
index 5bf5b563ec4..44e08c2e6f6 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_event.h
@@ -41,7 +41,13 @@ class SpeechRecognitionEvent final : public Event {
public:
static SpeechRecognitionEvent* Create(const AtomicString&,
- const SpeechRecognitionEventInit&);
+ const SpeechRecognitionEventInit*);
+
+ SpeechRecognitionEvent(const AtomicString&,
+ const SpeechRecognitionEventInit*);
+ SpeechRecognitionEvent(const AtomicString& event_name,
+ uint32_t result_index,
+ SpeechRecognitionResultList* results);
~SpeechRecognitionEvent() override;
static SpeechRecognitionEvent* CreateResult(
@@ -63,12 +69,6 @@ class SpeechRecognitionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- SpeechRecognitionEvent(const AtomicString&,
- const SpeechRecognitionEventInit&);
- SpeechRecognitionEvent(const AtomicString& event_name,
- uint32_t result_index,
- SpeechRecognitionResultList* results);
-
uint32_t result_index_;
Member<SpeechRecognitionResultList> results_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.cc
index 94927983b7e..4d861bbec8c 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.cc
@@ -30,7 +30,7 @@ namespace blink {
SpeechRecognitionResult* SpeechRecognitionResult::Create(
const HeapVector<Member<SpeechRecognitionAlternative>>& alternatives,
bool final) {
- return new SpeechRecognitionResult(alternatives, final);
+ return MakeGarbageCollected<SpeechRecognitionResult>(alternatives, final);
}
SpeechRecognitionAlternative* SpeechRecognitionResult::item(unsigned index) {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.h
index 3a34128abeb..570d39e779a 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result.h
@@ -41,6 +41,10 @@ class MODULES_EXPORT SpeechRecognitionResult final : public ScriptWrappable {
const HeapVector<Member<SpeechRecognitionAlternative>>&,
bool final);
+ SpeechRecognitionResult(
+ const HeapVector<Member<SpeechRecognitionAlternative>>&,
+ bool final);
+
unsigned length() { return alternatives_.size(); }
SpeechRecognitionAlternative* item(unsigned index);
bool isFinal() { return final_; }
@@ -48,10 +52,6 @@ class MODULES_EXPORT SpeechRecognitionResult final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- SpeechRecognitionResult(
- const HeapVector<Member<SpeechRecognitionAlternative>>&,
- bool final);
-
bool final_;
HeapVector<Member<SpeechRecognitionAlternative>> alternatives_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.cc b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.cc
index 2ab1767919d..ae92bc1a31f 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.cc
@@ -29,7 +29,7 @@ namespace blink {
SpeechRecognitionResultList* SpeechRecognitionResultList::Create(
const HeapVector<Member<SpeechRecognitionResult>>& results) {
- return new SpeechRecognitionResultList(results);
+ return MakeGarbageCollected<SpeechRecognitionResultList>(results);
}
SpeechRecognitionResult* SpeechRecognitionResultList::item(unsigned index) {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.h b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.h
index b741e22e930..6046b093410 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_recognition_result_list.h
@@ -39,15 +39,15 @@ class SpeechRecognitionResultList : public ScriptWrappable {
static SpeechRecognitionResultList* Create(
const HeapVector<Member<SpeechRecognitionResult>>&);
+ explicit SpeechRecognitionResultList(
+ const HeapVector<Member<SpeechRecognitionResult>>&);
+
unsigned length() { return results_.size(); }
SpeechRecognitionResult* item(unsigned index);
void Trace(blink::Visitor*) override;
private:
- explicit SpeechRecognitionResultList(
- const HeapVector<Member<SpeechRecognitionResult>>&);
-
HeapVector<Member<SpeechRecognitionResult>> results_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.cc b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.cc
index c86e56d786b..aa66606f948 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.cc
@@ -41,7 +41,7 @@
namespace blink {
SpeechSynthesis* SpeechSynthesis::Create(ExecutionContext* context) {
- return new SpeechSynthesis(context);
+ return MakeGarbageCollected<SpeechSynthesis>(context);
}
SpeechSynthesis::SpeechSynthesis(ExecutionContext* context)
@@ -59,7 +59,7 @@ void SpeechSynthesis::SetPlatformSynthesizer(
void SpeechSynthesis::VoicesDidChange() {
voice_list_.clear();
if (GetExecutionContext())
- DispatchEvent(*Event::Create(EventTypeNames::voiceschanged));
+ DispatchEvent(*Event::Create(event_type_names::kVoiceschanged));
}
const HeapVector<Member<SpeechSynthesisVoice>>& SpeechSynthesis::getVoices() {
@@ -158,28 +158,28 @@ void SpeechSynthesis::FireEvent(const AtomicString& type,
if (!GetElapsedTimeMillis(&millis))
return;
- SpeechSynthesisEventInit init;
- init.setUtterance(utterance);
- init.setCharIndex(char_index);
- init.setElapsedTime(millis - (utterance->StartTime() * 1000.0));
- init.setName(name);
+ SpeechSynthesisEventInit* init = SpeechSynthesisEventInit::Create();
+ init->setUtterance(utterance);
+ init->setCharIndex(char_index);
+ init->setElapsedTime(millis - (utterance->StartTime() * 1000.0));
+ init->setName(name);
utterance->DispatchEvent(*SpeechSynthesisEvent::Create(type, init));
}
void SpeechSynthesis::FireErrorEvent(SpeechSynthesisUtterance* utterance,
- unsigned long char_index,
+ uint32_t char_index,
const String& error) {
double millis;
if (!GetElapsedTimeMillis(&millis))
return;
- SpeechSynthesisErrorEventInit init;
- init.setUtterance(utterance);
- init.setCharIndex(char_index);
- init.setElapsedTime(millis - (utterance->StartTime() * 1000.0));
- init.setError(error);
+ SpeechSynthesisErrorEventInit* init = SpeechSynthesisErrorEventInit::Create();
+ init->setUtterance(utterance);
+ init->setCharIndex(char_index);
+ init->setElapsedTime(millis - (utterance->StartTime() * 1000.0));
+ init->setError(error);
utterance->DispatchEvent(
- *SpeechSynthesisErrorEvent::Create(EventTypeNames::error, init));
+ *SpeechSynthesisErrorEvent::Create(event_type_names::kError, init));
}
void SpeechSynthesis::HandleSpeakingCompleted(
@@ -204,7 +204,7 @@ void SpeechSynthesis::HandleSpeakingCompleted(
// generic error.
FireErrorEvent(utterance, 0, "synthesis-failed");
} else {
- FireEvent(EventTypeNames::end, utterance, 0, String());
+ FireEvent(event_type_names::kEnd, utterance, 0, String());
}
// Start the next utterance if we just finished one and one was pending.
@@ -221,12 +221,12 @@ void SpeechSynthesis::BoundaryEventOccurred(
switch (boundary) {
case kSpeechWordBoundary:
- FireEvent(EventTypeNames::boundary,
+ FireEvent(event_type_names::kBoundary,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()),
char_index, word_boundary_string);
break;
case kSpeechSentenceBoundary:
- FireEvent(EventTypeNames::boundary,
+ FireEvent(event_type_names::kBoundary,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()),
char_index, sentence_boundary_string);
break;
@@ -238,7 +238,7 @@ void SpeechSynthesis::BoundaryEventOccurred(
void SpeechSynthesis::DidStartSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
if (utterance->Client())
- FireEvent(EventTypeNames::start,
+ FireEvent(event_type_names::kStart,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), 0,
String());
}
@@ -247,7 +247,7 @@ void SpeechSynthesis::DidPauseSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
is_paused_ = true;
if (utterance->Client())
- FireEvent(EventTypeNames::pause,
+ FireEvent(event_type_names::kPause,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), 0,
String());
}
@@ -256,7 +256,7 @@ void SpeechSynthesis::DidResumeSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
is_paused_ = false;
if (utterance->Client())
- FireEvent(EventTypeNames::resume,
+ FireEvent(event_type_names::kResume,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), 0,
String());
}
@@ -283,7 +283,7 @@ SpeechSynthesisUtterance* SpeechSynthesis::CurrentSpeechUtterance() const {
}
const AtomicString& SpeechSynthesis::InterfaceName() const {
- return EventTargetNames::SpeechSynthesis;
+ return event_target_names::kSpeechSynthesis;
}
void SpeechSynthesis::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.h b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.h
index 850407dad5a..3eb87a4f6d0 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis.h
@@ -49,6 +49,8 @@ class MODULES_EXPORT SpeechSynthesis final
public:
static SpeechSynthesis* Create(ExecutionContext*);
+ explicit SpeechSynthesis(ExecutionContext*);
+
bool pending() const;
bool speaking() const;
bool paused() const;
@@ -63,7 +65,7 @@ class MODULES_EXPORT SpeechSynthesis final
// Used in testing to use a mock platform synthesizer
void SetPlatformSynthesizer(PlatformSpeechSynthesizer*);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(voiceschanged);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(voiceschanged, kVoiceschanged);
ExecutionContext* GetExecutionContext() const override {
return ContextClient::GetExecutionContext();
@@ -72,8 +74,6 @@ class MODULES_EXPORT SpeechSynthesis final
void Trace(blink::Visitor*) override;
private:
- explicit SpeechSynthesis(ExecutionContext*);
-
// PlatformSpeechSynthesizerClient override methods.
void VoicesDidChange() override;
void DidStartSpeaking(PlatformSpeechSynthesisUtterance*) override;
@@ -93,7 +93,7 @@ class MODULES_EXPORT SpeechSynthesis final
const String& name);
void FireErrorEvent(SpeechSynthesisUtterance*,
- unsigned long char_index,
+ uint32_t char_index,
const String& error);
// Returns the utterance at the front of the queue.
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.cc b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.cc
index 40801425425..54e4bbbf6e4 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.cc
@@ -9,18 +9,18 @@ namespace blink {
// static
SpeechSynthesisErrorEvent* SpeechSynthesisErrorEvent::Create(
const AtomicString& type,
- const SpeechSynthesisErrorEventInit& init) {
+ const SpeechSynthesisErrorEventInit* init) {
return new SpeechSynthesisErrorEvent(type, init);
}
SpeechSynthesisErrorEvent::SpeechSynthesisErrorEvent(
const AtomicString& type,
- const SpeechSynthesisErrorEventInit& init)
+ const SpeechSynthesisErrorEventInit* init)
: SpeechSynthesisEvent(type,
- init.utterance(),
- init.charIndex(),
- init.elapsedTime(),
- init.name()),
- error_(init.error()) {}
+ init->utterance(),
+ init->charIndex(),
+ init->elapsedTime(),
+ init->name()),
+ error_(init->error()) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.h b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.h
index 24be96080e0..62f5a5f301d 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.h
@@ -18,13 +18,13 @@ class SpeechSynthesisErrorEvent : public SpeechSynthesisEvent {
public:
static SpeechSynthesisErrorEvent* Create(
const AtomicString& type,
- const SpeechSynthesisErrorEventInit& init);
+ const SpeechSynthesisErrorEventInit* init);
const String error() const { return error_; }
private:
SpeechSynthesisErrorEvent(const AtomicString& type,
- const SpeechSynthesisErrorEventInit& init);
+ const SpeechSynthesisErrorEventInit* init);
const String error_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.idl b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.idl
index ec5d7809207..f766c5b5161 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.idl
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_error_event.idl
@@ -22,7 +22,7 @@ enum SpeechSynthesisErrorCode {
[
Exposed=Window,
Constructor(DOMString type, SpeechSynthesisErrorEventInit eventInitDict),
- RuntimeEnabled=ScriptedSpeech
+ RuntimeEnabled=ScriptedSpeechSynthesis
] interface SpeechSynthesisErrorEvent : SpeechSynthesisEvent {
readonly attribute SpeechSynthesisErrorCode error;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.cc b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.cc
index 6e0ab68cdbc..9148c911bad 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.cc
@@ -29,9 +29,10 @@ namespace blink {
SpeechSynthesisEvent* SpeechSynthesisEvent::Create(
const AtomicString& type,
- const SpeechSynthesisEventInit& init) {
- return new SpeechSynthesisEvent(type, init.utterance(), init.charIndex(),
- init.elapsedTime(), init.name());
+ const SpeechSynthesisEventInit* init) {
+ return MakeGarbageCollected<SpeechSynthesisEvent>(
+ type, init->utterance(), init->charIndex(), init->elapsedTime(),
+ init->name());
}
SpeechSynthesisEvent::SpeechSynthesisEvent(const AtomicString& type,
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.h b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.h
index 71fbf3e31e4..31cae84b5c2 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.h
@@ -37,7 +37,13 @@ class SpeechSynthesisEvent : public Event {
public:
static SpeechSynthesisEvent* Create(const AtomicString& type,
- const SpeechSynthesisEventInit& init);
+ const SpeechSynthesisEventInit* init);
+
+ SpeechSynthesisEvent(const AtomicString& type,
+ SpeechSynthesisUtterance*,
+ unsigned char_index,
+ float elapsed_time,
+ const String& name);
SpeechSynthesisUtterance* utterance() const { return utterance_; }
unsigned charIndex() const { return char_index_; }
@@ -45,18 +51,11 @@ class SpeechSynthesisEvent : public Event {
const String& name() const { return name_; }
const AtomicString& InterfaceName() const override {
- return EventNames::SpeechSynthesisEvent;
+ return event_interface_names::kSpeechSynthesisEvent;
}
void Trace(blink::Visitor*) override;
- protected:
- SpeechSynthesisEvent(const AtomicString& type,
- SpeechSynthesisUtterance*,
- unsigned char_index,
- float elapsed_time,
- const String& name);
-
private:
Member<SpeechSynthesisUtterance> utterance_;
unsigned char_index_;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.idl b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.idl
index 0f9e01be747..b64b8487a52 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.idl
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_event.idl
@@ -25,7 +25,7 @@
// https://w3c.github.io/speech-api/#speechsynthesisevent
[
- RuntimeEnabled=ScriptedSpeech,
+ RuntimeEnabled=ScriptedSpeechSynthesis,
Constructor(DOMString type, SpeechSynthesisEventInit eventInitDict)
] interface SpeechSynthesisEvent : Event {
readonly attribute SpeechSynthesisUtterance utterance;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.cc b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.cc
index 77b153fbd48..3ea1cd65d16 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.cc
@@ -32,7 +32,7 @@ namespace blink {
SpeechSynthesisUtterance* SpeechSynthesisUtterance::Create(
ExecutionContext* context,
const String& text) {
- return new SpeechSynthesisUtterance(context, text);
+ return MakeGarbageCollected<SpeechSynthesisUtterance>(context, text);
}
SpeechSynthesisUtterance::SpeechSynthesisUtterance(ExecutionContext* context,
@@ -45,7 +45,7 @@ SpeechSynthesisUtterance::SpeechSynthesisUtterance(ExecutionContext* context,
SpeechSynthesisUtterance::~SpeechSynthesisUtterance() = default;
const AtomicString& SpeechSynthesisUtterance::InterfaceName() const {
- return EventTargetNames::SpeechSynthesisUtterance;
+ return event_target_names::kSpeechSynthesisUtterance;
}
SpeechSynthesisVoice* SpeechSynthesisUtterance::voice() const {
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.h b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.h
index 487e7ef4702..5cad4e7083c 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.h
@@ -44,6 +44,7 @@ class SpeechSynthesisUtterance final
public:
static SpeechSynthesisUtterance* Create(ExecutionContext*, const String&);
+ SpeechSynthesisUtterance(ExecutionContext*, const String&);
~SpeechSynthesisUtterance() override;
const String& text() const { return platform_utterance_->GetText(); }
@@ -69,13 +70,13 @@ class SpeechSynthesisUtterance final
platform_utterance_->SetStartTime(start_time);
}
- DEFINE_ATTRIBUTE_EVENT_LISTENER(start);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(end);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pause);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resume);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mark);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(boundary);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(start, kStart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(end, kEnd);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(pause, kPause);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resume, kResume);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(mark, kMark);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(boundary, kBoundary);
ExecutionContext* GetExecutionContext() const override {
return ContextClient::GetExecutionContext();
@@ -88,8 +89,6 @@ class SpeechSynthesisUtterance final
void Trace(blink::Visitor*) override;
private:
- SpeechSynthesisUtterance(ExecutionContext*, const String&);
-
// EventTarget
const AtomicString& InterfaceName() const override;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.idl b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.idl
index e8e8fa2534d..1f34c7c2a74 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.idl
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_utterance.idl
@@ -28,7 +28,7 @@
[
Constructor(optional DOMString text = null),
ConstructorCallWith=ExecutionContext,
- RuntimeEnabled=ScriptedSpeech
+ RuntimeEnabled=ScriptedSpeechSynthesis
] interface SpeechSynthesisUtterance : EventTarget {
attribute DOMString text;
attribute DOMString lang;
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.cc b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.cc
index 6aed85da9d2..8cae9c8ebcf 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.cc
@@ -29,7 +29,7 @@ namespace blink {
SpeechSynthesisVoice* SpeechSynthesisVoice::Create(
scoped_refptr<PlatformSpeechSynthesisVoice> voice) {
- return new SpeechSynthesisVoice(std::move(voice));
+ return MakeGarbageCollected<SpeechSynthesisVoice>(std::move(voice));
}
SpeechSynthesisVoice::SpeechSynthesisVoice(
diff --git a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.h b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.h
index f641ac946ad..70ddd89aa60 100644
--- a/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.h
+++ b/chromium/third_party/blink/renderer/modules/speech/speech_synthesis_voice.h
@@ -40,6 +40,8 @@ class SpeechSynthesisVoice final : public ScriptWrappable {
public:
static SpeechSynthesisVoice* Create(
scoped_refptr<PlatformSpeechSynthesisVoice>);
+
+ explicit SpeechSynthesisVoice(scoped_refptr<PlatformSpeechSynthesisVoice>);
~SpeechSynthesisVoice() override;
const String& voiceURI() const { return platform_voice_->VoiceURI(); }
@@ -53,8 +55,6 @@ class SpeechSynthesisVoice final : public ScriptWrappable {
}
private:
- explicit SpeechSynthesisVoice(scoped_refptr<PlatformSpeechSynthesisVoice>);
-
scoped_refptr<PlatformSpeechSynthesisVoice> platform_voice_;
};
diff --git a/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.cc b/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.cc
index c0feb2071e0..5d9830ec7c3 100644
--- a/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.cc
+++ b/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.cc
@@ -35,7 +35,7 @@ PlatformSpeechSynthesizerMock* PlatformSpeechSynthesizerMock::Create(
PlatformSpeechSynthesizerClient* client,
ExecutionContext* context) {
PlatformSpeechSynthesizerMock* synthesizer =
- new PlatformSpeechSynthesizerMock(client, context);
+ MakeGarbageCollected<PlatformSpeechSynthesizerMock>(client, context);
synthesizer->InitializeVoiceList();
client->VoicesDidChange();
return synthesizer;
diff --git a/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.h b/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.h
index 3c690abe366..bfd6ff748e7 100644
--- a/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.h
+++ b/chromium/third_party/blink/renderer/modules/speech/testing/platform_speech_synthesizer_mock.h
@@ -38,7 +38,10 @@ class PlatformSpeechSynthesizerMock final : public PlatformSpeechSynthesizer {
static PlatformSpeechSynthesizerMock* Create(PlatformSpeechSynthesizerClient*,
ExecutionContext*);
+ explicit PlatformSpeechSynthesizerMock(PlatformSpeechSynthesizerClient*,
+ ExecutionContext*);
~PlatformSpeechSynthesizerMock() override;
+
void Speak(PlatformSpeechSynthesisUtterance*) override;
void Pause() override;
void Resume() override;
@@ -47,9 +50,6 @@ class PlatformSpeechSynthesizerMock final : public PlatformSpeechSynthesizer {
void Trace(blink::Visitor*) override;
private:
- explicit PlatformSpeechSynthesizerMock(PlatformSpeechSynthesizerClient*,
- ExecutionContext*);
-
void InitializeVoiceList() override;
void SpeakNext();
diff --git a/chromium/third_party/blink/renderer/modules/speech/window_speech.idl b/chromium/third_party/blink/renderer/modules/speech/window_speech.idl
index fdc4623ab12..4aa18e25f97 100644
--- a/chromium/third_party/blink/renderer/modules/speech/window_speech.idl
+++ b/chromium/third_party/blink/renderer/modules/speech/window_speech.idl
@@ -4,7 +4,7 @@
[
ImplementedAs=DOMWindowSpeech,
- RuntimeEnabled=ScriptedSpeech
+ RuntimeEnabled=ScriptedSpeechRecognition
] partial interface Window {
[Measure] attribute SpeechGrammarConstructor webkitSpeechGrammar;
[Measure] attribute SpeechGrammarListConstructor webkitSpeechGrammarList;
diff --git a/chromium/third_party/blink/renderer/modules/speech/window_speech_synthesis.idl b/chromium/third_party/blink/renderer/modules/speech/window_speech_synthesis.idl
index ca272551bb8..c7a94d9e50a 100644
--- a/chromium/third_party/blink/renderer/modules/speech/window_speech_synthesis.idl
+++ b/chromium/third_party/blink/renderer/modules/speech/window_speech_synthesis.idl
@@ -25,7 +25,7 @@
[
ImplementedAs=DOMWindowSpeechSynthesis,
- RuntimeEnabled=ScriptedSpeech
+ RuntimeEnabled=ScriptedSpeechSynthesis
] partial interface Window {
[Measure, CallWith=ScriptState] readonly attribute SpeechSynthesis speechSynthesis;
};
diff --git a/chromium/third_party/blink/renderer/modules/storage/DEPS b/chromium/third_party/blink/renderer/modules/storage/DEPS
new file mode 100644
index 00000000000..9b836bbc861
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/storage/DEPS
@@ -0,0 +1,5 @@
+specific_include_rules = {
+ "storage_controller_test\.cc": [
+ "+base/run_loop.h",
+ ],
+}
diff --git a/chromium/third_party/blink/renderer/modules/storage/cached_storage_area.cc b/chromium/third_party/blink/renderer/modules/storage/cached_storage_area.cc
index afc5524c536..35a114eb8fc 100644
--- a/chromium/third_party/blink/renderer/modules/storage/cached_storage_area.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/cached_storage_area.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/modules/storage/cached_storage_area.h"
#include "base/metrics/histogram_macros.h"
+#include "base/numerics/safe_conversions.h"
#include "base/rand_util.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
@@ -229,7 +230,7 @@ CachedStorageArea::CachedStorageArea(
mojo_area_(area.get()),
mojo_area_ptr_(std::move(area)),
binding_(this),
- areas_(new HeapHashMap<WeakMember<Source>, String>),
+ areas_(MakeGarbageCollected<HeapHashMap<WeakMember<Source>, String>>()),
weak_factory_(this) {
mojom::blink::StorageAreaObserverAssociatedPtrInfo ptr_info;
binding_.Bind(mojo::MakeRequest(&ptr_info), std::move(ipc_runner));
@@ -247,7 +248,7 @@ CachedStorageArea::CachedStorageArea(
mojo_area_(area.get()),
mojo_area_associated_ptr_(std::move(area)),
binding_(this),
- areas_(new HeapHashMap<WeakMember<Source>, String>),
+ areas_(MakeGarbageCollected<HeapHashMap<WeakMember<Source>, String>>()),
weak_factory_(this) {
mojom::blink::StorageAreaObserverAssociatedPtrInfo ptr_info;
binding_.Bind(mojo::MakeRequest(&ptr_info), std::move(ipc_runner));
@@ -423,8 +424,11 @@ void CachedStorageArea::EnsureLoaded() {
if (map_)
return;
+ // There might be something weird happening during the sync call that destroys
+ // this object. Keep a reference to either fix or rule out that this is the
+ // problem. See https://crbug.com/915577.
+ scoped_refptr<CachedStorageArea> keep_alive(this);
base::TimeTicks before = base::TimeTicks::Now();
-
ignore_all_mutations_ = true;
bool success = false;
Vector<mojom::blink::KeyValuePtr> data;
@@ -451,8 +455,10 @@ void CachedStorageArea::EnsureLoaded() {
// Track localStorage size, from 0-6MB. Note that the maximum size should be
// 10MB, but we add some slop since we want to make sure the max size is
// always above what we see in practice, since histograms can't change.
- UMA_HISTOGRAM_CUSTOM_COUNTS("LocalStorage.MojoSizeInKB",
- local_storage_size_kb, 1, 6 * 1024, 50);
+ UMA_HISTOGRAM_CUSTOM_COUNTS(
+ "LocalStorage.MojoSizeInKB",
+ base::saturated_cast<base::Histogram::Sample>(local_storage_size_kb), 1,
+ 6 * 1024, 50);
if (local_storage_size_kb < 100) {
UMA_HISTOGRAM_TIMES("LocalStorage.MojoTimeToPrimeForUnder100KB",
time_to_prime);
@@ -509,7 +515,7 @@ String CachedStorageArea::Uint8VectorToString(const Vector<uint8_t>& input,
FormatOption format_option) {
if (input.IsEmpty())
return g_empty_string;
- const size_t input_size = input.size();
+ const wtf_size_t input_size = input.size();
String result;
bool corrupt = false;
switch (format_option) {
@@ -536,7 +542,7 @@ String CachedStorageArea::Uint8VectorToString(const Vector<uint8_t>& input,
}
case FormatOption::kLocalStorageDetectFormat: {
StorageFormat format = static_cast<StorageFormat>(input[0]);
- const size_t payload_size = input_size - 1;
+ const wtf_size_t payload_size = input_size - 1;
switch (format) {
case StorageFormat::UTF16: {
if (payload_size % sizeof(UChar) != 0) {
@@ -580,7 +586,7 @@ Vector<uint8_t> CachedStorageArea::StringToUint8Vector(
}
case FormatOption::kSessionStorageForceUTF8: {
unsigned length = input.length();
- if (input.Is8Bit() && input.ContainsOnlyASCII()) {
+ if (input.Is8Bit() && input.ContainsOnlyASCIIOrEmpty()) {
Vector<uint8_t> result(length);
std::memcpy(result.data(), input.Characters8(), length);
return result;
@@ -597,14 +603,15 @@ Vector<uint8_t> CachedStorageArea::StringToUint8Vector(
uint8_t* buffer = buffer_vector.data();
const LChar* characters = input.Characters8();
- WTF::Unicode::ConversionResult result =
- WTF::Unicode::ConvertLatin1ToUTF8(
+ WTF::unicode::ConversionResult result =
+ WTF::unicode::ConvertLatin1ToUTF8(
&characters, characters + length,
reinterpret_cast<char**>(&buffer),
reinterpret_cast<char*>(buffer + buffer_vector.size()));
// (length * 3) should be sufficient for any conversion
- DCHECK_NE(result, WTF::Unicode::kTargetExhausted);
- buffer_vector.Shrink(buffer - buffer_vector.data());
+ DCHECK_NE(result, WTF::unicode::kTargetExhausted);
+ buffer_vector.Shrink(
+ static_cast<wtf_size_t>(buffer - buffer_vector.data()));
return buffer_vector;
}
@@ -617,7 +624,7 @@ Vector<uint8_t> CachedStorageArea::StringToUint8Vector(
return result;
}
case FormatOption::kLocalStorageDetectFormat: {
- if (input.ContainsOnlyLatin1()) {
+ if (input.ContainsOnlyLatin1OrEmpty()) {
Vector<uint8_t> result(input.length() + 1);
result[0] = static_cast<uint8_t>(StorageFormat::Latin1);
if (input.Is8Bit()) {
diff --git a/chromium/third_party/blink/renderer/modules/storage/cached_storage_area_test.cc b/chromium/third_party/blink/renderer/modules/storage/cached_storage_area_test.cc
index c85494858cb..eab9d836e6a 100644
--- a/chromium/third_party/blink/renderer/modules/storage/cached_storage_area_test.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/cached_storage_area_test.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/modules/storage/cached_storage_area.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/renderer/modules/storage/testing/fake_area_source.h"
#include "third_party/blink/renderer/modules/storage/testing/mock_storage_area.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
@@ -32,16 +32,16 @@ class CachedStorageAreaTest : public testing::Test,
if (IsSessionStorage()) {
cached_area_ = CachedStorageArea::CreateForSessionStorage(
kOrigin, mock_storage_area_.GetAssociatedInterfacePtr(),
- renderer_scheduler_->IPCTaskRunner(), this);
+ scheduler::GetSingleThreadTaskRunnerForTesting(), this);
} else {
cached_area_ = CachedStorageArea::CreateForLocalStorage(
kOrigin, mock_storage_area_.GetInterfacePtr(),
- renderer_scheduler_->IPCTaskRunner(), this);
+ scheduler::GetSingleThreadTaskRunnerForTesting(), this);
}
- source_area_ = new FakeAreaSource(kPageUrl);
+ source_area_ = MakeGarbageCollected<FakeAreaSource>(kPageUrl);
source_area_id_ = cached_area_->RegisterSource(source_area_);
source_ = kPageUrl.GetString() + "\n" + source_area_id_;
- source_area2_ = new FakeAreaSource(kPageUrl2);
+ source_area2_ = MakeGarbageCollected<FakeAreaSource>(kPageUrl2);
cached_area_->RegisterSource(source_area2_);
}
@@ -98,8 +98,6 @@ class CachedStorageAreaTest : public testing::Test,
}
protected:
- std::unique_ptr<scheduler::WebThreadScheduler> renderer_scheduler_ =
- std::make_unique<scheduler::FakeRendererScheduler>();
MockStorageArea mock_storage_area_;
Persistent<FakeAreaSource> source_area_;
Persistent<FakeAreaSource> source_area2_;
diff --git a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.cc b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.cc
index e62490bd038..a03053bbe62 100644
--- a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.cc
@@ -4,7 +4,9 @@
#include "third_party/blink/renderer/modules/storage/dom_window_storage.h"
+#include "base/feature_list.h"
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -35,7 +37,7 @@ DOMWindowStorage& DOMWindowStorage::From(LocalDOMWindow& window) {
DOMWindowStorage* supplement =
Supplement<LocalDOMWindow>::From<DOMWindowStorage>(window);
if (!supplement) {
- supplement = new DOMWindowStorage(window);
+ supplement = MakeGarbageCollected<DOMWindowStorage>(window);
ProvideTo(window, supplement);
}
return *supplement;
@@ -89,11 +91,22 @@ StorageArea* DOMWindowStorage::sessionStorage(
if (!page)
return nullptr;
- auto storage_area = StorageNamespace::From(page)->GetWebStorageArea(
- document->GetSecurityOrigin());
- session_storage_ =
- StorageArea::Create(document->GetFrame(), std::move(storage_area),
- StorageArea::StorageType::kSessionStorage);
+ StorageNamespace* storage_namespace = StorageNamespace::From(page);
+ if (!storage_namespace)
+ return nullptr;
+ if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) {
+ auto storage_area =
+ storage_namespace->GetCachedArea(document->GetSecurityOrigin());
+ session_storage_ =
+ StorageArea::Create(document->GetFrame(), std::move(storage_area),
+ StorageArea::StorageType::kSessionStorage);
+ } else {
+ auto storage_area =
+ storage_namespace->GetWebStorageArea(document->GetSecurityOrigin());
+ session_storage_ =
+ StorageArea::Create(document->GetFrame(), std::move(storage_area),
+ StorageArea::StorageType::kSessionStorage);
+ }
if (!session_storage_->CanAccessStorage()) {
exception_state.ThrowSecurityError(access_denied_message);
return nullptr;
@@ -136,11 +149,20 @@ StorageArea* DOMWindowStorage::localStorage(
Page* page = document->GetPage();
if (!page || !page->GetSettings().GetLocalStorageEnabled())
return nullptr;
- auto storage_area = StorageController::GetInstance()->GetWebLocalStorageArea(
- document->GetSecurityOrigin());
- local_storage_ =
- StorageArea::Create(document->GetFrame(), std::move(storage_area),
- StorageArea::StorageType::kLocalStorage);
+ if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) {
+ auto storage_area = StorageController::GetInstance()->GetLocalStorageArea(
+ document->GetSecurityOrigin());
+ local_storage_ =
+ StorageArea::Create(document->GetFrame(), std::move(storage_area),
+ StorageArea::StorageType::kLocalStorage);
+ } else {
+ auto storage_area =
+ StorageController::GetInstance()->GetWebLocalStorageArea(
+ document->GetSecurityOrigin());
+ local_storage_ =
+ StorageArea::Create(document->GetFrame(), std::move(storage_area),
+ StorageArea::StorageType::kLocalStorage);
+ }
if (!local_storage_->CanAccessStorage()) {
exception_state.ThrowSecurityError(access_denied_message);
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.h b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.h
index d958b9075aa..34d67facfdc 100644
--- a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.h
+++ b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage.h
@@ -25,6 +25,8 @@ class DOMWindowStorage final : public GarbageCollected<DOMWindowStorage>,
static StorageArea* sessionStorage(LocalDOMWindow&, ExceptionState&);
static StorageArea* localStorage(LocalDOMWindow&, ExceptionState&);
+ explicit DOMWindowStorage(LocalDOMWindow&);
+
StorageArea* sessionStorage(ExceptionState&) const;
StorageArea* localStorage(ExceptionState&) const;
StorageArea* OptionalSessionStorage() const { return session_storage_.Get(); }
@@ -33,8 +35,6 @@ class DOMWindowStorage final : public GarbageCollected<DOMWindowStorage>,
void Trace(blink::Visitor*) override;
private:
- explicit DOMWindowStorage(LocalDOMWindow&);
-
mutable Member<StorageArea> session_storage_;
mutable Member<StorageArea> local_storage_;
};
diff --git a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.cc b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.cc
index b3ae3a54956..0bca8b97e15 100644
--- a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.cc
@@ -30,7 +30,7 @@ DOMWindowStorageController& DOMWindowStorageController::From(
DOMWindowStorageController* controller =
Supplement<Document>::From<DOMWindowStorageController>(document);
if (!controller) {
- controller = new DOMWindowStorageController(document);
+ controller = MakeGarbageCollected<DOMWindowStorageController>(document);
ProvideTo(document, controller);
}
return *controller;
@@ -39,7 +39,7 @@ DOMWindowStorageController& DOMWindowStorageController::From(
void DOMWindowStorageController::DidAddEventListener(
LocalDOMWindow* window,
const AtomicString& event_type) {
- if (event_type == EventTypeNames::storage) {
+ if (event_type == event_type_names::kStorage) {
// Creating these blink::Storage objects informs the system that we'd like
// to receive notifications about storage events that might be triggered in
// other processes. Rather than subscribe to these notifications explicitly,
diff --git a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.h b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.h
index 59adc639f8d..f0a17f7d299 100644
--- a/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.h
+++ b/chromium/third_party/blink/renderer/modules/storage/dom_window_storage_controller.h
@@ -24,6 +24,8 @@ class MODULES_EXPORT DOMWindowStorageController final
public:
static const char kSupplementName[];
+ explicit DOMWindowStorageController(Document&);
+
void Trace(blink::Visitor*) override;
static DOMWindowStorageController& From(Document&);
@@ -32,9 +34,6 @@ class MODULES_EXPORT DOMWindowStorageController final
void DidAddEventListener(LocalDOMWindow*, const AtomicString&) override;
void DidRemoveEventListener(LocalDOMWindow*, const AtomicString&) override {}
void DidRemoveAllEventListeners(LocalDOMWindow*) override {}
-
- private:
- explicit DOMWindowStorageController(Document&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc b/chromium/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc
index 708b67262c5..88982b97c6b 100644
--- a/chromium/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc
@@ -29,6 +29,8 @@
#include "third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.h"
+#include "base/feature_list.h"
+#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
@@ -219,11 +221,19 @@ Response InspectorDOMStorageAgent::FindStorageArea(
if (is_local_storage) {
if (!frame->GetDocument()->GetSecurityOrigin()->CanAccessLocalStorage())
return Response::Error("Security origin cannot access local storage");
- storage_area = StorageArea::Create(
- frame,
- StorageController::GetInstance()->GetWebLocalStorageArea(
- frame->GetDocument()->GetSecurityOrigin()),
- StorageArea::StorageType::kLocalStorage);
+ if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) {
+ storage_area = StorageArea::CreateForInspectorAgent(
+ frame,
+ StorageController::GetInstance()->GetLocalStorageArea(
+ frame->GetDocument()->GetSecurityOrigin()),
+ StorageArea::StorageType::kLocalStorage);
+ } else {
+ storage_area = StorageArea::Create(
+ frame,
+ StorageController::GetInstance()->GetWebLocalStorageArea(
+ frame->GetDocument()->GetSecurityOrigin()),
+ StorageArea::StorageType::kLocalStorage);
+ }
return Response::OK();
}
@@ -235,11 +245,19 @@ Response InspectorDOMStorageAgent::FindStorageArea(
return Response::Error("SessionStorage is not supported");
DCHECK(session_namespace->IsSessionStorage());
- storage_area =
- StorageArea::Create(frame,
- session_namespace->GetWebStorageArea(
- frame->GetDocument()->GetSecurityOrigin()),
- StorageArea::StorageType::kSessionStorage);
+ if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) {
+ storage_area = StorageArea::CreateForInspectorAgent(
+ frame,
+ session_namespace->GetCachedArea(
+ frame->GetDocument()->GetSecurityOrigin()),
+ StorageArea::StorageType::kSessionStorage);
+ } else {
+ storage_area =
+ StorageArea::Create(frame,
+ session_namespace->GetWebStorageArea(
+ frame->GetDocument()->GetSecurityOrigin()),
+ StorageArea::StorageType::kSessionStorage);
+ }
return Response::OK();
}
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_area.cc b/chromium/third_party/blink/renderer/modules/storage/storage_area.cc
index 9aa7c7a460e..61c5f607171 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_area.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_area.cc
@@ -25,7 +25,10 @@
#include "third_party/blink/renderer/modules/storage/storage_area.h"
+#include "base/feature_list.h"
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/public/common/features.h"
+#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_storage_area.h"
#include "third_party/blink/public/platform/web_storage_namespace.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -44,7 +47,25 @@ namespace blink {
StorageArea* StorageArea::Create(LocalFrame* frame,
std::unique_ptr<WebStorageArea> storage_area,
StorageType storage_type) {
- return new StorageArea(frame, std::move(storage_area), storage_type);
+ return MakeGarbageCollected<StorageArea>(frame, std::move(storage_area),
+ storage_type);
+}
+
+StorageArea* StorageArea::Create(LocalFrame* frame,
+ scoped_refptr<CachedStorageArea> storage_area,
+ StorageType storage_type) {
+ return MakeGarbageCollected<StorageArea>(frame, std::move(storage_area),
+ storage_type,
+ /* should_enqueue_events */ true);
+}
+
+StorageArea* StorageArea::CreateForInspectorAgent(
+ LocalFrame* frame,
+ scoped_refptr<CachedStorageArea> storage_area,
+ StorageType storage_type) {
+ return MakeGarbageCollected<StorageArea>(frame, std::move(storage_area),
+ storage_type,
+ /* should_enqueue_events */ false);
}
StorageArea::StorageArea(LocalFrame* frame,
@@ -52,16 +73,34 @@ StorageArea::StorageArea(LocalFrame* frame,
StorageType storage_type)
: ContextClient(frame),
storage_area_(std::move(storage_area)),
- storage_type_(storage_type) {
+ storage_type_(storage_type),
+ should_enqueue_events_(true) {
+ DCHECK(!base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage));
DCHECK(frame);
DCHECK(storage_area_);
}
+StorageArea::StorageArea(LocalFrame* frame,
+ scoped_refptr<CachedStorageArea> storage_area,
+ StorageType storage_type,
+ bool should_enqueue_events)
+ : ContextClient(frame),
+ cached_area_(std::move(storage_area)),
+ storage_type_(storage_type),
+ should_enqueue_events_(should_enqueue_events) {
+ CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage));
+ DCHECK(frame);
+ DCHECK(cached_area_);
+ cached_area_->RegisterSource(this);
+}
+
unsigned StorageArea::length(ExceptionState& exception_state) const {
if (!CanAccessStorage()) {
exception_state.ThrowSecurityError("access is denied for this document.");
return 0;
}
+ if (cached_area_)
+ return cached_area_->GetLength();
return storage_area_->length();
}
@@ -70,6 +109,8 @@ String StorageArea::key(unsigned index, ExceptionState& exception_state) const {
exception_state.ThrowSecurityError("access is denied for this document.");
return String();
}
+ if (cached_area_)
+ return cached_area_->GetKey(index);
bool did_decrease_iterator = false;
String result = storage_area_->Key(index, &did_decrease_iterator);
if (did_decrease_iterator)
@@ -83,6 +124,8 @@ String StorageArea::getItem(const String& key,
exception_state.ThrowSecurityError("access is denied for this document.");
return String();
}
+ if (cached_area_)
+ return cached_area_->GetItem(key);
return storage_area_->GetItem(key);
}
@@ -94,7 +137,12 @@ bool StorageArea::setItem(const String& key,
return true;
}
WebStorageArea::Result result = WebStorageArea::kResultOK;
- storage_area_->SetItem(key, value, GetFrame()->GetDocument()->Url(), result);
+ if (!cached_area_) {
+ storage_area_->SetItem(key, value, GetFrame()->GetDocument()->Url(),
+ result);
+ } else if (!cached_area_->SetItem(key, value, this)) {
+ result = WebStorageArea::kResultBlockedByQuota;
+ }
if (result != WebStorageArea::kResultOK) {
exception_state.ThrowDOMException(
DOMExceptionCode::kQuotaExceededError,
@@ -109,7 +157,10 @@ DeleteResult StorageArea::removeItem(const String& key,
exception_state.ThrowSecurityError("access is denied for this document.");
return kDeleteSuccess;
}
- storage_area_->RemoveItem(key, GetFrame()->GetDocument()->Url());
+ if (cached_area_)
+ cached_area_->RemoveItem(key, this);
+ else
+ storage_area_->RemoveItem(key, GetFrame()->GetDocument()->Url());
return kDeleteSuccess;
}
@@ -118,7 +169,10 @@ void StorageArea::clear(ExceptionState& exception_state) {
exception_state.ThrowSecurityError("access is denied for this document.");
return;
}
- storage_area_->Clear(GetFrame()->GetDocument()->Url());
+ if (cached_area_)
+ cached_area_->Clear(this);
+ else
+ storage_area_->Clear(GetFrame()->GetDocument()->Url());
}
bool StorageArea::Contains(const String& key,
@@ -127,6 +181,8 @@ bool StorageArea::Contains(const String& key,
exception_state.ThrowSecurityError("access is denied for this document.");
return false;
}
+ if (cached_area_)
+ return !cached_area_->GetItem(key).IsNull();
return !storage_area_->GetItem(key).IsNull();
}
@@ -174,7 +230,43 @@ bool StorageArea::CanAccessStorage() const {
return can_access_storage_cached_result_;
}
+KURL StorageArea::GetPageUrl() const {
+ LocalFrame* frame = GetFrame();
+ if (!frame)
+ return KURL();
+ return GetFrame()->GetDocument()->Url();
+}
+
+bool StorageArea::EnqueueStorageEvent(const String& key,
+ const String& old_value,
+ const String& new_value,
+ const String& url) {
+ if (!should_enqueue_events_)
+ return true;
+ if (!GetExecutionContext())
+ return false;
+ LocalFrame* frame = GetFrame();
+ if (!frame)
+ return true;
+ frame->DomWindow()->EnqueueWindowEvent(
+ *StorageEvent::Create(event_type_names::kStorage, key, old_value,
+ new_value, url, this),
+ TaskType::kDOMManipulation);
+ return true;
+}
+
+blink::WebScopedVirtualTimePauser StorageArea::CreateWebScopedVirtualTimePauser(
+ const char* name,
+ WebScopedVirtualTimePauser::VirtualTaskDuration duration) {
+ LocalFrame* frame = GetFrame();
+ if (!frame)
+ return blink::WebScopedVirtualTimePauser();
+ return frame->GetFrameScheduler()->CreateWebScopedVirtualTimePauser(name,
+ duration);
+}
+
namespace {
+// TODO(dmurph): Remove this after onion souping. crbug.com/781870
Page* FindPageWithSessionStorageNamespace(
const WebStorageNamespace& session_namespace) {
// Iterate over all pages that have a StorageNamespace supplement.
@@ -219,7 +311,7 @@ void StorageArea::DispatchLocalStorageEvent(
!IsEventSource(storage, source_area_instance)) {
// https://www.w3.org/TR/webstorage/#the-storage-event
local_frame->DomWindow()->EnqueueWindowEvent(
- *StorageEvent::Create(EventTypeNames::storage, key, old_value,
+ *StorageEvent::Create(event_type_names::kStorage, key, old_value,
new_value, page_url, storage),
TaskType::kDOMManipulation);
}
@@ -256,7 +348,7 @@ void StorageArea::DispatchSessionStorageEvent(
!IsEventSource(storage, source_area_instance)) {
// https://www.w3.org/TR/webstorage/#the-storage-event
local_frame->DomWindow()->EnqueueWindowEvent(
- *StorageEvent::Create(EventTypeNames::storage, key, old_value,
+ *StorageEvent::Create(event_type_names::kStorage, key, old_value,
new_value, page_url, storage),
TaskType::kDOMManipulation);
}
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_area.h b/chromium/third_party/blink/renderer/modules/storage/storage_area.h
index f7780afc6e3..c3de6fcb301 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_area.h
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_area.h
@@ -29,6 +29,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
+#include "third_party/blink/renderer/modules/storage/cached_storage_area.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
@@ -40,17 +41,39 @@ class LocalFrame;
class WebStorageArea;
class WebStorageNamespace;
-class StorageArea final : public ScriptWrappable, public ContextClient {
+class StorageArea final : public ScriptWrappable,
+ public ContextClient,
+ public CachedStorageArea::Source {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(StorageArea);
public:
enum class StorageType { kLocalStorage, kSessionStorage };
+ // TODO(dmurph): Remove this after onion souping. crbug.com/781870
static StorageArea* Create(LocalFrame*,
std::unique_ptr<WebStorageArea>,
StorageType);
+ // Creates the onion-souped version.
+ static StorageArea* Create(LocalFrame*,
+ scoped_refptr<CachedStorageArea>,
+ StorageType);
+
+ // This storage area doesn't enqueue any events. This avoids duplicate event
+ // dispatch when an inspector agent is present.
+ static StorageArea* CreateForInspectorAgent(LocalFrame*,
+ scoped_refptr<CachedStorageArea>,
+ StorageType);
+
+ // TODO(dmurph): Remove this after onion souping. crbug.com/781870
+ StorageArea(LocalFrame*, std::unique_ptr<WebStorageArea>, StorageType);
+
+ StorageArea(LocalFrame*,
+ scoped_refptr<CachedStorageArea>,
+ StorageType,
+ bool should_enqueue_events);
+
unsigned length(ExceptionState&) const;
String key(unsigned index, ExceptionState&) const;
String getItem(const String& key, ExceptionState&) const;
@@ -68,12 +91,25 @@ class StorageArea final : public ScriptWrappable, public ContextClient {
void Trace(blink::Visitor*) override;
+ // CachedStorageArea::Source:
+ KURL GetPageUrl() const override;
+ bool EnqueueStorageEvent(const String& key,
+ const String& old_value,
+ const String& new_value,
+ const String& url) override;
+
+ blink::WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser(
+ const char* name,
+ WebScopedVirtualTimePauser::VirtualTaskDuration duration) override;
+
+ // TODO(dmurph): Remove this after onion souping. crbug.com/781870
static void DispatchLocalStorageEvent(const String& key,
const String& old_value,
const String& new_value,
const SecurityOrigin*,
const KURL& page_url,
WebStorageArea* source_area_instance);
+ // TODO(dmurph): Remove this after onion souping. crbug.com/781870
static void DispatchSessionStorageEvent(const String& key,
const String& old_value,
const String& new_value,
@@ -83,13 +119,15 @@ class StorageArea final : public ScriptWrappable, public ContextClient {
WebStorageArea* source_area_instance);
private:
- StorageArea(LocalFrame*, std::unique_ptr<WebStorageArea>, StorageType);
-
+ // TODO(dmurph): Remove this after onion souping. crbug.com/781870
std::unique_ptr<WebStorageArea> storage_area_;
+
+ scoped_refptr<CachedStorageArea> cached_area_;
StorageType storage_type_;
+ const bool should_enqueue_events_;
mutable bool did_check_can_access_storage_ = false;
- mutable bool can_access_storage_cached_result_;
+ mutable bool can_access_storage_cached_result_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_controller.cc b/chromium/third_party/blink/renderer/modules/storage/storage_controller.cc
index 855e3ba7254..185d8f576a4 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_controller.cc
@@ -5,13 +5,13 @@
#include "third_party/blink/renderer/modules/storage/storage_controller.h"
#include "base/feature_list.h"
-#include "base/sys_info.h"
+#include "base/system/sys_info.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/interface_provider.h"
#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_storage_area.h"
#include "third_party/blink/public/platform/web_storage_namespace.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/modules/storage/cached_storage_area.h"
#include "third_party/blink/renderer/modules/storage/storage_namespace.h"
@@ -23,14 +23,6 @@
namespace blink {
namespace {
-#define STATIC_ASSERT_MATCHING_ENUM(enum_name1, enum_name2) \
- static_assert(static_cast<int>(enum_name1) == static_cast<int>(enum_name2), \
- "mismatching enums: " #enum_name1)
-STATIC_ASSERT_MATCHING_ENUM(StorageArea::StorageType::kLocalStorage,
- ContentSettingsClient::StorageType::kLocal);
-STATIC_ASSERT_MATCHING_ENUM(StorageArea::StorageType::kSessionStorage,
- ContentSettingsClient::StorageType::kSession);
-
const size_t kStorageControllerTotalCacheLimitInBytesLowEnd = 1 * 1024 * 1024;
const size_t kStorageControllerTotalCacheLimitInBytes = 5 * 1024 * 1024;
@@ -44,22 +36,23 @@ mojom::blink::StoragePartitionServicePtr GetAndCreateStorageInterface() {
// static
StorageController* StorageController::GetInstance() {
- DEFINE_STATIC_LOCAL(
- StorageController, gCachedStorageAreaController,
- (Platform::Current()->MainThread()->Scheduler()->IPCTaskRunner(),
- GetAndCreateStorageInterface(),
- base::SysInfo::IsLowEndDevice()
- ? kStorageControllerTotalCacheLimitInBytesLowEnd
- : kStorageControllerTotalCacheLimitInBytes));
+ DEFINE_STATIC_LOCAL(StorageController, gCachedStorageAreaController,
+ (Thread::MainThread()->Scheduler()->IPCTaskRunner(),
+ GetAndCreateStorageInterface(),
+ base::SysInfo::IsLowEndDevice()
+ ? kStorageControllerTotalCacheLimitInBytesLowEnd
+ : kStorageControllerTotalCacheLimitInBytes));
return &gCachedStorageAreaController;
}
// static
bool StorageController::CanAccessStorageArea(LocalFrame* frame,
StorageArea::StorageType type) {
- DCHECK(frame->GetContentSettingsClient());
- return frame->GetContentSettingsClient()->AllowStorage(
- static_cast<ContentSettingsClient::StorageType>(type));
+ if (auto* settings_client = frame->GetContentSettingsClient()) {
+ return settings_client->AllowStorage(
+ type == StorageArea::StorageType::kLocalStorage);
+ }
+ return true;
}
StorageController::StorageController(
@@ -67,7 +60,8 @@ StorageController::StorageController(
mojom::blink::StoragePartitionServicePtr storage_partition_service,
size_t total_cache_limit)
: ipc_runner_(std::move(ipc_runner)),
- namespaces_(new HeapHashMap<String, WeakMember<StorageNamespace>>()),
+ namespaces_(MakeGarbageCollected<
+ HeapHashMap<String, WeakMember<StorageNamespace>>>()),
total_cache_limit_(total_cache_limit),
storage_partition_service_(std::move(storage_partition_service)) {}
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_controller_test.cc b/chromium/third_party/blink/renderer/modules/storage/storage_controller_test.cc
index ff0d8a140a4..1d9ad4d9a7b 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_controller_test.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_controller_test.cc
@@ -4,18 +4,19 @@
#include "third_party/blink/renderer/modules/storage/storage_controller.h"
+#include "base/run_loop.h"
#include "base/task/post_task.h"
#include "base/test/scoped_feature_list.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/renderer/modules/storage/storage_namespace.h"
#include "third_party/blink/renderer/modules/storage/testing/fake_area_source.h"
#include "third_party/blink/renderer/modules/storage/testing/mock_storage_area.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/uuid.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -54,9 +55,8 @@ TEST(StorageControllerTest, CacheLimit) {
const String kKey("key");
const String kValue("value");
const KURL kPageUrl("http://dom_storage/page");
- Persistent<FakeAreaSource> source_area = new FakeAreaSource(kPageUrl);
-
- blink::scheduler::FakeRendererScheduler renderer_scheduler;
+ Persistent<FakeAreaSource> source_area =
+ MakeGarbageCollected<FakeAreaSource>(kPageUrl);
mojom::blink::StoragePartitionServicePtr storage_partition_service_ptr;
PostCrossThreadTask(
@@ -69,7 +69,7 @@ TEST(StorageControllerTest, CacheLimit) {
},
WTF::Passed(MakeRequest(&storage_partition_service_ptr))));
- StorageController controller(renderer_scheduler.IPCTaskRunner(),
+ StorageController controller(scheduler::GetSingleThreadTaskRunnerForTesting(),
std::move(storage_partition_service_ptr),
kTestCacheLimit);
@@ -110,9 +110,9 @@ TEST(StorageControllerTest, CacheLimitSessionStorage) {
const String kValue("value");
const KURL kPageUrl("http://dom_storage/page");
- Persistent<FakeAreaSource> source_area = new FakeAreaSource(kPageUrl);
+ Persistent<FakeAreaSource> source_area =
+ MakeGarbageCollected<FakeAreaSource>(kPageUrl);
- blink::scheduler::FakeRendererScheduler renderer_scheduler;
auto task_runner = base::CreateSequencedTaskRunnerWithTraits({});
auto mock_storage_partition_service =
@@ -131,9 +131,8 @@ TEST(StorageControllerTest, CacheLimitSessionStorage) {
},
WTF::Passed(std::move(mock_storage_partition_service)),
WTF::Passed(MakeRequest(&storage_partition_service_ptr))));
- StorageController controller(renderer_scheduler.IPCTaskRunner(),
- std::move(storage_partition_service_ptr),
- kTestCacheLimit);
+ StorageController controller(
+ nullptr, std::move(storage_partition_service_ptr), kTestCacheLimit);
StorageNamespace* ns1 = controller.CreateSessionStorageNamespace(kNamespace1);
StorageNamespace* ns2 = controller.CreateSessionStorageNamespace(kNamespace2);
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_event.cc b/chromium/third_party/blink/renderer/modules/storage/storage_event.cc
index 8b2c8c07567..d0f475c1574 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_event.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_event.cc
@@ -32,7 +32,7 @@
namespace blink {
StorageEvent* StorageEvent::Create() {
- return new StorageEvent;
+ return MakeGarbageCollected<StorageEvent>();
}
StorageEvent::StorageEvent() = default;
@@ -45,12 +45,13 @@ StorageEvent* StorageEvent::Create(const AtomicString& type,
const String& new_value,
const String& url,
StorageArea* storage_area) {
- return new StorageEvent(type, key, old_value, new_value, url, storage_area);
+ return MakeGarbageCollected<StorageEvent>(type, key, old_value, new_value,
+ url, storage_area);
}
StorageEvent* StorageEvent::Create(const AtomicString& type,
- const StorageEventInit& initializer) {
- return new StorageEvent(type, initializer);
+ const StorageEventInit* initializer) {
+ return MakeGarbageCollected<StorageEvent>(type, initializer);
}
StorageEvent::StorageEvent(const AtomicString& type,
@@ -67,18 +68,18 @@ StorageEvent::StorageEvent(const AtomicString& type,
storage_area_(storage_area) {}
StorageEvent::StorageEvent(const AtomicString& type,
- const StorageEventInit& initializer)
+ const StorageEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasKey())
- key_ = initializer.key();
- if (initializer.hasOldValue())
- old_value_ = initializer.oldValue();
- if (initializer.hasNewValue())
- new_value_ = initializer.newValue();
- if (initializer.hasURL())
- url_ = initializer.url();
- if (initializer.hasStorageArea())
- storage_area_ = initializer.storageArea();
+ if (initializer->hasKey())
+ key_ = initializer->key();
+ if (initializer->hasOldValue())
+ old_value_ = initializer->oldValue();
+ if (initializer->hasNewValue())
+ new_value_ = initializer->newValue();
+ if (initializer->hasURL())
+ url_ = initializer->url();
+ if (initializer->hasStorageArea())
+ storage_area_ = initializer->storageArea();
}
void StorageEvent::initStorageEvent(const AtomicString& type,
@@ -102,7 +103,7 @@ void StorageEvent::initStorageEvent(const AtomicString& type,
}
const AtomicString& StorageEvent::InterfaceName() const {
- return EventNames::StorageEvent;
+ return event_interface_names::kStorageEvent;
}
void StorageEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_event.h b/chromium/third_party/blink/renderer/modules/storage/storage_event.h
index 361c22fe344..8d58da048d0 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_event.h
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_event.h
@@ -46,7 +46,16 @@ class StorageEvent final : public Event {
const String& new_value,
const String& url,
StorageArea* storage_area);
- static StorageEvent* Create(const AtomicString&, const StorageEventInit&);
+ static StorageEvent* Create(const AtomicString&, const StorageEventInit*);
+
+ StorageEvent();
+ StorageEvent(const AtomicString& type,
+ const String& key,
+ const String& old_value,
+ const String& new_value,
+ const String& url,
+ StorageArea* storage_area);
+ StorageEvent(const AtomicString&, const StorageEventInit*);
~StorageEvent() override;
const String& key() const { return key_; }
@@ -75,15 +84,6 @@ class StorageEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- StorageEvent();
- StorageEvent(const AtomicString& type,
- const String& key,
- const String& old_value,
- const String& new_value,
- const String& url,
- StorageArea* storage_area);
- StorageEvent(const AtomicString&, const StorageEventInit&);
-
String key_;
String old_value_;
String new_value_;
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_namespace.cc b/chromium/third_party/blink/renderer/modules/storage/storage_namespace.cc
index fdc44083b4c..3dc641a7298 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_namespace.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_namespace.cc
@@ -131,6 +131,7 @@ scoped_refptr<CachedStorageArea> StorageNamespace::GetCachedArea(
}
void StorageNamespace::CloneTo(const String& target) {
+ CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage));
DCHECK(IsSessionStorage()) << "Cannot clone a local storage namespace.";
EnsureConnected();
namespace_->Clone(target);
diff --git a/chromium/third_party/blink/renderer/modules/storage/storage_namespace_test.cc b/chromium/third_party/blink/renderer/modules/storage/storage_namespace_test.cc
index ca24c518276..31d1b306b08 100644
--- a/chromium/third_party/blink/renderer/modules/storage/storage_namespace_test.cc
+++ b/chromium/third_party/blink/renderer/modules/storage/storage_namespace_test.cc
@@ -10,11 +10,11 @@
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/public/platform/scheduler/test/fake_renderer_scheduler.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/renderer/modules/storage/testing/fake_area_source.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/uuid.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
namespace {
@@ -53,9 +53,8 @@ TEST_F(StorageNamespaceTest, BasicStorageAreas) {
const String kValue("value");
const String kSessionStorageNamespace("abcd");
const KURL kPageUrl("http://dom_storage/page");
- Persistent<FakeAreaSource> source_area = new FakeAreaSource(kPageUrl);
-
- blink::scheduler::FakeRendererScheduler renderer_scheduler;
+ Persistent<FakeAreaSource> source_area =
+ MakeGarbageCollected<FakeAreaSource>(kPageUrl);
mojom::blink::StoragePartitionServicePtr storage_partition_service_ptr;
PostCrossThreadTask(
@@ -68,7 +67,7 @@ TEST_F(StorageNamespaceTest, BasicStorageAreas) {
},
WTF::Passed(MakeRequest(&storage_partition_service_ptr))));
- StorageController controller(renderer_scheduler.IPCTaskRunner(),
+ StorageController controller(scheduler::GetSingleThreadTaskRunnerForTesting(),
std::move(storage_partition_service_ptr),
kTestCacheLimit);
StorageNamespace* localStorage = new StorageNamespace(&controller);
diff --git a/chromium/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc b/chromium/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc
index e17c7d029ef..7438528c735 100644
--- a/chromium/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc
+++ b/chromium/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc
@@ -57,7 +57,7 @@ void TimeZoneMonitorClient::OnTimeZoneChange(const String& time_zone_info) {
DCHECK(IsMainThread());
if (!time_zone_info.IsEmpty()) {
- DCHECK(time_zone_info.ContainsOnlyASCII());
+ DCHECK(time_zone_info.ContainsOnlyASCIIOrEmpty());
icu::TimeZone* zone = icu::TimeZone::createTimeZone(
icu::UnicodeString(time_zone_info.Ascii().data(), -1, US_INV));
icu::TimeZone::adoptDefault(zone);
diff --git a/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.cc b/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.cc
index 181bac4a60b..f91fd837053 100644
--- a/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.cc
+++ b/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.cc
@@ -45,7 +45,7 @@ NavigatorVibration& NavigatorVibration::From(Navigator& navigator) {
NavigatorVibration* navigator_vibration =
Supplement<Navigator>::From<NavigatorVibration>(navigator);
if (!navigator_vibration) {
- navigator_vibration = new NavigatorVibration(navigator);
+ navigator_vibration = MakeGarbageCollected<NavigatorVibration>(navigator);
ProvideTo(navigator, navigator_vibration);
}
return *navigator_vibration;
@@ -131,7 +131,7 @@ void NavigatorVibration::CollectHistogramMetrics(const LocalFrame& frame) {
VibrationController* NavigatorVibration::Controller(LocalFrame& frame) {
if (!controller_)
- controller_ = new VibrationController(frame);
+ controller_ = MakeGarbageCollected<VibrationController>(frame);
return controller_.Get();
}
diff --git a/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.h b/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.h
index 3ea1cab910a..81cbeda70b8 100644
--- a/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.h
+++ b/chromium/third_party/blink/renderer/modules/vibration/navigator_vibration.h
@@ -57,6 +57,7 @@ class MODULES_EXPORT NavigatorVibration final
using VibrationPattern = Vector<unsigned>;
+ explicit NavigatorVibration(Navigator&);
virtual ~NavigatorVibration();
static NavigatorVibration& From(Navigator&);
@@ -69,8 +70,6 @@ class MODULES_EXPORT NavigatorVibration final
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorVibration(Navigator&);
-
// Inherited from ContextLifecycleObserver.
void ContextDestroyed(ExecutionContext*) override;
diff --git a/chromium/third_party/blink/renderer/modules/vibration/vibration_controller.cc b/chromium/third_party/blink/renderer/modules/vibration/vibration_controller.cc
index 20965e8dca3..7b4448c08ac 100644
--- a/chromium/third_party/blink/renderer/modules/vibration/vibration_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/vibration/vibration_controller.cc
@@ -38,7 +38,7 @@ const unsigned kVibrationDurationMsMax = 10000;
blink::VibrationController::VibrationPattern sanitizeVibrationPatternInternal(
const blink::VibrationController::VibrationPattern& pattern) {
blink::VibrationController::VibrationPattern sanitized = pattern;
- size_t length = sanitized.size();
+ wtf_size_t length = sanitized.size();
// If the pattern is too long then truncate it.
if (length > kVibrationPatternLengthMax) {
@@ -47,7 +47,7 @@ blink::VibrationController::VibrationPattern sanitizeVibrationPatternInternal(
}
// If any pattern entry is too long then truncate it.
- for (size_t i = 0; i < length; ++i) {
+ for (wtf_size_t i = 0; i < length; ++i) {
if (sanitized[i] > kVibrationDurationMsMax)
sanitized[i] = kVibrationDurationMsMax;
}
diff --git a/chromium/third_party/blink/renderer/modules/vr/PRESUBMIT.py b/chromium/third_party/blink/renderer/modules/vr/PRESUBMIT.py
deleted file mode 100644
index 19d6c2c67bc..00000000000
--- a/chromium/third_party/blink/renderer/modules/vr/PRESUBMIT.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (c) 2018 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Top-level presubmit script for third_party/blink/renderer/modules/vr.
-
-See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
-for more details about the presubmit API built into depot_tools.
-"""
-
-
-def PostUploadHook(cl, change, output_api): # pylint: disable=C0103,W0613
- """git cl upload will call this hook after the issue is created/modified.
-
- This hook modifies the CL description in order to run extra GPU
- tests (in particular, WebXR and WebVR browser tests) in addition
- to the regular CQ try bots. This test suite is too large to run
- against all Chromium commits, but should be run against changes
- likely to affect these tests.
- """
- return output_api.EnsureCQIncludeTrybotsAreAdded(
- cl,
- ['luci.chromium.try:win_optional_gpu_tests_rel'],
- 'Automatically added optional GPU tests to run on CQ.')
diff --git a/chromium/third_party/blink/renderer/modules/vr/navigator_vr.cc b/chromium/third_party/blink/renderer/modules/vr/navigator_vr.cc
index 25c1178ad50..fda8db7874c 100644
--- a/chromium/third_party/blink/renderer/modules/vr/navigator_vr.cc
+++ b/chromium/third_party/blink/renderer/modules/vr/navigator_vr.cc
@@ -51,7 +51,7 @@ NavigatorVR* NavigatorVR::From(Document& document) {
NavigatorVR& NavigatorVR::From(Navigator& navigator) {
NavigatorVR* supplement = Supplement<Navigator>::From<NavigatorVR>(navigator);
if (!supplement) {
- supplement = new NavigatorVR(navigator);
+ supplement = MakeGarbageCollected<NavigatorVR>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -179,7 +179,7 @@ VRController* NavigatorVR::Controller() {
return nullptr;
if (!controller_) {
- controller_ = new VRController(this);
+ controller_ = MakeGarbageCollected<VRController>(this);
controller_->SetListeningForActivate(focused_ && listening_for_activate_);
controller_->FocusChanged();
}
@@ -260,10 +260,10 @@ void NavigatorVR::DidAddEventListener(LocalDOMWindow* window,
if (xr_)
return;
- if (event_type == EventTypeNames::vrdisplayactivate) {
+ if (event_type == event_type_names::kVrdisplayactivate) {
listening_for_activate_ = true;
Controller()->SetListeningForActivate(focused_);
- } else if (event_type == EventTypeNames::vrdisplayconnect) {
+ } else if (event_type == event_type_names::kVrdisplayconnect) {
// If the page is listening for connection events make sure we've created a
// controller so that we'll be notified of new devices.
Controller();
@@ -276,8 +276,8 @@ void NavigatorVR::DidRemoveEventListener(LocalDOMWindow* window,
if (xr_)
return;
- if (event_type == EventTypeNames::vrdisplayactivate &&
- !window->HasEventListeners(EventTypeNames::vrdisplayactivate)) {
+ if (event_type == event_type_names::kVrdisplayactivate &&
+ !window->HasEventListeners(event_type_names::kVrdisplayactivate)) {
listening_for_activate_ = false;
Controller()->SetListeningForActivate(false);
}
diff --git a/chromium/third_party/blink/renderer/modules/vr/navigator_vr.h b/chromium/third_party/blink/renderer/modules/vr/navigator_vr.h
index 9841513c48c..58cf4e22b96 100644
--- a/chromium/third_party/blink/renderer/modules/vr/navigator_vr.h
+++ b/chromium/third_party/blink/renderer/modules/vr/navigator_vr.h
@@ -36,6 +36,8 @@ class MODULES_EXPORT NavigatorVR final
static NavigatorVR* From(Document&);
static NavigatorVR& From(Navigator&);
+
+ explicit NavigatorVR(Navigator&);
~NavigatorVR() override;
// XR API
@@ -77,8 +79,6 @@ class MODULES_EXPORT NavigatorVR final
friend class VRDisplay;
friend class VRGetDevicesCallback;
- explicit NavigatorVR(Navigator&);
-
void FireVRDisplayPresentChange(VRDisplay*);
Member<XR> xr_;
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_controller.cc b/chromium/third_party/blink/renderer/modules/vr/vr_controller.cc
index c726001ee72..27cf491ed64 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_controller.cc
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_controller.cc
@@ -87,7 +87,7 @@ void VRController::OnRequestDeviceReturned(
device->GetImmersiveVRDisplayInfo(WTF::Bind(
&VRController::OnImmersiveDisplayInfoReturned, WrapPersistent(this)));
- display_ = new VRDisplay(navigator_vr_, std::move(device));
+ display_ = MakeGarbageCollected<VRDisplay>(navigator_vr_, std::move(device));
if (pending_listening_for_activate_) {
SetListeningForActivate(pending_listening_for_activate_);
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_display.cc b/chromium/third_party/blink/renderer/modules/vr/vr_display.cc
index 17ab044676d..850e5feb206 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_display.cc
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_display.cc
@@ -95,10 +95,11 @@ class VRDisplayFrameRequestCallback
SessionClientBinding::SessionClientBinding(
VRDisplay* display,
- bool is_immersive,
+ SessionClientBinding::SessionBindingType immersive,
device::mojom::blink::XRSessionClientRequest request)
: display_(display),
- is_immersive_(is_immersive),
+ is_immersive_(immersive ==
+ SessionClientBinding::SessionBindingType::kImmersive),
client_binding_(this, std::move(request)){};
SessionClientBinding::~SessionClientBinding() = default;
@@ -128,7 +129,7 @@ VRDisplay::VRDisplay(NavigatorVR* navigator_vr,
device::mojom::blink::XRDevicePtr device)
: PausableObject(navigator_vr->GetDocument()),
navigator_vr_(navigator_vr),
- capabilities_(new VRDisplayCapabilities()),
+ capabilities_(MakeGarbageCollected<VRDisplayCapabilities>()),
device_ptr_(std::move(device)),
display_client_binding_(this) {
PauseIfNeeded(); // Initialize SuspendabaleObject.
@@ -179,9 +180,9 @@ void VRDisplay::Update(const device::mojom::blink::VRDisplayInfoPtr& display) {
DCHECK_GT(display->leftEye->renderWidth, 0u);
is_valid = true;
- eye_parameters_left_ = new VREyeParameters(
+ eye_parameters_left_ = MakeGarbageCollected<VREyeParameters>(
display->leftEye, display->webvr_default_framebuffer_scale);
- eye_parameters_right_ = new VREyeParameters(
+ eye_parameters_right_ = MakeGarbageCollected<VREyeParameters>(
display->rightEye, display->webvr_default_framebuffer_scale);
}
@@ -193,7 +194,7 @@ void VRDisplay::Update(const device::mojom::blink::VRDisplayInfoPtr& display) {
if (!display->stageParameters.is_null()) {
if (!stage_parameters_)
- stage_parameters_ = new VRStageParameters();
+ stage_parameters_ = MakeGarbageCollected<VRStageParameters>();
stage_parameters_->Update(display->stageParameters);
} else {
stage_parameters_ = nullptr;
@@ -331,7 +332,7 @@ void VRDisplay::OnBlur(bool is_immersive) {
DVLOG(1) << __FUNCTION__;
display_blurred_ = true;
navigator_vr_->EnqueueVREvent(
- VRDisplayEvent::Create(EventTypeNames::vrdisplayblur, this, ""));
+ VRDisplayEvent::Create(event_type_names::kVrdisplayblur, this, ""));
}
void VRDisplay::OnFocus(bool is_immersive) {
@@ -343,7 +344,7 @@ void VRDisplay::OnFocus(bool is_immersive) {
RequestVSync();
navigator_vr_->EnqueueVREvent(
- VRDisplayEvent::Create(EventTypeNames::vrdisplayfocus, this, ""));
+ VRDisplayEvent::Create(event_type_names::kVrdisplayfocus, this, ""));
}
void ReportPresentationResult(PresentationResult result) {
@@ -357,8 +358,9 @@ void ReportPresentationResult(PresentationResult result) {
vr_presentation_result_histogram.Count(static_cast<int>(result));
}
-ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
- const HeapVector<VRLayerInit>& layers) {
+ScriptPromise VRDisplay::requestPresent(
+ ScriptState* script_state,
+ const HeapVector<Member<VRLayerInit>>& layers) {
DVLOG(1) << __FUNCTION__;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
UseCounter::Count(execution_context, WebFeature::kVRRequestPresent);
@@ -426,7 +428,7 @@ ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
// If what we were given has an invalid source, need to exit fullscreen with
// previous, valid source, so delay m_layer reassignment
- if (layers[0].source().IsNull()) {
+ if (layers[0]->source().IsNull()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
DOMExceptionCode::kInvalidStateError, "Invalid layer source.");
@@ -437,13 +439,13 @@ ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
layer_ = layers[0];
CanvasRenderingContext* rendering_context;
- if (layer_.source().IsHTMLCanvasElement()) {
+ if (layer_->source().IsHTMLCanvasElement()) {
rendering_context =
- layer_.source().GetAsHTMLCanvasElement()->RenderingContext();
+ layer_->source().GetAsHTMLCanvasElement()->RenderingContext();
} else {
- DCHECK(layer_.source().IsOffscreenCanvas());
+ DCHECK(layer_->source().IsOffscreenCanvas());
rendering_context =
- layer_.source().GetAsOffscreenCanvas()->RenderingContext();
+ layer_->source().GetAsOffscreenCanvas()->RenderingContext();
}
if (!rendering_context || !rendering_context->Is3d()) {
@@ -461,8 +463,9 @@ ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
rendering_context_ = ToWebGLRenderingContextBase(rendering_context);
context_gl_ = rendering_context_->ContextGL();
- if ((layer_.leftBounds().size() != 0 && layer_.leftBounds().size() != 4) ||
- (layer_.rightBounds().size() != 0 && layer_.rightBounds().size() != 4)) {
+ if ((layer_->leftBounds().size() != 0 && layer_->leftBounds().size() != 4) ||
+ (layer_->rightBounds().size() != 0 &&
+ layer_->rightBounds().size() != 4)) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
DOMExceptionCode::kInvalidStateError,
@@ -472,7 +475,7 @@ ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
return promise;
}
- for (float value : layer_.leftBounds()) {
+ for (float value : layer_->leftBounds()) {
if (std::isnan(value)) {
ForceExitPresent();
DOMException* exception =
@@ -484,7 +487,7 @@ ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
}
}
- for (float value : layer_.rightBounds()) {
+ for (float value : layer_->rightBounds()) {
if (std::isnan(value)) {
ForceExitPresent();
DOMException* exception =
@@ -557,7 +560,7 @@ void VRDisplay::OnRequestImmersiveSessionReturned(
WTF::Bind(&VRDisplay::OnPresentationProviderConnectionError,
WrapWeakPersistent(this)));
- frame_transport_ = new XRFrameTransport();
+ frame_transport_ = MakeGarbageCollected<XRFrameTransport>();
frame_transport_->BindSubmitFrameClient(
std::move(session->submit_frame_sink->client_request));
frame_transport_->SetTransportOptions(
@@ -565,8 +568,9 @@ void VRDisplay::OnRequestImmersiveSessionReturned(
if (immersive_client_binding_)
immersive_client_binding_->Close();
- immersive_client_binding_ = new SessionClientBinding(
- this, false, std::move(session->client_request));
+ immersive_client_binding_ = MakeGarbageCollected<SessionClientBinding>(
+ this, SessionClientBinding::SessionBindingType::kImmersive,
+ std::move(session->client_request));
Update(std::move(session->display_info));
@@ -590,8 +594,9 @@ void VRDisplay::OnNonImmersiveSessionRequestReturned(
return;
}
non_immersive_provider_.Bind(std::move(session->data_provider));
- non_immersive_client_binding_ =
- new SessionClientBinding(this, false, std::move(session->client_request));
+ non_immersive_client_binding_ = MakeGarbageCollected<SessionClientBinding>(
+ this, SessionClientBinding::SessionBindingType::kNonImmersive,
+ std::move(session->client_request));
RequestVSync();
}
@@ -633,14 +638,14 @@ void VRDisplay::BeginPresent() {
"VRDisplay presentation path not configured.");
}
- if (layer_.source().IsOffscreenCanvas()) {
+ if (layer_->source().IsOffscreenCanvas()) {
// TODO(junov, crbug.com/695497): Implement OffscreenCanvas presentation
exception =
DOMException::Create(DOMExceptionCode::kInvalidStateError,
"OffscreenCanvas presentation not implemented.");
} else {
// A canvas must be either Offscreen or plain HTMLCanvas.
- DCHECK(layer_.source().IsHTMLCanvasElement());
+ DCHECK(layer_->source().IsHTMLCanvasElement());
}
if (exception) {
@@ -706,14 +711,14 @@ void VRDisplay::UpdateLayerBounds() {
return;
// Left eye defaults
- if (layer_.leftBounds().size() != 4)
- layer_.setLeftBounds({0.0f, 0.0f, 0.5f, 1.0f});
+ if (layer_->leftBounds().size() != 4)
+ layer_->setLeftBounds({0.0f, 0.0f, 0.5f, 1.0f});
// Right eye defaults
- if (layer_.rightBounds().size() != 4)
- layer_.setRightBounds({0.5f, 0.0f, 0.5f, 1.0f});
+ if (layer_->rightBounds().size() != 4)
+ layer_->setRightBounds({0.5f, 0.0f, 0.5f, 1.0f});
- const Vector<float>& left = layer_.leftBounds();
- const Vector<float>& right = layer_.rightBounds();
+ const Vector<float>& left = layer_->leftBounds();
+ const Vector<float>& right = layer_->rightBounds();
vr_presentation_provider_->UpdateLayerBounds(
vr_frame_id_, WebFloatRect(left[0], left[1], left[2], left[3]),
@@ -721,8 +726,8 @@ void VRDisplay::UpdateLayerBounds() {
WebSize(source_width_, source_height_));
}
-HeapVector<VRLayerInit> VRDisplay::getLayers() {
- HeapVector<VRLayerInit> layers;
+HeapVector<Member<VRLayerInit>> VRDisplay::getLayers() {
+ HeapVector<Member<VRLayerInit>> layers;
if (is_presenting_) {
layers.push_back(layer_);
@@ -864,8 +869,8 @@ void VRDisplay::OnPresentChange() {
DVLOG(1) << __FUNCTION__ << ": device not valid, not sending event";
return;
}
- navigator_vr_->EnqueueVREvent(
- VRDisplayEvent::Create(EventTypeNames::vrdisplaypresentchange, this, ""));
+ navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
+ event_type_names::kVrdisplaypresentchange, this, ""));
}
void VRDisplay::OnChanged(device::mojom::blink::VRDisplayInfoPtr display,
@@ -888,18 +893,18 @@ void VRDisplay::OnExitPresent(bool is_immersive) {
void VRDisplay::OnConnected() {
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
- EventTypeNames::vrdisplayconnect, this, "connect"));
+ event_type_names::kVrdisplayconnect, this, "connect"));
}
void VRDisplay::OnDisconnected() {
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
- EventTypeNames::vrdisplaydisconnect, this, "disconnect"));
+ event_type_names::kVrdisplaydisconnect, this, "disconnect"));
}
void VRDisplay::StopPresenting() {
if (is_presenting_) {
if (!capabilities_->hasExternalDisplay()) {
- if (layer_.source().IsHTMLCanvasElement()) {
+ if (layer_->source().IsHTMLCanvasElement()) {
// TODO(klausw,crbug.com/698923): If compositor updates are
// suppressed, restore them here.
} else {
@@ -939,15 +944,15 @@ void VRDisplay::OnActivate(device::mojom::blink::VRDisplayEventReason reason,
base::AutoReset<bool> in_activate(&in_display_activate_, true);
- navigator_vr_->DispatchVREvent(
- VRDisplayEvent::Create(EventTypeNames::vrdisplayactivate, this, reason));
+ navigator_vr_->DispatchVREvent(VRDisplayEvent::Create(
+ event_type_names::kVrdisplayactivate, this, reason));
std::move(on_handled).Run(!pending_present_request_ && !is_presenting_);
}
void VRDisplay::OnDeactivate(
device::mojom::blink::VRDisplayEventReason reason) {
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
- EventTypeNames::vrdisplaydeactivate, this, reason));
+ event_type_names::kVrdisplaydeactivate, this, reason));
}
void VRDisplay::ProcessScheduledWindowAnimations(TimeTicks timestamp) {
@@ -1149,7 +1154,7 @@ ExecutionContext* VRDisplay::GetExecutionContext() const {
}
const AtomicString& VRDisplay::InterfaceName() const {
- return EventTargetNames::VRDisplay;
+ return event_target_names::kVRDisplay;
}
void VRDisplay::ContextDestroyed(ExecutionContext* context) {
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_display.h b/chromium/third_party/blink/renderer/modules/vr/vr_display.h
index 429ac4e6f69..03a7faa80ea 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_display.h
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_display.h
@@ -45,8 +45,13 @@ class SessionClientBinding
: public GarbageCollectedFinalized<SessionClientBinding>,
public device::mojom::blink::XRSessionClient {
public:
+ enum class SessionBindingType {
+ kImmersive = 0,
+ kNonImmersive = 1,
+ };
+
SessionClientBinding(VRDisplay* display,
- bool is_immersive,
+ SessionBindingType immersive,
device::mojom::blink::XRSessionClientRequest request);
~SessionClientBinding() override;
void Close();
@@ -77,6 +82,7 @@ class VRDisplay final : public EventTargetWithInlineData,
USING_PRE_FINALIZER(VRDisplay, Dispose);
public:
+ VRDisplay(NavigatorVR*, device::mojom::blink::XRDevicePtr);
~VRDisplay() override;
// We hand out at most one VRDisplay, so hardcode displayId to 1.
@@ -104,10 +110,10 @@ class VRDisplay final : public EventTargetWithInlineData,
void cancelAnimationFrame(int id);
ScriptPromise requestPresent(ScriptState*,
- const HeapVector<VRLayerInit>& layers);
+ const HeapVector<Member<VRLayerInit>>& layers);
ScriptPromise exitPresent(ScriptState*);
- HeapVector<VRLayerInit> getLayers();
+ HeapVector<Member<VRLayerInit>> getLayers();
void submitFrame();
@@ -143,8 +149,6 @@ class VRDisplay final : public EventTargetWithInlineData,
protected:
friend class VRController;
- VRDisplay(NavigatorVR*, device::mojom::blink::XRDevicePtr);
-
void Update(const device::mojom::blink::VRDisplayInfoPtr&);
void UpdatePose();
@@ -214,7 +218,7 @@ class VRDisplay final : public EventTargetWithInlineData,
// VR compositor so that it knows which poses to use, when to apply bounds
// updates, etc.
int16_t vr_frame_id_ = -1;
- VRLayerInit layer_;
+ Member<VRLayerInit> layer_;
double depth_near_ = 0.01;
double depth_far_ = 10000.0;
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_display_event.cc b/chromium/third_party/blink/renderer/modules/vr/vr_display_event.cc
index b00d727d858..ec24267c43a 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_display_event.cc
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_display_event.cc
@@ -31,8 +31,8 @@ VRDisplayEvent* VRDisplayEvent::Create(
const AtomicString& type,
VRDisplay* display,
device::mojom::blink::VRDisplayEventReason reason) {
- return new VRDisplayEvent(type, display,
- VRDisplayEventReasonToString(reason));
+ return MakeGarbageCollected<VRDisplayEvent>(
+ type, display, VRDisplayEventReasonToString(reason));
}
VRDisplayEvent::VRDisplayEvent() = default;
@@ -45,19 +45,19 @@ VRDisplayEvent::VRDisplayEvent(const AtomicString& type,
reason_(reason) {}
VRDisplayEvent::VRDisplayEvent(const AtomicString& type,
- const VRDisplayEventInit& initializer)
+ const VRDisplayEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasDisplay())
- display_ = initializer.display();
+ if (initializer->hasDisplay())
+ display_ = initializer->display();
- if (initializer.hasReason())
- reason_ = initializer.reason();
+ if (initializer->hasReason())
+ reason_ = initializer->reason();
}
VRDisplayEvent::~VRDisplayEvent() = default;
const AtomicString& VRDisplayEvent::InterfaceName() const {
- return EventNames::VRDisplayEvent;
+ return event_interface_names::kVRDisplayEvent;
}
void VRDisplayEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_display_event.h b/chromium/third_party/blink/renderer/modules/vr/vr_display_event.h
index 93ea5a4e65f..a73c03a30a6 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_display_event.h
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_display_event.h
@@ -15,21 +15,26 @@ class VRDisplayEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static VRDisplayEvent* Create() { return new VRDisplayEvent; }
+ static VRDisplayEvent* Create() {
+ return MakeGarbageCollected<VRDisplayEvent>();
+ }
static VRDisplayEvent* Create(const AtomicString& type,
VRDisplay* display,
String reason) {
- return new VRDisplayEvent(type, display, reason);
+ return MakeGarbageCollected<VRDisplayEvent>(type, display, reason);
}
static VRDisplayEvent* Create(const AtomicString& type,
VRDisplay*,
device::mojom::blink::VRDisplayEventReason);
static VRDisplayEvent* Create(const AtomicString& type,
- const VRDisplayEventInit& initializer) {
- return new VRDisplayEvent(type, initializer);
+ const VRDisplayEventInit* initializer) {
+ return MakeGarbageCollected<VRDisplayEvent>(type, initializer);
}
+ VRDisplayEvent();
+ VRDisplayEvent(const AtomicString& type, VRDisplay*, String);
+ VRDisplayEvent(const AtomicString&, const VRDisplayEventInit*);
~VRDisplayEvent() override;
VRDisplay* display() const { return display_.Get(); }
@@ -40,12 +45,6 @@ class VRDisplayEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- VRDisplayEvent();
- VRDisplayEvent(const AtomicString& type,
- VRDisplay*,
- String);
- VRDisplayEvent(const AtomicString&, const VRDisplayEventInit&);
-
Member<VRDisplay> display_;
String reason_;
};
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.cc b/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.cc
index 0c4f15ffa2d..d4232a70064 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.cc
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.cc
@@ -14,7 +14,7 @@ VREyeParameters::VREyeParameters(
offset_->Data()[1] = eye_parameters->offset[1];
offset_->Data()[2] = eye_parameters->offset[2];
- field_of_view_ = new VRFieldOfView();
+ field_of_view_ = MakeGarbageCollected<VRFieldOfView>();
field_of_view_->SetUpDegrees(eye_parameters->fieldOfView->upDegrees);
field_of_view_->SetDownDegrees(eye_parameters->fieldOfView->downDegrees);
field_of_view_->SetLeftDegrees(eye_parameters->fieldOfView->leftDegrees);
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.h b/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.h
index 235f30cc1ac..12b57d3f251 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.h
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_eye_parameters.h
@@ -24,16 +24,16 @@ class VREyeParameters final : public ScriptWrappable {
DOMFloat32Array* offset() const { return offset_; }
VRFieldOfView* FieldOfView() const { return field_of_view_; }
- unsigned long renderWidth() const { return render_width_; }
- unsigned long renderHeight() const { return render_height_; }
+ uint32_t renderWidth() const { return render_width_; }
+ uint32_t renderHeight() const { return render_height_; }
void Trace(blink::Visitor*) override;
private:
Member<DOMFloat32Array> offset_;
Member<VRFieldOfView> field_of_view_;
- unsigned long render_width_;
- unsigned long render_height_;
+ uint32_t render_width_;
+ uint32_t render_height_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.cc b/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.cc
index d17d973b810..dd1af5b18a2 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.cc
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.cc
@@ -187,7 +187,7 @@ bool VRFrameData::Update(const device::mojom::blink::VRPosePtr& pose,
fov_right = right_eye->FieldOfView();
} else {
DCHECK(!left_eye && !right_eye);
- fov_left = fov_right = new VRFieldOfView(45, 45, 45, 45);
+ fov_left = fov_right = MakeGarbageCollected<VRFieldOfView>(45, 45, 45, 45);
}
// Build the projection matrices
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.h b/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.h
index 3bbbb98fd8f..b028cbd8d45 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.h
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_frame_data.h
@@ -20,7 +20,7 @@ class VRFrameData final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static VRFrameData* Create() { return new VRFrameData(); }
+ static VRFrameData* Create() { return MakeGarbageCollected<VRFrameData>(); }
VRFrameData();
diff --git a/chromium/third_party/blink/renderer/modules/vr/vr_pose.h b/chromium/third_party/blink/renderer/modules/vr/vr_pose.h
index de606d4335b..626bf3305c2 100644
--- a/chromium/third_party/blink/renderer/modules/vr/vr_pose.h
+++ b/chromium/third_party/blink/renderer/modules/vr/vr_pose.h
@@ -17,7 +17,9 @@ class VRPose final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static VRPose* Create() { return new VRPose(); }
+ static VRPose* Create() { return MakeGarbageCollected<VRPose>(); }
+
+ VRPose();
DOMFloat32Array* orientation() const { return orientation_; }
DOMFloat32Array* position() const { return position_; }
@@ -31,8 +33,6 @@ class VRPose final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- VRPose();
-
Member<DOMFloat32Array> orientation_;
Member<DOMFloat32Array> position_;
Member<DOMFloat32Array> angular_velocity_;
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.cc b/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.cc
index 58ea962fae5..8856158e88d 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.cc
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.cc
@@ -46,7 +46,7 @@ NavigatorWakeLock& NavigatorWakeLock::From(Navigator& navigator) {
NavigatorWakeLock* supplement =
Supplement<Navigator>::From<NavigatorWakeLock>(navigator);
if (!supplement) {
- supplement = new NavigatorWakeLock(navigator);
+ supplement = MakeGarbageCollected<NavigatorWakeLock>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.h b/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.h
index f6d0c183b9a..ebe18dd2336 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.h
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/navigator_wake_lock.h
@@ -26,11 +26,12 @@ class NavigatorWakeLock final : public GarbageCollected<NavigatorWakeLock>,
static ScriptPromise getWakeLock(ScriptState*, Navigator&, String);
+ explicit NavigatorWakeLock(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
ScriptPromise getWakeLock(ScriptState*, String);
- explicit NavigatorWakeLock(Navigator&);
Member<WakeLock> wake_lock_screen_;
Member<WakeLock> wake_lock_system_;
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.cc b/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.cc
index 3d283da7768..90d19e5a29b 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.cc
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.cc
@@ -39,7 +39,7 @@ ScreenWakeLock* ScreenWakeLock::From(LocalFrame* frame) {
ScreenWakeLock* supplement =
Supplement<LocalFrame>::From<ScreenWakeLock>(frame);
if (!supplement) {
- supplement = new ScreenWakeLock(*frame);
+ supplement = MakeGarbageCollected<ScreenWakeLock>(*frame);
ProvideTo(*frame, supplement);
}
return supplement;
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.h b/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.h
index a2757d3a25b..dc47bbdd4f7 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.h
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock.h
@@ -33,13 +33,12 @@ class MODULES_EXPORT ScreenWakeLock final
static ScreenWakeLock* From(LocalFrame*);
+ explicit ScreenWakeLock(LocalFrame&);
~ScreenWakeLock() = default;
void Trace(blink::Visitor*) override;
private:
- explicit ScreenWakeLock(LocalFrame&);
-
// Inherited from PageVisibilityObserver.
void PageVisibilityChanged() override;
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock_test.cc b/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock_test.cc
index 5565fbf918f..6e776116afe 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock_test.cc
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/screen_wake_lock_test.cc
@@ -63,7 +63,7 @@ class ScreenWakeLockTest : public testing::Test {
WTF::Unretained(&mock_wake_lock_)));
web_view_helper_.Initialize(&test_web_frame_client_);
- URLTestHelpers::RegisterMockedURLLoadFromBase(
+ url_test_helpers::RegisterMockedURLLoadFromBase(
WebString::FromUTF8("http://example.com/"), test::CoreTestDataPath(),
WebString::FromUTF8("foo.html"));
LoadFrame();
@@ -76,9 +76,12 @@ class ScreenWakeLockTest : public testing::Test {
}
void LoadFrame() {
- FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(),
- "http://example.com/foo.html");
- web_view_helper_.GetWebView()->UpdateAllLifecyclePhases();
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(),
+ "http://example.com/foo.html");
+
+ web_view_helper_.GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
+ WebWidget::LifecycleUpdateReason::kTest);
}
LocalFrame* GetFrame() {
@@ -125,8 +128,8 @@ class ScreenWakeLockTest : public testing::Test {
// Order of these members is important as we need to make sure that
// test_web_frame_client_ outlives web_view_helper_ (destruction order)
- FrameTestHelpers::TestWebFrameClient test_web_frame_client_;
- FrameTestHelpers::WebViewHelper web_view_helper_;
+ frame_test_helpers::TestWebFrameClient test_web_frame_client_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
MockWakeLock mock_wake_lock_;
ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.cc b/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.cc
index f1947ebc4b5..1b281c9d0c3 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.cc
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.cc
@@ -20,11 +20,11 @@
namespace blink {
WakeLock* WakeLock::CreateScreenWakeLock(ScriptState* script_state) {
- return new WakeLock(script_state, LockType::kScreen);
+ return MakeGarbageCollected<WakeLock>(script_state, LockType::kScreen);
}
WakeLock* WakeLock::CreateSystemWakeLock(ScriptState* script_state) {
- return new WakeLock(script_state, LockType::kSystem);
+ return MakeGarbageCollected<WakeLock>(script_state, LockType::kSystem);
}
WakeLock::~WakeLock() = default;
@@ -76,7 +76,7 @@ void WakeLock::ChangeActiveStatus(bool active) {
wake_lock_service_->CancelWakeLock();
active_ = active;
- EnqueueEvent(*Event::Create(EventTypeNames::activechange),
+ EnqueueEvent(*Event::Create(event_type_names::kActivechange),
TaskType::kMiscPlatformAPI);
}
@@ -110,7 +110,7 @@ WakeLockRequest* WakeLock::createRequest() {
ChangeActiveStatus(true);
request_counter_++;
- return new WakeLockRequest(this);
+ return MakeGarbageCollected<WakeLockRequest>(this);
}
void WakeLock::CancelRequest() {
@@ -122,7 +122,7 @@ void WakeLock::CancelRequest() {
}
const WTF::AtomicString& WakeLock::InterfaceName() const {
- return EventTargetNames::WakeLock;
+ return event_target_names::kWakeLock;
}
ExecutionContext* WakeLock::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.h b/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.h
index a8896f249de..0355ec62969 100644
--- a/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.h
+++ b/chromium/third_party/blink/renderer/modules/wake_lock/wake_lock.h
@@ -26,12 +26,15 @@ class WakeLock final : public EventTargetWithInlineData,
USING_GARBAGE_COLLECTED_MIXIN(WakeLock);
public:
+ enum class LockType { kSystem, kScreen };
+
+ WakeLock(ScriptState*, LockType);
~WakeLock() override;
// wake_lock.idl implementation
AtomicString type() const;
bool active() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(activechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(activechange, kActivechange);
WakeLockRequest* createRequest();
// Called by NavigatorWakeLock to create Screen Wake Lock
@@ -61,10 +64,6 @@ class WakeLock final : public EventTargetWithInlineData,
void CancelRequest();
private:
- enum class LockType { kSystem, kScreen };
-
- WakeLock(ScriptState*, LockType);
-
// Error handler in case of failure to connect to Wake Lock mojo service
void OnConnectionError();
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.cc
index 39ee21aae4b..a6887cfd30d 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.cc
@@ -48,7 +48,7 @@ AnalyserHandler::~AnalyserHandler() {
Uninitialize();
}
-void AnalyserHandler::Process(size_t frames_to_process) {
+void AnalyserHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
if (!IsInitialized()) {
@@ -205,7 +205,7 @@ AnalyserNode* AnalyserNode::Create(BaseAudioContext& context,
}
AnalyserNode* AnalyserNode::Create(BaseAudioContext* context,
- const AnalyserOptions& options,
+ const AnalyserOptions* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -216,13 +216,13 @@ AnalyserNode* AnalyserNode::Create(BaseAudioContext* context,
node->HandleChannelOptions(options, exception_state);
- node->setFftSize(options.fftSize(), exception_state);
- node->setSmoothingTimeConstant(options.smoothingTimeConstant(),
+ node->setFftSize(options->fftSize(), exception_state);
+ node->setSmoothingTimeConstant(options->smoothingTimeConstant(),
exception_state);
// minDecibels and maxDecibels have default values. Set both of the values
// at once.
- node->SetMinMaxDecibels(options.minDecibels(), options.maxDecibels(),
+ node->SetMinMaxDecibels(options->minDecibels(), options->maxDecibels(),
exception_state);
return node;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.h b/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.h
index 3b805158e30..235bfd7c0cb 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/analyser_node.h
@@ -43,7 +43,7 @@ class AnalyserHandler final : public AudioBasicInspectorHandler {
~AnalyserHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
unsigned FftSize() const { return analyser_.FftSize(); }
void SetFftSize(unsigned size, ExceptionState&);
@@ -103,7 +103,7 @@ class AnalyserNode final : public AudioBasicInspectorNode {
public:
static AnalyserNode* Create(BaseAudioContext&, ExceptionState&);
static AnalyserNode* Create(BaseAudioContext*,
- const AnalyserOptions&,
+ const AnalyserOptions*,
ExceptionState&);
unsigned fftSize() const;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/async_audio_decoder.cc b/chromium/third_party/blink/renderer/modules/webaudio/async_audio_decoder.cc
index aae1753fe87..08554e404cc 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/async_audio_decoder.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/async_audio_decoder.cc
@@ -34,8 +34,8 @@
#include "third_party/blink/renderer/platform/audio/audio_file_reader.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -55,7 +55,7 @@ void AsyncAudioDecoder::DecodeAsync(
context->GetExecutionContext()->GetTaskRunner(
blink::TaskType::kInternalMedia);
- BackgroundScheduler::PostOnBackgroundThread(
+ background_scheduler::PostOnBackgroundThread(
FROM_HERE,
CrossThreadBind(&AsyncAudioDecoder::DecodeOnBackgroundThread,
WrapCrossThreadPersistent(audio_data), sample_rate,
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.cc
index bc5eb7f158c..5df6a023764 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.cc
@@ -44,7 +44,7 @@ AudioBasicInspectorHandler::AudioBasicInspectorHandler(
// advantage of in-place processing, where the input is simply passed through
// unprocessed to the output.
// Note: this only applies if the input and output channel counts match.
-void AudioBasicInspectorHandler::PullInputs(size_t frames_to_process) {
+void AudioBasicInspectorHandler::PullInputs(uint32_t frames_to_process) {
// Render input stream - try to render directly into output bus for
// pass-through processing where process() doesn't need to do anything...
Input(0).Pull(Output(0).Bus(), frames_to_process);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.h
index eaaf754ef94..884495b635b 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_inspector_node.h
@@ -44,7 +44,7 @@ class AudioBasicInspectorHandler : public AudioHandler {
unsigned output_channel_count);
// AudioHandler
- void PullInputs(size_t frames_to_process) final;
+ void PullInputs(uint32_t frames_to_process) final;
void CheckNumberOfChannelsForInput(AudioNodeInput*) final;
// AudioNode
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc
index a7f6b05aed0..7be1d80b6aa 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.cc
@@ -68,7 +68,7 @@ void AudioBasicProcessorHandler::Uninitialize() {
AudioHandler::Uninitialize();
}
-void AudioBasicProcessorHandler::Process(size_t frames_to_process) {
+void AudioBasicProcessorHandler::Process(uint32_t frames_to_process) {
AudioBus* destination_bus = Output(0).Bus();
if (!IsInitialized() || !Processor() ||
@@ -87,7 +87,7 @@ void AudioBasicProcessorHandler::Process(size_t frames_to_process) {
}
void AudioBasicProcessorHandler::ProcessOnlyAudioParams(
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (!IsInitialized() || !Processor())
return;
@@ -95,7 +95,7 @@ void AudioBasicProcessorHandler::ProcessOnlyAudioParams(
}
// Nice optimization in the very common case allowing for "in-place" processing
-void AudioBasicProcessorHandler::PullInputs(size_t frames_to_process) {
+void AudioBasicProcessorHandler::PullInputs(uint32_t frames_to_process) {
// Render input stream - suggest to the input to render directly into output
// bus for in-place processing in process() if possible.
Input(0).Pull(Output(0).Bus(), frames_to_process);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h
index 056e60f0ffb..e4951b6887c 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler.h
@@ -43,9 +43,9 @@ class MODULES_EXPORT AudioBasicProcessorHandler : public AudioHandler {
~AudioBasicProcessorHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) final;
- void ProcessOnlyAudioParams(size_t frames_to_process) final;
- void PullInputs(size_t frames_to_process) final;
+ void Process(uint32_t frames_to_process) final;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) final;
+ void PullInputs(uint32_t frames_to_process) final;
void Initialize() final;
void Uninitialize() final;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler_test.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler_test.cc
index bb908aed720..1daf55e63a2 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler_test.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_basic_processor_handler_test.cc
@@ -16,7 +16,7 @@ class MockAudioProcessor final : public AudioProcessor {
MockAudioProcessor() : AudioProcessor(48000, 2) {}
void Initialize() override { initialized_ = true; }
void Uninitialize() override { initialized_ = false; }
- void Process(const AudioBus*, AudioBus*, size_t) override {}
+ void Process(const AudioBus*, AudioBus*, uint32_t) override {}
void Reset() override {}
void SetNumberOfChannels(unsigned) override {}
unsigned NumberOfChannels() const override { return number_of_channels_; }
@@ -53,7 +53,7 @@ TEST(AudioBasicProcessorHandlerTest, ProcessorFinalization) {
std::unique_ptr<DummyPageHolder> page = DummyPageHolder::Create();
OfflineAudioContext* context = OfflineAudioContext::Create(
&page->GetDocument(), 2, 1, 48000, ASSERT_NO_EXCEPTION);
- MockProcessorNode* node = new MockProcessorNode(*context);
+ MockProcessorNode* node = MakeGarbageCollected<MockProcessorNode>(*context);
AudioBasicProcessorHandler& handler =
static_cast<AudioBasicProcessorHandler&>(node->Handler());
EXPECT_TRUE(handler.Processor());
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.cc
index e3133cde0da..37818f29ab1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.cc
@@ -40,9 +40,9 @@
namespace blink {
AudioBuffer* AudioBuffer::Create(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate) {
- if (!AudioUtilities::IsValidAudioBufferSampleRate(sample_rate) ||
+ if (!audio_utilities::IsValidAudioBufferSampleRate(sample_rate) ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
!number_of_channels || !number_of_frames)
return nullptr;
@@ -56,7 +56,7 @@ AudioBuffer* AudioBuffer::Create(unsigned number_of_channels,
}
AudioBuffer* AudioBuffer::Create(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
ExceptionState& exception_state) {
if (!number_of_channels ||
@@ -71,14 +71,14 @@ AudioBuffer* AudioBuffer::Create(unsigned number_of_channels,
return nullptr;
}
- if (!AudioUtilities::IsValidAudioBufferSampleRate(sample_rate)) {
+ if (!audio_utilities::IsValidAudioBufferSampleRate(sample_rate)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
ExceptionMessages::IndexOutsideRange(
"sample rate", sample_rate,
- AudioUtilities::MinAudioBufferSampleRate(),
+ audio_utilities::MinAudioBufferSampleRate(),
ExceptionMessages::kInclusiveBound,
- AudioUtilities::MaxAudioBufferSampleRate(),
+ audio_utilities::MaxAudioBufferSampleRate(),
ExceptionMessages::kInclusiveBound));
return nullptr;
}
@@ -86,8 +86,8 @@ AudioBuffer* AudioBuffer::Create(unsigned number_of_channels,
if (!number_of_frames) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
- ExceptionMessages::IndexExceedsMinimumBound(
- "number of frames", number_of_frames, static_cast<size_t>(0)));
+ ExceptionMessages::IndexExceedsMinimumBound("number of frames",
+ number_of_frames, 0u));
return nullptr;
}
@@ -105,16 +105,16 @@ AudioBuffer* AudioBuffer::Create(unsigned number_of_channels,
return audio_buffer;
}
-AudioBuffer* AudioBuffer::Create(const AudioBufferOptions& options,
+AudioBuffer* AudioBuffer::Create(const AudioBufferOptions* options,
ExceptionState& exception_state) {
- return Create(options.numberOfChannels(), options.length(),
- options.sampleRate(), exception_state);
+ return Create(options->numberOfChannels(), options->length(),
+ options->sampleRate(), exception_state);
}
AudioBuffer* AudioBuffer::CreateUninitialized(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate) {
- if (!AudioUtilities::IsValidAudioBufferSampleRate(sample_rate) ||
+ if (!audio_utilities::IsValidAudioBufferSampleRate(sample_rate) ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
!number_of_channels || !number_of_frames)
return nullptr;
@@ -157,7 +157,7 @@ bool AudioBuffer::CreatedSuccessfully(
}
DOMFloat32Array* AudioBuffer::CreateFloat32ArrayOrNull(
- size_t length,
+ uint32_t length,
InitializationPolicy policy) {
scoped_refptr<WTF::Float32Array> buffer;
@@ -180,7 +180,7 @@ DOMFloat32Array* AudioBuffer::CreateFloat32ArrayOrNull(
}
AudioBuffer::AudioBuffer(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
InitializationPolicy policy)
: sample_rate_(sample_rate), length_(number_of_frames) {
@@ -243,23 +243,23 @@ NotShared<DOMFloat32Array> AudioBuffer::getChannelData(unsigned channel_index) {
}
void AudioBuffer::copyFromChannel(NotShared<DOMFloat32Array> destination,
- long channel_number,
+ int32_t channel_number,
ExceptionState& exception_state) {
return copyFromChannel(destination, channel_number, 0, exception_state);
}
void AudioBuffer::copyFromChannel(NotShared<DOMFloat32Array> destination,
- long channel_number,
- unsigned long start_in_channel,
+ int32_t channel_number,
+ uint32_t start_in_channel,
ExceptionState& exception_state) {
if (channel_number < 0 ||
- channel_number >= static_cast<long>(channels_.size())) {
+ static_cast<uint32_t>(channel_number) >= channels_.size()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexOutsideRange(
- "channelNumber", channel_number, 0L,
+ "channelNumber", channel_number, 0,
ExceptionMessages::kInclusiveBound,
- static_cast<long>(channels_.size() - 1),
+ static_cast<int32_t>(channels_.size() - 1),
ExceptionMessages::kInclusiveBound));
return;
@@ -271,9 +271,8 @@ void AudioBuffer::copyFromChannel(NotShared<DOMFloat32Array> destination,
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexOutsideRange(
- "startInChannel", start_in_channel, 0UL,
- ExceptionMessages::kInclusiveBound,
- static_cast<unsigned long>(channel_data->length()),
+ "startInChannel", start_in_channel, 0U,
+ ExceptionMessages::kInclusiveBound, channel_data->length(),
ExceptionMessages::kExclusiveBound));
return;
@@ -292,23 +291,23 @@ void AudioBuffer::copyFromChannel(NotShared<DOMFloat32Array> destination,
}
void AudioBuffer::copyToChannel(NotShared<DOMFloat32Array> source,
- long channel_number,
+ int32_t channel_number,
ExceptionState& exception_state) {
return copyToChannel(source, channel_number, 0, exception_state);
}
void AudioBuffer::copyToChannel(NotShared<DOMFloat32Array> source,
- long channel_number,
- unsigned long start_in_channel,
+ int32_t channel_number,
+ uint32_t start_in_channel,
ExceptionState& exception_state) {
if (channel_number < 0 ||
- channel_number >= static_cast<long>(channels_.size())) {
+ static_cast<uint32_t>(channel_number) >= channels_.size()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexOutsideRange(
- "channelNumber", channel_number, 0L,
+ "channelNumber", channel_number, 0,
ExceptionMessages::kInclusiveBound,
- static_cast<long>(channels_.size() - 1),
+ static_cast<int32_t>(channels_.size() - 1),
ExceptionMessages::kInclusiveBound));
return;
}
@@ -319,9 +318,8 @@ void AudioBuffer::copyToChannel(NotShared<DOMFloat32Array> source,
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexOutsideRange(
- "startInChannel", start_in_channel, 0UL,
- ExceptionMessages::kInclusiveBound,
- static_cast<unsigned long>(channel_data->length()),
+ "startInChannel", start_in_channel, 0U,
+ ExceptionMessages::kInclusiveBound, channel_data->length(),
ExceptionMessages::kExclusiveBound));
return;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.h
index d9bdda78b09..9867f77b9ac 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer.h
@@ -47,13 +47,13 @@ class MODULES_EXPORT AudioBuffer final : public ScriptWrappable {
public:
static AudioBuffer* Create(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate);
static AudioBuffer* Create(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
ExceptionState&);
- static AudioBuffer* Create(const AudioBufferOptions&, ExceptionState&);
+ static AudioBuffer* Create(const AudioBufferOptions*, ExceptionState&);
// Creates an AudioBuffer with uninitialized contents. This should
// only be used where we are guaranteed to initialize the contents
@@ -61,7 +61,7 @@ class MODULES_EXPORT AudioBuffer final : public ScriptWrappable {
// is done. |OfflineAudioContext::startRendering()| is one such
// place.
static AudioBuffer* CreateUninitialized(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate);
// Returns 0 if data is not a valid audio file.
@@ -73,7 +73,7 @@ class MODULES_EXPORT AudioBuffer final : public ScriptWrappable {
static AudioBuffer* CreateFromAudioBus(AudioBus*);
// Format
- size_t length() const { return length_; }
+ uint32_t length() const { return length_; }
double duration() const {
return length() / static_cast<double>(sampleRate());
}
@@ -85,18 +85,18 @@ class MODULES_EXPORT AudioBuffer final : public ScriptWrappable {
ExceptionState&);
NotShared<DOMFloat32Array> getChannelData(unsigned channel_index);
void copyFromChannel(NotShared<DOMFloat32Array>,
- long channel_number,
+ int32_t channel_number,
ExceptionState&);
void copyFromChannel(NotShared<DOMFloat32Array>,
- long channel_number,
- unsigned long start_in_channel,
+ int32_t channel_number,
+ uint32_t start_in_channel,
ExceptionState&);
void copyToChannel(NotShared<DOMFloat32Array>,
- long channel_number,
+ int32_t channel_number,
ExceptionState&);
void copyToChannel(NotShared<DOMFloat32Array>,
- long channel_number,
- unsigned long start_in_channel,
+ int32_t channel_number,
+ uint32_t start_in_channel,
ExceptionState&);
void Zero();
@@ -115,17 +115,17 @@ class MODULES_EXPORT AudioBuffer final : public ScriptWrappable {
explicit AudioBuffer(AudioBus*);
static DOMFloat32Array* CreateFloat32ArrayOrNull(
- size_t length,
+ uint32_t length,
InitializationPolicy allocation_policy = kZeroInitialize);
AudioBuffer(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
InitializationPolicy allocation_policy = kZeroInitialize);
bool CreatedSuccessfully(unsigned desired_number_of_channels) const;
float sample_rate_;
- size_t length_;
+ uint32_t length_;
HeapVector<Member<DOMFloat32Array>> channels_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc
index 74ce5c17336..5f1162e3425 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.cc
@@ -93,7 +93,7 @@ AudioBufferSourceHandler::~AudioBufferSourceHandler() {
Uninitialize();
}
-void AudioBufferSourceHandler::Process(size_t frames_to_process) {
+void AudioBufferSourceHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
if (!IsInitialized()) {
@@ -119,8 +119,8 @@ void AudioBufferSourceHandler::Process(size_t frames_to_process) {
return;
}
- size_t quantum_frame_offset;
- size_t buffer_frames_to_process;
+ uint32_t quantum_frame_offset;
+ uint32_t buffer_frames_to_process;
double start_time_offset;
std::tie(quantum_frame_offset, buffer_frames_to_process,
@@ -154,7 +154,7 @@ void AudioBufferSourceHandler::Process(size_t frames_to_process) {
bool AudioBufferSourceHandler::RenderSilenceAndFinishIfNotLooping(
AudioBus*,
unsigned index,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (!Loop()) {
// If we're not looping, then stop playing when we get to the end.
@@ -176,7 +176,7 @@ bool AudioBufferSourceHandler::RenderSilenceAndFinishIfNotLooping(
bool AudioBufferSourceHandler::RenderFromBuffer(
AudioBus* bus,
unsigned destination_frame_offset,
- size_t number_of_frames) {
+ uint32_t number_of_frames) {
DCHECK(Context()->IsAudioThread());
// Basic sanity checking
@@ -198,8 +198,8 @@ bool AudioBufferSourceHandler::RenderFromBuffer(
size_t destination_length = bus->length();
bool is_length_good =
- destination_length <= AudioUtilities::kRenderQuantumFrames &&
- number_of_frames <= AudioUtilities::kRenderQuantumFrames;
+ destination_length <= audio_utilities::kRenderQuantumFrames &&
+ number_of_frames <= audio_utilities::kRenderQuantumFrames;
DCHECK(is_length_good);
if (!is_length_good)
return false;
@@ -221,13 +221,13 @@ bool AudioBufferSourceHandler::RenderFromBuffer(
// Offset the pointers to the correct offset frame.
unsigned write_index = destination_frame_offset;
- size_t buffer_length = Buffer()->length();
+ uint32_t buffer_length = Buffer()->length();
double buffer_sample_rate = Buffer()->sampleRate();
// Avoid converting from time to sample-frames twice by computing
// the grain end time first before computing the sample frame.
unsigned end_frame =
- is_grain_ ? AudioUtilities::TimeToSampleFrame(
+ is_grain_ ? audio_utilities::TimeToSampleFrame(
grain_offset_ + grain_duration_, buffer_sample_rate)
: buffer_length;
@@ -482,7 +482,7 @@ void AudioBufferSourceHandler::ClampGrainParameters(const AudioBuffer* buffer) {
// identical to the PCM data stored in the buffer. Since playbackRate == 1 is
// very common, it's worth considering quality.
virtual_read_index_ =
- AudioUtilities::TimeToSampleFrame(grain_offset_, buffer->sampleRate());
+ audio_utilities::TimeToSampleFrame(grain_offset_, buffer->sampleRate());
}
void AudioBufferSourceHandler::Start(double when,
@@ -687,7 +687,7 @@ AudioBufferSourceNode* AudioBufferSourceNode::Create(
AudioBufferSourceNode* AudioBufferSourceNode::Create(
BaseAudioContext* context,
- AudioBufferSourceOptions& options,
+ AudioBufferSourceOptions* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -696,13 +696,13 @@ AudioBufferSourceNode* AudioBufferSourceNode::Create(
if (!node)
return nullptr;
- if (options.hasBuffer())
- node->setBuffer(options.buffer(), exception_state);
- node->detune()->setValue(options.detune());
- node->setLoop(options.loop());
- node->setLoopEnd(options.loopEnd());
- node->setLoopStart(options.loopStart());
- node->playbackRate()->setValue(options.playbackRate());
+ if (options->hasBuffer())
+ node->setBuffer(options->buffer(), exception_state);
+ node->detune()->setValue(options->detune());
+ node->setLoop(options->loop());
+ node->setLoopEnd(options->loopEnd());
+ node->setLoopStart(options->loopStart());
+ node->playbackRate()->setValue(options->playbackRate());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.h
index 0547dc956c1..27e28265e96 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_buffer_source_node.h
@@ -55,7 +55,7 @@ class AudioBufferSourceHandler final : public AudioScheduledSourceHandler {
~AudioBufferSourceHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
// setBuffer() is called on the main thread. This is the buffer we use for
// playback.
@@ -110,12 +110,12 @@ class AudioBufferSourceHandler final : public AudioScheduledSourceHandler {
// Returns true on success.
bool RenderFromBuffer(AudioBus*,
unsigned destination_frame_offset,
- size_t number_of_frames);
+ uint32_t number_of_frames);
// Render silence starting from "index" frame in AudioBus.
inline bool RenderSilenceAndFinishIfNotLooping(AudioBus*,
unsigned index,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Clamps grain parameters to the duration of the given AudioBuffer.
void ClampGrainParameters(const AudioBuffer*);
@@ -191,7 +191,7 @@ class AudioBufferSourceNode final : public AudioScheduledSourceNode {
public:
static AudioBufferSourceNode* Create(BaseAudioContext&, ExceptionState&);
static AudioBufferSourceNode* Create(BaseAudioContext*,
- AudioBufferSourceOptions&,
+ AudioBufferSourceOptions*,
ExceptionState&);
void Trace(blink::Visitor*) override;
AudioBufferSourceHandler& GetAudioBufferSourceHandler() const;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_context.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_context.cc
index 9669d35a3f2..51c52a2d08c 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_context.cc
@@ -46,36 +46,37 @@ static unsigned g_hardware_context_count = 0;
static unsigned g_context_id = 0;
AudioContext* AudioContext::Create(Document& document,
- const AudioContextOptions& context_options,
+ const AudioContextOptions* context_options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
+ LOG(ERROR) << __func__;
UseCounter::CountCrossOriginIframe(
document, WebFeature::kAudioContextCrossOriginIframe);
WebAudioLatencyHint latency_hint(WebAudioLatencyHint::kCategoryInteractive);
- if (context_options.latencyHint().IsAudioContextLatencyCategory()) {
+ if (context_options->latencyHint().IsAudioContextLatencyCategory()) {
latency_hint = WebAudioLatencyHint(
- context_options.latencyHint().GetAsAudioContextLatencyCategory());
- } else if (context_options.latencyHint().IsDouble()) {
+ context_options->latencyHint().GetAsAudioContextLatencyCategory());
+ } else if (context_options->latencyHint().IsDouble()) {
// This should be the requested output latency in seconds, without taking
// into account double buffering (same as baseLatency).
latency_hint =
- WebAudioLatencyHint(context_options.latencyHint().GetAsDouble());
+ WebAudioLatencyHint(context_options->latencyHint().GetAsDouble());
}
AudioContext* audio_context = new AudioContext(document, latency_hint);
audio_context->PauseIfNeeded();
- if (!AudioUtilities::IsValidAudioBufferSampleRate(
+ if (!audio_utilities::IsValidAudioBufferSampleRate(
audio_context->sampleRate())) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
ExceptionMessages::IndexOutsideRange(
"hardware sample rate", audio_context->sampleRate(),
- AudioUtilities::MinAudioBufferSampleRate(),
+ audio_utilities::MinAudioBufferSampleRate(),
ExceptionMessages::kInclusiveBound,
- AudioUtilities::MaxAudioBufferSampleRate(),
+ audio_utilities::MaxAudioBufferSampleRate(),
ExceptionMessages::kInclusiveBound));
return audio_context;
}
@@ -89,6 +90,7 @@ AudioContext* AudioContext::Create(Document& document,
audio_context->MaybeAllowAutoplayWithUnlockType(
AutoplayUnlockType::kContextConstructor);
if (audio_context->IsAllowedToStart()) {
+ LOG(ERROR) << "starting";
audio_context->StartRendering();
audio_context->SetContextState(kRunning);
}
@@ -125,12 +127,15 @@ AudioContext::AudioContext(Document& document,
: BaseAudioContext(&document, kRealtimeContext),
context_id_(g_context_id++) {
destination_node_ = DefaultAudioDestinationNode::Create(this, latency_hint);
+ LOG(ERROR) << __func__;
switch (GetAutoplayPolicy()) {
case AutoplayPolicy::Type::kNoUserGestureRequired:
+ LOG(ERROR) << "no user gesture";
break;
case AutoplayPolicy::Type::kUserGestureRequired:
case AutoplayPolicy::Type::kUserGestureRequiredForCrossOrigin:
+ LOG(ERROR) << "user gesture";
if (document.GetFrame() &&
document.GetFrame()->IsCrossOriginSubframe()) {
autoplay_status_ = AutoplayStatus::kAutoplayStatusFailed;
@@ -138,6 +143,7 @@ AudioContext::AudioContext(Document& document,
}
break;
case AutoplayPolicy::Type::kDocumentUserActivationRequired:
+ LOG(ERROR) << "document user activation";
autoplay_status_ = AutoplayStatus::kAutoplayStatusFailed;
user_gesture_required_ = true;
break;
@@ -197,6 +203,7 @@ ScriptPromise AudioContext::suspendContext(ScriptState* script_state) {
ScriptPromise AudioContext::resumeContext(ScriptState* script_state) {
DCHECK(IsMainThread());
+ LOG(ERROR) << __func__;
if (IsContextClosed()) {
return ScriptPromise::RejectWithDOMException(
@@ -237,17 +244,19 @@ ScriptPromise AudioContext::resumeContext(ScriptState* script_state) {
return promise;
}
-void AudioContext::getOutputTimestamp(ScriptState* script_state,
- AudioTimestamp& result) {
+AudioTimestamp* AudioContext::getOutputTimestamp(
+ ScriptState* script_state) const {
+ AudioTimestamp* result = AudioTimestamp::Create();
+
DCHECK(IsMainThread());
LocalDOMWindow* window = LocalDOMWindow::From(script_state);
if (!window)
- return;
+ return result;
if (!destination()) {
- result.setContextTime(0.0);
- result.setPerformanceTime(0.0);
- return;
+ result->setContextTime(0.0);
+ result->setPerformanceTime(0.0);
+ return result;
}
WindowPerformance* performance = DOMWindowPerformance::performance(*window);
@@ -266,8 +275,9 @@ void AudioContext::getOutputTimestamp(ScriptState* script_state,
if (performance_time < 0.0)
performance_time = 0.0;
- result.setContextTime(position.position);
- result.setPerformanceTime(performance_time);
+ result->setContextTime(position.position);
+ result->setPerformanceTime(performance_time);
+ return result;
}
ScriptPromise AudioContext::closeContext(ScriptState* script_state) {
@@ -423,6 +433,7 @@ void AudioContext::MaybeAllowAutoplayWithUnlockType(AutoplayUnlockType type) {
}
bool AudioContext::IsAllowedToStart() const {
+ LOG(ERROR) << __func__;
if (!user_gesture_required_)
return true;
@@ -504,33 +515,32 @@ void AudioContext::ContextDestroyed(ExecutionContext*) {
void AudioContext::NotifyAudibleAudioStarted() {
DCHECK(IsMainThread());
- if (!audio_context_manager_) {
- Document* document = GetDocument();
-
- // If there's no document don't bother to try to create the mojom interface.
- // This can happen if the document has been reloaded while the audio thread
- // is still running.
- if (!document) {
- return;
- }
-
- document->GetFrame()->GetInterfaceProvider().GetInterface(
- mojo::MakeRequest(&audio_context_manager_));
- }
-
- DCHECK(audio_context_manager_);
- audio_context_manager_->AudioContextAudiblePlaybackStarted(context_id_);
+ EnsureAudioContextManagerService();
+ if (audio_context_manager_)
+ audio_context_manager_->AudioContextAudiblePlaybackStarted(context_id_);
}
void AudioContext::NotifyAudibleAudioStopped() {
DCHECK(IsMainThread());
- DCHECK(audio_context_manager_);
- // If we don't have a document, we don't need to notify anyone that we've
- // stopped.
- if (GetDocument()) {
+ EnsureAudioContextManagerService();
+ if (audio_context_manager_)
audio_context_manager_->AudioContextAudiblePlaybackStopped(context_id_);
- }
+}
+
+void AudioContext::EnsureAudioContextManagerService() {
+ if (audio_context_manager_ || !GetDocument())
+ return;
+
+ GetDocument()->GetFrame()->GetInterfaceProvider().GetInterface(
+ mojo::MakeRequest(&audio_context_manager_));
+ audio_context_manager_.set_connection_error_handler(
+ WTF::Bind(&AudioContext::OnAudioContextManagerServiceConnectionError,
+ WrapWeakPersistent(this)));
+}
+
+void AudioContext::OnAudioContextManagerServiceConnectionError() {
+ audio_context_manager_ = nullptr;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_context.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_context.h
index 7a3db4c0c1b..c9bd2a53bbd 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_context.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_context.h
@@ -34,7 +34,7 @@ class MODULES_EXPORT AudioContext : public BaseAudioContext {
public:
static AudioContext* Create(Document&,
- const AudioContextOptions&,
+ const AudioContextOptions*,
ExceptionState&);
~AudioContext() override;
@@ -51,7 +51,7 @@ class MODULES_EXPORT AudioContext : public BaseAudioContext {
bool HasRealtimeConstraint() final { return true; }
- void getOutputTimestamp(ScriptState*, AudioTimestamp&);
+ AudioTimestamp* getOutputTimestamp(ScriptState*) const;
double baseLatency() const;
MediaElementAudioSourceNode* createMediaElementSource(HTMLMediaElement*,
@@ -72,6 +72,7 @@ class MODULES_EXPORT AudioContext : public BaseAudioContext {
private:
friend class AudioContextAutoplayTest;
+ friend class AudioContextTest;
// Do not change the order of this enum, it is used for metrics.
enum AutoplayStatus {
@@ -123,6 +124,9 @@ class MODULES_EXPORT AudioContext : public BaseAudioContext {
void NotifyAudibleAudioStarted() final;
void NotifyAudibleAudioStopped() final;
+ void EnsureAudioContextManagerService();
+ void OnAudioContextManagerServiceConnectionError();
+
unsigned context_id_;
Member<ScriptPromiseResolver> close_resolver_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_context_autoplay_test.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_context_autoplay_test.cc
index b9b40ca63c7..e58c2f40042 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_context_autoplay_test.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_context_autoplay_test.cc
@@ -64,6 +64,8 @@ class MockWebAudioDeviceForAutoplayTest : public WebAudioDevice {
void Start() override {}
void Stop() override {}
+ void Pause() override {}
+ void Resume() override {}
double SampleRate() override { return sample_rate_; }
int FramesPerBuffer() override { return frames_per_buffer_; }
@@ -157,7 +159,7 @@ class AudioContextAutoplayTest
// Creates an AudioContext without a gesture inside a x-origin child frame.
TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CreateNoGesture_Child) {
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
@@ -181,7 +183,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CreateNoGesture_Child) {
// Creates an AudioContext without a gesture inside a main frame.
TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CreateNoGesture_Main) {
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
@@ -207,7 +209,7 @@ TEST_P(AudioContextAutoplayTest,
ScriptState::Scope scope(GetScriptStateFrom(ChildDocument()));
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
audio_context->resumeContext(GetScriptStateFrom(ChildDocument()));
RejectPendingResolvers(audio_context);
RecordAutoplayStatus(audio_context);
@@ -235,7 +237,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CallResumeNoGesture_Main) {
ScriptState::Scope scope(GetScriptStateFrom(GetDocument()));
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
audio_context->resumeContext(GetScriptStateFrom(ChildDocument()));
RejectPendingResolvers(audio_context);
RecordAutoplayStatus(audio_context);
@@ -263,7 +265,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CreateGesture_Child) {
UserGestureToken::kNewGesture);
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
@@ -292,7 +294,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CreateGesture_Main) {
UserGestureToken::kNewGesture);
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
@@ -317,7 +319,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CallResumeGesture_Child) {
ScriptState::Scope scope(GetScriptStateFrom(ChildDocument()));
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
LocalFrame::NotifyUserActivation(ChildDocument().GetFrame(),
@@ -352,7 +354,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CallResumeGesture_Main) {
ScriptState::Scope scope(GetScriptStateFrom(GetDocument()));
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
LocalFrame::NotifyUserActivation(GetDocument().GetFrame(),
@@ -382,7 +384,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_CallResumeGesture_Main) {
// x-origin child frame.
TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartNoGesture_Child) {
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
audio_context->NotifySourceNodeStart();
RecordAutoplayStatus(audio_context);
@@ -408,7 +410,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartNoGesture_Child) {
// main frame.
TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartNoGesture_Main) {
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
audio_context->NotifySourceNodeStart();
RecordAutoplayStatus(audio_context);
@@ -432,7 +434,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartNoGesture_Main) {
// x-origin child frame.
TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartGesture_Child) {
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
LocalFrame::NotifyUserActivation(ChildDocument().GetFrame(),
@@ -463,7 +465,7 @@ TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartGesture_Child) {
// main frame.
TEST_P(AudioContextAutoplayTest, AutoplayMetrics_NodeStartGesture_Main) {
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
LocalFrame::NotifyUserActivation(GetDocument().GetFrame(),
@@ -494,7 +496,7 @@ TEST_P(AudioContextAutoplayTest,
ScriptState::Scope scope(GetScriptStateFrom(ChildDocument()));
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
audio_context->NotifySourceNodeStart();
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
@@ -530,7 +532,7 @@ TEST_P(AudioContextAutoplayTest,
ScriptState::Scope scope(GetScriptStateFrom(GetDocument()));
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
audio_context->NotifySourceNodeStart();
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
@@ -563,7 +565,7 @@ TEST_P(AudioContextAutoplayTest,
ScriptState::Scope scope(GetScriptStateFrom(ChildDocument()));
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
LocalFrame::NotifyUserActivation(ChildDocument().GetFrame(),
@@ -599,7 +601,7 @@ TEST_P(AudioContextAutoplayTest,
ScriptState::Scope scope(GetScriptStateFrom(GetDocument()));
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
std::unique_ptr<UserGestureIndicator> user_gesture_scope =
LocalFrame::NotifyUserActivation(GetDocument().GetFrame(),
@@ -633,7 +635,7 @@ TEST_P(AudioContextAutoplayTest,
UserGestureToken::kNewGesture);
AudioContext* audio_context = AudioContext::Create(
- ChildDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ ChildDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
@@ -670,7 +672,7 @@ TEST_P(AudioContextAutoplayTest,
UserGestureToken::kNewGesture);
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
@@ -697,7 +699,7 @@ TEST_P(AudioContextAutoplayTest,
true);
AudioContext* audio_context = AudioContext::Create(
- GetDocument(), AudioContextOptions(), ASSERT_NO_EXCEPTION);
+ GetDocument(), AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
RecordAutoplayStatus(audio_context);
switch (GetParam()) {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_context_test.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_context_test.cc
index 2923f69a21f..9a7cbde4e5c 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_context_test.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_context_test.cc
@@ -27,6 +27,8 @@ class MockWebAudioDeviceForAudioContext : public WebAudioDevice {
void Start() override {}
void Stop() override {}
+ void Pause() override {}
+ void Resume() override {}
double SampleRate() override { return sample_rate_; }
int FramesPerBuffer() override { return frames_per_buffer_; }
@@ -87,21 +89,31 @@ class AudioContextTest : public PageTestBase {
void SetUp() override { PageTestBase::SetUp(IntSize()); }
+ mojom::blink::AudioContextManagerPtr& GetAudioContextManagerPtrFor(
+ AudioContext* audio_context) {
+ return audio_context->audio_context_manager_;
+ }
+
+ void SetContextState(AudioContext* audio_context,
+ AudioContext::AudioContextState state) {
+ audio_context->SetContextState(state);
+ }
+
private:
std::unique_ptr<ScopedTestingPlatformSupport<AudioContextTestPlatform>>
platform_;
};
TEST_F(AudioContextTest, AudioContextOptions_WebAudioLatencyHint) {
- AudioContextOptions interactive_options;
- interactive_options.setLatencyHint(
+ AudioContextOptions* interactive_options = AudioContextOptions::Create();
+ interactive_options->setLatencyHint(
AudioContextLatencyCategoryOrDouble::FromAudioContextLatencyCategory(
"interactive"));
AudioContext* interactive_context = AudioContext::Create(
GetDocument(), interactive_options, ASSERT_NO_EXCEPTION);
- AudioContextOptions balanced_options;
- balanced_options.setLatencyHint(
+ AudioContextOptions* balanced_options = AudioContextOptions::Create();
+ balanced_options->setLatencyHint(
AudioContextLatencyCategoryOrDouble::FromAudioContextLatencyCategory(
"balanced"));
AudioContext* balanced_context = AudioContext::Create(
@@ -109,16 +121,16 @@ TEST_F(AudioContextTest, AudioContextOptions_WebAudioLatencyHint) {
EXPECT_GT(balanced_context->baseLatency(),
interactive_context->baseLatency());
- AudioContextOptions playback_options;
- playback_options.setLatencyHint(
+ AudioContextOptions* playback_options = AudioContextOptions::Create();
+ playback_options->setLatencyHint(
AudioContextLatencyCategoryOrDouble::FromAudioContextLatencyCategory(
"playback"));
AudioContext* playback_context = AudioContext::Create(
GetDocument(), playback_options, ASSERT_NO_EXCEPTION);
EXPECT_GT(playback_context->baseLatency(), balanced_context->baseLatency());
- AudioContextOptions exact_too_small_options;
- exact_too_small_options.setLatencyHint(
+ AudioContextOptions* exact_too_small_options = AudioContextOptions::Create();
+ exact_too_small_options->setLatencyHint(
AudioContextLatencyCategoryOrDouble::FromDouble(
interactive_context->baseLatency() / 2));
AudioContext* exact_too_small_context = AudioContext::Create(
@@ -129,15 +141,15 @@ TEST_F(AudioContextTest, AudioContextOptions_WebAudioLatencyHint) {
const double exact_latency_sec =
(interactive_context->baseLatency() + playback_context->baseLatency()) /
2;
- AudioContextOptions exact_ok_options;
- exact_ok_options.setLatencyHint(
+ AudioContextOptions* exact_ok_options = AudioContextOptions::Create();
+ exact_ok_options->setLatencyHint(
AudioContextLatencyCategoryOrDouble::FromDouble(exact_latency_sec));
AudioContext* exact_ok_context = AudioContext::Create(
GetDocument(), exact_ok_options, ASSERT_NO_EXCEPTION);
EXPECT_EQ(exact_ok_context->baseLatency(), exact_latency_sec);
- AudioContextOptions exact_too_big_options;
- exact_too_big_options.setLatencyHint(
+ AudioContextOptions* exact_too_big_options = AudioContextOptions::Create();
+ exact_too_big_options->setLatencyHint(
AudioContextLatencyCategoryOrDouble::FromDouble(
playback_context->baseLatency() * 2));
AudioContext* exact_too_big_context = AudioContext::Create(
@@ -146,4 +158,17 @@ TEST_F(AudioContextTest, AudioContextOptions_WebAudioLatencyHint) {
playback_context->baseLatency());
}
+TEST_F(AudioContextTest, AudioContextAudibility_ServiceUnbind) {
+ AudioContextOptions* options = AudioContextOptions::Create();
+ AudioContext* audio_context =
+ AudioContext::Create(GetDocument(), options, ASSERT_NO_EXCEPTION);
+
+ audio_context->set_was_audible_for_testing(true);
+ GetAudioContextManagerPtrFor(audio_context).reset();
+ SetContextState(audio_context, AudioContext::AudioContextState::kSuspended);
+
+ ScopedTestingPlatformSupport<TestingPlatformSupport> platform;
+ platform->RunUntilIdle();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.cc
index ac37756aab8..b4050e53f5e 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.cc
@@ -30,7 +30,7 @@
namespace blink {
AudioDestinationHandler::AudioDestinationHandler(AudioNode& node)
- : AudioHandler(kNodeTypeDestination, node, 0), current_sample_frame_(0) {
+ : AudioHandler(kNodeTypeDestination, node, 0) {
AddInput();
}
@@ -48,7 +48,7 @@ AudioDestinationHandler& AudioDestinationNode::GetAudioDestinationHandler()
return static_cast<AudioDestinationHandler&>(Handler());
}
-unsigned long AudioDestinationNode::maxChannelCount() const {
+uint32_t AudioDestinationNode::maxChannelCount() const {
return GetAudioDestinationHandler().MaxChannelCount();
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.h
index c143f860bd3..818b3ac50b9 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_destination_node.h
@@ -26,8 +26,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_AUDIO_DESTINATION_NODE_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_AUDIO_DESTINATION_NODE_H_
+#include <atomic>
#include "third_party/blink/renderer/modules/webaudio/audio_node.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
namespace blink {
@@ -43,7 +43,7 @@ class AudioDestinationHandler : public AudioHandler {
// The method MUST NOT be invoked when rendering a graph because the
// destination node is a sink. Instead, this node gets pulled by the
// underlying renderer (audio hardware or worker thread).
- void Process(size_t) final { NOTREACHED(); }
+ void Process(uint32_t) final { NOTREACHED(); }
virtual void StartRendering() = 0;
virtual void StopRendering() = 0;
@@ -54,7 +54,7 @@ class AudioDestinationHandler : public AudioHandler {
virtual void RestartRendering() = 0;
size_t CurrentSampleFrame() const {
- return AcquireLoad(&current_sample_frame_);
+ return current_sample_frame_.load(std::memory_order_acquire);
}
double CurrentTime() const {
@@ -62,7 +62,7 @@ class AudioDestinationHandler : public AudioHandler {
}
virtual double SampleRate() const = 0;
- virtual unsigned long MaxChannelCount() const = 0;
+ virtual uint32_t MaxChannelCount() const = 0;
void ContextDestroyed() { is_execution_context_destroyed_ = true; }
bool IsExecutionContextDestroyed() const {
@@ -70,10 +70,15 @@ class AudioDestinationHandler : public AudioHandler {
}
protected:
- // The number of sample frames processed by the destination so far.
- size_t current_sample_frame_;
+ void AdvanceCurrentSampleFrame(size_t number_of_frames) {
+ current_sample_frame_.fetch_add(number_of_frames,
+ std::memory_order_release);
+ }
private:
+ // The number of sample frames processed by the destination so far.
+ std::atomic_size_t current_sample_frame_{0};
+
// True if the execution context is being destroyed. If this is true, the
// destination ndoe must avoid checking for or accessing the execution
// context.
@@ -92,7 +97,7 @@ class AudioDestinationNode : public AudioNode {
DEFINE_WRAPPERTYPEINFO();
public:
- unsigned long maxChannelCount() const;
+ uint32_t maxChannelCount() const;
// Returns its own handler object instead of a generic one from
// AudioNode::Handler().
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.cc
index 33574aae5cd..acc8566847e 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.cc
@@ -91,15 +91,15 @@ AudioListener::AudioListener(BaseAudioContext& context)
AudioParamHandler::AutomationRateMode::kVariable)),
last_update_time_(-1),
is_listener_dirty_(false),
- position_x_values_(AudioUtilities::kRenderQuantumFrames),
- position_y_values_(AudioUtilities::kRenderQuantumFrames),
- position_z_values_(AudioUtilities::kRenderQuantumFrames),
- forward_x_values_(AudioUtilities::kRenderQuantumFrames),
- forward_y_values_(AudioUtilities::kRenderQuantumFrames),
- forward_z_values_(AudioUtilities::kRenderQuantumFrames),
- up_x_values_(AudioUtilities::kRenderQuantumFrames),
- up_y_values_(AudioUtilities::kRenderQuantumFrames),
- up_z_values_(AudioUtilities::kRenderQuantumFrames) {
+ position_x_values_(audio_utilities::kRenderQuantumFrames),
+ position_y_values_(audio_utilities::kRenderQuantumFrames),
+ position_z_values_(audio_utilities::kRenderQuantumFrames),
+ forward_x_values_(audio_utilities::kRenderQuantumFrames),
+ forward_y_values_(audio_utilities::kRenderQuantumFrames),
+ forward_z_values_(audio_utilities::kRenderQuantumFrames),
+ up_x_values_(audio_utilities::kRenderQuantumFrames),
+ up_y_values_(audio_utilities::kRenderQuantumFrames),
+ up_z_values_(audio_utilities::kRenderQuantumFrames) {
// Initialize the cached values with the current values. Thus, we don't need
// to notify any panners because we haved moved.
last_position_ = GetPosition();
@@ -148,7 +148,7 @@ bool AudioListener::HasSampleAccurateValues() const {
upZ()->Handler().HasSampleAccurateValues();
}
-void AudioListener::UpdateValuesIfNeeded(size_t frames_to_process) {
+void AudioListener::UpdateValuesIfNeeded(uint32_t frames_to_process) {
double current_time =
positionX()->Handler().DestinationHandler().CurrentTime();
if (last_update_time_ != current_time) {
@@ -192,47 +192,47 @@ void AudioListener::UpdateValuesIfNeeded(size_t frames_to_process) {
}
}
-const float* AudioListener::GetPositionXValues(size_t frames_to_process) {
+const float* AudioListener::GetPositionXValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return position_x_values_.Data();
}
-const float* AudioListener::GetPositionYValues(size_t frames_to_process) {
+const float* AudioListener::GetPositionYValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return position_y_values_.Data();
}
-const float* AudioListener::GetPositionZValues(size_t frames_to_process) {
+const float* AudioListener::GetPositionZValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return position_z_values_.Data();
}
-const float* AudioListener::GetForwardXValues(size_t frames_to_process) {
+const float* AudioListener::GetForwardXValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return forward_x_values_.Data();
}
-const float* AudioListener::GetForwardYValues(size_t frames_to_process) {
+const float* AudioListener::GetForwardYValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return forward_y_values_.Data();
}
-const float* AudioListener::GetForwardZValues(size_t frames_to_process) {
+const float* AudioListener::GetForwardZValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return forward_z_values_.Data();
}
-const float* AudioListener::GetUpXValues(size_t frames_to_process) {
+const float* AudioListener::GetUpXValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return up_x_values_.Data();
}
-const float* AudioListener::GetUpYValues(size_t frames_to_process) {
+const float* AudioListener::GetUpYValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return up_y_values_.Data();
}
-const float* AudioListener::GetUpZValues(size_t frames_to_process) {
+const float* AudioListener::GetUpZValues(uint32_t frames_to_process) {
UpdateValuesIfNeeded(frames_to_process);
return up_z_values_.Data();
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.h
index 71fcae06954..608bd4de29a 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_listener.h
@@ -87,17 +87,17 @@ class AudioListener : public ScriptWrappable {
return FloatPoint3D(up_x_->value(), up_y_->value(), up_z_->value());
}
- const float* GetPositionXValues(size_t frames_to_process);
- const float* GetPositionYValues(size_t frames_to_process);
- const float* GetPositionZValues(size_t frames_to_process);
+ const float* GetPositionXValues(uint32_t frames_to_process);
+ const float* GetPositionYValues(uint32_t frames_to_process);
+ const float* GetPositionZValues(uint32_t frames_to_process);
- const float* GetForwardXValues(size_t frames_to_process);
- const float* GetForwardYValues(size_t frames_to_process);
- const float* GetForwardZValues(size_t frames_to_process);
+ const float* GetForwardXValues(uint32_t frames_to_process);
+ const float* GetForwardYValues(uint32_t frames_to_process);
+ const float* GetForwardZValues(uint32_t frames_to_process);
- const float* GetUpXValues(size_t frames_to_process);
- const float* GetUpYValues(size_t frames_to_process);
- const float* GetUpZValues(size_t frames_to_process);
+ const float* GetUpXValues(uint32_t frames_to_process);
+ const float* GetUpYValues(uint32_t frames_to_process);
+ const float* GetUpZValues(uint32_t frames_to_process);
// Position
void setPosition(float x, float y, float z, ExceptionState& exceptionState) {
@@ -167,7 +167,7 @@ class AudioListener : public ScriptWrappable {
// the audio thread.
bool is_listener_dirty_;
- void UpdateValuesIfNeeded(size_t frames_to_process);
+ void UpdateValuesIfNeeded(uint32_t frames_to_process);
AudioFloatArray position_x_values_;
AudioFloatArray position_y_values_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_node.cc
index f3f1d0d78c2..81343ac7a23 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_node.cc
@@ -32,7 +32,6 @@
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/instance_counters.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
#if DEBUG_AUDIONODE_REFERENCES
#include <stdio.h>
@@ -76,8 +75,6 @@ AudioHandler::AudioHandler(NodeType node_type,
AudioHandler::~AudioHandler() {
DCHECK(IsMainThread());
- // dispose() should be called.
- DCHECK(!GetNode());
InstanceCounters::DecrementCounter(InstanceCounters::kAudioHandlerCounter);
#if DEBUG_AUDIONODE_REFERENCES
--node_count_[GetNodeType()];
@@ -111,7 +108,6 @@ void AudioHandler::Dispose() {
Context()->GetDeferredTaskHandler().RemoveAutomaticPullNode(this);
for (auto& output : outputs_)
output->Dispose();
- node_ = nullptr;
}
AudioNode* AudioHandler::GetNode() const {
@@ -203,7 +199,7 @@ AudioNodeOutput& AudioHandler::Output(unsigned i) {
return *outputs_[i];
}
-unsigned long AudioHandler::ChannelCount() {
+unsigned AudioHandler::ChannelCount() {
return channel_count_;
}
@@ -218,7 +214,7 @@ void AudioHandler::SetInternalChannelInterpretation(
new_channel_interpretation_ = interpretation;
}
-void AudioHandler::SetChannelCount(unsigned long channel_count,
+void AudioHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -316,7 +312,7 @@ void AudioHandler::UpdateChannelsForInputs() {
input->ChangedOutputs();
}
-void AudioHandler::ProcessIfNecessary(size_t frames_to_process) {
+void AudioHandler::ProcessIfNecessary(uint32_t frames_to_process) {
DCHECK(Context()->IsAudioThread());
if (!IsInitialized())
@@ -378,7 +374,7 @@ bool AudioHandler::PropagatesSilence() const {
Context()->currentTime();
}
-void AudioHandler::PullInputs(size_t frames_to_process) {
+void AudioHandler::PullInputs(uint32_t frames_to_process) {
DCHECK(Context()->IsAudioThread());
// Process all of the AudioNodes connected to our inputs.
@@ -453,10 +449,9 @@ void AudioHandler::DisableOutputsIfNecessary() {
// the outputs so that the tail for the node can be output.
// Otherwise, we can disable the outputs right away.
if (RequiresTailProcessing()) {
- if (Context()->ContextState() !=
- BaseAudioContext::AudioContextState::kClosed) {
- Context()->GetDeferredTaskHandler().AddTailProcessingHandler(this);
- }
+ auto& deferred_task_handler = Context()->GetDeferredTaskHandler();
+ if (deferred_task_handler.AcceptsTailProcessing())
+ deferred_task_handler.AddTailProcessingHandler(this);
} else {
DisableOutputs();
}
@@ -470,7 +465,8 @@ void AudioHandler::DisableOutputs() {
}
void AudioHandler::MakeConnection() {
- AtomicIncrement(&connection_ref_count_);
+ Context()->AssertGraphOwner();
+ connection_ref_count_++;
#if DEBUG_AUDIONODE_REFERENCES
fprintf(
@@ -512,8 +508,7 @@ void AudioHandler::BreakConnection() {
void AudioHandler::BreakConnectionWithLock() {
Context()->AssertGraphOwner();
-
- AtomicDecrement(&connection_ref_count_);
+ connection_ref_count_--;
#if DEBUG_AUDIONODE_REFERENCES
fprintf(stderr,
@@ -618,11 +613,11 @@ void AudioNode::Dispose() {
if (context()->HasRealtimeConstraint()) {
// Add the handler to the orphan list if the context is not
- // closed. (Nothing will clean up the orphan list if the context
- // is closed.) These will get cleaned up in the post render task
+ // uninitialized (Nothing will clean up the orphan list if the context
+ // is uninitialized.) These will get cleaned up in the post render task
// if audio thread is running or when the context is colleced (in
// the worst case).
- if (context()->ContextState() != BaseAudioContext::kClosed) {
+ if (!context()->IsContextClosed()) {
context()->GetDeferredTaskHandler().AddRenderingOrphanHandler(
std::move(handler_));
}
@@ -659,16 +654,16 @@ void AudioNode::Trace(blink::Visitor* visitor) {
EventTargetWithInlineData::Trace(visitor);
}
-void AudioNode::HandleChannelOptions(const AudioNodeOptions& options,
+void AudioNode::HandleChannelOptions(const AudioNodeOptions* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
- if (options.hasChannelCount())
- setChannelCount(options.channelCount(), exception_state);
- if (options.hasChannelCountMode())
- setChannelCountMode(options.channelCountMode(), exception_state);
- if (options.hasChannelInterpretation())
- setChannelInterpretation(options.channelInterpretation(), exception_state);
+ if (options->hasChannelCount())
+ setChannelCount(options->channelCount(), exception_state);
+ if (options->hasChannelCountMode())
+ setChannelCountMode(options->channelCountMode(), exception_state);
+ if (options->hasChannelInterpretation())
+ setChannelInterpretation(options->channelInterpretation(), exception_state);
}
BaseAudioContext* AudioNode::context() const {
@@ -737,8 +732,10 @@ AudioNode* AudioNode::connect(AudioNode* destination,
destination->Handler()
.Input(input_index)
.Connect(Handler().Output(output_index));
- if (!connected_nodes_[output_index])
- connected_nodes_[output_index] = new HeapHashSet<Member<AudioNode>>();
+ if (!connected_nodes_[output_index]) {
+ connected_nodes_[output_index] =
+ MakeGarbageCollected<HeapHashSet<Member<AudioNode>>>();
+ }
connected_nodes_[output_index]->insert(destination);
Handler().UpdatePullStatusIfNeeded();
@@ -783,8 +780,10 @@ void AudioNode::connect(AudioParam* param,
}
param->Handler().Connect(Handler().Output(output_index));
- if (!connected_params_[output_index])
- connected_params_[output_index] = new HeapHashSet<Member<AudioParam>>();
+ if (!connected_params_[output_index]) {
+ connected_params_[output_index] =
+ MakeGarbageCollected<HeapHashSet<Member<AudioParam>>>();
+ }
connected_params_[output_index]->insert(param);
Handler().UpdatePullStatusIfNeeded();
@@ -1024,11 +1023,11 @@ unsigned AudioNode::numberOfOutputs() const {
return Handler().NumberOfOutputs();
}
-unsigned long AudioNode::channelCount() const {
+unsigned AudioNode::channelCount() const {
return Handler().ChannelCount();
}
-void AudioNode::setChannelCount(unsigned long count,
+void AudioNode::setChannelCount(unsigned count,
ExceptionState& exception_state) {
Handler().SetChannelCount(count, exception_state);
}
@@ -1052,7 +1051,7 @@ void AudioNode::setChannelInterpretation(const String& interpretation,
}
const AtomicString& AudioNode::InterfaceName() const {
- return EventTargetNames::AudioNode;
+ return event_target_names::kAudioNode;
}
ExecutionContext* AudioNode::GetExecutionContext() const {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_node.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_node.h
index be391ade062..a89174b2969 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_node.h
@@ -32,6 +32,7 @@
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/audio/audio_bus.h"
#include "third_party/blink/renderer/platform/audio/audio_utilities.h"
+#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -108,10 +109,11 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
// Do not release resources used by an audio rendering thread in dispose().
virtual void Dispose();
- // GetNode() returns a valid object until dispose() is called. This returns
- // nullptr after dispose(). We must not call GetNode() in an audio rendering
- // thread.
+ // GetNode() returns a valid object until the AudioNode is collected on the
+ // main thread, and nullptr thereafter. We must not call GetNode() in an audio
+ // rendering thread.
AudioNode* GetNode() const;
+
// context() returns a valid object until the BaseAudioContext dies, and
// returns nullptr otherwise. This always returns a valid object in an audio
// rendering thread, and inside dispose(). We must not call context() in the
@@ -141,12 +143,12 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
// when process() is called. Subclasses will take this input data and put the
// results in the AudioBus(s) of its AudioNodeOutput(s) (if any).
// Called from context's audio thread.
- virtual void Process(size_t frames_to_process) = 0;
+ virtual void Process(uint32_t frames_to_process) = 0;
// Like process(), but only causes the automations to process; the
// normal processing of the node is bypassed. By default, we assume
// no AudioParams need to be updated.
- virtual void ProcessOnlyAudioParams(size_t frames_to_process){};
+ virtual void ProcessOnlyAudioParams(uint32_t frames_to_process){};
// No significant resources should be allocated until initialize() is called.
// Processing may not occur until a node is initialized.
@@ -171,7 +173,7 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
// will only process once per rendering time quantum even if it's called
// repeatedly. This handles the case of "fanout" where an output is connected
// to multiple AudioNode inputs. Called from context's audio thread.
- void ProcessIfNecessary(size_t frames_to_process);
+ void ProcessIfNecessary(uint32_t frames_to_process);
// Called when a new connection has been made to one of our inputs or the
// connection number of channels has changed. This potentially gives us
@@ -220,8 +222,8 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
void DisableOutputsIfNecessary();
void DisableOutputs();
- unsigned long ChannelCount();
- virtual void SetChannelCount(unsigned long, ExceptionState&);
+ unsigned ChannelCount();
+ virtual void SetChannelCount(unsigned, ExceptionState&);
String GetChannelCountMode();
virtual void SetChannelCountMode(const String&, ExceptionState&);
@@ -253,7 +255,7 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
// connected to us to process. Each rendering quantum, the audio data for
// each of the AudioNode's inputs will be available after this method is
// called. Called from context's audio thread.
- virtual void PullInputs(size_t frames_to_process);
+ virtual void PullInputs(uint32_t frames_to_process);
// Force all inputs to take any channel interpretation changes into account.
void UpdateChannelsForInputs();
@@ -261,14 +263,11 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
private:
void SetNodeType(NodeType);
- volatile bool is_initialized_;
+ bool is_initialized_;
NodeType node_type_;
- // The owner AudioNode. This untraced member is safe because dispose() is
- // called before the AudioNode death, and it clears |node_|. Do not access
- // |node_| directly, use GetNode() instead.
- // See http://crbug.com/404527 for the detail.
- UntracedMember<AudioNode> node_;
+ // The owner AudioNode. Accessed only on the main thread.
+ const WeakPersistent<AudioNode> node_;
// This untraced member is safe because this is cleared for all of live
// AudioHandlers when the BaseAudioContext dies. Do not access m_context
@@ -282,7 +281,7 @@ class MODULES_EXPORT AudioHandler : public ThreadSafeRefCounted<AudioHandler> {
double last_processing_time_;
double last_non_silent_time_;
- volatile int connection_ref_count_;
+ int connection_ref_count_;
bool is_disabled_;
@@ -320,7 +319,7 @@ class MODULES_EXPORT AudioNode : public EventTargetWithInlineData {
void Trace(blink::Visitor*) override;
AudioHandler& Handler() const;
- void HandleChannelOptions(const AudioNodeOptions&, ExceptionState&);
+ void HandleChannelOptions(const AudioNodeOptions*, ExceptionState&);
AudioNode* connect(AudioNode*,
unsigned output_index,
@@ -340,8 +339,8 @@ class MODULES_EXPORT AudioNode : public EventTargetWithInlineData {
BaseAudioContext* context() const;
unsigned numberOfInputs() const;
unsigned numberOfOutputs() const;
- unsigned long channelCount() const;
- void setChannelCount(unsigned long, ExceptionState&);
+ unsigned channelCount() const;
+ void setChannelCount(unsigned, ExceptionState&);
String channelCountMode() const;
void setChannelCountMode(const String&, ExceptionState&);
String channelInterpretation() const;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.cc
index 0e557c93e54..178b1bf0a39 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.cc
@@ -38,7 +38,7 @@ inline AudioNodeInput::AudioNodeInput(AudioHandler& handler)
handler_(handler) {
// Set to mono by default.
internal_summing_bus_ =
- AudioBus::Create(1, AudioUtilities::kRenderQuantumFrames);
+ AudioBus::Create(1, audio_utilities::kRenderQuantumFrames);
}
std::unique_ptr<AudioNodeInput> AudioNodeInput::Create(AudioHandler& handler) {
@@ -123,7 +123,7 @@ void AudioNodeInput::UpdateInternalBus() {
return;
internal_summing_bus_ = AudioBus::Create(
- number_of_input_channels, AudioUtilities::kRenderQuantumFrames);
+ number_of_input_channels, audio_utilities::kRenderQuantumFrames);
}
unsigned AudioNodeInput::NumberOfChannels() const {
@@ -168,7 +168,7 @@ AudioBus* AudioNodeInput::InternalSummingBus() {
}
void AudioNodeInput::SumAllConnections(AudioBus* summing_bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(GetDeferredTaskHandler().IsAudioThread());
// We shouldn't be calling this method if there's only one connection, since
@@ -198,7 +198,7 @@ void AudioNodeInput::SumAllConnections(AudioBus* summing_bus,
}
AudioBus* AudioNodeInput::Pull(AudioBus* in_place_bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(GetDeferredTaskHandler().IsAudioThread());
// Handle single connection case.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.h
index 85b5048bcb8..ae8a7b66fcf 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_input.h
@@ -72,7 +72,7 @@ class AudioNodeInput final : public AudioSummingJunction {
// where possible using inPlaceBus. It returns the bus which it rendered
// into, returning inPlaceBus if in-place processing was performed.
// Called from context's audio thread.
- AudioBus* Pull(AudioBus* in_place_bus, size_t frames_to_process);
+ AudioBus* Pull(AudioBus* in_place_bus, uint32_t frames_to_process);
// bus() contains the rendered audio after pull() has been called for each
// time quantum.
@@ -107,7 +107,7 @@ class AudioNodeInput final : public AudioSummingJunction {
// Called from context's audio thread.
AudioBus* InternalSummingBus();
- void SumAllConnections(AudioBus* summing_bus, size_t frames_to_process);
+ void SumAllConnections(AudioBus* summing_bus, uint32_t frames_to_process);
scoped_refptr<AudioBus> internal_summing_bus_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.cc
index a90d51e2c62..def68ddfe37 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.cc
@@ -47,7 +47,7 @@ inline AudioNodeOutput::AudioNodeOutput(AudioHandler* handler,
DCHECK_LE(number_of_channels, BaseAudioContext::MaxNumberOfChannels());
internal_bus_ = AudioBus::Create(number_of_channels,
- AudioUtilities::kRenderQuantumFrames);
+ audio_utilities::kRenderQuantumFrames);
}
std::unique_ptr<AudioNodeOutput> AudioNodeOutput::Create(
@@ -88,7 +88,7 @@ void AudioNodeOutput::UpdateInternalBus() {
return;
internal_bus_ = AudioBus::Create(NumberOfChannels(),
- AudioUtilities::kRenderQuantumFrames);
+ audio_utilities::kRenderQuantumFrames);
}
void AudioNodeOutput::UpdateRenderingState() {
@@ -121,7 +121,7 @@ void AudioNodeOutput::PropagateChannelCount() {
}
AudioBus* AudioNodeOutput::Pull(AudioBus* in_place_bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(GetDeferredTaskHandler().IsAudioThread());
DCHECK(rendering_fan_out_count_ > 0 || rendering_param_fan_out_count_ > 0);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.h
index dd76a98dd6c..b8d63521d9d 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_node_output.h
@@ -53,7 +53,7 @@ class AudioNodeOutput final {
// quantum. It returns the bus containing the processed audio for this
// output, returning inPlaceBus if in-place processing was possible. Called
// from context's audio thread.
- AudioBus* Pull(AudioBus* in_place_bus, size_t frames_to_process);
+ AudioBus* Pull(AudioBus* in_place_bus, uint32_t frames_to_process);
// bus() will contain the rendered audio after pull() is called for each
// rendering time quantum.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_param.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_param.cc
index 24f4820c89b..70af68e84cc 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_param.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_param.cc
@@ -54,7 +54,7 @@ AudioParamHandler::AudioParamHandler(BaseAudioContext& context,
min_value_(min_value),
max_value_(max_value),
summing_bus_(
- AudioBus::Create(1, AudioUtilities::kRenderQuantumFrames, false)) {
+ AudioBus::Create(1, audio_utilities::kRenderQuantumFrames, false)) {
// The destination MUST exist because we need the destination handler for the
// AudioParam.
CHECK(context.destination());
@@ -264,7 +264,7 @@ void AudioParamHandler::CalculateFinalValues(float* values,
// together (unity-gain summing junction). Note that connections would
// normally be mono, but we mix down to mono if necessary.
if (NumberOfRenderingConnections() > 0) {
- DCHECK_LE(number_of_values, AudioUtilities::kRenderQuantumFrames);
+ DCHECK_LE(number_of_values, audio_utilities::kRenderQuantumFrames);
summing_bus_->SetChannelMemory(0, values, number_of_values);
@@ -274,7 +274,7 @@ void AudioParamHandler::CalculateFinalValues(float* values,
// Render audio from this output.
AudioBus* connection_bus =
- output->Pull(nullptr, AudioUtilities::kRenderQuantumFrames);
+ output->Pull(nullptr, audio_utilities::kRenderQuantumFrames);
// Sum, with unity-gain.
summing_bus_->SumFrom(*connection_bus);
@@ -286,7 +286,7 @@ void AudioParamHandler::CalculateTimelineValues(float* values,
unsigned number_of_values) {
// Calculate values for this render quantum. Normally
// |numberOfValues| will equal to
- // AudioUtilities::kRenderQuantumFrames (the render quantum size).
+ // audio_utilities::kRenderQuantumFrames (the render quantum size).
double sample_rate = DestinationHandler().SampleRate();
size_t start_frame = DestinationHandler().CurrentSampleFrame();
size_t end_frame = start_frame + number_of_values;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_param_map.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_param_map.h
index 052b53b37e4..8d16542493c 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_param_map.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_param_map.h
@@ -26,7 +26,7 @@ class AudioParamMap final : public ScriptWrappable,
const HeapHashMap<String, Member<AudioParam>>& parameter_map);
// IDL attributes / methods
- size_t size() const { return parameter_map_.size(); }
+ uint32_t size() const { return parameter_map_.size(); }
AudioParam* At(String name) { return parameter_map_.at(name); }
bool Contains(String name) { return parameter_map_.Contains(name); }
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.cc
index 139b8c50bc2..cd7ad2e7b64 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.cc
@@ -642,7 +642,7 @@ bool AudioParamTimeline::HasValues(size_t current_frame,
// Need automation if the event starts somewhere before the
// end of the current render quantum.
return events_[0]->Time() <=
- (current_frame + AudioUtilities::kRenderQuantumFrames) /
+ (current_frame + audio_utilities::kRenderQuantumFrames) /
sample_rate;
default:
// Otherwise, there's some kind of other event running, so we
@@ -675,7 +675,7 @@ void AudioParamTimeline::CancelScheduledValues(
MutexLocker locker(events_lock_);
// Remove all events starting at startTime.
- for (unsigned i = 0; i < events_.size(); ++i) {
+ for (wtf_size_t i = 0; i < events_.size(); ++i) {
if (events_[i]->Time() >= start_time) {
RemoveCancelledEvents(i);
break;
@@ -692,7 +692,7 @@ void AudioParamTimeline::CancelAndHoldAtTime(double cancel_time,
MutexLocker locker(events_lock_);
- unsigned i;
+ wtf_size_t i;
// Find the first event at or just past cancelTime.
for (i = 0; i < events_.size(); ++i) {
if (events_[i]->Time() > cancel_time) {
@@ -702,7 +702,7 @@ void AudioParamTimeline::CancelAndHoldAtTime(double cancel_time,
// The event that is being cancelled. This is the event just past
// cancelTime, if any.
- unsigned cancelled_event_index = i;
+ wtf_size_t cancelled_event_index = i;
// If the event just before cancelTime is a SetTarget or SetValueCurve
// event, we need to handle that event specially instead of the event after.
@@ -821,7 +821,7 @@ float AudioParamTimeline::ValueForContextTime(
double sample_rate = audio_destination.SampleRate();
size_t start_frame = audio_destination.CurrentSampleFrame();
// One parameter change per render quantum.
- double control_rate = sample_rate / AudioUtilities::kRenderQuantumFrames;
+ double control_rate = sample_rate / audio_utilities::kRenderQuantumFrames;
value =
ValuesForFrameRange(start_frame, start_frame + 1, default_value, &value,
1, sample_rate, control_rate, min_value, max_value);
@@ -854,8 +854,8 @@ float AudioParamTimeline::ValuesForFrameRange(size_t start_frame,
number_of_values, sample_rate, control_rate);
// Clamp the values now to the nominal range
- VectorMath::Vclip(values, 1, &min_value, &max_value, values, 1,
- number_of_values);
+ vector_math::Vclip(values, 1, &min_value, &max_value, values, 1,
+ number_of_values);
return last_value;
}
@@ -1212,7 +1212,7 @@ bool AudioParamTimeline::HandleAllEventsInThePast(double current_time,
// the curve, so we don't need to worry that SetValueCurve time is a
// start time, not an end time.
if (last_event_time +
- 1.5 * AudioUtilities::kRenderQuantumFrames / sample_rate <
+ 1.5 * audio_utilities::kRenderQuantumFrames / sample_rate <
current_time) {
// If the last event is SetTarget, make sure we've converged and, that
// we're at least 5 time constants past the start of the event. If not, we
@@ -1291,7 +1291,7 @@ void AudioParamTimeline::ProcessSetTargetFollowedByRamp(
// SetTarget has already started. Update |value| one frame because it's
// the value from the previous frame.
float discrete_time_constant =
- static_cast<float>(AudioUtilities::DiscreteTimeConstantForSampleRate(
+ static_cast<float>(audio_utilities::DiscreteTimeConstantForSampleRate(
event->TimeConstant(), control_rate));
value += (event->Value() - value) * discrete_time_constant;
}
@@ -1560,7 +1560,7 @@ std::tuple<size_t, float, unsigned> AudioParamTimeline::ProcessSetTarget(
float target = value1;
float time_constant = event->TimeConstant();
float discrete_time_constant =
- static_cast<float>(AudioUtilities::DiscreteTimeConstantForSampleRate(
+ static_cast<float>(audio_utilities::DiscreteTimeConstantForSampleRate(
time_constant, control_rate));
// Set the starting value correctly. This is only needed when the
@@ -1864,8 +1864,8 @@ std::tuple<size_t, float, unsigned> AudioParamTimeline::ProcessCancelValues(
float target = events_[event_index - 1]->Value();
float time_constant = events_[event_index - 1]->TimeConstant();
float discrete_time_constant = static_cast<float>(
- AudioUtilities::DiscreteTimeConstantForSampleRate(time_constant,
- control_rate));
+ audio_utilities::DiscreteTimeConstantForSampleRate(time_constant,
+ control_rate));
value += (target - value) * discrete_time_constant;
}
}
@@ -1880,11 +1880,11 @@ std::tuple<size_t, float, unsigned> AudioParamTimeline::ProcessCancelValues(
return std::make_tuple(current_frame, value, write_index);
}
-unsigned AudioParamTimeline::FillWithDefault(float* values,
+uint32_t AudioParamTimeline::FillWithDefault(float* values,
float default_value,
- size_t end_frame,
- unsigned write_index) {
- size_t index = write_index;
+ uint32_t end_frame,
+ uint32_t write_index) {
+ uint32_t index = write_index;
for (; index < end_frame; ++index)
values[index] = default_value;
@@ -1892,11 +1892,12 @@ unsigned AudioParamTimeline::FillWithDefault(float* values,
return index;
}
-void AudioParamTimeline::RemoveCancelledEvents(size_t first_event_to_remove) {
+void AudioParamTimeline::RemoveCancelledEvents(
+ wtf_size_t first_event_to_remove) {
// For all the events that are being removed, also remove that event
// from |new_events_|.
if (new_events_.size() > 0) {
- for (size_t k = first_event_to_remove; k < events_.size(); ++k) {
+ for (wtf_size_t k = first_event_to_remove; k < events_.size(); ++k) {
new_events_.erase(events_[k].get());
}
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.h
index e0cf3cd4825..34fe05fb890 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_param_timeline.h
@@ -440,14 +440,14 @@ class AudioParamTimeline {
// Fill the output vector |values| with the value |defaultValue|,
// starting at |writeIndex| and continuing up to |endFrame|
// (exclusive). |writeIndex| is updated with the new index.
- unsigned FillWithDefault(float* values,
+ uint32_t FillWithDefault(float* values,
float default_value,
- size_t end_frame,
- unsigned write_index);
+ uint32_t end_frame,
+ uint32_t write_index);
// When cancelling events, remove the items from |events_| starting
// at the given index. Update |new_events_| too.
- void RemoveCancelledEvents(size_t first_event_to_remove);
+ void RemoveCancelledEvents(wtf_size_t first_event_to_remove);
// Vector of all automation events for the AudioParam. Access must
// be locked via m_eventsLock.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.cc
index b580ddffe2a..c5629a61be9 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.cc
@@ -42,7 +42,7 @@ AudioProcessingEvent* AudioProcessingEvent::Create(AudioBuffer* input_buffer,
AudioProcessingEvent* AudioProcessingEvent::Create(
const AtomicString& type,
- const AudioProcessingEventInit& initializer) {
+ const AudioProcessingEventInit* initializer) {
return new AudioProcessingEvent(type, initializer);
}
@@ -51,24 +51,24 @@ AudioProcessingEvent::AudioProcessingEvent() = default;
AudioProcessingEvent::AudioProcessingEvent(AudioBuffer* input_buffer,
AudioBuffer* output_buffer,
double playback_time)
- : Event(EventTypeNames::audioprocess, Bubbles::kYes, Cancelable::kNo),
+ : Event(event_type_names::kAudioprocess, Bubbles::kYes, Cancelable::kNo),
input_buffer_(input_buffer),
output_buffer_(output_buffer),
playback_time_(playback_time) {}
AudioProcessingEvent::AudioProcessingEvent(
const AtomicString& type,
- const AudioProcessingEventInit& initializer)
+ const AudioProcessingEventInit* initializer)
: Event(type, initializer) {
- input_buffer_ = initializer.inputBuffer();
- output_buffer_ = initializer.outputBuffer();
- playback_time_ = initializer.playbackTime();
+ input_buffer_ = initializer->inputBuffer();
+ output_buffer_ = initializer->outputBuffer();
+ playback_time_ = initializer->playbackTime();
}
AudioProcessingEvent::~AudioProcessingEvent() = default;
const AtomicString& AudioProcessingEvent::InterfaceName() const {
- return EventNames::AudioProcessingEvent;
+ return event_interface_names::kAudioProcessingEvent;
}
void AudioProcessingEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.h
index 4c31db8f0d0..705a3d448bb 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_processing_event.h
@@ -46,7 +46,7 @@ class AudioProcessingEvent final : public Event {
double playback_time);
static AudioProcessingEvent* Create(const AtomicString& type,
- const AudioProcessingEventInit&);
+ const AudioProcessingEventInit*);
~AudioProcessingEvent() override;
@@ -64,7 +64,7 @@ class AudioProcessingEvent final : public Event {
AudioBuffer* output_buffer,
double playback_time);
AudioProcessingEvent(const AtomicString& type,
- const AudioProcessingEventInit&);
+ const AudioProcessingEventInit*);
Member<AudioBuffer> input_buffer_;
Member<AudioBuffer> output_buffer_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc
index 4c6c0e4baa3..767cd033749 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_scheduled_source_node.cc
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -69,8 +69,8 @@ AudioScheduledSourceHandler::UpdateSchedulingInfo(size_t quantum_frame_size,
}
DCHECK_EQ(quantum_frame_size,
- static_cast<size_t>(AudioUtilities::kRenderQuantumFrames));
- if (quantum_frame_size != AudioUtilities::kRenderQuantumFrames) {
+ static_cast<size_t>(audio_utilities::kRenderQuantumFrames));
+ if (quantum_frame_size != audio_utilities::kRenderQuantumFrames) {
return std::make_tuple(quantum_frame_offset, non_silent_frames_to_process,
start_frame_offset);
}
@@ -84,11 +84,11 @@ AudioScheduledSourceHandler::UpdateSchedulingInfo(size_t quantum_frame_size,
size_t quantum_start_frame = Context()->CurrentSampleFrame();
size_t quantum_end_frame = quantum_start_frame + quantum_frame_size;
size_t start_frame =
- AudioUtilities::TimeToSampleFrame(start_time_, sample_rate);
+ audio_utilities::TimeToSampleFrame(start_time_, sample_rate);
size_t end_frame =
end_time_ == kUnknownTime
? 0
- : AudioUtilities::TimeToSampleFrame(end_time_, sample_rate);
+ : audio_utilities::TimeToSampleFrame(end_time_, sample_rate);
// If we know the end time and it's already passed, then don't bother doing
// any more rendering this cycle.
@@ -252,7 +252,7 @@ void AudioScheduledSourceHandler::NotifyEnded() {
if (!Context() || !Context()->GetExecutionContext())
return;
if (GetNode())
- GetNode()->DispatchEvent(*Event::Create(EventTypeNames::ended));
+ GetNode()->DispatchEvent(*Event::Create(event_type_names::kEnded));
}
// ----------------------------------------------------------------
@@ -284,11 +284,11 @@ void AudioScheduledSourceNode::stop(double when,
}
EventListener* AudioScheduledSourceNode::onended() {
- return GetAttributeEventListener(EventTypeNames::ended);
+ return GetAttributeEventListener(event_type_names::kEnded);
}
void AudioScheduledSourceNode::setOnended(EventListener* listener) {
- SetAttributeEventListener(EventTypeNames::ended, listener);
+ SetAttributeEventListener(event_type_names::kEnded, listener);
}
bool AudioScheduledSourceNode::HasPendingActivity() const {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc
index 718ef75dbb8..b5f727fb2d5 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.cc
@@ -110,7 +110,7 @@ void AudioWorkletGlobalScope::registerProcessor(
// of |AudioParamDescriptor| and pass it to the definition.
if (did_get_parameter_descriptor &&
!parameter_descriptors_value_local->IsNullOrUndefined()) {
- HeapVector<AudioParamDescriptor> audio_param_descriptors =
+ HeapVector<Member<AudioParamDescriptor>> audio_param_descriptors =
NativeValueTraits<IDLSequence<AudioParamDescriptor>>::NativeValue(
isolate, parameter_descriptors_value_local, exception_state);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.h
index ce29470c280..d6154430dff 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.h
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/modules/webaudio/audio_param_descriptor.h"
#include "third_party/blink/renderer/platform/audio/audio_array.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -126,11 +127,12 @@ class MODULES_EXPORT AudioWorkletGlobalScope final : public WorkletGlobalScope {
float sample_rate_ = 0.0;
};
-DEFINE_TYPE_CASTS(AudioWorkletGlobalScope,
- ExecutionContext,
- context,
- context->IsAudioWorkletGlobalScope(),
- context.IsAudioWorkletGlobalScope());
+template <>
+struct DowncastTraits<AudioWorkletGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsAudioWorkletGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope_test.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope_test.cc
index 80b166f42dd..c60b0414d34 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope_test.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope_test.cc
@@ -21,6 +21,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/messaging/message_channel.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
@@ -28,7 +29,6 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#include "third_party/blink/renderer/modules/webaudio/audio_buffer.h"
@@ -39,7 +39,6 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding_macros.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
@@ -69,15 +68,15 @@ class AudioWorkletGlobalScopeTest : public PageTestBase {
Document* document = &GetDocument();
thread->Start(
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
- Vector<CSPHeaderAndType>(), document->GetReferrerPolicy(),
- document->GetSecurityOrigin(), document->IsSecureContext(),
- document->GetHttpsState(), nullptr /* worker_clients */,
- document->AddressSpace(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */, Vector<CSPHeaderAndType>(),
+ document->GetReferrerPolicy(), document->GetSecurityOrigin(),
+ document->IsSecureContext(), document->GetHttpsState(),
+ nullptr /* worker_clients */, document->AddressSpace(),
OriginTrialContext::GetTokens(document).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap),
- base::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
+ base::nullopt, std::make_unique<WorkerDevToolsParams>(),
ParentExecutionContextTaskRunners::Create());
return thread;
}
@@ -137,8 +136,8 @@ class AudioWorkletGlobalScopeTest : public PageTestBase {
KURL js_url("https://example.com/worklet.js");
ScriptModule module = ScriptModule::Compile(
script_state->GetIsolate(), source_code, js_url, js_url,
- ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
EXPECT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(script_state);
EXPECT_TRUE(exception.IsEmpty());
@@ -154,7 +153,7 @@ class AudioWorkletGlobalScopeTest : public PageTestBase {
WaitableEvent* wait_event) {
EXPECT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAudioWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AudioWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
@@ -202,7 +201,7 @@ class AudioWorkletGlobalScopeTest : public PageTestBase {
WaitableEvent* wait_event) {
EXPECT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAudioWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AudioWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
@@ -257,7 +256,7 @@ class AudioWorkletGlobalScopeTest : public PageTestBase {
WaitableEvent* wait_event) {
EXPECT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAudioWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AudioWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
@@ -323,7 +322,7 @@ class AudioWorkletGlobalScopeTest : public PageTestBase {
WaitableEvent* wait_event) {
EXPECT_TRUE(thread->IsCurrentThread());
- auto* global_scope = ToAudioWorkletGlobalScope(thread->GlobalScope());
+ auto* global_scope = To<AudioWorkletGlobalScope>(thread->GlobalScope());
ScriptState* script_state =
global_scope->ScriptController()->GetScriptState();
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_messaging_proxy.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_messaging_proxy.cc
index b9d26b3fa31..63750f23866 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_messaging_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_messaging_proxy.cc
@@ -4,6 +4,8 @@
#include "third_party/blink/renderer/modules/webaudio/audio_worklet_messaging_proxy.h"
+#include <utility>
+
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
@@ -47,9 +49,9 @@ void AudioWorkletMessagingProxy::CreateProcessorOnRenderingThread(
scoped_refptr<SerializedScriptValue> node_options) {
DCHECK(worker_thread->IsCurrentThread());
AudioWorkletGlobalScope* global_scope =
- ToAudioWorkletGlobalScope(worker_thread->GlobalScope());
- AudioWorkletProcessor* processor =
- global_scope->CreateProcessor(name, message_port_channel, node_options);
+ To<AudioWorkletGlobalScope>(worker_thread->GlobalScope());
+ AudioWorkletProcessor* processor = global_scope->CreateProcessor(
+ name, message_port_channel, std::move(node_options));
handler->SetProcessorOnRenderThread(processor);
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.cc
index cee79bc7253..055cb2b54a2 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.cc
@@ -22,6 +22,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -30,32 +31,30 @@ AudioWorkletHandler::AudioWorkletHandler(
float sample_rate,
String name,
HashMap<String, scoped_refptr<AudioParamHandler>> param_handler_map,
- const AudioWorkletNodeOptions& options)
+ const AudioWorkletNodeOptions* options)
: AudioHandler(kNodeTypeAudioWorklet, node, sample_rate),
name_(name),
param_handler_map_(param_handler_map) {
DCHECK(IsMainThread());
for (const auto& param_name : param_handler_map_.Keys()) {
- param_value_map_.Set(
- param_name,
- std::make_unique<AudioFloatArray>(
- AudioUtilities::kRenderQuantumFrames));
+ param_value_map_.Set(param_name,
+ std::make_unique<AudioFloatArray>(
+ audio_utilities::kRenderQuantumFrames));
}
- for (unsigned i = 0; i < options.numberOfInputs(); ++i) {
+ for (unsigned i = 0; i < options->numberOfInputs(); ++i) {
AddInput();
}
- if (options.hasOutputChannelCount()) {
+ if (options->hasOutputChannelCount()) {
is_output_channel_count_given_ = true;
}
- for (unsigned i = 0; i < options.numberOfOutputs(); ++i) {
- // If |options.outputChannelCount| unspecified, all outputs are mono.
- AddOutput(is_output_channel_count_given_
- ? options.outputChannelCount()[i]
- : 1);
+ for (unsigned i = 0; i < options->numberOfOutputs(); ++i) {
+ // If |options->outputChannelCount| unspecified, all outputs are mono.
+ AddOutput(is_output_channel_count_given_ ? options->outputChannelCount()[i]
+ : 1);
}
if (Context()->GetExecutionContext()) {
@@ -78,12 +77,12 @@ scoped_refptr<AudioWorkletHandler> AudioWorkletHandler::Create(
float sample_rate,
String name,
HashMap<String, scoped_refptr<AudioParamHandler>> param_handler_map,
- const AudioWorkletNodeOptions& options) {
+ const AudioWorkletNodeOptions* options) {
return base::AdoptRef(new AudioWorkletHandler(node, sample_rate, name,
param_handler_map, options));
}
-void AudioWorkletHandler::Process(size_t frames_to_process) {
+void AudioWorkletHandler::Process(uint32_t frames_to_process) {
DCHECK(Context()->IsAudioThread());
// Render and update the node state when the processor is ready with no error.
@@ -106,7 +105,7 @@ void AudioWorkletHandler::Process(size_t frames_to_process) {
AudioFloatArray* param_values = param_value_map_.at(param_name);
if (param_handler->HasSampleAccurateValues()) {
param_handler->CalculateSampleAccurateValues(
- param_values->Data(), frames_to_process);
+ param_values->Data(), static_cast<uint32_t>(frames_to_process));
} else {
std::fill(param_values->Data(),
param_values->Data() + frames_to_process,
@@ -218,11 +217,10 @@ void AudioWorkletHandler::NotifyProcessorError(
AudioWorkletNode::AudioWorkletNode(
BaseAudioContext& context,
const String& name,
- const AudioWorkletNodeOptions& options,
+ const AudioWorkletNodeOptions* options,
const Vector<CrossThreadAudioParamInfo> param_info_list,
MessagePort* node_port)
- : AudioNode(context),
- node_port_(node_port) {
+ : AudioNode(context), node_port_(node_port) {
HeapHashMap<String, Member<AudioParam>> audio_param_map;
HashMap<String, scoped_refptr<AudioParamHandler>> param_handler_map;
for (const auto& param_info : param_info_list) {
@@ -237,8 +235,8 @@ AudioWorkletNode::AudioWorkletNode(
audio_param_map.Set(param_name, audio_param);
param_handler_map.Set(param_name, WrapRefCounted(&audio_param->Handler()));
- if (options.hasParameterData()) {
- for (const auto& key_value_pair : options.parameterData()) {
+ if (options->hasParameterData()) {
+ for (const auto& key_value_pair : options->parameterData()) {
if (key_value_pair.first == param_name)
audio_param->setValue(key_value_pair.second);
}
@@ -257,7 +255,7 @@ AudioWorkletNode* AudioWorkletNode::Create(
ScriptState* script_state,
BaseAudioContext* context,
const String& name,
- const AudioWorkletNodeOptions& options,
+ const AudioWorkletNodeOptions* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -266,7 +264,7 @@ AudioWorkletNode* AudioWorkletNode::Create(
return nullptr;
}
- if (options.numberOfInputs() == 0 && options.numberOfOutputs() == 0) {
+ if (options->numberOfInputs() == 0 && options->numberOfOutputs() == 0) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"AudioWorkletNode cannot be created: Number of inputs and number of "
@@ -274,19 +272,19 @@ AudioWorkletNode* AudioWorkletNode::Create(
return nullptr;
}
- if (options.hasOutputChannelCount()) {
- if (options.numberOfOutputs() != options.outputChannelCount().size()) {
+ if (options->hasOutputChannelCount()) {
+ if (options->numberOfOutputs() != options->outputChannelCount().size()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
"AudioWorkletNode cannot be created: Length of specified "
"'outputChannelCount' (" +
- String::Number(options.outputChannelCount().size()) +
+ String::Number(options->outputChannelCount().size()) +
") does not match the given number of outputs (" +
- String::Number(options.numberOfOutputs()) + ").");
+ String::Number(options->numberOfOutputs()) + ").");
return nullptr;
}
- for (const auto& channel_count : options.outputChannelCount()) {
+ for (const auto& channel_count : options->outputChannelCount()) {
if (channel_count < 1 ||
channel_count > BaseAudioContext::MaxNumberOfChannels()) {
exception_state.ThrowDOMException(
@@ -384,7 +382,7 @@ MessagePort* AudioWorkletNode::port() const {
}
void AudioWorkletNode::FireProcessorError() {
- DispatchEvent(*Event::Create(EventTypeNames::processorerror));
+ DispatchEvent(*Event::Create(event_type_names::kProcessorerror));
}
scoped_refptr<AudioWorkletHandler> AudioWorkletNode::GetWorkletHandler() const {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.h
index 058202c2392..5a67d491922 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_node.h
@@ -38,12 +38,12 @@ class AudioWorkletHandler final : public AudioHandler {
float sample_rate,
String name,
HashMap<String, scoped_refptr<AudioParamHandler>> param_handler_map,
- const AudioWorkletNodeOptions&);
+ const AudioWorkletNodeOptions*);
~AudioWorkletHandler() override;
// Called from render thread.
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
void CheckNumberOfChannelsForInput(AudioNodeInput*) override;
@@ -68,7 +68,7 @@ class AudioWorkletHandler final : public AudioHandler {
float sample_rate,
String name,
HashMap<String, scoped_refptr<AudioParamHandler>> param_handler_map,
- const AudioWorkletNodeOptions&);
+ const AudioWorkletNodeOptions*);
String name_;
@@ -99,7 +99,7 @@ class AudioWorkletNode final : public AudioNode,
static AudioWorkletNode* Create(ScriptState*,
BaseAudioContext*,
const String& name,
- const AudioWorkletNodeOptions&,
+ const AudioWorkletNodeOptions*,
ExceptionState&);
// ActiveScriptWrappable
@@ -108,7 +108,7 @@ class AudioWorkletNode final : public AudioNode,
// IDL
AudioParamMap* parameters() const;
MessagePort* port() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(processorerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(processorerror, kProcessorerror);
void FireProcessorError();
@@ -117,7 +117,7 @@ class AudioWorkletNode final : public AudioNode,
private:
AudioWorkletNode(BaseAudioContext&,
const String& name,
- const AudioWorkletNodeOptions&,
+ const AudioWorkletNodeOptions*,
const Vector<CrossThreadAudioParamInfo>,
MessagePort* node_port);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_object_proxy.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_object_proxy.cc
index 04ee72e61eb..e9567d27c56 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_object_proxy.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_object_proxy.cc
@@ -24,7 +24,7 @@ AudioWorkletObjectProxy::AudioWorkletObjectProxy(
void AudioWorkletObjectProxy::DidCreateWorkerGlobalScope(
WorkerOrWorkletGlobalScope* global_scope) {
- global_scope_ = ToAudioWorkletGlobalScope(global_scope);
+ global_scope_ = To<AudioWorkletGlobalScope>(global_scope);
global_scope_->SetSampleRate(context_sample_rate_);
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc
index a197e21a6b8..67fa0edf9ce 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor.cc
@@ -13,7 +13,7 @@ namespace blink {
AudioWorkletProcessor* AudioWorkletProcessor::Create(
ExecutionContext* context) {
- AudioWorkletGlobalScope* global_scope = ToAudioWorkletGlobalScope(context);
+ AudioWorkletGlobalScope* global_scope = To<AudioWorkletGlobalScope>(context);
DCHECK(global_scope);
DCHECK(global_scope->IsContextThread());
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.cc
index b3cc204dc0c..80baa713901 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.cc
@@ -40,15 +40,15 @@ v8::Local<v8::Function> AudioWorkletProcessorDefinition::ProcessLocal(
}
void AudioWorkletProcessorDefinition::SetAudioParamDescriptors(
- const HeapVector<AudioParamDescriptor>& descriptors) {
+ const HeapVector<Member<AudioParamDescriptor>>& descriptors) {
audio_param_descriptors_ = descriptors;
}
const Vector<String>
AudioWorkletProcessorDefinition::GetAudioParamDescriptorNames() const {
Vector<String> names;
- for (const auto& descriptor : audio_param_descriptors_) {
- names.push_back(descriptor.name());
+ for (const auto descriptor : audio_param_descriptors_) {
+ names.push_back(descriptor->name());
}
return names;
}
@@ -56,9 +56,9 @@ const Vector<String>
const AudioParamDescriptor*
AudioWorkletProcessorDefinition::GetAudioParamDescriptor (
const String& key) const {
- for (const auto& descriptor : audio_param_descriptors_) {
- if (descriptor.name() == key)
- return &descriptor;
+ for (const auto descriptor : audio_param_descriptors_) {
+ if (descriptor->name() == key)
+ return descriptor;
}
return nullptr;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.h b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.h
index b5100163ee7..d54fdb20ed1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.h
@@ -37,7 +37,8 @@ class MODULES_EXPORT AudioWorkletProcessorDefinition final
const String& GetName() const { return name_; }
v8::Local<v8::Object> ConstructorLocal(v8::Isolate*);
v8::Local<v8::Function> ProcessLocal(v8::Isolate*);
- void SetAudioParamDescriptors(const HeapVector<AudioParamDescriptor>&);
+ void SetAudioParamDescriptors(
+ const HeapVector<Member<AudioParamDescriptor>>&);
const Vector<String> GetAudioParamDescriptorNames() const;
const AudioParamDescriptor* GetAudioParamDescriptor(const String& key) const;
@@ -70,7 +71,7 @@ class MODULES_EXPORT AudioWorkletProcessorDefinition final
TraceWrapperV8Reference<v8::Object> constructor_;
TraceWrapperV8Reference<v8::Function> process_;
- HeapVector<AudioParamDescriptor> audio_param_descriptors_;
+ HeapVector<Member<AudioParamDescriptor>> audio_param_descriptors_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_thread_test.cc b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_thread_test.cc
index 076dbbfff1b..97250df4c50 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_thread_test.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/audio_worklet_thread_test.cc
@@ -15,18 +15,17 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
@@ -53,15 +52,15 @@ class AudioWorkletThreadTest : public PageTestBase {
Document* document = &GetDocument();
thread->Start(
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
- Vector<CSPHeaderAndType>(), document->GetReferrerPolicy(),
- document->GetSecurityOrigin(), document->IsSecureContext(),
- document->GetHttpsState(), nullptr /* worker_clients */,
- document->AddressSpace(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */, Vector<CSPHeaderAndType>(),
+ document->GetReferrerPolicy(), document->GetSecurityOrigin(),
+ document->IsSecureContext(), document->GetHttpsState(),
+ nullptr /* worker_clients */, document->AddressSpace(),
OriginTrialContext::GetTokens(document).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap),
- base::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
+ base::nullopt, std::make_unique<WorkerDevToolsParams>(),
ParentExecutionContextTaskRunners::Create());
return thread;
}
@@ -87,8 +86,8 @@ class AudioWorkletThreadTest : public PageTestBase {
KURL js_url("https://example.com/worklet.js");
ScriptModule module = ScriptModule::Compile(
script_state->GetIsolate(), "var counter = 0; ++counter;", js_url,
- js_url, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ js_url, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
EXPECT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(script_state);
EXPECT_TRUE(exception.IsEmpty());
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.cc b/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.cc
index 64d9b51b82e..2102fef2103 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.cc
@@ -79,7 +79,7 @@ namespace blink {
BaseAudioContext* BaseAudioContext::Create(
Document& document,
- const AudioContextOptions& context_options,
+ const AudioContextOptions* context_options,
ExceptionState& exception_state) {
return AudioContext::Create(document, context_options, exception_state);
}
@@ -205,7 +205,7 @@ void BaseAudioContext::ThrowExceptionForClosedState(
}
AudioBuffer* BaseAudioContext::createBuffer(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
ExceptionState& exception_state) {
// It's ok to call createBuffer, even if the context is closed because the
@@ -225,8 +225,8 @@ AudioBuffer* BaseAudioContext::createBuffer(unsigned number_of_channels,
("WebAudio.AudioBuffer.Length", 1, 1000000, 50));
// The limits are the min and max AudioBuffer sample rates currently
// supported. We use explicit values here instead of
- // AudioUtilities::minAudioBufferSampleRate() and
- // AudioUtilities::maxAudioBufferSampleRate(). The number of buckets is
+ // audio_utilities::minAudioBufferSampleRate() and
+ // audio_utilities::maxAudioBufferSampleRate(). The number of buckets is
// fairly arbitrary.
DEFINE_STATIC_LOCAL(
CustomCountHistogram, audio_buffer_sample_rate_histogram,
@@ -514,11 +514,11 @@ PeriodicWave* BaseAudioContext::createPeriodicWave(
PeriodicWave* BaseAudioContext::createPeriodicWave(
const Vector<float>& real,
const Vector<float>& imag,
- const PeriodicWaveConstraints& options,
+ const PeriodicWaveConstraints* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
- bool disable = options.disableNormalization();
+ bool disable = options->disableNormalization();
return PeriodicWave::Create(*this, real, imag, disable, exception_state);
}
@@ -605,12 +605,16 @@ void BaseAudioContext::SetContextState(AudioContextState new_state) {
// notification is required when the context gets suspended or closed.
if (was_audible_ && context_state_ != kRunning) {
was_audible_ = false;
- PostCrossThreadTask(
- *task_runner_, FROM_HERE,
- CrossThreadBind(&BaseAudioContext::NotifyAudibleAudioStopped,
- WrapCrossThreadPersistent(this)));
+ GetExecutionContext()
+ ->GetTaskRunner(TaskType::kMediaElementEvent)
+ ->PostTask(FROM_HERE,
+ WTF::Bind(&BaseAudioContext::NotifyAudibleAudioStopped,
+ WrapPersistent(this)));
}
+ if (new_state == kClosed)
+ GetDeferredTaskHandler().StopAcceptingTailProcessing();
+
// Notify context that state changed
if (GetExecutionContext()) {
GetExecutionContext()
@@ -621,7 +625,7 @@ void BaseAudioContext::SetContextState(AudioContextState new_state) {
}
void BaseAudioContext::NotifyStateChange() {
- DispatchEvent(*Event::Create(EventTypeNames::statechange));
+ DispatchEvent(*Event::Create(event_type_names::kStatechange));
}
void BaseAudioContext::NotifySourceNodeFinishedProcessing(
@@ -697,7 +701,7 @@ static bool IsAudible(const AudioBus* rendered_data) {
for (unsigned k = 0; k < rendered_data->NumberOfChannels(); ++k) {
const float* data = rendered_data->Channel(k)->Data();
float channel_energy;
- VectorMath::Vsvesq(data, 1, &channel_energy, data_size);
+ vector_math::Vsvesq(data, 1, &channel_energy, data_size);
energy += channel_energy;
}
@@ -852,7 +856,7 @@ void BaseAudioContext::RejectPendingDecodeAudioDataResolvers() {
decode_audio_resolvers_.clear();
}
-AudioIOPosition BaseAudioContext::OutputPosition() {
+AudioIOPosition BaseAudioContext::OutputPosition() const {
DCHECK(IsMainThread());
GraphAutoLocker locker(this);
return output_position_;
@@ -875,7 +879,7 @@ void BaseAudioContext::RejectPendingResolvers() {
}
const AtomicString& BaseAudioContext::InterfaceName() const {
- return EventTargetNames::AudioContext;
+ return event_target_names::kAudioContext;
}
ExecutionContext* BaseAudioContext::GetExecutionContext() const {
@@ -950,7 +954,7 @@ void BaseAudioContext::UpdateWorkletGlobalScopeOnRenderingThread() {
if (TryLock()) {
if (audio_worklet_thread_) {
AudioWorkletGlobalScope* global_scope =
- ToAudioWorkletGlobalScope(audio_worklet_thread_->GlobalScope());
+ To<AudioWorkletGlobalScope>(audio_worklet_thread_->GlobalScope());
DCHECK(global_scope);
global_scope->SetCurrentFrame(CurrentSampleFrame());
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.h b/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.h
index ae933f20167..d2459fd07be 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/base_audio_context.h
@@ -105,7 +105,7 @@ class MODULES_EXPORT BaseAudioContext
// Create an AudioContext for rendering to the audio hardware.
static BaseAudioContext* Create(Document&,
- const AudioContextOptions&,
+ const AudioContextOptions*,
ExceptionState&);
~BaseAudioContext() override;
@@ -138,7 +138,7 @@ class MODULES_EXPORT BaseAudioContext
void ThrowExceptionForClosedState(ExceptionState&);
AudioBuffer* createBuffer(unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
ExceptionState&);
@@ -206,7 +206,7 @@ class MODULES_EXPORT BaseAudioContext
ExceptionState&);
PeriodicWave* createPeriodicWave(const Vector<float>& real,
const Vector<float>& imag,
- const PeriodicWaveConstraints&,
+ const PeriodicWaveConstraints*,
ExceptionState&);
// IIRFilter
@@ -261,7 +261,7 @@ class MODULES_EXPORT BaseAudioContext
const AtomicString& InterfaceName() const final;
ExecutionContext* GetExecutionContext() const final;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
void StartRendering();
@@ -296,6 +296,8 @@ class MODULES_EXPORT BaseAudioContext
// Does nothing when the worklet global scope does not exist.
void UpdateWorkletGlobalScopeOnRenderingThread();
+ void set_was_audible_for_testing(bool value) { was_audible_ = value; }
+
protected:
enum ContextType { kRealtimeContext, kOfflineContext };
@@ -322,7 +324,7 @@ class MODULES_EXPORT BaseAudioContext
void RejectPendingDecodeAudioDataResolvers();
- AudioIOPosition OutputPosition();
+ AudioIOPosition OutputPosition() const;
// Returns the Document wich wich the instance is associated.
Document* GetDocument() const;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.cc b/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.cc
index 51afc5bdf50..5b72b8750d7 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.cc
@@ -48,13 +48,13 @@ static bool hasConstantValues(float* values, int frames_to_process) {
void BiquadDSPKernel::UpdateCoefficientsIfNecessary(int frames_to_process) {
if (GetBiquadProcessor()->FilterCoefficientsDirty()) {
- float cutoff_frequency[AudioUtilities::kRenderQuantumFrames];
- float q[AudioUtilities::kRenderQuantumFrames];
- float gain[AudioUtilities::kRenderQuantumFrames];
- float detune[AudioUtilities::kRenderQuantumFrames]; // in Cents
+ float cutoff_frequency[audio_utilities::kRenderQuantumFrames];
+ float q[audio_utilities::kRenderQuantumFrames];
+ float gain[audio_utilities::kRenderQuantumFrames];
+ float detune[audio_utilities::kRenderQuantumFrames]; // in Cents
SECURITY_CHECK(static_cast<unsigned>(frames_to_process) <=
- AudioUtilities::kRenderQuantumFrames);
+ audio_utilities::kRenderQuantumFrames);
if (GetBiquadProcessor()->HasSampleAccurateValues()) {
GetBiquadProcessor()->Parameter1().CalculateSampleAccurateValues(
@@ -164,7 +164,7 @@ void BiquadDSPKernel::UpdateTailTime(int coef_index) {
void BiquadDSPKernel::Process(const float* source,
float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(source);
DCHECK(destination);
DCHECK(GetBiquadProcessor());
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.h b/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.h
index 21fe6b0a34e..c8b124a072e 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/biquad_dsp_kernel.h
@@ -46,7 +46,7 @@ class BiquadDSPKernel final : public AudioDSPKernel {
// AudioDSPKernel
void Process(const float* source,
float* dest,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
void Reset() override { biquad_.Reset(); }
// Get the magnitude and phase response of the filter at the given
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc
index a418bb59127..07cb774c2d2 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.cc
@@ -112,7 +112,7 @@ BiquadFilterNode* BiquadFilterNode::Create(BaseAudioContext& context,
}
BiquadFilterNode* BiquadFilterNode::Create(BaseAudioContext* context,
- const BiquadFilterOptions& options,
+ const BiquadFilterOptions* options,
ExceptionState& exception_state) {
BiquadFilterNode* node = Create(*context, exception_state);
@@ -121,11 +121,11 @@ BiquadFilterNode* BiquadFilterNode::Create(BaseAudioContext* context,
node->HandleChannelOptions(options, exception_state);
- node->setType(options.type());
- node->q()->setValue(options.Q());
- node->detune()->setValue(options.detune());
- node->frequency()->setValue(options.frequency());
- node->gain()->setValue(options.gain());
+ node->setType(options->type());
+ node->q()->setValue(options->Q());
+ node->detune()->setValue(options->detune());
+ node->frequency()->setValue(options->frequency());
+ node->gain()->setValue(options->gain());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h b/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h
index 25be501d2a9..e4a7b177333 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/biquad_filter_node.h
@@ -75,7 +75,7 @@ class BiquadFilterNode final : public AudioNode {
static BiquadFilterNode* Create(BaseAudioContext&, ExceptionState&);
static BiquadFilterNode* Create(BaseAudioContext*,
- const BiquadFilterOptions&,
+ const BiquadFilterOptions*,
ExceptionState&);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.cc b/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.cc
index 5b80b30be8b..9bc6a40bdd4 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.cc
@@ -31,7 +31,7 @@
namespace blink {
BiquadProcessor::BiquadProcessor(float sample_rate,
- size_t number_of_channels,
+ uint32_t number_of_channels,
AudioParamHandler& frequency,
AudioParamHandler& q,
AudioParamHandler& gain,
@@ -104,7 +104,7 @@ void BiquadProcessor::CheckForDirtyCoefficients() {
void BiquadProcessor::Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (!IsInitialized()) {
destination->Zero();
return;
@@ -128,10 +128,10 @@ void BiquadProcessor::Process(const AudioBus* source,
frames_to_process);
}
-void BiquadProcessor::ProcessOnlyAudioParams(size_t frames_to_process) {
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+void BiquadProcessor::ProcessOnlyAudioParams(uint32_t frames_to_process) {
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
- float values[AudioUtilities::kRenderQuantumFrames];
+ float values[audio_utilities::kRenderQuantumFrames];
parameter1_->CalculateSampleAccurateValues(values, frames_to_process);
parameter2_->CalculateSampleAccurateValues(values, frames_to_process);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.h b/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.h
index 17ea56bed34..954ac2cc33e 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/biquad_processor.h
@@ -54,7 +54,7 @@ class BiquadProcessor final : public AudioDSPKernelProcessor {
};
BiquadProcessor(float sample_rate,
- size_t number_of_channels,
+ uint32_t number_of_channels,
AudioParamHandler& frequency,
AudioParamHandler& q,
AudioParamHandler& gain,
@@ -65,9 +65,9 @@ class BiquadProcessor final : public AudioDSPKernelProcessor {
void Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
// Get the magnitude and phase response of the filter at the given
// set of frequencies (in Hz). The phase response is in radians.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.cc
index e6c2b074ba2..a1d325c8c4e 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.cc
@@ -64,7 +64,7 @@ scoped_refptr<ChannelMergerHandler> ChannelMergerHandler::Create(
new ChannelMergerHandler(node, sample_rate, number_of_inputs));
}
-void ChannelMergerHandler::Process(size_t frames_to_process) {
+void ChannelMergerHandler::Process(uint32_t frames_to_process) {
AudioNodeOutput& output = this->Output(0);
DCHECK_EQ(frames_to_process, output.Bus()->length());
@@ -94,7 +94,7 @@ void ChannelMergerHandler::Process(size_t frames_to_process) {
}
}
-void ChannelMergerHandler::SetChannelCount(unsigned long channel_count,
+void ChannelMergerHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -165,10 +165,10 @@ ChannelMergerNode* ChannelMergerNode::Create(BaseAudioContext& context,
ChannelMergerNode* ChannelMergerNode::Create(
BaseAudioContext* context,
- const ChannelMergerOptions& options,
+ const ChannelMergerOptions* options,
ExceptionState& exception_state) {
ChannelMergerNode* node =
- Create(*context, options.numberOfInputs(), exception_state);
+ Create(*context, options->numberOfInputs(), exception_state);
if (!node)
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.h b/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.h
index 7ab089c8657..eb92527a920 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/channel_merger_node.h
@@ -43,8 +43,8 @@ class ChannelMergerHandler final : public AudioHandler {
float sample_rate,
unsigned number_of_inputs);
- void Process(size_t frames_to_process) override;
- void SetChannelCount(unsigned long, ExceptionState&) final;
+ void Process(uint32_t frames_to_process) override;
+ void SetChannelCount(unsigned, ExceptionState&) final;
void SetChannelCountMode(const String&, ExceptionState&) final;
double TailTime() const override { return 0; }
@@ -66,7 +66,7 @@ class ChannelMergerNode final : public AudioNode {
unsigned number_of_inputs,
ExceptionState&);
static ChannelMergerNode* Create(BaseAudioContext*,
- const ChannelMergerOptions&,
+ const ChannelMergerOptions*,
ExceptionState&);
private:
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.cc
index 1b87eb74314..6471c29edf2 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.cc
@@ -60,7 +60,7 @@ scoped_refptr<ChannelSplitterHandler> ChannelSplitterHandler::Create(
new ChannelSplitterHandler(node, sample_rate, number_of_outputs));
}
-void ChannelSplitterHandler::Process(size_t frames_to_process) {
+void ChannelSplitterHandler::Process(uint32_t frames_to_process) {
AudioBus* source = Input(0).Bus();
DCHECK(source);
DCHECK_EQ(frames_to_process, source->length());
@@ -83,7 +83,7 @@ void ChannelSplitterHandler::Process(size_t frames_to_process) {
}
}
-void ChannelSplitterHandler::SetChannelCount(unsigned long channel_count,
+void ChannelSplitterHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -171,10 +171,10 @@ ChannelSplitterNode* ChannelSplitterNode::Create(
ChannelSplitterNode* ChannelSplitterNode::Create(
BaseAudioContext* context,
- const ChannelSplitterOptions& options,
+ const ChannelSplitterOptions* options,
ExceptionState& exception_state) {
ChannelSplitterNode* node =
- Create(*context, options.numberOfOutputs(), exception_state);
+ Create(*context, options->numberOfOutputs(), exception_state);
if (!node)
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.h b/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.h
index 31e2e9af892..155c8f17014 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/channel_splitter_node.h
@@ -40,8 +40,8 @@ class ChannelSplitterHandler final : public AudioHandler {
Create(AudioNode&, float sample_rate, unsigned number_of_outputs);
// AudioHandler
- void Process(size_t frames_to_process) override;
- void SetChannelCount(unsigned long, ExceptionState&) final;
+ void Process(uint32_t frames_to_process) override;
+ void SetChannelCount(unsigned, ExceptionState&) final;
void SetChannelCountMode(const String&, ExceptionState&) final;
void SetChannelInterpretation(const String&, ExceptionState&) final;
@@ -64,7 +64,7 @@ class ChannelSplitterNode final : public AudioNode {
unsigned number_of_outputs,
ExceptionState&);
static ChannelSplitterNode* Create(BaseAudioContext*,
- const ChannelSplitterOptions&,
+ const ChannelSplitterOptions*,
ExceptionState&);
private:
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.cc
index 21349c352e8..b56415124b2 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.cc
@@ -20,7 +20,7 @@ ConstantSourceHandler::ConstantSourceHandler(AudioNode& node,
AudioParamHandler& offset)
: AudioScheduledSourceHandler(kNodeTypeConstantSource, node, sample_rate),
offset_(&offset),
- sample_accurate_values_(AudioUtilities::kRenderQuantumFrames) {
+ sample_accurate_values_(audio_utilities::kRenderQuantumFrames) {
// A ConstantSource is always mono.
AddOutput(1);
@@ -38,7 +38,7 @@ ConstantSourceHandler::~ConstantSourceHandler() {
Uninitialize();
}
-void ConstantSourceHandler::Process(size_t frames_to_process) {
+void ConstantSourceHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
DCHECK(output_bus);
@@ -132,7 +132,7 @@ ConstantSourceNode* ConstantSourceNode::Create(
ConstantSourceNode* ConstantSourceNode::Create(
BaseAudioContext* context,
- const ConstantSourceOptions& options,
+ const ConstantSourceOptions* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -141,7 +141,7 @@ ConstantSourceNode* ConstantSourceNode::Create(
if (!node)
return nullptr;
- node->offset()->setValue(options.offset());
+ node->offset()->setValue(options->offset());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.h b/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.h
index cc4f97adc33..4885e2d78e7 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/constant_source_node.h
@@ -27,7 +27,7 @@ class ConstantSourceHandler final : public AudioScheduledSourceHandler {
~ConstantSourceHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
private:
ConstantSourceHandler(AudioNode&,
@@ -47,7 +47,7 @@ class ConstantSourceNode final : public AudioScheduledSourceNode {
public:
static ConstantSourceNode* Create(BaseAudioContext&, ExceptionState&);
static ConstantSourceNode* Create(BaseAudioContext*,
- const ConstantSourceOptions&,
+ const ConstantSourceOptions*,
ExceptionState&);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.cc
index 3e6b0b4f240..4886bab5e51 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.cc
@@ -65,7 +65,7 @@ ConvolverHandler::~ConvolverHandler() {
Uninitialize();
}
-void ConvolverHandler::Process(size_t frames_to_process) {
+void ConvolverHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
DCHECK(output_bus);
@@ -140,7 +140,7 @@ void ConvolverHandler::SetBuffer(AudioBuffer* buffer,
// Create the reverb with the given impulse response.
std::unique_ptr<Reverb> reverb = std::make_unique<Reverb>(
- buffer_bus.get(), AudioUtilities::kRenderQuantumFrames, MaxFFTSize,
+ buffer_bus.get(), audio_utilities::kRenderQuantumFrames, MaxFFTSize,
Context() && Context()->HasRealtimeConstraint(), normalize_);
{
@@ -202,7 +202,7 @@ unsigned ConvolverHandler::ComputeNumberOfOutputChannels(
return clampTo(std::max(input_channels, response_channels), 1, 2);
}
-void ConvolverHandler::SetChannelCount(unsigned long channel_count,
+void ConvolverHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -277,7 +277,7 @@ ConvolverNode* ConvolverNode::Create(BaseAudioContext& context,
}
ConvolverNode* ConvolverNode::Create(BaseAudioContext* context,
- const ConvolverOptions& options,
+ const ConvolverOptions* options,
ExceptionState& exception_state) {
ConvolverNode* node = Create(*context, exception_state);
@@ -288,9 +288,9 @@ ConvolverNode* ConvolverNode::Create(BaseAudioContext* context,
// It is important to set normalize first because setting the buffer will
// examing the normalize attribute to see if normalization needs to be done.
- node->setNormalize(!options.disableNormalization());
- if (options.hasBuffer())
- node->setBuffer(options.buffer(), exception_state);
+ node->setNormalize(!options->disableNormalization());
+ if (options->hasBuffer())
+ node->setBuffer(options->buffer(), exception_state);
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.h b/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.h
index fc11d61ce49..9b28e5efd01 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/convolver_node.h
@@ -47,7 +47,7 @@ class MODULES_EXPORT ConvolverHandler final : public AudioHandler {
~ConvolverHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
// Called in the main thread when the number of channels for the input may
// have changed.
void CheckNumberOfChannelsForInput(AudioNodeInput*) override;
@@ -58,7 +58,7 @@ class MODULES_EXPORT ConvolverHandler final : public AudioHandler {
bool Normalize() const { return normalize_; }
void SetNormalize(bool normalize) { normalize_ = normalize; }
- void SetChannelCount(unsigned long, ExceptionState&) final;
+ void SetChannelCount(unsigned, ExceptionState&) final;
void SetChannelCountMode(const String&, ExceptionState&) final;
private:
@@ -95,7 +95,7 @@ class MODULES_EXPORT ConvolverNode final : public AudioNode {
public:
static ConvolverNode* Create(BaseAudioContext&, ExceptionState&);
static ConvolverNode* Create(BaseAudioContext*,
- const ConvolverOptions&,
+ const ConvolverOptions*,
ExceptionState&);
AudioBuffer* buffer() const;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.cc
index 964e68ea31a..9d8b35737b1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.cc
@@ -35,7 +35,6 @@
#include "third_party/blink/renderer/platform/audio/audio_utilities.h"
#include "third_party/blink/renderer/platform/audio/denormal_disabler.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
namespace blink {
@@ -86,7 +85,7 @@ void DefaultAudioDestinationHandler::Uninitialize() {
}
void DefaultAudioDestinationHandler::SetChannelCount(
- unsigned long channel_count,
+ unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -134,7 +133,7 @@ void DefaultAudioDestinationHandler::RestartRendering() {
StartRendering();
}
-unsigned long DefaultAudioDestinationHandler::MaxChannelCount() const {
+uint32_t DefaultAudioDestinationHandler::MaxChannelCount() const {
return AudioDestination::MaxChannelCount();
}
@@ -147,7 +146,7 @@ double DefaultAudioDestinationHandler::SampleRate() const {
void DefaultAudioDestinationHandler::Render(
AudioBus* destination_bus,
- size_t number_of_frames,
+ uint32_t number_of_frames,
const AudioIOPosition& output_position) {
TRACE_EVENT0("webaudio", "DefaultAudioDestinationHandler::Render");
@@ -198,8 +197,7 @@ void DefaultAudioDestinationHandler::Render(
Context()->HandlePostRenderTasks(destination_bus);
// Advances the current sample-frame.
- size_t new_sample_frame = current_sample_frame_ + number_of_frames;
- ReleaseStore(&current_sample_frame_, new_sample_frame);
+ AdvanceCurrentSampleFrame(number_of_frames);
Context()->UpdateWorkletGlobalScopeOnRenderingThread();
}
@@ -259,7 +257,8 @@ DefaultAudioDestinationNode::DefaultAudioDestinationNode(
DefaultAudioDestinationNode* DefaultAudioDestinationNode::Create(
BaseAudioContext* context,
const WebAudioLatencyHint& latency_hint) {
- return new DefaultAudioDestinationNode(*context, latency_hint);
+ return MakeGarbageCollected<DefaultAudioDestinationNode>(*context,
+ latency_hint);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.h b/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.h
index 0507a5a85ff..1451f6cddc5 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/default_audio_destination_node.h
@@ -50,7 +50,7 @@ class DefaultAudioDestinationHandler final : public AudioDestinationHandler,
void Dispose() override;
void Initialize() override;
void Uninitialize() override;
- void SetChannelCount(unsigned long, ExceptionState&) override;
+ void SetChannelCount(unsigned, ExceptionState&) override;
double LatencyTime() const override { return 0; }
double TailTime() const override { return 0; }
bool RequiresTailProcessing() const final { return false; }
@@ -59,14 +59,14 @@ class DefaultAudioDestinationHandler final : public AudioDestinationHandler,
void StartRendering() override;
void StopRendering() override;
void RestartRendering() override;
- unsigned long MaxChannelCount() const override;
+ uint32_t MaxChannelCount() const override;
double SampleRate() const override;
// For AudioIOCallback. This is invoked by the platform audio destination to
// get the next render quantum into |destination_bus| and update
// |output_position|.
void Render(AudioBus* destination_bus,
- size_t number_of_frames,
+ uint32_t number_of_frames,
const AudioIOPosition& output_position) final;
// Returns a hadrware callback buffer size from audio infra.
@@ -96,7 +96,6 @@ class DefaultAudioDestinationNode final : public AudioDestinationNode {
static DefaultAudioDestinationNode* Create(BaseAudioContext*,
const WebAudioLatencyHint&);
- private:
explicit DefaultAudioDestinationNode(BaseAudioContext&,
const WebAudioLatencyHint&);
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc b/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc
index 073fbc01c0f..9d409388f14 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.cc
@@ -30,8 +30,9 @@
#include "third_party/blink/renderer/modules/webaudio/audio_node_output.h"
#include "third_party/blink/renderer/modules/webaudio/offline_audio_context.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -137,12 +138,12 @@ void DeferredTaskHandler::AddAutomaticPullNode(
}
}
-void DeferredTaskHandler::RemoveAutomaticPullNode(
- scoped_refptr<AudioHandler> node) {
+void DeferredTaskHandler::RemoveAutomaticPullNode(AudioHandler* node) {
AssertGraphOwner();
- if (automatic_pull_handlers_.Contains(node)) {
- automatic_pull_handlers_.erase(node);
+ auto it = automatic_pull_handlers_.find(node);
+ if (it != automatic_pull_handlers_.end()) {
+ automatic_pull_handlers_.erase(it);
automatic_pull_handlers_need_updating_ = true;
}
}
@@ -156,7 +157,8 @@ void DeferredTaskHandler::UpdateAutomaticPullNodes() {
}
}
-void DeferredTaskHandler::ProcessAutomaticPullNodes(size_t frames_to_process) {
+void DeferredTaskHandler::ProcessAutomaticPullNodes(
+ uint32_t frames_to_process) {
DCHECK(IsAudioThread());
for (unsigned i = 0; i < rendering_automatic_pull_handlers_.size(); ++i) {
@@ -167,6 +169,7 @@ void DeferredTaskHandler::ProcessAutomaticPullNodes(size_t frames_to_process) {
void DeferredTaskHandler::AddTailProcessingHandler(
scoped_refptr<AudioHandler> handler) {
+ DCHECK(accepts_tail_processing_);
AssertGraphOwner();
if (!tail_processing_handlers_.Contains(handler)) {
@@ -177,12 +180,11 @@ void DeferredTaskHandler::AddTailProcessingHandler(
}
}
-void DeferredTaskHandler::RemoveTailProcessingHandler(
- scoped_refptr<AudioHandler> handler,
- bool disable_outputs) {
+void DeferredTaskHandler::RemoveTailProcessingHandler(AudioHandler* handler,
+ bool disable_outputs) {
AssertGraphOwner();
- size_t index = tail_processing_handlers_.Find(handler);
+ wtf_size_t index = tail_processing_handlers_.Find(handler);
if (index != kNotFound) {
#if DEBUG_AUDIONODE_REFERENCES > 1
handler->RemoveTailProcessingDebug(disable_outputs);
@@ -191,7 +193,8 @@ void DeferredTaskHandler::RemoveTailProcessingHandler(
if (disable_outputs) {
// Disabling of outputs should happen on the main thread so save this
// handler so it can be processed there.
- finished_tail_processing_handlers_.push_back(handler);
+ finished_tail_processing_handlers_.push_back(
+ std::move(tail_processing_handlers_[index]));
}
tail_processing_handlers_.EraseAt(index);
@@ -223,7 +226,7 @@ void DeferredTaskHandler::UpdateTailProcessingHandlers() {
handler->Context()->currentTime(), handler->TailTime(),
handler->LatencyTime());
#endif
- RemoveTailProcessingHandler(handler, true);
+ RemoveTailProcessingHandler(handler.get(), true);
}
}
}
@@ -296,7 +299,8 @@ void DeferredTaskHandler::ContextWillBeDestroyed() {
// Some handlers might live because of their cross thread tasks.
}
-DeferredTaskHandler::GraphAutoLocker::GraphAutoLocker(BaseAudioContext* context)
+DeferredTaskHandler::GraphAutoLocker::GraphAutoLocker(
+ const BaseAudioContext* context)
: handler_(context->GetDeferredTaskHandler()) {
handler_.lock();
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h b/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h
index aa1752797db..cc72c0b87aa 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/deferred_task_handler.h
@@ -75,11 +75,11 @@ class MODULES_EXPORT DeferredTaskHandler final
// called by the nodes who want to add/remove themselves into/from the
// automatic pull lists.
void AddAutomaticPullNode(scoped_refptr<AudioHandler>);
- void RemoveAutomaticPullNode(scoped_refptr<AudioHandler>);
+ void RemoveAutomaticPullNode(AudioHandler*);
// Called right before handlePostRenderTasks() to handle nodes which need to
// be pulled even when they are not connected to anything.
- void ProcessAutomaticPullNodes(size_t frames_to_process);
+ void ProcessAutomaticPullNodes(uint32_t frames_to_process);
// Keep track of AudioNode's that have their channel count mode changed. We
// process the changes in the post rendering phase.
@@ -109,6 +109,9 @@ class MODULES_EXPORT DeferredTaskHandler final
void RequestToDeleteHandlersOnMainThread();
void ClearHandlersToBeDeleted();
+ bool AcceptsTailProcessing() const { return accepts_tail_processing_; }
+ void StopAcceptingTailProcessing() { accepts_tail_processing_ = false; }
+
// If |node| requires tail processing, add it to the list of tail
// nodes so the tail is processed.
void AddTailProcessingHandler(scoped_refptr<AudioHandler>);
@@ -117,8 +120,7 @@ class MODULES_EXPORT DeferredTaskHandler final
// complete). Set |disable_outputs| to true if the outputs of the handler
// should also be disabled. This should be true if the tail is done. But if
// we're reconnected or re-enabled, then |disable_outputs| should be false.
- void RemoveTailProcessingHandler(scoped_refptr<AudioHandler> node,
- bool disable_outputs);
+ void RemoveTailProcessingHandler(AudioHandler*, bool disable_outputs);
// Remove all tail processing nodes. Should be called only when the
// context is done.
@@ -161,7 +163,7 @@ class MODULES_EXPORT DeferredTaskHandler final
explicit GraphAutoLocker(DeferredTaskHandler& handler) : handler_(handler) {
handler_.lock();
}
- explicit GraphAutoLocker(BaseAudioContext*);
+ explicit GraphAutoLocker(const BaseAudioContext*);
~GraphAutoLocker() { handler_.unlock(); }
@@ -229,11 +231,16 @@ class MODULES_EXPORT DeferredTaskHandler final
// Nodes that are processing its tail.
Vector<scoped_refptr<AudioHandler>> tail_processing_handlers_;
+
// Tail processing nodes that are now finished and want the output to be
// disabled. This is updated in the audio thread (with the graph lock). The
// main thread will disable the outputs.
Vector<scoped_refptr<AudioHandler>> finished_tail_processing_handlers_;
+ // Once the associated context closes, new tail processing handlers are not
+ // accepted.
+ bool accepts_tail_processing_ = true;
+
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
// Graph locking.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.cc b/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.cc
index 0d50d42071d..946858750b1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.cc
@@ -31,7 +31,7 @@
namespace blink {
DelayDSPKernel::DelayDSPKernel(DelayProcessor* processor)
- : AudioDelayDSPKernel(processor, AudioUtilities::kRenderQuantumFrames) {
+ : AudioDelayDSPKernel(processor, audio_utilities::kRenderQuantumFrames) {
DCHECK(processor);
DCHECK_GT(processor->SampleRate(), 0);
if (!(processor && processor->SampleRate() > 0))
@@ -53,7 +53,7 @@ bool DelayDSPKernel::HasSampleAccurateValues() {
}
void DelayDSPKernel::CalculateSampleAccurateValues(float* delay_times,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
GetDelayProcessor()->DelayTime().CalculateSampleAccurateValues(
delay_times, frames_to_process);
}
@@ -62,10 +62,10 @@ double DelayDSPKernel::DelayTime(float) {
return GetDelayProcessor()->DelayTime().FinalValue();
}
-void DelayDSPKernel::ProcessOnlyAudioParams(size_t frames_to_process) {
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+void DelayDSPKernel::ProcessOnlyAudioParams(uint32_t frames_to_process) {
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
- float values[AudioUtilities::kRenderQuantumFrames];
+ float values[audio_utilities::kRenderQuantumFrames];
GetDelayProcessor()->DelayTime().CalculateSampleAccurateValues(
values, frames_to_process);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.h b/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.h
index 8ba48b472d5..e4d0529da20 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/delay_dsp_kernel.h
@@ -40,10 +40,10 @@ class DelayDSPKernel final : public AudioDelayDSPKernel {
protected:
bool HasSampleAccurateValues() override;
void CalculateSampleAccurateValues(float* delay_times,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
double DelayTime(float sample_rate) override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
private:
DelayProcessor* GetDelayProcessor() {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/delay_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/delay_node.cc
index cc527506953..e06c962d79a 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/delay_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/delay_node.cc
@@ -104,21 +104,21 @@ DelayNode* DelayNode::Create(BaseAudioContext& context,
return nullptr;
}
- return new DelayNode(context, max_delay_time);
+ return MakeGarbageCollected<DelayNode>(context, max_delay_time);
}
DelayNode* DelayNode::Create(BaseAudioContext* context,
- const DelayOptions& options,
+ const DelayOptions* options,
ExceptionState& exception_state) {
// maxDelayTime has a default value specified.
- DelayNode* node = Create(*context, options.maxDelayTime(), exception_state);
+ DelayNode* node = Create(*context, options->maxDelayTime(), exception_state);
if (!node)
return nullptr;
node->HandleChannelOptions(options, exception_state);
- node->delayTime()->setValue(options.delayTime());
+ node->delayTime()->setValue(options->delayTime());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/delay_node.h b/chromium/third_party/blink/renderer/modules/webaudio/delay_node.h
index 37a5a200a39..72f6ff716b3 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/delay_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/delay_node.h
@@ -59,14 +59,15 @@ class DelayNode final : public AudioNode {
double max_delay_time,
ExceptionState&);
static DelayNode* Create(BaseAudioContext*,
- const DelayOptions&,
+ const DelayOptions*,
ExceptionState&);
+
+ DelayNode(BaseAudioContext&, double max_delay_time);
+
void Trace(blink::Visitor*) override;
AudioParam* delayTime();
private:
- DelayNode(BaseAudioContext&, double max_delay_time);
-
Member<AudioParam> delay_time_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.cc b/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.cc
index 491c68315ea..b1c3580aa9c 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.cc
@@ -47,10 +47,10 @@ std::unique_ptr<AudioDSPKernel> DelayProcessor::CreateKernel() {
return std::make_unique<DelayDSPKernel>(this);
}
-void DelayProcessor::ProcessOnlyAudioParams(size_t frames_to_process) {
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+void DelayProcessor::ProcessOnlyAudioParams(uint32_t frames_to_process) {
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
- float values[AudioUtilities::kRenderQuantumFrames];
+ float values[audio_utilities::kRenderQuantumFrames];
delay_time_->CalculateSampleAccurateValues(values, frames_to_process);
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.h b/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.h
index e4ab174a13e..bb19b9f5e61 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/delay_processor.h
@@ -45,7 +45,7 @@ class DelayProcessor final : public AudioDSPKernelProcessor {
std::unique_ptr<AudioDSPKernel> CreateKernel() override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
AudioParamHandler& DelayTime() const { return *delay_time_; }
double MaxDelayTime() { return max_delay_time_; }
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.cc
index 1fd4e451a0d..099e5ce64be 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.cc
@@ -77,7 +77,7 @@ DynamicsCompressorHandler::~DynamicsCompressorHandler() {
Uninitialize();
}
-void DynamicsCompressorHandler::Process(size_t frames_to_process) {
+void DynamicsCompressorHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
DCHECK(output_bus);
@@ -105,11 +105,11 @@ void DynamicsCompressorHandler::Process(size_t frames_to_process) {
}
void DynamicsCompressorHandler::ProcessOnlyAudioParams(
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(Context()->IsAudioThread());
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
- float values[AudioUtilities::kRenderQuantumFrames];
+ float values[audio_utilities::kRenderQuantumFrames];
threshold_->CalculateSampleAccurateValues(values, frames_to_process);
knee_->CalculateSampleAccurateValues(values, frames_to_process);
@@ -141,7 +141,7 @@ double DynamicsCompressorHandler::LatencyTime() const {
}
void DynamicsCompressorHandler::SetChannelCount(
- unsigned long channel_count,
+ unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -245,12 +245,12 @@ DynamicsCompressorNode* DynamicsCompressorNode::Create(
return nullptr;
}
- return new DynamicsCompressorNode(context);
+ return MakeGarbageCollected<DynamicsCompressorNode>(context);
}
DynamicsCompressorNode* DynamicsCompressorNode::Create(
BaseAudioContext* context,
- const DynamicsCompressorOptions& options,
+ const DynamicsCompressorOptions* options,
ExceptionState& exception_state) {
DynamicsCompressorNode* node = Create(*context, exception_state);
@@ -259,11 +259,11 @@ DynamicsCompressorNode* DynamicsCompressorNode::Create(
node->HandleChannelOptions(options, exception_state);
- node->attack()->setValue(options.attack());
- node->knee()->setValue(options.knee());
- node->ratio()->setValue(options.ratio());
- node->release()->setValue(options.release());
- node->threshold()->setValue(options.threshold());
+ node->attack()->setValue(options->attack());
+ node->knee()->setValue(options->knee());
+ node->ratio()->setValue(options->ratio());
+ node->release()->setValue(options->release());
+ node->threshold()->setValue(options->threshold());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.h b/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.h
index 1479b9271c2..a4f681a96c4 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/dynamics_compressor_node.h
@@ -52,13 +52,13 @@ class MODULES_EXPORT DynamicsCompressorHandler final : public AudioHandler {
~DynamicsCompressorHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
void Initialize() override;
float ReductionValue() const { return NoBarrierLoad(&reduction_); }
- void SetChannelCount(unsigned long, ExceptionState&) final;
+ void SetChannelCount(unsigned, ExceptionState&) final;
void SetChannelCountMode(const String&, ExceptionState&) final;
private:
@@ -90,8 +90,11 @@ class MODULES_EXPORT DynamicsCompressorNode final : public AudioNode {
public:
static DynamicsCompressorNode* Create(BaseAudioContext&, ExceptionState&);
static DynamicsCompressorNode* Create(BaseAudioContext*,
- const DynamicsCompressorOptions&,
+ const DynamicsCompressorOptions*,
ExceptionState&);
+
+ DynamicsCompressorNode(BaseAudioContext&);
+
void Trace(blink::Visitor*) override;
AudioParam* threshold() const;
@@ -102,7 +105,6 @@ class MODULES_EXPORT DynamicsCompressorNode final : public AudioNode {
AudioParam* release() const;
private:
- DynamicsCompressorNode(BaseAudioContext&);
DynamicsCompressorHandler& GetDynamicsCompressorHandler() const;
Member<AudioParam> threshold_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/gain_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/gain_node.cc
index b2e8c6328b6..dfa6dfb85c5 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/gain_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/gain_node.cc
@@ -38,9 +38,9 @@ GainHandler::GainHandler(AudioNode& node,
: AudioHandler(kNodeTypeGain, node, sample_rate),
gain_(&gain),
sample_accurate_gain_values_(
- AudioUtilities::kRenderQuantumFrames) // FIXME: can probably
- // share temp buffer
- // in context
+ audio_utilities::kRenderQuantumFrames) // FIXME: can probably
+ // share temp buffer
+ // in context
{
AddInput();
AddOutput(1);
@@ -54,7 +54,7 @@ scoped_refptr<GainHandler> GainHandler::Create(AudioNode& node,
return base::AdoptRef(new GainHandler(node, sample_rate, gain));
}
-void GainHandler::Process(size_t frames_to_process) {
+void GainHandler::Process(uint32_t frames_to_process) {
// FIXME: for some cases there is a nice optimization to avoid processing
// here, and let the gain change happen in the summing junction input of the
// AudioNode we're connected to. Then we can avoid all of the following:
@@ -89,11 +89,11 @@ void GainHandler::Process(size_t frames_to_process) {
}
}
-void GainHandler::ProcessOnlyAudioParams(size_t frames_to_process) {
+void GainHandler::ProcessOnlyAudioParams(uint32_t frames_to_process) {
DCHECK(Context()->IsAudioThread());
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
- float values[AudioUtilities::kRenderQuantumFrames];
+ float values[audio_utilities::kRenderQuantumFrames];
gain_->CalculateSampleAccurateValues(values, frames_to_process);
}
@@ -154,11 +154,11 @@ GainNode* GainNode::Create(BaseAudioContext& context,
return nullptr;
}
- return new GainNode(context);
+ return MakeGarbageCollected<GainNode>(context);
}
GainNode* GainNode::Create(BaseAudioContext* context,
- const GainOptions& options,
+ const GainOptions* options,
ExceptionState& exception_state) {
GainNode* node = Create(*context, exception_state);
@@ -167,7 +167,7 @@ GainNode* GainNode::Create(BaseAudioContext* context,
node->HandleChannelOptions(options, exception_state);
- node->gain()->setValue(options.gain());
+ node->gain()->setValue(options->gain());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/gain_node.h b/chromium/third_party/blink/renderer/modules/webaudio/gain_node.h
index 2837a2a9930..3e2b34481a1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/gain_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/gain_node.h
@@ -47,8 +47,8 @@ class GainHandler final : public AudioHandler {
AudioParamHandler& gain);
// AudioHandler
- void Process(size_t frames_to_process) override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
// Called in the main thread when the number of channels for the input may
// have changed.
@@ -73,15 +73,16 @@ class GainNode final : public AudioNode {
public:
static GainNode* Create(BaseAudioContext&, ExceptionState&);
static GainNode* Create(BaseAudioContext*,
- const GainOptions&,
+ const GainOptions*,
ExceptionState&);
+
+ GainNode(BaseAudioContext&);
+
void Trace(blink::Visitor*) override;
AudioParam* gain() const;
private:
- GainNode(BaseAudioContext&);
-
Member<AudioParam> gain_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc
index 96e2aa951bf..d97c8606ef3 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.cc
@@ -145,7 +145,7 @@ IIRFilterNode* IIRFilterNode::Create(BaseAudioContext& context,
bool has_non_zero_coef = false;
- for (size_t k = 0; k < feedforward_coef.size(); ++k) {
+ for (wtf_size_t k = 0; k < feedforward_coef.size(); ++k) {
if (feedforward_coef[k] != 0) {
has_non_zero_coef = true;
break;
@@ -164,7 +164,7 @@ IIRFilterNode* IIRFilterNode::Create(BaseAudioContext& context,
StringBuilder message;
message.Append("Unstable IIRFilter with feedback coefficients: [");
message.AppendNumber(feedback_coef[0]);
- for (size_t k = 1; k < feedback_coef.size(); ++k) {
+ for (wtf_size_t k = 1; k < feedback_coef.size(); ++k) {
message.Append(", ");
message.AppendNumber(feedback_coef[k]);
}
@@ -174,15 +174,15 @@ IIRFilterNode* IIRFilterNode::Create(BaseAudioContext& context,
kJSMessageSource, kWarningMessageLevel, message.ToString()));
}
- return new IIRFilterNode(context, feedforward_coef, feedback_coef,
- is_filter_stable);
+ return MakeGarbageCollected<IIRFilterNode>(context, feedforward_coef,
+ feedback_coef, is_filter_stable);
}
IIRFilterNode* IIRFilterNode::Create(BaseAudioContext* context,
- const IIRFilterOptions& options,
+ const IIRFilterOptions* options,
ExceptionState& exception_state) {
- IIRFilterNode* node = Create(*context, options.feedforward(),
- options.feedback(), exception_state);
+ IIRFilterNode* node = Create(*context, options->feedforward(),
+ options->feedback(), exception_state);
if (!node)
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.h b/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.h
index 081987c0b42..a33d99c249a 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/iir_filter_node.h
@@ -44,9 +44,14 @@ class IIRFilterNode : public AudioNode {
ExceptionState&);
static IIRFilterNode* Create(BaseAudioContext*,
- const IIRFilterOptions&,
+ const IIRFilterOptions*,
ExceptionState&);
+ IIRFilterNode(BaseAudioContext&,
+ const Vector<double>& denominator,
+ const Vector<double>& numerator,
+ bool is_filter_stable);
+
void Trace(blink::Visitor*) override;
// Get the magnitude and phase response of the filter at the given
@@ -57,11 +62,6 @@ class IIRFilterNode : public AudioNode {
ExceptionState&);
private:
- IIRFilterNode(BaseAudioContext&,
- const Vector<double>& denominator,
- const Vector<double>& numerator,
- bool is_filter_stable);
-
IIRProcessor* GetIIRFilterProcessor() const;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.cc b/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.cc
index f9b9f8707ca..653b2cfe862 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.cc
@@ -10,7 +10,7 @@
namespace blink {
IIRProcessor::IIRProcessor(float sample_rate,
- size_t number_of_channels,
+ uint32_t number_of_channels,
const Vector<double>& feedforward_coef,
const Vector<double>& feedback_coef,
bool is_filter_stable)
@@ -66,7 +66,7 @@ std::unique_ptr<AudioDSPKernel> IIRProcessor::CreateKernel() {
void IIRProcessor::Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (!IsInitialized()) {
destination->Zero();
return;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.h b/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.h
index e55bf919c2f..a2160eebdc8 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/iir_processor.h
@@ -18,7 +18,7 @@ class IIRDSPKernel;
class IIRProcessor final : public AudioDSPKernelProcessor {
public:
IIRProcessor(float sample_rate,
- size_t number_of_channels,
+ uint32_t number_of_channels,
const Vector<double>& feedforward_coef,
const Vector<double>& feedback_coef,
bool is_filter_stable);
@@ -28,7 +28,7 @@ class IIRProcessor final : public AudioDSPKernelProcessor {
void Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
// Get the magnitude and phase response of the filter at the given
// set of frequencies (in Hz). The phase response is in radians.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.cc b/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.cc
index 6aadf7830ca..b24849b8934 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.cc
@@ -17,7 +17,7 @@ IIRDSPKernel::IIRDSPKernel(IIRProcessor* processor)
void IIRDSPKernel::Process(const float* source,
float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(source);
DCHECK(destination);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.h b/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.h
index bdf62ff185c..03979a3cfc0 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/iirdsp_kernel.h
@@ -20,7 +20,7 @@ class IIRDSPKernel final : public AudioDSPKernel {
// AudioDSPKernel
void Process(const float* source,
float* dest,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
void Reset() override { iir_.Reset(); }
// Get the magnitude and phase response of the filter at the given
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc
index d7b07b5fea7..3e5064496d7 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.cc
@@ -83,19 +83,19 @@ void MediaElementAudioSourceHandler::Dispose() {
AudioHandler::Dispose();
}
-void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels,
+void MediaElementAudioSourceHandler::SetFormat(uint32_t number_of_channels,
float source_sample_rate) {
bool is_tainted = WouldTaintOrigin();
if (is_tainted) {
- PrintCORSMessage(MediaElement()->currentSrc().GetString());
+ PrintCorsMessage(MediaElement()->currentSrc().GetString());
}
if (number_of_channels != source_number_of_channels_ ||
source_sample_rate != source_sample_rate_) {
if (!number_of_channels ||
number_of_channels > BaseAudioContext::MaxNumberOfChannels() ||
- !AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) {
+ !audio_utilities::IsValidAudioBufferSampleRate(source_sample_rate)) {
// process() will generate silence for these uninitialized values.
DLOG(ERROR) << "setFormat(" << number_of_channels << ", "
<< source_sample_rate << ") - unhandled format change";
@@ -139,7 +139,7 @@ bool MediaElementAudioSourceHandler::WouldTaintOrigin() {
return MediaElement()->GetWebMediaPlayer()->WouldTaintOrigin();
}
-void MediaElementAudioSourceHandler::PrintCORSMessage(const String& message) {
+void MediaElementAudioSourceHandler::PrintCorsMessage(const String& message) {
if (Context()->GetExecutionContext()) {
Context()->GetExecutionContext()->AddConsoleMessage(
ConsoleMessage::Create(kSecurityMessageSource, kInfoMessageLevel,
@@ -149,7 +149,7 @@ void MediaElementAudioSourceHandler::PrintCORSMessage(const String& message) {
}
}
-void MediaElementAudioSourceHandler::Process(size_t number_of_frames) {
+void MediaElementAudioSourceHandler::Process(uint32_t number_of_frames) {
AudioBus* output_bus = Output(0).Bus();
// Use a tryLock() to avoid contention in the real-time audio thread.
@@ -232,7 +232,7 @@ MediaElementAudioSourceNode* MediaElementAudioSourceNode::Create(
}
MediaElementAudioSourceNode* node =
- new MediaElementAudioSourceNode(context, media_element);
+ MakeGarbageCollected<MediaElementAudioSourceNode>(context, media_element);
if (node) {
media_element.SetAudioSourceNode(node);
@@ -250,9 +250,9 @@ MediaElementAudioSourceNode* MediaElementAudioSourceNode::Create(
MediaElementAudioSourceNode* MediaElementAudioSourceNode::Create(
AudioContext* context,
- const MediaElementAudioSourceOptions& options,
+ const MediaElementAudioSourceOptions* options,
ExceptionState& exception_state) {
- return Create(*context, *options.mediaElement(), exception_state);
+ return Create(*context, *options->mediaElement(), exception_state);
}
void MediaElementAudioSourceNode::Trace(blink::Visitor* visitor) {
@@ -269,7 +269,7 @@ HTMLMediaElement* MediaElementAudioSourceNode::mediaElement() const {
return GetMediaElementAudioSourceHandler().MediaElement();
}
-void MediaElementAudioSourceNode::SetFormat(size_t number_of_channels,
+void MediaElementAudioSourceNode::SetFormat(uint32_t number_of_channels,
float sample_rate) {
GetMediaElementAudioSourceHandler().SetFormat(number_of_channels,
sample_rate);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.h b/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.h
index 9fbb8127720..74599d3fc76 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/media_element_audio_source_node.h
@@ -53,7 +53,7 @@ class MediaElementAudioSourceHandler final : public AudioHandler {
// AudioHandler
void Dispose() override;
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
// AudioNode
double TailTime() const override { return 0; }
@@ -61,7 +61,7 @@ class MediaElementAudioSourceHandler final : public AudioHandler {
// Helpers for AudioSourceProviderClient implementation of
// MediaElementAudioSourceNode.
- void SetFormat(size_t number_of_channels, float sample_rate);
+ void SetFormat(uint32_t number_of_channels, float sample_rate);
void lock() EXCLUSIVE_LOCK_FUNCTION(GetProcessLock());
void unlock() UNLOCK_FUNCTION(GetProcessLock());
@@ -84,7 +84,7 @@ class MediaElementAudioSourceHandler final : public AudioHandler {
// Print warning if CORS restrictions cause MediaElementAudioSource to output
// zeroes.
- void PrintCORSMessage(const String& message);
+ void PrintCorsMessage(const String& message);
// This Persistent doesn't make a reference cycle. The reference from
// HTMLMediaElement to AudioSourceProvideClient, which
@@ -119,7 +119,9 @@ class MediaElementAudioSourceNode final : public AudioNode,
HTMLMediaElement&,
ExceptionState&);
static MediaElementAudioSourceNode*
- Create(AudioContext*, const MediaElementAudioSourceOptions&, ExceptionState&);
+ Create(AudioContext*, const MediaElementAudioSourceOptions*, ExceptionState&);
+
+ MediaElementAudioSourceNode(AudioContext&, HTMLMediaElement&);
void Trace(blink::Visitor*) override;
MediaElementAudioSourceHandler& GetMediaElementAudioSourceHandler() const;
@@ -127,14 +129,11 @@ class MediaElementAudioSourceNode final : public AudioNode,
HTMLMediaElement* mediaElement() const;
// AudioSourceProviderClient functions:
- void SetFormat(size_t number_of_channels, float sample_rate) override;
+ void SetFormat(uint32_t number_of_channels, float sample_rate) override;
void lock() override EXCLUSIVE_LOCK_FUNCTION(
GetMediaElementAudioSourceHandler().GetProcessLock());
void unlock() override
UNLOCK_FUNCTION(GetMediaElementAudioSourceHandler().GetProcessLock());
-
- private:
- MediaElementAudioSourceNode(AudioContext&, HTMLMediaElement&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc
index 31f983cea2b..5dfad803f08 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.cc
@@ -40,17 +40,17 @@ namespace blink {
// WebAudioCapturerSource ignores the channel count beyond 8, so we set the
// block here to avoid anything can cause the crash.
-static const unsigned long kMaxChannelCount = 8;
+static const uint32_t kMaxChannelCount = 8;
MediaStreamAudioDestinationHandler::MediaStreamAudioDestinationHandler(
AudioNode& node,
- size_t number_of_channels)
+ uint32_t number_of_channels)
: AudioBasicInspectorHandler(kNodeTypeMediaStreamAudioDestination,
node,
node.context()->sampleRate(),
number_of_channels),
mix_bus_(AudioBus::Create(number_of_channels,
- AudioUtilities::kRenderQuantumFrames)) {
+ audio_utilities::kRenderQuantumFrames)) {
source_ = MediaStreamSource::Create("WebAudio-" + CreateCanonicalUUIDString(),
MediaStreamSource::kTypeAudio,
"MediaStreamAudioDestinationNode", false,
@@ -72,7 +72,7 @@ MediaStreamAudioDestinationHandler::MediaStreamAudioDestinationHandler(
scoped_refptr<MediaStreamAudioDestinationHandler>
MediaStreamAudioDestinationHandler::Create(AudioNode& node,
- size_t number_of_channels) {
+ uint32_t number_of_channels) {
return base::AdoptRef(
new MediaStreamAudioDestinationHandler(node, number_of_channels));
}
@@ -81,7 +81,7 @@ MediaStreamAudioDestinationHandler::~MediaStreamAudioDestinationHandler() {
Uninitialize();
}
-void MediaStreamAudioDestinationHandler::Process(size_t number_of_frames) {
+void MediaStreamAudioDestinationHandler::Process(uint32_t number_of_frames) {
// Conform the input bus into the internal mix bus, which represents
// MediaStreamDestination's channel count.
@@ -95,7 +95,7 @@ void MediaStreamAudioDestinationHandler::Process(size_t number_of_frames) {
if (try_locker.Locked()) {
unsigned count = ChannelCount();
if (count != mix_bus_->NumberOfChannels()) {
- mix_bus_ = AudioBus::Create(count, AudioUtilities::kRenderQuantumFrames);
+ mix_bus_ = AudioBus::Create(count, audio_utilities::kRenderQuantumFrames);
// setAudioFormat has an internal lock. This can cause audio to
// glitch. This is outside of our control.
source_->SetAudioFormat(count, Context()->sampleRate());
@@ -110,7 +110,7 @@ void MediaStreamAudioDestinationHandler::Process(size_t number_of_frames) {
}
void MediaStreamAudioDestinationHandler::SetChannelCount(
- unsigned long channel_count,
+ unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -135,7 +135,7 @@ void MediaStreamAudioDestinationHandler::SetChannelCount(
AudioHandler::SetChannelCount(channel_count, exception_state);
}
-unsigned long MediaStreamAudioDestinationHandler::MaxChannelCount() const {
+uint32_t MediaStreamAudioDestinationHandler::MaxChannelCount() const {
return kMaxChannelCount;
}
@@ -143,7 +143,7 @@ unsigned long MediaStreamAudioDestinationHandler::MaxChannelCount() const {
MediaStreamAudioDestinationNode::MediaStreamAudioDestinationNode(
AudioContext& context,
- size_t number_of_channels)
+ uint32_t number_of_channels)
: AudioBasicInspectorNode(context) {
SetHandler(
MediaStreamAudioDestinationHandler::Create(*this, number_of_channels));
@@ -151,7 +151,7 @@ MediaStreamAudioDestinationNode::MediaStreamAudioDestinationNode(
MediaStreamAudioDestinationNode* MediaStreamAudioDestinationNode::Create(
AudioContext& context,
- size_t number_of_channels,
+ uint32_t number_of_channels,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
@@ -160,25 +160,26 @@ MediaStreamAudioDestinationNode* MediaStreamAudioDestinationNode::Create(
return nullptr;
}
- return new MediaStreamAudioDestinationNode(context, number_of_channels);
+ return MakeGarbageCollected<MediaStreamAudioDestinationNode>(
+ context, number_of_channels);
}
MediaStreamAudioDestinationNode* MediaStreamAudioDestinationNode::Create(
AudioContext* context,
- const AudioNodeOptions& options,
+ const AudioNodeOptions* options,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
// Default to stereo; |options| will update it approriately if needed.
MediaStreamAudioDestinationNode* node =
- new MediaStreamAudioDestinationNode(*context, 2);
+ MakeGarbageCollected<MediaStreamAudioDestinationNode>(*context, 2);
// Need to handle channelCount here ourselves because the upper
// limit is different from the normal AudioNode::setChannelCount
// limit of 32. Error messages will sometimes show the wrong
// limits.
- if (options.hasChannelCount())
- node->setChannelCount(options.channelCount(), exception_state);
+ if (options->hasChannelCount())
+ node->setChannelCount(options->channelCount(), exception_state);
node->HandleChannelOptions(options, exception_state);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.h b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.h
index 427d924d5d4..78bbf3dfacc 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_destination_node.h
@@ -40,21 +40,21 @@ class MediaStreamAudioDestinationHandler final
public:
static scoped_refptr<MediaStreamAudioDestinationHandler> Create(
AudioNode&,
- size_t number_of_channels);
+ uint32_t number_of_channels);
~MediaStreamAudioDestinationHandler() override;
MediaStream* Stream() { return stream_.Get(); }
// AudioHandler.
- void Process(size_t frames_to_process) override;
- void SetChannelCount(unsigned long, ExceptionState&) override;
+ void Process(uint32_t frames_to_process) override;
+ void SetChannelCount(unsigned, ExceptionState&) override;
- unsigned long MaxChannelCount() const;
+ uint32_t MaxChannelCount() const;
bool RequiresTailProcessing() const final { return false; }
private:
- MediaStreamAudioDestinationHandler(AudioNode&, size_t number_of_channels);
+ MediaStreamAudioDestinationHandler(AudioNode&, uint32_t number_of_channels);
// As an audio source, we will never propagate silence.
bool PropagatesSilence() const override { return false; }
@@ -79,16 +79,15 @@ class MediaStreamAudioDestinationNode final : public AudioBasicInspectorNode {
public:
static MediaStreamAudioDestinationNode* Create(AudioContext&,
- size_t number_of_channels,
+ uint32_t number_of_channels,
ExceptionState&);
static MediaStreamAudioDestinationNode* Create(AudioContext*,
- const AudioNodeOptions&,
+ const AudioNodeOptions*,
ExceptionState&);
- MediaStream* stream() const;
+ MediaStreamAudioDestinationNode(AudioContext&, uint32_t number_of_channels);
- private:
- MediaStreamAudioDestinationNode(AudioContext&, size_t number_of_channels);
+ MediaStream* stream() const;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc
index 488a5380262..35c7dbbc061 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.cc
@@ -61,7 +61,7 @@ MediaStreamAudioSourceHandler::~MediaStreamAudioSourceHandler() {
Uninitialize();
}
-void MediaStreamAudioSourceHandler::SetFormat(size_t number_of_channels,
+void MediaStreamAudioSourceHandler::SetFormat(uint32_t number_of_channels,
float source_sample_rate) {
if (number_of_channels != source_number_of_channels_ ||
source_sample_rate != Context()->sampleRate()) {
@@ -91,7 +91,7 @@ void MediaStreamAudioSourceHandler::SetFormat(size_t number_of_channels,
}
}
-void MediaStreamAudioSourceHandler::Process(size_t number_of_frames) {
+void MediaStreamAudioSourceHandler::Process(uint32_t number_of_frames) {
AudioBus* output_bus = Output(0).Bus();
if (!GetAudioSourceProvider()) {
@@ -153,8 +153,9 @@ MediaStreamAudioSourceNode* MediaStreamAudioSourceNode::Create(
std::unique_ptr<AudioSourceProvider> provider =
audio_track->CreateWebAudioSource();
- MediaStreamAudioSourceNode* node = new MediaStreamAudioSourceNode(
- context, media_stream, audio_track, std::move(provider));
+ MediaStreamAudioSourceNode* node =
+ MakeGarbageCollected<MediaStreamAudioSourceNode>(
+ context, media_stream, audio_track, std::move(provider));
if (!node)
return nullptr;
@@ -170,9 +171,9 @@ MediaStreamAudioSourceNode* MediaStreamAudioSourceNode::Create(
MediaStreamAudioSourceNode* MediaStreamAudioSourceNode::Create(
AudioContext* context,
- const MediaStreamAudioSourceOptions& options,
+ const MediaStreamAudioSourceOptions* options,
ExceptionState& exception_state) {
- return Create(*context, *options.mediaStream(), exception_state);
+ return Create(*context, *options->mediaStream(), exception_state);
}
void MediaStreamAudioSourceNode::Trace(blink::Visitor* visitor) {
@@ -191,7 +192,7 @@ MediaStream* MediaStreamAudioSourceNode::getMediaStream() const {
return media_stream_;
}
-void MediaStreamAudioSourceNode::SetFormat(size_t number_of_channels,
+void MediaStreamAudioSourceNode::SetFormat(uint32_t number_of_channels,
float source_sample_rate) {
GetMediaStreamAudioSourceHandler().SetFormat(number_of_channels,
source_sample_rate);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.h b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.h
index 21bd3e48818..6f1b4de8dd2 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/media_stream_audio_source_node.h
@@ -47,7 +47,7 @@ class MediaStreamAudioSourceHandler final : public AudioHandler {
~MediaStreamAudioSourceHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
// AudioNode
double TailTime() const override { return 0; }
@@ -55,7 +55,7 @@ class MediaStreamAudioSourceHandler final : public AudioHandler {
// A helper for AudioSourceProviderClient implementation of
// MediaStreamAudioSourceNode.
- void SetFormat(size_t number_of_channels, float sample_rate);
+ void SetFormat(uint32_t number_of_channels, float sample_rate);
bool RequiresTailProcessing() const final { return false; }
@@ -87,21 +87,21 @@ class MediaStreamAudioSourceNode final : public AudioNode,
MediaStream&,
ExceptionState&);
static MediaStreamAudioSourceNode*
- Create(AudioContext*, const MediaStreamAudioSourceOptions&, ExceptionState&);
+ Create(AudioContext*, const MediaStreamAudioSourceOptions*, ExceptionState&);
+
+ MediaStreamAudioSourceNode(AudioContext&,
+ MediaStream&,
+ MediaStreamTrack*,
+ std::unique_ptr<AudioSourceProvider>);
void Trace(blink::Visitor*) override;
MediaStream* getMediaStream() const;
// AudioSourceProviderClient functions:
- void SetFormat(size_t number_of_channels, float sample_rate) override;
+ void SetFormat(uint32_t number_of_channels, float sample_rate) override;
private:
- MediaStreamAudioSourceNode(AudioContext&,
- MediaStream&,
- MediaStreamTrack*,
- std::unique_ptr<AudioSourceProvider>);
-
MediaStreamAudioSourceHandler& GetMediaStreamAudioSourceHandler() const;
Member<MediaStreamTrack> audio_track_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.cc b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.cc
index 29ae509469e..9b33de63654 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.cc
@@ -30,38 +30,39 @@
namespace blink {
OfflineAudioCompletionEvent* OfflineAudioCompletionEvent::Create() {
- return new OfflineAudioCompletionEvent;
+ return MakeGarbageCollected<OfflineAudioCompletionEvent>();
}
OfflineAudioCompletionEvent* OfflineAudioCompletionEvent::Create(
AudioBuffer* rendered_buffer) {
- return new OfflineAudioCompletionEvent(rendered_buffer);
+ return MakeGarbageCollected<OfflineAudioCompletionEvent>(rendered_buffer);
}
OfflineAudioCompletionEvent* OfflineAudioCompletionEvent::Create(
const AtomicString& event_type,
- const OfflineAudioCompletionEventInit& event_init) {
- return new OfflineAudioCompletionEvent(event_type, event_init);
+ const OfflineAudioCompletionEventInit* event_init) {
+ return MakeGarbageCollected<OfflineAudioCompletionEvent>(event_type,
+ event_init);
}
OfflineAudioCompletionEvent::OfflineAudioCompletionEvent() = default;
OfflineAudioCompletionEvent::OfflineAudioCompletionEvent(
AudioBuffer* rendered_buffer)
- : Event(EventTypeNames::complete, Bubbles::kYes, Cancelable::kNo),
+ : Event(event_type_names::kComplete, Bubbles::kYes, Cancelable::kNo),
rendered_buffer_(rendered_buffer) {}
OfflineAudioCompletionEvent::OfflineAudioCompletionEvent(
const AtomicString& event_type,
- const OfflineAudioCompletionEventInit& event_init)
+ const OfflineAudioCompletionEventInit* event_init)
: Event(event_type, event_init) {
- rendered_buffer_ = event_init.renderedBuffer();
+ rendered_buffer_ = event_init->renderedBuffer();
}
OfflineAudioCompletionEvent::~OfflineAudioCompletionEvent() = default;
const AtomicString& OfflineAudioCompletionEvent::InterfaceName() const {
- return EventNames::OfflineAudioCompletionEvent;
+ return event_interface_names::kOfflineAudioCompletionEvent;
}
void OfflineAudioCompletionEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.h b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.h
index e08e9909ee1..f897a794725 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_completion_event.h
@@ -44,8 +44,12 @@ class OfflineAudioCompletionEvent final : public Event {
static OfflineAudioCompletionEvent* Create(AudioBuffer* rendered_buffer);
static OfflineAudioCompletionEvent* Create(
const AtomicString& type,
- const OfflineAudioCompletionEventInit&);
+ const OfflineAudioCompletionEventInit*);
+ OfflineAudioCompletionEvent();
+ explicit OfflineAudioCompletionEvent(AudioBuffer* rendered_buffer);
+ explicit OfflineAudioCompletionEvent(const AtomicString& type,
+ const OfflineAudioCompletionEventInit*);
~OfflineAudioCompletionEvent() override;
AudioBuffer* renderedBuffer() { return rendered_buffer_.Get(); }
@@ -55,11 +59,6 @@ class OfflineAudioCompletionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- OfflineAudioCompletionEvent();
- explicit OfflineAudioCompletionEvent(AudioBuffer* rendered_buffer);
- explicit OfflineAudioCompletionEvent(const AtomicString& type,
- const OfflineAudioCompletionEventInit&);
-
Member<AudioBuffer> rendered_buffer_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.cc b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.cc
index ba5601767ff..5c447b8cbb0 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.cc
@@ -77,21 +77,22 @@ OfflineAudioContext* OfflineAudioContext::Create(
return nullptr;
}
- if (!AudioUtilities::IsValidAudioBufferSampleRate(sample_rate)) {
+ if (!audio_utilities::IsValidAudioBufferSampleRate(sample_rate)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
ExceptionMessages::IndexOutsideRange(
"sampleRate", sample_rate,
- AudioUtilities::MinAudioBufferSampleRate(),
+ audio_utilities::MinAudioBufferSampleRate(),
ExceptionMessages::kInclusiveBound,
- AudioUtilities::MaxAudioBufferSampleRate(),
+ audio_utilities::MaxAudioBufferSampleRate(),
ExceptionMessages::kInclusiveBound));
return nullptr;
}
OfflineAudioContext* audio_context =
- new OfflineAudioContext(document, number_of_channels, number_of_frames,
- sample_rate, exception_state);
+ MakeGarbageCollected<OfflineAudioContext>(document, number_of_channels,
+ number_of_frames, sample_rate,
+ exception_state);
audio_context->PauseIfNeeded();
#if DEBUG_AUDIONODE_REFERENCES
@@ -106,8 +107,8 @@ OfflineAudioContext* OfflineAudioContext::Create(
("WebAudio.OfflineAudioContext.Length", 1, 1000000, 50));
// The limits are the min and max AudioBuffer sample rates currently
// supported. We use explicit values here instead of
- // AudioUtilities::minAudioBufferSampleRate() and
- // AudioUtilities::maxAudioBufferSampleRate(). The number of buckets is
+ // audio_utilities::minAudioBufferSampleRate() and
+ // audio_utilities::maxAudioBufferSampleRate(). The number of buckets is
// fairly arbitrary.
DEFINE_STATIC_LOCAL(
CustomCountHistogram, offline_context_sample_rate_histogram,
@@ -122,18 +123,18 @@ OfflineAudioContext* OfflineAudioContext::Create(
OfflineAudioContext* OfflineAudioContext::Create(
ExecutionContext* context,
- const OfflineAudioContextOptions& options,
+ const OfflineAudioContextOptions* options,
ExceptionState& exception_state) {
OfflineAudioContext* offline_context =
- Create(context, options.numberOfChannels(), options.length(),
- options.sampleRate(), exception_state);
+ Create(context, options->numberOfChannels(), options->length(),
+ options->sampleRate(), exception_state);
return offline_context;
}
OfflineAudioContext::OfflineAudioContext(Document* document,
unsigned number_of_channels,
- size_t number_of_frames,
+ uint32_t number_of_frames,
float sample_rate,
ExceptionState& exception_state)
: BaseAudioContext(document, kOfflineContext),
@@ -267,7 +268,8 @@ ScriptPromise OfflineAudioContext::suspendContext(ScriptState* script_state,
// The specified suspend time is in the past; reject the promise.
if (frame < CurrentSampleFrame()) {
- size_t current_frame_clamped = std::min(CurrentSampleFrame(), length());
+ size_t current_frame_clamped =
+ std::min(CurrentSampleFrame(), static_cast<size_t>(length()));
double current_time_clamped =
std::min(currentTime(), length() / static_cast<double>(sampleRate()));
resolver->Reject(DOMException::Create(
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.h b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.h
index 17e47893dc1..22872f75c52 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_context.h
@@ -47,14 +47,19 @@ class MODULES_EXPORT OfflineAudioContext final : public BaseAudioContext {
ExceptionState&);
static OfflineAudioContext* Create(ExecutionContext*,
- const OfflineAudioContextOptions&,
+ const OfflineAudioContextOptions*,
ExceptionState&);
+ OfflineAudioContext(Document*,
+ unsigned number_of_channels,
+ uint32_t number_of_frames,
+ float sample_rate,
+ ExceptionState&);
~OfflineAudioContext() override;
void Trace(blink::Visitor*) override;
- size_t length() const { return total_render_frames_; }
+ uint32_t length() const { return total_render_frames_; }
ScriptPromise startOfflineRendering(ScriptState*);
@@ -65,7 +70,7 @@ class MODULES_EXPORT OfflineAudioContext final : public BaseAudioContext {
bool HasRealtimeConstraint() final { return false; }
- DEFINE_ATTRIBUTE_EVENT_LISTENER(complete);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(complete, kComplete);
// Fire completion event when the rendering is finished.
void FireCompletionEvent();
@@ -97,12 +102,6 @@ class MODULES_EXPORT OfflineAudioContext final : public BaseAudioContext {
bool HasPendingActivity() const final;
private:
- OfflineAudioContext(Document*,
- unsigned number_of_channels,
- size_t number_of_frames,
- float sample_rate,
- ExceptionState&);
-
// Fetch directly the destination handler.
OfflineAudioDestinationHandler& DestinationHandler();
@@ -130,7 +129,7 @@ class MODULES_EXPORT OfflineAudioContext final : public BaseAudioContext {
bool is_rendering_started_;
// Total render sample length.
- size_t total_render_frames_;
+ uint32_t total_render_frames_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.cc
index fd5e12d5934..e854d861998 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.cc
@@ -44,7 +44,7 @@ namespace blink {
OfflineAudioDestinationHandler::OfflineAudioDestinationHandler(
AudioNode& node,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate)
: AudioDestinationHandler(node),
render_target_(nullptr),
@@ -68,7 +68,7 @@ OfflineAudioDestinationHandler::OfflineAudioDestinationHandler(
scoped_refptr<OfflineAudioDestinationHandler>
OfflineAudioDestinationHandler::Create(AudioNode& node,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate) {
return base::AdoptRef(new OfflineAudioDestinationHandler(
node, number_of_channels, frames_to_process, sample_rate));
@@ -103,7 +103,7 @@ OfflineAudioContext* OfflineAudioDestinationHandler::Context() const {
return static_cast<OfflineAudioContext*>(AudioDestinationHandler::Context());
}
-unsigned long OfflineAudioDestinationHandler::MaxChannelCount() const {
+uint32_t OfflineAudioDestinationHandler::MaxChannelCount() const {
return channel_count_;
}
@@ -141,7 +141,7 @@ void OfflineAudioDestinationHandler::InitializeOfflineRenderThread(
render_target_ = render_target;
render_bus_ = AudioBus::Create(render_target->numberOfChannels(),
- AudioUtilities::kRenderQuantumFrames);
+ audio_utilities::kRenderQuantumFrames);
DCHECK(render_bus_);
PrepareTaskRunnerForRendering();
@@ -166,7 +166,7 @@ void OfflineAudioDestinationHandler::StartOfflineRendering() {
return;
bool is_render_bus_allocated =
- render_bus_->length() >= AudioUtilities::kRenderQuantumFrames;
+ render_bus_->length() >= audio_utilities::kRenderQuantumFrames;
DCHECK(is_render_bus_allocated);
if (!is_render_bus_allocated)
return;
@@ -209,12 +209,11 @@ void OfflineAudioDestinationHandler::DoOfflineRendering() {
// Suspend the rendering if a scheduled suspend found at the current
// sample frame. Otherwise render one quantum.
if (RenderIfNotSuspended(nullptr, render_bus_.get(),
- AudioUtilities::kRenderQuantumFrames))
+ audio_utilities::kRenderQuantumFrames))
return;
- size_t frames_available_to_copy =
- std::min(frames_to_process_,
- static_cast<size_t>(AudioUtilities::kRenderQuantumFrames));
+ uint32_t frames_available_to_copy =
+ std::min(frames_to_process_, audio_utilities::kRenderQuantumFrames);
for (unsigned channel_index = 0; channel_index < number_of_channels;
++channel_index) {
@@ -279,7 +278,7 @@ void OfflineAudioDestinationHandler::NotifyComplete() {
bool OfflineAudioDestinationHandler::RenderIfNotSuspended(
AudioBus* source_bus,
AudioBus* destination_bus,
- size_t number_of_frames) {
+ uint32_t number_of_frames) {
// We don't want denormals slowing down any of the audio processing
// since they can very seriously hurt performance.
// This will take care of all AudioNodes because they all process within this
@@ -340,8 +339,7 @@ bool OfflineAudioDestinationHandler::RenderIfNotSuspended(
Context()->HandlePostOfflineRenderTasks();
// Advance current sample-frame.
- size_t new_sample_frame = current_sample_frame_ + number_of_frames;
- ReleaseStore(&current_sample_frame_, new_sample_frame);
+ AdvanceCurrentSampleFrame(number_of_frames);
Context()->UpdateWorkletGlobalScopeOnRenderingThread();
@@ -395,7 +393,7 @@ void OfflineAudioDestinationHandler::RestartRendering() {
OfflineAudioDestinationNode::OfflineAudioDestinationNode(
BaseAudioContext& context,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate)
: AudioDestinationNode(context) {
SetHandler(OfflineAudioDestinationHandler::Create(
@@ -405,10 +403,10 @@ OfflineAudioDestinationNode::OfflineAudioDestinationNode(
OfflineAudioDestinationNode* OfflineAudioDestinationNode::Create(
BaseAudioContext* context,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate) {
- return new OfflineAudioDestinationNode(*context, number_of_channels,
- frames_to_process, sample_rate);
+ return MakeGarbageCollected<OfflineAudioDestinationNode>(
+ *context, number_of_channels, frames_to_process, sample_rate);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.h b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.h
index dc658d2a2f7..df9ffd4edb5 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/offline_audio_destination_node.h
@@ -44,7 +44,7 @@ class OfflineAudioDestinationHandler final : public AudioDestinationHandler {
static scoped_refptr<OfflineAudioDestinationHandler> Create(
AudioNode&,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate);
~OfflineAudioDestinationHandler() override;
@@ -62,14 +62,14 @@ class OfflineAudioDestinationHandler final : public AudioDestinationHandler {
// AudioDestinationHandler
void StartRendering() override;
void StopRendering() override;
- unsigned long MaxChannelCount() const override;
+ uint32_t MaxChannelCount() const override;
void RestartRendering() override;
double SampleRate() const override { return sample_rate_; }
size_t RenderQuantumFrames() const {
- return AudioUtilities::kRenderQuantumFrames;
+ return audio_utilities::kRenderQuantumFrames;
}
// This is called when rendering of the offline context is started
@@ -86,7 +86,7 @@ class OfflineAudioDestinationHandler final : public AudioDestinationHandler {
private:
OfflineAudioDestinationHandler(AudioNode&,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate);
// Set up the rendering and start. After setting the context up, it will
@@ -113,7 +113,7 @@ class OfflineAudioDestinationHandler final : public AudioDestinationHandler {
// Otherwise, it returns false after rendering one quantum.
bool RenderIfNotSuspended(AudioBus* source_bus,
AudioBus* destination_bus,
- size_t number_of_frames);
+ uint32_t number_of_frames);
// Prepares a task runner for the rendering based on the operation mode
// (i.e. non-AudioWorklet or AudioWorklet). This is called when the
@@ -133,7 +133,7 @@ class OfflineAudioDestinationHandler final : public AudioDestinationHandler {
// These variables are for counting the number of frames for the current
// progress and the remaining frames to be processed.
size_t frames_processed_;
- size_t frames_to_process_;
+ uint32_t frames_to_process_;
// This flag is necessary to distinguish the state of the context between
// 'created' and 'suspended'. If this flag is false and the current state
@@ -155,13 +155,12 @@ class OfflineAudioDestinationNode final : public AudioDestinationNode {
public:
static OfflineAudioDestinationNode* Create(BaseAudioContext*,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate);
- private:
OfflineAudioDestinationNode(BaseAudioContext&,
unsigned number_of_channels,
- size_t frames_to_process,
+ uint32_t frames_to_process,
float sample_rate);
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.cc
index c1f07b9f888..80fc5596d2c 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.cc
@@ -36,7 +36,7 @@
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
OscillatorHandler::OscillatorHandler(AudioNode& node,
float sample_rate,
@@ -49,8 +49,8 @@ OscillatorHandler::OscillatorHandler(AudioNode& node,
detune_(&detune),
first_render_(true),
virtual_read_index_(0),
- phase_increments_(AudioUtilities::kRenderQuantumFrames),
- detune_values_(AudioUtilities::kRenderQuantumFrames) {
+ phase_increments_(audio_utilities::kRenderQuantumFrames),
+ detune_values_(audio_utilities::kRenderQuantumFrames) {
if (wave_table) {
// A PeriodicWave overrides any value for the oscillator type,
// forcing the type to be 'custom".
@@ -177,7 +177,7 @@ static void ClampFrequency(float* frequency,
}
bool OscillatorHandler::CalculateSampleAccuratePhaseIncrements(
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
bool is_good = frames_to_process <= phase_increments_.size() &&
frames_to_process <= detune_values_.size();
DCHECK(is_good);
@@ -354,7 +354,7 @@ static float DoInterpolation(double virtual_read_index,
return sample;
}
-void OscillatorHandler::Process(size_t frames_to_process) {
+void OscillatorHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
if (!IsInitialized() || !output_bus->NumberOfChannels()) {
@@ -382,7 +382,7 @@ void OscillatorHandler::Process(size_t frames_to_process) {
}
size_t quantum_frame_offset;
- size_t non_silent_frames_to_process;
+ uint32_t non_silent_frames_to_process;
double start_frame_offset;
std::tie(quantum_frame_offset, non_silent_frames_to_process,
@@ -529,29 +529,30 @@ OscillatorNode* OscillatorNode::Create(BaseAudioContext& context,
return nullptr;
}
- return new OscillatorNode(context, oscillator_type, wave_table);
+ return MakeGarbageCollected<OscillatorNode>(context, oscillator_type,
+ wave_table);
}
OscillatorNode* OscillatorNode::Create(BaseAudioContext* context,
- const OscillatorOptions& options,
+ const OscillatorOptions* options,
ExceptionState& exception_state) {
- if (options.type() == "custom" && !options.hasPeriodicWave()) {
+ if (options->type() == "custom" && !options->hasPeriodicWave()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"A PeriodicWave must be specified if the type is set to \"custom\"");
return nullptr;
}
- OscillatorNode* node =
- Create(*context, options.type(), options.periodicWave(), exception_state);
+ OscillatorNode* node = Create(*context, options->type(),
+ options->periodicWave(), exception_state);
if (!node)
return nullptr;
node->HandleChannelOptions(options, exception_state);
- node->detune()->setValue(options.detune());
- node->frequency()->setValue(options.frequency());
+ node->detune()->setValue(options->detune());
+ node->frequency()->setValue(options->frequency());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.h b/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.h
index 1270d42483c..a3840ecf957 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/oscillator_node.h
@@ -57,7 +57,7 @@ class OscillatorHandler final : public AudioScheduledSourceHandler {
~OscillatorHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
String GetType() const;
void SetType(const String&, ExceptionState&);
@@ -74,7 +74,7 @@ class OscillatorHandler final : public AudioScheduledSourceHandler {
bool SetType(unsigned); // Returns true on success.
// Returns true if there are sample-accurate timeline parameter changes.
- bool CalculateSampleAccuratePhaseIncrements(size_t frames_to_process);
+ bool CalculateSampleAccuratePhaseIncrements(uint32_t frames_to_process);
bool PropagatesSilence() const override;
@@ -113,8 +113,12 @@ class OscillatorNode final : public AudioScheduledSourceNode {
PeriodicWave* wave_table,
ExceptionState&);
static OscillatorNode* Create(BaseAudioContext*,
- const OscillatorOptions&,
+ const OscillatorOptions*,
ExceptionState&);
+
+ OscillatorNode(BaseAudioContext&,
+ const String& oscillator_type,
+ PeriodicWave* wave_table);
void Trace(blink::Visitor*) override;
String type() const;
@@ -124,9 +128,6 @@ class OscillatorNode final : public AudioScheduledSourceNode {
void setPeriodicWave(PeriodicWave*);
private:
- OscillatorNode(BaseAudioContext&,
- const String& oscillator_type,
- PeriodicWave* wave_table);
OscillatorHandler& GetOscillatorHandler() const;
Member<AudioParam> frequency_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/panner_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/panner_node.cc
index fac20df4477..3eca10bb952 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/panner_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/panner_node.cc
@@ -99,7 +99,7 @@ PannerHandler::~PannerHandler() {
Uninitialize();
}
-void PannerHandler::Process(size_t frames_to_process) {
+void PannerHandler::Process(uint32_t frames_to_process) {
AudioBus* destination = Output(0).Bus();
if (!IsInitialized() || !panner_.get()) {
@@ -162,18 +162,18 @@ void PannerHandler::Process(size_t frames_to_process) {
void PannerHandler::ProcessSampleAccurateValues(AudioBus* destination,
const AudioBus* source,
- size_t frames_to_process) {
- CHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+ uint32_t frames_to_process) {
+ CHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
// Get the sample accurate values from all of the AudioParams, including the
// values from the AudioListener.
- float panner_x[AudioUtilities::kRenderQuantumFrames];
- float panner_y[AudioUtilities::kRenderQuantumFrames];
- float panner_z[AudioUtilities::kRenderQuantumFrames];
+ float panner_x[audio_utilities::kRenderQuantumFrames];
+ float panner_y[audio_utilities::kRenderQuantumFrames];
+ float panner_z[audio_utilities::kRenderQuantumFrames];
- float orientation_x[AudioUtilities::kRenderQuantumFrames];
- float orientation_y[AudioUtilities::kRenderQuantumFrames];
- float orientation_z[AudioUtilities::kRenderQuantumFrames];
+ float orientation_x[audio_utilities::kRenderQuantumFrames];
+ float orientation_y[audio_utilities::kRenderQuantumFrames];
+ float orientation_z[audio_utilities::kRenderQuantumFrames];
position_x_->CalculateSampleAccurateValues(panner_x, frames_to_process);
position_y_->CalculateSampleAccurateValues(panner_y, frames_to_process);
@@ -187,30 +187,30 @@ void PannerHandler::ProcessSampleAccurateValues(AudioBus* destination,
// Get the automation values from the listener.
const float* listener_x =
- Listener()->GetPositionXValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetPositionXValues(audio_utilities::kRenderQuantumFrames);
const float* listener_y =
- Listener()->GetPositionYValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetPositionYValues(audio_utilities::kRenderQuantumFrames);
const float* listener_z =
- Listener()->GetPositionZValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetPositionZValues(audio_utilities::kRenderQuantumFrames);
const float* forward_x =
- Listener()->GetForwardXValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetForwardXValues(audio_utilities::kRenderQuantumFrames);
const float* forward_y =
- Listener()->GetForwardYValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetForwardYValues(audio_utilities::kRenderQuantumFrames);
const float* forward_z =
- Listener()->GetForwardZValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetForwardZValues(audio_utilities::kRenderQuantumFrames);
const float* up_x =
- Listener()->GetUpXValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetUpXValues(audio_utilities::kRenderQuantumFrames);
const float* up_y =
- Listener()->GetUpYValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetUpYValues(audio_utilities::kRenderQuantumFrames);
const float* up_z =
- Listener()->GetUpZValues(AudioUtilities::kRenderQuantumFrames);
+ Listener()->GetUpZValues(audio_utilities::kRenderQuantumFrames);
// Compute the azimuth, elevation, and total gains for each position.
- double azimuth[AudioUtilities::kRenderQuantumFrames];
- double elevation[AudioUtilities::kRenderQuantumFrames];
- float total_gain[AudioUtilities::kRenderQuantumFrames];
+ double azimuth[audio_utilities::kRenderQuantumFrames];
+ double elevation[audio_utilities::kRenderQuantumFrames];
+ float total_gain[audio_utilities::kRenderQuantumFrames];
for (unsigned k = 0; k < frames_to_process; ++k) {
FloatPoint3D panner_position(panner_x[k], panner_y[k], panner_z[k]);
@@ -235,10 +235,10 @@ void PannerHandler::ProcessSampleAccurateValues(AudioBus* destination,
frames_to_process);
}
-void PannerHandler::ProcessOnlyAudioParams(size_t frames_to_process) {
- float values[AudioUtilities::kRenderQuantumFrames];
+void PannerHandler::ProcessOnlyAudioParams(uint32_t frames_to_process) {
+ float values[audio_utilities::kRenderQuantumFrames];
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
position_x_->CalculateSampleAccurateValues(values, frames_to_process);
position_y_->CalculateSampleAccurateValues(values, frames_to_process);
@@ -577,7 +577,7 @@ void PannerHandler::MarkPannerAsDirty(unsigned dirty) {
is_distance_cone_gain_dirty_ = true;
}
-void PannerHandler::SetChannelCount(unsigned long channel_count,
+void PannerHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -714,11 +714,11 @@ PannerNode* PannerNode::Create(BaseAudioContext& context,
return nullptr;
}
- return new PannerNode(context);
+ return MakeGarbageCollected<PannerNode>(context);
}
PannerNode* PannerNode::Create(BaseAudioContext* context,
- const PannerOptions& options,
+ const PannerOptions* options,
ExceptionState& exception_state) {
PannerNode* node = Create(*context, exception_state);
@@ -727,23 +727,23 @@ PannerNode* PannerNode::Create(BaseAudioContext* context,
node->HandleChannelOptions(options, exception_state);
- node->setPanningModel(options.panningModel());
- node->setDistanceModel(options.distanceModel());
+ node->setPanningModel(options->panningModel());
+ node->setDistanceModel(options->distanceModel());
- node->positionX()->setValue(options.positionX());
- node->positionY()->setValue(options.positionY());
- node->positionZ()->setValue(options.positionZ());
+ node->positionX()->setValue(options->positionX());
+ node->positionY()->setValue(options->positionY());
+ node->positionZ()->setValue(options->positionZ());
- node->orientationX()->setValue(options.orientationX());
- node->orientationY()->setValue(options.orientationY());
- node->orientationZ()->setValue(options.orientationZ());
+ node->orientationX()->setValue(options->orientationX());
+ node->orientationY()->setValue(options->orientationY());
+ node->orientationZ()->setValue(options->orientationZ());
- node->setRefDistance(options.refDistance(), exception_state);
- node->setMaxDistance(options.maxDistance(), exception_state);
- node->setRolloffFactor(options.rolloffFactor(), exception_state);
- node->setConeInnerAngle(options.coneInnerAngle());
- node->setConeOuterAngle(options.coneOuterAngle());
- node->setConeOuterGain(options.coneOuterGain(), exception_state);
+ node->setRefDistance(options->refDistance(), exception_state);
+ node->setMaxDistance(options->maxDistance(), exception_state);
+ node->setRolloffFactor(options->rolloffFactor(), exception_state);
+ node->setConeInnerAngle(options->coneInnerAngle());
+ node->setConeOuterAngle(options->coneOuterAngle());
+ node->setConeOuterGain(options->coneOuterGain(), exception_state);
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/panner_node.h b/chromium/third_party/blink/renderer/modules/webaudio/panner_node.h
index 2e4851c6c7a..775241fbdc9 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/panner_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/panner_node.h
@@ -71,11 +71,11 @@ class PannerHandler final : public AudioHandler {
~PannerHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
void ProcessSampleAccurateValues(AudioBus* destination,
const AudioBus* source,
- size_t frames_to_process);
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ uint32_t frames_to_process);
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
void Initialize() override;
void Uninitialize() override;
@@ -118,7 +118,7 @@ class PannerHandler final : public AudioHandler {
}
bool RequiresTailProcessing() const final;
- void SetChannelCount(unsigned long, ExceptionState&) final;
+ void SetChannelCount(unsigned, ExceptionState&) final;
void SetChannelCountMode(const String&, ExceptionState&) final;
private:
@@ -210,10 +210,12 @@ class PannerNode final : public AudioNode {
public:
static PannerNode* Create(BaseAudioContext&, ExceptionState&);
static PannerNode* Create(BaseAudioContext*,
- const PannerOptions&,
+ const PannerOptions*,
ExceptionState&);
PannerHandler& GetPannerHandler() const;
+ PannerNode(BaseAudioContext&);
+
void Trace(blink::Visitor*) override;
// Uses a 3D cartesian coordinate system
@@ -245,8 +247,6 @@ class PannerNode final : public AudioNode {
void setConeOuterGain(double, ExceptionState&);
private:
- PannerNode(BaseAudioContext&);
-
Member<AudioParam> position_x_;
Member<AudioParam> position_y_;
Member<AudioParam> position_z_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.cc b/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.cc
index 01568dbfa4c..d99e2f78af3 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.cc
@@ -49,7 +49,7 @@ const unsigned kMaxPeriodicWaveSize = 16384;
const float kCentsPerRange = 1200 / kNumberOfOctaveBands;
-using namespace VectorMath;
+using namespace vector_math;
PeriodicWave* PeriodicWave::Create(BaseAudioContext& context,
const Vector<float>& real,
@@ -72,29 +72,30 @@ PeriodicWave* PeriodicWave::Create(BaseAudioContext& context,
return nullptr;
}
- PeriodicWave* periodic_wave = new PeriodicWave(context.sampleRate());
+ PeriodicWave* periodic_wave =
+ MakeGarbageCollected<PeriodicWave>(context.sampleRate());
periodic_wave->CreateBandLimitedTables(real.data(), imag.data(), real.size(),
disable_normalization);
return periodic_wave;
}
PeriodicWave* PeriodicWave::Create(BaseAudioContext* context,
- const PeriodicWaveOptions& options,
+ const PeriodicWaveOptions* options,
ExceptionState& exception_state) {
- bool normalize = options.disableNormalization();
+ bool normalize = options->disableNormalization();
Vector<float> real_coef;
Vector<float> imag_coef;
- if (options.hasReal()) {
- real_coef = options.real();
- if (options.hasImag())
- imag_coef = options.imag();
+ if (options->hasReal()) {
+ real_coef = options->real();
+ if (options->hasImag())
+ imag_coef = options->imag();
else
imag_coef.resize(real_coef.size());
- } else if (options.hasImag()) {
+ } else if (options->hasImag()) {
// |real| not given, but we have |imag|.
- imag_coef = options.imag();
+ imag_coef = options->imag();
real_coef.resize(imag_coef.size());
} else {
// Neither |real| nor |imag| given. Return an object that would
@@ -108,25 +109,25 @@ PeriodicWave* PeriodicWave::Create(BaseAudioContext* context,
}
PeriodicWave* PeriodicWave::CreateSine(float sample_rate) {
- PeriodicWave* periodic_wave = new PeriodicWave(sample_rate);
+ PeriodicWave* periodic_wave = MakeGarbageCollected<PeriodicWave>(sample_rate);
periodic_wave->GenerateBasicWaveform(OscillatorHandler::SINE);
return periodic_wave;
}
PeriodicWave* PeriodicWave::CreateSquare(float sample_rate) {
- PeriodicWave* periodic_wave = new PeriodicWave(sample_rate);
+ PeriodicWave* periodic_wave = MakeGarbageCollected<PeriodicWave>(sample_rate);
periodic_wave->GenerateBasicWaveform(OscillatorHandler::SQUARE);
return periodic_wave;
}
PeriodicWave* PeriodicWave::CreateSawtooth(float sample_rate) {
- PeriodicWave* periodic_wave = new PeriodicWave(sample_rate);
+ PeriodicWave* periodic_wave = MakeGarbageCollected<PeriodicWave>(sample_rate);
periodic_wave->GenerateBasicWaveform(OscillatorHandler::SAWTOOTH);
return periodic_wave;
}
PeriodicWave* PeriodicWave::CreateTriangle(float sample_rate) {
- PeriodicWave* periodic_wave = new PeriodicWave(sample_rate);
+ PeriodicWave* periodic_wave = MakeGarbageCollected<PeriodicWave>(sample_rate);
periodic_wave->GenerateBasicWaveform(OscillatorHandler::TRIANGLE);
return periodic_wave;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.h b/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.h
index 1670f92ca4d..685213fefbd 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/periodic_wave.h
@@ -61,9 +61,10 @@ class PeriodicWave final : public ScriptWrappable {
ExceptionState&);
static PeriodicWave* Create(BaseAudioContext*,
- const PeriodicWaveOptions&,
+ const PeriodicWaveOptions*,
ExceptionState&);
+ explicit PeriodicWave(float sample_rate);
~PeriodicWave() override;
// Returns pointers to the lower and higher wave data for the pitch range
@@ -90,8 +91,6 @@ class PeriodicWave final : public ScriptWrappable {
unsigned NumberOfRanges() const { return number_of_ranges_; }
private:
- explicit PeriodicWave(float sample_rate);
-
void GenerateBasicWaveform(int);
size_t v8_external_memory_;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.cc b/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.cc
index e6a293d6e69..dbcee692acf 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.cc
@@ -49,7 +49,7 @@ const unsigned RealtimeAnalyser::kInputBufferSize =
RealtimeAnalyser::RealtimeAnalyser()
: input_buffer_(kInputBufferSize),
write_index_(0),
- down_mix_bus_(AudioBus::Create(1, AudioUtilities::kRenderQuantumFrames)),
+ down_mix_bus_(AudioBus::Create(1, audio_utilities::kRenderQuantumFrames)),
fft_size_(kDefaultFFTSize),
magnitude_buffer_(kDefaultFFTSize / 2),
smoothing_time_constant_(kDefaultSmoothingTimeConstant),
@@ -59,12 +59,12 @@ RealtimeAnalyser::RealtimeAnalyser()
analysis_frame_ = std::make_unique<FFTFrame>(kDefaultFFTSize);
}
-bool RealtimeAnalyser::SetFftSize(size_t size) {
+bool RealtimeAnalyser::SetFftSize(uint32_t size) {
DCHECK(IsMainThread());
// Only allow powers of two within the allowed range.
if (size > kMaxFFTSize || size < kMinFFTSize ||
- !AudioUtilities::IsPowerOfTwo(size))
+ !audio_utilities::IsPowerOfTwo(size))
return false;
if (fft_size_ != size) {
@@ -78,7 +78,7 @@ bool RealtimeAnalyser::SetFftSize(size_t size) {
return true;
}
-void RealtimeAnalyser::WriteInput(AudioBus* bus, size_t frames_to_process) {
+void RealtimeAnalyser::WriteInput(AudioBus* bus, uint32_t frames_to_process) {
bool is_bus_good = bus && bus->NumberOfChannels() > 0 &&
bus->Channel(0)->length() >= frames_to_process;
DCHECK(is_bus_good);
@@ -136,7 +136,7 @@ void RealtimeAnalyser::DoFFTAnalysis() {
// Unroll the input buffer into a temporary buffer, where we'll apply an
// analysis window followed by an FFT.
- size_t fft_size = this->FftSize();
+ uint32_t fft_size = this->FftSize();
AudioFloatArray temporary_buffer(fft_size);
float* input_buffer = input_buffer_.Data();
@@ -198,7 +198,7 @@ void RealtimeAnalyser::ConvertFloatToDb(DOMFloat32Array* destination_array) {
for (unsigned i = 0; i < len; ++i) {
float linear_value = source[i];
- double db_mag = AudioUtilities::LinearToDecibels(linear_value);
+ double db_mag = audio_utilities::LinearToDecibels(linear_value);
destination[i] = float(db_mag);
}
}
@@ -236,7 +236,7 @@ void RealtimeAnalyser::ConvertToByteData(DOMUint8Array* destination_array) {
for (unsigned i = 0; i < len; ++i) {
float linear_value = source[i];
- double db_mag = AudioUtilities::LinearToDecibels(linear_value);
+ double db_mag = audio_utilities::LinearToDecibels(linear_value);
// The range m_minDecibels to m_maxDecibels will be scaled to byte values
// from 0 to UCHAR_MAX.
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.h b/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.h
index 295b28a4caa..9bd21a25363 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/realtime_analyser.h
@@ -43,8 +43,8 @@ class RealtimeAnalyser final {
public:
RealtimeAnalyser();
- size_t FftSize() const { return fft_size_; }
- bool SetFftSize(size_t);
+ uint32_t FftSize() const { return fft_size_; }
+ bool SetFftSize(uint32_t);
unsigned FrequencyBinCount() const { return fft_size_ / 2; }
@@ -63,7 +63,7 @@ class RealtimeAnalyser final {
void GetByteTimeDomainData(DOMUint8Array*);
// The audio thread writes input data here.
- void WriteInput(AudioBus*, size_t frames_to_process);
+ void WriteInput(AudioBus*, uint32_t frames_to_process);
static const double kDefaultSmoothingTimeConstant;
static const double kDefaultMinDecibels;
@@ -87,7 +87,7 @@ class RealtimeAnalyser final {
// Input audio is downmixed to this bus before copying to m_inputBuffer.
scoped_refptr<AudioBus> down_mix_bus_;
- size_t fft_size_;
+ uint32_t fft_size_;
std::unique_ptr<FFTFrame> analysis_frame_;
void DoFFTAnalysis();
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.cc
index 7d6bce137ea..5c81ddbfaf1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.cc
@@ -38,8 +38,8 @@
#include "third_party/blink/renderer/modules/webaudio/default_audio_destination_node.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -51,19 +51,20 @@ ScriptProcessorHandler::ScriptProcessorHandler(
unsigned number_of_output_channels)
: AudioHandler(kNodeTypeScriptProcessor, node, sample_rate),
double_buffer_index_(0),
- input_buffers_(new HeapVector<Member<AudioBuffer>>()),
- output_buffers_(new HeapVector<Member<AudioBuffer>>()),
+ input_buffers_(MakeGarbageCollected<HeapVector<Member<AudioBuffer>>>()),
+ output_buffers_(MakeGarbageCollected<HeapVector<Member<AudioBuffer>>>()),
buffer_size_(buffer_size),
buffer_read_write_index_(0),
number_of_input_channels_(number_of_input_channels),
number_of_output_channels_(number_of_output_channels),
- internal_input_bus_(AudioBus::Create(number_of_input_channels,
- AudioUtilities::kRenderQuantumFrames,
- false)) {
+ internal_input_bus_(
+ AudioBus::Create(number_of_input_channels,
+ audio_utilities::kRenderQuantumFrames,
+ false)) {
// Regardless of the allowed buffer sizes, we still need to process at the
// granularity of the AudioNode.
- if (buffer_size_ < AudioUtilities::kRenderQuantumFrames)
- buffer_size_ = AudioUtilities::kRenderQuantumFrames;
+ if (buffer_size_ < audio_utilities::kRenderQuantumFrames)
+ buffer_size_ = audio_utilities::kRenderQuantumFrames;
DCHECK_LE(number_of_input_channels, BaseAudioContext::MaxNumberOfChannels());
@@ -124,7 +125,7 @@ void ScriptProcessorHandler::Initialize() {
AudioHandler::Initialize();
}
-void ScriptProcessorHandler::Process(size_t frames_to_process) {
+void ScriptProcessorHandler::Process(uint32_t frames_to_process) {
// Discussion about inputs and outputs:
// As in other AudioNodes, ScriptProcessorNode uses an AudioBus for its input
// and output (see inputBus and outputBus below). Additionally, there is a
@@ -333,7 +334,7 @@ double ScriptProcessorHandler::LatencyTime() const {
return std::numeric_limits<double>::infinity();
}
-void ScriptProcessorHandler::SetChannelCount(unsigned long channel_count,
+void ScriptProcessorHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -498,7 +499,7 @@ ScriptProcessorNode* ScriptProcessorNode::Create(
return nullptr;
}
- ScriptProcessorNode* node = new ScriptProcessorNode(
+ ScriptProcessorNode* node = MakeGarbageCollected<ScriptProcessorNode>(
context, context.sampleRate(), buffer_size, number_of_input_channels,
number_of_output_channels);
@@ -511,7 +512,7 @@ ScriptProcessorNode* ScriptProcessorNode::Create(
return node;
}
-size_t ScriptProcessorNode::bufferSize() const {
+uint32_t ScriptProcessorNode::bufferSize() const {
return static_cast<ScriptProcessorHandler&>(Handler()).BufferSize();
}
@@ -522,7 +523,7 @@ bool ScriptProcessorNode::HasPendingActivity() const {
// If |onaudioprocess| event handler is defined, the node should not be
// GCed even if it is out of scope.
- if (HasEventListeners(EventTypeNames::audioprocess))
+ if (HasEventListeners(event_type_names::kAudioprocess))
return true;
return false;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.h b/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.h
index 9e658ef1453..04161593dc1 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/script_processor_node.h
@@ -60,12 +60,12 @@ class ScriptProcessorHandler final : public AudioHandler {
~ScriptProcessorHandler() override;
// AudioHandler
- void Process(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
void Initialize() override;
- size_t BufferSize() const { return buffer_size_; }
+ uint32_t BufferSize() const { return static_cast<uint32_t>(buffer_size_); }
- void SetChannelCount(unsigned long, ExceptionState&) override;
+ void SetChannelCount(unsigned, ExceptionState&) override;
void SetChannelCountMode(const String&, ExceptionState&) override;
unsigned NumberOfOutputChannels() const override {
@@ -139,20 +139,19 @@ class ScriptProcessorNode final
unsigned number_of_output_channels,
ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(audioprocess);
- size_t bufferSize() const;
-
- // ScriptWrappable
- bool HasPendingActivity() const final;
-
- void Trace(blink::Visitor* visitor) override { AudioNode::Trace(visitor); }
-
- private:
ScriptProcessorNode(BaseAudioContext&,
float sample_rate,
size_t buffer_size,
unsigned number_of_input_channels,
unsigned number_of_output_channels);
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(audioprocess, kAudioprocess);
+ uint32_t bufferSize() const;
+
+ // ScriptWrappable
+ bool HasPendingActivity() const final;
+
+ void Trace(blink::Visitor* visitor) override { AudioNode::Trace(visitor); }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.cc
index 9d01baaeb51..7e6305541b7 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.cc
@@ -21,7 +21,7 @@ StereoPannerHandler::StereoPannerHandler(AudioNode& node,
AudioParamHandler& pan)
: AudioHandler(kNodeTypeStereoPanner, node, sample_rate),
pan_(&pan),
- sample_accurate_pan_values_(AudioUtilities::kRenderQuantumFrames) {
+ sample_accurate_pan_values_(audio_utilities::kRenderQuantumFrames) {
AddInput();
AddOutput(2);
@@ -45,7 +45,7 @@ StereoPannerHandler::~StereoPannerHandler() {
Uninitialize();
}
-void StereoPannerHandler::Process(size_t frames_to_process) {
+void StereoPannerHandler::Process(uint32_t frames_to_process) {
AudioBus* output_bus = Output(0).Bus();
if (!IsInitialized() || !Input(0).IsConnected() || !stereo_panner_.get()) {
@@ -74,9 +74,9 @@ void StereoPannerHandler::Process(size_t frames_to_process) {
}
}
-void StereoPannerHandler::ProcessOnlyAudioParams(size_t frames_to_process) {
- float values[AudioUtilities::kRenderQuantumFrames];
- DCHECK_LE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+void StereoPannerHandler::ProcessOnlyAudioParams(uint32_t frames_to_process) {
+ float values[audio_utilities::kRenderQuantumFrames];
+ DCHECK_LE(frames_to_process, audio_utilities::kRenderQuantumFrames);
pan_->CalculateSampleAccurateValues(values, frames_to_process);
}
@@ -90,7 +90,7 @@ void StereoPannerHandler::Initialize() {
AudioHandler::Initialize();
}
-void StereoPannerHandler::SetChannelCount(unsigned long channel_count,
+void StereoPannerHandler::SetChannelCount(unsigned channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
@@ -162,11 +162,11 @@ StereoPannerNode* StereoPannerNode::Create(BaseAudioContext& context,
return nullptr;
}
- return new StereoPannerNode(context);
+ return MakeGarbageCollected<StereoPannerNode>(context);
}
StereoPannerNode* StereoPannerNode::Create(BaseAudioContext* context,
- const StereoPannerOptions& options,
+ const StereoPannerOptions* options,
ExceptionState& exception_state) {
StereoPannerNode* node = Create(*context, exception_state);
@@ -175,7 +175,7 @@ StereoPannerNode* StereoPannerNode::Create(BaseAudioContext* context,
node->HandleChannelOptions(options, exception_state);
- node->pan()->setValue(options.pan());
+ node->pan()->setValue(options->pan());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.h b/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.h
index b527220ee35..f03abe3633a 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/stereo_panner_node.h
@@ -26,11 +26,11 @@ class StereoPannerHandler final : public AudioHandler {
AudioParamHandler& pan);
~StereoPannerHandler() override;
- void Process(size_t frames_to_process) override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ void Process(uint32_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
void Initialize() override;
- void SetChannelCount(unsigned long, ExceptionState&) final;
+ void SetChannelCount(unsigned, ExceptionState&) final;
void SetChannelCountMode(const String&, ExceptionState&) final;
double TailTime() const override { return 0; }
@@ -54,15 +54,16 @@ class StereoPannerNode final : public AudioNode {
public:
static StereoPannerNode* Create(BaseAudioContext&, ExceptionState&);
static StereoPannerNode* Create(BaseAudioContext*,
- const StereoPannerOptions&,
+ const StereoPannerOptions*,
ExceptionState&);
+
+ StereoPannerNode(BaseAudioContext&);
+
void Trace(blink::Visitor*) override;
AudioParam* pan() const;
private:
- StereoPannerNode(BaseAudioContext&);
-
Member<AudioParam> pan_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.cc b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.cc
index 0e48f88bef2..ee76705be11 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.cc
@@ -42,23 +42,23 @@ WaveShaperDSPKernel::WaveShaperDSPKernel(WaveShaperProcessor* processor)
void WaveShaperDSPKernel::LazyInitializeOversampling() {
if (!temp_buffer_) {
temp_buffer_ = std::make_unique<AudioFloatArray>(
- AudioUtilities::kRenderQuantumFrames * 2);
+ audio_utilities::kRenderQuantumFrames * 2);
temp_buffer2_ = std::make_unique<AudioFloatArray>(
- AudioUtilities::kRenderQuantumFrames * 4);
+ audio_utilities::kRenderQuantumFrames * 4);
up_sampler_ =
- std::make_unique<UpSampler>(AudioUtilities::kRenderQuantumFrames);
- down_sampler_ =
- std::make_unique<DownSampler>(AudioUtilities::kRenderQuantumFrames * 2);
+ std::make_unique<UpSampler>(audio_utilities::kRenderQuantumFrames);
+ down_sampler_ = std::make_unique<DownSampler>(
+ audio_utilities::kRenderQuantumFrames * 2);
up_sampler2_ =
- std::make_unique<UpSampler>(AudioUtilities::kRenderQuantumFrames * 2);
- down_sampler2_ =
- std::make_unique<DownSampler>(AudioUtilities::kRenderQuantumFrames * 4);
+ std::make_unique<UpSampler>(audio_utilities::kRenderQuantumFrames * 2);
+ down_sampler2_ = std::make_unique<DownSampler>(
+ audio_utilities::kRenderQuantumFrames * 4);
}
}
void WaveShaperDSPKernel::Process(const float* source,
float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
switch (GetWaveShaperProcessor()->Oversample()) {
case WaveShaperProcessor::kOverSampleNone:
ProcessCurve(source, destination, frames_to_process);
@@ -110,7 +110,7 @@ double WaveShaperDSPKernel::WaveShaperCurveValue(float input,
void WaveShaperDSPKernel::ProcessCurve(const float* source,
float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(source);
DCHECK(destination);
DCHECK(GetWaveShaperProcessor());
@@ -142,8 +142,8 @@ void WaveShaperDSPKernel::ProcessCurve(const float* source,
void WaveShaperDSPKernel::ProcessCurve2x(const float* source,
float* destination,
- size_t frames_to_process) {
- bool is_safe = frames_to_process == AudioUtilities::kRenderQuantumFrames;
+ uint32_t frames_to_process) {
+ bool is_safe = frames_to_process == audio_utilities::kRenderQuantumFrames;
DCHECK(is_safe);
if (!is_safe)
return;
@@ -160,8 +160,8 @@ void WaveShaperDSPKernel::ProcessCurve2x(const float* source,
void WaveShaperDSPKernel::ProcessCurve4x(const float* source,
float* destination,
- size_t frames_to_process) {
- bool is_safe = frames_to_process == AudioUtilities::kRenderQuantumFrames;
+ uint32_t frames_to_process) {
+ bool is_safe = frames_to_process == audio_utilities::kRenderQuantumFrames;
DCHECK(is_safe);
if (!is_safe)
return;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.h b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.h
index 77f037b7f85..cea94736949 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_dsp_kernel.h
@@ -47,7 +47,7 @@ class WaveShaperDSPKernel final : public AudioDSPKernel {
// AudioDSPKernel
void Process(const float* source,
float* dest,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
void Reset() override;
double TailTime() const override;
double LatencyTime() const override;
@@ -67,15 +67,17 @@ class WaveShaperDSPKernel final : public AudioDSPKernel {
protected:
// Apply the shaping curve.
- void ProcessCurve(const float* source, float* dest, size_t frames_to_process);
+ void ProcessCurve(const float* source,
+ float* dest,
+ uint32_t frames_to_process);
// Use up-sampling, process at the higher sample-rate, then down-sample.
void ProcessCurve2x(const float* source,
float* dest,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void ProcessCurve4x(const float* source,
float* dest,
- size_t frames_to_process);
+ uint32_t frames_to_process);
WaveShaperProcessor* GetWaveShaperProcessor() {
return static_cast<WaveShaperProcessor*>(Processor());
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.cc b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.cc
index b74b95d8f5e..d36b0951582 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.cc
@@ -61,11 +61,11 @@ WaveShaperNode* WaveShaperNode::Create(BaseAudioContext& context,
return nullptr;
}
- return new WaveShaperNode(context);
+ return MakeGarbageCollected<WaveShaperNode>(context);
}
WaveShaperNode* WaveShaperNode::Create(BaseAudioContext* context,
- const WaveShaperOptions& options,
+ const WaveShaperOptions* options,
ExceptionState& exception_state) {
WaveShaperNode* node = Create(*context, exception_state);
@@ -74,10 +74,10 @@ WaveShaperNode* WaveShaperNode::Create(BaseAudioContext* context,
node->HandleChannelOptions(options, exception_state);
- if (options.hasCurve())
- node->setCurve(options.curve(), exception_state);
+ if (options->hasCurve())
+ node->setCurve(options->curve(), exception_state);
- node->setOversample(options.oversample());
+ node->setOversample(options->oversample());
return node;
}
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.h b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.h
index 6f51f121dc9..db5a832540b 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_node.h
@@ -52,9 +52,11 @@ class WaveShaperNode final : public AudioNode {
public:
static WaveShaperNode* Create(BaseAudioContext&, ExceptionState&);
static WaveShaperNode* Create(BaseAudioContext*,
- const WaveShaperOptions&,
+ const WaveShaperOptions*,
ExceptionState&);
+ explicit WaveShaperNode(BaseAudioContext&);
+
// setCurve() is called on the main thread.
void setCurve(NotShared<DOMFloat32Array>, ExceptionState&);
void setCurve(const Vector<float>&, ExceptionState&);
@@ -64,8 +66,6 @@ class WaveShaperNode final : public AudioNode {
String oversample() const;
private:
- explicit WaveShaperNode(BaseAudioContext&);
-
void SetCurveImpl(const float* curve_data,
unsigned curve_length,
ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.cc b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.cc
index ec42e046c84..6c3e83b8f54 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.cc
+++ b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.cc
@@ -30,7 +30,7 @@
namespace blink {
WaveShaperProcessor::WaveShaperProcessor(float sample_rate,
- size_t number_of_channels)
+ unsigned number_of_channels)
: AudioDSPKernelProcessor(sample_rate, number_of_channels),
oversample_(kOverSampleNone) {}
@@ -91,7 +91,7 @@ void WaveShaperProcessor::SetOversample(OverSampleType oversample) {
void WaveShaperProcessor::Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (!IsInitialized()) {
destination->Zero();
return;
diff --git a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.h b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.h
index 8c5ba1099af..b83906755fe 100644
--- a/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.h
+++ b/chromium/third_party/blink/renderer/modules/webaudio/wave_shaper_processor.h
@@ -43,7 +43,7 @@ class WaveShaperProcessor final : public AudioDSPKernelProcessor {
public:
enum OverSampleType { kOverSampleNone, kOverSample2x, kOverSample4x };
- WaveShaperProcessor(float sample_rate, size_t number_of_channels);
+ WaveShaperProcessor(float sample_rate, unsigned number_of_channels);
~WaveShaperProcessor() override;
@@ -51,7 +51,7 @@ class WaveShaperProcessor final : public AudioDSPKernelProcessor {
void Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
void SetCurve(const float* curve_data, unsigned curve_length);
Vector<float>* Curve() const { return curve_.get(); };
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/BUILD.gn b/chromium/third_party/blink/renderer/modules/webdatabase/BUILD.gn
index 1fff5b94467..2f66e4c1c7a 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/BUILD.gn
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/BUILD.gn
@@ -45,18 +45,14 @@ blink_modules_sources("webdatabase") {
"sql_statement.h",
"sql_statement_backend.cc",
"sql_statement_backend.h",
- "sql_statement_callback.h",
- "sql_statement_error_callback.h",
"sql_transaction.cc",
"sql_transaction.h",
"sql_transaction_backend.cc",
"sql_transaction_backend.h",
- "sql_transaction_callback.h",
"sql_transaction_client.cc",
"sql_transaction_client.h",
"sql_transaction_coordinator.cc",
"sql_transaction_coordinator.h",
- "sql_transaction_error_callback.h",
"sql_transaction_state.h",
"sql_transaction_state_machine.cc",
"sql_transaction_state_machine.h",
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/change_version_wrapper.cc b/chromium/third_party/blink/renderer/modules/webdatabase/change_version_wrapper.cc
index 689a2e54524..44d8ee42457 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/change_version_wrapper.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/change_version_wrapper.cc
@@ -47,7 +47,7 @@ bool ChangeVersionWrapper::PerformPreflight(
String actual_version;
if (!database->GetVersionFromDatabase(actual_version)) {
int sqlite_error = database->SqliteDatabase().LastError();
- database->ReportChangeVersionResult(1, SQLError::kUnknownErr, sqlite_error);
+ database->ReportSqliteError(sqlite_error);
sql_error_ = SQLErrorData::Create(
SQLError::kUnknownErr, "unable to read the current version",
sqlite_error, database->SqliteDatabase().LastErrorMsg());
@@ -55,7 +55,6 @@ bool ChangeVersionWrapper::PerformPreflight(
}
if (actual_version != old_version_) {
- database->ReportChangeVersionResult(2, SQLError::kVersionErr, 0);
sql_error_ = SQLErrorData::Create(SQLError::kVersionErr,
"current version of the database and "
"`oldVersion` argument do not match");
@@ -74,7 +73,7 @@ bool ChangeVersionWrapper::PerformPostflight(
if (!database->SetVersionInDatabase(new_version_)) {
int sqlite_error = database->SqliteDatabase().LastError();
- database->ReportChangeVersionResult(3, SQLError::kUnknownErr, sqlite_error);
+ database->ReportSqliteError(sqlite_error);
sql_error_ = SQLErrorData::Create(
SQLError::kUnknownErr, "unable to set new version in database",
sqlite_error, database->SqliteDatabase().LastErrorMsg());
@@ -83,7 +82,6 @@ bool ChangeVersionWrapper::PerformPostflight(
database->SetExpectedVersion(new_version_);
- database->ReportChangeVersionResult(0, -1, 0); // OK
return true;
}
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database.cc
index d3c597ee455..dc8fcd38ba6 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database.cc
@@ -51,8 +51,8 @@
#include "third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_transaction.h"
#include "third_party/blink/renderer/modules/webdatabase/storage_log.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/atomics.h"
// Registering "opened" databases with the DatabaseTracker
@@ -454,7 +454,6 @@ class DoneCreatingDatabaseOnExitCaller {
bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
DatabaseError& error,
String& error_message) {
- TimeTicks call_start_time = WTF::CurrentTimeTicks();
DoneCreatingDatabaseOnExitCaller on_exit_caller(this);
DCHECK(error_message.IsEmpty());
DCHECK_EQ(error,
@@ -465,10 +464,7 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
const int kMaxSqliteBusyWaitTime = 30000;
if (!sqlite_database_.Open(filename_)) {
- ReportOpenDatabaseResult(
- 1, static_cast<int>(DOMExceptionCode::kInvalidStateError),
- sqlite_database_.LastError(),
- WTF::CurrentTimeTicks() - call_start_time);
+ ReportSqliteError(sqlite_database_.LastError());
error_message = FormatErrorMessage("unable to open database",
sqlite_database_.LastError(),
sqlite_database_.LastErrorMsg());
@@ -512,10 +508,7 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
SQLiteTransaction transaction(sqlite_database_);
transaction.begin();
if (!transaction.InProgress()) {
- ReportOpenDatabaseResult(
- 2, static_cast<int>(DOMExceptionCode::kInvalidStateError),
- sqlite_database_.LastError(),
- WTF::CurrentTimeTicks() - call_start_time);
+ ReportSqliteError(sqlite_database_.LastError());
error_message = FormatErrorMessage(
"unable to open database, failed to start transaction",
sqlite_database_.LastError(), sqlite_database_.LastErrorMsg());
@@ -531,10 +524,7 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
"CREATE TABLE " + table_name +
" (key TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT "
"REPLACE,value TEXT NOT NULL ON CONFLICT FAIL);")) {
- ReportOpenDatabaseResult(
- 3, static_cast<int>(DOMExceptionCode::kInvalidStateError),
- sqlite_database_.LastError(),
- WTF::CurrentTimeTicks() - call_start_time);
+ ReportSqliteError(sqlite_database_.LastError());
error_message = FormatErrorMessage(
"unable to open database, failed to create 'info' table",
sqlite_database_.LastError(), sqlite_database_.LastErrorMsg());
@@ -543,10 +533,7 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
return false;
}
} else if (!GetVersionFromDatabase(current_version, false)) {
- ReportOpenDatabaseResult(
- 4, static_cast<int>(DOMExceptionCode::kInvalidStateError),
- sqlite_database_.LastError(),
- WTF::CurrentTimeTicks() - call_start_time);
+ ReportSqliteError(sqlite_database_.LastError());
error_message = FormatErrorMessage(
"unable to open database, failed to read current version",
sqlite_database_.LastError(), sqlite_database_.LastErrorMsg());
@@ -563,10 +550,7 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
<< " in database " << DatabaseDebugName()
<< " that was just created";
if (!SetVersionInDatabase(expected_version_, false)) {
- ReportOpenDatabaseResult(
- 5, static_cast<int>(DOMExceptionCode::kInvalidStateError),
- sqlite_database_.LastError(),
- WTF::CurrentTimeTicks() - call_start_time);
+ ReportSqliteError(sqlite_database_.LastError());
error_message = FormatErrorMessage(
"unable to open database, failed to write current version",
sqlite_database_.LastError(), sqlite_database_.LastErrorMsg());
@@ -594,9 +578,6 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
// whatever version of the database we have.
if ((!new_ || should_set_version_in_new_database) &&
expected_version_.length() && expected_version_ != current_version) {
- ReportOpenDatabaseResult(
- 6, static_cast<int>(DOMExceptionCode::kInvalidStateError), 0,
- WTF::CurrentTimeTicks() - call_start_time);
error_message =
"unable to open database, version mismatch, '" + expected_version_ +
"' does not match the currentVersion of '" + current_version + "'";
@@ -621,9 +602,6 @@ bool Database::PerformOpenAndVerify(bool should_set_version_in_new_database,
expected_version_ = "";
}
- ReportOpenDatabaseResult(0, -1, 0,
- WTF::CurrentTimeTicks() - call_start_time); // OK
-
if (GetDatabaseContext()->GetDatabaseThread())
GetDatabaseContext()->GetDatabaseThread()->RecordDatabaseOpen(this);
return true;
@@ -766,69 +744,17 @@ void Database::IncrementalVacuumIfNeeded() {
int64_t total_size = sqlite_database_.TotalSize();
if (total_size <= 10 * free_space_size) {
int result = sqlite_database_.RunIncrementalVacuumCommand();
- ReportVacuumDatabaseResult(result);
- if (result != kSQLResultOk)
+ if (result != kSQLResultOk) {
+ ReportSqliteError(result);
LogErrorMessage(FormatErrorMessage("error vacuuming database", result,
sqlite_database_.LastErrorMsg()));
+ }
}
}
-// These are used to generate histograms of errors seen with websql.
-// See about:histograms in chromium.
-void Database::ReportOpenDatabaseResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code,
- TimeDelta duration) {
- if (Platform::Current()->DatabaseObserver()) {
- Platform::Current()->DatabaseObserver()->ReportOpenDatabaseResult(
- WebSecurityOrigin(GetSecurityOrigin()), StringIdentifier(), error_site,
- web_sql_error_code, sqlite_error_code, duration);
- }
-}
-
-void Database::ReportChangeVersionResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code) {
- if (Platform::Current()->DatabaseObserver()) {
- Platform::Current()->DatabaseObserver()->ReportChangeVersionResult(
- WebSecurityOrigin(GetSecurityOrigin()), StringIdentifier(), error_site,
- web_sql_error_code, sqlite_error_code);
- }
-}
-
-void Database::ReportStartTransactionResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code) {
- if (Platform::Current()->DatabaseObserver()) {
- Platform::Current()->DatabaseObserver()->ReportStartTransactionResult(
- WebSecurityOrigin(GetSecurityOrigin()), StringIdentifier(), error_site,
- web_sql_error_code, sqlite_error_code);
- }
-}
-
-void Database::ReportCommitTransactionResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code) {
- if (Platform::Current()->DatabaseObserver()) {
- Platform::Current()->DatabaseObserver()->ReportCommitTransactionResult(
- WebSecurityOrigin(GetSecurityOrigin()), StringIdentifier(), error_site,
- web_sql_error_code, sqlite_error_code);
- }
-}
-
-void Database::ReportExecuteStatementResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code) {
- if (Platform::Current()->DatabaseObserver()) {
- Platform::Current()->DatabaseObserver()->ReportExecuteStatementResult(
- WebSecurityOrigin(GetSecurityOrigin()), StringIdentifier(), error_site,
- web_sql_error_code, sqlite_error_code);
- }
-}
-
-void Database::ReportVacuumDatabaseResult(int sqlite_error_code) {
+void Database::ReportSqliteError(int sqlite_error_code) {
if (Platform::Current()->DatabaseObserver()) {
- Platform::Current()->DatabaseObserver()->ReportVacuumDatabaseResult(
+ Platform::Current()->DatabaseObserver()->ReportSqliteError(
WebSecurityOrigin(GetSecurityOrigin()), StringIdentifier(),
sqlite_error_code);
}
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database.h b/chromium/third_party/blink/renderer/modules/webdatabase/database.h
index 028fca4713a..f01a6852d61 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database.h
@@ -53,6 +53,11 @@ class Database final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
+ Database(DatabaseContext*,
+ const String& name,
+ const String& expected_version,
+ const String& display_name,
+ unsigned estimated_size);
~Database() override;
void Trace(blink::Visitor*) override;
@@ -128,11 +133,6 @@ class Database final : public ScriptWrappable {
class DatabaseTransactionTask;
class DatabaseTableNamesTask;
- Database(DatabaseContext*,
- const String& name,
- const String& expected_version,
- const String& display_name,
- unsigned estimated_size);
bool PerformOpenAndVerify(bool set_version_in_new_database,
DatabaseError&,
String& error_message);
@@ -158,23 +158,7 @@ class Database final : public ScriptWrappable {
const ChangeVersionData* = nullptr);
Vector<String> PerformGetTableNames();
- void ReportOpenDatabaseResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code,
- TimeDelta duration);
- void ReportChangeVersionResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code);
- void ReportStartTransactionResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code);
- void ReportCommitTransactionResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code);
- void ReportExecuteStatementResult(int error_site,
- int web_sql_error_code,
- int sqlite_error_code);
- void ReportVacuumDatabaseResult(int sqlite_error_code);
+ void ReportSqliteError(int sqlite_error_code);
void LogErrorMessage(const String&);
static const char* DatabaseInfoTableName();
String DatabaseDebugName() const {
@@ -193,7 +177,7 @@ class Database final : public ScriptWrappable {
String name_;
String expected_version_;
String display_name_;
- unsigned long estimated_size_;
+ unsigned estimated_size_;
String filename_;
DatabaseGuid guid_;
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.cc
index c1a4560c2f8..b15f5a5bf5c 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.cc
@@ -40,7 +40,8 @@ namespace blink {
DatabaseAuthorizer* DatabaseAuthorizer::Create(
DatabaseContext* database_context,
const String& database_info_table_name) {
- return new DatabaseAuthorizer(database_context, database_info_table_name);
+ return MakeGarbageCollected<DatabaseAuthorizer>(database_context,
+ database_info_table_name);
}
DatabaseAuthorizer::DatabaseAuthorizer(DatabaseContext* database_context,
@@ -319,14 +320,6 @@ int DatabaseAuthorizer::AllowPragma(const String&, const String&) {
return security_enabled_ ? kSQLAuthDeny : kSQLAuthAllow;
}
-int DatabaseAuthorizer::AllowAttach(const String&) {
- return security_enabled_ ? kSQLAuthDeny : kSQLAuthAllow;
-}
-
-int DatabaseAuthorizer::AllowDetach(const String&) {
- return security_enabled_ ? kSQLAuthDeny : kSQLAuthAllow;
-}
-
int DatabaseAuthorizer::AllowFunction(const String& function_name) {
if (security_enabled_ && !WhitelistedFunctions().Contains(function_name))
return kSQLAuthDeny;
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.h b/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.h
index bd79fef0454..4af1926ad7a 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_authorizer.h
@@ -50,6 +50,10 @@ class DatabaseAuthorizer
static DatabaseAuthorizer* Create(DatabaseContext*,
const String& database_info_table_name);
+
+ explicit DatabaseAuthorizer(DatabaseContext*,
+ const String& database_info_table_name);
+
void Trace(blink::Visitor*);
int CreateTable(const String& table_name);
@@ -89,9 +93,6 @@ class DatabaseAuthorizer
int AllowFunction(const String& function_name);
int AllowPragma(const String& pragma_name, const String& first_argument);
- int AllowAttach(const String& filename);
- int AllowDetach(const String& database_name);
-
void Disable();
void Enable();
void SetPermissions(int permissions);
@@ -106,8 +107,6 @@ class DatabaseAuthorizer
bool HadDeletes() const { return had_deletes_; }
private:
- explicit DatabaseAuthorizer(DatabaseContext*,
- const String& database_info_table_name);
void AddWhitelistedFunctions();
int DenyBasedOnTableName(const String&) const;
int UpdateDeletesBasedOnTableName(const String&);
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_client.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database_client.cc
index 5c936399e32..a05e62d3d3b 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_client.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_client.cc
@@ -30,8 +30,8 @@
#include "third_party/blink/renderer/modules/webdatabase/database_client.h"
+#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/content_settings_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/modules/webdatabase/database.h"
@@ -62,11 +62,8 @@ bool DatabaseClient::AllowDatabase(ExecutionContext* context,
unsigned estimated_size) {
DCHECK(context->IsContextThread());
Document* document = To<Document>(context);
- DCHECK(document->GetFrame());
- if (document->GetFrame()->GetContentSettingsClient()) {
- return document->GetFrame()->GetContentSettingsClient()->AllowDatabase(
- name, display_name, estimated_size);
- }
+ if (auto* client = document->GetFrame()->GetContentSettingsClient())
+ return client->AllowDatabase(name, display_name, estimated_size);
return true;
}
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_context.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database_context.cc
index 1eb9b79abff..765aaaa4115 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_context.cc
@@ -93,7 +93,7 @@ namespace blink {
// which of the 2 destructs first.
DatabaseContext* DatabaseContext::Create(ExecutionContext* context) {
- DatabaseContext* self = new DatabaseContext(context);
+ DatabaseContext* self = MakeGarbageCollected<DatabaseContext>(context);
DatabaseManager::Manager().RegisterDatabaseContext(self);
return self;
}
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_context.h b/chromium/third_party/blink/renderer/modules/webdatabase/database_context.h
index bfbf056e610..063e20b27f3 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_context.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_context.h
@@ -47,6 +47,7 @@ class DatabaseContext final : public GarbageCollectedFinalized<DatabaseContext>,
static DatabaseContext* Create(ExecutionContext*);
+ explicit DatabaseContext(ExecutionContext*);
~DatabaseContext();
void Trace(blink::Visitor*) override;
@@ -67,8 +68,6 @@ class DatabaseContext final : public GarbageCollectedFinalized<DatabaseContext>,
bool IsContextThread() const;
private:
- explicit DatabaseContext(ExecutionContext*);
-
Member<DatabaseThread> database_thread_;
bool has_open_databases_; // This never changes back to false, even after the
// database thread is closed.
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_manager.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database_manager.cc
index 919a6e193d9..abe73205556 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_manager.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_manager.cc
@@ -49,7 +49,8 @@ DatabaseManager& DatabaseManager::Manager() {
return *g_database_manager;
}
-DatabaseManager::DatabaseManager() : context_map_(new ContextMap) {}
+DatabaseManager::DatabaseManager()
+ : context_map_(MakeGarbageCollected<ContextMap>()) {}
DatabaseManager::~DatabaseManager() = default;
@@ -143,8 +144,8 @@ Database* DatabaseManager::OpenDatabaseInternal(
DatabaseContext* backend_context = DatabaseContextFor(context)->Backend();
if (DatabaseTracker::Tracker().CanEstablishDatabase(
backend_context, name, display_name, estimated_size, error)) {
- Database* backend = new Database(backend_context, name, expected_version,
- display_name, estimated_size);
+ Database* backend = MakeGarbageCollected<Database>(
+ backend_context, name, expected_version, display_name, estimated_size);
if (backend->OpenAndVerifyVersion(set_version_in_new_database, error,
error_message, creation_callback))
return backend;
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.cc
index 554d5418f73..38671f3c611 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.cc
@@ -69,7 +69,7 @@ void DatabaseThread::Start() {
void DatabaseThread::SetupDatabaseThread() {
DCHECK(thread_->IsCurrentThread());
thread_->InitializeOnThread();
- transaction_coordinator_ = new SQLTransactionCoordinator();
+ transaction_coordinator_ = MakeGarbageCollected<SQLTransactionCoordinator>();
}
void DatabaseThread::Terminate() {
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.h b/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.h
index 045b609c954..168cc4ab626 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_thread.h
@@ -44,7 +44,11 @@ class WaitableEvent;
class DatabaseThread : public GarbageCollectedFinalized<DatabaseThread> {
public:
- static DatabaseThread* Create() { return new DatabaseThread; }
+ static DatabaseThread* Create() {
+ return MakeGarbageCollected<DatabaseThread>();
+ }
+
+ DatabaseThread();
~DatabaseThread();
void Trace(blink::Visitor*);
@@ -69,8 +73,6 @@ class DatabaseThread : public GarbageCollectedFinalized<DatabaseThread> {
}
private:
- DatabaseThread();
-
void SetupDatabaseThread();
void CleanupDatabaseThread();
void CleanupDatabaseThreadCompleted();
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/database_tracker.cc b/chromium/third_party/blink/renderer/modules/webdatabase/database_tracker.cc
index a6d1208c289..99bdad2184c 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/database_tracker.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/database_tracker.cc
@@ -45,6 +45,7 @@
#include "third_party/blink/renderer/modules/webdatabase/quota_tracker.h"
#include "third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_file_system.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.cc b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.cc
index 5c77fbdb83b..b28ced3c07a 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.cc
@@ -95,13 +95,13 @@ class StatementCallback final : public SQLStatement::OnSuccessCallback {
std::unique_ptr<protocol::Array<String>> column_names =
protocol::Array<String>::create();
const Vector<String>& columns = row_list->ColumnNames();
- for (size_t i = 0; i < columns.size(); ++i)
+ for (wtf_size_t i = 0; i < columns.size(); ++i)
column_names->addItem(columns[i]);
std::unique_ptr<protocol::Array<protocol::Value>> values =
protocol::Array<protocol::Value>::create();
const Vector<SQLValue>& data = row_list->Values();
- for (size_t i = 0; i < data.size(); ++i) {
+ for (wtf_size_t i = 0; i < data.size(); ++i) {
const SQLValue& value = row_list->Values()[i];
switch (value.GetType()) {
case SQLValue::kStringValue:
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.h b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.h
index 0643e9a6c00..8e36c493031 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_agent.h
@@ -49,8 +49,10 @@ class MODULES_EXPORT InspectorDatabaseAgent final
public:
static InspectorDatabaseAgent* Create(Page* page) {
- return new InspectorDatabaseAgent(page);
+ return MakeGarbageCollected<InspectorDatabaseAgent>(page);
}
+
+ explicit InspectorDatabaseAgent(Page*);
~InspectorDatabaseAgent() override;
void Trace(blink::Visitor*) override;
@@ -73,7 +75,6 @@ class MODULES_EXPORT InspectorDatabaseAgent final
const String& version);
private:
- explicit InspectorDatabaseAgent(Page*);
void InnerEnable();
void RegisterDatabaseOnCreation(blink::Database*);
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.cc b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.cc
index 688a98e9ac6..9a696e6f7c3 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.cc
@@ -41,7 +41,8 @@ InspectorDatabaseResource* InspectorDatabaseResource::Create(
const String& domain,
const String& name,
const String& version) {
- return new InspectorDatabaseResource(database, domain, name, version);
+ return MakeGarbageCollected<InspectorDatabaseResource>(database, domain, name,
+ version);
}
InspectorDatabaseResource::InspectorDatabaseResource(Database* database,
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.h b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.h
index 9f7e8015282..f5d59f02898 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/inspector_database_resource.h
@@ -46,6 +46,10 @@ class InspectorDatabaseResource
const String& domain,
const String& name,
const String& version);
+ InspectorDatabaseResource(Database*,
+ const String& domain,
+ const String& name,
+ const String& version);
void Trace(blink::Visitor*);
void Bind(protocol::Database::Frontend*);
@@ -54,11 +58,6 @@ class InspectorDatabaseResource
String Id() const { return id_; }
private:
- InspectorDatabaseResource(Database*,
- const String& domain,
- const String& name,
- const String& version);
-
Member<Database> database_;
String id_;
String domain_;
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_error.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_error.h
index 1c44a8ee5c5..afcd120d801 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_error.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_error.h
@@ -77,9 +77,11 @@ class SQLError final : public ScriptWrappable {
public:
static SQLError* Create(const SQLErrorData& data) {
- return new SQLError(data);
+ return MakeGarbageCollected<SQLError>(data);
}
+ explicit SQLError(const SQLErrorData& data) : data_(data) {}
+
unsigned code() const { return data_.Code(); }
String message() const { return data_.Message(); }
@@ -99,8 +101,6 @@ class SQLError final : public ScriptWrappable {
static const char kVersionErrorMessage[];
private:
- explicit SQLError(const SQLErrorData& data) : data_(data) {}
-
const SQLErrorData data_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.h
index 0fbda787382..8577ba94d28 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.h
@@ -41,7 +41,10 @@ class SQLResultSet final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static SQLResultSet* Create() { return new SQLResultSet; }
+ static SQLResultSet* Create() { return MakeGarbageCollected<SQLResultSet>(); }
+
+ SQLResultSet();
+
void Trace(blink::Visitor*) override;
SQLResultSetRowList* rows() const;
@@ -55,8 +58,6 @@ class SQLResultSet final : public ScriptWrappable {
bool IsValid() { return is_valid_; }
private:
- SQLResultSet();
-
Member<SQLResultSetRowList> rows_;
int64_t insert_id_;
int rows_affected_;
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.idl b/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.idl
index 84a20be0049..acc7eda8d83 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.idl
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set.idl
@@ -32,6 +32,6 @@
] interface SQLResultSet {
readonly attribute SQLResultSetRowList rows;
- [RaisesException=Getter] readonly attribute long insertId;
+ [RaisesException=Getter] readonly attribute long long insertId;
readonly attribute long rowsAffected;
};
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set_row_list.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set_row_list.h
index 46b342fb163..206ce9b06df 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set_row_list.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_result_set_row_list.h
@@ -43,7 +43,11 @@ class SQLResultSetRowList final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- static SQLResultSetRowList* Create() { return new SQLResultSetRowList; }
+ static SQLResultSetRowList* Create() {
+ return MakeGarbageCollected<SQLResultSetRowList>();
+ }
+
+ SQLResultSetRowList() = default;
const Vector<String>& ColumnNames() const { return columns_; }
const Vector<SQLValue>& Values() const { return result_; }
@@ -55,8 +59,6 @@ class SQLResultSetRowList final : public ScriptWrappable {
ScriptValue item(ScriptState*, unsigned index, ExceptionState&);
private:
- SQLResultSetRowList() = default;
-
Vector<String> columns_;
Vector<SQLValue> result_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.cc b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.cc
index 8f40b675741..d0608815a0c 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.cc
@@ -86,7 +86,7 @@ bool SQLStatement::OnErrorV8Impl::OnError(SQLTransaction* transaction,
SQLStatement* SQLStatement::Create(Database* database,
OnSuccessCallback* callback,
OnErrorCallback* error_callback) {
- return new SQLStatement(database, callback, error_callback);
+ return MakeGarbageCollected<SQLStatement>(database, callback, error_callback);
}
SQLStatement::SQLStatement(Database* database,
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.h
index 7814694e936..7fd086c4120 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement.h
@@ -58,15 +58,17 @@ class SQLStatement final : public GarbageCollected<SQLStatement> {
class OnSuccessV8Impl : public OnSuccessCallback {
public:
static OnSuccessV8Impl* Create(V8SQLStatementCallback* callback) {
- return callback ? new OnSuccessV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnSuccessV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- bool OnSuccess(SQLTransaction*, SQLResultSet*) override;
- private:
explicit OnSuccessV8Impl(V8SQLStatementCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ bool OnSuccess(SQLTransaction*, SQLResultSet*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8SQLStatementCallback>> callback_;
};
@@ -83,20 +85,24 @@ class SQLStatement final : public GarbageCollected<SQLStatement> {
class OnErrorV8Impl : public OnErrorCallback {
public:
static OnErrorV8Impl* Create(V8SQLStatementErrorCallback* callback) {
- return callback ? new OnErrorV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnErrorV8Impl>(callback) : nullptr;
}
- void Trace(blink::Visitor*) override;
- bool OnError(SQLTransaction*, SQLError*) override;
- private:
explicit OnErrorV8Impl(V8SQLStatementErrorCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ bool OnError(SQLTransaction*, SQLError*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8SQLStatementErrorCallback>>
callback_;
};
static SQLStatement* Create(Database*, OnSuccessCallback*, OnErrorCallback*);
+
+ SQLStatement(Database*, OnSuccessCallback*, OnErrorCallback*);
+
void Trace(blink::Visitor*);
bool PerformCallback(SQLTransaction*);
@@ -107,8 +113,6 @@ class SQLStatement final : public GarbageCollected<SQLStatement> {
bool HasErrorCallback();
private:
- SQLStatement(Database*, OnSuccessCallback*, OnErrorCallback*);
-
// The SQLStatementBackend owns the SQLStatement. Hence, the backend is
// guaranteed to be outlive the SQLStatement, and it is safe for us to refer
// to the backend using a raw pointer here.
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.cc b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.cc
index e3a7b1bbd11..e331be9ff4e 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.cc
@@ -87,7 +87,8 @@ SQLStatementBackend* SQLStatementBackend::Create(
const String& statement,
const Vector<SQLValue>& arguments,
int permissions) {
- return new SQLStatementBackend(frontend, statement, arguments, permissions);
+ return MakeGarbageCollected<SQLStatementBackend>(frontend, statement,
+ arguments, permissions);
}
SQLStatementBackend::SQLStatementBackend(SQLStatement* frontend,
@@ -146,15 +147,16 @@ bool SQLStatementBackend::Execute(Database* db) {
STORAGE_DVLOG(1) << "Unable to verify correctness of statement "
<< statement_ << " - error " << result << " ("
<< database->LastErrorMsg() << ")";
- if (result == kSQLResultInterrupt)
+ if (result == kSQLResultInterrupt) {
error_ = SQLErrorData::Create(SQLError::kDatabaseErr,
"could not prepare statement", result,
"interrupted");
- else
+ } else {
error_ = SQLErrorData::Create(SQLError::kSyntaxErr,
"could not prepare statement", result,
database->LastErrorMsg());
- db->ReportExecuteStatementResult(1, error_->Code(), result);
+ }
+ db->ReportSqliteError(result);
return false;
}
@@ -167,7 +169,6 @@ bool SQLStatementBackend::Execute(Database* db) {
error_ = SQLErrorData::Create(
SQLError::kSyntaxErr,
"number of '?'s in statement string does not match argument count");
- db->ReportExecuteStatementResult(2, error_->Code(), 0);
return false;
}
@@ -181,7 +182,7 @@ bool SQLStatementBackend::Execute(Database* db) {
if (result != kSQLResultOk) {
STORAGE_DVLOG(1) << "Failed to bind value index " << (i + 1)
<< " to statement for query " << statement_;
- db->ReportExecuteStatementResult(3, SQLError::kDatabaseErr, result);
+ db->ReportSqliteError(result);
error_ =
SQLErrorData::Create(SQLError::kDatabaseErr, "could not bind value",
result, database->LastErrorMsg());
@@ -206,7 +207,7 @@ bool SQLStatementBackend::Execute(Database* db) {
} while (result == kSQLResultRow);
if (result != kSQLResultDone) {
- db->ReportExecuteStatementResult(4, SQLError::kDatabaseErr, result);
+ db->ReportSqliteError(result);
error_ = SQLErrorData::Create(SQLError::kDatabaseErr,
"could not iterate results", result,
database->LastErrorMsg());
@@ -222,14 +223,14 @@ bool SQLStatementBackend::Execute(Database* db) {
SetFailureDueToQuota(db);
return false;
} else if (result == kSQLResultConstraint) {
- db->ReportExecuteStatementResult(6, SQLError::kConstraintErr, result);
+ db->ReportSqliteError(result);
error_ = SQLErrorData::Create(
SQLError::kConstraintErr,
"could not execute statement due to a constraint failure", result,
database->LastErrorMsg());
return false;
} else {
- db->ReportExecuteStatementResult(5, SQLError::kDatabaseErr, result);
+ db->ReportSqliteError(result);
error_ = SQLErrorData::Create(SQLError::kDatabaseErr,
"could not execute statement", result,
database->LastErrorMsg());
@@ -242,14 +243,12 @@ bool SQLStatementBackend::Execute(Database* db) {
// For now, this seems sufficient.
result_set_->SetRowsAffected(database->LastChanges());
- db->ReportExecuteStatementResult(0, -1, 0); // OK
return true;
}
void SQLStatementBackend::SetVersionMismatchedError(Database* database) {
DCHECK(!error_);
DCHECK(!result_set_->IsValid());
- database->ReportExecuteStatementResult(7, SQLError::kVersionErr, 0);
error_ = SQLErrorData::Create(
SQLError::kVersionErr,
"current version of the database and `oldVersion` argument do not match");
@@ -258,7 +257,6 @@ void SQLStatementBackend::SetVersionMismatchedError(Database* database) {
void SQLStatementBackend::SetFailureDueToQuota(Database* database) {
DCHECK(!error_);
DCHECK(!result_set_->IsValid());
- database->ReportExecuteStatementResult(8, SQLError::kQuotaErr, 0);
error_ = SQLErrorData::Create(SQLError::kQuotaErr,
"there was not enough remaining storage "
"space, or the storage quota was reached and "
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.h
index 166a7f98705..bd4174c581a 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_statement_backend.h
@@ -49,6 +49,12 @@ class SQLStatementBackend final
const String& sql_statement,
const Vector<SQLValue>& arguments,
int permissions);
+
+ SQLStatementBackend(SQLStatement*,
+ const String& statement,
+ const Vector<SQLValue>& arguments,
+ int permissions);
+
void Trace(blink::Visitor*);
bool Execute(Database*);
@@ -64,11 +70,6 @@ class SQLStatementBackend final
SQLResultSet* SqlResultSet() const;
private:
- SQLStatementBackend(SQLStatement*,
- const String& statement,
- const Vector<SQLValue>& arguments,
- int permissions);
-
void SetFailureDueToQuota(Database*);
void ClearFailureDueToQuota();
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc
index 6c1024fc530..b2fb0e7bdd4 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.cc
@@ -85,8 +85,8 @@ SQLTransaction* SQLTransaction::Create(Database* db,
OnSuccessCallback* success_callback,
OnErrorCallback* error_callback,
bool read_only) {
- return new SQLTransaction(db, callback, success_callback, error_callback,
- read_only);
+ return MakeGarbageCollected<SQLTransaction>(db, callback, success_callback,
+ error_callback, read_only);
}
SQLTransaction::SQLTransaction(Database* db,
@@ -198,13 +198,11 @@ SQLTransactionState SQLTransaction::DeliverTransactionCallback() {
// jump to the error callback.
SQLTransactionState next_state = SQLTransactionState::kRunStatements;
if (should_deliver_error_callback) {
- database_->ReportStartTransactionResult(5, SQLError::kUnknownErr, 0);
transaction_error_ = SQLErrorData::Create(
SQLError::kUnknownErr,
"the SQLTransactionCallback was null or threw an exception");
next_state = SQLTransactionState::kDeliverTransactionErrorCallback;
}
- database_->ReportStartTransactionResult(0, -1, 0); // OK
return next_state;
}
@@ -249,7 +247,6 @@ SQLTransactionState SQLTransaction::DeliverStatementCallback() {
execute_sql_allowed_ = false;
if (result) {
- database_->ReportCommitTransactionResult(2, SQLError::kUnknownErr, 0);
transaction_error_ =
SQLErrorData::Create(SQLError::kUnknownErr,
"the statement callback raised an exception or "
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.h
index 43390f358c9..7ba78635a73 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction.h
@@ -69,15 +69,17 @@ class SQLTransaction final : public ScriptWrappable,
class OnProcessV8Impl : public OnProcessCallback {
public:
static OnProcessV8Impl* Create(V8SQLTransactionCallback* callback) {
- return callback ? new OnProcessV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnProcessV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- bool OnProcess(SQLTransaction*) override;
- private:
explicit OnProcessV8Impl(V8SQLTransactionCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ bool OnProcess(SQLTransaction*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8SQLTransactionCallback>> callback_;
};
@@ -95,15 +97,17 @@ class SQLTransaction final : public ScriptWrappable,
class OnSuccessV8Impl : public OnSuccessCallback {
public:
static OnSuccessV8Impl* Create(V8VoidCallback* callback) {
- return callback ? new OnSuccessV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnSuccessV8Impl>(callback)
+ : nullptr;
}
- void Trace(blink::Visitor*) override;
- void OnSuccess() override;
- private:
explicit OnSuccessV8Impl(V8VoidCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ void OnSuccess() override;
+
+ private:
Member<V8PersistentCallbackInterface<V8VoidCallback>> callback_;
};
@@ -120,15 +124,16 @@ class SQLTransaction final : public ScriptWrappable,
class OnErrorV8Impl : public OnErrorCallback {
public:
static OnErrorV8Impl* Create(V8SQLTransactionErrorCallback* callback) {
- return callback ? new OnErrorV8Impl(callback) : nullptr;
+ return callback ? MakeGarbageCollected<OnErrorV8Impl>(callback) : nullptr;
}
- void Trace(blink::Visitor*) override;
- bool OnError(SQLError*) override;
- private:
explicit OnErrorV8Impl(V8SQLTransactionErrorCallback* callback)
: callback_(ToV8PersistentCallbackInterface(callback)) {}
+ void Trace(blink::Visitor*) override;
+ bool OnError(SQLError*) override;
+
+ private:
Member<V8PersistentCallbackInterface<V8SQLTransactionErrorCallback>>
callback_;
};
@@ -138,6 +143,12 @@ class SQLTransaction final : public ScriptWrappable,
OnSuccessCallback*,
OnErrorCallback*,
bool read_only);
+
+ SQLTransaction(Database*,
+ OnProcessCallback*,
+ OnSuccessCallback*,
+ OnErrorCallback*,
+ bool read_only);
~SQLTransaction() override;
void Trace(blink::Visitor*) override;
@@ -168,12 +179,6 @@ class SQLTransaction final : public ScriptWrappable,
void SetBackend(SQLTransactionBackend*);
private:
- SQLTransaction(Database*,
- OnProcessCallback*,
- OnSuccessCallback*,
- OnErrorCallback*,
- bool read_only);
-
void ClearCallbacks();
// State Machine functions:
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc
index 9376297e0cd..11ef20ccd07 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.cc
@@ -369,7 +369,8 @@ SQLTransactionBackend* SQLTransactionBackend::Create(
SQLTransaction* frontend,
SQLTransactionWrapper* wrapper,
bool read_only) {
- return new SQLTransactionBackend(db, frontend, wrapper, read_only);
+ return MakeGarbageCollected<SQLTransactionBackend>(db, frontend, wrapper,
+ read_only);
}
SQLTransactionBackend::SQLTransactionBackend(Database* db,
@@ -616,8 +617,7 @@ SQLTransactionState SQLTransactionBackend::OpenTransactionAndPreflight() {
// callback if that fails.
if (!sqlite_transaction_->InProgress()) {
DCHECK(!database_->SqliteDatabase().TransactionInProgress());
- database_->ReportStartTransactionResult(
- 2, SQLError::kDatabaseErr, database_->SqliteDatabase().LastError());
+ database_->ReportSqliteError(database_->SqliteDatabase().LastError());
transaction_error_ = SQLErrorData::Create(
SQLError::kDatabaseErr, "unable to begin transaction",
database_->SqliteDatabase().LastError(),
@@ -632,8 +632,7 @@ SQLTransactionState SQLTransactionBackend::OpenTransactionAndPreflight() {
// this is just a map lookup.
String actual_version;
if (!database_->GetActualVersionForTransaction(actual_version)) {
- database_->ReportStartTransactionResult(
- 3, SQLError::kDatabaseErr, database_->SqliteDatabase().LastError());
+ database_->ReportSqliteError(database_->SqliteDatabase().LastError());
transaction_error_ =
SQLErrorData::Create(SQLError::kDatabaseErr, "unable to read version",
database_->SqliteDatabase().LastError(),
@@ -655,7 +654,6 @@ SQLTransactionState SQLTransactionBackend::OpenTransactionAndPreflight() {
if (wrapper_->SqlError()) {
transaction_error_ = SQLErrorData::Create(*wrapper_->SqlError());
} else {
- database_->ReportStartTransactionResult(4, SQLError::kUnknownErr, 0);
transaction_error_ = SQLErrorData::Create(
SQLError::kUnknownErr,
"unknown error occurred during transaction preflight");
@@ -774,7 +772,6 @@ SQLTransactionState SQLTransactionBackend::NextStateForCurrentStatementError() {
transaction_error_ =
SQLErrorData::Create(*current_statement_backend_->SqlError());
} else {
- database_->ReportCommitTransactionResult(1, SQLError::kDatabaseErr, 0);
transaction_error_ = SQLErrorData::Create(
SQLError::kDatabaseErr, "the statement failed to execute");
}
@@ -790,7 +787,6 @@ SQLTransactionState SQLTransactionBackend::PostflightAndCommit() {
if (wrapper_->SqlError()) {
transaction_error_ = SQLErrorData::Create(*wrapper_->SqlError());
} else {
- database_->ReportCommitTransactionResult(3, SQLError::kUnknownErr, 0);
transaction_error_ = SQLErrorData::Create(
SQLError::kUnknownErr,
"unknown error occurred during transaction postflight");
@@ -810,8 +806,7 @@ SQLTransactionState SQLTransactionBackend::PostflightAndCommit() {
if (sqlite_transaction_->InProgress()) {
if (wrapper_)
wrapper_->HandleCommitFailedAfterPostflight(this);
- database_->ReportCommitTransactionResult(
- 4, SQLError::kDatabaseErr, database_->SqliteDatabase().LastError());
+ database_->ReportSqliteError(database_->SqliteDatabase().LastError());
transaction_error_ = SQLErrorData::Create(
SQLError::kDatabaseErr, "unable to commit transaction",
database_->SqliteDatabase().LastError(),
@@ -819,8 +814,6 @@ SQLTransactionState SQLTransactionBackend::PostflightAndCommit() {
return NextStateForTransactionError();
}
- database_->ReportCommitTransactionResult(0, -1, 0); // OK
-
// Vacuum the database if anything was deleted.
if (database_->HadDeletes())
database_->IncrementalVacuumIfNeeded();
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.h b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.h
index bd98c3509ea..d6197d45bae 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sql_transaction_backend.h
@@ -67,6 +67,10 @@ class SQLTransactionBackend final
SQLTransactionWrapper*,
bool read_only);
+ SQLTransactionBackend(Database*,
+ SQLTransaction*,
+ SQLTransactionWrapper*,
+ bool read_only);
~SQLTransactionBackend() override;
void Trace(blink::Visitor*);
@@ -88,11 +92,6 @@ class SQLTransactionBackend final
int permissions);
private:
- SQLTransactionBackend(Database*,
- SQLTransaction*,
- SQLTransactionWrapper*,
- bool read_only);
-
void DoCleanup();
void EnqueueStatementBackend(SQLStatementBackend*);
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.cc b/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.cc
index 277ae05f216..ae8ea1994f3 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.cc
@@ -47,9 +47,6 @@ SQLiteDatabase::SQLiteDatabase()
: db_(nullptr),
page_size_(-1),
transaction_in_progress_(false),
-#if DCHECK_IS_ON()
- sharable_(false),
-#endif
opening_thread_(0),
open_error_(SQLITE_ERROR),
open_error_message_(),
@@ -314,14 +311,13 @@ int SQLiteDatabase::AuthorizerFunction(void* user_data,
case SQLITE_UPDATE:
return auth->AllowUpdate(parameter1, parameter2);
case SQLITE_ATTACH:
- return auth->AllowAttach(parameter1);
+ return kSQLAuthDeny;
case SQLITE_DETACH:
- return auth->AllowDetach(parameter1);
+ return kSQLAuthDeny;
case SQLITE_ALTER_TABLE:
return auth->AllowAlterTable(parameter1, parameter2);
case SQLITE_REINDEX:
return auth->AllowReindex(parameter1);
-#if SQLITE_VERSION_NUMBER >= 3003013
case SQLITE_ANALYZE:
return auth->AllowAnalyze(parameter1);
case SQLITE_CREATE_VTABLE:
@@ -330,11 +326,13 @@ int SQLiteDatabase::AuthorizerFunction(void* user_data,
return auth->DropVTable(parameter1, parameter2);
case SQLITE_FUNCTION:
return auth->AllowFunction(parameter2);
-#endif
- default:
- NOTREACHED();
+ case SQLITE_SAVEPOINT:
+ return kSQLAuthDeny;
+ case SQLITE_RECURSIVE:
return kSQLAuthDeny;
}
+ NOTREACHED();
+ return kSQLAuthDeny;
}
void SQLiteDatabase::SetAuthorizer(DatabaseAuthorizer* auth) {
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.h b/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.h
index 16717405c82..6d109ed13ca 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.h
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_database.h
@@ -35,10 +35,6 @@
#include "third_party/blink/renderer/platform/wtf/threading.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
-#if defined(COMPILER_MSVC)
-#pragma warning(disable : 4800)
-#endif
-
struct sqlite3;
namespace blink {
@@ -97,7 +93,7 @@ class SQLiteDatabase {
sqlite3* Sqlite3Handle() const {
#if DCHECK_IS_ON()
- DCHECK_EQ(sharable_ || CurrentThread(), opening_thread_ || !db_);
+ DCHECK_EQ(!!CurrentThread(), opening_thread_ || !db_);
#endif
return db_;
}
@@ -140,9 +136,6 @@ class SQLiteDatabase {
int page_size_;
bool transaction_in_progress_;
-#if DCHECK_IS_ON()
- bool sharable_;
-#endif
Mutex authorizer_lock_;
CrossThreadPersistent<DatabaseAuthorizer> authorizer_;
diff --git a/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc b/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc
index 5b443d16633..fac805a93f0 100644
--- a/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc
+++ b/chromium/third_party/blink/renderer/modules/webdatabase/sqlite/sqlite_statement.cc
@@ -254,24 +254,21 @@ SQLValue SQLiteStatement::GetColumnValue(int col) {
// SQLite is typed per value. optional column types are
// "(mostly) ignored"
- sqlite3_value* value = sqlite3_column_value(statement_, col);
- switch (sqlite3_value_type(value)) {
+ switch (sqlite3_column_type(statement_, col)) {
case SQLITE_INTEGER: // SQLValue and JS don't represent integers, so use
// FLOAT -case
case SQLITE_FLOAT:
- return SQLValue(sqlite3_value_double(value));
+ return SQLValue(sqlite3_column_double(statement_, col));
case SQLITE_BLOB: // SQLValue and JS don't represent blobs, so use TEXT
// -case
case SQLITE_TEXT: {
- const UChar* string =
- reinterpret_cast<const UChar*>(sqlite3_value_text16(value));
- unsigned length = sqlite3_value_bytes16(value) / sizeof(UChar);
+ const UChar* string = reinterpret_cast<const UChar*>(
+ sqlite3_column_text16(statement_, col));
+ unsigned length = sqlite3_column_bytes16(statement_, col) / sizeof(UChar);
return SQLValue(StringImpl::Create8BitIfPossible(string, length));
}
case SQLITE_NULL:
return SQLValue();
- default:
- break;
}
NOTREACHED();
return SQLValue();
diff --git a/chromium/third_party/blink/renderer/modules/webgl/PRESUBMIT.py b/chromium/third_party/blink/renderer/modules/webgl/PRESUBMIT.py
deleted file mode 100644
index ca8282aba0b..00000000000
--- a/chromium/third_party/blink/renderer/modules/webgl/PRESUBMIT.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (c) 2016 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Top-level presubmit script for Source/modules/webgl.
-
-See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
-for more details about the presubmit API built into depot_tools.
-"""
-
-def PostUploadHook(cl, change, output_api):
- """git cl upload will call this hook after the issue is created/modified.
-
- This hook modifies the CL description in order to run extra GPU
- tests (in particular, the WebGL 2.0 conformance tests) in addition
- to the regular CQ try bots. This test suite is too large to run
- against all Chromium commits, but should be run against changes
- likely to affect these tests.
- """
- return output_api.EnsureCQIncludeTrybotsAreAdded(
- cl,
- ['luci.chromium.try:linux_optional_gpu_tests_rel',
- 'luci.chromium.try:mac_optional_gpu_tests_rel',
- 'luci.chromium.try:win_optional_gpu_tests_rel',
- 'luci.chromium.try:android_optional_gpu_tests_rel'],
- 'Automatically added optional GPU tests to run on CQ.')
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.cc
index f84a9bde15b..9ccc0f19eaa 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.cc
@@ -16,7 +16,7 @@ WebGLExtensionName EXTBlendMinMax::GetName() const {
}
EXTBlendMinMax* EXTBlendMinMax::Create(WebGLRenderingContextBase* context) {
- return new EXTBlendMinMax(context);
+ return MakeGarbageCollected<EXTBlendMinMax>(context);
}
bool EXTBlendMinMax::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.h b/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.h
index a9a6c261e63..09598f29db3 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_blend_min_max.h
@@ -17,10 +17,9 @@ class EXTBlendMinMax final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTBlendMinMax(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.cc
index e19fa24f2ed..bcce26a5432 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.cc
@@ -18,7 +18,7 @@ WebGLExtensionName EXTColorBufferFloat::GetName() const {
EXTColorBufferFloat* EXTColorBufferFloat::Create(
WebGLRenderingContextBase* context) {
- return new EXTColorBufferFloat(context);
+ return MakeGarbageCollected<EXTColorBufferFloat>(context);
}
bool EXTColorBufferFloat::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.h b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.h
index 74c86a62892..15a85874ae2 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_float.h
@@ -17,10 +17,9 @@ class EXTColorBufferFloat final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTColorBufferFloat(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.cc
index 166eaae2491..82bd7bc0ad0 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.cc
@@ -37,7 +37,7 @@ WebGLExtensionName EXTColorBufferHalfFloat::GetName() const {
EXTColorBufferHalfFloat* EXTColorBufferHalfFloat::Create(
WebGLRenderingContextBase* context) {
- return new EXTColorBufferHalfFloat(context);
+ return MakeGarbageCollected<EXTColorBufferHalfFloat>(context);
}
bool EXTColorBufferHalfFloat::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.h b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.h
index bf31b51ce77..e82ec1b7d6b 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_color_buffer_half_float.h
@@ -38,10 +38,9 @@ class EXTColorBufferHalfFloat final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTColorBufferHalfFloat(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.cc
index 8f6dcdb31fe..4be645fb90e 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.cc
@@ -17,7 +17,7 @@ WebGLExtensionName EXTDisjointTimerQuery::GetName() const {
EXTDisjointTimerQuery* EXTDisjointTimerQuery::Create(
WebGLRenderingContextBase* context) {
- return new EXTDisjointTimerQuery(context);
+ return MakeGarbageCollected<EXTDisjointTimerQuery>(context);
}
bool EXTDisjointTimerQuery::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.h b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.h
index ad18e650524..2a1e205caae 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query.h
@@ -22,6 +22,8 @@ class EXTDisjointTimerQuery final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit EXTDisjointTimerQuery(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
WebGLTimerQueryEXT* createQueryEXT();
@@ -37,7 +39,6 @@ class EXTDisjointTimerQuery final : public WebGLExtension {
private:
friend class WebGLTimerQueryEXT;
- explicit EXTDisjointTimerQuery(WebGLRenderingContextBase*);
Member<WebGLTimerQueryEXT> current_elapsed_query_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.cc
index 123d601d9e4..8eba91c82ee 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.cc
@@ -16,7 +16,8 @@ WebGLExtensionName EXTDisjointTimerQueryWebGL2::GetName() const {
EXTDisjointTimerQueryWebGL2* EXTDisjointTimerQueryWebGL2::Create(
WebGLRenderingContextBase* context) {
- EXTDisjointTimerQueryWebGL2* o = new EXTDisjointTimerQueryWebGL2(context);
+ EXTDisjointTimerQueryWebGL2* o =
+ MakeGarbageCollected<EXTDisjointTimerQueryWebGL2>(context);
return o;
}
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.h b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.h
index 076932abc04..8ff994aa549 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_disjoint_timer_query_webgl2.h
@@ -23,14 +23,13 @@ class EXTDisjointTimerQueryWebGL2 final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit EXTDisjointTimerQueryWebGL2(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
void queryCounterEXT(WebGLQuery*, GLenum);
void Trace(blink::Visitor*) override;
-
- private:
- explicit EXTDisjointTimerQueryWebGL2(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.cc
index 7185974ad17..e5e78867a1d 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.cc
@@ -37,7 +37,7 @@ WebGLExtensionName EXTFragDepth::GetName() const {
}
EXTFragDepth* EXTFragDepth::Create(WebGLRenderingContextBase* context) {
- return new EXTFragDepth(context);
+ return MakeGarbageCollected<EXTFragDepth>(context);
}
bool EXTFragDepth::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.h b/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.h
index 16d9e78f266..3d332a90cdf 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_frag_depth.h
@@ -38,10 +38,9 @@ class EXTFragDepth final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTFragDepth(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.cc
index 173f6c28da8..a15db7a72af 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.cc
@@ -18,7 +18,7 @@ WebGLExtensionName EXTShaderTextureLOD::GetName() const {
EXTShaderTextureLOD* EXTShaderTextureLOD::Create(
WebGLRenderingContextBase* context) {
- return new EXTShaderTextureLOD(context);
+ return MakeGarbageCollected<EXTShaderTextureLOD>(context);
}
bool EXTShaderTextureLOD::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.h b/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.h
index 8912f836509..1f8065e5ed0 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_shader_texture_lod.h
@@ -17,10 +17,9 @@ class EXTShaderTextureLOD final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTShaderTextureLOD(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.cc
index fad8cc277f2..bd28afaf3a2 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.cc
@@ -17,7 +17,7 @@ WebGLExtensionName EXTsRGB::GetName() const {
}
EXTsRGB* EXTsRGB::Create(WebGLRenderingContextBase* context) {
- return new EXTsRGB(context);
+ return MakeGarbageCollected<EXTsRGB>(context);
}
bool EXTsRGB::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.h b/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.h
index 9e655907a06..673f3b9e690 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_srgb.h
@@ -17,10 +17,9 @@ class EXTsRGB final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTsRGB(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.cc b/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.cc
index d9e9005e778..31d33a985f6 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.cc
@@ -40,7 +40,7 @@ WebGLExtensionName EXTTextureFilterAnisotropic::GetName() const {
EXTTextureFilterAnisotropic* EXTTextureFilterAnisotropic::Create(
WebGLRenderingContextBase* context) {
- return new EXTTextureFilterAnisotropic(context);
+ return MakeGarbageCollected<EXTTextureFilterAnisotropic>(context);
}
bool EXTTextureFilterAnisotropic::Supported(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.h b/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.h
index 90dfa126a63..353e0487f78 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/ext_texture_filter_anisotropic.h
@@ -38,10 +38,9 @@ class EXTTextureFilterAnisotropic final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit EXTTextureFilterAnisotropic(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.cc
index e7f6d2ebbab..e1b13e49ef2 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.cc
@@ -39,7 +39,7 @@ WebGLExtensionName OESElementIndexUint::GetName() const {
OESElementIndexUint* OESElementIndexUint::Create(
WebGLRenderingContextBase* context) {
- return new OESElementIndexUint(context);
+ return MakeGarbageCollected<OESElementIndexUint>(context);
}
bool OESElementIndexUint::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.h b/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.h
index b9fe21f879c..5e57acac62a 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_element_index_uint.h
@@ -40,7 +40,6 @@ class OESElementIndexUint final : public WebGLExtension {
WebGLExtensionName GetName() const override;
- private:
explicit OESElementIndexUint(WebGLRenderingContextBase*);
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.cc
index c0d37c334e1..ff4b64bc2fb 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.cc
@@ -40,7 +40,7 @@ WebGLExtensionName OESStandardDerivatives::GetName() const {
OESStandardDerivatives* OESStandardDerivatives::Create(
WebGLRenderingContextBase* context) {
- return new OESStandardDerivatives(context);
+ return MakeGarbageCollected<OESStandardDerivatives>(context);
}
bool OESStandardDerivatives::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.h b/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.h
index 264e9bc8898..5b6023632a1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_standard_derivatives.h
@@ -40,7 +40,6 @@ class OESStandardDerivatives final : public WebGLExtension {
WebGLExtensionName GetName() const override;
- private:
explicit OESStandardDerivatives(WebGLRenderingContextBase*);
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.cc
index 082ea22b173..8bc1f14ab00 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.cc
@@ -44,7 +44,7 @@ WebGLExtensionName OESTextureFloat::GetName() const {
}
OESTextureFloat* OESTextureFloat::Create(WebGLRenderingContextBase* context) {
- return new OESTextureFloat(context);
+ return MakeGarbageCollected<OESTextureFloat>(context);
}
bool OESTextureFloat::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.h b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.h
index 1a40b6ce943..95f64796bf4 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float.h
@@ -40,7 +40,6 @@ class OESTextureFloat final : public WebGLExtension {
WebGLExtensionName GetName() const override;
- private:
explicit OESTextureFloat(WebGLRenderingContextBase*);
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.cc
index 8a4afa044d8..588c758cc72 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.cc
@@ -39,7 +39,7 @@ WebGLExtensionName OESTextureFloatLinear::GetName() const {
OESTextureFloatLinear* OESTextureFloatLinear::Create(
WebGLRenderingContextBase* context) {
- return new OESTextureFloatLinear(context);
+ return MakeGarbageCollected<OESTextureFloatLinear>(context);
}
bool OESTextureFloatLinear::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.h b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.h
index 8714877f61c..5aa67dfd7c4 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_float_linear.h
@@ -38,10 +38,9 @@ class OESTextureFloatLinear final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit OESTextureFloatLinear(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.cc
index 184102fba2a..ef44f4a4a5d 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.cc
@@ -41,7 +41,7 @@ WebGLExtensionName OESTextureHalfFloat::GetName() const {
OESTextureHalfFloat* OESTextureHalfFloat::Create(
WebGLRenderingContextBase* context) {
- return new OESTextureHalfFloat(context);
+ return MakeGarbageCollected<OESTextureHalfFloat>(context);
}
bool OESTextureHalfFloat::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.h b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.h
index 4333592c4fd..470c8aad6a0 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float.h
@@ -38,10 +38,9 @@ class OESTextureHalfFloat final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit OESTextureHalfFloat(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.cc
index 943f00eaf99..e17e2647472 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.cc
@@ -40,7 +40,7 @@ WebGLExtensionName OESTextureHalfFloatLinear::GetName() const {
OESTextureHalfFloatLinear* OESTextureHalfFloatLinear::Create(
WebGLRenderingContextBase* context) {
- return new OESTextureHalfFloatLinear(context);
+ return MakeGarbageCollected<OESTextureHalfFloatLinear>(context);
}
bool OESTextureHalfFloatLinear::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.h b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.h
index da06b2e5737..19405ae16e6 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_texture_half_float_linear.h
@@ -38,10 +38,9 @@ class OESTextureHalfFloatLinear final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit OESTextureHalfFloatLinear(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.cc b/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.cc
index 9a14b859003..359498a4841 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.cc
@@ -44,7 +44,7 @@ WebGLExtensionName OESVertexArrayObject::GetName() const {
OESVertexArrayObject* OESVertexArrayObject::Create(
WebGLRenderingContextBase* context) {
- return new OESVertexArrayObject(context);
+ return MakeGarbageCollected<OESVertexArrayObject>(context);
}
WebGLVertexArrayObjectOES* OESVertexArrayObject::createVertexArrayOES() {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.h b/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.h
index 039b485ac65..98f87c978fa 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/oes_vertex_array_object.h
@@ -41,15 +41,14 @@ class OESVertexArrayObject final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit OESVertexArrayObject(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
WebGLVertexArrayObjectOES* createVertexArrayOES();
void deleteVertexArrayOES(WebGLVertexArrayObjectOES*);
GLboolean isVertexArrayOES(WebGLVertexArrayObjectOES*);
void bindVertexArrayOES(WebGLVertexArrayObjectOES*);
-
- private:
- explicit OESVertexArrayObject(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.cc
index cef47c715b5..fe827188990 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.cc
@@ -40,7 +40,7 @@ static bool ShouldCreateWebGL2ComputeContext(
CanvasRenderingContextHost* host) {
if (!context_provider) {
host->HostDispatchEvent(WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror,
+ event_type_names::kWebglcontextcreationerror,
"Failed to create a WebGL2 Compute context."));
return false;
}
@@ -69,12 +69,12 @@ CanvasRenderingContext* WebGL2ComputeRenderingContext::Factory::Create(
if (!ShouldCreateWebGL2ComputeContext(context_provider.get(), host))
return nullptr;
WebGL2ComputeRenderingContext* rendering_context =
- new WebGL2ComputeRenderingContext(host, std::move(context_provider),
- using_gpu_compositing, attrs);
+ MakeGarbageCollected<WebGL2ComputeRenderingContext>(
+ host, std::move(context_provider), using_gpu_compositing, attrs);
if (!rendering_context->GetDrawingBuffer()) {
host->HostDispatchEvent(WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror,
+ event_type_names::kWebglcontextcreationerror,
"Could not create a WebGL2 Compute context."));
return nullptr;
}
@@ -88,7 +88,7 @@ CanvasRenderingContext* WebGL2ComputeRenderingContext::Factory::Create(
void WebGL2ComputeRenderingContext::Factory::OnError(HTMLCanvasElement* canvas,
const String& error) {
canvas->DispatchEvent(*WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror, error));
+ event_type_names::kWebglcontextcreationerror, error));
}
WebGL2ComputeRenderingContext::WebGL2ComputeRenderingContext(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.h b/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.h
index 2b83035147e..914ddcb5cbf 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_compute_rendering_context.h
@@ -38,6 +38,12 @@ class WebGL2ComputeRenderingContext : public WebGL2ComputeRenderingContextBase {
void OnError(HTMLCanvasElement*, const String& error) override;
};
+ WebGL2ComputeRenderingContext(
+ CanvasRenderingContextHost*,
+ std::unique_ptr<WebGraphicsContext3DProvider>,
+ bool using_gpu_compositing,
+ const CanvasContextCreationAttributesCore& requested_attributes);
+
CanvasRenderingContext::ContextType GetContextType() const override {
return CanvasRenderingContext::kContextWebgl2Compute;
}
@@ -52,12 +58,6 @@ class WebGL2ComputeRenderingContext : public WebGL2ComputeRenderingContextBase {
void Trace(blink::Visitor*) override;
protected:
- WebGL2ComputeRenderingContext(
- CanvasRenderingContextHost*,
- std::unique_ptr<WebGraphicsContext3DProvider>,
- bool using_gpu_compositing,
- const CanvasContextCreationAttributesCore& requested_attributes);
-
Member<EXTColorBufferFloat> ext_color_buffer_float_;
Member<EXTDisjointTimerQueryWebGL2> ext_disjoint_timer_query_web_gl2_;
Member<EXTTextureFilterAnisotropic> ext_texture_filter_anisotropic_;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.cc
index 5c3ae9ea8ae..198f039622d 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.cc
@@ -41,7 +41,7 @@ static bool ShouldCreateContext(WebGraphicsContext3DProvider* context_provider,
CanvasRenderingContextHost* host) {
if (!context_provider) {
host->HostDispatchEvent(
- WebGLContextEvent::Create(EventTypeNames::webglcontextcreationerror,
+ WebGLContextEvent::Create(event_type_names::kWebglcontextcreationerror,
"Failed to create a WebGL2 context."));
return false;
}
@@ -68,12 +68,13 @@ CanvasRenderingContext* WebGL2RenderingContext::Factory::Create(
host, attrs, Platform::kWebGL2ContextType, &using_gpu_compositing));
if (!ShouldCreateContext(context_provider.get(), host))
return nullptr;
- WebGL2RenderingContext* rendering_context = new WebGL2RenderingContext(
- host, std::move(context_provider), using_gpu_compositing, attrs);
+ WebGL2RenderingContext* rendering_context =
+ MakeGarbageCollected<WebGL2RenderingContext>(
+ host, std::move(context_provider), using_gpu_compositing, attrs);
if (!rendering_context->GetDrawingBuffer()) {
host->HostDispatchEvent(
- WebGLContextEvent::Create(EventTypeNames::webglcontextcreationerror,
+ WebGLContextEvent::Create(event_type_names::kWebglcontextcreationerror,
"Could not create a WebGL2 context."));
return nullptr;
}
@@ -87,7 +88,7 @@ CanvasRenderingContext* WebGL2RenderingContext::Factory::Create(
void WebGL2RenderingContext::Factory::OnError(HTMLCanvasElement* canvas,
const String& error) {
canvas->DispatchEvent(*WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror, error));
+ event_type_names::kWebglcontextcreationerror, error));
}
WebGL2RenderingContext::WebGL2RenderingContext(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h
index 4b6f24ea49a..18a4af61f3a 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context.h
@@ -40,6 +40,12 @@ class WebGL2RenderingContext : public WebGL2RenderingContextBase {
void OnError(HTMLCanvasElement*, const String& error) override;
};
+ WebGL2RenderingContext(
+ CanvasRenderingContextHost*,
+ std::unique_ptr<WebGraphicsContext3DProvider>,
+ bool using_gpu_compositing,
+ const CanvasContextCreationAttributesCore& requested_attributes);
+
CanvasRenderingContext::ContextType GetContextType() const override {
return CanvasRenderingContext::kContextWebgl2;
}
@@ -52,12 +58,6 @@ class WebGL2RenderingContext : public WebGL2RenderingContextBase {
void Trace(blink::Visitor*) override;
protected:
- WebGL2RenderingContext(
- CanvasRenderingContextHost*,
- std::unique_ptr<WebGraphicsContext3DProvider>,
- bool using_gpu_compositing,
- const CanvasContextCreationAttributesCore& requested_attributes);
-
Member<EXTColorBufferFloat> ext_color_buffer_float_;
Member<EXTDisjointTimerQueryWebGL2> ext_disjoint_timer_query_web_gl2_;
Member<EXTTextureFilterAnisotropic> ext_texture_filter_anisotropic_;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc
index 690a0193749..3bd6dac474b 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc
@@ -589,7 +589,7 @@ bool WebGL2RenderingContextBase::CheckAndTranslateAttachments(
if (!framebuffer_binding) {
// For the default framebuffer, translate GL_COLOR/GL_DEPTH/GL_STENCIL.
// The default framebuffer of WebGL is not fb 0, it is an internal fbo.
- for (size_t i = 0; i < attachments.size(); ++i) {
+ for (wtf_size_t i = 0; i < attachments.size(); ++i) {
switch (attachments[i]) {
case GL_COLOR:
attachments[i] = GL_COLOR_ATTACHMENT0;
@@ -758,7 +758,7 @@ void WebGL2RenderingContextBase::readPixels(
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels,
- GLuint offset) {
+ long long offset) {
if (isContextLost())
return;
if (bound_pixel_pack_buffer_.Get()) {
@@ -4035,7 +4035,7 @@ void WebGL2RenderingContextBase::deleteSampler(WebGLSampler* sampler) {
if (isContextLost())
return;
- for (size_t i = 0; i < sampler_units_.size(); ++i) {
+ for (wtf_size_t i = 0; i < sampler_units_.size(); ++i) {
if (sampler == sampler_units_[i]) {
sampler_units_[i] = nullptr;
ContextGL()->BindSampler(i, 0);
@@ -4465,8 +4465,8 @@ void WebGL2RenderingContextBase::transformFeedbackVaryings(
Vector<CString> keep_alive; // Must keep these instances alive while looking
// at their data
Vector<const char*> varying_strings;
- for (size_t i = 0; i < varyings.size(); ++i) {
- keep_alive.push_back(varyings[i].Ascii());
+ for (const String& varying : varyings) {
+ keep_alive.push_back(varying.Ascii());
varying_strings.push_back(keep_alive.back().data());
}
@@ -4746,8 +4746,8 @@ Vector<GLuint> WebGL2RenderingContextBase::getUniformIndices(
Vector<CString> keep_alive; // Must keep these instances alive while looking
// at their data
Vector<const char*> uniform_strings;
- for (size_t i = 0; i < uniform_names.size(); ++i) {
- keep_alive.push_back(uniform_names[i].Ascii());
+ for (const String& uniform_name : uniform_names) {
+ keep_alive.push_back(uniform_name.Ascii());
uniform_strings.push_back(keep_alive.back().data());
}
@@ -4795,9 +4795,9 @@ ScriptValue WebGL2RenderingContextBase::getActiveUniforms(
&active_uniforms);
GLuint active_uniforms_unsigned = active_uniforms;
- size_t size = uniform_indices.size();
- for (size_t i = 0; i < size; ++i) {
- if (uniform_indices[i] >= active_uniforms_unsigned) {
+ wtf_size_t size = uniform_indices.size();
+ for (GLuint index : uniform_indices) {
+ if (index >= active_uniforms_unsigned) {
SynthesizeGLError(GL_INVALID_VALUE, "getActiveUniforms",
"uniform index greater than ACTIVE_UNIFORMS");
return ScriptValue::CreateNull(script_state);
@@ -4811,13 +4811,13 @@ ScriptValue WebGL2RenderingContextBase::getActiveUniforms(
switch (return_type) {
case kEnumType: {
Vector<GLenum> enum_result(size);
- for (size_t i = 0; i < size; ++i)
+ for (wtf_size_t i = 0; i < size; ++i)
enum_result[i] = static_cast<GLenum>(result[i]);
return WebGLAny(script_state, enum_result);
}
case kUnsignedIntType: {
Vector<GLuint> uint_result(size);
- for (size_t i = 0; i < size; ++i)
+ for (wtf_size_t i = 0; i < size; ++i)
uint_result[i] = static_cast<GLuint>(result[i]);
return WebGLAny(script_state, uint_result);
}
@@ -4826,7 +4826,7 @@ ScriptValue WebGL2RenderingContextBase::getActiveUniforms(
}
case kBoolType: {
Vector<bool> bool_result(size);
- for (size_t i = 0; i < size; ++i)
+ for (wtf_size_t i = 0; i < size; ++i)
bool_result[i] = static_cast<bool>(result[i]);
return WebGLAny(script_state, bool_result);
}
@@ -5445,7 +5445,7 @@ bool WebGL2RenderingContextBase::ValidateAndUpdateBufferBindBaseTarget(
max_bound_uniform_buffer_index_ = index;
} else if (max_bound_uniform_buffer_index_ > 0 &&
index == max_bound_uniform_buffer_index_) {
- size_t i = max_bound_uniform_buffer_index_ - 1;
+ wtf_size_t i = max_bound_uniform_buffer_index_ - 1;
for (; i > 0; --i) {
if (bound_indexed_uniform_buffers_[i].Get())
break;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h
index a410ef3d21f..f8e36e4b031 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h
@@ -936,7 +936,7 @@ class WebGL2RenderingContextBase : public WebGLRenderingContextBase {
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels,
- GLuint offset);
+ long long offset);
void readPixels(GLint x,
GLint y,
GLsizei width,
@@ -1136,7 +1136,7 @@ class WebGL2RenderingContextBase : public WebGLRenderingContextBase {
bound_indexed_shader_storage_buffers_;
HeapVector<TraceWrapperMember<WebGLBuffer>> bound_indexed_uniform_buffers_;
GLint max_transform_feedback_separate_attribs_;
- size_t max_bound_uniform_buffer_index_;
+ wtf_size_t max_bound_uniform_buffer_index_;
TraceWrapperMember<WebGLQuery> current_boolean_occlusion_query_;
TraceWrapperMember<WebGLQuery>
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.idl b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.idl
index 9046cbf916e..beb3f21a734 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.idl
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.idl
@@ -368,51 +368,51 @@ typedef unsigned long long GLuint64;
// to avoid conflicts. The effect is the same: if uniform*v is called with only two arguments,
// it goes to the WebGL1 signatures; if it's called with three or four arguments, it goes to
// the WebGL2 specific signatures.
- void uniform1fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v,
+ void uniform1fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform1fv(WebGLUniformLocation? location, sequence<GLfloat> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform2fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v,
+ void uniform2fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform2fv(WebGLUniformLocation? location, sequence<GLfloat> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform3fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v,
+ void uniform3fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform3fv(WebGLUniformLocation? location, sequence<GLfloat> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform4fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v,
+ void uniform4fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform4fv(WebGLUniformLocation? location, sequence<GLfloat> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform1iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v,
+ void uniform1iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform1iv(WebGLUniformLocation? location, sequence<GLint> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform2iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v,
+ void uniform2iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform2iv(WebGLUniformLocation? location, sequence<GLint> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform3iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v,
+ void uniform3iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform3iv(WebGLUniformLocation? location, sequence<GLint> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform4iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v,
+ void uniform4iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v,
GLuint srcOffset, optional GLuint srcLength = 0);
void uniform4iv(WebGLUniformLocation? location, sequence<GLint> v,
GLuint srcOffset, optional GLuint srcLength = 0);
- void uniform1uiv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Uint32Array v,
+ void uniform1uiv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Uint32Array v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
void uniform1uiv(WebGLUniformLocation? location, sequence<GLuint> v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
- void uniform2uiv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Uint32Array v,
+ void uniform2uiv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Uint32Array v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
void uniform2uiv(WebGLUniformLocation? location, sequence<GLuint> v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
- void uniform3uiv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Uint32Array v,
+ void uniform3uiv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Uint32Array v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
void uniform3uiv(WebGLUniformLocation? location, sequence<GLuint> v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
- void uniform4uiv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Uint32Array v,
+ void uniform4uiv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Uint32Array v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
void uniform4uiv(WebGLUniformLocation? location, sequence<GLuint> v,
optional GLuint srcOffset = 0, optional GLuint srcLength = 0);
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_active_info.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_active_info.h
index 026ac66902d..6168c57b2e0 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_active_info.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_active_info.h
@@ -36,19 +36,19 @@ class WebGLActiveInfo final : public ScriptWrappable {
public:
static WebGLActiveInfo* Create(const String& name, GLenum type, GLint size) {
- return new WebGLActiveInfo(name, type, size);
+ return MakeGarbageCollected<WebGLActiveInfo>(name, type, size);
}
- String name() const { return name_; }
- GLenum type() const { return type_; }
- GLint size() const { return size_; }
-
- private:
WebGLActiveInfo(const String& name, GLenum type, GLint size)
: name_(name), type_(type), size_(size) {
DCHECK(name.length());
DCHECK(type);
DCHECK(size);
}
+ String name() const { return name_; }
+ GLenum type() const { return type_; }
+ GLint size() const { return size_; }
+
+ private:
String name_;
GLenum type_;
GLint size_;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.cc
index d7e8c889b3f..2df498dceff 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.cc
@@ -31,7 +31,7 @@
namespace blink {
WebGLBuffer* WebGLBuffer::Create(WebGLRenderingContextBase* ctx) {
- return new WebGLBuffer(ctx);
+ return MakeGarbageCollected<WebGLBuffer>(ctx);
}
WebGLBuffer::WebGLBuffer(WebGLRenderingContextBase* ctx)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.h
index 660f95f960a..c0c495ac0ff 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_buffer.h
@@ -34,6 +34,7 @@ class WebGLBuffer final : public WebGLSharedPlatform3DObject {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit WebGLBuffer(WebGLRenderingContextBase*);
~WebGLBuffer() override;
static WebGLBuffer* Create(WebGLRenderingContextBase*);
@@ -47,8 +48,6 @@ class WebGLBuffer final : public WebGLSharedPlatform3DObject {
long long GetSize() const { return size_; }
protected:
- explicit WebGLBuffer(WebGLRenderingContextBase*);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
private:
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.cc
index 2c0b5a286a2..bb2568350c1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.cc
@@ -36,7 +36,7 @@ WebGLExtensionName WebGLColorBufferFloat::GetName() const {
WebGLColorBufferFloat* WebGLColorBufferFloat::Create(
WebGLRenderingContextBase* context) {
- return new WebGLColorBufferFloat(context);
+ return MakeGarbageCollected<WebGLColorBufferFloat>(context);
}
bool WebGLColorBufferFloat::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.h
index 83ebd54c3b4..f12d349f693 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_color_buffer_float.h
@@ -38,10 +38,9 @@ class WebGLColorBufferFloat final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLColorBufferFloat(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc
index 1997b11d49a..22c765f1f0f 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.cc
@@ -49,7 +49,7 @@ WebGLExtensionName WebGLCompressedTextureASTC::GetName() const {
WebGLCompressedTextureASTC* WebGLCompressedTextureASTC::Create(
WebGLRenderingContextBase* context) {
- return new WebGLCompressedTextureASTC(context);
+ return MakeGarbageCollected<WebGLCompressedTextureASTC>(context);
}
bool WebGLCompressedTextureASTC::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h
index f30014a55c3..6da53dbf7f4 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_astc.h
@@ -23,11 +23,10 @@ class WebGLCompressedTextureASTC final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit WebGLCompressedTextureASTC(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
static const BlockSizeCompressASTC kBlockSizeCompressASTC[];
-
- private:
- explicit WebGLCompressedTextureASTC(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.cc
index 1ce5361e70d..444834b91c6 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.cc
@@ -11,6 +11,8 @@ namespace blink {
WebGLCompressedTextureETC::WebGLCompressedTextureETC(
WebGLRenderingContextBase* context)
: WebGLExtension(context) {
+ context->ExtensionsUtil()->EnsureExtensionEnabled(
+ "GL_CHROMIUM_compressed_texture_etc");
context->AddCompressedTextureFormat(GL_COMPRESSED_R11_EAC);
context->AddCompressedTextureFormat(GL_COMPRESSED_SIGNED_R11_EAC);
context->AddCompressedTextureFormat(GL_COMPRESSED_RGB8_ETC2);
@@ -31,7 +33,7 @@ WebGLExtensionName WebGLCompressedTextureETC::GetName() const {
WebGLCompressedTextureETC* WebGLCompressedTextureETC::Create(
WebGLRenderingContextBase* context) {
- return new WebGLCompressedTextureETC(context);
+ return MakeGarbageCollected<WebGLCompressedTextureETC>(context);
}
bool WebGLCompressedTextureETC::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.h
index 6b2a1d5ea08..eca56909ba4 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc.h
@@ -17,10 +17,9 @@ class WebGLCompressedTextureETC final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLCompressedTextureETC(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.cc
index 28348b3e83f..c8c15b06543 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.cc
@@ -20,7 +20,7 @@ WebGLExtensionName WebGLCompressedTextureETC1::GetName() const {
WebGLCompressedTextureETC1* WebGLCompressedTextureETC1::Create(
WebGLRenderingContextBase* context) {
- return new WebGLCompressedTextureETC1(context);
+ return MakeGarbageCollected<WebGLCompressedTextureETC1>(context);
}
bool WebGLCompressedTextureETC1::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.h
index 7814b8c71be..afd69b8d6b1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_etc1.h
@@ -17,10 +17,9 @@ class WebGLCompressedTextureETC1 final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLCompressedTextureETC1(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.cc
index 11586ab7447..2f595303dae 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.cc
@@ -44,7 +44,7 @@ WebGLExtensionName WebGLCompressedTexturePVRTC::GetName() const {
WebGLCompressedTexturePVRTC* WebGLCompressedTexturePVRTC::Create(
WebGLRenderingContextBase* context) {
- return new WebGLCompressedTexturePVRTC(context);
+ return MakeGarbageCollected<WebGLCompressedTexturePVRTC>(context);
}
bool WebGLCompressedTexturePVRTC::Supported(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.h
index 5ff3e1ccc56..67c62fc9e0d 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_pvrtc.h
@@ -38,10 +38,9 @@ class WebGLCompressedTexturePVRTC final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLCompressedTexturePVRTC(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.cc
index c148a245e58..60efc28a43a 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.cc
@@ -44,7 +44,7 @@ WebGLExtensionName WebGLCompressedTextureS3TC::GetName() const {
WebGLCompressedTextureS3TC* WebGLCompressedTextureS3TC::Create(
WebGLRenderingContextBase* context) {
- return new WebGLCompressedTextureS3TC(context);
+ return MakeGarbageCollected<WebGLCompressedTextureS3TC>(context);
}
bool WebGLCompressedTextureS3TC::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.h
index da9b6c054d0..5e8d2c531cf 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc.h
@@ -38,10 +38,9 @@ class WebGLCompressedTextureS3TC final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLCompressedTextureS3TC(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.cc
index 32eaedb2f86..634f4a65966 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.cc
@@ -25,7 +25,7 @@ WebGLExtensionName WebGLCompressedTextureS3TCsRGB::GetName() const {
WebGLCompressedTextureS3TCsRGB* WebGLCompressedTextureS3TCsRGB::Create(
WebGLRenderingContextBase* context) {
- return new WebGLCompressedTextureS3TCsRGB(context);
+ return MakeGarbageCollected<WebGLCompressedTextureS3TCsRGB>(context);
}
bool WebGLCompressedTextureS3TCsRGB::Supported(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.h
index b23dcbf5b42..7e44399c31c 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_compressed_texture_s3tc_srgb.h
@@ -17,10 +17,9 @@ class WebGLCompressedTextureS3TCsRGB final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLCompressedTextureS3TCsRGB(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc
index 26b4610c87c..121b0fd8726 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc
@@ -9,20 +9,20 @@
namespace blink {
-WebGLContextAttributes ToWebGLContextAttributes(
+WebGLContextAttributes* ToWebGLContextAttributes(
const CanvasContextCreationAttributesCore& attrs) {
- WebGLContextAttributes result;
- result.setAlpha(attrs.alpha);
- result.setDepth(attrs.depth);
- result.setStencil(attrs.stencil);
- result.setAntialias(attrs.antialias);
- result.setPremultipliedAlpha(attrs.premultiplied_alpha);
- result.setPreserveDrawingBuffer(attrs.preserve_drawing_buffer);
- result.setFailIfMajorPerformanceCaveat(
+ WebGLContextAttributes* result = WebGLContextAttributes::Create();
+ result->setAlpha(attrs.alpha);
+ result->setDepth(attrs.depth);
+ result->setStencil(attrs.stencil);
+ result->setAntialias(attrs.antialias);
+ result->setPremultipliedAlpha(attrs.premultiplied_alpha);
+ result->setPreserveDrawingBuffer(attrs.preserve_drawing_buffer);
+ result->setFailIfMajorPerformanceCaveat(
attrs.fail_if_major_performance_caveat);
- result.setCompatibleXRDevice(
+ result->setCompatibleXRDevice(
static_cast<XRDevice*>(attrs.compatible_xr_device.Get()));
- result.setLowLatency(attrs.low_latency);
+ result->setLowLatency(attrs.low_latency);
return result;
}
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.h
index d1cbf484c4c..ea8c979937a 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.h
@@ -11,7 +11,7 @@
namespace blink {
-WebGLContextAttributes ToWebGLContextAttributes(
+WebGLContextAttributes* ToWebGLContextAttributes(
const CanvasContextCreationAttributesCore&);
// Set up the attributes that can be used to create a GL context via the
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.cc
index b7b7e3f8924..7b799dae9ca 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.cc
@@ -35,16 +35,16 @@ WebGLContextEvent::WebGLContextEvent(const AtomicString& type,
status_message_(status_message) {}
WebGLContextEvent::WebGLContextEvent(const AtomicString& type,
- const WebGLContextEventInit& initializer)
+ const WebGLContextEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasStatusMessage())
- status_message_ = initializer.statusMessage();
+ if (initializer->hasStatusMessage())
+ status_message_ = initializer->statusMessage();
}
WebGLContextEvent::~WebGLContextEvent() = default;
const AtomicString& WebGLContextEvent::InterfaceName() const {
- return EventNames::WebGLContextEvent;
+ return event_interface_names::kWebGLContextEvent;
}
void WebGLContextEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.h
index 83db084b948..0b9c207f9f9 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_context_event.h
@@ -35,15 +35,21 @@ class WebGLContextEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static WebGLContextEvent* Create() { return new WebGLContextEvent; }
+ static WebGLContextEvent* Create() {
+ return MakeGarbageCollected<WebGLContextEvent>();
+ }
static WebGLContextEvent* Create(const AtomicString& type,
const String& status_message) {
- return new WebGLContextEvent(type, status_message);
+ return MakeGarbageCollected<WebGLContextEvent>(type, status_message);
}
static WebGLContextEvent* Create(const AtomicString& type,
- const WebGLContextEventInit& initializer) {
- return new WebGLContextEvent(type, initializer);
+ const WebGLContextEventInit* initializer) {
+ return MakeGarbageCollected<WebGLContextEvent>(type, initializer);
}
+
+ WebGLContextEvent();
+ WebGLContextEvent(const AtomicString& type, const String& status_message);
+ WebGLContextEvent(const AtomicString&, const WebGLContextEventInit*);
~WebGLContextEvent() override;
const String& statusMessage() const { return status_message_; }
@@ -53,11 +59,6 @@ class WebGLContextEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- WebGLContextEvent();
- WebGLContextEvent(const AtomicString& type,
- const String& status_message);
- WebGLContextEvent(const AtomicString&, const WebGLContextEventInit&);
-
String status_message_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.cc
index 493c7f199cd..9a16dd71399 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.cc
@@ -37,7 +37,7 @@ WebGLExtensionName WebGLDebugRendererInfo::GetName() const {
WebGLDebugRendererInfo* WebGLDebugRendererInfo::Create(
WebGLRenderingContextBase* context) {
- return new WebGLDebugRendererInfo(context);
+ return MakeGarbageCollected<WebGLDebugRendererInfo>(context);
}
bool WebGLDebugRendererInfo::Supported(WebGLRenderingContextBase*) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.h
index 4eab76de52f..6746429fb4d 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_renderer_info.h
@@ -40,13 +40,13 @@ class WebGLDebugRendererInfo final : public WebGLExtension {
};
static WebGLDebugRendererInfo* Create(WebGLRenderingContextBase*);
+
+ explicit WebGLDebugRendererInfo(WebGLRenderingContextBase*);
+
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
WebGLExtensionName GetName() const override;
-
- private:
- explicit WebGLDebugRendererInfo(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.cc
index 115a1af2aea..0f3595ad993 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.cc
@@ -44,7 +44,7 @@ WebGLExtensionName WebGLDebugShaders::GetName() const {
WebGLDebugShaders* WebGLDebugShaders::Create(
WebGLRenderingContextBase* context) {
- return new WebGLDebugShaders(context);
+ return MakeGarbageCollected<WebGLDebugShaders>(context);
}
String WebGLDebugShaders::getTranslatedShaderSource(WebGLShader* shader) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.h
index 3081dc04426..64945ba4bad 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_debug_shaders.h
@@ -40,12 +40,11 @@ class WebGLDebugShaders final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit WebGLDebugShaders(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
String getTranslatedShaderSource(WebGLShader*);
-
- private:
- explicit WebGLDebugShaders(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.cc
index 7606ae9174c..e472f987d78 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.cc
@@ -39,7 +39,7 @@ WebGLExtensionName WebGLDepthTexture::GetName() const {
WebGLDepthTexture* WebGLDepthTexture::Create(
WebGLRenderingContextBase* context) {
- return new WebGLDepthTexture(context);
+ return MakeGarbageCollected<WebGLDepthTexture>(context);
}
bool WebGLDepthTexture::Supported(WebGLRenderingContextBase* context) {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.h
index 8aa8a0c0388..f8885ddb07b 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_depth_texture.h
@@ -38,10 +38,9 @@ class WebGLDepthTexture final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
- WebGLExtensionName GetName() const override;
-
- private:
explicit WebGLDepthTexture(WebGLRenderingContextBase*);
+
+ WebGLExtensionName GetName() const override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.cc
index 79cd23c2bfb..b60fcbfc7b9 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.cc
@@ -40,7 +40,7 @@ WebGLExtensionName WebGLDrawBuffers::GetName() const {
}
WebGLDrawBuffers* WebGLDrawBuffers::Create(WebGLRenderingContextBase* context) {
- return new WebGLDrawBuffers(context);
+ return MakeGarbageCollected<WebGLDrawBuffers>(context);
}
// static
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.h
index 698435ae441..b60aaeb039b 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_draw_buffers.h
@@ -39,12 +39,11 @@ class WebGLDrawBuffers final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit WebGLDrawBuffers(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
void drawBuffersWEBGL(const Vector<GLenum>& buffers);
-
- private:
- explicit WebGLDrawBuffers(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.cc
index 0e8efc0a4f8..2cdb82072f2 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.cc
@@ -15,7 +15,7 @@ WebGLSync* WebGLFenceSync::Create(WebGL2RenderingContextBase* ctx,
GLbitfield flags) {
DCHECK(condition == GL_SYNC_GPU_COMMANDS_COMPLETE);
DCHECK(flags == 0);
- return new WebGLFenceSync(ctx, condition, flags);
+ return MakeGarbageCollected<WebGLFenceSync>(ctx, condition, flags);
}
WebGLFenceSync::WebGLFenceSync(WebGL2RenderingContextBase* ctx,
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.h
index cb971d579d2..7612adfade1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_fence_sync.h
@@ -17,7 +17,6 @@ class WebGLFenceSync : public WebGLSync {
GLenum condition,
GLbitfield flags);
- protected:
WebGLFenceSync(WebGL2RenderingContextBase*,
GLenum condition,
GLbitfield flags);
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.cc
index 7d03d4031e2..397c5966fe5 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.cc
@@ -200,12 +200,12 @@ void WebGLTextureAttachment::Unattach(gpu::gles2::GLES2Interface* gl,
WebGLFramebuffer::WebGLAttachment::WebGLAttachment() = default;
WebGLFramebuffer* WebGLFramebuffer::Create(WebGLRenderingContextBase* ctx) {
- return new WebGLFramebuffer(ctx, false);
+ return MakeGarbageCollected<WebGLFramebuffer>(ctx, false);
}
WebGLFramebuffer* WebGLFramebuffer::CreateOpaque(
WebGLRenderingContextBase* ctx) {
- return new WebGLFramebuffer(ctx, true);
+ return MakeGarbageCollected<WebGLFramebuffer>(ctx, true);
}
WebGLFramebuffer::WebGLFramebuffer(WebGLRenderingContextBase* ctx, bool opaque)
@@ -416,7 +416,7 @@ bool WebGLFramebuffer::IsBound(GLenum target) const {
void WebGLFramebuffer::DrawBuffers(const Vector<GLenum>& bufs) {
draw_buffers_ = bufs;
filtered_draw_buffers_.resize(draw_buffers_.size());
- for (size_t i = 0; i < filtered_draw_buffers_.size(); ++i)
+ for (wtf_size_t i = 0; i < filtered_draw_buffers_.size(); ++i)
filtered_draw_buffers_[i] = GL_NONE;
DrawBuffersIfNecessary(true);
}
@@ -426,7 +426,7 @@ void WebGLFramebuffer::DrawBuffersIfNecessary(bool force) {
Context()->ExtensionEnabled(kWebGLDrawBuffersName)) {
bool reset = force;
// This filtering works around graphics driver bugs on Mac OS X.
- for (size_t i = 0; i < draw_buffers_.size(); ++i) {
+ for (wtf_size_t i = 0; i < draw_buffers_.size(); ++i) {
if (draw_buffers_[i] != GL_NONE && GetAttachment(draw_buffers_[i])) {
if (filtered_draw_buffers_[i] != draw_buffers_[i]) {
filtered_draw_buffers_[i] = draw_buffers_[i];
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.h
index e1b58213804..d9962803668 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_framebuffer.h
@@ -65,6 +65,7 @@ class WebGLFramebuffer final : public WebGLContextObject {
WebGLAttachment();
};
+ explicit WebGLFramebuffer(WebGLRenderingContextBase*, bool opaque);
~WebGLFramebuffer() override;
static WebGLFramebuffer* Create(WebGLRenderingContextBase*);
@@ -123,8 +124,6 @@ class WebGLFramebuffer final : public WebGLContextObject {
const char* NameInHeapSnapshot() const override { return "WebGLFramebuffer"; }
protected:
- explicit WebGLFramebuffer(WebGLRenderingContextBase*, bool opaque);
-
bool HasObject() const override { return object_ != 0; }
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.cc
index dc451b6b80b..28a643c23b0 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.cc
@@ -42,7 +42,7 @@ WebGLExtensionName WebGLLoseContext::GetName() const {
}
WebGLLoseContext* WebGLLoseContext::Create(WebGLRenderingContextBase* context) {
- return new WebGLLoseContext(context);
+ return MakeGarbageCollected<WebGLLoseContext>(context);
}
void WebGLLoseContext::loseContext() {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.h
index aa65b6da18c..19b168fab73 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_lose_context.h
@@ -40,14 +40,13 @@ class WebGLLoseContext final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit WebGLLoseContext(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
void Lose(bool) override;
void loseContext();
void restoreContext();
-
- private:
- explicit WebGLLoseContext(WebGLRenderingContextBase*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.cc
index 06fe14a24ee..8e36180afbf 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.cc
@@ -21,7 +21,7 @@ WebGLExtensionName WebGLMultiview::GetName() const {
}
WebGLMultiview* WebGLMultiview::Create(WebGLRenderingContextBase* context) {
- return new WebGLMultiview(context);
+ return MakeGarbageCollected<WebGLMultiview>(context);
}
void WebGLMultiview::framebufferTextureMultiviewWEBGL(GLenum target,
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.h
index d59c12442ed..8f76d0fd7a3 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_multiview.h
@@ -17,6 +17,8 @@ class WebGLMultiview final : public WebGLExtension {
static bool Supported(WebGLRenderingContextBase*);
static const char* ExtensionName();
+ explicit WebGLMultiview(WebGLRenderingContextBase*);
+
WebGLExtensionName GetName() const override;
void framebufferTextureMultiviewWEBGL(GLenum target,
@@ -27,8 +29,6 @@ class WebGLMultiview final : public WebGLExtension {
GLsizei numViews);
private:
- explicit WebGLMultiview(WebGLRenderingContextBase*);
-
GLsizei max_views_ovr_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_program.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_program.cc
index dc72854384c..2caeae2f2eb 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_program.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_program.cc
@@ -32,7 +32,7 @@
namespace blink {
WebGLProgram* WebGLProgram::Create(WebGLRenderingContextBase* ctx) {
- return new WebGLProgram(ctx);
+ return MakeGarbageCollected<WebGLProgram>(ctx);
}
WebGLProgram::WebGLProgram(WebGLRenderingContextBase* ctx)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_program.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_program.h
index d70c358163b..776704d7d2c 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_program.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_program.h
@@ -37,6 +37,7 @@ class WebGLProgram final : public WebGLSharedPlatform3DObject {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit WebGLProgram(WebGLRenderingContextBase*);
~WebGLProgram() override;
static WebGLProgram* Create(WebGLRenderingContextBase*);
@@ -75,8 +76,6 @@ class WebGLProgram final : public WebGLSharedPlatform3DObject {
void Trace(blink::Visitor*) override;
protected:
- explicit WebGLProgram(WebGLRenderingContextBase*);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
private:
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_query.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_query.cc
index 3381e7c498c..ed12cbef3cf 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_query.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_query.cc
@@ -12,7 +12,7 @@
namespace blink {
WebGLQuery* WebGLQuery::Create(WebGL2RenderingContextBase* ctx) {
- return new WebGLQuery(ctx);
+ return MakeGarbageCollected<WebGLQuery>(ctx);
}
WebGLQuery::WebGLQuery(WebGL2RenderingContextBase* ctx)
@@ -26,7 +26,7 @@ WebGLQuery::WebGLQuery(WebGL2RenderingContextBase* ctx)
ctx->canvas()->GetDocument().GetTaskRunner(TaskType::kInternalDefault);
} else {
// Fallback for OffscreenCanvas (no frame scheduler)
- task_runner_ = Platform::Current()->CurrentThread()->GetTaskRunner();
+ task_runner_ = Thread::Current()->GetTaskRunner();
}
GLuint query;
ctx->ContextGL()->GenQueriesEXT(1, &query);
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_query.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_query.h
index 508cd0e0272..3258c409ed7 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_query.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_query.h
@@ -7,7 +7,7 @@
#include "base/single_thread_task_runner.h"
#include "third_party/blink/renderer/modules/webgl/webgl_shared_platform_3d_object.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
namespace gpu {
namespace gles2 {
@@ -23,6 +23,7 @@ class WebGLQuery : public WebGLSharedPlatform3DObject {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit WebGLQuery(WebGL2RenderingContextBase*);
~WebGLQuery() override;
static WebGLQuery* Create(WebGL2RenderingContextBase*);
@@ -38,8 +39,6 @@ class WebGLQuery : public WebGLSharedPlatform3DObject {
GLuint GetQueryResult();
protected:
- explicit WebGLQuery(WebGL2RenderingContextBase*);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
private:
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.cc
index 76f787d7f22..09203b8ab75 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.cc
@@ -31,7 +31,7 @@
namespace blink {
WebGLRenderbuffer* WebGLRenderbuffer::Create(WebGLRenderingContextBase* ctx) {
- return new WebGLRenderbuffer(ctx);
+ return MakeGarbageCollected<WebGLRenderbuffer>(ctx);
}
WebGLRenderbuffer::WebGLRenderbuffer(WebGLRenderingContextBase* ctx)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.h
index 3a7fc849608..7ce5daafaa5 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_renderbuffer.h
@@ -35,6 +35,7 @@ class WebGLRenderbuffer final : public WebGLSharedPlatform3DObject {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit WebGLRenderbuffer(WebGLRenderingContextBase*);
~WebGLRenderbuffer() override;
static WebGLRenderbuffer* Create(WebGLRenderingContextBase*);
@@ -58,8 +59,6 @@ class WebGLRenderbuffer final : public WebGLSharedPlatform3DObject {
void Trace(blink::Visitor*) override;
protected:
- explicit WebGLRenderbuffer(WebGLRenderingContextBase*);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
private:
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.cc
index 059b718a360..452ad896f36 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.cc
@@ -98,11 +98,12 @@ CanvasRenderingContext* WebGLRenderingContext::Factory::Create(
if (!ShouldCreateContext(context_provider.get()))
return nullptr;
- WebGLRenderingContext* rendering_context = new WebGLRenderingContext(
- host, std::move(context_provider), using_gpu_compositing, attrs);
+ WebGLRenderingContext* rendering_context =
+ MakeGarbageCollected<WebGLRenderingContext>(
+ host, std::move(context_provider), using_gpu_compositing, attrs);
if (!rendering_context->GetDrawingBuffer()) {
host->HostDispatchEvent(
- WebGLContextEvent::Create(EventTypeNames::webglcontextcreationerror,
+ WebGLContextEvent::Create(event_type_names::kWebglcontextcreationerror,
"Could not create a WebGL context."));
return nullptr;
}
@@ -115,7 +116,7 @@ CanvasRenderingContext* WebGLRenderingContext::Factory::Create(
void WebGLRenderingContext::Factory::OnError(HTMLCanvasElement* canvas,
const String& error) {
canvas->DispatchEvent(*WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror, error));
+ event_type_names::kWebglcontextcreationerror, error));
}
WebGLRenderingContext::WebGLRenderingContext(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.h
index 46b21b8d8af..9c71981509e 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context.h
@@ -73,6 +73,11 @@ class WebGLRenderingContext final : public WebGLRenderingContextBase {
void OnError(HTMLCanvasElement*, const String& error) override;
};
+ WebGLRenderingContext(CanvasRenderingContextHost*,
+ std::unique_ptr<WebGraphicsContext3DProvider>,
+ bool using_gpu_compositing,
+ const CanvasContextCreationAttributesCore&);
+
CanvasRenderingContext::ContextType GetContextType() const override {
return CanvasRenderingContext::kContextWebgl;
}
@@ -85,11 +90,6 @@ class WebGLRenderingContext final : public WebGLRenderingContextBase {
void Trace(blink::Visitor*) override;
private:
- WebGLRenderingContext(CanvasRenderingContextHost*,
- std::unique_ptr<WebGraphicsContext3DProvider>,
- bool using_gpu_compositing,
- const CanvasContextCreationAttributesCore&);
-
// Enabled extension objects.
Member<ANGLEInstancedArrays> angle_instanced_arrays_;
Member<EXTBlendMinMax> ext_blend_min_max_;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
index 2d312c67b97..9fd9c417aa7 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -102,6 +102,7 @@
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -134,7 +135,8 @@ WebGLRenderingContextBaseSet& ActiveContexts() {
Persistent<WebGLRenderingContextBaseSet>& active_contexts_persistent =
*active_contexts;
if (!active_contexts_persistent) {
- active_contexts_persistent = new WebGLRenderingContextBaseSet();
+ active_contexts_persistent =
+ MakeGarbageCollected<WebGLRenderingContextBaseSet>();
active_contexts_persistent.RegisterAsStaticReference();
}
return *active_contexts_persistent;
@@ -149,7 +151,8 @@ WebGLRenderingContextBaseMap& ForciblyEvictedContexts() {
Persistent<WebGLRenderingContextBaseMap>&
forcibly_evicted_contexts_persistent = *forcibly_evicted_contexts;
if (!forcibly_evicted_contexts_persistent) {
- forcibly_evicted_contexts_persistent = new WebGLRenderingContextBaseMap();
+ forcibly_evicted_contexts_persistent =
+ MakeGarbageCollected<WebGLRenderingContextBaseMap>();
forcibly_evicted_contexts_persistent.RegisterAsStaticReference();
}
return *forcibly_evicted_contexts_persistent;
@@ -642,7 +645,7 @@ CreateContextProviderOnWorkerThread(
creation_info.url = url.Copy();
creation_info.using_gpu_compositing = using_gpu_compositing;
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- Platform::Current()->MainThread()->GetTaskRunner();
+ Thread::MainThread()->GetTaskRunner();
PostCrossThreadTask(*task_runner, FROM_HERE,
CrossThreadBind(&CreateContextProviderOnMainThread,
CrossThreadUnretained(&creation_info),
@@ -695,7 +698,7 @@ WebGLRenderingContextBase::CreateContextProviderInternal(
if (!context_provider || g_should_fail_context_creation_for_testing) {
g_should_fail_context_creation_for_testing = false;
host->HostDispatchEvent(
- WebGLContextEvent::Create(EventTypeNames::webglcontextcreationerror,
+ WebGLContextEvent::Create(event_type_names::kWebglcontextcreationerror,
ExtractWebGLContextCreationError(gl_info)));
return nullptr;
}
@@ -703,7 +706,7 @@ WebGLRenderingContextBase::CreateContextProviderInternal(
if (!String(gl->GetString(GL_EXTENSIONS))
.Contains("GL_OES_packed_depth_stencil")) {
host->HostDispatchEvent(WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror,
+ event_type_names::kWebglcontextcreationerror,
"OES_packed_depth_stencil support is required."));
return nullptr;
}
@@ -722,7 +725,7 @@ WebGLRenderingContextBase::CreateWebGraphicsContext3DProvider(
if (host->IsWebGLBlocked()) {
host->SetContextCreationWasBlocked();
host->HostDispatchEvent(WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror,
+ event_type_names::kWebglcontextcreationerror,
"Web page caused context loss and was blocked"));
return nullptr;
}
@@ -733,7 +736,7 @@ WebGLRenderingContextBase::CreateWebGraphicsContext3DProvider(
(context_type == Platform::kWebGL2ComputeContextType &&
!host->IsWebGL2Enabled())) {
host->HostDispatchEvent(WebGLContextEvent::Create(
- EventTypeNames::webglcontextcreationerror,
+ event_type_names::kWebglcontextcreationerror,
"disabled by enterprise policy or commandline switch"));
return nullptr;
}
@@ -864,7 +867,8 @@ static const GLenum kSupportedInternalFormatsES3[] = {
GL_SRGB8_ALPHA8, GL_R8I, GL_R8UI, GL_R16I, GL_R16UI,
GL_R32I, GL_R32UI, GL_RG8I, GL_RG8UI, GL_RG16I,
GL_RG16UI, GL_RG32I, GL_RG32UI, GL_RGBA8I, GL_RGBA8UI,
- GL_RGBA16I, GL_RGBA16UI, GL_RGBA32I, GL_RGBA32UI,
+ GL_RGBA16I, GL_RGBA16UI, GL_RGBA32I, GL_RGBA32UI, GL_RGB32I,
+ GL_RGB32UI, GL_RGB8I, GL_RGB8UI, GL_RGB16I, GL_RGB16UI,
};
// ES3 enums only supported by TexImage
@@ -880,12 +884,6 @@ static const GLenum kSupportedInternalFormatsTexImageES3[] = {
GL_RGB9_E5,
GL_RGB16F,
GL_RGB32F,
- GL_RGB8UI,
- GL_RGB8I,
- GL_RGB16UI,
- GL_RGB16I,
- GL_RGB32UI,
- GL_RGB32I,
GL_RGBA8_SNORM,
GL_RGBA16F,
GL_RGBA32F,
@@ -1007,7 +1005,7 @@ WebGLRenderingContextBase::WebGLRenderingContextBase(
const CanvasContextCreationAttributesCore& requested_attributes,
Platform::ContextType context_type)
: CanvasRenderingContext(host, requested_attributes),
- context_group_(new WebGLContextGroup()),
+ context_group_(MakeGarbageCollected<WebGLContextGroup>()),
dispatch_context_lost_event_timer_(
task_runner,
this,
@@ -1421,8 +1419,7 @@ WebGLRenderingContextBase::ClearIfComposited(GLbitfield mask) {
if (buffers_needing_clearing == 0 || (mask && framebuffer_binding_))
return kSkipped;
- base::Optional<WebGLContextAttributes> context_attributes;
- getContextAttributes(context_attributes);
+ WebGLContextAttributes* context_attributes = getContextAttributes();
if (!context_attributes) {
// Unlikely, but context was lost.
return kSkipped;
@@ -1751,7 +1748,7 @@ bool WebGLRenderingContextBase::CheckObjectToBeBound(const char* function_name,
"object not from this context");
return false;
}
- deleted = !object->HasObject();
+ deleted = object->IsDeleted();
}
return true;
}
@@ -2418,7 +2415,7 @@ void WebGLRenderingContextBase::deleteTexture(WebGLTexture* texture) {
return;
int max_bound_texture_index = -1;
- for (size_t i = 0; i < one_plus_max_non_default_texture_unit_; ++i) {
+ for (wtf_size_t i = 0; i < one_plus_max_non_default_texture_unit_; ++i) {
if (texture == texture_units_[i].texture2d_binding_) {
texture_units_[i].texture2d_binding_ = nullptr;
max_bound_texture_index = i;
@@ -2883,11 +2880,14 @@ ScriptValue WebGLRenderingContextBase::getBufferParameter(
}
}
-void WebGLRenderingContextBase::getContextAttributes(
- base::Optional<WebGLContextAttributes>& result) {
+WebGLContextAttributes* WebGLRenderingContextBase::getContextAttributes()
+ const {
if (isContextLost())
- return;
- result = ToWebGLContextAttributes(CreationAttributes());
+ return nullptr;
+
+ WebGLContextAttributes* result =
+ ToWebGLContextAttributes(CreationAttributes());
+
// Some requested attributes may not be honored, so we need to query the
// underlying context/drawing buffer and adjust accordingly.
if (CreationAttributes().depth && !GetDrawingBuffer()->HasDepthBuffer())
@@ -2898,6 +2898,7 @@ void WebGLRenderingContextBase::getContextAttributes(
if (compatible_xr_device_) {
result->setCompatibleXRDevice(compatible_xr_device_);
}
+ return result;
}
GLenum WebGLRenderingContextBase::getError() {
@@ -2956,8 +2957,7 @@ ScriptValue WebGLRenderingContextBase::getExtension(ScriptState* script_state,
WebGLExtension* extension = nullptr;
if (!isContextLost()) {
- for (size_t i = 0; i < extensions_.size(); ++i) {
- ExtensionTracker* tracker = extensions_[i];
+ for (ExtensionTracker* tracker : extensions_) {
if (tracker->MatchesNameWithPrefixes(name)) {
if (ExtensionSupportedAndAllowed(tracker)) {
extension = tracker->GetExtension(this);
@@ -3556,8 +3556,7 @@ WebGLRenderingContextBase::getSupportedExtensions() {
Vector<String> result;
- for (size_t i = 0; i < extensions_.size(); ++i) {
- ExtensionTracker* tracker = extensions_[i].Get();
+ for (ExtensionTracker* tracker : extensions_) {
if (ExtensionSupportedAndAllowed(tracker)) {
const char* const* prefixes = tracker->Prefixes();
for (; *prefixes; ++prefixes) {
@@ -3856,7 +3855,7 @@ ScriptValue WebGLRenderingContextBase::getUniform(
GLint value[4] = {0};
ContextGL()->GetUniformiv(ObjectOrZero(program), location, value);
if (length > 1) {
- bool bool_value[16] = {0};
+ bool bool_value[4] = {0};
for (unsigned j = 0; j < length; j++)
bool_value[j] = static_cast<bool>(value[j]);
return WebGLAny(script_state, bool_value, length);
@@ -4302,7 +4301,7 @@ void WebGLRenderingContextBase::ReadPixelsHelper(GLint x,
GLenum format,
GLenum type,
DOMArrayBufferView* pixels,
- GLuint offset) {
+ long long offset) {
if (isContextLost())
return;
// Due to WebGL's same-origin restrictions, it is not possible to
@@ -6467,12 +6466,11 @@ void WebGLRenderingContextBase::LoseContextImpl(
auto_recovery_method_ = auto_recovery_method;
// Lose all the extensions.
- for (size_t i = 0; i < extensions_.size(); ++i) {
- ExtensionTracker* tracker = extensions_[i];
+ for (ExtensionTracker* tracker : extensions_) {
tracker->LoseExtension(false);
}
- for (size_t i = 0; i < kWebGLExtensionNameCount; ++i)
+ for (wtf_size_t i = 0; i < kWebGLExtensionNameCount; ++i)
extension_enabled_[i] = false;
RemoveAllCompressedTextureFormats();
@@ -6852,7 +6850,7 @@ bool WebGLRenderingContextBase::ValidateSize(const char* function_name,
bool WebGLRenderingContextBase::ValidateString(const char* function_name,
const String& string) {
- for (size_t i = 0; i < string.length(); ++i) {
+ for (wtf_size_t i = 0; i < string.length(); ++i) {
if (!ValidateCharacter(string[i])) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "string not ASCII");
return false;
@@ -6862,7 +6860,7 @@ bool WebGLRenderingContextBase::ValidateString(const char* function_name,
}
bool WebGLRenderingContextBase::ValidateShaderSource(const String& string) {
- for (size_t i = 0; i < string.length(); ++i) {
+ for (wtf_size_t i = 0; i < string.length(); ++i) {
// line-continuation character \ is supported in WebGL 2.0.
if (IsWebGL2OrHigher() && string[i] == '\\') {
continue;
@@ -7673,7 +7671,7 @@ void WebGLRenderingContextBase::OnBeforeDrawCall() {
void WebGLRenderingContextBase::DispatchContextLostEvent(TimerBase*) {
WebGLContextEvent* event =
- WebGLContextEvent::Create(EventTypeNames::webglcontextlost, "");
+ WebGLContextEvent::Create(event_type_names::kWebglcontextlost, "");
Host()->HostDispatchEvent(event);
restore_allowed_ = event->defaultPrevented();
if (restore_allowed_ && !is_hidden_) {
@@ -7766,7 +7764,7 @@ void WebGLRenderingContextBase::MaybeRestoreContext(TimerBase*) {
InitializeNewContext();
MarkContextChanged(kCanvasContextChanged);
WebGLContextEvent* event =
- WebGLContextEvent::Create(EventTypeNames::webglcontextrestored, "");
+ WebGLContextEvent::Create(event_type_names::kWebglcontextrestored, "");
Host()->HostDispatchEvent(event);
}
@@ -7777,13 +7775,13 @@ String WebGLRenderingContextBase::EnsureNotNull(const String& text) const {
}
WebGLRenderingContextBase::LRUCanvasResourceProviderCache::
- LRUCanvasResourceProviderCache(size_t capacity)
+ LRUCanvasResourceProviderCache(wtf_size_t capacity)
: resource_providers_(capacity) {}
CanvasResourceProvider* WebGLRenderingContextBase::
LRUCanvasResourceProviderCache::GetCanvasResourceProvider(
const IntSize& size) {
- size_t i;
+ wtf_size_t i;
for (i = 0; i < resource_providers_.size(); ++i) {
CanvasResourceProvider* resource_provider = resource_providers_[i].get();
if (!resource_provider)
@@ -7803,7 +7801,7 @@ CanvasResourceProvider* WebGLRenderingContextBase::
nullptr)); // canvas_resource_dispatcher
if (!temp)
return nullptr;
- i = std::min(static_cast<size_t>(resource_providers_.size() - 1), i);
+ i = std::min(resource_providers_.size() - 1, i);
resource_providers_[i] = std::move(temp);
CanvasResourceProvider* resource_provider = resource_providers_[i].get();
@@ -7812,8 +7810,8 @@ CanvasResourceProvider* WebGLRenderingContextBase::
}
void WebGLRenderingContextBase::LRUCanvasResourceProviderCache::BubbleToFront(
- size_t idx) {
- for (size_t i = idx; i > 0; --i)
+ wtf_size_t idx) {
+ for (wtf_size_t i = idx; i > 0; --i)
resource_providers_[i].swap(resource_providers_[i - 1]);
}
@@ -7877,8 +7875,7 @@ void WebGLRenderingContextBase::ApplyStencilTest() {
if (framebuffer_binding_) {
have_stencil_buffer = framebuffer_binding_->HasStencilBuffer();
} else {
- base::Optional<WebGLContextAttributes> attributes;
- getContextAttributes(attributes);
+ WebGLContextAttributes* attributes = getContextAttributes();
have_stencil_buffer = attributes && attributes->stencil();
}
EnableOrDisable(GL_STENCIL_TEST, stencil_enabled_ && have_stencil_buffer);
@@ -7997,8 +7994,7 @@ int WebGLRenderingContextBase::ExternallyAllocatedBufferCountPerPixel() {
int buffer_count = 1;
buffer_count *= 2; // WebGL's front and back color buffers.
int samples = GetDrawingBuffer() ? GetDrawingBuffer()->SampleCount() : 0;
- base::Optional<WebGLContextAttributes> attribs;
- getContextAttributes(attribs);
+ WebGLContextAttributes* attribs = getContextAttributes();
if (attribs) {
// Handle memory from WebGL multisample and depth/stencil buffers.
// It is enabled only in case of explicit resolve assuming that there
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h
index 96c15706bcf..58fbb7a45ed 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h
@@ -282,7 +282,7 @@ class MODULES_EXPORT WebGLRenderingContextBase : public CanvasRenderingContext,
WebGLProgram*);
GLint getAttribLocation(WebGLProgram*, const String& name);
ScriptValue getBufferParameter(ScriptState*, GLenum target, GLenum pname);
- void getContextAttributes(base::Optional<WebGLContextAttributes>&);
+ WebGLContextAttributes* getContextAttributes() const;
GLenum getError();
ScriptValue getExtension(ScriptState*, const String& name);
virtual ScriptValue getFramebufferAttachmentParameter(ScriptState*,
@@ -760,19 +760,19 @@ class MODULES_EXPORT WebGLRenderingContextBase : public CanvasRenderingContext,
Member<XRDevice> compatible_xr_device_;
HeapVector<TextureUnitState> texture_units_;
- unsigned long active_texture_unit_;
+ wtf_size_t active_texture_unit_;
Vector<GLenum> compressed_texture_formats_;
// Fixed-size cache of reusable resource providers for video texImage2D calls.
class LRUCanvasResourceProviderCache {
public:
- explicit LRUCanvasResourceProviderCache(size_t capacity);
+ explicit LRUCanvasResourceProviderCache(wtf_size_t capacity);
// The pointer returned is owned by the image buffer map.
CanvasResourceProvider* GetCanvasResourceProvider(const IntSize&);
private:
- void BubbleToFront(size_t idx);
+ void BubbleToFront(wtf_size_t idx);
Vector<std::unique_ptr<CanvasResourceProvider>> resource_providers_;
};
LRUCanvasResourceProviderCache generated_image_cache_ =
@@ -826,7 +826,7 @@ class MODULES_EXPORT WebGLRenderingContextBase : public CanvasRenderingContext,
bool synthesized_errors_to_console_ = true;
int num_gl_errors_to_console_allowed_;
- unsigned long one_plus_max_non_default_texture_unit_ = 0;
+ wtf_size_t one_plus_max_non_default_texture_unit_ = 0;
std::unique_ptr<Extensions3DUtil> extensions_util_;
@@ -1672,7 +1672,7 @@ class MODULES_EXPORT WebGLRenderingContextBase : public CanvasRenderingContext,
GLenum format,
GLenum type,
DOMArrayBufferView* pixels,
- GLuint offset);
+ long long offset);
private:
WebGLRenderingContextBase(CanvasRenderingContextHost*,
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl
index f424abb8847..5857522f575 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.idl
@@ -487,7 +487,7 @@ typedef unrestricted float GLclampf;
void bufferData(GLenum target, GLsizeiptr size, GLenum usage);
void bufferData(GLenum target, [AllowShared] ArrayBufferView data, GLenum usage);
void bufferData(GLenum target, ArrayBuffer? data, GLenum usage);
- void bufferSubData(GLenum target, GLintptr offset, [FlexibleArrayBufferView] ArrayBufferView data);
+ void bufferSubData(GLenum target, GLintptr offset, [AllowShared, FlexibleArrayBufferView] ArrayBufferView data);
void bufferSubData(GLenum target, GLintptr offset, ArrayBuffer data);
GLenum checkFramebufferStatus(GLenum target);
@@ -660,28 +660,28 @@ typedef unrestricted float GLclampf;
GLenum format, GLenum type, ImageBitmap bitmap);
void uniform1f(WebGLUniformLocation? location, GLfloat x);
- void uniform1fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v);
+ void uniform1fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v);
void uniform1fv(WebGLUniformLocation? location, sequence<GLfloat> v);
void uniform1i(WebGLUniformLocation? location, GLint x);
- void uniform1iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v);
+ void uniform1iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v);
void uniform1iv(WebGLUniformLocation? location, sequence<GLint> v);
void uniform2f(WebGLUniformLocation? location, GLfloat x, GLfloat y);
- void uniform2fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v);
+ void uniform2fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v);
void uniform2fv(WebGLUniformLocation? location, sequence<GLfloat> v);
void uniform2i(WebGLUniformLocation? location, GLint x, GLint y);
- void uniform2iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v);
+ void uniform2iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v);
void uniform2iv(WebGLUniformLocation? location, sequence<GLint> v);
void uniform3f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z);
- void uniform3fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v);
+ void uniform3fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v);
void uniform3fv(WebGLUniformLocation? location, sequence<GLfloat> v);
void uniform3i(WebGLUniformLocation? location, GLint x, GLint y, GLint z);
- void uniform3iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v);
+ void uniform3iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v);
void uniform3iv(WebGLUniformLocation? location, sequence<GLint> v);
void uniform4f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
- void uniform4fv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Float32Array v);
+ void uniform4fv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Float32Array v);
void uniform4fv(WebGLUniformLocation? location, sequence<GLfloat> v);
void uniform4i(WebGLUniformLocation? location, GLint x, GLint y, GLint z, GLint w);
- void uniform4iv(WebGLUniformLocation? location, [FlexibleArrayBufferView] Int32Array v);
+ void uniform4iv(WebGLUniformLocation? location, [AllowShared, FlexibleArrayBufferView] Int32Array v);
void uniform4iv(WebGLUniformLocation? location, sequence<GLint> v);
void uniformMatrix2fv(WebGLUniformLocation? location, GLboolean transpose, [AllowShared] Float32Array array);
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.cc
index 7402ea9c810..962aa16961f 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.cc
@@ -10,7 +10,7 @@
namespace blink {
WebGLSampler* WebGLSampler::Create(WebGL2RenderingContextBase* ctx) {
- return new WebGLSampler(ctx);
+ return MakeGarbageCollected<WebGLSampler>(ctx);
}
WebGLSampler::WebGLSampler(WebGL2RenderingContextBase* ctx)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.h
index 294c96d33e1..288145477c4 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_sampler.h
@@ -15,13 +15,12 @@ class WebGLSampler : public WebGLSharedPlatform3DObject {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit WebGLSampler(WebGL2RenderingContextBase*);
~WebGLSampler() override;
static WebGLSampler* Create(WebGL2RenderingContextBase*);
protected:
- explicit WebGLSampler(WebGL2RenderingContextBase*);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
private:
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.cc
index 476e48212dc..c9fea1f12ec 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.cc
@@ -31,7 +31,7 @@
namespace blink {
WebGLShader* WebGLShader::Create(WebGLRenderingContextBase* ctx, GLenum type) {
- return new WebGLShader(ctx, type);
+ return MakeGarbageCollected<WebGLShader>(ctx, type);
}
WebGLShader::WebGLShader(WebGLRenderingContextBase* ctx, GLenum type)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.h
index 9a81ed0aac9..0cc62ead4a1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader.h
@@ -39,14 +39,14 @@ class WebGLShader final : public WebGLSharedPlatform3DObject {
static WebGLShader* Create(WebGLRenderingContextBase*, GLenum);
+ WebGLShader(WebGLRenderingContextBase*, GLenum);
+
GLenum GetType() const { return type_; }
const String& Source() const { return source_; }
void SetSource(const String& source) { source_ = source; }
private:
- WebGLShader(WebGLRenderingContextBase*, GLenum);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
bool IsShader() const override { return true; }
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.cc
index dc491df9468..b29becdb23f 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.cc
@@ -33,7 +33,8 @@ WebGLShaderPrecisionFormat* WebGLShaderPrecisionFormat::Create(
GLint range_min,
GLint range_max,
GLint precision) {
- return new WebGLShaderPrecisionFormat(range_min, range_max, precision);
+ return MakeGarbageCollected<WebGLShaderPrecisionFormat>(range_min, range_max,
+ precision);
}
GLint WebGLShaderPrecisionFormat::rangeMin() const {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h
index 8d566239cf7..a7432ab8158 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h
@@ -41,13 +41,13 @@ class WebGLShaderPrecisionFormat final : public ScriptWrappable {
GLint range_max,
GLint precision);
+ WebGLShaderPrecisionFormat(GLint range_min, GLint range_max, GLint precision);
+
GLint rangeMin() const;
GLint rangeMax() const;
GLint precision() const;
private:
- WebGLShaderPrecisionFormat(GLint range_min, GLint range_max, GLint precision);
-
GLint range_min_;
GLint range_max_;
GLint precision_;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.cc
index 5aea3371718..b1062539185 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.cc
@@ -23,7 +23,7 @@ WebGLSync::WebGLSync(WebGL2RenderingContextBase* ctx,
ctx->canvas()->GetDocument().GetTaskRunner(TaskType::kInternalDefault);
} else {
// Fallback for OffscreenCanvas (no frame scheduler)
- task_runner_ = Platform::Current()->CurrentThread()->GetTaskRunner();
+ task_runner_ = Thread::Current()->GetTaskRunner();
}
ScheduleAllowCacheUpdate();
}
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.h
index 2f88db96216..b7fc0459ee0 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_sync.h
@@ -7,7 +7,7 @@
#include "base/single_thread_task_runner.h"
#include "third_party/blink/renderer/modules/webgl/webgl_shared_object.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
namespace gpu {
namespace gles2 {
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.cc
index 1c8cfa89e05..6f2647a2409 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.cc
@@ -31,7 +31,7 @@
namespace blink {
WebGLTexture* WebGLTexture::Create(WebGLRenderingContextBase* ctx) {
- return new WebGLTexture(ctx);
+ return MakeGarbageCollected<WebGLTexture>(ctx);
}
WebGLTexture::WebGLTexture(WebGLRenderingContextBase* ctx)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.h
index e846a206f54..93c6e88d5b1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_texture.h
@@ -35,6 +35,7 @@ class WebGLTexture final : public WebGLSharedPlatform3DObject {
DEFINE_WRAPPERTYPEINFO();
public:
+ explicit WebGLTexture(WebGLRenderingContextBase*);
~WebGLTexture() override;
static WebGLTexture* Create(WebGLRenderingContextBase*);
@@ -72,8 +73,6 @@ class WebGLTexture final : public WebGLSharedPlatform3DObject {
}
private:
- explicit WebGLTexture(WebGLRenderingContextBase*);
-
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
bool IsTexture() const override { return true; }
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.cc
index 85eabb10c88..cbb0b5e2143 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.cc
@@ -12,7 +12,7 @@
namespace blink {
WebGLTimerQueryEXT* WebGLTimerQueryEXT::Create(WebGLRenderingContextBase* ctx) {
- return new WebGLTimerQueryEXT(ctx);
+ return MakeGarbageCollected<WebGLTimerQueryEXT>(ctx);
}
WebGLTimerQueryEXT::WebGLTimerQueryEXT(WebGLRenderingContextBase* ctx)
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.h
index 6262c5b9270..d5f709f528c 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_timer_query_ext.h
@@ -7,7 +7,7 @@
#include "base/single_thread_task_runner.h"
#include "third_party/blink/renderer/modules/webgl/webgl_context_object.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
namespace gpu {
namespace gles2 {
@@ -22,6 +22,8 @@ class WebGLTimerQueryEXT : public WebGLContextObject {
public:
static WebGLTimerQueryEXT* Create(WebGLRenderingContextBase*);
+
+ WebGLTimerQueryEXT(WebGLRenderingContextBase*);
~WebGLTimerQueryEXT() override;
void SetTarget(GLenum target) { target_ = target; }
@@ -36,9 +38,6 @@ class WebGLTimerQueryEXT : public WebGLContextObject {
bool IsQueryResultAvailable();
GLuint64 GetQueryResult();
- protected:
- WebGLTimerQueryEXT(WebGLRenderingContextBase*);
-
private:
bool HasObject() const override { return query_id_ != 0; }
void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.cc
index db1df4bf068..907695bf2f3 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.cc
@@ -12,7 +12,7 @@ namespace blink {
WebGLTransformFeedback* WebGLTransformFeedback::Create(
WebGL2RenderingContextBase* ctx,
TFType type) {
- return new WebGLTransformFeedback(ctx, type);
+ return MakeGarbageCollected<WebGLTransformFeedback>(ctx, type);
}
WebGLTransformFeedback::WebGLTransformFeedback(WebGL2RenderingContextBase* ctx,
@@ -45,10 +45,9 @@ WebGLTransformFeedback::~WebGLTransformFeedback() {
}
void WebGLTransformFeedback::DispatchDetached(gpu::gles2::GLES2Interface* gl) {
- for (size_t i = 0; i < bound_indexed_transform_feedback_buffers_.size();
- ++i) {
- if (bound_indexed_transform_feedback_buffers_[i])
- bound_indexed_transform_feedback_buffers_[i]->OnDetached(gl);
+ for (WebGLBuffer* buffer : bound_indexed_transform_feedback_buffers_) {
+ if (buffer)
+ buffer->OnDetached(gl);
}
}
@@ -123,16 +122,16 @@ bool WebGLTransformFeedback::HasEnoughBuffers(GLuint num_required) const {
}
bool WebGLTransformFeedback::UsesBuffer(WebGLBuffer* buffer) {
- for (size_t i = 0; i < bound_indexed_transform_feedback_buffers_.size();
- ++i) {
- if (bound_indexed_transform_feedback_buffers_[i] == buffer)
+ for (WebGLBuffer* feedback_buffer :
+ bound_indexed_transform_feedback_buffers_) {
+ if (feedback_buffer == buffer)
return true;
}
return false;
}
void WebGLTransformFeedback::UnbindBuffer(WebGLBuffer* buffer) {
- for (size_t i = 0; i < bound_indexed_transform_feedback_buffers_.size();
+ for (wtf_size_t i = 0; i < bound_indexed_transform_feedback_buffers_.size();
++i) {
if (bound_indexed_transform_feedback_buffers_[i] == buffer) {
bound_indexed_transform_feedback_buffers_[i]->OnDetached(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.h
index cf561d31357..a27fb6f85d3 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_transform_feedback.h
@@ -23,6 +23,7 @@ class WebGLTransformFeedback : public WebGLContextObject {
TFTypeUser,
};
+ explicit WebGLTransformFeedback(WebGL2RenderingContextBase*, TFType);
~WebGLTransformFeedback() override;
GLuint Object() const { return object_; }
@@ -70,9 +71,6 @@ class WebGLTransformFeedback : public WebGLContextObject {
bool ValidateProgramForResume(WebGLProgram*) const;
- protected:
- explicit WebGLTransformFeedback(WebGL2RenderingContextBase*, TFType);
-
private:
void DispatchDetached(gpu::gles2::GLES2Interface*);
bool HasObject() const override { return object_ != 0; }
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.cc
index 7b73628219b..e6d7a1db38c 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.cc
@@ -30,7 +30,7 @@ namespace blink {
WebGLUniformLocation* WebGLUniformLocation::Create(WebGLProgram* program,
GLint location) {
- return new WebGLUniformLocation(program, location);
+ return MakeGarbageCollected<WebGLUniformLocation>(program, location);
}
WebGLUniformLocation::WebGLUniformLocation(WebGLProgram* program,
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.h
index 4d975f4834f..3ed78d9c05f 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_uniform_location.h
@@ -38,15 +38,14 @@ class WebGLUniformLocation final : public ScriptWrappable {
public:
static WebGLUniformLocation* Create(WebGLProgram*, GLint location);
+ WebGLUniformLocation(WebGLProgram*, GLint location);
+
WebGLProgram* Program() const;
GLint Location() const;
void Trace(blink::Visitor*) override;
- protected:
- WebGLUniformLocation(WebGLProgram*, GLint location);
-
private:
Member<WebGLProgram> program_;
GLint location_;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.cc
index c47d0838f02..de593528f27 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.cc
@@ -11,7 +11,7 @@ namespace blink {
WebGLVertexArrayObject* WebGLVertexArrayObject::Create(
WebGLRenderingContextBase* ctx,
VaoType type) {
- return new WebGLVertexArrayObject(ctx, type);
+ return MakeGarbageCollected<WebGLVertexArrayObject>(ctx, type);
}
WebGLVertexArrayObject::WebGLVertexArrayObject(WebGLRenderingContextBase* ctx,
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.h
index 808d822bcd5..8b09f2283f1 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object.h
@@ -15,7 +15,6 @@ class WebGLVertexArrayObject final : public WebGLVertexArrayObjectBase {
public:
static WebGLVertexArrayObject* Create(WebGLRenderingContextBase*, VaoType);
- private:
explicit WebGLVertexArrayObject(WebGLRenderingContextBase*, VaoType);
};
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.cc
index da110a05a7c..61135789a0f 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.cc
@@ -19,7 +19,7 @@ WebGLVertexArrayObjectBase::WebGLVertexArrayObjectBase(
is_all_enabled_attrib_buffer_bound_(true) {
array_buffer_list_.resize(ctx->MaxVertexAttribs());
attrib_enabled_.resize(ctx->MaxVertexAttribs());
- for (size_t i = 0; i < attrib_enabled_.size(); ++i) {
+ for (wtf_size_t i = 0; i < attrib_enabled_.size(); ++i) {
attrib_enabled_[i] = false;
}
@@ -41,9 +41,9 @@ void WebGLVertexArrayObjectBase::DispatchDetached(
if (bound_element_array_buffer_)
bound_element_array_buffer_->OnDetached(gl);
- for (size_t i = 0; i < array_buffer_list_.size(); ++i) {
- if (array_buffer_list_[i])
- array_buffer_list_[i]->OnDetached(gl);
+ for (WebGLBuffer* buffer : array_buffer_list_) {
+ if (buffer)
+ buffer->OnDetached(gl);
}
}
@@ -74,7 +74,7 @@ void WebGLVertexArrayObjectBase::SetElementArrayBuffer(WebGLBuffer* buffer) {
bound_element_array_buffer_ = buffer;
}
-WebGLBuffer* WebGLVertexArrayObjectBase::GetArrayBufferForAttrib(size_t index) {
+WebGLBuffer* WebGLVertexArrayObjectBase::GetArrayBufferForAttrib(GLuint index) {
DCHECK(index < Context()->MaxVertexAttribs());
return array_buffer_list_[index].Get();
}
@@ -103,7 +103,7 @@ bool WebGLVertexArrayObjectBase::GetAttribEnabled(GLuint index) const {
void WebGLVertexArrayObjectBase::UpdateAttribBufferBoundStatus() {
is_all_enabled_attrib_buffer_bound_ = true;
- for (size_t i = 0; i < attrib_enabled_.size(); ++i) {
+ for (wtf_size_t i = 0; i < attrib_enabled_.size(); ++i) {
if (attrib_enabled_[i] && !array_buffer_list_[i]) {
is_all_enabled_attrib_buffer_bound_ = false;
return;
@@ -117,7 +117,7 @@ void WebGLVertexArrayObjectBase::UnbindBuffer(WebGLBuffer* buffer) {
bound_element_array_buffer_ = nullptr;
}
- for (size_t i = 0; i < array_buffer_list_.size(); ++i) {
+ for (wtf_size_t i = 0; i < array_buffer_list_.size(); ++i) {
if (array_buffer_list_[i] == buffer) {
array_buffer_list_[i]->OnDetached(Context()->ContextGL());
array_buffer_list_[i] = nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.h
index 18930ea7181..9b0de361f52 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_base.h
@@ -33,7 +33,7 @@ class WebGLVertexArrayObjectBase : public WebGLContextObject {
}
void SetElementArrayBuffer(WebGLBuffer*);
- WebGLBuffer* GetArrayBufferForAttrib(size_t);
+ WebGLBuffer* GetArrayBufferForAttrib(GLuint);
void SetArrayBufferForAttrib(GLuint, WebGLBuffer*);
void SetAttribEnabled(GLuint, bool);
bool GetAttribEnabled(GLuint) const;
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.cc b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.cc
index 77253eb90cc..34928eef020 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.cc
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.cc
@@ -32,7 +32,7 @@ namespace blink {
WebGLVertexArrayObjectOES* WebGLVertexArrayObjectOES::Create(
WebGLRenderingContextBase* ctx,
VaoType type) {
- return new WebGLVertexArrayObjectOES(ctx, type);
+ return MakeGarbageCollected<WebGLVertexArrayObjectOES>(ctx, type);
}
WebGLVertexArrayObjectOES::WebGLVertexArrayObjectOES(
diff --git a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.h b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.h
index cb22a707622..9368d09830a 100644
--- a/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.h
+++ b/chromium/third_party/blink/renderer/modules/webgl/webgl_vertex_array_object_oes.h
@@ -36,7 +36,6 @@ class WebGLVertexArrayObjectOES final : public WebGLVertexArrayObjectBase {
public:
static WebGLVertexArrayObjectOES* Create(WebGLRenderingContextBase*, VaoType);
- private:
explicit WebGLVertexArrayObjectOES(WebGLRenderingContextBase*, VaoType);
};
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/webgpu.cc b/chromium/third_party/blink/renderer/modules/webgpu/webgpu.cc
index 4ec95c9d1e2..05edb4298ca 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/webgpu.cc
+++ b/chromium/third_party/blink/renderer/modules/webgpu/webgpu.cc
@@ -11,11 +11,11 @@ namespace blink {
// static
WebGPU* WebGPU::Create() {
- return new WebGPU();
+ return MakeGarbageCollected<WebGPU>();
}
-WebGPUAdapter* WebGPU::getAdapter(const WebGPUAdapterDescriptor& descriptor) {
- return WebGPUAdapter::Create(descriptor.powerPreference());
+WebGPUAdapter* WebGPU::getAdapter(const WebGPUAdapterDescriptor* descriptor) {
+ return WebGPUAdapter::Create(descriptor->powerPreference());
}
WebGPU::WebGPU() {}
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/webgpu.h b/chromium/third_party/blink/renderer/modules/webgpu/webgpu.h
index d989b7a1966..84a2fc53878 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/webgpu.h
+++ b/chromium/third_party/blink/renderer/modules/webgpu/webgpu.h
@@ -19,10 +19,9 @@ class WebGPU final : public ScriptWrappable {
public:
static WebGPU* Create();
- WebGPUAdapter* getAdapter(const WebGPUAdapterDescriptor&);
-
- private:
WebGPU();
+
+ WebGPUAdapter* getAdapter(const WebGPUAdapterDescriptor*);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.cc b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.cc
index 1d026aea4c1..b54707463f9 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.cc
+++ b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.cc
@@ -10,7 +10,7 @@ namespace blink {
// static
WebGPUAdapter* WebGPUAdapter::Create(const String& name) {
- return new WebGPUAdapter(name);
+ return MakeGarbageCollected<WebGPUAdapter>(name);
}
const String& WebGPUAdapter::name() const {
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.h b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.h
index 1111631f3e7..07af4bdbd53 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.h
+++ b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_adapter.h
@@ -20,13 +20,13 @@ class WebGPUAdapter final : public ScriptWrappable {
public:
static WebGPUAdapter* Create(const String& name);
+ WebGPUAdapter(const String& name);
+
const String& name() const;
WebGPUDevice* createDevice(ExecutionContext*);
private:
- WebGPUAdapter(const String& name);
-
String name_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.cc b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.cc
index f10c7e37fed..3d78a0c9642 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.cc
+++ b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.cc
@@ -34,7 +34,8 @@ WebGPUDevice* WebGPUDevice::Create(ExecutionContext* execution_context,
return nullptr;
}
- return new WebGPUDevice(adapter, std::move(context_provider));
+ return MakeGarbageCollected<WebGPUDevice>(adapter,
+ std::move(context_provider));
}
WebGPUAdapter* WebGPUDevice::adapter() const {
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.h b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.h
index 5b1bd9d9b4c..0275962f5dd 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.h
+++ b/chromium/third_party/blink/renderer/modules/webgpu/webgpu_device.h
@@ -20,6 +20,8 @@ class WebGPUDevice final : public ScriptWrappable {
public:
static WebGPUDevice* Create(ExecutionContext*, WebGPUAdapter*);
+ WebGPUDevice(WebGPUAdapter*, std::unique_ptr<WebGraphicsContext3DProvider>);
+
WebGPUAdapter* adapter() const;
void dummy() const;
@@ -27,8 +29,6 @@ class WebGPUDevice final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- WebGPUDevice(WebGPUAdapter*, std::unique_ptr<WebGraphicsContext3DProvider>);
-
gpu::webgpu::WebGPUInterface* Interface() const;
Member<WebGPUAdapter> adapter_;
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.cc b/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.cc
index 1a578453d91..b392dd09d1b 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.cc
+++ b/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.cc
@@ -16,7 +16,7 @@ WindowWebGPU& WindowWebGPU::From(LocalDOMWindow& window) {
WindowWebGPU* supplement =
Supplement<LocalDOMWindow>::From<WindowWebGPU>(window);
if (!supplement) {
- supplement = new WindowWebGPU(window);
+ supplement = MakeGarbageCollected<WindowWebGPU>(window);
ProvideTo(window, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.h b/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.h
index 426040f0ce1..6ca560639a4 100644
--- a/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.h
+++ b/chromium/third_party/blink/renderer/modules/webgpu/window_webgpu.h
@@ -24,11 +24,11 @@ class WindowWebGPU final : public GarbageCollected<WindowWebGPU>,
static WebGPU* webgpu(LocalDOMWindow&);
WebGPU* webgpu() const;
+ explicit WindowWebGPU(LocalDOMWindow&);
+
void Trace(blink::Visitor*) override;
private:
- explicit WindowWebGPU(LocalDOMWindow&);
-
mutable Member<WebGPU> webgpu_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_access.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_access.cc
index 1d64eac6069..e123c7fad26 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_access.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_access.cc
@@ -89,12 +89,12 @@ void MIDIAccess::Dispose() {
}
EventListener* MIDIAccess::onstatechange() {
- return GetAttributeEventListener(EventTypeNames::statechange);
+ return GetAttributeEventListener(event_type_names::kStatechange);
}
void MIDIAccess::setOnstatechange(EventListener* listener) {
has_pending_activity_ = listener;
- SetAttributeEventListener(EventTypeNames::statechange, listener);
+ SetAttributeEventListener(event_type_names::kStatechange, listener);
}
bool MIDIAccess::HasPendingActivity() const {
@@ -115,7 +115,7 @@ MIDIInputMap* MIDIAccess::inputs() const {
// There is id duplication that violates the spec.
inputs.clear();
}
- return new MIDIInputMap(inputs);
+ return MakeGarbageCollected<MIDIInputMap>(inputs);
}
MIDIOutputMap* MIDIAccess::outputs() const {
@@ -131,7 +131,7 @@ MIDIOutputMap* MIDIAccess::outputs() const {
// There is id duplication that violates the spec.
outputs.clear();
}
- return new MIDIOutputMap(outputs);
+ return MakeGarbageCollected<MIDIOutputMap>(outputs);
}
void MIDIAccess::DidAddInputPort(const String& id,
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_access.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_access.h
index 0316e8976a5..e0b5f9ab0ce 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_access.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_access.h
@@ -65,9 +65,14 @@ class MIDIAccess final : public EventTargetWithInlineData,
bool sysex_enabled,
const Vector<MIDIAccessInitializer::PortDescriptor>& ports,
ExecutionContext* execution_context) {
- return new MIDIAccess(std::move(accessor), sysex_enabled, ports,
- execution_context);
+ return MakeGarbageCollected<MIDIAccess>(std::move(accessor), sysex_enabled,
+ ports, execution_context);
}
+
+ MIDIAccess(std::unique_ptr<MIDIAccessor>,
+ bool sysex_enabled,
+ const Vector<MIDIAccessInitializer::PortDescriptor>&,
+ ExecutionContext*);
~MIDIAccess() override;
MIDIInputMap* inputs() const;
@@ -80,7 +85,7 @@ class MIDIAccess final : public EventTargetWithInlineData,
// EventTarget
const AtomicString& InterfaceName() const override {
- return EventTargetNames::MIDIAccess;
+ return event_target_names::kMIDIAccess;
}
ExecutionContext* GetExecutionContext() const override {
return ContextLifecycleObserver::GetExecutionContext();
@@ -130,10 +135,6 @@ class MIDIAccess final : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
private:
- MIDIAccess(std::unique_ptr<MIDIAccessor>,
- bool sysex_enabled,
- const Vector<MIDIAccessInitializer::PortDescriptor>&,
- ExecutionContext*);
void Dispose();
std::unique_ptr<MIDIAccessor> accessor_;
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.cc
index 5db5ab3f029..f6be881d194 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.cc
@@ -26,7 +26,7 @@ using midi::mojom::Result;
using mojom::blink::PermissionStatus;
MIDIAccessInitializer::MIDIAccessInitializer(ScriptState* script_state,
- const MIDIOptions& options)
+ const MIDIOptions* options)
: ScriptPromiseResolver(script_state), options_(options) {}
void MIDIAccessInitializer::ContextDestroyed(ExecutionContext* context) {
@@ -45,7 +45,7 @@ ScriptPromise MIDIAccessInitializer::Start() {
Document& doc = To<Document>(*GetExecutionContext());
permission_service_->RequestPermission(
- CreateMidiPermissionDescriptor(options_.hasSysex() && options_.sysex()),
+ CreateMidiPermissionDescriptor(options_->hasSysex() && options_->sysex()),
LocalFrame::HasTransientUserActivation(doc.GetFrame()),
WTF::Bind(&MIDIAccessInitializer::OnPermissionsUpdated,
WrapPersistent(this)));
@@ -96,7 +96,7 @@ void MIDIAccessInitializer::DidStartSession(Result result) {
break;
case Result::OK:
return Resolve(MIDIAccess::Create(
- std::move(accessor_), options_.hasSysex() && options_.sysex(),
+ std::move(accessor_), options_->hasSysex() && options_->sysex(),
port_descriptors_, GetExecutionContext()));
case Result::NOT_SUPPORTED:
return Reject(DOMException::Create(DOMExceptionCode::kNotSupportedError));
@@ -110,6 +110,11 @@ void MIDIAccessInitializer::DidStartSession(Result result) {
"Unknown internal error occurred."));
}
+void MIDIAccessInitializer::Trace(Visitor* visitor) {
+ visitor->Trace(options_);
+ ScriptPromiseResolver::Trace(visitor);
+}
+
ExecutionContext* MIDIAccessInitializer::GetExecutionContext() const {
return ExecutionContext::From(GetScriptState());
}
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.h
index ef1e7d4d84b..cf12df77925 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_access_initializer.h
@@ -49,14 +49,15 @@ class MODULES_EXPORT MIDIAccessInitializer : public ScriptPromiseResolver,
};
static ScriptPromise Start(ScriptState* script_state,
- const MIDIOptions& options) {
+ const MIDIOptions* options) {
MIDIAccessInitializer* resolver =
- new MIDIAccessInitializer(script_state, options);
+ MakeGarbageCollected<MIDIAccessInitializer>(script_state, options);
resolver->KeepAliveWhilePending();
resolver->PauseIfNeeded();
return resolver->Start();
}
+ MIDIAccessInitializer(ScriptState*, const MIDIOptions*);
~MIDIAccessInitializer() override = default;
// Eager finalization to allow dispose() operation access
@@ -84,9 +85,9 @@ class MODULES_EXPORT MIDIAccessInitializer : public ScriptPromiseResolver,
size_t length,
TimeTicks time_stamp) override {}
- private:
- MIDIAccessInitializer(ScriptState*, const MIDIOptions&);
+ void Trace(Visitor*) override;
+ private:
ExecutionContext* GetExecutionContext() const;
ScriptPromise Start();
@@ -97,7 +98,7 @@ class MODULES_EXPORT MIDIAccessInitializer : public ScriptPromiseResolver,
std::unique_ptr<MIDIAccessor> accessor_;
Vector<PortDescriptor> port_descriptors_;
- MIDIOptions options_;
+ Member<const MIDIOptions> options_;
mojom::blink::PermissionServicePtr permission_service_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.cc
index ebb22da3fe5..b08a4b1d41d 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.cc
@@ -36,10 +36,10 @@ namespace blink {
MIDIConnectionEvent::MIDIConnectionEvent(
const AtomicString& type,
- const MIDIConnectionEventInit& initializer)
+ const MIDIConnectionEventInit* initializer)
: Event(type, initializer), port_(nullptr) {
- if (initializer.hasPort())
- port_ = initializer.port();
+ if (initializer->hasPort())
+ port_ = initializer->port();
}
void MIDIConnectionEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.h
index 93bd351e724..40ed7cda65d 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_connection_event.h
@@ -43,30 +43,28 @@ class MIDIConnectionEvent final : public Event {
public:
static MIDIConnectionEvent* Create(MIDIPort* port) {
- return new MIDIConnectionEvent(port);
+ return MakeGarbageCollected<MIDIConnectionEvent>(port);
}
static MIDIConnectionEvent* Create(
const AtomicString& type,
- const MIDIConnectionEventInit& initializer) {
- return new MIDIConnectionEvent(type, initializer);
+ const MIDIConnectionEventInit* initializer) {
+ return MakeGarbageCollected<MIDIConnectionEvent>(type, initializer);
}
+ MIDIConnectionEvent(MIDIPort* port)
+ : Event(event_type_names::kStatechange, Bubbles::kNo, Cancelable::kNo),
+ port_(port) {}
+ MIDIConnectionEvent(const AtomicString&, const MIDIConnectionEventInit*);
MIDIPort* port() { return port_; }
const AtomicString& InterfaceName() const override {
- return EventNames::MIDIConnectionEvent;
+ return event_interface_names::kMIDIConnectionEvent;
}
void Trace(blink::Visitor*) override;
private:
- MIDIConnectionEvent(MIDIPort* port)
- : Event(EventTypeNames::statechange, Bubbles::kNo, Cancelable::kNo),
- port_(port) {}
-
- MIDIConnectionEvent(const AtomicString&, const MIDIConnectionEventInit&);
-
Member<MIDIPort> port_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_input.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_input.cc
index 65395387832..641d1431490 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_input.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_input.cc
@@ -35,6 +35,7 @@
#include "third_party/blink/renderer/modules/webmidi/midi_access.h"
#include "third_party/blink/renderer/modules/webmidi/midi_message_event.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -47,7 +48,8 @@ MIDIInput* MIDIInput::Create(MIDIAccess* access,
const String& version,
PortState state) {
DCHECK(access);
- return new MIDIInput(access, id, manufacturer, name, version, state);
+ return MakeGarbageCollected<MIDIInput>(access, id, manufacturer, name,
+ version, state);
}
MIDIInput::MIDIInput(MIDIAccess* access,
@@ -59,7 +61,7 @@ MIDIInput::MIDIInput(MIDIAccess* access,
: MIDIPort(access, id, manufacturer, name, kTypeInput, version, state) {}
EventListener* MIDIInput::onmidimessage() {
- return GetAttributeEventListener(EventTypeNames::midimessage);
+ return GetAttributeEventListener(event_type_names::kMidimessage);
}
void MIDIInput::setOnmidimessage(EventListener* listener) {
@@ -67,14 +69,14 @@ void MIDIInput::setOnmidimessage(EventListener* listener) {
// See http://www.w3.org/TR/webmidi/#widl-MIDIPort-open-Promise-MIDIPort
open();
- SetAttributeEventListener(EventTypeNames::midimessage, listener);
+ SetAttributeEventListener(event_type_names::kMidimessage, listener);
}
void MIDIInput::AddedEventListener(
const AtomicString& event_type,
RegisteredEventListener& registered_listener) {
MIDIPort::AddedEventListener(event_type, registered_listener);
- if (event_type == EventTypeNames::midimessage) {
+ if (event_type == event_type_names::kMidimessage) {
// Implicit open. See setOnmidimessage().
open();
}
@@ -98,7 +100,8 @@ void MIDIInput::DidReceiveMIDIData(unsigned port_index,
// the current process has an explicit permission to handle sysex message.
if (data[0] == 0xf0 && !midiAccess()->sysexEnabled())
return;
- DOMUint8Array* array = DOMUint8Array::Create(data, length);
+ DOMUint8Array* array =
+ DOMUint8Array::Create(data, SafeCast<unsigned>(length));
DispatchEvent(*MIDIMessageEvent::Create(time_stamp, array));
UseCounter::Count(*To<Document>(GetExecutionContext()),
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_input.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_input.h
index 2cb60fc366f..9e19a3cbfd5 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_input.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_input.h
@@ -50,6 +50,13 @@ class MIDIInput final : public MIDIPort {
const String& name,
const String& version,
midi::mojom::PortState);
+
+ MIDIInput(MIDIAccess*,
+ const String& id,
+ const String& manufacturer,
+ const String& name,
+ const String& version,
+ midi::mojom::PortState);
~MIDIInput() override = default;
EventListener* onmidimessage();
@@ -57,7 +64,7 @@ class MIDIInput final : public MIDIPort {
// EventTarget
const AtomicString& InterfaceName() const override {
- return EventTargetNames::MIDIInput;
+ return event_target_names::kMIDIInput;
}
void DidReceiveMIDIData(unsigned port_index,
@@ -70,14 +77,6 @@ class MIDIInput final : public MIDIPort {
protected:
void AddedEventListener(const AtomicString& event_type,
RegisteredEventListener&) override;
-
- private:
- MIDIInput(MIDIAccess*,
- const String& id,
- const String& manufacturer,
- const String& name,
- const String& version,
- midi::mojom::PortState);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.cc
index 0a9c6ad2bda..cd12cc44f80 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.cc
@@ -9,10 +9,10 @@
namespace blink {
MIDIMessageEvent::MIDIMessageEvent(const AtomicString& type,
- const MIDIMessageEventInit& initializer)
+ const MIDIMessageEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasData())
- data_ = initializer.data().View();
+ if (initializer->hasData())
+ data_ = initializer->data().View();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.h
index 5a2336d14be..8407d3332b9 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_message_event.h
@@ -46,18 +46,27 @@ class MIDIMessageEvent final : public Event {
public:
static MIDIMessageEvent* Create(base::TimeTicks time_stamp,
DOMUint8Array* data) {
- return new MIDIMessageEvent(time_stamp, data);
+ return MakeGarbageCollected<MIDIMessageEvent>(time_stamp, data);
}
static MIDIMessageEvent* Create(const AtomicString& type,
- const MIDIMessageEventInit& initializer) {
- return new MIDIMessageEvent(type, initializer);
+ const MIDIMessageEventInit* initializer) {
+ return MakeGarbageCollected<MIDIMessageEvent>(type, initializer);
}
+ MIDIMessageEvent(base::TimeTicks time_stamp, DOMUint8Array* data)
+ : Event(event_type_names::kMidimessage,
+ Bubbles::kYes,
+ Cancelable::kNo,
+ time_stamp),
+ data_(data) {}
+ MIDIMessageEvent(const AtomicString& type,
+ const MIDIMessageEventInit* initializer);
+
DOMUint8Array* data() { return data_; }
const AtomicString& InterfaceName() const override {
- return EventNames::MIDIMessageEvent;
+ return event_interface_names::kMIDIMessageEvent;
}
void Trace(blink::Visitor* visitor) override {
@@ -66,16 +75,6 @@ class MIDIMessageEvent final : public Event {
}
private:
- MIDIMessageEvent(base::TimeTicks time_stamp, DOMUint8Array* data)
- : Event(EventTypeNames::midimessage,
- Bubbles::kYes,
- Cancelable::kNo,
- time_stamp),
- data_(data) {}
-
- MIDIMessageEvent(const AtomicString& type,
- const MIDIMessageEventInit& initializer);
-
Member<DOMUint8Array> data_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_output.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_output.cc
index 9c087cbbad3..01a88dafee0 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_output.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_output.cc
@@ -234,8 +234,8 @@ MIDIOutput* MIDIOutput::Create(MIDIAccess* access,
const String& version,
PortState state) {
DCHECK(access);
- return new MIDIOutput(access, port_index, id, manufacturer, name, version,
- state);
+ return MakeGarbageCollected<MIDIOutput>(access, port_index, id, manufacturer,
+ name, version, state);
}
MIDIOutput::MIDIOutput(MIDIAccess* access,
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_output.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_output.h
index 60a5947bfd1..da32ab87b9d 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_output.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_output.h
@@ -54,6 +54,14 @@ class MIDIOutput final : public MIDIPort {
const String& name,
const String& version,
midi::mojom::PortState);
+
+ MIDIOutput(MIDIAccess*,
+ unsigned port_index,
+ const String& id,
+ const String& manufacturer,
+ const String& name,
+ const String& version,
+ midi::mojom::PortState);
~MIDIOutput() override;
void send(NotShared<DOMUint8Array>, double timestamp, ExceptionState&);
@@ -66,14 +74,6 @@ class MIDIOutput final : public MIDIPort {
void Trace(blink::Visitor*) override;
private:
- MIDIOutput(MIDIAccess*,
- unsigned port_index,
- const String& id,
- const String& manufacturer,
- const String& name,
- const String& version,
- midi::mojom::PortState);
-
void DidOpen(bool opened) override;
void SendInternal(DOMUint8Array*, base::TimeTicks timestamp, ExceptionState&);
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_port.cc b/chromium/third_party/blink/renderer/modules/webmidi/midi_port.cc
index 776eaa6d9fe..f2716813b2b 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_port.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_port.cc
@@ -37,6 +37,7 @@
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/modules/webmidi/midi_access.h"
#include "third_party/blink/renderer/modules/webmidi/midi_connection_event.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
using midi::mojom::PortState;
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_port.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_port.h
index c8e43429c0b..f289b719223 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_port.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_port.h
@@ -79,11 +79,11 @@ class MIDIPort : public EventTargetWithInlineData,
void Trace(blink::Visitor*) override;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange);
// EventTarget
const AtomicString& InterfaceName() const override {
- return EventTargetNames::MIDIPort;
+ return event_target_names::kMIDIPort;
}
ExecutionContext* GetExecutionContext() const final;
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/midi_port_map.h b/chromium/third_party/blink/renderer/modules/webmidi/midi_port_map.h
index 51db70ef437..c73a226a188 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/midi_port_map.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/midi_port_map.h
@@ -36,7 +36,8 @@ class MIDIPortMap : public ScriptWrappable, public Maplike<String, T*> {
typename PairIterable<String, T*>::IterationSource* StartIteration(
ScriptState*,
ExceptionState&) override {
- return new MapIterationSource(this, entries_.begin(), entries_.end());
+ return MakeGarbageCollected<MapIterationSource>(this, entries_.begin(),
+ entries_.end());
}
bool GetMapEntry(ScriptState*,
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.cc b/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.cc
index aa7c5fbf746..1fa441d5e00 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.cc
+++ b/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.cc
@@ -68,7 +68,7 @@ NavigatorWebMIDI& NavigatorWebMIDI::From(Navigator& navigator) {
NavigatorWebMIDI* supplement =
Supplement<Navigator>::From<NavigatorWebMIDI>(navigator);
if (!supplement) {
- supplement = new NavigatorWebMIDI(navigator);
+ supplement = MakeGarbageCollected<NavigatorWebMIDI>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -76,13 +76,13 @@ NavigatorWebMIDI& NavigatorWebMIDI::From(Navigator& navigator) {
ScriptPromise NavigatorWebMIDI::requestMIDIAccess(ScriptState* script_state,
Navigator& navigator,
- const MIDIOptions& options) {
+ const MIDIOptions* options) {
return NavigatorWebMIDI::From(navigator).requestMIDIAccess(script_state,
options);
}
ScriptPromise NavigatorWebMIDI::requestMIDIAccess(ScriptState* script_state,
- const MIDIOptions& options) {
+ const MIDIOptions* options) {
if (!script_state->ContextIsValid()) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kAbortError,
@@ -90,7 +90,7 @@ ScriptPromise NavigatorWebMIDI::requestMIDIAccess(ScriptState* script_state,
}
Document& document = *To<Document>(ExecutionContext::From(script_state));
- if (options.hasSysex() && options.sysex()) {
+ if (options->hasSysex() && options->sysex()) {
UseCounter::Count(
document,
WebFeature::kRequestMIDIAccessWithSysExOption_ObscuredByFootprinting);
@@ -103,10 +103,9 @@ ScriptPromise NavigatorWebMIDI::requestMIDIAccess(ScriptState* script_state,
document, WebFeature::kRequestMIDIAccessIframe_ObscuredByFootprinting);
if (!document.IsFeatureEnabled(mojom::FeaturePolicyFeature::kMidiFeature,
- ReportOptions::kReportOnFailure)) {
+ ReportOptions::kReportOnFailure,
+ kFeaturePolicyConsoleWarning)) {
UseCounter::Count(document, WebFeature::kMidiDisabledByFeaturePolicy);
- document.AddConsoleMessage(ConsoleMessage::Create(
- kJSMessageSource, kWarningMessageLevel, kFeaturePolicyConsoleWarning));
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kSecurityError,
kFeaturePolicyErrorMessage));
diff --git a/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.h b/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.h
index a0cc3d061f0..51d1c93207f 100644
--- a/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.h
+++ b/chromium/third_party/blink/renderer/modules/webmidi/navigator_web_midi.h
@@ -51,13 +51,12 @@ class NavigatorWebMIDI final : public GarbageCollected<NavigatorWebMIDI>,
static NavigatorWebMIDI& From(Navigator&);
static ScriptPromise requestMIDIAccess(ScriptState*,
Navigator&,
- const MIDIOptions&);
- ScriptPromise requestMIDIAccess(ScriptState*, const MIDIOptions&);
+ const MIDIOptions*);
+ ScriptPromise requestMIDIAccess(ScriptState*, const MIDIOptions*);
- void Trace(blink::Visitor*) override;
-
- private:
explicit NavigatorWebMIDI(Navigator&);
+
+ void Trace(blink::Visitor*) override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/webshare/navigator_share.cc b/chromium/third_party/blink/renderer/modules/webshare/navigator_share.cc
index a1495b090ca..261658ce0a5 100644
--- a/chromium/third_party/blink/renderer/modules/webshare/navigator_share.cc
+++ b/chromium/third_party/blink/renderer/modules/webshare/navigator_share.cc
@@ -85,7 +85,7 @@ NavigatorShare& NavigatorShare::From(Navigator& navigator) {
NavigatorShare* supplement =
Supplement<Navigator>::From<NavigatorShare>(navigator);
if (!supplement) {
- supplement = new NavigatorShare();
+ supplement = MakeGarbageCollected<NavigatorShare>();
ProvideTo(navigator, supplement);
}
return *supplement;
@@ -101,10 +101,11 @@ NavigatorShare::NavigatorShare() = default;
const char NavigatorShare::kSupplementName[] = "NavigatorShare";
ScriptPromise NavigatorShare::share(ScriptState* script_state,
- const ShareData& share_data) {
+ const ShareData* share_data) {
Document* doc = To<Document>(ExecutionContext::From(script_state));
- if (!share_data.hasTitle() && !share_data.hasText() && !share_data.hasURL()) {
+ if (!share_data->hasTitle() && !share_data->hasText() &&
+ !share_data->hasURL()) {
v8::Local<v8::Value> error = V8ThrowException::CreateTypeError(
script_state->GetIsolate(),
"No known share data fields supplied. If using only new fields (other "
@@ -112,7 +113,7 @@ ScriptPromise NavigatorShare::share(ScriptState* script_state,
return ScriptPromise::Reject(script_state, error);
}
- KURL full_url = doc->CompleteURL(share_data.url());
+ KURL full_url = doc->CompleteURL(share_data->url());
if (!full_url.IsNull() && !full_url.IsValid()) {
v8::Local<v8::Value> error = V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "Invalid URL");
@@ -143,13 +144,14 @@ ScriptPromise NavigatorShare::share(ScriptState* script_state,
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
- ShareClientImpl* client = new ShareClientImpl(this, resolver);
+ ShareClientImpl* client =
+ MakeGarbageCollected<ShareClientImpl>(this, resolver);
clients_.insert(client);
ScriptPromise promise = resolver->Promise();
service_->Share(
- share_data.hasTitle() ? share_data.title() : g_empty_string,
- share_data.hasText() ? share_data.text() : g_empty_string, full_url,
+ share_data->hasTitle() ? share_data->title() : g_empty_string,
+ share_data->hasText() ? share_data->text() : g_empty_string, full_url,
WTF::Bind(&ShareClientImpl::Callback, WrapPersistent(client)));
return promise;
@@ -157,7 +159,7 @@ ScriptPromise NavigatorShare::share(ScriptState* script_state,
ScriptPromise NavigatorShare::share(ScriptState* script_state,
Navigator& navigator,
- const ShareData& share_data) {
+ const ShareData* share_data) {
return From(navigator).share(script_state, share_data);
}
diff --git a/chromium/third_party/blink/renderer/modules/webshare/navigator_share.h b/chromium/third_party/blink/renderer/modules/webshare/navigator_share.h
index 265103a50a2..b2ec8047a5c 100644
--- a/chromium/third_party/blink/renderer/modules/webshare/navigator_share.h
+++ b/chromium/third_party/blink/renderer/modules/webshare/navigator_share.h
@@ -28,6 +28,7 @@ class NavigatorShare final : public GarbageCollectedFinalized<NavigatorShare>,
public:
static const char kSupplementName[];
+ NavigatorShare();
~NavigatorShare();
// Gets, or creates, NavigatorShare supplement on Navigator.
@@ -35,16 +36,14 @@ class NavigatorShare final : public GarbageCollectedFinalized<NavigatorShare>,
static NavigatorShare& From(Navigator&);
// Navigator partial interface
- ScriptPromise share(ScriptState*, const ShareData&);
- static ScriptPromise share(ScriptState*, Navigator&, const ShareData&);
+ ScriptPromise share(ScriptState*, const ShareData*);
+ static ScriptPromise share(ScriptState*, Navigator&, const ShareData*);
void Trace(blink::Visitor*) override;
private:
class ShareClientImpl;
- NavigatorShare();
-
void OnConnectionError();
blink::mojom::blink::ShareServicePtr service_;
diff --git a/chromium/third_party/blink/renderer/modules/websockets/DEPS b/chromium/third_party/blink/renderer/modules/websockets/DEPS
index 601a4f2c7f9..885d10830dd 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/DEPS
+++ b/chromium/third_party/blink/renderer/modules/websockets/DEPS
@@ -1,6 +1,5 @@
include_rules = [
"+mojo/public/cpp/bindings",
- "+services/network/public/mojom/websocket.mojom-blink.h",
"-third_party/blink/renderer/modules",
"+third_party/blink/renderer/modules/event_modules.h",
"+third_party/blink/renderer/modules/event_target_modules.h",
diff --git a/chromium/third_party/blink/renderer/modules/websockets/close_event.cc b/chromium/third_party/blink/renderer/modules/websockets/close_event.cc
index c127ceca8a6..82ab1c81149 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/close_event.cc
+++ b/chromium/third_party/blink/renderer/modules/websockets/close_event.cc
@@ -7,14 +7,14 @@
namespace blink {
CloseEvent::CloseEvent(const AtomicString& type,
- const CloseEventInit& initializer)
+ const CloseEventInit* initializer)
: Event(type, initializer), was_clean_(false), code_(0) {
- if (initializer.hasWasClean())
- was_clean_ = initializer.wasClean();
- if (initializer.hasCode())
- code_ = initializer.code();
- if (initializer.hasReason())
- reason_ = initializer.reason();
+ if (initializer->hasWasClean())
+ was_clean_ = initializer->wasClean();
+ if (initializer->hasCode())
+ code_ = initializer->code();
+ if (initializer->hasReason())
+ reason_ = initializer->reason();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/websockets/close_event.h b/chromium/third_party/blink/renderer/modules/websockets/close_event.h
index b7aec3eceb1..96f686e616b 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/close_event.h
+++ b/chromium/third_party/blink/renderer/modules/websockets/close_event.h
@@ -55,7 +55,7 @@ class CloseEvent final : public Event {
}
static CloseEvent* Create(const AtomicString& type,
- const CloseEventInit& initializer) {
+ const CloseEventInit* initializer) {
return new CloseEvent(type, initializer);
}
@@ -65,7 +65,7 @@ class CloseEvent final : public Event {
// Event function.
const AtomicString& InterfaceName() const override {
- return EventNames::CloseEvent;
+ return event_interface_names::kCloseEvent;
}
void Trace(blink::Visitor* visitor) override { Event::Trace(visitor); }
@@ -74,12 +74,12 @@ class CloseEvent final : public Event {
CloseEvent() : was_clean_(false), code_(0) {}
CloseEvent(bool was_clean, int code, const String& reason)
- : Event(EventTypeNames::close, Bubbles::kNo, Cancelable::kNo),
+ : Event(event_type_names::kClose, Bubbles::kNo, Cancelable::kNo),
was_clean_(was_clean),
code_(code),
reason_(reason) {}
- CloseEvent(const AtomicString& type, const CloseEventInit& initializer);
+ CloseEvent(const AtomicString& type, const CloseEventInit* initializer);
bool was_clean_;
unsigned short code_;
diff --git a/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.cc b/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.cc
index 8d10617e9f6..68dc041aa60 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.cc
+++ b/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.cc
@@ -62,6 +62,7 @@
#include "third_party/blink/renderer/platform/weborigin/known_ports.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -276,7 +277,7 @@ DOMWebSocket* DOMWebSocket::Create(ExecutionContext* context,
return nullptr;
}
- DOMWebSocket* websocket = new DOMWebSocket(context);
+ DOMWebSocket* websocket = MakeGarbageCollected<DOMWebSocket>(context);
websocket->PauseIfNeeded();
if (protocols.IsNull()) {
@@ -318,6 +319,9 @@ void DOMWebSocket::Connect(const String& url,
if (!upgrade_insecure_requests_set) {
was_autoupgraded_to_wss_ = true;
LogMixedAutoupgradeStatus(MixedContentAutoupgradeStatus::kStarted);
+ GetExecutionContext()->AddConsoleMessage(
+ MixedContentChecker::CreateConsoleMessageAboutWebSocketAutoupgrade(
+ GetExecutionContext()->Url(), url_));
}
UseCounter::Count(GetExecutionContext(),
WebFeature::kUpgradeInsecureRequestsUpgradedRequest);
@@ -367,7 +371,7 @@ void DOMWebSocket::Connect(const String& url,
// resuming the queue. If we don't do this, the event is fired synchronously
// with the constructor, meaning that it's impossible to listen for.
event_queue_->Pause();
- event_queue_->Dispatch(Event::Create(EventTypeNames::error));
+ event_queue_->Dispatch(Event::Create(event_type_names::kError));
event_queue_->Unpause();
return;
}
@@ -664,7 +668,7 @@ void DOMWebSocket::setBinaryType(const String& binary_type) {
}
const AtomicString& DOMWebSocket::InterfaceName() const {
- return EventTargetNames::DOMWebSocket;
+ return event_target_names::kWebSocket;
}
ExecutionContext* DOMWebSocket::GetExecutionContext() const {
@@ -709,7 +713,7 @@ void DOMWebSocket::DidConnect(const String& subprotocol,
state_ = kOpen;
subprotocol_ = subprotocol;
extensions_ = extensions;
- event_queue_->Dispatch(Event::Create(EventTypeNames::open));
+ event_queue_->Dispatch(Event::Create(event_type_names::kOpen));
}
void DOMWebSocket::DidReceiveTextMessage(const String& msg) {
@@ -769,7 +773,7 @@ void DOMWebSocket::DidError() {
LogMixedAutoupgradeStatus(MixedContentAutoupgradeStatus::kFailed);
ReflectBufferedAmountConsumption();
state_ = kClosed;
- event_queue_->Dispatch(Event::Create(EventTypeNames::error));
+ event_queue_->Dispatch(Event::Create(event_type_names::kError));
}
void DOMWebSocket::DidConsumeBufferedAmount(uint64_t consumed) {
diff --git a/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.h b/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.h
index 5511d12644a..b9e6bc94dc4 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.h
+++ b/chromium/third_party/blink/renderer/modules/websockets/dom_websocket.h
@@ -79,6 +79,8 @@ class MODULES_EXPORT DOMWebSocket : public EventTargetWithInlineData,
const String& url,
const StringOrStringSequence& protocols,
ExceptionState&);
+
+ explicit DOMWebSocket(ExecutionContext*);
~DOMWebSocket() override;
enum State { kConnecting = 0, kOpen = 1, kClosing = 2, kClosed = 3 };
@@ -111,10 +113,10 @@ class MODULES_EXPORT DOMWebSocket : public EventTargetWithInlineData,
String binaryType() const;
void setBinaryType(const String&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(open);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(open, kOpen);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose);
// EventTarget functions.
const AtomicString& InterfaceName() const override;
@@ -145,16 +147,15 @@ class MODULES_EXPORT DOMWebSocket : public EventTargetWithInlineData,
static bool IsValidSubprotocolString(const String&);
- protected:
- explicit DOMWebSocket(ExecutionContext*);
-
private:
// FIXME: This should inherit blink::EventQueue.
class EventQueue final : public GarbageCollectedFinalized<EventQueue> {
public:
static EventQueue* Create(EventTarget* target) {
- return new EventQueue(target);
+ return MakeGarbageCollected<EventQueue>(target);
}
+
+ explicit EventQueue(EventTarget*);
~EventQueue();
// Dispatches the event if this queue is active.
@@ -180,8 +181,6 @@ class MODULES_EXPORT DOMWebSocket : public EventTargetWithInlineData,
kStopped,
};
- explicit EventQueue(EventTarget*);
-
// Dispatches queued events if this queue is active.
// Does nothing otherwise.
void DispatchQueuedEvents();
diff --git a/chromium/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc b/chromium/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc
index f94cb8d91ea..bf5eff3f8a4 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc
+++ b/chromium/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc
@@ -27,11 +27,10 @@ std::unique_ptr<TracedValue> InspectorWebSocketCreateEvent::Data(
if (auto* document = DynamicTo<Document>(execution_context)) {
value->SetString("frame",
IdentifiersFactory::FrameId(document->GetFrame()));
- } else if (execution_context->IsWorkerGlobalScope()) {
- value->SetString("workerId", IdentifiersFactory::IdFromToken(
- ToWorkerGlobalScope(execution_context)
- ->GetThread()
- ->GetDevToolsWorkerToken()));
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) {
+ value->SetString("workerId",
+ IdentifiersFactory::IdFromToken(
+ scope->GetThread()->GetDevToolsWorkerToken()));
} else {
NOTREACHED()
<< "WebSocket is available only in Document and WorkerGlobalScope";
@@ -51,11 +50,10 @@ std::unique_ptr<TracedValue> InspectorWebSocketEvent::Data(
if (auto* document = DynamicTo<Document>(execution_context)) {
value->SetString("frame",
IdentifiersFactory::FrameId(document->GetFrame()));
- } else if (execution_context->IsWorkerGlobalScope()) {
- value->SetString("workerId", IdentifiersFactory::IdFromToken(
- ToWorkerGlobalScope(execution_context)
- ->GetThread()
- ->GetDevToolsWorkerToken()));
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) {
+ value->SetString("workerId",
+ IdentifiersFactory::IdFromToken(
+ scope->GetThread()->GetDevToolsWorkerToken()));
} else {
NOTREACHED()
<< "WebSocket is available only in Document and WorkerGlobalScope";
diff --git a/chromium/third_party/blink/renderer/modules/websockets/web_pepper_socket_channel_client_proxy.h b/chromium/third_party/blink/renderer/modules/websockets/web_pepper_socket_channel_client_proxy.h
index 95bf5af572f..46dc16de433 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/web_pepper_socket_channel_client_proxy.h
+++ b/chromium/third_party/blink/renderer/modules/websockets/web_pepper_socket_channel_client_proxy.h
@@ -26,9 +26,12 @@ class WebPepperSocketChannelClientProxy final
USING_GARBAGE_COLLECTED_MIXIN(WebPepperSocketChannelClientProxy)
public:
static WebPepperSocketChannelClientProxy* Create(WebPepperSocketImpl* impl) {
- return new WebPepperSocketChannelClientProxy(impl);
+ return MakeGarbageCollected<WebPepperSocketChannelClientProxy>(impl);
}
+ explicit WebPepperSocketChannelClientProxy(WebPepperSocketImpl* impl)
+ : impl_(impl) {}
+
void DidConnect(const String& subprotocol,
const String& extensions) override {
impl_->DidConnect(subprotocol, extensions);
@@ -59,9 +62,6 @@ class WebPepperSocketChannelClientProxy final
}
private:
- explicit WebPepperSocketChannelClientProxy(WebPepperSocketImpl* impl)
- : impl_(impl) {}
-
WebPepperSocketImpl* impl_;
};
diff --git a/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc b/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc
index f08c1c4b9fe..16f5c53bf85 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc
@@ -41,6 +41,7 @@
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/websocket_handshake_throttle.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -88,7 +89,7 @@ class WebSocketChannelImpl::BlobLoader final
void DidStartLoading() override {}
void DidReceiveData() override {}
void DidFinishLoading() override;
- void DidFail(FileError::ErrorCode) override;
+ void DidFail(FileErrorCode) override;
void Trace(blink::Visitor* visitor) { visitor->Trace(channel_); }
@@ -139,8 +140,7 @@ void WebSocketChannelImpl::BlobLoader::DidFinishLoading() {
loader_ = nullptr;
}
-void WebSocketChannelImpl::BlobLoader::DidFail(
- FileError::ErrorCode error_code) {
+void WebSocketChannelImpl::BlobLoader::DidFail(FileErrorCode error_code) {
channel_->DidFailLoadingBlob(error_code);
loader_ = nullptr;
}
@@ -160,7 +160,7 @@ WebSocketChannelImpl* WebSocketChannelImpl::CreateForTesting(
std::unique_ptr<SourceLocation> location,
WebSocketHandle* handle,
std::unique_ptr<WebSocketHandshakeThrottle> handshake_throttle) {
- auto* channel = new WebSocketChannelImpl(
+ auto* channel = MakeGarbageCollected<WebSocketChannelImpl>(
document, client, std::move(location), base::WrapUnique(handle));
channel->handshake_throttle_ = std::move(handshake_throttle);
return channel;
@@ -171,9 +171,9 @@ WebSocketChannelImpl* WebSocketChannelImpl::Create(
ExecutionContext* execution_context,
WebSocketChannelClient* client,
std::unique_ptr<SourceLocation> location) {
- auto* channel =
- new WebSocketChannelImpl(execution_context, client, std::move(location),
- std::make_unique<WebSocketHandleImpl>());
+ auto* channel = MakeGarbageCollected<WebSocketChannelImpl>(
+ execution_context, client, std::move(location),
+ std::make_unique<WebSocketHandleImpl>());
channel->handshake_throttle_ =
channel->GetBaseFetchContext()->CreateWebSocketHandshakeThrottle();
return channel;
@@ -193,8 +193,8 @@ WebSocketChannelImpl::WebSocketChannelImpl(
sent_size_of_top_message_(0),
location_at_construction_(std::move(location)),
throttle_passed_(false) {
- if (execution_context_->IsWorkerGlobalScope())
- ToWorkerGlobalScope(execution_context_)->EnsureFetcher();
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_))
+ scope->EnsureFetcher();
}
WebSocketChannelImpl::~WebSocketChannelImpl() {
@@ -283,7 +283,7 @@ void WebSocketChannelImpl::Send(const CString& message) {
probe::didSendWebSocketFrame(execution_context_, identifier_,
WebSocketOpCode::kOpCodeText, true,
message.data(), message.length());
- messages_.push_back(new Message(message));
+ messages_.push_back(MakeGarbageCollected<Message>(message));
ProcessSendQueue();
}
@@ -300,7 +300,8 @@ void WebSocketChannelImpl::Send(
// affect actual behavior.
probe::didSendWebSocketFrame(execution_context_, identifier_,
WebSocketOpCode::kOpCodeBinary, true, "", 0);
- messages_.push_back(new Message(std::move(blob_data_handle)));
+ messages_.push_back(
+ MakeGarbageCollected<Message>(std::move(blob_data_handle)));
ProcessSendQueue();
}
@@ -318,8 +319,8 @@ void WebSocketChannelImpl::Send(const DOMArrayBuffer& buffer,
// buffer.slice copies its contents.
// FIXME: Reduce copy by sending the data immediately when we don't need to
// queue the data.
- messages_.push_back(
- new Message(buffer.Slice(byte_offset, byte_offset + byte_length)));
+ messages_.push_back(MakeGarbageCollected<Message>(
+ buffer.Slice(byte_offset, byte_offset + byte_length)));
ProcessSendQueue();
}
@@ -333,8 +334,8 @@ void WebSocketChannelImpl::SendTextAsCharVector(
probe::didSendWebSocketFrame(execution_context_, identifier_,
WebSocketOpCode::kOpCodeText, true, data->data(),
data->size());
- messages_.push_back(
- new Message(std::move(data), kMessageTypeTextAsCharVector));
+ messages_.push_back(MakeGarbageCollected<Message>(
+ std::move(data), kMessageTypeTextAsCharVector));
ProcessSendQueue();
}
@@ -348,8 +349,8 @@ void WebSocketChannelImpl::SendBinaryAsCharVector(
probe::didSendWebSocketFrame(execution_context_, identifier_,
WebSocketOpCode::kOpCodeBinary, true,
data->data(), data->size());
- messages_.push_back(
- new Message(std::move(data), kMessageTypeBinaryAsCharVector));
+ messages_.push_back(MakeGarbageCollected<Message>(
+ std::move(data), kMessageTypeBinaryAsCharVector));
ProcessSendQueue();
}
@@ -358,7 +359,7 @@ void WebSocketChannelImpl::Close(int code, const String& reason) {
DCHECK(handle_);
unsigned short code_to_send = static_cast<unsigned short>(
code == kCloseEventCodeNotSpecified ? kCloseEventCodeNoStatusRcvd : code);
- messages_.push_back(new Message(code_to_send, reason));
+ messages_.push_back(MakeGarbageCollected<Message>(code_to_send, reason));
ProcessSendQueue();
}
@@ -472,7 +473,8 @@ void WebSocketChannelImpl::ProcessSendQueue() {
CHECK(!blob_loader_);
CHECK(message);
CHECK(message->blob_data_handle);
- blob_loader_ = new BlobLoader(message->blob_data_handle, this);
+ blob_loader_ =
+ MakeGarbageCollected<BlobLoader>(message->blob_data_handle, this);
break;
case kMessageTypeArrayBuffer:
CHECK(message->array_buffer);
@@ -762,19 +764,19 @@ void WebSocketChannelImpl::DidFinishLoadingBlob(DOMArrayBuffer* buffer) {
DCHECK_GT(messages_.size(), 0u);
DCHECK_EQ(messages_.front()->type, kMessageTypeBlob);
// We replace it with the loaded blob.
- messages_.front() = new Message(buffer);
+ messages_.front() = MakeGarbageCollected<Message>(buffer);
ProcessSendQueue();
}
-void WebSocketChannelImpl::DidFailLoadingBlob(FileError::ErrorCode error_code) {
+void WebSocketChannelImpl::DidFailLoadingBlob(FileErrorCode error_code) {
blob_loader_.Clear();
- if (error_code == FileError::kAbortErr) {
+ if (error_code == FileErrorCode::kAbortErr) {
// The error is caused by cancel().
return;
}
// FIXME: Generate human-friendly reason message.
FailAsError("Failed to load Blob: error code = " +
- String::Number(error_code));
+ String::Number(static_cast<unsigned>(error_code)));
}
void WebSocketChannelImpl::TearDownFailedConnection() {
diff --git a/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h b/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h
index 121dca5eccc..88c0702e7e4 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h
+++ b/chromium/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h
@@ -39,7 +39,6 @@
#include "third_party/blink/public/platform/web_callbacks.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
-#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/websockets/websocket_channel.h"
#include "third_party/blink/renderer/modules/websockets/websocket_handle.h"
@@ -56,6 +55,7 @@
namespace blink {
class BaseFetchContext;
+enum class FileErrorCode;
class WebSocketChannelClient;
class WebSocketHandshakeThrottle;
@@ -81,6 +81,10 @@ class MODULES_EXPORT WebSocketChannelImpl final
WebSocketHandle*,
std::unique_ptr<WebSocketHandshakeThrottle>);
+ WebSocketChannelImpl(ExecutionContext*,
+ WebSocketChannelClient*,
+ std::unique_ptr<SourceLocation>,
+ std::unique_ptr<WebSocketHandle>);
~WebSocketChannelImpl() override;
// Allows the caller to provide the Mojo pipe through which the socket is
@@ -127,11 +131,6 @@ class MODULES_EXPORT WebSocketChannelImpl final
Vector<char> data;
};
- WebSocketChannelImpl(ExecutionContext*,
- WebSocketChannelClient*,
- std::unique_ptr<SourceLocation>,
- std::unique_ptr<WebSocketHandle>);
-
void SendInternal(WebSocketHandle::MessageType,
const char* data,
wtf_size_t total_size,
@@ -177,7 +176,7 @@ class MODULES_EXPORT WebSocketChannelImpl final
// Methods for BlobLoader.
void DidFinishLoadingBlob(DOMArrayBuffer*);
- void DidFailLoadingBlob(FileError::ErrorCode);
+ void DidFailLoadingBlob(FileErrorCode);
void TearDownFailedConnection();
bool ShouldDisallowConnection(const KURL&);
diff --git a/chromium/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc b/chromium/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc
index 2d052f9b2d3..981a4fed359 100644
--- a/chromium/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc
+++ b/chromium/third_party/blink/renderer/modules/websockets/websocket_handle_impl.cc
@@ -56,7 +56,7 @@ void WebSocketHandleImpl::Connect(network::mojom::blink::WebSocketPtr websocket,
Vector<network::mojom::blink::HttpHeaderPtr> additional_headers;
if (!user_agent_override.IsNull()) {
additional_headers.push_back(network::mojom::blink::HttpHeader::New(
- HTTPNames::User_Agent, user_agent_override));
+ http_names::kUserAgent, user_agent_override));
}
client_binding_.Bind(mojo::MakeRequest(&client_proxy, task_runner));
websocket_->AddChannelRequest(url, protocols, site_for_cookies,
diff --git a/chromium/third_party/blink/renderer/modules/webusb/OWNERS b/chromium/third_party/blink/renderer/modules/webusb/OWNERS
index 3525a5f5546..2caff2fa3a8 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/OWNERS
+++ b/chromium/third_party/blink/renderer/modules/webusb/OWNERS
@@ -1,4 +1,4 @@
reillyg@chromium.org
-rockot@chromium.org
+rockot@google.com
# COMPONENT: Blink>USB \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/modules/webusb/README.md b/chromium/third_party/blink/renderer/modules/webusb/README.md
index 19f3c4161d7..defb91149b7 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/README.md
+++ b/chromium/third_party/blink/renderer/modules/webusb/README.md
@@ -13,5 +13,5 @@ for the [WebUSB specification]. It communicates with the browser process through
WebUSB is primarily tested in [Web Platform Tests].
Chromium implementation details are tested in [Layout Tests].
-[Web Platform Tests]: ../../../LayoutTests/external/wpt/webusb/
-[Layout Tests]: ../../../LayoutTests/usb/
+[Web Platform Tests]: ../../../web_tests/external/wpt/webusb/
+[Layout Tests]: ../../../web_tests/usb/
diff --git a/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.cc b/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.cc
index 31c3f8465ae..c341a7e3c73 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.cc
@@ -15,7 +15,7 @@ NavigatorUSB& NavigatorUSB::From(Navigator& navigator) {
NavigatorUSB* supplement =
Supplement<Navigator>::From<NavigatorUSB>(navigator);
if (!supplement) {
- supplement = new NavigatorUSB(navigator);
+ supplement = MakeGarbageCollected<NavigatorUSB>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.h b/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.h
index cd833558a87..6da05edd311 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/navigator_usb.h
@@ -28,11 +28,11 @@ class NavigatorUSB final : public GarbageCollected<NavigatorUSB>,
static USB* usb(Navigator&);
USB* usb();
+ explicit NavigatorUSB(Navigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit NavigatorUSB(Navigator&);
-
Member<USB> usb_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb.cc b/chromium/third_party/blink/renderer/modules/webusb/usb.cc
index 5da4060b792..d41521b2556 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb.cc
@@ -41,13 +41,13 @@ void RejectWithTypeError(const String& error_details,
resolver->Reject(V8ThrowException::CreateTypeError(isolate, error_details));
}
-UsbDeviceFilterPtr ConvertDeviceFilter(const USBDeviceFilter& filter,
+UsbDeviceFilterPtr ConvertDeviceFilter(const USBDeviceFilter* filter,
ScriptPromiseResolver* resolver) {
auto mojo_filter = device::mojom::blink::UsbDeviceFilter::New();
- mojo_filter->has_vendor_id = filter.hasVendorId();
+ mojo_filter->has_vendor_id = filter->hasVendorId();
if (mojo_filter->has_vendor_id)
- mojo_filter->vendor_id = filter.vendorId();
- mojo_filter->has_product_id = filter.hasProductId();
+ mojo_filter->vendor_id = filter->vendorId();
+ mojo_filter->has_product_id = filter->hasProductId();
if (mojo_filter->has_product_id) {
if (!mojo_filter->has_vendor_id) {
RejectWithTypeError(
@@ -55,12 +55,12 @@ UsbDeviceFilterPtr ConvertDeviceFilter(const USBDeviceFilter& filter,
resolver);
return nullptr;
}
- mojo_filter->product_id = filter.productId();
+ mojo_filter->product_id = filter->productId();
}
- mojo_filter->has_class_code = filter.hasClassCode();
+ mojo_filter->has_class_code = filter->hasClassCode();
if (mojo_filter->has_class_code)
- mojo_filter->class_code = filter.classCode();
- mojo_filter->has_subclass_code = filter.hasSubclassCode();
+ mojo_filter->class_code = filter->classCode();
+ mojo_filter->has_subclass_code = filter->hasSubclassCode();
if (mojo_filter->has_subclass_code) {
if (!mojo_filter->has_class_code) {
RejectWithTypeError(
@@ -68,9 +68,9 @@ UsbDeviceFilterPtr ConvertDeviceFilter(const USBDeviceFilter& filter,
resolver);
return nullptr;
}
- mojo_filter->subclass_code = filter.subclassCode();
+ mojo_filter->subclass_code = filter->subclassCode();
}
- mojo_filter->has_protocol_code = filter.hasProtocolCode();
+ mojo_filter->has_protocol_code = filter->hasProtocolCode();
if (mojo_filter->has_protocol_code) {
if (!mojo_filter->has_subclass_code) {
RejectWithTypeError(
@@ -79,10 +79,10 @@ UsbDeviceFilterPtr ConvertDeviceFilter(const USBDeviceFilter& filter,
resolver);
return nullptr;
}
- mojo_filter->protocol_code = filter.protocolCode();
+ mojo_filter->protocol_code = filter->protocolCode();
}
- if (filter.hasSerialNumber())
- mojo_filter->serial_number = filter.serialNumber();
+ if (filter->hasSerialNumber())
+ mojo_filter->serial_number = filter->serialNumber();
return mojo_filter;
}
@@ -110,11 +110,19 @@ ScriptPromise USB::getDevices(ScriptState* script_state) {
script_state,
DOMException::Create(DOMExceptionCode::kNotSupportedError));
}
- if (!IsFeatureEnabled()) {
+
+ FeatureEnabledState state = GetFeatureEnabledState();
+ if (state != FeatureEnabledState::kEnabled) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
if (auto* document = DynamicTo<Document>(execution_context)) {
- document->ReportFeaturePolicyViolation(mojom::FeaturePolicyFeature::kUsb);
+ document->ReportFeaturePolicyViolation(
+ mojom::FeaturePolicyFeature::kUsb,
+ (state == FeatureEnabledState::kReportOnly
+ ? mojom::FeaturePolicyDisposition::kReport
+ : mojom::FeaturePolicyDisposition::kEnforce));
}
+ }
+ if (state == FeatureEnabledState::kDisabled) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kSecurityError,
kFeaturePolicyBlocked));
@@ -129,7 +137,7 @@ ScriptPromise USB::getDevices(ScriptState* script_state) {
}
ScriptPromise USB::requestDevice(ScriptState* script_state,
- const USBDeviceRequestOptions& options) {
+ const USBDeviceRequestOptions* options) {
LocalFrame* frame = GetFrame();
if (!frame || !frame->GetDocument()) {
return ScriptPromise::RejectWithDOMException(
@@ -157,9 +165,9 @@ ScriptPromise USB::requestDevice(ScriptState* script_state,
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
Vector<UsbDeviceFilterPtr> filters;
- if (options.hasFilters()) {
- filters.ReserveCapacity(options.filters().size());
- for (const auto& filter : options.filters()) {
+ if (options->hasFilters()) {
+ filters.ReserveCapacity(options->filters().size());
+ for (const auto& filter : options->filters()) {
UsbDeviceFilterPtr converted_filter =
ConvertDeviceFilter(filter, resolver);
if (!converted_filter)
@@ -168,7 +176,7 @@ ScriptPromise USB::requestDevice(ScriptState* script_state,
}
}
- DCHECK(options.filters().size() == filters.size());
+ DCHECK(options->filters().size() == filters.size());
get_permission_requests_.insert(resolver);
service_->GetPermission(std::move(filters),
WTF::Bind(&USB::OnGetPermission, WrapPersistent(this),
@@ -181,7 +189,7 @@ ExecutionContext* USB::GetExecutionContext() const {
}
const AtomicString& USB::InterfaceName() const {
- return EventTargetNames::USB;
+ return event_target_names::kUSB;
}
void USB::ContextDestroyed(ExecutionContext*) {
@@ -234,7 +242,7 @@ void USB::OnDeviceAdded(UsbDeviceInfoPtr device_info) {
return;
DispatchEvent(*USBConnectionEvent::Create(
- EventTypeNames::connect, GetOrCreateDevice(std::move(device_info))));
+ event_type_names::kConnect, GetOrCreateDevice(std::move(device_info))));
}
void USB::OnDeviceRemoved(UsbDeviceInfoPtr device_info) {
@@ -245,7 +253,7 @@ void USB::OnDeviceRemoved(UsbDeviceInfoPtr device_info) {
GetExecutionContext());
}
DispatchEvent(
- *USBConnectionEvent::Create(EventTypeNames::disconnect, device));
+ *USBConnectionEvent::Create(event_type_names::kDisconnect, device));
device_cache_.erase(guid);
}
@@ -266,12 +274,13 @@ void USB::OnServiceConnectionError() {
void USB::AddedEventListener(const AtomicString& event_type,
RegisteredEventListener& listener) {
EventTargetWithInlineData::AddedEventListener(event_type, listener);
- if (event_type != EventTypeNames::connect &&
- event_type != EventTypeNames::disconnect) {
+ if (event_type != event_type_names::kConnect &&
+ event_type != event_type_names::kDisconnect) {
return;
}
- if (!IsContextSupported() || !IsFeatureEnabled())
+ if (!IsContextSupported() ||
+ GetFeatureEnabledState() == FeatureEnabledState::kDisabled)
return;
EnsureServiceConnection();
@@ -282,7 +291,7 @@ void USB::EnsureServiceConnection() {
return;
DCHECK(IsContextSupported());
- DCHECK(IsFeatureEnabled());
+ DCHECK(GetFeatureEnabledState() != FeatureEnabledState::kDisabled);
GetExecutionContext()->GetInterfaceProvider()->GetInterface(
mojo::MakeRequest(&service_));
service_.set_connection_error_handler(
@@ -311,8 +320,8 @@ bool USB::IsContextSupported() const {
return true;
}
-bool USB::IsFeatureEnabled() const {
- return GetExecutionContext()->GetSecurityContext().IsFeatureEnabled(
+FeatureEnabledState USB::GetFeatureEnabledState() const {
+ return GetExecutionContext()->GetSecurityContext().GetFeatureEnabledState(
mojom::FeaturePolicyFeature::kUsb);
}
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb.h b/chromium/third_party/blink/renderer/modules/webusb/usb.h
index 768227ec3bd..78e713b4f7b 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb.h
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/execution_context/security_context.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -30,17 +31,20 @@ class USB final : public EventTargetWithInlineData,
USING_PRE_FINALIZER(USB, Dispose);
public:
- static USB* Create(ExecutionContext& context) { return new USB(context); }
+ static USB* Create(ExecutionContext& context) {
+ return MakeGarbageCollected<USB>(context);
+ }
+ explicit USB(ExecutionContext&);
~USB() override;
void Dispose();
// USB.idl
ScriptPromise getDevices(ScriptState*);
- ScriptPromise requestDevice(ScriptState*, const USBDeviceRequestOptions&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect);
+ ScriptPromise requestDevice(ScriptState*, const USBDeviceRequestOptions*);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(disconnect, kDisconnect);
// EventTarget overrides.
ExecutionContext* GetExecutionContext() const override;
@@ -74,12 +78,10 @@ class USB final : public EventTargetWithInlineData,
RegisteredEventListener&) override;
private:
- explicit USB(ExecutionContext&);
-
void EnsureServiceConnection();
bool IsContextSupported() const;
- bool IsFeatureEnabled() const;
+ FeatureEnabledState GetFeatureEnabledState() const;
mojom::blink::WebUsbServicePtr service_;
HeapHashSet<Member<ScriptPromiseResolver>> get_devices_requests_;
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc b/chromium/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc
index fb2799d19b7..0c431218285 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_alternate_interface.cc
@@ -13,7 +13,8 @@ namespace blink {
USBAlternateInterface* USBAlternateInterface::Create(
const USBInterface* interface,
wtf_size_t alternate_index) {
- return new USBAlternateInterface(interface, alternate_index);
+ return MakeGarbageCollected<USBAlternateInterface>(interface,
+ alternate_index);
}
USBAlternateInterface* USBAlternateInterface::Create(
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_configuration.cc b/chromium/third_party/blink/renderer/modules/webusb/usb_configuration.cc
index cc21bf0ffd5..56b0d636f9c 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_configuration.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_configuration.cc
@@ -13,7 +13,7 @@ namespace blink {
USBConfiguration* USBConfiguration::Create(const USBDevice* device,
wtf_size_t configuration_index) {
- return new USBConfiguration(device, configuration_index);
+ return MakeGarbageCollected<USBConfiguration>(device, configuration_index);
}
USBConfiguration* USBConfiguration::Create(const USBDevice* device,
@@ -22,7 +22,7 @@ USBConfiguration* USBConfiguration::Create(const USBDevice* device,
const auto& configurations = device->Info().configurations;
for (wtf_size_t i = 0; i < configurations.size(); ++i) {
if (configurations[i]->configuration_value == configuration_value)
- return new USBConfiguration(device, i);
+ return MakeGarbageCollected<USBConfiguration>(device, i);
}
exception_state.ThrowRangeError("Invalid configuration value.");
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.cc b/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.cc
index e2989755a23..898ed01fbea 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.cc
@@ -11,19 +11,19 @@ namespace blink {
USBConnectionEvent* USBConnectionEvent::Create(
const AtomicString& type,
- const USBConnectionEventInit& initializer) {
- return new USBConnectionEvent(type, initializer);
+ const USBConnectionEventInit* initializer) {
+ return MakeGarbageCollected<USBConnectionEvent>(type, initializer);
}
USBConnectionEvent* USBConnectionEvent::Create(const AtomicString& type,
USBDevice* device) {
- return new USBConnectionEvent(type, device);
+ return MakeGarbageCollected<USBConnectionEvent>(type, device);
}
USBConnectionEvent::USBConnectionEvent(
const AtomicString& type,
- const USBConnectionEventInit& initializer)
- : Event(type, initializer), device_(initializer.device()) {}
+ const USBConnectionEventInit* initializer)
+ : Event(type, initializer), device_(initializer->device()) {}
USBConnectionEvent::USBConnectionEvent(const AtomicString& type,
USBDevice* device)
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.h b/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.h
index 868353a0d72..96e0b092500 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_connection_event.h
@@ -18,10 +18,10 @@ class USBConnectionEvent final : public Event {
public:
static USBConnectionEvent* Create(const AtomicString& type,
- const USBConnectionEventInit&);
+ const USBConnectionEventInit*);
static USBConnectionEvent* Create(const AtomicString& type, USBDevice*);
- USBConnectionEvent(const AtomicString& type, const USBConnectionEventInit&);
+ USBConnectionEvent(const AtomicString& type, const USBConnectionEventInit*);
USBConnectionEvent(const AtomicString& type, USBDevice*);
USBDevice* device() const { return device_; }
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_device.cc b/chromium/third_party/blink/renderer/modules/webusb/usb_device.cc
index d46935c3fd0..091e727dd0c 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_device.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_device.cc
@@ -325,7 +325,7 @@ ScriptPromise USBDevice::selectAlternateInterface(ScriptState* script_state,
ScriptPromise USBDevice::controlTransferIn(
ScriptState* script_state,
- const USBControlTransferParameters& setup,
+ const USBControlTransferParameters* setup,
unsigned length) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -344,7 +344,7 @@ ScriptPromise USBDevice::controlTransferIn(
ScriptPromise USBDevice::controlTransferOut(
ScriptState* script_state,
- const USBControlTransferParameters& setup) {
+ const USBControlTransferParameters* setup) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (EnsureDeviceConfigured(resolver)) {
@@ -362,7 +362,7 @@ ScriptPromise USBDevice::controlTransferOut(
ScriptPromise USBDevice::controlTransferOut(
ScriptState* script_state,
- const USBControlTransferParameters& setup,
+ const USBControlTransferParameters* setup,
const ArrayBufferOrArrayBufferView& data) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
@@ -644,15 +644,15 @@ bool USBDevice::AnyInterfaceChangeInProgress() const {
}
UsbControlTransferParamsPtr USBDevice::ConvertControlTransferParameters(
- const USBControlTransferParameters& parameters,
+ const USBControlTransferParameters* parameters,
ScriptPromiseResolver* resolver) const {
auto mojo_parameters = device::mojom::blink::UsbControlTransferParams::New();
- if (parameters.requestType() == "standard") {
+ if (parameters->requestType() == "standard") {
mojo_parameters->type = UsbControlTransferType::STANDARD;
- } else if (parameters.requestType() == "class") {
+ } else if (parameters->requestType() == "class") {
mojo_parameters->type = UsbControlTransferType::CLASS;
- } else if (parameters.requestType() == "vendor") {
+ } else if (parameters->requestType() == "vendor") {
mojo_parameters->type = UsbControlTransferType::VENDOR;
} else {
resolver->Reject(DOMException::Create(
@@ -661,20 +661,20 @@ UsbControlTransferParamsPtr USBDevice::ConvertControlTransferParameters(
return nullptr;
}
- if (parameters.recipient() == "device") {
+ if (parameters->recipient() == "device") {
mojo_parameters->recipient = UsbControlTransferRecipient::DEVICE;
- } else if (parameters.recipient() == "interface") {
- uint8_t interface_number = parameters.index() & 0xff;
+ } else if (parameters->recipient() == "interface") {
+ uint8_t interface_number = parameters->index() & 0xff;
if (!EnsureInterfaceClaimed(interface_number, resolver))
return nullptr;
mojo_parameters->recipient = UsbControlTransferRecipient::INTERFACE;
- } else if (parameters.recipient() == "endpoint") {
- bool in_transfer = parameters.index() & 0x80;
- uint8_t endpoint_number = parameters.index() & 0x0f;
+ } else if (parameters->recipient() == "endpoint") {
+ bool in_transfer = parameters->index() & 0x80;
+ uint8_t endpoint_number = parameters->index() & 0x0f;
if (!EnsureEndpointAvailable(in_transfer, endpoint_number, resolver))
return nullptr;
mojo_parameters->recipient = UsbControlTransferRecipient::ENDPOINT;
- } else if (parameters.recipient() == "other") {
+ } else if (parameters->recipient() == "other") {
mojo_parameters->recipient = UsbControlTransferRecipient::OTHER;
} else {
resolver->Reject(DOMException::Create(
@@ -683,9 +683,9 @@ UsbControlTransferParamsPtr USBDevice::ConvertControlTransferParameters(
return nullptr;
}
- mojo_parameters->request = parameters.request();
- mojo_parameters->value = parameters.value();
- mojo_parameters->index = parameters.index();
+ mojo_parameters->request = parameters->request();
+ mojo_parameters->value = parameters->value();
+ mojo_parameters->index = parameters->index();
return mojo_parameters;
}
@@ -926,7 +926,7 @@ void USBDevice::AsyncIsochronousTransferIn(
DOMArrayBuffer* buffer = DOMArrayBuffer::Create(data.data(), data.size());
HeapVector<Member<USBIsochronousInTransferPacket>> packets;
packets.ReserveCapacity(mojo_packets.size());
- size_t byte_offset = 0;
+ uint32_t byte_offset = 0;
for (const auto& packet : mojo_packets) {
DOMException* error = ConvertFatalTransferStatus(packet->status);
if (error) {
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_device.h b/chromium/third_party/blink/renderer/modules/webusb/usb_device.h
index c106b4b8b86..2515f9f1292 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_device.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_device.h
@@ -29,7 +29,8 @@ class USBDevice : public ScriptWrappable, public ContextLifecycleObserver {
static USBDevice* Create(device::mojom::blink::UsbDeviceInfoPtr device_info,
device::mojom::blink::UsbDevicePtr device,
ExecutionContext* context) {
- return new USBDevice(std::move(device_info), std::move(device), context);
+ return MakeGarbageCollected<USBDevice>(std::move(device_info),
+ std::move(device), context);
}
explicit USBDevice(device::mojom::blink::UsbDeviceInfoPtr,
@@ -74,12 +75,12 @@ class USBDevice : public ScriptWrappable, public ContextLifecycleObserver {
uint8_t interface_number,
uint8_t alternate_setting);
ScriptPromise controlTransferIn(ScriptState*,
- const USBControlTransferParameters& setup,
+ const USBControlTransferParameters* setup,
unsigned length);
ScriptPromise controlTransferOut(ScriptState*,
- const USBControlTransferParameters& setup);
+ const USBControlTransferParameters* setup);
ScriptPromise controlTransferOut(ScriptState*,
- const USBControlTransferParameters& setup,
+ const USBControlTransferParameters* setup,
const ArrayBufferOrArrayBufferView& data);
ScriptPromise clearHalt(ScriptState*,
String direction,
@@ -119,7 +120,7 @@ class USBDevice : public ScriptWrappable, public ContextLifecycleObserver {
ScriptPromiseResolver*) const;
bool AnyInterfaceChangeInProgress() const;
device::mojom::blink::UsbControlTransferParamsPtr
- ConvertControlTransferParameters(const USBControlTransferParameters&,
+ ConvertControlTransferParameters(const USBControlTransferParameters*,
ScriptPromiseResolver*) const;
void SetEndpointsForInterface(wtf_size_t interface_index, bool set);
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_endpoint.cc b/chromium/third_party/blink/renderer/modules/webusb/usb_endpoint.cc
index 5a0043c1734..3533a944d2a 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_endpoint.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_endpoint.cc
@@ -46,7 +46,7 @@ String ConvertTypeToEnum(const UsbTransferType& type) {
USBEndpoint* USBEndpoint::Create(const USBAlternateInterface* alternate,
wtf_size_t endpoint_index) {
- return new USBEndpoint(alternate, endpoint_index);
+ return MakeGarbageCollected<USBEndpoint>(alternate, endpoint_index);
}
USBEndpoint* USBEndpoint::Create(const USBAlternateInterface* alternate,
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_in_transfer_result.h b/chromium/third_party/blink/renderer/modules/webusb/usb_in_transfer_result.h
index 8d9f7045afd..1f1e43d508d 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_in_transfer_result.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_in_transfer_result.h
@@ -22,15 +22,15 @@ class USBInTransferResult final : public ScriptWrappable {
const Vector<uint8_t>& data) {
DOMDataView* data_view = DOMDataView::Create(
DOMArrayBuffer::Create(data.data(), data.size()), 0, data.size());
- return new USBInTransferResult(status, data_view);
+ return MakeGarbageCollected<USBInTransferResult>(status, data_view);
}
static USBInTransferResult* Create(const String& status) {
- return new USBInTransferResult(status, nullptr);
+ return MakeGarbageCollected<USBInTransferResult>(status, nullptr);
}
static USBInTransferResult* Create(const String& status, DOMDataView* data) {
- return new USBInTransferResult(status, data);
+ return MakeGarbageCollected<USBInTransferResult>(status, data);
}
USBInTransferResult(const String& status, DOMDataView* data)
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_interface.cc b/chromium/third_party/blink/renderer/modules/webusb/usb_interface.cc
index 4193de72179..ff0ee424759 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_interface.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_interface.cc
@@ -14,8 +14,8 @@ namespace blink {
USBInterface* USBInterface::Create(const USBConfiguration* configuration,
wtf_size_t interface_index) {
- return new USBInterface(configuration->Device(), configuration->Index(),
- interface_index);
+ return MakeGarbageCollected<USBInterface>(
+ configuration->Device(), configuration->Index(), interface_index);
}
USBInterface* USBInterface::Create(const USBConfiguration* configuration,
@@ -23,9 +23,10 @@ USBInterface* USBInterface::Create(const USBConfiguration* configuration,
ExceptionState& exception_state) {
const auto& interfaces = configuration->Info().interfaces;
for (wtf_size_t i = 0; i < interfaces.size(); ++i) {
- if (interfaces[i]->interface_number == interface_number)
- return new USBInterface(configuration->Device(), configuration->Index(),
- i);
+ if (interfaces[i]->interface_number == interface_number) {
+ return MakeGarbageCollected<USBInterface>(configuration->Device(),
+ configuration->Index(), i);
+ }
}
exception_state.ThrowRangeError("Invalid interface index.");
return nullptr;
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_packet.h b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_packet.h
index 9cbdc1fc3cd..b0b06313aaa 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_packet.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_packet.h
@@ -17,14 +17,17 @@ class USBIsochronousInTransferPacket final : public ScriptWrappable {
public:
static USBIsochronousInTransferPacket* Create(const String& status) {
- return new USBIsochronousInTransferPacket(status, nullptr);
+ return MakeGarbageCollected<USBIsochronousInTransferPacket>(status,
+ nullptr);
}
static USBIsochronousInTransferPacket* Create(const String& status,
DOMDataView* data) {
- return new USBIsochronousInTransferPacket(status, data);
+ return MakeGarbageCollected<USBIsochronousInTransferPacket>(status, data);
}
+ USBIsochronousInTransferPacket(const String& status, DOMDataView* data)
+ : status_(status), data_(data) {}
~USBIsochronousInTransferPacket() override = default;
String status() const { return status_; }
@@ -36,9 +39,6 @@ class USBIsochronousInTransferPacket final : public ScriptWrappable {
}
private:
- USBIsochronousInTransferPacket(const String& status, DOMDataView* data)
- : status_(status), data_(data) {}
-
const String status_;
const Member<DOMDataView> data_;
};
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_result.h b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_result.h
index 3a53e131965..36c379e40ba 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_result.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_in_transfer_result.h
@@ -22,18 +22,20 @@ class USBIsochronousInTransferResult final : public ScriptWrappable {
DOMArrayBuffer* data,
const HeapVector<Member<USBIsochronousInTransferPacket>>& packets) {
DOMDataView* data_view = DOMDataView::Create(data, 0, data->ByteLength());
- return new USBIsochronousInTransferResult(data_view, packets);
+ return MakeGarbageCollected<USBIsochronousInTransferResult>(data_view,
+ packets);
}
static USBIsochronousInTransferResult* Create(
const HeapVector<Member<USBIsochronousInTransferPacket>>& packets,
DOMDataView* data) {
- return new USBIsochronousInTransferResult(data, packets);
+ return MakeGarbageCollected<USBIsochronousInTransferResult>(data, packets);
}
static USBIsochronousInTransferResult* Create(
const HeapVector<Member<USBIsochronousInTransferPacket>>& packets) {
- return new USBIsochronousInTransferResult(nullptr, packets);
+ return MakeGarbageCollected<USBIsochronousInTransferResult>(nullptr,
+ packets);
}
USBIsochronousInTransferResult(
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_packet.h b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_packet.h
index c1c3c2054c4..f1af0f52f10 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_packet.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_packet.h
@@ -16,12 +16,13 @@ class USBIsochronousOutTransferPacket final : public ScriptWrappable {
public:
static USBIsochronousOutTransferPacket* Create(const String& status) {
- return new USBIsochronousOutTransferPacket(status, 0);
+ return MakeGarbageCollected<USBIsochronousOutTransferPacket>(status, 0);
}
static USBIsochronousOutTransferPacket* Create(const String& status,
unsigned bytes_written) {
- return new USBIsochronousOutTransferPacket(status, bytes_written);
+ return MakeGarbageCollected<USBIsochronousOutTransferPacket>(status,
+ bytes_written);
}
USBIsochronousOutTransferPacket(const String& status, unsigned bytes_written)
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_result.h b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_result.h
index 9f5052676fd..67bf99591ad 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_result.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_isochronous_out_transfer_result.h
@@ -19,7 +19,7 @@ class USBIsochronousOutTransferResult final : public ScriptWrappable {
public:
static USBIsochronousOutTransferResult* Create(
const HeapVector<Member<USBIsochronousOutTransferPacket>>& packets) {
- return new USBIsochronousOutTransferResult(packets);
+ return MakeGarbageCollected<USBIsochronousOutTransferResult>(packets);
}
USBIsochronousOutTransferResult(
diff --git a/chromium/third_party/blink/renderer/modules/webusb/usb_out_transfer_result.h b/chromium/third_party/blink/renderer/modules/webusb/usb_out_transfer_result.h
index 139b65a77cc..de501a8d589 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/usb_out_transfer_result.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/usb_out_transfer_result.h
@@ -16,12 +16,12 @@ class USBOutTransferResult final : public ScriptWrappable {
public:
static USBOutTransferResult* Create(const String& status) {
- return new USBOutTransferResult(status, 0);
+ return MakeGarbageCollected<USBOutTransferResult>(status, 0);
}
static USBOutTransferResult* Create(const String& status,
unsigned bytes_written) {
- return new USBOutTransferResult(status, bytes_written);
+ return MakeGarbageCollected<USBOutTransferResult>(status, bytes_written);
}
USBOutTransferResult(const String& status, unsigned bytes_written)
diff --git a/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.cc b/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.cc
index b521d2f00a2..55cb400eb72 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.cc
+++ b/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.cc
@@ -15,7 +15,7 @@ WorkerNavigatorUSB& WorkerNavigatorUSB::From(
WorkerNavigatorUSB* supplement =
Supplement<WorkerNavigator>::From<WorkerNavigatorUSB>(worker_navigator);
if (!supplement) {
- supplement = new WorkerNavigatorUSB(worker_navigator);
+ supplement = MakeGarbageCollected<WorkerNavigatorUSB>(worker_navigator);
ProvideTo(worker_navigator, supplement);
}
return *supplement;
diff --git a/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.h b/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.h
index 613829e0bfb..38b240f8ed6 100644
--- a/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.h
+++ b/chromium/third_party/blink/renderer/modules/webusb/worker_navigator_usb.h
@@ -29,11 +29,11 @@ class WorkerNavigatorUSB final : public GarbageCollected<WorkerNavigatorUSB>,
static USB* usb(ScriptState*, WorkerNavigator&);
USB* usb(ScriptState*);
+ explicit WorkerNavigatorUSB(WorkerNavigator&);
+
void Trace(blink::Visitor*) override;
private:
- explicit WorkerNavigatorUSB(WorkerNavigator&);
-
Member<USB> usb_;
};
diff --git a/chromium/third_party/blink/renderer/modules/worklet/BUILD.gn b/chromium/third_party/blink/renderer/modules/worklet/BUILD.gn
new file mode 100644
index 00000000000..3816329e996
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/worklet/BUILD.gn
@@ -0,0 +1,12 @@
+# Copyright 2018 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//third_party/blink/renderer/modules/modules.gni")
+
+blink_modules_sources("worklet") {
+ sources = [
+ "animation_and_paint_worklet_thread.cc",
+ "animation_and_paint_worklet_thread.h",
+ ]
+}
diff --git a/chromium/third_party/blink/renderer/modules/worklet/DEPS b/chromium/third_party/blink/renderer/modules/worklet/DEPS
new file mode 100644
index 00000000000..05af31aee9c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/worklet/DEPS
@@ -0,0 +1,7 @@
+include_rules = [
+ "-third_party/blink/renderer/modules",
+ "+third_party/blink/renderer/modules/animationworklet",
+ "+third_party/blink/renderer/modules/csspaint",
+ "+third_party/blink/renderer/modules/modules_export.h",
+ "+third_party/blink/renderer/modules/worklet",
+]
diff --git a/chromium/third_party/blink/renderer/modules/worklet/OWNERS b/chromium/third_party/blink/renderer/modules/worklet/OWNERS
new file mode 100644
index 00000000000..2129484b425
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/worklet/OWNERS
@@ -0,0 +1,8 @@
+flackr@chromium.org
+
+# For AnimationWorklet-related changes
+majidvp@chromium.org
+
+# For PaintWorklet-related changes
+ikilpatrick@chromium.org
+xidachen@chromium.org
diff --git a/chromium/third_party/blink/renderer/modules/worklet/README.md b/chromium/third_party/blink/renderer/modules/worklet/README.md
new file mode 100644
index 00000000000..fb8253fd359
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/worklet/README.md
@@ -0,0 +1,4 @@
+# modules/worklet
+
+This directory contains data structures shared between the different types of
+worklets (modules/animationworklet, modules/csspaint, etc).
diff --git a/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.cc b/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.cc
new file mode 100644
index 00000000000..5b6926544b7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.cc
@@ -0,0 +1,120 @@
+// 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 "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
+
+#include "base/memory/ptr_util.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
+#include "third_party/blink/renderer/core/workers/worklet_thread_holder.h"
+#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h"
+#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h"
+#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
+
+namespace blink {
+
+namespace {
+unsigned s_ref_count = 0;
+} // namespace
+
+std::unique_ptr<AnimationAndPaintWorkletThread>
+AnimationAndPaintWorkletThread::CreateForAnimationWorklet(
+ WorkerReportingProxy& worker_reporting_proxy) {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("animation-worklet"),
+ "AnimationAndPaintWorkletThread::CreateForAnimationWorklet");
+ DCHECK(IsMainThread());
+ return base::WrapUnique(new AnimationAndPaintWorkletThread(
+ WorkletType::ANIMATION_WORKLET, worker_reporting_proxy));
+}
+
+std::unique_ptr<AnimationAndPaintWorkletThread>
+AnimationAndPaintWorkletThread::CreateForPaintWorklet(
+ WorkerReportingProxy& worker_reporting_proxy) {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("paint-worklet"),
+ "AnimationAndPaintWorkletThread::CreateForPaintWorklet");
+ DCHECK(IsMainThread());
+ return base::WrapUnique(new AnimationAndPaintWorkletThread(
+ WorkletType::PAINT_WORKLET, worker_reporting_proxy));
+}
+
+template class WorkletThreadHolder<AnimationAndPaintWorkletThread>;
+
+AnimationAndPaintWorkletThread::AnimationAndPaintWorkletThread(
+ WorkletType worklet_type,
+ WorkerReportingProxy& worker_reporting_proxy)
+ : WorkerThread(worker_reporting_proxy), worklet_type_(worklet_type) {
+ DCHECK(IsMainThread());
+ if (++s_ref_count == 1) {
+ EnsureSharedBackingThread();
+ }
+}
+
+AnimationAndPaintWorkletThread::~AnimationAndPaintWorkletThread() {
+ DCHECK(IsMainThread());
+ if (--s_ref_count == 0) {
+ ClearSharedBackingThread();
+ }
+}
+
+WorkerBackingThread& AnimationAndPaintWorkletThread::GetWorkerBackingThread() {
+ return *WorkletThreadHolder<AnimationAndPaintWorkletThread>::GetInstance()
+ ->GetThread();
+}
+
+static void CollectAllGarbageOnThread(WaitableEvent* done_event) {
+ blink::ThreadState::Current()->CollectAllGarbage();
+ done_event->Signal();
+}
+
+void AnimationAndPaintWorkletThread::CollectAllGarbage() {
+ DCHECK(IsMainThread());
+ WaitableEvent done_event;
+ auto* holder =
+ WorkletThreadHolder<AnimationAndPaintWorkletThread>::GetInstance();
+ if (!holder)
+ return;
+ holder->GetThread()->BackingThread().PostTask(
+ FROM_HERE, CrossThreadBind(&CollectAllGarbageOnThread,
+ CrossThreadUnretained(&done_event)));
+ done_event.Wait();
+}
+
+WorkerOrWorkletGlobalScope*
+AnimationAndPaintWorkletThread::CreateWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params) {
+ switch (worklet_type_) {
+ case WorkletType::ANIMATION_WORKLET: {
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("animation-worklet"),
+ "AnimationAndPaintWorkletThread::CreateWorkerGlobalScope");
+ return AnimationWorkletGlobalScope::Create(std::move(creation_params),
+ this);
+ }
+ case WorkletType::PAINT_WORKLET:
+ TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("paint-worklet"),
+ "AnimationAndPaintWorkletThread::CreateWorkerGlobalScope");
+ return PaintWorkletGlobalScope::Create(std::move(creation_params), this);
+ };
+}
+
+void AnimationAndPaintWorkletThread::EnsureSharedBackingThread() {
+ DCHECK(IsMainThread());
+ WorkletThreadHolder<AnimationAndPaintWorkletThread>::EnsureInstance(
+ ThreadCreationParams(WebThreadType::kAnimationAndPaintWorkletThread));
+}
+
+void AnimationAndPaintWorkletThread::ClearSharedBackingThread() {
+ DCHECK(IsMainThread());
+ DCHECK_EQ(s_ref_count, 0u);
+ WorkletThreadHolder<AnimationAndPaintWorkletThread>::ClearInstance();
+}
+
+// static
+WorkletThreadHolder<AnimationAndPaintWorkletThread>*
+AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting() {
+ return WorkletThreadHolder<AnimationAndPaintWorkletThread>::GetInstance();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h b/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h
new file mode 100644
index 00000000000..a875eee8182
--- /dev/null
+++ b/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h
@@ -0,0 +1,65 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_WORKLET_ANIMATION_AND_PAINT_WORKLET_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_MODULES_WORKLET_ANIMATION_AND_PAINT_WORKLET_THREAD_H_
+
+#include <memory>
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/core/workers/worklet_thread_holder.h"
+#include "third_party/blink/renderer/modules/modules_export.h"
+
+namespace blink {
+
+class WorkerReportingProxy;
+
+// Represents the shared backing thread that is used by both animation worklets
+// and off-thread paint worklets. This thread participates in the Blink garbage
+// collection process.
+class MODULES_EXPORT AnimationAndPaintWorkletThread final
+ : public WorkerThread {
+ public:
+ static std::unique_ptr<AnimationAndPaintWorkletThread>
+ CreateForAnimationWorklet(WorkerReportingProxy&);
+ static std::unique_ptr<AnimationAndPaintWorkletThread> CreateForPaintWorklet(
+ WorkerReportingProxy&);
+ ~AnimationAndPaintWorkletThread() override;
+
+ WorkerBackingThread& GetWorkerBackingThread() override;
+
+ // The backing thread is cleared by ClearSharedBackingThread().
+ void ClearWorkerBackingThread() override {}
+
+ // This may block the main thread.
+ static void CollectAllGarbage();
+
+ static WorkletThreadHolder<AnimationAndPaintWorkletThread>*
+ GetWorkletThreadHolderForTesting();
+
+ private:
+ enum class WorkletType {
+ ANIMATION_WORKLET,
+ PAINT_WORKLET,
+ };
+
+ explicit AnimationAndPaintWorkletThread(WorkletType, WorkerReportingProxy&);
+
+ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams>) final;
+
+ bool IsOwningBackingThread() const override { return false; }
+
+ WebThreadType GetThreadType() const override {
+ return WebThreadType::kAnimationAndPaintWorkletThread;
+ }
+
+ void EnsureSharedBackingThread();
+ void ClearSharedBackingThread();
+
+ WorkletType worklet_type_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WORKLET_ANIMATION_AND_PAINT_WORKLET_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread_test.cc b/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread_test.cc
index e7462ff02ac..0928a5e240a 100644
--- a/chromium/third_party/blink/renderer/modules/animationworklet/animation_worklet_thread_test.cc
+++ b/chromium/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread_test.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 "third_party/blink/renderer/modules/animationworklet/animation_worklet_thread.h"
+#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
@@ -14,19 +14,19 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
+#include "third_party/blink/renderer/core/workers/worklet_thread_holder.h"
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_proxy_client.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
@@ -45,10 +45,9 @@ class TestAnimationWorkletProxyClient : public AnimationWorkletProxyClient {
} // namespace
-class AnimationWorkletThreadTest : public PageTestBase {
+class AnimationAndPaintWorkletThreadTest : public PageTestBase {
public:
void SetUp() override {
- AnimationWorkletThread::EnsureSharedBackingThread();
PageTestBase::SetUp(IntSize());
Document* document = &GetDocument();
document->SetURL(KURL("https://example.com/"));
@@ -56,28 +55,27 @@ class AnimationWorkletThreadTest : public PageTestBase {
reporting_proxy_ = std::make_unique<WorkerReportingProxy>();
}
- void TearDown() override {
- AnimationWorkletThread::ClearSharedBackingThread();
- }
-
- std::unique_ptr<AnimationWorkletThread> CreateAnimationWorkletThread() {
+ std::unique_ptr<AnimationAndPaintWorkletThread>
+ CreateAnimationAndPaintWorkletThread() {
WorkerClients* clients = WorkerClients::Create();
ProvideAnimationWorkletProxyClientTo(clients,
new TestAnimationWorkletProxyClient());
- std::unique_ptr<AnimationWorkletThread> thread =
- AnimationWorkletThread::Create(*reporting_proxy_);
+ std::unique_ptr<AnimationAndPaintWorkletThread> thread =
+ AnimationAndPaintWorkletThread::CreateForAnimationWorklet(
+ *reporting_proxy_);
Document* document = &GetDocument();
thread->Start(
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
- Vector<CSPHeaderAndType>(), document->GetReferrerPolicy(),
- document->GetSecurityOrigin(), document->IsSecureContext(),
- document->GetHttpsState(), clients, document->AddressSpace(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */, Vector<CSPHeaderAndType>(),
+ document->GetReferrerPolicy(), document->GetSecurityOrigin(),
+ document->IsSecureContext(), document->GetHttpsState(), clients,
+ document->AddressSpace(),
OriginTrialContext::GetTokens(document).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap),
- base::nullopt, WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
+ base::nullopt, std::make_unique<WorkerDevToolsParams>(),
ParentExecutionContextTaskRunners::Create());
return thread;
}
@@ -88,10 +86,10 @@ class AnimationWorkletThreadTest : public PageTestBase {
std::make_unique<WaitableEvent>();
thread->GetWorkerBackingThread().BackingThread().PostTask(
FROM_HERE,
- CrossThreadBind(&AnimationWorkletThreadTest::ExecuteScriptInWorklet,
- CrossThreadUnretained(this),
- CrossThreadUnretained(thread),
- CrossThreadUnretained(wait_event.get())));
+ CrossThreadBind(
+ &AnimationAndPaintWorkletThreadTest::ExecuteScriptInWorklet,
+ CrossThreadUnretained(this), CrossThreadUnretained(thread),
+ CrossThreadUnretained(wait_event.get())));
wait_event->Wait();
}
@@ -104,8 +102,8 @@ class AnimationWorkletThreadTest : public PageTestBase {
const KURL js_url("https://example.com/foo.js");
ScriptModule module = ScriptModule::Compile(
script_state->GetIsolate(), "var counter = 0; ++counter;", js_url,
- js_url, ScriptFetchOptions(), kSharableCrossOrigin,
- TextPosition::MinimumPosition(), ASSERT_NO_EXCEPTION);
+ js_url, ScriptFetchOptions(), TextPosition::MinimumPosition(),
+ ASSERT_NO_EXCEPTION);
EXPECT_FALSE(module.IsNull());
ScriptValue exception = module.Instantiate(script_state);
EXPECT_TRUE(exception.IsEmpty());
@@ -117,9 +115,9 @@ class AnimationWorkletThreadTest : public PageTestBase {
std::unique_ptr<WorkerReportingProxy> reporting_proxy_;
};
-TEST_F(AnimationWorkletThreadTest, Basic) {
- std::unique_ptr<AnimationWorkletThread> worklet =
- CreateAnimationWorkletThread();
+TEST_F(AnimationAndPaintWorkletThreadTest, Basic) {
+ std::unique_ptr<AnimationAndPaintWorkletThread> worklet =
+ CreateAnimationAndPaintWorkletThread();
CheckWorkletCanExecuteScript(worklet.get());
worklet->Terminate();
worklet->WaitForShutdownForTesting();
@@ -127,10 +125,10 @@ TEST_F(AnimationWorkletThreadTest, Basic) {
// Tests that the same WebThread is used for new worklets if the WebThread is
// still alive.
-TEST_F(AnimationWorkletThreadTest, CreateSecondAndTerminateFirst) {
+TEST_F(AnimationAndPaintWorkletThreadTest, CreateSecondAndTerminateFirst) {
// Create the first worklet and wait until it is initialized.
- std::unique_ptr<AnimationWorkletThread> first_worklet =
- CreateAnimationWorkletThread();
+ std::unique_ptr<AnimationAndPaintWorkletThread> first_worklet =
+ CreateAnimationAndPaintWorkletThread();
WebThreadSupportingGC* first_thread =
&first_worklet->GetWorkerBackingThread().BackingThread();
CheckWorkletCanExecuteScript(first_worklet.get());
@@ -138,8 +136,8 @@ TEST_F(AnimationWorkletThreadTest, CreateSecondAndTerminateFirst) {
ASSERT_TRUE(first_isolate);
// Create the second worklet and immediately destroy the first worklet.
- std::unique_ptr<AnimationWorkletThread> second_worklet =
- CreateAnimationWorkletThread();
+ std::unique_ptr<AnimationAndPaintWorkletThread> second_worklet =
+ CreateAnimationAndPaintWorkletThread();
// We don't use terminateAndWait here to avoid forcible termination.
first_worklet->Terminate();
first_worklet->WaitForShutdownForTesting();
@@ -161,12 +159,12 @@ TEST_F(AnimationWorkletThreadTest, CreateSecondAndTerminateFirst) {
second_worklet->WaitForShutdownForTesting();
}
-// Tests that a new WebThread is created if all existing worklets are
-// terminated before a new worklet is created.
-TEST_F(AnimationWorkletThreadTest, TerminateFirstAndCreateSecond) {
+// Tests that the WebThread is reused if all existing worklets are terminated
+// before a new worklet is created, as long as the worklets are not destructed.
+TEST_F(AnimationAndPaintWorkletThreadTest, TerminateFirstAndCreateSecond) {
// Create the first worklet, wait until it is initialized, and terminate it.
- std::unique_ptr<AnimationWorkletThread> worklet =
- CreateAnimationWorkletThread();
+ std::unique_ptr<AnimationAndPaintWorkletThread> worklet =
+ CreateAnimationAndPaintWorkletThread();
WebThreadSupportingGC* first_thread =
&worklet->GetWorkerBackingThread().BackingThread();
CheckWorkletCanExecuteScript(worklet.get());
@@ -176,7 +174,7 @@ TEST_F(AnimationWorkletThreadTest, TerminateFirstAndCreateSecond) {
worklet->WaitForShutdownForTesting();
// Create the second worklet. The backing thread is same.
- worklet = CreateAnimationWorkletThread();
+ worklet = CreateAnimationAndPaintWorkletThread();
WebThreadSupportingGC* second_thread =
&worklet->GetWorkerBackingThread().BackingThread();
EXPECT_EQ(first_thread, second_thread);
@@ -188,9 +186,10 @@ TEST_F(AnimationWorkletThreadTest, TerminateFirstAndCreateSecond) {
// Tests that v8::Isolate and WebThread are correctly set-up if a worklet is
// created while another is terminating.
-TEST_F(AnimationWorkletThreadTest, CreatingSecondDuringTerminationOfFirst) {
- std::unique_ptr<AnimationWorkletThread> first_worklet =
- CreateAnimationWorkletThread();
+TEST_F(AnimationAndPaintWorkletThreadTest,
+ CreatingSecondDuringTerminationOfFirst) {
+ std::unique_ptr<AnimationAndPaintWorkletThread> first_worklet =
+ CreateAnimationAndPaintWorkletThread();
CheckWorkletCanExecuteScript(first_worklet.get());
v8::Isolate* first_isolate = first_worklet->GetIsolate();
ASSERT_TRUE(first_isolate);
@@ -202,8 +201,8 @@ TEST_F(AnimationWorkletThreadTest, CreatingSecondDuringTerminationOfFirst) {
// Note: We rely on the assumption that the termination steps don't run
// on the worklet thread so quickly. This could be a source of flakiness.
- std::unique_ptr<AnimationWorkletThread> second_worklet =
- CreateAnimationWorkletThread();
+ std::unique_ptr<AnimationAndPaintWorkletThread> second_worklet =
+ CreateAnimationAndPaintWorkletThread();
v8::Isolate* second_isolate = second_worklet->GetIsolate();
ASSERT_TRUE(second_isolate);
@@ -216,4 +215,47 @@ TEST_F(AnimationWorkletThreadTest, CreatingSecondDuringTerminationOfFirst) {
second_worklet->WaitForShutdownForTesting();
}
+// Tests that the backing thread is correctly created, torn down, and recreated
+// as AnimationWorkletThreads are created and destroyed.
+TEST_F(AnimationAndPaintWorkletThreadTest,
+ WorkletThreadHolderIsRefCountedProperly) {
+ EXPECT_FALSE(
+ AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting());
+
+ std::unique_ptr<AnimationAndPaintWorkletThread> worklet =
+ CreateAnimationAndPaintWorkletThread();
+ ASSERT_TRUE(worklet.get());
+ WorkletThreadHolder<AnimationAndPaintWorkletThread>* holder =
+ AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting();
+ EXPECT_TRUE(holder);
+
+ std::unique_ptr<AnimationAndPaintWorkletThread> worklet2 =
+ CreateAnimationAndPaintWorkletThread();
+ ASSERT_TRUE(worklet2.get());
+ WorkletThreadHolder<AnimationAndPaintWorkletThread>* holder2 =
+ AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting();
+ EXPECT_EQ(holder, holder2);
+
+ worklet->Terminate();
+ worklet->WaitForShutdownForTesting();
+ worklet.reset();
+ EXPECT_TRUE(
+ AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting());
+
+ worklet2->Terminate();
+ worklet2->WaitForShutdownForTesting();
+ worklet2.reset();
+ EXPECT_FALSE(
+ AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting());
+
+ std::unique_ptr<AnimationAndPaintWorkletThread> worklet3 =
+ CreateAnimationAndPaintWorkletThread();
+ ASSERT_TRUE(worklet3.get());
+ EXPECT_TRUE(
+ AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting());
+
+ worklet3->Terminate();
+ worklet3->WaitForShutdownForTesting();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/xr/PRESUBMIT.py b/chromium/third_party/blink/renderer/modules/xr/PRESUBMIT.py
deleted file mode 100644
index 81cd49bc4f9..00000000000
--- a/chromium/third_party/blink/renderer/modules/xr/PRESUBMIT.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (c) 2018 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Top-level presubmit script for third_party/blink/renderer/modules/xr.
-
-See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
-for more details about the presubmit API built into depot_tools.
-"""
-
-
-def PostUploadHook(cl, change, output_api): # pylint: disable=C0103,W0613
- """git cl upload will call this hook after the issue is created/modified.
-
- This hook modifies the CL description in order to run extra GPU
- tests (in particular, WebXR and WebVR browser tests) in addition
- to the regular CQ try bots. This test suite is too large to run
- against all Chromium commits, but should be run against changes
- likely to affect these tests.
- """
- return output_api.EnsureCQIncludeTrybotsAreAdded(
- cl,
- ['luci.chromium.try:win_optional_gpu_tests_rel'],
- 'Automatically added optional GPU tests to run on CQ.')
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr.cc b/chromium/third_party/blink/renderer/modules/xr/xr.cc
index 6115eafb100..95500107a54 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr.cc
@@ -15,6 +15,8 @@
#include "third_party/blink/renderer/modules/event_modules.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/xr/xr_device.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
+
namespace blink {
namespace {
@@ -54,7 +56,7 @@ ExecutionContext* XR::GetExecutionContext() const {
}
const AtomicString& XR::InterfaceName() const {
- return EventTargetNames::XR;
+ return event_target_names::kXR;
}
ScriptPromise XR::requestDevice(ScriptState* script_state) {
@@ -125,13 +127,13 @@ ScriptPromise XR::requestDevice(ScriptState* script_state) {
// the XRDevice might now be able to support immersive sessions, where it
// couldn't before.
void XR::OnDeviceChanged() {
- DispatchEvent(*blink::Event::Create(EventTypeNames::devicechange));
+ DispatchEvent(*blink::Event::Create(event_type_names::kDevicechange));
}
void XR::OnRequestDeviceReturned(device::mojom::blink::XRDevicePtr device) {
pending_sync_ = false;
if (device) {
- device_ = new XRDevice(this, std::move(device));
+ device_ = MakeGarbageCollected<XRDevice>(this, std::move(device));
}
ResolveRequestDevice();
}
@@ -191,7 +193,7 @@ void XR::AddedEventListener(const AtomicString& event_type,
// If we don't have device and there is no sync pending, then request the
// device to ensure devices have been enumerated and register as a listener
// for changes.
- if (event_type == EventTypeNames::devicechange && !device_ &&
+ if (event_type == event_type_names::kDevicechange && !device_ &&
!pending_sync_) {
device::mojom::blink::VRServiceClientPtr client;
binding_.Bind(mojo::MakeRequest(&client));
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr.h b/chromium/third_party/blink/renderer/modules/xr/xr.h
index fc3dc56ab09..346964a7608 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr.h
@@ -29,10 +29,12 @@ class XR final : public EventTargetWithInlineData,
public:
static XR* Create(LocalFrame& frame, int64_t source_id) {
- return new XR(frame, source_id);
+ return MakeGarbageCollected<XR>(frame, source_id);
}
- DEFINE_ATTRIBUTE_EVENT_LISTENER(devicechange);
+ explicit XR(LocalFrame& frame, int64_t ukm_source_id_);
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(devicechange, kDevicechange);
ScriptPromise requestDevice(ScriptState*);
@@ -54,8 +56,6 @@ class XR final : public EventTargetWithInlineData,
int64_t GetSourceId() const { return ukm_source_id_; }
private:
- explicit XR(LocalFrame& frame, int64_t ukm_source_id_);
-
void OnRequestDeviceReturned(device::mojom::blink::XRDevicePtr device);
void ResolveRequestDevice();
void ReportImmersiveSupported(bool supported);
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.cc b/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.cc
index 93f341e1af0..9420e85f5d5 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/modules/xr/xr_canvas_input_provider.h"
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
-#include "third_party/blink/renderer/core/events/mouse_event.h"
+#include "third_party/blink/renderer/core/events/pointer_event.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/modules/xr/xr_device.h"
#include "third_party/blink/renderer/modules/xr/xr_frame_provider.h"
@@ -26,12 +26,15 @@ class XRCanvasInputEventListener : public EventListener {
return this == &that;
}
- void handleEvent(ExecutionContext* execution_context, Event* event) override {
+ void Invoke(ExecutionContext* execution_context, Event* event) override {
if (!input_provider_->ShouldProcessEvents())
return;
- if (event->type() == EventTypeNames::click) {
- input_provider_->OnClick(ToMouseEvent(event));
+ if (event->type() == event_type_names::kPointerdown) {
+ input_provider_->OnPointerDown(ToPointerEvent(event));
+ } else if (event->type() == event_type_names::kPointerup ||
+ event->type() == event_type_names::kPointercancel) {
+ input_provider_->OnPointerUp(ToPointerEvent(event));
}
}
@@ -50,18 +53,21 @@ XRCanvasInputProvider::XRCanvasInputProvider(XRSession* session,
HTMLCanvasElement* canvas)
: session_(session), canvas_(canvas) {
listener_ = new XRCanvasInputEventListener(this);
- canvas->addEventListener(EventTypeNames::click, listener_);
+ canvas->addEventListener(event_type_names::kPointerdown, listener_);
+ canvas->addEventListener(event_type_names::kPointerup, listener_);
+ canvas->addEventListener(event_type_names::kPointercancel, listener_);
}
XRCanvasInputProvider::~XRCanvasInputProvider() {
- Stop();
}
void XRCanvasInputProvider::Stop() {
if (!listener_) {
return;
}
- canvas_->removeEventListener(EventTypeNames::click, listener_);
+ canvas_->removeEventListener(event_type_names::kPointerdown, listener_);
+ canvas_->removeEventListener(event_type_names::kPointerup, listener_);
+ canvas_->removeEventListener(event_type_names::kPointercancel, listener_);
canvas_ = nullptr;
listener_ = nullptr;
}
@@ -71,7 +77,12 @@ bool XRCanvasInputProvider::ShouldProcessEvents() {
return !(session_->device()->frameProvider()->immersive_session());
}
-void XRCanvasInputProvider::OnClick(MouseEvent* event) {
+void XRCanvasInputProvider::OnPointerDown(PointerEvent* event) {
+ UpdateInputSource(event);
+ session_->OnSelectStart(input_source_);
+}
+
+void XRCanvasInputProvider::OnPointerUp(PointerEvent* event) {
UpdateInputSource(event);
session_->OnSelect(input_source_);
ClearInputSource();
@@ -81,12 +92,12 @@ XRInputSource* XRCanvasInputProvider::GetInputSource() {
return input_source_;
}
-void XRCanvasInputProvider::UpdateInputSource(MouseEvent* event) {
+void XRCanvasInputProvider::UpdateInputSource(PointerEvent* event) {
if (!canvas_)
return;
if (!input_source_) {
- input_source_ = new XRInputSource(session_, 0);
+ input_source_ = MakeGarbageCollected<XRInputSource>(session_, 0);
input_source_->SetTargetRayMode(XRInputSource::kScreen);
}
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.h b/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.h
index 201092ae33a..cd4f219d881 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_canvas_input_provider.h
@@ -16,7 +16,7 @@ namespace blink {
class EventListener;
class HTMLCanvasElement;
-class MouseEvent;
+class PointerEvent;
class XRInputSource;
class XRSession;
@@ -34,7 +34,8 @@ class XRCanvasInputProvider
bool ShouldProcessEvents();
- void OnClick(MouseEvent*);
+ void OnPointerDown(PointerEvent*);
+ void OnPointerUp(PointerEvent*);
XRInputSource* GetInputSource();
@@ -44,7 +45,7 @@ class XRCanvasInputProvider
}
private:
- void UpdateInputSource(MouseEvent*);
+ void UpdateInputSource(PointerEvent*);
void ClearInputSource();
const Member<XRSession> session_;
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_coordinate_system.cc b/chromium/third_party/blink/renderer/modules/xr/xr_coordinate_system.cc
index b00c970e42b..11c9f28cce0 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_coordinate_system.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_coordinate_system.cc
@@ -35,7 +35,7 @@ ExecutionContext* XRCoordinateSystem::GetExecutionContext() const {
}
const AtomicString& XRCoordinateSystem::InterfaceName() const {
- return EventTargetNames::XRCoordinateSystem;
+ return event_target_names::kXRCoordinateSystem;
}
void XRCoordinateSystem::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_device.cc b/chromium/third_party/blink/renderer/modules/xr/xr_device.cc
index a2a9d57ffcf..d48f157eeda 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_device.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_device.cc
@@ -32,17 +32,34 @@ const char kRequestRequiresUserActivation[] =
const char kSessionNotSupported[] =
"The specified session configuration is not supported.";
+/**
+ * Helper method to convert IDL options into Mojo options.
+ */
+device::mojom::blink::XRSessionOptionsPtr convertIdlOptionsToMojo(
+ const XRSessionCreationOptions* options) {
+ auto session_options = device::mojom::blink::XRSessionOptions::New();
+ if (options->hasImmersive()) {
+ session_options->immersive = options->immersive();
+ }
+ if (options->hasEnvironmentIntegration()) {
+ session_options->environment_integration =
+ options->environmentIntegration();
+ }
+
+ return session_options;
+}
+
} // namespace
XRDevice::XRDevice(XR* xr, device::mojom::blink::XRDevicePtr device)
: xr_(xr), device_ptr_(std::move(device)) {}
const char* XRDevice::checkSessionSupport(
- const XRSessionCreationOptions& options) const {
- if (!options.immersive()) {
+ const XRSessionCreationOptions* options) const {
+ if (!options->immersive()) {
// Validation for non-immersive sessions. Validation for immersive sessions
// happens browser side.
- if (!options.hasOutputContext()) {
+ if (!options->hasOutputContext()) {
return kNoOutputContext;
}
}
@@ -52,7 +69,7 @@ const char* XRDevice::checkSessionSupport(
ScriptPromise XRDevice::supportsSession(
ScriptState* script_state,
- const XRSessionCreationOptions& options) {
+ const XRSessionCreationOptions* options) {
// Check to see if the device is capable of supporting the requested session
// options. Note that reporting support here does not guarantee that creating
// a session with those options will succeed, as other external and
@@ -71,8 +88,7 @@ ScriptPromise XRDevice::supportsSession(
ScriptPromise promise = resolver->Promise();
device::mojom::blink::XRSessionOptionsPtr session_options =
- device::mojom::blink::XRSessionOptions::New();
- session_options->immersive = options.immersive();
+ convertIdlOptionsToMojo(options);
device_ptr_->SupportsSession(
std::move(session_options),
@@ -94,12 +110,17 @@ int64_t XRDevice::GetSourceId() const {
return xr_->GetSourceId();
}
+const device::mojom::blink::XREnvironmentIntegrationProviderAssociatedPtr&
+XRDevice::xrEnvironmentProviderPtr() {
+ return environment_provider_;
+}
+
ScriptPromise XRDevice::requestSession(
ScriptState* script_state,
- const XRSessionCreationOptions& options) {
+ const XRSessionCreationOptions* options) {
Document* doc = To<Document>(ExecutionContext::From(script_state));
- if (options.immersive() && !did_log_request_immersive_session_ && doc) {
+ if (options->immersive() && !did_log_request_immersive_session_ && doc) {
ukm::builders::XR_WebXR(GetSourceId())
.SetDidRequestPresentation(1)
.Record(doc->UkmRecorder());
@@ -121,7 +142,7 @@ ScriptPromise XRDevice::requestSession(
// Check if the current page state prevents the requested session from being
// created.
- if (options.immersive()) {
+ if (options->immersive()) {
if (frameProvider()->immersive_session()) {
return ScriptPromise::RejectWithDOMException(
script_state,
@@ -137,7 +158,7 @@ ScriptPromise XRDevice::requestSession(
}
// All AR sessions require a user gesture.
- if (options.environmentIntegration()) {
+ if (options->environmentIntegration()) {
if (!has_user_activation) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kSecurityError,
@@ -149,14 +170,11 @@ ScriptPromise XRDevice::requestSession(
ScriptPromise promise = resolver->Promise();
device::mojom::blink::XRSessionOptionsPtr session_options =
- device::mojom::blink::XRSessionOptions::New();
- session_options->immersive = options.immersive();
- session_options->provide_passthrough_camera =
- options.environmentIntegration();
+ convertIdlOptionsToMojo(options);
session_options->has_user_activation = has_user_activation;
XRPresentationContext* output_context =
- options.hasOutputContext() ? options.outputContext() : nullptr;
+ options->hasOutputContext() ? options->outputContext() : nullptr;
// TODO(http://crbug.com/826899) Once device activation is sorted out for
// WebXR, either pass in the correct value for metrics to know whether
@@ -166,7 +184,7 @@ ScriptPromise XRDevice::requestSession(
std::move(session_options), false /* triggered by display activate */,
WTF::Bind(&XRDevice::OnRequestSessionReturned, WrapWeakPersistent(this),
WrapPersistent(resolver), WrapPersistent(output_context),
- options.environmentIntegration(), options.immersive()));
+ options->environmentIntegration(), options->immersive()));
return promise;
}
@@ -185,24 +203,31 @@ void XRDevice::OnRequestSessionReturned(
return;
}
+ // immersive sessions must supply display info.
+ DCHECK(session_ptr->display_info);
+ // If the session supports environment integration, ensure the device does
+ // as well.
+ DCHECK(!environment_integration || session_ptr->display_info->capabilities
+ ->canProvideEnvironmentIntegration);
+
XRSession::EnvironmentBlendMode blend_mode = XRSession::kBlendModeOpaque;
if (environment_integration)
blend_mode = XRSession::kBlendModeAlphaBlend;
- XRSession* session =
- new XRSession(this, std::move(session_ptr->client_request), immersive,
- environment_integration, output_context, blend_mode);
- // immersive sessions must supply display info.
- DCHECK(!immersive || session_ptr->display_info);
- if (session_ptr->display_info)
- session->SetXRDisplayInfo(std::move(session_ptr->display_info));
+ XRSession* session = MakeGarbageCollected<XRSession>(
+ this, std::move(session_ptr->client_request), immersive,
+ environment_integration, output_context, blend_mode);
+ session->SetXRDisplayInfo(std::move(session_ptr->display_info));
sessions_.insert(session);
if (immersive) {
frameProvider()->BeginImmersiveSession(session, std::move(session_ptr));
} else {
magic_window_provider_.Bind(std::move(session_ptr->data_provider));
- environment_provider_.Bind(std::move(session_ptr->environment_provider));
+ if (environment_integration) {
+ magic_window_provider_->GetEnvironmentIntegrationProvider(
+ mojo::MakeRequest(&environment_provider_));
+ }
}
resolver->Resolve(session);
@@ -228,7 +253,7 @@ bool XRDevice::IsFrameFocused() {
XRFrameProvider* XRDevice::frameProvider() {
if (!frame_provider_) {
- frame_provider_ = new XRFrameProvider(this);
+ frame_provider_ = MakeGarbageCollected<XRFrameProvider>(this);
}
return frame_provider_;
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_device.h b/chromium/third_party/blink/renderer/modules/xr/xr_device.h
index 83e27506412..047a54ffadf 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_device.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_device.h
@@ -29,8 +29,8 @@ class XRDevice final : public ScriptWrappable {
XRDevice(XR*, device::mojom::blink::XRDevicePtr);
XR* xr() const { return xr_; }
- ScriptPromise supportsSession(ScriptState*, const XRSessionCreationOptions&);
- ScriptPromise requestSession(ScriptState*, const XRSessionCreationOptions&);
+ ScriptPromise supportsSession(ScriptState*, const XRSessionCreationOptions*);
+ ScriptPromise requestSession(ScriptState*, const XRSessionCreationOptions*);
XRFrameProvider* frameProvider();
@@ -43,10 +43,8 @@ class XRDevice final : public ScriptWrappable {
const {
return magic_window_provider_;
}
- const device::mojom::blink::XREnvironmentIntegrationProviderPtr&
- xrEnvironmentProviderPtr() const {
- return environment_provider_;
- }
+ const device::mojom::blink::XREnvironmentIntegrationProviderAssociatedPtr&
+ xrEnvironmentProviderPtr();
void OnFrameFocusChanged();
bool HasFrameFocus() { return IsFrameFocused(); }
@@ -56,7 +54,7 @@ class XRDevice final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- const char* checkSessionSupport(const XRSessionCreationOptions&) const;
+ const char* checkSessionSupport(const XRSessionCreationOptions*) const;
void OnRequestSessionReturned(ScriptPromiseResolver* resolver,
XRPresentationContext* output_context,
@@ -81,7 +79,7 @@ class XRDevice final : public ScriptWrappable {
bool did_log_request_immersive_session_ = false;
device::mojom::blink::XRFrameDataProviderPtr magic_window_provider_;
- device::mojom::blink::XREnvironmentIntegrationProviderPtr
+ device::mojom::blink::XREnvironmentIntegrationProviderAssociatedPtr
environment_provider_;
device::mojom::blink::XRDevicePtr device_ptr_;
};
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_frame.cc b/chromium/third_party/blink/renderer/modules/xr/xr_frame.cc
index aa0f07eb382..f4404b8a678 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_frame.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_frame.cc
@@ -41,7 +41,7 @@ XRDevicePose* XRFrame::getDevicePose(
return nullptr;
}
- return new XRDevicePose(session(), std::move(pose));
+ return MakeGarbageCollected<XRDevicePose>(session(), std::move(pose));
}
XRInputPose* XRFrame::getInputPose(
@@ -71,7 +71,8 @@ XRInputPose* XRFrame::getInputPose(
coordinate_system->TransformBasePose(*base_pose_matrix_);
pointer_pose->Multiply(*(input_source->pointer_transform_matrix_));
- return new XRInputPose(std::move(pointer_pose), nullptr);
+ return MakeGarbageCollected<XRInputPose>(std::move(pointer_pose),
+ nullptr);
}
case XRInputSource::kGaze: {
// If the pointer origin is the users head, this is a gaze cursor and the
@@ -85,8 +86,8 @@ XRInputPose* XRFrame::getInputPose(
std::unique_ptr<TransformationMatrix> pointer_pose =
coordinate_system->TransformBasePose(*base_pose_matrix_);
- return new XRInputPose(std::move(pointer_pose), nullptr,
- input_source->emulatedPosition());
+ return MakeGarbageCollected<XRInputPose>(
+ std::move(pointer_pose), nullptr, input_source->emulatedPosition());
}
case XRInputSource::kTrackedPointer: {
// If the input source doesn't have a base pose return null;
@@ -109,8 +110,9 @@ XRInputPose* XRFrame::getInputPose(
pointer_pose->Multiply(*(input_source->pointer_transform_matrix_));
}
- return new XRInputPose(std::move(pointer_pose), std::move(grip_pose),
- input_source->emulatedPosition());
+ return MakeGarbageCollected<XRInputPose>(
+ std::move(pointer_pose), std::move(grip_pose),
+ input_source->emulatedPosition());
}
}
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_frame_provider.cc b/chromium/third_party/blink/renderer/modules/xr/xr_frame_provider.cc
index fa26356ef1c..e935fdb22b3 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_frame_provider.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_frame_provider.cc
@@ -88,7 +88,7 @@ std::unique_ptr<TransformationMatrix> getPoseMatrix(
XRFrameProvider::XRFrameProvider(XRDevice* device)
: device_(device), last_has_focus_(device->HasFrameFocus()) {
- frame_transport_ = new XRFrameTransport();
+ frame_transport_ = MakeGarbageCollected<XRFrameTransport>();
}
void XRFrameProvider::BeginImmersiveSession(
@@ -156,7 +156,7 @@ void XRFrameProvider::OnImmersiveSessionEnded() {
presentation_provider_.reset();
immersive_data_provider_.reset();
- frame_transport_ = new XRFrameTransport();
+ frame_transport_ = MakeGarbageCollected<XRFrameTransport>();
// When we no longer have an active immersive session schedule all the
// outstanding frames that were requested while the immersive session was
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_input_pose.cc b/chromium/third_party/blink/renderer/modules/xr/xr_input_pose.cc
index 5b7ce8560c9..44e626bec8b 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_input_pose.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_input_pose.cc
@@ -11,7 +11,7 @@ namespace blink {
XRInputPose::XRInputPose(std::unique_ptr<TransformationMatrix> pointer_matrix,
std::unique_ptr<TransformationMatrix> grip_matrix,
bool emulated_position)
- : target_ray_(new XRRay(std::move(pointer_matrix))),
+ : target_ray_(MakeGarbageCollected<XRRay>(std::move(pointer_matrix))),
grip_matrix_(std::move(grip_matrix)),
emulated_position_(emulated_position) {}
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.cc b/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.cc
index c9e918a53b9..a59842c8e74 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.cc
@@ -17,18 +17,18 @@ XRInputSourceEvent::XRInputSourceEvent(const AtomicString& type,
XRInputSourceEvent::XRInputSourceEvent(
const AtomicString& type,
- const XRInputSourceEventInit& initializer)
+ const XRInputSourceEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasFrame())
- frame_ = initializer.frame();
- if (initializer.hasInputSource())
- input_source_ = initializer.inputSource();
+ if (initializer->hasFrame())
+ frame_ = initializer->frame();
+ if (initializer->hasInputSource())
+ input_source_ = initializer->inputSource();
}
XRInputSourceEvent::~XRInputSourceEvent() {}
const AtomicString& XRInputSourceEvent::InterfaceName() const {
- return EventNames::XRInputSourceEvent;
+ return event_interface_names::kXRInputSourceEvent;
}
void XRInputSourceEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.h b/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.h
index a94b263b5c9..f7e8c286e5e 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_input_source_event.h
@@ -16,18 +16,23 @@ class XRInputSourceEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static XRInputSourceEvent* Create() { return new XRInputSourceEvent; }
+ static XRInputSourceEvent* Create() {
+ return MakeGarbageCollected<XRInputSourceEvent>();
+ }
static XRInputSourceEvent* Create(const AtomicString& type,
XRFrame* frame,
XRInputSource* input_source) {
- return new XRInputSourceEvent(type, frame, input_source);
+ return MakeGarbageCollected<XRInputSourceEvent>(type, frame, input_source);
}
static XRInputSourceEvent* Create(const AtomicString& type,
- const XRInputSourceEventInit& initializer) {
- return new XRInputSourceEvent(type, initializer);
+ const XRInputSourceEventInit* initializer) {
+ return MakeGarbageCollected<XRInputSourceEvent>(type, initializer);
}
+ XRInputSourceEvent();
+ XRInputSourceEvent(const AtomicString& type, XRFrame*, XRInputSource*);
+ XRInputSourceEvent(const AtomicString&, const XRInputSourceEventInit*);
~XRInputSourceEvent() override;
XRFrame* frame() const { return frame_.Get(); }
@@ -38,10 +43,6 @@ class XRInputSourceEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- XRInputSourceEvent();
- XRInputSourceEvent(const AtomicString& type, XRFrame*, XRInputSource*);
- XRInputSourceEvent(const AtomicString&, const XRInputSourceEventInit&);
-
Member<XRFrame> frame_;
Member<XRInputSource> input_source_;
};
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.cc b/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.cc
index 1ee356f0a76..9944e793c72 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.cc
@@ -24,9 +24,9 @@ void XRPresentationContext::SetCanvasGetContextResult(
CanvasRenderingContext* XRPresentationContext::Factory::Create(
CanvasRenderingContextHost* host,
const CanvasContextCreationAttributesCore& attrs) {
- if (!OriginTrials::WebXREnabled(host->GetTopExecutionContext()))
+ if (!origin_trials::WebXREnabled(host->GetTopExecutionContext()))
return nullptr;
- return new XRPresentationContext(host, attrs);
+ return MakeGarbageCollected<XRPresentationContext>(host, attrs);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.h b/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.h
index 71ed62bcbe4..6041095fea2 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_presentation_context.h
@@ -38,11 +38,9 @@ class MODULES_EXPORT XRPresentationContext final
}
void SetCanvasGetContextResult(RenderingContext&) final;
- ~XRPresentationContext() override;
-
- private:
XRPresentationContext(CanvasRenderingContextHost*,
const CanvasContextCreationAttributesCore&);
+ ~XRPresentationContext() override;
};
DEFINE_TYPE_CASTS(XRPresentationContext,
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_session.cc b/chromium/third_party/blink/renderer/modules/xr/xr_session.cc
index d2e7b43e2b2..1d1f2d9a1e7 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_session.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_session.cc
@@ -101,8 +101,9 @@ XRSession::XRSession(
environment_integration_(environment_integration),
output_context_(output_context),
client_binding_(this, std::move(client_request)),
- callback_collection_(new XRFrameRequestCallbackCollection(
- device->xr()->GetExecutionContext())) {
+ callback_collection_(
+ MakeGarbageCollected<XRFrameRequestCallbackCollection>(
+ device->xr()->GetExecutionContext())) {
blurred_ = !HasAppropriateFocus();
// When an output context is provided, monitor it for resize events.
@@ -110,12 +111,14 @@ XRSession::XRSession(
HTMLCanvasElement* canvas = outputContext()->canvas();
if (canvas) {
resize_observer_ = ResizeObserver::Create(
- canvas->GetDocument(), new XRSessionResizeObserverDelegate(this));
+ canvas->GetDocument(),
+ MakeGarbageCollected<XRSessionResizeObserverDelegate>(this));
resize_observer_->observe(canvas);
// Begin processing input events on the output context's canvas.
if (!immersive_) {
- canvas_input_provider_ = new XRCanvasInputProvider(this, canvas);
+ canvas_input_provider_ =
+ MakeGarbageCollected<XRCanvasInputProvider>(this, canvas);
}
// Get the initial canvas dimensions
@@ -177,13 +180,13 @@ ExecutionContext* XRSession::GetExecutionContext() const {
}
const AtomicString& XRSession::InterfaceName() const {
- return EventTargetNames::XRSession;
+ return event_target_names::kXRSession;
}
ScriptPromise XRSession::requestFrameOfReference(
ScriptState* script_state,
const String& type,
- const XRFrameOfReferenceOptions& options) {
+ const XRFrameOfReferenceOptions* options) {
if (ended_) {
return ScriptPromise::RejectWithDOMException(
script_state, DOMException::Create(DOMExceptionCode::kInvalidStateError,
@@ -192,17 +195,19 @@ ScriptPromise XRSession::requestFrameOfReference(
XRFrameOfReference* frameOfRef = nullptr;
if (type == "head-model") {
- frameOfRef =
- new XRFrameOfReference(this, XRFrameOfReference::kTypeHeadModel);
+ frameOfRef = MakeGarbageCollected<XRFrameOfReference>(
+ this, XRFrameOfReference::kTypeHeadModel);
} else if (type == "eye-level") {
- frameOfRef =
- new XRFrameOfReference(this, XRFrameOfReference::kTypeEyeLevel);
+ frameOfRef = MakeGarbageCollected<XRFrameOfReference>(
+ this, XRFrameOfReference::kTypeEyeLevel);
} else if (type == "stage") {
- if (!options.disableStageEmulation()) {
- frameOfRef = new XRFrameOfReference(this, XRFrameOfReference::kTypeStage);
- frameOfRef->UseEmulatedHeight(options.stageEmulationHeight());
+ if (!options->disableStageEmulation()) {
+ frameOfRef = MakeGarbageCollected<XRFrameOfReference>(
+ this, XRFrameOfReference::kTypeStage);
+ frameOfRef->UseEmulatedHeight(options->stageEmulationHeight());
} else if (display_info_ && display_info_->stageParameters) {
- frameOfRef = new XRFrameOfReference(this, XRFrameOfReference::kTypeStage);
+ frameOfRef = MakeGarbageCollected<XRFrameOfReference>(
+ this, XRFrameOfReference::kTypeStage);
} else {
return ScriptPromise::RejectWithDOMException(
script_state,
@@ -297,8 +302,17 @@ ScriptPromise XRSession::requestHitTest(ScriptState* script_state,
// TODO(https://crbug.com/846411): use coordinate_system.
- // TODO(https://crbug.com/843376): Reject the promise if device doesn't
- // support the hit-test API.
+ // Reject the promise if device doesn't support the hit-test API.
+ // TODO(https://crbug.com/878936): Get the environment provider without going
+ // up to device_, since it doesn't know which runtime's environment provider
+ // we want.
+ if (!device_->xrEnvironmentProviderPtr()) {
+ return ScriptPromise::RejectWithDOMException(
+ script_state,
+ DOMException::Create(DOMExceptionCode::kNotSupportedError,
+ "Device does not support hit-test!"));
+ }
+
device::mojom::blink::XRRayPtr ray = device::mojom::blink::XRRay::New();
ray->origin = gfx::mojom::blink::Point3F::New();
@@ -334,15 +348,16 @@ void XRSession::OnHitTestResults(
HeapVector<Member<XRHitResult>> hit_results;
for (const auto& mojom_result : results.value()) {
- XRHitResult* hit_result = new XRHitResult(TransformationMatrix::Create(
- mojom_result->hit_matrix[0], mojom_result->hit_matrix[1],
- mojom_result->hit_matrix[2], mojom_result->hit_matrix[3],
- mojom_result->hit_matrix[4], mojom_result->hit_matrix[5],
- mojom_result->hit_matrix[6], mojom_result->hit_matrix[7],
- mojom_result->hit_matrix[8], mojom_result->hit_matrix[9],
- mojom_result->hit_matrix[10], mojom_result->hit_matrix[11],
- mojom_result->hit_matrix[12], mojom_result->hit_matrix[13],
- mojom_result->hit_matrix[14], mojom_result->hit_matrix[15]));
+ XRHitResult* hit_result =
+ MakeGarbageCollected<XRHitResult>(TransformationMatrix::Create(
+ mojom_result->hit_matrix[0], mojom_result->hit_matrix[1],
+ mojom_result->hit_matrix[2], mojom_result->hit_matrix[3],
+ mojom_result->hit_matrix[4], mojom_result->hit_matrix[5],
+ mojom_result->hit_matrix[6], mojom_result->hit_matrix[7],
+ mojom_result->hit_matrix[8], mojom_result->hit_matrix[9],
+ mojom_result->hit_matrix[10], mojom_result->hit_matrix[11],
+ mojom_result->hit_matrix[12], mojom_result->hit_matrix[13],
+ mojom_result->hit_matrix[14], mojom_result->hit_matrix[15]));
hit_results.push_back(hit_result);
}
resolver->Resolve(hit_results);
@@ -384,7 +399,7 @@ void XRSession::ForceEnd() {
device_->frameProvider()->OnImmersiveSessionEnded();
}
- DispatchEvent(*XRSessionEvent::Create(EventTypeNames::end, this));
+ DispatchEvent(*XRSessionEvent::Create(event_type_names::kEnd, this));
}
double XRSession::NativeFramebufferScale() const {
@@ -426,7 +441,7 @@ void XRSession::OnFocus() {
return;
blurred_ = false;
- DispatchEvent(*XRSessionEvent::Create(EventTypeNames::focus, this));
+ DispatchEvent(*XRSessionEvent::Create(event_type_names::kFocus, this));
}
void XRSession::OnBlur() {
@@ -434,7 +449,7 @@ void XRSession::OnBlur() {
return;
blurred_ = true;
- DispatchEvent(*XRSessionEvent::Create(EventTypeNames::blur, this));
+ DispatchEvent(*XRSessionEvent::Create(event_type_names::kBlur, this));
}
// Immersive sessions may still not be blurred in headset even if the page isn't
@@ -521,7 +536,7 @@ void XRSession::LogGetPose() const {
}
XRFrame* XRSession::CreatePresentationFrame() {
- XRFrame* presentation_frame = new XRFrame(this);
+ XRFrame* presentation_frame = MakeGarbageCollected<XRFrame>(this);
if (base_pose_matrix_) {
presentation_frame->SetBasePoseMatrix(*base_pose_matrix_);
}
@@ -574,7 +589,8 @@ void XRSession::OnInputStateChange(
for (const auto& input_state : input_states) {
XRInputSource* input_source = input_sources_.at(input_state->source_id);
if (!input_source) {
- input_source = new XRInputSource(this, input_state->source_id);
+ input_source =
+ MakeGarbageCollected<XRInputSource>(this, input_state->source_id);
input_sources_.Set(input_state->source_id, input_source);
devices_changed = true;
}
@@ -599,7 +615,7 @@ void XRSession::OnInputStateChange(
if (devices_changed) {
DispatchEvent(
- *XRSessionEvent::Create(EventTypeNames::inputsourceschange, this));
+ *XRSessionEvent::Create(event_type_names::kInputsourceschange, this));
}
}
@@ -612,7 +628,7 @@ void XRSession::OnSelectStart(XRInputSource* input_source) {
input_source->selection_cancelled = false;
XRInputSourceEvent* event =
- CreateInputSourceEvent(EventTypeNames::selectstart, input_source);
+ CreateInputSourceEvent(event_type_names::kSelectstart, input_source);
DispatchEvent(*event);
if (event->defaultPrevented())
@@ -634,7 +650,7 @@ void XRSession::OnSelectEnd(XRInputSource* input_source) {
LocalFrame::NotifyUserActivation(frame);
XRInputSourceEvent* event =
- CreateInputSourceEvent(EventTypeNames::selectend, input_source);
+ CreateInputSourceEvent(event_type_names::kSelectend, input_source);
DispatchEvent(*event);
if (event->defaultPrevented())
@@ -654,13 +670,13 @@ void XRSession::OnSelect(XRInputSource* input_source) {
if (!input_source->selection_cancelled) {
XRInputSourceEvent* event =
- CreateInputSourceEvent(EventTypeNames::select, input_source);
+ CreateInputSourceEvent(event_type_names::kSelect, input_source);
DispatchEvent(*event);
}
}
void XRSession::OnPoseReset() {
- DispatchEvent(*XRSessionEvent::Create(EventTypeNames::resetpose, this));
+ DispatchEvent(*XRSessionEvent::Create(event_type_names::kResetpose, this));
}
void XRSession::UpdateInputSourceState(
@@ -752,8 +768,8 @@ const HeapVector<Member<XRView>>& XRSession::views() {
if (immersive_) {
// If we don't already have the views allocated, do so now.
if (views_.IsEmpty()) {
- views_.push_back(new XRView(this, XRView::kEyeLeft));
- views_.push_back(new XRView(this, XRView::kEyeRight));
+ views_.push_back(MakeGarbageCollected<XRView>(this, XRView::kEyeLeft));
+ views_.push_back(MakeGarbageCollected<XRView>(this, XRView::kEyeRight));
}
// In immersive mode the projection and view matrices must be aligned with
// the device's physical optics.
@@ -765,7 +781,7 @@ const HeapVector<Member<XRView>>& XRSession::views() {
depth_far_);
} else {
if (views_.IsEmpty()) {
- views_.push_back(new XRView(this, XRView::kEyeLeft));
+ views_.push_back(MakeGarbageCollected<XRView>(this, XRView::kEyeLeft));
views_[XRView::kEyeLeft]->UpdateOffset(0, 0, 0);
}
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_session.h b/chromium/third_party/blink/renderer/modules/xr/xr_session.h
index 293b9035134..21cae6dd4af 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_session.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_session.h
@@ -74,18 +74,18 @@ class XRSession final : public EventTargetWithInlineData,
XRLayer* baseLayer() const { return base_layer_; }
void setBaseLayer(XRLayer* value);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resetpose);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(end);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(blur, kBlur);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(focus, kFocus);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(resetpose, kResetpose);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(end, kEnd);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(selectend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart, kSelectstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(selectend, kSelectend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(select, kSelect);
ScriptPromise requestFrameOfReference(ScriptState*,
const String& type,
- const XRFrameOfReferenceOptions&);
+ const XRFrameOfReferenceOptions*);
int requestAnimationFrame(V8XRFrameRequestCallback*);
void cancelAnimationFrame(int id);
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_session_event.cc b/chromium/third_party/blink/renderer/modules/xr/xr_session_event.cc
index bb7fdbd862e..8a683ff3768 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_session_event.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_session_event.cc
@@ -12,16 +12,16 @@ XRSessionEvent::XRSessionEvent(const AtomicString& type, XRSession* session)
: Event(type, Bubbles::kNo, Cancelable::kYes), session_(session) {}
XRSessionEvent::XRSessionEvent(const AtomicString& type,
- const XRSessionEventInit& initializer)
+ const XRSessionEventInit* initializer)
: Event(type, initializer) {
- if (initializer.hasSession())
- session_ = initializer.session();
+ if (initializer->hasSession())
+ session_ = initializer->session();
}
XRSessionEvent::~XRSessionEvent() = default;
const AtomicString& XRSessionEvent::InterfaceName() const {
- return EventNames::XRSessionEvent;
+ return event_interface_names::kXRSessionEvent;
}
void XRSessionEvent::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_session_event.h b/chromium/third_party/blink/renderer/modules/xr/xr_session_event.h
index fa99848c3e4..ecfd00e5d06 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_session_event.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_session_event.h
@@ -15,16 +15,21 @@ class XRSessionEvent final : public Event {
DEFINE_WRAPPERTYPEINFO();
public:
- static XRSessionEvent* Create() { return new XRSessionEvent; }
+ static XRSessionEvent* Create() {
+ return MakeGarbageCollected<XRSessionEvent>();
+ }
static XRSessionEvent* Create(const AtomicString& type, XRSession* session) {
- return new XRSessionEvent(type, session);
+ return MakeGarbageCollected<XRSessionEvent>(type, session);
}
static XRSessionEvent* Create(const AtomicString& type,
- const XRSessionEventInit& initializer) {
- return new XRSessionEvent(type, initializer);
+ const XRSessionEventInit* initializer) {
+ return MakeGarbageCollected<XRSessionEvent>(type, initializer);
}
+ XRSessionEvent();
+ XRSessionEvent(const AtomicString& type, XRSession*);
+ XRSessionEvent(const AtomicString& type, const XRSessionEventInit*);
~XRSessionEvent() override;
XRSession* session() const { return session_.Get(); }
@@ -34,10 +39,6 @@ class XRSessionEvent final : public Event {
void Trace(blink::Visitor*) override;
private:
- XRSessionEvent();
- XRSessionEvent(const AtomicString& type, XRSession*);
- XRSessionEvent(const AtomicString& type, const XRSessionEventInit&);
-
Member<XRSession> session_;
};
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.cc b/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.cc
index 99f98b4a820..a9f62d52bb6 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.cc
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.cc
@@ -38,7 +38,7 @@ double ClampToRange(const double value, const double min, const double max) {
XRWebGLLayer* XRWebGLLayer::Create(
XRSession* session,
const WebGLRenderingContextOrWebGL2RenderingContext& context,
- const XRWebGLLayerInit& initializer,
+ const XRWebGLLayerInit* initializer,
ExceptionState& exception_state) {
if (session->ended()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
@@ -68,15 +68,15 @@ XRWebGLLayer* XRWebGLLayer::Create(
return nullptr;
}
- bool want_antialiasing = initializer.antialias();
- bool want_depth_buffer = initializer.depth();
- bool want_stencil_buffer = initializer.stencil();
- bool want_alpha_channel = initializer.alpha();
- bool want_multiview = initializer.multiview();
+ bool want_antialiasing = initializer->antialias();
+ bool want_depth_buffer = initializer->depth();
+ bool want_stencil_buffer = initializer->stencil();
+ bool want_alpha_channel = initializer->alpha();
+ bool want_multiview = initializer->multiview();
double framebuffer_scale = 1.0;
- if (initializer.hasFramebufferScaleFactor()) {
+ if (initializer->hasFramebufferScaleFactor()) {
// The max size will be either the native resolution or the default
// if that happens to be larger than the native res. (That can happen on
// desktop systems.)
@@ -86,7 +86,7 @@ XRWebGLLayer* XRWebGLLayer::Create(
// small to see or unreasonably large.
// TODO: Would be best to have the max value communicated from the service
// rather than limited to the native res.
- framebuffer_scale = ClampToRange(initializer.framebufferScaleFactor(),
+ framebuffer_scale = ClampToRange(initializer->framebufferScaleFactor(),
kFramebufferMinScale, max_scale);
}
@@ -110,8 +110,9 @@ XRWebGLLayer* XRWebGLLayer::Create(
return nullptr;
}
- return new XRWebGLLayer(session, webgl_context, std::move(drawing_buffer),
- framebuffer, framebuffer_scale);
+ return MakeGarbageCollected<XRWebGLLayer>(session, webgl_context,
+ std::move(drawing_buffer),
+ framebuffer, framebuffer_scale);
}
XRWebGLLayer::XRWebGLLayer(XRSession* session,
@@ -196,13 +197,13 @@ void XRWebGLLayer::UpdateViewports() {
viewports_dirty_ = false;
if (session()->immersive()) {
- left_viewport_ =
- new XRViewport(0, 0, framebuffer_width * 0.5 * viewport_scale_,
- framebuffer_height * viewport_scale_);
- right_viewport_ =
- new XRViewport(framebuffer_width * 0.5 * viewport_scale_, 0,
- framebuffer_width * 0.5 * viewport_scale_,
- framebuffer_height * viewport_scale_);
+ left_viewport_ = MakeGarbageCollected<XRViewport>(
+ 0, 0, framebuffer_width * 0.5 * viewport_scale_,
+ framebuffer_height * viewport_scale_);
+ right_viewport_ = MakeGarbageCollected<XRViewport>(
+ framebuffer_width * 0.5 * viewport_scale_, 0,
+ framebuffer_width * 0.5 * viewport_scale_,
+ framebuffer_height * viewport_scale_);
session()->device()->frameProvider()->UpdateWebGLLayerViewports(this);
@@ -243,8 +244,9 @@ void XRWebGLLayer::UpdateViewports() {
FloatPoint(right, bottom));
}
} else {
- left_viewport_ = new XRViewport(0, 0, framebuffer_width * viewport_scale_,
- framebuffer_height * viewport_scale_);
+ left_viewport_ = MakeGarbageCollected<XRViewport>(
+ 0, 0, framebuffer_width * viewport_scale_,
+ framebuffer_height * viewport_scale_);
}
}
diff --git a/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.h b/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.h
index 6368b919df4..a23ece99225 100644
--- a/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.h
+++ b/chromium/third_party/blink/renderer/modules/xr/xr_webgl_layer.h
@@ -31,12 +31,17 @@ class XRWebGLLayer final : public XRLayer,
DEFINE_WRAPPERTYPEINFO();
public:
+ XRWebGLLayer(XRSession*,
+ WebGLRenderingContextBase*,
+ scoped_refptr<XRWebGLDrawingBuffer>,
+ WebGLFramebuffer*,
+ double framebuffer_scale);
~XRWebGLLayer() override;
static XRWebGLLayer* Create(
XRSession*,
const WebGLRenderingContextOrWebGL2RenderingContext&,
- const XRWebGLLayerInit&,
+ const XRWebGLLayerInit*,
ExceptionState&);
WebGLRenderingContextBase* context() const { return webgl_context_; }
@@ -84,12 +89,6 @@ class XRWebGLLayer final : public XRLayer,
void Trace(blink::Visitor*) override;
private:
- XRWebGLLayer(XRSession*,
- WebGLRenderingContextBase*,
- scoped_refptr<XRWebGLDrawingBuffer>,
- WebGLFramebuffer*,
- double framebuffer_scale);
-
Member<XRViewport> left_viewport_;
Member<XRViewport> right_viewport_;
diff --git a/chromium/third_party/blink/renderer/platform/BUILD.gn b/chromium/third_party/blink/renderer/platform/BUILD.gn
index 1f0518e9cc2..ba938f7d750 100644
--- a/chromium/third_party/blink/renderer/platform/BUILD.gn
+++ b/chromium/third_party/blink/renderer/platform/BUILD.gn
@@ -120,8 +120,8 @@ action("instrumentation_probes") {
executable("character_data_generator") {
sources = [
+ "text/character_property_data.h",
"text/character_property_data_generator.cc",
- "text/character_property_data_generator.h",
]
configs += [ "//third_party/blink/renderer:config" ]
deps = [
@@ -262,6 +262,7 @@ jumbo_component("platform") {
visibility = [
"//components/pdf/common:interfaces_blink",
"//services/device/public/mojom:mojom_blink",
+ "//services/media_session/public/mojom:mojom_blink",
"//third_party/blink/*",
"//url/mojom:url_mojom_origin_blink",
"//url/mojom:url_mojom_gurl_blink",
@@ -408,6 +409,8 @@ jumbo_component("platform") {
"audio/vector_math_scalar.h",
"bindings/active_script_wrappable_base.cc",
"bindings/active_script_wrappable_base.h",
+ "bindings/binding_security_for_platform.cc",
+ "bindings/binding_security_for_platform.h",
"bindings/callback_function_base.cc",
"bindings/callback_function_base.h",
"bindings/callback_interface_base.cc",
@@ -478,11 +481,8 @@ jumbo_component("platform") {
"bindings/v8_throw_exception.h",
"bindings/v8_value_cache.cc",
"bindings/v8_value_cache.h",
- "bindings/wrapper_creation_security_check.cc",
- "bindings/wrapper_creation_security_check.h",
"bindings/wrapper_type_info.cc",
"bindings/wrapper_type_info.h",
- "calculation_value.h",
"content_decryption_module_result.h",
"content_setting_callbacks.cc",
"content_setting_callbacks.h",
@@ -519,7 +519,6 @@ jumbo_component("platform") {
"exported/web_content_decryption_module_result.cc",
"exported/web_content_decryption_module_session.cc",
"exported/web_content_setting_callbacks.cc",
- "exported/web_cors.cc",
"exported/web_crypto_algorithm.cc",
"exported/web_crypto_key.cc",
"exported/web_crypto_key_algorithm.cc",
@@ -679,8 +678,6 @@ jumbo_component("platform") {
"fonts/opentype/open_type_vertical_data.h",
"fonts/orientation_iterator.cc",
"fonts/orientation_iterator.h",
- "fonts/paint_font.h",
- "fonts/paint_text_blob.h",
"fonts/script_run_iterator.cc",
"fonts/script_run_iterator.h",
"fonts/segmented_font_data.cc",
@@ -691,6 +688,7 @@ jumbo_component("platform") {
"fonts/shaping/caching_word_shaper.h",
"fonts/shaping/case_mapping_harfbuzz_buffer_filler.cc",
"fonts/shaping/case_mapping_harfbuzz_buffer_filler.h",
+ "fonts/shaping/glyph_bounds_accumulator.h",
"fonts/shaping/harfbuzz_face.cc",
"fonts/shaping/harfbuzz_face.h",
"fonts/shaping/harfbuzz_font_cache.h",
@@ -711,6 +709,8 @@ jumbo_component("platform") {
"fonts/shaping/shape_result_spacing.h",
"fonts/shaping/shape_result_test_info.cc",
"fonts/shaping/shape_result_test_info.h",
+ "fonts/shaping/shape_result_view.cc",
+ "fonts/shaping/shape_result_view.h",
"fonts/shaping/shaping_line_breaker.cc",
"fonts/shaping/shaping_line_breaker.h",
"fonts/simple_font_data.cc",
@@ -747,6 +747,7 @@ jumbo_component("platform") {
"fonts/win/font_fallback_win.h",
"fonts/win/font_platform_data_win.cc",
"geometry/blend.h",
+ "geometry/calculation_value.h",
"geometry/cg/float_point_cg.cc",
"geometry/cg/float_rect_cg.cc",
"geometry/cg/float_size_cg.cc",
@@ -793,6 +794,15 @@ jumbo_component("platform") {
"geometry/layout_rect_outsets.h",
"geometry/layout_size.cc",
"geometry/layout_size.h",
+ "geometry/layout_unit.cc",
+ "geometry/layout_unit.h",
+ "geometry/length.cc",
+ "geometry/length.h",
+ "geometry/length_box.h",
+ "geometry/length_functions.cc",
+ "geometry/length_functions.h",
+ "geometry/length_point.h",
+ "geometry/length_size.h",
"geometry/region.cc",
"geometry/region.h",
"graphics/accelerated_static_bitmap_image.cc",
@@ -816,8 +826,6 @@ jumbo_component("platform") {
"graphics/canvas_color_params.cc",
"graphics/canvas_color_params.h",
"graphics/canvas_heuristic_parameters.h",
- "graphics/canvas_metrics.cc",
- "graphics/canvas_metrics.h",
"graphics/canvas_resource.cc",
"graphics/canvas_resource.h",
"graphics/canvas_resource_dispatcher.cc",
@@ -1028,6 +1036,8 @@ jumbo_component("platform") {
"graphics/paint/geometry_mapper_transform_cache.h",
"graphics/paint/hit_test_data.cc",
"graphics/paint/hit_test_data.h",
+ "graphics/paint/hit_test_display_item.cc",
+ "graphics/paint/hit_test_display_item.h",
"graphics/paint/paint_artifact.cc",
"graphics/paint/paint_artifact.h",
"graphics/paint/paint_canvas.h",
@@ -1081,6 +1091,7 @@ jumbo_component("platform") {
"graphics/picture_snapshot.h",
"graphics/placeholder_image.cc",
"graphics/placeholder_image.h",
+ "graphics/platform_paint_worklet_input.h",
"graphics/profiling_canvas.cc",
"graphics/profiling_canvas.h",
"graphics/replaying_canvas.cc",
@@ -1157,17 +1168,6 @@ jumbo_component("platform") {
"keyboard_codes.h",
"language.cc",
"language.h",
- "layout_test_support.cc",
- "layout_test_support.h",
- "layout_unit.cc",
- "layout_unit.h",
- "length.cc",
- "length.h",
- "length_box.h",
- "length_functions.cc",
- "length_functions.h",
- "length_point.h",
- "length_size.h",
"lifecycle_notifier.h",
"lifecycle_observer.h",
"link_hash.cc",
@@ -1210,7 +1210,6 @@ jumbo_component("platform") {
"mojo/bluetooth_struct_traits.h",
"mojo/canonical_cookie_mojom_traits.cc",
"mojo/canonical_cookie_mojom_traits.h",
- "mojo/fetch_api_request_struct_traits.cc",
"mojo/interface_invalidator.cc",
"mojo/interface_invalidator.h",
"mojo/mojo_helper.h",
@@ -1245,7 +1244,6 @@ jumbo_component("platform") {
"scroll/scroll_alignment.h",
"scroll/scroll_snap_data.h",
"scroll/scroll_types.h",
- "scroll/web_scrollbar_theme_client.h",
"serialized_resource.h",
"shared_buffer.cc",
"shared_buffer.h",
@@ -1272,6 +1270,7 @@ jumbo_component("platform") {
"text/character.h",
"text/character_emoji.cc",
"text/character_property.h",
+ "text/character_property_data.h",
"text/date_time_format.cc",
"text/date_time_format.h",
"text/decode_escape_sequences.h",
@@ -1295,8 +1294,6 @@ jumbo_component("platform") {
"text/mac/hyphenation_mac.cc",
"text/platform_locale.cc",
"text/platform_locale.h",
- "text/quoted_printable.cc",
- "text/quoted_printable.h",
"text/segmented_string.cc",
"text/segmented_string.h",
"text/suffix_tree.h",
@@ -1367,8 +1364,9 @@ jumbo_component("platform") {
"web_mouse_event.cc",
"web_mouse_wheel_event.cc",
"web_pointer_event.cc",
- "web_task_runner.cc",
"web_task_runner.h",
+ "web_test_support.cc",
+ "web_test_support.h",
"web_text_input_info.cc",
"web_thread_supporting_gc.cc",
"web_thread_supporting_gc.h",
@@ -1382,7 +1380,6 @@ jumbo_component("platform") {
"weborigin/origin_access_entry.cc",
"weborigin/origin_access_entry.h",
"weborigin/referrer.h",
- "weborigin/referrer_policy.h",
"weborigin/scheme_registry.cc",
"weborigin/scheme_registry.h",
"weborigin/security_origin.cc",
@@ -1440,7 +1437,6 @@ jumbo_component("platform") {
"//third_party/blink/renderer/platform/heap",
"//third_party/blink/renderer/platform/instrumentation",
"//third_party/blink/renderer/platform/loader",
- "//third_party/blink/renderer/platform/media",
"//third_party/blink/renderer/platform/network",
"//third_party/blink/renderer/platform/scheduler",
]
@@ -1463,10 +1459,19 @@ jumbo_component("platform") {
"//third_party/blink/public/common",
"//third_party/ced",
"//third_party/icu",
+ "//third_party/webrtc/p2p:rtc_p2p",
+ "//third_party/webrtc_overrides:init_webrtc",
+ "//third_party/zlib/google:compression_utils",
+ "//ui/base:base",
"//ui/gfx",
"//ui/gfx/geometry",
]
+ # This is faster on armv7, untested on other CPUs (e.g. mips, power, etc).
+ # TODO(cavalcantii): add next xxhash.
+ defines = [ "USE_FUNCTION_CITYHASH" ]
+ deps += [ "//third_party/smhasher:cityhash" ]
+
if (is_mac) {
sources -= [
"fonts/skia/font_cache_skia.cc",
@@ -1574,15 +1579,17 @@ jumbo_static_library("test_support") {
"testing/picture_matchers.h",
"testing/scoped_fake_plugin_registry.cc",
"testing/scoped_fake_plugin_registry.h",
+ "testing/scoped_main_thread_overrider.cc",
+ "testing/scoped_main_thread_overrider.h",
"testing/scoped_mocked_url.cc",
"testing/scoped_mocked_url.h",
+ "testing/scoped_scheduler_overrider.cc",
+ "testing/scoped_scheduler_overrider.h",
"testing/stub_graphics_layer_client.h",
"testing/test_paint_artifact.cc",
"testing/test_paint_artifact.h",
"testing/testing_platform_support.cc",
"testing/testing_platform_support.h",
- "testing/testing_platform_support_with_custom_scheduler.cc",
- "testing/testing_platform_support_with_custom_scheduler.h",
"testing/testing_platform_support_with_mock_scheduler.cc",
"testing/testing_platform_support_with_mock_scheduler.h",
"testing/testing_platform_support_with_web_rtc.cc",
@@ -1662,7 +1669,6 @@ jumbo_source_set("blink_platform_unittests_sources") {
"drag_image_test.cc",
"exported/file_path_conversion_test.cc",
"exported/web_canonical_cookie_test.cc",
- "exported/web_cors_test.cc",
"exported/web_string_test.cc",
"fonts/android/font_cache_android_test.cc",
"fonts/bitmap_glyphs_blacklist_test.cc",
@@ -1684,6 +1690,7 @@ jumbo_source_set("blink_platform_unittests_sources") {
"fonts/shaping/harfbuzz_shaper_test.cc",
"fonts/shaping/run_segmenter_test.cc",
"fonts/shaping/shape_result_bloberizer_test.cc",
+ "fonts/shaping/shape_result_view_test.cc",
"fonts/shaping/shaping_line_breaker_test.cc",
"fonts/small_caps_iterator_test.cc",
"fonts/symbols_iterator_test.cc",
@@ -1705,6 +1712,7 @@ jumbo_source_set("blink_platform_unittests_sources") {
"geometry/int_rect_test.cc",
"geometry/layout_rect_test.cc",
"geometry/layout_size_test.cc",
+ "geometry/layout_unit_test.cc",
"geometry/region_test.cc",
"graphics/accelerated_static_bitmap_image_test.cc",
"graphics/bitmap_image_test.cc",
@@ -1737,7 +1745,6 @@ jumbo_source_set("blink_platform_unittests_sources") {
"graphics/paint/paint_controller_test.h",
"graphics/paint/paint_property_node_test.cc",
"graphics/paint/paint_record_builder_test.cc",
- "graphics/paint/property_tree_state_test.cc",
"graphics/paint/raster_invalidator_test.cc",
"graphics/paint_invalidation_reason_test.cc",
"graphics/path_test.cc",
@@ -1760,8 +1767,8 @@ jumbo_source_set("blink_platform_unittests_sources") {
"image-decoders/webp/webp_image_decoder_test.cc",
"json/json_parser_test.cc",
"json/json_values_test.cc",
- "layout_unit_test.cc",
"lifecycle_context_test.cc",
+ "loader/cors/cors_test.cc",
"mac/graphics_context_canvas_test.mm",
"mac/version_util_mac_test.mm",
"mhtml/mhtml_parser_test.cc",
@@ -1798,7 +1805,6 @@ jumbo_source_set("blink_platform_unittests_sources") {
"uuid_test.cc",
"web_icon_sizes_parser_test.cc",
"web_screen_info_test.cc",
- "web_task_runner_test.cc",
"web_vector_test.cc",
"weborigin/known_ports_test.cc",
"weborigin/kurl_test.cc",
@@ -1921,7 +1927,7 @@ group("blink_platform_unittests_data") {
# Required by some image decoder tests.
"image-decoders/testing/",
- "//third_party/WebKit/LayoutTests/images/resources/",
+ "//third_party/blink/web_tests/images/resources/",
]
}
@@ -1985,7 +1991,7 @@ fuzzer_test("mhtml_parser_fuzzer") {
":platform",
]
dict = "//testing/libfuzzer/fuzzers/dicts/mhtml.dict"
- seed_corpus = "//third_party/WebKit/LayoutTests/mhtml"
+ seed_corpus = "//third_party/blink/web_tests/mhtml"
additional_configs = [
"//third_party/blink/renderer/platform/wtf:wtf_config",
"//third_party/blink/renderer:config",
@@ -2016,8 +2022,8 @@ fuzzer_test("blink_png_decoder_fuzzer") {
dict = "//testing/libfuzzer/fuzzers/dicts/png.dict"
seed_corpuses = [
"//components/viz/test/data",
- "//third_party/WebKit/LayoutTests/images/png-suite/samples",
- "//third_party/WebKit/LayoutTests/images/resources/pngfuzz",
+ "//third_party/blink/web_tests/images/png-suite/samples",
+ "//third_party/blink/web_tests/images/resources/pngfuzz",
]
}
@@ -2095,6 +2101,7 @@ jumbo_source_set("unit_tests") {
"graphics/canvas_2d_layer_bridge_test.cc",
"graphics/canvas_color_params_test.cc",
"graphics/canvas_resource_dispatcher_test.cc",
+ "graphics/canvas_resource_provider_test.cc",
"graphics/canvas_resource_test.cc",
"graphics/color_correction_test_utils.cc",
"graphics/deferred_image_decoder_test.cc",
@@ -2106,6 +2113,7 @@ jumbo_source_set("unit_tests") {
"graphics/test/fake_canvas_resource_host.h",
"graphics/test/fake_gles2_interface.h",
"graphics/test/fake_web_graphics_context_3d_provider.h",
+ "graphics/test/gpu_memory_buffer_test_platform.h",
"graphics/test/mock_compositor_frame_sink.h",
"graphics/test/mock_embedded_frame_sink_provider.h",
"graphics/test/mock_image_decoder.h",
diff --git a/chromium/third_party/blink/renderer/platform/DEPS b/chromium/third_party/blink/renderer/platform/DEPS
index 9c6e6535946..86b4080429c 100644
--- a/chromium/third_party/blink/renderer/platform/DEPS
+++ b/chromium/third_party/blink/renderer/platform/DEPS
@@ -34,8 +34,8 @@ include_rules = [
"+base/strings/string_util.h",
"+base/strings/stringprintf.h",
"+base/synchronization/waitable_event.h",
- "+base/sys_info.h",
"+base/android/sys_utils.h",
+ "+base/system/sys_info.h",
"+base/task/sequence_manager/task_time_observer.h",
"+base/test",
"+base/test/fuzzed_data_provider.h",
@@ -56,7 +56,6 @@ include_rules = [
"+mozilla",
"+services/metrics/public/cpp/ukm_entry_builder.h",
"+services/metrics/public/cpp/ukm_recorder.h",
- "+services/network/public/mojom/data_pipe_getter.mojom-blink.h",
"+services/viz/public/interfaces/compositing/compositor_frame_sink.mojom-blink.h",
"+skia/ext",
#TODO(nverne): remove this
@@ -81,4 +80,8 @@ specific_include_rules = {
"ukm_time_aggregator_test.cc" : [
"+components/ukm/test_ukm_recorder.h"
],
+ "data_resource_helper.cc" : [
+ "+third_party/zlib/google/compression_utils.h",
+ "+ui/base/resource",
+ ],
}
diff --git a/chromium/third_party/blink/renderer/platform/OWNERS b/chromium/third_party/blink/renderer/platform/OWNERS
index a6ca217c757..bd19319ac19 100644
--- a/chromium/third_party/blink/renderer/platform/OWNERS
+++ b/chromium/third_party/blink/renderer/platform/OWNERS
@@ -7,7 +7,6 @@ fserb@chromium.org
haraken@chromium.org
jbroman@chromium.org
jochen@chromium.org
-junov@chromium.org
kbr@chromium.org
kinuko@chromium.org
mkwst@chromium.org
diff --git a/chromium/third_party/blink/renderer/platform/animation/DEPS b/chromium/third_party/blink/renderer/platform/animation/DEPS
index d15d7b3e622..7ec486a7f3a 100644
--- a/chromium/third_party/blink/renderer/platform/animation/DEPS
+++ b/chromium/third_party/blink/renderer/platform/animation/DEPS
@@ -10,7 +10,6 @@ include_rules = [
"+third_party/blink/renderer/platform/geometry",
"+third_party/blink/renderer/platform/graphics",
"+third_party/blink/renderer/platform/heap",
- "+third_party/blink/renderer/platform/layout_unit.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/runtime_enabled_features.h",
"+third_party/blink/renderer/platform/testing",
diff --git a/chromium/third_party/blink/renderer/platform/animation/animated_layers_test.cc b/chromium/third_party/blink/renderer/platform/animation/animated_layers_test.cc
index 1b278094dae..b2f469936ca 100644
--- a/chromium/third_party/blink/renderer/platform/animation/animated_layers_test.cc
+++ b/chromium/third_party/blink/renderer/platform/animation/animated_layers_test.cc
@@ -69,8 +69,8 @@ TEST_P(AnimatedLayersTest, updateLayerShouldFlattenTransformWithAnimations) {
*CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE)));
std::unique_ptr<CompositorKeyframeModel> float_keyframe_model(
- CompositorKeyframeModel::Create(*curve, CompositorTargetProperty::OPACITY,
- 0, 0));
+ CompositorKeyframeModel::Create(
+ *curve, compositor_target_property::OPACITY, 0, 0));
int keyframe_model_id = float_keyframe_model->Id();
std::unique_ptr<CompositorAnimationTimeline> compositor_timeline =
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_animation.cc b/chromium/third_party/blink/renderer/platform/animation/compositor_animation.cc
index 547ea225b6b..093ef251f11 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_animation.cc
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_animation.cc
@@ -81,9 +81,13 @@ void CompositorAnimation::AbortKeyframeModel(int keyframe_model_id) {
animation_->AbortKeyframeModel(keyframe_model_id);
}
-void CompositorAnimation::UpdateScrollTimelineId(
- base::Optional<cc::ElementId> element_id) {
- cc::ToWorkletAnimation(animation_.get())->SetScrollSourceId(element_id);
+void CompositorAnimation::UpdateScrollTimeline(
+ base::Optional<cc::ElementId> element_id,
+ base::Optional<double> start_scroll_offset,
+ base::Optional<double> end_scroll_offset) {
+ cc::ToWorkletAnimation(animation_.get())
+ ->UpdateScrollTimeline(element_id, start_scroll_offset,
+ end_scroll_offset);
}
void CompositorAnimation::NotifyAnimationStarted(base::TimeTicks monotonic_time,
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_animation.h b/chromium/third_party/blink/renderer/platform/animation/compositor_animation.h
index c604a1847a3..8781610df20 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_animation.h
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_animation.h
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace cc {
class AnimationCurve;
@@ -60,7 +61,9 @@ class PLATFORM_EXPORT CompositorAnimation : public cc::AnimationDelegate {
void PauseKeyframeModel(int keyframe_model_id, double time_offset);
void AbortKeyframeModel(int keyframe_model_id);
- void UpdateScrollTimelineId(base::Optional<cc::ElementId>);
+ void UpdateScrollTimeline(base::Optional<cc::ElementId>,
+ base::Optional<double> start_scroll_offset,
+ base::Optional<double> end_scroll_offset);
private:
// cc::AnimationDelegate implementation.
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_animation_test.cc b/chromium/third_party/blink/renderer/platform/animation/compositor_animation_test.cc
index 99644785f25..32ed3418410 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_animation_test.cc
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_animation_test.cc
@@ -64,21 +64,21 @@ TEST_F(CompositorAnimationTest, NullDelegate) {
CompositorFloatAnimationCurve::Create();
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
CompositorKeyframeModel::Create(
- *curve, CompositorTargetProperty::TRANSFORM, 1, 0);
+ *curve, compositor_target_property::TRANSFORM, 1, 0);
animation->AddKeyframeModel(std::move(keyframe_model));
animation->SetAnimationDelegate(delegate.get());
EXPECT_FALSE(delegate->finished_);
cc_animation->NotifyKeyframeModelFinishedForTesting(
- CompositorTargetProperty::TRANSFORM, 1);
+ compositor_target_property::TRANSFORM, 1);
EXPECT_TRUE(delegate->finished_);
delegate->ResetFlags();
animation->SetAnimationDelegate(nullptr);
cc_animation->NotifyKeyframeModelFinishedForTesting(
- CompositorTargetProperty::TRANSFORM, 1);
+ compositor_target_property::TRANSFORM, 1);
EXPECT_FALSE(delegate->finished_);
}
@@ -94,15 +94,15 @@ TEST_F(CompositorAnimationTest, NotifyFromCCAfterCompositorAnimationDeletion) {
std::unique_ptr<CompositorAnimationCurve> curve =
CompositorFloatAnimationCurve::Create();
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
- CompositorKeyframeModel::Create(*curve, CompositorTargetProperty::OPACITY,
- 1, 0);
+ CompositorKeyframeModel::Create(
+ *curve, compositor_target_property::OPACITY, 1, 0);
animation->AddKeyframeModel(std::move(keyframe_model));
animation->SetAnimationDelegate(delegate.get());
EXPECT_FALSE(delegate->finished_);
cc_animation->NotifyKeyframeModelFinishedForTesting(
- CompositorTargetProperty::OPACITY, 1);
+ compositor_target_property::OPACITY, 1);
EXPECT_TRUE(delegate->finished_);
delegate->finished_ = false;
@@ -111,7 +111,7 @@ TEST_F(CompositorAnimationTest, NotifyFromCCAfterCompositorAnimationDeletion) {
// No notifications. Doesn't crash.
cc_animation->NotifyKeyframeModelFinishedForTesting(
- CompositorTargetProperty::OPACITY, 1);
+ compositor_target_property::OPACITY, 1);
EXPECT_FALSE(delegate->finished_);
}
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.cc b/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.cc
index eece33c5b20..32b814132bd 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.cc
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.cc
@@ -25,7 +25,7 @@ namespace blink {
CompositorKeyframeModel::CompositorKeyframeModel(
const CompositorAnimationCurve& curve,
- CompositorTargetProperty::Type target_property,
+ compositor_target_property::Type target_property,
int keyframe_model_id,
int group_id) {
if (!keyframe_model_id)
@@ -48,11 +48,16 @@ int CompositorKeyframeModel::Group() const {
return keyframe_model_->group();
}
-CompositorTargetProperty::Type CompositorKeyframeModel::TargetProperty() const {
- return static_cast<CompositorTargetProperty::Type>(
+compositor_target_property::Type CompositorKeyframeModel::TargetProperty()
+ const {
+ return static_cast<compositor_target_property::Type>(
keyframe_model_->target_property_id());
}
+void CompositorKeyframeModel::SetElementId(CompositorElementId element_id) {
+ keyframe_model_->set_element_id(element_id);
+}
+
double CompositorKeyframeModel::Iterations() const {
return keyframe_model_->iterations();
}
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.h b/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.h
index 86d4a5bdfb6..b9a0db9a246 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.h
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model.h
@@ -10,6 +10,7 @@
#include "base/memory/ptr_util.h"
#include "cc/animation/keyframe_model.h"
#include "third_party/blink/renderer/platform/animation/compositor_target_property.h"
+#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
@@ -32,7 +33,7 @@ class PLATFORM_EXPORT CompositorKeyframeModel {
static std::unique_ptr<CompositorKeyframeModel> Create(
const blink::CompositorAnimationCurve& curve,
- CompositorTargetProperty::Type target,
+ compositor_target_property::Type target,
int group_id,
int keyframe_model_id) {
return base::WrapUnique(new CompositorKeyframeModel(
@@ -45,7 +46,9 @@ class PLATFORM_EXPORT CompositorKeyframeModel {
int Id() const;
int Group() const;
- CompositorTargetProperty::Type TargetProperty() const;
+ compositor_target_property::Type TargetProperty() const;
+
+ void SetElementId(CompositorElementId element_id);
// This is the number of times that the animation will play. If this
// value is zero the animation will not play. If it is negative, then
@@ -77,7 +80,7 @@ class PLATFORM_EXPORT CompositorKeyframeModel {
private:
CompositorKeyframeModel(const CompositorAnimationCurve&,
- CompositorTargetProperty::Type,
+ compositor_target_property::Type,
int keyframe_model_id,
int group_id);
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model_test.cc b/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model_test.cc
index 2ab711bb7f7..a7b63b4668c 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model_test.cc
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_keyframe_model_test.cc
@@ -13,8 +13,8 @@ TEST(WebCompositorAnimationTest, DefaultSettings) {
std::unique_ptr<CompositorAnimationCurve> curve =
CompositorFloatAnimationCurve::Create();
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
- CompositorKeyframeModel::Create(*curve, CompositorTargetProperty::OPACITY,
- 1, 0);
+ CompositorKeyframeModel::Create(
+ *curve, compositor_target_property::OPACITY, 1, 0);
// Ensure that the defaults are correct.
EXPECT_EQ(1, keyframe_model->Iterations());
@@ -28,8 +28,8 @@ TEST(WebCompositorAnimationTest, ModifiedSettings) {
std::unique_ptr<CompositorFloatAnimationCurve> curve =
CompositorFloatAnimationCurve::Create();
std::unique_ptr<CompositorKeyframeModel> keyframe_model =
- CompositorKeyframeModel::Create(*curve, CompositorTargetProperty::OPACITY,
- 1, 0);
+ CompositorKeyframeModel::Create(
+ *curve, compositor_target_property::OPACITY, 1, 0);
keyframe_model->SetIterations(2);
keyframe_model->SetStartTime(2);
keyframe_model->SetTimeOffset(2);
diff --git a/chromium/third_party/blink/renderer/platform/animation/compositor_target_property.h b/chromium/third_party/blink/renderer/platform/animation/compositor_target_property.h
index b0222f3082e..964bdb2742f 100644
--- a/chromium/third_party/blink/renderer/platform/animation/compositor_target_property.h
+++ b/chromium/third_party/blink/renderer/platform/animation/compositor_target_property.h
@@ -9,7 +9,7 @@
namespace blink {
-namespace CompositorTargetProperty = cc::TargetProperty;
+namespace compositor_target_property = cc::TargetProperty;
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_array.h b/chromium/third_party/blink/renderer/platform/audio/audio_array.h
index fa07821c804..674aa6956e7 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_array.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_array.h
@@ -60,7 +60,7 @@ class AudioArray {
// unsigned in zeroRange() and copyToRange(). Also check for integer
// overflow.
CHECK_LE(n, std::numeric_limits<unsigned>::max() / sizeof(T));
- unsigned initial_size = sizeof(T) * n;
+ uint32_t initial_size = static_cast<uint32_t>(sizeof(T) * n);
#if defined(ARCH_CPU_X86_FAMILY) || defined(WTF_USE_WEBAUDIO_FFMPEG) || \
defined(WTF_USE_WEBAUDIO_OPENMAX_DL_FFT)
@@ -90,7 +90,7 @@ class AudioArray {
if (aligned_data == allocation || extra_allocation_bytes == kAlignment) {
allocation_ = allocation;
aligned_data_ = aligned_data;
- size_ = n;
+ size_ = static_cast<uint32_t>(n);
is_allocation_good = true;
} else {
// always allocate extra after the first alignment failure.
@@ -102,7 +102,7 @@ class AudioArray {
T* Data() { return aligned_data_; }
const T* Data() const { return aligned_data_; }
- size_t size() const { return size_; }
+ uint32_t size() const { return size_; }
T& at(size_t i) {
// Note that although it is a size_t, m_size is now guaranteed to be
@@ -148,7 +148,7 @@ class AudioArray {
T* allocation_;
T* aligned_data_;
- size_t size_;
+ uint32_t size_;
};
typedef AudioArray<float> AudioFloatArray;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_bus.cc b/chromium/third_party/blink/renderer/platform/audio/audio_bus.cc
index 2b68239b1f1..98a5f1621ae 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_bus.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_bus.cc
@@ -44,7 +44,7 @@
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
const unsigned kMaxBusChannels = 32;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_channel.cc b/chromium/third_party/blink/renderer/platform/audio/audio_channel.cc
index afa322cbb5a..e62d8396bfa 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_channel.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_channel.cc
@@ -35,7 +35,7 @@
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
void AudioChannel::ResizeSmaller(size_t new_length) {
DCHECK_LE(new_length, length_);
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.cc b/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.cc
index 97130f3e33f..bf97e5418ed 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.cc
@@ -61,14 +61,14 @@ size_t AudioDelayDSPKernel::BufferLengthForDelay(double max_delay_time,
// Compute the length of the buffer needed to handle a max delay of
// |maxDelayTime|. One is added to handle the case where the actual delay
// equals the maximum delay.
- return 1 + AudioUtilities::TimeToSampleFrame(max_delay_time, sample_rate);
+ return 1 + audio_utilities::TimeToSampleFrame(max_delay_time, sample_rate);
}
bool AudioDelayDSPKernel::HasSampleAccurateValues() {
return false;
}
-void AudioDelayDSPKernel::CalculateSampleAccurateValues(float*, size_t) {
+void AudioDelayDSPKernel::CalculateSampleAccurateValues(float*, uint32_t) {
NOTREACHED();
}
@@ -78,7 +78,7 @@ double AudioDelayDSPKernel::DelayTime(float sample_rate) {
void AudioDelayDSPKernel::Process(const float* source,
float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
size_t buffer_length = buffer_.size();
float* buffer = buffer_.Data();
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.h b/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.h
index 3cfed07d62b..cecc59b797f 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_delay_dsp_kernel.h
@@ -37,7 +37,7 @@ class PLATFORM_EXPORT AudioDelayDSPKernel : public AudioDSPKernel {
void Process(const float* source,
float* destination,
- size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
void Reset() override;
double MaxDelayTime() const { return max_delay_time_; }
@@ -56,7 +56,7 @@ class PLATFORM_EXPORT AudioDelayDSPKernel : public AudioDSPKernel {
virtual bool HasSampleAccurateValues();
virtual void CalculateSampleAccurateValues(float* delay_times,
- size_t frames_to_process);
+ uint32_t frames_to_process);
virtual double DelayTime(float sample_rate);
AudioFloatArray buffer_;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_destination.cc b/chromium/third_party/blink/renderer/platform/audio/audio_destination.cc
index 5e740515fed..6f99b28263c 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_destination.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_destination.cc
@@ -40,7 +40,7 @@
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -64,14 +64,14 @@ AudioDestination::AudioDestination(AudioIOCallback& callback,
unsigned number_of_output_channels,
const WebAudioLatencyHint& latency_hint)
: number_of_output_channels_(number_of_output_channels),
- is_playing_(false),
+ play_state_(PlayState::kStopped),
fifo_(
std::make_unique<PushPullFIFO>(number_of_output_channels, kFIFOSize)),
output_bus_(AudioBus::Create(number_of_output_channels,
- AudioUtilities::kRenderQuantumFrames,
+ audio_utilities::kRenderQuantumFrames,
false)),
render_bus_(AudioBus::Create(number_of_output_channels,
- AudioUtilities::kRenderQuantumFrames)),
+ audio_utilities::kRenderQuantumFrames)),
callback_(callback),
frames_elapsed_(0) {
// Create WebAudioDevice. blink::WebAudioDevice is designed to support the
@@ -88,7 +88,7 @@ AudioDestination::AudioDestination(AudioIOCallback& callback,
// first FIFO pulls from causing "underflow" errors.
const unsigned priming_render_quanta =
ceil(callback_buffer_size_ /
- static_cast<float>(AudioUtilities::kRenderQuantumFrames));
+ static_cast<float>(audio_utilities::kRenderQuantumFrames));
for (unsigned i = 0; i < priming_render_quanta; ++i) {
fifo_->Push(render_bus_.get());
}
@@ -169,11 +169,11 @@ void AudioDestination::RequestRender(size_t frames_requested,
base::TimeTicks received_timestamp = base::TimeTicks::Now();
for (size_t pushed_frames = 0; pushed_frames < frames_to_render;
- pushed_frames += AudioUtilities::kRenderQuantumFrames) {
+ pushed_frames += audio_utilities::kRenderQuantumFrames) {
// If platform buffer is more than two times longer than |framesToProcess|
// we do not want output position to get stuck so we promote it
// using the elapsed time from the moment it was initially obtained.
- if (callback_buffer_size_ > AudioUtilities::kRenderQuantumFrames * 2) {
+ if (callback_buffer_size_ > audio_utilities::kRenderQuantumFrames * 2) {
double delta = (base::TimeTicks::Now() - received_timestamp).InSecondsF();
output_position.position += delta;
output_position.timestamp += delta;
@@ -185,8 +185,8 @@ void AudioDestination::RequestRender(size_t frames_requested,
output_position.position = 0.0;
// Process WebAudio graph and push the rendered output to FIFO.
- callback_.Render(render_bus_.get(),
- AudioUtilities::kRenderQuantumFrames, output_position);
+ callback_.Render(render_bus_.get(), audio_utilities::kRenderQuantumFrames,
+ output_position);
fifo_->Push(render_bus_.get());
}
@@ -198,10 +198,10 @@ void AudioDestination::Start() {
DCHECK(IsMainThread());
// Start the "audio device" after the rendering thread is ready.
- if (web_audio_device_ && !is_playing_) {
+ if (web_audio_device_ && play_state_ == PlayState::kStopped) {
TRACE_EVENT0("webaudio", "AudioDestination::Start");
web_audio_device_->Start();
- is_playing_ = true;
+ play_state_ = PlayState::kPlaying;
}
}
@@ -209,11 +209,11 @@ void AudioDestination::StartWithWorkletTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> worklet_task_runner) {
DCHECK(IsMainThread());
- if (web_audio_device_ && !is_playing_) {
+ if (web_audio_device_ && play_state_ == PlayState::kStopped) {
TRACE_EVENT0("webaudio", "AudioDestination::Start");
worklet_task_runner_ = std::move(worklet_task_runner);
web_audio_device_->Start();
- is_playing_ = true;
+ play_state_ = PlayState::kPlaying;
}
}
@@ -222,11 +222,27 @@ void AudioDestination::Stop() {
// This assumes stopping the "audio device" is synchronous and dumping the
// rendering thread is safe after that.
- if (web_audio_device_ && is_playing_) {
+ if (web_audio_device_ && play_state_ != PlayState::kStopped) {
TRACE_EVENT0("webaudio", "AudioDestination::Stop");
web_audio_device_->Stop();
worklet_task_runner_ = nullptr;
- is_playing_ = false;
+ play_state_ = PlayState::kStopped;
+ }
+}
+
+void AudioDestination::Pause() {
+ DCHECK(IsMainThread());
+ if (web_audio_device_ && play_state_ == PlayState::kPlaying) {
+ web_audio_device_->Pause();
+ play_state_ = PlayState::kPaused;
+ }
+}
+
+void AudioDestination::Resume() {
+ DCHECK(IsMainThread());
+ if (web_audio_device_ && play_state_ == PlayState::kPaused) {
+ web_audio_device_->Resume();
+ play_state_ = PlayState::kPlaying;
}
}
@@ -237,7 +253,7 @@ size_t AudioDestination::CallbackBufferSize() const {
bool AudioDestination::IsPlaying() {
DCHECK(IsMainThread());
- return is_playing_;
+ return play_state_ == PlayState::kPlaying;
}
int AudioDestination::FramesPerBuffer() const {
@@ -253,9 +269,8 @@ float AudioDestination::HardwareSampleRate() {
return static_cast<float>(Platform::Current()->AudioHardwareSampleRate());
}
-unsigned long AudioDestination::MaxChannelCount() {
- return static_cast<unsigned long>(
- Platform::Current()->AudioHardwareOutputChannels());
+uint32_t AudioDestination::MaxChannelCount() {
+ return Platform::Current()->AudioHardwareOutputChannels();
}
bool AudioDestination::CheckBufferSize() {
@@ -275,8 +290,9 @@ bool AudioDestination::CheckBufferSize() {
// Check if the requested buffer size is too large.
bool is_buffer_size_valid =
- callback_buffer_size_ + AudioUtilities::kRenderQuantumFrames <= kFIFOSize;
- DCHECK_LE(callback_buffer_size_ + AudioUtilities::kRenderQuantumFrames,
+ callback_buffer_size_ + audio_utilities::kRenderQuantumFrames <=
+ kFIFOSize;
+ DCHECK_LE(callback_buffer_size_ + audio_utilities::kRenderQuantumFrames,
kFIFOSize);
return is_buffer_size_valid;
}
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_destination.h b/chromium/third_party/blink/renderer/platform/audio/audio_destination.h
index bca1f5c4153..a6a93e629bd 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_destination.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_destination.h
@@ -91,6 +91,8 @@ class PLATFORM_EXPORT AudioDestination
virtual void Start();
virtual void Stop();
+ virtual void Pause();
+ virtual void Resume();
// Starts the destination with the AudioWorklet support.
void StartWithWorkletTaskRunner(
@@ -109,9 +111,11 @@ class PLATFORM_EXPORT AudioDestination
// The information from the actual audio hardware. (via Platform::current)
static float HardwareSampleRate();
- static unsigned long MaxChannelCount();
+ static uint32_t MaxChannelCount();
private:
+ enum class PlayState { kStopped, kPlaying, kPaused };
+
// Check if the buffer size chosen by the WebAudioDevice is too large.
bool CheckBufferSize();
@@ -121,7 +125,7 @@ class PLATFORM_EXPORT AudioDestination
std::unique_ptr<WebAudioDevice> web_audio_device_;
const unsigned number_of_output_channels_;
size_t callback_buffer_size_;
- bool is_playing_;
+ PlayState play_state_;
// The task runner for AudioWorklet operation. This is only valid when
// the AudioWorklet is activated.
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel.h b/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel.h
index 04127347748..cee15210bf9 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel.h
@@ -56,10 +56,10 @@ class PLATFORM_EXPORT AudioDSPKernel {
// reset DSP state.
virtual void Process(const float* source,
float* destination,
- size_t frames_to_process) = 0;
+ uint32_t frames_to_process) = 0;
// Subclasses that have AudioParams must override this to process the
// AudioParams.
- virtual void ProcessOnlyAudioParams(size_t frames_to_process){};
+ virtual void ProcessOnlyAudioParams(uint32_t frames_to_process){};
virtual void Reset() = 0;
float SampleRate() const { return sample_rate_; }
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.cc b/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.cc
index e15026be65f..c945bbb972b 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.cc
@@ -67,7 +67,7 @@ void AudioDSPKernelProcessor::Uninitialize() {
void AudioDSPKernelProcessor::Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(source);
DCHECK(destination);
if (!source || !destination)
@@ -98,7 +98,8 @@ void AudioDSPKernelProcessor::Process(const AudioBus* source,
}
}
-void AudioDSPKernelProcessor::ProcessOnlyAudioParams(size_t frames_to_process) {
+void AudioDSPKernelProcessor::ProcessOnlyAudioParams(
+ uint32_t frames_to_process) {
if (!IsInitialized())
return;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.h b/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.h
index 3f405d04451..50ac6c7fb79 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_dsp_kernel_processor.h
@@ -63,8 +63,8 @@ class PLATFORM_EXPORT AudioDSPKernelProcessor : public AudioProcessor {
void Uninitialize() override;
void Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) override;
- void ProcessOnlyAudioParams(size_t frames_to_process) override;
+ uint32_t frames_to_process) override;
+ void ProcessOnlyAudioParams(uint32_t frames_to_process) override;
void Reset() override;
void SetNumberOfChannels(unsigned) override;
unsigned NumberOfChannels() const override { return number_of_channels_; }
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_io_callback.h b/chromium/third_party/blink/renderer/platform/audio/audio_io_callback.h
index e97f83a8a0c..99f0372823a 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_io_callback.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_io_callback.h
@@ -49,7 +49,7 @@ class AudioIOCallback {
// Called periodically to get the next render quantum of audio into
// |destination_bus|.
virtual void Render(AudioBus* destination_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
const AudioIOPosition& output_position) = 0;
virtual ~AudioIOCallback() = default;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_processor.h b/chromium/third_party/blink/renderer/platform/audio/audio_processor.h
index 895eb796aa4..1fdd14091cc 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_processor.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_processor.h
@@ -63,12 +63,12 @@ class PLATFORM_EXPORT AudioProcessor {
// in source and destination.
virtual void Process(const AudioBus* source,
AudioBus* destination,
- size_t frames_to_process) = 0;
+ uint32_t frames_to_process) = 0;
// Forces all AudioParams in the processor to run the timeline,
// bypassing any other processing the processor would do in
// process().
- virtual void ProcessOnlyAudioParams(size_t frames_to_process){};
+ virtual void ProcessOnlyAudioParams(uint32_t frames_to_process){};
// Resets filter state
virtual void Reset() = 0;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_resampler.cc b/chromium/third_party/blink/renderer/platform/audio/audio_resampler.cc
index e9cfa894182..b22fe6a9b2c 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_resampler.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_resampler.cc
@@ -62,7 +62,7 @@ void AudioResampler::ConfigureChannels(unsigned number_of_channels) {
void AudioResampler::Process(AudioSourceProvider* provider,
AudioBus* destination_bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(provider);
if (!provider)
return;
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_resampler.h b/chromium/third_party/blink/renderer/platform/audio/audio_resampler.h
index 5f667ed954d..17ea917e402 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_resampler.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_resampler.h
@@ -53,7 +53,7 @@ class PLATFORM_EXPORT AudioResampler {
// destinationBus.
void Process(AudioSourceProvider*,
AudioBus* destination_bus,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Resets the processing state.
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.cc b/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.cc
index 9a24777a14f..1ea00b17bac 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.cc
@@ -44,7 +44,7 @@ AudioResamplerKernel::AudioResamplerKernel(AudioResampler* resampler)
}
float* AudioResamplerKernel::GetSourcePointer(
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t* number_of_source_frames_needed_p) {
DCHECK_LE(frames_to_process, kMaxFramesToProcess);
@@ -76,7 +76,7 @@ float* AudioResamplerKernel::GetSourcePointer(
}
void AudioResamplerKernel::Process(float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK_LE(frames_to_process, kMaxFramesToProcess);
float* source = source_buffer_.Data();
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.h b/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.h
index a8d2e427b16..d47fcdd6e76 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_resampler_kernel.h
@@ -50,14 +50,14 @@ class PLATFORM_EXPORT AudioResamplerKernel {
// be copied. This sample data provides the input to the resampler when
// process() is called. framesToProcess must be less than or equal to
// MaxFramesToProcess.
- float* GetSourcePointer(size_t frames_to_process,
+ float* GetSourcePointer(uint32_t frames_to_process,
size_t* number_of_source_frames_needed);
// process() resamples framesToProcess frames from the source into
// destination. Each call to process() must be preceded by a call to
// getSourcePointer() so that source input may be supplied. framesToProcess
// must be less than or equal to MaxFramesToProcess.
- void Process(float* destination, size_t frames_to_process);
+ void Process(float* destination, uint32_t frames_to_process);
// Resets the processing state.
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_source_provider.h b/chromium/third_party/blink/renderer/platform/audio/audio_source_provider.h
index 174658c08a5..d673dd9e775 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_source_provider.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_source_provider.h
@@ -49,7 +49,7 @@ class PLATFORM_EXPORT AudioSourceProvider {
// provideInput() gets called repeatedly to render time-slices of a continuous
// audio stream.
- virtual void ProvideInput(AudioBus* bus, size_t frames_to_process) = 0;
+ virtual void ProvideInput(AudioBus* bus, uint32_t frames_to_process) = 0;
// If a client is set, we call it back when the audio format is available or
// changes.
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_source_provider_client.h b/chromium/third_party/blink/renderer/platform/audio/audio_source_provider_client.h
index c1537a14925..2d77c44a5cd 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_source_provider_client.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_source_provider_client.h
@@ -33,7 +33,7 @@ namespace blink {
class AudioSourceProviderClient : public GarbageCollectedMixin {
public:
- virtual void SetFormat(size_t number_of_channels, float sample_rate) = 0;
+ virtual void SetFormat(uint32_t number_of_channels, float sample_rate) = 0;
// Oilpan: Callers should keep this object alive during lock() and unlock().
virtual void lock() {}
virtual void unlock() {}
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_utilities.cc b/chromium/third_party/blink/renderer/platform/audio/audio_utilities.cc
index 4489753411f..f15d3762411 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_utilities.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_utilities.cc
@@ -29,7 +29,7 @@
namespace blink {
-namespace AudioUtilities {
+namespace audio_utilities {
float DecibelsToLinear(float decibels) {
return powf(10, 0.05f * decibels);
@@ -101,6 +101,6 @@ bool IsPowerOfTwo(size_t x) {
return x > 0 && ((x & (x - 1)) == 0);
}
-} // namespace AudioUtilities
+} // namespace audio_utilities
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/audio/audio_utilities.h b/chromium/third_party/blink/renderer/platform/audio/audio_utilities.h
index 9855db93a24..94cdb94bddb 100644
--- a/chromium/third_party/blink/renderer/platform/audio/audio_utilities.h
+++ b/chromium/third_party/blink/renderer/platform/audio/audio_utilities.h
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/platform/platform_export.h"
namespace blink {
-namespace AudioUtilities {
+namespace audio_utilities {
// Rendering quantum size. This is how many frames are processed at a time for
// each node in the audio graph.
@@ -60,7 +60,7 @@ PLATFORM_EXPORT float MaxAudioBufferSampleRate();
// Check to see if x is a power of two. If x == 0, returns false.
PLATFORM_EXPORT bool IsPowerOfTwo(size_t x);
-} // namespace AudioUtilities
+} // namespace audio_utilities
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_AUDIO_UTILITIES_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/biquad.cc b/chromium/third_party/blink/renderer/platform/audio/biquad.cc
index a97089040c0..188ea251226 100644
--- a/chromium/third_party/blink/renderer/platform/audio/biquad.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/biquad.cc
@@ -60,11 +60,11 @@ Biquad::Biquad() : has_sample_accurate_values_(false) {
// Allocate enough space for the a-rate filter coefficients to handle a
// rendering quantum of 128 frames.
- b0_.Allocate(AudioUtilities::kRenderQuantumFrames);
- b1_.Allocate(AudioUtilities::kRenderQuantumFrames);
- b2_.Allocate(AudioUtilities::kRenderQuantumFrames);
- a1_.Allocate(AudioUtilities::kRenderQuantumFrames);
- a2_.Allocate(AudioUtilities::kRenderQuantumFrames);
+ b0_.Allocate(audio_utilities::kRenderQuantumFrames);
+ b1_.Allocate(audio_utilities::kRenderQuantumFrames);
+ b2_.Allocate(audio_utilities::kRenderQuantumFrames);
+ a1_.Allocate(audio_utilities::kRenderQuantumFrames);
+ a2_.Allocate(audio_utilities::kRenderQuantumFrames);
// Initialize as pass-thru (straight-wire, no filter effect)
SetNormalizedCoefficients(0, 1, 0, 0, 1, 0, 0);
@@ -76,7 +76,7 @@ Biquad::~Biquad() = default;
void Biquad::Process(const float* source_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
// WARNING: sourceP and destP may be pointing to the same area of memory!
// Be sure to read from sourceP before writing to destP!
if (HasSampleAccurateValues()) {
@@ -195,7 +195,7 @@ void Biquad::Process(const float* source_p,
void Biquad::ProcessFast(const float* source_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
double filter_coefficients[5];
filter_coefficients[0] = b0_[0];
filter_coefficients[1] = b1_[0];
@@ -233,7 +233,7 @@ void Biquad::ProcessFast(const float* source_p,
void Biquad::ProcessSliceFast(double* source_p,
double* dest_p,
double* coefficients_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
// Use double-precision for filter stability
vDSP_deq22D(source_p, 1, coefficients_p, dest_p, 1, frames_to_process);
diff --git a/chromium/third_party/blink/renderer/platform/audio/biquad.h b/chromium/third_party/blink/renderer/platform/audio/biquad.h
index 6b6238040ee..30d9a2af52b 100644
--- a/chromium/third_party/blink/renderer/platform/audio/biquad.h
+++ b/chromium/third_party/blink/renderer/platform/audio/biquad.h
@@ -52,7 +52,9 @@ class PLATFORM_EXPORT Biquad final {
Biquad();
~Biquad();
- void Process(const float* source_p, float* dest_p, size_t frames_to_process);
+ void Process(const float* source_p,
+ float* dest_p,
+ uint32_t frames_to_process);
bool HasSampleAccurateValues() const { return has_sample_accurate_values_; }
void SetHasSampleAccurateValues(bool is_sample_accurate) {
@@ -113,11 +115,11 @@ class PLATFORM_EXPORT Biquad final {
#if defined(OS_MACOSX)
void ProcessFast(const float* source_p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void ProcessSliceFast(double* source_p,
double* dest_p,
double* coefficients_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
AudioDoubleArray input_buffer_;
AudioDoubleArray output_buffer_;
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/arm/vector_math_neon.h b/chromium/third_party/blink/renderer/platform/audio/cpu/arm/vector_math_neon.h
index f985fbd4b06..20e3945de70 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/arm/vector_math_neon.h
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/arm/vector_math_neon.h
@@ -12,11 +12,11 @@
#include "third_party/blink/renderer/platform/audio/vector_math_scalar.h"
namespace blink {
-namespace VectorMath {
-namespace NEON {
+namespace vector_math {
+namespace neon {
// TODO: Consider optimizing this.
-using Scalar::Conv;
+using scalar::Conv;
static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride1,
@@ -24,7 +24,7 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride1 == 1 && source_stride2 == 1 && dest_stride == 1) {
@@ -43,7 +43,7 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
n = tail_frames;
}
- Scalar::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
+ scalar::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, n);
}
@@ -53,7 +53,7 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1 && dest_stride == 1) {
@@ -71,14 +71,14 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
n = tail_frames;
}
- Scalar::Vclip(source_p, source_stride, low_threshold_p, high_threshold_p,
+ scalar::Vclip(source_p, source_stride, low_threshold_p, high_threshold_p,
dest_p, dest_stride, n);
}
static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1) {
@@ -101,7 +101,7 @@ static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
n = tail_frames;
}
- Scalar::Vmaxmgv(source_p, source_stride, max_p, n);
+ scalar::Vmaxmgv(source_p, source_stride, max_p, n);
}
static ALWAYS_INLINE void Vmul(const float* source1p,
@@ -110,7 +110,7 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride1 == 1 && source_stride2 == 1 && dest_stride == 1) {
@@ -129,7 +129,7 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
n = tail_frames;
}
- Scalar::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
+ scalar::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, n);
}
@@ -138,7 +138,7 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1 && dest_stride == 1) {
@@ -159,7 +159,7 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
n = tail_frames;
}
- Scalar::Vsma(source_p, source_stride, scale, dest_p, dest_stride, n);
+ scalar::Vsma(source_p, source_stride, scale, dest_p, dest_stride, n);
}
static ALWAYS_INLINE void Vsmul(const float* source_p,
@@ -167,7 +167,7 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1 && dest_stride == 1) {
@@ -185,13 +185,13 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
n = tail_frames;
}
- Scalar::Vsmul(source_p, source_stride, scale, dest_p, dest_stride, n);
+ scalar::Vsmul(source_p, source_stride, scale, dest_p, dest_stride, n);
}
static ALWAYS_INLINE void Vsvesq(const float* source_p,
int source_stride,
float* sum_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1) {
@@ -214,7 +214,7 @@ static ALWAYS_INLINE void Vsvesq(const float* source_p,
n = tail_frames;
}
- Scalar::Vsvesq(source_p, source_stride, sum_p, n);
+ scalar::Vsvesq(source_p, source_stride, sum_p, n);
}
static ALWAYS_INLINE void Zvmul(const float* real1p,
@@ -223,7 +223,7 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
unsigned i = 0;
unsigned end_size = frames_to_process - frames_to_process % 4;
@@ -242,12 +242,12 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
i += 4;
}
- Scalar::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
+ scalar::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
imag_dest_p + i, frames_to_process - i);
}
-} // namespace NEON
-} // namespace VectorMath
+} // namespace neon
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_CPU_ARM_VECTOR_MATH_NEON_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/mips/vector_math_msa.h b/chromium/third_party/blink/renderer/platform/audio/cpu/mips/vector_math_msa.h
index 90263606ee5..0b5428a9314 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/mips/vector_math_msa.h
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/mips/vector_math_msa.h
@@ -11,13 +11,13 @@
#include "third_party/blink/renderer/platform/cpu/mips/common_macros_msa.h"
namespace blink {
-namespace VectorMath {
-namespace MSA {
+namespace vector_math {
+namespace msa {
// TODO: Consider optimizing these.
-using Scalar::Conv;
-using Scalar::Vsvesq;
-using Scalar::Zvmul;
+using scalar::Conv;
+using scalar::Vsvesq;
+using scalar::Zvmul;
static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride1,
@@ -25,7 +25,7 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride1 == 1 && source_stride2 == 1 && dest_stride == 1) {
@@ -48,7 +48,7 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
}
}
- Scalar::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
+ scalar::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, n);
}
@@ -58,7 +58,7 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1 && dest_stride == 1) {
@@ -83,14 +83,14 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
}
}
- Scalar::Vclip(source_p, source_stride, low_threshold_p, high_threshold_p,
+ scalar::Vclip(source_p, source_stride, low_threshold_p, high_threshold_p,
dest_p, dest_stride, n);
}
static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1) {
@@ -115,7 +115,7 @@ static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
*max_p = std::max(*max_p, vMax[3]);
}
- Scalar::Vmaxmgv(source_p, source_stride, max_p, n);
+ scalar::Vmaxmgv(source_p, source_stride, max_p, n);
}
static ALWAYS_INLINE void Vmul(const float* source1p,
@@ -124,7 +124,7 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride1 == 1 && source_stride2 == 1 && dest_stride == 1) {
@@ -147,7 +147,7 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
}
}
- Scalar::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
+ scalar::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, n);
}
@@ -156,7 +156,7 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1 && dest_stride == 1) {
@@ -180,7 +180,7 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
}
}
- Scalar::Vsma(source_p, source_stride, scale, dest_p, dest_stride, n);
+ scalar::Vsma(source_p, source_stride, scale, dest_p, dest_stride, n);
}
static ALWAYS_INLINE void Vsmul(const float* source_p,
@@ -188,7 +188,7 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
int n = frames_to_process;
if (source_stride == 1 && dest_stride == 1) {
@@ -209,11 +209,11 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
}
}
- Scalar::Vsmul(source_p, source_stride, scale, dest_p, dest_stride, n);
+ scalar::Vsmul(source_p, source_stride, scale, dest_p, dest_stride, n);
}
-} // namespace MSA
-} // namespace VectorMath
+} // namespace msa
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_CPU_MIPS_VECTOR_MATH_MSA_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.cc b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.cc
index ade6f22898f..d613ff6a64e 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.cc
@@ -11,17 +11,17 @@
#include <immintrin.h>
namespace blink {
-namespace VectorMath {
-namespace AVX {
+namespace vector_math {
+namespace avx {
using MType = __m256;
-} // namespace AVX
-} // namespace VectorMath
+} // namespace avx
+} // namespace vector_math
} // namespace blink
#define MM_PS(name) _mm256_##name##_ps
-#define VECTOR_MATH_SIMD_NAMESPACE_NAME AVX
+#define VECTOR_MATH_SIMD_NAMESPACE_NAME avx
#include "third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h"
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.h b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.h
index 488df04affe..abe75ff23bc 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.h
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_avx.h
@@ -10,8 +10,8 @@
#include "third_party/blink/renderer/platform/audio/audio_array.h"
namespace blink {
-namespace VectorMath {
-namespace AVX {
+namespace vector_math {
+namespace avx {
constexpr size_t kBitsPerRegister = 256u;
constexpr size_t kPackedFloatsPerRegister = kBitsPerRegister / 32u;
@@ -26,7 +26,7 @@ bool IsAligned(const float*);
void Conv(const float* source_p,
const float* prepared_filter_p,
float* dest_p,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size);
void PrepareFilterForConv(const float* filter_p,
@@ -38,7 +38,7 @@ void PrepareFilterForConv(const float* filter_p,
void Vadd(const float* source1p,
const float* source2p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// dest[k] = clip(source[k], low_threshold, high_threshold)
// = max(low_threshold, min(high_threshold, source[k]))
@@ -46,32 +46,32 @@ void Vclip(const float* source_p,
const float* low_threshold_p,
const float* high_threshold_p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// *max_p = max(*max_p, source_max) where
// source_max = max(abs(source[k])) for all k
-void Vmaxmgv(const float* source_p, float* max_p, size_t frames_to_process);
+void Vmaxmgv(const float* source_p, float* max_p, uint32_t frames_to_process);
// dest[k] = source1[k] * source2[k]
void Vmul(const float* source1p,
const float* source2p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// dest[k] += scale * source[k]
void Vsma(const float* source_p,
const float* scale,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// dest[k] = scale * source[k]
void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// sum += sum(source[k]^2) for all k
-void Vsvesq(const float* source_p, float* sum_p, size_t frames_to_process);
+void Vsvesq(const float* source_p, float* sum_p, uint32_t frames_to_process);
// real_dest[k] = real1[k] * real2[k] - imag1[k] * imag2[k]
// imag_dest[k] = real1[k] * imag2[k] + imag1[k] * real2[k]
@@ -81,10 +81,10 @@ void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
-} // namespace AVX
-} // namespace VectorMath
+} // namespace avx
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_CPU_X86_VECTOR_MATH_AVX_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h
index ef87b87e120..5a81f88264f 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h
@@ -18,13 +18,13 @@
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
-namespace VectorMath {
+namespace vector_math {
namespace VECTOR_MATH_SIMD_NAMESPACE_NAME {
// This stride is chosen so that the same prepared filter created by
-// AVX::PrepareFilterForConv can be used by both AVX::Conv and SSE::Conv.
-// A prepared filter created by SSE::PrepareFilterForConv can only be used
-// by SSE::Conv.
+// AVX::PrepareFilterForConv can be used by both AVX::Conv and sse::Conv.
+// A prepared filter created by sse::PrepareFilterForConv can only be used
+// by sse::Conv.
constexpr size_t kReversedFilterStride = 8u / kPackedFloatsPerRegister;
bool IsAligned(const float* p) {
@@ -59,7 +59,7 @@ void PrepareFilterForConv(const float* filter_p,
void Conv(const float* source_p,
const float* prepared_filter_p,
float* dest_p,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size) {
const float* const dest_end_p = dest_p + frames_to_process;
@@ -98,7 +98,7 @@ void Conv(const float* source_p,
void Vadd(const float* source1p,
const float* source2p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float* const source1_end_p = source1p + frames_to_process;
DCHECK(IsAligned(source1p));
@@ -138,7 +138,7 @@ void Vclip(const float* source_p,
const float* low_threshold_p,
const float* high_threshold_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float* const source_end_p = source_p + frames_to_process;
DCHECK(IsAligned(source_p));
@@ -168,7 +168,7 @@ void Vclip(const float* source_p,
// *max_p = max(*max_p, source_max) where
// source_max = max(abs(source[k])) for all k
-void Vmaxmgv(const float* source_p, float* max_p, size_t frames_to_process) {
+void Vmaxmgv(const float* source_p, float* max_p, uint32_t frames_to_process) {
constexpr uint32_t kMask = 0x7FFFFFFFu;
const float* const source_end_p = source_p + frames_to_process;
@@ -198,7 +198,7 @@ void Vmaxmgv(const float* source_p, float* max_p, size_t frames_to_process) {
void Vmul(const float* source1p,
const float* source2p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float* const source1_end_p = source1p + frames_to_process;
DCHECK(IsAligned(source1p));
@@ -236,7 +236,7 @@ void Vmul(const float* source1p,
void Vsma(const float* source_p,
const float* scale,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float* const source_end_p = source_p + frames_to_process;
DCHECK(IsAligned(source_p));
@@ -267,7 +267,7 @@ void Vsma(const float* source_p,
void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float* const source_end_p = source_p + frames_to_process;
DCHECK(IsAligned(source_p));
@@ -294,7 +294,7 @@ void Vsmul(const float* source_p,
}
// sum += sum(source[k]^2) for all k
-void Vsvesq(const float* source_p, float* sum_p, size_t frames_to_process) {
+void Vsvesq(const float* source_p, float* sum_p, uint32_t frames_to_process) {
const float* const source_end_p = source_p + frames_to_process;
DCHECK(IsAligned(source_p));
@@ -322,7 +322,7 @@ void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(IsAligned(real1p));
DCHECK_EQ(0u, frames_to_process % kPackedFloatsPerRegister);
@@ -351,7 +351,7 @@ void Zvmul(const float* real1p,
}
} // namespace VECTOR_MATH_SIMD_NAMESPACE_NAME
-} // namespace VectorMath
+} // namespace vector_math
} // namespace blink
#endif // defined(ARCH_CPU_X86_FAMILY) && !defined(OS_MACOSX)
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.cc b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.cc
index f5c44968d10..582f8faa4af 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.cc
@@ -11,17 +11,17 @@
#include <xmmintrin.h>
namespace blink {
-namespace VectorMath {
-namespace SSE {
+namespace vector_math {
+namespace sse {
using MType = __m128;
-} // namespace SSE
-} // namespace VectorMath
+} // namespace sse
+} // namespace vector_math
} // namespace blink
#define MM_PS(name) _mm_##name##_ps
-#define VECTOR_MATH_SIMD_NAMESPACE_NAME SSE
+#define VECTOR_MATH_SIMD_NAMESPACE_NAME sse
#include "third_party/blink/renderer/platform/audio/cpu/x86/vector_math_impl.h"
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.h b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.h
index 14cd73ea95e..71ac06c58cb 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.h
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_sse.h
@@ -10,8 +10,8 @@
#include "third_party/blink/renderer/platform/audio/audio_array.h"
namespace blink {
-namespace VectorMath {
-namespace SSE {
+namespace vector_math {
+namespace sse {
constexpr size_t kBitsPerRegister = 128u;
constexpr size_t kPackedFloatsPerRegister = kBitsPerRegister / 32u;
@@ -26,7 +26,7 @@ bool IsAligned(const float*);
void Conv(const float* source_p,
const float* prepared_filter_p,
float* dest_p,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size);
void PrepareFilterForConv(const float* filter_p,
@@ -38,7 +38,7 @@ void PrepareFilterForConv(const float* filter_p,
void Vadd(const float* source1p,
const float* source2p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// dest[k] = clip(source[k], low_threshold, high_threshold)
// = max(low_threshold, min(high_threshold, source[k]))
@@ -46,32 +46,32 @@ void Vclip(const float* source_p,
const float* low_threshold_p,
const float* high_threshold_p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// *max_p = max(*max_p, source_max) where
// source_max = max(abs(source[k])) for all k
-void Vmaxmgv(const float* source_p, float* max_p, size_t frames_to_process);
+void Vmaxmgv(const float* source_p, float* max_p, uint32_t frames_to_process);
// dest[k] = source1[k] * source2[k]
void Vmul(const float* source1p,
const float* source2p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// dest[k] += scale * source[k]
void Vsma(const float* source_p,
const float* scale,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// dest[k] = scale * source[k]
void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// sum += sum(source[k]^2) for all k
-void Vsvesq(const float* source_p, float* sum_p, size_t frames_to_process);
+void Vsvesq(const float* source_p, float* sum_p, uint32_t frames_to_process);
// real_dest[k] = real1[k] * real2[k] - imag1[k] * imag2[k]
// imag_dest[k] = real1[k] * imag2[k] + imag1[k] * real2[k]
@@ -81,10 +81,10 @@ void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
-} // namespace SSE
-} // namespace VectorMath
+} // namespace sse
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_CPU_X86_VECTOR_MATH_SSE_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h
index f023b8f2dc1..3aa112f30c0 100644
--- a/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h
+++ b/chromium/third_party/blink/renderer/platform/audio/cpu/x86/vector_math_x86.h
@@ -12,8 +12,8 @@
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
-namespace VectorMath {
-namespace X86 {
+namespace vector_math {
+namespace x86 {
struct FrameCounts {
size_t scalar_for_alignment;
@@ -29,7 +29,7 @@ static bool CPUSupportsAVX() {
}
static size_t GetAVXAlignmentOffsetInNumberOfFloats(const float* source_p) {
- constexpr size_t kBytesPerRegister = AVX::kBitsPerRegister / 8u;
+ constexpr size_t kBytesPerRegister = avx::kBitsPerRegister / 8u;
constexpr size_t kAlignmentOffsetMask = kBytesPerRegister - 1u;
size_t offset = reinterpret_cast<size_t>(source_p) & kAlignmentOffsetMask;
DCHECK_EQ(0u, offset % sizeof(*source_p));
@@ -37,7 +37,7 @@ static size_t GetAVXAlignmentOffsetInNumberOfFloats(const float* source_p) {
}
static ALWAYS_INLINE FrameCounts
-SplitFramesToProcess(const float* source_p, size_t frames_to_process) {
+SplitFramesToProcess(const float* source_p, uint32_t frames_to_process) {
FrameCounts counts = {0u, 0u, 0u, 0u, 0u};
const size_t avx_alignment_offset =
@@ -46,43 +46,43 @@ SplitFramesToProcess(const float* source_p, size_t frames_to_process) {
// If the first frame is not AVX aligned, the first several frames (at most
// seven) must be processed separately for proper alignment.
const size_t total_for_alignment =
- (AVX::kPackedFloatsPerRegister - avx_alignment_offset) &
- ~AVX::kFramesToProcessMask;
+ (avx::kPackedFloatsPerRegister - avx_alignment_offset) &
+ ~avx::kFramesToProcessMask;
const size_t scalar_for_alignment =
- total_for_alignment & ~SSE::kFramesToProcessMask;
+ total_for_alignment & ~sse::kFramesToProcessMask;
const size_t sse_for_alignment =
- total_for_alignment & SSE::kFramesToProcessMask;
+ total_for_alignment & sse::kFramesToProcessMask;
// Check which CPU features can be used based on the number of frames to
// process and based on CPU support.
const bool use_at_least_avx =
CPUSupportsAVX() &&
frames_to_process >= scalar_for_alignment + sse_for_alignment +
- AVX::kPackedFloatsPerRegister;
+ avx::kPackedFloatsPerRegister;
const bool use_at_least_sse =
use_at_least_avx ||
- frames_to_process >= scalar_for_alignment + SSE::kPackedFloatsPerRegister;
+ frames_to_process >= scalar_for_alignment + sse::kPackedFloatsPerRegister;
if (use_at_least_sse) {
counts.scalar_for_alignment = scalar_for_alignment;
frames_to_process -= counts.scalar_for_alignment;
// The remaining frames are SSE aligned.
- DCHECK(SSE::IsAligned(source_p + counts.scalar_for_alignment));
+ DCHECK(sse::IsAligned(source_p + counts.scalar_for_alignment));
if (use_at_least_avx) {
counts.sse_for_alignment = sse_for_alignment;
frames_to_process -= counts.sse_for_alignment;
// The remaining frames are AVX aligned.
- DCHECK(AVX::IsAligned(source_p + counts.scalar_for_alignment +
+ DCHECK(avx::IsAligned(source_p + counts.scalar_for_alignment +
counts.sse_for_alignment));
// Process as many as possible of the remaining frames using AVX.
- counts.avx = frames_to_process & AVX::kFramesToProcessMask;
+ counts.avx = frames_to_process & avx::kFramesToProcessMask;
frames_to_process -= counts.avx;
}
// Process as many as possible of the remaining frames using SSE.
- counts.sse = frames_to_process & SSE::kFramesToProcessMask;
+ counts.sse = frames_to_process & sse::kFramesToProcessMask;
frames_to_process -= counts.sse;
}
@@ -97,10 +97,10 @@ static ALWAYS_INLINE void PrepareFilterForConv(
size_t filter_size,
AudioFloatArray* prepared_filter) {
if (CPUSupportsAVX()) {
- AVX::PrepareFilterForConv(filter_p, filter_stride, filter_size,
+ avx::PrepareFilterForConv(filter_p, filter_stride, filter_size,
prepared_filter);
} else {
- SSE::PrepareFilterForConv(filter_p, filter_stride, filter_size,
+ sse::PrepareFilterForConv(filter_p, filter_stride, filter_size,
prepared_filter);
}
}
@@ -111,30 +111,30 @@ static ALWAYS_INLINE void Conv(const float* source_p,
int filter_stride,
float* dest_p,
int dest_stride,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size,
const AudioFloatArray* prepared_filter) {
const float* prepared_filter_p =
prepared_filter ? prepared_filter->Data() : nullptr;
if (source_stride == 1 && dest_stride == 1 && prepared_filter_p) {
- if (CPUSupportsAVX() && (filter_size & ~AVX::kFramesToProcessMask) == 0u) {
+ if (CPUSupportsAVX() && (filter_size & ~avx::kFramesToProcessMask) == 0u) {
// |frames_to_process| is always a multiply of render quantum and
// therefore the frames can always be processed using AVX.
- CHECK_EQ(frames_to_process & ~AVX::kFramesToProcessMask, 0u);
- AVX::Conv(source_p, prepared_filter_p, dest_p, frames_to_process,
+ CHECK_EQ(frames_to_process & ~avx::kFramesToProcessMask, 0u);
+ avx::Conv(source_p, prepared_filter_p, dest_p, frames_to_process,
filter_size);
return;
}
- if ((filter_size & ~SSE::kFramesToProcessMask) == 0u) {
+ if ((filter_size & ~sse::kFramesToProcessMask) == 0u) {
// |frames_to_process| is always a multiply of render quantum and
// therefore the frames can always be processed using SSE.
- CHECK_EQ(frames_to_process & ~SSE::kFramesToProcessMask, 0u);
- SSE::Conv(source_p, prepared_filter_p, dest_p, frames_to_process,
+ CHECK_EQ(frames_to_process & ~sse::kFramesToProcessMask, 0u);
+ sse::Conv(source_p, prepared_filter_p, dest_p, frames_to_process,
filter_size);
return;
}
}
- Scalar::Conv(source_p, source_stride, filter_p, filter_stride, dest_p,
+ scalar::Conv(source_p, source_stride, filter_p, filter_stride, dest_p,
dest_stride, frames_to_process, filter_size, nullptr);
}
@@ -144,32 +144,32 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride1 == 1 && source_stride2 == 1 && dest_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source1p, frames_to_process);
- Scalar::Vadd(source1p, 1, source2p, 1, dest_p, 1,
+ scalar::Vadd(source1p, 1, source2p, 1, dest_p, 1,
frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vadd(source1p + i, source2p + i, dest_p + i,
+ sse::Vadd(source1p + i, source2p + i, dest_p + i,
frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vadd(source1p + i, source2p + i, dest_p + i, frame_counts.avx);
+ avx::Vadd(source1p + i, source2p + i, dest_p + i, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vadd(source1p + i, source2p + i, dest_p + i, frame_counts.sse);
+ sse::Vadd(source1p + i, source2p + i, dest_p + i, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vadd(source1p + i, 1, source2p + i, 1, dest_p + i, 1,
+ scalar::Vadd(source1p + i, 1, source2p + i, 1, dest_p + i, 1,
frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
+ scalar::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, frames_to_process);
}
}
@@ -180,34 +180,34 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride == 1 && dest_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source_p, frames_to_process);
- Scalar::Vclip(source_p, 1, low_threshold_p, high_threshold_p, dest_p, 1,
+ scalar::Vclip(source_p, 1, low_threshold_p, high_threshold_p, dest_p, 1,
frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vclip(source_p + i, low_threshold_p, high_threshold_p, dest_p + i,
+ sse::Vclip(source_p + i, low_threshold_p, high_threshold_p, dest_p + i,
frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vclip(source_p + i, low_threshold_p, high_threshold_p, dest_p + i,
+ avx::Vclip(source_p + i, low_threshold_p, high_threshold_p, dest_p + i,
frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vclip(source_p + i, low_threshold_p, high_threshold_p, dest_p + i,
+ sse::Vclip(source_p + i, low_threshold_p, high_threshold_p, dest_p + i,
frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vclip(source_p + i, 1, low_threshold_p, high_threshold_p,
+ scalar::Vclip(source_p + i, 1, low_threshold_p, high_threshold_p,
dest_p + i, 1, frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vclip(source_p, source_stride, low_threshold_p, high_threshold_p,
+ scalar::Vclip(source_p, source_stride, low_threshold_p, high_threshold_p,
dest_p, dest_stride, frames_to_process);
}
}
@@ -215,29 +215,29 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source_p, frames_to_process);
- Scalar::Vmaxmgv(source_p, 1, max_p, frame_counts.scalar_for_alignment);
+ scalar::Vmaxmgv(source_p, 1, max_p, frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vmaxmgv(source_p + i, max_p, frame_counts.sse_for_alignment);
+ sse::Vmaxmgv(source_p + i, max_p, frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vmaxmgv(source_p + i, max_p, frame_counts.avx);
+ avx::Vmaxmgv(source_p + i, max_p, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vmaxmgv(source_p + i, max_p, frame_counts.sse);
+ sse::Vmaxmgv(source_p + i, max_p, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vmaxmgv(source_p + i, 1, max_p, frame_counts.scalar);
+ scalar::Vmaxmgv(source_p + i, 1, max_p, frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vmaxmgv(source_p, source_stride, max_p, frames_to_process);
+ scalar::Vmaxmgv(source_p, source_stride, max_p, frames_to_process);
}
}
@@ -247,32 +247,32 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride1 == 1 && source_stride2 == 1 && dest_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source1p, frames_to_process);
- Scalar::Vmul(source1p, 1, source2p, 1, dest_p, 1,
+ scalar::Vmul(source1p, 1, source2p, 1, dest_p, 1,
frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vmul(source1p + i, source2p + i, dest_p + i,
+ sse::Vmul(source1p + i, source2p + i, dest_p + i,
frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vmul(source1p + i, source2p + i, dest_p + i, frame_counts.avx);
+ avx::Vmul(source1p + i, source2p + i, dest_p + i, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vmul(source1p + i, source2p + i, dest_p + i, frame_counts.sse);
+ sse::Vmul(source1p + i, source2p + i, dest_p + i, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vmul(source1p + i, 1, source2p + i, 1, dest_p + i, 1,
+ scalar::Vmul(source1p + i, 1, source2p + i, 1, dest_p + i, 1,
frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
+ scalar::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, frames_to_process);
}
}
@@ -282,31 +282,31 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride == 1 && dest_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source_p, frames_to_process);
- Scalar::Vsma(source_p, 1, scale, dest_p, 1,
+ scalar::Vsma(source_p, 1, scale, dest_p, 1,
frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vsma(source_p + i, scale, dest_p + i,
+ sse::Vsma(source_p + i, scale, dest_p + i,
frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vsma(source_p + i, scale, dest_p + i, frame_counts.avx);
+ avx::Vsma(source_p + i, scale, dest_p + i, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vsma(source_p + i, scale, dest_p + i, frame_counts.sse);
+ sse::Vsma(source_p + i, scale, dest_p + i, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vsma(source_p + i, 1, scale, dest_p + i, 1, frame_counts.scalar);
+ scalar::Vsma(source_p + i, 1, scale, dest_p + i, 1, frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vsma(source_p, source_stride, scale, dest_p, dest_stride,
+ scalar::Vsma(source_p, source_stride, scale, dest_p, dest_stride,
frames_to_process);
}
}
@@ -316,31 +316,31 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride == 1 && dest_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source_p, frames_to_process);
- Scalar::Vsmul(source_p, 1, scale, dest_p, 1,
+ scalar::Vsmul(source_p, 1, scale, dest_p, 1,
frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vsmul(source_p + i, scale, dest_p + i,
+ sse::Vsmul(source_p + i, scale, dest_p + i,
frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vsmul(source_p + i, scale, dest_p + i, frame_counts.avx);
+ avx::Vsmul(source_p + i, scale, dest_p + i, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vsmul(source_p + i, scale, dest_p + i, frame_counts.sse);
+ sse::Vsmul(source_p + i, scale, dest_p + i, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vsmul(source_p + i, 1, scale, dest_p + i, 1, frame_counts.scalar);
+ scalar::Vsmul(source_p + i, 1, scale, dest_p + i, 1, frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vsmul(source_p, source_stride, scale, dest_p, dest_stride,
+ scalar::Vsmul(source_p, source_stride, scale, dest_p, dest_stride,
frames_to_process);
}
}
@@ -348,29 +348,29 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
static ALWAYS_INLINE void Vsvesq(const float* source_p,
int source_stride,
float* sum_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
if (source_stride == 1) {
const FrameCounts frame_counts =
SplitFramesToProcess(source_p, frames_to_process);
- Scalar::Vsvesq(source_p, 1, sum_p, frame_counts.scalar_for_alignment);
+ scalar::Vsvesq(source_p, 1, sum_p, frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Vsvesq(source_p + i, sum_p, frame_counts.sse_for_alignment);
+ sse::Vsvesq(source_p + i, sum_p, frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Vsvesq(source_p + i, sum_p, frame_counts.avx);
+ avx::Vsvesq(source_p + i, sum_p, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Vsvesq(source_p + i, sum_p, frame_counts.sse);
+ sse::Vsvesq(source_p + i, sum_p, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Vsvesq(source_p + i, 1, sum_p, frame_counts.scalar);
+ scalar::Vsvesq(source_p + i, 1, sum_p, frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
} else {
- Scalar::Vsvesq(source_p, source_stride, sum_p, frames_to_process);
+ scalar::Vsvesq(source_p, source_stride, sum_p, frames_to_process);
}
}
@@ -380,34 +380,34 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
FrameCounts frame_counts = SplitFramesToProcess(real1p, frames_to_process);
- Scalar::Zvmul(real1p, imag1p, real2p, imag2p, real_dest_p, imag_dest_p,
+ scalar::Zvmul(real1p, imag1p, real2p, imag2p, real_dest_p, imag_dest_p,
frame_counts.scalar_for_alignment);
size_t i = frame_counts.scalar_for_alignment;
if (frame_counts.sse_for_alignment > 0u) {
- SSE::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
+ sse::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
imag_dest_p + i, frame_counts.sse_for_alignment);
i += frame_counts.sse_for_alignment;
}
if (frame_counts.avx > 0u) {
- AVX::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
+ avx::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
imag_dest_p + i, frame_counts.avx);
i += frame_counts.avx;
}
if (frame_counts.sse > 0u) {
- SSE::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
+ sse::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
imag_dest_p + i, frame_counts.sse);
i += frame_counts.sse;
}
- Scalar::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
+ scalar::Zvmul(real1p + i, imag1p + i, real2p + i, imag2p + i, real_dest_p + i,
imag_dest_p + i, frame_counts.scalar);
DCHECK_EQ(frames_to_process, i + frame_counts.scalar);
}
-} // namespace X86
-} // namespace VectorMath
+} // namespace x86
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_CPU_X86_VECTOR_MATH_X86_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/direct_convolver.cc b/chromium/third_party/blink/renderer/platform/audio/direct_convolver.cc
index a07206cc23b..3a06f249219 100644
--- a/chromium/third_party/blink/renderer/platform/audio/direct_convolver.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/direct_convolver.cc
@@ -44,8 +44,8 @@
namespace blink {
namespace {
-using VectorMath::Conv;
-using VectorMath::PrepareFilterForConv;
+using vector_math::Conv;
+using vector_math::PrepareFilterForConv;
} // namespace
DirectConvolver::DirectConvolver(
@@ -61,7 +61,7 @@ DirectConvolver::DirectConvolver(
void DirectConvolver::Process(const float* source_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK_EQ(frames_to_process, input_block_size_);
if (frames_to_process != input_block_size_)
return;
diff --git a/chromium/third_party/blink/renderer/platform/audio/direct_convolver.h b/chromium/third_party/blink/renderer/platform/audio/direct_convolver.h
index 79617a64b6e..f2f6f98edb8 100644
--- a/chromium/third_party/blink/renderer/platform/audio/direct_convolver.h
+++ b/chromium/third_party/blink/renderer/platform/audio/direct_convolver.h
@@ -46,7 +46,9 @@ class PLATFORM_EXPORT DirectConvolver {
DirectConvolver(size_t input_block_size,
std::unique_ptr<AudioFloatArray> convolution_kernel);
- void Process(const float* source_p, float* dest_p, size_t frames_to_process);
+ void Process(const float* source_p,
+ float* dest_p,
+ uint32_t frames_to_process);
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor.cc b/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor.cc
index 3cec9e8aba8..6b7846b34a3 100644
--- a/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor.cc
@@ -33,7 +33,7 @@
namespace blink {
-using namespace AudioUtilities;
+using namespace audio_utilities;
DynamicsCompressor::DynamicsCompressor(float sample_rate,
unsigned number_of_channels)
diff --git a/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor_kernel.cc b/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor_kernel.cc
index 34a85f0e77e..8241e18b763 100644
--- a/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor_kernel.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/dynamics_compressor_kernel.cc
@@ -36,7 +36,7 @@
namespace blink {
-using namespace AudioUtilities;
+using namespace audio_utilities;
// Metering hits peaks instantly, but releases this fast (in seconds).
const float kMeteringReleaseTimeConstant = 0.325f;
diff --git a/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.cc b/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.cc
index a87f17b0021..d313e3ef17f 100644
--- a/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.cc
@@ -40,7 +40,7 @@ void EqualPowerPanner::Pan(double azimuth,
double /*elevation*/,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) {
bool is_input_safe = input_bus &&
(input_bus->NumberOfChannels() == 1 ||
@@ -179,7 +179,7 @@ void EqualPowerPanner::PanWithSampleAccurateValues(
double* /*elevation*/,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) {
bool is_input_safe = input_bus &&
(input_bus->NumberOfChannels() == 1 ||
diff --git a/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.h b/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.h
index 6ac92af746d..8de50db41a0 100644
--- a/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.h
+++ b/chromium/third_party/blink/renderer/platform/audio/equal_power_panner.h
@@ -40,13 +40,13 @@ class PLATFORM_EXPORT EqualPowerPanner final : public Panner {
double elevation,
const AudioBus* input_bus,
AudioBus* output_buf,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) override;
void PanWithSampleAccurateValues(double* azimuth,
double* elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) override;
void Reset() override {}
diff --git a/chromium/third_party/blink/renderer/platform/audio/ffmpeg/fft_frame_ffmpeg.cc b/chromium/third_party/blink/renderer/platform/audio/ffmpeg/fft_frame_ffmpeg.cc
index 3a17a0e6d59..769e9f66776 100644
--- a/chromium/third_party/blink/renderer/platform/audio/ffmpeg/fft_frame_ffmpeg.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/ffmpeg/fft_frame_ffmpeg.cc
@@ -128,7 +128,7 @@ void FFTFrame::DoInverseFFT(float* data) {
// expect. Hence make the scale factor
// twice as large to compensate for that.
const float scale = 2.0 / fft_size_;
- VectorMath::Vsmul(interleaved_data, 1, &scale, data, 1, fft_size_);
+ vector_math::Vsmul(interleaved_data, 1, &scale, data, 1, fft_size_);
}
float* FFTFrame::GetUpToDateComplexData() {
diff --git a/chromium/third_party/blink/renderer/platform/audio/fft_convolver.cc b/chromium/third_party/blink/renderer/platform/audio/fft_convolver.cc
index e2df351a971..45122414729 100644
--- a/chromium/third_party/blink/renderer/platform/audio/fft_convolver.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/fft_convolver.cc
@@ -31,7 +31,7 @@
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
FFTConvolver::FFTConvolver(size_t fft_size)
: frame_(fft_size),
@@ -43,7 +43,7 @@ FFTConvolver::FFTConvolver(size_t fft_size)
void FFTConvolver::Process(const FFTFrame* fft_kernel,
const float* source_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
size_t half_size = FftSize() / 2;
// framesToProcess must be an exact multiple of halfSize,
diff --git a/chromium/third_party/blink/renderer/platform/audio/fft_convolver.h b/chromium/third_party/blink/renderer/platform/audio/fft_convolver.h
index 421a4cefcdb..af6c5681ade 100644
--- a/chromium/third_party/blink/renderer/platform/audio/fft_convolver.h
+++ b/chromium/third_party/blink/renderer/platform/audio/fft_convolver.h
@@ -56,7 +56,7 @@ class PLATFORM_EXPORT FFTConvolver {
void Process(const FFTFrame* fft_kernel,
const float* source_p,
float* dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/fft_frame.cc b/chromium/third_party/blink/renderer/platform/audio/fft_frame.cc
index 55c658a54ff..3357941ddec 100644
--- a/chromium/third_party/blink/renderer/platform/audio/fft_frame.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/fft_frame.cc
@@ -265,8 +265,8 @@ void FFTFrame::Multiply(const FFTFrame& frame) {
float real0 = real_p1[0];
float imag0 = imag_p1[0];
- VectorMath::Zvmul(real_p1, imag_p1, real_p2, imag_p2, real_p1, imag_p1,
- half_size);
+ vector_math::Zvmul(real_p1, imag_p1, real_p2, imag_p2, real_p1, imag_p1,
+ half_size);
// Multiply the packed DC/nyquist component
real_p1[0] = real0 * real_p2[0];
diff --git a/chromium/third_party/blink/renderer/platform/audio/hrtf_database_loader.cc b/chromium/third_party/blink/renderer/platform/audio/hrtf_database_loader.cc
index 51b93a03fa6..faac2ca4c21 100644
--- a/chromium/third_party/blink/renderer/platform/audio/hrtf_database_loader.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/hrtf_database_loader.cc
@@ -31,8 +31,8 @@
#include "base/location.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.cc b/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.cc
index ac16deebc07..b2e287986b9 100644
--- a/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.cc
@@ -56,10 +56,10 @@ HRTFPanner::HRTFPanner(float sample_rate, HRTFDatabaseLoader* database_loader)
convolver_r2_(FftSizeForSampleRate(sample_rate)),
delay_line_l_(kMaxDelayTimeSeconds, sample_rate),
delay_line_r_(kMaxDelayTimeSeconds, sample_rate),
- temp_l1_(AudioUtilities::kRenderQuantumFrames),
- temp_r1_(AudioUtilities::kRenderQuantumFrames),
- temp_l2_(AudioUtilities::kRenderQuantumFrames),
- temp_r2_(AudioUtilities::kRenderQuantumFrames) {
+ temp_l1_(audio_utilities::kRenderQuantumFrames),
+ temp_r1_(audio_utilities::kRenderQuantumFrames),
+ temp_l2_(audio_utilities::kRenderQuantumFrames),
+ temp_r2_(audio_utilities::kRenderQuantumFrames) {
DCHECK(database_loader);
}
@@ -75,7 +75,7 @@ size_t HRTFPanner::FftSizeForSampleRate(float sample_rate) {
// of two that is greater than or equal the resampled length. This power of
// two is doubled to get the actual FFT size.
- DCHECK(AudioUtilities::IsValidAudioBufferSampleRate(sample_rate));
+ DCHECK(audio_utilities::IsValidAudioBufferSampleRate(sample_rate));
int truncated_impulse_length = 256;
double sample_rate_ratio = sample_rate / 44100;
@@ -121,7 +121,7 @@ void HRTFPanner::Pan(double desired_azimuth,
double elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation channel_interpretation) {
unsigned num_input_channels = input_bus ? input_bus->NumberOfChannels() : 0;
@@ -212,12 +212,12 @@ void HRTFPanner::Pan(double desired_azimuth,
}
// This algorithm currently requires that we process in power-of-two size
- // chunks at least AudioUtilities::kRenderQuantumFrames.
+ // chunks at least audio_utilities::kRenderQuantumFrames.
DCHECK_EQ(1UL << static_cast<int>(log2(frames_to_process)),
frames_to_process);
- DCHECK_GE(frames_to_process, AudioUtilities::kRenderQuantumFrames);
+ DCHECK_GE(frames_to_process, audio_utilities::kRenderQuantumFrames);
- const unsigned kFramesPerSegment = AudioUtilities::kRenderQuantumFrames;
+ const unsigned kFramesPerSegment = audio_utilities::kRenderQuantumFrames;
const unsigned number_of_segments = frames_to_process / kFramesPerSegment;
for (unsigned segment = 0; segment < number_of_segments; ++segment) {
@@ -335,7 +335,7 @@ void HRTFPanner::PanWithSampleAccurateValues(
double* elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation channel_interpretation) {
// Sample-accurate (a-rate) HRTF panner is not implemented, just k-rate. Just
// grab the current azimuth/elevation and use that.
diff --git a/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.h b/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.h
index ce35804ec0c..00406fd0f01 100644
--- a/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.h
+++ b/chromium/third_party/blink/renderer/platform/audio/hrtf_panner.h
@@ -43,13 +43,13 @@ class PLATFORM_EXPORT HRTFPanner final : public Panner {
double elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) override;
void PanWithSampleAccurateValues(double* azimuth,
double* elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) override;
void Reset() override;
diff --git a/chromium/third_party/blink/renderer/platform/audio/iir_filter.cc b/chromium/third_party/blink/renderer/platform/audio/iir_filter.cc
index b9e435eeea2..4ef915ccfbf 100644
--- a/chromium/third_party/blink/renderer/platform/audio/iir_filter.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/iir_filter.cc
@@ -51,7 +51,7 @@ static std::complex<double> EvaluatePolynomial(const double* coef,
void IIRFilter::Process(const float* source_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
// Compute
//
// y[n] = sum(b[k] * x[n - k], k = 0, M) - sum(a[k] * y[n - k], k = 1, N)
@@ -182,11 +182,11 @@ double IIRFilter::TailTime(double sample_rate, bool is_filter_stable) {
// Number of render quanta needed to reach the max tail time.
int number_of_blocks = std::ceil(sample_rate * kMaxTailTime /
- AudioUtilities::kRenderQuantumFrames);
+ audio_utilities::kRenderQuantumFrames);
// Input and output buffers for filtering.
- AudioFloatArray input(AudioUtilities::kRenderQuantumFrames);
- AudioFloatArray output(AudioUtilities::kRenderQuantumFrames);
+ AudioFloatArray input(audio_utilities::kRenderQuantumFrames);
+ AudioFloatArray output(audio_utilities::kRenderQuantumFrames);
// Array to hold the max magnitudes
AudioFloatArray magnitudes(number_of_blocks);
@@ -195,18 +195,18 @@ double IIRFilter::TailTime(double sample_rate, bool is_filter_stable) {
input[0] = 1;
// Process the first block and get the max magnitude of the output.
- Process(input.Data(), output.Data(), AudioUtilities::kRenderQuantumFrames);
- VectorMath::Vmaxmgv(output.Data(), 1, &magnitudes[0],
- AudioUtilities::kRenderQuantumFrames);
+ Process(input.Data(), output.Data(), audio_utilities::kRenderQuantumFrames);
+ vector_math::Vmaxmgv(output.Data(), 1, &magnitudes[0],
+ audio_utilities::kRenderQuantumFrames);
// Process the rest of the signal, getting the max magnitude of the
// output for each block.
input[0] = 0;
for (int k = 1; k < number_of_blocks; ++k) {
- Process(input.Data(), output.Data(), AudioUtilities::kRenderQuantumFrames);
- VectorMath::Vmaxmgv(output.Data(), 1, &magnitudes[k],
- AudioUtilities::kRenderQuantumFrames);
+ Process(input.Data(), output.Data(), audio_utilities::kRenderQuantumFrames);
+ vector_math::Vmaxmgv(output.Data(), 1, &magnitudes[k],
+ audio_utilities::kRenderQuantumFrames);
}
// Done computing the impulse response; reset the state so the actual node
@@ -224,7 +224,7 @@ double IIRFilter::TailTime(double sample_rate, bool is_filter_stable) {
// The magnitude first become lower than the threshold at the next block.
// Compute the corresponding time value value; that's the tail time.
- return (index + 1) * AudioUtilities::kRenderQuantumFrames / sample_rate;
+ return (index + 1) * audio_utilities::kRenderQuantumFrames / sample_rate;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/audio/iir_filter.h b/chromium/third_party/blink/renderer/platform/audio/iir_filter.h
index 00def1f35ea..1789cdf12f7 100644
--- a/chromium/third_party/blink/renderer/platform/audio/iir_filter.h
+++ b/chromium/third_party/blink/renderer/platform/audio/iir_filter.h
@@ -20,7 +20,9 @@ class PLATFORM_EXPORT IIRFilter final {
const AudioDoubleArray* feedback_coef);
~IIRFilter();
- void Process(const float* source_p, float* dest_p, size_t frames_to_process);
+ void Process(const float* source_p,
+ float* dest_p,
+ uint32_t frames_to_process);
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc b/chromium/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc
index 65e991098b5..6df22383b6c 100644
--- a/chromium/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc
@@ -93,7 +93,7 @@ void FFTFrame::DoFFT(const float* data) {
// Compensate for that by scaling the input by half so the FFT has the
// correct scaling.
float scale = 0.5f;
- VectorMath::Vsmul(data, 1, &scale, scaled_data.Data(), 1, fft_size_);
+ vector_math::Vsmul(data, 1, &scale, scaled_data.Data(), 1, fft_size_);
vDSP_ctoz((DSPComplex*)scaled_data.Data(), 2, &frame_, 1, fft_size_ / 2);
vDSP_fft_zrip(fft_setup_, &frame_, 1, log2fft_size_, FFT_FORWARD);
@@ -105,7 +105,7 @@ void FFTFrame::DoInverseFFT(float* data) {
// Do final scaling so that x == IFFT(FFT(x))
float scale = 1.0f / fft_size_;
- VectorMath::Vsmul(data, 1, &scale, data, 1, fft_size_);
+ vector_math::Vsmul(data, 1, &scale, data, 1, fft_size_);
}
FFTSetup FFTFrame::FftSetupForSize(unsigned fft_size) {
diff --git a/chromium/third_party/blink/renderer/platform/audio/mac/vector_math_mac.h b/chromium/third_party/blink/renderer/platform/audio/mac/vector_math_mac.h
index 26035dda573..781568f4a72 100644
--- a/chromium/third_party/blink/renderer/platform/audio/mac/vector_math_mac.h
+++ b/chromium/third_party/blink/renderer/platform/audio/mac/vector_math_mac.h
@@ -11,8 +11,8 @@
#include "third_party/blink/renderer/platform/audio/audio_array.h"
namespace blink {
-namespace VectorMath {
-namespace Mac {
+namespace vector_math {
+namespace mac {
// On the Mac we use the highly optimized versions in Accelerate.framework
// In 32-bit mode (__ppc__ or __i386__) <Accelerate/Accelerate.h> includes
@@ -26,7 +26,7 @@ static ALWAYS_INLINE void Conv(const float* source_p,
int filter_stride,
float* dest_p,
int dest_stride,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size,
const AudioFloatArray* /*prepared_filter*/) {
#if defined(ARCH_CPU_X86)
@@ -44,7 +44,7 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
#if defined(ARCH_CPU_X86)
::vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, frames_to_process);
@@ -60,7 +60,7 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
vDSP_vclip(source_p, source_stride, low_threshold_p, high_threshold_p, dest_p,
dest_stride, frames_to_process);
}
@@ -68,7 +68,7 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
vDSP_maxmgv(source_p, source_stride, max_p, frames_to_process);
}
@@ -78,7 +78,7 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
#if defined(ARCH_CPU_X86)
::vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, frames_to_process);
@@ -93,7 +93,7 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
vDSP_vsma(source_p, source_stride, scale, dest_p, dest_stride, dest_p,
dest_stride, frames_to_process);
}
@@ -103,7 +103,7 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
#if defined(ARCH_CPU_X86)
::vsmul(source_p, source_stride, scale, dest_p, dest_stride,
frames_to_process);
@@ -116,7 +116,7 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
static ALWAYS_INLINE void Vsvesq(const float* source_p,
int source_stride,
float* sum_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
vDSP_svesq(source_p, source_stride, sum_p, frames_to_process);
}
@@ -126,7 +126,7 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DSPSplitComplex sc1;
DSPSplitComplex sc2;
DSPSplitComplex dest;
@@ -143,8 +143,8 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
#endif
}
-} // namespace Mac
-} // namespace VectorMath
+} // namespace mac
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_MAC_VECTOR_MATH_MAC_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.cc b/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.cc
index 1a1a7de5d3a..06c4d7a7274 100644
--- a/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.cc
@@ -50,7 +50,7 @@ class ChannelProvider final : public AudioSourceProvider {
// provideInput() will be called once for each channel, starting with the
// first channel. Each time it's called, it will provide the next channel of
// data.
- void ProvideInput(AudioBus* bus, size_t frames_to_process) override {
+ void ProvideInput(AudioBus* bus, uint32_t frames_to_process) override {
bool is_bus_good = bus && bus->NumberOfChannels() == 1;
DCHECK(is_bus_good);
if (!is_bus_good)
@@ -91,7 +91,7 @@ class ChannelProvider final : public AudioSourceProvider {
unsigned number_of_channels_;
unsigned current_channel_;
// Used to verify that all channels ask for the same amount.
- size_t frames_to_process_;
+ uint32_t frames_to_process_;
};
} // namespace
@@ -107,7 +107,7 @@ MultiChannelResampler::MultiChannelResampler(double scale_factor,
void MultiChannelResampler::Process(AudioSourceProvider* provider,
AudioBus* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
// The provider can provide us with multi-channel audio data. But each of our
// single-channel resamplers (kernels) below requires a provider which
// provides a single unique channel of data. channelProvider wraps the
diff --git a/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.h b/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.h
index 7b3dad9be25..64949504b80 100644
--- a/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.h
+++ b/chromium/third_party/blink/renderer/platform/audio/multi_channel_resampler.h
@@ -49,7 +49,7 @@ class PLATFORM_EXPORT MultiChannelResampler {
// Process given AudioSourceProvider for streaming applications.
void Process(AudioSourceProvider*,
AudioBus* destination,
- size_t frames_to_process);
+ uint32_t frames_to_process);
private:
// FIXME: the mac port can have a more highly optimized implementation based
diff --git a/chromium/third_party/blink/renderer/platform/audio/panner.h b/chromium/third_party/blink/renderer/platform/audio/panner.h
index 4fa56c1f8c6..dd4f0abfe7c 100644
--- a/chromium/third_party/blink/renderer/platform/audio/panner.h
+++ b/chromium/third_party/blink/renderer/platform/audio/panner.h
@@ -62,13 +62,13 @@ class PLATFORM_EXPORT Panner {
double elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) = 0;
virtual void PanWithSampleAccurateValues(double* azimuth,
double* elevation,
const AudioBus* input_bus,
AudioBus* output_bus,
- size_t frames_to_process,
+ uint32_t frames_to_process,
AudioBus::ChannelInterpretation) = 0;
virtual void Reset() = 0;
diff --git a/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo.cc b/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo.cc
index 21d6924539d..92bee137033 100644
--- a/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo.cc
@@ -63,7 +63,7 @@ void PushPullFIFO::Push(const AudioBus* input_bus) {
MutexLocker locker(lock_);
CHECK(input_bus);
- CHECK_EQ(input_bus->length(), AudioUtilities::kRenderQuantumFrames);
+ CHECK_EQ(input_bus->length(), audio_utilities::kRenderQuantumFrames);
SECURITY_CHECK(input_bus->length() <= fifo_length_);
SECURITY_CHECK(index_write_ < fifo_length_);
diff --git a/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_multithread_test.cc b/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_multithread_test.cc
index 049cc6b1afb..e96a3aab939 100644
--- a/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_multithread_test.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_multithread_test.cc
@@ -9,12 +9,12 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/audio/audio_utilities.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_test.cc b/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_test.cc
index c024c1d4aad..6d44b003c36 100644
--- a/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_test.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/push_pull_fifo_test.cc
@@ -32,13 +32,13 @@ TEST(PushPullFIFOBasicTest, BasicTests) {
std::unique_ptr<PushPullFIFO> test_fifo =
std::make_unique<PushPullFIFO>(2, 1024);
- // The input bus length must be |AudioUtilities::kRenderQuantumFrames|.
+ // The input bus length must be |audio_utilities::kRenderQuantumFrames|.
// i.e.) input_bus->length() == kRenderQuantumFrames
scoped_refptr<AudioBus> input_bus_129_frames =
- AudioBus::Create(2, AudioUtilities::kRenderQuantumFrames + 1);
+ AudioBus::Create(2, audio_utilities::kRenderQuantumFrames + 1);
EXPECT_DEATH(test_fifo->Push(input_bus_129_frames.get()), "");
scoped_refptr<AudioBus> input_bus_127_frames =
- AudioBus::Create(2, AudioUtilities::kRenderQuantumFrames - 1);
+ AudioBus::Create(2, audio_utilities::kRenderQuantumFrames - 1);
EXPECT_DEATH(test_fifo->Push(input_bus_127_frames.get()), "");
// Pull request frames cannot exceed the length of output bus.
diff --git a/chromium/third_party/blink/renderer/platform/audio/resources/README b/chromium/third_party/blink/renderer/platform/audio/resources/README
index 90d3fd6255e..7dbdec7202b 100644
--- a/chromium/third_party/blink/renderer/platform/audio/resources/README
+++ b/chromium/third_party/blink/renderer/platform/audio/resources/README
@@ -16,5 +16,5 @@ To create the FLAC-encoded version:
avconv -i Composite.wav Composite.flac
If you change Composite.flac (or Composite.wav), be sure to update
-LayoutTests/webaudio/resources/hrtf with the updated files!
+web_tests/webaudio/resources/hrtf with the updated files!
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb.cc b/chromium/third_party/blink/renderer/platform/audio/reverb.cc
index 0738a6991b8..e08c6968056 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb.cc
@@ -41,7 +41,7 @@
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
// Empirical gain calibration tested across many impulse responses to ensure
// perceived volume is same as dry (unprocessed) signal
@@ -148,7 +148,7 @@ void Reverb::Initialize(AudioBus* impulse_response_buffer,
void Reverb::Process(const AudioBus* source_bus,
AudioBus* destination_bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
// Do a fairly comprehensive sanity check.
// If these conditions are satisfied, all of the source and destination
// pointers will be valid for the various matrixing cases.
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb.h b/chromium/third_party/blink/renderer/platform/audio/reverb.h
index 3b5b6983175..03ce81feca4 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb.h
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb.h
@@ -59,7 +59,7 @@ class PLATFORM_EXPORT Reverb {
void Process(const AudioBus* source_bus,
AudioBus* destination_bus,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void Reset();
size_t ImpulseResponseLength() const { return impulse_response_length_; }
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb_accumulation_buffer.cc b/chromium/third_party/blink/renderer/platform/audio/reverb_accumulation_buffer.cc
index b5b4c859604..dc1d5d81570 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb_accumulation_buffer.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb_accumulation_buffer.cc
@@ -32,7 +32,7 @@
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
ReverbAccumulationBuffer::ReverbAccumulationBuffer(size_t length)
: buffer_(length), read_index_(0), read_time_frame_(0) {}
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.cc b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.cc
index da7a7ace57a..64ae9454942 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.cc
@@ -36,12 +36,12 @@
#include "third_party/blink/renderer/platform/audio/audio_bus.h"
#include "third_party/blink/renderer/platform/audio/vector_math.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
-using namespace VectorMath;
+using namespace vector_math;
const int kInputBufferSize = 8 * 16384;
@@ -173,7 +173,7 @@ void ReverbConvolver::ProcessInBackground() {
void ReverbConvolver::Process(const AudioChannel* source_channel,
AudioChannel* destination_channel,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
bool is_safe = source_channel && destination_channel &&
source_channel->length() >= frames_to_process &&
destination_channel->length() >= frames_to_process;
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.h b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.h
index 793061c9fee..40c53798574 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.h
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver.h
@@ -63,7 +63,7 @@ class PLATFORM_EXPORT ReverbConvolver {
void Process(const AudioChannel* source_channel,
AudioChannel* destination_channel,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void Reset();
ReverbInputBuffer* InputBuffer() { return &input_buffer_; }
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.cc b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.cc
index b9dc0f3bded..f982cdafb03 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.cc
@@ -106,7 +106,7 @@ ReverbConvolverStage::ReverbConvolverStage(
}
void ReverbConvolverStage::ProcessInBackground(ReverbConvolver* convolver,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
ReverbInputBuffer* input_buffer = convolver->InputBuffer();
float* source =
input_buffer->DirectReadFrom(&input_read_index_, frames_to_process);
@@ -114,7 +114,7 @@ void ReverbConvolverStage::ProcessInBackground(ReverbConvolver* convolver,
}
void ReverbConvolverStage::Process(const float* source,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(source);
if (!source)
return;
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.h b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.h
index d40df064021..39f00a99524 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.h
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb_convolver_stage.h
@@ -68,10 +68,10 @@ class PLATFORM_EXPORT ReverbConvolverStage {
// WARNING: framesToProcess must be such that it evenly divides the delay
// buffer size (stage_offset).
- void Process(const float* source, size_t frames_to_process);
+ void Process(const float* source, uint32_t frames_to_process);
void ProcessInBackground(ReverbConvolver* convolver,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/reverb_input_buffer.h b/chromium/third_party/blink/renderer/platform/audio/reverb_input_buffer.h
index 3d86ea226d6..b08aad199bc 100644
--- a/chromium/third_party/blink/renderer/platform/audio/reverb_input_buffer.h
+++ b/chromium/third_party/blink/renderer/platform/audio/reverb_input_buffer.h
@@ -29,10 +29,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_REVERB_INPUT_BUFFER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_REVERB_INPUT_BUFFER_H_
+#include <atomic>
#include "third_party/blink/renderer/platform/audio/audio_array.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
namespace blink {
@@ -53,9 +53,8 @@ class PLATFORM_EXPORT ReverbInputBuffer {
void Write(const float* source_p, size_t number_of_frames);
// Background threads can call this to check if there's anything to read...
- size_t WriteIndex() const { return AcquireLoad(&write_index_); }
- void SetWriteIndex(size_t new_index) {
- ReleaseStore(&write_index_, new_index);
+ size_t WriteIndex() const {
+ return write_index_.load(std::memory_order_acquire);
}
// The individual background threads read here (and hope that they can keep up
@@ -69,12 +68,16 @@ class PLATFORM_EXPORT ReverbInputBuffer {
void Reset();
private:
+ void SetWriteIndex(size_t new_index) {
+ write_index_.store(new_index, std::memory_order_release);
+ }
+
AudioFloatArray buffer_;
// |write_index_| can be accessed from several threads. Only use
// the getter and setter to access it atomically. Don't access
// directly!
- size_t write_index_;
+ std::atomic_size_t write_index_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.cc b/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.cc
index eefe344a9b7..04c7b315873 100644
--- a/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.cc
@@ -26,7 +26,7 @@ SimpleFFTConvolver::SimpleFFTConvolver(
void SimpleFFTConvolver::Process(const float* source_p,
float* dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
size_t half_size = FftSize() / 2;
// frames_to_process must be exactly half_size.
@@ -46,8 +46,8 @@ void SimpleFFTConvolver::Process(const float* source_p,
// Overlap-add 1st half with 2nd half from previous time and write
// to destination.
- VectorMath::Vadd(output_buffer_.Data(), 1, last_overlap_buffer_.Data(), 1,
- dest_p, 1, half_size);
+ vector_math::Vadd(output_buffer_.Data(), 1, last_overlap_buffer_.Data(), 1,
+ dest_p, 1, half_size);
// Finally, save 2nd half for the next time.
last_overlap_buffer_.CopyToRange(output_buffer_.Data() + half_size, 0,
diff --git a/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.h b/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.h
index 571ac9e0f5e..8e2093d3df7 100644
--- a/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.h
+++ b/chromium/third_party/blink/renderer/platform/audio/simple_fft_convolver.h
@@ -29,7 +29,9 @@ class PLATFORM_EXPORT SimpleFFTConvolver {
size_t input_block_size,
const std::unique_ptr<AudioFloatArray>& convolution_kernel);
- void Process(const float* source_p, float* dest_p, size_t frames_to_process);
+ void Process(const float* source_p,
+ float* dest_p,
+ uint32_t frames_to_process);
void Reset();
diff --git a/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.cc b/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.cc
index c949fa60bce..f5232627189 100644
--- a/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.cc
@@ -154,11 +154,11 @@ namespace {
class BufferSourceProvider final : public AudioSourceProvider {
public:
- BufferSourceProvider(const float* source, size_t number_of_source_frames)
+ BufferSourceProvider(const float* source, uint32_t number_of_source_frames)
: source_(source), source_frames_available_(number_of_source_frames) {}
// Consumes samples from the in-memory buffer.
- void ProvideInput(AudioBus* bus, size_t frames_to_process) override {
+ void ProvideInput(AudioBus* bus, uint32_t frames_to_process) override {
DCHECK(source_);
DCHECK(bus);
if (!source_ || !bus)
@@ -167,7 +167,7 @@ class BufferSourceProvider final : public AudioSourceProvider {
float* buffer = bus->Channel(0)->MutableData();
// Clamp to number of frames available and zero-pad.
- size_t frames_to_copy =
+ uint32_t frames_to_copy =
std::min(source_frames_available_, frames_to_process);
memcpy(buffer, source_, sizeof(float) * frames_to_copy);
@@ -182,7 +182,7 @@ class BufferSourceProvider final : public AudioSourceProvider {
private:
const float* source_;
- size_t source_frames_available_;
+ uint32_t source_frames_available_;
};
} // namespace
@@ -208,7 +208,7 @@ void SincResampler::Process(const float* source,
void SincResampler::Process(AudioSourceProvider* source_provider,
float* destination,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
bool is_good = source_provider && block_size_ > kernel_size_ &&
input_buffer_.size() >= block_size_ + kernel_size_ &&
!(kernel_size_ % 2);
diff --git a/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.h b/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.h
index f0f83c7cd26..df8885711b7 100644
--- a/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.h
+++ b/chromium/third_party/blink/renderer/platform/audio/sinc_resampler.h
@@ -61,7 +61,7 @@ class PLATFORM_EXPORT SincResampler {
// Process with input source callback function for streaming applications.
void Process(AudioSourceProvider*,
float* destination,
- size_t frames_to_process);
+ uint32_t frames_to_process);
protected:
void InitializeKernel();
diff --git a/chromium/third_party/blink/renderer/platform/audio/stereo_panner.cc b/chromium/third_party/blink/renderer/platform/audio/stereo_panner.cc
index d375cd24adb..9ba7245c477 100644
--- a/chromium/third_party/blink/renderer/platform/audio/stereo_panner.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/stereo_panner.cc
@@ -26,7 +26,7 @@ StereoPanner::StereoPanner(float sample_rate) {}
void StereoPanner::PanWithSampleAccurateValues(const AudioBus* input_bus,
AudioBus* output_bus,
const float* pan_values,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
bool is_input_safe = input_bus &&
(input_bus->NumberOfChannels() == 1 ||
input_bus->NumberOfChannels() == 2) &&
@@ -92,7 +92,7 @@ void StereoPanner::PanWithSampleAccurateValues(const AudioBus* input_bus,
void StereoPanner::PanToTargetValue(const AudioBus* input_bus,
AudioBus* output_bus,
float pan_value,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
bool is_input_safe = input_bus &&
(input_bus->NumberOfChannels() == 1 ||
input_bus->NumberOfChannels() == 2) &&
@@ -131,7 +131,7 @@ void StereoPanner::PanToTargetValue(const AudioBus* input_bus,
double gain_l = std::cos(pan_radian);
double gain_r = std::sin(pan_radian);
- // TODO(rtoy): This can be vectorized using VectorMath::Vsmul
+ // TODO(rtoy): This can be vectorized using vector_math::Vsmul
while (n--) {
float input_l = *source_l++;
*destination_l++ = static_cast<float>(input_l * gain_l);
diff --git a/chromium/third_party/blink/renderer/platform/audio/stereo_panner.h b/chromium/third_party/blink/renderer/platform/audio/stereo_panner.h
index cf1b7efce09..e06094edc68 100644
--- a/chromium/third_party/blink/renderer/platform/audio/stereo_panner.h
+++ b/chromium/third_party/blink/renderer/platform/audio/stereo_panner.h
@@ -28,11 +28,11 @@ class PLATFORM_EXPORT StereoPanner {
void PanWithSampleAccurateValues(const AudioBus* input_bus,
AudioBus* output_bus,
const float* pan_values,
- size_t frames_to_process);
+ uint32_t frames_to_process);
void PanToTargetValue(const AudioBus* input_bus,
AudioBus* output_bus,
float pan_value,
- size_t frames_to_process);
+ uint32_t frames_to_process);
private:
explicit StereoPanner(float sample_rate);
diff --git a/chromium/third_party/blink/renderer/platform/audio/vector_math.cc b/chromium/third_party/blink/renderer/platform/audio/vector_math.cc
index af76fad0b2b..38a8b95b6c5 100644
--- a/chromium/third_party/blink/renderer/platform/audio/vector_math.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/vector_math.cc
@@ -45,19 +45,19 @@
namespace blink {
-namespace VectorMath {
+namespace vector_math {
namespace {
#if defined(OS_MACOSX)
-namespace Impl = Mac;
+namespace impl = mac;
#elif WTF_CPU_ARM_NEON
-namespace Impl = NEON;
+namespace impl = neon;
#elif HAVE_MIPS_MSA_INTRINSICS
-namespace Impl = MSA;
+namespace impl = msa;
#elif defined(ARCH_CPU_X86_FAMILY)
-namespace Impl = X86;
+namespace impl = x86;
#else
-namespace Impl = Scalar;
+namespace impl = scalar;
#endif
} // namespace
@@ -71,7 +71,7 @@ void PrepareFilterForConv(const float* filter_p,
DCHECK_EQ(-1, filter_stride);
DCHECK(prepared_filter);
#if defined(ARCH_CPU_X86_FAMILY) && !defined(OS_MACOSX)
- X86::PrepareFilterForConv(filter_p, filter_stride, filter_size,
+ x86::PrepareFilterForConv(filter_p, filter_stride, filter_size,
prepared_filter);
#endif
}
@@ -82,7 +82,7 @@ void Conv(const float* source_p,
int filter_stride,
float* dest_p,
int dest_stride,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size,
const AudioFloatArray* prepared_filter) {
// Only contiguous convolution is implemented by all implementations.
@@ -91,7 +91,7 @@ void Conv(const float* source_p,
DCHECK_EQ(1, source_stride);
DCHECK_EQ(-1, filter_stride);
DCHECK_EQ(1, dest_stride);
- Impl::Conv(source_p, source_stride, filter_p, filter_stride, dest_p,
+ impl::Conv(source_p, source_stride, filter_p, filter_stride, dest_p,
dest_stride, frames_to_process, filter_size, prepared_filter);
}
@@ -101,8 +101,8 @@ void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
- Impl::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
+ uint32_t frames_to_process) {
+ impl::Vadd(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, frames_to_process);
}
@@ -112,7 +112,7 @@ void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
float low_threshold = *low_threshold_p;
float high_threshold = *high_threshold_p;
@@ -125,17 +125,17 @@ void Vclip(const float* source_p,
DCHECK_LE(low_threshold, high_threshold);
#endif
- Impl::Vclip(source_p, source_stride, &low_threshold, &high_threshold, dest_p,
+ impl::Vclip(source_p, source_stride, &low_threshold, &high_threshold, dest_p,
dest_stride, frames_to_process);
}
void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
float max = 0;
- Impl::Vmaxmgv(source_p, source_stride, &max, frames_to_process);
+ impl::Vmaxmgv(source_p, source_stride, &max, frames_to_process);
DCHECK(max_p);
*max_p = max;
@@ -147,8 +147,8 @@ void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
- Impl::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
+ uint32_t frames_to_process) {
+ impl::Vmul(source1p, source_stride1, source2p, source_stride2, dest_p,
dest_stride, frames_to_process);
}
@@ -157,10 +157,10 @@ void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float k = *scale;
- Impl::Vsma(source_p, source_stride, &k, dest_p, dest_stride,
+ impl::Vsma(source_p, source_stride, &k, dest_p, dest_stride,
frames_to_process);
}
@@ -169,20 +169,20 @@ void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float k = *scale;
- Impl::Vsmul(source_p, source_stride, &k, dest_p, dest_stride,
+ impl::Vsmul(source_p, source_stride, &k, dest_p, dest_stride,
frames_to_process);
}
void Vsvesq(const float* source_p,
int source_stride,
float* sum_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
float sum = 0;
- Impl::Vsvesq(source_p, source_stride, &sum, frames_to_process);
+ impl::Vsvesq(source_p, source_stride, &sum, frames_to_process);
DCHECK(sum_p);
*sum_p = sum;
@@ -194,11 +194,11 @@ void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process) {
- Impl::Zvmul(real1p, imag1p, real2p, imag2p, real_dest_p, imag_dest_p,
+ uint32_t frames_to_process) {
+ impl::Zvmul(real1p, imag1p, real2p, imag2p, real_dest_p, imag_dest_p,
frames_to_process);
}
-} // namespace VectorMath
+} // namespace vector_math
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/audio/vector_math.h b/chromium/third_party/blink/renderer/platform/audio/vector_math.h
index 1dec0c9acf1..50578e28846 100644
--- a/chromium/third_party/blink/renderer/platform/audio/vector_math.h
+++ b/chromium/third_party/blink/renderer/platform/audio/vector_math.h
@@ -35,7 +35,7 @@
// will ideally be optimized.
namespace blink {
-namespace VectorMath {
+namespace vector_math {
// Direct vector convolution:
//
@@ -47,7 +47,7 @@ PLATFORM_EXPORT void Conv(const float* source_p,
int filter_stride,
float* dest_p,
int dest_stride,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size,
const AudioFloatArray* prepared_filter);
@@ -65,7 +65,7 @@ PLATFORM_EXPORT void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Vector scalar multiply:
//
@@ -75,7 +75,7 @@ PLATFORM_EXPORT void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Vector add:
//
@@ -86,7 +86,7 @@ PLATFORM_EXPORT void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Finds the maximum magnitude of a float vector:
//
@@ -94,7 +94,7 @@ PLATFORM_EXPORT void Vadd(const float* source1p,
PLATFORM_EXPORT void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Sums the squares of a float vector's elements:
//
@@ -102,7 +102,7 @@ PLATFORM_EXPORT void Vmaxmgv(const float* source_p,
PLATFORM_EXPORT void Vsvesq(const float* source_p,
int source_stride,
float* sum_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// For an element-by-element multiply of two float vectors:
//
@@ -113,7 +113,7 @@ PLATFORM_EXPORT void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Multiplies two complex vectors. Complex version of Vmul where |rea1p| and
// |imag1p| forms the real and complex components of source1; |real2p| and
@@ -125,7 +125,7 @@ PLATFORM_EXPORT void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process);
+ uint32_t frames_to_process);
// Copies elements while clipping values to the threshold inputs.
//
@@ -139,9 +139,9 @@ PLATFORM_EXPORT void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process);
+ uint32_t frames_to_process);
-} // namespace VectorMath
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_VECTOR_MATH_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/vector_math_scalar.h b/chromium/third_party/blink/renderer/platform/audio/vector_math_scalar.h
index 70b0a59d446..47d8b204e83 100644
--- a/chromium/third_party/blink/renderer/platform/audio/vector_math_scalar.h
+++ b/chromium/third_party/blink/renderer/platform/audio/vector_math_scalar.h
@@ -13,8 +13,8 @@
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
-namespace VectorMath {
-namespace Scalar {
+namespace vector_math {
+namespace scalar {
static ALWAYS_INLINE void Conv(const float* source_p,
int source_stride,
@@ -22,7 +22,7 @@ static ALWAYS_INLINE void Conv(const float* source_p,
int filter_stride,
float* dest_p,
int dest_stride,
- size_t frames_to_process,
+ uint32_t frames_to_process,
size_t filter_size,
const AudioFloatArray* /*prepared_filter*/) {
// Only contiguous convolution is implemented. Correlation (positive
@@ -314,7 +314,7 @@ static ALWAYS_INLINE void Vadd(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
while (frames_to_process > 0u) {
*dest_p = *source1p + *source2p;
source1p += source_stride1;
@@ -330,7 +330,7 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
const float* high_threshold_p,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
while (frames_to_process > 0u) {
*dest_p = clampTo(*source_p, *low_threshold_p, *high_threshold_p);
source_p += source_stride;
@@ -342,7 +342,7 @@ static ALWAYS_INLINE void Vclip(const float* source_p,
static ALWAYS_INLINE void Vmaxmgv(const float* source_p,
int source_stride,
float* max_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
while (frames_to_process > 0u) {
*max_p = std::max(*max_p, std::abs(*source_p));
source_p += source_stride;
@@ -356,7 +356,7 @@ static ALWAYS_INLINE void Vmul(const float* source1p,
int source_stride2,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
while (frames_to_process > 0u) {
*dest_p = *source1p * *source2p;
source1p += source_stride1;
@@ -371,7 +371,7 @@ static ALWAYS_INLINE void Vsma(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float k = *scale;
while (frames_to_process > 0u) {
*dest_p += k * *source_p;
@@ -386,7 +386,7 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
const float* scale,
float* dest_p,
int dest_stride,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
const float k = *scale;
while (frames_to_process > 0u) {
*dest_p = k * *source_p;
@@ -399,7 +399,7 @@ static ALWAYS_INLINE void Vsmul(const float* source_p,
static ALWAYS_INLINE void Vsvesq(const float* source_p,
int source_stride,
float* sum_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
while (frames_to_process > 0u) {
const float sample = *source_p;
*sum_p += sample * sample;
@@ -414,7 +414,7 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
const float* imag2p,
float* real_dest_p,
float* imag_dest_p,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
for (size_t i = 0u; i < frames_to_process; ++i) {
// Read and compute result before storing them, in case the
// destination is the same as one of the sources.
@@ -426,8 +426,8 @@ static ALWAYS_INLINE void Zvmul(const float* real1p,
}
}
-} // namespace Scalar
-} // namespace VectorMath
+} // namespace scalar
+} // namespace vector_math
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_AUDIO_VECTOR_MATH_SCALAR_H_
diff --git a/chromium/third_party/blink/renderer/platform/audio/vector_math_test.cc b/chromium/third_party/blink/renderer/platform/audio/vector_math_test.cc
index 7b45ec290d5..5d85c7a5d5d 100644
--- a/chromium/third_party/blink/renderer/platform/audio/vector_math_test.cc
+++ b/chromium/third_party/blink/renderer/platform/audio/vector_math_test.cc
@@ -17,7 +17,7 @@
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
-namespace VectorMath {
+namespace vector_math {
namespace {
struct MemoryLayout {
@@ -67,7 +67,7 @@ bool Equal(float a, float b) {
// This represents a real source or destination vector which is aligned, can be
// non-contiguous and can be used as a source or destination vector for
-// blink::VectorMath functions.
+// blink::vector_math functions.
template <typename T>
class TestVector {
class Iterator {
@@ -272,7 +272,7 @@ TEST_F(VectorMathTest, Conv) {
// process only |source.size() - filter_size| frames here.
if (filter_size >= source.size())
break;
- size_t frames_to_process = source.size() - filter_size;
+ uint32_t frames_to_process = source.size() - filter_size;
// The stride of a convolution filter must be -1. Let's first create
// a reversed filter whose stride is 1.
TestVector<const float> reversed_filter(
@@ -515,5 +515,5 @@ TEST_F(VectorMathTest, Zvmul) {
}
} // namespace
-} // namespace VectorMath
+} // namespace vector_math
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/bindings/DEPS b/chromium/third_party/blink/renderer/platform/bindings/DEPS
index 87cfbf26f01..455e08941d6 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/DEPS
+++ b/chromium/third_party/blink/renderer/platform/bindings/DEPS
@@ -7,13 +7,17 @@ include_rules = [
# Dependencies.
"+gin/public",
+ "+third_party/blink/renderer/platform/cross_thread_functional.h",
"+third_party/blink/renderer/platform/heap",
"+third_party/blink/renderer/platform/instance_counters.h",
"+third_party/blink/renderer/platform/instrumentation",
+ "+third_party/blink/renderer/platform/memory_coordinator.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/runtime_enabled_features.h",
"+third_party/blink/renderer/platform/scheduler",
"+third_party/blink/renderer/platform/testing",
+ "+third_party/blink/renderer/platform/web_task_runner.h",
"+third_party/blink/renderer/platform/weborigin",
"+third_party/blink/renderer/platform/wtf",
+ "+third_party/zlib/google/compression_utils.h",
]
diff --git a/chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.cc b/chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.cc
new file mode 100644
index 00000000000..2e5ef41c291
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.cc
@@ -0,0 +1,96 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/bindings/binding_security_for_platform.h"
+
+namespace blink {
+
+BindingSecurityForPlatform::
+ ShouldAllowAccessToV8ContextWithExceptionStateFunction
+ BindingSecurityForPlatform::
+ should_allow_access_to_v8context_with_exception_state_ = nullptr;
+BindingSecurityForPlatform::
+ ShouldAllowAccessToV8ContextWithErrorReportOptionFunction
+ BindingSecurityForPlatform::
+ should_allow_access_to_v8context_with_error_report_option_ =
+ nullptr;
+BindingSecurityForPlatform::ShouldAllowWrapperCreationOrThrowExceptionFunction
+ BindingSecurityForPlatform::
+ should_allow_wrapper_creation_or_throw_exception_ = nullptr;
+BindingSecurityForPlatform::RethrowWrapperCreationExceptionFunction
+ BindingSecurityForPlatform::rethrow_wrapper_creation_exception_ = nullptr;
+
+// static
+bool BindingSecurityForPlatform::ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ExceptionState& exception_state) {
+ return (*should_allow_access_to_v8context_with_exception_state_)(
+ accessing_context, target_context, exception_state);
+}
+
+// static
+bool BindingSecurityForPlatform::ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ErrorReportOption reporting_option) {
+ return (*should_allow_access_to_v8context_with_error_report_option_)(
+ accessing_context, target_context, reporting_option);
+}
+
+// static
+bool BindingSecurityForPlatform::ShouldAllowWrapperCreationOrThrowException(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> creation_context,
+ const WrapperTypeInfo* wrapper_type_info) {
+ return (*should_allow_wrapper_creation_or_throw_exception_)(
+ accessing_context, creation_context, wrapper_type_info);
+}
+
+// static
+void BindingSecurityForPlatform::RethrowWrapperCreationException(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> creation_context,
+ const WrapperTypeInfo* wrapper_type_info,
+ v8::Local<v8::Value> cross_context_exception) {
+ (*rethrow_wrapper_creation_exception_)(accessing_context, creation_context,
+ wrapper_type_info,
+ cross_context_exception);
+}
+
+// static
+void BindingSecurityForPlatform::
+ SetShouldAllowAccessToV8ContextWithExceptionState(
+ ShouldAllowAccessToV8ContextWithExceptionStateFunction func) {
+ DCHECK(!should_allow_access_to_v8context_with_exception_state_);
+ DCHECK(func);
+ should_allow_access_to_v8context_with_exception_state_ = func;
+}
+
+// static
+void BindingSecurityForPlatform::
+ SetShouldAllowAccessToV8ContextWithErrorReportOption(
+ ShouldAllowAccessToV8ContextWithErrorReportOptionFunction func) {
+ DCHECK(!should_allow_access_to_v8context_with_error_report_option_);
+ DCHECK(func);
+ should_allow_access_to_v8context_with_error_report_option_ = func;
+}
+
+// static
+void BindingSecurityForPlatform::SetShouldAllowWrapperCreationOrThrowException(
+ ShouldAllowWrapperCreationOrThrowExceptionFunction func) {
+ DCHECK(!should_allow_wrapper_creation_or_throw_exception_);
+ DCHECK(func);
+ should_allow_wrapper_creation_or_throw_exception_ = func;
+}
+
+// static
+void BindingSecurityForPlatform::SetRethrowWrapperCreationException(
+ RethrowWrapperCreationExceptionFunction func) {
+ DCHECK(!rethrow_wrapper_creation_exception_);
+ DCHECK(func);
+ rethrow_wrapper_creation_exception_ = func;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.h b/chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.h
new file mode 100644
index 00000000000..1470bc7492f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/bindings/binding_security_for_platform.h
@@ -0,0 +1,101 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_BINDING_SECURITY_FOR_PLATFORM_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_BINDING_SECURITY_FOR_PLATFORM_H_
+
+#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+class ExceptionState;
+struct WrapperTypeInfo;
+
+// BindingSecurityForPlatform provides utility functions that determine access
+// permission between two realms.
+//
+// This class is a collection of trampolines to the actual implementations in
+// BindingSecurity in core/ component.
+class PLATFORM_EXPORT BindingSecurityForPlatform {
+ STATIC_ONLY(BindingSecurityForPlatform);
+
+ public:
+ enum class ErrorReportOption {
+ kDoNotReport,
+ kReport,
+ };
+
+ // These overloads should be used only when checking a general access from
+ // one context to another context. For access to a receiver object or
+ // returned object, you should use BindingSecurity::ShouldAllowAccessTo
+ // family.
+ static bool ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ExceptionState&);
+ static bool ShouldAllowAccessToV8Context(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ErrorReportOption);
+
+ // Checks if a wrapper creation of the given wrapper type associated with
+ // |creation_context| is allowed in |accessing_context|.
+ static bool ShouldAllowWrapperCreationOrThrowException(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> creation_context,
+ const WrapperTypeInfo* wrapper_type_info);
+
+ // Rethrows a cross context exception, that is possibly cross origin.
+ // A SecurityError may be rethrown instead of the exception if necessary.
+ static void RethrowWrapperCreationException(
+ v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> creation_context,
+ const WrapperTypeInfo* wrapper_type_info,
+ v8::Local<v8::Value> cross_context_exception);
+
+ private:
+ using ShouldAllowAccessToV8ContextWithExceptionStateFunction =
+ bool (*)(v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ExceptionState&);
+ using ShouldAllowAccessToV8ContextWithErrorReportOptionFunction =
+ bool (*)(v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> target_context,
+ ErrorReportOption);
+ using ShouldAllowWrapperCreationOrThrowExceptionFunction =
+ bool (*)(v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> creation_context,
+ const WrapperTypeInfo* wrapper_type_info);
+ using RethrowWrapperCreationExceptionFunction =
+ void (*)(v8::Local<v8::Context> accessing_context,
+ v8::Local<v8::Context> creation_context,
+ const WrapperTypeInfo* wrapper_type_info,
+ v8::Local<v8::Value> cross_context_exception);
+
+ static void SetShouldAllowAccessToV8ContextWithExceptionState(
+ ShouldAllowAccessToV8ContextWithExceptionStateFunction);
+ static void SetShouldAllowAccessToV8ContextWithErrorReportOption(
+ ShouldAllowAccessToV8ContextWithErrorReportOptionFunction);
+ static void SetShouldAllowWrapperCreationOrThrowException(
+ ShouldAllowWrapperCreationOrThrowExceptionFunction);
+ static void SetRethrowWrapperCreationException(
+ RethrowWrapperCreationExceptionFunction);
+
+ static ShouldAllowAccessToV8ContextWithExceptionStateFunction
+ should_allow_access_to_v8context_with_exception_state_;
+ static ShouldAllowAccessToV8ContextWithErrorReportOptionFunction
+ should_allow_access_to_v8context_with_error_report_option_;
+ static ShouldAllowWrapperCreationOrThrowExceptionFunction
+ should_allow_wrapper_creation_or_throw_exception_;
+ static RethrowWrapperCreationExceptionFunction
+ rethrow_wrapper_creation_exception_;
+
+ friend class BindingSecurity;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_BINDING_SECURITY_FOR_PLATFORM_H_
diff --git a/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.cc b/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.cc
index afc9e46de98..0777e2cf2b6 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.cc
@@ -54,11 +54,6 @@ static WorldMap& GetWorldMap() {
}
#if DCHECK_IS_ON()
-static bool IsIsolatedWorldId(int world_id) {
- return DOMWrapperWorld::kMainWorldId < world_id &&
- world_id < DOMWrapperWorld::kIsolatedWorldIdLimit;
-}
-
static bool IsMainWorldId(int world_id) {
return world_id == DOMWrapperWorld::kMainWorldId;
}
@@ -212,35 +207,6 @@ void DOMWrapperWorld::SetNonMainWorldHumanReadableName(
IsolatedWorldHumanReadableNames().Set(world_id, human_readable_name);
}
-typedef HashMap<int, bool> IsolatedWorldContentSecurityPolicyMap;
-static IsolatedWorldContentSecurityPolicyMap&
-IsolatedWorldContentSecurityPolicies() {
- DCHECK(IsMainThread());
- DEFINE_STATIC_LOCAL(IsolatedWorldContentSecurityPolicyMap, map, ());
- return map;
-}
-
-bool DOMWrapperWorld::IsolatedWorldHasContentSecurityPolicy() {
- DCHECK(this->IsIsolatedWorld());
- IsolatedWorldContentSecurityPolicyMap& policies =
- IsolatedWorldContentSecurityPolicies();
- IsolatedWorldContentSecurityPolicyMap::iterator it =
- policies.find(GetWorldId());
- return it == policies.end() ? false : it->value;
-}
-
-void DOMWrapperWorld::SetIsolatedWorldContentSecurityPolicy(
- int world_id,
- const String& policy) {
-#if DCHECK_IS_ON()
- DCHECK(IsIsolatedWorldId(world_id));
-#endif
- if (!policy.IsEmpty())
- IsolatedWorldContentSecurityPolicies().Set(world_id, true);
- else
- IsolatedWorldContentSecurityPolicies().erase(world_id);
-}
-
void DOMWrapperWorld::RegisterDOMObjectHolderInternal(
std::unique_ptr<DOMObjectHolderBase> holder_base) {
DCHECK(!dom_object_holders_.Contains(holder_base.get()));
diff --git a/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h b/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h
index 04ca480999d..fca64772026 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h
@@ -59,8 +59,10 @@ class PLATFORM_EXPORT DOMWrapperWorld : public RefCounted<DOMWrapperWorld> {
kInvalidWorldId = -1,
kMainWorldId = 0,
- kEmbedderWorldIdLimit = IsolatedWorldId::kEmbedderWorldIdLimit,
- kIsolatedWorldIdLimit = IsolatedWorldId::kIsolatedWorldIdLimit,
+ kDOMWrapperWorldEmbedderWorldIdLimit =
+ IsolatedWorldId::kEmbedderWorldIdLimit,
+ kDOMWrapperWorldIsolatedWorldIdLimit =
+ IsolatedWorldId::kIsolatedWorldIdLimit,
// Other worlds can use IDs after this. Don't manually pick up an ID from
// this range. generateWorldIdForType() picks it up on behalf of you.
@@ -77,6 +79,11 @@ class PLATFORM_EXPORT DOMWrapperWorld : public RefCounted<DOMWrapperWorld> {
kWorker,
};
+ static bool IsIsolatedWorldId(int world_id) {
+ return DOMWrapperWorld::kMainWorldId < world_id &&
+ world_id < DOMWrapperWorld::kDOMWrapperWorldIsolatedWorldIdLimit;
+ }
+
// Creates a world other than IsolatedWorld. Note this can return nullptr if
// GenerateWorldIdForType fails to allocate a valid id.
static scoped_refptr<DOMWrapperWorld> Create(v8::Isolate*, WorldType);
@@ -119,18 +126,6 @@ class PLATFORM_EXPORT DOMWrapperWorld : public RefCounted<DOMWrapperWorld> {
scoped_refptr<SecurityOrigin>);
SecurityOrigin* IsolatedWorldSecurityOrigin();
- // Associated an isolated world with a Content Security Policy. Resources
- // embedded into the main world's DOM from script executed in an isolated
- // world should be restricted based on the isolated world's DOM, not the
- // main world's.
- //
- // FIXME: Right now, resource injection simply bypasses the main world's
- // DOM. More work is necessary to allow the isolated world's policy to be
- // applied correctly.
- static void SetIsolatedWorldContentSecurityPolicy(int world_id,
- const String& policy);
- bool IsolatedWorldHasContentSecurityPolicy();
-
static bool HasWrapperInAnyWorldInMainThread(ScriptWrappable*);
bool IsMainWorld() const { return world_type_ == WorldType::kMain; }
diff --git a/chromium/third_party/blink/renderer/platform/bindings/parkable_string.cc b/chromium/third_party/blink/renderer/platform/bindings/parkable_string.cc
index 98b53c75d13..f2189c0b52c 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/parkable_string.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/parkable_string.cc
@@ -4,11 +4,24 @@
#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
+#include <string>
+
+#include "base/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
+#include "base/single_thread_task_runner.h"
+#include "base/timer/elapsed_timer.h"
+#include "base/trace_event/trace_event.h"
+#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string_manager.h"
+#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/wtf/address_sanitizer.h"
#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+#include "third_party/zlib/google/compression_utils.h"
namespace blink {
@@ -18,31 +31,110 @@ void RecordParkingAction(ParkableStringImpl::ParkingAction action) {
UMA_HISTOGRAM_ENUMERATION("Memory.MovableStringParkingAction", action);
}
-#if defined(ADDRESS_SANITIZER)
+void RecordStatistics(size_t size,
+ base::TimeDelta duration,
+ ParkableStringImpl::ParkingAction action) {
+ size_t throughput_mb_s =
+ static_cast<size_t>(size / duration.InSecondsF()) / 1000000;
+ size_t size_kb = size / 1000;
+ if (action == ParkableStringImpl::ParkingAction::kParkedInBackground) {
+ UMA_HISTOGRAM_COUNTS_10000("Memory.ParkableString.Compression.SizeKb",
+ size_kb);
+ // Size is at least 10kB, and at most ~1MB, and compression throughput
+ // ranges from single-digit MB/s to ~40MB/s depending on the CPU, hence
+ // the range.
+ UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
+ "Memory.ParkableString.Compression.Latency", duration,
+ base::TimeDelta::FromMicroseconds(500), base::TimeDelta::FromSeconds(1),
+ 100);
+ UMA_HISTOGRAM_COUNTS_1000(
+ "Memory.ParkableString.Compression.ThroughputMBps", throughput_mb_s);
+ } else {
+ UMA_HISTOGRAM_COUNTS_10000("Memory.ParkableString.Decompression.SizeKb",
+ size_kb);
+ UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
+ "Memory.ParkableString.Decompression.Latency", duration,
+ base::TimeDelta::FromMicroseconds(500), base::TimeDelta::FromSeconds(1),
+ 100);
+ // Decompression speed can go up to >500MB/s.
+ UMA_HISTOGRAM_COUNTS_1000(
+ "Memory.ParkableString.Decompression.ThroughputMBps", throughput_mb_s);
+ }
+}
+
void AsanPoisonString(const String& string) {
- const void* start = string.Is8Bit()
- ? static_cast<const void*>(string.Characters8())
- : static_cast<const void*>(string.Characters16());
- ASAN_POISON_MEMORY_REGION(start, string.CharactersSizeInBytes());
+#if defined(ADDRESS_SANITIZER)
+ if (string.IsNull())
+ return;
+ // Since |string| is not deallocated, it remains in the per-thread
+ // AtomicStringTable, where its content can be accessed for equality
+ // comparison for instance, triggering a poisoned memory access.
+ // See crbug.com/883344 for an example.
+ if (string.Impl()->IsAtomic())
+ return;
+
+ ASAN_POISON_MEMORY_REGION(string.Bytes(), string.CharactersSizeInBytes());
+#endif // defined(ADDRESS_SANITIZER)
}
void AsanUnpoisonString(const String& string) {
- const void* start = string.Is8Bit()
- ? static_cast<const void*>(string.Characters8())
- : static_cast<const void*>(string.Characters16());
- ASAN_UNPOISON_MEMORY_REGION(start, string.CharactersSizeInBytes());
-}
+#if defined(ADDRESS_SANITIZER)
+ if (string.IsNull())
+ return;
+
+ ASAN_UNPOISON_MEMORY_REGION(string.Bytes(), string.CharactersSizeInBytes());
#endif // defined(ADDRESS_SANITIZER)
+}
} // namespace
+// Created and destroyed on the same thread, accessed on a background thread as
+// well. |string|'s reference counting is *not* thread-safe, hence |string|'s
+// reference count must *not* change on the background thread.
+struct CompressionTaskParams final {
+ CompressionTaskParams(
+ scoped_refptr<ParkableStringImpl> string,
+ const void* data,
+ size_t size,
+ scoped_refptr<base::SingleThreadTaskRunner> callback_task_runner)
+ : string(string),
+ data(data),
+ size(size),
+ callback_task_runner(std::move(callback_task_runner)) {
+ DCHECK(IsMainThread());
+ }
+
+ ~CompressionTaskParams() { DCHECK(IsMainThread()); }
+
+ const scoped_refptr<ParkableStringImpl> string;
+ const void* data;
+ const size_t size;
+ const scoped_refptr<base::SingleThreadTaskRunner> callback_task_runner;
+
+ CompressionTaskParams(CompressionTaskParams&&) = delete;
+ DISALLOW_COPY_AND_ASSIGN(CompressionTaskParams);
+};
+
+// Valid transitions are:
+// 1. kUnparked -> kParkingInProgress: Parking started asynchronously
+// 2. kParkingInProgress -> kUnparked: Parking did not complete
+// 3. kParkingInProgress -> kParked: Parking completed normally
+// 4. kParked -> kUnparked: String has been unparked.
+//
+// See |Park()| for (1), |OnParkingCompleteOnMainThread()| for 2-3, and
+// |Unpark()| for (4).
+enum class ParkableStringImpl::State { kUnparked, kParkingInProgress, kParked };
+
ParkableStringImpl::ParkableStringImpl(scoped_refptr<StringImpl>&& impl,
ParkableState parkable)
: mutex_(),
lock_depth_(0),
+ state_(State::kUnparked),
string_(std::move(impl)),
- is_parked_(false),
- is_parkable_(parkable == ParkableState::kParkable)
+ compressed_(nullptr),
+ may_be_parked_(parkable == ParkableState::kParkable),
+ is_8bit_(string_.Is8Bit()),
+ length_(string_.length())
#if DCHECK_IS_ON()
,
owning_thread_(CurrentThread())
@@ -53,11 +145,17 @@ ParkableStringImpl::ParkableStringImpl(scoped_refptr<StringImpl>&& impl,
ParkableStringImpl::~ParkableStringImpl() {
AssertOnValidThread();
-#if defined(ADDRESS_SANITIZER)
- AsanUnpoisonString(string_);
+#if DCHECK_IS_ON()
+ {
+ MutexLocker locker(mutex_);
+ DCHECK_EQ(0, lock_depth_);
+ }
#endif
- if (is_parkable_)
- ParkableStringManager::Instance().Remove(string_.Impl());
+ AsanUnpoisonString(string_);
+ DCHECK(state_ == State::kParked || state_ == State::kUnparked);
+
+ if (may_be_parked_)
+ ParkableStringManager::Instance().Remove(this, string_.Impl());
}
void ParkableStringImpl::Lock() {
@@ -78,29 +176,19 @@ void ParkableStringImpl::Unlock() {
// the owning thread may concurrently call |ToString()|. It is then allowed
// to use the string until the end of the current owning thread task.
// Requires DCHECK_IS_ON() for the |owning_thread_| check.
- if (lock_depth_ == 0 && is_parkable_ && string_.Impl()->HasOneRef() &&
- owning_thread_ == CurrentThread()) {
+ //
+ // Checking the owning thread first as CanParkNow() can only be called from
+ // the owning thread.
+ if (owning_thread_ == CurrentThread() && CanParkNow()) {
AsanPoisonString(string_);
}
#endif // defined(ADDRESS_SANITIZER) && DCHECK_IS_ON()
}
-bool ParkableStringImpl::Is8Bit() const {
- AssertOnValidThread();
- return string_.Is8Bit();
-}
-
-bool ParkableStringImpl::IsNull() const {
- AssertOnValidThread();
- return string_.IsNull();
-}
-
const String& ParkableStringImpl::ToString() {
AssertOnValidThread();
MutexLocker locker(mutex_);
-#if defined(ADDRESS_SANITIZER)
AsanUnpoisonString(string_);
-#endif
Unpark();
return string_;
@@ -108,39 +196,177 @@ const String& ParkableStringImpl::ToString() {
unsigned ParkableStringImpl::CharactersSizeInBytes() const {
AssertOnValidThread();
- return string_.CharactersSizeInBytes();
+ return length_ * (is_8bit() ? sizeof(LChar) : sizeof(UChar));
}
-bool ParkableStringImpl::Park() {
+bool ParkableStringImpl::Park(ParkingMode mode) {
AssertOnValidThread();
MutexLocker locker(mutex_);
- DCHECK(is_parkable_);
+ DCHECK(may_be_parked_);
+ if (state_ == State::kUnparked && CanParkNow()) {
+ // Parking can proceed synchronously.
+ if (has_compressed_data()) {
+ RecordParkingAction(ParkingAction::kParkedInBackground);
+ state_ = State::kParked;
+ ParkableStringManager::Instance().OnParked(this, string_.Impl());
+
+ // Must unpoison the memory before releasing it.
+ AsanUnpoisonString(string_);
+ string_ = String();
+ } else if (mode == ParkingMode::kAlways) {
+ // |string_|'s data should not be touched except in the compression task.
+ AsanPoisonString(string_);
+ // |params| keeps |this| alive until |OnParkingCompleteOnMainThread()|.
+ auto params = std::make_unique<CompressionTaskParams>(
+ this, string_.Bytes(), string_.CharactersSizeInBytes(),
+ Thread::Current()->GetTaskRunner());
+ background_scheduler::PostOnBackgroundThread(
+ FROM_HERE, CrossThreadBind(&ParkableStringImpl::CompressInBackground,
+ WTF::Passed(std::move(params))));
+ state_ = State::kParkingInProgress;
+ }
+ }
- if (lock_depth_ != 0)
- return false;
+ return state_ == State::kParked || state_ == State::kParkingInProgress;
+}
- // Cannot park strings with several references.
- if (string_.Impl()->HasOneRef()) {
-#if defined(ADDRESS_SANITIZER)
- AsanPoisonString(string_);
-#endif
- RecordParkingAction(ParkingAction::kParkedInBackground);
- is_parked_ = true;
- }
- return is_parked_;
+bool ParkableStringImpl::is_parked() const {
+ return state_ == State::kParked;
+}
+
+bool ParkableStringImpl::CanParkNow() const {
+ mutex_.AssertAcquired();
+ // Can park iff:
+ // - the string is eligible to parking
+ // - There are no external reference to |string_|. Since |this| holds a
+ // reference to it, then we are the only one.
+ // - |this| is not locked.
+ return may_be_parked_ && string_.Impl()->HasOneRef() && lock_depth_ == 0;
}
void ParkableStringImpl::Unpark() {
AssertOnValidThread();
mutex_.AssertAcquired();
- if (!is_parked_)
+ if (state_ != State::kParked)
return;
+ TRACE_EVENT1("blink", "ParkableStringImpl::Unpark", "size",
+ CharactersSizeInBytes());
+ DCHECK(compressed_);
+ base::ElapsedTimer timer;
+
+ base::StringPiece compressed_string_piece(
+ reinterpret_cast<const char*>(compressed_->data()),
+ compressed_->size() * sizeof(uint8_t));
+ String uncompressed;
+ base::StringPiece uncompressed_string_piece;
+ size_t size = CharactersSizeInBytes();
+ if (is_8bit()) {
+ LChar* data;
+ uncompressed = String::CreateUninitialized(length(), data);
+ uncompressed_string_piece =
+ base::StringPiece(reinterpret_cast<const char*>(data), size);
+ } else {
+ UChar* data;
+ uncompressed = String::CreateUninitialized(length(), data);
+ uncompressed_string_piece =
+ base::StringPiece(reinterpret_cast<const char*>(data), size);
+ }
+
+ // If decompression fails, this is either because:
+ // 1. The output buffer is too small
+ // 2. Compressed data is corrupted
+ // 3. Cannot allocate memory in zlib
+ //
+ // (1-2) are data corruption, and (3) is OOM. In all cases, we cannot recover
+ // the string we need, nothing else to do than to abort.
+ CHECK(compression::GzipUncompress(compressed_string_piece,
+ uncompressed_string_piece));
+ string_ = uncompressed;
+ state_ = State::kUnparked;
+ ParkableStringManager::Instance().OnUnparked(this, string_.Impl());
+
bool backgrounded =
ParkableStringManager::Instance().IsRendererBackgrounded();
- RecordParkingAction(backgrounded ? ParkingAction::kUnparkedInBackground
- : ParkingAction::kUnparkedInForeground);
- is_parked_ = false;
+ auto action = backgrounded ? ParkingAction::kUnparkedInBackground
+ : ParkingAction::kUnparkedInForeground;
+ RecordParkingAction(action);
+ RecordStatistics(CharactersSizeInBytes(), timer.Elapsed(), action);
+}
+
+void ParkableStringImpl::OnParkingCompleteOnMainThread(
+ std::unique_ptr<CompressionTaskParams> params,
+ std::unique_ptr<Vector<uint8_t>> compressed) {
+ MutexLocker locker(mutex_);
+ DCHECK_EQ(State::kParkingInProgress, state_);
+ // Between |Park()| and now, things may have happened:
+ // 1. |ToString()| or
+ // 2. |Lock()| may have been called.
+ //
+ // We only care about "surviving" calls, that is iff the string returned by
+ // |ToString()| is still alive, or whether we are still locked. Since this
+ // function is protected by the lock, no concurrent modifications can occur.
+ //
+ // Finally, since this is a distinct task from any one that can call
+ // |ToString()|, the invariant that the pointer stays valid until the next
+ // task is preserved.
+ if (CanParkNow() && compressed) {
+ RecordParkingAction(ParkingAction::kParkedInBackground);
+ state_ = State::kParked;
+ compressed_ = std::move(compressed);
+ ParkableStringManager::Instance().OnParked(this, string_.Impl());
+
+ // Must unpoison the memory before releasing it.
+ AsanUnpoisonString(string_);
+ string_ = String();
+ } else {
+ state_ = State::kUnparked;
+ }
+}
+
+// static
+void ParkableStringImpl::CompressInBackground(
+ std::unique_ptr<CompressionTaskParams> params) {
+ TRACE_EVENT1("blink", "ParkableStringImpl::CompressInBackground", "size",
+ params->size);
+
+ base::ElapsedTimer timer;
+#if defined(ADDRESS_SANITIZER)
+ // Lock the string to prevent a concurrent |Unlock()| on the main thread from
+ // poisoning the string in the meantime.
+ params->string->Lock();
+#endif // defined(ADDRESS_SANITIZER)
+ // Compression touches the string.
+ AsanUnpoisonString(params->string->string_);
+ base::StringPiece data(reinterpret_cast<const char*>(params->data),
+ params->size);
+ std::string compressed_string;
+ bool ok = compression::GzipCompress(data, &compressed_string);
+
+ std::unique_ptr<Vector<uint8_t>> compressed = nullptr;
+ if (ok && compressed_string.size() < params->size) {
+ compressed = std::make_unique<Vector<uint8_t>>();
+ compressed->Append(
+ reinterpret_cast<const uint8_t*>(compressed_string.c_str()),
+ compressed_string.size());
+ }
+#if defined(ADDRESS_SANITIZER)
+ params->string->Unlock();
+#endif // defined(ADDRESS_SANITIZER)
+
+ auto* task_runner = params->callback_task_runner.get();
+ size_t size = params->size;
+ PostCrossThreadTask(
+ *task_runner, FROM_HERE,
+ CrossThreadBind(
+ [](std::unique_ptr<CompressionTaskParams> params,
+ std::unique_ptr<Vector<uint8_t>> compressed) {
+ auto* string = params->string.get();
+ string->OnParkingCompleteOnMainThread(std::move(params),
+ std::move(compressed));
+ },
+ WTF::Passed(std::move(params)), WTF::Passed(std::move(compressed))));
+ RecordStatistics(size, timer.Elapsed(), ParkingAction::kParkedInBackground);
}
ParkableString::ParkableString(scoped_refptr<StringImpl>&& impl) {
@@ -171,14 +397,14 @@ void ParkableString::Unlock() const {
}
bool ParkableString::Is8Bit() const {
- return impl_->Is8Bit();
+ return impl_->is_8bit();
}
String ParkableString::ToString() const {
return impl_ ? impl_->ToString() : String();
}
-unsigned ParkableString::CharactersSizeInBytes() const {
+wtf_size_t ParkableString::CharactersSizeInBytes() const {
return impl_ ? impl_->CharactersSizeInBytes() : 0;
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/parkable_string.h b/chromium/third_party/blink/renderer/platform/bindings/parkable_string.h
index 12c1dff85cd..d828bcc9c35 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/parkable_string.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/parkable_string.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_PARKABLE_STRING_H_
#include <map>
+#include <memory>
#include <set>
#include <utility>
@@ -26,12 +27,11 @@
//
// As with WTF::AtomicString, this class is *not* thread-safe, and strings
// created on a thread must always be used on the same thread.
-//
-// Implementation note: the string content is not parked yet, it is merely
-// used to gather statistics.
namespace blink {
+struct CompressionTaskParams;
+
// A parked string is parked by calling |Park()|, and unparked by calling
// |ToString()| on a parked string.
// |Lock()| does *not* unpark a string, and |ToString()| must be called on
@@ -49,6 +49,7 @@ class PLATFORM_EXPORT ParkableStringImpl final
};
enum class ParkableState { kParkable, kNotParkable };
+ enum class ParkingMode { kIfCompressedDataExists, kAlways };
// Not all parkable strings can actually be parked. If |parkable| is
// kNotParkable, then one cannot call |Park()|, and the underlying StringImpl
@@ -64,28 +65,62 @@ class PLATFORM_EXPORT ParkableStringImpl final
const String& ToString();
// See the matching String methods.
- bool Is8Bit() const;
- bool IsNull() const;
- unsigned length() const { return string_.length(); }
+ bool is_8bit() const { return is_8bit_; }
+ unsigned length() const { return length_; }
unsigned CharactersSizeInBytes() const;
// A parked string cannot be accessed until it has been |Unpark()|-ed.
- // Returns true iff the string has been parked.
- bool Park();
- // Returns true iff the string can be parked.
- bool is_parkable() const { return is_parkable_; }
+ //
+ // Parking may be synchronous, and will be if compressed data is already
+ // available. If |mode| is |kIfCompressedDataExists|, then parking will always
+ // be synchronous.
+ //
+ // Returns true if the string is being parked or has been parked.
+ bool Park(ParkingMode mode);
+ // Returns true iff the string can be parked. This does not mean that the
+ // string can be parked now, merely that it is eligible to be parked at some
+ // point.
+ bool may_be_parked() const { return may_be_parked_; }
+ // Returns true if the string is parked.
+ bool is_parked() const;
+ // Returns whether synchronous parking is possible, that is the string was
+ // parked in the past.
+ bool has_compressed_data() const { return !!compressed_; }
+ // Returns the compressed size, must not be called unless the string has a
+ // compressed representation.
+ size_t compressed_size() const {
+ DCHECK(has_compressed_data());
+ return compressed_->size();
+ }
private:
+ enum class State;
+
+ // Whether the string can be parked now. Must be called with |mutex_| held,
+ // and the return value is valid as long as the mutex is held.
+ bool CanParkNow() const;
void Unpark();
- // Returns true if the string is parked.
- bool is_parked() const { return is_parked_; }
+ // Called on the main thread after compression is done.
+ // |params| is the same as the one passed to |CompressInBackground()|,
+ // |compressed| is the compressed data, nullptr if compression failed.
+ void OnParkingCompleteOnMainThread(
+ std::unique_ptr<CompressionTaskParams> params,
+ std::unique_ptr<Vector<uint8_t>> compressed);
+
+ // Background thread.
+ static void CompressInBackground(std::unique_ptr<CompressionTaskParams>);
- Mutex mutex_; // protects the variables below.
+ Mutex mutex_; // protects lock_depth_.
int lock_depth_;
+
+ // Main thread only.
+ State state_;
String string_;
- bool is_parked_;
+ std::unique_ptr<Vector<uint8_t>> compressed_;
- const bool is_parkable_;
+ const bool may_be_parked_;
+ const bool is_8bit_;
+ const unsigned length_;
#if DCHECK_IS_ON()
const ThreadIdentifier owning_thread_;
@@ -97,12 +132,8 @@ class PLATFORM_EXPORT ParkableStringImpl final
#endif
}
- FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, Park);
- FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, Unpark);
FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, LockUnlock);
FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, LockParkedString);
- FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, TableSimple);
- FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, TableMultiple);
DISALLOW_COPY_AND_ASSIGN(ParkableStringImpl);
};
@@ -126,14 +157,14 @@ class PLATFORM_EXPORT ParkableString final {
bool Is8Bit() const;
bool IsNull() const { return !impl_; }
unsigned length() const { return impl_ ? impl_->length() : 0; }
- bool is_parkable() const { return impl_ && impl_->is_parkable(); }
+ bool may_be_parked() const { return impl_ && impl_->may_be_parked(); }
ParkableStringImpl* Impl() const { return impl_ ? impl_.get() : nullptr; }
// Returns an unparked version of the string.
// The string is guaranteed to be valid for
// max(lifetime of a copy of the returned reference, current thread task).
String ToString() const;
- unsigned CharactersSizeInBytes() const;
+ wtf_size_t CharactersSizeInBytes() const;
// Causes the string to be unparked. Note that the pointer must not be
// cached.
diff --git a/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc b/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc
index 4042ad47ed4..11b9aa40e8b 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.cc
@@ -9,38 +9,88 @@
#include "base/bind.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
+#include "base/single_thread_task_runner.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
+#include "third_party/blink/renderer/platform/memory_coordinator.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
+class OnPurgeMemoryListener : public GarbageCollected<OnPurgeMemoryListener>,
+ public MemoryCoordinatorClient {
+ USING_GARBAGE_COLLECTED_MIXIN(OnPurgeMemoryListener);
+
+ void OnPurgeMemory() override {
+ if (!base::FeatureList::IsEnabled(kCompressParkableStringsInBackground))
+ return;
+
+ ParkableStringManager::Instance().ParkAllIfRendererBackgrounded(
+ ParkableStringImpl::ParkingMode::kAlways);
+ }
+};
+
ParkableStringManager& ParkableStringManager::Instance() {
DCHECK(IsMainThread());
DEFINE_STATIC_LOCAL(ParkableStringManager, instance, ());
return instance;
}
-ParkableStringManager::~ParkableStringManager() {}
+ParkableStringManager::~ParkableStringManager() = default;
void ParkableStringManager::SetRendererBackgrounded(bool backgrounded) {
+ DCHECK(IsMainThread());
backgrounded_ = backgrounded;
+ if (!base::FeatureList::IsEnabled(kCompressParkableStringsInBackground))
+ return;
+
if (backgrounded_) {
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- Platform::Current()->CurrentThread()->GetTaskRunner();
+ Thread::Current()->GetTaskRunner();
+ DCHECK(task_runner);
task_runner->PostDelayedTask(
FROM_HERE,
base::BindOnce(&ParkableStringManager::ParkAllIfRendererBackgrounded,
- base::Unretained(this)),
- base::TimeDelta::FromSeconds(10));
+ base::Unretained(this),
+ ParkableStringImpl::ParkingMode::kAlways),
+ base::TimeDelta::FromSeconds(kParkingDelayInSeconds));
+ // We only want to record statistics in the following case: a foreground tab
+ // goes to background, and stays in background until the stats are recorded,
+ // to make analysis simpler.
+ //
+ // To that end:
+ // 1. Don't post a recording task if one has been posted and hasn't run yet.
+ // 2. Any background -> foreground transition between now and the
+ // recording task running cancels the task.
+ //
+ // Also drop strings that can be dropped cheaply in this task, to prevent
+ // used-once strings from increasing memory usage.
+ if (!waiting_to_record_stats_) {
+ task_runner->PostDelayedTask(
+ FROM_HERE,
+ base::BindOnce(&ParkableStringManager::
+ DropStringsWithCompressedDataAndRecordStatistics,
+ base::Unretained(this)),
+ base::TimeDelta::FromSeconds(kParkingDelayInSeconds +
+ kStatisticsRecordingDelayInSeconds));
+ waiting_to_record_stats_ = true;
+ should_record_stats_ = true;
+ }
+ } else {
+ // See (2) above.
+ if (waiting_to_record_stats_) {
+ should_record_stats_ = false;
+ }
}
}
bool ParkableStringManager::IsRendererBackgrounded() const {
+ DCHECK(IsMainThread());
return backgrounded_;
}
@@ -54,44 +104,157 @@ bool ParkableStringManager::ShouldPark(const StringImpl& string) {
scoped_refptr<ParkableStringImpl> ParkableStringManager::Add(
scoped_refptr<StringImpl>&& string) {
+ DCHECK(IsMainThread());
StringImpl* raw_ptr = string.get();
- auto it = table_.find(raw_ptr);
- if (it != table_.end())
+ auto it = unparked_strings_.find(raw_ptr);
+ if (it != unparked_strings_.end())
return it->value;
auto new_parkable_string = base::MakeRefCounted<ParkableStringImpl>(
std::move(string), ParkableStringImpl::ParkableState::kParkable);
- table_.insert(raw_ptr, new_parkable_string.get());
+ unparked_strings_.insert(raw_ptr, new_parkable_string.get());
return new_parkable_string;
}
-void ParkableStringManager::Remove(StringImpl* string) {
- DCHECK(string);
- DCHECK(ShouldPark(*string));
- auto it = table_.find(string);
- DCHECK(it != table_.end());
- table_.erase(it);
+void ParkableStringManager::Remove(ParkableStringImpl* string,
+ StringImpl* maybe_unparked_string) {
+ DCHECK(IsMainThread());
+ if (string->is_parked()) {
+ auto it = parked_strings_.find(string);
+ DCHECK(it != parked_strings_.end());
+ parked_strings_.erase(it);
+ } else {
+ DCHECK(maybe_unparked_string);
+ auto it = unparked_strings_.find(maybe_unparked_string);
+ DCHECK(it != unparked_strings_.end());
+ unparked_strings_.erase(it);
+ }
}
-void ParkableStringManager::ParkAllIfRendererBackgrounded() {
+void ParkableStringManager::OnParked(ParkableStringImpl* newly_parked_string,
+ StringImpl* previous_unparked_string) {
DCHECK(IsMainThread());
+ DCHECK(newly_parked_string->is_parked());
+ auto it = unparked_strings_.find(previous_unparked_string);
+ DCHECK(it != unparked_strings_.end());
+ unparked_strings_.erase(it);
+ parked_strings_.insert(newly_parked_string);
+}
+
+void ParkableStringManager::OnUnparked(ParkableStringImpl* was_parked_string,
+ StringImpl* new_unparked_string) {
+ DCHECK(IsMainThread());
+ DCHECK(!was_parked_string->is_parked());
+ auto it = parked_strings_.find(was_parked_string);
+ DCHECK(it != parked_strings_.end());
+ parked_strings_.erase(it);
+ unparked_strings_.insert(new_unparked_string, was_parked_string);
+}
+
+void ParkableStringManager::ParkAllIfRendererBackgrounded(
+ ParkableStringImpl::ParkingMode mode) {
+ DCHECK(IsMainThread());
+ DCHECK(base::FeatureList::IsEnabled(kCompressParkableStringsInBackground));
+
if (!IsRendererBackgrounded())
return;
- size_t total_size = 0, count = 0;
- for (ParkableStringImpl* str : table_.Values()) {
- str->Park();
+ size_t total_size = 0;
+ for (ParkableStringImpl* str : parked_strings_)
+ total_size += str->CharactersSizeInBytes();
+
+ // Parking may be synchronous, need to copy values first.
+ // In case of synchronous parking, |ParkableStringImpl::Park()| calls
+ // |OnParked()|, which moves the string from |unparked_strings_|
+ // to |parked_strings_|, hence the need to copy values first.
+ //
+ // Efficiency: In practice, either we are parking strings for the first time,
+ // and |unparked_strings_| can contain a few 10s of strings (and we will
+ // trigger expensive compression), or this is a subsequent one, and
+ // |unparked_strings_| will have few entries.
+ WTF::Vector<ParkableStringImpl*> unparked;
+ unparked.ReserveCapacity(unparked_strings_.size());
+ for (ParkableStringImpl* str : unparked_strings_.Values())
+ unparked.push_back(str);
+
+ for (ParkableStringImpl* str : unparked) {
+ str->Park(mode);
+ total_size += str->CharactersSizeInBytes();
+ }
+
+ // Only collect stats for "full" parking calls.
+ if (mode == ParkableStringImpl::ParkingMode::kAlways) {
+ size_t total_size_kb = total_size / 1000;
+ UMA_HISTOGRAM_COUNTS_100000("Memory.MovableStringsTotalSizeKb",
+ total_size_kb);
+ UMA_HISTOGRAM_COUNTS_1000("Memory.MovableStringsCount", Size());
+ }
+}
+
+size_t ParkableStringManager::Size() const {
+ return parked_strings_.size() + unparked_strings_.size();
+}
+
+void ParkableStringManager::DropStringsWithCompressedDataAndRecordStatistics() {
+ DCHECK(IsMainThread());
+ DCHECK(base::FeatureList::IsEnabled(kCompressParkableStringsInBackground));
+ DCHECK(waiting_to_record_stats_);
+ waiting_to_record_stats_ = false;
+ if (!should_record_stats_)
+ return;
+ // See |SetRendererBackgrounded()|, is |should_record_stats_| is true then the
+ // renderer is still backgrounded_.
+ DCHECK(IsRendererBackgrounded());
+
+ // We are in the background, drop all the ParkableStrings we can without
+ // costing any CPU (as we already have the compressed representation).
+ ParkAllIfRendererBackgrounded(
+ ParkableStringImpl::ParkingMode::kIfCompressedDataExists);
+
+ size_t total_size = 0, total_before_compression_size = 0;
+ size_t total_compressed_size = 0;
+ for (ParkableStringImpl* str : parked_strings_) {
+ size_t size = str->CharactersSizeInBytes();
+ total_size += size;
+ total_before_compression_size += size;
+ total_compressed_size += str->compressed_size();
+ }
+
+ for (ParkableStringImpl* str : unparked_strings_.Values())
total_size += str->CharactersSizeInBytes();
- count += 1;
+
+ UMA_HISTOGRAM_COUNTS_100000("Memory.ParkableString.TotalSizeKb",
+ total_size / 1000);
+ UMA_HISTOGRAM_COUNTS_100000("Memory.ParkableString.CompressedSizeKb",
+ total_compressed_size / 1000);
+ size_t savings = total_before_compression_size - total_compressed_size;
+ UMA_HISTOGRAM_COUNTS_100000("Memory.ParkableString.SavingsKb",
+ savings / 1000);
+ if (total_before_compression_size != 0) {
+ size_t ratio_percentage =
+ (100 * total_compressed_size) / total_before_compression_size;
+ UMA_HISTOGRAM_PERCENTAGE("Memory.ParkableString.CompressionRatio",
+ ratio_percentage);
}
+}
- size_t total_size_kb = total_size / 1000;
- UMA_HISTOGRAM_COUNTS_100000("Memory.MovableStringsTotalSizeKb",
- total_size_kb);
- UMA_HISTOGRAM_COUNTS_1000("Memory.MovableStringsCount", table_.size());
+void ParkableStringManager::ResetForTesting() {
+ backgrounded_ = false;
+ waiting_to_record_stats_ = false;
+ should_record_stats_ = false;
+ unparked_strings_.clear();
+ parked_strings_.clear();
}
ParkableStringManager::ParkableStringManager()
- : backgrounded_(false), table_() {}
+ : backgrounded_(false),
+ waiting_to_record_stats_(false),
+ should_record_stats_(false),
+ unparked_strings_(),
+ parked_strings_() {
+ // No need to ever unregister, as the only ParkableStringManager instance
+ // lives forever.
+ MemoryCoordinator::Instance().RegisterClient(new OnPurgeMemoryListener());
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.h b/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.h
index 3067372523c..262b9ddea2f 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/parkable_string_manager.h
@@ -5,19 +5,23 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_PARKABLE_STRING_MANAGER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_PARKABLE_STRING_MANAGER_H_
+#include "base/feature_list.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
-#include "base/single_thread_task_runner.h"
+#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
class ParkableString;
-class ParkableStringImpl;
+
+const base::Feature kCompressParkableStringsInBackground{
+ "CompressParkableStringsInBackground", base::FEATURE_DISABLED_BY_DEFAULT};
// Manages all the ParkableStrings, and parks eligible strings after the
// renderer has been backgrounded.
@@ -31,26 +35,42 @@ class PLATFORM_EXPORT ParkableStringManager {
void SetRendererBackgrounded(bool backgrounded);
bool IsRendererBackgrounded() const;
+ // Number of parked and unparked strings. Public for testing.
+ size_t Size() const;
// Whether a string is parkable or not. Can be called from any thread.
static bool ShouldPark(const StringImpl& string);
+ // Public for testing.
+ constexpr static int kParkingDelayInSeconds = 10;
+ constexpr static int kStatisticsRecordingDelayInSeconds = 30;
+
private:
friend class ParkableString;
friend class ParkableStringImpl;
+ friend class OnPurgeMemoryListener;
scoped_refptr<ParkableStringImpl> Add(scoped_refptr<StringImpl>&&);
- void Remove(StringImpl*);
+ void Remove(ParkableStringImpl*, StringImpl*);
- void ParkAllIfRendererBackgrounded();
+ void OnParked(ParkableStringImpl*, StringImpl*);
+ void OnUnparked(ParkableStringImpl*, StringImpl*);
+
+ void ParkAllIfRendererBackgrounded(ParkableStringImpl::ParkingMode mode);
+ void DropStringsWithCompressedDataAndRecordStatistics();
+ void ResetForTesting();
ParkableStringManager();
bool backgrounded_;
- HashMap<StringImpl*, ParkableStringImpl*, PtrHash<StringImpl>> table_;
-
- FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, TableSimple);
- FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, TableMultiple);
+ bool waiting_to_record_stats_;
+ bool should_record_stats_;
+ HashMap<StringImpl*, ParkableStringImpl*, PtrHash<StringImpl>>
+ unparked_strings_;
+ HashSet<ParkableStringImpl*, PtrHash<ParkableStringImpl>> parked_strings_;
+
+ friend class ParkableStringTest;
+ FRIEND_TEST_ALL_PREFIXES(ParkableStringTest, SynchronousCompression);
DISALLOW_COPY_AND_ASSIGN(ParkableStringManager);
};
diff --git a/chromium/third_party/blink/renderer/platform/bindings/parkable_string_test.cc b/chromium/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
index 92053ea6bb7..b186942e1e8 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
@@ -2,36 +2,105 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
-#include "third_party/blink/renderer/platform/bindings/parkable_string_manager.h"
-
#include <thread>
#include <vector>
#include "base/test/metrics/histogram_tester.h"
+#include "base/test/scoped_feature_list.h"
#include "base/test/scoped_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
+#include "third_party/blink/renderer/platform/bindings/parkable_string_manager.h"
+#include "third_party/blink/renderer/platform/memory_coordinator.h"
namespace blink {
namespace {
+constexpr size_t kSizeKb = 20;
+// Compressed size of the string returned by |MakeLargeString()|.
+// Update if the assertion in the |CheckCompressedSize()| test fails.
+constexpr size_t kCompressedSize = 55;
+
String MakeLargeString() {
- std::vector<char> data(20000, 'a');
+ std::vector<char> data(kSizeKb * 1000, 'a');
return String(String(data.data(), data.size()).ReleaseImpl());
}
} // namespace
class ParkableStringTest : public ::testing::Test {
+ public:
+ ParkableStringTest()
+ : ::testing::Test(),
+ scoped_task_environment_(
+ base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME),
+ scoped_feature_list_() {}
+
protected:
+ void RunPostedTasks() { scoped_task_environment_.RunUntilIdle(); }
+
+ void WaitForDelayedParking() {
+ scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(
+ ParkableStringManager::kParkingDelayInSeconds));
+ RunPostedTasks();
+ }
+
+ void WaitForStatisticsRecording() {
+ scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(
+ ParkableStringManager::kStatisticsRecordingDelayInSeconds));
+ RunPostedTasks();
+ }
+
+ bool ParkAndWait(const ParkableString& string) {
+ bool return_value =
+ string.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways);
+ RunPostedTasks();
+ return return_value;
+ }
+
+ ParkableString CreateAndParkAll() {
+ auto& manager = ParkableStringManager::Instance();
+ // Checking that there are no other strings, to make sure this doesn't
+ // cause side-effects.
+ CHECK_EQ(0u, manager.Size());
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ manager.SetRendererBackgrounded(true);
+ EXPECT_FALSE(parkable.Impl()->is_parked());
+ WaitForDelayedParking();
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+ return parkable;
+ }
+
void SetUp() override {
- ParkableStringManager::Instance().SetRendererBackgrounded(false);
+ ParkableStringManager::Instance().ResetForTesting();
+ scoped_feature_list_.InitAndEnableFeature(
+ kCompressParkableStringsInBackground);
+ }
+
+ void TearDown() override {
+ // No leaks.
+ CHECK_EQ(0u, ParkableStringManager::Instance().Size());
+ // Delayed tasks may remain, clear the queues.
+ scoped_task_environment_.FastForwardUntilNoTasksRemain();
+ RunPostedTasks();
}
base::test::ScopedTaskEnvironment scoped_task_environment_;
+ base::test::ScopedFeatureList scoped_feature_list_;
};
+// The main aim of this test is to check that the compressed size of a string
+// doesn't change. If it does, |kCompressedsize| will need to be updated.
+TEST_F(ParkableStringTest, CheckCompressedSize) {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ EXPECT_TRUE(parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ RunPostedTasks();
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+ EXPECT_EQ(kCompressedSize, parkable.Impl()->compressed_size());
+}
+
TEST_F(ParkableStringTest, Simple) {
ParkableString parkable_abc(String("abc").ReleaseImpl());
@@ -40,7 +109,8 @@ TEST_F(ParkableStringTest, Simple) {
EXPECT_TRUE(parkable_abc.Is8Bit());
EXPECT_EQ(3u, parkable_abc.length());
EXPECT_EQ(3u, parkable_abc.CharactersSizeInBytes());
- EXPECT_FALSE(parkable_abc.is_parkable()); // Small strings are not parkable.
+ EXPECT_FALSE(
+ parkable_abc.may_be_parked()); // Small strings are not parkable.
EXPECT_EQ(String("abc"), parkable_abc.ToString());
ParkableString copy = parkable_abc;
@@ -52,24 +122,95 @@ TEST_F(ParkableStringTest, Park) {
{
ParkableString parkable(MakeLargeString().ReleaseImpl());
- EXPECT_TRUE(parkable.is_parkable());
+ EXPECT_TRUE(parkable.may_be_parked());
EXPECT_FALSE(parkable.Impl()->is_parked());
- EXPECT_TRUE(parkable.Impl()->Park());
+ EXPECT_TRUE(ParkAndWait(parkable));
EXPECT_TRUE(parkable.Impl()->is_parked());
}
String large_string = MakeLargeString();
ParkableString parkable(large_string.Impl());
- EXPECT_TRUE(parkable.is_parkable());
+ EXPECT_TRUE(parkable.may_be_parked());
// Not the only one to have a reference to the string.
- EXPECT_FALSE(parkable.Impl()->Park());
+ EXPECT_FALSE(ParkAndWait(parkable));
large_string = String();
- EXPECT_TRUE(parkable.Impl()->Park());
+ EXPECT_TRUE(ParkAndWait(parkable));
histogram_tester.ExpectBucketCount(
"Memory.MovableStringParkingAction",
ParkableStringImpl::ParkingAction::kParkedInBackground, 2);
histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 2);
+
+ {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ EXPECT_TRUE(parkable.may_be_parked());
+ EXPECT_FALSE(parkable.Impl()->is_parked());
+ EXPECT_TRUE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ parkable = ParkableString(); // release the reference.
+ RunPostedTasks(); // Should not crash.
+ }
+}
+
+TEST_F(ParkableStringTest, AbortParking) {
+ {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ EXPECT_TRUE(parkable.may_be_parked());
+ EXPECT_FALSE(parkable.Impl()->is_parked());
+
+ // The string is locked at the end of parking, should cancel it.
+ EXPECT_TRUE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ parkable.Impl()->Lock();
+ RunPostedTasks();
+ EXPECT_FALSE(parkable.Impl()->is_parked());
+
+ // Unlock, OK to park.
+ parkable.Impl()->Unlock();
+ EXPECT_TRUE(ParkAndWait(parkable));
+ }
+
+ {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ // |ToString()| cancels parking as |content| is kept alive.
+ EXPECT_TRUE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ {
+ String content = parkable.Impl()->ToString();
+ RunPostedTasks();
+ EXPECT_FALSE(parkable.Impl()->is_parked());
+ }
+ EXPECT_TRUE(ParkAndWait(parkable));
+ }
+
+ {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ // Transient |Lock()| or |ToString()| doesn't cancel parking.
+ EXPECT_TRUE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ parkable.Impl()->Lock();
+ parkable.Impl()->ToString();
+ parkable.Impl()->Unlock();
+ RunPostedTasks();
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+
+ // Synchronous parking respects locking and external references.
+ parkable.ToString();
+ EXPECT_TRUE(parkable.Impl()->has_compressed_data());
+ parkable.Lock();
+ EXPECT_FALSE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ parkable.Unlock();
+ {
+ String content = parkable.ToString();
+ EXPECT_FALSE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ }
+ // Parking is synchronous.
+ EXPECT_TRUE(
+ parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+ }
}
TEST_F(ParkableStringTest, Unpark) {
@@ -77,9 +218,9 @@ TEST_F(ParkableStringTest, Unpark) {
ParkableString parkable(MakeLargeString().Impl());
String unparked_copy = parkable.ToString().IsolatedCopy();
- EXPECT_TRUE(parkable.is_parkable());
+ EXPECT_TRUE(parkable.may_be_parked());
EXPECT_FALSE(parkable.Impl()->is_parked());
- EXPECT_TRUE(parkable.Impl()->Park());
+ EXPECT_TRUE(ParkAndWait(parkable));
EXPECT_TRUE(parkable.Impl()->is_parked());
String unparked = parkable.ToString();
@@ -109,22 +250,21 @@ TEST_F(ParkableStringTest, LockUnlock) {
EXPECT_EQ(0, impl->lock_depth_);
parkable.Lock();
- EXPECT_FALSE(impl->Park());
+ EXPECT_FALSE(ParkAndWait(parkable));
parkable.Unlock();
- EXPECT_TRUE(impl->Park());
+ EXPECT_TRUE(ParkAndWait(parkable));
+ parkable.ToString();
std::thread t([&]() { parkable.Lock(); });
t.join();
- EXPECT_FALSE(impl->Park());
+ EXPECT_FALSE(ParkAndWait(parkable));
parkable.Unlock();
- EXPECT_TRUE(impl->Park());
+ EXPECT_TRUE(ParkAndWait(parkable));
}
TEST_F(ParkableStringTest, LockParkedString) {
- ParkableString parkable(MakeLargeString().Impl());
+ ParkableString parkable = CreateAndParkAll();
ParkableStringImpl* impl = parkable.Impl();
- EXPECT_EQ(0, impl->lock_depth_);
- EXPECT_TRUE(impl->Park());
parkable.Lock(); // Locking doesn't unpark.
EXPECT_TRUE(impl->is_parked());
@@ -132,44 +272,46 @@ TEST_F(ParkableStringTest, LockParkedString) {
EXPECT_FALSE(impl->is_parked());
EXPECT_EQ(1, impl->lock_depth_);
- EXPECT_FALSE(impl->Park());
+ EXPECT_FALSE(ParkAndWait(parkable));
+
parkable.Unlock();
EXPECT_EQ(0, impl->lock_depth_);
- EXPECT_TRUE(impl->Park());
+ EXPECT_TRUE(ParkAndWait(parkable));
EXPECT_TRUE(impl->is_parked());
}
-TEST_F(ParkableStringTest, TableSimple) {
+TEST_F(ParkableStringTest, ManagerSimple) {
base::HistogramTester histogram_tester;
- std::vector<char> data(20000, 'a');
- ParkableString parkable(String(data.data(), data.size()).ReleaseImpl());
+ ParkableString parkable(MakeLargeString().Impl());
ASSERT_FALSE(parkable.Impl()->is_parked());
auto& manager = ParkableStringManager::Instance();
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
- // Small strings are not in the table.
+ // Small strings are not tracked.
ParkableString small(String("abc").ReleaseImpl());
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
// No parking as the current state is not "backgrounded".
+ manager.SetRendererBackgrounded(true);
manager.SetRendererBackgrounded(false);
ASSERT_FALSE(manager.IsRendererBackgrounded());
- manager.ParkAllIfRendererBackgrounded();
+ WaitForDelayedParking();
EXPECT_FALSE(parkable.Impl()->is_parked());
histogram_tester.ExpectTotalCount("Memory.MovableStringsCount", 0);
manager.SetRendererBackgrounded(true);
ASSERT_TRUE(manager.IsRendererBackgrounded());
- manager.ParkAllIfRendererBackgrounded();
+ WaitForDelayedParking();
EXPECT_TRUE(parkable.Impl()->is_parked());
histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 1, 1);
// Park and unpark.
parkable.ToString();
EXPECT_FALSE(parkable.Impl()->is_parked());
- manager.ParkAllIfRendererBackgrounded();
+ manager.SetRendererBackgrounded(true);
+ WaitForDelayedParking();
EXPECT_TRUE(parkable.Impl()->is_parked());
histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 1, 2);
@@ -177,12 +319,13 @@ TEST_F(ParkableStringTest, TableSimple) {
manager.SetRendererBackgrounded(false);
String alive_unparked = parkable.ToString(); // Unparked in foreground.
manager.SetRendererBackgrounded(true);
- manager.ParkAllIfRendererBackgrounded();
+ WaitForDelayedParking();
EXPECT_FALSE(parkable.Impl()->is_parked());
// Other reference is dropped, OK to park.
alive_unparked = String();
- manager.ParkAllIfRendererBackgrounded();
+ manager.SetRendererBackgrounded(true);
+ WaitForDelayedParking();
EXPECT_TRUE(parkable.Impl()->is_parked());
histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 5);
@@ -197,50 +340,102 @@ TEST_F(ParkableStringTest, TableSimple) {
ParkableStringImpl::ParkingAction::kUnparkedInForeground, 1);
}
-TEST_F(ParkableStringTest, TableMultiple) {
+TEST_F(ParkableStringTest, ManagerMultipleStrings) {
base::HistogramTester histogram_tester;
- size_t size_kb = 20;
- std::vector<char> data(size_kb * 1000, 'a');
- ParkableString parkable(String(data.data(), data.size()).ReleaseImpl());
- ParkableString parkable2(String(data.data(), data.size()).ReleaseImpl());
+ ParkableString parkable(MakeLargeString().Impl());
+ ParkableString parkable2(MakeLargeString().Impl());
auto& manager = ParkableStringManager::Instance();
- EXPECT_EQ(2u, manager.table_.size());
+ EXPECT_EQ(2u, manager.Size());
parkable2 = ParkableString();
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
ParkableString copy = parkable;
parkable = ParkableString();
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
copy = ParkableString();
- EXPECT_EQ(0u, manager.table_.size());
+ EXPECT_EQ(0u, manager.Size());
- String str(data.data(), data.size());
+ String str = MakeLargeString();
ParkableString parkable3(str.Impl());
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
// De-duplicated.
ParkableString other_parkable3(str.Impl());
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
EXPECT_EQ(parkable3.Impl(), other_parkable3.Impl());
- // If all the references to a string are in the table, park it.
+ // If all the references to a string are internal, park it.
str = String();
+ // This string is not parkable, bur should still be in size and count
+ // histograms.
+ ParkableString parkable4(MakeLargeString().Impl());
+ String parkable4_content = parkable4.ToString();
+
+ int parking_count = 0;
manager.SetRendererBackgrounded(true);
+ parking_count++;
ASSERT_TRUE(manager.IsRendererBackgrounded());
- manager.ParkAllIfRendererBackgrounded();
+ WaitForDelayedParking();
EXPECT_TRUE(parkable3.Impl()->is_parked());
+ manager.SetRendererBackgrounded(true);
+ parking_count++;
+ WaitForDelayedParking();
+ WaitForStatisticsRecording();
+ // Even though two parking tasks ran, only one metrics collection.
+ histogram_tester.ExpectUniqueSample("Memory.ParkableString.TotalSizeKb",
+ 2 * kSizeKb, 1);
+ // a 20kB string with only one character compresses down to <1kB, hence with
+ // rounding:
+ // - CompressedSizeKb == 0
+ // - SavingsKb == 19
+ // - CompressionRatio == 0 (<1%)
+ size_t expected_savings = kSizeKb * 1000 - kCompressedSize;
+ histogram_tester.ExpectUniqueSample("Memory.ParkableString.CompressedSizeKb",
+ kCompressedSize / 1000, 1);
+ histogram_tester.ExpectUniqueSample("Memory.ParkableString.SavingsKb",
+ expected_savings / 1000, 1);
+ histogram_tester.ExpectUniqueSample("Memory.ParkableString.CompressionRatio",
+ 100 * kCompressedSize / (kSizeKb * 1000),
+ 1);
+
+ // Don't record statistics if the renderer moves to foreground before
+ // recording statistics.
+ manager.SetRendererBackgrounded(true);
+ parking_count++;
+ manager.SetRendererBackgrounded(false);
+ manager.SetRendererBackgrounded(true);
+ parking_count++;
+ WaitForDelayedParking();
+ WaitForStatisticsRecording();
+ // Same count as above, no stats recording in the meantime.
+ histogram_tester.ExpectUniqueSample("Memory.ParkableString.TotalSizeKb",
+ 2 * kSizeKb, 1);
+
+ // Calling |ParkStringsWithCompressedDataAndRecordStatistics()| resets the
+ // state, can now record stats next time.
+ manager.SetRendererBackgrounded(true);
+ parking_count++;
+ WaitForDelayedParking();
+ WaitForStatisticsRecording();
+ histogram_tester.ExpectUniqueSample("Memory.ParkableString.TotalSizeKb",
+ 2 * kSizeKb, 2);
- // Only drop it from the table when the last one is gone.
+ // Only drop it from the managed strings when the last one is gone.
parkable3 = ParkableString();
- EXPECT_EQ(1u, manager.table_.size());
+ EXPECT_EQ(2u, manager.Size());
other_parkable3 = ParkableString();
- EXPECT_EQ(0u, manager.table_.size());
+ EXPECT_EQ(1u, manager.Size());
+ parkable4 = ParkableString();
+ EXPECT_EQ(0u, manager.Size());
- histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 1, 1);
+ // 1 parked, 1 unparked. Bucket count is 2 as we collected stats twice.
+ histogram_tester.ExpectUniqueSample("Memory.MovableStringsCount", 2,
+ parking_count);
histogram_tester.ExpectUniqueSample("Memory.MovableStringsTotalSizeKb",
- size_kb, 1);
+ 2 * kSizeKb, parking_count);
+
histogram_tester.ExpectTotalCount("Memory.MovableStringParkingAction", 1);
histogram_tester.ExpectBucketCount(
"Memory.MovableStringParkingAction",
@@ -263,4 +458,106 @@ TEST_F(ParkableStringTest, ShouldPark) {
t.join();
}
+#if defined(ADDRESS_SANITIZER)
+TEST_F(ParkableStringTest, AsanPoisoningTest) {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ const LChar* data = parkable.ToString().Characters8();
+ EXPECT_TRUE(ParkAndWait(parkable));
+ EXPECT_DEATH(EXPECT_NE(0, data[10]), "");
+}
+
+// Non-regression test for crbug.com/905137.
+TEST_F(ParkableStringTest, CorrectAsanPoisoning) {
+ ParkableString parkable(MakeLargeString().ReleaseImpl());
+ EXPECT_TRUE(parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways));
+ // A main thread task is posted once compression is done.
+ while (!scoped_task_environment_.MainThreadHasPendingTask()) {
+ parkable.Lock();
+ parkable.ToString();
+ parkable.Unlock();
+ }
+ RunPostedTasks();
+}
+#endif // defined(ADDRESS_SANITIZER)
+
+TEST_F(ParkableStringTest, Compression) {
+ base::HistogramTester histogram_tester;
+
+ ParkableString parkable = CreateAndParkAll();
+ ParkableStringImpl* impl = parkable.Impl();
+
+ EXPECT_TRUE(impl->is_parked());
+ EXPECT_TRUE(impl->has_compressed_data());
+ EXPECT_EQ(kCompressedSize, impl->compressed_size());
+ parkable.ToString(); // First decompression.
+ EXPECT_FALSE(impl->is_parked());
+ EXPECT_TRUE(impl->has_compressed_data());
+ EXPECT_TRUE(
+ impl->Park(ParkableStringImpl::ParkingMode::kIfCompressedDataExists));
+ EXPECT_TRUE(impl->is_parked());
+ parkable.ToString(); // Second decompression.
+
+ histogram_tester.ExpectUniqueSample(
+ "Memory.ParkableString.Compression.SizeKb", kSizeKb, 1);
+ histogram_tester.ExpectTotalCount("Memory.ParkableString.Compression.Latency",
+ 1);
+ histogram_tester.ExpectTotalCount(
+ "Memory.ParkableString.Compression.ThroughputMBps", 1);
+ // |parkable| is decompressed twice.
+ histogram_tester.ExpectUniqueSample(
+ "Memory.ParkableString.Decompression.SizeKb", kSizeKb, 2);
+ histogram_tester.ExpectTotalCount(
+ "Memory.ParkableString.Decompression.Latency", 2);
+ histogram_tester.ExpectTotalCount(
+ "Memory.ParkableString.Decompression.ThroughputMBps", 2);
+}
+
+TEST_F(ParkableStringTest, DelayedTasks) {
+ ParkableStringManager& manager = ParkableStringManager::Instance();
+ base::HistogramTester histogram_tester;
+
+ ParkableString parkable(MakeLargeString().Impl());
+ manager.SetRendererBackgrounded(true);
+
+ // Parking, and statistics.
+ EXPECT_EQ(2u, scoped_task_environment_.GetPendingMainThreadTaskCount());
+ WaitForDelayedParking();
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+ histogram_tester.ExpectUniqueSample(
+ "Memory.ParkableString.Compression.SizeKb", kSizeKb, 1);
+ // Statistics haven't been recorded yet.
+ histogram_tester.ExpectTotalCount("Memory.ParkableString.TotalSizeKb", 0);
+
+ // Statistics task.
+ EXPECT_EQ(1u, scoped_task_environment_.GetPendingMainThreadTaskCount());
+ WaitForStatisticsRecording();
+ EXPECT_EQ(0u, scoped_task_environment_.GetPendingMainThreadTaskCount());
+ // Statistics should have been recorded.
+ histogram_tester.ExpectTotalCount("Memory.ParkableString.TotalSizeKb", 1);
+}
+
+TEST_F(ParkableStringTest, SynchronousCompression) {
+ ParkableStringManager& manager = ParkableStringManager::Instance();
+ ParkableString parkable = CreateAndParkAll();
+
+ parkable.ToString();
+ EXPECT_TRUE(parkable.Impl()->has_compressed_data());
+ // No waiting, synchronous compression.
+ manager.ParkAllIfRendererBackgrounded(
+ ParkableStringImpl::ParkingMode::kIfCompressedDataExists);
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+ scoped_task_environment_.FastForwardUntilNoTasksRemain();
+}
+
+TEST_F(ParkableStringTest, OnPurgeMemory) {
+ ParkableString parkable = CreateAndParkAll();
+
+ parkable.ToString();
+ EXPECT_FALSE(parkable.Impl()->is_parked());
+ EXPECT_TRUE(parkable.Impl()->has_compressed_data());
+
+ MemoryCoordinator::Instance().OnPurgeMemory();
+ EXPECT_TRUE(parkable.Impl()->is_parked());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc b/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc
index 4c248ff1a62..4bbe43d87c6 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc
@@ -188,9 +188,9 @@ void RuntimeCallStats::AddCounterMapStatsToBuilder(
}
#endif
-const char* const RuntimeCallStatsScopedTracer::s_category_group_ =
+constexpr const char* RuntimeCallStatsScopedTracer::s_category_group_ =
TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats");
-const char* const RuntimeCallStatsScopedTracer::s_name_ =
+constexpr const char* RuntimeCallStatsScopedTracer::s_name_ =
"BlinkRuntimeCallStats";
void RuntimeCallStatsScopedTracer::AddBeginTraceEventIfEnabled(
diff --git a/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.h b/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.h
index 98c8bc13410..24643901979 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats.h
@@ -17,6 +17,11 @@
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "v8/include/v8.h"
+#if BUILDFLAG(RCS_COUNT_EVERYTHING)
+#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+#endif
+
namespace base {
class TickClock;
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats_test.cc b/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats_test.cc
index 04287a513fe..7d4061b1a32 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats_test.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/runtime_call_stats_test.cc
@@ -112,7 +112,7 @@ TEST_F(RuntimeCallStatsTest, CountAndTimeAreUpdatedAfterMultipleExecutions) {
const unsigned loops = 5;
RuntimeCallStatsTest* test = this;
- auto func = [&stats, func_duration, test]() {
+ auto func = [&stats, test]() {
RuntimeCallTimer timer(test->clock());
stats.Enter(&timer, test_counter_1_id);
test->AdvanceClock(func_duration);
@@ -135,14 +135,14 @@ TEST_F(RuntimeCallStatsTest, NestedTimersTest) {
const unsigned outer_func_duration = 20;
RuntimeCallStatsTest* test = this;
- auto inner_func = [&stats, inner_func_duration, test]() {
+ auto inner_func = [&stats, test]() {
RuntimeCallTimer timer(test->clock());
stats.Enter(&timer, test_counter_2_id);
test->AdvanceClock(inner_func_duration);
stats.Leave(&timer);
};
- auto outer_func = [&stats, &inner_func, outer_func_duration, test]() {
+ auto outer_func = [&stats, &inner_func, test]() {
RuntimeCallTimer timer(test->clock());
stats.Enter(&timer, test_counter_1_id);
inner_func();
diff --git a/chromium/third_party/blink/renderer/platform/bindings/script_state.cc b/chromium/third_party/blink/renderer/platform/bindings/script_state.cc
index 9e0b06d0056..cd270eba15e 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/script_state.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/script_state.cc
@@ -12,7 +12,7 @@ namespace blink {
ScriptState* ScriptState::Create(v8::Local<v8::Context> context,
scoped_refptr<DOMWrapperWorld> world) {
- return new ScriptState(context, std::move(world));
+ return MakeGarbageCollected<ScriptState>(context, std::move(world));
}
ScriptState::ScriptState(v8::Local<v8::Context> context,
diff --git a/chromium/third_party/blink/renderer/platform/bindings/script_state.h b/chromium/third_party/blink/renderer/platform/bindings/script_state.h
index 0dc01ac7b5e..05b12d078f2 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/script_state.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/script_state.h
@@ -99,6 +99,8 @@ class PLATFORM_EXPORT ScriptState final
static ScriptState* Create(v8::Local<v8::Context>,
scoped_refptr<DOMWrapperWorld>);
+
+ ScriptState(v8::Local<v8::Context>, scoped_refptr<DOMWrapperWorld>);
~ScriptState();
void Trace(blink::Visitor*) {}
@@ -112,6 +114,11 @@ class PLATFORM_EXPORT ScriptState final
return From(info.GetIsolate()->GetCurrentContext());
}
+ static ScriptState* ForCurrentRealm(
+ const v8::PropertyCallbackInfo<v8::Value>& info) {
+ return From(info.GetIsolate()->GetCurrentContext());
+ }
+
static ScriptState* ForRelevantRealm(
const v8::FunctionCallbackInfo<v8::Value>& info) {
return From(info.Holder()->CreationContext());
@@ -164,9 +171,6 @@ class PLATFORM_EXPORT ScriptState final
// termination.
void DissociateContext();
- protected:
- ScriptState(v8::Local<v8::Context>, scoped_refptr<DOMWrapperWorld>);
-
private:
static void OnV8ContextCollectedCallback(
const v8::WeakCallbackInfo<ScriptState>&);
@@ -208,7 +212,16 @@ class ScriptStateProtectingContext
public:
static ScriptStateProtectingContext* Create(ScriptState* script_state) {
- return new ScriptStateProtectingContext(script_state);
+ return MakeGarbageCollected<ScriptStateProtectingContext>(script_state);
+ }
+
+ explicit ScriptStateProtectingContext(ScriptState* script_state)
+ : script_state_(script_state) {
+ if (script_state_) {
+ context_.Set(script_state_->GetIsolate(), script_state_->GetContext());
+ context_.Get().AnnotateStrongRetainer(
+ "blink::ScriptStateProtectingContext::context_");
+ }
}
void Trace(blink::Visitor* visitor) { visitor->Trace(script_state_); }
@@ -227,15 +240,6 @@ class ScriptStateProtectingContext
}
private:
- explicit ScriptStateProtectingContext(ScriptState* script_state)
- : script_state_(script_state) {
- if (script_state_) {
- context_.Set(script_state_->GetIsolate(), script_state_->GetContext());
- context_.Get().AnnotateStrongRetainer(
- "blink::ScriptStateProtectingContext::context_");
- }
- }
-
Member<ScriptState> script_state_;
ScopedPersistent<v8::Context> context_;
};
diff --git a/chromium/third_party/blink/renderer/platform/bindings/script_wrappable.h b/chromium/third_party/blink/renderer/platform/bindings/script_wrappable.h
index 8020b098b13..8bff04164bd 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/script_wrappable.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/script_wrappable.h
@@ -182,9 +182,10 @@ class PLATFORM_EXPORT ScriptWrappable
// i.e. "extern template class EXPORT_API X;"
// However, once we instantiate X, we cannot specialize X after
// the instantiation. i.e. we will see "error: explicit specialization of ...
-// after instantiation". So we cannot define X's s_wrapperTypeInfo in generated
-// code by using specialization. Instead, we need to implement wrapperTypeInfo
-// in X's cpp code, and instantiate X, i.e. "template class X;".
+// after instantiation". So we cannot define X's s_wrapper_type_info in
+// generated code by using specialization. Instead, we need to implement
+// wrapper_type_info in X's cpp code, and instantiate X, i.e. "template class
+// X;".
#define DECLARE_WRAPPERTYPEINFO() \
public: \
const WrapperTypeInfo* GetWrapperTypeInfo() const override; \
diff --git a/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.cc b/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.cc
index cb13a62ae63..c73607fb79a 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.cc
@@ -66,7 +66,7 @@ void ScriptWrappableMarkingVisitor::TraceEpilogue() {
ScheduleIdleLazyCleanup();
}
-void ScriptWrappableMarkingVisitor::AbortTracing() {
+void ScriptWrappableMarkingVisitor::AbortTracingForTermination() {
CHECK(ThreadState::Current());
should_cleanup_ = true;
tracing_in_progress_ = false;
@@ -74,9 +74,8 @@ void ScriptWrappableMarkingVisitor::AbortTracing() {
PerformCleanup();
}
-size_t ScriptWrappableMarkingVisitor::NumberOfWrappersToTrace() {
- CHECK(ThreadState::Current());
- return marking_deque_.size();
+bool ScriptWrappableMarkingVisitor::IsTracingDone() {
+ return marking_deque_.empty();
}
void ScriptWrappableMarkingVisitor::PerformCleanup() {
@@ -99,16 +98,10 @@ void ScriptWrappableMarkingVisitor::PerformCleanup() {
}
void ScriptWrappableMarkingVisitor::ScheduleIdleLazyCleanup() {
- Thread* const thread = Platform::Current()->CurrentThread();
- // Thread might already be gone, or some threads (e.g. PPAPI) don't have a
- // scheduler.
- if (!thread || !thread->Scheduler())
- return;
-
if (idle_cleanup_task_scheduled_)
return;
- Platform::Current()->CurrentThread()->Scheduler()->PostIdleTask(
+ ThreadScheduler::Current()->PostIdleTask(
FROM_HERE, WTF::Bind(&ScriptWrappableMarkingVisitor::PerformLazyCleanup,
WTF::Unretained(this)));
idle_cleanup_task_scheduled_ = true;
diff --git a/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.h b/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.h
index 889d2f03272..20778d6a0de 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.h
@@ -72,6 +72,8 @@ class PLATFORM_EXPORT ScriptWrappableMarkingVisitor
bool WrapperTracingInProgress() const { return tracing_in_progress_; }
+ void AbortTracingForTermination();
+
// v8::EmbedderHeapTracer interface.
void TracePrologue() override;
void RegisterV8References(const std::vector<std::pair<void*, void*>>&
@@ -79,9 +81,8 @@ class PLATFORM_EXPORT ScriptWrappableMarkingVisitor
void RegisterV8Reference(const std::pair<void*, void*>& internal_fields);
bool AdvanceTracing(double deadline_in_ms) override;
void TraceEpilogue() override;
- void AbortTracing() override;
void EnterFinalPause(EmbedderStackState) override;
- size_t NumberOfWrappersToTrace() override;
+ bool IsTracingDone() override;
// ScriptWrappableVisitor interface.
void Visit(const TraceWrapperV8Reference<v8::Value>&) override;
diff --git a/chromium/third_party/blink/renderer/platform/bindings/string_resource.cc b/chromium/third_party/blink/renderer/platform/bindings/string_resource.cc
index ea7f2460a2a..6ff600c0959 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/string_resource.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/string_resource.cc
@@ -4,6 +4,8 @@
#include "third_party/blink/renderer/platform/bindings/string_resource.h"
+#include <type_traits>
+
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
namespace blink {
@@ -92,11 +94,28 @@ StringType ToBlinkString(v8::Local<v8::String> v8_string,
v8::String::ExternalStringResourceBase* resource =
v8_string->GetExternalStringResourceBase(&encoding);
if (LIKELY(!!resource)) {
+ // Inheritance:
+ // - V8 side: v8::String::ExternalStringResourceBase
+ // -> v8::External{One,}ByteStringResource
+ // - Both: StringResource{8,16}Base inherits from the matching v8 class.
+ static_assert(std::is_base_of<v8::String::ExternalOneByteStringResource,
+ StringResource8Base>::value,
+ "");
+ static_assert(std::is_base_of<v8::String::ExternalStringResource,
+ StringResource16Base>::value,
+ "");
+ static_assert(
+ std::is_base_of<StringResourceBase, StringResource8Base>::value, "");
+ static_assert(
+ std::is_base_of<StringResourceBase, StringResource16Base>::value, "");
+ // Then StringResource{8,16}Base allows to go from one ancestry path to
+ // the other one. Even though it's empty, removing it causes UB, see
+ // crbug.com/909796.
StringResourceBase* base;
if (encoding == v8::String::ONE_BYTE_ENCODING)
- base = static_cast<StringResource8*>(resource);
+ base = static_cast<StringResource8Base*>(resource);
else
- base = static_cast<StringResource16*>(resource);
+ base = static_cast<StringResource16Base*>(resource);
return StringTraits<StringType>::FromStringResource(base);
}
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/string_resource.h b/chromium/third_party/blink/renderer/platform/bindings/string_resource.h
index 3207d258def..7874392294e 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/string_resource.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/string_resource.h
@@ -114,57 +114,57 @@ class StringResourceBase {
DISALLOW_COPY_AND_ASSIGN(StringResourceBase);
};
-class StringResource16 final : public StringResourceBase,
- public v8::String::ExternalStringResource {
+// Even though StringResource{8,16}Base are effectively empty in release mode,
+// they are needed as they serve as a common ancestor to Parkable and regular
+// strings.
+//
+// See the comment in |ToBlinkString()|'s implementation for the rationale.
+class StringResource16Base : public StringResourceBase,
+ public v8::String::ExternalStringResource {
public:
- explicit StringResource16(const String& string) : StringResourceBase(string) {
+ explicit StringResource16Base(const String& string)
+ : StringResourceBase(string) {
DCHECK(!string.Is8Bit());
}
- explicit StringResource16(const AtomicString& string)
+ explicit StringResource16Base(const AtomicString& string)
: StringResourceBase(string) {
DCHECK(!string.Is8Bit());
}
- size_t length() const override { return plain_string_.Impl()->length(); }
- const uint16_t* data() const override {
- return reinterpret_cast<const uint16_t*>(
- plain_string_.Impl()->Characters16());
+ explicit StringResource16Base(const ParkableString& parkable_string)
+ : StringResourceBase(parkable_string) {
+ DCHECK(!parkable_string.Is8Bit());
}
- DISALLOW_COPY_AND_ASSIGN(StringResource16);
+ DISALLOW_COPY_AND_ASSIGN(StringResource16Base);
};
-class StringResource8 final : public StringResourceBase,
- public v8::String::ExternalOneByteStringResource {
+class StringResource16 final : public StringResource16Base {
public:
- explicit StringResource8(const String& string) : StringResourceBase(string) {
- DCHECK(string.Is8Bit());
- }
+ explicit StringResource16(const String& string)
+ : StringResource16Base(string) {}
- explicit StringResource8(const AtomicString& string)
- : StringResourceBase(string) {
- DCHECK(string.Is8Bit());
- }
+ explicit StringResource16(const AtomicString& string)
+ : StringResource16Base(string) {}
size_t length() const override { return plain_string_.Impl()->length(); }
- const char* data() const override {
- return reinterpret_cast<const char*>(plain_string_.Impl()->Characters8());
+ const uint16_t* data() const override {
+ return reinterpret_cast<const uint16_t*>(
+ plain_string_.Impl()->Characters16());
}
- DISALLOW_COPY_AND_ASSIGN(StringResource8);
+ DISALLOW_COPY_AND_ASSIGN(StringResource16);
};
-class ParkableStringResource16 final
- : public StringResourceBase,
- public v8::String::ExternalStringResource {
+class ParkableStringResource16 final : public StringResource16Base {
public:
explicit ParkableStringResource16(const ParkableString& string)
- : StringResourceBase(string) {
- DCHECK(!parkable_string_.Is8Bit());
- }
+ : StringResource16Base(string) {}
- bool IsCacheable() const override { return !parkable_string_.is_parkable(); }
+ bool IsCacheable() const override {
+ return !parkable_string_.may_be_parked();
+ }
void Lock() const override { parkable_string_.Lock(); }
@@ -179,16 +179,51 @@ class ParkableStringResource16 final
DISALLOW_COPY_AND_ASSIGN(ParkableStringResource16);
};
-class ParkableStringResource8 final
- : public StringResourceBase,
- public v8::String::ExternalOneByteStringResource {
+class StringResource8Base : public StringResourceBase,
+ public v8::String::ExternalOneByteStringResource {
public:
- explicit ParkableStringResource8(const ParkableString& string)
+ explicit StringResource8Base(const String& string)
: StringResourceBase(string) {
- DCHECK(parkable_string_.Is8Bit());
+ DCHECK(string.Is8Bit());
+ }
+
+ explicit StringResource8Base(const AtomicString& string)
+ : StringResourceBase(string) {
+ DCHECK(string.Is8Bit());
+ }
+
+ explicit StringResource8Base(const ParkableString& parkable_string)
+ : StringResourceBase(parkable_string) {
+ DCHECK(parkable_string.Is8Bit());
}
- bool IsCacheable() const override { return !parkable_string_.is_parkable(); }
+ DISALLOW_COPY_AND_ASSIGN(StringResource8Base);
+};
+
+class StringResource8 final : public StringResource8Base {
+ public:
+ explicit StringResource8(const String& string)
+ : StringResource8Base(string) {}
+
+ explicit StringResource8(const AtomicString& string)
+ : StringResource8Base(string) {}
+
+ size_t length() const override { return plain_string_.Impl()->length(); }
+ const char* data() const override {
+ return reinterpret_cast<const char*>(plain_string_.Impl()->Characters8());
+ }
+
+ DISALLOW_COPY_AND_ASSIGN(StringResource8);
+};
+
+class ParkableStringResource8 final : public StringResource8Base {
+ public:
+ explicit ParkableStringResource8(const ParkableString& string)
+ : StringResource8Base(string) {}
+
+ bool IsCacheable() const override {
+ return !parkable_string_.may_be_parked();
+ }
void Lock() const override { parkable_string_.Lock(); }
diff --git a/chromium/third_party/blink/renderer/platform/bindings/to_v8.h b/chromium/third_party/blink/renderer/platform/bindings/to_v8.h
index 3746e29ea89..75478328831 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/to_v8.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/to_v8.h
@@ -10,6 +10,7 @@
#include <utility>
+#include "base/containers/span.h"
#include "base/optional.h"
#include "third_party/blink/renderer/platform/bindings/callback_function_base.h"
#include "third_party/blink/renderer/platform/bindings/callback_interface_base.h"
@@ -18,6 +19,7 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "v8/include/v8.h"
namespace blink {
@@ -206,6 +208,13 @@ inline v8::Local<v8::Value> ToV8SequenceInternal(
v8::Local<v8::Object> creation_context,
v8::Isolate*);
+template <typename T, size_t Extent>
+inline v8::Local<v8::Value> ToV8(base::span<T, Extent> value,
+ v8::Local<v8::Object> creation_context,
+ v8::Isolate* isolate) {
+ return ToV8SequenceInternal(value, creation_context, isolate);
+}
+
template <typename T, wtf_size_t inlineCapacity>
inline v8::Local<v8::Value> ToV8(const Vector<T, inlineCapacity>& value,
v8::Local<v8::Object> creation_context,
@@ -231,14 +240,19 @@ inline v8::Local<v8::Value> ToV8(const Vector<std::pair<String, T>>& value,
v8::Context::Scope context_scope(creation_context->CreationContext());
object = v8::Object::New(isolate);
}
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (unsigned i = 0; i < value.size(); ++i) {
v8::Local<v8::Value> v8_value = ToV8(value[i].second, object, isolate);
if (v8_value.IsEmpty())
v8_value = v8::Undefined(isolate);
- if (!V8CallBoolean(object->CreateDataProperty(
- isolate->GetCurrentContext(), V8String(isolate, value[i].first),
- v8_value)))
+ bool created_property;
+ if (!object
+ ->CreateDataProperty(
+ context, V8AtomicString(isolate, value[i].first), v8_value)
+ .To(&created_property) ||
+ !created_property) {
return v8::Local<v8::Value>();
+ }
}
return object;
}
@@ -252,14 +266,19 @@ inline v8::Local<v8::Value> ToV8(const HeapVector<std::pair<String, T>>& value,
v8::Context::Scope context_scope(creation_context->CreationContext());
object = v8::Object::New(isolate);
}
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (unsigned i = 0; i < value.size(); ++i) {
v8::Local<v8::Value> v8_value = ToV8(value[i].second, object, isolate);
if (v8_value.IsEmpty())
v8_value = v8::Undefined(isolate);
- if (!V8CallBoolean(object->CreateDataProperty(
- isolate->GetCurrentContext(), V8String(isolate, value[i].first),
- v8_value)))
+ bool created_property;
+ if (!object
+ ->CreateDataProperty(
+ context, V8AtomicString(isolate, value[i].first), v8_value)
+ .To(&created_property) ||
+ !created_property) {
return v8::Local<v8::Value>();
+ }
}
return object;
}
@@ -274,8 +293,9 @@ inline v8::Local<v8::Value> ToV8SequenceInternal(
v8::Local<v8::Array> array;
{
v8::Context::Scope context_scope(creation_context->CreationContext());
- array = v8::Array::New(isolate, sequence.size());
+ array = v8::Array::New(isolate, SafeCast<int>(sequence.size()));
}
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
uint32_t index = 0;
typename Sequence::const_iterator end = sequence.end();
for (typename Sequence::const_iterator iter = sequence.begin(); iter != end;
@@ -283,9 +303,12 @@ inline v8::Local<v8::Value> ToV8SequenceInternal(
v8::Local<v8::Value> value = ToV8(*iter, array, isolate);
if (value.IsEmpty())
value = v8::Undefined(isolate);
- if (!V8CallBoolean(array->CreateDataProperty(isolate->GetCurrentContext(),
- index++, value)))
+ bool created_property;
+ if (!array->CreateDataProperty(context, index++, value)
+ .To(&created_property) ||
+ !created_property) {
return v8::Local<v8::Value>();
+ }
}
return array;
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h b/chromium/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h
index 78f0ba21b77..21bb8db0d92 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h
@@ -53,8 +53,8 @@ class TraceWrapperV8Reference {
bool IsEmpty() const { return handle_.IsEmpty(); }
void Clear() { handle_.Reset(); }
- ALWAYS_INLINE const v8::Persistent<T>& Get() const { return handle_; }
- ALWAYS_INLINE v8::Persistent<T>& Get() { return handle_; }
+ ALWAYS_INLINE const v8::Global<T>& Get() const { return handle_; }
+ ALWAYS_INLINE v8::Global<T>& Get() { return handle_; }
template <typename S>
const TraceWrapperV8Reference<S>& Cast() const {
@@ -77,7 +77,7 @@ class TraceWrapperV8Reference {
UnifiedHeapMarkingVisitor::WriteBarrier(isolate, UnsafeCast<v8::Value>());
}
- v8::Persistent<T> handle_;
+ v8::Global<T> handle_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_binding.h b/chromium/third_party/blink/renderer/platform/bindings/v8_binding.h
index f5209d21c8a..378f5434309 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_binding.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_binding.h
@@ -328,25 +328,6 @@ inline v8::Local<v8::String> V8AtomicString(v8::Isolate* isolate,
.ToLocalChecked();
}
-inline v8::Local<v8::String> V8StringFromUtf8(v8::Isolate* isolate,
- const char* bytes,
- int length) {
- DCHECK(isolate);
- return v8::String::NewFromUtf8(isolate, bytes, v8::NewStringType::kNormal,
- length)
- .ToLocalChecked();
-}
-
-inline v8::Local<v8::Value> V8Undefined() {
- return v8::Local<v8::Value>();
-}
-
-inline v8::MaybeLocal<v8::Value> V8DateOrNaN(v8::Isolate* isolate,
- double value) {
- DCHECK(isolate);
- return v8::Date::New(isolate->GetCurrentContext(), value);
-}
-
inline bool IsUndefinedOrNull(v8::Local<v8::Value> value) {
return value.IsEmpty() || value->IsNullOrUndefined();
}
@@ -364,8 +345,10 @@ static void IndexedPropertyEnumerator(
v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
for (int i = 0; i < length; ++i) {
v8::Local<v8::Integer> integer = v8::Integer::New(info.GetIsolate(), i);
- if (!V8CallBoolean(properties->CreateDataProperty(context, i, integer)))
+ bool created;
+ if (!properties->CreateDataProperty(context, i, integer).To(&created))
return;
+ DCHECK(created);
}
V8SetReturnValue(info, properties);
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_binding_macros.h b/chromium/third_party/blink/renderer/platform/bindings/v8_binding_macros.h
index 83751de1266..53b2bddb02b 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_binding_macros.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_binding_macros.h
@@ -59,12 +59,6 @@ namespace blink {
? alloca(value.As<v8::ArrayBufferView>()->ByteLength()) \
: nullptr)
-// DEPRECATED
-inline bool V8CallBoolean(v8::Maybe<bool> maybe) {
- bool result;
- return maybe.To(&result) && result;
-}
-
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_V8_BINDING_MACROS_H_
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc b/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc
index adee1ee25f7..798b4d236c9 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc
@@ -62,7 +62,7 @@ v8::Local<v8::Object> V8DOMWrapper::CreateWrapper(
// V8PerContextData::createWrapperFromCache, though there is no need to
// cache resulting objects or their constructors.
const DOMWrapperWorld& world = DOMWrapperWorld::World(scope.GetContext());
- wrapper = type->domTemplate(isolate, world)
+ wrapper = type->DomTemplate(isolate, world)
->InstanceTemplate()
->NewInstance(scope.GetContext())
.ToLocalChecked();
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h b/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h
index a91198ca0c4..5905a1733af 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h
@@ -32,13 +32,13 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_V8_DOM_WRAPPER_H_
#include "base/stl_util.h"
+#include "third_party/blink/renderer/platform/bindings/binding_security_for_platform.h"
#include "third_party/blink/renderer/platform/bindings/custom_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/dom_data_store.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable_marking_visitor.h"
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
-#include "third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h"
#include "third_party/blink/renderer/platform/heap/unified_heap_marking_visitor.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/compiler.h"
@@ -185,9 +185,8 @@ class V8WrapperInstantiationScope {
if (context_for_wrapper == context_)
return;
- context_ = context_for_wrapper;
-
- if (!WrapperCreationSecurityCheck::VerifyContextAccess(context_, type_)) {
+ if (!BindingSecurityForPlatform::ShouldAllowWrapperCreationOrThrowException(
+ isolate->GetCurrentContext(), context_for_wrapper, type_)) {
DCHECK(try_catch_.HasCaught());
try_catch_.ReThrow();
access_check_failed_ = true;
@@ -195,6 +194,7 @@ class V8WrapperInstantiationScope {
}
did_enter_context_ = true;
+ context_ = context_for_wrapper;
context_->Enter();
}
@@ -214,8 +214,9 @@ class V8WrapperInstantiationScope {
// such a scenario.
v8::Local<v8::Value> caught_exception = try_catch_.Exception();
try_catch_.Reset();
- WrapperCreationSecurityCheck::RethrowCrossContextException(
- context_, type_, caught_exception);
+ BindingSecurityForPlatform::RethrowWrapperCreationException(
+ context_->GetIsolate()->GetCurrentContext(), context_, type_,
+ caught_exception);
try_catch_.ReThrow();
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_object_constructor.cc b/chromium/third_party/blink/renderer/platform/bindings/v8_object_constructor.cc
index 87f2176ce89..e1378ffcd7e 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_object_constructor.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_object_constructor.cc
@@ -74,10 +74,10 @@ v8::Local<v8::Function> V8ObjectConstructor::CreateInterfaceObject(
v8::Local<v8::Function> parent_interface,
CreationMode creation_mode) {
// We shouldn't reach this point for the types that are implemented in v8 such
- // as typed arrays and hence don't have domTemplateFunction.
+ // as typed arrays and hence don't have DomTemplateFunction.
DCHECK(type->dom_template_function);
v8::Local<v8::FunctionTemplate> interface_template =
- type->domTemplate(isolate, world);
+ type->DomTemplate(isolate, world);
// Getting the function might fail if we're running out of stack or memory.
v8::Local<v8::Function> interface_object;
bool get_interface_object =
@@ -102,11 +102,6 @@ v8::Local<v8::Function> V8ObjectConstructor::CreateInterfaceObject(
CHECK(prototype_value->IsObject());
prototype_object = prototype_value.As<v8::Object>();
- if (prototype_object->InternalFieldCount() ==
- kV8PrototypeInternalFieldcount) {
- prototype_object->SetAlignedPointerInInternalField(
- kV8PrototypeTypeIndex, const_cast<WrapperTypeInfo*>(type));
- }
}
if (creation_mode == CreationMode::kInstallConditionalFeatures) {
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc b/chromium/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc
index 70b71cff50e..20c5c4df946 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc
@@ -52,7 +52,7 @@ V8PerContextData::V8PerContextData(v8::Local<v8::Context> context)
context_holder_(std::make_unique<gin::ContextHolder>(isolate_)),
context_(isolate_, context),
activity_logger_(nullptr),
- data_map_(new DataMap()) {
+ data_map_(MakeGarbageCollected<DataMap>()) {
context_holder_->SetContext(context);
context_.Get().AnnotateStrongRetainer("blink::V8PerContextData::context_");
diff --git a/chromium/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc b/chromium/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc
index 6694666d313..eed599acde1 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc
@@ -100,7 +100,7 @@ V8PerIsolateData::V8PerIsolateData(
// the main thread.
V8PerIsolateData::V8PerIsolateData()
: v8_context_snapshot_mode_(V8ContextSnapshotMode::kTakeSnapshot),
- isolate_holder_(Platform::Current()->MainThread()->GetTaskRunner(),
+ isolate_holder_(Thread::Current()->GetTaskRunner(),
gin::IsolateHolder::kSingleThread,
gin::IsolateHolder::kAllowAtomicsWait,
gin::IsolateHolder::IsolateType::kBlinkMainThread,
@@ -171,7 +171,7 @@ void V8PerIsolateData::WillBeDestroyed(v8::Isolate* isolate) {
}
isolate->SetEmbedderHeapTracer(nullptr);
if (data->script_wrappable_visitor_->WrapperTracingInProgress())
- data->script_wrappable_visitor_->AbortTracing();
+ data->script_wrappable_visitor_->AbortTracingForTermination();
data->script_wrappable_visitor_.reset();
}
@@ -379,8 +379,10 @@ V8PerIsolateData::Data* V8PerIsolateData::ThreadDebugger() {
void V8PerIsolateData::AddActiveScriptWrappable(
ActiveScriptWrappableBase* wrappable) {
- if (!active_script_wrappables_)
- active_script_wrappables_ = new ActiveScriptWrappableSet();
+ if (!active_script_wrappables_) {
+ active_script_wrappables_ =
+ MakeGarbageCollected<ActiveScriptWrappableSet>();
+ }
active_script_wrappables_->insert(wrappable);
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.cc b/chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.cc
deleted file mode 100644
index 8d9b988583c..00000000000
--- a/chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h"
-
-#include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h"
-
-namespace blink {
-
-WrapperCreationSecurityCheck::SecurityCheckFunction
- WrapperCreationSecurityCheck::security_check_ = nullptr;
-WrapperCreationSecurityCheck::RethrowExceptionFunction
- WrapperCreationSecurityCheck::rethrow_exception_ = nullptr;
-
-void WrapperCreationSecurityCheck::SetSecurityCheckFunction(
- SecurityCheckFunction func) {
- DCHECK(!security_check_);
- security_check_ = func;
-}
-
-void WrapperCreationSecurityCheck::SetRethrowExceptionFunction(
- RethrowExceptionFunction func) {
- DCHECK(!rethrow_exception_);
- rethrow_exception_ = func;
-}
-
-bool WrapperCreationSecurityCheck::VerifyContextAccess(
- v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo* type) {
- return (*security_check_)(creation_context, type);
-}
-
-void WrapperCreationSecurityCheck::RethrowCrossContextException(
- v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo* type,
- v8::Local<v8::Value> cross_context_exception) {
- (*rethrow_exception_)(creation_context, type, cross_context_exception);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h b/chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h
deleted file mode 100644
index a5f6ea1bf63..00000000000
--- a/chromium/third_party/blink/renderer/platform/bindings/wrapper_creation_security_check.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_WRAPPER_CREATION_SECURITY_CHECK_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_WRAPPER_CREATION_SECURITY_CHECK_H_
-
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "v8/include/v8.h"
-
-namespace blink {
-
-struct WrapperTypeInfo;
-
-// This class holds pointers to functions that implement creation context access
-// and exception rethrowing logic required by V8WrapperInstantiationScope when
-// creating wrappers.
-class PLATFORM_EXPORT WrapperCreationSecurityCheck {
- STATIC_ONLY(WrapperCreationSecurityCheck);
-
- public:
- using SecurityCheckFunction = bool (*)(v8::Local<v8::Context>,
- const WrapperTypeInfo*);
- using RethrowExceptionFunction = void (*)(v8::Local<v8::Context>,
- const WrapperTypeInfo*,
- v8::Local<v8::Value>);
-
- static void SetSecurityCheckFunction(SecurityCheckFunction);
- static void SetRethrowExceptionFunction(RethrowExceptionFunction);
-
- static bool VerifyContextAccess(v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo*);
- static void RethrowCrossContextException(
- v8::Local<v8::Context> creation_context,
- const WrapperTypeInfo*,
- v8::Local<v8::Value> cross_context_exception);
-
- private:
- static SecurityCheckFunction security_check_;
- static RethrowExceptionFunction rethrow_exception_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_WRAPPER_CREATION_SECURITY_CHECK_H_
diff --git a/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.cc b/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.cc
index f4f4d7dfd66..45c8cc662cc 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.cc
+++ b/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.cc
@@ -21,14 +21,8 @@ void WrapperTypeInfo::WrapperCreated() {
}
void WrapperTypeInfo::WrapperDestroyed() {
- ThreadState* const thread_state = ThreadState::Current();
- // WrapperDestroyed may be called during thread teardown as part of invoking
- // V8 callbacks in which case ThreadState has already been destroyed.
- if (!thread_state)
- return;
-
ThreadHeapStatsCollector* stats_collector =
- thread_state->Heap().stats_collector();
+ ThreadState::Current()->Heap().stats_collector();
stats_collector->DecreaseWrapperCount(1);
stats_collector->IncreaseCollectedWrapperCount(1);
}
diff --git a/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.h b/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.h
index 1a913f2be52..13a672f575c 100644
--- a/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.h
+++ b/chromium/third_party/blink/renderer/platform/bindings/wrapper_type_info.h
@@ -55,7 +55,8 @@ static const int kV8DOMWrapperObjectIndex =
static_cast<int>(gin::kEncodedValueIndex);
static const int kV8DefaultWrapperInternalFieldCount =
static_cast<int>(gin::kNumberOfInternalFields);
-static const int kV8PrototypeTypeIndex = 0;
+// The value of the following field isn't used (only its presence), hence no
+// corresponding Index constant exists for it.
static const int kV8PrototypeInternalFieldcount = 1;
typedef v8::Local<v8::FunctionTemplate> (
@@ -121,7 +122,7 @@ struct WrapperTypeInfo {
wrapper->SetWrapperClassId(wrapper_class_id);
}
- v8::Local<v8::FunctionTemplate> domTemplate(
+ v8::Local<v8::FunctionTemplate> DomTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world) const {
return dom_template_function(isolate, world);
diff --git a/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider.cc b/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider.cc
index f52dc45d2bd..32e89b09d5a 100644
--- a/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider.cc
+++ b/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider.cc
@@ -10,8 +10,8 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -32,11 +32,12 @@ class BlobBytesStreamer {
mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC,
std::move(task_runner)) {
watcher_.Watch(pipe_.get(), MOJO_HANDLE_SIGNAL_WRITABLE,
+ MOJO_WATCH_CONDITION_SATISFIED,
WTF::BindRepeating(&BlobBytesStreamer::OnWritable,
WTF::Unretained(this)));
}
- void OnWritable(MojoResult result) {
+ void OnWritable(MojoResult result, const mojo::HandleSignalsState& state) {
if (result == MOJO_RESULT_CANCELLED ||
result == MOJO_RESULT_FAILED_PRECONDITION) {
delete this;
@@ -89,9 +90,8 @@ class BlobBytesStreamer {
// This keeps the process alive while blobs are being transferred.
void IncreaseChildProcessRefCount() {
- if (!Platform::Current()->MainThread()->IsCurrentThread()) {
- PostCrossThreadTask(*Platform::Current()->MainThread()->GetTaskRunner(),
- FROM_HERE,
+ if (!WTF::IsMainThread()) {
+ PostCrossThreadTask(*Thread::MainThread()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(&IncreaseChildProcessRefCount));
return;
}
@@ -99,9 +99,8 @@ void IncreaseChildProcessRefCount() {
}
void DecreaseChildProcessRefCount() {
- if (!Platform::Current()->MainThread()->IsCurrentThread()) {
- PostCrossThreadTask(*Platform::Current()->MainThread()->GetTaskRunner(),
- FROM_HERE,
+ if (!WTF::IsMainThread()) {
+ PostCrossThreadTask(*Thread::MainThread()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(&DecreaseChildProcessRefCount));
return;
}
diff --git a/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider_test.cc b/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider_test.cc
index b6f890e00eb..4c06a7cf227 100644
--- a/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider_test.cc
+++ b/chromium/third_party/blink/renderer/platform/blob/blob_bytes_provider_test.cc
@@ -336,9 +336,11 @@ TEST_F(BlobBytesProviderTest, RequestAsStream) {
blink::scheduler::GetSequencedTaskRunnerForTesting());
watcher.Watch(
pipe.consumer_handle.get(), MOJO_HANDLE_SIGNAL_READABLE,
+ MOJO_WATCH_CONDITION_SATISFIED,
base::BindRepeating(
[](mojo::DataPipeConsumerHandle pipe, base::Closure quit_closure,
- Vector<uint8_t>* bytes_out, MojoResult result) {
+ Vector<uint8_t>* bytes_out, MojoResult result,
+ const mojo::HandleSignalsState& state) {
if (result == MOJO_RESULT_CANCELLED ||
result == MOJO_RESULT_FAILED_PRECONDITION) {
quit_closure.Run();
diff --git a/chromium/third_party/blink/renderer/platform/blob/blob_data.cc b/chromium/third_party/blink/renderer/platform/blob/blob_data.cc
index 57889d8d652..2abdefe328a 100644
--- a/chromium/third_party/blink/renderer/platform/blob/blob_data.cc
+++ b/chromium/third_party/blink/renderer/platform/blob/blob_data.cc
@@ -48,7 +48,6 @@
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/text/line_ending.h"
#include "third_party/blink/renderer/platform/uuid.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/platform/cross_thread_copier.h b/chromium/third_party/blink/renderer/platform/cross_thread_copier.h
index 738ceed65ed..4c14240beb2 100644
--- a/chromium/third_party/blink/renderer/platform/cross_thread_copier.h
+++ b/chromium/third_party/blink/renderer/platform/cross_thread_copier.h
@@ -183,6 +183,13 @@ struct CrossThreadCopier<
};
template <wtf_size_t inlineCapacity, typename Allocator>
+struct CrossThreadCopier<Vector<uint8_t, inlineCapacity, Allocator>> {
+ STATIC_ONLY(CrossThreadCopier);
+ using Type = Vector<uint8_t, inlineCapacity, Allocator>;
+ static Type Copy(Type value) { return value; }
+};
+
+template <wtf_size_t inlineCapacity, typename Allocator>
struct CrossThreadCopier<Vector<uint64_t, inlineCapacity, Allocator>> {
STATIC_ONLY(CrossThreadCopier);
using Type = Vector<uint64_t, inlineCapacity, Allocator>;
diff --git a/chromium/third_party/blink/renderer/platform/cross_thread_functional.h b/chromium/third_party/blink/renderer/platform/cross_thread_functional.h
index 4e9db67273b..de9e71eb589 100644
--- a/chromium/third_party/blink/renderer/platform/cross_thread_functional.h
+++ b/chromium/third_party/blink/renderer/platform/cross_thread_functional.h
@@ -30,7 +30,7 @@ namespace blink {
template <typename FunctionType, typename... Ps>
WTF::CrossThreadFunction<base::MakeUnboundRunType<FunctionType, Ps...>>
-CrossThreadBind(FunctionType function, Ps&&... parameters) {
+CrossThreadBind(FunctionType&& function, Ps&&... parameters) {
static_assert(
WTF::internal::CheckGCedTypeRestrictions<std::index_sequence_for<Ps...>,
std::decay_t<Ps>...>::ok,
diff --git a/chromium/third_party/blink/renderer/platform/data_resource_helper.cc b/chromium/third_party/blink/renderer/platform/data_resource_helper.cc
index b0e6ab17f3c..349661443fb 100644
--- a/chromium/third_party/blink/renderer/platform/data_resource_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/data_resource_helper.cc
@@ -7,9 +7,22 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_data.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+#include "third_party/zlib/google/compression_utils.h"
+#include "ui/base/resource/resource_bundle.h"
namespace blink {
+namespace {
+
+std::string GetResourceById(int resource_id) {
+ ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
+ return bundle
+ .GetRawDataResourceForScale(resource_id, bundle.GetMaxScaleFactor())
+ .as_string();
+}
+
+} // namespace
+
String GetDataResourceAsASCIIString(const char* resource) {
StringBuilder builder;
const WebData& resource_data = Platform::Current()->GetDataResource(resource);
@@ -23,8 +36,19 @@ String GetDataResourceAsASCIIString(const char* resource) {
String data_string = builder.ToString();
DCHECK(!data_string.IsEmpty());
- DCHECK(data_string.ContainsOnlyASCII());
+ DCHECK(data_string.ContainsOnlyASCIIOrEmpty());
return data_string;
}
+String GetResourceAsString(int resource_id) {
+ return String::FromUTF8(GetResourceById(resource_id).c_str());
+};
+
+String UncompressResourceAsString(int resource_id) {
+ std::string uncompressed;
+ CHECK(
+ compression::GzipUncompress(GetResourceById(resource_id), &uncompressed));
+ return String::FromUTF8(uncompressed.c_str());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/data_resource_helper.h b/chromium/third_party/blink/renderer/platform/data_resource_helper.h
index f9811bf0056..638a0c67472 100644
--- a/chromium/third_party/blink/renderer/platform/data_resource_helper.h
+++ b/chromium/third_party/blink/renderer/platform/data_resource_helper.h
@@ -10,8 +10,20 @@
namespace blink {
+// Helper functions providing access to ui::ResourceBundle in Blink.
+
+// Returns the contents of a resource as a string specified by the
+// resource name.
PLATFORM_EXPORT String GetDataResourceAsASCIIString(const char* resource);
+// Returns the contents of a resource as a string specified by the
+// resource id from Grit.
+PLATFORM_EXPORT String GetResourceAsString(int resource_id);
+
+// Uncompresses a gzipped resource and returns it as a string. The resource
+// is specified by the resource id from Grit.
+PLATFORM_EXPORT String UncompressResourceAsString(int resource_id);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_DATA_RESOURCE_HELPER_H_
diff --git a/chromium/third_party/blink/renderer/platform/exported/platform.cc b/chromium/third_party/blink/renderer/platform/exported/platform.cc
index 13a3cf4cb27..5e03ba6e8ed 100644
--- a/chromium/third_party/blink/renderer/platform/exported/platform.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/platform.cc
@@ -33,7 +33,6 @@
#include <memory>
#include "base/single_thread_task_runner.h"
-#include "base/synchronization/waitable_event.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/memory_dump_manager.h"
#include "build/build_config.h"
@@ -41,7 +40,6 @@
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/interface_provider.h"
#include "third_party/blink/public/platform/modules/webmidi/web_midi_accessor.h"
-#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
#include "third_party/blink/public/platform/web_canvas_capture_handler.h"
#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
@@ -66,10 +64,11 @@
#include "third_party/blink/renderer/platform/memory_coordinator.h"
#include "third_party/blink/renderer/platform/partition_alloc_memory_dump_provider.h"
#include "third_party/blink/renderer/platform/scheduler/common/simple_thread_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/webrtc/api/rtpparameters.h"
+#include "third_party/webrtc/p2p/base/portallocator.h"
namespace blink {
@@ -109,11 +108,11 @@ static void MaxObservedSizeFunction(size_t size_in_mb) {
static void CallOnMainThreadFunction(WTF::MainThreadFunction function,
void* context) {
PostCrossThreadTask(
- *Platform::Current()->MainThread()->GetTaskRunner(), FROM_HERE,
+ *Thread::MainThread()->GetTaskRunner(), FROM_HERE,
CrossThreadBind(function, CrossThreadUnretained(context)));
}
-Platform::Platform() : main_thread_(nullptr) {
+Platform::Platform() {
WTF::Partitions::Initialize(MaxObservedSizeFunction);
}
@@ -140,7 +139,6 @@ class SimpleMainThread : public Thread {
// This function is called from Platform::SetMainThreadTaskRunnerForTesting()
// and Platform::UnsetMainThreadTaskRunnerForTesting().
- bool IsCurrentThread() const override { return WTF::IsMainThread(); }
ThreadScheduler* Scheduler() override { return &scheduler_; }
scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() const override {
if (main_thread_task_runner_for_testing_)
@@ -170,27 +168,22 @@ void Platform::Initialize(
DCHECK(!g_platform);
DCHECK(platform);
g_platform = platform;
- g_platform->owned_main_thread_ = main_thread_scheduler->CreateMainThread();
- g_platform->main_thread_ = g_platform->owned_main_thread_.get();
- DCHECK(!g_platform->current_thread_slot_.Get());
- g_platform->current_thread_slot_.Set(g_platform->main_thread_);
- InitializeCommon(platform);
+ InitializeCommon(platform, main_thread_scheduler->CreateMainThread());
}
void Platform::CreateMainThreadAndInitialize(Platform* platform) {
DCHECK(!g_platform);
DCHECK(platform);
g_platform = platform;
- g_platform->owned_main_thread_ = std::make_unique<SimpleMainThread>();
- g_platform->main_thread_ = g_platform->owned_main_thread_.get();
- DCHECK(!g_platform->current_thread_slot_.Get());
- g_platform->current_thread_slot_.Set(g_platform->main_thread_);
- InitializeCommon(platform);
+ InitializeCommon(platform, std::make_unique<SimpleMainThread>());
}
-void Platform::InitializeCommon(Platform* platform) {
+void Platform::InitializeCommon(Platform* platform,
+ std::unique_ptr<Thread> main_thread) {
WTF::Initialize(CallOnMainThreadFunction);
+ Thread::SetMainThread(std::move(main_thread));
+
ProcessHeap::Init();
MemoryCoordinator::Initialize();
if (base::ThreadTaskRunnerHandle::IsSet()) {
@@ -202,69 +195,51 @@ void Platform::InitializeCommon(Platform* platform) {
ThreadState::AttachMainThread();
- // FontFamilyNames are used by platform/fonts and are initialized by core.
+ // font_family_names are used by platform/fonts and are initialized by core.
// In case core is not available (like on PPAPI plugins), we need to init
// them here.
- FontFamilyNames::init();
+ font_family_names::Init();
InitializePlatformLanguage();
- // TODO(ssid): remove this check after fixing crbug.com/486782.
- if (g_platform->main_thread_) {
- DCHECK(!g_gc_task_runner);
- g_gc_task_runner = new GCTaskRunner(g_platform->main_thread_);
- base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
- PartitionAllocMemoryDumpProvider::Instance(), "PartitionAlloc",
- base::ThreadTaskRunnerHandle::Get());
- base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
- FontCacheMemoryDumpProvider::Instance(), "FontCaches",
- base::ThreadTaskRunnerHandle::Get());
- base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
- MemoryCacheDumpProvider::Instance(), "MemoryCache",
- base::ThreadTaskRunnerHandle::Get());
- base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
- InstanceCountersMemoryDumpProvider::Instance(), "BlinkObjectCounters",
- base::ThreadTaskRunnerHandle::Get());
- }
+ DCHECK(!g_gc_task_runner);
+ g_gc_task_runner = new GCTaskRunner(Thread::MainThread());
+ base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
+ PartitionAllocMemoryDumpProvider::Instance(), "PartitionAlloc",
+ base::ThreadTaskRunnerHandle::Get());
+ base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
+ FontCacheMemoryDumpProvider::Instance(), "FontCaches",
+ base::ThreadTaskRunnerHandle::Get());
+ base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
+ MemoryCacheDumpProvider::Instance(), "MemoryCache",
+ base::ThreadTaskRunnerHandle::Get());
+ base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
+ InstanceCountersMemoryDumpProvider::Instance(), "BlinkObjectCounters",
+ base::ThreadTaskRunnerHandle::Get());
RendererResourceCoordinator::Initialize();
}
void Platform::SetCurrentPlatformForTesting(Platform* platform) {
DCHECK(platform);
-
- // The overriding platform does not necessarily own the main thread
- // (owned_main_thread_ may be null), but must have a pointer to a valid
- // main thread object (which may be from the overridden platform).
- //
- // If the new platform's main_thread_ is null, that means we need to
- // create a new main thread for it. This happens only in
- // ScopedUnittestsEnvironmentSetup's constructor, which bypasses
- // Platform::Initialize().
- if (!platform->main_thread_) {
- platform->owned_main_thread_ = std::make_unique<SimpleMainThread>();
- platform->main_thread_ = platform->owned_main_thread_.get();
- }
-
- // Set only the main thread to TLS for the new platform. This is OK for the
- // testing purposes. The TLS slot may already be set when
- // ScopedTestingPlatformSupport tries to revert to the old platform.
- if (!platform->current_thread_slot_.Get())
- platform->current_thread_slot_.Set(platform->main_thread_);
-
g_platform = platform;
}
+void Platform::CreateMainThreadForTesting() {
+ DCHECK(!Thread::MainThread());
+ Thread::SetMainThread(std::make_unique<SimpleMainThread>());
+}
+
void Platform::SetMainThreadTaskRunnerForTesting() {
DCHECK(WTF::IsMainThread());
- DCHECK(g_platform->main_thread_->IsSimpleMainThread());
- static_cast<SimpleMainThread*>(g_platform->main_thread_)
+ DCHECK(Thread::MainThread()->IsSimpleMainThread());
+ static_cast<SimpleMainThread*>(Thread::MainThread())
->SetMainThreadTaskRunnerForTesting(base::ThreadTaskRunnerHandle::Get());
}
void Platform::UnsetMainThreadTaskRunnerForTesting() {
DCHECK(WTF::IsMainThread());
- DCHECK(g_platform->main_thread_->IsSimpleMainThread());
- static_cast<SimpleMainThread*>(g_platform->main_thread_)
+ DCHECK(Thread::MainThread()->IsSimpleMainThread());
+ static_cast<SimpleMainThread*>(Thread::MainThread())
->SetMainThreadTaskRunnerForTesting(nullptr);
}
@@ -273,11 +248,11 @@ Platform* Platform::Current() {
}
Thread* Platform::MainThread() {
- return main_thread_;
+ return Thread::MainThread();
}
Thread* Platform::CurrentThread() {
- return static_cast<Thread*>(current_thread_slot_.Get());
+ return Thread::Current();
}
service_manager::Connector* Platform::GetConnector() {
@@ -305,57 +280,19 @@ std::unique_ptr<WebStorageNamespace> Platform::CreateSessionStorageNamespace(
std::unique_ptr<Thread> Platform::CreateThread(
const ThreadCreationParams& params) {
- std::unique_ptr<scheduler::WebThreadBase> thread =
- scheduler::WebThreadBase::CreateWorkerThread(params);
- thread->Init();
- WaitUntilThreadTLSUpdate(thread.get());
- return std::move(thread);
+ return Thread::CreateThread(params);
}
std::unique_ptr<Thread> Platform::CreateWebAudioThread() {
- ThreadCreationParams params(WebThreadType::kWebAudioThread);
- // WebAudio uses a thread with |DISPLAY| priority to avoid glitch when the
- // system is under the high pressure. Note that the main browser thread also
- // runs with same priority. (see: crbug.com/734539)
- params.thread_options.priority = base::ThreadPriority::DISPLAY;
- return CreateThread(params);
-}
-
-void Platform::WaitUntilThreadTLSUpdate(Thread* thread) {
- base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
- base::WaitableEvent::InitialState::NOT_SIGNALED);
- // This cross-thread posting is guaranteed to be safe.
- PostCrossThreadTask(*thread->GetTaskRunner(), FROM_HERE,
- CrossThreadBind(&Platform::UpdateThreadTLS,
- WTF::CrossThreadUnretained(this),
- WTF::CrossThreadUnretained(thread),
- WTF::CrossThreadUnretained(&event)));
- event.Wait();
-}
-
-void Platform::UpdateThreadTLS(Thread* thread, base::WaitableEvent* event) {
- DCHECK(!current_thread_slot_.Get());
- current_thread_slot_.Set(thread);
- event->Signal();
-}
-
-void Platform::InitializeCompositorThread() {
- DCHECK(!compositor_thread_);
-
- ThreadCreationParams params(WebThreadType::kCompositorThread);
-#if defined(OS_ANDROID)
- params.thread_options.priority = base::ThreadPriority::DISPLAY;
-#endif
- std::unique_ptr<scheduler::WebThreadBase> compositor_thread =
- scheduler::WebThreadBase::CreateCompositorThread(params);
- compositor_thread->Init();
- WaitUntilThreadTLSUpdate(compositor_thread.get());
- compositor_thread_ = std::move(compositor_thread);
- SetDisplayThreadPriority(compositor_thread_->ThreadId());
+ return Thread::CreateWebAudioThread();
+}
+
+void Platform::CreateAndSetCompositorThread() {
+ Thread::CreateAndSetCompositorThread();
}
Thread* Platform::CompositorThread() {
- return compositor_thread_.get();
+ return Thread::CompositorThread();
}
scoped_refptr<base::SingleThreadTaskRunner>
@@ -391,6 +328,11 @@ Platform::CreateRTCPeerConnectionHandler(
return nullptr;
}
+std::unique_ptr<cricket::PortAllocator> Platform::CreateWebRtcPortAllocator(
+ WebLocalFrame* frame) {
+ return nullptr;
+}
+
std::unique_ptr<WebMediaRecorderHandler> Platform::CreateMediaRecorderHandler(
scoped_refptr<base::SingleThreadTaskRunner>) {
return nullptr;
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie.cc b/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie.cc
index bfd464b8c6e..048c413383a 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie.cc
@@ -84,16 +84,6 @@ WebCanonicalCookie& WebCanonicalCookie::operator=(
WebCanonicalCookie::~WebCanonicalCookie() = default;
-// static
-String WebCanonicalCookie::BuildCookieLine(
- const Vector<WebCanonicalCookie>& cookies) {
- std::vector<net::CanonicalCookie> copy;
- copy.reserve(cookies.size());
- for (const auto& cookie : cookies)
- copy.push_back(ToNetCanonicalCookie(cookie));
- return WebString::FromUTF8(net::CanonicalCookie::BuildCookieLine(copy));
-}
-
namespace {
// TODO(crbug.com/851889): WebURL::operator GURL() is only available if
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie_test.cc b/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie_test.cc
index 71d59fd8998..b2e7a5a7d5b 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie_test.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_canonical_cookie_test.cc
@@ -98,17 +98,4 @@ TEST(WebCanonicalCookieTest, Properties) {
}
}
-TEST(WebCanonicalCookieTest, BuildLine) {
- const WebURL url(KURL("http://example.com"));
- Vector<WebCanonicalCookie> cookies;
-
- cookies.push_back(
- WebCanonicalCookie::Create(url, "a=1", base::Time::Now()).value());
- EXPECT_EQ("a=1", WebCanonicalCookie::BuildCookieLine(cookies));
-
- cookies.push_back(
- WebCanonicalCookie::Create(url, "b=2", base::Time::Now()).value());
- EXPECT_EQ("a=1; b=2", WebCanonicalCookie::BuildCookieLine(cookies));
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_coalesced_input_event.cc b/chromium/third_party/blink/renderer/platform/exported/web_coalesced_input_event.cc
index 87ed9f774f8..1a4e999626b 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_coalesced_input_event.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_coalesced_input_event.cc
@@ -82,6 +82,28 @@ WebCoalescedInputEvent::GetCoalescedEventsPointers() const {
return events;
}
+void WebCoalescedInputEvent::AddPredictedEvent(
+ const blink::WebInputEvent& event) {
+ predicted_events_.push_back(MakeWebScopedInputEvent(event));
+}
+
+size_t WebCoalescedInputEvent::PredictedEventSize() const {
+ return predicted_events_.size();
+}
+
+const WebInputEvent& WebCoalescedInputEvent::PredictedEvent(
+ size_t index) const {
+ return *predicted_events_[index].get();
+}
+
+std::vector<const WebInputEvent*>
+WebCoalescedInputEvent::GetPredictedEventsPointers() const {
+ std::vector<const WebInputEvent*> events;
+ for (const auto& event : predicted_events_)
+ events.push_back(event.get());
+ return events;
+}
+
WebCoalescedInputEvent::WebCoalescedInputEvent(const WebInputEvent& event) {
event_ = MakeWebScopedInputEvent(event);
coalesced_events_.push_back(MakeWebScopedInputEvent(event));
@@ -89,24 +111,31 @@ WebCoalescedInputEvent::WebCoalescedInputEvent(const WebInputEvent& event) {
WebCoalescedInputEvent::WebCoalescedInputEvent(
const WebInputEvent& event,
- const std::vector<const WebInputEvent*>& coalesced_events) {
+ const std::vector<const WebInputEvent*>& coalesced_events,
+ const std::vector<const WebInputEvent*>& predicted_events) {
event_ = MakeWebScopedInputEvent(event);
for (auto* const coalesced_event : coalesced_events)
coalesced_events_.push_back(MakeWebScopedInputEvent(*coalesced_event));
+ for (auto* const predicted_event : predicted_events)
+ predicted_events_.push_back(MakeWebScopedInputEvent(*predicted_event));
}
WebCoalescedInputEvent::WebCoalescedInputEvent(
const WebPointerEvent& event,
- const std::vector<WebPointerEvent>& coalesced_events) {
+ const std::vector<WebPointerEvent>& coalesced_events,
+ const std::vector<WebPointerEvent>& predicted_events) {
event_ = MakeWebScopedInputEvent(event);
for (const auto& coalesced_event : coalesced_events)
coalesced_events_.push_back(MakeWebScopedInputEvent(coalesced_event));
+ for (const auto& predicted_event : predicted_events)
+ predicted_events_.push_back(MakeWebScopedInputEvent(predicted_event));
}
WebCoalescedInputEvent::WebCoalescedInputEvent(
const WebCoalescedInputEvent& event)
: WebCoalescedInputEvent(event.Event(),
- event.GetCoalescedEventsPointers()) {}
+ event.GetCoalescedEventsPointers(),
+ event.GetPredictedEventsPointers()) {}
WebCoalescedInputEvent::WebScopedInputEvent
WebCoalescedInputEvent::MakeWebScopedInputEvent(
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_cors.cc b/chromium/third_party/blink/renderer/platform/exported/web_cors.cc
deleted file mode 100644
index 91f68634c90..00000000000
--- a/chromium/third_party/blink/renderer/platform/exported/web_cors.cc
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "third_party/blink/public/platform/web_cors.h"
-
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "net/http/http_util.h"
-#include "third_party/blink/public/platform/web_security_origin.h"
-#include "third_party/blink/public/platform/web_url_response.h"
-#include "third_party/blink/renderer/platform/loader/cors/cors.h"
-#include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
-#include "third_party/blink/renderer/platform/network/http_names.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-#include "url/gurl.h"
-#include "url/url_util.h"
-
-using network::mojom::CORSError;
-
-namespace blink {
-
-namespace WebCORS {
-
-namespace {
-
-// A parser for the value of the Access-Control-Expose-Headers header.
-class HTTPHeaderNameListParser {
- STACK_ALLOCATED();
-
- public:
- explicit HTTPHeaderNameListParser(const String& value)
- : value_(value), pos_(0) {}
-
- // Tries parsing |value_| expecting it to be conforming to the #field-name
- // ABNF rule defined in RFC 7230. Returns with the field-name entries stored
- // in |output| when successful. Otherwise, returns with |output| kept empty.
- //
- // |output| must be empty.
- void Parse(WebHTTPHeaderSet& output) {
- DCHECK(output.empty());
-
- while (true) {
- ConsumeSpaces();
-
- size_t token_start = pos_;
- ConsumeTokenChars();
- size_t token_size = pos_ - token_start;
- if (token_size == 0) {
- output.clear();
- return;
- }
-
- const CString& name = value_.Substring(token_start, token_size).Ascii();
- output.emplace(name.data(), name.length());
-
- ConsumeSpaces();
-
- if (pos_ == value_.length())
- return;
-
- if (value_[pos_] == ',') {
- ++pos_;
- } else {
- output.clear();
- return;
- }
- }
- }
-
- private:
- // Consumes zero or more spaces (SP and HTAB) from value_.
- void ConsumeSpaces() {
- while (true) {
- if (pos_ == value_.length())
- return;
-
- UChar c = value_[pos_];
- if (c != ' ' && c != '\t')
- return;
- ++pos_;
- }
- }
-
- // Consumes zero or more tchars from value_.
- void ConsumeTokenChars() {
- while (true) {
- if (pos_ == value_.length())
- return;
-
- UChar c = value_[pos_];
- if (c > 0x7F || !net::HttpUtil::IsTokenChar(c))
- return;
- ++pos_;
- }
- }
-
- const String value_;
- size_t pos_;
-};
-
-} // namespace
-
-WebHTTPHeaderSet ExtractCorsExposedHeaderNamesList(
- network::mojom::FetchCredentialsMode credentials_mode,
- const WebURLResponse& response) {
- // If a response was fetched via a service worker, it will always have
- // CorsExposedHeaderNames set from the Access-Control-Expose-Headers header.
- // For requests that didn't come from a service worker, just parse the CORS
- // header.
- if (response.WasFetchedViaServiceWorker()) {
- WebHTTPHeaderSet header_set;
- for (const auto& header : response.CorsExposedHeaderNames())
- header_set.emplace(header.Ascii().data(), header.Ascii().length());
- return header_set;
- }
-
- WebHTTPHeaderSet header_set;
- HTTPHeaderNameListParser parser(response.HttpHeaderField(
- WebString(HTTPNames::Access_Control_Expose_Headers)));
- parser.Parse(header_set);
-
- if (credentials_mode != network::mojom::FetchCredentialsMode::kInclude &&
- header_set.find("*") != header_set.end()) {
- header_set.clear();
- for (const auto& header :
- response.ToResourceResponse().HttpHeaderFields()) {
- CString name = header.key.Ascii();
- header_set.emplace(name.data(), name.length());
- }
- }
- return header_set;
-}
-
-bool IsOnAccessControlResponseHeaderWhitelist(const WebString& name) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- WebHTTPHeaderSet, allowed_cross_origin_response_headers,
- ({
- "cache-control", "content-language", "content-type", "expires",
- "last-modified", "pragma",
- }));
- return allowed_cross_origin_response_headers.find(name.Ascii().data()) !=
- allowed_cross_origin_response_headers.end();
-}
-
-// In the spec, https://fetch.spec.whatwg.org/#ref-for-concept-request-mode,
-// No-CORS mode is highly discouraged from using it for new features. Only
-// legacy usages for backward compatibility are allowed except for well-designed
-// usages over the fetch API.
-bool IsNoCORSAllowedContext(mojom::RequestContextType context) {
- switch (context) {
- case mojom::RequestContextType::AUDIO:
- case mojom::RequestContextType::FAVICON:
- case mojom::RequestContextType::FETCH:
- case mojom::RequestContextType::IMAGE:
- case mojom::RequestContextType::OBJECT:
- case mojom::RequestContextType::PLUGIN:
- case mojom::RequestContextType::SCRIPT:
- case mojom::RequestContextType::SHARED_WORKER:
- case mojom::RequestContextType::VIDEO:
- case mojom::RequestContextType::WORKER:
- return true;
- default:
- return false;
- }
-}
-
-} // namespace WebCORS
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_media_constraints.cc b/chromium/third_party/blink/renderer/platform/exported/web_media_constraints.cc
index a97a407a7ff..c6715848beb 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_media_constraints.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_media_constraints.cc
@@ -161,6 +161,10 @@ BaseConstraint::BaseConstraint(const char* name) : name_(name) {}
BaseConstraint::~BaseConstraint() = default;
+bool BaseConstraint::HasMandatory() const {
+ return HasMin() || HasMax() || HasExact();
+}
+
LongConstraint::LongConstraint(const char* name)
: BaseConstraint(name),
min_(),
@@ -189,10 +193,6 @@ bool LongConstraint::IsEmpty() const {
return !has_min_ && !has_max_ && !has_exact_ && !has_ideal_;
}
-bool LongConstraint::HasMandatory() const {
- return has_min_ || has_max_ || has_exact_;
-}
-
WebString LongConstraint::ToString() const {
StringBuilder builder;
builder.Append('{');
@@ -235,10 +235,6 @@ bool DoubleConstraint::IsEmpty() const {
return !has_min_ && !has_max_ && !has_exact_ && !has_ideal_;
}
-bool DoubleConstraint::HasMandatory() const {
- return has_min_ || has_max_ || has_exact_;
-}
-
WebString DoubleConstraint::ToString() const {
StringBuilder builder;
builder.Append('{');
@@ -269,10 +265,6 @@ bool StringConstraint::IsEmpty() const {
return exact_.empty() && ideal_.empty();
}
-bool StringConstraint::HasMandatory() const {
- return !exact_.empty();
-}
-
const WebVector<WebString>& StringConstraint::Exact() const {
return exact_;
}
@@ -333,10 +325,6 @@ bool BooleanConstraint::IsEmpty() const {
return !has_ideal_ && !has_exact_;
}
-bool BooleanConstraint::HasMandatory() const {
- return has_exact_;
-}
-
WebString BooleanConstraint::ToString() const {
StringBuilder builder;
builder.Append('{');
@@ -352,6 +340,7 @@ WebMediaTrackConstraintSet::WebMediaTrackConstraintSet()
aspect_ratio("aspectRatio"),
frame_rate("frameRate"),
facing_mode("facingMode"),
+ resize_mode("resizeMode"),
volume("volume"),
sample_rate("sampleRate"),
sample_size("sampleSize"),
@@ -413,6 +402,7 @@ std::vector<const BaseConstraint*> WebMediaTrackConstraintSet::AllConstraints()
&aspect_ratio,
&frame_rate,
&facing_mode,
+ &resize_mode,
&volume,
&sample_rate,
&sample_size,
@@ -496,6 +486,22 @@ bool WebMediaTrackConstraintSet::HasMandatory() const {
return HasMandatoryOutsideSet(std::vector<std::string>(), dummy_string);
}
+bool WebMediaTrackConstraintSet::HasMin() const {
+ for (auto* const constraint : AllConstraints()) {
+ if (constraint->HasMin())
+ return true;
+ }
+ return false;
+}
+
+bool WebMediaTrackConstraintSet::HasExact() const {
+ for (auto* const constraint : AllConstraints()) {
+ if (constraint->HasExact())
+ return true;
+ }
+ return false;
+}
+
WebString WebMediaTrackConstraintSet::ToString() const {
StringBuilder builder;
bool first = true;
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_media_stream_track.cc b/chromium/third_party/blink/renderer/platform/exported/web_media_stream_track.cc
index 8b78c45649f..2e760bc6b2c 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_media_stream_track.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_media_stream_track.cc
@@ -57,6 +57,9 @@ class TrackDataContainer : public MediaStreamComponent::TrackData {
} // namespace
+const char WebMediaStreamTrack::kResizeModeNone[] = "none";
+const char WebMediaStreamTrack::kResizeModeRescale[] = "crop-and-scale";
+
WebMediaStreamTrack::WebMediaStreamTrack(
MediaStreamComponent* media_stream_component)
: private_(media_stream_component) {}
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_prerender.cc b/chromium/third_party/blink/renderer/platform/exported/web_prerender.cc
index 6e123924e8d..fbe19674b70 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_prerender.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_prerender.cc
@@ -90,8 +90,8 @@ WebString WebPrerender::GetReferrer() const {
return private_->GetReferrer();
}
-WebReferrerPolicy WebPrerender::GetReferrerPolicy() const {
- return static_cast<WebReferrerPolicy>(private_->GetReferrerPolicy());
+network::mojom::ReferrerPolicy WebPrerender::GetReferrerPolicy() const {
+ return private_->GetReferrerPolicy();
}
void WebPrerender::SetExtraData(WebPrerender::ExtraData* extra_data) {
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/chromium/third_party/blink/renderer/platform/exported/web_runtime_features.cc
index 26310e81903..36c10eaccf7 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_runtime_features.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -39,6 +39,10 @@ void WebRuntimeFeatures::EnableBlinkHeapIncrementalMarking(bool enable) {
RuntimeEnabledFeatures::SetHeapIncrementalMarkingEnabled(enable);
}
+void WebRuntimeFeatures::EnableBlinkHeapUnifiedGarbageCollection(bool enable) {
+ RuntimeEnabledFeatures::SetHeapUnifiedGarbageCollectionEnabled(enable);
+}
+
void WebRuntimeFeatures::EnableBloatedRendererDetection(bool enable) {
RuntimeEnabledFeatures::SetBloatedRendererDetectionEnabled(enable);
}
@@ -64,6 +68,14 @@ void WebRuntimeFeatures::EnableFeatureFromString(const std::string& name,
RuntimeEnabledFeatures::SetFeatureEnabledFromString(name, enable);
}
+bool WebRuntimeFeatures::IsBlinkGenPropertyTreesEnabled() {
+ return RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled();
+}
+
+bool WebRuntimeFeatures::IsFractionalScrollOffsetsEnabled() {
+ return RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled();
+}
+
void WebRuntimeFeatures::EnableTestOnlyFeatures(bool enable) {
RuntimeEnabledFeatures::SetTestFeaturesEnabled(enable);
}
@@ -72,8 +84,8 @@ void WebRuntimeFeatures::EnableOriginTrialControlledFeatures(bool enable) {
RuntimeEnabledFeatures::SetOriginTrialControlledFeaturesEnabled(enable);
}
-void WebRuntimeFeatures::EnableOutOfBlinkCORS(bool enable) {
- RuntimeEnabledFeatures::SetOutOfBlinkCORSEnabled(enable);
+void WebRuntimeFeatures::EnableOutOfBlinkCors(bool enable) {
+ RuntimeEnabledFeatures::SetOutOfBlinkCorsEnabled(enable);
}
void WebRuntimeFeatures::EnableAccelerated2dCanvas(bool enable) {
@@ -104,6 +116,10 @@ void WebRuntimeFeatures::EnableIsolatedCodeCache(bool enable) {
RuntimeEnabledFeatures::SetIsolatedCodeCacheEnabled(enable);
}
+void WebRuntimeFeatures::EnableWasmCodeCache(bool enable) {
+ RuntimeEnabledFeatures::SetWasmCodeCacheEnabled(enable);
+}
+
void WebRuntimeFeatures::EnableCanvas2dImageChromium(bool enable) {
RuntimeEnabledFeatures::SetCanvas2dImageChromiumEnabled(enable);
}
@@ -148,6 +164,10 @@ void WebRuntimeFeatures::EnableFileSystem(bool enable) {
RuntimeEnabledFeatures::SetFileSystemEnabled(enable);
}
+void WebRuntimeFeatures::EnableFirstContentfulPaintPlusPlus(bool enable) {
+ RuntimeEnabledFeatures::SetFirstContentfulPaintPlusPlusEnabled(enable);
+}
+
void WebRuntimeFeatures::EnableForceTallerSelectPopup(bool enable) {
RuntimeEnabledFeatures::SetForceTallerSelectPopupEnabled(enable);
}
@@ -172,6 +192,10 @@ void WebRuntimeFeatures::EnableHeapCompaction(bool enable) {
RuntimeEnabledFeatures::SetHeapCompactionEnabled(enable);
}
+void WebRuntimeFeatures::EnableImplicitRootScroller(bool enable) {
+ RuntimeEnabledFeatures::SetImplicitRootScrollerEnabled(enable);
+}
+
void WebRuntimeFeatures::EnableInputMultipleFieldsUI(bool enable) {
RuntimeEnabledFeatures::SetInputMultipleFieldsUIEnabled(enable);
}
@@ -240,10 +264,6 @@ void WebRuntimeFeatures::EnableNavigatorContentUtils(bool enable) {
RuntimeEnabledFeatures::SetNavigatorContentUtilsEnabled(enable);
}
-void WebRuntimeFeatures::EnableNestedWorkers(bool enable) {
- RuntimeEnabledFeatures::SetNestedWorkersEnabled(enable);
-}
-
void WebRuntimeFeatures::EnableNetInfoDownlinkMax(bool enable) {
RuntimeEnabledFeatures::SetNetInfoDownlinkMaxEnabled(enable);
}
@@ -316,10 +336,6 @@ void WebRuntimeFeatures::EnablePortals(bool enable) {
RuntimeEnabledFeatures::SetPortalsEnabled(enable);
}
-void WebRuntimeFeatures::EnablePreloadDefaultIsMetadata(bool enable) {
- RuntimeEnabledFeatures::SetPreloadDefaultIsMetadataEnabled(enable);
-}
-
void WebRuntimeFeatures::EnablePreloadImageSrcSetEnabled(bool enable) {
RuntimeEnabledFeatures::SetPreloadImageSrcSetEnabled(enable);
}
@@ -328,12 +344,20 @@ void WebRuntimeFeatures::EnableRasterInducingScroll(bool enable) {
RuntimeEnabledFeatures::SetRasterInducingScrollEnabled(enable);
}
-void WebRuntimeFeatures::EnableScriptedSpeech(bool enable) {
- RuntimeEnabledFeatures::SetScriptedSpeechEnabled(enable);
+void WebRuntimeFeatures::EnableScriptedSpeechRecognition(bool enable) {
+ RuntimeEnabledFeatures::SetScriptedSpeechRecognitionEnabled(enable);
+}
+
+void WebRuntimeFeatures::EnableScriptedSpeechSynthesis(bool enable) {
+ RuntimeEnabledFeatures::SetScriptedSpeechSynthesisEnabled(enable);
+}
+
+bool WebRuntimeFeatures::IsSlimmingPaintV2Enabled() {
+ return RuntimeEnabledFeatures::SlimmingPaintV2Enabled();
}
-void WebRuntimeFeatures::EnableSlimmingPaintV2(bool enable) {
- RuntimeEnabledFeatures::SetSlimmingPaintV2Enabled(enable);
+void WebRuntimeFeatures::EnableUserActivationSameOriginVisibility(bool enable) {
+ RuntimeEnabledFeatures::SetUserActivationSameOriginVisibilityEnabled(enable);
}
void WebRuntimeFeatures::EnableUserActivationV2(bool enable) {
@@ -432,14 +456,20 @@ void WebRuntimeFeatures::EnableRenderingPipelineThrottling(bool enable) {
RuntimeEnabledFeatures::SetRenderingPipelineThrottlingEnabled(enable);
}
-void WebRuntimeFeatures::EnableRequireCSSExtensionForFile(bool enable) {
- RuntimeEnabledFeatures::SetRequireCSSExtensionForFileEnabled(enable);
-}
-
void WebRuntimeFeatures::EnableResourceLoadScheduler(bool enable) {
RuntimeEnabledFeatures::SetResourceLoadSchedulerEnabled(enable);
}
+void WebRuntimeFeatures::EnableRestrictLazyFrameLoadingToDataSaver(
+ bool enable) {
+ RuntimeEnabledFeatures::SetRestrictLazyFrameLoadingToDataSaverEnabled(enable);
+}
+
+void WebRuntimeFeatures::EnableRestrictLazyImageLoadingToDataSaver(
+ bool enable) {
+ RuntimeEnabledFeatures::SetRestrictLazyImageLoadingToDataSaverEnabled(enable);
+}
+
void WebRuntimeFeatures::EnableExpensiveBackgroundTimerThrottling(bool enable) {
RuntimeEnabledFeatures::SetExpensiveBackgroundTimerThrottlingEnabled(enable);
}
@@ -452,10 +482,6 @@ void WebRuntimeFeatures::EnableSecMetadata(bool enable) {
RuntimeEnabledFeatures::SetSecMetadataEnabled(enable);
}
-void WebRuntimeFeatures::EnableServiceWorkerScriptFullCodeCache(bool enable) {
- RuntimeEnabledFeatures::SetServiceWorkerScriptFullCodeCacheEnabled(enable);
-}
-
void WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(bool enable) {
RuntimeEnabledFeatures::SetTimerThrottlingForBackgroundTabsEnabled(enable);
}
@@ -544,12 +570,8 @@ void WebRuntimeFeatures::EnableScheduledScriptStreaming(bool enable) {
RuntimeEnabledFeatures::SetScheduledScriptStreamingEnabled(enable);
}
-void WebRuntimeFeatures::EnablePWAFullCodeCache(bool enable) {
- RuntimeEnabledFeatures::SetPWAFullCodeCacheEnabled(enable);
-}
-
-void WebRuntimeFeatures::EnableOffMainThreadWebSocket(bool enable) {
- RuntimeEnabledFeatures::SetOffMainThreadWebSocketEnabled(enable);
+void WebRuntimeFeatures::EnableScriptStreamingOnPreload(bool enable) {
+ RuntimeEnabledFeatures::SetScriptStreamingOnPreloadEnabled(enable);
}
void WebRuntimeFeatures::EnableExperimentalProductivityFeatures(bool enable) {
@@ -568,12 +590,28 @@ void WebRuntimeFeatures::EnableMediaControlsExpandGesture(bool enable) {
RuntimeEnabledFeatures::SetMediaControlsExpandGestureEnabled(enable);
}
-void WebRuntimeFeatures::EnableHrefTranslate(bool enable) {
- RuntimeEnabledFeatures::SetHrefTranslateEnabled(enable);
+void WebRuntimeFeatures::EnableTranslateService(bool enable) {
+ RuntimeEnabledFeatures::SetTranslateServiceEnabled(enable);
}
void WebRuntimeFeatures::EnableBackgroundFetch(bool enable) {
RuntimeEnabledFeatures::SetBackgroundFetchEnabled(enable);
}
+void WebRuntimeFeatures::EnableBackgroundFetchAccessActiveFetches(bool enable) {
+ RuntimeEnabledFeatures::SetBackgroundFetchAccessActiveFetchesEnabled(enable);
+}
+
+void WebRuntimeFeatures::EnableBackgroundFetchUploads(bool enable) {
+ RuntimeEnabledFeatures::SetBackgroundFetchUploadsEnabled(enable);
+}
+
+void WebRuntimeFeatures::EnableMergeBlockingNonBlockingPools(bool enable) {
+ RuntimeEnabledFeatures::SetMergeBlockingNonBlockingPoolsEnabled(enable);
+}
+
+void WebRuntimeFeatures::EnableGetDisplayMedia(bool enable) {
+ RuntimeEnabledFeatures::SetGetDisplayMediaEnabled(enable);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_service_worker_request.cc b/chromium/third_party/blink/renderer/platform/exported/web_service_worker_request.cc
index f71aa41f648..1a4b4ae2fbe 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_service_worker_request.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_service_worker_request.cc
@@ -26,7 +26,7 @@ class WebServiceWorkerRequestPrivate
scoped_refptr<BlobDataHandle> blob_data_handle;
Referrer referrer_;
network::mojom::FetchRequestMode mode_ =
- network::mojom::FetchRequestMode::kNoCORS;
+ network::mojom::FetchRequestMode::kNoCors;
bool is_main_resource_load_ = false;
network::mojom::FetchCredentialsMode credentials_mode_ =
network::mojom::FetchCredentialsMode::kOmit;
@@ -147,23 +147,24 @@ scoped_refptr<BlobDataHandle> WebServiceWorkerRequest::GetBlobDataHandle()
return private_->blob_data_handle;
}
-void WebServiceWorkerRequest::SetReferrer(const WebString& web_referrer,
- WebReferrerPolicy referrer_policy) {
+void WebServiceWorkerRequest::SetReferrer(
+ const WebString& web_referrer,
+ network::mojom::ReferrerPolicy referrer_policy) {
// WebString doesn't have the distinction between empty and null. We use
// the null WTFString for referrer.
DCHECK_EQ(Referrer::NoReferrer(), String());
String referrer =
web_referrer.IsEmpty() ? Referrer::NoReferrer() : String(web_referrer);
- private_->referrer_ =
- Referrer(referrer, static_cast<ReferrerPolicy>(referrer_policy));
+ private_->referrer_ = Referrer(referrer, referrer_policy);
}
WebURL WebServiceWorkerRequest::ReferrerUrl() const {
return KURL(private_->referrer_.referrer);
}
-WebReferrerPolicy WebServiceWorkerRequest::GetReferrerPolicy() const {
- return static_cast<WebReferrerPolicy>(private_->referrer_.referrer_policy);
+network::mojom::ReferrerPolicy WebServiceWorkerRequest::GetReferrerPolicy()
+ const {
+ return private_->referrer_.referrer_policy;
}
const Referrer& WebServiceWorkerRequest::GetReferrer() const {
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_string.cc b/chromium/third_party/blink/renderer/platform/exported/web_string.cc
index cddf917e560..52b5189f6bd 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_string.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_string.cc
@@ -139,7 +139,7 @@ std::string WebString::Ascii() const {
}
bool WebString::ContainsOnlyASCII() const {
- return String(impl_).ContainsOnlyASCII();
+ return String(impl_).ContainsOnlyASCIIOrEmpty();
}
WebString WebString::FromASCII(const std::string& s) {
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_url_error.cc b/chromium/third_party/blink/renderer/platform/exported/web_url_error.cc
index 488a6e356fb..9bc40c70762 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_url_error.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_url_error.cc
@@ -27,7 +27,7 @@ WebURLError::WebURLError(int reason,
DCHECK_NE(reason_, 0);
}
-WebURLError::WebURLError(const network::CORSErrorStatus& cors_error_status,
+WebURLError::WebURLError(const network::CorsErrorStatus& cors_error_status,
HasCopyInCache has_copy_in_cache,
const WebURL& url)
: reason_(net::ERR_FAILED),
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_url_request.cc b/chromium/third_party/blink/renderer/platform/exported/web_url_request.cc
index bd90972c588..c387c5d9492 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_url_request.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_url_request.cc
@@ -148,8 +148,9 @@ void WebURLRequest::SetHTTPHeaderField(const WebString& name,
resource_request_->SetHTTPHeaderField(name, value);
}
-void WebURLRequest::SetHTTPReferrer(const WebString& web_referrer,
- WebReferrerPolicy referrer_policy) {
+void WebURLRequest::SetHTTPReferrer(
+ const WebString& web_referrer,
+ network::mojom::ReferrerPolicy referrer_policy) {
// WebString doesn't have the distinction between empty and null. We use
// the null WTFString for referrer.
DCHECK_EQ(Referrer::NoReferrer(), String());
@@ -157,8 +158,7 @@ void WebURLRequest::SetHTTPReferrer(const WebString& web_referrer,
web_referrer.IsEmpty() ? Referrer::NoReferrer() : String(web_referrer);
// TODO(domfarolino): Stop storing ResourceRequest's generated referrer as a
// header and instead use a separate member. See https://crbug.com/850813.
- resource_request_->SetHTTPReferrer(
- Referrer(referrer, static_cast<ReferrerPolicy>(referrer_policy)));
+ resource_request_->SetHTTPReferrer(Referrer(referrer, referrer_policy));
}
void WebURLRequest::AddHTTPHeaderField(const WebString& name,
@@ -208,8 +208,8 @@ network::mojom::RequestContextFrameType WebURLRequest::GetFrameType() const {
return resource_request_->GetFrameType();
}
-WebReferrerPolicy WebURLRequest::GetReferrerPolicy() const {
- return static_cast<WebReferrerPolicy>(resource_request_->GetReferrerPolicy());
+network::mojom::ReferrerPolicy WebURLRequest::GetReferrerPolicy() const {
+ return resource_request_->GetReferrerPolicy();
}
void WebURLRequest::SetHTTPOriginIfNeeded(const WebSecurityOrigin& origin) {
@@ -346,6 +346,14 @@ void WebURLRequest::SetExtraData(std::unique_ptr<ExtraData> extra_data) {
resource_request_->SetExtraData(std::move(extra_data));
}
+bool WebURLRequest::IsDownloadToNetworkCacheOnly() const {
+ return resource_request_->IsDownloadToNetworkCacheOnly();
+}
+
+void WebURLRequest::SetDownloadToNetworkCacheOnly(bool download_to_cache_only) {
+ resource_request_->SetDownloadToNetworkCacheOnly(download_to_cache_only);
+}
+
ResourceRequest& WebURLRequest::ToMutableResourceRequest() {
DCHECK(resource_request_);
return *resource_request_;
@@ -370,9 +378,9 @@ bool WebURLRequest::IsExternalRequest() const {
return resource_request_->IsExternalRequest();
}
-network::mojom::CORSPreflightPolicy WebURLRequest::GetCORSPreflightPolicy()
+network::mojom::CorsPreflightPolicy WebURLRequest::GetCorsPreflightPolicy()
const {
- return resource_request_->CORSPreflightPolicy();
+ return resource_request_->CorsPreflightPolicy();
}
void WebURLRequest::SetNavigationStartTime(
@@ -424,12 +432,20 @@ void WebURLRequest::SetOriginPolicy(const WebString& policy) {
resource_request_->SetOriginPolicy(policy);
}
-const WebString WebURLRequest::GetRequestedWith() const {
- return resource_request_->GetRequestedWith();
+const WebString WebURLRequest::GetRequestedWithHeader() const {
+ return resource_request_->GetRequestedWithHeader();
+}
+
+void WebURLRequest::SetRequestedWithHeader(const WebString& value) {
+ resource_request_->SetRequestedWithHeader(value);
+}
+
+const WebString WebURLRequest::GetClientDataHeader() const {
+ return resource_request_->GetClientDataHeader();
}
-void WebURLRequest::SetRequestedWith(const WebString& value) {
- resource_request_->SetRequestedWith(value);
+void WebURLRequest::SetClientDataHeader(const WebString& value) {
+ resource_request_->SetClientDataHeader(value);
}
const base::UnguessableToken& WebURLRequest::GetFetchWindowId() const {
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_url_response.cc b/chromium/third_party/blink/renderer/platform/exported/web_url_response.cc
index 6b1d6b1c00a..3dc90c58557 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_url_response.cc
+++ b/chromium/third_party/blink/renderer/platform/exported/web_url_response.cc
@@ -261,6 +261,10 @@ void WebURLResponse::SetIsLegacySymantecCert(bool value) {
resource_response_->SetIsLegacySymantecCert(value);
}
+void WebURLResponse::SetIsLegacyTLSVersion(bool value) {
+ resource_response_->SetIsLegacyTLSVersion(value);
+}
+
void WebURLResponse::SetSecurityStyle(WebSecurityStyle security_style) {
resource_response_->SetSecurityStyle(
static_cast<ResourceResponse::SecurityStyle>(security_style));
@@ -447,6 +451,10 @@ void WebURLResponse::SetAsyncRevalidationRequested(bool requested) {
resource_response_->SetAsyncRevalidationRequested(requested);
}
+void WebURLResponse::SetNetworkAccessed(bool network_accessed) {
+ resource_response_->SetNetworkAccessed(network_accessed);
+}
+
WebURLResponse::WebURLResponse(ResourceResponse& r) : resource_response_(&r) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/DEPS b/chromium/third_party/blink/renderer/platform/fonts/DEPS
index 971791ef45b..d859ec63d6e 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/DEPS
+++ b/chromium/third_party/blink/renderer/platform/fonts/DEPS
@@ -13,8 +13,6 @@ include_rules = [
"+third_party/blink/renderer/platform/histogram.h",
"+third_party/blink/renderer/platform/instrumentation",
"+third_party/blink/renderer/platform/language.h",
- "+third_party/blink/renderer/platform/layout_test_support.h",
- "+third_party/blink/renderer/platform/layout_unit.h",
"+third_party/blink/renderer/platform/mac/version_util_mac.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/resolution_units.h",
@@ -23,5 +21,6 @@ include_rules = [
"+third_party/blink/renderer/platform/shared_buffer.h",
"+third_party/blink/renderer/platform/testing",
"+third_party/blink/renderer/platform/text",
+ "+third_party/blink/renderer/platform/web_test_support.h",
"+third_party/blink/renderer/platform/wtf",
]
diff --git a/chromium/third_party/blink/renderer/platform/fonts/alternate_font_family.h b/chromium/third_party/blink/renderer/platform/fonts/alternate_font_family.h
index 62ae63d6b66..2382615a524 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/alternate_font_family.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/alternate_font_family.h
@@ -48,20 +48,20 @@ inline const AtomicString& AdjustFamilyNameToAvoidUnsupportedFonts(
// 'Courier' is a bitmap font. On Mac on the other hand 'Courier' is
// a truetype font. Thus pages asking for Courier are better of
// using 'Courier New' on windows.
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Courier))
- return FontFamilyNames::Courier_New;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kCourier))
+ return font_family_names::kCourierNew;
// Alias 'MS Sans Serif' (bitmap font) -> 'Microsoft Sans Serif'
// (truetype font).
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::MS_Sans_Serif))
- return FontFamilyNames::Microsoft_Sans_Serif;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kMSSansSerif))
+ return font_family_names::kMicrosoftSansSerif;
// Alias 'MS Serif' (bitmap) -> 'Times New Roman' (truetype font).
// Alias 'Times' -> 'Times New Roman' (truetype font).
// There's no 'Microsoft Sans Serif-equivalent' for Serif.
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::MS_Serif) ||
- EqualIgnoringASCIICase(family_name, FontFamilyNames::Times))
- return FontFamilyNames::Times_New_Roman;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kMSSerif) ||
+ EqualIgnoringASCIICase(family_name, font_family_names::kTimes))
+ return font_family_names::kTimesNewRoman;
#endif
return family_name;
@@ -70,27 +70,27 @@ inline const AtomicString& AdjustFamilyNameToAvoidUnsupportedFonts(
inline const AtomicString& AlternateFamilyName(
const AtomicString& family_name) {
// Alias Courier <-> Courier New
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Courier))
- return FontFamilyNames::Courier_New;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kCourier))
+ return font_family_names::kCourierNew;
#if !defined(OS_WIN)
// On Windows, Courier New (truetype font) is always present and
// Courier is a bitmap font. So, we don't want to map Courier New to
// Courier.
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Courier_New))
- return FontFamilyNames::Courier;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kCourierNew))
+ return font_family_names::kCourier;
#endif
// Alias Times and Times New Roman.
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Times))
- return FontFamilyNames::Times_New_Roman;
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Times_New_Roman))
- return FontFamilyNames::Times;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kTimes))
+ return font_family_names::kTimesNewRoman;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kTimesNewRoman))
+ return font_family_names::kTimes;
// Alias Arial and Helvetica
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Arial))
- return FontFamilyNames::Helvetica;
- if (EqualIgnoringASCIICase(family_name, FontFamilyNames::Helvetica))
- return FontFamilyNames::Arial;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kArial))
+ return font_family_names::kHelvetica;
+ if (EqualIgnoringASCIICase(family_name, font_family_names::kHelvetica))
+ return font_family_names::kArial;
return g_empty_atom;
}
@@ -99,15 +99,15 @@ inline const AtomicString& GetFallbackFontFamily(
const FontDescription& description) {
switch (description.GenericFamily()) {
case FontDescription::kSansSerifFamily:
- return FontFamilyNames::sans_serif;
+ return font_family_names::kSansSerif;
case FontDescription::kSerifFamily:
- return FontFamilyNames::serif;
+ return font_family_names::kSerif;
case FontDescription::kMonospaceFamily:
- return FontFamilyNames::monospace;
+ return font_family_names::kMonospace;
case FontDescription::kCursiveFamily:
- return FontFamilyNames::cursive;
+ return font_family_names::kCursive;
case FontDescription::kFantasyFamily:
- return FontFamilyNames::fantasy;
+ return font_family_names::kFantasy;
default:
// Let the caller use the system default font.
return g_empty_atom;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android.cc b/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android.cc
index 6c8efc827f5..99aec1d670c 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android.cc
@@ -56,7 +56,7 @@ static AtomicString DefaultFontFamily(sk_sp<SkFontMgr> font_manager) {
// do here, use "Arial", the value LayoutTheme uses for CSS system font
// keywords such as "menu".
NOTREACHED();
- return FontFamilyNames::Arial;
+ return font_family_names::kArial;
}
static AtomicString DefaultFontFamily() {
@@ -99,7 +99,7 @@ AtomicString FontCache::GetGenericFamilyNameForScript(
// i18n fonts are likely not monospace. Monospace is mostly used
// for code, but when i18n characters appear in monospace, system
// fallback can still render the characters.
- if (family_name == FontFamilyNames::webkit_monospace)
+ if (family_name == font_family_names::kWebkitMonospace)
return family_name;
// The CJK hack below should be removed, at latest when we have
diff --git a/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android_test.cc b/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android_test.cc
index efe8ddc64ef..5f03b588f82 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android_test.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/android/font_cache_android_test.cc
@@ -39,26 +39,25 @@ TEST(FontCacheAndroid, genericFamilyNameForScript) {
FontDescription chinese;
chinese.SetLocale(LayoutLocale::Get("zh"));
- if (FontFamilyNames::webkit_standard.IsEmpty())
- FontFamilyNames::init();
+ font_family_names::Init();
// For non-CJK, getGenericFamilyNameForScript should return the given
// familyName.
- EXPECT_EQ(FontFamilyNames::webkit_standard,
+ EXPECT_EQ(font_family_names::kWebkitStandard,
FontCache::GetGenericFamilyNameForScript(
- FontFamilyNames::webkit_standard, english));
- EXPECT_EQ(FontFamilyNames::webkit_monospace,
+ font_family_names::kWebkitStandard, english));
+ EXPECT_EQ(font_family_names::kWebkitMonospace,
FontCache::GetGenericFamilyNameForScript(
- FontFamilyNames::webkit_monospace, english));
+ font_family_names::kWebkitMonospace, english));
// For CJK, getGenericFamilyNameForScript should return CJK fonts except
// monospace.
- EXPECT_NE(FontFamilyNames::webkit_standard,
+ EXPECT_NE(font_family_names::kWebkitStandard,
FontCache::GetGenericFamilyNameForScript(
- FontFamilyNames::webkit_standard, chinese));
- EXPECT_EQ(FontFamilyNames::webkit_monospace,
+ font_family_names::kWebkitStandard, chinese));
+ EXPECT_EQ(font_family_names::kWebkitMonospace,
FontCache::GetGenericFamilyNameForScript(
- FontFamilyNames::webkit_monospace, chinese));
+ font_family_names::kWebkitMonospace, chinese));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font.cc b/chromium/third_party/blink/renderer/platform/fonts/font.cc
index def231a9a7a..ef63a49a1f5 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/font.cc
@@ -31,13 +31,12 @@
#include "third_party/blink/renderer/platform/fonts/font_fallback_iterator.h"
#include "third_party/blink/renderer/platform/fonts/font_fallback_list.h"
#include "third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h"
-#include "third_party/blink/renderer/platform/fonts/paint_text_blob.h"
#include "third_party/blink/renderer/platform/fonts/shaping/caching_word_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
#include "third_party/blink/renderer/platform/fonts/text_run_paint_info.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/text/bidi_resolver.h"
#include "third_party/blink/renderer/platform/text/character.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
@@ -291,9 +290,8 @@ unsigned InterceptsFromBlobs(const ShapeResultBloberizer::BlobBuffer& blobs,
SkScalar* offset_intercepts_buffer = nullptr;
if (intercepts_buffer)
offset_intercepts_buffer = &intercepts_buffer[num_intervals];
- num_intervals +=
- paint.getTextBlobIntercepts(blob_info.blob->ToSkTextBlob().get(),
- bounds_array, offset_intercepts_buffer);
+ num_intervals += paint.getTextBlobIntercepts(
+ blob_info.blob.get(), bounds_array, offset_intercepts_buffer);
}
return num_intervals;
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font.h b/chromium/third_party/blink/renderer/platform/fonts/font.h
index 559bd97f1d3..313afb7a155 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/font.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/platform/fonts/font_fallback_list.h"
#include "third_party/blink/renderer/platform/fonts/font_fallback_priority.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/text/tab_size.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_cache.cc b/chromium/third_party/blink/renderer/platform/fonts/font_cache.cc
index ac44cca505d..b72da9f7015 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_cache.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_cache.cc
@@ -89,10 +89,10 @@ FontPlatformData* FontCache::SystemFontPlatformData(
const FontDescription& font_description) {
const AtomicString& family = FontCache::SystemFontFamily();
#if defined(OS_LINUX)
- if (family.IsEmpty() || family == FontFamilyNames::system_ui)
+ if (family.IsEmpty() || family == font_family_names::kSystemUi)
return nullptr;
#else
- DCHECK(!family.IsEmpty() && family != FontFamilyNames::system_ui);
+ DCHECK(!family.IsEmpty() && family != font_family_names::kSystemUi);
#endif
return GetFontPlatformData(font_description, FontFaceCreationParams(family),
AlternateFontName::kNoAlternate);
@@ -110,7 +110,7 @@ FontPlatformData* FontCache::GetFontPlatformData(
#if !defined(OS_MACOSX)
if (creation_params.CreationType() == kCreateFontByFamily &&
- creation_params.Family() == FontFamilyNames::system_ui) {
+ creation_params.Family() == font_family_names::kSystemUi) {
return SystemFontPlatformData(font_description);
}
#endif
@@ -355,7 +355,8 @@ void FontCache::Purge(PurgeSeverity purge_severity) {
void FontCache::AddClient(FontCacheClient* client) {
CHECK(client);
if (!font_cache_clients_) {
- font_cache_clients_ = new HeapHashSet<WeakMember<FontCacheClient>>();
+ font_cache_clients_ =
+ MakeGarbageCollected<HeapHashSet<WeakMember<FontCacheClient>>>();
font_cache_clients_.RegisterAsStaticReference();
}
DCHECK(!font_cache_clients_->Contains(client));
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_description.h b/chromium/third_party/blink/renderer/platform/fonts/font_description.h
index 15a999cb190..925923d8ff1 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_description.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_description.h
@@ -179,7 +179,7 @@ class PLATFORM_EXPORT FontDescription {
// family is "monospace"
bool IsMonospace() const {
return GenericFamily() == kMonospaceFamily && !Family().Next() &&
- Family().Family() == FontFamilyNames::webkit_monospace;
+ Family().Family() == font_family_names::kWebkitMonospace;
}
Kerning GetKerning() const { return static_cast<Kerning>(fields_.kerning_); }
FontVariantEastAsian VariantEastAsian() const {
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_fallback_list.cc b/chromium/third_party/blink/renderer/platform/fonts/font_fallback_list.cc
index a29433a64c5..85e8fbc134c 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_fallback_list.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_fallback_list.cc
@@ -174,7 +174,7 @@ scoped_refptr<FontData> FontFallbackList::GetFontData(
if (font_selector_) {
// Try the user's preferred standard font.
if (scoped_refptr<FontData> data = font_selector_->GetFontData(
- font_description, FontFamilyNames::webkit_standard))
+ font_description, font_family_names::kWebkitStandard))
return data;
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_family_names.json5 b/chromium/third_party/blink/renderer/platform/fonts/font_family_names.json5
index 638bf7995fe..ac7a142f9bf 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_family_names.json5
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_family_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "FontFamily",
+ namespace: "font_family_names",
export: "PLATFORM_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_metrics.cc b/chromium/third_party/blink/renderer/platform/fonts/font_metrics.cc
index 0d431a2eb65..abc03f40a1b 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_metrics.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_metrics.cc
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/fonts/font_platform_data.h"
#include "third_party/blink/renderer/platform/fonts/vdmx_parser.h"
-#include <SkPaint.h>
+#include <SkFont.h>
#include <SkTypeface.h>
namespace blink {
@@ -49,13 +49,13 @@ void FontMetrics::AscentDescentWithHacks(
unsigned& visual_overflow_inflation_for_ascent,
unsigned& visual_overflow_inflation_for_descent,
const FontPlatformData& platform_data,
- const SkPaint& paint,
+ const SkFont& font,
bool subpixel_ascent_descent) {
- SkTypeface* face = paint.getTypeface();
+ SkTypeface* face = font.getTypeface();
DCHECK(face);
- SkPaint::FontMetrics metrics;
- paint.getFontMetrics(&metrics);
+ SkFontMetrics metrics;
+ font.getMetrics(&metrics);
int vdmx_ascent = 0, vdmx_descent = 0;
bool is_vdmx_valid = false;
@@ -66,9 +66,9 @@ void FontMetrics::AscentDescentWithHacks(
// done. This code should be pushed into FreeType (hinted font metrics).
static const uint32_t kVdmxTag = SkSetFourByteTag('V', 'D', 'M', 'X');
int pixel_size = platform_data.size() + 0.5;
- if (!paint.isAutohinted() &&
- (paint.getHinting() == SkPaint::kFull_Hinting ||
- paint.getHinting() == SkPaint::kNormal_Hinting)) {
+ if (!font.isForceAutoHinting() &&
+ (font.getHinting() == SkFontHinting::kFull ||
+ font.getHinting() == SkFontHinting::kNormal)) {
size_t vdmx_size = face->getTableSize(kVdmxTag);
if (vdmx_size && vdmx_size < kMaxVDMXTableSize) {
uint8_t* vdmx_table = (uint8_t*)WTF::Partitions::FastMalloc(
@@ -132,9 +132,9 @@ void FontMetrics::AscentDescentWithHacks(
// incorrectly added to line spacing, so we use a 15% adjustment instead
// and add it to the ascent.
String family_name = platform_data.FontFamilyName();
- if (family_name == FontFamilyNames::Times ||
- family_name == FontFamilyNames::Helvetica ||
- family_name == FontFamilyNames::Courier)
+ if (family_name == font_family_names::kTimes ||
+ family_name == font_family_names::kHelvetica ||
+ family_name == font_family_names::kCourier)
ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
#endif
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_metrics.h b/chromium/third_party/blink/renderer/platform/fonts/font_metrics.h
index fbacc8cfee4..e440a79c627 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_metrics.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_metrics.h
@@ -21,11 +21,11 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_FONT_METRICS_H_
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
-#include <SkPaint.h>
+class SkFont;
namespace blink {
@@ -168,7 +168,7 @@ class FontMetrics {
unsigned& visual_overflow_inflation_for_ascent,
unsigned& visual_overflow_inflation_for_descent,
const FontPlatformData&,
- const SkPaint&,
+ const SkFont&,
bool subpixel_ascent_descent = false);
private:
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.cc b/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.cc
index 426c7db61e5..64dd8218e9a 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.cc
@@ -20,6 +20,7 @@
#include "third_party/blink/renderer/platform/fonts/font_platform_data.h"
+#include "SkFont.h"
#include "SkTypeface.h"
#include "build/build_config.h"
#include "hb-ot.h"
@@ -28,8 +29,8 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/text/character.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
@@ -147,11 +148,11 @@ FontPlatformData::FontPlatformData(sk_sp<SkTypeface> typeface,
auto system_style =
QuerySystemRenderStyle(family_, text_size_, typeface_->fontStyle());
- // In layout tests, ignore system preference for subpixel positioning,
+ // In web tests, ignore system preference for subpixel positioning,
// or explicitly disable if requested.
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
system_style.use_subpixel_positioning =
- LayoutTestSupport::IsTextSubpixelPositioningAllowedForTest()
+ WebTestSupport::IsTextSubpixelPositioningAllowedForTest()
? WebFontRenderStyle::kNoPreference
: 0;
}
@@ -281,13 +282,9 @@ unsigned FontPlatformData::GetHash() const {
#if !defined(OS_MACOSX)
bool FontPlatformData::FontContainsCharacter(UChar32 character) {
- PaintFont font;
- SetupPaintFont(&font);
- font.SetTextEncoding(SkPaint::kUTF32_TextEncoding);
-
- uint16_t glyph;
- font.ToSkPaint().textToGlyphs(&character, sizeof(character), &glyph);
- return glyph;
+ SkFont font;
+ SetupSkFont(&font);
+ return font.unicharToGlyph(character);
}
#endif
@@ -314,18 +311,32 @@ WebFontRenderStyle FontPlatformData::QuerySystemRenderStyle(
return result;
}
-void FontPlatformData::SetupPaintFont(PaintFont* font,
- float device_scale_factor,
- const Font*) const {
- style_.ApplyToPaintFont(*font, device_scale_factor);
+void FontPlatformData::SetupSkPaint(SkPaint* font,
+ float device_scale_factor,
+ const Font*) const {
+ style_.ApplyToSkPaint(*font, device_scale_factor);
+
+ const float ts = text_size_ >= 0 ? text_size_ : 12;
+ font->setTextSize(SkFloatToScalar(ts));
+ font->setTypeface(typeface_);
+ font->setFakeBoldText(synthetic_bold_);
+ font->setTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
+
+ font->setEmbeddedBitmapText(!avoid_embedded_bitmaps_);
+}
+
+void FontPlatformData::SetupSkFont(SkFont* font,
+ float device_scale_factor,
+ const Font*) const {
+ style_.ApplyToSkFont(font, device_scale_factor);
const float ts = text_size_ >= 0 ? text_size_ : 12;
- font->SetTextSize(SkFloatToScalar(ts));
- font->SetTypeface(typeface_);
- font->SetFakeBoldText(synthetic_bold_);
- font->SetTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
+ font->setSize(SkFloatToScalar(ts));
+ font->setTypeface(typeface_);
+ font->setEmbolden(synthetic_bold_);
+ font->setSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
- font->SetEmbeddedBitmapText(!avoid_embedded_bitmaps_);
+ font->setEmbeddedBitmaps(!avoid_embedded_bitmaps_);
}
#endif
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.h b/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.h
index ea701d0480a..7c6939331e2 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_platform_data.h
@@ -38,7 +38,6 @@
#include "third_party/blink/public/platform/web_font_render_style.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
#include "third_party/blink/renderer/platform/fonts/font_orientation.h"
-#include "third_party/blink/renderer/platform/fonts/paint_font.h"
#include "third_party/blink/renderer/platform/fonts/small_caps_iterator.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -66,6 +65,7 @@ inline NSFont* toNSFont(CTFontRef ctFontRef) {
}
#endif // defined(OS_MACOSX)
+class SkFont;
class SkTypeface;
typedef uint32_t SkFontID;
@@ -154,9 +154,14 @@ class PLATFORM_EXPORT FontPlatformData {
const WebFontRenderStyle& GetFontRenderStyle() const { return style_; }
#endif
- void SetupPaintFont(PaintFont*,
- float device_scale_factor = 1,
- const Font* = nullptr) const;
+ // TODO(reed): SetupSkPaint is deprecated. Remove this once all call sites
+ // are moved to SetupSkFont.
+ void SetupSkPaint(SkPaint*,
+ float device_scale_factor = 1,
+ const Font* = nullptr) const;
+ void SetupSkFont(SkFont*,
+ float device_scale_factor = 1,
+ const Font* = nullptr) const;
#if defined(OS_WIN)
int PaintTextFlags() const { return paint_text_flags_; }
diff --git a/chromium/third_party/blink/renderer/platform/fonts/font_selector.cc b/chromium/third_party/blink/renderer/platform/fonts/font_selector.cc
index 90bb107acbc..4e484041c51 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/font_selector.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/font_selector.cc
@@ -18,7 +18,7 @@ AtomicString FontSelector::FamilyNameFromSettings(
#if defined(OS_ANDROID)
if (font_description.GenericFamily() == FontDescription::kStandardFamily) {
return FontCache::GetGenericFamilyNameForScript(
- FontFamilyNames::webkit_standard, font_description);
+ font_family_names::kWebkitStandard, font_description);
}
if (generic_family_name.StartsWith("-webkit-")) {
@@ -29,19 +29,19 @@ AtomicString FontSelector::FamilyNameFromSettings(
UScriptCode script = font_description.GetScript();
if (font_description.GenericFamily() == FontDescription::kStandardFamily)
return settings.Standard(script);
- if (generic_family_name == FontFamilyNames::webkit_serif)
+ if (generic_family_name == font_family_names::kWebkitSerif)
return settings.Serif(script);
- if (generic_family_name == FontFamilyNames::webkit_sans_serif)
+ if (generic_family_name == font_family_names::kWebkitSansSerif)
return settings.SansSerif(script);
- if (generic_family_name == FontFamilyNames::webkit_cursive)
+ if (generic_family_name == font_family_names::kWebkitCursive)
return settings.Cursive(script);
- if (generic_family_name == FontFamilyNames::webkit_fantasy)
+ if (generic_family_name == font_family_names::kWebkitFantasy)
return settings.Fantasy(script);
- if (generic_family_name == FontFamilyNames::webkit_monospace)
+ if (generic_family_name == font_family_names::kWebkitMonospace)
return settings.Fixed(script);
- if (generic_family_name == FontFamilyNames::webkit_pictograph)
+ if (generic_family_name == font_family_names::kWebkitPictograph)
return settings.Pictograph(script);
- if (generic_family_name == FontFamilyNames::webkit_standard)
+ if (generic_family_name == font_family_names::kWebkitStandard)
return settings.Standard(script);
#endif
return g_empty_atom;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/mac/font_cache_mac.mm b/chromium/third_party/blink/renderer/platform/fonts/mac/font_cache_mac.mm
index 8b605043d91..829170dec12 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/mac/font_cache_mac.mm
+++ b/chromium/third_party/blink/renderer/platform/fonts/mac/font_cache_mac.mm
@@ -39,9 +39,9 @@
#include "third_party/blink/renderer/platform/fonts/font_platform_data.h"
#include "third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -63,12 +63,12 @@ const char kColorEmojiFontMac[] = "Apple Color Emoji";
// static
const AtomicString& FontCache::LegacySystemFontFamily() {
- return FontFamilyNames::BlinkMacSystemFont;
+ return font_family_names::kBlinkMacSystemFont;
}
static void InvalidateFontCache() {
if (!IsMainThread()) {
- Platform::Current()->MainThread()->GetTaskRunner()->PostTask(
+ Thread::MainThread()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&InvalidateFontCache));
return;
}
@@ -87,9 +87,9 @@ static void FontCacheRegisteredFontsChangedNotificationCallback(
}
static bool UseHinting() {
- // Enable hinting only when antialiasing is disabled in layout tests.
- return (LayoutTestSupport::IsRunningLayoutTest() &&
- !LayoutTestSupport::IsFontAntialiasingEnabledForTest());
+ // Enable hinting only when antialiasing is disabled in web tests.
+ return (WebTestSupport::IsRunningWebTest() &&
+ !WebTestSupport::IsFontAntialiasingEnabledForTest());
}
void FontCache::PlatformInit() {
@@ -232,7 +232,7 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
// For now we'll pick the default that the user would get without changing
// any prefs.
scoped_refptr<SimpleFontData> simple_font_data =
- GetFontData(font_description, FontFamilyNames::Times,
+ GetFontData(font_description, font_family_names::kTimes,
AlternateFontName::kAllowAlternate, should_retain);
if (simple_font_data)
return simple_font_data;
@@ -241,7 +241,7 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
// where the user doesn't have it, we fall back on Lucida Grande because
// that's guaranteed to be there, according to Nathan Taylor. This is good
// enough to avoid a crash at least.
- return GetFontData(font_description, FontFamilyNames::Lucida_Grande,
+ return GetFontData(font_description, font_family_names::kLucidaGrande,
AlternateFontName::kAllowAlternate, should_retain);
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm b/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm
index c6bced3e598..8d71fc2f18a 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm
+++ b/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm
@@ -174,7 +174,7 @@ NSFont* MatchNSFontFamily(const AtomicString& desired_family_string,
float size) {
DCHECK_NE(desired_family_string, FontCache::LegacySystemFontFamily());
- if (desired_family_string == FontFamilyNames::system_ui) {
+ if (desired_family_string == font_family_names::kSystemUi) {
NSFont* font = nil;
// Normally we'd use an availability macro here, but
// systemFontOfSize:weight: is available but not visible on macOS 10.10,
diff --git a/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac_test.mm b/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac_test.mm
index 67476f5a82b..c1d9ad62145 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac_test.mm
+++ b/chromium/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac_test.mm
@@ -19,7 +19,7 @@ namespace blink {
void TestSystemFontContainsString(FontSelectionValue desired_weight,
NSString* substring) {
NSFont* font =
- MatchNSFontFamily(FontFamilyNames::system_ui, 0, desired_weight, 11);
+ MatchNSFontFamily(font_family_names::kSystemUi, 0, desired_weight, 11);
EXPECT_TRUE([font.description containsString:substring]);
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm b/chromium/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
index 33b228f6b8a..97bebbdb53a 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
+++ b/chromium/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
@@ -30,9 +30,10 @@
#import "third_party/blink/renderer/platform/fonts/font.h"
#import "third_party/blink/renderer/platform/fonts/opentype/font_settings.h"
#import "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.h"
-#import "third_party/blink/renderer/platform/layout_test_support.h"
+#import "third_party/blink/renderer/platform/web_test_support.h"
#import "third_party/blink/renderer/platform/wtf/retain_ptr.h"
#import "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#import "third_party/skia/include/core/SkFont.h"
#import "third_party/skia/include/core/SkStream.h"
#import "third_party/skia/include/ports/SkTypeface_mac.h"
@@ -111,9 +112,9 @@ static sk_sp<SkTypeface> LoadFromBrowserProcess(NSFont* ns_font,
return return_font;
}
-void FontPlatformData::SetupPaintFont(PaintFont* paint_font,
- float,
- const Font* font) const {
+void FontPlatformData::SetupSkPaint(SkPaint* paint,
+ float,
+ const Font* font) const {
bool should_smooth_fonts = true;
bool should_antialias = true;
bool should_subpixel_position = true;
@@ -136,23 +137,23 @@ void FontPlatformData::SetupPaintFont(PaintFont* paint_font,
}
}
- if (LayoutTestSupport::IsRunningLayoutTest()) {
+ if (WebTestSupport::IsRunningWebTest()) {
should_smooth_fonts = false;
- should_antialias = should_antialias &&
- LayoutTestSupport::IsFontAntialiasingEnabledForTest();
+ should_antialias =
+ should_antialias && WebTestSupport::IsFontAntialiasingEnabledForTest();
should_subpixel_position =
- LayoutTestSupport::IsTextSubpixelPositioningAllowedForTest();
+ WebTestSupport::IsTextSubpixelPositioningAllowedForTest();
}
- paint_font->SetAntiAlias(should_antialias);
- paint_font->SetEmbeddedBitmapText(false);
+ paint->setAntiAlias(should_antialias);
+ paint->setEmbeddedBitmapText(false);
const float ts = text_size_ >= 0 ? text_size_ : 12;
- paint_font->SetTextSize(SkFloatToScalar(ts));
- paint_font->SetTypeface(typeface_);
- paint_font->SetFakeBoldText(synthetic_bold_);
- paint_font->SetTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
- paint_font->SetLcdRenderText(should_smooth_fonts);
- paint_font->SetSubpixelText(should_subpixel_position);
+ paint->setTextSize(SkFloatToScalar(ts));
+ paint->setTypeface(typeface_);
+ paint->setFakeBoldText(synthetic_bold_);
+ paint->setTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
+ paint->setLCDRenderText(should_smooth_fonts);
+ paint->setSubpixelText(should_subpixel_position);
// When rendering using CoreGraphics, disable hinting when
// webkit-font-smoothing:antialiased or text-rendering:geometricPrecision is
@@ -160,7 +161,64 @@ void FontPlatformData::SetupPaintFont(PaintFont* paint_font,
if (font &&
(font->GetFontDescription().FontSmoothing() == kAntialiased ||
font->GetFontDescription().TextRendering() == kGeometricPrecision))
- paint_font->SetHinting(SkPaint::kNo_Hinting);
+ paint->setHinting(SkFontHinting::kNone);
+}
+
+void FontPlatformData::SetupSkFont(SkFont* skfont,
+ float,
+ const Font* font) const {
+ bool should_smooth_fonts = true;
+ bool should_antialias = true;
+ bool should_subpixel_position = true;
+
+ if (font) {
+ switch (font->GetFontDescription().FontSmoothing()) {
+ case kAntialiased:
+ should_smooth_fonts = false;
+ break;
+ case kSubpixelAntialiased:
+ break;
+ case kNoSmoothing:
+ should_antialias = false;
+ should_smooth_fonts = false;
+ break;
+ case kAutoSmoothing:
+ // For the AutoSmooth case, don't do anything! Keep the default
+ // settings.
+ break;
+ }
+ }
+
+ if (WebTestSupport::IsRunningWebTest()) {
+ should_smooth_fonts = false;
+ should_antialias =
+ should_antialias && WebTestSupport::IsFontAntialiasingEnabledForTest();
+ should_subpixel_position =
+ WebTestSupport::IsTextSubpixelPositioningAllowedForTest();
+ }
+
+ if (should_antialias && should_smooth_fonts) {
+ skfont->setEdging(SkFont::Edging::kSubpixelAntiAlias);
+ } else if (should_antialias) {
+ skfont->setEdging(SkFont::Edging::kAntiAlias);
+ } else {
+ skfont->setEdging(SkFont::Edging::kAlias);
+ }
+ skfont->setEmbeddedBitmaps(false);
+ const float ts = text_size_ >= 0 ? text_size_ : 12;
+ skfont->setSize(SkFloatToScalar(ts));
+ skfont->setTypeface(typeface_);
+ skfont->setEmbolden(synthetic_bold_);
+ skfont->setSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
+ skfont->setSubpixel(should_subpixel_position);
+
+ // When rendering using CoreGraphics, disable hinting when
+ // webkit-font-smoothing:antialiased or text-rendering:geometricPrecision is
+ // used. See crbug.com/152304
+ if (font &&
+ (font->GetFontDescription().FontSmoothing() == kAntialiased ||
+ font->GetFontDescription().TextRendering() == kGeometricPrecision))
+ skfont->setHinting(SkFontHinting::kNone);
}
FontPlatformData::FontPlatformData(NSFont* ns_font,
diff --git a/chromium/third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h b/chromium/third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h
index e4b58a8a90b..d42fc22c15f 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/ng_text_fragment_paint_info.h
@@ -10,7 +10,7 @@
namespace blink {
-class ShapeResult;
+class ShapeResultView;
// Bridge struct for painting text. Encapsulates info needed by the paint code.
struct PLATFORM_EXPORT NGTextFragmentPaintInfo {
@@ -23,7 +23,7 @@ struct PLATFORM_EXPORT NGTextFragmentPaintInfo {
// The |shape_result| may not contain all characters of the |text|, but is
// guaranteed to contain |from| to |to|.
- const ShapeResult* shape_result;
+ const ShapeResultView* shape_result;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support_mpl.cc b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support_mpl.cc
index 0e0a808ac1c..f04b91d087b 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support_mpl.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support_mpl.cc
@@ -6,6 +6,7 @@
*
* ***** END LICENSE BLOCK ***** */
+#include "base/stl_util.h"
#include "third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support.h"
#include <hb-ot.h>
@@ -29,17 +30,18 @@ bool OpenTypeCapsSupport::SupportsOpenTypeFeature(hb_script_t script,
return false;
// Get the OpenType tag(s) that match this script code
- hb_tag_t script_tags[] = {
- HB_TAG_NONE, HB_TAG_NONE, HB_TAG_NONE,
- };
- hb_ot_tags_from_script(static_cast<hb_script_t>(script), &script_tags[0],
- &script_tags[1]);
+ DCHECK_EQ(HB_TAG_NONE, 0u);
+ hb_tag_t script_tags[2] = {};
+ unsigned num_returned_script_tags = base::size(script_tags);
+ hb_ot_tags_from_script_and_language(
+ static_cast<hb_script_t>(script), HB_LANGUAGE_INVALID,
+ &num_returned_script_tags, script_tags, nullptr, nullptr);
const hb_tag_t kGSUB = HB_TAG('G', 'S', 'U', 'B');
unsigned script_index = 0;
// Identify for which script a GSUB table is available.
- hb_ot_layout_table_choose_script(face, kGSUB, script_tags, &script_index,
- nullptr);
+ hb_ot_layout_table_select_script(face, kGSUB, num_returned_script_tags,
+ script_tags, &script_index, nullptr);
if (hb_ot_layout_language_find_feature(face, kGSUB, script_index,
HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX,
diff --git a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_types.h b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_types.h
index d605c176897..12c90c9b174 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_types.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_types.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
-namespace OpenType {
+namespace open_type {
struct Int16 {
DISALLOW_NEW();
@@ -101,6 +101,6 @@ struct TableBase {
}
};
-} // namespace OpenType
+} // namespace open_type
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_OPENTYPE_OPEN_TYPE_TYPES_H_
diff --git a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.cc b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.cc
index 32362740417..39676595708 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.cc
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
-namespace OpenType {
+namespace open_type {
// The input characters are big-endian (first is most significant).
#define OT_MAKE_TAG(ch1, ch2, ch3, ch4) \
@@ -50,46 +50,46 @@ const SkFontTableTag kVORGTag = OT_MAKE_TAG('V', 'O', 'R', 'G');
struct HheaTable {
DISALLOW_NEW();
- OpenType::Fixed version;
- OpenType::Int16 ascender;
- OpenType::Int16 descender;
- OpenType::Int16 line_gap;
- OpenType::Int16 advance_width_max;
- OpenType::Int16 min_left_side_bearing;
- OpenType::Int16 min_right_side_bearing;
- OpenType::Int16 x_max_extent;
- OpenType::Int16 caret_slope_rise;
- OpenType::Int16 caret_slope_run;
- OpenType::Int16 caret_offset;
- OpenType::Int16 reserved[4];
- OpenType::Int16 metric_data_format;
- OpenType::UInt16 number_of_h_metrics;
+ open_type::Fixed version;
+ open_type::Int16 ascender;
+ open_type::Int16 descender;
+ open_type::Int16 line_gap;
+ open_type::Int16 advance_width_max;
+ open_type::Int16 min_left_side_bearing;
+ open_type::Int16 min_right_side_bearing;
+ open_type::Int16 x_max_extent;
+ open_type::Int16 caret_slope_rise;
+ open_type::Int16 caret_slope_run;
+ open_type::Int16 caret_offset;
+ open_type::Int16 reserved[4];
+ open_type::Int16 metric_data_format;
+ open_type::UInt16 number_of_h_metrics;
};
struct VheaTable {
DISALLOW_NEW();
- OpenType::Fixed version;
- OpenType::Int16 ascent;
- OpenType::Int16 descent;
- OpenType::Int16 line_gap;
- OpenType::Int16 advance_height_max;
- OpenType::Int16 min_top_side_bearing;
- OpenType::Int16 min_bottom_side_bearing;
- OpenType::Int16 y_max_extent;
- OpenType::Int16 caret_slope_rise;
- OpenType::Int16 caret_slope_run;
- OpenType::Int16 caret_offset;
- OpenType::Int16 reserved[4];
- OpenType::Int16 metric_data_format;
- OpenType::UInt16 num_of_long_ver_metrics;
+ open_type::Fixed version;
+ open_type::Int16 ascent;
+ open_type::Int16 descent;
+ open_type::Int16 line_gap;
+ open_type::Int16 advance_height_max;
+ open_type::Int16 min_top_side_bearing;
+ open_type::Int16 min_bottom_side_bearing;
+ open_type::Int16 y_max_extent;
+ open_type::Int16 caret_slope_rise;
+ open_type::Int16 caret_slope_run;
+ open_type::Int16 caret_offset;
+ open_type::Int16 reserved[4];
+ open_type::Int16 metric_data_format;
+ open_type::UInt16 num_of_long_ver_metrics;
};
struct HmtxTable {
DISALLOW_NEW();
struct Entry {
DISALLOW_NEW();
- OpenType::UInt16 advance_width;
- OpenType::Int16 lsb;
+ open_type::UInt16 advance_width;
+ open_type::Int16 lsb;
} entries[1];
};
@@ -97,21 +97,21 @@ struct VmtxTable {
DISALLOW_NEW();
struct Entry {
DISALLOW_NEW();
- OpenType::UInt16 advance_height;
- OpenType::Int16 top_side_bearing;
+ open_type::UInt16 advance_height;
+ open_type::Int16 top_side_bearing;
} entries[1];
};
struct VORGTable {
DISALLOW_NEW();
- OpenType::UInt16 major_version;
- OpenType::UInt16 minor_version;
- OpenType::Int16 default_vert_origin_y;
- OpenType::UInt16 num_vert_origin_y_metrics;
+ open_type::UInt16 major_version;
+ open_type::UInt16 minor_version;
+ open_type::Int16 default_vert_origin_y;
+ open_type::UInt16 num_vert_origin_y_metrics;
struct VertOriginYMetrics {
DISALLOW_NEW();
- OpenType::UInt16 glyph_index;
- OpenType::Int16 vert_origin_y;
+ open_type::UInt16 glyph_index;
+ open_type::Int16 vert_origin_y;
} vert_origin_y_metrics[1];
size_t RequiredSize() const {
@@ -122,7 +122,7 @@ struct VORGTable {
#pragma pack()
-} // namespace OpenType
+} // namespace open_type
OpenTypeVerticalData::OpenTypeVerticalData(sk_sp<SkTypeface> typeface)
: default_vert_origin_y_(0),
@@ -146,9 +146,9 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
// Load hhea and hmtx to get x-component of vertical origins.
// If these tables are missing, it's not an OpenType font.
Vector<char> buffer;
- CopyOpenTypeTable(typeface, OpenType::kHheaTag, buffer);
- const OpenType::HheaTable* hhea =
- OpenType::ValidateTable<OpenType::HheaTable>(buffer);
+ CopyOpenTypeTable(typeface, open_type::kHheaTag, buffer);
+ const open_type::HheaTable* hhea =
+ open_type::ValidateTable<open_type::HheaTable>(buffer);
if (!hhea)
return;
uint16_t count_hmtx_entries = hhea->number_of_h_metrics;
@@ -157,9 +157,10 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
return;
}
- CopyOpenTypeTable(typeface, OpenType::kHmtxTag, buffer);
- const OpenType::HmtxTable* hmtx =
- OpenType::ValidateTable<OpenType::HmtxTable>(buffer, count_hmtx_entries);
+ CopyOpenTypeTable(typeface, open_type::kHmtxTag, buffer);
+ const open_type::HmtxTable* hmtx =
+ open_type::ValidateTable<open_type::HmtxTable>(buffer,
+ count_hmtx_entries);
if (!hmtx) {
DLOG(ERROR) << "hhea exists but hmtx does not (or broken)";
return;
@@ -170,9 +171,9 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
// Load vhea first. This table is required for fonts that support vertical
// flow.
- CopyOpenTypeTable(typeface, OpenType::kVheaTag, buffer);
- const OpenType::VheaTable* vhea =
- OpenType::ValidateTable<OpenType::VheaTable>(buffer);
+ CopyOpenTypeTable(typeface, open_type::kVheaTag, buffer);
+ const open_type::VheaTable* vhea =
+ open_type::ValidateTable<open_type::VheaTable>(buffer);
if (!vhea)
return;
uint16_t count_vmtx_entries = vhea->num_of_long_ver_metrics;
@@ -182,9 +183,9 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
}
// Load VORG. This table is optional.
- CopyOpenTypeTable(typeface, OpenType::kVORGTag, buffer);
- const OpenType::VORGTable* vorg =
- OpenType::ValidateTable<OpenType::VORGTable>(buffer);
+ CopyOpenTypeTable(typeface, open_type::kVORGTag, buffer);
+ const open_type::VORGTable* vorg =
+ open_type::ValidateTable<open_type::VORGTable>(buffer);
if (vorg && buffer.size() >= vorg->RequiredSize()) {
default_vert_origin_y_ = vorg->default_vert_origin_y;
uint16_t count_vert_origin_y_metrics = vorg->num_vert_origin_y_metrics;
@@ -193,7 +194,7 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
vert_origin_y_.Set(0, default_vert_origin_y_);
} else {
for (uint16_t i = 0; i < count_vert_origin_y_metrics; ++i) {
- const OpenType::VORGTable::VertOriginYMetrics& metrics =
+ const open_type::VORGTable::VertOriginYMetrics& metrics =
vorg->vert_origin_y_metrics[i];
vert_origin_y_.Set(metrics.glyph_index, metrics.vert_origin_y);
}
@@ -202,9 +203,10 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
// Load vmtx then. This table is required for fonts that support vertical
// flow.
- CopyOpenTypeTable(typeface, OpenType::kVmtxTag, buffer);
- const OpenType::VmtxTable* vmtx =
- OpenType::ValidateTable<OpenType::VmtxTable>(buffer, count_vmtx_entries);
+ CopyOpenTypeTable(typeface, open_type::kVmtxTag, buffer);
+ const open_type::VmtxTable* vmtx =
+ open_type::ValidateTable<open_type::VmtxTable>(buffer,
+ count_vmtx_entries);
if (!vmtx) {
DLOG(ERROR) << "vhea exists but vmtx does not (or broken)";
return;
@@ -219,20 +221,20 @@ void OpenTypeVerticalData::LoadMetrics(sk_sp<SkTypeface> typeface) {
return;
wtf_size_t size_extra =
- buffer.size() - sizeof(OpenType::VmtxTable::Entry) * count_vmtx_entries;
- if (size_extra % sizeof(OpenType::Int16)) {
+ buffer.size() - sizeof(open_type::VmtxTable::Entry) * count_vmtx_entries;
+ if (size_extra % sizeof(open_type::Int16)) {
DLOG(ERROR) << "vmtx has incorrect tsb count";
return;
}
wtf_size_t count_top_side_bearings =
- count_vmtx_entries + size_extra / sizeof(OpenType::Int16);
+ count_vmtx_entries + size_extra / sizeof(open_type::Int16);
top_side_bearings_.resize(count_top_side_bearings);
wtf_size_t i;
for (i = 0; i < count_vmtx_entries; ++i)
top_side_bearings_[i] = vmtx->entries[i].top_side_bearing;
if (i < count_top_side_bearings) {
- const OpenType::Int16* p_top_side_bearings_extra =
- reinterpret_cast<const OpenType::Int16*>(
+ const open_type::Int16* p_top_side_bearings_extra =
+ reinterpret_cast<const open_type::Int16*>(
&vmtx->entries[count_vmtx_entries]);
for (; i < count_top_side_bearings; ++i, ++p_top_side_bearings_extra)
top_side_bearings_[i] = *p_top_side_bearings_extra;
@@ -261,7 +263,7 @@ float OpenTypeVerticalData::AdvanceHeight(Glyph glyph) const {
}
void OpenTypeVerticalData::GetVerticalTranslationsForGlyphs(
- const SkPaint& paint,
+ const SkFont& font,
const Glyph* glyphs,
size_t count,
float* out_xy_array) const {
@@ -302,7 +304,7 @@ void OpenTypeVerticalData::GetVerticalTranslationsForGlyphs(
float top_side_bearing = top_side_bearing_f_unit * size_per_unit_;
SkRect skiaBounds;
- SkiaTextMetrics(&paint).GetSkiaBoundsForGlyph(glyph, &skiaBounds);
+ SkFontGetBoundsForGlyph(font, glyph, &skiaBounds);
FloatRect bounds(skiaBounds);
out_xy_array[1] = bounds.Y() - top_side_bearing;
continue;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.h b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.h
index 109609279df..d6aa27105a2 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data.h
@@ -33,10 +33,11 @@
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
-#include <SkPaint.h>
#include <SkRefCnt.h>
#include <SkTypeface.h>
+class SkFont;
+
namespace blink {
class PLATFORM_EXPORT OpenTypeVerticalData
@@ -55,7 +56,7 @@ class PLATFORM_EXPORT OpenTypeVerticalData
bool HasVerticalMetrics() const { return !advance_heights_.IsEmpty(); }
float AdvanceHeight(Glyph) const;
- void GetVerticalTranslationsForGlyphs(const SkPaint&,
+ void GetVerticalTranslationsForGlyphs(const SkFont&,
const Glyph*,
size_t,
float* out_xy_array) const;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data_test.cc b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data_test.cc
index cd03dc5d349..bdb7d7bc845 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data_test.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/opentype/open_type_vertical_data_test.cc
@@ -28,9 +28,9 @@
namespace blink {
-struct TestTable : OpenType::TableBase {
- OpenType::Fixed version;
- OpenType::Int16 ascender;
+struct TestTable : open_type::TableBase {
+ open_type::Fixed version;
+ open_type::Int16 ascender;
template <typename T>
const T* ValidateOffset(const Vector<char>& buffer, uint16_t offset) const {
@@ -40,21 +40,21 @@ struct TestTable : OpenType::TableBase {
TEST(OpenTypeVerticalDataTest, ValidateTableTest) {
Vector<char> buffer(sizeof(TestTable));
- const TestTable* table = OpenType::ValidateTable<TestTable>(buffer);
+ const TestTable* table = open_type::ValidateTable<TestTable>(buffer);
EXPECT_TRUE(table);
buffer = Vector<char>(sizeof(TestTable) - 1);
- table = OpenType::ValidateTable<TestTable>(buffer);
+ table = open_type::ValidateTable<TestTable>(buffer);
EXPECT_FALSE(table);
buffer = Vector<char>(sizeof(TestTable) + 1);
- table = OpenType::ValidateTable<TestTable>(buffer);
+ table = open_type::ValidateTable<TestTable>(buffer);
EXPECT_TRUE(table);
}
TEST(OpenTypeVerticalDataTest, ValidateOffsetTest) {
Vector<char> buffer(sizeof(TestTable));
- const TestTable* table = OpenType::ValidateTable<TestTable>(buffer);
+ const TestTable* table = open_type::ValidateTable<TestTable>(buffer);
ASSERT_TRUE(table);
// Test overflow
diff --git a/chromium/third_party/blink/renderer/platform/fonts/paint_font.h b/chromium/third_party/blink/renderer/platform/fonts/paint_font.h
deleted file mode 100644
index 1902b8ba259..00000000000
--- a/chromium/third_party/blink/renderer/platform/fonts/paint_font.h
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_PAINT_FONT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_PAINT_FONT_H_
-
-#include "cc/paint/paint_font.h"
-
-namespace blink {
-using cc::PaintFont;
-}
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_PAINT_FONT_H_
diff --git a/chromium/third_party/blink/renderer/platform/fonts/paint_text_blob.h b/chromium/third_party/blink/renderer/platform/fonts/paint_text_blob.h
deleted file mode 100644
index 978dc6392ca..00000000000
--- a/chromium/third_party/blink/renderer/platform/fonts/paint_text_blob.h
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_PAINT_TEXT_BLOB_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_PAINT_TEXT_BLOB_H_
-
-#include "cc/paint/paint_text_blob.h"
-#include "cc/paint/paint_text_blob_builder.h"
-
-namespace blink {
-using cc::PaintTextBlob;
-using cc::PaintTextBlobBuilder;
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_PAINT_TEXT_BLOB_H_
diff --git a/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator.cc b/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator.cc
index 86da0df514e..012238f1901 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator.cc
@@ -10,6 +10,26 @@
namespace blink {
+namespace {
+
+// UScriptCode and OpenType script are not 1:1; specifically, both Hiragana and
+// Katakana map to 'kana' in OpenType. They will be mapped correctly in
+// HarfBuzz, but normalizing earlier helps to reduce splitting runs between
+// these scripts.
+// https://docs.microsoft.com/en-us/typography/opentype/spec/scripttags
+inline UScriptCode getScriptForOpenType(UChar32 ch, UErrorCode* status) {
+ UScriptCode script = uscript_getScript(ch, status);
+ if (UNLIKELY(U_FAILURE(*status)))
+ return script;
+ if (UNLIKELY(script == USCRIPT_KATAKANA ||
+ script == USCRIPT_KATAKANA_OR_HIRAGANA)) {
+ return USCRIPT_HIRAGANA;
+ }
+ return script;
+}
+
+} // namespace
+
typedef ScriptData::PairedBracketType PairedBracketType;
constexpr int ScriptRunIterator::kMaxScriptCount;
@@ -27,6 +47,10 @@ void ICUScriptData::GetScripts(UChar32 ch, UScriptCodeList& dst) const {
// regardless of the capacity passed to the call. So count can be greater
// than dst->size(), if a later version of the unicode data has more
// than kMaxScriptCount items.
+
+ // |uscript_getScriptExtensions| do not need to be collated to
+ // USCRIPT_HIRAGANA because when ScriptExtensions contains Kana, it contains
+ // Hira as well, and Hira is always before Kana.
int count = uscript_getScriptExtensions(ch, &dst[0], dst.size(), &status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
// Allow this, we'll just use what we have.
@@ -35,7 +59,7 @@ void ICUScriptData::GetScripts(UChar32 ch, UScriptCodeList& dst) const {
count = dst.size();
status = U_ZERO_ERROR;
}
- UScriptCode primary_script = uscript_getScript(ch, &status);
+ UScriptCode primary_script = getScriptForOpenType(ch, &status);
if (U_FAILURE(status)) {
DLOG(ERROR) << "Could not get icu script data: " << status << " for 0x"
diff --git a/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc b/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc
index 3e2a7a0e6eb..a792bdfb5c8 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc
@@ -370,6 +370,50 @@ TEST_F(ScriptRunIteratorTest, Chinese) {
CHECK_SCRIPT_RUNS({{"萬國碼", USCRIPT_HAN}});
}
+struct JapaneseMixedScript {
+ const char* string;
+ // The expected primary_script when the string alone was evaluated.
+ UScriptCode script;
+} japanese_mixed_scripts[] = {{"あ", USCRIPT_HIRAGANA},
+ // Katakana should be normalized to Hiragana
+ {"ア", USCRIPT_HIRAGANA},
+ // Script_Extensions=Hira Kana
+ {"\u30FC", USCRIPT_HIRAGANA},
+ // Script_Extensions=Hani Hira Kana
+ {"\u303C", USCRIPT_HAN},
+ // Script_Extensions=Bopo Hang Hani Hira Kana
+ {"\u3003", USCRIPT_BOPOMOFO},
+ // Script_Extensions=Bopo Hang Hani Hira Kana Yiii
+ {"\u3001", USCRIPT_BOPOMOFO}};
+
+class JapaneseMixedScriptTest
+ : public ScriptRunIteratorTest,
+ public testing::WithParamInterface<JapaneseMixedScript> {};
+
+INSTANTIATE_TEST_CASE_P(ScriptRunIteratorTest,
+ JapaneseMixedScriptTest,
+ testing::ValuesIn(japanese_mixed_scripts));
+
+TEST_P(JapaneseMixedScriptTest, Data) {
+ const auto& data = GetParam();
+ std::string string(data.string);
+
+ CheckRuns({{string.data(), data.script}});
+
+ // If the string follows Hiragana or Katakana, or is followed by Hiragnaa or
+ // Katakana, it should be normalized as Hiragana.
+ std::string hiragana("か");
+ std::string katakana("カ");
+ CheckRuns({{(hiragana + string).data(), USCRIPT_HIRAGANA}});
+ CheckRuns({{(string + hiragana).data(), USCRIPT_HIRAGANA}});
+
+ CheckRuns({{(katakana + string).data(), USCRIPT_HIRAGANA}});
+ CheckRuns({{(string + katakana).data(), USCRIPT_HIRAGANA}});
+
+ CheckRuns({{(hiragana + string + katakana).data(), USCRIPT_HIRAGANA}});
+ CheckRuns({{(katakana + string + hiragana).data(), USCRIPT_HIRAGANA}});
+}
+
// Close bracket without matching open is ignored
TEST_F(ScriptRunIteratorTest, UnbalancedParens1) {
CHECK_SCRIPT_RUNS(
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/case_mapping_harfbuzz_buffer_filler.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/case_mapping_harfbuzz_buffer_filler.cc
index 2ab8d8c22be..e6a5fff8636 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/case_mapping_harfbuzz_buffer_filler.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/case_mapping_harfbuzz_buffer_filler.cc
@@ -38,8 +38,10 @@ CaseMappingHarfBuzzBufferFiller::CaseMappingHarfBuzzBufferFiller(
case_mapped_text.Ensure16Bit();
if (case_mapped_text.length() != text.length()) {
- FillSlowCase(case_map_intend, locale, text.Characters16(), text.length(),
- start_index, num_characters);
+ String original_text = text;
+ original_text.Ensure16Bit();
+ FillSlowCase(case_map_intend, locale, original_text.Characters16(),
+ original_text.length(), start_index, num_characters);
return;
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h
new file mode 100644
index 00000000000..06e1adb9fff
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_GLYPH_BOUNDS_ACCUMULATOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_GLYPH_BOUNDS_ACCUMULATOR_H_
+
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h"
+#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+
+namespace blink {
+
+// Helper class to accumulate glyph bounding box.
+//
+// Glyph positions and bounding boxes from HarfBuzz and fonts are in physical
+// coordinate, while ShapeResult::glyph_bounding_box_ is in logical coordinate.
+// To minimize the number of conversions, this class accumulates the bounding
+// boxes in physical coordinate, and convert the accumulated box to logical.
+struct GlyphBoundsAccumulator {
+ // Construct an accumulator with the logical glyph origin.
+ explicit GlyphBoundsAccumulator(float origin) : origin(origin) {}
+
+ // The accumulated glyph bounding box in physical coordinate, until
+ // ConvertVerticalRunToLogical().
+ FloatRect bounds;
+ // The current origin, in logical coordinate.
+ float origin;
+
+ // Unite a glyph bounding box to |bounds|.
+ template <bool is_horizontal_run>
+ void Unite(const HarfBuzzRunGlyphData& glyph_data,
+ FloatRect bounds_for_glyph) {
+ if (UNLIKELY(bounds_for_glyph.IsEmpty()))
+ return;
+
+ // Glyphs are drawn at |origin + offset|. Move glyph_bounds to that point.
+ // All positions in hb_glyph_position_t are relative to the current point.
+ // https://behdad.github.io/harfbuzz/harfbuzz-Buffers.html#hb-glyph-position-t-struct
+ if (is_horizontal_run)
+ bounds_for_glyph.SetX(bounds_for_glyph.X() + origin);
+ else
+ bounds_for_glyph.SetY(bounds_for_glyph.Y() + origin);
+ bounds_for_glyph.Move(glyph_data.offset);
+
+ bounds.Unite(bounds_for_glyph);
+ }
+
+ // Non-template version of |Unite()|, see above.
+ void Unite(bool is_horizontal_run,
+ const HarfBuzzRunGlyphData& glyph,
+ FloatRect bounds_for_glyph) {
+ is_horizontal_run ? Unite<true>(glyph, bounds_for_glyph)
+ : Unite<false>(glyph, bounds_for_glyph);
+ }
+
+ // Convert vertical run glyph bounding box to logical. Horizontal runs do not
+ // need conversions because physical and logical are the same.
+ void ConvertVerticalRunToLogical(const FontMetrics& font_metrics) {
+ // Convert physical glyph_bounding_box to logical.
+ bounds = bounds.TransposedRect();
+
+ // The glyph bounding box of a vertical run uses ideographic baseline.
+ // Adjust the box Y position because the bounding box of a ShapeResult uses
+ // alphabetic baseline.
+ // See diagrams of base lines at
+ // https://drafts.csswg.org/css-writing-modes-3/#intro-baselines
+ int baseline_adjust = font_metrics.Ascent(kIdeographicBaseline) -
+ font_metrics.Ascent(kAlphabeticBaseline);
+ bounds.SetY(bounds.Y() + baseline_adjust);
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_GLYPH_BOUNDS_ACCUMULATOR_H_
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.cc
index b8bdb2a2c02..12a451129b9 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_face.cc
@@ -49,9 +49,6 @@
#include <hb-ot.h>
#include <hb.h>
-#if defined(OS_MACOSX)
-#include <hb-coretext.h>
-#endif
#include <SkPaint.h>
#include <SkPath.h>
@@ -123,6 +120,14 @@ static hb_bool_t HarfBuzzGetGlyph(hb_font_t* hb_font,
variation_selector, glyph);
}
+static hb_bool_t HarfBuzzGetNominalGlyph(hb_font_t* hb_font,
+ void* font_data,
+ hb_codepoint_t unicode,
+ hb_codepoint_t* glyph,
+ void* user_data) {
+ return HarfBuzzGetGlyph(hb_font, font_data, unicode, 0, glyph, user_data);
+}
+
static hb_position_t HarfBuzzGetGlyphHorizontalAdvance(hb_font_t* hb_font,
void* font_data,
hb_codepoint_t glyph,
@@ -131,24 +136,23 @@ static hb_position_t HarfBuzzGetGlyphHorizontalAdvance(hb_font_t* hb_font,
reinterpret_cast<HarfBuzzFontData*>(font_data);
hb_position_t advance = 0;
- SkiaTextMetrics(&hb_font_data->paint_)
- .GetGlyphWidthForHarfBuzz(glyph, &advance);
+ SkFontGetGlyphWidthForHarfBuzz(hb_font_data->font_, glyph, &advance);
return advance;
}
-static void HarfBuzzGetGlyphHorizontalAdvances(hb_font_t* font,
- void* font_data,
- unsigned count,
- hb_codepoint_t* first_glyph,
- unsigned int glyph_stride,
- hb_position_t* first_advance,
- unsigned int advance_stride,
- void* user_data) {
+static void HarfBuzzGetGlyphHorizontalAdvances(
+ hb_font_t* font,
+ void* font_data,
+ unsigned count,
+ const hb_codepoint_t* first_glyph,
+ unsigned int glyph_stride,
+ hb_position_t* first_advance,
+ unsigned int advance_stride,
+ void* user_data) {
HarfBuzzFontData* hb_font_data =
reinterpret_cast<HarfBuzzFontData*>(font_data);
- SkiaTextMetrics(&hb_font_data->paint_)
- .GetGlyphWidthForHarfBuzz(count, first_glyph, glyph_stride, first_advance,
- advance_stride);
+ SkFontGetGlyphWidthForHarfBuzz(hb_font_data->font_, count, first_glyph,
+ glyph_stride, first_advance, advance_stride);
}
static hb_bool_t HarfBuzzGetGlyphVerticalOrigin(hb_font_t* hb_font,
@@ -166,10 +170,10 @@ static hb_bool_t HarfBuzzGetGlyphVerticalOrigin(hb_font_t* hb_font,
float result[] = {0, 0};
Glyph the_glyph = glyph;
- vertical_data->GetVerticalTranslationsForGlyphs(hb_font_data->paint_,
+ vertical_data->GetVerticalTranslationsForGlyphs(hb_font_data->font_,
&the_glyph, 1, result);
- *x = SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(-result[0]);
- *y = SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(-result[1]);
+ *x = SkiaScalarToHarfBuzzPosition(-result[0]);
+ *y = SkiaScalarToHarfBuzzPosition(-result[1]);
return true;
}
@@ -182,42 +186,12 @@ static hb_position_t HarfBuzzGetGlyphVerticalAdvance(hb_font_t* hb_font,
scoped_refptr<OpenTypeVerticalData> vertical_data =
hb_font_data->VerticalData();
if (!vertical_data) {
- return SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(
- hb_font_data->height_fallback_);
+ return SkiaScalarToHarfBuzzPosition(hb_font_data->height_fallback_);
}
Glyph the_glyph = glyph;
float advance_height = -vertical_data->AdvanceHeight(the_glyph);
- return SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(
- SkFloatToScalar(advance_height));
-}
-
-static hb_position_t HarfBuzzGetGlyphHorizontalKerning(
- hb_font_t*,
- void* font_data,
- hb_codepoint_t left_glyph,
- hb_codepoint_t right_glyph,
- void*) {
- HarfBuzzFontData* hb_font_data =
- reinterpret_cast<HarfBuzzFontData*>(font_data);
- if (hb_font_data->paint_.isVerticalText()) {
- // We don't support cross-stream kerning
- return 0;
- }
-
- SkTypeface* typeface = hb_font_data->paint_.getTypeface();
-
- const uint16_t glyphs[2] = {static_cast<uint16_t>(left_glyph),
- static_cast<uint16_t>(right_glyph)};
- int32_t kerning_adjustments[1] = {0};
-
- if (typeface->getKerningPairAdjustments(glyphs, 2, kerning_adjustments)) {
- return SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(
- SkIntToScalar(kerning_adjustments[0]) *
- hb_font_data->SizePerUnit(*typeface));
- }
-
- return 0;
+ return SkiaScalarToHarfBuzzPosition(SkFloatToScalar(advance_height));
}
static hb_bool_t HarfBuzzGetGlyphExtents(hb_font_t* hb_font,
@@ -228,8 +202,7 @@ static hb_bool_t HarfBuzzGetGlyphExtents(hb_font_t* hb_font,
HarfBuzzFontData* hb_font_data =
reinterpret_cast<HarfBuzzFontData*>(font_data);
- SkiaTextMetrics(&hb_font_data->paint_)
- .GetGlyphExtentsForHarfBuzz(glyph, extents);
+ SkFontGetGlyphExtentsForHarfBuzz(hb_font_data->font_, glyph, extents);
return true;
}
@@ -304,7 +277,7 @@ unsigned HarfBuzzFace::UnitsPerEmFromHeadTable() {
}
bool HarfBuzzFace::ShouldSubpixelPosition() {
- return harfbuzz_font_data_->paint_.isSubpixelText();
+ return harfbuzz_font_data_->font_.isSubpixel();
}
static hb_font_funcs_t* HarfBuzzSkiaGetFontFuncs() {
@@ -314,13 +287,16 @@ static hb_font_funcs_t* HarfBuzzSkiaGetFontFuncs() {
// HarfBuzz will use the fallback implementation if they aren't set.
if (!funcs) {
funcs = hb_font_funcs_create();
- hb_font_funcs_set_glyph_func(funcs, HarfBuzzGetGlyph, nullptr, nullptr);
+ hb_font_funcs_set_variation_glyph_func(funcs, HarfBuzzGetGlyph, nullptr,
+ nullptr);
+ hb_font_funcs_set_nominal_glyph_func(funcs, HarfBuzzGetNominalGlyph,
+ nullptr, nullptr);
hb_font_funcs_set_glyph_h_advance_func(
funcs, HarfBuzzGetGlyphHorizontalAdvance, nullptr, nullptr);
hb_font_funcs_set_glyph_h_advances_func(
funcs, HarfBuzzGetGlyphHorizontalAdvances, nullptr, nullptr);
- hb_font_funcs_set_glyph_h_kerning_func(
- funcs, HarfBuzzGetGlyphHorizontalKerning, nullptr, nullptr);
+ // TODO(https://crbug.com/899718): Replace vertical metrics callbacks with
+ // HarfBuzz VORG/VMTX internal implementation by deregistering those.
hb_font_funcs_set_glyph_v_advance_func(
funcs, HarfBuzzGetGlyphVerticalAdvance, nullptr, nullptr);
hb_font_funcs_set_glyph_v_origin_func(funcs, HarfBuzzGetGlyphVerticalOrigin,
@@ -359,30 +335,26 @@ static hb_blob_t* HarfBuzzSkiaGetTable(hb_face_t* face,
WTF::Partitions::FastFree);
}
+#if !defined(OS_MACOSX)
static void DeleteTypefaceStream(void* stream_asset_ptr) {
SkStreamAsset* stream_asset =
reinterpret_cast<SkStreamAsset*>(stream_asset_ptr);
delete stream_asset;
}
+#endif
hb_face_t* HarfBuzzFace::CreateFace() {
-#if defined(OS_MACOSX)
- // hb_face_t needs to be instantiated using the CoreText constructor for
- // compatibility with AAT font, in which case HarfBuzz' CoreText backend is
- // used. If we encounter a FreeType backed SkTypeface, for variable fonts on
- // Mac OS < 10.12, follow the regular OpenType-only codepath below.
- if (platform_data_->CgFont()) {
- hb_face_t* face = hb_coretext_face_create(platform_data_->CgFont());
- DCHECK(face);
- return face;
- }
-#endif
hb_face_t* face = nullptr;
DEFINE_THREAD_SAFE_STATIC_LOCAL(BooleanHistogram, zero_copy_success_histogram,
("Blink.Fonts.HarfBuzzFaceZeroCopyAccess"));
SkTypeface* typeface = platform_data_->Typeface();
CHECK(typeface);
+ // The attempt of doing zero copy-mmaped memory access to the font blobs does
+ // not work efficiently on Mac, since what is returned from
+ // typeface->openStream is a synthesized font assembled from copying all font
+ // tables on Mac. See the implementation of SkTypeface_Mac::onOpenStream.
+#if !defined(OS_MACOSX)
int ttc_index = 0;
SkStreamAsset* typeface_stream = typeface->openStream(&ttc_index);
if (typeface_stream && typeface_stream->getMemoryBase()) {
@@ -394,6 +366,7 @@ hb_face_t* HarfBuzzFace::CreateFace() {
hb_blob_destroy);
face = hb_face_create(face_blob.get(), ttc_index);
}
+#endif
// Fallback to table copies if there is no in-memory access.
if (!face) {
@@ -435,19 +408,15 @@ static_assert(
hb_font_t* HarfBuzzFace::GetScaledFont(
scoped_refptr<UnicodeRangeSet> range_set,
VerticalLayoutCallbacks vertical_layout) const {
- PaintFont paint_font;
- platform_data_->SetupPaintFont(&paint_font);
- paint_font.SetTextEncoding(SkPaint::kGlyphID_TextEncoding);
harfbuzz_font_data_->range_set_ = std::move(range_set);
- harfbuzz_font_data_->UpdateFallbackMetricsAndScale(
- *platform_data_, paint_font.ToSkPaint(), vertical_layout);
+ harfbuzz_font_data_->UpdateFallbackMetricsAndScale(*platform_data_,
+ vertical_layout);
- int scale =
- SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(platform_data_->size());
+ int scale = SkiaScalarToHarfBuzzPosition(platform_data_->size());
hb_font_set_scale(unscaled_font_, scale, scale);
hb_font_set_ptem(unscaled_font_, platform_data_->size() / kCssPixelsPerPoint);
- SkTypeface* typeface = harfbuzz_font_data_->paint_.getTypeface();
+ SkTypeface* typeface = harfbuzz_font_data_->font_.getTypeface();
int axis_count = typeface->getVariationDesignPosition(nullptr, 0);
if (axis_count > 0) {
Vector<SkFontArguments::VariationPosition::Coordinate> axis_values;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_font_cache.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_font_cache.h
index 69fa5f128a7..f3645969638 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_font_cache.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_font_cache.h
@@ -40,7 +40,7 @@ struct HarfBuzzFontData {
public:
HarfBuzzFontData()
- : paint_(),
+ : font_(),
space_in_gpos_(SpaceGlyphInOpenTypeTables::Unknown),
space_in_gsub_(SpaceGlyphInOpenTypeTables::Unknown),
vertical_data_(nullptr),
@@ -51,19 +51,19 @@ struct HarfBuzzFontData {
// layout information is found from the font.
void UpdateFallbackMetricsAndScale(
const FontPlatformData& platform_data,
- const SkPaint& paint,
HarfBuzzFace::VerticalLayoutCallbacks vertical_layout) {
float ascent = 0;
float descent = 0;
unsigned dummy_ascent_inflation = 0;
unsigned dummy_descent_inflation = 0;
- paint_ = paint;
+ font_ = SkFont();
+ platform_data.SetupSkFont(&font_);
if (UNLIKELY(vertical_layout == HarfBuzzFace::PrepareForVerticalLayout)) {
FontMetrics::AscentDescentWithHacks(
ascent, descent, dummy_ascent_inflation, dummy_descent_inflation,
- platform_data, paint);
+ platform_data, font_);
ascent_fallback_ = ascent;
// Simulate the rounding that FontMetrics does so far for returning the
// integer Height()
@@ -87,7 +87,7 @@ struct HarfBuzzFontData {
if (size_per_unit_ != kInvalidFallbackMetricsValue)
return size_per_unit_;
int units_per_em = typeface.getUnitsPerEm();
- size_per_unit_ = paint_.getTextSize() / units_per_em;
+ size_per_unit_ = font_.getSize() / units_per_em;
return size_per_unit_;
}
@@ -98,14 +98,14 @@ struct HarfBuzzFontData {
DCHECK_NE(size_per_unit_, kInvalidFallbackMetricsValue);
vertical_data_ =
- OpenTypeVerticalData::CreateUnscaled(paint_.refTypeface());
+ OpenTypeVerticalData::CreateUnscaled(font_.refTypeface());
}
vertical_data_->SetScaleAndFallbackMetrics(size_per_unit_, ascent_fallback_,
height_fallback_);
return vertical_data_;
}
- SkPaint paint_;
+ SkFont font_;
// Capture these scaled fallback metrics from FontPlatformData so that a
// OpenTypeVerticalData object can be constructed from them when needed.
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.cc
index 8a59fbb19bc..3cef0162ce7 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.cc
@@ -39,6 +39,7 @@
#include <utility>
#include "base/memory/ptr_util.h"
+#include "build/build_config.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
#include "third_party/blink/renderer/platform/fonts/font_fallback_iterator.h"
@@ -70,8 +71,7 @@ void CheckShapeResultRange(const ShapeResult* result,
DCHECK_LE(start, end);
unsigned length = end - start;
if (length == result->NumCharacters() &&
- (!length || (start == result->StartIndexForResult() &&
- end == result->EndIndexForResult())))
+ (!length || (start == result->StartIndex() && end == result->EndIndex())))
return;
// Log font-family/size as specified.
@@ -99,8 +99,7 @@ void CheckShapeResultRange(const ShapeResult* result,
// Log the text to shape.
log.Append(String::Format(": %u-%u -> %u-%u:", start, end,
- result->StartIndexForResult(),
- result->EndIndexForResult()));
+ result->StartIndex(), result->EndIndex()));
for (unsigned i = start; i < end; ++i)
log.Append(String::Format(" %02X", text[i]));
@@ -238,14 +237,6 @@ inline bool ShapeRange(hb_buffer_t* buffer,
? HarfBuzzFace::PrepareForVerticalLayout
: HarfBuzzFace::NoVerticalLayout);
hb_shape(hb_font, buffer, font_features, font_features_size);
-
- // We cannot round all glyph positions during hb_shape because the
- // hb_font_funcs_set_glyph_h_kerning_func only works for legacy kerning.
- // OpenType uses gpos tables for kerning and harfbuzz does not call
- // the callback to let us round as we go.
- // Without this rounding, we get inconsistent spacing between kern points
- // if subpixel positioning is disabled.
- // See http://crbug.com/740385.
if (!face->ShouldSubpixelPosition())
RoundHarfBuzzBufferPositions(buffer);
@@ -336,12 +327,11 @@ void HarfBuzzShaper::CommitGlyphs(RangeData* range_data,
// Here we need to specify glyph positions.
BufferSlice next_slice;
for (const BufferSlice* current_slice = &slice;;) {
- ShapeResult::RunInfo* run = new ShapeResult::RunInfo(
+ auto run = ShapeResult::RunInfo::Create(
current_font, direction, canvas_rotation, script,
current_slice->start_character_index, current_slice->num_glyphs,
current_slice->num_characters);
- shape_result->InsertRun(base::WrapUnique(run),
- current_slice->start_glyph_index,
+ shape_result->InsertRun(run, current_slice->start_glyph_index,
current_slice->num_glyphs, range_data->buffer);
unsigned num_glyphs_inserted = run->NumGlyphs();
if (num_glyphs_inserted == current_slice->num_glyphs)
@@ -1004,9 +994,9 @@ scoped_refptr<ShapeResult> HarfBuzzShaper::Shape(
}
}
- // Ensure we have at least one run for StartIndexForResult().
- if (UNLIKELY(result->runs_.IsEmpty() && start))
- result->InsertRunForIndex(start);
+ // Ensure |start_index_| is updated even when no runs were inserted.
+ if (UNLIKELY(result->runs_.IsEmpty()))
+ result->start_index_ = start;
#if DCHECK_IS_ON()
if (result)
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper_test.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper_test.cc
index a6c267b157d..35e0d66e541 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper_test.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper_test.cc
@@ -16,11 +16,11 @@
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_test_info.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/testing/font_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
using testing::ElementsAre;
@@ -114,40 +114,40 @@ class HarfBuzzShaperTest : public testing::Test {
class ScopedSubpixelOverride {
public:
ScopedSubpixelOverride(bool b) {
- prev_layout_test_ = LayoutTestSupport::IsRunningLayoutTest();
+ prev_layout_test_ = WebTestSupport::IsRunningWebTest();
prev_subpixel_allowed_ =
- LayoutTestSupport::IsTextSubpixelPositioningAllowedForTest();
- prev_antialias_ = LayoutTestSupport::IsFontAntialiasingEnabledForTest();
+ WebTestSupport::IsTextSubpixelPositioningAllowedForTest();
+ prev_antialias_ = WebTestSupport::IsFontAntialiasingEnabledForTest();
prev_fd_subpixel_ = FontDescription::SubpixelPositioning();
- // This is required for all LayoutTestSupport settings to have effects.
- LayoutTestSupport::SetIsRunningLayoutTest(true);
+ // This is required for all WebTestSupport settings to have effects.
+ WebTestSupport::SetIsRunningWebTest(true);
if (b) {
// Allow subpixel positioning.
- LayoutTestSupport::SetTextSubpixelPositioningAllowedForTest(true);
+ WebTestSupport::SetTextSubpixelPositioningAllowedForTest(true);
// Now, enable subpixel positioning in platform-specific ways.
// Mac always enables subpixel positioning.
// On Windows, subpixel positioning also requires antialiasing.
- LayoutTestSupport::SetFontAntialiasingEnabledForTest(true);
+ WebTestSupport::SetFontAntialiasingEnabledForTest(true);
// On platforms other than Windows and Mac this needs to be set as
// well.
FontDescription::SetSubpixelPositioning(true);
} else {
// Explicitly disallow all subpixel positioning.
- LayoutTestSupport::SetTextSubpixelPositioningAllowedForTest(false);
+ WebTestSupport::SetTextSubpixelPositioningAllowedForTest(false);
}
}
~ScopedSubpixelOverride() {
FontDescription::SetSubpixelPositioning(prev_fd_subpixel_);
- LayoutTestSupport::SetFontAntialiasingEnabledForTest(prev_antialias_);
- LayoutTestSupport::SetTextSubpixelPositioningAllowedForTest(
+ WebTestSupport::SetFontAntialiasingEnabledForTest(prev_antialias_);
+ WebTestSupport::SetTextSubpixelPositioningAllowedForTest(
prev_subpixel_allowed_);
- LayoutTestSupport::SetIsRunningLayoutTest(prev_layout_test_);
+ WebTestSupport::SetIsRunningWebTest(prev_layout_test_);
// Fonts cached with a different subpixel positioning state are not
// automatically invalidated and need to be cleared between test
@@ -245,11 +245,9 @@ TEST_F(HarfBuzzShaperTest, ResolveCandidateRunsUnicodeVariants) {
// If the specified VS is not in the font, it's mapped to .notdef.
// then hb_ot_hide_default_ignorables() swaps it to a space with zero-advance.
// http://lists.freedesktop.org/archives/harfbuzz/2015-May/004888.html
-#if !defined(OS_MACOSX)
EXPECT_EQ(TestInfo(result)->FontDataForTesting(0)->SpaceGlyph(),
TestInfo(result)->GlyphForTesting(0, 1))
<< test.name;
-#endif
EXPECT_EQ(0.f, TestInfo(result)->AdvanceForTesting(0, 1)) << test.name;
} else {
EXPECT_EQ(1u, num_glyphs) << test.name;
@@ -413,8 +411,9 @@ TEST_F(HarfBuzzShaperTest, ShapeLatinSegment) {
}
// Represents the case where a part of a cluster has a different color.
-// <div>0x647<span style="color: red;">0x64A</span></div>
-// TODO(crbug.com/689155): Still fails on Mac, AAT?
+// <div>0x647<span style="color: red;">0x64A</span></
+// Cannot be enabled on Mac yet, compare
+// https:// https://github.com/harfbuzz/harfbuzz/issues/1415
#if defined(OS_MACOSX)
#define MAYBE_ShapeArabicWithContext DISABLED_ShapeArabicWithContext
#else
@@ -517,9 +516,6 @@ TEST_F(HarfBuzzShaperTest, ShapeVerticalMixed) {
HarfBuzzShaper shaper(string);
scoped_refptr<ShapeResult> result = shaper.Shape(&font, direction);
- // Check width and bounds are not too much different. ".1" is heuristic.
- EXPECT_NEAR(result->Width(), result->Bounds().Width(), result->Width() * .1);
-
// Shape each run and merge them using CopyRange. Bounds() should match.
scoped_refptr<ShapeResult> result1 = shaper.Shape(&font, direction, 0, 3);
scoped_refptr<ShapeResult> result2 =
@@ -533,15 +529,24 @@ TEST_F(HarfBuzzShaperTest, ShapeVerticalMixed) {
EXPECT_EQ(result->Bounds(), composite_result->Bounds());
}
-TEST_P(ShapeParameterTest, MissingGlyph) {
- // U+FFF0 is not assigned as of Unicode 10.0.
- String string(
- u"\uFFF0"
- u"Hello");
+class ShapeStringTest : public HarfBuzzShaperTest,
+ public testing::WithParamInterface<const char16_t*> {};
+
+INSTANTIATE_TEST_CASE_P(HarfBuzzShaperTest,
+ ShapeStringTest,
+ testing::Values(
+ // U+FFF0 is not assigned as of Unicode 10.0.
+ u"\uFFF0",
+ u"\uFFF0Hello",
+ // U+00AD SOFT HYPHEN often does not have glyphs.
+ u"\u00AD"));
+
+TEST_P(ShapeStringTest, MissingGlyph) {
+ String string(GetParam());
HarfBuzzShaper shaper(string);
- scoped_refptr<ShapeResult> result = ShapeWithParameter(&shaper);
- EXPECT_EQ(0u, result->StartIndexForResult());
- EXPECT_EQ(string.length(), result->EndIndexForResult());
+ scoped_refptr<ShapeResult> result = shaper.Shape(&font, TextDirection::kLtr);
+ EXPECT_EQ(0u, result->StartIndex());
+ EXPECT_EQ(string.length(), result->EndIndex());
}
// Test splitting runs by kMaxCharacterIndex using a simple string that has code
@@ -640,8 +645,8 @@ TEST_P(ShapeParameterTest, ZeroWidthSpace) {
const unsigned length = base::size(string);
HarfBuzzShaper shaper(String(string, length));
scoped_refptr<ShapeResult> result = ShapeWithParameter(&shaper);
- EXPECT_EQ(0u, result->StartIndexForResult());
- EXPECT_EQ(length, result->EndIndexForResult());
+ EXPECT_EQ(0u, result->StartIndex());
+ EXPECT_EQ(length, result->EndIndex());
#if DCHECK_IS_ON()
result->CheckConsistency();
#endif
@@ -717,17 +722,14 @@ static struct GlyphDataRangeTestData {
// The two code points form a grapheme cluster, which produces two glyphs.
// Character index array should be [0, 0].
{u"\u05E9\u05B0", TextDirection::kRtl, 0, 0, 1, 0, 2},
-#if !defined(OS_MACOSX)
// ZWJ tests taken from fast/text/international/zerowidthjoiner.html
// Character index array should be [6, 3, 3, 3, 0, 0, 0].
- // Mac shapes differently and that glyph index expectations do not match.
{u"\u0639\u200D\u200D\u0639\u200D\u200D\u0639", TextDirection::kRtl, 0, 0,
1, 4, 7},
{u"\u0639\u200D\u200D\u0639\u200D\u200D\u0639", TextDirection::kRtl, 0, 2,
5, 1, 4},
{u"\u0639\u200D\u200D\u0639\u200D\u200D\u0639", TextDirection::kRtl, 0, 4,
7, 0, 1},
-#endif
};
std::ostream& operator<<(std::ostream& ostream,
@@ -1106,14 +1108,14 @@ TEST_P(ShapeResultCopyRangeTest, Split) {
scoped_refptr<ShapeResult> result1 = ShapeResult::Create(&font, 0, direction);
result->CopyRange(0, test_data.break_point, result1.get());
EXPECT_EQ(test_data.break_point, result1->NumCharacters());
- EXPECT_EQ(0u, result1->StartIndexForResult());
- EXPECT_EQ(test_data.break_point, result1->EndIndexForResult());
+ EXPECT_EQ(0u, result1->StartIndex());
+ EXPECT_EQ(test_data.break_point, result1->EndIndex());
scoped_refptr<ShapeResult> result2 = ShapeResult::Create(&font, 0, direction);
result->CopyRange(test_data.break_point, string.length(), result2.get());
EXPECT_EQ(string.length() - test_data.break_point, result2->NumCharacters());
- EXPECT_EQ(test_data.break_point, result2->StartIndexForResult());
- EXPECT_EQ(string.length(), result2->EndIndexForResult());
+ EXPECT_EQ(test_data.break_point, result2->StartIndex());
+ EXPECT_EQ(string.length(), result2->EndIndex());
// Combine them.
scoped_refptr<ShapeResult> composite_result =
@@ -1301,8 +1303,8 @@ TEST_F(HarfBuzzShaperTest, SubRange) {
scoped_refptr<ShapeResult> result = shaper.Shape(&font, direction);
scoped_refptr<ShapeResult> sub_range = result->SubRange(4, 7);
- DCHECK_EQ(4u, sub_range->StartIndexForResult());
- DCHECK_EQ(7u, sub_range->EndIndexForResult());
+ DCHECK_EQ(4u, sub_range->StartIndex());
+ DCHECK_EQ(7u, sub_range->EndIndex());
DCHECK_EQ(3u, sub_range->NumCharacters());
DCHECK_EQ(result->Direction(), sub_range->Direction());
}
@@ -1399,60 +1401,59 @@ TEST_F(HarfBuzzShaperTest, SafeToBreakLatinDiscretionaryLigatures) {
"third_party/MEgalopolis/MEgalopolisExtra.woff"),
16, &ligatures);
- // RA and CA form ligatures, most glyph pairs have kerning.
- String string(u"ABRACADABRA");
- HarfBuzzShaper shaper(string);
+ // $ ./hb-shape --shaper=ot --features="dlig=1,kern" --show-flags
+ // MEgalopolisExtra.ttf "RADDAYoVaDD"
+ // [R_A=0+1150|D=2+729|D=3+699|A=4+608#1|Y=5+608#1|o=6+696#1|V=7+652#1|a=8+657#1|D=9+729|D=10+729]
+ // RA Ligature, unkerned D D, D A kerns, A Y kerns, Y o kerns, o V kerns, V a
+ // kerns, no kerning with D.
+ String test_word(u"RADDAYoVaDD");
+ unsigned safe_to_break_positions[] = {2, 3, 9, 10};
+ HarfBuzzShaper shaper(test_word);
scoped_refptr<ShapeResult> result =
shaper.Shape(&testFont, TextDirection::kLtr);
- EXPECT_EQ(6u, result->NextSafeToBreakOffset(1)); // After CA ligature.
- EXPECT_EQ(6u, result->NextSafeToBreakOffset(6)); // After CA ligature.
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(7)); // At end of string.
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(9)); // At end of string.
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(10)); // At end of string.
-
- // Add zero-width spaces at the safe to break offsets.
- String refString(u"ABRACA\u200BDAB\u200BRA");
- HarfBuzzShaper refShaper(refString);
+
+ unsigned compare_safe_to_break_position = 0;
+ for (unsigned i = 1; i < test_word.length() - 1; ++i) {
+ EXPECT_EQ(safe_to_break_positions[compare_safe_to_break_position],
+ result->NextSafeToBreakOffset(i));
+ if (i == safe_to_break_positions[compare_safe_to_break_position])
+ compare_safe_to_break_position++;
+ }
+
+ // Add zero-width spaces at some of the safe to break offsets.
+ String inserted_zero_width_spaces = test_word;
+ inserted_zero_width_spaces.Ensure16Bit();
+ unsigned enlarged_by = 0;
+ for (unsigned safe_to_break_position : safe_to_break_positions) {
+ inserted_zero_width_spaces.insert(u"\u200B",
+ safe_to_break_position + enlarged_by++);
+ }
+ HarfBuzzShaper refShaper(inserted_zero_width_spaces);
scoped_refptr<ShapeResult> referenceResult =
refShaper.Shape(&testFont, TextDirection::kLtr);
// Results should be identical if it truly is safe to break at the designated
- // safe-to-break offsets
+ // safe-to-break offsets because otherwise, the zero-width spaces would have
+ // altered the text spacing, for example by breaking apart ligatures or
+ // kerning pairs.
EXPECT_EQ(result->SnappedWidth(), referenceResult->SnappedWidth());
EXPECT_EQ(result->Bounds(), referenceResult->Bounds());
- EXPECT_EQ(result->SnappedStartPositionForOffset(0),
- referenceResult->SnappedStartPositionForOffset(0));
- EXPECT_EQ(result->SnappedStartPositionForOffset(1),
- referenceResult->SnappedStartPositionForOffset(1));
- EXPECT_EQ(result->SnappedStartPositionForOffset(2),
- referenceResult->SnappedStartPositionForOffset(2));
- EXPECT_EQ(result->SnappedStartPositionForOffset(3),
- referenceResult->SnappedStartPositionForOffset(3));
- EXPECT_EQ(result->SnappedStartPositionForOffset(4),
- referenceResult->SnappedStartPositionForOffset(4));
- EXPECT_EQ(result->SnappedStartPositionForOffset(5),
- referenceResult->SnappedStartPositionForOffset(5));
- // First zero-width space is at position 6 so the the matching character in
- // the reference results is 7.
- EXPECT_EQ(result->SnappedStartPositionForOffset(6),
- referenceResult->SnappedStartPositionForOffset(7));
- EXPECT_EQ(result->SnappedStartPositionForOffset(7),
- referenceResult->SnappedStartPositionForOffset(8));
- EXPECT_EQ(result->SnappedStartPositionForOffset(8),
- referenceResult->SnappedStartPositionForOffset(9));
-
- // Second zero-width space is at position 9 so the the matching character in
- // the reference results is 11.
- EXPECT_EQ(result->SnappedStartPositionForOffset(9),
- referenceResult->SnappedStartPositionForOffset(11));
- EXPECT_EQ(result->SnappedStartPositionForOffset(10),
- referenceResult->SnappedStartPositionForOffset(12));
+ // Zero-width spaces were inserted, so we need to account for that by
+ // offseting the index that we compare against.
+ unsigned inserts_offset = 0;
+ for (unsigned i = 0; i < test_word.length(); ++i) {
+ if (i == safe_to_break_positions[inserts_offset])
+ inserts_offset++;
+ EXPECT_EQ(
+ result->SnappedStartPositionForOffset(i),
+ referenceResult->SnappedStartPositionForOffset(i + inserts_offset));
+ }
}
-// TODO(crbug.com/870712): This test fails on Mac due to AAT shaping and
-// font fallback differences on Android.
-#if defined(OS_MACOSX) || defined(OS_ANDROID)
+// TODO(crbug.com/870712): This test fails due to font fallback differences on
+// Android.
+#if defined(OS_ANDROID)
#define MAYBE_SafeToBreakArabicCommonLigatures \
DISABLED_SafeToBreakArabicCommonLigatures
#else
@@ -1469,33 +1470,27 @@ TEST_F(HarfBuzzShaperTest, MAYBE_SafeToBreakArabicCommonLigatures) {
HarfBuzzShaper shaper(string);
scoped_refptr<ShapeResult> result = shaper.Shape(&font, TextDirection::kRtl);
- // Safe to break at 0, 3, 4, 5, 7, and 11.
- EXPECT_EQ(0u, result->NextSafeToBreakOffset(0));
- EXPECT_EQ(3u, result->NextSafeToBreakOffset(1));
- EXPECT_EQ(3u, result->NextSafeToBreakOffset(2));
- EXPECT_EQ(3u, result->NextSafeToBreakOffset(3));
- EXPECT_EQ(4u, result->NextSafeToBreakOffset(4));
- EXPECT_EQ(5u, result->NextSafeToBreakOffset(5));
- EXPECT_EQ(7u, result->NextSafeToBreakOffset(6));
- EXPECT_EQ(7u, result->NextSafeToBreakOffset(7));
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(8));
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(9));
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(10));
- EXPECT_EQ(11u, result->NextSafeToBreakOffset(11));
- EXPECT_EQ(12u, result->NextSafeToBreakOffset(12));
+ std::vector<unsigned> safe_to_break_positions;
+
+#if defined(OS_MACOSX)
+ safe_to_break_positions = {0, 2, 3, 4, 11};
+#else
+ safe_to_break_positions = {0, 3, 4, 5, 7, 11};
+#endif
+ unsigned compare_safe_to_break_position = 0;
+ for (unsigned i = 0; i < string.length() - 1; ++i) {
+ EXPECT_EQ(safe_to_break_positions[compare_safe_to_break_position],
+ result->NextSafeToBreakOffset(i));
+ if (i == safe_to_break_positions[compare_safe_to_break_position])
+ compare_safe_to_break_position++;
+ }
}
// TODO(layout-dev): Expand RTL test coverage and add tests for mixed
// directionality strings.
// Test when some characters are missing in |runs_|.
-// RTL on Mac may not have runs for all characters. crbug.com/774034
-#if defined(OS_MACOSX)
-#define MAYBE_SafeToBreakMissingRun DISABLED_SafeToBreakMissingRun
-#else
-#define MAYBE_SafeToBreakMissingRun SafeToBreakMissingRun
-#endif
-TEST_P(ShapeParameterTest, MAYBE_SafeToBreakMissingRun) {
+TEST_P(ShapeParameterTest, SafeToBreakMissingRun) {
TextDirection direction = GetParam();
scoped_refptr<ShapeResult> result = ShapeResult::Create(&font, 8, direction);
result->InsertRunForTesting(2, 1, direction, {0});
@@ -1506,8 +1501,8 @@ TEST_P(ShapeParameterTest, MAYBE_SafeToBreakMissingRun) {
result->CheckConsistency();
#endif
- EXPECT_EQ(2u, result->StartIndexForResult());
- EXPECT_EQ(10u, result->EndIndexForResult());
+ EXPECT_EQ(2u, result->StartIndex());
+ EXPECT_EQ(10u, result->EndIndex());
EXPECT_EQ(2u, result->NextSafeToBreakOffset(2));
EXPECT_EQ(3u, result->NextSafeToBreakOffset(3));
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_cache.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_cache.cc
index 3fbc1ef3978..664b1fcf3fa 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_cache.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_cache.cc
@@ -30,13 +30,17 @@
#include "third_party/blink/renderer/platform/fonts/shaping/shape_cache.h"
#include "third_party/blink/renderer/platform/wtf/string_hasher.h"
+#if defined(USE_FUNCTION_CITYHASH)
+#include "third_party/smhasher/src/City.h"
+#endif
namespace blink {
void ShapeCache::SmallStringKey::HashString() {
- // TODO(cavalcantii): replace this for a better hash function,
- // see crbug.com/735674.
- hash_ = StringHasher::ComputeHash(characters_, length_);
+// TODO(cavalcanti): next add xxhash.
+#if defined(USE_FUNCTION_CITYHASH)
+ hash_ = CityHash64((const char*)characters_, length_ * sizeof(UChar));
+#endif
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
index 1c84a168159..11ca1595552 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
@@ -39,9 +39,11 @@
#include "base/containers/adapters.h"
#include "base/memory/ptr_util.h"
+#include "base/numerics/safe_conversions.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/fonts/character_range.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_buffer.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
@@ -53,6 +55,18 @@ namespace blink {
constexpr unsigned HarfBuzzRunGlyphData::kMaxCharacterIndex;
constexpr unsigned HarfBuzzRunGlyphData::kMaxGlyphs;
+struct SameSizeAsHarfBuzzRunGlyphData {
+ uint16_t unsigned_int16;
+ unsigned bit_fields : 2;
+ int16_t signed_int16[2];
+ float advance;
+ FloatSize offset;
+};
+
+static_assert(sizeof(HarfBuzzRunGlyphData) ==
+ sizeof(SameSizeAsHarfBuzzRunGlyphData),
+ "HarfBuzzRunGlyphData should stay small");
+
unsigned ShapeResult::RunInfo::NextSafeToBreakOffset(unsigned offset) const {
DCHECK_LE(offset, num_characters_);
if (!Rtl()) {
@@ -129,7 +143,7 @@ void ShapeResult::EnsureGraphemes(const StringView& text) const {
if (is_computed)
return;
- unsigned result_start_index = StartIndexForResult();
+ unsigned result_start_index = StartIndex();
for (const auto& run : runs_) {
if (!run)
continue;
@@ -321,7 +335,8 @@ void ShapeResult::RunInfo::CharacterIndexForXPosition(
// representing a sequence of glyphs, of size glyph_sequence_advance. We
// linearly interpolate how much space each character takes, and reduce the
// sequence to only match the character size.
- if (break_glyphs_option == BreakGlyphs) {
+ if (break_glyphs_option == BreakGlyphs &&
+ glyph_sequence_end > glyph_sequence_start) {
int graphemes = NumGraphemes(glyph_sequence_start, glyph_sequence_end);
if (graphemes > 1) {
float unit_size = result->advance / graphemes;
@@ -360,9 +375,23 @@ void HarfBuzzRunGlyphData::SetGlyphAndPositions(uint16_t glyph_id,
this->advance = advance;
this->offset = offset;
this->safe_to_break_before = safe_to_break_before;
+ this->bounds_before_raw_value = std::numeric_limits<int16_t>::max();
+ this->bounds_after_raw_value = std::numeric_limits<int16_t>::max();
+}
+
+void HarfBuzzRunGlyphData::SetGlyphBounds(LayoutUnit bounds_before,
+ LayoutUnit bounds_after) {
+ this->bounds_before_raw_value =
+ base::IsValueInRangeForNumericType<int16_t>(bounds_before.RawValue())
+ ? bounds_before.RawValue()
+ : std::numeric_limits<int16_t>::max();
+ this->bounds_after_raw_value =
+ base::IsValueInRangeForNumericType<int16_t>(bounds_after.RawValue())
+ ? bounds_after.RawValue()
+ : std::numeric_limits<int16_t>::max();
}
-ShapeResult::ShapeResult(const SimpleFontData* font_data,
+ShapeResult::ShapeResult(scoped_refptr<const SimpleFontData> font_data,
unsigned num_characters,
TextDirection direction)
: width_(0),
@@ -388,7 +417,7 @@ ShapeResult::ShapeResult(const ShapeResult& other)
has_vertical_offsets_(other.has_vertical_offsets_) {
runs_.ReserveCapacity(other.runs_.size());
for (const auto& run : other.runs_)
- runs_.push_back(std::make_unique<RunInfo>(*run));
+ runs_.push_back(run->Create(*run.get()));
}
ShapeResult::~ShapeResult() = default;
@@ -438,7 +467,7 @@ unsigned ShapeResult::NextSafeToBreakOffset(unsigned index) const {
}
}
- return EndIndexForResult();
+ return EndIndex();
}
unsigned ShapeResult::PreviousSafeToBreakOffset(unsigned index) const {
@@ -464,7 +493,7 @@ unsigned ShapeResult::PreviousSafeToBreakOffset(unsigned index) const {
}
}
- return StartIndexForResult();
+ return StartIndex();
}
// If the position is outside of the result, returns the start or the end offset
@@ -710,12 +739,10 @@ float ShapeResult::ForEachGlyph(float initial_advance,
return total_advance;
}
-namespace {
-
-inline unsigned CountGraphemesInCluster(const UChar* str,
- unsigned str_length,
- uint16_t start_index,
- uint16_t end_index) {
+unsigned ShapeResult::CountGraphemesInCluster(const UChar* str,
+ unsigned str_length,
+ uint16_t start_index,
+ uint16_t end_index) {
if (start_index > end_index)
std::swap(start_index, end_index);
uint16_t length = end_index - start_index;
@@ -732,8 +759,6 @@ inline unsigned CountGraphemesInCluster(const UChar* str,
return std::max(0, num_graphemes);
}
-} // anonymous namespace
-
float ShapeResult::ForEachGraphemeClusters(const StringView& text,
float initial_advance,
unsigned from,
@@ -914,66 +939,6 @@ float HarfBuzzPositionToFloat(hb_position_t value) {
return static_cast<float>(value) / (1 << 16);
}
-// This is a helper class to accumulate glyph bounding box.
-//
-// Glyph positions and bounding boxes from HarfBuzz and fonts are in physical
-// coordinate, while ShapeResult::glyph_bounding_box_ is in logical coordinate.
-// To minimize the number of conversions, this class accumulates the bounding
-// boxes in physical coordinate, and convert the accumulated box to logical.
-struct GlyphBoundsAccumulator {
- // Construct an accumulator with the logical glyph origin.
- explicit GlyphBoundsAccumulator(float origin) : origin(origin) {}
-
- // The accumulated glyph bounding box in physical coordinate, until
- // ConvertVerticalRunToLogical().
- FloatRect bounds;
- // The current origin, in logical coordinate.
- float origin;
-
- // Unite a glyph bounding box to |bounds|.
- template <bool is_horizontal_run>
- void Unite(const HarfBuzzRunGlyphData& glyph_data,
- FloatRect bounds_for_glyph) {
- if (UNLIKELY(bounds_for_glyph.IsEmpty()))
- return;
-
- // Glyphs are drawn at |origin + offset|. Move glyph_bounds to that point.
- // All positions in hb_glyph_position_t are relative to the current point.
- // https://behdad.github.io/harfbuzz/harfbuzz-Buffers.html#hb-glyph-position-t-struct
- if (is_horizontal_run)
- bounds_for_glyph.SetX(bounds_for_glyph.X() + origin);
- else
- bounds_for_glyph.SetY(bounds_for_glyph.Y() + origin);
- bounds_for_glyph.Move(glyph_data.offset);
-
- bounds.Unite(bounds_for_glyph);
- }
-
- // Non-template version of |Unite()|, see above.
- void Unite(bool is_horizontal_run,
- const HarfBuzzRunGlyphData& glyph,
- FloatRect bounds_for_glyph) {
- is_horizontal_run ? Unite<true>(glyph, bounds_for_glyph)
- : Unite<false>(glyph, bounds_for_glyph);
- }
-
- // Convert vertical run glyph bounding box to logical. Horizontal runs do not
- // need conversions because physical and logical are the same.
- void ConvertVerticalRunToLogical(const FontMetrics& font_metrics) {
- // Convert physical glyph_bounding_box to logical.
- bounds = bounds.TransposedRect();
-
- // The glyph bounding box of a vertical run uses ideographic baseline.
- // Adjust the box Y position because the bounding box of a ShapeResult uses
- // alphabetic baseline.
- // See diagrams of base lines at
- // https://drafts.csswg.org/css-writing-modes-3/#intro-baselines
- int baseline_adjust = font_metrics.Ascent(kIdeographicBaseline) -
- font_metrics.Ascent(kAlphabeticBaseline);
- bounds.SetY(bounds.Y() + baseline_adjust);
- }
-};
-
// Checks whether it's safe to break without reshaping before the given glyph.
bool IsSafeToBreakBefore(const hb_glyph_info_t* glyph_infos,
unsigned num_glyphs,
@@ -1097,7 +1062,24 @@ void ShapeResult::ComputeGlyphPositions(ShapeResult::RunInfo* run,
float total_advance = 0.0f;
bool has_vertical_offsets = !is_horizontal_run;
+ // Get glyph bounds from Skia. It's a lot faster if we give it list of glyph
+ // IDs rather than calling it for each glyph.
+ // TODO(kojii): MacOS does not benefit from batching the Skia request due to
+ // https://bugs.chromium.org/p/skia/issues/detail?id=5328, and the cost to
+ // prepare batching, which is normally much less than the benefit of batching,
+ // is not ignorable unfortunately.
+ const SimpleFontData& current_font_data = *run->font_data_;
+ DCHECK_EQ(num_glyphs, run->glyph_data_.size());
+#if !defined(OS_MACOSX)
+ Vector<Glyph, 256> glyphs(num_glyphs);
+ for (unsigned i = 0; i < num_glyphs; i++)
+ glyphs[i] = glyph_infos[start_glyph + i].codepoint;
+ Vector<SkRect, 256> bounds_list(num_glyphs);
+ current_font_data.BoundsForGlyphs(glyphs, &bounds_list);
+#endif
+
// HarfBuzz returns result in visual order, no need to flip for RTL.
+ GlyphBoundsAccumulator bounds(width_);
for (unsigned i = 0; i < num_glyphs; ++i) {
uint16_t glyph = glyph_infos[start_glyph + i].codepoint;
const hb_glyph_position_t& pos = glyph_positions[start_glyph + i];
@@ -1119,6 +1101,17 @@ void ShapeResult::ComputeGlyphPositions(ShapeResult::RunInfo* run,
glyph_data.SetGlyphAndPositions(
glyph, character_index, advance, offset,
IsSafeToBreakBefore(glyph_infos + start_glyph, num_glyphs, i));
+
+#if defined(OS_MACOSX)
+ FloatRect glyph_bounds = current_font_data.BoundsForGlyph(glyph_data.glyph);
+#else
+ FloatRect glyph_bounds(bounds_list[i]);
+#endif
+ glyph_data.SetGlyphBounds(LayoutUnit(glyph_bounds.X()),
+ LayoutUnit(glyph_bounds.MaxX()));
+ bounds.Unite<is_horizontal_run>(glyph_data, glyph_bounds);
+ bounds.origin += advance;
+
total_advance += advance;
has_vertical_offsets |= (offset.Height() != 0);
}
@@ -1126,51 +1119,17 @@ void ShapeResult::ComputeGlyphPositions(ShapeResult::RunInfo* run,
run->width_ = std::max(0.0f, total_advance);
has_vertical_offsets_ |= has_vertical_offsets;
- ComputeGlyphBounds<is_horizontal_run>(*run);
-}
-
-template <bool is_horizontal_run>
-void ShapeResult::ComputeGlyphBounds(const ShapeResult::RunInfo& run) {
- // Skia runs much faster if we give a list of glyph ID rather than calling it
- // on each glyph.
- const SimpleFontData& current_font_data = *run.font_data_;
-#if defined(OS_MACOSX)
- // TODO(kojii): MacOS does not benefit from batching the Skia request due to
- // https://bugs.chromium.org/p/skia/issues/detail?id=5328 , and the cost to
- // prepare batching, which is normally much less than the benefit of batching,
- // is not ignorable unfortunately.
- GlyphBoundsAccumulator bounds(width_);
- for (const HarfBuzzRunGlyphData& glyph_data : run.glyph_data_) {
- bounds.Unite<is_horizontal_run>(
- glyph_data, current_font_data.BoundsForGlyph(glyph_data.glyph));
- bounds.origin += glyph_data.advance;
- }
-#else
- unsigned num_glyphs = run.glyph_data_.size();
- Vector<Glyph, 256> glyphs(num_glyphs);
- for (unsigned i = 0; i < num_glyphs; i++)
- glyphs[i] = run.glyph_data_[i].glyph;
- Vector<SkRect, 256> bounds_list(num_glyphs);
- current_font_data.BoundsForGlyphs(glyphs, &bounds_list);
-
- GlyphBoundsAccumulator bounds(width_);
- for (unsigned i = 0; i < num_glyphs; i++) {
- const HarfBuzzRunGlyphData& glyph_data = run.glyph_data_[i];
- bounds.Unite<is_horizontal_run>(glyph_data, FloatRect(bounds_list[i]));
- bounds.origin += glyph_data.advance;
- }
-#endif
if (!is_horizontal_run)
bounds.ConvertVerticalRunToLogical(current_font_data.GetFontMetrics());
glyph_bounding_box_.Unite(bounds.bounds);
}
-void ShapeResult::InsertRun(std::unique_ptr<ShapeResult::RunInfo> run_to_insert,
+void ShapeResult::InsertRun(scoped_refptr<ShapeResult::RunInfo> run_to_insert,
unsigned start_glyph,
unsigned num_glyphs,
hb_buffer_t* harfbuzz_buffer) {
DCHECK_GT(num_glyphs, 0u);
- std::unique_ptr<ShapeResult::RunInfo> run(std::move(run_to_insert));
+ scoped_refptr<ShapeResult::RunInfo> run(std::move(run_to_insert));
if (run->IsHorizontal()) {
// Inserting a horizontal run into a horizontal or vertical result. In both
@@ -1190,7 +1149,7 @@ void ShapeResult::InsertRun(std::unique_ptr<ShapeResult::RunInfo> run_to_insert,
InsertRun(std::move(run));
}
-void ShapeResult::InsertRun(std::unique_ptr<ShapeResult::RunInfo> run) {
+void ShapeResult::InsertRun(scoped_refptr<ShapeResult::RunInfo> run) {
// The runs are stored in result->m_runs in visual order. For LTR, we place
// the run to be inserted before the next run with a bigger character
// start index. For RTL, we place the run before the next run with a lower
@@ -1219,24 +1178,12 @@ void ShapeResult::InsertRun(std::unique_ptr<ShapeResult::RunInfo> run) {
UpdateStartIndex();
}
-// Insert a |RunInfo| without glyphs. |StartIndexForResult()| needs a run to
-// compute the start character index. When all glyphs are missing, this function
-// synthesize a run without glyphs.
-void ShapeResult::InsertRunForIndex(unsigned start_character_index) {
- DCHECK(runs_.IsEmpty());
- runs_.push_back(std::make_unique<RunInfo>(
- primary_font_.get(), !Rtl() ? HB_DIRECTION_LTR : HB_DIRECTION_RTL,
- CanvasRotationInVertical::kRegular, HB_SCRIPT_UNKNOWN,
- start_character_index, 0, num_characters_));
- UpdateStartIndex();
-}
-
ShapeResult::RunInfo* ShapeResult::InsertRunForTesting(
unsigned start_index,
unsigned num_characters,
TextDirection direction,
Vector<uint16_t> safe_break_offsets) {
- std::unique_ptr<RunInfo> run = std::make_unique<ShapeResult::RunInfo>(
+ auto run = RunInfo::Create(
nullptr, IsLtr(direction) ? HB_DIRECTION_LTR : HB_DIRECTION_RTL,
CanvasRotationInVertical::kRegular, HB_SCRIPT_COMMON, start_index,
num_characters, num_characters);
@@ -1264,7 +1211,7 @@ void ShapeResult::ReorderRtlRuns(unsigned run_size_before) {
if (runs_.size() == run_size_before + 1) {
if (!run_size_before)
return;
- std::unique_ptr<RunInfo> new_run(std::move(runs_.back()));
+ scoped_refptr<RunInfo> new_run(std::move(runs_.back()));
runs_.Shrink(runs_.size() - 1);
runs_.push_front(std::move(new_run));
return;
@@ -1272,7 +1219,7 @@ void ShapeResult::ReorderRtlRuns(unsigned run_size_before) {
// |push_front| is O(n) that we should not call it multiple times.
// Create a new list in the correct order and swap it.
- Vector<std::unique_ptr<RunInfo>> new_runs;
+ Vector<scoped_refptr<RunInfo>> new_runs;
new_runs.ReserveInitialCapacity(runs_.size());
for (unsigned i = run_size_before; i < runs_.size(); i++)
new_runs.push_back(std::move(runs_[i]));
@@ -1346,7 +1293,8 @@ float ShapeResult::LineRightBounds() const {
void ShapeResult::CopyRange(unsigned start_offset,
unsigned end_offset,
- ShapeResult* target) const {
+ ShapeResult* target,
+ unsigned* start_run_index) const {
if (!runs_.size())
return;
@@ -1356,13 +1304,15 @@ void ShapeResult::CopyRange(unsigned start_offset,
// When |target| is empty, its character indexes are the specified sub range
// of |this|. Otherwise the character indexes are renumbered to be continuous.
- int index_diff = !target->num_characters_
- ? 0
- : target->EndIndexForResult() -
- std::max(start_offset, StartIndexForResult());
+ int index_diff =
+ !target->num_characters_
+ ? 0
+ : target->EndIndex() - std::max(start_offset, StartIndex());
unsigned target_run_size_before = target->runs_.size();
float total_width = 0;
- for (const auto& run : runs_) {
+ unsigned run_index = start_run_index ? *start_run_index : 0;
+ for (; run_index < runs_.size(); run_index++) {
+ const auto& run = runs_[run_index];
unsigned run_start = run->start_index_;
unsigned run_end = run_start + run->num_characters_;
@@ -1377,6 +1327,14 @@ void ShapeResult::CopyRange(unsigned start_offset,
target->num_characters_ += sub_run->num_characters_;
target->num_glyphs_ += sub_run->glyph_data_.size();
target->runs_.push_back(std::move(sub_run));
+
+ // No need to process runs after the end of the range.
+ if ((!Rtl() && end_offset <= run_end) ||
+ (Rtl() && start_offset > run_start)) {
+ if (start_run_index)
+ *start_run_index = run_index;
+ break;
+ }
}
}
@@ -1397,8 +1355,8 @@ void ShapeResult::CopyRange(unsigned start_offset,
// operations. If |start_offset| or |end_offset| are the start/end of |this|,
// use the current |glyph_bounding_box_| for the side.
DCHECK(primary_font_.get() == target->primary_font_.get());
- bool know_left_edge = start_offset <= StartIndexForResult();
- bool know_right_edge = end_offset >= EndIndexForResult();
+ bool know_left_edge = start_offset <= StartIndex();
+ bool know_right_edge = end_offset >= EndIndex();
if (UNLIKELY(Rtl()))
std::swap(know_left_edge, know_right_edge);
float left = know_left_edge ? target->width_ + glyph_bounding_box_.X()
@@ -1416,19 +1374,21 @@ void ShapeResult::CopyRange(unsigned start_offset,
target->UpdateStartIndex();
#if DCHECK_IS_ON()
- DCHECK_EQ(target->num_characters_ - target_num_characters_before,
- std::min(end_offset, EndIndexForResult()) -
- std::max(start_offset, StartIndexForResult()));
+ DCHECK_EQ(
+ target->num_characters_ - target_num_characters_before,
+ std::min(end_offset, EndIndex()) - std::max(start_offset, StartIndex()));
target->CheckConsistency();
#endif
}
-scoped_refptr<ShapeResult> ShapeResult::SubRange(unsigned start_offset,
- unsigned end_offset) const {
+scoped_refptr<ShapeResult> ShapeResult::SubRange(
+ unsigned start_offset,
+ unsigned end_offset,
+ unsigned* start_run_index) const {
scoped_refptr<ShapeResult> sub_range =
Create(primary_font_.get(), 0, Direction());
- CopyRange(start_offset, end_offset, sub_range.get());
+ CopyRange(start_offset, end_offset, sub_range.get(), start_run_index);
return sub_range;
}
@@ -1436,12 +1396,12 @@ scoped_refptr<ShapeResult> ShapeResult::CopyAdjustedOffset(
unsigned start_index) const {
scoped_refptr<ShapeResult> result = base::AdoptRef(new ShapeResult(*this));
- if (start_index > result->StartIndexForResult()) {
- unsigned delta = start_index - result->StartIndexForResult();
+ if (start_index > result->StartIndex()) {
+ unsigned delta = start_index - result->StartIndex();
for (auto& run : result->runs_)
run->start_index_ += delta;
} else {
- unsigned delta = result->StartIndexForResult() - start_index;
+ unsigned delta = result->StartIndex() - start_index;
for (auto& run : result->runs_) {
DCHECK(run->start_index_ >= delta);
run->start_index_ -= delta;
@@ -1461,7 +1421,7 @@ void ShapeResult::CheckConsistency() const {
}
DCHECK_EQ(start_index_, ComputeStartIndex());
- const unsigned start_index = StartIndexForResult();
+ const unsigned start_index = StartIndex();
unsigned index = start_index;
unsigned num_glyphs = 0;
if (!Rtl()) {
@@ -1480,7 +1440,7 @@ void ShapeResult::CheckConsistency() const {
num_glyphs += run->glyph_data_.size();
}
}
- const unsigned end_index = EndIndexForResult();
+ const unsigned end_index = EndIndex();
DCHECK_LE(index, end_index);
DCHECK_EQ(end_index - start_index, num_characters_);
DCHECK_EQ(num_glyphs, num_glyphs_);
@@ -1495,7 +1455,7 @@ scoped_refptr<ShapeResult> ShapeResult::CreateForTabulationCharacters(
const SimpleFontData* font_data = font->PrimaryFont();
// Tab characters are always LTR or RTL, not TTB, even when
// isVerticalAnyUpright().
- std::unique_ptr<ShapeResult::RunInfo> run = std::make_unique<RunInfo>(
+ scoped_refptr<ShapeResult::RunInfo> run = RunInfo::Create(
font_data, text_run.Rtl() ? HB_DIRECTION_RTL : HB_DIRECTION_LTR,
CanvasRotationInVertical::kRegular, HB_SCRIPT_COMMON, 0, count, count);
float position = text_run.XPos() + position_offset;
@@ -1573,7 +1533,7 @@ std::ostream& operator<<(std::ostream& ostream,
template <bool rtl>
void ShapeResult::ComputePositionData() const {
auto& data = character_position_->data_;
- unsigned start_offset = StartIndexForResult();
+ unsigned start_offset = StartIndex();
unsigned next_character_index = 0;
float run_advance = 0;
float last_x_position = 0;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.h
index 214f2567f75..72e7d4ee9f9 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result.h
@@ -34,14 +34,16 @@
#include <memory>
#include "third_party/blink/renderer/platform/fonts/canvas_rotation_in_vertical.h"
#include "third_party/blink/renderer/platform/fonts/glyph.h"
+#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
+#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
struct hb_buffer_t;
@@ -52,8 +54,8 @@ struct CharacterRange;
class Font;
template <typename TextContainerType>
class PLATFORM_EXPORT ShapeResultSpacing;
-class SimpleFontData;
class TextRun;
+class ShapeResultView;
enum class AdjustMidCluster {
// Adjust the middle of a grapheme cluster to the logical end boundary.
@@ -142,8 +144,8 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
float start_x = 0) const;
// The character start/end index of a range shape result.
- unsigned StartIndexForResult() const { return start_index_; }
- unsigned EndIndexForResult() const { return start_index_ + num_characters_; }
+ unsigned StartIndex() const { return start_index_; }
+ unsigned EndIndex() const { return start_index_ + num_characters_; }
void FallbackFonts(HashSet<const SimpleFontData*>*) const;
TextDirection Direction() const {
return static_cast<TextDirection>(direction_);
@@ -162,12 +164,12 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
// Returns the next or previous offsets respectively at which it is safe to
// break without reshaping.
// The |offset| given and the return value is for the original string, between
- // |StartIndexForResult| and |EndIndexForResult|.
+ // |StartIndex| and |EndIndex|.
// TODO(eae): Remove these ones the cached versions are used everywhere.
unsigned NextSafeToBreakOffset(unsigned offset) const;
unsigned PreviousSafeToBreakOffset(unsigned offset) const;
- // Returns the offset, relative to StartIndexForResult, whose (origin,
+ // Returns the offset, relative to StartIndex, whose (origin,
// origin+advance) contains |x|.
unsigned OffsetForPosition(float x, BreakGlyphsOption) const;
// Returns the offset whose glyph boundary is nearest to |x|. Depends on
@@ -194,7 +196,7 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
return CaretOffsetForHitTest(x, text, break_glyphs_option);
}
- // Returns the position for a given offset, relative to StartIndexForResult.
+ // Returns the position for a given offset, relative to StartIndex.
float PositionForOffset(unsigned offset,
AdjustMidCluster = AdjustMidCluster::kToEnd) const;
// Similar to |PositionForOffset| with mid-glyph (mid-ligature) support.
@@ -222,7 +224,7 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
// break without reshaping. Operates on a cache (that needs to be pre-computed
// using EnsurePositionData) and does not take partial glyphs into account.
// The |offset| given and the return value is for the original string, between
- // |StartIndexForResult| and |EndIndexForResult|.
+ // |StartIndex| and |EndIndex|.
unsigned CachedNextSafeToBreakOffset(unsigned offset) const;
unsigned CachedPreviousSafeToBreakOffset(unsigned offset) const;
@@ -230,17 +232,33 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
// configured to |ShapeResultSpacing|.
// |text_start_offset| adjusts the character index in the ShapeResult before
// giving it to |ShapeResultSpacing|. It can be negative if
- // |StartIndexForResult()| is larger than the text in |ShapeResultSpacing|.
+ // |StartIndex()| is larger than the text in |ShapeResultSpacing|.
void ApplySpacing(ShapeResultSpacing<String>&, int text_start_offset = 0);
scoped_refptr<ShapeResult> ApplySpacingToCopy(ShapeResultSpacing<TextRun>&,
const TextRun&) const;
// Append a copy of a range within an existing result to another result.
- void CopyRange(unsigned start, unsigned end, ShapeResult*) const;
+ //
+ // For sequential copies the opaque_context in/out parameter can be used to
+ // improve performance by avoding a linear scan to find the first run for the
+ // range. It should be set to zero for the first call and the resulting out
+ // value for one call is the appropiate input value for the next.
+ // NOTE: opaque_context assumes non-overlapping ranges.
+ void CopyRange(unsigned start,
+ unsigned end,
+ ShapeResult*,
+ unsigned* opaque_context = nullptr) const;
// Create a new ShapeResult instance from a range within an existing result.
+ //
+ // For sequential copies the opaque_context in/out parameter can be used to
+ // improve performance by avoding a linear scan to find the first run for the
+ // range. It should be set to zero for the first call and the resulting out
+ // value for one call is the appropiate input value for the next.
+ // NOTE: opaque_context assumes non-overlapping ranges.
scoped_refptr<ShapeResult> SubRange(unsigned start_offset,
- unsigned end_offset) const;
+ unsigned end_offset,
+ unsigned* opaque_context = nullptr) const;
// Create a new ShapeResult instance with the start offset adjusted.
scoped_refptr<ShapeResult> CopyAdjustedOffset(unsigned start_offset) const;
@@ -298,7 +316,9 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
#endif
protected:
- ShapeResult(const SimpleFontData*, unsigned num_characters, TextDirection);
+ ShapeResult(scoped_refptr<const SimpleFontData>,
+ unsigned num_characters,
+ TextDirection);
ShapeResult(const Font*, unsigned num_characters, TextDirection);
ShapeResult(const ShapeResult&);
@@ -313,6 +333,11 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
// |grapheme_| is computed.
void EnsureGraphemes(const StringView& text) const;
+ static unsigned CountGraphemesInCluster(const UChar*,
+ unsigned str_length,
+ uint16_t start_index,
+ uint16_t end_index);
+
struct GlyphIndexResult {
STACK_ALLOCATED();
@@ -382,14 +407,11 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
unsigned start_glyph,
unsigned num_glyphs,
hb_buffer_t*);
- template <bool is_horizontal_run>
- void ComputeGlyphBounds(const ShapeResult::RunInfo&);
- void InsertRun(std::unique_ptr<ShapeResult::RunInfo>,
+ void InsertRun(scoped_refptr<ShapeResult::RunInfo>,
unsigned start_glyph,
unsigned num_glyphs,
hb_buffer_t*);
- void InsertRun(std::unique_ptr<ShapeResult::RunInfo>);
- void InsertRunForIndex(unsigned start_character_index);
+ void InsertRun(scoped_refptr<ShapeResult::RunInfo>);
void ReorderRtlRuns(unsigned run_size_before);
unsigned ComputeStartIndex() const;
void UpdateStartIndex();
@@ -399,7 +421,7 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
float width_;
FloatRect glyph_bounding_box_;
- Vector<std::unique_ptr<RunInfo>> runs_;
+ Vector<scoped_refptr<RunInfo>> runs_;
scoped_refptr<const SimpleFontData> primary_font_;
mutable std::unique_ptr<CharacterPositionData> character_position_;
@@ -418,6 +440,7 @@ class PLATFORM_EXPORT ShapeResult : public RefCounted<ShapeResult> {
friend class HarfBuzzShaper;
friend class ShapeResultBuffer;
friend class ShapeResultBloberizer;
+ friend class ShapeResultView;
};
PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, const ShapeResult&);
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.cc
index d9dc7285a07..2e03906ae6a 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.cc
@@ -8,6 +8,7 @@
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/shaping/caching_word_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/fonts/text_run_paint_info.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
@@ -39,15 +40,14 @@ void ShapeResultBloberizer::CommitPendingRun() {
builder_rotation_ = pending_canvas_rotation_;
}
- PaintFont run_font;
- run_font.SetTextEncoding(SkPaint::kGlyphID_TextEncoding);
- pending_font_data_->PlatformData().SetupPaintFont(
- &run_font, device_scale_factor_, &font_);
+ SkFont run_font;
+ pending_font_data_->PlatformData().SetupSkFont(&run_font,
+ device_scale_factor_, &font_);
const auto run_size = pending_glyphs_.size();
const auto& buffer = HasPendingVerticalOffsets()
- ? builder_.AllocRunPos(run_font, run_size)
- : builder_.AllocRunPosH(run_font, run_size, 0);
+ ? builder_.allocRunPos(run_font, run_size)
+ : builder_.allocRunPosH(run_font, run_size, 0);
std::copy(pending_glyphs_.begin(), pending_glyphs_.end(), buffer.glyphs);
std::copy(pending_offsets_.begin(), pending_offsets_.end(), buffer.pos);
@@ -61,7 +61,7 @@ void ShapeResultBloberizer::CommitPendingBlob() {
if (!builder_run_count_)
return;
- blobs_.emplace_back(builder_.TakeTextBlob(), builder_rotation_);
+ blobs_.emplace_back(builder_.make(), builder_rotation_);
builder_run_count_ = 0;
}
@@ -74,54 +74,6 @@ const ShapeResultBloberizer::BlobBuffer& ShapeResultBloberizer::Blobs() {
return blobs_;
}
-float ShapeResultBloberizer::FillGlyphs(
- const TextRunPaintInfo& run_info,
- const ShapeResultBuffer& result_buffer) {
- if (CanUseFastPath(run_info.from, run_info.to, run_info.run.length(),
- result_buffer.HasVerticalOffsets())) {
- return FillFastHorizontalGlyphs(result_buffer, run_info.run.Direction());
- }
-
- float advance = 0;
- auto results = result_buffer.results_;
-
- if (run_info.run.Rtl()) {
- unsigned word_offset = run_info.run.length();
- for (unsigned j = 0; j < results.size(); j++) {
- unsigned resolved_index = results.size() - 1 - j;
- const scoped_refptr<const ShapeResult>& word_result = results[resolved_index];
- word_offset -= word_result->NumCharacters();
- advance =
- FillGlyphsForResult(word_result.get(), run_info.run.ToStringView(),
- run_info.from, run_info.to, advance, word_offset);
- }
- } else {
- unsigned word_offset = 0;
- for (const auto& word_result : results) {
- advance =
- FillGlyphsForResult(word_result.get(), run_info.run.ToStringView(),
- run_info.from, run_info.to, advance, word_offset);
- word_offset += word_result->NumCharacters();
- }
- }
-
- return advance;
-}
-
-float ShapeResultBloberizer::FillGlyphs(const StringView& text,
- unsigned from,
- unsigned to,
- const ShapeResult* result) {
- DCHECK(result);
- DCHECK(to <= text.length());
- if (CanUseFastPath(from, to, result))
- return FillFastHorizontalGlyphs(result);
-
- float advance = 0;
- float word_offset = 0;
- return FillGlyphsForResult(result, text, from, to, advance, word_offset);
-}
-
namespace {
inline bool IsSkipInkException(const ShapeResultBloberizer& bloberizer,
@@ -205,6 +157,19 @@ void AddFastHorizontalGlyphToBloberizer(
advance + glyph_offset.Width());
}
+float FillGlyphsForResult(ShapeResultBloberizer* bloberizer,
+ const ShapeResult* result,
+ const StringView& text,
+ unsigned from,
+ unsigned to,
+ float initial_advance,
+ unsigned run_offset) {
+ GlyphCallbackContext context = {bloberizer, text};
+ return result->ForEachGlyph(initial_advance, from, to, run_offset,
+ AddGlyphToBloberizer,
+ static_cast<void*>(&context));
+}
+
class ClusterCallbackContext {
WTF_MAKE_NONCOPYABLE(ClusterCallbackContext);
STACK_ALLOCATED();
@@ -250,6 +215,63 @@ void AddEmphasisMarkToBloberizer(void* context,
} // namespace
+float ShapeResultBloberizer::FillGlyphs(
+ const TextRunPaintInfo& run_info,
+ const ShapeResultBuffer& result_buffer) {
+ if (CanUseFastPath(run_info.from, run_info.to, run_info.run.length(),
+ result_buffer.HasVerticalOffsets())) {
+ return FillFastHorizontalGlyphs(result_buffer, run_info.run.Direction());
+ }
+
+ float advance = 0;
+ auto results = result_buffer.results_;
+
+ if (run_info.run.Rtl()) {
+ unsigned word_offset = run_info.run.length();
+ for (unsigned j = 0; j < results.size(); j++) {
+ unsigned resolved_index = results.size() - 1 - j;
+ const scoped_refptr<const ShapeResult>& word_result =
+ results[resolved_index];
+ word_offset -= word_result->NumCharacters();
+ advance = FillGlyphsForResult(this, word_result.get(),
+ run_info.run.ToStringView(), run_info.from,
+ run_info.to, advance, word_offset);
+ }
+ } else {
+ unsigned word_offset = 0;
+ for (const auto& word_result : results) {
+ advance = FillGlyphsForResult(this, word_result.get(),
+ run_info.run.ToStringView(), run_info.from,
+ run_info.to, advance, word_offset);
+ word_offset += word_result->NumCharacters();
+ }
+ }
+
+ return advance;
+}
+
+float ShapeResultBloberizer::FillGlyphs(const StringView& text,
+ unsigned from,
+ unsigned to,
+ const ShapeResultView* result) {
+ DCHECK(result);
+ DCHECK(to <= text.length());
+ float initial_advance = 0;
+ if (CanUseFastPath(from, to, result)) {
+ DCHECK(!result->HasVerticalOffsets());
+ DCHECK_NE(GetType(), ShapeResultBloberizer::Type::kTextIntercepts);
+ return result->ForEachGlyph(initial_advance,
+ &AddFastHorizontalGlyphToBloberizer,
+ static_cast<void*>(this));
+ }
+
+ float run_offset = 0;
+ GlyphCallbackContext context = {this, text};
+ return result->ForEachGlyph(initial_advance, from, to, run_offset,
+ AddGlyphToBloberizer,
+ static_cast<void*>(&context));
+}
+
void ShapeResultBloberizer::FillTextEmphasisGlyphs(
const TextRunPaintInfo& run_info,
const GlyphData& emphasis,
@@ -286,11 +308,12 @@ void ShapeResultBloberizer::FillTextEmphasisGlyphs(
}
}
-void ShapeResultBloberizer::FillTextEmphasisGlyphs(const StringView& text,
- unsigned from,
- unsigned to,
- const GlyphData& emphasis,
- const ShapeResult* result) {
+void ShapeResultBloberizer::FillTextEmphasisGlyphs(
+ const StringView& text,
+ unsigned from,
+ unsigned to,
+ const GlyphData& emphasis,
+ const ShapeResultView* result) {
FloatPoint glyph_center =
emphasis.font_data->BoundsForGlyph(emphasis.glyph).Center();
ClusterCallbackContext context = {this, text, emphasis, glyph_center};
@@ -301,18 +324,6 @@ void ShapeResultBloberizer::FillTextEmphasisGlyphs(const StringView& text,
static_cast<void*>(&context));
}
-float ShapeResultBloberizer::FillGlyphsForResult(const ShapeResult* result,
- const StringView& text,
- unsigned from,
- unsigned to,
- float initial_advance,
- unsigned run_offset) {
- GlyphCallbackContext context = {this, text};
- return result->ForEachGlyph(initial_advance, from, to, run_offset,
- AddGlyphToBloberizer,
- static_cast<void*>(&context));
-}
-
bool ShapeResultBloberizer::CanUseFastPath(unsigned from,
unsigned to,
unsigned length,
@@ -321,11 +332,11 @@ bool ShapeResultBloberizer::CanUseFastPath(unsigned from,
GetType() != ShapeResultBloberizer::Type::kTextIntercepts;
}
-bool ShapeResultBloberizer::CanUseFastPath(unsigned from,
- unsigned to,
- const ShapeResult* shape_result) {
- return from <= shape_result->StartIndexForResult() &&
- to >= shape_result->EndIndexForResult() &&
+bool ShapeResultBloberizer::CanUseFastPath(
+ unsigned from,
+ unsigned to,
+ const ShapeResultView* shape_result) {
+ return from <= shape_result->StartIndex() && to >= shape_result->EndIndex() &&
!shape_result->HasVerticalOffsets() &&
GetType() != ShapeResultBloberizer::Type::kTextIntercepts;
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.h
index 86cbcac380a..218321934a9 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_bloberizer.h
@@ -7,7 +7,6 @@
#include "third_party/blink/renderer/platform/fonts/canvas_rotation_in_vertical.h"
#include "third_party/blink/renderer/platform/fonts/glyph.h"
-#include "third_party/blink/renderer/platform/fonts/paint_text_blob.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_buffer.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
@@ -38,7 +37,7 @@ class PLATFORM_EXPORT ShapeResultBloberizer {
float FillGlyphs(const StringView&,
unsigned from,
unsigned to,
- const ShapeResult*);
+ const ShapeResultView*);
void FillTextEmphasisGlyphs(const TextRunPaintInfo&,
const GlyphData& emphasis_data,
const ShapeResultBuffer&);
@@ -46,7 +45,7 @@ class PLATFORM_EXPORT ShapeResultBloberizer {
unsigned from,
unsigned to,
const GlyphData& emphasis_data,
- const ShapeResult*);
+ const ShapeResultView*);
void Add(Glyph glyph,
const SimpleFontData* font_data,
CanvasRotationInVertical canvas_rotation,
@@ -93,9 +92,9 @@ class PLATFORM_EXPORT ShapeResultBloberizer {
}
struct BlobInfo {
- BlobInfo(scoped_refptr<PaintTextBlob> b, CanvasRotationInVertical r)
+ BlobInfo(sk_sp<SkTextBlob> b, CanvasRotationInVertical r)
: blob(std::move(b)), rotation(r) {}
- scoped_refptr<PaintTextBlob> blob;
+ sk_sp<SkTextBlob> blob;
CanvasRotationInVertical rotation;
};
@@ -105,20 +104,13 @@ class PLATFORM_EXPORT ShapeResultBloberizer {
private:
friend class ShapeResultBloberizerTestInfo;
- float FillGlyphsForResult(const ShapeResult*,
- const StringView&,
- unsigned from,
- unsigned to,
- float initial_advance,
- unsigned run_offset);
-
// Whether the FillFastHorizontalGlyphs can be used. Only applies for full
// runs with no vertical offsets and no text intercepts.
bool CanUseFastPath(unsigned from,
unsigned to,
unsigned length,
bool has_vertical_offsets);
- bool CanUseFastPath(unsigned from, unsigned to, const ShapeResult*);
+ bool CanUseFastPath(unsigned from, unsigned to, const ShapeResultView*);
float FillFastHorizontalGlyphs(const ShapeResultBuffer&, TextDirection);
float FillFastHorizontalGlyphs(const ShapeResult*, float advance = 0);
@@ -132,7 +124,7 @@ class PLATFORM_EXPORT ShapeResultBloberizer {
const Type type_;
// Current text blob state.
- PaintTextBlobBuilder builder_;
+ SkTextBlobBuilder builder_;
CanvasRotationInVertical builder_rotation_ =
CanvasRotationInVertical::kRegular;
size_t builder_run_count_ = 0;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h
index 4ad56a56899..4ad568d79e8 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h
@@ -55,6 +55,12 @@ struct HarfBuzzRunGlyphData {
uint16_t glyph;
unsigned character_index : kCharacterIndexBits;
unsigned safe_to_break_before : 1;
+
+ // LayoutUnit like fixed-point values, with 6 fractional and 10 integear bits.
+ // Can represent values between -1023.98 and 1023.96 which should be enough in
+ // the vast majority of cases. Max value is reserved to indicate invalid.
+ int16_t bounds_before_raw_value;
+ int16_t bounds_after_raw_value;
float advance;
FloatSize offset;
@@ -63,12 +69,43 @@ struct HarfBuzzRunGlyphData {
float advance,
const FloatSize& offset,
bool safe_to_break_before);
+ void SetGlyphBounds(LayoutUnit bounds_before, LayoutUnit bounds_after);
+ bool HasValidGlyphBounds() const {
+ return bounds_before_raw_value != std::numeric_limits<int16_t>::max() &&
+ bounds_after_raw_value != std::numeric_limits<int16_t>::max();
+ }
+
+ LayoutUnit GlyphBoundsBefore() const {
+ LayoutUnit bounds;
+ bounds.SetRawValue(static_cast<int>(bounds_before_raw_value));
+ return bounds;
+ }
+ LayoutUnit GlyphBoundsAfter() const {
+ LayoutUnit bounds;
+ bounds.SetRawValue(static_cast<int>(bounds_after_raw_value));
+ return bounds;
+ }
};
-struct ShapeResult::RunInfo {
+struct ShapeResult::RunInfo : public RefCounted<ShapeResult::RunInfo> {
USING_FAST_MALLOC(RunInfo);
public:
+ static scoped_refptr<RunInfo> Create(const SimpleFontData* font,
+ hb_direction_t dir,
+ CanvasRotationInVertical canvas_rotation,
+ hb_script_t script,
+ unsigned start_index,
+ unsigned num_glyphs,
+ unsigned num_characters) {
+ return base::AdoptRef(new RunInfo(font, dir, canvas_rotation, script,
+ start_index, num_glyphs, num_characters));
+ }
+
+ static scoped_refptr<RunInfo> Create(const RunInfo& other) {
+ return base::AdoptRef(new RunInfo(other));
+ }
+
RunInfo(const SimpleFontData* font,
hb_direction_t dir,
CanvasRotationInVertical canvas_rotation,
@@ -171,16 +208,16 @@ struct ShapeResult::RunInfo {
}
// Creates a new RunInfo instance representing a subset of the current run.
- std::unique_ptr<RunInfo> CreateSubRun(unsigned start, unsigned end) {
+ scoped_refptr<RunInfo> CreateSubRun(unsigned start, unsigned end) {
DCHECK(end > start);
unsigned number_of_characters = std::min(end - start, num_characters_);
auto glyphs = FindGlyphDataRange(start, end);
unsigned number_of_glyphs =
static_cast<unsigned>(std::distance(glyphs.begin, glyphs.end));
- auto run = std::make_unique<RunInfo>(
- font_data_.get(), direction_, canvas_rotation_, script_,
- start_index_ + start, number_of_glyphs, number_of_characters);
+ auto run =
+ Create(font_data_.get(), direction_, canvas_rotation_, script_,
+ start_index_ + start, number_of_glyphs, number_of_characters);
static_assert(base::is_trivially_copyable<HarfBuzzRunGlyphData>::value,
"HarfBuzzRunGlyphData should be trivially copyable");
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc
new file mode 100644
index 00000000000..fad054902a6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc
@@ -0,0 +1,472 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
+
+#include <iterator>
+#include "base/containers/adapters.h"
+#include "third_party/blink/renderer/platform/fonts/font.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h"
+
+namespace blink {
+
+struct ShapeResultView::RunInfoPart {
+ USING_FAST_MALLOC(RunInfoPart);
+
+ public:
+ RunInfoPart(scoped_refptr<ShapeResult::RunInfo> run,
+ ShapeResult::RunInfo::GlyphDataRange range,
+ unsigned start_index,
+ unsigned offset,
+ unsigned num_characters,
+ float width)
+ : run_(run),
+ range_(range),
+ start_index_(start_index),
+ offset_(offset),
+ num_characters_(num_characters),
+ width_(width) {}
+
+ using const_iterator = const HarfBuzzRunGlyphData*;
+ const_iterator begin() const { return range_.begin; }
+ const_iterator end() const { return range_.end; }
+ using const_reverse_iterator = std::reverse_iterator<const_iterator>;
+ const_reverse_iterator rbegin() const {
+ return const_reverse_iterator(end());
+ }
+ const_reverse_iterator rend() const {
+ return const_reverse_iterator(begin());
+ }
+ const HarfBuzzRunGlyphData& GlyphAt(unsigned index) const {
+ return *(range_.begin + index);
+ }
+
+ bool Rtl() const { return run_->Rtl(); }
+ bool IsHorizontal() const { return run_->IsHorizontal(); }
+ unsigned NumCharacters() const { return num_characters_; }
+ unsigned NumGlyphs() const { return range_.end - range_.begin; }
+ float Width() const { return width_; }
+
+ unsigned PreviousSafeToBreakOffset(unsigned offset) const;
+ size_t GlyphToCharacterIndex(size_t i) const {
+ return run_->GlyphToCharacterIndex(i);
+ }
+
+ scoped_refptr<ShapeResult::RunInfo> run_;
+ ShapeResult::RunInfo::GlyphDataRange range_;
+
+ // Start index for partial run, adjusted to ensure that runs are continuous.
+ unsigned start_index_;
+
+ // Offset relative to start index for the original run.
+ unsigned offset_;
+
+ unsigned num_characters_;
+ float width_;
+};
+
+unsigned ShapeResultView::RunInfoPart::PreviousSafeToBreakOffset(
+ unsigned offset) const {
+ if (offset >= NumCharacters())
+ return NumCharacters();
+ if (!Rtl()) {
+ for (const auto& glyph : base::Reversed(*this)) {
+ if (glyph.safe_to_break_before && glyph.character_index <= offset)
+ return glyph.character_index;
+ }
+ } else {
+ for (const auto& glyph : *this) {
+ if (glyph.safe_to_break_before && glyph.character_index <= offset)
+ return glyph.character_index;
+ }
+ }
+
+ // Next safe break is at the start of the run.
+ return 0;
+}
+
+ShapeResultView::ShapeResultView(const ShapeResult* other)
+ : primary_font_(other->primary_font_),
+ start_index_(0),
+ num_characters_(0),
+ num_glyphs_(0),
+ direction_(other->direction_),
+ has_vertical_offsets_(other->has_vertical_offsets_),
+ width_(0) {}
+
+ShapeResultView::~ShapeResultView() = default;
+
+scoped_refptr<ShapeResult> ShapeResultView::CreateShapeResult() const {
+ ShapeResult* new_result =
+ new ShapeResult(primary_font_, num_characters_, Direction());
+ new_result->runs_.ReserveCapacity(parts_.size());
+ for (const auto& part : parts_) {
+ auto new_run = ShapeResult::RunInfo::Create(
+ part->run_->font_data_.get(), part->run_->direction_,
+ part->run_->canvas_rotation_, part->run_->script_, part->start_index_,
+ part->NumGlyphs(), part->num_characters_);
+ std::copy(part->range_.begin, part->range_.end,
+ new_run->glyph_data_.begin());
+ for (HarfBuzzRunGlyphData& glyph_data : new_run->glyph_data_) {
+ glyph_data.character_index -= part->offset_;
+ }
+
+ new_run->start_index_ += char_index_offset_;
+ new_run->width_ = part->width_;
+ new_run->num_characters_ = part->num_characters_;
+ new_result->runs_.push_back(std::move(new_run));
+ }
+
+ new_result->start_index_ = start_index_ + char_index_offset_;
+ new_result->num_glyphs_ = num_glyphs_;
+ new_result->has_vertical_offsets_ = has_vertical_offsets_;
+ new_result->width_ = width_;
+ new_result->glyph_bounding_box_ = glyph_bounding_box_;
+
+ return base::AdoptRef(new_result);
+}
+
+void ShapeResultView::CreateViewsForResult(const ShapeResult* other,
+ unsigned start_index,
+ unsigned end_index) {
+ bool first_result = num_characters_ == 0;
+ for (const auto& run : other->runs_) {
+ if (!run)
+ continue;
+ unsigned part_start = run->start_index_;
+ unsigned run_end = part_start + run->num_characters_;
+ if (start_index < run_end && end_index > part_start) {
+ ShapeResult::RunInfo::GlyphDataRange range;
+
+ unsigned adjusted_start =
+ start_index > part_start ? start_index - part_start : 0;
+ unsigned adjusted_end = std::min(end_index, run_end) - part_start;
+ DCHECK(adjusted_end > adjusted_start);
+ unsigned part_characters = adjusted_end - adjusted_start;
+ float part_width;
+
+ // Avoid O(log n) find operation if the entire run is in range.
+ if (part_start >= start_index && run_end <= end_index) {
+ range = {run->glyph_data_.begin(), run->glyph_data_.end()};
+ part_width = run->width_;
+ } else {
+ range = run->FindGlyphDataRange(adjusted_start, adjusted_end);
+ part_width = 0;
+ for (auto* glyph = range.begin; glyph != range.end; glyph++)
+ part_width += glyph->advance;
+ }
+
+ // Adjust start_index for runs to be continuous.
+ unsigned part_start_index;
+ unsigned part_offset;
+ if (!run->Rtl()) { // Left-to-right
+ part_start_index = start_index_ + num_characters_;
+ part_offset = adjusted_start;
+ } else { // Right-to-left
+ part_start_index = run->start_index_ + adjusted_start;
+ part_offset = adjusted_start;
+ }
+
+ parts_.push_back(std::make_unique<RunInfoPart>(
+ run, range, part_start_index, part_offset, part_characters,
+ part_width));
+
+ num_characters_ += part_characters;
+ num_glyphs_ += range.end - range.begin;
+ width_ += part_width;
+ }
+ }
+
+ if (first_result || Rtl())
+ start_index_ = ComputeStartIndex();
+}
+
+scoped_refptr<ShapeResultView> ShapeResultView::Create(const Segment* segments,
+ size_t segment_count) {
+ ShapeResultView* out = new ShapeResultView(segments[0].result);
+ out->AddSegments(segments, segment_count);
+ return base::AdoptRef(out);
+}
+
+scoped_refptr<ShapeResultView> ShapeResultView::Create(
+ const ShapeResult* result,
+ unsigned start_index,
+ unsigned end_index) {
+ Segment segment = {result, start_index, end_index};
+ return Create(&segment, 1);
+}
+
+scoped_refptr<ShapeResultView> ShapeResultView::Create(
+ const ShapeResult* result) {
+ // This specialization is an optimization to allow the bounding box to be
+ // re-used.
+ ShapeResultView* out = new ShapeResultView(result);
+ out->char_index_offset_ = out->Rtl() ? 0 : result->StartIndex();
+ out->CreateViewsForResult(result, 0, std::numeric_limits<unsigned>::max());
+ out->has_vertical_offsets_ = result->has_vertical_offsets_;
+ out->glyph_bounding_box_ = result->glyph_bounding_box_;
+ return base::AdoptRef(out);
+}
+
+void ShapeResultView::AddSegments(const Segment* segments,
+ size_t segment_count) {
+ // This method assumes that no parts have been added yet.
+ DCHECK_EQ(parts_.size(), 0u);
+
+ // Segments are in logical order, runs and parts are in visual order. Iterate
+ // over segments back-to-front for RTL.
+ DCHECK_GT(segment_count, 0u);
+ unsigned last_segment_index = segment_count - 1;
+
+ // Compute start index offset for the overall run. This is added to the start
+ // index of each glyph to ensure consistency with ShapeResult::SubRange
+ if (!Rtl()) { // Left-to-right
+ char_index_offset_ =
+ std::max(segments[0].result->StartIndex(), segments[0].start_index);
+ } else { // Right to left
+ char_index_offset_ = 0;
+ }
+
+ for (unsigned i = 0; i < segment_count; i++) {
+ const Segment& segment = segments[Rtl() ? last_segment_index - i : i];
+ DCHECK_EQ(segment.result->Direction(), Direction());
+ CreateViewsForResult(segment.result, segment.start_index,
+ segment.end_index);
+ has_vertical_offsets_ |= segment.result->has_vertical_offsets_;
+ }
+
+ float origin = 0;
+ for (const auto& part : parts_) {
+ if (part->IsHorizontal())
+ ComputeBoundsForPart<true>(*part, origin);
+ else
+ ComputeBoundsForPart<false>(*part, origin);
+ origin += part->width_;
+ }
+}
+
+template <bool is_horizontal_run>
+void ShapeResultView::ComputeBoundsForPart(const RunInfoPart& part,
+ float origin) {
+ GlyphBoundsAccumulator bounds(origin);
+ const auto& run = part.run_;
+ const SimpleFontData* font_data = run->font_data_.get();
+ for (const auto& glyph_data : part) {
+ FloatRect glyph_bounds = glyph_data.HasValidGlyphBounds()
+ ? FloatRect(glyph_data.GlyphBoundsBefore(), 0,
+ glyph_data.GlyphBoundsAfter(), 0)
+ : font_data->BoundsForGlyph(glyph_data.glyph);
+
+ bounds.Unite<is_horizontal_run>(glyph_data, glyph_bounds);
+ bounds.origin += glyph_data.advance;
+ }
+ if (!is_horizontal_run)
+ bounds.ConvertVerticalRunToLogical(font_data->GetFontMetrics());
+ glyph_bounding_box_.Unite(bounds.bounds);
+}
+
+unsigned ShapeResultView::ComputeStartIndex() const {
+ if (UNLIKELY(parts_.IsEmpty()))
+ return 0;
+ const RunInfoPart& first_part = *parts_.front();
+ if (!Rtl()) // Left-to-right.
+ return first_part.start_index_;
+ // Right-to-left.
+ unsigned end_index = first_part.start_index_ + first_part.num_characters_;
+ return end_index - num_characters_;
+}
+
+unsigned ShapeResultView::PreviousSafeToBreakOffset(unsigned index) const {
+ for (auto it = parts_.rbegin(); it != parts_.rend(); ++it) {
+ const auto& part = *it;
+ if (!part)
+ continue;
+
+ unsigned run_start = part->start_index_;
+ if (index >= run_start) {
+ unsigned offset = index - run_start;
+ if (offset <= part->num_characters_) {
+ return part->PreviousSafeToBreakOffset(offset) + run_start;
+ }
+ if (!Rtl()) {
+ return run_start + part->num_characters_;
+ }
+ } else if (Rtl()) {
+ if (it == parts_.rbegin())
+ return part->start_index_;
+ const auto& previous_run = *--it;
+ return previous_run->start_index_ + previous_run->num_characters_;
+ }
+ }
+
+ return StartIndex();
+}
+
+void ShapeResultView::GetRunFontData(
+ Vector<ShapeResult::RunFontData>* font_data) const {
+ for (const auto& part : parts_) {
+ font_data->push_back(ShapeResult::RunFontData(
+ {part->run_->font_data_.get(), part->end() - part->begin()}));
+ }
+}
+
+void ShapeResultView::FallbackFonts(
+ HashSet<const SimpleFontData*>* fallback) const {
+ DCHECK(fallback);
+ DCHECK(primary_font_);
+ for (const auto& part : parts_) {
+ if (part->run_->font_data_ && part->run_->font_data_ != primary_font_) {
+ fallback->insert(part->run_->font_data_.get());
+ }
+ }
+}
+
+float ShapeResultView::ForEachGlyph(float initial_advance,
+ GlyphCallback glyph_callback,
+ void* context) const {
+ auto total_advance = initial_advance;
+ for (const auto& part : parts_) {
+ const auto& run = part->run_;
+ bool is_horizontal = HB_DIRECTION_IS_HORIZONTAL(run->direction_);
+ const SimpleFontData* font_data = run->font_data_.get();
+ for (const auto& glyph_data : *part) {
+ unsigned character_index = glyph_data.character_index +
+ part->start_index_ + char_index_offset_ -
+ part->offset_;
+ glyph_callback(context, character_index, glyph_data.glyph,
+ glyph_data.offset, total_advance, is_horizontal,
+ run->canvas_rotation_, font_data);
+ total_advance += glyph_data.advance;
+ }
+ }
+
+ return total_advance;
+}
+
+float ShapeResultView::ForEachGlyph(float initial_advance,
+ unsigned from,
+ unsigned to,
+ unsigned index_offset,
+ GlyphCallback glyph_callback,
+ void* context) const {
+ auto total_advance = initial_advance;
+
+ for (const auto& part : parts_) {
+ const auto& run = part->run_;
+ bool is_horizontal = HB_DIRECTION_IS_HORIZONTAL(run->direction_);
+ const SimpleFontData* font_data = run->font_data_.get();
+
+ if (!run->Rtl()) { // Left-to-right
+ for (const auto& glyph_data : *part) {
+ unsigned character_index = glyph_data.character_index +
+ part->start_index_ + char_index_offset_ -
+ part->offset_;
+ if (character_index >= to)
+ break;
+ if (character_index >= from) {
+ glyph_callback(context, character_index, glyph_data.glyph,
+ glyph_data.offset, total_advance, is_horizontal,
+ run->canvas_rotation_, font_data);
+ }
+ total_advance += glyph_data.advance;
+ }
+
+ } else { // Right-to-left
+ for (const auto& glyph_data : *part) {
+ unsigned character_index = glyph_data.character_index +
+ part->start_index_ + char_index_offset_ -
+ part->offset_;
+ if (character_index < from)
+ break;
+ if (character_index < to) {
+ glyph_callback(context, character_index, glyph_data.glyph,
+ glyph_data.offset, total_advance, is_horizontal,
+ run->canvas_rotation_, font_data);
+ }
+ total_advance += glyph_data.advance;
+ }
+ }
+ }
+ return total_advance;
+}
+
+float ShapeResultView::ForEachGraphemeClusters(const StringView& text,
+ float initial_advance,
+ unsigned from,
+ unsigned to,
+ unsigned index_offset,
+ GraphemeClusterCallback callback,
+ void* context) const {
+ unsigned run_offset = index_offset;
+ float advance_so_far = initial_advance;
+
+ for (const auto& part : parts_) {
+ const auto& run = part->run_;
+ unsigned graphemes_in_cluster = 1;
+ float cluster_advance = 0;
+ bool rtl = Direction() == TextDirection::kRtl;
+
+ // A "cluster" in this context means a cluster as it is used by HarfBuzz:
+ // The minimal group of characters and corresponding glyphs, that cannot be
+ // broken down further from a text shaping point of view. A cluster can
+ // contain multiple glyphs and grapheme clusters, with mutually overlapping
+ // boundaries.
+ uint16_t cluster_start = static_cast<uint16_t>(
+ rtl ? run->start_index_ + run->num_characters_ + run_offset
+ : run->GlyphToCharacterIndex(0) + run_offset);
+
+ const unsigned num_glyphs = part->NumGlyphs();
+ for (unsigned i = 0; i < num_glyphs; ++i) {
+ const HarfBuzzRunGlyphData& glyph_data = part->GlyphAt(i);
+ uint16_t current_character_index = glyph_data.character_index +
+ part->start_index_ +
+ char_index_offset_ - part->offset_;
+
+ bool is_run_end = (i + 1 == num_glyphs);
+ bool is_cluster_end =
+ is_run_end || (run->GlyphToCharacterIndex(i + 1) + run_offset !=
+ current_character_index);
+
+ if ((rtl && current_character_index >= to) ||
+ (!rtl && current_character_index < from)) {
+ advance_so_far += glyph_data.advance;
+ rtl ? --cluster_start : ++cluster_start;
+ continue;
+ }
+
+ cluster_advance += glyph_data.advance;
+
+ if (text.Is8Bit()) {
+ callback(context, current_character_index, advance_so_far, 1,
+ glyph_data.advance, run->canvas_rotation_);
+
+ advance_so_far += glyph_data.advance;
+ } else if (is_cluster_end) {
+ uint16_t cluster_end;
+ if (rtl) {
+ cluster_end = current_character_index;
+ } else {
+ cluster_end = static_cast<uint16_t>(
+ is_run_end ? run->start_index_ + run->num_characters_ + run_offset
+ : run->GlyphToCharacterIndex(i + 1) + run_offset);
+ }
+ graphemes_in_cluster = ShapeResult::CountGraphemesInCluster(
+ text.Characters16(), text.length(), cluster_start, cluster_end);
+ if (!graphemes_in_cluster || !cluster_advance)
+ continue;
+
+ callback(context, current_character_index, advance_so_far,
+ graphemes_in_cluster, cluster_advance, run->canvas_rotation_);
+ advance_so_far += cluster_advance;
+
+ cluster_start = cluster_end;
+ cluster_advance = 0;
+ }
+ }
+ }
+ return advance_so_far;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h
new file mode 100644
index 00000000000..214fd54fbc1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h
@@ -0,0 +1,167 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_SHAPE_RESULT_VIEW_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_SHAPE_RESULT_VIEW_H_
+
+#include <memory>
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
+#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/text/text_direction.h"
+#include "third_party/blink/renderer/platform/wtf/forward.h"
+#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+class ShapeResult;
+
+// Class representing a read-only composite of views into one or more existing
+// shape results.
+// Implemented as a list of ref counted RunInfo instances and a start/end
+// offset for each, represented using the internal RunInfoPart struct.
+// This allows lines to be reference sections of the overall paragraph shape
+// results without the memory or computational overhead of a copy.
+//
+// The example below shows the shape result and the individual lines as
+// ShapeResultView instances pointing to the original paragraph results for
+// the string "Pack my box with five dozen liquor jugs.":
+// ╔═════════════════════════════════════════════════════╗
+// ║ Paragraph with single run, no re-shaping for lines. ║
+// ╟─────────────────────────────────────────────────────╢
+// ║ runs_ ╭───────────────────────────────────────────╮ ║
+// ║ 1: │ Pack my box with five dozen liquor jugs. │ ║
+// ║ ╰───────────────────────────────────────────╯ ║
+// ║ lines ╭───────────────────────────────────────────╮ ║
+// ║ 1: │ Pack my box with -> view, run 1: 0-16 │ ║
+// ║ 2: │ five dozen liquor -> view, run 1: 17-34 │ ║
+// ║ 3: │ jugs. -> view, run 1: 35-40 │ ║
+// ║ ╰───────────────────────────────────────────╯ ║
+// ╚═════════════════════════════════════════════════════╝
+//
+// In cases where a portion of the line needs re-shaping the new results are
+// added as separate runs at the beginning and/or end of the runs_ vector with a
+// reference to zero or more sub-runs in the middle representing the original
+// content that could be reused.
+//
+// In the example below the end of the first line "Jack!" needs to be re-shaped:
+// ╔═════════════════════════════════════════════════════╗
+// ║ Paragraph with single run, requiring re-shape. ║
+// ╟─────────────────────────────────────────────────────╢
+// ║ runs_ ╭───────────────────────────────────────────╮ ║
+// ║ 1: │ "Now fax quiz Jack!" my brave ghost pled. │ ║
+// ║ ╰───────────────────────────────────────────╯ ║
+// ║ lines ╭───────────────────────────────────────────╮ ║
+// ║ 1: │ "Now fax quiz -> view, run 1: 0-14 │ ║
+// ║ 1: │ Jack! -> new result/run │ ║
+// ║ 2: │ my brave ghost -> view, run 1: 21-35 │ ║
+// ║ 3: │ pled. -> view, run 1: 41-36 │ ║
+// ║ ╰───────────────────────────────────────────╯ ║
+// ╚═════════════════════════════════════════════════════╝
+//
+// In this case the beginning of the first line would be represented as a part
+// referecing the a range into the original ShapeResult while the last word wold
+// be a separate result owned by the ShapeResultView instance. The second
+// and third lines would again be represented as parts.
+class PLATFORM_EXPORT ShapeResultView final
+ : public RefCounted<ShapeResultView> {
+ public:
+ // Create a new ShapeResultView from a pre-defined list of segments.
+ // The segments list is assumed to be in logical order.
+ struct Segment {
+ const ShapeResult* result;
+ unsigned start_index;
+ unsigned end_index;
+ };
+ static scoped_refptr<ShapeResultView> Create(const Segment*, size_t);
+
+ // Creates a new ShapeResultView from a single segment.
+ static scoped_refptr<ShapeResultView> Create(const ShapeResult*);
+ static scoped_refptr<ShapeResultView> Create(const ShapeResult*,
+ unsigned start_index,
+ unsigned end_index);
+
+ ~ShapeResultView();
+
+ scoped_refptr<ShapeResult> CreateShapeResult() const;
+
+ unsigned StartIndex() const { return start_index_ + char_index_offset_; }
+ unsigned EndIndex() const { return StartIndex() + num_characters_; }
+ unsigned NumCharacters() const { return num_characters_; }
+ unsigned NumGlyphs() const { return num_glyphs_; }
+ float Width() const { return width_; }
+ LayoutUnit SnappedWidth() const { return LayoutUnit::FromFloatCeil(width_); }
+ const FloatRect& Bounds() const { return glyph_bounding_box_; }
+ TextDirection Direction() const {
+ return static_cast<TextDirection>(direction_);
+ }
+ bool Rtl() const { return Direction() == TextDirection::kRtl; }
+ bool HasVerticalOffsets() const { return has_vertical_offsets_; }
+ void FallbackFonts(HashSet<const SimpleFontData*>* fallback) const;
+
+ unsigned PreviousSafeToBreakOffset(unsigned index) const;
+
+ float ForEachGlyph(float initial_advance, GlyphCallback, void* context) const;
+ float ForEachGlyph(float initial_advance,
+ unsigned from,
+ unsigned to,
+ unsigned index_offset,
+ GlyphCallback,
+ void* context) const;
+
+ float ForEachGraphemeClusters(const StringView& text,
+ float initial_advance,
+ unsigned from,
+ unsigned to,
+ unsigned index_offset,
+ GraphemeClusterCallback,
+ void* context) const;
+
+ scoped_refptr<const SimpleFontData> PrimaryFont() const {
+ return primary_font_;
+ }
+ void GetRunFontData(Vector<ShapeResult::RunFontData>*) const;
+
+ private:
+ ShapeResultView(const ShapeResult*);
+ unsigned ComputeStartIndex() const;
+
+ struct RunInfoPart;
+ void CreateViewsForResult(const ShapeResult*,
+ unsigned start_index,
+ unsigned end_index);
+ void AddSegments(const Segment*, size_t);
+ template <bool is_horizontal_run>
+ void ComputeBoundsForPart(const RunInfoPart&, float origin);
+
+ scoped_refptr<const SimpleFontData> primary_font_;
+
+ mutable unsigned start_index_; // Cached and updated by ComputeStartIndex.
+ unsigned num_characters_;
+ unsigned num_glyphs_ : 30;
+
+ // Overall direction for the TextRun, dictates which order each individual
+ // sub run (represented by RunInfo structs in the m_runs vector) can
+ // have a different text direction.
+ unsigned direction_ : 1;
+
+ // Tracks whether any runs contain glyphs with a y-offset != 0.
+ unsigned has_vertical_offsets_ : 1;
+
+ // Offset of the first component added to the view. Used for compatibility
+ // with ShapeResult::SubRange
+ unsigned char_index_offset_;
+
+ float width_;
+ FloatRect glyph_bounding_box_;
+ Vector<std::unique_ptr<RunInfoPart>, 4> parts_;
+
+ friend class ShapeResult;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_SHAPE_RESULT_VIEW_H_
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view_test.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view_test.cc
new file mode 100644
index 00000000000..04af141cb59
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shape_result_view_test.cc
@@ -0,0 +1,366 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h"
+
+#include <unicode/uscript.h>
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/fonts/font.h"
+#include "third_party/blink/renderer/platform/fonts/font_cache.h"
+#include "third_party/blink/renderer/platform/fonts/font_test_utilities.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
+
+namespace blink {
+
+class ShapeResultViewTest : public testing::Test {
+ protected:
+ void SetUp() override {
+ font_description.SetComputedSize(12.0);
+ font = Font(font_description);
+ font.Update(nullptr);
+ }
+
+ void TearDown() override {}
+
+ FontCachePurgePreventer font_cache_purge_preventer;
+ FontDescription font_description;
+ Font font;
+};
+
+namespace {
+
+struct ShapeResultViewGlyphInfo {
+ unsigned character_index;
+ Glyph glyph;
+ float advance;
+};
+
+void AddGlyphInfo(void* context,
+ unsigned character_index,
+ Glyph glyph,
+ FloatSize glyph_offset,
+ float advance,
+ bool is_horizontal,
+ CanvasRotationInVertical rotation,
+ const SimpleFontData* font_data) {
+ auto* list = static_cast<Vector<ShapeResultViewGlyphInfo>*>(context);
+ ShapeResultViewGlyphInfo glyph_info = {character_index, glyph, advance};
+ list->push_back(glyph_info);
+}
+
+bool CompareResultGlyphs(const Vector<ShapeResultViewGlyphInfo>& test,
+ const Vector<ShapeResultViewGlyphInfo>& reference,
+ unsigned reference_start,
+ unsigned num_glyphs) {
+ float advance_offset = reference[reference_start].advance;
+ bool glyphs_match = true;
+ for (unsigned i = 0; i < test.size(); i++) {
+ const auto& test_glyph = test[i];
+ const auto& reference_glyph = reference[i + reference_start];
+ if (test_glyph.character_index != reference_glyph.character_index ||
+ test_glyph.glyph != reference_glyph.glyph ||
+ test_glyph.advance != reference_glyph.advance - advance_offset) {
+ glyphs_match = false;
+ break;
+ }
+ }
+ if (!glyphs_match) {
+ fprintf(stderr, "╔══ Actual ═══════╤═══════╤═════════╗ ");
+ fprintf(stderr, "╔══ Expected ═════╤═══════╤═════════╗\n");
+ fprintf(stderr, "║ Character Index │ Glyph │ Advance ║ ");
+ fprintf(stderr, "║ Character Index │ Glyph │ Advance ║\n");
+ fprintf(stderr, "╟─────────────────┼───────┼─────────╢ ");
+ fprintf(stderr, "╟─────────────────┼───────┼─────────╢\n");
+ for (unsigned i = 0; i < test.size(); i++) {
+ const auto& test_glyph = test[i];
+ const auto& reference_glyph = reference[i + reference_start];
+
+ if (test_glyph.character_index == reference_glyph.character_index)
+ fprintf(stderr, "║ %10u │", test_glyph.character_index);
+ else
+ fprintf(stderr, "║▶ %10u◀│", test_glyph.character_index);
+
+ if (test_glyph.glyph == reference_glyph.glyph)
+ fprintf(stderr, " %04X │", test_glyph.glyph);
+ else
+ fprintf(stderr, "▶ %04X◀│", test_glyph.glyph);
+
+ if (test_glyph.advance == reference_glyph.advance)
+ fprintf(stderr, " %7.2f ║ ", test_glyph.advance);
+ else
+ fprintf(stderr, "▶%7.2f◀║ ", test_glyph.advance);
+
+ fprintf(stderr, "║ %10u │ %04X │ %7.2f ║\n",
+ reference_glyph.character_index, reference_glyph.glyph,
+ reference_glyph.advance - advance_offset);
+ }
+ fprintf(stderr, "╚═════════════════╧═══════╧═════════╝ ");
+ fprintf(stderr, "╚═════════════════╧═══════╧═════════╝\n");
+ }
+ return glyphs_match;
+}
+
+} // anonymous namespace
+
+TEST_F(ShapeResultViewTest, LatinSingleView) {
+ String string =
+ To16Bit("Test run with multiple words and breaking opportunities.", 56);
+ TextDirection direction = TextDirection::kLtr;
+
+ HarfBuzzShaper shaper(string);
+ scoped_refptr<const ShapeResult> result = shaper.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> glyphs;
+ result->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&glyphs));
+
+ // Test view at the start of the result: "Test run with multiple"
+ ShapeResultView::Segment segment = {result.get(), 0, 22};
+ auto first4 = ShapeResultView::Create(&segment, 1);
+
+ EXPECT_EQ(first4->StartIndex(), 0u);
+ EXPECT_EQ(first4->NumCharacters(), 22u);
+ EXPECT_EQ(first4->NumGlyphs(), 22u);
+
+ Vector<ShapeResultViewGlyphInfo> first4_glyphs;
+ first4->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&first4_glyphs));
+ EXPECT_EQ(first4_glyphs.size(), 22u);
+ EXPECT_TRUE(CompareResultGlyphs(first4_glyphs, glyphs, 0u, 22u));
+
+ // Test view in the middle of the result: "multiple words and breaking"
+ segment = {result.get(), 14, 41};
+ auto middle4 = ShapeResultView::Create(&segment, 1);
+
+ EXPECT_EQ(middle4->StartIndex(), 14u);
+ EXPECT_EQ(middle4->NumCharacters(), 27u);
+ EXPECT_EQ(middle4->NumGlyphs(), 27u);
+
+ Vector<ShapeResultViewGlyphInfo> middle4_glyphs;
+ middle4->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&middle4_glyphs));
+ EXPECT_EQ(middle4_glyphs.size(), 27u);
+ EXPECT_TRUE(CompareResultGlyphs(middle4_glyphs, glyphs, 14u, 27u));
+
+ // Test view at the end of the result: "breaking opportunities."
+ segment = {result.get(), 33, 56};
+ auto last2 = ShapeResultView::Create(&segment, 1);
+
+ EXPECT_EQ(last2->StartIndex(), 33u);
+ EXPECT_EQ(last2->NumCharacters(), 23u);
+ EXPECT_EQ(last2->NumGlyphs(), 23u);
+
+ Vector<ShapeResultViewGlyphInfo> last2_glyphs;
+ last2->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&last2_glyphs));
+ EXPECT_EQ(last2_glyphs.size(), 23u);
+ EXPECT_TRUE(CompareResultGlyphs(last2_glyphs, glyphs, 33u, 23u));
+}
+
+TEST_F(ShapeResultViewTest, ArabicSingleView) {
+ String string = To16Bit("عربى نص", 7);
+ TextDirection direction = TextDirection::kRtl;
+
+ HarfBuzzShaper shaper(string);
+ scoped_refptr<const ShapeResult> result = shaper.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> glyphs;
+ result->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&glyphs));
+
+ // Test view at the start of the result: "عربى"
+ ShapeResultView::Segment segment = {result.get(), 0, 4};
+ auto first_word = ShapeResultView::Create(&segment, 1);
+ Vector<ShapeResultViewGlyphInfo> first_glyphs;
+ first_word->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&first_glyphs));
+
+ EXPECT_EQ(first_word->StartIndex(), 0u);
+ EXPECT_EQ(first_word->NumCharacters(), 4u);
+ EXPECT_EQ(first_word->NumGlyphs(), 4u);
+ EXPECT_EQ(first_glyphs.size(), 4u);
+
+ String first_reference_string = To16Bit("عربى", 4);
+ HarfBuzzShaper first_reference_shaper(first_reference_string);
+ scoped_refptr<const ShapeResult> first_wortd_reference =
+ first_reference_shaper.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> first_reference_glyphs;
+ first_wortd_reference->ForEachGlyph(
+ 0, AddGlyphInfo, static_cast<void*>(&first_reference_glyphs));
+ EXPECT_EQ(first_reference_glyphs.size(), 4u);
+
+ EXPECT_TRUE(
+ CompareResultGlyphs(first_glyphs, first_reference_glyphs, 0u, 4u));
+ EXPECT_TRUE(CompareResultGlyphs(first_glyphs, glyphs, 3u, 7u));
+
+ // Test view at the end of the result: "نص"
+ segment = {result.get(), 4, 7};
+ auto last_word = ShapeResultView::Create(&segment, 1);
+ Vector<ShapeResultViewGlyphInfo> last_glyphs;
+ last_word->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&last_glyphs));
+
+ EXPECT_EQ(last_word->StartIndex(), 4u);
+ EXPECT_EQ(last_word->NumCharacters(), 3u);
+ EXPECT_EQ(last_word->NumGlyphs(), 3u);
+ EXPECT_EQ(last_glyphs.size(), 3u);
+}
+
+TEST_F(ShapeResultViewTest, LatinMultiRun) {
+ TextDirection direction = TextDirection::kLtr;
+ HarfBuzzShaper shaper_a(To16Bit("hello", 5));
+ HarfBuzzShaper shaper_b(To16Bit(" w", 2));
+ HarfBuzzShaper shaper_c(To16Bit("orld", 4));
+ HarfBuzzShaper shaper_d(To16Bit("!", 1));
+
+ // Combine four separate results into a single one to ensure we have a result
+ // with multiple runs: "hello world!"
+ scoped_refptr<ShapeResult> result = ShapeResult::Create(&font, 0, direction);
+ shaper_a.Shape(&font, direction)->CopyRange(0u, 5u, result.get());
+ shaper_b.Shape(&font, direction)->CopyRange(0u, 2u, result.get());
+ shaper_c.Shape(&font, direction)->CopyRange(0u, 4u, result.get());
+ shaper_d.Shape(&font, direction)->CopyRange(0u, 1u, result.get());
+
+ Vector<ShapeResultViewGlyphInfo> result_glyphs;
+ result->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&result_glyphs));
+
+ // Create composite view out of multiple segments where at least some of the
+ // segments have multiple runs: "hello wood wold!"
+ ShapeResultView::Segment segments[5] = {
+ {result.get(), 0, 8}, // "hello wo"
+ {result.get(), 7, 8}, // "o"
+ {result.get(), 10, 11}, // "d"
+ {result.get(), 5, 8}, // " wo"
+ {result.get(), 9, 12}, // "ld!"
+ };
+ auto composite_view = ShapeResultView::Create(&segments[0], 5);
+ Vector<ShapeResultViewGlyphInfo> view_glyphs;
+ composite_view->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&view_glyphs));
+
+ EXPECT_EQ(composite_view->StartIndex(), 0u);
+ EXPECT_EQ(composite_view->NumCharacters(), 16u);
+ EXPECT_EQ(composite_view->NumGlyphs(), 16u);
+ EXPECT_EQ(view_glyphs.size(), 16u);
+
+ HarfBuzzShaper shaper2(To16Bit("hello world!", 12));
+ scoped_refptr<const ShapeResult> result2 = shaper2.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> glyphs2;
+ result2->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&glyphs2));
+ EXPECT_TRUE(CompareResultGlyphs(result_glyphs, glyphs2, 0u, 12u));
+
+ HarfBuzzShaper reference_shaper(To16Bit("hello wood wold!", 16));
+ scoped_refptr<const ShapeResult> reference_result =
+ reference_shaper.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> reference_glyphs;
+ reference_result->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&reference_glyphs));
+
+ scoped_refptr<ShapeResult> composite_copy =
+ ShapeResult::Create(&font, 0, direction);
+ result->CopyRange(0, 8, composite_copy.get());
+ result->CopyRange(7, 8, composite_copy.get());
+ result->CopyRange(10, 11, composite_copy.get());
+ result->CopyRange(5, 8, composite_copy.get());
+ result->CopyRange(9, 12, composite_copy.get());
+
+ Vector<ShapeResultViewGlyphInfo> composite_copy_glyphs;
+ composite_copy->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&composite_copy_glyphs));
+
+ EXPECT_TRUE(CompareResultGlyphs(view_glyphs, reference_glyphs, 0u, 16u));
+ EXPECT_TRUE(
+ CompareResultGlyphs(composite_copy_glyphs, reference_glyphs, 0u, 16u));
+}
+
+TEST_F(ShapeResultViewTest, LatinCompositeView) {
+ String string =
+ To16Bit("Test run with multiple words and breaking opportunities.", 56);
+ TextDirection direction = TextDirection::kLtr;
+
+ HarfBuzzShaper shaper(string);
+ scoped_refptr<const ShapeResult> result = shaper.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> glyphs;
+ result->ForEachGlyph(0, AddGlyphInfo, static_cast<void*>(&glyphs));
+
+ String reference_string = To16Bit("multiple breaking opportunities Test", 36);
+ HarfBuzzShaper reference_shaper(reference_string);
+ scoped_refptr<const ShapeResult> reference_result =
+ reference_shaper.Shape(&font, direction);
+ Vector<ShapeResultViewGlyphInfo> reference_glyphs;
+
+ // Match the character index logic of ShapeResult::CopyRange where the the
+ // character index of the first result is preserved and all subsequent ones
+ // are adjusted to be sequential.
+ // TODO(layout-dev): Arguably both should be updated to renumber the first
+ // result as well but some callers depend on the existing behavior.
+ scoped_refptr<ShapeResult> composite_copy =
+ ShapeResult::Create(&font, 0, direction);
+ result->CopyRange(14, 23, composite_copy.get());
+ result->CopyRange(33, 55, composite_copy.get());
+ result->CopyRange(4, 5, composite_copy.get());
+ result->CopyRange(0, 4, composite_copy.get());
+ EXPECT_EQ(composite_copy->NumCharacters(), reference_result->NumCharacters());
+ EXPECT_EQ(composite_copy->NumGlyphs(), reference_result->NumGlyphs());
+ composite_copy->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&reference_glyphs));
+
+ // Create composite view out of multiple segments:
+ ShapeResultView::Segment segments[4] = {
+ {result.get(), 14, 23}, // "multiple "
+ {result.get(), 33, 55}, // "breaking opportunities"
+ {result.get(), 4, 5}, // " "
+ {result.get(), 0, 4} // "Test"
+ };
+ auto composite_view = ShapeResultView::Create(&segments[0], 4);
+
+ EXPECT_EQ(composite_view->StartIndex(), composite_copy->StartIndex());
+ EXPECT_EQ(composite_view->NumCharacters(), reference_result->NumCharacters());
+ EXPECT_EQ(composite_view->NumGlyphs(), reference_result->NumGlyphs());
+
+ Vector<ShapeResultViewGlyphInfo> composite_glyphs;
+ composite_view->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&composite_glyphs));
+ EXPECT_EQ(composite_glyphs.size(), 36u);
+ EXPECT_TRUE(CompareResultGlyphs(composite_glyphs, reference_glyphs, 0u, 22u));
+}
+
+TEST_F(ShapeResultViewTest, MixedScriptsCompositeView) {
+ String string_a = To16Bit("Test with multiple 字体 ", 22);
+ String string_b = To16Bit("and 本書.", 7);
+ TextDirection direction = TextDirection::kLtr;
+
+ HarfBuzzShaper shaper_a(string_a);
+ scoped_refptr<const ShapeResult> result_a = shaper_a.Shape(&font, direction);
+ HarfBuzzShaper shaper_b(string_b);
+ scoped_refptr<const ShapeResult> result_b = shaper_b.Shape(&font, direction);
+
+ String reference_string = To16Bit("Test with multiple 字体 and 本書.", 29);
+ HarfBuzzShaper reference_shaper(reference_string);
+ scoped_refptr<const ShapeResult> reference_result =
+ reference_shaper.Shape(&font, direction);
+
+ // Create a copy using CopyRange and compare with that to ensure that the same
+ // fonts are used for both the composite and the reference. The combined
+ // reference_result data might use different fonts, resulting in different
+ // glyph ids and metrics.
+ scoped_refptr<ShapeResult> composite_copy =
+ ShapeResult::Create(&font, 0, direction);
+ result_a->CopyRange(0, 22, composite_copy.get());
+ result_b->CopyRange(0, 7, composite_copy.get());
+ EXPECT_EQ(composite_copy->NumCharacters(), reference_result->NumCharacters());
+ EXPECT_EQ(composite_copy->NumGlyphs(), reference_result->NumGlyphs());
+ Vector<ShapeResultViewGlyphInfo> reference_glyphs;
+ composite_copy->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&reference_glyphs));
+
+ ShapeResultView::Segment segments[4] = {{result_a.get(), 0, 22},
+ {result_b.get(), 0, 7}};
+ auto composite_view = ShapeResultView::Create(&segments[0], 2);
+
+ EXPECT_EQ(composite_view->StartIndex(), 0u);
+ EXPECT_EQ(composite_view->NumCharacters(), reference_result->NumCharacters());
+ EXPECT_EQ(composite_view->NumGlyphs(), reference_result->NumGlyphs());
+
+ Vector<ShapeResultViewGlyphInfo> composite_glyphs;
+ composite_view->ForEachGlyph(0, AddGlyphInfo,
+ static_cast<void*>(&composite_glyphs));
+ EXPECT_TRUE(CompareResultGlyphs(composite_glyphs, reference_glyphs, 0u,
+ reference_glyphs.size()));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.cc
index 655112d0aee..22198066fef 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.cc
@@ -8,6 +8,7 @@
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
namespace blink {
@@ -215,14 +216,14 @@ inline scoped_refptr<ShapeResult> ShapingLineBreaker::Shape(TextDirection direct
// If we further assume that the font kerns with space then even though it's a
// valid break opportunity reshaping is required as the combined width of the
// two segments "Line " and "breaking" may be different from "Line breaking".
-scoped_refptr<const ShapeResult> ShapingLineBreaker::ShapeLine(
+scoped_refptr<const ShapeResultView> ShapingLineBreaker::ShapeLine(
unsigned start,
LayoutUnit available_space,
unsigned options,
ShapingLineBreaker::Result* result_out) {
DCHECK_GE(available_space, LayoutUnit(0));
- unsigned range_start = result_->StartIndexForResult();
- unsigned range_end = result_->EndIndexForResult();
+ unsigned range_start = result_->StartIndex();
+ unsigned range_end = result_->EndIndex();
DCHECK_GE(start, range_start);
DCHECK_LT(start, range_end);
result_out->is_hyphenated = false;
@@ -287,7 +288,8 @@ scoped_refptr<const ShapeResult> ShapingLineBreaker::ShapeLine(
if (first_safe >= break_opportunity.offset) {
// There is no safe-to-break, reshape the whole range.
result_out->break_offset = break_opportunity.offset;
- return Shape(direction, start, break_opportunity.offset);
+ return ShapeResultView::Create(
+ Shape(direction, start, break_opportunity.offset).get());
}
LayoutUnit original_width = FlipRtl(
SnapEnd(result_->CachedPositionForOffset(first_safe - range_start),
@@ -354,14 +356,16 @@ scoped_refptr<const ShapeResult> ShapingLineBreaker::ShapeLine(
// Create shape results for the line by copying from the re-shaped result (if
// reshaping was needed) and the original shape results.
- scoped_refptr<ShapeResult> line_result = ShapeResult::Create(font_, 0, direction);
+ ShapeResultView::Segment segments[3];
unsigned max_length = std::numeric_limits<unsigned>::max();
+ unsigned count = 0;
if (line_start_result)
- line_start_result->CopyRange(0, max_length, line_result.get());
+ segments[count++] = {line_start_result.get(), 0, max_length};
if (last_safe > first_safe)
- result_->CopyRange(first_safe, last_safe, line_result.get());
+ segments[count++] = {result_.get(), first_safe, last_safe};
if (line_end_result)
- line_end_result->CopyRange(last_safe, max_length, line_result.get());
+ segments[count++] = {line_end_result.get(), last_safe, max_length};
+ auto line_result = ShapeResultView::Create(&segments[0], count);
DCHECK_GT(break_opportunity.offset, start);
DCHECK_LE(break_opportunity.offset, range_end);
@@ -376,37 +380,40 @@ scoped_refptr<const ShapeResult> ShapingLineBreaker::ShapeLine(
// Shape from the specified offset to the end of the ShapeResult.
// If |start| is safe-to-break, this copies the subset of the result.
-scoped_refptr<const ShapeResult> ShapingLineBreaker::ShapeToEnd(
+scoped_refptr<const ShapeResultView> ShapingLineBreaker::ShapeToEnd(
unsigned start,
unsigned first_safe,
unsigned range_start,
unsigned range_end) {
DCHECK(result_);
- DCHECK_EQ(range_start, result_->StartIndexForResult());
- DCHECK_EQ(range_end, result_->EndIndexForResult());
+ DCHECK_EQ(range_start, result_->StartIndex());
+ DCHECK_EQ(range_end, result_->EndIndex());
DCHECK_GE(start, range_start);
DCHECK_LT(start, range_end);
DCHECK_GE(first_safe, start);
// If |start| is at the start of the range the entire result object may be
- // reused, which avoids creating an extra copy an the sub-range logic.
+ // reused, which avoids the sub-range logic and bounds computation.
if (start == range_start)
- return result_;
+ return ShapeResultView::Create(result_.get());
// If |start| is safe-to-break, no reshape is needed.
if (start == first_safe)
- return result_->SubRange(start, range_end);
+ return ShapeResultView::Create(result_.get(), start, range_end);
// If no safe-to-break offset is found in range, reshape the entire range.
TextDirection direction = result_->Direction();
- if (first_safe >= range_end)
- return Shape(direction, start, range_end);
+ if (first_safe >= range_end) {
+ scoped_refptr<ShapeResult> line_result = Shape(direction, start, range_end);
+ return ShapeResultView::Create(line_result.get());
+ }
// Otherwise reshape to |first_safe|, then copy the rest.
- scoped_refptr<ShapeResult> line_result = Shape(direction, start, first_safe);
- result_->CopyRange(first_safe, range_end, line_result.get());
- DCHECK_EQ(range_end - start, line_result->NumCharacters());
- return line_result;
+ scoped_refptr<ShapeResult> line_start = Shape(direction, start, first_safe);
+ ShapeResultView::Segment segments[2] = {
+ {line_start.get(), 0, std::numeric_limits<unsigned>::max()},
+ {result_.get(), first_safe, range_end}};
+ return ShapeResultView::Create(&segments[0], 2);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h b/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h
index e58db434b6e..159cd3e4068 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SHAPING_SHAPING_LINE_BREAKER_H_
#include "third_party/blink/renderer/platform/fonts/shaping/run_segmenter.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
@@ -15,6 +15,7 @@ namespace blink {
class Font;
class ShapeResult;
+class ShapeResultView;
class HarfBuzzShaper;
class Hyphenation;
class LazyLineBreakIterator;
@@ -76,13 +77,13 @@ class PLATFORM_EXPORT ShapingLineBreaker final {
// suppress if ShapeResult is not needed when this line overflows.
kNoResultIfOverflow = 2,
};
- scoped_refptr<const ShapeResult> ShapeLine(unsigned start_offset,
- LayoutUnit available_space,
- unsigned options,
- Result* result_out);
- scoped_refptr<const ShapeResult> ShapeLine(unsigned start_offset,
- LayoutUnit available_space,
- Result* result_out) {
+ scoped_refptr<const ShapeResultView> ShapeLine(unsigned start_offset,
+ LayoutUnit available_space,
+ unsigned options,
+ Result* result_out);
+ scoped_refptr<const ShapeResultView> ShapeLine(unsigned start_offset,
+ LayoutUnit available_space,
+ Result* result_out) {
return ShapeLine(start_offset, available_space, kDefaultOptions,
result_out);
}
@@ -116,10 +117,10 @@ class PLATFORM_EXPORT ShapingLineBreaker final {
bool backwards) const;
scoped_refptr<ShapeResult> Shape(TextDirection, unsigned start, unsigned end);
- scoped_refptr<const ShapeResult> ShapeToEnd(unsigned start,
- unsigned first_safe,
- unsigned range_start,
- unsigned range_end);
+ scoped_refptr<const ShapeResultView> ShapeToEnd(unsigned start,
+ unsigned first_safe,
+ unsigned range_start,
+ unsigned range_end);
const HarfBuzzShaper* shaper_;
const Font* font_;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker_test.cc b/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker_test.cc
index 3b62eec89a7..25ba3d14546 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker_test.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/shaping/shaping_line_breaker_test.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_test_utilities.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_test_info.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -19,12 +20,12 @@ namespace blink {
namespace {
-scoped_refptr<const ShapeResult> ShapeLine(ShapingLineBreaker* breaker,
- unsigned start_offset,
- LayoutUnit available_space,
- unsigned* break_offset) {
+scoped_refptr<const ShapeResultView> ShapeLine(ShapingLineBreaker* breaker,
+ unsigned start_offset,
+ LayoutUnit available_space,
+ unsigned* break_offset) {
ShapingLineBreaker::Result result;
- scoped_refptr<const ShapeResult> shape_result =
+ scoped_refptr<const ShapeResultView> shape_result =
breaker->ShapeLine(start_offset, available_space, &result);
*break_offset = result.break_offset;
return shape_result;
@@ -109,7 +110,7 @@ TEST_F(ShapingLineBreakerTest, ShapeLineLatin) {
ASSERT_LT(first1->SnappedWidth(), first2->SnappedWidth());
ShapingLineBreaker breaker(&shaper, &font, result.get(), &break_iterator);
- scoped_refptr<const ShapeResult> line;
+ scoped_refptr<const ShapeResultView> line;
unsigned break_offset = 0;
// Test the case where the entire string fits.
@@ -195,7 +196,7 @@ TEST_F(ShapingLineBreakerTest, ShapeLineLatinBreakAll) {
shaper.Shape(&font, direction, 0, 16);
ShapingLineBreaker breaker(&shaper, &font, result.get(), &break_iterator);
- scoped_refptr<const ShapeResult> line;
+ scoped_refptr<const ShapeResultView> line;
unsigned break_offset = 0;
line = ShapeLine(&breaker, 0, midpoint->SnappedWidth(), &break_offset);
@@ -216,7 +217,7 @@ TEST_F(ShapingLineBreakerTest, ShapeLineZeroAvailableWidth) {
scoped_refptr<const ShapeResult> result = shaper.Shape(&font, direction);
ShapingLineBreaker breaker(&shaper, &font, result.get(), &break_iterator);
- scoped_refptr<const ShapeResult> line;
+ scoped_refptr<const ShapeResultView> line;
unsigned break_offset = 0;
LayoutUnit zero(0);
@@ -288,7 +289,7 @@ TEST_F(ShapingLineBreakerTest, ShapeLineRangeEndMidWord) {
shaper.Shape(&font, direction, 0, 2);
ShapingLineBreaker breaker(&shaper, &font, result.get(), &break_iterator);
- scoped_refptr<const ShapeResult> line;
+ scoped_refptr<const ShapeResultView> line;
unsigned break_offset = 0;
line = ShapeLine(&breaker, 0, LayoutUnit::Max(), &break_offset);
diff --git a/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.cc b/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.cc
index 520dad11c05..d742599579d 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.cc
@@ -77,20 +77,18 @@ void SimpleFontData::PlatformInit(bool subpixel_ascent_descent) {
return;
}
- SkPaint::FontMetrics metrics;
+ SkFontMetrics metrics;
- PaintFont font;
- platform_data_.SetupPaintFont(&font);
- font.SetTextEncoding(SkPaint::kGlyphID_TextEncoding);
- paint_ = font.ToSkPaint();
- paint_.getFontMetrics(&metrics);
+ font_ = SkFont();
+ platform_data_.SetupSkFont(&font_);
+ font_.getMetrics(&metrics);
float ascent;
float descent;
FontMetrics::AscentDescentWithHacks(
ascent, descent, visual_overflow_inflation_for_ascent_,
- visual_overflow_inflation_for_descent_, platform_data_, paint_,
+ visual_overflow_inflation_for_descent_, platform_data_, font_,
subpixel_ascent_descent);
font_metrics_.SetAscent(ascent);
@@ -162,7 +160,7 @@ void SimpleFontData::PlatformInit(bool subpixel_ascent_descent) {
}
#endif
- SkTypeface* face = paint_.getTypeface();
+ SkTypeface* face = font_.getTypeface();
DCHECK(face);
if (int units_per_em = face->getUnitsPerEm())
font_metrics_.SetUnitsPerEm(units_per_em);
@@ -350,7 +348,7 @@ FloatRect SimpleFontData::PlatformBoundsForGlyph(Glyph glyph) const {
static_assert(sizeof(glyph) == 2, "Glyph id should not be truncated.");
SkRect bounds;
- SkiaTextMetrics(&paint_).GetSkiaBoundsForGlyph(glyph, &bounds);
+ SkFontGetBoundsForGlyph(font_, glyph, &bounds);
return FloatRect(bounds);
}
@@ -362,7 +360,7 @@ void SimpleFontData::BoundsForGlyphs(const Vector<Glyph, 256>& glyphs,
return;
DCHECK_EQ(bounds->size(), glyphs.size());
- SkiaTextMetrics(&paint_).GetSkiaBoundsForGlyphs(glyphs, bounds->data());
+ SkFontGetBoundsForGlyphs(font_, glyphs, bounds->data());
}
float SimpleFontData::PlatformWidthForGlyph(Glyph glyph) const {
@@ -371,7 +369,7 @@ float SimpleFontData::PlatformWidthForGlyph(Glyph glyph) const {
static_assert(sizeof(glyph) == 2, "Glyph id should not be truncated.");
- return SkiaTextMetrics(&paint_).GetSkiaWidthForGlyph(glyph);
+ return SkFontGetWidthForGlyph(font_, glyph);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.h b/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.h
index cc4a85d261e..055acafeff3 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/simple_font_data.h
@@ -24,7 +24,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SIMPLE_FONT_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SIMPLE_FONT_DATA_H_
-#include <SkPaint.h>
+#include <SkFont.h>
#include <memory>
#include <utility>
@@ -170,7 +170,7 @@ class PLATFORM_EXPORT SimpleFontData : public FontData {
float avg_char_width_;
FontPlatformData platform_data_;
- SkPaint paint_;
+ SkFont font_;
Glyph space_glyph_;
float space_width_;
diff --git a/chromium/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc b/chromium/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc
index 0c49c09a536..90898dbc4a8 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/skia/font_cache_skia.cc
@@ -166,14 +166,14 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
sans_creation_params,
- (FontFamilyNames::Sans));
+ (font_family_names::kSans));
font_platform_data = GetFontPlatformData(description, sans_creation_params,
AlternateFontName::kLastResort);
}
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
arial_creation_params,
- (FontFamilyNames::Arial));
+ (font_family_names::kArial));
font_platform_data = GetFontPlatformData(description, arial_creation_params,
AlternateFontName::kLastResort);
}
@@ -182,7 +182,7 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
msuigothic_creation_params,
- (FontFamilyNames::MS_UI_Gothic));
+ (font_family_names::kMSUIGothic));
font_platform_data =
GetFontPlatformData(description, msuigothic_creation_params,
AlternateFontName::kLastResort);
@@ -190,7 +190,7 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
mssansserif_creation_params,
- (FontFamilyNames::Microsoft_Sans_Serif));
+ (font_family_names::kMicrosoftSansSerif));
font_platform_data =
GetFontPlatformData(description, mssansserif_creation_params,
AlternateFontName::kLastResort);
@@ -198,21 +198,21 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
segoeui_creation_params,
- (FontFamilyNames::Segoe_UI));
+ (font_family_names::kSegoeUI));
font_platform_data = GetFontPlatformData(
description, segoeui_creation_params, AlternateFontName::kLastResort);
}
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
calibri_creation_params,
- (FontFamilyNames::Calibri));
+ (font_family_names::kCalibri));
font_platform_data = GetFontPlatformData(
description, calibri_creation_params, AlternateFontName::kLastResort);
}
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
timesnewroman_creation_params,
- (FontFamilyNames::Times_New_Roman));
+ (font_family_names::kTimesNewRoman));
font_platform_data =
GetFontPlatformData(description, timesnewroman_creation_params,
AlternateFontName::kLastResort);
@@ -220,7 +220,7 @@ scoped_refptr<SimpleFontData> FontCache::GetLastResortFallbackFont(
if (!font_platform_data) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(const FontFaceCreationParams,
couriernew_creation_params,
- (FontFamilyNames::Courier_New));
+ (font_family_names::kCourierNew));
font_platform_data =
GetFontPlatformData(description, couriernew_creation_params,
AlternateFontName::kLastResort);
@@ -249,7 +249,7 @@ sk_sp<SkTypeface> FontCache::CreateTypeface(
#endif
AtomicString family = creation_params.Family();
- DCHECK_NE(family, FontFamilyNames::system_ui);
+ DCHECK_NE(family, font_family_names::kSystemUi);
// If we're creating a fallback font (e.g. "-webkit-monospace"), convert the
// name into the fallback name (like "monospace") that fontconfig understands.
if (!family.length() || family.StartsWith("-webkit-")) {
diff --git a/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.cc b/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.cc
index 77ec6209fab..73a48b721be 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.cc
@@ -7,6 +7,7 @@
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
+#include <SkFont.h>
#include <SkPath.h>
namespace blink {
@@ -18,33 +19,37 @@ T* advance_by_byte_size(T* p, unsigned byte_size) {
return reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(p) + byte_size);
}
-} // namespace
-
-SkiaTextMetrics::SkiaTextMetrics(const SkPaint* paint) : paint_(paint) {
- CHECK(paint_->getTextEncoding() == SkPaint::kGlyphID_TextEncoding);
+template <class T>
+const T* advance_by_byte_size(const T* p, unsigned byte_size) {
+ return reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(p) +
+ byte_size);
}
-void SkiaTextMetrics::GetGlyphWidthForHarfBuzz(hb_codepoint_t codepoint,
- hb_position_t* width) {
+} // namespace
+
+void SkFontGetGlyphWidthForHarfBuzz(const SkFont& font,
+ hb_codepoint_t codepoint,
+ hb_position_t* width) {
DCHECK_LE(codepoint, 0xFFFFu);
CHECK(width);
SkScalar sk_width;
uint16_t glyph = codepoint;
- paint_->getTextWidths(&glyph, sizeof(glyph), &sk_width, nullptr);
- if (!paint_->isSubpixelText())
+ font.getWidths(&glyph, 1, &sk_width, nullptr);
+ if (!font.isSubpixel())
sk_width = SkScalarRoundToInt(sk_width);
*width = SkiaScalarToHarfBuzzPosition(sk_width);
}
-void SkiaTextMetrics::GetGlyphWidthForHarfBuzz(unsigned count,
- hb_codepoint_t* glyphs,
- unsigned glyph_stride,
- hb_position_t* advances,
- unsigned advance_stride) {
- // Batch the call to getTextWidths because its function entry cost is not
- // cheap. getTextWidths accepts multiple glyphd ID, but not from a sparse
+void SkFontGetGlyphWidthForHarfBuzz(const SkFont& font,
+ unsigned count,
+ const hb_codepoint_t* glyphs,
+ const unsigned glyph_stride,
+ hb_position_t* advances,
+ unsigned advance_stride) {
+ // Batch the call to getWidths because its function entry cost is not
+ // cheap. getWidths accepts multiple glyphd ID, but not from a sparse
// array that copy them to a regular array.
Vector<Glyph, 256> glyph_array(count);
for (unsigned i = 0; i < count;
@@ -52,10 +57,9 @@ void SkiaTextMetrics::GetGlyphWidthForHarfBuzz(unsigned count,
glyph_array[i] = *glyphs;
}
Vector<SkScalar, 256> sk_width_array(count);
- paint_->getTextWidths(glyph_array.data(), sizeof(Glyph) * count,
- sk_width_array.data(), nullptr);
+ font.getWidths(glyph_array.data(), count, sk_width_array.data(), nullptr);
- if (!paint_->isSubpixelText()) {
+ if (!font.isSubpixel()) {
for (unsigned i = 0; i < count; i++)
sk_width_array[i] = SkScalarRoundToInt(sk_width_array[i]);
}
@@ -67,21 +71,34 @@ void SkiaTextMetrics::GetGlyphWidthForHarfBuzz(unsigned count,
}
}
-void SkiaTextMetrics::GetGlyphExtentsForHarfBuzz(hb_codepoint_t codepoint,
- hb_glyph_extents_t* extents) {
+// HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
+// fallback mark positioning, i.e. the situation when the font does not have
+// mark anchors or other mark positioning rules, but instead HarfBuzz is
+// supposed to heuristically place combining marks around base glyphs. HarfBuzz
+// does this by measuring "ink boxes" of glyphs, and placing them according to
+// Unicode mark classes. Above, below, centered or left or right, etc.
+void SkFontGetGlyphExtentsForHarfBuzz(const SkFont& font,
+ hb_codepoint_t codepoint,
+ hb_glyph_extents_t* extents) {
DCHECK_LE(codepoint, 0xFFFFu);
CHECK(extents);
SkRect sk_bounds;
uint16_t glyph = codepoint;
- paint_->getTextWidths(&glyph, sizeof(glyph), nullptr, &sk_bounds);
- if (!paint_->isSubpixelText()) {
+#if defined(OS_MACOSX)
+ // TODO(drott): Remove this once we have better metrics bounds
+ // on Mac, https://bugs.chromium.org/p/skia/issues/detail?id=5328
+ SkPath path;
+ font.getPath(glyph, &path);
+ sk_bounds = path.getBounds();
+#else
+ font.getWidths(&glyph, 1, nullptr, &sk_bounds);
+#endif
+ if (!font.isSubpixel()) {
// Use roundOut() rather than round() to avoid rendering glyphs
// outside the visual overflow rect. crbug.com/452914.
- SkIRect ir;
- sk_bounds.roundOut(&ir);
- sk_bounds.set(ir);
+ sk_bounds.set(sk_bounds.roundOut());
}
// Invert y-axis because Skia is y-grows-down but we set up HarfBuzz to be
@@ -92,36 +109,36 @@ void SkiaTextMetrics::GetGlyphExtentsForHarfBuzz(hb_codepoint_t codepoint,
extents->height = SkiaScalarToHarfBuzzPosition(-sk_bounds.height());
}
-void SkiaTextMetrics::GetSkiaBoundsForGlyph(Glyph glyph, SkRect* bounds) {
+void SkFontGetBoundsForGlyph(const SkFont& font, Glyph glyph, SkRect* bounds) {
#if defined(OS_MACOSX)
// TODO(drott): Remove this once we have better metrics bounds
// on Mac, https://bugs.chromium.org/p/skia/issues/detail?id=5328
SkPath path;
- paint_->getTextPath(&glyph, sizeof(glyph), 0, 0, &path);
+ font.getPath(glyph, &path);
*bounds = path.getBounds();
#else
- paint_->getTextWidths(&glyph, sizeof(glyph), nullptr, bounds);
+ font.getWidths(&glyph, 1, nullptr, bounds);
#endif
- if (!paint_->isSubpixelText()) {
+ if (!font.isSubpixel()) {
SkIRect ir;
bounds->roundOut(&ir);
bounds->set(ir);
}
}
-void SkiaTextMetrics::GetSkiaBoundsForGlyphs(const Vector<Glyph, 256>& glyphs,
- SkRect* bounds) {
+void SkFontGetBoundsForGlyphs(const SkFont& font,
+ const Vector<Glyph, 256>& glyphs,
+ SkRect* bounds) {
#if defined(OS_MACOSX)
for (unsigned i = 0; i < glyphs.size(); i++) {
- GetSkiaBoundsForGlyph(glyphs[i], &bounds[i]);
+ SkFontGetBoundsForGlyph(font, glyphs[i], &bounds[i]);
}
#else
static_assert(sizeof(Glyph) == 2, "Skia expects 2 bytes glyph id.");
- paint_->getTextWidths(glyphs.data(), sizeof(Glyph) * glyphs.size(), nullptr,
- bounds);
+ font.getWidths(glyphs.data(), glyphs.size(), nullptr, bounds);
- if (!paint_->isSubpixelText()) {
+ if (!font.isSubpixel()) {
for (unsigned i = 0; i < glyphs.size(); i++) {
SkIRect ir;
bounds[i].roundOut(&ir);
@@ -131,17 +148,17 @@ void SkiaTextMetrics::GetSkiaBoundsForGlyphs(const Vector<Glyph, 256>& glyphs,
#endif
}
-float SkiaTextMetrics::GetSkiaWidthForGlyph(Glyph glyph) {
+float SkFontGetWidthForGlyph(const SkFont& font, Glyph glyph) {
SkScalar sk_width;
- paint_->getTextWidths(&glyph, sizeof(glyph), &sk_width, nullptr);
+ font.getWidths(&glyph, 1, &sk_width, nullptr);
- if (!paint_->isSubpixelText())
+ if (!font.isSubpixel())
sk_width = SkScalarRoundToInt(sk_width);
return SkScalarToFloat(sk_width);
}
-hb_position_t SkiaTextMetrics::SkiaScalarToHarfBuzzPosition(SkScalar value) {
+hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value) {
// We treat HarfBuzz hb_position_t as 16.16 fixed-point.
static const int kHbPosition1 = 1 << 16;
return clampTo<int>(value * kHbPosition1);
diff --git a/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.h b/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.h
index 787d8af0375..6a72122ee22 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.h
+++ b/chromium/third_party/blink/renderer/platform/fonts/skia/skia_text_metrics.h
@@ -7,33 +7,34 @@
#include "third_party/blink/renderer/platform/fonts/glyph.h"
-#include <SkPaint.h>
#include <hb.h>
#include "third_party/blink/renderer/platform/wtf/vector.h"
+#include "third_party/skia/include/core/SkRect.h"
-namespace blink {
-
-class SkiaTextMetrics final {
- public:
- SkiaTextMetrics(const SkPaint*);
-
- void GetGlyphWidthForHarfBuzz(hb_codepoint_t, hb_position_t* width);
- void GetGlyphWidthForHarfBuzz(unsigned count,
- hb_codepoint_t* first_glyph,
- unsigned glyph_stride,
- hb_position_t* first_advance,
- unsigned advance_stride);
- void GetGlyphExtentsForHarfBuzz(hb_codepoint_t, hb_glyph_extents_t*);
+class SkFont;
- void GetSkiaBoundsForGlyph(Glyph, SkRect* bounds);
- void GetSkiaBoundsForGlyphs(const Vector<Glyph, 256>&, SkRect*);
- float GetSkiaWidthForGlyph(Glyph);
-
- static hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value);
+namespace blink {
- private:
- const SkPaint* paint_;
-};
+void SkFontGetGlyphWidthForHarfBuzz(const SkFont&,
+ hb_codepoint_t,
+ hb_position_t* width);
+void SkFontGetGlyphWidthForHarfBuzz(const SkFont&,
+ unsigned count,
+ const hb_codepoint_t* first_glyph,
+ unsigned glyph_stride,
+ hb_position_t* first_advance,
+ unsigned advance_stride);
+void SkFontGetGlyphExtentsForHarfBuzz(const SkFont&,
+ hb_codepoint_t,
+ hb_glyph_extents_t*);
+
+void SkFontGetBoundsForGlyph(const SkFont&, Glyph, SkRect* bounds);
+void SkFontGetBoundsForGlyphs(const SkFont&,
+ const Vector<Glyph, 256>&,
+ SkRect*);
+float SkFontGetWidthForGlyph(const SkFont&, Glyph);
+
+hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/utf16_text_iterator.cc b/chromium/third_party/blink/renderer/platform/fonts/utf16_text_iterator.cc
index 3f175552aea..abceeae6a9a 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/utf16_text_iterator.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/utf16_text_iterator.cc
@@ -53,7 +53,7 @@ bool UTF16TextIterator::ConsumeSurrogatePair(UChar32& character) {
DCHECK(U16_IS_SURROGATE(character));
if (!IsValidSurrogatePair(character)) {
- character = WTF::Unicode::kReplacementCharacter;
+ character = WTF::unicode::kReplacementCharacter;
return true;
}
diff --git a/chromium/third_party/blink/renderer/platform/fonts/web_font_render_style.cc b/chromium/third_party/blink/renderer/platform/fonts/web_font_render_style.cc
index bf7f7c5d072..b63f8a2051d 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/web_font_render_style.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/web_font_render_style.cc
@@ -7,14 +7,15 @@
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
-#include "third_party/blink/renderer/platform/fonts/paint_font.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
+
+#include <SkFont.h>
namespace blink {
namespace {
-SkPaint::Hinting g_skia_hinting = SkPaint::kNormal_Hinting;
+SkFontHinting g_skia_hinting = SkFontHinting::kNormal;
bool g_use_skia_auto_hint = true;
bool g_use_skia_bitmaps = true;
bool g_use_skia_anti_alias = true;
@@ -28,7 +29,7 @@ void WebFontRenderStyle::SetSkiaFontManager(sk_sp<SkFontMgr> font_mgr) {
}
// static
-void WebFontRenderStyle::SetHinting(SkPaint::Hinting hinting) {
+void WebFontRenderStyle::SetHinting(SkFontHinting hinting) {
g_skia_hinting = hinting;
}
@@ -66,8 +67,7 @@ void WebFontRenderStyle::SetSystemFontFamily(const WebString& name) {
WebFontRenderStyle WebFontRenderStyle::GetDefault() {
WebFontRenderStyle result;
result.use_anti_alias = g_use_skia_anti_alias;
- result.hint_style = SkPaint::kNo_Hinting;
- result.hint_style = g_skia_hinting;
+ result.hint_style = static_cast<char>(g_skia_hinting);
result.use_bitmaps = g_use_skia_bitmaps;
result.use_auto_hint = g_use_skia_auto_hint;
result.use_anti_alias = g_use_skia_anti_alias;
@@ -97,23 +97,46 @@ void WebFontRenderStyle::OverrideWith(const WebFontRenderStyle& other) {
use_subpixel_positioning = other.use_subpixel_positioning;
}
-void WebFontRenderStyle::ApplyToPaintFont(PaintFont& font,
- float device_scale_factor) const {
- auto sk_hint_style = static_cast<SkPaint::Hinting>(hint_style);
- font.SetAntiAlias(use_anti_alias);
- font.SetHinting(sk_hint_style);
- font.SetEmbeddedBitmapText(use_bitmaps);
- font.SetAutohinted(use_auto_hint);
+void WebFontRenderStyle::ApplyToSkPaint(SkPaint& font,
+ float device_scale_factor) const {
+ auto sk_hint_style = static_cast<SkFontHinting>(hint_style);
+ font.setAntiAlias(use_anti_alias);
+ font.setHinting(sk_hint_style);
+ font.setEmbeddedBitmapText(use_bitmaps);
+ font.setAutohinted(use_auto_hint);
if (use_anti_alias)
- font.SetLcdRenderText(use_subpixel_rendering);
+ font.setLCDRenderText(use_subpixel_rendering);
+
+ // Force-enable subpixel positioning, except when full hinting is requested on
+ // low-dpi screen or when running web tests.
+ bool force_subpixel_positioning =
+ !WebTestSupport::IsRunningWebTest() &&
+ (sk_hint_style != SkFontHinting::kFull || device_scale_factor > 1.0f);
+
+ font.setSubpixelText(force_subpixel_positioning || use_subpixel_positioning);
+}
+
+void WebFontRenderStyle::ApplyToSkFont(SkFont* font,
+ float device_scale_factor) const {
+ auto sk_hint_style = static_cast<SkFontHinting>(hint_style);
+ font->setHinting(sk_hint_style);
+ font->setEmbeddedBitmaps(use_bitmaps);
+ font->setForceAutoHinting(use_auto_hint);
+ if (use_anti_alias && use_subpixel_rendering) {
+ font->setEdging(SkFont::Edging::kSubpixelAntiAlias);
+ } else if (use_anti_alias) {
+ font->setEdging(SkFont::Edging::kAntiAlias);
+ } else {
+ font->setEdging(SkFont::Edging::kAlias);
+ }
// Force-enable subpixel positioning, except when full hinting is requested on
- // low-dpi screen or when running layout tests.
+ // low-dpi screen or when running web tests.
bool force_subpixel_positioning =
- !LayoutTestSupport::IsRunningLayoutTest() &&
- (sk_hint_style != SkPaint::kFull_Hinting || device_scale_factor > 1.0f);
+ !WebTestSupport::IsRunningWebTest() &&
+ (sk_hint_style != SkFontHinting::kFull || device_scale_factor > 1.0f);
- font.SetSubpixelText(force_subpixel_positioning || use_subpixel_positioning);
+ font->setSubpixel(force_subpixel_positioning || use_subpixel_positioning);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/fonts/win/font_platform_data_win.cc b/chromium/third_party/blink/renderer/platform/fonts/win/font_platform_data_win.cc
index e4ed5f67725..4fc4b20ddfa 100644
--- a/chromium/third_party/blink/renderer/platform/fonts/win/font_platform_data_win.cc
+++ b/chromium/third_party/blink/renderer/platform/fonts/win/font_platform_data_win.cc
@@ -32,35 +32,26 @@
#include "third_party/blink/renderer/platform/fonts/font_platform_data.h"
#include <windows.h>
+#include "SkFont.h"
#include "SkTypeface.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
-// Maximum font size, in pixels, at which embedded bitmaps will be used
-// if available.
-const float kMaxSizeForEmbeddedBitmap = 24.0f;
-
-void FontPlatformData::SetupPaintFont(PaintFont* font,
- float,
- const Font*) const {
- const float ts = text_size_ >= 0 ? text_size_ : 12;
- font->SetTextSize(SkFloatToScalar(text_size_));
- font->SetTypeface(typeface_);
- font->SetFakeBoldText(synthetic_bold_);
- font->SetTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
+void FontPlatformData::SetupSkPaint(SkPaint* font, float, const Font*) const {
+ font->setTextSize(SkFloatToScalar(text_size_));
+ font->setTypeface(typeface_);
+ font->setFakeBoldText(synthetic_bold_);
+ font->setTextSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
uint32_t text_flags = PaintTextFlags();
- uint32_t flags = font->flags();
+ uint32_t flags = font->getFlags();
static const uint32_t kTextFlagsMask =
SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag |
SkPaint::kEmbeddedBitmapText_Flag | SkPaint::kSubpixelText_Flag;
flags &= ~kTextFlagsMask;
- if (ts <= kMaxSizeForEmbeddedBitmap)
- flags |= SkPaint::kEmbeddedBitmapText_Flag;
-
// Only use sub-pixel positioning if anti aliasing is enabled. Otherwise,
// without font smoothing, subpixel text positioning leads to uneven spacing
// since subpixel test placement coordinates would be passed to Skia, which
@@ -70,16 +61,48 @@ void FontPlatformData::SetupPaintFont(PaintFont* font,
if (text_flags & SkPaint::kAntiAlias_Flag)
flags |= SkPaint::kSubpixelText_Flag;
- if (LayoutTestSupport::IsRunningLayoutTest() &&
- !LayoutTestSupport::IsTextSubpixelPositioningAllowedForTest())
+ if (WebTestSupport::IsRunningWebTest() &&
+ !WebTestSupport::IsTextSubpixelPositioningAllowedForTest())
flags &= ~SkPaint::kSubpixelText_Flag;
SkASSERT(!(text_flags & ~kTextFlagsMask));
flags |= text_flags;
- font->SetFlags(flags);
+ font->setFlags(flags);
+
+ font->setEmbeddedBitmapText(!avoid_embedded_bitmaps_);
+}
+
+void FontPlatformData::SetupSkFont(SkFont* font, float, const Font*) const {
+ font->setSize(SkFloatToScalar(text_size_));
+ font->setTypeface(typeface_);
+ font->setEmbolden(synthetic_bold_);
+ font->setSkewX(synthetic_italic_ ? -SK_Scalar1 / 4 : 0);
+
+ uint32_t text_flags = PaintTextFlags();
+ if (text_flags & SkPaint::kLCDRenderText_Flag) {
+ font->setEdging(SkFont::Edging::kSubpixelAntiAlias);
+ } else if (text_flags & SkPaint::kAntiAlias_Flag) {
+ font->setEdging(SkFont::Edging::kAntiAlias);
+ } else {
+ font->setEdging(SkFont::Edging::kAlias);
+ }
+ font->setSubpixel(SkToBool(text_flags & SkPaint::kSubpixelText_Flag));
+
+ // Only use sub-pixel positioning if anti aliasing is enabled. Otherwise,
+ // without font smoothing, subpixel text positioning leads to uneven spacing
+ // since subpixel test placement coordinates would be passed to Skia, which
+ // only has non-antialiased glyphs to draw, so they necessarily get clamped at
+ // pixel positions, which leads to uneven spacing, either too close or too far
+ // away from adjacent glyphs. We avoid this by linking the two flags.
+ if (text_flags & SkPaint::kAntiAlias_Flag)
+ font->setSubpixel(true);
+
+ if (WebTestSupport::IsRunningWebTest() &&
+ !WebTestSupport::IsTextSubpixelPositioningAllowedForTest())
+ font->setSubpixel(false);
- font->SetEmbeddedBitmapText(!avoid_embedded_bitmaps_);
+ font->setEmbeddedBitmaps(!avoid_embedded_bitmaps_);
}
static bool IsWebFont(const String& family_name) {
@@ -91,8 +114,8 @@ static bool IsWebFont(const String& family_name) {
}
static int ComputePaintTextFlags(String font_family_name) {
- if (LayoutTestSupport::IsRunningLayoutTest())
- return LayoutTestSupport::IsFontAntialiasingEnabledForTest()
+ if (WebTestSupport::IsRunningWebTest())
+ return WebTestSupport::IsFontAntialiasingEnabledForTest()
? SkPaint::kAntiAlias_Flag
: 0;
diff --git a/chromium/third_party/blink/renderer/platform/geometry/DEPS b/chromium/third_party/blink/renderer/platform/geometry/DEPS
index 9b2fc5f0f91..6eb877bf5f7 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/DEPS
+++ b/chromium/third_party/blink/renderer/platform/geometry/DEPS
@@ -8,7 +8,6 @@ include_rules = [
# Dependencies.
"+cc/base/region.h",
"+third_party/blink/renderer/platform/json",
- "+third_party/blink/renderer/platform/layout_unit.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/wtf",
"+ui/gfx/geometry",
diff --git a/chromium/third_party/blink/renderer/platform/geometry/blend.h b/chromium/third_party/blink/renderer/platform/geometry/blend.h
index 6db4f3c923a..f0aaa48102b 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/blend.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/blend.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/int_point.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
diff --git a/chromium/third_party/blink/renderer/platform/calculation_value.h b/chromium/third_party/blink/renderer/platform/geometry/calculation_value.h
index 060dfe71642..24c7ae0b989 100644
--- a/chromium/third_party/blink/renderer/platform/calculation_value.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/calculation_value.h
@@ -28,12 +28,12 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_CALCULATION_VALUE_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_CALCULATION_VALUE_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_CALCULATION_VALUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_CALCULATION_VALUE_H_
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/platform/length.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
namespace blink {
@@ -70,4 +70,4 @@ class PLATFORM_EXPORT CalculationValue : public RefCounted<CalculationValue> {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_CALCULATION_VALUE_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_CALCULATION_VALUE_H_
diff --git a/chromium/third_party/blink/renderer/platform/geometry/float_box_test.cc b/chromium/third_party/blink/renderer/platform/geometry/float_box_test.cc
index 09f1ef2dbc6..14e0410e1cd 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/float_box_test.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/float_box_test.cc
@@ -46,11 +46,11 @@ TEST(FloatBoxTest, SimpleCreationTest) {
TEST(FloatBoxTest, PositionTest) {
FloatBox box(0, 0, 0, 4, 4, 4);
box.Move(FloatPoint3D(1, 2, 3));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(1, 2, 3, 4, 4, 4), box);
box.SetOrigin(FloatPoint3D(-1, -2, -3));
box.Move(FloatPoint3D(-1, -2, -3));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-2, -4, -6, 4, 4, 4), box);
}
@@ -60,36 +60,36 @@ TEST(FloatBoxTest, CopyTest) {
EXPECT_EQ(box, box2);
box.SetSize(FloatPoint3D(3, 3, 3));
EXPECT_NE(box, box2);
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(1, 2, 3, 3, 3, 3), box);
}
TEST(FloatBoxTest, FlattenTest) {
FloatBox box(1, 2, 3, 4, 4, 4);
box.Flatten();
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(1, 2, 0, 4, 4, 0), box);
}
TEST(FloatBoxTest, ExpandTests) {
FloatBox box;
box.ExpandTo(FloatPoint3D(10, -3, 2));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, -3, 0, 10, 3, 2), box);
box.ExpandTo(FloatPoint3D(-15, 6, 8));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-15, -3, 0, 25, 9, 8), box);
box = FloatBox();
box.ExpandTo(FloatPoint3D(-3, 6, 9), FloatPoint3D(-2, 10, 11));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-3, 0, 0, 3, 10, 11), box);
box = FloatBox();
box.ExpandTo(FloatBox(-10, -10, -10, 3, 30, 40));
box.ExpandTo(FloatBox(-11, 3, 50, 10, 15, 1));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-11, -10, -10, 11, 30, 61), box);
}
@@ -98,13 +98,13 @@ TEST(FloatBoxTest, UnionTest) {
EXPECT_TRUE(box.IsEmpty());
FloatBox unioned_box(3, 5, 6, 5, 3, 9);
box.UnionBounds(unioned_box);
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual, unioned_box, box);
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual, unioned_box, box);
box.UnionBounds(FloatBox());
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual, unioned_box, box);
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual, unioned_box, box);
box.UnionBounds(FloatBox(0, 0, 0, 1, 1, 1));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 8, 8, 15), box);
}
diff --git a/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.cc b/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.cc
index 0f8ec3833a1..bd5f9ac176a 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.cc
@@ -30,10 +30,10 @@
const static float kTestEpsilon = 1e-6;
namespace blink {
-namespace FloatBoxTest {
+namespace float_box_test {
bool ApproximatelyEqual(const float& a, const float& b) {
- return GeometryTest::ApproximatelyEqual(a, b, kTestEpsilon);
+ return geometry_test::ApproximatelyEqual(a, b, kTestEpsilon);
}
bool ApproximatelyEqual(const FloatBox& a, const FloatBox& b) {
@@ -77,5 +77,5 @@ testing::AssertionResult AssertContains(const char* expr,
return testing::AssertionSuccess();
}
-} // namespace FloatBoxTest
+} // namespace float_box_test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.h b/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.h
index c155aa4aa45..57f59eead60 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/float_box_test_helpers.h
@@ -30,7 +30,7 @@ class FloatBox;
bool ApproximatelyEqual(const float&, const float&);
-namespace FloatBoxTest {
+namespace float_box_test {
bool ApproximatelyEqual(const float&, const float&);
bool ApproximatelyEqual(const FloatBox&, const FloatBox&);
testing::AssertionResult AssertAlmostEqual(const char*,
@@ -41,7 +41,7 @@ testing::AssertionResult AssertContains(const char*,
const char*,
const FloatBox&,
const FloatBox&);
-} // namespace FloatBoxTest
+} // namespace float_box_test
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_FLOAT_BOX_TEST_HELPERS_H_
diff --git a/chromium/third_party/blink/renderer/platform/geometry/float_point_test.cc b/chromium/third_party/blink/renderer/platform/geometry/float_point_test.cc
index d9489e20178..c7d15480669 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/float_point_test.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/float_point_test.cc
@@ -12,19 +12,19 @@ namespace blink {
TEST(FloatPointTest, LengthTest) {
// Sanity check the Pythagorean triples 3-4-5 and 5-12-13
FloatPoint p1 = FloatPoint(3.f, 4.f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, p1.length(), 5.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, p1.length(), 5.f);
FloatPoint p2 = FloatPoint(5.f, 12.f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, p2.length(), 13.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, p2.length(), 13.f);
// Test very small numbers. This fails under the old implementation of
// FloatPoint::length(): `return sqrtf(lengthSquared());'
FloatPoint p3 = FloatPoint(.5e-20f, .5e-20f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, p3.length(),
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, p3.length(),
.707106781186548e-20f);
// Test very large numbers.
FloatPoint p4 = FloatPoint(.5e20f, .5e20f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, p4.length(),
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, p4.length(),
.707106781186548e20f);
}
diff --git a/chromium/third_party/blink/renderer/platform/geometry/float_rect_test.cc b/chromium/third_party/blink/renderer/platform/geometry/float_rect_test.cc
index d2f6098b2d8..99451c77ac4 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/float_rect_test.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/float_rect_test.cc
@@ -31,107 +31,107 @@ TEST(FloatRectTest, SquaredDistanceToTest) {
// `1` case
FloatPoint p1(80, 80);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p1),
- 800.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p1), 800.f);
FloatPoint p2(-10, -10);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p2),
- 24200.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p2), 24200.f);
FloatPoint p3(80, -10);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p3),
- 12500.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p3), 12500.f);
// `2` case
FloatPoint p4(110, 80);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p4),
- 400.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p4), 400.f);
FloatPoint p5(150, 0);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p5),
- 10000.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p5), 10000.f);
FloatPoint p6(180, -10);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p6),
- 12100.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p6), 12100.f);
// `3` case
FloatPoint p7(400, 80);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p7),
- 2900.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p7), 2900.f);
FloatPoint p8(360, -10);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p8),
- 12200.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p8), 12200.f);
// `4` case
FloatPoint p9(80, 110);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, r1.SquaredDistanceTo(p9),
- 400.f);
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
+ r1.SquaredDistanceTo(p9), 400.f);
FloatPoint p10(-10, 180);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p10), 12100.f);
// `5`(& In) case
FloatPoint p11(100, 100);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p11), 0.f);
FloatPoint p12(150, 100);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p12), 0.f);
FloatPoint p13(350, 100);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p13), 0.f);
FloatPoint p14(350, 150);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p14), 0.f);
FloatPoint p15(350, 250);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p15), 0.f);
FloatPoint p16(150, 250);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p16), 0.f);
FloatPoint p17(100, 250);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p17), 0.f);
FloatPoint p18(100, 150);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p18), 0.f);
FloatPoint p19(150, 150);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p19), 0.f);
// `6` case
FloatPoint p20(380, 150);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p20), 900.f);
// `7` case
FloatPoint p21(80, 280);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p21), 1300.f);
FloatPoint p22(-10, 300);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p22), 14600.f);
// `8` case
FloatPoint p23(180, 300);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p23), 2500.f);
// `9` case
FloatPoint p24(450, 450);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual,
r1.SquaredDistanceTo(p24), 50000.f);
}
diff --git a/chromium/third_party/blink/renderer/platform/geometry/float_size_test.cc b/chromium/third_party/blink/renderer/platform/geometry/float_size_test.cc
index c9e185b7bb4..86e3e5411b9 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/float_size_test.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/float_size_test.cc
@@ -12,20 +12,20 @@ namespace blink {
TEST(FloatSizeTest, DiagonalLengthTest) {
// Sanity check the Pythagorean triples 3-4-5 and 5-12-13
FloatSize s1 = FloatSize(3.f, 4.f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, s1.DiagonalLength(),
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, s1.DiagonalLength(),
5.f);
FloatSize s2 = FloatSize(5.f, 12.f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, s2.DiagonalLength(),
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, s2.DiagonalLength(),
13.f);
// Test very small numbers.
FloatSize s3 = FloatSize(.5e-20f, .5e-20f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, s3.DiagonalLength(),
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, s3.DiagonalLength(),
.707106781186548e-20f);
// Test very large numbers.
FloatSize s4 = FloatSize(.5e20f, .5e20f);
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, s4.DiagonalLength(),
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, s4.DiagonalLength(),
.707106781186548e20f);
}
diff --git a/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.cc b/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.cc
index 77d0e7625a0..9acb3161de1 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.cc
@@ -8,7 +8,7 @@
#include <math.h>
namespace blink {
-namespace GeometryTest {
+namespace geometry_test {
bool ApproximatelyEqual(float a, float b, float test_epsilon) {
float abs_a = ::fabs(a);
@@ -39,5 +39,5 @@ testing::AssertionResult AssertAlmostEqual(const char* actual_expr,
return testing::AssertionSuccess();
}
-} // namespace GeometryTest
+} // namespace geometry_test
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.h b/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.h
index 9ebef7d8c4b..6853994677c 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/geometry_test_helpers.h
@@ -8,7 +8,7 @@
#include <gtest/gtest.h>
namespace blink {
-namespace GeometryTest {
+namespace geometry_test {
bool ApproximatelyEqual(float, float, float test_epsilon);
testing::AssertionResult AssertAlmostEqual(const char* actual_expr,
@@ -17,7 +17,7 @@ testing::AssertionResult AssertAlmostEqual(const char* actual_expr,
float expected,
float test_epsilon = 1e-6);
-} // namespace GeometryTest
+} // namespace geometry_test
} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/platform/geometry/int_point.h b/chromium/third_party/blink/renderer/platform/geometry/int_point.h
index b8d637c7765..67e3f0eaf5c 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/int_point.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/int_point.h
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/saturated_arithmetic.h"
#include "third_party/blink/renderer/platform/wtf/vector_traits.h"
+#include "ui/gfx/geometry/point.h"
#if defined(OS_MACOSX)
typedef struct CGPoint CGPoint;
@@ -44,7 +45,6 @@ typedef struct CGPoint CGPoint;
#endif
namespace gfx {
-class Point;
class Vector2d;
}
@@ -58,6 +58,7 @@ class PLATFORM_EXPORT IntPoint {
constexpr IntPoint(int x, int y) : x_(x), y_(y) {}
explicit IntPoint(const IntSize& size)
: x_(size.Width()), y_(size.Height()) {}
+ explicit IntPoint(const gfx::Point& point) : x_(point.x()), y_(point.y()) {}
static IntPoint Zero() { return IntPoint(); }
diff --git a/chromium/third_party/blink/renderer/platform/geometry/layout_rect.cc b/chromium/third_party/blink/renderer/platform/geometry/layout_rect.cc
index 50af328c93a..3ef7c936253 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/layout_rect.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/layout_rect.cc
@@ -34,7 +34,7 @@
#include <algorithm>
#include "third_party/blink/renderer/platform/geometry/double_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/text/text_stream.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/platform/geometry/layout_rect_outsets.h b/chromium/third_party/blink/renderer/platform/geometry/layout_rect_outsets.h
index 9f9c4bcc6b9..3f3eccf4942 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/layout_rect_outsets.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/layout_rect_outsets.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/platform/geometry/float_rect_outsets.h"
#include "third_party/blink/renderer/platform/geometry/int_rect_outsets.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
diff --git a/chromium/third_party/blink/renderer/platform/geometry/layout_size.h b/chromium/third_party/blink/renderer/platform/geometry/layout_size.h
index ef1381db80a..e007b6c0d47 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/layout_size.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/layout_size.h
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "ui/gfx/geometry/size.h"
diff --git a/chromium/third_party/blink/renderer/platform/layout_unit.cc b/chromium/third_party/blink/renderer/platform/geometry/layout_unit.cc
index e27c262080c..f6d46bf5a8f 100644
--- a/chromium/third_party/blink/renderer/platform/layout_unit.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/layout_unit.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 "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include <ostream>
#include "third_party/blink/renderer/platform/wtf/text/text_stream.h"
diff --git a/chromium/third_party/blink/renderer/platform/layout_unit.h b/chromium/third_party/blink/renderer/platform/geometry/layout_unit.h
index c4c248e2b4e..834b3b14e98 100644
--- a/chromium/third_party/blink/renderer/platform/layout_unit.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/layout_unit.h
@@ -28,11 +28,12 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LAYOUT_UNIT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LAYOUT_UNIT_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LAYOUT_UNIT_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LAYOUT_UNIT_H_
#include <iosfwd>
#include <limits>
+#include "base/compiler_specific.h"
#include "base/numerics/safe_conversions.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -45,7 +46,7 @@ namespace blink {
#if DCHECK_IS_ON()
#define REPORT_OVERFLOW(doesOverflow) \
DLOG_IF(ERROR, !(doesOverflow)) << "LayoutUnit overflow !(" << #doesOverflow \
- << ") in " << WTF_PRETTY_FUNCTION
+ << ") in " << PRETTY_FUNCTION
#else
#define REPORT_OVERFLOW(doesOverflow) ((void)0)
#endif
@@ -199,12 +200,12 @@ class LayoutUnit {
return return_value;
}
- static const LayoutUnit Max() {
+ static constexpr LayoutUnit Max() {
LayoutUnit m;
m.value_ = std::numeric_limits<int>::max();
return m;
}
- static const LayoutUnit Min() {
+ static constexpr LayoutUnit Min() {
LayoutUnit m;
m.value_ = std::numeric_limits<int>::min();
return m;
@@ -711,4 +712,4 @@ PLATFORM_EXPORT WTF::TextStream& operator<<(WTF::TextStream&,
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LAYOUT_UNIT_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LAYOUT_UNIT_H_
diff --git a/chromium/third_party/blink/renderer/platform/layout_unit_test.cc b/chromium/third_party/blink/renderer/platform/geometry/layout_unit_test.cc
index 5eadbe8ed19..cf5509fdf4b 100644
--- a/chromium/third_party/blink/renderer/platform/layout_unit_test.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/layout_unit_test.cc
@@ -28,10 +28,10 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
-#include "testing/gtest/include/gtest/gtest.h"
#include <limits.h>
+#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/length.cc b/chromium/third_party/blink/renderer/platform/geometry/length.cc
index 6ddb1526742..da185538615 100644
--- a/chromium/third_party/blink/renderer/platform/length.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/length.cc
@@ -23,11 +23,11 @@
*
*/
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/animation/animation_utilities.h"
-#include "third_party/blink/renderer/platform/calculation_value.h"
+#include "third_party/blink/renderer/platform/geometry/blend.h"
+#include "third_party/blink/renderer/platform/geometry/calculation_value.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/length.h b/chromium/third_party/blink/renderer/platform/geometry/length.h
index 081a103d03d..c8d5b0234ed 100644
--- a/chromium/third_party/blink/renderer/platform/length.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/length.h
@@ -20,10 +20,10 @@
Boston, MA 02110-1301, USA.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_H_
-#include "third_party/blink/renderer/platform/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
@@ -305,4 +305,4 @@ class PLATFORM_EXPORT Length {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_H_
diff --git a/chromium/third_party/blink/renderer/platform/length_box.h b/chromium/third_party/blink/renderer/platform/geometry/length_box.h
index 62e23d47f33..f8008943bea 100644
--- a/chromium/third_party/blink/renderer/platform/length_box.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/length_box.h
@@ -19,13 +19,11 @@
Boston, MA 02110-1301, USA.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_BOX_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_BOX_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_BOX_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_BOX_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/text/writing_mode.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -79,4 +77,4 @@ class PLATFORM_EXPORT LengthBox {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_BOX_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_BOX_H_
diff --git a/chromium/third_party/blink/renderer/platform/length_functions.cc b/chromium/third_party/blink/renderer/platform/geometry/length_functions.cc
index 0fa4f38ba82..b61d48f5046 100644
--- a/chromium/third_party/blink/renderer/platform/length_functions.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/length_functions.cc
@@ -21,13 +21,13 @@
Boston, MA 02110-1301, USA.
*/
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
-#include "third_party/blink/renderer/platform/layout_unit.h"
-#include "third_party/blink/renderer/platform/length_point.h"
-#include "third_party/blink/renderer/platform/length_size.h"
+#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/geometry/length_point.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/length_functions.h b/chromium/third_party/blink/renderer/platform/geometry/length_functions.h
index 8d1626f3775..13219213844 100644
--- a/chromium/third_party/blink/renderer/platform/length_functions.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/length_functions.h
@@ -21,8 +21,8 @@
Boston, MA 02110-1301, USA.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_FUNCTIONS_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_FUNCTIONS_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_FUNCTIONS_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_FUNCTIONS_H_
#include "third_party/blink/renderer/platform/platform_export.h"
@@ -51,4 +51,4 @@ PLATFORM_EXPORT FloatPoint FloatPointForLengthPoint(const LengthPoint&,
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_FUNCTIONS_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_FUNCTIONS_H_
diff --git a/chromium/third_party/blink/renderer/platform/length_point.h b/chromium/third_party/blink/renderer/platform/geometry/length_point.h
index 3d9eb5b5aab..8826ec3fef6 100644
--- a/chromium/third_party/blink/renderer/platform/length_point.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/length_point.h
@@ -27,10 +27,10 @@
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_POINT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_POINT_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_POINT_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_POINT_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -63,4 +63,4 @@ struct LengthPoint {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_POINT_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_POINT_H_
diff --git a/chromium/third_party/blink/renderer/platform/length_size.h b/chromium/third_party/blink/renderer/platform/geometry/length_size.h
index 5e7eef2146b..a0e2ea17699 100644
--- a/chromium/third_party/blink/renderer/platform/length_size.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/length_size.h
@@ -18,10 +18,10 @@
Boston, MA 02110-1301, USA.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_SIZE_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_SIZE_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_SIZE_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_SIZE_H_
-#include "third_party/blink/renderer/platform/length.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
@@ -52,4 +52,4 @@ class LengthSize {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LENGTH_SIZE_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_LENGTH_SIZE_H_
diff --git a/chromium/third_party/blink/renderer/platform/geometry/region.cc b/chromium/third_party/blink/renderer/platform/geometry/region.cc
index 217ce615280..d06233399ae 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/region.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/region.cc
@@ -100,8 +100,8 @@ bool Region::Intersects(const Region& region) const {
region.shape_);
}
-double Region::Area() const {
- double area = 0.0;
+uint64_t Region::Area() const {
+ uint64_t area = 0;
for (Shape::SpanIterator span = shape_.SpansBegin(), end = shape_.SpansEnd();
span != end && span + 1 != end; ++span) {
int height = (span + 1)->y - span->y;
@@ -110,7 +110,7 @@ double Region::Area() const {
end = shape_.SegmentsEnd(span);
segment != end && segment + 1 != end; segment += 2) {
int width = *(segment + 1) - *segment;
- area += height * width;
+ area += (uint64_t)height * (uint64_t)width;
}
}
return area;
diff --git a/chromium/third_party/blink/renderer/platform/geometry/region.h b/chromium/third_party/blink/renderer/platform/geometry/region.h
index 12e29acb225..943756a9771 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/region.h
+++ b/chromium/third_party/blink/renderer/platform/geometry/region.h
@@ -71,7 +71,7 @@ class PLATFORM_EXPORT Region {
// Returns true if the query region intersects any part of this region.
bool Intersects(const Region&) const;
- double Area() const;
+ uint64_t Area() const;
#ifndef NDEBUG
void Dump() const;
diff --git a/chromium/third_party/blink/renderer/platform/geometry/region_test.cc b/chromium/third_party/blink/renderer/platform/geometry/region_test.cc
index 2b207d52327..cb64229305b 100644
--- a/chromium/third_party/blink/renderer/platform/geometry/region_test.cc
+++ b/chromium/third_party/blink/renderer/platform/geometry/region_test.cc
@@ -383,19 +383,22 @@ TEST(RegionTest, unite) {
TEST(RegionTest, Area) {
Region r;
- EXPECT_EQ(0.0, r.Area());
+ EXPECT_EQ(0u, r.Area());
r.Unite(IntRect(10, 20, 30, 10));
- EXPECT_EQ(300.0, r.Area());
+ EXPECT_EQ(300u, r.Area());
r.Unite(IntRect(20, 10, 10, 30));
- EXPECT_EQ(500.0, r.Area());
+ EXPECT_EQ(500u, r.Area());
r.Unite(IntRect(10, 10, 30, 30));
- EXPECT_EQ(900.0, r.Area());
+ EXPECT_EQ(900u, r.Area());
r.Subtract(IntRect(20, 20, 10, 10));
- EXPECT_EQ(800.0, r.Area());
+ EXPECT_EQ(800u, r.Area());
+
+ r.Unite(IntRect(0, 0, 50000, 50000));
+ EXPECT_EQ(2500000000u, r.Area());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/DEPS b/chromium/third_party/blink/renderer/platform/graphics/DEPS
index 11fa8ee237a..4a56a8d8607 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/DEPS
+++ b/chromium/third_party/blink/renderer/platform/graphics/DEPS
@@ -35,7 +35,6 @@ include_rules = [
"+third_party/blink/renderer/platform/image-encoders",
"+third_party/blink/renderer/platform/instrumentation",
"+third_party/blink/renderer/platform/json",
- "+third_party/blink/renderer/platform/length.h",
"+third_party/blink/renderer/platform/mojo/mojo_helper.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/runtime_enabled_features.h",
diff --git a/chromium/third_party/blink/renderer/platform/graphics/OWNERS b/chromium/third_party/blink/renderer/platform/graphics/OWNERS
index fa782ad69fb..78c0ada3f1e 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/OWNERS
+++ b/chromium/third_party/blink/renderer/platform/graphics/OWNERS
@@ -5,13 +5,15 @@ flackr@chromium.org
fmalita@chromium.org
fserb@chromium.org
jbroman@chromium.org
-junov@chromium.org
kbr@chromium.org
pdr@chromium.org
schenney@chromium.org
senorblanco@chromium.org
vollick@chromium.org
+# For surface ID propagation and synchronization
+samans@chromium.org
+
# lowLatency canvas
mcasas@chromium.org
diff --git a/chromium/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc b/chromium/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc
index b43b23aa7c6..3214da58c82 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/graphics/skia_texture_holder.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/gpu/GrTexture.h"
@@ -125,8 +125,7 @@ void AcceleratedStaticBitmapImage::RetainOriginalSkImage() {
original_skia_image_context_provider_wrapper_ = ContextProviderWrapper();
DCHECK(original_skia_image_);
- Thread* thread = Platform::Current()->CurrentThread();
- original_skia_image_task_runner_ = thread->GetTaskRunner();
+ original_skia_image_task_runner_ = Thread::Current()->GetTaskRunner();
}
IntSize AcceleratedStaticBitmapImage::Size() const {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc b/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc
index 5f1eca83539..5fb4c57c500 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.cc
@@ -3,16 +3,17 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl.h"
-
+#include "base/metrics/histogram_macros.h"
+#include "base/timer/elapsed_timer.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/animation_worklet_mutator.h"
#include "third_party/blink/renderer/platform/graphics/compositor_mutator_client.h"
#include "third_party/blink/renderer/platform/graphics/main_thread_mutator_client.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -21,10 +22,9 @@ AnimationWorkletMutatorDispatcherImpl::AnimationWorkletMutatorDispatcherImpl(
: client_(nullptr), weak_factory_(this) {
// By default layout tests run without threaded compositing. See
// https://crbug.com/770028 For these situations we run on the Main thread.
- host_queue_ =
- main_thread_task_runner || !Platform::Current()->CompositorThread()
- ? Platform::Current()->MainThread()->GetTaskRunner()
- : Platform::Current()->CompositorThread()->GetTaskRunner();
+ host_queue_ = main_thread_task_runner || !Thread::CompositorThread()
+ ? Thread::MainThread()->GetTaskRunner()
+ : Thread::CompositorThread()->GetTaskRunner();
}
AnimationWorkletMutatorDispatcherImpl::
@@ -67,6 +67,7 @@ void AnimationWorkletMutatorDispatcherImpl::Mutate(
TRACE_EVENT0("cc", "AnimationWorkletMutatorDispatcherImpl::mutate");
if (mutator_map_.IsEmpty())
return;
+ base::ElapsedTimer timer;
DCHECK(client_);
Vector<std::unique_ptr<AnimationWorkletDispatcherOutput>> outputs(
@@ -113,6 +114,11 @@ void AnimationWorkletMutatorDispatcherImpl::Mutate(
continue;
client_->SetMutationUpdate(std::move(output));
}
+
+ UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
+ "Animation.AnimationWorklet.Dispatcher.SynchronousMutateDuration",
+ timer.Elapsed(), base::TimeDelta::FromMicroseconds(1),
+ base::TimeDelta::FromMilliseconds(100), 50);
}
void AnimationWorkletMutatorDispatcherImpl::RegisterAnimationWorkletMutator(
diff --git a/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc b/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc
index 70218ad6320..383fe843619 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/animation_worklet_mutator_dispatcher_impl_test.cc
@@ -94,10 +94,10 @@ class AnimationWorkletMutatorDispatcherImplTest : public ::testing::Test {
std::unique_ptr<AnimationWorkletDispatcherInput> CreateTestMutatorInput() {
AnimationWorkletInput::AddAndUpdateState state1{
- {11, 1}, "test1", 5000, nullptr};
+ {11, 1}, "test1", 5000, nullptr, 1};
AnimationWorkletInput::AddAndUpdateState state2{
- {22, 2}, "test2", 5000, nullptr};
+ {22, 2}, "test2", 5000, nullptr, 1};
auto input = std::make_unique<AnimationWorkletDispatcherInput>();
input->Add(std::move(state1));
@@ -146,7 +146,7 @@ TEST_F(AnimationWorkletMutatorDispatcherImplTest,
EXPECT_CALL(*client_, SetMutationUpdateRef(_)).Times(0);
AnimationWorkletInput::AddAndUpdateState state2{
- {22, 2}, "test2", 5000, nullptr};
+ {22, 2}, "test2", 5000, nullptr, 1};
auto input = std::make_unique<AnimationWorkletDispatcherInput>();
input->Add(std::move(state2));
diff --git a/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.cc b/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.cc
index 73b05209e14..1e185d0fd63 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.cc
@@ -8,7 +8,6 @@
#include "third_party/blink/public/platform/interface_provider.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -62,10 +61,8 @@ void BeginFrameProvider::CreateCompositorFrameSinkIfNeeded() {
Platform::Current()->GetInterfaceProvider()->GetInterface(
mojo::MakeRequest(&provider));
- scoped_refptr<base::SingleThreadTaskRunner> task_runner;
- auto* scheduler = blink::Platform::Current()->CurrentThread()->Scheduler();
- if (scheduler)
- task_runner = scheduler->CompositorTaskRunner();
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner =
+ ThreadScheduler::Current()->CompositorTaskRunner();
mojom::blink::EmbeddedFrameSinkClientPtr efs_client;
efs_binding_.Bind(mojo::MakeRequest(&efs_client), task_runner);
@@ -94,7 +91,9 @@ void BeginFrameProvider::RequestBeginFrame() {
compositor_frame_sink_->SetNeedsBeginFrame(true);
}
-void BeginFrameProvider::OnBeginFrame(const viz::BeginFrameArgs& args) {
+void BeginFrameProvider::OnBeginFrame(
+ const viz::BeginFrameArgs& args,
+ WTF::HashMap<uint32_t, ::gfx::mojom::blink::PresentationFeedbackPtr>) {
// If there was no need for a BeginFrame, just skip it.
if (needs_begin_frame_ && requested_needs_begin_frame_) {
requested_needs_begin_frame_ = false;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.h b/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.h
index 409ea510d0c..bb1204b6496 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/begin_frame_provider.h
@@ -41,12 +41,10 @@ class PLATFORM_EXPORT BeginFrameProvider
const WTF::Vector<viz::ReturnedResource>& resources) final {
NOTIMPLEMENTED();
}
- void DidPresentCompositorFrame(
- uint32_t presentation_token,
- ::gfx::mojom::blink::PresentationFeedbackPtr feedback) final {
- NOTIMPLEMENTED();
- }
- void OnBeginFrame(const viz::BeginFrameArgs&) final;
+ void OnBeginFrame(
+ const viz::BeginFrameArgs&,
+ WTF::HashMap<uint32_t, ::gfx::mojom::blink::PresentationFeedbackPtr>)
+ final;
void OnBeginFramePausedChanged(bool paused) final {}
void ReclaimResources(
const WTF::Vector<viz::ReturnedResource>& resources) final {
@@ -57,6 +55,10 @@ class PLATFORM_EXPORT BeginFrameProvider
void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) final {
NOTIMPLEMENTED();
}
+ void BindSurfaceEmbedder(
+ mojom::blink::SurfaceEmbedderRequest request) override {
+ NOTIMPLEMENTED();
+ }
void ResetCompositorFrameSink();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/bitmap_image.cc b/chromium/third_party/blink/renderer/platform/graphics/bitmap_image.cc
index cc3fdee415d..0fdd3dd61b2 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/bitmap_image.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/bitmap_image.cc
@@ -41,7 +41,6 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_image.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
-#include "third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
@@ -284,8 +283,11 @@ void BitmapImage::Draw(
&flags,
WebCoreClampingModeToSkiaRectConstraint(clamp_mode));
- if (is_lazy_generated)
- PlatformInstrumentation::DidDrawLazyPixelRef(unique_id);
+ if (is_lazy_generated) {
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "Draw LazyPixelRef", TRACE_EVENT_SCOPE_THREAD,
+ "LazyPixelRef", unique_id);
+ }
StartAnimation();
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/bitmap_image_test.cc b/chromium/third_party/blink/renderer/platform/graphics/bitmap_image_test.cc
index 42e7b288dec..616b61d76b9 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/bitmap_image_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/bitmap_image_test.cc
@@ -91,6 +91,26 @@ void GenerateBitmapForPaintImage(cc::PaintImage paint_image,
} // namespace
+// Extends TestingPlatformSupportWithMockScheduler to add the ability to set the
+// return value of MaxDecodedImageBytes().
+class TestingPlatformSupportWithMaxDecodedBytes
+ : public TestingPlatformSupportWithMockScheduler {
+ WTF_MAKE_NONCOPYABLE(TestingPlatformSupportWithMaxDecodedBytes);
+
+ public:
+ TestingPlatformSupportWithMaxDecodedBytes() {}
+ ~TestingPlatformSupportWithMaxDecodedBytes() override {}
+
+ void SetMaxDecodedImageBytes(size_t max_decoded_image_bytes) {
+ max_decoded_image_bytes_ = max_decoded_image_bytes;
+ }
+
+ size_t MaxDecodedImageBytes() override { return max_decoded_image_bytes_; }
+
+ private:
+ size_t max_decoded_image_bytes_ = Platform::kNoDecodedImageByteLimit;
+};
+
class BitmapImageTest : public testing::Test {
public:
class FakeImageObserver : public GarbageCollectedFinalized<FakeImageObserver>,
@@ -107,21 +127,16 @@ class BitmapImageTest : public testing::Test {
last_decoded_size_ = new_size;
}
bool ShouldPauseAnimation(const Image*) override { return false; }
- void AnimationAdvanced(const Image*) override {
- animation_advanced_ = true;
- }
void AsyncLoadCompleted(const Image*) override { NOTREACHED(); }
void Changed(const Image*) override {}
size_t last_decoded_size_;
int last_decoded_size_changed_delta_;
- bool animation_advanced_ = false;
};
static scoped_refptr<SharedBuffer> ReadFile(const char* file_name) {
- String file_path = test::BlinkLayoutTestsDir();
- file_path.append(file_name);
+ String file_path = test::PlatformTestDataPath(file_name);
return test::ReadFromFile(file_path);
}
@@ -224,12 +239,12 @@ class BitmapImageTest : public testing::Test {
Persistent<FakeImageObserver> image_observer_;
scoped_refptr<BitmapImage> image_;
- ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
+ ScopedTestingPlatformSupport<TestingPlatformSupportWithMaxDecodedBytes>
platform_;
};
TEST_F(BitmapImageTest, destroyDecodedData) {
- LoadImage("/images/resources/animated-10color.gif");
+ LoadImage("animated-10color.gif");
image_->PaintImageForCurrentFrame();
size_t total_size = DecodedSize();
EXPECT_GT(total_size, 0u);
@@ -239,13 +254,12 @@ TEST_F(BitmapImageTest, destroyDecodedData) {
}
TEST_F(BitmapImageTest, maybeAnimated) {
- LoadImage("/images/resources/gif-loop-count.gif");
+ LoadImage("gif-loop-count.gif");
EXPECT_TRUE(image_->MaybeAnimated());
}
TEST_F(BitmapImageTest, isAllDataReceived) {
- scoped_refptr<SharedBuffer> image_data =
- ReadFile("/images/resources/green.jpg");
+ scoped_refptr<SharedBuffer> image_data = ReadFile("green.jpg");
ASSERT_TRUE(image_data.get());
scoped_refptr<BitmapImage> image = BitmapImage::Create();
@@ -265,14 +279,14 @@ TEST_F(BitmapImageTest, isAllDataReceived) {
}
TEST_F(BitmapImageTest, noColorProfile) {
- LoadImage("/images/resources/green.jpg");
+ LoadImage("green.jpg");
image_->PaintImageForCurrentFrame();
EXPECT_EQ(1024u, DecodedSize());
EXPECT_FALSE(image_->HasColorProfile());
}
TEST_F(BitmapImageTest, jpegHasColorProfile) {
- LoadImage("/images/resources/icc-v2-gbr.jpg");
+ LoadImage("icc-v2-gbr.jpg");
image_->PaintImageForCurrentFrame();
EXPECT_EQ(227700u, DecodedSize());
EXPECT_TRUE(image_->HasColorProfile());
@@ -280,7 +294,6 @@ TEST_F(BitmapImageTest, jpegHasColorProfile) {
TEST_F(BitmapImageTest, pngHasColorProfile) {
LoadImage(
- "/images/resources/"
"palatted-color-png-gamma-one-color-profile.png");
image_->PaintImageForCurrentFrame();
EXPECT_EQ(65536u, DecodedSize());
@@ -288,21 +301,21 @@ TEST_F(BitmapImageTest, pngHasColorProfile) {
}
TEST_F(BitmapImageTest, webpHasColorProfile) {
- LoadImage("/images/resources/webp-color-profile-lossy.webp");
+ LoadImage("webp-color-profile-lossy.webp");
image_->PaintImageForCurrentFrame();
EXPECT_EQ(2560000u, DecodedSize());
EXPECT_TRUE(image_->HasColorProfile());
}
TEST_F(BitmapImageTest, icoHasWrongFrameDimensions) {
- LoadImage("/images/resources/wrong-frame-dimensions.ico");
+ LoadImage("wrong-frame-dimensions.ico");
// This call would cause crash without fix for 408026
ImageForDefaultFrame();
}
TEST_F(BitmapImageTest, correctDecodedDataSize) {
// Requesting any one frame shouldn't result in decoding any other frames.
- LoadImage("/images/resources/anim_none.gif");
+ LoadImage("anim_none.gif");
image_->PaintImageForCurrentFrame();
int frame_size =
static_cast<int>(image_->Size().Area() * sizeof(ImageFrame::PixelData));
@@ -310,7 +323,7 @@ TEST_F(BitmapImageTest, correctDecodedDataSize) {
}
TEST_F(BitmapImageTest, recachingFrameAfterDataChanged) {
- LoadImage("/images/resources/green.jpg");
+ LoadImage("green.jpg");
image_->PaintImageForCurrentFrame();
EXPECT_GT(LastDecodedSizeChange(), 0);
image_observer_->last_decoded_size_changed_delta_ = 0;
@@ -325,8 +338,7 @@ TEST_F(BitmapImageTest, recachingFrameAfterDataChanged) {
}
TEST_F(BitmapImageTest, ConstantImageIdForPartiallyLoadedImages) {
- scoped_refptr<SharedBuffer> image_data =
- ReadFile("/images/resources/green.jpg");
+ scoped_refptr<SharedBuffer> image_data = ReadFile("green.jpg");
ASSERT_TRUE(image_data.get());
// Create a new buffer to partially supply the data.
@@ -381,7 +393,7 @@ TEST_F(BitmapImageTest, ConstantImageIdForPartiallyLoadedImages) {
}
TEST_F(BitmapImageTest, ImageForDefaultFrame_MultiFrame) {
- LoadImage("/images/resources/anim_none.gif");
+ LoadImage("anim_none.gif");
// Multi-frame images create new StaticBitmapImages for each call.
auto default_image1 = image_->ImageForDefaultFrame();
@@ -397,39 +409,39 @@ TEST_F(BitmapImageTest, ImageForDefaultFrame_MultiFrame) {
}
TEST_F(BitmapImageTest, ImageForDefaultFrame_SingleFrame) {
- LoadImage("/images/resources/green.jpg");
+ LoadImage("green.jpg");
// Default frame images for single-frame cases is the image itself.
EXPECT_EQ(image_->ImageForDefaultFrame(), image_);
}
TEST_F(BitmapImageTest, GifDecoderFrame0) {
- LoadImage("/images/resources/green-red-blue-yellow-animated.gif");
+ LoadImage("green-red-blue-yellow-animated.gif");
auto bitmap = GenerateBitmap(0u);
SkColor color = SkColorSetARGB(255, 0, 128, 0);
VerifyBitmap(bitmap, color);
}
TEST_F(BitmapImageTest, GifDecoderFrame1) {
- LoadImage("/images/resources/green-red-blue-yellow-animated.gif");
+ LoadImage("green-red-blue-yellow-animated.gif");
auto bitmap = GenerateBitmap(1u);
VerifyBitmap(bitmap, SK_ColorRED);
}
TEST_F(BitmapImageTest, GifDecoderFrame2) {
- LoadImage("/images/resources/green-red-blue-yellow-animated.gif");
+ LoadImage("green-red-blue-yellow-animated.gif");
auto bitmap = GenerateBitmap(2u);
VerifyBitmap(bitmap, SK_ColorBLUE);
}
TEST_F(BitmapImageTest, GifDecoderFrame3) {
- LoadImage("/images/resources/green-red-blue-yellow-animated.gif");
+ LoadImage("green-red-blue-yellow-animated.gif");
auto bitmap = GenerateBitmap(3u);
VerifyBitmap(bitmap, SK_ColorYELLOW);
}
TEST_F(BitmapImageTest, GifDecoderMultiThreaded) {
- LoadImage("/images/resources/green-red-blue-yellow-animated.gif");
+ LoadImage("green-red-blue-yellow-animated.gif");
auto paint_image = image_->PaintImageForTesting();
ASSERT_EQ(paint_image.FrameCount(), 4u);
@@ -460,108 +472,131 @@ TEST_F(BitmapImageTest, GifDecoderMultiThreaded) {
}
TEST_F(BitmapImageTest, APNGDecoder00) {
- LoadImage("/images/resources/apng00.png");
+ LoadImage("apng00.png");
auto actual_bitmap = GenerateBitmap(0u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng00-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng00-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
// Jump to the final frame of each image.
TEST_F(BitmapImageTest, APNGDecoder01) {
- LoadImage("/images/resources/apng01.png");
+ LoadImage("apng01.png");
auto actual_bitmap = GenerateBitmap(9u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng01-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng01-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder02) {
- LoadImage("/images/resources/apng02.png");
+ LoadImage("apng02.png");
auto actual_bitmap = GenerateBitmap(9u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng02-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng02-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder04) {
- LoadImage("/images/resources/apng04.png");
+ LoadImage("apng04.png");
auto actual_bitmap = GenerateBitmap(12u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng04-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng04-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder08) {
- LoadImage("/images/resources/apng08.png");
+ LoadImage("apng08.png");
auto actual_bitmap = GenerateBitmap(12u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng08-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng08-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder10) {
- LoadImage("/images/resources/apng10.png");
+ LoadImage("apng10.png");
auto actual_bitmap = GenerateBitmap(3u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng10-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng10-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder11) {
- LoadImage("/images/resources/apng11.png");
+ LoadImage("apng11.png");
auto actual_bitmap = GenerateBitmap(9u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng11-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng11-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder12) {
- LoadImage("/images/resources/apng12.png");
+ LoadImage("apng12.png");
auto actual_bitmap = GenerateBitmap(9u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng12-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng12-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder14) {
- LoadImage("/images/resources/apng14.png");
+ LoadImage("apng14.png");
auto actual_bitmap = GenerateBitmap(12u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng14-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng14-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder18) {
- LoadImage("/images/resources/apng18.png");
+ LoadImage("apng18.png");
auto actual_bitmap = GenerateBitmap(12u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng18-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng18-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoder19) {
- LoadImage("/images/resources/apng19.png");
+ LoadImage("apng19.png");
auto actual_bitmap = GenerateBitmap(12u);
- auto expected_bitmap =
- GenerateBitmapForImage("/images/resources/apng19-ref.png");
+ auto expected_bitmap = GenerateBitmapForImage("apng19-ref.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, APNGDecoderDisposePrevious) {
- LoadImage("/images/resources/crbug722072.png");
+ LoadImage("crbug722072.png");
auto actual_bitmap = GenerateBitmap(3u);
- auto expected_bitmap = GenerateBitmapForImage("/images/resources/green.png");
+ auto expected_bitmap = GenerateBitmapForImage("green.png");
VerifyBitmap(actual_bitmap, expected_bitmap);
}
TEST_F(BitmapImageTest, GIFRepetitionCount) {
- LoadImage("/images/resources/three-frames_loop-three-times.gif");
+ LoadImage("three-frames_loop-three-times.gif");
auto paint_image = image_->PaintImageForCurrentFrame();
EXPECT_EQ(paint_image.repetition_count(), 3);
EXPECT_EQ(paint_image.FrameCount(), 3u);
}
+TEST_F(BitmapImageTest, DecoderAndCacheMipLevels) {
+ // Here, we want to test that the mip level calculated by the cc matches
+ // exactly a size supported by the decoder. This is to make sure that the
+ // rounding used in cc matches the rounding in the decoder. The image in this
+ // test is 629x473 and uses 4:2:0 sampling. This means that the MCU is 16x16.
+ // Under no memory limits, this image would not be eligible for downscaling by
+ // the JPEG decoder because neither dimension is a multiple of 16 (see
+ // https://crbug.com/890745). However, we can force the JPEG decoder to
+ // support downscaling by limiting the maximum bytes allowed for decoding. If
+ // we limit to 315 * 237 * 4 bytes, we'll be forcing the maximum scale factor
+ // numerator to be 4 (assuming a denominator of 8).
+ platform_->SetMaxDecodedImageBytes(315 * 237 * 4);
+ LoadImage("original-cat-420-629x473.jpg");
+ auto paint_image = image_->PaintImageForCurrentFrame();
+
+ // The size of the PaintImage is based on the maximum bytes allowed for
+ // decoding.
+ ASSERT_EQ(315, paint_image.width());
+ ASSERT_EQ(237, paint_image.height());
+
+ // Level 0 should match the decoder supported size for scale factor 4/8.
+ // Level 1 should match the decoder supported size for scale factor 2/8.
+ // Level 2 should match the decoder supported size for scale factor 1/8.
+ // Higher levels (smaller sizes) are not supported by the JPEG decoder.
+ for (int mip_level = 0; mip_level < 3; ++mip_level) {
+ SCOPED_TRACE(mip_level);
+ SkISize scaled_size = gfx::SizeToSkISize(cc::MipMapUtil::GetSizeForLevel(
+ gfx::Size(paint_image.width(), paint_image.height()), mip_level));
+ SkISize supported_size = paint_image.GetSupportedDecodeSize(scaled_size);
+ EXPECT_EQ(gfx::SkISizeToSize(supported_size),
+ gfx::SkISizeToSize(scaled_size));
+ }
+}
+
class BitmapImageTestWithMockDecoder : public BitmapImageTest,
public MockImageDecoderClient {
public:
@@ -787,17 +822,13 @@ TEST_P(DecodedImageTypeHistogramTest, ImageType) {
const DecodedImageTypeHistogramTest::ParamType
kDecodedImageTypeHistogramTestparams[] = {
- {"/images/resources/green.jpg", BitmapImageMetrics::kImageJPEG},
- {"/images/resources/"
- "palatted-color-png-gamma-one-color-profile.png",
+ {"green.jpg", BitmapImageMetrics::kImageJPEG},
+ {"palatted-color-png-gamma-one-color-profile.png",
BitmapImageMetrics::kImagePNG},
- {"/images/resources/animated-10color.gif",
- BitmapImageMetrics::kImageGIF},
- {"/images/resources/webp-color-profile-lossy.webp",
- BitmapImageMetrics::kImageWebP},
- {"/images/resources/wrong-frame-dimensions.ico",
- BitmapImageMetrics::kImageICO},
- {"/images/resources/lenna.bmp", BitmapImageMetrics::kImageBMP}};
+ {"animated-10color.gif", BitmapImageMetrics::kImageGIF},
+ {"webp-color-profile-lossy.webp", BitmapImageMetrics::kImageWebP},
+ {"wrong-frame-dimensions.ico", BitmapImageMetrics::kImageICO},
+ {"lenna.bmp", BitmapImageMetrics::kImageBMP}};
INSTANTIATE_TEST_CASE_P(
DecodedImageTypeHistogramTest,
@@ -813,14 +844,14 @@ TEST_P(DecodedImageOrientationHistogramTest, ImageOrientation) {
const DecodedImageOrientationHistogramTest::ParamType
kDecodedImageOrientationHistogramTestParams[] = {
- {"/images/resources/exif-orientation-1-ul.jpg", kOriginTopLeft},
- {"/images/resources/exif-orientation-2-ur.jpg", kOriginTopRight},
- {"/images/resources/exif-orientation-3-lr.jpg", kOriginBottomRight},
- {"/images/resources/exif-orientation-4-lol.jpg", kOriginBottomLeft},
- {"/images/resources/exif-orientation-5-lu.jpg", kOriginLeftTop},
- {"/images/resources/exif-orientation-6-ru.jpg", kOriginRightTop},
- {"/images/resources/exif-orientation-7-rl.jpg", kOriginRightBottom},
- {"/images/resources/exif-orientation-8-llo.jpg", kOriginLeftBottom}};
+ {"exif-orientation-1-ul.jpg", kOriginTopLeft},
+ {"exif-orientation-2-ur.jpg", kOriginTopRight},
+ {"exif-orientation-3-lr.jpg", kOriginBottomRight},
+ {"exif-orientation-4-lol.jpg", kOriginBottomLeft},
+ {"exif-orientation-5-lu.jpg", kOriginLeftTop},
+ {"exif-orientation-6-ru.jpg", kOriginRightTop},
+ {"exif-orientation-7-rl.jpg", kOriginRightBottom},
+ {"exif-orientation-8-llo.jpg", kOriginLeftBottom}};
INSTANTIATE_TEST_CASE_P(
DecodedImageOrientationHistogramTest,
@@ -836,15 +867,14 @@ TEST_P(DecodedImageDensityHistogramTest100px, JpegDensity) {
const DecodedImageDensityHistogramTest100px::ParamType
kDecodedImageDensityHistogramTest100pxParams[] = {
// 64x64 too small to report any metric
- {"/images/resources/rgb-jpeg-red.jpg",
+ {"rgb-jpeg-red.jpg",
DecodedImageDensityHistogramTest100px::kNoSamplesReported},
// 439x154, 23220 bytes --> 2.74 bpp
- {"/images/resources/cropped_mandrill.jpg", 274},
+ {"cropped_mandrill.jpg", 274},
// 320x320, 74017 bytes --> 5.78
- {"/images/resources/blue-wheel-srgb-color-profile.jpg", 578},
+ {"blue-wheel-srgb-color-profile.jpg", 578},
// 632x475 too big for the 100-399px range.
- {"/images/resources/cat.jpg",
- DecodedImageDensityHistogramTest100px::kNoSamplesReported}};
+ {"cat.jpg", DecodedImageDensityHistogramTest100px::kNoSamplesReported}};
INSTANTIATE_TEST_CASE_P(
DecodedImageDensityHistogramTest100px,
@@ -860,13 +890,13 @@ TEST_P(DecodedImageDensityHistogramTest400px, JpegDensity) {
const DecodedImageDensityHistogramTest400px::ParamType
kDecodedImageDensityHistogramTest400pxParams[] = {
// 439x154, only one dimension is big enough.
- {"/images/resources/cropped_mandrill.jpg",
+ {"cropped_mandrill.jpg",
DecodedImageDensityHistogramTest400px::kNoSamplesReported},
// 320x320, not big enough.
- {"/images/resources/blue-wheel-srgb-color-profile.jpg",
+ {"blue-wheel-srgb-color-profile.jpg",
DecodedImageDensityHistogramTest400px::kNoSamplesReported},
// 632x475, 68826 bytes --> 1.83
- {"/images/resources/cat.jpg", 183}};
+ {"cat.jpg", 183}};
INSTANTIATE_TEST_CASE_P(
DecodedImageDensityHistogramTest400px,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc
index 9603c55a8b3..ca6a5261754 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc
@@ -35,7 +35,6 @@
#include "gpu/command_buffer/client/gles2_interface.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h"
-#include "third_party/blink/renderer/platform/graphics/canvas_metrics.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_context_rate_limiter.h"
@@ -91,6 +90,9 @@ Canvas2DLayerBridge::Canvas2DLayerBridge(const IntSize& size,
}
Canvas2DLayerBridge::~Canvas2DLayerBridge() {
+ UMA_HISTOGRAM_BOOLEAN("Blink.Canvas.2DLayerBridgeIsDeferred",
+ is_deferral_enabled_);
+
if (IsHibernating())
logger_->ReportHibernationEvent(kHibernationEndedWithTeardown);
ResetResourceProvider();
@@ -255,17 +257,6 @@ void Canvas2DLayerBridge::Hibernate() {
logger_->DidStartHibernating();
}
-void Canvas2DLayerBridge::ReportResourceProviderCreationFailure() {
- if (!resource_provider_creation_failed_at_least_once_) {
- // Only count the failure once per instance so that the histogram may
- // reflect the proportion of Canvas2DLayerBridge instances with surface
- // allocation failures.
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kGPUAccelerated2DCanvasSurfaceCreationFailed);
- resource_provider_creation_failed_at_least_once_ = true;
- }
-}
-
CanvasResourceProvider* Canvas2DLayerBridge::ResourceProvider() const {
return resource_host_ ? resource_host_->ResourceProvider() : nullptr;
}
@@ -314,9 +305,6 @@ CanvasResourceProvider* Canvas2DLayerBridge::GetOrCreateResourceProvider(
resource_provider =
resource_host_->GetOrCreateCanvasResourceProviderImpl(adjusted_hint);
- if (!resource_provider)
- ReportResourceProviderCreationFailure();
-
if (resource_provider && IsAccelerated() && !layer_) {
layer_ = cc::TextureLayer::CreateForMailbox(this);
layer_->SetIsDrawable(true);
@@ -385,12 +373,9 @@ void Canvas2DLayerBridge::DisableDeferral(DisableDeferralReason reason) {
if (!is_deferral_enabled_ || !resource_host_)
return;
- DEFINE_STATIC_LOCAL(EnumerationHistogram, gpu_disabled_histogram,
- ("Canvas.GPUAccelerated2DCanvasDisableDeferralReason",
- kDisableDeferralReasonCount));
- gpu_disabled_histogram.Count(reason);
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kGPUAccelerated2DCanvasDeferralDisabled);
+ UMA_HISTOGRAM_ENUMERATION(
+ "Blink.Canvas.GPUAccelerated2DCanvasDisableDeferralReason", reason,
+ kDisableDeferralReasonCount);
FlushRecording();
// Because we will be discarding the recorder, if the flush failed
// content will be lost -> force m_haveRecordedDrawCommands to false
@@ -426,11 +411,11 @@ void Canvas2DLayerBridge::SetIsHidden(bool hidden) {
logger_->ReportHibernationEvent(kHibernationScheduled);
hibernation_scheduled_ = true;
if (dont_use_idle_scheduling_for_testing_) {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&HibernateWrapperForTesting,
weak_ptr_factory_.GetWeakPtr()));
} else {
- Platform::Current()->CurrentThread()->Scheduler()->PostIdleTask(
+ ThreadScheduler::Current()->PostIdleTask(
FROM_HERE,
WTF::Bind(&HibernateWrapper, weak_ptr_factory_.GetWeakPtr()));
}
@@ -546,8 +531,6 @@ bool Canvas2DLayerBridge::CheckResourceProviderValid() {
ResetResourceProvider();
if (resource_host_)
resource_host_->NotifyGpuContextLost();
- CanvasMetrics::CountCanvasContextUsage(
- CanvasMetrics::kAccelerated2DCanvasGPUContextLost);
return false;
}
return !!GetOrCreateResourceProvider();
@@ -571,9 +554,6 @@ bool Canvas2DLayerBridge::Restore() {
resource_host_->GetOrCreateCanvasResourceProviderImpl(
kPreferAcceleration);
- if (!resource_provider)
- ReportResourceProviderCreationFailure();
-
// The current paradigm does not support switching from accelerated to
// non-accelerated, which would be tricky due to changes to the layer tree,
// which can only happen at specific times during the document lifecycle.
@@ -651,7 +631,7 @@ void Canvas2DLayerBridge::DidDraw(const FloatRect& rect) {
}
base::CheckedNumeric<int> threshold_size = size_.Width();
threshold_size *= size_.Height();
- threshold_size *= CanvasHeuristicParameters::kExpensiveOverdrawThreshold;
+ threshold_size *= canvas_heuristic_parameters::kExpensiveOverdrawThreshold;
if (!threshold_size.IsValid()) {
DisableDeferral(kDisableDeferralReasonExpensiveOverdrawHeuristic);
return;
@@ -717,9 +697,7 @@ void Canvas2DLayerBridge::WillOverwriteCanvas() {
void Canvas2DLayerBridge::Logger::ReportHibernationEvent(
HibernationEvent event) {
- DEFINE_STATIC_LOCAL(EnumerationHistogram, hibernation_histogram,
- ("Canvas.HibernationEvents", kHibernationEventCount));
- hibernation_histogram.Count(event);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.HibernationEvents", event);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h
index 60263c7a607..326c4f6727f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h
@@ -149,8 +149,7 @@ class PLATFORM_EXPORT Canvas2DLayerBridge : public cc::TextureLayerClient {
kHibernationEndedWithFallbackToSW = 9,
kHibernationEndedWithTeardown = 10,
kHibernationAbortedBecauseNoSurface = 11,
-
- kHibernationEventCount = 12,
+ kMaxValue = kHibernationAbortedBecauseNoSurface,
};
class PLATFORM_EXPORT Logger {
@@ -173,7 +172,6 @@ class PLATFORM_EXPORT Canvas2DLayerBridge : public cc::TextureLayerClient {
void StartRecording();
void SkipQueuedDrawCommands();
- void ReportResourceProviderCreationFailure();
bool ShouldAccelerate(AccelerationHint) const;
@@ -189,7 +187,6 @@ class PLATFORM_EXPORT Canvas2DLayerBridge : public cc::TextureLayerClient {
bool is_hidden_;
bool is_deferral_enabled_;
bool software_rendering_while_hidden_;
- bool resource_provider_creation_failed_at_least_once_ = false;
bool hibernation_scheduled_ = false;
bool dont_use_idle_scheduling_for_testing_ = false;
bool context_lost_ = false;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc
index ba1c10814cc..97e51b47421 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc
@@ -53,11 +53,11 @@
#include "third_party/blink/renderer/platform/graphics/test/fake_canvas_resource_host.h"
#include "third_party/blink/renderer/platform/graphics/test/fake_gles2_interface.h"
#include "third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h"
+#include "third_party/blink/renderer/platform/graphics/test/gpu_memory_buffer_test_platform.h"
#include "third_party/blink/renderer/platform/graphics/web_graphics_context_3d_provider_wrapper.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/gl/GrGLTypes.h"
@@ -91,20 +91,6 @@ class MockGLES2InterfaceWithImageSupport : public FakeGLES2Interface {
}
};
-class FakePlatformSupport : public TestingPlatformSupport {
- public:
- void RunUntilStop() const { base::RunLoop().Run(); }
-
- void StopRunning() const { base::RunLoop().Quit(); }
-
- private:
- gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override {
- return &test_gpu_memory_buffer_manager_;
- }
-
- viz::TestGpuMemoryBufferManager test_gpu_memory_buffer_manager_;
-};
-
class ImageTrackingDecodeCache : public cc::StubDecodeCache {
public:
ImageTrackingDecodeCache() = default;
@@ -421,7 +407,7 @@ TEST_F(Canvas2DLayerBridgeTest, HibernationLifeCycle)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_HibernationLifeCycle)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -467,7 +453,7 @@ TEST_F(Canvas2DLayerBridgeTest, HibernationReEntry)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_HibernationReEntry)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -517,7 +503,7 @@ TEST_F(Canvas2DLayerBridgeTest,
DISABLED_HibernationLifeCycleWithDeferredRenderingDisabled)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
@@ -566,7 +552,7 @@ TEST_F(Canvas2DLayerBridgeTest, BackgroundRenderingWhileHibernating)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_BackgroundRenderingWhileHibernating)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -619,7 +605,7 @@ TEST_F(
DISABLED_BackgroundRenderingWhileHibernatingWithDeferredRenderingDisabled)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -677,7 +663,7 @@ TEST_F(Canvas2DLayerBridgeTest,
DISABLED_DisableDeferredRenderingWhileHibernating)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -738,7 +724,7 @@ TEST_F(Canvas2DLayerBridgeTest, TeardownWhileHibernating)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_TeardownWhileHibernating)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -776,7 +762,7 @@ TEST_F(Canvas2DLayerBridgeTest, SnapshotWhileHibernating)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_SnapshotWhileHibernating)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -825,7 +811,7 @@ TEST_F(Canvas2DLayerBridgeTest, TeardownWhileHibernationIsPending)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_TeardownWhileHibernationIsPending)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -859,7 +845,7 @@ TEST_F(Canvas2DLayerBridgeTest,
DISABLED_HibernationAbortedDueToVisibilityChange)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -895,7 +881,7 @@ TEST_F(Canvas2DLayerBridgeTest, HibernationAbortedDueToLostContext)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_HibernationAbortedDueToLostContext)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -930,7 +916,7 @@ TEST_F(Canvas2DLayerBridgeTest, PrepareMailboxWhileHibernating)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_PrepareMailboxWhileHibernating)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -973,7 +959,7 @@ TEST_F(Canvas2DLayerBridgeTest, PrepareMailboxWhileBackgroundRendering)
TEST_F(Canvas2DLayerBridgeTest, DISABLED_PrepareMailboxWhileBackgroundRendering)
#endif
{
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
CanvasColorParams());
@@ -1017,11 +1003,11 @@ TEST_F(Canvas2DLayerBridgeTest, DISABLED_PrepareMailboxWhileBackgroundRendering)
TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
InSequence s;
ScopedCanvas2dImageChromiumForTest canvas_2d_image_chromium(true);
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
const_cast<gpu::Capabilities&>(SharedGpuContext::ContextProviderWrapper()
->ContextProvider()
->GetCapabilities())
- .texture_format_bgra8888 = true;
+ .gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRA_8888);
viz::TransferableResource resource1;
viz::TransferableResource resource2;
@@ -1041,6 +1027,7 @@ TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _)).WillOnce(Return(image_id1));
EXPECT_CALL(gl_, GenTextures(1, _)).WillOnce(SetArgPointee<1>(texture_id1));
+ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id1));
if (texture_target == GL_TEXTURE_EXTERNAL_OES) {
constexpr GLuint image_2d_id_for_copy = 17;
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _))
@@ -1055,6 +1042,7 @@ TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _)).WillOnce(Return(image_id2));
EXPECT_CALL(gl_, GenTextures(1, _)).WillOnce(SetArgPointee<1>(texture_id2));
+ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id2));
if (texture_target == GL_TEXTURE_EXTERNAL_OES) {
constexpr GLuint image_2d_id_for_copy = 19;
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _))
@@ -1069,7 +1057,6 @@ TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
// Check that release resources does not result in destruction due
// to recycling.
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(_)).Times(0);
EXPECT_CALL(gl_, DeleteTextures(_, _)).Times(0);
bool lost_resource = false;
release_callback1->Run(gpu::SyncToken(), lost_resource);
@@ -1077,7 +1064,6 @@ TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
testing::Mock::VerifyAndClearExpectations(&gl_);
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(_)).Times(0);
EXPECT_CALL(gl_, DeleteTextures(_, _)).Times(0);
release_callback2->Run(gpu::SyncToken(), lost_resource);
release_callback2 = nullptr;
@@ -1085,10 +1071,8 @@ TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
testing::Mock::VerifyAndClearExpectations(&gl_);
// Destroying the bridge results in destruction of cached resources.
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id1)).Times(1);
- EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id1))).Times(1);
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id2)).Times(1);
- EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id2))).Times(1);
+ EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id1)));
+ EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id2)));
bridge.reset();
testing::Mock::VerifyAndClearExpectations(&gl_);
@@ -1097,11 +1081,11 @@ TEST_F(Canvas2DLayerBridgeTest, GpuMemoryBufferRecycling) {
TEST_F(Canvas2DLayerBridgeTest, NoGpuMemoryBufferRecyclingWhenPageHidden) {
InSequence s;
ScopedCanvas2dImageChromiumForTest canvas_2d_image_chromium(true);
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
const_cast<gpu::Capabilities&>(SharedGpuContext::ContextProviderWrapper()
->ContextProvider()
->GetCapabilities())
- .texture_format_bgra8888 = true;
+ .gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRA_8888);
viz::TransferableResource resource1;
viz::TransferableResource resource2;
@@ -1121,6 +1105,7 @@ TEST_F(Canvas2DLayerBridgeTest, NoGpuMemoryBufferRecyclingWhenPageHidden) {
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _)).WillOnce(Return(image_id1));
EXPECT_CALL(gl_, GenTextures(1, _)).WillOnce(SetArgPointee<1>(texture_id1));
+ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id1));
if (texture_target == GL_TEXTURE_EXTERNAL_OES) {
constexpr GLuint image_2d_id_for_copy = 17;
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _))
@@ -1135,6 +1120,7 @@ TEST_F(Canvas2DLayerBridgeTest, NoGpuMemoryBufferRecyclingWhenPageHidden) {
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _)).WillOnce(Return(image_id2));
EXPECT_CALL(gl_, GenTextures(1, _)).WillOnce(SetArgPointee<1>(texture_id2));
+ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id2));
if (texture_target == GL_TEXTURE_EXTERNAL_OES) {
constexpr GLuint image_2d_id_for_copy = 19;
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _))
@@ -1148,7 +1134,6 @@ TEST_F(Canvas2DLayerBridgeTest, NoGpuMemoryBufferRecyclingWhenPageHidden) {
testing::Mock::VerifyAndClearExpectations(&gl_);
// Release first frame to cache
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(_)).Times(0);
EXPECT_CALL(gl_, DeleteTextures(_, _)).Times(0);
bool lost_resource = false;
release_callback1->Run(gpu::SyncToken(), lost_resource);
@@ -1157,16 +1142,14 @@ TEST_F(Canvas2DLayerBridgeTest, NoGpuMemoryBufferRecyclingWhenPageHidden) {
testing::Mock::VerifyAndClearExpectations(&gl_);
// Switching to Hidden frees cached resources immediately
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id1)).Times(1);
- EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id1))).Times(1);
+ EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id1)));
bridge->SetIsHidden(true);
testing::Mock::VerifyAndClearExpectations(&gl_);
// Release second frame and verify that its resource is destroyed immediately
// due to the layer bridge being hidden
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id2)).Times(1);
- EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id2))).Times(1);
+ EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id2)));
release_callback2->Run(gpu::SyncToken(), lost_resource);
release_callback2 = nullptr;
@@ -1176,11 +1159,11 @@ TEST_F(Canvas2DLayerBridgeTest, NoGpuMemoryBufferRecyclingWhenPageHidden) {
TEST_F(Canvas2DLayerBridgeTest, ReleaseGpuMemoryBufferAfterBridgeDestroyed) {
InSequence s;
ScopedCanvas2dImageChromiumForTest canvas_2d_image_chromium(true);
- ScopedTestingPlatformSupport<FakePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
const_cast<gpu::Capabilities&>(SharedGpuContext::ContextProviderWrapper()
->ContextProvider()
->GetCapabilities())
- .texture_format_bgra8888 = true;
+ .gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRA_8888);
viz::TransferableResource resource;
std::unique_ptr<viz::SingleReleaseCallback> release_callback;
@@ -1196,7 +1179,7 @@ TEST_F(Canvas2DLayerBridgeTest, ReleaseGpuMemoryBufferAfterBridgeDestroyed) {
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _)).WillOnce(Return(image_id));
EXPECT_CALL(gl_, GenTextures(1, _)).WillOnce(SetArgPointee<1>(texture_id));
-
+ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id));
if (texture_target == GL_TEXTURE_EXTERNAL_OES) {
constexpr GLuint image_2d_id_for_copy = 17;
EXPECT_CALL(gl_, CreateImageCHROMIUM(_, _, _, _))
@@ -1210,15 +1193,13 @@ TEST_F(Canvas2DLayerBridgeTest, ReleaseGpuMemoryBufferAfterBridgeDestroyed) {
testing::Mock::VerifyAndClearExpectations(&gl_);
// Tearing down the bridge does not destroy unreleased resources.
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(_)).Times(0);
EXPECT_CALL(gl_, DeleteTextures(_, _)).Times(0);
bridge.reset();
testing::Mock::VerifyAndClearExpectations(&gl_);
- EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_id)).Times(1);
- EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id))).Times(1);
- bool lost_resource = false;
+ EXPECT_CALL(gl_, DeleteTextures(1, Pointee(texture_id)));
+ constexpr bool lost_resource = false;
release_callback->Run(gpu::SyncToken(), lost_resource);
release_callback = nullptr;
@@ -1233,14 +1214,13 @@ TEST_F(Canvas2DLayerBridgeTest, EnsureCCImageCacheUse) {
std::unique_ptr<Canvas2DLayerBridge> bridge =
MakeBridge(IntSize(300, 300), Canvas2DLayerBridge::kEnableAcceleration,
color_params);
- gfx::ColorSpace expected_color_space = gfx::ColorSpace::CreateSRGB();
std::vector<cc::DrawImage> images = {
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(10, 10)),
SkIRect::MakeWH(10, 10), kNone_SkFilterQuality,
- SkMatrix::I(), 0u, expected_color_space),
+ SkMatrix::I(), 0u),
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(20, 20)),
SkIRect::MakeWH(5, 5), kNone_SkFilterQuality, SkMatrix::I(),
- 0u, expected_color_space)};
+ 0u)};
bridge->Canvas()->drawImage(images[0].paint_image(), 0u, 0u, nullptr);
bridge->Canvas()->drawImageRect(
@@ -1262,10 +1242,10 @@ TEST_F(Canvas2DLayerBridgeTest, EnsureCCImageCacheUseWithColorConversion) {
std::vector<cc::DrawImage> images = {
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(10, 10)),
SkIRect::MakeWH(10, 10), kNone_SkFilterQuality,
- SkMatrix::I(), 0u, color_params.GetStorageGfxColorSpace()),
+ SkMatrix::I(), 0u),
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(20, 20)),
SkIRect::MakeWH(5, 5), kNone_SkFilterQuality, SkMatrix::I(),
- 0u, color_params.GetStorageGfxColorSpace())};
+ 0u)};
bridge->Canvas()->drawImage(images[0].paint_image(), 0u, 0u, nullptr);
bridge->Canvas()->drawImageRect(
@@ -1288,13 +1268,13 @@ TEST_F(Canvas2DLayerBridgeTest, ImagesLockedUntilCacheLimit) {
std::vector<cc::DrawImage> images = {
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(10, 10)),
SkIRect::MakeWH(10, 10), kNone_SkFilterQuality,
- SkMatrix::I(), 0u, color_params.GetStorageGfxColorSpace()),
+ SkMatrix::I(), 0u),
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(20, 20)),
SkIRect::MakeWH(5, 5), kNone_SkFilterQuality, SkMatrix::I(),
- 0u, color_params.GetStorageGfxColorSpace()),
+ 0u),
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(20, 20)),
SkIRect::MakeWH(5, 5), kNone_SkFilterQuality, SkMatrix::I(),
- 0u, color_params.GetStorageGfxColorSpace())};
+ 0u)};
// First 2 images are budgeted, they should remain locked after the op.
bridge->Canvas()->drawImage(images[0].paint_image(), 0u, 0u, nullptr);
@@ -1321,10 +1301,9 @@ TEST_F(Canvas2DLayerBridgeTest, QueuesCleanupTaskForLockedImages) {
color_params);
bridge->DisableDeferral(DisableDeferralReason::kDisableDeferralReasonUnknown);
- auto image =
- cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(10, 10)),
- SkIRect::MakeWH(10, 10), kNone_SkFilterQuality,
- SkMatrix::I(), 0u, color_params.GetStorageGfxColorSpace());
+ auto image = cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(10, 10)),
+ SkIRect::MakeWH(10, 10), kNone_SkFilterQuality,
+ SkMatrix::I(), 0u);
bridge->Canvas()->drawImage(image.paint_image(), 0u, 0u, nullptr);
EXPECT_EQ(image_decode_cache_.num_locked_images(), 1);
@@ -1345,10 +1324,10 @@ TEST_F(Canvas2DLayerBridgeTest, ImageCacheOnContextLost) {
std::vector<cc::DrawImage> images = {
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(10, 10)),
SkIRect::MakeWH(10, 10), kNone_SkFilterQuality,
- SkMatrix::I(), 0u, color_params.GetStorageGfxColorSpace()),
+ SkMatrix::I(), 0u),
cc::DrawImage(cc::CreateDiscardablePaintImage(gfx::Size(20, 20)),
SkIRect::MakeWH(5, 5), kNone_SkFilterQuality, SkMatrix::I(),
- 0u, color_params.GetStorageGfxColorSpace())};
+ 0u)};
bridge->Canvas()->drawImage(images[0].paint_image(), 0u, 0u, nullptr);
// Lose the context and ensure that the image provider is not used.
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.cc
index cbbafe32f1b..e3079a828ba 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.cc
@@ -20,6 +20,7 @@ gfx::ColorSpace::PrimaryID GetPrimaryID(CanvasColorSpace color_space) {
gfx::ColorSpace::PrimaryID primary_id = gfx::ColorSpace::PrimaryID::BT709;
switch (color_space) {
case kSRGBCanvasColorSpace:
+ case kLinearRGBCanvasColorSpace:
primary_id = gfx::ColorSpace::PrimaryID::BT709;
break;
case kRec2020CanvasColorSpace:
@@ -43,48 +44,9 @@ CanvasColorParams::CanvasColorParams(CanvasColorSpace color_space,
pixel_format_(pixel_format),
opacity_mode_(opacity_mode) {}
-CanvasColorParams::CanvasColorParams(const sk_sp<SkColorSpace> color_space,
- SkColorType color_type) {
- color_space_ = kSRGBCanvasColorSpace;
- pixel_format_ = kRGBA8CanvasPixelFormat;
- // When there is no color space information, the SkImage is in legacy mode and
- // the color type is kN32_SkColorType (which translates to kRGBA8 canvas pixel
- // format).
- if (!color_space)
- return;
- // kSRGBCanvasColorSpace covers sRGB and linear-rgb. We need to check for
- // Rec2020 and P3.
- if (SkColorSpace::Equals(
- color_space.get(),
- SkColorSpace::MakeRGB(SkColorSpace::kLinear_RenderTargetGamma,
- SkColorSpace::kRec2020_Gamut)
- .get()))
- color_space_ = kRec2020CanvasColorSpace;
- else if (SkColorSpace::Equals(
- color_space.get(),
- SkColorSpace::MakeRGB(SkColorSpace::kLinear_RenderTargetGamma,
- SkColorSpace::kDCIP3_D65_Gamut)
- .get()))
- color_space_ = kP3CanvasColorSpace;
- if (color_type == kRGBA_F16_SkColorType)
- pixel_format_ = kF16CanvasPixelFormat;
-}
-
CanvasColorParams::CanvasColorParams(const SkImageInfo& info)
: CanvasColorParams(info.refColorSpace(), info.colorType()) {}
-void CanvasColorParams::SetCanvasColorSpace(CanvasColorSpace color_space) {
- color_space_ = color_space;
-}
-
-void CanvasColorParams::SetCanvasPixelFormat(CanvasPixelFormat pixel_format) {
- pixel_format_ = pixel_format;
-}
-
-void CanvasColorParams::SetOpacityMode(OpacityMode opacity_mode) {
- opacity_mode_ = opacity_mode;
-}
-
bool CanvasColorParams::NeedsSkColorSpaceXformCanvas() const {
return color_space_ == kSRGBCanvasColorSpace &&
pixel_format_ == kRGBA8CanvasPixelFormat;
@@ -92,9 +54,8 @@ bool CanvasColorParams::NeedsSkColorSpaceXformCanvas() const {
std::unique_ptr<cc::PaintCanvas> CanvasColorParams::WrapCanvas(
SkCanvas* canvas) const {
- if (NeedsSkColorSpaceXformCanvas()) {
+ if (NeedsSkColorSpaceXformCanvas())
return std::make_unique<cc::SkiaPaintCanvas>(canvas, GetSkColorSpace());
- }
// |canvas| already does its own color correction.
return std::make_unique<cc::SkiaPaintCanvas>(canvas);
}
@@ -116,15 +77,24 @@ bool CanvasColorParams::NeedsColorConversion(
}
SkColorType CanvasColorParams::GetSkColorType() const {
- if (pixel_format_ == kF16CanvasPixelFormat)
- return kRGBA_F16_SkColorType;
+ return PixelFormatToSkColorType(pixel_format_);
+}
+
+// static
+SkColorType CanvasColorParams::PixelFormatToSkColorType(
+ CanvasPixelFormat pixel_format) {
+ switch (pixel_format) {
+ case kF16CanvasPixelFormat:
+ return kRGBA_F16_SkColorType;
+ case kRGBA8CanvasPixelFormat:
+ return kN32_SkColorType;
+ }
+ NOTREACHED();
return kN32_SkColorType;
}
SkAlphaType CanvasColorParams::GetSkAlphaType() const {
- if (opacity_mode_ == kOpaque)
- return kOpaque_SkAlphaType;
- return kPremul_SkAlphaType;
+ return opacity_mode_ == kOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
}
const SkSurfaceProps* CanvasColorParams::GetSkSurfaceProps() const {
@@ -156,19 +126,27 @@ gfx::ColorSpace CanvasColorParams::GetStorageGfxColorSpace() const {
gfx::ColorSpace::TransferID transfer_id =
gfx::ColorSpace::TransferID::IEC61966_2_1;
- if (pixel_format_ == kF16CanvasPixelFormat)
+ // Only sRGB and e-sRGB use sRGB transfer function. Other canvas color spaces,
+ // i.e., linear-rgb, p3 and rec2020 use linear transfer function.
+ if (color_space_ != kSRGBCanvasColorSpace)
transfer_id = gfx::ColorSpace::TransferID::LINEAR_HDR;
return gfx::ColorSpace(primary_id, transfer_id);
}
sk_sp<SkColorSpace> CanvasColorParams::GetSkColorSpace() const {
+ return CanvasColorSpaceToSkColorSpace(color_space_);
+}
+
+sk_sp<SkColorSpace> CanvasColorParams::CanvasColorSpaceToSkColorSpace(
+ CanvasColorSpace color_space) {
SkColorSpace::Gamut gamut = SkColorSpace::kSRGB_Gamut;
SkColorSpace::RenderTargetGamma gamma = SkColorSpace::kSRGB_RenderTargetGamma;
- switch (color_space_) {
+ switch (color_space) {
case kSRGBCanvasColorSpace:
- if (pixel_format_ == kF16CanvasPixelFormat)
- gamma = SkColorSpace::kLinear_RenderTargetGamma;
+ break;
+ case kLinearRGBCanvasColorSpace:
+ gamma = SkColorSpace::kLinear_RenderTargetGamma;
break;
case kRec2020CanvasColorSpace:
gamut = SkColorSpace::kRec2020_Gamut;
@@ -246,4 +224,35 @@ viz::ResourceFormat CanvasColorParams::TransferableResourceFormat() const {
return viz::RGBA_8888;
}
+CanvasColorParams::CanvasColorParams(const sk_sp<SkColorSpace> color_space,
+ SkColorType color_type) {
+ color_space_ = kSRGBCanvasColorSpace;
+ pixel_format_ = kRGBA8CanvasPixelFormat;
+ // When there is no color space information, the SkImage is in legacy mode and
+ // the color type is kN32_SkColorType (which translates to kRGBA8 canvas pixel
+ // format).
+ if (!color_space)
+ return;
+ // kSRGBCanvasColorSpace covers sRGB and e-sRGB. We need to check for
+ // linear-rgb, rec2020 and p3.
+ if (SkColorSpace::Equals(color_space.get(),
+ SkColorSpace::MakeSRGB()->makeLinearGamma().get())) {
+ color_space_ = kLinearRGBCanvasColorSpace;
+ } else if (SkColorSpace::Equals(
+ color_space.get(),
+ SkColorSpace::MakeRGB(SkColorSpace::kLinear_RenderTargetGamma,
+ SkColorSpace::kRec2020_Gamut)
+ .get())) {
+ color_space_ = kRec2020CanvasColorSpace;
+ } else if (SkColorSpace::Equals(
+ color_space.get(),
+ SkColorSpace::MakeRGB(SkColorSpace::kLinear_RenderTargetGamma,
+ SkColorSpace::kDCIP3_D65_Gamut)
+ .get())) {
+ color_space_ = kP3CanvasColorSpace;
+ }
+ if (color_type == kRGBA_F16_SkColorType)
+ pixel_format_ = kF16CanvasPixelFormat;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.h
index 5b433cd44e6..e068a43554f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params.h
@@ -26,15 +26,16 @@ namespace blink {
enum CanvasColorSpace {
kSRGBCanvasColorSpace,
+ kLinearRGBCanvasColorSpace,
kRec2020CanvasColorSpace,
kP3CanvasColorSpace,
+ kMaxCanvasColorSpace = kP3CanvasColorSpace
};
enum CanvasPixelFormat {
kRGBA8CanvasPixelFormat,
- kRGB10A2CanvasPixelFormat,
- kRGBA12CanvasPixelFormat,
kF16CanvasPixelFormat,
+ kMaxCanvasPixelFormat = kF16CanvasPixelFormat
};
class PLATFORM_EXPORT CanvasColorParams {
@@ -42,16 +43,15 @@ class PLATFORM_EXPORT CanvasColorParams {
// The default constructor will create an output-blended 8-bit surface.
CanvasColorParams();
CanvasColorParams(CanvasColorSpace, CanvasPixelFormat, OpacityMode);
- explicit CanvasColorParams(const sk_sp<SkColorSpace> color_space,
- SkColorType color_type);
explicit CanvasColorParams(const SkImageInfo&);
+
CanvasColorSpace ColorSpace() const { return color_space_; }
CanvasPixelFormat PixelFormat() const { return pixel_format_; }
OpacityMode GetOpacityMode() const { return opacity_mode_; }
- void SetCanvasColorSpace(CanvasColorSpace);
- void SetCanvasPixelFormat(CanvasPixelFormat);
- void SetOpacityMode(OpacityMode);
+ void SetCanvasColorSpace(CanvasColorSpace c) { color_space_ = c; }
+ void SetCanvasPixelFormat(CanvasPixelFormat f) { pixel_format_ = f; }
+ void SetOpacityMode(OpacityMode m) { opacity_mode_ = m; }
// Indicates whether rendering needs to go through an SkColorSpaceXformCanvas
// in order to enforce non-gamma-aware pixel math behaviour.
@@ -73,6 +73,7 @@ class PLATFORM_EXPORT CanvasColorParams {
// The pixel format to use for allocating SkSurfaces.
SkColorType GetSkColorType() const;
+ static SkColorType PixelFormatToSkColorType(CanvasPixelFormat pixel_format);
uint8_t BytesPerPixel() const;
// The color space in which pixels read from the canvas via a shader will be
@@ -83,6 +84,8 @@ class PLATFORM_EXPORT CanvasColorParams {
// Return the color space of the underlying data for the canvas.
gfx::ColorSpace GetStorageGfxColorSpace() const;
sk_sp<SkColorSpace> GetSkColorSpace() const;
+ static sk_sp<SkColorSpace> CanvasColorSpaceToSkColorSpace(
+ CanvasColorSpace color_space);
SkAlphaType GetSkAlphaType() const;
const SkSurfaceProps* GetSkSurfaceProps() const;
@@ -95,6 +98,9 @@ class PLATFORM_EXPORT CanvasColorParams {
viz::ResourceFormat TransferableResourceFormat() const;
private:
+ CanvasColorParams(const sk_sp<SkColorSpace> color_space,
+ SkColorType color_type);
+
CanvasColorSpace color_space_ = kSRGBCanvasColorSpace;
CanvasPixelFormat pixel_format_ = kRGBA8CanvasPixelFormat;
OpacityMode opacity_mode_ = kNonOpaque;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params_test.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params_test.cc
index 8616bf8ad23..1a63e589660 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_color_params_test.cc
@@ -18,9 +18,10 @@ namespace blink {
// spaces are approximately the same for different CanvasColorParam objects.
TEST(CanvasColorParamsTest, MatchSkColorSpaceWithGfxColorSpace) {
CanvasColorSpace canvas_color_spaces[] = {
- kSRGBCanvasColorSpace, kRec2020CanvasColorSpace, kP3CanvasColorSpace,
+ kSRGBCanvasColorSpace, kLinearRGBCanvasColorSpace,
+ kRec2020CanvasColorSpace, kP3CanvasColorSpace,
};
- for (int iter_color_space = 0; iter_color_space < 3; iter_color_space++) {
+ for (int iter_color_space = 0; iter_color_space < 4; iter_color_space++) {
CanvasColorParams color_params(canvas_color_spaces[iter_color_space],
kF16CanvasPixelFormat, kNonOpaque);
sk_sp<SkColorSpace> canvas_drawing_color_space =
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h
index d95bad3ef20..f70a866e12e 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h
@@ -9,7 +9,7 @@
namespace blink {
-namespace CanvasHeuristicParameters {
+namespace canvas_heuristic_parameters {
enum {
// Disable Deferral overdraw parameters
@@ -80,7 +80,7 @@ enum {
}; // enum
-} // namespace CanvasHeuristicParameters
+} // namespace canvas_heuristic_parameters
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.cc
deleted file mode 100644
index d57c6173e09..00000000000
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.cc
+++ /dev/null
@@ -1,21 +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 "third_party/blink/renderer/platform/graphics/canvas_metrics.h"
-
-#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
-#include "third_party/blink/renderer/platform/wtf/threading.h"
-
-namespace blink {
-
-void CanvasMetrics::CountCanvasContextUsage(
- const CanvasContextUsage canvas_context_usage) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- EnumerationHistogram, usage_histogram,
- ("WebCore.CanvasContextUsage", CanvasContextUsage::kNumberOfUsages));
- usage_histogram.Count(canvas_context_usage);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.h
deleted file mode 100644
index 0958ba51ade..00000000000
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_metrics.h
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CANVAS_METRICS_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CANVAS_METRICS_H_
-
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-
-namespace blink {
-
-class PLATFORM_EXPORT CanvasMetrics {
- STATIC_ONLY(CanvasMetrics);
-
- public:
- enum CanvasContextUsage {
- kCanvasCreated = 0,
- kGPUAccelerated2DCanvasImageBufferCreated = 1,
- kUnaccelerated2DCanvasImageBufferCreated = 3,
- kAccelerated2DCanvasGPUContextLost = 4,
- kUnaccelerated2DCanvasImageBufferCreationFailed = 5,
- kGPUAccelerated2DCanvasImageBufferCreationFailed = 6,
- kGPUAccelerated2DCanvasDeferralDisabled = 8,
- kGPUAccelerated2DCanvasSurfaceCreationFailed = 9,
- kNumberOfUsages
- };
-
- static void CountCanvasContextUsage(const CanvasContextUsage);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CANVAS_METRICS_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.cc
index 72b2aa728e9..69d5a9a547f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.cc
@@ -39,7 +39,7 @@ CanvasResource::CanvasResource(base::WeakPtr<CanvasResourceProvider> provider,
: provider_(std::move(provider)),
filter_quality_(filter_quality),
color_params_(color_params) {
- thread_of_origin_ = Platform::Current()->CurrentThread()->ThreadId();
+ thread_of_origin_ = Thread::Current()->ThreadId();
}
CanvasResource::~CanvasResource() {
@@ -49,7 +49,7 @@ CanvasResource::~CanvasResource() {
}
void CanvasResource::OnDestroy() {
- if (thread_of_origin_ != Platform::Current()->CurrentThread()->ThreadId()) {
+ if (thread_of_origin_ != Thread::Current()->ThreadId()) {
// Destroyed on wrong thread. This can happen when the thread of origin was
// torn down, in which case the GPU context owning any underlying resources
// no longer exists.
@@ -97,19 +97,15 @@ bool CanvasResource::PrepareTransferableResource(
DCHECK(IsValid());
DCHECK(out_callback);
- scoped_refptr<CanvasResource> this_ref(this);
auto func = WTF::Bind(&ReleaseFrameResources, provider_,
- WTF::Passed(std::move(this_ref)));
+ WTF::Passed(base::WrapRefCounted(this)));
*out_callback = viz::SingleReleaseCallback::Create(std::move(func));
- if (out_resource) {
- if (SupportsAcceleratedCompositing()) {
- return PrepareAcceleratedTransferableResource(out_resource, sync_mode);
- }
-
- return PrepareUnacceleratedTransferableResource(out_resource);
- }
- return true;
+ if (!out_resource)
+ return true;
+ if (SupportsAcceleratedCompositing())
+ return PrepareAcceleratedTransferableResource(out_resource, sync_mode);
+ return PrepareUnacceleratedTransferableResource(out_resource);
}
bool CanvasResource::PrepareAcceleratedTransferableResource(
@@ -182,18 +178,13 @@ scoped_refptr<CanvasResourceBitmap> CanvasResourceBitmap::Create(
base::WeakPtr<CanvasResourceProvider> provider,
SkFilterQuality filter_quality,
const CanvasColorParams& color_params) {
- scoped_refptr<CanvasResourceBitmap> resource =
- AdoptRef(new CanvasResourceBitmap(std::move(image), std::move(provider),
- filter_quality, color_params));
- if (resource->IsValid())
- return resource;
- return nullptr;
+ auto resource = AdoptRef(new CanvasResourceBitmap(
+ std::move(image), std::move(provider), filter_quality, color_params));
+ return resource->IsValid() ? resource : nullptr;
}
bool CanvasResourceBitmap::IsValid() const {
- if (!image_)
- return false;
- return image_->IsValid();
+ return image_ ? image_->IsValid() : false;
}
bool CanvasResourceBitmap::IsAccelerated() const {
@@ -320,12 +311,9 @@ CanvasResourceGpuMemoryBuffer::CanvasResourceGpuMemoryBuffer(
if (!gl || !gr)
return;
- gfx::BufferUsage buffer_usage;
- if (is_accelerated) {
- buffer_usage = gfx::BufferUsage::SCANOUT;
- } else {
- buffer_usage = gfx::BufferUsage::SCANOUT_CPU_READ_WRITE;
- }
+ const gfx::BufferUsage buffer_usage =
+ is_accelerated ? gfx::BufferUsage::SCANOUT
+ : gfx::BufferUsage::SCANOUT_CPU_READ_WRITE;
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager =
Platform::Current()->GetGpuMemoryBufferManager();
@@ -334,25 +322,23 @@ CanvasResourceGpuMemoryBuffer::CanvasResourceGpuMemoryBuffer(
gpu_memory_buffer_ = gpu_memory_buffer_manager->CreateGpuMemoryBuffer(
gfx::Size(size.Width(), size.Height()), ColorParams().GetBufferFormat(),
buffer_usage, gpu::kNullSurfaceHandle);
- if (!gpu_memory_buffer_) {
+ if (!gpu_memory_buffer_)
return;
- }
+
gpu_memory_buffer_->SetColorSpace(color_params.GetStorageGfxColorSpace());
- image_id_ = gl->CreateImageCHROMIUM(gpu_memory_buffer_->AsClientBuffer(),
- size.Width(), size.Height(),
- ColorParams().GLUnsizedInternalFormat());
- if (!image_id_) {
+ const GLuint image_id = gl->CreateImageCHROMIUM(
+ gpu_memory_buffer_->AsClientBuffer(), size.Width(), size.Height(),
+ ColorParams().GLUnsizedInternalFormat());
+ if (!image_id) {
gpu_memory_buffer_ = nullptr;
return;
}
gl->GenTextures(1, &texture_id_);
const GLenum target = TextureTarget();
gl->BindTexture(target, texture_id_);
- // TODO(mcasas): consider making |image_id_| a local variable and balancing
- // BindTexImage2DCHROMIUM() with DestroyImageCHROMIUM(), leaving |texture_id_|
- // to keep alive the Image2DCHROMIUM.
- gl->BindTexImage2DCHROMIUM(target, image_id_);
+ gl->BindTexImage2DCHROMIUM(target, image_id);
+ gl->DestroyImageCHROMIUM(image_id);
if (is_accelerated_ && target == GL_TEXTURE_EXTERNAL_OES) {
// We can't CopyTextureCHROMIUM() into a GL_TEXTURE_EXTERNAL_OES; create
@@ -374,7 +360,7 @@ CanvasResourceGpuMemoryBuffer::~CanvasResourceGpuMemoryBuffer() {
}
bool CanvasResourceGpuMemoryBuffer::IsValid() const {
- return !!context_provider_wrapper_ && image_id_;
+ return !!context_provider_wrapper_ && gpu_memory_buffer_;
}
GLenum CanvasResourceGpuMemoryBuffer::TextureTarget() const {
@@ -382,8 +368,7 @@ GLenum CanvasResourceGpuMemoryBuffer::TextureTarget() const {
}
IntSize CanvasResourceGpuMemoryBuffer::Size() const {
- return IntSize(gpu_memory_buffer_->GetSize().width(),
- gpu_memory_buffer_->GetSize().height());
+ return IntSize(gpu_memory_buffer_->GetSize());
}
scoped_refptr<CanvasResourceGpuMemoryBuffer>
@@ -395,14 +380,10 @@ CanvasResourceGpuMemoryBuffer::Create(
SkFilterQuality filter_quality,
bool is_accelerated) {
TRACE_EVENT0("blink", "CanvasResourceGpuMemoryBuffer::Create");
-
- scoped_refptr<CanvasResourceGpuMemoryBuffer> resource =
- AdoptRef(new CanvasResourceGpuMemoryBuffer(
- size, color_params, std::move(context_provider_wrapper),
- std::move(provider), filter_quality, is_accelerated));
- if (resource->IsValid())
- return resource;
- return nullptr;
+ auto resource = AdoptRef(new CanvasResourceGpuMemoryBuffer(
+ size, color_params, std::move(context_provider_wrapper),
+ std::move(provider), filter_quality, is_accelerated));
+ return resource->IsValid() ? resource : nullptr;
}
void CanvasResourceGpuMemoryBuffer::TearDown() {
@@ -410,16 +391,13 @@ void CanvasResourceGpuMemoryBuffer::TearDown() {
DCHECK(!surface_ || surface_->unique());
surface_ = nullptr;
- if (context_provider_wrapper_ && image_id_) {
+ if (context_provider_wrapper_) {
auto* gl = ContextGL();
- if (gl && image_id_)
- gl->DestroyImageCHROMIUM(image_id_);
if (gl && texture_id_)
gl->DeleteTextures(1, &texture_id_);
if (gl && texture_2d_id_for_copy_)
gl->DeleteTextures(1, &texture_2d_id_for_copy_);
}
- image_id_ = 0;
texture_id_ = 0;
texture_2d_id_for_copy_ = 0;
gpu_memory_buffer_ = nullptr;
@@ -427,7 +405,6 @@ void CanvasResourceGpuMemoryBuffer::TearDown() {
void CanvasResourceGpuMemoryBuffer::Abandon() {
surface_ = nullptr;
- image_id_ = 0;
texture_id_ = 0;
texture_2d_id_for_copy_ = 0;
gpu_memory_buffer_ = nullptr;
@@ -449,6 +426,10 @@ bool CanvasResourceGpuMemoryBuffer::HasGpuMailbox() const {
return !gpu_mailbox_.IsZero();
}
+GLuint CanvasResourceGpuMemoryBuffer::GetBackingTextureHandleForOverwrite() {
+ return texture_2d_id_for_copy_ ? texture_2d_id_for_copy_ : texture_id_;
+}
+
const gpu::SyncToken CanvasResourceGpuMemoryBuffer::GetSyncToken() {
if (mailbox_needs_new_sync_token_) {
auto* gl = ContextGL();
@@ -490,8 +471,6 @@ void CanvasResourceGpuMemoryBuffer::CopyFromTexture(GLuint source_texture,
}
void CanvasResourceGpuMemoryBuffer::TakeSkImage(sk_sp<SkImage> image) {
- TRACE_EVENT0("blink", "CanvasResourceGpuMemoryBuffer::CopyFromTexture");
-
WillPaint();
if (!surface_)
return;
@@ -638,12 +617,9 @@ scoped_refptr<CanvasResourceSharedBitmap> CanvasResourceSharedBitmap::Create(
const CanvasColorParams& color_params,
base::WeakPtr<CanvasResourceProvider> provider,
SkFilterQuality filter_quality) {
- scoped_refptr<CanvasResourceSharedBitmap> resource =
- AdoptRef(new CanvasResourceSharedBitmap(
- size, color_params, std::move(provider), filter_quality));
- if (resource->IsValid())
- return resource;
- return nullptr;
+ auto resource = AdoptRef(new CanvasResourceSharedBitmap(
+ size, color_params, std::move(provider), filter_quality));
+ return resource->IsValid() ? resource : nullptr;
}
void CanvasResourceSharedBitmap::TearDown() {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.h
index b15ccb9558b..113d199f700 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource.h
@@ -86,6 +86,11 @@ class PLATFORM_EXPORT CanvasResource
// Only CanvasResourceProvider and derivatives should call this.
virtual void TakeSkImage(sk_sp<SkImage> image) = 0;
+ virtual GLuint GetBackingTextureHandleForOverwrite() {
+ NOTREACHED();
+ return 0;
+ }
+
protected:
CanvasResource(base::WeakPtr<CanvasResourceProvider>,
SkFilterQuality,
@@ -208,6 +213,7 @@ class PLATFORM_EXPORT CanvasResourceGpuMemoryBuffer final
GLenum format,
GLenum type) override;
scoped_refptr<StaticBitmapImage> Bitmap() override;
+ GLuint GetBackingTextureHandleForOverwrite() final;
private:
void TearDown() override;
@@ -236,7 +242,6 @@ class PLATFORM_EXPORT CanvasResourceGpuMemoryBuffer final
std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer_;
void* buffer_base_address_ = nullptr;
sk_sp<SkSurface> surface_;
- GLuint image_id_ = 0;
GLuint texture_id_ = 0;
MailboxSyncMode mailbox_sync_mode_ = kVerifiedSyncToken;
bool is_accelerated_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc
index 51b95ff6ca3..d66820e97e0 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc
@@ -6,6 +6,7 @@
#include <memory>
#include "base/single_thread_task_runner.h"
+#include "components/viz/common/features.h"
#include "components/viz/common/quads/compositor_frame.h"
#include "components/viz/common/quads/texture_draw_quad.h"
#include "components/viz/common/resources/resource_format.h"
@@ -19,8 +20,8 @@
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.h"
#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -58,6 +59,8 @@ CanvasResourceDispatcher::CanvasResourceDispatcher(
placeholder_canvas_id_(canvas_id),
num_unreclaimed_frames_posted_(0),
client_(client),
+ enable_surface_synchronization_(
+ features::IsSurfaceSynchronizationEnabled()),
weak_ptr_factory_(this) {
// Frameless canvas pass an invalid |frame_sink_id_|; don't create mojo
// channel for this special case.
@@ -72,7 +75,8 @@ CanvasResourceDispatcher::CanvasResourceDispatcher(
DCHECK(provider);
binding_.Bind(mojo::MakeRequest(&client_ptr_));
provider->CreateCompositorFrameSink(frame_sink_id_, std::move(client_ptr_),
- mojo::MakeRequest(&sink_));
+ mojo::MakeRequest(&sink_),
+ mojo::MakeRequest(&surface_embedder_));
}
CanvasResourceDispatcher::~CanvasResourceDispatcher() = default;
@@ -125,15 +129,14 @@ void CanvasResourceDispatcher::PostImageToPlaceholder(
scoped_refptr<CanvasResource> canvas_resource,
viz::ResourceId resource_id) {
scoped_refptr<base::SingleThreadTaskRunner> dispatcher_task_runner =
- Platform::Current()->CurrentThread()->GetTaskRunner();
+ Thread::Current()->GetTaskRunner();
// After this point, |canvas_resource| can only be used on the main thread,
// until it is returned.
canvas_resource->Transfer();
PostCrossThreadTask(
- *Platform::Current()->MainThread()->Scheduler()->CompositorTaskRunner(),
- FROM_HERE,
+ *Thread::MainThread()->Scheduler()->CompositorTaskRunner(), FROM_HERE,
CrossThreadBind(UpdatePlaceholderImage, this->GetWeakPtr(),
WTF::Passed(std::move(dispatcher_task_runner)),
placeholder_canvas_id_, std::move(canvas_resource),
@@ -156,7 +159,8 @@ void CanvasResourceDispatcher::DispatchFrameSync(
pending_compositor_frames_++;
WTF::Vector<viz::ReturnedResource> resources;
sink_->SubmitCompositorFrameSync(
- parent_local_surface_id_allocator_.GetCurrentLocalSurfaceId(),
+ parent_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id(),
std::move(frame), nullptr, 0, &resources);
DidReceiveCompositorFrameAck(resources);
}
@@ -176,7 +180,8 @@ void CanvasResourceDispatcher::DispatchFrame(
pending_compositor_frames_++;
sink_->SubmitCompositorFrame(
- parent_local_surface_id_allocator_.GetCurrentLocalSurfaceId(),
+ parent_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id(),
std::move(frame), nullptr, 0);
}
@@ -226,33 +231,6 @@ bool CanvasResourceDispatcher::PrepareFrame(
sqs->SetAll(gfx::Transform(), bounds, bounds, bounds, is_clipped, is_opaque,
1.f, SkBlendMode::kSrcOver, 0);
- OffscreenCanvasCommitType commit_type;
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- EnumerationHistogram, commit_type_histogram,
- ("OffscreenCanvas.CommitType", kOffscreenCanvasCommitTypeCount));
- if (canvas_resource->IsAccelerated()) {
- // While |image| is texture backed, it could be generated with "software
- // rendering" aka swiftshader. If the compositor is not also using
- // swiftshader, then we could not give a swiftshader based texture
- // to the compositor. However in that case, IsGpuCompositingEnabled() will
- // also be false, so we will avoid doing so.
- if (SharedGpuContext::IsGpuCompositingEnabled()) {
- // Case 1: both canvas and compositor are gpu accelerated.
- commit_type = kCommitGPUCanvasGPUCompositing;
- } else {
- // Case 2: canvas is accelerated but gpu compositing is disabled.
- commit_type = kCommitGPUCanvasSoftwareCompositing;
- }
- } else {
- if (SharedGpuContext::IsGpuCompositingEnabled()) {
- // Case 3: canvas is not gpu-accelerated, but compositor is.
- commit_type = kCommitSoftwareCanvasGPUCompositing;
- } else {
- // Case 4: both canvas and compositor are not gpu accelerated.
- commit_type = kCommitSoftwareCanvasSoftwareCompositing;
- }
- }
-
viz::TransferableResource resource;
auto frame_resource = std::make_unique<FrameResource>();
@@ -265,8 +243,6 @@ bool CanvasResourceDispatcher::PrepareFrame(
// TODO(crbug.com/869913): add unit testing for this.
const gfx::Size canvas_resource_size(canvas_resource->Size());
- commit_type_histogram.Count(commit_type);
-
PostImageToPlaceholderIfNotBlocked(std::move(canvas_resource),
next_resource_id_);
@@ -295,100 +271,25 @@ bool CanvasResourceDispatcher::PrepareFrame(
quad->SetAll(sqs, bounds, bounds, needs_blending, resource.id,
canvas_resource_size, kPremultipliedAlpha, uv_top_left,
uv_bottom_right, SK_ColorTRANSPARENT, vertex_opacity, yflipped,
- kNearestNeighbor, false);
+ kNearestNeighbor, /*secure_output_only=*/false,
+ ui::ProtectedVideoType::kClear);
frame->render_pass_list.push_back(std::move(pass));
- base::TimeDelta elapsed_time = WTF::CurrentTimeTicks() - commit_start_time;
-
- switch (commit_type) {
- case kCommitGPUCanvasGPUCompositing:
- if (IsMainThread()) {
- DEFINE_STATIC_LOCAL(
- CustomCountHistogram, commit_gpu_canvas_gpu_compositing_main_timer,
- ("Blink.Canvas.OffscreenCommit.GPUCanvasGPUCompositingMain", 0,
- 10000000, 50));
- commit_gpu_canvas_gpu_compositing_main_timer.CountMicroseconds(
- elapsed_time);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_gpu_canvas_gpu_compositing_worker_timer,
- ("Blink.Canvas.OffscreenCommit.GPUCanvasGPUCompositingWorker", 0,
- 10000000, 50));
- commit_gpu_canvas_gpu_compositing_worker_timer.CountMicroseconds(
- elapsed_time);
- }
- break;
- case kCommitGPUCanvasSoftwareCompositing:
- if (IsMainThread()) {
- DEFINE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_gpu_canvas_software_compositing_main_timer,
- ("Blink.Canvas.OffscreenCommit.GPUCanvasSoftwareCompositingMain", 0,
- 10000000, 50));
- commit_gpu_canvas_software_compositing_main_timer.CountMicroseconds(
- elapsed_time);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_gpu_canvas_software_compositing_worker_timer,
- ("Blink.Canvas.OffscreenCommit."
- "GPUCanvasSoftwareCompositingWorker",
- 0, 10000000, 50));
- commit_gpu_canvas_software_compositing_worker_timer.CountMicroseconds(
- elapsed_time);
- }
- break;
- case kCommitSoftwareCanvasGPUCompositing:
- if (IsMainThread()) {
- DEFINE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_software_canvas_gpu_compositing_main_timer,
- ("Blink.Canvas.OffscreenCommit.SoftwareCanvasGPUCompositingMain", 0,
- 10000000, 50));
- commit_software_canvas_gpu_compositing_main_timer.CountMicroseconds(
- elapsed_time);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_software_canvas_gpu_compositing_worker_timer,
- ("Blink.Canvas.OffscreenCommit."
- "SoftwareCanvasGPUCompositingWorker",
- 0, 10000000, 50));
- commit_software_canvas_gpu_compositing_worker_timer.CountMicroseconds(
- elapsed_time);
- }
- break;
- case kCommitSoftwareCanvasSoftwareCompositing:
- if (IsMainThread()) {
- DEFINE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_software_canvas_software_compositing_main_timer,
- ("Blink.Canvas.OffscreenCommit."
- "SoftwareCanvasSoftwareCompositingMain",
- 0, 10000000, 50));
- commit_software_canvas_software_compositing_main_timer
- .CountMicroseconds(elapsed_time);
- } else {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- CustomCountHistogram,
- commit_software_canvas_software_compositing_worker_timer,
- ("Blink.Canvas.OffscreenCommit."
- "SoftwareCanvasSoftwareCompositingWorker",
- 0, 10000000, 50));
- commit_software_canvas_software_compositing_worker_timer
- .CountMicroseconds(elapsed_time);
- }
- break;
- case kOffscreenCanvasCommitTypeCount:
- NOTREACHED();
- }
-
- if (change_size_for_next_commit_) {
+ if (change_size_for_next_commit_ ||
+ !parent_local_surface_id_allocator_.HasValidLocalSurfaceIdAllocation()) {
parent_local_surface_id_allocator_.GenerateId();
+ if (enable_surface_synchronization_) {
+ surface_embedder_->SetLocalSurfaceId(
+ parent_local_surface_id_allocator_
+ .GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id());
+ }
change_size_for_next_commit_ = false;
}
+ frame->metadata.local_surface_id_allocation_time =
+ parent_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .allocation_time();
return true;
}
@@ -400,12 +301,6 @@ void CanvasResourceDispatcher::DidReceiveCompositorFrameAck(
DCHECK_GE(pending_compositor_frames_, 0);
}
-void CanvasResourceDispatcher::DidPresentCompositorFrame(
- uint32_t presentation_token,
- ::gfx::mojom::blink::PresentationFeedbackPtr feedback) {
- NOTIMPLEMENTED();
-}
-
void CanvasResourceDispatcher::SetNeedsBeginFrame(bool needs_begin_frame) {
if (needs_begin_frame_ == needs_begin_frame)
return;
@@ -428,7 +323,8 @@ void CanvasResourceDispatcher::SetNeedsBeginFrameInternal() {
}
void CanvasResourceDispatcher::OnBeginFrame(
- const viz::BeginFrameArgs& begin_frame_args) {
+ const viz::BeginFrameArgs& begin_frame_args,
+ WTF::HashMap<uint32_t, ::gfx::mojom::blink::PresentationFeedbackPtr>) {
current_begin_frame_ack_ = viz::BeginFrameAck(begin_frame_args, false);
if (pending_compositor_frames_ >= kMaxPendingCompositorFrames ||
(begin_frame_args.type == viz::BeginFrameArgs::MISSED &&
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h
index 3cf5341b952..299818c4434 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h
@@ -11,6 +11,7 @@
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/frame_sinks/embedded_frame_sink.mojom-blink.h"
#include "third_party/blink/renderer/platform/wtf/compiler.h"
namespace blink {
@@ -63,10 +64,10 @@ class PLATFORM_EXPORT CanvasResourceDispatcher
// viz::mojom::blink::CompositorFrameSinkClient implementation.
void DidReceiveCompositorFrameAck(
const WTF::Vector<viz::ReturnedResource>& resources) final;
- void DidPresentCompositorFrame(
- uint32_t presentation_token,
- ::gfx::mojom::blink::PresentationFeedbackPtr feedback) final;
- void OnBeginFrame(const viz::BeginFrameArgs&) final;
+ void OnBeginFrame(
+ const viz::BeginFrameArgs&,
+ WTF::HashMap<uint32_t, ::gfx::mojom::blink::PresentationFeedbackPtr>)
+ final;
void OnBeginFramePausedChanged(bool paused) final{};
void ReclaimResources(
const WTF::Vector<viz::ReturnedResource>& resources) final;
@@ -75,15 +76,6 @@ class PLATFORM_EXPORT CanvasResourceDispatcher
::gpu::mojom::blink::MailboxPtr id);
void DidDeleteSharedBitmap(::gpu::mojom::blink::MailboxPtr id);
- // This enum is used in histogram, so it should be append-only.
- enum OffscreenCanvasCommitType {
- kCommitGPUCanvasGPUCompositing = 0,
- kCommitGPUCanvasSoftwareCompositing = 1,
- kCommitSoftwareCanvasGPUCompositing = 2,
- kCommitSoftwareCanvasSoftwareCompositing = 3,
- kOffscreenCanvasCommitTypeCount,
- };
-
private:
friend class CanvasResourceDispatcherTest;
struct FrameResource;
@@ -119,6 +111,7 @@ class PLATFORM_EXPORT CanvasResourceDispatcher
void ReclaimResourceInternal(const ResourceMap::iterator&);
viz::mojom::blink::CompositorFrameSinkPtr sink_;
+ mojom::blink::SurfaceEmbedderPtr surface_embedder_;
mojo::Binding<viz::mojom::blink::CompositorFrameSinkClient> binding_;
viz::mojom::blink::CompositorFrameSinkClientPtr client_ptr_;
@@ -137,6 +130,8 @@ class PLATFORM_EXPORT CanvasResourceDispatcher
CanvasResourceDispatcherClient* client_;
+ const bool enable_surface_synchronization_;
+
base::WeakPtrFactory<CanvasResourceDispatcher> weak_ptr_factory_;
};
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
index 4b63a08410e..d04b01988af 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
@@ -4,36 +4,27 @@
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
+#include "base/metrics/histogram_functions.h"
#include "cc/paint/decode_stashing_image_provider.h"
-#include "cc/paint/skia_paint_canvas.h"
#include "cc/tiles/software_image_decode_cache.h"
#include "components/viz/common/resources/resource_format_utils.h"
-#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/common/capabilities.h"
-#include "gpu/command_buffer/common/gpu_memory_buffer_support.h"
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "gpu/config/gpu_feature_info.h"
#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/canvas_heuristic_parameters.h"
-#include "third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
-#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/skia/include/core/SkColorSpaceXformCanvas.h"
-#include "third_party/skia/include/gpu/GrBackendSurface.h"
-#include "third_party/skia/include/gpu/GrContext.h"
-#include "ui/gfx/gpu_memory_buffer.h"
namespace blink {
-// CanvasResourceProviderTexture
-//==============================================================================
-//
-// * Renders to a texture managed by skia. Mailboxes are straight GL textures.
-// * Layers are not overlay candidates
+void CanvasResourceProvider::RecordTypeToUMA(ResourceProviderType type) {
+ base::UmaHistogramEnumeration("Blink.Canvas.ResourceProviderType", type);
+}
+// * Renders to a texture managed by Skia. Mailboxes are backed by vanilla GL
+// textures.
+// * Layers are not overlay candidates.
class CanvasResourceProviderTexture : public CanvasResourceProvider {
public:
CanvasResourceProviderTexture(
@@ -49,7 +40,9 @@ class CanvasResourceProviderTexture : public CanvasResourceProvider {
std::move(context_provider_wrapper),
std::move(resource_dispatcher)),
msaa_sample_count_(msaa_sample_count),
- is_origin_top_left_(is_origin_top_left) {}
+ is_origin_top_left_(is_origin_top_left) {
+ RecordTypeToUMA(kTexture);
+ }
~CanvasResourceProviderTexture() override = default;
@@ -86,7 +79,7 @@ class CanvasResourceProviderTexture : public CanvasResourceProvider {
// A readback operation may alter the texture parameters, which may affect
// the compositor's behavior. Therefore, we must trigger copy-on-write
// even though we are not technically writing to the texture, only to its
- // parameters.
+ // parameters. This issue is Android-WebView specific: crbug.com/585250.
// If this issue with readback affecting state is ever fixed, then we'll
// have to do this instead of triggering a copy-on-write:
// static_cast<AcceleratedStaticBitmapImage*>(image.get())
@@ -136,13 +129,9 @@ class CanvasResourceProviderTexture : public CanvasResourceProvider {
const bool is_origin_top_left_;
};
-// CanvasResourceProviderTextureGpuMemoryBuffer
-//==============================================================================
-//
-// * Renders to a texture managed by skia. Mailboxes are
-// gpu-accelerated platform native surfaces.
-// * Layers are overlay candidates
-
+// * Renders to a texture managed by Skia. Mailboxes are GPU-accelerated
+// platform native surfaces.
+// * Layers are overlay candidates.
class CanvasResourceProviderTextureGpuMemoryBuffer final
: public CanvasResourceProviderTexture {
public:
@@ -159,7 +148,9 @@ class CanvasResourceProviderTextureGpuMemoryBuffer final
color_params,
std::move(context_provider_wrapper),
std::move(resource_dispatcher),
- is_origin_top_left) {}
+ is_origin_top_left) {
+ RecordTypeToUMA(kTextureGpuMemoryBuffer);
+ }
~CanvasResourceProviderTextureGpuMemoryBuffer() override = default;
bool SupportsDirectCompositing() const override { return true; }
@@ -179,7 +170,6 @@ class CanvasResourceProviderTextureGpuMemoryBuffer final
scoped_refptr<CanvasResource> ProduceFrame() final {
TRACE_EVENT0("blink",
"CanvasResourceProviderTextureGpuMemoreBuffer::ProduceFrame");
-
DCHECK(GetSkSurface());
if (IsGpuContextLost())
@@ -208,17 +198,12 @@ class CanvasResourceProviderTextureGpuMemoryBuffer final
output_resource->CopyFromTexture(skia_texture_id,
ColorParams().GLUnsizedInternalFormat(),
ColorParams().GLType());
-
return output_resource;
}
};
-// CanvasResourceProviderBitmap
-//==============================================================================
-//
-// * Renders to a skia RAM-backed bitmap
-// * Mailboxing is not supported : cannot be directly composited
-
+// * Renders to a Skia RAM-backed bitmap.
+// * Mailboxing is not supported : cannot be directly composited.
class CanvasResourceProviderBitmap : public CanvasResourceProvider {
public:
CanvasResourceProviderBitmap(
@@ -230,7 +215,9 @@ class CanvasResourceProviderBitmap : public CanvasResourceProvider {
: CanvasResourceProvider(size,
color_params,
std::move(context_provider_wrapper),
- std::move(resource_dispatcher)) {}
+ std::move(resource_dispatcher)) {
+ RecordTypeToUMA(kBitmap);
+ }
~CanvasResourceProviderBitmap() override = default;
@@ -253,17 +240,13 @@ class CanvasResourceProviderBitmap : public CanvasResourceProvider {
}
};
-// CanvasResourceProviderRamGpuMemoryBuffer
-//==============================================================================
-//
-// * Renders to a ram memory buffer managed by skia
+// * Renders to a ram memory buffer managed by Skia
// * Uses GpuMemoryBuffer to pass frames to the compositor
// * Layers are overlay candidates
-
-class CanvasResourceProviderRamGpuMemoryBuffer final
+class CanvasResourceProviderBitmapGpuMemoryBuffer final
: public CanvasResourceProviderBitmap {
public:
- CanvasResourceProviderRamGpuMemoryBuffer(
+ CanvasResourceProviderBitmapGpuMemoryBuffer(
const IntSize& size,
const CanvasColorParams color_params,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>
@@ -272,16 +255,18 @@ class CanvasResourceProviderRamGpuMemoryBuffer final
: CanvasResourceProviderBitmap(size,
color_params,
std::move(context_provider_wrapper),
- std::move(resource_dispatcher)) {}
+ std::move(resource_dispatcher)) {
+ RecordTypeToUMA(kBitmapGpuMemoryBuffer);
+ }
- ~CanvasResourceProviderRamGpuMemoryBuffer() override = default;
+ ~CanvasResourceProviderBitmapGpuMemoryBuffer() override = default;
bool SupportsDirectCompositing() const override { return true; }
bool SupportsSingleBuffering() const override { return true; }
private:
scoped_refptr<CanvasResource> CreateResource() final {
TRACE_EVENT0("blink",
- "CanvasResourceProviderRamGpuMemoryBuffer::CreateResource");
+ "CanvasResourceProviderBitmapGpuMemoryBuffer::CreateResource");
constexpr bool is_accelerated = false;
return CanvasResourceGpuMemoryBuffer::Create(
@@ -291,7 +276,7 @@ class CanvasResourceProviderRamGpuMemoryBuffer final
scoped_refptr<CanvasResource> ProduceFrame() final {
TRACE_EVENT0("blink",
- "CanvasResourceProviderRamGpuMemoryBuffer::ProduceFrame");
+ "CanvasResourceProviderBitmapGpuMemoryBuffer::ProduceFrame");
DCHECK(GetSkSurface());
@@ -312,12 +297,8 @@ class CanvasResourceProviderRamGpuMemoryBuffer final
}
};
-// CanvasResourceProviderSharedBitmap
-//==============================================================================
-//
-// * Renders to a shared memory bitmap
-// * Uses SharedBitmaps to pass frames directly to the compositor
-
+// * Renders to a shared memory bitmap.
+// * Uses SharedBitmaps to pass frames directly to the compositor.
class CanvasResourceProviderSharedBitmap : public CanvasResourceProviderBitmap {
public:
CanvasResourceProviderSharedBitmap(
@@ -329,6 +310,7 @@ class CanvasResourceProviderSharedBitmap : public CanvasResourceProviderBitmap {
nullptr, // context_provider_wrapper
std::move(resource_dispatcher)) {
DCHECK(ResourceDispatcher());
+ RecordTypeToUMA(kSharedBitmap);
}
~CanvasResourceProviderSharedBitmap() override = default;
bool SupportsDirectCompositing() const override { return true; }
@@ -350,10 +332,8 @@ class CanvasResourceProviderSharedBitmap : public CanvasResourceProviderBitmap {
scoped_refptr<CanvasResource> ProduceFrame() final {
DCHECK(GetSkSurface());
scoped_refptr<CanvasResource> output_resource = NewOrRecycledResource();
- if (!output_resource) {
- // Not compositable without a SharedBitmap
+ if (!output_resource)
return nullptr;
- }
auto paint_image = MakeImageSnapshot();
if (!paint_image)
@@ -366,19 +346,107 @@ class CanvasResourceProviderSharedBitmap : public CanvasResourceProviderBitmap {
}
};
-// CanvasResourceProvider base class implementation
-//==============================================================================
+// * Renders to a GpuMemoryBuffer-backed texture used to create a SkSurface.
+// * Layers are overlay candidates
+class CanvasResourceProviderDirectGpuMemoryBuffer final
+ : public CanvasResourceProvider {
+ public:
+ CanvasResourceProviderDirectGpuMemoryBuffer(
+ const IntSize& size,
+ unsigned msaa_sample_count,
+ const CanvasColorParams color_params,
+ base::WeakPtr<WebGraphicsContext3DProviderWrapper>
+ context_provider_wrapper,
+ base::WeakPtr<CanvasResourceDispatcher> resource_dispatcher,
+ bool is_origin_top_left)
+ : CanvasResourceProvider(size,
+ color_params,
+ std::move(context_provider_wrapper),
+ std::move(resource_dispatcher)),
+ msaa_sample_count_(msaa_sample_count),
+ is_origin_top_left_(is_origin_top_left) {
+ constexpr bool is_accelerated = true;
+ resource_ = CanvasResourceGpuMemoryBuffer::Create(
+ Size(), ColorParams(), ContextProviderWrapper(), CreateWeakPtr(),
+ FilterQuality(), is_accelerated);
+ }
+
+ ~CanvasResourceProviderDirectGpuMemoryBuffer() override = default;
+ bool IsValid() const final { return GetSkSurface() && !IsGpuContextLost(); }
+ bool IsAccelerated() const final { return true; }
+ bool SupportsDirectCompositing() const override { return true; }
+ bool SupportsSingleBuffering() const override { return true; }
+
+ private:
+ GLuint GetBackingTextureHandleForOverwrite() override {
+ return resource_->GetBackingTextureHandleForOverwrite();
+ }
+
+ scoped_refptr<CanvasResource> CreateResource() final {
+ TRACE_EVENT0("blink",
+ "CanvasResourceProviderDirectGpuMemoryBuffer::CreateResource");
+ DCHECK(resource_);
+ return resource_;
+ }
+
+ scoped_refptr<CanvasResource> ProduceFrame() final {
+ TRACE_EVENT0("blink",
+ "CanvasResourceProviderDirectGpuMemoryBuffer::ProduceFrame");
+ if (IsGpuContextLost())
+ return nullptr;
+ FlushSkia();
+
+ auto* gl = ContextGL();
+ DCHECK(gl);
+ gl->Flush();
+
+ return NewOrRecycledResource();
+ }
+
+ sk_sp<SkSurface> CreateSkSurface() const override {
+ if (IsGpuContextLost())
+ return nullptr;
+ auto* gr = GetGrContext();
+ DCHECK(gr);
+
+ GrGLTextureInfo texture_info = {};
+ texture_info.fID = resource_->GetBackingTextureHandleForOverwrite();
+ texture_info.fTarget = GL_TEXTURE_2D;
+ // Skia requires a sized internal format.
+ texture_info.fFormat = ColorParams().GLSizedInternalFormat();
+
+ const GrBackendTexture backend_texture(Size().Width(), Size().Height(),
+ GrMipMapped::kNo, texture_info);
+
+ const enum GrSurfaceOrigin surface_origin =
+ is_origin_top_left_ ? kTopLeft_GrSurfaceOrigin
+ : kBottomLeft_GrSurfaceOrigin;
+
+ auto surface = SkSurface::MakeFromBackendTextureAsRenderTarget(
+ gr, backend_texture, surface_origin, msaa_sample_count_,
+ ColorParams().GetSkColorType(),
+ ColorParams().GetSkColorSpaceForSkSurfaces(),
+ ColorParams().GetSkSurfaceProps());
+ return surface;
+ }
+
+ const unsigned msaa_sample_count_;
+ const bool is_origin_top_left_;
+ scoped_refptr<CanvasResource> resource_;
+};
enum CanvasResourceType {
+ kDirectGpuMemoryBufferResourceType,
kTextureGpuMemoryBufferResourceType,
- kRamGpuMemoryBufferResourceType,
+ kBitmapGpuMemoryBufferResourceType,
kSharedBitmapResourceType,
kTextureResourceType,
kBitmapResourceType,
};
constexpr CanvasResourceType kSoftwareCompositedFallbackList[] = {
- kRamGpuMemoryBufferResourceType, kSharedBitmapResourceType,
+ kBitmapGpuMemoryBufferResourceType,
+ kSharedBitmapResourceType,
// Fallback to no direct compositing support
kBitmapResourceType,
};
@@ -394,9 +462,23 @@ constexpr CanvasResourceType kAcceleratedFallbackList[] = {
};
constexpr CanvasResourceType kAcceleratedCompositedFallbackList[] = {
- kTextureGpuMemoryBufferResourceType, kTextureResourceType,
+ kTextureGpuMemoryBufferResourceType,
+ kTextureResourceType,
+ // Fallback to software composited
+ kBitmapGpuMemoryBufferResourceType,
+ kSharedBitmapResourceType,
+ // Fallback to no direct compositing support
+ kBitmapResourceType,
+};
+
+constexpr CanvasResourceType kAcceleratedDirectFallbackList[] = {
+ kDirectGpuMemoryBufferResourceType,
+ // The rest is equal to |kAcceleratedCompositedFallbackList|.
+ kTextureGpuMemoryBufferResourceType,
+ kTextureResourceType,
// Fallback to software composited
- kRamGpuMemoryBufferResourceType, kSharedBitmapResourceType,
+ kBitmapGpuMemoryBufferResourceType,
+ kSharedBitmapResourceType,
// Fallback to no direct compositing support
kBitmapResourceType,
};
@@ -430,19 +512,24 @@ std::unique_ptr<CanvasResourceProvider> CanvasResourceProvider::Create(
resource_type_fallback_list = kAcceleratedCompositedFallbackList;
list_length = arraysize(kAcceleratedCompositedFallbackList);
break;
+ case kAcceleratedDirectResourceUsage:
+ resource_type_fallback_list = kAcceleratedDirectFallbackList;
+ list_length = arraysize(kAcceleratedDirectFallbackList);
+ break;
}
std::unique_ptr<CanvasResourceProvider> provider;
for (size_t i = 0; i < list_length; ++i) {
// Note: We are deliberately not using std::move() on
- // context_provider_wrapper and resource_dispatcher to ensure that the
+ // |context_provider_wrapper| and |resource_dispatcher| to ensure that the
// pointers remain valid for the next iteration of this loop if necessary.
switch (resource_type_fallback_list[i]) {
case kTextureGpuMemoryBufferResourceType:
+ FALLTHROUGH;
+ case kDirectGpuMemoryBufferResourceType:
if (!SharedGpuContext::IsGpuCompositingEnabled())
continue;
- if (presentation_mode !=
- CanvasResourceProvider::kAllowImageChromiumPresentationMode)
+ if (presentation_mode != kAllowImageChromiumPresentationMode)
continue;
if (!context_provider_wrapper)
continue;
@@ -456,15 +543,25 @@ std::unique_ptr<CanvasResourceProvider> CanvasResourceProvider::Create(
gfx::Size(size), color_params.GetBufferFormat())) {
continue;
}
- DCHECK(gpu::IsImageFormatCompatibleWithGpuMemoryBufferFormat(
- color_params.GLUnsizedInternalFormat(),
- color_params.GetBufferFormat()));
- provider =
- std::make_unique<CanvasResourceProviderTextureGpuMemoryBuffer>(
- size, msaa_sample_count, color_params, context_provider_wrapper,
- resource_dispatcher, is_origin_top_left);
+ DCHECK_EQ(color_params.GLUnsizedInternalFormat(),
+ gpu::InternalFormatForGpuMemoryBufferFormat(
+ color_params.GetBufferFormat()));
+ if (resource_type_fallback_list[i] ==
+ kDirectGpuMemoryBufferResourceType) {
+ provider =
+ std::make_unique<CanvasResourceProviderDirectGpuMemoryBuffer>(
+ size, msaa_sample_count, color_params,
+ context_provider_wrapper, resource_dispatcher,
+ is_origin_top_left);
+ } else {
+ provider =
+ std::make_unique<CanvasResourceProviderTextureGpuMemoryBuffer>(
+ size, msaa_sample_count, color_params,
+ context_provider_wrapper, resource_dispatcher,
+ is_origin_top_left);
+ }
break;
- case kRamGpuMemoryBufferResourceType:
+ case kBitmapGpuMemoryBufferResourceType:
if (!SharedGpuContext::IsGpuCompositingEnabled())
continue;
if (presentation_mode != kAllowImageChromiumPresentationMode)
@@ -477,8 +574,10 @@ std::unique_ptr<CanvasResourceProvider> CanvasResourceProvider::Create(
gfx::Size(size), color_params.GetBufferFormat())) {
continue;
}
- provider = std::make_unique<CanvasResourceProviderRamGpuMemoryBuffer>(
- size, color_params, context_provider_wrapper, resource_dispatcher);
+ provider =
+ std::make_unique<CanvasResourceProviderBitmapGpuMemoryBuffer>(
+ size, color_params, context_provider_wrapper,
+ resource_dispatcher);
break;
case kSharedBitmapResourceType:
if (!resource_dispatcher)
@@ -498,33 +597,62 @@ std::unique_ptr<CanvasResourceProvider> CanvasResourceProvider::Create(
size, color_params, context_provider_wrapper, resource_dispatcher);
break;
}
- if (provider && provider->IsValid())
- return provider;
+ if (!provider->IsValid())
+ continue;
+ base::UmaHistogramBoolean("Blink.Canvas.ResourceProviderIsAccelerated",
+ provider->IsAccelerated());
+ return provider;
}
return nullptr;
}
+class CanvasResourceProvider::CanvasImageProvider : public cc::ImageProvider {
+ public:
+ CanvasImageProvider(cc::ImageDecodeCache* cache_n32,
+ cc::ImageDecodeCache* cache_f16,
+ SkColorType target_color_type,
+ bool is_hardware_decode_cache);
+ ~CanvasImageProvider() override = default;
+
+ // cc::ImageProvider implementation.
+ ScopedDecodedDrawImage GetDecodedDrawImage(const cc::DrawImage&) override;
+
+ void ReleaseLockedImages() { locked_images_.clear(); }
+
+ private:
+ void CanUnlockImage(ScopedDecodedDrawImage);
+ void CleanupLockedImages();
+
+ bool is_hardware_decode_cache_;
+ bool cleanup_task_pending_ = false;
+ std::vector<ScopedDecodedDrawImage> locked_images_;
+ cc::PlaybackImageProvider playback_image_provider_n32_;
+ base::Optional<cc::PlaybackImageProvider> playback_image_provider_f16_;
+
+ base::WeakPtrFactory<CanvasImageProvider> weak_factory_;
+
+ DISALLOW_COPY_AND_ASSIGN(CanvasImageProvider);
+};
+
CanvasResourceProvider::CanvasImageProvider::CanvasImageProvider(
cc::ImageDecodeCache* cache_n32,
cc::ImageDecodeCache* cache_f16,
- const gfx::ColorSpace& target_color_space,
- SkColorType canvas_color_type)
- : playback_image_provider_n32_(cache_n32,
- target_color_space,
+ SkColorType canvas_color_type,
+ bool is_hardware_decode_cache)
+ : is_hardware_decode_cache_(is_hardware_decode_cache),
+ playback_image_provider_n32_(cache_n32,
cc::PlaybackImageProvider::Settings()),
weak_factory_(this) {
// If the image provider may require to decode to half float instead of
// uint8, create a f16 PlaybackImageProvider with the passed cache.
if (canvas_color_type == kRGBA_F16_SkColorType) {
DCHECK(cache_f16);
- playback_image_provider_f16_.emplace(cache_f16, target_color_space,
+ playback_image_provider_f16_.emplace(cache_f16,
cc::PlaybackImageProvider::Settings());
}
}
-CanvasResourceProvider::CanvasImageProvider::~CanvasImageProvider() = default;
-
cc::ImageProvider::ScopedDecodedDrawImage
CanvasResourceProvider::CanvasImageProvider::GetDecodedDrawImage(
const cc::DrawImage& draw_image) {
@@ -540,7 +668,17 @@ CanvasResourceProvider::CanvasImageProvider::GetDecodedDrawImage(
scoped_decoded_image =
playback_image_provider_n32_.GetDecodedDrawImage(draw_image);
}
- if (!scoped_decoded_image.needs_unlock())
+
+ // Holding onto locked images here is a performance optimization for the
+ // gpu image decode cache. For that cache, it is expensive to lock and
+ // unlock gpu discardable, and so it is worth it to hold the lock on
+ // these images across multiple potential decodes. In the software case,
+ // locking in this manner makes it easy to run out of discardable memory
+ // (backed by shared memory sometimes) because each per-colorspace image
+ // decode cache has its own limit. In the software case, just unlock
+ // immediately and let the discardable system manage the cache logic
+ // behind the scenes.
+ if (!scoped_decoded_image.needs_unlock() || !is_hardware_decode_cache_)
return scoped_decoded_image;
constexpr int kMaxLockedImagesCount = 500;
@@ -550,24 +688,24 @@ CanvasResourceProvider::CanvasImageProvider::GetDecodedDrawImage(
ReleaseLockedImages();
}
- // It is safe to use base::Unretained, since decodes acquired from a provider
- // must not exceed the provider's lifetime.
auto decoded_draw_image = scoped_decoded_image.decoded_image();
return ScopedDecodedDrawImage(
- decoded_draw_image,
- base::BindOnce(&CanvasImageProvider::CanUnlockImage,
- base::Unretained(this), std::move(scoped_decoded_image)));
-}
-
-void CanvasResourceProvider::CanvasImageProvider::ReleaseLockedImages() {
- locked_images_.clear();
+ decoded_draw_image, base::BindOnce(&CanvasImageProvider::CanUnlockImage,
+ weak_factory_.GetWeakPtr(),
+ std::move(scoped_decoded_image)));
}
void CanvasResourceProvider::CanvasImageProvider::CanUnlockImage(
ScopedDecodedDrawImage image) {
+ // We should early out and avoid calling this function for software decodes.
+ DCHECK(is_hardware_decode_cache_);
+
+ // Because these image decodes are being done in javascript calling into
+ // canvas code, there's no obvious time to do the cleanup. To handle this,
+ // post a cleanup task to run after javascript is done running.
if (!cleanup_task_pending_) {
cleanup_task_pending_ = true;
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
+ Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&CanvasImageProvider::CleanupLockedImages,
weak_factory_.GetWeakPtr()));
}
@@ -612,20 +750,14 @@ cc::PaintCanvas* CanvasResourceProvider::Canvas() {
DCHECK(!canvas_image_provider_);
- gfx::ColorSpace target_color_space =
- ColorParams().NeedsSkColorSpaceXformCanvas()
- ? ColorParams().GetStorageGfxColorSpace()
- : gfx::ColorSpace::CreateSRGB();
-
// Create an ImageDecodeCache for half float images only if the canvas is
// using half float back storage.
cc::ImageDecodeCache* cache_f16 = nullptr;
- if (ColorParams().GetSkColorType() == kRGBA_F16_SkColorType)
+ if (ColorParams().PixelFormat() == kF16CanvasPixelFormat)
cache_f16 = ImageDecodeCacheF16();
- canvas_image_provider_.emplace(ImageDecodeCache(), cache_f16,
- target_color_space,
- color_params_.GetSkColorType());
- cc::ImageProvider* image_provider = &*canvas_image_provider_;
+ canvas_image_provider_ = std::make_unique<CanvasImageProvider>(
+ ImageDecodeCacheRGBA8(), cache_f16, color_params_.GetSkColorType(),
+ use_hardware_decode_cache());
cc::SkiaPaintCanvas::ContextFlushes context_flushes;
if (IsAccelerated() &&
@@ -634,17 +766,18 @@ cc::PaintCanvas* CanvasResourceProvider::Canvas() {
->GetGpuFeatureInfo()
.IsWorkaroundEnabled(gpu::DISABLE_2D_CANVAS_AUTO_FLUSH)) {
context_flushes.enable =
- CanvasHeuristicParameters::kEnableGrContextFlushes;
+ canvas_heuristic_parameters::kEnableGrContextFlushes;
context_flushes.max_draws_before_flush =
- CanvasHeuristicParameters::kMaxDrawsBeforeContextFlush;
+ canvas_heuristic_parameters::kMaxDrawsBeforeContextFlush;
}
if (ColorParams().NeedsSkColorSpaceXformCanvas()) {
canvas_ = std::make_unique<cc::SkiaPaintCanvas>(
GetSkSurface()->getCanvas(), ColorParams().GetSkColorSpace(),
- image_provider, context_flushes);
+ canvas_image_provider_.get(), context_flushes);
} else {
canvas_ = std::make_unique<cc::SkiaPaintCanvas>(
- GetSkSurface()->getCanvas(), image_provider, context_flushes);
+ GetSkSurface()->getCanvas(), canvas_image_provider_.get(),
+ context_flushes);
}
}
@@ -742,14 +875,6 @@ void CanvasResourceProvider::Clear() {
Canvas()->clear(SK_ColorTRANSPARENT);
}
-void CanvasResourceProvider::InvalidateSurface() {
- canvas_ = nullptr;
- canvas_image_provider_.reset();
- xform_canvas_ = nullptr;
- surface_ = nullptr;
- single_buffer_ = nullptr;
-}
-
uint32_t CanvasResourceProvider::ContentUniqueID() const {
return GetSkSurface()->generationID();
}
@@ -760,20 +885,33 @@ scoped_refptr<CanvasResource> CanvasResourceProvider::CreateResource() {
return nullptr;
}
-cc::ImageDecodeCache* CanvasResourceProvider::ImageDecodeCache() {
- if (IsAccelerated() && context_provider_wrapper_) {
+cc::ImageDecodeCache* CanvasResourceProvider::ImageDecodeCacheRGBA8() {
+ auto color_space = ColorParams().ColorSpace();
+ if (!ColorParams().NeedsSkColorSpaceXformCanvas()) {
+ color_space = kSRGBCanvasColorSpace;
+ }
+
+ if (use_hardware_decode_cache()) {
return context_provider_wrapper_->ContextProvider()->ImageDecodeCache(
- kN32_SkColorType);
+ kN32_SkColorType,
+ blink::CanvasColorParams::CanvasColorSpaceToSkColorSpace(color_space));
}
- return &Image::SharedCCDecodeCache(kN32_SkColorType);
+
+ return Image::SharedCCDecodeCache(color_space, kRGBA8CanvasPixelFormat);
}
cc::ImageDecodeCache* CanvasResourceProvider::ImageDecodeCacheF16() {
- if (IsAccelerated() && context_provider_wrapper_) {
+ auto color_space = ColorParams().ColorSpace();
+ if (!ColorParams().NeedsSkColorSpaceXformCanvas()) {
+ color_space = kSRGBCanvasColorSpace;
+ }
+
+ if (use_hardware_decode_cache()) {
return context_provider_wrapper_->ContextProvider()->ImageDecodeCache(
- kRGBA_F16_SkColorType);
+ kRGBA_F16_SkColorType,
+ blink::CanvasColorParams::CanvasColorSpaceToSkColorSpace(color_space));
}
- return &Image::SharedCCDecodeCache(kRGBA_F16_SkColorType);
+ return Image::SharedCCDecodeCache(color_space, kF16CanvasPixelFormat);
}
void CanvasResourceProvider::RecycleResource(
@@ -781,7 +919,7 @@ void CanvasResourceProvider::RecycleResource(
// Need to check HasOneRef() because if there are outstanding references to
// the resource, it cannot be safely recycled.
if (resource->HasOneRef() && resource_recycling_enabled_)
- recycled_resources_.push_back(std::move(resource));
+ canvas_resources_.push_back(std::move(resource));
}
void CanvasResourceProvider::SetResourceRecyclingEnabled(bool value) {
@@ -791,29 +929,27 @@ void CanvasResourceProvider::SetResourceRecyclingEnabled(bool value) {
}
void CanvasResourceProvider::ClearRecycledResources() {
- recycled_resources_.clear();
+ canvas_resources_.clear();
}
scoped_refptr<CanvasResource> CanvasResourceProvider::NewOrRecycledResource() {
+ if (canvas_resources_.IsEmpty())
+ canvas_resources_.push_back(CreateResource());
+
if (IsSingleBuffered()) {
- if (!single_buffer_)
- single_buffer_ = CreateResource();
- return single_buffer_;
- }
- if (recycled_resources_.size()) {
- scoped_refptr<CanvasResource> resource =
- std::move(recycled_resources_.back());
- recycled_resources_.pop_back();
- return resource;
+ DCHECK_EQ(canvas_resources_.size(), 1u);
+ return canvas_resources_.back();
}
- return CreateResource();
+
+ scoped_refptr<CanvasResource> resource = std::move(canvas_resources_.back());
+ canvas_resources_.pop_back();
+ return resource;
}
void CanvasResourceProvider::TryEnableSingleBuffering() {
if (IsSingleBuffered() || !SupportsSingleBuffering())
return;
SetResourceRecyclingEnabled(false);
- is_single_buffered_ = true;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
index 8ac91ea8186..3a06967df39 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
@@ -5,20 +5,9 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CANVAS_RESOURCE_PROVIDER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_CANVAS_RESOURCE_PROVIDER_H_
-#include "base/macros.h"
-#include "base/memory/scoped_refptr.h"
-#include "base/memory/weak_ptr.h"
-#include "base/optional.h"
#include "cc/paint/skia_paint_canvas.h"
#include "cc/raster/playback_image_provider.h"
-#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom-blink.h"
-#include "third_party/blink/renderer/platform/geometry/int_size.h"
-#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource.h"
-#include "third_party/blink/renderer/platform/graphics/web_graphics_context_3d_provider_wrapper.h"
-#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
-#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/skia/include/core/SkSurface.h"
class GrContext;
@@ -66,6 +55,7 @@ class PLATFORM_EXPORT CanvasResourceProvider
kSoftwareCompositedResourceUsage,
kAcceleratedResourceUsage,
kAcceleratedCompositedResourceUsage,
+ kAcceleratedDirectResourceUsage,
};
enum PresentationMode {
@@ -73,6 +63,19 @@ class PLATFORM_EXPORT CanvasResourceProvider
kAllowImageChromiumPresentationMode // Use CHROMIUM_image gl extension
};
+ // These values are persisted to logs. Entries should not be renumbered and
+ // numeric values should never be reused.
+ enum ResourceProviderType {
+ kTexture = 0,
+ kBitmap = 1,
+ kSharedBitmap = 2,
+ kTextureGpuMemoryBuffer = 3,
+ kBitmapGpuMemoryBuffer = 4,
+ kMaxValue = kBitmapGpuMemoryBuffer,
+ };
+
+ void static RecordTypeToUMA(ResourceProviderType type);
+
static std::unique_ptr<CanvasResourceProvider> Create(
const IntSize&,
ResourceUsage,
@@ -83,9 +86,9 @@ class PLATFORM_EXPORT CanvasResourceProvider
base::WeakPtr<CanvasResourceDispatcher>,
bool is_origin_top_left = true);
- // Use this method for capturing a frame that is intended to be displayed via
- // the compositor. Cases that need to acquire a snaptshot that is not destined
- // to be transfered via TransferableResource should call Snapshot() instead.
+ // Use Snapshot() for capturing a frame that is intended to be displayed via
+ // the compositor. Cases that are destined to be transferred via a
+ // TransferableResource should call ProduceFrame() instead.
virtual scoped_refptr<CanvasResource> ProduceFrame() = 0;
scoped_refptr<StaticBitmapImage> Snapshot();
@@ -110,11 +113,10 @@ class PLATFORM_EXPORT CanvasResourceProvider
// Indicates that the compositing path is single buffered, meaning that
// ProduceFrame() return a reference to the same resource each time, which
// implies that Producing an animation frame may overwrite the resource used
- // by the previous frame. This results in graphics updates skipping the
- // queue, thus reducing latency, but with the possible side effects of
- // tearring (in cases where the resource is scanned out directly) and
- // irregular frame rate.
- bool IsSingleBuffered() { return is_single_buffered_; }
+ // by the previous frame. This results in graphics updates skipping the queue,
+ // thus reducing latency, but with the possible side effects of tearing (in
+ // cases where the resource is scanned out directly) and irregular frame rate.
+ bool IsSingleBuffered() { return !resource_recycling_enabled_; }
// Attempt to enable single buffering mode on this resource provider. May
// fail if the CanvasResourcePRovider subclass does not support this mode of
@@ -155,10 +157,6 @@ class PLATFORM_EXPORT CanvasResourceProvider
return weak_ptr_factory_.GetWeakPtr();
}
- // Called by subclasses when the backing resource has changed and resources
- // are not managed by skia, signaling that a new surface needs to be created.
- void InvalidateSurface();
-
CanvasResourceProvider(const IntSize&,
const CanvasColorParams&,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>,
@@ -172,41 +170,21 @@ class PLATFORM_EXPORT CanvasResourceProvider
cc::PaintImage MakeImageSnapshot();
private:
- class CanvasImageProvider : public cc::ImageProvider {
- public:
- CanvasImageProvider(cc::ImageDecodeCache* cache_n32,
- cc::ImageDecodeCache* cache_f16,
- const gfx::ColorSpace& target_color_space,
- SkColorType target_color_type);
- ~CanvasImageProvider() override;
-
- // cc::ImageProvider implementation.
- ScopedDecodedDrawImage GetDecodedDrawImage(const cc::DrawImage&) override;
-
- void ReleaseLockedImages();
-
- private:
- void CanUnlockImage(ScopedDecodedDrawImage);
- void CleanupLockedImages();
-
- bool cleanup_task_pending_ = false;
- std::vector<ScopedDecodedDrawImage> locked_images_;
- cc::PlaybackImageProvider playback_image_provider_n32_;
- base::Optional<cc::PlaybackImageProvider> playback_image_provider_f16_;
-
- base::WeakPtrFactory<CanvasImageProvider> weak_factory_;
- };
+ class CanvasImageProvider;
virtual sk_sp<SkSurface> CreateSkSurface() const = 0;
virtual scoped_refptr<CanvasResource> CreateResource();
- cc::ImageDecodeCache* ImageDecodeCache();
+ bool use_hardware_decode_cache() const {
+ return IsAccelerated() && context_provider_wrapper_;
+ }
+ cc::ImageDecodeCache* ImageDecodeCacheRGBA8();
cc::ImageDecodeCache* ImageDecodeCacheF16();
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_;
base::WeakPtr<CanvasResourceDispatcher> resource_dispatcher_;
IntSize size_;
CanvasColorParams color_params_;
- base::Optional<CanvasImageProvider> canvas_image_provider_;
+ std::unique_ptr<CanvasImageProvider> canvas_image_provider_;
std::unique_ptr<cc::SkiaPaintCanvas> canvas_;
mutable sk_sp<SkSurface> surface_; // mutable for lazy init
std::unique_ptr<SkCanvas> xform_canvas_;
@@ -217,12 +195,11 @@ class PLATFORM_EXPORT CanvasResourceProvider
cc::PaintImage::kInvalidContentId;
uint32_t snapshot_sk_image_id_ = 0u;
- WTF::Vector<scoped_refptr<CanvasResource>> recycled_resources_;
+ // When and if |resource_recycling_enabled_| is false, |canvas_resources_|
+ // will only hold one CanvasResource at most.
+ WTF::Vector<scoped_refptr<CanvasResource>> canvas_resources_;
bool resource_recycling_enabled_ = true;
- bool is_single_buffered_ = false;
- scoped_refptr<CanvasResource> single_buffer_;
-
base::WeakPtrFactory<CanvasResourceProvider> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(CanvasResourceProvider);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc
new file mode 100644
index 00000000000..90bf30b64a4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc
@@ -0,0 +1,248 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
+
+#include "components/viz/test/test_gpu_memory_buffer_manager.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
+#include "third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h"
+#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
+#include "third_party/blink/renderer/platform/graphics/test/fake_gles2_interface.h"
+#include "third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h"
+#include "third_party/blink/renderer/platform/graphics/test/gpu_memory_buffer_test_platform.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
+
+using testing::_;
+using testing::InSequence;
+using testing::Return;
+using testing::Test;
+
+namespace blink {
+
+namespace {
+
+class FakeGLES2InterfaceWithImageSupport : public FakeGLES2Interface {
+ public:
+ GLuint CreateImageCHROMIUM(ClientBuffer, GLsizei, GLsizei, GLenum) final {
+ return image_id_++;
+ }
+ void DestroyImageCHROMIUM(GLuint image_id) final {
+ EXPECT_LE(image_id, image_id_);
+ }
+
+ private:
+ GLuint image_id_ = 3;
+};
+
+class MockCanvasResourceDispatcherClient
+ : public CanvasResourceDispatcherClient {
+ public:
+ MockCanvasResourceDispatcherClient() = default;
+
+ MOCK_METHOD0(BeginFrame, void());
+};
+
+} // anonymous namespace
+
+class CanvasResourceProviderTest : public Test {
+ public:
+ void SetUp() override {
+ // Install our mock GL context so that it gets served by SharedGpuContext.
+ auto factory = [](FakeGLES2Interface* gl, bool* gpu_compositing_disabled)
+ -> std::unique_ptr<WebGraphicsContext3DProvider> {
+ *gpu_compositing_disabled = false;
+ // Unretained is safe since TearDown() cleans up the SharedGpuContext.
+ return std::make_unique<FakeWebGraphicsContext3DProvider>(gl);
+ };
+ SharedGpuContext::SetContextProviderFactoryForTesting(
+ WTF::BindRepeating(factory, WTF::Unretained(&gl_)));
+ context_provider_wrapper_ = SharedGpuContext::ContextProviderWrapper();
+ }
+
+ void TearDown() override { SharedGpuContext::ResetForTesting(); }
+
+ // Adds |buffer_format| to the context capabilities if it's not supported.
+ void EnsureBufferFormatIsSupported(gfx::BufferFormat buffer_format) {
+ auto* context_provider = context_provider_wrapper_->ContextProvider();
+ if (context_provider->GetCapabilities().gpu_memory_buffer_formats.Has(
+ buffer_format)) {
+ return;
+ }
+
+ auto capabilities = context_provider->GetCapabilities();
+ capabilities.gpu_memory_buffer_formats.Add(buffer_format);
+
+ static_cast<FakeWebGraphicsContext3DProvider*>(context_provider)
+ ->SetCapabilities(capabilities);
+ }
+
+ protected:
+ FakeGLES2InterfaceWithImageSupport gl_;
+ base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform_;
+};
+
+TEST_F(CanvasResourceProviderTest,
+ CanvasResourceProviderTextureGpuMemoryBuffer) {
+ const IntSize kSize(10, 10);
+ const CanvasColorParams kColorParams(kSRGBCanvasColorSpace,
+ kRGBA8CanvasPixelFormat, kNonOpaque);
+ EnsureBufferFormatIsSupported(kColorParams.GetBufferFormat());
+
+ auto provider = CanvasResourceProvider::Create(
+ kSize, CanvasResourceProvider::kAcceleratedCompositedResourceUsage,
+ context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams,
+ CanvasResourceProvider::kAllowImageChromiumPresentationMode,
+ nullptr /* resource_dispatcher */, true /* is_origin_top_left */);
+
+ EXPECT_EQ(provider->Size(), kSize);
+ EXPECT_TRUE(provider->IsValid());
+ EXPECT_TRUE(provider->IsAccelerated());
+ EXPECT_TRUE(provider->SupportsDirectCompositing());
+ EXPECT_TRUE(provider->SupportsSingleBuffering());
+ EXPECT_EQ(provider->ColorParams().ColorSpace(), kColorParams.ColorSpace());
+ EXPECT_EQ(provider->ColorParams().PixelFormat(), kColorParams.PixelFormat());
+ EXPECT_EQ(provider->ColorParams().GetOpacityMode(),
+ kColorParams.GetOpacityMode());
+
+ EXPECT_FALSE(provider->IsSingleBuffered());
+ provider->TryEnableSingleBuffering();
+ EXPECT_TRUE(provider->IsSingleBuffered());
+}
+
+TEST_F(CanvasResourceProviderTest, CanvasResourceProviderTexture) {
+ const IntSize kSize(10, 10);
+ const CanvasColorParams kColorParams(kSRGBCanvasColorSpace,
+ kRGBA8CanvasPixelFormat, kNonOpaque);
+
+ auto provider = CanvasResourceProvider::Create(
+ kSize, CanvasResourceProvider::kAcceleratedResourceUsage,
+ context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams,
+ CanvasResourceProvider::kAllowImageChromiumPresentationMode,
+ nullptr /* resource_dispatcher */, true /* is_origin_top_left */);
+
+ EXPECT_EQ(provider->Size(), kSize);
+ EXPECT_TRUE(provider->IsValid());
+ EXPECT_TRUE(provider->IsAccelerated());
+ EXPECT_TRUE(provider->SupportsDirectCompositing());
+ EXPECT_FALSE(provider->SupportsSingleBuffering());
+ EXPECT_EQ(provider->ColorParams().ColorSpace(), kColorParams.ColorSpace());
+ EXPECT_EQ(provider->ColorParams().PixelFormat(), kColorParams.PixelFormat());
+ EXPECT_EQ(provider->ColorParams().GetOpacityMode(),
+ kColorParams.GetOpacityMode());
+
+ EXPECT_FALSE(provider->IsSingleBuffered());
+}
+
+TEST_F(CanvasResourceProviderTest,
+ CanvasResourceProviderBitmapGpuMemoryBuffer) {
+ const IntSize kSize(10, 10);
+ const CanvasColorParams kColorParams(kSRGBCanvasColorSpace,
+ kRGBA8CanvasPixelFormat, kNonOpaque);
+
+ auto provider = CanvasResourceProvider::Create(
+ kSize, CanvasResourceProvider::kSoftwareCompositedResourceUsage,
+ context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams,
+ CanvasResourceProvider::kAllowImageChromiumPresentationMode,
+ nullptr /* resource_dispatcher */, true /* is_origin_top_left */);
+
+ EXPECT_EQ(provider->Size(), kSize);
+ EXPECT_TRUE(provider->IsValid());
+ EXPECT_FALSE(provider->IsAccelerated());
+ EXPECT_TRUE(provider->SupportsDirectCompositing());
+ EXPECT_TRUE(provider->SupportsSingleBuffering());
+ EXPECT_EQ(provider->ColorParams().ColorSpace(), kColorParams.ColorSpace());
+ EXPECT_EQ(provider->ColorParams().PixelFormat(), kColorParams.PixelFormat());
+ EXPECT_EQ(provider->ColorParams().GetOpacityMode(),
+ kColorParams.GetOpacityMode());
+
+ EXPECT_FALSE(provider->IsSingleBuffered());
+}
+
+TEST_F(CanvasResourceProviderTest, CanvasResourceProviderBitmap) {
+ const IntSize kSize(10, 10);
+ const CanvasColorParams kColorParams(kSRGBCanvasColorSpace,
+ kRGBA8CanvasPixelFormat, kNonOpaque);
+
+ auto provider = CanvasResourceProvider::Create(
+ kSize, CanvasResourceProvider::kSoftwareResourceUsage,
+ context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams,
+ CanvasResourceProvider::kAllowImageChromiumPresentationMode,
+ nullptr /* resource_dispatcher */, true /* is_origin_top_left */);
+
+ EXPECT_EQ(provider->Size(), kSize);
+ EXPECT_TRUE(provider->IsValid());
+ EXPECT_FALSE(provider->IsAccelerated());
+ EXPECT_FALSE(provider->SupportsDirectCompositing());
+ EXPECT_FALSE(provider->SupportsSingleBuffering());
+ EXPECT_EQ(provider->ColorParams().ColorSpace(), kColorParams.ColorSpace());
+ EXPECT_EQ(provider->ColorParams().PixelFormat(), kColorParams.PixelFormat());
+ EXPECT_EQ(provider->ColorParams().GetOpacityMode(),
+ kColorParams.GetOpacityMode());
+
+ EXPECT_FALSE(provider->IsSingleBuffered());
+}
+
+TEST_F(CanvasResourceProviderTest, CanvasResourceProviderSharedBitmap) {
+ const IntSize kSize(10, 10);
+ const CanvasColorParams kColorParams(kSRGBCanvasColorSpace,
+ kRGBA8CanvasPixelFormat, kNonOpaque);
+
+ MockCanvasResourceDispatcherClient client;
+ CanvasResourceDispatcher resource_dispatcher(
+ &client, 1 /* client_id */, 1 /* sink_id */,
+ 1 /* placeholder_canvas_id */, kSize);
+
+ auto provider = CanvasResourceProvider::Create(
+ kSize, CanvasResourceProvider::kSoftwareCompositedResourceUsage,
+ context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams,
+ CanvasResourceProvider::kDefaultPresentationMode,
+ resource_dispatcher.GetWeakPtr(), true /* is_origin_top_left */);
+
+ EXPECT_EQ(provider->Size(), kSize);
+ EXPECT_TRUE(provider->IsValid());
+ EXPECT_FALSE(provider->IsAccelerated());
+ EXPECT_TRUE(provider->SupportsDirectCompositing());
+ EXPECT_TRUE(provider->SupportsSingleBuffering());
+ EXPECT_EQ(provider->ColorParams().ColorSpace(), kColorParams.ColorSpace());
+ EXPECT_EQ(provider->ColorParams().PixelFormat(), kColorParams.PixelFormat());
+ EXPECT_EQ(provider->ColorParams().GetOpacityMode(),
+ kColorParams.GetOpacityMode());
+
+ EXPECT_FALSE(provider->IsSingleBuffered());
+ provider->TryEnableSingleBuffering();
+ EXPECT_TRUE(provider->IsSingleBuffered());
+}
+
+TEST_F(CanvasResourceProviderTest,
+ CanvasResourceProviderDirectGpuMemoryBuffer) {
+ const IntSize kSize(10, 10);
+ const CanvasColorParams kColorParams(kSRGBCanvasColorSpace,
+ kRGBA8CanvasPixelFormat, kNonOpaque);
+ EnsureBufferFormatIsSupported(kColorParams.GetBufferFormat());
+
+ auto provider = CanvasResourceProvider::Create(
+ kSize, CanvasResourceProvider::kAcceleratedDirectResourceUsage,
+ context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams,
+ CanvasResourceProvider::kAllowImageChromiumPresentationMode,
+ nullptr /* resource_dispatcher */, true /* is_origin_top_left */);
+
+ EXPECT_EQ(provider->Size(), kSize);
+ EXPECT_TRUE(provider->IsValid());
+ EXPECT_TRUE(provider->IsAccelerated());
+ EXPECT_TRUE(provider->SupportsDirectCompositing());
+ EXPECT_TRUE(provider->SupportsSingleBuffering());
+ EXPECT_EQ(provider->ColorParams().ColorSpace(), kColorParams.ColorSpace());
+ EXPECT_EQ(provider->ColorParams().PixelFormat(), kColorParams.PixelFormat());
+ EXPECT_EQ(provider->ColorParams().GetOpacityMode(),
+ kColorParams.GetOpacityMode());
+
+ EXPECT_FALSE(provider->IsSingleBuffered());
+ provider->TryEnableSingleBuffering();
+ EXPECT_TRUE(provider->IsSingleBuffered());
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_test.cc b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_test.cc
index f27b5bf8901..3dc0a13fc4a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/canvas_resource_test.cc
@@ -16,7 +16,7 @@
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/test/fake_gles2_interface.h"
#include "third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
+#include "third_party/blink/renderer/platform/graphics/test/gpu_memory_buffer_test_platform.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/skia/include/core/SkSurface.h"
@@ -39,20 +39,6 @@ class MockGLES2InterfaceWithMailboxSupport : public FakeGLES2Interface {
MOCK_METHOD2(BindTexture, void(GLenum, GLuint));
};
-class FakeCanvasResourcePlatformSupport : public TestingPlatformSupport {
- public:
- void RunUntilStop() const { base::RunLoop().Run(); }
-
- void StopRunning() const { base::RunLoop().Quit(); }
-
- private:
- gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override {
- return &test_gpu_memory_buffer_manager_;
- }
-
- viz::TestGpuMemoryBufferManager test_gpu_memory_buffer_manager_;
-};
-
class CanvasResourceTest : public Test {
public:
void SetUp() override {
@@ -134,7 +120,7 @@ TEST_F(CanvasResourceTest, SkiaResourceNoMailboxLeak) {
TEST_F(CanvasResourceTest, GpuMemoryBufferSyncTokenRefresh) {
testing::InSequence s;
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
constexpr GLuint image_id = 1;
const GLuint texture_target = gpu::GetPlatformSpecificTextureTarget();
@@ -204,7 +190,7 @@ TEST_F(CanvasResourceTest, GpuMemoryBufferSyncTokenRefresh) {
}
TEST_F(CanvasResourceTest, MakeAcceleratedFromAcceleratedResourceIsNoOp) {
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
SkImageInfo image_info =
SkImageInfo::MakeN32(10, 10, kPremul_SkAlphaType, nullptr);
@@ -232,7 +218,7 @@ TEST_F(CanvasResourceTest, MakeAcceleratedFromAcceleratedResourceIsNoOp) {
}
TEST_F(CanvasResourceTest, MakeAcceleratedFromRasterResource) {
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
SkImageInfo image_info =
SkImageInfo::MakeN32(10, 10, kPremul_SkAlphaType, nullptr);
@@ -258,7 +244,7 @@ TEST_F(CanvasResourceTest, MakeAcceleratedFromRasterResource) {
}
TEST_F(CanvasResourceTest, MakeUnacceleratedFromUnacceleratedResourceIsNoOp) {
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
SkImageInfo image_info =
SkImageInfo::MakeN32(10, 10, kPremul_SkAlphaType, nullptr);
@@ -277,7 +263,7 @@ TEST_F(CanvasResourceTest, MakeUnacceleratedFromUnacceleratedResourceIsNoOp) {
}
TEST_F(CanvasResourceTest, MakeUnacceleratedFromAcceleratedResource) {
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
SkImageInfo image_info =
SkImageInfo::MakeN32(10, 10, kPremul_SkAlphaType, nullptr);
@@ -315,7 +301,7 @@ void PaintToCanvasResource(CanvasResource* canvas_resource) {
TEST_F(CanvasResourceTest, RamGpuMemoryBuffer_ResourcePreparation) {
testing::InSequence s;
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
EXPECT_TRUE(!!context_provider_wrapper_);
constexpr GLuint image_id = 1;
@@ -355,7 +341,7 @@ TEST_F(CanvasResourceTest, RamGpuMemoryBuffer_ResourcePreparation) {
TEST_F(CanvasResourceTest, GpuMemoryBuffer_accelerated_8bit) {
testing::InSequence s;
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
EXPECT_TRUE(!!context_provider_wrapper_);
constexpr GLuint image_id = 1;
@@ -381,7 +367,7 @@ TEST_F(CanvasResourceTest, GpuMemoryBuffer_accelerated_8bit) {
TEST_F(CanvasResourceTest, GpuMemoryBuffer_accelerated_float16) {
testing::InSequence s;
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
EXPECT_TRUE(!!context_provider_wrapper_);
constexpr GLuint image_id = 1;
@@ -409,7 +395,7 @@ TEST_F(CanvasResourceTest, GpuMemoryBuffer_accelerated_float16) {
TEST_F(CanvasResourceTest, PrepareTransferableResource_SharedBitmap) {
testing::InSequence s;
- ScopedTestingPlatformSupport<FakeCanvasResourcePlatformSupport> platform;
+ ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform> platform;
scoped_refptr<CanvasResource> canvas_resource =
CanvasResourceSharedBitmap::Create(IntSize(10, 10), CanvasColorParams(),
nullptr, // CanvasResourceProvider
diff --git a/chromium/third_party/blink/renderer/platform/graphics/color.cc b/chromium/third_party/blink/renderer/platform/graphics/color.cc
index fdf5deae86b..b2e5039f07b 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/color.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/color.cc
@@ -225,40 +225,6 @@ bool Color::SetFromString(const String& name) {
return ParseHexColor(name.Characters16() + 1, name.length() - 1, color_);
}
-String Color::SerializedAsCSSComponentValue() const {
- StringBuilder result;
- result.ReserveCapacity(32);
- bool color_has_alpha = HasAlpha();
- if (color_has_alpha)
- result.Append("rgba(");
- else
- result.Append("rgb(");
-
- result.AppendNumber(static_cast<unsigned char>(Red()));
- result.Append(", ");
-
- result.AppendNumber(static_cast<unsigned char>(Green()));
- result.Append(", ");
-
- result.AppendNumber(static_cast<unsigned char>(Blue()));
- if (color_has_alpha) {
- result.Append(", ");
- // See <alphavalue> section in
- // https://drafts.csswg.org/cssom/#serializing-css-values
- int alphavalue = Alpha();
- float rounded = round(alphavalue * 100 / 255.0f) / 100;
- if (round(rounded * 255) == alphavalue) {
- result.AppendNumber(rounded, 2);
- } else {
- rounded = round(alphavalue * 1000 / 255.0f) / 1000;
- result.AppendNumber(rounded, 3);
- }
- }
-
- result.Append(')');
- return result.ToString();
-}
-
String Color::Serialized() const {
if (!HasAlpha()) {
StringBuilder builder;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/color.h b/chromium/third_party/blink/renderer/platform/graphics/color.h
index ad360f3d340..c682ad44f5a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/color.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/color.h
@@ -97,10 +97,6 @@ class PLATFORM_EXPORT Color {
// http://www.whatwg.org/specs/web-apps/current-work/#serialization-of-a-color
String Serialized() const;
- // Returns the color serialized according to CSSOM:
- // https://drafts.csswg.org/cssom/#serialize-a-css-component-value
- String SerializedAsCSSComponentValue() const;
-
// Returns the color serialized as either #RRGGBB or #RRGGBBAA. The latter
// format is not a valid CSS color, and should only be seen in DRT dumps.
String NameForLayoutTreeAsText() const;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc
index f5af9c611f7..a1b314914fd 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc
@@ -37,7 +37,7 @@ class ChunkToLayerMapperTest : public testing::Test {
e0(), EffectPaintPropertyNode::State{
layer_transform_.get(), layer_clip_.get(),
kColorFilterLuminanceToAlpha, CompositorFilterOperations(),
- 0.789f, SkBlendMode::kSrcIn});
+ 0.789f, CompositorFilterOperations(), SkBlendMode::kSrcIn});
}
return PropertyTreeState(layer_transform_.get(), layer_clip_.get(),
layer_effect_.get());
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/content_layer_client_impl.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing/content_layer_client_impl.cc
index e3429e1aa20..374222bd712 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/content_layer_client_impl.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/content_layer_client_impl.cc
@@ -6,7 +6,7 @@
#include <memory>
#include "base/optional.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/paint_op_buffer.h"
#include "third_party/blink/renderer/platform/geometry/geometry_as_json.h"
@@ -201,9 +201,7 @@ scoped_refptr<cc::PictureLayer> ContentLayerClientImpl::UpdateCcPictureLayer(
json->SetArray("displayItems",
paint_artifact->GetDisplayItemList().SubsequenceAsJSON(
chunk.begin_index, chunk.end_index,
- DisplayItemList::kSkipNonDrawings |
- DisplayItemList::kShownOnlyDisplayItemTypes));
- json->SetString("propertyTreeState", chunk.properties.ToTreeString());
+ DisplayItemList::kShownOnlyDisplayItemTypes));
paint_chunk_debug_data_->PushObject(std::move(json));
}
#endif
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc
index 8a2187658b5..43aeb50ebdd 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc
@@ -31,6 +31,31 @@
namespace blink {
+namespace {
+
+// Inserts the element ids of the given node and all of its ancestors into the
+// given |composited_element_ids| set. Returns once it finds an id which already
+// exists as this implies that all of those ancestor nodes have already been
+// inserted.
+template <typename NodeType>
+void InsertAncestorElementIds(const NodeType* node,
+ CompositorElementIdSet& composited_element_ids) {
+ while (node) {
+ const CompositorElementId& element_id = node->GetCompositorElementId();
+ if (element_id) {
+ if (composited_element_ids.count(element_id)) {
+ // Once we reach a node already counted we can stop traversing the
+ // parent chain.
+ return;
+ }
+ composited_element_ids.insert(element_id);
+ }
+ node = node->Parent() ? node->Parent()->Unalias() : nullptr;
+ }
+}
+
+} // namespace
+
// cc property trees make use of a sequence number to identify when tree
// topology changes. For now we naively increment the sequence number each time
// we update the property trees. We should explore optimizing our management of
@@ -107,13 +132,8 @@ static scoped_refptr<cc::Layer> ForeignLayerForPaintChunk(
const auto& foreign_layer_display_item =
static_cast<const ForeignLayerDisplayItem&>(display_item);
- layer_offset = gfx::Vector2dF(foreign_layer_display_item.Location().X(),
- foreign_layer_display_item.Location().Y());
- scoped_refptr<cc::Layer> layer = foreign_layer_display_item.GetLayer();
- DCHECK(layer->bounds() ==
- static_cast<gfx::Size>(foreign_layer_display_item.Bounds()))
- << "\n layer bounds: " << layer->bounds().ToString()
- << "\n display item bounds: " << foreign_layer_display_item.Bounds();
+ auto* layer = foreign_layer_display_item.GetLayer();
+ layer_offset = layer->offset_to_transform_parent();
return layer;
}
@@ -264,9 +284,49 @@ PaintArtifactCompositor::CompositedLayerForPendingLayer(
return cc_layer;
}
+void PaintArtifactCompositor::UpdateTouchActionRects(
+ cc::Layer* layer,
+ const gfx::Vector2dF& layer_offset,
+ const PropertyTreeState& layer_state,
+ const PaintChunkSubset& paint_chunks) {
+ Vector<HitTestRect> touch_action_rects_in_layer_space;
+ for (const auto& chunk : paint_chunks) {
+ const auto* hit_test_data = chunk.hit_test_data.get();
+ if (!hit_test_data || hit_test_data->touch_action_rects.IsEmpty())
+ continue;
+
+ const auto& chunk_state = chunk.properties.GetPropertyTreeState();
+ for (auto touch_action_rect : hit_test_data->touch_action_rects) {
+ auto rect =
+ FloatClipRect(FloatRect(PixelSnappedIntRect(touch_action_rect.rect)));
+ if (!GeometryMapper::LocalToAncestorVisualRect(chunk_state, layer_state,
+ rect)) {
+ continue;
+ }
+ LayoutRect layout_rect = LayoutRect(rect.Rect());
+ layout_rect.MoveBy(
+ LayoutPoint(FloatPoint(-layer_offset.x(), -layer_offset.y())));
+ touch_action_rects_in_layer_space.emplace_back(
+ HitTestRect(layout_rect, touch_action_rect.whitelisted_touch_action));
+ }
+ }
+ layer->SetTouchActionRegion(
+ HitTestRect::BuildRegion(touch_action_rects_in_layer_space));
+}
+
+bool PaintArtifactCompositor::PropertyTreeStateChanged(
+ const PropertyTreeState& state) const {
+ const PropertyTreeState root = PropertyTreeState::Root();
+ bool changed = false;
+ changed = changed || state.Transform()->Changed(*root.Transform());
+ changed = changed || state.Clip()->Changed(root, state.Transform());
+ changed = changed || state.Effect()->Changed(root, state.Transform());
+ return changed;
+}
+
PaintArtifactCompositor::PendingLayer::PendingLayer(
const PaintChunk& first_paint_chunk,
- size_t chunk_index,
+ wtf_size_t chunk_index,
bool chunk_requires_own_layer)
: bounds(first_paint_chunk.bounds),
rect_known_to_be_opaque(
@@ -468,7 +528,7 @@ void PaintArtifactCompositor::LayerizeGroup(
chunk_it))
return;
- size_t first_layer_in_current_group = pending_layers.size();
+ wtf_size_t first_layer_in_current_group = pending_layers.size();
// The worst case time complexity of the algorithm is O(pqd), where
// p = the number of paint chunks.
// q = average number of trials to find a squash layer or rejected
@@ -517,7 +577,7 @@ void PaintArtifactCompositor::LayerizeGroup(
break;
// Case C: The following chunks belong to a subgroup. Process them by
// a recursion call.
- size_t first_layer_in_subgroup = pending_layers.size();
+ wtf_size_t first_layer_in_subgroup = pending_layers.size();
LayerizeGroup(paint_artifact, pending_layers, *unaliased_subgroup,
chunk_it);
// Now the chunk iterator stepped over the subgroup we just saw.
@@ -548,7 +608,7 @@ void PaintArtifactCompositor::LayerizeGroup(
DCHECK(!new_layer.requires_own_layer);
DCHECK_EQ(&unaliased_group, new_layer.property_tree_state.Effect());
// This iterates pending_layers[first_layer_in_current_group:-1] in reverse.
- for (size_t candidate_index = pending_layers.size() - 1;
+ for (wtf_size_t candidate_index = pending_layers.size() - 1;
candidate_index-- > first_layer_in_current_group;) {
PendingLayer& candidate_layer = pending_layers[candidate_index];
if (candidate_layer.CanMerge(new_layer)) {
@@ -720,13 +780,14 @@ void PaintArtifactCompositor::Update(
Vector<PendingLayer, 0> pending_layers;
CollectPendingLayers(*paint_artifact, pending_layers);
- // The page scale layer would create this below but we need to use the
- // special EnsureCompositorPageScaleTransformNode method since the transform
- // created in a different way so we call it here.
+ cc::LayerTreeHost::ViewportPropertyIds viewport_property_ids;
if (viewport_scale_node) {
- property_tree_manager.EnsureCompositorPageScaleTransformNode(
- viewport_scale_node);
+ viewport_property_ids.page_scale_transform =
+ property_tree_manager.EnsureCompositorPageScaleTransformNode(
+ viewport_scale_node);
}
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled())
+ host->RegisterViewportPropertyIds(viewport_property_ids);
Vector<std::unique_ptr<ContentLayerClientImpl>> new_content_layer_clients;
new_content_layer_clients.ReserveCapacity(pending_layers.size());
@@ -747,28 +808,24 @@ void PaintArtifactCompositor::Update(
} else if (const auto* scroll = transform->ScrollNode()) {
// Limit layer bounds to the scroll range to hide the areas that will
// never be scrolled into the visible area.
- pending_layer.bounds.Intersect(
- FloatRect(FloatPoint(), FloatSize(scroll->ContentsSize())));
+ pending_layer.bounds.Intersect(FloatRect(
+ IntRect(scroll->ContainerRect().Location(), scroll->ContentsSize())));
}
gfx::Vector2dF layer_offset;
scoped_refptr<cc::Layer> layer = CompositedLayerForPendingLayer(
paint_artifact, pending_layer, layer_offset, new_content_layer_clients,
new_scroll_hit_test_layers);
- // Get the compositor element id for the layer. Scrollable layers are only
- // associated with scroll element ids which are set in
- // ScrollHitTestLayerForPendingLayer.
- CompositorElementId element_id =
- layer->scrollable()
- ? layer->element_id()
- : property_state.GetCompositorElementId(composited_element_ids);
- // TODO(wkorman): Cease setting element id on layer once
- // animation subsystem no longer requires element id to layer
- // map. http://crbug.com/709137
- // TODO(pdr): Element ids will still need to be set on scroll layers.
- layer->SetElementId(element_id);
- if (element_id)
- composited_element_ids.insert(element_id);
+
+ // Pre-SPV2, touch action rects are updated through
+ // ScrollingCoordinator::UpdateLayerTouchActionRects.
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ auto paint_chunks = paint_artifact->GetPaintChunkSubset(
+ pending_layer.paint_chunk_indices);
+ UpdateTouchActionRects(layer.get(), layer_offset, property_state,
+ paint_chunks);
+ }
+
layer->SetLayerTreeHost(root_layer_->layer_tree_host());
int transform_id =
@@ -793,12 +850,24 @@ void PaintArtifactCompositor::Update(
layer->SetScrollTreeIndex(scroll_id);
layer->SetClipTreeIndex(clip_id);
layer->SetEffectTreeIndex(effect_id);
- bool backface_hidden =
- pending_layer.property_tree_state.Transform()->IsBackfaceHidden();
+ bool backface_hidden = property_state.Transform()->IsBackfaceHidden();
layer->SetDoubleSided(!backface_hidden);
// TODO(wangxianzhu): cc::PropertyTreeBuilder has a more sophisticated
// condition for this. Do we need to do the same here?
layer->SetShouldCheckBackfaceVisibility(backface_hidden);
+
+ InsertAncestorElementIds(property_state.Effect(), composited_element_ids);
+ InsertAncestorElementIds(transform, composited_element_ids);
+ if (layer->scrollable())
+ composited_element_ids.insert(layer->element_id());
+
+ // If the property tree state has changed between the layer and the root, we
+ // need to inform the compositor so damage can be calculated.
+ // Calling |PropertyTreeStateChanged| for every pending layer is
+ // O(|property nodes|^2) and could be optimized by caching the lookup of
+ // nodes known to be changed/unchanged.
+ if (PropertyTreeStateChanged(property_state))
+ layer->SetSubtreePropertyChanged();
}
property_tree_manager.Finalize();
content_layer_clients_.swap(new_content_layer_clients);
@@ -818,6 +887,9 @@ void PaintArtifactCompositor::Update(
root_layer_->SetChildLayerList(layer_list_builder.Finalize());
+ // Update the host's active registered element ids.
+ host->SetActiveRegisteredElementIds(composited_element_ids);
+
// Mark the property trees as having been rebuilt.
host->property_trees()->sequence_number = g_s_property_tree_sequence_number;
host->property_trees()->needs_rebuild = false;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h
index 030294ca48c..1b04c0b9d04 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h
@@ -11,6 +11,7 @@
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
+#include "cc/layers/layer_collections.h"
#include "third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer_client.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
@@ -106,12 +107,24 @@ class PLATFORM_EXPORT PaintArtifactCompositor final
void ShowDebugData();
#endif
+ const Vector<std::unique_ptr<ContentLayerClientImpl>>&
+ ContentLayerClientsForTesting() const {
+ return content_layer_clients_;
+ }
+
+ // Update the cc::Layer's touch action region from the touch action rects of
+ // the paint chunks.
+ static void UpdateTouchActionRects(cc::Layer*,
+ const gfx::Vector2dF& layer_offset,
+ const PropertyTreeState& layer_state,
+ const PaintChunkSubset& paint_chunks);
+
private:
// A pending layer is a collection of paint chunks that will end up in
// the same cc::Layer.
struct PLATFORM_EXPORT PendingLayer {
PendingLayer(const PaintChunk& first_paint_chunk,
- size_t first_chunk_index,
+ wtf_size_t first_chunk_index,
bool requires_own_layer);
// Merge another pending layer after this one, appending all its paint
// chunks after chunks in this layer, with appropriate space conversion
@@ -127,7 +140,7 @@ class PLATFORM_EXPORT PaintArtifactCompositor final
void Upcast(const PropertyTreeState&);
FloatRect bounds;
- Vector<size_t> paint_chunk_indices;
+ Vector<wtf_size_t> paint_chunk_indices;
FloatRect rect_known_to_be_opaque;
PropertyTreeState property_tree_state;
bool requires_own_layer;
@@ -180,6 +193,8 @@ class PLATFORM_EXPORT PaintArtifactCompositor final
new_content_layer_clients,
Vector<scoped_refptr<cc::Layer>>& new_scroll_hit_test_layers);
+ bool PropertyTreeStateChanged(const PropertyTreeState&) const;
+
const TransformPaintPropertyNode& ScrollTranslationForPendingLayer(
const PaintArtifact&,
const PendingLayer&);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
index c89bf816d8f..1855e61bdf5 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
@@ -167,13 +167,13 @@ class PaintArtifactCompositorTest : public testing::Test,
const auto* scroll_node = scroll_offset.ScrollNode();
scoped_refptr<cc::Layer> layer = cc::Layer::Create();
auto rect = scroll_node->ContainerRect();
- layer->SetScrollable(gfx::Size(rect.Width(), rect.Height()));
- layer->SetBounds(gfx::Size(rect.Width(), rect.Height()));
+ layer->SetOffsetToTransformParent(gfx::Vector2dF(rect.X(), rect.Y()));
+ layer->SetScrollable(gfx::Size(rect.Size()));
+ layer->SetBounds(gfx::Size(rect.Size()));
layer->SetElementId(scroll_node->GetCompositorElementId());
layer->set_did_scroll_callback(
paint_artifact_compositor_->scroll_callback_);
- artifact.Chunk(scroll_offset, clip, effect)
- .ForeignLayer(FloatPoint(rect.Location()), rect.Size(), layer);
+ artifact.Chunk(scroll_offset, clip, effect).ForeignLayer(layer);
return;
}
// Scroll hit test layers are marked as scrollable for hit testing but are
@@ -904,12 +904,12 @@ TEST_P(PaintArtifactCompositorTest, SiblingClipsWithAlias) {
TEST_P(PaintArtifactCompositorTest, ForeignLayerPassesThrough) {
scoped_refptr<cc::Layer> layer = cc::Layer::Create();
layer->SetIsDrawable(true);
+ layer->SetOffsetToTransformParent(gfx::Vector2dF(50, 60));
layer->SetBounds(gfx::Size(400, 300));
TestPaintArtifact test_artifact;
test_artifact.Chunk().RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite);
- test_artifact.Chunk().ForeignLayer(FloatPoint(50, 60), IntSize(400, 300),
- layer);
+ test_artifact.Chunk().ForeignLayer(layer);
test_artifact.Chunk().RectDrawing(FloatRect(0, 0, 100, 100), Color::kGray);
auto artifact = test_artifact.Build();
@@ -1059,9 +1059,9 @@ TEST_P(PaintArtifactCompositorTest, OneScrollNode) {
// The scrolling contents layer is clipped to the scrolling range.
EXPECT_EQ(gfx::Size(27, 19), layer->bounds());
- EXPECT_EQ(gfx::Vector2dF(0, 12), layer->offset_to_transform_parent());
+ EXPECT_EQ(gfx::Vector2dF(3, 12), layer->offset_to_transform_parent());
EXPECT_THAT(layer->GetPicture(),
- Pointee(DrawsRectangle(FloatRect(0, 0, 60, 19), Color::kWhite)));
+ Pointee(DrawsRectangle(FloatRect(0, 0, 57, 19), Color::kWhite)));
auto* scroll_layer = ScrollableLayerAt(0);
EXPECT_TRUE(scroll_layer->scrollable());
@@ -1105,10 +1105,10 @@ TEST_P(PaintArtifactCompositorTest, TransformUnderScrollNode) {
EXPECT_EQ(scroll_node.id, layer1->scroll_tree_index());
// The scrolling layer is clipped to the scrollable range.
- EXPECT_EQ(gfx::Vector2dF(0, 4), layer0->offset_to_transform_parent());
- EXPECT_EQ(gfx::Size(27, 8), layer0->bounds());
+ EXPECT_EQ(gfx::Vector2dF(3, 5), layer0->offset_to_transform_parent());
+ EXPECT_EQ(gfx::Size(27, 7), layer0->bounds());
EXPECT_THAT(layer0->GetPicture(),
- Pointee(DrawsRectangle(FloatRect(0, 0, 40, 8), Color::kBlack)));
+ Pointee(DrawsRectangle(FloatRect(0, 0, 37, 7), Color::kBlack)));
// The layer under the transform without a scroll node is not clipped.
EXPECT_EQ(gfx::Vector2dF(1, -30), layer1->offset_to_transform_parent());
@@ -1863,7 +1863,7 @@ TEST_P(PaintArtifactCompositorTest, PendingLayer) {
PendingLayer pending_layer(chunk1, 0, false);
EXPECT_EQ(FloatRect(0, 0, 30, 40), pending_layer.bounds);
- EXPECT_EQ((Vector<size_t>{0}), pending_layer.paint_chunk_indices);
+ EXPECT_EQ((Vector<wtf_size_t>{0}), pending_layer.paint_chunk_indices);
EXPECT_EQ(pending_layer.bounds, pending_layer.rect_known_to_be_opaque);
PaintChunk chunk2 = DefaultChunk();
@@ -1874,7 +1874,7 @@ TEST_P(PaintArtifactCompositorTest, PendingLayer) {
// Bounds not equal to one PaintChunk.
EXPECT_EQ(FloatRect(0, 0, 40, 60), pending_layer.bounds);
- EXPECT_EQ((Vector<size_t>{0, 1}), pending_layer.paint_chunk_indices);
+ EXPECT_EQ((Vector<wtf_size_t>{0, 1}), pending_layer.paint_chunk_indices);
EXPECT_NE(pending_layer.bounds, pending_layer.rect_known_to_be_opaque);
PaintChunk chunk3 = DefaultChunk();
@@ -1884,7 +1884,7 @@ TEST_P(PaintArtifactCompositorTest, PendingLayer) {
pending_layer.Merge(PendingLayer(chunk3, 2, false));
EXPECT_EQ(FloatRect(-5, -25, 45, 85), pending_layer.bounds);
- EXPECT_EQ((Vector<size_t>{0, 1, 2}), pending_layer.paint_chunk_indices);
+ EXPECT_EQ((Vector<wtf_size_t>{0, 1, 2}), pending_layer.paint_chunk_indices);
EXPECT_NE(pending_layer.bounds, pending_layer.rect_known_to_be_opaque);
}
@@ -2290,9 +2290,43 @@ TEST_P(PaintArtifactCompositorTest, UpdatePopulatesCompositedElementIds) {
EXPECT_EQ(2u, composited_element_ids.size());
EXPECT_TRUE(
- composited_element_ids.Contains(transform->GetCompositorElementId()));
+ composited_element_ids.count(transform->GetCompositorElementId()));
+ EXPECT_TRUE(composited_element_ids.count(effect->GetCompositorElementId()));
+}
+
+// If we have both a transform and an opacity animation, they should both be
+// included in the composited element id set returned from
+// |PaintArtifactCompositor::Update(...)|.
+TEST_P(PaintArtifactCompositorTest, UniqueAnimationCompositedElementIds) {
+ TransformPaintPropertyNode::State transform_state;
+ transform_state.direct_compositing_reasons =
+ CompositingReason::kActiveTransformAnimation;
+ transform_state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
+ 31, CompositorElementIdNamespace::kPrimaryTransform);
+ auto transform =
+ TransformPaintPropertyNode::Create(t0(), std::move(transform_state));
+
+ EffectPaintPropertyNode::State effect_state;
+ effect_state.local_transform_space = transform;
+ effect_state.output_clip = &c0();
+ effect_state.opacity = 2.0 / 255.0;
+ effect_state.direct_compositing_reasons =
+ CompositingReason::kActiveOpacityAnimation;
+ effect_state.compositor_element_id = CompositorElementIdFromUniqueObjectId(
+ 41, CompositorElementIdNamespace::kPrimaryEffect);
+ auto effect = EffectPaintPropertyNode::Create(e0(), std::move(effect_state));
+
+ TestPaintArtifact artifact;
+ artifact.Chunk(*transform, c0(), *effect)
+ .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack);
+
+ CompositorElementIdSet composited_element_ids;
+ Update(artifact.Build(), composited_element_ids);
+
+ EXPECT_EQ(2u, composited_element_ids.size());
EXPECT_TRUE(
- composited_element_ids.Contains(effect->GetCompositorElementId()));
+ composited_element_ids.count(transform->GetCompositorElementId()));
+ EXPECT_TRUE(composited_element_ids.count(effect->GetCompositorElementId()));
}
TEST_P(PaintArtifactCompositorTest, SkipChunkWithOpacityZero) {
@@ -2444,15 +2478,18 @@ TEST_P(PaintArtifactCompositorTest, UpdateManagesLayerElementIds) {
Update(artifact.Build());
ASSERT_EQ(1u, ContentLayerCount());
- ASSERT_TRUE(GetLayerTreeHost().LayerByElementId(element_id));
+ ASSERT_TRUE(GetLayerTreeHost().IsElementInList(
+ element_id, cc::ElementListType::ACTIVE));
}
{
TestPaintArtifact artifact;
- ASSERT_TRUE(GetLayerTreeHost().LayerByElementId(element_id));
+ ASSERT_TRUE(GetLayerTreeHost().IsElementInList(
+ element_id, cc::ElementListType::ACTIVE));
Update(artifact.Build());
ASSERT_EQ(0u, ContentLayerCount());
- ASSERT_FALSE(GetLayerTreeHost().LayerByElementId(element_id));
+ ASSERT_FALSE(GetLayerTreeHost().IsElementInList(
+ element_id, cc::ElementListType::ACTIVE));
}
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
index 368dda9bc1a..c14f863846a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
@@ -497,6 +497,9 @@ void ConversionContext::StartEffect(const EffectPaintPropertyNode* effect) {
effect->GetColorFilter() != kColorFilterNone;
DCHECK(!has_filter || !(has_opacity || has_other_effects));
+ // TODO(crbug.com/904592): Add support for non-composited backdrop-filter
+ // here.
+
// Apply effects.
cc_list_.StartPaint();
if (!has_filter) {
@@ -525,7 +528,6 @@ void ConversionContext::StartEffect(const EffectPaintPropertyNode* effect) {
cc_list_.push<cc::TranslateOp>(filter_origin.X(), filter_origin.Y());
saved_count++;
}
-
// The size parameter is only used to computed the origin of zoom
// operation, which we never generate.
gfx::SizeF empty;
@@ -534,7 +536,6 @@ void ConversionContext::StartEffect(const EffectPaintPropertyNode* effect) {
effect->Filter().AsCcFilterOperations(), empty));
save_layer_id = cc_list_.push<cc::SaveLayerOp>(nullptr, &filter_flags);
saved_count++;
-
if (filter_origin != FloatPoint())
cc_list_.push<cc::TranslateOp>(-filter_origin.X(), -filter_origin.Y());
}
@@ -671,7 +672,9 @@ void ConversionContext::Convert(const PaintChunkSubset& paint_chunks,
bool switched_to_chunk_state = false;
for (const auto& item : display_items.ItemsInPaintChunk(chunk)) {
- DCHECK(item.IsDrawing());
+ if (!item.IsDrawing())
+ continue;
+
auto record =
static_cast<const DrawingDisplayItem&>(item).GetPaintRecord();
// If we have an empty paint record, then we would prefer not to draw it.
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc
index da7e94b8a30..83635ef9c2a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc
@@ -178,11 +178,6 @@ void PropertyTreeManager::SetCurrentEffectHasRenderSurface() {
int PropertyTreeManager::EnsureCompositorTransformNode(
const TransformPaintPropertyNode* transform_node) {
- DCHECK(transform_node);
- // TODO(crbug.com/645615): Remove the failsafe here.
- if (!transform_node)
- return kSecondaryRootNodeId;
-
transform_node = transform_node->Unalias();
auto it = transform_node_map_.find(transform_node);
if (it != transform_node_map_.end())
@@ -295,7 +290,7 @@ int PropertyTreeManager::EnsureCompositorTransformNode(
return id;
}
-void PropertyTreeManager::EnsureCompositorPageScaleTransformNode(
+int PropertyTreeManager::EnsureCompositorPageScaleTransformNode(
const TransformPaintPropertyNode* node) {
int id = EnsureCompositorTransformNode(node);
DCHECK(GetTransformTree().Node(id));
@@ -308,15 +303,12 @@ void PropertyTreeManager::EnsureCompositorPageScaleTransformNode(
compositor_node.post_local.matrix() = compositor_node.local.matrix();
compositor_node.pre_local.matrix().setIdentity();
compositor_node.local.matrix().setIdentity();
+
+ return id;
}
int PropertyTreeManager::EnsureCompositorClipNode(
const ClipPaintPropertyNode* clip_node) {
- DCHECK(clip_node);
- // TODO(crbug.com/645615): Remove the failsafe here.
- if (!clip_node)
- return kSecondaryRootNodeId;
-
clip_node = clip_node->Unalias();
auto it = clip_node_map_.find(clip_node);
if (it != clip_node_map_.end())
@@ -720,6 +712,7 @@ bool PropertyTreeManager::BuildEffectNodesRecursively(
// decision until later phase of the pipeline. Remove premature optimization
// here once the work is ready.
if (!next_effect->Filter().IsEmpty() ||
+ !next_effect->BackdropFilter().IsEmpty() ||
used_blend_mode != SkBlendMode::kSrcOver)
effect_node.has_render_surface = true;
@@ -735,6 +728,8 @@ bool PropertyTreeManager::BuildEffectNodesRecursively(
nullptr)));
} else {
effect_node.filters = next_effect->Filter().AsCcFilterOperations();
+ effect_node.backdrop_filters =
+ next_effect->BackdropFilter().AsCcFilterOperations();
effect_node.filters_origin = next_effect->FiltersOrigin();
effect_node.transform_id =
EnsureCompositorTransformNode(next_effect->LocalTransformSpace());
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.h b/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.h
index edfce2ee663..1bab20eea08 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.h
@@ -100,8 +100,7 @@ class PropertyTreeManager {
int EnsureCompositorScrollNode(
const TransformPaintPropertyNode* scroll_offset_translation);
- void EnsureCompositorPageScaleTransformNode(
- const TransformPaintPropertyNode*);
+ int EnsureCompositorPageScaleTransformNode(const TransformPaintPropertyNode*);
// This function is expected to be invoked right before emitting each layer.
// It keeps track of the nesting of clip and effects, output a composited
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.cc b/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.cc
index 843a84a4fe7..b5824d882bb 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.cc
@@ -156,9 +156,6 @@ constexpr CompositingReasonStringMap kCompositingReasonsStringMap[] = {
"with no scrolling contents"},
{CompositingReason::kLayerForDecoration, "layerForDecoration",
"Layer painted on top of other layers as decoration"},
- {CompositingReason::kInlineTransform, "inlineTransform",
- "Has an inline transform, which causes subsequent layers to assume "
- "overlap"},
};
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.h b/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.h
index 30e174d5109..a9d700afff1 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositing_reasons.h
@@ -82,11 +82,7 @@ using CompositingReasons = uint64_t;
V(LayerForAncestorClippingMask) \
V(LayerForScrollingBlockSelection) \
/* Composited layer painted on top of all other layers as decoration. */ \
- V(LayerForDecoration) \
- \
- /* Composited elements with inline transforms trigger assumed overlap so \
- that we can update their transforms quickly. */ \
- V(InlineTransform)
+ V(LayerForDecoration)
class PLATFORM_EXPORT CompositingReason {
private:
@@ -147,7 +143,7 @@ class PLATFORM_EXPORT CompositingReason {
kComboAllStyleDeterminedReasons = kComboAllDirectStyleDeterminedReasons |
kComboCompositedDescendants |
- kCombo3DDescendants | kInlineTransform,
+ kCombo3DDescendants,
kComboSquashableReasons =
kOverlap | kAssumedOverlap | kOverflowScrollingParent,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.cc b/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.cc
index 2986ada33bd..3678cee8ffb 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.cc
@@ -32,6 +32,8 @@ CompositorElementId PLATFORM_EXPORT CompositorElementIdFromUniqueObjectId(
DCHECK(namespace_id == CompositorElementIdNamespace::kPrimary ||
namespace_id == CompositorElementIdNamespace::kScroll ||
namespace_id == CompositorElementIdNamespace::kStickyTranslation ||
+ namespace_id == CompositorElementIdNamespace::kPrimaryEffect ||
+ namespace_id == CompositorElementIdNamespace::kPrimaryTransform ||
namespace_id == CompositorElementIdNamespace::kEffectFilter ||
namespace_id == CompositorElementIdNamespace::kEffectMask ||
namespace_id == CompositorElementIdNamespace::kEffectClipPath ||
diff --git a/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.h b/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.h
index e010e890787..eeaeed8b823 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/compositor_element_id.h
@@ -5,11 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_COMPOSITOR_ELEMENT_ID_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_COMPOSITOR_ELEMENT_ID_H_
+#include <unordered_set>
+
#include "cc/trees/element_id.h"
#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
-#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
namespace blink {
@@ -20,7 +19,8 @@ enum class CompositorElementIdNamespace {
kUniqueObjectId,
kScroll,
kStickyTranslation,
- // The following are SPv2-only.
+ kPrimaryEffect,
+ kPrimaryTransform,
kEffectFilter,
kEffectMask,
kEffectClipPath,
@@ -54,37 +54,11 @@ CompositorElementId PLATFORM_EXPORT
// TODO(chrishtr): refactor ScrollState to remove this dependency.
CompositorElementId PLATFORM_EXPORT CompositorElementIdFromDOMNodeId(DOMNodeId);
-// Note cc::ElementId has a hash function already implemented via
-// ElementIdHash::operator(). However for consistency's sake we choose to use
-// Blink's hash functions with Blink specific data structures.
-struct CompositorElementIdHash {
- static unsigned GetHash(const CompositorElementId& key) {
- return WTF::HashInt(static_cast<cc::ElementIdType>(key.GetInternalValue()));
- }
- static bool Equal(const CompositorElementId& a,
- const CompositorElementId& b) {
- return a == b;
- }
- static const bool safe_to_compare_to_empty_or_deleted = true;
-};
-
CompositorElementIdNamespace PLATFORM_EXPORT
NamespaceFromCompositorElementId(CompositorElementId);
-struct CompositorElementIdHashTraits
- : WTF::GenericHashTraits<CompositorElementId> {
- static CompositorElementId EmptyValue() { return CompositorElementId(1); }
- static void ConstructDeletedValue(CompositorElementId& slot, bool) {
- slot = CompositorElementId();
- }
- static bool IsDeletedValue(CompositorElementId value) {
- return value == CompositorElementId();
- }
-};
-
-using CompositorElementIdSet = HashSet<CompositorElementId,
- CompositorElementIdHash,
- CompositorElementIdHashTraits>;
+using CompositorElementIdSet =
+ std::unordered_set<cc::ElementId, cc::ElementIdHash>;
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/contiguous_container.h b/chromium/third_party/blink/renderer/platform/graphics/contiguous_container.h
index d551da78b00..3430f74cb61 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/contiguous_container.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/contiguous_container.h
@@ -13,7 +13,6 @@
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/compiler.h"
#include "third_party/blink/renderer/platform/wtf/type_traits.h"
@@ -138,6 +137,8 @@ class ContiguousContainer : public ContiguousContainerBase {
IteratorWrapper<Vector<void*>::const_reverse_iterator,
const BaseElementType>;
+ using value_type = BaseElementType;
+
explicit ContiguousContainer(size_t max_object_size)
: ContiguousContainerBase(Align(max_object_size)) {}
@@ -199,7 +200,7 @@ class ContiguousContainer : public ContiguousContainerBase {
DerivedElementType& AllocateAndConstruct(Args&&... args) {
static_assert(WTF::IsSubclass<DerivedElementType, BaseElementType>::value,
"Must use subclass of BaseElementType.");
- static_assert(alignment % WTF_ALIGN_OF(DerivedElementType) == 0,
+ static_assert(alignment % alignof(DerivedElementType) == 0,
"Derived type requires stronger alignment.");
return *new (AlignedAllocate(sizeof(DerivedElementType)))
DerivedElementType(std::forward<Args>(args)...);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/contiguous_container_test.cc b/chromium/third_party/blink/renderer/platform/graphics/contiguous_container_test.cc
index e936bfb7619..cc5887984b6 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/contiguous_container_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/contiguous_container_test.cc
@@ -512,7 +512,7 @@ TEST(ContiguousContainerTest, CapacityInBytesAfterClear) {
}
TEST(ContiguousContainerTest, Alignment) {
- const size_t kMaxAlign = WTF_ALIGN_OF(long double);
+ const size_t kMaxAlign = alignof(long double);
ContiguousContainer<Point2D, kMaxAlign> list(kMaxPointSize);
list.AllocateAndConstruct<Point2D>();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/cpu/arm/webgl_image_conversion_neon.h b/chromium/third_party/blink/renderer/platform/graphics/cpu/arm/webgl_image_conversion_neon.h
index 1e1d1834bdd..6316c32e2f8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/cpu/arm/webgl_image_conversion_neon.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/cpu/arm/webgl_image_conversion_neon.h
@@ -33,7 +33,7 @@
namespace blink {
-namespace SIMD {
+namespace simd {
ALWAYS_INLINE void UnpackOneRowOfRGBA16LittleToRGBA8(const uint16_t*& source,
uint8_t*& destination,
@@ -288,7 +288,7 @@ ALWAYS_INLINE void PackOneRowOfRGBA8ToUnsignedShort565(
pixels_per_row = tail_components / 4;
}
-} // namespace SIMD
+} // namespace simd
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/cpu/mips/webgl_image_conversion_msa.h b/chromium/third_party/blink/renderer/platform/graphics/cpu/mips/webgl_image_conversion_msa.h
index 03c75706ff5..3de62947216 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/cpu/mips/webgl_image_conversion_msa.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/cpu/mips/webgl_image_conversion_msa.h
@@ -11,7 +11,7 @@
namespace blink {
-namespace SIMD {
+namespace simd {
#define SEPERATE_RGBA_FRM_16BIT_5551INPUT(in, out_r, out_g, out_b, out_a) \
cnst31 = (v8u16)__msa_ldi_h(0x1F); \
@@ -1145,7 +1145,7 @@ ALWAYS_INLINE void packOneRowOfRGBA8LittleToRA8MSA(const uint8_t*& source,
pixelsPerRow &= 7;
}
-} // namespace SIMD
+} // namespace simd
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/cpu/x86/webgl_image_conversion_sse.h b/chromium/third_party/blink/renderer/platform/graphics/cpu/x86/webgl_image_conversion_sse.h
index 6438ee77835..c33573df5fb 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/cpu/x86/webgl_image_conversion_sse.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/cpu/x86/webgl_image_conversion_sse.h
@@ -12,7 +12,7 @@
namespace blink {
-namespace SIMD {
+namespace simd {
ALWAYS_INLINE void UnpackOneRowOfRGBA4444LittleToRGBA8(
const uint16_t*& source,
@@ -192,7 +192,7 @@ ALWAYS_INLINE void PackOneRowOfRGBA8LittleToRGBA8(const uint8_t* source,
}
}
-} // namespace SIMD
+} // namespace simd
} // namespace blink
#endif // ARCH_CPU_X86_FAMILY
diff --git a/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.cc b/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.cc
index 08e80c12b0c..6c0aef5f8af 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.cc
@@ -32,7 +32,6 @@
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/image-decoders/segment_reader.h"
-#include "third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/skia/include/core/SkData.h"
@@ -131,6 +130,7 @@ bool DecodingImageGenerator::GetPixels(const SkImageInfo& dst_info,
// the requested color type from N32.
SkImageInfo target_info = dst_info;
char* memory = static_cast<char*>(pixels);
+ std::unique_ptr<char[]> memory_ref_ptr;
size_t adjusted_row_bytes = row_bytes;
if ((target_info.colorType() != kN32_SkColorType) &&
(target_info.colorType() != kRGBA_F16_SkColorType)) {
@@ -141,7 +141,8 @@ bool DecodingImageGenerator::GetPixels(const SkImageInfo& dst_info,
DCHECK_EQ(0ul, row_bytes % dst_info.bytesPerPixel());
adjusted_row_bytes =
target_info.bytesPerPixel() * (row_bytes / dst_info.bytesPerPixel());
- memory = new char[target_info.computeMinByteSize()];
+ memory_ref_ptr.reset(new char[target_info.computeMinByteSize()]);
+ memory = memory_ref_ptr.get();
}
// Skip the check for alphaType. blink::ImageFrame may have changed the
@@ -162,64 +163,83 @@ bool DecodingImageGenerator::GetPixels(const SkImageInfo& dst_info,
decode_info = decode_info.makeAlphaType(kUnpremul_SkAlphaType);
}
- PlatformInstrumentation::WillDecodeLazyPixelRef(lazy_pixel_ref);
- bool decoded = frame_generator_->DecodeAndScale(
- data_.get(), all_data_received_, frame_index, decode_info, memory,
- adjusted_row_bytes, alpha_option, client_id);
- PlatformInstrumentation::DidDecodeLazyPixelRef();
+ bool decoded = false;
+ {
+ TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "Decode LazyPixelRef", "LazyPixelRef", lazy_pixel_ref);
+ decoded = frame_generator_->DecodeAndScale(
+ data_.get(), all_data_received_, frame_index, decode_info, memory,
+ adjusted_row_bytes, alpha_option, client_id);
+ }
if (decoded && needs_color_xform) {
TRACE_EVENT0("blink", "DecodingImageGenerator::getPixels - apply xform");
SkPixmap src(decode_info, memory, adjusted_row_bytes);
- decoded =
- decoded && src.readPixels(target_info, memory, adjusted_row_bytes);
+ decoded = src.readPixels(target_info, memory, adjusted_row_bytes);
DCHECK(decoded);
}
// Convert the color type to the requested one if necessary
if (decoded && target_info.colorType() != dst_info.colorType()) {
- decoded =
- decoded && SkPixmap{target_info, memory, adjusted_row_bytes}.readPixels(
- SkPixmap{dst_info, pixels, row_bytes});
- delete[] memory;
+ decoded = SkPixmap{target_info, memory, adjusted_row_bytes}.readPixels(
+ SkPixmap{dst_info, pixels, row_bytes});
DCHECK(decoded);
}
-
return decoded;
}
-bool DecodingImageGenerator::QueryYUV8(SkYUVSizeInfo* size_info,
- SkYUVColorSpace* color_space) const {
- // YUV decoding does not currently support progressive decoding. See comment
- // in ImageFrameGenerator.h.
- if (!can_yuv_decode_ || !all_data_received_)
+bool DecodingImageGenerator::QueryYUVA8(
+ SkYUVASizeInfo* size_info,
+ SkYUVAIndex indices[SkYUVAIndex::kIndexCount],
+ SkYUVColorSpace* color_space) const {
+ if (!can_yuv_decode_)
return false;
- TRACE_EVENT0("blink", "DecodingImageGenerator::queryYUV8");
+ TRACE_EVENT0("blink", "DecodingImageGenerator::queryYUVA8");
if (color_space)
*color_space = kJPEG_SkYUVColorSpace;
+ // Indicate that we have three separate planes
+ indices[SkYUVAIndex::kY_Index] = {0, SkColorChannel::kR};
+ indices[SkYUVAIndex::kU_Index] = {1, SkColorChannel::kR};
+ indices[SkYUVAIndex::kV_Index] = {2, SkColorChannel::kR};
+ indices[SkYUVAIndex::kA_Index] = {-1, SkColorChannel::kR};
+
return frame_generator_->GetYUVComponentSizes(data_.get(), size_info);
}
-bool DecodingImageGenerator::GetYUV8Planes(const SkYUVSizeInfo& size_info,
- void* planes[3],
- size_t frame_index,
- uint32_t lazy_pixel_ref) {
+bool DecodingImageGenerator::GetYUVA8Planes(const SkYUVASizeInfo& size_info,
+ const SkYUVAIndex indices[4],
+ void* planes[3],
+ size_t frame_index,
+ uint32_t lazy_pixel_ref) {
// YUV decoding does not currently support progressive decoding. See comment
// in ImageFrameGenerator.h.
DCHECK(can_yuv_decode_);
DCHECK(all_data_received_);
- TRACE_EVENT0("blink", "DecodingImageGenerator::getYUV8Planes");
+ TRACE_EVENT0("blink", "DecodingImageGenerator::getYUVA8Planes");
+ TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "Decode LazyPixelRef", "LazyPixelRef", lazy_pixel_ref);
+
+ // Verify sizes and indices
+ for (int i = 0; i < 3; ++i) {
+ if (size_info.fSizes[i].isEmpty() || !size_info.fWidthBytes[i]) {
+ return false;
+ }
+ }
+ if (!size_info.fSizes[3].isEmpty() || size_info.fWidthBytes[3]) {
+ return false;
+ }
+ int numPlanes;
+ if (!SkYUVAIndex::AreValidIndices(indices, &numPlanes) || numPlanes != 3) {
+ return false;
+ }
- PlatformInstrumentation::WillDecodeLazyPixelRef(lazy_pixel_ref);
bool decoded =
frame_generator_->DecodeToYUV(data_.get(), frame_index, size_info.fSizes,
planes, size_info.fWidthBytes);
- PlatformInstrumentation::DidDecodeLazyPixelRef();
-
return decoded;
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.h b/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.h
index 8e083e0d288..5e95cdc597a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/decoding_image_generator.h
@@ -33,6 +33,7 @@
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/skia/include/core/SkImageInfo.h"
+#include "third_party/skia/include/core/SkYUVAIndex.h"
class SkData;
@@ -74,11 +75,14 @@ class PLATFORM_EXPORT DecodingImageGenerator final
size_t frame_index,
PaintImage::GeneratorClientId client_id,
uint32_t lazy_pixel_ref) override;
- bool QueryYUV8(SkYUVSizeInfo*, SkYUVColorSpace*) const override;
- bool GetYUV8Planes(const SkYUVSizeInfo&,
- void* planes[3],
- size_t frame_index,
- uint32_t lazy_pixel_ref) override;
+ bool QueryYUVA8(SkYUVASizeInfo*,
+ SkYUVAIndex[SkYUVAIndex::kIndexCount],
+ SkYUVColorSpace*) const override;
+ bool GetYUVA8Planes(const SkYUVASizeInfo&,
+ const SkYUVAIndex[SkYUVAIndex::kIndexCount],
+ void* planes[4],
+ size_t frame_index,
+ uint32_t lazy_pixel_ref) override;
SkISize GetSupportedDecodeSize(const SkISize& requested_size) const override;
PaintImage::ContentId GetContentIdForFrame(size_t frame_index) const override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder.cc b/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder.cc
index 715bd9ca53b..e0efd3fb029 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder.cc
@@ -266,10 +266,6 @@ void DeferredImageDecoder::ActivateLazyDecoding() {
image_is_high_bit_depth_ = metadata_decoder_->ImageIsHighBitDepth();
has_hot_spot_ = metadata_decoder_->HotSpot(hot_spot_);
filename_extension_ = metadata_decoder_->FilenameExtension();
- // JPEG images support YUV decoding; other decoders do not. (WebP could in the
- // future.)
- can_yuv_decode_ = RuntimeEnabledFeatures::DecodeToYUVEnabled() &&
- (filename_extension_ == "jpg");
has_embedded_color_profile_ = metadata_decoder_->HasEmbeddedColorProfile();
color_space_for_sk_images_ = metadata_decoder_->ColorSpaceForSkImages();
@@ -311,6 +307,12 @@ void DeferredImageDecoder::PrepareLazyDecodedFrames() {
metadata_decoder_->FrameIsReceivedAtIndex(last_frame);
}
+ // YUV decoding does not currently support progressive decoding. See comment
+ // in image_frame_generator.h.
+ can_yuv_decode_ = RuntimeEnabledFeatures::DecodeToYUVEnabled() &&
+ metadata_decoder_->CanDecodeToYUV() && all_data_received_ &&
+ !frame_generator_->IsMultiFrame();
+
// If we've received all of the data, then we can reset the metadata decoder,
// since everything we care about should now be stored in |frame_data_|.
if (all_data_received_) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test.cc b/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test.cc
index d6dd9d1c21b..fd85381f277 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/deferred_image_decoder_test.cc
@@ -39,9 +39,9 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h"
#include "third_party/blink/renderer/platform/graphics/test/mock_image_decoder.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkPixmap.h"
#include "third_party/skia/include/core/SkSurface.h"
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.cc
index dc633651cf0..80f35353935 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.cc
@@ -35,7 +35,7 @@ FEBlend::FEBlend(Filter* filter, BlendMode mode)
: FilterEffect(filter), mode_(mode) {}
FEBlend* FEBlend::Create(Filter* filter, BlendMode mode) {
- return new FEBlend(filter, mode);
+ return MakeGarbageCollected<FEBlend>(filter, mode);
}
bool FEBlend::SetBlendMode(BlendMode mode) {
@@ -46,10 +46,10 @@ bool FEBlend::SetBlendMode(BlendMode mode) {
}
sk_sp<PaintFilter> FEBlend::CreateImageFilter() {
- sk_sp<PaintFilter> foreground(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
- sk_sp<PaintFilter> background(
- PaintFilterBuilder::Build(InputEffect(1), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> foreground(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> background(paint_filter_builder::Build(
+ InputEffect(1), OperatingInterpolationSpace()));
SkBlendMode mode =
WebCoreCompositeToSkiaComposite(kCompositeSourceOver, mode_);
PaintFilter::CropRect crop_rect = GetCropRect();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.h
index 4dbbf31c668..0b23ad9621d 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_blend.h
@@ -32,6 +32,8 @@ class PLATFORM_EXPORT FEBlend final : public FilterEffect {
public:
static FEBlend* Create(Filter*, BlendMode);
+ FEBlend(Filter*, BlendMode);
+
BlendMode GetBlendMode() const { return mode_; }
bool SetBlendMode(BlendMode);
@@ -39,8 +41,6 @@ class PLATFORM_EXPORT FEBlend final : public FilterEffect {
int indention) const override;
private:
- FEBlend(Filter*, BlendMode);
-
sk_sp<PaintFilter> CreateImageFilter() override;
BlendMode mode_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.cc
index 1b956a66f99..f16cee8f182 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.cc
@@ -28,9 +28,9 @@ WTF::TextStream& FEBoxReflect::ExternalRepresentation(WTF::TextStream& ts,
}
sk_sp<PaintFilter> FEBoxReflect::CreateImageFilter() {
- return PaintFilterBuilder::BuildBoxReflectFilter(
- reflection_,
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ return paint_filter_builder::BuildBoxReflectFilter(
+ reflection_, paint_filter_builder::Build(InputEffect(0),
+ OperatingInterpolationSpace()));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.h
index f7227790c0f..a28d295fc43 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_box_reflect.h
@@ -15,15 +15,16 @@ namespace blink {
class PLATFORM_EXPORT FEBoxReflect final : public FilterEffect {
public:
static FEBoxReflect* Create(Filter* filter, const BoxReflection& reflection) {
- return new FEBoxReflect(filter, reflection);
+ return MakeGarbageCollected<FEBoxReflect>(filter, reflection);
}
+ FEBoxReflect(Filter*, const BoxReflection&);
+
// FilterEffect implementation
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
int indentation) const final;
private:
- FEBoxReflect(Filter*, const BoxReflection&);
~FEBoxReflect() final;
FloatRect MapEffect(const FloatRect&) const final;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.cc
index a1046f3fd5f..616cb4312c2 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.cc
@@ -40,7 +40,7 @@ FEColorMatrix::FEColorMatrix(Filter* filter,
FEColorMatrix* FEColorMatrix::Create(Filter* filter,
ColorMatrixType type,
const Vector<float>& values) {
- return new FEColorMatrix(filter, type, values);
+ return MakeGarbageCollected<FEColorMatrix>(filter, type, values);
}
ColorMatrixType FEColorMatrix::GetType() const {
@@ -153,8 +153,8 @@ bool FEColorMatrix::AffectsTransparentPixels() const {
}
sk_sp<PaintFilter> FEColorMatrix::CreateImageFilter() {
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
sk_sp<SkColorFilter> filter = CreateColorFilter(type_, values_);
PaintFilter::CropRect rect = GetCropRect();
return sk_make_sp<ColorFilterPaintFilter>(std::move(filter), std::move(input),
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.h
index 2cd73e87872..212eb9681fa 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_color_matrix.h
@@ -40,6 +40,8 @@ class PLATFORM_EXPORT FEColorMatrix final : public FilterEffect {
public:
static FEColorMatrix* Create(Filter*, ColorMatrixType, const Vector<float>&);
+ FEColorMatrix(Filter*, ColorMatrixType, const Vector<float>&);
+
ColorMatrixType GetType() const;
bool SetType(ColorMatrixType);
@@ -55,8 +57,6 @@ class PLATFORM_EXPORT FEColorMatrix final : public FilterEffect {
float value);
private:
- FEColorMatrix(Filter*, ColorMatrixType, const Vector<float>&);
-
sk_sp<PaintFilter> CreateImageFilter() override;
bool AffectsTransparentPixels() const override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc
index ba73a1f815e..af4e32d69d9 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.cc
@@ -52,8 +52,8 @@ FEComponentTransfer* FEComponentTransfer::Create(
const ComponentTransferFunction& green_func,
const ComponentTransferFunction& blue_func,
const ComponentTransferFunction& alpha_func) {
- return new FEComponentTransfer(filter, red_func, green_func, blue_func,
- alpha_func);
+ return MakeGarbageCollected<FEComponentTransfer>(filter, red_func, green_func,
+ blue_func, alpha_func);
}
static void Identity(unsigned char*, const ComponentTransferFunction&) {}
@@ -134,8 +134,8 @@ bool FEComponentTransfer::AffectsTransparentPixels() const {
}
sk_sp<PaintFilter> FEComponentTransfer::CreateImageFilter() {
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
unsigned char r_values[256], g_values[256], b_values[256], a_values[256];
GetValues(r_values, g_values, b_values, a_values);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.h
index 74738c4dc1b..1509883afe5 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_component_transfer.h
@@ -67,16 +67,16 @@ class PLATFORM_EXPORT FEComponentTransfer final : public FilterEffect {
const ComponentTransferFunction& blue_func,
const ComponentTransferFunction& alpha_func);
- WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
- int indention) const override;
-
- private:
FEComponentTransfer(Filter*,
const ComponentTransferFunction& red_func,
const ComponentTransferFunction& green_func,
const ComponentTransferFunction& blue_func,
const ComponentTransferFunction& alpha_func);
+ WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
+ int indention) const override;
+
+ private:
sk_sp<PaintFilter> CreateImageFilter() override;
bool AffectsTransparentPixels() const override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.cc
index b62ac9f8a77..2b0834f4522 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.cc
@@ -47,7 +47,7 @@ FEComposite* FEComposite::Create(Filter* filter,
float k2,
float k3,
float k4) {
- return new FEComposite(filter, type, k1, k2, k3, k4);
+ return MakeGarbageCollected<FEComposite>(filter, type, k1, k2, k3, k4);
}
CompositeOperationType FEComposite::Operation() const {
@@ -191,11 +191,11 @@ sk_sp<PaintFilter> FEComposite::CreateImageFilterWithoutValidation() {
sk_sp<PaintFilter> FEComposite::CreateImageFilterInternal(
bool requires_pm_color_validation) {
sk_sp<PaintFilter> foreground(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace(),
- !MayProduceInvalidPreMultipliedPixels()));
+ paint_filter_builder::Build(InputEffect(0), OperatingInterpolationSpace(),
+ !MayProduceInvalidPreMultipliedPixels()));
sk_sp<PaintFilter> background(
- PaintFilterBuilder::Build(InputEffect(1), OperatingInterpolationSpace(),
- !MayProduceInvalidPreMultipliedPixels()));
+ paint_filter_builder::Build(InputEffect(1), OperatingInterpolationSpace(),
+ !MayProduceInvalidPreMultipliedPixels()));
PaintFilter::CropRect crop_rect = GetCropRect();
if (type_ == FECOMPOSITE_OPERATOR_ARITHMETIC) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.h
index 3841eb7b411..d416525a0b9 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_composite.h
@@ -48,6 +48,13 @@ class PLATFORM_EXPORT FEComposite final : public FilterEffect {
float,
float);
+ FEComposite(Filter*,
+ const CompositeOperationType&,
+ float,
+ float,
+ float,
+ float);
+
CompositeOperationType Operation() const;
bool SetOperation(CompositeOperationType);
@@ -72,13 +79,6 @@ class PLATFORM_EXPORT FEComposite final : public FilterEffect {
}
private:
- FEComposite(Filter*,
- const CompositeOperationType&,
- float,
- float,
- float,
- float);
-
FloatRect MapInputs(const FloatRect&) const override;
bool AffectsTransparentPixels() const override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.cc
index 181432ee635..2598ea24b04 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.cc
@@ -57,8 +57,9 @@ FEConvolveMatrix* FEConvolveMatrix::Create(Filter* filter,
EdgeModeType edge_mode,
bool preserve_alpha,
const Vector<float>& kernel_matrix) {
- return new FEConvolveMatrix(filter, kernel_size, divisor, bias, target_offset,
- edge_mode, preserve_alpha, kernel_matrix);
+ return MakeGarbageCollected<FEConvolveMatrix>(filter, kernel_size, divisor,
+ bias, target_offset, edge_mode,
+ preserve_alpha, kernel_matrix);
}
FloatRect FEConvolveMatrix::MapEffect(const FloatRect& rect) const {
@@ -140,8 +141,8 @@ sk_sp<PaintFilter> FEConvolveMatrix::CreateImageFilter() {
if (!ParametersValid())
return CreateTransparentBlack();
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
SkISize kernel_size(
SkISize::Make(kernel_size_.Width(), kernel_size_.Height()));
// parametersValid() above checks that the kernel area fits in int.
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.h
index 615e29cf88a..9212f5a30f8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_convolve_matrix.h
@@ -50,6 +50,15 @@ class PLATFORM_EXPORT FEConvolveMatrix final : public FilterEffect {
bool,
const Vector<float>&);
+ FEConvolveMatrix(Filter*,
+ const IntSize&,
+ float,
+ float,
+ const IntPoint&,
+ EdgeModeType,
+ bool,
+ const Vector<float>&);
+
bool SetDivisor(float);
bool SetBias(float);
bool SetTargetOffset(const IntPoint&);
@@ -60,15 +69,6 @@ class PLATFORM_EXPORT FEConvolveMatrix final : public FilterEffect {
int indention) const override;
private:
- FEConvolveMatrix(Filter*,
- const IntSize&,
- float,
- float,
- const IntPoint&,
- EdgeModeType,
- bool,
- const Vector<float>&);
-
FloatRect MapEffect(const FloatRect&) const final;
sk_sp<PaintFilter> CreateImageFilter() override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.cc
index 344387f83fd..8d0c99da026 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.cc
@@ -47,8 +47,9 @@ FEDiffuseLighting* FEDiffuseLighting::Create(
float surface_scale,
float diffuse_constant,
scoped_refptr<LightSource> light_source) {
- return new FEDiffuseLighting(filter, lighting_color, surface_scale,
- diffuse_constant, std::move(light_source));
+ return MakeGarbageCollected<FEDiffuseLighting>(
+ filter, lighting_color, surface_scale, diffuse_constant,
+ std::move(light_source));
}
FEDiffuseLighting::~FEDiffuseLighting() = default;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.h
index 8c57b151a76..5db5f8afc3e 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_diffuse_lighting.h
@@ -36,6 +36,12 @@ class PLATFORM_EXPORT FEDiffuseLighting final : public FELighting {
float,
float,
scoped_refptr<LightSource>);
+
+ FEDiffuseLighting(Filter*,
+ const Color&,
+ float,
+ float,
+ scoped_refptr<LightSource>);
~FEDiffuseLighting() override;
Color LightingColor() const;
@@ -52,13 +58,6 @@ class PLATFORM_EXPORT FEDiffuseLighting final : public FELighting {
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
int indention) const override;
-
- private:
- FEDiffuseLighting(Filter*,
- const Color&,
- float,
- float,
- scoped_refptr<LightSource>);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.cc
index 79d35126a50..02ecb59ef78 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.cc
@@ -45,8 +45,8 @@ FEDisplacementMap* FEDisplacementMap::Create(
ChannelSelectorType x_channel_selector,
ChannelSelectorType y_channel_selector,
float scale) {
- return new FEDisplacementMap(filter, x_channel_selector, y_channel_selector,
- scale);
+ return MakeGarbageCollected<FEDisplacementMap>(filter, x_channel_selector,
+ y_channel_selector, scale);
}
FloatRect FEDisplacementMap::MapEffect(const FloatRect& rect) const {
@@ -113,16 +113,16 @@ static SkDisplacementMapEffect::ChannelSelectorType ToSkiaMode(
}
sk_sp<PaintFilter> FEDisplacementMap::CreateImageFilter() {
- sk_sp<PaintFilter> color =
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace());
+ sk_sp<PaintFilter> color = paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace());
// FEDisplacementMap must be a pass-through filter if
// the origin is tainted. See:
// https://drafts.fxtf.org/filter-effects/#fedisplacemnentmap-restrictions.
if (InputEffect(1)->OriginTainted())
return color;
- sk_sp<PaintFilter> displ =
- PaintFilterBuilder::Build(InputEffect(1), OperatingInterpolationSpace());
+ sk_sp<PaintFilter> displ = paint_filter_builder::Build(
+ InputEffect(1), OperatingInterpolationSpace());
SkDisplacementMapEffect::ChannelSelectorType type_x =
ToSkiaMode(x_channel_selector_);
SkDisplacementMapEffect::ChannelSelectorType type_y =
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.h
index a224f92a065..fac11a8d0dd 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_displacement_map.h
@@ -42,6 +42,11 @@ class PLATFORM_EXPORT FEDisplacementMap final : public FilterEffect {
ChannelSelectorType y_channel_selector,
float);
+ FEDisplacementMap(Filter*,
+ ChannelSelectorType x_channel_selector,
+ ChannelSelectorType y_channel_selector,
+ float);
+
ChannelSelectorType XChannelSelector() const;
bool SetXChannelSelector(const ChannelSelectorType);
@@ -55,11 +60,6 @@ class PLATFORM_EXPORT FEDisplacementMap final : public FilterEffect {
int indention) const override;
private:
- FEDisplacementMap(Filter*,
- ChannelSelectorType x_channel_selector,
- ChannelSelectorType y_channel_selector,
- float);
-
FloatRect MapInputs(const FloatRect&) const override;
FloatRect MapEffect(const FloatRect&) const override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.cc
index 113995770d0..e9d121f6586 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.cc
@@ -50,8 +50,8 @@ FEDropShadow* FEDropShadow::Create(Filter* filter,
float dy,
const Color& shadow_color,
float shadow_opacity) {
- return new FEDropShadow(filter, std_x, std_y, dx, dy, shadow_color,
- shadow_opacity);
+ return MakeGarbageCollected<FEDropShadow>(filter, std_x, std_y, dx, dy,
+ shadow_color, shadow_opacity);
}
FloatRect FEDropShadow::MapEffect(const FloatSize& std_deviation,
@@ -75,8 +75,8 @@ FloatRect FEDropShadow::MapEffect(const FloatRect& rect) const {
}
sk_sp<PaintFilter> FEDropShadow::CreateImageFilter() {
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
float dx = GetFilter()->ApplyHorizontalScale(dx_);
float dy = GetFilter()->ApplyVerticalScale(dy_);
float std_x = GetFilter()->ApplyHorizontalScale(std_x_);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.h
index bbdf2838f03..e3fa045d54c 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_drop_shadow.h
@@ -31,6 +31,8 @@ class PLATFORM_EXPORT FEDropShadow final : public FilterEffect {
static FEDropShadow*
Create(Filter*, float, float, float, float, const Color&, float);
+ FEDropShadow(Filter*, float, float, float, float, const Color&, float);
+
// Compute which destination area will be affected when applying a drop
// shadow effect with |stdDeviation| and |offset| to an area |rect|.
static FloatRect MapEffect(const FloatSize& std_deviation,
@@ -44,8 +46,6 @@ class PLATFORM_EXPORT FEDropShadow final : public FilterEffect {
int indention) const override;
private:
- FEDropShadow(Filter*, float, float, float, float, const Color&, float);
-
FloatRect MapEffect(const FloatRect&) const override;
sk_sp<PaintFilter> CreateImageFilter() override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.cc
index 27d749cd8b7..08715d1b987 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.cc
@@ -39,7 +39,7 @@ FEFlood::FEFlood(Filter* filter, const Color& flood_color, float flood_opacity)
FEFlood* FEFlood::Create(Filter* filter,
const Color& flood_color,
float flood_opacity) {
- return new FEFlood(filter, flood_color, flood_opacity);
+ return MakeGarbageCollected<FEFlood>(filter, flood_color, flood_opacity);
}
Color FEFlood::FloodColor() const {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.h
index 6ebaae3aafe..43147f601d5 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_flood.h
@@ -32,6 +32,8 @@ class PLATFORM_EXPORT FEFlood final : public FilterEffect {
public:
static FEFlood* Create(Filter*, const Color&, float);
+ FEFlood(Filter*, const Color&, float);
+
Color FloodColor() const;
bool SetFloodColor(const Color&);
@@ -47,8 +49,6 @@ class PLATFORM_EXPORT FEFlood final : public FilterEffect {
int indention) const override;
private:
- FEFlood(Filter*, const Color&, float);
-
sk_sp<PaintFilter> CreateImageFilter() override;
Color flood_color_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.cc
index 53325c61361..7be8b9452f1 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.cc
@@ -60,7 +60,7 @@ FEGaussianBlur::FEGaussianBlur(Filter* filter, float x, float y)
: FilterEffect(filter), std_x_(x), std_y_(y) {}
FEGaussianBlur* FEGaussianBlur::Create(Filter* filter, float x, float y) {
- return new FEGaussianBlur(filter, x, y);
+ return MakeGarbageCollected<FEGaussianBlur>(filter, x, y);
}
FloatRect FEGaussianBlur::MapEffect(const FloatSize& std_deviation,
@@ -81,8 +81,8 @@ FloatRect FEGaussianBlur::MapEffect(const FloatRect& rect) const {
}
sk_sp<PaintFilter> FEGaussianBlur::CreateImageFilter() {
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
float std_x = GetFilter()->ApplyHorizontalScale(std_x_);
float std_y = GetFilter()->ApplyVerticalScale(std_y_);
PaintFilter::CropRect rect = GetCropRect();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.h
index 73ec88b7263..ec92a6eb09e 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_gaussian_blur.h
@@ -31,6 +31,8 @@ class PLATFORM_EXPORT FEGaussianBlur final : public FilterEffect {
public:
static FEGaussianBlur* Create(Filter*, float, float);
+ FEGaussianBlur(Filter*, float, float);
+
// Compute which destination area will be affected when applying a gaussian
// blur effect with |stdDeviation| to an area |rect|.
static FloatRect MapEffect(const FloatSize& std_deviation, const FloatRect&);
@@ -39,8 +41,6 @@ class PLATFORM_EXPORT FEGaussianBlur final : public FilterEffect {
int indention) const override;
private:
- FEGaussianBlur(Filter*, float, float);
-
FloatRect MapEffect(const FloatRect&) const override;
sk_sp<PaintFilter> CreateImageFilter() override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc
index 4ec708206e2..232a37cb30b 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc
@@ -58,8 +58,8 @@ sk_sp<PaintFilter> FELighting::CreateImageFilter() {
return CreateTransparentBlack();
PaintFilter::CropRect rect = GetCropRect();
Color light_color = AdaptColorToOperatingInterpolationSpace(lighting_color_);
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
switch (light_source_->GetType()) {
case LS_DISTANT: {
DistantLightSource* distant_light_source =
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.cc
index 57aec415e97..f3c40fee615 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.cc
@@ -32,7 +32,7 @@ namespace blink {
FEMerge::FEMerge(Filter* filter) : FilterEffect(filter) {}
FEMerge* FEMerge::Create(Filter* filter) {
- return new FEMerge(filter);
+ return MakeGarbageCollected<FEMerge>(filter);
}
sk_sp<PaintFilter> FEMerge::CreateImageFilter() {
@@ -40,8 +40,8 @@ sk_sp<PaintFilter> FEMerge::CreateImageFilter() {
auto input_refs = std::make_unique<sk_sp<PaintFilter>[]>(size);
for (unsigned i = 0; i < size; ++i) {
- input_refs[i] = PaintFilterBuilder::Build(InputEffect(i),
- OperatingInterpolationSpace());
+ input_refs[i] = paint_filter_builder::Build(InputEffect(i),
+ OperatingInterpolationSpace());
}
PaintFilter::CropRect rect = GetCropRect();
return sk_make_sp<MergePaintFilter>(input_refs.get(), size, &rect);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.h
index 0577157d77a..02dab02abf0 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_merge.h
@@ -31,12 +31,12 @@ class PLATFORM_EXPORT FEMerge final : public FilterEffect {
public:
static FEMerge* Create(Filter*);
+ explicit FEMerge(Filter*);
+
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
int indention) const override;
private:
- explicit FEMerge(Filter*);
-
sk_sp<PaintFilter> CreateImageFilter() override;
};
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.cc
index 40842ec1d32..d8ee86f63d4 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.cc
@@ -44,7 +44,7 @@ FEMorphology* FEMorphology::Create(Filter* filter,
MorphologyOperatorType type,
float radius_x,
float radius_y) {
- return new FEMorphology(filter, type, radius_x, radius_y);
+ return MakeGarbageCollected<FEMorphology>(filter, type, radius_x, radius_y);
}
MorphologyOperatorType FEMorphology::MorphologyOperator() const {
@@ -90,8 +90,8 @@ FloatRect FEMorphology::MapEffect(const FloatRect& rect) const {
}
sk_sp<PaintFilter> FEMorphology::CreateImageFilter() {
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
int radius_x = clampTo<int>(GetFilter()->ApplyHorizontalScale(radius_x_));
int radius_y = clampTo<int>(GetFilter()->ApplyVerticalScale(radius_y_));
PaintFilter::CropRect rect = GetCropRect();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.h
index 93b7048cea9..baa3ca6f486 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_morphology.h
@@ -39,6 +39,9 @@ class PLATFORM_EXPORT FEMorphology final : public FilterEffect {
MorphologyOperatorType,
float radius_x,
float radius_y);
+
+ FEMorphology(Filter*, MorphologyOperatorType, float radius_x, float radius_y);
+
MorphologyOperatorType MorphologyOperator() const;
bool SetMorphologyOperator(MorphologyOperatorType);
@@ -52,8 +55,6 @@ class PLATFORM_EXPORT FEMorphology final : public FilterEffect {
int indention) const override;
private:
- FEMorphology(Filter*, MorphologyOperatorType, float radius_x, float radius_y);
-
FloatRect MapEffect(const FloatRect&) const override;
sk_sp<PaintFilter> CreateImageFilter() override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.cc
index 01236fda004..f5844d654d5 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.cc
@@ -35,7 +35,7 @@ FEOffset::FEOffset(Filter* filter, float dx, float dy)
: FilterEffect(filter), dx_(dx), dy_(dy) {}
FEOffset* FEOffset::Create(Filter* filter, float dx, float dy) {
- return new FEOffset(filter, dx, dy);
+ return MakeGarbageCollected<FEOffset>(filter, dx, dy);
}
float FEOffset::Dx() const {
@@ -67,7 +67,8 @@ sk_sp<PaintFilter> FEOffset::CreateImageFilter() {
return sk_make_sp<OffsetPaintFilter>(
SkFloatToScalar(filter->ApplyHorizontalScale(dx_)),
SkFloatToScalar(filter->ApplyVerticalScale(dy_)),
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()),
+ paint_filter_builder::Build(InputEffect(0),
+ OperatingInterpolationSpace()),
&crop_rect);
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.h
index 2a456246cdb..b7c1f1be49a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_offset.h
@@ -31,6 +31,8 @@ class PLATFORM_EXPORT FEOffset final : public FilterEffect {
public:
static FEOffset* Create(Filter*, float dx, float dy);
+ FEOffset(Filter*, float dx, float dy);
+
float Dx() const;
void SetDx(float);
@@ -41,8 +43,6 @@ class PLATFORM_EXPORT FEOffset final : public FilterEffect {
int indention) const override;
private:
- FEOffset(Filter*, float dx, float dy);
-
FloatRect MapEffect(const FloatRect&) const override;
sk_sp<PaintFilter> CreateImageFilter() override;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.cc
index 427ef6715ef..d2679a7a1df 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.cc
@@ -51,9 +51,9 @@ FESpecularLighting* FESpecularLighting::Create(
float specular_constant,
float specular_exponent,
scoped_refptr<LightSource> light_source) {
- return new FESpecularLighting(filter, lighting_color, surface_scale,
- specular_constant, specular_exponent,
- std::move(light_source));
+ return MakeGarbageCollected<FESpecularLighting>(
+ filter, lighting_color, surface_scale, specular_constant,
+ specular_exponent, std::move(light_source));
}
FESpecularLighting::~FESpecularLighting() = default;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.h
index da68cb2136f..e35c0e4aca8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_specular_lighting.h
@@ -35,6 +35,13 @@ class PLATFORM_EXPORT FESpecularLighting final : public FELighting {
float,
float,
scoped_refptr<LightSource>);
+
+ FESpecularLighting(Filter*,
+ const Color&,
+ float,
+ float,
+ float,
+ scoped_refptr<LightSource>);
~FESpecularLighting() override;
Color LightingColor() const;
@@ -54,14 +61,6 @@ class PLATFORM_EXPORT FESpecularLighting final : public FELighting {
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
int indention) const override;
-
- private:
- FESpecularLighting(Filter*,
- const Color&,
- float,
- float,
- float,
- scoped_refptr<LightSource>);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.cc
index 31292c463e9..70cb72261bb 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.cc
@@ -31,7 +31,7 @@ namespace blink {
FETile::FETile(Filter* filter) : FilterEffect(filter) {}
FETile* FETile::Create(Filter* filter) {
- return new FETile(filter);
+ return MakeGarbageCollected<FETile>(filter);
}
FloatRect FETile::MapInputs(const FloatRect& rect) const {
@@ -39,8 +39,8 @@ FloatRect FETile::MapInputs(const FloatRect& rect) const {
}
sk_sp<PaintFilter> FETile::CreateImageFilter() {
- sk_sp<PaintFilter> input(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> input(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
if (!input)
return nullptr;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.h
index 29c4cbf4894..1a7b7c58b7e 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_tile.h
@@ -31,12 +31,12 @@ class PLATFORM_EXPORT FETile final : public FilterEffect {
public:
static FETile* Create(Filter*);
+ FETile(Filter*);
+
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
int indention) const override;
private:
- FETile(Filter*);
-
FilterEffectType GetFilterEffectType() const override {
return kFilterEffectTypeTile;
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.cc
index da06cbabff0..05e4acf7187 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.cc
@@ -54,8 +54,9 @@ FETurbulence* FETurbulence::Create(Filter* filter,
int num_octaves,
float seed,
bool stitch_tiles) {
- return new FETurbulence(filter, type, base_frequency_x, base_frequency_y,
- num_octaves, seed, stitch_tiles);
+ return MakeGarbageCollected<FETurbulence>(filter, type, base_frequency_x,
+ base_frequency_y, num_octaves, seed,
+ stitch_tiles);
}
TurbulenceType FETurbulence::GetType() const {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.h b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.h
index 8f07b2d1b73..21ef9424edd 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/fe_turbulence.h
@@ -40,6 +40,8 @@ class PLATFORM_EXPORT FETurbulence final : public FilterEffect {
static FETurbulence*
Create(Filter*, TurbulenceType, float, float, int, float, bool);
+ FETurbulence(Filter*, TurbulenceType, float, float, int, float, bool);
+
TurbulenceType GetType() const;
bool SetType(TurbulenceType);
@@ -62,8 +64,6 @@ class PLATFORM_EXPORT FETurbulence final : public FilterEffect {
int indention) const override;
private:
- FETurbulence(Filter*, TurbulenceType, float, float, int, float, bool);
-
sk_sp<PaintFilter> CreateImageFilter() override;
TurbulenceType type_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/filter.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/filter.cc
index 3cc292d28f8..57ab7b79346 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/filter.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/filter.cc
@@ -49,11 +49,13 @@ Filter* Filter::Create(const FloatRect& reference_box,
const FloatRect& filter_region,
float scale,
UnitScaling unit_scaling) {
- return new Filter(reference_box, filter_region, scale, unit_scaling);
+ return MakeGarbageCollected<Filter>(reference_box, filter_region, scale,
+ unit_scaling);
}
Filter* Filter::Create(float scale) {
- return new Filter(FloatRect(), FloatRect(), scale, kUserSpace);
+ return MakeGarbageCollected<Filter>(FloatRect(), FloatRect(), scale,
+ kUserSpace);
}
void Filter::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/filter.h b/chromium/third_party/blink/renderer/platform/graphics/filters/filter.h
index 0eda8102d1e..ecdfd6c23c0 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/filter.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/filter.h
@@ -44,6 +44,11 @@ class PLATFORM_EXPORT Filter final : public GarbageCollected<Filter> {
UnitScaling);
static Filter* Create(float scale);
+ Filter(const FloatRect& reference_box,
+ const FloatRect& filter_region,
+ float scale,
+ UnitScaling);
+
void Trace(blink::Visitor*);
float Scale() const { return scale_; }
@@ -68,11 +73,6 @@ class PLATFORM_EXPORT Filter final : public GarbageCollected<Filter> {
SourceGraphic* GetSourceGraphic() const { return source_graphic_.Get(); }
private:
- Filter(const FloatRect& reference_box,
- const FloatRect& filter_region,
- float scale,
- UnitScaling);
-
FloatRect reference_box_;
FloatRect filter_region_;
float scale_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/filter_effect.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/filter_effect.cc
index f440f58c937..dcd2fe7b6c0 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/filter_effect.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/filter_effect.cc
@@ -104,7 +104,7 @@ void FilterEffect::DisposeImageFiltersRecursive() {
Color FilterEffect::AdaptColorToOperatingInterpolationSpace(
const Color& device_color) {
// |deviceColor| is assumed to be DeviceRGB.
- return InterpolationSpaceUtilities::ConvertColor(
+ return interpolation_space_utilities::ConvertColor(
device_color, OperatingInterpolationSpace());
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/image_filter_builder_test.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/image_filter_builder_test.cc
index 1f15afc01c3..ad4f8c730db 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/image_filter_builder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/image_filter_builder_test.cc
@@ -69,7 +69,7 @@ class ImageFilterBuilderTest : public Test {
reference_filter->SetLastEffect(merge_effect);
// Get PaintFilter resulting tree
- sk_sp<PaintFilter> filter = PaintFilterBuilder::Build(
+ sk_sp<PaintFilter> filter = paint_filter_builder::Build(
reference_filter->LastEffect(), kInterpolationSpaceSRGB);
// Let's check that the resulting tree looks like this :
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.cc
index bf0cb7aa1d2..77db2ffb4d4 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.cc
@@ -40,7 +40,7 @@
#include "third_party/skia/include/effects/SkXfermodeImageFilter.h"
namespace blink {
-namespace PaintFilterBuilder {
+namespace paint_filter_builder {
void PopulateSourceGraphicImageFilters(
FilterEffect* source_graphic,
@@ -102,7 +102,7 @@ sk_sp<PaintFilter> TransformInterpolationSpace(
InterpolationSpace src_interpolation_space,
InterpolationSpace dst_interpolation_space) {
sk_sp<SkColorFilter> color_filter =
- InterpolationSpaceUtilities::CreateInterpolationSpaceFilter(
+ interpolation_space_utilities::CreateInterpolationSpaceFilter(
src_interpolation_space, dst_interpolation_space);
if (!color_filter)
return input;
@@ -184,5 +184,5 @@ sk_sp<PaintFilter> BuildBoxReflectFilter(const BoxReflection& reflection,
std::move(input), nullptr);
}
-} // namespace PaintFilterBuilder
+} // namespace paint_filter_builder
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h
index bff2da32762..f7400e17a73 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h
@@ -37,7 +37,7 @@ class BoxReflection;
class FilterEffect;
class FloatRect;
-namespace PaintFilterBuilder {
+namespace paint_filter_builder {
PLATFORM_EXPORT sk_sp<PaintFilter> Build(
FilterEffect*,
@@ -61,7 +61,7 @@ PLATFORM_EXPORT sk_sp<PaintFilter> BuildBoxReflectFilter(
const BoxReflection&,
sk_sp<PaintFilter> input);
-} // namespace PaintFilterBuilder
+} // namespace paint_filter_builder
} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.cc
index 6686196539d..b7172f91f03 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.cc
@@ -19,7 +19,7 @@ PaintFilterEffect::~PaintFilterEffect() = default;
PaintFilterEffect* PaintFilterEffect::Create(Filter* filter,
const PaintFlags& flags) {
- return new PaintFilterEffect(filter, flags);
+ return MakeGarbageCollected<PaintFilterEffect>(filter, flags);
}
sk_sp<PaintFilter> PaintFilterEffect::CreateImageFilter() {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.h b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.h
index 599f5cc175f..5150316afbc 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/paint_filter_effect.h
@@ -13,6 +13,8 @@ namespace blink {
class PLATFORM_EXPORT PaintFilterEffect : public FilterEffect {
public:
static PaintFilterEffect* Create(Filter*, const PaintFlags&);
+
+ PaintFilterEffect(Filter*, const PaintFlags&);
~PaintFilterEffect() override;
FilterEffectType GetFilterEffectType() const override {
@@ -24,8 +26,6 @@ class PLATFORM_EXPORT PaintFilterEffect : public FilterEffect {
sk_sp<PaintFilter> CreateImageFilter() override;
private:
- PaintFilterEffect(Filter*, const PaintFlags&);
-
PaintFlags flags_;
};
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.cc
index 0d08d1eb646..4559afffd92 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.cc
@@ -30,7 +30,7 @@
namespace blink {
SourceAlpha* SourceAlpha::Create(FilterEffect* source_effect) {
- return new SourceAlpha(source_effect);
+ return MakeGarbageCollected<SourceAlpha>(source_effect);
}
SourceAlpha::SourceAlpha(FilterEffect* source_effect)
@@ -40,8 +40,8 @@ SourceAlpha::SourceAlpha(FilterEffect* source_effect)
}
sk_sp<PaintFilter> SourceAlpha::CreateImageFilter() {
- sk_sp<PaintFilter> source_graphic(
- PaintFilterBuilder::Build(InputEffect(0), OperatingInterpolationSpace()));
+ sk_sp<PaintFilter> source_graphic(paint_filter_builder::Build(
+ InputEffect(0), OperatingInterpolationSpace()));
SkScalar matrix[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, SK_Scalar1, 0};
sk_sp<SkColorFilter> color_filter =
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.h b/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.h
index 6b4cd7adc8a..499783081b5 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/source_alpha.h
@@ -29,12 +29,12 @@ class PLATFORM_EXPORT SourceAlpha final : public FilterEffect {
public:
static SourceAlpha* Create(FilterEffect*);
+ explicit SourceAlpha(FilterEffect*);
+
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
int indention) const override;
private:
- explicit SourceAlpha(FilterEffect*);
-
FilterEffectType GetFilterEffectType() const override {
return kFilterEffectTypeSourceInput;
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.cc b/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.cc
index bb5d23d7229..a4871a816c8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.cc
@@ -32,7 +32,7 @@ SourceGraphic::SourceGraphic(Filter* filter) : FilterEffect(filter) {
SourceGraphic::~SourceGraphic() = default;
SourceGraphic* SourceGraphic::Create(Filter* filter) {
- return new SourceGraphic(filter);
+ return MakeGarbageCollected<SourceGraphic>(filter);
}
FloatRect SourceGraphic::MapInputs(const FloatRect& rect) const {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.h b/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.h
index 753b71ac8e8..76cc9af4464 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/filters/source_graphic.h
@@ -30,6 +30,8 @@ namespace blink {
class PLATFORM_EXPORT SourceGraphic final : public FilterEffect {
public:
static SourceGraphic* Create(Filter*);
+
+ explicit SourceGraphic(Filter*);
~SourceGraphic() override;
WTF::TextStream& ExternalRepresentation(WTF::TextStream&,
@@ -38,8 +40,6 @@ class PLATFORM_EXPORT SourceGraphic final : public FilterEffect {
void SetSourceRect(const IntRect&);
private:
- explicit SourceGraphic(Filter*);
-
FilterEffectType GetFilterEffectType() const override {
return kFilterEffectTypeSourceInput;
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/generated_image.cc b/chromium/third_party/blink/renderer/platform/graphics/generated_image.cc
index 2db7d3e5f15..a0b90a2f1ba 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/generated_image.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/generated_image.cc
@@ -33,8 +33,8 @@
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
+#include "third_party/blink/renderer/platform/graphics/paint/paint_image.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
-#include "third_party/skia/include/core/SkImage.h"
namespace blink {
@@ -46,7 +46,7 @@ void GeneratedImage::DrawPattern(GraphicsContext& dest_context,
const FloatRect& dest_rect,
const FloatSize& repeat_spacing) {
FloatRect tile_rect = src_rect;
- tile_rect.Expand(FloatSize(repeat_spacing));
+ tile_rect.Expand(repeat_spacing);
std::unique_ptr<PaintController> paint_controller = PaintController::Create();
GraphicsContext context(*paint_controller);
@@ -58,11 +58,12 @@ void GeneratedImage::DrawPattern(GraphicsContext& dest_context,
pattern_matrix.preScale(scale.Width(), scale.Height());
pattern_matrix.preTranslate(tile_rect.X(), tile_rect.Y());
- scoped_refptr<Pattern> pattern =
- Pattern::CreatePaintRecordPattern(std::move(record), tile_rect);
+ sk_sp<PaintShader> tile_shader = PaintShader::MakePaintRecord(
+ std::move(record), tile_rect, SkShader::kRepeat_TileMode,
+ SkShader::kRepeat_TileMode, &pattern_matrix);
PaintFlags fill_flags = dest_context.FillFlags();
- pattern->ApplyToFlags(fill_flags, pattern_matrix);
+ fill_flags.setShader(std::move(tile_shader));
fill_flags.setColor(SK_ColorBLACK);
fill_flags.setBlendMode(composite_op);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/PRESUBMIT.py b/chromium/third_party/blink/renderer/platform/graphics/gpu/PRESUBMIT.py
deleted file mode 100644
index 2efada7170d..00000000000
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/PRESUBMIT.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (c) 2018 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Top-level presubmit script for third_party/blink/renderer/platform/graphics/gpu.
-
-See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
-for more details about the presubmit API built into depot_tools.
-"""
-
-
-def PostUploadHook(cl, change, output_api): # pylint: disable=C0103,W0613
- """git cl upload will call this hook after the issue is created/modified.
-
- This hook modifies the CL description in order to run extra GPU
- tests (in particular, WebXR and WebVR browser tests) in addition
- to the regular CQ try bots. This test suite is too large to run
- against all Chromium commits, but should be run against changes
- likely to affect these tests.
- """
- return output_api.EnsureCQIncludeTrybotsAreAdded(
- cl,
- ['luci.chromium.try:win_optional_gpu_tests_rel'],
- 'Automatically added optional GPU tests to run on CQ.')
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc b/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc
index 45a3ce6496e..06fd08f6f75 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer.cc
@@ -466,9 +466,15 @@ void DrawingBuffer::FinishPrepareTransferableResourceGpu(
color_buffer_for_mailbox->produce_sync_token, gfx::Size(size_),
is_overlay_candidate);
out_resource->color_space = sampler_color_space_;
- out_resource->format = viz::RGBA_8888;
- if (use_half_float_storage_)
- out_resource->format = viz::RGBA_F16;
+ if (allocate_alpha_channel_) {
+ if (use_half_float_storage_)
+ out_resource->format = viz::RGBA_F16;
+ else
+ out_resource->format = viz::RGBA_8888;
+ } else {
+ DCHECK(!use_half_float_storage_);
+ out_resource->format = viz::RGBX_8888;
+ }
// This holds a ref on the DrawingBuffer that will keep it alive until the
// mailbox is released (and while the release callback is running).
@@ -711,7 +717,9 @@ bool DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) {
webgl_preferences.max_active_webgl_contexts_on_worker;
int max_sample_count = 0;
- gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count);
+ if (use_multisampling) {
+ gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count);
+ }
if (webgl_preferences.anti_aliasing_mode ==
gpu::kAntialiasingModeUnspecified) {
if (use_multisampling) {
@@ -727,7 +735,6 @@ bool DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) {
}
} else {
anti_aliasing_mode_ = gpu::kAntialiasingModeNone;
- max_sample_count = 0;
}
} else {
if ((webgl_preferences.anti_aliasing_mode ==
@@ -1414,25 +1421,25 @@ scoped_refptr<DrawingBuffer::ColorBuffer> DrawingBuffer::CreateColorBuffer(
Platform::Current()->GetGpuMemoryBufferManager();
if (ShouldUseChromiumImage()) {
gfx::BufferFormat buffer_format;
- GLenum gl_format = GL_NONE;
if (allocate_alpha_channel_) {
buffer_format = use_half_float_storage_ ? gfx::BufferFormat::RGBA_F16
: gfx::BufferFormat::RGBA_8888;
- gl_format = GL_RGBA;
} else {
DCHECK(!use_half_float_storage_);
buffer_format = gfx::BufferFormat::RGBX_8888;
if (gpu::IsImageFromGpuMemoryBufferFormatSupported(
gfx::BufferFormat::BGRX_8888,
- ContextProvider()->GetCapabilities()))
+ ContextProvider()->GetCapabilities())) {
buffer_format = gfx::BufferFormat::BGRX_8888;
- gl_format = GL_RGB;
+ }
}
gpu_memory_buffer = gpu_memory_buffer_manager->CreateGpuMemoryBuffer(
gfx::Size(size), buffer_format, gfx::BufferUsage::SCANOUT,
gpu::kNullSurfaceHandle);
if (gpu_memory_buffer) {
gpu_memory_buffer->SetColorSpace(storage_color_space_);
+ const GLenum gl_format = allocate_alpha_channel_ ? GL_RGBA : GL_RGB;
+
image_id =
gl_->CreateImageCHROMIUM(gpu_memory_buffer->AsClientBuffer(),
size.Width(), size.Height(), gl_format);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc b/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc
index c5f07c6736e..2fdde120800 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test.cc
@@ -42,8 +42,8 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
#include "third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h"
+#include "third_party/blink/renderer/platform/graphics/test/gpu_memory_buffer_test_platform.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "v8/include/v8.h"
using testing::Test;
@@ -51,19 +51,6 @@ using testing::_;
namespace blink {
-namespace {
-
-class FakePlatformSupport : public TestingPlatformSupport {
- gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override {
- return &test_gpu_memory_buffer_manager_;
- }
-
- private:
- viz::TestGpuMemoryBufferManager test_gpu_memory_buffer_manager_;
-};
-
-} // anonymous namespace
-
class DrawingBufferTest : public Test {
protected:
void SetUp() override { Init(kDisableMultisampling); }
@@ -394,7 +381,8 @@ class DrawingBufferImageChromiumTest : public DrawingBufferTest,
protected:
void SetUp() override {
- platform_.reset(new ScopedTestingPlatformSupport<FakePlatformSupport>);
+ platform_.reset(
+ new ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform>);
IntSize initial_size(kInitialWidth, kInitialHeight);
auto gl = std::make_unique<GLES2InterfaceForTests>();
@@ -418,7 +406,8 @@ class DrawingBufferImageChromiumTest : public DrawingBufferTest,
}
GLuint image_id0_;
- std::unique_ptr<ScopedTestingPlatformSupport<FakePlatformSupport>> platform_;
+ std::unique_ptr<ScopedTestingPlatformSupport<GpuMemoryBufferTestPlatform>>
+ platform_;
};
TEST_F(DrawingBufferImageChromiumTest, VerifyResizingReallocatesImages) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h b/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h
index 7f39cc947d5..d5e83b84fd6 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h
@@ -53,7 +53,9 @@ class WebGraphicsContext3DProviderForTests
void SetLostContextCallback(base::Closure) override {}
void SetErrorMessageCallback(
base::RepeatingCallback<void(const char*, int32_t id)>) override {}
- cc::ImageDecodeCache* ImageDecodeCache(SkColorType) override {
+ cc::ImageDecodeCache* ImageDecodeCache(
+ SkColorType color_type,
+ sk_sp<SkColorSpace> color_space) override {
return &image_decode_cache_;
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.cc b/chromium/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.cc
index d2b1712d885..4ef2065bbb3 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.cc
@@ -11,9 +11,9 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
@@ -124,7 +124,7 @@ void SharedGpuContext::CreateContextProviderIfNeeded(
// this once per thread.
WaitableEvent waitable_event;
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
- Platform::Current()->MainThread()->GetTaskRunner();
+ Thread::MainThread()->GetTaskRunner();
PostCrossThreadTask(
*task_runner, FROM_HERE,
CrossThreadBind(&CreateContextProviderOnMainThread,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/webgl_image_conversion.cc b/chromium/third_party/blink/renderer/platform/graphics/gpu/webgl_image_conversion.cc
index 4631eb4eff0..6ad59bb2a61 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/webgl_image_conversion.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/gpu/webgl_image_conversion.cc
@@ -446,11 +446,11 @@ void Unpack<WebGLImageConversion::kDataFormatBGRA8, uint8_t, uint8_t>(
uint32_t* destination32 = reinterpret_cast_ptr<uint32_t*>(destination);
#if defined(ARCH_CPU_X86_FAMILY)
- SIMD::UnpackOneRowOfBGRA8LittleToRGBA8(source32, destination32,
+ simd::UnpackOneRowOfBGRA8LittleToRGBA8(source32, destination32,
pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::unpackOneRowOfBGRA8LittleToRGBA8MSA(source32, destination32,
+ simd::unpackOneRowOfBGRA8LittleToRGBA8MSA(source32, destination32,
pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
@@ -474,14 +474,14 @@ void Unpack<WebGLImageConversion::kDataFormatRGBA5551, uint16_t, uint8_t>(
uint8_t* destination,
unsigned pixels_per_row) {
#if defined(ARCH_CPU_X86_FAMILY)
- SIMD::UnpackOneRowOfRGBA5551LittleToRGBA8(source, destination,
+ simd::UnpackOneRowOfRGBA5551LittleToRGBA8(source, destination,
pixels_per_row);
#endif
#if WTF_CPU_ARM_NEON
- SIMD::UnpackOneRowOfRGBA5551ToRGBA8(source, destination, pixels_per_row);
+ simd::UnpackOneRowOfRGBA5551ToRGBA8(source, destination, pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::unpackOneRowOfRGBA5551ToRGBA8MSA(source, destination, pixels_per_row);
+ simd::unpackOneRowOfRGBA5551ToRGBA8MSA(source, destination, pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
@@ -504,14 +504,14 @@ void Unpack<WebGLImageConversion::kDataFormatRGBA4444, uint16_t, uint8_t>(
uint8_t* destination,
unsigned pixels_per_row) {
#if defined(ARCH_CPU_X86_FAMILY)
- SIMD::UnpackOneRowOfRGBA4444LittleToRGBA8(source, destination,
+ simd::UnpackOneRowOfRGBA4444LittleToRGBA8(source, destination,
pixels_per_row);
#endif
#if WTF_CPU_ARM_NEON
- SIMD::UnpackOneRowOfRGBA4444ToRGBA8(source, destination, pixels_per_row);
+ simd::UnpackOneRowOfRGBA4444ToRGBA8(source, destination, pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::unpackOneRowOfRGBA4444ToRGBA8MSA(source, destination, pixels_per_row);
+ simd::unpackOneRowOfRGBA4444ToRGBA8MSA(source, destination, pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
uint16_t packed_value = source[0];
@@ -720,10 +720,10 @@ void Pack<WebGLImageConversion::kDataFormatR8,
uint8_t* destination,
unsigned pixels_per_row) {
#if defined(ARCH_CPU_X86_FAMILY)
- SIMD::PackOneRowOfRGBA8LittleToR8(source, destination, pixels_per_row);
+ simd::PackOneRowOfRGBA8LittleToR8(source, destination, pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::packOneRowOfRGBA8LittleToR8MSA(source, destination, pixels_per_row);
+ simd::packOneRowOfRGBA8LittleToR8MSA(source, destination, pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
float scale_factor = source[3] ? 255.0f / source[3] : 1.0f;
@@ -777,10 +777,10 @@ void Pack<WebGLImageConversion::kDataFormatRA8,
uint8_t* destination,
unsigned pixels_per_row) {
#if defined(ARCH_CPU_X86_FAMILY)
- SIMD::PackOneRowOfRGBA8LittleToRA8(source, destination, pixels_per_row);
+ simd::PackOneRowOfRGBA8LittleToRA8(source, destination, pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::packOneRowOfRGBA8LittleToRA8MSA(source, destination, pixels_per_row);
+ simd::packOneRowOfRGBA8LittleToRA8MSA(source, destination, pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
float scale_factor = source[3] ? 255.0f / source[3] : 1.0f;
@@ -889,10 +889,10 @@ void Pack<WebGLImageConversion::kDataFormatRGBA8,
uint8_t* destination,
unsigned pixels_per_row) {
#if defined(ARCH_CPU_X86_FAMILY)
- SIMD::PackOneRowOfRGBA8LittleToRGBA8(source, destination, pixels_per_row);
+ simd::PackOneRowOfRGBA8LittleToRGBA8(source, destination, pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::packOneRowOfRGBA8LittleToRGBA8MSA(source, destination, pixels_per_row);
+ simd::packOneRowOfRGBA8LittleToRGBA8MSA(source, destination, pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
float scale_factor = source[3] ? 255.0f / source[3] : 1.0f;
@@ -919,11 +919,11 @@ void Pack<WebGLImageConversion::kDataFormatRGBA4444,
uint16_t* destination,
unsigned pixels_per_row) {
#if WTF_CPU_ARM_NEON
- SIMD::PackOneRowOfRGBA8ToUnsignedShort4444(source, destination,
+ simd::PackOneRowOfRGBA8ToUnsignedShort4444(source, destination,
pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::packOneRowOfRGBA8ToUnsignedShort4444MSA(source, destination,
+ simd::packOneRowOfRGBA8ToUnsignedShort4444MSA(source, destination,
pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
@@ -987,11 +987,11 @@ void Pack<WebGLImageConversion::kDataFormatRGBA5551,
uint16_t* destination,
unsigned pixels_per_row) {
#if WTF_CPU_ARM_NEON
- SIMD::PackOneRowOfRGBA8ToUnsignedShort5551(source, destination,
+ simd::PackOneRowOfRGBA8ToUnsignedShort5551(source, destination,
pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::packOneRowOfRGBA8ToUnsignedShort5551MSA(source, destination,
+ simd::packOneRowOfRGBA8ToUnsignedShort5551MSA(source, destination,
pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
@@ -1055,11 +1055,11 @@ void Pack<WebGLImageConversion::kDataFormatRGB565,
uint16_t* destination,
unsigned pixels_per_row) {
#if WTF_CPU_ARM_NEON
- SIMD::PackOneRowOfRGBA8ToUnsignedShort565(source, destination,
+ simd::PackOneRowOfRGBA8ToUnsignedShort565(source, destination,
pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
- SIMD::packOneRowOfRGBA8ToUnsignedShort565MSA(source, destination,
+ simd::packOneRowOfRGBA8ToUnsignedShort565MSA(source, destination,
pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gpu/xr_webgl_drawing_buffer.h b/chromium/third_party/blink/renderer/platform/graphics/gpu/xr_webgl_drawing_buffer.h
index 3003a125de1..919566a74f6 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gpu/xr_webgl_drawing_buffer.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/gpu/xr_webgl_drawing_buffer.h
@@ -69,7 +69,7 @@ class PLATFORM_EXPORT XRWebGLDrawingBuffer
void BeginDestruction();
private:
- struct ColorBuffer : public RefCounted<ColorBuffer> {
+ struct PLATFORM_EXPORT ColorBuffer : public RefCounted<ColorBuffer> {
ColorBuffer(XRWebGLDrawingBuffer*, const IntSize&, GLuint texture_id);
~ColorBuffer();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gradient.cc b/chromium/third_party/blink/renderer/platform/graphics/gradient.cc
index 745999aee35..90b8990bb9f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gradient.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/gradient.cc
@@ -42,10 +42,12 @@ namespace blink {
Gradient::Gradient(Type type,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation)
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling)
: type_(type),
spread_method_(spread_method),
color_interpolation_(interpolation),
+ degenerate_handling_(degenerate_handling),
stops_sorted_(true) {}
Gradient::~Gradient() = default;
@@ -187,8 +189,12 @@ class LinearGradient final : public Gradient {
LinearGradient(const FloatPoint& p0,
const FloatPoint& p1,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation)
- : Gradient(Type::kLinear, spread_method, interpolation),
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling)
+ : Gradient(Type::kLinear,
+ spread_method,
+ interpolation,
+ degenerate_handling),
p0_(p0),
p1_(p1) {}
@@ -199,6 +205,11 @@ class LinearGradient final : public Gradient {
uint32_t flags,
const SkMatrix& local_matrix,
SkColor fallback_color) const override {
+ if (GetDegenerateHandling() == DegenerateHandling::kDisallow &&
+ p0_ == p1_) {
+ return PaintShader::MakeEmpty();
+ }
+
SkPoint pts[2] = {FloatPointToSkPoint(p0_), FloatPointToSkPoint(p1_)};
return PaintShader::MakeLinearGradient(
pts, colors.data(), pos.data(), static_cast<int>(colors.size()),
@@ -218,8 +229,12 @@ class RadialGradient final : public Gradient {
float r1,
float aspect_ratio,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation)
- : Gradient(Type::kRadial, spread_method, interpolation),
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling)
+ : Gradient(Type::kRadial,
+ spread_method,
+ interpolation,
+ degenerate_handling),
p0_(p0),
p1_(p1),
r0_(r0),
@@ -248,6 +263,12 @@ class RadialGradient final : public Gradient {
// negative radius, ask for zero instead.
const SkScalar radius0 = std::max(WebCoreFloatToSkScalar(r0_), 0.0f);
const SkScalar radius1 = std::max(WebCoreFloatToSkScalar(r1_), 0.0f);
+
+ if (GetDegenerateHandling() == DegenerateHandling::kDisallow &&
+ p0_ == p1_ && radius0 == radius1) {
+ return PaintShader::MakeEmpty();
+ }
+
return PaintShader::MakeTwoPointConicalGradient(
FloatPointToSkPoint(p0_), radius0, FloatPointToSkPoint(p1_), radius1,
colors.data(), pos.data(), static_cast<int>(colors.size()), tile_mode,
@@ -269,8 +290,12 @@ class ConicGradient final : public Gradient {
float start_angle,
float end_angle,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation)
- : Gradient(Type::kConic, spread_method, interpolation),
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling)
+ : Gradient(Type::kConic,
+ spread_method,
+ interpolation,
+ degenerate_handling),
position_(position),
rotation_(rotation),
start_angle_(start_angle),
@@ -283,6 +308,11 @@ class ConicGradient final : public Gradient {
uint32_t flags,
const SkMatrix& local_matrix,
SkColor fallback_color) const override {
+ if (GetDegenerateHandling() == DegenerateHandling::kDisallow &&
+ start_angle_ == end_angle_) {
+ return PaintShader::MakeEmpty();
+ }
+
// Skia's sweep gradient angles are relative to the x-axis, not the y-axis.
const float skia_rotation = rotation_ - 90;
const SkMatrix* matrix = &local_matrix;
@@ -313,9 +343,10 @@ scoped_refptr<Gradient> Gradient::CreateLinear(
const FloatPoint& p0,
const FloatPoint& p1,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation) {
- return base::AdoptRef(
- new LinearGradient(p0, p1, spread_method, interpolation));
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling) {
+ return base::AdoptRef(new LinearGradient(p0, p1, spread_method, interpolation,
+ degenerate_handling));
}
scoped_refptr<Gradient> Gradient::CreateRadial(
@@ -325,9 +356,11 @@ scoped_refptr<Gradient> Gradient::CreateRadial(
float r1,
float aspect_ratio,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation) {
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling) {
return base::AdoptRef(new RadialGradient(p0, r0, p1, r1, aspect_ratio,
- spread_method, interpolation));
+ spread_method, interpolation,
+ degenerate_handling));
}
scoped_refptr<Gradient> Gradient::CreateConic(
@@ -336,10 +369,11 @@ scoped_refptr<Gradient> Gradient::CreateConic(
float start_angle,
float end_angle,
GradientSpreadMethod spread_method,
- ColorInterpolation interpolation) {
+ ColorInterpolation interpolation,
+ DegenerateHandling degenerate_handling) {
return base::AdoptRef(new ConicGradient(position, rotation, start_angle,
end_angle, spread_method,
- interpolation));
+ interpolation, degenerate_handling));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/gradient.h b/chromium/third_party/blink/renderer/platform/graphics/gradient.h
index 92e88432b2b..d158edbe6a9 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/gradient.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/gradient.h
@@ -57,11 +57,17 @@ class PLATFORM_EXPORT Gradient : public RefCounted<Gradient> {
kUnpremultiplied,
};
+ enum class DegenerateHandling {
+ kAllow,
+ kDisallow,
+ };
+
static scoped_refptr<Gradient> CreateLinear(
const FloatPoint& p0,
const FloatPoint& p1,
GradientSpreadMethod = kSpreadMethodPad,
- ColorInterpolation = ColorInterpolation::kUnpremultiplied);
+ ColorInterpolation = ColorInterpolation::kUnpremultiplied,
+ DegenerateHandling = DegenerateHandling::kAllow);
static scoped_refptr<Gradient> CreateRadial(
const FloatPoint& p0,
@@ -70,7 +76,8 @@ class PLATFORM_EXPORT Gradient : public RefCounted<Gradient> {
float r1,
float aspect_ratio = 1,
GradientSpreadMethod = kSpreadMethodPad,
- ColorInterpolation = ColorInterpolation::kUnpremultiplied);
+ ColorInterpolation = ColorInterpolation::kUnpremultiplied,
+ DegenerateHandling = DegenerateHandling::kAllow);
static scoped_refptr<Gradient> CreateConic(
const FloatPoint& position,
@@ -78,7 +85,8 @@ class PLATFORM_EXPORT Gradient : public RefCounted<Gradient> {
float start_angle,
float end_angle,
GradientSpreadMethod = kSpreadMethodPad,
- ColorInterpolation = ColorInterpolation::kUnpremultiplied);
+ ColorInterpolation = ColorInterpolation::kUnpremultiplied,
+ DegenerateHandling = DegenerateHandling::kAllow);
virtual ~Gradient();
@@ -100,7 +108,7 @@ class PLATFORM_EXPORT Gradient : public RefCounted<Gradient> {
void ApplyToFlags(PaintFlags&, const SkMatrix& local_matrix);
protected:
- Gradient(Type, GradientSpreadMethod, ColorInterpolation);
+ Gradient(Type, GradientSpreadMethod, ColorInterpolation, DegenerateHandling);
using ColorBuffer = Vector<SkColor, 8>;
using OffsetBuffer = Vector<SkScalar, 8>;
@@ -111,6 +119,10 @@ class PLATFORM_EXPORT Gradient : public RefCounted<Gradient> {
const SkMatrix&,
SkColor) const = 0;
+ DegenerateHandling GetDegenerateHandling() const {
+ return degenerate_handling_;
+ }
+
private:
sk_sp<PaintShader> CreateShaderInternal(const SkMatrix& local_matrix);
@@ -122,6 +134,7 @@ class PLATFORM_EXPORT Gradient : public RefCounted<Gradient> {
const Type type_;
const GradientSpreadMethod spread_method_;
const ColorInterpolation color_interpolation_;
+ const DegenerateHandling degenerate_handling_;
Vector<ColorStop, 2> stops_;
bool stops_sorted_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/graphics_context.cc b/chromium/third_party/blink/renderer/platform/graphics/graphics_context.cc
index 7661ef3c2f3..0f9141b2e29 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/graphics_context.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/graphics_context.cc
@@ -1390,10 +1390,10 @@ sk_sp<SkColorFilter> GraphicsContext::WebCoreColorFilterToSkiaColorFilter(
case kColorFilterLuminanceToAlpha:
return SkLumaColorFilter::Make();
case kColorFilterLinearRGBToSRGB:
- return InterpolationSpaceUtilities::CreateInterpolationSpaceFilter(
+ return interpolation_space_utilities::CreateInterpolationSpaceFilter(
kInterpolationSpaceLinear, kInterpolationSpaceSRGB);
case kColorFilterSRGBToLinearRGB:
- return InterpolationSpaceUtilities::CreateInterpolationSpaceFilter(
+ return interpolation_space_utilities::CreateInterpolationSpaceFilter(
kInterpolationSpaceSRGB, kInterpolationSpaceLinear);
case kColorFilterNone:
break;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.cc b/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.cc
index a7523363379..5a8572622a4 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.cc
@@ -31,7 +31,7 @@
#include <utility>
#include "base/memory/ptr_util.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "cc/layers/layer.h"
#include "cc/layers/picture_image_layer.h"
#include "cc/layers/picture_layer.h"
@@ -241,7 +241,12 @@ void GraphicsLayer::RemoveFromParent() {
SetParent(nullptr);
}
- CcLayer()->RemoveFromParent();
+ // When using layer lists, cc::Layers are created and removed in
+ // PaintArtifactCompositor.
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ CcLayer()->RemoveFromParent();
+ }
}
void GraphicsLayer::SetOffsetFromLayoutObject(const IntSize& offset) {
@@ -377,7 +382,11 @@ bool GraphicsLayer::PaintWithoutCommit(
}
void GraphicsLayer::UpdateChildList() {
- // TODO(pdr): Do not attach cc::Layers when using layer lists.
+ // When using layer lists, cc::Layers are created in PaintArtifactCompositor.
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
+ RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ return;
+ }
cc::Layer* child_host = layer_.get();
child_host->RemoveAllChildren();
@@ -515,7 +524,10 @@ void GraphicsLayer::SetupContentsLayer(cc::Layer* contents_layer) {
// Insert the content layer first. Video elements require this, because they
// have shadow content that must display in front of the video.
- CcLayer()->InsertChild(contents_layer_, 0);
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ !RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ CcLayer()->InsertChild(contents_layer_, 0);
+ }
cc::PictureLayer* border_cc_layer =
contents_clipping_mask_layer_ ? contents_clipping_mask_layer_->CcLayer()
: nullptr;
@@ -909,7 +921,7 @@ void GraphicsLayer::SetFilters(CompositorFilterOperations filters) {
}
void GraphicsLayer::SetBackdropFilters(CompositorFilterOperations filters) {
- CcLayer()->SetBackgroundFilters(filters.ReleaseCcFilterOperations());
+ CcLayer()->SetBackdropFilters(filters.ReleaseCcFilterOperations());
}
void GraphicsLayer::SetStickyPositionConstraint(
@@ -1010,27 +1022,44 @@ sk_sp<PaintRecord> GraphicsLayer::CapturePaintRecord() const {
void GraphicsLayer::SetLayerState(const PropertyTreeState& layer_state,
const IntPoint& layer_offset) {
- if (!layer_state_) {
+ DCHECK(layer_state.Transform() && layer_state.Clip() && layer_state.Effect());
+
+ if (layer_state_) {
+ layer_state_->state = layer_state;
+ layer_state_->offset = layer_offset;
+ } else {
layer_state_ =
std::make_unique<LayerState>(LayerState{layer_state, layer_offset});
- return;
}
- layer_state_->state = layer_state;
- layer_state_->offset = layer_offset;
- CHECK(layer_state_->state.Transform() && layer_state_->state.Clip() &&
- layer_state_->state.Effect());
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
+ CcLayer()->SetOffsetToTransformParent(
+ gfx::Vector2dF(layer_offset.X(), layer_offset.Y()));
+
+ if (!contents_layer_state_ && ContentsLayer()) {
+ ContentsLayer()->SetOffsetToTransformParent(
+ gfx::Vector2dF(layer_offset.X(), layer_offset.Y()));
+ }
+ }
}
void GraphicsLayer::SetContentsLayerState(const PropertyTreeState& layer_state,
const IntPoint& layer_offset) {
- if (!contents_layer_state_) {
+ DCHECK(layer_state.Transform() && layer_state.Clip() && layer_state.Effect());
+ DCHECK(ContentsLayer());
+
+ if (contents_layer_state_) {
+ contents_layer_state_->state = layer_state;
+ contents_layer_state_->offset = layer_offset;
+ } else {
contents_layer_state_ =
std::make_unique<LayerState>(LayerState{layer_state, layer_offset});
- return;
}
- contents_layer_state_->state = layer_state;
- contents_layer_state_->offset = layer_offset;
+
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
+ ContentsLayer()->SetOffsetToTransformParent(
+ gfx::Vector2dF(layer_offset.X(), layer_offset.Y()));
+ }
}
scoped_refptr<cc::DisplayItemList> GraphicsLayer::PaintContentsToDisplayList(
diff --git a/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.h b/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.h
index dd43884ff50..954f933c69e 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/graphics_layer.h
@@ -34,6 +34,7 @@
#include "cc/input/overscroll_behavior.h"
#include "cc/input/scroll_snap_data.h"
#include "cc/layers/content_layer_client.h"
+#include "cc/layers/layer.h"
#include "cc/layers/layer_client.h"
#include "cc/layers/layer_sticky_position_constraint.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
@@ -59,7 +60,6 @@
#include "third_party/skia/include/core/SkRefCnt.h"
namespace cc {
-class Layer;
class PictureImageLayer;
class PictureLayer;
}
@@ -250,8 +250,6 @@ class PLATFORM_EXPORT GraphicsLayer : public cc::LayerClient,
int GetRenderingContext3D() const { return rendering_context3d_; }
- cc::PictureLayer* ContentLayer() const { return layer_.get(); }
-
static void RegisterContentsLayer(cc::Layer*);
static void UnregisterContentsLayer(cc::Layer*);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/graphics_layer_test.cc b/chromium/third_party/blink/renderer/platform/graphics/graphics_layer_test.cc
index 9d11f2086a2..e79095e8fbf 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/graphics_layer_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/graphics_layer_test.cc
@@ -139,8 +139,11 @@ TEST_P(GraphicsLayerTest, PaintRecursively) {
layers_.graphics_layer_client().SetNeedsRepaint(true);
layers_.graphics_layer().PaintRecursively();
- EXPECT_FALSE(transform1->Changed(transform_root));
- EXPECT_FALSE(transform2->Changed(transform_root));
+ // With BlinkGenPropertyTrees, these are not cleared until after paint.
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
+ EXPECT_FALSE(transform1->Changed(transform_root));
+ EXPECT_FALSE(transform2->Changed(transform_root));
+ }
}
TEST_P(GraphicsLayerTest, SetDrawsContentFalse) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/high_contrast_image_classifier_test.cc b/chromium/third_party/blink/renderer/platform/graphics/high_contrast_image_classifier_test.cc
index e225f5e3309..951146cbab7 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/high_contrast_image_classifier_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/high_contrast_image_classifier_test.cc
@@ -43,7 +43,7 @@ class HighContrastImageClassifierTest : public testing::Test {
protected:
scoped_refptr<BitmapImage> LoadImage(const std::string& file_name) {
- String file_path = test::BlinkLayoutTestsDir();
+ String file_path = test::BlinkWebTestsDir();
file_path.append(file_name.c_str());
scoped_refptr<SharedBuffer> image_data = test::ReadFromFile(file_path);
EXPECT_TRUE(image_data.get() && image_data.get()->size());
diff --git a/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.cc b/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.cc
index 4424ffbd635..34bc9cad298 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.cc
@@ -7,6 +7,7 @@
#include "base/containers/flat_map.h"
#include "cc/base/region.h"
#include "cc/layers/touch_action_region.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -34,4 +35,13 @@ LayoutRect HitTestRect::GetBounds(const Vector<HitTestRect>& hit_test_rects) {
return LayoutRect(IntRect(rect));
}
+String HitTestRect::ToString() const {
+ // TODO(pdr): Print the value of |whitelisted_touch_action|.
+ return rect.ToString();
+}
+
+std::ostream& operator<<(std::ostream& os, const HitTestRect& hit_test_rect) {
+ return os << hit_test_rect.ToString();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.h b/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.h
index e8c23d59214..90d2fd7ed30 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/hit_test_rect.h
@@ -40,10 +40,14 @@ struct PLATFORM_EXPORT HitTestRect {
}
bool operator!=(const HitTestRect& rhs) const { return !(*this == rhs); }
+
+ String ToString() const;
};
using LayerHitTestRects = WTF::HashMap<const PaintLayer*, Vector<HitTestRect>>;
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, const HitTestRect&);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_HIT_TEST_RECT_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/image.cc b/chromium/third_party/blink/renderer/platform/graphics/image.cc
index dcb853f240a..4b07a4b2fdc 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/image.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/image.cc
@@ -35,6 +35,7 @@
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/deferred_image_decoder.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
@@ -43,9 +44,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_shader.h"
#include "third_party/blink/renderer/platform/graphics/scoped_interpolation_quality.h"
#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/length.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -56,6 +55,35 @@
namespace blink {
+class CombinedImageDecodeCache {
+ public:
+ CombinedImageDecodeCache(size_t locked_memory_limit_bytes)
+ : locked_memory_limit_bytes_(locked_memory_limit_bytes) {
+ constexpr int kMaxIndex =
+ (kMaxCanvasPixelFormat + 1) * (kMaxCanvasColorSpace + 1);
+ decode_caches_.resize(kMaxIndex);
+ }
+
+ cc::ImageDecodeCache* GetCache(CanvasColorSpace color_space,
+ CanvasPixelFormat pixel_format) {
+ base::AutoLock lock(lock_);
+ int index = (kMaxCanvasColorSpace + 1) * pixel_format + color_space;
+ if (!decode_caches_[index]) {
+ decode_caches_[index] = std::make_unique<cc::SoftwareImageDecodeCache>(
+ CanvasColorParams::PixelFormatToSkColorType(pixel_format),
+ locked_memory_limit_bytes_, PaintImage::kDefaultGeneratorClientId,
+ blink::CanvasColorParams::CanvasColorSpaceToSkColorSpace(
+ color_space));
+ }
+ return decode_caches_[index].get();
+ }
+
+ private:
+ std::vector<std::unique_ptr<cc::SoftwareImageDecodeCache>> decode_caches_;
+ const size_t locked_memory_limit_bytes_;
+ base::Lock lock_;
+};
+
Image::Image(ImageObserver* observer, bool is_multipart)
: image_observer_disabled_(false),
image_observer_(observer),
@@ -73,24 +101,16 @@ Image* Image::NullImage() {
}
// static
-cc::ImageDecodeCache& Image::SharedCCDecodeCache(SkColorType color_type) {
+cc::ImageDecodeCache* Image::SharedCCDecodeCache(
+ CanvasColorSpace color_space,
+ CanvasPixelFormat pixel_format) {
// This denotes the allocated locked memory budget for the cache used for
// book-keeping. The cache indicates when the total memory locked exceeds this
// budget in cc::DecodedDrawImage.
- DCHECK(color_type == kN32_SkColorType || color_type == kRGBA_F16_SkColorType);
static const size_t kLockedMemoryLimitBytes = 64 * 1024 * 1024;
- if (color_type == kRGBA_F16_SkColorType) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- cc::SoftwareImageDecodeCache, image_decode_cache,
- (kRGBA_F16_SkColorType, kLockedMemoryLimitBytes,
- PaintImage::kDefaultGeneratorClientId));
- return image_decode_cache;
- }
- DEFINE_THREAD_SAFE_STATIC_LOCAL(cc::SoftwareImageDecodeCache,
- image_decode_cache,
- (kN32_SkColorType, kLockedMemoryLimitBytes,
- PaintImage::kDefaultGeneratorClientId));
- return image_decode_cache;
+ DEFINE_THREAD_SAFE_STATIC_LOCAL(CombinedImageDecodeCache, combined_cache,
+ (kLockedMemoryLimitBytes));
+ return combined_cache.GetCache(color_space, pixel_format);
}
scoped_refptr<Image> Image::LoadPlatformResource(const char* name) {
@@ -388,8 +408,11 @@ void Image::DrawPattern(GraphicsContext& context,
context.DrawRect(dest_rect, flags);
- if (CurrentFrameIsLazyDecoded())
- PlatformInstrumentation::DidDrawLazyPixelRef(image_id);
+ if (CurrentFrameIsLazyDecoded()) {
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
+ "Draw LazyPixelRef", TRACE_EVENT_SCOPE_THREAD,
+ "LazyPixelRef", image_id);
+ }
}
scoped_refptr<Image> Image::ImageForDefaultFrame() {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/image.h b/chromium/third_party/blink/renderer/platform/graphics/image.h
index 71e5ea21a2e..490c63fe13c 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/image.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/image.h
@@ -31,6 +31,7 @@
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/graphics/image_animation_policy.h"
#include "third_party/blink/renderer/platform/graphics/image_observer.h"
@@ -73,7 +74,9 @@ class PLATFORM_EXPORT Image : public ThreadSafeRefCounted<Image> {
public:
virtual ~Image();
- static cc::ImageDecodeCache& SharedCCDecodeCache(SkColorType);
+ static cc::ImageDecodeCache* SharedCCDecodeCache(
+ CanvasColorSpace color_space,
+ CanvasPixelFormat pixel_format);
static scoped_refptr<Image> LoadPlatformResource(const char* name);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.cc b/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.cc
index 0b3c8d3cf11..5fb66875b85 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.cc
@@ -34,21 +34,22 @@
#include "third_party/blink/renderer/platform/graphics/image_decoding_store.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/skia/include/core/SkYUVSizeInfo.h"
+#include "third_party/skia/include/core/SkYUVASizeInfo.h"
namespace blink {
static bool UpdateYUVComponentSizes(ImageDecoder* decoder,
- SkISize component_sizes[3],
- size_t component_width_bytes[3]) {
- if (!decoder->CanDecodeToYUV())
- return false;
+ SkISize component_sizes[4],
+ size_t component_width_bytes[4]) {
+ DCHECK(decoder->CanDecodeToYUV());
for (int yuv_index = 0; yuv_index < 3; ++yuv_index) {
IntSize size = decoder->DecodedYUVSize(yuv_index);
component_sizes[yuv_index].set(size.Width(), size.Height());
component_width_bytes[yuv_index] = decoder->DecodedYUVWidthBytes(yuv_index);
}
+ component_sizes[3] = SkISize::MakeEmpty();
+ component_width_bytes[3] = 0;
return true;
}
@@ -149,6 +150,7 @@ bool ImageFrameGenerator::DecodeToYUV(SegmentReader* data,
void* planes[3],
const size_t row_bytes[3]) {
MutexLocker lock(generator_mutex_);
+ DCHECK_EQ(index, 0u);
// TODO (scroggo): The only interesting thing this uses from the
// ImageFrameGenerator is m_decodeFailed. Move this into
@@ -209,7 +211,7 @@ bool ImageFrameGenerator::HasAlpha(size_t index) {
}
bool ImageFrameGenerator::GetYUVComponentSizes(SegmentReader* data,
- SkYUVSizeInfo* size_info) {
+ SkYUVASizeInfo* size_info) {
TRACE_EVENT2("blink", "ImageFrameGenerator::getYUVComponentSizes", "width",
full_size_.width(), "height", full_size_.height());
diff --git a/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.h b/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.h
index 593722cf6c5..9951c2ca24a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator.h
@@ -42,8 +42,7 @@
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkTypes.h"
-
-struct SkYUVSizeInfo;
+#include "third_party/skia/include/core/SkYUVASizeInfo.h"
namespace blink {
@@ -112,7 +111,7 @@ class PLATFORM_EXPORT ImageFrameGenerator final
// Must not be called unless the SkROBuffer has all the data. YUV decoding
// does not currently support progressive decoding. See comment above on
// decodeToYUV().
- bool GetYUVComponentSizes(SegmentReader*, SkYUVSizeInfo*);
+ bool GetYUVComponentSizes(SegmentReader*, SkYUVASizeInfo*);
private:
class ClientMutexLocker {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator_test.cc b/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator_test.cc
index 4c2c7410aa3..ba596337c05 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/image_frame_generator_test.cc
@@ -33,10 +33,10 @@
#include "third_party/blink/renderer/platform/graphics/image_decoding_store.h"
#include "third_party/blink/renderer/platform/graphics/test/mock_image_decoder.h"
#include "third_party/blink/renderer/platform/image-decoders/segment_reader.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/image_observer.h b/chromium/third_party/blink/renderer/platform/graphics/image_observer.h
index 38db5dcd099..db0a5275b0a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/image_observer.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/image_observer.h
@@ -43,7 +43,6 @@ class PLATFORM_EXPORT ImageObserver : public GarbageCollectedMixin {
virtual void DecodedSizeChangedTo(const Image*, size_t new_size) = 0;
virtual bool ShouldPauseAnimation(const Image*) = 0;
- virtual void AnimationAdvanced(const Image*) = 0;
// Notification for when the image's contents have changed such as when an
// SVG image animates.
diff --git a/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.cc b/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.cc
index 19f751e0939..2981128b533 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.cc
@@ -36,7 +36,7 @@
namespace blink {
-namespace InterpolationSpaceUtilities {
+namespace interpolation_space_utilities {
namespace {
@@ -76,6 +76,6 @@ sk_sp<SkColorFilter> CreateInterpolationSpaceFilter(
return GetConversionFilter(dst_interpolation_space, src_interpolation_space);
}
-} // namespace InterpolationSpaceUtilities
+} // namespace interpolation_space_utilities
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.h b/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.h
index 93418c44ef3..352755fc066 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/interpolation_space.h
@@ -42,7 +42,7 @@ enum InterpolationSpace {
kInterpolationSpaceLinear
};
-namespace InterpolationSpaceUtilities {
+namespace interpolation_space_utilities {
// Convert a Color assumed to be in the |src_interpolation_space| into the
// |dst_interpolation_space|.
@@ -57,7 +57,7 @@ sk_sp<SkColorFilter> CreateInterpolationSpaceFilter(
InterpolationSpace src_interpolation_space,
InterpolationSpace dst_interpolation_space);
-} // namespace InterpolationSpaceUtilities
+} // namespace interpolation_space_utilities
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/logging_canvas.cc b/chromium/third_party/blink/renderer/platform/graphics/logging_canvas.cc
index 93c255ffeca..0b830191a69 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/logging_canvas.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/logging_canvas.cc
@@ -349,12 +349,10 @@ String StringForSkPaintFlags(const SkPaint& paint) {
AppendFlagToString(&flags_string, paint.isFakeBoldText(), "FakeBoldText");
AppendFlagToString(&flags_string, paint.isLinearText(), "LinearText");
AppendFlagToString(&flags_string, paint.isSubpixelText(), "SubpixelText");
- AppendFlagToString(&flags_string, paint.isDevKernText(), "DevKernText");
AppendFlagToString(&flags_string, paint.isLCDRenderText(), "LCDRenderText");
AppendFlagToString(&flags_string, paint.isEmbeddedBitmapText(),
"EmbeddedBitmapText");
AppendFlagToString(&flags_string, paint.isAutohinted(), "Autohinted");
- AppendFlagToString(&flags_string, paint.isVerticalText(), "VerticalText");
return flags_string;
}
@@ -374,20 +372,6 @@ String FilterQualityName(SkFilterQuality filter_quality) {
};
}
-String TextAlignName(SkPaint::Align align) {
- switch (align) {
- case SkPaint::kLeft_Align:
- return "Left";
- case SkPaint::kCenter_Align:
- return "Center";
- case SkPaint::kRight_Align:
- return "Right";
- default:
- NOTREACHED();
- return "?";
- };
-}
-
String StrokeCapName(SkPaint::Cap cap) {
switch (cap) {
case SkPaint::kButt_Cap:
@@ -446,15 +430,15 @@ String TextEncodingName(SkPaint::TextEncoding encoding) {
};
}
-String HintingName(SkPaint::Hinting hinting) {
+String HintingName(SkFontHinting hinting) {
switch (hinting) {
- case SkPaint::kNo_Hinting:
+ case SkFontHinting::kNone:
return "None";
- case SkPaint::kSlight_Hinting:
+ case SkFontHinting::kSlight:
return "Slight";
- case SkPaint::kNormal_Hinting:
+ case SkFontHinting::kNormal:
return "Normal";
- case SkPaint::kFull_Hinting:
+ case SkFontHinting::kFull:
return "Full";
default:
NOTREACHED();
@@ -475,7 +459,6 @@ std::unique_ptr<JSONObject> ObjectForSkPaint(const SkPaint& paint) {
paint_item->SetString("flags", StringForSkPaintFlags(paint));
paint_item->SetString("filterLevel",
FilterQualityName(paint.getFilterQuality()));
- paint_item->SetString("textAlign", TextAlignName(paint.getTextAlign()));
paint_item->SetString("strokeCap", StrokeCapName(paint.getStrokeCap()));
paint_item->SetString("strokeJoin", StrokeJoinName(paint.getStrokeJoin()));
paint_item->SetString("styleName", StyleName(paint.getStyle()));
@@ -594,7 +577,7 @@ JSONObject* AutoLogger::LogItemWithParams(const String& name) {
}
LoggingCanvas::LoggingCanvas()
- : InterceptingCanvasBase(0, 0), log_(JSONArray::Create()) {}
+ : InterceptingCanvasBase(999999, 999999), log_(JSONArray::Create()) {}
void LoggingCanvas::onDrawPaint(const SkPaint& paint) {
AutoLogger logger(this);
diff --git a/chromium/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc b/chromium/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc
index e26626532fd..76a59a710b6 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/skia_texture_holder.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/skia/include/gpu/GrContext.h"
namespace blink {
@@ -118,7 +118,7 @@ void MailboxTextureHolder::Sync(MailboxSyncMode mode) {
}
void MailboxTextureHolder::InitCommon() {
- Thread* thread = Platform::Current()->CurrentThread();
+ Thread* thread = Thread::Current();
thread_id_ = thread->ThreadId();
texture_thread_task_runner_ = thread->GetTaskRunner();
}
@@ -133,7 +133,7 @@ bool MailboxTextureHolder::IsValid() const {
}
bool MailboxTextureHolder::IsCrossThread() const {
- return thread_id_ != Platform::Current()->CurrentThread()->ThreadId();
+ return thread_id_ != Thread::Current()->ThreadId();
}
MailboxTextureHolder::~MailboxTextureHolder() {
@@ -143,7 +143,7 @@ MailboxTextureHolder::~MailboxTextureHolder() {
if (!IsAbandoned()) {
if (texture_thread_task_runner_ &&
- thread_id_ != Platform::Current()->CurrentThread()->ThreadId()) {
+ thread_id_ != Thread::Current()->ThreadId()) {
PostCrossThreadTask(
*texture_thread_task_runner_, FROM_HERE,
CrossThreadBind(&ReleaseTexture, is_converted_from_skia_texture_,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.cc b/chromium/third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.cc
index bb5b34354e5..b618d59c8a3 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.cc
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/README.md b/chromium/third_party/blink/renderer/platform/graphics/paint/README.md
index f3033e12d8c..26a11012dab 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/README.md
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/README.md
@@ -17,7 +17,7 @@ replaces.
## Paint artifact
-The SPv2 [paint artifact](PaintArtifact.h) consists of a list of display items
+The SPv2 [paint artifact](paint_artifact.h) consists of a list of display items
in paint order (ideally mostly or all drawings), partitioned into *paint chunks*
which define certain *paint properties* which affect how the content should be
drawn or composited.
@@ -31,38 +31,33 @@ chunk is associated with a transform node, whose matrix should be multiplied by
its ancestor transform nodes in order to compute the final transformation matrix
to the screen.
-*** note
-Support for all paint properties has yet to be implemented in SPv2.
-***
+See [`ObjectPaintProperties`](../../../core/paint/object_paint_properties.h) for
+description of all paint properties that we create for a `LayoutObject`.
-*** aside
-TODO(jbroman): Explain the semantics of transforms, clips, scrolls and effects
-as support for them is added to SPv2.
-***
+Paint properties are represented by four paint property trees (transform, clip,
+effect and scroll) each of which contains corresponding type of
+[paint property nodes](paint_property_node.h). Each paint property node has a
+pointer to the parent node. The parent node pointers link the paint property
+nodes in a tree.
### Transforms
-Each paint chunk is associated with a [transform node](TransformPaintPropertyNode.h),
+Each paint chunk is associated with a [transform node](transform_paint_property_node.h),
which defines the coordinate space in which the content should be painted.
Each transform node has:
-* a 4x4 [`TransformationMatrix`](../../transforms/TransformationMatrix.h)
+* a 4x4 [`TransformationMatrix`](../../transforms/transformation_matrix.h)
* a 3-dimensional transform origin, which defines the origin relative to which
the transformation matrix should be applied (e.g. a rotation applied with some
transform origin will rotate the plane about that point)
-* a pointer to the parent node, which defines the coordinate space relative to
- which the above should be interpreted
* a boolean indicating whether the transform should be projected into the plane
of its parent (i.e., whether the total transform inherited from its parent
should be flattened before this node's transform is applied and propagated to
children)
* an integer rendering context ID; content whose transform nodes share a
rendering context ID should sort together
-
-The parent node pointers link the transform nodes in a hierarchy (the *transform
-tree*), which defines how the transform for any painted content can be
-determined.
+* other fields, see [the header file](transform_paint_property_node.h)
***promo
The painting system may create transform nodes which don't affect the position
@@ -80,60 +75,57 @@ imply any 3D sorting.
### Clips
-Each paint chunk is associated with a [clip node](ClipPaintPropertyNode.h),
+Each paint chunk is associated with a [clip node](clip_paint_property_node.h),
which defines the raster region that will be applied on the canvas when
the chunk is rastered.
Each clip node has:
* A float rect with (optionally) rounded corner radius.
+* An optional clip path if the clip is a clip path.
* An associated transform node, which the clip rect is based on.
-The raster region defined by a node is the rounded rect transformed to the
-root space, intersects with the raster region defined by its parent clip node
-(if not root).
-
-### Scrolling
-
-Each paint chunk is associated with a [scroll node](ScrollPaintPropertyNode.h)
-which defines information about how a subtree scrolls so threads other than the
-main thread can perform scrolling. Scroll information includes:
-
-* Which directions, if any, are scrollable by the user.
-* A reference to a [transform node](TransformPaintPropertyNode.h) which contains
-a 2d scroll offset.
-* The extent that can be scrolled. For example, an overflow clip of size 7x9
-with scrolling contents of size 7x13 can scroll 4px vertically and none
-horizontally.
-
-To ensure geometry operations are simple and only deal with transforms, the
-scroll offset is stored as a 2d transform in the transform tree.
+The raster region defined by a node is the rounded rect and/or clip path
+transformed to the root space, intersects with the raster region defined by its
+parent clip node (if not root).
### Effects
-Each paint chunk is associated with an [effect node](EffectPaintPropertyNode.h),
+Each paint chunk is associated with an [effect node](effect_paint_property_node.h),
which defines the effect (opacity, transfer mode, filter, mask, etc.) that
should be applied to the content before or as it is composited into the content
below.
Each effect node has:
-* a floating-point opacity (from 0 to 1, inclusive)
-* a pointer to the parent node, which will be applied to the result of this
- effect before or as it is composited into its parent in the effect tree
+* effects, including opacity, transfer mode, filter, mask, etc.
+* an optional associated clip node which clips the output of the effect when
+ composited into the current backdrop.
+* an associated transform node which defines the geometry space of some
+ geometry-related effects (e.g. some filters).
-The paret node pointers link the effect nodes in a hierarchy (the *effect
-tree*), which defines the dependencies between rasterization of different
-contents.
+The hierarchy in the *effect tree* defines the dependencies between
+rasterization of different contents.
One can imagine each effect node as corresponding roughly to a bitmap that is
drawn before being composited into another bitmap, though for implementation
reasons this may not be how it is actually implemented.
-*** aside
-TODO(jbroman): Explain the connection with the transform and clip trees, once it
-exists, as well as effects other than opacity.
-***
+### Scrolling
+
+Each paint chunk is associated with a [scroll node](scroll_paint_property_node.h)
+which defines information about how a subtree scrolls so threads other than the
+main thread can perform scrolling. Scroll information includes:
+
+* Which directions, if any, are scrollable by the user.
+* A reference to a [transform node](transform_paint_property_node.h) which contains
+ a 2d scroll offset.
+* The extent that can be scrolled. For example, an overflow clip of size 7x9
+ with scrolling contents of size 7x13 can scroll 4px vertically and none
+ horizontally.
+
+To ensure geometry operations are simple and only deal with transforms, the
+scroll offset is stored as a 2d transform in the transform tree.
## Display items
@@ -148,8 +140,8 @@ but can be other Blink objects which get painted, such as inline boxes and drag
images.
*** note
-It is illegal for there to be two drawings with the same ID in a display item
-list, except for drawings that are marked uncacheable
+It is illegal for there to be two display items with the same ID in a display
+item list, except for display items that are marked uncacheable
(see [DisplayItemCacheSkipper](DisplayItemCacheSkipper.h)).
***
@@ -177,13 +169,6 @@ in the compositor requires both property trees (scroll nodes) and a scrollable
`cc::layer` in paint order. This should be associated with the scroll
translation paint property node as well as any overflow clip nodes.
-### Paired begin/end display items
-
-*** aside
-TODO(jbroman): Describe how these work, once we've worked out what happens to
-them in SPv2.
-***
-
## Paint controller
Callers use `GraphicsContext` (via its drawing methods, and its
@@ -194,10 +179,10 @@ a `PaintController`.
the *current* paint artifact, and *new* display items and paint chunks, which
are added as content is painted.
-Painters should call `PaintController::useCachedDrawingIfPossible()` or
-`PaintController::useCachedSubsequenceIfPossible()` and if the function returns
+Painters should call `PaintController::UseCachedItemIfPossible()` or
+`PaintController::UseCachedSubsequenceIfPossible()` and if the function returns
`true`, existing display items that are still valid in the *current* paint artifact
-will be reused and the painter should skip real painting of the drawing or subsequence.
+will be reused and the painter should skip real painting of the item or subsequence.
When the new display items have been populated, clients call
`commitNewDisplayItems`, which replaces the previous artifact with the new data,
@@ -212,50 +197,9 @@ and [Paint invalidation](../../../core/paint/README.md#paint-invalidation) for
more details about how caching and invalidation are handled in blink core
module using `PaintController` API.
-We use 'cache generation' which is a unique id of cache status in each
-`DisplayItemClient` and `PaintController` to determine if the client is validly
-cached by a `PaintController`.
-
-A paint controller sets its cache generation to
-`DisplayItemCacheGeneration::next()` at the end of each
-`commitNewDisplayItems()`, and updates the cache generation of each client with
-cached drawings by calling `DisplayItemClient::setDisplayItemsCached()`.
-A display item is treated as validly cached in a paint controller if its cache
-generation matches the paint controller's cache generation.
-
-A cache generation value smaller than `kFirstValidGeneration` matches no
-other cache generations thus is always treated as invalid. When a
-`DisplayItemClient` is invalidated, we set its cache generation to one of
-`PaintInvalidationReason` values which are smaller than `kFirstValidGeneration`.
-When a `PaintController` is cleared (e.g. when the corresponding `GraphicsLayer`
-is fully invalidated), we also invalidate its cache generation.
-
-For now we use a uint32_t variable to store cache generation. Assuming there is
-an animation in 60fps needing main-thread repaint, the cache generation will
-overflow after 2^32/86400/60 = 828 days. The time may be shorter if there are
-multiple animating `PaintController`s in the same process. When it overflows,
-we may treat some object that is not cached as cached if the following
-conditions are all met:
-* the object was painted when the cache generation was *n*;
-* the object has been neither painted nor invalidated since cache generation
- *n*;
-* when the cache generation wraps back to exact *n*, the object happens to be
- painted again.
-As the paint controller doesn't have cached display items for the object, there
-will be corrupted painting or assertion failure. The chance is too low to be
-concerned.
-
-SPv1 only: If a display item is painted on multiple paint controllers, because
-cache generations are unique, the client's cache generation matches the last
-paint controller only. The client will be treated as invalid on other paint
-controllers regardless if it's validly cached by these paint controllers.
-The situation is very rare (about 0.07% clients were painted on multiple paint
-controllers in a [Cluster Telemetry run](https://ct.skia.org/chromium_perf_runs)
-(run 803) so the performance penalty is trivial.
-
## Paint artifact compositor
-The [`PaintArtifactCompositor`](PaintArtifactCompositor.h) is responsible for
+The [`PaintArtifactCompositor`](paint_artifact_compositor.h) is responsible for
consuming the `PaintArtifact` produced by the `PaintController`, and converting
it into a form suitable for the compositor to consume.
@@ -270,11 +214,65 @@ In the future we would like to explore moving to a single shared property tree
representation across both cc and
Blink. See [Web Page Geometries](https://goo.gl/MwVIto) for more.
+## Raster invalidation
+
+This is to mark which parts of the composited layers need to be re-rasterized to
+reflect changes of painting, by comparing the current paint artifact against the
+previous paint artifact. It's the last step of painting.
+
+It's done in two levels:
+
+* Paint chunk level (`RasterInvalidator`](raster_invalidator.h): matches each
+ paint chunk in the current paint artifact against the corresponding paint
+ chunk in the previous paint artifact, by matching their ids. There are
+ following cases:
+
+ * A new paint chunk doesn't match any old paint chunk (appearing): The bounds
+ of the new paint chunk in the composited layer will be fully raster
+ invalidated.
+
+ * An old paint chunk doesn't match any new paint chunk (disappearing): The
+ bounds of the old paint chunk in the composited layer will be fully raster
+ invalidated.
+
+ * A new paint chunk matches an old paint chunk:
+
+ * The new paint chunk is moved backward (reordering): this may expose other
+ chunks that was previously covered by it: Both of the old bounds and the
+ new bounds will be fully raster invalidated.
+
+ * Paint properties of the paint chunk changed:
+
+ * If only clip changed, the difference between the old bounds and
+ the new bounds will be raster invalidated (i.e. do incremental
+ invalidation).
+
+ * Otherwise, both of the old bounds and the new bounds will be fully
+ raster invalidated.
+
+ * Otherwise, check for changed display items within the paint chunk.
+
+* Display item level (`DisplayItemRasterInvalidator`](display_item_raster_invalidator.h]:
+ This is executed when a new chunk matches an old chunk in-order and paint
+ properties didn't change. The algorithm checks changed display items within a
+ paint chunk.
+
+ * Similar to the paint chunk level, the visual rects (mapped to the space of
+ the composited layer) of appearing, disappearing, reordering display items
+ are fully raster invalidated.
+
+ * If a new paint chunk in-order matches an old paint chunk, if the display
+ item client has been [paint invalidated](../../../core/paint/README.md#paint-invalidation),
+ we will do full raster invalidation (which invalidates the old visual rect
+ and the new visual rect in the composted layer) or incremental raster
+ invalidation (which invalidates the difference between the old visual rect
+ and the new visual rect) according to the paint invalidation reason.
+
## Geometry routines
-The [`GeometryMapper`](GeometryMapper.h) is responsible for efficiently computing
+The [`GeometryMapper`](geometry_mapper.h) is responsible for efficiently computing
visual and transformed rects of display items in the coordinate space of ancestor
-[`PropertyTreeState`](PropertyTreeState.h)s.
+[`PropertyTreeState`](property_tree_state.h)s.
The transformed rect of a display item in an ancestor `PropertyTreeState` is
that rect, multiplied by the transforms between the display item's
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.cc
index 325f8c5af37..a79f58d730d 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.cc
@@ -6,31 +6,25 @@
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
+#include "third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h"
+#include "third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
namespace blink {
-CullRect::CullRect(const CullRect& cull_rect, const IntPoint& offset) {
- rect_ = cull_rect.rect_;
- rect_.MoveBy(offset);
+bool CullRect::Intersects(const IntRect& rect) const {
+ return IsInfinite() || rect.Intersects(rect_);
}
-CullRect::CullRect(const CullRect& cull_rect, const IntSize& offset) {
- rect_ = cull_rect.rect_;
- rect_.Move(offset);
+bool CullRect::Intersects(const LayoutRect& rect) const {
+ return IsInfinite() || rect_.Intersects(EnclosingIntRect(rect));
}
-bool CullRect::IntersectsCullRect(const IntRect& bounding_box) const {
- return bounding_box.Intersects(rect_);
-}
-
-bool CullRect::IntersectsCullRect(const AffineTransform& transform,
- const FloatRect& bounding_box) const {
- return transform.MapRect(bounding_box).Intersects(rect_);
-}
-
-bool CullRect::IntersectsCullRect(const LayoutRect& rect_arg) const {
- return rect_.Intersects(EnclosingIntRect(rect_arg));
+bool CullRect::IntersectsTransformed(const AffineTransform& transform,
+ const FloatRect& rect) const {
+ return IsInfinite() || transform.MapRect(rect).Intersects(rect_);
}
bool CullRect::IntersectsHorizontalRange(LayoutUnit lo, LayoutUnit hi) const {
@@ -41,23 +35,100 @@ bool CullRect::IntersectsVerticalRange(LayoutUnit lo, LayoutUnit hi) const {
return !(lo >= rect_.MaxY() || hi <= rect_.Y());
}
-void CullRect::UpdateCullRect(
- const AffineTransform& local_to_parent_transform) {
- if (rect_ != LayoutRect::InfiniteIntRect())
- rect_ = local_to_parent_transform.Inverse().MapRect(rect_);
+void CullRect::MoveBy(const IntPoint& offset) {
+ if (!IsInfinite())
+ rect_.MoveBy(offset);
+}
+
+void CullRect::Move(const IntSize& offset) {
+ if (!IsInfinite())
+ rect_.Move(offset);
+}
+
+CullRect::ApplyTransformResult CullRect::ApplyTransformInternal(
+ const TransformPaintPropertyNode* transform) {
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) {
+ if (const auto* scroll = transform->ScrollNode()) {
+ rect_.Intersect(scroll->ContainerRect());
+ if (rect_.IsEmpty())
+ return kNotExpanded;
+ rect_ = transform->Matrix().Inverse().MapRect(rect_);
+
+ // Expand the cull rect for scrolling contents in case of composited
+ // scrolling.
+ // TODO(wangxianzhu): options for non-composited-scrolling contents:
+ // 1. to use non-composted-scrolling heuristics to avoid expansion;
+ // 2. to reduce the 4000px distance, no matter if the contents with be
+ // composited scrolling.
+ // 3. mixed method of 1 and 2, e.g. the distance could be a function of
+ // confidence that the contents will be composited scrolling.
+ static const int kPixelDistanceToExpand = 4000;
+ rect_.Inflate(kPixelDistanceToExpand);
+ // Don't clip the cull rect by contents size to let ChangedEnough() work
+ // even if the new cull rect exceeds the bounds of contents rect.
+ return rect_.Contains(IntRect(IntPoint(), scroll->ContentsSize()))
+ ? kExpandedForWholeScrollingContents
+ : kExpandedForPartialScrollingContents;
+ }
+ }
+
+ if (!IsInfinite())
+ rect_ = transform->Matrix().Inverse().MapRect(rect_);
+ return kNotExpanded;
}
-void CullRect::UpdateForScrollingContents(
- const IntRect& overflow_clip_rect,
- const AffineTransform& local_to_parent_transform) {
+void CullRect::ApplyTransforms(const TransformPaintPropertyNode* source,
+ const TransformPaintPropertyNode* destination,
+ const base::Optional<CullRect>& old_cull_rect) {
DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
- rect_.Intersect(overflow_clip_rect);
- UpdateCullRect(local_to_parent_transform);
- // TODO(wangxianzhu, chrishtr): How about non-composited scrolling contents?
- // The distance to expand the cull rect for scrolling contents.
- static const int kPixelDistanceToExpand = 4000;
- rect_.Inflate(kPixelDistanceToExpand);
+ Vector<const TransformPaintPropertyNode*> scroll_translations;
+ for (const auto* t = destination; t != source; t = t->Parent()) {
+ if (!t) {
+ // |source| is not an ancestor of |destination|. Simply map.
+ GeometryMapper::SourceToDestinationRect(source, destination, rect_);
+ return;
+ }
+ if (t->ScrollNode())
+ scroll_translations.push_back(t);
+ }
+
+ const auto* last_transform = source;
+ ApplyTransformResult last_scroll_translation_result = kNotExpanded;
+ for (auto it = scroll_translations.rbegin(); it != scroll_translations.rend();
+ ++it) {
+ const auto* scroll_translation = *it;
+ if (!IsInfinite()) {
+ GeometryMapper::SourceToDestinationRect(
+ last_transform, scroll_translation->Parent(), rect_);
+ }
+ last_scroll_translation_result = ApplyTransformInternal(scroll_translation);
+ last_transform = scroll_translation;
+ }
+
+ if (!IsInfinite())
+ GeometryMapper::SourceToDestinationRect(last_transform, destination, rect_);
+
+ if (last_scroll_translation_result == kExpandedForPartialScrollingContents &&
+ old_cull_rect && !ChangedEnough(*old_cull_rect))
+ rect_ = old_cull_rect->Rect();
+}
+
+bool CullRect::ChangedEnough(const CullRect& old_cull_rect) const {
+ DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+
+ const auto& new_rect = Rect();
+ const auto& old_rect = old_cull_rect.Rect();
+ if (old_rect == new_rect || (old_rect.IsEmpty() && new_rect.IsEmpty()))
+ return false;
+
+ if (old_rect.IsEmpty())
+ return true;
+
+ auto expanded_old_rect = old_rect;
+ static const int kChangedEnoughMinimumDistance = 512;
+ expanded_old_rect.Inflate(kChangedEnoughMinimumDistance);
+ return !expanded_old_rect.Contains(new_rect);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.h b/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.h
index bde6db06165..73ef85de6e4 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_CULL_RECT_H_
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
-#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
+#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -14,9 +14,11 @@
namespace blink {
+class AffineTransform;
class FloatRect;
class LayoutRect;
class LayoutUnit;
+class TransformPaintPropertyNode;
class PLATFORM_EXPORT CullRect {
DISALLOW_NEW();
@@ -24,44 +26,81 @@ class PLATFORM_EXPORT CullRect {
public:
CullRect() = default;
explicit CullRect(const IntRect& rect) : rect_(rect) {}
- CullRect(const CullRect&, const IntPoint& offset);
- CullRect(const CullRect&, const IntSize& offset);
- bool IntersectsCullRect(const AffineTransform&,
- const FloatRect& bounding_box) const;
- bool IntersectsCullRect(const IntRect&) const;
- bool IntersectsCullRect(const LayoutRect&) const;
+ static CullRect Infinite() { return CullRect(LayoutRect::InfiniteIntRect()); }
+
+ bool IsInfinite() const { return rect_ == LayoutRect::InfiniteIntRect(); }
+
+ bool Intersects(const IntRect&) const;
+ bool Intersects(const LayoutRect&) const;
+ bool IntersectsTransformed(const AffineTransform&, const FloatRect&) const;
bool IntersectsHorizontalRange(LayoutUnit lo, LayoutUnit hi) const;
bool IntersectsVerticalRange(LayoutUnit lo, LayoutUnit hi) const;
- void UpdateCullRect(const AffineTransform& local_to_parent_transform);
-
- // |overflow_clip_rect| should be in the same coordinate space as |rect_|.
- void UpdateForScrollingContents(
- const IntRect& overflow_clip_rect,
- const AffineTransform& local_to_parent_transform);
+ void MoveBy(const IntPoint& offset);
+ void Move(const IntSize& offset);
+
+ // Applies one transform to the cull rect. Before this function is called,
+ // the cull rect is in the space of the parent the transform node.
+ // For SlimmingPaintV2, when the transform is a scroll translation, the cull
+ // rect is converted in the following steps:
+ // 1. it's clipped by the container rect,
+ // 2. transformed by inverse of the scroll translation,
+ // 3. expanded by thousands of pixels for composited scrolling.
+ void ApplyTransform(const TransformPaintPropertyNode* transform) {
+ ApplyTransformInternal(transform);
+ }
+
+ // For SlimmingPaintV2 only. Applies transforms from |source| (not included)
+ // to |destination| (included). For each scroll translation, the cull rect is
+ // converted as described in ApplyTransform(). If |old_cull_rect| is provided,
+ // and the cull rect converted by the last scroll translation doesn't cover
+ // the whole scrolling contents, and the new cull rect doesn't change enough
+ // (by hundreds of pixels) from |old_cull_rect|, the cull rect will be set to
+ // |old_cull_rect| to avoid repaint on each composited scroll.
+ void ApplyTransforms(const TransformPaintPropertyNode* source,
+ const TransformPaintPropertyNode* destination,
+ const base::Optional<CullRect>& old_cull_rect);
const IntRect& Rect() const { return rect_; }
String ToString() const { return rect_.ToString(); }
private:
- IntRect rect_;
-
- friend bool operator==(const CullRect&, const CullRect&);
-
friend class CullRectTest;
- friend class TableSectionPainter;
+ enum ApplyTransformResult {
+ // The cull rect is transformed into the target transform space (by mapping
+ // the cull rect with the inverse of the transform) without expansion.
+ // In SlimmingPaintV1, the functions always return this value.
+ kNotExpanded,
+ // The cull rect is converted by a scroll translation (in the steps
+ // described in ApplyTransform(), and the result covers the whole scrolling
+ // contents.
+ kExpandedForWholeScrollingContents,
+ // The cull rect is converted by a scroll translation, and the result
+ // doesn't cover the whole scrolling contents.
+ kExpandedForPartialScrollingContents,
+ };
+ ApplyTransformResult ApplyTransformInternal(
+ const TransformPaintPropertyNode*);
+
+ bool ChangedEnough(const CullRect& old_cull_rect) const;
+
+ IntRect rect_;
};
inline bool operator==(const CullRect& a, const CullRect& b) {
- return a.rect_ == b.rect_;
+ return a.Rect() == b.Rect();
}
inline bool operator!=(const CullRect& a, const CullRect& b) {
return !(a == b);
}
+inline std::ostream& operator<<(std::ostream& os, const CullRect& cull_rect) {
+ return os << cull_rect.Rect();
+}
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_CULL_RECT_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect_test.cc
index 2690dd8e06a..40081fb82f9 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/cull_rect_test.cc
@@ -7,46 +7,431 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/platform/testing/paint_property_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
+#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
namespace blink {
class CullRectTest : public testing::Test {
protected:
- IntRect Rect(const CullRect& cull_rect) { return cull_rect.rect_; }
+ const CullRect::ApplyTransformResult kNotExpanded = CullRect::kNotExpanded;
+ const CullRect::ApplyTransformResult kExpandedForPartialScrollingContents =
+ CullRect::kExpandedForPartialScrollingContents;
+ const CullRect::ApplyTransformResult kExpandedForWholeScrollingContents =
+ CullRect::kExpandedForWholeScrollingContents;
+
+ CullRect::ApplyTransformResult ApplyTransform(
+ CullRect& cull_rect,
+ const TransformPaintPropertyNode* t) {
+ return cull_rect.ApplyTransformInternal(t);
+ }
+
+ bool ChangedEnough(const IntRect& old_rect, const IntRect& new_rect) {
+ return CullRect(new_rect).ChangedEnough(CullRect(old_rect));
+ }
};
-TEST_F(CullRectTest, IntersectsCullRect) {
+TEST_F(CullRectTest, IntersectsIntRect) {
CullRect cull_rect(IntRect(0, 0, 50, 50));
- EXPECT_TRUE(cull_rect.IntersectsCullRect(IntRect(0, 0, 1, 1)));
- EXPECT_FALSE(cull_rect.IntersectsCullRect(IntRect(51, 51, 1, 1)));
+ EXPECT_TRUE(cull_rect.Intersects(IntRect(0, 0, 1, 1)));
+ EXPECT_FALSE(cull_rect.Intersects(IntRect(51, 51, 1, 1)));
}
-TEST_F(CullRectTest, IntersectsCullRectWithLayoutRect) {
+TEST_F(CullRectTest, IntersectsLayoutRect) {
CullRect cull_rect(IntRect(0, 0, 50, 50));
- EXPECT_TRUE(cull_rect.IntersectsCullRect(LayoutRect(0, 0, 1, 1)));
- EXPECT_TRUE(cull_rect.IntersectsCullRect(LayoutRect(
+ EXPECT_TRUE(cull_rect.Intersects(LayoutRect(0, 0, 1, 1)));
+ EXPECT_TRUE(cull_rect.Intersects(LayoutRect(
LayoutUnit(0.1), LayoutUnit(0.1), LayoutUnit(0.1), LayoutUnit(0.1))));
}
-TEST_F(CullRectTest, IntersectsCullRectWithTransform) {
+TEST_F(CullRectTest, IntersectsTransformed) {
CullRect cull_rect(IntRect(0, 0, 50, 50));
AffineTransform transform;
transform.Translate(-2, -2);
- EXPECT_TRUE(cull_rect.IntersectsCullRect(transform, FloatRect(51, 51, 1, 1)));
- EXPECT_FALSE(cull_rect.IntersectsCullRect(IntRect(52, 52, 1, 1)));
+ EXPECT_TRUE(
+ cull_rect.IntersectsTransformed(transform, FloatRect(51, 51, 1, 1)));
+ EXPECT_FALSE(cull_rect.Intersects(IntRect(52, 52, 1, 1)));
+}
+
+TEST_F(CullRectTest, Infinite) {
+ EXPECT_TRUE(CullRect::Infinite().IsInfinite());
+ EXPECT_TRUE(CullRect(LayoutRect::InfiniteIntRect()).IsInfinite());
+ EXPECT_FALSE(CullRect(IntRect(0, 0, 100, 100)).IsInfinite());
+}
+
+TEST_F(CullRectTest, Move) {
+ CullRect cull_rect(IntRect(0, 0, 50, 50));
+ cull_rect.Move(IntSize());
+ EXPECT_EQ(IntRect(0, 0, 50, 50), cull_rect.Rect());
+ cull_rect.Move(IntSize(10, 20));
+ EXPECT_EQ(IntRect(10, 20, 50, 50), cull_rect.Rect());
+}
+
+TEST_F(CullRectTest, MoveInfinite) {
+ CullRect cull_rect = CullRect::Infinite();
+ cull_rect.Move(IntSize());
+ EXPECT_TRUE(cull_rect.IsInfinite());
+ cull_rect.Move(IntSize(10, 20));
+ EXPECT_TRUE(cull_rect.IsInfinite());
+}
+
+TEST_F(CullRectTest, MoveBy) {
+ CullRect cull_rect(IntRect(0, 0, 50, 50));
+ cull_rect.MoveBy(IntPoint());
+ EXPECT_EQ(IntRect(0, 0, 50, 50), cull_rect.Rect());
+ cull_rect.MoveBy(IntPoint(10, 20));
+ EXPECT_EQ(IntRect(10, 20, 50, 50), cull_rect.Rect());
+}
+
+TEST_F(CullRectTest, MoveByInfinite) {
+ CullRect cull_rect = CullRect::Infinite();
+ cull_rect.MoveBy(IntPoint());
+ EXPECT_TRUE(cull_rect.IsInfinite());
+ cull_rect.MoveBy(IntPoint(10, 20));
+ EXPECT_TRUE(cull_rect.IsInfinite());
}
-TEST_F(CullRectTest, UpdateCullRect) {
+TEST_F(CullRectTest, ApplyTransform) {
CullRect cull_rect(IntRect(1, 1, 50, 50));
- AffineTransform transform;
- transform.Translate(1, 1);
- cull_rect.UpdateCullRect(transform);
+ auto transform =
+ CreateTransform(t0(), TransformationMatrix().Translate(1, 1));
+ EXPECT_EQ(kNotExpanded, ApplyTransform(cull_rect, transform.get()));
+
+ EXPECT_EQ(IntRect(0, 0, 50, 50), cull_rect.Rect());
+}
+
+TEST_F(CullRectTest, ApplyTransformInfinite) {
+ CullRect cull_rect = CullRect::Infinite();
+ auto transform =
+ CreateTransform(t0(), TransformationMatrix().Translate(1, 1));
+ EXPECT_EQ(kNotExpanded, ApplyTransform(cull_rect, transform.get()));
+
+ EXPECT_TRUE(cull_rect.IsInfinite());
+}
+
+TEST_F(CullRectTest, ApplyScrollTranslationPartialScrollingContents) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+
+ ScrollPaintPropertyNode::State scroll_state;
+ scroll_state.container_rect = IntRect(20, 10, 40, 50);
+ scroll_state.contents_size = IntSize(8000, 8000);
+ auto scroll = ScrollPaintPropertyNode::Create(ScrollPaintPropertyNode::Root(),
+ std::move(scroll_state));
+ auto scroll_translation =
+ CreateScrollTranslation(t0(), -3000, -5000, *scroll);
+
+ CullRect cull_rect(IntRect(0, 0, 50, 100));
+ EXPECT_EQ(kExpandedForPartialScrollingContents,
+ ApplyTransform(cull_rect, scroll_translation.get()));
- EXPECT_EQ(IntRect(0, 0, 50, 50), Rect(cull_rect));
+ // Clipped: (20, 10, 30, 50)
+ // Inverse transformed: (3020, 5010, 30, 50)
+ // Expanded: (-980, 1010, 8030, 8050)
+ EXPECT_EQ(IntRect(-980, 1010, 8030, 8050), cull_rect.Rect());
+
+ cull_rect = CullRect::Infinite();
+ EXPECT_EQ(kExpandedForPartialScrollingContents,
+ ApplyTransform(cull_rect, scroll_translation.get()));
+ // This result differs from the above result in height (8040 vs 8030)
+ // because it's not clipped by the infinite input cull rect.
+ EXPECT_EQ(IntRect(-980, 1010, 8040, 8050), cull_rect.Rect());
+}
+
+TEST_F(CullRectTest, ApplyScrollTranslationNoIntersectionWithContainerRect) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+
+ ScrollPaintPropertyNode::State scroll_state;
+ scroll_state.container_rect = IntRect(200, 100, 40, 50);
+ scroll_state.contents_size = IntSize(2000, 2000);
+ auto scroll = ScrollPaintPropertyNode::Create(ScrollPaintPropertyNode::Root(),
+ std::move(scroll_state));
+ auto scroll_translation = CreateScrollTranslation(t0(), -10, -15, *scroll);
+
+ CullRect cull_rect(IntRect(0, 0, 50, 100));
+ EXPECT_EQ(kNotExpanded, ApplyTransform(cull_rect, scroll_translation.get()));
+ EXPECT_TRUE(cull_rect.Rect().IsEmpty());
+}
+
+TEST_F(CullRectTest, ApplyScrollTranslationWholeScrollingContents) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+
+ ScrollPaintPropertyNode::State scroll_state;
+ scroll_state.container_rect = IntRect(20, 10, 40, 50);
+ scroll_state.contents_size = IntSize(2000, 2000);
+ auto scroll = ScrollPaintPropertyNode::Create(ScrollPaintPropertyNode::Root(),
+ std::move(scroll_state));
+ auto scroll_translation = CreateScrollTranslation(t0(), -10, -15, *scroll);
+
+ CullRect cull_rect(IntRect(0, 0, 50, 100));
+ EXPECT_EQ(kExpandedForWholeScrollingContents,
+ ApplyTransform(cull_rect, scroll_translation.get()));
+
+ // Clipped: (20, 10, 30, 50)
+ // Inverse transformed: (30, 25, 30, 50)
+ // Expanded: (-3970, -3975, 8030, 8050)
+ EXPECT_EQ(IntRect(-3970, -3975, 8030, 8050), cull_rect.Rect());
+
+ cull_rect = CullRect::Infinite();
+ EXPECT_EQ(kExpandedForWholeScrollingContents,
+ ApplyTransform(cull_rect, scroll_translation.get()));
+ // This result differs from the above result in height (8040 vs 8030)
+ // because it's not clipped by the infinite input cull rect.
+ EXPECT_EQ(IntRect(-3970, -3975, 8040, 8050), cull_rect.Rect());
+}
+
+TEST_F(CullRectTest, ChangedEnoughEmpty) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ EXPECT_FALSE(ChangedEnough(IntRect(), IntRect()));
+ EXPECT_FALSE(ChangedEnough(IntRect(1, 1, 0, 0), IntRect(2, 2, 0, 0)));
+ EXPECT_TRUE(ChangedEnough(IntRect(), IntRect(0, 0, 1, 1)));
+ EXPECT_FALSE(ChangedEnough(IntRect(0, 0, 1, 1), IntRect()));
+}
+
+TEST_F(CullRectTest, ChangedNotEnough) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ IntRect old_rect(100, 100, 100, 100);
+ EXPECT_FALSE(ChangedEnough(old_rect, old_rect));
+ EXPECT_FALSE(ChangedEnough(old_rect, IntRect(100, 100, 90, 90)));
+ EXPECT_FALSE(ChangedEnough(old_rect, IntRect(100, 100, 100, 100)));
+ EXPECT_FALSE(ChangedEnough(old_rect, IntRect(1, 1, 200, 200)));
+}
+
+TEST_F(CullRectTest, ChangedEnoughScrollScenarios) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ IntRect old_rect(100, 100, 100, 100);
+ IntRect new_rect(old_rect);
+ new_rect.Move(500, 0);
+ EXPECT_FALSE(ChangedEnough(old_rect, new_rect));
+ new_rect.Move(0, 500);
+ EXPECT_FALSE(ChangedEnough(old_rect, new_rect));
+ new_rect.Move(50, 0);
+ EXPECT_TRUE(ChangedEnough(old_rect, new_rect));
+ new_rect.Move(-50, 50);
+ EXPECT_TRUE(ChangedEnough(old_rect, new_rect));
+}
+
+TEST_F(CullRectTest, ApplyTransformsSameTransform) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto transform =
+ CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+ CullRect cull_rect1(IntRect(1, 1, 50, 50));
+ cull_rect1.ApplyTransforms(transform.get(), transform.get(), base::nullopt);
+ EXPECT_EQ(IntRect(1, 1, 50, 50), cull_rect1.Rect());
+
+ CullRect old_cull_rect = cull_rect1;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect2(IntRect(1, 1, 50, 50));
+ // Should ignore old_cull_rect.
+ cull_rect2.ApplyTransforms(transform.get(), transform.get(), old_cull_rect);
+ EXPECT_EQ(cull_rect1, cull_rect2);
+
+ CullRect infinite = CullRect::Infinite();
+ infinite.ApplyTransforms(transform.get(), transform.get(), base::nullopt);
+ EXPECT_TRUE(infinite.IsInfinite());
+}
+
+TEST_F(CullRectTest, ApplyTransformsWithoutScroll) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+ auto t2 = CreateTransform(*t1, TransformationMatrix().Translate(10, 20));
+
+ CullRect cull_rect1(IntRect(1, 1, 50, 50));
+ cull_rect1.ApplyTransforms(t1.get(), t2.get(), base::nullopt);
+ EXPECT_EQ(IntRect(-9, -19, 50, 50), cull_rect1.Rect());
+
+ CullRect cull_rect2(IntRect(1, 1, 50, 50));
+ cull_rect2.ApplyTransforms(&t0(), t2.get(), base::nullopt);
+ EXPECT_EQ(IntRect(-10, -21, 50, 50), cull_rect2.Rect());
+
+ CullRect old_cull_rect = cull_rect2;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect3(IntRect(1, 1, 50, 50));
+ // Should ignore old_cull_rect.
+ cull_rect3.ApplyTransforms(&t0(), t2.get(), old_cull_rect);
+ EXPECT_EQ(cull_rect2, cull_rect3);
+
+ CullRect infinite = CullRect::Infinite();
+ infinite.ApplyTransforms(&t0(), t2.get(), base::nullopt);
+ EXPECT_TRUE(infinite.IsInfinite());
+}
+
+TEST_F(CullRectTest, ApplyTransformsSingleScrollWholeScrollingContents) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+
+ ScrollPaintPropertyNode::State scroll_state;
+ scroll_state.container_rect = IntRect(20, 10, 40, 50);
+ scroll_state.contents_size = IntSize(2000, 2000);
+ auto scroll = ScrollPaintPropertyNode::Create(ScrollPaintPropertyNode::Root(),
+ std::move(scroll_state));
+ auto scroll_translation = CreateScrollTranslation(*t1, -10, -15, *scroll);
+
+ // Same as ApplyScrollTranslationWholeScrollingContents.
+ CullRect cull_rect1(IntRect(0, 0, 50, 100));
+ cull_rect1.ApplyTransforms(t1.get(), scroll_translation.get(), base::nullopt);
+ EXPECT_EQ(IntRect(-3970, -3975, 8030, 8050), cull_rect1.Rect());
+
+ CullRect old_cull_rect = cull_rect1;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect2(IntRect(0, 0, 50, 100));
+ // Should ignore old_cull_rect.
+ cull_rect2.ApplyTransforms(t1.get(), scroll_translation.get(), old_cull_rect);
+ EXPECT_EQ(cull_rect1, cull_rect2);
+
+ CullRect cull_rect3 = CullRect::Infinite();
+ cull_rect3.ApplyTransforms(t1.get(), scroll_translation.get(), base::nullopt);
+ // This result differs from the first result in height (8040 vs 8030)
+ // because it's not clipped by the infinite input cull rect.
+ EXPECT_EQ(IntRect(-3970, -3975, 8040, 8050), cull_rect3.Rect());
+}
+
+TEST_F(CullRectTest, ApplyTransformsSingleScrollPartialScrollingContents) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+
+ ScrollPaintPropertyNode::State scroll_state;
+ scroll_state.container_rect = IntRect(20, 10, 40, 50);
+ scroll_state.contents_size = IntSize(8000, 8000);
+ auto scroll = ScrollPaintPropertyNode::Create(ScrollPaintPropertyNode::Root(),
+ std::move(scroll_state));
+ auto scroll_translation = CreateScrollTranslation(*t1, -3000, -5000, *scroll);
+
+ // Same as ApplyScrollTranslationPartialScrollingContents.
+ CullRect cull_rect1(IntRect(0, 0, 50, 100));
+ cull_rect1.ApplyTransforms(t1.get(), scroll_translation.get(), base::nullopt);
+ EXPECT_EQ(IntRect(-980, 1010, 8030, 8050), cull_rect1.Rect());
+
+ CullRect old_cull_rect = cull_rect1;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect2(IntRect(0, 0, 50, 100));
+ // Use old_cull_rect if the new cull rect didn't change enough.
+ cull_rect2.ApplyTransforms(t1.get(), scroll_translation.get(), old_cull_rect);
+ EXPECT_EQ(old_cull_rect, cull_rect2);
+
+ old_cull_rect.Move(IntSize(1000, 1000));
+ CullRect cull_rect3(IntRect(0, 0, 50, 100));
+ // Use the new cull rect if it changed enough.
+ cull_rect3.ApplyTransforms(t1.get(), scroll_translation.get(), old_cull_rect);
+ EXPECT_EQ(cull_rect1, cull_rect3);
+
+ CullRect cull_rect4 = CullRect::Infinite();
+ cull_rect4.ApplyTransforms(t1.get(), scroll_translation.get(), base::nullopt);
+ // This result differs from the first result in height (8040 vs 8030)
+ // because it's not clipped by the infinite input cull rect.
+ EXPECT_EQ(IntRect(-980, 1010, 8040, 8050), cull_rect4.Rect());
+}
+
+TEST_F(CullRectTest, ApplyTransformsEscapingScroll) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+
+ ScrollPaintPropertyNode::State scroll_state;
+ scroll_state.container_rect = IntRect(20, 10, 40, 50);
+ scroll_state.contents_size = IntSize(8000, 8000);
+ auto scroll = ScrollPaintPropertyNode::Create(ScrollPaintPropertyNode::Root(),
+ std::move(scroll_state));
+ auto scroll_translation = CreateScrollTranslation(*t1, -3000, -5000, *scroll);
+ auto t2 = CreateTransform(*scroll_translation,
+ TransformationMatrix().Translate(100, 200));
+
+ CullRect cull_rect1(IntRect(0, 0, 50, 100));
+ // Just apply tranforms without clipping and expansion for scroll translation.
+ cull_rect1.ApplyTransforms(t2.get(), t1.get(), base::nullopt);
+ EXPECT_EQ(IntRect(-2900, -4800, 50, 100), cull_rect1.Rect());
+
+ CullRect old_cull_rect = cull_rect1;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect2(IntRect(0, 0, 50, 100));
+ // Should ignore old_cull_rect.
+ cull_rect2.ApplyTransforms(t2.get(), t1.get(), old_cull_rect);
+ EXPECT_EQ(cull_rect1, cull_rect2);
+}
+
+TEST_F(CullRectTest, ApplyTransformsSmallScrollContentsAfterBigScrollContents) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+
+ ScrollPaintPropertyNode::State scroll_state1;
+ scroll_state1.container_rect = IntRect(20, 10, 40, 50);
+ scroll_state1.contents_size = IntSize(8000, 8000);
+ auto scroll1 = ScrollPaintPropertyNode::Create(
+ ScrollPaintPropertyNode::Root(), std::move(scroll_state1));
+ auto scroll_translation1 = CreateScrollTranslation(*t1, -10, -15, *scroll1);
+
+ auto t2 = CreateTransform(*scroll_translation1,
+ TransformationMatrix().Translate(2000, 3000));
+
+ ScrollPaintPropertyNode::State scroll_state2;
+ scroll_state2.container_rect = IntRect(30, 20, 100, 200);
+ scroll_state2.contents_size = IntSize(200, 400);
+ auto scroll2 = ScrollPaintPropertyNode::Create(
+ ScrollPaintPropertyNode::Root(), std::move(scroll_state2));
+ auto scroll_translation2 = CreateScrollTranslation(*t2, -10, -15, *scroll2);
+
+ CullRect cull_rect1(IntRect(0, 0, 50, 100));
+ cull_rect1.ApplyTransforms(t1.get(), scroll_translation2.get(),
+ base::nullopt);
+ EXPECT_EQ(IntRect(-3960, -3965, 8100, 8200), cull_rect1.Rect());
+
+ CullRect old_cull_rect = cull_rect1;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect2(IntRect(0, 0, 50, 100));
+ // Should ignore old_cull_rect.
+ cull_rect2.ApplyTransforms(t1.get(), scroll_translation2.get(),
+ old_cull_rect);
+ EXPECT_EQ(cull_rect1, cull_rect2);
+}
+
+TEST_F(CullRectTest, ApplyTransformsBigScrollContentsAfterSmallScrollContents) {
+ ScopedSlimmingPaintV2ForTest spv2(true);
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Translate(1, 2));
+
+ ScrollPaintPropertyNode::State scroll_state1;
+ scroll_state1.container_rect = IntRect(30, 20, 100, 200);
+ scroll_state1.contents_size = IntSize(200, 400);
+ auto scroll1 = ScrollPaintPropertyNode::Create(
+ ScrollPaintPropertyNode::Root(), std::move(scroll_state1));
+ auto scroll_translation1 = CreateScrollTranslation(*t1, -10, -15, *scroll1);
+
+ auto t2 = CreateTransform(*scroll_translation1,
+ TransformationMatrix().Translate(10, 20));
+
+ ScrollPaintPropertyNode::State scroll_state2;
+ scroll_state2.container_rect = IntRect(20, 10, 50, 100);
+ scroll_state2.contents_size = IntSize(10000, 20000);
+ auto scroll2 = ScrollPaintPropertyNode::Create(
+ ScrollPaintPropertyNode::Root(), std::move(scroll_state2));
+ auto scroll_translation2 =
+ CreateScrollTranslation(*t2, -3000, -5000, *scroll2);
+
+ CullRect cull_rect1(IntRect(0, 0, 100, 200));
+ cull_rect1.ApplyTransforms(t1.get(), scroll_translation2.get(),
+ base::nullopt);
+ // After the first scroll: (-3960, -3965, 8070, 8180)
+ // After t2: (-3980, -3975, 8070, 8180)
+ // Clipped by the container rect of the second scroll: (20, 10, 50, 100)
+ // After the second scroll offset: (3020, 5010, 50, 100)
+ // Expanded: (-980, 1010, 8050, 8100)
+ EXPECT_EQ(IntRect(-980, 1010, 8050, 8100), cull_rect1.Rect());
+
+ CullRect old_cull_rect = cull_rect1;
+ old_cull_rect.Move(IntSize(1, 1));
+ CullRect cull_rect2(IntRect(0, 0, 100, 200));
+ // Use old_cull_rect if the new cull rect didn't change enough.
+ cull_rect2.ApplyTransforms(t1.get(), scroll_translation2.get(),
+ old_cull_rect);
+ EXPECT_EQ(old_cull_rect, cull_rect2);
+
+ old_cull_rect.Move(IntSize(1000, 1000));
+ CullRect cull_rect3(IntRect(0, 0, 100, 200));
+ // Use the new cull rect if it changed enough.
+ cull_rect3.ApplyTransforms(t1.get(), scroll_translation2.get(),
+ old_cull_rect);
+ EXPECT_EQ(cull_rect1, cull_rect3);
}
TEST_F(CullRectTest, IntersectsVerticalRange) {
@@ -65,18 +450,4 @@ TEST_F(CullRectTest, IntersectsHorizontalRange) {
cull_rect.IntersectsHorizontalRange(LayoutUnit(50), LayoutUnit(51)));
}
-TEST_F(CullRectTest, UpdateForScrollingContents) {
- ScopedSlimmingPaintV2ForTest spv2(true);
-
- CullRect cull_rect(IntRect(0, 0, 50, 100));
- AffineTransform transform;
- transform.Translate(10, 15);
- cull_rect.UpdateForScrollingContents(IntRect(20, 10, 40, 50), transform);
-
- // Clipped: (20, 10, 30, 50)
- // Expanded: (-3980, -3990, 8030, 8050)
- // Inverse transformed: (-3990, -4005, 8030, 8050)
- EXPECT_EQ(IntRect(-3990, -4005, 8030, 8050), Rect(cull_rect));
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.cc
index 5f5984a09b7..8077c0e9b3a 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.cc
@@ -26,9 +26,9 @@ static WTF::String PaintPhaseAsDebugString(int paint_phase) {
case 0:
return "PaintPhaseBlockBackground";
case 1:
- return "PaintPhaseSelfBlockBackground";
+ return "PaintPhaseSelfBlockBackgroundOnly";
case 2:
- return "PaintPhaseChildBlockBackgrounds";
+ return "PaintPhaseDescendantBlockBackgroundsOnly";
case 3:
return "PaintPhaseFloat";
case 4:
@@ -36,9 +36,9 @@ static WTF::String PaintPhaseAsDebugString(int paint_phase) {
case 5:
return "PaintPhaseOutline";
case 6:
- return "PaintPhaseSelfOutline";
+ return "PaintPhaseSelfOutlineOnly";
case 7:
- return "PaintPhaseChildOutlines";
+ return "PaintPhaseDescendantOutlinesOnly";
case 8:
return "PaintPhaseSelection";
case 9:
@@ -88,6 +88,7 @@ static WTF::String SpecialDrawingTypeAsDebugString(DisplayItem::Type type) {
DEBUG_STRING_CASE(PopupListBoxRow);
DEBUG_STRING_CASE(PrintedContentDestinationLocations);
DEBUG_STRING_CASE(PrintedContentPDFURLRect);
+ DEBUG_STRING_CASE(ReflectionMask);
DEBUG_STRING_CASE(Resizer);
DEBUG_STRING_CASE(SVGClip);
DEBUG_STRING_CASE(SVGFilter);
@@ -107,10 +108,8 @@ static WTF::String SpecialDrawingTypeAsDebugString(DisplayItem::Type type) {
DEBUG_STRING_CASE(SelectionTint);
DEBUG_STRING_CASE(TableCollapsedBorders);
DEBUG_STRING_CASE(VideoBitmap);
- DEBUG_STRING_CASE(WebPlugin);
DEBUG_STRING_CASE(WebFont);
- DEBUG_STRING_CASE(ReflectionMask);
- DEBUG_STRING_CASE(HitTest);
+ DEBUG_STRING_CASE(WebPlugin);
DEFAULT_CASE;
}
@@ -146,6 +145,7 @@ WTF::String DisplayItem::TypeAsDebugString(Type type) {
PAINT_PHASE_BASED_DEBUG_STRINGS(SVGEffect);
switch (type) {
+ DEBUG_STRING_CASE(HitTest);
DEBUG_STRING_CASE(ScrollHitTest);
DEBUG_STRING_CASE(LayerChunkBackground);
DEBUG_STRING_CASE(LayerChunkNegativeZOrderChildren);
@@ -174,16 +174,36 @@ void DisplayItem::PropertiesAsJSON(JSONObject& json) const {
json.SetDouble("outset", OutsetForRasterEffects());
}
-#endif
+#endif // DCHECK_IS_ON()
String DisplayItem::Id::ToString() const {
#if DCHECK_IS_ON()
- return String::Format("%p:%s:%d", &client,
- DisplayItem::TypeAsDebugString(type).Ascii().data(),
+ return String::Format("%s:%s:%d", client.ToString().Utf8().data(),
+ DisplayItem::TypeAsDebugString(type).Utf8().data(),
fragment);
#else
return String::Format("%p:%d:%d", &client, static_cast<int>(type), fragment);
#endif
}
+std::ostream& operator<<(std::ostream& os, DisplayItem::Type type) {
+#if DCHECK_IS_ON()
+ return os << DisplayItem::TypeAsDebugString(type).Utf8().data();
+#else
+ return os << static_cast<int>(type);
+#endif
+}
+
+std::ostream& operator<<(std::ostream& os, const DisplayItem::Id& id) {
+ return os << id.ToString().Utf8().data();
+}
+
+std::ostream& operator<<(std::ostream& os, const DisplayItem& item) {
+#if DCHECK_IS_ON()
+ return os << item.AsDebugString().Utf8().data();
+#else
+ return os << "{\"id\": " << item.GetId() << "}";
+#endif
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.h b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.h
index 1304ddda638..e0ff93900e2 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item.h
@@ -81,6 +81,7 @@ class PLATFORM_EXPORT DisplayItem {
kPopupListBoxRow,
kPrintedContentDestinationLocations,
kPrintedContentPDFURLRect,
+ kReflectionMask,
kResizer,
kSVGClip,
kSVGFilter,
@@ -100,15 +101,9 @@ class PLATFORM_EXPORT DisplayItem {
kSelectionTint,
kTableCollapsedBorders,
kVideoBitmap,
- kWebPlugin,
kWebFont,
- kReflectionMask,
- // Compositor hit testing requires that layers are created and sized to
- // include content that does not paint. Hit test display items ensure
- // a layer exists and is sized properly even if no content would otherwise
- // be painted.
- kHitTest,
- kDrawingLast = kHitTest,
+ kWebPlugin,
+ kDrawingLast = kWebPlugin,
kForeignLayerFirst,
kForeignLayerCanvas = kForeignLayerFirst,
@@ -131,6 +126,12 @@ class PLATFORM_EXPORT DisplayItem {
kSVGEffectPaintPhaseFirst,
kSVGEffectPaintPhaseLast = kSVGEffectPaintPhaseFirst + kPaintPhaseMax,
+ // Compositor hit testing requires that layers are created and sized to
+ // include content that does not paint. Hit test display items ensure
+ // a layer exists and is sized properly even if no content would otherwise
+ // be painted.
+ kHitTest,
+
kScrollHitTest,
kLayerChunkBackground,
@@ -151,15 +152,14 @@ class PLATFORM_EXPORT DisplayItem {
visual_rect_(client.VisualRect()),
outset_for_raster_effects_(client.VisualRectOutsetForRasterEffects()),
type_(type),
- derived_size_(derived_size),
fragment_(0),
- // TODO(pdr): Should this return true for IsScrollHitTestType too?
- is_cacheable_(client.IsCacheable() && IsDrawingType(type)),
+ is_cacheable_(client.IsCacheable()),
is_tombstone_(false) {
// |derived_size| must fit in |derived_size_|.
// If it doesn't, enlarge |derived_size_| and fix this assert.
SECURITY_DCHECK(derived_size < (1 << 8));
SECURITY_DCHECK(derived_size >= sizeof(*this));
+ derived_size_ = static_cast<unsigned>(derived_size);
}
virtual ~DisplayItem() = default;
@@ -196,7 +196,7 @@ class PLATFORM_EXPORT DisplayItem {
// Visual rect can change without needing invalidation of the client, e.g.
// when ancestor clip changes. This is called from PaintController::
- // UseCachedDrawingIfPossible() to update the visual rect of a cached display
+ // UseCachedItemIfPossible() to update the visual rect of a cached display
// item.
void UpdateVisualRect() { visual_rect_ = FloatRect(client_->VisualRect()); }
@@ -225,20 +225,20 @@ class PLATFORM_EXPORT DisplayItem {
// See comments of enum Type for usage of the following macros.
#define DEFINE_CATEGORY_METHODS(Category) \
- static bool Is##Category##Type(Type type) { \
+ static constexpr bool Is##Category##Type(Type type) { \
return type >= k##Category##First && type <= k##Category##Last; \
} \
bool Is##Category() const { return Is##Category##Type(GetType()); }
-#define DEFINE_PAINT_PHASE_CONVERSION_METHOD(Category) \
- static Type PaintPhaseTo##Category##Type(PaintPhase paint_phase) { \
- static_assert( \
- k##Category##PaintPhaseLast - k##Category##PaintPhaseFirst == \
- kPaintPhaseMax, \
- "Invalid paint-phase-based category " #Category \
- ". See comments of DisplayItem::Type"); \
- return static_cast<Type>(static_cast<int>(paint_phase) + \
- k##Category##PaintPhaseFirst); \
+#define DEFINE_PAINT_PHASE_CONVERSION_METHOD(Category) \
+ static constexpr Type PaintPhaseTo##Category##Type(PaintPhase paint_phase) { \
+ static_assert( \
+ k##Category##PaintPhaseLast - k##Category##PaintPhaseFirst == \
+ kPaintPhaseMax, \
+ "Invalid paint-phase-based category " #Category \
+ ". See comments of DisplayItem::Type"); \
+ return static_cast<Type>(static_cast<int>(paint_phase) + \
+ k##Category##PaintPhaseFirst); \
}
DEFINE_CATEGORY_METHODS(Drawing)
@@ -251,9 +251,11 @@ class PLATFORM_EXPORT DisplayItem {
DEFINE_PAINT_PHASE_CONVERSION_METHOD(SVGTransform)
DEFINE_PAINT_PHASE_CONVERSION_METHOD(SVGEffect)
+ bool IsHitTest() const { return type_ == kHitTest; }
bool IsScrollHitTest() const { return type_ == kScrollHitTest; }
bool IsCacheable() const { return is_cacheable_; }
+ void SetUncacheable() { is_cacheable_ = false; }
virtual bool Equals(const DisplayItem& other) const {
// Failure of this DCHECK would cause bad casts in subclasses.
@@ -308,6 +310,10 @@ inline bool operator!=(const DisplayItem::Id& a, const DisplayItem::Id& b) {
return !(a == b);
}
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, DisplayItem::Type);
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, const DisplayItem::Id&);
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, const DisplayItem&);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_DISPLAY_ITEM_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc
index c739385ef21..3888b08e3a6 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.cc
@@ -30,21 +30,39 @@ bool DisplayItemClient::IsAlive() const {
g_live_display_item_clients->Contains(this);
}
-String DisplayItemClient::SafeDebugName(const DisplayItemClient& client,
- bool known_to_be_safe) {
+String DisplayItemClient::SafeDebugName(bool known_to_be_safe) const {
if (known_to_be_safe) {
- DCHECK(client.IsAlive());
- return client.DebugName();
+ DCHECK(IsAlive());
+ return DebugName();
}
// If the caller is not sure, we must ensure the client is alive, and it's
// not a destroyed client at the same address of a new client.
- if (client.IsAlive() && !client.IsJustCreated())
- return client.DebugName();
-
+ if (IsJustCreated())
+ return "Just created:" + DebugName();
+ if (IsAlive())
+ return DebugName();
return "DEAD";
}
#endif // DCHECK_IS_ON()
+String DisplayItemClient::ToString() const {
+#if DCHECK_IS_ON()
+ return String::Format("%p:%s", this, SafeDebugName().Utf8().data());
+#else
+ return String::Format("%p", this);
+#endif
+}
+
+std::ostream& operator<<(std::ostream& out, const DisplayItemClient& client) {
+ return out << client.ToString();
+}
+
+std::ostream& operator<<(std::ostream& out, const DisplayItemClient* client) {
+ if (!client)
+ return out << "<null>";
+ return out << *client;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.h b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.h
index 2d6ec1cf10c..27a43f1627d 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_client.h
@@ -36,7 +36,7 @@ class PLATFORM_EXPORT DisplayItemClient {
// Tests if this DisplayItemClient object has been created and has not been
// deleted yet.
bool IsAlive() const;
- static String SafeDebugName(const DisplayItemClient&, bool known_to_be_safe);
+ String SafeDebugName(bool known_to_be_safe = false) const;
#endif
virtual String DebugName() const = 0;
@@ -114,6 +114,8 @@ class PLATFORM_EXPORT DisplayItemClient {
return paint_invalidation_reason_ == PaintInvalidationReason::kNone;
}
+ String ToString() const;
+
private:
friend class FakeDisplayItemClient;
friend class PaintController;
@@ -141,6 +143,11 @@ inline bool operator!=(const DisplayItemClient& client1,
return &client1 != &client2;
}
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&,
+ const DisplayItemClient*);
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&,
+ const DisplayItemClient&);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_DISPLAY_ITEM_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.cc
index 6bd2940d364..c77aa88fd87 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.cc
@@ -41,17 +41,18 @@ void DisplayItemList::AppendSubsequenceAsJSON(size_t begin_index,
std::unique_ptr<JSONObject> json = JSONObject::Create();
const auto& item = (*this)[i];
- if ((flags & kSkipNonDrawings) && !item.IsDrawing())
- continue;
-
json->SetInteger("index", i);
if (flags & kShownOnlyDisplayItemTypes) {
json->SetString("type", DisplayItem::TypeAsDebugString(item.GetType()));
} else {
- json->SetString("clientDebugName",
- DisplayItemClient::SafeDebugName(
- item.Client(), flags & kClientKnownToBeAlive));
+ json->SetString("clientDebugName", item.Client().SafeDebugName(
+ flags & kClientKnownToBeAlive));
+ if (flags & kClientKnownToBeAlive) {
+ json->SetString("invalidation",
+ PaintInvalidationReasonToString(
+ item.Client().GetPaintInvalidationReason()));
+ }
item.PropertiesAsJSON(*json);
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.h b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.h
index 5a6df085081..c6c87fb3fe6 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/display_item_list.h
@@ -7,8 +7,7 @@
#include "third_party/blink/renderer/platform/graphics/contiguous_container.h"
#include "third_party/blink/renderer/platform/graphics/paint/display_item.h"
-#include "third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -20,9 +19,8 @@ struct PaintChunk;
// each derived display item; the ideal value is the least common multiple.
// The validity of kDisplayItemAlignment and kMaximumDisplayItemSize are checked
// in PaintController::CreateAndAppend().
-static const size_t kDisplayItemAlignment =
- WTF_ALIGN_OF(ForeignLayerDisplayItem);
-static const size_t kMaximumDisplayItemSize = sizeof(ForeignLayerDisplayItem);
+static const size_t kDisplayItemAlignment = alignof(HitTestDisplayItem);
+static const size_t kMaximumDisplayItemSize = sizeof(HitTestDisplayItem);
// A container for a list of display items.
class PLATFORM_EXPORT DisplayItemList
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h
index 00cf611d07d..dd79922e214 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h
@@ -31,12 +31,12 @@ class PLATFORM_EXPORT DrawingDisplayItem final : public DisplayItem {
DrawingDisplayItem(const DisplayItemClient& client,
Type type,
sk_sp<const PaintRecord> record,
- bool known_to_be_opaque);
+ bool known_to_be_opaque = false);
- void Replay(GraphicsContext&) const override;
+ void Replay(GraphicsContext&) const final;
void AppendToDisplayItemList(const FloatSize& visual_rect_offset,
- cc::DisplayItemList&) const override;
- bool DrawsContent() const override;
+ cc::DisplayItemList&) const final;
+ bool DrawsContent() const final;
const sk_sp<const PaintRecord>& GetPaintRecord() const { return record_; }
@@ -49,7 +49,7 @@ class PLATFORM_EXPORT DrawingDisplayItem final : public DisplayItem {
private:
#if DCHECK_IS_ON()
- void PropertiesAsJSON(JSONObject&) const override;
+ void PropertiesAsJSON(JSONObject&) const final;
#endif
sk_sp<const PaintRecord> record_;
@@ -63,7 +63,7 @@ DISABLE_CFI_PERF
inline DrawingDisplayItem::DrawingDisplayItem(const DisplayItemClient& client,
Type type,
sk_sp<const PaintRecord> record,
- bool known_to_be_opaque = false)
+ bool known_to_be_opaque)
: DisplayItem(client, type, sizeof(*this)),
record_(record && record->size() ? std::move(record) : nullptr),
known_to_be_opaque_(known_to_be_opaque) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc
index 323eb4aef18..ed2b6bf2f39 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.cc
@@ -34,7 +34,7 @@ DrawingRecorder::DrawingRecorder(GraphicsContext& context,
if (context.GetPaintController().DisplayItemConstructionIsDisabled())
return;
- // Must check DrawingRecorder::useCachedDrawingIfPossible before creating the
+ // Must check DrawingRecorder::UseCachedDrawingIfPossible before creating the
// DrawingRecorder.
DCHECK(RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() ||
!UseCachedDrawingIfPossible(context_, client_, type_));
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h
index 5fd1b94aab5..e51a61abb9f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h
@@ -27,8 +27,7 @@ class PLATFORM_EXPORT DrawingRecorder final {
static bool UseCachedDrawingIfPossible(GraphicsContext& context,
const DisplayItemClient& client,
DisplayItem::Type type) {
- return context.GetPaintController().UseCachedDrawingIfPossible(client,
- type);
+ return context.GetPaintController().UseCachedItemIfPossible(client, type);
}
static bool UseCachedDrawingIfPossible(GraphicsContext& context,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder_test.cc
index 37f21620734..7d9ded94e6b 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/drawing_recorder_test.cc
@@ -9,6 +9,8 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h"
#include "third_party/blink/renderer/platform/testing/fake_display_item_client.h"
+using testing::ElementsAre;
+
namespace blink {
using DrawingRecorderTest = PaintControllerTestBase;
@@ -23,8 +25,8 @@ TEST_F(DrawingRecorderTest, Nothing) {
InitRootChunk();
DrawNothing(context, client, kForegroundType);
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kForegroundType)));
EXPECT_FALSE(static_cast<const DrawingDisplayItem&>(
GetPaintController().GetDisplayItemList()[0])
.GetPaintRecord());
@@ -36,8 +38,8 @@ TEST_F(DrawingRecorderTest, Rect) {
InitRootChunk();
DrawRect(context, client, kForegroundType, kBounds);
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kForegroundType)));
}
TEST_F(DrawingRecorderTest, Cached) {
@@ -48,9 +50,9 @@ TEST_F(DrawingRecorderTest, Cached) {
DrawRect(context, client, kForegroundType, kBounds);
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(client, kBackgroundType),
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType),
+ IsSameId(&client, kForegroundType)));
InitRootChunk();
DrawNothing(context, client, kBackgroundType);
@@ -60,9 +62,9 @@ TEST_F(DrawingRecorderTest, Cached) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(client, kBackgroundType),
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType),
+ IsSameId(&client, kForegroundType)));
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc
index 668d4dd6f49..29c7300ca2d 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc
@@ -32,21 +32,25 @@ FloatRect EffectPaintPropertyNode::MapRect(const FloatRect& input_rect) const {
bool EffectPaintPropertyNode::Changed(
const PropertyTreeState& relative_to_state,
const TransformPaintPropertyNode* transform_not_to_check) const {
- auto* relative_effect = relative_to_state.Effect()
- ? relative_to_state.Effect()->Unalias()
- : nullptr;
- if (transform_not_to_check)
- transform_not_to_check = transform_not_to_check->Unalias();
- for (const auto* node = Unalias(); node && node != relative_effect;
- node = node->Parent() ? node->Parent()->Unalias() : nullptr) {
+ auto* relative_effect = relative_to_state.Effect();
+ auto* relative_transform = relative_to_state.Transform();
+
+ // Note that we can't unalias nodes in the loop conditions, since we need to
+ // check NodeChanged() function on aliased nodes as well (since the parenting
+ // might change).
+ for (const auto* node = this; node && node != relative_effect;
+ node = node->Parent()) {
if (node->NodeChanged())
return true;
- auto* local_transform = node->LocalTransformSpace()
- ? node->LocalTransformSpace()->Unalias()
- : nullptr;
+
+ // We shouldn't check state on aliased nodes, other than NodeChanged().
+ if (node->IsParentAlias())
+ continue;
+
+ auto* local_transform = node->LocalTransformSpace();
if (node->HasFilterThatMovesPixels() &&
local_transform != transform_not_to_check &&
- local_transform->Changed(*relative_to_state.Transform()->Unalias())) {
+ local_transform->Changed(*relative_transform)) {
return true;
}
// We don't check for change of OutputClip here to avoid N^3 complexity.
@@ -69,6 +73,8 @@ std::unique_ptr<JSONObject> EffectPaintPropertyNode::ToJSON() const {
json->SetInteger("colorFilter", state_.color_filter);
if (!state_.filter.IsEmpty())
json->SetString("filter", state_.filter.ToString());
+ if (!state_.backdrop_filter.IsEmpty())
+ json->SetString("backdrop_filter", state_.backdrop_filter.ToString());
if (state_.opacity != 1.0f)
json->SetDouble("opacity", state_.opacity);
if (state_.blend_mode != SkBlendMode::kSrcOver)
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h b/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h
index ac03328e909..09473c1ccdc 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h
@@ -43,6 +43,7 @@ class PLATFORM_EXPORT EffectPaintPropertyNode
ColorFilter color_filter = kColorFilterNone;
CompositorFilterOperations filter;
float opacity = 1;
+ CompositorFilterOperations backdrop_filter;
SkBlendMode blend_mode = SkBlendMode::kSrcOver;
// === End of effects ===
CompositingReasons direct_compositing_reasons = CompositingReason::kNone;
@@ -54,6 +55,7 @@ class PLATFORM_EXPORT EffectPaintPropertyNode
return local_transform_space == o.local_transform_space &&
output_clip == o.output_clip && color_filter == o.color_filter &&
filter == o.filter && opacity == o.opacity &&
+ backdrop_filter == o.backdrop_filter &&
blend_mode == o.blend_mode &&
direct_compositing_reasons == o.direct_compositing_reasons &&
compositor_element_id == o.compositor_element_id &&
@@ -124,6 +126,10 @@ class PLATFORM_EXPORT EffectPaintPropertyNode
return state_.color_filter;
}
+ const CompositorFilterOperations& BackdropFilter() const {
+ return state_.backdrop_filter;
+ }
+
bool HasFilterThatMovesPixels() const {
DCHECK(!Parent() || !IsParentAlias());
return state_.filter.HasFilterThatMovesPixels();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc
index 360913c2920..810f41d8b6c 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.cc
@@ -13,23 +13,47 @@
namespace blink {
-ForeignLayerDisplayItem::ForeignLayerDisplayItem(
- const DisplayItemClient& client,
- Type type,
- scoped_refptr<cc::Layer> layer,
- const FloatPoint& location,
- const IntSize& bounds)
- : DisplayItem(client, type, sizeof(*this)),
- layer_(std::move(layer)),
- location_(location),
- bounds_(bounds) {
+namespace {
+
+class ForeignLayerDisplayItemClient final : public DisplayItemClient {
+ public:
+ ForeignLayerDisplayItemClient(scoped_refptr<cc::Layer> layer)
+ : layer_(std::move(layer)) {}
+
+ String DebugName() const final { return "ForeignLayer"; }
+
+ LayoutRect VisualRect() const final {
+ const auto& offset = layer_->offset_to_transform_parent();
+ return LayoutRect(LayoutPoint(offset.x(), offset.y()),
+ LayoutSize(IntSize(layer_->bounds())));
+ }
+
+ cc::Layer* GetLayer() const { return layer_.get(); }
+
+ private:
+ scoped_refptr<cc::Layer> layer_;
+};
+
+} // anonymous namespace
+
+ForeignLayerDisplayItem::ForeignLayerDisplayItem(Type type,
+ scoped_refptr<cc::Layer> layer)
+ : DisplayItem(*new ForeignLayerDisplayItemClient(std::move(layer)),
+ type,
+ sizeof(*this)) {
DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled());
DCHECK(IsForeignLayerType(type));
- DCHECK(layer_);
+ DCHECK(GetLayer());
}
-ForeignLayerDisplayItem::~ForeignLayerDisplayItem() = default;
+ForeignLayerDisplayItem::~ForeignLayerDisplayItem() {
+ delete &Client();
+}
+
+cc::Layer* ForeignLayerDisplayItem::GetLayer() const {
+ return static_cast<const ForeignLayerDisplayItemClient&>(Client()).GetLayer();
+}
void ForeignLayerDisplayItem::Replay(GraphicsContext&) const {
NOTREACHED();
@@ -42,33 +66,31 @@ void ForeignLayerDisplayItem::AppendToDisplayItemList(
}
bool ForeignLayerDisplayItem::DrawsContent() const {
- return true;
+ return false;
}
bool ForeignLayerDisplayItem::Equals(const DisplayItem& other) const {
return DisplayItem::Equals(other) &&
- layer_ == static_cast<const ForeignLayerDisplayItem&>(other).layer_;
+ GetLayer() ==
+ static_cast<const ForeignLayerDisplayItem&>(other).GetLayer();
}
#if DCHECK_IS_ON()
void ForeignLayerDisplayItem::PropertiesAsJSON(JSONObject& json) const {
DisplayItem::PropertiesAsJSON(json);
- json.SetInteger("layer", layer_->id());
+ json.SetInteger("layer", GetLayer()->id());
}
#endif
void RecordForeignLayer(GraphicsContext& context,
- const DisplayItemClient& client,
DisplayItem::Type type,
- scoped_refptr<cc::Layer> layer,
- const FloatPoint& location,
- const IntSize& bounds) {
+ scoped_refptr<cc::Layer> layer) {
PaintController& paint_controller = context.GetPaintController();
if (paint_controller.DisplayItemConstructionIsDisabled())
return;
- paint_controller.CreateAndAppend<ForeignLayerDisplayItem>(
- client, type, std::move(layer), location, bounds);
+ paint_controller.CreateAndAppend<ForeignLayerDisplayItem>(type,
+ std::move(layer));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h b/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h
index 6d7e51e1d34..6b42d096d78 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h
@@ -21,16 +21,10 @@ class GraphicsContext;
// GraphicsLayer tree.
class PLATFORM_EXPORT ForeignLayerDisplayItem final : public DisplayItem {
public:
- ForeignLayerDisplayItem(const DisplayItemClient&,
- Type,
- scoped_refptr<cc::Layer>,
- const FloatPoint& location,
- const IntSize& bounds);
+ ForeignLayerDisplayItem(Type, scoped_refptr<cc::Layer>);
~ForeignLayerDisplayItem() override;
- cc::Layer* GetLayer() const { return layer_.get(); }
- const FloatPoint& Location() const { return location_; }
- const IntSize& Bounds() const { return bounds_; }
+ cc::Layer* GetLayer() const;
// DisplayItem
void Replay(GraphicsContext&) const override;
@@ -41,21 +35,13 @@ class PLATFORM_EXPORT ForeignLayerDisplayItem final : public DisplayItem {
#if DCHECK_IS_ON()
void PropertiesAsJSON(JSONObject&) const override;
#endif
-
- private:
- scoped_refptr<cc::Layer> layer_;
- FloatPoint location_;
- IntSize bounds_;
};
// Records a foreign layer into a GraphicsContext.
// Use this where you would use a recorder class.
PLATFORM_EXPORT void RecordForeignLayer(GraphicsContext&,
- const DisplayItemClient&,
DisplayItem::Type,
- scoped_refptr<cc::Layer>,
- const FloatPoint& location,
- const IntSize& bounds);
+ scoped_refptr<cc::Layer>);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc
index d173cfe91a2..24bae6a33f5 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc
@@ -281,13 +281,13 @@ bool GeometryMapper::SlowLocalToAncestorVisualRectWithEffects(
PropertyTreeState final_transform_and_clip_state(
ancestor_state.Transform(), ancestor_state.Clip(), nullptr);
- LocalToAncestorVisualRectInternal(
+ bool intersects = LocalToAncestorVisualRectInternal(
last_transform_and_clip_state, final_transform_and_clip_state,
mapping_rect, clip_behavior, inclusive_behavior, success);
// Many effects (e.g. filters, clip-paths) can make a clip rect not tight.
mapping_rect.ClearIsTight();
- return true;
+ return intersects;
}
FloatClipRect GeometryMapper::LocalToAncestorClipRect(
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc
index 0a7fc36db5d..4803e356871 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc
@@ -53,16 +53,16 @@ class GeometryMapperTest : public testing::Test,
INSTANTIATE_PAINT_TEST_CASE_P(GeometryMapperTest);
-#define EXPECT_FLOAT_RECT_NEAR(expected, actual) \
- do { \
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, (actual).X(), \
- (expected).X()); \
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, (actual).Y(), \
- (expected).Y()); \
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, (actual).Width(), \
- (expected).Width()); \
- EXPECT_PRED_FORMAT2(GeometryTest::AssertAlmostEqual, (actual).Height(), \
- (expected).Height()); \
+#define EXPECT_FLOAT_RECT_NEAR(expected, actual) \
+ do { \
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, (actual).X(), \
+ (expected).X()); \
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, (actual).Y(), \
+ (expected).Y()); \
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, (actual).Width(), \
+ (expected).Width()); \
+ EXPECT_PRED_FORMAT2(geometry_test::AssertAlmostEqual, (actual).Height(), \
+ (expected).Height()); \
} while (false)
#define EXPECT_CLIP_RECT_EQ(expected, actual) \
@@ -394,6 +394,37 @@ TEST_P(GeometryMapperTest, SimpleClipInclusiveIntersect) {
EXPECT_CLIP_RECT_EQ(FloatClipRect(FloatRect()), actual_clip_rect);
}
+TEST_P(GeometryMapperTest, SimpleClipPlusOpacity) {
+ auto clip = CreateClip(c0(), &t0(), FloatRoundedRect(10, 10, 50, 50));
+ local_state.SetClip(clip.get());
+
+ auto opacity = CreateOpacityEffect(e0(), 0.99);
+ local_state.SetEffect(opacity.get());
+
+ FloatClipRect actual_clip_rect(FloatRect(60, 10, 10, 10));
+ auto intersects = GeometryMapper::LocalToAncestorVisualRect(
+ local_state, ancestor_state, actual_clip_rect);
+
+ EXPECT_TRUE(actual_clip_rect.Rect().IsEmpty());
+ EXPECT_FALSE(intersects);
+}
+
+TEST_P(GeometryMapperTest, SimpleClipPlusOpacityInclusiveIntersect) {
+ auto clip = CreateClip(c0(), &t0(), FloatRoundedRect(10, 10, 50, 50));
+ local_state.SetClip(clip.get());
+
+ auto opacity = CreateOpacityEffect(e0(), 0.99);
+ local_state.SetEffect(opacity.get());
+
+ FloatClipRect actual_clip_rect(FloatRect(10, 10, 10, 0));
+ auto intersects = GeometryMapper::LocalToAncestorVisualRect(
+ local_state, ancestor_state, actual_clip_rect,
+ kIgnorePlatformOverlayScrollbarSize, kInclusiveIntersect);
+
+ EXPECT_TRUE(actual_clip_rect.Rect().IsEmpty());
+ EXPECT_TRUE(intersects);
+}
+
TEST_P(GeometryMapperTest, RoundedClip) {
FloatRoundedRect rect(FloatRect(10, 10, 50, 50),
FloatRoundedRect::Radii(FloatSize(1, 1), FloatSize(),
@@ -743,7 +774,7 @@ TEST_P(GeometryMapperTest, FilterWithClipsAndTransformsWithAlias) {
TEST_P(GeometryMapperTest, ReflectionWithPaintOffset) {
CompositorFilterOperations filters;
- filters.AppendReferenceFilter(PaintFilterBuilder::BuildBoxReflectFilter(
+ filters.AppendReferenceFilter(paint_filter_builder::BuildBoxReflectFilter(
BoxReflection(BoxReflection::kHorizontalReflection, 0), nullptr));
auto effect = CreateFilterEffect(e0(), filters, FloatPoint(100, 100));
local_state.SetEffect(effect.get());
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc
index 6bfc25d4114..2bd6a070535 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.cc
@@ -4,32 +4,61 @@
#include "third_party/blink/renderer/platform/graphics/paint/hit_test_data.h"
-#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
-#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
-#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
-void HitTestData::RecordHitTestRect(GraphicsContext& context,
- const DisplayItemClient& client,
- const HitTestRect& action) {
- DCHECK(RuntimeEnabledFeatures::PaintTouchActionRectsEnabled());
-
- PaintController& paint_controller = context.GetPaintController();
- if (paint_controller.DisplayItemConstructionIsDisabled())
- return;
-
- if (!paint_controller.UseCachedDrawingIfPossible(client,
- DisplayItem::kHitTest)) {
- // A display item must be created to ensure a paint chunk exists. For
- // example, without this, an empty div with a transform will incorrectly use
- // the parent paint chunk instead of creating a new one.
- paint_controller.CreateAndAppend<DrawingDisplayItem>(
- client, DisplayItem::kHitTest, nullptr, false);
+static String HitTestRectsAsString(HitTestRects rects) {
+ StringBuilder sb;
+ sb.Append("[");
+ bool first = true;
+ for (const auto& rect : rects) {
+ if (!first)
+ sb.Append(", ");
+ first = false;
+ sb.Append("(");
+ sb.Append(rect.ToString());
+ sb.Append(")");
}
+ sb.Append("]");
+ return sb.ToString();
+}
+
+String HitTestData::ToString() const {
+ StringBuilder sb;
+ sb.Append("{");
+
+ bool printed_top_level_field = false;
+ if (!touch_action_rects.IsEmpty()) {
+ sb.Append("touch_action_rects: ");
+ sb.Append(HitTestRectsAsString(touch_action_rects));
+ printed_top_level_field = true;
+ }
+
+ if (!wheel_event_handler_region.IsEmpty()) {
+ if (printed_top_level_field)
+ sb.Append(", ");
+ sb.Append("wheel_event_handler_region: ");
+ sb.Append(HitTestRectsAsString(wheel_event_handler_region));
+ printed_top_level_field = true;
+ }
+
+ if (!non_fast_scrollable_region.IsEmpty()) {
+ if (printed_top_level_field)
+ sb.Append(", ");
+ sb.Append("non_fast_scrollable_region: ");
+ sb.Append(HitTestRectsAsString(non_fast_scrollable_region));
+ printed_top_level_field = true;
+ }
+
+ sb.Append("}");
+
+ return sb.ToString();
+}
- auto& chunk = paint_controller.CurrentPaintChunk();
- chunk.EnsureHitTestData().touch_action_rects.push_back(action);
+std::ostream& operator<<(std::ostream& os, const HitTestData& data) {
+ return os << data.ToString().Utf8().data();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.h b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.h
index 492effc7b15..3c2c0865d2d 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_data.h
@@ -5,15 +5,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_HIT_TEST_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_HIT_TEST_DATA_H_
-#include "third_party/blink/renderer/platform/geometry/region.h"
#include "third_party/blink/renderer/platform/graphics/hit_test_rect.h"
#include "third_party/blink/renderer/platform/platform_export.h"
namespace blink {
-class DisplayItemClient;
-class GraphicsContext;
-
using HitTestRects = Vector<HitTestRect>;
struct PLATFORM_EXPORT HitTestData {
@@ -33,16 +29,18 @@ struct PLATFORM_EXPORT HitTestData {
non_fast_scrollable_region == rhs.non_fast_scrollable_region;
}
+ void Append(const HitTestRect& rect) {
+ // TODO(836905): Support other types of hit testing.
+ touch_action_rects.push_back(rect);
+ }
+
bool operator!=(const HitTestData& rhs) const { return !(*this == rhs); }
- // Records a display item for hit testing to ensure a paint chunk exists and
- // is sized to include hit test rects, then adds the hit test rect to
- // |HitTestData.touch_action_rects|.
- static void RecordHitTestRect(GraphicsContext&,
- const DisplayItemClient&,
- const HitTestRect&);
+ String ToString() const;
};
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, const HitTestData&);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_HIT_TEST_DATA_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.cc
new file mode 100644
index 00000000000..bd1f4432f8a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.cc
@@ -0,0 +1,40 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
+
+#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
+#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
+
+namespace blink {
+
+void HitTestDisplayItem::Record(GraphicsContext& context,
+ const DisplayItemClient& client,
+ const HitTestRect& hit_test_rect) {
+ DCHECK(RuntimeEnabledFeatures::PaintTouchActionRectsEnabled());
+
+ auto& paint_controller = context.GetPaintController();
+ if (paint_controller.DisplayItemConstructionIsDisabled())
+ return;
+
+ if (paint_controller.UseCachedItemIfPossible(client, DisplayItem::kHitTest))
+ return;
+
+ paint_controller.CreateAndAppend<HitTestDisplayItem>(client, hit_test_rect);
+}
+
+#if DCHECK_IS_ON()
+void HitTestDisplayItem::PropertiesAsJSON(JSONObject& json) const {
+ DisplayItem::PropertiesAsJSON(json);
+ json.SetString("hitTestRect", hit_test_rect_.ToString());
+}
+#endif
+
+bool HitTestDisplayItem::Equals(const DisplayItem& other) const {
+ return DisplayItem::Equals(other) &&
+ hit_test_rect_ ==
+ static_cast<const HitTestDisplayItem&>(other).hit_test_rect_;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h
new file mode 100644
index 00000000000..51af360bd8f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h
@@ -0,0 +1,42 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_HIT_TEST_DISPLAY_ITEM_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_HIT_TEST_DISPLAY_ITEM_H_
+
+#include "third_party/blink/renderer/platform/graphics/paint/display_item.h"
+
+#include "third_party/blink/renderer/platform/graphics/hit_test_rect.h"
+
+namespace blink {
+
+// A special DisplayItem containing hit test data.
+class PLATFORM_EXPORT HitTestDisplayItem final : public DisplayItem {
+ public:
+ HitTestDisplayItem(const DisplayItemClient& client,
+ const HitTestRect& hit_test_rect)
+ : DisplayItem(client, kHitTest, sizeof(*this)),
+ hit_test_rect_(hit_test_rect) {
+ DCHECK(RuntimeEnabledFeatures::PaintTouchActionRectsEnabled());
+ }
+
+ const HitTestRect& GetHitTestRect() const { return hit_test_rect_; }
+
+ static void Record(GraphicsContext&,
+ const DisplayItemClient&,
+ const HitTestRect&);
+
+ bool Equals(const DisplayItem& other) const final;
+
+ private:
+#if DCHECK_IS_ON()
+ void PropertiesAsJSON(JSONObject&) const override;
+#endif
+
+ HitTestRect hit_test_rect_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_HIT_TEST_DISPLAY_ITEM_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.cc
index d1366a474bc..f4d24ceb026 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
+#include "third_party/blink/renderer/platform/graphics/paint/hit_test_display_item.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/skia/include/core/SkRegion.h"
@@ -17,20 +18,19 @@ namespace blink {
namespace {
-void ComputeChunkBoundsAndOpaqueness(const DisplayItemList& display_items,
- Vector<PaintChunk>& paint_chunks) {
- for (PaintChunk& chunk : paint_chunks) {
- // This happens in tests testing paint chunks without display items.
- if (!chunk.size())
- continue;
-
- FloatRect bounds;
- SkRegion known_to_be_opaque_region;
- for (const DisplayItem& item : display_items.ItemsInPaintChunk(chunk)) {
- bounds.Unite(item.VisualRect());
- if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled() ||
- !item.IsDrawing())
- continue;
+void ComputeChunkDerivedData(const DisplayItemList& display_items,
+ PaintChunk& chunk) {
+ // This happens in tests testing paint chunks without display items.
+ if (!chunk.size())
+ return;
+
+ SkRegion known_to_be_opaque_region;
+ for (const DisplayItem& item : display_items.ItemsInPaintChunk(chunk)) {
+ chunk.bounds.Unite(item.VisualRect());
+ chunk.outset_for_raster_effects = std::max(chunk.outset_for_raster_effects,
+ item.OutsetForRasterEffects());
+
+ if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() && item.IsDrawing()) {
const auto& drawing = static_cast<const DrawingDisplayItem&>(item);
if (drawing.GetPaintRecord() && drawing.KnownToBeOpaque()) {
known_to_be_opaque_region.op(
@@ -38,12 +38,30 @@ void ComputeChunkBoundsAndOpaqueness(const DisplayItemList& display_items,
SkRegion::kUnion_Op);
}
}
- chunk.bounds = bounds;
- if (known_to_be_opaque_region.contains(EnclosingIntRect(bounds)))
- chunk.known_to_be_opaque = true;
+
+ if (RuntimeEnabledFeatures::PaintTouchActionRectsEnabled() &&
+ item.IsHitTest()) {
+ const auto& hit_test = static_cast<const HitTestDisplayItem&>(item);
+ if (!chunk.hit_test_data)
+ chunk.hit_test_data = std::make_unique<HitTestData>();
+ chunk.hit_test_data->Append(hit_test.GetHitTestRect());
+ }
}
+
+ if (known_to_be_opaque_region.contains(EnclosingIntRect(chunk.bounds)))
+ chunk.known_to_be_opaque = true;
}
+// For PaintArtifact::AppendDebugDrawing().
+class DebugDrawingClient final : public DisplayItemClient {
+ public:
+ DebugDrawingClient() { Invalidate(PaintInvalidationReason::kUncacheable); }
+ String DebugName() const final { return "DebugDrawing"; }
+ LayoutRect VisualRect() const final {
+ return LayoutRect(LayoutRect::InfiniteIntRect());
+ }
+};
+
} // namespace
PaintArtifact::PaintArtifact() : display_item_list_(0) {}
@@ -51,7 +69,8 @@ PaintArtifact::PaintArtifact() : display_item_list_(0) {}
PaintArtifact::PaintArtifact(DisplayItemList display_items,
Vector<PaintChunk> chunks)
: display_item_list_(std::move(display_items)), chunks_(std::move(chunks)) {
- ComputeChunkBoundsAndOpaqueness(display_item_list_, chunks_);
+ for (auto& chunk : chunks_)
+ ComputeChunkDerivedData(display_item_list_, chunk);
}
PaintArtifact::~PaintArtifact() = default;
@@ -76,6 +95,22 @@ size_t PaintArtifact::ApproximateUnsharedMemoryUsage() const {
return total_size;
}
+void PaintArtifact::AppendDebugDrawing(
+ sk_sp<const PaintRecord> record,
+ const PropertyTreeState& property_tree_state) {
+ DEFINE_STATIC_LOCAL(DebugDrawingClient, debug_drawing_client, ());
+
+ DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
+ auto& display_item =
+ display_item_list_.AllocateAndConstruct<DrawingDisplayItem>(
+ debug_drawing_client, DisplayItem::kDebugDrawing, std::move(record));
+
+ // Create a PaintChunk for the debug drawing.
+ chunks_.emplace_back(display_item_list_.size() - 1, display_item_list_.size(),
+ display_item.GetId(), property_tree_state);
+ ComputeChunkDerivedData(display_item_list_, chunks_.back());
+}
+
void PaintArtifact::Replay(GraphicsContext& graphics_context,
const PropertyTreeState& replay_state,
const IntPoint& offset) const {
@@ -103,9 +138,15 @@ void PaintArtifact::AppendToDisplayItemList(const FloatSize& visual_rect_offset,
}
void PaintArtifact::FinishCycle() {
+ // BlinkGenPropertyTrees uses PaintController::ClearPropertyTreeChangedStateTo
+ // for clearing the property tree changed state at the end of paint instead of
+ // in FinishCycle. See: LocalFrameView::RunPaintLifecyclePhase.
+ bool clear_property_tree_changed =
+ !RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled();
for (auto& chunk : chunks_) {
chunk.client_is_just_created = false;
- chunk.properties.ClearChangedToRoot();
+ if (clear_property_tree_changed)
+ chunk.properties.ClearChangedToRoot();
}
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.h
index 6214baea2f2..a4fe34d21c8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_artifact.h
@@ -54,7 +54,7 @@ class PLATFORM_EXPORT PaintArtifact final : public RefCounted<PaintArtifact> {
const Vector<PaintChunk>& PaintChunks() const { return chunks_; }
PaintChunkSubset GetPaintChunkSubset(
- const Vector<size_t>& subset_indices) const {
+ const Vector<wtf_size_t>& subset_indices) const {
return PaintChunkSubset(PaintChunks(), subset_indices);
}
@@ -67,6 +67,8 @@ class PLATFORM_EXPORT PaintArtifact final : public RefCounted<PaintArtifact> {
// shared with the embedder after copying to cc::DisplayItemList.
size_t ApproximateUnsharedMemoryUsage() const;
+ void AppendDebugDrawing(sk_sp<const PaintRecord>, const PropertyTreeState&);
+
// Draws the paint artifact to a GraphicsContext, into the ancestor state
// given by |replay_state|.
void Replay(GraphicsContext&,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc
index 799cafd9364..d109fb5931d 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_chunk.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -23,40 +24,24 @@ static_assert(sizeof(PaintChunk) == sizeof(SameSizeAsPaintChunk),
"PaintChunk should stay small");
String PaintChunk::ToString() const {
- String ret_val = String::Format(
- "PaintChunk(begin=%zu, end=%zu, id=%s cacheable=%d props=(%s) bounds=%s "
+ StringBuilder sb;
+ sb.Append("PaintChunk(");
+ sb.Append(String::Format(
+ "begin=%zu, end=%zu, id=%s cacheable=%d props=(%s) bounds=%s "
"known_to_be_opaque=%d",
- begin_index, end_index, id.ToString().Ascii().data(), is_cacheable,
- properties.ToString().Ascii().data(), bounds.ToString().Ascii().data(),
- known_to_be_opaque);
+ begin_index, end_index, id.ToString().Utf8().data(), is_cacheable,
+ properties.ToString().Utf8().data(), bounds.ToString().Utf8().data(),
+ known_to_be_opaque));
if (hit_test_data) {
- ret_val.append(String::Format(
- ", touch_action_rects=(rects: %u, bounds: %s), "
- "wheel_event_handler_region=(rects: %u, bounds: %s), "
- "non_fast_scrollable_region=(rects: %u, bounds: %s))",
- hit_test_data->touch_action_rects.size(),
- HitTestRect::GetBounds(hit_test_data->touch_action_rects)
- .ToString()
- .Ascii()
- .data(),
- hit_test_data->wheel_event_handler_region.size(),
- HitTestRect::GetBounds(hit_test_data->wheel_event_handler_region)
- .ToString()
- .Ascii()
- .data(),
- hit_test_data->non_fast_scrollable_region.size(),
- HitTestRect::GetBounds(hit_test_data->non_fast_scrollable_region)
- .ToString()
- .Ascii()
- .data()));
- } else {
- ret_val.append(")");
+ sb.Append(", hit_test_data=");
+ sb.Append(hit_test_data->ToString());
}
- return ret_val;
+ sb.Append(")");
+ return sb.ToString();
}
std::ostream& operator<<(std::ostream& os, const PaintChunk& chunk) {
- return os << chunk.ToString().Utf8().data();
+ return os << chunk.ToString().Utf8().data() << "\n";
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h
index 0bd65f75f49..4c8bb2876bc 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk.h
@@ -36,11 +36,8 @@ struct PLATFORM_EXPORT PaintChunk {
end_index(end),
id(id),
properties(props),
- outset_for_raster_effects(0),
- known_to_be_opaque(false),
is_cacheable(id.client.IsCacheable()),
- client_is_just_created(id.client.IsJustCreated()),
- hit_test_data(nullptr) {}
+ client_is_just_created(id.client.IsJustCreated()) {}
size_t size() const {
DCHECK_GE(end_index, begin_index);
@@ -66,14 +63,6 @@ struct PLATFORM_EXPORT PaintChunk {
return !client_is_just_created;
}
- HitTestData& EnsureHitTestData() {
- if (!hit_test_data)
- hit_test_data = std::make_unique<HitTestData>();
- return *hit_test_data.get();
- }
-
- HitTestData* GetHitTestData() const { return hit_test_data.get(); }
-
size_t MemoryUsageInBytes() const {
size_t total_size = sizeof(*this);
if (hit_test_data) {
@@ -84,6 +73,8 @@ struct PLATFORM_EXPORT PaintChunk {
return total_size;
}
+ String ToString() const;
+
// Index of the first drawing in this chunk.
size_t begin_index;
@@ -99,6 +90,12 @@ struct PLATFORM_EXPORT PaintChunk {
// The paint properties which apply to this chunk.
RefCountedPropertyTreeState properties;
+ // The following fields are not initialized when the chunk is created because
+ // they depend on the display items in this chunk. They are updated by the
+ // constructor of PaintArtifact.
+
+ std::unique_ptr<HitTestData> hit_test_data;
+
// The total bounds of this paint chunk's contents, in the coordinate space of
// the containing transform node.
FloatRect bounds;
@@ -106,30 +103,15 @@ struct PLATFORM_EXPORT PaintChunk {
// Some raster effects can exceed |bounds| in the rasterization space. This
// is the maximum DisplayItemClient::VisualRectOutsetForRasterEffects() of
// all clients of items in this chunk.
- float outset_for_raster_effects;
+ float outset_for_raster_effects = 0;
// True if the bounds are filled entirely with opaque contents.
- bool known_to_be_opaque : 1;
+ bool known_to_be_opaque = false;
- bool is_cacheable : 1;
-
- bool client_is_just_created : 1;
-
- String ToString() const;
-
- bool operator==(const PaintChunk& rhs) const {
- return begin_index == rhs.begin_index && end_index == rhs.end_index &&
- id == rhs.id && properties == rhs.properties &&
- is_cacheable == rhs.is_cacheable &&
- ((!hit_test_data && !rhs.hit_test_data) ||
- (hit_test_data && rhs.hit_test_data &&
- *hit_test_data == *rhs.hit_test_data));
- }
-
- bool operator!=(const PaintChunk& rhs) const { return !(*this == rhs); }
-
- private:
- std::unique_ptr<HitTestData> hit_test_data;
+ // End of derived data.
+ // The following fields are put here to avoid memory gap.
+ bool is_cacheable;
+ bool client_is_just_created;
};
inline bool ChunkLessThanIndex(const PaintChunk& chunk, size_t index) {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk_subset.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk_subset.h
index 15d9ef5932a..c5f4ae9989b 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk_subset.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunk_subset.h
@@ -15,7 +15,7 @@ struct PaintChunk;
class PaintChunkSubset {
public:
PaintChunkSubset(const Vector<PaintChunk>& chunks,
- const Vector<size_t>& subset_indices)
+ const Vector<wtf_size_t>& subset_indices)
: chunks_(chunks), subset_indices_(&subset_indices) {}
// For convenience, this allows using a Vector<PaintChunk> in place of
@@ -41,35 +41,35 @@ class PaintChunkSubset {
private:
friend class PaintChunkSubset;
- Iterator(const PaintChunkSubset& subset, size_t offset)
+ Iterator(const PaintChunkSubset& subset, wtf_size_t offset)
: subset_(subset), offset_(offset) {}
const PaintChunkSubset& subset_;
- size_t offset_;
+ wtf_size_t offset_;
};
Iterator begin() const { return Iterator(*this, 0); }
Iterator end() const { return Iterator(*this, size()); }
- size_t size() const {
+ wtf_size_t size() const {
return subset_indices_ ? subset_indices_->size() : chunks_.size();
}
// |i| is an index in the subset.
- const PaintChunk& operator[](size_t i) const {
+ const PaintChunk& operator[](wtf_size_t i) const {
return chunks_[OriginalIndex(i)];
}
// |i| is an index in the subset.
// Returns the index in the whole paint chunks set.
- size_t OriginalIndex(size_t i) const {
+ wtf_size_t OriginalIndex(wtf_size_t i) const {
return subset_indices_ ? (*subset_indices_)[i] : i;
}
private:
const Vector<PaintChunk>& chunks_;
- const Vector<size_t>* subset_indices_;
+ const Vector<wtf_size_t>* subset_indices_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h
index 8a0f11ad98b..28bf697fa5c 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker.h
@@ -42,8 +42,8 @@ class PLATFORM_EXPORT PaintChunker final {
const Vector<PaintChunk>& PaintChunks() const { return chunks_; }
- PaintChunk& PaintChunkAt(size_t i) { return chunks_[i]; }
- size_t LastChunkIndex() const {
+ PaintChunk& PaintChunkAt(wtf_size_t i) { return chunks_[i]; }
+ wtf_size_t LastChunkIndex() const {
return chunks_.IsEmpty() ? kNotFound : chunks_.size() - 1;
}
PaintChunk& LastChunk() { return chunks_.back(); }
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker_test.cc
index 04f41a4c614..a96ab6fc5fa 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_chunker_test.cc
@@ -6,6 +6,7 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h"
#include "third_party/blink/renderer/platform/testing/paint_property_test_helpers.h"
using testing::ElementsAre;
@@ -62,13 +63,13 @@ TEST_F(PaintChunkerTest, SingleNonEmptyRange) {
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 1u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 2, id, DefaultPaintChunkProperties()));
+ EXPECT_THAT(chunks, ElementsAre(IsPaintChunk(0, 2, id,
+ DefaultPaintChunkProperties())));
auto chunks1 = chunker.ReleasePaintChunks();
EXPECT_TRUE(chunker.PaintChunks().IsEmpty());
- EXPECT_EQ(chunks1.size(), 1u);
- EXPECT_EQ(chunks1[0], PaintChunk(0, 2, id, DefaultPaintChunkProperties()));
+ EXPECT_THAT(chunks1, ElementsAre(IsPaintChunk(
+ 0, 2, id, DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, SamePropertiesTwiceCombineIntoOneChunk) {
@@ -81,13 +82,13 @@ TEST_F(PaintChunkerTest, SamePropertiesTwiceCombineIntoOneChunk) {
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 1u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 3, id, DefaultPaintChunkProperties()));
+ EXPECT_THAT(chunks, ElementsAre(IsPaintChunk(0, 3, id,
+ DefaultPaintChunkProperties())));
auto chunks1 = chunker.ReleasePaintChunks();
EXPECT_TRUE(chunker.PaintChunks().IsEmpty());
- EXPECT_EQ(chunks1.size(), 1u);
- EXPECT_EQ(chunks1[0], PaintChunk(0, 3, id, DefaultPaintChunkProperties()));
+ EXPECT_THAT(chunks1, ElementsAre(IsPaintChunk(
+ 0, 3, id, DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, BuildMultipleChunksWithSinglePropertyChanging) {
@@ -114,11 +115,11 @@ TEST_F(PaintChunkerTest, BuildMultipleChunksWithSinglePropertyChanging) {
chunker.UpdateCurrentPaintChunkProperties(id3, another_transform);
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 3u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 2, id1, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1], PaintChunk(2, 3, id2, simple_transform));
- EXPECT_EQ(chunks[2], PaintChunk(3, 4, id3, another_transform));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 2, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(2, 3, id2, simple_transform),
+ IsPaintChunk(3, 4, id3, another_transform)));
}
TEST_F(PaintChunkerTest, BuildMultipleChunksWithDifferentPropertyChanges) {
@@ -168,16 +169,16 @@ TEST_F(PaintChunkerTest, BuildMultipleChunksWithDifferentPropertyChanges) {
chunker.IncrementDisplayItemIndex(item_after_restore);
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 5u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 1, id1, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1], PaintChunk(1, 3, id2, simple_transform));
- EXPECT_EQ(chunks[2], PaintChunk(3, 5, id3, simple_transform_and_effect));
- EXPECT_EQ(chunks[3],
- PaintChunk(5, 7, id4,
- simple_transform_and_effect_with_updated_transform));
- EXPECT_EQ(chunks[4], PaintChunk(7, 9, item_after_restore.GetId(),
- simple_transform_and_effect));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(0, 1, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(1, 3, id2, simple_transform),
+ IsPaintChunk(3, 5, id3, simple_transform_and_effect),
+ IsPaintChunk(5, 7, id4,
+ simple_transform_and_effect_with_updated_transform),
+ IsPaintChunk(7, 9, item_after_restore.GetId(),
+ simple_transform_and_effect)));
}
TEST_F(PaintChunkerTest, BuildChunksFromNestedTransforms) {
@@ -209,12 +210,12 @@ TEST_F(PaintChunkerTest, BuildChunksFromNestedTransforms) {
TestChunkerDisplayItem item_after_restore(client_, DisplayItemType(10));
chunker.IncrementDisplayItemIndex(item_after_restore);
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 3u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 1, id1, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1], PaintChunk(1, 3, id2, simple_transform));
- EXPECT_EQ(chunks[2], PaintChunk(3, 4, item_after_restore.GetId(),
- DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(1, 3, id2, simple_transform),
+ IsPaintChunk(3, 4, item_after_restore.GetId(),
+ DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, ChangingPropertiesWithoutItems) {
@@ -239,10 +240,10 @@ TEST_F(PaintChunkerTest, ChangingPropertiesWithoutItems) {
chunker.UpdateCurrentPaintChunkProperties(id3, second_transform);
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 2u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 1, id1, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1], PaintChunk(1, 2, id3, second_transform));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(1, 2, id3, second_transform)));
}
TEST_F(PaintChunkerTest, CreatesSeparateChunksWhenRequested) {
@@ -266,17 +267,14 @@ TEST_F(PaintChunkerTest, CreatesSeparateChunksWhenRequested) {
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
chunker.IncrementDisplayItemIndex(i3);
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 5u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 1, id0, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1],
- PaintChunk(1, 2, i1.GetId(), DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[2],
- PaintChunk(2, 3, i2.GetId(), DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[3],
- PaintChunk(3, 5, after_i2.GetId(), DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[4],
- PaintChunk(5, 6, i3.GetId(), DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(0, 1, id0, DefaultPaintChunkProperties()),
+ IsPaintChunk(1, 2, i1.GetId(), DefaultPaintChunkProperties()),
+ IsPaintChunk(2, 3, i2.GetId(), DefaultPaintChunkProperties()),
+ IsPaintChunk(3, 5, after_i2.GetId(), DefaultPaintChunkProperties()),
+ IsPaintChunk(5, 6, i3.GetId(), DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, ForceNewChunkWithNewId) {
@@ -298,11 +296,11 @@ TEST_F(PaintChunkerTest, ForceNewChunkWithNewId) {
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 3u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 2, id0, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1], PaintChunk(2, 4, id1, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[2], PaintChunk(4, 6, id2, DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 2, id0, DefaultPaintChunkProperties()),
+ IsPaintChunk(2, 4, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(4, 6, id2, DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, ForceNewChunkWithoutNewId) {
@@ -328,11 +326,11 @@ TEST_F(PaintChunkerTest, ForceNewChunkWithoutNewId) {
chunker.IncrementDisplayItemIndex(
TestChunkerDisplayItem(client_, DisplayItemType(21)));
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 3u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 2, id0, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1], PaintChunk(2, 4, id1, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[2], PaintChunk(4, 6, id2, DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 2, id0, DefaultPaintChunkProperties()),
+ IsPaintChunk(2, 4, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(4, 6, id2, DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, NoNewChunkForSamePropertyDifferentIds) {
@@ -352,9 +350,9 @@ TEST_F(PaintChunkerTest, NoNewChunkForSamePropertyDifferentIds) {
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
chunker.IncrementDisplayItemIndex(TestChunkerDisplayItem(client_));
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 1u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 6, id0, DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 6, id0, DefaultPaintChunkProperties())));
}
class TestScrollHitTestRequiringSeparateChunk : public TestChunkerDisplayItem {
@@ -385,13 +383,13 @@ TEST_F(PaintChunkerTest, ChunksFollowingForcedChunk) {
chunker.IncrementDisplayItemIndex(after_forced1);
chunker.IncrementDisplayItemIndex(after_forced2);
- const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 3u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 2, id0, DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[1],
- PaintChunk(2, 3, forced.GetId(), DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[2], PaintChunk(3, 5, after_forced1.GetId(),
- DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunker.PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(0, 2, id0, DefaultPaintChunkProperties()),
+ IsPaintChunk(2, 3, forced.GetId(), DefaultPaintChunkProperties()),
+ IsPaintChunk(3, 5, after_forced1.GetId(),
+ DefaultPaintChunkProperties())));
}
TEST_F(PaintChunkerTest, ChunkIdsSkippingCache) {
@@ -429,19 +427,20 @@ TEST_F(PaintChunkerTest, ChunkIdsSkippingCache) {
chunker.IncrementDisplayItemIndex(after_restore);
const auto& chunks = chunker.PaintChunks();
- EXPECT_EQ(chunks.size(), 5u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 2, id1, DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ chunks,
+ ElementsAre(
+ IsPaintChunk(0, 2, id1, DefaultPaintChunkProperties()),
+ IsPaintChunk(2, 4, id2, simple_transform),
+ IsPaintChunk(4, 5, uncacheable_separate_chunk_item.GetId(),
+ simple_transform),
+ IsPaintChunk(5, 6, after_separate_chunk.GetId(), simple_transform),
+ IsPaintChunk(6, 7, after_restore.GetId(),
+ DefaultPaintChunkProperties())));
EXPECT_TRUE(chunks[0].is_cacheable);
- EXPECT_EQ(chunks[1], PaintChunk(2, 4, id2, simple_transform));
EXPECT_FALSE(chunks[1].is_cacheable);
- EXPECT_EQ(chunks[2], PaintChunk(4, 5, uncacheable_separate_chunk_item.GetId(),
- simple_transform));
EXPECT_FALSE(chunks[2].is_cacheable);
- EXPECT_EQ(chunks[3],
- PaintChunk(5, 6, after_separate_chunk.GetId(), simple_transform));
EXPECT_TRUE(chunks[3].is_cacheable);
- EXPECT_EQ(chunks[4], PaintChunk(6, 7, after_restore.GetId(),
- DefaultPaintChunkProperties()));
EXPECT_TRUE(chunks[4].is_cacheable);
}
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc
index b2faaef74f8..8af002eccdf 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.cc
@@ -25,15 +25,13 @@ PaintController::PaintController(Usage usage)
}
PaintController::~PaintController() {
- // New display items should be committed before PaintController is destroyed.
- DCHECK(new_display_item_list_.IsEmpty());
+ // New display items should be committed before PaintController is destroyed,
+ // except for transient paint controllers.
+ DCHECK(usage_ == kTransient || new_display_item_list_.IsEmpty());
}
-bool PaintController::UseCachedDrawingIfPossible(
- const DisplayItemClient& client,
- DisplayItem::Type type) {
- DCHECK(DisplayItem::IsDrawingType(type));
-
+bool PaintController::UseCachedItemIfPossible(const DisplayItemClient& client,
+ DisplayItem::Type type) {
if (usage_ == kTransient)
return false;
@@ -202,38 +200,24 @@ void PaintController::EndSubsequence(const DisplayItemClient& client,
new_cached_subsequences_.insert(&client, SubsequenceMarkers(start, end));
}
-const DisplayItem* PaintController::LastDisplayItem(unsigned offset) {
- if (offset < new_display_item_list_.size())
- return &new_display_item_list_[new_display_item_list_.size() - offset - 1];
- return nullptr;
-}
-
void PaintController::ProcessNewItem(DisplayItem& display_item) {
DCHECK(!construction_disabled_);
- if (IsSkippingCache() && usage_ == kMultiplePaints)
+ if (IsSkippingCache() && usage_ == kMultiplePaints) {
display_item.Client().Invalidate(PaintInvalidationReason::kUncacheable);
+ display_item.SetUncacheable();
+ }
-#if DCHECK_IS_ON()
- bool chunk_added =
-#endif
- new_paint_chunks_.IncrementDisplayItemIndex(display_item);
- auto& last_chunk = new_paint_chunks_.LastChunk();
+ bool chunk_added = new_paint_chunks_.IncrementDisplayItemIndex(display_item);
#if DCHECK_IS_ON()
- if (chunk_added && last_chunk.is_cacheable) {
- AddToIndicesByClientMap(last_chunk.id.client,
+ if (chunk_added && CurrentPaintChunk().is_cacheable) {
+ AddToIndicesByClientMap(CurrentPaintChunk().id.client,
new_paint_chunks_.LastChunkIndex(),
new_paint_chunk_indices_by_client_);
}
-#endif
- last_chunk.outset_for_raster_effects =
- std::max(last_chunk.outset_for_raster_effects,
- display_item.OutsetForRasterEffects());
-
-#if DCHECK_IS_ON()
- if (usage_ == kMultiplePaints && !IsSkippingCache()) {
+ if (usage_ == kMultiplePaints && display_item.IsCacheable()) {
size_t index = FindMatchingItemFromIndex(
display_item.GetId(), new_display_item_indices_by_client_,
new_display_item_list_);
@@ -249,7 +233,9 @@ void PaintController::ProcessNewItem(DisplayItem& display_item) {
new_display_item_list_.size() - 1,
new_display_item_indices_by_client_);
}
-#endif // DCHECK_IS_ON()
+#else // DCHECK_IS_ON()
+ std::ignore = chunk_added;
+#endif
if (usage_ == kMultiplePaints &&
RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled())
@@ -457,9 +443,8 @@ void PaintController::CopyCachedSubsequence(size_t begin_index,
#endif
ProcessNewItem(MoveItemFromCurrentListToNewList(current_index));
- DCHECK((!new_paint_chunks_.LastChunk().is_cacheable &&
- !cached_chunk->is_cacheable) ||
- new_paint_chunks_.LastChunk().Matches(*cached_chunk));
+ DCHECK((!CurrentPaintChunk().is_cacheable && !cached_chunk->is_cacheable) ||
+ CurrentPaintChunk().Matches(*cached_chunk));
}
if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) {
@@ -562,6 +547,19 @@ void PaintController::FinishCycle() {
#endif
}
+void PaintController::ClearPropertyTreeChangedStateTo(
+ const PropertyTreeState& to) {
+ DCHECK(RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled());
+
+ // Calling |ClearChangedTo| for every chunk is O(|property nodes|^2) and
+ // could be optimized by caching which nodes that have already been cleared.
+ for (const auto& chunk : current_paint_artifact_->PaintChunks()) {
+ chunk.properties.Transform()->ClearChangedTo(to.Transform());
+ chunk.properties.Clip()->ClearChangedTo(to.Clip());
+ chunk.properties.Effect()->ClearChangedTo(to.Effect());
+ }
+}
+
size_t PaintController::ApproximateUnsharedMemoryUsage() const {
size_t memory_usage = sizeof(*this);
@@ -587,35 +585,12 @@ size_t PaintController::ApproximateUnsharedMemoryUsage() const {
return memory_usage;
}
-namespace {
-
-class DebugDrawingClient final : public DisplayItemClient {
- public:
- DebugDrawingClient() { Invalidate(PaintInvalidationReason::kUncacheable); }
- String DebugName() const final { return "DebugDrawing"; }
- LayoutRect VisualRect() const final {
- return LayoutRect(LayoutRect::InfiniteIntRect());
- }
-};
-
-} // anonymous namespace
-
void PaintController::AppendDebugDrawingAfterCommit(
sk_sp<const PaintRecord> record,
const PropertyTreeState& property_tree_state) {
- DEFINE_STATIC_LOCAL(DebugDrawingClient, debug_drawing_client, ());
-
DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
DCHECK(new_display_item_list_.IsEmpty());
- auto& display_item_list = current_paint_artifact_->GetDisplayItemList();
- auto& display_item =
- display_item_list.AllocateAndConstruct<DrawingDisplayItem>(
- debug_drawing_client, DisplayItem::kDebugDrawing, std::move(record));
-
- // Create a PaintChunk for the debug drawing.
- current_paint_artifact_->PaintChunks().emplace_back(
- display_item_list.size() - 1, display_item_list.size(),
- display_item.GetId(), property_tree_state);
+ current_paint_artifact_->AppendDebugDrawing(record, property_tree_state);
}
void PaintController::ShowUnderInvalidationError(
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.h
index 183561d8f6f..469ae053bd9 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller.h
@@ -20,7 +20,6 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_chunker.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -114,7 +113,7 @@ class PLATFORM_EXPORT PaintController {
static_assert(
sizeof(DisplayItemClass) <= kMaximumDisplayItemSize,
"DisplayItem subclass is larger than kMaximumDisplayItemSize.");
- static_assert(kDisplayItemAlignment % WTF_ALIGN_OF(DisplayItemClass) == 0,
+ static_assert(kDisplayItemAlignment % alignof(DisplayItemClass) == 0,
"DisplayItem subclass alignment is not a factor of "
"kDisplayItemAlignment.");
@@ -129,10 +128,10 @@ class PLATFORM_EXPORT PaintController {
ProcessNewItem(display_item);
}
- // Tries to find the cached drawing display item corresponding to the given
+ // Tries to find the cached display item corresponding to the given
// parameters. If found, appends the cached display item to the new display
// list and returns true. Otherwise returns false.
- bool UseCachedDrawingIfPossible(const DisplayItemClient&, DisplayItem::Type);
+ bool UseCachedItemIfPossible(const DisplayItemClient&, DisplayItem::Type);
// Tries to find the cached subsequence corresponding to the given parameters.
// If found, copies the cache subsequence to the new display list and returns
@@ -144,8 +143,6 @@ class PLATFORM_EXPORT PaintController {
// BeginSubsequence().
void EndSubsequence(const DisplayItemClient&, size_t start);
- const DisplayItem* LastDisplayItem(unsigned offset);
-
void BeginSkippingCache() {
if (usage_ == kTransient)
return;
@@ -173,6 +170,13 @@ class PLATFORM_EXPORT PaintController {
// there FinishCycle() at the same time to ensure consistent caching status.
void FinishCycle();
+ // |FinishCycle| clears the property tree changed state but only does this for
+ // non-transient controllers. The root paint controller is transient with
+ // BlinkGenPropertyTrees and this function provides a hook for clearing
+ // the property tree changed state after paint.
+ // TODO(pdr): Remove this when BlinkGenPropertyTrees ships.
+ void ClearPropertyTreeChangedStateTo(const PropertyTreeState&);
+
// Returns the approximate memory usage, excluding memory likely to be
// shared with the embedder after copying to WebPaintController.
// Should only be called after a full document life cycle update.
@@ -248,7 +252,7 @@ class PLATFORM_EXPORT PaintController {
// However, the current algorithm allows the following situations even if
// ClientCacheIsValid() is true for a client during painting:
// 1. The client paints a new display item that is not cached:
- // UseCachedDrawingIfPossible() returns false for the display item and the
+ // UseCachedItemIfPossible() returns false for the display item and the
// newly painted display item will be added into the cache. This situation
// has slight performance hit (see FindOutOfOrderCachedItemForward()) so we
// print a warning in the situation and should keep it rare.
@@ -360,7 +364,7 @@ class PLATFORM_EXPORT PaintController {
// Stores indices to valid cacheable display items in
// current_paint_artifact_.GetDisplayItemList() that have not been matched by
- // requests of cached display items (using UseCachedDrawingIfPossible() and
+ // requests of cached display items (using UseCachedItemIfPossible() and
// UseCachedSubsequenceIfPossible()) during sequential matching. The indexed
// items will be matched by later out-of-order requests of cached display
// items. This ensures that when out-of-order cached display items are
@@ -387,7 +391,7 @@ class PLATFORM_EXPORT PaintController {
IndicesByClientMap new_paint_chunk_indices_by_client_;
#endif
- // These are set in UseCachedDrawingIfPossible() and
+ // These are set in UseCachedItemIfPossible() and
// UseCachedSubsequenceIfPossible() when we could use cached drawing or
// subsequence and under-invalidation checking is on, indicating the begin and
// end of the cached drawing or subsequence in the current list. The functions
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc
index 8f70d35bb2e..0d0289e47db 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_debug_data.cc
@@ -146,17 +146,20 @@ void PaintController::DisplayItemListAsJSON::AppendSubsequenceAsJSON(
String PaintController::DisplayItemListAsJSON::ClientName(
const DisplayItemClient& client) const {
- return DisplayItemClient::SafeDebugName(
- client, flags_ & DisplayItemList::kClientKnownToBeAlive);
+ return client.SafeDebugName(flags_ & DisplayItemList::kClientKnownToBeAlive);
}
void PaintController::ShowDebugDataInternal(
DisplayItemList::JsonFlags flags) const {
+ auto current_list_flags = flags;
+ // The clients in the current list are known to be alive before FinishCycle().
+ if (committed_)
+ current_list_flags |= DisplayItemList::kClientKnownToBeAlive;
LOG(ERROR) << "current display item list: "
<< DisplayItemListAsJSON(
current_paint_artifact_->GetDisplayItemList(),
current_cached_subsequences_,
- current_paint_artifact_->PaintChunks(), flags)
+ current_paint_artifact_->PaintChunks(), current_list_flags)
.ToString()
.Utf8()
.data();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc
index be7dd5659c4..ad521693437 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.cc
@@ -15,6 +15,8 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/testing/paint_test_configurations.h"
+using testing::ElementsAre;
+
namespace blink {
// Tests using this class will be tested with under-invalidation-checking
@@ -23,6 +25,11 @@ class PaintControllerTest : public PaintTestConfigurations,
public PaintControllerTestBase {
};
+#define EXPECT_DEFAULT_ROOT_CHUNK(size) \
+ EXPECT_THAT(GetPaintController().PaintChunks(), \
+ ElementsAre(IsPaintChunk(0, size, DefaultRootChunkId(), \
+ DefaultPaintChunkProperties())))
+
INSTANTIATE_TEST_CASE_P(
All,
PaintControllerTest,
@@ -41,10 +48,9 @@ TEST_P(PaintControllerTest, NestedRecorders) {
DrawRect(context, client, kBackgroundType, FloatRect(100, 100, 200, 200));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 1,
- TestDisplayItem(client, kBackgroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(1);
}
TEST_P(PaintControllerTest, UpdateBasic) {
@@ -61,12 +67,11 @@ TEST_P(PaintControllerTest, UpdateBasic) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(first, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&first, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(3);
InitRootChunk();
DrawRect(context, first, kBackgroundType, FloatRect(100, 100, 300, 300));
@@ -81,11 +86,10 @@ TEST_P(PaintControllerTest, UpdateBasic) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(2);
}
TEST_P(PaintControllerTest, UpdateSwapOrder) {
@@ -103,13 +107,13 @@ TEST_P(PaintControllerTest, UpdateSwapOrder) {
DrawRect(context, unaffected, kForegroundType, FloatRect(300, 300, 10, 10));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType),
- TestDisplayItem(unaffected, kBackgroundType),
- TestDisplayItem(unaffected, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType),
+ IsSameId(&unaffected, kBackgroundType),
+ IsSameId(&unaffected, kForegroundType)));
InitRootChunk();
DrawRect(context, second, kBackgroundType, FloatRect(100, 100, 50, 200));
@@ -128,15 +132,14 @@ TEST_P(PaintControllerTest, UpdateSwapOrder) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType),
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(unaffected, kBackgroundType),
- TestDisplayItem(unaffected, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType),
+ IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&unaffected, kBackgroundType),
+ IsSameId(&unaffected, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(6);
}
TEST_P(PaintControllerTest, UpdateSwapOrderWithInvalidation) {
@@ -154,13 +157,13 @@ TEST_P(PaintControllerTest, UpdateSwapOrderWithInvalidation) {
DrawRect(context, unaffected, kForegroundType, FloatRect(300, 300, 10, 10));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType),
- TestDisplayItem(unaffected, kBackgroundType),
- TestDisplayItem(unaffected, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType),
+ IsSameId(&unaffected, kBackgroundType),
+ IsSameId(&unaffected, kForegroundType)));
InitRootChunk();
first.Invalidate();
@@ -180,15 +183,14 @@ TEST_P(PaintControllerTest, UpdateSwapOrderWithInvalidation) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType),
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(unaffected, kBackgroundType),
- TestDisplayItem(unaffected, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType),
+ IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&unaffected, kBackgroundType),
+ IsSameId(&unaffected, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(6);
}
TEST_P(PaintControllerTest, UpdateNewItemInMiddle) {
@@ -202,9 +204,9 @@ TEST_P(PaintControllerTest, UpdateNewItemInMiddle) {
DrawRect(context, second, kBackgroundType, FloatRect(100, 100, 50, 200));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType)));
InitRootChunk();
@@ -221,12 +223,11 @@ TEST_P(PaintControllerTest, UpdateNewItemInMiddle) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(third, kBackgroundType),
- TestDisplayItem(second, kBackgroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&third, kBackgroundType),
+ IsSameId(&second, kBackgroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(3);
}
TEST_P(PaintControllerTest, UpdateInvalidationWithPhases) {
@@ -244,13 +245,13 @@ TEST_P(PaintControllerTest, UpdateInvalidationWithPhases) {
DrawRect(context, third, kForegroundType, FloatRect(300, 100, 50, 50));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(third, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(second, kForegroundType),
- TestDisplayItem(third, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&third, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&second, kForegroundType),
+ IsSameId(&third, kForegroundType)));
InitRootChunk();
@@ -271,45 +272,14 @@ TEST_P(PaintControllerTest, UpdateInvalidationWithPhases) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(third, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(second, kForegroundType),
- TestDisplayItem(third, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
-}
-
-TEST_P(PaintControllerTest, IncrementalRasterInvalidation) {
- LayoutRect initial_rect(100, 100, 100, 100);
- std::unique_ptr<FakeDisplayItemClient> clients[6];
- for (auto& client : clients)
- client = std::make_unique<FakeDisplayItemClient>("", initial_rect);
- GraphicsContext context(GetPaintController());
-
- InitRootChunk();
-
- for (auto& client : clients)
- DrawRect(context, *client, kBackgroundType, FloatRect(initial_rect));
- CommitAndFinishCycle();
-
- InitRootChunk();
- clients[0]->SetVisualRect(LayoutRect(100, 100, 150, 100));
- clients[1]->SetVisualRect(LayoutRect(100, 100, 100, 150));
- clients[2]->SetVisualRect(LayoutRect(100, 100, 150, 80));
- clients[3]->SetVisualRect(LayoutRect(100, 100, 80, 150));
- clients[4]->SetVisualRect(LayoutRect(100, 100, 150, 150));
- clients[5]->SetVisualRect(LayoutRect(100, 100, 80, 80));
- for (auto& client : clients) {
- client->Invalidate(PaintInvalidationReason::kIncremental);
- DrawRect(context, *client, kBackgroundType,
- FloatRect(client->VisualRect()));
- }
- CommitAndFinishCycle();
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&third, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&second, kForegroundType),
+ IsSameId(&third, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(6);
}
TEST_P(PaintControllerTest, UpdateAddFirstOverlap) {
@@ -322,9 +292,9 @@ TEST_P(PaintControllerTest, UpdateAddFirstOverlap) {
DrawRect(context, second, kForegroundType, FloatRect(200, 200, 50, 50));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType)));
InitRootChunk();
@@ -338,13 +308,12 @@ TEST_P(PaintControllerTest, UpdateAddFirstOverlap) {
EXPECT_EQ(0, NumCachedNewItems());
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(4);
InitRootChunk();
DrawRect(context, second, kBackgroundType, FloatRect(150, 250, 100, 100));
@@ -359,11 +328,10 @@ TEST_P(PaintControllerTest, UpdateAddFirstOverlap) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(2);
}
TEST_P(PaintControllerTest, UpdateAddLastOverlap) {
@@ -376,9 +344,9 @@ TEST_P(PaintControllerTest, UpdateAddLastOverlap) {
DrawRect(context, first, kForegroundType, FloatRect(100, 100, 150, 150));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType)));
InitRootChunk();
@@ -392,13 +360,12 @@ TEST_P(PaintControllerTest, UpdateAddLastOverlap) {
EXPECT_EQ(0, NumCachedNewItems());
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(second, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&second, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(4);
InitRootChunk();
first.Invalidate();
@@ -409,11 +376,10 @@ TEST_P(PaintControllerTest, UpdateAddLastOverlap) {
EXPECT_EQ(0, NumCachedNewItems());
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(first, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&first, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(2);
}
TEST_P(PaintControllerTest, CachedDisplayItems) {
@@ -426,9 +392,9 @@ TEST_P(PaintControllerTest, CachedDisplayItems) {
DrawRect(context, second, kBackgroundType, FloatRect(100, 100, 150, 150));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType)));
EXPECT_TRUE(ClientCacheIsValid(first));
EXPECT_TRUE(ClientCacheIsValid(second));
sk_sp<const PaintRecord> first_paint_record =
@@ -449,9 +415,9 @@ TEST_P(PaintControllerTest, CachedDisplayItems) {
DrawRect(context, second, kBackgroundType, FloatRect(100, 100, 150, 150));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType)));
// The first display item should be updated.
EXPECT_NE(first_paint_record,
static_cast<const DrawingDisplayItem&>(
@@ -492,15 +458,15 @@ TEST_P(PaintControllerTest, UpdateSwapOrderWithChildren) {
DrawRect(context, container2, kForegroundType, FloatRect(100, 200, 100, 100));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 8,
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType)));
InitRootChunk();
@@ -516,17 +482,16 @@ TEST_P(PaintControllerTest, UpdateSwapOrderWithChildren) {
DrawRect(context, container1, kForegroundType, FloatRect(100, 100, 100, 100));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 8,
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(8);
}
TEST_P(PaintControllerTest, UpdateSwapOrderWithChildrenAndInvalidation) {
@@ -549,15 +514,15 @@ TEST_P(PaintControllerTest, UpdateSwapOrderWithChildrenAndInvalidation) {
DrawRect(context, container2, kForegroundType, FloatRect(100, 200, 100, 100));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 8,
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType)));
InitRootChunk();
@@ -574,17 +539,16 @@ TEST_P(PaintControllerTest, UpdateSwapOrderWithChildrenAndInvalidation) {
DrawRect(context, container1, kForegroundType, FloatRect(100, 100, 100, 100));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 8,
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType));
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType)));
+ EXPECT_DEFAULT_ROOT_CHUNK(8);
}
TEST_P(PaintControllerTest, CachedSubsequenceForcePaintChunk) {
@@ -601,10 +565,9 @@ TEST_P(PaintControllerTest, CachedSubsequenceForcePaintChunk) {
DrawRect(context, root, kBackgroundType, FloatRect(100, 100, 100, 100));
FakeDisplayItemClient container("container");
+ auto container_properties = DefaultPaintChunkProperties();
+ PaintChunk::Id container_id(container, DisplayItem::kCaret);
{
- auto container_properties = DefaultPaintChunkProperties();
- PaintChunk::Id container_id(container, DisplayItem::kCaret);
-
SubsequenceRecorder r(context, container);
GetPaintController().UpdateCurrentPaintChunkProperties(
container_id, container_properties);
@@ -620,13 +583,12 @@ TEST_P(PaintControllerTest, CachedSubsequenceForcePaintChunk) {
// Even though the paint properties match, |container| should receive its
// own PaintChunk because it created a subsequence.
- EXPECT_EQ(3u, GetPaintController().GetPaintArtifact().PaintChunks().size());
- EXPECT_EQ(root,
- GetPaintController().GetPaintArtifact().PaintChunks()[0].id.client);
- EXPECT_EQ(container,
- GetPaintController().GetPaintArtifact().PaintChunks()[1].id.client);
- EXPECT_EQ(root,
- GetPaintController().GetPaintArtifact().PaintChunks()[2].id.client);
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_id, root_properties),
+ IsPaintChunk(1, 3, container_id, container_properties),
+ IsPaintChunk(3, 4, PaintChunk::Id(root, kForegroundType),
+ root_properties)));
GetPaintController().UpdateCurrentPaintChunkProperties(root_id,
root_properties);
@@ -637,13 +599,12 @@ TEST_P(PaintControllerTest, CachedSubsequenceForcePaintChunk) {
// |container| should still receive its own PaintChunk because it is a cached
// subsequence.
- EXPECT_EQ(3u, GetPaintController().GetPaintArtifact().PaintChunks().size());
- EXPECT_EQ(root,
- GetPaintController().GetPaintArtifact().PaintChunks()[0].id.client);
- EXPECT_EQ(container,
- GetPaintController().GetPaintArtifact().PaintChunks()[1].id.client);
- EXPECT_EQ(root,
- GetPaintController().GetPaintArtifact().PaintChunks()[2].id.client);
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, root_id, root_properties),
+ IsPaintChunk(1, 3, container_id, container_properties),
+ IsPaintChunk(3, 4, PaintChunk::Id(root, kForegroundType),
+ container_properties)));
}
TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
@@ -655,17 +616,19 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200));
GraphicsContext context(GetPaintController());
+ PaintChunk::Id container1_id(container1, kBackgroundType);
auto container1_effect = CreateOpacityEffect(e0(), 0.5);
auto container1_properties = DefaultPaintChunkProperties();
container1_properties.SetEffect(container1_effect.get());
+ PaintChunk::Id container2_id(container2, kBackgroundType);
auto container2_effect = CreateOpacityEffect(e0(), 0.5);
auto container2_properties = DefaultPaintChunkProperties();
container2_properties.SetEffect(container2_effect.get());
{
GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container1, kBackgroundType), container1_properties);
+ container1_id, container1_properties);
SubsequenceRecorder r(context, container1);
DrawRect(context, container1, kBackgroundType,
@@ -677,7 +640,7 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
}
{
GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container2, kBackgroundType), container2_properties);
+ container2_id, container2_properties);
SubsequenceRecorder r(context, container2);
DrawRect(context, container2, kBackgroundType,
@@ -689,16 +652,16 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
}
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 8,
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType),
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType));
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType)));
auto* markers = GetSubsequenceMarkers(container1);
CHECK(markers);
@@ -710,11 +673,10 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
EXPECT_EQ(4u, markers->start);
EXPECT_EQ(8u, markers->end);
- EXPECT_EQ(2u, GetPaintController().PaintChunks().size());
- EXPECT_EQ(PaintChunk::Id(container1, kBackgroundType),
- GetPaintController().PaintChunks()[0].id);
- EXPECT_EQ(PaintChunk::Id(container2, kBackgroundType),
- GetPaintController().PaintChunks()[1].id);
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 4, container1_id, container1_properties),
+ IsPaintChunk(4, 8, container2_id, container2_properties)));
// Simulate the situation when |container1| gets a z-index that is greater
// than that of |container2|.
@@ -725,9 +687,8 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible(
context, container2));
{
- PaintChunk::Id id(container2, kBackgroundType);
GetPaintController().UpdateCurrentPaintChunkProperties(
- id, container2_properties);
+ container2_id, container2_properties);
SubsequenceRecorder r(context, container2);
DrawRect(context, container2, kBackgroundType,
@@ -742,9 +703,8 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible(
context, container1));
{
- PaintChunk::Id id(container1, kBackgroundType);
GetPaintController().UpdateCurrentPaintChunkProperties(
- id, container1_properties);
+ container1_id, container1_properties);
SubsequenceRecorder r(context, container1);
DrawRect(context, container1, kBackgroundType,
@@ -772,15 +732,15 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 8,
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType),
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType),
+ IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType)));
markers = GetSubsequenceMarkers(container2);
CHECK(markers);
@@ -792,11 +752,10 @@ TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) {
EXPECT_EQ(4u, markers->start);
EXPECT_EQ(8u, markers->end);
- EXPECT_EQ(2u, GetPaintController().PaintChunks().size());
- EXPECT_EQ(PaintChunk::Id(container2, kBackgroundType),
- GetPaintController().PaintChunks()[0].id);
- EXPECT_EQ(PaintChunk::Id(container1, kBackgroundType),
- GetPaintController().PaintChunks()[1].id);
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 4, container2_id, container2_properties),
+ IsPaintChunk(4, 8, container1_id, container1_properties)));
}
TEST_P(PaintControllerTest, CachedSubsequenceAndDisplayItemsSwapOrder) {
@@ -822,13 +781,13 @@ TEST_P(PaintControllerTest, CachedSubsequenceAndDisplayItemsSwapOrder) {
DrawRect(context, content1, kForegroundType, FloatRect(100, 100, 50, 200));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType),
- TestDisplayItem(content1, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&content1, kBackgroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType),
+ IsSameId(&content1, kForegroundType)));
auto* markers = GetSubsequenceMarkers(container2);
CHECK(markers);
@@ -875,13 +834,13 @@ TEST_P(PaintControllerTest, CachedSubsequenceAndDisplayItemsSwapOrder) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(container2, kForegroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&content2, kForegroundType),
+ IsSameId(&container2, kForegroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType)));
markers = GetSubsequenceMarkers(container2);
CHECK(markers);
@@ -896,7 +855,7 @@ TEST_P(PaintControllerTest, CachedSubsequenceContainingFragments) {
FakeDisplayItemClient container("container");
// The first paint.
- auto paint_container = [this, &context, &container, kFragmentCount]() {
+ auto paint_container = [this, &context, &container]() {
SubsequenceRecorder r(context, container);
for (size_t i = 0; i < kFragmentCount; ++i) {
ScopedDisplayItemFragment scoped_fragment(context, i);
@@ -918,17 +877,17 @@ TEST_P(PaintControllerTest, CachedSubsequenceContainingFragments) {
CommitAndFinishCycle();
auto check_paint_results = [this, &root, &container]() {
- const auto& chunks = GetPaintController().PaintChunks();
- EXPECT_EQ(chunks.size(), 3u);
- EXPECT_EQ(chunks[0], PaintChunk(0, 1, PaintChunk::Id(root, kBackgroundType),
- DefaultPaintChunkProperties()));
- // One chunk for all of the fragments because they have the
- // same properties.
- EXPECT_EQ(chunks[1],
- PaintChunk(1, 4, PaintChunk::Id(container, kBackgroundType),
- DefaultPaintChunkProperties()));
- EXPECT_EQ(chunks[2], PaintChunk(4, 5, PaintChunk::Id(root, kForegroundType),
- DefaultPaintChunkProperties()));
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(
+ IsPaintChunk(0, 1, PaintChunk::Id(root, kBackgroundType),
+ DefaultPaintChunkProperties()),
+ // One chunk for all of the fragments because they have the
+ // same properties.
+ IsPaintChunk(1, 4, PaintChunk::Id(container, kBackgroundType),
+ DefaultPaintChunkProperties()),
+ IsPaintChunk(4, 5, PaintChunk::Id(root, kForegroundType),
+ DefaultPaintChunkProperties())));
};
// Check results of the first paint.
check_paint_results();
@@ -965,44 +924,45 @@ TEST_P(PaintControllerTest, UpdateSwapOrderCrossingChunks) {
FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200));
GraphicsContext context(GetPaintController());
+ PaintChunk::Id container1_id(container1, kBackgroundType);
auto container1_effect = CreateOpacityEffect(e0(), 0.5);
auto container1_properties = DefaultPaintChunkProperties();
container1_properties.SetEffect(container1_effect.get());
+ PaintChunk::Id container2_id(container2, kBackgroundType);
auto container2_effect = CreateOpacityEffect(e0(), 0.5);
auto container2_properties = DefaultPaintChunkProperties();
container2_properties.SetEffect(container2_effect.get());
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container1, kBackgroundType), container1_properties);
+ GetPaintController().UpdateCurrentPaintChunkProperties(container1_id,
+ container1_properties);
DrawRect(context, container1, kBackgroundType, FloatRect(100, 100, 100, 100));
DrawRect(context, content1, kBackgroundType, FloatRect(100, 100, 50, 200));
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container2, kBackgroundType), container2_properties);
+ GetPaintController().UpdateCurrentPaintChunkProperties(container2_id,
+ container2_properties);
DrawRect(context, container2, kBackgroundType, FloatRect(100, 200, 100, 100));
DrawRect(context, content2, kBackgroundType, FloatRect(100, 200, 50, 200));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType)));
- EXPECT_EQ(2u, GetPaintController().PaintChunks().size());
- EXPECT_EQ(PaintChunk::Id(container1, kBackgroundType),
- GetPaintController().PaintChunks()[0].id);
- EXPECT_EQ(PaintChunk::Id(container2, kBackgroundType),
- GetPaintController().PaintChunks()[1].id);
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 2, container1_id, container1_properties),
+ IsPaintChunk(2, 4, container2_id, container2_properties)));
// Move content2 into container1, without invalidation.
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container1, kBackgroundType), container1_properties);
+ GetPaintController().UpdateCurrentPaintChunkProperties(container1_id,
+ container1_properties);
DrawRect(context, container1, kBackgroundType, FloatRect(100, 100, 100, 100));
DrawRect(context, content1, kBackgroundType, FloatRect(100, 100, 50, 200));
DrawRect(context, content2, kBackgroundType, FloatRect(100, 200, 50, 200));
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container2, kBackgroundType), container2_properties);
+ GetPaintController().UpdateCurrentPaintChunkProperties(container2_id,
+ container2_properties);
DrawRect(context, container2, kBackgroundType, FloatRect(100, 200, 100, 100));
EXPECT_EQ(4, NumCachedNewItems());
@@ -1014,17 +974,16 @@ TEST_P(PaintControllerTest, UpdateSwapOrderCrossingChunks) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType),
- TestDisplayItem(container2, kBackgroundType));
-
- EXPECT_EQ(2u, GetPaintController().PaintChunks().size());
- EXPECT_EQ(PaintChunk::Id(container1, kBackgroundType),
- GetPaintController().PaintChunks()[0].id);
- EXPECT_EQ(PaintChunk::Id(container2, kBackgroundType),
- GetPaintController().PaintChunks()[1].id);
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content2, kBackgroundType),
+ IsSameId(&container2, kBackgroundType)));
+
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 3, container1_id, container1_properties),
+ IsPaintChunk(3, 4, container2_id, container2_properties)));
}
TEST_P(PaintControllerTest, OutOfOrderNoCrash) {
@@ -1065,71 +1024,73 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
FakeDisplayItemClient content2("content2", LayoutRect(100, 200, 50, 200));
GraphicsContext context(GetPaintController());
+ PaintChunk::Id container1_background_id(container1, kBackgroundType);
auto container1_effect = CreateOpacityEffect(e0(), 0.5);
auto container1_background_properties = DefaultPaintChunkProperties();
container1_background_properties.SetEffect(container1_effect.get());
+ PaintChunk::Id container1_foreground_id(container1, kForegroundType);
auto container1_foreground_properties = DefaultPaintChunkProperties();
container1_foreground_properties.SetEffect(container1_effect.get());
+ PaintChunk::Id content1_id(content1, kBackgroundType);
auto content1_effect = CreateOpacityEffect(e0(), 0.6);
auto content1_properties = DefaultPaintChunkProperties();
content1_properties.SetEffect(content1_effect.get());
+ PaintChunk::Id container2_background_id(container2, kBackgroundType);
auto container2_effect = CreateOpacityEffect(e0(), 0.7);
auto container2_background_properties = DefaultPaintChunkProperties();
container2_background_properties.SetEffect(container2_effect.get());
+ PaintChunk::Id content2_id(content2, kBackgroundType);
auto content2_effect = CreateOpacityEffect(e0(), 0.8);
auto content2_properties = DefaultPaintChunkProperties();
content2_properties.SetEffect(content2_effect.get());
{
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container1, kBackgroundType),
- container1_background_properties);
SubsequenceRecorder r(context, container1);
+ GetPaintController().UpdateCurrentPaintChunkProperties(
+ container1_background_id, container1_background_properties);
DrawRect(context, container1, kBackgroundType,
FloatRect(100, 100, 100, 100));
{
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(content1, kBackgroundType), content1_properties);
SubsequenceRecorder r(context, content1);
+ GetPaintController().UpdateCurrentPaintChunkProperties(
+ content1_id, content1_properties);
DrawRect(context, content1, kBackgroundType,
FloatRect(100, 100, 50, 200));
DrawRect(context, content1, kForegroundType,
FloatRect(100, 100, 50, 200));
}
GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container1, kForegroundType),
- container1_foreground_properties);
+ container1_foreground_id, container1_foreground_properties);
DrawRect(context, container1, kForegroundType,
FloatRect(100, 100, 100, 100));
}
{
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container2, kBackgroundType),
- container2_background_properties);
SubsequenceRecorder r(context, container2);
+ GetPaintController().UpdateCurrentPaintChunkProperties(
+ container2_background_id, container2_background_properties);
DrawRect(context, container2, kBackgroundType,
FloatRect(100, 200, 100, 100));
{
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(content2, kBackgroundType), content2_properties);
SubsequenceRecorder r(context, content2);
+ GetPaintController().UpdateCurrentPaintChunkProperties(
+ content2_id, content2_properties);
DrawRect(context, content2, kBackgroundType,
FloatRect(100, 200, 50, 200));
}
}
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 6,
- TestDisplayItem(container1, kBackgroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType),
- TestDisplayItem(container2, kBackgroundType),
- TestDisplayItem(content2, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&container1, kBackgroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType),
+ IsSameId(&container2, kBackgroundType),
+ IsSameId(&content2, kBackgroundType)));
auto* markers = GetSubsequenceMarkers(container1);
CHECK(markers);
@@ -1151,17 +1112,16 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
EXPECT_EQ(5u, markers->start);
EXPECT_EQ(6u, markers->end);
- EXPECT_EQ(5u, GetPaintController().PaintChunks().size());
- EXPECT_EQ(PaintChunk::Id(container1, kBackgroundType),
- GetPaintController().PaintChunks()[0].id);
- EXPECT_EQ(PaintChunk::Id(content1, kBackgroundType),
- GetPaintController().PaintChunks()[1].id);
- EXPECT_EQ(PaintChunk::Id(container1, kForegroundType),
- GetPaintController().PaintChunks()[2].id);
- EXPECT_EQ(PaintChunk::Id(container2, kBackgroundType),
- GetPaintController().PaintChunks()[3].id);
- EXPECT_EQ(PaintChunk::Id(content2, kBackgroundType),
- GetPaintController().PaintChunks()[4].id);
+ EXPECT_THAT(
+ GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, container1_background_id,
+ container1_background_properties),
+ IsPaintChunk(1, 3, content1_id, content1_properties),
+ IsPaintChunk(3, 4, container1_foreground_id,
+ container1_foreground_properties),
+ IsPaintChunk(4, 5, container2_background_id,
+ container2_background_properties),
+ IsPaintChunk(5, 6, content2_id, content2_properties)));
// Invalidate container1 but not content1.
container1.Invalidate();
@@ -1177,16 +1137,16 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
SubsequenceRecorder::UseCachedSubsequenceIfPossible(context, content2));
// Content2 now outputs foreground only.
{
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(content2, kForegroundType), content2_properties);
SubsequenceRecorder r(context, content2);
+ GetPaintController().UpdateCurrentPaintChunkProperties(content2_id,
+ content2_properties);
DrawRect(context, content2, kForegroundType, FloatRect(100, 200, 50, 200));
}
// Repaint container1 with foreground only.
{
+ SubsequenceRecorder r(context, container1);
EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible(
context, container1));
- SubsequenceRecorder r(context, container1);
// Use cached subsequence of content1.
if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) {
// When under-invalidation-checking is enabled,
@@ -1194,9 +1154,9 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
// expected to create the same painting as in the previous paint.
EXPECT_FALSE(SubsequenceRecorder::UseCachedSubsequenceIfPossible(
context, content1));
- GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(content1, kBackgroundType), content1_properties);
SubsequenceRecorder r(context, content1);
+ GetPaintController().UpdateCurrentPaintChunkProperties(
+ content1_id, content1_properties);
DrawRect(context, content1, kBackgroundType,
FloatRect(100, 100, 50, 200));
DrawRect(context, content1, kForegroundType,
@@ -1206,8 +1166,7 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
context, content1));
}
GetPaintController().UpdateCurrentPaintChunkProperties(
- PaintChunk::Id(container1, kForegroundType),
- container1_foreground_properties);
+ container1_foreground_id, container1_foreground_properties);
DrawRect(context, container1, kForegroundType,
FloatRect(100, 100, 100, 100));
}
@@ -1221,11 +1180,11 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(content2, kForegroundType),
- TestDisplayItem(content1, kBackgroundType),
- TestDisplayItem(content1, kForegroundType),
- TestDisplayItem(container1, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&content2, kForegroundType),
+ IsSameId(&content1, kBackgroundType),
+ IsSameId(&content1, kForegroundType),
+ IsSameId(&container1, kForegroundType)));
markers = GetSubsequenceMarkers(content2);
CHECK(markers);
@@ -1242,13 +1201,11 @@ TEST_P(PaintControllerTest, CachedNestedSubsequenceUpdate) {
EXPECT_EQ(1u, markers->start);
EXPECT_EQ(3u, markers->end);
- EXPECT_EQ(3u, GetPaintController().PaintChunks().size());
- EXPECT_EQ(PaintChunk::Id(content2, kForegroundType),
- GetPaintController().PaintChunks()[0].id);
- EXPECT_EQ(PaintChunk::Id(content1, kBackgroundType),
- GetPaintController().PaintChunks()[1].id);
- EXPECT_EQ(PaintChunk::Id(container1, kForegroundType),
- GetPaintController().PaintChunks()[2].id);
+ EXPECT_THAT(GetPaintController().PaintChunks(),
+ ElementsAre(IsPaintChunk(0, 1, content2_id, content2_properties),
+ IsPaintChunk(1, 3, content1_id, content1_properties),
+ IsPaintChunk(3, 4, container1_foreground_id,
+ container1_foreground_properties)));
}
TEST_P(PaintControllerTest, SkipCache) {
@@ -1270,10 +1227,10 @@ TEST_P(PaintControllerTest, SkipCache) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(multicol, kBackgroundType),
- TestDisplayItem(content, kForegroundType),
- TestDisplayItem(content, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&multicol, kBackgroundType),
+ IsSameId(&content, kForegroundType),
+ IsSameId(&content, kForegroundType)));
sk_sp<const PaintRecord> record1 =
static_cast<const DrawingDisplayItem&>(
GetPaintController().GetDisplayItemList()[1])
@@ -1283,8 +1240,7 @@ TEST_P(PaintControllerTest, SkipCache) {
GetPaintController().GetDisplayItemList()[2])
.GetPaintRecord();
EXPECT_NE(record1, record2);
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_DEFAULT_ROOT_CHUNK(3);
InitRootChunk();
// Draw again with nothing invalidated.
@@ -1305,18 +1261,17 @@ TEST_P(PaintControllerTest, SkipCache) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(multicol, kBackgroundType),
- TestDisplayItem(content, kForegroundType),
- TestDisplayItem(content, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&multicol, kBackgroundType),
+ IsSameId(&content, kForegroundType),
+ IsSameId(&content, kForegroundType)));
EXPECT_NE(record1, static_cast<const DrawingDisplayItem&>(
GetPaintController().GetDisplayItemList()[1])
.GetPaintRecord());
EXPECT_NE(record2, static_cast<const DrawingDisplayItem&>(
GetPaintController().GetDisplayItemList()[2])
.GetPaintRecord());
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_DEFAULT_ROOT_CHUNK(3);
InitRootChunk();
// Now the multicol becomes 3 columns and repaints.
@@ -1330,11 +1285,11 @@ TEST_P(PaintControllerTest, SkipCache) {
GetPaintController().EndSkippingCache();
// We should repaint everything on invalidation of the scope container.
- EXPECT_DISPLAY_LIST(GetPaintController().NewDisplayItemList(), 4,
- TestDisplayItem(multicol, kBackgroundType),
- TestDisplayItem(content, kForegroundType),
- TestDisplayItem(content, kForegroundType),
- TestDisplayItem(content, kForegroundType));
+ EXPECT_THAT(GetPaintController().NewDisplayItemList(),
+ ElementsAre(IsSameId(&multicol, kBackgroundType),
+ IsSameId(&content, kForegroundType),
+ IsSameId(&content, kForegroundType),
+ IsSameId(&content, kForegroundType)));
EXPECT_NE(record1, static_cast<const DrawingDisplayItem&>(
GetPaintController().NewDisplayItemList()[1])
.GetPaintRecord());
@@ -1343,8 +1298,7 @@ TEST_P(PaintControllerTest, SkipCache) {
.GetPaintRecord());
CommitAndFinishCycle();
-
- EXPECT_EQ(1u, GetPaintController().PaintChunks().size());
+ EXPECT_DEFAULT_ROOT_CHUNK(4);
}
TEST_P(PaintControllerTest, PartialSkipCache) {
@@ -1364,10 +1318,10 @@ TEST_P(PaintControllerTest, PartialSkipCache) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(content, kBackgroundType),
- TestDisplayItem(content, kForegroundType),
- TestDisplayItem(content, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&content, kBackgroundType),
+ IsSameId(&content, kForegroundType),
+ IsSameId(&content, kForegroundType)));
sk_sp<const PaintRecord> record0 =
static_cast<const DrawingDisplayItem&>(
GetPaintController().GetDisplayItemList()[0])
@@ -1404,10 +1358,10 @@ TEST_P(PaintControllerTest, PartialSkipCache) {
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 3,
- TestDisplayItem(content, kBackgroundType),
- TestDisplayItem(content, kForegroundType),
- TestDisplayItem(content, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&content, kBackgroundType),
+ IsSameId(&content, kForegroundType),
+ IsSameId(&content, kForegroundType)));
EXPECT_NE(record0, static_cast<const DrawingDisplayItem&>(
GetPaintController().GetDisplayItemList()[0])
.GetPaintRecord());
@@ -1542,11 +1496,11 @@ TEST_P(PaintControllerTest, InsertValidItemInFront) {
EXPECT_EQ(0, NumCachedNewItems());
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(third, kBackgroundType),
- TestDisplayItem(fourth, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&third, kBackgroundType),
+ IsSameId(&fourth, kBackgroundType)));
EXPECT_TRUE(first.IsValid());
EXPECT_TRUE(second.IsValid());
EXPECT_TRUE(third.IsValid());
@@ -1567,9 +1521,9 @@ TEST_P(PaintControllerTest, InsertValidItemInFront) {
#endif
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(third, kBackgroundType),
- TestDisplayItem(fourth, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&third, kBackgroundType),
+ IsSameId(&fourth, kBackgroundType)));
EXPECT_TRUE(first.IsValid());
EXPECT_TRUE(second.IsValid());
EXPECT_TRUE(third.IsValid());
@@ -1591,17 +1545,67 @@ TEST_P(PaintControllerTest, InsertValidItemInFront) {
#endif
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 4,
- TestDisplayItem(first, kBackgroundType),
- TestDisplayItem(second, kBackgroundType),
- TestDisplayItem(third, kBackgroundType),
- TestDisplayItem(fourth, kBackgroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&first, kBackgroundType),
+ IsSameId(&second, kBackgroundType),
+ IsSameId(&third, kBackgroundType),
+ IsSameId(&fourth, kBackgroundType)));
EXPECT_TRUE(first.IsValid());
EXPECT_TRUE(second.IsValid());
EXPECT_TRUE(third.IsValid());
EXPECT_TRUE(fourth.IsValid());
}
+TEST_P(PaintControllerTest, TransientPaintControllerIncompleteCycle) {
+ auto paint_controller = PaintController::Create(PaintController::kTransient);
+ GraphicsContext context(*paint_controller);
+ FakeDisplayItemClient client("client", LayoutRect(100, 100, 50, 50));
+ InitRootChunk(*paint_controller);
+ DrawRect(context, client, kBackgroundType, FloatRect(100, 100, 50, 50));
+ // The client of a transient paint controller can abort without
+ // CommintNewDisplayItems() and FinishCycle(). This should not crash.
+ paint_controller = nullptr;
+}
+
+TEST_P(PaintControllerTest, AllowDuplicatedIdForUncacheableItem) {
+ if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled())
+ return;
+
+ LayoutRect r(100, 100, 300, 300);
+ FakeDisplayItemClient cacheable("cacheable", r);
+ FakeDisplayItemClient uncacheable("uncacheable", r);
+ GraphicsContext context(GetPaintController());
+
+ uncacheable.Invalidate(PaintInvalidationReason::kUncacheable);
+ EXPECT_TRUE(cacheable.IsCacheable());
+ EXPECT_FALSE(uncacheable.IsCacheable());
+
+ InitRootChunk();
+ {
+ SubsequenceRecorder recorder(context, cacheable);
+ DrawRect(context, cacheable, kBackgroundType, FloatRect(r));
+ DrawRect(context, uncacheable, kBackgroundType, FloatRect(r));
+ // This should not trigger the duplicated id assert.
+ DrawRect(context, uncacheable, kBackgroundType, FloatRect(r));
+ }
+
+ CommitAndFinishCycle();
+ EXPECT_TRUE(GetPaintController().GetDisplayItemList()[0].IsCacheable());
+ EXPECT_FALSE(GetPaintController().GetDisplayItemList()[1].IsCacheable());
+ EXPECT_FALSE(GetPaintController().GetDisplayItemList()[2].IsCacheable());
+ EXPECT_TRUE(cacheable.IsCacheable());
+ EXPECT_FALSE(uncacheable.IsCacheable());
+
+ InitRootChunk();
+ EXPECT_TRUE(GetPaintController().UseCachedSubsequenceIfPossible(cacheable));
+ CommitAndFinishCycle();
+ EXPECT_TRUE(GetPaintController().GetDisplayItemList()[0].IsCacheable());
+ EXPECT_FALSE(GetPaintController().GetDisplayItemList()[1].IsCacheable());
+ EXPECT_FALSE(GetPaintController().GetDisplayItemList()[2].IsCacheable());
+ EXPECT_TRUE(cacheable.IsCacheable());
+ EXPECT_FALSE(uncacheable.IsCacheable());
+}
+
// Death tests don't work properly on Android.
#if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID)
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h
index 2ec882b5332..572b17be415 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_controller_test.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PAINT_CONTROLLER_TEST_H_
+#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
@@ -17,12 +18,6 @@ class GraphicsContext;
class PaintControllerTestBase : public testing::Test {
public:
- PaintControllerTestBase()
- : root_paint_property_client_("root"),
- root_paint_chunk_id_(root_paint_property_client_,
- DisplayItem::kUninitializedType),
- paint_controller_(PaintController::Create()) {}
-
static void DrawNothing(GraphicsContext& context,
const DisplayItemClient& client,
DisplayItem::Type type) {
@@ -42,13 +37,22 @@ class PaintControllerTestBase : public testing::Test {
context.DrawRect(RoundedIntRect(FloatRect(bounds)));
}
+ protected:
+ PaintControllerTestBase()
+ : root_paint_property_client_("root"),
+ root_paint_chunk_id_(root_paint_property_client_,
+ DisplayItem::kUninitializedType),
+ paint_controller_(PaintController::Create()) {}
+
void InitRootChunk() { InitRootChunk(GetPaintController()); }
void InitRootChunk(PaintController& paint_controller) {
paint_controller.UpdateCurrentPaintChunkProperties(
root_paint_chunk_id_, DefaultPaintChunkProperties());
}
+ const PaintChunk::Id DefaultRootChunkId() const {
+ return root_paint_chunk_id_;
+ }
- protected:
PaintController& GetPaintController() { return *paint_controller_; }
int NumCachedNewItems() const {
@@ -92,37 +96,39 @@ class PaintControllerTestBase : public testing::Test {
std::unique_ptr<PaintController> paint_controller_;
};
-class TestDisplayItem final : public DisplayItem {
- public:
- TestDisplayItem(const DisplayItemClient& client, Type type)
- : DisplayItem(client, type, sizeof(*this)) {}
-
- void Replay(GraphicsContext&) const final { NOTREACHED(); }
- void AppendToDisplayItemList(const FloatSize&,
- cc::DisplayItemList&) const final {
- NOTREACHED();
- }
-};
-
-#define EXPECT_DISPLAY_LIST(actual, expected_size, ...) \
- do { \
- EXPECT_EQ((size_t)expected_size, actual.size()); \
- if (expected_size != actual.size()) \
- break; \
- const TestDisplayItem expected[] = {__VA_ARGS__}; \
- for (size_t i = 0; i < expected_size; ++i) { \
- SCOPED_TRACE( \
- String::Format("%d: Expected:(client=%p:\"%s\" type=%d) " \
- "Actual:(client=%p:%s type=%d)", \
- (int)i, &expected[i].Client(), \
- expected[i].Client().DebugName().Ascii().data(), \
- (int)expected[i].GetType(), &actual[i].Client(), \
- actual[i].Client().DebugName().Ascii().data(), \
- (int)actual[i].GetType())); \
- EXPECT_EQ(&expected[i].Client(), &actual[i].Client()); \
- EXPECT_EQ(expected[i].GetType(), actual[i].GetType()); \
- } \
- } while (false);
+// Matcher for checking display item list. Sample usage:
+// EXPECT_THAT(paint_controller.GetDisplayItemList(),
+// ElementsAre(IsSameId(client1, kBackgroundType),
+// IsSameId(client2, kForegroundType)));
+MATCHER_P(IsSameId, id, "") {
+ return arg.GetId() == id;
+}
+MATCHER_P2(IsSameId, client, type, "") {
+ return arg.GetId() == DisplayItem::Id(*client, type);
+}
+
+// Matcher for checking paint chunks. Sample usage:
+// EXPACT_THAT(paint_controller.PaintChunks(),
+// ELementsAre(IsPaintChunk(0, 1, id1, properties1),
+// IsPaintChunk(1, 3, id2, properties2)));
+inline bool CheckChunk(const PaintChunk& chunk,
+ size_t begin,
+ size_t end,
+ const PaintChunk::Id& id,
+ const PropertyTreeState& properties,
+ const HitTestData* hit_test_data = nullptr) {
+ return chunk.begin_index == begin && chunk.end_index == end &&
+ chunk.id == id && chunk.properties == properties &&
+ ((!chunk.hit_test_data && !hit_test_data) ||
+ (chunk.hit_test_data && hit_test_data &&
+ *chunk.hit_test_data == *hit_test_data));
+}
+MATCHER_P4(IsPaintChunk, begin, end, id, properties, "") {
+ return CheckChunk(arg, begin, end, id, properties);
+}
+MATCHER_P5(IsPaintChunk, begin, end, id, properties, hit_test_data, "") {
+ return CheckChunk(arg, begin, end, id, properties, &hit_test_data);
+}
// Shorter names for frequently used display item types in tests.
const DisplayItem::Type kBackgroundType = DisplayItem::kBoxDecorationBackground;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h
index 97aeb406b29..46899a783e8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_property_node.h
@@ -74,8 +74,9 @@ class PaintPropertyNode : public RefCounted<NodeType> {
return true;
}
- void ClearChangedToRoot() const {
- for (auto* n = this; n; n = n->Parent())
+ void ClearChangedToRoot() const { ClearChangedTo(nullptr); }
+ void ClearChangedTo(const NodeType* node) const {
+ for (auto* n = this; n && n != node; n = n->Parent())
n->changed_ = false;
}
@@ -143,6 +144,13 @@ class PaintPropertyNode : public RefCounted<NodeType> {
// nodes that do not affect rendering and are ignored for the purposes of
// display item list generation.
bool is_parent_alias_ = false;
+
+ // Indicates that the paint property value changed in the last update in the
+ // prepaint lifecycle step. This is used for raster invalidation and damage
+ // in the compositor. This value is cleared through |ClearChangedTo*|. With
+ // BlinkGenPropertyTrees, this is cleared explicitly at the end of paint (see:
+ // LocalFrameView::RunPaintLifecyclePhase), otherwise this is cleared through
+ // PaintController::FinishCycle.
mutable bool changed_ = true;
#if DCHECK_IS_ON()
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_record_builder_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_record_builder_test.cc
index baac60ed768..712f046da51 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/paint_record_builder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/paint_record_builder_test.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/platform/testing/fake_display_item_client.h"
using testing::_;
+using testing::ElementsAre;
namespace blink {
@@ -27,9 +28,9 @@ TEST_F(PaintRecordBuilderTest, TransientPaintController) {
EXPECT_CALL(canvas, drawPicture(_)).Times(1);
builder.EndRecording(canvas);
- EXPECT_DISPLAY_LIST(context.GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(client, kBackgroundType),
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(context.GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType),
+ IsSameId(&client, kForegroundType)));
EXPECT_FALSE(ClientCacheIsValid(context.GetPaintController(), client));
}
@@ -51,9 +52,9 @@ TEST_F(PaintRecordBuilderTest, LastingPaintController) {
builder.EndRecording(canvas);
EXPECT_TRUE(ClientCacheIsValid(client));
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(client, kBackgroundType),
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType),
+ IsSameId(&client, kForegroundType)));
InitRootChunk();
EXPECT_TRUE(DrawingRecorder::UseCachedDrawingIfPossible(context, client,
@@ -63,9 +64,9 @@ TEST_F(PaintRecordBuilderTest, LastingPaintController) {
EXPECT_CALL(canvas, drawPicture(_)).Times(1);
builder.EndRecording(canvas);
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(client, kBackgroundType),
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType),
+ IsSameId(&client, kForegroundType)));
EXPECT_TRUE(ClientCacheIsValid(client));
}
@@ -77,9 +78,9 @@ TEST_F(PaintRecordBuilderTest, TransientAndAnotherPaintController) {
DrawRect(context, client, kBackgroundType, FloatRect(10, 10, 20, 20));
DrawRect(context, client, kForegroundType, FloatRect(15, 15, 10, 10));
CommitAndFinishCycle();
- EXPECT_DISPLAY_LIST(GetPaintController().GetDisplayItemList(), 2,
- TestDisplayItem(client, kBackgroundType),
- TestDisplayItem(client, kForegroundType));
+ EXPECT_THAT(GetPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&client, kBackgroundType),
+ IsSameId(&client, kForegroundType)));
// EXPECT_TRUE(ClientCacheIsValid(client));
PaintRecordBuilder builder;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc
index 452637674a4..741fe872bc8 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc
@@ -22,29 +22,6 @@ PropertyTreeState PropertyTreeState::Unalias() const {
effect_ ? effect_->Unalias() : nullptr);
}
-const CompositorElementId PropertyTreeState::GetCompositorElementId(
- const CompositorElementIdSet& element_ids) const {
- // The effect or transform nodes could have a compositor element id. The order
- // doesn't matter as the element id should be the same on all that have a
- // non-default CompositorElementId.
- //
- // Note that PropertyTreeState acts as a context that accumulates state as we
- // traverse the tree building layers. This means that we could see a
- // compositor element id 'A' for a parent layer in conjunction with a
- // compositor element id 'B' for a child layer. To preserve uniqueness of
- // element ids, then, we check for presence in the |element_ids| set (which
- // represents element ids already previously attached to a layer). This is an
- // interim step while we pursue broader rework of animation subsystem noted in
- // http://crbug.com/709137.
- if (Effect()->GetCompositorElementId() &&
- !element_ids.Contains(Effect()->GetCompositorElementId()))
- return Effect()->GetCompositorElementId();
- if (Transform()->GetCompositorElementId() &&
- !element_ids.Contains(Transform()->GetCompositorElementId()))
- return Transform()->GetCompositorElementId();
- return CompositorElementId();
-}
-
String PropertyTreeState::ToString() const {
return String::Format("t:%p c:%p e:%p", Transform(), Clip(), Effect());
}
@@ -64,4 +41,8 @@ size_t PropertyTreeState::CacheMemoryUsageInBytes() const {
Transform()->CacheMemoryUsageInBytes();
}
+std::ostream& operator<<(std::ostream& os, const PropertyTreeState& state) {
+ return os << state.ToString().Utf8().data();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.h b/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.h
index 60d60a0acee..4cb5d2b6b1b 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state.h
@@ -8,9 +8,6 @@
#include "third_party/blink/renderer/platform/graphics/paint/clip_paint_property_node.h"
#include "third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h"
#include "third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h"
-#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
-#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -41,12 +38,6 @@ class PLATFORM_EXPORT PropertyTreeState {
static const PropertyTreeState& Root();
- // Returns the compositor element id, if any, for this property state. If
- // neither the effect nor transform nodes have a compositor element id then a
- // default instance is returned.
- const CompositorElementId GetCompositorElementId(
- const CompositorElementIdSet& element_ids) const;
-
void ClearChangedToRoot() const {
Transform()->ClearChangedToRoot();
Clip()->ClearChangedToRoot();
@@ -78,6 +69,9 @@ inline bool operator!=(const PropertyTreeState& a, const PropertyTreeState& b) {
return !(a == b);
}
+PLATFORM_EXPORT std::ostream& operator<<(std::ostream&,
+ const PropertyTreeState&);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_PROPERTY_TREE_STATE_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state_test.cc
index 52027813c4d..6fbb0f1e131 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/property_tree_state_test.cc
@@ -10,81 +10,4 @@ namespace blink {
class PropertyTreeStateTest : public testing::Test {};
-static scoped_refptr<TransformPaintPropertyNode>
-CreateTransformWithCompositorElementId(
- const CompositorElementId& compositor_element_id) {
- TransformPaintPropertyNode::State state;
- state.compositor_element_id = compositor_element_id;
- return TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(),
- std::move(state));
-}
-
-static scoped_refptr<EffectPaintPropertyNode>
-CreateEffectWithCompositorElementId(
- const CompositorElementId& compositor_element_id) {
- EffectPaintPropertyNode::State state;
- state.compositor_element_id = compositor_element_id;
- return EffectPaintPropertyNode::Create(EffectPaintPropertyNode::Root(),
- std::move(state));
-}
-
-TEST_F(PropertyTreeStateTest, CompositorElementIdNoElementIdOnAnyNode) {
- EXPECT_EQ(CompositorElementId(),
- PropertyTreeState::Root().GetCompositorElementId(
- CompositorElementIdSet()));
-}
-
-TEST_F(PropertyTreeStateTest, CompositorElementIdWithElementIdOnTransformNode) {
- CompositorElementId expected_compositor_element_id = CompositorElementId(2);
- auto transform =
- CreateTransformWithCompositorElementId(expected_compositor_element_id);
- PropertyTreeState state(transform.get(), &ClipPaintPropertyNode::Root(),
- &EffectPaintPropertyNode::Root());
- EXPECT_EQ(expected_compositor_element_id,
- state.GetCompositorElementId(CompositorElementIdSet()));
-}
-
-TEST_F(PropertyTreeStateTest, CompositorElementIdWithElementIdOnEffectNode) {
- CompositorElementId expected_compositor_element_id = CompositorElementId(2);
- auto effect =
- CreateEffectWithCompositorElementId(expected_compositor_element_id);
- PropertyTreeState state(&TransformPaintPropertyNode::Root(),
- &ClipPaintPropertyNode::Root(), effect.get());
- EXPECT_EQ(expected_compositor_element_id,
- state.GetCompositorElementId(CompositorElementIdSet()));
-}
-
-TEST_F(PropertyTreeStateTest, CompositorElementIdWithElementIdOnMultipleNodes) {
- CompositorElementId expected_compositor_element_id = CompositorElementId(2);
- auto transform =
- CreateTransformWithCompositorElementId(expected_compositor_element_id);
- auto effect =
- CreateEffectWithCompositorElementId(expected_compositor_element_id);
- PropertyTreeState state(transform.get(), &ClipPaintPropertyNode::Root(),
- effect.get());
- EXPECT_EQ(expected_compositor_element_id,
- state.GetCompositorElementId(CompositorElementIdSet()));
-}
-
-TEST_F(PropertyTreeStateTest, CompositorElementIdWithDifferingElementIds) {
- CompositorElementId first_compositor_element_id = CompositorElementId(2);
- CompositorElementId second_compositor_element_id = CompositorElementId(3);
- auto transform =
- CreateTransformWithCompositorElementId(first_compositor_element_id);
- auto effect =
- CreateEffectWithCompositorElementId(second_compositor_element_id);
- PropertyTreeState state(transform.get(), &ClipPaintPropertyNode::Root(),
- effect.get());
-
- CompositorElementIdSet composited_element_ids;
- composited_element_ids.insert(first_compositor_element_id);
- EXPECT_EQ(second_compositor_element_id,
- state.GetCompositorElementId(composited_element_ids));
-
- composited_element_ids.clear();
- composited_element_ids.insert(second_compositor_element_id);
- EXPECT_EQ(first_compositor_element_id,
- state.GetCompositorElementId(composited_element_ids));
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.cc
index 4f3e4ac3f31..8039f0680d3 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.h"
#include "SkImageFilter.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "third_party/blink/renderer/platform/geometry/geometry_as_json.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidator_test.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidator_test.cc
index 7f8306e2703..13cbaaab2ea 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidator_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/raster_invalidator_test.cc
@@ -688,4 +688,103 @@ TEST_F(RasterInvalidatorTest, EffectLocalTransformSpaceChangeNoInvalidation) {
FinishCycle(*artifact);
}
+TEST_P(RasterInvalidatorTest, AliasEffectParentChanges) {
+ RasterInvalidator invalidator(kNoopRasterInvalidation);
+
+ CompositorFilterOperations filter;
+ filter.AppendOpacityFilter(0.5);
+ // Create an effect and an alias for that effect.
+ auto e1 = CreateFilterEffect(e0(), &t0(), &c0(), filter);
+ auto alias_effect = EffectPaintPropertyNode::CreateAlias(*e1);
+
+ // The artifact has a chunk pointing to the alias.
+ PropertyTreeState layer_state(&t0(), &c0(), &e0());
+ PropertyTreeState chunk_state(&t0(), &c0(), alias_effect.get());
+ auto artifact = TestPaintArtifact().Chunk(0).Properties(chunk_state).Build();
+
+ invalidator.Generate(artifact, kDefaultLayerBounds, layer_state);
+ FinishCycle(*artifact);
+
+ invalidator.SetTracksRasterInvalidations(true);
+ // Reparent the aliased effect, so the chunk doesn't change the actual alias
+ // node, but its parent is now different.
+ alias_effect->Update(e0(), EffectPaintPropertyNode::State{});
+
+ // We expect to get invalidations since the effect unaliased effect is
+ // actually different now.
+ invalidator.Generate(artifact, kDefaultLayerBounds, layer_state);
+ const auto& invalidations = TrackedRasterInvalidations(invalidator);
+ ASSERT_EQ(1u, invalidations.size());
+ EXPECT_CHUNK_INVALIDATION(invalidations, 0, artifact->PaintChunks()[0],
+ PaintInvalidationReason::kPaintProperty);
+ FinishCycle(*artifact);
+}
+
+TEST_P(RasterInvalidatorTest, NestedAliasEffectParentChanges) {
+ RasterInvalidator invalidator(kNoopRasterInvalidation);
+
+ CompositorFilterOperations filter;
+ filter.AppendOpacityFilter(0.5);
+ // Create an effect and an alias for that effect.
+ auto e1 = CreateFilterEffect(e0(), &t0(), &c0(), filter);
+ auto alias_effect_1 = EffectPaintPropertyNode::CreateAlias(*e1);
+ auto alias_effect_2 = EffectPaintPropertyNode::CreateAlias(*alias_effect_1);
+
+ // The artifact has a chunk pointing to the nested alias.
+ PropertyTreeState layer_state(&t0(), &c0(), &e0());
+ PropertyTreeState chunk_state(&t0(), &c0(), alias_effect_2.get());
+ auto artifact = TestPaintArtifact().Chunk(0).Properties(chunk_state).Build();
+
+ invalidator.Generate(artifact, kDefaultLayerBounds, layer_state);
+ FinishCycle(*artifact);
+
+ invalidator.SetTracksRasterInvalidations(true);
+ // Reparent the parent aliased effect, so the chunk doesn't change the actual
+ // alias node, but its parent is now different, this also ensures that the
+ // nested alias is unchanged.
+ alias_effect_1->Update(e0(), EffectPaintPropertyNode::State{});
+
+ // We expect to get invalidations since the effect unaliased effect is
+ // actually different now.
+ invalidator.Generate(artifact, kDefaultLayerBounds, layer_state);
+ const auto& invalidations = TrackedRasterInvalidations(invalidator);
+ ASSERT_EQ(1u, invalidations.size());
+ EXPECT_CHUNK_INVALIDATION(invalidations, 0, artifact->PaintChunks()[0],
+ PaintInvalidationReason::kPaintProperty);
+ FinishCycle(*artifact);
+}
+
+TEST_P(RasterInvalidatorTest, EffectWithAliasTransformWhoseParentChanges) {
+ RasterInvalidator invalidator(kNoopRasterInvalidation);
+
+ auto t1 = CreateTransform(t0(), TransformationMatrix().Scale(5));
+ auto alias_transform = TransformPaintPropertyNode::CreateAlias(*t1);
+
+ CompositorFilterOperations filter;
+ filter.AppendBlurFilter(0);
+ // Create an effect and an alias for that effect.
+ auto e1 = CreateFilterEffect(e0(), alias_transform.get(), &c0(), filter);
+
+ // The artifact has a chunk pointing to the alias.
+ PropertyTreeState layer_state(&t0(), &c0(), &e0());
+ PropertyTreeState chunk_state(&t0(), &c0(), e1.get());
+ auto artifact = TestPaintArtifact().Chunk(0).Properties(chunk_state).Build();
+
+ invalidator.Generate(artifact, kDefaultLayerBounds, layer_state);
+ FinishCycle(*artifact);
+
+ invalidator.SetTracksRasterInvalidations(true);
+ // Reparent the aliased effect, so the chunk doesn't change the actual alias
+ // node, but its parent is now different.
+ alias_transform->Update(t0(), TransformPaintPropertyNode::State{});
+
+ // We expect to get invalidations since the effect unaliased effect is
+ // actually different now.
+ invalidator.Generate(artifact, kDefaultLayerBounds, layer_state);
+ const auto& invalidations = TrackedRasterInvalidations(invalidator);
+ ASSERT_EQ(1u, invalidations.size());
+ EXPECT_CHUNK_INVALIDATION(invalidations, 0, artifact->PaintChunks()[0],
+ PaintInvalidationReason::kPaintProperty);
+ FinishCycle(*artifact);
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.cc b/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.cc
index 43fb4206792..fe890492952 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.cc
@@ -17,27 +17,4 @@ const RefCountedPropertyTreeState& RefCountedPropertyTreeState::Root() {
return *root;
}
-const CompositorElementId RefCountedPropertyTreeState::GetCompositorElementId(
- const CompositorElementIdSet& element_ids) const {
- // The effect or transform nodes could have a compositor element id. The order
- // doesn't matter as the element id should be the same on all that have a
- // non-default CompositorElementId.
- //
- // Note that RefCountedPropertyTreeState acts as a context that accumulates
- // state as we traverse the tree building layers. This means that we could see
- // a compositor element id 'A' for a parent layer in conjunction with a
- // compositor element id 'B' for a child layer. To preserve uniqueness of
- // element ids, then, we check for presence in the |element_ids| set (which
- // represents element ids already previously attached to a layer). This is an
- // interim step while we pursue broader rework of animation subsystem noted in
- // http://crbug.com/709137.
- if (Effect()->GetCompositorElementId() &&
- !element_ids.Contains(Effect()->GetCompositorElementId()))
- return Effect()->GetCompositorElementId();
- if (Transform()->GetCompositorElementId() &&
- !element_ids.Contains(Transform()->GetCompositorElementId()))
- return Transform()->GetCompositorElementId();
- return CompositorElementId();
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h b/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h
index 340d6e95116..35174a78d99 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h
@@ -6,9 +6,6 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_REF_COUNTED_PROPERTY_TREE_STATE_H_
#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h"
-#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
-#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -53,12 +50,6 @@ class PLATFORM_EXPORT RefCountedPropertyTreeState {
return PropertyTreeState(transform_.get(), clip_.get(), effect_.get());
}
- // Returns the compositor element id, if any, for this property state. If
- // neither the effect nor transform nodes have a compositor element id then a
- // default instance is returned.
- const CompositorElementId GetCompositorElementId(
- const CompositorElementIdSet& element_ids) const;
-
void ClearChangedToRoot() const {
Transform()->ClearChangedToRoot();
Clip()->ClearChangedToRoot();
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.cc b/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.cc
index 8fd5c50d98e..3fcb7a2f69f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.cc
@@ -44,8 +44,6 @@ const char* PaintInvalidationReasonToString(PaintInvalidationReason reason) {
return "subtree";
case PaintInvalidationReason::kSVGResource:
return "SVG resource change";
- case PaintInvalidationReason::kBackgroundOnScrollingContentsLayer:
- return "background on scrolling contents layer";
case PaintInvalidationReason::kCaret:
return "caret";
case PaintInvalidationReason::kDocumentMarker:
diff --git a/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h b/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h
index c81b0d2edf8..b257a69f4d0 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h
@@ -36,7 +36,6 @@ enum class PaintInvalidationReason : uint8_t {
kSubtree,
kSVGResource,
kBackground,
- kBackgroundOnScrollingContentsLayer,
kCaret,
kDocumentMarker,
kImage,
diff --git a/chromium/third_party/blink/renderer/platform/graphics/path.cc b/chromium/third_party/blink/renderer/platform/graphics/path.cc
index 1da4c73fe4e..cde993cb82c 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/path.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/path.cc
@@ -67,13 +67,16 @@ bool Path::operator==(const Path& other) const {
}
bool Path::Contains(const FloatPoint& point) const {
- return path_.contains(WebCoreFloatToSkScalar(point.X()),
- WebCoreFloatToSkScalar(point.Y()));
+ if (!std::isfinite(point.X()) || !std::isfinite(point.Y()))
+ return false;
+ return path_.contains(SkScalar(point.X()), SkScalar(point.Y()));
}
bool Path::Contains(const FloatPoint& point, WindRule rule) const {
- SkScalar x = WebCoreFloatToSkScalar(point.X());
- SkScalar y = WebCoreFloatToSkScalar(point.Y());
+ if (!std::isfinite(point.X()) || !std::isfinite(point.Y()))
+ return false;
+ SkScalar x = point.X();
+ SkScalar y = point.Y();
SkPath::FillType fill_type = WebCoreWindRuleToSkFillType(rule);
if (path_.getFillType() != fill_type) {
SkPath tmp(path_);
@@ -101,9 +104,10 @@ SkPath Path::StrokePath(const StrokeData& stroke_data) const {
bool Path::StrokeContains(const FloatPoint& point,
const StrokeData& stroke_data) const {
+ if (!std::isfinite(point.X()) || !std::isfinite(point.Y()))
+ return false;
return StrokePath(stroke_data)
- .contains(WebCoreFloatToSkScalar(point.X()),
- WebCoreFloatToSkScalar(point.Y()));
+ .contains(SkScalar(point.X()), SkScalar(point.Y()));
}
FloatRect Path::BoundingRect() const {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.cc b/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.cc
index 20da31898b3..6da2f942080 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.cc
@@ -59,8 +59,7 @@ scoped_refptr<PictureSnapshot> PictureSnapshot::Load(
pictures.ReserveCapacity(tiles.size());
FloatRect union_rect;
for (const auto& tile_stream : tiles) {
- sk_sp<SkPicture> picture = SkPicture::MakeFromData(
- tile_stream->data.begin(), tile_stream->data.size());
+ sk_sp<SkPicture> picture = std::move(tile_stream->picture);
if (!picture)
return nullptr;
FloatRect cull_rect(picture->cullRect());
diff --git a/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.h b/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.h
index aa9cbb1d27f..35565acfe55 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/picture_snapshot.h
@@ -52,7 +52,7 @@ class PLATFORM_EXPORT PictureSnapshot : public RefCounted<PictureSnapshot> {
public:
struct TilePictureStream : RefCounted<TilePictureStream> {
FloatPoint layer_offset;
- Vector<char> data;
+ sk_sp<SkPicture> picture;
};
static scoped_refptr<PictureSnapshot> Load(
diff --git a/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.cc b/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.cc
index f883e79c45b..67831cef073 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.cc
@@ -49,30 +49,36 @@ constexpr int kFontSize = 14;
void DrawIcon(cc::PaintCanvas* canvas,
const PaintFlags& flags,
float x,
- float y) {
+ float y,
+ float scale_factor) {
+ // Note that |icon_image| will be a 0x0 image when running
+ // blink_platform_unittests.
DEFINE_STATIC_REF(Image, icon_image,
(Image::LoadPlatformResource("placeholderIcon")));
- DCHECK(!icon_image->IsNull());
// Note that the |icon_image| is not scaled according to dest_rect / src_rect,
// and is always drawn at the same size. This is so that placeholder icons are
// visible (e.g. when replacing a large image that's scaled down to a small
// area) and so that all placeholder images on the same page look consistent.
- canvas->drawImageRect(icon_image->PaintImageForCurrentFrame(),
- IntRect(IntPoint::Zero(), icon_image->Size()),
- FloatRect(x, y, kIconWidth, kIconHeight), &flags,
- cc::PaintCanvas::kFast_SrcRectConstraint);
+ canvas->drawImageRect(
+ icon_image->PaintImageForCurrentFrame(),
+ IntRect(IntPoint::Zero(), icon_image->Size()),
+ FloatRect(x, y, scale_factor * kIconWidth, scale_factor * kIconHeight),
+ &flags, cc::PaintCanvas::kFast_SrcRectConstraint);
}
void DrawCenteredIcon(cc::PaintCanvas* canvas,
const PaintFlags& flags,
- const FloatRect& dest_rect) {
- DrawIcon(canvas, flags,
- dest_rect.X() + (dest_rect.Width() - kIconWidth) / 2.0f,
- dest_rect.Y() + (dest_rect.Height() - kIconHeight) / 2.0f);
+ const FloatRect& dest_rect,
+ float scale_factor) {
+ DrawIcon(
+ canvas, flags,
+ dest_rect.X() + (dest_rect.Width() - scale_factor * kIconWidth) / 2.0f,
+ dest_rect.Y() + (dest_rect.Height() - scale_factor * kIconHeight) / 2.0f,
+ scale_factor);
}
-FontDescription CreatePlaceholderFontDescription() {
+FontDescription CreatePlaceholderFontDescription(float scale_factor) {
FontDescription description;
description.FirstFamily().SetFamily("Roboto");
@@ -88,7 +94,7 @@ FontDescription CreatePlaceholderFontDescription() {
description.FirstFamily().AppendFamily(std::move(helvetica_neue));
description.SetGenericFamily(FontDescription::kSansSerifFamily);
- description.SetComputedSize(kFontSize);
+ description.SetComputedSize(scale_factor * kFontSize);
description.SetWeight(FontSelectionValue(500));
return description;
@@ -152,29 +158,47 @@ String FormatOriginalResourceSizeBytes(int64_t bytes) {
// can share the same Font.
class PlaceholderImage::SharedFont : public RefCounted<SharedFont> {
public:
- static scoped_refptr<SharedFont> GetOrCreateInstance() {
- if (g_instance_)
- return scoped_refptr<SharedFont>(g_instance_);
-
- scoped_refptr<SharedFont> shared_font(base::AdoptRef(new SharedFont()));
+ static scoped_refptr<SharedFont> GetOrCreateInstance(float scale_factor) {
+ if (g_instance_) {
+ scoped_refptr<SharedFont> shared_font(g_instance_);
+ shared_font->MaybeUpdateForScaleFactor(scale_factor);
+ return shared_font;
+ }
+
+ scoped_refptr<SharedFont> shared_font =
+ base::MakeRefCounted<SharedFont>(scale_factor);
g_instance_ = shared_font.get();
return shared_font;
}
+ // This constructor is public so that base::MakeRefCounted() can call it.
+ explicit SharedFont(float scale_factor)
+ : font_(CreatePlaceholderFontDescription(scale_factor)),
+ scale_factor_(scale_factor) {
+ font_.Update(nullptr);
+ }
+
~SharedFont() {
DCHECK_EQ(this, g_instance_);
g_instance_ = nullptr;
}
- const Font& font() const { return font_; }
+ void MaybeUpdateForScaleFactor(float scale_factor) {
+ if (scale_factor_ == scale_factor)
+ return;
- private:
- SharedFont() : font_(CreatePlaceholderFontDescription()) {
+ scale_factor_ = scale_factor;
+ font_ = Font(CreatePlaceholderFontDescription(scale_factor_));
font_.Update(nullptr);
}
+ const Font& font() const { return font_; }
+
+ private:
static SharedFont* g_instance_;
+
Font font_;
+ float scale_factor_;
};
// static
@@ -237,6 +261,15 @@ PaintImage PlaceholderImage::PaintImageForCurrentFrame() {
.TakePaintImage();
}
+void PlaceholderImage::SetIconAndTextScaleFactor(
+ float icon_and_text_scale_factor) {
+ if (icon_and_text_scale_factor_ == icon_and_text_scale_factor)
+ return;
+ icon_and_text_scale_factor_ = icon_and_text_scale_factor;
+ cached_text_width_.reset();
+ paint_record_for_current_frame_.reset();
+}
+
void PlaceholderImage::Draw(cc::PaintCanvas* canvas,
const PaintFlags& base_flags,
const FloatRect& dest_rect,
@@ -259,27 +292,35 @@ void PlaceholderImage::Draw(cc::PaintCanvas* canvas,
flags.setColor(SkColorSetARGB(0x80, 0xD9, 0xD9, 0xD9));
canvas->drawRect(dest_rect, flags);
- if (dest_rect.Width() < kIconWidth + 2 * kFeaturePaddingX ||
- dest_rect.Height() < kIconHeight + 2 * kIconPaddingY) {
+ if (dest_rect.Width() <
+ icon_and_text_scale_factor_ * (kIconWidth + 2 * kFeaturePaddingX) ||
+ dest_rect.Height() <
+ icon_and_text_scale_factor_ * (kIconHeight + 2 * kIconPaddingY)) {
return;
}
if (text_.IsEmpty()) {
- DrawCenteredIcon(canvas, base_flags, dest_rect);
+ DrawCenteredIcon(canvas, base_flags, dest_rect,
+ icon_and_text_scale_factor_);
return;
}
if (!shared_font_)
- shared_font_ = SharedFont::GetOrCreateInstance();
+ shared_font_ = SharedFont::GetOrCreateInstance(icon_and_text_scale_factor_);
+ else
+ shared_font_->MaybeUpdateForScaleFactor(icon_and_text_scale_factor_);
+
if (!cached_text_width_.has_value())
cached_text_width_ = shared_font_->font().Width(TextRun(text_));
const float icon_and_text_width =
cached_text_width_.value() +
- (kIconWidth + 2 * kFeaturePaddingX + kPaddingBetweenIconAndText);
+ icon_and_text_scale_factor_ *
+ (kIconWidth + 2 * kFeaturePaddingX + kPaddingBetweenIconAndText);
if (dest_rect.Width() < icon_and_text_width) {
- DrawCenteredIcon(canvas, base_flags, dest_rect);
+ DrawCenteredIcon(canvas, base_flags, dest_rect,
+ icon_and_text_scale_factor_);
return;
}
@@ -287,25 +328,32 @@ void PlaceholderImage::Draw(cc::PaintCanvas* canvas,
dest_rect.X() + (dest_rect.Width() - icon_and_text_width) / 2.0f;
const float feature_y =
dest_rect.Y() +
- (dest_rect.Height() - (kIconHeight + 2 * kIconPaddingY)) / 2.0f;
+ (dest_rect.Height() -
+ icon_and_text_scale_factor_ * (kIconHeight + 2 * kIconPaddingY)) /
+ 2.0f;
float icon_x, text_x;
if (Locale::DefaultLocale().IsRTL()) {
icon_x = feature_x + cached_text_width_.value() +
- (kFeaturePaddingX + kPaddingBetweenIconAndText);
- text_x = feature_x + kFeaturePaddingX;
+ icon_and_text_scale_factor_ *
+ (kFeaturePaddingX + kPaddingBetweenIconAndText);
+ text_x = feature_x + icon_and_text_scale_factor_ * kFeaturePaddingX;
} else {
- icon_x = feature_x + kFeaturePaddingX;
+ icon_x = feature_x + icon_and_text_scale_factor_ * kFeaturePaddingX;
text_x = feature_x +
- (kFeaturePaddingX + kIconWidth + kPaddingBetweenIconAndText);
+ icon_and_text_scale_factor_ *
+ (kFeaturePaddingX + kIconWidth + kPaddingBetweenIconAndText);
}
- DrawIcon(canvas, base_flags, icon_x, feature_y + kIconPaddingY);
+ DrawIcon(canvas, base_flags, icon_x,
+ feature_y + icon_and_text_scale_factor_ * kIconPaddingY,
+ icon_and_text_scale_factor_);
flags.setColor(SkColorSetARGB(0xAB, 0, 0, 0));
shared_font_->font().DrawBidiText(
canvas, TextRunPaintInfo(TextRun(text_)),
- FloatPoint(text_x, feature_y + (kTextPaddingY + kFontSize)),
+ FloatPoint(text_x, feature_y + icon_and_text_scale_factor_ *
+ (kTextPaddingY + kFontSize)),
Font::kUseFallbackIfFontNotReady, 1.0f, flags);
}
@@ -339,4 +387,8 @@ Image::SizeAvailability PlaceholderImage::SetData(scoped_refptr<SharedBuffer>,
return Image::kSizeAvailable;
}
+const Font* PlaceholderImage::GetFontForTesting() const {
+ return shared_font_ ? &shared_font_->font() : nullptr;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.h b/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.h
index e869f990d91..e6a2647bbba 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/placeholder_image.h
@@ -21,6 +21,7 @@ namespace blink {
class FloatPoint;
class FloatRect;
class FloatSize;
+class Font;
class GraphicsContext;
class ImageObserver;
@@ -62,6 +63,9 @@ class PLATFORM_EXPORT PlaceholderImage final : public Image {
bool IsPlaceholderImage() const override;
const String& GetTextForTesting() const { return text_; }
+ const Font* GetFontForTesting() const;
+
+ void SetIconAndTextScaleFactor(float icon_and_text_scale_factor);
private:
PlaceholderImage(ImageObserver*,
@@ -90,6 +94,8 @@ class PLATFORM_EXPORT PlaceholderImage final : public Image {
// This placeholder image is used for lazyloading of images.
bool is_lazy_image_;
+ float icon_and_text_scale_factor_ = 1.0f;
+
class SharedFont;
// Lazily initialized. All instances of PlaceholderImage will share the same
// Font object, wrapped as a SharedFont.
diff --git a/chromium/third_party/blink/renderer/platform/graphics/placeholder_image_test.cc b/chromium/third_party/blink/renderer/platform/graphics/placeholder_image_test.cc
index 5df5aca22ec..b3367adea8f 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/placeholder_image_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/placeholder_image_test.cc
@@ -6,16 +6,204 @@
#include <stdint.h>
+#include "base/memory/scoped_refptr.h"
+#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/web_localized_string.h"
#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/renderer/platform/fonts/font.h"
+#include "third_party/blink/renderer/platform/fonts/font_description.h"
+#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
+#include "third_party/blink/renderer/platform/graphics/image.h"
+#include "third_party/blink/renderer/platform/graphics/image_orientation.h"
+#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
+#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
+#include "third_party/blink/renderer/platform/graphics/test/mock_paint_canvas.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
+#include "third_party/blink/renderer/platform/text/platform_locale.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/skia/include/core/SkColor.h"
+#include "third_party/skia/include/core/SkRect.h"
namespace blink {
namespace {
+using testing::_;
+using testing::AllOf;
+using testing::FloatNear;
+using testing::InvokeWithoutArgs;
+using testing::Property;
+
+constexpr float kBaseIconWidth = 24.0f;
+constexpr float kBaseIconHeight = 24.0f;
+constexpr float kBaseFeaturePaddingX = 8.0f;
+constexpr float kBaseIconPaddingY = 5.0f;
+
+constexpr float kBasePaddingBetweenIconAndText = 2.0f;
+constexpr float kBaseTextPaddingY = 9.0f;
+constexpr float kBaseFontSize = 14.0f;
+
+constexpr float kBaseIconOnlyFeatureWidth =
+ kBaseFeaturePaddingX + kBaseIconWidth + kBaseFeaturePaddingX;
+constexpr float kBaseFeatureHeight =
+ kBaseIconPaddingY + kBaseIconHeight + kBaseIconPaddingY;
+
+void ExpectDrawGrayBox(MockPaintCanvas& canvas,
+ const FloatRect& expected_rect) {
+ EXPECT_CALL(
+ canvas,
+ drawRect(AllOf(Property(&SkRect::x, FloatNear(expected_rect.X(), 0.01)),
+ Property(&SkRect::y, FloatNear(expected_rect.Y(), 0.01)),
+ Property(&SkRect::width,
+ FloatNear(expected_rect.Width(), 0.01)),
+ Property(&SkRect::height,
+ FloatNear(expected_rect.Height(), 0.01))),
+ AllOf(Property(&PaintFlags::getStyle, PaintFlags::kFill_Style),
+ Property(&PaintFlags::getColor,
+ SkColorSetARGB(0x80, 0xD9, 0xD9, 0xD9)))))
+ .Times(1);
+}
+
+void DrawImageExpectingGrayBoxOnly(PlaceholderImage& image,
+ const FloatRect& dest_rect) {
+ MockPaintCanvas canvas;
+ ExpectDrawGrayBox(canvas, dest_rect);
+ EXPECT_CALL(canvas, drawImageRect(_, _, _, _, _)).Times(0);
+ EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0);
+
+ image.Draw(&canvas, PaintFlags(), dest_rect,
+ FloatRect(0.0f, 0.0f, 100.0f, 100.0f),
+ kDoNotRespectImageOrientation, Image::kClampImageToSourceRect,
+ Image::kUnspecifiedDecode);
+}
+
+void DrawImageExpectingIconOnly(PlaceholderImage& image,
+ const FloatRect& dest_rect,
+ float scale_factor) {
+ MockPaintCanvas canvas;
+ ExpectDrawGrayBox(canvas, dest_rect);
+
+ EXPECT_CALL(
+ canvas,
+ drawImageRect(
+ /*image=*/_, /*src=*/_, /*dst=*/
+ AllOf(Property(&SkRect::x,
+ FloatNear(dest_rect.Center().X() -
+ scale_factor * kBaseIconWidth / 2.0f,
+ 0.01)),
+ Property(&SkRect::y,
+ FloatNear(dest_rect.Center().Y() -
+ scale_factor * kBaseIconHeight / 2.0f,
+ 0.01)),
+ Property(&SkRect::width,
+ FloatNear(scale_factor * kBaseIconWidth, 0.01)),
+ Property(&SkRect::height,
+ FloatNear(scale_factor * kBaseIconHeight, 0.01))),
+ /*flags=*/_, /*constraint=*/_))
+ .Times(1);
+
+ EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0);
+
+ image.Draw(&canvas, PaintFlags(), dest_rect,
+ FloatRect(0.0f, 0.0f, 100.0f, 100.0f),
+ kDoNotRespectImageOrientation, Image::kClampImageToSourceRect,
+ Image::kUnspecifiedDecode);
+}
+
+float GetExpectedPlaceholderTextWidth(const StringView& text,
+ float scale_factor) {
+ FontDescription description;
+ description.FirstFamily().SetFamily("Roboto");
+
+ scoped_refptr<SharedFontFamily> helvetica_neue = SharedFontFamily::Create();
+ helvetica_neue->SetFamily("Helvetica Neue");
+ scoped_refptr<SharedFontFamily> helvetica = SharedFontFamily::Create();
+ helvetica->SetFamily("Helvetica");
+ scoped_refptr<SharedFontFamily> arial = SharedFontFamily::Create();
+ arial->SetFamily("Arial");
+
+ helvetica->AppendFamily(std::move(arial));
+ helvetica_neue->AppendFamily(std::move(helvetica));
+ description.FirstFamily().AppendFamily(std::move(helvetica_neue));
+
+ description.SetGenericFamily(FontDescription::kSansSerifFamily);
+ description.SetComputedSize(scale_factor * 14.0f);
+ description.SetWeight(FontSelectionValue(500));
+
+ Font font(description);
+ font.Update(nullptr);
+ return font.Width(TextRun(text));
+}
+
+void DrawImageExpectingIconAndTextLTR(PlaceholderImage& image,
+ const FloatRect& dest_rect,
+ float scale_factor) {
+ EXPECT_FALSE(Locale::DefaultLocale().IsRTL());
+
+ MockPaintCanvas canvas;
+ ExpectDrawGrayBox(canvas, dest_rect);
+
+ const float expected_text_width =
+ GetExpectedPlaceholderTextWidth(image.GetTextForTesting(), scale_factor);
+ const float expected_feature_width =
+ scale_factor *
+ (kBaseIconOnlyFeatureWidth + kBasePaddingBetweenIconAndText) +
+ expected_text_width;
+ const float expected_feature_x =
+ dest_rect.Center().X() - expected_feature_width / 2.0f;
+ const float expected_feature_y =
+ dest_rect.Center().Y() - scale_factor * kBaseFeatureHeight / 2.0f;
+
+ EXPECT_CALL(
+ canvas,
+ drawImageRect(
+ /*image=*/_, /*src=*/_, /*dst=*/
+ AllOf(Property(&SkRect::x,
+ FloatNear(expected_feature_x +
+ scale_factor * kBaseFeaturePaddingX,
+ 0.01)),
+ Property(&SkRect::y,
+ FloatNear(expected_feature_y +
+ scale_factor * kBaseIconPaddingY,
+ 0.01)),
+ Property(&SkRect::width,
+ FloatNear(scale_factor * kBaseIconWidth, 0.01)),
+ Property(&SkRect::height,
+ FloatNear(scale_factor * kBaseIconHeight, 0.01))),
+ /*flags=*/_,
+ /*constraint=*/_))
+ .Times(1);
+
+ EXPECT_CALL(
+ canvas,
+ drawTextBlob(
+ _,
+ FloatNear(expected_feature_x +
+ scale_factor * (kBaseFeaturePaddingX + kBaseIconWidth +
+ kBasePaddingBetweenIconAndText),
+ 0.01),
+ FloatNear(expected_feature_y +
+ scale_factor * (kBaseTextPaddingY + kBaseFontSize),
+ 0.01),
+ AllOf(
+ Property(&PaintFlags::getStyle, PaintFlags::kFill_Style),
+ Property(&PaintFlags::getColor, SkColorSetARGB(0xAB, 0, 0, 0)))))
+ .WillOnce(InvokeWithoutArgs([&image, scale_factor]() {
+ EXPECT_NEAR(
+ scale_factor * kBaseFontSize,
+ image.GetFontForTesting()->GetFontDescription().ComputedSize(),
+ 0.01);
+ }));
+
+ image.Draw(&canvas, PaintFlags(), dest_rect,
+ FloatRect(0.0f, 0.0f, 100.0f, 100.0f),
+ kDoNotRespectImageOrientation, Image::kClampImageToSourceRect,
+ Image::kUnspecifiedDecode);
+}
+
class TestingUnitsPlatform : public TestingPlatformSupport {
public:
TestingUnitsPlatform() {}
@@ -44,8 +232,19 @@ class TestingUnitsPlatform : public TestingPlatformSupport {
TestingUnitsPlatform::~TestingUnitsPlatform() = default;
class PlaceholderImageTest : public testing::Test {
+ public:
+ void SetUp() override {
+ old_user_preferred_languages_ = UserPreferredLanguages();
+ OverrideUserPreferredLanguagesForTesting(Vector<AtomicString>(1U, "en-US"));
+ }
+
+ void TearDown() override {
+ OverrideUserPreferredLanguagesForTesting(old_user_preferred_languages_);
+ }
+
private:
ScopedTestingPlatformSupport<TestingUnitsPlatform> platform_;
+ Vector<AtomicString> old_user_preferred_languages_;
};
TEST_F(PlaceholderImageTest, FormatPlaceholderText) {
@@ -84,6 +283,214 @@ TEST_F(PlaceholderImageTest, FormatPlaceholderText) {
}
}
+TEST_F(PlaceholderImageTest, DrawLazyImage) {
+ MockPaintCanvas canvas;
+ EXPECT_CALL(canvas, drawRect(_, _)).Times(0);
+ EXPECT_CALL(canvas, drawImageRect(_, _, _, _, _)).Times(0);
+ EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0);
+
+ PlaceholderImage::CreateForLazyImages(nullptr, IntSize(800, 600))
+ ->Draw(&canvas, PaintFlags(), FloatRect(0.0f, 0.0f, 800.0f, 600.0f),
+ FloatRect(0.0f, 0.0f, 800.0f, 600.0f),
+ kDoNotRespectImageOrientation, Image::kClampImageToSourceRect,
+ Image::kUnspecifiedDecode);
+}
+
+TEST_F(PlaceholderImageTest, DrawNonIntersectingSrcRect) {
+ MockPaintCanvas canvas;
+ EXPECT_CALL(canvas, drawRect(_, _)).Times(0);
+ EXPECT_CALL(canvas, drawImageRect(_, _, _, _, _)).Times(0);
+ EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0);
+
+ PlaceholderImage::Create(nullptr, IntSize(800, 600), 0)
+ ->Draw(&canvas, PaintFlags(), FloatRect(0.0f, 0.0f, 800.0f, 600.0f),
+ // The source rectangle is outside the 800x600 bounds of the image,
+ // so nothing should be drawn.
+ FloatRect(1000.0f, 0.0f, 800.0f, 600.0f),
+ kDoNotRespectImageOrientation, Image::kClampImageToSourceRect,
+ Image::kUnspecifiedDecode);
+}
+
+TEST_F(PlaceholderImageTest, DrawWithoutOriginalResourceSize) {
+ scoped_refptr<PlaceholderImage> image =
+ PlaceholderImage::Create(nullptr, IntSize(800, 600), 0);
+
+ constexpr float kTestScaleFactors[] = {0.5f, 1.0f, 2.0f};
+ for (const float scale_factor : kTestScaleFactors) {
+ image->SetIconAndTextScaleFactor(scale_factor);
+
+ DrawImageExpectingGrayBoxOnly(
+ *image, FloatRect(1000.0f, 2000.0f,
+ scale_factor * kBaseIconOnlyFeatureWidth - 1.0f,
+ scale_factor * kBaseFeatureHeight + 1.0f));
+ DrawImageExpectingGrayBoxOnly(
+ *image, FloatRect(1000.0f, 2000.0f,
+ scale_factor * kBaseIconOnlyFeatureWidth + 1.0f,
+ scale_factor * kBaseFeatureHeight - 1.0f));
+
+ DrawImageExpectingIconOnly(
+ *image,
+ FloatRect(1000.0f, 2000.0f,
+ scale_factor * kBaseIconOnlyFeatureWidth + 1.0f,
+ scale_factor * kBaseFeatureHeight + 1.0f),
+ scale_factor);
+ DrawImageExpectingIconOnly(
+ *image, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), scale_factor);
+ }
+}
+
+TEST_F(PlaceholderImageTest, DrawWithOriginalResourceSizeLTR) {
+ scoped_refptr<PlaceholderImage> image =
+ PlaceholderImage::Create(nullptr, IntSize(800, 600), 50 * 1024);
+
+ String expected_text = "50 KB";
+ expected_text.Ensure16Bit();
+ EXPECT_EQ(expected_text, image->GetTextForTesting());
+
+ constexpr float kTestScaleFactors[] = {0.5f, 1.0f, 2.0f};
+ for (const float scale_factor : kTestScaleFactors) {
+ image->SetIconAndTextScaleFactor(scale_factor);
+
+ DrawImageExpectingGrayBoxOnly(
+ *image, FloatRect(1000.0f, 2000.0f,
+ scale_factor * kBaseIconOnlyFeatureWidth - 1.0f,
+ scale_factor * kBaseFeatureHeight + 1.0f));
+ DrawImageExpectingGrayBoxOnly(
+ *image, FloatRect(1000.0f, 2000.0f,
+ scale_factor * kBaseIconOnlyFeatureWidth + 1.0f,
+ scale_factor * kBaseFeatureHeight - 1.0f));
+ DrawImageExpectingGrayBoxOnly(
+ *image, FloatRect(1000.0f, 2000.0f, 800.0f,
+ scale_factor * kBaseFeatureHeight - 1.0f));
+
+ const float expected_text_width = GetExpectedPlaceholderTextWidth(
+ image->GetTextForTesting(), scale_factor);
+ const float expected_icon_and_text_width =
+ scale_factor *
+ (kBaseIconOnlyFeatureWidth + kBasePaddingBetweenIconAndText) +
+ expected_text_width;
+
+ DrawImageExpectingIconOnly(
+ *image,
+ FloatRect(1000.0f, 2000.0f,
+ scale_factor * kBaseIconOnlyFeatureWidth + 1.0f,
+ scale_factor * kBaseFeatureHeight + 1.0f),
+ scale_factor);
+ DrawImageExpectingIconOnly(
+ *image,
+ FloatRect(1000.0f, 2000.0f, expected_icon_and_text_width - 1.0f,
+ scale_factor * kBaseFeatureHeight + 1.0f),
+ scale_factor);
+
+ DrawImageExpectingIconAndTextLTR(
+ *image,
+ FloatRect(1000.0f, 2000.0f, expected_icon_and_text_width + 1.0f,
+ scale_factor * kBaseFeatureHeight + 1.0f),
+ scale_factor);
+ DrawImageExpectingIconAndTextLTR(
+ *image, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), scale_factor);
+ }
+}
+
+TEST_F(PlaceholderImageTest, DrawWithOriginalResourceSizeRTL) {
+ scoped_refptr<PlaceholderImage> image =
+ PlaceholderImage::Create(nullptr, IntSize(800, 600), 50 * 1024);
+
+ String expected_text = "50 KB";
+ expected_text.Ensure16Bit();
+ EXPECT_EQ(expected_text, image->GetTextForTesting());
+
+ OverrideUserPreferredLanguagesForTesting(Vector<AtomicString>(1U, "ar"));
+ EXPECT_TRUE(Locale::DefaultLocale().IsRTL());
+
+ static constexpr float kScaleFactor = 2.0f;
+ image->SetIconAndTextScaleFactor(kScaleFactor);
+
+ const FloatRect dest_rect(1000.0f, 2000.0f, 800.0f, 600.0f);
+
+ MockPaintCanvas canvas;
+ ExpectDrawGrayBox(canvas, dest_rect);
+
+ const float expected_text_width =
+ GetExpectedPlaceholderTextWidth(image->GetTextForTesting(), kScaleFactor);
+ const float expected_feature_width =
+ kScaleFactor *
+ (kBaseIconOnlyFeatureWidth + kBasePaddingBetweenIconAndText) +
+ expected_text_width;
+ const float expected_feature_x =
+ dest_rect.Center().X() - expected_feature_width / 2.0f;
+ const float expected_feature_y =
+ dest_rect.Center().Y() - kScaleFactor * kBaseFeatureHeight / 2.0f;
+
+ EXPECT_CALL(
+ canvas,
+ drawImageRect(
+ /*image=*/_, /*src=*/_, /*dst=*/
+ AllOf(Property(&SkRect::x,
+ FloatNear(expected_feature_x +
+ kScaleFactor *
+ (kBaseFeaturePaddingX +
+ kBasePaddingBetweenIconAndText) +
+ expected_text_width,
+ 0.01)),
+ Property(&SkRect::y,
+ FloatNear(expected_feature_y +
+ kScaleFactor * kBaseIconPaddingY,
+ 0.01)),
+ Property(&SkRect::width,
+ FloatNear(kScaleFactor * kBaseIconWidth, 0.01)),
+ Property(&SkRect::height,
+ FloatNear(kScaleFactor * kBaseIconHeight, 0.01))),
+ /*flags=*/_,
+ /*constraint=*/_))
+ .Times(1);
+
+ EXPECT_CALL(
+ canvas,
+ drawTextBlob(
+ _,
+ FloatNear(expected_feature_x + kScaleFactor * kBaseFeaturePaddingX,
+ 0.01),
+ FloatNear(expected_feature_y +
+ kScaleFactor * (kBaseTextPaddingY + kBaseFontSize),
+ 0.01),
+ AllOf(
+ Property(&PaintFlags::getStyle, PaintFlags::kFill_Style),
+ Property(&PaintFlags::getColor, SkColorSetARGB(0xAB, 0, 0, 0)))))
+ .WillOnce(InvokeWithoutArgs([image]() {
+ EXPECT_NEAR(
+ kScaleFactor * kBaseFontSize,
+ image->GetFontForTesting()->GetFontDescription().ComputedSize(),
+ 0.01);
+ }));
+
+ image->Draw(&canvas, PaintFlags(), dest_rect,
+ FloatRect(0.0f, 0.0f, 100.0f, 100.0f),
+ kDoNotRespectImageOrientation, Image::kClampImageToSourceRect,
+ Image::kUnspecifiedDecode);
+}
+
+TEST_F(PlaceholderImageTest, DrawSeparateImageWithDifferentScaleFactor) {
+ scoped_refptr<PlaceholderImage> image_1 =
+ PlaceholderImage::Create(nullptr, IntSize(800, 600), 50 * 1024);
+ constexpr float kScaleFactor1 = 0.5f;
+ image_1->SetIconAndTextScaleFactor(kScaleFactor1);
+
+ DrawImageExpectingIconAndTextLTR(
+ *image_1, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), kScaleFactor1);
+
+ scoped_refptr<PlaceholderImage> image_2 =
+ PlaceholderImage::Create(nullptr, IntSize(800, 600), 100 * 1024);
+ constexpr float kScaleFactor2 = 2.0f;
+ image_2->SetIconAndTextScaleFactor(kScaleFactor2);
+
+ DrawImageExpectingIconAndTextLTR(
+ *image_2, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), kScaleFactor2);
+
+ DrawImageExpectingIconAndTextLTR(
+ *image_1, FloatRect(1000.0f, 2000.0f, 1600.0f, 1200.0f), kScaleFactor1);
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/platform_paint_worklet_input.h b/chromium/third_party/blink/renderer/platform/graphics/platform_paint_worklet_input.h
new file mode 100644
index 00000000000..7eb83bad38f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/graphics/platform_paint_worklet_input.h
@@ -0,0 +1,36 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PLATFORM_PAINT_WORKLET_INPUT_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PLATFORM_PAINT_WORKLET_INPUT_H_
+
+#include "cc/trees/layer_tree_painter.h"
+
+namespace blink {
+
+class PLATFORM_EXPORT PlatformPaintWorkletInput : public cc::PaintWorkletInput {
+ public:
+ PlatformPaintWorkletInput(const std::string& name,
+ const FloatSize& container_size,
+ float effective_zoom)
+ : name_(name),
+ container_size_(container_size),
+ effective_zoom_(effective_zoom) {}
+
+ ~PlatformPaintWorkletInput() override = default;
+
+ const std::string& Name() const { return name_; }
+ const FloatSize& ContainerSize() const { return container_size_; }
+ float EffectiveZoom() const { return effective_zoom_; }
+
+ private:
+ std::string name_;
+ FloatSize container_size_;
+ float effective_zoom_;
+ // TODO(crbug.com/895579): add a cross thread style map.
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHIC_PLATFORM_PAINT_WORKLET_INPUT_H_
diff --git a/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc b/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc
index c42c311f08c..47a08b29157 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc
@@ -10,6 +10,7 @@
#include "cc/layers/layer.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/layers/surface_layer.h"
+#include "components/viz/common/features.h"
#include "components/viz/common/surfaces/surface_id.h"
#include "components/viz/common/surfaces/surface_info.h"
#include "media/base/media_switches.h"
@@ -31,6 +32,9 @@ SurfaceLayerBridge::SurfaceLayerBridge(
update_submission_state_callback_(
std::move(update_submission_state_callback)),
binding_(this),
+ surface_embedder_binding_(this),
+ enable_surface_synchronization_(
+ features::IsSurfaceSynchronizationEnabled()),
frame_sink_id_(Platform::Current()->GenerateFrameSinkId()),
parent_frame_sink_id_(layer_tree_view ? layer_tree_view->GetFrameSinkId()
: viz::FrameSinkId()) {
@@ -57,10 +61,27 @@ void SurfaceLayerBridge::CreateSolidColorLayer() {
observer_->RegisterContentsLayer(solid_color_layer_.get());
}
+void SurfaceLayerBridge::SetLocalSurfaceId(
+ const viz::LocalSurfaceId& local_surface_id) {
+ if (!enable_surface_synchronization_) {
+ NOTREACHED();
+ return;
+ }
+ EmbedSurface(viz::SurfaceId(frame_sink_id_, local_surface_id));
+}
+
void SurfaceLayerBridge::OnFirstSurfaceActivation(
const viz::SurfaceInfo& surface_info) {
+ if (enable_surface_synchronization_) {
+ NOTREACHED();
+ return;
+ }
DCHECK(surface_info.is_valid());
+ DCHECK_EQ(frame_sink_id_, surface_info.id().frame_sink_id());
+ EmbedSurface(surface_info.id());
+}
+void SurfaceLayerBridge::EmbedSurface(const viz::SurfaceId& surface_id) {
surface_activated_ = true;
if (solid_color_layer_) {
if (observer_)
@@ -76,20 +97,24 @@ void SurfaceLayerBridge::OnFirstSurfaceActivation(
CreateSurfaceLayer();
}
- current_surface_id_ = surface_info.id();
+ current_surface_id_ = surface_id;
- surface_layer_->SetPrimarySurfaceId(
- surface_info.id(), cc::DeadlinePolicy::UseSpecifiedDeadline(0u));
- surface_layer_->SetFallbackSurfaceId(surface_info.id());
+ surface_layer_->SetSurfaceId(surface_id,
+ cc::DeadlinePolicy::UseSpecifiedDeadline(0u));
if (observer_) {
observer_->OnWebLayerUpdated();
- observer_->OnSurfaceIdUpdated(surface_info.id());
+ observer_->OnSurfaceIdUpdated(surface_id);
}
surface_layer_->SetContentsOpaque(opaque_);
}
+void SurfaceLayerBridge::BindSurfaceEmbedder(
+ mojom::blink::SurfaceEmbedderRequest request) {
+ surface_embedder_binding_.Bind(std::move(request));
+}
+
cc::Layer* SurfaceLayerBridge::GetCcLayer() const {
if (surface_layer_)
return surface_layer_.get();
@@ -110,9 +135,9 @@ void SurfaceLayerBridge::ClearSurfaceId() {
// We reset the Ids if we lose the context_provider (case: GPU process ended)
// If we destroyed the surface_layer before that point, we need not update
// the ids.
- surface_layer_->SetPrimarySurfaceId(viz::SurfaceId(),
- cc::DeadlinePolicy::UseDefaultDeadline());
- surface_layer_->SetFallbackSurfaceId(viz::SurfaceId());
+ surface_layer_->SetSurfaceId(viz::SurfaceId(),
+ cc::DeadlinePolicy::UseDefaultDeadline());
+ surface_layer_->SetOldestAcceptableFallback(viz::SurfaceId());
}
void SurfaceLayerBridge::SetContentsOpaque(bool opaque) {
@@ -129,12 +154,14 @@ void SurfaceLayerBridge::CreateSurfaceLayer() {
// This surface_id is essentially just a placeholder for the real one we will
// get in OnFirstSurfaceActivation. We need it so that we properly get a
// WillDraw, which then pushes the first compositor frame.
+ parent_local_surface_id_allocator_.GenerateId();
current_surface_id_ = viz::SurfaceId(
frame_sink_id_,
- parent_local_surface_id_allocator_.GetCurrentLocalSurfaceId());
+ parent_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id());
- surface_layer_->SetPrimarySurfaceId(current_surface_id_,
- cc::DeadlinePolicy::UseDefaultDeadline());
+ surface_layer_->SetSurfaceId(current_surface_id_,
+ cc::DeadlinePolicy::UseDefaultDeadline());
surface_layer_->SetStretchContentToFillBounds(true);
surface_layer_->SetIsDrawable(true);
@@ -148,4 +175,9 @@ void SurfaceLayerBridge::CreateSurfaceLayer() {
surface_layer_->SetContentsOpaque(false);
}
+base::TimeTicks SurfaceLayerBridge::GetLocalSurfaceIdAllocationTime() const {
+ return parent_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .allocation_time();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h b/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h
index 120b32a6a04..6874555fd52 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h
@@ -8,6 +8,7 @@
#include <memory>
#include "base/memory/scoped_refptr.h"
+#include "base/time/time.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "components/viz/common/surfaces/surface_id.h"
#include "mojo/public/cpp/bindings/binding.h"
@@ -32,6 +33,7 @@ class WebLayerTreeView;
// between the Render and Browser processes.
class PLATFORM_EXPORT SurfaceLayerBridge
: public blink::mojom::blink::EmbeddedFrameSinkClient,
+ public blink::mojom::blink::SurfaceEmbedder,
public WebSurfaceLayerBridge {
public:
SurfaceLayerBridge(
@@ -44,6 +46,13 @@ class PLATFORM_EXPORT SurfaceLayerBridge
// Implementation of blink::mojom::blink::EmbeddedFrameSinkClient
void OnFirstSurfaceActivation(const viz::SurfaceInfo&) override;
+ void BindSurfaceEmbedder(
+ mojom::blink::SurfaceEmbedderRequest request) override;
+
+ void EmbedSurface(const viz::SurfaceId& surface_id);
+
+ // Implementation of blink::mojom::blink::SurfaceEmbedder
+ void SetLocalSurfaceId(const viz::LocalSurfaceId& local_surface_id) override;
// Implementation of WebSurfaceLayerBridge.
cc::Layer* GetCcLayer() const override;
@@ -56,6 +65,8 @@ class PLATFORM_EXPORT SurfaceLayerBridge
return current_surface_id_;
}
+ base::TimeTicks GetLocalSurfaceIdAllocationTime() const override;
+
private:
scoped_refptr<cc::SurfaceLayer> surface_layer_;
scoped_refptr<cc::SolidColorLayer> solid_color_layer_;
@@ -65,7 +76,9 @@ class PLATFORM_EXPORT SurfaceLayerBridge
cc::UpdateSubmissionStateCB update_submission_state_callback_;
viz::ParentLocalSurfaceIdAllocator parent_local_surface_id_allocator_;
mojo::Binding<blink::mojom::blink::EmbeddedFrameSinkClient> binding_;
+ mojo::Binding<blink::mojom::blink::SurfaceEmbedder> surface_embedder_binding_;
+ const bool enable_surface_synchronization_;
const viz::FrameSinkId frame_sink_id_;
viz::SurfaceId current_surface_id_;
const viz::FrameSinkId parent_frame_sink_id_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.cc b/chromium/third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.cc
index 280c9f25f91..bb8b1e7e890 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/unaccelerated_static_bitmap_image.cc
@@ -10,8 +10,8 @@
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/web_graphics_context_3d_provider_wrapper.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/skia/include/core/SkImage.h"
namespace blink {
@@ -112,8 +112,7 @@ void UnacceleratedStaticBitmapImage::Transfer() {
DETACH_FROM_THREAD(thread_checker_);
original_skia_image_ = paint_image_.GetSkImage();
- Thread* thread = Platform::Current()->CurrentThread();
- original_skia_image_task_runner_ = thread->GetTaskRunner();
+ original_skia_image_task_runner_ = Thread::Current()->GetTaskRunner();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.cc b/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.cc
index 382cbf027ff..96036bba6c2 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.cc
@@ -72,57 +72,51 @@ void VideoFrameResourceProvider::AppendQuads(
DCHECK(resource_updater_);
DCHECK(resource_provider_);
+ // When obtaining frame resources, we end up having to wait. See
+ // https://crbug/878070.
+ // Unfortunately, we have no idea if blocking is allowed on the current thread
+ // or not. If we're on the cc impl thread, the answer is yes, and further
+ // the thread is marked as not allowing blocking primitives. On the various
+ // media threads, however, blocking is not allowed but the blocking scopes
+ // are. So, we use ScopedAllow only if we're told that we should do so.
+ if (use_sync_primitives_) {
+ base::ScopedAllowBaseSyncPrimitives allow_base_sync_primitives;
+ resource_updater_->ObtainFrameResources(frame);
+ } else {
+ resource_updater_->ObtainFrameResources(frame);
+ }
+
gfx::Transform transform = gfx::Transform();
- gfx::Size rotated_size = frame->coded_size();
+ // The quad's rect is in pre-transform space so that applying the transform on
+ // it will produce the bounds in target space.
+ gfx::Rect quad_rect = gfx::Rect(frame->natural_size());
switch (rotation) {
case media::VIDEO_ROTATION_90:
- rotated_size = gfx::Size(rotated_size.height(), rotated_size.width());
transform.Rotate(90.0);
- transform.Translate(0.0, -rotated_size.height());
+ transform.Translate(0.0, -quad_rect.height());
break;
case media::VIDEO_ROTATION_180:
transform.Rotate(180.0);
- transform.Translate(-rotated_size.width(), -rotated_size.height());
+ transform.Translate(-quad_rect.width(), -quad_rect.height());
break;
case media::VIDEO_ROTATION_270:
- rotated_size = gfx::Size(rotated_size.height(), rotated_size.width());
transform.Rotate(270.0);
- transform.Translate(-rotated_size.width(), 0);
+ transform.Translate(-quad_rect.width(), 0);
break;
case media::VIDEO_ROTATION_0:
break;
}
- // When obtaining frame resources, we end up having to wait. See
- // https://crbug/878070.
- // Unfortunately, we have no idea if blocking is allowed on the current thread
- // or not. If we're on the cc impl thread, the answer is yes, and further
- // the thread is marked as not allowing blocking primitives. On the various
- // media threads, however, blocking is not allowed but the blocking scopes
- // are. So, we use ScopedAllow only if we're told that we should do so.
- if (use_sync_primitives_) {
- base::ScopedAllowBaseSyncPrimitives allow_base_sync_primitives;
- resource_updater_->ObtainFrameResources(frame);
- } else {
- resource_updater_->ObtainFrameResources(frame);
- }
-
- // TODO(lethalantidote) : update with true value;
- gfx::Rect visible_layer_rect = gfx::Rect(rotated_size);
- gfx::Rect clip_rect = gfx::Rect(frame->coded_size());
+ gfx::Rect visible_quad_rect = quad_rect;
+ gfx::Rect clip_rect;
bool is_clipped = false;
float draw_opacity = 1.0f;
int sorting_context_id = 0;
- // Internal to this compositor frame, this video quad is never occluded,
- // thus the full quad is visible.
- gfx::Rect visible_quad_rect = gfx::Rect(rotated_size);
-
- resource_updater_->AppendQuads(render_pass, std::move(frame), transform,
- rotated_size, visible_layer_rect, clip_rect,
- is_clipped, is_opaque, draw_opacity,
- sorting_context_id, visible_quad_rect);
+ resource_updater_->AppendQuads(
+ render_pass, std::move(frame), transform, quad_rect, visible_quad_rect,
+ clip_rect, is_clipped, is_opaque, draw_opacity, sorting_context_id);
}
void VideoFrameResourceProvider::ReleaseFrameResources() {
diff --git a/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h b/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h
index a5481e28030..709958e8f3c 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h
@@ -25,9 +25,7 @@ namespace blink {
// VideoFrameResourceProvider obtains required GPU resources for the video
// frame.
-// VideoFrameResourceProvider methods are currently called on the media thread.
-// TODO(lethalantidote): Move the usage of this class off media thread
-// https://crbug.com/753605
+// This class is called from the thread to which |context_provider_| is bound.
class PLATFORM_EXPORT VideoFrameResourceProvider {
public:
// |use_sync_primitives| controls whether we ScopedAllowBaseSyncPrimitives
diff --git a/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc b/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc
index 985fcb81dc5..c20b1272045 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc
@@ -10,6 +10,7 @@
#include "base/trace_event/trace_event.h"
#include "cc/paint/filter_operations.h"
#include "cc/scheduler/video_frame_controller.h"
+#include "components/viz/common/features.h"
#include "components/viz/common/resources/resource_id.h"
#include "components/viz/common/resources/returned_resource.h"
#include "media/base/video_frame.h"
@@ -36,7 +37,9 @@ VideoFrameSubmitter::VideoFrameSubmitter(
: binding_(this),
context_provider_callback_(context_provider_callback),
resource_provider_(std::move(resource_provider)),
- is_rendering_(false),
+ rotation_(media::VIDEO_ROTATION_0),
+ enable_surface_synchronization_(
+ features::IsSurfaceSynchronizationEnabled()),
weak_ptr_factory_(this) {
DETACH_FROM_THREAD(media_thread_checker_);
}
@@ -60,13 +63,15 @@ void VideoFrameSubmitter::SetIsOpaque(bool is_opaque) {
void VideoFrameSubmitter::EnableSubmission(
viz::SurfaceId surface_id,
+ base::TimeTicks local_surface_id_allocation_time,
WebFrameSinkDestroyedCallback frame_sink_destroyed_callback) {
// TODO(lethalantidote): Set these fields earlier in the constructor. Will
// need to construct VideoFrameSubmitter later in order to do this.
frame_sink_id_ = surface_id.frame_sink_id();
frame_sink_destroyed_callback_ = frame_sink_destroyed_callback;
child_local_surface_id_allocator_.UpdateFromParent(
- surface_id.local_surface_id());
+ viz::LocalSurfaceIdAllocation(surface_id.local_surface_id(),
+ local_surface_id_allocation_time));
if (resource_provider_->IsInitialized())
StartSubmitting();
}
@@ -95,13 +100,13 @@ void VideoFrameSubmitter::StopUsingProvider() {
DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_);
if (is_rendering_)
StopRendering();
- provider_ = nullptr;
+ video_frame_provider_ = nullptr;
}
void VideoFrameSubmitter::StopRendering() {
DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_);
DCHECK(is_rendering_);
- DCHECK(provider_);
+ DCHECK(video_frame_provider_);
is_rendering_ = false;
UpdateSubmissionStateInternal();
@@ -110,19 +115,23 @@ void VideoFrameSubmitter::StopRendering() {
void VideoFrameSubmitter::SubmitSingleFrame() {
// If we haven't gotten a valid result yet from |context_provider_callback_|
// |resource_provider_| will remain uninitalized.
- if (!resource_provider_->IsInitialized())
+ // |video_frame_provider_| may be null if StopUsingProvider has been called,
+ // which could happen if the |video_frame_provider_| is destructing while we
+ // are waiting for the ContextProvider.
+ if (!resource_provider_->IsInitialized() || !video_frame_provider_)
return;
viz::BeginFrameAck current_begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
- scoped_refptr<media::VideoFrame> video_frame = provider_->GetCurrentFrame();
+ scoped_refptr<media::VideoFrame> video_frame =
+ video_frame_provider_->GetCurrentFrame();
if (video_frame) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(base::IgnoreResult(&VideoFrameSubmitter::SubmitFrame),
weak_ptr_factory_.GetWeakPtr(), current_begin_frame_ack,
video_frame));
- provider_->PutCurrentFrame();
+ video_frame_provider_->PutCurrentFrame();
}
}
@@ -139,7 +148,7 @@ bool VideoFrameSubmitter::IsDrivingFrameUpdates() const {
void VideoFrameSubmitter::DidReceiveFrame() {
DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_);
- DCHECK(provider_);
+ DCHECK(video_frame_provider_);
// DidReceiveFrame is called before renderering has started, as a part of
// PaintSingleFrame.
@@ -160,8 +169,8 @@ void VideoFrameSubmitter::StartRendering() {
void VideoFrameSubmitter::Initialize(cc::VideoFrameProvider* provider) {
DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_);
if (provider) {
- DCHECK(!provider_);
- provider_ = provider;
+ DCHECK(!video_frame_provider_);
+ video_frame_provider_ = provider;
context_provider_callback_.Run(
nullptr, base::BindOnce(&VideoFrameSubmitter::OnReceivedContextProvider,
weak_ptr_factory_.GetWeakPtr()));
@@ -219,7 +228,8 @@ void VideoFrameSubmitter::StartSubmitting() {
binding_.Bind(mojo::MakeRequest(&client));
provider->CreateCompositorFrameSink(
frame_sink_id_, std::move(client),
- mojo::MakeRequest(&compositor_frame_sink_));
+ mojo::MakeRequest(&compositor_frame_sink_),
+ mojo::MakeRequest(&surface_embedder_));
compositor_frame_sink_.set_connection_error_handler(base::BindOnce(
&VideoFrameSubmitter::OnContextLost, base::Unretained(this)));
@@ -236,16 +246,29 @@ bool VideoFrameSubmitter::SubmitFrame(
if (!compositor_frame_sink_ || !ShouldSubmit())
return false;
- if (frame_size_ != gfx::Rect(video_frame->coded_size())) {
- if (!frame_size_.IsEmpty())
+ gfx::Size frame_size(video_frame->natural_size());
+ if (rotation_ == media::VIDEO_ROTATION_90 ||
+ rotation_ == media::VIDEO_ROTATION_270) {
+ frame_size = gfx::Size(frame_size.height(), frame_size.width());
+ }
+ if (frame_size_ != frame_size) {
+ if (!frame_size_.IsEmpty()) {
child_local_surface_id_allocator_.GenerateId();
- frame_size_ = gfx::Rect(video_frame->coded_size());
+ if (enable_surface_synchronization_) {
+ surface_embedder_->SetLocalSurfaceId(
+ child_local_surface_id_allocator_
+ .GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id());
+ }
+ }
+ frame_size_ = frame_size;
}
viz::CompositorFrame compositor_frame;
std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create();
- render_pass->SetNew(1, frame_size_, frame_size_, gfx::Transform());
+ render_pass->SetNew(1, gfx::Rect(frame_size_), gfx::Rect(frame_size_),
+ gfx::Transform());
render_pass->filters = cc::FilterOperations();
resource_provider_->AppendQuads(render_pass.get(), video_frame, rotation_,
is_opaque_);
@@ -267,10 +290,14 @@ bool VideoFrameSubmitter::SubmitFrame(
resource_provider_->PrepareSendToParent(resources,
&compositor_frame.resource_list);
compositor_frame.render_pass_list.push_back(std::move(render_pass));
+ compositor_frame.metadata.local_surface_id_allocation_time =
+ child_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .allocation_time();
// TODO(lethalantidote): Address third/fourth arg in SubmitCompositorFrame.
compositor_frame_sink_->SubmitCompositorFrame(
- child_local_surface_id_allocator_.GetCurrentLocalSurfaceId(),
+ child_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id(),
std::move(compositor_frame), nullptr, 0);
resource_provider_->ReleaseFrameResources();
@@ -290,18 +317,25 @@ void VideoFrameSubmitter::SubmitEmptyFrame() {
viz::BeginFrameAck::CreateManualAckWithDamage();
compositor_frame.metadata.device_scale_factor = 1;
compositor_frame.metadata.may_contain_video = true;
+ compositor_frame.metadata.local_surface_id_allocation_time =
+ child_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .allocation_time();
std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create();
- render_pass->SetNew(1, frame_size_, frame_size_, gfx::Transform());
+ render_pass->SetNew(1, gfx::Rect(frame_size_), gfx::Rect(frame_size_),
+ gfx::Transform());
compositor_frame.render_pass_list.push_back(std::move(render_pass));
compositor_frame_sink_->SubmitCompositorFrame(
- child_local_surface_id_allocator_.GetCurrentLocalSurfaceId(),
+ child_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id(),
std::move(compositor_frame), nullptr, 0);
waiting_for_compositor_ack_ = true;
}
-void VideoFrameSubmitter::OnBeginFrame(const viz::BeginFrameArgs& args) {
+void VideoFrameSubmitter::OnBeginFrame(
+ const viz::BeginFrameArgs& args,
+ WTF::HashMap<uint32_t, ::gfx::mojom::blink::PresentationFeedbackPtr>) {
TRACE_EVENT0("media", "VideoFrameSubmitter::OnBeginFrame");
DCHECK_CALLED_ON_VALID_THREAD(media_thread_checker_);
viz::BeginFrameAck current_begin_frame_ack(args, false);
@@ -314,14 +348,15 @@ void VideoFrameSubmitter::OnBeginFrame(const viz::BeginFrameArgs& args) {
// frame yet. That probably signals a dropped frame, and this will let the
// provider know that it happened, since we won't PutCurrentFrame this one.
// Note that we should DidNotProduceFrame with or without the ack.
- if (!provider_ ||
- !provider_->UpdateCurrentFrame(args.frame_time + args.interval,
- args.frame_time + 2 * args.interval)) {
+ if (!video_frame_provider_ || !video_frame_provider_->UpdateCurrentFrame(
+ args.frame_time + args.interval,
+ args.frame_time + 2 * args.interval)) {
compositor_frame_sink_->DidNotProduceFrame(current_begin_frame_ack);
return;
}
- scoped_refptr<media::VideoFrame> video_frame = provider_->GetCurrentFrame();
+ scoped_refptr<media::VideoFrame> video_frame =
+ video_frame_provider_->GetCurrentFrame();
// We do have a new frame that we could display. See if we're supposed to
// actually submit a frame or not, and try to submit one.
@@ -337,7 +372,7 @@ void VideoFrameSubmitter::OnBeginFrame(const viz::BeginFrameArgs& args) {
// lines up with the correct frame. Otherwise, any intervening calls to
// OnBeginFrame => UpdateCurrentFrame will cause the put to signal that the
// later frame was displayed.
- provider_->PutCurrentFrame();
+ video_frame_provider_->PutCurrentFrame();
}
void VideoFrameSubmitter::OnContextLost() {
@@ -387,10 +422,6 @@ void VideoFrameSubmitter::ReclaimResources(
resource_provider_->ReceiveReturnsFromParent(std_resources);
}
-void VideoFrameSubmitter::DidPresentCompositorFrame(
- uint32_t presentation_token,
- ::gfx::mojom::blink::PresentationFeedbackPtr feedback) {}
-
void VideoFrameSubmitter::DidAllocateSharedBitmap(
mojo::ScopedSharedBufferHandle buffer,
const viz::SharedBitmapId& id) {
@@ -406,10 +437,12 @@ void VideoFrameSubmitter::DidDeleteSharedBitmap(const viz::SharedBitmapId& id) {
}
void VideoFrameSubmitter::SetSurfaceIdForTesting(
- const viz::SurfaceId& surface_id) {
+ const viz::SurfaceId& surface_id,
+ base::TimeTicks allocation_time) {
frame_sink_id_ = surface_id.frame_sink_id();
child_local_surface_id_allocator_.UpdateFromParent(
- surface_id.local_surface_id());
+ viz::LocalSurfaceIdAllocation(surface_id.local_surface_id(),
+ allocation_time));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.h b/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.h
index d1384945f19..0a0f90deece 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.h
+++ b/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter.h
@@ -10,6 +10,7 @@
#include "base/memory/weak_ptr.h"
#include "base/threading/thread_checker.h"
+#include "base/time/time.h"
#include "components/viz/client/shared_bitmap_reporter.h"
#include "components/viz/common/gpu/context_provider.h"
#include "components/viz/common/resources/shared_bitmap.h"
@@ -17,6 +18,7 @@
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/system/buffer.h"
#include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom-blink.h"
+#include "third_party/blink/public/platform/modules/frame_sinks/embedded_frame_sink.mojom-blink.h"
#include "third_party/blink/public/platform/web_video_frame_submitter.h"
#include "third_party/blink/renderer/platform/graphics/video_frame_resource_provider.h"
#include "third_party/blink/renderer/platform/platform_export.h"
@@ -42,7 +44,7 @@ class PLATFORM_EXPORT VideoFrameSubmitter
~VideoFrameSubmitter() override;
bool Rendering() { return is_rendering_; }
- cc::VideoFrameProvider* Provider() { return provider_; }
+ cc::VideoFrameProvider* Provider() { return video_frame_provider_; }
mojo::Binding<viz::mojom::blink::CompositorFrameSinkClient>* Binding() {
return &binding_;
}
@@ -60,7 +62,9 @@ class PLATFORM_EXPORT VideoFrameSubmitter
void Initialize(cc::VideoFrameProvider*) override;
void SetRotation(media::VideoRotation) override;
void SetIsOpaque(bool) override;
- void EnableSubmission(viz::SurfaceId, WebFrameSinkDestroyedCallback) override;
+ void EnableSubmission(viz::SurfaceId,
+ base::TimeTicks local_surface_id_allocation_time,
+ WebFrameSinkDestroyedCallback) override;
void UpdateSubmissionState(bool is_visible) override;
void SetForceSubmit(bool) override;
@@ -70,10 +74,10 @@ class PLATFORM_EXPORT VideoFrameSubmitter
// cc::mojom::CompositorFrameSinkClient implementation.
void DidReceiveCompositorFrameAck(
const WTF::Vector<viz::ReturnedResource>& resources) override;
- void DidPresentCompositorFrame(
- uint32_t presentation_token,
- ::gfx::mojom::blink::PresentationFeedbackPtr feedback) final;
- void OnBeginFrame(const viz::BeginFrameArgs&) override;
+ void OnBeginFrame(
+ const viz::BeginFrameArgs&,
+ WTF::HashMap<uint32_t, ::gfx::mojom::blink::PresentationFeedbackPtr>)
+ override;
void OnBeginFramePausedChanged(bool paused) override {}
void ReclaimResources(
const WTF::Vector<viz::ReturnedResource>& resources) override;
@@ -87,8 +91,11 @@ class PLATFORM_EXPORT VideoFrameSubmitter
viz::mojom::blink::CompositorFrameSinkPtr* sink) {
compositor_frame_sink_ = std::move(*sink);
}
-
- void SetSurfaceIdForTesting(const viz::SurfaceId&);
+ void SetSurfaceEmbedderPtrForTesting(
+ mojom::blink::SurfaceEmbedderPtr embedder) {
+ surface_embedder_ = std::move(embedder);
+ }
+ void SetSurfaceIdForTesting(const viz::SurfaceId&, base::TimeTicks);
private:
FRIEND_TEST_ALL_PREFIXES(VideoFrameSubmitterTest, ContextLostDuringSubmit);
@@ -98,6 +105,8 @@ class PLATFORM_EXPORT VideoFrameSubmitter
SetForceSubmitForcesSubmission);
FRIEND_TEST_ALL_PREFIXES(VideoFrameSubmitterTest,
FrameSizeChangeUpdatesLocalSurfaceId);
+ FRIEND_TEST_ALL_PREFIXES(VideoFrameSubmitterTest,
+ StopUsingProviderDuringContextLost);
void StartSubmitting();
void UpdateSubmissionStateInternal();
@@ -115,20 +124,23 @@ class PLATFORM_EXPORT VideoFrameSubmitter
// state.
bool ShouldSubmit() const;
- cc::VideoFrameProvider* provider_ = nullptr;
+ cc::VideoFrameProvider* video_frame_provider_ = nullptr;
scoped_refptr<viz::ContextProvider> context_provider_;
viz::mojom::blink::CompositorFrameSinkPtr compositor_frame_sink_;
+ mojom::blink::SurfaceEmbedderPtr surface_embedder_;
mojo::Binding<viz::mojom::blink::CompositorFrameSinkClient> binding_;
WebContextProviderCallback context_provider_callback_;
std::unique_ptr<VideoFrameResourceProvider> resource_provider_;
WebFrameSinkDestroyedCallback frame_sink_destroyed_callback_;
bool waiting_for_compositor_ack_ = false;
- bool is_rendering_;
+ bool is_rendering_ = false;
// If we are not on screen, we should not submit.
bool should_submit_internal_ = false;
// Whether frames should always be submitted, even if we're not visible.
bool force_submit_ = false;
+ // Needs to be initialized in implementation because media isn't a public_dep
+ // of blink/platform.
media::VideoRotation rotation_;
bool is_opaque_ = true;
@@ -137,12 +149,14 @@ class PLATFORM_EXPORT VideoFrameSubmitter
// Size of the video frame being submitted. It is set the first time a frame
// is submitted. Every time there is a change in the video frame size, the
// child component of the LocalSurfaceId will be updated.
- gfx::Rect frame_size_;
+ gfx::Size frame_size_;
// Used to updated the LocalSurfaceId when detecting a change in video frame
// size.
viz::ChildLocalSurfaceIdAllocator child_local_surface_id_allocator_;
+ const bool enable_surface_synchronization_;
+
THREAD_CHECKER(media_thread_checker_);
base::WeakPtrFactory<VideoFrameSubmitter> weak_ptr_factory_;
diff --git a/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc b/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc
index b21f2e4cd25..6ec09248d5b 100644
--- a/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc
+++ b/chromium/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc
@@ -8,6 +8,7 @@
#include "base/memory/ptr_util.h"
#include "base/test/scoped_task_environment.h"
#include "base/test/simple_test_tick_clock.h"
+#include "base/time/time.h"
#include "cc/layers/video_frame_provider.h"
#include "cc/test/layer_test_common.h"
#include "cc/trees/layer_tree_settings.h"
@@ -53,6 +54,10 @@ class MockCompositorFrameSink : public viz::mojom::blink::CompositorFrameSink {
: binding_(this, std::move(*request)) {}
~MockCompositorFrameSink() override = default;
+ const viz::CompositorFrame& last_submitted_compositor_frame() const {
+ return last_submitted_compositor_frame_;
+ }
+
MOCK_METHOD1(SetNeedsBeginFrame, void(bool));
MOCK_METHOD0(SetWantsAnimateOnlyBeginFrames, void());
@@ -63,7 +68,8 @@ class MockCompositorFrameSink : public viz::mojom::blink::CompositorFrameSink {
viz::CompositorFrame frame,
viz::mojom::blink::HitTestRegionListPtr hit_test_region_list,
uint64_t submit_time) override {
- DoSubmitCompositorFrame(id, &frame);
+ last_submitted_compositor_frame_ = std::move(frame);
+ DoSubmitCompositorFrame(id, &last_submitted_compositor_frame_);
}
void SubmitCompositorFrameSync(
const viz::LocalSurfaceId& id,
@@ -71,7 +77,8 @@ class MockCompositorFrameSink : public viz::mojom::blink::CompositorFrameSink {
viz::mojom::blink::HitTestRegionListPtr hit_test_region_list,
uint64_t submit_time,
const SubmitCompositorFrameSyncCallback callback) override {
- DoSubmitCompositorFrame(id, &frame);
+ last_submitted_compositor_frame_ = std::move(frame);
+ DoSubmitCompositorFrame(id, &last_submitted_compositor_frame_);
}
MOCK_METHOD1(DidNotProduceFrame, void(const viz::BeginFrameAck&));
@@ -92,6 +99,8 @@ class MockCompositorFrameSink : public viz::mojom::blink::CompositorFrameSink {
private:
mojo::Binding<viz::mojom::blink::CompositorFrameSink> binding_;
+ viz::CompositorFrame last_submitted_compositor_frame_;
+
DISALLOW_COPY_AND_ASSIGN(MockCompositorFrameSink);
};
@@ -133,7 +142,7 @@ class VideoFrameSubmitterTest : public testing::Test {
VideoFrameSubmitterTest()
: now_src_(new base::SimpleTestTickClock()),
begin_frame_source_(new viz::FakeExternalBeginFrameSource(0.f, false)),
- provider_(new StrictMock<MockVideoFrameProvider>()),
+ video_frame_provider_(new StrictMock<MockVideoFrameProvider>()),
context_provider_(viz::TestContextProvider::Create()) {
context_provider_->BindToCurrentThread();
}
@@ -153,7 +162,7 @@ class VideoFrameSubmitterTest : public testing::Test {
bool, scoped_refptr<viz::ContextProvider>)>) {}),
base::WrapUnique<MockVideoFrameResourceProvider>(resource_provider_));
- submitter_->Initialize(provider_.get());
+ submitter_->Initialize(video_frame_provider_.get());
viz::mojom::blink::CompositorFrameSinkPtr submitter_sink;
viz::mojom::blink::CompositorFrameSinkRequest request =
mojo::MakeRequest(&submitter_sink);
@@ -163,10 +172,15 @@ class VideoFrameSubmitterTest : public testing::Test {
// testing easier without having to worry about the first sent frame.
submitter_->UpdateSubmissionState(true);
submitter_->SetCompositorFrameSinkPtrForTesting(&submitter_sink);
- submitter_->SetSurfaceIdForTesting(viz::SurfaceId(
- viz::FrameSinkId(1, 1),
- viz::LocalSurfaceId(11,
- base::UnguessableToken::Deserialize(0x111111, 0))));
+ mojom::blink::SurfaceEmbedderPtr embedder;
+ mojo::MakeRequest(&embedder);
+ submitter_->SetSurfaceEmbedderPtrForTesting(std::move(embedder));
+ submitter_->SetSurfaceIdForTesting(
+ viz::SurfaceId(
+ viz::FrameSinkId(1, 1),
+ viz::LocalSurfaceId(
+ 11, base::UnguessableToken::Deserialize(0x111111, 0))),
+ base::TimeTicks::Now());
}
protected:
@@ -174,16 +188,13 @@ class VideoFrameSubmitterTest : public testing::Test {
std::unique_ptr<base::SimpleTestTickClock> now_src_;
std::unique_ptr<viz::FakeExternalBeginFrameSource> begin_frame_source_;
std::unique_ptr<StrictMock<MockCompositorFrameSink>> sink_;
- std::unique_ptr<StrictMock<MockVideoFrameProvider>> provider_;
+ std::unique_ptr<StrictMock<MockVideoFrameProvider>> video_frame_provider_;
StrictMock<MockVideoFrameResourceProvider>* resource_provider_;
scoped_refptr<viz::TestContextProvider> context_provider_;
std::unique_ptr<VideoFrameSubmitter> submitter_;
};
TEST_F(VideoFrameSubmitterTest, StatRenderingFlipsBits) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_FALSE(submitter_->Rendering());
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
@@ -195,11 +206,8 @@ TEST_F(VideoFrameSubmitterTest, StatRenderingFlipsBits) {
}
TEST_F(VideoFrameSubmitterTest, StopUsingProviderNullsProvider) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_FALSE(submitter_->Rendering());
- EXPECT_EQ(provider_.get(), submitter_->Provider());
+ EXPECT_EQ(video_frame_provider_.get(), submitter_->Provider());
submitter_->StopUsingProvider();
@@ -208,9 +216,6 @@ TEST_F(VideoFrameSubmitterTest, StopUsingProviderNullsProvider) {
TEST_F(VideoFrameSubmitterTest,
StopUsingProviderSubmitsFrameAndStopsRendering) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
submitter_->StartRendering();
@@ -218,12 +223,12 @@ TEST_F(VideoFrameSubmitterTest,
EXPECT_TRUE(submitter_->Rendering());
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
@@ -237,9 +242,6 @@ TEST_F(VideoFrameSubmitterTest,
}
TEST_F(VideoFrameSubmitterTest, DidReceiveFrameDoesNothingIfRendering) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
submitter_->StartRendering();
@@ -252,17 +254,14 @@ TEST_F(VideoFrameSubmitterTest, DidReceiveFrameDoesNothingIfRendering) {
}
TEST_F(VideoFrameSubmitterTest, DidReceiveFrameSubmitsFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_FALSE(submitter_->Rendering());
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -272,9 +271,6 @@ TEST_F(VideoFrameSubmitterTest, DidReceiveFrameSubmitsFrame) {
}
TEST_F(VideoFrameSubmitterTest, ShouldSubmitPreventsSubmission) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
submitter_->UpdateSubmissionState(false);
scoped_task_environment_.RunUntilIdle();
@@ -286,12 +282,12 @@ TEST_F(VideoFrameSubmitterTest, ShouldSubmitPreventsSubmission) {
scoped_task_environment_.RunUntilIdle();
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -302,17 +298,17 @@ TEST_F(VideoFrameSubmitterTest, ShouldSubmitPreventsSubmission) {
EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, GetCurrentFrame()).Times(0);
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame()).Times(0);
submitter_->UpdateSubmissionState(false);
scoped_task_environment_.RunUntilIdle();
EXPECT_FALSE(submitter_->ShouldSubmit());
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
submitter_->SubmitSingleFrame();
}
@@ -320,20 +316,17 @@ TEST_F(VideoFrameSubmitterTest, ShouldSubmitPreventsSubmission) {
// Tests that when set to true SetForceSubmit forces frame submissions.
// regardless of the internal submit state.
TEST_F(VideoFrameSubmitterTest, SetForceSubmitForcesSubmission) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
submitter_->UpdateSubmissionState(false);
scoped_task_environment_.RunUntilIdle();
EXPECT_FALSE(submitter_->ShouldSubmit());
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
submitter_->SetForceSubmit(true);
EXPECT_TRUE(submitter_->ShouldSubmit());
@@ -347,12 +340,12 @@ TEST_F(VideoFrameSubmitterTest, SetForceSubmitForcesSubmission) {
scoped_task_environment_.RunUntilIdle();
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -363,8 +356,8 @@ TEST_F(VideoFrameSubmitterTest, SetForceSubmitForcesSubmission) {
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, PutCurrentFrame());
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
@@ -376,30 +369,27 @@ TEST_F(VideoFrameSubmitterTest, SetForceSubmitForcesSubmission) {
EXPECT_TRUE(submitter_->ShouldSubmit());
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
submitter_->SubmitSingleFrame();
}
TEST_F(VideoFrameSubmitterTest, RotationInformationPassedToResourceProvider) {
// Check to see if rotation is communicated pre-rendering.
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_FALSE(submitter_->Rendering());
submitter_->SetRotation(media::VideoRotation::VIDEO_ROTATION_90);
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_,
AppendQuads(_, _, media::VideoRotation::VIDEO_ROTATION_90, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
@@ -428,13 +418,14 @@ TEST_F(VideoFrameSubmitterTest, RotationInformationPassedToResourceProvider) {
submitter_->DidReceiveCompositorFrameAck(resources);
}
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).WillOnce(Return(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_,
AppendQuads(_, _, media::VideoRotation::VIDEO_ROTATION_180, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
@@ -442,7 +433,7 @@ TEST_F(VideoFrameSubmitterTest, RotationInformationPassedToResourceProvider) {
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
{
@@ -454,37 +445,35 @@ TEST_F(VideoFrameSubmitterTest, RotationInformationPassedToResourceProvider) {
// Check to see if changing rotation while rendering is handled.
submitter_->SetRotation(media::VideoRotation::VIDEO_ROTATION_270);
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).WillOnce(Return(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_,
AppendQuads(_, _, media::VideoRotation::VIDEO_ROTATION_270, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
// Check to see if is_opaque is communicated pre-rendering.
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_FALSE(submitter_->Rendering());
// We submit a frame on opacity change.
EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -498,12 +487,12 @@ TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
submitter_->DidReceiveCompositorFrameAck(resources);
}
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, false));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -520,12 +509,12 @@ TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
// Check to see if an update to is_opaque just before rendering is
// communicated.
EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -542,20 +531,21 @@ TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
submitter_->DidReceiveCompositorFrameAck(resources);
}
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).WillOnce(Return(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, true));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
{
@@ -566,12 +556,12 @@ TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
// Check to see if changing is_opaque while rendering is handled.
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)).Times(1);
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -585,18 +575,19 @@ TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
submitter_->DidReceiveCompositorFrameAck(resources);
}
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).WillOnce(Return(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, false));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
// Updating |is_opaque_| with the same value should not cause a frame submit.
@@ -604,93 +595,78 @@ TEST_F(VideoFrameSubmitterTest, IsOpaquePassedToResourceProvider) {
}
TEST_F(VideoFrameSubmitterTest, OnBeginFrameSubmitsFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
submitter_->StartRendering();
scoped_task_environment_.RunUntilIdle();
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).WillOnce(Return(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
TEST_F(VideoFrameSubmitterTest, MissedFrameArgDoesNotProduceFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, DidNotProduceFrame(_));
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
args.type = viz::BeginFrameArgs::MISSED;
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
TEST_F(VideoFrameSubmitterTest, MissingProviderDoesNotProduceFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
submitter_->StopUsingProvider();
EXPECT_CALL(*sink_, DidNotProduceFrame(_));
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
TEST_F(VideoFrameSubmitterTest, NoUpdateOnFrameDoesNotProduceFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
submitter_->StartRendering();
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).WillOnce(Return(false));
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(false));
EXPECT_CALL(*sink_, DidNotProduceFrame(_));
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
TEST_F(VideoFrameSubmitterTest, NotRenderingDoesNotProduceFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
// We don't care if UpdateCurrentFrame is called or not; it doesn't matter
// if we're not rendering.
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).Times(AnyNumber());
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .Times(AnyNumber());
EXPECT_CALL(*sink_, DidNotProduceFrame(_));
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
TEST_F(VideoFrameSubmitterTest, ReturnsResourceOnCompositorAck) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
WTF::Vector<viz::ReturnedResource> resources;
EXPECT_CALL(*resource_provider_, ReceiveReturnsFromParent(_));
submitter_->DidReceiveCompositorFrameAck(resources);
@@ -700,33 +676,30 @@ TEST_F(VideoFrameSubmitterTest, ReturnsResourceOnCompositorAck) {
// Tests that after submitting a frame, no frame will be submitted until an ACK
// was received. This is tested by simulating another BeginFrame message.
TEST_F(VideoFrameSubmitterTest, WaitingForAckPreventsNewFrame) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
submitter_->StartRendering();
scoped_task_environment_.RunUntilIdle();
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _))
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
.Times(1)
.WillOnce(Return(true));
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.Times(1)
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
BEGINFRAME_FROM_HERE, now_src_.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
// DidNotProduceFrame should be called because no frame will be submitted
@@ -735,31 +708,28 @@ TEST_F(VideoFrameSubmitterTest, WaitingForAckPreventsNewFrame) {
// UpdateCurrentFrame should still be called, however, so that the compositor
// knows that we missed a frame.
- EXPECT_CALL(*provider_, UpdateCurrentFrame(_, _)).Times(1);
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _)).Times(1);
std::unique_ptr<base::SimpleTestTickClock> new_time =
std::make_unique<base::SimpleTestTickClock>();
args = begin_frame_source_->CreateBeginFrameArgs(BEGINFRAME_FROM_HERE,
new_time.get());
- submitter_->OnBeginFrame(args);
+ submitter_->OnBeginFrame(args, {});
scoped_task_environment_.RunUntilIdle();
}
// Test that no crash happens if the context is lost during a frame submission.
TEST_F(VideoFrameSubmitterTest, ContextLostDuringSubmit) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
submitter_->StartRendering();
scoped_task_environment_.RunUntilIdle();
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
// This will post a task that will later call SubmitFrame(). The call will
// happen after OnContextLost().
@@ -770,17 +740,45 @@ TEST_F(VideoFrameSubmitterTest, ContextLostDuringSubmit) {
scoped_task_environment_.RunUntilIdle();
}
+// This test simulates a race condition in which the |video_frame_provider_| is
+// destroyed before OnReceivedContextProvider returns.
+TEST_F(VideoFrameSubmitterTest, StopUsingProviderDuringContextLost) {
+ EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
+
+ submitter_->StartRendering();
+ scoped_task_environment_.RunUntilIdle();
+
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
+ .WillOnce(Return(media::VideoFrame::CreateFrame(
+ media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
+ gfx::Size(8, 8), base::TimeDelta())));
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
+
+ EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
+ EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
+ EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
+ EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
+ EXPECT_CALL(*sink_, SetNeedsBeginFrame(false));
+ submitter_->StopUsingProvider();
+
+ scoped_task_environment_.RunUntilIdle();
+
+ // OnReceivedContextProvider returns. We don't run the actual function
+ // because it would overwrite our fake |sink_| with a real one.
+ submitter_->SubmitSingleFrame();
+
+ scoped_task_environment_.RunUntilIdle();
+}
+
// Test the behaviour of the ChildLocalSurfaceIdAllocator instance. It checks
// that the LocalSurfaceId is propoerly set at creation and updated when the
// video frames change.
TEST_F(VideoFrameSubmitterTest, FrameSizeChangeUpdatesLocalSurfaceId) {
- MakeSubmitter();
- scoped_task_environment_.RunUntilIdle();
-
{
viz::LocalSurfaceId local_surface_id =
submitter_->child_local_surface_id_allocator_
- .GetCurrentLocalSurfaceId();
+ .GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id();
EXPECT_TRUE(local_surface_id.is_valid());
EXPECT_EQ(11u, local_surface_id.parent_sequence_number());
EXPECT_EQ(viz::kInitialChildSequenceNumber,
@@ -793,12 +791,12 @@ TEST_F(VideoFrameSubmitterTest, FrameSizeChangeUpdatesLocalSurfaceId) {
submitter_->StartRendering();
scoped_task_environment_.RunUntilIdle();
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(8, 8), gfx::Rect(gfx::Size(8, 8)),
gfx::Size(8, 8), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -809,20 +807,21 @@ TEST_F(VideoFrameSubmitterTest, FrameSizeChangeUpdatesLocalSurfaceId) {
{
viz::LocalSurfaceId local_surface_id =
submitter_->child_local_surface_id_allocator_
- .GetCurrentLocalSurfaceId();
+ .GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id();
EXPECT_TRUE(local_surface_id.is_valid());
EXPECT_EQ(11u, local_surface_id.parent_sequence_number());
EXPECT_EQ(viz::kInitialChildSequenceNumber,
local_surface_id.child_sequence_number());
- EXPECT_EQ(gfx::Rect(8, 8), submitter_->frame_size_);
+ EXPECT_EQ(gfx::Size(8, 8), submitter_->frame_size_);
}
- EXPECT_CALL(*provider_, GetCurrentFrame())
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
.WillOnce(Return(media::VideoFrame::CreateFrame(
media::PIXEL_FORMAT_YV12, gfx::Size(2, 2), gfx::Rect(gfx::Size(2, 2)),
gfx::Size(2, 2), base::TimeDelta())));
EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
- EXPECT_CALL(*provider_, PutCurrentFrame());
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
EXPECT_CALL(*resource_provider_, AppendQuads(_, _, _, _));
EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
@@ -833,12 +832,118 @@ TEST_F(VideoFrameSubmitterTest, FrameSizeChangeUpdatesLocalSurfaceId) {
{
viz::LocalSurfaceId local_surface_id =
submitter_->child_local_surface_id_allocator_
- .GetCurrentLocalSurfaceId();
+ .GetCurrentLocalSurfaceIdAllocation()
+ .local_surface_id();
EXPECT_TRUE(local_surface_id.is_valid());
EXPECT_EQ(11u, local_surface_id.parent_sequence_number());
EXPECT_EQ(viz::kInitialChildSequenceNumber + 1,
local_surface_id.child_sequence_number());
- EXPECT_EQ(gfx::Rect(2, 2), submitter_->frame_size_);
+ EXPECT_EQ(gfx::Size(2, 2), submitter_->frame_size_);
+ }
+}
+
+TEST_F(VideoFrameSubmitterTest, VideoRotationOutputRect) {
+ MakeSubmitter();
+ EXPECT_CALL(*sink_, SetNeedsBeginFrame(true));
+ submitter_->StartRendering();
+ EXPECT_TRUE(submitter_->Rendering());
+
+ gfx::Size coded_size(1280, 720);
+ gfx::Size natural_size(1280, 1024);
+ gfx::Size rotated_size(1024, 1280);
+
+ {
+ submitter_->SetRotation(media::VideoRotation::VIDEO_ROTATION_90);
+
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
+ .WillOnce(Return(media::VideoFrame::CreateFrame(
+ media::PIXEL_FORMAT_YV12, coded_size, gfx::Rect(coded_size),
+ natural_size, base::TimeDelta())));
+ EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
+ EXPECT_CALL(*resource_provider_,
+ AppendQuads(_, _, media::VideoRotation::VIDEO_ROTATION_90, _));
+ EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
+ EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
+
+ viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
+ BEGINFRAME_FROM_HERE, now_src_.get());
+ submitter_->OnBeginFrame(args, {});
+ scoped_task_environment_.RunUntilIdle();
+
+ EXPECT_EQ(sink_->last_submitted_compositor_frame().size_in_pixels(),
+ rotated_size);
+
+ submitter_->DidReceiveFrame();
+
+ WTF::Vector<viz::ReturnedResource> resources;
+ EXPECT_CALL(*resource_provider_, ReceiveReturnsFromParent(_));
+ submitter_->DidReceiveCompositorFrameAck(resources);
+ }
+
+ {
+ submitter_->SetRotation(media::VideoRotation::VIDEO_ROTATION_180);
+
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
+ .WillOnce(Return(media::VideoFrame::CreateFrame(
+ media::PIXEL_FORMAT_YV12, coded_size, gfx::Rect(coded_size),
+ natural_size, base::TimeDelta())));
+ EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
+ EXPECT_CALL(*resource_provider_,
+ AppendQuads(_, _, media::VideoRotation::VIDEO_ROTATION_180, _));
+ EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
+ EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
+
+ viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
+ BEGINFRAME_FROM_HERE, now_src_.get());
+ submitter_->OnBeginFrame(args, {});
+ scoped_task_environment_.RunUntilIdle();
+
+ // 180 deg rotation has same size.
+ EXPECT_EQ(sink_->last_submitted_compositor_frame().size_in_pixels(),
+ natural_size);
+
+ submitter_->DidReceiveFrame();
+
+ WTF::Vector<viz::ReturnedResource> resources;
+ EXPECT_CALL(*resource_provider_, ReceiveReturnsFromParent(_));
+ submitter_->DidReceiveCompositorFrameAck(resources);
+ }
+
+ {
+ submitter_->SetRotation(media::VideoRotation::VIDEO_ROTATION_270);
+
+ EXPECT_CALL(*video_frame_provider_, UpdateCurrentFrame(_, _))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*video_frame_provider_, GetCurrentFrame())
+ .WillOnce(Return(media::VideoFrame::CreateFrame(
+ media::PIXEL_FORMAT_YV12, coded_size, gfx::Rect(coded_size),
+ natural_size, base::TimeDelta())));
+ EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _));
+ EXPECT_CALL(*video_frame_provider_, PutCurrentFrame());
+ EXPECT_CALL(*resource_provider_,
+ AppendQuads(_, _, media::VideoRotation::VIDEO_ROTATION_270, _));
+ EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _));
+ EXPECT_CALL(*resource_provider_, ReleaseFrameResources());
+
+ viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs(
+ BEGINFRAME_FROM_HERE, now_src_.get());
+ submitter_->OnBeginFrame(args, {});
+ scoped_task_environment_.RunUntilIdle();
+
+ EXPECT_EQ(sink_->last_submitted_compositor_frame().size_in_pixels(),
+ rotated_size);
+
+ submitter_->DidReceiveFrame();
+
+ WTF::Vector<viz::ReturnedResource> resources;
+ EXPECT_CALL(*resource_provider_, ReceiveReturnsFromParent(_));
+ submitter_->DidReceiveCompositorFrameAck(resources);
}
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/BUILD.gn b/chromium/third_party/blink/renderer/platform/heap/BUILD.gn
index edaa9417fcd..470d7033ba4 100644
--- a/chromium/third_party/blink/renderer/platform/heap/BUILD.gn
+++ b/chromium/third_party/blink/renderer/platform/heap/BUILD.gn
@@ -4,8 +4,8 @@
import("//build/buildflag_header.gni")
import("//build/config/jumbo.gni")
-import("//third_party/blink/renderer/platform/platform.gni")
import("//testing/test.gni")
+import("//third_party/blink/renderer/platform/platform.gni")
declare_args() {
# Build Blink with incremental marking infrastructure for Oilpan.
@@ -52,8 +52,6 @@ blink_platform_sources("heap") {
"heap_page.h",
"heap_stats_collector.cc",
"heap_stats_collector.h",
- "heap_terminated_array.h",
- "heap_terminated_array_builder.h",
"heap_traits.h",
"marking_verifier.h",
"marking_visitor.cc",
diff --git a/chromium/third_party/blink/renderer/platform/heap/asm/SaveRegisters_arm64.S b/chromium/third_party/blink/renderer/platform/heap/asm/SaveRegisters_arm64.S
index a6f31555e6f..5c765f23d80 100644
--- a/chromium/third_party/blink/renderer/platform/heap/asm/SaveRegisters_arm64.S
+++ b/chromium/third_party/blink/renderer/platform/heap/asm/SaveRegisters_arm64.S
@@ -34,10 +34,22 @@
* extern "C" void PushAllRegisters(SafePointBarrier*, ThreadState*, PushAllRegistersCallback)
*/
-.type PushAllRegisters, %function
-.global PushAllRegisters
-.hidden PushAllRegisters
-PushAllRegisters:
+/* Supplementary macro for setting function attributes */
+.macro asm_function fname
+#ifdef __APPLE__
+ .globl _\fname
+_\fname:
+#else
+ .global \fname
+#ifdef __ELF__
+ .hidden \fname
+ .type \fname, %function
+#endif
+\fname:
+#endif
+.endm
+
+asm_function PushAllRegisters
/* Save return address. */
sub sp, sp, #96
stp x19, x20, [sp, #80]
diff --git a/chromium/third_party/blink/renderer/platform/heap/finalizer_traits.h b/chromium/third_party/blink/renderer/platform/heap/finalizer_traits.h
index c0b335cb874..fe4c8ccfb29 100644
--- a/chromium/third_party/blink/renderer/platform/heap/finalizer_traits.h
+++ b/chromium/third_party/blink/renderer/platform/heap/finalizer_traits.h
@@ -77,7 +77,7 @@ template <typename T, typename Allocator>
struct FinalizerTrait<WTF::ListHashSetNode<T, Allocator>> {
STATIC_ONLY(FinalizerTrait);
static const bool kNonTrivialFinalizer =
- !WTF::IsTriviallyDestructible<T>::value;
+ !std::is_trivially_destructible<T>::value;
static void Finalize(void* obj) {
FinalizerTraitImpl<WTF::ListHashSetNode<T, Allocator>,
kNonTrivialFinalizer>::Finalize(obj);
@@ -110,7 +110,7 @@ template <typename Table>
struct FinalizerTrait<HeapHashTableBacking<Table>> {
STATIC_ONLY(FinalizerTrait);
static const bool kNonTrivialFinalizer =
- !WTF::IsTriviallyDestructible<typename Table::ValueType>::value;
+ !std::is_trivially_destructible<typename Table::ValueType>::value;
static void Finalize(void* obj) {
FinalizerTraitImpl<HeapHashTableBacking<Table>,
kNonTrivialFinalizer>::Finalize(obj);
diff --git a/chromium/third_party/blink/renderer/platform/heap/gc_info.cc b/chromium/third_party/blink/renderer/platform/heap/gc_info.cc
index d553b28b369..6e943a758d0 100644
--- a/chromium/third_party/blink/renderer/platform/heap/gc_info.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/gc_info.cc
@@ -42,14 +42,16 @@ constexpr size_t MaxTableSize() {
} // namespace
GCInfoTable* GCInfoTable::global_table_ = nullptr;
+constexpr uint32_t GCInfoTable::kMaxIndex;
void GCInfoTable::CreateGlobalTable() {
DEFINE_STATIC_LOCAL(GCInfoTable, table, ());
global_table_ = &table;
}
-void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info,
- uint32_t* gc_info_index_slot) {
+uint32_t GCInfoTable::EnsureGCInfoIndex(
+ const GCInfo* gc_info,
+ std::atomic_uint32_t* gc_info_index_slot) {
DCHECK(gc_info);
DCHECK(gc_info_index_slot);
@@ -61,16 +63,18 @@ void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info,
// If more than one thread ends up allocating a slot for
// the same GCInfo, have later threads reuse the slot
// allocated by the first.
- if (*gc_info_index_slot)
- return;
+ uint32_t gc_info_index = gc_info_index_slot->load(std::memory_order_acquire);
+ if (gc_info_index)
+ return gc_info_index;
- uint32_t gc_info_index = ++current_index_;
+ gc_info_index = ++current_index_;
CHECK(gc_info_index < GCInfoTable::kMaxIndex);
if (current_index_ >= limit_)
Resize();
table_[gc_info_index] = gc_info;
- ReleaseStore(gc_info_index_slot, gc_info_index);
+ gc_info_index_slot->store(gc_info_index, std::memory_order_release);
+ return gc_info_index;
}
void GCInfoTable::Resize() {
@@ -89,11 +93,10 @@ void GCInfoTable::Resize() {
// Commit the new size and allow read/write.
// TODO(ajwong): SetSystemPagesAccess should be part of RecommitSystemPages to
// avoid having two calls here.
- bool ok = base::SetSystemPagesAccess(current_table_end, table_size_delta,
- base::PageReadWrite);
- CHECK(ok);
- ok = base::RecommitSystemPages(current_table_end, table_size_delta,
- base::PageReadWrite);
+ base::SetSystemPagesAccess(current_table_end, table_size_delta,
+ base::PageReadWrite);
+ bool ok = base::RecommitSystemPages(current_table_end, table_size_delta,
+ base::PageReadWrite);
CHECK(ok);
#if DCHECK_IS_ON()
diff --git a/chromium/third_party/blink/renderer/platform/heap/gc_info.h b/chromium/third_party/blink/renderer/platform/heap/gc_info.h
index 46eb0fdbb51..37925aeb289 100644
--- a/chromium/third_party/blink/renderer/platform/heap/gc_info.h
+++ b/chromium/third_party/blink/renderer/platform/heap/gc_info.h
@@ -5,13 +5,13 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_GC_INFO_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_GC_INFO_H_
+#include <atomic>
#include "base/gtest_prod_util.h"
#include "third_party/blink/renderer/platform/heap/finalizer_traits.h"
#include "third_party/blink/renderer/platform/heap/name_traits.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
#include "third_party/blink/renderer/platform/wtf/hash_counted_set.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
@@ -72,7 +72,7 @@ class PLATFORM_EXPORT GCInfoTable {
return info;
}
- void EnsureGCInfoIndex(const GCInfo*, uint32_t*);
+ uint32_t EnsureGCInfoIndex(const GCInfo*, std::atomic_uint32_t*);
uint32_t GcInfoIndex() { return current_index_; }
@@ -115,12 +115,15 @@ struct GCInfoAtBaseType {
NameTrait<T>::GetName, FinalizerTrait<T>::kNonTrivialFinalizer,
std::is_polymorphic<T>::value,
};
- static uint32_t gc_info_index = 0;
- if (!AcquireLoad(&gc_info_index))
- GCInfoTable::Get().EnsureGCInfoIndex(&kGcInfo, &gc_info_index);
- DCHECK_GE(gc_info_index, 1u);
- DCHECK(gc_info_index < GCInfoTable::kMaxIndex);
- return gc_info_index;
+ // This is more complicated than using threadsafe initialization, but this
+ // is instantiated many times (once for every GC type).
+ static std::atomic_uint32_t gc_info_index{0};
+ uint32_t index = gc_info_index.load(std::memory_order_acquire);
+ if (!index)
+ index = GCInfoTable::Get().EnsureGCInfoIndex(&kGcInfo, &gc_info_index);
+ DCHECK_GE(index, 1u);
+ DCHECK_LT(index, GCInfoTable::kMaxIndex);
+ return index;
}
};
diff --git a/chromium/third_party/blink/renderer/platform/heap/gc_info_test.cc b/chromium/third_party/blink/renderer/platform/heap/gc_info_test.cc
index 6447fc31900..e87246b9a7d 100644
--- a/chromium/third_party/blink/renderer/platform/heap/gc_info_test.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/gc_info_test.cc
@@ -16,10 +16,11 @@ TEST(GCInfoTest, InitialEmpty) {
TEST(GCInfoTest, ResizeToMaxIndex) {
GCInfoTable table;
GCInfo info = {nullptr, nullptr, nullptr, false, false};
- uint32_t slot = 0;
+ std::atomic_uint32_t slot{0};
for (uint32_t i = 0; i < (GCInfoTable::kMaxIndex - 1); i++) {
slot = 0;
- table.EnsureGCInfoIndex(&info, &slot);
+ uint32_t index = table.EnsureGCInfoIndex(&info, &slot);
+ EXPECT_EQ(index, slot);
EXPECT_LT(0u, slot);
EXPECT_EQ(&info, table.GCInfoFromIndex(slot));
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/gc_task_runner.h b/chromium/third_party/blink/renderer/platform/heap/gc_task_runner.h
index 5c262d85c0d..b088bd8c988 100644
--- a/chromium/third_party/blink/renderer/platform/heap/gc_task_runner.h
+++ b/chromium/third_party/blink/renderer/platform/heap/gc_task_runner.h
@@ -51,9 +51,9 @@ class GCTaskObserver final : public Thread::TaskObserver {
DCHECK(!nesting_ || nesting_ == 1);
}
- void WillProcessTask() override { nesting_++; }
+ void WillProcessTask(const base::PendingTask&) override { nesting_++; }
- void DidProcessTask() override {
+ void DidProcessTask(const base::PendingTask&) override {
// In the production code WebKit::initialize is called from inside the
// message loop so we can get didProcessTask() without corresponding
// willProcessTask once. This is benign.
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap.h b/chromium/third_party/blink/renderer/platform/heap/heap.h
index 499750ce30a..18d8498d8ea 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap.h
+++ b/chromium/third_party/blink/renderer/platform/heap/heap.h
@@ -524,6 +524,55 @@ class GarbageCollected {
DISALLOW_COPY_AND_ASSIGN(GarbageCollected);
};
+template <typename T, bool is_mixin = IsGarbageCollectedMixin<T>::value>
+class ConstructTrait {
+ public:
+};
+
+template <typename T>
+class ConstructTrait<T, false> {
+ public:
+ template <typename... Args>
+ static T* Construct(Args&&... args) {
+ void* memory =
+ T::AllocateObject(sizeof(T), IsEagerlyFinalizedType<T>::value);
+ HeapObjectHeader* header = HeapObjectHeader::FromPayload(memory);
+ header->MarkIsInConstruction();
+ // Placement new as regular operator new() is deleted.
+ T* object = ::new (memory) T(std::forward<Args>(args)...);
+ header->UnmarkIsInConstruction();
+ return object;
+ }
+};
+
+template <typename T>
+class ConstructTrait<T, true> {
+ public:
+ template <typename... Args>
+ NO_SANITIZE_UNRELATED_CAST static T* Construct(Args&&... args) {
+ void* memory =
+ T::AllocateObject(sizeof(T), IsEagerlyFinalizedType<T>::value);
+ HeapObjectHeader* header = HeapObjectHeader::FromPayload(memory);
+ header->MarkIsInConstruction();
+ ThreadState* state =
+ ThreadStateFor<ThreadingTrait<T>::kAffinity>::GetState();
+ state->EnterGCForbiddenScopeIfNeeded(
+ &(reinterpret_cast<T*>(memory)->mixin_constructor_marker_));
+ // Placement new as regular operator new() is deleted.
+ T* object = ::new (memory) T(std::forward<Args>(args)...);
+ header->UnmarkIsInConstruction();
+ return object;
+ }
+};
+
+// Constructs an instance of T, which is a garbage collected type.
+template <typename T, typename... Args>
+T* MakeGarbageCollected(Args&&... args) {
+ static_assert(WTF::IsGarbageCollectedType<T>::value,
+ "T needs to be a garbage collected object");
+ return ConstructTrait<T>::Construct(std::forward<Args>(args)...);
+}
+
// Assigning class types to their arenas.
//
// We use sized arenas for most 'normal' objects to improve memory locality.
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_allocator.h b/chromium/third_party/blink/renderer/platform/heap/heap_allocator.h
index d66766ab92e..fc47be71ac8 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_allocator.h
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_allocator.h
@@ -390,7 +390,9 @@ void HeapVectorBacking<T, Traits>::Finalize(void* pointer) {
"HeapVectorBacking doesn't support objects that cannot be cleared as "
"unused with memset or don't have a vtable");
- DCHECK(!WTF::IsTriviallyDestructible<T>::value);
+ static_assert(
+ !std::is_trivially_destructible<T>::value,
+ "Finalization of trivially destructible classes should not happen.");
HeapObjectHeader* header = HeapObjectHeader::FromPayload(pointer);
// Use the payload size as recorded by the heap to determine how many
// elements to finalize.
@@ -417,7 +419,9 @@ void HeapVectorBacking<T, Traits>::Finalize(void* pointer) {
template <typename Table>
void HeapHashTableBacking<Table>::Finalize(void* pointer) {
using Value = typename Table::ValueType;
- DCHECK(!WTF::IsTriviallyDestructible<Value>::value);
+ static_assert(
+ !std::is_trivially_destructible<Value>::value,
+ "Finalization of trivially destructible classes should not happen.");
HeapObjectHeader* header = HeapObjectHeader::FromPayload(pointer);
// Use the payload size as recorded by the heap to determine how many
// elements to finalize.
@@ -441,10 +445,30 @@ class HeapHashMap : public HashMap<KeyArg,
MappedTraitsArg,
HeapAllocator> {
IS_GARBAGE_COLLECTED_TYPE();
+ using Base =
+ HashMap<KeyArg, MappedArg, HashArg, KeyTraitsArg, MappedTraitsArg>;
static_assert(WTF::IsTraceable<KeyArg>::value ||
WTF::IsTraceable<MappedArg>::value,
"For hash maps without traceable elements, use HashMap<> "
"instead of HeapHashMap<>");
+
+ public:
+ static void* AllocateObject(size_t size, bool eagerly_sweep) {
+ return ThreadHeap::Allocate<
+ HeapHashMap<KeyArg, MappedArg, HashArg, KeyTraitsArg, MappedTraitsArg>>(
+ size, eagerly_sweep);
+ }
+
+ void* operator new(size_t size) = delete;
+ void operator delete(void* p) = delete;
+ void* operator new[](size_t size) = delete;
+ void operator delete[](void* p) = delete;
+ void* operator new(size_t size, NotNullTag null_tag, void* location) {
+ return Base::operator new(size, null_tag, location);
+ }
+ void* operator new(size_t size, void* location) {
+ return Base::operator new(size, location);
+ }
};
template <typename ValueArg,
@@ -453,9 +477,27 @@ template <typename ValueArg,
class HeapHashSet
: public HashSet<ValueArg, HashArg, TraitsArg, HeapAllocator> {
IS_GARBAGE_COLLECTED_TYPE();
+ using Base = HashSet<ValueArg, HashArg, TraitsArg>;
static_assert(WTF::IsTraceable<ValueArg>::value,
"For hash sets without traceable elements, use HashSet<> "
"instead of HeapHashSet<>");
+
+ public:
+ static void* AllocateObject(size_t size, bool eagerly_sweep) {
+ return ThreadHeap::Allocate<HeapHashSet<ValueArg, HashArg, TraitsArg>>(
+ size, eagerly_sweep);
+ }
+
+ void* operator new(size_t size) = delete;
+ void operator delete(void* p) = delete;
+ void* operator new[](size_t size) = delete;
+ void operator delete[](void* p) = delete;
+ void* operator new(size_t size, NotNullTag null_tag, void* location) {
+ return Base::operator new(size, null_tag, location);
+ }
+ void* operator new(size_t size, void* location) {
+ return Base::operator new(size, location);
+ }
};
template <typename ValueArg,
@@ -464,9 +506,27 @@ template <typename ValueArg,
class HeapLinkedHashSet
: public LinkedHashSet<ValueArg, HashArg, TraitsArg, HeapAllocator> {
IS_GARBAGE_COLLECTED_TYPE();
+ using Base = LinkedHashSet<ValueArg, HashArg, TraitsArg>;
static_assert(WTF::IsTraceable<ValueArg>::value,
"For sets without traceable elements, use LinkedHashSet<> "
"instead of HeapLinkedHashSet<>");
+
+ public:
+ static void* AllocateObject(size_t size, bool eagerly_sweep) {
+ return ThreadHeap::Allocate<
+ HeapLinkedHashSet<ValueArg, HashArg, TraitsArg>>(size, eagerly_sweep);
+ }
+
+ void* operator new(size_t size) = delete;
+ void operator delete(void* p) = delete;
+ void* operator new[](size_t size) = delete;
+ void operator delete[](void* p) = delete;
+ void* operator new(size_t size, NotNullTag null_tag, void* location) {
+ return Base::operator new(size, null_tag, location);
+ }
+ void* operator new(size_t size, void* location) {
+ return Base::operator new(size, location);
+ }
};
template <typename ValueArg,
@@ -480,9 +540,28 @@ class HeapListHashSet
HashArg,
HeapListHashSetAllocator<ValueArg, inlineCapacity>> {
IS_GARBAGE_COLLECTED_TYPE();
+ using Base = ListHashSet<ValueArg, inlineCapacity, HashArg>;
static_assert(WTF::IsTraceable<ValueArg>::value,
"For sets without traceable elements, use ListHashSet<> "
"instead of HeapListHashSet<>");
+
+ public:
+ static void* AllocateObject(size_t size, bool eagerly_sweep) {
+ return ThreadHeap::Allocate<
+ HeapListHashSet<ValueArg, inlineCapacity, HashArg>>(size,
+ eagerly_sweep);
+ }
+
+ void* operator new(size_t size) = delete;
+ void operator delete(void* p) = delete;
+ void* operator new[](size_t size) = delete;
+ void operator delete[](void* p) = delete;
+ void* operator new(size_t size, NotNullTag null_tag, void* location) {
+ return Base::operator new(size, null_tag, location);
+ }
+ void* operator new(size_t size, void* location) {
+ return Base::operator new(size, location);
+ }
};
template <typename Value,
@@ -508,24 +587,21 @@ class HeapVector : public Vector<T, inlineCapacity, HeapAllocator> {
"instead of HeapVector<>");
}
- void* operator new(size_t size) {
- static_assert(
- inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
- "on-heap HeapVector<Persistent<>> should not have an inline capacity");
- return Base::operator new(size);
- }
- void operator delete(void* p) { return Base::operator delete(p); };
- void* operator new[](size_t size) {
- static_assert(
- inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
- "on-heap HeapVector<Persistent<>> should not have an inline capacity");
- return Base::operator new[](size);
+ static void* AllocateObject(size_t size, bool eagerly_sweep) {
+ // On-heap HeapVectors generally should not have inline capacity, but it is
+ // hard to avoid when using a type alias. Hence we only disallow the
+ // VectorTraits<T>::kNeedsDestruction case for now.
+ static_assert(inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
+ "on-heap HeapVector<> should not have an inline capacity");
+ return ThreadHeap::Allocate<HeapVector<T, inlineCapacity>>(size,
+ eagerly_sweep);
}
- void operator delete[](void* p) { return Base::operator delete[](p); };
+
+ void* operator new(size_t size) = delete;
+ void operator delete(void* p) = delete;
+ void* operator new[](size_t size) = delete;
+ void operator delete[](void* p) = delete;
void* operator new(size_t size, NotNullTag null_tag, void* location) {
- static_assert(
- inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
- "on-heap HeapVector<Persistent<>> should not have an inline capacity");
return Base::operator new(size, null_tag, location);
}
void* operator new(size_t size, void* location) {
@@ -555,24 +631,21 @@ class HeapDeque : public Deque<T, inlineCapacity, HeapAllocator> {
"of HeapDeque<>");
}
- void* operator new(size_t size) {
- static_assert(
- inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
- "on-heap HeapDeque<Persistent<>> should not have an inline capacity");
- return Base::operator new(size);
+ static void* AllocateObject(size_t size, bool eagerly_sweep) {
+ // On-heap HeapDeques generally should not have inline capacity, but it is
+ // hard to avoid when using a type alias. Hence we only disallow the
+ // VectorTraits<T>::kNeedsDestruction case for now.
+ static_assert(inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
+ "on-heap HeapDeque<> should not have an inline capacity");
+ return ThreadHeap::Allocate<HeapVector<T, inlineCapacity>>(size,
+ eagerly_sweep);
}
- void operator delete(void* p) { return Base::operator delete(p); };
- void* operator new[](size_t size) {
- static_assert(
- inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
- "on-heap HeapDequer<Persistent<>> should not have an inline capacity");
- return Base::operator new[](size);
- }
- void operator delete[](void* p) { return Base::operator delete[](p); };
+
+ void* operator new(size_t size) = delete;
+ void operator delete(void* p) = delete;
+ void* operator new[](size_t size) = delete;
+ void operator delete[](void* p) = delete;
void* operator new(size_t size, NotNullTag null_tag, void* location) {
- static_assert(
- inlineCapacity == 0 || !VectorTraits<T>::kNeedsDestruction,
- "on-heap HeapDeque<Persistent<>> should not have an inline capacity");
return Base::operator new(size, null_tag, location);
}
void* operator new(size_t size, void* location) {
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_compact.cc b/chromium/third_party/blink/renderer/platform/heap/heap_compact.cc
index 4b6e34ce42b..551e0059f5a 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_compact.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_compact.cc
@@ -315,7 +315,8 @@ HeapCompact::HeapCompact(ThreadHeap* heap)
do_compact_(false),
gc_count_since_last_compaction_(0),
free_list_size_(0),
- compactable_arenas_(0u) {
+ compactable_arenas_(0u),
+ last_fixup_count_for_testing_(0) {
// The heap compaction implementation assumes the contiguous range,
//
// [Vector1ArenaIndex, HashTableArenaIndex]
@@ -489,9 +490,12 @@ void HeapCompact::StartThreadCompaction() {
return;
// The mapping between the slots and the backing stores are created
+ last_fixup_count_for_testing_ = 0;
for (auto** slot : traced_slots_) {
- if (*slot)
+ if (*slot) {
Fixups().Add(slot);
+ last_fixup_count_for_testing_++;
+ }
}
traced_slots_.clear();
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_compact.h b/chromium/third_party/blink/renderer/platform/heap/heap_compact.h
index 780e72f56a4..a41c5d39ef0 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_compact.h
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_compact.h
@@ -137,6 +137,10 @@ class PLATFORM_EXPORT HeapCompact final {
return false;
}
+ size_t last_fixup_count_for_testing() {
+ return last_fixup_count_for_testing_;
+ }
+
private:
class MovableObjectFixups;
@@ -180,6 +184,8 @@ class PLATFORM_EXPORT HeapCompact final {
// created at the atomic pause phase.
HashSet<MovableReference*> traced_slots_;
+ size_t last_fixup_count_for_testing_;
+
static bool force_compaction_gc_;
};
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_compact_test.cc b/chromium/third_party/blink/renderer/platform/heap/heap_compact_test.cc
index bc50ef6de6e..c7035774eab 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_compact_test.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_compact_test.cc
@@ -242,7 +242,7 @@ TEST(HeapCompactTest, CompactVector) {
ClearOutOldGarbage();
IntWrapper* val = IntWrapper::Create(1, VectorsAreCompacted);
- Persistent<IntVector> vector = new IntVector(10, val);
+ Persistent<IntVector> vector = MakeGarbageCollected<IntVector>(10, val);
EXPECT_EQ(10u, vector->size());
for (IntWrapper* item : *vector)
@@ -257,7 +257,7 @@ TEST(HeapCompactTest, CompactVector) {
TEST(HeapCompactTest, CompactHashMap) {
ClearOutOldGarbage();
- Persistent<IntMap> int_map = new IntMap();
+ Persistent<IntMap> int_map = MakeGarbageCollected<IntMap>();
for (wtf_size_t i = 0; i < 100; ++i) {
IntWrapper* val = IntWrapper::Create(i, HashTablesAreCompacted);
int_map->insert(val, 100 - i);
@@ -279,7 +279,8 @@ TEST(HeapCompactTest, CompactVectorPartHashMap) {
using IntMapVector = HeapVector<IntMap>;
- Persistent<IntMapVector> int_map_vector = new IntMapVector();
+ Persistent<IntMapVector> int_map_vector =
+ MakeGarbageCollected<IntMapVector>();
for (size_t i = 0; i < 10; ++i) {
IntMap map;
for (wtf_size_t j = 0; j < 10; ++j) {
@@ -314,7 +315,8 @@ TEST(HeapCompactTest, CompactHashPartVector) {
using IntVectorMap = HeapHashMap<int, IntVector>;
- Persistent<IntVectorMap> int_vector_map = new IntVectorMap();
+ Persistent<IntVectorMap> int_vector_map =
+ MakeGarbageCollected<IntVectorMap>();
for (wtf_size_t i = 0; i < 10; ++i) {
IntVector vector;
for (wtf_size_t j = 0; j < 10; ++j) {
@@ -344,7 +346,7 @@ TEST(HeapCompactTest, CompactHashPartVector) {
}
TEST(HeapCompactTest, CompactDeques) {
- Persistent<IntDeque> deque = new IntDeque;
+ Persistent<IntDeque> deque = MakeGarbageCollected<IntDeque>();
for (int i = 0; i < 8; ++i) {
deque->push_front(IntWrapper::Create(i, VectorsAreCompacted));
}
@@ -361,7 +363,8 @@ TEST(HeapCompactTest, CompactDeques) {
}
TEST(HeapCompactTest, CompactDequeVectors) {
- Persistent<HeapDeque<IntVector>> deque = new HeapDeque<IntVector>;
+ Persistent<HeapDeque<IntVector>> deque =
+ MakeGarbageCollected<HeapDeque<IntVector>>();
for (int i = 0; i < 8; ++i) {
IntWrapper* value = IntWrapper::Create(i, VectorsAreCompacted);
IntVector vector = IntVector(8, value);
@@ -381,7 +384,7 @@ TEST(HeapCompactTest, CompactDequeVectors) {
TEST(HeapCompactTest, CompactLinkedHashSet) {
using OrderedHashSet = HeapLinkedHashSet<Member<IntWrapper>>;
- Persistent<OrderedHashSet> set = new OrderedHashSet;
+ Persistent<OrderedHashSet> set = MakeGarbageCollected<OrderedHashSet>();
for (int i = 0; i < 13; ++i) {
IntWrapper* value = IntWrapper::Create(i, HashTablesAreCompacted);
set->insert(value);
@@ -406,10 +409,10 @@ TEST(HeapCompactTest, CompactLinkedHashSet) {
TEST(HeapCompactTest, CompactLinkedHashSetVector) {
using OrderedHashSet = HeapLinkedHashSet<Member<IntVector>>;
- Persistent<OrderedHashSet> set = new OrderedHashSet;
+ Persistent<OrderedHashSet> set = MakeGarbageCollected<OrderedHashSet>();
for (int i = 0; i < 13; ++i) {
IntWrapper* value = IntWrapper::Create(i);
- IntVector* vector = new IntVector(19, value);
+ IntVector* vector = MakeGarbageCollected<IntVector>(19, value);
set->insert(vector);
}
EXPECT_EQ(13u, set->size());
@@ -434,10 +437,10 @@ TEST(HeapCompactTest, CompactLinkedHashSetMap) {
using Inner = HeapHashSet<Member<IntWrapper>>;
using OrderedHashSet = HeapLinkedHashSet<Member<Inner>>;
- Persistent<OrderedHashSet> set = new OrderedHashSet;
+ Persistent<OrderedHashSet> set = MakeGarbageCollected<OrderedHashSet>();
for (int i = 0; i < 13; ++i) {
IntWrapper* value = IntWrapper::Create(i);
- Inner* inner = new Inner;
+ Inner* inner = MakeGarbageCollected<Inner>();
inner->insert(value);
set->insert(inner);
}
@@ -465,10 +468,10 @@ TEST(HeapCompactTest, CompactLinkedHashSetNested) {
using Inner = HeapLinkedHashSet<Member<IntWrapper>>;
using OrderedHashSet = HeapLinkedHashSet<Member<Inner>>;
- Persistent<OrderedHashSet> set = new OrderedHashSet;
+ Persistent<OrderedHashSet> set = MakeGarbageCollected<OrderedHashSet>();
for (int i = 0; i < 13; ++i) {
IntWrapper* value = IntWrapper::Create(i);
- Inner* inner = new Inner;
+ Inner* inner = MakeGarbageCollected<Inner>();
inner->insert(value);
set->insert(inner);
}
@@ -507,10 +510,11 @@ TEST(HeapCompactTest, CompactInlinedBackingStore) {
using Value = HeapVector<Member<IntWrapper>, 64>;
using MapWithInlinedBacking = HeapHashMap<Key, Value>;
- Persistent<MapWithInlinedBacking> map = new MapWithInlinedBacking;
+ Persistent<MapWithInlinedBacking> map =
+ MakeGarbageCollected<MapWithInlinedBacking>();
{
// Create a map that is reclaimed during compaction.
- (new MapWithInlinedBacking)
+ (MakeGarbageCollected<MapWithInlinedBacking>())
->insert(IntWrapper::Create(1, HashTablesAreCompacted), Value());
IntWrapper* wrapper = IntWrapper::Create(1, HashTablesAreCompacted);
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_linked_stack.h b/chromium/third_party/blink/renderer/platform/heap/heap_linked_stack.h
index 8f6820b1b99..27bc3d7acdf 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_linked_stack.h
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_linked_stack.h
@@ -87,7 +87,7 @@ inline bool HeapLinkedStack<T>::IsEmpty() {
template <typename T>
inline void HeapLinkedStack<T>::Push(const T& data) {
- head_ = new Node(data, head_);
+ head_ = MakeGarbageCollected<Node>(data, head_);
++size_;
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_page.h b/chromium/third_party/blink/renderer/platform/heap/heap_page.h
index 29c37d9c342..b2625f01a6a 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_page.h
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_page.h
@@ -146,34 +146,39 @@ uint32_t ComputeRandomMagic();
// HeapObjectHeader is a 64-bit (64-bit platforms) or 32-bit (32-bit platforms)
// object that has the following layout:
//
-// | random magic value (32 bits) | <- present on 64-bit platforms only
+// | random magic value (32 bits) | Only present on 64-bit platforms.
// | gc_info_index (14 bits) |
-// | DOM mark bit (1 bit) |
-// | size (14 bits) |
-// | dead bit (1 bit) |
-// | freed bit (1 bit) |
+// | in construction (1 bit) |
+// | size (14 bits) | Actually 17 bits because sizes are aligned.
+// | wrapper mark bit (1 bit) |
+// | unused (1 bit) |
// | mark bit (1 bit) |
//
-// - For non-large objects, 14 bits are enough for |size| because the Blink page
-// size is 2^kBlinkPageSizeLog2 (kBlinkPageSizeLog2 = 17) bytes, and each
-// object is guaranteed to be aligned on a kAllocationGranularity-byte
-// boundary.
-// - For large objects, |size| is 0. The actual size of a large object is
+// Notes:
+// - 14 bits for |gc_info_index} (type information) are enough as there are
+// fewer than 2^14 types allocated in Blink.
+// - |size| for regular objects is encoded with 14 bits but can actually
+// represent sizes up to |kBlinkPageSize| (2^17) because allocations are
+// always 8 byte aligned (see kAllocationGranularity).
+// - |size| for large objects is encoded as 0. The size of a large object is
// stored in |LargeObjectPage::PayloadSize()|.
-// - 1 bit used to mark DOM trees for V8.
-// - 14 bits are enough for |gc_info_index| because there are fewer than 2^14
-// types in Blink.
-constexpr size_t kHeaderWrapperMarkBitMask = 1u << kBlinkPageSizeLog2;
-constexpr size_t kHeaderGCInfoIndexShift = kBlinkPageSizeLog2 + 1;
-constexpr size_t kHeaderGCInfoIndexMask = (static_cast<size_t>((1 << 14) - 1))
- << kHeaderGCInfoIndexShift;
-constexpr size_t kHeaderSizeMask = (static_cast<size_t>((1 << 14) - 1)) << 3;
-constexpr size_t kHeaderMarkBitMask = 1;
-constexpr size_t kHeaderFreedBitMask = 2;
-constexpr size_t kLargeObjectSizeInHeader = 0;
-constexpr size_t kGcInfoIndexForFreeListHeader = 0;
+constexpr uint32_t kHeaderMarkBitMask = 1;
+constexpr uint32_t kHeaderUnusedBit1Mask = 2;
+constexpr uint32_t kHeaderWrapperMarkBitMask = 4;
+constexpr uint32_t kHeaderSizeMask = ((uint32_t{1} << 14) - 1) << 3;
+constexpr uint32_t kHeaderIsInConstructionMask = uint32_t{1} << 17;
+constexpr uint32_t kHeaderGCInfoIndexShift = 18;
+constexpr uint32_t kHeaderGCInfoSize = uint32_t{1} << 14;
+constexpr uint32_t kHeaderGCInfoIndexMask = (kHeaderGCInfoSize - 1)
+ << kHeaderGCInfoIndexShift;
+
+constexpr uint32_t kLargeObjectSizeInHeader = 0;
+constexpr uint32_t kGcInfoIndexForFreeListHeader = 0;
constexpr size_t kNonLargeObjectPageSizeMax = 1 << kBlinkPageSizeLog2;
+static_assert(kHeaderGCInfoSize == GCInfoTable::kMaxIndex,
+ "GCInfoTable size and and header GCInfo index size must match");
+
static_assert(
kNonLargeObjectPageSizeMax >= kBlinkPageSize,
"max size supported by HeapObjectHeader must at least be kBlinkPageSize");
@@ -184,34 +189,46 @@ class PLATFORM_EXPORT HeapObjectHeader {
public:
enum HeaderLocation { kNormalPage, kLargePage };
+ // The following values are used when zapping free list entries.
+ // Regular zapping value.
+ static const uint32_t kZappedMagic = 0xDEAD4321;
+ // On debug and sanitizer builds the zap values differ, indicating when free
+ // list entires are allowed to be reused.
+ static const uint32_t kZappedMagicAllowed = 0x2a2a2a2a;
+ static const uint32_t kZappedMagicForbidden = 0x2c2c2c2c;
+
+ static HeapObjectHeader* FromPayload(const void*);
+
+ // Checks sanity of the header given a payload pointer.
+ static void CheckFromPayload(const void*);
+
// If |gc_info_index| is 0, this header is interpreted as a free list header.
- NO_SANITIZE_ADDRESS
- inline HeapObjectHeader(size_t, size_t, HeaderLocation);
+ HeapObjectHeader(size_t, size_t, HeaderLocation);
NO_SANITIZE_ADDRESS bool IsFree() const {
- return encoded_ & kHeaderFreedBitMask;
+ return GcInfoIndex() == kGcInfoIndexForFreeListHeader;
}
- size_t size() const;
-
NO_SANITIZE_ADDRESS uint32_t GcInfoIndex() const {
return (encoded_ & kHeaderGCInfoIndexMask) >> kHeaderGCInfoIndexShift;
}
- NO_SANITIZE_ADDRESS void SetSize(size_t size) {
- DCHECK_LT(size, kNonLargeObjectPageSizeMax);
- CheckHeader();
- encoded_ = static_cast<uint32_t>(size) | (encoded_ & ~kHeaderSizeMask);
- }
+ size_t size() const;
+ void SetSize(size_t size);
bool IsWrapperHeaderMarked() const;
void MarkWrapperHeader();
void UnmarkWrapperHeader();
+
bool IsMarked() const;
void Mark();
void Unmark();
bool TryMark();
+ void MarkIsInConstruction();
+ void UnmarkIsInConstruction();
+ bool IsInConstruction() const;
+
// The payload starts directly after the HeapObjectHeader, and the payload
// size does not include the sizeof(HeapObjectHeader).
Address Payload();
@@ -219,27 +236,12 @@ class PLATFORM_EXPORT HeapObjectHeader {
Address PayloadEnd();
void Finalize(Address, size_t);
- static HeapObjectHeader* FromPayload(const void*);
-
- // Some callers formerly called |FromPayload| only for its side-effect of
- // calling |CheckHeader| (which is now private). This function does that, but
- // its explanatory name makes the intention at the call sites easier to
- // understand, and is public.
- static void CheckFromPayload(const void*);
// Returns true if magic number is valid.
bool IsValid() const;
// Returns true if magic number is valid or zapped.
bool IsValidOrZapped() const;
- // The following values are used when zapping free list entries.
- // Regular zapping value.
- static const uint32_t kZappedMagic = 0xDEAD4321;
- // On debug and sanitizer builds the zap values differ, indicating when free
- // list entires are allowed to be reused.
- static const uint32_t kZappedMagicAllowed = 0x2a2a2a2a;
- static const uint32_t kZappedMagicForbidden = 0x2c2c2c2c;
-
protected:
#if DCHECK_IS_ON() && defined(ARCH_CPU_64_BITS)
// Zap |m_magic| with a new magic number that means there was once an object
@@ -892,6 +894,18 @@ PLATFORM_EXPORT ALWAYS_INLINE BasePage* PageFromObject(const void* object) {
return page;
}
+inline HeapObjectHeader* HeapObjectHeader::FromPayload(const void* payload) {
+ Address addr = reinterpret_cast<Address>(const_cast<void*>(payload));
+ HeapObjectHeader* header =
+ reinterpret_cast<HeapObjectHeader*>(addr - sizeof(HeapObjectHeader));
+ header->CheckHeader();
+ return header;
+}
+
+inline void HeapObjectHeader::CheckFromPayload(const void* payload) {
+ (void)FromPayload(payload);
+}
+
NO_SANITIZE_ADDRESS inline size_t HeapObjectHeader::size() const {
size_t result = encoded_ & kHeaderSizeMask;
// Large objects should not refer to header->size() but use
@@ -901,6 +915,26 @@ NO_SANITIZE_ADDRESS inline size_t HeapObjectHeader::size() const {
return result;
}
+NO_SANITIZE_ADDRESS inline void HeapObjectHeader::SetSize(size_t size) {
+ DCHECK_LT(size, kNonLargeObjectPageSizeMax);
+ CheckHeader();
+ encoded_ = static_cast<uint32_t>(size) | (encoded_ & ~kHeaderSizeMask);
+}
+
+NO_SANITIZE_ADDRESS inline bool HeapObjectHeader::IsInConstruction() const {
+ return encoded_ & kHeaderIsInConstructionMask;
+}
+
+NO_SANITIZE_ADDRESS inline void HeapObjectHeader::MarkIsInConstruction() {
+ DCHECK(!IsInConstruction());
+ encoded_ = encoded_ | kHeaderIsInConstructionMask;
+}
+
+NO_SANITIZE_ADDRESS inline void HeapObjectHeader::UnmarkIsInConstruction() {
+ DCHECK(IsInConstruction());
+ encoded_ = encoded_ & ~kHeaderIsInConstructionMask;
+}
+
NO_SANITIZE_ADDRESS inline bool HeapObjectHeader::IsValid() const {
#if defined(ARCH_CPU_64_BITS)
return GetMagic() == magic_;
@@ -943,18 +977,6 @@ NO_SANITIZE_ADDRESS inline size_t HeapObjectHeader::PayloadSize() {
return size - sizeof(HeapObjectHeader);
}
-inline HeapObjectHeader* HeapObjectHeader::FromPayload(const void* payload) {
- Address addr = reinterpret_cast<Address>(const_cast<void*>(payload));
- HeapObjectHeader* header =
- reinterpret_cast<HeapObjectHeader*>(addr - sizeof(HeapObjectHeader));
- header->CheckHeader();
- return header;
-}
-
-inline void HeapObjectHeader::CheckFromPayload(const void* payload) {
- (void)FromPayload(payload);
-}
-
NO_SANITIZE_ADDRESS inline bool HeapObjectHeader::IsWrapperHeaderMarked()
const {
CheckHeader();
@@ -1079,9 +1101,10 @@ inline void ObjectStartBitmap::Iterate(Callback callback) const {
}
}
-inline HeapObjectHeader::HeapObjectHeader(size_t size,
- size_t gc_info_index,
- HeaderLocation header_location) {
+NO_SANITIZE_ADDRESS inline HeapObjectHeader::HeapObjectHeader(
+ size_t size,
+ size_t gc_info_index,
+ HeaderLocation header_location) {
// sizeof(HeapObjectHeader) must be equal to or smaller than
// |kAllocationGranularity|, because |HeapObjectHeader| is used as a header
// for a freed entry. Given that the smallest entry size is
@@ -1098,11 +1121,8 @@ inline HeapObjectHeader::HeapObjectHeader(size_t size,
DCHECK(gc_info_index < GCInfoTable::kMaxIndex);
DCHECK_LT(size, kNonLargeObjectPageSizeMax);
DCHECK(!(size & kAllocationMask));
- encoded_ = static_cast<uint32_t>(
- (gc_info_index << kHeaderGCInfoIndexShift) | size |
- (gc_info_index == kGcInfoIndexForFreeListHeader ? kHeaderFreedBitMask
- : 0));
-
+ encoded_ =
+ static_cast<uint32_t>((gc_info_index << kHeaderGCInfoIndexShift) | size);
if (header_location == kNormalPage) {
DCHECK(!PageFromObject(this)->IsLargeObjectPage());
static_cast<NormalPage*>(PageFromObject(this))
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.cc b/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.cc
index 7e6c95857c2..58c37a29736 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.cc
@@ -79,11 +79,13 @@ void ThreadHeapStatsCollector::NotifySweepingCompleted() {
? static_cast<double>(current().marked_bytes) /
current_.object_size_in_bytes_before_sweeping
: 0.0;
+ current_.gc_nested_in_v8_ = gc_nested_in_v8_;
previous_ = std::move(current_);
// Reset the current state.
static_assert(!std::is_polymorphic<Event>::value,
"Event should not be polymorphic");
memset(&current_, 0, sizeof(current_));
+ gc_nested_in_v8_ = TimeDelta();
}
void ThreadHeapStatsCollector::UpdateReason(BlinkGC::GCReason reason) {
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.h b/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.h
index 05680bbd4d9..2e8880d4ae4 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.h
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_stats_collector.h
@@ -112,11 +112,11 @@ class PLATFORM_EXPORT ThreadHeapStatsCollector {
template <typename... Args>
inline InternalScope(ThreadHeapStatsCollector* tracer, Id id, Args... args)
: tracer_(tracer), start_time_(WTF::CurrentTimeTicks()), id_(id) {
- StartTrace(args...);
+ StartTrace(id, args...);
}
inline ~InternalScope() {
- TRACE_EVENT_END0(TraceCategory(), ToString(id_));
+ StopTrace(id_);
tracer_->IncreaseScopeTime(id_, WTF::CurrentTimeTicks() - start_time_);
}
@@ -132,18 +132,26 @@ class PLATFORM_EXPORT ThreadHeapStatsCollector {
}
}
- void StartTrace() { TRACE_EVENT_BEGIN0(TraceCategory(), ToString(id_)); }
+ void StartTrace(Id id) {
+ TRACE_EVENT_BEGIN0(TraceCategory(), ToString(id));
+ }
template <typename Value1>
- void StartTrace(const char* k1, Value1 v1) {
- TRACE_EVENT_BEGIN1(TraceCategory(), ToString(id_), k1, v1);
+ void StartTrace(Id id, const char* k1, Value1 v1) {
+ TRACE_EVENT_BEGIN1(TraceCategory(), ToString(id), k1, v1);
}
template <typename Value1, typename Value2>
- void StartTrace(const char* k1, Value1 v1, const char* k2, Value2 v2) {
- TRACE_EVENT_BEGIN2(TraceCategory(), ToString(id_), k1, v1, k2, v2);
+ void StartTrace(Id id,
+ const char* k1,
+ Value1 v1,
+ const char* k2,
+ Value2 v2) {
+ TRACE_EVENT_BEGIN2(TraceCategory(), ToString(id), k1, v1, k2, v2);
}
+ void StopTrace(Id id) { TRACE_EVENT_END0(TraceCategory(), ToString(id)); }
+
ThreadHeapStatsCollector* const tracer_;
const TimeTicks start_time_;
const Id id_;
@@ -153,6 +161,25 @@ class PLATFORM_EXPORT ThreadHeapStatsCollector {
using EnabledScope = InternalScope<kEnabled>;
using DevToolsScope = InternalScope<kDevTools>;
+ class PLATFORM_EXPORT BlinkGCInV8Scope {
+ DISALLOW_NEW();
+ DISALLOW_COPY_AND_ASSIGN(BlinkGCInV8Scope);
+
+ public:
+ template <typename... Args>
+ BlinkGCInV8Scope(ThreadHeapStatsCollector* tracer)
+ : tracer_(tracer), start_time_(WTF::CurrentTimeTicks()) {}
+
+ ~BlinkGCInV8Scope() {
+ if (tracer_)
+ tracer_->gc_nested_in_v8_ += WTF::CurrentTimeTicks() - start_time_;
+ }
+
+ private:
+ ThreadHeapStatsCollector* const tracer_;
+ const TimeTicks start_time_;
+ };
+
// POD to hold interesting data accumulated during a garbage collection cycle.
// The event is always fully polulated when looking at previous events but
// is only be partially populated when looking at the current event. See
@@ -173,6 +200,7 @@ class PLATFORM_EXPORT ThreadHeapStatsCollector {
size_t partition_alloc_bytes_before_sweeping = 0;
double live_object_rate = 0;
size_t wrapper_count_before_sweeping = 0;
+ TimeDelta gc_nested_in_v8_;
};
// Indicates a new garbage collection cycle.
@@ -250,6 +278,10 @@ class PLATFORM_EXPORT ThreadHeapStatsCollector {
bool is_started_ = false;
+ // TimeDelta for RawScope. These don't need to be nested within a garbage
+ // collection cycle to make them easier to use.
+ TimeDelta gc_nested_in_v8_;
+
FRIEND_TEST_ALL_PREFIXES(ThreadHeapStatsCollectorTest, InitialEmpty);
FRIEND_TEST_ALL_PREFIXES(ThreadHeapStatsCollectorTest, IncreaseScopeTime);
FRIEND_TEST_ALL_PREFIXES(ThreadHeapStatsCollectorTest, StopResetsCurrent);
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_terminated_array.h b/chromium/third_party/blink/renderer/platform/heap/heap_terminated_array.h
deleted file mode 100644
index 1f5772757d5..00000000000
--- a/chromium/third_party/blink/renderer/platform/heap/heap_terminated_array.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TERMINATED_ARRAY_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TERMINATED_ARRAY_H_
-
-#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"
-#include "third_party/blink/renderer/platform/wtf/construct_traits.h"
-#include "third_party/blink/renderer/platform/wtf/terminated_array.h"
-#include "third_party/blink/renderer/platform/wtf/terminated_array_builder.h"
-
-namespace blink {
-
-template <typename T>
-class HeapTerminatedArray : public TerminatedArray<T> {
- DISALLOW_NEW();
- IS_GARBAGE_COLLECTED_TYPE();
-
- public:
- using TerminatedArray<T>::begin;
- using TerminatedArray<T>::end;
-
- void Trace(blink::Visitor* visitor) {
- for (typename TerminatedArray<T>::iterator it = begin(); it != end(); ++it)
- visitor->Trace(*it);
- }
-
- private:
- // Allocator describes how HeapTerminatedArrayBuilder should create new
- // instances of HeapTerminatedArray and manage their lifetimes.
- struct Allocator final {
- STATIC_ONLY(Allocator);
- using BackendAllocator = HeapAllocator;
- using PassPtr = HeapTerminatedArray*;
- using Ptr = Member<HeapTerminatedArray>;
-
- static PassPtr Release(Ptr& ptr) { return ptr; }
-
- static PassPtr Create(size_t capacity) {
- // No ConstructTraits as there are no real elements in the array after
- // construction.
- return reinterpret_cast<HeapTerminatedArray*>(
- ThreadHeap::Allocate<HeapTerminatedArray>(
- WTF::Partitions::ComputeAllocationSize(capacity, sizeof(T)),
- IsEagerlyFinalizedType<T>::value));
- }
-
- static PassPtr Resize(PassPtr ptr, size_t capacity) {
- PassPtr array = reinterpret_cast<HeapTerminatedArray*>(
- ThreadHeap::Reallocate<HeapTerminatedArray>(
- ptr,
- WTF::Partitions::ComputeAllocationSize(capacity, sizeof(T))));
- WTF::ConstructTraits<T, VectorTraits<T>, HeapAllocator>::
- NotifyNewElements(reinterpret_cast<T*>(array), array->size());
- return array;
- }
- };
-
- // Prohibit construction. Allocator makes HeapTerminatedArray instances for
- // HeapTerminatedArrayBuilder by pointer casting.
- HeapTerminatedArray() = delete;
-
- template <typename U, template <typename> class>
- friend class WTF::TerminatedArrayBuilder;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TERMINATED_ARRAY_H_
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_terminated_array_builder.h b/chromium/third_party/blink/renderer/platform/heap/heap_terminated_array_builder.h
deleted file mode 100644
index 38bcf84edbd..00000000000
--- a/chromium/third_party/blink/renderer/platform/heap/heap_terminated_array_builder.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.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TERMINATED_ARRAY_BUILDER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TERMINATED_ARRAY_BUILDER_H_
-
-#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/heap/heap_terminated_array.h"
-#include "third_party/blink/renderer/platform/wtf/terminated_array_builder.h"
-
-namespace blink {
-
-template <typename T>
-class HeapTerminatedArrayBuilder final
- : public TerminatedArrayBuilder<T, HeapTerminatedArray> {
- STACK_ALLOCATED();
-
- public:
- explicit HeapTerminatedArrayBuilder(HeapTerminatedArray<T>* array)
- : TerminatedArrayBuilder<T, HeapTerminatedArray>(array) {}
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_HEAP_TERMINATED_ARRAY_BUILDER_H_
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_test.cc b/chromium/third_party/blink/renderer/platform/heap/heap_test.cc
index fa987f1c1ab..d2f50322d53 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_test.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_test.cc
@@ -43,16 +43,15 @@
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/heap_linked_stack.h"
#include "third_party/blink/renderer/platform/heap/heap_stats_collector.h"
-#include "third_party/blink/renderer/platform/heap/heap_terminated_array_builder.h"
#include "third_party/blink/renderer/platform/heap/heap_test_utilities.h"
#include "third_party/blink/renderer/platform/heap/marking_visitor.h"
#include "third_party/blink/renderer/platform/heap/self_keep_alive.h"
#include "third_party/blink/renderer/platform/heap/stack_frame_depth.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
#include "third_party/blink/renderer/platform/wtf/linked_hash_set.h"
@@ -622,7 +621,8 @@ class ThreadedWeaknessTester : public ThreadedTesterBase {
while (!Done()) {
{
Persistent<HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>> weak_map =
- new HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>;
+ MakeGarbageCollected<
+ HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>>();
for (int i = 0; i < kNumberOfAllocations; i++) {
weak_map->insert(static_cast<unsigned>(i), IntWrapper::Create(0));
@@ -1249,8 +1249,10 @@ class FinalizationObserverWithHashMap {
private:
static ObserverMap& Observers() {
- if (!observer_map_)
- observer_map_ = new Persistent<ObserverMap>(new ObserverMap());
+ if (!observer_map_) {
+ observer_map_ =
+ new Persistent<ObserverMap>(MakeGarbageCollected<ObserverMap>());
+ }
return **observer_map_;
}
@@ -1897,7 +1899,9 @@ TEST(HeapTest, SimplePersistent) {
}
TEST(HeapTest, SimpleFinalization) {
+ ClearOutOldGarbage();
{
+ SimpleFinalizedObject::destructor_calls_ = 0;
Persistent<SimpleFinalizedObject> finalized =
SimpleFinalizedObject::Create();
EXPECT_EQ(0, SimpleFinalizedObject::destructor_calls_);
@@ -2069,6 +2073,8 @@ TEST(HeapTest, EagerlySweepingPages) {
TEST(HeapTest, Finalization) {
{
+ HeapTestSubClass::destructor_calls_ = 0;
+ HeapTestSuperClass::destructor_calls_ = 0;
HeapTestSubClass* t1 = HeapTestSubClass::Create();
HeapTestSubClass* t2 = HeapTestSubClass::Create();
HeapTestSuperClass* t3 = HeapTestSuperClass::Create();
@@ -2108,6 +2114,7 @@ TEST(HeapTest, NoAllocation) {
}
TEST(HeapTest, Members) {
+ ClearOutOldGarbage();
Bar::live_ = 0;
{
Persistent<Baz> h1;
@@ -2131,6 +2138,7 @@ TEST(HeapTest, Members) {
}
TEST(HeapTest, MarkTest) {
+ ClearOutOldGarbage();
{
Bar::live_ = 0;
Persistent<Bar> bar = Bar::Create();
@@ -2158,6 +2166,7 @@ TEST(HeapTest, MarkTest) {
}
TEST(HeapTest, DeepTest) {
+ ClearOutOldGarbage();
const unsigned kDepth = 100000;
Bar::live_ = 0;
{
@@ -2187,6 +2196,7 @@ TEST(HeapTest, DeepTest) {
}
TEST(HeapTest, WideTest) {
+ ClearOutOldGarbage();
Bar::live_ = 0;
{
Bars* bars = Bars::Create();
@@ -2204,10 +2214,9 @@ TEST(HeapTest, WideTest) {
}
TEST(HeapTest, HashMapOfMembers) {
+ ClearOutOldGarbage();
ThreadHeap& heap = ThreadState::Current()->Heap();
IntWrapper::destructor_calls_ = 0;
-
- ClearOutOldGarbage();
size_t initial_object_payload_size = heap.ObjectPayloadSizeForTesting();
{
typedef HeapHashMap<Member<IntWrapper>, Member<IntWrapper>,
@@ -2216,7 +2225,8 @@ TEST(HeapTest, HashMapOfMembers) {
HashTraits<Member<IntWrapper>>>
HeapObjectIdentityMap;
- Persistent<HeapObjectIdentityMap> map = new HeapObjectIdentityMap();
+ Persistent<HeapObjectIdentityMap> map =
+ MakeGarbageCollected<HeapObjectIdentityMap>();
map->clear();
size_t after_set_was_created = heap.ObjectPayloadSizeForTesting();
@@ -2388,7 +2398,7 @@ TEST(HeapTest, MAYBE_LargeHashMap) {
wtf_size_t size = kMaxHeapObjectSize /
sizeof(HeapHashMap<int, Member<IntWrapper>>::ValueType);
Persistent<HeapHashMap<int, Member<IntWrapper>>> map =
- new HeapHashMap<int, Member<IntWrapper>>();
+ MakeGarbageCollected<HeapHashMap<int, Member<IntWrapper>>>();
map->ReserveCapacityForSize(size);
EXPECT_LE(size, map->Capacity());
}
@@ -2399,7 +2409,8 @@ TEST(HeapTest, LargeVector) {
// Try to allocate a HeapVectors larger than kMaxHeapObjectSize
// (crbug.com/597953).
wtf_size_t size = kMaxHeapObjectSize / sizeof(int);
- Persistent<HeapVector<int>> vector = new HeapVector<int>(size);
+ Persistent<HeapVector<int>> vector =
+ MakeGarbageCollected<HeapVector<int>>(size);
EXPECT_LE(size, vector->capacity());
}
@@ -2612,26 +2623,30 @@ TEST(HeapTest, HeapCollectionTypes) {
typedef HeapDeque<PairWrappedUnwrapped, 0> DequeWU;
typedef HeapDeque<PairUnwrappedWrapped, 0> DequeUW;
- Persistent<MemberMember> member_member = new MemberMember();
- Persistent<MemberMember> member_member2 = new MemberMember();
- Persistent<MemberMember> member_member3 = new MemberMember();
- Persistent<MemberPrimitive> member_primitive = new MemberPrimitive();
- Persistent<PrimitiveMember> primitive_member = new PrimitiveMember();
- Persistent<MemberSet> set = new MemberSet();
- Persistent<MemberSet> set2 = new MemberSet();
+ Persistent<MemberMember> member_member = MakeGarbageCollected<MemberMember>();
+ Persistent<MemberMember> member_member2 =
+ MakeGarbageCollected<MemberMember>();
+ Persistent<MemberMember> member_member3 =
+ MakeGarbageCollected<MemberMember>();
+ Persistent<MemberPrimitive> member_primitive =
+ MakeGarbageCollected<MemberPrimitive>();
+ Persistent<PrimitiveMember> primitive_member =
+ MakeGarbageCollected<PrimitiveMember>();
+ Persistent<MemberSet> set = MakeGarbageCollected<MemberSet>();
+ Persistent<MemberSet> set2 = MakeGarbageCollected<MemberSet>();
Persistent<MemberCountedSet> set3 = new MemberCountedSet();
- Persistent<MemberVector> vector = new MemberVector();
- Persistent<MemberVector> vector2 = new MemberVector();
- Persistent<VectorWU> vector_wu = new VectorWU();
- Persistent<VectorWU> vector_wu2 = new VectorWU();
- Persistent<VectorUW> vector_uw = new VectorUW();
- Persistent<VectorUW> vector_uw2 = new VectorUW();
- Persistent<MemberDeque> deque = new MemberDeque();
- Persistent<MemberDeque> deque2 = new MemberDeque();
- Persistent<DequeWU> deque_wu = new DequeWU();
- Persistent<DequeWU> deque_wu2 = new DequeWU();
- Persistent<DequeUW> deque_uw = new DequeUW();
- Persistent<DequeUW> deque_uw2 = new DequeUW();
+ Persistent<MemberVector> vector = MakeGarbageCollected<MemberVector>();
+ Persistent<MemberVector> vector2 = MakeGarbageCollected<MemberVector>();
+ Persistent<VectorWU> vector_wu = MakeGarbageCollected<VectorWU>();
+ Persistent<VectorWU> vector_wu2 = MakeGarbageCollected<VectorWU>();
+ Persistent<VectorUW> vector_uw = MakeGarbageCollected<VectorUW>();
+ Persistent<VectorUW> vector_uw2 = MakeGarbageCollected<VectorUW>();
+ Persistent<MemberDeque> deque = MakeGarbageCollected<MemberDeque>();
+ Persistent<MemberDeque> deque2 = MakeGarbageCollected<MemberDeque>();
+ Persistent<DequeWU> deque_wu = MakeGarbageCollected<DequeWU>();
+ Persistent<DequeWU> deque_wu2 = MakeGarbageCollected<DequeWU>();
+ Persistent<DequeUW> deque_uw = MakeGarbageCollected<DequeUW>();
+ Persistent<DequeUW> deque_uw2 = MakeGarbageCollected<DequeUW>();
Persistent<Container> container = Container::Create();
ClearOutOldGarbage();
@@ -3185,7 +3200,7 @@ TEST(HeapTest, HeapWeakCollectionSimple) {
IntWrapper::destructor_calls_ = 0;
Persistent<HeapVector<Member<IntWrapper>>> keep_numbers_alive =
- new HeapVector<Member<IntWrapper>>;
+ MakeGarbageCollected<HeapVector<Member<IntWrapper>>>();
typedef HeapHashMap<WeakMember<IntWrapper>, Member<IntWrapper>> WeakStrong;
typedef HeapHashMap<Member<IntWrapper>, WeakMember<IntWrapper>> StrongWeak;
@@ -3193,10 +3208,10 @@ TEST(HeapTest, HeapWeakCollectionSimple) {
typedef HeapHashSet<WeakMember<IntWrapper>> WeakSet;
typedef HeapHashCountedSet<WeakMember<IntWrapper>> WeakCountedSet;
- Persistent<WeakStrong> weak_strong = new WeakStrong();
- Persistent<StrongWeak> strong_weak = new StrongWeak();
- Persistent<WeakWeak> weak_weak = new WeakWeak();
- Persistent<WeakSet> weak_set = new WeakSet();
+ Persistent<WeakStrong> weak_strong = MakeGarbageCollected<WeakStrong>();
+ Persistent<StrongWeak> strong_weak = MakeGarbageCollected<StrongWeak>();
+ Persistent<WeakWeak> weak_weak = MakeGarbageCollected<WeakWeak>();
+ Persistent<WeakSet> weak_set = MakeGarbageCollected<WeakSet>();
Persistent<WeakCountedSet> weak_counted_set = new WeakCountedSet();
Persistent<IntWrapper> two = IntWrapper::Create(2);
@@ -3246,10 +3261,10 @@ void OrderedSetHelper(bool strong) {
IntWrapper::destructor_calls_ = 0;
Persistent<HeapVector<Member<IntWrapper>>> keep_numbers_alive =
- new HeapVector<Member<IntWrapper>>;
+ MakeGarbageCollected<HeapVector<Member<IntWrapper>>>();
- Persistent<Set> set1 = new Set();
- Persistent<Set> set2 = new Set();
+ Persistent<Set> set1 = MakeGarbageCollected<Set>();
+ Persistent<Set> set2 = MakeGarbageCollected<Set>();
const Set& const_set = *set1.Get();
@@ -3396,8 +3411,8 @@ static void HeapMapDestructorHelper(bool clear_maps) {
HashTraits<WeakMember<IntWrapper>>>
Map;
- Persistent<Map> map(new Map());
- Persistent<RefMap> ref_map(new RefMap());
+ Persistent<Map> map(MakeGarbageCollected<Map>());
+ Persistent<RefMap> ref_map(MakeGarbageCollected<RefMap>());
Persistent<IntWrapper> luck(IntWrapper::Create(103));
@@ -3554,12 +3569,12 @@ void WeakPairsHelper() {
IntWrapper::destructor_calls_ = 0;
Persistent<HeapVector<Member<IntWrapper>>> keep_numbers_alive =
- new HeapVector<Member<IntWrapper>>;
+ MakeGarbageCollected<HeapVector<Member<IntWrapper>>>();
- Persistent<WSSet> weak_strong = new WSSet();
- Persistent<SWSet> strong_weak = new SWSet();
- Persistent<WUSet> weak_unwrapped = new WUSet();
- Persistent<UWSet> unwrapped_weak = new UWSet();
+ Persistent<WSSet> weak_strong = MakeGarbageCollected<WSSet>();
+ Persistent<SWSet> strong_weak = MakeGarbageCollected<SWSet>();
+ Persistent<WUSet> weak_unwrapped = MakeGarbageCollected<WUSet>();
+ Persistent<UWSet> unwrapped_weak = MakeGarbageCollected<UWSet>();
Persistent<IntWrapper> two = IntWrapper::Create(2);
@@ -3642,15 +3657,16 @@ TEST(HeapTest, HeapWeakCollectionTypes) {
unsigned added = add_afterwards ? 100 : 0;
- Persistent<WeakStrong> weak_strong = new WeakStrong();
- Persistent<StrongWeak> strong_weak = new StrongWeak();
- Persistent<WeakWeak> weak_weak = new WeakWeak();
+ Persistent<WeakStrong> weak_strong = MakeGarbageCollected<WeakStrong>();
+ Persistent<StrongWeak> strong_weak = MakeGarbageCollected<StrongWeak>();
+ Persistent<WeakWeak> weak_weak = MakeGarbageCollected<WeakWeak>();
- Persistent<WeakSet> weak_set = new WeakSet();
- Persistent<WeakOrderedSet> weak_ordered_set = new WeakOrderedSet();
+ Persistent<WeakSet> weak_set = MakeGarbageCollected<WeakSet>();
+ Persistent<WeakOrderedSet> weak_ordered_set =
+ MakeGarbageCollected<WeakOrderedSet>();
Persistent<HeapVector<Member<IntWrapper>>> keep_numbers_alive =
- new HeapVector<Member<IntWrapper>>;
+ MakeGarbageCollected<HeapVector<Member<IntWrapper>>>();
for (int i = 0; i < 128; i += 2) {
IntWrapper* wrapped = IntWrapper::Create(i);
IntWrapper* wrapped2 = IntWrapper::Create(i + 1);
@@ -3895,6 +3911,7 @@ TEST(HeapTest, RefCountedGarbageCollected) {
}
TEST(HeapTest, WeakMembers) {
+ ClearOutOldGarbage();
Bar::live_ = 0;
{
Persistent<Bar> h1 = Bar::Create();
@@ -4098,8 +4115,10 @@ TEST(HeapTest, CollectionNesting) {
IntWrapper::destructor_calls_ = 0;
typedef HeapVector<Member<IntWrapper>> IntVector;
typedef HeapDeque<Member<IntWrapper>> IntDeque;
- HeapHashMap<void*, IntVector>* map = new HeapHashMap<void*, IntVector>();
- HeapHashMap<void*, IntDeque>* map2 = new HeapHashMap<void*, IntDeque>();
+ HeapHashMap<void*, IntVector>* map =
+ MakeGarbageCollected<HeapHashMap<void*, IntVector>>();
+ HeapHashMap<void*, IntDeque>* map2 =
+ MakeGarbageCollected<HeapHashMap<void*, IntDeque>>();
static_assert(WTF::IsTraceable<IntVector>::value,
"Failed to recognize HeapVector as traceable");
static_assert(WTF::IsTraceable<IntDeque>::value,
@@ -4153,7 +4172,7 @@ TEST(HeapTest, GarbageCollectedMixin) {
EXPECT_EQ(2, UseMixin::trace_count_);
Persistent<HeapHashSet<WeakMember<Mixin>>> weak_map =
- new HeapHashSet<WeakMember<Mixin>>;
+ MakeGarbageCollected<HeapHashSet<WeakMember<Mixin>>>();
weak_map->insert(UseMixin::Create());
PreciselyCollectGarbage();
EXPECT_EQ(0u, weak_map->size());
@@ -4164,7 +4183,8 @@ TEST(HeapTest, CollectionNesting2) {
void* key = &IntWrapper::destructor_calls_;
IntWrapper::destructor_calls_ = 0;
typedef HeapHashSet<Member<IntWrapper>> IntSet;
- HeapHashMap<void*, IntSet>* map = new HeapHashMap<void*, IntSet>();
+ HeapHashMap<void*, IntSet>* map =
+ MakeGarbageCollected<HeapHashMap<void*, IntSet>>();
map->insert(key, IntSet());
@@ -4185,8 +4205,8 @@ TEST(HeapTest, CollectionNesting3) {
IntWrapper::destructor_calls_ = 0;
typedef HeapVector<Member<IntWrapper>> IntVector;
typedef HeapDeque<Member<IntWrapper>> IntDeque;
- HeapVector<IntVector>* vector = new HeapVector<IntVector>();
- HeapDeque<IntDeque>* deque = new HeapDeque<IntDeque>();
+ HeapVector<IntVector>* vector = MakeGarbageCollected<HeapVector<IntVector>>();
+ HeapDeque<IntDeque>* deque = MakeGarbageCollected<HeapDeque<IntDeque>>();
vector->push_back(IntVector());
deque->push_back(IntDeque());
@@ -4214,9 +4234,9 @@ TEST(HeapTest, EmbeddedInVector) {
SimpleFinalizedObject::destructor_calls_ = 0;
{
Persistent<HeapVector<VectorObject, 2>> inline_vector =
- new HeapVector<VectorObject, 2>;
+ MakeGarbageCollected<HeapVector<VectorObject, 2>>();
Persistent<HeapVector<VectorObject>> outline_vector =
- new HeapVector<VectorObject>;
+ MakeGarbageCollected<HeapVector<VectorObject>>();
VectorObject i1, i2;
inline_vector->push_back(i1);
inline_vector->push_back(i2);
@@ -4226,7 +4246,7 @@ TEST(HeapTest, EmbeddedInVector) {
outline_vector->push_back(o2);
Persistent<HeapVector<VectorObjectInheritedTrace>> vector_inherited_trace =
- new HeapVector<VectorObjectInheritedTrace>;
+ MakeGarbageCollected<HeapVector<VectorObjectInheritedTrace>>();
VectorObjectInheritedTrace it1, it2;
vector_inherited_trace->push_back(it1);
vector_inherited_trace->push_back(it2);
@@ -4243,9 +4263,9 @@ TEST(HeapTest, EmbeddedInDeque) {
SimpleFinalizedObject::destructor_calls_ = 0;
{
Persistent<HeapDeque<VectorObject, 2>> inline_deque =
- new HeapDeque<VectorObject, 2>;
+ MakeGarbageCollected<HeapDeque<VectorObject, 2>>();
Persistent<HeapDeque<VectorObject>> outline_deque =
- new HeapDeque<VectorObject>;
+ MakeGarbageCollected<HeapDeque<VectorObject>>();
VectorObject i1, i2;
inline_deque->push_back(i1);
inline_deque->push_back(i2);
@@ -4255,7 +4275,7 @@ TEST(HeapTest, EmbeddedInDeque) {
outline_deque->push_back(o2);
Persistent<HeapDeque<VectorObjectInheritedTrace>> deque_inherited_trace =
- new HeapDeque<VectorObjectInheritedTrace>;
+ MakeGarbageCollected<HeapDeque<VectorObjectInheritedTrace>>();
VectorObjectInheritedTrace it1, it2;
deque_inherited_trace->push_back(it1);
deque_inherited_trace->push_back(it2);
@@ -4456,60 +4476,6 @@ void RawPtrInHashHelper() {
}
}
-TEST(HeapTest, HeapTerminatedArray) {
- ClearOutOldGarbage();
- IntWrapper::destructor_calls_ = 0;
-
- HeapTerminatedArray<TerminatedArrayItem>* arr = nullptr;
-
- const wtf_size_t kPrefixSize = 4;
- const wtf_size_t kSuffixSize = 4;
-
- {
- HeapTerminatedArrayBuilder<TerminatedArrayItem> builder(arr);
- builder.Grow(kPrefixSize);
- ConservativelyCollectGarbage();
- for (wtf_size_t i = 0; i < kPrefixSize; i++)
- builder.Append(TerminatedArrayItem(IntWrapper::Create(i)));
- arr = builder.Release();
- }
-
- ConservativelyCollectGarbage();
- EXPECT_EQ(0, IntWrapper::destructor_calls_);
- EXPECT_EQ(kPrefixSize, arr->size());
- for (wtf_size_t i = 0; i < kPrefixSize; i++)
- EXPECT_EQ(i, static_cast<wtf_size_t>(arr->at(i).Payload()->Value()));
-
- {
- HeapTerminatedArrayBuilder<TerminatedArrayItem> builder(arr);
- builder.Grow(kSuffixSize);
- for (wtf_size_t i = 0; i < kSuffixSize; i++)
- builder.Append(TerminatedArrayItem(IntWrapper::Create(kPrefixSize + i)));
- arr = builder.Release();
- }
-
- ConservativelyCollectGarbage();
- EXPECT_EQ(0, IntWrapper::destructor_calls_);
- EXPECT_EQ(kPrefixSize + kSuffixSize, arr->size());
- for (wtf_size_t i = 0; i < kPrefixSize + kSuffixSize; i++)
- EXPECT_EQ(i, static_cast<wtf_size_t>(arr->at(i).Payload()->Value()));
-
- {
- Persistent<HeapTerminatedArray<TerminatedArrayItem>> persistent_arr = arr;
- arr = nullptr;
- PreciselyCollectGarbage();
- arr = persistent_arr.Get();
- EXPECT_EQ(0, IntWrapper::destructor_calls_);
- EXPECT_EQ(kPrefixSize + kSuffixSize, arr->size());
- for (wtf_size_t i = 0; i < kPrefixSize + kSuffixSize; i++)
- EXPECT_EQ(i, static_cast<wtf_size_t>(arr->at(i).Payload()->Value()));
- }
-
- arr = nullptr;
- PreciselyCollectGarbage();
- EXPECT_EQ(8, IntWrapper::destructor_calls_);
-}
-
TEST(HeapTest, HeapLinkedStack) {
ClearOutOldGarbage();
IntWrapper::destructor_calls_ = 0;
@@ -4823,10 +4789,10 @@ template <typename Set>
void SetWithCustomWeaknessHandling() {
typedef typename Set::iterator Iterator;
Persistent<IntWrapper> living_int(IntWrapper::Create(42));
- Persistent<Set> set1(new Set());
+ Persistent<Set> set1(MakeGarbageCollected<Set>());
{
Set set2;
- Set* set3 = new Set();
+ Set* set3 = MakeGarbageCollected<Set>();
set2.insert(
PairWithWeakHandling(IntWrapper::Create(0), IntWrapper::Create(1)));
set3->insert(
@@ -4887,11 +4853,11 @@ TEST(HeapTest, MapWithCustomWeaknessHandling) {
ClearOutOldGarbage();
OffHeapInt::destructor_calls_ = 0;
- Persistent<Map> map1(new Map());
+ Persistent<Map> map1(MakeGarbageCollected<Map>());
Persistent<IntWrapper> living_int(IntWrapper::Create(42));
{
Map map2;
- Map* map3 = new Map();
+ Map* map3 = MakeGarbageCollected<Map>();
map2.insert(
PairWithWeakHandling(IntWrapper::Create(0), IntWrapper::Create(1)),
OffHeapInt::Create(1001));
@@ -4969,12 +4935,12 @@ TEST(HeapTest, MapWithCustomWeaknessHandling2) {
ClearOutOldGarbage();
OffHeapInt::destructor_calls_ = 0;
- Persistent<Map> map1(new Map());
+ Persistent<Map> map1(MakeGarbageCollected<Map>());
Persistent<IntWrapper> living_int(IntWrapper::Create(42));
{
Map map2;
- Map* map3 = new Map();
+ Map* map3 = MakeGarbageCollected<Map>();
map2.insert(
OffHeapInt::Create(1001),
PairWithWeakHandling(IntWrapper::Create(0), IntWrapper::Create(1)));
@@ -5056,7 +5022,7 @@ static void AddElementsToWeakMap(
// If it doesn't assert a concurrent modification to the map, then it's passing.
TEST(HeapTest, RegressNullIsStrongified) {
Persistent<HeapHashMap<int, WeakMember<IntWrapper>>> map =
- new HeapHashMap<int, WeakMember<IntWrapper>>();
+ MakeGarbageCollected<HeapHashMap<int, WeakMember<IntWrapper>>>();
AddElementsToWeakMap(map);
HeapHashMap<int, WeakMember<IntWrapper>>::AddResult result =
map->insert(800, nullptr);
@@ -5146,7 +5112,7 @@ TEST(HeapTest, RemoveEmptySets) {
typedef HeapHashMap<Key, WeakSet, WTF::DefaultHash<Key>::Hash,
HashTraits<Key>, EmptyClearingHashSetTraits>
Map;
- Persistent<Map> map(new Map());
+ Persistent<Map> map(MakeGarbageCollected<Map>());
map->insert(OffHeapInt::Create(1), WeakSet());
{
WeakSet& set = map->begin()->value;
@@ -5179,7 +5145,7 @@ TEST(HeapTest, EphemeronsInEphemerons) {
for (int keep_outer_alive = 0; keep_outer_alive <= 1; keep_outer_alive++) {
for (int keep_inner_alive = 0; keep_inner_alive <= 1; keep_inner_alive++) {
- Persistent<OuterMap> outer = new OuterMap();
+ Persistent<OuterMap> outer = MakeGarbageCollected<OuterMap>();
Persistent<IntWrapper> one = IntWrapper::Create(1);
Persistent<IntWrapper> two = IntWrapper::Create(2);
outer->insert(one, InnerMap());
@@ -5207,7 +5173,7 @@ TEST(HeapTest, EphemeronsInEphemerons) {
Persistent<IntWrapper> home = IntWrapper::Create(103);
Persistent<IntWrapper> composite = IntWrapper::Create(91);
Persistent<HeapVector<Member<IntWrapper>>> keep_alive =
- new HeapVector<Member<IntWrapper>>();
+ MakeGarbageCollected<HeapVector<Member<IntWrapper>>>();
for (int i = 0; i < 10000; i++) {
IntWrapper* value = IntWrapper::Create(i);
keep_alive->push_back(value);
@@ -5290,15 +5256,15 @@ TEST(HeapTest, Ephemeron) {
typedef HeapHashMap<PairWithWeakHandling, WeakMember<IntWrapper>> PairWeakMap;
typedef HeapHashSet<WeakMember<IntWrapper>> Set;
- Persistent<WeakPairMap> weak_pair_map = new WeakPairMap();
- Persistent<WeakPairMap> weak_pair_map2 = new WeakPairMap();
- Persistent<WeakPairMap> weak_pair_map3 = new WeakPairMap();
- Persistent<WeakPairMap> weak_pair_map4 = new WeakPairMap();
+ Persistent<WeakPairMap> weak_pair_map = MakeGarbageCollected<WeakPairMap>();
+ Persistent<WeakPairMap> weak_pair_map2 = MakeGarbageCollected<WeakPairMap>();
+ Persistent<WeakPairMap> weak_pair_map3 = MakeGarbageCollected<WeakPairMap>();
+ Persistent<WeakPairMap> weak_pair_map4 = MakeGarbageCollected<WeakPairMap>();
- Persistent<PairWeakMap> pair_weak_map = new PairWeakMap();
- Persistent<PairWeakMap> pair_weak_map2 = new PairWeakMap();
+ Persistent<PairWeakMap> pair_weak_map = MakeGarbageCollected<PairWeakMap>();
+ Persistent<PairWeakMap> pair_weak_map2 = MakeGarbageCollected<PairWeakMap>();
- Persistent<Set> set = new Set();
+ Persistent<Set> set = MakeGarbageCollected<Set>();
Persistent<IntWrapper> wp1 = IntWrapper::Create(1);
Persistent<IntWrapper> wp2 = IntWrapper::Create(2);
@@ -5381,7 +5347,7 @@ class Link1 : public GarbageCollected<Link1> {
TEST(HeapTest, IndirectStrongToWeak) {
typedef HeapHashMap<WeakMember<IntWrapper>, Member<Link1>> Map;
- Persistent<Map> map = new Map();
+ Persistent<Map> map = MakeGarbageCollected<Map>();
Persistent<IntWrapper> dead_object =
IntWrapper::Create(100); // Named for "Drowning by Numbers" (1988).
Persistent<IntWrapper> life_object = IntWrapper::Create(42);
@@ -5489,7 +5455,8 @@ class ThreadedStrongificationTester {
Persistent<IntWrapper> wrapper4 = IntWrapper::Create(32);
Persistent<IntWrapper> wrapper5 = IntWrapper::Create(32);
Persistent<IntWrapper> wrapper6 = IntWrapper::Create(32);
- Persistent<WeakCollectionType> weak_collection = new WeakCollectionType;
+ Persistent<WeakCollectionType> weak_collection =
+ MakeGarbageCollected<WeakCollectionType>();
weak_collection->insert(wrapper1, wrapper1);
weak_collection->insert(wrapper2, wrapper2);
weak_collection->insert(wrapper3, wrapper3);
@@ -5738,6 +5705,7 @@ int ClassWithGarbageCollectingMixinConstructor::trace_called_ = 0;
// Regression test for out of bounds call through vtable.
// Passes if it doesn't crash.
TEST(HeapTest, GarbageCollectionDuringMixinConstruction) {
+ ClassWithGarbageCollectingMixinConstructor::trace_called_ = 0;
ClassWithGarbageCollectingMixinConstructor* a =
new ClassWithGarbageCollectingMixinConstructor();
a->Verify();
@@ -5883,7 +5851,7 @@ namespace blink {
TEST(HeapTest, GCInHashMapOperations) {
typedef HeapHashMap<AllocatesOnAssignment, AllocatesOnAssignment> Map;
- Map* map = new Map();
+ Map* map = MakeGarbageCollected<Map>();
IntWrapper* key = new IntWrapper(42);
map->insert(key, AllocatesOnAssignment(103));
map->erase(key);
@@ -6048,7 +6016,7 @@ TEST(HeapTest, DequeExpand) {
typedef HeapDeque<Member<IntWrapper>> IntDeque;
- Persistent<IntDeque> deque = new IntDeque();
+ Persistent<IntDeque> deque = MakeGarbageCollected<IntDeque>();
// Append a sequence, bringing about repeated expansions of the
// deque's buffer.
@@ -6130,9 +6098,9 @@ TEST(HeapTest, DequePartObjectsExpand) {
using PartDeque = HeapDeque<PartObjectWithRef>;
- Persistent<PartDeque> deque = new PartDeque();
+ Persistent<PartDeque> deque = MakeGarbageCollected<PartDeque>();
// Auxillary Deque used to prevent 'inline' buffer expansion.
- Persistent<PartDeque> deque_unused = new PartDeque();
+ Persistent<PartDeque> deque_unused = MakeGarbageCollected<PartDeque>();
// Append a sequence, bringing about repeated expansions of the
// deque's buffer.
@@ -6366,6 +6334,7 @@ class TestMixinAllocatingObject final
};
TEST(HeapTest, MixinConstructionNoGC) {
+ ClearOutOldGarbage();
Persistent<ClassWithMember> object = ClassWithMember::Create();
EXPECT_EQ(0, object->TraceCount());
TestMixinAllocatingObject* mixin =
@@ -6541,7 +6510,7 @@ ThreadedClearOnShutdownTester::GetWeakHeapObjectSet() {
singleton, ());
Persistent<WeakHeapObjectSet>& singleton_persistent = *singleton;
if (!singleton_persistent) {
- singleton_persistent = new WeakHeapObjectSet();
+ singleton_persistent = MakeGarbageCollected<WeakHeapObjectSet>();
singleton_persistent.RegisterAsStaticReference();
}
return *singleton_persistent;
@@ -6553,7 +6522,7 @@ ThreadedClearOnShutdownTester::GetHeapObjectSet() {
singleton, ());
Persistent<HeapObjectSet>& singleton_persistent = *singleton;
if (!singleton_persistent) {
- singleton_persistent = new HeapObjectSet();
+ singleton_persistent = MakeGarbageCollected<HeapObjectSet>();
singleton_persistent.RegisterAsStaticReference();
}
return *singleton_persistent;
@@ -6653,9 +6622,6 @@ TEST(HeapTest, IsGarbageCollected) {
static_assert(
WTF::IsGarbageCollectedType<HeapDeque<Member<IntWrapper>>>::value,
"HeapDeque");
- static_assert(WTF::IsGarbageCollectedType<
- HeapTerminatedArray<Member<IntWrapper>>>::value,
- "HeapTerminatedArray");
}
TEST(HeapTest, HeapHashMapCallsDestructor) {
@@ -6785,6 +6751,7 @@ TEST(HeapTest, PromptlyFreeStackAllocatedHeapHashSet) {
}
TEST(HeapTest, PromptlyFreeStackAllocatedHeapListHashSet) {
+ ClearOutOldGarbage();
NormalPageArena* normal_arena = static_cast<NormalPageArena*>(
ThreadState::Current()->Heap().Arena(BlinkGC::kHashTableArenaIndex));
CHECK(normal_arena);
@@ -6831,4 +6798,85 @@ TEST(HeapTest, ShrinkVector) {
vector.ShrinkToFit();
}
+namespace {
+
+class MixinCheckingConstructionScope : public GarbageCollectedMixin {
+ public:
+ MixinCheckingConstructionScope() {
+ // Oilpan treats mixin construction as forbidden scopes for garbage
+ // collection.
+ CHECK(ThreadState::Current()->IsMixinInConstruction());
+ }
+};
+
+class UsingMixinCheckingConstructionScope
+ : public GarbageCollected<UsingMixinCheckingConstructionScope>,
+ public MixinCheckingConstructionScope {
+ USING_GARBAGE_COLLECTED_MIXIN(UsingMixinCheckingConstructionScope);
+};
+
+} // namespace
+
+TEST(HeapTest, NoConservativeGCDuringMixinConstruction) {
+ // Regression test: https://crbug.com/904546
+ MakeGarbageCollected<UsingMixinCheckingConstructionScope>();
+}
+
+namespace {
+
+class ObjectCheckingForInConstruction
+ : public GarbageCollected<ObjectCheckingForInConstruction> {
+ public:
+ ObjectCheckingForInConstruction() {
+ CHECK(HeapObjectHeader::FromPayload(this)->IsInConstruction());
+ }
+
+ virtual void Trace(Visitor* v) { v->Trace(foo_); }
+
+ private:
+ Member<IntWrapper> foo_;
+};
+
+class MixinCheckingInConstruction : public GarbageCollectedMixin {
+ public:
+ MixinCheckingInConstruction() {
+ BasePage* const page = PageFromObject(reinterpret_cast<Address>(this));
+ HeapObjectHeader* const header =
+ static_cast<NormalPage*>(page)->FindHeaderFromAddress(
+ reinterpret_cast<Address>(
+ const_cast<MixinCheckingInConstruction*>(this)));
+ CHECK(header->IsInConstruction());
+ }
+
+ void Trace(Visitor* v) override { v->Trace(bar_); }
+
+ private:
+ Member<IntWrapper> bar_;
+};
+
+class MixinAppCheckingInConstruction
+ : public GarbageCollected<MixinAppCheckingInConstruction>,
+ public MixinCheckingInConstruction {
+ USING_GARBAGE_COLLECTED_MIXIN(MixinAppCheckingInConstruction)
+ public:
+ MixinAppCheckingInConstruction() {
+ CHECK(HeapObjectHeader::FromPayload(this)->IsInConstruction());
+ }
+
+ void Trace(Visitor* v) override { v->Trace(foo_); }
+
+ private:
+ Member<IntWrapper> foo_;
+};
+
+} // namespace
+
+TEST(HeapTest, GarbageCollectedInConstruction) {
+ MakeGarbageCollected<ObjectCheckingForInConstruction>();
+}
+
+TEST(HeapTest, GarbageCollectedMixinInConstruction) {
+ MakeGarbageCollected<MixinAppCheckingInConstruction>();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/heap/heap_test_utilities.cc b/chromium/third_party/blink/renderer/platform/heap/heap_test_utilities.cc
index 34fff007117..1d01f7b8856 100644
--- a/chromium/third_party/blink/renderer/platform/heap/heap_test_utilities.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/heap_test_utilities.cc
@@ -25,6 +25,7 @@ void ConservativelyCollectGarbage(BlinkGC::SweepingType sweeping_type) {
// Do several GCs to make sure that later GCs don't free up old memory from
// previously run tests in this process.
void ClearOutOldGarbage() {
+ PreciselyCollectGarbage();
ThreadHeap& heap = ThreadState::Current()->Heap();
while (true) {
size_t used = heap.ObjectPayloadSizeForTesting();
diff --git a/chromium/third_party/blink/renderer/platform/heap/incremental_marking_test.cc b/chromium/third_party/blink/renderer/platform/heap/incremental_marking_test.cc
index f9987a3dec4..f82eaf2df9c 100644
--- a/chromium/third_party/blink/renderer/platform/heap/incremental_marking_test.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/incremental_marking_test.cc
@@ -11,8 +11,7 @@
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/heap/heap_buildflags.h"
#include "third_party/blink/renderer/platform/heap/heap_compact.h"
-#include "third_party/blink/renderer/platform/heap/heap_terminated_array.h"
-#include "third_party/blink/renderer/platform/heap/heap_terminated_array_builder.h"
+#include "third_party/blink/renderer/platform/heap/heap_test_utilities.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
@@ -85,6 +84,10 @@ class IncrementalMarkingScopeBase {
public:
explicit IncrementalMarkingScopeBase(ThreadState* thread_state)
: thread_state_(thread_state), heap_(thread_state_->Heap()) {
+ if (thread_state_->IsMarkingInProgress() ||
+ thread_state_->IsSweepingInProgress()) {
+ PreciselyCollectGarbage();
+ }
heap_.CommitCallbackStacks();
}
@@ -231,6 +234,8 @@ class Object : public GarbageCollected<Object> {
virtual void Trace(blink::Visitor* visitor) { visitor->Trace(next_); }
+ Member<Object>& next_ref() { return next_; }
+
private:
Object() : next_(nullptr) {}
explicit Object(Object* next) : next_(next) {}
@@ -1016,11 +1021,9 @@ TEST(IncrementalMarkingTest, HeapHashSetStrongWeakPair) {
Object* obj2 = Object::Create();
HeapHashSet<StrongWeakPair> set;
{
- // Only the strong field in the StrongWeakPair should be hit by the
- // write barrier.
- ExpectWriteBarrierFires scope(ThreadState::Current(), {obj1});
+ // Both, the weak and the strong field, are hit by the write barrier.
+ ExpectWriteBarrierFires scope(ThreadState::Current(), {obj1, obj2});
set.insert(StrongWeakPair(obj1, obj2));
- EXPECT_FALSE(obj2->IsMarked());
}
}
@@ -1029,11 +1032,9 @@ TEST(IncrementalMarkingTest, HeapLinkedHashSetStrongWeakPair) {
Object* obj2 = Object::Create();
HeapLinkedHashSet<StrongWeakPair> set;
{
- // Only the strong field in the StrongWeakPair should be hit by the
- // write barrier.
- ExpectWriteBarrierFires scope(ThreadState::Current(), {obj1});
+ // Both, the weak and the strong field, are hit by the write barrier.
+ ExpectWriteBarrierFires scope(ThreadState::Current(), {obj1, obj2});
set.insert(StrongWeakPair(obj1, obj2));
- EXPECT_FALSE(obj2->IsMarked());
}
}
@@ -1107,52 +1108,6 @@ TEST(IncrementalMarkingTest, HeapHashCountedSetSwap) {
}
// =============================================================================
-// HeapTerminatedArray support. ================================================
-// =============================================================================
-
-class TerminatedArrayNode {
- DISALLOW_NEW();
-
- public:
- TerminatedArrayNode(Object* obj) : obj_(obj), is_last_in_array_(false) {}
-
- // TerminatedArray support.
- bool IsLastInArray() const { return is_last_in_array_; }
- void SetLastInArray(bool flag) { is_last_in_array_ = flag; }
-
- void Trace(blink::Visitor* visitor) { visitor->Trace(obj_); }
-
- private:
- Member<Object> obj_;
- bool is_last_in_array_;
-};
-
-} // namespace incremental_marking_test
-} // namespace blink
-
-WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(
- blink::incremental_marking_test::TerminatedArrayNode);
-
-namespace blink {
-namespace incremental_marking_test {
-
-TEST(IncrementalMarkingTest, HeapTerminatedArrayBuilder) {
- Object* obj = Object::Create();
- HeapTerminatedArray<TerminatedArrayNode>* array = nullptr;
- {
- // The builder allocates the backing store on Oilpans heap, effectively
- // triggering a write barrier.
- HeapTerminatedArrayBuilder<TerminatedArrayNode> builder(array);
- builder.Grow(1);
- {
- ExpectWriteBarrierFires scope(ThreadState::Current(), {obj});
- builder.Append(TerminatedArrayNode(obj));
- }
- array = builder.Release();
- }
-}
-
-// =============================================================================
// HeapHashMap support. ========================================================
// =============================================================================
@@ -1632,9 +1587,9 @@ class IncrementalMarkingTestDriver {
thread_state_->CompleteSweep();
}
- HashSet<MovableReference*>& GetTracedSlot() {
+ size_t GetHeapCompactLastFixupCount() {
HeapCompact* compaction = ThreadState::Current()->Heap().Compaction();
- return compaction->traced_slots_;
+ return compaction->last_fixup_count_for_testing();
}
private:
@@ -1727,7 +1682,7 @@ TEST(IncrementalMarkingTest, NoBackingFreeDuringIncrementalMarking) {
TEST(IncrementalMarkingTest, DropReferenceWithHeapCompaction) {
using Store = HeapHashCountedSet<Member<Object>>;
- Persistent<Store> persistent(new Store);
+ Persistent<Store> persistent(new Store());
persistent->insert(Object::Create());
IncrementalMarkingTestDriver driver(ThreadState::Current());
HeapCompact::ScheduleCompactionGCForTesting(true);
@@ -1742,19 +1697,88 @@ TEST(IncrementalMarkingTest, DropReferenceWithHeapCompaction) {
TEST(IncrementalMarkingTest, HasInlineCapacityCollectionWithHeapCompaction) {
using Store = HeapVector<Member<Object>, 2>;
- Persistent<Store> persistent(new Store);
- Persistent<Store> persistent2(new Store);
+ Persistent<Store> persistent(MakeGarbageCollected<Store>());
+ Persistent<Store> persistent2(MakeGarbageCollected<Store>());
IncrementalMarkingTestDriver driver(ThreadState::Current());
HeapCompact::ScheduleCompactionGCForTesting(true);
persistent->push_back(Object::Create());
driver.Start();
- driver.FinishSteps();
+ driver.FinishGC();
// Should collect also slots that has only inline buffer and nullptr
// references.
- EXPECT_EQ(driver.GetTracedSlot().size(), 2u);
+#if defined(ANNOTATE_CONTIGUOUS_CONTAINER)
+ // When ANNOTATE_CONTIGUOUS_CONTAINER is defined, inline capacity is ignored.
+ EXPECT_EQ(driver.GetHeapCompactLastFixupCount(), 1u);
+#else
+ EXPECT_EQ(driver.GetHeapCompactLastFixupCount(), 2u);
+#endif
+}
+
+TEST(IncrementalMarkingTest, WeakHashMapHeapCompaction) {
+ using Store = HeapHashCountedSet<WeakMember<Object>>;
+
+ Persistent<Store> persistent(new Store());
+
+ IncrementalMarkingTestDriver driver(ThreadState::Current());
+ HeapCompact::ScheduleCompactionGCForTesting(true);
+ driver.Start();
+ driver.FinishSteps();
+ persistent->insert(Object::Create());
+ driver.FinishGC();
+
+ // Weak caallback should register the slot.
+ EXPECT_EQ(driver.GetHeapCompactLastFixupCount(), 1u);
+}
+
+namespace {
+
+class ObjectWithWeakMember : public GarbageCollected<ObjectWithWeakMember> {
+ public:
+ ObjectWithWeakMember() = default;
+
+ void set_object(Object* object) { object_ = object; }
+
+ void Trace(Visitor* visitor) { visitor->Trace(object_); }
+
+ private:
+ WeakMember<Object> object_ = nullptr;
+};
+
+} // namespace
+
+TEST(IncrementalMarkingTest, WeakMember) {
+ // Regression test: https://crbug.com/913431
+
+ Persistent<ObjectWithWeakMember> persistent(
+ MakeGarbageCollected<ObjectWithWeakMember>());
+ IncrementalMarkingTestDriver driver(ThreadState::Current());
+ driver.Start();
+ driver.FinishSteps();
+ persistent->set_object(Object::Create());
+ driver.FinishGC();
+ ConservativelyCollectGarbage();
+}
+
+TEST(IncrementalMarkingTest, MemberSwap) {
+ // Regression test: https://crbug.com/913431
+ //
+ // MemberBase::Swap may be used to swap in a not-yet-processed member into an
+ // already-processed member. This leads to a stale pointer that is not marked.
+
+ Persistent<Object> object1(MakeGarbageCollected<Object>());
+ IncrementalMarkingTestDriver driver(ThreadState::Current());
+ driver.Start();
+ // The repro leverages the fact that initializing stores do not emit a barrier
+ // (because they are still reachable from stack) to simulate the problematic
+ // interleaving.
+ driver.FinishSteps();
+ Object* object2 =
+ MakeGarbageCollected<Object>(MakeGarbageCollected<Object>());
+ object2->next_ref().Swap(object1->next_ref());
driver.FinishGC();
+ ConservativelyCollectGarbage();
}
} // namespace incremental_marking_test
diff --git a/chromium/third_party/blink/renderer/platform/heap/marking_verifier.h b/chromium/third_party/blink/renderer/platform/heap/marking_verifier.h
index 33f084dcf68..2075952a36b 100644
--- a/chromium/third_party/blink/renderer/platform/heap/marking_verifier.h
+++ b/chromium/third_party/blink/renderer/platform/heap/marking_verifier.h
@@ -63,11 +63,18 @@ class MarkingVerifier final : public Visitor {
private:
void VerifyChild(void* base_object_payload) {
+ // The following check ensures that an object is currently not under
+ // construction. All verifier runs are assumed to be run outside of mixin
+ // construction. Consequently, the following cases can lead to a failing
+ // check:
+ // 1. The garbage collector ignoring no-GC scopes for mixin construction.
+ // 2. Missing macro USING_GARBAGE_COLLECTED_MIXIN for users of
+ // GarbageCollectedMixin.
CHECK(base_object_payload);
HeapObjectHeader* child_header =
HeapObjectHeader::FromPayload(base_object_payload);
- // This CHECKs ensure that any children reachable from marked parents are
- // also marked. If you hit these CHECKs then marking is in an inconsistent
+ // These checks ensure that any children reachable from marked parents are
+ // also marked. If you hit these checks then marking is in an inconsistent
// state meaning that there are unmarked objects reachable from marked
// ones.
CHECK(child_header);
diff --git a/chromium/third_party/blink/renderer/platform/heap/marking_visitor.h b/chromium/third_party/blink/renderer/platform/heap/marking_visitor.h
index 8a8d1e58169..8892d9cc23b 100644
--- a/chromium/third_party/blink/renderer/platform/heap/marking_visitor.h
+++ b/chromium/third_party/blink/renderer/platform/heap/marking_visitor.h
@@ -135,6 +135,9 @@ class PLATFORM_EXPORT MarkingVisitor : public Visitor {
TraceDescriptor desc,
WeakCallback callback,
void* parameter) final {
+ RegisterBackingStoreReference(object_slot);
+ if (!object)
+ return;
RegisterWeakCallback(parameter, callback);
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/member.h b/chromium/third_party/blink/renderer/platform/heap/member.h
index 5f971273aba..acca8c067e3 100644
--- a/chromium/third_party/blink/renderer/platform/heap/member.h
+++ b/chromium/third_party/blink/renderer/platform/heap/member.h
@@ -33,6 +33,70 @@ enum class TracenessMemberConfiguration {
template <typename T,
TracenessMemberConfiguration tracenessConfiguration =
TracenessMemberConfiguration::kTraced>
+class MemberPointerVerifier {
+ public:
+ MemberPointerVerifier() = default;
+
+ void SaveCreationThreadState(T* pointer) {
+ if (tracenessConfiguration == TracenessMemberConfiguration::kUntraced) {
+ creation_thread_state_ = nullptr;
+ } else {
+ creation_thread_state_ = ThreadState::Current();
+ // Members should be created in an attached thread. But an empty
+ // value Member may be created on an unattached thread by a heap
+ // collection iterator.
+ DCHECK(creation_thread_state_ || !pointer);
+ }
+ }
+ void CheckPointer(T* pointer) {
+ if (!pointer)
+ return;
+ // HashTable can store a special value (which is not aligned to the
+ // allocation granularity) to Member<> to represent a deleted entry.
+ // Thus we treat a pointer that is not aligned to the granularity
+ // as a valid pointer.
+ if (reinterpret_cast<intptr_t>(pointer) % kAllocationGranularity)
+ return;
+
+ if (tracenessConfiguration != TracenessMemberConfiguration::kUntraced) {
+ ThreadState* current = ThreadState::Current();
+ DCHECK(current);
+ // m_creationThreadState may be null when this is used in a heap
+ // collection which initialized the Member with memset and the
+ // constructor wasn't called.
+ if (creation_thread_state_) {
+ // Member should point to objects that belong in the same ThreadHeap.
+ DCHECK(creation_thread_state_->IsOnThreadHeap(pointer));
+ // Member should point to objects that belong in the same ThreadHeap.
+ DCHECK_EQ(&current->Heap(), &creation_thread_state_->Heap());
+ } else {
+ DCHECK(current->IsOnThreadHeap(pointer));
+ }
+ }
+
+#if defined(ADDRESS_SANITIZER)
+ // TODO(haraken): What we really want to check here is that the pointer
+ // is a traceable object. In other words, the pointer is either of:
+ //
+ // (a) a pointer to the head of an on-heap object.
+ // (b) a pointer to the head of an on-heap mixin object.
+ //
+ // We can check it by calling ThreadHeap::isHeapObjectAlive(pointer),
+ // but we cannot call it here because it requires to include T.h.
+ // So we currently only try to implement the check for (a), but do
+ // not insist that T's definition is in scope.
+ if (IsFullyDefined<T>::value && !IsGarbageCollectedMixin<T>::value)
+ HeapObjectHeader::CheckFromPayload(pointer);
+#endif // ADDRESS_SANITIZER
+ }
+
+ private:
+ const ThreadState* creation_thread_state_;
+};
+
+template <typename T,
+ TracenessMemberConfiguration tracenessConfiguration =
+ TracenessMemberConfiguration::kTraced>
class MemberBase {
DISALLOW_NEW();
@@ -41,59 +105,55 @@ class MemberBase {
MemberBase(std::nullptr_t) : raw_(nullptr) { SaveCreationThreadState(); }
- MemberBase(T* raw) : raw_(raw) {
+ explicit MemberBase(T* raw) : raw_(raw) {
SaveCreationThreadState();
CheckPointer();
+ // No write barrier for initializing stores.
}
explicit MemberBase(T& raw) : raw_(&raw) {
SaveCreationThreadState();
CheckPointer();
+ // No write barrier for initializing stores.
}
- MemberBase(WTF::HashTableDeletedValueType) : raw_(reinterpret_cast<T*>(-1)) {
+ MemberBase(WTF::HashTableDeletedValueType)
+ : raw_(reinterpret_cast<T*>(kHashTableDeletedRawValue)) {
SaveCreationThreadState();
}
- bool IsHashTableDeletedValue() const {
- return raw_ == reinterpret_cast<T*>(-1);
- }
-
- MemberBase(const MemberBase& other) : raw_(other) {
+ MemberBase(const MemberBase& other) : raw_(other.raw_) {
SaveCreationThreadState();
CheckPointer();
+ WriteBarrier();
}
template <typename U>
- MemberBase(const Persistent<U>& other) {
+ MemberBase(const Persistent<U>& other) : raw_(other) {
SaveCreationThreadState();
- raw_ = other;
CheckPointer();
+ WriteBarrier();
}
template <typename U>
MemberBase(const MemberBase<U>& other) : raw_(other) {
SaveCreationThreadState();
CheckPointer();
+ WriteBarrier();
}
- T* Release() {
- T* result = raw_;
- raw_ = nullptr;
- return result;
- }
-
- explicit operator bool() const { return raw_; }
-
- operator T*() const { return raw_; }
-
- T* operator->() const { return raw_; }
- T& operator*() const { return *raw_; }
-
template <typename U>
MemberBase& operator=(const Persistent<U>& other) {
raw_ = other;
CheckPointer();
+ WriteBarrier();
+ return *this;
+ }
+
+ MemberBase& operator=(const MemberBase& other) {
+ raw_ = other;
+ CheckPointer();
+ WriteBarrier();
return *this;
}
@@ -101,6 +161,7 @@ class MemberBase {
MemberBase& operator=(const MemberBase<U>& other) {
raw_ = other;
CheckPointer();
+ WriteBarrier();
return *this;
}
@@ -108,6 +169,7 @@ class MemberBase {
MemberBase& operator=(U* other) {
raw_ = other;
CheckPointer();
+ WriteBarrier();
return *this;
}
@@ -124,75 +186,55 @@ class MemberBase {
void Swap(MemberBase<T>& other) {
std::swap(raw_, other.raw_);
CheckPointer();
+ WriteBarrier();
+ other.WriteBarrier();
}
+ explicit operator bool() const { return raw_; }
+ operator T*() const { return raw_; }
+ T* operator->() const { return raw_; }
+ T& operator*() const { return *raw_; }
+
T* Get() const { return raw_; }
void Clear() { raw_ = nullptr; }
+ T* Release() {
+ T* result = raw_;
+ raw_ = nullptr;
+ return result;
+ }
+
+ bool IsHashTableDeletedValue() const {
+ return raw_ == reinterpret_cast<T*>(kHashTableDeletedRawValue);
+ }
+
protected:
- void CheckPointer() {
-#if DCHECK_IS_ON()
- if (!raw_)
- return;
- // HashTable can store a special value (which is not aligned to the
- // allocation granularity) to Member<> to represent a deleted entry.
- // Thus we treat a pointer that is not aligned to the granularity
- // as a valid pointer.
- if (reinterpret_cast<intptr_t>(raw_) % kAllocationGranularity)
- return;
+ static constexpr intptr_t kHashTableDeletedRawValue = -1;
- if (tracenessConfiguration != TracenessMemberConfiguration::kUntraced) {
- ThreadState* current = ThreadState::Current();
- DCHECK(current);
- // m_creationThreadState may be null when this is used in a heap
- // collection which initialized the Member with memset and the
- // constructor wasn't called.
- if (creation_thread_state_) {
- // Member should point to objects that belong in the same ThreadHeap.
- DCHECK(creation_thread_state_->IsOnThreadHeap(raw_));
- // Member should point to objects that belong in the same ThreadHeap.
- DCHECK_EQ(&current->Heap(), &creation_thread_state_->Heap());
- } else {
- DCHECK(current->IsOnThreadHeap(raw_));
- }
- }
+ ALWAYS_INLINE void WriteBarrier() const {
+#if BUILDFLAG(BLINK_HEAP_INCREMENTAL_MARKING)
+ MarkingVisitor::WriteBarrier(
+ const_cast<typename std::remove_const<T>::type*>(this->raw_));
+#endif // BUILDFLAG(BLINK_HEAP_INCREMENTAL_MARKING)
+ }
-#if defined(ADDRESS_SANITIZER)
- // TODO(haraken): What we really want to check here is that the pointer
- // is a traceable object. In other words, the pointer is either of:
- //
- // (a) a pointer to the head of an on-heap object.
- // (b) a pointer to the head of an on-heap mixin object.
- //
- // We can check it by calling ThreadHeap::isHeapObjectAlive(raw_),
- // but we cannot call it here because it requires to include T.h.
- // So we currently only try to implement the check for (a), but do
- // not insist that T's definition is in scope.
- if (IsFullyDefined<T>::value && !IsGarbageCollectedMixin<T>::value)
- HeapObjectHeader::CheckFromPayload(raw_);
-#endif
-#endif
+ void CheckPointer() {
+#if DCHECK_IS_ON()
+ pointer_verifier_.CheckPointer(raw_);
+#endif // DCHECK_IS_ON()
}
void SaveCreationThreadState() {
#if DCHECK_IS_ON()
- if (tracenessConfiguration == TracenessMemberConfiguration::kUntraced) {
- creation_thread_state_ = nullptr;
- } else {
- creation_thread_state_ = ThreadState::Current();
- // Members should be created in an attached thread. But an empty
- // value Member may be created on an unattached thread by a heap
- // collection iterator.
- DCHECK(creation_thread_state_ || !raw_);
- }
-#endif
+ pointer_verifier_.SaveCreationThreadState(raw_);
+#endif // DCHECK_IS_ON()
}
T* raw_;
#if DCHECK_IS_ON()
- const ThreadState* creation_thread_state_;
-#endif
+ MemberPointerVerifier<T, tracenessConfiguration> pointer_verifier_;
+#endif // DCHECK_IS_ON()
};
// Members are used in classes to contain strong pointers to other oilpan heap
@@ -208,55 +250,45 @@ class Member : public MemberBase<T, TracenessMemberConfiguration::kTraced> {
public:
Member() : Parent() {}
Member(std::nullptr_t) : Parent(nullptr) {}
- Member(T* raw) : Parent(raw) {
- // No write barrier for initializing stores.
- }
- Member(T& raw) : Parent(raw) {
- // No write barrier for initializing stores.
- }
+ Member(T* raw) : Parent(raw) {}
+ Member(T& raw) : Parent(raw) {}
Member(WTF::HashTableDeletedValueType x) : Parent(x) {}
- Member(const Member& other) : Parent(other) { WriteBarrier(); }
+ Member(const Member& other) : Parent(other) {}
+
template <typename U>
Member(const Member<U>& other) : Parent(other) {
- WriteBarrier();
}
+
template <typename U>
- Member(const Persistent<U>& other) : Parent(other) {
- WriteBarrier();
- }
+ Member(const Persistent<U>& other) : Parent(other) {}
template <typename U>
Member& operator=(const Persistent<U>& other) {
Parent::operator=(other);
- WriteBarrier();
return *this;
}
Member& operator=(const Member& other) {
Parent::operator=(other);
- WriteBarrier();
return *this;
}
template <typename U>
Member& operator=(const Member<U>& other) {
Parent::operator=(other);
- WriteBarrier();
return *this;
}
template <typename U>
Member& operator=(const WeakMember<U>& other) {
Parent::operator=(other);
- WriteBarrier();
return *this;
}
template <typename U>
Member& operator=(U* other) {
Parent::operator=(other);
- WriteBarrier();
return *this;
}
@@ -271,13 +303,6 @@ class Member : public MemberBase<T, TracenessMemberConfiguration::kTraced> {
}
protected:
- ALWAYS_INLINE void WriteBarrier() const {
-#if BUILDFLAG(BLINK_HEAP_INCREMENTAL_MARKING)
- MarkingVisitor::WriteBarrier(
- const_cast<typename std::remove_const<T>::type*>(this->raw_));
-#endif // BUILDFLAG(BLINK_HEAP_INCREMENTAL_MARKING)
- }
-
template <typename P, typename Traits, typename Allocator>
friend class WTF::ConstructTraits;
};
@@ -365,40 +390,14 @@ class SameThreadCheckedMember : public Member<T> {
}
private:
- void CheckPointer() {
- if (!this->raw_)
- return;
- // HashTable can store a special value (which is not aligned to the
- // allocation granularity) to Member<> to represent a deleted entry.
- // Thus we treat a pointer that is not aligned to the granularity
- // as a valid pointer.
- if (reinterpret_cast<intptr_t>(this->raw_) % kAllocationGranularity)
- return;
-
- ThreadState* current = ThreadState::Current();
- DCHECK(current);
- // m_creationThreadState may be null when this is used in a heap
- // collection which initialized the Member with memset and the
- // constructor wasn't called.
- if (creation_thread_state_) {
- // Member should point to objects that belong in the same ThreadHeap.
- CHECK(creation_thread_state_->IsOnThreadHeap(this->raw_));
- // Member should point to objects that belong in the same ThreadHeap.
- CHECK_EQ(&current->Heap(), &creation_thread_state_->Heap());
- } else {
- CHECK(current->IsOnThreadHeap(this->raw_));
- }
- }
+ void CheckPointer() { pointer_verifier_.CheckPointer(this->raw_); }
void SaveCreationThreadState() {
- creation_thread_state_ = ThreadState::Current();
- // All Members should be created in an attached thread, but an empty
- // value Member may be created on an unattached thread by a heap
- // collection iterator.
- CHECK(this->creation_thread_state_ || !this->raw_);
+ pointer_verifier_.SaveCreationThreadState(this->raw_);
}
- const ThreadState* creation_thread_state_;
+ MemberPointerVerifier<T, TracenessMemberConfiguration::kTraced>
+ pointer_verifier_;
};
// WeakMember is similar to Member in that it is used to point to other oilpan
@@ -429,22 +428,19 @@ class WeakMember : public MemberBase<T, TracenessMemberConfiguration::kTraced> {
template <typename U>
WeakMember& operator=(const Persistent<U>& other) {
- this->raw_ = other;
- this->CheckPointer();
+ Parent::operator=(other);
return *this;
}
template <typename U>
WeakMember& operator=(const Member<U>& other) {
- this->raw_ = other;
- this->CheckPointer();
+ Parent::operator=(other);
return *this;
}
template <typename U>
WeakMember& operator=(U* other) {
- this->raw_ = other;
- this->CheckPointer();
+ Parent::operator=(other);
return *this;
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/page_memory.cc b/chromium/third_party/blink/renderer/platform/heap/page_memory.cc
index 3f6a7180f5a..2a4d3f2117d 100644
--- a/chromium/third_party/blink/renderer/platform/heap/page_memory.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/page_memory.cc
@@ -19,13 +19,13 @@ void MemoryRegion::Release() {
bool MemoryRegion::Commit() {
CHECK(base::RecommitSystemPages(base_, size_, base::PageReadWrite));
- return base::SetSystemPagesAccess(base_, size_, base::PageReadWrite);
+ return base::TrySetSystemPagesAccess(base_, size_, base::PageReadWrite);
}
void MemoryRegion::Decommit() {
ASAN_UNPOISON_MEMORY_REGION(base_, size_);
base::DecommitSystemPages(base_, size_);
- CHECK(base::SetSystemPagesAccess(base_, size_, base::PageInaccessible));
+ base::SetSystemPagesAccess(base_, size_, base::PageInaccessible);
}
PageMemoryRegion::PageMemoryRegion(Address base,
diff --git a/chromium/third_party/blink/renderer/platform/heap/persistent.h b/chromium/third_party/blink/renderer/platform/heap/persistent.h
index e8bf8c4a93e..52dc689d86f 100644
--- a/chromium/third_party/blink/renderer/platform/heap/persistent.h
+++ b/chromium/third_party/blink/renderer/platform/heap/persistent.h
@@ -197,13 +197,6 @@ class PersistentBase {
region.FreePersistentNode(persistent_node_);
}
- protected:
- NO_SANITIZE_ADDRESS
- T* AtomicGet() {
- return reinterpret_cast<T*>(AcquireLoad(reinterpret_cast<void* volatile*>(
- const_cast<typename std::remove_const<T>::type**>(&raw_))));
- }
-
private:
NO_SANITIZE_ADDRESS
void Assign(T* ptr) {
@@ -511,8 +504,6 @@ class CrossThreadPersistent
CrossThreadPersistent(const Member<U>& other) : Parent(other) {}
CrossThreadPersistent(WTF::HashTableDeletedValueType x) : Parent(x) {}
- T* AtomicGet() { return Parent::AtomicGet(); }
-
// Instead of using release(), assign then clear() instead.
// Using release() with per thread heap enabled can cause the object to be
// destroyed before assigning it to a new handle.
diff --git a/chromium/third_party/blink/renderer/platform/heap/persistent_node.cc b/chromium/third_party/blink/renderer/platform/heap/persistent_node.cc
index 2ebb0726057..ce00cc36e00 100644
--- a/chromium/third_party/blink/renderer/platform/heap/persistent_node.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/persistent_node.cc
@@ -182,7 +182,7 @@ void CrossThreadPersistentRegion::PrepareForThreadStateTermination(
reinterpret_cast<CrossThreadPersistent<DummyGCBase>*>(
slots->slot_[i].Self());
DCHECK(persistent);
- void* raw_object = persistent->AtomicGet();
+ void* raw_object = persistent->Get();
if (!raw_object)
continue;
BasePage* page = PageFromObject(raw_object);
diff --git a/chromium/third_party/blink/renderer/platform/heap/persistent_node.h b/chromium/third_party/blink/renderer/platform/heap/persistent_node.h
index 1401441a8fa..596ce270b33 100644
--- a/chromium/third_party/blink/renderer/platform/heap/persistent_node.h
+++ b/chromium/third_party/blink/renderer/platform/heap/persistent_node.h
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/atomics.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/heap/process_heap.cc b/chromium/third_party/blink/renderer/platform/heap/process_heap.cc
index 26afa8bd483..023b2033a3b 100644
--- a/chromium/third_party/blink/renderer/platform/heap/process_heap.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/process_heap.cc
@@ -61,8 +61,8 @@ Mutex& ProcessHeap::CrossThreadPersistentMutex() {
return mutex;
}
-size_t ProcessHeap::total_allocated_space_ = 0;
-size_t ProcessHeap::total_allocated_object_size_ = 0;
-size_t ProcessHeap::total_marked_object_size_ = 0;
+std::atomic_size_t ProcessHeap::total_allocated_space_{0};
+std::atomic_size_t ProcessHeap::total_allocated_object_size_{0};
+std::atomic_size_t ProcessHeap::total_marked_object_size_{0};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/heap/process_heap.h b/chromium/third_party/blink/renderer/platform/heap/process_heap.h
index f119f058d23..ec3db19496b 100644
--- a/chromium/third_party/blink/renderer/platform/heap/process_heap.h
+++ b/chromium/third_party/blink/renderer/platform/heap/process_heap.h
@@ -5,9 +5,9 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_PROCESS_HEAP_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_PROCESS_HEAP_H_
+#include <atomic>
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
namespace blink {
@@ -35,38 +35,38 @@ class PLATFORM_EXPORT ProcessHeap {
static Mutex& CrossThreadPersistentMutex();
static void IncreaseTotalAllocatedObjectSize(size_t delta) {
- AtomicAdd(&total_allocated_object_size_, static_cast<long>(delta));
+ total_allocated_object_size_.fetch_add(delta, std::memory_order_relaxed);
}
static void DecreaseTotalAllocatedObjectSize(size_t delta) {
- AtomicSubtract(&total_allocated_object_size_, static_cast<long>(delta));
+ total_allocated_object_size_.fetch_sub(delta, std::memory_order_relaxed);
}
static size_t TotalAllocatedObjectSize() {
- return AcquireLoad(&total_allocated_object_size_);
+ return total_allocated_object_size_.load(std::memory_order_relaxed);
}
static void IncreaseTotalMarkedObjectSize(size_t delta) {
- AtomicAdd(&total_marked_object_size_, static_cast<long>(delta));
+ total_marked_object_size_.fetch_add(delta, std::memory_order_relaxed);
}
static void DecreaseTotalMarkedObjectSize(size_t delta) {
- AtomicSubtract(&total_marked_object_size_, static_cast<long>(delta));
+ total_marked_object_size_.fetch_sub(delta, std::memory_order_relaxed);
}
static size_t TotalMarkedObjectSize() {
- return AcquireLoad(&total_marked_object_size_);
+ return total_marked_object_size_.load(std::memory_order_relaxed);
}
static void IncreaseTotalAllocatedSpace(size_t delta) {
- AtomicAdd(&total_allocated_space_, static_cast<long>(delta));
+ total_allocated_space_.fetch_add(delta, std::memory_order_relaxed);
}
static void DecreaseTotalAllocatedSpace(size_t delta) {
- AtomicSubtract(&total_allocated_space_, static_cast<long>(delta));
+ total_allocated_space_.fetch_sub(delta, std::memory_order_relaxed);
}
static size_t TotalAllocatedSpace() {
- return AcquireLoad(&total_allocated_space_);
+ return total_allocated_space_.load(std::memory_order_relaxed);
}
static void ResetHeapCounters();
private:
- static size_t total_allocated_space_;
- static size_t total_allocated_object_size_;
- static size_t total_marked_object_size_;
+ static std::atomic_size_t total_allocated_space_;
+ static std::atomic_size_t total_allocated_object_size_;
+ static std::atomic_size_t total_marked_object_size_;
friend class ThreadState;
};
diff --git a/chromium/third_party/blink/renderer/platform/heap/sparse_heap_bitmap.h b/chromium/third_party/blink/renderer/platform/heap/sparse_heap_bitmap.h
index f0614a9854d..70654e74e4e 100644
--- a/chromium/third_party/blink/renderer/platform/heap/sparse_heap_bitmap.h
+++ b/chromium/third_party/blink/renderer/platform/heap/sparse_heap_bitmap.h
@@ -11,7 +11,6 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/platform/heap/blink_gc.h"
#include "third_party/blink/renderer/platform/heap/heap_page.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
namespace blink {
@@ -64,7 +63,7 @@ class PLATFORM_EXPORT SparseHeapBitmap {
// The assumed minimum alignment of the pointers being added. Cannot
// exceed |log2(allocationGranularity)|; having it be equal to
// the platform pointer alignment is what's wanted.
- static const int kPointerAlignmentInBits = WTF_ALIGN_OF(void*) == 8 ? 3 : 2;
+ static const int kPointerAlignmentInBits = alignof(void*) == 8 ? 3 : 2;
static const size_t kPointerAlignmentMask =
(0x1u << kPointerAlignmentInBits) - 1;
@@ -87,7 +86,7 @@ class PLATFORM_EXPORT SparseHeapBitmap {
static_assert(kPointerAlignmentMask <= kAllocationMask,
"address shift exceeds heap pointer alignment");
// For now, only recognize 8 and 4.
- static_assert(WTF_ALIGN_OF(void*) == 8 || WTF_ALIGN_OF(void*) == 4,
+ static_assert(alignof(void*) == 8 || alignof(void*) == 4,
"unsupported pointer alignment");
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/thread_state.cc b/chromium/third_party/blink/renderer/platform/heap/thread_state.cc
index 6d88de3a79b..198af3f0761 100644
--- a/chromium/third_party/blink/renderer/platform/heap/thread_state.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/thread_state.cc
@@ -171,12 +171,6 @@ ThreadState::ThreadState()
weak_persistent_region_(std::make_unique<PersistentRegion>()),
start_of_stack_(reinterpret_cast<intptr_t*>(WTF::GetStackStart())),
end_of_stack_(reinterpret_cast<intptr_t*>(WTF::GetStackStart())),
-#if HAS_FEATURE(safe_stack)
- start_of_unsafe_stack_(
- reinterpret_cast<intptr_t*>(__builtin___get_unsafe_stack_top())),
- end_of_unsafe_stack_(
- reinterpret_cast<intptr_t*>(__builtin___get_unsafe_stack_bottom())),
-#endif
sweep_forbidden_(false),
no_allocation_count_(0),
gc_forbidden_count_(0),
@@ -221,15 +215,7 @@ void ThreadState::AttachMainThread() {
thread_specific_ = new WTF::ThreadSpecific<ThreadState*>();
new (main_thread_state_storage_) ThreadState();
- // PpapiThread doesn't set the current thread.
- Thread* current_thread = Platform::Current()->CurrentThread();
- if (current_thread) {
- ThreadScheduler* scheduler = current_thread->Scheduler();
- // Some binaries do not have a scheduler (e.g.
- // v8_context_snapshot_generator)
- if (scheduler)
- scheduler->AddRAILModeObserver(MainThreadState());
- }
+ ThreadScheduler::Current()->AddRAILModeObserver(MainThreadState());
}
void ThreadState::AttachCurrentThread() {
@@ -355,19 +341,6 @@ void ThreadState::VisitStack(MarkingVisitor* visitor) {
heap_->CheckAndMarkPointer(visitor, ptr);
VisitAsanFakeStackForPointer(visitor, ptr);
}
-
-#if HAS_FEATURE(safe_stack)
- start = reinterpret_cast<Address*>(start_of_unsafe_stack_);
- end = reinterpret_cast<Address*>(end_of_unsafe_stack_);
- current = end;
-
- for (; current < start; ++current) {
- Address ptr = *current;
- // SafeStack And MSan are not compatible
- heap_->CheckAndMarkPointer(visitor, ptr);
- VisitAsanFakeStackForPointer(visitor, ptr);
- }
-#endif
}
void ThreadState::VisitDOMWrappers(Visitor* visitor) {
@@ -639,6 +612,16 @@ void ThreadState::ScheduleGCIfNeeded() {
if (IsGCForbidden() || SweepForbidden())
return;
+ // This method should not call out to V8 during unified heap garbage
+ // collections. Specifically, reporting memory to V8 may trigger a marking
+ // step which is not allowed during construction of an object. The reason is
+ // that a parent object's constructor is potentially being invoked which may
+ // have already published the object. In that case the object may be colored
+ // black in a v8 marking step which invalidates the assumption that write
+ // barriers may be avoided when constructing an object as it is white.
+ if (IsUnifiedGCMarkingInProgress())
+ return;
+
ReportMemoryToV8();
if (ShouldForceMemoryPressureGC()) {
@@ -693,7 +676,6 @@ ThreadState* ThreadState::FromObject(const void* object) {
void ThreadState::PerformIdleGC(TimeTicks deadline) {
DCHECK(CheckThread());
- DCHECK(Platform::Current()->CurrentThread()->Scheduler());
if (GetGCState() != kIdleGCScheduled)
return;
@@ -707,10 +689,7 @@ void ThreadState::PerformIdleGC(TimeTicks deadline) {
TimeDelta estimated_marking_time =
heap_->stats_collector()->estimated_marking_time();
if ((deadline - CurrentTimeTicks()) <= estimated_marking_time &&
- !Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->CanExceedIdleDeadlineIfRequired()) {
+ !ThreadScheduler::Current()->CanExceedIdleDeadlineIfRequired()) {
// If marking is estimated to take longer than the deadline and we can't
// exceed the deadline, then reschedule for the next idle period.
RescheduleIdleGC();
@@ -773,18 +752,13 @@ void ThreadState::ScheduleIncrementalMarkingFinalize() {
}
void ThreadState::ScheduleIdleGC() {
- // Some threads (e.g. PPAPI thread) don't have a scheduler.
- // Also some tests can call Platform::SetCurrentPlatformForTesting() at any
- // time, so we need to check if it exists.
- if (!Platform::Current()->CurrentThread()->Scheduler())
- return;
// Idle GC has the lowest priority so do not schedule if a GC is already
// scheduled or if marking is in progress.
if (GetGCState() != kNoGCScheduled)
return;
CompleteSweep();
SetGCState(kIdleGCScheduled);
- Platform::Current()->CurrentThread()->Scheduler()->PostNonNestableIdleTask(
+ ThreadScheduler::Current()->PostNonNestableIdleTask(
FROM_HERE, WTF::Bind(&ThreadState::PerformIdleGC, WTF::Unretained(this)));
}
@@ -795,11 +769,7 @@ void ThreadState::RescheduleIdleGC() {
}
void ThreadState::ScheduleIdleLazySweep() {
- // Some threads (e.g. PPAPI thread) don't have a scheduler.
- if (!Platform::Current()->CurrentThread()->Scheduler())
- return;
-
- Platform::Current()->CurrentThread()->Scheduler()->PostIdleTask(
+ ThreadScheduler::Current()->PostIdleTask(
FROM_HERE,
WTF::Bind(&ThreadState::PerformIdleLazySweep, WTF::Unretained(this)));
}
@@ -834,6 +804,7 @@ void UnexpectedGCState(ThreadState::GCState gc_state) {
UNEXPECTED_GCSTATE(kIdleGCScheduled);
UNEXPECTED_GCSTATE(kPreciseGCScheduled);
UNEXPECTED_GCSTATE(kFullGCScheduled);
+ UNEXPECTED_GCSTATE(kIncrementalMarkingStepPaused);
UNEXPECTED_GCSTATE(kIncrementalMarkingStepScheduled);
UNEXPECTED_GCSTATE(kIncrementalMarkingFinalizeScheduled);
UNEXPECTED_GCSTATE(kPageNavigationGCScheduled);
@@ -857,6 +828,7 @@ void ThreadState::SetGCState(GCState gc_state) {
gc_state_ == kNoGCScheduled || gc_state_ == kIdleGCScheduled ||
gc_state_ == kPreciseGCScheduled || gc_state_ == kFullGCScheduled ||
gc_state_ == kPageNavigationGCScheduled ||
+ gc_state_ == kIncrementalMarkingStepPaused ||
gc_state_ == kIncrementalMarkingStepScheduled ||
gc_state_ == kIncrementalMarkingFinalizeScheduled ||
gc_state_ == kIncrementalGCScheduled);
@@ -879,6 +851,7 @@ void ThreadState::SetGCState(GCState gc_state) {
DCHECK(!IsSweepingInProgress());
VERIFY_STATE_TRANSITION(
gc_state_ == kNoGCScheduled || gc_state_ == kIdleGCScheduled ||
+ gc_state_ == kIncrementalMarkingStepPaused ||
gc_state_ == kIncrementalMarkingStepScheduled ||
gc_state_ == kIncrementalMarkingFinalizeScheduled ||
gc_state_ == kPreciseGCScheduled || gc_state_ == kFullGCScheduled ||
@@ -898,6 +871,12 @@ void ThreadState::SetGCState(GCState gc_state) {
VERIFY_STATE_TRANSITION(gc_state_ == kNoGCScheduled ||
gc_state_ == kIdleGCScheduled);
break;
+ case kIncrementalMarkingStepPaused:
+ DCHECK(CheckThread());
+ DCHECK(IsMarkingInProgress());
+ DCHECK(!IsSweepingInProgress());
+ VERIFY_STATE_TRANSITION(gc_state_ == kIncrementalMarkingStepScheduled);
+ break;
default:
NOTREACHED();
}
@@ -1133,6 +1112,19 @@ void UpdateTraceCounters(const ThreadHeapStatsCollector& stats_collector) {
void UpdateHistograms(const ThreadHeapStatsCollector::Event& event) {
UMA_HISTOGRAM_ENUMERATION("BlinkGC.GCReason", event.reason);
+ // Blink GC cycle time.
+ const WTF::TimeDelta cycle_duration =
+ event.scope_data
+ [ThreadHeapStatsCollector::kIncrementalMarkingStartMarking] +
+ event.scope_data[ThreadHeapStatsCollector::kIncrementalMarkingStep] +
+ event.scope_data[ThreadHeapStatsCollector::kAtomicPhase] +
+ event.scope_data[ThreadHeapStatsCollector::kCompleteSweep] +
+ event.scope_data[ThreadHeapStatsCollector::kLazySweepInIdle] +
+ event.scope_data[ThreadHeapStatsCollector::kLazySweepOnAllocation];
+ UMA_HISTOGRAM_TIMES("BlinkGC.TimeForGCCycle", cycle_duration);
+
+ UMA_HISTOGRAM_TIMES("BlinkGC.TimeForNestedInV8", event.gc_nested_in_v8_);
+
// TODO(mlippautz): Update name of this histogram.
UMA_HISTOGRAM_TIMES(
"BlinkGC.CollectGarbage",
@@ -1298,10 +1290,6 @@ extern "C" void PushAllRegisters(void*, ThreadState*, PushAllRegistersCallback);
static void DidPushRegisters(void*, ThreadState* state, intptr_t* stack_end) {
state->RecordStackEnd(stack_end);
-#if HAS_FEATURE(safe_stack)
- state->RecordUnsafeStackEnd(
- reinterpret_cast<intptr_t*>(__builtin___get_unsafe_stack_ptr()));
-#endif
}
void ThreadState::PushRegistersAndVisitStack() {
@@ -1484,7 +1472,7 @@ void ThreadState::IncrementalMarkingStep() {
// further marking if new objects are discovered. Otherwise, just process
// the rest in the atomic pause.
DCHECK(IsUnifiedGCMarkingInProgress());
- SetGCState(kNoGCScheduled);
+ SetGCState(kIncrementalMarkingStepPaused);
} else {
ScheduleIncrementalMarkingFinalize();
}
diff --git a/chromium/third_party/blink/renderer/platform/heap/thread_state.h b/chromium/third_party/blink/renderer/platform/heap/thread_state.h
index c7b4b643946..d04c2b07051 100644
--- a/chromium/third_party/blink/renderer/platform/heap/thread_state.h
+++ b/chromium/third_party/blink/renderer/platform/heap/thread_state.h
@@ -147,6 +147,7 @@ class PLATFORM_EXPORT ThreadState final
enum GCState {
kNoGCScheduled,
kIdleGCScheduled,
+ kIncrementalMarkingStepPaused,
kIncrementalMarkingStepScheduled,
kIncrementalMarkingFinalizeScheduled,
kPreciseGCScheduled,
@@ -419,11 +420,6 @@ class PLATFORM_EXPORT ThreadState final
void SafePoint(BlinkGC::StackState);
void RecordStackEnd(intptr_t* end_of_stack) { end_of_stack_ = end_of_stack; }
-#if HAS_FEATURE(safe_stack)
- void RecordUnsafeStackEnd(intptr_t* end_of_unsafe_stack) {
- end_of_unsafe_stack_ = end_of_unsafe_stack;
- }
-#endif
void PushRegistersAndVisitStack();
@@ -699,11 +695,6 @@ class PLATFORM_EXPORT ThreadState final
intptr_t* start_of_stack_;
intptr_t* end_of_stack_;
-#if HAS_FEATURE(safe_stack)
- intptr_t* start_of_unsafe_stack_;
- intptr_t* end_of_unsafe_stack_;
-#endif
-
bool sweep_forbidden_;
size_t no_allocation_count_;
size_t gc_forbidden_count_;
diff --git a/chromium/third_party/blink/renderer/platform/heap/trace_traits.h b/chromium/third_party/blink/renderer/platform/heap/trace_traits.h
index fe9477409c6..5975759610a 100644
--- a/chromium/third_party/blink/renderer/platform/heap/trace_traits.h
+++ b/chromium/third_party/blink/renderer/platform/heap/trace_traits.h
@@ -30,8 +30,6 @@ class CrossThreadWeakPersistent;
template <typename T>
class HeapDoublyLinkedList;
template <typename T>
-class HeapTerminatedArray;
-template <typename T>
class Member;
template <typename T>
class TraceEagerlyTrait;
@@ -389,12 +387,6 @@ class TraceEagerlyTrait<CrossThreadWeakPersistent<T>> {
};
template <typename T>
-class TraceEagerlyTrait<HeapTerminatedArray<T>> {
- public:
- static const bool value = TraceEagerlyTrait<T>::value;
-};
-
-template <typename T>
class TraceEagerlyTrait<HeapDoublyLinkedList<T>> {
STATIC_ONLY(TraceEagerlyTrait);
diff --git a/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.cc b/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.cc
index d3a5611de7b..30cb2fe6b75 100644
--- a/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.cc
+++ b/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.cc
@@ -7,6 +7,8 @@
#include "third_party/blink/renderer/platform/bindings/active_script_wrappable_base.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h"
+#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/heap/heap_stats_collector.h"
#include "third_party/blink/renderer/platform/heap/marking_visitor.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
@@ -28,19 +30,29 @@ UnifiedHeapController::UnifiedHeapController(ThreadState* thread_state)
void UnifiedHeapController::TracePrologue() {
VLOG(2) << "UnifiedHeapController::TracePrologue";
+ ThreadHeapStatsCollector::BlinkGCInV8Scope nested_scope(
+ thread_state_->Heap().stats_collector());
// Be conservative here as a new garbage collection gets started right away.
thread_state_->FinishIncrementalMarkingIfRunning(
BlinkGC::kHeapPointersOnStack, BlinkGC::kIncrementalMarking,
BlinkGC::kLazySweeping, thread_state_->current_gc_data_.reason);
+
// Reset any previously scheduled garbage collections.
thread_state_->SetGCState(ThreadState::kNoGCScheduled);
// Start incremental marking with unified tracing.
thread_state_->IncrementalMarkingStart(BlinkGC::GCReason::kUnifiedHeapGC);
+
+ is_tracing_done_ = false;
}
void UnifiedHeapController::EnterFinalPause(EmbedderStackState stack_state) {
VLOG(2) << "UnifiedHeapController::EnterFinalPause";
+ ThreadHeapStatsCollector::BlinkGCInV8Scope nested_scope(
+ thread_state_->Heap().stats_collector());
+ ThreadHeapStatsCollector::Scope stats_scope(
+ thread_state_->Heap().stats_collector(),
+ ThreadHeapStatsCollector::kAtomicPhase);
// ActiveScriptWrappable may not have persistents keeping them alive but rely
// on explicit tracing to be kept alive.
@@ -59,11 +71,19 @@ void UnifiedHeapController::EnterFinalPause(EmbedderStackState stack_state) {
void UnifiedHeapController::TraceEpilogue() {
VLOG(2) << "UnifiedHeapController::TraceEpilogue";
- thread_state_->AtomicPauseMarkEpilogue(BlinkGC::kIncrementalMarking);
- thread_state_->LeaveAtomicPause();
- thread_state_->LeaveGCForbiddenScope();
- thread_state_->AtomicPauseSweepAndCompact(BlinkGC::kIncrementalMarking,
- BlinkGC::kLazySweeping);
+ {
+ ThreadHeapStatsCollector::BlinkGCInV8Scope nested_scope(
+ thread_state_->Heap().stats_collector());
+ ThreadHeapStatsCollector::Scope stats_scope(
+ thread_state_->Heap().stats_collector(),
+ ThreadHeapStatsCollector::kAtomicPhase);
+ thread_state_->AtomicPauseMarkEpilogue(BlinkGC::kIncrementalMarking);
+ thread_state_->LeaveAtomicPause();
+ thread_state_->LeaveGCForbiddenScope();
+ thread_state_->AtomicPauseSweepAndCompact(BlinkGC::kIncrementalMarking,
+ BlinkGC::kLazySweeping);
+ }
+
if (!thread_state_->IsSweepingInProgress()) {
// Sweeping was finished during the atomic pause. Update statistics needs to
// run outside of the top-most stats scope.
@@ -75,7 +95,6 @@ void UnifiedHeapController::RegisterV8References(
const std::vector<std::pair<void*, void*>>&
internal_fields_of_potential_wrappers) {
VLOG(2) << "UnifiedHeapController::RegisterV8References";
-
DCHECK(thread_state()->IsMarkingInProgress());
const bool was_in_atomic_pause = thread_state()->in_atomic_pause();
@@ -87,6 +106,7 @@ void UnifiedHeapController::RegisterV8References(
if (wrapper_type_info->gin_embedder != gin::GinEmbedder::kEmbedderBlink) {
continue;
}
+ is_tracing_done_ = false;
wrapper_type_info->Trace(thread_state_->CurrentVisitor(),
internal_fields.second);
}
@@ -99,22 +119,20 @@ bool UnifiedHeapController::AdvanceTracing(double deadline_in_ms) {
if (!thread_state_->in_atomic_pause()) {
// V8 calls into embedder tracing from its own marking to ensure
- // progress.Oilpan will additionally schedule marking steps.
+ // progress. Oilpan will additionally schedule marking steps.
ThreadState::AtomicPauseScope atomic_pause_scope(thread_state_);
TimeTicks deadline =
TimeTicks() + TimeDelta::FromMillisecondsD(deadline_in_ms);
- return thread_state_->MarkPhaseAdvanceMarking(deadline);
+ is_tracing_done_ = thread_state_->MarkPhaseAdvanceMarking(deadline);
+ return is_tracing_done_;
}
thread_state_->AtomicPauseMarkTransitiveClosure();
+ is_tracing_done_ = true;
return true;
}
-void UnifiedHeapController::AbortTracing() {
- VLOG(2) << "UnifiedHeapController::AbortTracing";
-
- // TODO(mlippautz): Only needed when V8 aborts incremental marking which
- // should be rare in non-production code.
- LOG(FATAL) << "Not yet implemented";
+bool UnifiedHeapController::IsTracingDone() {
+ return is_tracing_done_;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.h b/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.h
index 924c0f92a84..02a0f750f3c 100644
--- a/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.h
+++ b/chromium/third_party/blink/renderer/platform/heap/unified_heap_controller.h
@@ -38,15 +38,18 @@ class PLATFORM_EXPORT UnifiedHeapController final
// v8::EmbedderHeapTracer implementation.
void TracePrologue() final;
void TraceEpilogue() final;
- void AbortTracing() final;
void EnterFinalPause(EmbedderStackState) final;
void RegisterV8References(const std::vector<std::pair<void*, void*>>&) final;
bool AdvanceTracing(double) final;
+ bool IsTracingDone() final;
ThreadState* thread_state() const { return thread_state_; }
private:
ThreadState* const thread_state_;
+
+ // Returns whether the Blink heap has been fully processed.
+ bool is_tracing_done_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/heap/visitor.h b/chromium/third_party/blink/renderer/platform/heap/visitor.h
index e0723f7ae6c..2a53f1ac542 100644
--- a/chromium/third_party/blink/renderer/platform/heap/visitor.h
+++ b/chromium/third_party/blink/renderer/platform/heap/visitor.h
@@ -134,8 +134,6 @@ class PLATFORM_EXPORT Visitor {
static_assert(IsGarbageCollectedType<T>::value,
"T needs to be a garbage collected object");
- if (!backing_store)
- return;
VisitBackingStoreWeakly(reinterpret_cast<void*>(backing_store),
reinterpret_cast<void**>(backing_store_slot),
TraceTrait<T>::GetTraceDescriptor(
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/gif/gif_image_decoder_test.cc b/chromium/third_party/blink/renderer/platform/image-decoders/gif/gif_image_decoder_test.cc
index 414dc305c23..5e80c871b34 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/gif/gif_image_decoder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/gif/gif_image_decoder_test.cc
@@ -42,7 +42,7 @@ namespace blink {
namespace {
-const char kLayoutTestResourcesDir[] = "LayoutTests/images/resources";
+const char kWebTestsResourcesDir[] = "web_tests/images/resources";
std::unique_ptr<ImageDecoder> CreateDecoder() {
return std::make_unique<GIFImageDecoder>(
@@ -66,7 +66,7 @@ TEST(GIFImageDecoderTest, decodeTwoFrames) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
scoped_refptr<SharedBuffer> data =
- ReadFile(kLayoutTestResourcesDir, "animated.gif");
+ ReadFile(kWebTestsResourcesDir, "animated.gif");
ASSERT_TRUE(data.get());
decoder->SetData(data.get(), true);
@@ -90,7 +90,7 @@ TEST(GIFImageDecoderTest, decodeTwoFrames) {
TEST(GIFImageDecoderTest, crbug779261) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
scoped_refptr<SharedBuffer> data =
- ReadFile(kLayoutTestResourcesDir, "crbug779261.gif");
+ ReadFile(kWebTestsResourcesDir, "crbug779261.gif");
ASSERT_TRUE(data.get());
decoder->SetData(data.get(), true);
@@ -112,7 +112,7 @@ TEST(GIFImageDecoderTest, parseAndDecode) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
scoped_refptr<SharedBuffer> data =
- ReadFile(kLayoutTestResourcesDir, "animated.gif");
+ ReadFile(kWebTestsResourcesDir, "animated.gif");
ASSERT_TRUE(data.get());
decoder->SetData(data.get(), true);
@@ -135,7 +135,7 @@ TEST(GIFImageDecoderTest, parseByteByByte) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
const Vector<char> data =
- ReadFile(kLayoutTestResourcesDir, "animated.gif")->CopyAs<Vector<char>>();
+ ReadFile(kWebTestsResourcesDir, "animated.gif")->CopyAs<Vector<char>>();
size_t frame_count = 0;
@@ -157,7 +157,7 @@ TEST(GIFImageDecoderTest, parseByteByByte) {
}
TEST(GIFImageDecoderTest, parseAndDecodeByteByByte) {
- TestByteByByteDecode(&CreateDecoder, kLayoutTestResourcesDir,
+ TestByteByByteDecode(&CreateDecoder, kWebTestsResourcesDir,
"animated-gif-with-offsets.gif", 5u,
kAnimationLoopInfinite);
}
@@ -184,7 +184,7 @@ TEST(GIFImageDecoderTest, allDataReceivedTruncation) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
const Vector<char> data =
- ReadFile(kLayoutTestResourcesDir, "animated.gif")->CopyAs<Vector<char>>();
+ ReadFile(kWebTestsResourcesDir, "animated.gif")->CopyAs<Vector<char>>();
ASSERT_GE(data.size(), 10u);
scoped_refptr<SharedBuffer> temp_data =
@@ -204,7 +204,7 @@ TEST(GIFImageDecoderTest, frameIsComplete) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
scoped_refptr<SharedBuffer> data =
- ReadFile(kLayoutTestResourcesDir, "animated.gif");
+ ReadFile(kWebTestsResourcesDir, "animated.gif");
ASSERT_TRUE(data.get());
decoder->SetData(data.get(), true);
@@ -219,7 +219,7 @@ TEST(GIFImageDecoderTest, frameIsCompleteLoading) {
std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
scoped_refptr<SharedBuffer> data_buffer =
- ReadFile(kLayoutTestResourcesDir, "animated.gif");
+ ReadFile(kWebTestsResourcesDir, "animated.gif");
ASSERT_TRUE(data_buffer.get());
const Vector<char> data = data_buffer->CopyAs<Vector<char>>();
@@ -265,16 +265,16 @@ TEST(GIFImageDecoderTest, badTerminator) {
TEST(GIFImageDecoderTest, updateRequiredPreviousFrameAfterFirstDecode) {
TestUpdateRequiredPreviousFrameAfterFirstDecode(
- &CreateDecoder, kLayoutTestResourcesDir, "animated-10color.gif");
+ &CreateDecoder, kWebTestsResourcesDir, "animated-10color.gif");
}
TEST(GIFImageDecoderTest, randomFrameDecode) {
// Single frame image.
TestRandomFrameDecode(&CreateDecoder, kDecodersTestingDir, "radient.gif");
// Multiple frame images.
- TestRandomFrameDecode(&CreateDecoder, kLayoutTestResourcesDir,
+ TestRandomFrameDecode(&CreateDecoder, kWebTestsResourcesDir,
"animated-gif-with-offsets.gif");
- TestRandomFrameDecode(&CreateDecoder, kLayoutTestResourcesDir,
+ TestRandomFrameDecode(&CreateDecoder, kWebTestsResourcesDir,
"animated-10color.gif");
}
@@ -284,14 +284,14 @@ TEST(GIFImageDecoderTest, randomDecodeAfterClearFrameBufferCache) {
&CreateDecoder, kDecodersTestingDir, "radient.gif");
// Multiple frame images.
TestRandomDecodeAfterClearFrameBufferCache(
- &CreateDecoder, kLayoutTestResourcesDir, "animated-gif-with-offsets.gif");
+ &CreateDecoder, kWebTestsResourcesDir, "animated-gif-with-offsets.gif");
TestRandomDecodeAfterClearFrameBufferCache(
- &CreateDecoder, kLayoutTestResourcesDir, "animated-10color.gif");
+ &CreateDecoder, kWebTestsResourcesDir, "animated-10color.gif");
}
TEST(GIFImageDecoderTest, resumePartialDecodeAfterClearFrameBufferCache) {
TestResumePartialDecodeAfterClearFrameBufferCache(
- &CreateDecoder, kLayoutTestResourcesDir, "animated-10color.gif");
+ &CreateDecoder, kWebTestsResourcesDir, "animated-10color.gif");
}
// The first LZW codes in the image are invalid values that try to create a loop
@@ -372,13 +372,13 @@ TEST(GIFImageDecoderTest, firstFrameHasGreaterSizeThanScreenSize) {
}
TEST(GIFImageDecoderTest, verifyRepetitionCount) {
- TestRepetitionCount(kLayoutTestResourcesDir, "full2loop.gif", 2);
+ TestRepetitionCount(kWebTestsResourcesDir, "full2loop.gif", 2);
TestRepetitionCount(kDecodersTestingDir, "radient.gif", kAnimationNone);
}
TEST(GIFImageDecoderTest, repetitionCountChangesWhenSeen) {
scoped_refptr<SharedBuffer> full_data_buffer =
- ReadFile(kLayoutTestResourcesDir, "animated-10color.gif");
+ ReadFile(kWebTestsResourcesDir, "animated-10color.gif");
ASSERT_TRUE(full_data_buffer.get());
const Vector<char> full_data = full_data_buffer->CopyAs<Vector<char>>();
@@ -462,7 +462,7 @@ class Allocator final : public SkBitmap::Allocator {
// Ensure that calling SetMemoryAllocator does not short-circuit
// InitializeNewFrame.
TEST(GIFImageDecoderTest, externalAllocator) {
- auto data = ReadFile(kLayoutTestResourcesDir, "boston.gif");
+ auto data = ReadFile(kWebTestsResourcesDir, "boston.gif");
ASSERT_TRUE(data.get());
auto decoder = CreateDecoder();
@@ -480,7 +480,7 @@ TEST(GIFImageDecoderTest, externalAllocator) {
}
TEST(GIFImageDecoderTest, recursiveDecodeFailure) {
- auto data = ReadFile(kLayoutTestResourcesDir, "count-down-color-test.gif");
+ auto data = ReadFile(kWebTestsResourcesDir, "count-down-color-test.gif");
ASSERT_TRUE(data.get());
{
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.cc b/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.cc
index c544780efa9..b9ad319e989 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.cc
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.cc
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.h"
#include "third_party/blink/renderer/platform/image-decoders/png/png_image_decoder.h"
#include "third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h"
-#include "third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h"
+#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
namespace blink {
@@ -156,9 +156,9 @@ ImageFrame* ImageDecoder::DecodeFrameBufferAtIndex(size_t index) {
return nullptr;
ImageFrame* frame = &frame_buffer_cache_[index];
if (frame->GetStatus() != ImageFrame::kFrameComplete) {
- PlatformInstrumentation::WillDecodeImage(FilenameExtension());
+ TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Decode Image",
+ "imageType", FilenameExtension().Ascii());
Decode(index);
- PlatformInstrumentation::DidDecodeImage();
}
if (!has_histogrammed_color_space_) {
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.h b/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.h
index c620481aa73..e51dcca6398 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.h
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder.h
@@ -443,7 +443,7 @@ class PLATFORM_EXPORT ImageDecoder {
//
// Before calling this, verify that frame |index| exists by checking that
// |index| is smaller than |frame_buffer_cache_|.size().
- virtual bool FrameStatusSufficientForSuccessors(size_t index) {
+ virtual bool FrameStatusSufficientForSuccessors(wtf_size_t index) {
DCHECK(index < frame_buffer_cache_.size());
ImageFrame::Status frame_status = frame_buffer_cache_[index].GetStatus();
return frame_status == ImageFrame::kFramePartial ||
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.cc b/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.cc
index 74ffbd0a8e7..e55f3006d76 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.cc
@@ -15,17 +15,17 @@
namespace blink {
scoped_refptr<SharedBuffer> ReadFile(const char* file_name) {
- String file_path = test::BlinkLayoutTestsDir();
+ String file_path = test::BlinkWebTestsDir();
file_path.append(file_name);
return test::ReadFromFile(file_path);
}
scoped_refptr<SharedBuffer> ReadFile(const char* dir, const char* file_name) {
StringBuilder file_path;
- if (strncmp(dir, "LayoutTests/", 12) == 0) {
- file_path.Append(test::BlinkLayoutTestsDir());
+ if (strncmp(dir, "web_tests/", 10) == 0) {
+ file_path.Append(test::BlinkWebTestsDir());
file_path.Append('/');
- file_path.Append(dir + 12);
+ file_path.Append(dir + 10);
} else {
file_path.Append(test::BlinkRootDir());
file_path.Append('/');
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc b/chromium/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc
index f08fbb3d5ac..b6c6aaeb43b 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.cc
@@ -40,7 +40,7 @@
#include <memory>
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image_metrics.h"
-#include "third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h"
+#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
extern "C" {
#include <stdio.h> // jpeglib.h needs stdio FILE.
@@ -929,9 +929,11 @@ bool JPEGImageDecoder::DecodeToYUV() {
if (!HasImagePlanes())
return false;
- PlatformInstrumentation::WillDecodeImage("JPEG");
- Decode(false);
- PlatformInstrumentation::DidDecodeImage();
+ {
+ TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Decode Image",
+ "imageType", "JPEG");
+ Decode(false);
+ }
return !Failed();
}
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/png/png_image_decoder_test.cc b/chromium/third_party/blink/renderer/platform/image-decoders/png/png_image_decoder_test.cc
index b4fa63f3c66..998193ccdee 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/png/png_image_decoder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/png/png_image_decoder_test.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/skia/include/core/SkImage.h"
-// /LayoutTests/images/resources/png-animated-idat-part-of-animation.png
+// web_tests/images/resources/png-animated-idat-part-of-animation.png
// is modified in multiple tests to simulate erroneous PNGs. As a reference,
// the table below shows how the file is structured.
//
@@ -117,7 +117,7 @@ struct PublicFrameInfo {
};
// This is the frame data for the following PNG image:
-// /LayoutTests/images/resources/png-animated-idat-part-of-animation.png
+// web_tests/images/resources/png-animated-idat-part-of-animation.png
static PublicFrameInfo g_png_animated_frame_info[] = {
{TimeDelta::FromMilliseconds(500),
{IntPoint(0, 0), IntSize(5, 5)},
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/segment_stream.cc b/chromium/third_party/blink/renderer/platform/image-decoders/segment_stream.cc
index b2af6860c0d..5a9870125d2 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/segment_stream.cc
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/segment_stream.cc
@@ -31,7 +31,8 @@ bool SegmentStream::IsCleared() const {
}
size_t SegmentStream::read(void* buffer, size_t size) {
- DCHECK(!IsCleared());
+ if (IsCleared())
+ return 0;
size = std::min(size, reader_->size() - position_);
@@ -48,7 +49,8 @@ size_t SegmentStream::read(void* buffer, size_t size) {
}
size_t SegmentStream::peek(void* buffer, size_t size) const {
- DCHECK(!IsCleared());
+ if (IsCleared())
+ return 0;
size = std::min(size, reader_->size() - position_);
diff --git a/chromium/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h b/chromium/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h
index 30a7971a15a..5b09982d011 100644
--- a/chromium/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h
+++ b/chromium/third_party/blink/renderer/platform/image-decoders/webp/webp_image_decoder.h
@@ -70,7 +70,7 @@ class PLATFORM_EXPORT WEBPImageDecoder final : public ImageDecoder {
//
// Before calling this, verify that frame |index| exists by checking that
// |index| is smaller than |frame_buffer_cache_|.size().
- bool FrameStatusSufficientForSuccessors(size_t index) override {
+ bool FrameStatusSufficientForSuccessors(wtf_size_t index) override {
DCHECK(index < frame_buffer_cache_.size());
return frame_buffer_cache_[index].GetStatus() == ImageFrame::kFrameComplete;
}
diff --git a/chromium/third_party/blink/renderer/platform/image-encoders/image_encoder_utils.cc b/chromium/third_party/blink/renderer/platform/image-encoders/image_encoder_utils.cc
index 2a6639ad427..b803f96c161 100644
--- a/chromium/third_party/blink/renderer/platform/image-encoders/image_encoder_utils.cc
+++ b/chromium/third_party/blink/renderer/platform/image-encoders/image_encoder_utils.cc
@@ -14,6 +14,7 @@ const ImageEncodingMimeType ImageEncoderUtils::kDefaultEncodingMimeType =
kMimeTypePng;
const char ImageEncoderUtils::kDefaultRequestedMimeType[] = "image/png";
+namespace {
// This enum is used in a UMA histogram; the values should not be changed.
enum RequestedImageMimeType {
kRequestedImageMimeTypePng = 0,
@@ -24,9 +25,11 @@ enum RequestedImageMimeType {
kRequestedImageMimeTypeIco = 5,
kRequestedImageMimeTypeTiff = 6,
kRequestedImageMimeTypeUnknown = 7,
- kNumberOfRequestedImageMimeTypes
+ kMaxValue = kRequestedImageMimeTypeUnknown,
};
+} // namespace
+
ImageEncodingMimeType ImageEncoderUtils::ToEncodingMimeType(
const String& mime_type_name,
const EncodeReason encode_reason) {
@@ -57,24 +60,15 @@ ImageEncodingMimeType ImageEncoderUtils::ToEncodingMimeType(
}
if (encode_reason == kEncodeReasonToDataURL) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram,
- to_data_url_requested_mime_type_histogram,
- ("Canvas.RequestedImageMimeTypes_toDataURL",
- kNumberOfRequestedImageMimeTypes));
- to_data_url_requested_mime_type_histogram.Count(requested_mime_type);
+ UMA_HISTOGRAM_ENUMERATION("Blink.Canvas.RequestedImageMimeTypes_toDataURL",
+ requested_mime_type);
} else if (encode_reason == kEncodeReasonToBlobCallback) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- EnumerationHistogram, to_blob_callback_requested_mime_type_histogram,
- ("Canvas.RequestedImageMimeTypes_toBlobCallback",
- kNumberOfRequestedImageMimeTypes));
- to_blob_callback_requested_mime_type_histogram.Count(requested_mime_type);
+ UMA_HISTOGRAM_ENUMERATION(
+ "Blink.Canvas.RequestedImageMimeTypes_toBlobCallback",
+ requested_mime_type);
} else if (encode_reason == kEncodeReasonConvertToBlobPromise) {
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- EnumerationHistogram,
- convert_to_blob_promise_requested_mime_type_histogram,
- ("Canvas.RequestedImageMimeTypes_convertToBlobPromise",
- kNumberOfRequestedImageMimeTypes));
- convert_to_blob_promise_requested_mime_type_histogram.Count(
+ UMA_HISTOGRAM_ENUMERATION(
+ "Blink.Canvas.RequestedImageMimeTypes_convertToBlobPromise",
requested_mime_type);
}
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/BUILD.gn b/chromium/third_party/blink/renderer/platform/instrumentation/BUILD.gn
index ad0058db5c4..664297efc95 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/BUILD.gn
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/BUILD.gn
@@ -7,8 +7,6 @@ import("//third_party/blink/renderer/platform/platform.gni")
blink_platform_sources("instrumentation") {
sources = [
- "platform_instrumentation.cc",
- "platform_instrumentation.h",
"resource_coordinator/frame_resource_coordinator.cc",
"resource_coordinator/frame_resource_coordinator.h",
"resource_coordinator/renderer_resource_coordinator.cc",
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.cc b/chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.cc
deleted file mode 100644
index c7c9d6aacc7..00000000000
--- a/chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h"
-
-namespace blink {
-
-const char PlatformInstrumentation::kCategoryName[] =
- TRACE_DISABLED_BY_DEFAULT("devtools.timeline");
-
-const char PlatformInstrumentation::kImageDecodeEvent[] = "Decode Image";
-const char PlatformInstrumentation::kImageResizeEvent[] = "Resize Image";
-const char PlatformInstrumentation::kDrawLazyPixelRefEvent[] =
- "Draw LazyPixelRef";
-const char PlatformInstrumentation::kDecodeLazyPixelRefEvent[] =
- "Decode LazyPixelRef";
-
-const char PlatformInstrumentation::kLazyPixelRef[] = "LazyPixelRef";
-
-const char PlatformInstrumentation::kImageTypeArgument[] = "imageType";
-const char PlatformInstrumentation::kCachedArgument[] = "cached";
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h b/chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h
deleted file mode 100644
index 919b32af0f0..00000000000
--- a/chromium/third_party/blink/renderer/platform/instrumentation/platform_instrumentation.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_PLATFORM_INSTRUMENTATION_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_PLATFORM_INSTRUMENTATION_H_
-
-#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-
-class PLATFORM_EXPORT PlatformInstrumentation {
- public:
- class LazyPixelRefTracker : TraceEvent::TraceScopedTrackableObject<void*> {
- public:
- LazyPixelRefTracker(void* instance)
- : TraceEvent::TraceScopedTrackableObject<void*>(kCategoryName,
- kLazyPixelRef,
- instance) {}
- };
-
- static const char kImageDecodeEvent[];
- static const char kImageResizeEvent[];
- static const char kDrawLazyPixelRefEvent[];
- static const char kDecodeLazyPixelRefEvent[];
-
- static const char kImageTypeArgument[];
- static const char kCachedArgument[];
-
- static const char kLazyPixelRef[];
-
- static void WillDecodeImage(const String& image_type);
- static void DidDecodeImage();
- static void DidDrawLazyPixelRef(unsigned long long lazy_pixel_ref_id);
- static void WillDecodeLazyPixelRef(unsigned long long lazy_pixel_ref_id);
- static void DidDecodeLazyPixelRef();
-
- private:
- static const char kCategoryName[];
-};
-
-inline void PlatformInstrumentation::WillDecodeImage(const String& image_type) {
- TRACE_EVENT_BEGIN1(kCategoryName, kImageDecodeEvent, kImageTypeArgument,
- image_type.Ascii());
-}
-
-inline void PlatformInstrumentation::DidDecodeImage() {
- TRACE_EVENT_END0(kCategoryName, kImageDecodeEvent);
-}
-
-inline void PlatformInstrumentation::DidDrawLazyPixelRef(
- unsigned long long lazy_pixel_ref_id) {
- TRACE_EVENT_INSTANT1(kCategoryName, kDrawLazyPixelRefEvent,
- TRACE_EVENT_SCOPE_THREAD, kLazyPixelRef,
- lazy_pixel_ref_id);
-}
-
-inline void PlatformInstrumentation::WillDecodeLazyPixelRef(
- unsigned long long lazy_pixel_ref_id) {
- TRACE_EVENT_BEGIN1(kCategoryName, kDecodeLazyPixelRefEvent, kLazyPixelRef,
- lazy_pixel_ref_id);
-}
-
-inline void PlatformInstrumentation::DidDecodeLazyPixelRef() {
- TRACE_EVENT_END0(kCategoryName, kDecodeLazyPixelRefEvent);
-}
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_PLATFORM_INSTRUMENTATION_H_
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc
index 40a645a7906..3f6c59c9db9 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.cc
@@ -7,7 +7,7 @@
#include "base/trace_event/trace_event.h"
namespace blink {
-namespace TraceEvent {
+namespace trace_event {
void EnableTracing(const String& category_filter) {
base::trace_event::TraceLog::GetInstance()->SetEnabled(
@@ -39,5 +39,5 @@ void RemoveEnabledStateObserver(EnabledStateObserver* observer) {
observer);
}
-} // namespace TraceEvent
+} // namespace trace_event
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h
index aa96a2bc812..97e1475fa58 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h
@@ -26,7 +26,7 @@ static inline void SetTraceValue(const CString& arg,
} // namespace WTF
namespace blink {
-namespace TraceEvent {
+namespace trace_event {
using base::trace_event::TraceScopedTrackableObject;
using AsyncEnabledStateObserver =
@@ -51,7 +51,7 @@ PLATFORM_EXPORT void RemoveAsyncEnabledStateObserver(
PLATFORM_EXPORT void AddEnabledStateObserver(EnabledStateObserver*);
PLATFORM_EXPORT void RemoveEnabledStateObserver(EnabledStateObserver*);
-} // namespace TraceEvent
+} // namespace trace_event
} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc
index 811f4c65e5b..dbc8c6f82bd 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc
@@ -112,6 +112,10 @@ void TracedValue::AppendAsTraceFormat(std::string* out) const {
traced_value_.AppendAsTraceFormat(out);
}
+bool TracedValue::AppendToProto(ProtoAppender* appender) {
+ return traced_value_.AppendToProto(appender);
+}
+
void TracedValue::EstimateTraceMemoryOverhead(
base::trace_event::TraceEventMemoryOverhead* overhead) {
traced_value_.EstimateTraceMemoryOverhead(overhead);
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h
index 6a25ad9876e..1efbf6332d4 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_INSTRUMENTATION_TRACING_TRACED_VALUE_H_
#include "base/macros.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -52,6 +52,7 @@ class PLATFORM_EXPORT TracedValue final
// ConvertableToTraceFormat
void AppendAsTraceFormat(std::string*) const final;
+ bool AppendToProto(ProtoAppender* appender) final;
void EstimateTraceMemoryOverhead(
base::trace_event::TraceEventMemoryOverhead*) final;
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump.cc b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump.cc
index 21c82cd046f..a8eb0b162fc 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump.cc
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump.cc
@@ -11,8 +11,8 @@
#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/trace_event/process_memory_dump.h"
-#include "base/trace_event/trace_event_argument.h"
#include "base/trace_event/trace_event_memory_overhead.h"
+#include "base/trace_event/traced_value.h"
#include "skia/ext/skia_trace_memory_dump_impl.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/web_memory_allocator_dump.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
diff --git a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump_test.cc b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump_test.cc
index b1d03c00f05..71ee46dd28c 100644
--- a/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump_test.cc
+++ b/chromium/third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump_test.cc
@@ -8,7 +8,7 @@
#include "base/test/test_discardable_memory_allocator.h"
#include "base/trace_event/memory_allocator_dump.h"
#include "base/trace_event/process_memory_dump.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "base/values.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromium/third_party/blink/renderer/platform/lifecycle_context_test.cc b/chromium/third_party/blink/renderer/platform/lifecycle_context_test.cc
index 2b482bfafb4..fa3b3316653 100644
--- a/chromium/third_party/blink/renderer/platform/lifecycle_context_test.cc
+++ b/chromium/third_party/blink/renderer/platform/lifecycle_context_test.cc
@@ -41,7 +41,7 @@ class DummyContext final
USING_GARBAGE_COLLECTED_MIXIN(DummyContext);
public:
- static DummyContext* Create() { return new DummyContext; }
+ static DummyContext* Create() { return MakeGarbageCollected<DummyContext>(); }
void Trace(blink::Visitor* visitor) override {
LifecycleNotifier<DummyContext, TestingObserver>::Trace(visitor);
@@ -58,9 +58,12 @@ class TestingObserver final
public:
static TestingObserver* Create(DummyContext* context) {
- return new TestingObserver(context);
+ return MakeGarbageCollected<TestingObserver>(context);
}
+ explicit TestingObserver(DummyContext* context)
+ : LifecycleObserver(context), context_destroyed_called_(false) {}
+
void ContextDestroyed(DummyContext* destroyed_context) {
if (observer_to_remove_on_destruct_) {
destroyed_context->RemoveObserver(observer_to_remove_on_destruct_);
@@ -88,9 +91,6 @@ class TestingObserver final
bool ContextDestroyedCalled() const { return context_destroyed_called_; }
private:
- explicit TestingObserver(DummyContext* context)
- : LifecycleObserver(context), context_destroyed_called_(false) {}
-
Member<TestingObserver> observer_to_remove_on_destruct_;
bool context_destroyed_called_;
};
diff --git a/chromium/third_party/blink/renderer/platform/loader/BUILD.gn b/chromium/third_party/blink/renderer/platform/loader/BUILD.gn
index bf3f9262d43..6f44d60d89e 100644
--- a/chromium/third_party/blink/renderer/platform/loader/BUILD.gn
+++ b/chromium/third_party/blink/renderer/platform/loader/BUILD.gn
@@ -18,7 +18,6 @@ blink_platform_sources("loader") {
"cors/cors.h",
"cors/cors_error_string.cc",
"cors/cors_error_string.h",
- "fetch/access_control_status.h",
"fetch/buffering_data_pipe_writer.cc",
"fetch/buffering_data_pipe_writer.h",
"fetch/cached_metadata.cc",
@@ -120,6 +119,7 @@ jumbo_source_set("unit_tests") {
"fetch/raw_resource_test.cc",
"fetch/resource_fetcher_test.cc",
"fetch/resource_load_scheduler_test.cc",
+ "fetch/resource_loader_defer_loading_test.cc",
"fetch/resource_loader_test.cc",
"fetch/resource_request_test.cc",
"fetch/resource_response_test.cc",
diff --git a/chromium/third_party/blink/renderer/platform/loader/OWNERS b/chromium/third_party/blink/renderer/platform/loader/OWNERS
index b2c834a0937..0e5b601a377 100644
--- a/chromium/third_party/blink/renderer/platform/loader/OWNERS
+++ b/chromium/third_party/blink/renderer/platform/loader/OWNERS
@@ -1,3 +1,4 @@
+hiroshige@chromium.org
japhet@chromium.org
mkwst@chromium.org
toyoshim@chromium.org
diff --git a/chromium/third_party/blink/renderer/platform/loader/cors/cors.cc b/chromium/third_party/blink/renderer/platform/loader/cors/cors.cc
index 40e51eb3863..ceab3bb784a 100644
--- a/chromium/third_party/blink/renderer/platform/loader/cors/cors.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/cors/cors.cc
@@ -8,10 +8,12 @@
#include <string>
#include <utility>
+#include "net/http/http_util.h"
#include "services/network/public/cpp/cors/cors.h"
#include "services/network/public/cpp/cors/preflight_cache.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/platform/loader/cors/cors_error_string.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include "third_party/blink/renderer/platform/network/http_header_map.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -29,9 +31,7 @@ namespace {
base::Optional<std::string> GetHeaderValue(const HTTPHeaderMap& header_map,
const AtomicString& header_name) {
if (header_map.Contains(header_name)) {
- const AtomicString& atomic_value = header_map.Get(header_name);
- CString string_value = atomic_value.GetString().Utf8();
- return std::string(string_value.data(), string_value.length());
+ return WebString(header_map.Get(header_name)).Latin1();
}
return base::nullopt;
}
@@ -75,11 +75,86 @@ url::Origin AsUrlOrigin(const SecurityOrigin& origin) {
return origin.ToString() == "null" ? url::Origin() : origin.ToUrlOrigin();
}
+// A parser for the value of the Access-Control-Expose-Headers header.
+class HTTPHeaderNameListParser {
+ STACK_ALLOCATED();
+
+ public:
+ explicit HTTPHeaderNameListParser(const String& value)
+ : value_(value), pos_(0) {}
+
+ // Tries parsing |value_| expecting it to be conforming to the #field-name
+ // ABNF rule defined in RFC 7230. Returns with the field-name entries stored
+ // in |output| when successful. Otherwise, returns with |output| kept empty.
+ //
+ // |output| must be empty.
+ void Parse(WebHTTPHeaderSet& output) {
+ DCHECK(output.empty());
+
+ while (true) {
+ ConsumeSpaces();
+
+ size_t token_start = pos_;
+ ConsumeTokenChars();
+ size_t token_size = pos_ - token_start;
+ if (token_size == 0) {
+ output.clear();
+ return;
+ }
+
+ const CString& name = value_.Substring(token_start, token_size).Ascii();
+ output.emplace(name.data(), name.length());
+
+ ConsumeSpaces();
+
+ if (pos_ == value_.length())
+ return;
+
+ if (value_[pos_] == ',') {
+ ++pos_;
+ } else {
+ output.clear();
+ return;
+ }
+ }
+ }
+
+ private:
+ // Consumes zero or more spaces (SP and HTAB) from value_.
+ void ConsumeSpaces() {
+ while (true) {
+ if (pos_ == value_.length())
+ return;
+
+ UChar c = value_[pos_];
+ if (c != ' ' && c != '\t')
+ return;
+ ++pos_;
+ }
+ }
+
+ // Consumes zero or more tchars from value_.
+ void ConsumeTokenChars() {
+ while (true) {
+ if (pos_ == value_.length())
+ return;
+
+ UChar c = value_[pos_];
+ if (c > 0x7F || !net::HttpUtil::IsTokenChar(c))
+ return;
+ ++pos_;
+ }
+ }
+
+ const String value_;
+ size_t pos_;
+};
+
} // namespace
-namespace CORS {
+namespace cors {
-base::Optional<network::CORSErrorStatus> CheckAccess(
+base::Optional<network::CorsErrorStatus> CheckAccess(
const KURL& response_url,
const int response_status_code,
const HTTPHeaderMap& response_header,
@@ -87,13 +162,13 @@ base::Optional<network::CORSErrorStatus> CheckAccess(
const SecurityOrigin& origin) {
return network::cors::CheckAccess(
response_url, response_status_code,
- GetHeaderValue(response_header, HTTPNames::Access_Control_Allow_Origin),
+ GetHeaderValue(response_header, http_names::kAccessControlAllowOrigin),
GetHeaderValue(response_header,
- HTTPNames::Access_Control_Allow_Credentials),
+ http_names::kAccessControlAllowCredentials),
credentials_mode, AsUrlOrigin(origin));
}
-base::Optional<network::CORSErrorStatus> CheckPreflightAccess(
+base::Optional<network::CorsErrorStatus> CheckPreflightAccess(
const KURL& response_url,
const int response_status_code,
const HTTPHeaderMap& response_header,
@@ -101,17 +176,17 @@ base::Optional<network::CORSErrorStatus> CheckPreflightAccess(
const SecurityOrigin& origin) {
return network::cors::CheckPreflightAccess(
response_url, response_status_code,
- GetHeaderValue(response_header, HTTPNames::Access_Control_Allow_Origin),
+ GetHeaderValue(response_header, http_names::kAccessControlAllowOrigin),
GetHeaderValue(response_header,
- HTTPNames::Access_Control_Allow_Credentials),
+ http_names::kAccessControlAllowCredentials),
actual_credentials_mode, AsUrlOrigin(origin));
}
-base::Optional<network::CORSErrorStatus> CheckRedirectLocation(
+base::Optional<network::CorsErrorStatus> CheckRedirectLocation(
const KURL& url,
network::mojom::FetchRequestMode request_mode,
const SecurityOrigin* origin,
- CORSFlag cors_flag) {
+ CorsFlag cors_flag) {
base::Optional<url::Origin> origin_to_pass;
if (origin)
origin_to_pass = AsUrlOrigin(*origin);
@@ -119,25 +194,25 @@ base::Optional<network::CORSErrorStatus> CheckRedirectLocation(
// Blink-side implementations rewrite the origin instead of setting the
// tainted flag.
return network::cors::CheckRedirectLocation(
- url, request_mode, origin_to_pass, cors_flag == CORSFlag::Set, false);
+ url, request_mode, origin_to_pass, cors_flag == CorsFlag::Set, false);
}
-base::Optional<network::mojom::CORSError> CheckPreflight(
+base::Optional<network::mojom::CorsError> CheckPreflight(
const int preflight_response_status_code) {
return network::cors::CheckPreflight(preflight_response_status_code);
}
-base::Optional<network::CORSErrorStatus> CheckExternalPreflight(
+base::Optional<network::CorsErrorStatus> CheckExternalPreflight(
const HTTPHeaderMap& response_header) {
- return network::cors::CheckExternalPreflight(GetHeaderValue(
- response_header, HTTPNames::Access_Control_Allow_External));
+ return network::cors::CheckExternalPreflight(
+ GetHeaderValue(response_header, http_names::kAccessControlAllowExternal));
}
-bool IsCORSEnabledRequestMode(network::mojom::FetchRequestMode request_mode) {
- return network::cors::IsCORSEnabledRequestMode(request_mode);
+bool IsCorsEnabledRequestMode(network::mojom::FetchRequestMode request_mode) {
+ return network::cors::IsCorsEnabledRequestMode(request_mode);
}
-base::Optional<network::CORSErrorStatus> EnsurePreflightResultAndCacheOnSuccess(
+base::Optional<network::CorsErrorStatus> EnsurePreflightResultAndCacheOnSuccess(
const HTTPHeaderMap& response_header_map,
const String& origin,
const KURL& request_url,
@@ -147,22 +222,22 @@ base::Optional<network::CORSErrorStatus> EnsurePreflightResultAndCacheOnSuccess(
DCHECK(!origin.IsNull());
DCHECK(!request_method.IsNull());
- base::Optional<network::mojom::CORSError> error;
+ base::Optional<network::mojom::CorsError> error;
std::unique_ptr<network::cors::PreflightResult> result =
network::cors::PreflightResult::Create(
request_credentials_mode,
GetOptionalHeaderValue(response_header_map,
- HTTPNames::Access_Control_Allow_Methods),
+ http_names::kAccessControlAllowMethods),
GetOptionalHeaderValue(response_header_map,
- HTTPNames::Access_Control_Allow_Headers),
+ http_names::kAccessControlAllowHeaders),
GetOptionalHeaderValue(response_header_map,
- HTTPNames::Access_Control_Max_Age),
+ http_names::kAccessControlMaxAge),
&error);
if (error)
- return network::CORSErrorStatus(*error);
+ return network::CorsErrorStatus(*error);
- base::Optional<network::CORSErrorStatus> status;
+ base::Optional<network::CorsErrorStatus> status;
status = result->EnsureAllowedCrossOriginMethod(
std::string(request_method.Ascii().data()));
if (status)
@@ -201,12 +276,12 @@ network::mojom::FetchResponseType CalculateResponseTainting(
const KURL& url,
network::mojom::FetchRequestMode request_mode,
const SecurityOrigin* origin,
- CORSFlag cors_flag) {
+ CorsFlag cors_flag) {
base::Optional<url::Origin> origin_to_pass;
if (origin)
origin_to_pass = AsUrlOrigin(*origin);
return network::cors::CalculateResponseTainting(
- url, request_mode, origin_to_pass, cors_flag == CORSFlag::Set);
+ url, request_mode, origin_to_pass, cors_flag == CorsFlag::Set);
}
bool CalculateCredentialsFlag(
@@ -216,37 +291,24 @@ bool CalculateCredentialsFlag(
response_tainting);
}
-bool IsCORSSafelistedMethod(const String& method) {
+bool IsCorsSafelistedMethod(const String& method) {
DCHECK(!method.IsNull());
- CString utf8_method = method.Utf8();
- return network::cors::IsCORSSafelistedMethod(
- std::string(utf8_method.data(), utf8_method.length()));
-}
-
-bool IsCORSSafelistedContentType(const String& media_type) {
- CString utf8_media_type = media_type.Utf8();
- return network::cors::IsCORSSafelistedContentType(
- std::string(utf8_media_type.data(), utf8_media_type.length()));
+ return network::cors::IsCorsSafelistedMethod(WebString(method).Latin1());
}
-bool IsCORSSafelistedHeader(const String& name, const String& value) {
- DCHECK(!name.IsNull());
- DCHECK(!value.IsNull());
- CString utf8_name = name.Utf8();
- CString utf8_value = value.Utf8();
- return network::cors::IsCORSSafelistedHeader(
- std::string(utf8_name.data(), utf8_name.length()),
- std::string(utf8_value.data(), utf8_value.length()));
+bool IsCorsSafelistedContentType(const String& media_type) {
+ return network::cors::IsCorsSafelistedContentType(
+ WebString(media_type).Latin1());
}
-bool IsNoCORSSafelistedHeader(const String& name, const String& value) {
+bool IsNoCorsSafelistedHeader(const String& name, const String& value) {
DCHECK(!name.IsNull());
DCHECK(!value.IsNull());
- return network::cors::IsNoCORSSafelistedHeader(WebString(name).Latin1(),
+ return network::cors::IsNoCorsSafelistedHeader(WebString(name).Latin1(),
WebString(value).Latin1());
}
-Vector<String> CORSUnsafeRequestHeaderNames(const HTTPHeaderMap& headers) {
+Vector<String> CorsUnsafeRequestHeaderNames(const HTTPHeaderMap& headers) {
net::HttpRequestHeaders::HeaderVector in;
for (const auto& entry : headers) {
in.push_back(net::HttpRequestHeaders::HeaderKeyValuePair(
@@ -254,23 +316,21 @@ Vector<String> CORSUnsafeRequestHeaderNames(const HTTPHeaderMap& headers) {
}
Vector<String> header_names;
- for (const auto& name : network::cors::CORSUnsafeRequestHeaderNames(in))
+ for (const auto& name : network::cors::CorsUnsafeRequestHeaderNames(in))
header_names.push_back(WebString::FromLatin1(name));
return header_names;
}
bool IsForbiddenHeaderName(const String& name) {
- CString utf8_name = name.Utf8();
- return network::cors::IsForbiddenHeader(
- std::string(utf8_name.data(), utf8_name.length()));
+ return network::cors::IsForbiddenHeader(WebString(name).Latin1());
}
-bool ContainsOnlyCORSSafelistedHeaders(const HTTPHeaderMap& header_map) {
- Vector<String> header_names = CORSUnsafeRequestHeaderNames(header_map);
+bool ContainsOnlyCorsSafelistedHeaders(const HTTPHeaderMap& header_map) {
+ Vector<String> header_names = CorsUnsafeRequestHeaderNames(header_map);
return header_names.IsEmpty();
}
-bool ContainsOnlyCORSSafelistedOrForbiddenHeaders(
+bool ContainsOnlyCorsSafelistedOrForbiddenHeaders(
const HTTPHeaderMap& headers) {
Vector<String> header_names;
@@ -281,7 +341,7 @@ bool ContainsOnlyCORSSafelistedOrForbiddenHeaders(
}
// |is_revalidating| is not needed for blink-side CORS.
constexpr bool is_revalidating = false;
- return network::cors::CORSUnsafeNotForbiddenRequestHeaderNames(
+ return network::cors::CorsUnsafeNotForbiddenRequestHeaderNames(
in, is_revalidating)
.empty();
}
@@ -290,11 +350,11 @@ bool IsOkStatus(int status) {
return network::cors::IsOkStatus(status);
}
-bool CalculateCORSFlag(const KURL& url,
+bool CalculateCorsFlag(const KURL& url,
const SecurityOrigin* origin,
network::mojom::FetchRequestMode request_mode) {
if (request_mode == network::mojom::FetchRequestMode::kNavigate ||
- request_mode == network::mojom::FetchRequestMode::kNoCORS) {
+ request_mode == network::mojom::FetchRequestMode::kNoCors) {
return false;
}
// CORS needs a proper origin (including a unique opaque origin). If the
@@ -303,6 +363,69 @@ bool CalculateCORSFlag(const KURL& url,
return !origin->CanReadContent(url);
}
-} // namespace CORS
+WebHTTPHeaderSet ExtractCorsExposedHeaderNamesList(
+ network::mojom::FetchCredentialsMode credentials_mode,
+ const ResourceResponse& response) {
+ // If a response was fetched via a service worker, it will always have
+ // CorsExposedHeaderNames set from the Access-Control-Expose-Headers header.
+ // For requests that didn't come from a service worker, just parse the CORS
+ // header.
+ if (response.WasFetchedViaServiceWorker()) {
+ WebHTTPHeaderSet header_set;
+ for (const auto& header : response.CorsExposedHeaderNames())
+ header_set.emplace(header.Ascii().data(), header.Ascii().length());
+ return header_set;
+ }
+
+ WebHTTPHeaderSet header_set;
+ HTTPHeaderNameListParser parser(response.HttpHeaderField(
+ WebString(http_names::kAccessControlExposeHeaders)));
+ parser.Parse(header_set);
+
+ if (credentials_mode != network::mojom::FetchCredentialsMode::kInclude &&
+ header_set.find("*") != header_set.end()) {
+ header_set.clear();
+ for (const auto& header : response.HttpHeaderFields()) {
+ CString name = header.key.Ascii();
+ header_set.emplace(name.data(), name.length());
+ }
+ }
+ return header_set;
+}
+
+bool IsOnAccessControlResponseHeaderWhitelist(const String& name) {
+ DEFINE_THREAD_SAFE_STATIC_LOCAL(
+ WebHTTPHeaderSet, allowed_cross_origin_response_headers,
+ ({
+ "cache-control", "content-language", "content-type", "expires",
+ "last-modified", "pragma",
+ }));
+ return allowed_cross_origin_response_headers.find(name.Ascii().data()) !=
+ allowed_cross_origin_response_headers.end();
+}
+
+// In the spec, https://fetch.spec.whatwg.org/#ref-for-concept-request-mode,
+// No-CORS mode is highly discouraged from using it for new features. Only
+// legacy usages for backward compatibility are allowed except for well-designed
+// usages over the fetch API.
+bool IsNoCorsAllowedContext(mojom::RequestContextType context) {
+ switch (context) {
+ case mojom::RequestContextType::AUDIO:
+ case mojom::RequestContextType::FAVICON:
+ case mojom::RequestContextType::FETCH:
+ case mojom::RequestContextType::IMAGE:
+ case mojom::RequestContextType::OBJECT:
+ case mojom::RequestContextType::PLUGIN:
+ case mojom::RequestContextType::SCRIPT:
+ case mojom::RequestContextType::SHARED_WORKER:
+ case mojom::RequestContextType::VIDEO:
+ case mojom::RequestContextType::WORKER:
+ return true;
+ default:
+ return false;
+ }
+}
+
+} // namespace cors
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/cors/cors.h b/chromium/third_party/blink/renderer/platform/loader/cors/cors.h
index de2f73f4aae..425930b9fb4 100644
--- a/chromium/third_party/blink/renderer/platform/loader/cors/cors.h
+++ b/chromium/third_party/blink/renderer/platform/loader/cors/cors.h
@@ -9,6 +9,8 @@
#include "services/network/public/cpp/cors/cors_error_status.h"
#include "services/network/public/mojom/cors.mojom-shared.h"
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/platform/web_http_header_set.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -17,48 +19,49 @@ namespace blink {
class HTTPHeaderMap;
class KURL;
+class ResourceResponse;
class SecurityOrigin;
-enum class CORSFlag : uint8_t {
+enum class CorsFlag : uint8_t {
Unset,
Set,
};
// CORS related utility functions.
-namespace CORS {
+namespace cors {
// Thin wrapper functions below are for calling ::network::cors functions from
// Blink core. Once Out-of-renderer CORS is enabled, following functions will
// be removed.
-PLATFORM_EXPORT base::Optional<network::CORSErrorStatus> CheckAccess(
+PLATFORM_EXPORT base::Optional<network::CorsErrorStatus> CheckAccess(
const KURL&,
const int response_status_code,
const HTTPHeaderMap&,
network::mojom::FetchCredentialsMode,
const SecurityOrigin&);
-PLATFORM_EXPORT base::Optional<network::CORSErrorStatus> CheckPreflightAccess(
+PLATFORM_EXPORT base::Optional<network::CorsErrorStatus> CheckPreflightAccess(
const KURL&,
const int response_status_code,
const HTTPHeaderMap&,
network::mojom::FetchCredentialsMode,
const SecurityOrigin&);
-PLATFORM_EXPORT base::Optional<network::CORSErrorStatus> CheckRedirectLocation(
+PLATFORM_EXPORT base::Optional<network::CorsErrorStatus> CheckRedirectLocation(
const KURL&,
network::mojom::FetchRequestMode,
const SecurityOrigin*,
- CORSFlag);
+ CorsFlag);
-PLATFORM_EXPORT base::Optional<network::mojom::CORSError> CheckPreflight(
+PLATFORM_EXPORT base::Optional<network::mojom::CorsError> CheckPreflight(
const int preflight_response_status_code);
-PLATFORM_EXPORT base::Optional<network::CORSErrorStatus> CheckExternalPreflight(
+PLATFORM_EXPORT base::Optional<network::CorsErrorStatus> CheckExternalPreflight(
const HTTPHeaderMap&);
-PLATFORM_EXPORT bool IsCORSEnabledRequestMode(network::mojom::FetchRequestMode);
+PLATFORM_EXPORT bool IsCorsEnabledRequestMode(network::mojom::FetchRequestMode);
-PLATFORM_EXPORT base::Optional<network::CORSErrorStatus>
+PLATFORM_EXPORT base::Optional<network::CorsErrorStatus>
EnsurePreflightResultAndCacheOnSuccess(
const HTTPHeaderMap& response_header_map,
const String& origin,
@@ -78,7 +81,7 @@ PLATFORM_EXPORT network::mojom::FetchResponseType CalculateResponseTainting(
const KURL& url,
network::mojom::FetchRequestMode request_mode,
const SecurityOrigin* origin,
- CORSFlag cors_flag);
+ CorsFlag cors_flag);
PLATFORM_EXPORT bool CalculateCredentialsFlag(
network::mojom::FetchCredentialsMode credentials_mode,
@@ -86,17 +89,15 @@ PLATFORM_EXPORT bool CalculateCredentialsFlag(
// Thin wrapper functions that will not be removed even after out-of-renderer
// CORS is enabled.
-PLATFORM_EXPORT bool IsCORSSafelistedMethod(const String& method);
-PLATFORM_EXPORT bool IsCORSSafelistedContentType(const String&);
-PLATFORM_EXPORT bool IsCORSSafelistedHeader(const String& name,
- const String& value);
-PLATFORM_EXPORT bool IsNoCORSSafelistedHeader(const String& name,
+PLATFORM_EXPORT bool IsCorsSafelistedMethod(const String& method);
+PLATFORM_EXPORT bool IsCorsSafelistedContentType(const String&);
+PLATFORM_EXPORT bool IsNoCorsSafelistedHeader(const String& name,
const String& value);
-PLATFORM_EXPORT Vector<String> CORSUnsafeRequestHeaderNames(
+PLATFORM_EXPORT Vector<String> CorsUnsafeRequestHeaderNames(
const HTTPHeaderMap& headers);
PLATFORM_EXPORT bool IsForbiddenHeaderName(const String& name);
-PLATFORM_EXPORT bool ContainsOnlyCORSSafelistedHeaders(const HTTPHeaderMap&);
-PLATFORM_EXPORT bool ContainsOnlyCORSSafelistedOrForbiddenHeaders(
+PLATFORM_EXPORT bool ContainsOnlyCorsSafelistedHeaders(const HTTPHeaderMap&);
+PLATFORM_EXPORT bool ContainsOnlyCorsSafelistedOrForbiddenHeaders(
const HTTPHeaderMap&);
PLATFORM_EXPORT bool IsOkStatus(int status);
@@ -105,17 +106,26 @@ PLATFORM_EXPORT bool IsOkStatus(int status);
// https://fetch.spec.whatwg.org/. This function is corresponding to the CORS
// flag setting logic in https://fetch.spec.whatwg.org/#main-fetch.
// This function can return true even when |request_mode| is |kSameOrigin|.
-// |origin| must not be nullptr when |request_mode| is neither |kNoCORS| nor
+// |origin| must not be nullptr when |request_mode| is neither |kNoCors| nor
// |kNavigate|.
-// This should be identical to CalculateCORSFlag defined in
+// This should be identical to CalculateCorsFlag defined in
// //services/network/cors/cors_url_loader.cc.
// This function will be removed when out-of-renderer CORS is enabled.
-PLATFORM_EXPORT bool CalculateCORSFlag(
+PLATFORM_EXPORT bool CalculateCorsFlag(
const KURL& url,
const SecurityOrigin* origin,
network::mojom::FetchRequestMode request_mode);
-} // namespace CORS
+PLATFORM_EXPORT WebHTTPHeaderSet
+ExtractCorsExposedHeaderNamesList(network::mojom::FetchCredentialsMode,
+ const ResourceResponse&);
+
+PLATFORM_EXPORT bool IsOnAccessControlResponseHeaderWhitelist(const String&);
+
+// Checks whether request mode 'no-cors' is allowed for a certain context.
+PLATFORM_EXPORT bool IsNoCorsAllowedContext(mojom::RequestContextType);
+
+} // namespace cors
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.cc b/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.cc
index f8d51600836..e20d4dd8dd4 100644
--- a/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.cc
@@ -19,7 +19,7 @@
namespace blink {
-namespace CORS {
+namespace cors {
namespace {
@@ -29,18 +29,18 @@ void Append(StringBuilder& builder, std::initializer_list<StringView> views) {
}
}
-bool IsPreflightError(network::mojom::CORSError error_code) {
+bool IsPreflightError(network::mojom::CorsError error_code) {
switch (error_code) {
- case network::mojom::CORSError::kPreflightWildcardOriginNotAllowed:
- case network::mojom::CORSError::kPreflightMissingAllowOriginHeader:
- case network::mojom::CORSError::kPreflightMultipleAllowOriginValues:
- case network::mojom::CORSError::kPreflightInvalidAllowOriginValue:
- case network::mojom::CORSError::kPreflightAllowOriginMismatch:
- case network::mojom::CORSError::kPreflightInvalidAllowCredentials:
- case network::mojom::CORSError::kPreflightInvalidStatus:
- case network::mojom::CORSError::kPreflightDisallowedRedirect:
- case network::mojom::CORSError::kPreflightMissingAllowExternal:
- case network::mojom::CORSError::kPreflightInvalidAllowExternal:
+ case network::mojom::CorsError::kPreflightWildcardOriginNotAllowed:
+ case network::mojom::CorsError::kPreflightMissingAllowOriginHeader:
+ case network::mojom::CorsError::kPreflightMultipleAllowOriginValues:
+ case network::mojom::CorsError::kPreflightInvalidAllowOriginValue:
+ case network::mojom::CorsError::kPreflightAllowOriginMismatch:
+ case network::mojom::CorsError::kPreflightInvalidAllowCredentials:
+ case network::mojom::CorsError::kPreflightInvalidStatus:
+ case network::mojom::CorsError::kPreflightDisallowedRedirect:
+ case network::mojom::CorsError::kPreflightMissingAllowExternal:
+ case network::mojom::CorsError::kPreflightInvalidAllowExternal:
return true;
default:
return false;
@@ -49,7 +49,7 @@ bool IsPreflightError(network::mojom::CORSError error_code) {
} // namespace
-String GetErrorString(const network::CORSErrorStatus& status,
+String GetErrorString(const network::CorsErrorStatus& status,
const KURL& initial_request_url,
const KURL& last_request_url,
const SecurityOrigin& origin,
@@ -61,9 +61,9 @@ String GetErrorString(const network::CORSErrorStatus& status,
"response serves your needs, set the request's mode to 'no-cors' to "
"fetch the resource with CORS disabled.";
- using CORSError = network::mojom::CORSError;
+ using CorsError = network::mojom::CorsError;
const StringView hint(status.failed_parameter.data(),
- status.failed_parameter.size());
+ SafeCast<wtf_size_t>(status.failed_parameter.size()));
const char* resource_kind_raw =
Resource::ResourceTypeToString(resource_type, initiator_name);
@@ -86,93 +86,93 @@ String GetErrorString(const network::CORSErrorStatus& status,
}
switch (status.cors_error) {
- case CORSError::kDisallowedByMode:
+ case CorsError::kDisallowedByMode:
builder.Append("Cross origin requests are not allowed by request mode.");
break;
- case CORSError::kInvalidResponse:
+ case CorsError::kInvalidResponse:
builder.Append("The response is invalid.");
break;
- case CORSError::kWildcardOriginNotAllowed:
- case CORSError::kPreflightWildcardOriginNotAllowed:
+ case CorsError::kWildcardOriginNotAllowed:
+ case CorsError::kPreflightWildcardOriginNotAllowed:
builder.Append(
"The value of the 'Access-Control-Allow-Origin' header in the "
"response must not be the wildcard '*' when the request's "
"credentials mode is 'include'.");
- if (initiator_name == FetchInitiatorTypeNames::xmlhttprequest) {
+ if (initiator_name == fetch_initiator_type_names::kXmlhttprequest) {
builder.Append(
" The credentials mode of requests initiated by the "
"XMLHttpRequest is controlled by the withCredentials attribute.");
}
break;
- case CORSError::kMissingAllowOriginHeader:
- case CORSError::kPreflightMissingAllowOriginHeader:
+ case CorsError::kMissingAllowOriginHeader:
+ case CorsError::kPreflightMissingAllowOriginHeader:
builder.Append(
"No 'Access-Control-Allow-Origin' header is present on the "
"requested resource.");
- if (initiator_name == FetchInitiatorTypeNames::fetch) {
+ if (initiator_name == fetch_initiator_type_names::kFetch) {
builder.Append(
" If an opaque response serves your needs, set the request's "
"mode to 'no-cors' to fetch the resource with CORS disabled.");
}
break;
- case CORSError::kMultipleAllowOriginValues:
- case CORSError::kPreflightMultipleAllowOriginValues:
+ case CorsError::kMultipleAllowOriginValues:
+ case CorsError::kPreflightMultipleAllowOriginValues:
Append(builder,
{"The 'Access-Control-Allow-Origin' header contains multiple "
"values '",
hint, "', but only one is allowed."});
- if (initiator_name == FetchInitiatorTypeNames::fetch)
+ if (initiator_name == fetch_initiator_type_names::kFetch)
builder.Append(kNoCorsInformation);
break;
- case CORSError::kInvalidAllowOriginValue:
- case CORSError::kPreflightInvalidAllowOriginValue:
+ case CorsError::kInvalidAllowOriginValue:
+ case CorsError::kPreflightInvalidAllowOriginValue:
Append(builder, {"The 'Access-Control-Allow-Origin' header contains the "
"invalid value '",
hint, "'."});
- if (initiator_name == FetchInitiatorTypeNames::fetch)
+ if (initiator_name == fetch_initiator_type_names::kFetch)
builder.Append(kNoCorsInformation);
break;
- case CORSError::kAllowOriginMismatch:
- case CORSError::kPreflightAllowOriginMismatch:
+ case CorsError::kAllowOriginMismatch:
+ case CorsError::kPreflightAllowOriginMismatch:
Append(builder, {"The 'Access-Control-Allow-Origin' header has a value '",
hint, "' that is not equal to the supplied origin."});
- if (initiator_name == FetchInitiatorTypeNames::fetch)
+ if (initiator_name == fetch_initiator_type_names::kFetch)
builder.Append(kNoCorsInformation);
break;
- case CORSError::kInvalidAllowCredentials:
- case CORSError::kPreflightInvalidAllowCredentials:
+ case CorsError::kInvalidAllowCredentials:
+ case CorsError::kPreflightInvalidAllowCredentials:
Append(builder,
{"The value of the 'Access-Control-Allow-Credentials' header in "
"the response is '",
hint,
"' which must be 'true' when the request's credentials mode is "
"'include'."});
- if (initiator_name == FetchInitiatorTypeNames::xmlhttprequest) {
+ if (initiator_name == fetch_initiator_type_names::kXmlhttprequest) {
builder.Append(
" The credentials mode of requests initiated by the "
"XMLHttpRequest is controlled by the withCredentials "
"attribute.");
}
break;
- case CORSError::kCORSDisabledScheme:
+ case CorsError::kCorsDisabledScheme:
Append(builder,
{"Cross origin requests are only supported for protocol schemes: ",
- SchemeRegistry::ListOfCORSEnabledURLSchemes(), "."});
+ SchemeRegistry::ListOfCorsEnabledURLSchemes(), "."});
break;
- case CORSError::kPreflightInvalidStatus:
+ case CorsError::kPreflightInvalidStatus:
builder.Append("It does not have HTTP ok status.");
break;
- case CORSError::kPreflightDisallowedRedirect:
+ case CorsError::kPreflightDisallowedRedirect:
builder.Append("Redirect is not allowed for a preflight request.");
break;
- case CORSError::kPreflightMissingAllowExternal:
+ case CorsError::kPreflightMissingAllowExternal:
builder.Append(
"No 'Access-Control-Allow-External' header was present in the "
"preflight response for this external request (This is an "
"experimental header which is defined in "
"'https://wicg.github.io/cors-rfc1918/').");
break;
- case CORSError::kPreflightInvalidAllowExternal:
+ case CorsError::kPreflightInvalidAllowExternal:
Append(builder,
{"The 'Access-Control-Allow-External' header in the preflight "
"response for this external request had a value of '",
@@ -180,27 +180,27 @@ String GetErrorString(const network::CORSErrorStatus& status,
"', not 'true' (This is an experimental header which is defined "
"in 'https://wicg.github.io/cors-rfc1918/')."});
break;
- case CORSError::kInvalidAllowMethodsPreflightResponse:
+ case CorsError::kInvalidAllowMethodsPreflightResponse:
builder.Append(
"Cannot parse Access-Control-Allow-Methods response header field in "
"preflight response.");
break;
- case CORSError::kInvalidAllowHeadersPreflightResponse:
+ case CorsError::kInvalidAllowHeadersPreflightResponse:
builder.Append(
"Cannot parse Access-Control-Allow-Headers response header field in "
"preflight response.");
break;
- case CORSError::kMethodDisallowedByPreflightResponse:
+ case CorsError::kMethodDisallowedByPreflightResponse:
Append(builder, {"Method ", hint,
" is not allowed by Access-Control-Allow-Methods in "
"preflight response."});
break;
- case CORSError::kHeaderDisallowedByPreflightResponse:
+ case CorsError::kHeaderDisallowedByPreflightResponse:
Append(builder, {"Request header field ", hint,
" is not allowed by "
"Access-Control-Allow-Headers in preflight response."});
break;
- case CORSError::kRedirectContainsCredentials:
+ case CorsError::kRedirectContainsCredentials:
Append(builder, {"Redirect location '", hint,
"' contains a username and password, which is "
"disallowed for cross-origin requests."});
@@ -209,6 +209,6 @@ String GetErrorString(const network::CORSErrorStatus& status,
return builder.ToString();
}
-} // namespace CORS
+} // namespace cors
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.h b/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.h
index e4f86806ed4..f9e8664f175 100644
--- a/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.h
+++ b/chromium/third_party/blink/renderer/platform/loader/cors/cors_error_string.h
@@ -19,18 +19,18 @@ class SecurityOrigin;
enum class ResourceType : uint8_t;
// CORS error strings related utility functions.
-namespace CORS {
+namespace cors {
-// Stringify CORSError mainly for inspector messages. Generated string should
+// Stringify CorsError mainly for inspector messages. Generated string should
// not be exposed to JavaScript for security reasons.
-PLATFORM_EXPORT String GetErrorString(const network::CORSErrorStatus& status,
+PLATFORM_EXPORT String GetErrorString(const network::CorsErrorStatus& status,
const KURL& initial_request_url,
const KURL& last_request_url,
const SecurityOrigin& origin,
ResourceType resource_type,
const AtomicString& initiator_name);
-} // namespace CORS
+} // namespace cors
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/exported/web_cors_test.cc b/chromium/third_party/blink/renderer/platform/loader/cors/cors_test.cc
index f724d12c7d1..718a51fe3de 100644
--- a/chromium/third_party/blink/renderer/platform/exported/web_cors_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/cors/cors_test.cc
@@ -2,18 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/public/platform/web_cors.h"
+#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/platform/web_cors.h"
-#include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
namespace blink {
namespace {
-class CORSExposedHeadersTest : public testing::Test {
+class CorsExposedHeadersTest : public testing::Test {
public:
using CredentialsMode = network::mojom::FetchCredentialsMode;
@@ -22,12 +20,11 @@ class CORSExposedHeadersTest : public testing::Test {
ResourceResponse response;
response.AddHTTPHeaderField("access-control-expose-headers", header);
- return WebCORS::ExtractCorsExposedHeaderNamesList(
- credentials_mode, WrappedResourceResponse(response));
+ return cors::ExtractCorsExposedHeaderNamesList(credentials_mode, response);
}
};
-TEST_F(CORSExposedHeadersTest, ValidInput) {
+TEST_F(CorsExposedHeadersTest, ValidInput) {
EXPECT_EQ(Parse(CredentialsMode::kOmit, "valid"),
WebHTTPHeaderSet({"valid"}));
@@ -40,14 +37,14 @@ TEST_F(CORSExposedHeadersTest, ValidInput) {
WebHTTPHeaderSet({"a"}));
}
-TEST_F(CORSExposedHeadersTest, DuplicatedEntries) {
+TEST_F(CorsExposedHeadersTest, DuplicatedEntries) {
EXPECT_EQ(Parse(CredentialsMode::kOmit, "a, a"), WebHTTPHeaderSet{"a"});
EXPECT_EQ(Parse(CredentialsMode::kOmit, "a, a, b"),
WebHTTPHeaderSet({"a", "b"}));
}
-TEST_F(CORSExposedHeadersTest, InvalidInput) {
+TEST_F(CorsExposedHeadersTest, InvalidInput) {
EXPECT_TRUE(Parse(CredentialsMode::kOmit, "not valid").empty());
EXPECT_TRUE(Parse(CredentialsMode::kOmit, "///").empty());
@@ -72,7 +69,7 @@ TEST_F(CORSExposedHeadersTest, InvalidInput) {
.empty());
}
-TEST_F(CORSExposedHeadersTest, Wildcard) {
+TEST_F(CorsExposedHeadersTest, Wildcard) {
ResourceResponse response;
response.AddHTTPHeaderField("access-control-expose-headers", "a, b, *");
response.AddHTTPHeaderField("b", "-");
@@ -81,17 +78,16 @@ TEST_F(CORSExposedHeadersTest, Wildcard) {
response.AddHTTPHeaderField("*", "-");
EXPECT_EQ(
- WebCORS::ExtractCorsExposedHeaderNamesList(
- CredentialsMode::kOmit, WrappedResourceResponse(response)),
+ cors::ExtractCorsExposedHeaderNamesList(CredentialsMode::kOmit, response),
WebHTTPHeaderSet({"access-control-expose-headers", "b", "c", "d", "*"}));
EXPECT_EQ(
- WebCORS::ExtractCorsExposedHeaderNamesList(
- CredentialsMode::kSameOrigin, WrappedResourceResponse(response)),
+ cors::ExtractCorsExposedHeaderNamesList(CredentialsMode::kSameOrigin,
+ response),
WebHTTPHeaderSet({"access-control-expose-headers", "b", "c", "d", "*"}));
}
-TEST_F(CORSExposedHeadersTest, Asterisk) {
+TEST_F(CorsExposedHeadersTest, Asterisk) {
ResourceResponse response;
response.AddHTTPHeaderField("access-control-expose-headers", "a, b, *");
response.AddHTTPHeaderField("b", "-");
@@ -99,8 +95,8 @@ TEST_F(CORSExposedHeadersTest, Asterisk) {
response.AddHTTPHeaderField("d", "-");
response.AddHTTPHeaderField("*", "-");
- EXPECT_EQ(WebCORS::ExtractCorsExposedHeaderNamesList(
- CredentialsMode::kInclude, WrappedResourceResponse(response)),
+ EXPECT_EQ(cors::ExtractCorsExposedHeaderNamesList(CredentialsMode::kInclude,
+ response),
WebHTTPHeaderSet({"a", "b", "*"}));
}
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/access_control_status.h b/chromium/third_party/blink/renderer/platform/loader/fetch/access_control_status.h
deleted file mode 100644
index 56de552dafa..00000000000
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/access_control_status.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_ACCESS_CONTROL_STATUS_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_ACCESS_CONTROL_STATUS_H_
-
-namespace blink {
-
-enum AccessControlStatus {
- kSharableCrossOrigin,
- kOpaqueResource
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_ACCESS_CONTROL_STATUS_H_
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer.h b/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer.h
index 8b3175fd537..91033647fd8 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer.h
@@ -36,7 +36,7 @@ class PLATFORM_EXPORT BufferingDataPipeWriter {
mojo::ScopedDataPipeProducerHandle handle_;
mojo::SimpleWatcher watcher_;
Deque<Vector<char>> buffer_;
- size_t front_written_size_ = 0;
+ wtf_size_t front_written_size_ = 0;
bool waiting_ = false;
bool finished_ = false;
};
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer_test.cc
index 4809d2179a8..98836354f03 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/buffering_data_pipe_writer_test.cc
@@ -31,21 +31,21 @@ TEST(BufferingDataPipeWriterTest, WriteMany) {
MojoResult result = mojo::CreateDataPipe(&options, &producer, &consumer);
ASSERT_EQ(MOJO_RESULT_OK, result);
- constexpr size_t total = kCapacity * 3;
- constexpr size_t writing_chunk_size = 5;
- constexpr size_t reading_chunk_size = 7;
+ constexpr wtf_size_t total = kCapacity * 3;
+ constexpr wtf_size_t writing_chunk_size = 5;
+ constexpr wtf_size_t reading_chunk_size = 7;
Vector<char> input, output;
- for (size_t i = 0; i < total; ++i)
+ for (wtf_size_t i = 0; i < total; ++i)
input.push_back(static_cast<char>(engine() % 26 + 'A'));
auto writer = std::make_unique<BufferingDataPipeWriter>(
std::move(producer), platform->test_task_runner().get());
- for (size_t i = 0; i < total;) {
+ for (wtf_size_t i = 0; i < total;) {
// We use a temporary buffer to check that the buffer is copied immediately.
char temp[writing_chunk_size] = {};
- size_t size = std::min(total - i, writing_chunk_size);
+ wtf_size_t size = std::min(total - i, writing_chunk_size);
std::copy(input.data() + i, input.data() + i + size, temp);
ASSERT_TRUE(writer->Write(temp, size));
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.cc
index 563a6742750..1edafd9beac 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.cc
@@ -12,7 +12,8 @@ scoped_refptr<CachedMetadata> CachedMetadata::CreateFromSerializedData(
const char* data,
size_t size) {
// Ensure the data is big enough, otherwise discard the data.
- if (size < kCachedMetaDataStart) {
+ if (size < kCachedMetaDataStart ||
+ size > std::numeric_limits<wtf_size_t>::max()) {
return nullptr;
}
// Ensure the marker matches, otherwise discard the data.
@@ -20,10 +21,10 @@ scoped_refptr<CachedMetadata> CachedMetadata::CreateFromSerializedData(
CachedMetadataHandler::kSingleEntry) {
return nullptr;
}
- return base::AdoptRef(new CachedMetadata(data, size));
+ return base::AdoptRef(
+ new CachedMetadata(data, static_cast<wtf_size_t>(size)));
}
-
-CachedMetadata::CachedMetadata(const char* data, size_t size) {
+CachedMetadata::CachedMetadata(const char* data, wtf_size_t size) {
// Serialized metadata should have non-empty data.
DCHECK_GT(size, kCachedMetaDataStart);
DCHECK(data);
@@ -37,7 +38,7 @@ CachedMetadata::CachedMetadata(const char* data, size_t size) {
CachedMetadata::CachedMetadata(uint32_t data_type_id,
const char* data,
- size_t size) {
+ wtf_size_t size) {
// Don't allow an ID of 0, it is used internally to indicate errors.
DCHECK(data_type_id);
DCHECK(data);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.h b/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.h
index 1763b23fd42..2657ea0972c 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/cached_metadata.h
@@ -36,6 +36,7 @@
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -54,7 +55,8 @@ class PLATFORM_EXPORT CachedMetadata : public RefCounted<CachedMetadata> {
static scoped_refptr<CachedMetadata> Create(uint32_t data_type_id,
const char* data,
size_t size) {
- return base::AdoptRef(new CachedMetadata(data_type_id, data, size));
+ return base::AdoptRef(
+ new CachedMetadata(data_type_id, data, SafeCast<wtf_size_t>(size)));
}
static scoped_refptr<CachedMetadata> CreateFromSerializedData(
@@ -76,14 +78,14 @@ class PLATFORM_EXPORT CachedMetadata : public RefCounted<CachedMetadata> {
return serialized_data_.data() + kCachedMetaDataStart;
}
- size_t size() const {
+ uint32_t size() const {
DCHECK_GE(serialized_data_.size(), kCachedMetaDataStart);
return serialized_data_.size() - kCachedMetaDataStart;
}
private:
- CachedMetadata(const char* data, size_t);
- CachedMetadata(uint32_t data_type_id, const char* data, size_t);
+ CachedMetadata(const char* data, wtf_size_t);
+ CachedMetadata(uint32_t data_type_id, const char* data, wtf_size_t);
// Since the serialization format supports random access, storing it in
// serialized form avoids need for a copy during serialization.
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc
index 20ef7e619fe..b79e782daf9 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc
@@ -34,18 +34,15 @@ void ParseAcceptChHeader(const String& header_value,
enabled_hints.SetIsEnabled(
mojom::WebClientHintsType::kRtt,
- enabled_hints.IsEnabled(mojom::WebClientHintsType::kRtt) &&
- RuntimeEnabledFeatures::NetInfoRttHeaderEnabled());
+ enabled_hints.IsEnabled(mojom::WebClientHintsType::kRtt));
enabled_hints.SetIsEnabled(
mojom::WebClientHintsType::kDownlink,
- enabled_hints.IsEnabled(mojom::WebClientHintsType::kDownlink) &&
- RuntimeEnabledFeatures::NetInfoDownlinkHeaderEnabled());
+ enabled_hints.IsEnabled(mojom::WebClientHintsType::kDownlink));
enabled_hints.SetIsEnabled(
mojom::WebClientHintsType::kEct,
- enabled_hints.IsEnabled(mojom::WebClientHintsType::kEct) &&
- RuntimeEnabledFeatures::NetInfoEffectiveTypeHeaderEnabled());
+ enabled_hints.IsEnabled(mojom::WebClientHintsType::kEct));
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h
index cfabe9a2ec4..9e6f23327bd 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h
@@ -5,12 +5,13 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_FETCH_CLIENT_SETTINGS_OBJECT_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_FETCH_CLIENT_SETTINGS_OBJECT_H_
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/platform/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/loader/fetch/https_state.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -41,12 +42,15 @@ class PLATFORM_EXPORT FetchClientSettingsObject
// "The default referrer policy for fetches performed using this environment
// settings object as a request client."
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-settings-object-referrer-policy
- virtual ReferrerPolicy GetReferrerPolicy() const = 0;
+ virtual network::mojom::ReferrerPolicy GetReferrerPolicy() const = 0;
// "referrerURL" used in the "Determine request's Referrer" algorithm:
// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
virtual const String GetOutgoingReferrer() const = 0;
+ // https://html.spec.whatwg.org/multipage/webappapis.html#https-state
+ virtual HttpsState GetHttpsState() const = 0;
+
virtual void Trace(Visitor*) {}
};
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.cc
index 40d15d1acb0..38c1829bd45 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.cc
@@ -13,16 +13,19 @@ FetchClientSettingsObjectSnapshot::FetchClientSettingsObjectSnapshot(
: FetchClientSettingsObjectSnapshot(data->base_url,
data->security_origin,
data->referrer_policy,
- data->outgoing_referrer) {}
+ data->outgoing_referrer,
+ data->https_state) {}
FetchClientSettingsObjectSnapshot::FetchClientSettingsObjectSnapshot(
const KURL& base_url,
const scoped_refptr<const SecurityOrigin> security_origin,
- ReferrerPolicy referrer_policy,
- const String& outgoing_referrer)
+ network::mojom::ReferrerPolicy referrer_policy,
+ const String& outgoing_referrer,
+ HttpsState https_state)
: base_url_(base_url),
security_origin_(std::move(security_origin)),
referrer_policy_(referrer_policy),
- outgoing_referrer_(outgoing_referrer) {}
+ outgoing_referrer_(outgoing_referrer),
+ https_state_(https_state) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h
index 4a5ec3595ba..09290decad4 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h
@@ -5,11 +5,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_FETCH_CLIENT_SETTINGS_OBJECT_SNAPSHOT_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_FETCH_CLIENT_SETTINGS_OBJECT_SNAPSHOT_H_
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/platform/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -30,17 +30,20 @@ struct CrossThreadFetchClientSettingsObjectData {
CrossThreadFetchClientSettingsObjectData(
KURL base_url,
scoped_refptr<const SecurityOrigin> security_origin,
- ReferrerPolicy referrer_policy,
- String outgoing_referrer)
+ network::mojom::ReferrerPolicy referrer_policy,
+ String outgoing_referrer,
+ HttpsState https_state)
: base_url(std::move(base_url)),
security_origin(std::move(security_origin)),
referrer_policy(referrer_policy),
- outgoing_referrer(std::move(outgoing_referrer)) {}
+ outgoing_referrer(std::move(outgoing_referrer)),
+ https_state(https_state) {}
- KURL base_url;
- scoped_refptr<const SecurityOrigin> security_origin;
- ReferrerPolicy referrer_policy;
- String outgoing_referrer;
+ const KURL base_url;
+ const scoped_refptr<const SecurityOrigin> security_origin;
+ const network::mojom::ReferrerPolicy referrer_policy;
+ const String outgoing_referrer;
+ const HttpsState https_state;
};
// This takes a partial snapshot of the execution context's states so that an
@@ -61,8 +64,9 @@ class PLATFORM_EXPORT FetchClientSettingsObjectSnapshot final
FetchClientSettingsObjectSnapshot(
const KURL& base_url,
const scoped_refptr<const SecurityOrigin> security_origin,
- ReferrerPolicy referrer_policy,
- const String& outgoing_referrer);
+ network::mojom::ReferrerPolicy referrer_policy,
+ const String& outgoing_referrer,
+ HttpsState https_state);
~FetchClientSettingsObjectSnapshot() override = default;
@@ -70,23 +74,27 @@ class PLATFORM_EXPORT FetchClientSettingsObjectSnapshot final
const SecurityOrigin* GetSecurityOrigin() const override {
return security_origin_.get();
}
- ReferrerPolicy GetReferrerPolicy() const override { return referrer_policy_; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const override {
+ return referrer_policy_;
+ }
const String GetOutgoingReferrer() const override {
return outgoing_referrer_;
}
+ HttpsState GetHttpsState() const override { return https_state_; }
// Gets a copy of the data suitable for passing to another thread.
std::unique_ptr<CrossThreadFetchClientSettingsObjectData> CopyData() const {
return std::make_unique<CrossThreadFetchClientSettingsObjectData>(
base_url_.Copy(), security_origin_->IsolatedCopy(), referrer_policy_,
- outgoing_referrer_.IsolatedCopy());
+ outgoing_referrer_.IsolatedCopy(), https_state_);
}
private:
const KURL base_url_;
const scoped_refptr<const SecurityOrigin> security_origin_;
- const ReferrerPolicy referrer_policy_;
+ const network::mojom::ReferrerPolicy referrer_policy_;
const String outgoing_referrer_;
+ const HttpsState https_state_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc
index aae54cb6290..b54b55038a0 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc
@@ -30,14 +30,46 @@
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/platform_probe_sink.h"
#include "third_party/blink/renderer/platform/probe/platform_trace_events_agent.h"
namespace blink {
+namespace {
+
+class NullFetchContext final : public FetchContext {
+ public:
+ explicit NullFetchContext(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : FetchContext(std::move(task_runner)),
+ fetch_client_settings_object_(
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ KURL(),
+ nullptr /* security_origin */,
+ network::mojom::ReferrerPolicy::kDefault,
+ String(),
+ HttpsState::kNone)) {}
+
+ const FetchClientSettingsObject* GetFetchClientSettingsObject()
+ const override {
+ return fetch_client_settings_object_;
+ }
+
+ void Trace(blink::Visitor* visitor) override {
+ visitor->Trace(fetch_client_settings_object_);
+ FetchContext::Trace(visitor);
+ }
+
+ private:
+ const Member<const FetchClientSettingsObject> fetch_client_settings_object_;
+};
+
+} // namespace
+
FetchContext& FetchContext::NullInstance(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
- return *(new FetchContext(std::move(task_runner)));
+ return *(new NullFetchContext(std::move(task_runner)));
}
FetchContext::FetchContext(
@@ -86,9 +118,9 @@ void FetchContext::DispatchDidReceiveResponse(
Resource*,
ResourceResponseType) {}
-void FetchContext::DispatchDidReceiveData(unsigned long, const char*, int) {}
+void FetchContext::DispatchDidReceiveData(unsigned long, const char*, size_t) {}
-void FetchContext::DispatchDidReceiveEncodedData(unsigned long, int) {}
+void FetchContext::DispatchDidReceiveEncodedData(unsigned long, size_t) {}
void FetchContext::DispatchDidDownloadToBlob(unsigned long identifier,
BlobDataHandle*) {}
@@ -112,6 +144,8 @@ void FetchContext::RecordLoadingActivity(
void FetchContext::DidLoadResource(Resource*) {}
+void FetchContext::DidObserveLoadingBehavior(WebLoadingBehaviorFlag) {}
+
void FetchContext::AddResourceTiming(const ResourceTimingInfo&) {}
void FetchContext::AddInfoConsoleMessage(const String&, LogSource) const {}
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.h b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.h
index 7a8b684e0fa..60875d2b2a3 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_context.h
@@ -43,6 +43,7 @@
#include "third_party/blink/public/platform/resource_request_blocked_reason.h"
#include "third_party/blink/public/platform/scheduler/web_resource_loading_task_runner_handle.h"
#include "third_party/blink/public/platform/web_application_cache_host.h"
+#include "third_party/blink/public/platform/web_loading_behavior_flag.h"
#include "third_party/blink/public/platform/web_url_loader.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -61,6 +62,7 @@
namespace blink {
class ClientHintsPreferences;
+class FetchClientSettingsObject;
class KURL;
class MHTMLArchive;
class PlatformProbeSink;
@@ -106,6 +108,9 @@ class PLATFORM_EXPORT FetchContext
virtual void AddAdditionalRequestHeaders(ResourceRequest&, FetchResourceType);
+ virtual const FetchClientSettingsObject* GetFetchClientSettingsObject()
+ const = 0;
+
// Called when the ResourceFetcher observes a data: URI load that contains an
// octothorpe ('#') character. This is a temporary method to support an Intent
// to Deprecate for spec incompliant handling of '#' characters in data URIs.
@@ -152,9 +157,9 @@ class PLATFORM_EXPORT FetchContext
ResourceResponseType);
virtual void DispatchDidReceiveData(unsigned long identifier,
const char* data,
- int data_length);
+ size_t data_length);
virtual void DispatchDidReceiveEncodedData(unsigned long identifier,
- int encoded_data_length);
+ size_t encoded_data_length);
virtual void DispatchDidDownloadToBlob(unsigned long identifier,
BlobDataHandle*);
virtual void DispatchDidFinishLoading(unsigned long identifier,
@@ -177,6 +182,7 @@ class PLATFORM_EXPORT FetchContext
const AtomicString& fetch_initiator_name);
virtual void DidLoadResource(Resource*);
+ virtual void DidObserveLoadingBehavior(WebLoadingBehaviorFlag);
virtual void AddResourceTiming(const ResourceTimingInfo&);
virtual bool AllowImage(bool, const KURL&) const { return false; }
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.json5 b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.json5
index e7c2bb03ec4..237e54878ee 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.json5
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "FetchInitiatorType",
+ namespace: "fetch_initiator_type_names",
export: "PLATFORM_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.cc
index d704559189f..497d88babc2 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/fetch_parameters.cc
@@ -75,7 +75,7 @@ void FetchParameters::SetCrossOriginAccessControl(
// Currently FetchParametersMode is only used when the request goes to
// Service Worker.
resource_request_.SetFetchRequestMode(
- network::mojom::FetchRequestMode::kCORS);
+ network::mojom::FetchRequestMode::kCors);
resource_request_.SetFetchCredentialsMode(credentials_mode);
resource_request_.SetRequestorOrigin(origin);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.cc
index 6d4b6d9ef2b..61413dc58ca 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.cc
@@ -47,8 +47,8 @@ static const float kCTargetPrunePercentage = .95f;
MemoryCache* GetMemoryCache() {
DCHECK(WTF::IsMainThread());
if (!g_memory_cache) {
- g_memory_cache = new Persistent<MemoryCache>(MemoryCache::Create(
- Platform::Current()->MainThread()->GetTaskRunner()));
+ g_memory_cache = new Persistent<MemoryCache>(
+ MemoryCache::Create(Thread::MainThread()->GetTaskRunner()));
}
return g_memory_cache->Get();
}
@@ -93,7 +93,7 @@ inline MemoryCache::MemoryCache(
MemoryCache* MemoryCache::Create(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
- return new MemoryCache(std::move(task_runner));
+ return MakeGarbageCollected<MemoryCache>(std::move(task_runner));
}
MemoryCache::~MemoryCache() = default;
@@ -124,8 +124,8 @@ String MemoryCache::DefaultCacheIdentifier() {
MemoryCache::ResourceMap* MemoryCache::EnsureResourceMap(
const String& cache_identifier) {
if (!resource_maps_.Contains(cache_identifier)) {
- ResourceMapIndex::AddResult result =
- resource_maps_.insert(cache_identifier, new ResourceMap);
+ ResourceMapIndex::AddResult result = resource_maps_.insert(
+ cache_identifier, MakeGarbageCollected<ResourceMap>());
CHECK(result.is_new_entry);
}
return resource_maps_.at(cache_identifier);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.h b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.h
index d2b35e825e6..c452243a87a 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache.h
@@ -50,17 +50,18 @@ class KURL;
class MemoryCacheEntry final : public GarbageCollected<MemoryCacheEntry> {
public:
static MemoryCacheEntry* Create(Resource* resource) {
- return new MemoryCacheEntry(resource);
+ return MakeGarbageCollected<MemoryCacheEntry>(resource);
}
+
+ explicit MemoryCacheEntry(Resource* resource)
+ : last_decoded_access_time_(0.0), resource_(resource) {}
+
void Trace(blink::Visitor*);
Resource* GetResource() const { return resource_; }
double last_decoded_access_time_; // Used as a thrash guard
private:
- explicit MemoryCacheEntry(Resource* resource)
- : last_decoded_access_time_(0.0), resource_(resource) {}
-
void ClearResourceWeak(Visitor*);
WeakMember<Resource> resource_;
@@ -80,6 +81,8 @@ class PLATFORM_EXPORT MemoryCache final
public:
static MemoryCache* Create(
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
+
+ explicit MemoryCache(scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~MemoryCache() override;
void Trace(blink::Visitor*) override;
@@ -182,8 +185,6 @@ class PLATFORM_EXPORT MemoryCache final
ResourceMap* EnsureResourceMap(const String& cache_identifier);
ResourceMapIndex resource_maps_;
- explicit MemoryCache(scoped_refptr<base::SingleThreadTaskRunner> task_runner);
-
void AddInternal(ResourceMap*, MemoryCacheEntry*);
void RemoveInternal(ResourceMap*, const ResourceMap::iterator&);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_correctness_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_correctness_test.cc
index 6c75b4559ae..aa91bb45165 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_correctness_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_correctness_test.cc
@@ -283,11 +283,11 @@ TEST_F(MemoryCacheCorrectnessTest, ExpiredFromMaxAge) {
TEST_F(MemoryCacheCorrectnessTest, FreshButNoCache) {
ResourceResponse fresh200_nocache_response;
fresh200_nocache_response.SetHTTPStatusCode(200);
- fresh200_nocache_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_nocache_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_nocache_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_nocache_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
- fresh200_nocache_response.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ fresh200_nocache_response.SetHTTPHeaderField(http_names::kCacheControl,
"no-cache");
MockResource* fresh200_nocache =
@@ -303,7 +303,7 @@ TEST_F(MemoryCacheCorrectnessTest, FreshButNoCache) {
TEST_F(MemoryCacheCorrectnessTest, RequestWithNoCache) {
ResourceRequest no_cache_request;
- no_cache_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "no-cache");
+ no_cache_request.SetHTTPHeaderField(http_names::kCacheControl, "no-cache");
no_cache_request.SetRequestorOrigin(GetSecurityOrigin());
MockResource* no_cache_resource =
ResourceFromResourceRequest(no_cache_request);
@@ -314,11 +314,11 @@ TEST_F(MemoryCacheCorrectnessTest, RequestWithNoCache) {
TEST_F(MemoryCacheCorrectnessTest, FreshButNoStore) {
ResourceResponse fresh200_nostore_response;
fresh200_nostore_response.SetHTTPStatusCode(200);
- fresh200_nostore_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_nostore_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_nostore_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_nostore_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
- fresh200_nostore_response.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ fresh200_nostore_response.SetHTTPHeaderField(http_names::kCacheControl,
"no-store");
MockResource* fresh200_nostore =
@@ -334,7 +334,7 @@ TEST_F(MemoryCacheCorrectnessTest, FreshButNoStore) {
TEST_F(MemoryCacheCorrectnessTest, RequestWithNoStore) {
ResourceRequest no_store_request;
- no_store_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "no-store");
+ no_store_request.SetHTTPHeaderField(http_names::kCacheControl, "no-store");
no_store_request.SetRequestorOrigin(GetSecurityOrigin());
MockResource* no_store_resource =
ResourceFromResourceRequest(no_store_request);
@@ -348,11 +348,11 @@ TEST_F(MemoryCacheCorrectnessTest, DISABLED_FreshButMustRevalidate) {
ResourceResponse fresh200_must_revalidate_response;
fresh200_must_revalidate_response.SetHTTPStatusCode(200);
fresh200_must_revalidate_response.SetHTTPHeaderField(
- HTTPNames::Date, kOriginalRequestDateAsString);
+ http_names::kDate, kOriginalRequestDateAsString);
fresh200_must_revalidate_response.SetHTTPHeaderField(
- HTTPNames::Expires, kOneDayAfterOriginalRequest);
- fresh200_must_revalidate_response.SetHTTPHeaderField(HTTPNames::Cache_Control,
- "must-revalidate");
+ http_names::kExpires, kOneDayAfterOriginalRequest);
+ fresh200_must_revalidate_response.SetHTTPHeaderField(
+ http_names::kCacheControl, "must-revalidate");
MockResource* fresh200_must_revalidate =
ResourceFromResourceResponse(fresh200_must_revalidate_response);
@@ -376,11 +376,12 @@ TEST_F(MemoryCacheCorrectnessTest, FreshWithFreshRedirect) {
ResourceResponse fresh301_response(redirect_url);
fresh301_response.SetHTTPStatusCode(301);
- fresh301_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh301_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh301_response.SetHTTPHeaderField(HTTPNames::Location,
+ fresh301_response.SetHTTPHeaderField(http_names::kLocation,
kRedirectTargetUrlString);
- fresh301_response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=600");
+ fresh301_response.SetHTTPHeaderField(http_names::kCacheControl,
+ "max-age=600");
// Add the redirect to our request.
ResourceRequest redirect_request = ResourceRequest(redirect_target_url);
@@ -390,9 +391,9 @@ TEST_F(MemoryCacheCorrectnessTest, FreshWithFreshRedirect) {
// Add the final response to our request.
ResourceResponse fresh200_response(redirect_target_url);
fresh200_response.SetHTTPStatusCode(200);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
first_resource->SetResponse(fresh200_response);
@@ -417,9 +418,9 @@ TEST_F(MemoryCacheCorrectnessTest, FreshWithStaleRedirect) {
ResourceResponse stale301_response(redirect_url);
stale301_response.SetHTTPStatusCode(301);
- stale301_response.SetHTTPHeaderField(HTTPNames::Date,
+ stale301_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- stale301_response.SetHTTPHeaderField(HTTPNames::Location,
+ stale301_response.SetHTTPHeaderField(http_names::kLocation,
kRedirectTargetUrlString);
// Add the redirect to our request.
@@ -430,9 +431,9 @@ TEST_F(MemoryCacheCorrectnessTest, FreshWithStaleRedirect) {
// Add the final response to our request.
ResourceResponse fresh200_response(redirect_target_url);
fresh200_response.SetHTTPStatusCode(200);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
first_resource->SetResponse(fresh200_response);
@@ -447,7 +448,7 @@ TEST_F(MemoryCacheCorrectnessTest, FreshWithStaleRedirect) {
TEST_F(MemoryCacheCorrectnessTest, PostToSameURLTwice) {
ResourceRequest request1{KURL(kResourceURL)};
- request1.SetHTTPMethod(HTTPNames::POST);
+ request1.SetHTTPMethod(http_names::kPOST);
request1.SetRequestorOrigin(GetSecurityOrigin());
RawResource* resource1 =
RawResource::CreateForTest(request1, ResourceType::kRaw);
@@ -455,7 +456,7 @@ TEST_F(MemoryCacheCorrectnessTest, PostToSameURLTwice) {
AddResourceToMemoryCache(resource1);
ResourceRequest request2{KURL(kResourceURL)};
- request2.SetHTTPMethod(HTTPNames::POST);
+ request2.SetHTTPMethod(http_names::kPOST);
request2.SetRequestorOrigin(GetSecurityOrigin());
FetchParameters fetch2(request2);
RawResource* resource2 = RawResource::FetchSynchronously(fetch2, Fetcher());
@@ -472,11 +473,11 @@ TEST_F(MemoryCacheCorrectnessTest, 302RedirectNotImplicitlyFresh) {
ResourceResponse fresh302_response(redirect_url);
fresh302_response.SetHTTPStatusCode(302);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh302_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Last_Modified,
+ fresh302_response.SetHTTPHeaderField(http_names::kLastModified,
kOneDayBeforeOriginalRequest);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Location,
+ fresh302_response.SetHTTPHeaderField(http_names::kLocation,
kRedirectTargetUrlString);
// Add the redirect to our request.
@@ -487,9 +488,9 @@ TEST_F(MemoryCacheCorrectnessTest, 302RedirectNotImplicitlyFresh) {
// Add the final response to our request.
ResourceResponse fresh200_response(redirect_target_url);
fresh200_response.SetHTTPStatusCode(200);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
first_resource->SetResponse(fresh200_response);
@@ -513,10 +514,11 @@ TEST_F(MemoryCacheCorrectnessTest, 302RedirectExplicitlyFreshMaxAge) {
ResourceResponse fresh302_response(redirect_url);
fresh302_response.SetHTTPStatusCode(302);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh302_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=600");
- fresh302_response.SetHTTPHeaderField(HTTPNames::Location,
+ fresh302_response.SetHTTPHeaderField(http_names::kCacheControl,
+ "max-age=600");
+ fresh302_response.SetHTTPHeaderField(http_names::kLocation,
kRedirectTargetUrlString);
// Add the redirect to our request.
@@ -527,9 +529,9 @@ TEST_F(MemoryCacheCorrectnessTest, 302RedirectExplicitlyFreshMaxAge) {
// Add the final response to our request.
ResourceResponse fresh200_response(redirect_target_url);
fresh200_response.SetHTTPStatusCode(200);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
first_resource->SetResponse(fresh200_response);
@@ -553,11 +555,11 @@ TEST_F(MemoryCacheCorrectnessTest, 302RedirectExplicitlyFreshExpires) {
ResourceResponse fresh302_response(redirect_url);
fresh302_response.SetHTTPStatusCode(302);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh302_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh302_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
- fresh302_response.SetHTTPHeaderField(HTTPNames::Location,
+ fresh302_response.SetHTTPHeaderField(http_names::kLocation,
kRedirectTargetUrlString);
// Add the redirect to our request.
@@ -567,9 +569,9 @@ TEST_F(MemoryCacheCorrectnessTest, 302RedirectExplicitlyFreshExpires) {
// Add the final response to our request.
ResourceResponse fresh200_response(redirect_target_url);
fresh200_response.SetHTTPStatusCode(200);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Date,
+ fresh200_response.SetHTTPHeaderField(http_names::kDate,
kOriginalRequestDateAsString);
- fresh200_response.SetHTTPHeaderField(HTTPNames::Expires,
+ fresh200_response.SetHTTPHeaderField(http_names::kExpires,
kOneDayAfterOriginalRequest);
first_resource->SetResponse(fresh200_response);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_test.cc
index e8c592412e7..837ad739e84 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/memory_cache_test.cc
@@ -54,6 +54,10 @@ class FakeDecodedResource final : public Resource {
fetcher->RequestResource(params, Factory(), client));
}
+ FakeDecodedResource(const ResourceRequest& request,
+ const ResourceLoaderOptions& options)
+ : Resource(request, ResourceType::kMock, options) {}
+
void AppendData(const char* data, size_t len) override {
Resource::AppendData(data, len);
SetDecodedSize(this->size());
@@ -68,14 +72,10 @@ class FakeDecodedResource final : public Resource {
Resource* Create(const ResourceRequest& request,
const ResourceLoaderOptions& options) const override {
- return new FakeDecodedResource(request, options);
+ return MakeGarbageCollected<FakeDecodedResource>(request, options);
}
};
- FakeDecodedResource(const ResourceRequest& request,
- const ResourceLoaderOptions& options)
- : Resource(request, ResourceType::kMock, options) {}
-
void DestroyDecodedDataIfPossible() override { SetDecodedSize(0); }
};
@@ -93,10 +93,9 @@ class MemoryCacheTest : public testing::Test {
ResourceLoaderOptions options;
- return new FakeResource(request, type, options);
+ return MakeGarbageCollected<FakeResource>(request, type, options);
}
- private:
FakeResource(const ResourceRequest& request,
ResourceType type,
const ResourceLoaderOptions& options)
@@ -142,7 +141,8 @@ TEST_F(MemoryCacheTest, MAYBE_VeryLargeResourceAccounting) {
const size_t kResourceSize1 = kSizeMax / 16;
const size_t kResourceSize2 = kSizeMax / 20;
GetMemoryCache()->SetCapacity(kTotalCapacity);
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
FetchParameters params(ResourceRequest("data:text/html,"));
FakeDecodedResource* cached_resource =
FakeDecodedResource::Fetch(params, fetcher_, client);
@@ -211,7 +211,8 @@ static void TestResourcePruningLater(ResourceFetcher* fetcher,
resource1->AppendData(kData, 3u);
resource1->FinishForTest();
FetchParameters params2(ResourceRequest("data:text/html,resource2"));
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
Resource* resource2 = FakeDecodedResource::Fetch(params2, fetcher, client);
GetMemoryCache()->Remove(resource2);
if (!identifier2.IsEmpty())
@@ -270,8 +271,10 @@ static void TestClientRemoval(ResourceFetcher* fetcher,
const String& identifier2) {
GetMemoryCache()->SetCapacity(0);
const char kData[6] = "abcde";
- Persistent<MockResourceClient> client1 = new MockResourceClient;
- Persistent<MockResourceClient> client2 = new MockResourceClient;
+ Persistent<MockResourceClient> client1 =
+ MakeGarbageCollected<MockResourceClient>();
+ Persistent<MockResourceClient> client2 =
+ MakeGarbageCollected<MockResourceClient>();
FetchParameters params1(ResourceRequest("data:text/html,foo"));
Resource* resource1 = FakeDecodedResource::Fetch(params1, fetcher, client1);
FetchParameters params2(ResourceRequest("data:text/html,bar"));
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
index e1f17b211c9..bbf09a00d31 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -139,7 +140,7 @@ RawResource::RawResource(const ResourceRequest& resource_request,
void RawResource::AppendData(const char* data, size_t length) {
if (data_pipe_writer_) {
DCHECK_EQ(kDoNotBufferData, GetDataBufferingPolicy());
- data_pipe_writer_->Write(data, length);
+ data_pipe_writer_->Write(data, SafeCast<uint32_t>(length));
} else {
Resource::AppendData(data, length);
}
@@ -237,13 +238,13 @@ CachedMetadataHandler* RawResource::CreateCachedMetadataHandler(
if (GetType() == ResourceType::kMainResource) {
// This is a document resource; create a cache handler that can handle
// multiple inline scripts.
- return new SourceKeyedCachedMetadataHandler(Encoding(),
- std::move(send_callback));
+ return MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
+ Encoding(), std::move(send_callback));
} else if (GetType() == ResourceType::kRaw) {
// This is a resource of indeterminate type, e.g. a fetched WebAssembly
// module; create a cache handler that can store a single metadata entry.
- return new ScriptCachedMetadataHandler(Encoding(),
- std::move(send_callback));
+ return MakeGarbageCollected<ScriptCachedMetadataHandler>(
+ Encoding(), std::move(send_callback));
}
return Resource::CreateCachedMetadataHandler(std::move(send_callback));
}
@@ -340,7 +341,7 @@ bool RawResource::MatchPreload(const FetchParameters& params,
if (Data()) {
for (const auto& span : *Data())
- data_pipe_writer_->Write(span.data(), span.size());
+ data_pipe_writer_->Write(span.data(), SafeCast<uint32_t>(span.size()));
}
SetDataBufferingPolicy(kDoNotBufferData);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.h b/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.h
index 7e5c651c694..7f5e4200ce9 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource.h
@@ -70,7 +70,7 @@ class PLATFORM_EXPORT RawResource final : public Resource {
static RawResource* CreateForTest(ResourceRequest request,
ResourceType type) {
ResourceLoaderOptions options;
- return new RawResource(request, type, options);
+ return MakeGarbageCollected<RawResource>(request, type, options);
}
static RawResource* CreateForTest(const KURL& url,
scoped_refptr<const SecurityOrigin> origin,
@@ -80,6 +80,10 @@ class PLATFORM_EXPORT RawResource final : public Resource {
return CreateForTest(request, type);
}
+ RawResource(const ResourceRequest&,
+ ResourceType,
+ const ResourceLoaderOptions&);
+
// Resource implementation
MatchStatus CanReuse(const FetchParameters&) const override;
bool WillFollowRedirect(const ResourceRequest&,
@@ -114,14 +118,10 @@ class PLATFORM_EXPORT RawResource final : public Resource {
Resource* Create(const ResourceRequest& request,
const ResourceLoaderOptions& options) const override {
- return new RawResource(request, type_, options);
+ return MakeGarbageCollected<RawResource>(request, type_, options);
}
};
- RawResource(const ResourceRequest&,
- ResourceType,
- const ResourceLoaderOptions&);
-
// Resource implementation
void DidAddClient(ResourceClient*) override;
void AppendData(const char*, size_t) override;
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource_test.cc
index 484521b3286..a28d04aeafc 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/raw_resource_test.cc
@@ -45,6 +45,7 @@
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -92,7 +93,7 @@ class DummyClient final : public GarbageCollectedFinalized<DummyClient>,
String DebugName() const override { return "DummyClient"; }
void DataReceived(Resource*, const char* data, size_t length) override {
- data_.Append(data, length);
+ data_.Append(data, SafeCast<wtf_size_t>(length));
}
bool RedirectReceived(Resource*,
@@ -164,7 +165,7 @@ TEST_F(RawResourceTest, AddClientDuringCallback) {
raw->FinishForTest();
EXPECT_FALSE(raw->GetResponse().IsNull());
- Persistent<DummyClient> dummy_client = new DummyClient();
+ Persistent<DummyClient> dummy_client = MakeGarbageCollected<DummyClient>();
Persistent<AddingClient> adding_client =
new AddingClient(dummy_client.Get(), raw);
raw->AddClient(adding_client, platform_->test_task_runner().get());
@@ -207,9 +208,9 @@ TEST_F(RawResourceTest, RemoveClientDuringCallback) {
raw->FinishForTest();
EXPECT_FALSE(raw->GetResponse().IsNull());
- Persistent<DummyClient> dummy_client = new DummyClient();
+ Persistent<DummyClient> dummy_client = MakeGarbageCollected<DummyClient>();
Persistent<RemovingClient> removing_client =
- new RemovingClient(dummy_client.Get());
+ MakeGarbageCollected<RemovingClient>(dummy_client.Get());
raw->AddClient(dummy_client, platform_->test_task_runner().get());
raw->AddClient(removing_client, platform_->test_task_runner().get());
platform_->RunUntilIdle();
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource.cc
index c5867dc831e..335f6c1218d 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource.cc
@@ -194,7 +194,6 @@ Resource::Resource(const ResourceRequest& request,
encoded_size_(0),
encoded_size_memory_usage_(0),
decoded_size_(0),
- overhead_size_(CalculateOverheadSize()),
cache_identifier_(MemoryCache::DefaultCacheIdentifier()),
link_preload_(false),
is_revalidating_(false),
@@ -203,7 +202,8 @@ Resource::Resource(const ResourceRequest& request,
integrity_disposition_(ResourceIntegrityDisposition::kNotChecked),
options_(options),
response_timestamp_(CurrentTime()),
- resource_request_(request) {
+ resource_request_(request),
+ overhead_size_(CalculateOverheadSize()) {
InstanceCounters::IncrementCounter(InstanceCounters::kResourceCounter);
if (IsMainThread())
@@ -272,7 +272,7 @@ void Resource::CheckResourceIntegrity() {
}
void Resource::NotifyFinished() {
- DCHECK(IsLoaded());
+ CHECK(IsFinishedInternal());
ResourceClientWalker<ResourceClient> w(clients_);
while (ResourceClient* c = w.Next()) {
@@ -299,6 +299,10 @@ void Resource::AppendData(const char* data, size_t length) {
data_ = SharedBuffer::Create(data, length);
SetEncodedSize(data_->size());
}
+ NotifyDataReceived(data, length);
+}
+
+void Resource::NotifyDataReceived(const char* data, size_t length) {
ResourceClientWalker<ResourceClient> w(Clients());
while (ResourceClient* c = w.Next())
c->DataReceived(this, data, length);
@@ -322,8 +326,9 @@ void Resource::TriggerNotificationForFinishObservers(
if (finish_observers_.IsEmpty())
return;
- auto* new_collections = new HeapHashSet<WeakMember<ResourceFinishObserver>>(
- std::move(finish_observers_));
+ auto* new_collections =
+ MakeGarbageCollected<HeapHashSet<WeakMember<ResourceFinishObserver>>>(
+ std::move(finish_observers_));
finish_observers_.clear();
task_runner->PostTask(FROM_HERE, WTF::Bind(&NotifyFinishObservers,
@@ -617,7 +622,7 @@ void Resource::DidAddClient(ResourceClient* c) {
}
if (!HasClient(c))
return;
- if (IsLoaded()) {
+ if (IsFinishedInternal()) {
c->NotifyFinished(this);
if (clients_.Contains(c)) {
finished_clients_.insert(c);
@@ -689,6 +694,12 @@ void Resource::AddFinishObserver(ResourceFinishObserver* client,
WillAddClientOrObserver();
finish_observers_.insert(client);
+ // Despite these being "Finish" observers, what they actually care about is
+ // whether the resource is "Loaded", not "Finished" (e.g. link onload). Hence
+ // we check IsLoaded directly here, rather than IsFinishedInternal.
+ //
+ // TODO(leszeks): Either rename FinishObservers to LoadedObservers, or the
+ // NotifyFinished method of ResourceClient to NotifyProcessed (or similar).
if (IsLoaded())
TriggerNotificationForFinishObservers(task_runner);
}
@@ -798,7 +809,7 @@ Resource::MatchStatus Resource::CanReuse(const FetchParameters& params) const {
if (GetResponse().WasFetchedViaServiceWorker() &&
GetResponse().GetType() == network::mojom::FetchResponseType::kOpaque &&
new_request.GetFetchRequestMode() !=
- network::mojom::FetchRequestMode::kNoCORS) {
+ network::mojom::FetchRequestMode::kNoCors) {
return MatchStatus::kUnknownFailure;
}
@@ -884,13 +895,13 @@ Resource::MatchStatus Resource::CanReuse(const FetchParameters& params) const {
return MatchStatus::kRequestModeDoesNotMatch;
switch (new_mode) {
- case network::mojom::FetchRequestMode::kNoCORS:
+ case network::mojom::FetchRequestMode::kNoCors:
case network::mojom::FetchRequestMode::kNavigate:
break;
- case network::mojom::FetchRequestMode::kCORS:
+ case network::mojom::FetchRequestMode::kCors:
case network::mojom::FetchRequestMode::kSameOrigin:
- case network::mojom::FetchRequestMode::kCORSWithForcedPreflight:
+ case network::mojom::FetchRequestMode::kCorsWithForcedPreflight:
// We have two separate CORS handling logics in ThreadableLoader
// and ResourceLoader and sharing resources is difficult when they are
// handled differently.
@@ -964,7 +975,7 @@ void Resource::OnMemoryDump(WebMemoryDumpLevelOfDetail level_of_detail,
WTF::CodePointCompareLessThan);
StringBuilder builder;
- for (size_t i = 0;
+ for (wtf_size_t i = 0;
i < client_names.size() && i < kMaxResourceClientToShowInMemoryInfra;
++i) {
if (i > 0)
@@ -1072,7 +1083,7 @@ bool Resource::HasCacheControlNoStoreHeader() const {
bool Resource::MustReloadDueToVaryHeader(
const ResourceRequest& new_request) const {
- const AtomicString& vary = GetResponse().HttpHeaderField(HTTPNames::Vary);
+ const AtomicString& vary = GetResponse().HttpHeaderField(http_names::kVary);
if (vary.IsNull())
return false;
if (vary == "*")
@@ -1133,6 +1144,17 @@ bool Resource::StaleRevalidationRequested() const {
return false;
}
+bool Resource::NetworkAccessed() const {
+ if (GetResponse().NetworkAccessed())
+ return true;
+
+ for (auto& redirect : redirect_chain_) {
+ if (redirect.redirect_response_.NetworkAccessed())
+ return true;
+ }
+ return false;
+}
+
bool Resource::CanUseCacheValidator() const {
if (IsLoading() || ErrorOccurred())
return false;
@@ -1165,37 +1187,37 @@ void Resource::DidChangePriority(ResourceLoadPriority load_priority,
// TODO(toyoshim): Consider to generate automatically. https://crbug.com/675515.
static const char* InitiatorTypeNameToString(
const AtomicString& initiator_type_name) {
- if (initiator_type_name == FetchInitiatorTypeNames::audio)
+ if (initiator_type_name == fetch_initiator_type_names::kAudio)
return "Audio";
- if (initiator_type_name == FetchInitiatorTypeNames::css)
+ if (initiator_type_name == fetch_initiator_type_names::kCSS)
return "CSS resource";
- if (initiator_type_name == FetchInitiatorTypeNames::document)
+ if (initiator_type_name == fetch_initiator_type_names::kDocument)
return "Document";
- if (initiator_type_name == FetchInitiatorTypeNames::icon)
+ if (initiator_type_name == fetch_initiator_type_names::kIcon)
return "Icon";
- if (initiator_type_name == FetchInitiatorTypeNames::internal)
+ if (initiator_type_name == fetch_initiator_type_names::kInternal)
return "Internal resource";
- if (initiator_type_name == FetchInitiatorTypeNames::fetch)
+ if (initiator_type_name == fetch_initiator_type_names::kFetch)
return "Fetch";
- if (initiator_type_name == FetchInitiatorTypeNames::link)
+ if (initiator_type_name == fetch_initiator_type_names::kLink)
return "Link element resource";
- if (initiator_type_name == FetchInitiatorTypeNames::other)
+ if (initiator_type_name == fetch_initiator_type_names::kOther)
return "Other resource";
- if (initiator_type_name == FetchInitiatorTypeNames::processinginstruction)
+ if (initiator_type_name == fetch_initiator_type_names::kProcessinginstruction)
return "Processing instruction";
- if (initiator_type_name == FetchInitiatorTypeNames::track)
+ if (initiator_type_name == fetch_initiator_type_names::kTrack)
return "Track";
- if (initiator_type_name == FetchInitiatorTypeNames::uacss)
+ if (initiator_type_name == fetch_initiator_type_names::kUacss)
return "User Agent CSS resource";
- if (initiator_type_name == FetchInitiatorTypeNames::video)
+ if (initiator_type_name == fetch_initiator_type_names::kVideo)
return "Video";
- if (initiator_type_name == FetchInitiatorTypeNames::xml)
+ if (initiator_type_name == fetch_initiator_type_names::kXml)
return "XML resource";
- if (initiator_type_name == FetchInitiatorTypeNames::xmlhttprequest)
+ if (initiator_type_name == fetch_initiator_type_names::kXmlhttprequest)
return "XMLHttpRequest";
static_assert(
- FetchInitiatorTypeNames::FetchInitiatorTypeNamesCount == 17,
+ fetch_initiator_type_names::kNamesCount == 17,
"New FetchInitiatorTypeNames should be handled correctly here.");
return "Resource";
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource.h
index 4f16c04e357..3847b60c346 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource.h
@@ -45,9 +45,9 @@
#include "third_party/blink/renderer/platform/loader/subresource_integrity.h"
#include "third_party/blink/renderer/platform/memory_coordinator.h"
#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_counted_set.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -316,6 +316,10 @@ class PLATFORM_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
// revalidation is started SetStaleRevalidationStarted() should be called.
bool StaleRevalidationRequested() const;
+ // Returns true if any response returned from the upstream in the redirect
+ // chain accessed the network.
+ bool NetworkAccessed() const;
+
// Set that stale revalidation has been started so that subsequent
// requests won't trigger it again. When stale revalidation is completed
// this resource will be removed from the MemoryCache so there is no
@@ -354,10 +358,10 @@ class PLATFORM_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
void SetEncodedDataLength(int64_t value) {
response_.SetEncodedDataLength(value);
}
- void SetEncodedBodyLength(int value) {
+ void SetEncodedBodyLength(int64_t value) {
response_.SetEncodedBodyLength(value);
}
- void SetDecodedBodyLength(int value) {
+ void SetDecodedBodyLength(int64_t value) {
response_.SetDecodedBodyLength(value);
}
@@ -427,6 +431,19 @@ class PLATFORM_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
protected:
Resource(const ResourceRequest&, ResourceType, const ResourceLoaderOptions&);
+ // Returns true if the resource has finished any processing it wanted to do
+ // after loading. Should only be used to decide whether to call
+ // NotifyFinished.
+ //
+ // By default this is the same as being loaded (i.e. no processing), but it is
+ // used by ScriptResource to signal that streaming JavaScript compilation
+ // completed. Note that classes overloading this method should also overload
+ // NotifyFinished to not call Resource::NotifyFinished until this value
+ // becomes true.
+ // TODO(hiroshige): Remove this when ScriptResourceContent is introduced.
+ virtual bool IsFinishedInternal() const { return IsLoaded(); }
+
+ virtual void NotifyDataReceived(const char* data, size_t size);
virtual void NotifyFinished();
void MarkClientFinished(ResourceClient*);
@@ -532,12 +549,6 @@ class PLATFORM_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
size_t encoded_size_memory_usage_;
size_t decoded_size_;
- // Resource::CalculateOverheadSize() is affected by changes in
- // |m_resourceRequest.url()|, but |m_overheadSize| is not updated after
- // initial |m_resourceRequest| is given, to reduce MemoryCache manipulation
- // and thus potential bugs. crbug.com/594644
- const size_t overhead_size_;
-
String cache_identifier_;
bool link_preload_;
@@ -566,6 +577,13 @@ class PLATFORM_EXPORT Resource : public GarbageCollectedFinalized<Resource>,
TaskHandle async_finish_pending_clients_task_;
ResourceRequest resource_request_;
+
+ // Resource::CalculateOverheadSize() is affected by changes in
+ // |m_resourceRequest.url()|, but |m_overheadSize| is not updated after
+ // initial |m_resourceRequest| is given, to reduce MemoryCache manipulation
+ // and thus potential bugs. crbug.com/594644
+ const size_t overhead_size_;
+
Member<ResourceLoader> loader_;
ResourceResponse response_;
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client.h
index 2238aa1807b..dced85b7646 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client.h
@@ -42,7 +42,7 @@ class Resource;
class PLATFORM_EXPORT ResourceClient : public GarbageCollectedMixin {
USING_PRE_FINALIZER(ResourceClient, ClearResource);
public:
-
+ ResourceClient() = default;
virtual ~ResourceClient() = default;
// DataReceived() is called each time a chunk of data is received.
@@ -70,8 +70,6 @@ class PLATFORM_EXPORT ResourceClient : public GarbageCollectedMixin {
void Trace(Visitor* visitor) override;
protected:
- ResourceClient() = default;
-
void ClearResource() { SetResource(nullptr, nullptr); }
private:
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h
index 3e740d8de55..723d2ca57e1 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h
@@ -46,7 +46,7 @@ class ResourceClientWalker {
}
T* Next() {
- size_t size = client_vector_.size();
+ wtf_size_t size = client_vector_.size();
while (index_ < size) {
ResourceClient* next = client_vector_[index_++];
DCHECK(next);
@@ -60,7 +60,7 @@ class ResourceClientWalker {
private:
const HeapHashCountedSet<WeakMember<ResourceClient>>& client_set_;
HeapVector<Member<ResourceClient>> client_vector_;
- size_t index_ = 0;
+ wtf_size_t index_ = 0;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.cc
index 1670ba04db8..ca115e69991 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.cc
@@ -84,7 +84,7 @@ ResourceError ResourceError::Failure(const KURL& url) {
ResourceError::ResourceError(
int error_code,
const KURL& url,
- base::Optional<network::CORSErrorStatus> cors_error_status)
+ base::Optional<network::CorsErrorStatus> cors_error_status)
: error_code_(error_code),
failing_url_(url),
is_access_check_(cors_error_status.has_value()),
@@ -94,7 +94,7 @@ ResourceError::ResourceError(
}
ResourceError::ResourceError(const KURL& url,
- const network::CORSErrorStatus& cors_error_status)
+ const network::CorsErrorStatus& cors_error_status)
: ResourceError(net::ERR_FAILED, url, cors_error_status) {}
ResourceError::ResourceError(const WebURLError& error)
@@ -151,7 +151,7 @@ bool ResourceError::Compare(const ResourceError& a, const ResourceError& b) {
if (a.HasCopyInCache() != b.HasCopyInCache())
return false;
- if (a.CORSErrorStatus() != b.CORSErrorStatus())
+ if (a.CorsErrorStatus() != b.CorsErrorStatus())
return false;
if (a.extended_error_code_ != b.extended_error_code_)
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.h
index 8917c2fedb1..b50e630e04f 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_error.h
@@ -63,9 +63,9 @@ class PLATFORM_EXPORT ResourceError final {
// |error_code| must not be 0.
ResourceError(int error_code,
const KURL& failing_url,
- base::Optional<network::CORSErrorStatus>);
+ base::Optional<network::CorsErrorStatus>);
ResourceError(const KURL& failing_url,
- const network::CORSErrorStatus& status);
+ const network::CorsErrorStatus& status);
ResourceError(const WebURLError&);
// Makes a deep copy. Useful for when you need to use a ResourceError on
@@ -86,7 +86,7 @@ class PLATFORM_EXPORT ResourceError final {
base::Optional<ResourceRequestBlockedReason> GetResourceRequestBlockedReason()
const;
- base::Optional<network::CORSErrorStatus> CORSErrorStatus() const {
+ base::Optional<network::CorsErrorStatus> CorsErrorStatus() const {
return cors_error_status_;
}
@@ -107,7 +107,7 @@ class PLATFORM_EXPORT ResourceError final {
bool is_access_check_ = false;
bool has_copy_in_cache_ = false;
bool blocked_by_subresource_filter_ = false;
- base::Optional<network::CORSErrorStatus> cors_error_status_;
+ base::Optional<network::CorsErrorStatus> cors_error_status_;
};
inline bool operator==(const ResourceError& a, const ResourceError& b) {
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
index 1961073ea88..4b1f9320013 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -31,6 +31,8 @@
#include <limits>
#include <utility>
+#include "base/feature_list.h"
+#include "base/metrics/field_trial_params.h"
#include "base/time/time.h"
#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
@@ -112,7 +114,7 @@ constexpr base::TimeDelta kKeepaliveLoadersTimeout =
void AddRedirectsToTimingInfo(Resource* resource, ResourceTimingInfo* info) {
// Store redirect responses that were packed inside the final response.
const auto& responses = resource->GetResponse().RedirectResponses();
- for (size_t i = 0; i < responses.size(); ++i) {
+ for (wtf_size_t i = 0; i < responses.size(); ++i) {
const KURL& new_url = i + 1 < responses.size()
? KURL(responses[i + 1].Url())
: resource->GetResourceRequest().Url();
@@ -160,7 +162,7 @@ ResourceLoadPriority TypeToPriority(ResourceType type) {
static bool IsCacheableHTTPMethod(const AtomicString& method) {
// Per http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10,
// these methods always invalidate the cache entry.
- return method != HTTPNames::POST && method != HTTPNames::PUT &&
+ return method != http_names::kPOST && method != http_names::kPUT &&
method != "DELETE";
}
@@ -178,8 +180,9 @@ bool ShouldResourceBeAddedToMemoryCache(const FetchParameters& params,
}
static ResourceFetcher::ResourceFetcherSet& MainThreadFetchersSet() {
- DEFINE_STATIC_LOCAL(Persistent<ResourceFetcher::ResourceFetcherSet>, fetchers,
- (new ResourceFetcher::ResourceFetcherSet));
+ DEFINE_STATIC_LOCAL(
+ Persistent<ResourceFetcher::ResourceFetcherSet>, fetchers,
+ (MakeGarbageCollected<ResourceFetcher::ResourceFetcherSet>()));
return *fetchers;
}
@@ -236,6 +239,27 @@ ResourceLoadPriority AdjustPriorityWithPriorityHint(
return new_priority;
}
+const base::Feature kStaleWhileRevalidateExperiment{
+ "StaleWhileRevalidateExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
+
+bool MatchesStaleWhileRevalidateControlList(const String& host) {
+ DEFINE_STATIC_LOCAL(String, kStaleWhileRevalidateControlHosts,
+ (GetFieldTrialParamValueByFeature(
+ kStaleWhileRevalidateExperiment, "control_hosts")
+ .c_str()));
+ return !host.IsEmpty() &&
+ kStaleWhileRevalidateControlHosts.Find(host) != kNotFound;
+}
+
+bool MatchesStaleWhileRevalidateAllowList(const String& host) {
+ DEFINE_STATIC_LOCAL(String, kStaleWhileRevalidateAllowHosts,
+ (GetFieldTrialParamValueByFeature(
+ kStaleWhileRevalidateExperiment, "hosts")
+ .c_str()));
+ return !host.IsEmpty() &&
+ kStaleWhileRevalidateAllowHosts.Find(host) != kNotFound;
+}
+
} // namespace
ResourceLoadPriority ResourceFetcher::ComputeLoadPriority(
@@ -539,7 +563,7 @@ Resource* ResourceFetcher::ResourceForStaticData(
response.SetExpectedContentLength(data->size());
response.SetTextEncodingName(substitute_data.TextEncoding());
} else if (url.ProtocolIsData()) {
- data = NetworkUtils::ParseDataURLAndPopulateResponse(url, response);
+ data = network_utils::ParseDataURLAndPopulateResponse(url, response);
if (!data)
return nullptr;
// |response| is modified by parseDataURLAndPopulateResponse() and is
@@ -701,8 +725,26 @@ base::Optional<ResourceRequestBlockedReason> ResourceFetcher::PrepareRequest(
resource_type, kImageNotImageSet, Context().IsMainFrame()));
}
if (resource_type == ResourceType::kLinkPrefetch)
- resource_request.SetHTTPHeaderField(HTTPNames::Purpose, "prefetch");
-
+ resource_request.SetHTTPHeaderField(http_names::kPurpose, "prefetch");
+
+ bool resource_allows_stale_while_revalidate = false;
+ bool host_matches_control =
+ MatchesStaleWhileRevalidateControlList(params.Url().Host());
+ bool host_matches_allow = false;
+ if (!host_matches_control) {
+ host_matches_allow =
+ MatchesStaleWhileRevalidateAllowList(params.Url().Host());
+ }
+ if (host_matches_allow)
+ resource_allows_stale_while_revalidate = host_matches_allow;
+
+ // For the finch experiment indicate that the resource likely supports
+ // stale while revalidate (based on a list of hosts). This allows us
+ // to only log metrics for sites that would possibly benefit from
+ // stale while revalidate being enabled.
+ resource_request.SetStaleRevalidateCandidate(
+ (host_matches_allow || host_matches_control) &&
+ !params.IsStaleRevalidation());
// Indicate whether the network stack can return a stale resource. If a
// stale resource is returned a StaleRevalidation request will be scheduled.
// Explicitly disallow stale responses for fetchers that don't have SWR
@@ -711,8 +753,9 @@ base::Optional<ResourceRequestBlockedReason> ResourceFetcher::PrepareRequest(
// unintentional SWR, as bugs around RawResources tend to be complicated and
// critical.
resource_request.SetAllowStaleResponse(
- stale_while_revalidate_enabled_ &&
- resource_request.HttpMethod() == HTTPNames::GET &&
+ (resource_allows_stale_while_revalidate ||
+ stale_while_revalidate_enabled_) &&
+ resource_request.HttpMethod() == http_names::kGET &&
!IsRawResource(resource_type) && !params.IsStaleRevalidation());
Context().AddAdditionalRequestHeaders(
@@ -745,24 +788,24 @@ base::Optional<ResourceRequestBlockedReason> ResourceFetcher::PrepareRequest(
if (!params.Url().IsValid())
return ResourceRequestBlockedReason::kOther;
- if (!RuntimeEnabledFeatures::OutOfBlinkCORSEnabled() &&
+ if (!RuntimeEnabledFeatures::OutOfBlinkCorsEnabled() &&
options.cors_handling_by_resource_fetcher ==
- kEnableCORSHandlingByResourceFetcher) {
+ kEnableCorsHandlingByResourceFetcher) {
const scoped_refptr<const SecurityOrigin> origin =
resource_request.RequestorOrigin();
DCHECK(!options.cors_flag);
- params.MutableOptions().cors_flag = CORS::CalculateCORSFlag(
+ params.MutableOptions().cors_flag = cors::CalculateCorsFlag(
params.Url(), origin.get(), resource_request.GetFetchRequestMode());
// TODO(yhirano): Reject requests for non CORS-enabled schemes.
// See https://crrev.com/c/1298828.
- resource_request.SetAllowStoredCredentials(CORS::CalculateCredentialsFlag(
+ resource_request.SetAllowStoredCredentials(cors::CalculateCredentialsFlag(
resource_request.GetFetchCredentialsMode(),
- CORS::CalculateResponseTainting(
+ cors::CalculateResponseTainting(
params.Url(), resource_request.GetFetchRequestMode(), origin.get(),
- params.Options().cors_flag ? CORSFlag::Set : CORSFlag::Unset)));
+ params.Options().cors_flag ? CorsFlag::Set : CorsFlag::Unset)));
}
- if (RuntimeEnabledFeatures::OutOfBlinkCORSEnabled() &&
+ if (RuntimeEnabledFeatures::OutOfBlinkCorsEnabled() &&
resource_request.GetFetchCredentialsMode() ==
network::mojom::FetchCredentialsMode::kOmit) {
// See comments at network::ResourceRequest::fetch_credentials_mode.
@@ -783,7 +826,6 @@ Resource* ResourceFetcher::RequestResource(
scoped_resource_load_tracker(identifier, resource_request);
SCOPED_BLINK_UMA_HISTOGRAM_TIMER_THREAD_SAFE(
"Blink.Fetch.RequestResourceTime");
- // TODO(dproy): Remove this. http://crbug.com/659666
TRACE_EVENT1("blink", "ResourceFetcher::requestResource", "url",
UrlForTraceEvent(params.Url()));
@@ -870,10 +912,20 @@ Resource* ResourceFetcher::RequestResource(
InitializeRevalidation(resource_request, resource);
break;
case kUse:
+ bool used_stale = false;
if (resource_request.AllowsStaleResponse() &&
resource->ShouldRevalidateStaleResponse()) {
+ used_stale = true;
ScheduleStaleRevalidate(resource);
}
+ if (resource_request.IsStaleRevalidateCandidate()) {
+ context_->DidObserveLoadingBehavior(
+ used_stale
+ ? WebLoadingBehaviorFlag::
+ kStaleWhileRevalidateResourceCandidateStaleCacheLoad
+ : WebLoadingBehaviorFlag::
+ kStaleWhileRevalidateResourceCandidateCacheLoad);
+ }
if (resource->IsLinkPreload() && !params.IsLinkPreload())
resource->SetLinkPreload(false);
@@ -918,9 +970,7 @@ Resource* ResourceFetcher::RequestResource(
// the resource was already initialized for the revalidation here, but won't
// start loading.
if (ResourceNeedsLoad(resource, params, policy)) {
- if (StartLoad(resource)) {
- scoped_resource_load_tracker.ResourceLoadContinuesBeyondScope();
- } else {
+ if (!StartLoad(resource)) {
resource->FinishAsError(ResourceError::CancelledError(params.Url()),
Context().GetLoadingTaskRunner().get());
}
@@ -929,6 +979,11 @@ Resource* ResourceFetcher::RequestResource(
if (policy != kUse)
InsertAsPreloadIfNecessary(resource, params, resource_type);
+ if (resource->Identifier() == identifier &&
+ (resource->StillNeedsLoad() || resource->IsLoading())) {
+ scoped_resource_load_tracker.ResourceLoadContinuesBeyondScope();
+ }
+
return resource;
}
@@ -956,24 +1011,24 @@ void ResourceFetcher::InitializeRevalidation(
revalidating_request.SetIsRevalidating(true);
const AtomicString& last_modified =
- resource->GetResponse().HttpHeaderField(HTTPNames::Last_Modified);
+ resource->GetResponse().HttpHeaderField(http_names::kLastModified);
const AtomicString& e_tag =
- resource->GetResponse().HttpHeaderField(HTTPNames::ETag);
+ resource->GetResponse().HttpHeaderField(http_names::kETag);
if (!last_modified.IsEmpty() || !e_tag.IsEmpty()) {
DCHECK_NE(mojom::FetchCacheMode::kBypassCache,
revalidating_request.GetCacheMode());
if (revalidating_request.GetCacheMode() ==
mojom::FetchCacheMode::kValidateCache) {
- revalidating_request.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ revalidating_request.SetHTTPHeaderField(http_names::kCacheControl,
"max-age=0");
}
}
if (!last_modified.IsEmpty()) {
- revalidating_request.SetHTTPHeaderField(HTTPNames::If_Modified_Since,
+ revalidating_request.SetHTTPHeaderField(http_names::kIfModifiedSince,
last_modified);
}
if (!e_tag.IsEmpty())
- revalidating_request.SetHTTPHeaderField(HTTPNames::If_None_Match, e_tag);
+ revalidating_request.SetHTTPHeaderField(http_names::kIfNoneMatch, e_tag);
resource->SetRevalidatingRequest(revalidating_request);
}
@@ -1009,7 +1064,7 @@ Resource* ResourceFetcher::CreateResourceForLoading(
void ResourceFetcher::StorePerformanceTimingInitiatorInformation(
Resource* resource) {
const AtomicString& fetch_initiator = resource->Options().initiator_info.name;
- if (fetch_initiator == FetchInitiatorTypeNames::internal)
+ if (fetch_initiator == fetch_initiator_type_names::kInternal)
return;
bool is_main_resource = resource->GetType() == ResourceType::kMainResource;
@@ -1034,7 +1089,7 @@ void ResourceFetcher::StorePerformanceTimingInitiatorInformation(
if (resource->IsCacheValidator()) {
const AtomicString& timing_allow_origin =
- resource->GetResponse().HttpHeaderField(HTTPNames::Timing_Allow_Origin);
+ resource->GetResponse().HttpHeaderField(http_names::kTimingAllowOrigin);
if (!timing_allow_origin.IsEmpty())
info->SetOriginalTimingAllowOrigin(timing_allow_origin);
}
@@ -1441,9 +1496,9 @@ void ResourceFetcher::ReloadImagesIfNotDeferred() {
}
FetchContext& ResourceFetcher::Context() const {
- return context_ ? *context_.Get()
- : FetchContext::NullInstance(
- Platform::Current()->CurrentThread()->GetTaskRunner());
+ return context_
+ ? *context_.Get()
+ : FetchContext::NullInstance(Thread::Current()->GetTaskRunner());
}
void ResourceFetcher::ClearContext() {
@@ -1631,7 +1686,7 @@ void ResourceFetcher::HandleLoaderFinish(
WebString::FromUTF8(timing_info.alpn_negotiated_protocol));
response.SetConnectionInfo(timing_info.connection_info);
response.SetHTTPHeaderField(
- HTTPNames::Timing_Allow_Origin,
+ http_names::kTimingAllowOrigin,
WebString::FromUTF8(timing_info.timing_allow_origin));
response.SetEncodedDataLength(timing_info.transfer_size);
preflight_info->SetFinalResponse(response);
@@ -1655,10 +1710,25 @@ void ResourceFetcher::HandleLoaderFinish(
// is fresh at the time of the network stack handling but not at the time
// handling here and we should not be forcing a revalidation in that case.
// eg. network stack returning a resource with max-age=0.
+ bool used_stale = false;
if (resource->GetResourceRequest().AllowsStaleResponse() &&
resource->StaleRevalidationRequested()) {
+ used_stale = true;
ScheduleStaleRevalidate(resource);
}
+
+ if (resource->GetResourceRequest().IsStaleRevalidateCandidate()) {
+ WebLoadingBehaviorFlag behavior = WebLoadingBehaviorFlag::
+ kStaleWhileRevalidateResourceCandidateCacheLoad;
+ if (used_stale) {
+ behavior = WebLoadingBehaviorFlag::
+ kStaleWhileRevalidateResourceCandidateStaleCacheLoad;
+ } else if (resource->NetworkAccessed()) {
+ behavior = WebLoadingBehaviorFlag::
+ kStaleWhileRevalidateResourceCandidateNetworkLoad;
+ }
+ context_->DidObserveLoadingBehavior(behavior);
+ }
}
HandleLoadCompletion(resource);
@@ -1677,7 +1747,7 @@ void ResourceFetcher::HandleLoaderError(Resource* resource,
resource_timing_info_map_.Take(resource);
bool is_internal_request = resource->Options().initiator_info.name ==
- FetchInitiatorTypeNames::internal;
+ fetch_initiator_type_names::kInternal;
resource->VirtualTimePauser().UnpauseVirtualTime();
Context().DispatchDidFail(
@@ -1924,8 +1994,9 @@ void ResourceFetcher::RevalidateStaleResource(Resource* stale_resource) {
// requests.
FetchParameters params(stale_resource->GetResourceRequest());
params.SetStaleRevalidation(true);
- RawResource::Fetch(params, this,
- new StaleRevalidationResourceClient(stale_resource));
+ RawResource::Fetch(
+ params, this,
+ MakeGarbageCollected<StaleRevalidationResourceClient>(stale_resource));
}
void ResourceFetcher::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h
index 1bb482a33e2..86b375837ee 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h
@@ -75,8 +75,10 @@ class PLATFORM_EXPORT ResourceFetcher
public:
static ResourceFetcher* Create(FetchContext* context) {
- return new ResourceFetcher(context);
+ return MakeGarbageCollected<ResourceFetcher>(context);
}
+
+ ResourceFetcher(FetchContext*);
virtual ~ResourceFetcher();
virtual void Trace(blink::Visitor*);
@@ -197,8 +199,6 @@ class PLATFORM_EXPORT ResourceFetcher
kIncludingKeepaliveLoaders,
};
- ResourceFetcher(FetchContext*);
-
void InitializeRevalidation(ResourceRequest&, Resource*);
// When |security_origin| of the ResourceLoaderOptions is not a nullptr, it'll
// be used instead of the associated FetchContext's SecurityOrigin.
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc
index 5ec42066fb0..783d74edb74 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_fetcher_test.cc
@@ -77,13 +77,13 @@ constexpr int kTestResourceSize = 103; // size of white-1x1.png
void RegisterMockedURLLoadWithCustomResponse(const KURL& url,
const ResourceResponse& response) {
- URLTestHelpers::RegisterMockedURLLoadWithCustomResponse(
+ url_test_helpers::RegisterMockedURLLoadWithCustomResponse(
url, test::PlatformTestDataPath(kTestResourceFilename),
WrappedResourceResponse(response));
}
void RegisterMockedURLLoad(const KURL& url) {
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
url, test::PlatformTestDataPath(kTestResourceFilename),
kTestResourceMimeType);
}
@@ -140,7 +140,7 @@ TEST_F(ResourceFetcherTest, UseExistingResource) {
KURL url("http://127.0.0.1:8000/foo.html");
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=3600");
RegisterMockedURLLoadWithCustomResponse(url, response);
FetchParameters fetch_params{ResourceRequest(url)};
@@ -167,7 +167,7 @@ TEST_F(ResourceFetcherTest, WillSendRequestAdBit) {
AddResourceToMemoryCache(resource);
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=3600");
resource->ResponseReceived(response, nullptr);
resource->FinishForTest();
@@ -200,8 +200,8 @@ TEST_F(ResourceFetcherTest, Vary) {
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
- response.SetHTTPHeaderField(HTTPNames::Vary, "*");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=3600");
+ response.SetHTTPHeaderField(http_names::kVary, "*");
resource->ResponseReceived(response, nullptr);
resource->FinishForTest();
ASSERT_TRUE(resource->MustReloadDueToVaryHeader(ResourceRequest(url)));
@@ -268,8 +268,8 @@ TEST_F(ResourceFetcherTest, VaryOnBack) {
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
- response.SetHTTPHeaderField(HTTPNames::Vary, "*");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=3600");
+ response.SetHTTPHeaderField(http_names::kVary, "*");
resource->ResponseReceived(response, nullptr);
resource->FinishForTest();
ASSERT_TRUE(resource->MustReloadDueToVaryHeader(ResourceRequest(url)));
@@ -288,8 +288,8 @@ TEST_F(ResourceFetcherTest, VaryResource) {
KURL url("http://127.0.0.1:8000/foo.html");
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
- response.SetHTTPHeaderField(HTTPNames::Vary, "*");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=3600");
+ response.SetHTTPHeaderField(http_names::kVary, "*");
RegisterMockedURLLoadWithCustomResponse(url, response);
FetchParameters fetch_params_original{ResourceRequest(url)};
@@ -353,16 +353,17 @@ TEST_F(ResourceFetcherTest, RevalidateWhileFinishingLoading) {
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
- response.SetHTTPHeaderField(HTTPNames::ETag, "1234567890");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=3600");
+ response.SetHTTPHeaderField(http_names::kETag, "1234567890");
RegisterMockedURLLoadWithCustomResponse(url, response);
ResourceFetcher* fetcher1 = ResourceFetcher::Create(Context());
ResourceRequest request1(url);
- request1.SetHTTPHeaderField(HTTPNames::Cache_Control, "no-cache");
+ request1.SetHTTPHeaderField(http_names::kCacheControl, "no-cache");
FetchParameters fetch_params1(request1);
Persistent<RequestSameResourceOnComplete> client =
- new RequestSameResourceOnComplete(fetch_params1, fetcher1);
+ MakeGarbageCollected<RequestSameResourceOnComplete>(fetch_params1,
+ fetcher1);
platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests();
EXPECT_TRUE(client->NotifyFinishedCalled());
}
@@ -380,7 +381,7 @@ TEST_F(ResourceFetcherTest, MAYBE_DontReuseMediaDataUrl) {
request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
ResourceLoaderOptions options;
options.data_buffering_policy = kDoNotBufferData;
- options.initiator_info.name = FetchInitiatorTypeNames::internal;
+ options.initiator_info.name = fetch_initiator_type_names::kInternal;
FetchParameters fetch_params(request, options);
Resource* resource1 = RawResource::FetchMedia(fetch_params, fetcher, nullptr);
Resource* resource2 = RawResource::FetchMedia(fetch_params, fetcher, nullptr);
@@ -446,7 +447,7 @@ TEST_F(ResourceFetcherTest, ResponseOnCancel) {
resource_request.SetRequestContext(mojom::RequestContextType::INTERNAL);
FetchParameters fetch_params(resource_request);
Persistent<ServeRequestsOnCompleteClient> client =
- new ServeRequestsOnCompleteClient();
+ MakeGarbageCollected<ServeRequestsOnCompleteClient>();
Resource* resource = RawResource::Fetch(fetch_params, fetcher, client);
resource->Loader()->Cancel();
}
@@ -464,7 +465,7 @@ class ScopedMockRedirectRequester {
WebURLResponse redirect_response;
redirect_response.SetURL(redirect_url);
redirect_response.SetHTTPStatusCode(301);
- redirect_response.SetHTTPHeaderField(HTTPNames::Location, to_url);
+ redirect_response.SetHTTPHeaderField(http_names::kLocation, to_url);
redirect_response.SetEncodedDataLength(kRedirectResponseOverheadBytes);
Platform::Current()->GetURLLoaderMockFactory()->RegisterURL(
redirect_url, redirect_response, "");
@@ -605,7 +606,8 @@ TEST_F(ResourceFetcherTest, LinkPreloadResourceAndUse) {
// Resource created by parser
FetchParameters fetch_params{ResourceRequest(url)};
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
Resource* new_resource = MockResource::Fetch(fetch_params, fetcher, client);
EXPECT_EQ(resource, new_resource);
EXPECT_FALSE(resource->IsLinkPreload());
@@ -810,7 +812,8 @@ TEST_F(ResourceFetcherTest, LinkPreloadResourceMultipleFetchersAndMove) {
// Resource created by parser on the second fetcher
FetchParameters fetch_params2{ResourceRequest(url)};
- Persistent<MockResourceClient> client2 = new MockResourceClient;
+ Persistent<MockResourceClient> client2 =
+ MakeGarbageCollected<MockResourceClient>();
Resource* new_resource2 =
MockResource::Fetch(fetch_params2, fetcher2, client2);
EXPECT_NE(resource, new_resource2);
@@ -883,7 +886,7 @@ TEST_F(ResourceFetcherTest, StaleWhileRevalidate) {
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ response.SetHTTPHeaderField(http_names::kCacheControl,
"max-age=0, stale-while-revalidate=40");
RegisterMockedURLLoadWithCustomResponse(url, response);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.cc
index f8d0f074957..a9e198f9d32 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.cc
@@ -6,13 +6,14 @@
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram.h"
+#include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/scheduler/renderer/frame_status.h"
-#include "third_party/blink/renderer/platform/scheduler/util/aggregated_metric_reporter.h"
+#include "third_party/blink/renderer/platform/scheduler/public/aggregated_metric_reporter.h"
+#include "third_party/blink/renderer/platform/scheduler/public/frame_status.h"
namespace blink {
@@ -106,7 +107,7 @@ size_t GetOutstandingThrottledLimit(FetchContext* context) {
}
int TakeWholeKilobytes(int64_t& bytes) {
- int kilobytes = bytes / 1024;
+ int kilobytes = base::saturated_cast<int>(bytes / 1024);
bytes %= 1024;
return kilobytes;
}
@@ -140,13 +141,13 @@ class ResourceLoadScheduler::TrafficMonitor {
scheduler::SchedulingLifecycleState current_state_ =
scheduler::SchedulingLifecycleState::kStopped;
- size_t total_throttled_request_count_ = 0;
+ uint32_t total_throttled_request_count_ = 0;
size_t total_throttled_traffic_bytes_ = 0;
size_t total_throttled_decoded_bytes_ = 0;
- size_t total_not_throttled_request_count_ = 0;
+ uint32_t total_not_throttled_request_count_ = 0;
size_t total_not_throttled_traffic_bytes_ = 0;
size_t total_not_throttled_decoded_bytes_ = 0;
- size_t throttling_state_change_count_ = 0;
+ uint32_t throttling_state_change_count_ = 0;
bool report_all_is_called_ = false;
scheduler::AggregatedMetricReporter<scheduler::FrameStatus, int64_t>
@@ -311,26 +312,34 @@ void ResourceLoadScheduler::TrafficMonitor::ReportAll() {
main_frame_total_not_throttled_request_count.Count(
total_not_throttled_request_count_);
main_frame_total_throttled_traffic_bytes.Count(
- total_throttled_traffic_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_throttled_traffic_bytes_));
main_frame_total_not_throttled_traffic_bytes.Count(
- total_not_throttled_traffic_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_not_throttled_traffic_bytes_));
main_frame_total_throttled_decoded_bytes.Count(
- total_throttled_decoded_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_throttled_decoded_bytes_));
main_frame_total_not_throttled_decoded_bytes.Count(
- total_not_throttled_decoded_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_not_throttled_decoded_bytes_));
} else {
sub_frame_total_throttled_request_count.Count(
total_throttled_request_count_);
sub_frame_total_not_throttled_request_count.Count(
total_not_throttled_request_count_);
sub_frame_total_throttled_traffic_bytes.Count(
- total_throttled_traffic_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_throttled_traffic_bytes_));
sub_frame_total_not_throttled_traffic_bytes.Count(
- total_not_throttled_traffic_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_not_throttled_traffic_bytes_));
sub_frame_total_throttled_decoded_bytes.Count(
- total_throttled_decoded_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_throttled_decoded_bytes_));
sub_frame_total_not_throttled_decoded_bytes.Count(
- total_not_throttled_decoded_bytes_);
+ base::saturated_cast<base::Histogram::Sample>(
+ total_not_throttled_decoded_bytes_));
}
throttling_state_change_count.Count(throttling_state_change_count_);
@@ -365,10 +374,10 @@ ResourceLoadScheduler::ResourceLoadScheduler(FetchContext* context)
}
ResourceLoadScheduler* ResourceLoadScheduler::Create(FetchContext* context) {
- return new ResourceLoadScheduler(
- context ? context
- : &FetchContext::NullInstance(
- Platform::Current()->CurrentThread()->GetTaskRunner()));
+ return MakeGarbageCollected<ResourceLoadScheduler>(
+ context
+ ? context
+ : &FetchContext::NullInstance(Thread::Current()->GetTaskRunner()));
}
ResourceLoadScheduler::~ResourceLoadScheduler() = default;
@@ -421,7 +430,8 @@ void ResourceLoadScheduler::Request(ResourceLoadSchedulerClient* client,
ThrottleOption::kThrottleable == option);
pending_requests_[option].insert(request_info);
pending_request_map_.insert(
- *id, new ClientInfo(client, option, priority, intra_priority));
+ *id, MakeGarbageCollected<ClientInfo>(client, option, priority,
+ intra_priority));
// Remember the ClientId since MaybeRun() below may destruct the caller
// instance and |id| may be inaccessible after the call.
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.h
index b1591417ebe..7f327a2c9ea 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler.h
@@ -148,6 +148,8 @@ class PLATFORM_EXPORT ResourceLoadScheduler final
std::numeric_limits<size_t>::max();
static ResourceLoadScheduler* Create(FetchContext* = nullptr);
+
+ ResourceLoadScheduler(FetchContext*);
~ResourceLoadScheduler() override;
void Trace(blink::Visitor*);
@@ -252,8 +254,6 @@ class PLATFORM_EXPORT ResourceLoadScheduler final
bool IsClientDelayable(const ClientIdWithPriority& info,
ThrottleOption option) const;
- ResourceLoadScheduler(FetchContext*);
-
// Generates the next ClientId.
ClientId GenerateClientId();
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler_test.cc
index 33fde7b59b3..440a7e61b07 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_load_scheduler_test.cc
@@ -87,7 +87,7 @@ TEST_F(ResourceLoadSchedulerTest, StopStoppableRequest) {
Scheduler()->OnLifecycleStateChanged(
scheduler::SchedulingLifecycleState::kStopped);
// A request that disallows throttling should be queued.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id1 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client1, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -97,7 +97,7 @@ TEST_F(ResourceLoadSchedulerTest, StopStoppableRequest) {
// Another request that disallows throttling, but allows stopping should also
// be queued.
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kStoppable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -107,7 +107,7 @@ TEST_F(ResourceLoadSchedulerTest, StopStoppableRequest) {
// Another request that disallows throttling and stopping also should be run
// even it makes the outstanding number reaches to the limit.
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kCanNotBeStoppedOrThrottled,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -135,7 +135,7 @@ TEST_F(ResourceLoadSchedulerTest, ThrottleThrottleableRequest) {
Scheduler()->SetOutstandingLimitForTesting(0);
// A request that allows throttling should be queued.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id1 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client1, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -145,7 +145,7 @@ TEST_F(ResourceLoadSchedulerTest, ThrottleThrottleableRequest) {
// Another request that disallows throttling also should be run even it makes
// the outstanding number reaches to the limit.
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kStoppable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -155,7 +155,7 @@ TEST_F(ResourceLoadSchedulerTest, ThrottleThrottleableRequest) {
// Another request that disallows stopping should be run even it makes the
// outstanding number reaches to the limit.
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kCanNotBeStoppedOrThrottled,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -179,7 +179,7 @@ TEST_F(ResourceLoadSchedulerTest, ThrottleThrottleableRequest) {
TEST_F(ResourceLoadSchedulerTest, Throttled) {
// The first request should be ran synchronously.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id1 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client1, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -188,7 +188,7 @@ TEST_F(ResourceLoadSchedulerTest, Throttled) {
EXPECT_TRUE(client1->WasRun());
// Another request should be throttled until the first request calls Release.
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -197,7 +197,7 @@ TEST_F(ResourceLoadSchedulerTest, Throttled) {
EXPECT_FALSE(client2->WasRun());
// Two more requests.
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -205,7 +205,7 @@ TEST_F(ResourceLoadSchedulerTest, Throttled) {
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id3);
EXPECT_FALSE(client3->WasRun());
- MockClient* client4 = new MockClient;
+ MockClient* client4 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id4 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client4, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -231,7 +231,7 @@ TEST_F(ResourceLoadSchedulerTest, Throttled) {
TEST_F(ResourceLoadSchedulerTest, Unthrottle) {
// Push three requests.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id1 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client1, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -239,7 +239,7 @@ TEST_F(ResourceLoadSchedulerTest, Unthrottle) {
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id1);
EXPECT_TRUE(client1->WasRun());
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -247,7 +247,7 @@ TEST_F(ResourceLoadSchedulerTest, Unthrottle) {
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id2);
EXPECT_FALSE(client2->WasRun());
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -268,7 +268,7 @@ TEST_F(ResourceLoadSchedulerTest, Unthrottle) {
TEST_F(ResourceLoadSchedulerTest, Stopped) {
// Push three requests.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id1 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client1, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -276,7 +276,7 @@ TEST_F(ResourceLoadSchedulerTest, Stopped) {
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id1);
EXPECT_TRUE(client1->WasRun());
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -284,7 +284,7 @@ TEST_F(ResourceLoadSchedulerTest, Stopped) {
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id2);
EXPECT_FALSE(client2->WasRun());
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kThrottleable,
ResourceLoadPriority::kMedium, 0 /* intra_priority */,
@@ -310,7 +310,7 @@ TEST_F(ResourceLoadSchedulerTest, Stopped) {
TEST_F(ResourceLoadSchedulerTest, PriorityIsConsidered) {
// Push three requests.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
Scheduler()->SetOutstandingLimitForTesting(0);
@@ -320,21 +320,21 @@ TEST_F(ResourceLoadSchedulerTest, PriorityIsConsidered) {
&id1);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id1);
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLow, 1 /* intra_priority */,
&id2);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id2);
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLow, 3 /* intra_priority */,
&id3);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id3);
- MockClient* client4 = new MockClient;
+ MockClient* client4 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id4 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client4, ThrottleOption::kThrottleable,
ResourceLoadPriority::kHigh, 0 /* intra_priority */,
@@ -383,8 +383,8 @@ TEST_F(ResourceLoadSchedulerTest, AllowedRequestsRunInPriorityOrder) {
MockClient::MockClientDelegate delegate;
// Push two requests.
- MockClient* client1 = new MockClient;
- MockClient* client2 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
client1->SetDelegate(&delegate);
client2->SetDelegate(&delegate);
@@ -426,7 +426,7 @@ TEST_F(ResourceLoadSchedulerTest, StoppableRequestResumesWhenThrottled) {
Scheduler()->OnLifecycleStateChanged(
scheduler::SchedulingLifecycleState::kStopped);
// Push two requests.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
Scheduler()->SetOutstandingLimitForTesting(0);
@@ -436,14 +436,14 @@ TEST_F(ResourceLoadSchedulerTest, StoppableRequestResumesWhenThrottled) {
&id1);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id1);
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kHigh, 1 /* intra_priority */,
&id2);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id2);
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kStoppable,
ResourceLoadPriority::kLowest, 10 /* intra_priority */,
@@ -477,7 +477,7 @@ TEST_F(ResourceLoadSchedulerTest, SetPriority) {
// Start with the normal scheduling policy.
Scheduler()->LoosenThrottlingPolicy();
// Push three requests.
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
Scheduler()->SetOutstandingLimitForTesting(0);
@@ -487,14 +487,14 @@ TEST_F(ResourceLoadSchedulerTest, SetPriority) {
&id1);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id1);
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLow, 5 /* intra_priority */,
&id2);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id2);
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLow, 10 /* intra_priority */,
@@ -530,7 +530,7 @@ TEST_F(ResourceLoadSchedulerTest, SetPriority) {
}
TEST_F(ResourceLoadSchedulerTest, LoosenThrottlingPolicy) {
- MockClient* client1 = new MockClient;
+ MockClient* client1 = MakeGarbageCollected<MockClient>();
Scheduler()->SetOutstandingLimitForTesting(0, 0);
@@ -540,21 +540,21 @@ TEST_F(ResourceLoadSchedulerTest, LoosenThrottlingPolicy) {
&id1);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id1);
- MockClient* client2 = new MockClient;
+ MockClient* client2 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id2 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client2, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLowest, 0 /* intra_priority */,
&id2);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id2);
- MockClient* client3 = new MockClient;
+ MockClient* client3 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id3 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client3, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLowest, 0 /* intra_priority */,
&id3);
EXPECT_NE(ResourceLoadScheduler::kInvalidClientId, id3);
- MockClient* client4 = new MockClient;
+ MockClient* client4 = MakeGarbageCollected<MockClient>();
ResourceLoadScheduler::ClientId id4 = ResourceLoadScheduler::kInvalidClientId;
Scheduler()->Request(client4, ThrottleOption::kThrottleable,
ResourceLoadPriority::kLowest, 0 /* intra_priority */,
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc
index d8e9312580f..5ff1ba1bda6 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc
@@ -38,14 +38,12 @@
#include "third_party/blink/public/mojom/blob/blob_registry.mojom-blink.h"
#include "third_party/blink/public/platform/code_cache_loader.h"
#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/public/platform/web_cors.h"
#include "third_party/blink/public/platform/web_data.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/platform/web_url_error.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h"
-#include "third_party/blink/renderer/platform/exported/wrapped_resource_response.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/cors/cors_error_string.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
@@ -63,6 +61,7 @@
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/weborigin/security_violation_reporting_policy.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -131,6 +130,7 @@ class ResourceLoader::CodeCacheRequest {
// resource_response_time that is used to validate responses from
// code cache. Might send cached code if available.
void DidReceiveResponse(const base::Time& resource_response_time,
+ bool use_isolated_code_cache,
ResourceLoader* resource_loader);
// Stores the value of defers that is needed to restore the state
@@ -168,6 +168,7 @@ class ResourceLoader::CodeCacheRequest {
std::vector<uint8_t> cached_code_;
base::Time cached_code_response_time_;
base::Time resource_response_time_;
+ bool use_isolated_code_cache_ = false;
base::WeakPtrFactory<CodeCacheRequest> weak_ptr_factory_;
};
@@ -213,8 +214,10 @@ bool ResourceLoader::CodeCacheRequest::FetchFromCodeCacheSynchronously(
// the response_time if the response from code cache is not available yet.
void ResourceLoader::CodeCacheRequest::DidReceiveResponse(
const base::Time& resource_response_time,
+ bool use_isolated_code_cache,
ResourceLoader* resource_loader) {
resource_response_time_ = resource_response_time;
+ use_isolated_code_cache_ = use_isolated_code_cache;
MaybeSendCachedCode(cached_code_, resource_loader);
}
@@ -270,7 +273,11 @@ void ResourceLoader::CodeCacheRequest::MaybeSendCachedCode(
return;
}
- if (resource_response_time_ != cached_code_response_time_) {
+ // If the resource was fetched for service worker script or was served from
+ // CacheStorage via service worker then they maintain their own code cache.
+ // We should not use the isolated cache.
+ if (!use_isolated_code_cache_ ||
+ resource_response_time_ != cached_code_response_time_) {
resource_loader->ClearCachedCode();
return;
}
@@ -285,8 +292,8 @@ ResourceLoader* ResourceLoader::Create(ResourceFetcher* fetcher,
ResourceLoadScheduler* scheduler,
Resource* resource,
uint32_t inflight_keepalive_bytes) {
- return new ResourceLoader(fetcher, scheduler, resource,
- inflight_keepalive_bytes);
+ return MakeGarbageCollected<ResourceLoader>(fetcher, scheduler, resource,
+ inflight_keepalive_bytes);
}
ResourceLoader::ResourceLoader(ResourceFetcher* fetcher,
@@ -321,6 +328,9 @@ void ResourceLoader::Trace(blink::Visitor* visitor) {
bool ResourceLoader::ShouldFetchCodeCache() {
if (!RuntimeEnabledFeatures::IsolatedCodeCacheEnabled())
return false;
+ if (resource_->GetType() == ResourceType::kRaw &&
+ !RuntimeEnabledFeatures::WasmCodeCacheEnabled())
+ return false;
// TODO(crbug.com/867347): Enable fetching of code caches on non-main threads
// once code cache has its own mojo interface. Currently it is using
@@ -331,8 +341,21 @@ bool ResourceLoader::ShouldFetchCodeCache() {
const ResourceRequest& request = resource_->GetResourceRequest();
if (!request.Url().ProtocolIsInHTTPFamily())
return false;
+ // When loading the service worker scripts, we don't need to check the
+ // GeneratedCodeCache. The code cache corresponding to these scripts is in
+ // the service worker's "installed script storage" and would be fetched along
+ // with the resource from the cache storage.
if (request.GetRequestContext() == mojom::RequestContextType::SERVICE_WORKER)
return false;
+ // These requests are serviced by the service worker. It is possible that the
+ // service worker may not service the request in which case it is serviced
+ // by the network. Assuming those fallback cases are not frequent, we don't
+ // fetch from code cache. We may want to have some actual data, to make an
+ // informed decision.
+ // TODO(crbug.com/895850): Get UMA data to see if this check is necessary.
+ if (ResourceLoader::Context().IsControlledByServiceWorker() ==
+ mojom::ControllerServiceWorkerMode::kControlled)
+ return false;
if (request.DownloadToBlob())
return false;
// Javascript resources have type kScript or kMainResource (for inline
@@ -370,11 +393,11 @@ void ResourceLoader::Start() {
throttle_option = ResourceLoadScheduler::ThrottleOption::kStoppable;
}
- if (ShouldCheckCORSInResourceLoader()) {
+ if (ShouldCheckCorsInResourceLoader()) {
const auto origin = resource_->GetOrigin();
- response_tainting_ = CORS::CalculateResponseTainting(
+ response_tainting_ = cors::CalculateResponseTainting(
request.Url(), request.GetFetchRequestMode(), origin.get(),
- GetCORSFlag() ? CORSFlag::Set : CORSFlag::Unset);
+ GetCorsFlag() ? CorsFlag::Set : CorsFlag::Unset);
}
if (request.IsAutomaticUpgrade()) {
@@ -384,6 +407,13 @@ void ResourceLoader::Start() {
base::nullopt, request.GetUkmSourceId(),
recorder.get());
}
+ if (resource_->GetResourceRequest().IsDownloadToNetworkCacheOnly()) {
+ // The download-to-cache requests are throttled in net/, they are fire-and
+ // forget, and cannot unregister properly from the scheduler once they are
+ // finished.
+ throttle_option =
+ ResourceLoadScheduler::ThrottleOption::kCanNotBeStoppedOrThrottled;
+ }
scheduler_->Request(this, throttle_option, request.Priority(),
request.IntraPriorityValue(), &scheduler_client_id_);
}
@@ -518,7 +548,7 @@ bool ResourceLoader::WillFollowRedirect(
const WebURL& new_url,
const WebURL& new_site_for_cookies,
const WebString& new_referrer,
- WebReferrerPolicy new_referrer_policy,
+ network::mojom::ReferrerPolicy new_referrer_policy,
const WebString& new_method,
const WebURLResponse& passed_redirect_response,
bool& report_raw_headers) {
@@ -534,7 +564,7 @@ bool ResourceLoader::WillFollowRedirect(
std::unique_ptr<ResourceRequest> new_request =
resource_->LastResourceRequest().CreateRedirectRequest(
new_url, new_method, new_site_for_cookies, new_referrer,
- static_cast<ReferrerPolicy>(new_referrer_policy),
+ new_referrer_policy,
!passed_redirect_response.WasFetchedViaServiceWorker());
ResourceType resource_type = resource_->GetType();
@@ -584,15 +614,15 @@ bool ResourceLoader::WillFollowRedirect(
return false;
}
- if (ShouldCheckCORSInResourceLoader()) {
+ if (ShouldCheckCorsInResourceLoader()) {
scoped_refptr<const SecurityOrigin> origin = resource_->GetOrigin();
- base::Optional<network::CORSErrorStatus> cors_error =
- CORS::CheckRedirectLocation(
+ base::Optional<network::CorsErrorStatus> cors_error =
+ cors::CheckRedirectLocation(
new_url, fetch_request_mode, origin.get(),
- GetCORSFlag() ? CORSFlag::Set : CORSFlag::Unset);
- if (!cors_error && GetCORSFlag()) {
+ GetCorsFlag() ? CorsFlag::Set : CorsFlag::Unset);
+ if (!cors_error && GetCorsFlag()) {
cors_error =
- CORS::CheckAccess(new_url, redirect_response.HttpStatusCode(),
+ cors::CheckAccess(new_url, redirect_response.HttpStatusCode(),
redirect_response.HttpHeaderFields(),
fetch_credentials_mode, *origin);
}
@@ -626,8 +656,8 @@ bool ResourceLoader::WillFollowRedirect(
cross_origin);
base::Optional<ResourceResponse> redirect_response_with_type;
- if (ShouldCheckCORSInResourceLoader()) {
- new_request->SetAllowStoredCredentials(CORS::CalculateCredentialsFlag(
+ if (ShouldCheckCorsInResourceLoader()) {
+ new_request->SetAllowStoredCredentials(cors::CalculateCredentialsFlag(
fetch_credentials_mode, response_tainting_));
if (!redirect_response.WasFetchedViaServiceWorker()) {
auto response_type = response_tainting_;
@@ -691,24 +721,24 @@ bool ResourceLoader::WillFollowRedirect(
return false;
}
- if (ShouldCheckCORSInResourceLoader()) {
+ if (ShouldCheckCorsInResourceLoader()) {
bool new_cors_flag =
- GetCORSFlag() || CORS::CalculateCORSFlag(new_request->Url(),
+ GetCorsFlag() || cors::CalculateCorsFlag(new_request->Url(),
resource_->GetOrigin().get(),
fetch_request_mode);
resource_->MutableOptions().cors_flag = new_cors_flag;
// Cross-origin requests are only allowed certain registered schemes.
- if (GetCORSFlag() && !SchemeRegistry::ShouldTreatURLSchemeAsCORSEnabled(
+ if (GetCorsFlag() && !SchemeRegistry::ShouldTreatURLSchemeAsCorsEnabled(
new_request->Url().Protocol())) {
HandleError(
ResourceError(new_request->Url(),
- network::CORSErrorStatus(
- network::mojom::CORSError::kCORSDisabledScheme)));
+ network::CorsErrorStatus(
+ network::mojom::CorsError::kCorsDisabledScheme)));
return false;
}
- response_tainting_ = CORS::CalculateResponseTainting(
+ response_tainting_ = cors::CalculateResponseTainting(
new_request->Url(), fetch_request_mode, resource_->GetOrigin().get(),
- GetCORSFlag() ? CORSFlag::Set : CORSFlag::Unset);
+ GetCorsFlag() ? CorsFlag::Set : CorsFlag::Unset);
}
report_raw_headers = new_request->ReportRawHeaders();
@@ -716,7 +746,7 @@ bool ResourceLoader::WillFollowRedirect(
}
void ResourceLoader::DidReceiveCachedMetadata(const char* data, int length) {
- DCHECK(!RuntimeEnabledFeatures::IsolatedCodeCacheEnabled());
+ DCHECK(!should_use_isolated_code_cache_);
resource_->SetSerializedCachedMetadata(data, length);
}
@@ -776,6 +806,14 @@ void ResourceLoader::DidReceiveResponse(
const ResourceLoaderOptions& options = resource_->Options();
const ResourceResponse& response = web_url_response.ToResourceResponse();
+ // Service worker script has its own code cache. And also, resources which
+ // are served from CacheStorage via service workers have its own code cache.
+ // We should not use cached code from site isolated GeneratedCodeCache in such
+ // cases.
+ should_use_isolated_code_cache_ =
+ RuntimeEnabledFeatures::IsolatedCodeCacheEnabled() &&
+ !(request_context == mojom::RequestContextType::SERVICE_WORKER ||
+ response.WasFetchedViaServiceWorker());
// Perform 'nosniff' checks against the original response instead of the 304
// response for a successful revalidation.
@@ -793,8 +831,8 @@ void ResourceLoader::DidReceiveResponse(
if (response.WasFetchedViaServiceWorker()) {
if (options.cors_handling_by_resource_fetcher ==
- kEnableCORSHandlingByResourceFetcher &&
- fetch_request_mode == network::mojom::FetchRequestMode::kCORS &&
+ kEnableCorsHandlingByResourceFetcher &&
+ fetch_request_mode == network::mojom::FetchRequestMode::kCors &&
response.WasFallbackRequiredByServiceWorker()) {
ResourceRequest last_request = resource_->LastResourceRequest();
DCHECK(!last_request.GetSkipServiceWorker());
@@ -837,11 +875,11 @@ void ResourceLoader::DidReceiveResponse(
}
base::Optional<ResourceResponse> response_with_type;
- if (ShouldCheckCORSInResourceLoader() &&
+ if (ShouldCheckCorsInResourceLoader() &&
!response.WasFetchedViaServiceWorker() &&
!(resource_->IsCacheValidator() && response.HttpStatusCode() == 304)) {
- if (GetCORSFlag()) {
- base::Optional<network::CORSErrorStatus> cors_error = CORS::CheckAccess(
+ if (GetCorsFlag()) {
+ base::Optional<network::CorsErrorStatus> cors_error = cors::CheckAccess(
response.Url(), response.HttpStatusCode(),
response.HttpHeaderFields(),
initial_request.GetFetchCredentialsMode(), *resource_->GetOrigin());
@@ -870,8 +908,10 @@ void ResourceLoader::DidReceiveResponse(
// Send the cached code after we notify that the response is received.
// Resource expects that we receive the response first before the
// corresponding cached code.
- if (code_cache_request_)
- code_cache_request_->DidReceiveResponse(response.ResponseTime(), this);
+ if (code_cache_request_) {
+ code_cache_request_->DidReceiveResponse(
+ response.ResponseTime(), should_use_isolated_code_cache_, this);
+ }
if (!resource_->Loader())
return;
@@ -902,8 +942,8 @@ void ResourceLoader::DidStartLoadingResponseBody(
mojom::blink::BlobRegistry* blob_registry = BlobDataHandle::GetBlobRegistry();
blob_registry->RegisterFromStream(
mime_type.IsNull() ? g_empty_string : mime_type.LowerASCII(), "",
- std::max(0ll, response.ExpectedContentLength()), std::move(body),
- std::move(progress_client_ptr),
+ std::max(static_cast<int64_t>(0), response.ExpectedContentLength()),
+ std::move(body), std::move(progress_client_ptr),
WTF::Bind(&ResourceLoader::FinishedCreatingBlob,
WrapWeakPersistent(this)));
}
@@ -993,10 +1033,10 @@ void ResourceLoader::HandleError(const ResourceError& error) {
Restart(resource_->GetResourceRequest());
return;
}
- if (error.CORSErrorStatus()) {
+ if (error.CorsErrorStatus()) {
Context().AddErrorConsoleMessage(
- CORS::GetErrorString(
- *error.CORSErrorStatus(), resource_->GetResourceRequest().Url(),
+ cors::GetErrorString(
+ *error.CorsErrorStatus(), resource_->GetResourceRequest().Url(),
resource_->LastResourceRequest().Url(), *resource_->GetOrigin(),
resource_->GetType(), resource_->Options().initiator_info.name),
FetchContext::kJSSource);
@@ -1055,7 +1095,7 @@ void ResourceLoader::RequestSynchronously(const ResourceRequest& request) {
if (data_out.size()) {
data_out.ForEachSegment([this](const char* segment, size_t segment_size,
size_t segment_offset) {
- DidReceiveData(segment, segment_size);
+ DidReceiveData(segment, SafeCast<int>(segment_size));
return true;
});
}
@@ -1132,7 +1172,7 @@ void ResourceLoader::OnProgress(uint64_t delta) {
return;
Context().DispatchDidReceiveData(resource_->Identifier(), nullptr, delta);
- resource_->DidDownloadData(delta);
+ resource_->DidDownloadData(SafeCast<int>(delta));
}
void ResourceLoader::FinishedCreatingBlob(
@@ -1161,7 +1201,7 @@ ResourceLoader::CheckResponseNosniff(mojom::RequestContextType request_context,
const ResourceResponse& response) const {
bool sniffing_allowed =
ParseContentTypeOptionsHeader(response.HttpHeaderField(
- HTTPNames::X_Content_Type_Options)) != kContentTypeOptionsNosniff;
+ http_names::kXContentTypeOptions)) != kContentTypeOptionsNosniff;
if (sniffing_allowed)
return base::nullopt;
@@ -1182,10 +1222,10 @@ ResourceLoader::CheckResponseNosniff(mojom::RequestContextType request_context,
return base::nullopt;
}
-bool ResourceLoader::ShouldCheckCORSInResourceLoader() const {
- return !RuntimeEnabledFeatures::OutOfBlinkCORSEnabled() &&
+bool ResourceLoader::ShouldCheckCorsInResourceLoader() const {
+ return !RuntimeEnabledFeatures::OutOfBlinkCorsEnabled() &&
resource_->Options().cors_handling_by_resource_fetcher ==
- kEnableCORSHandlingByResourceFetcher;
+ kEnableCorsHandlingByResourceFetcher;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.h
index ed7a4a5c816..2cc7f9cae9d 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader.h
@@ -68,6 +68,12 @@ class PLATFORM_EXPORT ResourceLoader final
ResourceLoadScheduler*,
Resource*,
uint32_t inflight_keepalive_bytes = 0);
+
+ // Assumes ResourceFetcher and Resource are non-null.
+ ResourceLoader(ResourceFetcher*,
+ ResourceLoadScheduler*,
+ Resource*,
+ uint32_t inflight_keepalive_bytes);
~ResourceLoader() override;
void Trace(blink::Visitor*) override;
@@ -106,7 +112,7 @@ class PLATFORM_EXPORT ResourceLoader final
bool WillFollowRedirect(const WebURL& new_url,
const WebURL& new_site_for_cookies,
const WebString& new_referrer,
- WebReferrerPolicy new_referrer_policy,
+ network::mojom::ReferrerPolicy new_referrer_policy,
const WebString& new_method,
const WebURLResponse& passed_redirect_response,
bool& report_raw_headers) override;
@@ -149,12 +155,6 @@ class PLATFORM_EXPORT ResourceLoader final
friend class SubresourceIntegrityTest;
class CodeCacheRequest;
- // Assumes ResourceFetcher and Resource are non-null.
- ResourceLoader(ResourceFetcher*,
- ResourceLoadScheduler*,
- Resource*,
- uint32_t inflight_keepalive_bytes);
-
bool ShouldFetchCodeCache();
void StartWith(const ResourceRequest&);
@@ -178,13 +178,13 @@ class PLATFORM_EXPORT ResourceLoader final
void OnProgress(uint64_t delta) override;
void FinishedCreatingBlob(const scoped_refptr<BlobDataHandle>&);
- bool GetCORSFlag() const { return resource_->Options().cors_flag; }
+ bool GetCorsFlag() const { return resource_->Options().cors_flag; }
base::Optional<ResourceRequestBlockedReason> CheckResponseNosniff(
mojom::RequestContextType,
const ResourceResponse&) const;
- bool ShouldCheckCORSInResourceLoader() const;
+ bool ShouldCheckCorsInResourceLoader() const;
std::unique_ptr<WebURLLoader> loader_;
ResourceLoadScheduler::ClientId scheduler_client_id_;
@@ -201,6 +201,7 @@ class PLATFORM_EXPORT ResourceLoader final
uint32_t inflight_keepalive_bytes_;
bool is_cache_aware_loading_activated_;
+ bool should_use_isolated_code_cache_ = false;
bool is_downloading_to_blob_ = false;
mojo::AssociatedBinding<mojom::blink::ProgressClient> progress_binding_;
bool blob_finished_ = false;
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_defer_loading_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_defer_loading_test.cc
new file mode 100644
index 00000000000..66c097c3235
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_defer_loading_test.cc
@@ -0,0 +1,275 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/loader/fetch/resource_loader.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/platform/web_url_loader.h"
+#include "third_party/blink/public/platform/web_url_loader_factory.h"
+#include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
+#include "third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h"
+#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
+
+namespace blink {
+
+class ResourceLoaderDefersLoadingTest : public testing::Test {
+ public:
+ using ProcessCodeCacheRequestCallback =
+ base::RepeatingCallback<void(CodeCacheLoader::FetchCodeCacheCallback)>;
+ class TestingPlatformSupportWithMockCodeCacheLoader;
+ class TestCodeCacheLoader;
+ class TestWebURLLoaderFactory;
+ class TestWebURLLoader;
+
+ ResourceLoaderDefersLoadingTest();
+
+ void SetUp() override {
+ context_ =
+ MockFetchContext::Create(MockFetchContext::kShouldLoadNewResource);
+ }
+
+ void SaveCodeCacheCallback(CodeCacheLoader::FetchCodeCacheCallback callback) {
+ // Store the callback to send back a response.
+ code_cache_response_callback_ = std::move(callback);
+ }
+
+ CodeCacheLoader::FetchCodeCacheCallback code_cache_response_callback_;
+ // Passed to TestWebURLLoader (via |platform_|) and updated when its
+ // SetDefersLoading method is called.
+ bool web_url_loader_defers_ = false;
+ Persistent<MockFetchContext> context_;
+ const KURL test_url_;
+
+ ScopedTestingPlatformSupport<
+ ResourceLoaderDefersLoadingTest::
+ TestingPlatformSupportWithMockCodeCacheLoader,
+ bool*>
+ platform_;
+};
+
+// A mock code cache loader that calls the processing function whenever it
+// receives fetch requests.
+class ResourceLoaderDefersLoadingTest::TestCodeCacheLoader
+ : public CodeCacheLoader {
+ public:
+ explicit TestCodeCacheLoader(ProcessCodeCacheRequestCallback callback)
+ : process_request_(callback) {}
+ ~TestCodeCacheLoader() override = default;
+
+ // CodeCacheLoader methods:
+ void FetchFromCodeCacheSynchronously(
+ const GURL& url,
+ base::Time* response_time_out,
+ std::vector<uint8_t>* data_out) override {}
+ void FetchFromCodeCache(
+ blink::mojom::CodeCacheType cache_type,
+ const GURL& url,
+ CodeCacheLoader::FetchCodeCacheCallback callback) override {
+ process_request_.Run(std::move(callback));
+ }
+
+ private:
+ ProcessCodeCacheRequestCallback process_request_;
+};
+
+// A mock WebURLLoader to know the status of defers flag.
+class ResourceLoaderDefersLoadingTest::TestWebURLLoader final
+ : public WebURLLoader {
+ public:
+ explicit TestWebURLLoader(bool* const defers_flag_ptr)
+ : defers_flag_ptr_(defers_flag_ptr) {}
+ ~TestWebURLLoader() override = default;
+
+ void LoadSynchronously(const WebURLRequest&,
+ WebURLLoaderClient*,
+ WebURLResponse&,
+ base::Optional<WebURLError>&,
+ WebData&,
+ int64_t& encoded_data_length,
+ int64_t& encoded_body_length,
+ WebBlobInfo& downloaded_blob) override {
+ NOTREACHED();
+ }
+ void LoadAsynchronously(const WebURLRequest&, WebURLLoaderClient*) override {}
+
+ void Cancel() override {}
+ void SetDefersLoading(bool defers) override { *defers_flag_ptr_ = defers; }
+ void DidChangePriority(WebURLRequest::Priority, int) override {
+ NOTREACHED();
+ }
+
+ private:
+ // Points to |ResourceLoaderDefersLoadingTest::web_url_loader_defers_|.
+ bool* const defers_flag_ptr_;
+};
+
+// Mock WebURLLoaderFactory.
+class ResourceLoaderDefersLoadingTest::TestWebURLLoaderFactory final
+ : public WebURLLoaderFactory {
+ public:
+ explicit TestWebURLLoaderFactory(bool* const defers_flag)
+ : defers_flag_(defers_flag) {}
+
+ std::unique_ptr<WebURLLoader> CreateURLLoader(
+ const WebURLRequest& request,
+ std::unique_ptr<scheduler::WebResourceLoadingTaskRunnerHandle>) override {
+ return std::make_unique<TestWebURLLoader>(defers_flag_);
+ }
+
+ private:
+ // Points to |ResourceLoaderDefersLoadingTest::web_url_loader_defers_|.
+ bool* const defers_flag_;
+};
+
+// Mock TestPlatform to create the specific WebURLLoaderFactory and
+// CodeCacheLoader required for the tests.
+class ResourceLoaderDefersLoadingTest::
+ TestingPlatformSupportWithMockCodeCacheLoader
+ : public TestingPlatformSupportWithMockScheduler {
+ public:
+ TestingPlatformSupportWithMockCodeCacheLoader(bool* const defers_flag)
+ : defers_flag_(defers_flag) {}
+
+ std::unique_ptr<CodeCacheLoader> CreateCodeCacheLoader() override {
+ return std::make_unique<TestCodeCacheLoader>(process_code_cache_request_);
+ }
+
+ std::unique_ptr<WebURLLoaderFactory> CreateDefaultURLLoaderFactory()
+ override {
+ return std::make_unique<TestWebURLLoaderFactory>(defers_flag_);
+ }
+
+ void SetCodeCacheProcessFunction(ProcessCodeCacheRequestCallback callback) {
+ process_code_cache_request_ = callback;
+ }
+
+ private:
+ ProcessCodeCacheRequestCallback process_code_cache_request_;
+ // Points to |ResourceLoaderDefersLoadingTest::web_url_loader_defers_|.
+ bool* const defers_flag_;
+};
+
+ResourceLoaderDefersLoadingTest::ResourceLoaderDefersLoadingTest()
+ : test_url_("http://example.com/"), platform_(&web_url_loader_defers_) {
+ // Saves the callback to control when the response is sent from
+ // the code cache loader.
+ platform_->SetCodeCacheProcessFunction(base::BindRepeating(
+ &ResourceLoaderDefersLoadingTest::SaveCodeCacheCallback,
+ base::Unretained(this)));
+}
+
+TEST_F(ResourceLoaderDefersLoadingTest, CodeCacheFetchCheckDefers) {
+ ResourceFetcher* fetcher = ResourceFetcher::Create(context_);
+
+ ResourceRequest request;
+ request.SetURL(test_url_);
+ request.SetRequestContext(mojom::RequestContextType::FRAME);
+ request.SetFrameType(network::mojom::RequestContextFrameType::kTopLevel);
+ FetchParameters fetch_parameters(request);
+
+ Resource* resource = RawResource::FetchMainResource(
+ fetch_parameters, fetcher, nullptr, SubstituteData());
+
+ // After code cache fetch it should have deferred WebURLLoader.
+ DCHECK(web_url_loader_defers_);
+ DCHECK(resource);
+ std::move(code_cache_response_callback_)
+ .Run(base::Time(), std::vector<uint8_t>());
+ // Once the response is received it should be reset.
+ DCHECK(!web_url_loader_defers_);
+}
+
+TEST_F(ResourceLoaderDefersLoadingTest, CodeCacheFetchSyncReturn) {
+ platform_->SetCodeCacheProcessFunction(
+ base::BindRepeating([](CodeCacheLoader::FetchCodeCacheCallback callback) {
+ std::move(callback).Run(base::Time(), std::vector<uint8_t>());
+ }));
+
+ ResourceFetcher* fetcher = ResourceFetcher::Create(context_);
+
+ ResourceRequest request;
+ request.SetURL(test_url_);
+ request.SetRequestContext(mojom::RequestContextType::FRAME);
+ request.SetFrameType(network::mojom::RequestContextFrameType::kTopLevel);
+ FetchParameters fetch_parameters(request);
+
+ Resource* resource = RawResource::FetchMainResource(
+ fetch_parameters, fetcher, nullptr, SubstituteData());
+ DCHECK(resource);
+ // The callback would be called so it should not be deferred.
+ DCHECK(!web_url_loader_defers_);
+}
+
+TEST_F(ResourceLoaderDefersLoadingTest, ChangeDefersToFalse) {
+ ResourceFetcher* fetcher = ResourceFetcher::Create(context_);
+
+ ResourceRequest request;
+ request.SetURL(test_url_);
+ request.SetRequestContext(mojom::RequestContextType::FRAME);
+ request.SetFrameType(network::mojom::RequestContextFrameType::kTopLevel);
+ FetchParameters fetch_parameters(request);
+
+ Resource* resource = RawResource::FetchMainResource(
+ fetch_parameters, fetcher, nullptr, SubstituteData());
+ DCHECK(web_url_loader_defers_);
+
+ // Change Defers loading to false. This should not be sent to
+ // WebURLLoader since a code cache request is still pending.
+ ResourceLoader* loader = resource->Loader();
+ loader->SetDefersLoading(false);
+ DCHECK(web_url_loader_defers_);
+}
+
+TEST_F(ResourceLoaderDefersLoadingTest, ChangeDefersToTrue) {
+ ResourceFetcher* fetcher = ResourceFetcher::Create(context_);
+
+ ResourceRequest request;
+ request.SetURL(test_url_);
+ request.SetRequestContext(mojom::RequestContextType::FRAME);
+ request.SetFrameType(network::mojom::RequestContextFrameType::kTopLevel);
+ FetchParameters fetch_parameters(request);
+
+ Resource* resource = RawResource::FetchMainResource(
+ fetch_parameters, fetcher, nullptr, SubstituteData());
+ DCHECK(web_url_loader_defers_);
+
+ ResourceLoader* loader = resource->Loader();
+ loader->SetDefersLoading(true);
+ DCHECK(web_url_loader_defers_);
+
+ std::move(code_cache_response_callback_)
+ .Run(base::Time(), std::vector<uint8_t>());
+ // Since it was requested to be deferred, it should be reset to the
+ // correct value.
+ DCHECK(web_url_loader_defers_);
+}
+
+TEST_F(ResourceLoaderDefersLoadingTest, ChangeDefersMultipleTimes) {
+ ResourceFetcher* fetcher = ResourceFetcher::Create(context_);
+
+ ResourceRequest request;
+ request.SetURL(test_url_);
+ request.SetRequestContext(mojom::RequestContextType::FRAME);
+ request.SetFrameType(network::mojom::RequestContextFrameType::kTopLevel);
+
+ FetchParameters fetch_parameters(request);
+ Resource* resource = RawResource::FetchMainResource(
+ fetch_parameters, fetcher, nullptr, SubstituteData());
+ DCHECK(web_url_loader_defers_);
+
+ ResourceLoader* loader = resource->Loader();
+ loader->SetDefersLoading(true);
+ DCHECK(web_url_loader_defers_);
+
+ loader->SetDefersLoading(false);
+ DCHECK(web_url_loader_defers_);
+
+ std::move(code_cache_response_callback_)
+ .Run(base::Time(), std::vector<uint8_t>());
+ DCHECK(!web_url_loader_defers_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h
index df851a8c97d..07983d1fbb3 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h
@@ -59,9 +59,9 @@ enum SynchronousPolicy : uint8_t {
// Used by the ThreadableLoader to turn off part of the CORS handling
// logic in the ResourceFetcher to use its own CORS handling logic.
-enum CORSHandlingByResourceFetcher {
- kDisableCORSHandlingByResourceFetcher,
- kEnableCORSHandlingByResourceFetcher,
+enum CorsHandlingByResourceFetcher {
+ kDisableCorsHandlingByResourceFetcher,
+ kEnableCorsHandlingByResourceFetcher,
};
// Was the request generated from a "parser-inserted" element?
@@ -83,7 +83,7 @@ struct ResourceLoaderOptions {
content_security_policy_option(kCheckContentSecurityPolicy),
request_initiator_context(kDocumentContext),
synchronous_policy(kRequestAsynchronously),
- cors_handling_by_resource_fetcher(kEnableCORSHandlingByResourceFetcher),
+ cors_handling_by_resource_fetcher(kEnableCorsHandlingByResourceFetcher),
cors_flag(false),
parser_disposition(kParserInserted),
cache_aware_loading_enabled(kNotCacheAwareLoadingEnabled) {}
@@ -96,10 +96,10 @@ struct ResourceLoaderOptions {
RequestInitiatorContext request_initiator_context;
SynchronousPolicy synchronous_policy;
- // When set to kDisableCORSHandlingByResourceFetcher, the ResourceFetcher
+ // When set to kDisableCorsHandlingByResourceFetcher, the ResourceFetcher
// suppresses part of its CORS handling logic.
// Used by ThreadableLoader which does CORS handling by itself.
- CORSHandlingByResourceFetcher cors_handling_by_resource_fetcher;
+ CorsHandlingByResourceFetcher cors_handling_by_resource_fetcher;
// Corresponds to the CORS flag in the Fetch spec.
bool cors_flag;
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_test.cc
index 712f78c73a6..274bcb8e56f 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_loader_test.cc
@@ -106,8 +106,8 @@ std::ostream& operator<<(std::ostream& o, const ResourceLoaderTest::From& f) {
}
TEST_F(ResourceLoaderTest, ResponseType) {
- // This test will be trivial if EnableOutOfBlinkCORS is enabled.
- WebRuntimeFeatures::EnableOutOfBlinkCORS(false);
+ // This test will be trivial if EnableOutOfBlinkCors is enabled.
+ WebRuntimeFeatures::EnableOutOfBlinkCors(false);
const scoped_refptr<const SecurityOrigin> origin =
SecurityOrigin::Create(foo_url_);
@@ -117,40 +117,40 @@ TEST_F(ResourceLoaderTest, ResponseType) {
TestCase cases[] = {
// Same origin response:
- {same_origin_url, FetchRequestMode::kNoCORS, From::kNetwork, no_origin,
+ {same_origin_url, FetchRequestMode::kNoCors, From::kNetwork, no_origin,
FetchResponseType::kDefault, FetchResponseType::kBasic},
- {same_origin_url, FetchRequestMode::kCORS, From::kNetwork, no_origin,
+ {same_origin_url, FetchRequestMode::kCors, From::kNetwork, no_origin,
FetchResponseType::kDefault, FetchResponseType::kBasic},
// Cross origin, no-cors:
- {cross_origin_url, FetchRequestMode::kNoCORS, From::kNetwork, no_origin,
+ {cross_origin_url, FetchRequestMode::kNoCors, From::kNetwork, no_origin,
FetchResponseType::kDefault, FetchResponseType::kOpaque},
// Cross origin, cors:
- {cross_origin_url, FetchRequestMode::kCORS, From::kNetwork, origin,
- FetchResponseType::kDefault, FetchResponseType::kCORS},
- {cross_origin_url, FetchRequestMode::kCORS, From::kNetwork, no_origin,
+ {cross_origin_url, FetchRequestMode::kCors, From::kNetwork, origin,
+ FetchResponseType::kDefault, FetchResponseType::kCors},
+ {cross_origin_url, FetchRequestMode::kCors, From::kNetwork, no_origin,
FetchResponseType::kDefault, FetchResponseType::kError},
// From service worker, no-cors:
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
no_origin, FetchResponseType::kBasic, FetchResponseType::kBasic},
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
- no_origin, FetchResponseType::kCORS, FetchResponseType::kCORS},
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
+ no_origin, FetchResponseType::kCors, FetchResponseType::kCors},
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
no_origin, FetchResponseType::kDefault, FetchResponseType::kDefault},
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
no_origin, FetchResponseType::kOpaque, FetchResponseType::kOpaque},
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
no_origin, FetchResponseType::kOpaqueRedirect,
FetchResponseType::kOpaqueRedirect},
// From service worker, cors:
- {same_origin_url, FetchRequestMode::kCORS, From::kServiceWorker,
+ {same_origin_url, FetchRequestMode::kCors, From::kServiceWorker,
no_origin, FetchResponseType::kBasic, FetchResponseType::kBasic},
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
- no_origin, FetchResponseType::kCORS, FetchResponseType::kCORS},
- {same_origin_url, FetchRequestMode::kNoCORS, From::kServiceWorker,
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
+ no_origin, FetchResponseType::kCors, FetchResponseType::kCors},
+ {same_origin_url, FetchRequestMode::kNoCors, From::kServiceWorker,
no_origin, FetchResponseType::kDefault, FetchResponseType::kDefault},
};
@@ -173,7 +173,7 @@ TEST_F(ResourceLoaderTest, ResponseType) {
request.SetRequestContext(mojom::RequestContextType::FETCH);
FetchParameters fetch_parameters(request);
- if (test.request_mode == network::mojom::FetchRequestMode::kCORS) {
+ if (test.request_mode == network::mojom::FetchRequestMode::kCors) {
fetch_parameters.SetCrossOriginAccessControl(
origin.get(), network::mojom::FetchCredentialsMode::kOmit);
}
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.cc
index b7141499637..4e0c30afdc0 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.cc
@@ -48,7 +48,7 @@ ResourceRequest::ResourceRequest(const String& url_string)
ResourceRequest::ResourceRequest(const KURL& url)
: url_(url),
timeout_interval_(default_timeout_interval_),
- http_method_(HTTPNames::GET),
+ http_method_(http_names::kGET),
allow_stored_credentials_(true),
report_upload_progress_(false),
report_raw_headers_(false),
@@ -58,8 +58,10 @@ ResourceRequest::ResourceRequest(const KURL& url)
keepalive_(false),
should_reset_app_cache_(false),
allow_stale_response_(false),
+ stale_revalidate_candidate_(false),
cache_mode_(mojom::FetchCacheMode::kDefault),
skip_service_worker_(false),
+ download_to_cache_only_(false),
priority_(ResourceLoadPriority::kLowest),
intra_priority_value_(0),
requestor_id_(0),
@@ -68,17 +70,17 @@ ResourceRequest::ResourceRequest(const KURL& url)
previews_state_(WebURLRequest::kPreviewsUnspecified),
request_context_(mojom::RequestContextType::UNSPECIFIED),
frame_type_(network::mojom::RequestContextFrameType::kNone),
- fetch_request_mode_(network::mojom::FetchRequestMode::kNoCORS),
+ fetch_request_mode_(network::mojom::FetchRequestMode::kNoCors),
fetch_importance_mode_(mojom::FetchImportanceMode::kImportanceAuto),
fetch_credentials_mode_(network::mojom::FetchCredentialsMode::kInclude),
fetch_redirect_mode_(network::mojom::FetchRedirectMode::kFollow),
referrer_string_(Referrer::ClientReferrerString()),
- referrer_policy_(kReferrerPolicyDefault),
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
did_set_http_referrer_(false),
was_discarded_(false),
is_external_request_(false),
cors_preflight_policy_(
- network::mojom::CORSPreflightPolicy::kConsiderPreflight),
+ network::mojom::CorsPreflightPolicy::kConsiderPreflight),
redirect_status_(RedirectStatus::kNoRedirect) {}
ResourceRequest::ResourceRequest(const ResourceRequest&) = default;
@@ -92,7 +94,7 @@ std::unique_ptr<ResourceRequest> ResourceRequest::CreateRedirectRequest(
const AtomicString& new_method,
const KURL& new_site_for_cookies,
const String& new_referrer,
- ReferrerPolicy new_referrer_policy,
+ network::mojom::ReferrerPolicy new_referrer_policy,
bool skip_service_worker) const {
std::unique_ptr<ResourceRequest> request =
std::make_unique<ResourceRequest>(new_url);
@@ -103,8 +105,7 @@ std::unique_ptr<ResourceRequest> ResourceRequest::CreateRedirectRequest(
new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer);
// TODO(domfarolino): Stop storing ResourceRequest's generated referrer as a
// header and instead use a separate member. See https://crbug.com/850813.
- request->SetHTTPReferrer(
- Referrer(referrer, static_cast<ReferrerPolicy>(new_referrer_policy)));
+ request->SetHTTPReferrer(Referrer(referrer, new_referrer_policy));
request->SetSkipServiceWorker(skip_service_worker);
request->SetRedirectStatus(RedirectStatus::kFollowedRedirect);
@@ -122,13 +123,14 @@ std::unique_ptr<ResourceRequest> ResourceRequest::CreateRedirectRequest(
if (request->HttpMethod() == HttpMethod())
request->SetHTTPBody(HttpBody());
request->SetWasDiscarded(WasDiscarded());
- request->SetCORSPreflightPolicy(CORSPreflightPolicy());
+ request->SetCorsPreflightPolicy(CorsPreflightPolicy());
if (IsAdResource())
request->SetIsAdResource();
request->SetInitiatorCSP(GetInitiatorCSP());
request->SetUpgradeIfInsecure(UpgradeIfInsecure());
request->SetIsAutomaticUpgrade(IsAutomaticUpgrade());
- request->SetRequestedWith(GetRequestedWith());
+ request->SetRequestedWithHeader(GetRequestedWithHeader());
+ request->SetClientDataHeader(GetClientDataHeader());
request->SetUkmSourceId(GetUkmSourceId());
return request;
@@ -203,25 +205,25 @@ void ResourceRequest::SetHTTPHeaderField(const AtomicString& name,
void ResourceRequest::SetHTTPReferrer(const Referrer& referrer) {
if (referrer.referrer.IsEmpty())
- http_header_fields_.Remove(HTTPNames::Referer);
+ http_header_fields_.Remove(http_names::kReferer);
else
- SetHTTPHeaderField(HTTPNames::Referer, referrer.referrer);
+ SetHTTPHeaderField(http_names::kReferer, referrer.referrer);
referrer_policy_ = referrer.referrer_policy;
did_set_http_referrer_ = true;
}
void ResourceRequest::ClearHTTPReferrer() {
- http_header_fields_.Remove(HTTPNames::Referer);
- referrer_policy_ = kReferrerPolicyDefault;
+ http_header_fields_.Remove(http_names::kReferer);
+ referrer_policy_ = network::mojom::ReferrerPolicy::kDefault;
did_set_http_referrer_ = false;
}
void ResourceRequest::SetHTTPOrigin(const SecurityOrigin* origin) {
- SetHTTPHeaderField(HTTPNames::Origin, origin->ToAtomicString());
+ SetHTTPHeaderField(http_names::kOrigin, origin->ToAtomicString());
}
void ResourceRequest::ClearHTTPOrigin() {
- http_header_fields_.Remove(HTTPNames::Origin);
+ http_header_fields_.Remove(http_names::kOrigin);
}
void ResourceRequest::SetHTTPOriginIfNeeded(const SecurityOrigin* origin) {
@@ -232,13 +234,13 @@ void ResourceRequest::SetHTTPOriginIfNeeded(const SecurityOrigin* origin) {
void ResourceRequest::SetHTTPOriginToMatchReferrerIfNeeded() {
if (NeedsHTTPOrigin()) {
SetHTTPOrigin(
- SecurityOrigin::CreateFromString(HttpHeaderField(HTTPNames::Referer))
+ SecurityOrigin::CreateFromString(HttpHeaderField(http_names::kReferer))
.get());
}
}
void ResourceRequest::ClearHTTPUserAgent() {
- http_header_fields_.Remove(HTTPNames::User_Agent);
+ http_header_fields_.Remove(http_names::kUserAgent);
}
EncodedFormData* ResourceRequest::HttpBody() const {
@@ -308,7 +310,7 @@ void ResourceRequest::SetExternalRequestStateFromRequestorAddressSpace(
}
mojom::IPAddressSpace target_space = mojom::IPAddressSpace::kPublic;
- if (NetworkUtils::IsReservedIPAddress(url_.Host()))
+ if (network_utils::IsReservedIPAddress(url_.Host()))
target_space = mojom::IPAddressSpace::kPrivate;
if (SecurityOrigin::Create(url_)->IsLocalhost())
target_space = mojom::IPAddressSpace::kLocal;
@@ -321,11 +323,11 @@ void ResourceRequest::SetNavigationStartTime(TimeTicks navigation_start) {
}
bool ResourceRequest::IsConditional() const {
- return (http_header_fields_.Contains(HTTPNames::If_Match) ||
- http_header_fields_.Contains(HTTPNames::If_Modified_Since) ||
- http_header_fields_.Contains(HTTPNames::If_None_Match) ||
- http_header_fields_.Contains(HTTPNames::If_Range) ||
- http_header_fields_.Contains(HTTPNames::If_Unmodified_Since));
+ return (http_header_fields_.Contains(http_names::kIfMatch) ||
+ http_header_fields_.Contains(http_names::kIfModifiedSince) ||
+ http_header_fields_.Contains(http_names::kIfNoneMatch) ||
+ http_header_fields_.Contains(http_names::kIfRange) ||
+ http_header_fields_.Contains(http_names::kIfUnmodifiedSince));
}
void ResourceRequest::SetHasUserGesture(bool has_user_gesture) {
@@ -335,8 +337,8 @@ void ResourceRequest::SetHasUserGesture(bool has_user_gesture) {
const CacheControlHeader& ResourceRequest::GetCacheControlHeader() const {
if (!cache_control_header_cache_.parsed) {
cache_control_header_cache_ = ParseCacheControlDirectives(
- http_header_fields_.Get(HTTPNames::Cache_Control),
- http_header_fields_.Get(HTTPNames::Pragma));
+ http_header_fields_.Get(http_names::kCacheControl),
+ http_header_fields_.Get(http_names::kPragma));
}
return cache_control_header_cache_;
}
@@ -350,8 +352,8 @@ bool ResourceRequest::CacheControlContainsNoStore() const {
}
bool ResourceRequest::HasCacheValidatorFields() const {
- return !http_header_fields_.Get(HTTPNames::Last_Modified).IsEmpty() ||
- !http_header_fields_.Get(HTTPNames::ETag).IsEmpty();
+ return !http_header_fields_.Get(http_names::kLastModified).IsEmpty() ||
+ !http_header_fields_.Get(http_names::kETag).IsEmpty();
}
bool ResourceRequest::NeedsHTTPOrigin() const {
@@ -364,7 +366,7 @@ bool ResourceRequest::NeedsHTTPOrigin() const {
// will leak the internal host name. Similar privacy concerns have lead
// to the widespread suppression of the Referer header at the network
// layer.
- if (HttpMethod() == HTTPNames::GET || HttpMethod() == HTTPNames::HEAD)
+ if (HttpMethod() == http_names::kGET || HttpMethod() == http_names::kHEAD)
return false;
// For non-GET and non-HEAD methods, always send an Origin header so the
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.h
index cf82a6123ab..98f750cd6b5 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_request.h
@@ -85,7 +85,7 @@ class PLATFORM_EXPORT ResourceRequest final {
const AtomicString& new_method,
const KURL& new_site_for_cookies,
const String& new_referrer,
- ReferrerPolicy new_referrer_policy,
+ network::mojom::ReferrerPolicy new_referrer_policy,
bool skip_service_worker) const;
bool IsNull() const;
@@ -127,26 +127,28 @@ class PLATFORM_EXPORT ResourceRequest final {
void ClearHTTPHeaderField(const AtomicString& name);
const AtomicString& HttpContentType() const {
- return HttpHeaderField(HTTPNames::Content_Type);
+ return HttpHeaderField(http_names::kContentType);
}
void SetHTTPContentType(const AtomicString& http_content_type) {
- SetHTTPHeaderField(HTTPNames::Content_Type, http_content_type);
+ SetHTTPHeaderField(http_names::kContentType, http_content_type);
}
// TODO(domfarolino): Remove this once we stop storing the generated referrer
// as a header, and instead use a separate member. See
// https://crbug.com/850813.
const AtomicString& HttpReferrer() const {
- return HttpHeaderField(HTTPNames::Referer);
+ return HttpHeaderField(http_names::kReferer);
}
void SetHTTPReferrer(const Referrer&);
bool DidSetHTTPReferrer() const { return did_set_http_referrer_; }
void ClearHTTPReferrer();
- void SetReferrerPolicy(ReferrerPolicy referrer_policy) {
+ void SetReferrerPolicy(network::mojom::ReferrerPolicy referrer_policy) {
referrer_policy_ = referrer_policy;
}
- ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
void SetReferrerString(const String& referrer_string) {
referrer_string_ = referrer_string;
@@ -154,7 +156,7 @@ class PLATFORM_EXPORT ResourceRequest final {
const String& ReferrerString() const { return referrer_string_; }
const AtomicString& HttpOrigin() const {
- return HttpHeaderField(HTTPNames::Origin);
+ return HttpHeaderField(http_names::kOrigin);
}
void SetHTTPOrigin(const SecurityOrigin*);
void ClearHTTPOrigin();
@@ -162,12 +164,12 @@ class PLATFORM_EXPORT ResourceRequest final {
void SetHTTPOriginToMatchReferrerIfNeeded();
void SetHTTPUserAgent(const AtomicString& http_user_agent) {
- SetHTTPHeaderField(HTTPNames::User_Agent, http_user_agent);
+ SetHTTPHeaderField(http_names::kUserAgent, http_user_agent);
}
void ClearHTTPUserAgent();
void SetHTTPAccept(const AtomicString& http_accept) {
- SetHTTPHeaderField(HTTPNames::Accept, http_accept);
+ SetHTTPHeaderField(http_names::kAccept, http_accept);
}
EncodedFormData* HttpBody() const;
@@ -260,6 +262,12 @@ class PLATFORM_EXPORT ResourceRequest final {
}
}
+ bool IsDownloadToNetworkCacheOnly() const { return download_to_cache_only_; }
+
+ void SetDownloadToNetworkCacheOnly(bool download_to_cache_only) {
+ download_to_cache_only_ = download_to_cache_only;
+ }
+
mojom::RequestContextType GetRequestContext() const {
return request_context_;
}
@@ -333,10 +341,10 @@ class PLATFORM_EXPORT ResourceRequest final {
bool IsExternalRequest() const { return is_external_request_; }
void SetExternalRequestStateFromRequestorAddressSpace(mojom::IPAddressSpace);
- network::mojom::CORSPreflightPolicy CORSPreflightPolicy() const {
+ network::mojom::CorsPreflightPolicy CorsPreflightPolicy() const {
return cors_preflight_policy_;
}
- void SetCORSPreflightPolicy(network::mojom::CORSPreflightPolicy policy) {
+ void SetCorsPreflightPolicy(network::mojom::CorsPreflightPolicy policy) {
cors_preflight_policy_ = policy;
}
@@ -378,6 +386,13 @@ class PLATFORM_EXPORT ResourceRequest final {
void SetAllowStaleResponse(bool value) { allow_stale_response_ = value; }
bool AllowsStaleResponse() const { return allow_stale_response_; }
+ void SetStaleRevalidateCandidate(bool value) {
+ stale_revalidate_candidate_ = value;
+ }
+ bool IsStaleRevalidateCandidate() const {
+ return stale_revalidate_candidate_;
+ }
+
const base::Optional<base::UnguessableToken>& GetDevToolsToken() const {
return devtools_token_;
}
@@ -389,8 +404,15 @@ class PLATFORM_EXPORT ResourceRequest final {
void SetOriginPolicy(const String& policy) { origin_policy_ = policy; }
const String& GetOriginPolicy() const { return origin_policy_; }
- void SetRequestedWith(const String& value) { requested_with_ = value; }
- const String& GetRequestedWith() const { return requested_with_; }
+ void SetRequestedWithHeader(const String& value) {
+ requested_with_header_ = value;
+ }
+ const String& GetRequestedWithHeader() const {
+ return requested_with_header_;
+ }
+
+ void SetClientDataHeader(const String& value) { client_data_header_ = value; }
+ const String& GetClientDataHeader() const { return client_data_header_; }
void SetUkmSourceId(int64_t ukm_source_id) { ukm_source_id_ = ukm_source_id; }
int64_t GetUkmSourceId() const { return ukm_source_id_; }
@@ -431,8 +453,10 @@ class PLATFORM_EXPORT ResourceRequest final {
bool keepalive_ : 1;
bool should_reset_app_cache_ : 1;
bool allow_stale_response_ : 1;
+ bool stale_revalidate_candidate_ : 1;
mojom::FetchCacheMode cache_mode_;
bool skip_service_worker_ : 1;
+ bool download_to_cache_only_ : 1;
ResourceLoadPriority priority_;
int intra_priority_value_;
int requestor_id_;
@@ -451,11 +475,11 @@ class PLATFORM_EXPORT ResourceRequest final {
// off-main-thread fetch is fully implemented and ResourceRequest never gets
// transferred between threads. See https://crbug.com/706331.
String referrer_string_;
- ReferrerPolicy referrer_policy_;
+ network::mojom::ReferrerPolicy referrer_policy_;
bool did_set_http_referrer_;
bool was_discarded_;
bool is_external_request_;
- network::mojom::CORSPreflightPolicy cors_preflight_policy_;
+ network::mojom::CorsPreflightPolicy cors_preflight_policy_;
RedirectStatus redirect_status_;
base::Optional<String> suggested_filename_;
@@ -475,7 +499,8 @@ class PLATFORM_EXPORT ResourceRequest final {
base::Optional<base::UnguessableToken> devtools_token_;
String origin_policy_;
- String requested_with_;
+ String requested_with_header_;
+ String client_data_header_;
int64_t ukm_source_id_;
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.cc
index 5405a2e00ca..27757d33de9 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.cc
@@ -112,12 +112,12 @@ void ResourceResponse::SetMimeType(const AtomicString& mime_type) {
mime_type_ = mime_type;
}
-long long ResourceResponse::ExpectedContentLength() const {
+int64_t ResourceResponse::ExpectedContentLength() const {
return expected_content_length_;
}
void ResourceResponse::SetExpectedContentLength(
- long long expected_content_length) {
+ int64_t expected_content_length) {
is_null_ = false;
// FIXME: Content length is determined by HTTP Content-Length header. We
@@ -342,8 +342,8 @@ double ResourceResponse::LastModified() const {
bool ResourceResponse::IsAttachment() const {
static const char kAttachmentString[] = "attachment";
- String value = http_header_fields_.Get(HTTPNames::Content_Disposition);
- size_t loc = value.find(';');
+ String value = http_header_fields_.Get(http_names::kContentDisposition);
+ wtf_size_t loc = value.find(';');
if (loc != kNotFound)
value = value.Left(loc);
value = value.StripWhiteSpace();
@@ -352,7 +352,7 @@ bool ResourceResponse::IsAttachment() const {
AtomicString ResourceResponse::HttpContentType() const {
return ExtractMIMETypeFromMediaType(
- HttpHeaderField(HTTPNames::Content_Type).DeprecatedLower());
+ HttpHeaderField(http_names::kContentType).DeprecatedLower());
}
bool ResourceResponse::WasCached() const {
@@ -402,7 +402,7 @@ void ResourceResponse::SetCTPolicyCompliance(CTPolicyCompliance compliance) {
}
bool ResourceResponse::IsOpaqueResponseFromServiceWorker() const {
- return IsCORSCrossOrigin() && WasFetchedViaServiceWorker();
+ return IsCorsCrossOrigin() && WasFetchedViaServiceWorker();
}
KURL ResourceResponse::OriginalURLViaServiceWorker() const {
@@ -419,15 +419,15 @@ AtomicString ResourceResponse::ConnectionInfoString() const {
connection_info_string.length());
}
-void ResourceResponse::SetEncodedDataLength(long long value) {
+void ResourceResponse::SetEncodedDataLength(int64_t value) {
encoded_data_length_ = value;
}
-void ResourceResponse::SetEncodedBodyLength(long long value) {
+void ResourceResponse::SetEncodedBodyLength(int64_t value) {
encoded_body_length_ = value;
}
-void ResourceResponse::SetDecodedBodyLength(long long value) {
+void ResourceResponse::SetDecodedBodyLength(int64_t value) {
decoded_body_length_ = value;
}
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.h b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.h
index eb219c3af24..bd18c9cc5cd 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response.h
@@ -172,8 +172,8 @@ class PLATFORM_EXPORT ResourceResponse final {
const AtomicString& MimeType() const;
void SetMimeType(const AtomicString&);
- long long ExpectedContentLength() const;
- void SetExpectedContentLength(long long);
+ int64_t ExpectedContentLength() const;
+ void SetExpectedContentLength(int64_t);
const AtomicString& TextEncodingName() const;
void SetTextEncodingName(const AtomicString&);
@@ -248,6 +248,9 @@ class PLATFORM_EXPORT ResourceResponse final {
is_legacy_symantec_cert_ = is_legacy_symantec_cert;
}
+ bool IsLegacyTLSVersion() const { return is_legacy_tls_version_; }
+ void SetIsLegacyTLSVersion(bool value) { is_legacy_tls_version_ = value; }
+
SecurityStyle GetSecurityStyle() const { return security_style_; }
void SetSecurityStyle(SecurityStyle security_style) {
security_style_ = security_style;
@@ -269,8 +272,8 @@ class PLATFORM_EXPORT ResourceResponse final {
const Vector<AtomicString>& certificate,
const SignedCertificateTimestampList& sct_list);
- long long AppCacheID() const { return app_cache_id_; }
- void SetAppCacheID(long long id) { app_cache_id_ = id; }
+ int64_t AppCacheID() const { return app_cache_id_; }
+ void SetAppCacheID(int64_t id) { app_cache_id_ = id; }
const KURL& AppCacheManifestURL() const { return app_cache_manifest_url_; }
void SetAppCacheManifestURL(const KURL& url) {
@@ -302,12 +305,12 @@ class PLATFORM_EXPORT ResourceResponse final {
}
bool IsOpaqueResponseFromServiceWorker() const;
// https://html.spec.whatwg.org/#cors-same-origin
- bool IsCORSSameOrigin() const {
- return network::cors::IsCORSSameOriginResponseType(response_type_);
+ bool IsCorsSameOrigin() const {
+ return network::cors::IsCorsSameOriginResponseType(response_type_);
}
// https://html.spec.whatwg.org/#cors-cross-origin
- bool IsCORSCrossOrigin() const {
- return network::cors::IsCORSCrossOriginResponseType(response_type_);
+ bool IsCorsCrossOrigin() const {
+ return network::cors::IsCorsCrossOriginResponseType(response_type_);
}
// See ServiceWorkerResponseInfo::url_list_via_service_worker.
@@ -323,7 +326,7 @@ class PLATFORM_EXPORT ResourceResponse final {
KURL OriginalURLViaServiceWorker() const;
const Vector<char>& MultipartBoundary() const { return multipart_boundary_; }
- void SetMultipartBoundary(const char* bytes, size_t size) {
+ void SetMultipartBoundary(const char* bytes, uint32_t size) {
multipart_boundary_.clear();
multipart_boundary_.Append(bytes, size);
}
@@ -376,14 +379,14 @@ class PLATFORM_EXPORT ResourceResponse final {
AtomicString ConnectionInfoString() const;
- long long EncodedDataLength() const { return encoded_data_length_; }
- void SetEncodedDataLength(long long value);
+ int64_t EncodedDataLength() const { return encoded_data_length_; }
+ void SetEncodedDataLength(int64_t value);
- long long EncodedBodyLength() const { return encoded_body_length_; }
- void SetEncodedBodyLength(long long value);
+ int64_t EncodedBodyLength() const { return encoded_body_length_; }
+ void SetEncodedBodyLength(int64_t value);
- long long DecodedBodyLength() const { return decoded_body_length_; }
- void SetDecodedBodyLength(long long value);
+ int64_t DecodedBodyLength() const { return decoded_body_length_; }
+ void SetDecodedBodyLength(int64_t value);
// Extra data associated with this response.
ExtraData* GetExtraData() const { return extra_data_.get(); }
@@ -412,6 +415,12 @@ class PLATFORM_EXPORT ResourceResponse final {
async_revalidation_requested_ = requested;
}
+ bool NetworkAccessed() const { return network_accessed_; }
+
+ void SetNetworkAccessed(bool network_accessed) {
+ network_accessed_ = network_accessed;
+ }
+
bool IsSignedExchangeInnerResponse() const {
return is_signed_exchange_inner_response_;
}
@@ -463,6 +472,10 @@ class PLATFORM_EXPORT ResourceResponse final {
// is slated for distrust in future.
bool is_legacy_symantec_cert_ = false;
+ // True if the response was sent over TLS 1.0 or 1.1, which are deprecated and
+ // will be removed in the future.
+ bool is_legacy_tls_version_ = false;
+
// The time at which the resource's certificate expires. Null if there was no
// certificate.
base::Time cert_validity_start_;
@@ -488,6 +501,9 @@ class PLATFORM_EXPORT ResourceResponse final {
// https://wicg.github.io/webpackage/draft-yasskin-http-origin-signed-responses.html
bool is_signed_exchange_inner_response_ = false;
+ // True if this resource was loaded from the network.
+ bool network_accessed_ = false;
+
// https://fetch.spec.whatwg.org/#concept-response-type
network::mojom::FetchResponseType response_type_ =
network::mojom::FetchResponseType::kDefault;
@@ -520,7 +536,7 @@ class PLATFORM_EXPORT ResourceResponse final {
// The id of the appcache this response was retrieved from, or zero if
// the response was not retrieved from an appcache.
- long long app_cache_id_ = 0;
+ int64_t app_cache_id_ = 0;
// The manifest url of the appcache this response was retrieved from, if any.
// Note: only valid for main resource responses.
@@ -553,14 +569,14 @@ class PLATFORM_EXPORT ResourceResponse final {
net::HttpResponseInfo::ConnectionInfo::CONNECTION_INFO_UNKNOWN;
// Size of the response in bytes prior to decompression.
- long long encoded_data_length_ = 0;
+ int64_t encoded_data_length_ = 0;
// Size of the response body in bytes prior to decompression.
- long long encoded_body_length_ = 0;
+ int64_t encoded_body_length_ = 0;
// Sizes of the response body in bytes after any content-encoding is
// removed.
- long long decoded_body_length_ = 0;
+ int64_t decoded_body_length_ = 0;
// ExtraData associated with the response.
scoped_refptr<ExtraData> extra_data_;
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response_test.cc
index 9d5f60ee271..d97d53a19d2 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_response_test.cc
@@ -7,9 +7,9 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_test.cc
index ca4f8952cd3..014a96dc783 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/resource_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/resource_test.cc
@@ -42,7 +42,7 @@ class MockPlatform final : public TestingPlatformSupportWithMockScheduler {
};
ResourceResponse CreateTestResourceResponse() {
- ResourceResponse response(URLTestHelpers::ToKURL("https://example.com/"));
+ ResourceResponse response(url_test_helpers::ToKURL("https://example.com/"));
response.SetHTTPStatusCode(200);
return response;
}
@@ -105,46 +105,46 @@ TEST(ResourceTest, Vary) {
ResourceRequest new_request(url);
EXPECT_FALSE(resource->MustReloadDueToVaryHeader(new_request));
- response.SetHTTPHeaderField(HTTPNames::Vary, "*");
+ response.SetHTTPHeaderField(http_names::kVary, "*");
resource->SetResponse(response);
EXPECT_TRUE(resource->MustReloadDueToVaryHeader(new_request));
// Irrelevant header
- response.SetHTTPHeaderField(HTTPNames::Vary, "definitelynotarealheader");
+ response.SetHTTPHeaderField(http_names::kVary, "definitelynotarealheader");
resource->SetResponse(response);
EXPECT_FALSE(resource->MustReloadDueToVaryHeader(new_request));
// Header present on new but not old
- new_request.SetHTTPHeaderField(HTTPNames::User_Agent, "something");
- response.SetHTTPHeaderField(HTTPNames::Vary, HTTPNames::User_Agent);
+ new_request.SetHTTPHeaderField(http_names::kUserAgent, "something");
+ response.SetHTTPHeaderField(http_names::kVary, http_names::kUserAgent);
resource->SetResponse(response);
EXPECT_TRUE(resource->MustReloadDueToVaryHeader(new_request));
- new_request.ClearHTTPHeaderField(HTTPNames::User_Agent);
+ new_request.ClearHTTPHeaderField(http_names::kUserAgent);
ResourceRequest old_request(url);
- old_request.SetHTTPHeaderField(HTTPNames::User_Agent, "something");
- old_request.SetHTTPHeaderField(HTTPNames::Referer, "http://foo.com");
+ old_request.SetHTTPHeaderField(http_names::kUserAgent, "something");
+ old_request.SetHTTPHeaderField(http_names::kReferer, "http://foo.com");
resource = MockResource::Create(old_request);
resource->ResponseReceived(response, nullptr);
resource->FinishForTest();
// Header present on old but not new
- new_request.ClearHTTPHeaderField(HTTPNames::User_Agent);
- response.SetHTTPHeaderField(HTTPNames::Vary, HTTPNames::User_Agent);
+ new_request.ClearHTTPHeaderField(http_names::kUserAgent);
+ response.SetHTTPHeaderField(http_names::kVary, http_names::kUserAgent);
resource->SetResponse(response);
EXPECT_TRUE(resource->MustReloadDueToVaryHeader(new_request));
// Header present on both
- new_request.SetHTTPHeaderField(HTTPNames::User_Agent, "something");
+ new_request.SetHTTPHeaderField(http_names::kUserAgent, "something");
EXPECT_FALSE(resource->MustReloadDueToVaryHeader(new_request));
// One matching, one mismatching
- response.SetHTTPHeaderField(HTTPNames::Vary, "User-Agent, Referer");
+ response.SetHTTPHeaderField(http_names::kVary, "User-Agent, Referer");
resource->SetResponse(response);
EXPECT_TRUE(resource->MustReloadDueToVaryHeader(new_request));
// Two matching
- new_request.SetHTTPHeaderField(HTTPNames::Referer, "http://foo.com");
+ new_request.SetHTTPHeaderField(http_names::kReferer, "http://foo.com");
EXPECT_FALSE(resource->MustReloadDueToVaryHeader(new_request));
}
@@ -169,7 +169,8 @@ TEST(ResourceTest, RevalidationFailed) {
EXPECT_EQ(original_cache_handler, resource->CacheHandler());
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
resource->AddClient(client, nullptr);
ResourceResponse revalidating_response(url);
@@ -216,7 +217,8 @@ TEST(ResourceTest, RevalidationSucceeded) {
EXPECT_EQ(original_cache_handler, resource->CacheHandler());
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
resource->AddClient(client, nullptr);
ResourceResponse revalidating_response(url);
@@ -250,7 +252,8 @@ TEST(ResourceTest, RevalidationSucceededForResourceWithoutBody) {
// Simulate a successful revalidation.
resource->SetRevalidatingRequest(ResourceRequest(url));
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
resource->AddClient(client, nullptr);
ResourceResponse revalidating_response(url);
@@ -303,7 +306,8 @@ TEST(ResourceTest, RevalidationSucceededUpdateHeaders) {
EXPECT_EQ("custom value",
resource->GetResponse().HttpHeaderField("x-custom"));
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
resource->AddClient(client, nullptr);
// Perform a revalidation step.
@@ -371,7 +375,8 @@ TEST(ResourceTest, RedirectDuringRevalidation) {
EXPECT_EQ(url, resource->LastResourceRequest().Url());
EXPECT_EQ(original_cache_handler, resource->CacheHandler());
- Persistent<MockResourceClient> client = new MockResourceClient;
+ Persistent<MockResourceClient> client =
+ MakeGarbageCollected<MockResourceClient>();
resource->AddClient(client, nullptr);
// The revalidating request is redirected.
@@ -408,7 +413,8 @@ TEST(ResourceTest, RedirectDuringRevalidation) {
EXPECT_TRUE(client->NotifyFinishedCalled());
// Test the case where a client is added after revalidation is completed.
- Persistent<MockResourceClient> client2 = new MockResourceClient;
+ Persistent<MockResourceClient> client2 =
+ MakeGarbageCollected<MockResourceClient>();
auto* platform = static_cast<TestingPlatformSupportWithMockScheduler*>(
Platform::Current());
resource->AddClient(client2, platform->test_task_runner().get());
@@ -431,7 +437,7 @@ TEST(ResourceTest, StaleWhileRevalidateCacheControl) {
const KURL url("http://127.0.0.1:8000/foo.html");
ResourceResponse response(url);
response.SetHTTPStatusCode(200);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ response.SetHTTPHeaderField(http_names::kCacheControl,
"max-age=0, stale-while-revalidate=40");
MockResource* resource = MockResource::Create(url);
@@ -458,7 +464,7 @@ TEST(ResourceTest, StaleWhileRevalidateCacheControlWithRedirect) {
const KURL url("http://127.0.0.1:8000/foo.html");
const KURL redirect_target_url("http://127.0.0.1:8000/food.html");
ResourceResponse response(url);
- response.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=50");
+ response.SetHTTPHeaderField(http_names::kCacheControl, "max-age=50");
response.SetHTTPStatusCode(200);
// The revalidating request is redirected.
@@ -466,7 +472,7 @@ TEST(ResourceTest, StaleWhileRevalidateCacheControlWithRedirect) {
redirect_response.SetHTTPHeaderField(
"location", AtomicString(redirect_target_url.GetString()));
redirect_response.SetHTTPStatusCode(302);
- redirect_response.SetHTTPHeaderField(HTTPNames::Cache_Control,
+ redirect_response.SetHTTPHeaderField(http_names::kCacheControl,
"max-age=0, stale-while-revalidate=40");
redirect_response.SetAsyncRevalidationRequested(true);
ResourceRequest redirected_revalidating_request(redirect_target_url);
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h b/chromium/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h
index 0f20f74db9d..4cb4632a89c 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h
@@ -5,13 +5,13 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_SCRIPT_FETCH_OPTIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_SCRIPT_FETCH_OPTIONS_H_
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/platform/cross_origin_attribute_value.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -35,14 +35,14 @@ class PLATFORM_EXPORT ScriptFetchOptions final {
ScriptFetchOptions()
: parser_state_(ParserDisposition::kNotParserInserted),
credentials_mode_(network::mojom::FetchCredentialsMode::kOmit),
- referrer_policy_(kReferrerPolicyDefault) {}
+ referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {}
ScriptFetchOptions(const String& nonce,
const IntegrityMetadataSet& integrity_metadata,
const String& integrity_attribute,
ParserDisposition parser_state,
network::mojom::FetchCredentialsMode credentials_mode,
- ReferrerPolicy referrer_policy)
+ network::mojom::ReferrerPolicy referrer_policy)
: nonce_(nonce),
integrity_metadata_(integrity_metadata),
integrity_attribute_(integrity_attribute),
@@ -62,7 +62,9 @@ class PLATFORM_EXPORT ScriptFetchOptions final {
network::mojom::FetchCredentialsMode CredentialsMode() const {
return credentials_mode_;
}
- ReferrerPolicy GetReferrerPolicy() const { return referrer_policy_; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_policy_;
+ }
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
// Steps 1 and 3.
@@ -87,7 +89,7 @@ class PLATFORM_EXPORT ScriptFetchOptions final {
const network::mojom::FetchCredentialsMode credentials_mode_;
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-script-fetch-options-referrer-policy
- const ReferrerPolicy referrer_policy_;
+ const network::mojom::ReferrerPolicy referrer_policy_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc
index 4e4e33a3147..d1d3c7bbb86 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler.cc
@@ -66,7 +66,8 @@ class SourceKeyedCachedMetadataHandler::SingleKeyHandler final
class SourceKeyedCachedMetadataHandler::KeyHash {
public:
static unsigned GetHash(const Key& key) {
- return StringHasher::ComputeHash(key.data(), key.size());
+ return StringHasher::ComputeHash(key.data(),
+ static_cast<uint32_t>(key.size()));
}
static bool Equal(const Key& a, const Key& b) { return a == b; }
@@ -87,7 +88,7 @@ SingleCachedMetadataHandler* SourceKeyedCachedMetadataHandler::HandlerForSource(
DCHECK_EQ(digest_value.size(), kKeySize);
memcpy(key.data(), digest_value.data(), kKeySize);
- return new SingleKeyHandler(this, key);
+ return MakeGarbageCollected<SingleKeyHandler>(this, key);
}
void SourceKeyedCachedMetadataHandler::ClearCachedMetadata(
diff --git a/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc b/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc
index 2746de6b4d2..61a489c16f3 100644
--- a/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/fetch/source_keyed_cached_metadata_handler_test.cc
@@ -9,6 +9,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/crypto.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -69,7 +70,7 @@ struct CacheMetadataEntry {
CacheMetadataEntry(const WebURL& url,
base::Time response_time,
const char* data,
- size_t data_size)
+ wtf_size_t data_size)
: url(url), response_time(response_time) {
this->data.Append(data, data_size);
}
@@ -93,7 +94,8 @@ class SourceKeyedCachedMetadataHandlerMockPlatform final
base::Time response_time,
const char* data,
size_t data_size) override {
- cache_entries_.emplace_back(url, response_time, data, data_size);
+ cache_entries_.emplace_back(url, response_time, data,
+ SafeCast<wtf_size_t>(data_size));
}
bool HasCacheMetadataFor(const WebURL& url) {
@@ -205,7 +207,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest,
KURL url("http://SourceKeyedCachedMetadataHandlerTest.com");
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(), std::make_unique<MockCachedMetadataSender>(url));
WTF::String source1("source1");
@@ -229,7 +231,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest,
KURL url("http://SourceKeyedCachedMetadataHandlerTest.com");
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(), std::make_unique<MockCachedMetadataSender>(url));
WTF::String source1("source1");
@@ -256,7 +258,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest, HandlerForSource_BothHandlersSet) {
KURL url("http://SourceKeyedCachedMetadataHandlerTest.com");
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(), std::make_unique<MockCachedMetadataSender>(url));
WTF::String source1("source1");
@@ -286,7 +288,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest, Serialize_EmptyClearDoesSend) {
KURL url("http://SourceKeyedCachedMetadataHandlerTest.com");
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(), std::make_unique<MockCachedMetadataSender>(url));
// Clear and send to the platform
@@ -305,7 +307,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest, Serialize_EachSetDoesSend) {
KURL url("http://SourceKeyedCachedMetadataHandlerTest.com");
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(), std::make_unique<MockCachedMetadataSender>(url));
WTF::String source1("source1");
@@ -335,7 +337,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest, Serialize_SetWithNoSendDoesNotSend) {
KURL url("http://SourceKeyedCachedMetadataHandlerTest.com");
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(), std::make_unique<MockCachedMetadataSender>(url));
WTF::String source1("source1");
@@ -370,7 +372,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest,
WTF::String source2("source2");
{
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(),
std::make_unique<MockCachedMetadataSender>(url));
@@ -387,7 +389,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest,
CacheMetadataEntry& last_cache_metadata = cache_metadatas[0];
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(),
std::make_unique<MockCachedMetadataSender>(url));
handler->SetSerializedCachedMetadata(last_cache_metadata.data.data(),
@@ -418,7 +420,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest,
std::array<char, 4> data2 = {3, 4, 5, 6};
{
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(),
std::make_unique<MockCachedMetadataSender>(url));
@@ -440,7 +442,7 @@ TEST(SourceKeyedCachedMetadataHandlerTest,
CacheMetadataEntry& last_cache_metadata = cache_metadatas[1];
SourceKeyedCachedMetadataHandler* handler =
- new SourceKeyedCachedMetadataHandler(
+ MakeGarbageCollected<SourceKeyedCachedMetadataHandler>(
WTF::TextEncoding(),
std::make_unique<MockCachedMetadataSender>(url));
handler->SetSerializedCachedMetadata(last_cache_metadata.data.data(),
diff --git a/chromium/third_party/blink/renderer/platform/loader/link_header.cc b/chromium/third_party/blink/renderer/platform/loader/link_header.cc
index d314eebcbca..fdd6bf68133 100644
--- a/chromium/third_party/blink/renderer/platform/loader/link_header.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/link_header.cc
@@ -40,10 +40,10 @@ static LinkHeader::LinkParameterName ParameterNameFromString(
return LinkHeader::kLinkParameterNonce;
if (base::EqualsCaseInsensitiveASCII(name, "integrity"))
return LinkHeader::kLinkParameterIntegrity;
- if (base::EqualsCaseInsensitiveASCII(name, "srcset"))
- return LinkHeader::kLinkParameterSrcset;
- if (base::EqualsCaseInsensitiveASCII(name, "imgsizes"))
- return LinkHeader::kLinkParameterImgsizes;
+ if (base::EqualsCaseInsensitiveASCII(name, "imagesrcset"))
+ return LinkHeader::kLinkParameterImageSrcset;
+ if (base::EqualsCaseInsensitiveASCII(name, "imagesizes"))
+ return LinkHeader::kLinkParameterImageSizes;
return LinkHeader::kLinkParameterUnknown;
}
@@ -64,10 +64,10 @@ void LinkHeader::SetValue(LinkParameterName name, const String& value) {
nonce_ = value;
else if (name == kLinkParameterIntegrity)
integrity_ = value;
- else if (name == kLinkParameterSrcset)
- srcset_ = value;
- else if (name == kLinkParameterImgsizes)
- imgsizes_ = value;
+ else if (name == kLinkParameterImageSrcset)
+ image_srcset_ = value;
+ else if (name == kLinkParameterImageSizes)
+ image_sizes_ = value;
}
template <typename Iterator>
diff --git a/chromium/third_party/blink/renderer/platform/loader/link_header.h b/chromium/third_party/blink/renderer/platform/loader/link_header.h
index ff9eb0d6e6b..1505f38c1be 100644
--- a/chromium/third_party/blink/renderer/platform/loader/link_header.h
+++ b/chromium/third_party/blink/renderer/platform/loader/link_header.h
@@ -23,8 +23,8 @@ class LinkHeader {
const String& CrossOrigin() const { return cross_origin_; }
const String& Nonce() const { return nonce_; }
const String& Integrity() const { return integrity_; }
- const String& Srcset() const { return srcset_; }
- const String& Imgsizes() const { return imgsizes_; }
+ const String& ImageSrcset() const { return image_srcset_; }
+ const String& ImageSizes() const { return image_sizes_; }
bool Valid() const { return is_valid_; }
enum LinkParameterName {
@@ -41,8 +41,8 @@ class LinkHeader {
kLinkParameterAs,
kLinkParameterNonce,
kLinkParameterIntegrity,
- kLinkParameterSrcset,
- kLinkParameterImgsizes,
+ kLinkParameterImageSrcset,
+ kLinkParameterImageSizes,
};
private:
@@ -60,8 +60,8 @@ class LinkHeader {
String cross_origin_;
String nonce_;
String integrity_;
- String srcset_;
- String imgsizes_;
+ String image_srcset_;
+ String image_sizes_;
bool is_valid_;
};
@@ -75,8 +75,8 @@ class PLATFORM_EXPORT LinkHeaderSet {
return header_set_.begin();
}
Vector<LinkHeader>::const_iterator end() const { return header_set_.end(); }
- LinkHeader& operator[](size_t i) { return header_set_[i]; }
- size_t size() { return header_set_.size(); }
+ LinkHeader& operator[](wtf_size_t i) { return header_set_[i]; }
+ wtf_size_t size() { return header_set_.size(); }
private:
Vector<LinkHeader> header_set_;
diff --git a/chromium/third_party/blink/renderer/platform/loader/subresource_integrity.cc b/chromium/third_party/blink/renderer/platform/loader/subresource_integrity.cc
index dbaaeb528c5..d92b21df2ca 100644
--- a/chromium/third_party/blink/renderer/platform/loader/subresource_integrity.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/subresource_integrity.cc
@@ -39,7 +39,7 @@ static bool DigestsEqual(const DigestValue& digest1,
if (digest1.size() != digest2.size())
return false;
- for (size_t i = 0; i < digest1.size(); i++) {
+ for (wtf_size_t i = 0; i < digest1.size(); i++) {
if (digest1[i] != digest2[i])
return false;
}
@@ -80,7 +80,7 @@ bool SubresourceIntegrity::CheckSubresourceIntegrity(
// FetchResponseType::kError never arrives because it is a loading error.
DCHECK_NE(resource.GetResponse().GetType(),
network::mojom::FetchResponseType::kError);
- if (!resource.GetResponse().IsCORSSameOrigin()) {
+ if (!resource.GetResponse().IsCorsSameOrigin()) {
report_info.AddConsoleErrorMessage(
"Subresource Integrity: The resource '" + resource_url.ElidedString() +
"' has an integrity attribute, but the resource "
@@ -384,7 +384,8 @@ bool SubresourceIntegrity::ParseDigest(const UChar*& position,
}
// We accept base64url encoding, but normalize to "normal" base64 internally:
- digest = NormalizeToBase64(String(begin, position - begin));
+ digest = NormalizeToBase64(
+ String(begin, static_cast<wtf_size_t>(position - begin)));
return true;
}
@@ -490,7 +491,7 @@ SubresourceIntegrity::ParseIntegrityAttribute(
if (begin != position && report_info) {
report_info->AddConsoleErrorMessage(
"Ignoring unrecogized 'integrity' attribute option '" +
- String(begin, position - begin) + "'.");
+ String(begin, static_cast<wtf_size_t>(position - begin)) + "'.");
}
}
diff --git a/chromium/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc b/chromium/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc
index 5ef60f61355..ec90823234b 100644
--- a/chromium/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/subresource_integrity_test.cc
@@ -538,20 +538,20 @@ TEST_F(SubresourceIntegrityTest, OriginIntegrity) {
const TestCase cases[] = {
// FetchResponseType::kError never arrives because it is a loading error.
- {url, FetchRequestMode::kNoCORS, FetchResponseType::kBasic, kOk},
- {url, FetchRequestMode::kNoCORS, FetchResponseType::kCORS, kOk},
- {url, FetchRequestMode::kNoCORS, FetchResponseType::kDefault, kOk},
- {url, FetchRequestMode::kNoCORS, FetchResponseType::kOpaque, kFail},
- {url, FetchRequestMode::kNoCORS, FetchResponseType::kOpaqueRedirect,
+ {url, FetchRequestMode::kNoCors, FetchResponseType::kBasic, kOk},
+ {url, FetchRequestMode::kNoCors, FetchResponseType::kCors, kOk},
+ {url, FetchRequestMode::kNoCors, FetchResponseType::kDefault, kOk},
+ {url, FetchRequestMode::kNoCors, FetchResponseType::kOpaque, kFail},
+ {url, FetchRequestMode::kNoCors, FetchResponseType::kOpaqueRedirect,
kFail},
// FetchResponseType::kError never arrives because it is a loading error.
// FetchResponseType::kOpaque and FetchResponseType::kOpaqueResponse
// never arrives: even when service worker is involved, it's handled as
// an error.
- {url, FetchRequestMode::kCORS, FetchResponseType::kBasic, kOk},
- {url, FetchRequestMode::kCORS, FetchResponseType::kCORS, kOk},
- {url, FetchRequestMode::kCORS, FetchResponseType::kDefault, kOk},
+ {url, FetchRequestMode::kCors, FetchResponseType::kBasic, kOk},
+ {url, FetchRequestMode::kCors, FetchResponseType::kCors, kOk},
+ {url, FetchRequestMode::kCors, FetchResponseType::kDefault, kOk},
};
MockWebCryptoDigestorFactory factory_sha256(
diff --git a/chromium/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h b/chromium/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h
index 53b598566fb..7859d37a2c5 100644
--- a/chromium/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h
+++ b/chromium/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h
@@ -10,6 +10,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url_loader_factory.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
@@ -36,10 +37,24 @@ class MockFetchContext : public FetchContext {
LoadPolicy load_policy,
scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner = nullptr,
std::unique_ptr<WebURLLoaderFactory> url_loader_factory = nullptr) {
- return new MockFetchContext(load_policy, std::move(loading_task_runner),
- std::move(url_loader_factory));
+ return MakeGarbageCollected<MockFetchContext>(
+ load_policy, std::move(loading_task_runner),
+ std::move(url_loader_factory));
}
+ MockFetchContext(
+ LoadPolicy load_policy,
+ scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
+ std::unique_ptr<WebURLLoaderFactory> url_loader_factory)
+ : FetchContext(loading_task_runner
+ ? std::move(loading_task_runner)
+ : base::MakeRefCounted<scheduler::FakeTaskRunner>()),
+ load_policy_(load_policy),
+ security_origin_(SecurityOrigin::CreateUniqueOpaque()),
+ frame_scheduler_(new MockFrameScheduler(GetLoadingTaskRunner())),
+ url_loader_factory_(std::move(url_loader_factory)),
+ complete_(false),
+ transfer_size_(-1) {}
~MockFetchContext() override = default;
void SetLoadComplete(bool complete) { complete_ = complete; }
@@ -53,6 +68,13 @@ class MockFetchContext : public FetchContext {
security_origin_ = security_origin;
}
+ const FetchClientSettingsObject* GetFetchClientSettingsObject()
+ const override {
+ return MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ KURL(), security_origin_, network::mojom::ReferrerPolicy::kDefault,
+ String(), HttpsState::kNone);
+ }
+
// The last ResourceRequest passed to DispatchWillSendRequest.
base::Optional<ResourceRequest> RequestFromWillSendRequest() const {
return will_send_request_;
@@ -138,20 +160,6 @@ class MockFetchContext : public FetchContext {
scoped_refptr<base::SingleThreadTaskRunner> runner_;
};
- MockFetchContext(
- LoadPolicy load_policy,
- scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner,
- std::unique_ptr<WebURLLoaderFactory> url_loader_factory)
- : FetchContext(loading_task_runner
- ? std::move(loading_task_runner)
- : base::MakeRefCounted<scheduler::FakeTaskRunner>()),
- load_policy_(load_policy),
- security_origin_(SecurityOrigin::CreateUniqueOpaque()),
- frame_scheduler_(new MockFrameScheduler(GetLoadingTaskRunner())),
- url_loader_factory_(std::move(url_loader_factory)),
- complete_(false),
- transfer_size_(-1) {}
-
enum LoadPolicy load_policy_;
scoped_refptr<const SecurityOrigin> security_origin_;
std::unique_ptr<FrameScheduler> frame_scheduler_;
diff --git a/chromium/third_party/blink/renderer/platform/loader/testing/mock_resource.cc b/chromium/third_party/blink/renderer/platform/loader/testing/mock_resource.cc
index 98b66d703ef..57de25a182e 100644
--- a/chromium/third_party/blink/renderer/platform/loader/testing/mock_resource.cc
+++ b/chromium/third_party/blink/renderer/platform/loader/testing/mock_resource.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
@@ -18,7 +19,7 @@ class MockResourceFactory final : public NonTextResourceFactory {
Resource* Create(const ResourceRequest& request,
const ResourceLoaderOptions& options) const override {
- return new MockResource(request, options);
+ return MakeGarbageCollected<MockResource>(request, options);
}
};
@@ -36,7 +37,7 @@ MockResource* MockResource::Fetch(FetchParameters& params,
// static
MockResource* MockResource::Create(const ResourceRequest& request) {
ResourceLoaderOptions options;
- return new MockResource(request, options);
+ return MakeGarbageCollected<MockResource>(request, options);
}
MockResource* MockResource::Create(const KURL& url) {
@@ -50,7 +51,7 @@ MockResource::MockResource(const ResourceRequest& request,
CachedMetadataHandler* MockResource::CreateCachedMetadataHandler(
std::unique_ptr<CachedMetadataSender> send_callback) {
- return new MockCacheHandler(std::move(send_callback));
+ return MakeGarbageCollected<MockCacheHandler>(std::move(send_callback));
}
void MockResource::SetSerializedCachedMetadata(const char* data, size_t size) {
@@ -81,7 +82,7 @@ MockCacheHandler::MockCacheHandler(
void MockCacheHandler::Set(const char* data, size_t size) {
data_.emplace();
- data_->Append(data, size);
+ data_->Append(data, SafeCast<wtf_size_t>(size));
}
void MockCacheHandler::ClearCachedMetadata(
diff --git a/chromium/third_party/blink/renderer/platform/mac/theme_mac.mm b/chromium/third_party/blink/renderer/platform/mac/theme_mac.mm
index 50f2f9ebf2b..da06b3aa2cc 100644
--- a/chromium/third_party/blink/renderer/platform/mac/theme_mac.mm
+++ b/chromium/third_party/blink/renderer/platform/mac/theme_mac.mm
@@ -395,7 +395,7 @@ FontDescription ThemeMac::ControlFont(ControlPart part,
NSFont* ns_font = [NSFont
systemFontOfSize:[NSFont systemFontSizeForControlSize:
ControlSizeForFont(font_description)]];
- result.FirstFamily().SetFamily(FontFamilyNames::system_ui);
+ result.FirstFamily().SetFamily(font_family_names::kSystemUi);
result.SetComputedSize([ns_font pointSize] * zoom_factor);
result.SetSpecifiedSize([ns_font pointSize] * zoom_factor);
return result;
diff --git a/chromium/third_party/blink/renderer/platform/media/BUILD.gn b/chromium/third_party/blink/renderer/platform/media/BUILD.gn
deleted file mode 100644
index 59532133dbc..00000000000
--- a/chromium/third_party/blink/renderer/platform/media/BUILD.gn
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright 2017 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/blink/renderer/platform/platform.gni")
-
-blink_platform_sources("media") {
- sources = [
- "resource_bundle_helper.cc",
- "resource_bundle_helper.h",
- ]
-
- deps = [
- "//third_party/zlib/google:compression_utils",
- "//ui/base:base",
- ]
-}
diff --git a/chromium/third_party/blink/renderer/platform/media/DEPS b/chromium/third_party/blink/renderer/platform/media/DEPS
deleted file mode 100644
index d34ec436d8f..00000000000
--- a/chromium/third_party/blink/renderer/platform/media/DEPS
+++ /dev/null
@@ -1,13 +0,0 @@
-include_rules = [
- # Don't depend on platform/.
- "-third_party/blink/renderer/platform",
-
- # Module.
- "+third_party/blink/renderer/platform/media",
-
- # Dependencies.
- "+third_party/blink/renderer/platform/platform_export.h",
- "+third_party/blink/renderer/platform/wtf",
- "+third_party/zlib/google/compression_utils.h",
- "+ui/base/resource",
-]
diff --git a/chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.cc b/chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.cc
deleted file mode 100644
index 7737f5bf6f6..00000000000
--- a/chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.cc
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/platform/media/resource_bundle_helper.h"
-
-#include "third_party/zlib/google/compression_utils.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/resource/resource_handle.h"
-
-namespace {
-
-std::string GetResource(int resource_id) {
- ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
- return bundle
- .GetRawDataResourceForScale(resource_id, bundle.GetMaxScaleFactor())
- .as_string();
-}
-
-} // namespace.
-
-namespace blink {
-
-String ResourceBundleHelper::GetResourceAsString(int resource_id) {
- return String::FromUTF8(GetResource(resource_id).c_str());
-};
-
-String ResourceBundleHelper::UncompressResourceAsString(int resource_id) {
- std::string uncompressed;
- CHECK(compression::GzipUncompress(GetResource(resource_id), &uncompressed));
- return String::FromUTF8(uncompressed.c_str());
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.h b/chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.h
deleted file mode 100644
index de115f593ed..00000000000
--- a/chromium/third_party/blink/renderer/platform/media/resource_bundle_helper.h
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_RESOURCE_BUNDLE_HELPER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_RESOURCE_BUNDLE_HELPER_H_
-
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-
-// Provides access to ui::ResourceBundle in Blink. This
-// allows Blink to directly load resources from the bundle.
-class ResourceBundleHelper {
- STATIC_ONLY(ResourceBundleHelper);
-
- public:
- // Returns the contents of a resource as a string specified by the
- // resource id from Grit.
- static PLATFORM_EXPORT String GetResourceAsString(int resource_id);
-
- // Uncompresses a gzipped resource and returns it as a string. The resource
- // is specified by the resource id from Grit.
- static PLATFORM_EXPORT String UncompressResourceAsString(int resource_id);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MEDIA_RESOURCE_BUNDLE_HELPER_H_
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_center.cc b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_center.cc
index 7e6ff05cd7a..354c2af630d 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_center.cc
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_center.cc
@@ -72,10 +72,10 @@ void MediaStreamCenter::DidCreateMediaStreamAndTracks(
if (!private_)
return;
- for (size_t i = 0; i < stream->NumberOfAudioComponents(); ++i)
+ for (uint32_t i = 0; i < stream->NumberOfAudioComponents(); ++i)
DidCreateMediaStreamTrack(stream->AudioComponent(i));
- for (size_t i = 0; i < stream->NumberOfVideoComponents(); ++i)
+ for (uint32_t i = 0; i < stream->NumberOfVideoComponents(); ++i)
DidCreateMediaStreamTrack(stream->VideoComponent(i));
}
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.cc b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.cc
index 0eeed8b76b6..b05352d5815 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.cc
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.cc
@@ -52,12 +52,13 @@ int MediaStreamComponent::GenerateUniqueId() {
}
MediaStreamComponent* MediaStreamComponent::Create(MediaStreamSource* source) {
- return new MediaStreamComponent(CreateCanonicalUUIDString(), source);
+ return MakeGarbageCollected<MediaStreamComponent>(CreateCanonicalUUIDString(),
+ source);
}
MediaStreamComponent* MediaStreamComponent::Create(const String& id,
MediaStreamSource* source) {
- return new MediaStreamComponent(id, source);
+ return MakeGarbageCollected<MediaStreamComponent>(id, source);
}
MediaStreamComponent::MediaStreamComponent(const String& id,
@@ -68,7 +69,8 @@ MediaStreamComponent::MediaStreamComponent(const String& id,
MediaStreamComponent* MediaStreamComponent::Clone() const {
MediaStreamComponent* cloned_component =
- new MediaStreamComponent(CreateCanonicalUUIDString(), Source());
+ MakeGarbageCollected<MediaStreamComponent>(CreateCanonicalUUIDString(),
+ Source());
cloned_component->SetEnabled(enabled_);
cloned_component->SetMuted(muted_);
cloned_component->SetContentHint(content_hint_);
@@ -117,7 +119,7 @@ void MediaStreamComponent::SetContentHint(
void MediaStreamComponent::AudioSourceProviderImpl::ProvideInput(
AudioBus* bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(bus);
if (!bus)
return;
@@ -129,9 +131,9 @@ void MediaStreamComponent::AudioSourceProviderImpl::ProvideInput(
}
// Wrap the AudioBus channel data using WebVector.
- size_t n = bus->NumberOfChannels();
+ uint32_t n = bus->NumberOfChannels();
WebVector<float*> web_audio_data(n);
- for (size_t i = 0; i < n; ++i)
+ for (uint32_t i = 0; i < n; ++i)
web_audio_data[i] = bus->Channel(i)->MutableData();
web_audio_source_provider_->ProvideInput(web_audio_data, frames_to_process);
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.h b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.h
index ed0b1cd2db2..8839431c19b 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.h
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_component.h
@@ -70,6 +70,8 @@ class PLATFORM_EXPORT MediaStreamComponent final
static MediaStreamComponent* Create(MediaStreamSource*);
static MediaStreamComponent* Create(const String& id, MediaStreamSource*);
+ MediaStreamComponent(const String& id, MediaStreamSource*);
+
MediaStreamComponent* Clone() const;
// |m_trackData| may hold pointers to GC objects indirectly, and it may touch
@@ -110,8 +112,6 @@ class PLATFORM_EXPORT MediaStreamComponent final
void Trace(blink::Visitor*);
private:
- MediaStreamComponent(const String& id, MediaStreamSource*);
-
// AudioSourceProviderImpl wraps a WebAudioSourceProvider::provideInput()
// calls into chromium to get a rendered audio stream.
@@ -127,7 +127,7 @@ class PLATFORM_EXPORT MediaStreamComponent final
void Wrap(WebAudioSourceProvider*);
// blink::AudioSourceProvider
- void ProvideInput(AudioBus*, size_t frames_to_process) override;
+ void ProvideInput(AudioBus*, uint32_t frames_to_process) override;
private:
WebAudioSourceProvider* web_audio_source_provider_;
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.cc b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.cc
index cae016b4f06..3c702126a08 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.cc
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.cc
@@ -50,22 +50,23 @@ int MediaStreamDescriptor::GenerateUniqueId() {
MediaStreamDescriptor* MediaStreamDescriptor::Create(
const MediaStreamSourceVector& audio_sources,
const MediaStreamSourceVector& video_sources) {
- return new MediaStreamDescriptor(CreateCanonicalUUIDString(), audio_sources,
- video_sources);
+ return MakeGarbageCollected<MediaStreamDescriptor>(
+ CreateCanonicalUUIDString(), audio_sources, video_sources);
}
MediaStreamDescriptor* MediaStreamDescriptor::Create(
const MediaStreamComponentVector& audio_components,
const MediaStreamComponentVector& video_components) {
- return new MediaStreamDescriptor(CreateCanonicalUUIDString(),
- audio_components, video_components);
+ return MakeGarbageCollected<MediaStreamDescriptor>(
+ CreateCanonicalUUIDString(), audio_components, video_components);
}
MediaStreamDescriptor* MediaStreamDescriptor::Create(
const String& id,
const MediaStreamComponentVector& audio_components,
const MediaStreamComponentVector& video_components) {
- return new MediaStreamDescriptor(id, audio_components, video_components);
+ return MakeGarbageCollected<MediaStreamDescriptor>(id, audio_components,
+ video_components);
}
void MediaStreamDescriptor::AddComponent(MediaStreamComponent* component) {
@@ -87,7 +88,7 @@ void MediaStreamDescriptor::AddComponent(MediaStreamComponent* component) {
}
void MediaStreamDescriptor::RemoveComponent(MediaStreamComponent* component) {
- size_t pos = kNotFound;
+ wtf_size_t pos = kNotFound;
switch (component->Source()->GetType()) {
case MediaStreamSource::kTypeAudio:
pos = audio_components_.Find(component);
@@ -138,7 +139,7 @@ void MediaStreamDescriptor::AddObserver(WebMediaStreamObserver* observer) {
}
void MediaStreamDescriptor::RemoveObserver(WebMediaStreamObserver* observer) {
- size_t index = observers_.Find(observer);
+ wtf_size_t index = observers_.Find(observer);
DCHECK(index != kNotFound);
observers_.EraseAt(index);
}
@@ -149,11 +150,11 @@ MediaStreamDescriptor::MediaStreamDescriptor(
const MediaStreamSourceVector& video_sources)
: client_(nullptr), id_(id), unique_id_(GenerateUniqueId()), active_(true) {
DCHECK(id_.length());
- for (size_t i = 0; i < audio_sources.size(); i++)
- audio_components_.push_back(MediaStreamComponent::Create(audio_sources[i]));
+ for (MediaStreamSource* source : audio_sources)
+ audio_components_.push_back(MediaStreamComponent::Create(source));
- for (size_t i = 0; i < video_sources.size(); i++)
- video_components_.push_back(MediaStreamComponent::Create(video_sources[i]));
+ for (MediaStreamSource* source : video_sources)
+ video_components_.push_back(MediaStreamComponent::Create(source));
}
MediaStreamDescriptor::MediaStreamDescriptor(
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h
index aed544e029b..d7d0c01482c 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h
@@ -74,6 +74,13 @@ class PLATFORM_EXPORT MediaStreamDescriptor final
const MediaStreamComponentVector& audio_components,
const MediaStreamComponentVector& video_components);
+ MediaStreamDescriptor(const String& id,
+ const MediaStreamSourceVector& audio_sources,
+ const MediaStreamSourceVector& video_sources);
+ MediaStreamDescriptor(const String& id,
+ const MediaStreamComponentVector& audio_components,
+ const MediaStreamComponentVector& video_components);
+
MediaStreamDescriptorClient* Client() const { return client_; }
void SetClient(MediaStreamDescriptorClient* client) { client_ = client; }
@@ -114,13 +121,6 @@ class PLATFORM_EXPORT MediaStreamDescriptor final
void Trace(blink::Visitor*);
private:
- MediaStreamDescriptor(const String& id,
- const MediaStreamSourceVector& audio_sources,
- const MediaStreamSourceVector& video_sources);
- MediaStreamDescriptor(const String& id,
- const MediaStreamComponentVector& audio_components,
- const MediaStreamComponentVector& video_components);
-
Member<MediaStreamDescriptorClient> client_;
String id_;
int unique_id_;
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.cc b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.cc
index 9f6364b1e58..ca58bd388e4 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.cc
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.cc
@@ -41,8 +41,8 @@ MediaStreamSource* MediaStreamSource::Create(const String& id,
bool remote,
ReadyState ready_state,
bool requires_consumer) {
- return new MediaStreamSource(id, type, name, remote, ready_state,
- requires_consumer);
+ return MakeGarbageCollected<MediaStreamSource>(
+ id, type, name, remote, ready_state, requires_consumer);
}
MediaStreamSource::MediaStreamSource(const String& id,
@@ -87,7 +87,7 @@ void MediaStreamSource::SetReadyState(ReadyState ready_state) {
//
// TODO(sof): consider adding run-time checks that disallows this kind
// of dead object revivification by default.
- for (size_t i = 0; i < observers.size(); ++i)
+ for (wtf_size_t i = 0; i < observers.size(); ++i)
observers[i] = nullptr;
}
}
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.h b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.h
index 2c138540fd4..6f8acec957d 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.h
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_source.h
@@ -81,6 +81,13 @@ class PLATFORM_EXPORT MediaStreamSource final
ReadyState = kReadyStateLive,
bool requires_consumer = false);
+ MediaStreamSource(const String& id,
+ StreamType,
+ const String& name,
+ bool remote,
+ ReadyState,
+ bool requires_consumer);
+
const String& Id() const { return id_; }
StreamType GetType() const { return type_; }
const String& GetName() const { return name_; }
@@ -129,13 +136,6 @@ class PLATFORM_EXPORT MediaStreamSource final
void Trace(blink::Visitor*);
private:
- MediaStreamSource(const String& id,
- StreamType,
- const String& name,
- bool remote,
- ReadyState,
- bool requires_consumer);
-
String id_;
StreamType type_;
String name_;
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.cc b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.cc
index b21a41baf7d..65ace13a83d 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.cc
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.cc
@@ -42,7 +42,7 @@ MediaStreamWebAudioSource::MediaStreamWebAudioSource(
MediaStreamWebAudioSource::~MediaStreamWebAudioSource() = default;
void MediaStreamWebAudioSource::ProvideInput(AudioBus* bus,
- size_t frames_to_process) {
+ uint32_t frames_to_process) {
DCHECK(bus);
if (!bus)
return;
@@ -53,9 +53,9 @@ void MediaStreamWebAudioSource::ProvideInput(AudioBus* bus,
}
// Wrap the AudioBus channel data using WebVector.
- size_t n = bus->NumberOfChannels();
+ uint32_t n = bus->NumberOfChannels();
WebVector<float*> web_audio_data(n);
- for (size_t i = 0; i < n; ++i)
+ for (uint32_t i = 0; i < n; ++i)
web_audio_data[i] = bus->Channel(i)->MutableData();
web_audio_source_provider_->ProvideInput(web_audio_data, frames_to_process);
diff --git a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.h b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.h
index ba2ba04b275..ab466d0ac2c 100644
--- a/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.h
+++ b/chromium/third_party/blink/renderer/platform/mediastream/media_stream_web_audio_source.h
@@ -58,7 +58,7 @@ class MediaStreamWebAudioSource : public AudioSourceProvider {
explicit MediaStreamWebAudioSource(std::unique_ptr<WebAudioSourceProvider>);
// blink::AudioSourceProvider implementation.
- void ProvideInput(AudioBus*, size_t frames_to_process) override;
+ void ProvideInput(AudioBus*, uint32_t frames_to_process) override;
std::unique_ptr<WebAudioSourceProvider> web_audio_source_provider_;
};
diff --git a/chromium/third_party/blink/renderer/platform/memory_coordinator.cc b/chromium/third_party/blink/renderer/platform/memory_coordinator.cc
index cd58de7441b..a65474abb18 100644
--- a/chromium/third_party/blink/renderer/platform/memory_coordinator.cc
+++ b/chromium/third_party/blink/renderer/platform/memory_coordinator.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/platform/memory_coordinator.h"
-#include "base/sys_info.h"
+#include "base/system/sys_info.h"
#include "build/build_config.h"
#include "third_party/blink/public/common/device_memory/approximated_device_memory.h"
#include "third_party/blink/public/web/blink.h"
@@ -12,8 +12,8 @@
#include "third_party/blink/renderer/platform/fonts/font_global_context.h"
#include "third_party/blink/renderer/platform/graphics/image_decoding_store.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"
#if defined(OS_ANDROID)
diff --git a/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc b/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc
index a0e67e305dd..d3082bb08b5 100644
--- a/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc
+++ b/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.cc
@@ -30,6 +30,8 @@
#include "third_party/blink/renderer/platform/mhtml/mhtml_archive.h"
+#include <stddef.h>
+#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/date_components.h"
#include "third_party/blink/renderer/platform/mhtml/archive_resource.h"
@@ -37,13 +39,14 @@
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
#include "third_party/blink/renderer/platform/serialized_resource.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
-#include "third_party/blink/renderer/platform/text/quoted_printable.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
+#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -60,66 +63,115 @@ const char kQuotedPrintable[] = "quoted-printable";
const char kBase64[] = "base64";
const char kBinary[] = "binary";
-} // namespace
-
-// Controls quoted-printable encoding characters in body, per RFC 2045.
-class QuotedPrintableEncodeBodyDelegate : public QuotedPrintableEncodeDelegate {
- public:
- QuotedPrintableEncodeBodyDelegate() = default;
- ~QuotedPrintableEncodeBodyDelegate() override = default;
-
- size_t GetMaxLineLengthForEncodedContent() const override {
- return kMaximumLineLength;
+// Returns the length of a line-ending if one is present starting at
+// |input[index]| or zero if no line-ending is present at the given |index|.
+size_t LengthOfLineEndingAtIndex(const char* input,
+ size_t input_length,
+ size_t index) {
+ SECURITY_DCHECK(index < input_length);
+ if (input[index] == '\n')
+ return 1; // Single LF.
+
+ if (input[index] == '\r') {
+ if ((index + 1) == input_length || input[index + 1] != '\n')
+ return 1; // Single CR (Classic Mac OS).
+ return 2; // CR-LF.
}
- bool ShouldEncodeWhiteSpaceCharacters(bool end_of_line) const override {
- // They should be encoded only if they appear at the end of a body line.
- return end_of_line;
- }
+ return 0;
+}
- void DidStartLine(Vector<char>& out) override {
- // Nothing to add.
- }
+// Performs quoted-printable encoding characters, per RFC 2047.
+void QuotedPrintableEncode(const char* input,
+ wtf_size_t input_length,
+ bool is_header,
+ Vector<char>& out) {
+ out.clear();
+ out.ReserveCapacity(input_length);
+ if (is_header)
+ out.Append(kRFC2047EncodingPrefix, kRFC2047EncodingPrefixLength);
+ size_t current_line_length = 0;
+ for (size_t i = 0; i < input_length; ++i) {
+ bool is_last_character = (i == input_length - 1);
+ char current_character = input[i];
+ bool requires_encoding = false;
+ // All non-printable ASCII characters and = require encoding.
+ if ((current_character < ' ' || current_character > '~' ||
+ current_character == '=') &&
+ current_character != '\t')
+ requires_encoding = true;
+
+ // Decide if space and tab characters need to be encoded.
+ if (!requires_encoding &&
+ (current_character == '\t' || current_character == ' ')) {
+ if (is_header) {
+ // White space characters should always be encoded if they appear
+ // anywhere in the header.
+ requires_encoding = true;
+ } else {
+ bool end_of_line = is_last_character || LengthOfLineEndingAtIndex(
+ input, input_length, i + 1);
+ requires_encoding = end_of_line;
+ }
+ }
- void DidFinishLine(bool last_line, Vector<char>& out) override {
- if (!last_line) {
- out.push_back('=');
- out.Append("\r\n", 2);
+ // End of line should be converted to CR-LF sequences.
+ if (!is_last_character) {
+ size_t length_of_line_ending =
+ LengthOfLineEndingAtIndex(input, input_length, i);
+ if (length_of_line_ending) {
+ out.Append("\r\n", 2);
+ current_line_length = 0;
+ i += (length_of_line_ending -
+ 1); // -1 because we'll ++ in the for() above.
+ continue;
+ }
}
- }
-};
-
-// Controls quoted-printable encoding characters in headers, per RFC 2047.
-class QuotedPrintableEncodeHeaderDelegate
- : public QuotedPrintableEncodeDelegate {
- public:
- QuotedPrintableEncodeHeaderDelegate() = default;
- ~QuotedPrintableEncodeHeaderDelegate() override = default;
-
- size_t GetMaxLineLengthForEncodedContent() const override {
- return kMaximumLineLength - kRFC2047EncodingPrefixLength -
- kRFC2047EncodingSuffixLength;
- }
- bool ShouldEncodeWhiteSpaceCharacters(bool end_of_line) const override {
- // They should always be encoded if they appear anywhere in the header.
- return true;
- }
+ size_t length_of_encoded_character = 1;
+ if (requires_encoding)
+ length_of_encoded_character += 2;
+ if (!is_last_character)
+ length_of_encoded_character += 1; // + 1 for the = (soft line break).
+
+ // Insert a soft line break if necessary.
+ size_t max_line_length_for_encoded_content = kMaximumLineLength;
+ if (is_header) {
+ max_line_length_for_encoded_content -= kRFC2047EncodingPrefixLength;
+ max_line_length_for_encoded_content -= kRFC2047EncodingSuffixLength;
+ }
- void DidStartLine(Vector<char>& out) override {
- out.Append(kRFC2047EncodingPrefix, kRFC2047EncodingPrefixLength);
- }
+ if (current_line_length + length_of_encoded_character >
+ max_line_length_for_encoded_content) {
+ if (is_header) {
+ out.Append(kRFC2047EncodingSuffix, kRFC2047EncodingSuffixLength);
+ out.Append("\r\n", 2);
+ out.push_back(' ');
+ } else {
+ out.push_back('=');
+ out.Append("\r\n", 2);
+ }
+ current_line_length = 0;
+ if (is_header)
+ out.Append(kRFC2047EncodingPrefix, kRFC2047EncodingPrefixLength);
+ }
- void DidFinishLine(bool last_line, Vector<char>& out) override {
- out.Append(kRFC2047EncodingSuffix, kRFC2047EncodingSuffixLength);
- if (!last_line) {
- out.Append("\r\n", 2);
- out.push_back(' ');
+ // Finally, insert the actual character(s).
+ if (requires_encoding) {
+ out.push_back('=');
+ out.push_back(UpperNibbleToASCIIHexDigit(current_character));
+ out.push_back(LowerNibbleToASCIIHexDigit(current_character));
+ current_line_length += 3;
+ } else {
+ out.push_back(current_character);
+ current_line_length++;
}
}
-};
+ if (is_header)
+ out.Append(kRFC2047EncodingSuffix, kRFC2047EncodingSuffixLength);
+}
-static String ConvertToPrintableCharacters(const String& text) {
+String ConvertToPrintableCharacters(const String& text) {
// If the text contains all printable ASCII characters, no need for encoding.
bool found_non_printable_char = false;
for (wtf_size_t i = 0; i < text.length(); ++i) {
@@ -137,33 +189,48 @@ static String ConvertToPrintableCharacters(const String& text) {
// where, "utf-8" is the chosen charset to represent the text and "Q" is the
// Quoted-Printable format to convert to 7-bit printable ASCII characters.
CString utf8_text = text.Utf8();
- QuotedPrintableEncodeHeaderDelegate header_delegate;
Vector<char> encoded_text;
- QuotedPrintableEncode(utf8_text.data(), utf8_text.length(), &header_delegate,
- encoded_text);
+ QuotedPrintableEncode(utf8_text.data(), utf8_text.length(),
+ true /* is_header */, encoded_text);
return String(encoded_text.data(), encoded_text.size());
}
+} // namespace
+
+const char* MHTMLArchive::kLoadResultUmaName =
+ "PageSerialization.MhtmlLoading.LoadResult";
+
MHTMLArchive::MHTMLArchive() = default;
+// static
+void MHTMLArchive::ReportLoadResult(MHTMLArchive::LoadResult result) {
+ UMA_HISTOGRAM_ENUMERATION(kLoadResultUmaName, result);
+}
+
MHTMLArchive* MHTMLArchive::Create(const KURL& url,
scoped_refptr<const SharedBuffer> data) {
// |data| may be null if archive file is empty.
- if (!data)
+ if (!data || data->IsEmpty()) {
+ ReportLoadResult(LoadResult::kEmptyFile);
return nullptr;
+ }
// MHTML pages can only be loaded from local URLs, http/https URLs, and
// content URLs(Android specific). The latter is now allowed due to full
// sandboxing enforcement on MHTML pages.
- if (!CanLoadArchive(url))
+ if (!CanLoadArchive(url)) {
+ ReportLoadResult(LoadResult::kUrlSchemeNotAllowed);
return nullptr;
+ }
MHTMLParser parser(std::move(data));
HeapVector<Member<ArchiveResource>> resources = parser.ParseArchive();
- if (resources.IsEmpty())
+ if (resources.IsEmpty()) {
+ ReportLoadResult(LoadResult::kInvalidArchive);
return nullptr; // Invalid MHTML file.
+ }
- MHTMLArchive* archive = new MHTMLArchive;
+ MHTMLArchive* archive = MakeGarbageCollected<MHTMLArchive>();
archive->date_ = parser.CreationDate();
size_t resources_count = resources.size();
@@ -194,8 +261,12 @@ MHTMLArchive* MHTMLArchive::Create(const KURL& url,
else
archive->AddSubresource(resource);
}
- if (archive->MainResource())
+ if (archive->MainResource()) {
+ ReportLoadResult(LoadResult::kSuccess);
return archive;
+ }
+
+ ReportLoadResult(LoadResult::kMissingMainResource);
return nullptr;
}
@@ -248,7 +319,7 @@ void MHTMLArchive::GenerateMHTMLHeader(const String& boundary,
// We use utf8() below instead of ascii() as ascii() replaces CRLFs with ??
// (we still only have put ASCII characters in it).
- DCHECK(string_builder.ToString().ContainsOnlyASCII());
+ DCHECK(string_builder.ToString().ContainsOnlyASCIIOrEmpty());
CString ascii_string = string_builder.ToString().Utf8();
output_buffer.Append(ascii_string.data(), ascii_string.length());
@@ -314,9 +385,8 @@ void MHTMLArchive::GenerateMHTMLPart(const String& boundary,
size_t data_length = flat_data.size();
Vector<char> encoded_data;
if (!strcmp(content_encoding, kQuotedPrintable)) {
- QuotedPrintableEncodeBodyDelegate body_delegate;
QuotedPrintableEncode(data, SafeCast<wtf_size_t>(data_length),
- &body_delegate, encoded_data);
+ false /* is_header */, encoded_data);
output_buffer.Append(encoded_data.data(), encoded_data.size());
} else {
DCHECK(!strcmp(content_encoding, kBase64));
diff --git a/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.h b/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.h
index da2d415b334..2f465454a1e 100644
--- a/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.h
+++ b/chromium/third_party/blink/renderer/platform/mhtml/mhtml_archive.h
@@ -55,6 +55,21 @@ class PLATFORM_EXPORT MHTMLArchive final
public:
static MHTMLArchive* Create(const KURL&, scoped_refptr<const SharedBuffer>);
+ MHTMLArchive();
+
+ // Every outcome when loading an archive with MHTMLArchive::Create (mirroring
+ // MHTMLLoadResult in tools/metrics/histograms/enums.xml).
+ enum class LoadResult {
+ kSuccess,
+ kEmptyFile,
+ kUrlSchemeNotAllowed,
+ kInvalidArchive,
+ kMissingMainResource,
+
+ kMaxValue = kMissingMainResource
+ };
+ static const char* kLoadResultUmaName;
+
// Binary encoding results in smaller MHTML files but they might not work in
// other browsers.
enum EncodingPolicy { kUseDefaultEncoding, kUseBinaryEncoding };
@@ -106,7 +121,7 @@ class PLATFORM_EXPORT MHTMLArchive final
void Trace(blink::Visitor*);
private:
- MHTMLArchive();
+ static void ReportLoadResult(LoadResult result);
void SetMainResource(ArchiveResource*);
void AddSubresource(ArchiveResource*);
diff --git a/chromium/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc b/chromium/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc
index 2ffa87c3503..ab208815186 100644
--- a/chromium/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc
+++ b/chromium/third_party/blink/renderer/platform/mhtml/mhtml_parser.cc
@@ -30,24 +30,70 @@
#include "third_party/blink/renderer/platform/mhtml/mhtml_parser.h"
+#include <stddef.h>
#include "third_party/blink/renderer/platform/mhtml/archive_resource.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/network/parsed_content_type.h"
-#include "third_party/blink/renderer/platform/text/quoted_printable.h"
+#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/string_concatenate.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
+namespace {
+
+void QuotedPrintableDecode(const char* data,
+ size_t data_length,
+ Vector<char>& out) {
+ out.clear();
+ if (!data_length)
+ return;
+
+ for (size_t i = 0; i < data_length; ++i) {
+ char current_character = data[i];
+ if (current_character != '=') {
+ out.push_back(current_character);
+ continue;
+ }
+ // We are dealing with a '=xx' sequence.
+ if (data_length - i < 3) {
+ // Unfinished = sequence, append as is.
+ out.push_back(current_character);
+ continue;
+ }
+ char upper_character = data[++i];
+ char lower_character = data[++i];
+ if (upper_character == '\r' && lower_character == '\n')
+ continue;
+
+ if (!IsASCIIHexDigit(upper_character) ||
+ !IsASCIIHexDigit(lower_character)) {
+ // Invalid sequence, = followed by non hex digits, just insert the
+ // characters as is.
+ out.push_back('=');
+ out.push_back(upper_character);
+ out.push_back(lower_character);
+ continue;
+ }
+ out.push_back(
+ static_cast<char>(ToASCIIHexValue(upper_character, lower_character)));
+ }
+}
+
+} // namespace
+
// This class is a limited MIME parser used to parse the MIME headers of MHTML
// files.
class MIMEHeader : public GarbageCollectedFinalized<MIMEHeader> {
public:
- static MIMEHeader* Create() { return new MIMEHeader; }
+ static MIMEHeader* Create() { return MakeGarbageCollected<MIMEHeader>(); }
+
+ MIMEHeader();
enum Encoding {
kQuotedPrintable,
@@ -81,8 +127,6 @@ class MIMEHeader : public GarbageCollectedFinalized<MIMEHeader> {
void Trace(blink::Visitor* visitor) {}
private:
- MIMEHeader();
-
static Encoding ParseContentTransferEncoding(const String&);
String content_type_;
diff --git a/chromium/third_party/blink/renderer/platform/mojo/DEPS b/chromium/third_party/blink/renderer/platform/mojo/DEPS
index 645db84ec00..ea09dcb6cd3 100644
--- a/chromium/third_party/blink/renderer/platform/mojo/DEPS
+++ b/chromium/third_party/blink/renderer/platform/mojo/DEPS
@@ -14,8 +14,6 @@ include_rules = [
"+mojo/public/cpp/base/time_mojom_traits.h",
"+mojo/public/cpp/bindings/binding.h",
"+mojo/public/mojom/base/string16.mojom-blink.h",
- "+services/network/public/mojom/fetch_api.mojom-blink.h",
- "+services/network/public/mojom/restricted_cookie_manager.mojom-blink.h",
"+skia/public/interfaces/bitmap_skbitmap_struct_traits.h",
"+third_party/blink/renderer/platform/blob/blob_data.h",
diff --git a/chromium/third_party/blink/renderer/platform/mojo/blink_typemaps.gni b/chromium/third_party/blink/renderer/platform/mojo/blink_typemaps.gni
index 20484467acc..80784cdc8bd 100644
--- a/chromium/third_party/blink/renderer/platform/mojo/blink_typemaps.gni
+++ b/chromium/third_party/blink/renderer/platform/mojo/blink_typemaps.gni
@@ -10,6 +10,7 @@ typemaps = [
"//mojo/public/cpp/base/unguessable_token.typemap",
"//third_party/blink/renderer/core/messaging/blink_cloneable_message.typemap",
"//third_party/blink/renderer/core/messaging/blink_transferable_message.typemap",
+ "//third_party/blink/renderer/modules/indexeddb/indexed_db_blink.typemap",
"//third_party/blink/renderer/platform/blob/serialized_blob.typemap",
"//third_party/blink/renderer/platform/mojo/big_buffer.typemap",
"//third_party/blink/renderer/platform/mojo/big_string.typemap",
@@ -17,12 +18,10 @@ typemaps = [
"//third_party/blink/renderer/platform/mojo/file.typemap",
"//third_party/blink/renderer/platform/mojo/geometry.typemap",
"//third_party/blink/renderer/platform/mojo/kurl.typemap",
- "//third_party/blink/renderer/platform/mojo/referrer.typemap",
"//third_party/blink/renderer/platform/mojo/security_origin.typemap",
"//third_party/blink/renderer/platform/mojo/string.typemap",
"//third_party/blink/renderer/platform/mojo/time.typemap",
"//third_party/blink/public/platform/modules/bluetooth/bluetooth.typemap",
- "//third_party/blink/public/platform/modules/fetch/fetch_api_request.typemap",
"//third_party/blink/public/common/manifest/display_mode.typemap",
"//third_party/blink/public/common/screen_orientation/screen_orientation_lock_types.typemap",
]
diff --git a/chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.cc b/chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.cc
deleted file mode 100644
index 7f2e0c2e35a..00000000000
--- a/chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.cc
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.h"
-
-#include "mojo/public/cpp/bindings/map_traits_wtf_hash_map.h"
-#include "mojo/public/cpp/bindings/string_traits_wtf.h"
-#include "services/network/public/mojom/fetch_api.mojom-blink.h"
-#include "third_party/blink/public/platform/web_referrer_policy.h"
-#include "third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h"
-#include "third_party/blink/renderer/platform/mojo/kurl_struct_traits.h"
-#include "third_party/blink/renderer/platform/mojo/referrer_struct_traits.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer.h"
-
-namespace mojo {
-
-// static
-blink::KURL StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- url(const blink::WebServiceWorkerRequest& request) {
- return request.Url();
-}
-
-// static
-WTF::String StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- method(const blink::WebServiceWorkerRequest& request) {
- return request.Method();
-}
-
-// static
-WTF::HashMap<WTF::String, WTF::String>
-StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- headers(const blink::WebServiceWorkerRequest& request) {
- WTF::HashMap<WTF::String, WTF::String> header_map;
- for (const auto& pair : request.Headers())
- header_map.insert(pair.key, pair.value);
- return header_map;
-}
-
-// static
-const blink::Referrer& StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- referrer(const blink::WebServiceWorkerRequest& request) {
- return request.GetReferrer();
-}
-
-// static
-scoped_refptr<blink::BlobDataHandle> StructTraits<
- blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::blob(const blink::WebServiceWorkerRequest&
- request) {
- return request.GetBlobDataHandle();
-}
-
-// static
-WTF::String StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- integrity(const blink::WebServiceWorkerRequest& request) {
- return request.Integrity();
-}
-
-// static
-WTF::String StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- client_id(const blink::WebServiceWorkerRequest& request) {
- return request.ClientId();
-}
-
-// static
-bool StructTraits<blink::mojom::FetchAPIRequestDataView,
- blink::WebServiceWorkerRequest>::
- Read(blink::mojom::FetchAPIRequestDataView data,
- blink::WebServiceWorkerRequest* out) {
- network::mojom::FetchRequestMode mode;
- blink::mojom::RequestContextType requestContext;
- network::mojom::RequestContextFrameType frameType;
- blink::KURL url;
- WTF::String method;
- WTF::HashMap<WTF::String, WTF::String> headers;
- scoped_refptr<blink::BlobDataHandle> blob;
- blink::Referrer referrer;
- network::mojom::FetchCredentialsMode credentialsMode;
- network::mojom::FetchRedirectMode redirectMode;
- WTF::String integrity;
- WTF::String clientId;
-
- if (!data.ReadMode(&mode) || !data.ReadRequestContextType(&requestContext) ||
- !data.ReadFrameType(&frameType) || !data.ReadUrl(&url) ||
- !data.ReadMethod(&method) || !data.ReadHeaders(&headers) ||
- !data.ReadBlob(&blob) || !data.ReadReferrer(&referrer) ||
- !data.ReadCredentialsMode(&credentialsMode) ||
- !data.ReadRedirectMode(&redirectMode) || !data.ReadClientId(&clientId) ||
- !data.ReadIntegrity(&integrity)) {
- return false;
- }
-
- out->SetMode(mode);
- out->SetIsMainResourceLoad(data.is_main_resource_load());
- out->SetRequestContext(requestContext);
- out->SetFrameType(frameType);
- out->SetURL(url);
- out->SetMethod(method);
- for (const auto& pair : headers)
- out->SetHeader(pair.key, pair.value);
- out->SetBlobDataHandle(blob);
- out->SetReferrer(referrer.referrer, static_cast<blink::WebReferrerPolicy>(
- referrer.referrer_policy));
- out->SetCredentialsMode(credentialsMode);
- out->SetCacheMode(data.cache_mode());
- out->SetRedirectMode(redirectMode);
- out->SetIntegrity(integrity);
- out->SetKeepalive(data.keepalive());
- out->SetClientId(clientId);
- out->SetIsReload(data.is_reload());
- out->SetIsHistoryNavigation(data.is_history_navigation());
- return true;
-}
-
-} // namespace mojo
diff --git a/chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.h b/chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.h
deleted file mode 100644
index 9b75d1cc348..00000000000
--- a/chromium/third_party/blink/renderer/platform/mojo/fetch_api_request_struct_traits.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_FETCH_API_REQUEST_STRUCT_TRAITS_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_FETCH_API_REQUEST_STRUCT_TRAITS_H_
-
-#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-blink.h"
-#include "third_party/blink/public/platform/web_url_request.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-class KURL;
-}
-
-namespace mojo {
-
-template <>
-struct StructTraits<::blink::mojom::FetchAPIRequestDataView,
- ::blink::WebServiceWorkerRequest> {
- static ::network::mojom::FetchRequestMode mode(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.Mode();
- }
-
- static bool is_main_resource_load(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.IsMainResourceLoad();
- }
-
- static ::blink::mojom::RequestContextType request_context_type(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.GetRequestContext();
- }
-
- static ::network::mojom::RequestContextFrameType frame_type(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.GetFrameType();
- }
-
- static ::blink::KURL url(const ::blink::WebServiceWorkerRequest&);
-
- static WTF::String method(const ::blink::WebServiceWorkerRequest&);
-
- static WTF::HashMap<WTF::String, WTF::String> headers(
- const ::blink::WebServiceWorkerRequest&);
-
- static scoped_refptr<::blink::BlobDataHandle> blob(
- const ::blink::WebServiceWorkerRequest&);
-
- static const ::blink::Referrer& referrer(
- const ::blink::WebServiceWorkerRequest&);
-
- static ::network::mojom::FetchCredentialsMode credentials_mode(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.CredentialsMode();
- }
-
- static ::blink::mojom::FetchCacheMode cache_mode(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.CacheMode();
- }
-
- static ::network::mojom::FetchRedirectMode redirect_mode(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.RedirectMode();
- }
-
- static WTF::String integrity(const ::blink::WebServiceWorkerRequest&);
- static bool keepalive(const ::blink::WebServiceWorkerRequest& request) {
- return request.Keepalive();
- }
- static WTF::String client_id(const ::blink::WebServiceWorkerRequest&);
-
- static bool is_reload(const ::blink::WebServiceWorkerRequest& request) {
- return request.IsReload();
- }
-
- static bool is_history_navigation(
- const ::blink::WebServiceWorkerRequest& request) {
- return request.IsHistoryNavigation();
- }
-
- static bool Read(::blink::mojom::FetchAPIRequestDataView,
- ::blink::WebServiceWorkerRequest* output);
-};
-
-} // namespace mojo
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_FETCH_API_REQUEST_STRUCT_TRAITS_H_
diff --git a/chromium/third_party/blink/renderer/platform/mojo/referrer.typemap b/chromium/third_party/blink/renderer/platform/mojo/referrer.typemap
deleted file mode 100644
index f151339e76c..00000000000
--- a/chromium/third_party/blink/renderer/platform/mojo/referrer.typemap
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2017 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-mojom = "//third_party/blink/public/platform/referrer.mojom"
-public_headers =
- [ "//third_party/blink/renderer/platform/weborigin/referrer.h" ]
-traits_headers =
- [ "//third_party/blink/renderer/platform/mojo/referrer_struct_traits.h" ]
-deps = [
- "//mojo/public/cpp/bindings",
- "//url",
-]
-type_mappings = [ "blink.mojom.Referrer=::blink::Referrer" ]
diff --git a/chromium/third_party/blink/renderer/platform/mojo/referrer_struct_traits.h b/chromium/third_party/blink/renderer/platform/mojo/referrer_struct_traits.h
deleted file mode 100644
index 6ae5f2dccc1..00000000000
--- a/chromium/third_party/blink/renderer/platform/mojo/referrer_struct_traits.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_REFERRER_STRUCT_TRAITS_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_REFERRER_STRUCT_TRAITS_H_
-
-#include "third_party/blink/public/platform/referrer_policy_enum_traits.h"
-#include "third_party/blink/public/platform/web_referrer_policy.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
-#include "third_party/blink/renderer/platform/wtf/assertions.h"
-
-namespace mojo {
-
-template <>
-struct StructTraits<blink::mojom::ReferrerDataView, blink::Referrer> {
- static blink::KURL url(const blink::Referrer& referrer) {
- if (referrer.referrer == blink::Referrer::NoReferrer())
- return blink::KURL();
-
- return blink::KURL(blink::KURL(), referrer.referrer);
- }
-
- // Equality of values is asserted in //Source/web/AssertMatchingEnums.cpp.
- static blink::WebReferrerPolicy policy(const blink::Referrer& referrer) {
- return static_cast<blink::WebReferrerPolicy>(referrer.referrer_policy);
- }
-
- static bool Read(blink::mojom::ReferrerDataView data, blink::Referrer* out) {
- blink::KURL referrer;
- blink::WebReferrerPolicy webReferrerPolicy;
- if (!data.ReadUrl(&referrer) || !data.ReadPolicy(&webReferrerPolicy))
- return false;
-
- out->referrer_policy =
- static_cast<blink::ReferrerPolicy>(webReferrerPolicy);
- if (referrer.GetString().IsEmpty())
- out->referrer = g_null_atom;
- else
- out->referrer = AtomicString(referrer.GetString());
-
- // Mimics the DCHECK() done in the blink::Referrer constructor.
- return referrer.IsValid() || out->referrer == blink::Referrer::NoReferrer();
- }
-};
-
-} // namespace mojo
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_REFERRER_STRUCT_TRAITS_H_
diff --git a/chromium/third_party/blink/renderer/platform/mojo/string16_mojom_traits.cc b/chromium/third_party/blink/renderer/platform/mojo/string16_mojom_traits.cc
index ca71ff99633..985601f7473 100644
--- a/chromium/third_party/blink/renderer/platform/mojo/string16_mojom_traits.cc
+++ b/chromium/third_party/blink/renderer/platform/mojo/string16_mojom_traits.cc
@@ -57,7 +57,10 @@ bool StructTraits<mojo_base::mojom::String16DataView, WTF::String>::Read(
WTF::String* out) {
ArrayDataView<uint16_t> view;
data.GetDataDataView(&view);
- *out = WTF::String(reinterpret_cast<const UChar*>(view.data()), view.size());
+ if (view.size() > std::numeric_limits<uint32_t>::max())
+ return false;
+ *out = WTF::String(reinterpret_cast<const UChar*>(view.data()),
+ static_cast<uint32_t>(view.size()));
return true;
}
@@ -88,12 +91,16 @@ bool StructTraits<mojo_base::mojom::BigString16DataView, WTF::String>::Read(
if (size % sizeof(UChar))
return false;
+ size /= sizeof(UChar);
+ if (size > std::numeric_limits<uint32_t>::max())
+ return false;
+
// An empty |mojo_base::BigBuffer| may have a null |data()| if empty.
if (!size) {
*out = g_empty_string;
} else {
*out = WTF::String(reinterpret_cast<const UChar*>(buffer.data()),
- size / sizeof(UChar));
+ static_cast<uint32_t>(size));
}
return true;
diff --git a/chromium/third_party/blink/renderer/platform/network/content_security_policy_response_headers.cc b/chromium/third_party/blink/renderer/platform/network/content_security_policy_response_headers.cc
index f19a8487e86..83a957a4472 100644
--- a/chromium/third_party/blink/renderer/platform/network/content_security_policy_response_headers.cc
+++ b/chromium/third_party/blink/renderer/platform/network/content_security_policy_response_headers.cc
@@ -42,9 +42,9 @@ ContentSecurityPolicyResponseHeaders::ContentSecurityPolicyResponseHeaders(
ContentSecurityPolicyResponseHeaders::ContentSecurityPolicyResponseHeaders(
const HTTPHeaderMap& headers,
bool should_parse_wasm_eval)
- : content_security_policy_(headers.Get(HTTPNames::Content_Security_Policy)),
+ : content_security_policy_(headers.Get(http_names::kContentSecurityPolicy)),
content_security_policy_report_only_(
- headers.Get(HTTPNames::Content_Security_Policy_Report_Only)),
+ headers.Get(http_names::kContentSecurityPolicyReportOnly)),
should_parse_wasm_eval_(should_parse_wasm_eval) {}
ContentSecurityPolicyResponseHeaders
diff --git a/chromium/third_party/blink/renderer/platform/network/encoded_form_data.cc b/chromium/third_party/blink/renderer/platform/network/encoded_form_data.cc
index 5ae025f2d62..a01dfe7f21a 100644
--- a/chromium/third_party/blink/renderer/platform/network/encoded_form_data.cc
+++ b/chromium/third_party/blink/renderer/platform/network/encoded_form_data.cc
@@ -49,7 +49,7 @@ scoped_refptr<EncodedFormData> EncodedFormData::Create() {
}
scoped_refptr<EncodedFormData> EncodedFormData::Create(const void* data,
- size_t size) {
+ wtf_size_t size) {
scoped_refptr<EncodedFormData> result = Create();
result->AppendData(data, size);
return result;
@@ -79,10 +79,8 @@ scoped_refptr<EncodedFormData> EncodedFormData::DeepCopy() const {
form_data->boundary_ = boundary_;
form_data->contains_password_data_ = contains_password_data_;
- size_t n = elements_.size();
- form_data->elements_.ReserveInitialCapacity(n);
- for (size_t i = 0; i < n; ++i) {
- const FormDataElement& e = elements_[i];
+ form_data->elements_.ReserveInitialCapacity(elements_.size());
+ for (const FormDataElement& e : elements_) {
switch (e.type_) {
case FormDataElement::kData:
form_data->elements_.UncheckedAppend(FormDataElement(e.data_));
@@ -110,11 +108,11 @@ scoped_refptr<EncodedFormData> EncodedFormData::DeepCopy() const {
return form_data;
}
-void EncodedFormData::AppendData(const void* data, size_t size) {
+void EncodedFormData::AppendData(const void* data, wtf_size_t size) {
if (elements_.IsEmpty() || elements_.back().type_ != FormDataElement::kData)
elements_.push_back(FormDataElement());
FormDataElement& e = elements_.back();
- size_t old_size = e.data_.size();
+ wtf_size_t old_size = e.data_.size();
e.data_.Grow(old_size + size);
memcpy(e.data_.data() + old_size, data, size);
}
@@ -146,11 +144,9 @@ void EncodedFormData::AppendDataPipe(
void EncodedFormData::Flatten(Vector<char>& data) const {
// Concatenate all the byte arrays, but omit everything else.
data.clear();
- size_t n = elements_.size();
- for (size_t i = 0; i < n; ++i) {
- const FormDataElement& e = elements_[i];
+ for (const FormDataElement& e : elements_) {
if (e.type_ == FormDataElement::kData)
- data.Append(e.data_.data(), static_cast<size_t>(e.data_.size()));
+ data.Append(e.data_.data(), e.data_.size());
}
}
@@ -163,9 +159,7 @@ String EncodedFormData::FlattenToString() const {
unsigned long long EncodedFormData::SizeInBytes() const {
unsigned size = 0;
- size_t n = elements_.size();
- for (size_t i = 0; i < n; ++i) {
- const FormDataElement& e = elements_[i];
+ for (const FormDataElement& e : elements_) {
switch (e.type_) {
case FormDataElement::kData:
size += e.data_.size();
diff --git a/chromium/third_party/blink/renderer/platform/network/encoded_form_data.h b/chromium/third_party/blink/renderer/platform/network/encoded_form_data.h
index 3c4e6f6146c..c112cd531d6 100644
--- a/chromium/third_party/blink/renderer/platform/network/encoded_form_data.h
+++ b/chromium/third_party/blink/renderer/platform/network/encoded_form_data.h
@@ -125,14 +125,14 @@ class PLATFORM_EXPORT EncodedFormData : public RefCounted<EncodedFormData> {
};
static scoped_refptr<EncodedFormData> Create();
- static scoped_refptr<EncodedFormData> Create(const void*, size_t);
+ static scoped_refptr<EncodedFormData> Create(const void*, wtf_size_t);
static scoped_refptr<EncodedFormData> Create(const CString&);
static scoped_refptr<EncodedFormData> Create(const Vector<char>&);
scoped_refptr<EncodedFormData> Copy() const;
scoped_refptr<EncodedFormData> DeepCopy() const;
~EncodedFormData();
- void AppendData(const void* data, size_t);
+ void AppendData(const void* data, wtf_size_t);
void AppendFile(const String& file_path);
void AppendFileRange(const String& filename,
long long start,
diff --git a/chromium/third_party/blink/renderer/platform/network/encoded_form_data_test.cc b/chromium/third_party/blink/renderer/platform/network/encoded_form_data_test.cc
index 7d8ac9748f8..3349b1cb395 100644
--- a/chromium/third_party/blink/renderer/platform/network/encoded_form_data_test.cc
+++ b/chromium/third_party/blink/renderer/platform/network/encoded_form_data_test.cc
@@ -76,7 +76,7 @@ TEST_F(EncodedFormDataTest, DeepCopy) {
// Check pointers are different, i.e. deep-copied.
ASSERT_NE(original.get(), copy.get());
- for (size_t i = 0; i < 3; ++i) {
+ for (wtf_size_t i = 0; i < 3; ++i) {
if (copy_elements[i].filename_.Impl()) {
EXPECT_NE(original_elements[i].filename_.Impl(),
copy_elements[i].filename_.Impl());
diff --git a/chromium/third_party/blink/renderer/platform/network/form_data_encoder.cc b/chromium/third_party/blink/renderer/platform/network/form_data_encoder.cc
index 57116306536..c5cca2a7288 100644
--- a/chromium/third_party/blink/renderer/platform/network/form_data_encoder.cc
+++ b/chromium/third_party/blink/renderer/platform/network/form_data_encoder.cc
@@ -39,7 +39,7 @@ static inline void Append(Vector<char>& buffer, char string) {
}
static inline void Append(Vector<char>& buffer, const char* string) {
- buffer.Append(string, strlen(string));
+ buffer.Append(string, static_cast<wtf_size_t>(strlen(string)));
}
static inline void Append(Vector<char>& buffer, const CString& string) {
diff --git a/chromium/third_party/blink/renderer/platform/network/http_header_map.cc b/chromium/third_party/blink/renderer/platform/network/http_header_map.cc
index 5d63fd0fdc0..a4fa8a202d9 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_header_map.cc
+++ b/chromium/third_party/blink/renderer/platform/network/http_header_map.cc
@@ -53,11 +53,8 @@ std::unique_ptr<CrossThreadHTTPHeaderMapData> HTTPHeaderMap::CopyData() const {
void HTTPHeaderMap::Adopt(std::unique_ptr<CrossThreadHTTPHeaderMapData> data) {
Clear();
- size_t data_size = data->size();
- for (size_t index = 0; index < data_size; ++index) {
- std::pair<String, String>& header = (*data)[index];
+ for (const auto& header : *data)
Set(AtomicString(header.first), AtomicString(header.second));
- }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/network/http_header_map.h b/chromium/third_party/blink/renderer/platform/network/http_header_map.h
index 12a2e012492..d7e0f4b6898 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_header_map.h
+++ b/chromium/third_party/blink/renderer/platform/network/http_header_map.h
@@ -60,7 +60,7 @@ class PLATFORM_EXPORT HTTPHeaderMap final {
typedef MapType::AddResult AddResult;
typedef MapType::const_iterator const_iterator;
- size_t size() const { return headers_.size(); }
+ wtf_size_t size() const { return headers_.size(); }
const_iterator begin() const { return headers_.begin(); }
const_iterator end() const { return headers_.end(); }
const_iterator Find(const AtomicString& k) const { return headers_.find(k); }
diff --git a/chromium/third_party/blink/renderer/platform/network/http_names.json5 b/chromium/third_party/blink/renderer/platform/network/http_names.json5
index e12b5fe4c54..ca872fec2d0 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_names.json5
+++ b/chromium/third_party/blink/renderer/platform/network/http_names.json5
@@ -1,6 +1,6 @@
{
metadata: {
- namespace: "HTTP",
+ namespace: "http_names",
export: "PLATFORM_EXPORT",
},
diff --git a/chromium/third_party/blink/renderer/platform/network/http_parsers.cc b/chromium/third_party/blink/renderer/platform/network/http_parsers.cc
index ff198ca43ce..9847f064c20 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_parsers.cc
+++ b/chromium/third_party/blink/renderer/platform/network/http_parsers.cc
@@ -124,7 +124,7 @@ bool IsValidHTTPHeaderValue(const String& name) {
// FIXME: This should really match name against
// field-value in section 4.2 of RFC 2616.
- return name.ContainsOnlyLatin1() && !name.Contains('\r') &&
+ return name.ContainsOnlyLatin1OrEmpty() && !name.Contains('\r') &&
!name.Contains('\n') && !name.Contains('\0');
}
@@ -381,7 +381,7 @@ ContentTypeOptionsDisposition ParseContentTypeOptionsHeader(
Vector<String> results;
value.Split(",", results);
- if (results[0].StripWhiteSpace().LowerASCII() == "nosniff")
+ if (results.size() && results[0].StripWhiteSpace().LowerASCII() == "nosniff")
return kContentTypeOptionsNosniff;
return kContentTypeOptionsNone;
}
@@ -425,10 +425,10 @@ static inline String TrimToNextSeparator(const String& str) {
static void ParseCacheHeader(const String& header,
Vector<std::pair<String, String>>& result) {
const String safe_header = header.RemoveCharacters(IsControlCharacter);
- unsigned max = safe_header.length();
- for (unsigned pos = 0; pos < max; /* pos incremented in loop */) {
- size_t next_comma_position = safe_header.find(',', pos);
- size_t next_equal_sign_position = safe_header.find('=', pos);
+ wtf_size_t max = safe_header.length();
+ for (wtf_size_t pos = 0; pos < max; /* pos incremented in loop */) {
+ wtf_size_t next_comma_position = safe_header.find(',', pos);
+ wtf_size_t next_equal_sign_position = safe_header.find('=', pos);
if (next_equal_sign_position != kNotFound &&
(next_equal_sign_position < next_comma_position ||
next_comma_position == kNotFound)) {
@@ -442,7 +442,7 @@ static void ParseCacheHeader(const String& header,
String value = safe_header.Substring(pos, max - pos).StripWhiteSpace();
if (value[0] == '"') {
// The value is a quoted string
- size_t next_double_quote_position = value.find('"', 1);
+ wtf_size_t next_double_quote_position = value.find('"', 1);
if (next_double_quote_position != kNotFound) {
// Store the value as a quoted string without quotes
result.push_back(std::pair<String, String>(
@@ -451,7 +451,7 @@ static void ParseCacheHeader(const String& header,
pos += (safe_header.find('"', pos) - pos) +
next_double_quote_position + 1;
// Move past next comma, if there is one
- size_t next_comma_position2 = safe_header.find(',', pos);
+ wtf_size_t next_comma_position2 = safe_header.find(',', pos);
if (next_comma_position2 != kNotFound)
pos += next_comma_position2 - pos + 1;
else
@@ -466,7 +466,7 @@ static void ParseCacheHeader(const String& header,
}
} else {
// The value is a token until the next comma
- size_t next_comma_position2 = value.find(',');
+ wtf_size_t next_comma_position2 = value.find(',');
if (next_comma_position2 != kNotFound) {
// The value is delimited by the next comma
result.push_back(std::pair<String, String>(
@@ -521,8 +521,8 @@ CacheControlHeader ParseCacheControlDirectives(
Vector<std::pair<String, String>> directives;
ParseCacheHeader(cache_control_value, directives);
- size_t directives_size = directives.size();
- for (size_t i = 0; i < directives_size; ++i) {
+ wtf_size_t directives_size = directives.size();
+ for (wtf_size_t i = 0; i < directives_size; ++i) {
// RFC2616 14.9.1: A no-cache directive with a value is only meaningful
// for proxy caches. It should be ignored by a browser level cache.
if (DeprecatedEqualIgnoringCase(directives[i].first, kNoCacheDirective) &&
@@ -578,9 +578,9 @@ void ParseCommaDelimitedHeader(const String& header_value,
}
bool ParseMultipartHeadersFromBody(const char* bytes,
- size_t size,
+ wtf_size_t size,
ResourceResponse* response,
- size_t* end) {
+ wtf_size_t* end) {
DCHECK(IsMainThread());
int headers_end_pos =
@@ -589,7 +589,7 @@ bool ParseMultipartHeadersFromBody(const char* bytes,
if (headers_end_pos < 0)
return false;
- *end = headers_end_pos;
+ *end = static_cast<wtf_size_t>(headers_end_pos);
// Eat headers and prepend a status line as is required by
// HttpResponseHeaders.
@@ -597,8 +597,8 @@ bool ParseMultipartHeadersFromBody(const char* bytes,
headers.append(bytes, headers_end_pos);
scoped_refptr<net::HttpResponseHeaders> response_headers =
- new net::HttpResponseHeaders(
- net::HttpUtil::AssembleRawHeaders(headers.data(), headers.length()));
+ new net::HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders(
+ headers.data(), static_cast<int>(headers.length())));
std::string mime_type, charset;
response_headers->GetMimeTypeAndCharset(&mime_type, &charset);
@@ -622,31 +622,31 @@ bool ParseMultipartHeadersFromBody(const char* bytes,
}
bool ParseMultipartFormHeadersFromBody(const char* bytes,
- size_t size,
+ wtf_size_t size,
HTTPHeaderMap* header_fields,
- size_t* end) {
+ wtf_size_t* end) {
DCHECK_EQ(0u, header_fields->size());
- int headersEndPos =
+ int headers_end_pos =
net::HttpUtil::LocateEndOfAdditionalHeaders(bytes, size, 0);
- if (headersEndPos < 0)
+ if (headers_end_pos < 0)
return false;
- *end = headersEndPos;
+ *end = static_cast<wtf_size_t>(headers_end_pos);
// Eat headers and prepend a status line as is required by
// HttpResponseHeaders.
std::string headers("HTTP/1.1 200 OK\r\n");
- headers.append(bytes, headersEndPos);
+ headers.append(bytes, headers_end_pos);
scoped_refptr<net::HttpResponseHeaders> responseHeaders =
- new net::HttpResponseHeaders(
- net::HttpUtil::AssembleRawHeaders(headers.data(), headers.length()));
+ new net::HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders(
+ headers.data(), static_cast<wtf_size_t>(headers.length())));
// Copy selected header fields.
const AtomicString* const headerNamePointers[] = {
- &HTTPNames::Content_Disposition, &HTTPNames::Content_Type};
+ &http_names::kContentDisposition, &http_names::kContentType};
for (const AtomicString* headerNamePointer : headerNamePointers) {
StringUTF8Adaptor adaptor(*headerNamePointer);
size_t iterator = 0;
diff --git a/chromium/third_party/blink/renderer/platform/network/http_parsers.h b/chromium/third_party/blink/renderer/platform/network/http_parsers.h
index 7232cc34a63..44f42550cad 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_parsers.h
+++ b/chromium/third_party/blink/renderer/platform/network/http_parsers.h
@@ -139,16 +139,16 @@ ParseContentTypeOptionsHeader(const String& header);
// if the headers part ends in |bytes[0..size]|. Returns false otherwise.
PLATFORM_EXPORT bool ParseMultipartFormHeadersFromBody(
const char* bytes,
- size_t,
+ wtf_size_t,
HTTPHeaderMap* header_fields,
- size_t* end);
+ wtf_size_t* end);
// Returns true and stores the position of the end of the headers to |*end|
// if the headers part ends in |bytes[0..size]|. Returns false otherwise.
PLATFORM_EXPORT bool ParseMultipartHeadersFromBody(const char* bytes,
- size_t,
+ wtf_size_t,
ResourceResponse*,
- size_t* end);
+ wtf_size_t* end);
// Extracts the values in a Content-Range header and returns true if all three
// values are present and valid for a 206 response; otherwise returns false.
diff --git a/chromium/third_party/blink/renderer/platform/network/http_parsers_fuzzer.cc b/chromium/third_party/blink/renderer/platform/network/http_parsers_fuzzer.cc
index 7f8de80b18e..ad0dbf80356 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_parsers_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/platform/network/http_parsers_fuzzer.cc
@@ -12,13 +12,17 @@
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ // Larger inputs trigger OOMs, timeouts and slow units.
+ if (size > 65536)
+ return 0;
+
static blink::BlinkFuzzerTestSupport test_support;
blink::CommaDelimitedHeaderSet set;
double delay;
String url;
blink::ResourceResponse response;
- size_t end;
+ wtf_size_t end;
String report_url;
String failure_reason;
unsigned failure_position = 0;
diff --git a/chromium/third_party/blink/renderer/platform/network/http_parsers_test.cc b/chromium/third_party/blink/renderer/platform/network/http_parsers_test.cc
index 358a4cd1ed8..0b796138c19 100644
--- a/chromium/third_party/blink/renderer/platform/network/http_parsers_test.cc
+++ b/chromium/third_party/blink/renderer/platform/network/http_parsers_test.cc
@@ -306,9 +306,10 @@ TEST(HTTPParsersTest, ParseMultipartHeadersResult) {
};
for (size_t i = 0; i < arraysize(tests); ++i) {
ResourceResponse response;
- size_t end = 0;
+ wtf_size_t end = 0;
bool result = ParseMultipartHeadersFromBody(
- tests[i].data, strlen(tests[i].data), &response, &end);
+ tests[i].data, static_cast<wtf_size_t>(strlen(tests[i].data)),
+ &response, &end);
EXPECT_EQ(tests[i].result, result);
EXPECT_EQ(tests[i].end, end);
}
@@ -321,7 +322,7 @@ TEST(HTTPParsersTest, ParseMultipartHeaders) {
response.AddHTTPHeaderField("content-length", "999");
const char kData[] = "content-type: image/png\ncontent-length: 10\n\n";
- size_t end = 0;
+ wtf_size_t end = 0;
bool result =
ParseMultipartHeadersFromBody(kData, strlen(kData), &response, &end);
@@ -336,7 +337,7 @@ TEST(HTTPParsersTest, ParseMultipartHeaders) {
TEST(HTTPParsersTest, ParseMultipartHeadersContentCharset) {
ResourceResponse response;
const char kData[] = "content-type: text/html; charset=utf-8\n\n";
- size_t end = 0;
+ wtf_size_t end = 0;
bool result =
ParseMultipartHeadersFromBody(kData, strlen(kData), &response, &end);
@@ -598,6 +599,7 @@ TEST(HTTPParsersTest, ParseContentTypeOptionsTest) {
{"nosniff , not-nosniff", kContentTypeOptionsNosniff},
{" nosniff , none", kContentTypeOptionsNosniff},
{"", kContentTypeOptionsNone},
+ {",", kContentTypeOptionsNone},
{"none", kContentTypeOptionsNone},
{"none, nosniff", kContentTypeOptionsNone}};
for (const auto& test : cases) {
diff --git a/chromium/third_party/blink/renderer/platform/network/mime/content_type.cc b/chromium/third_party/blink/renderer/platform/network/mime/content_type.cc
index a3ddcda5792..95072e109fa 100644
--- a/chromium/third_party/blink/renderer/platform/network/mime/content_type.cc
+++ b/chromium/third_party/blink/renderer/platform/network/mime/content_type.cc
@@ -38,15 +38,15 @@ String ContentType::Parameter(const String& parameter_name) const {
// a MIME type can have one or more "param=value" after a semi-colon, and
// separated from each other by semi-colons
- size_t semi = stripped_type.find(';');
+ wtf_size_t semi = stripped_type.find(';');
if (semi != kNotFound) {
- size_t start =
+ wtf_size_t start =
stripped_type.FindIgnoringASCIICase(parameter_name, semi + 1);
if (start != kNotFound) {
start = stripped_type.find('=', start + parameter_name.length());
if (start != kNotFound) {
- size_t quote = stripped_type.find('\"', start + 1);
- size_t end = stripped_type.find('\"', start + 2);
+ wtf_size_t quote = stripped_type.find('\"', start + 1);
+ wtf_size_t end = stripped_type.find('\"', start + 2);
if (quote != kNotFound && end != kNotFound) {
start = quote;
} else {
@@ -67,7 +67,7 @@ String ContentType::GetType() const {
String stripped_type = type_.StripWhiteSpace();
// "type" can have parameters after a semi-colon, strip them
- size_t semi = stripped_type.find(';');
+ wtf_size_t semi = stripped_type.find(';');
if (semi != kNotFound)
stripped_type = stripped_type.Left(semi).StripWhiteSpace();
diff --git a/chromium/third_party/blink/renderer/platform/network/mime/mime_type_from_url.cc b/chromium/third_party/blink/renderer/platform/network/mime/mime_type_from_url.cc
index e1f5c1ae3f8..d0a112285a8 100644
--- a/chromium/third_party/blink/renderer/platform/network/mime/mime_type_from_url.cc
+++ b/chromium/third_party/blink/renderer/platform/network/mime/mime_type_from_url.cc
@@ -34,7 +34,7 @@ namespace blink {
String MimeTypeFromDataURL(const String& url) {
DCHECK(ProtocolIs(url, "data"));
- size_t index = url.find(';');
+ wtf_size_t index = url.find(';');
if (index == kNotFound)
index = url.find(',');
if (index != kNotFound) {
diff --git a/chromium/third_party/blink/renderer/platform/network/mime/mime_type_registry.cc b/chromium/third_party/blink/renderer/platform/network/mime/mime_type_registry.cc
index 354528a3938..6fd5cf4bf64 100644
--- a/chromium/third_party/blink/renderer/platform/network/mime/mime_type_registry.cc
+++ b/chromium/third_party/blink/renderer/platform/network/mime/mime_type_registry.cc
@@ -47,7 +47,7 @@ std::string ToLowerASCIIInternal(CHARTYPE* str, SIZETYPE length) {
// Does the same as ToASCIIOrEmpty, but also makes the chars lower.
std::string ToLowerASCIIOrEmpty(const String& str) {
- if (str.IsEmpty() || !str.ContainsOnlyASCII())
+ if (str.IsEmpty() || !str.ContainsOnlyASCIIOrEmpty())
return std::string();
if (str.Is8Bit())
return ToLowerASCIIInternal(str.Characters8(), str.length());
diff --git a/chromium/third_party/blink/renderer/platform/network/network_instrumentation.cc b/chromium/third_party/blink/renderer/platform/network/network_instrumentation.cc
index 1c0e4a23a82..cf4f6a26278 100644
--- a/chromium/third_party/blink/renderer/platform/network/network_instrumentation.cc
+++ b/chromium/third_party/blink/renderer/platform/network/network_instrumentation.cc
@@ -18,7 +18,8 @@ using blink::TracedValue;
const char kBlinkResourceID[] = "BlinkResourceID";
const char kResourceLoadTitle[] = "ResourceLoad";
const char kResourcePrioritySetTitle[] = "ResourcePrioritySet";
-const char kNetInstrumentationCategory[] = TRACE_DISABLED_BY_DEFAULT("network");
+constexpr const char kNetInstrumentationCategory[] =
+ TRACE_DISABLED_BY_DEFAULT("network");
const char* RequestOutcomeToString(RequestOutcome outcome) {
switch (outcome) {
diff --git a/chromium/third_party/blink/renderer/platform/network/network_state_notifier.cc b/chromium/third_party/blink/renderer/platform/network/network_state_notifier.cc
index 91e7ab621fe..769ce628d4f 100644
--- a/chromium/third_party/blink/renderer/platform/network/network_state_notifier.cc
+++ b/chromium/third_party/blink/renderer/platform/network/network_state_notifier.cc
@@ -30,7 +30,7 @@
#include "net/nqe/network_quality_estimator_params.h"
#include "third_party/blink/public/common/client_hints/client_hints.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -301,7 +301,7 @@ void NetworkStateNotifier::NotifyObserversOnTaskRunner(
observer_list->iterating = true;
- for (size_t i = 0; i < observer_list->observers.size(); ++i) {
+ for (wtf_size_t i = 0; i < observer_list->observers.size(); ++i) {
// Observers removed during iteration are zeroed out, skip them.
if (!observer_list->observers[i])
continue;
@@ -370,7 +370,7 @@ void NetworkStateNotifier::RemoveObserverFromMap(
return;
Vector<NetworkStateObserver*>& observers = observer_list->observers;
- size_t index = observers.Find(observer);
+ wtf_size_t index = observers.Find(observer);
if (index != kNotFound) {
observers[index] = 0;
observer_list->zeroed_observers.push_back(index);
@@ -398,7 +398,7 @@ void NetworkStateNotifier::CollectZeroedObservers(
// If any observers were removed during the iteration they will have
// 0 values, clean them up.
- for (size_t i = 0; i < list->zeroed_observers.size(); ++i)
+ for (wtf_size_t i = 0; i < list->zeroed_observers.size(); ++i)
list->observers.EraseAt(list->zeroed_observers[i]);
list->zeroed_observers.clear();
diff --git a/chromium/third_party/blink/renderer/platform/network/network_state_notifier.h b/chromium/third_party/blink/renderer/platform/network/network_state_notifier.h
index 5fb43bd0fc3..14e350a1ab5 100644
--- a/chromium/third_party/blink/renderer/platform/network/network_state_notifier.h
+++ b/chromium/third_party/blink/renderer/platform/network/network_state_notifier.h
@@ -306,7 +306,7 @@ class PLATFORM_EXPORT NetworkStateNotifier {
ObserverList() : iterating(false) {}
bool iterating;
Vector<NetworkStateObserver*> observers;
- Vector<size_t> zeroed_observers; // Indices in observers that are 0.
+ Vector<wtf_size_t> zeroed_observers; // Indices in observers that are 0.
};
// This helper scope issues required notifications when mutating the state if
diff --git a/chromium/third_party/blink/renderer/platform/network/network_utils.cc b/chromium/third_party/blink/renderer/platform/network/network_utils.cc
index ef4690790df..9f7d946f297 100644
--- a/chromium/third_party/blink/renderer/platform/network/network_utils.cc
+++ b/chromium/third_party/blink/renderer/platform/network/network_utils.cc
@@ -24,14 +24,15 @@
namespace {
net::registry_controlled_domains::PrivateRegistryFilter
-getNetPrivateRegistryFilter(blink::NetworkUtils::PrivateRegistryFilter filter) {
+getNetPrivateRegistryFilter(
+ blink::network_utils::PrivateRegistryFilter filter) {
switch (filter) {
- case blink::NetworkUtils::kIncludePrivateRegistries:
+ case blink::network_utils::kIncludePrivateRegistries:
return net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES;
- case blink::NetworkUtils::kExcludePrivateRegistries:
+ case blink::network_utils::kExcludePrivateRegistries:
return net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES;
}
- // There are only two NetworkUtils::PrivateRegistryFilter enum entries, so
+ // There are only two network_utils::PrivateRegistryFilter enum entries, so
// we should never reach this point. However, we must have a default return
// value to avoid a compiler error.
NOTREACHED();
@@ -42,7 +43,7 @@ getNetPrivateRegistryFilter(blink::NetworkUtils::PrivateRegistryFilter filter) {
namespace blink {
-namespace NetworkUtils {
+namespace network_utils {
bool IsReservedIPAddress(const String& host) {
net::IPAddress address;
@@ -132,6 +133,6 @@ String GenerateAcceptLanguageHeader(const String& lang) {
net::HttpUtil::GenerateAcceptLanguageHeader(string));
}
-} // NetworkUtils
+} // namespace network_utils
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/network/network_utils.h b/chromium/third_party/blink/renderer/platform/network/network_utils.h
index 30afc6127a9..ac3cb6fbc29 100644
--- a/chromium/third_party/blink/renderer/platform/network/network_utils.h
+++ b/chromium/third_party/blink/renderer/platform/network/network_utils.h
@@ -14,7 +14,7 @@ class KURL;
class SharedBuffer;
class ResourceResponse;
-namespace NetworkUtils {
+namespace network_utils {
enum PrivateRegistryFilter {
kIncludePrivateRegistries,
@@ -46,7 +46,7 @@ PLATFORM_EXPORT bool IsLegacySymantecCertError(int);
PLATFORM_EXPORT String GenerateAcceptLanguageHeader(const String&);
-} // NetworkUtils
+} // namespace network_utils
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/network/network_utils_test.cc b/chromium/third_party/blink/renderer/platform/network/network_utils_test.cc
index bb493108ca6..b206ecfb1c1 100644
--- a/chromium/third_party/blink/renderer/platform/network/network_utils_test.cc
+++ b/chromium/third_party/blink/renderer/platform/network/network_utils_test.cc
@@ -12,104 +12,104 @@ namespace blink {
TEST(NetworkUtilsTest, IsReservedIPAddress) {
// Unreserved IPv4 addresses (in various forms).
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("8.8.8.8"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("99.64.0.0"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("212.15.0.0"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("212.15"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("212.15.0"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("3557752832"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("8.8.8.8"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("99.64.0.0"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15.0.0"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15.0"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("3557752832"));
// Reserved IPv4 addresses (in various forms).
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("192.168.0.0"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("192.168.0.6"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("10.0.0.5"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("10.0.0"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("10.0"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("3232235526"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("192.168.0.0"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("192.168.0.6"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0.0.5"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0.0"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("3232235526"));
// Unreserved IPv6 addresses.
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress(
+ EXPECT_FALSE(network_utils::IsReservedIPAddress(
"[FFC0:ba98:7654:3210:FEDC:BA98:7654:3210]"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress(
+ EXPECT_FALSE(network_utils::IsReservedIPAddress(
"[2000:ba98:7654:2301:EFCD:BA98:7654:3210]"));
// IPv4-mapped to IPv6
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("[::ffff:8.8.8.8]"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("[::ffff:8.8.8.8]"));
// Reserved IPv6 addresses.
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("[::1]"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("[::192.9.5.5]"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("[::ffff:192.168.1.1]"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress("[FEED::BEEF]"));
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress(
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("[::1]"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("[::192.9.5.5]"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("[::ffff:192.168.1.1]"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress("[FEED::BEEF]"));
+ EXPECT_TRUE(network_utils::IsReservedIPAddress(
"[FEC0:ba98:7654:3210:FEDC:BA98:7654:3210]"));
// Not IP addresses at all.
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("example.com"));
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress("127.0.0.1.example.com"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("example.com"));
+ EXPECT_FALSE(network_utils::IsReservedIPAddress("127.0.0.1.example.com"));
// Moar IPv4
for (int i = 0; i < 256; i++) {
net::IPAddress address(i, 0, 0, 1);
std::string address_string = address.ToString();
if (i == 0 || i == 10 || i == 127 || i > 223) {
- EXPECT_TRUE(NetworkUtils::IsReservedIPAddress(
+ EXPECT_TRUE(network_utils::IsReservedIPAddress(
String::FromUTF8(address_string.data(), address_string.length())));
} else {
- EXPECT_FALSE(NetworkUtils::IsReservedIPAddress(
+ EXPECT_FALSE(network_utils::IsReservedIPAddress(
String::FromUTF8(address_string.data(), address_string.length())));
}
}
}
TEST(NetworkUtilsTest, GetDomainAndRegistry) {
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- "", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- ".", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- "..", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- "com", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- ".com", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ(
- "", NetworkUtils::GetDomainAndRegistry(
- "www.example.com:8000", NetworkUtils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ "", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ ".", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ "..", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ "com", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ ".com", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ "www.example.com:8000",
+ network_utils::kIncludePrivateRegistries));
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- "localhost", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("", NetworkUtils::GetDomainAndRegistry(
- "127.0.0.1", NetworkUtils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ "localhost", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("", network_utils::GetDomainAndRegistry(
+ "127.0.0.1", network_utils::kIncludePrivateRegistries));
EXPECT_EQ("example.com",
- NetworkUtils::GetDomainAndRegistry(
- "example.com", NetworkUtils::kIncludePrivateRegistries));
+ network_utils::GetDomainAndRegistry(
+ "example.com", network_utils::kIncludePrivateRegistries));
EXPECT_EQ("example.com",
- NetworkUtils::GetDomainAndRegistry(
- "www.example.com", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("example.com",
- NetworkUtils::GetDomainAndRegistry(
- "static.example.com", NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("example.com", NetworkUtils::GetDomainAndRegistry(
+ network_utils::GetDomainAndRegistry(
+ "www.example.com", network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry(
+ "static.example.com",
+ network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry(
"multilevel.www.example.com",
- NetworkUtils::kIncludePrivateRegistries));
+ network_utils::kIncludePrivateRegistries));
EXPECT_EQ("example.co.uk",
- NetworkUtils::GetDomainAndRegistry(
- "www.example.co.uk", NetworkUtils::kIncludePrivateRegistries));
+ network_utils::GetDomainAndRegistry(
+ "www.example.co.uk", network_utils::kIncludePrivateRegistries));
// Verify proper handling of 'private registries'.
- EXPECT_EQ("foo.appspot.com", NetworkUtils::GetDomainAndRegistry(
+ EXPECT_EQ("foo.appspot.com", network_utils::GetDomainAndRegistry(
"www.foo.appspot.com",
- NetworkUtils::kIncludePrivateRegistries));
- EXPECT_EQ("appspot.com", NetworkUtils::GetDomainAndRegistry(
+ network_utils::kIncludePrivateRegistries));
+ EXPECT_EQ("appspot.com", network_utils::GetDomainAndRegistry(
"www.foo.appspot.com",
- NetworkUtils::kExcludePrivateRegistries));
+ network_utils::kExcludePrivateRegistries));
// Verify that unknown registries are included.
EXPECT_EQ("example.notarealregistry",
- NetworkUtils::GetDomainAndRegistry(
+ network_utils::GetDomainAndRegistry(
"www.example.notarealregistry",
- NetworkUtils::kIncludePrivateRegistries));
+ network_utils::kIncludePrivateRegistries));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/network/parsed_content_header_field_parameters.cc b/chromium/third_party/blink/renderer/platform/network/parsed_content_header_field_parameters.cc
index bda672d3713..4cfe25b5833 100644
--- a/chromium/third_party/blink/renderer/platform/network/parsed_content_header_field_parameters.cc
+++ b/chromium/third_party/blink/renderer/platform/network/parsed_content_header_field_parameters.cc
@@ -66,7 +66,7 @@ ParsedContentHeaderFieldParameters::Parse(HeaderFieldTokenizer tokenizer,
String ParsedContentHeaderFieldParameters::ParameterValueForName(
const String& name) const {
- if (!name.ContainsOnlyASCII())
+ if (!name.ContainsOnlyASCIIOrEmpty())
return String();
String lower_name = name.LowerASCII();
diff --git a/chromium/third_party/blink/renderer/platform/peerconnection/OWNERS b/chromium/third_party/blink/renderer/platform/peerconnection/OWNERS
new file mode 100644
index 00000000000..b3a7338c70a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/peerconnection/OWNERS
@@ -0,0 +1,3 @@
+file://third_party/blink/renderer/modules/peerconnection/OWNERS
+
+# COMPONENT: Blink>WebRTC
diff --git a/chromium/third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h b/chromium/third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h
index b5eecfd80d2..7de4760629d 100644
--- a/chromium/third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h
+++ b/chromium/third_party/blink/renderer/platform/peerconnection/rtc_answer_options_platform.h
@@ -13,17 +13,18 @@ class RTCAnswerOptionsPlatform final
: public GarbageCollected<RTCAnswerOptionsPlatform> {
public:
static RTCAnswerOptionsPlatform* Create(bool voice_activity_detection) {
- return new RTCAnswerOptionsPlatform(voice_activity_detection);
+ return MakeGarbageCollected<RTCAnswerOptionsPlatform>(
+ voice_activity_detection);
}
+ explicit RTCAnswerOptionsPlatform(bool voice_activity_detection)
+ : voice_activity_detection_(voice_activity_detection) {}
+
bool VoiceActivityDetection() const { return voice_activity_detection_; }
void Trace(blink::Visitor* visitor) {}
private:
- explicit RTCAnswerOptionsPlatform(bool voice_activity_detection)
- : voice_activity_detection_(voice_activity_detection) {}
-
bool voice_activity_detection_;
};
diff --git a/chromium/third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h b/chromium/third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h
index 169715664ed..0ee6920b2c9 100644
--- a/chromium/third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h
+++ b/chromium/third_party/blink/renderer/platform/peerconnection/rtc_offer_options_platform.h
@@ -16,19 +16,11 @@ class RTCOfferOptionsPlatform final
int32_t offer_to_receive_audio,
bool voice_activity_detection,
bool ice_restart) {
- return new RTCOfferOptionsPlatform(offer_to_receive_video,
- offer_to_receive_audio,
- voice_activity_detection, ice_restart);
+ return MakeGarbageCollected<RTCOfferOptionsPlatform>(
+ offer_to_receive_video, offer_to_receive_audio,
+ voice_activity_detection, ice_restart);
}
- int32_t OfferToReceiveVideo() const { return offer_to_receive_video_; }
- int32_t OfferToReceiveAudio() const { return offer_to_receive_audio_; }
- bool VoiceActivityDetection() const { return voice_activity_detection_; }
- bool IceRestart() const { return ice_restart_; }
-
- void Trace(blink::Visitor* visitor) {}
-
- private:
RTCOfferOptionsPlatform(int32_t offer_to_receive_video,
int32_t offer_to_receive_audio,
bool voice_activity_detection,
@@ -38,6 +30,14 @@ class RTCOfferOptionsPlatform final
voice_activity_detection_(voice_activity_detection),
ice_restart_(ice_restart) {}
+ int32_t OfferToReceiveVideo() const { return offer_to_receive_video_; }
+ int32_t OfferToReceiveAudio() const { return offer_to_receive_audio_; }
+ bool VoiceActivityDetection() const { return voice_activity_detection_; }
+ bool IceRestart() const { return ice_restart_; }
+
+ void Trace(blink::Visitor* visitor) {}
+
+ private:
int32_t offer_to_receive_video_;
int32_t offer_to_receive_audio_;
bool voice_activity_detection_;
diff --git a/chromium/third_party/blink/renderer/platform/plugins/plugin_data.cc b/chromium/third_party/blink/renderer/platform/plugins/plugin_data.cc
index 8e1cba5dcfe..29721cbbc16 100644
--- a/chromium/third_party/blink/renderer/platform/plugins/plugin_data.cc
+++ b/chromium/third_party/blink/renderer/platform/plugins/plugin_data.cc
@@ -101,13 +101,13 @@ void PluginData::UpdatePluginList(const SecurityOrigin* main_frame_origin) {
Vector<mojom::blink::PluginInfoPtr> plugins;
registry->GetPlugins(false, main_frame_origin_, &plugins);
for (const auto& plugin : plugins) {
- auto* plugin_info =
- new PluginInfo(plugin->name, FilePathToWebString(plugin->filename),
- plugin->description, plugin->background_color);
+ auto* plugin_info = MakeGarbageCollected<PluginInfo>(
+ plugin->name, FilePathToWebString(plugin->filename),
+ plugin->description, plugin->background_color);
plugins_.push_back(plugin_info);
for (const auto& mime : plugin->mime_types) {
- auto* mime_info =
- new MimeClassInfo(mime->mime_type, mime->description, *plugin_info);
+ auto* mime_info = MakeGarbageCollected<MimeClassInfo>(
+ mime->mime_type, mime->description, *plugin_info);
mime_info->extensions_ = mime->file_extensions;
plugin_info->AddMimeType(mime_info);
mimes_.push_back(mime_info);
diff --git a/chromium/third_party/blink/renderer/platform/plugins/plugin_data.h b/chromium/third_party/blink/renderer/platform/plugins/plugin_data.h
index fc395cb63ce..bb48e3956f5 100644
--- a/chromium/third_party/blink/renderer/platform/plugins/plugin_data.h
+++ b/chromium/third_party/blink/renderer/platform/plugins/plugin_data.h
@@ -96,7 +96,9 @@ class PLATFORM_EXPORT PluginData final
public:
void Trace(blink::Visitor*);
- static PluginData* Create() { return new PluginData(); }
+ static PluginData* Create() { return MakeGarbageCollected<PluginData>(); }
+
+ PluginData() = default;
const HeapVector<Member<PluginInfo>>& Plugins() const { return plugins_; }
const HeapVector<Member<MimeClassInfo>>& Mimes() const { return mimes_; }
@@ -112,8 +114,6 @@ class PLATFORM_EXPORT PluginData final
static void RefreshBrowserSidePluginCache();
private:
- PluginData() = default;
-
HeapVector<Member<PluginInfo>> plugins_;
HeapVector<Member<MimeClassInfo>> mimes_;
scoped_refptr<const SecurityOrigin> main_frame_origin_;
diff --git a/chromium/third_party/blink/renderer/platform/png_fuzzer.cc b/chromium/third_party/blink/renderer/platform/png_fuzzer.cc
index 8bd18d633b7..dd872b72359 100644
--- a/chromium/third_party/blink/renderer/platform/png_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/platform/png_fuzzer.cc
@@ -12,11 +12,11 @@
//
// Run with:
// ./out/Fuzz/blink_png_decoder_fuzzer
-// third_party/WebKit/LayoutTests/images/resources/pngfuzz
+// third_party/blink/web_tests/images/resources/pngfuzz
//
// Alternatively, it can be run with:
// ./out/Fuzz/blink_png_decoder_fuzzer ~/another_dir_to_store_corpus
-// third_party/WebKit/LayoutTests/images/resources/pngfuzz
+// third_party/blink/web_tests/images/resources/pngfuzz
//
// so the fuzzer will read both directories passed, but all new generated
// testcases will go into ~/another_dir_to_store_corpus
diff --git a/chromium/third_party/blink/renderer/platform/prerender.h b/chromium/third_party/blink/renderer/platform/prerender.h
index 7cccea02b27..5f0f7fddf0c 100644
--- a/chromium/third_party/blink/renderer/platform/prerender.h
+++ b/chromium/third_party/blink/renderer/platform/prerender.h
@@ -59,9 +59,10 @@ class PLATFORM_EXPORT Prerender final
const KURL& url,
unsigned rel_types,
const Referrer& referrer) {
- return new Prerender(client, url, rel_types, referrer);
+ return MakeGarbageCollected<Prerender>(client, url, rel_types, referrer);
}
+ Prerender(PrerenderClient*, const KURL&, unsigned rel_types, const Referrer&);
~Prerender();
void Trace(blink::Visitor*);
@@ -74,7 +75,9 @@ class PLATFORM_EXPORT Prerender final
const KURL& Url() const { return url_; }
unsigned RelTypes() const { return rel_types_; }
const String& GetReferrer() const { return referrer_.referrer; }
- ReferrerPolicy GetReferrerPolicy() const { return referrer_.referrer_policy; }
+ network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+ return referrer_.referrer_policy;
+ }
void SetExtraData(scoped_refptr<ExtraData> extra_data) {
extra_data_ = std::move(extra_data);
@@ -87,8 +90,6 @@ class PLATFORM_EXPORT Prerender final
void DidSendDOMContentLoadedForPrerender();
private:
- Prerender(PrerenderClient*, const KURL&, unsigned rel_types, const Referrer&);
-
// The embedder's prerendering support holds on to pending Prerender objects;
// those references should not keep the PrerenderClient alive -- if the client
// becomes otherwise unreachable it should be GCed (at which point it will
diff --git a/chromium/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/chromium/third_party/blink/renderer/platform/runtime_enabled_features.json5
index 802f6bd61cb..f4f07c4f51c 100644
--- a/chromium/third_party/blink/renderer/platform/runtime_enabled_features.json5
+++ b/chromium/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -118,6 +118,14 @@
status: "experimental",
},
{
+ name: "BackgroundFetchAccessActiveFetches",
+ status: "experimental",
+ },
+ {
+ name: "BackgroundFetchUploads",
+ status: "experimental",
+ },
+ {
name: "BackgroundVideoTrackOptimization",
status: "stable",
},
@@ -156,7 +164,7 @@
},
{
name: "CacheStorageAddAllRejectsDuplicates",
- status: "experimental",
+ status: "stable",
},
{
name: "CacheStyleSheetWithMediaQueries",
@@ -221,6 +229,10 @@
status: "experimental",
},
{
+ name: "ContactsManager",
+ status: "experimental",
+ },
+ {
name: "ContextMenu",
status: "experimental",
},
@@ -246,14 +258,13 @@
status: "experimental",
},
{
- name: "CSSEnvironmentVariables",
- status: "stable",
- },
- {
name: "CSSFocusVisible",
status: "experimental",
},
{
+ name: "CSSFontFeatureValues"
+ },
+ {
name: "CSSFontSizeAdjust",
status: "experimental",
},
@@ -261,6 +272,9 @@
name: "CSSFragmentIdentifiers"
},
{
+ // This needs to be kept as a runtime flag as long as we need to forcibly
+ // disable it for WebView on Android versions older than P. See
+ // https://crrev.com/f311a84728272e30979432e8474089b3db3c67df
name: "CSSHexAlphaColor",
status: "stable",
},
@@ -286,10 +300,6 @@
status: "experimental",
},
{
- name: "CSSMatches",
- status: "experimental",
- },
- {
name: "CSSOffsetPathRay",
status: "experimental",
},
@@ -302,30 +312,21 @@
status: "experimental",
},
{
- name: "CSSOMSmoothScroll",
- status: "stable",
- },
- // Do not ship CSSPaintAPIArguments without shipping CSSVariables2 first.
- //
- // CSSPaintAPIArguments depends on parts of the the 'CSS Properties and
- // Values API Level 1', specification (section 'Supported syntax strings').
- // That specification is implemented behind the runtime enabled feature
- // CSSVariables2.
- {
name: "CSSPaintAPIArguments",
status: "experimental",
+ depends_on: ["CSSVariables2"],
},
{
name: "CSSPartPseudoElement",
status: "experimental",
},
{
- name: "CSSPseudoIS",
+ name: "CSSPseudoIs",
status: "experimental",
},
{
- name: "CSSScrollSnapPoints",
- status: "stable",
+ name: "CSSPseudoWhere",
+ status: "experimental",
},
{
name: "CSSSnapSize",
@@ -335,6 +336,19 @@
name: "CSSVariables2",
status: "experimental",
},
+ // Support for registered custom properties with <image> syntax.
+ {
+ name: "CSSVariables2ImageValues",
+ status: "test",
+ depends_on: ["CSSVariables2"],
+ },
+ // Support for registered custom properties with <transform-list> and
+ // <transform-function> syntax.
+ {
+ name: "CSSVariables2TransformValues",
+ status: "test",
+ depends_on: ["CSSVariables2"],
+ },
{
name: "CSSViewport",
status: "experimental",
@@ -361,10 +375,6 @@
status: "experimental",
},
{
- name: "DeprecationReporting",
- status: "stable",
- },
- {
name: "DesktopCaptureDisableLocalEchoControl",
status: "experimental",
},
@@ -381,10 +391,6 @@
name: "DisplayLocking",
},
{
- name: "DisplayNoneIFrameCreatesNoLayoutObject",
- status: "stable",
- },
- {
name: "DocumentCookie",
},
{
@@ -398,6 +404,11 @@
name: "EditingNG",
},
{
+ // http://crbug.com/905922
+ name: "ElementInternals",
+ implied_by: ["FormAssociatedCustomElements"],
+ },
+ {
// https://crbug.com/879270
name: "ElementTiming",
status: "test",
@@ -473,11 +484,13 @@
},
{
name: "FeaturePolicyJavaScriptInterface",
+ implied_by: ["ExperimentalProductivityFeatures"],
origin_trial_feature_name: "FeaturePolicyJSAPI",
status: "experimental"
},
{
name: "FeaturePolicyReporting",
+ implied_by: ["ExperimentalProductivityFeatures"],
status: "experimental"
},
{
@@ -487,6 +500,12 @@
name: "FileSystem",
status: "stable",
},
+ // FirstContentfulPaintPlusPlus enables the Largest Text Paint metric, Last
+ // Text Paint metric, Largest Image Paint metric and Last Image Paint
+ // metric. See also: http://bit.ly/fcp_plus_plus
+ {
+ name: "FirstContentfulPaintPlusPlus",
+ },
{
name: "FontCacheScaling",
status: "test",
@@ -504,6 +523,10 @@
name: "ForceTallerSelectPopup",
},
{
+ name: "FormAssociatedCustomElements",
+ status: "test",
+ },
+ {
name: "FormDataEvent",
status: "experimental",
},
@@ -511,10 +534,6 @@
name: "FractionalMouseEvent",
},
{
- name: "FractionalMouseTypePointerEvent",
- status: "stable",
- },
- {
name: "FractionalScrollOffsets",
},
{
@@ -550,7 +569,7 @@
},
{
name: "GetDisplayMedia",
- status: "experimental",
+ status: "stable",
},
{
name: "HeapCompaction",
@@ -566,10 +585,11 @@
{
name: "HeapUnifiedGarbageCollection",
},
- // Only exposed when a translation engine is available
- // and experimental features are enabled.
{
name: "HrefTranslate",
+ depends_on: ["TranslateService"],
+ origin_trial_feature_name: "HrefTranslate",
+ status: "experimental",
},
// https://crbug.com/766694 for testing disabling the feature.
{
@@ -586,8 +606,8 @@
status: "experimental",
},
{
- name: "IdleTimeColdModeSpellChecking",
- status: "stable",
+ name: "IgnoreCrossOriginWindowWhenNamedAccessOnWindow",
+ status: "experimental",
},
{
name: "ImageOrientation",
@@ -615,10 +635,6 @@
name: "IntersectionObserverV2",
},
{
- name: "InterventionReporting",
- status: "stable",
- },
- {
name: "InvisibleDOM",
status: "experimental",
},
@@ -630,12 +646,17 @@
// Tracks "jank" from layout objects changing their visual location
// between animation frames (see crbug.com/581518).
name: "JankTracking",
- implied_by: ["LayoutJankAPI"],
+ implied_by: ["LayoutJankAPI", "JankTrackingSweepLine"],
status: "experimental",
},
{
- name: "KeyboardMap",
- status: "stable",
+ // Modifies JankTracking to use O(n log n) sweep line algorithm for
+ // computing the area of the jank region.
+ name: "JankTrackingSweepLine",
+ },
+ {
+ name: "KeyboardFocusableScrollers",
+ status: "experimental",
},
{
name: "LangAttributeAwareFormControlUI",
@@ -668,6 +689,10 @@
implied_by: ["LayoutNG"],
},
{
+ name: "LayoutViewIsolationNodes",
+ status: "stable",
+ },
+ {
name: "LazyFrameLoading",
},
{
@@ -696,12 +721,11 @@
status:"experimental",
},
{
- name: "MediaCapabilities",
- origin_trial_feature_name: "MediaCapabilities",
- status: "stable",
+ name: "MediaCapabilitiesEncodingInfo",
+ status: "experimental",
},
{
- name: "MediaCapabilitiesEncodingInfo",
+ name: "MediaCapabilitiesEncryptedMedia",
status: "experimental",
},
{
@@ -755,6 +779,9 @@
name: "MediaStreamTrackContentHint",
status: "stable",
},
+ {
+ name: "MergeBlockingNonBlockingPools",
+ },
// This is enabled by default on Windows only. The only part that's
// "experimental" is the support on other platforms.
{
@@ -772,10 +799,6 @@
status: "experimental",
},
{
- name: "ModulePreload",
- status: "stable",
- },
- {
name: "ModuleServiceWorker",
status: "test",
},
@@ -790,18 +813,13 @@
status: "test",
},
{
- name: "NavigatorContentUtils",
- },
- {
- name: "NavigatorDeviceMemory",
- status: "stable",
+ name: "MovementXYInBlink",
},
{
- name: "NestedWorkers",
- status: "stable",
+ name: "NavigatorContentUtils",
},
{
- name: "NetInfoDownlinkHeader",
+ name: "NavigatorDeviceMemory",
status: "stable",
},
{
@@ -809,14 +827,6 @@
status: "stable",
},
{
- name: "NetInfoEffectiveTypeHeader",
- status: "stable",
- },
- {
- name: "NetInfoRttHeader",
- status: "stable",
- },
- {
name: "NetworkService",
},
// Not a web exposed feature, enabled from the command line.
@@ -845,10 +855,6 @@
status: "test",
},
{
- name: "NotificationInlineReplies",
- status: "stable",
- },
- {
name: "Notifications",
status: "stable",
},
@@ -860,7 +866,7 @@
name: "OffMainThreadCSSPaint",
},
{
- name: "OffMainThreadWebSocket",
+ name: "OffMainThreadWorkerScriptFetch",
},
{
name: "OffscreenCanvas",
@@ -903,7 +909,7 @@
implied_by: ["OriginTrialsSampleAPI"],
},
{
- name: "OutOfBlinkCORS",
+ name: "OutOfBlinkCors",
},
{
name: "OverflowIconsForMediaControls",
@@ -923,12 +929,7 @@
// Compute touch action rects in paint instead of ScrollingCoordinator.
{
name: "PaintTouchActionRects",
- },
- // PaintTracking enables the Largest Text Paint metric, Last Text Paint
- // metric, Largest Image Paint metric and Last Image Paint metric.
- // See also: https://docs.google.com/document/d/1DRVd4a2VU8-yyWftgOparZF-sf16daf0vfbsHuz2rws/edit
- {
- name: "PaintTracking",
+ status: "stable",
},
{
name: "PaintUnderInvalidationChecking",
@@ -962,10 +963,6 @@
status: "experimental",
},
{
- name: "PerformanceNavigationTiming2",
- status: "stable",
- },
- {
name: "PermissionDelegation",
status: "test",
},
@@ -999,11 +996,11 @@
status: "test",
},
{
- name: "PostMessageOptions",
- status: "stable",
+ name: "PreciseMemoryInfo",
},
{
- name: "PreciseMemoryInfo",
+ name: "PredictedEvents",
+ status: "experimental",
},
// This feature is deprecated and we are evangelizing affected sites.
// See https://crbug.com/346236 for current status.
@@ -1012,10 +1009,6 @@
status: "stable",
},
{
- name: "PreloadDefaultIsMetadata",
- status: "stable",
- },
- {
name: "PreloadImageSrcSet",
status: "experimental",
},
@@ -1035,9 +1028,6 @@
status: "stable",
},
{
- name: "PWAFullCodeCache"
- },
- {
name: "RasterInducingScroll",
status: "experimental",
},
@@ -1060,21 +1050,28 @@
status: "stable",
},
{
- name: "ReportingObserver",
- implied_by: ["DeprecationReporting", "InterventionReporting"],
- status: "stable",
+ name: "ResourceLoadScheduler",
+ status: "experimental",
},
{
- name: "RequireCSSExtensionForFile",
+ name: "RestrictAppCacheToSecureContexts",
status: "stable",
},
{
- name: "ResourceLoadScheduler",
+ name: "RestrictLazyFrameLoadingToDataSaver",
+ },
+ {
+ name: "RestrictLazyImageLoadingToDataSaver",
+ },
+ {
+ name: "RtcAudioJitterBufferMaxPackets",
+ origin_trial_feature_name: "RtcAudioJitterBufferMaxPackets",
status: "experimental",
},
+ // Enables the use of the RTCDtlsTransport object.
{
- name: "RestrictAppCacheToSecureContexts",
- status: "stable",
+ name: "RTCDtlsTransport",
+ status: "test",
},
// Enables the use of the RTCIceTransport with extensions.
{
@@ -1109,10 +1106,19 @@
{
name: "ScheduledScriptStreaming",
},
+ // WebSpeech API with both speech recognition and synthesis functionality
+ // is not fully enabled on all platforms.
+ {
+ name: "ScriptedSpeechRecognition",
+ status: "stable",
+ },
{
- name: "ScriptedSpeech",
+ name: "ScriptedSpeechSynthesis",
status: "stable",
},
+ {
+ name: "ScriptStreamingOnPreload",
+ },
// Serialize and restore scroll anchors.
{
name: "ScrollAnchorSerialization",
@@ -1153,9 +1159,6 @@
status: "experimental",
},
{
- name: "ServiceWorkerScriptFullCodeCache",
- },
- {
name: "SetRootScroller",
status: "experimental",
},
@@ -1194,12 +1197,13 @@
name: "SlimmingPaintV2",
},
{
- name: "SMIL",
+ name: "SmoothScrollJSIntervention",
status: "stable",
},
+ // When this is enabled (and Spatial Navigation is enabled), overrides of box shadow and outline
+ // on focused elements will be ignored.
{
- name: "SmoothScrollJSIntervention",
- status: "stable",
+ name: "SpatialNavigationForcesOutline",
},
// Used as argument in attribute of stable-release functions/interfaces
// where a runtime-enabled feature name is required for correct IDL syntax.
@@ -1218,6 +1222,10 @@
status: "experimental",
},
{
+ name: "StorageQuotaDetails",
+ status: "experimental",
+ },
+ {
name: "TextUnderlinePositionLeftRight",
status: "stable",
},
@@ -1239,18 +1247,19 @@
origin_trial_feature_name: "ForceTouchEventFeatureDetectionForInspector",
status: "stable",
},
- // This is set conditionally in SetRuntimeFeaturesDefaultsAndUpdateFromArgs
- // and will eventually go away when the touchpad/wheel scroll latching is
- // enabled on all platforms (http://crbug.com/526463).
- {
- name: "TouchpadAndWheelScrollLatching",
- },
// When enabled, tracks the number of times each LayoutBlock
// goes through layout. For testing purposes only.
{
name: "TrackLayoutPassesPerBlock",
},
{
+ name: "TransferableStreams",
+ },
+ // This is conditionally set if the platform supports translation.
+ {
+ name: "TranslateService"
+ },
+ {
name: "TrustedDOMTypes",
status: "experimental",
},
@@ -1268,7 +1277,10 @@
},
{
name: "UserActivationAPI",
- status: "experimental",
+ status: "stable",
+ },
+ {
+ name: "UserActivationSameOriginVisibility",
},
{
name: "UserActivationV2",
@@ -1301,6 +1313,10 @@
status: "experimental",
},
{
+ name: "WasmCodeCache",
+ status: "experimental",
+ },
+ {
name: "WebAnimationsAPI",
status: "experimental",
implied_by: ['AnimationWorklet']
@@ -1352,10 +1368,6 @@
status: "test",
},
{
- name: "WebLocksAPI",
- status: "stable",
- },
- {
name: "WebNFC",
status: "experimental",
},
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/BUILD.gn b/chromium/third_party/blink/renderer/platform/scheduler/BUILD.gn
index 0988dd16323..99ba202179e 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/BUILD.gn
+++ b/chromium/third_party/blink/renderer/platform/scheduler/BUILD.gn
@@ -9,19 +9,11 @@ import("//testing/libfuzzer/fuzzer_test.gni")
blink_platform_sources("scheduler") {
sources = [
- "child/features.cc",
- "child/features.h",
- "child/pollable_thread_safe_flag.cc",
- "child/pollable_thread_safe_flag.h",
- "child/process_state.cc",
- "child/process_state.h",
- "child/single_thread_idle_task_runner.cc",
- "child/webthread_base.cc",
- "child/webthread_impl_for_worker_scheduler.cc",
- "child/webthread_impl_for_worker_scheduler.h",
"common/background_scheduler.cc",
"common/cancelable_closure_holder.cc",
"common/cancelable_closure_holder.h",
+ "common/features.cc",
+ "common/features.h",
"common/frame_or_worker_scheduler.cc",
"common/idle_canceled_delayed_task_sweeper.cc",
"common/idle_canceled_delayed_task_sweeper.h",
@@ -29,12 +21,23 @@ blink_platform_sources("scheduler") {
"common/idle_helper.h",
"common/metrics_helper.cc",
"common/metrics_helper.h",
+ "common/pollable_thread_safe_flag.cc",
+ "common/pollable_thread_safe_flag.h",
+ "common/post_cancellable_task.cc",
+ "common/post_cross_thread_task.cc",
+ "common/process_state.cc",
+ "common/process_state.h",
"common/scheduler_helper.cc",
"common/scheduler_helper.h",
"common/scheduling_lifecycle_state.cc",
"common/simple_thread_scheduler.cc",
"common/simple_thread_scheduler.h",
+ "common/single_thread_idle_task_runner.cc",
+ "common/single_thread_idle_task_runner.h",
"common/thread.cc",
+ "common/thread_cpu_throttler.cc",
+ "common/thread_load_tracker.cc",
+ "common/thread_load_tracker.h",
"common/thread_scheduler.cc",
"common/thread_scheduler_impl.cc",
"common/thread_scheduler_impl.h",
@@ -48,6 +51,8 @@ blink_platform_sources("scheduler") {
"common/throttling/throttled_time_domain.h",
"common/throttling/wake_up_budget_pool.cc",
"common/throttling/wake_up_budget_pool.h",
+ "common/tracing_helper.cc",
+ "common/tracing_helper.h",
"common/unprioritized_resource_loading_task_runner_handle.cc",
"common/unprioritized_resource_loading_task_runner_handle.h",
"common/web_resource_loading_task_runner_handle.cc",
@@ -60,10 +65,13 @@ blink_platform_sources("scheduler") {
"main_thread/frame_origin_type.h",
"main_thread/frame_scheduler_impl.cc",
"main_thread/frame_scheduler_impl.h",
+ "main_thread/frame_status.cc",
"main_thread/frame_task_queue_controller.cc",
"main_thread/frame_task_queue_controller.h",
"main_thread/idle_time_estimator.cc",
"main_thread/idle_time_estimator.h",
+ "main_thread/main_thread.cc",
+ "main_thread/main_thread.h",
"main_thread/main_thread_metrics_helper.cc",
"main_thread/main_thread_metrics_helper.h",
"main_thread/main_thread_scheduler_helper.cc",
@@ -92,30 +100,25 @@ blink_platform_sources("scheduler") {
"main_thread/user_model.cc",
"main_thread/user_model.h",
"main_thread/web_render_widget_scheduling_state.cc",
+ "main_thread/web_scoped_virtual_time_pauser.cc",
+ "public/aggregated_metric_reporter.h",
"public/background_scheduler.h",
"public/frame_or_worker_scheduler.h",
"public/frame_scheduler.h",
+ "public/frame_status.h",
"public/page_lifecycle_state.h",
"public/page_scheduler.h",
+ "public/post_cancellable_task.h",
+ "public/post_cross_thread_task.h",
"public/scheduling_lifecycle_state.h",
"public/thread.h",
+ "public/thread_cpu_throttler.h",
"public/thread_scheduler.h",
"public/worker_scheduler.h",
- "renderer/frame_status.cc",
- "renderer/frame_status.h",
- "renderer/web_scoped_virtual_time_pauser.cc",
- "renderer/webthread_impl_for_renderer_scheduler.cc",
- "renderer/webthread_impl_for_renderer_scheduler.h",
- "util/aggregated_metric_reporter.h",
- "util/thread_cpu_throttler.cc",
- "util/thread_cpu_throttler.h",
- "util/thread_load_tracker.cc",
- "util/thread_load_tracker.h",
- "util/thread_type.h",
- "util/tracing_helper.cc",
- "util/tracing_helper.h",
"worker/compositor_metrics_helper.cc",
"worker/compositor_metrics_helper.h",
+ "worker/compositor_thread.cc",
+ "worker/compositor_thread.h",
"worker/compositor_thread_scheduler.cc",
"worker/compositor_thread_scheduler.h",
"worker/non_main_thread_scheduler_helper.cc",
@@ -129,6 +132,8 @@ blink_platform_sources("scheduler") {
"worker/worker_scheduler.cc",
"worker/worker_scheduler_proxy.cc",
"worker/worker_scheduler_proxy.h",
+ "worker/worker_thread.cc",
+ "worker/worker_thread.h",
"worker/worker_thread_scheduler.cc",
"worker/worker_thread_scheduler.h",
]
@@ -151,12 +156,12 @@ jumbo_source_set("test_support") {
sources = [
"test/fake_frame_scheduler.h",
"test/fake_page_scheduler.h",
- "test/fake_renderer_scheduler.cc",
"test/fake_task_runner.cc",
"test/fake_task_runner.h",
"test/renderer_scheduler_test_support.cc",
"test/test_queueing_time_estimator_client.cc",
"test/test_queueing_time_estimator_client.h",
+ "test/web_fake_thread_scheduler.cc",
]
deps = [
@@ -173,14 +178,16 @@ jumbo_source_set("unit_tests") {
testonly = true
sources = [
- "child/webthread_impl_for_worker_scheduler_unittest.cc",
"common/background_scheduler_unittest.cc",
"common/idle_canceled_delayed_task_sweeper_unittest.cc",
"common/idle_helper_unittest.cc",
"common/metrics_helper_unittest.cc",
+ "common/post_cancellable_task_unittest.cc",
"common/scheduler_helper_unittest.cc",
+ "common/thread_load_tracker_unittest.cc",
"common/throttling/budget_pool_unittest.cc",
"common/throttling/task_queue_throttler_unittest.cc",
+ "common/tracing_helper_unittest.cc",
"main_thread/auto_advancing_virtual_time_domain_unittest.cc",
"main_thread/deadline_task_runner_unittest.cc",
"main_thread/frame_scheduler_impl_unittest.cc",
@@ -188,18 +195,17 @@ jumbo_source_set("unit_tests") {
"main_thread/idle_time_estimator_unittest.cc",
"main_thread/main_thread_metrics_helper_unittest.cc",
"main_thread/main_thread_scheduler_impl_unittest.cc",
+ "main_thread/main_thread_unittest.cc",
"main_thread/page_scheduler_impl_unittest.cc",
"main_thread/queueing_time_estimator_unittest.cc",
"main_thread/render_widget_signals_unittest.cc",
"main_thread/task_cost_estimator_unittest.cc",
"main_thread/user_model_unittest.cc",
- "renderer/webthread_impl_for_renderer_scheduler_unittest.cc",
- "util/thread_load_tracker_unittest.cc",
- "util/tracing_helper_unittest.cc",
"worker/compositor_thread_scheduler_unittest.cc",
"worker/worker_scheduler_proxy_unittest.cc",
"worker/worker_scheduler_unittest.cc",
"worker/worker_thread_scheduler_unittest.cc",
+ "worker/worker_thread_unittest.cc",
]
deps = [
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/DEPS b/chromium/third_party/blink/renderer/platform/scheduler/child/DEPS
deleted file mode 100644
index f3b7e66a005..00000000000
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/DEPS
+++ /dev/null
@@ -1,4 +0,0 @@
-include_rules = [
- "+third_party/blink/public/platform/scheduler/base",
- "+third_party/blink/renderer/platform/scheduler/base",
-]
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/OWNERS b/chromium/third_party/blink/renderer/platform/scheduler/child/OWNERS
deleted file mode 100644
index 8423b497efb..00000000000
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/OWNERS
+++ /dev/null
@@ -1,7 +0,0 @@
-altimin@chromium.org
-alexclarke@chromium.org
-rmcilroy@chromium.org
-skyostil@chromium.org
-
-# TEAM: scheduler-dev@chromium.org
-# COMPONENT: Blink>Scheduling
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_base.cc b/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_base.cc
deleted file mode 100644
index f83120a1b34..00000000000
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_base.cc
+++ /dev/null
@@ -1,125 +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.
-
-// An implementation of blink::Thread in terms of base::MessageLoop and
-// base::Thread
-
-#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
-
-#include <memory>
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/location.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/message_loop_current.h"
-#include "base/pending_task.h"
-#include "base/threading/platform_thread.h"
-#include "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h"
-
-namespace blink {
-namespace scheduler {
-
-class WebThreadBase::TaskObserverAdapter
- : public base::MessageLoop::TaskObserver {
- public:
- explicit TaskObserverAdapter(Thread::TaskObserver* observer)
- : observer_(observer) {}
-
- void WillProcessTask(const base::PendingTask& pending_task) override {
- observer_->WillProcessTask();
- }
-
- void DidProcessTask(const base::PendingTask& pending_task) override {
- observer_->DidProcessTask();
- }
-
- private:
- Thread::TaskObserver* observer_;
-};
-
-WebThreadBase::WebThreadBase() = default;
-
-WebThreadBase::~WebThreadBase() {
- for (auto& observer_entry : task_observer_map_) {
- delete observer_entry.second;
- }
-}
-
-void WebThreadBase::AddTaskObserver(TaskObserver* observer) {
- CHECK(IsCurrentThread());
- std::pair<TaskObserverMap::iterator, bool> result =
- task_observer_map_.insert(std::make_pair(observer, nullptr));
- if (result.second)
- result.first->second = new TaskObserverAdapter(observer);
- AddTaskObserverInternal(result.first->second);
-}
-
-void WebThreadBase::RemoveTaskObserver(TaskObserver* observer) {
- CHECK(IsCurrentThread());
- TaskObserverMap::iterator iter = task_observer_map_.find(observer);
- if (iter == task_observer_map_.end())
- return;
- RemoveTaskObserverInternal(iter->second);
- delete iter->second;
- task_observer_map_.erase(iter);
-}
-
-void WebThreadBase::AddTaskTimeObserver(
- base::sequence_manager::TaskTimeObserver* task_time_observer) {
- AddTaskTimeObserverInternal(task_time_observer);
-}
-
-void WebThreadBase::RemoveTaskTimeObserver(
- base::sequence_manager::TaskTimeObserver* task_time_observer) {
- RemoveTaskTimeObserverInternal(task_time_observer);
-}
-
-void WebThreadBase::AddTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) {
- base::MessageLoopCurrent::Get()->AddTaskObserver(observer);
-}
-
-void WebThreadBase::RemoveTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) {
- base::MessageLoopCurrent::Get()->RemoveTaskObserver(observer);
-}
-
-bool WebThreadBase::IsCurrentThread() const {
- return GetTaskRunner()->BelongsToCurrentThread();
-}
-
-namespace {
-
-class WebThreadForCompositor : public WebThreadImplForWorkerScheduler {
- public:
- explicit WebThreadForCompositor(const ThreadCreationParams& params)
- : WebThreadImplForWorkerScheduler(params) {}
- ~WebThreadForCompositor() override = default;
-
- private:
- // WebThreadImplForWorkerScheduler:
- std::unique_ptr<blink::scheduler::NonMainThreadSchedulerImpl>
- CreateNonMainThreadScheduler() override {
- return std::make_unique<CompositorThreadScheduler>(
- base::sequence_manager::CreateSequenceManagerOnCurrentThread());
- }
-
- DISALLOW_COPY_AND_ASSIGN(WebThreadForCompositor);
-};
-
-} // namespace
-
-std::unique_ptr<WebThreadBase> WebThreadBase::CreateWorkerThread(
- const ThreadCreationParams& params) {
- return std::make_unique<WebThreadImplForWorkerScheduler>(params);
-}
-
-std::unique_ptr<WebThreadBase> WebThreadBase::CreateCompositorThread(
- const ThreadCreationParams& params) {
- return std::make_unique<WebThreadForCompositor>(params);
-}
-
-} // namespace scheduler
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/DEPS b/chromium/third_party/blink/renderer/platform/scheduler/common/DEPS
new file mode 100644
index 00000000000..ad2eb03460d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/DEPS
@@ -0,0 +1,7 @@
+specific_include_rules = {
+ "scheduler_helper.cc": [
+ "+base/task/sequence_manager/sequence_manager_impl.h",
+ ],
+}
+
+
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler.cc
index dbf59fae8f7..481d2df4223 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler.cc
@@ -9,14 +9,15 @@
namespace blink {
-void BackgroundScheduler::PostOnBackgroundThread(const base::Location& location,
- CrossThreadClosure closure) {
+void background_scheduler::PostOnBackgroundThread(
+ const base::Location& location,
+ CrossThreadClosure closure) {
PostOnBackgroundThreadWithTraits(
location, {base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
std::move(closure));
}
-void BackgroundScheduler::PostOnBackgroundThreadWithTraits(
+void background_scheduler::PostOnBackgroundThreadWithTraits(
const base::Location& location,
const base::TaskTraits& traits,
CrossThreadClosure closure) {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler_unittest.cc
index 66710ec5290..bcd2372cda4 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/background_scheduler_unittest.cc
@@ -24,7 +24,7 @@ void PingPongTask(WaitableEvent* done_event) {
TEST(BackgroundSchedulerTest, RunOnBackgroundThread) {
base::test::ScopedTaskEnvironment scoped_task_environment;
std::unique_ptr<WaitableEvent> done_event = std::make_unique<WaitableEvent>();
- BackgroundScheduler::PostOnBackgroundThread(
+ background_scheduler::PostOnBackgroundThread(
FROM_HERE,
CrossThreadBind(&PingPongTask, CrossThreadUnretained(done_event.get())));
// Test passes by not hanging on the following wait().
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/features.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/features.cc
index e16aa5d850d..b49ffd20c5b 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/features.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/features.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 "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/features.h b/chromium/third_party/blink/renderer/platform/scheduler/common/features.h
index 79e1b401bba..dd978f3a571 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/features.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/features.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_FEATURES_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_FEATURES_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_FEATURES_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_FEATURES_H_
#include "base/feature_list.h"
#include "third_party/blink/renderer/platform/platform_export.h"
@@ -162,4 +162,4 @@ const base::Feature kDisableTouchstartInputHeuristics{
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_FEATURES_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_FEATURES_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h
index def2193665e..8bbe9f69067 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h
@@ -7,8 +7,8 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
-#include "third_party/blink/public/platform/scheduler/single_thread_idle_task_runner.h"
#include "third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.cc
index c24db09ca25..afaa48d47ec 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.cc
@@ -9,7 +9,7 @@
#include "base/task/sequence_manager/time_domain.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.h b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.h
index a7f5f49a6ba..15fcdfc5203 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper.h
@@ -8,10 +8,10 @@
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
-#include "third_party/blink/public/platform/scheduler/single_thread_idle_task_runner.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/scheduler/common/cancelable_closure_holder.h"
#include "third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper_unittest.cc
index 8a8c1dc9024..a1e8fc41b11 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/idle_helper_unittest.cc
@@ -185,7 +185,7 @@ class BaseIdleHelperTest : public testing::Test {
// It's okay to use |test_task_runner_| just as a mock clock because
// it isn't bound to thread and all tasks will go through a MessageLoop.
sequence_manager = base::sequence_manager::SequenceManagerForTest::Create(
- message_loop_.get(), message_loop_->task_runner(),
+ message_loop_->GetMessageLoopBase(), message_loop_->task_runner(),
test_task_runner_->GetMockTickClock());
}
sequence_manager_ = sequence_manager.get();
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc
index a06c71d0f16..2d5704459a0 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/platform/scheduler/common/metrics_helper.h"
-#include "third_party/blink/renderer/platform/scheduler/child/process_state.h"
+#include "third_party/blink/renderer/platform/scheduler/common/process_state.h"
namespace blink {
namespace scheduler {
@@ -28,7 +28,7 @@ scheduling_metrics::ThreadType ConvertBlinkThreadType(
return scheduling_metrics::ThreadType::kRendererDedicatedWorkerThread;
case WebThreadType::kServiceWorkerThread:
return scheduling_metrics::ThreadType::kRendererServiceWorkerThread;
- case WebThreadType::kAnimationWorkletThread:
+ case WebThreadType::kAnimationAndPaintWorkletThread:
case WebThreadType::kAudioWorkletThread:
case WebThreadType::kDatabaseThread:
case WebThreadType::kFileThread:
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.cc
index 409d276a10c..d26f6d7ac75 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.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 "third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.h"
+#include "third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.h"
PollableThreadSafeFlag::PollableThreadSafeFlag(base::Lock* write_lock_)
: flag_(false), write_lock_(write_lock_) {}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.h b/chromium/third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.h
index d3e4a531858..5a8d1b15057 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_POLLABLE_THREAD_SAFE_FLAG_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_POLLABLE_THREAD_SAFE_FLAG_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_POLLABLE_THREAD_SAFE_FLAG_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_POLLABLE_THREAD_SAFE_FLAG_H_
#include "base/atomicops.h"
#include "base/macros.h"
@@ -33,4 +33,4 @@ class PollableThreadSafeFlag {
DISALLOW_COPY_AND_ASSIGN(PollableThreadSafeFlag);
};
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_POLLABLE_THREAD_SAFE_FLAG_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_POLLABLE_THREAD_SAFE_FLAG_H_
diff --git a/chromium/third_party/blink/renderer/platform/web_task_runner.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/post_cancellable_task.cc
index 261a0bc03dc..b32596e4550 100644
--- a/chromium/third_party/blink/renderer/platform/web_task_runner.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/post_cancellable_task.cc
@@ -1,22 +1,15 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
+// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
-#include "base/bind_helpers.h"
-#include "base/single_thread_task_runner.h"
+#include "base/memory/weak_ptr.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
+#include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h"
namespace blink {
-namespace {
-
-void RunCrossThreadClosure(CrossThreadClosure task) {
- std::move(task).Run();
-}
-
-} // namespace
-
class TaskHandle::Runner : public WTF::ThreadSafeRefCounted<Runner> {
public:
explicit Runner(base::OnceClosure task)
@@ -124,26 +117,6 @@ TaskHandle::TaskHandle(scoped_refptr<Runner> runner)
DCHECK(runner_);
}
-// Use a custom function for base::Bind instead of WTF::Bind to
-// avoid copying the closure later in the call chain. Copying the bound state
-// can lead to data races with ref counted objects like StringImpl. See
-// crbug.com/679915 for more details.
-void PostCrossThreadTask(base::SequencedTaskRunner& task_runner,
- const base::Location& location,
- CrossThreadClosure task) {
- task_runner.PostDelayedTask(
- location, base::BindOnce(&RunCrossThreadClosure, std::move(task)),
- base::TimeDelta());
-}
-
-void PostDelayedCrossThreadTask(base::SequencedTaskRunner& task_runner,
- const base::Location& location,
- CrossThreadClosure task,
- TimeDelta delay) {
- task_runner.PostDelayedTask(
- location, base::BindOnce(&RunCrossThreadClosure, std::move(task)), delay);
-}
-
TaskHandle PostCancellableTask(base::SequencedTaskRunner& task_runner,
const base::Location& location,
base::OnceClosure task) {
@@ -159,7 +132,7 @@ TaskHandle PostCancellableTask(base::SequencedTaskRunner& task_runner,
TaskHandle PostDelayedCancellableTask(base::SequencedTaskRunner& task_runner,
const base::Location& location,
base::OnceClosure task,
- TimeDelta delay) {
+ base::TimeDelta delay) {
DCHECK(task_runner.RunsTasksInCurrentSequence());
scoped_refptr<TaskHandle::Runner> runner =
base::AdoptRef(new TaskHandle::Runner(std::move(task)));
diff --git a/chromium/third_party/blink/renderer/platform/web_task_runner_test.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/post_cancellable_task_unittest.cc
index c20c21dc9cf..f9ad74fcd9c 100644
--- a/chromium/third_party/blink/renderer/platform/web_task_runner_test.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/post_cancellable_task_unittest.cc
@@ -2,10 +2,12 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
+#include "base/memory/weak_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/scheduler/test/fake_task_runner.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
namespace {
@@ -54,7 +56,7 @@ TEST(WebTaskRunnerTest, PostCancellableTaskTest) {
count = 0;
handle = PostDelayedCancellableTask(
*task_runner, FROM_HERE, WTF::Bind(&Increment, WTF::Unretained(&count)),
- TimeDelta::FromMilliseconds(1));
+ base::TimeDelta::FromMilliseconds(1));
EXPECT_EQ(0, count);
EXPECT_TRUE(handle.IsActive());
task_runner->RunUntilIdle();
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/post_cross_thread_task.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/post_cross_thread_task.cc
new file mode 100644
index 00000000000..bf8827b0656
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/post_cross_thread_task.cc
@@ -0,0 +1,41 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
+
+#include "base/bind.h"
+
+namespace blink {
+
+namespace {
+
+void RunCrossThreadClosure(WTF::CrossThreadClosure task) {
+ std::move(task).Run();
+}
+
+} // namespace
+
+// In those functions, we must use plain base::BindOnce() because:
+//
+// * WTF::Bind() does thread checks which isn't compatible with our use case.
+// * CrossThreadBind() returns WTF::CrossThreadFunction which isn't
+// convertible to base::OnceClosure (this is actually a chicken-and-egg;
+// we need base::BindOnce() as an escape hatch).
+void PostCrossThreadTask(base::SequencedTaskRunner& task_runner,
+ const base::Location& location,
+ WTF::CrossThreadClosure task) {
+ task_runner.PostDelayedTask(
+ location, base::BindOnce(&RunCrossThreadClosure, std::move(task)),
+ base::TimeDelta());
+}
+
+void PostDelayedCrossThreadTask(base::SequencedTaskRunner& task_runner,
+ const base::Location& location,
+ WTF::CrossThreadClosure task,
+ base::TimeDelta delay) {
+ task_runner.PostDelayedTask(
+ location, base::BindOnce(&RunCrossThreadClosure, std::move(task)), delay);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/process_state.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/process_state.cc
index e62069f67de..a769976fabc 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/process_state.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/process_state.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 "third_party/blink/renderer/platform/scheduler/child/process_state.h"
+#include "third_party/blink/renderer/platform/scheduler/common/process_state.h"
#include "base/lazy_instance.h"
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/process_state.h b/chromium/third_party/blink/renderer/platform/scheduler/common/process_state.h
index 37d0fbcc5fd..4a3a072b85e 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/process_state.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/process_state.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_PROCESS_STATE_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_PROCESS_STATE_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_PROCESS_STATE_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_PROCESS_STATE_H_
#include <atomic>
@@ -26,4 +26,4 @@ struct PLATFORM_EXPORT ProcessState {
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_PROCESS_STATE_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_PROCESS_STATE_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.cc
index ae458f1a2e1..8e297487d12 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.cc
@@ -6,10 +6,11 @@
#include <utility>
+#include "base/task/sequence_manager/sequence_manager_impl.h"
#include "base/task/sequence_manager/task_queue.h"
#include "base/time/default_tick_clock.h"
#include "base/trace_event/trace_event.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
namespace blink {
namespace scheduler {
@@ -55,7 +56,7 @@ SchedulerHelper::DefaultTaskRunner() {
return default_task_runner_;
}
-void SchedulerHelper::SetWorkBatchSizeForTesting(size_t work_batch_size) {
+void SchedulerHelper::SetWorkBatchSizeForTesting(int work_batch_size) {
CheckOnValidThread();
DCHECK(sequence_manager_.get());
sequence_manager_->SetWorkBatchSize(work_batch_size);
@@ -70,15 +71,21 @@ bool SchedulerHelper::GetAndClearSystemIsQuiescentBit() {
void SchedulerHelper::AddTaskObserver(
base::MessageLoop::TaskObserver* task_observer) {
CheckOnValidThread();
- if (sequence_manager_)
- sequence_manager_->AddTaskObserver(task_observer);
+ if (sequence_manager_) {
+ static_cast<base::sequence_manager::internal::SequenceManagerImpl*>(
+ sequence_manager_.get())
+ ->AddTaskObserver(task_observer);
+ }
}
void SchedulerHelper::RemoveTaskObserver(
base::MessageLoop::TaskObserver* task_observer) {
CheckOnValidThread();
- if (sequence_manager_)
- sequence_manager_->RemoveTaskObserver(task_observer);
+ if (sequence_manager_) {
+ static_cast<base::sequence_manager::internal::SequenceManagerImpl*>(
+ sequence_manager_.get())
+ ->RemoveTaskObserver(task_observer);
+ }
}
void SchedulerHelper::AddTaskTimeObserver(
@@ -148,7 +155,11 @@ base::TimeTicks SchedulerHelper::NowTicks() const {
}
void SchedulerHelper::SetTimerSlack(base::TimerSlack timer_slack) {
- sequence_manager_->SetTimerSlack(timer_slack);
+ if (sequence_manager_) {
+ static_cast<base::sequence_manager::internal::SequenceManagerImpl*>(
+ sequence_manager_.get())
+ ->SetTimerSlack(timer_slack);
+ }
}
double SchedulerHelper::GetSamplingRateForRecordingCPUTime() const {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h b/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h
index 577f1ed8f85..065fce39916 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h
@@ -99,7 +99,7 @@ class PLATFORM_EXPORT SchedulerHelper
bool HasCPUTimingForEachTask() const;
// Test helpers.
- void SetWorkBatchSizeForTesting(size_t work_batch_size);
+ void SetWorkBatchSizeForTesting(int work_batch_size);
protected:
void InitDefaultQueues(
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/single_thread_idle_task_runner.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.cc
index fae4dab6c0a..1f2ce23d62f 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/single_thread_idle_task_runner.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_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 "third_party/blink/public/platform/scheduler/single_thread_idle_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h b/chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h
new file mode 100644
index 00000000000..045e7f6f3a3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h
@@ -0,0 +1,119 @@
+// 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 THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_SINGLE_THREAD_IDLE_TASK_RUNNER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_SINGLE_THREAD_IDLE_TASK_RUNNER_H_
+
+#include <map>
+
+#include "base/bind.h"
+#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/time/time.h"
+#include "base/trace_event/trace_event.h"
+#include "third_party/blink/public/platform/web_common.h"
+
+namespace base {
+namespace trace_event {
+class BlameContext;
+}
+} // namespace base
+
+namespace blink {
+namespace scheduler {
+class IdleHelper;
+
+// A SingleThreadIdleTaskRunner is a task runner for running idle tasks. Idle
+// tasks have an unbound argument which is bound to a deadline
+// (in base::TimeTicks) when they are run. The idle task is expected to
+// complete by this deadline.
+//
+// This class uses base::RefCountedThreadSafe instead of WTF::ThreadSafe-
+// RefCounted, which is against the general rule for code in platform/
+// (see audit_non_blink_usage.py). This is because SingleThreadIdleTaskRunner
+// is held by MainThreadSchedulerImpl and MainThreadSchedulerImpl is created
+// before WTF (and PartitionAlloc) is initialized.
+// TODO(yutak): Fix this.
+class SingleThreadIdleTaskRunner
+ : public base::RefCountedThreadSafe<SingleThreadIdleTaskRunner> {
+ public:
+ using IdleTask = base::OnceCallback<void(base::TimeTicks)>;
+
+ // Used to request idle task deadlines and signal posting of idle tasks.
+ class BLINK_PLATFORM_EXPORT Delegate {
+ public:
+ Delegate();
+ virtual ~Delegate();
+
+ // Signals that an idle task has been posted. This will be called on the
+ // posting thread, which may not be the same thread as the
+ // SingleThreadIdleTaskRunner runs on.
+ virtual void OnIdleTaskPosted() = 0;
+
+ // Signals that a new idle task is about to be run and returns the deadline
+ // for this idle task.
+ virtual base::TimeTicks WillProcessIdleTask() = 0;
+
+ // Signals that an idle task has finished being run.
+ virtual void DidProcessIdleTask() = 0;
+
+ // Returns the current time.
+ virtual base::TimeTicks NowTicks() = 0;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(Delegate);
+ };
+
+ // NOTE Category strings must have application lifetime (statics or
+ // literals). They may not include " chars.
+ SingleThreadIdleTaskRunner(
+ scoped_refptr<base::SingleThreadTaskRunner> idle_priority_task_runner,
+ Delegate* delegate);
+
+ virtual void PostIdleTask(const base::Location& from_here,
+ IdleTask idle_task);
+
+ // |idle_task| is eligible to run after the next time an idle period starts
+ // after |delay|. Note this has after wake-up semantics, i.e. unless
+ // something else wakes the CPU up, this won't run.
+ virtual void PostDelayedIdleTask(const base::Location& from_here,
+ const base::TimeDelta delay,
+ IdleTask idle_task);
+
+ virtual void PostNonNestableIdleTask(const base::Location& from_here,
+ IdleTask idle_task);
+
+ bool RunsTasksInCurrentSequence() const;
+
+ void SetBlameContext(base::trace_event::BlameContext* blame_context);
+
+ protected:
+ virtual ~SingleThreadIdleTaskRunner();
+
+ private:
+ friend class base::RefCountedThreadSafe<SingleThreadIdleTaskRunner>;
+ friend class IdleHelper;
+
+ void RunTask(IdleTask idle_task);
+
+ void EnqueueReadyDelayedIdleTasks();
+
+ using DelayedIdleTask = std::pair<const base::Location, base::OnceClosure>;
+
+ scoped_refptr<base::SingleThreadTaskRunner> idle_priority_task_runner_;
+ std::multimap<base::TimeTicks, DelayedIdleTask> delayed_idle_tasks_;
+ Delegate* delegate_; // NOT OWNED
+ base::trace_event::BlameContext* blame_context_; // Not owned.
+ base::WeakPtr<SingleThreadIdleTaskRunner> weak_scheduler_ptr_;
+ base::WeakPtrFactory<SingleThreadIdleTaskRunner> weak_factory_;
+ DISALLOW_COPY_AND_ASSIGN(SingleThreadIdleTaskRunner);
+};
+
+} // namespace scheduler
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_SINGLE_THREAD_IDLE_TASK_RUNNER_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/thread.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/thread.cc
index bb3b7ad1ef6..0c92352c0f7 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/thread.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread.cc
@@ -5,8 +5,17 @@
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "base/single_thread_task_runner.h"
+#include "base/synchronization/waitable_event.h"
#include "build/build_config.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/compositor_thread.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
+#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
#if defined(OS_WIN)
#include <windows.h>
@@ -16,6 +25,46 @@
namespace blink {
+namespace {
+
+// Thread-local storage for "blink::Thread"s.
+Thread*& ThreadTLSSlot() {
+ DEFINE_THREAD_SAFE_STATIC_LOCAL(WTF::ThreadSpecific<Thread*>, thread_tls_slot,
+ ());
+ return *thread_tls_slot;
+}
+
+// Update the threads TLS on the newly created thread.
+void UpdateThreadTLS(Thread* thread, base::WaitableEvent* event) {
+ ThreadTLSSlot() = thread;
+ event->Signal();
+}
+
+// Post a task to register |thread| to the TLS, and wait until it gets actually
+// registered. This is called on a thread that created |thread| (not on
+// |thread|.)
+void UpdateThreadTLSAndWait(Thread* thread) {
+ base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
+ base::WaitableEvent::InitialState::NOT_SIGNALED);
+ PostCrossThreadTask(
+ *thread->GetTaskRunner(), FROM_HERE,
+ CrossThreadBind(&UpdateThreadTLS, WTF::CrossThreadUnretained(thread),
+ WTF::CrossThreadUnretained(&event)));
+ event.Wait();
+}
+
+std::unique_ptr<Thread>& GetMainThread() {
+ DEFINE_STATIC_LOCAL(std::unique_ptr<Thread>, main_thread, ());
+ return main_thread;
+}
+
+std::unique_ptr<Thread>& GetCompositorThread() {
+ DEFINE_STATIC_LOCAL(std::unique_ptr<Thread>, compositor_thread, ());
+ return compositor_thread;
+}
+
+} // namespace
+
ThreadCreationParams::ThreadCreationParams(WebThreadType thread_type)
: thread_type(thread_type),
name(GetNameForThreadType(thread_type)),
@@ -33,6 +82,76 @@ ThreadCreationParams& ThreadCreationParams::SetFrameOrWorkerScheduler(
return *this;
}
+std::unique_ptr<Thread> Thread::CreateThread(
+ const ThreadCreationParams& params) {
+ auto thread = std::make_unique<scheduler::WorkerThread>(params);
+ thread->Init();
+ UpdateThreadTLSAndWait(thread.get());
+ return std::move(thread);
+}
+
+std::unique_ptr<Thread> Thread::CreateWebAudioThread() {
+ ThreadCreationParams params(WebThreadType::kWebAudioThread);
+ // WebAudio uses a thread with |DISPLAY| priority to avoid glitch when the
+ // system is under the high pressure. Note that the main browser thread also
+ // runs with same priority. (see: crbug.com/734539)
+ params.thread_options.priority = base::ThreadPriority::DISPLAY;
+ return CreateThread(params);
+}
+
+void Thread::CreateAndSetCompositorThread() {
+ DCHECK(!GetCompositorThread());
+
+ ThreadCreationParams params(WebThreadType::kCompositorThread);
+#if defined(OS_ANDROID)
+ params.thread_options.priority = base::ThreadPriority::DISPLAY;
+#endif
+ auto compositor_thread =
+ std::make_unique<scheduler::CompositorThread>(params);
+ compositor_thread->Init();
+ UpdateThreadTLSAndWait(compositor_thread.get());
+ GetCompositorThread() = std::move(compositor_thread);
+ Platform::Current()->SetDisplayThreadPriority(
+ GetCompositorThread()->ThreadId());
+}
+
+Thread* Thread::Current() {
+ return ThreadTLSSlot();
+}
+
+Thread* Thread::MainThread() {
+ return GetMainThread().get();
+}
+
+Thread* Thread::CompositorThread() {
+ return GetCompositorThread().get();
+}
+
+std::unique_ptr<Thread> Thread::SetMainThread(
+ std::unique_ptr<Thread> main_thread) {
+ ThreadTLSSlot() = main_thread.get();
+ std::swap(GetMainThread(), main_thread);
+ return main_thread;
+}
+
+Thread::Thread() = default;
+
+Thread::~Thread() = default;
+
+bool Thread::IsCurrentThread() const {
+ return ThreadTLSSlot() == this;
+}
+
+void Thread::AddTaskObserver(TaskObserver* task_observer) {
+ CHECK(IsCurrentThread());
+ Scheduler()->AddTaskObserver(task_observer);
+}
+
+void Thread::RemoveTaskObserver(TaskObserver* task_observer) {
+ CHECK(IsCurrentThread());
+ Scheduler()->RemoveTaskObserver(task_observer);
+}
+
#if defined(OS_WIN)
static_assert(sizeof(blink::PlatformThreadId) >= sizeof(DWORD),
"size of platform thread id is too small");
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_cpu_throttler.cc
index a38dd349293..6c2458e265c 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_cpu_throttler.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 "third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread_cpu_throttler.h"
#include "base/atomicops.h"
#include "base/macros.h"
@@ -79,7 +79,7 @@ ThreadCPUThrottler::ThrottlingThread::ThrottlingThread(double rate)
SetThrottlingRate(rate);
CHECK_EQ(base::subtle::NoBarrier_AtomicExchange(&thread_exists_, 1), 0);
Start();
-}
+} // namespace scheduler
ThreadCPUThrottler::ThrottlingThread::~ThrottlingThread() {
Stop();
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.cc
index f84529ea118..54dc1b56928 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.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 "third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h"
+#include "third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h"
#include <algorithm>
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h
index 1cd7ee89188..35014aaa40d 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_THREAD_LOAD_TRACKER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_THREAD_LOAD_TRACKER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
#include "base/callback.h"
#include "base/macros.h"
@@ -70,4 +70,4 @@ class PLATFORM_EXPORT ThreadLoadTracker {
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_THREAD_LOAD_TRACKER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker_unittest.cc
index 7f015763b7f..48443c2b165 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_load_tracker_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_load_tracker_unittest.cc
@@ -1,4 +1,4 @@
-#include "third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h"
+#include "third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h"
#include "base/bind.h"
#include "testing/gmock/include/gmock/gmock.h"
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler.cc
index 67f51a1554d..92e2e58a2b8 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler.cc
@@ -4,12 +4,12 @@
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
namespace blink {
ThreadScheduler* ThreadScheduler::Current() {
- return Platform::Current()->CurrentThread()->Scheduler();
+ return Thread::Current()->Scheduler();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h
index 270cbdfbc47..9b36e583382 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h
@@ -11,6 +11,7 @@
#include "base/single_thread_task_runner.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
namespace base {
@@ -36,6 +37,11 @@ class PLATFORM_EXPORT ThreadSchedulerImpl : public ThreadScheduler,
// to hide the base classes' ones.
using RendererPauseHandle = WebThreadScheduler::RendererPauseHandle;
+ // Returns the idle task runner. Tasks posted to this runner may be reordered
+ // relative to other task types and may be starved for an arbitrarily long
+ // time if no idle time is available.
+ virtual scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() = 0;
+
virtual scoped_refptr<base::SingleThreadTaskRunner> ControlTaskRunner() = 0;
virtual void RegisterTimeDomain(
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/cpu_time_budget_pool.h b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/cpu_time_budget_pool.h
index db1571e9c34..586fe5f4b26 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/cpu_time_budget_pool.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/cpu_time_budget_pool.h
@@ -10,7 +10,7 @@
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/optional.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
namespace blink {
namespace scheduler {
@@ -115,7 +115,7 @@ class PLATFORM_EXPORT CPUTimeBudgetPool : public BudgetPool {
// See CPUTimeBudgetPool::SetMinBudgetLevelToRun.
base::TimeDelta min_budget_level_to_run_;
- TraceableCounter<base::TimeDelta, kTracingCategoryNameInfo>
+ TraceableCounter<base::TimeDelta, TracingCategoryName::kInfo>
current_budget_level_;
base::TimeTicks last_checkpoint_;
double cpu_percentage_;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.cc
index 3c8a80b6a37..f9f9684e0dd 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.cc
@@ -444,7 +444,7 @@ void TaskQueueThrottler::AsValueInto(base::trace_event::TracedValue* state,
for (const auto& map_entry : queue_details_) {
state->BeginDictionaryWithCopiedName(PointerToString(map_entry.first));
state->SetInteger("throttling_ref_count",
- map_entry.second.throttling_ref_count);
+ static_cast<int>(map_entry.second.throttling_ref_count));
state->EndDictionary();
}
state->EndDictionary();
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h
index 42269fa5dd7..b29f409bb71 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h
@@ -20,7 +20,7 @@
#include "third_party/blink/renderer/platform/scheduler/common/throttling/budget_pool.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/cpu_time_budget_pool.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/wake_up_budget_pool.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
namespace base {
namespace trace_event {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.cc
index ca69a886b36..828a6d36710 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.cc
@@ -54,5 +54,10 @@ base::Optional<base::TimeDelta> ThrottledTimeDomain::DelayTillNextTask(
return base::nullopt;
}
+bool ThrottledTimeDomain::MaybeFastForwardToNextTask(
+ bool quit_when_idle_requested) {
+ return false;
+}
+
} // namespace scheduler
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.h b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.h
index 889a4918833..185015a4758 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/throttled_time_domain.h
@@ -27,6 +27,7 @@ class PLATFORM_EXPORT ThrottledTimeDomain
base::TimeTicks Now() const override;
base::Optional<base::TimeDelta> DelayTillNextTask(
base::sequence_manager::LazyNow* lazy_now) override;
+ bool MaybeFastForwardToNextTask(bool quit_when_idle_requested) override;
protected:
const char* GetName() const override;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/wake_up_budget_pool.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/wake_up_budget_pool.cc
index 48bee55d124..e90fda491c4 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/wake_up_budget_pool.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/throttling/wake_up_budget_pool.cc
@@ -7,7 +7,7 @@
#include <cstdint>
#include "third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper.cc
index f24c42380d4..277b1ca3952 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper.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 "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "base/format_macros.h"
#include "base/strings/stringprintf.h"
@@ -10,12 +10,10 @@
namespace blink {
namespace scheduler {
-const char kTracingCategoryNameTopLevel[] = "toplevel";
-const char kTracingCategoryNameDefault[] = "renderer.scheduler";
-const char kTracingCategoryNameInfo[] =
- TRACE_DISABLED_BY_DEFAULT("renderer.scheduler");
-const char kTracingCategoryNameDebug[] =
- TRACE_DISABLED_BY_DEFAULT("renderer.scheduler.debug");
+constexpr const char TracingCategoryName::kTopLevel[];
+constexpr const char TracingCategoryName::kDefault[];
+constexpr const char TracingCategoryName::kInfo[];
+constexpr const char TracingCategoryName::kDebug[];
namespace internal {
@@ -24,19 +22,19 @@ void ValidateTracingCategory(const char* category) {
// portable way to use string literals as a template argument.
// Unfortunately, static_assert won't work with templates either because
// inequality (!=) of linker symbols is undefined in compile-time.
- DCHECK(category == kTracingCategoryNameTopLevel ||
- category == kTracingCategoryNameDefault ||
- category == kTracingCategoryNameInfo ||
- category == kTracingCategoryNameDebug);
+ DCHECK(category == TracingCategoryName::kTopLevel ||
+ category == TracingCategoryName::kDefault ||
+ category == TracingCategoryName::kInfo ||
+ category == TracingCategoryName::kDebug);
}
} // namespace internal
void WarmupTracingCategories() {
// No need to warm-up toplevel category here.
- TRACE_EVENT_WARMUP_CATEGORY(kTracingCategoryNameDefault);
- TRACE_EVENT_WARMUP_CATEGORY(kTracingCategoryNameInfo);
- TRACE_EVENT_WARMUP_CATEGORY(kTracingCategoryNameDebug);
+ TRACE_EVENT_WARMUP_CATEGORY(TracingCategoryName::kDefault);
+ TRACE_EVENT_WARMUP_CATEGORY(TracingCategoryName::kInfo);
+ TRACE_EVENT_WARMUP_CATEGORY(TracingCategoryName::kDebug);
}
std::string PointerToString(const void* pointer) {
@@ -57,8 +55,7 @@ const char* YesNoStateToString(bool is_yes) {
}
}
-TraceableVariableController::TraceableVariableController() {
-}
+TraceableVariableController::TraceableVariableController() {}
TraceableVariableController::~TraceableVariableController() {
// Controller should have very same lifetime as their tracers.
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper.h b/chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h
index 75e41431faa..eb5ceb5f1e3 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_TRACING_HELPER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_TRACING_HELPER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_TRACING_HELPER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_TRACING_HELPER_H_
#include <string>
#include <unordered_set>
@@ -21,10 +21,16 @@ namespace scheduler {
// DISCLAIMER
// Using these constants in TRACE_EVENTs is discouraged nor should you pass any
// non-literal string as a category, unless familiar with tracing internals.
-PLATFORM_EXPORT extern const char kTracingCategoryNameTopLevel[];
-PLATFORM_EXPORT extern const char kTracingCategoryNameDefault[];
-PLATFORM_EXPORT extern const char kTracingCategoryNameInfo[];
-PLATFORM_EXPORT extern const char kTracingCategoryNameDebug[];
+// The constants are implemented as static members of a class to have an unique
+// address and not violate ODR.
+struct PLATFORM_EXPORT TracingCategoryName {
+ static constexpr const char kTopLevel[] = "toplevel";
+ static constexpr const char kDefault[] = "renderer.scheduler";
+ static constexpr const char kInfo[] =
+ TRACE_DISABLED_BY_DEFAULT("renderer.scheduler");
+ static constexpr const char kDebug[] =
+ TRACE_DISABLED_BY_DEFAULT("renderer.scheduler.debug");
+};
namespace internal {
@@ -101,9 +107,7 @@ class StateTracer {
// Trace compile-time defined const string, so no copy needed.
// Null may be passed to indicate the absence of state.
- void TraceCompileTimeString(const char* state) {
- TraceImpl(state, false);
- }
+ void TraceCompileTimeString(const char* state) { TraceImpl(state, false); }
protected:
bool is_enabled() const {
@@ -168,25 +172,19 @@ class TraceableState : public TraceableVariable, private StateTracer<category> {
~TraceableState() override = default;
- TraceableState& operator =(const T& value) {
+ TraceableState& operator=(const T& value) {
Assign(value);
return *this;
}
- TraceableState& operator =(const TraceableState& another) {
+ TraceableState& operator=(const TraceableState& another) {
Assign(another.state_);
return *this;
}
- operator T() const {
- return state_;
- }
- const T& get() const {
- return state_;
- }
+ operator T() const { return state_; }
+ const T& get() const { return state_; }
- void OnTraceLogEnabled() final {
- Trace();
- }
+ void OnTraceLogEnabled() final { Trace(); }
protected:
void Assign(T new_state) {
@@ -254,48 +252,40 @@ class TraceableCounter : public TraceableVariable {
Trace();
}
- TraceableCounter& operator =(const T& value) {
+ TraceableCounter& operator=(const T& value) {
value_ = value;
Trace();
return *this;
}
- TraceableCounter& operator =(const TraceableCounter& another) {
+ TraceableCounter& operator=(const TraceableCounter& another) {
value_ = another.value_;
Trace();
return *this;
}
- TraceableCounter& operator +=(const T& value) {
+ TraceableCounter& operator+=(const T& value) {
value_ += value;
Trace();
return *this;
}
- TraceableCounter& operator -=(const T& value) {
+ TraceableCounter& operator-=(const T& value) {
value_ -= value;
Trace();
return *this;
}
- const T& value() const {
- return value_;
- }
- const T* operator ->() const {
- return &value_;
- }
- operator T() const {
- return value_;
- }
+ const T& value() const { return value_; }
+ const T* operator->() const { return &value_; }
+ operator T() const { return value_; }
- void OnTraceLogEnabled() final {
- Trace();
- }
+ void OnTraceLogEnabled() final { Trace(); }
void Trace() const {
TRACE_COUNTER_ID1(category, name_, object_, converter_(value_));
}
private:
- const char* const name_; // Not owned.
+ const char* const name_; // Not owned.
const void* const object_; // Not owned.
const ConverterFuncPtr converter_;
@@ -306,54 +296,54 @@ class TraceableCounter : public TraceableVariable {
// Add operators when it's needed.
template <typename T, const char* category>
-constexpr T operator -(const TraceableCounter<T, category>& counter) {
+constexpr T operator-(const TraceableCounter<T, category>& counter) {
return -counter.value();
}
template <typename T, const char* category>
-constexpr T operator /(const TraceableCounter<T, category>& lhs, const T& rhs) {
+constexpr T operator/(const TraceableCounter<T, category>& lhs, const T& rhs) {
return lhs.value() / rhs;
}
template <typename T, const char* category>
-constexpr bool operator >(
- const TraceableCounter<T, category>& lhs, const T& rhs) {
+constexpr bool operator>(const TraceableCounter<T, category>& lhs,
+ const T& rhs) {
return lhs.value() > rhs;
}
template <typename T, const char* category>
-constexpr bool operator <(
- const TraceableCounter<T, category>& lhs, const T& rhs) {
+constexpr bool operator<(const TraceableCounter<T, category>& lhs,
+ const T& rhs) {
return lhs.value() < rhs;
}
template <typename T, const char* category>
-constexpr bool operator !=(
- const TraceableCounter<T, category>& lhs, const T& rhs) {
+constexpr bool operator!=(const TraceableCounter<T, category>& lhs,
+ const T& rhs) {
return lhs.value() != rhs;
}
template <typename T, const char* category>
-constexpr T operator ++(TraceableCounter<T, category>& counter) {
+constexpr T operator++(TraceableCounter<T, category>& counter) {
counter = counter.value() + 1;
return counter.value();
}
template <typename T, const char* category>
-constexpr T operator --(TraceableCounter<T, category>& counter) {
+constexpr T operator--(TraceableCounter<T, category>& counter) {
counter = counter.value() - 1;
return counter.value();
}
template <typename T, const char* category>
-constexpr T operator ++(TraceableCounter<T, category>& counter, int) {
+constexpr T operator++(TraceableCounter<T, category>& counter, int) {
T value = counter.value();
counter = value + 1;
return value;
}
template <typename T, const char* category>
-constexpr T operator --(TraceableCounter<T, category>& counter, int) {
+constexpr T operator--(TraceableCounter<T, category>& counter, int) {
T value = counter.value();
counter = value - 1;
return value;
@@ -362,4 +352,4 @@ constexpr T operator --(TraceableCounter<T, category>& counter, int) {
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_TRACING_HELPER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_TRACING_HELPER_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper_unittest.cc
index 61931729e01..332310b3748 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/tracing_helper_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/tracing_helper_unittest.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include <unordered_set>
@@ -35,7 +35,7 @@ const char* SignOfInt(int value) {
}
class TraceableStateForTest
- : public TraceableState<int, kTracingCategoryNameDefault> {
+ : public TraceableState<int, TracingCategoryName::kDefault> {
public:
TraceableStateForTest(TraceableVariableController* controller)
: TraceableState(0, "State", controller, controller, SignOfInt) {
@@ -43,7 +43,7 @@ class TraceableStateForTest
mock_trace_for_test_ = &MockTrace;
}
- TraceableStateForTest& operator =(const int& value) {
+ TraceableStateForTest& operator=(const int& value) {
Assign(value);
return *this;
}
@@ -74,10 +74,10 @@ TEST(TracingHelperTest, TraceableState) {
TEST(TracingHelperTest, TraceableStateOperators) {
TraceableVariableController controller;
- TraceableState<int, kTracingCategoryNameDebug> x(
- -1, "X", &controller, &controller, SignOfInt);
- TraceableState<int, kTracingCategoryNameDebug> y(
- 1, "Y", &controller, &controller, SignOfInt);
+ TraceableState<int, TracingCategoryName::kDebug> x(-1, "X", &controller,
+ &controller, SignOfInt);
+ TraceableState<int, TracingCategoryName::kDebug> y(1, "Y", &controller,
+ &controller, SignOfInt);
EXPECT_EQ(0, x + y);
EXPECT_FALSE(x == y);
EXPECT_TRUE(x != y);
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc
index e81a397b0bd..cf19a8928c3 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc
@@ -7,8 +7,8 @@
#include <utility>
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
namespace blink {
namespace scheduler {
@@ -18,16 +18,21 @@ WebThreadScheduler::~WebThreadScheduler() = default;
// static
std::unique_ptr<WebThreadScheduler>
WebThreadScheduler::CreateMainThreadScheduler(
+ std::unique_ptr<base::MessagePump> message_pump,
base::Optional<base::Time> initial_virtual_time) {
// Ensure categories appear as an option in chrome://tracing.
WarmupTracingCategories();
// Workers might be short-lived, so placing warmup here.
TRACE_EVENT_WARMUP_CATEGORY(TRACE_DISABLED_BY_DEFAULT("worker.scheduler"));
-
+ auto sequence_manager =
+ message_pump
+ ? base::sequence_manager::
+ CreateSequenceManagerOnCurrentThreadWithPump(
+ base::MessageLoop::TYPE_DEFAULT, std::move(message_pump))
+ : base::sequence_manager::CreateSequenceManagerOnCurrentThread();
std::unique_ptr<MainThreadSchedulerImpl> scheduler(
- new MainThreadSchedulerImpl(
- base::sequence_manager::CreateSequenceManagerOnCurrentThread(),
- initial_virtual_time));
+ new MainThreadSchedulerImpl(std::move(sequence_manager),
+ initial_virtual_time));
return std::move(scheduler);
}
@@ -161,7 +166,7 @@ void WebThreadScheduler::AddRAILModeObserver(WebRAILModeObserver* observer) {
NOTREACHED();
}
-void WebThreadScheduler::SetRendererProcessType(RendererProcessType type) {
+void WebThreadScheduler::SetRendererProcessType(WebRendererProcessType type) {
NOTREACHED();
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.cc
index 58c7a6d5592..1009395d075 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.cc
@@ -83,15 +83,26 @@ AutoAdvancingVirtualTimeDomain::DelayTillNextTask(
if (run_time <= Now())
return base::TimeDelta();
+ // Rely on MaybeFastForwardToNextTask to be called to advance
+ // virtual time.
+ return base::nullopt;
+}
+
+bool AutoAdvancingVirtualTimeDomain::MaybeFastForwardToNextTask(
+ bool quit_when_idle_requested) {
if (!can_advance_virtual_time_)
- return base::nullopt;
+ return false;
+
+ base::Optional<base::TimeTicks> run_time = NextScheduledRunTime();
+ if (!run_time)
+ return false;
if (MaybeAdvanceVirtualTime(*run_time)) {
task_starvation_count_ = 0;
- return base::TimeDelta(); // Makes DoWork post an immediate continuation.
+ return true;
}
- return base::nullopt;
+ return false;
}
void AutoAdvancingVirtualTimeDomain::SetNextDelayedDoWork(
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h
index 3a3dbecddc5..bd68b9329d7 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h
@@ -77,6 +77,7 @@ class PLATFORM_EXPORT AutoAdvancingVirtualTimeDomain
base::TimeTicks Now() const override;
base::Optional<base::TimeDelta> DelayTillNextTask(
base::sequence_manager::LazyNow* lazy_now) override;
+ bool MaybeFastForwardToNextTask(bool quit_when_idle_requested) override;
protected:
const char* GetName() const override;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc
index c6daad5a39e..fe2a37facc5 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc
@@ -15,15 +15,15 @@
#include "third_party/blink/public/platform/blame_context.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/budget_pool.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_visibility_state.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/resource_loading_task_runner_handle_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h"
namespace blink {
@@ -452,6 +452,8 @@ base::Optional<QueueTraits> FrameSchedulerImpl::CreateQueueTraitsForTaskType(
// when recovering from debugger JavaScript statetment.
case TaskType::kInternalTest:
return UnpausableTaskQueueTraits();
+ case TaskType::kInternalTranslation:
+ return ForegroundOnlyTaskQueueTraits();
case TaskType::kDeprecatedNone:
case TaskType::kMainThreadTaskQueueV8:
case TaskType::kMainThreadTaskQueueCompositor:
@@ -704,7 +706,8 @@ void FrameSchedulerImpl::UpdateQueuePolicy(
if (!voter)
return;
DCHECK(parent_page_scheduler_);
- bool queue_paused = frame_paused_ && queue->CanBePaused();
+ bool queue_disabled = false;
+ queue_disabled |= frame_paused_ && queue->CanBePaused();
// Per-frame freezable task queues will be frozen after 5 mins in background
// on Android, and if the browser freezes the page in the background. They
// will be resumed when the page is visible.
@@ -713,7 +716,12 @@ void FrameSchedulerImpl::UpdateQueuePolicy(
// Override freezing if keep-active is true.
if (queue_frozen && !queue->FreezeWhenKeepActive())
queue_frozen = !parent_page_scheduler_->KeepActive();
- voter->SetQueueEnabled(!queue_paused && !queue_frozen);
+ queue_disabled |= queue_frozen;
+ // Per-frame freezable queues of tasks which are specified as getting frozen
+ // immediately when their frame becomes invisible get frozen. They will be
+ // resumed when the frame becomes visible again.
+ queue_disabled |= !frame_visible_ && !queue->CanRunInBackground();
+ voter->SetQueueEnabled(!queue_disabled);
}
SchedulingLifecycleState FrameSchedulerImpl::CalculateLifecycleState(
@@ -979,5 +987,10 @@ FrameSchedulerImpl::UnpausableTaskQueueTraits() {
return QueueTraits();
}
+MainThreadTaskQueue::QueueTraits
+FrameSchedulerImpl::ForegroundOnlyTaskQueueTraits() {
+ return ThrottleableTaskQueueTraits().SetCanRunInBackground(false);
+}
+
} // namespace scheduler
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h
index b0aada21f06..5fce666c8e5 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h
@@ -20,12 +20,12 @@
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_origin_type.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_visibility_state.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
@@ -244,6 +244,7 @@ class PLATFORM_EXPORT FrameSchedulerImpl : public FrameScheduler,
static MainThreadTaskQueue::QueueTraits DeferrableTaskQueueTraits();
static MainThreadTaskQueue::QueueTraits PausableTaskQueueTraits();
static MainThreadTaskQueue::QueueTraits UnpausableTaskQueueTraits();
+ static MainThreadTaskQueue::QueueTraits ForegroundOnlyTaskQueueTraits();
const FrameScheduler::FrameType frame_type_;
@@ -265,25 +266,27 @@ class PLATFORM_EXPORT FrameSchedulerImpl : public FrameScheduler,
FrameScheduler::Delegate* delegate_; // NOT OWNED
base::trace_event::BlameContext* blame_context_; // NOT OWNED
SchedulingLifecycleState throttling_state_;
- TraceableState<bool, kTracingCategoryNameInfo> frame_visible_;
- TraceableState<bool, kTracingCategoryNameInfo> frame_paused_;
- TraceableState<FrameOriginType, kTracingCategoryNameInfo> frame_origin_type_;
- TraceableState<bool, kTracingCategoryNameInfo> subresource_loading_paused_;
- StateTracer<kTracingCategoryNameInfo> url_tracer_;
- TraceableState<bool, kTracingCategoryNameInfo> task_queues_throttled_;
+ TraceableState<bool, TracingCategoryName::kInfo> frame_visible_;
+ TraceableState<bool, TracingCategoryName::kInfo> frame_paused_;
+ TraceableState<FrameOriginType, TracingCategoryName::kInfo>
+ frame_origin_type_;
+ TraceableState<bool, TracingCategoryName::kInfo> subresource_loading_paused_;
+ StateTracer<TracingCategoryName::kInfo> url_tracer_;
+ TraceableState<bool, TracingCategoryName::kInfo> task_queues_throttled_;
// TODO(kraynov): https://crbug.com/827113
// Trace active connection count.
int active_connection_count_;
size_t subresource_loading_pause_count_;
- TraceableState<bool, kTracingCategoryNameInfo> has_active_connection_;
+ TraceableState<bool, TracingCategoryName::kInfo> has_active_connection_;
// These are the states of the Page.
// They should be accessed via GetPageScheduler()->SetPageState().
// they are here because we don't support page-level tracing yet.
- TraceableState<bool, kTracingCategoryNameInfo> page_frozen_for_tracing_;
- TraceableState<PageVisibilityState, kTracingCategoryNameInfo>
+ TraceableState<bool, TracingCategoryName::kInfo> page_frozen_for_tracing_;
+ TraceableState<PageVisibilityState, TracingCategoryName::kInfo>
page_visibility_for_tracing_;
- TraceableState<bool, kTracingCategoryNameInfo> page_keep_active_for_tracing_;
+ TraceableState<bool, TracingCategoryName::kInfo>
+ page_keep_active_for_tracing_;
base::WeakPtrFactory<FrameSchedulerImpl> weak_factory_;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc
index a9855ee1970..c8f6eeb781c 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc
@@ -17,14 +17,13 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/resource_loading_task_runner_handle_impl.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
using base::sequence_manager::TaskQueue;
using testing::UnorderedElementsAre;
@@ -115,6 +114,11 @@ class FrameSchedulerImplTest : public testing::Test {
return NonLoadingTaskQueue(FrameSchedulerImpl::UnpausableTaskQueueTraits());
}
+ scoped_refptr<TaskQueue> ForegroundOnlyTaskQueue() {
+ return NonLoadingTaskQueue(
+ FrameSchedulerImpl::ForegroundOnlyTaskQueueTraits());
+ }
+
scoped_refptr<MainThreadTaskQueue> GetTaskQueue(TaskType type) {
return frame_scheduler_->GetTaskQueue(type);
}
@@ -369,6 +373,24 @@ TEST_F(FrameSchedulerImplTest, PauseAndResume) {
EXPECT_EQ(5, counter);
}
+TEST_F(FrameSchedulerImplTest, FreezeForegroundOnlyTasks) {
+ int counter = 0;
+ ForegroundOnlyTaskQueue()->task_runner()->PostTask(
+ FROM_HERE, base::BindOnce(&IncrementCounter, base::Unretained(&counter)));
+
+ page_scheduler_->SetPageVisible(false);
+
+ EXPECT_EQ(0, counter);
+ base::RunLoop().RunUntilIdle();
+ EXPECT_EQ(0, counter);
+
+ page_scheduler_->SetPageVisible(true);
+
+ EXPECT_EQ(0, counter);
+ base::RunLoop().RunUntilIdle();
+ EXPECT_EQ(1, counter);
+}
+
TEST_F(FrameSchedulerImplStopNonTimersInBackgroundEnabledTest,
PageFreezeAndUnfreezeFlagEnabled) {
int counter = 0;
@@ -394,7 +416,7 @@ TEST_F(FrameSchedulerImplStopNonTimersInBackgroundEnabledTest,
page_scheduler_->SetPageFrozen(false);
EXPECT_EQ(1, counter);
- // Same as RunUntilIdle but also advances the cock if necessary.
+ // Same as RunUntilIdle but also advances the clock if necessary.
task_environment_.FastForwardUntilNoTasksRemain();
EXPECT_EQ(5, counter);
}
@@ -1581,6 +1603,8 @@ TEST_F(FrameSchedulerImplTest, TaskTypeToTaskQueueMapping) {
EXPECT_EQ(GetTaskQueue(TaskType::kNetworking), LoadingTaskQueue());
EXPECT_EQ(GetTaskQueue(TaskType::kNetworkingControl),
LoadingControlTaskQueue());
+ EXPECT_EQ(GetTaskQueue(TaskType::kInternalTranslation),
+ ForegroundOnlyTaskQueue());
}
class ThrottleAndFreezeTaskTypesExperimentTest : public FrameSchedulerImplTest {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/frame_status.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_status.cc
index da08cbdaa7e..cfda104e005 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/frame_status.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_status.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 "third_party/blink/renderer/platform/scheduler/renderer/frame_status.h"
+#include "third_party/blink/renderer/platform/scheduler/public/frame_status.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/page_scheduler.h"
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.cc
index 13bd6f5ccd7..7afcea9586c 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/frame_task_queue_controller.cc
@@ -10,12 +10,12 @@
#include "base/callback.h"
#include "base/logging.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator_unittest.cc
index c12e7b3ae43..f53a86b5ef9 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator_unittest.cc
@@ -51,8 +51,9 @@ class IdleTimeEstimatorTest : public testing::Test {
nullptr, task_environment_.GetMainThreadTaskRunner(),
task_environment_.GetMockTickClock());
compositor_task_queue_ =
- manager_->CreateTaskQueue<base::sequence_manager::TestTaskQueue>(
- base::sequence_manager::TaskQueue::Spec("test_tq"));
+ manager_
+ ->CreateTaskQueueWithType<base::sequence_manager::TestTaskQueue>(
+ base::sequence_manager::TaskQueue::Spec("test_tq"));
estimator_.reset(new IdleTimeEstimatorForTest(
compositor_task_queue_, task_environment_.GetMockTickClock(), 10, 50));
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.cc
new file mode 100644
index 00000000000..1aa76a26338
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.cc
@@ -0,0 +1,46 @@
+// 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 "third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h"
+
+#include "base/location.h"
+#include "base/task/sequence_manager/task_queue.h"
+#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
+
+namespace blink {
+namespace scheduler {
+
+MainThread::MainThread(MainThreadSchedulerImpl* scheduler)
+ : task_runner_(scheduler->DefaultTaskRunner()),
+ scheduler_(scheduler),
+ thread_id_(base::PlatformThread::CurrentId()) {}
+
+MainThread::~MainThread() = default;
+
+void MainThread::Init() {}
+
+blink::PlatformThreadId MainThread::ThreadId() const {
+ return thread_id_;
+}
+
+blink::ThreadScheduler* MainThread::Scheduler() {
+ return scheduler_;
+}
+
+scoped_refptr<base::SingleThreadTaskRunner> MainThread::GetTaskRunner() const {
+ return task_runner_;
+}
+
+void MainThread::AddTaskTimeObserver(
+ base::sequence_manager::TaskTimeObserver* task_time_observer) {
+ scheduler_->AddTaskTimeObserver(task_time_observer);
+}
+
+void MainThread::RemoveTaskTimeObserver(
+ base::sequence_manager::TaskTimeObserver* task_time_observer) {
+ scheduler_->RemoveTaskTimeObserver(task_time_observer);
+}
+
+} // namespace scheduler
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h
new file mode 100644
index 00000000000..8bca7f03bf2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h
@@ -0,0 +1,46 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_MAIN_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_MAIN_THREAD_H_
+
+#include "base/memory/scoped_refptr.h"
+#include "base/message_loop/message_loop.h"
+#include "base/single_thread_task_runner.h"
+#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+
+namespace blink {
+class ThreadScheduler;
+};
+
+namespace blink {
+namespace scheduler {
+class MainThreadSchedulerImpl;
+
+class PLATFORM_EXPORT MainThread : public Thread {
+ public:
+ explicit MainThread(MainThreadSchedulerImpl* scheduler);
+ ~MainThread() override;
+
+ // Thread implementation.
+ void Init() override;
+ ThreadScheduler* Scheduler() override;
+ PlatformThreadId ThreadId() const override;
+ scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() const override;
+
+ void AddTaskTimeObserver(base::sequence_manager::TaskTimeObserver*) override;
+ void RemoveTaskTimeObserver(
+ base::sequence_manager::TaskTimeObserver*) override;
+
+ private:
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
+ MainThreadSchedulerImpl* scheduler_; // Not owned.
+ PlatformThreadId thread_id_;
+};
+
+} // namespace scheduler
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_MAIN_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc
index 7da5a4f7ee3..d1b33c34124 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc
@@ -8,7 +8,7 @@
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
#include "services/resource_coordinator/public/cpp/resource_coordinator_features.h"
-#include "third_party/blink/public/platform/scheduler/renderer_process_type.h"
+#include "third_party/blink/public/platform/scheduler/web_renderer_process_type.h"
#include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/renderer_resource_coordinator.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
@@ -478,7 +478,7 @@ void MainThreadMetricsHelper::RecordMainThreadTaskLoad(base::TimeTicks time,
UMA_HISTOGRAM_PERCENTAGE(MAIN_THREAD_LOAD_METRIC_NAME, load_percentage);
if (main_thread_scheduler_->main_thread_only().process_type ==
- RendererProcessType::kExtensionRenderer) {
+ WebRendererProcessType::kExtensionRenderer) {
UMA_HISTOGRAM_PERCENTAGE(EXTENSIONS_MAIN_THREAD_LOAD_METRIC_NAME,
load_percentage);
}
@@ -494,12 +494,12 @@ void MainThreadMetricsHelper::RecordForegroundMainThreadTaskLoad(
DCHECK_LE(load_percentage, 100);
switch (main_thread_scheduler_->main_thread_only().process_type) {
- case RendererProcessType::kExtensionRenderer:
+ case WebRendererProcessType::kExtensionRenderer:
UMA_HISTOGRAM_PERCENTAGE(EXTENSIONS_MAIN_THREAD_LOAD_METRIC_NAME
".Foreground",
load_percentage);
break;
- case RendererProcessType::kRenderer:
+ case WebRendererProcessType::kRenderer:
UMA_HISTOGRAM_PERCENTAGE(MAIN_THREAD_LOAD_METRIC_NAME ".Foreground",
load_percentage);
@@ -526,12 +526,12 @@ void MainThreadMetricsHelper::RecordBackgroundMainThreadTaskLoad(
DCHECK_LE(load_percentage, 100);
switch (main_thread_scheduler_->main_thread_only().process_type) {
- case RendererProcessType::kExtensionRenderer:
+ case WebRendererProcessType::kExtensionRenderer:
UMA_HISTOGRAM_PERCENTAGE(EXTENSIONS_MAIN_THREAD_LOAD_METRIC_NAME
".Background",
load_percentage);
break;
- case RendererProcessType::kRenderer:
+ case WebRendererProcessType::kRenderer:
UMA_HISTOGRAM_PERCENTAGE(MAIN_THREAD_LOAD_METRIC_NAME ".Background",
load_percentage);
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h
index c024e311d99..f1b990677a0 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h
@@ -14,10 +14,10 @@
#include "third_party/blink/public/platform/web_thread_type.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/scheduler/common/metrics_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/use_case.h"
-#include "third_party/blink/renderer/platform/scheduler/renderer/frame_status.h"
-#include "third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h"
+#include "third_party/blink/renderer/platform/scheduler/public/frame_status.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc
index 6222ae68489..c2f50406000 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc
@@ -56,7 +56,7 @@ scoped_refptr<TaskQueue> MainThreadSchedulerHelper::ControlTaskQueue() {
scoped_refptr<MainThreadTaskQueue> MainThreadSchedulerHelper::NewTaskQueue(
const MainThreadTaskQueue::QueueCreationParams& params) {
scoped_refptr<MainThreadTaskQueue> task_queue =
- sequence_manager_->CreateTaskQueue<MainThreadTaskQueue>(
+ sequence_manager_->CreateTaskQueueWithType<MainThreadTaskQueue>(
params.spec, params, main_thread_scheduler_);
if (params.fixed_priority)
task_queue->SetQueuePriority(params.fixed_priority.value());
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
index 9f6f633db60..2057cb35313 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
@@ -19,25 +19,25 @@
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "build/build_config.h"
#include "components/viz/common/frame_sinks/begin_frame_args.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "third_party/blink/public/common/page/launching_process_state.h"
-#include "third_party/blink/public/platform/scheduler/renderer_process_type.h"
+#include "third_party/blink/public/platform/scheduler/web_renderer_process_type.h"
#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "third_party/blink/public/platform/web_touch_event.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string_manager.h"
#include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/renderer_resource_coordinator.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/process_state.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/process_state.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
+#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.h"
-#include "third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h"
namespace blink {
namespace scheduler {
@@ -109,11 +109,11 @@ const char* AudioPlayingStateToString(bool is_audio_playing) {
}
}
-const char* RendererProcessTypeToString(RendererProcessType process_type) {
+const char* RendererProcessTypeToString(WebRendererProcessType process_type) {
switch (process_type) {
- case RendererProcessType::kRenderer:
+ case WebRendererProcessType::kRenderer:
return "normal";
- case RendererProcessType::kExtensionRenderer:
+ case WebRendererProcessType::kExtensionRenderer:
return "extension";
}
NOTREACHED();
@@ -215,7 +215,10 @@ MainThreadSchedulerImpl::MainThreadSchedulerImpl(
base::Unretained(this)),
helper_.ControlMainThreadTaskQueue()->CreateTaskRunner(
TaskType::kMainThreadTaskQueueControl)),
- queueing_time_estimator_(this, kQueueingTimeWindowDuration, 20),
+ queueing_time_estimator_(this,
+ kQueueingTimeWindowDuration,
+ 20,
+ kLaunchingProcessIsBackgrounded),
main_thread_only_(this,
compositor_task_queue_,
helper_.GetClock(),
@@ -483,7 +486,7 @@ MainThreadSchedulerImpl::MainThreadOnly::MainThreadOnly(
main_thread_scheduler_impl->helper_.HasCPUTimingForEachTask(),
now,
renderer_backgrounded),
- process_type(RendererProcessType::kRenderer,
+ process_type(WebRendererProcessType::kRenderer,
"RendererProcessType",
main_thread_scheduler_impl,
&main_thread_scheduler_impl->tracing_controller_,
@@ -657,7 +660,7 @@ void MainThreadSchedulerImpl::Shutdown() {
}
std::unique_ptr<Thread> MainThreadSchedulerImpl::CreateMainThread() {
- return std::make_unique<WebThreadImplForRendererScheduler>(this);
+ return std::make_unique<MainThread>(this);
}
scoped_refptr<base::SingleThreadTaskRunner>
@@ -995,7 +998,7 @@ void MainThreadSchedulerImpl::SetRendererBackgrounded(bool backgrounded) {
internal::ProcessState::Get()->is_process_backgrounded = backgrounded;
main_thread_only().background_status_changed_at = tick_clock()->NowTicks();
- queueing_time_estimator_.OnRendererStateChanged(
+ queueing_time_estimator_.OnRecordingStateChanged(
backgrounded, main_thread_only().background_status_changed_at);
UpdatePolicy();
@@ -2349,14 +2352,16 @@ void MainThreadSchedulerImpl::ResetForNavigationLocked() {
UpdatePolicyLocked(UpdateType::kMayEarlyOutIfPolicyUnchanged);
UMA_HISTOGRAM_COUNTS_100("RendererScheduler.WebViewsPerScheduler",
- main_thread_only().page_schedulers.size());
+ base::saturated_cast<base::HistogramBase::Sample>(
+ main_thread_only().page_schedulers.size()));
size_t frame_count = 0;
for (PageSchedulerImpl* page_scheduler : main_thread_only().page_schedulers) {
frame_count += page_scheduler->FrameCount();
}
- UMA_HISTOGRAM_COUNTS_100("RendererScheduler.WebFramesPerScheduler",
- frame_count);
+ UMA_HISTOGRAM_COUNTS_100(
+ "RendererScheduler.WebFramesPerScheduler",
+ base::saturated_cast<base::HistogramBase::Sample>(frame_count));
}
void MainThreadSchedulerImpl::SetTopLevelBlameContext(
@@ -2384,7 +2389,8 @@ void MainThreadSchedulerImpl::AddRAILModeObserver(
observer->OnRAILModeChanged(main_thread_only().current_policy.rail_mode());
}
-void MainThreadSchedulerImpl::SetRendererProcessType(RendererProcessType type) {
+void MainThreadSchedulerImpl::SetRendererProcessType(
+ WebRendererProcessType type) {
main_thread_only().process_type = type;
}
@@ -2600,7 +2606,7 @@ UkmRecordingStatus MainThreadSchedulerImpl::RecordTaskUkmImpl(
// Trade off for privacy: Round to seconds for times below 10 minutes and
// minutes afterwards.
- int seconds_since_backgrounded = 0;
+ int64_t seconds_since_backgrounded = 0;
if (time_since_backgrounded < base::TimeDelta::FromMinutes(10)) {
seconds_since_backgrounded = time_since_backgrounded.InSeconds();
} else {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
index 97d61fb413a..d63270a982a 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
@@ -26,10 +26,11 @@
#include "build/build_config.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/scheduler/child/pollable_thread_safe_flag.h"
#include "third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h"
#include "third_party/blink/renderer/platform/scheduler/common/idle_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/pollable_thread_safe_flag.h"
#include "third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/deadline_task_runner.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/idle_time_estimator.h"
@@ -44,7 +45,6 @@
#include "third_party/blink/renderer/platform/scheduler/main_thread/use_case.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/user_model.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
namespace base {
namespace trace_event {
@@ -161,7 +161,6 @@ class PLATFORM_EXPORT MainThreadSchedulerImpl
// WebThreadScheduler implementation:
std::unique_ptr<Thread> CreateMainThread() override;
- scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() override;
// Note: this is also shared by the ThreadScheduler interface.
scoped_refptr<base::SingleThreadTaskRunner> IPCTaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> CleanupTaskRunner() override;
@@ -198,7 +197,7 @@ class PLATFORM_EXPORT MainThreadSchedulerImpl
void SetTopLevelBlameContext(
base::trace_event::BlameContext* blame_context) override;
void AddRAILModeObserver(WebRAILModeObserver* observer) override;
- void SetRendererProcessType(RendererProcessType type) override;
+ void SetRendererProcessType(WebRendererProcessType type) override;
WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser(
const char* name,
WebScopedVirtualTimePauser::VirtualTaskDuration duration) override;
@@ -252,6 +251,7 @@ class PLATFORM_EXPORT MainThreadSchedulerImpl
base::TimeDelta queueing_time) override;
// ThreadSchedulerImpl implementation:
+ scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> ControlTaskRunner() override;
void RegisterTimeDomain(
base::sequence_manager::TimeDomain* time_domain) override;
@@ -815,49 +815,51 @@ class PLATFORM_EXPORT MainThreadSchedulerImpl
TaskCostEstimator loading_task_cost_estimator;
TaskCostEstimator timer_task_cost_estimator;
IdleTimeEstimator idle_time_estimator;
- TraceableState<UseCase, kTracingCategoryNameDefault> current_use_case;
+ TraceableState<UseCase, TracingCategoryName::kDefault> current_use_case;
Policy current_policy;
base::TimeTicks current_policy_expiration_time;
base::TimeTicks estimated_next_frame_begin;
base::TimeTicks current_task_start_time;
base::TimeDelta compositor_frame_interval;
- TraceableCounter<base::TimeDelta, kTracingCategoryNameDebug>
+ TraceableCounter<base::TimeDelta, TracingCategoryName::kDebug>
longest_jank_free_task_duration;
- TraceableCounter<int, kTracingCategoryNameInfo>
+ TraceableCounter<int, TracingCategoryName::kInfo>
renderer_pause_count; // Renderer is paused if non-zero.
- TraceableState<ExpensiveTaskPolicy, kTracingCategoryNameInfo>
+ TraceableState<ExpensiveTaskPolicy, TracingCategoryName::kInfo>
expensive_task_policy;
- TraceableState<v8::RAILMode, kTracingCategoryNameInfo>
+ TraceableState<v8::RAILMode, TracingCategoryName::kInfo>
rail_mode_for_tracing; // Don't use except for tracing.
- TraceableState<bool, kTracingCategoryNameDebug> renderer_hidden;
- TraceableState<bool, kTracingCategoryNameTopLevel> renderer_backgrounded;
- TraceableState<bool, kTracingCategoryNameDefault>
+ TraceableState<bool, TracingCategoryName::kDebug> renderer_hidden;
+ TraceableState<bool, TracingCategoryName::kTopLevel> renderer_backgrounded;
+ TraceableState<bool, TracingCategoryName::kDefault>
keep_active_fetch_or_worker;
- TraceableCounter<base::TimeDelta, kTracingCategoryNameInfo>
+ TraceableCounter<base::TimeDelta, TracingCategoryName::kInfo>
loading_task_estimated_cost;
- TraceableCounter<base::TimeDelta, kTracingCategoryNameInfo>
+ TraceableCounter<base::TimeDelta, TracingCategoryName::kInfo>
timer_task_estimated_cost;
- TraceableState<bool, kTracingCategoryNameInfo> loading_tasks_seem_expensive;
- TraceableState<bool, kTracingCategoryNameInfo> timer_tasks_seem_expensive;
- TraceableState<bool, kTracingCategoryNameDefault>
+ TraceableState<bool, TracingCategoryName::kInfo>
+ loading_tasks_seem_expensive;
+ TraceableState<bool, TracingCategoryName::kInfo> timer_tasks_seem_expensive;
+ TraceableState<bool, TracingCategoryName::kDefault>
blocking_input_expected_soon;
- TraceableState<bool, kTracingCategoryNameDebug>
+ TraceableState<bool, TracingCategoryName::kDebug>
have_seen_a_begin_main_frame;
- TraceableState<bool, kTracingCategoryNameDebug>
+ TraceableState<bool, TracingCategoryName::kDebug>
have_reported_blocking_intervention_in_current_policy;
- TraceableState<bool, kTracingCategoryNameDebug>
+ TraceableState<bool, TracingCategoryName::kDebug>
have_reported_blocking_intervention_since_navigation;
- TraceableState<bool, kTracingCategoryNameDebug>
+ TraceableState<bool, TracingCategoryName::kDebug>
has_visible_render_widget_with_touch_handler;
- TraceableState<bool, kTracingCategoryNameDebug>
+ TraceableState<bool, TracingCategoryName::kDebug>
begin_frame_not_expected_soon;
- TraceableState<bool, kTracingCategoryNameDebug> in_idle_period_for_testing;
- TraceableState<bool, kTracingCategoryNameInfo> use_virtual_time;
- TraceableState<bool, kTracingCategoryNameTopLevel> is_audio_playing;
- TraceableState<bool, kTracingCategoryNameDebug>
+ TraceableState<bool, TracingCategoryName::kDebug>
+ in_idle_period_for_testing;
+ TraceableState<bool, TracingCategoryName::kInfo> use_virtual_time;
+ TraceableState<bool, TracingCategoryName::kTopLevel> is_audio_playing;
+ TraceableState<bool, TracingCategoryName::kDebug>
compositor_will_send_main_frame_not_expected;
- TraceableState<bool, kTracingCategoryNameDebug> has_navigated;
- TraceableState<bool, kTracingCategoryNameDebug> pause_timers_for_webview;
+ TraceableState<bool, TracingCategoryName::kDebug> has_navigated;
+ TraceableState<bool, TracingCategoryName::kDebug> pause_timers_for_webview;
std::unique_ptr<base::SingleSampleMetric> max_queueing_time_metric;
base::TimeDelta max_queueing_time;
base::TimeTicks background_status_changed_at;
@@ -866,14 +868,14 @@ class PLATFORM_EXPORT MainThreadSchedulerImpl
rail_mode_observers; // Not owned.
WakeUpBudgetPool* wake_up_budget_pool; // Not owned.
MainThreadMetricsHelper metrics_helper;
- TraceableState<RendererProcessType, kTracingCategoryNameTopLevel>
+ TraceableState<WebRendererProcessType, TracingCategoryName::kTopLevel>
process_type;
TraceableState<base::Optional<TaskDescriptionForTracing>,
- kTracingCategoryNameInfo>
+ TracingCategoryName::kInfo>
task_description_for_tracing; // Don't use except for tracing.
TraceableState<
base::Optional<base::sequence_manager::TaskQueue::QueuePriority>,
- kTracingCategoryNameInfo>
+ TracingCategoryName::kInfo>
task_priority_for_tracing; // Only used for tracing.
base::ObserverList<VirtualTimeObserver>::Unchecked virtual_time_observers;
base::Time initial_virtual_time;
@@ -917,17 +919,19 @@ class PLATFORM_EXPORT MainThreadSchedulerImpl
base::TimeTicks last_idle_period_end_time;
base::TimeTicks fling_compositor_escalation_deadline;
UserModel user_model;
- TraceableState<bool, kTracingCategoryNameInfo>
+ TraceableState<bool, TracingCategoryName::kInfo>
awaiting_touch_start_response;
- TraceableState<bool, kTracingCategoryNameInfo> in_idle_period;
- TraceableState<bool, kTracingCategoryNameInfo>
+ TraceableState<bool, TracingCategoryName::kInfo> in_idle_period;
+ TraceableState<bool, TracingCategoryName::kInfo>
begin_main_frame_on_critical_path;
- TraceableState<bool, kTracingCategoryNameInfo>
+ TraceableState<bool, TracingCategoryName::kInfo>
last_gesture_was_compositor_driven;
- TraceableState<bool, kTracingCategoryNameInfo> default_gesture_prevented;
- TraceableState<bool, kTracingCategoryNameInfo> have_seen_a_blocking_gesture;
- TraceableState<bool, kTracingCategoryNameInfo> waiting_for_meaningful_paint;
- TraceableState<bool, kTracingCategoryNameInfo>
+ TraceableState<bool, TracingCategoryName::kInfo> default_gesture_prevented;
+ TraceableState<bool, TracingCategoryName::kInfo>
+ have_seen_a_blocking_gesture;
+ TraceableState<bool, TracingCategoryName::kInfo>
+ waiting_for_meaningful_paint;
+ TraceableState<bool, TracingCategoryName::kInfo>
have_seen_input_since_navigation;
};
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc
index 5fbaf37c31e..4af2aa252cd 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc
@@ -27,7 +27,7 @@
#include "third_party/blink/public/common/page/launching_process_state.h"
#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "third_party/blink/public/platform/web_touch_event.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/budget_pool.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/auto_advancing_virtual_time_domain.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
@@ -2258,7 +2258,8 @@ class MainThreadSchedulerImplWithMessageLoopTest
clock_.Advance(base::TimeDelta::FromMilliseconds(5));
Initialize(std::make_unique<MainThreadSchedulerImplForTest>(
base::sequence_manager::SequenceManagerForTest::Create(
- message_loop_.get(), message_loop_->task_runner(), &clock_),
+ message_loop_->GetMessageLoopBase(), message_loop_->task_runner(),
+ &clock_),
base::nullopt));
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.cc
index 61804744dd5..8888bd9861d 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.cc
@@ -115,7 +115,7 @@ MainThreadTaskQueue::MainThreadTaskQueue(
freeze_when_keep_active_(params.freeze_when_keep_active),
main_thread_scheduler_(main_thread_scheduler),
frame_scheduler_(params.frame_scheduler) {
- if (GetTaskQueueImpl()) {
+ if (GetTaskQueueImpl() && spec.should_notify_observers) {
// TaskQueueImpl may be null for tests.
// TODO(scheduler-dev): Consider mapping directly to
// MainThreadSchedulerImpl::OnTaskStarted/Completed. At the moment this
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h
index 8c27749947e..49a6db60eeb 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h
@@ -97,7 +97,8 @@ class PLATFORM_EXPORT MainThreadTaskQueue
: can_be_deferred(false),
can_be_throttled(false),
can_be_paused(false),
- can_be_frozen(false) {}
+ can_be_frozen(false),
+ can_run_in_background(true) {}
QueueTraits(const QueueTraits&) = default;
@@ -121,11 +122,17 @@ class PLATFORM_EXPORT MainThreadTaskQueue
return *this;
}
+ QueueTraits SetCanRunInBackground(bool value) {
+ can_run_in_background = value;
+ return *this;
+ }
+
bool operator==(const QueueTraits& other) const {
return can_be_deferred == other.can_be_deferred &&
can_be_throttled == other.can_be_throttled &&
can_be_paused == other.can_be_paused &&
- can_be_frozen == other.can_be_frozen;
+ can_be_frozen == other.can_be_frozen &&
+ can_run_in_background == other.can_run_in_background;
}
// Return a key suitable for WTF::HashMap.
@@ -136,6 +143,7 @@ class PLATFORM_EXPORT MainThreadTaskQueue
key |= can_be_throttled << 2;
key |= can_be_paused << 3;
key |= can_be_frozen << 4;
+ key |= can_run_in_background << 5;
return key;
}
@@ -143,6 +151,7 @@ class PLATFORM_EXPORT MainThreadTaskQueue
bool can_be_throttled : 1;
bool can_be_paused : 1;
bool can_be_frozen : 1;
+ bool can_run_in_background : 1;
};
struct QueueCreationParams {
@@ -168,26 +177,37 @@ class PLATFORM_EXPORT MainThreadTaskQueue
QueueCreationParams SetCanBeDeferred(bool value) {
queue_traits = queue_traits.SetCanBeDeferred(value);
+ ApplyQueueTraitsToSpec();
return *this;
}
QueueCreationParams SetCanBeThrottled(bool value) {
queue_traits = queue_traits.SetCanBeThrottled(value);
+ ApplyQueueTraitsToSpec();
return *this;
}
QueueCreationParams SetCanBePaused(bool value) {
queue_traits = queue_traits.SetCanBePaused(value);
+ ApplyQueueTraitsToSpec();
return *this;
}
QueueCreationParams SetCanBeFrozen(bool value) {
queue_traits = queue_traits.SetCanBeFrozen(value);
+ ApplyQueueTraitsToSpec();
+ return *this;
+ }
+
+ QueueCreationParams SetCanRunInBackground(bool value) {
+ queue_traits = queue_traits.SetCanRunInBackground(value);
+ ApplyQueueTraitsToSpec();
return *this;
}
QueueCreationParams SetQueueTraits(QueueTraits value) {
queue_traits = value;
+ ApplyQueueTraitsToSpec();
return *this;
}
@@ -220,6 +240,11 @@ class PLATFORM_EXPORT MainThreadTaskQueue
FrameSchedulerImpl* frame_scheduler;
QueueTraits queue_traits;
bool freeze_when_keep_active;
+
+ private:
+ void ApplyQueueTraitsToSpec() {
+ spec = spec.SetDelayedFencesAllowed(queue_traits.can_be_throttled);
+ }
};
~MainThreadTaskQueue() override;
@@ -241,6 +266,10 @@ class PLATFORM_EXPORT MainThreadTaskQueue
bool CanBeFrozen() const { return queue_traits_.can_be_frozen; }
+ bool CanRunInBackground() const {
+ return queue_traits_.can_run_in_background;
+ }
+
bool FreezeWhenKeepActive() const { return freeze_when_keep_active_; }
QueueTraits GetQueueTraits() const { return queue_traits_; }
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_unittest.cc
index c9fc34774ff..5bacaecdd33 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_unittest.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread.h"
#include <stddef.h>
#include <memory>
@@ -16,15 +16,19 @@
#include "base/test/simple_test_tick_clock.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
+#include "third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h"
namespace blink {
namespace scheduler {
// To avoid symbol collisions in jumbo builds.
-namespace webthread_impl_for_renderer_scheduler_unittest {
+namespace main_thread_unittest {
const int kWorkBatchSize = 2;
+using ::testing::_;
+
class MockTask {
public:
MOCK_METHOD0(Run, void());
@@ -32,26 +36,29 @@ class MockTask {
class MockTaskObserver : public Thread::TaskObserver {
public:
- MOCK_METHOD0(WillProcessTask, void());
- MOCK_METHOD0(DidProcessTask, void());
+ MOCK_METHOD1(WillProcessTask, void(const base::PendingTask&));
+ MOCK_METHOD1(DidProcessTask, void(const base::PendingTask&));
};
-class WebThreadImplForRendererSchedulerTest : public testing::Test {
+class MainThreadTest : public testing::Test {
public:
- WebThreadImplForRendererSchedulerTest() = default;
+ MainThreadTest() = default;
void SetUp() override {
clock_.Advance(base::TimeDelta::FromMicroseconds(5000));
scheduler_.reset(new MainThreadSchedulerImpl(
base::sequence_manager::SequenceManagerForTest::Create(
- &message_loop_, message_loop_.task_runner(), &clock_),
+ message_loop_.GetMessageLoopBase(), message_loop_.task_runner(),
+ &clock_),
base::nullopt));
- thread_ = scheduler_->CreateMainThread();
+ scheduler_overrider_ =
+ std::make_unique<ScopedSchedulerOverrider>(scheduler_.get());
+ thread_ = Thread::Current();
}
- ~WebThreadImplForRendererSchedulerTest() override = default;
+ ~MainThreadTest() override = default;
- void SetWorkBatchSizeForTesting(size_t work_batch_size) {
+ void SetWorkBatchSizeForTesting(int work_batch_size) {
scheduler_->GetSchedulerHelperForTesting()->SetWorkBatchSizeForTesting(
work_batch_size);
}
@@ -62,21 +69,22 @@ class WebThreadImplForRendererSchedulerTest : public testing::Test {
base::MessageLoop message_loop_;
base::SimpleTestTickClock clock_;
std::unique_ptr<MainThreadSchedulerImpl> scheduler_;
- std::unique_ptr<Thread> thread_;
+ std::unique_ptr<ScopedSchedulerOverrider> scheduler_overrider_;
+ Thread* thread_;
- DISALLOW_COPY_AND_ASSIGN(WebThreadImplForRendererSchedulerTest);
+ DISALLOW_COPY_AND_ASSIGN(MainThreadTest);
};
-TEST_F(WebThreadImplForRendererSchedulerTest, TestTaskObserver) {
+TEST_F(MainThreadTest, TestTaskObserver) {
MockTaskObserver observer;
thread_->AddTaskObserver(&observer);
MockTask task;
{
testing::InSequence sequence;
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
}
message_loop_.task_runner()->PostTask(
@@ -85,7 +93,7 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestTaskObserver) {
thread_->RemoveTaskObserver(&observer);
}
-TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithOneTask) {
+TEST_F(MainThreadTest, TestWorkBatchWithOneTask) {
MockTaskObserver observer;
thread_->AddTaskObserver(&observer);
MockTask task;
@@ -93,9 +101,9 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithOneTask) {
SetWorkBatchSizeForTesting(kWorkBatchSize);
{
testing::InSequence sequence;
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
}
message_loop_.task_runner()->PostTask(
@@ -104,7 +112,7 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithOneTask) {
thread_->RemoveTaskObserver(&observer);
}
-TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithTwoTasks) {
+TEST_F(MainThreadTest, TestWorkBatchWithTwoTasks) {
MockTaskObserver observer;
thread_->AddTaskObserver(&observer);
MockTask task1;
@@ -113,13 +121,13 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithTwoTasks) {
SetWorkBatchSizeForTesting(kWorkBatchSize);
{
testing::InSequence sequence;
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task1, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task2, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
}
message_loop_.task_runner()->PostTask(
@@ -130,7 +138,7 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithTwoTasks) {
thread_->RemoveTaskObserver(&observer);
}
-TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithThreeTasks) {
+TEST_F(MainThreadTest, TestWorkBatchWithThreeTasks) {
MockTaskObserver observer;
thread_->AddTaskObserver(&observer);
MockTask task1;
@@ -140,17 +148,17 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithThreeTasks) {
SetWorkBatchSizeForTesting(kWorkBatchSize);
{
testing::InSequence sequence;
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task1, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task2, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
EXPECT_CALL(task3, Run());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
}
message_loop_.task_runner()->PostTask(
@@ -166,14 +174,13 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestWorkBatchWithThreeTasks) {
void EnterRunLoop(base::MessageLoop* message_loop, Thread* thread) {
// Note: blink::Threads do not support nested run loops, which is why we use a
// run loop directly.
- base::RunLoop run_loop;
+ base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
message_loop->task_runner()->PostTask(
FROM_HERE, WTF::Bind(&base::RunLoop::Quit, WTF::Unretained(&run_loop)));
- message_loop->SetNestableTasksAllowed(true);
run_loop.Run();
}
-TEST_F(WebThreadImplForRendererSchedulerTest, TestNestedRunLoop) {
+TEST_F(MainThreadTest, TestNestedRunLoop) {
MockTaskObserver observer;
thread_->AddTaskObserver(&observer);
@@ -181,23 +188,23 @@ TEST_F(WebThreadImplForRendererSchedulerTest, TestNestedRunLoop) {
testing::InSequence sequence;
// One callback for EnterRunLoop.
- EXPECT_CALL(observer, WillProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
// A pair for ExitRunLoopTask.
- EXPECT_CALL(observer, WillProcessTask());
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, WillProcessTask(_));
+ EXPECT_CALL(observer, DidProcessTask(_));
// A final callback for EnterRunLoop.
- EXPECT_CALL(observer, DidProcessTask());
+ EXPECT_CALL(observer, DidProcessTask(_));
}
message_loop_.task_runner()->PostTask(
FROM_HERE, base::BindOnce(&EnterRunLoop, base::Unretained(&message_loop_),
- base::Unretained(thread_.get())));
+ base::Unretained(thread_)));
base::RunLoop().RunUntilIdle();
thread_->RemoveTaskObserver(&observer);
}
-} // namespace webthread_impl_for_renderer_scheduler_unittest
+} // namespace main_thread_unittest
} // namespace scheduler
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h
index 175131defa3..7b277b061e1 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h
@@ -17,11 +17,11 @@
#include "base/time/time.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_visibility_state.h"
#include "third_party/blink/renderer/platform/scheduler/public/page_lifecycle_state.h"
#include "third_party/blink/renderer/platform/scheduler/public/page_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
namespace base {
namespace trace_event {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/prioritize_compositing_after_input_experiment.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/prioritize_compositing_after_input_experiment.cc
index efacf002661..3b660d33420 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/prioritize_compositing_after_input_experiment.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/prioritize_compositing_after_input_experiment.cc
@@ -6,7 +6,7 @@
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_number_conversions.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h"
@@ -21,9 +21,9 @@ constexpr const char kPrioritizeCompositingAfterInputTrial[] =
constexpr const char kNumberOfCompositingTasksToPrioritizeAfterInputParam[] =
"number_of_tasks";
-constexpr size_t kDefaultNumberOfTasksToPrioritizeAfterInput = 1;
+constexpr int kDefaultNumberOfTasksToPrioritizeAfterInput = 1;
-size_t GetNumberOfCompositingTasksToPrioritizeAfterInput() {
+int GetNumberOfCompositingTasksToPrioritizeAfterInput() {
if (!base::FeatureList::IsEnabled(kPrioritizeCompositingAfterInput))
return 0;
int number_of_tasks;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.cc
index 5bc2d976028..b879587cfd1 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.cc
@@ -4,12 +4,11 @@
#include "third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h"
+#include <algorithm>
+
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
-#include <algorithm>
-#include <map>
-
namespace blink {
namespace scheduler {
@@ -42,8 +41,8 @@ base::TimeDelta ExpectedQueueingTimeFromTask(base::TimeTicks task_start,
DCHECK_LE(task_start, task_end);
DCHECK_LE(task_start, step_end);
DCHECK_LT(step_start, step_end);
- // Because we skip steps when the renderer is backgrounded, we may have gone
- // into the future, and in that case we ignore this task completely.
+ // Because we skip steps when disabled, we may have gone into the future, and
+ // in that case we ignore this task completely.
if (task_end < step_start)
return base::TimeDelta();
@@ -67,10 +66,11 @@ base::TimeDelta ExpectedQueueingTimeFromTask(base::TimeTicks task_start,
QueueingTimeEstimator::QueueingTimeEstimator(Client* client,
base::TimeDelta window_duration,
- int steps_per_window)
+ int steps_per_window,
+ bool start_disabled)
: client_(client),
window_step_width_(window_duration / steps_per_window),
- renderer_backgrounded_(kLaunchingProcessIsBackgrounded),
+ disabled_(start_disabled),
calculator_(steps_per_window) {
DCHECK_GE(steps_per_window, 1);
}
@@ -91,13 +91,13 @@ void QueueingTimeEstimator::OnExecutionStopped(base::TimeTicks now) {
busy_period_start_time_ = base::TimeTicks();
}
-void QueueingTimeEstimator::OnRendererStateChanged(
- bool backgrounded,
+void QueueingTimeEstimator::OnRecordingStateChanged(
+ bool disabled,
base::TimeTicks transition_time) {
- DCHECK_NE(backgrounded, renderer_backgrounded_);
+ DCHECK_NE(disabled, disabled_);
if (!busy_)
AdvanceTime(transition_time);
- renderer_backgrounded_ = backgrounded;
+ disabled_ = disabled;
}
void QueueingTimeEstimator::AdvanceTime(base::TimeTicks current_time) {
@@ -110,11 +110,10 @@ void QueueingTimeEstimator::AdvanceTime(base::TimeTicks current_time) {
}
base::TimeTicks reference_time =
busy_ ? busy_period_start_time_ : step_start_time_;
- if (renderer_backgrounded_ ||
- current_time - reference_time > kInvalidPeriodThreshold) {
- // Skip steps when the renderer was backgrounded, when a task took too long,
- // or when we remained idle for too long. May cause |step_start_time_| to go
- // slightly into the future.
+ if (disabled_ || current_time - reference_time > kInvalidPeriodThreshold) {
+ // Skip steps when we're disabled, when a task took too long, or when we
+ // remained idle for too long. May cause |step_start_time_| to go slightly
+ // into the future.
// TODO(npm): crbug.com/776013. Base skipping long tasks/idling on a signal
// that we've been suspended.
step_start_time_ =
@@ -144,8 +143,7 @@ bool QueueingTimeEstimator::TimePastStepEnd(base::TimeTicks time) {
}
QueueingTimeEstimator::Calculator::Calculator(int steps_per_window)
- : steps_per_window_(steps_per_window),
- step_queueing_times_(steps_per_window) {}
+ : steps_per_window_(steps_per_window), sliding_window_(steps_per_window) {}
void QueueingTimeEstimator::Calculator::UpdateStatusFromTaskQueue(
MainThreadTaskQueue* queue) {
@@ -165,7 +163,7 @@ void QueueingTimeEstimator::Calculator::AddQueueingTime(
}
void QueueingTimeEstimator::Calculator::EndStep(Client* client) {
- step_queueing_times_.Add(step_expected_queueing_time_);
+ sliding_window_.Add(step_expected_queueing_time_);
DCHECK(client);
// MainThreadSchedulerImpl reports the queueing time once per disjoint window.
@@ -174,10 +172,10 @@ void QueueingTimeEstimator::Calculator::EndStep(Client* client) {
// Discard: |-------window EQT------|
// Discard: |-------window EQT------|
// Report: |-------window EQT------|
- client->OnQueueingTimeForWindowEstimated(step_queueing_times_.GetAverage(),
- step_queueing_times_.IndexIsZero());
+ client->OnQueueingTimeForWindowEstimated(sliding_window_.GetAverage(),
+ sliding_window_.IndexIsZero());
ResetStep();
- if (!step_queueing_times_.IndexIsZero())
+ if (!sliding_window_.IndexIsZero())
return;
// Report splits by task queue type.
@@ -248,13 +246,11 @@ void QueueingTimeEstimator::Calculator::ResetStep() {
step_expected_queueing_time_ = base::TimeDelta();
}
-QueueingTimeEstimator::RunningAverage::RunningAverage(int size) {
- circular_buffer_.resize(size);
- index_ = 0;
-}
+QueueingTimeEstimator::RunningAverage::RunningAverage(int size)
+ : index_(0), circular_buffer_(size), running_sum_() {}
int QueueingTimeEstimator::RunningAverage::GetStepsPerWindow() const {
- return circular_buffer_.size();
+ return static_cast<int>(circular_buffer_.size());
}
void QueueingTimeEstimator::RunningAverage::Add(base::TimeDelta bin_value) {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h
index f56ab52afa3..ec1d4da955c 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h
@@ -5,15 +5,14 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_QUEUEING_TIME_ESTIMATOR_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_QUEUEING_TIME_ESTIMATOR_H_
+#include <array>
+#include <vector>
+
#include "base/macros.h"
#include "base/time/time.h"
-#include "third_party/blink/public/common/page/launching_process_state.h"
#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_task_queue.h"
-
-#include <array>
-#include <vector>
+#include "third_party/blink/renderer/platform/scheduler/public/frame_status.h"
namespace blink {
namespace scheduler {
@@ -91,7 +90,7 @@ class PLATFORM_EXPORT QueueingTimeEstimator {
// In this case:
// |steps_per_window_| = 3, because each window is the length of 3 steps.
base::TimeDelta step_expected_queueing_time_;
- RunningAverage step_queueing_times_;
+ RunningAverage sliding_window_;
// Variables to split Expected Queueing Time by task queue type.
std::array<base::TimeDelta,
@@ -108,12 +107,12 @@ class PLATFORM_EXPORT QueueingTimeEstimator {
QueueingTimeEstimator(Client* client,
base::TimeDelta window_duration,
- int steps_per_window);
+ int steps_per_window,
+ bool start_disabled);
void OnExecutionStarted(base::TimeTicks now, MainThreadTaskQueue* queue);
void OnExecutionStopped(base::TimeTicks now);
- void OnRendererStateChanged(bool backgrounded,
- base::TimeTicks transition_time);
+ void OnRecordingStateChanged(bool disabled, base::TimeTicks transition_time);
private:
void AdvanceTime(base::TimeTicks current_time);
@@ -127,8 +126,8 @@ class PLATFORM_EXPORT QueueingTimeEstimator {
bool busy_ = false;
base::TimeTicks busy_period_start_time_;
- // |renderer_backgrounded_| is the renderer's current status.
- bool renderer_backgrounded_;
+ // |disabled_| is true iff we want to ignore start/stop events.
+ bool disabled_;
Calculator calculator_;
DISALLOW_ASSIGN(QueueingTimeEstimator);
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator_unittest.cc
index 780a929790d..1d435fa4f58 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator_unittest.cc
@@ -4,6 +4,10 @@
#include "third_party/blink/renderer/platform/scheduler/main_thread/queueing_time_estimator.h"
+#include <memory>
+#include <string>
+#include <vector>
+
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -14,10 +18,6 @@
#include "third_party/blink/renderer/platform/scheduler/test/test_queueing_time_estimator_client.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
-#include <map>
-#include <string>
-#include <vector>
-
namespace blink {
namespace scheduler {
@@ -195,8 +195,8 @@ TEST_F(QueueingTimeEstimatorTest, IgnoreExtremelyLongTasks) {
fine_grained);
}
-// If we idle for too long, ignore idling time, even if the renderer is on the
-// foreground. Perhaps the user's machine went to sleep while we were idling.
+// If we idle for too long, ignore idling time, even if the estimator is
+// enabled. Perhaps the user's machine went to sleep while we were idling.
TEST_F(QueueingTimeEstimatorTest, IgnoreExtremelyLongIdlePeriods) {
QueueingTimeEstimatorForTest estimator(
&client, base::TimeDelta::FromSeconds(5), 1, time);
@@ -405,9 +405,9 @@ TEST_F(QueueingTimeEstimatorTest,
}
// There are multiple windows, but some of the EQTs are not reported due to
-// backgrounded renderer. EQT(win1) = 0. EQT(win3) = (1500+500)/2 = 1000.
+// enabling/disabling. EQT(win1) = 0. EQT(win3) = (1500+500)/2 = 1000.
// EQT(win4) = 1/2*500/2 = 250. EQT(win7) = 1/5*200/2 = 20.
-TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithSingleStepPerWindow) {
+TEST_F(QueueingTimeEstimatorTest, DisabledEQTsWithSingleStepPerWindow) {
QueueingTimeEstimatorForTest estimator(
&client, base::TimeDelta::FromSeconds(1), 1, time);
time += base::TimeDelta::FromMilliseconds(1000);
@@ -416,12 +416,12 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithSingleStepPerWindow) {
time += base::TimeDelta::FromMilliseconds(1001);
// Second window should not be reported.
- estimator.OnRendererStateChanged(true, time);
+ estimator.OnRecordingStateChanged(true, time);
estimator.OnExecutionStarted(time, nullptr);
time += base::TimeDelta::FromMilliseconds(456);
estimator.OnExecutionStopped(time);
time += base::TimeDelta::FromMilliseconds(200);
- estimator.OnRendererStateChanged(false, time);
+ estimator.OnRecordingStateChanged(false, time);
time += base::TimeDelta::FromMilliseconds(343);
// Third, fourth windows should be reported
@@ -434,9 +434,9 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithSingleStepPerWindow) {
estimator.OnExecutionStarted(time, nullptr);
time += base::TimeDelta::FromMilliseconds(800);
estimator.OnExecutionStopped(time);
- estimator.OnRendererStateChanged(true, time);
+ estimator.OnRecordingStateChanged(true, time);
time += base::TimeDelta::FromMilliseconds(200);
- estimator.OnRendererStateChanged(false, time);
+ estimator.OnRecordingStateChanged(false, time);
estimator.OnExecutionStarted(time, nullptr);
time += base::TimeDelta::FromMilliseconds(999);
@@ -461,9 +461,9 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithSingleStepPerWindow) {
fine_grained);
}
-// We only ignore steps that contain some part that is backgrounded. Thus a
-// window could be made up of non-contiguous steps. The following are EQTs, with
-// time deltas with respect to the end of the first, 0-time task:
+// We only ignore steps that contain some time span that is disabled. Thus a
+// window could be made up of non-contiguous steps. The following are EQTs,
+// with time deltas with respect to the end of the first, 0-time task:
// Win1: [0-1000]. EQT of step [0-1000]: 500/2*1/2 = 125. EQT(win1) = 125/5 =
// 25.
// Win2: [0-1000],[2000-3000]. EQT of [2000-3000]: (1000+200)/2*4/5 = 480.
@@ -480,7 +480,7 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithSingleStepPerWindow) {
// EQT(win7) = (0+145+900+80+1680)/5 = 561.
// Win8: [12000-17000]. EQT of [16000-17000]: (1700+700)/2 = 1200. EQT(win8) =
// (145+900+80+1680+1200)/5 = 801.
-TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithMutipleStepsPerWindow) {
+TEST_F(QueueingTimeEstimatorTest, DisabledEQTsWithMutipleStepsPerWindow) {
QueueingTimeEstimatorForTest estimator(
&client, base::TimeDelta::FromSeconds(5), 5, time);
time += base::TimeDelta::FromMilliseconds(5000);
@@ -492,12 +492,12 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithMutipleStepsPerWindow) {
time += base::TimeDelta::FromMilliseconds(500);
estimator.OnExecutionStopped(time);
- estimator.OnRendererStateChanged(true, time);
+ estimator.OnRecordingStateChanged(true, time);
// This task should be ignored.
estimator.OnExecutionStarted(time, nullptr);
time += base::TimeDelta::FromMilliseconds(800);
estimator.OnExecutionStopped(time);
- estimator.OnRendererStateChanged(false, time);
+ estimator.OnRecordingStateChanged(false, time);
time += base::TimeDelta::FromMilliseconds(400);
estimator.OnExecutionStarted(time, nullptr);
@@ -505,7 +505,7 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithMutipleStepsPerWindow) {
estimator.OnExecutionStopped(time);
time += base::TimeDelta::FromMilliseconds(300);
- estimator.OnRendererStateChanged(true, time);
+ estimator.OnRecordingStateChanged(true, time);
time += base::TimeDelta::FromMilliseconds(2000);
// These tasks should be ignored.
estimator.OnExecutionStarted(time, nullptr);
@@ -514,7 +514,7 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithMutipleStepsPerWindow) {
estimator.OnExecutionStarted(time, nullptr);
time += base::TimeDelta::FromMilliseconds(3400);
estimator.OnExecutionStopped(time);
- estimator.OnRendererStateChanged(false, time);
+ estimator.OnRecordingStateChanged(false, time);
time += base::TimeDelta::FromMilliseconds(2000);
estimator.OnExecutionStarted(time, nullptr);
@@ -527,7 +527,7 @@ TEST_F(QueueingTimeEstimatorTest, BackgroundedEQTsWithMutipleStepsPerWindow) {
estimator.OnExecutionStopped(time);
// Window with last step should not be reported.
- estimator.OnRendererStateChanged(true, time);
+ estimator.OnRecordingStateChanged(true, time);
time += base::TimeDelta::FromMilliseconds(1000);
estimator.OnExecutionStarted(time, nullptr);
estimator.OnExecutionStopped(time);
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/render_widget_signals.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/render_widget_signals.h
index 453e3b69468..66742271a2c 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/render_widget_signals.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/render_widget_signals.h
@@ -8,7 +8,7 @@
#include <memory>
#include "base/trace_event/trace_event.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "third_party/blink/renderer/platform/platform_export.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc
index f81e030a917..75feaa7adfd 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/task_type_names.cc
@@ -117,6 +117,8 @@ const char* TaskTypeNames::TaskTypeToString(TaskType task_type) {
return "WorkerThreadTaskQueueCompositor";
case TaskType::kWorkerAnimation:
return "WorkerAnimation";
+ case TaskType::kInternalTranslation:
+ return "InternalTranslation";
case TaskType::kCount:
return "Count";
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/user_model.h b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/user_model.h
index 559a853e62d..32ad7b6ea74 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/main_thread/user_model.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/user_model.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "base/trace_event/trace_event.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/renderer/platform/platform_export.h"
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/web_scoped_virtual_time_pauser.cc b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/web_scoped_virtual_time_pauser.cc
index b3bd2a7e4ec..b3bd2a7e4ec 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/web_scoped_virtual_time_pauser.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/main_thread/web_scoped_virtual_time_pauser.cc
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/aggregated_metric_reporter.h b/chromium/third_party/blink/renderer/platform/scheduler/public/aggregated_metric_reporter.h
index 9e4e423e954..a705015c64b 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/aggregated_metric_reporter.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/aggregated_metric_reporter.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_AGGREGATED_METRIC_REPORTER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_AGGREGATED_METRIC_REPORTER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_AGGREGATED_METRIC_REPORTER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_AGGREGATED_METRIC_REPORTER_H_
#include <array>
@@ -86,4 +86,4 @@ class AggregatedMetricReporter {
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_AGGREGATED_METRIC_REPORTER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_AGGREGATED_METRIC_REPORTER_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/public/background_scheduler.h b/chromium/third_party/blink/renderer/platform/scheduler/public/background_scheduler.h
index 8139d02ab36..f11c9446149 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/public/background_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/background_scheduler.h
@@ -13,7 +13,7 @@
namespace blink {
-namespace BackgroundScheduler {
+namespace background_scheduler {
// These are a thin wrapper around base::TaskScheduler to accomodate
// Blink's CrossThreadClosure, which only allows background tasks
@@ -31,7 +31,7 @@ PLATFORM_EXPORT void PostOnBackgroundThreadWithTraits(const base::Location&,
// TODO(altimin): Expose CreateBackgroundTaskRunnerWithTraits when the
// need arises.
-} // namespace BackgroundScheduler
+} // namespace background_scheduler
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/frame_status.h b/chromium/third_party/blink/renderer/platform/scheduler/public/frame_status.h
index d1dfdc80741..a7dbd98232e 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/frame_status.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/frame_status.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_RENDERER_FRAME_STATUS_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_RENDERER_FRAME_STATUS_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_FRAME_STATUS_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_FRAME_STATUS_H_
#include "third_party/blink/renderer/platform/platform_export.h"
@@ -82,4 +82,4 @@ PLATFORM_EXPORT FrameStatus GetFrameStatus(FrameScheduler* frame_scheduler);
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_RENDERER_FRAME_STATUS_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_FRAME_STATUS_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h b/chromium/third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h
new file mode 100644
index 00000000000..585c28f1ab5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h
@@ -0,0 +1,75 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_POST_CANCELLABLE_TASK_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_POST_CANCELLABLE_TASK_H_
+
+#include "base/callback.h"
+#include "base/compiler_specific.h"
+#include "base/location.h"
+#include "base/memory/scoped_refptr.h"
+#include "base/sequenced_task_runner.h"
+#include "base/time/time.h"
+#include "third_party/blink/renderer/platform/platform_export.h"
+
+namespace blink {
+
+// TaskHandle is associated to a task posted by PostCancellableTask() or
+// PostCancellableDelayedTask() and cancels the associated task on
+// TaskHandle::cancel() call or on TaskHandle destruction.
+class PLATFORM_EXPORT TaskHandle {
+ public:
+ class Runner;
+
+ TaskHandle();
+ ~TaskHandle();
+
+ TaskHandle(TaskHandle&&);
+ TaskHandle& operator=(TaskHandle&&);
+
+ // Returns true if the task will run later. Returns false if the task is
+ // cancelled or the task is run already.
+ // This function is not thread safe. Call this on the thread that has posted
+ // the task.
+ bool IsActive() const;
+
+ // Cancels the task invocation. Do nothing if the task is cancelled or run
+ // already.
+ // This function is not thread safe. Call this on the thread that has posted
+ // the task.
+ void Cancel();
+
+ private:
+ TaskHandle(const TaskHandle&) = delete;
+ TaskHandle& operator=(const TaskHandle&) = delete;
+
+ friend PLATFORM_EXPORT TaskHandle
+ PostCancellableTask(base::SequencedTaskRunner&,
+ const base::Location&,
+ base::OnceClosure) WARN_UNUSED_RESULT;
+ friend PLATFORM_EXPORT TaskHandle
+ PostDelayedCancellableTask(base::SequencedTaskRunner&,
+ const base::Location&,
+ base::OnceClosure,
+ base::TimeDelta delay) WARN_UNUSED_RESULT;
+
+ explicit TaskHandle(scoped_refptr<Runner>);
+ scoped_refptr<Runner> runner_;
+};
+
+// For same-thread cancellable task posting. Returns a TaskHandle object for
+// cancellation.
+PLATFORM_EXPORT TaskHandle PostCancellableTask(base::SequencedTaskRunner&,
+ const base::Location&,
+ base::OnceClosure)
+ WARN_UNUSED_RESULT;
+PLATFORM_EXPORT TaskHandle
+PostDelayedCancellableTask(base::SequencedTaskRunner&,
+ const base::Location&,
+ base::OnceClosure,
+ base::TimeDelta delay) WARN_UNUSED_RESULT;
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_POST_CANCELLABLE_TASK_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h b/chromium/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h
new file mode 100644
index 00000000000..f40cf477054
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h
@@ -0,0 +1,28 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_POST_CROSS_THREAD_TASK_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_POST_CROSS_THREAD_TASK_H_
+
+#include "base/location.h"
+#include "base/sequenced_task_runner.h"
+#include "base/time/time.h"
+#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
+
+namespace blink {
+
+// For cross-thread posting. Can be called from any thread.
+PLATFORM_EXPORT void PostCrossThreadTask(base::SequencedTaskRunner&,
+ const base::Location&,
+ WTF::CrossThreadClosure);
+
+PLATFORM_EXPORT void PostDelayedCrossThreadTask(base::SequencedTaskRunner&,
+ const base::Location&,
+ WTF::CrossThreadClosure,
+ base::TimeDelta delay);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_POST_CROSS_THREAD_TASK_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/public/thread.h b/chromium/third_party/blink/renderer/platform/scheduler/public/thread.h
index 61f99d154b5..07747576fa8 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/public/thread.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/thread.h
@@ -27,6 +27,7 @@
#include <stdint.h>
#include "base/callback_forward.h"
+#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/threading/thread.h"
#include "third_party/blink/public/platform/web_thread_type.h"
@@ -70,17 +71,42 @@ struct PLATFORM_EXPORT ThreadCreationParams {
// run.
class PLATFORM_EXPORT Thread {
public:
- friend class Platform; // For IsSimpleMainThread().
+ friend class Platform; // For SetMainThread() and IsSimpleMainThread().
+ friend class ScopedMainThreadOverrider; // For SetMainThread().
// An IdleTask is expected to complete before the deadline it is passed.
using IdleTask = base::OnceCallback<void(base::TimeTicks deadline)>;
- class PLATFORM_EXPORT TaskObserver {
- public:
- virtual ~TaskObserver() = default;
- virtual void WillProcessTask() = 0;
- virtual void DidProcessTask() = 0;
- };
+ // TaskObserver is an observer fired before and after a task is executed.
+ using TaskObserver = base::MessageLoop::TaskObserver;
+
+ // Creates a new thread. This may be called from a non-main thread (e.g.
+ // nested Web workers).
+ static std::unique_ptr<Thread> CreateThread(const ThreadCreationParams&);
+
+ // Creates a WebAudio-specific thread with the elevated priority. Do NOT use
+ // for any other purpose.
+ static std::unique_ptr<Thread> CreateWebAudioThread();
+
+ // Create and save (as a global variable) the compositor thread. The thread
+ // will be accessible through CompositorThread().
+ static void CreateAndSetCompositorThread();
+
+ // Return an interface to the current thread.
+ static Thread* Current();
+
+ // Return an interface to the main thread.
+ static Thread* MainThread();
+
+ // Return an interface to the compositor thread (if initialized). This can be
+ // null if the renderer was created with threaded rendering disabled.
+ static Thread* CompositorThread();
+
+ Thread();
+ virtual ~Thread();
+
+ // Must be called immediately after the construction.
+ virtual void Init() {}
// DEPRECATED: Returns a task runner bound to the underlying scheduler's
// default task queue.
@@ -92,16 +118,16 @@ class PLATFORM_EXPORT Thread {
return nullptr;
}
- virtual bool IsCurrentThread() const = 0;
+ bool IsCurrentThread() const;
virtual PlatformThreadId ThreadId() const { return 0; }
// TaskObserver is an object that receives task notifications from the
- // MessageLoop
+ // MessageLoop.
// NOTE: TaskObserver implementation should be extremely fast!
// This API is performance sensitive. Use only if you have a compelling
// reason.
- virtual void AddTaskObserver(TaskObserver*) {}
- virtual void RemoveTaskObserver(TaskObserver*) {}
+ void AddTaskObserver(TaskObserver*);
+ void RemoveTaskObserver(TaskObserver*);
// TaskTimeObserver is an object that receives notifications for
// CPU time spent in each top-level MessageLoop task.
@@ -115,12 +141,19 @@ class PLATFORM_EXPORT Thread {
// Returns the scheduler associated with the thread.
virtual ThreadScheduler* Scheduler() = 0;
- virtual ~Thread() = default;
-
private:
+ // For Platform and ScopedMainThreadOverrider. Return the thread object
+ // previously set (if any).
+ //
+ // This is done this way because we need to be able to "override" the main
+ // thread temporarily for ScopedTestingPlatformSupport.
+ static std::unique_ptr<Thread> SetMainThread(std::unique_ptr<Thread>);
+
// This is used to identify the actual Thread instance. This should be
// used only in Platform, and other users should ignore this.
virtual bool IsSimpleMainThread() const { return false; }
+
+ DISALLOW_COPY_AND_ASSIGN(Thread);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.h b/chromium/third_party/blink/renderer/platform/scheduler/public/thread_cpu_throttler.h
index 95c5c4ca1f5..6f02b7ad1cb 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/util/thread_cpu_throttler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/thread_cpu_throttler.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_THREAD_CPU_THROTTLER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_THREAD_CPU_THROTTLER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_THREAD_CPU_THROTTLER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_THREAD_CPU_THROTTLER_H_
#include <memory>
@@ -46,4 +46,4 @@ class PLATFORM_EXPORT ThreadCPUThrottler final {
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_UTIL_THREAD_CPU_THROTTLER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_PUBLIC_THREAD_CPU_THROTTLER_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h b/chromium/third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h
index 8cdc688ec05..6e979d5c859 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h
@@ -28,9 +28,6 @@ class PLATFORM_EXPORT ThreadScheduler {
scheduler::WebThreadScheduler::RendererPauseHandle;
// Return the current thread's ThreadScheduler.
- //
- // TODO(yutak): Replace all the "Platform::Current()->CurrentThread()
- // ->Scheduler()" calls in Blink with this.
static ThreadScheduler* Current();
virtual ~ThreadScheduler() = default;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/DEPS b/chromium/third_party/blink/renderer/platform/scheduler/renderer/DEPS
deleted file mode 100644
index e6bf2b837da..00000000000
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/DEPS
+++ /dev/null
@@ -1,8 +0,0 @@
-include_rules = [
- "+base/metrics/single_sample_metrics.h",
- "+cc",
- "+components/viz/common",
- "+services/resource_coordinator/public/cpp/resource_coordinator_features.h",
- "+third_party/blink/renderer/platform/scheduler/base",
- "+third_party/blink/renderer/platform/scheduler/child",
-]
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.cc
deleted file mode 100644
index 541e3c284e8..00000000000
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.cc
+++ /dev/null
@@ -1,59 +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 "third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h"
-
-#include "base/location.h"
-#include "base/task/sequence_manager/task_queue.h"
-#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
-
-namespace blink {
-namespace scheduler {
-
-WebThreadImplForRendererScheduler::WebThreadImplForRendererScheduler(
- MainThreadSchedulerImpl* scheduler)
- : task_runner_(scheduler->DefaultTaskRunner()),
- scheduler_(scheduler),
- thread_id_(base::PlatformThread::CurrentId()) {}
-
-WebThreadImplForRendererScheduler::~WebThreadImplForRendererScheduler() =
- default;
-
-blink::PlatformThreadId WebThreadImplForRendererScheduler::ThreadId() const {
- return thread_id_;
-}
-
-blink::ThreadScheduler* WebThreadImplForRendererScheduler::Scheduler() {
- return scheduler_;
-}
-
-scoped_refptr<base::SingleThreadTaskRunner>
-WebThreadImplForRendererScheduler::GetTaskRunner() const {
- return task_runner_;
-}
-
-void WebThreadImplForRendererScheduler::AddTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) {
- scheduler_->AddTaskObserver(observer);
-}
-
-void WebThreadImplForRendererScheduler::RemoveTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) {
- scheduler_->RemoveTaskObserver(observer);
-}
-
-void WebThreadImplForRendererScheduler::AddTaskTimeObserverInternal(
- base::sequence_manager::TaskTimeObserver* task_time_observer) {
- scheduler_->AddTaskTimeObserver(task_time_observer);
-}
-
-void WebThreadImplForRendererScheduler::RemoveTaskTimeObserverInternal(
- base::sequence_manager::TaskTimeObserver* task_time_observer) {
- scheduler_->RemoveTaskTimeObserver(task_time_observer);
-}
-
-void WebThreadImplForRendererScheduler::Init() {}
-
-} // namespace scheduler
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h b/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h
deleted file mode 100644
index 2bf7bd1b2ec..00000000000
--- a/chromium/third_party/blink/renderer/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_RENDERER_WEBTHREAD_IMPL_FOR_RENDERER_SCHEDULER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_RENDERER_WEBTHREAD_IMPL_FOR_RENDERER_SCHEDULER_H_
-
-#include "base/memory/scoped_refptr.h"
-#include "base/message_loop/message_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
-
-namespace blink {
-class ThreadScheduler;
-};
-
-namespace blink {
-namespace scheduler {
-class MainThreadSchedulerImpl;
-
-class PLATFORM_EXPORT WebThreadImplForRendererScheduler : public WebThreadBase {
- public:
- explicit WebThreadImplForRendererScheduler(
- MainThreadSchedulerImpl* scheduler);
- ~WebThreadImplForRendererScheduler() override;
-
- // WebThread implementation.
- ThreadScheduler* Scheduler() override;
- PlatformThreadId ThreadId() const override;
- scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() const override;
-
- // WebThreadBase implementation.
- void Init() override;
-
- private:
- void AddTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) override;
- void RemoveTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) override;
-
- void AddTaskTimeObserverInternal(
- base::sequence_manager::TaskTimeObserver*) override;
- void RemoveTaskTimeObserverInternal(
- base::sequence_manager::TaskTimeObserver*) override;
-
- scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
- MainThreadSchedulerImpl* scheduler_; // Not owned.
- PlatformThreadId thread_id_;
-};
-
-} // namespace scheduler
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_RENDERER_WEBTHREAD_IMPL_FOR_RENDERER_SCHEDULER_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.cc
new file mode 100644
index 00000000000..0236b1f5073
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.cc
@@ -0,0 +1,25 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/scheduler/worker/compositor_thread.h"
+
+#include "base/task/sequence_manager/sequence_manager.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h"
+
+namespace blink {
+namespace scheduler {
+
+CompositorThread::CompositorThread(const ThreadCreationParams& params)
+ : WorkerThread(params) {}
+
+CompositorThread::~CompositorThread() = default;
+
+std::unique_ptr<NonMainThreadSchedulerImpl>
+CompositorThread::CreateNonMainThreadScheduler() {
+ return std::make_unique<CompositorThreadScheduler>(
+ base::sequence_manager::CreateSequenceManagerOnCurrentThread());
+}
+
+} // namespace scheduler
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.h
new file mode 100644
index 00000000000..d6c7025a9c5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread.h
@@ -0,0 +1,29 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_WORKER_COMPOSITOR_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_WORKER_COMPOSITOR_THREAD_H_
+
+#include "base/macros.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
+
+namespace blink {
+namespace scheduler {
+
+class PLATFORM_EXPORT CompositorThread : public WorkerThread {
+ public:
+ explicit CompositorThread(const ThreadCreationParams& params);
+ ~CompositorThread() override;
+
+ private:
+ std::unique_ptr<NonMainThreadSchedulerImpl> CreateNonMainThreadScheduler()
+ override;
+
+ DISALLOW_COPY_AND_ASSIGN(CompositorThread);
+};
+
+} // namespace scheduler
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_WORKER_COMPOSITOR_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.cc
index a500417f1e9..6ce154ec620 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.cc
@@ -13,7 +13,7 @@
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "third_party/blink/public/platform/task_type.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
#include "third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h
index 1a2ca366b24..edbe9ad65a3 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler.h
@@ -9,9 +9,9 @@
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "components/scheduling_metrics/task_duration_metric_reporter.h"
-#include "third_party/blink/public/platform/scheduler/single_thread_idle_task_runner.h"
#include "third_party/blink/public/platform/web_thread_type.h"
#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h"
#include "third_party/blink/renderer/platform/scheduler/worker/compositor_metrics_helper.h"
#include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h"
@@ -36,8 +36,6 @@ class PLATFORM_EXPORT CompositorThreadScheduler
task_timing) override;
// WebThreadScheduler:
- scoped_refptr<scheduler::SingleThreadIdleTaskRunner> IdleTaskRunner()
- override;
scoped_refptr<base::SingleThreadTaskRunner> V8TaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> CompositorTaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> IPCTaskRunner() override;
@@ -50,6 +48,10 @@ class PLATFORM_EXPORT CompositorThreadScheduler
void AddRAILModeObserver(WebRAILModeObserver*) override {}
void Shutdown() override;
+ // ThreadSchedulerImpl:
+ scoped_refptr<scheduler::SingleThreadIdleTaskRunner> IdleTaskRunner()
+ override;
+
// SingleThreadIdleTaskRunner::Delegate:
void OnIdleTaskPosted() override;
base::TimeTicks WillProcessIdleTask() override;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler_unittest.cc
index 2aaf26be5d6..c5c61ff1b56 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/compositor_thread_scheduler_unittest.cc
@@ -11,7 +11,7 @@
#include "base/test/test_mock_time_task_runner.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
using testing::ElementsAreArray;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.cc
index 85b34bde904..906c538f053 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.cc
@@ -51,7 +51,7 @@ scoped_refptr<TaskQueue> NonMainThreadSchedulerHelper::ControlTaskQueue() {
scoped_refptr<NonMainThreadTaskQueue>
NonMainThreadSchedulerHelper::NewTaskQueue(const TaskQueue::Spec& spec) {
- return sequence_manager_->CreateTaskQueue<NonMainThreadTaskQueue>(
+ return sequence_manager_->CreateTaskQueueWithType<NonMainThreadTaskQueue>(
spec, non_main_thread_scheduler_);
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h
index a06d242c2c1..1edbe7cee79 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h
@@ -9,13 +9,13 @@
#include "base/macros.h"
#include "base/task/sequence_manager/task_queue.h"
-#include "third_party/blink/public/platform/scheduler/single_thread_idle_task_runner.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
#include "third_party/blink/public/platform/web_thread_type.h"
#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/renderer/platform/scheduler/common/single_thread_idle_task_runner.h"
#include "third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h"
+#include "third_party/blink/renderer/platform/scheduler/common/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/util/tracing_helper.h"
#include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.h"
#include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.h"
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.cc
index fdf08d5c51b..2ba5085b2fc 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.cc
@@ -17,7 +17,7 @@ NonMainThreadTaskQueue::NonMainThreadTaskQueue(
NonMainThreadSchedulerImpl* non_main_thread_scheduler)
: TaskQueue(std::move(impl), spec),
non_main_thread_scheduler_(non_main_thread_scheduler) {
- if (GetTaskQueueImpl()) {
+ if (GetTaskQueueImpl() && spec.should_notify_observers) {
// TaskQueueImpl may be null for tests.
GetTaskQueueImpl()->SetOnTaskCompletedHandler(base::BindRepeating(
&NonMainThreadTaskQueue::OnTaskCompleted, base::Unretained(this)));
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.cc
index 71bd7ae35af..553db17d9e2 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h"
-#include "third_party/blink/renderer/platform/scheduler/child/process_state.h"
+#include "third_party/blink/renderer/platform/scheduler/common/process_state.h"
namespace blink {
namespace scheduler {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h
index d4a15356eec..56db0582bd0 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h
@@ -7,8 +7,8 @@
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/platform/scheduler/common/metrics_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_origin_type.h"
-#include "third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h"
#include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_task_queue.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc
index ab18ef47802..32e376914ee 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler.cc
@@ -147,6 +147,7 @@ scoped_refptr<base::SingleThreadTaskRunner> WorkerScheduler::GetTaskRunner(
case TaskType::kWorkerThreadTaskQueueCompositor:
case TaskType::kExperimentalWebSchedulingUserInteraction:
case TaskType::kExperimentalWebSchedulingBestEffort:
+ case TaskType::kInternalTranslation:
case TaskType::kCount:
NOTREACHED();
break;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h
index 60ed4b64263..f0ebe2114a9 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy.h
@@ -16,7 +16,7 @@
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_origin_type.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_or_worker_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/renderer/frame_status.h"
+#include "third_party/blink/renderer/platform/scheduler/public/frame_status.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc
index 036af44a138..62706fe7d47 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_scheduler_proxy_unittest.cc
@@ -8,11 +8,11 @@
#include "base/test/scoped_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
@@ -45,24 +45,22 @@ class WorkerThreadSchedulerForTest : public WorkerThreadScheduler {
WaitableEvent* throtting_state_changed_;
};
-class WebThreadImplForWorkerSchedulerForTest
- : public WebThreadImplForWorkerScheduler {
+class WorkerThreadForTest : public WorkerThread {
public:
- WebThreadImplForWorkerSchedulerForTest(FrameScheduler* frame_scheduler,
- WaitableEvent* throtting_state_changed)
- : WebThreadImplForWorkerScheduler(
- ThreadCreationParams(WebThreadType::kTestThread)
- .SetFrameOrWorkerScheduler(frame_scheduler)),
+ WorkerThreadForTest(FrameScheduler* frame_scheduler,
+ WaitableEvent* throtting_state_changed)
+ : WorkerThread(ThreadCreationParams(WebThreadType::kTestThread)
+ .SetFrameOrWorkerScheduler(frame_scheduler)),
throtting_state_changed_(throtting_state_changed) {}
- ~WebThreadImplForWorkerSchedulerForTest() override {
+ ~WorkerThreadForTest() override {
base::WaitableEvent completion(
base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
thread_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&WebThreadImplForWorkerSchedulerForTest::
- DisposeWorkerSchedulerOnThread,
- base::Unretained(this), &completion));
+ FROM_HERE,
+ base::BindOnce(&WorkerThreadForTest::DisposeWorkerSchedulerOnThread,
+ base::Unretained(this), &completion));
completion.Wait();
}
@@ -94,12 +92,11 @@ class WebThreadImplForWorkerSchedulerForTest
std::unique_ptr<WorkerScheduler> worker_scheduler_ = nullptr;
};
-std::unique_ptr<WebThreadImplForWorkerSchedulerForTest> CreateWorkerThread(
+std::unique_ptr<WorkerThreadForTest> CreateWorkerThread(
FrameScheduler* frame_scheduler,
WaitableEvent* throtting_state_changed) {
- std::unique_ptr<WebThreadImplForWorkerSchedulerForTest> thread =
- std::make_unique<WebThreadImplForWorkerSchedulerForTest>(
- frame_scheduler, throtting_state_changed);
+ auto thread = std::make_unique<WorkerThreadForTest>(frame_scheduler,
+ throtting_state_changed);
thread->Init();
return thread;
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread.cc
index 040992c2c41..be6f9cf3171 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread.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 "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
#include <memory>
#include "base/bind.h"
@@ -18,8 +18,7 @@
namespace blink {
namespace scheduler {
-WebThreadImplForWorkerScheduler::WebThreadImplForWorkerScheduler(
- const ThreadCreationParams& params)
+WorkerThread::WorkerThread(const ThreadCreationParams& params)
: thread_(new base::Thread(params.name ? params.name : std::string())),
thread_type_(params.thread_type),
worker_scheduler_proxy_(params.frame_or_worker_scheduler
@@ -31,17 +30,17 @@ WebThreadImplForWorkerScheduler::WebThreadImplForWorkerScheduler(
thread_task_runner_ = thread_->task_runner();
}
-void WebThreadImplForWorkerScheduler::Init() {
+void WorkerThread::Init() {
base::WaitableEvent completion(
base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
thread_task_runner_->PostTask(
- FROM_HERE, base::BindOnce(&WebThreadImplForWorkerScheduler::InitOnThread,
+ FROM_HERE, base::BindOnce(&WorkerThread::InitOnThread,
base::Unretained(this), &completion));
completion.Wait();
}
-WebThreadImplForWorkerScheduler::~WebThreadImplForWorkerScheduler() {
+WorkerThread::~WorkerThread() {
// We want to avoid blocking main thread when the thread was already
// shut down, but calling ShutdownOnThread twice does not cause any problems.
if (!was_shutdown_on_thread_.IsSet()) {
@@ -49,16 +48,14 @@ WebThreadImplForWorkerScheduler::~WebThreadImplForWorkerScheduler() {
base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED);
thread_task_runner_->PostTask(
- FROM_HERE,
- base::BindOnce(&WebThreadImplForWorkerScheduler::ShutdownOnThread,
- base::Unretained(this), &completion));
+ FROM_HERE, base::BindOnce(&WorkerThread::ShutdownOnThread,
+ base::Unretained(this), &completion));
completion.Wait();
}
thread_->Stop();
}
-void WebThreadImplForWorkerScheduler::InitOnThread(
- base::WaitableEvent* completion) {
+void WorkerThread::InitOnThread(base::WaitableEvent* completion) {
// TODO(alexclarke): Do we need to unify virtual time for workers and the
// main thread?
non_main_thread_scheduler_ = CreateNonMainThreadScheduler();
@@ -70,8 +67,7 @@ void WebThreadImplForWorkerScheduler::InitOnThread(
completion->Signal();
}
-void WebThreadImplForWorkerScheduler::ShutdownOnThread(
- base::WaitableEvent* completion) {
+void WorkerThread::ShutdownOnThread(base::WaitableEvent* completion) {
was_shutdown_on_thread_.Set();
task_queue_ = nullptr;
@@ -83,37 +79,27 @@ void WebThreadImplForWorkerScheduler::ShutdownOnThread(
}
std::unique_ptr<NonMainThreadSchedulerImpl>
-WebThreadImplForWorkerScheduler::CreateNonMainThreadScheduler() {
+WorkerThread::CreateNonMainThreadScheduler() {
return NonMainThreadSchedulerImpl::Create(thread_type_,
worker_scheduler_proxy_.get());
}
-void WebThreadImplForWorkerScheduler::WillDestroyCurrentMessageLoop() {
+void WorkerThread::WillDestroyCurrentMessageLoop() {
ShutdownOnThread(nullptr);
}
-blink::PlatformThreadId WebThreadImplForWorkerScheduler::ThreadId() const {
+blink::PlatformThreadId WorkerThread::ThreadId() const {
return thread_->GetThreadId();
}
-blink::ThreadScheduler* WebThreadImplForWorkerScheduler::Scheduler() {
+blink::ThreadScheduler* WorkerThread::Scheduler() {
return non_main_thread_scheduler_.get();
}
-scoped_refptr<base::SingleThreadTaskRunner>
-WebThreadImplForWorkerScheduler::GetTaskRunner() const {
+scoped_refptr<base::SingleThreadTaskRunner> WorkerThread::GetTaskRunner()
+ const {
return task_runner_;
}
-void WebThreadImplForWorkerScheduler::AddTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) {
- non_main_thread_scheduler_->AddTaskObserver(observer);
-}
-
-void WebThreadImplForWorkerScheduler::RemoveTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) {
- non_main_thread_scheduler_->RemoveTaskObserver(observer);
-}
-
} // namespace scheduler
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread.h
index 893889be302..811bef15fc4 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread.h
@@ -2,16 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_WEBTHREAD_IMPL_FOR_WORKER_SCHEDULER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_WEBTHREAD_IMPL_FOR_WORKER_SCHEDULER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_WORKER_WORKER_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_WORKER_WORKER_THREAD_H_
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_current.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/atomic_flag.h"
#include "base/threading/thread.h"
-#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
#include "third_party/blink/public/platform/web_private_ptr.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
namespace base {
class WaitableEvent;
@@ -28,21 +28,25 @@ class NonMainThreadSchedulerImpl;
class NonMainThreadTaskQueue;
class WorkerSchedulerProxy;
-class PLATFORM_EXPORT WebThreadImplForWorkerScheduler
- : public WebThreadBase,
+// Thread implementation for a thread created by Blink. Although the name says
+// "worker", the thread represented by this class is used not only for Web
+// Workers but for many other use cases, like for WebAudio, Web Database, etc.
+//
+// TODO(yutak): This could be a misnomer, as we already have WorkerThread in
+// core/ (though this is under blink::scheduler namespace).
+class PLATFORM_EXPORT WorkerThread
+ : public Thread,
public base::MessageLoopCurrent::DestructionObserver {
public:
- explicit WebThreadImplForWorkerScheduler(const ThreadCreationParams& params);
- ~WebThreadImplForWorkerScheduler() override;
+ explicit WorkerThread(const ThreadCreationParams& params);
+ ~WorkerThread() override;
// Thread implementation.
+ void Init() override;
ThreadScheduler* Scheduler() override;
PlatformThreadId ThreadId() const override;
scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() const override;
- // WebThreadBase implementation.
- void Init() override;
-
// base::MessageLoopCurrent::DestructionObserver implementation.
void WillDestroyCurrentMessageLoop() override;
@@ -64,11 +68,6 @@ class PLATFORM_EXPORT WebThreadImplForWorkerScheduler
scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner_;
private:
- void AddTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) override;
- void RemoveTaskObserverInternal(
- base::MessageLoop::TaskObserver* observer) override;
-
void InitOnThread(base::WaitableEvent* completion);
void ShutdownOnThread(base::WaitableEvent* completion);
@@ -86,4 +85,4 @@ class PLATFORM_EXPORT WebThreadImplForWorkerScheduler
} // namespace scheduler
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_CHILD_WEBTHREAD_IMPL_FOR_WORKER_SCHEDULER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_WORKER_WORKER_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.cc
index e031d0f4763..cfb3395b38d 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.cc
@@ -14,12 +14,12 @@
#include "base/task/sequence_manager/task_queue.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
-#include "base/trace_event/trace_event_argument.h"
+#include "base/trace_event/traced_value.h"
#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/scheduler/child/features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/process_state.h"
+#include "third_party/blink/renderer/platform/scheduler/common/features.h"
+#include "third_party/blink/renderer/platform/scheduler/common/process_state.h"
#include "third_party/blink/renderer/platform/scheduler/common/throttling/task_queue_throttler.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_helper.h"
@@ -206,6 +206,7 @@ void WorkerThreadScheduler::Shutdown() {
"WorkerThread.Runtime", delta, base::TimeDelta::FromSeconds(1),
base::TimeDelta::FromDays(1), 50 /* bucket count */);
task_queue_throttler_.reset();
+ idle_helper_.Shutdown();
helper()->Shutdown();
}
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h
index 3ddbe4d0f88..c09cf5b27af 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h
@@ -13,9 +13,9 @@
#include "third_party/blink/public/platform/web_thread_type.h"
#include "third_party/blink/renderer/platform/scheduler/common/idle_canceled_delayed_task_sweeper.h"
#include "third_party/blink/renderer/platform/scheduler/common/idle_helper.h"
+#include "third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
-#include "third_party/blink/renderer/platform/scheduler/renderer/frame_status.h"
-#include "third_party/blink/renderer/platform/scheduler/util/thread_load_tracker.h"
+#include "third_party/blink/renderer/platform/scheduler/public/frame_status.h"
#include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_metrics_helper.h"
@@ -54,7 +54,6 @@ class PLATFORM_EXPORT WorkerThreadScheduler
~WorkerThreadScheduler() override;
// WebThreadScheduler implementation:
- scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> V8TaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> CompositorTaskRunner() override;
scoped_refptr<base::SingleThreadTaskRunner> IPCTaskRunner() override;
@@ -66,6 +65,9 @@ class PLATFORM_EXPORT WorkerThreadScheduler
void AddRAILModeObserver(WebRAILModeObserver*) override {}
void Shutdown() override;
+ // ThreadSchedulerImpl implementation:
+ scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() override;
+
// NonMainThreadSchedulerImpl implementation:
scoped_refptr<NonMainThreadTaskQueue> DefaultTaskQueue() override;
void OnTaskCompleted(NonMainThreadTaskQueue* worker_task_queue,
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler_unittest.cc
index acf14e73e09..44ca277719a 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler_unittest.cc
@@ -13,7 +13,7 @@
#include "components/ukm/test_ukm_recorder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/scheduler/child/process_state.h"
+#include "third_party/blink/renderer/platform/scheduler/common/process_state.h"
#include "third_party/blink/renderer/platform/scheduler/test/fake_frame_scheduler.h"
using testing::ElementsAreArray;
diff --git a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler_unittest.cc b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc
index 95c2a1bcf9c..0862bdfd143 100644
--- a/chromium/third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler_unittest.cc
+++ b/chromium/third_party/blink/renderer/platform/scheduler/worker/worker_thread_unittest.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
#include "base/location.h"
#include "base/macros.h"
@@ -10,8 +10,8 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
using testing::_;
using testing::AnyOf;
@@ -20,7 +20,7 @@ using testing::Invoke;
namespace blink {
namespace scheduler {
-namespace webthread_impl_for_worker_scheduler_unittest {
+namespace worker_thread_unittest {
class MockTask {
public:
@@ -38,9 +38,13 @@ class TestObserver : public Thread::TaskObserver {
~TestObserver() override = default;
- void WillProcessTask() override { calls_->append(" willProcessTask"); }
+ void WillProcessTask(const base::PendingTask&) override {
+ calls_->append(" willProcessTask");
+ }
- void DidProcessTask() override { calls_->append(" didProcessTask"); }
+ void DidProcessTask(const base::PendingTask&) override {
+ calls_->append(" didProcessTask");
+ }
private:
std::string* calls_; // NOT OWNED
@@ -50,30 +54,27 @@ void RunTestTask(std::string* calls) {
calls->append(" run");
}
-void AddTaskObserver(WebThreadImplForWorkerScheduler* thread,
- TestObserver* observer) {
+void AddTaskObserver(Thread* thread, TestObserver* observer) {
thread->AddTaskObserver(observer);
}
-void RemoveTaskObserver(WebThreadImplForWorkerScheduler* thread,
- TestObserver* observer) {
+void RemoveTaskObserver(Thread* thread, TestObserver* observer) {
thread->RemoveTaskObserver(observer);
}
-void ShutdownOnThread(WebThreadImplForWorkerScheduler* thread) {
+void ShutdownOnThread(Thread* thread) {
thread->Scheduler()->Shutdown();
}
-class WebThreadImplForWorkerSchedulerTest : public testing::Test {
+class WorkerThreadTest : public testing::Test {
public:
- WebThreadImplForWorkerSchedulerTest() = default;
+ WorkerThreadTest() = default;
- ~WebThreadImplForWorkerSchedulerTest() override = default;
+ ~WorkerThreadTest() override = default;
void SetUp() override {
- thread_.reset(new WebThreadImplForWorkerScheduler(
- ThreadCreationParams(WebThreadType::kTestThread)));
- thread_->Init();
+ thread_ =
+ Thread::CreateThread(ThreadCreationParams(WebThreadType::kTestThread));
}
void RunOnWorkerThread(const base::Location& from_here,
@@ -83,9 +84,8 @@ class WebThreadImplForWorkerSchedulerTest : public testing::Test {
base::WaitableEvent::InitialState::NOT_SIGNALED);
thread_->GetTaskRunner()->PostTask(
from_here,
- base::BindOnce(
- &WebThreadImplForWorkerSchedulerTest::RunOnWorkerThreadTask,
- base::Unretained(this), std::move(task), &completion));
+ base::BindOnce(&WorkerThreadTest::RunOnWorkerThreadTask,
+ base::Unretained(this), std::move(task), &completion));
completion.Wait();
}
@@ -96,12 +96,12 @@ class WebThreadImplForWorkerSchedulerTest : public testing::Test {
completion->Signal();
}
- std::unique_ptr<WebThreadImplForWorkerScheduler> thread_;
+ std::unique_ptr<Thread> thread_;
- DISALLOW_COPY_AND_ASSIGN(WebThreadImplForWorkerSchedulerTest);
+ DISALLOW_COPY_AND_ASSIGN(WorkerThreadTest);
};
-TEST_F(WebThreadImplForWorkerSchedulerTest, TestDefaultTask) {
+TEST_F(WorkerThreadTest, TestDefaultTask) {
MockTask task;
base::WaitableEvent completion(
base::WaitableEvent::ResetPolicy::AUTOMATIC,
@@ -118,8 +118,7 @@ TEST_F(WebThreadImplForWorkerSchedulerTest, TestDefaultTask) {
completion.Wait();
}
-TEST_F(WebThreadImplForWorkerSchedulerTest,
- TestTaskExecutedBeforeThreadDeletion) {
+TEST_F(WorkerThreadTest, TestTaskExecutedBeforeThreadDeletion) {
MockTask task;
base::WaitableEvent completion(
base::WaitableEvent::ResetPolicy::AUTOMATIC,
@@ -136,7 +135,7 @@ TEST_F(WebThreadImplForWorkerSchedulerTest,
thread_.reset();
}
-TEST_F(WebThreadImplForWorkerSchedulerTest, TestTaskObserver) {
+TEST_F(WorkerThreadTest, TestTaskObserver) {
std::string calls;
TestObserver observer(&calls);
@@ -156,7 +155,7 @@ TEST_F(WebThreadImplForWorkerSchedulerTest, TestTaskObserver) {
EXPECT_THAT(calls, testing::HasSubstr("willProcessTask run didProcessTask"));
}
-TEST_F(WebThreadImplForWorkerSchedulerTest, TestShutdown) {
+TEST_F(WorkerThreadTest, TestShutdown) {
MockTask task;
MockTask delayed_task;
@@ -176,6 +175,6 @@ TEST_F(WebThreadImplForWorkerSchedulerTest, TestShutdown) {
thread_.reset();
}
-} // namespace webthread_impl_for_worker_scheduler_unittest
+} // namespace worker_thread_unittest
} // namespace scheduler
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/scroll/scroll_snap_data.h b/chromium/third_party/blink/renderer/platform/scroll/scroll_snap_data.h
index 0aa52947b3b..81c8a55262f 100644
--- a/chromium/third_party/blink/renderer/platform/scroll/scroll_snap_data.h
+++ b/chromium/third_party/blink/renderer/platform/scroll/scroll_snap_data.h
@@ -7,6 +7,7 @@
#include "cc/input/scroll_snap_data.h"
#include "cc/input/snap_fling_controller.h"
+#include "cc/input/snap_selection_strategy.h"
// This file defines classes and structs used in SnapCoordinator.h
@@ -16,6 +17,7 @@ using SnapAxis = cc::SnapAxis;
using SearchAxis = cc::SearchAxis;
using SnapStrictness = cc::SnapStrictness;
using SnapAlignment = cc::SnapAlignment;
+using SnapSelectionStrategy = cc::SnapSelectionStrategy;
using ScrollSnapType = cc::ScrollSnapType;
using ScrollSnapAlign = cc::ScrollSnapAlign;
using SnapAreaData = cc::SnapAreaData;
diff --git a/chromium/third_party/blink/renderer/platform/scroll/web_scrollbar_theme_client.h b/chromium/third_party/blink/renderer/platform/scroll/web_scrollbar_theme_client.h
deleted file mode 100644
index 6a9952eac1d..00000000000
--- a/chromium/third_party/blink/renderer/platform/scroll/web_scrollbar_theme_client.h
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCROLL_WEB_SCROLLBAR_THEME_CLIENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCROLL_WEB_SCROLLBAR_THEME_CLIENT_H_
-
-namespace blink {
-
-class WebScrollbarThemeClient {
- protected:
- WebScrollbarThemeClient() = default;
-
- public:
- virtual void PreferencesChanged() {}
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCROLL_WEB_SCROLLBAR_THEME_CLIENT_H_
diff --git a/chromium/third_party/blink/renderer/platform/shared_buffer.h b/chromium/third_party/blink/renderer/platform/shared_buffer.h
index 311fb9c5e46..8c01968affe 100644
--- a/chromium/third_party/blink/renderer/platform/shared_buffer.h
+++ b/chromium/third_party/blink/renderer/platform/shared_buffer.h
@@ -27,6 +27,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SHARED_BUFFER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SHARED_BUFFER_H_
+#include <algorithm>
#include <utility>
#include <vector>
@@ -61,7 +62,9 @@ class PLATFORM_EXPORT SharedBuffer : public RefCounted<SharedBuffer> {
return temp;
}
bool operator==(const Iterator& that) const {
- return value_ == that.value_ && buffer_ == that.buffer_;
+ return std::equal(value_.begin(), value_.end(), that.value_.begin(),
+ that.value_.end()) &&
+ buffer_ == that.buffer_;
}
bool operator!=(const Iterator& that) const { return !(*this == that); }
const base::span<const char>& operator*() const {
diff --git a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.cc b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.cc
index 0ab189b4a53..defd1e33f94 100644
--- a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.cc
+++ b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.cc
@@ -29,7 +29,7 @@ namespace blink {
PlatformSpeechSynthesisUtterance* PlatformSpeechSynthesisUtterance::Create(
PlatformSpeechSynthesisUtteranceClient* client) {
- return new PlatformSpeechSynthesisUtterance(client);
+ return MakeGarbageCollected<PlatformSpeechSynthesisUtterance>(client);
}
PlatformSpeechSynthesisUtterance::PlatformSpeechSynthesisUtterance(
diff --git a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.h b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.h
index 8440d819358..69ec13bf584 100644
--- a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.h
+++ b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesis_utterance.h
@@ -48,6 +48,9 @@ class PLATFORM_EXPORT PlatformSpeechSynthesisUtterance final
static PlatformSpeechSynthesisUtterance* Create(
PlatformSpeechSynthesisUtteranceClient*);
+ explicit PlatformSpeechSynthesisUtterance(
+ PlatformSpeechSynthesisUtteranceClient*);
+
const String& GetText() const { return text_; }
void SetText(const String& text) { text_ = text; }
@@ -77,16 +80,13 @@ class PLATFORM_EXPORT PlatformSpeechSynthesisUtterance final
void Trace(blink::Visitor*);
private:
- explicit PlatformSpeechSynthesisUtterance(
- PlatformSpeechSynthesisUtteranceClient*);
-
Member<PlatformSpeechSynthesisUtteranceClient> client_;
String text_;
String lang_;
scoped_refptr<PlatformSpeechSynthesisVoice> voice_;
- float volume_ = SpeechSynthesisConstants::kDoublePrefNotSet;
- float rate_ = SpeechSynthesisConstants::kDoublePrefNotSet;
- float pitch_ = SpeechSynthesisConstants::kDoublePrefNotSet;
+ float volume_ = kWebSpeechSynthesisDoublePrefNotSet;
+ float rate_ = kWebSpeechSynthesisDoublePrefNotSet;
+ float pitch_ = kWebSpeechSynthesisDoublePrefNotSet;
double start_time_;
};
diff --git a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.cc b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.cc
index f56c547e843..630cb12b947 100644
--- a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.cc
+++ b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.cc
@@ -38,7 +38,7 @@ namespace blink {
PlatformSpeechSynthesizer* PlatformSpeechSynthesizer::Create(
PlatformSpeechSynthesizerClient* client) {
PlatformSpeechSynthesizer* synthesizer =
- new PlatformSpeechSynthesizer(client);
+ MakeGarbageCollected<PlatformSpeechSynthesizer>(client);
#if defined(OS_ANDROID)
// On Android devices we don't fetch voices until the object
// is touched to avoid needlessly binding to TTS service, see
@@ -53,7 +53,7 @@ PlatformSpeechSynthesizer::PlatformSpeechSynthesizer(
PlatformSpeechSynthesizerClient* client)
: speech_synthesizer_client_(client) {
web_speech_synthesizer_client_ =
- new WebSpeechSynthesizerClientImpl(this, client);
+ MakeGarbageCollected<WebSpeechSynthesizerClientImpl>(this, client);
web_speech_synthesizer_ = Platform::Current()->CreateSpeechSynthesizer(
web_speech_synthesizer_client_);
}
diff --git a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.h b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.h
index 355aa486d35..f15bc8eaeea 100644
--- a/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.h
+++ b/chromium/third_party/blink/renderer/platform/speech/platform_speech_synthesizer.h
@@ -64,6 +64,7 @@ class PLATFORM_EXPORT PlatformSpeechSynthesizer
public:
static PlatformSpeechSynthesizer* Create(PlatformSpeechSynthesizerClient*);
+ explicit PlatformSpeechSynthesizer(PlatformSpeechSynthesizerClient*);
virtual ~PlatformSpeechSynthesizer();
virtual void Speak(PlatformSpeechSynthesisUtterance*);
@@ -93,8 +94,6 @@ class PLATFORM_EXPORT PlatformSpeechSynthesizer
virtual void Trace(blink::Visitor*);
protected:
- explicit PlatformSpeechSynthesizer(PlatformSpeechSynthesizerClient*);
-
virtual void InitializeVoiceList();
Vector<scoped_refptr<PlatformSpeechSynthesisVoice>> voice_list_;
diff --git a/chromium/third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.cc b/chromium/third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.cc
index 219a6870079..a1f9ef8774b 100644
--- a/chromium/third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.cc
@@ -8,6 +8,7 @@
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "content/public/test/blink_test_environment.h"
+#include "third_party/blink/renderer/platform/heap/thread_state.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
namespace blink {
@@ -30,6 +31,13 @@ BlinkFuzzerTestSupport::BlinkFuzzerTestSupport(int argc, char** argv) {
blink::SchemeRegistry::Initialize();
}
-BlinkFuzzerTestSupport::~BlinkFuzzerTestSupport() = default;
+BlinkFuzzerTestSupport::~BlinkFuzzerTestSupport() {
+#if defined(ADDRESS_SANITIZER)
+ // LSAN needs unreachable objects to be released to avoid reporting them
+ // incorrectly as a memory leak.
+ blink::ThreadState* currentThreadState = blink::ThreadState::Current();
+ currentThreadState->CollectAllGarbage();
+#endif
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/anim_none.gif b/chromium/third_party/blink/renderer/platform/testing/data/anim_none.gif
new file mode 100644
index 00000000000..0e2dab041e6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/anim_none.gif
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/animated-10color.gif b/chromium/third_party/blink/renderer/platform/testing/data/animated-10color.gif
new file mode 100644
index 00000000000..64b0c43f8f4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/animated-10color.gif
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng00-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng00-ref.png
new file mode 100644
index 00000000000..1fc670ce391
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng00-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng00.png b/chromium/third_party/blink/renderer/platform/testing/data/apng00.png
new file mode 100644
index 00000000000..5fd007885d7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng00.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng01-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng01-ref.png
new file mode 100644
index 00000000000..c6a2f13c9a2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng01-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng01.png b/chromium/third_party/blink/renderer/platform/testing/data/apng01.png
new file mode 100644
index 00000000000..96d4057172d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng01.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng02-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng02-ref.png
new file mode 100644
index 00000000000..6d226cc22d2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng02-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng02.png b/chromium/third_party/blink/renderer/platform/testing/data/apng02.png
new file mode 100644
index 00000000000..fdbceb3b692
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng02.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng04-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng04-ref.png
new file mode 100644
index 00000000000..47a77dc5da1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng04-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng04.png b/chromium/third_party/blink/renderer/platform/testing/data/apng04.png
new file mode 100644
index 00000000000..c3ea3464fa5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng04.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng08-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng08-ref.png
new file mode 100644
index 00000000000..91bf2b9dc21
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng08-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng08.png b/chromium/third_party/blink/renderer/platform/testing/data/apng08.png
new file mode 100644
index 00000000000..2683af68947
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng08.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng10-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng10-ref.png
new file mode 100644
index 00000000000..80041da4d29
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng10-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng10.png b/chromium/third_party/blink/renderer/platform/testing/data/apng10.png
new file mode 100644
index 00000000000..716256f45a1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng10.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng11-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng11-ref.png
new file mode 100644
index 00000000000..308db582bac
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng11-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng11.png b/chromium/third_party/blink/renderer/platform/testing/data/apng11.png
new file mode 100644
index 00000000000..58dd50d5f74
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng11.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng12-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng12-ref.png
new file mode 100644
index 00000000000..b55c926b82f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng12-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng12.png b/chromium/third_party/blink/renderer/platform/testing/data/apng12.png
new file mode 100644
index 00000000000..402ff06042b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng12.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng14-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng14-ref.png
new file mode 100644
index 00000000000..09274c87bc8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng14-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng14.png b/chromium/third_party/blink/renderer/platform/testing/data/apng14.png
new file mode 100644
index 00000000000..e1e18c0c84f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng14.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng18-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng18-ref.png
new file mode 100644
index 00000000000..1eb8f50265a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng18-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng18.png b/chromium/third_party/blink/renderer/platform/testing/data/apng18.png
new file mode 100644
index 00000000000..f0274e22ea8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng18.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng19-ref.png b/chromium/third_party/blink/renderer/platform/testing/data/apng19-ref.png
new file mode 100644
index 00000000000..b9bf8229204
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng19-ref.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/apng19.png b/chromium/third_party/blink/renderer/platform/testing/data/apng19.png
new file mode 100644
index 00000000000..8bfcc149230
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/apng19.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/blue-wheel-srgb-color-profile.jpg b/chromium/third_party/blink/renderer/platform/testing/data/blue-wheel-srgb-color-profile.jpg
new file mode 100644
index 00000000000..4df68d3aac2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/blue-wheel-srgb-color-profile.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/cat.jpg b/chromium/third_party/blink/renderer/platform/testing/data/cat.jpg
new file mode 100644
index 00000000000..e24b6295751
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/cat.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/crbug722072.png b/chromium/third_party/blink/renderer/platform/testing/data/crbug722072.png
new file mode 100644
index 00000000000..cf7aa7fe1da
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/crbug722072.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/cropped_mandrill.jpg b/chromium/third_party/blink/renderer/platform/testing/data/cropped_mandrill.jpg
new file mode 100644
index 00000000000..e1a233ad35e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/cropped_mandrill.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-1-ul.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-1-ul.jpg
new file mode 100644
index 00000000000..102e82c6b38
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-1-ul.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-2-ur.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-2-ur.jpg
new file mode 100644
index 00000000000..70c14d4272b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-2-ur.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-3-lr.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-3-lr.jpg
new file mode 100644
index 00000000000..a0a718f7f6c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-3-lr.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-4-lol.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-4-lol.jpg
new file mode 100644
index 00000000000..c75ea6a17f0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-4-lol.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-5-lu.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-5-lu.jpg
new file mode 100644
index 00000000000..7f96232c532
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-5-lu.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-6-ru.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-6-ru.jpg
new file mode 100644
index 00000000000..deffbcd291c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-6-ru.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-7-rl.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-7-rl.jpg
new file mode 100644
index 00000000000..8da2ae26c2c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-7-rl.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-8-llo.jpg b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-8-llo.jpg
new file mode 100644
index 00000000000..294c4b86f97
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/exif-orientation-8-llo.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/gif-loop-count.gif b/chromium/third_party/blink/renderer/platform/testing/data/gif-loop-count.gif
new file mode 100644
index 00000000000..2b51a62b47a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/gif-loop-count.gif
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/green-red-blue-yellow-animated.gif b/chromium/third_party/blink/renderer/platform/testing/data/green-red-blue-yellow-animated.gif
new file mode 100644
index 00000000000..37a9cf1c1d1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/green-red-blue-yellow-animated.gif
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/green.jpg b/chromium/third_party/blink/renderer/platform/testing/data/green.jpg
new file mode 100644
index 00000000000..f5f700b6807
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/green.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/green.png b/chromium/third_party/blink/renderer/platform/testing/data/green.png
new file mode 100644
index 00000000000..28a1faab377
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/green.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/icc-v2-gbr.jpg b/chromium/third_party/blink/renderer/platform/testing/data/icc-v2-gbr.jpg
new file mode 100644
index 00000000000..0984e9b3fd7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/icc-v2-gbr.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/lenna.bmp b/chromium/third_party/blink/renderer/platform/testing/data/lenna.bmp
new file mode 100644
index 00000000000..8851ea9d4ef
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/lenna.bmp
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/original-cat-420-629x473.jpg b/chromium/third_party/blink/renderer/platform/testing/data/original-cat-420-629x473.jpg
new file mode 100644
index 00000000000..f5689993982
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/original-cat-420-629x473.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/palatted-color-png-gamma-one-color-profile.png b/chromium/third_party/blink/renderer/platform/testing/data/palatted-color-png-gamma-one-color-profile.png
new file mode 100644
index 00000000000..ad7c3dceb37
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/palatted-color-png-gamma-one-color-profile.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/rgb-jpeg-red.jpg b/chromium/third_party/blink/renderer/platform/testing/data/rgb-jpeg-red.jpg
new file mode 100644
index 00000000000..9a69dbbe59c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/rgb-jpeg-red.jpg
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/three-frames_loop-three-times.gif b/chromium/third_party/blink/renderer/platform/testing/data/three-frames_loop-three-times.gif
new file mode 100644
index 00000000000..a474c8ee5c7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/three-frames_loop-three-times.gif
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/webp-color-profile-lossy.webp b/chromium/third_party/blink/renderer/platform/testing/data/webp-color-profile-lossy.webp
new file mode 100644
index 00000000000..fdff0a9941d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/webp-color-profile-lossy.webp
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/data/wrong-frame-dimensions.ico b/chromium/third_party/blink/renderer/platform/testing/data/wrong-frame-dimensions.ico
new file mode 100644
index 00000000000..dee64c74ecb
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/data/wrong-frame-dimensions.ico
Binary files differ
diff --git a/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.cc b/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.cc
index 10ed823d1d5..76f39b5545e 100644
--- a/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.cc
@@ -10,7 +10,7 @@
namespace blink {
WebMediaPlayer::LoadTiming
-EmptyWebMediaPlayer::Load(LoadType, const WebMediaPlayerSource&, CORSMode) {
+EmptyWebMediaPlayer::Load(LoadType, const WebMediaPlayerSource&, CorsMode) {
return LoadTiming::kImmediate;
}
diff --git a/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.h b/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.h
index d82b4e18d21..205fde9900d 100644
--- a/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.h
+++ b/chromium/third_party/blink/renderer/platform/testing/empty_web_media_player.h
@@ -22,7 +22,7 @@ class EmptyWebMediaPlayer : public WebMediaPlayer {
public:
~EmptyWebMediaPlayer() override = default;
- LoadTiming Load(LoadType, const WebMediaPlayerSource&, CORSMode) override;
+ LoadTiming Load(LoadType, const WebMediaPlayerSource&, CorsMode) override;
void Play() override {}
void Pause() override {}
void Seek(double seconds) override {}
@@ -40,7 +40,7 @@ class EmptyWebMediaPlayer : public WebMediaPlayer {
WebTimeRanges Buffered() const override;
WebTimeRanges Seekable() const override;
void SetSinkId(const WebString& sink_id,
- WebSetSinkIdCallbacks*) override {}
+ std::unique_ptr<WebSetSinkIdCallbacks>) override {}
bool HasVideo() const override { return false; }
bool HasAudio() const override { return false; }
WebSize NaturalSize() const override;
diff --git a/chromium/third_party/blink/renderer/platform/testing/font_test_helpers.cc b/chromium/third_party/blink/renderer/platform/testing/font_test_helpers.cc
index fa18103a622..b26098f0a92 100644
--- a/chromium/third_party/blink/renderer/platform/testing/font_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/font_test_helpers.cc
@@ -21,10 +21,14 @@ class TestFontSelector : public FontSelector {
static TestFontSelector* Create(const String& path) {
scoped_refptr<SharedBuffer> font_buffer = test::ReadFromFile(path);
String ots_parse_message;
- return new TestFontSelector(
+ return MakeGarbageCollected<TestFontSelector>(
FontCustomPlatformData::Create(font_buffer.get(), ots_parse_message));
}
+ TestFontSelector(scoped_refptr<FontCustomPlatformData> custom_platform_data)
+ : custom_platform_data_(std::move(custom_platform_data)) {
+ DCHECK(custom_platform_data_);
+ }
~TestFontSelector() override = default;
scoped_refptr<FontData> GetFontData(
@@ -66,11 +70,6 @@ class TestFontSelector : public FontSelector {
}
private:
- TestFontSelector(scoped_refptr<FontCustomPlatformData> custom_platform_data)
- : custom_platform_data_(std::move(custom_platform_data)) {
- DCHECK(custom_platform_data_);
- }
-
scoped_refptr<FontCustomPlatformData> custom_platform_data_;
};
diff --git a/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.cc b/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.cc
index 2cbfb01b084..dae01542af8 100644
--- a/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.cc
@@ -11,23 +11,14 @@ FuzzedDataProvider::FuzzedDataProvider(const uint8_t* bytes, size_t num_bytes)
CString FuzzedDataProvider::ConsumeBytesInRange(uint32_t min_bytes,
uint32_t max_bytes) {
- size_t num_bytes =
- static_cast<size_t>(provider_.ConsumeUint32InRange(min_bytes, max_bytes));
- std::string bytes = provider_.ConsumeBytes(num_bytes);
+ size_t num_bytes = provider_.ConsumeIntegralInRange(min_bytes, max_bytes);
+ std::vector<char> bytes = provider_.ConsumeBytes<char>(num_bytes);
return CString(bytes.data(), bytes.size());
}
CString FuzzedDataProvider::ConsumeRemainingBytes() {
- std::string bytes = provider_.ConsumeRemainingBytes();
+ std::vector<char> bytes = provider_.ConsumeRemainingBytes<char>();
return CString(bytes.data(), bytes.size());
}
-bool FuzzedDataProvider::ConsumeBool() {
- return provider_.ConsumeBool();
-}
-
-int FuzzedDataProvider::ConsumeInt32InRange(int min, int max) {
- return provider_.ConsumeInt32InRange(min, max);
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.h b/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.h
index ee8897fa453..bcb6ac896da 100644
--- a/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.h
+++ b/chromium/third_party/blink/renderer/platform/testing/fuzzed_data_provider.h
@@ -28,19 +28,30 @@ class FuzzedDataProvider {
CString ConsumeRemainingBytes();
// Returns a bool, or false when no data remains.
- bool ConsumeBool();
+ bool ConsumeBool() { return provider_.ConsumeBool(); }
// Returns a number in the range [min, max] by consuming bytes from the input
// data. The value might not be uniformly distributed in the given range. If
// there's no input data left, always returns |min|. |min| must be less than
// or equal to |max|.
- int ConsumeInt32InRange(int min, int max);
+ template <typename T>
+ T ConsumeIntegralInRange(T min, T max) {
+ return provider_.ConsumeIntegralInRange<T>(min, max);
+ }
+
+ // Returns a number in the range [Type's min, Type's max]. The value might
+ // not be uniformly distributed in the given range. If there's no input data
+ // left, always returns |min|.
+ template <typename T>
+ T ConsumeIntegral() {
+ return provider_.ConsumeIntegral<T>();
+ }
// Returns a value from |array|, consuming as many bytes as needed to do so.
// |array| must be a fixed-size array.
- template <typename Type, size_t size>
- Type PickValueInArray(Type (&array)[size]) {
- return array[provider_.ConsumeUint32InRange(0, size - 1)];
+ template <typename T, size_t size>
+ T PickValueInArray(T (&array)[size]) {
+ return array[provider_.ConsumeIntegralInRange<size_t>(0, size - 1)];
}
// Reports the remaining bytes available for fuzzed input.
diff --git a/chromium/third_party/blink/renderer/platform/testing/scoped_fake_plugin_registry.cc b/chromium/third_party/blink/renderer/platform/testing/scoped_fake_plugin_registry.cc
index df5f4e9e77d..96fc9c40891 100644
--- a/chromium/third_party/blink/renderer/platform/testing/scoped_fake_plugin_registry.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/scoped_fake_plugin_registry.cc
@@ -52,24 +52,22 @@ class FakePluginRegistryImpl : public mojom::blink::PluginRegistry {
} // namespace
ScopedFakePluginRegistry::ScopedFakePluginRegistry() {
- service_manager::Identity browser_id(
- Platform::Current()->GetBrowserServiceName());
const char* interface_name = mojom::blink::PluginRegistry::Name_;
- service_manager::Connector::TestApi test_api(
- Platform::Current()->GetConnector());
- DCHECK(!test_api.HasBinderOverride(browser_id, interface_name));
- test_api.OverrideBinderForTesting(
- browser_id, interface_name,
+ service_manager::Connector* connector = Platform::Current()->GetConnector();
+ auto browser_service_filter = service_manager::ServiceFilter::ByName(
+ Platform::Current()->GetBrowserServiceName());
+ DCHECK(!connector->HasBinderOverrideForTesting(browser_service_filter,
+ interface_name));
+ connector->OverrideBinderForTesting(
+ browser_service_filter, interface_name,
WTF::BindRepeating(&FakePluginRegistryImpl::Bind));
}
ScopedFakePluginRegistry::~ScopedFakePluginRegistry() {
- service_manager::Identity browser_id(
- Platform::Current()->GetBrowserServiceName());
- const char* interface_name = mojom::blink::PluginRegistry::Name_;
- service_manager::Connector::TestApi test_api(
- Platform::Current()->GetConnector());
- test_api.ClearBinderOverride(browser_id, interface_name);
+ Platform::Current()->GetConnector()->ClearBinderOverrideForTesting(
+ service_manager::ServiceFilter::ByName(
+ Platform::Current()->GetBrowserServiceName()),
+ mojom::blink::PluginRegistry::Name_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.cc b/chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.cc
new file mode 100644
index 00000000000..cc7d56f1743
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.cc
@@ -0,0 +1,17 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h"
+
+namespace blink {
+
+ScopedMainThreadOverrider::ScopedMainThreadOverrider(
+ std::unique_ptr<Thread> main_thread)
+ : original_main_thread_(Thread::SetMainThread(std::move(main_thread))) {}
+
+ScopedMainThreadOverrider::~ScopedMainThreadOverrider() {
+ Thread::SetMainThread(std::move(original_main_thread_));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h b/chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h
new file mode 100644
index 00000000000..dbe1719207a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h
@@ -0,0 +1,32 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_SCOPED_MAIN_THREAD_OVERRIDER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_SCOPED_MAIN_THREAD_OVERRIDER_H_
+
+#include <memory>
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+
+namespace blink {
+
+// This class instance lets you override the main thread (of type blink::Thread)
+// temporarily. This is useful when you want to change the main thread scheduler
+// during a test (see ScopedSchedulerOverrider).
+//
+// When ScopedMainThreadOverrider goes out of scope, the main thread is
+// reverted back to the original one, and the main thread object passed in
+// the constructor gets destructed.
+
+class ScopedMainThreadOverrider final {
+ public:
+ explicit ScopedMainThreadOverrider(std::unique_ptr<Thread> main_thread);
+ ~ScopedMainThreadOverrider();
+
+ private:
+ std::unique_ptr<Thread> original_main_thread_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_SCOPED_MAIN_THREAD_OVERRIDER_H_
diff --git a/chromium/third_party/blink/renderer/platform/testing/scoped_mocked_url.cc b/chromium/third_party/blink/renderer/platform/testing/scoped_mocked_url.cc
index 95965ad1875..701b0b59508 100644
--- a/chromium/third_party/blink/renderer/platform/testing/scoped_mocked_url.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/scoped_mocked_url.cc
@@ -21,7 +21,7 @@ ScopedMockedURLLoad::ScopedMockedURLLoad(const WebURL& full_url,
const WebString& file_path,
const WebString& mime_type)
: ScopedMockedURL(full_url) {
- URLTestHelpers::RegisterMockedURLLoad(full_url, file_path, mime_type);
+ url_test_helpers::RegisterMockedURLLoad(full_url, file_path, mime_type);
}
} // namespace test
diff --git a/chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.cc b/chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.cc
new file mode 100644
index 00000000000..8aa156cd53c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.cc
@@ -0,0 +1,33 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h"
+
+#include "third_party/blink/renderer/platform/wtf/wtf.h"
+
+namespace blink {
+
+namespace {
+
+class ThreadWithCustomScheduler : public Thread {
+ public:
+ explicit ThreadWithCustomScheduler(ThreadScheduler* scheduler)
+ : scheduler_(scheduler) {}
+ ~ThreadWithCustomScheduler() override {}
+
+ ThreadScheduler* Scheduler() override { return scheduler_; }
+
+ private:
+ ThreadScheduler* scheduler_;
+};
+
+} // namespace
+
+ScopedSchedulerOverrider::ScopedSchedulerOverrider(ThreadScheduler* scheduler)
+ : main_thread_overrider_(
+ std::make_unique<ThreadWithCustomScheduler>(scheduler)) {}
+
+ScopedSchedulerOverrider::~ScopedSchedulerOverrider() {}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h b/chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h
new file mode 100644
index 00000000000..7f46ea37a3f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/platform/testing/scoped_scheduler_overrider.h
@@ -0,0 +1,30 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_SCOPED_SCHEDULER_OVERRIDER_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_SCOPED_SCHEDULER_OVERRIDER_H_
+
+#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
+#include "third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h"
+
+namespace blink {
+
+// A utility which lets you inject your custom implementation of ThreadScheduler
+// on the main thread. This class sets up a very simple instance of
+// blink::Thread and overrides the global main thread using ScopedMainThread-
+// Overrider. Multi-thread is not supported.
+
+class ScopedSchedulerOverrider final {
+ public:
+ // |scheduler| must be owned by the caller.
+ explicit ScopedSchedulerOverrider(ThreadScheduler* scheduler);
+ ~ScopedSchedulerOverrider();
+
+ private:
+ ScopedMainThreadOverrider main_thread_overrider_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_SCOPED_SCHEDULER_OVERRIDER_H_
diff --git a/chromium/third_party/blink/renderer/platform/testing/shaping_line_breaker_perf_test.cc b/chromium/third_party/blink/renderer/platform/testing/shaping_line_breaker_perf_test.cc
index 8952c357cfc..15219c4cbef 100644
--- a/chromium/third_party/blink/renderer/platform/testing/shaping_line_breaker_perf_test.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/shaping_line_breaker_perf_test.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_test_utilities.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_test_info.h"
+#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
@@ -30,7 +31,7 @@ LayoutUnit ShapeText(ShapingLineBreaker* breaker,
unsigned break_offset = 0;
LayoutUnit total_width;
ShapingLineBreaker::Result result;
- scoped_refptr<const ShapeResult> shape_result;
+ scoped_refptr<const ShapeResultView> shape_result;
while (break_offset < string_length) {
shape_result = breaker->ShapeLine(break_offset, available_space, &result);
break_offset = result.break_offset;
diff --git a/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.cc b/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.cc
index 4e0ab00d472..9514346ca2e 100644
--- a/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.cc
@@ -78,12 +78,6 @@ TestPaintArtifact& TestPaintArtifact::RectDrawing(const FloatRect& bounds,
return RectDrawing(NewClient(), bounds, color);
}
-TestPaintArtifact& TestPaintArtifact::ForeignLayer(
- const FloatPoint& location,
- const IntSize& size,
- scoped_refptr<cc::Layer> layer) {
- return ForeignLayer(NewClient(), location, size, std::move(layer));
-}
TestPaintArtifact& TestPaintArtifact::ScrollHitTest(
const TransformPaintPropertyNode& scroll_offset) {
return ScrollHitTest(NewClient(), scroll_offset);
@@ -99,15 +93,9 @@ TestPaintArtifact& TestPaintArtifact::RectDrawing(FakeDisplayItemClient& client,
}
TestPaintArtifact& TestPaintArtifact::ForeignLayer(
- FakeDisplayItemClient& client,
- const FloatPoint& location,
- const IntSize& size,
scoped_refptr<cc::Layer> layer) {
- static_cast<DummyRectClient&>(client).SetVisualRect(
- FloatRect(location, FloatSize(size)));
display_item_list_.AllocateAndConstruct<ForeignLayerDisplayItem>(
- client, DisplayItem::kForeignLayerFirst, std::move(layer), location,
- size);
+ DisplayItem::kForeignLayerFirst, std::move(layer));
return *this;
}
diff --git a/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.h b/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.h
index 613003aa9a2..ee3637fcda8 100644
--- a/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.h
+++ b/chromium/third_party/blink/renderer/platform/testing/test_paint_artifact.h
@@ -93,20 +93,15 @@ class TestPaintArtifact {
// Add display item in the chunk. Each display item will have a different
// automatically created client.
TestPaintArtifact& RectDrawing(const FloatRect& bounds, Color color);
- TestPaintArtifact& ForeignLayer(const FloatPoint& location,
- const IntSize& size,
- scoped_refptr<cc::Layer> layer);
TestPaintArtifact& ScrollHitTest(
const TransformPaintPropertyNode& scroll_offset);
+ TestPaintArtifact& ForeignLayer(scoped_refptr<cc::Layer> layer);
+
// Add display item with the specified client in the chunk.
TestPaintArtifact& RectDrawing(FakeDisplayItemClient&,
const FloatRect& bounds,
Color);
- TestPaintArtifact& ForeignLayer(FakeDisplayItemClient&,
- const FloatPoint&,
- const IntSize&,
- scoped_refptr<cc::Layer>);
TestPaintArtifact& ScrollHitTest(
FakeDisplayItemClient&,
const TransformPaintPropertyNode& scroll_offset);
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.cc b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.cc
index 3eea5032012..f44a0dc1480 100644
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.cc
@@ -96,7 +96,6 @@ TestingPlatformSupport::TestingPlatformSupport()
interface_provider_(new TestingInterfaceProvider) {
DCHECK(old_platform_);
DCHECK(WTF::IsMainThread());
- main_thread_ = old_platform_->CurrentThread();
}
TestingPlatformSupport::~TestingPlatformSupport() {
@@ -111,10 +110,6 @@ WebBlobRegistry* TestingPlatformSupport::GetBlobRegistry() {
return old_platform_ ? old_platform_->GetBlobRegistry() : nullptr;
}
-std::unique_ptr<WebIDBFactory> TestingPlatformSupport::CreateIdbFactory() {
- return old_platform_ ? old_platform_->CreateIdbFactory() : nullptr;
-}
-
WebURLLoaderMockFactory* TestingPlatformSupport::GetURLLoaderMockFactory() {
return old_platform_ ? old_platform_->GetURLLoaderMockFactory() : nullptr;
}
@@ -159,12 +154,22 @@ ScopedUnittestsEnvironmentSetup::ScopedUnittestsEnvironmentSetup(int argc,
base::DiscardableMemoryAllocator::SetInstance(
discardable_memory_allocator_.get());
+ // TODO(yutak): The initialization steps below are essentially a subset of
+ // Platform::Initialize() steps with a few modifications for tests.
+ // We really shouldn't have those initialization steps in two places,
+ // because they are a very fragile piece of code (the initialization order
+ // is so sensitive) and we want it to be consistent between tests and
+ // production. Fix this someday.
dummy_platform_ = std::make_unique<Platform>();
Platform::SetCurrentPlatformForTesting(dummy_platform_.get());
WTF::Partitions::Initialize(nullptr);
WTF::Initialize(nullptr);
+ // This must be called after WTF::Initialize(), because ThreadSpecific<>
+ // used in this function depends on WTF::IsMainThread().
+ Platform::CreateMainThreadForTesting();
+
testing_platform_support_ = std::make_unique<TestingPlatformSupport>();
Platform::SetCurrentPlatformForTesting(testing_platform_support_.get());
@@ -177,11 +182,11 @@ ScopedUnittestsEnvironmentSetup::ScopedUnittestsEnvironmentSetup(int argc,
ThreadState::AttachMainThread();
ThreadState::Current()->RegisterTraceDOMWrappers(nullptr, nullptr, nullptr,
nullptr);
- HTTPNames::init();
- FetchInitiatorTypeNames::init();
+ http_names::Init();
+ fetch_initiator_type_names::Init();
InitializePlatformLanguage();
- FontFamilyNames::init();
+ font_family_names::Init();
WebRuntimeFeatures::EnableExperimentalFeatures(true);
WebRuntimeFeatures::EnableTestOnlyFeatures(true);
}
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.h b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.h
index 87cfa93fc18..38bf52010e7 100644
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.h
+++ b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support.h
@@ -61,7 +61,6 @@ class TestingPlatformSupport : public Platform {
// Platform:
WebString DefaultLocale() override;
WebBlobRegistry* GetBlobRegistry() override;
- std::unique_ptr<WebIDBFactory> CreateIdbFactory() override;
WebURLLoaderMockFactory* GetURLLoaderMockFactory() override;
std::unique_ptr<blink::WebURLLoaderFactory> CreateDefaultURLLoaderFactory()
override;
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.cc b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.cc
deleted file mode 100644
index 1a32b34efda..00000000000
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h"
-
-#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/wtf/wtf.h"
-
-namespace blink {
-
-namespace {
-
-class ThreadWithCustomScheduler : public Thread {
- public:
- explicit ThreadWithCustomScheduler(ThreadScheduler* scheduler)
- : scheduler_(scheduler) {}
- ~ThreadWithCustomScheduler() override {}
-
- bool IsCurrentThread() const override {
- DCHECK(WTF::IsMainThread());
- return true;
- }
- ThreadScheduler* Scheduler() override { return scheduler_; }
-
- private:
- ThreadScheduler* scheduler_;
-};
-
-} // namespace
-
-TestingPlatformSupportWithCustomScheduler::
- TestingPlatformSupportWithCustomScheduler(ThreadScheduler* scheduler)
- : thread_(std::make_unique<ThreadWithCustomScheduler>(scheduler)) {
- // If main_thread_ is set, Platform::SetCurrentPlatformForTesting() properly
- // sets up the platform so Platform::CurrentThread() would return the
- // thread specified here.
- main_thread_ = thread_.get();
-}
-
-TestingPlatformSupportWithCustomScheduler::
- ~TestingPlatformSupportWithCustomScheduler() {}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h
deleted file mode 100644
index 604b8a3472c..00000000000
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_custom_scheduler.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_TESTING_PLATFORM_SUPPORT_WITH_CUSTOM_SCHEDULER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_TESTING_PLATFORM_SUPPORT_WITH_CUSTOM_SCHEDULER_H_
-
-#include <memory>
-#include "base/macros.h"
-#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
-
-// Test environment where you can inject your custom implementation of
-// ThreadScheduler on the main thread. Multi-thread is not supported.
-//
-// You would probably like to use this with ScopedTestingPlatformSupport
-// class template. See testing_platform_support.h for details.
-
-namespace blink {
-
-class TestingPlatformSupportWithCustomScheduler
- : public TestingPlatformSupport {
- public:
- // |scheduler| must be owned by the caller.
- explicit TestingPlatformSupportWithCustomScheduler(
- ThreadScheduler* scheduler);
- ~TestingPlatformSupportWithCustomScheduler() override;
-
- private:
- std::unique_ptr<Thread> thread_;
-
- DISALLOW_COPY_AND_ASSIGN(TestingPlatformSupportWithCustomScheduler);
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_TESTING_PLATFORM_SUPPORT_WITH_CUSTOM_SCHEDULER_H_
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.cc b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.cc
index 0fdccdceb87..8b5ae307177 100644
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.cc
@@ -7,7 +7,6 @@
#include "base/bind.h"
#include "base/task/sequence_manager/test/sequence_manager_for_test.h"
#include "base/test/test_mock_time_task_runner.h"
-#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -27,8 +26,8 @@ TestingPlatformSupportWithMockScheduler::
scheduler_ = std::make_unique<scheduler::MainThreadSchedulerImpl>(
std::move(sequence_manager), base::nullopt);
- thread_ = scheduler_->CreateMainThread();
- main_thread_ = thread_.get();
+ main_thread_overrider_ = std::make_unique<ScopedMainThreadOverrider>(
+ scheduler_->CreateMainThread());
// Set the work batch size to one so TakePendingTasks behaves as expected.
scheduler_->GetSchedulerHelperForTesting()->SetWorkBatchSizeForTesting(1);
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h
index 46027c90a44..f2b22e5c10b 100644
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h
+++ b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h
@@ -8,6 +8,7 @@
#include <memory>
#include "base/test/test_mock_time_task_runner.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+#include "third_party/blink/renderer/platform/testing/scoped_main_thread_overrider.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
@@ -36,6 +37,8 @@ class TestingPlatformSupportWithMockScheduler : public TestingPlatformSupport {
TestingPlatformSupportWithMockScheduler();
~TestingPlatformSupportWithMockScheduler() override;
+ std::unique_ptr<Thread> CreateMainThread();
+
scoped_refptr<base::TestMockTimeTaskRunner> test_task_runner() {
return test_task_runner_;
}
@@ -77,7 +80,7 @@ class TestingPlatformSupportWithMockScheduler : public TestingPlatformSupport {
std::unique_ptr<scheduler::MainThreadSchedulerImpl> scheduler_;
base::sequence_manager::SequenceManager*
sequence_manager_; // Owned by scheduler_.
- std::unique_ptr<Thread> thread_;
+ std::unique_ptr<ScopedMainThreadOverrider> main_thread_overrider_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.cc b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.cc
index 440c68fcf99..c8d8b52392d 100644
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/public/platform/web_rtc_dtmf_sender_handler.h"
#include "third_party/blink/public/platform/web_rtc_rtp_transceiver.h"
#include "third_party/blink/public/platform/web_rtc_session_description.h"
+#include "third_party/blink/public/platform/web_rtc_stats.h"
#include "third_party/blink/public/platform/web_vector.h"
namespace blink {
@@ -43,7 +44,8 @@ class DummyWebRTCRtpSender : public WebRTCRtpSender {
void SetParameters(blink::WebVector<webrtc::RtpEncodingParameters>,
webrtc::DegradationPreference,
WebRTCVoidRequest) override {}
- void GetStats(std::unique_ptr<blink::WebRTCStatsReportCallback>) override {}
+ void GetStats(std::unique_ptr<blink::WebRTCStatsReportCallback>,
+ blink::RTCStatsFilter) override {}
void set_track(WebMediaStreamTrack track) { track_ = std::move(track); }
@@ -167,7 +169,8 @@ webrtc::RTCErrorType MockWebRTCPeerConnectionHandler::SetConfiguration(
void MockWebRTCPeerConnectionHandler::GetStats(const WebRTCStatsRequest&) {}
void MockWebRTCPeerConnectionHandler::GetStats(
- std::unique_ptr<WebRTCStatsReportCallback>) {}
+ std::unique_ptr<WebRTCStatsReportCallback>,
+ blink::RTCStatsFilter) {}
webrtc::RTCErrorOr<std::unique_ptr<WebRTCRtpTransceiver>>
MockWebRTCPeerConnectionHandler::AddTransceiverWithTrack(
diff --git a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h
index af2f28bf7dd..e37585d7f1f 100644
--- a/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h
+++ b/chromium/third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h
@@ -12,6 +12,9 @@
namespace blink {
+// TODO(https://crbug.com/908461): This is currently implemented as NO-OPs or to
+// create dummy objects whose methods return default values. Consider renaming
+// the class, changing it to be GMOCK friendly or deleting it.
class MockWebRTCPeerConnectionHandler : public WebRTCPeerConnectionHandler {
public:
MockWebRTCPeerConnectionHandler();
@@ -43,7 +46,8 @@ class MockWebRTCPeerConnectionHandler : public WebRTCPeerConnectionHandler {
webrtc::RTCErrorType SetConfiguration(
const webrtc::PeerConnectionInterface::RTCConfiguration&) override;
void GetStats(const WebRTCStatsRequest&) override;
- void GetStats(std::unique_ptr<WebRTCStatsReportCallback>) override;
+ void GetStats(std::unique_ptr<WebRTCStatsReportCallback>,
+ RTCStatsFilter) override;
webrtc::RTCErrorOr<std::unique_ptr<WebRTCRtpTransceiver>>
AddTransceiverWithTrack(const WebMediaStreamTrack&,
const webrtc::RtpTransceiverInit&) override;
diff --git a/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.cc b/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.cc
index d3e60da3321..5d18e769b99 100644
--- a/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.cc
@@ -51,23 +51,18 @@ base::FilePath BlinkRootFilePath() {
path.Append(FILE_PATH_LITERAL("third_party/blink")));
}
-// TODO(tkent): Rename this function. crbug.com/843412.
-base::FilePath LayoutTestsFilePath() {
+base::FilePath WebTestsFilePath() {
base::FilePath path;
base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
- base::FilePath web_tests_path = base::MakeAbsoluteFilePath(
- path.Append(FILE_PATH_LITERAL("third_party/blink/web_tests")));
- if (base::PathExists(web_tests_path))
- return web_tests_path;
return base::MakeAbsoluteFilePath(
- path.Append(FILE_PATH_LITERAL("third_party/WebKit/LayoutTests")));
+ path.Append(FILE_PATH_LITERAL("third_party/blink/web_tests")));
}
} // namespace
void RunPendingTasks() {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostTask(
- FROM_HERE, WTF::Bind(&ExitRunLoop));
+ Thread::Current()->GetTaskRunner()->PostTask(FROM_HERE,
+ WTF::Bind(&ExitRunLoop));
// We forbid GC in the tasks. Otherwise the registered GCTaskObserver tries
// to run GC with NoHeapPointerOnStack.
@@ -77,7 +72,7 @@ void RunPendingTasks() {
}
void RunDelayedTasks(TimeDelta delay) {
- Platform::Current()->CurrentThread()->GetTaskRunner()->PostDelayedTask(
+ Thread::Current()->GetTaskRunner()->PostDelayedTask(
FROM_HERE, WTF::Bind(&ExitRunLoop), delay);
EnterRunLoop();
}
@@ -98,8 +93,8 @@ String BlinkRootDir() {
return FilePathToWebString(BlinkRootFilePath());
}
-String BlinkLayoutTestsDir() {
- return FilePathToWebString(LayoutTestsFilePath());
+String BlinkWebTestsDir() {
+ return FilePathToWebString(WebTestsFilePath());
}
String ExecutableDir() {
@@ -122,6 +117,14 @@ String PlatformTestDataPath(const String& relative_path) {
.Append(WebStringToFilePath(relative_path)));
}
+String AccessibilityTestDataPath(const String& relative_path) {
+ return FilePathToWebString(
+ BlinkRootFilePath()
+ .Append(
+ FILE_PATH_LITERAL("renderer/modules/accessibility/testing/data"))
+ .Append(WebStringToFilePath(relative_path)));
+}
+
scoped_refptr<SharedBuffer> ReadFromFile(const String& path) {
base::FilePath file_path = blink::WebStringToFilePath(path);
std::string buffer;
diff --git a/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.h b/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.h
index e3fd7b9a369..832b5d8d107 100644
--- a/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/testing/unit_test_helpers.h
@@ -52,9 +52,9 @@ void YieldCurrentThread();
// /src/third_party/blink.
String BlinkRootDir();
-// Returns Blink LayoutTests directory as an absolute path, e.g.
-// /src/third_party/WebKit/LayoutTests.
-String BlinkLayoutTestsDir();
+// Returns Blink web_tests directory as an absolute path, e.g.
+// /src/third_party/blink/web_tests.
+String BlinkWebTestsDir();
// Returns directory containing the current executable as absolute path.
String ExecutableDir();
@@ -70,6 +70,12 @@ String CoreTestDataPath(const String& relative_path = String());
// specified.
String PlatformTestDataPath(const String& relative_path = String());
+// Returns test data absolute path for accessibility unittests, i.e.
+// <blinkRootDir>/renderer/modules/accessibility/testing/data/<relativePath>. It
+// returns the top accessibility test directory if |relativePath| was not
+// specified.
+String AccessibilityTestDataPath(const String& relative_path = String());
+
scoped_refptr<SharedBuffer> ReadFromFile(const String& path);
class LineReader {
diff --git a/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.cc b/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.cc
index 33ec9064890..1548d0f8885 100644
--- a/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.cc
@@ -43,7 +43,7 @@
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
namespace blink {
-namespace URLTestHelpers {
+namespace url_test_helpers {
WebURL RegisterMockedURLLoadFromBase(const WebString& base_url,
const WebString& base_path,
@@ -70,7 +70,7 @@ void RegisterMockedURLLoad(const WebURL& full_url,
WebURLResponse response(full_url);
response.SetMIMEType(mime_type);
- response.SetHTTPHeaderField(HTTPNames::Content_Type, mime_type);
+ response.SetHTTPHeaderField(http_names::kContentType, mime_type);
response.SetHTTPStatusCode(200);
response.SetLoadTiming(timing);
@@ -83,7 +83,7 @@ void RegisterMockedErrorURLLoad(const WebURL& full_url) {
WebURLResponse response;
response.SetMIMEType("image/png");
- response.SetHTTPHeaderField(HTTPNames::Content_Type, "image/png");
+ response.SetHTTPHeaderField(http_names::kContentType, "image/png");
response.SetHTTPStatusCode(404);
response.SetLoadTiming(timing);
@@ -103,5 +103,5 @@ void RegisterMockedURLUnregister(const WebURL& url) {
Platform::Current()->GetURLLoaderMockFactory()->UnregisterURL(url);
}
-} // namespace URLTestHelpers
+} // namespace url_test_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.h b/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.h
index 051339d7c07..aaf7c516f85 100644
--- a/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/testing/url_test_helpers.h
@@ -37,7 +37,7 @@
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
namespace blink {
-namespace URLTestHelpers {
+namespace url_test_helpers {
inline blink::KURL ToKURL(const std::string& url) {
WTF::String wtf_string(url.c_str());
@@ -85,7 +85,7 @@ void RegisterMockedURLLoadWithCustomResponse(const WebURL& full_url,
// Registers a mock URL that returns a 404 error.
void RegisterMockedErrorURLLoad(const WebURL& full_url);
-} // namespace URLTestHelpers
+} // namespace url_test_helpers
} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/platform/testing/viewport_layers_setup.cc b/chromium/third_party/blink/renderer/platform/testing/viewport_layers_setup.cc
index 548263843e0..6275435065b 100644
--- a/chromium/third_party/blink/renderer/platform/testing/viewport_layers_setup.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/viewport_layers_setup.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/platform/testing/viewport_layers_setup.h"
#include <memory>
+#include "base/time/time.h"
#include "cc/layers/picture_layer.h"
#include "cc/trees/layer_tree_host.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
@@ -39,7 +40,8 @@ ViewportLayersSetup::ViewportLayersSetup() {
viewport_layers.inner_viewport_scroll = graphics_layer_->CcLayer();
layer_tree_->layer_tree_host()->RegisterViewportLayers(viewport_layers);
layer_tree_->layer_tree_host()->SetViewportSizeAndScale(
- gfx::Size(1, 1), /*device_scale_factor=*/1.f, viz::LocalSurfaceId());
+ gfx::Size(1, 1), /*device_scale_factor=*/1.f,
+ viz::LocalSurfaceIdAllocation());
graphics_layer_->SetLayerState(PropertyTreeState(PropertyTreeState::Root()),
IntPoint());
diff --git a/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock.cc b/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock.cc
index f27c87c8b52..93d1e97824b 100644
--- a/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock.cc
@@ -93,8 +93,9 @@ WebURL WebURLLoaderMock::ServeRedirect(
bool report_raw_headers = false;
bool follow = client_->WillFollowRedirect(
- redirect_url, redirect_url, WebString(), kWebReferrerPolicyDefault,
- request.HttpMethod(), redirect_response, report_raw_headers);
+ redirect_url, redirect_url, WebString(),
+ network::mojom::ReferrerPolicy::kDefault, request.HttpMethod(),
+ redirect_response, report_raw_headers);
// |this| might be deleted in willFollowRedirect().
if (!self)
return redirect_url;
diff --git a/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock_factory_impl.cc b/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock_factory_impl.cc
index 5ea9210026a..5914e486b43 100644
--- a/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock_factory_impl.cc
+++ b/chromium/third_party/blink/renderer/platform/testing/weburl_loader_mock_factory_impl.cc
@@ -168,10 +168,11 @@ void WebURLLoaderMockFactoryImpl::LoadAsynchronouly(
}
void WebURLLoaderMockFactoryImpl::RunUntilIdle() {
- if (platform_)
+ if (platform_) {
platform_->RunUntilIdle();
- else
- base::RunLoop().RunUntilIdle();
+ } else {
+ base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
+ }
}
void WebURLLoaderMockFactoryImpl::LoadRequest(
diff --git a/chromium/third_party/blink/renderer/platform/text/DEPS b/chromium/third_party/blink/renderer/platform/text/DEPS
index a7e3ce7576e..05eb49a63e2 100644
--- a/chromium/third_party/blink/renderer/platform/text/DEPS
+++ b/chromium/third_party/blink/renderer/platform/text/DEPS
@@ -9,10 +9,11 @@ include_rules = [
"+third_party/blink/renderer/platform/date_components.h",
"+third_party/blink/renderer/platform/heap",
"+third_party/blink/renderer/platform/language.h",
- "+third_party/blink/renderer/platform/layout_test_support.h",
+ "+third_party/blink/renderer/platform/mac/version_util_mac.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/runtime_enabled_features.h",
"+third_party/blink/renderer/platform/testing",
+ "+third_party/blink/renderer/platform/web_test_support.h",
"+third_party/blink/renderer/platform/weborigin",
"+third_party/blink/renderer/platform/wtf",
]
diff --git a/chromium/third_party/blink/renderer/platform/text/bidi_character_run.h b/chromium/third_party/blink/renderer/platform/text/bidi_character_run.h
index 1cb25f0250e..93e7afd854b 100644
--- a/chromium/third_party/blink/renderer/platform/text/bidi_character_run.h
+++ b/chromium/third_party/blink/renderer/platform/text/bidi_character_run.h
@@ -35,30 +35,30 @@ struct BidiCharacterRun {
unsigned char level,
int start,
int stop,
- WTF::Unicode::CharDirection dir,
- WTF::Unicode::CharDirection override_dir)
+ WTF::unicode::CharDirection dir,
+ WTF::unicode::CharDirection override_dir)
: override_(override),
level_(level),
next_(nullptr),
start_(start),
stop_(stop) {
DCHECK_LE(start_, stop_);
- if (dir == WTF::Unicode::kOtherNeutral)
+ if (dir == WTF::unicode::kOtherNeutral)
dir = override_dir;
level_ = level;
// add level of run (cases I1 & I2)
if (level_ % 2) {
- if (dir == WTF::Unicode::kLeftToRight ||
- dir == WTF::Unicode::kArabicNumber ||
- dir == WTF::Unicode::kEuropeanNumber)
+ if (dir == WTF::unicode::kLeftToRight ||
+ dir == WTF::unicode::kArabicNumber ||
+ dir == WTF::unicode::kEuropeanNumber)
level_++;
} else {
- if (dir == WTF::Unicode::kRightToLeft)
+ if (dir == WTF::unicode::kRightToLeft)
level_++;
- else if (dir == WTF::Unicode::kArabicNumber ||
- dir == WTF::Unicode::kEuropeanNumber)
+ else if (dir == WTF::unicode::kArabicNumber ||
+ dir == WTF::unicode::kEuropeanNumber)
level_ += 2;
}
}
diff --git a/chromium/third_party/blink/renderer/platform/text/bidi_context.cc b/chromium/third_party/blink/renderer/platform/text/bidi_context.cc
index c8c89b1735f..37b08a5cea6 100644
--- a/chromium/third_party/blink/renderer/platform/text/bidi_context.cc
+++ b/chromium/third_party/blink/renderer/platform/text/bidi_context.cc
@@ -38,7 +38,7 @@ static_assert(sizeof(BidiContext) == sizeof(SameSizeAsBidiContext),
inline scoped_refptr<BidiContext> BidiContext::CreateUncached(
unsigned char level,
- WTF::Unicode::CharDirection direction,
+ WTF::unicode::CharDirection direction,
bool override,
BidiEmbeddingSource source,
BidiContext* parent) {
@@ -48,12 +48,12 @@ inline scoped_refptr<BidiContext> BidiContext::CreateUncached(
scoped_refptr<BidiContext> BidiContext::Create(
unsigned char level,
- WTF::Unicode::CharDirection direction,
+ WTF::unicode::CharDirection direction,
bool override,
BidiEmbeddingSource source,
BidiContext* parent) {
- DCHECK_EQ(direction, (level % 2 ? WTF::Unicode::kRightToLeft
- : WTF::Unicode::kLeftToRight));
+ DCHECK_EQ(direction, (level % 2 ? WTF::unicode::kRightToLeft
+ : WTF::unicode::kLeftToRight));
if (parent || level >= 2)
return CreateUncached(level, direction, override, source, parent);
@@ -62,26 +62,26 @@ scoped_refptr<BidiContext> BidiContext::Create(
if (!level) {
if (!override) {
DEFINE_STATIC_REF(BidiContext, ltr_context,
- (CreateUncached(0, WTF::Unicode::kLeftToRight, false,
+ (CreateUncached(0, WTF::unicode::kLeftToRight, false,
kFromStyleOrDOM, nullptr)));
return ltr_context;
}
DEFINE_STATIC_REF(BidiContext, ltr_override_context,
- (CreateUncached(0, WTF::Unicode::kLeftToRight, true,
+ (CreateUncached(0, WTF::unicode::kLeftToRight, true,
kFromStyleOrDOM, nullptr)));
return ltr_override_context;
}
if (!override) {
DEFINE_STATIC_REF(BidiContext, rtl_context,
- (CreateUncached(1, WTF::Unicode::kRightToLeft, false,
+ (CreateUncached(1, WTF::unicode::kRightToLeft, false,
kFromStyleOrDOM, nullptr)));
return rtl_context;
}
DEFINE_STATIC_REF(BidiContext, rtl_override_context,
- (CreateUncached(1, WTF::Unicode::kRightToLeft, true,
+ (CreateUncached(1, WTF::unicode::kRightToLeft, true,
kFromStyleOrDOM, nullptr)));
return rtl_override_context;
}
@@ -91,7 +91,7 @@ static inline scoped_refptr<BidiContext> CopyContextAndRebaselineLevel(
BidiContext* parent) {
DCHECK(context);
unsigned char new_level = parent ? parent->Level() : 0;
- if (context->Dir() == WTF::Unicode::kRightToLeft)
+ if (context->Dir() == WTF::unicode::kRightToLeft)
new_level = NextGreaterOddLevel(new_level);
else if (parent)
new_level = NextGreaterEvenLevel(new_level);
diff --git a/chromium/third_party/blink/renderer/platform/text/bidi_context.h b/chromium/third_party/blink/renderer/platform/text/bidi_context.h
index e376d5f99fa..743ce4ba0bb 100644
--- a/chromium/third_party/blink/renderer/platform/text/bidi_context.h
+++ b/chromium/third_party/blink/renderer/platform/text/bidi_context.h
@@ -38,15 +38,15 @@ class PLATFORM_EXPORT BidiContext : public ThreadSafeRefCounted<BidiContext> {
public:
static scoped_refptr<BidiContext> Create(
unsigned char level,
- WTF::Unicode::CharDirection,
+ WTF::unicode::CharDirection,
bool override = false,
BidiEmbeddingSource = kFromStyleOrDOM,
BidiContext* parent = nullptr);
BidiContext* Parent() const { return parent_.get(); }
unsigned char Level() const { return level_; }
- WTF::Unicode::CharDirection Dir() const {
- return static_cast<WTF::Unicode::CharDirection>(direction_);
+ WTF::unicode::CharDirection Dir() const {
+ return static_cast<WTF::unicode::CharDirection>(direction_);
}
bool Override() const { return override_; }
BidiEmbeddingSource Source() const {
@@ -62,7 +62,7 @@ class PLATFORM_EXPORT BidiContext : public ThreadSafeRefCounted<BidiContext> {
private:
BidiContext(unsigned char level,
- WTF::Unicode::CharDirection direction,
+ WTF::unicode::CharDirection direction,
bool override,
BidiEmbeddingSource source,
BidiContext* parent)
@@ -75,7 +75,7 @@ class PLATFORM_EXPORT BidiContext : public ThreadSafeRefCounted<BidiContext> {
}
static scoped_refptr<BidiContext> CreateUncached(unsigned char level,
- WTF::Unicode::CharDirection,
+ WTF::unicode::CharDirection,
bool override,
BidiEmbeddingSource,
BidiContext* parent);
diff --git a/chromium/third_party/blink/renderer/platform/text/bidi_resolver.h b/chromium/third_party/blink/renderer/platform/text/bidi_resolver.h
index aba93e53c16..3dd964e0132 100644
--- a/chromium/third_party/blink/renderer/platform/text/bidi_resolver.h
+++ b/chromium/third_party/blink/renderer/platform/text/bidi_resolver.h
@@ -124,25 +124,25 @@ class MidpointState final {
struct BidiStatus final {
DISALLOW_NEW();
BidiStatus()
- : eor(WTF::Unicode::kOtherNeutral),
- last_strong(WTF::Unicode::kOtherNeutral),
- last(WTF::Unicode::kOtherNeutral) {}
+ : eor(WTF::unicode::kOtherNeutral),
+ last_strong(WTF::unicode::kOtherNeutral),
+ last(WTF::unicode::kOtherNeutral) {}
// Creates a BidiStatus representing a new paragraph root with a default
// direction. Uses TextDirection as it only has two possibilities instead of
- // WTF::Unicode::Direction which has 19.
+ // WTF::unicode::Direction which has 19.
BidiStatus(TextDirection text_direction, bool is_override) {
- WTF::Unicode::CharDirection direction =
- text_direction == TextDirection::kLtr ? WTF::Unicode::kLeftToRight
- : WTF::Unicode::kRightToLeft;
+ WTF::unicode::CharDirection direction =
+ text_direction == TextDirection::kLtr ? WTF::unicode::kLeftToRight
+ : WTF::unicode::kRightToLeft;
eor = last_strong = last = direction;
context = BidiContext::Create(text_direction == TextDirection::kLtr ? 0 : 1,
direction, is_override);
}
- BidiStatus(WTF::Unicode::CharDirection eor_dir,
- WTF::Unicode::CharDirection last_strong_dir,
- WTF::Unicode::CharDirection last_dir,
+ BidiStatus(WTF::unicode::CharDirection eor_dir,
+ WTF::unicode::CharDirection last_strong_dir,
+ WTF::unicode::CharDirection last_dir,
scoped_refptr<BidiContext> bidi_context)
: eor(eor_dir),
last_strong(last_strong_dir),
@@ -154,13 +154,13 @@ struct BidiStatus final {
static BidiStatus CreateForIsolate(TextDirection text_direction,
bool is_override,
unsigned char level) {
- WTF::Unicode::CharDirection direction;
+ WTF::unicode::CharDirection direction;
if (text_direction == TextDirection::kRtl) {
level = NextGreaterOddLevel(level);
- direction = WTF::Unicode::kRightToLeft;
+ direction = WTF::unicode::kRightToLeft;
} else {
level = NextGreaterEvenLevel(level);
- direction = WTF::Unicode::kLeftToRight;
+ direction = WTF::unicode::kLeftToRight;
}
scoped_refptr<BidiContext> context =
BidiContext::Create(level, direction, is_override, kFromStyleOrDOM);
@@ -170,9 +170,9 @@ struct BidiStatus final {
return BidiStatus(direction, direction, direction, std::move(context));
}
- WTF::Unicode::CharDirection eor;
- WTF::Unicode::CharDirection last_strong;
- WTF::Unicode::CharDirection last;
+ WTF::unicode::CharDirection eor;
+ WTF::unicode::CharDirection last_strong;
+ WTF::unicode::CharDirection last;
scoped_refptr<BidiContext> context;
};
@@ -180,15 +180,15 @@ class BidiEmbedding final {
DISALLOW_NEW();
public:
- BidiEmbedding(WTF::Unicode::CharDirection direction,
+ BidiEmbedding(WTF::unicode::CharDirection direction,
BidiEmbeddingSource source)
: direction_(direction), source_(source) {}
- WTF::Unicode::CharDirection Direction() const { return direction_; }
+ WTF::unicode::CharDirection Direction() const { return direction_; }
BidiEmbeddingSource Source() const { return source_; }
private:
- WTF::Unicode::CharDirection direction_;
+ WTF::unicode::CharDirection direction_;
BidiEmbeddingSource source_;
};
@@ -218,7 +218,7 @@ class BidiResolver final {
public:
BidiResolver()
- : direction_(WTF::Unicode::kOtherNeutral),
+ : direction_(WTF::unicode::kOtherNeutral),
reached_end_of_line_(false),
empty_run_(true),
nested_isolate_count_(0),
@@ -244,22 +244,22 @@ class BidiResolver final {
status_.context = std::move(c);
}
- void SetLastDir(WTF::Unicode::CharDirection last_dir) {
+ void SetLastDir(WTF::unicode::CharDirection last_dir) {
status_.last = last_dir;
}
- void SetLastStrongDir(WTF::Unicode::CharDirection last_strong_dir) {
+ void SetLastStrongDir(WTF::unicode::CharDirection last_strong_dir) {
status_.last_strong = last_strong_dir;
}
- void SetEorDir(WTF::Unicode::CharDirection eor_dir) { status_.eor = eor_dir; }
+ void SetEorDir(WTF::unicode::CharDirection eor_dir) { status_.eor = eor_dir; }
- WTF::Unicode::CharDirection Dir() const { return direction_; }
- void SetDir(WTF::Unicode::CharDirection d) { direction_ = d; }
+ WTF::unicode::CharDirection Dir() const { return direction_; }
+ void SetDir(WTF::unicode::CharDirection d) { direction_ = d; }
const BidiStatus& Status() const { return status_; }
void SetStatus(const BidiStatus s) {
DCHECK(s.context);
status_ = s;
- paragraph_directionality_ = s.context->Dir() == WTF::Unicode::kLeftToRight
+ paragraph_directionality_ = s.context->Dir() == WTF::unicode::kLeftToRight
? TextDirection::kLtr
: TextDirection::kRtl;
}
@@ -276,7 +276,7 @@ class BidiResolver final {
}
bool InIsolate() const { return nested_isolate_count_; }
- void Embed(WTF::Unicode::CharDirection, BidiEmbeddingSource);
+ void Embed(WTF::unicode::CharDirection, BidiEmbeddingSource);
bool CommitExplicitEmbedding(BidiRunList<Run>&);
void CreateBidiRunsForLine(const Iterator& end,
@@ -339,7 +339,7 @@ class BidiResolver final {
Iterator eor_; // Points to the last character in the current run.
Iterator last_;
BidiStatus status_;
- WTF::Unicode::CharDirection direction_;
+ WTF::unicode::CharDirection direction_;
// m_endOfRunAtEndOfLine is "the position last eor in the end of line"
Iterator end_of_run_at_end_of_line_;
Iterator end_of_line_;
@@ -361,13 +361,13 @@ class BidiResolver final {
private:
void RaiseExplicitEmbeddingLevel(BidiRunList<Run>&,
- WTF::Unicode::CharDirection from,
- WTF::Unicode::CharDirection to);
+ WTF::unicode::CharDirection from,
+ WTF::unicode::CharDirection to);
void LowerExplicitEmbeddingLevel(BidiRunList<Run>&,
- WTF::Unicode::CharDirection from);
+ WTF::unicode::CharDirection from);
void CheckDirectionInLowerRaiseEmbeddingLevel();
- void UpdateStatusLastFromCurrentDirection(WTF::Unicode::CharDirection);
+ void UpdateStatusLastFromCurrentDirection(WTF::unicode::CharDirection);
void ReorderRunsFromLevels(BidiRunList<Run>&) const;
bool NeedsTrailingSpace(BidiRunList<Run>&) { return needs_trailing_space_; }
@@ -428,71 +428,71 @@ void BidiResolver<Iterator, Run, IsolatedRun>::AppendRun(
sor_ = eor_;
}
- direction_ = WTF::Unicode::kOtherNeutral;
- status_.eor = WTF::Unicode::kOtherNeutral;
+ direction_ = WTF::unicode::kOtherNeutral;
+ status_.eor = WTF::unicode::kOtherNeutral;
}
template <class Iterator, class Run, class IsolatedRun>
void BidiResolver<Iterator, Run, IsolatedRun>::Embed(
- WTF::Unicode::CharDirection dir,
+ WTF::unicode::CharDirection dir,
BidiEmbeddingSource source) {
// Isolated spans compute base directionality during their own UBA run.
// Do not insert fake embed characters once we enter an isolated span.
DCHECK(!InIsolate());
- DCHECK(dir == WTF::Unicode::kPopDirectionalFormat ||
- dir == WTF::Unicode::kLeftToRightEmbedding ||
- dir == WTF::Unicode::kLeftToRightOverride ||
- dir == WTF::Unicode::kRightToLeftEmbedding ||
- dir == WTF::Unicode::kRightToLeftOverride);
+ DCHECK(dir == WTF::unicode::kPopDirectionalFormat ||
+ dir == WTF::unicode::kLeftToRightEmbedding ||
+ dir == WTF::unicode::kLeftToRightOverride ||
+ dir == WTF::unicode::kRightToLeftEmbedding ||
+ dir == WTF::unicode::kRightToLeftOverride);
current_explicit_embedding_sequence_.push_back(BidiEmbedding(dir, source));
}
template <class Iterator, class Run, class IsolatedRun>
void BidiResolver<Iterator, Run, IsolatedRun>::
CheckDirectionInLowerRaiseEmbeddingLevel() {
- DCHECK(status_.eor != WTF::Unicode::kOtherNeutral || eor_.AtEnd());
- DCHECK_NE(status_.last, WTF::Unicode::kNonSpacingMark);
- DCHECK_NE(status_.last, WTF::Unicode::kBoundaryNeutral);
- DCHECK_NE(status_.last, WTF::Unicode::kRightToLeftEmbedding);
- DCHECK_NE(status_.last, WTF::Unicode::kLeftToRightEmbedding);
- DCHECK_NE(status_.last, WTF::Unicode::kRightToLeftOverride);
- DCHECK_NE(status_.last, WTF::Unicode::kLeftToRightOverride);
- DCHECK_NE(status_.last, WTF::Unicode::kPopDirectionalFormat);
- if (direction_ == WTF::Unicode::kOtherNeutral) {
- direction_ = status_.last_strong == WTF::Unicode::kLeftToRight
- ? WTF::Unicode::kLeftToRight
- : WTF::Unicode::kRightToLeft;
+ DCHECK(status_.eor != WTF::unicode::kOtherNeutral || eor_.AtEnd());
+ DCHECK_NE(status_.last, WTF::unicode::kNonSpacingMark);
+ DCHECK_NE(status_.last, WTF::unicode::kBoundaryNeutral);
+ DCHECK_NE(status_.last, WTF::unicode::kRightToLeftEmbedding);
+ DCHECK_NE(status_.last, WTF::unicode::kLeftToRightEmbedding);
+ DCHECK_NE(status_.last, WTF::unicode::kRightToLeftOverride);
+ DCHECK_NE(status_.last, WTF::unicode::kLeftToRightOverride);
+ DCHECK_NE(status_.last, WTF::unicode::kPopDirectionalFormat);
+ if (direction_ == WTF::unicode::kOtherNeutral) {
+ direction_ = status_.last_strong == WTF::unicode::kLeftToRight
+ ? WTF::unicode::kLeftToRight
+ : WTF::unicode::kRightToLeft;
}
}
template <class Iterator, class Run, class IsolatedRun>
void BidiResolver<Iterator, Run, IsolatedRun>::LowerExplicitEmbeddingLevel(
BidiRunList<Run>& runs,
- WTF::Unicode::CharDirection from) {
+ WTF::unicode::CharDirection from) {
if (!empty_run_ && eor_ != last_) {
CheckDirectionInLowerRaiseEmbeddingLevel();
// bidi.sor ... bidi.eor ... bidi.last eor; need to append the
// bidi.sor-bidi.eor run or extend it through bidi.last
- if (from == WTF::Unicode::kLeftToRight) {
+ if (from == WTF::unicode::kLeftToRight) {
// bidi.sor ... bidi.eor ... bidi.last L
- if (status_.eor == WTF::Unicode::kEuropeanNumber) {
- if (status_.last_strong != WTF::Unicode::kLeftToRight) {
- direction_ = WTF::Unicode::kEuropeanNumber;
+ if (status_.eor == WTF::unicode::kEuropeanNumber) {
+ if (status_.last_strong != WTF::unicode::kLeftToRight) {
+ direction_ = WTF::unicode::kEuropeanNumber;
AppendRun(runs);
}
- } else if (status_.eor == WTF::Unicode::kArabicNumber) {
- direction_ = WTF::Unicode::kArabicNumber;
+ } else if (status_.eor == WTF::unicode::kArabicNumber) {
+ direction_ = WTF::unicode::kArabicNumber;
AppendRun(runs);
- } else if (status_.last_strong != WTF::Unicode::kLeftToRight) {
+ } else if (status_.last_strong != WTF::unicode::kLeftToRight) {
AppendRun(runs);
- direction_ = WTF::Unicode::kLeftToRight;
+ direction_ = WTF::unicode::kLeftToRight;
}
- } else if (status_.eor == WTF::Unicode::kEuropeanNumber ||
- status_.eor == WTF::Unicode::kArabicNumber ||
- status_.last_strong == WTF::Unicode::kLeftToRight) {
+ } else if (status_.eor == WTF::unicode::kEuropeanNumber ||
+ status_.eor == WTF::unicode::kArabicNumber ||
+ status_.last_strong == WTF::unicode::kLeftToRight) {
AppendRun(runs);
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
}
eor_ = last_;
}
@@ -509,36 +509,36 @@ void BidiResolver<Iterator, Run, IsolatedRun>::LowerExplicitEmbeddingLevel(
template <class Iterator, class Run, class IsolatedRun>
void BidiResolver<Iterator, Run, IsolatedRun>::RaiseExplicitEmbeddingLevel(
BidiRunList<Run>& runs,
- WTF::Unicode::CharDirection from,
- WTF::Unicode::CharDirection to) {
+ WTF::unicode::CharDirection from,
+ WTF::unicode::CharDirection to) {
if (!empty_run_ && eor_ != last_) {
CheckDirectionInLowerRaiseEmbeddingLevel();
// bidi.sor ... bidi.eor ... bidi.last eor; need to append the
// bidi.sor-bidi.eor run or extend it through bidi.last
- if (to == WTF::Unicode::kLeftToRight) {
+ if (to == WTF::unicode::kLeftToRight) {
// bidi.sor ... bidi.eor ... bidi.last L
- if (status_.eor == WTF::Unicode::kEuropeanNumber) {
- if (status_.last_strong != WTF::Unicode::kLeftToRight) {
- direction_ = WTF::Unicode::kEuropeanNumber;
+ if (status_.eor == WTF::unicode::kEuropeanNumber) {
+ if (status_.last_strong != WTF::unicode::kLeftToRight) {
+ direction_ = WTF::unicode::kEuropeanNumber;
AppendRun(runs);
}
- } else if (status_.eor == WTF::Unicode::kArabicNumber) {
- direction_ = WTF::Unicode::kArabicNumber;
+ } else if (status_.eor == WTF::unicode::kArabicNumber) {
+ direction_ = WTF::unicode::kArabicNumber;
AppendRun(runs);
- } else if (status_.last_strong != WTF::Unicode::kLeftToRight &&
- from == WTF::Unicode::kLeftToRight) {
+ } else if (status_.last_strong != WTF::unicode::kLeftToRight &&
+ from == WTF::unicode::kLeftToRight) {
AppendRun(runs);
- direction_ = WTF::Unicode::kLeftToRight;
+ direction_ = WTF::unicode::kLeftToRight;
}
- } else if (status_.eor == WTF::Unicode::kArabicNumber ||
- (status_.eor == WTF::Unicode::kEuropeanNumber &&
- (status_.last_strong != WTF::Unicode::kLeftToRight ||
- from == WTF::Unicode::kRightToLeft)) ||
- (status_.eor != WTF::Unicode::kEuropeanNumber &&
- status_.last_strong == WTF::Unicode::kLeftToRight &&
- from == WTF::Unicode::kRightToLeft)) {
+ } else if (status_.eor == WTF::unicode::kArabicNumber ||
+ (status_.eor == WTF::unicode::kEuropeanNumber &&
+ (status_.last_strong != WTF::unicode::kLeftToRight ||
+ from == WTF::unicode::kRightToLeft)) ||
+ (status_.eor != WTF::unicode::kEuropeanNumber &&
+ status_.last_strong == WTF::unicode::kLeftToRight &&
+ from == WTF::unicode::kRightToLeft)) {
AppendRun(runs);
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
}
eor_ = last_;
}
@@ -607,20 +607,20 @@ bool BidiResolver<Iterator, Run, IsolatedRun>::CommitExplicitEmbedding(
scoped_refptr<BidiContext> to_context = Context();
for (const BidiEmbedding& embedding : current_explicit_embedding_sequence_) {
- if (embedding.Direction() == WTF::Unicode::kPopDirectionalFormat) {
+ if (embedding.Direction() == WTF::unicode::kPopDirectionalFormat) {
if (BidiContext* parent_context = to_context->Parent())
to_context = parent_context;
} else {
- WTF::Unicode::CharDirection direction =
- (embedding.Direction() == WTF::Unicode::kRightToLeftEmbedding ||
- embedding.Direction() == WTF::Unicode::kRightToLeftOverride)
- ? WTF::Unicode::kRightToLeft
- : WTF::Unicode::kLeftToRight;
+ WTF::unicode::CharDirection direction =
+ (embedding.Direction() == WTF::unicode::kRightToLeftEmbedding ||
+ embedding.Direction() == WTF::unicode::kRightToLeftOverride)
+ ? WTF::unicode::kRightToLeft
+ : WTF::unicode::kLeftToRight;
bool override =
- embedding.Direction() == WTF::Unicode::kLeftToRightOverride ||
- embedding.Direction() == WTF::Unicode::kRightToLeftOverride;
+ embedding.Direction() == WTF::unicode::kLeftToRightOverride ||
+ embedding.Direction() == WTF::unicode::kRightToLeftOverride;
unsigned char level = to_context->Level();
- if (direction == WTF::Unicode::kRightToLeft)
+ if (direction == WTF::unicode::kRightToLeft)
level = NextGreaterOddLevel(level);
else
level = NextGreaterEvenLevel(level);
@@ -636,13 +636,13 @@ bool BidiResolver<Iterator, Run, IsolatedRun>::CommitExplicitEmbedding(
if (to_level > from_level) {
RaiseExplicitEmbeddingLevel(
runs,
- from_level % 2 ? WTF::Unicode::kRightToLeft
- : WTF::Unicode::kLeftToRight,
- to_level % 2 ? WTF::Unicode::kRightToLeft : WTF::Unicode::kLeftToRight);
+ from_level % 2 ? WTF::unicode::kRightToLeft
+ : WTF::unicode::kLeftToRight,
+ to_level % 2 ? WTF::unicode::kRightToLeft : WTF::unicode::kLeftToRight);
} else if (to_level < from_level) {
LowerExplicitEmbeddingLevel(runs, from_level % 2
- ? WTF::Unicode::kRightToLeft
- : WTF::Unicode::kLeftToRight);
+ ? WTF::unicode::kRightToLeft
+ : WTF::unicode::kLeftToRight);
}
SetContext(to_context);
@@ -655,39 +655,39 @@ bool BidiResolver<Iterator, Run, IsolatedRun>::CommitExplicitEmbedding(
template <class Iterator, class Run, class IsolatedRun>
inline void
BidiResolver<Iterator, Run, IsolatedRun>::UpdateStatusLastFromCurrentDirection(
- WTF::Unicode::CharDirection dir_current) {
+ WTF::unicode::CharDirection dir_current) {
switch (dir_current) {
- case WTF::Unicode::kEuropeanNumberTerminator:
- if (status_.last != WTF::Unicode::kEuropeanNumber)
- status_.last = WTF::Unicode::kEuropeanNumberTerminator;
+ case WTF::unicode::kEuropeanNumberTerminator:
+ if (status_.last != WTF::unicode::kEuropeanNumber)
+ status_.last = WTF::unicode::kEuropeanNumberTerminator;
break;
- case WTF::Unicode::kEuropeanNumberSeparator:
- case WTF::Unicode::kCommonNumberSeparator:
- case WTF::Unicode::kSegmentSeparator:
- case WTF::Unicode::kWhiteSpaceNeutral:
- case WTF::Unicode::kOtherNeutral:
+ case WTF::unicode::kEuropeanNumberSeparator:
+ case WTF::unicode::kCommonNumberSeparator:
+ case WTF::unicode::kSegmentSeparator:
+ case WTF::unicode::kWhiteSpaceNeutral:
+ case WTF::unicode::kOtherNeutral:
switch (status_.last) {
- case WTF::Unicode::kLeftToRight:
- case WTF::Unicode::kRightToLeft:
- case WTF::Unicode::kRightToLeftArabic:
- case WTF::Unicode::kEuropeanNumber:
- case WTF::Unicode::kArabicNumber:
+ case WTF::unicode::kLeftToRight:
+ case WTF::unicode::kRightToLeft:
+ case WTF::unicode::kRightToLeftArabic:
+ case WTF::unicode::kEuropeanNumber:
+ case WTF::unicode::kArabicNumber:
status_.last = dir_current;
break;
default:
- status_.last = WTF::Unicode::kOtherNeutral;
+ status_.last = WTF::unicode::kOtherNeutral;
}
break;
- case WTF::Unicode::kNonSpacingMark:
- case WTF::Unicode::kBoundaryNeutral:
- case WTF::Unicode::kRightToLeftEmbedding:
- case WTF::Unicode::kLeftToRightEmbedding:
- case WTF::Unicode::kRightToLeftOverride:
- case WTF::Unicode::kLeftToRightOverride:
- case WTF::Unicode::kPopDirectionalFormat:
+ case WTF::unicode::kNonSpacingMark:
+ case WTF::unicode::kBoundaryNeutral:
+ case WTF::unicode::kRightToLeftEmbedding:
+ case WTF::unicode::kLeftToRightEmbedding:
+ case WTF::unicode::kRightToLeftOverride:
+ case WTF::unicode::kLeftToRightOverride:
+ case WTF::unicode::kPopDirectionalFormat:
// ignore these
break;
- case WTF::Unicode::kEuropeanNumber:
+ case WTF::unicode::kEuropeanNumber:
// fall through
default:
status_.last = dir_current;
@@ -761,15 +761,15 @@ BidiResolver<Iterator, Run, IsolatedRun>::DetermineDirectionalityInternal(
continue;
current = U16_GET_SUPPLEMENTARY(high, low);
}
- WTF::Unicode::CharDirection char_direction =
- WTF::Unicode::Direction(current);
- if (char_direction == WTF::Unicode::kLeftToRight) {
+ WTF::unicode::CharDirection char_direction =
+ WTF::unicode::Direction(current);
+ if (char_direction == WTF::unicode::kLeftToRight) {
if (has_strong_directionality)
*has_strong_directionality = true;
return TextDirection::kLtr;
}
- if (char_direction == WTF::Unicode::kRightToLeft ||
- char_direction == WTF::Unicode::kRightToLeftArabic) {
+ if (char_direction == WTF::unicode::kRightToLeft ||
+ char_direction == WTF::unicode::kRightToLeftArabic) {
if (has_strong_directionality)
*has_strong_directionality = true;
return TextDirection::kRtl;
@@ -782,10 +782,10 @@ BidiResolver<Iterator, Run, IsolatedRun>::DetermineDirectionalityInternal(
}
inline TextDirection DirectionForCharacter(UChar32 character) {
- WTF::Unicode::CharDirection char_direction =
- WTF::Unicode::Direction(character);
- if (char_direction == WTF::Unicode::kRightToLeft ||
- char_direction == WTF::Unicode::kRightToLeftArabic)
+ WTF::unicode::CharDirection char_direction =
+ WTF::unicode::Direction(character);
+ if (char_direction == WTF::unicode::kRightToLeft ||
+ char_direction == WTF::unicode::kRightToLeftArabic)
return TextDirection::kRtl;
return TextDirection::kLtr;
}
@@ -796,7 +796,7 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
VisualDirectionOverride override,
bool hard_line_break,
bool reorder_runs) {
- DCHECK_EQ(direction_, WTF::Unicode::kOtherNeutral);
+ DCHECK_EQ(direction_, WTF::unicode::kOtherNeutral);
trailing_space_run_ = nullptr;
end_of_line_ = end;
@@ -810,8 +810,8 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
Increment();
}
direction_ = override == kVisualLeftToRightOverride
- ? WTF::Unicode::kLeftToRight
- : WTF::Unicode::kRightToLeft;
+ ? WTF::unicode::kLeftToRight
+ : WTF::unicode::kRightToLeft;
AppendRun(runs_);
runs_.SetLogicallyLastRun(runs_.LastRun());
if (override == kVisualRightToLeftOverride && runs_.RunCount())
@@ -847,7 +847,7 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
end_of_run_at_end_of_line_ = last_;
last_line_ended = true;
}
- WTF::Unicode::CharDirection dir_current;
+ WTF::unicode::CharDirection dir_current;
if (last_line_ended && (hard_line_break || current_.AtEnd())) {
BidiContext* c = Context();
if (hard_line_break) {
@@ -869,83 +869,83 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
} else {
dir_current = current_.Direction();
if (Context()->Override() &&
- dir_current != WTF::Unicode::kRightToLeftEmbedding &&
- dir_current != WTF::Unicode::kLeftToRightEmbedding &&
- dir_current != WTF::Unicode::kRightToLeftOverride &&
- dir_current != WTF::Unicode::kLeftToRightOverride &&
- dir_current != WTF::Unicode::kPopDirectionalFormat)
+ dir_current != WTF::unicode::kRightToLeftEmbedding &&
+ dir_current != WTF::unicode::kLeftToRightEmbedding &&
+ dir_current != WTF::unicode::kRightToLeftOverride &&
+ dir_current != WTF::unicode::kLeftToRightOverride &&
+ dir_current != WTF::unicode::kPopDirectionalFormat)
dir_current = Context()->Dir();
- else if (dir_current == WTF::Unicode::kNonSpacingMark)
+ else if (dir_current == WTF::unicode::kNonSpacingMark)
dir_current = status_.last;
}
// We ignore all character directionality while in unicode-bidi: isolate
// spans. We'll handle ordering the isolated characters in a second pass.
if (InIsolate())
- dir_current = WTF::Unicode::kOtherNeutral;
+ dir_current = WTF::unicode::kOtherNeutral;
- DCHECK(status_.eor != WTF::Unicode::kOtherNeutral || eor_.AtEnd());
+ DCHECK(status_.eor != WTF::unicode::kOtherNeutral || eor_.AtEnd());
switch (dir_current) {
// embedding and overrides (X1-X9 in the Bidi specs)
- case WTF::Unicode::kRightToLeftEmbedding:
- case WTF::Unicode::kLeftToRightEmbedding:
- case WTF::Unicode::kRightToLeftOverride:
- case WTF::Unicode::kLeftToRightOverride:
- case WTF::Unicode::kPopDirectionalFormat:
+ case WTF::unicode::kRightToLeftEmbedding:
+ case WTF::unicode::kLeftToRightEmbedding:
+ case WTF::unicode::kRightToLeftOverride:
+ case WTF::unicode::kLeftToRightOverride:
+ case WTF::unicode::kPopDirectionalFormat:
Embed(dir_current, kFromUnicode);
CommitExplicitEmbedding(runs_);
break;
// strong types
- case WTF::Unicode::kLeftToRight:
+ case WTF::unicode::kLeftToRight:
switch (status_.last) {
- case WTF::Unicode::kRightToLeft:
- case WTF::Unicode::kRightToLeftArabic:
- case WTF::Unicode::kEuropeanNumber:
- case WTF::Unicode::kArabicNumber:
- if (status_.last != WTF::Unicode::kEuropeanNumber ||
- status_.last_strong != WTF::Unicode::kLeftToRight)
+ case WTF::unicode::kRightToLeft:
+ case WTF::unicode::kRightToLeftArabic:
+ case WTF::unicode::kEuropeanNumber:
+ case WTF::unicode::kArabicNumber:
+ if (status_.last != WTF::unicode::kEuropeanNumber ||
+ status_.last_strong != WTF::unicode::kLeftToRight)
AppendRun(runs_);
break;
- case WTF::Unicode::kLeftToRight:
+ case WTF::unicode::kLeftToRight:
break;
- case WTF::Unicode::kEuropeanNumberSeparator:
- case WTF::Unicode::kEuropeanNumberTerminator:
- case WTF::Unicode::kCommonNumberSeparator:
- case WTF::Unicode::kBoundaryNeutral:
- case WTF::Unicode::kBlockSeparator:
- case WTF::Unicode::kSegmentSeparator:
- case WTF::Unicode::kWhiteSpaceNeutral:
- case WTF::Unicode::kOtherNeutral:
- if (status_.eor == WTF::Unicode::kEuropeanNumber) {
- if (status_.last_strong != WTF::Unicode::kLeftToRight) {
+ case WTF::unicode::kEuropeanNumberSeparator:
+ case WTF::unicode::kEuropeanNumberTerminator:
+ case WTF::unicode::kCommonNumberSeparator:
+ case WTF::unicode::kBoundaryNeutral:
+ case WTF::unicode::kBlockSeparator:
+ case WTF::unicode::kSegmentSeparator:
+ case WTF::unicode::kWhiteSpaceNeutral:
+ case WTF::unicode::kOtherNeutral:
+ if (status_.eor == WTF::unicode::kEuropeanNumber) {
+ if (status_.last_strong != WTF::unicode::kLeftToRight) {
// the numbers need to be on a higher embedding level, so let's
// close that run
- direction_ = WTF::Unicode::kEuropeanNumber;
+ direction_ = WTF::unicode::kEuropeanNumber;
AppendRun(runs_);
- if (Context()->Dir() != WTF::Unicode::kLeftToRight) {
+ if (Context()->Dir() != WTF::unicode::kLeftToRight) {
// the neutrals take the embedding direction, which is R
eor_ = last_;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
AppendRun(runs_);
}
}
- } else if (status_.eor == WTF::Unicode::kArabicNumber) {
+ } else if (status_.eor == WTF::unicode::kArabicNumber) {
// Arabic numbers are always on a higher embedding level, so let's
// close that run
- direction_ = WTF::Unicode::kArabicNumber;
+ direction_ = WTF::unicode::kArabicNumber;
AppendRun(runs_);
- if (Context()->Dir() != WTF::Unicode::kLeftToRight) {
+ if (Context()->Dir() != WTF::unicode::kLeftToRight) {
// the neutrals take the embedding direction, which is R
eor_ = last_;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
AppendRun(runs_);
}
- } else if (status_.last_strong != WTF::Unicode::kLeftToRight) {
+ } else if (status_.last_strong != WTF::unicode::kLeftToRight) {
// last stuff takes embedding dir
- if (Context()->Dir() == WTF::Unicode::kRightToLeft) {
+ if (Context()->Dir() == WTF::unicode::kRightToLeft) {
eor_ = last_;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
}
AppendRun(runs_);
}
@@ -954,38 +954,38 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
break;
}
eor_ = current_;
- status_.eor = WTF::Unicode::kLeftToRight;
- status_.last_strong = WTF::Unicode::kLeftToRight;
- direction_ = WTF::Unicode::kLeftToRight;
+ status_.eor = WTF::unicode::kLeftToRight;
+ status_.last_strong = WTF::unicode::kLeftToRight;
+ direction_ = WTF::unicode::kLeftToRight;
break;
- case WTF::Unicode::kRightToLeftArabic:
- case WTF::Unicode::kRightToLeft:
+ case WTF::unicode::kRightToLeftArabic:
+ case WTF::unicode::kRightToLeft:
switch (status_.last) {
- case WTF::Unicode::kLeftToRight:
- case WTF::Unicode::kEuropeanNumber:
- case WTF::Unicode::kArabicNumber:
+ case WTF::unicode::kLeftToRight:
+ case WTF::unicode::kEuropeanNumber:
+ case WTF::unicode::kArabicNumber:
AppendRun(runs_);
break;
- case WTF::Unicode::kRightToLeft:
- case WTF::Unicode::kRightToLeftArabic:
+ case WTF::unicode::kRightToLeft:
+ case WTF::unicode::kRightToLeftArabic:
break;
- case WTF::Unicode::kEuropeanNumberSeparator:
- case WTF::Unicode::kEuropeanNumberTerminator:
- case WTF::Unicode::kCommonNumberSeparator:
- case WTF::Unicode::kBoundaryNeutral:
- case WTF::Unicode::kBlockSeparator:
- case WTF::Unicode::kSegmentSeparator:
- case WTF::Unicode::kWhiteSpaceNeutral:
- case WTF::Unicode::kOtherNeutral:
- if (status_.eor == WTF::Unicode::kEuropeanNumber) {
- if (status_.last_strong == WTF::Unicode::kLeftToRight &&
- Context()->Dir() == WTF::Unicode::kLeftToRight)
+ case WTF::unicode::kEuropeanNumberSeparator:
+ case WTF::unicode::kEuropeanNumberTerminator:
+ case WTF::unicode::kCommonNumberSeparator:
+ case WTF::unicode::kBoundaryNeutral:
+ case WTF::unicode::kBlockSeparator:
+ case WTF::unicode::kSegmentSeparator:
+ case WTF::unicode::kWhiteSpaceNeutral:
+ case WTF::unicode::kOtherNeutral:
+ if (status_.eor == WTF::unicode::kEuropeanNumber) {
+ if (status_.last_strong == WTF::unicode::kLeftToRight &&
+ Context()->Dir() == WTF::unicode::kLeftToRight)
eor_ = last_;
AppendRun(runs_);
- } else if (status_.eor == WTF::Unicode::kArabicNumber) {
+ } else if (status_.eor == WTF::unicode::kArabicNumber) {
AppendRun(runs_);
- } else if (status_.last_strong == WTF::Unicode::kLeftToRight) {
- if (Context()->Dir() == WTF::Unicode::kLeftToRight)
+ } else if (status_.last_strong == WTF::unicode::kLeftToRight) {
+ if (Context()->Dir() == WTF::unicode::kLeftToRight)
eor_ = last_;
AppendRun(runs_);
}
@@ -994,129 +994,129 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
break;
}
eor_ = current_;
- status_.eor = WTF::Unicode::kRightToLeft;
+ status_.eor = WTF::unicode::kRightToLeft;
status_.last_strong = dir_current;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
break;
// weak types:
- case WTF::Unicode::kEuropeanNumber:
+ case WTF::unicode::kEuropeanNumber:
// If last_strong is kRightToLeftArabic, change kEuropeanNumber to
// kArabicNumber by falling through after this if.
- if (status_.last_strong != WTF::Unicode::kRightToLeftArabic) {
+ if (status_.last_strong != WTF::unicode::kRightToLeftArabic) {
switch (status_.last) {
- case WTF::Unicode::kEuropeanNumber:
- case WTF::Unicode::kLeftToRight:
+ case WTF::unicode::kEuropeanNumber:
+ case WTF::unicode::kLeftToRight:
break;
- case WTF::Unicode::kRightToLeft:
- case WTF::Unicode::kRightToLeftArabic:
- case WTF::Unicode::kArabicNumber:
+ case WTF::unicode::kRightToLeft:
+ case WTF::unicode::kRightToLeftArabic:
+ case WTF::unicode::kArabicNumber:
eor_ = last_;
AppendRun(runs_);
- direction_ = WTF::Unicode::kEuropeanNumber;
+ direction_ = WTF::unicode::kEuropeanNumber;
break;
- case WTF::Unicode::kEuropeanNumberSeparator:
- case WTF::Unicode::kCommonNumberSeparator:
- if (status_.eor == WTF::Unicode::kEuropeanNumber)
+ case WTF::unicode::kEuropeanNumberSeparator:
+ case WTF::unicode::kCommonNumberSeparator:
+ if (status_.eor == WTF::unicode::kEuropeanNumber)
break;
FALLTHROUGH;
- case WTF::Unicode::kEuropeanNumberTerminator:
- case WTF::Unicode::kBoundaryNeutral:
- case WTF::Unicode::kBlockSeparator:
- case WTF::Unicode::kSegmentSeparator:
- case WTF::Unicode::kWhiteSpaceNeutral:
- case WTF::Unicode::kOtherNeutral:
- if (status_.eor == WTF::Unicode::kEuropeanNumber) {
- if (status_.last_strong == WTF::Unicode::kRightToLeft) {
+ case WTF::unicode::kEuropeanNumberTerminator:
+ case WTF::unicode::kBoundaryNeutral:
+ case WTF::unicode::kBlockSeparator:
+ case WTF::unicode::kSegmentSeparator:
+ case WTF::unicode::kWhiteSpaceNeutral:
+ case WTF::unicode::kOtherNeutral:
+ if (status_.eor == WTF::unicode::kEuropeanNumber) {
+ if (status_.last_strong == WTF::unicode::kRightToLeft) {
// ENs on both sides behave like Rs, so the neutrals should be
// R. Terminate the EN run.
AppendRun(runs_);
// Make an R run.
- eor_ = status_.last == WTF::Unicode::kEuropeanNumberTerminator
+ eor_ = status_.last == WTF::unicode::kEuropeanNumberTerminator
? last_before_et_
: last_;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
AppendRun(runs_);
// Begin a new EN run.
- direction_ = WTF::Unicode::kEuropeanNumber;
+ direction_ = WTF::unicode::kEuropeanNumber;
}
- } else if (status_.eor == WTF::Unicode::kArabicNumber) {
+ } else if (status_.eor == WTF::unicode::kArabicNumber) {
// Terminate the AN run.
AppendRun(runs_);
- if (status_.last_strong == WTF::Unicode::kRightToLeft ||
- Context()->Dir() == WTF::Unicode::kRightToLeft) {
+ if (status_.last_strong == WTF::unicode::kRightToLeft ||
+ Context()->Dir() == WTF::unicode::kRightToLeft) {
// Make an R run.
- eor_ = status_.last == WTF::Unicode::kEuropeanNumberTerminator
+ eor_ = status_.last == WTF::unicode::kEuropeanNumberTerminator
? last_before_et_
: last_;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
AppendRun(runs_);
// Begin a new EN run.
- direction_ = WTF::Unicode::kEuropeanNumber;
+ direction_ = WTF::unicode::kEuropeanNumber;
}
- } else if (status_.last_strong == WTF::Unicode::kRightToLeft) {
+ } else if (status_.last_strong == WTF::unicode::kRightToLeft) {
// Extend the R run to include the neutrals.
- eor_ = status_.last == WTF::Unicode::kEuropeanNumberTerminator
+ eor_ = status_.last == WTF::unicode::kEuropeanNumberTerminator
? last_before_et_
: last_;
- direction_ = WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
AppendRun(runs_);
// Begin a new EN run.
- direction_ = WTF::Unicode::kEuropeanNumber;
+ direction_ = WTF::unicode::kEuropeanNumber;
}
break;
default:
break;
}
eor_ = current_;
- status_.eor = WTF::Unicode::kEuropeanNumber;
- if (direction_ == WTF::Unicode::kOtherNeutral)
- direction_ = WTF::Unicode::kLeftToRight;
+ status_.eor = WTF::unicode::kEuropeanNumber;
+ if (direction_ == WTF::unicode::kOtherNeutral)
+ direction_ = WTF::unicode::kLeftToRight;
break;
}
FALLTHROUGH;
- case WTF::Unicode::kArabicNumber:
- dir_current = WTF::Unicode::kArabicNumber;
+ case WTF::unicode::kArabicNumber:
+ dir_current = WTF::unicode::kArabicNumber;
switch (status_.last) {
- case WTF::Unicode::kLeftToRight:
- if (Context()->Dir() == WTF::Unicode::kLeftToRight)
+ case WTF::unicode::kLeftToRight:
+ if (Context()->Dir() == WTF::unicode::kLeftToRight)
AppendRun(runs_);
break;
- case WTF::Unicode::kArabicNumber:
+ case WTF::unicode::kArabicNumber:
break;
- case WTF::Unicode::kRightToLeft:
- case WTF::Unicode::kRightToLeftArabic:
- case WTF::Unicode::kEuropeanNumber:
+ case WTF::unicode::kRightToLeft:
+ case WTF::unicode::kRightToLeftArabic:
+ case WTF::unicode::kEuropeanNumber:
eor_ = last_;
AppendRun(runs_);
break;
- case WTF::Unicode::kCommonNumberSeparator:
- if (status_.eor == WTF::Unicode::kArabicNumber)
+ case WTF::unicode::kCommonNumberSeparator:
+ if (status_.eor == WTF::unicode::kArabicNumber)
break;
FALLTHROUGH;
- case WTF::Unicode::kEuropeanNumberSeparator:
- case WTF::Unicode::kEuropeanNumberTerminator:
- case WTF::Unicode::kBoundaryNeutral:
- case WTF::Unicode::kBlockSeparator:
- case WTF::Unicode::kSegmentSeparator:
- case WTF::Unicode::kWhiteSpaceNeutral:
- case WTF::Unicode::kOtherNeutral:
- if (status_.eor == WTF::Unicode::kArabicNumber ||
- (status_.eor == WTF::Unicode::kEuropeanNumber &&
- (status_.last_strong == WTF::Unicode::kRightToLeft ||
- Context()->Dir() == WTF::Unicode::kRightToLeft)) ||
- (status_.eor != WTF::Unicode::kEuropeanNumber &&
- status_.last_strong == WTF::Unicode::kLeftToRight &&
- Context()->Dir() == WTF::Unicode::kRightToLeft)) {
+ case WTF::unicode::kEuropeanNumberSeparator:
+ case WTF::unicode::kEuropeanNumberTerminator:
+ case WTF::unicode::kBoundaryNeutral:
+ case WTF::unicode::kBlockSeparator:
+ case WTF::unicode::kSegmentSeparator:
+ case WTF::unicode::kWhiteSpaceNeutral:
+ case WTF::unicode::kOtherNeutral:
+ if (status_.eor == WTF::unicode::kArabicNumber ||
+ (status_.eor == WTF::unicode::kEuropeanNumber &&
+ (status_.last_strong == WTF::unicode::kRightToLeft ||
+ Context()->Dir() == WTF::unicode::kRightToLeft)) ||
+ (status_.eor != WTF::unicode::kEuropeanNumber &&
+ status_.last_strong == WTF::unicode::kLeftToRight &&
+ Context()->Dir() == WTF::unicode::kRightToLeft)) {
// Terminate the run before the neutrals.
AppendRun(runs_);
// Begin an R run for the neutrals.
- direction_ = WTF::Unicode::kRightToLeft;
- } else if (direction_ == WTF::Unicode::kOtherNeutral) {
- direction_ = status_.last_strong == WTF::Unicode::kLeftToRight
- ? WTF::Unicode::kLeftToRight
- : WTF::Unicode::kRightToLeft;
+ direction_ = WTF::unicode::kRightToLeft;
+ } else if (direction_ == WTF::unicode::kOtherNeutral) {
+ direction_ = status_.last_strong == WTF::unicode::kLeftToRight
+ ? WTF::unicode::kLeftToRight
+ : WTF::unicode::kRightToLeft;
}
eor_ = last_;
AppendRun(runs_);
@@ -1125,39 +1125,39 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
break;
}
eor_ = current_;
- status_.eor = WTF::Unicode::kArabicNumber;
- if (direction_ == WTF::Unicode::kOtherNeutral)
- direction_ = WTF::Unicode::kArabicNumber;
+ status_.eor = WTF::unicode::kArabicNumber;
+ if (direction_ == WTF::unicode::kOtherNeutral)
+ direction_ = WTF::unicode::kArabicNumber;
break;
- case WTF::Unicode::kEuropeanNumberSeparator:
- case WTF::Unicode::kCommonNumberSeparator:
+ case WTF::unicode::kEuropeanNumberSeparator:
+ case WTF::unicode::kCommonNumberSeparator:
break;
- case WTF::Unicode::kEuropeanNumberTerminator:
- if (status_.last == WTF::Unicode::kEuropeanNumber) {
- dir_current = WTF::Unicode::kEuropeanNumber;
+ case WTF::unicode::kEuropeanNumberTerminator:
+ if (status_.last == WTF::unicode::kEuropeanNumber) {
+ dir_current = WTF::unicode::kEuropeanNumber;
eor_ = current_;
status_.eor = dir_current;
- } else if (status_.last != WTF::Unicode::kEuropeanNumberTerminator) {
+ } else if (status_.last != WTF::unicode::kEuropeanNumberTerminator) {
last_before_et_ = empty_run_ ? eor_ : last_;
}
break;
// boundary neutrals should be ignored
- case WTF::Unicode::kBoundaryNeutral:
+ case WTF::unicode::kBoundaryNeutral:
if (eor_ == last_)
eor_ = current_;
break;
// neutrals
- case WTF::Unicode::kBlockSeparator:
+ case WTF::unicode::kBlockSeparator:
// ### what do we do with newline and paragraph seperators that come to
// here?
break;
- case WTF::Unicode::kSegmentSeparator:
+ case WTF::unicode::kSegmentSeparator:
// ### implement rule L1
break;
- case WTF::Unicode::kWhiteSpaceNeutral:
+ case WTF::unicode::kWhiteSpaceNeutral:
break;
- case WTF::Unicode::kOtherNeutral:
+ case WTF::unicode::kOtherNeutral:
break;
default:
break;
@@ -1167,15 +1167,15 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
if (!reached_end_of_line_) {
eor_ = end_of_run_at_end_of_line_;
switch (status_.eor) {
- case WTF::Unicode::kLeftToRight:
- case WTF::Unicode::kRightToLeft:
- case WTF::Unicode::kArabicNumber:
+ case WTF::unicode::kLeftToRight:
+ case WTF::unicode::kRightToLeft:
+ case WTF::unicode::kArabicNumber:
direction_ = status_.eor;
break;
- case WTF::Unicode::kEuropeanNumber:
- direction_ = status_.last_strong == WTF::Unicode::kLeftToRight
- ? WTF::Unicode::kLeftToRight
- : WTF::Unicode::kEuropeanNumber;
+ case WTF::unicode::kEuropeanNumber:
+ direction_ = status_.last_strong == WTF::unicode::kLeftToRight
+ ? WTF::unicode::kLeftToRight
+ : WTF::unicode::kEuropeanNumber;
break;
default:
NOTREACHED();
@@ -1190,7 +1190,7 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
reached_end_of_line_ = state_at_end.reached_end_of_line_;
last_before_et_ = state_at_end.last_before_et_;
empty_run_ = state_at_end.empty_run_;
- direction_ = WTF::Unicode::kOtherNeutral;
+ direction_ = WTF::unicode::kOtherNeutral;
break;
}
@@ -1214,7 +1214,7 @@ void BidiResolver<Iterator, Run, IsolatedRun>::CreateBidiRunsForLine(
reached_end_of_line_ = state_at_end.reached_end_of_line_;
last_before_et_ = state_at_end.last_before_et_;
empty_run_ = state_at_end.empty_run_;
- direction_ = WTF::Unicode::kOtherNeutral;
+ direction_ = WTF::unicode::kOtherNeutral;
break;
}
}
diff --git a/chromium/third_party/blink/renderer/platform/text/capitalize.cc b/chromium/third_party/blink/renderer/platform/text/capitalize.cc
index 858ef838910..1336b820edf 100644
--- a/chromium/third_party/blink/renderer/platform/text/capitalize.cc
+++ b/chromium/third_party/blink/renderer/platform/text/capitalize.cc
@@ -48,7 +48,7 @@ String Capitalize(const String& string, UChar previous_character) {
result.Append(
input[start_of_word - 1] == kNoBreakSpaceCharacter
? kNoBreakSpaceCharacter
- : WTF::Unicode::ToTitleCase(string_with_previous[start_of_word]));
+ : WTF::unicode::ToTitleCase(string_with_previous[start_of_word]));
}
for (int i = start_of_word + 1; i < end_of_word; i++)
result.Append(input[i - 1]);
diff --git a/chromium/third_party/blink/renderer/platform/text/character.cc b/chromium/third_party/blink/renderer/platform/text/character.cc
index 3d8c948c14d..e43dbced99a 100644
--- a/chromium/third_party/blink/renderer/platform/text/character.cc
+++ b/chromium/third_party/blink/renderer/platform/text/character.cc
@@ -33,13 +33,13 @@
#include <unicode/uobject.h>
#include <unicode/uscript.h>
#include <algorithm>
+#include "third_party/blink/renderer/platform/text/character_property_data.h"
#include "third_party/blink/renderer/platform/text/icu_error.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#if defined(USING_SYSTEM_ICU)
#include <unicode/uniset.h>
-#include "third_party/blink/renderer/platform/text/character_property_data_generator.h"
#else
#define MUTEX_H // Prevent compile failure of utrie2.h on Windows
#include <utrie2.h>
@@ -71,10 +71,6 @@ static icu::UnicodeSet* createUnicodeSet(const UChar32* characters,
unicodeSet = CREATE_UNICODE_SET(name); \
return unicodeSet->contains(c);
#else
-// Freezed trie tree, see CharacterDataGenerator.cpp.
-extern const int32_t kSerializedCharacterDataSize;
-extern const uint8_t kSerializedCharacterData[];
-
static UTrie2* CreateTrie() {
// Create a Trie from the value array.
ICUError error;
@@ -240,11 +236,11 @@ bool Character::CanTextDecorationSkipInk(UChar32 codepoint) {
}
bool Character::CanReceiveTextEmphasis(UChar32 c) {
- WTF::Unicode::CharCategory category = WTF::Unicode::Category(c);
+ WTF::unicode::CharCategory category = WTF::unicode::Category(c);
if (category &
- (WTF::Unicode::kSeparator_Space | WTF::Unicode::kSeparator_Line |
- WTF::Unicode::kSeparator_Paragraph | WTF::Unicode::kOther_NotAssigned |
- WTF::Unicode::kOther_Control | WTF::Unicode::kOther_Format))
+ (WTF::unicode::kSeparator_Space | WTF::unicode::kSeparator_Line |
+ WTF::unicode::kSeparator_Paragraph | WTF::unicode::kOther_NotAssigned |
+ WTF::unicode::kOther_Control | WTF::unicode::kOther_Format))
return false;
// Additional word-separator characters listed in CSS Text Level 3 Editor's
@@ -296,7 +292,7 @@ bool Character::IsCommonOrInheritedScript(UChar32 character) {
}
bool Character::IsPrivateUse(UChar32 character) {
- return WTF::Unicode::Category(character) & WTF::Unicode::kOther_PrivateUse;
+ return WTF::unicode::Category(character) & WTF::unicode::kOther_PrivateUse;
}
bool Character::IsNonCharacter(UChar32 character) {
diff --git a/chromium/third_party/blink/renderer/platform/text/character.h b/chromium/third_party/blink/renderer/platform/text/character.h
index b1a41d1cd03..f0ccecceeac 100644
--- a/chromium/third_party/blink/renderer/platform/text/character.h
+++ b/chromium/third_party/blink/renderer/platform/text/character.h
@@ -174,7 +174,7 @@ class PLATFORM_EXPORT Character {
// http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#space-character
// This function returns true for 0x000B also, so that this is backward
// compatible. Otherwise, the test
- // LayoutTests/canvas/philip/tests/2d.text.draw.space.collapse.space.html
+ // web_tests/canvas/philip/tests/2d.text.draw.space.collapse.space.html
// will fail
return c == 0x0009 || (c >= 0x000A && c <= 0x000D);
}
diff --git a/chromium/third_party/blink/renderer/platform/text/character_property_data_generator.h b/chromium/third_party/blink/renderer/platform/text/character_property_data.h
index 28fb6a930cf..7d2cf90cb5a 100644
--- a/chromium/third_party/blink/renderer/platform/text/character_property_data_generator.h
+++ b/chromium/third_party/blink/renderer/platform/text/character_property_data.h
@@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_CHARACTER_PROPERTY_DATA_GENERATOR_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_CHARACTER_PROPERTY_DATA_GENERATOR_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_CHARACTER_PROPERTY_DATA_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_CHARACTER_PROPERTY_DATA_H_
#include <unicode/uobject.h>
@@ -249,6 +249,12 @@ static const UChar32 kIsHangulRanges[] = {
static const UChar32 kIsHangulArray[] = {};
+#if !defined(USING_SYSTEM_ICU)
+// Freezed trie tree, see character_property_data_generator.cc.
+extern const int32_t kSerializedCharacterDataSize;
+extern const uint8_t kSerializedCharacterData[];
+#endif
+
} // namespace blink
#endif
diff --git a/chromium/third_party/blink/renderer/platform/text/character_property_data_generator.cc b/chromium/third_party/blink/renderer/platform/text/character_property_data_generator.cc
index 846ceea42a7..893d52759fa 100644
--- a/chromium/third_party/blink/renderer/platform/text/character_property_data_generator.cc
+++ b/chromium/third_party/blink/renderer/platform/text/character_property_data_generator.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 "third_party/blink/renderer/platform/text/character_property_data_generator.h"
+#include "third_party/blink/renderer/platform/text/character_property_data.h"
#include <stdio.h>
#include <cassert>
@@ -15,9 +15,10 @@
#endif
namespace blink {
+namespace {
#if defined(USING_SYSTEM_ICU)
-static void Generate(FILE*) {}
+static void GenerateCharacterPropertyData(FILE*) {}
#else
const UChar32 kMaxCodepoint = 0x10FFFF;
@@ -66,7 +67,7 @@ static void GenerateUTrieSerialized(FILE* fp, int32_t size, uint8_t* array) {
"} // namespace blink\n");
}
-static void Generate(FILE* fp) {
+static void GenerateCharacterPropertyData(FILE* fp) {
// Create a value array of all possible code points.
const UChar32 kSize = kMaxCodepoint + 1;
std::unique_ptr<CharacterProperty[]> values(new CharacterProperty[kSize]);
@@ -120,15 +121,16 @@ static void Generate(FILE* fp) {
}
#endif
+} // namespace
} // namespace blink
int main(int argc, char** argv) {
// Write the serialized array to the source file.
if (argc <= 1) {
- blink::Generate(stdout);
+ blink::GenerateCharacterPropertyData(stdout);
} else {
FILE* fp = fopen(argv[1], "wb");
- blink::Generate(fp);
+ blink::GenerateCharacterPropertyData(fp);
fclose(fp);
}
diff --git a/chromium/third_party/blink/renderer/platform/text/locale_mac.mm b/chromium/third_party/blink/renderer/platform/text/locale_mac.mm
index 6271af2bc49..490dbff01e4 100644
--- a/chromium/third_party/blink/renderer/platform/text/locale_mac.mm
+++ b/chromium/third_party/blink/renderer/platform/text/locale_mac.mm
@@ -35,7 +35,7 @@
#include <memory>
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/platform/language.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/retain_ptr.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -52,7 +52,7 @@ static inline String LanguageFromLocale(const String& locale) {
}
static RetainPtr<NSLocale> DetermineLocale(const String& locale) {
- if (!LayoutTestSupport::IsRunningLayoutTest()) {
+ if (!WebTestSupport::IsRunningWebTest()) {
RetainPtr<NSLocale> current_locale = [NSLocale currentLocale];
String current_locale_language =
LanguageFromLocale(String([current_locale.Get() localeIdentifier]));
diff --git a/chromium/third_party/blink/renderer/platform/text/locale_mac_test.cc b/chromium/third_party/blink/renderer/platform/text/locale_mac_test.cc
index aad937bd696..661489cfae2 100644
--- a/chromium/third_party/blink/renderer/platform/text/locale_mac_test.cc
+++ b/chromium/third_party/blink/renderer/platform/text/locale_mac_test.cc
@@ -29,6 +29,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/date_components.h"
+#include "third_party/blink/renderer/platform/mac/version_util_mac.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
@@ -224,16 +225,26 @@ TEST_F(LocaleMacTest, formatDate) {
// Do not test ja_JP locale. OS X 10.8 and 10.7 have different formats.
}
-// http://crbug.com/811685 This test is flaky.
-TEST_F(LocaleMacTest, DISABLED_formatTime) {
+TEST_F(LocaleMacTest, formatTime) {
+ // On MacOS 10.13+, Arabic times (which contain spaces) use \xC2\xA0
+ // (which is a non-breaking space) instead of \x20 for those spaces. The
+ // 10.13+ behavior is probably more correct, but there does not appear to be a
+ // way to configure NSDateFormatter to behave that way on < 10.13.
+ bool expect_ar_nbsp = !IsOS10_10() && !IsOS10_11() && !IsOS10_12();
+
EXPECT_STREQ("1:23 PM",
FormatTime("en_US", 13, 23, 00, 000, true).Utf8().data());
EXPECT_STREQ("13:23",
FormatTime("fr_FR", 13, 23, 00, 000, true).Utf8().data());
EXPECT_STREQ("13:23",
FormatTime("ja_JP", 13, 23, 00, 000, true).Utf8().data());
- EXPECT_STREQ("\xD9\xA1:\xD9\xA2\xD9\xA3 \xD9\x85",
- FormatTime("ar", 13, 23, 00, 000, true).Utf8().data());
+ if (expect_ar_nbsp) {
+ EXPECT_STREQ("\xD9\xA1:\xD9\xA2\xD9\xA3\xC2\xA0\xD9\x85",
+ FormatTime("ar", 13, 23, 00, 000, true).Utf8().data());
+ } else {
+ EXPECT_STREQ("\xD9\xA1:\xD9\xA2\xD9\xA3 \xD9\x85",
+ FormatTime("ar", 13, 23, 00, 000, true).Utf8().data());
+ }
EXPECT_STREQ("\xDB\xB1\xDB\xB3:\xDB\xB2\xDB\xB3",
FormatTime("fa", 13, 23, 00, 000, true).Utf8().data());
@@ -243,8 +254,13 @@ TEST_F(LocaleMacTest, DISABLED_formatTime) {
FormatTime("fr_FR", 00, 00, 00, 000, true).Utf8().data());
EXPECT_STREQ("0:00",
FormatTime("ja_JP", 00, 00, 00, 000, true).Utf8().data());
- EXPECT_STREQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0 \xD8\xB5",
- FormatTime("ar", 00, 00, 00, 000, true).Utf8().data());
+ if (expect_ar_nbsp) {
+ EXPECT_STREQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0\xC2\xA0\xD8\xB5",
+ FormatTime("ar", 00, 00, 00, 000, true).Utf8().data());
+ } else {
+ EXPECT_STREQ("\xD9\xA1\xD9\xA2:\xD9\xA0\xD9\xA0 \xD8\xB5",
+ FormatTime("ar", 00, 00, 00, 000, true).Utf8().data());
+ }
EXPECT_STREQ("\xDB\xB0:\xDB\xB0\xDB\xB0",
FormatTime("fa", 00, 00, 00, 000, true).Utf8().data());
@@ -254,10 +270,17 @@ TEST_F(LocaleMacTest, DISABLED_formatTime) {
FormatTime("fr_FR", 07, 07, 07, 007, false).Utf8().data());
EXPECT_STREQ("7:07:07.007",
FormatTime("ja_JP", 07, 07, 07, 007, false).Utf8().data());
- EXPECT_STREQ(
- "\xD9\xA7:\xD9\xA0\xD9\xA7:"
- "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7 \xD8\xB5",
- FormatTime("ar", 07, 07, 07, 007, false).Utf8().data());
+ if (expect_ar_nbsp) {
+ EXPECT_STREQ(
+ "\xD9\xA7:\xD9\xA0\xD9\xA7:"
+ "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7\xC2\xA0\xD8\xB5",
+ FormatTime("ar", 07, 07, 07, 007, false).Utf8().data());
+ } else {
+ EXPECT_STREQ(
+ "\xD9\xA7:\xD9\xA0\xD9\xA7:"
+ "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7 \xD8\xB5",
+ FormatTime("ar", 07, 07, 07, 007, false).Utf8().data());
+ }
EXPECT_STREQ(
"\xDB\xB7:\xDB\xB0\xDB\xB7:"
"\xDB\xB0\xDB\xB7\xD9\xAB\xDB\xB0\xDB\xB0\xDB\xB7",
diff --git a/chromium/third_party/blink/renderer/platform/text/locale_win.cc b/chromium/third_party/blink/renderer/platform/text/locale_win.cc
index 2030fbf60d9..80fcf10e608 100644
--- a/chromium/third_party/blink/renderer/platform/text/locale_win.cc
+++ b/chromium/third_party/blink/renderer/platform/text/locale_win.cc
@@ -36,8 +36,8 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/platform/date_components.h"
#include "third_party/blink/renderer/platform/language.h"
-#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/text/date_time_format.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/string_buffer.h"
@@ -93,7 +93,7 @@ static LCID LCIDFromLocale(const String& locale, bool defaults_for_locale) {
std::unique_ptr<Locale> Locale::Create(const String& locale) {
// Whether the default settings for the locale should be used, ignoring user
// overrides.
- bool defaults_for_locale = LayoutTestSupport::IsRunningLayoutTest();
+ bool defaults_for_locale = WebTestSupport::IsRunningWebTest();
return LocaleWin::Create(LCIDFromLocale(locale, defaults_for_locale),
defaults_for_locale);
}
@@ -325,10 +325,10 @@ unsigned LocaleWin::FirstDayOfWeek() {
}
bool LocaleWin::IsRTL() {
- WTF::Unicode::CharDirection dir =
- WTF::Unicode::Direction(MonthLabels()[0][0]);
- return dir == WTF::Unicode::kRightToLeft ||
- dir == WTF::Unicode::kRightToLeftArabic;
+ WTF::unicode::CharDirection dir =
+ WTF::unicode::Direction(MonthLabels()[0][0]);
+ return dir == WTF::unicode::kRightToLeft ||
+ dir == WTF::unicode::kRightToLeftArabic;
}
String LocaleWin::DateFormat() {
diff --git a/chromium/third_party/blink/renderer/platform/text/quoted_printable.cc b/chromium/third_party/blink/renderer/platform/text/quoted_printable.cc
deleted file mode 100644
index 6c846dd6d6c..00000000000
--- a/chromium/third_party/blink/renderer/platform/text/quoted_printable.cc
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "third_party/blink/renderer/platform/text/quoted_printable.h"
-
-#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
-
-namespace blink {
-
-static size_t LengthOfLineEndingAtIndex(const char* input,
- size_t input_length,
- size_t index) {
- SECURITY_DCHECK(index < input_length);
- if (input[index] == '\n')
- return 1; // Single LF.
-
- if (input[index] == '\r') {
- if ((index + 1) == input_length || input[index + 1] != '\n')
- return 1; // Single CR (Classic Mac OS).
- return 2; // CR-LF.
- }
-
- return 0;
-}
-
-void QuotedPrintableEncode(const char* input,
- wtf_size_t input_length,
- QuotedPrintableEncodeDelegate* delegate,
- Vector<char>& out) {
- out.clear();
- out.ReserveCapacity(input_length);
- delegate->DidStartLine(out);
- size_t current_line_length = 0;
- for (size_t i = 0; i < input_length; ++i) {
- bool is_last_character = (i == input_length - 1);
- char current_character = input[i];
- bool requires_encoding = false;
- // All non-printable ASCII characters and = require encoding.
- if ((current_character < ' ' || current_character > '~' ||
- current_character == '=') &&
- current_character != '\t')
- requires_encoding = true;
-
- // Decide if space and tab characters need to be encoded.
- if (!requires_encoding &&
- (current_character == '\t' || current_character == ' ')) {
- bool end_of_line = is_last_character ||
- LengthOfLineEndingAtIndex(input, input_length, i + 1);
- requires_encoding =
- delegate->ShouldEncodeWhiteSpaceCharacters(end_of_line);
- }
-
- // End of line should be converted to CR-LF sequences.
- if (!is_last_character) {
- size_t length_of_line_ending =
- LengthOfLineEndingAtIndex(input, input_length, i);
- if (length_of_line_ending) {
- out.Append("\r\n", 2);
- current_line_length = 0;
- i += (length_of_line_ending -
- 1); // -1 because we'll ++ in the for() above.
- continue;
- }
- }
-
- size_t length_of_encoded_character = 1;
- if (requires_encoding)
- length_of_encoded_character += 2;
- if (!is_last_character)
- length_of_encoded_character += 1; // + 1 for the = (soft line break).
-
- // Insert a soft line break if necessary.
- if (current_line_length + length_of_encoded_character >
- delegate->GetMaxLineLengthForEncodedContent()) {
- delegate->DidFinishLine(false /*last_line*/, out);
- current_line_length = 0;
- delegate->DidStartLine(out);
- }
-
- // Finally, insert the actual character(s).
- if (requires_encoding) {
- out.push_back('=');
- out.push_back(UpperNibbleToASCIIHexDigit(current_character));
- out.push_back(LowerNibbleToASCIIHexDigit(current_character));
- current_line_length += 3;
- } else {
- out.push_back(current_character);
- current_line_length++;
- }
- }
- delegate->DidFinishLine(true /*last_line*/, out);
-}
-
-void QuotedPrintableDecode(const Vector<char>& in, Vector<char>& out) {
- QuotedPrintableDecode(in.data(), in.size(), out);
-}
-
-void QuotedPrintableDecode(const char* data,
- size_t data_length,
- Vector<char>& out) {
- out.clear();
- if (!data_length)
- return;
-
- for (size_t i = 0; i < data_length; ++i) {
- char current_character = data[i];
- if (current_character != '=') {
- out.push_back(current_character);
- continue;
- }
- // We are dealing with a '=xx' sequence.
- if (data_length - i < 3) {
- // Unfinished = sequence, append as is.
- out.push_back(current_character);
- continue;
- }
- char upper_character = data[++i];
- char lower_character = data[++i];
- if (upper_character == '\r' && lower_character == '\n')
- continue;
-
- if (!IsASCIIHexDigit(upper_character) ||
- !IsASCIIHexDigit(lower_character)) {
- // Invalid sequence, = followed by non hex digits, just insert the
- // characters as is.
- out.push_back('=');
- out.push_back(upper_character);
- out.push_back(lower_character);
- continue;
- }
- out.push_back(
- static_cast<char>(ToASCIIHexValue(upper_character, lower_character)));
- }
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/text/quoted_printable.h b/chromium/third_party/blink/renderer/platform/text/quoted_printable.h
deleted file mode 100644
index c17c7e27e24..00000000000
--- a/chromium/third_party/blink/renderer/platform/text/quoted_printable.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_QUOTED_PRINTABLE_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_QUOTED_PRINTABLE_H_
-
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
-#include "third_party/blink/renderer/platform/wtf/wtf_size_t.h"
-
-namespace blink {
-
-// Delegate for controling the behavior of quoted-printable encoding. The
-// original characters may be encoded a bit differently depending on where
-// they live, header or body. For example, "=CRLF" should be used to break
-// long line in body while "CRLF+SPACE" should be used to break long line in
-// header.
-class PLATFORM_EXPORT QuotedPrintableEncodeDelegate {
- public:
- QuotedPrintableEncodeDelegate() = default;
- virtual ~QuotedPrintableEncodeDelegate() = default;
-
- // Returns maximum number of characters allowed for an encoded line, excluding
- // prefix and soft line break.
- virtual size_t GetMaxLineLengthForEncodedContent() const = 0;
-
- // Returns true if space and tab characters need to be encoded.
- virtual bool ShouldEncodeWhiteSpaceCharacters(bool end_of_line) const = 0;
-
- // Called when an encoded line starts. The delegate can take this chance to
- // add any prefix.
- virtual void DidStartLine(Vector<char>& out) = 0;
-
- // Called when an encoded line ends. The delegate can take this chance to add
- // any suffix. If it is not last line, a soft line break should also
- // be added after the suffix.
- virtual void DidFinishLine(bool last_line, Vector<char>& out) = 0;
-};
-
-PLATFORM_EXPORT void QuotedPrintableEncode(const char*,
- wtf_size_t,
- QuotedPrintableEncodeDelegate*,
- Vector<char>&);
-
-PLATFORM_EXPORT void QuotedPrintableDecode(const char*, size_t, Vector<char>&);
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_QUOTED_PRINTABLE_H_
diff --git a/chromium/third_party/blink/renderer/platform/text/segmented_string.h b/chromium/third_party/blink/renderer/platform/text/segmented_string.h
index 5492f97cacc..9e5a55eac48 100644
--- a/chromium/third_party/blink/renderer/platform/text/segmented_string.h
+++ b/chromium/third_party/blink/renderer/platform/text/segmented_string.h
@@ -42,23 +42,23 @@ class PLATFORM_EXPORT SegmentedSubstring {
string_(str) {
if (length_) {
if (string_.Is8Bit()) {
- is8_bit_ = true;
+ is_8bit_ = true;
data_.string8_ptr = string_.Characters8();
current_char_ = *data_.string8_ptr;
} else {
- is8_bit_ = false;
+ is_8bit_ = false;
data_.string16_ptr = string_.Characters16();
current_char_ = *data_.string16_ptr;
}
} else {
- is8_bit_ = true;
+ is_8bit_ = true;
data_.string8_ptr = nullptr;
}
}
void Clear() {
length_ = 0;
- is8_bit_ = true;
+ is_8bit_ = true;
data_.string8_ptr = nullptr;
current_char_ = 0;
}
@@ -91,7 +91,7 @@ class PLATFORM_EXPORT SegmentedSubstring {
if (data_.void_ptr == string_.Impl()->Bytes())
return false;
- if (is8_bit_) {
+ if (is_8bit_) {
if (*(data_.string8_ptr - 1) != c)
return false;
@@ -111,7 +111,7 @@ class PLATFORM_EXPORT SegmentedSubstring {
ALWAYS_INLINE UChar GetCurrentChar() const { return current_char_; }
ALWAYS_INLINE void IncrementAndDecrementLength() {
- current_char_ = is8_bit_ ? *++data_.string8_ptr : *++data_.string16_ptr;
+ current_char_ = is_8bit_ ? *++data_.string8_ptr : *++data_.string16_ptr;
--length_;
}
@@ -131,7 +131,7 @@ class PLATFORM_EXPORT SegmentedSubstring {
int length_ = 0;
UChar current_char_ = 0;
bool do_not_exclude_line_numbers_ = true;
- bool is8_bit_ = true;
+ bool is_8bit_ = true;
String string_;
};
@@ -226,8 +226,8 @@ class PLATFORM_EXPORT SegmentedString {
}
ALWAYS_INLINE void AdvanceAndASSERTIgnoringCase(UChar expected_character) {
- DCHECK_EQ(WTF::Unicode::FoldCase(CurrentChar()),
- WTF::Unicode::FoldCase(expected_character));
+ DCHECK_EQ(WTF::unicode::FoldCase(CurrentChar()),
+ WTF::unicode::FoldCase(expected_character));
Advance();
}
diff --git a/chromium/third_party/blink/renderer/platform/text/text_boundaries.cc b/chromium/third_party/blink/renderer/platform/text/text_boundaries.cc
index 2161defad9d..3a09acd86d9 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_boundaries.cc
+++ b/chromium/third_party/blink/renderer/platform/text/text_boundaries.cc
@@ -62,7 +62,7 @@ int FindNextWordForward(const UChar* chars, int len, int position) {
// We stop searching when the character preceeding the break
// is alphanumeric or underscore.
if (position < len &&
- (WTF::Unicode::IsAlphanumeric(chars[position - 1]) ||
+ (WTF::unicode::IsAlphanumeric(chars[position - 1]) ||
chars[position - 1] == kLowLineCharacter))
return position;
@@ -79,7 +79,7 @@ int FindNextWordBackward(const UChar* chars, int len, int position) {
while (position != kTextBreakDone) {
// We stop searching when the character following the break
// is alphanumeric or underscore.
- if (position > 0 && (WTF::Unicode::IsAlphanumeric(chars[position]) ||
+ if (position > 0 && (WTF::unicode::IsAlphanumeric(chars[position]) ||
chars[position] == kLowLineCharacter))
return position;
diff --git a/chromium/third_party/blink/renderer/platform/text/text_boundaries.h b/chromium/third_party/blink/renderer/platform/text/text_boundaries.h
index 44c5438c5ab..7a7cc4b954d 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_boundaries.h
+++ b/chromium/third_party/blink/renderer/platform/text/text_boundaries.h
@@ -34,7 +34,7 @@
namespace blink {
inline bool RequiresContextForWordBoundary(UChar32 ch) {
- return WTF::Unicode::HasLineBreakingPropertyComplexContext(ch);
+ return WTF::unicode::HasLineBreakingPropertyComplexContext(ch);
}
PLATFORM_EXPORT int EndOfFirstWordBoundaryContext(const UChar* characters,
diff --git a/chromium/third_party/blink/renderer/platform/text/text_break_iterator.cc b/chromium/third_party/blink/renderer/platform/text/text_break_iterator.cc
index e39e8df0f79..0160d67d515 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_break_iterator.cc
+++ b/chromium/third_party/blink/renderer/platform/text/text_break_iterator.cc
@@ -284,9 +284,9 @@ static inline bool ShouldKeepAfterKeepAll(UChar last_ch,
UChar next_ch) {
UChar pre_ch = U_MASK(u_charType(ch)) & U_GC_M_MASK ? last_ch : ch;
return U_MASK(u_charType(pre_ch)) & (U_GC_L_MASK | U_GC_N_MASK) &&
- !WTF::Unicode::HasLineBreakingPropertyComplexContext(pre_ch) &&
+ !WTF::unicode::HasLineBreakingPropertyComplexContext(pre_ch) &&
U_MASK(u_charType(next_ch)) & (U_GC_L_MASK | U_GC_N_MASK) &&
- !WTF::Unicode::HasLineBreakingPropertyComplexContext(next_ch);
+ !WTF::unicode::HasLineBreakingPropertyComplexContext(next_ch);
}
inline bool NeedsLineBreakIterator(UChar ch) {
diff --git a/chromium/third_party/blink/renderer/platform/text/text_break_iterator.h b/chromium/third_party/blink/renderer/platform/text/text_break_iterator.h
index f7f02ebcb29..8d1f1a5a8ef 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_break_iterator.h
+++ b/chromium/third_party/blink/renderer/platform/text/text_break_iterator.h
@@ -346,30 +346,30 @@ class PLATFORM_EXPORT NonSharedCharacterBreakIterator final {
int Preceding(int offset) const;
int Following(int offset) const;
- bool operator!() const { return !is8_bit_ && !iterator_; }
+ bool operator!() const { return !is_8bit_ && !iterator_; }
private:
void CreateIteratorForBuffer(const UChar*, unsigned length);
unsigned ClusterLengthStartingAt(unsigned offset) const {
- DCHECK(is8_bit_);
+ DCHECK(is_8bit_);
// The only Latin-1 Extended Grapheme Cluster is CR LF
return IsCRBeforeLF(offset) ? 2 : 1;
}
bool IsCRBeforeLF(unsigned offset) const {
- DCHECK(is8_bit_);
+ DCHECK(is_8bit_);
return charaters8_[offset] == '\r' && offset + 1 < length_ &&
charaters8_[offset + 1] == '\n';
}
bool IsLFAfterCR(unsigned offset) const {
- DCHECK(is8_bit_);
+ DCHECK(is_8bit_);
return charaters8_[offset] == '\n' && offset >= 1 &&
charaters8_[offset - 1] == '\r';
}
- bool is8_bit_;
+ bool is_8bit_;
// For 8 bit strings, we implement the iterator ourselves.
const LChar* charaters8_;
diff --git a/chromium/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc b/chromium/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc
index be3599a4a31..da92f1fe27d 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc
+++ b/chromium/third_party/blink/renderer/platform/text/text_break_iterator_icu.cc
@@ -752,7 +752,7 @@ static TextBreakIterator* GetNonSharedCharacterBreakIterator() {
NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(
const StringView& string)
- : is8_bit_(true),
+ : is_8bit_(true),
charaters8_(nullptr),
offset_(0),
length_(0),
@@ -760,9 +760,9 @@ NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(
if (string.IsEmpty())
return;
- is8_bit_ = string.Is8Bit();
+ is_8bit_ = string.Is8Bit();
- if (is8_bit_) {
+ if (is_8bit_) {
charaters8_ = string.Characters8();
offset_ = 0;
length_ = string.length();
@@ -775,7 +775,7 @@ NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(
NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(
const UChar* buffer,
unsigned length)
- : is8_bit_(false),
+ : is_8bit_(false),
charaters8_(nullptr),
offset_(0),
length_(0),
@@ -791,12 +791,12 @@ void NonSharedCharacterBreakIterator::CreateIteratorForBuffer(
}
NonSharedCharacterBreakIterator::~NonSharedCharacterBreakIterator() {
- if (is8_bit_)
+ if (is_8bit_)
return;
}
int NonSharedCharacterBreakIterator::Next() {
- if (!is8_bit_)
+ if (!is_8bit_)
return iterator_->next();
if (offset_ >= length_)
@@ -807,19 +807,19 @@ int NonSharedCharacterBreakIterator::Next() {
}
int NonSharedCharacterBreakIterator::Current() {
- if (!is8_bit_)
+ if (!is_8bit_)
return iterator_->current();
return offset_;
}
bool NonSharedCharacterBreakIterator::IsBreak(int offset) const {
- if (!is8_bit_)
+ if (!is_8bit_)
return iterator_->isBoundary(offset);
return !IsLFAfterCR(offset);
}
int NonSharedCharacterBreakIterator::Preceding(int offset) const {
- if (!is8_bit_)
+ if (!is_8bit_)
return iterator_->preceding(offset);
if (offset <= 0)
return kTextBreakDone;
@@ -829,7 +829,7 @@ int NonSharedCharacterBreakIterator::Preceding(int offset) const {
}
int NonSharedCharacterBreakIterator::Following(int offset) const {
- if (!is8_bit_)
+ if (!is_8bit_)
return iterator_->following(offset);
if (static_cast<unsigned>(offset) >= length_)
return kTextBreakDone;
diff --git a/chromium/third_party/blink/renderer/platform/text/text_run.cc b/chromium/third_party/blink/renderer/platform/text/text_run.cc
index ebc89000c0d..7b9f54a484a 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_run.cc
+++ b/chromium/third_party/blink/renderer/platform/text/text_run.cc
@@ -47,11 +47,11 @@ void TextRun::SetText(const String& string) {
len_ = string.length();
if (!len_) {
data_.characters8 = nullptr;
- is8_bit_ = true;
+ is_8bit_ = true;
return;
}
- is8_bit_ = string.Is8Bit();
- if (is8_bit_)
+ is_8bit_ = string.Is8Bit();
+ if (is_8bit_)
data_.characters8 = string.Characters8();
else
data_.characters16 = string.Characters16();
diff --git a/chromium/third_party/blink/renderer/platform/text/text_run.h b/chromium/third_party/blink/renderer/platform/text/text_run.h
index df07c6f3915..72f9081c41f 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_run.h
+++ b/chromium/third_party/blink/renderer/platform/text/text_run.h
@@ -50,8 +50,6 @@ class PLATFORM_EXPORT TextRun final {
kAllowLeadingExpansion = 1 << 1,
};
- enum TextCodePath { kAuto = 0, kForceSimple = 1, kForceComplex = 2 };
-
typedef unsigned ExpansionBehavior;
TextRun(const LChar* c,
@@ -67,7 +65,7 @@ class PLATFORM_EXPORT TextRun final {
xpos_(xpos),
expansion_(expansion),
expansion_behavior_(expansion_behavior),
- is8_bit_(true),
+ is_8bit_(true),
allow_tabs_(false),
direction_(static_cast<unsigned>(direction)),
directional_override_(directional_override),
@@ -91,7 +89,7 @@ class PLATFORM_EXPORT TextRun final {
xpos_(xpos),
expansion_(expansion),
expansion_behavior_(expansion_behavior),
- is8_bit_(false),
+ is_8bit_(false),
allow_tabs_(false),
direction_(static_cast<unsigned>(direction)),
directional_override_(directional_override),
@@ -122,14 +120,14 @@ class PLATFORM_EXPORT TextRun final {
normalize_space_(false),
tab_size_(0) {
if (!characters_length_) {
- is8_bit_ = true;
+ is_8bit_ = true;
data_.characters8 = nullptr;
} else if (string.Is8Bit()) {
data_.characters8 = string.Characters8();
- is8_bit_ = true;
+ is_8bit_ = true;
} else {
data_.characters16 = string.Characters16();
- is8_bit_ = false;
+ is_8bit_ = false;
}
}
@@ -199,7 +197,7 @@ class PLATFORM_EXPORT TextRun final {
const void* Bytes() const { return data_.bytes_; }
- bool Is8Bit() const { return is8_bit_; }
+ bool Is8Bit() const { return is_8bit_; }
unsigned length() const { return len_; }
unsigned CharactersLength() const { return characters_length_; }
@@ -211,12 +209,12 @@ class PLATFORM_EXPORT TextRun final {
void SetText(const LChar* c, unsigned len) {
data_.characters8 = c;
len_ = len;
- is8_bit_ = true;
+ is_8bit_ = true;
}
void SetText(const UChar* c, unsigned len) {
data_.characters16 = c;
len_ = len;
- is8_bit_ = false;
+ is_8bit_ = false;
}
void SetText(const String&);
void SetCharactersLength(unsigned characters_length) {
@@ -287,7 +285,7 @@ class PLATFORM_EXPORT TextRun final {
float expansion_;
ExpansionBehavior expansion_behavior_ : 2;
- unsigned is8_bit_ : 1;
+ unsigned is_8bit_ : 1;
unsigned allow_tabs_ : 1;
unsigned direction_ : 1;
// Was this direction set by an override character.
diff --git a/chromium/third_party/blink/renderer/platform/text/text_run_iterator.h b/chromium/third_party/blink/renderer/platform/text/text_run_iterator.h
index 4e64b830406..a277cdc1963 100644
--- a/chromium/third_party/blink/renderer/platform/text/text_run_iterator.h
+++ b/chromium/third_party/blink/renderer/platform/text/text_run_iterator.h
@@ -52,9 +52,9 @@ class TextRunIterator {
void Increment() { offset_++; }
bool AtEnd() const { return offset_ >= length_; }
UChar Current() const { return (*text_run_)[offset_]; }
- WTF::Unicode::CharDirection Direction() const {
- return AtEnd() ? WTF::Unicode::kOtherNeutral
- : WTF::Unicode::Direction(Current());
+ WTF::unicode::CharDirection Direction() const {
+ return AtEnd() ? WTF::unicode::kOtherNeutral
+ : WTF::unicode::Direction(Current());
}
bool AtParagraphSeparator() const { return Current() == '\n'; }
diff --git a/chromium/third_party/blink/renderer/platform/theme.h b/chromium/third_party/blink/renderer/platform/theme.h
index fb4f97d527c..9b017dc5729 100644
--- a/chromium/third_party/blink/renderer/platform/theme.h
+++ b/chromium/third_party/blink/renderer/platform/theme.h
@@ -28,9 +28,9 @@
#include "third_party/blink/renderer/platform/fonts/font_description.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/geometry/length_box.h"
+#include "third_party/blink/renderer/platform/geometry/length_size.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/length_box.h"
-#include "third_party/blink/renderer/platform/length_size.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/theme_types.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
diff --git a/chromium/third_party/blink/renderer/platform/timer.cc b/chromium/third_party/blink/renderer/platform/timer.cc
index b7fed475935..3e8ae54944d 100644
--- a/chromium/third_party/blink/renderer/platform/timer.cc
+++ b/chromium/third_party/blink/renderer/platform/timer.cc
@@ -163,10 +163,8 @@ bool TimerBase::Comparator::operator()(const TimerBase* a,
// static
TimeTicks TimerBase::TimerCurrentTimeTicks() const {
- return WTF::TimeTicks(Platform::Current()
- ->CurrentThread()
- ->Scheduler()
- ->MonotonicallyIncreasingVirtualTime());
+ return WTF::TimeTicks(
+ ThreadScheduler::Current()->MonotonicallyIncreasingVirtualTime());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/transforms/DEPS b/chromium/third_party/blink/renderer/platform/transforms/DEPS
index ab6d0043cfd..4058e92e78e 100644
--- a/chromium/third_party/blink/renderer/platform/transforms/DEPS
+++ b/chromium/third_party/blink/renderer/platform/transforms/DEPS
@@ -9,7 +9,5 @@ include_rules = [
"+third_party/blink/renderer/platform/cpu/mips/common_macros_msa.h",
"+third_party/blink/renderer/platform/geometry",
"+third_party/blink/renderer/platform/json",
- "+third_party/blink/renderer/platform/length_functions.h",
- "+third_party/blink/renderer/platform/length.h",
"+third_party/blink/renderer/platform/wtf",
]
diff --git a/chromium/third_party/blink/renderer/platform/transforms/transform_operations_test.cc b/chromium/third_party/blink/renderer/platform/transforms/transform_operations_test.cc
index ab95da6ec4e..02db9ce8037 100644
--- a/chromium/third_party/blink/renderer/platform/transforms/transform_operations_test.cc
+++ b/chromium/third_party/blink/renderer/platform/transforms/transform_operations_test.cc
@@ -69,7 +69,7 @@ static void EmpiricallyTestBounds(const TransformOperations& from,
first_time = false;
}
- ASSERT_PRED_FORMAT2(FloatBoxTest::AssertContains, bounds, empirical_bounds);
+ ASSERT_PRED_FORMAT2(float_box_test::AssertContains, bounds, empirical_bounds);
}
TEST(TransformOperationsTest, AbsoluteAnimatedTranslatedBoundsTest) {
@@ -86,25 +86,25 @@ TEST(TransformOperationsTest, AbsoluteAnimatedTranslatedBoundsTest) {
EXPECT_TRUE(
to_ops.BlendedBoundsForBox(box, kIdentityOperations, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 20, 20, 210), bounds);
EXPECT_TRUE(
kIdentityOperations.BlendedBoundsForBox(box, to_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 20, 20, 210), bounds);
EXPECT_TRUE(
kIdentityOperations.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-30, 0, 0, 40, 30, 25), bounds);
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-30, 10, 15, 50, 20, 195), bounds);
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, -0.5, 1.25, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-50, 7.5, -77.5, 80, 27.5, 333.75), bounds);
}
@@ -148,25 +148,25 @@ TEST(TransformOperationsTest, AbsoluteAnimatedScaleBoundsTest) {
EXPECT_TRUE(
to_ops.BlendedBoundsForBox(box, kIdentityOperations, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 50, 20, 10), bounds);
EXPECT_TRUE(
kIdentityOperations.BlendedBoundsForBox(box, to_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 50, 20, 10), bounds);
EXPECT_TRUE(
kIdentityOperations.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, -30, 0, 40, 40, 10), bounds);
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, -30, 0, 50, 50, 10), bounds);
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, -0.5, 1.25, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, -55, 0, 52.5, 87.5, 10), bounds);
}
@@ -217,7 +217,7 @@ TEST(TransformOperationsTest, AbsoluteAnimatedRotationBounds) {
box.SetSize(FloatPoint3D(sizes[i], sizes[i], 0));
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-2, -2, 0, 4, 4, 0), bounds);
}
}
@@ -239,7 +239,7 @@ TEST(TransformOperationsTest, AbsoluteAnimatedExtremeRotationBounds) {
float max = 1;
float size = max - min;
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(min, min, min, size, size, size), bounds);
}
@@ -281,7 +281,7 @@ TEST(TransformOperationsTest, AbsoluteAnimatedOnAxisRotationBounds) {
FloatBox bounds;
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual, box, bounds);
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual, box, bounds);
}
// This would have been best as anonymous structs, but |arraysize|
@@ -328,7 +328,7 @@ TEST(TransformOperationsTest, AbsoluteAnimatedProblematicAxisRotationBounds) {
FloatBox bounds;
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual, tests[i].expected,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual, tests[i].expected,
bounds);
}
}
@@ -374,7 +374,7 @@ TEST(TransformOperationsTest, AbsoluteAnimatedPerspectiveBoundsTest) {
FloatBox box(0, 0, 0, 10, 10, 10);
FloatBox bounds;
to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds);
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 20, 20, 20), bounds);
from_ops.BlendedBoundsForBox(box, to_ops, -0.25, 1.25, &bounds);
@@ -383,7 +383,7 @@ TEST(TransformOperationsTest, AbsoluteAnimatedPerspectiveBoundsTest) {
// closest the observer is 17-10=7.
double projected_size = 10.0 / 7.0 * 17.0;
EXPECT_PRED_FORMAT2(
- FloatBoxTest::AssertAlmostEqual,
+ float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, projected_size, projected_size, projected_size),
bounds);
}
@@ -420,19 +420,19 @@ TEST(TransformOperationsTest, AnimatedSkewBoundsTest) {
FloatBox bounds;
to_ops.BlendedBoundsForBox(box, kIdentityOperations, 0, 1, &bounds);
- ASSERT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ ASSERT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(0, 0, 0, 10, 20, 10), bounds);
kIdentityOperations.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds);
- ASSERT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ ASSERT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-10, 0, 0, 20, 10, 10), bounds);
to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds);
- ASSERT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ ASSERT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-10, 0, 0, 20, 20, 10), bounds);
from_ops.BlendedBoundsForBox(box, to_ops, 0, 1, &bounds);
- ASSERT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ ASSERT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-10, 0, 0, 20, 20, 10), bounds);
}
@@ -465,7 +465,8 @@ TEST(TransformOperationsTest, NonCommutativeRotations) {
FloatBox expanded_bounds = bounds;
expanded_bounds.ExpandTo(blended_point);
- ASSERT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual, bounds, expanded_bounds);
+ ASSERT_PRED_FORMAT2(float_box_test::AssertAlmostEqual, bounds,
+ expanded_bounds);
}
TEST(TransformOperationsTest, AbsoluteSequenceBoundsTest) {
@@ -494,21 +495,21 @@ TEST(TransformOperationsTest, AbsoluteSequenceBoundsTest) {
FloatBox bounds;
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, -0.5, 1.5, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-57, -59, -1, 76, 112, 80), bounds);
EXPECT_TRUE(to_ops.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-32, -25, 7, 42, 44, 48), bounds);
EXPECT_TRUE(
to_ops.BlendedBoundsForBox(box, kIdentityOperations, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-33, -13, 3, 57, 19, 52), bounds);
EXPECT_TRUE(
kIdentityOperations.BlendedBoundsForBox(box, from_ops, 0, 1, &bounds));
- EXPECT_PRED_FORMAT2(FloatBoxTest::AssertAlmostEqual,
+ EXPECT_PRED_FORMAT2(float_box_test::AssertAlmostEqual,
FloatBox(-7, -3, 2, 15, 23, 20), bounds);
}
diff --git a/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.cc b/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.cc
index e14c89365f6..e4d3653082f 100644
--- a/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.cc
+++ b/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.cc
@@ -562,7 +562,7 @@ static void V3Cross(const Vector3 a, const Vector3 b, Vector3 result) {
static bool Decompose(const TransformationMatrix::Matrix4& mat,
TransformationMatrix::DecomposedType& result) {
TransformationMatrix::Matrix4 local_matrix;
- memcpy(local_matrix, mat, sizeof(TransformationMatrix::Matrix4));
+ memcpy(&local_matrix, &mat, sizeof(TransformationMatrix::Matrix4));
// Normalize the matrix.
if (local_matrix[3][3] == 0)
@@ -576,7 +576,7 @@ static bool Decompose(const TransformationMatrix::Matrix4& mat,
// perspectiveMatrix is used to solve for perspective, but it also provides
// an easy way to test for singularity of the upper 3x3 component.
TransformationMatrix::Matrix4 perspective_matrix;
- memcpy(perspective_matrix, local_matrix,
+ memcpy(&perspective_matrix, &local_matrix,
sizeof(TransformationMatrix::Matrix4));
for (i = 0; i < 3; i++)
perspective_matrix[i][3] = 0;
@@ -1431,6 +1431,11 @@ TransformationMatrix& TransformationMatrix::Multiply(
ST_DP(v_tmp_m2, &(matrix_[3][0]));
ST_DP(v_tmp_m3, &(matrix_[3][2]));
#elif defined(TRANSFORMATION_MATRIX_USE_X86_64_SSE2)
+ static_assert(alignof(TransformationMatrix) == 16,
+ "TransformationMatrix must be aligned.");
+ static_assert(alignof(TransformationMatrix::Matrix4) == 16,
+ "Matrix4 must be aligned.");
+
// x86_64 has 16 XMM registers which is enough to do the multiplication fully
// in registers.
__m128d matrix_block_a = _mm_load_pd(&(matrix_[0][0]));
diff --git a/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.h b/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.h
index e943e580a67..816565aec6f 100644
--- a/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.h
+++ b/chromium/third_party/blink/renderer/platform/transforms/transformation_matrix.h
@@ -34,7 +34,6 @@
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_point_3d.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace gfx {
@@ -53,6 +52,9 @@ class JSONArray;
struct Rotation;
#if defined(ARCH_CPU_X86_64)
#define TRANSFORMATION_MATRIX_USE_X86_64_SSE2
+#define ALIGNAS_TRANSFORMATION_MATRIX alignas(16)
+#else
+#define ALIGNAS_TRANSFORMATION_MATRIX
#endif
class PLATFORM_EXPORT TransformationMatrix {
@@ -62,24 +64,25 @@ class PLATFORM_EXPORT TransformationMatrix {
USING_FAST_MALLOC(TransformationMatrix);
public:
-// Throughout this class, we will be speaking in column vector convention.
-// i.e. Applying a transform T to point P is T * P.
-// The elements of the matrix and the vector looks like:
-// | scale_x skew_y_x skew_z_x translate_x | | x |
-// | skew_x_y scale_y skew_z_y translate_y | * | y |
-// | skew_x_z skew_y_z scale_z translate_z | | z |
-// | persp_x persp_y persp_z persp_w | | w |
-// Internally the matrix is stored as a 2-dimensional array in col-major order.
-// In other words, this is the layout of the matrix:
-// | matrix_[0][0] matrix_[1][0] matrix_[2][0] matrix_[3][0] |
-// | matrix_[0][1] matrix_[1][1] matrix_[2][1] matrix_[3][1] |
-// | matrix_[0][2] matrix_[1][2] matrix_[2][2] matrix_[3][2] |
-// | matrix_[0][3] matrix_[1][3] matrix_[2][3] matrix_[3][3] |
-#if defined(TRANSFORMATION_MATRIX_USE_X86_64_SSE2)
- typedef WTF_ALIGNED(double, Matrix4[4][4], 16);
-#else
- typedef double Matrix4[4][4];
-#endif
+ // Throughout this class, we will be speaking in column vector convention.
+ // i.e. Applying a transform T to point P is T * P.
+ // The elements of the matrix and the vector looks like:
+ // | scale_x skew_y_x skew_z_x translate_x | | x |
+ // | skew_x_y scale_y skew_z_y translate_y | * | y |
+ // | skew_x_z skew_y_z scale_z translate_z | | z |
+ // | persp_x persp_y persp_z persp_w | | w |
+ // Internally the matrix is stored as a 2-dimensional array in col-major
+ // order. In other words, this is the layout of the matrix:
+ // | matrix_[0][0] matrix_[1][0] matrix_[2][0] matrix_[3][0] |
+ // | matrix_[0][1] matrix_[1][1] matrix_[2][1] matrix_[3][1] |
+ // | matrix_[0][2] matrix_[1][2] matrix_[2][2] matrix_[3][2] |
+ // | matrix_[0][3] matrix_[1][3] matrix_[2][3] matrix_[3][3] |
+ struct ALIGNAS_TRANSFORMATION_MATRIX Matrix4 {
+ using Column = double[4];
+ Column& operator[](size_t i) { return columns[i]; }
+ const Column& operator[](size_t i) const { return columns[i]; }
+ Column columns[4];
+ };
static std::unique_ptr<TransformationMatrix> Create() {
return std::make_unique<TransformationMatrix>();
@@ -521,17 +524,14 @@ class PLATFORM_EXPORT TransformationMatrix {
static_cast<float>(result_z));
}
- void SetMatrix(const Matrix4 m) {
- if (m && m != matrix_)
- memcpy(matrix_, m, sizeof(Matrix4));
- }
+ void SetMatrix(const Matrix4& m) { memcpy(&matrix_, &m, sizeof(Matrix4)); }
void CheckAlignment() {
#if defined(TRANSFORMATION_MATRIX_USE_X86_64_SSE2)
// m_matrix can cause this class to require higher than usual alignment.
// Make sure the allocator handles this.
DCHECK_EQ((reinterpret_cast<uintptr_t>(this) &
- (WTF_ALIGN_OF(TransformationMatrix) - 1)),
+ (alignof(TransformationMatrix) - 1)),
0UL);
#endif
}
diff --git a/chromium/third_party/blink/renderer/platform/transforms/translate_transform_operation.h b/chromium/third_party/blink/renderer/platform/transforms/translate_transform_operation.h
index 3657ccb2102..ebb90a23612 100644
--- a/chromium/third_party/blink/renderer/platform/transforms/translate_transform_operation.h
+++ b/chromium/third_party/blink/renderer/platform/transforms/translate_transform_operation.h
@@ -25,8 +25,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_TRANSLATE_TRANSFORM_OPERATION_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_TRANSLATE_TRANSFORM_OPERATION_H_
-#include "third_party/blink/renderer/platform/length.h"
-#include "third_party/blink/renderer/platform/length_functions.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/transforms/transform_operation.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/platform/web_mouse_event.cc b/chromium/third_party/blink/renderer/platform/web_mouse_event.cc
index e21d084fddf..ff5338a2fd4 100644
--- a/chromium/third_party/blink/renderer/platform/web_mouse_event.cc
+++ b/chromium/third_party/blink/renderer/platform/web_mouse_event.cc
@@ -29,11 +29,6 @@ WebMouseEvent::WebMouseEvent(WebInputEvent::Type type,
SetMenuSourceType(gesture_event.GetType());
}
-WebFloatPoint WebMouseEvent::MovementInRootFrame() const {
- return WebFloatPoint((movement_x / frame_scale_),
- (movement_y / frame_scale_));
-}
-
WebFloatPoint WebMouseEvent::PositionInRootFrame() const {
return WebFloatPoint(
(position_in_widget_.x / frame_scale_) + frame_translate_.x,
diff --git a/chromium/third_party/blink/renderer/platform/web_pointer_event.cc b/chromium/third_party/blink/renderer/platform/web_pointer_event.cc
index c82c078b22f..8c710c12480 100644
--- a/chromium/third_party/blink/renderer/platform/web_pointer_event.cc
+++ b/chromium/third_party/blink/renderer/platform/web_pointer_event.cc
@@ -90,8 +90,6 @@ WebPointerEvent WebPointerEvent::WebPointerEventInRootFrame() const {
transformed_event.width /= frame_scale_;
if (HasHeight())
transformed_event.height /= frame_scale_;
- transformed_event.movement_x /= frame_scale_;
- transformed_event.movement_y /= frame_scale_;
transformed_event.position_in_widget_ =
WebFloatPoint((transformed_event.PositionInWidget().x / frame_scale_) +
frame_translate_.x,
diff --git a/chromium/third_party/blink/renderer/platform/web_task_runner.h b/chromium/third_party/blink/renderer/platform/web_task_runner.h
index 4b12e2e093a..04c6b31e89f 100644
--- a/chromium/third_party/blink/renderer/platform/web_task_runner.h
+++ b/chromium/third_party/blink/renderer/platform/web_task_runner.h
@@ -5,80 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEB_TASK_RUNNER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEB_TASK_RUNNER_H_
-#include <memory>
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/sequenced_task_runner.h"
-#include "third_party/blink/public/platform/web_common.h"
-#include "third_party/blink/renderer/platform/wtf/compiler.h"
-#include "third_party/blink/renderer/platform/wtf/functional.h"
-#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
-#include "third_party/blink/renderer/platform/wtf/time.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
-namespace blink {
-
-// TaskHandle is associated to a task posted by PostCancellableTask() or
-// PostCancellableDelayedTask() and cancels the associated task on
-// TaskHandle::cancel() call or on TaskHandle destruction.
-class BLINK_PLATFORM_EXPORT TaskHandle {
- public:
- // Returns true if the task will run later. Returns false if the task is
- // cancelled or the task is run already.
- // This function is not thread safe. Call this on the thread that has posted
- // the task.
- bool IsActive() const;
-
- // Cancels the task invocation. Do nothing if the task is cancelled or run
- // already.
- // This function is not thread safe. Call this on the thread that has posted
- // the task.
- void Cancel();
-
- TaskHandle();
- ~TaskHandle();
-
- TaskHandle(TaskHandle&&);
- TaskHandle& operator=(TaskHandle&&);
-
- class Runner;
-
- private:
- friend BLINK_PLATFORM_EXPORT WARN_UNUSED_RESULT TaskHandle
- PostCancellableTask(base::SequencedTaskRunner&,
- const base::Location&,
- base::OnceClosure);
- friend BLINK_PLATFORM_EXPORT WARN_UNUSED_RESULT TaskHandle
- PostDelayedCancellableTask(base::SequencedTaskRunner&,
- const base::Location&,
- base::OnceClosure,
- TimeDelta delay);
-
- explicit TaskHandle(scoped_refptr<Runner>);
- scoped_refptr<Runner> runner_;
-};
-
-// For cross-thread posting. Can be called from any thread.
-BLINK_PLATFORM_EXPORT void PostCrossThreadTask(base::SequencedTaskRunner&,
- const base::Location&,
- CrossThreadClosure);
-BLINK_PLATFORM_EXPORT void PostDelayedCrossThreadTask(
- base::SequencedTaskRunner&,
- const base::Location&,
- CrossThreadClosure,
- TimeDelta delay);
-
-// For same-thread cancellable task posting. Returns a TaskHandle object for
-// cancellation.
-BLINK_PLATFORM_EXPORT WARN_UNUSED_RESULT TaskHandle
-PostCancellableTask(base::SequencedTaskRunner&,
- const base::Location&,
- base::OnceClosure);
-BLINK_PLATFORM_EXPORT WARN_UNUSED_RESULT TaskHandle
-PostDelayedCancellableTask(base::SequencedTaskRunner&,
- const base::Location&,
- base::OnceClosure,
- TimeDelta delay);
-
-} // namespace blink
+// The contents of this file are moved to the above headers. For future
+// includes, use either of them.
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEB_TASK_RUNNER_H_
diff --git a/chromium/third_party/blink/renderer/platform/layout_test_support.cc b/chromium/third_party/blink/renderer/platform/web_test_support.cc
index a5c36884d92..66a26d6c60b 100644
--- a/chromium/third_party/blink/renderer/platform/layout_test_support.cc
+++ b/chromium/third_party/blink/renderer/platform/web_test_support.cc
@@ -28,28 +28,28 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/platform/layout_test_support.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
-// Wrapper functions defined in WebKit.h
+// Wrapper functions defined in blink.h
void SetLayoutTestMode(bool value) {
- LayoutTestSupport::SetIsRunningLayoutTest(value);
+ WebTestSupport::SetIsRunningWebTest(value);
}
bool LayoutTestMode() {
- return LayoutTestSupport::IsRunningLayoutTest();
+ return WebTestSupport::IsRunningWebTest();
}
void SetFontAntialiasingEnabledForTest(bool value) {
- LayoutTestSupport::SetFontAntialiasingEnabledForTest(value);
+ WebTestSupport::SetFontAntialiasingEnabledForTest(value);
}
bool FontAntialiasingEnabledForTest() {
- return LayoutTestSupport::IsFontAntialiasingEnabledForTest();
+ return WebTestSupport::IsFontAntialiasingEnabledForTest();
}
static bool g_is_running_layout_test = false;
@@ -57,36 +57,36 @@ static bool g_is_mock_theme_enabled = false;
static bool g_is_font_antialiasing_enabled = false;
static bool g_is_subpixel_positioning_allowed = true;
-bool LayoutTestSupport::IsRunningLayoutTest() {
+bool WebTestSupport::IsRunningWebTest() {
return g_is_running_layout_test;
}
-void LayoutTestSupport::SetIsRunningLayoutTest(bool value) {
+void WebTestSupport::SetIsRunningWebTest(bool value) {
g_is_running_layout_test = value;
}
-bool LayoutTestSupport::IsMockThemeEnabledForTest() {
+bool WebTestSupport::IsMockThemeEnabledForTest() {
return g_is_mock_theme_enabled;
}
-void LayoutTestSupport::SetMockThemeEnabledForTest(bool value) {
+void WebTestSupport::SetMockThemeEnabledForTest(bool value) {
DCHECK(g_is_running_layout_test);
g_is_mock_theme_enabled = value;
}
-bool LayoutTestSupport::IsFontAntialiasingEnabledForTest() {
+bool WebTestSupport::IsFontAntialiasingEnabledForTest() {
return g_is_font_antialiasing_enabled;
}
-void LayoutTestSupport::SetFontAntialiasingEnabledForTest(bool value) {
+void WebTestSupport::SetFontAntialiasingEnabledForTest(bool value) {
g_is_font_antialiasing_enabled = value;
}
-bool LayoutTestSupport::IsTextSubpixelPositioningAllowedForTest() {
+bool WebTestSupport::IsTextSubpixelPositioningAllowedForTest() {
return g_is_subpixel_positioning_allowed;
}
-void LayoutTestSupport::SetTextSubpixelPositioningAllowedForTest(bool value) {
+void WebTestSupport::SetTextSubpixelPositioningAllowedForTest(bool value) {
g_is_subpixel_positioning_allowed = value;
}
diff --git a/chromium/third_party/blink/renderer/platform/layout_test_support.h b/chromium/third_party/blink/renderer/platform/web_test_support.h
index 161819fd3a3..a3e5e5f9b29 100644
--- a/chromium/third_party/blink/renderer/platform/layout_test_support.h
+++ b/chromium/third_party/blink/renderer/platform/web_test_support.h
@@ -28,20 +28,20 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LAYOUT_TEST_SUPPORT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LAYOUT_TEST_SUPPORT_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEB_TEST_SUPPORT_H_
+#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEB_TEST_SUPPORT_H_
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
-class LayoutTestSupport {
- STATIC_ONLY(LayoutTestSupport);
+class WebTestSupport {
+ STATIC_ONLY(WebTestSupport);
public:
- PLATFORM_EXPORT static bool IsRunningLayoutTest();
- PLATFORM_EXPORT static void SetIsRunningLayoutTest(bool);
+ PLATFORM_EXPORT static bool IsRunningWebTest();
+ PLATFORM_EXPORT static void SetIsRunningWebTest(bool);
PLATFORM_EXPORT static bool IsMockThemeEnabledForTest();
PLATFORM_EXPORT static void SetMockThemeEnabledForTest(bool);
PLATFORM_EXPORT static bool IsFontAntialiasingEnabledForTest();
@@ -52,4 +52,4 @@ class LayoutTestSupport {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LAYOUT_TEST_SUPPORT_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEB_TEST_SUPPORT_H_
diff --git a/chromium/third_party/blink/renderer/platform/web_thread_supporting_gc.h b/chromium/third_party/blink/renderer/platform/web_thread_supporting_gc.h
index 03731ef80f4..d31e43dadfb 100644
--- a/chromium/third_party/blink/renderer/platform/web_thread_supporting_gc.h
+++ b/chromium/third_party/blink/renderer/platform/web_thread_supporting_gc.h
@@ -9,8 +9,8 @@
#include "base/threading/thread_checker.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/heap/gc_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/noncopyable.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
diff --git a/chromium/third_party/blink/renderer/platform/web_thread_type.cc b/chromium/third_party/blink/renderer/platform/web_thread_type.cc
index f767f455df9..fd20b801cfb 100644
--- a/chromium/third_party/blink/renderer/platform/web_thread_type.cc
+++ b/chromium/third_party/blink/renderer/platform/web_thread_type.cc
@@ -21,7 +21,7 @@ const char* GetNameForThreadType(WebThreadType thread_type) {
return "DedicatedWorker thread";
case WebThreadType::kSharedWorkerThread:
return "SharedWorker thread";
- case WebThreadType::kAnimationWorkletThread:
+ case WebThreadType::kAnimationAndPaintWorkletThread:
return "AnimationWorklet thread";
case WebThreadType::kServiceWorkerThread:
return "ServiceWorker thread";
diff --git a/chromium/third_party/blink/renderer/platform/web_touch_event.cc b/chromium/third_party/blink/renderer/platform/web_touch_event.cc
index 4f6bf26e1c7..e358ccb9d5f 100644
--- a/chromium/third_party/blink/renderer/platform/web_touch_event.cc
+++ b/chromium/third_party/blink/renderer/platform/web_touch_event.cc
@@ -26,8 +26,6 @@ WebTouchPoint WebTouchEvent::TouchPointInRootFrame(unsigned point) const {
WebTouchPoint transformed_point = touches[point];
transformed_point.radius_x /= frame_scale_;
transformed_point.radius_y /= frame_scale_;
- transformed_point.movement_x /= frame_scale_;
- transformed_point.movement_y /= frame_scale_;
transformed_point.SetPositionInWidget(
(transformed_point.PositionInWidget().x / frame_scale_) +
frame_translate_.x,
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/DEPS b/chromium/third_party/blink/renderer/platform/weborigin/DEPS
index 8b067e44441..14eb4e427a2 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/DEPS
+++ b/chromium/third_party/blink/renderer/platform/weborigin/DEPS
@@ -11,8 +11,6 @@ include_rules = [
"+net/base",
"+services/network/public/cpp/cors/origin_access_entry.h",
"+services/network/public/cpp/cors/origin_access_list.h",
- "+services/network/public/mojom/cors.mojom-shared.h",
- "+services/network/public/mojom/cors_origin_pattern.mojom-shared.h",
"+third_party/blink/renderer/platform/blob/blob_url.h",
"+third_party/blink/renderer/platform/platform_export.h",
"+third_party/blink/renderer/platform/runtime_enabled_features.h",
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/kurl.h b/chromium/third_party/blink/renderer/platform/weborigin/kurl.h
index b74bd5eca57..9dfcab29740 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/kurl.h
+++ b/chromium/third_party/blink/renderer/platform/weborigin/kurl.h
@@ -36,6 +36,9 @@
#include "url/url_canon.h"
#include "url/url_util.h"
+// KURL stands for the URL parser in KDE's HTML Widget (KHTML). The name hasn't
+// changed since Blink forked WebKit, which in turn forked KHTML.
+//
// KURL is Blink's main URL class, and is the analog to GURL in other Chromium
// code. It is not thread safe but is generally cheap to copy and compare KURLs
// to each other.
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.cc b/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.cc
index bba1484ec26..df41af03004 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.cc
+++ b/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.cc
@@ -38,8 +38,8 @@ namespace blink {
OriginAccessEntry::OriginAccessEntry(
const String& protocol,
const String& host,
- network::cors::OriginAccessEntry::MatchMode match_mode,
- network::mojom::CORSOriginAccessMatchPriority priority)
+ network::mojom::CorsOriginAccessMatchMode match_mode,
+ network::mojom::CorsOriginAccessMatchPriority priority)
: private_(std::string(protocol.Utf8().data()),
std::string(host.Utf8().data()),
match_mode,
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.h b/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.h
index 7b7ae44b46c..53e504d9b8a 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.h
+++ b/chromium/third_party/blink/renderer/platform/weborigin/origin_access_entry.h
@@ -54,9 +54,9 @@ class PLATFORM_EXPORT OriginAccessEntry {
OriginAccessEntry(
const String& protocol,
const String& host,
- network::cors::OriginAccessEntry::MatchMode,
- network::mojom::CORSOriginAccessMatchPriority priority =
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchMode,
+ network::mojom::CorsOriginAccessMatchPriority priority =
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
OriginAccessEntry(OriginAccessEntry&& from);
// 'matchesOrigin' requires a protocol match (e.g. 'http' != 'https').
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/referrer.h b/chromium/third_party/blink/renderer/platform/weborigin/referrer.h
index aa577e33d14..e47ab10aac3 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/referrer.h
+++ b/chromium/third_party/blink/renderer/platform/weborigin/referrer.h
@@ -31,8 +31,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REFERRER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REFERRER_H_
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -40,17 +40,18 @@ namespace blink {
struct Referrer {
DISALLOW_NEW();
- Referrer(const String& referrer, ReferrerPolicy referrer_policy)
+ Referrer(const String& referrer,
+ network::mojom::ReferrerPolicy referrer_policy)
: referrer(referrer), referrer_policy(referrer_policy) {
DCHECK(referrer == NoReferrer() || KURL(NullURL(), referrer).IsValid());
}
- Referrer() : referrer_policy(kReferrerPolicyDefault) {}
+ Referrer() : referrer_policy(network::mojom::ReferrerPolicy::kDefault) {}
// We use these strings instead of "no-referrer" and "client" in the spec.
static String NoReferrer() { return String(); }
static String ClientReferrerString() { return "about:client"; }
AtomicString referrer;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/referrer_policy.h b/chromium/third_party/blink/renderer/platform/weborigin/referrer_policy.h
deleted file mode 100644
index e9ddd2f8366..00000000000
--- a/chromium/third_party/blink/renderer/platform/weborigin/referrer_policy.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REFERRER_POLICY_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REFERRER_POLICY_H_
-
-#include <stdint.h>
-
-namespace blink {
-
-enum ReferrerPolicy : uint8_t {
- // https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-unsafe-url
- kReferrerPolicyAlways,
- // The default policy, if no policy is explicitly set by the page.
- kReferrerPolicyDefault,
- // https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-no-referrer-when-downgrade
- kReferrerPolicyNoReferrerWhenDowngrade,
- // https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-no-referrer
- kReferrerPolicyNever,
- // https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-origin
- kReferrerPolicyOrigin,
- // https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-origin-when-cross-origin
- kReferrerPolicyOriginWhenCrossOrigin,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin
- // Also used as the default policy when reduced-referrer-granularity is
- // enabled (not spec conformant).
- kReferrerPolicyStrictOriginWhenCrossOrigin,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-same-origin
- kReferrerPolicySameOrigin,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin
- kReferrerPolicyStrictOrigin,
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REFERRER_POLICY_H_
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/reporting_service_proxy_ptr_holder.h b/chromium/third_party/blink/renderer/platform/weborigin/reporting_service_proxy_ptr_holder.h
index c8776e5671a..c46bed490f9 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/reporting_service_proxy_ptr_holder.h
+++ b/chromium/third_party/blink/renderer/platform/weborigin/reporting_service_proxy_ptr_holder.h
@@ -49,26 +49,26 @@ class ReportingServiceProxyPtrHolder {
void QueueCspViolationReport(
const KURL& url,
const String& group,
- const SecurityPolicyViolationEventInit& violation_data) {
+ const SecurityPolicyViolationEventInit* violation_data) {
if (reporting_service_proxy) {
reporting_service_proxy->QueueCspViolationReport(
url, group ? group : "default",
- violation_data.documentURI() ? violation_data.documentURI() : "",
- violation_data.referrer() ? violation_data.referrer() : "",
- violation_data.violatedDirective()
- ? violation_data.violatedDirective()
+ violation_data->documentURI() ? violation_data->documentURI() : "",
+ violation_data->referrer() ? violation_data->referrer() : "",
+ violation_data->violatedDirective()
+ ? violation_data->violatedDirective()
: "",
- violation_data.effectiveDirective()
- ? violation_data.effectiveDirective()
+ violation_data->effectiveDirective()
+ ? violation_data->effectiveDirective()
: "",
- violation_data.originalPolicy() ? violation_data.originalPolicy()
- : "",
- violation_data.disposition() ? violation_data.disposition() : "",
- violation_data.blockedURI() ? violation_data.blockedURI() : "",
- violation_data.lineNumber(), violation_data.columnNumber(),
- violation_data.sourceFile() ? violation_data.sourceFile() : "",
- violation_data.statusCode(),
- violation_data.sample() ? violation_data.sample() : "");
+ violation_data->originalPolicy() ? violation_data->originalPolicy()
+ : "",
+ violation_data->disposition() ? violation_data->disposition() : "",
+ violation_data->blockedURI() ? violation_data->blockedURI() : "",
+ violation_data->lineNumber(), violation_data->columnNumber(),
+ violation_data->sourceFile() ? violation_data->sourceFile() : "",
+ violation_data->statusCode(),
+ violation_data->sample() ? violation_data->sample() : "");
}
}
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.cc b/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.cc
index a86de192760..65a0b9003c4 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.cc
+++ b/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.cc
@@ -58,7 +58,7 @@ class URLSchemesRegistry final {
secure_schemes.insert(scheme.c_str());
for (auto& scheme : url::GetNoAccessSchemes())
schemes_with_unique_origins.insert(scheme.c_str());
- for (auto& scheme : url::GetCORSEnabledSchemes())
+ for (auto& scheme : url::GetCorsEnabledSchemes())
cors_enabled_schemes.insert(scheme.c_str());
for (auto& scheme : url::GetCSPBypassingSchemes()) {
content_security_policy_bypassing_schemes.insert(
@@ -224,14 +224,14 @@ bool SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs(
scheme);
}
-bool SchemeRegistry::ShouldTreatURLSchemeAsCORSEnabled(const String& scheme) {
+bool SchemeRegistry::ShouldTreatURLSchemeAsCorsEnabled(const String& scheme) {
DCHECK_EQ(scheme, scheme.LowerASCII());
if (scheme.IsEmpty())
return false;
return GetURLSchemesRegistry().cors_enabled_schemes.Contains(scheme);
}
-String SchemeRegistry::ListOfCORSEnabledURLSchemes() {
+String SchemeRegistry::ListOfCorsEnabledURLSchemes() {
StringBuilder builder;
bool add_separator = false;
for (const auto& scheme : GetURLSchemesRegistry().cors_enabled_schemes) {
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.h b/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.h
index 4676a712d39..79b4b5358cc 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.h
+++ b/chromium/third_party/blink/renderer/platform/weborigin/scheme_registry.h
@@ -87,10 +87,10 @@ class PLATFORM_EXPORT SchemeRegistry {
static bool ShouldTreatURLSchemeAsNotAllowingJavascriptURLs(
const String& scheme);
- static bool ShouldTreatURLSchemeAsCORSEnabled(const String& scheme);
+ static bool ShouldTreatURLSchemeAsCorsEnabled(const String& scheme);
// Serialize the registered schemes in a comma-separated list.
- static String ListOfCORSEnabledURLSchemes();
+ static String ListOfCorsEnabledURLSchemes();
// "Legacy" schemes (e.g. 'ftp:', 'gopher:') which we might want to treat
// differently from "webby" schemes.
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/security_origin.cc b/chromium/third_party/blink/renderer/platform/weborigin/security_origin.cc
index fc7638c5b6b..81b8fa13fb8 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/security_origin.cc
+++ b/chromium/third_party/blink/renderer/platform/weborigin/security_origin.cc
@@ -99,12 +99,14 @@ static bool ShouldTreatAsOpaqueOrigin(const KURL& url) {
if (!url.IsValid())
return true;
- // FIXME: Do we need to unwrap the URL further?
KURL relevant_url;
if (SecurityOrigin::ShouldUseInnerURL(url)) {
relevant_url = SecurityOrigin::ExtractInnerURL(url);
if (!relevant_url.IsValid())
return true;
+ // If the inner URL is also wrapped, the URL is invalid, so treat as opqaue.
+ if (SecurityOrigin::ShouldUseInnerURL(relevant_url))
+ return true;
} else {
relevant_url = url;
}
@@ -215,8 +217,8 @@ scoped_refptr<SecurityOrigin> SecurityOrigin::CreateOpaque(
scoped_refptr<SecurityOrigin> SecurityOrigin::CreateFromUrlOrigin(
const url::Origin& origin) {
const url::SchemeHostPort& tuple = origin.GetTupleOrPrecursorTupleIfOpaque();
- DCHECK(String::FromUTF8(tuple.scheme().c_str()).ContainsOnlyASCII());
- DCHECK(String::FromUTF8(tuple.host().c_str()).ContainsOnlyASCII());
+ DCHECK(String::FromUTF8(tuple.scheme().c_str()).ContainsOnlyASCIIOrEmpty());
+ DCHECK(String::FromUTF8(tuple.host().c_str()).ContainsOnlyASCIIOrEmpty());
scoped_refptr<SecurityOrigin> tuple_origin;
if (!tuple.IsInvalid()) {
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/security_origin_test.cc b/chromium/third_party/blink/renderer/platform/weborigin/security_origin_test.cc
index 52c640c4934..e77bd9220af 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/security_origin_test.cc
+++ b/chromium/third_party/blink/renderer/platform/weborigin/security_origin_test.cc
@@ -48,7 +48,10 @@ namespace blink {
const uint16_t kMaxAllowedPort = UINT16_MAX;
-class SecurityOriginTest : public testing::Test {};
+class SecurityOriginTest : public testing::Test {
+ private:
+ void TearDown() override { SecurityPolicy::ClearOriginAccessList(); }
+};
TEST_F(SecurityOriginTest, ValidPortsCreateTupleOrigins) {
uint16_t ports[] = {0, 80, 443, 5000, kMaxAllowedPort};
@@ -358,7 +361,7 @@ TEST_F(SecurityOriginTest, CanRequestWithAllowListedAccess) {
// Adding the url to the access allowlist should allow the request.
SecurityPolicy::AddOriginAccessAllowListEntry(
*origin, "https", "example.com", false,
- network::mojom::CORSOriginAccessMatchPriority::kMediumPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kMediumPriority);
EXPECT_TRUE(origin->CanRequest(url));
}
@@ -371,10 +374,10 @@ TEST_F(SecurityOriginTest, CannotRequestWithBlockListedAccess) {
// BlockList that is more or same specificity wins.
SecurityPolicy::AddOriginAccessAllowListEntry(
*origin, "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
SecurityPolicy::AddOriginAccessBlockListEntry(
*origin, "https", "example.com", false,
- network::mojom::CORSOriginAccessMatchPriority::kLowPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kLowPriority);
// Block since example.com is on the allowlist & blocklist.
EXPECT_FALSE(origin->CanRequest(blocked_url));
// Allow since *.example.com is on the allowlist but not the blocklist.
@@ -389,10 +392,10 @@ TEST_F(SecurityOriginTest, CanRequestWithMoreSpecificAllowList) {
SecurityPolicy::AddOriginAccessAllowListEntry(
*origin, "https", "test.example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kMediumPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kMediumPriority);
SecurityPolicy::AddOriginAccessBlockListEntry(
*origin, "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kLowPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kLowPriority);
// Allow since test.example.com (allowlist) has a higher priority than
// *.example.com (blocklist).
EXPECT_TRUE(origin->CanRequest(allowed_url));
@@ -413,19 +416,19 @@ TEST_F(SecurityOriginTest, PunycodeNotUnicode) {
// Verify unicode origin can not be allowlisted.
SecurityPolicy::AddOriginAccessAllowListEntry(
*origin, "https", "☃.net", true,
- network::mojom::CORSOriginAccessMatchPriority::kMediumPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kMediumPriority);
EXPECT_FALSE(origin->CanRequest(punycode_url));
EXPECT_FALSE(origin->CanRequest(unicode_url));
// Verify punycode allowlist only affects punycode URLs.
SecurityPolicy::AddOriginAccessAllowListEntry(
*origin, "https", "xn--n3h.net", true,
- network::mojom::CORSOriginAccessMatchPriority::kMediumPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kMediumPriority);
EXPECT_TRUE(origin->CanRequest(punycode_url));
EXPECT_FALSE(origin->CanRequest(unicode_url));
- // Clear enterprise policy allowlist.
- SecurityPolicy::ClearOriginAccessAllowListForOrigin(*origin);
+ // Clear enterprise policy allow/block lists.
+ SecurityPolicy::ClearOriginAccessListForOrigin(*origin);
EXPECT_FALSE(origin->CanRequest(punycode_url));
EXPECT_FALSE(origin->CanRequest(unicode_url));
@@ -433,7 +436,7 @@ TEST_F(SecurityOriginTest, PunycodeNotUnicode) {
// Simulate <all_urls> being in the extension permissions.
SecurityPolicy::AddOriginAccessAllowListEntry(
*origin, "https", "", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
EXPECT_TRUE(origin->CanRequest(punycode_url));
EXPECT_FALSE(origin->CanRequest(unicode_url));
@@ -441,14 +444,14 @@ TEST_F(SecurityOriginTest, PunycodeNotUnicode) {
// Verify unicode origin can not be blocklisted.
SecurityPolicy::AddOriginAccessBlockListEntry(
*origin, "https", "☃.net", true,
- network::mojom::CORSOriginAccessMatchPriority::kLowPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kLowPriority);
EXPECT_TRUE(origin->CanRequest(punycode_url));
EXPECT_FALSE(origin->CanRequest(unicode_url));
// Verify punycode blocklist only affects punycode URLs.
SecurityPolicy::AddOriginAccessBlockListEntry(
*origin, "https", "xn--n3h.net", true,
- network::mojom::CORSOriginAccessMatchPriority::kLowPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kLowPriority);
EXPECT_FALSE(origin->CanRequest(punycode_url));
EXPECT_FALSE(origin->CanRequest(unicode_url));
}
@@ -694,6 +697,25 @@ TEST_F(SecurityOriginTest, UrlOriginConversions) {
}
}
+TEST_F(SecurityOriginTest, InvalidWrappedUrls) {
+ const char* kTestCases[] = {
+ "blob:filesystem:ws:b/.",
+ "blob:filesystem:ftp://a/b",
+ "filesystem:filesystem:http://example.org:88/foo/bar",
+ "blob:blob:file://localhost/foo/bar",
+ };
+
+ for (const char* test_url : kTestCases) {
+ scoped_refptr<SecurityOrigin> target_origin =
+ SecurityOrigin::CreateFromString(test_url);
+ EXPECT_TRUE(target_origin->IsOpaque())
+ << test_url << " is not opaque as a blink::SecurityOrigin";
+ url::Origin origin = target_origin->ToUrlOrigin();
+ EXPECT_TRUE(origin.opaque())
+ << test_url << " is not opaque as a url::Origin";
+ }
+}
+
TEST_F(SecurityOriginTest, EffectiveDomain) {
constexpr struct {
const char* expected_effective_domain;
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/security_policy.cc b/chromium/third_party/blink/renderer/platform/weborigin/security_policy.cc
index 1aef3f22de7..2a893a7f627 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/security_policy.cc
+++ b/chromium/third_party/blink/renderer/platform/weborigin/security_policy.cc
@@ -32,8 +32,7 @@
#include "base/strings/pattern.h"
#include "services/network/public/cpp/cors/origin_access_list.h"
-#include "services/network/public/mojom/cors_origin_pattern.mojom-shared.h"
-#include "third_party/blink/public/platform/web_referrer_policy.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
@@ -90,15 +89,18 @@ bool SecurityPolicy::ShouldHideReferrer(const KURL& url, const KURL& referrer) {
return !url_is_secure_url;
}
-Referrer SecurityPolicy::GenerateReferrer(ReferrerPolicy referrer_policy,
- const KURL& url,
- const String& referrer) {
- ReferrerPolicy referrer_policy_no_default = referrer_policy;
- if (referrer_policy_no_default == kReferrerPolicyDefault) {
+Referrer SecurityPolicy::GenerateReferrer(
+ network::mojom::ReferrerPolicy referrer_policy,
+ const KURL& url,
+ const String& referrer) {
+ network::mojom::ReferrerPolicy referrer_policy_no_default = referrer_policy;
+ if (referrer_policy_no_default == network::mojom::ReferrerPolicy::kDefault) {
if (RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()) {
- referrer_policy_no_default = kReferrerPolicyStrictOriginWhenCrossOrigin;
+ referrer_policy_no_default = network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin;
} else {
- referrer_policy_no_default = kReferrerPolicyNoReferrerWhenDowngrade;
+ referrer_policy_no_default =
+ network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade;
}
}
if (referrer == Referrer::NoReferrer())
@@ -114,17 +116,17 @@ Referrer SecurityPolicy::GenerateReferrer(ReferrerPolicy referrer_policy,
return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);
switch (referrer_policy_no_default) {
- case kReferrerPolicyNever:
+ case network::mojom::ReferrerPolicy::kNever:
return Referrer(Referrer::NoReferrer(), referrer_policy_no_default);
- case kReferrerPolicyAlways:
+ case network::mojom::ReferrerPolicy::kAlways:
return Referrer(referrer, referrer_policy_no_default);
- case kReferrerPolicyOrigin: {
+ case network::mojom::ReferrerPolicy::kOrigin: {
String origin = SecurityOrigin::Create(referrer_url)->ToString();
// A security origin is not a canonical URL as it lacks a path. Add /
// to turn it into a canonical URL we can use as referrer.
return Referrer(origin + "/", referrer_policy_no_default);
}
- case kReferrerPolicyOriginWhenCrossOrigin: {
+ case network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin: {
scoped_refptr<const SecurityOrigin> referrer_origin =
SecurityOrigin::Create(referrer_url);
scoped_refptr<const SecurityOrigin> url_origin =
@@ -135,7 +137,7 @@ Referrer SecurityPolicy::GenerateReferrer(ReferrerPolicy referrer_policy,
}
break;
}
- case kReferrerPolicySameOrigin: {
+ case network::mojom::ReferrerPolicy::kSameOrigin: {
scoped_refptr<const SecurityOrigin> referrer_origin =
SecurityOrigin::Create(referrer_url);
scoped_refptr<const SecurityOrigin> url_origin =
@@ -145,14 +147,15 @@ Referrer SecurityPolicy::GenerateReferrer(ReferrerPolicy referrer_policy,
}
return Referrer(referrer, referrer_policy_no_default);
}
- case kReferrerPolicyStrictOrigin: {
+ case network::mojom::ReferrerPolicy::kStrictOrigin: {
String origin = SecurityOrigin::Create(referrer_url)->ToString();
return Referrer(ShouldHideReferrer(url, referrer_url)
? Referrer::NoReferrer()
: origin + "/",
referrer_policy_no_default);
}
- case kReferrerPolicyStrictOriginWhenCrossOrigin: {
+ case network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin: {
scoped_refptr<const SecurityOrigin> referrer_origin =
SecurityOrigin::Create(referrer_url);
scoped_refptr<const SecurityOrigin> url_origin =
@@ -166,9 +169,9 @@ Referrer SecurityPolicy::GenerateReferrer(ReferrerPolicy referrer_policy,
}
break;
}
- case kReferrerPolicyNoReferrerWhenDowngrade:
+ case network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade:
break;
- case kReferrerPolicyDefault:
+ case network::mojom::ReferrerPolicy::kDefault:
NOTREACHED();
break;
}
@@ -240,57 +243,51 @@ void SecurityPolicy::AddOriginAccessAllowListEntry(
const String& destination_protocol,
const String& destination_domain,
bool allow_destination_subdomains,
- const network::mojom::CORSOriginAccessMatchPriority priority) {
+ const network::mojom::CorsOriginAccessMatchPriority priority) {
MutexLocker lock(GetMutex());
GetOriginAccessList().AddAllowListEntryForOrigin(
source_origin.ToUrlOrigin(), WebString(destination_protocol).Utf8(),
- WebString(destination_domain).Utf8(), allow_destination_subdomains,
+ WebString(destination_domain).Utf8(),
+ allow_destination_subdomains
+ ? network::mojom::CorsOriginAccessMatchMode::kAllowSubdomains
+ : network::mojom::CorsOriginAccessMatchMode::kDisallowSubdomains,
priority);
}
-void SecurityPolicy::ClearOriginAccessAllowListForOrigin(
- const SecurityOrigin& source_origin) {
- MutexLocker lock(GetMutex());
- GetOriginAccessList().SetAllowListForOrigin(
- source_origin.ToUrlOrigin(),
- std::vector<network::mojom::CorsOriginPatternPtr>());
-}
-
-void SecurityPolicy::ClearOriginAccessBlockListForOrigin(
- const SecurityOrigin& source_origin) {
- MutexLocker lock(GetMutex());
- GetOriginAccessList().SetBlockListForOrigin(
- source_origin.ToUrlOrigin(),
- std::vector<network::mojom::CorsOriginPatternPtr>());
-}
-
-void SecurityPolicy::ClearOriginAccessAllowList() {
- MutexLocker lock(GetMutex());
- GetOriginAccessList().ClearAllowList();
-}
-
void SecurityPolicy::AddOriginAccessBlockListEntry(
const SecurityOrigin& source_origin,
const String& destination_protocol,
const String& destination_domain,
bool allow_destination_subdomains,
- const network::mojom::CORSOriginAccessMatchPriority priority) {
+ const network::mojom::CorsOriginAccessMatchPriority priority) {
MutexLocker lock(GetMutex());
GetOriginAccessList().AddBlockListEntryForOrigin(
source_origin.ToUrlOrigin(), WebString(destination_protocol).Utf8(),
- WebString(destination_domain).Utf8(), allow_destination_subdomains,
+ WebString(destination_domain).Utf8(),
+ allow_destination_subdomains
+ ? network::mojom::CorsOriginAccessMatchMode::kAllowSubdomains
+ : network::mojom::CorsOriginAccessMatchMode::kDisallowSubdomains,
priority);
}
-void SecurityPolicy::ClearOriginAccessBlockList() {
+void SecurityPolicy::ClearOriginAccessListForOrigin(
+ const SecurityOrigin& source_origin) {
+ MutexLocker lock(GetMutex());
+ const url::Origin origin = source_origin.ToUrlOrigin();
+ GetOriginAccessList().ClearAllowListForOrigin(origin);
+ GetOriginAccessList().ClearBlockListForOrigin(origin);
+}
+
+void SecurityPolicy::ClearOriginAccessList() {
MutexLocker lock(GetMutex());
+ GetOriginAccessList().ClearAllowList();
GetOriginAccessList().ClearBlockList();
}
bool SecurityPolicy::ReferrerPolicyFromString(
const String& policy,
ReferrerPolicyLegacyKeywordsSupport legacy_keywords_support,
- ReferrerPolicy* result) {
+ network::mojom::ReferrerPolicy* result) {
DCHECK(!policy.IsNull());
bool support_legacy_keywords =
(legacy_keywords_support == kSupportReferrerPolicyLegacyKeywords);
@@ -298,39 +295,40 @@ bool SecurityPolicy::ReferrerPolicyFromString(
if (EqualIgnoringASCIICase(policy, "no-referrer") ||
(support_legacy_keywords && (EqualIgnoringASCIICase(policy, "never") ||
EqualIgnoringASCIICase(policy, "none")))) {
- *result = kReferrerPolicyNever;
+ *result = network::mojom::ReferrerPolicy::kNever;
return true;
}
if (EqualIgnoringASCIICase(policy, "unsafe-url") ||
(support_legacy_keywords && EqualIgnoringASCIICase(policy, "always"))) {
- *result = kReferrerPolicyAlways;
+ *result = network::mojom::ReferrerPolicy::kAlways;
return true;
}
if (EqualIgnoringASCIICase(policy, "origin")) {
- *result = kReferrerPolicyOrigin;
+ *result = network::mojom::ReferrerPolicy::kOrigin;
return true;
}
if (EqualIgnoringASCIICase(policy, "origin-when-cross-origin") ||
(support_legacy_keywords &&
EqualIgnoringASCIICase(policy, "origin-when-crossorigin"))) {
- *result = kReferrerPolicyOriginWhenCrossOrigin;
+ *result = network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin;
return true;
}
if (EqualIgnoringASCIICase(policy, "same-origin")) {
- *result = kReferrerPolicySameOrigin;
+ *result = network::mojom::ReferrerPolicy::kSameOrigin;
return true;
}
if (EqualIgnoringASCIICase(policy, "strict-origin")) {
- *result = kReferrerPolicyStrictOrigin;
+ *result = network::mojom::ReferrerPolicy::kStrictOrigin;
return true;
}
if (EqualIgnoringASCIICase(policy, "strict-origin-when-cross-origin")) {
- *result = kReferrerPolicyStrictOriginWhenCrossOrigin;
+ *result = network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin;
return true;
}
if (EqualIgnoringASCIICase(policy, "no-referrer-when-downgrade") ||
(support_legacy_keywords && EqualIgnoringASCIICase(policy, "default"))) {
- *result = kReferrerPolicyNoReferrerWhenDowngrade;
+ *result = network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade;
return true;
}
return false;
@@ -348,13 +346,14 @@ inline bool IsASCIIAlphaOrHyphen(CharType c) {
bool SecurityPolicy::ReferrerPolicyFromHeaderValue(
const String& header_value,
ReferrerPolicyLegacyKeywordsSupport legacy_keywords_support,
- ReferrerPolicy* result) {
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy* result) {
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
Vector<String> tokens;
header_value.Split(',', true, tokens);
for (const auto& token : tokens) {
- ReferrerPolicy current_result;
+ network::mojom::ReferrerPolicy current_result;
auto stripped_token = token.StripWhiteSpace();
if (SecurityPolicy::ReferrerPolicyFromString(token.StripWhiteSpace(),
legacy_keywords_support,
@@ -371,25 +370,32 @@ bool SecurityPolicy::ReferrerPolicyFromHeaderValue(
}
}
- if (referrer_policy == kReferrerPolicyDefault)
+ if (referrer_policy == network::mojom::ReferrerPolicy::kDefault)
return false;
*result = referrer_policy;
return true;
}
-STATIC_ASSERT_ENUM(kWebReferrerPolicyAlways, kReferrerPolicyAlways);
-STATIC_ASSERT_ENUM(kWebReferrerPolicyDefault, kReferrerPolicyDefault);
-STATIC_ASSERT_ENUM(kWebReferrerPolicyNoReferrerWhenDowngrade,
- kReferrerPolicyNoReferrerWhenDowngrade);
-STATIC_ASSERT_ENUM(kWebReferrerPolicyNever, kReferrerPolicyNever);
-STATIC_ASSERT_ENUM(kWebReferrerPolicyOrigin, kReferrerPolicyOrigin);
-STATIC_ASSERT_ENUM(kWebReferrerPolicyOriginWhenCrossOrigin,
- kReferrerPolicyOriginWhenCrossOrigin);
-STATIC_ASSERT_ENUM(kWebReferrerPolicySameOrigin, kReferrerPolicySameOrigin);
-STATIC_ASSERT_ENUM(kWebReferrerPolicyStrictOrigin, kReferrerPolicyStrictOrigin);
-STATIC_ASSERT_ENUM(
- kWebReferrerPolicyNoReferrerWhenDowngradeOriginWhenCrossOrigin,
- kReferrerPolicyStrictOriginWhenCrossOrigin);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kAlways,
+ network::mojom::ReferrerPolicy::kAlways);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kDefault,
+ network::mojom::ReferrerPolicy::kDefault);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade,
+ network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kNever,
+ network::mojom::ReferrerPolicy::kNever);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kOrigin,
+ network::mojom::ReferrerPolicy::kOrigin);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin,
+ network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kSameOrigin,
+ network::mojom::ReferrerPolicy::kSameOrigin);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::kStrictOrigin,
+ network::mojom::ReferrerPolicy::kStrictOrigin);
+STATIC_ASSERT_ENUM(network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/security_policy.h b/chromium/third_party/blink/renderer/platform/weborigin/security_policy.h
index 68aea8f9009..a3ebc1e87bc 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/security_policy.h
+++ b/chromium/third_party/blink/renderer/platform/weborigin/security_policy.h
@@ -29,10 +29,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_SECURITY_POLICY_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_SECURITY_POLICY_H_
-#include "services/network/public/mojom/cors.mojom-shared.h"
+#include "services/network/public/mojom/cors_origin_pattern.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -62,7 +62,7 @@ class PLATFORM_EXPORT SecurityPolicy {
// Returns the referrer modified according to the referrer policy for a
// navigation to a given URL. If the referrer returned is empty, the
// referrer header should be omitted.
- static Referrer GenerateReferrer(ReferrerPolicy,
+ static Referrer GenerateReferrer(network::mojom::ReferrerPolicy,
const KURL&,
const String& referrer);
@@ -71,20 +71,16 @@ class PLATFORM_EXPORT SecurityPolicy {
const String& destination_protocol,
const String& destination_domain,
bool allow_destination_subdomains,
- const network::mojom::CORSOriginAccessMatchPriority priority);
- static void ClearOriginAccessAllowListForOrigin(
- const SecurityOrigin& source_origin);
- static void ClearOriginAccessBlockListForOrigin(
- const SecurityOrigin& source_origin);
- static void ClearOriginAccessAllowList();
-
+ const network::mojom::CorsOriginAccessMatchPriority priority);
static void AddOriginAccessBlockListEntry(
const SecurityOrigin& source_origin,
const String& destination_protocol,
const String& destination_domain,
bool allow_destination_subdomains,
- const network::mojom::CORSOriginAccessMatchPriority priority);
- static void ClearOriginAccessBlockList();
+ const network::mojom::CorsOriginAccessMatchPriority priority);
+ static void ClearOriginAccessListForOrigin(
+ const SecurityOrigin& source_origin);
+ static void ClearOriginAccessList();
static bool IsOriginAccessAllowed(const SecurityOrigin* active_origin,
const SecurityOrigin* target_origin);
@@ -97,11 +93,12 @@ class PLATFORM_EXPORT SecurityPolicy {
static bool ReferrerPolicyFromString(const String& policy,
ReferrerPolicyLegacyKeywordsSupport,
- ReferrerPolicy* result);
+ network::mojom::ReferrerPolicy* result);
- static bool ReferrerPolicyFromHeaderValue(const String& header_value,
- ReferrerPolicyLegacyKeywordsSupport,
- ReferrerPolicy* result);
+ static bool ReferrerPolicyFromHeaderValue(
+ const String& header_value,
+ ReferrerPolicyLegacyKeywordsSupport,
+ network::mojom::ReferrerPolicy* result);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/platform/weborigin/security_policy_test.cc b/chromium/third_party/blink/renderer/platform/weborigin/security_policy_test.cc
index 6faa417291a..ec1e521288b 100644
--- a/chromium/third_party/blink/renderer/platform/weborigin/security_policy_test.cc
+++ b/chromium/third_party/blink/renderer/platform/weborigin/security_policy_test.cc
@@ -41,7 +41,8 @@ namespace blink {
TEST(SecurityPolicyTest, EmptyReferrerForUnauthorizedScheme) {
const KURL example_http_url = KURL("http://example.com/");
EXPECT_TRUE(String() == SecurityPolicy::GenerateReferrer(
- kReferrerPolicyAlways, example_http_url,
+ network::mojom::ReferrerPolicy::kAlways,
+ example_http_url,
String::FromUTF8("chrome://somepage/"))
.referrer);
}
@@ -52,11 +53,13 @@ TEST(SecurityPolicyTest, GenerateReferrerRespectsReferrerSchemesRegistry) {
const String foobar_scheme = String::FromUTF8("foobar");
EXPECT_EQ(String(), SecurityPolicy::GenerateReferrer(
- kReferrerPolicyAlways, example_http_url, foobar_url)
+ network::mojom::ReferrerPolicy::kAlways,
+ example_http_url, foobar_url)
.referrer);
SchemeRegistry::RegisterURLSchemeAsAllowedForReferrer(foobar_scheme);
EXPECT_EQ(foobar_url, SecurityPolicy::GenerateReferrer(
- kReferrerPolicyAlways, example_http_url, foobar_url)
+ network::mojom::ReferrerPolicy::kAlways,
+ example_http_url, foobar_url)
.referrer);
SchemeRegistry::RemoveURLSchemeAsAllowedForReferrer(foobar_scheme);
}
@@ -75,7 +78,7 @@ TEST(SecurityPolicyTest, ShouldHideReferrerRespectsReferrerSchemesRegistry) {
TEST(SecurityPolicyTest, GenerateReferrer) {
struct TestCase {
- ReferrerPolicy policy;
+ network::mojom::ReferrerPolicy policy;
const char* referrer;
const char* destination;
const char* expected;
@@ -95,97 +98,140 @@ TEST(SecurityPolicyTest, GenerateReferrer) {
TestCase inputs[] = {
// HTTP -> HTTP: Same Origin
- {kReferrerPolicyAlways, kInsecureURLA, kInsecureURLA, kInsecureURLA},
- {kReferrerPolicyDefault, kInsecureURLA, kInsecureURLA, kInsecureURLA},
- {kReferrerPolicyNoReferrerWhenDowngrade, kInsecureURLA, kInsecureURLA,
+ {network::mojom::ReferrerPolicy::kAlways, kInsecureURLA, kInsecureURLA,
kInsecureURLA},
- {kReferrerPolicyNever, kInsecureURLA, kInsecureURLA, nullptr},
- {kReferrerPolicyOrigin, kInsecureURLA, kInsecureURLA, kInsecureOriginA},
- {kReferrerPolicyOriginWhenCrossOrigin, kInsecureURLA, kInsecureURLA,
+ {network::mojom::ReferrerPolicy::kDefault, kInsecureURLA, kInsecureURLA,
kInsecureURLA},
- {kReferrerPolicySameOrigin, kInsecureURLA, kInsecureURLA, kInsecureURLA},
- {kReferrerPolicyStrictOrigin, kInsecureURLA, kInsecureURLA,
+ {network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, kInsecureURLA,
+ kInsecureURLA, kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kNever, kInsecureURLA, kInsecureURLA,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kOrigin, kInsecureURLA, kInsecureURLA,
kInsecureOriginA},
- {kReferrerPolicyStrictOriginWhenCrossOrigin, kInsecureURLA, kInsecureURLA,
- kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, kInsecureURLA,
+ kInsecureURLA, kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kSameOrigin, kInsecureURLA,
+ kInsecureURLA, kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kStrictOrigin, kInsecureURLA,
+ kInsecureURLA, kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ kInsecureURLA, kInsecureURLA, kInsecureURLA},
// HTTP -> HTTP: Cross Origin
- {kReferrerPolicyAlways, kInsecureURLA, kInsecureURLB, kInsecureURLA},
- {kReferrerPolicyDefault, kInsecureURLA, kInsecureURLB, kInsecureURLA},
- {kReferrerPolicyNoReferrerWhenDowngrade, kInsecureURLA, kInsecureURLB,
+ {network::mojom::ReferrerPolicy::kAlways, kInsecureURLA, kInsecureURLB,
kInsecureURLA},
- {kReferrerPolicyNever, kInsecureURLA, kInsecureURLB, nullptr},
- {kReferrerPolicyOrigin, kInsecureURLA, kInsecureURLB, kInsecureOriginA},
- {kReferrerPolicyOriginWhenCrossOrigin, kInsecureURLA, kInsecureURLB,
- kInsecureOriginA},
- {kReferrerPolicySameOrigin, kInsecureURLA, kInsecureURLB, nullptr},
- {kReferrerPolicyStrictOrigin, kInsecureURLA, kInsecureURLB,
- kInsecureOriginA},
- {kReferrerPolicyStrictOriginWhenCrossOrigin, kInsecureURLA, kInsecureURLB,
+ {network::mojom::ReferrerPolicy::kDefault, kInsecureURLA, kInsecureURLB,
+ kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, kInsecureURLA,
+ kInsecureURLB, kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kNever, kInsecureURLA, kInsecureURLB,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kOrigin, kInsecureURLA, kInsecureURLB,
kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, kInsecureURLA,
+ kInsecureURLB, kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::kSameOrigin, kInsecureURLA,
+ kInsecureURLB, nullptr},
+ {network::mojom::ReferrerPolicy::kStrictOrigin, kInsecureURLA,
+ kInsecureURLB, kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ kInsecureURLA, kInsecureURLB, kInsecureOriginA},
// HTTPS -> HTTPS: Same Origin
- {kReferrerPolicyAlways, kSecureURLA, kSecureURLA, kSecureURLA},
- {kReferrerPolicyDefault, kSecureURLA, kSecureURLA, kSecureURLA},
- {kReferrerPolicyNoReferrerWhenDowngrade, kSecureURLA, kSecureURLA,
+ {network::mojom::ReferrerPolicy::kAlways, kSecureURLA, kSecureURLA,
kSecureURLA},
- {kReferrerPolicyNever, kSecureURLA, kSecureURLA, nullptr},
- {kReferrerPolicyOrigin, kSecureURLA, kSecureURLA, kSecureOriginA},
- {kReferrerPolicyOriginWhenCrossOrigin, kSecureURLA, kSecureURLA,
+ {network::mojom::ReferrerPolicy::kDefault, kSecureURLA, kSecureURLA,
kSecureURLA},
- {kReferrerPolicySameOrigin, kSecureURLA, kSecureURLA, kSecureURLA},
- {kReferrerPolicyStrictOrigin, kSecureURLA, kSecureURLA, kSecureOriginA},
- {kReferrerPolicyStrictOriginWhenCrossOrigin, kSecureURLA, kSecureURLA,
+ {network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, kSecureURLA,
+ kSecureURLA, kSecureURLA},
+ {network::mojom::ReferrerPolicy::kNever, kSecureURLA, kSecureURLA,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kOrigin, kSecureURLA, kSecureURLA,
+ kSecureOriginA},
+ {network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, kSecureURLA,
+ kSecureURLA, kSecureURLA},
+ {network::mojom::ReferrerPolicy::kSameOrigin, kSecureURLA, kSecureURLA,
kSecureURLA},
+ {network::mojom::ReferrerPolicy::kStrictOrigin, kSecureURLA, kSecureURLA,
+ kSecureOriginA},
+ {network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ kSecureURLA, kSecureURLA, kSecureURLA},
// HTTPS -> HTTPS: Cross Origin
- {kReferrerPolicyAlways, kSecureURLA, kSecureURLB, kSecureURLA},
- {kReferrerPolicyDefault, kSecureURLA, kSecureURLB, kSecureURLA},
- {kReferrerPolicyNoReferrerWhenDowngrade, kSecureURLA, kSecureURLB,
+ {network::mojom::ReferrerPolicy::kAlways, kSecureURLA, kSecureURLB,
kSecureURLA},
- {kReferrerPolicyNever, kSecureURLA, kSecureURLB, nullptr},
- {kReferrerPolicyOrigin, kSecureURLA, kSecureURLB, kSecureOriginA},
- {kReferrerPolicyOriginWhenCrossOrigin, kSecureURLA, kSecureURLB,
+ {network::mojom::ReferrerPolicy::kDefault, kSecureURLA, kSecureURLB,
+ kSecureURLA},
+ {network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, kSecureURLA,
+ kSecureURLB, kSecureURLA},
+ {network::mojom::ReferrerPolicy::kNever, kSecureURLA, kSecureURLB,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kOrigin, kSecureURLA, kSecureURLB,
kSecureOriginA},
- {kReferrerPolicySameOrigin, kSecureURLA, kSecureURLB, nullptr},
- {kReferrerPolicyStrictOrigin, kSecureURLA, kSecureURLB, kSecureOriginA},
- {kReferrerPolicyStrictOriginWhenCrossOrigin, kSecureURLA, kSecureURLB,
+ {network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, kSecureURLA,
+ kSecureURLB, kSecureOriginA},
+ {network::mojom::ReferrerPolicy::kSameOrigin, kSecureURLA, kSecureURLB,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kStrictOrigin, kSecureURLA, kSecureURLB,
kSecureOriginA},
+ {network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ kSecureURLA, kSecureURLB, kSecureOriginA},
// HTTP -> HTTPS
- {kReferrerPolicyAlways, kInsecureURLA, kSecureURLB, kInsecureURLA},
- {kReferrerPolicyDefault, kInsecureURLA, kSecureURLB, kInsecureURLA},
- {kReferrerPolicyNoReferrerWhenDowngrade, kInsecureURLA, kSecureURLB,
+ {network::mojom::ReferrerPolicy::kAlways, kInsecureURLA, kSecureURLB,
kInsecureURLA},
- {kReferrerPolicyNever, kInsecureURLA, kSecureURLB, nullptr},
- {kReferrerPolicyOrigin, kInsecureURLA, kSecureURLB, kInsecureOriginA},
- {kReferrerPolicyOriginWhenCrossOrigin, kInsecureURLA, kSecureURLB,
- kInsecureOriginA},
- {kReferrerPolicySameOrigin, kInsecureURLA, kSecureURLB, nullptr},
- {kReferrerPolicyStrictOrigin, kInsecureURLA, kSecureURLB,
- kInsecureOriginA},
- {kReferrerPolicyStrictOriginWhenCrossOrigin, kInsecureURLA, kSecureURLB,
+ {network::mojom::ReferrerPolicy::kDefault, kInsecureURLA, kSecureURLB,
+ kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, kInsecureURLA,
+ kSecureURLB, kInsecureURLA},
+ {network::mojom::ReferrerPolicy::kNever, kInsecureURLA, kSecureURLB,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kOrigin, kInsecureURLA, kSecureURLB,
kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, kInsecureURLA,
+ kSecureURLB, kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::kSameOrigin, kInsecureURLA, kSecureURLB,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kStrictOrigin, kInsecureURLA,
+ kSecureURLB, kInsecureOriginA},
+ {network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ kInsecureURLA, kSecureURLB, kInsecureOriginA},
// HTTPS -> HTTP
- {kReferrerPolicyAlways, kSecureURLA, kInsecureURLB, kSecureURLA},
- {kReferrerPolicyDefault, kSecureURLA, kInsecureURLB, nullptr},
- {kReferrerPolicyNoReferrerWhenDowngrade, kSecureURLA, kInsecureURLB,
+ {network::mojom::ReferrerPolicy::kAlways, kSecureURLA, kInsecureURLB,
+ kSecureURLA},
+ {network::mojom::ReferrerPolicy::kDefault, kSecureURLA, kInsecureURLB,
nullptr},
- {kReferrerPolicyNever, kSecureURLA, kInsecureURLB, nullptr},
- {kReferrerPolicyOrigin, kSecureURLA, kInsecureURLB, kSecureOriginA},
- {kReferrerPolicyOriginWhenCrossOrigin, kSecureURLA, kSecureURLB,
+ {network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade, kSecureURLA,
+ kInsecureURLB, nullptr},
+ {network::mojom::ReferrerPolicy::kNever, kSecureURLA, kInsecureURLB,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kOrigin, kSecureURLA, kInsecureURLB,
kSecureOriginA},
- {kReferrerPolicySameOrigin, kSecureURLA, kInsecureURLB, nullptr},
- {kReferrerPolicyStrictOrigin, kSecureURLA, kInsecureURLB, nullptr},
- {kReferrerPolicyStrictOriginWhenCrossOrigin, kSecureURLA, kInsecureURLB,
+ {network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin, kSecureURLA,
+ kSecureURLB, kSecureOriginA},
+ {network::mojom::ReferrerPolicy::kSameOrigin, kSecureURLA, kInsecureURLB,
nullptr},
+ {network::mojom::ReferrerPolicy::kStrictOrigin, kSecureURLA,
+ kInsecureURLB, nullptr},
+ {network::mojom::ReferrerPolicy::
+ kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+ kSecureURLA, kInsecureURLB, nullptr},
// blob and filesystem URL handling
- {kReferrerPolicyAlways, kInsecureURLA, kBlobURL, nullptr},
- {kReferrerPolicyAlways, kBlobURL, kInsecureURLA, nullptr},
- {kReferrerPolicyAlways, kInsecureURLA, kFilesystemURL, nullptr},
- {kReferrerPolicyAlways, kFilesystemURL, kInsecureURLA, nullptr},
+ {network::mojom::ReferrerPolicy::kAlways, kInsecureURLA, kBlobURL,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kAlways, kBlobURL, kInsecureURLA,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kAlways, kInsecureURLA, kFilesystemURL,
+ nullptr},
+ {network::mojom::ReferrerPolicy::kAlways, kFilesystemURL, kInsecureURLA,
+ nullptr},
};
for (TestCase test : inputs) {
@@ -203,8 +249,8 @@ TEST(SecurityPolicyTest, GenerateReferrer) {
<< "' should have been empty: was '" << result.referrer.Utf8().data()
<< "'.";
}
- EXPECT_EQ(test.policy == kReferrerPolicyDefault
- ? kReferrerPolicyNoReferrerWhenDowngrade
+ EXPECT_EQ(test.policy == network::mojom::ReferrerPolicy::kDefault
+ ? network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade
: test.policy,
result.referrer_policy);
}
@@ -215,28 +261,29 @@ TEST(SecurityPolicyTest, ReferrerPolicyFromHeaderValue) {
const char* header;
bool is_valid;
ReferrerPolicyLegacyKeywordsSupport keywords;
- ReferrerPolicy expected_policy;
+ network::mojom::ReferrerPolicy expected_policy;
};
TestCase inputs[] = {
{"origin", true, kDoNotSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyOrigin},
+ network::mojom::ReferrerPolicy::kOrigin},
{"none", true, kSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyNever},
+ network::mojom::ReferrerPolicy::kNever},
{"none", false, kDoNotSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyDefault},
+ network::mojom::ReferrerPolicy::kDefault},
{"foo", false, kDoNotSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyDefault},
+ network::mojom::ReferrerPolicy::kDefault},
{"origin, foo", true, kDoNotSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyOrigin},
+ network::mojom::ReferrerPolicy::kOrigin},
{"origin, foo-bar", true, kDoNotSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyOrigin},
+ network::mojom::ReferrerPolicy::kOrigin},
{"origin, foo bar", false, kDoNotSupportReferrerPolicyLegacyKeywords,
- kReferrerPolicyDefault},
+ network::mojom::ReferrerPolicy::kDefault},
};
for (TestCase test : inputs) {
- ReferrerPolicy actual_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy actual_policy =
+ network::mojom::ReferrerPolicy::kDefault;
EXPECT_EQ(test.is_valid, SecurityPolicy::ReferrerPolicyFromHeaderValue(
test.header, test.keywords, &actual_policy));
if (test.is_valid)
@@ -306,10 +353,7 @@ class SecurityPolicyAccessTest : public testing::Test {
SecurityOrigin::CreateFromString("https://google.com");
}
- void TearDown() override {
- SecurityPolicy::ClearOriginAccessAllowList();
- SecurityPolicy::ClearOriginAccessBlockList();
- }
+ void TearDown() override { SecurityPolicy::ClearOriginAccessList(); }
const SecurityOrigin* https_example_origin() const {
return https_example_origin_.get();
@@ -352,7 +396,7 @@ TEST_F(SecurityPolicyAccessTest, IsOriginAccessAllowed) {
// access to subdomains or other schemes.
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "example.com", false,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
EXPECT_FALSE(SecurityPolicy::IsOriginAccessAllowed(
@@ -361,7 +405,7 @@ TEST_F(SecurityPolicyAccessTest, IsOriginAccessAllowed) {
http_example_origin()));
// Clearing the map should revoke all special access.
- SecurityPolicy::ClearOriginAccessAllowList();
+ SecurityPolicy::ClearOriginAccessList();
EXPECT_FALSE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
EXPECT_FALSE(SecurityPolicy::IsOriginAccessAllowed(
@@ -373,7 +417,7 @@ TEST_F(SecurityPolicyAccessTest, IsOriginAccessAllowed) {
// subdomains.
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(
@@ -386,7 +430,7 @@ TEST_F(SecurityPolicyAccessTest, IsOriginAccessAllowedWildCard) {
// An empty domain that matches subdomains results in matching every domain.
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
@@ -399,10 +443,10 @@ TEST_F(SecurityPolicyAccessTest, IsOriginAccessAllowedWithBlockListEntry) {
// The block list takes priority over the allow list.
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
SecurityPolicy::AddOriginAccessBlockListEntry(
*https_chromium_origin(), "https", "example.com", false,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
EXPECT_FALSE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
@@ -414,10 +458,10 @@ TEST_F(SecurityPolicyAccessTest,
IsOriginAccessAllowedWildcardWithBlockListEntry) {
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
SecurityPolicy::AddOriginAccessBlockListEntry(
*https_chromium_origin(), "https", "google.com", false,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
@@ -425,18 +469,18 @@ TEST_F(SecurityPolicyAccessTest,
https_google_origin()));
}
-TEST_F(SecurityPolicyAccessTest, ClearOriginAccessAllowListForOrigin) {
+TEST_F(SecurityPolicyAccessTest, ClearOriginAccessListForOrigin) {
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "google.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_example_origin(), "https", "google.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kDefaultPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority);
- SecurityPolicy::ClearOriginAccessAllowListForOrigin(*https_chromium_origin());
+ SecurityPolicy::ClearOriginAccessListForOrigin(*https_chromium_origin());
EXPECT_FALSE(SecurityPolicy::IsOriginAccessAllowed(https_chromium_origin(),
https_example_origin()));
@@ -451,17 +495,17 @@ TEST_F(SecurityPolicyAccessTest, IsOriginAccessAllowedPriority) {
https_chromium_origin(), https_sub_example_origin()));
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "sub.example.com", false,
- network::mojom::CORSOriginAccessMatchPriority::kLowPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kLowPriority);
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(
https_chromium_origin(), https_sub_example_origin()));
SecurityPolicy::AddOriginAccessBlockListEntry(
*https_chromium_origin(), "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kMediumPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kMediumPriority);
EXPECT_FALSE(SecurityPolicy::IsOriginAccessAllowed(
https_chromium_origin(), https_sub_example_origin()));
SecurityPolicy::AddOriginAccessAllowListEntry(
*https_chromium_origin(), "https", "example.com", true,
- network::mojom::CORSOriginAccessMatchPriority::kHighPriority);
+ network::mojom::CorsOriginAccessMatchPriority::kHighPriority);
EXPECT_TRUE(SecurityPolicy::IsOriginAccessAllowed(
https_chromium_origin(), https_sub_example_origin()));
diff --git a/chromium/third_party/blink/renderer/platform/wtf/BUILD.gn b/chromium/third_party/blink/renderer/platform/wtf/BUILD.gn
index 39eff107944..108a748ab72 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/BUILD.gn
+++ b/chromium/third_party/blink/renderer/platform/wtf/BUILD.gn
@@ -45,7 +45,6 @@ config("wtf_config") {
jumbo_component("wtf") {
sources = [
"address_sanitizer.h",
- "alignment.h",
"allocator.cc",
"allocator.h",
"allocator/partition_allocator.cc",
@@ -167,7 +166,6 @@ jumbo_component("wtf") {
"text/string_operators.h",
"text/string_statics.cc",
"text/string_statics.h",
- "text/string_statics.h",
"text/string_to_number.cc",
"text/string_to_number.h",
"text/string_utf8_adaptor.h",
diff --git a/chromium/third_party/blink/renderer/platform/wtf/alignment.h b/chromium/third_party/blink/renderer/platform/wtf/alignment.h
deleted file mode 100644
index f4d782f4f77..00000000000
--- a/chromium/third_party/blink/renderer/platform/wtf/alignment.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ALIGNMENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ALIGNMENT_H_
-
-#include <stdint.h>
-#include "build/build_config.h"
-
-namespace WTF {
-
-#if defined(COMPILER_GCC)
-#define WTF_ALIGN_OF(type) __alignof__(type)
-#define WTF_ALIGNED(variable_type, variable, n) \
- variable_type variable __attribute__((__aligned__(n)))
-#elif defined(COMPILER_MSVC)
-#define WTF_ALIGN_OF(type) __alignof(type)
-#define WTF_ALIGNED(variable_type, variable, n) \
- __declspec(align(n)) variable_type variable
-#else
-#error WTF_ALIGN macros need alignment control.
-#endif
-
-template <uintptr_t mask>
-inline bool IsAlignedTo(const void* pointer) {
- return !(reinterpret_cast<uintptr_t>(pointer) & mask);
-}
-
-} // namespace WTF
-
-#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_ALIGNMENT_H_
diff --git a/chromium/third_party/blink/renderer/platform/wtf/compiler.h b/chromium/third_party/blink/renderer/platform/wtf/compiler.h
index 40f79d40706..56843dac476 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/compiler.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/compiler.h
@@ -41,16 +41,6 @@
#endif
#endif
-/* WTF_PRETTY_FUNCTION */
-
-#if defined(COMPILER_GCC)
-#define WTF_PRETTY_FUNCTION __PRETTY_FUNCTION__
-#elif defined(COMPILER_MSVC)
-#define WTF_PRETTY_FUNCTION __FUNCSIG__
-#else
-#define WTF_PRETTY_FUNCTION __func__
-#endif
-
/* NO_SANITIZE_UNRELATED_CAST - Disable runtime checks related to casts between
* unrelated objects (-fsanitize=cfi-unrelated-cast or -fsanitize=vptr). */
diff --git a/chromium/third_party/blink/renderer/platform/wtf/date_math.cc b/chromium/third_party/blink/renderer/platform/wtf/date_math.cc
index a7f3e3e8c80..456098a9672 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/date_math.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/date_math.cc
@@ -87,6 +87,7 @@
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
+#include <unicode/basictz.h>
#include <unicode/timezone.h>
#if defined(OS_WIN)
@@ -100,9 +101,7 @@ namespace WTF {
/* Constants */
static const double kHoursPerDay = 24.0;
-static const double kSecondsPerDay = 24.0 * 60.0 * 60.0;
-static const double kMaxUnixTime = 2145859200.0; // 12/31/2037
static const double kMinimumECMADateInMs = -8640000000000000.0;
static const double kMaximumECMADateInMs = 8640000000000000.0;
@@ -112,14 +111,6 @@ static const int kFirstDayOfMonth[2][12] = {
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}};
-static inline void GetLocalTime(const time_t* local_time, struct tm* local_tm) {
-#if defined(COMPILER_MSVC)
- localtime_s(local_tm, local_time);
-#else
- localtime_r(local_time, local_tm);
-#endif
-}
-
bool IsLeapYear(int year) {
if (year % 4 != 0)
return false;
@@ -188,13 +179,6 @@ int DayInYear(double ms, int year) {
return static_cast<int>(MsToDays(ms) - DaysFrom1970ToYear(year));
}
-static inline double MsToMilliseconds(double ms) {
- double result = fmod(ms, kMsPerDay);
- if (result < 0)
- result += kMsPerDay;
- return result;
-}
-
int MonthFromDayInYear(int day_in_year, bool leap_year) {
const int d = day_in_year;
int step;
@@ -284,129 +268,6 @@ double DateToDaysFrom1970(int year, int month, int day) {
return yearday + DayInYear(year, month, day);
}
-// There is a hard limit at 2038 that we currently do not have a workaround
-// for (rdar://problem/5052975).
-static inline int MaximumYearForDST() {
- return 2037;
-}
-
-static inline double JsCurrentTime() {
- // JavaScript doesn't recognize fractions of a millisecond.
- return floor(WTF::CurrentTimeMS());
-}
-
-static inline int MinimumYearForDST() {
- // Because of the 2038 issue (see maximumYearForDST) if the current year is
- // greater than the max year minus 27 (2010), we want to use the max year
- // minus 27 instead, to ensure there is a range of 28 years that all years
- // can map to.
- return std::min(MsToYear(JsCurrentTime()), MaximumYearForDST() - 27);
-}
-
-// Find an equivalent year for the one given, where equivalence is deterined by
-// the two years having the same leapness and the first day of the year, falling
-// on the same day of the week.
-//
-// This function returns a year between this current year and 2037, however this
-// function will potentially return incorrect results if the current year is
-// after 2010, (rdar://problem/5052975), if the year passed in is before 1900
-// or after 2100, (rdar://problem/5055038).
-static int EquivalentYearForDST(int year) {
- // It is ok if the cached year is not the current year as long as the rules
- // for DST did not change between the two years; if they did the app would
- // need to be restarted.
- static int min_year = MinimumYearForDST();
- int max_year = MaximumYearForDST();
-
- int difference;
- if (year > max_year)
- difference = min_year - year;
- else if (year < min_year)
- difference = max_year - year;
- else
- return year;
-
- int quotient = difference / 28;
- int product = (quotient)*28;
-
- year += product;
- DCHECK((year >= min_year && year <= max_year) ||
- (product - year ==
- static_cast<int>(std::numeric_limits<double>::quiet_NaN())));
- return year;
-}
-
-static double CalculateUTCOffset() {
-#if defined(OS_WIN)
- TIME_ZONE_INFORMATION time_zone_information;
- GetTimeZoneInformation(&time_zone_information);
- int32_t bias =
- time_zone_information.Bias + time_zone_information.StandardBias;
- return -bias * 60 * 1000;
-#else
- time_t local_time = time(nullptr);
- tm localt;
- GetLocalTime(&local_time, &localt);
-
- // tm_gmtoff includes any daylight savings offset, so subtract it.
- return static_cast<double>(localt.tm_gmtoff * kMsPerSecond -
- (localt.tm_isdst > 0 ? kMsPerHour : 0));
-#endif
-}
-
-/*
- * Get the DST offset for the time passed in.
- */
-static double CalculateDSTOffsetSimple(double local_time_seconds,
- double utc_offset) {
- if (local_time_seconds > kMaxUnixTime)
- local_time_seconds = kMaxUnixTime;
- else if (local_time_seconds <
- 0) // Go ahead a day to make localtime work (does not work with 0)
- local_time_seconds += kSecondsPerDay;
-
- // FIXME: time_t has a potential problem in 2038
- time_t local_time = static_cast<time_t>(local_time_seconds);
-
- tm local_tm;
- GetLocalTime(&local_time, &local_tm);
-
- return local_tm.tm_isdst > 0 ? kMsPerHour : 0;
-}
-
-// Get the DST offset, given a time in UTC
-static double CalculateDSTOffset(double ms, double utc_offset) {
- // On macOS, the call to localtime (see calculateDSTOffsetSimple) will return
- // historically accurate DST information (e.g. New Zealand did not have DST
- // from 1946 to 1974) however the JavaScript standard explicitly dictates
- // that historical information should not be considered when determining DST.
- // For this reason we shift away from years that localtime can handle but
- // would return historically accurate information.
- int year = MsToYear(ms);
- int equivalent_year = EquivalentYearForDST(year);
- if (year != equivalent_year) {
- bool leap_year = IsLeapYear(year);
- int day_in_year_local = DayInYear(ms, year);
- int day_in_month = DayInMonthFromDayInYear(day_in_year_local, leap_year);
- int month = MonthFromDayInYear(day_in_year_local, leap_year);
- double day = DateToDaysFrom1970(equivalent_year, month, day_in_month);
- ms = (day * kMsPerDay) + MsToMilliseconds(ms);
- }
-
- return CalculateDSTOffsetSimple(ms / kMsPerSecond, utc_offset);
-}
-
-void InitializeDates() {
-#if DCHECK_IS_ON()
- static bool already_initialized;
- DCHECK(!already_initialized);
- already_initialized = true;
-#endif
-
- EquivalentYearForDST(
- 2000); // Need to call once to initialize a static used in this function.
-}
-
static inline double YmdhmsToSeconds(int year,
long mon,
long day,
@@ -799,9 +660,19 @@ double ParseDateFromNullTerminatedCharacters(const char* date_string) {
// fall back to local timezone
if (!have_tz) {
- double utc_offset = CalculateUTCOffset();
- double dst_offset = CalculateDSTOffset(ms, utc_offset);
- offset = static_cast<int>((utc_offset + dst_offset) / kMsPerMinute);
+ std::unique_ptr<icu::TimeZone> timezone(icu::TimeZone::createDefault());
+ int32_t raw_offset, dst_offset;
+ UErrorCode status = U_ZERO_ERROR;
+ // Handle the conversion of localtime to UTC the same way as the
+ // latest ECMA 262 spec for Javascript (v8 does that, too).
+ // TODO(jshin): Once http://bugs.icu-project.org/trac/ticket/13705
+ // is fixed, no casting would be necessary.
+ static_cast<const icu::BasicTimeZone*>(timezone.get())
+ ->getOffsetFromLocal(ms, icu::BasicTimeZone::kFormer,
+ icu::BasicTimeZone::kFormer, raw_offset,
+ dst_offset, status);
+ DCHECK(U_SUCCESS(status));
+ offset = static_cast<int>((raw_offset + dst_offset) / kMsPerMinute);
}
return ms - (offset * kMsPerMinute);
}
@@ -842,6 +713,7 @@ double ConvertToLocalTime(double ms) {
int32_t raw_offset, dst_offset;
UErrorCode status = U_ZERO_ERROR;
timezone->getOffset(ms, false, raw_offset, dst_offset, status);
+ DCHECK(U_SUCCESS(status));
return (ms + static_cast<double>(raw_offset + dst_offset));
}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/date_math.h b/chromium/third_party/blink/renderer/platform/wtf/date_math.h
index a7550acc1a3..069a557a87e 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/date_math.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/date_math.h
@@ -51,8 +51,6 @@
namespace WTF {
-WTF_EXPORT void InitializeDates();
-
// Not really math related, but this is currently the only shared place to put
// these.
WTF_EXPORT double ParseDateFromNullTerminatedCharacters(
diff --git a/chromium/third_party/blink/renderer/platform/wtf/decimal.cc b/chromium/third_party/blink/renderer/platform/wtf/decimal.cc
index 5dcc3b8d7a4..91d797e4409 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/decimal.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/decimal.cc
@@ -40,7 +40,7 @@
namespace blink {
-namespace DecimalPrivate {
+namespace decimal_private {
static int const kExponentMax = 1023;
static int const kExponentMin = -1023;
@@ -229,9 +229,9 @@ static uint64_t ScaleUp(uint64_t x, int n) {
}
}
-} // namespace DecimalPrivate
+} // namespace decimal_private
-using namespace DecimalPrivate;
+using namespace decimal_private;
Decimal::EncodedData::EncodedData(Sign sign, FormatClass format_class)
: coefficient_(0), exponent_(0), format_class_(format_class), sign_(sign) {}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/decimal.h b/chromium/third_party/blink/renderer/platform/wtf/decimal.h
index 48665c85c15..53e58074d04 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/decimal.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/decimal.h
@@ -39,7 +39,7 @@
namespace blink {
-namespace DecimalPrivate {
+namespace decimal_private {
class SpecialValueHandler;
}
@@ -63,7 +63,7 @@ class WTF_EXPORT Decimal {
DISALLOW_NEW();
// For accessing FormatClass.
friend class Decimal;
- friend class DecimalPrivate::SpecialValueHandler;
+ friend class decimal_private::SpecialValueHandler;
public:
EncodedData(Sign, int exponent, uint64_t coefficient);
diff --git a/chromium/third_party/blink/renderer/platform/wtf/decimal_test.cc b/chromium/third_party/blink/renderer/platform/wtf/decimal_test.cc
index da5330e0707..f1b83a8f3de 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/decimal_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/decimal_test.cc
@@ -899,7 +899,7 @@ TEST_F(DecimalTest, PredicatesSpecialValues) {
EXPECT_FALSE(Decimal::Nan().IsZero());
}
-// LayoutTests/fast/forms/number/number-stepup-stepdown-from-renderer
+// web_tests/fast/forms/number/number-stepup-stepdown-from-renderer
TEST_F(DecimalTest, RealWorldExampleNumberStepUpStepDownFromRenderer) {
EXPECT_DECIMAL_STREQ("10", StepDown("0", "100", "10", "19", 1));
EXPECT_DECIMAL_STREQ("90", StepUp("0", "99", "10", "89", 1));
diff --git a/chromium/third_party/blink/renderer/platform/wtf/dtoa.cc b/chromium/third_party/blink/renderer/platform/wtf/dtoa.cc
index dd87639d351..25ea1e60302 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/dtoa.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/dtoa.cc
@@ -131,7 +131,7 @@ const char* NumberToFixedWidthString(double d,
return builder.Finalize();
}
-namespace Internal {
+namespace internal {
double ParseDoubleFromLongString(const UChar* string,
size_t length,
@@ -143,6 +143,6 @@ double ParseDoubleFromLongString(const UChar* string,
return ParseDouble(conversion_buffer.data(), length, parsed_length);
}
-} // namespace Internal
+} // namespace internal
} // namespace WTF
diff --git a/chromium/third_party/blink/renderer/platform/wtf/dtoa.h b/chromium/third_party/blink/renderer/platform/wtf/dtoa.h
index e618ed3e68e..86bec2ed38d 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/dtoa.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/dtoa.h
@@ -49,7 +49,7 @@ WTF_EXPORT double ParseDouble(const UChar* string,
size_t length,
size_t& parsed_length);
-namespace Internal {
+namespace internal {
double ParseDoubleFromLongString(const UChar* string,
size_t length,
size_t& parsed_length);
@@ -67,7 +67,7 @@ inline double ParseDouble(const UChar* string,
size_t& parsed_length) {
const size_t kConversionBufferSize = 64;
if (length > kConversionBufferSize)
- return Internal::ParseDoubleFromLongString(string, length, parsed_length);
+ return internal::ParseDoubleFromLongString(string, length, parsed_length);
LChar conversion_buffer[kConversionBufferSize];
for (size_t i = 0; i < length; ++i)
conversion_buffer[i] =
diff --git a/chromium/third_party/blink/renderer/platform/wtf/hash_table.cc b/chromium/third_party/blink/renderer/platform/wtf/hash_table.cc
index c191d951ba1..dce719be4e2 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/hash_table.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/hash_table.cc
@@ -37,10 +37,10 @@ HashTableStats& HashTableStats::instance() {
}
void HashTableStats::copy(const HashTableStats* other) {
- numAccesses = other->numAccesses;
- numRehashes = other->numRehashes;
- numRemoves = other->numRemoves;
- numReinserts = other->numReinserts;
+ numAccesses = other->numAccesses.load(std::memory_order_relaxed);
+ numRehashes = other->numRehashes.load(std::memory_order_relaxed);
+ numRemoves = other->numRemoves.load(std::memory_order_relaxed);
+ numReinserts = other->numReinserts.load(std::memory_order_relaxed);
maxCollisions = other->maxCollisions;
numCollisions = other->numCollisions;
diff --git a/chromium/third_party/blink/renderer/platform/wtf/hash_table.h b/chromium/third_party/blink/renderer/platform/wtf/hash_table.h
index a760b6b5e9f..f99180d2e25 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/hash_table.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/hash_table.h
@@ -26,7 +26,6 @@
#include <memory>
#include "base/numerics/checked_math.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -42,7 +41,7 @@
#endif
#if DUMP_HASHTABLE_STATS
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
+#include <atomic>
#include "third_party/blink/renderer/platform/wtf/threading.h"
#endif
@@ -59,17 +58,19 @@
HashTableStats::instance().recordCollisionAtCount(probeCount); \
++perTableProbeCount; \
stats_->recordCollisionAtCount(perTableProbeCount)
-#define UPDATE_ACCESS_COUNTS() \
- AtomicIncrement(&HashTableStats::instance().numAccesses); \
- int probeCount = 0; \
- ++stats_->numAccesses; \
+#define UPDATE_ACCESS_COUNTS() \
+ HashTableStats::instance().numAccesses.fetch_add(1, \
+ std::memory_order_relaxed); \
+ int probeCount = 0; \
+ stats_->numAccesses.fetch_add(1, std::memory_order_relaxed); \
int perTableProbeCount = 0
#else
#define UPDATE_PROBE_COUNTS() \
++probeCount; \
HashTableStats::instance().recordCollisionAtCount(probeCount)
-#define UPDATE_ACCESS_COUNTS() \
- AtomicIncrement(&HashTableStats::instance().numAccesses); \
+#define UPDATE_ACCESS_COUNTS() \
+ HashTableStats::instance().numAccesses.fetch_add(1, \
+ std::memory_order_relaxed); \
int probeCount = 0
#endif
#else
@@ -77,8 +78,8 @@
#define UPDATE_PROBE_COUNTS() \
++perTableProbeCount; \
stats_->recordCollisionAtCount(perTableProbeCount)
-#define UPDATE_ACCESS_COUNTS() \
- ++stats_->numAccesses; \
+#define UPDATE_ACCESS_COUNTS() \
+ stats_->numAccesses.fetch_add(1, std::memory_order_relaxed); \
int perTableProbeCount = 0
#else
#define UPDATE_PROBE_COUNTS() \
@@ -117,10 +118,10 @@ struct WTF_EXPORT HashTableStats {
collisionGraph() {}
// The following variables are all atomically incremented when modified.
- int numAccesses;
- int numRehashes;
- int numRemoves;
- int numReinserts;
+ std::atomic_int numAccesses;
+ std::atomic_int numRehashes;
+ std::atomic_int numRemoves;
+ std::atomic_int numReinserts;
// The following variables are only modified in the recordCollisionAtCount
// method within a mutex.
@@ -1441,10 +1442,11 @@ HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::
DCHECK(
!IsDeletedBucket(*(LookupForWriting(Extractor::Extract(entry)).first)));
#if DUMP_HASHTABLE_STATS
- AtomicIncrement(&HashTableStats::instance().numReinserts);
+ HashTableStats::instance().numReinserts.fetch_add(1,
+ std::memory_order_relaxed);
#endif
#if DUMP_HASHTABLE_STATS_PER_TABLE
- ++stats_->numReinserts;
+ stats_->numReinserts.fetch_add(1, std::memory_order_relaxed);
#endif
Value* new_entry = LookupForWriting(Extractor::Extract(entry)).first;
Mover<ValueType, Allocator, Traits,
@@ -1536,10 +1538,10 @@ void HashTable<Key,
Allocator>::erase(const ValueType* pos) {
RegisterModification();
#if DUMP_HASHTABLE_STATS
- AtomicIncrement(&HashTableStats::instance().numRemoves);
+ HashTableStats::instance().numRemoves.fetch_add(1, std::memory_order_relaxed);
#endif
#if DUMP_HASHTABLE_STATS_PER_TABLE
- ++stats_->numRemoves;
+ stats_->numRemoves.fetch_add(1, std::memory_order_relaxed);
#endif
EnterAccessForbiddenScope();
@@ -1651,7 +1653,7 @@ void HashTable<Key,
KeyTraits,
Allocator>::DeleteAllBucketsAndDeallocate(ValueType* table,
unsigned size) {
- if (!IsTriviallyDestructible<ValueType>::value) {
+ if (!std::is_trivially_destructible<ValueType>::value) {
for (unsigned i = 0; i < size; ++i) {
// This code is called when the hash table is cleared or resized. We
// have allocated a new backing store and we need to run the
@@ -1769,13 +1771,15 @@ HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::
ValueType* old_table = table_;
#if DUMP_HASHTABLE_STATS
- if (old_table_size != 0)
- AtomicIncrement(&HashTableStats::instance().numRehashes);
+ if (old_table_size != 0) {
+ HashTableStats::instance().numRehashes.fetch_add(1,
+ std::memory_order_relaxed);
+ }
#endif
#if DUMP_HASHTABLE_STATS_PER_TABLE
if (old_table_size != 0)
- ++stats_->numRehashes;
+ stats_->numRehashes.fetch_add(1, std::memory_order_relaxed);
#endif
table_ = new_table;
@@ -1823,13 +1827,15 @@ HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::
ValueType* old_table = table_;
#if DUMP_HASHTABLE_STATS
- if (old_table_size != 0)
- AtomicIncrement(&HashTableStats::instance().numRehashes);
+ if (old_table_size != 0) {
+ HashTableStats::instance().numRehashes.fetch_add(1,
+ std::memory_order_relaxed);
+ }
#endif
#if DUMP_HASHTABLE_STATS_PER_TABLE
if (old_table_size != 0)
- ++stats_->numRehashes;
+ stats_->numRehashes.fetch_add(1, std::memory_order_relaxed);
#endif
// The Allocator::kIsGarbageCollected check is not needed. The check is just
diff --git a/chromium/third_party/blink/renderer/platform/wtf/hex_number.h b/chromium/third_party/blink/renderer/platform/wtf/hex_number.h
index 06f038c7c16..26a14621ff6 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/hex_number.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/hex_number.h
@@ -24,12 +24,12 @@
namespace WTF {
-namespace Internal {
+namespace internal {
const LChar kLowerHexDigits[17] = "0123456789abcdef";
const LChar kUpperHexDigits[17] = "0123456789ABCDEF";
-} // namespace Internal
+} // namespace internal
class HexNumber final {
STATIC_ONLY(HexNumber);
@@ -99,8 +99,8 @@ class HexNumber final {
private:
static inline const LChar* HexDigitsForMode(HexConversionMode mode) {
- return mode == kLowercase ? Internal::kLowerHexDigits
- : Internal::kUpperHexDigits;
+ return mode == kLowercase ? internal::kLowerHexDigits
+ : internal::kUpperHexDigits;
}
};
diff --git a/chromium/third_party/blink/renderer/platform/wtf/list_hash_set.h b/chromium/third_party/blink/renderer/platform/wtf/list_hash_set.h
index ce913652bbb..4c93a04da20 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/list_hash_set.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/list_hash_set.h
@@ -416,7 +416,7 @@ class ListHashSetNode : public ListHashSetNodeBase<ValueArg> {
void SetWasAlreadyDestructed() {
if (NodeAllocator::kIsGarbageCollected &&
- !IsTriviallyDestructible<ValueArg>::value)
+ !std::is_trivially_destructible<ValueArg>::value)
this->prev_ = UnlinkedNodePointer();
}
@@ -427,7 +427,9 @@ class ListHashSetNode : public ListHashSetNodeBase<ValueArg> {
static void Finalize(void* pointer) {
// No need to waste time calling finalize if it's not needed.
- DCHECK(!IsTriviallyDestructible<ValueArg>::value);
+ static_assert(
+ !std::is_trivially_destructible<ValueArg>::value,
+ "Finalization of trivially destructible classes should not happen.");
ListHashSetNode* self = reinterpret_cast_ptr<ListHashSetNode*>(pointer);
// Check whether this node was already destructed before being unlinked
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_arena.h b/chromium/third_party/blink/renderer/platform/wtf/pod_arena.h
index 173c979e4e2..9fd55e85c59 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_arena.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_arena.h
@@ -115,17 +115,13 @@ class PODArena final : public RefCounted<PODArena> {
current_(nullptr),
current_chunk_size_(kDefaultChunkSize) {}
- // Returns the alignment requirement for classes and structs on the
- // current platform.
- template <class T>
- static size_t MinAlignment() {
- return WTF_ALIGN_OF(T);
- }
-
template <class T>
void* AllocateBase() {
+ static_assert(
+ sizeof(T) % alignof(T) == 0,
+ "We are guaranteed that sizeof(T) is a multiple of alignof(T).");
void* ptr = nullptr;
- size_t rounded_size = RoundUp(sizeof(T), MinAlignment<T>());
+ size_t rounded_size = sizeof(T);
if (current_)
ptr = current_->Allocate(rounded_size);
@@ -140,12 +136,6 @@ class PODArena final : public RefCounted<PODArena> {
return ptr;
}
- // Rounds up the given allocation size to the specified alignment.
- size_t RoundUp(size_t size, size_t alignment) {
- DCHECK(!(alignment % 2));
- return (size + alignment - 1) & ~(alignment - 1);
- }
-
// Manages a chunk of memory and individual allocations out of it.
class Chunk final {
USING_FAST_MALLOC(Chunk);
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test.cc b/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test.cc
index a9c2d512bcb..24c29d7908d 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test.cc
@@ -32,7 +32,7 @@
namespace WTF {
-using ArenaTestHelpers::TrackedAllocator;
+using arena_test_helpers::TrackedAllocator;
namespace {
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test_helpers.h b/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test_helpers.h
index 09ed3f174a7..abe5a096db9 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_arena_test_helpers.h
@@ -33,7 +33,7 @@
#include <gtest/gtest.h>
namespace WTF {
-namespace ArenaTestHelpers {
+namespace arena_test_helpers {
// An allocator for the PODArena which tracks the regions which have
// been allocated.
@@ -65,7 +65,7 @@ class TrackedAllocator final : public PODArena::FastMallocAllocator {
Vector<void*> allocated_regions_;
};
-} // namespace ArenaTestHelpers
+} // namespace arena_test_helpers
} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_POD_ARENA_TEST_HELPERS_H_
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_free_list_arena_test.cc b/chromium/third_party/blink/renderer/platform/wtf/pod_free_list_arena_test.cc
index 94fc4a44c37..19efe4005b1 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_free_list_arena_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_free_list_arena_test.cc
@@ -32,7 +32,7 @@
namespace WTF {
-using ArenaTestHelpers::TrackedAllocator;
+using arena_test_helpers::TrackedAllocator;
namespace {
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_interval_tree_test.cc b/chromium/third_party/blink/renderer/platform/wtf/pod_interval_tree_test.cc
index 22cc18b7094..8b154587e2d 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_interval_tree_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_interval_tree_test.cc
@@ -34,8 +34,8 @@
namespace WTF {
-using TreeTestHelpers::InitRandom;
-using TreeTestHelpers::NextRandom;
+using tree_test_helpers::InitRandom;
+using tree_test_helpers::NextRandom;
#ifndef NDEBUG
template <>
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_red_black_tree_test.cc b/chromium/third_party/blink/renderer/platform/wtf/pod_red_black_tree_test.cc
index a583998181f..af831ed9306 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_red_black_tree_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_red_black_tree_test.cc
@@ -34,9 +34,9 @@
namespace WTF {
-using ArenaTestHelpers::TrackedAllocator;
-using TreeTestHelpers::InitRandom;
-using TreeTestHelpers::NextRandom;
+using arena_test_helpers::TrackedAllocator;
+using tree_test_helpers::InitRandom;
+using tree_test_helpers::NextRandom;
TEST(PODRedBlackTreeTest, TestTreeAllocatesFromArena) {
scoped_refptr<TrackedAllocator> allocator = TrackedAllocator::Create();
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.cc b/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.cc
index 0d96775b639..dc4d75a3f1b 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.cc
@@ -28,7 +28,7 @@
#include <cstdlib>
namespace WTF {
-namespace TreeTestHelpers {
+namespace tree_test_helpers {
void InitRandom(const int32_t seed) {
srand(seed);
@@ -39,5 +39,5 @@ int32_t NextRandom(const int32_t maximum_value) {
return rand() % maximum_value;
}
-} // namespace TreeTestHelpers
+} // namespace tree_test_helpers
} // namespace WTF
diff --git a/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.h b/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.h
index 1bf0fa6058d..c277731017e 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/pod_tree_test_helpers.h
@@ -34,7 +34,7 @@
#include <stdint.h>
namespace WTF {
-namespace TreeTestHelpers {
+namespace tree_test_helpers {
// Initializes the pseudo-random number generator with a specific seed.
void InitRandom(const int32_t seed);
@@ -44,7 +44,7 @@ void InitRandom(const int32_t seed);
// produce undefined results.
int32_t NextRandom(const int32_t maximum_value);
-} // namespace TreeTestHelpers
+} // namespace tree_test_helpers
} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_POD_TREE_TEST_HELPERS_H_
diff --git a/chromium/third_party/blink/renderer/platform/wtf/stack_util.cc b/chromium/third_party/blink/renderer/platform/wtf/stack_util.cc
index 21f49cf07a3..248f93968a6 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/stack_util.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/stack_util.cc
@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+#include "build/build_config.h"
+
#include "third_party/blink/renderer/platform/wtf/stack_util.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -133,10 +135,17 @@ void* GetStackStart() {
// On Windows stack limits for the current thread are available in
// the thread information block (TIB). Its fields can be accessed through
// FS segment register on x86 and GS segment register on x86_64.
-#ifdef _WIN64
+// On Windows ARM64, stack limits could be retrieved by calling
+// GetCurrentThreadStackLimits. This API doesn't work on x86 and x86_64 here
+// because it requires Windows 8+.
+#if defined(ARCH_CPU_X86_64)
return reinterpret_cast<void*>(__readgsqword(offsetof(NT_TIB64, StackBase)));
-#else
+#elif defined(ARCH_CPU_X86)
return reinterpret_cast<void*>(__readfsdword(offsetof(NT_TIB, StackBase)));
+#elif defined(ARCH_CPU_ARM64)
+ ULONG_PTR lowLimit, highLimit;
+ ::GetCurrentThreadStackLimits(&lowLimit, &highLimit);
+ return reinterpret_cast<void*>(highLimit);
#endif
#else
#error Unsupported getStackStart on this platform.
diff --git a/chromium/third_party/blink/renderer/platform/wtf/terminated_array_builder.h b/chromium/third_party/blink/renderer/platform/wtf/terminated_array_builder.h
index 9beb7a3745b..5ef3aa81d1a 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/terminated_array_builder.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/terminated_array_builder.h
@@ -10,6 +10,9 @@
namespace WTF {
+template <typename T>
+class TerminatedArray;
+
template <typename T, template <typename> class ArrayType = TerminatedArray>
class TerminatedArrayBuilder {
STACK_ALLOCATED();
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h b/chromium/third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h
index 84b044c0a9f..96b56b483c1 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h
@@ -24,7 +24,6 @@
#include <stdint.h>
#include "build/build_config.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
#include "third_party/blink/renderer/platform/wtf/cpu.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
@@ -117,7 +116,9 @@ inline void CopyLCharsFromUCharSource(LChar* destination,
const uintptr_t kMemoryAccessMask = kMemoryAccessSize - 1;
size_t i = 0;
- for (; i < length && !IsAlignedTo<kMemoryAccessMask>(&source[i]); ++i) {
+ for (; i < length &&
+ reinterpret_cast<uintptr_t>(&source[i]) & kMemoryAccessMask;
+ ++i) {
DCHECK(!(source[i] & 0xff00));
destination[i] = static_cast<LChar>(source[i]);
}
@@ -155,7 +156,7 @@ inline void CopyLCharsFromUCharSource(LChar* destination,
if (length >= (2 * kMemoryAccessSize) - 1) {
// Prefix: align dst on 64 bits.
const uintptr_t kMemoryAccessMask = kMemoryAccessSize - 1;
- while (!IsAlignedTo<kMemoryAccessMask>(destination))
+ while (reinterpret_cast<uintptr_t>(destination) & kMemoryAccessMask)
*destination++ = static_cast<LChar>(*source++);
// Vector interleaved unpack, we only store the lower 8 bits.
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc b/chromium/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc
index bcaa1c685dc..2d9af4b7184 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/atomic_string_table.cc
@@ -88,12 +88,12 @@ struct HashAndUTF8CharactersTranslator {
if (buffer.utf16_length != buffer.length) {
if (string->Is8Bit()) {
const LChar* characters8 = string->Characters8();
- return Unicode::EqualLatin1WithUTF8(
+ return unicode::EqualLatin1WithUTF8(
characters8, characters8 + string->length(), buffer.characters,
buffer.characters + buffer.length);
}
const UChar* characters16 = string->Characters16();
- return Unicode::EqualUTF16WithUTF8(
+ return unicode::EqualUTF16WithUTF8(
characters16, characters16 + string->length(), buffer.characters,
buffer.characters + buffer.length);
}
@@ -133,9 +133,9 @@ struct HashAndUTF8CharactersTranslator {
new_string = StringImpl::CreateUninitialized(buffer.utf16_length, target);
const char* source = buffer.characters;
- if (Unicode::ConvertUTF8ToUTF16(&source, source + buffer.length, &target,
+ if (unicode::ConvertUTF8ToUTF16(&source, source + buffer.length, &target,
target + buffer.utf16_length,
- &is_all_ascii) != Unicode::kConversionOK)
+ &is_all_ascii) != unicode::kConversionOK)
NOTREACHED();
} else {
new_string = StringImpl::Create(buffer.characters, buffer.length);
@@ -210,7 +210,7 @@ scoped_refptr<StringImpl> AtomicStringTable::AddUTF8(
const char* characters_end) {
HashAndUTF8Characters buffer;
buffer.characters = characters_start;
- buffer.hash = Unicode::CalculateStringHashAndLengthFromUTF8MaskingTop8Bits(
+ buffer.hash = unicode::CalculateStringHashAndLengthFromUTF8MaskingTop8Bits(
characters_start, characters_end, buffer.length, buffer.utf16_length);
if (!buffer.hash)
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/character_names.h b/chromium/third_party/blink/renderer/platform/wtf/text/character_names.h
index 93fab69b977..2668291933b 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/character_names.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/character_names.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace WTF {
-namespace Unicode {
+namespace unicode {
// Names here are taken from the Unicode standard.
@@ -138,101 +138,101 @@ const UChar kZeroWidthSpaceCharacter = 0x200B;
const UChar kZeroWidthNoBreakSpaceCharacter = 0xFEFF;
const UChar32 kMaxCodepoint = 0x10ffff;
-} // namespace Unicode
+} // namespace unicode
} // namespace WTF
-using WTF::Unicode::kAegeanWordSeparatorLineCharacter;
-using WTF::Unicode::kAegeanWordSeparatorDotCharacter;
-using WTF::Unicode::kActivateArabicFormShapingCharacter;
-using WTF::Unicode::kActivateSymmetricSwappingCharacter;
-using WTF::Unicode::kArabicLetterMarkCharacter;
-using WTF::Unicode::kBlackCircleCharacter;
-using WTF::Unicode::kBlackSquareCharacter;
-using WTF::Unicode::kBlackUpPointingTriangleCharacter;
-using WTF::Unicode::kBulletCharacter;
-using WTF::Unicode::kBullseyeCharacter;
-using WTF::Unicode::kCancelTag;
-using WTF::Unicode::kCarriageReturnCharacter;
-using WTF::Unicode::kCombiningEnclosingKeycapCharacter;
-using WTF::Unicode::kCombiningEnclosingCircleBackslashCharacter;
-using WTF::Unicode::kEthiopicPrefaceColonCharacter;
-using WTF::Unicode::kEthiopicWordspaceCharacter;
-using WTF::Unicode::kEyeCharacter;
-using WTF::Unicode::kFamilyCharacter;
-using WTF::Unicode::kFemaleSignCharacter;
-using WTF::Unicode::kFirstStrongIsolateCharacter;
-using WTF::Unicode::kFisheyeCharacter;
-using WTF::Unicode::kFormFeedCharacter;
-using WTF::Unicode::kFullstopCharacter;
-using WTF::Unicode::kHebrewPunctuationGereshCharacter;
-using WTF::Unicode::kHebrewPunctuationGershayimCharacter;
-using WTF::Unicode::kHiraganaLetterSmallACharacter;
-using WTF::Unicode::kHorizontalEllipsisCharacter;
-using WTF::Unicode::kHyphenCharacter;
-using WTF::Unicode::kHyphenMinusCharacter;
-using WTF::Unicode::kIdeographicCommaCharacter;
-using WTF::Unicode::kIdeographicFullStopCharacter;
+using WTF::unicode::kActivateArabicFormShapingCharacter;
+using WTF::unicode::kActivateSymmetricSwappingCharacter;
+using WTF::unicode::kAegeanWordSeparatorDotCharacter;
+using WTF::unicode::kAegeanWordSeparatorLineCharacter;
+using WTF::unicode::kArabicLetterMarkCharacter;
+using WTF::unicode::kBlackCircleCharacter;
+using WTF::unicode::kBlackSquareCharacter;
+using WTF::unicode::kBlackUpPointingTriangleCharacter;
+using WTF::unicode::kBulletCharacter;
+using WTF::unicode::kBullseyeCharacter;
+using WTF::unicode::kCancelTag;
+using WTF::unicode::kCarriageReturnCharacter;
+using WTF::unicode::kCombiningEnclosingCircleBackslashCharacter;
+using WTF::unicode::kCombiningEnclosingKeycapCharacter;
+using WTF::unicode::kEthiopicPrefaceColonCharacter;
+using WTF::unicode::kEthiopicWordspaceCharacter;
+using WTF::unicode::kEyeCharacter;
+using WTF::unicode::kFamilyCharacter;
+using WTF::unicode::kFemaleSignCharacter;
+using WTF::unicode::kFirstStrongIsolateCharacter;
+using WTF::unicode::kFisheyeCharacter;
+using WTF::unicode::kFormFeedCharacter;
+using WTF::unicode::kFullstopCharacter;
+using WTF::unicode::kHebrewPunctuationGereshCharacter;
+using WTF::unicode::kHebrewPunctuationGershayimCharacter;
+using WTF::unicode::kHiraganaLetterSmallACharacter;
+using WTF::unicode::kHorizontalEllipsisCharacter;
+using WTF::unicode::kHyphenCharacter;
+using WTF::unicode::kHyphenMinusCharacter;
+using WTF::unicode::kIdeographicCommaCharacter;
+using WTF::unicode::kIdeographicFullStopCharacter;
#if defined(USING_SYSTEM_ICU)
-using WTF::Unicode::ideographicSpaceCharacter;
+using WTF::unicode::ideographicSpaceCharacter;
#endif
-using WTF::Unicode::kInhibitArabicFormShapingCharacter;
-using WTF::Unicode::kInhibitSymmetricSwappingCharacter;
-using WTF::Unicode::kLatinCapitalLetterIWithDotAbove;
-using WTF::Unicode::kLatinSmallLetterDotlessI;
-using WTF::Unicode::kLeftDoubleQuotationMarkCharacter;
-using WTF::Unicode::kLeftSingleQuotationMarkCharacter;
-using WTF::Unicode::kLeftSpeechBubbleCharacter;
-using WTF::Unicode::kLeftToRightEmbedCharacter;
-using WTF::Unicode::kLeftToRightIsolateCharacter;
-using WTF::Unicode::kLeftToRightMarkCharacter;
-using WTF::Unicode::kLeftToRightOverrideCharacter;
-using WTF::Unicode::kLineSeparator;
-using WTF::Unicode::kLowLineCharacter;
-using WTF::Unicode::kMaleSignCharacter;
-using WTF::Unicode::kMinusSignCharacter;
-using WTF::Unicode::kNewlineCharacter;
-using WTF::Unicode::kNationalDigitShapesCharacter;
-using WTF::Unicode::kNominalDigitShapesCharacter;
-using WTF::Unicode::kNoBreakSpaceCharacter;
-using WTF::Unicode::kObjectReplacementCharacter;
-using WTF::Unicode::kParagraphSeparator;
-using WTF::Unicode::kPopDirectionalFormattingCharacter;
-using WTF::Unicode::kPopDirectionalIsolateCharacter;
-using WTF::Unicode::kRainbowCharacter;
-using WTF::Unicode::kReplacementCharacter;
-using WTF::Unicode::kReverseSolidusCharacter;
-using WTF::Unicode::kRightDoubleQuotationMarkCharacter;
-using WTF::Unicode::kRightSingleQuotationMarkCharacter;
-using WTF::Unicode::kRightToLeftEmbedCharacter;
-using WTF::Unicode::kRightToLeftIsolateCharacter;
-using WTF::Unicode::kRightToLeftMarkCharacter;
-using WTF::Unicode::kRightToLeftOverrideCharacter;
-using WTF::Unicode::kSesameDotCharacter;
-using WTF::Unicode::kSmallLetterSharpSCharacter;
-using WTF::Unicode::kSoftHyphenCharacter;
-using WTF::Unicode::kSolidusCharacter;
-using WTF::Unicode::kSpaceCharacter;
-using WTF::Unicode::kStaffOfAesculapiusCharacter;
-using WTF::Unicode::kTabulationCharacter;
-using WTF::Unicode::kTagDigitZero;
-using WTF::Unicode::kTagDigitNine;
-using WTF::Unicode::kTagLatinSmallLetterA;
-using WTF::Unicode::kTagLatinSmallLetterZ;
-using WTF::Unicode::kTibetanMarkIntersyllabicTshegCharacter;
-using WTF::Unicode::kTibetanMarkDelimiterTshegBstarCharacter;
-using WTF::Unicode::kUgariticWordDividerCharacter;
-using WTF::Unicode::kVariationSelector15Character;
-using WTF::Unicode::kVariationSelector16Character;
-using WTF::Unicode::kWavingWhiteFlagCharacter;
-using WTF::Unicode::kWhiteBulletCharacter;
-using WTF::Unicode::kWhiteCircleCharacter;
-using WTF::Unicode::kWhiteSesameDotCharacter;
-using WTF::Unicode::kWhiteUpPointingTriangleCharacter;
-using WTF::Unicode::kYenSignCharacter;
-using WTF::Unicode::kZeroWidthJoinerCharacter;
-using WTF::Unicode::kZeroWidthNonJoinerCharacter;
-using WTF::Unicode::kZeroWidthSpaceCharacter;
-using WTF::Unicode::kZeroWidthNoBreakSpaceCharacter;
-using WTF::Unicode::kMaxCodepoint;
+using WTF::unicode::kInhibitArabicFormShapingCharacter;
+using WTF::unicode::kInhibitSymmetricSwappingCharacter;
+using WTF::unicode::kLatinCapitalLetterIWithDotAbove;
+using WTF::unicode::kLatinSmallLetterDotlessI;
+using WTF::unicode::kLeftDoubleQuotationMarkCharacter;
+using WTF::unicode::kLeftSingleQuotationMarkCharacter;
+using WTF::unicode::kLeftSpeechBubbleCharacter;
+using WTF::unicode::kLeftToRightEmbedCharacter;
+using WTF::unicode::kLeftToRightIsolateCharacter;
+using WTF::unicode::kLeftToRightMarkCharacter;
+using WTF::unicode::kLeftToRightOverrideCharacter;
+using WTF::unicode::kLineSeparator;
+using WTF::unicode::kLowLineCharacter;
+using WTF::unicode::kMaleSignCharacter;
+using WTF::unicode::kMaxCodepoint;
+using WTF::unicode::kMinusSignCharacter;
+using WTF::unicode::kNationalDigitShapesCharacter;
+using WTF::unicode::kNewlineCharacter;
+using WTF::unicode::kNoBreakSpaceCharacter;
+using WTF::unicode::kNominalDigitShapesCharacter;
+using WTF::unicode::kObjectReplacementCharacter;
+using WTF::unicode::kParagraphSeparator;
+using WTF::unicode::kPopDirectionalFormattingCharacter;
+using WTF::unicode::kPopDirectionalIsolateCharacter;
+using WTF::unicode::kRainbowCharacter;
+using WTF::unicode::kReplacementCharacter;
+using WTF::unicode::kReverseSolidusCharacter;
+using WTF::unicode::kRightDoubleQuotationMarkCharacter;
+using WTF::unicode::kRightSingleQuotationMarkCharacter;
+using WTF::unicode::kRightToLeftEmbedCharacter;
+using WTF::unicode::kRightToLeftIsolateCharacter;
+using WTF::unicode::kRightToLeftMarkCharacter;
+using WTF::unicode::kRightToLeftOverrideCharacter;
+using WTF::unicode::kSesameDotCharacter;
+using WTF::unicode::kSmallLetterSharpSCharacter;
+using WTF::unicode::kSoftHyphenCharacter;
+using WTF::unicode::kSolidusCharacter;
+using WTF::unicode::kSpaceCharacter;
+using WTF::unicode::kStaffOfAesculapiusCharacter;
+using WTF::unicode::kTabulationCharacter;
+using WTF::unicode::kTagDigitNine;
+using WTF::unicode::kTagDigitZero;
+using WTF::unicode::kTagLatinSmallLetterA;
+using WTF::unicode::kTagLatinSmallLetterZ;
+using WTF::unicode::kTibetanMarkDelimiterTshegBstarCharacter;
+using WTF::unicode::kTibetanMarkIntersyllabicTshegCharacter;
+using WTF::unicode::kUgariticWordDividerCharacter;
+using WTF::unicode::kVariationSelector15Character;
+using WTF::unicode::kVariationSelector16Character;
+using WTF::unicode::kWavingWhiteFlagCharacter;
+using WTF::unicode::kWhiteBulletCharacter;
+using WTF::unicode::kWhiteCircleCharacter;
+using WTF::unicode::kWhiteSesameDotCharacter;
+using WTF::unicode::kWhiteUpPointingTriangleCharacter;
+using WTF::unicode::kYenSignCharacter;
+using WTF::unicode::kZeroWidthJoinerCharacter;
+using WTF::unicode::kZeroWidthNoBreakSpaceCharacter;
+using WTF::unicode::kZeroWidthNonJoinerCharacter;
+using WTF::unicode::kZeroWidthSpaceCharacter;
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_TEXT_CHARACTER_NAMES_H_
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.cc b/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.cc
index 5f6594a71c5..2de98044fa3 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.cc
@@ -38,7 +38,7 @@ String StringBuilder::ToString() {
if (!length_)
return g_empty_string;
if (string_.IsNull()) {
- if (is8_bit_)
+ if (is_8bit_)
string_ = String(Characters8(), length_);
else
string_ = String(Characters16(), length_);
@@ -51,7 +51,7 @@ AtomicString StringBuilder::ToAtomicString() {
if (!length_)
return g_empty_atom;
if (string_.IsNull()) {
- if (is8_bit_)
+ if (is_8bit_)
string_ = AtomicString(Characters8(), length_);
else
string_ = AtomicString(Characters16(), length_);
@@ -66,7 +66,7 @@ String StringBuilder::Substring(unsigned start, unsigned length) const {
if (!string_.IsNull())
return string_.Substring(start, length);
length = std::min(length, length_ - start);
- if (is8_bit_)
+ if (is_8bit_)
return String(Characters8() + start, length);
return String(Characters16() + start, length);
}
@@ -75,7 +75,7 @@ void StringBuilder::Swap(StringBuilder& builder) {
base::Optional<Buffer8> buffer8;
base::Optional<Buffer16> buffer16;
if (has_buffer_) {
- if (is8_bit_) {
+ if (is_8bit_) {
buffer8 = std::move(buffer8_);
buffer8_.~Buffer8();
} else {
@@ -85,7 +85,7 @@ void StringBuilder::Swap(StringBuilder& builder) {
}
if (builder.has_buffer_) {
- if (builder.is8_bit_) {
+ if (builder.is_8bit_) {
new (&buffer8_) Buffer8(std::move(builder.buffer8_));
builder.buffer8_.~Buffer8();
} else {
@@ -101,14 +101,14 @@ void StringBuilder::Swap(StringBuilder& builder) {
std::swap(string_, builder.string_);
std::swap(length_, builder.length_);
- std::swap(is8_bit_, builder.is8_bit_);
+ std::swap(is_8bit_, builder.is_8bit_);
std::swap(has_buffer_, builder.has_buffer_);
}
void StringBuilder::ClearBuffer() {
if (!has_buffer_)
return;
- if (is8_bit_)
+ if (is_8bit_)
buffer8_.~Buffer8();
else
buffer16_.~Buffer16();
@@ -119,19 +119,19 @@ void StringBuilder::Clear() {
ClearBuffer();
string_ = String();
length_ = 0;
- is8_bit_ = true;
+ is_8bit_ = true;
}
unsigned StringBuilder::Capacity() const {
if (!HasBuffer())
return 0;
- if (is8_bit_)
+ if (is_8bit_)
return buffer8_.capacity();
return buffer16_.capacity();
}
void StringBuilder::ReserveCapacity(unsigned new_capacity) {
- if (is8_bit_)
+ if (is_8bit_)
EnsureBuffer8(new_capacity);
else
EnsureBuffer16(new_capacity);
@@ -142,7 +142,7 @@ void StringBuilder::Resize(unsigned new_size) {
string_ = string_.Left(new_size);
length_ = new_size;
if (HasBuffer()) {
- if (is8_bit_)
+ if (is_8bit_)
buffer8_.resize(new_size);
else
buffer16_.resize(new_size);
@@ -151,7 +151,7 @@ void StringBuilder::Resize(unsigned new_size) {
void StringBuilder::CreateBuffer8(unsigned added_size) {
DCHECK(!HasBuffer());
- DCHECK(is8_bit_);
+ DCHECK(is_8bit_);
new (&buffer8_) Buffer8;
has_buffer_ = true;
// createBuffer is called right before appending addedSize more bytes. We
@@ -171,7 +171,7 @@ void StringBuilder::CreateBuffer8(unsigned added_size) {
}
void StringBuilder::CreateBuffer16(unsigned added_size) {
- DCHECK(is8_bit_ || !HasBuffer());
+ DCHECK(is_8bit_ || !HasBuffer());
Buffer8 buffer8;
unsigned length = length_;
if (has_buffer_) {
@@ -184,7 +184,7 @@ void StringBuilder::CreateBuffer16(unsigned added_size) {
buffer16_.ReserveInitialCapacity(
length_ +
std::max<unsigned>(added_size, InitialBufferSize() / sizeof(UChar)));
- is8_bit_ = false;
+ is_8bit_ = false;
length_ = 0;
if (!buffer8.IsEmpty()) {
Append(buffer8.data(), length);
@@ -216,7 +216,7 @@ void StringBuilder::Append(const LChar* characters, unsigned length) {
return;
DCHECK(characters);
- if (is8_bit_) {
+ if (is_8bit_) {
EnsureBuffer8(length);
buffer8_.Append(characters, length);
length_ += length;
@@ -267,7 +267,7 @@ void StringBuilder::erase(unsigned index) {
if (index >= length_)
return;
- if (is8_bit_) {
+ if (is_8bit_) {
EnsureBuffer8(0);
buffer8_.EraseAt(index);
} else {
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.h b/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.h
index c1795ff65a0..4898f0294e2 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_builder.h
@@ -54,7 +54,7 @@ class WTF_EXPORT StringBuilder {
if (!length_ && !HasBuffer() && !other.string_.IsNull()) {
string_ = other.string_;
length_ = other.string_.length();
- is8_bit_ = other.string_.Is8Bit();
+ is_8bit_ = other.string_.Is8Bit();
return;
}
@@ -94,7 +94,7 @@ class WTF_EXPORT StringBuilder {
if (!length_ && !HasBuffer() && impl) {
string_ = impl;
length_ = impl->length();
- is8_bit_ = impl->Is8Bit();
+ is_8bit_ = impl->Is8Bit();
return;
}
@@ -105,7 +105,7 @@ class WTF_EXPORT StringBuilder {
}
void Append(UChar c) {
- if (is8_bit_ && c <= 0xFF) {
+ if (is_8bit_ && c <= 0xFF) {
Append(static_cast<LChar>(c));
return;
}
@@ -115,7 +115,7 @@ class WTF_EXPORT StringBuilder {
}
void Append(LChar c) {
- if (!is8_bit_) {
+ if (!is_8bit_) {
Append(static_cast<UChar>(c));
return;
}
@@ -160,13 +160,13 @@ class WTF_EXPORT StringBuilder {
UChar operator[](unsigned i) const {
SECURITY_DCHECK(i < length_);
- if (is8_bit_)
+ if (is_8bit_)
return Characters8()[i];
return Characters16()[i];
}
const LChar* Characters8() const {
- DCHECK(is8_bit_);
+ DCHECK(is_8bit_);
if (!length())
return nullptr;
if (!string_.IsNull())
@@ -176,7 +176,7 @@ class WTF_EXPORT StringBuilder {
}
const UChar* Characters16() const {
- DCHECK(!is8_bit_);
+ DCHECK(!is_8bit_);
if (!length())
return nullptr;
if (!string_.IsNull())
@@ -185,7 +185,7 @@ class WTF_EXPORT StringBuilder {
return buffer16_.data();
}
- bool Is8Bit() const { return is8_bit_; }
+ bool Is8Bit() const { return is_8bit_; }
void Clear();
void Swap(StringBuilder&);
@@ -198,13 +198,13 @@ class WTF_EXPORT StringBuilder {
typedef Vector<UChar, kInlineBufferSize / sizeof(UChar)> Buffer16;
void EnsureBuffer8(unsigned added_size) {
- DCHECK(is8_bit_);
+ DCHECK(is_8bit_);
if (!HasBuffer())
CreateBuffer8(added_size);
}
void EnsureBuffer16(unsigned added_size) {
- if (is8_bit_ || !HasBuffer())
+ if (is_8bit_ || !HasBuffer())
CreateBuffer16(added_size);
}
@@ -220,7 +220,7 @@ class WTF_EXPORT StringBuilder {
Buffer16 buffer16_;
};
unsigned length_ = 0;
- bool is8_bit_ = true;
+ bool is_8bit_ = true;
bool has_buffer_ = false;
DISALLOW_COPY_AND_ASSIGN(StringBuilder);
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_hash.h b/chromium/third_party/blink/renderer/platform/wtf/text/string_hash.h
index 615a3c99c43..987d0c9ab31 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_hash.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_hash.h
@@ -138,11 +138,11 @@ class CaseFoldingHash {
static inline UChar FoldCase(T ch) {
if (std::is_same<T, LChar>::value)
return StringImpl::kLatin1CaseFoldTable[ch];
- // It's possible for WTF::Unicode::foldCase() to return a 32-bit value
+ // It's possible for WTF::unicode::foldCase() to return a 32-bit value
// that's not representable as a UChar. However, since this is rare and
// deterministic, and the result of this is merely used for hashing, go
// ahead and clamp the value.
- return static_cast<UChar>(WTF::Unicode::FoldCase(ch));
+ return static_cast<UChar>(WTF::unicode::FoldCase(ch));
}
};
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.cc b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.cc
index 871f2647dbc..b72f6c5faaa 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.cc
@@ -76,7 +76,7 @@ void StringImpl::DestroyIfNotStatic() const {
delete this;
}
-void StringImpl::UpdateContainsOnlyASCII() const {
+void StringImpl::UpdateContainsOnlyASCIIOrEmpty() const {
contains_only_ascii_ = Is8Bit()
? CharactersAreAllASCII(Characters8(), length())
: CharactersAreAllASCII(Characters16(), length());
@@ -275,7 +275,7 @@ scoped_refptr<StringImpl> StringImpl::Create(const LChar* string) {
return Create(string, SafeCast<wtf_size_t>(length));
}
-bool StringImpl::ContainsOnlyWhitespace() {
+bool StringImpl::ContainsOnlyWhitespaceOrEmpty() {
// FIXME: The definition of whitespace here includes a number of characters
// that are not whitespace from the point of view of LayoutText; I wonder if
// that's a problem in practice.
@@ -418,7 +418,7 @@ scoped_refptr<StringImpl> StringImpl::LowerUnicode() {
for (wtf_size_t i = first_index_to_be_lowered; i < length_; ++i) {
LChar ch = Characters8()[i];
- data8[i] = UNLIKELY(ch & ~0x7F) ? static_cast<LChar>(Unicode::ToLower(ch))
+ data8[i] = UNLIKELY(ch & ~0x7F) ? static_cast<LChar>(unicode::ToLower(ch))
: ToASCIILower(ch);
}
@@ -458,12 +458,12 @@ scoped_refptr<StringImpl> StringImpl::LowerUnicode() {
bool error;
int32_t real_length =
- Unicode::ToLower(data16, length, Characters16(), length_, &error);
+ unicode::ToLower(data16, length, Characters16(), length_, &error);
if (!error && real_length == length)
return new_impl;
new_impl = CreateUninitialized(real_length, data16);
- Unicode::ToLower(data16, real_length, Characters16(), length_, &error);
+ unicode::ToLower(data16, real_length, Characters16(), length_, &error);
if (error)
return this;
return new_impl;
@@ -503,7 +503,7 @@ scoped_refptr<StringImpl> StringImpl::UpperUnicode() {
LChar c = Characters8()[i];
if (UNLIKELY(c == kSmallLetterSharpSCharacter))
++number_sharp_s_characters;
- UChar upper = static_cast<UChar>(Unicode::ToUpper(c));
+ UChar upper = static_cast<UChar>(unicode::ToUpper(c));
if (UNLIKELY(upper > 0xff)) {
// Since this upper-cased character does not fit in an 8-bit string, we
// need to take the 16-bit path.
@@ -527,7 +527,7 @@ scoped_refptr<StringImpl> StringImpl::UpperUnicode() {
*dest++ = 'S';
*dest++ = 'S';
} else {
- *dest++ = static_cast<LChar>(Unicode::ToUpper(c));
+ *dest++ = static_cast<LChar>(unicode::ToUpper(c));
}
}
@@ -554,11 +554,11 @@ upconvert:
// Do a slower implementation for cases that include non-ASCII characters.
bool error;
int32_t real_length =
- Unicode::ToUpper(data16, length, source16, length_, &error);
+ unicode::ToUpper(data16, length, source16, length_, &error);
if (!error && real_length == length)
return new_impl;
new_impl = CreateUninitialized(real_length, data16);
- Unicode::ToUpper(data16, real_length, source16, length_, &error);
+ unicode::ToUpper(data16, real_length, source16, length_, &error);
if (error)
return this;
return new_impl;
@@ -720,7 +720,7 @@ scoped_refptr<StringImpl> StringImpl::FoldCase() {
// Do a slower implementation for cases that include non-ASCII Latin-1
// characters.
for (int32_t i = 0; i < length; ++i)
- data[i] = static_cast<LChar>(Unicode::ToLower(Characters8()[i]));
+ data[i] = static_cast<LChar>(unicode::ToLower(Characters8()[i]));
return new_impl;
}
@@ -740,11 +740,11 @@ scoped_refptr<StringImpl> StringImpl::FoldCase() {
// Do a slower implementation for cases that include non-ASCII characters.
bool error;
int32_t real_length =
- Unicode::FoldCase(data, length, Characters16(), length_, &error);
+ unicode::FoldCase(data, length, Characters16(), length_, &error);
if (!error && real_length == length)
return new_impl;
new_impl = CreateUninitialized(real_length, data);
- Unicode::FoldCase(data, real_length, Characters16(), length_, &error);
+ unicode::FoldCase(data, real_length, Characters16(), length_, &error);
if (error)
return this;
return new_impl;
@@ -1048,14 +1048,14 @@ bool DeprecatedEqualIgnoringCase(const UChar* a,
DCHECK_GE(length, 0u);
if (a == b)
return true;
- return !Unicode::Umemcasecmp(a, b, length);
+ return !unicode::Umemcasecmp(a, b, length);
}
bool DeprecatedEqualIgnoringCase(const UChar* a,
const LChar* b,
wtf_size_t length) {
while (length--) {
- if (Unicode::FoldCase(*a++) != StringImpl::kLatin1CaseFoldTable[*b++])
+ if (unicode::FoldCase(*a++) != StringImpl::kLatin1CaseFoldTable[*b++])
return false;
}
return true;
@@ -1757,15 +1757,15 @@ scoped_refptr<StringImpl> StringImpl::Replace(const StringView& pattern,
wtf_size_t src_segment_length;
src_segment_start = 0;
wtf_size_t dst_offset = 0;
- bool src_is8_bit = Is8Bit();
- bool replacement_is8_bit = replacement.Is8Bit();
+ bool src_is_8bit = Is8Bit();
+ bool replacement_is_8bit = replacement.Is8Bit();
// There are 4 cases:
// 1. This and replacement are both 8 bit.
// 2. This and replacement are both 16 bit.
// 3. This is 8 bit and replacement is 16 bit.
// 4. This is 16 bit and replacement is 8 bit.
- if (src_is8_bit && replacement_is8_bit) {
+ if (src_is_8bit && replacement_is_8bit) {
// Case 1
LChar* data;
scoped_refptr<StringImpl> new_impl = CreateUninitialized(new_size, data);
@@ -1793,7 +1793,7 @@ scoped_refptr<StringImpl> StringImpl::Replace(const StringView& pattern,
scoped_refptr<StringImpl> new_impl = CreateUninitialized(new_size, data);
while ((src_segment_end = Find(pattern, src_segment_start)) != kNotFound) {
src_segment_length = src_segment_end - src_segment_start;
- if (src_is8_bit) {
+ if (src_is_8bit) {
// Case 3.
for (wtf_size_t i = 0; i < src_segment_length; ++i)
data[i + dst_offset] = Characters8()[i + src_segment_start];
@@ -1803,7 +1803,7 @@ scoped_refptr<StringImpl> StringImpl::Replace(const StringView& pattern,
src_segment_length * sizeof(UChar));
}
dst_offset += src_segment_length;
- if (replacement_is8_bit) {
+ if (replacement_is_8bit) {
// Cases 2 & 3.
for (wtf_size_t i = 0; i < rep_str_length; ++i)
data[i + dst_offset] = replacement.Characters8()[i];
@@ -1817,7 +1817,7 @@ scoped_refptr<StringImpl> StringImpl::Replace(const StringView& pattern,
}
src_segment_length = length_ - src_segment_start;
- if (src_is8_bit) {
+ if (src_is_8bit) {
// Case 3.
for (wtf_size_t i = 0; i < src_segment_length; ++i)
data[i + dst_offset] = Characters8()[i + src_segment_start];
@@ -2000,7 +2000,7 @@ UChar32 ToUpper(UChar32 c, const AtomicString& locale_identifier) {
}
}
- return Unicode::ToUpper(c);
+ return unicode::ToUpper(c);
}
} // namespace WTF
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.h b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.h
index be183011e7f..3073b0856d2 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl.h
@@ -95,7 +95,7 @@ class WTF_EXPORT StringImpl {
contains_only_ascii_(true),
needs_ascii_check_(false),
is_atomic_(false),
- is8_bit_(true),
+ is_8bit_(true),
is_static_(true) {
// Ensure that the hash is computed so that AtomicStringHash can call
// existingHash() with impunity. The empty string is special because it
@@ -112,7 +112,7 @@ class WTF_EXPORT StringImpl {
contains_only_ascii_(true),
needs_ascii_check_(false),
is_atomic_(false),
- is8_bit_(false),
+ is_8bit_(false),
is_static_(true) {
GetHash();
}
@@ -126,7 +126,7 @@ class WTF_EXPORT StringImpl {
contains_only_ascii_(!length),
needs_ascii_check_(static_cast<bool>(length)),
is_atomic_(false),
- is8_bit_(true),
+ is_8bit_(true),
is_static_(false) {
DCHECK(length_);
}
@@ -138,7 +138,7 @@ class WTF_EXPORT StringImpl {
contains_only_ascii_(!length),
needs_ascii_check_(static_cast<bool>(length)),
is_atomic_(false),
- is8_bit_(false),
+ is_8bit_(false),
is_static_(false) {
DCHECK(length_);
}
@@ -151,7 +151,7 @@ class WTF_EXPORT StringImpl {
contains_only_ascii_(!length),
needs_ascii_check_(static_cast<bool>(length)),
is_atomic_(false),
- is8_bit_(true),
+ is_8bit_(true),
is_static_(true) {}
public:
@@ -198,7 +198,7 @@ class WTF_EXPORT StringImpl {
UChar*& data);
wtf_size_t length() const { return length_; }
- bool Is8Bit() const { return is8_bit_; }
+ bool Is8Bit() const { return is_8bit_; }
ALWAYS_INLINE const LChar* Characters8() const {
DCHECK(Is8Bit());
@@ -224,7 +224,7 @@ class WTF_EXPORT StringImpl {
bool IsStatic() const { return is_static_; }
- bool ContainsOnlyASCII() const;
+ bool ContainsOnlyASCIIOrEmpty() const;
bool IsSafeToSendToAnotherThread() const;
@@ -313,7 +313,7 @@ class WTF_EXPORT StringImpl {
}
UChar32 CharacterStartingAt(wtf_size_t);
- bool ContainsOnlyWhitespace();
+ bool ContainsOnlyWhitespaceOrEmpty();
int ToInt(NumberParsingOptions, bool* ok) const;
wtf_size_t ToUInt(NumberParsingOptions, bool* ok) const;
@@ -461,7 +461,7 @@ class WTF_EXPORT StringImpl {
NOINLINE wtf_size_t HashSlowCase() const;
void DestroyIfNotStatic() const;
- void UpdateContainsOnlyASCII() const;
+ void UpdateContainsOnlyASCIIOrEmpty() const;
#if DCHECK_IS_ON()
std::string AsciiForDebugging() const;
@@ -487,7 +487,7 @@ class WTF_EXPORT StringImpl {
mutable unsigned contains_only_ascii_ : 1;
mutable unsigned needs_ascii_check_ : 1;
unsigned is_atomic_ : 1;
- const unsigned is8_bit_ : 1;
+ const unsigned is_8bit_ : 1;
const unsigned is_static_ : 1;
DISALLOW_COPY_AND_ASSIGN(StringImpl);
@@ -521,9 +521,9 @@ inline bool Equal(const char* a, StringImpl* b) {
}
WTF_EXPORT bool EqualNonNull(const StringImpl* a, const StringImpl* b);
-ALWAYS_INLINE bool StringImpl::ContainsOnlyASCII() const {
+ALWAYS_INLINE bool StringImpl::ContainsOnlyASCIIOrEmpty() const {
if (needs_ascii_check_)
- UpdateContainsOnlyASCII();
+ UpdateContainsOnlyASCIIOrEmpty();
return contains_only_ascii_;
}
@@ -771,14 +771,14 @@ static inline int CodePointCompare(const StringImpl* string1,
if (!string2)
return string1->length() ? 1 : 0;
- bool string1_is8_bit = string1->Is8Bit();
- bool string2_is8_bit = string2->Is8Bit();
- if (string1_is8_bit) {
- if (string2_is8_bit)
+ bool string1_is_8bit = string1->Is8Bit();
+ bool string2_is_8bit = string2->Is8Bit();
+ if (string1_is_8bit) {
+ if (string2_is_8bit)
return CodePointCompare8(string1, string2);
return CodePointCompare8To16(string1, string2);
}
- if (string2_is8_bit)
+ if (string2_is_8bit)
return -CodePointCompare8To16(string2, string1);
return CodePointCompare16(string1, string2);
}
@@ -788,7 +788,7 @@ static inline bool IsSpaceOrNewline(UChar c) {
// This will include newlines, which aren't included in Unicode DirWS.
return c <= 0x7F
? WTF::IsASCIISpace(c)
- : WTF::Unicode::Direction(c) == WTF::Unicode::kWhiteSpaceNeutral;
+ : WTF::unicode::Direction(c) == WTF::unicode::kWhiteSpaceNeutral;
}
inline scoped_refptr<StringImpl> StringImpl::IsolatedCopy() const {
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_cf.cc b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_cf.cc
index cb1a4a46e49..ada812eb668 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_cf.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_cf.cc
@@ -32,7 +32,7 @@
namespace WTF {
-namespace StringWrapperCFAllocator {
+namespace string_wrapper_cf_allocator {
static StringImpl* g_current_string;
@@ -118,7 +118,7 @@ static CFAllocatorRef Allocator() {
return allocator;
}
-} // namespace StringWrapperCFAllocator
+} // namespace string_wrapper_cf_allocator
RetainPtr<CFStringRef> StringImpl::CreateCFString() {
// Since garbage collection isn't compatible with custom allocators, we
@@ -131,12 +131,12 @@ RetainPtr<CFStringRef> StringImpl::CreateCFString() {
return AdoptCF(CFStringCreateWithCharacters(
0, reinterpret_cast<const UniChar*>(Characters16()), length_));
}
- CFAllocatorRef allocator = StringWrapperCFAllocator::Allocator();
+ CFAllocatorRef allocator = string_wrapper_cf_allocator::Allocator();
// Put pointer to the StringImpl in a global so the allocator can store it
// with the CFString.
- DCHECK(!StringWrapperCFAllocator::g_current_string);
- StringWrapperCFAllocator::g_current_string = this;
+ DCHECK(!string_wrapper_cf_allocator::g_current_string);
+ string_wrapper_cf_allocator::g_current_string = this;
CFStringRef string;
if (Is8Bit())
@@ -149,13 +149,13 @@ RetainPtr<CFStringRef> StringImpl::CreateCFString() {
kCFAllocatorNull);
// CoreFoundation might not have to allocate anything, we clear currentString
// in case we did not execute allocate().
- StringWrapperCFAllocator::g_current_string = 0;
+ string_wrapper_cf_allocator::g_current_string = 0;
return AdoptCF(string);
}
// On StringImpl creation we could check if the allocator is the
-// StringWrapperCFAllocator. If it is, then we could find the original
+// string_wrapper_cf_allocator. If it is, then we could find the original
// StringImpl and just return that. But to do that we'd have to compute the
// offset from CFStringRef to the allocated block; the CFStringRef is *not* at
// the start of an allocated block. Testing shows 1000x more calls to
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_test.cc b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_test.cc
index 6f967bc148b..b8333d1608a 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_impl_test.cc
@@ -38,7 +38,7 @@ TEST(StringImplTest, Create8Bit) {
TEST(StringImplTest, Latin1CaseFoldTable) {
LChar symbol = 0xff;
while (symbol--) {
- EXPECT_EQ(Unicode::FoldCase(symbol),
+ EXPECT_EQ(unicode::FoldCase(symbol),
StringImpl::kLatin1CaseFoldTable[symbol]);
}
}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h b/chromium/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h
index 7bde4329f8f..8babc9155bb 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h
@@ -55,7 +55,7 @@ class StringUTF8Adaptor final {
// UTF-8 when processing 8 bit strings. If |relative| is entirely ASCII, we
// luck out and can avoid mallocing a new buffer to hold the UTF-8 data
// because UTF-8 and Latin-1 use the same code units for ASCII code points.
- if (string.Is8Bit() && string.ContainsOnlyASCII()) {
+ if (string.Is8Bit() && string.ContainsOnlyASCIIOrEmpty()) {
data_ = reinterpret_cast<const char*>(string.Characters8());
length_ = string.length();
} else {
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/text_encoding_registry.cc b/chromium/third_party/blink/renderer/platform/wtf/text/text_encoding_registry.cc
index b4649af0731..200b31f9c61 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/text_encoding_registry.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/text_encoding_registry.cc
@@ -26,9 +26,9 @@
#include "third_party/blink/renderer/platform/wtf/text/text_encoding_registry.h"
+#include <atomic>
#include <memory>
#include "third_party/blink/renderer/platform/wtf/ascii_ctype.h"
-#include "third_party/blink/renderer/platform/wtf/atomics.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -108,14 +108,14 @@ static TextEncodingNameMap* g_text_encoding_name_map;
static TextCodecMap* g_text_codec_map;
namespace {
-static unsigned g_did_extend_text_codec_maps = 0;
+static std::atomic_bool g_did_extend_text_codec_maps{false};
-ALWAYS_INLINE unsigned AtomicDidExtendTextCodecMaps() {
- return AcquireLoad(&g_did_extend_text_codec_maps);
+ALWAYS_INLINE bool AtomicDidExtendTextCodecMaps() {
+ return g_did_extend_text_codec_maps.load(std::memory_order_acquire);
}
ALWAYS_INLINE void AtomicSetDidExtendTextCodecMaps() {
- ReleaseStore(&g_did_extend_text_codec_maps, 1);
+ g_did_extend_text_codec_maps.store(true, std::memory_order_release);
}
} // namespace
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/unicode.h b/chromium/third_party/blink/renderer/platform/wtf/text/unicode.h
index 9202dc11d58..f0b5d7325c7 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/unicode.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/unicode.h
@@ -32,7 +32,7 @@ typedef unsigned char LChar;
static_assert(sizeof(UChar) == 2, "UChar should be two bytes");
namespace WTF {
-namespace Unicode {
+namespace unicode {
enum CharDirection {
kLeftToRight = U_LEFT_TO_RIGHT,
@@ -223,7 +223,7 @@ inline int Umemcasecmp(const UChar* a, const UChar* b, int len) {
return u_memcasecmp(a, b, len, U_FOLD_CASE_DEFAULT);
}
-} // namespace Unicode
+} // namespace unicode
} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_TEXT_UNICODE_H_
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/utf8.cc b/chromium/third_party/blink/renderer/platform/wtf/text/utf8.cc
index 8794311524c..570e7748e6c 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/utf8.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/utf8.cc
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
namespace WTF {
-namespace Unicode {
+namespace unicode {
inline int InlineUTF8SequenceLengthNonASCII(char b0) {
if ((b0 & 0xC0) != 0xC0)
@@ -472,5 +472,5 @@ bool EqualLatin1WithUTF8(const LChar* a,
return EqualWithUTF8Internal(a, a_end, b, b_end);
}
-} // namespace Unicode
+} // namespace unicode
} // namespace WTF
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/utf8.h b/chromium/third_party/blink/renderer/platform/wtf/text/utf8.h
index 1bbde324962..159aefb1fb6 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/utf8.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/utf8.h
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/platform/wtf/wtf_export.h"
namespace WTF {
-namespace Unicode {
+namespace unicode {
typedef enum {
kConversionOK, // conversion successful
@@ -87,7 +87,7 @@ WTF_EXPORT bool EqualLatin1WithUTF8(const LChar* a,
const char* b,
const char* b_end);
-} // namespace Unicode
+} // namespace unicode
} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_TEXT_UTF8_H_
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.cc b/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.cc
index 652afb2cb95..a243c0a8e04 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.cc
@@ -661,11 +661,11 @@ CString String::Utf8(UTF8ConversionMode mode) const {
if (Is8Bit()) {
const LChar* characters = this->Characters8();
- Unicode::ConversionResult result =
- Unicode::ConvertLatin1ToUTF8(&characters, characters + length, &buffer,
+ unicode::ConversionResult result =
+ unicode::ConvertLatin1ToUTF8(&characters, characters + length, &buffer,
buffer + buffer_vector.size());
// (length * 3) should be sufficient for any conversion
- DCHECK_NE(result, Unicode::kTargetExhausted);
+ DCHECK_NE(result, unicode::kTargetExhausted);
} else {
const UChar* characters = this->Characters16();
@@ -674,13 +674,13 @@ CString String::Utf8(UTF8ConversionMode mode) const {
char* buffer_end = buffer + buffer_vector.size();
while (characters < characters_end) {
// Use strict conversion to detect unpaired surrogates.
- Unicode::ConversionResult result = Unicode::ConvertUTF16ToUTF8(
+ unicode::ConversionResult result = unicode::ConvertUTF16ToUTF8(
&characters, characters_end, &buffer, buffer_end, true);
- DCHECK_NE(result, Unicode::kTargetExhausted);
+ DCHECK_NE(result, unicode::kTargetExhausted);
// Conversion fails when there is an unpaired surrogate. Put
// replacement character (U+FFFD) instead of the unpaired
// surrogate.
- if (result != Unicode::kConversionOK) {
+ if (result != unicode::kConversionOK) {
DCHECK_LE(0xD800, *characters);
DCHECK_LE(*characters, 0xDFFF);
// There should be room left, since one UChar hasn't been
@@ -692,20 +692,20 @@ CString String::Utf8(UTF8ConversionMode mode) const {
}
} else {
bool strict = mode == kStrictUTF8Conversion;
- Unicode::ConversionResult result =
- Unicode::ConvertUTF16ToUTF8(&characters, characters + length, &buffer,
+ unicode::ConversionResult result =
+ unicode::ConvertUTF16ToUTF8(&characters, characters + length, &buffer,
buffer + buffer_vector.size(), strict);
// (length * 3) should be sufficient for any conversion
- DCHECK_NE(result, Unicode::kTargetExhausted);
+ DCHECK_NE(result, unicode::kTargetExhausted);
// Only produced from strict conversion.
- if (result == Unicode::kSourceIllegal) {
+ if (result == unicode::kSourceIllegal) {
DCHECK(strict);
return CString();
}
// Check for an unconverted high surrogate.
- if (result == Unicode::kSourceExhausted) {
+ if (result == unicode::kSourceExhausted) {
if (strict)
return CString();
// This should be one unpaired high surrogate. Treat it the same
@@ -767,10 +767,10 @@ String String::FromUTF8(const LChar* string_start, size_t string_length) {
UChar* buffer_current = buffer_start;
const char* string_current = reinterpret_cast<const char*>(string_start);
- if (Unicode::ConvertUTF8ToUTF16(
+ if (unicode::ConvertUTF8ToUTF16(
&string_current, reinterpret_cast<const char*>(string_start + length),
&buffer_current,
- buffer_current + buffer.size()) != Unicode::kConversionOK)
+ buffer_current + buffer.size()) != unicode::kConversionOK)
return String();
unsigned utf16_length =
diff --git a/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.h b/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.h
index f1755fb5bb9..bb17132ae01 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/text/wtf_string.h
@@ -30,8 +30,6 @@
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/compiler.h"
-#include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h"
-#include "third_party/blink/renderer/platform/wtf/text/ascii_fast_path.h"
#include "third_party/blink/renderer/platform/wtf/text/string_impl.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include "third_party/blink/renderer/platform/wtf/wtf_export.h"
@@ -504,12 +502,12 @@ class WTF_EXPORT String {
length);
}
- bool ContainsOnlyASCII() const {
- return !impl_ || impl_->ContainsOnlyASCII();
+ bool ContainsOnlyASCIIOrEmpty() const {
+ return !impl_ || impl_->ContainsOnlyASCIIOrEmpty();
}
- bool ContainsOnlyLatin1() const;
- bool ContainsOnlyWhitespace() const {
- return !impl_ || impl_->ContainsOnlyWhitespace();
+ bool ContainsOnlyLatin1OrEmpty() const;
+ bool ContainsOnlyWhitespaceOrEmpty() const {
+ return !impl_ || impl_->ContainsOnlyWhitespaceOrEmpty();
}
size_t CharactersSizeInBytes() const {
@@ -587,7 +585,7 @@ inline const UChar* String::GetCharacters<UChar>() const {
return Characters16();
}
-inline bool String::ContainsOnlyLatin1() const {
+inline bool String::ContainsOnlyLatin1OrEmpty() const {
if (IsEmpty())
return true;
@@ -677,7 +675,6 @@ using WTF::kStrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD;
using WTF::String;
using WTF::g_empty_string;
using WTF::g_empty_string16_bit;
-using WTF::CharactersAreAllASCII;
using WTF::Equal;
using WTF::Find;
using WTF::IsSpaceOrNewline;
diff --git a/chromium/third_party/blink/renderer/platform/wtf/threading_primitives_test.cc b/chromium/third_party/blink/renderer/platform/wtf/threading_primitives_test.cc
index e9931aebbe5..c480d40c246 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/threading_primitives_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/threading_primitives_test.cc
@@ -28,23 +28,27 @@ class ThreadConditionTest : public testing::Test {
ThreadConditionTest() : condition_(mutex_) {}
void RunOtherThreadInfiniteWait() {
- base::internal::SetBlockingObserverForCurrentThread(&observer_);
MutexLocker lock(mutex_);
ready_.Signal();
+
+ base::internal::SetBlockingObserverForCurrentThread(&observer_);
+ EXPECT_CALL(observer_, BlockingStarted(base::BlockingType::MAY_BLOCK));
+ EXPECT_CALL(observer_, BlockingEnded());
condition_.Wait();
+ testing::Mock::VerifyAndClear(&observer_);
}
protected:
+ // Used to make sure that the other thread gets to wait before the main thread
+ // signals it. Otherwise it may wait forever.
base::WaitableEvent ready_;
+
testing::StrictMock<MockBlockingObserver> observer_;
Mutex mutex_;
ThreadCondition condition_;
};
TEST_F(ThreadConditionTest, WaitReportsBlockingCall) {
- EXPECT_CALL(observer_, BlockingStarted(base::BlockingType::MAY_BLOCK));
- EXPECT_CALL(observer_, BlockingEnded());
-
base::Thread other_thread("other thread");
other_thread.StartAndWaitForTesting();
other_thread.task_runner()->PostTask(
diff --git a/chromium/third_party/blink/renderer/platform/wtf/threading_win.cc b/chromium/third_party/blink/renderer/platform/wtf/threading_win.cc
index 4898e9ada73..0a8e15b7b63 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/threading_win.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/threading_win.cc
@@ -175,9 +175,8 @@ bool RecursiveMutex::TryLock() {
return true;
}
-ThreadCondition::ThreadCondition(Mutex& mutex) : mutex_(mutex.Impl()) {
- InitializeConditionVariable(&condition_);
-}
+ThreadCondition::ThreadCondition(Mutex& mutex)
+ : condition_(CONDITION_VARIABLE_INIT), mutex_(mutex.Impl()) {}
ThreadCondition::~ThreadCondition() {}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/type_traits.h b/chromium/third_party/blink/renderer/platform/wtf/type_traits.h
index f8003ca810e..e9073ebb305 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/type_traits.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/type_traits.h
@@ -25,6 +25,7 @@
#include <cstddef>
#include <type_traits>
#include <utility>
+#include "base/compiler_specific.h"
#include "base/template_util.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/wtf/compiler.h"
@@ -34,7 +35,7 @@ namespace WTF {
// Returns a string that contains the type name of |T| as a substring.
template <typename T>
inline const char* GetStringWithTypeName() {
- return WTF_PRETTY_FUNCTION;
+ return PRETTY_FUNCTION;
}
template <typename T>
@@ -47,14 +48,6 @@ enum WeakHandlingFlag {
kWeakHandling,
};
-template <typename T>
-struct IsTriviallyDestructible {
- // TODO(slangley): crbug.com/783060 - std::is_trivially_destructible behaves
- // differently on across platforms.
- static constexpr bool value =
- __has_trivial_destructor(T) && std::is_destructible<T>::value;
-};
-
template <typename T, typename U>
struct IsSubclass {
private:
diff --git a/chromium/third_party/blink/renderer/platform/wtf/type_traits_test.cc b/chromium/third_party/blink/renderer/platform/wtf/type_traits_test.cc
index ced43d3258e..2a33105f08b 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/type_traits_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/type_traits_test.cc
@@ -217,7 +217,7 @@ static_assert(
!std::is_trivially_default_constructible<DefaultConstructorDeleted>::value,
"DefaultConstructorDeleted must not be trivially default constructible.");
-static_assert(!IsTriviallyDestructible<DestructorDeleted>::value,
+static_assert(!std::is_trivially_destructible<DestructorDeleted>::value,
"DestructorDeleted must not be trivially destructible.");
#define EnsurePtrConvertibleArgDecl(From, To) \
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h
index 55d59c9f656..39f91ea147b 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h
@@ -45,7 +45,7 @@ class WTF_EXPORT ArrayBuffer : public RefCounted<ArrayBuffer> {
unsigned element_byte_size);
static inline scoped_refptr<ArrayBuffer> Create(ArrayBuffer*);
static inline scoped_refptr<ArrayBuffer> Create(const void* source,
- unsigned byte_length);
+ size_t byte_length);
static inline scoped_refptr<ArrayBuffer> Create(ArrayBufferContents&);
static inline scoped_refptr<ArrayBuffer> CreateOrNull(
@@ -106,20 +106,26 @@ class WTF_EXPORT ArrayBuffer : public RefCounted<ArrayBuffer> {
inline scoped_refptr<ArrayBuffer> SliceImpl(unsigned begin,
unsigned end) const;
inline unsigned ClampIndex(int index) const;
- static inline int ClampValue(int x, int left, int right);
+ static inline unsigned ClampValue(int x, unsigned left, unsigned right);
ArrayBufferContents contents_;
ArrayBufferView* first_view_;
bool is_neutered_;
};
-int ArrayBuffer::ClampValue(int x, int left, int right) {
+unsigned ArrayBuffer::ClampValue(int x, unsigned left, unsigned right) {
DCHECK_LE(left, right);
- if (x < left)
- x = left;
- if (right < x)
- x = right;
- return x;
+ unsigned result;
+ if (x < 0)
+ result = left;
+ else
+ result = static_cast<unsigned>(x);
+
+ if (result < left)
+ result = left;
+ if (right < result)
+ result = right;
+ return result;
}
scoped_refptr<ArrayBuffer> ArrayBuffer::Create(unsigned num_elements,
@@ -136,7 +142,7 @@ scoped_refptr<ArrayBuffer> ArrayBuffer::Create(ArrayBuffer* other) {
}
scoped_refptr<ArrayBuffer> ArrayBuffer::Create(const void* source,
- unsigned byte_length) {
+ size_t byte_length) {
ArrayBufferContents contents(byte_length, 1, ArrayBufferContents::kNotShared,
ArrayBufferContents::kDontInitialize);
if (UNLIKELY(!contents.Data()))
@@ -260,14 +266,14 @@ scoped_refptr<ArrayBuffer> ArrayBuffer::Slice(int begin) const {
scoped_refptr<ArrayBuffer> ArrayBuffer::SliceImpl(unsigned begin,
unsigned end) const {
- unsigned size = begin <= end ? end - begin : 0;
+ size_t size = static_cast<size_t>(begin <= end ? end - begin : 0);
return ArrayBuffer::Create(static_cast<const char*>(Data()) + begin, size);
}
unsigned ArrayBuffer::ClampIndex(int index) const {
unsigned current_length = ByteLength();
if (index < 0)
- index = current_length + index;
+ index = static_cast<int>(current_length + index);
return ClampValue(index, 0, current_length);
}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.cc b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.cc
index b35101e3fd3..4a2561a2bee 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.cc
@@ -43,7 +43,7 @@ ArrayBufferBuilder::ArrayBufferBuilder()
}
bool ArrayBufferBuilder::ExpandCapacity(unsigned size_to_increase) {
- unsigned current_buffer_size = buffer_->ByteLength();
+ size_t current_buffer_size = buffer_->ByteLength();
// If the size of the buffer exceeds max of unsigned, it can't be grown any
// more.
@@ -55,8 +55,10 @@ bool ArrayBufferBuilder::ExpandCapacity(unsigned size_to_increase) {
// Grow exponentially if possible.
unsigned exponential_growth_new_buffer_size =
std::numeric_limits<unsigned>::max();
- if (current_buffer_size <= std::numeric_limits<unsigned>::max() / 2)
- exponential_growth_new_buffer_size = current_buffer_size * 2;
+ if (current_buffer_size <= std::numeric_limits<unsigned>::max() / 2) {
+ exponential_growth_new_buffer_size =
+ static_cast<unsigned>(current_buffer_size * 2);
+ }
if (exponential_growth_new_buffer_size > new_buffer_size)
new_buffer_size = exponential_growth_new_buffer_size;
@@ -74,11 +76,11 @@ bool ArrayBufferBuilder::ExpandCapacity(unsigned size_to_increase) {
unsigned ArrayBufferBuilder::Append(const char* data, unsigned length) {
DCHECK_GT(length, 0u);
- unsigned current_buffer_size = buffer_->ByteLength();
+ size_t current_buffer_size = buffer_->ByteLength();
DCHECK_LE(bytes_used_, current_buffer_size);
- unsigned remaining_buffer_space = current_buffer_size - bytes_used_;
+ size_t remaining_buffer_space = current_buffer_size - bytes_used_;
unsigned bytes_to_save = length;
@@ -87,7 +89,7 @@ unsigned ArrayBufferBuilder::Append(const char* data, unsigned length) {
if (!ExpandCapacity(length))
return 0;
} else {
- bytes_to_save = remaining_buffer_space;
+ bytes_to_save = static_cast<unsigned>(remaining_buffer_space);
}
}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.h b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.h
index f521b13aa89..38e27fd2d30 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder.h
@@ -73,7 +73,7 @@ class WTF_EXPORT ArrayBufferBuilder final {
unsigned ByteLength() const { return bytes_used_; }
// Number of bytes allocated.
- unsigned Capacity() const { return buffer_->ByteLength(); }
+ size_t Capacity() const { return buffer_->ByteLength(); }
void ShrinkToFit();
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder_test.cc b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder_test.cc
index 3fca4bbf394..01a38a95983 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_builder_test.cc
@@ -53,7 +53,7 @@ TEST(ArrayBufferBuilderTest, Constructor) {
TEST(ArrayBufferBuilderTest, Append) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(2 * data_size);
@@ -72,11 +72,11 @@ TEST(ArrayBufferBuilderTest, Append) {
TEST(ArrayBufferBuilderTest, AppendRepeatedly) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(37); // Some number coprime with dataSize.
- for (size_t i = 1; i < 1000U; ++i) {
+ for (uint32_t i = 1; i < 1000U; ++i) {
EXPECT_EQ(data_size, builder.Append(kData, data_size));
EXPECT_EQ(data_size * i, builder.ByteLength());
EXPECT_GE(builder.Capacity(), data_size * i);
@@ -85,11 +85,11 @@ TEST(ArrayBufferBuilderTest, AppendRepeatedly) {
TEST(ArrayBufferBuilderTest, DefaultConstructorAndAppendRepeatedly) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder;
- for (size_t i = 1; i < 4000U; ++i) {
+ for (uint32_t i = 1; i < 4000U; ++i) {
EXPECT_EQ(data_size, builder.Append(kData, data_size));
EXPECT_EQ(data_size * i, builder.ByteLength());
EXPECT_GE(builder.Capacity(), data_size * i);
@@ -98,7 +98,7 @@ TEST(ArrayBufferBuilderTest, DefaultConstructorAndAppendRepeatedly) {
TEST(ArrayBufferBuilderTest, AppendFixedCapacity) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(15);
builder.SetVariableCapacity(false);
@@ -118,17 +118,17 @@ TEST(ArrayBufferBuilderTest, AppendFixedCapacity) {
TEST(ArrayBufferBuilderTest, ToArrayBuffer) {
const char kData1[] = "HelloWorld";
- size_t data1_size = sizeof(kData1) - 1;
+ uint32_t data1_size = sizeof(kData1) - 1;
const char kData2[] = "GoodbyeWorld";
- size_t data2_size = sizeof(kData2) - 1;
+ uint32_t data2_size = sizeof(kData2) - 1;
ArrayBufferBuilder builder(1024);
builder.Append(kData1, data1_size);
builder.Append(kData2, data2_size);
const char kExpected[] = "HelloWorldGoodbyeWorld";
- size_t expected_size = sizeof(kExpected) - 1;
+ uint32_t expected_size = sizeof(kExpected) - 1;
scoped_refptr<ArrayBuffer> result = builder.ToArrayBuffer();
ASSERT_EQ(data1_size + data2_size, result->ByteLength());
@@ -138,7 +138,7 @@ TEST(ArrayBufferBuilderTest, ToArrayBuffer) {
TEST(ArrayBufferBuilderTest, ToArrayBufferSameAddressIfExactCapacity) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(data_size);
builder.Append(kData, data_size);
@@ -150,21 +150,21 @@ TEST(ArrayBufferBuilderTest, ToArrayBufferSameAddressIfExactCapacity) {
TEST(ArrayBufferBuilderTest, ToString) {
const char kData1[] = "HelloWorld";
- size_t data1_size = sizeof(kData1) - 1;
+ uint32_t data1_size = sizeof(kData1) - 1;
const char kData2[] = "GoodbyeWorld";
- size_t data2_size = sizeof(kData2) - 1;
+ uint32_t data2_size = sizeof(kData2) - 1;
ArrayBufferBuilder builder(1024);
builder.Append(kData1, data1_size);
builder.Append(kData2, data2_size);
const char kExpected[] = "HelloWorldGoodbyeWorld";
- size_t expected_size = sizeof(kExpected) - 1;
+ uint32_t expected_size = sizeof(kExpected) - 1;
String result = builder.ToString();
EXPECT_EQ(expected_size, result.length());
- for (unsigned i = 0; i < result.length(); ++i)
+ for (uint32_t i = 0; i < result.length(); ++i)
EXPECT_EQ(kExpected[i], result[i]);
}
@@ -178,7 +178,7 @@ TEST(ArrayBufferBuilderTest, ShrinkToFitNoAppend) {
TEST(ArrayBufferBuilderTest, ShrinkToFit) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(32);
@@ -193,7 +193,7 @@ TEST(ArrayBufferBuilderTest, ShrinkToFit) {
TEST(ArrayBufferBuilderTest, ShrinkToFitFullyUsed) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(data_size);
const void* internal_address = builder.Data();
@@ -211,7 +211,7 @@ TEST(ArrayBufferBuilderTest, ShrinkToFitFullyUsed) {
TEST(ArrayBufferBuilderTest, ShrinkToFitAfterGrowth) {
const char kData[] = "HelloWorld";
- size_t data_size = sizeof(kData) - 1;
+ uint32_t data_size = sizeof(kData) - 1;
ArrayBufferBuilder builder(5);
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc
index 127d6d39d5b..5a8dbf109f4 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.cc
@@ -53,7 +53,7 @@ ArrayBufferContents::ArrayBufferContents()
: holder_(base::AdoptRef(new DataHolder())) {}
ArrayBufferContents::ArrayBufferContents(
- unsigned num_elements,
+ size_t num_elements,
unsigned element_byte_size,
SharingType is_shared,
ArrayBufferContents::InitializationPolicy policy)
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h
index 19ae6eb4a08..3cc1abe8e48 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_contents.h
@@ -103,7 +103,7 @@ class WTF_EXPORT ArrayBufferContents {
};
ArrayBufferContents();
- ArrayBufferContents(unsigned num_elements,
+ ArrayBufferContents(size_t num_elements,
unsigned element_byte_size,
SharingType is_shared,
InitializationPolicy);
@@ -160,7 +160,7 @@ class WTF_EXPORT ArrayBufferContents {
static void DefaultAdjustAmountOfExternalAllocatedMemoryFunction(
int64_t diff);
- class DataHolder : public ThreadSafeRefCounted<DataHolder> {
+ class WTF_EXPORT DataHolder : public ThreadSafeRefCounted<DataHolder> {
DISALLOW_COPY_AND_ASSIGN(DataHolder);
public:
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h
index 238290301f6..6301434e67d 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h
@@ -90,7 +90,7 @@ class WTF_EXPORT ArrayBufferView : public RefCounted<ArrayBufferView> {
if (byte_offset > buffer->ByteLength())
return false;
unsigned remaining_elements =
- (buffer->ByteLength() - byte_offset) / sizeof(T);
+ static_cast<unsigned>((buffer->ByteLength() - byte_offset) / sizeof(T));
if (num_elements > remaining_elements)
return false;
return true;
diff --git a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc
index 921586c6111..9c66673f16d 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_piece.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h"
#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer_view.h"
@@ -20,7 +21,7 @@ ArrayPiece::ArrayPiece(void* data, unsigned byte_length) {
ArrayPiece::ArrayPiece(ArrayBuffer* buffer) {
if (buffer) {
- InitWithData(buffer->Data(), buffer->ByteLength());
+ InitWithData(buffer->Data(), SafeCast<unsigned>(buffer->ByteLength()));
} else {
InitNull();
}
diff --git a/chromium/third_party/blink/renderer/platform/wtf/vector.h b/chromium/third_party/blink/renderer/platform/wtf/vector.h
index f5ee3abe0ad..1646a56b149 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/vector.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/vector.h
@@ -30,7 +30,6 @@
#include "base/macros.h"
#include "base/template_util.h"
#include "build/build_config.h"
-#include "third_party/blink/renderer/platform/wtf/alignment.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h"
#include "third_party/blink/renderer/platform/wtf/construct_traits.h"
#include "third_party/blink/renderer/platform/wtf/container_annotations.h"
@@ -271,12 +270,7 @@ struct VectorFiller<true, T, Allocator> {
STATIC_ONLY(VectorFiller);
static void UninitializedFill(T* dst, T* dst_end, const T& val) {
static_assert(sizeof(T) == sizeof(char), "size of type should be one");
-#if defined(COMPILER_GCC) && defined(_FORTIFY_SOURCE)
- if (!__builtin_constant_p(dst_end - dst) || (!(dst_end - dst)))
- memset(dst, val, dst_end - dst);
-#else
memset(dst, val, dst_end - dst);
-#endif
}
};
diff --git a/chromium/third_party/blink/renderer/platform/wtf/vector_test.cc b/chromium/third_party/blink/renderer/platform/wtf/vector_test.cc
index 5a7cfc34fd4..7c36e76f49b 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/vector_test.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/vector_test.cc
@@ -655,6 +655,13 @@ TEST(VectorTest, emplace_back) {
EXPECT_EQ(7, item.value2);
}
+TEST(VectorTest, UninitializedFill) {
+ Vector<char> v(3, 42);
+ EXPECT_EQ(42, v[0]);
+ EXPECT_EQ(42, v[1]);
+ EXPECT_EQ(42, v[2]);
+}
+
static_assert(VectorTraits<int>::kCanCopyWithMemcpy,
"int should be copied with memcopy.");
static_assert(VectorTraits<char>::kCanCopyWithMemcpy,
diff --git a/chromium/third_party/blink/renderer/platform/wtf/vector_traits.h b/chromium/third_party/blink/renderer/platform/wtf/vector_traits.h
index c813151348e..af6534fbb64 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/vector_traits.h
+++ b/chromium/third_party/blink/renderer/platform/wtf/vector_traits.h
@@ -32,7 +32,8 @@ namespace WTF {
template <typename T>
struct VectorTraitsBase {
- static const bool kNeedsDestruction = !IsTriviallyDestructible<T>::value;
+ static const bool kNeedsDestruction =
+ !std::is_trivially_destructible<T>::value;
static constexpr bool kCanInitializeWithMemset =
std::is_trivially_default_constructible<T>::value;
diff --git a/chromium/third_party/blink/renderer/platform/wtf/wtf.cc b/chromium/third_party/blink/renderer/platform/wtf/wtf.cc
index 10f76b16eb8..856f35398c4 100644
--- a/chromium/third_party/blink/renderer/platform/wtf/wtf.cc
+++ b/chromium/third_party/blink/renderer/platform/wtf/wtf.cc
@@ -72,8 +72,6 @@ void Initialize(void (*call_on_main_thread_function)(MainThreadFunction,
WTFThreadData::Initialize();
- InitializeDates();
-
// Force initialization of static DoubleToStringConverter converter variable
// inside EcmaScriptConverter function while we are in single thread mode.
double_conversion::DoubleToStringConverter::EcmaScriptConverter();